diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 2cc2da3ea..0260618fa 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -1,14 +1,9 @@ # cargo-mutants (docs/mutation-testing.md). Mutants are judged by the black-box suites that will -# outlive the kernel backend: the reference tests (tests/oracle, through the oracle_cases test) -# and the pull-request sample of the robustness goldens (every 8th seed, as ci.yml). The -# kernel's own unit tests are left out on purpose: a mutant only they catch is a behaviour the +# outlive the kernel backend: the reference tests (tests/oracle, through the oracle_cases test). +# The kernel's own unit tests are left out on purpose: a mutant only they catch is a behaviour the # backend-neutral suites would miss when the kernel is swapped. profile = "mutants" additional_cargo_test_args = [ - "--test", "oracle_cases", "--lib", "--", "--include-ignored", + "--test", "oracle_cases", "--", "--include-ignored", "oracle_suite", - "robustness_goldens::seed_00", "robustness_goldens::seed_08", "robustness_goldens::seed_16", - "robustness_goldens::seed_24", "robustness_goldens::seed_32", "robustness_goldens::seed_40", - "robustness_goldens::seed_48", "robustness_goldens::seed_56", "robustness_goldens::seed_64", - "robustness_goldens::seed_72", "robustness_goldens::seed_80", "robustness_goldens::seed_88", ] diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 000000000..a2f964aeb --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,20 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +reviews: + auto_review: + # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. + ignore_usernames: + - "dependabot[bot]" + path_instructions: + - path: "**" + instructions: | + Project rule: don't change anyone's existing defaults unless the change is purely additive and belongs in the application. + Flag any change to something a user already relies on: a default setting or preference value, what a command or tool does when used the usual way, the UI's default layout or behaviour, a keyboard or mouse shortcut, or the result an existing saved design rebuilds to. + Don't flag purely additive changes: a new command, a new setting whose default keeps today's behaviour, or a new option that appears only when someone chooses it. Don't flag bug fixes that only turn a crash or an error into the result the feature always promised. + When you flag one, start the comment with "Changes a default:", say what a user sees before and after, whether a setting keeps the old behaviour, and whether the PR description's `Changes a default:` line says so. + pre_merge_checks: + custom_checks: + - name: "Existing defaults unchanged" + mode: "warning" + instructions: | + Pass if the pull request changes no default a user already relies on (default setting or preference values, what a command or tool does when used the usual way, the UI's default layout or behaviour, shortcuts, or the result an existing saved design rebuilds to), or if its changes are purely additive. + Fail otherwise, naming each changed default and what a user sees before and after. Also fail if the description says `Changes a default: no` while the code changes one. diff --git a/.config/nextest.toml b/.config/nextest.toml index 2e00c234c..b8ac317b6 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -12,7 +12,6 @@ not ( (package(solidcraft-engine) & ( test(=tests::hostile_params_never_panic) | test(/^tests::robustness::/) - | test(/^tests::robustness_goldens::seed_/) | test(=pattern_suppress_tests::enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen) | test(=pattern_suppress_tests::enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs) | test(=cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall) @@ -44,13 +43,12 @@ threads-required = 12 priority = 100 # The slowest tests start first, so a shard does not end with one of them running alone on a -# core while the others sit idle (seed_81 alone takes about 20 minutes under CI load). Medians -# from the CI test timings (the junit artifacts), slowest first; a test over ~100 s belongs here. +# core while the others sit idle. Medians from the CI test timings (the junit artifacts), slowest +# first; a test over ~100 s belongs here. [[profile.ci.overrides]] filter = """ (package(solidcraft-engine) & ( - test(/^tests::robustness_goldens::seed_(81|45|20|24|95|02|57|40|18|48|32|46|85|61)$/) - | test(/^tests::robustness::/) + test(/^tests::robustness::/) | test(=tests::hostile_params_never_panic) | test(=cmd::clearance::tests::distances_are_exact_on_edges_and_curved_faces) | test(=cmd::clipboard::tests::a_pasted_coil_joins_the_pasted_body) @@ -92,14 +90,13 @@ threads-required = "num-cpus" priority = 100 [[profile.local-ci.overrides]] -filter = "(package(solidcraft-engine) & test(=tests::robustness_goldens::seed_81)) | (package(solidcraft-kernel) & test(=tspline::tests::hostile_tsplines_never_panic))" +filter = "package(solidcraft-kernel) & test(=tspline::tests::hostile_tsplines_never_panic)" priority = 99 [[profile.local-ci.overrides]] filter = """ (package(solidcraft-engine) & ( - test(/^tests::robustness_goldens::seed_(81|45|20|24|95|02|57|40|18|48|32|46|85|61)$/) - | test(/^tests::robustness::/) + test(/^tests::robustness::/) | test(=tests::hostile_params_never_panic) | test(=cmd::clearance::tests::distances_are_exact_on_edges_and_curved_faces) | test(=cmd::clipboard::tests::a_pasted_coil_joins_the_pasted_body) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index ba6bb8093..1c70e8343 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,6 +1,8 @@ + + ## Change -Describe the problem and resulting behavior. Link the issue when applicable. +Start with what this is, in plain words someone new to the project would understand: what it does and who it's for. Don't assume anyone knows the name of your tool, project or feature. Then describe the problem and resulting behavior. Link the issue when applicable. Changes a default: no @@ -14,6 +16,8 @@ What did you run, and what were the results? Include expected and measured value ## Screenshots of the behavior (when observable) +Put the picture or video here in the description. A file in the diff doesn't count: a maintainer has to be able to see what this is without opening the changed files. + For observable CAD, UI or model behavior, include actual descriptive screenshots or a short recording from a small reproduction. This includes kernel, geometry, assembly and backend effects that can be shown in the app. Coding agents should run the app and capture the evidence themselves, rather than asking a human for evidence they can produce. Show the actual failure/result, preferably before and after, with brief steps, expected/actual behavior and annotations where helpful. Flowcharts and Mermaid diagrams cannot substitute for evidence of visible behavior. Use diagrams for architectural reasoning when actual screenshots cannot illustrate the point. Changes with no useful observable behavior may omit screenshot/video evidence. Exclude private designs and sensitive details; attach media or link to an accessible recording rather than committing generated review artifacts. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ebebb0e67..26e12d113 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,8 @@ # `ci` job still runs and reports the commit's real result (see the `ci` job): the merge queue # 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. +# The release gate (release-gate.yml) calls this workflow (workflow_call) as a Run workflow with +# cross-compilation on. # Every Linux job runs on Blacksmith's Ubuntu 24.04 runners (blacksmith-vcpu-ubuntu-2404), sized # per job: 32 vCPU for the tests, 16 for Clippy, the GPU path tests, 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. # The Windows shader job runs on Blacksmith's Windows Server 2025 runners (blacksmith-8vcpu-windows-2025); @@ -50,10 +52,14 @@ on: # only (other labels are skipped, see the top of this file). pull_request: types: [opened, synchronize, reopened, ready_for_review, labeled] + # The kernel-smlib branch (ADR 0002) runs no CI for now (owner, 2026-10-21). Drop this + # line before the branch merges back into main. + branches-ignore: [kernel-smlib] # The merge queue: each queued group runs the full suite before it lands on main. merge_group: push: - branches: [main] + # develop: the SMLib kernel's trunk until it merges into main (its PRs land there). + branches: [main, develop] schedule: - cron: "17 6 * * *" workflow_dispatch: @@ -62,6 +68,14 @@ on: description: "Also check WebAssembly and RISC-V (before a release)" type: boolean default: false + # The release gate (release-gate.yml): the event stays the caller's (workflow_dispatch), so a + # call runs exactly what Run workflow runs. + workflow_call: + inputs: + cross_compile: + description: "Also check WebAssembly and RISC-V (before a release)" + type: boolean + default: false permissions: contents: read @@ -117,7 +131,6 @@ jobs: outputs: native: ${{ steps.paths.outputs.native }} kernel: ${{ steps.paths.outputs.kernel }} - goldens: ${{ steps.paths.outputs.goldens }} windows: ${{ steps.paths.outputs.windows }} # The GPU path tests run (see the rule where it is computed). The job's `if` and the `ci` job's check both read this, so they cannot disagree. gpu: ${{ steps.paths.outputs.gpu }} @@ -156,7 +169,6 @@ jobs: run: | native=false kernel=false - goldens=false windows=false gpu_paths=false deps=false @@ -238,12 +250,12 @@ jobs: if [ "${tested:-0}" -gt 0 ]; then echo "The merge queue already tested $PUSH_SHA: repository checks only." elif tested=$(curl -fsS -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" \ - "https://api.github.com/repos/$REPO/actions/workflows/ci.yml/runs?event=push&branch=main&status=success&per_page=1" \ + "https://api.github.com/repos/$REPO/actions/workflows/ci.yml/runs?event=push&branch=$GITHUB_REF_NAME&status=success&per_page=1" \ | grep -o '"head_sha": *"[0-9a-f]*"' | head -n 1 | grep -o '[0-9a-f]\{40\}') \ && [ -n "$tested" ] && git merge-base --is-ancestor "$tested" "$PUSH_SHA" \ && git diff --no-renames --name-only -z "$tested" "$PUSH_SHA" > "$RUNNER_TEMP/ci-paths" \ && select_packages "$RUNNER_TEMP/ci-paths" && [ "$full" != true ] && [ -z "$packages" ]; then - # Nothing a build reads changed since the last push to main whose run passed (the + # Nothing a build reads changed since the last push to this branch whose run passed (the # push before may never have run: a newer push cancels a waiting one). echo "$tested..$PUSH_SHA changes no code: repository checks only." else @@ -282,13 +294,6 @@ 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. - case "$path" in - crates/kernel/*|vendor/truck-*|tests/robustness/*) goldens=true ;; - esac done < "$RUNNER_TEMP/ci-paths" # Computed as for a merge group, then turned off below (the fast lane). windows_paths "$RUNNER_TEMP/ci-paths" "$BASE_SHA...$HEAD_SHA" @@ -300,10 +305,6 @@ jobs: # selected means no code changed. select_packages "$RUNNER_TEMP/ci-paths" if [ "$full" = true ] || [ -n "$packages" ]; then native=true; fi - # The goldens are solidcraft-engine tests: its tests must be in the archive. - if [ "$goldens" = true ] && [ "$full" != true ]; then - case " $packages " in *" solidcraft-engine "*) ;; *) packages="$packages solidcraft-engine" ;; esac - fi fi # The reference tests replay recipes through solidcraft-cli: needed when it, or anything # it depends on, is selected. @@ -318,13 +319,12 @@ jobs: doctests=$native if [ "$EVENT_NAME" = pull_request ]; then windows=false; oracle=false; doctests=false; fi # Until a maintainer adds approved-for-ci, a pull request gets a quick compile instead of - # Clippy, the tests, the doc tests and the goldens. + # Clippy, the tests and the doc tests. quick=false if [ "$EVENT_NAME" = pull_request ] && [ "$APPROVED" != true ]; then quick=$native native=false oracle=false - goldens=false fi # A push that only merges main into the change (Merge branch 'main', Update branch) when # the change itself already passed: nothing new to test here, and main tests the merged @@ -337,7 +337,6 @@ jobs: if [ -n "$carried" ]; then echo "Only a merge of main into a change that passed in $carried: repository checks only." native=false - goldens=false fi fi # The GPU path tests (their own job, about 56 runner-minutes) are for render changes only: @@ -363,7 +362,6 @@ jobs: echo "native=$native" echo "gpu=$gpu" echo "kernel=$kernel" - echo "goldens=$goldens" echo "windows=$windows" echo "oracle=$oracle" echo "doctests=$doctests" @@ -389,7 +387,7 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: repo-checks - save-if: ${{ github.ref == 'refs/heads/main' }} + save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' }} - name: Format run: cargo fmt --all -- --check - name: Asset attribution @@ -409,6 +407,10 @@ jobs: # New UI text must reach every complete catalog; report it here, before review (#8542). - name: Translations in the complete catalogs run: cargo xtask i18n --check + - name: Model decisions use exact geometry, not meshes + run: | + cargo xtask mesh-decisions + cargo test -p xtask mesh_decisions --locked - name: Agent router and skills cite real files run: | cargo xtask skills @@ -439,7 +441,7 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: quick-compile - save-if: ${{ github.ref == 'refs/heads/main' }} + save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' }} - name: Cargo check run: cargo check --workspace --all-targets --locked @@ -458,7 +460,7 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: native-clippy - save-if: ${{ github.ref == 'refs/heads/main' }} + save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' }} - name: Clippy env: FULL: ${{ needs.changes.outputs.full }} @@ -501,7 +503,7 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: native-tests - save-if: ${{ github.ref == 'refs/heads/main' }} + save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' }} - name: Set up compiler cache uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: @@ -572,7 +574,7 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: native-tests - save-if: ${{ github.ref == 'refs/heads/main' }} + save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' }} - name: Set up compiler cache uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: @@ -583,13 +585,8 @@ jobs: - name: Run tests env: EVENT_NAME: ${{ github.event_name }} - GOLDENS: ${{ needs.changes.outputs.goldens }} FULL: ${{ needs.changes.outputs.full }} PACKAGES: ${{ needs.changes.outputs.packages }} - # 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. @@ -603,29 +600,23 @@ jobs: # 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))' - 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)\$/))" 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 # The GPU path tracer's tests run in their own job (GPU path tests): one at a time, they # took about 36 of this job's 45 minutes. + # A failed test does not fail the step by itself: the tests known to fail today + # (tests/KNOWN_FAILING_TESTS) may fail, any other fails it, and so does a listed test + # that passes. nextest's exit code 100 is "tests failed"; any other is its own error + # (a build error, a bad filter) and fails the step at once. + status=0 cargo nextest run "${scope[@]}" --cargo-profile ci --locked --profile ci --no-tests=pass \ - --ignore-default-filter -E "($base) & not (package(=solidcraft-gpu) & test(/^path::/))" || status=1 - if [ "$status" != 0 ]; then - # A failed golden gets the hint to re-record it (junit.xml lists the failures). - if [ -f "$junit" ] && tr '\n' ' ' < "$junit" | grep -q ']*>[[:space:]]*- + cargo run -q --locked -p xtask -- kernel-cases --area fillets + --cli target/release/solidcraft-cli --out "$RUNNER_TEMP/fillet-rig" + --known-failing tests/kernel-cases/fillets/KNOWN_FAILING + - name: Keep the results + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fillet-rig-results + path: ${{ runner.temp }}/fillet-rig/results.json + if-no-files-found: ignore diff --git a/.github/workflows/flatpak-pages.yml b/.github/workflows/flatpak-pages.yml index 06e5e6a2e..4cc41f698 100644 --- a/.github/workflows/flatpak-pages.yml +++ b/.github/workflows/flatpak-pages.yml @@ -21,6 +21,8 @@ concurrency: jobs: publish: name: Request the combined docs, web, and Flatpak deployment + # A pre-release stays off the Flatpak feed: the feed's one branch is what `flatpak update` offers. + if: github.event_name == 'workflow_dispatch' || !github.event.release.prerelease runs-on: ubuntu-24.04 env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/kernel-paused.yml b/.github/workflows/kernel-paused.yml index cfa6d659b..be5de83cd 100644 --- a/.github/workflows/kernel-paused.yml +++ b/.github/workflows/kernel-paused.yml @@ -1,6 +1,7 @@ -# While a new geometry kernel is evaluated, new issues, pull requests and discussions about kernel -# work are labelled `kernel-paused` for a maintainer to answer (CONTRIBUTING.md, "Kernel work is -# paused"). The logic is in scripts/kernel-paused/ (tested in ci.yml). +# While a new geometry kernel is evaluated, new issues and discussions about kernel work, and new +# pull requests that change the kernel directories, are labelled `kernel-paused` for a maintainer to +# answer (CONTRIBUTING.md, "Kernel work is paused"). The logic is in scripts/kernel-paused/ (tested +# in ci.yml). name: Kernel paused on: diff --git a/.github/workflows/kernel-rig.yml b/.github/workflows/kernel-rig.yml new file mode 100644 index 000000000..a4a7d6387 --- /dev/null +++ b/.github/workflows/kernel-rig.yml @@ -0,0 +1,238 @@ +# The kernel rig and the complexity ladder as a regression gate. A plan job maps a pull request's +# changed files to the rig areas they can affect (scripts/ci/kernel_rig_plan.py): an area runs +# when a file its tests/kernel-cases//PATHS lists changes, or one of its cases; every area +# runs when the shared core in tests/kernel-cases/PATHS-ALL changes, and when the solidcore pin in +# the root Cargo.toml and Cargo.lock moves (the plan reads their diff); the ladder runs whenever any +# area does. One job then builds solidcraft-cli once (release), checks that every +# registry command has a case or an exemption (tests/kernel-cases/EXEMPT), and hands the CLI to a +# matrix of shards as an artifact, one per selected area plus the ladder, in parallel, so the +# wall time is the build plus the slowest shard. See tests/kernel-cases/README.md. +# +# - An area fails on a regression (a case that fails and its tests/kernel-cases//KNOWN_FAILING +# does not list) or on a listed case that passes (it is fixed: remove its line in the same pull +# request, so the list only shrinks). +# - The ladder fails on any case whose status or counts differ from +# tests/kernel-cases/ladder/golden.json; a right change is re-recorded (`--record "why"`). +# +# The trigger paths are whole folders that hold every area's PATHS (a self-test, +# scripts/ci/test_kernel_rig_plan.py, checks they do), so a pull request that touches none of +# them (the UI, docs, packaging) starts no runner at all, and a new area needs no edit here: the +# plan finds the areas from the folders. Pushes to main and develop on the same paths, merge groups +# (once the queue is on), the release gate (release-gate.yml, workflow_call) and a run by hand run +# every area; those pushes also commit the compiler cache (a Blacksmith sticky disk) that every +# other run mounts read-only. +name: Kernel rig + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - "crates/kernel/**" + - "crates/geom/**" + - "crates/smlib/**" + - "crates/step/**" + - "crates/io/src/**" + - "crates/doc/src/**" + - "crates/engine/src/**" + - "tests/kernel-cases/**" + # The solidcore pin (the plan runs every area only when its lines change). + - "Cargo.toml" + - "Cargo.lock" + # The rig itself: the grading, the runner, the selection and this workflow. + - "apps/solidcraft-cli/src/kernel_cases.rs" + - "xtask/src/kernel_cases.rs" + - "xtask/src/kernel_ladder.rs" + - "scripts/ci/kernel_rig_plan.py" + - "scripts/ci/test_kernel_rig_plan.py" + - ".github/workflows/kernel-rig.yml" + push: + branches: [main, develop] + # The same paths as pull_request. + paths: + - "crates/kernel/**" + - "crates/geom/**" + - "crates/smlib/**" + - "crates/step/**" + - "crates/io/src/**" + - "crates/doc/src/**" + - "crates/engine/src/**" + - "tests/kernel-cases/**" + # The solidcore pin (the plan runs every area only when its lines change). + - "Cargo.toml" + - "Cargo.lock" + # The rig itself: the grading, the runner, the selection and this workflow. + - "apps/solidcraft-cli/src/kernel_cases.rs" + - "xtask/src/kernel_cases.rs" + - "xtask/src/kernel_ladder.rs" + - "scripts/ci/kernel_rig_plan.py" + - "scripts/ci/test_kernel_rig_plan.py" + - ".github/workflows/kernel-rig.yml" + merge_group: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # A new push to a pull request replaces its old run. + group: kernel-rig-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + CARGO_TERM_COLOR: always + +jobs: + plan: + name: Select the rig areas + # Draft pull requests run no CI, as in ci.yml. + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 + outputs: + # The shard matrix (JSON list of areas and the ladder; [] when nothing is selected). + shards: ${{ steps.plan.outputs.shards }} + # Whether the build job, and with it the coverage check, runs. + build: ${{ steps.plan.outputs.build }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # A pull request's diff needs its base's history. + fetch-depth: ${{ github.event_name == 'pull_request' && '0' || '1' }} + - name: Selection self-test + run: python3 -I scripts/ci/test_kernel_rig_plan.py + - id: plan + name: Map the changed files to areas + env: + EVENT_NAME: ${{ github.event_name }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + # Pull requests run the areas their diff reaches; pushes, merge groups, the release + # gate and a run by hand run every area. + if [ "$EVENT_NAME" = pull_request ]; then + git diff --no-renames --name-only -z "$BASE_SHA...$HEAD_SHA" > "$RUNNER_TEMP/rig-paths" + git diff --no-renames "$BASE_SHA...$HEAD_SHA" -- Cargo.toml Cargo.lock > "$RUNNER_TEMP/rig-pin.diff" + python3 -I scripts/ci/kernel_rig_plan.py --paths "$RUNNER_TEMP/rig-paths" --pin-diff "$RUNNER_TEMP/rig-pin.diff" \ + --github-output "$GITHUB_OUTPUT" + else + python3 -I scripts/ci/kernel_rig_plan.py --all --github-output "$GITHUB_OUTPUT" + fi + + build: + name: Build the CLI + needs: plan + if: needs.plan.outputs.build == 'true' + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 60 + env: + CARGO_INCREMENTAL: "0" + RUSTC_WRAPPER: sccache + SCCACHE_DIR: /home/runner/.cache/sccache + SCCACHE_CACHE_SIZE: 10G + 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 + # Only pushes to main and develop commit the cache; pull requests, merge groups and forks + # mount a clone and never write back. + - name: Mount the compiler cache + uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 + continue-on-error: true + with: + key: ${{ github.repository }}-sccache-kernel-rig + path: /home/runner/.cache/sccache + commit: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop') && 'on-change' || 'false' }} + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + key: kernel-rig + save-if: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop') }} + - name: Set up compiler cache + uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 + with: + version: v0.16.0 + - name: Build the CLI (release) and the rig's runner + run: | + cargo build --release --locked -p solidcraft-cli + cargo build --locked -p xtask + # A tar keeps the executable bits, which an artifact drops. xtask finds the repository from + # the path it was built in (CARGO_MANIFEST_DIR), which is the same checkout path in every + # job of this workflow. + # Every registry command is used by a case or listed in tests/kernel-cases/EXEMPT. + - name: Every command has a case + run: target/debug/xtask kernel-cases --coverage --cli target/release/solidcraft-cli + # A coverage-only run (the registry or the cases changed, no area selected) runs no shard. + - name: Pack the binaries + if: needs.plan.outputs.shards != '[]' + run: tar -cf "$RUNNER_TEMP/kernel-rig-bin.tar" -C target release/solidcraft-cli debug/xtask + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: needs.plan.outputs.shards != '[]' + with: + name: kernel-rig-bin + path: ${{ runner.temp }}/kernel-rig-bin.tar + retention-days: 1 + - name: Compiler cache statistics + if: always() + run: sccache --show-stats + + shard: + name: Kernel rig (${{ matrix.shard }}) + needs: [plan, build] + if: needs.plan.outputs.shards != '[]' + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # The areas of tests/kernel-cases/ the plan selected, and the ladder. On the build box + # (aarch64, 4 cases at a time) the slowest areas took about 1 minute (booleans, 212 s of + # cases with one of 84 s; threads, 161 s) and the ladder, one case at a time, 92 s: no area + # needs splitting. + shard: ${{ fromJSON(needs.plan.outputs.shards) }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: kernel-rig-bin + path: ${{ runner.temp }} + - name: Unpack the binaries + run: mkdir -p target && tar -xf "$RUNNER_TEMP/kernel-rig-bin.tar" -C target + - name: Run the cases against the known-failing list (the ladder against its golden) + env: + SHARD: ${{ matrix.shard }} + run: | + if [ "$SHARD" = ladder ]; then + set -- --ladder --gate + else + set -- --area "$SHARD" --known-failing "tests/kernel-cases/$SHARD/KNOWN_FAILING" + fi + target/debug/xtask kernel-cases "$@" --cli target/release/solidcraft-cli --out "$RUNNER_TEMP/kernel-rig" + - name: Keep the results + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: kernel-rig-results-${{ matrix.shard }} + path: ${{ runner.temp }}/kernel-rig/**/results.json + if-no-files-found: ignore + + # One check for the whole gate, for branch protection and the merge queue. + kernel-rig: + name: kernel-rig + needs: [plan, build, shard] + if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) + runs-on: blacksmith-2vcpu-ubuntu-2404 + steps: + # A skipped build or shard counts as passed only when the plan selected none. + - name: Every selected job passed + env: + PLAN: ${{ needs.plan.result }} + WANT_BUILD: ${{ needs.plan.outputs.build }} + WANT_SHARDS: ${{ needs.plan.outputs.shards }} + BUILD: ${{ needs.build.result }} + SHARDS: ${{ needs.shard.result }} + run: | + echo "plan=$PLAN build=$BUILD shards=$SHARDS selected=$WANT_SHARDS" + test "$PLAN" = success + if [ "$WANT_BUILD" = true ]; then test "$BUILD" = success; else test "$BUILD" = skipped; fi + if [ "$WANT_SHARDS" != '[]' ]; then test "$SHARDS" = success; else test "$SHARDS" = skipped; fi diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 02c2c0200..cfac788fb 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,5 +1,6 @@ # The documentation site on GitHub Pages: the book (docs/book) at https://docs.solidcraft.io/ -# and the bundled web app at /app/. Needs Settings → Pages → Source = GitHub Actions; skipped while the +# and the web app at /app/ (the latest release), /app-rc/ (the newest release candidate) and +# /app-edge/ (this commit). Needs Settings → Pages → Source = GitHub Actions; skipped while the # repository is private. name: Pages @@ -66,7 +67,10 @@ jobs: mkdir -p site cp -r target/book/. site/ bash docs/book/seo.sh site # canonical links, robots.txt, sitemap.xml - cp -r dist/web site/app + - name: Add the web app channels (stable and release candidate from their releases, edge from this build) + env: + GH_TOKEN: ${{ github.token }} + run: bash packaging/web-channels.sh site dist/web - uses: actions/configure-pages@v5 id: pages - name: Install Flatpak repository tools diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2650b1ec5..c54957046 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -1,6 +1,6 @@ -# Two quick checks on every pull request (CONTRIBUTING.md, "Sending a change"): no second open PR -# for an issue a lower-numbered one already closes, and the "Changes a default:" line is filled in. -# Neither is a required status check. The logic is in scripts/pr-checks/pr-checks.js (tested in ci.yml). +# Three quick checks on every pull request (CONTRIBUTING.md, "Sending a change"): no second open PR +# for an issue a lower-numbered one already closes, the "Changes a default:" line is filled in, and +# a PR adding to the showcase shows a picture. None is a required status check. The logic is in scripts/pr-checks/pr-checks.js (tested in ci.yml). name: PR checks on: @@ -48,6 +48,21 @@ jobs: const r = await checks.checkDefaults({ github, context, core }); core.info(JSON.stringify(r)); + picture: + name: Picture check + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: scripts/pr-checks + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const checks = require('./scripts/pr-checks/pr-checks.js'); + const r = await checks.checkPicture({ github, context, core }); + core.info(JSON.stringify(r)); + # Labelling needs write access, which a fork PR's token never has, so it is its own job and best # effort: a fork PR just doesn't get the `changes-default` label from here. label: diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml new file mode 100644 index 000000000..537a1ab8c --- /dev/null +++ b/.github/workflows/release-gate.yml @@ -0,0 +1,74 @@ +# The release gate: everything, in full and in parallel, on one branch's head, before that branch +# replaces main as a release (develop, rebased onto main). Run it by hand: +# gh workflow run release-gate.yml --ref develop +# It calls the workflows that own each check instead of copying their jobs: +# - ci.yml as Run workflow with cross-compilation: every native suite in full (not scoped), the +# reference tests, the doc tests, the GPU path tests, the action matrix (all 16 shards) and its +# determinism check, the property tests, the repository checks (web-offline among them), +# WebAssembly and RISC-V, Windows D3D12 FXC and Windows app startup; +# - kernel-rig.yml: every rig area against its KNOWN_FAILING and the ladder against its golden; +# - release.yml as a dry run (draft false, packages_only): the Linux, Flatpak, Snap, FreeBSD, +# macOS, Windows and web packages with their smoke tests and package checks, unsigned (no +# secrets are passed, so no signing secret or SignPath quota is used) and without the release +# job (checksums, update signing, publishing). +# The gate passes only when all three pass. Before main is replaced, tag the old main +# (main-before-develop-) and push the tag. +name: Release gate + +on: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-gate-${{ github.ref }} + cancel-in-progress: false + +jobs: + ci: + name: CI + uses: ./.github/workflows/ci.yml + permissions: + contents: read + # Select checks reads this commit's other runs. + actions: read + with: + cross_compile: true + + kernel-rig: + name: Kernel rig + uses: ./.github/workflows/kernel-rig.yml + permissions: + contents: read + + packages: + name: Packages + uses: ./.github/workflows/release.yml + # No secrets: the signing steps skip without them. GitHub checks a called workflow's job + # permissions before the run, skipped jobs included, so the release job's contents: write must + # be granted here; packages_only skips that job, and no step that runs writes to the + # repository. actions: read is the Windows job's. + permissions: + contents: write + actions: read + with: + draft: false + packages_only: true + + release-gate: + name: release-gate + needs: [ci, kernel-rig, packages] + if: always() + runs-on: blacksmith-2vcpu-ubuntu-2404 + steps: + - name: Every part passed + env: + CI: ${{ needs.ci.result }} + KERNEL_RIG: ${{ needs.kernel-rig.result }} + PACKAGES: ${{ needs.packages.result }} + run: | + echo "ci=$CI kernel-rig=$KERNEL_RIG packages=$PACKAGES" + test "$CI" = success + test "$KERNEL_RIG" = success + test "$PACKAGES" = success diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 44c3d5bae..d1d192344 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,6 +21,8 @@ # releases/latest/download/ links in the README keep working across releases. # # A dry run: dispatch with draft=false (the default). Only the release branch may create drafts. +# The release gate (release-gate.yml) calls it as such a dry run, without secrets (unsigned) and +# without the release job (packages_only). # A dry run from any branch also test-signs the Windows files when SIGNPATH_API_TOKEN exists: # gh workflow run release.yml --ref -f draft=false [-f signpath_signing_policy=test-signing] name: Release @@ -41,6 +43,25 @@ on: description: "SignPath signing policy for the Windows files (empty: the repository variable, else test-signing)" type: string default: "" + # The release gate (release-gate.yml): a dry run (draft false) of every package and its checks. + # The event stays the caller's (workflow_dispatch), so a call runs as a dispatched dry run does. + # The gate passes no secrets, so nothing is signed (the signing steps skip without their + # secrets, as on a fork), and packages_only skips the release job (checksums, update signing, + # publishing). + workflow_call: + inputs: + packages_only: + description: "Build and check every package only: no release job" + type: boolean + default: false + draft: + description: "Create/update a draft (release branch only; off: build artifacts only)" + type: boolean + default: false + signpath_signing_policy: + description: "SignPath signing policy for the Windows files (empty: the repository variable, else test-signing)" + type: string + default: "" permissions: contents: read @@ -213,6 +234,8 @@ jobs: if: needs.version.outputs.build == 'true' # makepkg only repackages the tarball's prebuilt binaries, so both architectures build here. runs-on: ubuntu-24.04 + # A pre-release or nightly without an Arch package is still worth having; a stable release isn't. + continue-on-error: ${{ contains(needs.version.outputs.version, '-') }} strategy: fail-fast: false matrix: @@ -229,10 +252,29 @@ jobs: # makepkg in an archlinux:base-devel container. The package is named after the tarball's # .desktop file (io.tangencylabs.solidcraft) and written as # dist/release/solidcraft--linux-.pkg.tar.zst. + # An Arch version can't hold a hyphen, and the action reads the version from the tarball's name + # (a hyphenated one comes out as 0.0.0): 0.40.0-rc.1 goes in as 0.40.0rc.1, which pacman sorts + # before 0.40.0, and the package keeps the release's name. + - id: pkgver + name: Arch version + run: | + pkgver="${VERSION//-/}" + echo "pkgver=$pkgver" >>"$GITHUB_OUTPUT" + if [ "$pkgver" != "$VERSION" ]; then + cp "dist/linux/solidcraft-$VERSION-linux-$ARCH.tar.gz" "dist/linux/solidcraft-$pkgver-linux-$ARCH.tar.gz" + fi + env: + ARCH: ${{ matrix.arch }} - uses: storytold/craft-common-actions/actions/arch-package@fa5ef18780cf5e7d5d3b8de068de56cffc83cac5 # main with: - tarball: dist/linux/solidcraft-${{ env.VERSION }}-linux-${{ matrix.arch }}.tar.gz + tarball: dist/linux/solidcraft-${{ steps.pkgver.outputs.pkgver }}-linux-${{ matrix.arch }}.tar.gz arch: ${{ matrix.arch }} + - name: The package under the release's version + if: steps.pkgver.outputs.pkgver != env.VERSION + env: + ARCH: ${{ matrix.arch }} + PKGVER: ${{ steps.pkgver.outputs.pkgver }} + run: sudo mv "dist/release/solidcraft-$PKGVER-linux-$ARCH.pkg.tar.zst" "dist/release/solidcraft-$VERSION-linux-$ARCH.pkg.tar.zst" - name: Check the package env: PKG: dist/release/solidcraft-${{ env.VERSION }}-linux-${{ matrix.arch }}.pkg.tar.zst @@ -350,7 +392,7 @@ jobs: name: macOS build ${{ matrix.arch }} needs: version if: needs.version.outputs.build == 'true' - runs-on: macos-14 + runs-on: macos-15 strategy: fail-fast: false matrix: @@ -384,7 +426,7 @@ jobs: name: macOS universal needs: [version, macos-build] if: needs.version.outputs.build == 'true' - runs-on: macos-14 + runs-on: macos-15 env: SOLIDCRAFT_VERSION: ${{ needs.version.outputs.version }} SOLIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }} @@ -612,7 +654,8 @@ jobs: release: name: GitHub Release or dry-run artifacts needs: [version, linux, flatpak, arch, snap, freebsd, macos, windows, web] - if: needs.version.outputs.build == 'true' + # Not for the release gate (packages_only): it builds and checks the packages, nothing more. + if: needs.version.outputs.build == 'true' && !inputs.packages_only runs-on: ubuntu-latest permissions: contents: write diff --git a/AGENTS.md b/AGENTS.md index af4304973..8e27b26b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,8 @@ Work: ROADMAP.md, "Where help is wanted most" in CONTRIBUTING.md, issues labelle - No GPL/LGPL/AGPL code, not even reading it (OpenCASCADE, FreeCAD, SolveSpace, CadQuery, LibreCAD, QCAD): `cargo xtask licences --check`. - Every asset is original or openly licensed with a row in ATTRIBUTION.md; read `assets/AGENTS.md` before icon work: `cargo xtask assets`, `cargo xtask icons`. - Never crash: no unwrap/expect/panic/unsafe in non-test code (unsafe allowlist in crash-safety), errors are `Result`, input is hostile: clippy `-D warnings`, `hostile_params_never_panic`. +- Model decisions (what an operation does, which bodies it touches, which face or edge a point or name means, depths, nearness) use exact geometry; a mesh is for display, export, previews and mesh bodies (`xtask/mesh-decisions.txt` only shrinks): `cargo xtask mesh-decisions`. +- New kernel cases go to solidcore: `cargo xtask lists`. - Everything is a command and programmatic calls never open dialogs: `skills/solidcraft-commands/SKILL.md`. - Layering (geom, sketch/kernel/render, doc, io, engine, ui-egui, apps); only `crates/kernel` uses truck: `cargo xtask layers`. - One outer UI container, one camera path (`navigation::handle`), colours from theme tokens: `cargo xtask ui-containers`. @@ -22,6 +24,7 @@ Work: ROADMAP.md, "Where help is wanted most" in CONTRIBUTING.md, issues labelle - A changed default keeps the old behaviour behind a preference and fills the PR's `Changes a default:` line, and no second PR for an issue a lower-numbered one closes: `pr-checks.yml`. - A regression test goes in the area's existing test file, never a per-bug file (#3226). - Look at open PRs first, claim with a draft PR (lowest number wins), one topic per PR, never force-push `main`, no pushes just to catch up with `main`: `skills/solidcraft-contributing/SKILL.md`. +- A PR's title and first sentence make sense to someone who never saw your chat or the issue: `skills/solidcraft-contributing/SKILL.md`. - Show observable changes with real screenshots or a recording, captured yourself. - Run `cargo xtask ci` before every commit, without switching branches while it runs. `cargo xtask skills` keeps this file and `skills/` honest. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 5d1df4bfc..81b65bfab 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -84,6 +84,8 @@ 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 | +| assets/fonts/craft-ui-sc/CraftUI-SC.otf | Adobe / Google Inc. (Noto Sans SC); SolidCraft subset | https://github.com/notofonts/noto-cjk Sans/SubsetOTF/SC Regular, glyph-subset for assets/locales/zh.json and renamed Craft UI SC (OFL reserved-name); licence text in assets/fonts/craft-ui-sc/OFL.txt; web UI Simplified Chinese | SIL OFL 1.1 | +| assets/fonts/craft-ui-tc/CraftUI-TC.otf | Adobe / Google Inc. (Noto Sans TC); SolidCraft subset | https://github.com/notofonts/noto-cjk Sans/SubsetOTF/TC Regular, glyph-subset for assets/locales/zh-TW.json and renamed Craft UI TC (OFL reserved-name); licence text in assets/fonts/craft-ui-tc/OFL.txt; web UI Traditional Chinese | 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 | @@ -101,6 +103,22 @@ Editable drawing code, native projects and shipped exports are collected under ` | 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/kernel-cases/import/1721-closed-bspline-tube-face/input.step | step-conformance contributors | copy of tests/step-conformance/cylinder_nurbs.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#1721 | CC0-1.0 | +| tests/kernel-cases/import/2043-outer-bound-opposing-surface-sense/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#2043 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/258-cone-point-vertex/input.step | step-conformance contributors | copy of tests/step-conformance/cone_point_vertex.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#258 | CC0-1.0 | +| tests/kernel-cases/import/258-cone-to-point/input.step | step-conformance contributors | copy of tests/step-conformance/cone_point.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#258 | CC0-1.0 | +| tests/kernel-cases/import/258-tiny-pin/input.step | step-conformance contributors | copy of tests/step-conformance/tiny_pin.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#258 | CC0-1.0 | +| tests/kernel-cases/import/3098-bspline-edges-over-tiny-knot-span/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3098 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3208-extruded-ellipse-face-over-parameter-seam/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3208 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3352-vertex-off-its-edge-curve/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3352 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3730-void-oriented-shell-false/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3730 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3880-cylinder-seam-edge/input.step | step-conformance contributors | copy of tests/step-conformance/cylinder_seam.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#3880 | CC0-1.0 | +| tests/kernel-cases/import/3880-nurbs-hemisphere-dome/input.step | step-conformance contributors | copy of tests/step-conformance/dome_nurbs.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#3880 | CC0-1.0 | +| tests/kernel-cases/import/3963-closed-spline-edge-vertex-past-start/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3963 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/4005-cylinder-written-as-near-zero-cone/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#4005 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/4006-plane-written-as-cone-of-nearly-right-angle/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#4006 | MIT OR Apache-2.0 | +| tests/ssi-corpus/cases/*.json.gz, tests/ssi-corpus/LICENSE-MIT, tests/ssi-corpus/LICENSE-APACHE | ssi-corpus contributors (jyviko) | 119 surface/surface intersection cases with exact ground truth from https://github.com/jyviko/ssi-corpus (cases/data, b04c8a6), gzip-compressed, unchanged; SSI scorer fixtures (tests/ssi-corpus/README.md) | MIT OR Apache-2.0 | +| tests/ssi-corpus/cases/y23_*.json.gz | Yang, Jia and Yan (paper authors: published surfaces, figures and topology); ssi-corpus contributors (reconstructions and truth) | 25 cases built from Yang, Jia & Yan 2023, "Topology Guaranteed B-Spline Surface/Surface Intersection", ACM Transactions on Graphics 42(6), Article 211; each cites the paper in its `source` field | CC-BY 4.0 (paper); MIT OR Apache-2.0 (case files) | | tests/step-regressions/rod_doubled_edge.step | SolidCraft contributors | written by SolidCraft from the commands of #4598 (a bored rod moved 100 mm and exported); import regression fixture | MIT OR Apache-2.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 | @@ -125,6 +143,8 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/appearances/library.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/appearances/opaque_finishes.rs | SolidCraft contributors | original illustrative opaque finish values; no external dataset, textures or measured engineering data | 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/craft-ui-sc/OFL.txt | Adobe / Google Inc. (Noto CJK); SolidCraft header | Accompanying OFL for CraftUI-SC.otf | SIL OFL 1.1 | +| assets/fonts/craft-ui-tc/OFL.txt | Adobe / Google Inc. (Noto CJK); SolidCraft header | Accompanying OFL for CraftUI-TC.otf | SIL OFL 1.1 | | assets/fonts/ibm-plex-mono/OFL.txt | IBM Corp. | Unmodified accompanying font licence | SIL OFL 1.1 | | assets/fonts/ibm-plex-sans/OFL.txt | IBM Corp. | Unmodified accompanying font licence | SIL OFL 1.1 | | assets/fonts/liberation-sans/OFL.txt | Red Hat, Inc.; Liberation Fonts contributors | Unmodified accompanying font licence | SIL OFL 1.1 | @@ -185,11 +205,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/shaders/viewport.wgsl | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/styles/ui/palettes.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/styles/ui/themes/gruvbox-dark.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | -| assets/styles/ui/themes/gruvbox-dark-hard.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | -| assets/styles/ui/themes/gruvbox-dark-soft.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | | assets/styles/ui/themes/gruvbox-light.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | -| assets/styles/ui/themes/gruvbox-light-hard.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | -| assets/styles/ui/themes/gruvbox-light-soft.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | | assets/styles/ui/themes/solidcraft-95.json | SolidCraft contributors | original SolidCraft theme file | MIT OR Apache-2.0 | | assets/styles/ui/themes/platinum-9.json | SolidCraft contributors | original SolidCraft theme file | MIT OR Apache-2.0 | | assets/styles/ui/themes/cupertino.json | SolidCraft contributors | original SolidCraft theme file | MIT OR Apache-2.0 | @@ -229,6 +245,18 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/svg/flat/plus.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/pan.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/perspective.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_appearance.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_assistant.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_design.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_general.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_graphics.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_layout.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_mouse3d.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_navigation.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_plugins.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_shortcuts.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_sketch.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/prefs_tools.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/redo.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/save.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/settings.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | @@ -628,6 +656,137 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments. | docs/book/src/generated/equation-parabola.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/equation-parabola.json`; gitignored) | MIT OR Apache-2.0 | | docs/book/src/generated/equation-spiral.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/equation-spiral.json`; gitignored) | MIT OR Apache-2.0 | | docs/book/src/generated/equation-wave.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/equation-wave.json`; gitignored) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/model/print_face.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | +| assets/locales/fi.json | SolidCraft contributors | Original Finnish translation of SolidCraft's English catalog, AI-assisted (Claude Code) clean-room from the English and not yet reviewed line by line by a native speaker; no commercial CAD text used | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/model/plane_axis_point.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-2x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-2x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| `assets/locales/pending/sketch-offset-instances.json` | SolidCraft contributors | Original offset instance-count label and translations | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/settings_profile.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original analytic head and shoulder geometry for settings profiles | MIT OR Apache-2.0 | +| tests/kernel-cases/import/4561-convert-box-mesh-with-a-zero-area-triangle/box-degenerate.stl | SolidCraft contributors | synthetic ASCII STL written by hand: a box with one zero-area triangle, for the kernel regression case of tangency-labs/solidcraft#4561 | MIT OR Apache-2.0 | +| assets/locales/pending/theme-blur-ui.json | SolidCraft contributors | Original blur controls, notices and translations | MIT OR Apache-2.0 | +| crates/ui-egui/tests/fixtures/theme-blur.json | SolidCraft contributors | Original theme for blur option scenarios and manager review | MIT OR Apache-2.0 | +| assets/locales/ka.json | David Machakhelidze (devius) | Original Georgian translation of SolidCraft's English catalog, written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker; no commercial CAD text used | MIT OR Apache-2.0 | ## Code adapted from sibling projects @@ -667,6 +826,15 @@ in THIRD-PARTY-LICENSES.txt; no images or artwork from that project are copied. The glTF test files are built by the tests themselves (crates/io/src/gltf_in_tests.rs, crates/engine/src/tests/gltf_import.rs); no third-party models are committed. +## Geometry kernel crates + +| Crate | Used for | Licence | +|---|---|---| +| solidcore (https://github.com/tangency-labs/solidcore, pinned by rev in Cargo.toml) | the Rust port of NVIDIA's SMLib: the B-rep kernel behind crates/smlib | Apache-2.0 (its NOTICE credits NVIDIA's USD BRep) | + +Linked as a crate; no code from it is copied into SolidCraft. Its licence text and NOTICE go +into THIRD-PARTY-LICENSES.txt when `main` regenerates it. + ## FreeCAD and Rhino import library FreeCAD `.FCStd` and Rhino `.3dm` files are read with [cadmpeg](https://github.com/cadmpeg/cadmpeg) @@ -682,16 +850,13 @@ copied into SolidCraft. | SolidCraft file | Original contribution | Licence | |---|---|---| | crates/ui-egui/src/viewport.rs (`nearest_quarter_turn`, `axis_view_orbit`) | N3MI-DG's [PR #101](https://github.com/bherbruck/solidcraft/pull/101): [minimal TOP/BOTTOM turns](https://github.com/bherbruck/solidcraft/commit/c28e780f52490784ef5886f094b9d3f6d10c3e3f) and [drag-to-orbit](https://github.com/bherbruck/solidcraft/commit/f30b30be6ecc4e2e6544a851243137c01a354934), adapted to the axis gizmo | MIT OR Apache-2.0 | +| crates/smlib/src/core/offset.rs (`draft`: the tilted planes and `SmBrep::LocalOperation`, the tail of the capi's `draft_faces`) | ablasik's `draft` in `crates/smlib/src/ffi/rs_ops2.rs` on [ablasik/solidcraft `app/solidcore-backend-on-develop`](https://github.com/ablasik/solidcraft/blob/9c7e8e31565e1823f0591b58e2967351c32af13f/crates/smlib/src/ffi/rs_ops2.rs), adapted to `core::offset`'s errors and checks | MIT OR Apache-2.0 | ## Vendored third-party code | Directory | Source | Licence | Changes | |---|---|---|---| -| vendor/truck-meshalgo | truck-meshalgo 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | meshing: bounded parameter searches, collapsed-boundary projection, subdivision and provisional fixed-grid previews (vendor/README.md) | -| vendor/truck-stepio | truck-stepio 0.3.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | STEP writer: intersection-curve surfaces written at unique ids (vendor/README.md) | -| vendor/truck-shapeops | truck-shapeops 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | robust meshing and nearest-parameter fallback in booleans; degenerate intersection-curve rejection; face and edge history of booleans; trace macro; corner choice at vertices several intersection curves end on; reuse of an operand's meshes (vendor/README.md) | -| vendor/truck-geometry | truck-geometry 0.5.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | intersection curves divided from their neighbours' surface parameters; surface second derivatives (vendor/README.md) | -| vendor/matext4cgmath | matext4cgmath 0.1.0, https://github.com/ricosjp/matext4cgmath (RICOS Co. Ltd.) | Apache-2.0 | root refinement stops after 100 Newton steps (vendor/README.md) | +| vendor/accesskit_macos | accesskit_macos 0.26.3, https://github.com/AccessKit/accesskit (The AccessKit contributors) | MIT OR Apache-2.0 | the subclassing adapter and its tests from 0.27.2: dropping the adapter keeps AppKit's key-value observers (vendor/README.md) | ## Vendored renderer compatibility fix diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7d444429d..75ed5eab6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,12 +19,13 @@ Questions, ideas or want to say what you're working on? Join the [Discord](https ## Kernel work is paused -We're evaluating a new geometry kernel. Until that's decided, please don't open issues, pull -requests or discussions about kernel work: booleans, fillets, chamfers, shell, offsets, sweeps and -lofts, threads and holes, STEP/IGES import and export, tessellation, or anything else that changes -`crates/kernel/`. The pinned issue on the tracker explains it. New ones get the `kernel-paused` -label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes and data loss -are still taken as issues, and everything outside the kernel carries on as normal. +We're moving to a new geometry kernel. Until that's done, please don't open pull requests that +change `crates/kernel/`, `crates/geom/` or `vendor/truck*`, or issues and discussions about kernel +work: booleans, fillets, chamfers, shell, offsets, sweeps and lofts, threads and holes, STEP/IGES +import and export, or tessellation. The pinned issue on the tracker explains it. New ones get the +`kernel-paused` label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes +and data loss are still taken as issues. Pull requests outside those directories carry on as normal, +including the dialogs and tools for these features. ## Get it running (about 10 minutes on a fast machine) @@ -160,9 +161,23 @@ the most complete description of the house style. | UI scenarios | `crates/ui-egui/tests/scenarios/*.json` | part of `cargo test` | | Reference tests | `cargo xtask oracle` | `tests/oracle/` (see below) | -A geometry change that changes the robustness goldens re-records them in the same pull request: -`ROBUSTNESS_GOLDENS_BLESS="why it changed" cargo test --profile ci -p solidcraft-engine --lib robustness_goldens::` -(see [docs/robustness.md](docs/robustness.md)); CI runs every seed on pull requests that touch geometry. +The reference for what the kernel builds is the kernel-cases ladder (`tests/kernel-cases/ladder/`, +`cargo xtask kernel-cases --ladder`, [docs/kernel-ladder.md](docs/kernel-ladder.md)). + +**Kernel cases go to solidcore.** A case that checks a kernel operation (a boolean, a blend, a +shell, a sweep, an import's geometry) is a new entry in solidcore's corpus, +`crates/solidcore/tests/kernel_cases//` in +[tangency-labs/solidcore](https://github.com/tangency-labs/solidcore), with an answer in closed +form or exact. Draft it as a rig case here, export it with +`cargo xtask kernel-cases --area --export DIR`, add `DIR//.json` and its +`.bodies.json.gz` there, and delete the draft; or write the entry by hand as that folder's README +describes. `tests/kernel-cases/` takes no new cases: its `CASES` list only shrinks +(`cargo xtask lists`). App-level cases (what a command does, the UI, product rules) stay in +SolidCraft, as tests in their area's existing test file or UI scenarios. + +The naming corpus checks persistent names: every name a corpus design stores still finds a face or +an edge, and two builds name its faces and edges alike +(`cargo test --profile ci -p solidcraft-cli --test naming_corpus`). [docs/mutation-testing.md](docs/mutation-testing.md) shows how to find kernel behaviour these black-box suites miss. @@ -221,8 +236,7 @@ Pull requests skip a few heavy tests (one to twelve minutes each), which run in 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`), +- `solidcraft-engine`: `tests::hostile_params_never_panic`, everything in `tests::robustness`, `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 @@ -242,7 +256,8 @@ the surface itself). Expected values are either worked out in closed form (`tools/oracle-analytic/`) or computed by building the same recipe in FreeCAD, run as a separate program (`tools/freecad-oracle/`); each file says which. The generated [reference test report](docs/oracle.md) has the current case count and results. The reference-test -CI job runs `cargo xtask oracle` during full validation; pull-request runs skip it. A case that +CI job runs `cargo xtask oracle` during full validation, and on pull requests that reach +`solidcraft-cli`. A case that fails because of a known bug names its issue in `expected.json` (`"known_failure": "#123"`); never change an expected value to match SolidCraft's output. @@ -338,6 +353,15 @@ and a fresh CI run: PRs in groups by area, so PRs that touch the same code meet a conflict at most once. 4. Reference the issue (`Fixes #12`). In the PR, say what you tested and how. For geometry work, include the measured numbers (and the expected ones). +5. Write the PR title and first sentence for someone who hasn't seen your chat, the issue or the + code. Maintainers pick what to review from the title, and it becomes the commit on `main`. Say + which part of the app changes and what a user now sees or can do, and name things rather than + leaning on "there", "it" or "this". + - Unclear: `Send to Slicer: pick one print face per body there, and show print faces only while it is open` + - Clear: `3D printing: choose the face each body rests on in the Send to Slicer window, not the face menu` + + Use plain, literal English in PR text: one idea per sentence, active voice, and one word for one + thing. This helps everyone, including readers whose first language isn't English. Commenting `/claim` assigns you, adds the `in progress` label, and replies with its automatic cleanup deadline. It frees a claim with no linked PR after 72 hours, or a claim with a PR after 14 days @@ -346,6 +370,13 @@ without pushes. These automatic cleanup deadlines are separate from the daily pr `/unclaim` releases the bot claim early (only you or a maintainer can). Issues a maintainer has taken are never freed automatically. +**A PR has to explain itself.** Start the description with what it is, in plain words someone new +to the project would understand: what it does and who it's for. Don't assume anyone knows the name +of your tool, project or feature. If there's anything to look at, show it in the description: a +picture or video has to be visible there without opening the changed files. "The GIF is the change" +doesn't count. A PR that doesn't do this waits until it does. For a PR that adds to +`docs/showcase.md` or `docs/screenshots/`, the Picture check fails until the description shows one. + Help reviewers see what the words mean. For observable CAD, UI or model behavior, please include actual descriptive screenshots or a short recording in the issue or PR. This evidence is required for changes or bugs that can be demonstrated in the app, including kernel, diff --git a/Cargo.lock b/Cargo.lock index 98c2edccf..d23087a6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,8 +60,6 @@ dependencies = [ [[package]] name = "accesskit_macos" version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" dependencies = [ "accesskit", "accesskit_consumer 0.38.0", @@ -188,15 +186,6 @@ dependencies = [ "libc", ] -[[package]] -name = "approx" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f2a05fd1bd10b2527e20a2cd32d8873d115b8b39fe219ee25f42a8aca6ba278" -dependencies = [ - "num-traits", -] - [[package]] name = "arboard" version = "3.6.1" @@ -217,12 +206,6 @@ dependencies = [ "x11rb", ] -[[package]] -name = "array-macro" -version = "2.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "220a2c618ab466efe41d0eace94dfeff1c35e3aa47891bdb95e1c0fefffd3c99" - [[package]] name = "arrayref" version = "0.3.9" @@ -535,15 +518,6 @@ dependencies = [ "piper", ] -[[package]] -name = "branches" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f11502672c5570f77f6bdf573332483f8475bab6a7fda00f1fae8ddb5a6245c0" -dependencies = [ - "rustc_version", -] - [[package]] name = "bumpalo" version = "3.20.3" @@ -791,17 +765,6 @@ dependencies = [ "libc", ] -[[package]] -name = "cgmath" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a98d30140e3296250832bbaaff83b27dcd6fa3cc70fb6f1f3e5c9c0023b5317" -dependencies = [ - "approx", - "num-traits", - "serde", -] - [[package]] name = "chacha20" version = "0.10.2" @@ -824,19 +787,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "wasm-bindgen", - "windows-link", -] - [[package]] name = "cipher" version = "0.4.4" @@ -907,12 +857,6 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" -[[package]] -name = "convert_case" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" - [[package]] name = "core-foundation" version = "0.9.4" @@ -1090,19 +1034,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "derive_more" -version = "0.99.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" -dependencies = [ - "convert_case", - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.119", -] - [[package]] name = "digest" version = "0.10.7" @@ -1249,7 +1180,7 @@ dependencies = [ "bitflags 2.13.2", "emath", "epaint", - "itertools 0.15.0", + "itertools", "log", "nohash-hasher", "profiling", @@ -1667,10 +1598,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", - "js-sys", "libc", "wasi", - "wasm-bindgen", ] [[package]] @@ -1985,30 +1914,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -2168,15 +2073,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.15.0" @@ -2271,17 +2167,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "katexit" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccfb0b7ce7938f84a5ecbdca5d0a991e46bc9d6d078934ad5e92c5270fe547db" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "keyboard-types" version = "0.8.3" @@ -2432,15 +2317,6 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" -[[package]] -name = "matext4cgmath" -version = "0.1.0" -dependencies = [ - "cgmath", - "katexit", - "num-complex", -] - [[package]] name = "memchr" version = "2.8.3" @@ -3316,30 +3192,6 @@ dependencies = [ "toml_edit", ] -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn 1.0.109", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -3512,15 +3364,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "rclite" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e09665c494a9de2bd230e1aedc0c2fb20481a51f28f7db84d0c9bcfe2fe537b2" -dependencies = [ - "branches", -] - [[package]] name = "read-fonts" version = "0.41.0" @@ -4208,9 +4051,27 @@ dependencies = [ "serde", ] +[[package]] +name = "solidcore" +version = "1.0.1" +source = "git+https://github.com/tangency-labs/solidcore?rev=8ddce901671f1cebd9214a31d21895d725e886c8#8ddce901671f1cebd9214a31d21895d725e886c8" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "solidcore-record" +version = "0.1.0" +source = "git+https://github.com/tangency-labs/solidcore?rev=f5e8e9a29e0c9b7cf6c4040a5bc8878382b3c62f#f5e8e9a29e0c9b7cf6c4040a5bc8878382b3c62f" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "solidcraft" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "block2 0.6.2", "eframe", @@ -4241,28 +4102,32 @@ dependencies = [ "ureq", "windows-sys 0.61.2", "winit", + "winreg", "x11rb", + "zbus 5.19.0", ] [[package]] name = "solidcraft-3dx-client" -version = "0.27.1" +version = "0.40.0-rc.2" [[package]] name = "solidcraft-cli" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "image", "log", "serde_json", + "solidcore-record", "solidcraft-engine", "solidcraft-gpu", + "solidcraft-kernel", "solidcraft-mcp", ] [[package]] name = "solidcraft-derive" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "proc-macro2", "quote", @@ -4271,15 +4136,17 @@ dependencies = [ [[package]] name = "solidcraft-doc" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "log", "serde", "serde_json", "sha2 0.10.9", + "solidcore-record", "solidcraft-derive", "solidcraft-geom", "solidcraft-kernel", + "solidcraft-profile", "solidcraft-render", "solidcraft-sketch", "thiserror 2.0.21", @@ -4288,7 +4155,7 @@ dependencies = [ [[package]] name = "solidcraft-engine" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "image", "log", @@ -4296,10 +4163,12 @@ dependencies = [ "serde", "serde_json", "serde_path_to_error", + "solidcore-record", "solidcraft-doc", "solidcraft-geom", "solidcraft-io", "solidcraft-kernel", + "solidcraft-profile", "solidcraft-render", "solidcraft-sketch", "thiserror 2.0.21", @@ -4309,16 +4178,17 @@ dependencies = [ [[package]] name = "solidcraft-geom" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "serde", "serde_json", + "solidcore-record", "thiserror 2.0.21", ] [[package]] name = "solidcraft-gpu" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "image", "log", @@ -4327,6 +4197,7 @@ dependencies = [ "robust", "serde", "serde_json", + "solidcore-record", "solidcraft-engine", "solidcraft-geom", "solidcraft-io", @@ -4338,7 +4209,7 @@ dependencies = [ [[package]] name = "solidcraft-io" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "cadmpeg-core", "cadmpeg-ir", @@ -4354,10 +4225,13 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", + "solidcore-record", "solidcraft-doc", "solidcraft-geom", "solidcraft-kernel", + "solidcraft-profile", "solidcraft-sketch", + "solidcraft-testkit", "thiserror 2.0.21", "tiny-skia", "zip", @@ -4365,36 +4239,44 @@ dependencies = [ [[package]] name = "solidcraft-kernel" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "log", "proptest", "rayon", "serde", "serde_json", + "solidcore-record", "solidcraft-geom", + "solidcraft-profile", + "solidcraft-smlib", + "solidcraft-step", "spade", "thiserror 2.0.21", - "truck-meshalgo", - "truck-modeling", - "truck-shapeops", - "truck-stepio", - "truck-topology", "web-time", ] [[package]] name = "solidcraft-mcp" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ + "image", "serde_json", "solidcraft-engine", "solidcraft-gpu", ] +[[package]] +name = "solidcraft-profile" +version = "0.40.0-rc.2" +dependencies = [ + "serde_json", + "web-time", +] + [[package]] name = "solidcraft-render" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "image", "moxcms", @@ -4402,34 +4284,63 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", + "solidcore-record", "solidcraft-geom", + "web-time", "weezl", ] [[package]] name = "solidcraft-sketch" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "harfrust", "serde", "serde_json", "sha2 0.10.9", + "solidcore-record", "solidcraft-geom", "thiserror 2.0.21", "ttf-parser", "unicode-bidi", ] +[[package]] +name = "solidcraft-smlib" +version = "0.40.0-rc.2" +dependencies = [ + "flate2", + "log", + "serde_json", + "solidcore", + "solidcore-record", + "solidcraft-geom", + "solidcraft-profile", +] + [[package]] name = "solidcraft-space-mouse" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "serde", ] +[[package]] +name = "solidcraft-step" +version = "0.40.0-rc.2" +dependencies = [ + "solidcore-record", + "solidcraft-geom", + "solidcraft-profile", +] + +[[package]] +name = "solidcraft-testkit" +version = "0.40.0-rc.2" + [[package]] name = "solidcraft-ui-egui" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "arboard", "egui", @@ -4444,10 +4355,12 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", + "solidcore-record", "solidcraft-engine", "solidcraft-gpu", "solidcraft-space-mouse", "syn 2.0.119", + "sys-locale", "tiny-skia", "toml", "ttf-parser", @@ -4459,7 +4372,7 @@ dependencies = [ [[package]] name = "solidcraft-web" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ "eframe", "egui", @@ -4520,16 +4433,6 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "unicode-ident", -] - [[package]] name = "syn" version = "2.0.119" @@ -4563,6 +4466,18 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -4570,7 +4485,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", "windows-sys 0.61.2", @@ -4767,144 +4682,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "truck-base" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c279de9e92e5dc20a188deb0bb9a4bd421a6a185e57e03e19025e84a36c5a05" -dependencies = [ - "cgmath", - "matext4cgmath", - "rustc-hash 2.1.3", - "serde", -] - -[[package]] -name = "truck-derivers" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "421ff1c5a303aed64e295d9b30e8424ee7a2fa251617a59ae4acfd078496009f" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "truck-geometry" -version = "0.5.0" -dependencies = [ - "serde", - "thiserror 1.0.69", - "truck-base", - "truck-geotrait", -] - -[[package]] -name = "truck-geotrait" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a31fe98d5a0589ad20576260e214af23dea21a8d125da81ad3bbcb666f411f" -dependencies = [ - "getrandom 0.2.17", - "rand 0.8.8", - "thiserror 1.0.69", - "truck-base", - "truck-derivers", -] - -[[package]] -name = "truck-meshalgo" -version = "0.4.0" -dependencies = [ - "array-macro", - "derive_more", - "itertools 0.13.0", - "rayon", - "rustc-hash 2.1.3", - "spade", - "truck-base", - "truck-geometry", - "truck-modeling", - "truck-polymesh", - "truck-topology", -] - -[[package]] -name = "truck-modeling" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8082c2dfac8c2732a014d81807fb5d24dbac0d72ee4de2a705b7fbc05fa05b18" -dependencies = [ - "derive_more", - "rustc-hash 2.1.3", - "serde", - "thiserror 1.0.69", - "truck-base", - "truck-geometry", - "truck-geotrait", - "truck-polymesh", - "truck-topology", -] - -[[package]] -name = "truck-polymesh" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8f22def310af4a89c37beb4839bbf702b302d2c112ea29553759f0e16622fbf" -dependencies = [ - "array-macro", - "bytemuck", - "itertools 0.13.0", - "rustc-hash 2.1.3", - "serde", - "thiserror 1.0.69", - "truck-base", - "truck-geotrait", -] - -[[package]] -name = "truck-shapeops" -version = "0.4.0" -dependencies = [ - "derive_more", - "itertools 0.13.0", - "rustc-hash 2.1.3", - "truck-base", - "truck-geometry", - "truck-geotrait", - "truck-meshalgo", - "truck-topology", -] - -[[package]] -name = "truck-stepio" -version = "0.3.0" -dependencies = [ - "chrono", - "truck-geometry", - "truck-modeling", - "truck-polymesh", - "truck-topology", -] - -[[package]] -name = "truck-topology" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf62a1610405c5e39ab5eb6948f326fc1641689734a6b8207a80792133fe0e78" -dependencies = [ - "parking_lot", - "rayon", - "rclite", - "rustc-hash 2.1.3", - "serde", - "thiserror 1.0.69", - "truck-base", - "truck-geotrait", -] - [[package]] name = "ttf-parser" version = "0.25.1" @@ -6002,9 +5779,11 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.27.1" +version = "0.40.0-rc.2" dependencies = [ + "flate2", "proc-macro2", + "quick-xml", "serde", "serde_json", "sha2 0.10.9", diff --git a/Cargo.toml b/Cargo.toml index 988a5d5d6..365da62d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"] exclude = ["vendor"] [workspace.package] -version = "0.27.1" +version = "0.40.0-rc.2" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -16,8 +16,11 @@ repository = "https://github.com/bherbruck/solidcraft" robust = "1.2" # internal solidcraft-geom = { path = "crates/geom" } +solidcraft-profile = { path = "crates/profile" } solidcraft-sketch = { path = "crates/sketch" } solidcraft-kernel = { path = "crates/kernel" } +solidcraft-smlib = { path = "crates/smlib" } +solidcraft-step = { path = "crates/step" } solidcraft-render = { path = "crates/render" } solidcraft-gpu = { path = "crates/gpu" } solidcraft-doc = { path = "crates/doc" } @@ -28,6 +31,16 @@ solidcraft-space-mouse = { path = "crates/space-mouse" } solidcraft-mcp = { path = "crates/mcp" } solidcraft-derive = { path = "crates/derive" } solidcraft-3dx-client = { path = "crates/threedx-client" } +# The Rust port of NVIDIA's SMLib (Apache-2.0), the B-rep kernel behind crates/smlib. Pinned; +# move the rev on its own commit. For a +# local checkout, add `[patch."https://github.com/tangency-labs/solidcore"] solidcore = { path = +# "../solidcore/crates/solidcore" }` to a `.cargo/config.toml` outside the repository. +solidcore = { git = "https://github.com/tangency-labs/solidcore", rev = "8ddce901671f1cebd9214a31d21895d725e886c8" } +# Geometry as data (solidcore's layers §1, "Record"): the B-rep record, its structural validation +# and the native body file. Pinned like solidcore; for a local checkout, patch it as above. +solidcore-record = { git = "https://github.com/tangency-labs/solidcore", rev = "f5e8e9a29e0c9b7cf6c4040a5bc8878382b3c62f" } +# test tooling: a dev-dependency only (xtask/src/layers.rs) +solidcraft-testkit = { path = "crates/testkit" } # foundation thiserror = "2" @@ -45,14 +58,7 @@ sha2 = "0.10" moxcms = { version = "0.8.1", default-features = false, features = ["extended_range"] } semver = "1" -# geometry kernel (Apache-2.0; see plan/adr/0001-geometry-kernel.md). Only crates/kernel uses it. -truck-modeling = "0.6" -truck-shapeops = { version = "0.4", default-features = false } -truck-meshalgo = { version = "0.4", default-features = false, features = ["tessellation", "analyzers"] } -truck-stepio = { version = "0.3", default-features = false } -truck-topology = "0.6" -# constrained Delaunay + Ruppert refinement for trimmed faces (MIT OR Apache-2.0); already in the -# tree through truck-meshalgo. +# constrained Delaunay + Ruppert refinement for trimmed faces (MIT OR Apache-2.0). spade = { version = "2.15", default-features = false, features = ["std"] } rayon = "1.12" @@ -125,9 +131,7 @@ opt-level = 2 opt-level = 1 # Tests and lints (`cargo xtask ci`, GitHub CI): quick to build, quick enough to run. Light -# optimisation, line tables only (file:line in backtraces), no LTO. Debug assertions are off because -# truck's debug-only checks reject valid geometry (seam edges, closed edges); that was the only -# reason the tests used to build with --release, which cost most of CI's time. +# optimisation, line tables only (file:line in backtraces), no LTO, no debug assertions. [profile.ci] inherits = "dev" opt-level = 1 @@ -150,14 +154,9 @@ codegen-units = 16 # binary). See docs/crash-reports.md. debug = "line-tables-only" -# truck-shapeops with SolidCraft fixes (Apache-2.0, see vendor/truck-shapeops and ATTRIBUTION.md). -[patch.crates-io] -truck-geometry = { path = "vendor/truck-geometry" } -truck-shapeops = { path = "vendor/truck-shapeops" } -truck-stepio = { path = "vendor/truck-stepio" } -truck-meshalgo = { path = "vendor/truck-meshalgo" } -matext4cgmath = { path = "vendor/matext4cgmath" } +# Vendored crates with SolidCraft fixes (see vendor/README.md and ATTRIBUTION.md). +[patch.crates-io] # Keep OpenGL pipelines, resolve textures and CAD callbacks at the same safe sample count. egui-wgpu = { path = "vendor/egui-wgpu" } @@ -165,6 +164,9 @@ egui-wgpu = { path = "vendor/egui-wgpu" } # winit 0.30 never binds and eframe 0.36 still requires winit 0.30. winit = { path = "vendor/winit" } +# macOS: dropping the accessibility adapter leaves AppKit's key-value observers intact (#7535). +accesskit_macos = { path = "vendor/accesskit_macos" } + # Mutation testing (cargo-mutants, docs/mutation-testing.md): the ci profile with incremental # builds, since every mutant rebuilds the crates above the one it changes. [profile.mutants] diff --git a/ROADMAP.md b/ROADMAP.md index aaacf4e81..42d54fa27 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -668,7 +668,9 @@ completed drawings publish atomically. The browser still exports synchronously. pieces survive unfold/refold as one logical sheet group, including split flanged sheets. Cut-outs made in the flat pattern cross bends at any angle or curved: their edges fold to helices and curves on the bend, their walls square to the sheet. Free-form bases use bounded - sampling. + sampling. A fold crosses the sheet's own outer edges the same way, slanted or on any curve, + with the outline exact in the flat pattern and its DXF, and flanges and other folds still go + on the panels. Parallel prismatic partial-depth cuts retain pocket side and depth through transfer and unfold/refold, with separate pocket contours in preview and DXF. Planar Intersect preserves exact holes and retained islands, including the union of multiple selected profiles, and diff --git a/SECURITY.md b/SECURITY.md index 00bd15049..23811aaeb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -3,7 +3,7 @@ ## Supported versions SolidCraft is young and moves quickly, so only the latest release gets security fixes. Please -update to the [latest release](https://github.com/bherbruck/solidcraft/releases/latest) before +update to the [latest release](https://github.com/tangency-labs/solidcraft/releases/latest) before reporting, and check whether the problem is still on `main`. | Version | Supported | @@ -15,18 +15,46 @@ reporting, and check whether the problem is still on `main`. ## Reporting a vulnerability Please **don't open a public issue** for a security problem. Report it privately through GitHub: -open the repository's [Security tab](https://github.com/bherbruck/solidcraft/security) and choose +open the repository's [Security tab](https://github.com/tangency-labs/solidcraft/security) and choose **Report a vulnerability** -([direct link](https://github.com/bherbruck/solidcraft/security/advisories/new)). +([direct link](https://github.com/tangency-labs/solidcraft/security/advisories/new)). -Please include what you found, how to reproduce it (a design file, command or MCP request), the -version and platform, and the impact you expect. I'll acknowledge the report as soon as I can, -keep you updated in the advisory, and credit you when the fix is published unless you'd rather -stay anonymous. +Please include what you found, the steps you ran to reproduce it (a design file, command or MCP +request), the version and platform, and what an attacker gains. I'll acknowledge the report as soon +as I can, keep you updated in the advisory, and credit you when the fix is published unless you'd +rather stay anonymous. -Areas where reports are especially useful: +## What counts as a security issue -- opening untrusted design, STEP, STL or 3MF files (crashes, excessive memory or CPU, path tricks) -- the MCP server and the control API (file access outside the allowed folders, command injection) -- the web app (anything reaching beyond the page's own storage) -- release packages and the update paths (AppImage, Flatpak, MSI, deb, rpm, snap) +Advisories are for problems where someone gets something they shouldn't, without already having +access to your computer or your account. For example: + +- opening a design, STEP, STL or 3MF file from someone else runs code, or reads or overwrites files + it shouldn't +- a website or another computer can reach or control SolidCraft +- an agent gets past a prompt that promised to ask you first +- the web app reaches beyond the page's own storage +- a release package or an update can be tampered with +- an API key or token gets sent somewhere it shouldn't go + +## What to report as a normal bug + +Please [open an issue](https://github.com/tangency-labs/solidcraft/issues/new) for these. They're +still worth fixing, but they aren't security issues: + +- anything that needs a program already running on your computer, or the control token. A program + running as you can already do what you can. +- MCP's allowed folders. They guard against accidents, they aren't a security boundary, and an agent + with a shell of its own can already reach those files. Getting around them isn't a vulnerability. +- crashes, hangs, or heavy memory or CPU use, unless they also lead to something in the list above +- anything that only happens in an unusual setup you'd have to choose on purpose + +## Before you send it + +- **Run it.** Reproduce the problem on the latest release. If you only read the code, say so, and + expect it to wait. +- **Check it yourself.** If a scanner or an AI agent found it, read the code and confirm it first. + These tools tend to overrate what they find. +- **Say what's gained.** Name what the attacker needs and what they get. I set the final severity. + +Reports that don't fit will be closed with a short note, or moved to the issue tracker. diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index e2b1ccdb2..e10e667d3 100644 --- a/THIRD-PARTY-LICENSES.txt +++ b/THIRD-PARTY-LICENSES.txt @@ -1,6 +1,6 @@ Third-party software in SolidCraft -SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 560 crates below. +SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 537 crates below. Generated by `cargo xtask licences` from Cargo.lock and the crates' own licence files. SolidCraft's own licence is in LICENSE-MIT and LICENSE-APACHE, and NOTICE. @@ -20,9 +20,7 @@ allocator-api2 0.2.21 (MIT OR Apache-2.0) android-activity 0.6.1 (MIT OR Apache-2.0) android-properties 0.2.2 (MIT) android_system_properties 0.1.6 (MIT OR Apache-2.0) -approx 0.4.0 (Apache-2.0) arboard 3.6.1 (MIT OR Apache-2.0) -array-macro 2.1.8 (MIT OR Apache-2.0) arrayref 0.3.9 (BSD-2-Clause) arrayvec 0.7.8 (MIT OR Apache-2.0) as-raw-xcb-connection 1.0.1 (MIT OR Apache-2.0) @@ -53,7 +51,6 @@ block-padding 0.3.3 (MIT OR Apache-2.0) block2 0.5.1 (MIT) block2 0.6.2 (MIT) blocking 1.7.0 (Apache-2.0 OR MIT) -branches 0.3.0 (MIT) bumpalo 3.20.3 (MIT OR Apache-2.0) bytemuck 1.25.2 (Zlib OR Apache-2.0 OR MIT) bytemuck_derive 1.12.1 (Zlib OR Apache-2.0 OR MIT) @@ -74,9 +71,7 @@ calloop-wayland-source 0.4.1 (MIT) cbc 0.1.2 (MIT OR Apache-2.0) cfg-if 1.0.5 (MIT OR Apache-2.0) cgl 0.3.2 (MIT / Apache-2.0) -cgmath 0.18.0 (Apache-2.0) chardetng 0.1.17 (Apache-2.0 OR MIT) -chrono 0.4.45 (MIT OR Apache-2.0) cipher 0.4.4 (MIT OR Apache-2.0) clipboard-win 5.4.1 (BSL-1.0) codespan-reporting 0.13.1 (Apache-2.0) @@ -85,7 +80,6 @@ color_quant 1.1.0 (MIT) combine 4.6.8 (MIT) concurrent-queue 2.5.0 (Apache-2.0 OR MIT) const-oid 0.10.2 (Apache-2.0 OR MIT) -convert_case 0.4.0 (MIT) core-foundation 0.10.1 (MIT OR Apache-2.0) core-foundation 0.9.4 (MIT OR Apache-2.0) core-foundation-sys 0.8.7 (MIT OR Apache-2.0) @@ -105,7 +99,6 @@ crypto-common 0.2.2 (MIT OR Apache-2.0) cursor-icon 1.2.0 (MIT OR Apache-2.0 OR Zlib) dbus 0.9.12 (Apache-2.0/MIT) dbus-secret-service 4.1.0 (MIT OR Apache-2.0) -derive_more 0.99.20 (MIT) digest 0.10.7 (MIT OR Apache-2.0) digest 0.11.3 (MIT OR Apache-2.0) dispatch 0.2.0 (MIT) @@ -185,8 +178,6 @@ hmac 0.12.1 (MIT OR Apache-2.0) http 1.5.0 (MIT OR Apache-2.0) httparse 1.10.1 (MIT OR Apache-2.0) hybrid-array 0.4.15 (MIT OR Apache-2.0) -iana-time-zone 0.1.65 (MIT OR Apache-2.0) -iana-time-zone-haiku 0.1.2 (MIT OR Apache-2.0) icu_collections 2.3.0 (Unicode-3.0) icu_locale_core 2.3.0 (Unicode-3.0) icu_normalizer 2.3.0 (Unicode-3.0) @@ -201,7 +192,6 @@ image-webp 0.2.4 (MIT OR Apache-2.0) indexmap 2.14.2 (Apache-2.0 OR MIT) inflections 1.1.1 (MIT) inout 0.1.4 (MIT OR Apache-2.0) -itertools 0.13.0 (MIT OR Apache-2.0) itertools 0.15.0 (MIT OR Apache-2.0) itoa 1.0.18 (MIT OR Apache-2.0) jni 0.22.4 (MIT OR Apache-2.0) @@ -210,7 +200,6 @@ jni-sys 0.3.1 (MIT OR Apache-2.0) jni-sys 0.4.1 (MIT OR Apache-2.0) jni-sys-macros 0.4.1 (MIT OR Apache-2.0) js-sys 0.3.106 (MIT OR Apache-2.0) -katexit 0.1.5 (MIT OR Apache-2.0) keyboard-types 0.8.3 (MIT OR Apache-2.0) keyring 3.6.3 (MIT OR Apache-2.0) khronos-egl 6.0.0 (MIT/Apache-2.0) @@ -228,7 +217,6 @@ litemap 0.8.3 (Unicode-3.0) litrs 1.0.0 (MIT OR Apache-2.0) lock_api 0.4.14 (MIT OR Apache-2.0) log 0.4.34 (MIT OR Apache-2.0) -matext4cgmath 0.1.0 (Apache-2.0) memchr 2.8.3 (Unlicense OR MIT) memmap2 0.9.11 (MIT OR Apache-2.0) memoffset 0.9.1 (MIT) @@ -312,8 +300,6 @@ potential_utf 0.1.6 (Unicode-3.0) ppv-lite86 0.2.21 (MIT OR Apache-2.0) presser 0.3.1 (MIT OR Apache-2.0) proc-macro-crate 3.5.0 (MIT OR Apache-2.0) -proc-macro-error 1.0.4 (MIT OR Apache-2.0) -proc-macro-error-attr 1.0.4 (MIT OR Apache-2.0) proc-macro2 1.0.107 (MIT OR Apache-2.0) profiling 1.0.18 (MIT OR Apache-2.0) pxfm 0.1.30 (BSD-3-Clause OR Apache-2.0) @@ -331,7 +317,6 @@ raw-window-handle 0.6.2 (MIT OR Apache-2.0 OR Zlib) raw-window-metal 1.1.0 (MIT OR Apache-2.0) rayon 1.12.0 (MIT OR Apache-2.0) rayon-core 1.13.0 (MIT OR Apache-2.0) -rclite 0.2.8 (MIT OR Apache-2.0) read-fonts 0.41.0 (MIT OR Apache-2.0) redox_syscall 0.4.1 (MIT) redox_syscall 0.5.18 (MIT) @@ -393,16 +378,18 @@ smithay-client-toolkit 0.19.2 (MIT) smithay-client-toolkit 0.20.0 (MIT) smithay-clipboard 0.7.3 (MIT) smol_str 0.2.2 (MIT OR Apache-2.0) +solidcore 1.0.1 (Apache-2.0) +solidcore-record 0.1.0 (Apache-2.0) spade 2.15.1 (MIT OR Apache-2.0) spirv 0.4.0+sdk-1.4.341.0 (Apache-2.0) stable_deref_trait 1.2.1 (MIT OR Apache-2.0) static_assertions 1.1.0 (MIT OR Apache-2.0) strict-num 0.1.1 (MIT) subtle 2.6.1 (BSD-3-Clause) -syn 1.0.109 (MIT OR Apache-2.0) syn 2.0.119 (MIT OR Apache-2.0) syn 3.0.6 (MIT OR Apache-2.0) synstructure 0.13.2 (MIT) +sys-locale 0.3.2 (MIT OR Apache-2.0) tempfile 3.27.0 (MIT OR Apache-2.0) termcolor 1.4.1 (Unlicense OR MIT) thiserror 1.0.69 (MIT OR Apache-2.0) @@ -422,16 +409,6 @@ toml_writer 1.1.3+spec-1.1.0 (MIT OR Apache-2.0) tracing 0.1.44 (MIT) tracing-attributes 0.1.31 (MIT) tracing-core 0.1.36 (MIT) -truck-base 0.5.0 (Apache-2.0) -truck-derivers 0.1.0 (Apache-2.0) -truck-geometry 0.5.0 (Apache-2.0) -truck-geotrait 0.4.0 (Apache-2.0) -truck-meshalgo 0.4.0 (Apache-2.0) -truck-modeling 0.6.0 (Apache-2.0) -truck-polymesh 0.6.0 (Apache-2.0) -truck-shapeops 0.4.0 (Apache-2.0) -truck-stepio 0.3.0 (Apache-2.0) -truck-topology 0.6.0 (Apache-2.0) ttf-parser 0.25.1 (MIT OR Apache-2.0) twox-hash 2.1.5 (MIT) type-map 0.5.1 (MIT/Apache-2.0) @@ -595,12 +572,11 @@ pin-project 1.1.13, pin-project-internal 1.1.13, pin-project-lite 0.2.17, piper 1.0.107, quote 1.0.47, ref-cast 1.0.27, ref-cast-impl 1.0.27, rustc-hash 1.1.0, rustc-hash 2.1.3, rustix 0.38.44, rustix 1.1.5, rustversion 1.0.23, semver 1.0.28, serde 1.0.229, serde_core 1.0.229, serde_derive 1.0.229, serde_derive_internals 0.30.0, serde_json 1.0.151, serde_path_to_error 0.1.20, -serde_repr 0.1.21, simd_cesu8 1.2.0, smol_str 0.2.2, syn 1.0.109, syn 2.0.119, syn 3.0.6, thiserror -1.0.69, thiserror 2.0.21, thiserror-impl 1.0.69, thiserror-impl 2.0.21, typed-path 0.13.0, typeid -1.0.3, unicode-ident 1.0.26, utf8-zero 0.8.1, wasi 0.11.1+wasi-snapshot-preview1, wasip2 -1.0.4+wasi-0.2.12, wit-bindgen 0.57.1, x11-dl 2.21.0, xdg-home 1.3.0, zbus-lockstep 0.5.2, -zbus-lockstep-macros 0.5.2, zbus_names 3.0.0, zmij 1.0.23, zvariant_utils 2.1.0, zvariant_utils -4.2.0 +serde_repr 0.1.21, simd_cesu8 1.2.0, smol_str 0.2.2, syn 2.0.119, syn 3.0.6, thiserror 1.0.69, +thiserror 2.0.21, thiserror-impl 1.0.69, thiserror-impl 2.0.21, typed-path 0.13.0, typeid 1.0.3, +unicode-ident 1.0.26, utf8-zero 0.8.1, wasi 0.11.1+wasi-snapshot-preview1, wasip2 1.0.4+wasi-0.2.12, +wit-bindgen 0.57.1, x11-dl 2.21.0, xdg-home 1.3.0, zbus-lockstep 0.5.2, zbus-lockstep-macros 0.5.2, +zbus_names 3.0.0, zmij 1.0.23, zvariant_utils 2.1.0, zvariant_utils 4.2.0 ================================================================================ Permission is hereby granted, free of charge, to any @@ -1113,19 +1089,19 @@ ahash 0.8.12, arrayvec 0.7.8, async-channel 2.5.0, async-executor 1.14.0, async- euclid 0.22.14, event-listener 5.4.2, event-listener-strategy 0.5.4, fastrand 2.5.0, flate2 1.1.10, form_urlencoded 1.2.2, futures-lite 2.6.1, gethostname 1.1.0, gif 0.14.2, glow 0.17.0, gltf 1.4.1, gltf-derive 1.4.1, gltf-json 1.4.1, hashbrown 0.16.1, hashbrown 0.17.1, hermit-abi 0.5.3, httparse -1.10.1, idna 1.1.0, idna_adapter 1.2.2, indexmap 2.14.2, itertools 0.13.0, itertools 0.15.0, js-sys -0.3.106, keyboard-types 0.8.3, khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, -linux-raw-sys 0.4.15, lock_api 0.4.14, log 0.4.34, muda 0.21.2, num 0.4.3, num-bigint 0.4.8, -num-complex 0.4.6, num-integer 0.1.47, num-iter 0.1.46, num-rational 0.4.2, num-traits 0.2.19, -once_cell 1.21.4, openssl-probe 0.2.1, ordered-stream 0.2.0, parking 2.2.1, parking_lot 0.12.5, -parking_lot_core 0.9.12, percent-encoding 2.3.2, piper 0.2.5, plain 0.2.3, png 0.18.1, polling -3.11.0, pollster 0.4.0, pollster 1.0.1, rayon 1.12.0, rayon-core 1.13.0, renderdoc-sys 1.1.0, robust -1.2.0, ron 0.12.2, roxmltree 0.21.1, rustc-hash 1.1.0, rustix 0.38.44, rustix 1.1.5, rustls 0.23.46, +1.10.1, idna 1.1.0, idna_adapter 1.2.2, indexmap 2.14.2, itertools 0.15.0, js-sys 0.3.106, +keyboard-types 0.8.3, khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys +0.4.15, lock_api 0.4.14, log 0.4.34, muda 0.21.2, num 0.4.3, num-bigint 0.4.8, num-complex 0.4.6, +num-integer 0.1.47, num-iter 0.1.46, num-rational 0.4.2, num-traits 0.2.19, once_cell 1.21.4, +openssl-probe 0.2.1, ordered-stream 0.2.0, parking 2.2.1, parking_lot 0.12.5, parking_lot_core +0.9.12, percent-encoding 2.3.2, piper 0.2.5, plain 0.2.3, png 0.18.1, polling 3.11.0, pollster +0.4.0, pollster 1.0.1, rayon 1.12.0, rayon-core 1.13.0, renderdoc-sys 1.1.0, robust 1.2.0, ron +0.12.2, roxmltree 0.21.1, rustc-hash 1.1.0, rustix 0.38.44, rustix 1.1.5, rustls 0.23.46, rustls-native-certs 0.8.5, scoped-tls 1.0.1, scopeguard 1.2.0, secret-service 4.0.0, security-framework 2.11.1, security-framework 3.7.0, security-framework-sys 2.17.0, signal-hook-registry 1.4.8, simd_cesu8 1.2.0, smallvec 1.16.2, smol_str 0.2.2, stable_deref_trait -1.2.1, syn 1.0.109, tempfile 3.27.0, ttf-parser 0.25.1, unicode-bidi 0.3.18, unicode-segmentation -1.13.3, unicode-width 0.2.2, url 2.5.8, uuid 1.27.0, wasi 0.11.1+wasi-snapshot-preview1, wasip2 +1.2.1, tempfile 3.27.0, ttf-parser 0.25.1, unicode-bidi 0.3.18, unicode-segmentation 1.13.3, +unicode-width 0.2.2, url 2.5.8, uuid 1.27.0, wasi 0.11.1+wasi-snapshot-preview1, wasip2 1.0.4+wasi-0.2.12, wasm-bindgen 0.2.129, wasm-bindgen-futures 0.4.79, wasm-bindgen-macro 0.2.129, wasm-bindgen-macro-support 0.2.129, wasm-bindgen-shared 0.2.129, web-sys 0.3.106, weezl 0.1.12, wit-bindgen 0.57.1 @@ -1554,9 +1530,8 @@ android-activity 0.6.1, arboard 3.6.1, color 0.3.3, fdeflate 0.3.7, fearless_sim image 0.25.10, image-webp 0.2.4, linebender_resource_handle 0.1.1, miniz_oxide 0.8.9, miniz_oxide 0.9.1, naga 30.0.1, naga-types 30.0.1, pin-project 1.1.13, pin-project-internal 1.1.13, pin-project-lite 0.2.17, portable-atomic 1.15.0, portable-atomic-util 0.2.8, range-alloc 0.1.5, -raw-window-handle 0.6.2, simdutf8 0.1.5, truck-geometry 0.5.0, truck-meshalgo 0.4.0, truck-shapeops -0.4.0, truck-stepio 0.3.0, vello_common 0.1.0, vello_cpu 0.1.0, wgpu 30.0.1, wgpu-core 30.0.1, -wgpu-core-deps-apple 30.0.1, wgpu-core-deps-emscripten 30.0.1, wgpu-core-deps-wasm 30.0.1, +raw-window-handle 0.6.2, simdutf8 0.1.5, vello_common 0.1.0, vello_cpu 0.1.0, wgpu 30.0.1, wgpu-core +30.0.1, wgpu-core-deps-apple 30.0.1, wgpu-core-deps-emscripten 30.0.1, wgpu-core-deps-wasm 30.0.1, wgpu-core-deps-windows-linux-android 30.0.1, wgpu-hal 30.0.1, wgpu-naga-bridge 30.0.1, wgpu-types 30.0.1 ================================================================================ @@ -1832,12 +1807,129 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ -approx 0.4.0, as-raw-xcb-connection 1.0.1, atspi 0.29.0, atspi-common 0.13.0, atspi-proxies 0.13.0, -cgmath 0.18.0, chardetng 0.1.17, codespan-reporting 0.13.1, encoding_rs 0.8.42, kurbo 0.13.1, -multiversion_no_op 1.0.0, nohash-hasher 0.2.0, peniko 0.6.1, polycool 0.4.0, raw-window-metal 1.1.0, -rustls-platform-verifier 0.7.1, self_cell 1.3.0, siphasher 1.0.4, spade 2.15.1, static_assertions -1.1.0, ureq 3.4.2, ureq-proto 0.6.4, utf8_iter 1.0.4, x11rb 0.13.2, x11rb-protocol 0.13.2, zeroize -1.9.1, zeroize_derive 1.5.0, zune-core 0.5.3, zune-jpeg 0.5.15 +arboard 3.6.1 +================================================================================ + +MIT License + +Copyright (c) 2022 The Arboard contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +================================================================================ +arrayref 0.3.9 +================================================================================ + +Copyright (c) 2015 David Roundy +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ +arrayvec 0.7.8 +================================================================================ + +Copyright (c) Ulrik Sverdrup "bluss" 2015-2023 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +================================================================================ +as-raw-xcb-connection 1.0.1 +================================================================================ + +Copyright 2019 as-raw-xcb-connection Contributers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +================================================================================ +as-raw-xcb-connection 1.0.1, atspi 0.29.0, atspi-common 0.13.0, atspi-proxies 0.13.0, chardetng +0.1.17, codespan-reporting 0.13.1, encoding_rs 0.8.42, kurbo 0.13.1, multiversion_no_op 1.0.0, +nohash-hasher 0.2.0, peniko 0.6.1, polycool 0.4.0, raw-window-metal 1.1.0, rustls-platform-verifier +0.7.1, self_cell 1.3.0, siphasher 1.0.4, spade 2.15.1, static_assertions 1.1.0, sys-locale 0.3.2, +ureq 3.4.2, ureq-proto 0.6.4, utf8_iter 1.0.4, x11rb 0.13.2, x11rb-protocol 0.13.2, zeroize 1.9.1, +zeroize_derive 1.5.0, zune-core 0.5.3, zune-jpeg 0.5.15 ================================================================================ Apache License @@ -2042,123 +2134,6 @@ Apache License See the License for the specific language governing permissions and limitations under the License. -================================================================================ -arboard 3.6.1 -================================================================================ - -MIT License - -Copyright (c) 2022 The Arboard contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -================================================================================ -arrayref 0.3.9 -================================================================================ - -Copyright (c) 2015 David Roundy -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the - distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -================================================================================ -arrayvec 0.7.8 -================================================================================ - -Copyright (c) Ulrik Sverdrup "bluss" 2015-2023 - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - -================================================================================ -as-raw-xcb-connection 1.0.1 -================================================================================ - -Copyright 2019 as-raw-xcb-connection Contributers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - ================================================================================ ash 0.38.0+1.3.281 ================================================================================ @@ -2939,32 +2914,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -branches 0.3.0, rclite 0.2.8 -================================================================================ - -MIT License - -Copyright (c) 2023 Khashayar Fereidani - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ================================================================================ bumpalo 3.20.3 ================================================================================ @@ -3380,250 +3329,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -chrono 0.4.45 -================================================================================ - -Rust-chrono is dual-licensed under The MIT License [1] and -Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and -contributors. - -Nota Bene: This is same as the Rust Project's own license. - - -[1]: , which is reproduced below: - -~~~~ -The MIT License (MIT) - -Copyright (c) 2014, Kang Seonghoon. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -~~~~ - - -[2]: , which is reproduced below: - -~~~~ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -~~~~ - ================================================================================ cipher 0.4.4 ================================================================================ @@ -5252,32 +4957,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -derive_more 0.99.20 -================================================================================ - -The MIT License (MIT) - -Copyright (c) 2016 Jelte Fennema - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ================================================================================ digest 0.10.7, hmac 0.12.1 ================================================================================ @@ -5582,7 +5261,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ -either 1.19.0, itertools 0.13.0, itertools 0.15.0 +either 1.19.0, itertools 0.15.0 ================================================================================ Copyright (c) 2015 @@ -7855,242 +7534,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -iana-time-zone 0.1.65, iana-time-zone-haiku 0.1.2 -================================================================================ - -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright 2020 Andrew Straw - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -================================================================================ -iana-time-zone 0.1.65, iana-time-zone-haiku 0.1.2 -================================================================================ - -Copyright (c) 2020 Andrew D. Straw - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - ================================================================================ icu_collections 2.3.0, icu_locale_core 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, litemap 0.8.3, potential_utf @@ -9229,212 +8672,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -matext4cgmath 0.1.0 -================================================================================ - -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2022 Research Institute for Computational Science Co. Ltd - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ================================================================================ memmap2 0.9.11 ================================================================================ @@ -10705,238 +9942,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -proc-macro-error 1.0.4, proc-macro-error-attr 1.0.4 -================================================================================ - -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright 2019-2020 CreepySkeleton - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -================================================================================ -proc-macro-error 1.0.4, proc-macro-error-attr 1.0.4 -================================================================================ - -MIT License - -Copyright (c) 2019-2020 CreepySkeleton - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ================================================================================ quick-error 2.0.1 ================================================================================ @@ -11574,24 +10579,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -rclite 0.2.8 -================================================================================ - -Copyright 2023 Khashayar Fereidani - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - ================================================================================ redox_syscall 0.4.1, redox_syscall 0.5.18, redox_syscall 0.9.4 ================================================================================ @@ -13414,6 +12401,249 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +solidcore 1.0.1 +================================================================================ + +Copyright (c) 2020-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2020-2026 NVIDIA CORPORATION & AFFILIATES + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +================================================================================ +solidcore 1.0.1 +================================================================================ + +solidcore +Copyright (c) 2026 The solidcore contributors + +This product is a Rust port (a derivative work) of the SMLib and SM_API +components of USD BRep, https://github.com/NVIDIA-Omniverse/usd-brep +(v1.0.1, commit 3fd5b95), licensed under the Apache License, Version 2.0. +See ATTRIBUTION.md for exactly which upstream material is used. + +The upstream work carries the following notice: + + USD BRep is Copyright (c) 2020-2026, NVIDIA CORPORATION & AFFILIATES. All + rights reserved. NVIDIA-authored portions of this product are licensed under + the Apache License, Version 2.0, except where otherwise noted. + +The upstream SMLib and SM_API source files carry the SPDX header: + + SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + SPDX-License-Identifier: Apache-2.0 + +Upstream third-party notices (THIRD_PARTY_NOTICES.md at the pinned commit) cover +OpenUSD, oneTBB, hwloc, MaterialX, OpenSubdiv, CPython, HACL*, pybind11, the +UsdSolid proposals, usd-validation-nvidia, the repo bootstrap scripts and optional +Python GUI tooling. None of those components is part of SMLib or SM_API, and none +is used, ported or redistributed by solidcore, so no further third-party notices +apply. + +Modifications: the C++ sources were translated to Rust and restructured (arena +topology, typed ids, error values instead of status codes, explicit kernel +state instead of a global context). Each ported Rust file names the upstream +file(s) it derives from in its header. + ================================================================================ spade 2.15.1 ================================================================================ @@ -13570,6 +12800,32 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +sys-locale 0.3.2 +================================================================================ + +MIT License + +Copyright (c) 2021 1Password + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + ================================================================================ tempfile 3.27.0 ================================================================================ @@ -16720,7 +15976,6 @@ accesskit_macos 0.26.3: MIT OR Apache-2.0 (https://github.com/AccessKit/accesski accesskit_unix 0.21.1: MIT OR Apache-2.0 (https://github.com/AccessKit/accesskit) accesskit_windows 0.32.1: MIT OR Apache-2.0 (https://github.com/AccessKit/accesskit) accesskit_winit 0.32.2: Apache-2.0 (https://github.com/AccessKit/accesskit) -array-macro 2.1.8: MIT OR Apache-2.0 (https://codeberg.org/xfix/array-macro) block2 0.5.1: MIT (https://github.com/madsmtm/objc2) block2 0.6.2: MIT (https://github.com/madsmtm/objc2) cadmpeg-codec-freecad 0.6.3: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) @@ -16731,7 +15986,6 @@ cadmpeg-core 0.6.3: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) cadmpeg-ir 0.6.3: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) cadmpeg-registry 0.6.3: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) clipboard-win 5.4.1: BSL-1.0 (https://github.com/DoumanAsh/clipboard-win) -convert_case 0.4.0: MIT (https://github.com/rutrum/convert-case) dispatch 0.2.0: MIT (http://github.com/SSheldon/rust-dispatch) dispatch2 0.3.1: Zlib OR Apache-2.0 OR MIT (https://github.com/madsmtm/objc2) ecolor 0.36.2: MIT OR Apache-2.0 (https://github.com/emilk/egui) @@ -16745,7 +15999,6 @@ epaint_default_fonts 0.36.2: (MIT OR Apache-2.0) AND OFL-1.1 AND Ubuntu-font-1.0 jni 0.22.4: MIT OR Apache-2.0 (https://github.com/jni-rs/jni-rs) jni-macros 0.22.4: MIT OR Apache-2.0 (https://github.com/jni-rs/jni-rs) jni-sys-macros 0.4.1: MIT OR Apache-2.0 (https://github.com/jni-rs/jni-sys) -katexit 0.1.5: MIT OR Apache-2.0 (https://github.com/termoshtt/katexit) ndk 0.9.0: MIT OR Apache-2.0 (https://github.com/rust-mobile/ndk) ndk-context 0.1.1: MIT OR Apache-2.0 (https://github.com/rust-windowing/android-ndk-rs) ndk-sys 0.6.0+11769913: MIT OR Apache-2.0 (https://github.com/rust-mobile/ndk) @@ -16779,13 +16032,8 @@ profiling 1.0.18: MIT OR Apache-2.0 (https://github.com/aclysma/profiling) r-efi 5.3.0: MIT OR Apache-2.0 OR LGPL-2.1-or-later (https://github.com/r-efi/r-efi) r-efi 6.0.0: MIT OR Apache-2.0 OR LGPL-2.1-or-later (https://github.com/r-efi/r-efi) rustls-platform-verifier-android 0.2.0: MIT OR Apache-2.0 (https://github.com/rustls/rustls-platform-verifier) +solidcore-record 0.1.0: Apache-2.0 (https://github.com/tangency-labs/solidcore) spirv 0.4.0+sdk-1.4.341.0: Apache-2.0 (https://github.com/gfx-rs/rspirv) -truck-base 0.5.0: Apache-2.0 (https://github.com/ricosjp/truck) -truck-derivers 0.1.0: Apache-2.0 (https://github.com/ricosjp/truck) -truck-geotrait 0.4.0: Apache-2.0 (https://github.com/ricosjp/truck) -truck-modeling 0.6.0: Apache-2.0 (https://github.com/ricosjp/truck) -truck-polymesh 0.6.0: Apache-2.0 (https://github.com/ricosjp/truck) -truck-topology 0.6.0: Apache-2.0 (https://github.com/ricosjp/truck) ================================================================================ Bundled fonts (SIL Open Font License, Version 1.1) @@ -16799,6 +16047,14 @@ Bundled fonts (SIL Open Font License, Version 1.1) Copyright 2022 The BIZ UDGothic Project Authors (https://github.com/googlefonts/morisawa-biz-ud-mincho) Source: https://github.com/googlefonts/morisawa-biz-ud-gothic +- CraftUI-SC.otf (assets/fonts/craft-ui-sc/CraftUI-SC.otf) + Copyright 2014-2021 Adobe / Google Inc. (Noto Sans SC subset for SolidCraft web zh) + Source: https://github.com/notofonts/noto-cjk (Sans SubsetOTF/SC) + +- CraftUI-TC.otf (assets/fonts/craft-ui-tc/CraftUI-TC.otf) + Copyright 2014-2021 Adobe / Google Inc. (Noto Sans TC subset for SolidCraft web zh-TW) + Source: https://github.com/notofonts/noto-cjk (Sans SubsetOTF/TC) + - IBMPlexSans-Variable.ttf (assets/fonts/ibm-plex-sans/IBMPlexSans-Variable.ttf) Copyright 2017 IBM Corp. with Reserved Font Name "Plex" Source: https://github.com/IBM/plex diff --git a/apps/solidcraft-cli/Cargo.toml b/apps/solidcraft-cli/Cargo.toml index 4342a1415..e06584e27 100644 --- a/apps/solidcraft-cli/Cargo.toml +++ b/apps/solidcraft-cli/Cargo.toml @@ -20,11 +20,15 @@ name = "solvecraft-cli" path = "src/alias.rs" [features] -default = ["raytrace-cpu"] +default = ["raytrace-cpu", "profile"] bundled-render-library = ["solidcraft-engine/bundled-render-library"] raytrace-cpu = ["solidcraft-engine/raytrace-cpu"] +# The profiler, compiled in so any build can say where its time goes (`--profile`, +# SOLIDCRAFT_PROFILE=1); it records nothing until asked. +profile = ["solidcraft-engine/profile"] [dependencies] +solidcore-record = { workspace = true } solidcraft-engine = { workspace = true } solidcraft-gpu = { workspace = true } solidcraft-mcp = { workspace = true } @@ -34,3 +38,5 @@ serde_json = { workspace = true } [dev-dependencies] # Snapshot tests decode the pictures to compare them with a tolerance. image = { workspace = true } +# Tests measure meshes at their own tolerances. +solidcraft-kernel = { workspace = true } diff --git a/apps/solidcraft-cli/src/bench_agent.rs b/apps/solidcraft-cli/src/bench_agent.rs index ec059c25c..cb42cf7d5 100644 --- a/apps/solidcraft-cli/src/bench_agent.rs +++ b/apps/solidcraft-cli/src/bench_agent.rs @@ -184,7 +184,7 @@ pub fn run(args: &[String]) -> Result<(), String> { s.execute(id, &c["params"]).map_err(|e| format!("command {i} ({id}): {e}"))?; run.push(t.elapsed().as_secs_f64() * 1000.0); let t = std::time::Instant::now(); - s.world_state().warm_meshes(|| true); + s.world_state().map_err(|e| e.to_string())?.warm_meshes(|| true); shown.push(t.elapsed().as_secs_f64() * 1000.0); if run.len() == 100 || i + 1 == commands.len() { let mean = |v: &[f64]| v.iter().sum::() / v.len().max(1) as f64; @@ -198,7 +198,7 @@ pub fn run(args: &[String]) -> Result<(), String> { shown.clear(); } } - let world = s.world_state(); + let world = s.world_state().map_err(|e| e.to_string())?; println!( "{}", json!({"step": "built", "ms": began.elapsed().as_secs_f64() * 1000.0, "commands": commands.len(), "features": s.doc.features.len(), "bodies": world.bodies.len()}) @@ -236,7 +236,7 @@ mod tests { } } assert!(s.model.results.iter().all(|r| r.error.is_none())); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(world.bodies.len() > 40, "{} bodies", world.bodies.len()); assert!(world.bodies.iter().any(|b| b.name.contains("spoke"))); } diff --git a/apps/solidcraft-cli/src/fuzz.rs b/apps/solidcraft-cli/src/fuzz.rs index 5a25b9d0f..7b1fa61a3 100644 --- a/apps/solidcraft-cli/src/fuzz.rs +++ b/apps/solidcraft-cli/src/fuzz.rs @@ -40,8 +40,6 @@ pub fn one(args: &[String]) -> Result<(), String> { "steps": run.steps.iter().map(|s| s.kind).collect::>(), "unsupported": run.unsupported, "rejected": run.rejected, - "boolean_fallbacks": run.boolean_fallbacks, - "boolean_reports_truncated": run.boolean_reports_truncated, "panics": PANICS.swap(0, std::sync::atomic::Ordering::SeqCst), }); if run.outcome.is_bug() { @@ -191,23 +189,9 @@ fn summarise(results: &[Value], took: Duration) -> String { let mut boolean: BTreeMap = BTreeMap::new(); let mut at_step: BTreeMap = BTreeMap::new(); let mut unsupported: BTreeMap = BTreeMap::new(); - let mut fallbacks: BTreeMap = BTreeMap::new(); - let mut truncated = [0usize; 2]; let mut steps = 0; let (mut dp, mut bp) = (0, 0); for v in results { - for (i, group) in ["design", "boolean"].into_iter().enumerate() { - if v[group]["boolean_reports_truncated"].as_bool().unwrap_or(false) { - truncated[i] += 1; - } - if let Some(counts) = v[group]["boolean_fallbacks"].as_object() { - for (strategy, count) in counts { - if let Some(total) = fallbacks.entry(strategy.clone()).or_default().get_mut(i) { - *total = total.saturating_add(count.as_u64().unwrap_or(0)); - } - } - } - } dp += usize::from(v["design"]["panics"].as_u64().unwrap_or(0) > 0); bp += usize::from(v["boolean_panics"].as_u64().unwrap_or(0) > 0); let k = if v.get("timeout").is_some() { @@ -246,11 +230,6 @@ fn summarise(results: &[Value], took: Duration) -> String { for (k, c) in &boolean { s += &format!("- {k}: {}\n", pct(*c)); } - s += "\nSuccessful Boolean retries (events, including nested operations):\n"; - for (strategy, [designs, checks]) in &fallbacks { - s += &format!("- {strategy}: designs {designs}, boolean checks {checks}\n"); - } - s += &format!("- Capped reports: designs {}, boolean checks {}\n", truncated[0], truncated[1]); s } @@ -259,15 +238,13 @@ mod tests { use super::*; #[test] - fn report_counts_retry_events_separately_and_marks_incomplete_logs() { + fn report_counts_outcomes_and_timeouts() { let results = [ - json!({"design":{"outcome":{"kind":"ok"},"boolean_fallbacks":{"shifted_operands":2}},"boolean":{"outcome":"ok","boolean_fallbacks":{"shifted_operands":3},"boolean_reports_truncated":true}}), - json!({"design":{"outcome":{"kind":"ok"},"boolean_fallbacks":{"shifted_operands":1}},"boolean":{"outcome":"ok"}}), + json!({"design":{"outcome":{"kind":"ok"}},"boolean":{"outcome":"ok"}}), + json!({"design":{"outcome":{"kind":"ok"}},"boolean":{"outcome":"ok"}}), json!({"timeout":90}), ]; let text = summarise(&results, Duration::ZERO); - assert!(text.contains("shifted_operands: designs 3, boolean checks 3"), "{text}"); - assert!(text.contains("Capped reports: designs 0, boolean checks 1"), "{text}"); assert!(text.contains("timeout: 1 (33.3 %)"), "{text}"); } } diff --git a/apps/solidcraft-cli/src/kernel_cases.rs b/apps/solidcraft-cli/src/kernel_cases.rs new file mode 100644 index 000000000..d320b3a6e --- /dev/null +++ b/apps/solidcraft-cli/src/kernel_cases.rs @@ -0,0 +1,1305 @@ +//! The kernel regression rig: replay `tests/kernel-cases///recipe.json` (an oracle +//! recipe or a command script) and grade the result against the case's own `expected.json`: +//! closed-form numbers where the case has them, and always the invariants (the operation's +//! outcome, one closed valid solid per body, the expected counts). One kernel per run; kernels +//! are never compared with each other. See tests/kernel-cases/README.md. + +use serde_json::{Value, json}; +use solidcraft_engine::geom::prelude::*; + +use crate::oracle::{ABS_FRAC, Checks, REL_TOL, totals, v3}; +use crate::{read_json, recipe}; + +/// The kernel the cases run on: solidcore, the only one. +fn kernel() -> String { + "solidcore".into() +} + +/// How many cases a chain of `base` recipes may go through (a ladder case builds on the one +/// before it, which builds on the one before that). +const MAX_BASE_DEPTH: usize = 32; + +/// The case's commands: a script as is, or an oracle recipe translated. In a string, `$CASE` is +/// the case directory (input files such as `input.step`) and `$OUT` a scratch directory for files +/// the case writes (an export), outside the repository. A script with `"base": ""` (relative to this case's directory) runs that case's commands first: a ladder +/// case starts from the previous tier's finished part without copying its commands. +fn script(dir: &str, out: &str, recipe: &Value) -> Result { + script_at(dir, out, recipe, 0) +} + +fn script_at(dir: &str, out: &str, recipe: &Value, depth: usize) -> Result { + let s = if recipe.get("commands").is_some() || recipe.is_array() { recipe.clone() } else { recipe::to_script(recipe)? }; + let text = serde_json::to_string(&s).map_err(|e| e.to_string())?; + let inner = |p: &str| -> Result { + let j = serde_json::to_string(p).map_err(|e| e.to_string())?; + Ok(j.get(1..j.len().saturating_sub(1)).unwrap_or("").to_string()) + }; + let own: Value = serde_json::from_str(&text.replace("$CASE", &inner(dir)?).replace("$OUT", &inner(out)?)).map_err(|e| e.to_string())?; + let Some(base) = recipe.get("base").and_then(Value::as_str) else { return Ok(own) }; + if depth >= MAX_BASE_DEPTH { + return Err(format!("`base` chain deeper than {MAX_BASE_DEPTH} cases")); + } + let base_dir = std::path::Path::new(dir).join(base).to_string_lossy().to_string(); + let base_script = read_json(&format!("{base_dir}/recipe.json")) + .and_then(|r| script_at(&base_dir, out, &r, depth + 1)) + .map_err(|e| format!("base {base}: {e}"))?; + let list = |v: &Value| v.get("commands").or(Some(v)).and_then(Value::as_array).cloned().unwrap_or_default(); + let mut commands = list(&base_script); + commands.extend(list(&own)); + Ok(json!({"commands": commands})) +} + +/// A scratch directory for one case's output files. +fn scratch(area: &str, name: &str) -> Result { + let d = std::env::temp_dir().join(format!("solidcraft-kernel-cases-{}", std::process::id())).join(format!("{area}-{name}")); + std::fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?; + Ok(d.to_string_lossy().to_string()) +} + +/// Chord tolerance of the mesh a `watertight` case is checked on (mm). +const MESH_TOL: f64 = 0.01; + +/// A mesh's edges used by one triangle only (open) and by more than two (over-shared). Vertices +/// closer than `weld` (mm) are one vertex: a mesh repeats a vertex for each face, and faces +/// meeting at an edge may place it a rounding error apart. +fn open_edges(positions: &[solidcore_record::Vec3], triangles: &[[u32; 3]], weld: f64) -> (usize, usize) { + use std::collections::HashMap; + let weld = if weld.is_finite() && weld > 0.0 { weld } else { 1e-4 }; + let cell = |p: &solidcore_record::Vec3| [p.x, p.y, p.z].map(|x| (x / weld).floor() as i64); + // Union-find over positions, joining each vertex with any within `weld` in the 27 cells round it. + let mut parent: Vec = (0..positions.len()).collect(); + fn find(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i) { + if p == i { + break; + } + let gp = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = gp; + } + i = p; + } + i + } + let mut grid: HashMap<[i64; 3], Vec> = HashMap::new(); + for (i, p) in positions.iter().enumerate() { + let c = cell(p); + for dx in -1..=1 { + for dy in -1..=1 { + for dz in -1..=1 { + let Some(near) = grid.get(&[c[0] + dx, c[1] + dy, c[2] + dz]) else { continue }; + for &j in near { + if positions.get(j).is_some_and(|q| q.dist(*p) <= weld) { + let (a, b) = (find(&mut parent, i), find(&mut parent, j)); + if let Some(slot) = parent.get_mut(a) { + *slot = b; + } + } + } + } + } + } + grid.entry(c).or_default().push(i); + } + let mut uses: HashMap<(usize, usize), usize> = HashMap::new(); + for t in triangles { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + let (a, b) = (find(&mut parent, a as usize), find(&mut parent, b as usize)); + if a != b { + *uses.entry((a.min(b), a.max(b))).or_default() += 1; + } + } + } + (uses.values().filter(|&&n| n == 1).count(), uses.values().filter(|&&n| n > 2).count()) +} + +/// An error that means "this kernel can't do it yet", not a wrong answer. +/// Stations along each seam the `continuity` check samples. +const SEAM_SAMPLES: usize = 65; +/// A seam is tangent (G1), and two seams meeting at a vertex turn there, past this angle (°). +const SEAM_ANGLE_DEG: f64 = 1.0; + +/// The `continuity` check's measure of `body`: over the tangent seams lying wholly within +/// `within` of `near`, the worst curvature jump (1/mm) at every station and at the stations at +/// least `clear` (mm, along the seam) from each vertex where two of those seams turn (a corner of +/// the patch's boundary, where its neighbours' own G1 seams end and no surface is G2 to both), +/// with how many seams and stations clear there were. An error where the seams can't be measured. +fn curvature_jumps(body: &solidcraft_engine::kernel::Body, near: [f64; 3], within: f64, clear: f64) -> Result { + use solidcore_record::Vec3; + let tol = + solidcraft_engine::kernel::ContinuityTolerances { gap_mm: 1e-3, angle_deg: SEAM_ANGLE_DEG, curvature_per_mm: 0.0, ..Default::default() }; + let report = solidcraft_engine::kernel::seam_diagnostics(body, &[], SEAM_SAMPLES, tol).map_err(|e| e.to_string())?; + let at = Vec3::new(near[0], near[1], near[2]); + let seams: Vec<_> = report + .seams + .iter() + .filter(|s| s.normal_angle_deg.value <= SEAM_ANGLE_DEG && s.points.len() >= 2 && s.points.iter().all(|p| p.dist(at) <= within)) + .collect(); + // Each seam's end directions, pointing into it. + let ends = |s: &solidcraft_engine::kernel::SeamReport| -> Option<[(Vec3, Vec3); 2]> { + let (p0, p1) = (*s.points.first()?, *s.points.last()?); + let (q0, q1) = (*s.points.get(1)?, *s.points.get(s.points.len() - 2)?); + Some([(p0, (q0 - p0).normalized()?), (p1, (q1 - p1).normalized()?)]) + }; + let all_ends: Vec<(Vec3, Vec3)> = seams.iter().filter_map(|s| ends(s)).flatten().collect(); + let weld = 1e-6 * within.max(1.0); + let cos = SEAM_ANGLE_DEG.to_radians().cos(); + // A vertex turns where another seam leaves it other than straight on. + let turns = |p: Vec3, d: Vec3| all_ends.iter().any(|(q, e)| q.dist(p) <= weld && (*e - d).len() > 1e-9 && -e.dot(d) < cos); + let (mut worst, mut worst_clear, mut stations) = (0.0f64, 0.0f64, 0usize); + for s in &seams { + let Some(e) = ends(s) else { continue }; + let turning: Vec = e.iter().filter(|(p, d)| turns(*p, *d)).map(|(p, _)| *p).collect(); + // Arc length along the seam to each station, from its start. + let mut along = vec![0.0f64; s.points.len()]; + for k in 1..s.points.len() { + along[k] = along[k - 1] + s.points[k].dist(s.points[k - 1]); + } + let length = along.last().copied().unwrap_or(0.0); + for (k, st) in s.stations.iter().enumerate() { + worst = worst.max(st.curvature_jump_per_mm); + let a = along.get(k).copied().unwrap_or(0.0); + let from_turn = turning.iter().map(|p| if p.dist(s.points[0]) <= weld { a } else { length - a }).fold(f64::INFINITY, f64::min); + if from_turn >= clear { + worst_clear = worst_clear.max(st.curvature_jump_per_mm); + stations += 1; + } + } + } + Ok(json!({"seams": seams.len(), "stations_clear": stations, "worst_per_mm": worst, "worst_clear_per_mm": worst_clear})) +} + +/// The seams a `continuity: {order, edges}` check measures on `b`, by edge index, with what +/// each lies between: `blend` (the default), every seam of a face a fillet or chamfer made (a +/// round, a chamfer face or a corner patch) with the faces either side of the edge it replaced, +/// and every seam of a corner patch with the rounds it joins: what the blend is built to meet. +/// Where two rounds meet without a patch, their seam is the input's (tangent only where the +/// rounded edges were) and is not one. `corner`, those of them on a corner patch. A list of +/// points `[[x,y,z], …]`, the edges nearest them, as Continuity Analysis picks them. An error for +/// anything else, or a point near no edge. +fn continuity_seams(b: &solidcraft_engine::doc::ModelBody, edges: &Value) -> Result, String> { + use solidcraft_engine::doc::naming::BlendSeamKind; + if let Some(points) = edges.as_array() { + let picks = points + .iter() + .map(|p| v3(p).map(|[x, y, z]| solidcraft_engine::kernel::EdgePick::Point(solidcore_record::Vec3::new(x, y, z)))) + .collect::>>() + .ok_or("continuity `edges` points must each be [x,y,z]")?; + let picked = solidcraft_engine::kernel::pick_edges(&b.body, &picks).map_err(|e| e.to_string())?; + return Ok(picked.into_iter().map(|e| (e, "picked")).collect()); + } + let all = solidcraft_engine::doc::naming::blend_seams(b).into_iter().filter(|s| s.kind == BlendSeamKind::Contact || s.corner); + let label = + |s: &solidcraft_engine::doc::naming::BlendSeam| (s.edge, if s.kind == BlendSeamKind::Blend { "with_blends" } else { "with_contact_faces" }); + match edges.as_str().unwrap_or("blend") { + "blend" => Ok(all.map(|s| label(&s)).collect()), + "corner" => Ok(all.filter(|s| s.corner).map(|s| label(&s)).collect()), + other => Err(format!("continuity `edges` must be \"blend\", \"corner\" or a list of points, not {other:?}")), + } +} + +/// The orders a case's `continuity` asks for: `{order, edges, exact}` for its `edges` seams, or +/// `seams: [{order, edges, exact}, ...]`, each read the same way, for seams that reach different +/// orders (`edges` points picking each). Nothing where it asks for no order (the curvature-jump +/// form, or none); an `order` that is not g0…g4 is an error. +fn continuity_wants(cont: &Value) -> Vec> { + fn one(w: &Value) -> Option> { + let order = w.get("order").filter(|o| !o.is_null())?; + let exact = w["exact"].as_bool().unwrap_or(false); + Some( + order + .as_str() + .and_then(solidcraft_engine::kernel::Continuity::parse) + .map(|o| (&w["edges"], o, exact)) + .ok_or_else(|| format!("continuity `order` {order} is not g0…g4")), + ) + } + match cont.get("seams").and_then(Value::as_array) { + Some(seams) => seams.iter().map(|w| one(w).unwrap_or_else(|| Err("a continuity seam with no `order`".to_owned()))).collect(), + None => one(cont).into_iter().collect(), + } +} + +/// The `continuity: {order, edges}` check of `b`: its `edges` seams measured as Continuity +/// Analysis (`inspect.continuity`) measures them, at its default stations and tolerances, and the +/// lowest order among them with the seam that has it (the worst: of those, the one whose first +/// failing metric is furthest past its tolerance), its faces' names and that metric's worst value. +/// `Ok((report, ok))`, `ok` where every seam meets `want` (`exact`: reaches it and no more). +fn continuity_order( + b: &solidcraft_engine::doc::ModelBody, + want: solidcraft_engine::kernel::Continuity, + edges: &Value, + exact: bool, +) -> Result<(Value, bool), String> { + use solidcraft_engine::kernel::{self as k, Continuity}; + let seams = continuity_seams(b, edges)?; + let selected: Vec = seams.iter().map(|s| s.0).collect(); + if selected.is_empty() { + return Ok((json!(format!("{}: no {edges} seams", b.name)), false)); + } + let tol = k::ContinuityTolerances::default(); + let report = k::seam_diagnostics(&b.body, &selected, k::DEFAULT_SAMPLES, tol).map_err(|e| e.to_string())?; + let limits = [tol.gap_mm, tol.angle_deg, tol.curvature_per_mm, tol.curvature_change_per_mm2, tol.curvature_change_rate_per_mm3]; + let metric = ["gap_mm", "normal_angle_deg", "curvature_jump_per_mm", "curvature_change_jump_per_mm2", "curvature_change_rate_jump_per_mm3"]; + // The metric a seam of this order fails first (none past G4), and how far past its tolerance. + let first_failing = |s: &k::SeamReport| -> Option<(usize, f64, k::SeamWorst)> { + let i = s.order.map_or(0, |o| o.order() + 1); + let w = [s.gap_mm, s.normal_angle_deg, s.curvature_jump_per_mm, s.curvature_change_jump_per_mm2, s.curvature_change_rate_jump_per_mm3]; + let (worst, limit) = (*w.get(i)?, *limits.get(i)?); + Some((i, if limit > 0.0 { worst.value / limit } else { f64::INFINITY }, worst)) + }; + let worst = report.seams.iter().min_by(|a, b| { + a.order.cmp(&b.order).then_with(|| { + let past = |s: &k::SeamReport| first_failing(s).map_or(0.0, |(_, r, _)| r); + past(b).total_cmp(&past(a)) + }) + }); + let edge_names = solidcraft_engine::doc::naming::edge_names(b); + let order_word = |o: Option| o.map_or("none (the faces do not meet)", Continuity::as_str); + // How many seams reach each order, by what the blend meets there. + let kind = |edge: usize| seams.iter().find(|s| s.0 == edge).map_or("picked", |s| s.1); + let mut orders = json!({}); + for s in &report.seams { + let n = &mut orders[kind(s.edge)][order_word(s.order)]; + *n = json!(n.as_u64().unwrap_or(0) + 1); + } + let mut got = json!({ + "body": b.name, "edges": if edges.is_array() { "picked" } else { edges.as_str().unwrap_or("blend") }, "seams": report.seams.len(), "unmeasured": report.unmeasured, "orders": orders, + }); + if let Some(s) = worst { + got["order"] = json!(order_word(s.order)); + got["worst_edge"] = json!({"edge": s.edge, "faces": edge_names.get(s.edge), "meets": kind(s.edge)}); + if let Some((i, _, w)) = first_failing(s) { + got["worst_edge"]["next_order_metric"] = + json!({"metric": metric.get(i), "value": w.value, "tolerance": limits.get(i), "at": w.at, "edge_fraction": w.edge_fraction}); + } + } + let ok = report.unmeasured == 0 + && !report.seams.is_empty() + && report.seams.iter().all(|s| s.order.is_some_and(|o| if exact { o == want } else { o >= want })); + Ok((got, ok)) +} + +/// Where `got` differs from `want`, a part of it: every key of a `want` object in `got` and +/// matching, an array element by element and as long, a whole number exactly, any other number +/// within `rel` of it (relative, at least 1 absolute), anything else equal. `None` where it +/// matches; else the path to the first difference with both values. +fn json_mismatch(got: &Value, want: &Value, rel: f64, abs: f64, path: &str) -> Option { + let differ = || Some(format!("{path}: got {got}, want {want}")); + match (got, want) { + (_, Value::Object(w)) => { + let Value::Object(g) = got else { return differ() }; + w.iter().find_map(|(k, wv)| match g.get(k) { + Some(gv) => json_mismatch(gv, wv, rel, abs, &format!("{path}.{k}")), + None => Some(format!("{path}.{k}: missing, want {wv}")), + }) + } + (_, Value::Array(w)) => { + let Value::Array(g) = got else { return differ() }; + if g.len() != w.len() { + return Some(format!("{path}: {} items, want {}", g.len(), w.len())); + } + g.iter().zip(w).enumerate().find_map(|(i, (gv, wv))| json_mismatch(gv, wv, rel, abs, &format!("{path}[{i}]"))) + } + (_, Value::Number(w)) if w.is_i64() || w.is_u64() => (got.as_f64() != w.as_f64()).then(differ).flatten(), + (_, Value::Number(w)) => { + let (g, w) = (got.as_f64(), w.as_f64().unwrap_or(f64::NAN)); + (!g.is_some_and(|g| g.is_finite() && (g - w).abs() <= (rel * w.abs().max(1.0)).max(abs))).then(differ).flatten() + } + _ => (got != want).then(differ).flatten(), + } +} + +/// The rows of a CSV text (RFC 4180: quoted fields may hold commas, quotes and line breaks) as +/// objects keyed by the header row; a field that reads as a number is one. +fn csv_rows(text: &str) -> Vec { + let mut records: Vec> = Vec::new(); + let (mut row, mut field, mut quoted, mut chars) = (Vec::new(), String::new(), false, text.chars().peekable()); + while let Some(c) = chars.next() { + match (c, quoted) { + ('"', true) if chars.peek() == Some(&'"') => { + chars.next(); + field.push('"'); + } + ('"', _) => quoted = !quoted, + (',', false) => row.push(std::mem::take(&mut field)), + ('\r', false) => {} + ('\n', false) => { + row.push(std::mem::take(&mut field)); + records.push(std::mem::take(&mut row)); + } + _ => field.push(c), + } + } + if !field.is_empty() || !row.is_empty() { + row.push(field); + records.push(row); + } + let Some((head, rows)) = records.split_first() else { return Vec::new() }; + rows.iter() + .map(|r| { + let cell = |v: &String| v.parse::().ok().filter(|x| x.is_finite()).map_or_else(|| json!(v), |x| json!(x)); + Value::Object(head.iter().cloned().zip(r.iter().map(cell)).collect()) + }) + .collect() +} + +/// Per layer of a DXF text's ENTITIES section, how many of each entity it has and the total +/// length of its curves (`length_mm`: lines, arcs, circles, ellipses and polylines; a spline makes +/// the layer's length null, as not measured): `{layer: {"LINE": n, …, "length_mm": l}}`. +fn dxf_layers(text: &str) -> Value { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let pairs: Vec<(&str, &str)> = lines.chunks(2).filter_map(|p| Some((*p.first()?, *p.get(1)?))).collect(); + let start = pairs.windows(2).position(|w| w[0] == ("0", "SECTION") && w[1] == ("2", "ENTITIES")).map_or(pairs.len(), |i| i + 2); + let mut layers = serde_json::Map::new(); + let mut i = start; + while let Some(&(code, kind)) = pairs.get(i) { + if code != "0" || kind == "ENDSEC" { + break; + } + let end = pairs.get(i + 1..).and_then(|r| r.iter().position(|p| p.0 == "0")).map_or(pairs.len(), |k| i + 1 + k); + let group = pairs.get(i + 1..end).unwrap_or(&[]); + let num = |c: &str| group.iter().find(|p| p.0 == c).and_then(|p| p.1.parse::().ok()).unwrap_or(0.0); + let all = |c: &str| group.iter().filter(|p| p.0 == c).filter_map(|p| p.1.parse::().ok()).collect::>(); + let layer = group.iter().find(|p| p.0 == "8").map_or("0", |p| p.1); + let length = match kind { + "LINE" => Some((num("11") - num("10")).hypot(num("21") - num("20"))), + "CIRCLE" => Some(std::f64::consts::TAU * num("40")), + "ARC" => Some(num("40") * (num("51") - num("50")).rem_euclid(360.0).to_radians()), + "LWPOLYLINE" => { + let mut pts: Vec<(f64, f64)> = all("10").into_iter().zip(all("20")).collect(); + if (num("70") as i64) & 1 == 1 + && let Some(&p) = pts.first() + { + pts.push(p); + } + Some(pts.windows(2).map(|w| (w[1].0 - w[0].0).hypot(w[1].1 - w[0].1)).sum()) + } + "ELLIPSE" => { + // Arc length of c + cos t·major + sin t·ratio·minor, t from 41 to 42, by Simpson's rule. + let (a, b) = (num("11").hypot(num("21")), num("11").hypot(num("21")) * num("40")); + let (t0, t1) = (num("41"), num("42")); + let sweep = if t1 > t0 { t1 - t0 } else { t1 - t0 + std::f64::consts::TAU }; + let n = 4096; + let speed = |t: f64| (a * t.sin()).hypot(b * t.cos()); + let h = sweep / n as f64; + let weight = |k: usize| match k { + 0 => 1.0, + k if k == n => 1.0, + k if k % 2 == 1 => 4.0, + _ => 2.0, + }; + let sum: f64 = (0..=n).map(|k| speed(t0 + k as f64 * h) * weight(k)).sum(); + Some(sum * h / 3.0) + } + _ => None, + }; + let entry = layers.entry(layer.to_string()).or_insert_with(|| json!({"length_mm": 0.0})); + entry[kind] = json!(entry[kind].as_u64().unwrap_or(0) + 1); + entry["length_mm"] = match (entry["length_mm"].as_f64(), length) { + (Some(l), Some(more)) => json!(l + more), + _ => Value::Null, + }; + i = end; + } + Value::Object(layers) +} + +/// The `files` check of the files a case wrote to `$OUT` (`out`): each `{path, json | csv | dxf}` +/// read and matched as [`json_mismatch`] does: `json` against the file's JSON, `csv` against its +/// rows ([`csv_rows`]), `dxf` against its layers ([`dxf_layers`]), a count there exact or an +/// inclusive range `[min, max]`. And the `results` check of the commands' own answers: each +/// `{step, pointer?, json, rel?, abs_mm?}`, the answer of the `step`th command (from 1, base +/// commands included), or its part at the JSON `pointer` (RFC 6901), matched against `json`, +/// a number within the entry's `rel` (or the case's) or its `abs_mm`. +fn output_checks(c: &mut Checks, want: &Value, out: &str, results: &[Value], rel: f64) { + for f in want["files"].as_array().into_iter().flatten() { + let path = f["path"].as_str().unwrap_or_default(); + let what = format!("file {path}"); + let text = match std::fs::read_to_string(std::path::Path::new(out).join(path)) { + Ok(t) => t, + Err(e) => { + c.push(&what, json!(e.to_string()), json!("written"), false); + continue; + } + }; + let (got, wanted) = if let Some(w) = f.get("json") { + (serde_json::from_str::(&text).unwrap_or_else(|e| json!(format!("not JSON: {e}"))), w.clone()) + } else if let Some(w) = f.get("csv") { + (Value::Array(csv_rows(&text)), w.clone()) + } else if let Some(w) = f.get("dxf") { + let layers = dxf_layers(&text); + // A count given as a range is in it: compare the count itself with the range's bounds. + let mut w = w.clone(); + let mut ranged = Vec::new(); + for (layer, kinds) in w.as_object_mut().into_iter().flatten() { + for (kind, n) in kinds.as_object_mut().into_iter().flatten() { + if let Some([lo, hi]) = n.as_array().and_then(|r| <[Value; 2]>::try_from(r.clone()).ok()) { + let g = layers[layer.as_str()][kind.as_str()].as_u64().unwrap_or(0); + ranged.push((format!("{layer}.{kind}"), g, lo.clone(), hi.clone())); + *n = json!(g); + } + } + } + for (k, g, lo, hi) in ranged { + let ok = lo.as_u64().is_some_and(|lo| g >= lo) && hi.as_u64().is_some_and(|hi| g <= hi); + c.push(&format!("{what} {k}"), json!(g), json!([lo, hi]), ok); + } + // An entity the case names but the layer lacks counts 0. + let mut got = layers; + for (layer, kinds) in w.as_object().into_iter().flatten() { + for kind in kinds.as_object().into_iter().flatten().map(|(k, _)| k) { + if got[layer.as_str()].get(kind.as_str()).is_none() && kind != "length_mm" { + got[layer.as_str()][kind.as_str()] = json!(0); + } + } + } + (got, w) + } else { + c.push(&what, json!(f), json!("json, csv or dxf"), false); + continue; + }; + let miss = json_mismatch(&got, &wanted, rel, 0.0, ""); + c.push(&what, json!(miss.clone().unwrap_or_else(|| "matches".into())), wanted, miss.is_none()); + } + for r in want["results"].as_array().into_iter().flatten() { + let step = r["step"].as_u64().unwrap_or(0); + let pointer = r["pointer"].as_str().unwrap_or(""); + let what = format!("result of step {step}{pointer}"); + let (rel, abs) = (r["rel"].as_f64().unwrap_or(rel), r["abs_mm"].as_f64().unwrap_or(0.0)); + let got = step.checked_sub(1).and_then(|i| results.get(i as usize)); + let miss = match got.map(|g| g.pointer(pointer)) { + Some(Some(g)) => json_mismatch(g, &r["json"], rel, abs, ""), + Some(None) => Some(format!("no {pointer} in step {step}'s answer")), + None => Some(format!("no step {step} of {}", results.len())), + }; + c.push(&what, json!(miss.clone().unwrap_or_else(|| "matches".into())), r["json"].clone(), miss.is_none()); + } +} + +/// The word a `surface_types` check names a face's surface by, as the record holds it: an +/// analytic kind, `ball_patch` (a corner's patch on a sphere), `bspline` (a B-spline or NURBS +/// surface) or `revolution` (a revolved curve). +fn surface_word(s: &solidcore_record::brep::Surface) -> &'static str { + use solidcore_record::brep::Surface as S; + match s { + S::Plane { .. } | S::PlaneThrough { .. } => "plane", + S::Cylinder { .. } => "cylinder", + S::Cone { .. } => "cone", + S::Sphere { .. } => "sphere", + S::BallPatch { .. } => "ball_patch", + S::Torus { .. } => "torus", + S::Spline { .. } | S::RationalSpline { .. } => "bspline", + S::PlacedRevolution { .. } => "revolution", + } +} + +/// A B-spline face's two directions as `[degree, spans]` (spans: the distinct knot intervals of +/// the modelled range), the lower first, so a surface parameterised the other way round reads the +/// same. `None` for a surface that is not a B-spline. +fn spline_shape(s: &solidcore_record::brep::Surface) -> Option<[[u64; 2]; 2]> { + use solidcore_record::brep::Surface as S; + let (u, v, nu, nv) = match s { + S::Spline { u_knots, v_knots, points } => (u_knots, v_knots, points.len(), points.first().map_or(0, Vec::len)), + S::RationalSpline { u_knots, v_knots, homogeneous } => (u_knots, v_knots, homogeneous.len(), homogeneous.first().map_or(0, Vec::len)), + _ => return None, + }; + let dir = |k: &[f64], n: usize| -> Option<[u64; 2]> { + let p = k.len().checked_sub(n + 1)?; + let inner = k.get(p..=n)?; + let spans = inner.windows(2).filter(|w| w[1] > w[0]).count(); + Some([p as u64, spans as u64]) + }; + let (a, b) = (dir(u, nu)?, dir(v, nv)?); + Some(if a <= b { [a, b] } else { [b, a] }) +} + +/// The `splines` check: every B-spline face of the bodies matches one entry of `want` and every +/// entry one face (`{degree: [p, q], spans?: [m, n]}`, in either order of directions; without +/// `spans` only the degrees are graded). `Ok(got)` with what the faces are, `ok` when they match. +fn splines_match(faces: &[[[u64; 2]; 2]], want: &Value) -> Result<(Value, bool), String> { + let list = want.as_array().ok_or("`splines` must be a list of {degree: [p, q], spans?: [m, n]}")?; + let pair = |v: &Value| -> Option<[u64; 2]> { Some([v.get(0)?.as_u64()?, v.get(1)?.as_u64()?]) }; + let mut left: Vec<[[u64; 2]; 2]> = faces.to_vec(); + let mut ok = true; + for w in list { + let degree = w.get("degree").and_then(pair).ok_or("each `splines` entry needs `degree: [p, q]`")?; + let spans = match w.get("spans").filter(|s| !s.is_null()) { + Some(s) => Some(pair(s).ok_or("`spans` must be [m, n]")?), + None => None, + }; + let fits = |f: &[[u64; 2]; 2]| { + let mine = |d: [u64; 2], s: Option<[u64; 2]>| f[0][0] == d[0] && f[1][0] == d[1] && s.is_none_or(|s| f[0][1] == s[0] && f[1][1] == s[1]); + mine(degree, spans) || mine([degree[1], degree[0]], spans.map(|s| [s[1], s[0]])) + }; + match left.iter().position(fits) { + Some(i) => { + left.remove(i); + } + None => ok = false, + } + } + let got: Vec = faces.iter().map(|f| json!({"degree": [f[0][0], f[1][0]], "spans": [f[0][1], f[1][1]]})).collect(); + Ok((json!(got), ok && left.is_empty())) +} + +/// Largest sine of the angle between a construction's direction (an axis's, a plane's normal) +/// and the case's: either way along it. +const CONSTRUCT_DIR_TOL: f64 = 1e-6; + +/// The `construction` check: each named construction plane, axis or point, as the timeline +/// evaluated it, is the case's: a point within `tol` (mm); an axis whose direction is parallel to +/// `dir` (either way) and whose line passes within `tol` of `through`; a plane whose normal is +/// parallel to `normal` (either way) and which passes within `tol` of `through`. An axis or plane +/// is graded as the line or plane it is, never by the origin it happens to keep. +fn check_construction(s: &solidcraft_engine::Session, want: &Value, tol: f64, c: &mut Checks) { + use solidcore_record::Vec3; + use solidcraft_engine::view::{construction_axes, construction_planes, construction_points}; + let Some(named) = want.as_object() else { + c.push("construction", json!("`construction` must map names to {point} | {axis} | {plane}"), json!("an object"), false); + return; + }; + let vec = |v: &Value| v3(v).map(Vec3::from); + let parallel = |a: Vec3, b: Vec3| a.normalized().zip(b.normalized()).is_some_and(|(a, b)| a.cross(b).len() <= CONSTRUCT_DIR_TOL); + for (name, w) in named { + let what = format!("construction {name}"); + let (got, ok) = if let Some(p) = w.get("point").and_then(vec) { + match construction_points(s).into_iter().find(|x| &x.1 == name) { + Some((_, _, q)) => (json!({"point": q}), q.dist(p) <= tol), + None => (json!("no such construction point"), false), + } + } else if let Some((through, dir)) = w.get("axis").and_then(|a| vec(&a["through"]).zip(vec(&a["dir"]))) { + match construction_axes(s).into_iter().find(|x| &x.1 == name) { + Some((_, _, o, d)) => { + let off = d.normalized().map(|u| (through - o) - u * (through - o).dot(u)).map_or(f64::INFINITY, Vec3::len); + (json!({"axis": {"origin": o, "dir": d, "through_off_mm": off}}), parallel(d, dir) && off <= tol) + } + None => (json!("no such construction axis"), false), + } + } else if let Some((through, normal)) = w.get("plane").and_then(|p| vec(&p["through"]).zip(vec(&p["normal"]))) { + match construction_planes(s).into_iter().find(|x| &x.1 == name) { + Some((_, _, pl)) => { + let n = pl.normal(); + let off = n.normalized().map_or(f64::INFINITY, |u| (through - pl.origin).dot(u).abs()); + (json!({"plane": {"origin": pl.origin, "normal": n, "through_off_mm": off}}), parallel(n, normal) && off <= tol) + } + None => (json!("no such construction plane"), false), + } + } else { + (json!("give {point: [x,y,z]}, {axis: {through, dir}} or {plane: {through, normal}}"), false) + }; + c.push(&what, got, w.clone(), ok); + } +} + +fn unsupported(e: &str) -> bool { + e.contains("not supported yet") +} + +/// A panic caught by the engine or the kernel guard. +fn crashed(e: &str) -> bool { + e.contains("internal error") || e.contains("panicked") +} + +fn case_name(dir: &str) -> (String, String) { + let p = std::path::Path::new(dir); + let name = |q: Option<&std::path::Path>| q.and_then(|q| q.file_name()).map(|x| x.to_string_lossy().to_string()).unwrap_or_default(); + (name(p.parent()), name(Some(p))) +} + +/// The area a polygon of `[x, y]` points encloses (shoelace), unsigned. +fn polygon_area(points: &Value) -> f64 { + let pts: Vec<(f64, f64)> = points.as_array().into_iter().flatten().filter_map(|p| Some((p.get(0)?.as_f64()?, p.get(1)?.as_f64()?))).collect(); + pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| a.0 * b.1 - b.0 * a.1).sum::().abs() / 2.0 +} + +/// The `flat_pattern` check, against the script's last `sheet.flat_pattern` result: `size_mm` +/// ([w, h] of the outline), `area_mm2` (the outline loops' area less the cut-outs') and +/// `bend_lines` ([[x, y], [x, y]] each, the bends' centre lines in flat coordinates, every one +/// matched to its own one of the result's, either way round, and as many of them). +fn flat_pattern_checks(c: &mut Checks, want: &Value, results: &[Value], rel: f64, abs: f64) { + let Some(got) = results.iter().rev().find(|r| r.get("flat_size_mm").is_some()) else { + c.push("flat_pattern", json!("no sheet.flat_pattern result"), want.clone(), false); + return; + }; + if let Some(w) = want.get("size_mm").and_then(Value::as_array) { + let g = &got["flat_size_mm"]; + let ok = w.len() == 2 + && (0..2).all(|k| match (g.get(k).and_then(Value::as_f64), w.get(k).and_then(Value::as_f64)) { + (Some(g), Some(w)) => (g - w).abs() <= abs, + _ => false, + }); + c.push("flat_pattern.size_mm", json!([g.get(0), g.get(1)]), json!(w), ok); + } + if let Some(w) = want.get("area_mm2").and_then(Value::as_f64) { + let loops = |k: &str| got[k].as_array().into_iter().flatten().map(polygon_area).sum::(); + c.rel("flat_pattern.area_mm2", loops("outline") - loops("cutouts"), Some(w), rel); + } + if let Some(w) = want.get("bend_lines").and_then(Value::as_array) { + let line = |v: &Value| -> Option<[f64; 4]> { + let (a, b) = (v.get(0)?, v.get(1)?); + Some([a.get(0)?.as_f64()?, a.get(1)?.as_f64()?, b.get(0)?.as_f64()?, b.get(1)?.as_f64()?]) + }; + let mut left: Vec<[f64; 4]> = got["bends"].as_array().into_iter().flatten().filter_map(|b| line(&json!([b["start"], b["end"]]))).collect(); + let got_lines = json!(left.iter().map(|l| [[l[0], l[1]], [l[2], l[3]]]).collect::>()); + let near = |p: [f64; 4], q: [f64; 4]| (0..4).all(|k| (p[k] - q[k]).abs() <= abs); + let mut ok = left.len() == w.len(); + for l in w.iter().map(line) { + let found = l.and_then(|l| left.iter().position(|g| near(*g, l) || near(*g, [l[2], l[3], l[0], l[1]]))); + match found { + Some(i) => { + left.swap_remove(i); + } + None => ok = false, + } + } + c.push("flat_pattern.bend_lines", got_lines, json!(w), ok); + } +} + +/// [`check_case_in`], and with `export` the case's corpus entry written under it +/// ([`crate::kernel_cases_export`]). +fn check_case( + dir: &str, + dumps: Option<&std::path::Path>, + validation: solidcraft_engine::kernel::Validation, + export: Option<&std::path::Path>, +) -> Value { + let mut capture = export.map(|_| crate::kernel_cases_export::Capture::default()); + let out = check_case_in(dir, dumps, validation, capture.as_mut()); + if let (Some(root), Some(capture)) = (export, capture) + && let Err(e) = crate::kernel_cases_export::write(root, dir, &out, capture) + { + let mut out = out; + out["export_error"] = json!(e); + return out; + } + out +} + +/// One case run and graded. With `capture`, the kernel operations its commands make are traced +/// and kept there with the bodies the case ends with. +fn check_case_in( + dir: &str, + dumps: Option<&std::path::Path>, + validation: solidcraft_engine::kernel::Validation, + mut capture: Option<&mut crate::kernel_cases_export::Capture>, +) -> Value { + let (area, name) = case_name(dir); + let mut out = json!({"case": name, "area": area, "kernel": kernel()}); + let want = match read_json(&format!("{dir}/expected.json")) { + Ok(w) => w, + Err(e) => { + out["status"] = json!("fail"); + out["error"] = json!(format!("expected.json: {e}")); + return out; + } + }; + out["sources"] = want["sources"].clone(); + // A capability SolidCraft doesn't have yet (no command or parameter for it): recorded as a + // case so the gap is visible, never run against a stand-in. + if let Some(missing) = want["missing"].as_str() { + out["status"] = json!("unsupported"); + out["error"] = json!(missing); + return out; + } + let scratch_dir = match scratch(&area, &name) { + Ok(o) => o, + Err(e) => { + out["status"] = json!("fail"); + out["error"] = json!(e); + return out; + } + }; + let commands = match read_json(&format!("{dir}/recipe.json")).and_then(|r| script(dir, &scratch_dir, &r)) { + Ok(s) => s, + Err(e) => { + out["status"] = json!("fail"); + out["error"] = json!(format!("recipe.json: {e}")); + return out; + } + }; + // `refused`: only a clean refusal is right; `solid_or_refused`: a clean refusal, or a result + // graded as usual (where the geometry has no manifold answer, such as bodies touching along a + // curve only). + let outcome = want["outcome"].as_str().unwrap_or("solid"); + let refused = outcome == "refused"; + let may_refuse = refused || outcome == "solid_or_refused"; + // The kernel calls that fail in this case leave their inputs in its own folder. + if let Some(root) = dumps { + let folder = root.join(format!("{area}-{name}")); + if let Err(e) = std::fs::create_dir_all(&folder) { + out["status"] = json!("fail"); + out["error"] = json!(format!("--dumps: {}: {e}", folder.display())); + return out; + } + solidcraft_engine::kernel::smlib_dump_dir(Some(&folder)); + } + let mut s = solidcraft_engine::Session::default(); + s.set_validation(validation); + let clock = std::time::Instant::now(); + if capture.is_some() { + solidcraft_engine::kernel::smlib_trace::start(); + } + let ran = s.run_script(&commands); + // The trace ends with the commands: grading reads the bodies through the kernel too. + if let Some(c) = &mut capture { + c.events = solidcraft_engine::kernel::smlib_trace::finish(); + c.ran = Some(match &ran { + Ok(_) => s.world_state().map(|w| w.bodies.iter().map(|b| (b.name.clone(), b.body.record().clone())).collect()).map_err(|e| e.to_string()), + Err(e) => Err(e.to_string()), + }); + } + // The commands' own time, without process start or grading: the ladder's timing golden. + out["seconds"] = json!(clock.elapsed().as_secs_f64()); + let answers = match (ran, may_refuse) { + (Err(e), _) if crashed(&e.to_string()) => { + out["status"] = json!("crash"); + out["error"] = json!(e.to_string()); + return out; + } + (Err(e), true) => { + // The right answer is a clean refusal, for the reason the case gives: a `refused` + // case names it (`refusal`, a part of the message), so a failure for another reason + // (an SMLib status) is not taken for it. + let e = e.to_string(); + out["refused_with"] = json!(e); + match want["refusal"].as_str() { + Some(why) if !e.contains(why) => { + out["status"] = json!("fail"); + out["error"] = json!(format!("refused, but not because {why:?}: {e}")); + } + None if refused => { + out["status"] = json!("fail"); + out["error"] = json!(format!("refused ({e}), but expected.json gives no `refusal`: the reason it must be refused for")); + } + _ => out["status"] = json!("pass"), + } + return out; + } + (Err(e), false) => { + let e = e.to_string(); + out["status"] = json!(if unsupported(&e) { "unsupported" } else { "fail" }); + out["error"] = json!(e); + return out; + } + (Ok(_), true) if refused => { + out["status"] = json!("fail"); + out["error"] = json!("succeeded where the case expects a refusal"); + return out; + } + (Ok(r), _) => r, + }; + + // Every body in the world, imported components included. + let world = match s.world_state() { + Ok(w) => w, + Err(e) => { + out["status"] = json!("fail"); + out["error"] = json!(e.to_string()); + return out; + } + }; + let mut bodies = Vec::new(); + let mut c = Checks { list: Vec::new(), pass: true }; + let want_valid = want["valid"].as_bool().unwrap_or(true); + // Shells: the total where the case gives it (a body with a void, or several lumps in one + // body), else one per body. + let want_shells = want["shells"].as_u64(); + let mut shells = 0u64; + // What the faces lie on and the edges only one face uses, over every body, as the records + // hold them: for `surface_types`, `splines` and `boundary_edges`. + let (mut kinds, mut spline_faces, mut boundary) = (std::collections::BTreeSet::new(), Vec::new(), 0u64); + for b in &world.bodies { + let record = b.body.record(); + for f in &record.faces { + kinds.insert(surface_word(&f.surface)); + spline_faces.extend(spline_shape(&f.surface)); + } + boundary += record.edges.iter().filter(|e| e.uses.len() == 1).count() as u64; + } + for b in &world.bodies { + let m = match solidcraft_engine::kernel::measure(&b.body) { + Ok(m) => m, + Err(e) => { + c.push("measure", json!(format!("{}: {e}", b.name)), json!("measurable"), false); + continue; + } + }; + bodies.push(json!({ + "volume_mm3": m.volume, "area_mm2": m.area, "center_of_mass": m.centroid, + "bbox": {"min": m.bbox.min, "max": m.bbox.max}, + "faces": m.merged.faces, "edges": m.merged.edges, "vertices": m.merged.vertices, + })); + shells += m.shells as u64; + if want["watertight"].as_bool() == Some(true) { + let tol = want["tolerance"]["mesh_mm"].as_f64().unwrap_or(MESH_TOL); + let (open, over) = match b.body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(tol)) { + Ok(mesh) => open_edges(&mesh.positions, &mesh.triangles, want["tolerance"]["weld_mm"].as_f64().unwrap_or(1e-4)), + Err(e) => { + c.push("watertight", json!(format!("{}: {e}", b.name)), json!("no open edges"), false); + continue; + } + }; + c.push( + "watertight", + json!(format!("{}: {open} open, {over} over-shared mesh edges", b.name)), + json!("no open edges"), + open == 0 && over == 0, + ); + } + // The order every blend seam reaches, as Continuity Analysis measures it. + for wanted in continuity_wants(&want["continuity"]) { + match wanted { + Ok((edges, o, exact)) => { + let which = if edges.is_array() { "picked" } else { edges.as_str().unwrap_or("blend") }; + let need = format!("{} {} at every {which} seam", if exact { "exactly" } else { ">=" }, o.as_str()); + match continuity_order(b, o, edges, exact) { + Ok((got, ok)) => c.push("continuity_order", got, json!(need), ok), + Err(e) => c.push("continuity_order", json!(format!("{}: {e}", b.name)), json!(need), false), + } + } + Err(e) => c.push("continuity_order", json!(e), json!("an order"), false), + } + } + // Curvature continuity across the seams round a point: the worst jump clear of the + // seams' turns must be within the case's bound. + if let Some(cont) = want.get("continuity").filter(|c| !c.is_null() && c.get("order").is_none() && c.get("seams").is_none()) { + let (near, within, clear, bound) = + (v3(&cont["near"]), cont["within_mm"].as_f64(), cont["clear_mm"].as_f64(), cont["curvature_jump_per_mm"].as_f64()); + match (near, within, clear, bound) { + (Some(near), Some(within), Some(clear), Some(bound)) => match curvature_jumps(&b.body, near, within, clear) { + Ok(got) => { + let ok = got["seams"].as_u64().unwrap_or(0) > 0 + && got["stations_clear"].as_u64().unwrap_or(0) > 0 + && got["worst_clear_per_mm"].as_f64().is_some_and(|w| w <= bound); + c.push("curvature_jump", got, json!({"worst_clear_per_mm": format!("<= {bound}")}), ok); + } + Err(e) => c.push("curvature_jump", json!(format!("{}: {e}", b.name)), json!("measurable"), false), + }, + _ => c.push("curvature_jump", json!("continuity needs near, within_mm, clear_mm and curvature_jump_per_mm"), json!("a bound"), false), + } + } + if want_valid { + // Closed shells, and every validity check this build has. + if want_shells.is_none() { + c.push("shells", json!(format!("{}: {}", b.name, m.shells)), json!(1), m.shells == 1); + } + let v = solidcraft_engine::kernel::validity(&b.body); + c.push("record_valid", json!(v.record.clone().err().unwrap_or_else(|| "ok".into())), json!("ok"), v.record.is_ok()); + match &v.smlib { + Some(solidcraft_engine::kernel::SmlibCheck::Valid) => c.push("smlib_check", json!("ok"), json!("ok"), true), + Some(solidcraft_engine::kernel::SmlibCheck::Invalid(e)) => c.push("smlib_check", json!(e), json!("ok"), false), + // No verdict: the record can't be built in SMLib yet. Shown, not graded. + Some(solidcraft_engine::kernel::SmlibCheck::NotSupported(e)) => { + c.push("smlib_check", json!(format!("no verdict: {e}")), json!("ok"), true) + } + None => {} + } + } + } + let got = totals(&json!({"bodies": bodies})); + let (edges, vertices): (u64, u64) = + bodies.iter().fold((0, 0), |(e, v), b| (e + b["edges"].as_u64().unwrap_or(0), v + b["vertices"].as_u64().unwrap_or(0))); + // What the kernel made, graded or not: the ladder's golden records it per kernel. + out["measured"] = json!({ + "body_count": got.body_count, "faces": got.faces, "edges": edges, "vertices": vertices, + "volume_mm3": got.volume, "area_mm2": got.area, + }); + let has = |k: &str| want.get(k).is_some_and(|v| !v.is_null()); + let rel = want["tolerance"]["rel"].as_f64().unwrap_or(REL_TOL); + let diag = |b: ([f64; 3], [f64; 3])| ((b.1[0] - b.0[0]).powi(2) + (b.1[1] - b.0[1]).powi(2) + (b.1[2] - b.0[2]).powi(2)).sqrt(); + let want_bbox = v3(&want["bbox"]["min"]).zip(v3(&want["bbox"]["max"])); + let abs = want["tolerance"]["abs_mm"].as_f64().unwrap_or_else(|| ABS_FRAC * want_bbox.map(diag).unwrap_or_else(|| diag(got.bbox)).max(1.0)); + // A count is exact, or an inclusive range `[min, max]` where the geometry only bounds it. + let count = |c: &mut Checks, k: &str, g: u64| { + if has(k) { + let ok = match want[k].as_array() { + Some(r) => r.first().and_then(Value::as_u64).is_some_and(|lo| g >= lo) && r.get(1).and_then(Value::as_u64).is_some_and(|hi| g <= hi), + None => want[k].as_u64() == Some(g), + }; + c.push(k, json!(g), want[k].clone(), ok); + } + }; + count(&mut c, "body_count", got.body_count as u64); + count(&mut c, "shells", shells); + count(&mut c, "faces", got.faces); + count(&mut c, "edges", edges); + count(&mut c, "vertices", vertices); + // A measure is a value within `rel`, or an inclusive range `[min, max]` where analysis only + // bounds it (a cut removes at most its tool's volume). + let measure = |c: &mut Checks, k: &str, g: f64| { + if has(k) { + match want[k].as_array() { + Some(r) => c.push(k, json!(g), want[k].clone(), within(r, g)), + None => c.rel(k, g, want[k].as_f64(), rel), + } + } + }; + measure(&mut c, "volume_mm3", got.volume); + measure(&mut c, "area_mm2", got.area); + if has("center_of_mass") { + c.vec("center_of_mass", got.com, v3(&want["center_of_mass"]), abs); + } + if has("bbox") { + c.vec("bbox.min", got.bbox.0, want_bbox.map(|b| b.0), abs); + c.vec("bbox.max", got.bbox.1, want_bbox.map(|b| b.1), abs); + } + output_checks(&mut c, &want, &scratch_dir, &answers, rel); + count(&mut c, "boundary_edges", boundary); + if has("surface_types") { + // The set of surface kinds the faces lie on, exactly: none missing, none extra. + let want_kinds: std::collections::BTreeSet<&str> = want["surface_types"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let ok = want_kinds == kinds.iter().copied().collect(); + c.push("surface_types", json!(kinds), want["surface_types"].clone(), ok); + } + if has("splines") { + match splines_match(&spline_faces, &want["splines"]) { + Ok((got, ok)) => c.push("splines", got, want["splines"].clone(), ok), + Err(e) => c.push("splines", json!(e), want["splines"].clone(), false), + } + } + // With no body and no `bbox` the diagonal is not finite: positions then take ABS_FRAC of 1 mm. + let pos_tol = if abs.is_finite() { abs } else { ABS_FRAC }; + if has("construction") { + check_construction(&s, &want["construction"], pos_tol, &mut c); + } + if has("flat_pattern") { + flat_pattern_checks(&mut c, &want["flat_pattern"], &answers, rel, abs); + } + out["status"] = json!(if c.pass { "pass" } else { "fail" }); + out["checks"] = json!(c.list); + out +} + +fn report(args: &[String], results: &[Value]) { + if args.iter().any(|a| a == "--json") { + println!("{}", serde_json::to_string_pretty(&Value::Array(results.to_vec())).unwrap_or_default()); + return; + } + for r in results { + let detail: Vec = r["checks"] + .as_array() + .into_iter() + .flatten() + .filter(|c| !c["ok"].as_bool().unwrap_or(false)) + .map(|c| format!("{} got {} want {}", c["check"].as_str().unwrap_or(""), c["got"], c["want"])) + .collect(); + let err = r["error"].as_str().map(|e| format!(" ({e})")).unwrap_or_default(); + println!( + "{} {}/{} [{}]{err}{}", + r["status"].as_str().unwrap_or("?").to_uppercase(), + r["area"].as_str().unwrap_or(""), + r["case"].as_str().unwrap_or(""), + r["kernel"].as_str().unwrap_or(""), + if detail.is_empty() { String::new() } else { format!(": {}", detail.join("; ")) } + ); + } +} + +pub fn run(args: &[String]) -> Result<(), String> { + let dirs: Vec<&String> = args.iter().filter(|a| !a.starts_with("--")).collect(); + if dirs.is_empty() { + return Err("kernel-cases: give one or more case directories (each with recipe.json and expected.json)".into()); + } + // `--dumps=DIR`: each case's failing SMLib calls leave their inputs in DIR/-. + let dumps = args.iter().find_map(|a| a.strip_prefix("--dumps=")).map(std::path::PathBuf::from); + if dumps.as_ref().is_some_and(|d| d.as_os_str().is_empty()) { + return Err("kernel-cases: --dumps= needs a folder".into()); + } + // `--validation=MODE`: the cases' features are checked under MODE (each_step, each_feature, + // off; default each_feature, the app's default). + let validation = match args.iter().find_map(|a| a.strip_prefix("--validation=")) { + Some(m) => solidcraft_engine::kernel::Validation::parse(m) + .ok_or_else(|| format!("kernel-cases: --validation= must be each_step, each_feature or off, not `{m}`"))?, + None => solidcraft_engine::kernel::Validation::default(), + }; + // `--export=DIR`: each case's kernel operations, their input records and its expected values + // go to DIR//.json, the corpus for solidcore's rig. + let export = args.iter().find_map(|a| a.strip_prefix("--export=")).map(std::path::PathBuf::from); + if export.as_ref().is_some_and(|d| d.as_os_str().is_empty()) { + return Err("kernel-cases: --export= needs a folder".into()); + } + let results: Vec = dirs.iter().map(|d| check_case(d, dumps.as_deref(), validation, export.as_deref())).collect(); + if dumps.is_some() { + solidcraft_engine::kernel::smlib_dump_dir(None); + } + report(args, &results); + let bad = results.iter().filter(|r| matches!(r["status"].as_str(), Some("fail" | "crash"))).count(); + if bad > 0 { Err(format!("{bad} kernel case(s) failed")) } else { Ok(()) } +} + +/// `g` lies in the inclusive range `[min, max]`; a range without both ends holds nothing. +fn within(range: &[Value], g: f64) -> bool { + match (range.first().and_then(Value::as_f64), range.get(1).and_then(Value::as_f64), range.len()) { + (Some(lo), Some(hi), 2) => lo <= g && g <= hi, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use std::f64::consts::PI; + + use super::*; + + fn case_dir(root: &std::path::Path, name: &str, recipe: &Value) -> String { + let d = root.join(name); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("recipe.json"), recipe.to_string()).unwrap(); + d.to_string_lossy().to_string() + } + + #[test] + fn base_commands_run_first_through_the_chain() { + let root = std::env::temp_dir().join(format!("kernel-cases-base-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + case_dir(&root, "a", &json!({"commands": [{"command": "a", "params": {"file": "$OUT/a.step"}}]})); + case_dir(&root, "b", &json!({"base": "../a", "commands": [{"command": "b"}]})); + let c = case_dir(&root, "c", &json!({"base": "../b", "commands": [{"command": "c", "params": {"file": "$CASE/x"}}]})); + let r = read_json(&format!("{c}/recipe.json")).unwrap(); + let s = script(&c, "/scratch", &r).unwrap(); + let ids: Vec<&str> = s["commands"].as_array().unwrap().iter().map(|c| c["command"].as_str().unwrap()).collect(); + assert_eq!(ids, ["a", "b", "c"]); + assert_eq!(s["commands"][2]["params"]["file"], json!(format!("{c}/x"))); + // `$OUT` is the running case's scratch directory, in its bases too. + assert_eq!(s["commands"][0]["params"]["file"], json!("/scratch/a.step")); + let _ = std::fs::remove_dir_all(&root); + } + + /// A bicubic face of 4 × 3 spans and a bilinear one of one span: degrees and spans graded in + /// either order of directions, spans only where given, and every face must be accounted for. + #[test] + fn splines_match_degrees_and_spans_in_either_order() { + use solidcore_record::brep::Surface; + let knots = |p: usize, spans: usize| -> Vec { + let mut k = vec![0.0; p + 1]; + k.extend((1..spans).map(|i| i as f64)); + k.extend(vec![spans as f64; p + 1]); + k + }; + let face = |pu: usize, su: usize, pv: usize, sv: usize| Surface::Spline { + u_knots: knots(pu, su), + v_knots: knots(pv, sv), + points: vec![vec![[0.0; 3]; pv + sv]; pu + su], + }; + let faces: Vec<_> = [face(3, 4, 3, 3), face(1, 1, 1, 1)].iter().filter_map(spline_shape).collect(); + assert_eq!(faces[0], [[3, 3], [3, 4]]); + let ok = |w: Value| splines_match(&faces, &w).unwrap().1; + assert!(ok(json!([{"degree": [1, 1], "spans": [1, 1]}, {"degree": [3, 3], "spans": [4, 3]}]))); + assert!(ok(json!([{"degree": [3, 3]}, {"degree": [1, 1]}]))); + assert!(!ok(json!([{"degree": [3, 3], "spans": [4, 4]}, {"degree": [1, 1]}])), "wrong spans"); + assert!(!ok(json!([{"degree": [3, 3]}])), "a face left over"); + assert!(!ok(json!([{"degree": [3, 3]}, {"degree": [1, 1]}, {"degree": [1, 1]}])), "an entry with no face"); + assert!(splines_match(&faces, &json!([{"spans": [1, 1]}])).is_err()); + assert_eq!(spline_shape(&Surface::Plane { origin: [0.0; 3], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] }), None); + assert_eq!(surface_word(&face(1, 1, 1, 1)), "bspline"); + } + + #[test] + fn a_measure_range_holds_its_ends_and_nothing_outside() { + let r = [json!(22500.0), json!(24000.0)]; + assert!(within(&r, 22500.0) && within(&r, 24000.0) && within(&r, 23000.0)); + assert!(!within(&r, 22499.9) && !within(&r, 24000.1)); + assert!(!within(&[json!(1.0)], 1.0), "one end is no range"); + assert!(!within(&[json!(1.0), json!(2.0), json!(3.0)], 1.5), "three ends are no range"); + } + + #[test] + fn json_parts_match_within_tolerance_and_whole_numbers_exactly() { + let got = json!({"bends": [{"angle_deg": 90.00001, "direction": "up", "count": 3}], "extra": 1}); + assert_eq!(json_mismatch(&got, &json!({"bends": [{"angle_deg": 90.0, "direction": "up"}]}), 1e-3, 0.0, ""), None); + assert!(json_mismatch(&got, &json!({"bends": [{"count": 4}]}), 1e-3, 0.0, "").is_some_and(|m| m.contains(".bends[0].count"))); + assert!(json_mismatch(&got, &json!({"bends": []}), 1e-3, 0.0, "").is_some_and(|m| m.contains("1 items, want 0"))); + assert!(json_mismatch(&got, &json!({"missing": 1}), 1e-3, 0.0, "").is_some_and(|m| m.contains("missing"))); + assert!(json_mismatch(&got, &json!({"bends": [{"direction": "down"}]}), 1e-3, 0.0, "").is_some()); + } + + #[test] + fn csv_rows_are_keyed_by_the_header_and_read_quoted_fields() { + let rows = csv_rows("body,angle_deg,note\r\n\"a, \"\"b\"\"\",90.5,x\r\n\"c\",180,\r\n"); + assert_eq!(rows, vec![json!({"body": "a, \"b\"", "angle_deg": 90.5, "note": "x"}), json!({"body": "c", "angle_deg": 180.0, "note": ""})]); + } + + #[test] + fn dxf_layers_count_entities_and_measure_their_length() { + let pair = |c: &str, v: &str| format!("{c}\n{v}\n"); + let mut t = String::new(); + // A circle in the BLOCKS section is not an entity of the drawing. + for (c, v) in [("0", "SECTION"), ("2", "BLOCKS"), ("0", "CIRCLE"), ("8", "CUT"), ("40", "9"), ("0", "ENDSEC")] { + t += &pair(c, v); + } + t += &pair("0", "SECTION"); + t += &pair("2", "ENTITIES"); + for e in [ + vec![("0", "LINE"), ("8", "OUTLINE"), ("10", "0"), ("20", "0"), ("11", "3"), ("21", "4")], + vec![("0", "ARC"), ("8", "OUTLINE"), ("10", "0"), ("20", "0"), ("40", "2"), ("50", "270"), ("51", "0")], + vec![("0", "CIRCLE"), ("8", "CUT"), ("10", "5"), ("20", "5"), ("40", "1")], + vec![("0", "LWPOLYLINE"), ("8", "BEND_UP"), ("90", "2"), ("70", "128"), ("10", "0"), ("20", "1"), ("10", "10"), ("20", "1")], + vec![ + ("0", "ELLIPSE"), + ("8", "CUT"), + ("10", "0"), + ("20", "0"), + ("11", "10"), + ("21", "0"), + ("40", "1"), + ("41", "0"), + ("42", "6.283185307179586"), + ], + ] { + for (c, v) in e { + t += &pair(c, v); + } + } + t += &pair("0", "ENDSEC"); + t += &pair("0", "EOF"); + let l = dxf_layers(&t); + assert_eq!(l["OUTLINE"]["LINE"], 1); + assert_eq!(l["OUTLINE"]["ARC"], 1); + assert!((l["OUTLINE"]["length_mm"].as_f64().unwrap() - (5.0 + PI)).abs() < 1e-9, "{l}"); + assert_eq!(l["CUT"]["CIRCLE"], 1); + assert_eq!(l["CUT"]["ELLIPSE"], 1); + // A circle of radius 1 and an ellipse of ratio 1 (a circle of radius 10). + assert!((l["CUT"]["length_mm"].as_f64().unwrap() - 22.0 * PI).abs() < 1e-6, "{l}"); + assert!((l["BEND_UP"]["length_mm"].as_f64().unwrap() - 10.0).abs() < 1e-9, "{l}"); + } + + #[test] + fn output_checks_read_the_files_and_answers_a_case_names() { + let out = std::env::temp_dir().join(format!("kernel-cases-files-{}", std::process::id())); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("t.json"), r#"{"bends": [{"angle_deg": 90}]}"#).unwrap(); + std::fs::write(out.join("t.csv"), "bend,angle_deg\r\n1,90\r\n").unwrap(); + std::fs::write(out.join("t.dxf"), "0\nSECTION\n2\nENTITIES\n0\nLINE\n8\nOUTLINE\n10\n0\n20\n0\n11\n1\n21\n0\n0\nENDSEC\n").unwrap(); + let dir = out.to_string_lossy().to_string(); + let run = |want: Value| { + let mut c = Checks { list: Vec::new(), pass: true }; + output_checks(&mut c, &want, &dir, &[json!({"count": 3})], 1e-3); + c.pass + }; + assert!(run(json!({"files": [{"path": "t.json", "json": {"bends": [{"angle_deg": 90.0}]}}]}))); + assert!(run(json!({"files": [{"path": "t.csv", "csv": [{"bend": 1, "angle_deg": 90.0}]}]}))); + assert!(run(json!({"files": [{"path": "t.dxf", "dxf": {"OUTLINE": {"LINE": [1, 8], "ARC": 0, "length_mm": 1.0}}}]}))); + assert!(!run(json!({"files": [{"path": "t.dxf", "dxf": {"OUTLINE": {"LINE": [2, 8]}}}]}))); + assert!(!run(json!({"files": [{"path": "t.dxf", "dxf": {"CUT": {"CIRCLE": 1}}}]}))); + assert!(!run(json!({"files": [{"path": "none.json", "json": {}}]}))); + assert!(run(json!({"results": [{"step": 1, "json": {"count": 3}}]}))); + assert!(!run(json!({"results": [{"step": 2, "json": {}}]}))); + let _ = std::fs::remove_dir_all(&out); + } + + #[test] + fn construction_is_graded_as_the_point_line_or_plane_it_is() { + let mut s = solidcraft_engine::Session::default(); + let script = json!({"commands": [ + {"command": "construct.point.three_planes", "params": {"a": "XY", "b": "XZ", "c": "YZ", "name": "Pin"}}, + {"command": "construct.axis.two_planes", "params": {"a": "XZ", "b": "YZ", "name": "Spine"}}, + {"command": "construct.plane.offset", "params": {"base": "XY", "offset": "5 mm", "name": "Shelf"}}, + ]}); + s.run_script(&script).unwrap(); + let grade = |want: Value| { + let mut c = Checks { list: Vec::new(), pass: true }; + check_construction(&s, &want, 1e-3, &mut c); + c.pass + }; + // An axis is its line, either way along it, through any point of it; a plane likewise. + assert!(grade(json!({ + "Pin": {"point": [0, 0, 0]}, + "Spine": {"axis": {"through": [0, 0, 40], "dir": [0, 0, -1]}}, + "Shelf": {"plane": {"through": [7, -3, 5], "normal": [0, 0, 2]}}, + }))); + assert!(!grade(json!({"Pin": {"point": [0, 0, 0.01]}}))); + assert!(!grade(json!({"Spine": {"axis": {"through": [0.01, 0, 0], "dir": [0, 0, 1]}}}))); + assert!(!grade(json!({"Spine": {"axis": {"through": [0, 0, 0], "dir": [0, 0.01, 1]}}}))); + assert!(!grade(json!({"Shelf": {"plane": {"through": [0, 0, 5.01], "normal": [0, 0, 1]}}}))); + assert!(!grade(json!({"Shelf": {"plane": {"through": [0, 0, 5], "normal": [1, 0, 0]}}}))); + // A name the timeline has not got, or of another kind, fails. + assert!(!grade(json!({"Pin": {"plane": {"through": [0, 0, 0], "normal": [0, 0, 1]}}}))); + assert!(!grade(json!({"Nothing": {"point": [0, 0, 0]}}))); + assert!(!grade(json!({"Pin": {"centre": [0, 0, 0]}}))); + } + + #[test] + fn results_are_read_from_each_commands_reply() { + let replies = [json!({"center": [1.0, 2.0, 3.0], "volume": 24000.0}), json!({"summary": {"worst": "g1"}, "count": 1})]; + let grade = |results: Value| { + let mut c = Checks { list: Vec::new(), pass: true }; + output_checks(&mut c, &json!({ "results": results }), "", &replies, 1e-3); + c.pass + }; + assert!(grade(json!([ + {"step": 1, "pointer": "/center", "json": [1.0, 2.0, 3.0]}, + {"step": 1, "pointer": "/volume", "json": 24010.0}, + {"step": 2, "pointer": "/summary/worst", "json": "g1"}, + {"step": 2, "json": {"count": 1}}, + ]))); + assert!(!grade(json!([{"step": 1, "pointer": "/volume", "json": 24100.0}]))); + assert!(grade(json!([{"step": 1, "pointer": "/volume", "json": 24100.0, "rel": 0.01}]))); + assert!(!grade(json!([{"step": 1, "pointer": "/center", "json": [1.0, 2.0, 3.01]}]))); + assert!(grade(json!([{"step": 1, "pointer": "/center", "json": [1.0, 2.0, 3.01], "abs_mm": 0.02}]))); + assert!(!grade(json!([{"step": 2, "pointer": "/summary/worst", "json": "g2"}]))); + // A whole number is exact: a count. + assert!(!grade(json!([{"step": 2, "pointer": "/count", "json": 2}]))); + // A step or a part that is not there fails, as does an entry without a step. + assert!(!grade(json!([{"step": 3, "pointer": "/count", "json": 1}]))); + assert!(!grade(json!([{"step": 2, "pointer": "/missing", "json": null}]))); + assert!(!grade(json!([{"pointer": "/count", "json": 1}]))); + } + + #[test] + fn a_base_cycle_is_an_error_not_a_hang() { + let root = std::env::temp_dir().join(format!("kernel-cases-cycle-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let a = case_dir(&root, "a", &json!({"base": "../a", "commands": []})); + let r = read_json(&format!("{a}/recipe.json")).unwrap(); + assert!(script(&a, "/scratch", &r).unwrap_err().contains("deeper than")); + let _ = std::fs::remove_dir_all(&root); + } + + /// `continuity` asks for one order at every seam it picks, or per seam (`seams`), each entry + /// read as the one-order form; the curvature-jump form asks for none. + #[test] + fn continuity_asks_for_one_order_or_one_per_seam() { + use solidcraft_engine::kernel::Continuity; + let read = |c: Value| { + continuity_wants(&c).into_iter().map(|w| w.map(|(e, o, x)| (e.clone(), o, x))).collect::>>() + }; + let g2 = Continuity::parse("g2").unwrap(); + let g3 = Continuity::parse("g3").unwrap(); + assert_eq!(read(json!({"order": "g2", "exact": true})), vec![Ok((Value::Null, g2, true))]); + let (p, q) = (json!([[30.0, 31.3, 10.0]]), json!([[30.0, 29.4, 12.7]])); + assert_eq!( + read(json!({"seams": [{"order": "g2", "exact": true, "edges": p}, {"order": "g3", "edges": q}]})), + vec![Ok((p.clone(), g2, true)), Ok((q, g3, false))] + ); + assert!(read(json!({"near": [0.0, 0.0, 0.0], "within_mm": 1.0})).is_empty()); + assert!(read(Value::Null).is_empty()); + assert!(read(json!({"order": "g9"}))[0].is_err()); + assert!(read(json!({"seams": [{"edges": p}]}))[0].is_err(), "a seam must say its order"); + } + + /// The flat pattern is graded on the last `sheet.flat_pattern` result: its size, its outline's + /// area less the cut-outs', and its bend lines matched either way round, one for one. + #[test] + fn flat_pattern_grades_size_area_and_bend_lines() { + let flat = json!({"flat_size_mm": [10.0, 4.0, 2.0], + "outline": [[[0.0, 0.0], [10.0, 0.0], [10.0, 4.0], [0.0, 4.0]]], "cutouts": [[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], + "bends": [{"start": [5.0, 0.0], "end": [5.0, 4.0]}]}); + let results = [json!({"volume_mm3": 1.0}), flat]; + let grade = |want: Value| { + let mut c = Checks { list: Vec::new(), pass: true }; + flat_pattern_checks(&mut c, &want, &results, 1e-3, 1e-3); + c.pass + }; + assert!(grade(json!({"size_mm": [10.0, 4.0], "area_mm2": 39.0, "bend_lines": [[[5.0, 4.0], [5.0, 0.0]]]}))); + assert!(!grade(json!({"area_mm2": 40.0})), "the cut-out is not material"); + assert!(!grade(json!({"size_mm": [10.0, 5.0]}))); + assert!(!grade(json!({"bend_lines": [[[5.0, 0.0], [5.0, 4.0]], [[5.0, 0.0], [5.0, 4.0]]]})), "one bend line matches one only"); + assert!(!grade(json!({"bend_lines": [[[6.0, 0.0], [6.0, 4.0]]]}))); + let mut c = Checks { list: Vec::new(), pass: true }; + flat_pattern_checks(&mut c, &json!({"area_mm2": 1.0}), &results[..1], 1e-3, 1e-3); + assert!(!c.pass, "no flat pattern was made"); + } +} diff --git a/apps/solidcraft-cli/src/kernel_cases_export.rs b/apps/solidcraft-cli/src/kernel_cases_export.rs new file mode 100644 index 000000000..6d8a0dca0 --- /dev/null +++ b/apps/solidcraft-cli/src/kernel_cases_export.rs @@ -0,0 +1,299 @@ +//! `kernel-cases --export=DIR`: one kernel rig case as a corpus entry for solidcore's rig. The +//! case's commands run as the rig runs them while the kernel's operations are traced +//! (`smlib_trace`); the entry holds the operation (or the chain of operations) that made the +//! bodies the case ends with, each operand that came in as a record given as that record (the +//! B-rep record, solidcore-record's JSON), the fix set, the case's expected values and the rig's +//! own result. A case whose result no kernel operation alone accounts for is written too, with +//! the reasons, so nothing is dropped silently. +//! +//! An entry's operation is expressible (`operation_expressible`) when the run failed in a kernel +//! operation (the last one traced failed), or when every body the case ends with is the record a +//! traced operation's output was written as, or an operand some traced operation took, as its +//! record. The entry is wholly expressible (`expressible`) when, besides, every value it grades is +//! the kernel's: none of `continuity`, `watertight`, `files`, `results`, `construction` or +//! `flat_pattern` (SolidCraft computes them), no face, edge or vertex count that the rig's merging +//! across analytic surfaces (`merged_topology`) changes, and no refusal graded on SolidCraft's +//! wording of the kernel's error. Those are listed in `ungraded`. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use solidcore_record::brep::Brep; +use solidcraft_engine::kernel::smlib_trace::{self, Event}; + +use crate::read_json; + +/// What a traced case leaves for its entry: the trace of its commands, and the bodies it ends +/// with by name or the engine's error. +#[derive(Default)] +pub struct Capture { + pub events: Vec, + pub ran: Option, String>>, +} + +/// The expected values SolidCraft computes, never the kernel. +const GRADER_ONLY: [&str; 6] = ["continuity", "watertight", "files", "results", "construction", "flat_pattern"]; + +/// The case directory's area (its path under `tests/kernel-cases/`, a ladder case's tier under +/// `ladder/`) and its id. +fn area_and_id(dir: &str) -> Result<(String, String), String> { + let p = Path::new(dir); + let parts: Vec = p.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect(); + let at = parts.iter().rposition(|c| c == "kernel-cases").ok_or_else(|| format!("{dir}: not under tests/kernel-cases"))?; + let rest = parts.get(at + 1..).unwrap_or_default(); + match rest.split_last() { + Some((id, area)) if !area.is_empty() => Ok((area.join("/"), id.clone())), + _ => Err(format!("{dir}: no area")), + } +} + +/// The case's line in its area's `KNOWN_FAILING`: why it fails today; `None` when not listed. +fn known_failing(dir: &str, id: &str) -> Option { + let list = Path::new(dir).parent()?.join("KNOWN_FAILING"); + let text = std::fs::read_to_string(list).ok()?; + text.lines().filter(|l| !l.trim_start().starts_with('#')).find_map(|l| { + let (case, why) = l.split_once(char::is_whitespace).unwrap_or((l, "")); + (case == id).then(|| why.trim().to_string()) + }) +} + +/// The trace read as operations and the records that went in and came out. +struct Trace<'a> { + /// Each operation: its name, operands, parameters and outputs or error. + calls: Vec<(&'static str, &'a [u64], &'a Value, &'a Result, String>)>, + /// The record each body made from a record was made from. + imports: HashMap, + /// The records bodies were written as, in order. + exports: Vec<(u64, &'a Brep)>, + /// The operation that made each body. + producer: HashMap, +} + +impl<'a> Trace<'a> { + fn of(events: &'a [Event]) -> Trace<'a> { + let mut t = Trace { calls: Vec::new(), imports: HashMap::new(), exports: Vec::new(), producer: HashMap::new() }; + for e in events { + match e { + Event::Import { id, record, trusted, keeping_splines } => { + t.imports.insert(*id, (record, *trusted, *keeping_splines)); + } + Event::Export { id, record } => t.exports.push((*id, record)), + Event::Call { op, inputs, params, outputs } => { + if let Ok(made) = outputs { + for id in made { + t.producer.insert(*id, t.calls.len()); + } + } + t.calls.push((*op, inputs, params, outputs)); + } + } + } + t + } + + /// Bodies some operation took as an operand. + fn operands(&self) -> BTreeSet { + self.calls.iter().flat_map(|c| c.1.iter().copied()).collect() + } +} + +/// The operations `ends` need, in the order they ran: each body's maker, and its operands' makers +/// in turn, back to bodies made from records. Operands made by nothing traced are listed in +/// `unknown`. +fn chain(t: &Trace<'_>, ends: &[u64], unknown: &mut BTreeSet) -> Vec { + let mut need = BTreeSet::new(); + let mut todo: Vec = ends.to_vec(); + while let Some(id) = todo.pop() { + if t.imports.contains_key(&id) { + continue; + } + match t.producer.get(&id) { + Some(&i) => { + if need.insert(i) + && let Some(c) = t.calls.get(i) + { + todo.extend(c.1.iter().copied()); + } + } + None => { + unknown.insert(id); + } + } + } + need.into_iter().collect() +} + +/// The entry of case `dir`, run with result `out`, into `root//.json`, and the fix set +/// into `root/fixes.json`. +pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<(), String> { + let (area, id) = area_and_id(dir)?; + let want = read_json(&format!("{dir}/expected.json"))?; + let t = Trace::of(&capture.events); + // Why the operation is not the kernel's alone, and what the entry cannot grade without + // SolidCraft. + let mut why_not: Vec = Vec::new(); + let mut ungraded: Vec = Vec::new(); + let has = |k: &str| want.get(k).is_some_and(|v| !v.is_null()); + + if let Some(missing) = want["missing"].as_str() { + why_not.push(format!("SolidCraft has no command for it yet: {missing}")); + } + for k in GRADER_ONLY.iter().filter(|k| has(k)) { + ungraded.push(format!("{k}: SolidCraft computes it")); + } + + let mut result: Vec = Vec::new(); + let mut ends: Vec = Vec::new(); + let mut failed_call: Option = None; + let mut outcome = json!({"ran": true}); + match (&capture.ran, has("missing")) { + (_, true) => {} + (None, false) => why_not.push("the case did not run".into()), + (Some(Err(e)), false) => { + // The run stopped. It stopped in the kernel when the last operation that failed is + // followed by no operation but copies (a copy or a tagged copy, which build nothing): + // nothing was built after it, so the engine's error reports that failure in its own + // words. An operation that ran after it means the engine went on and failed itself. + outcome = json!({"ran": false, "engine_error": e}); + let last_failed = t.calls.iter().rposition(|c| c.3.is_err()); + let built_after = |i: usize| t.calls.iter().skip(i + 1).any(|c| !matches!(c.0, "copy" | "tagged")); + match last_failed.filter(|&i| !built_after(i)).and_then(|i| t.calls.get(i).map(|c| (i, c))) { + Some((i, c)) => { + failed_call = Some(i); + ends.extend(c.1.iter().copied()); + if let Err(k) = c.3 { + outcome["kernel_error"] = json!(k); + if let Some(why) = want["refusal"].as_str().filter(|w| !k.contains(*w)) { + ungraded.push(format!("refusal {why:?}: SolidCraft's wording of the kernel's error")); + } + } + } + None if t.calls.is_empty() => why_not.push(format!("no kernel operation ran before the failure: {e}")), + None => why_not.push(format!("the failure is SolidCraft's, not a kernel operation's: {e}")), + } + } + (Some(Ok(world)), false) => { + let operands = t.operands(); + let mut made = 0; + for (name, record) in world { + let from_op = t.exports.iter().rev().find(|(id, r)| *r == record && t.producer.contains_key(id)).map(|(id, _)| *id); + let operand = t.imports.iter().filter(|(i, (r, _, _))| *r == record && operands.contains(i)).map(|(i, _)| *i).min(); + match (from_op, operand) { + (Some(id), _) => { + made += 1; + ends.push(id); + result.push(json!({"body": name, "made": format!("b{id}")})); + } + (None, Some(id)) => { + ends.push(id); + result.push(json!({"body": name, "operand": format!("b{id}")})); + } + (None, None) => why_not.push(format!( + "body {name:?} is no kernel operation's output nor an operand: SolidCraft built it or changed the kernel's record" + )), + } + } + if world.is_empty() { + why_not.push("the case ends with no body".into()); + } else if made == 0 && why_not.is_empty() { + why_not.push("no kernel operation made a body the case ends with".into()); + } + // Counts graded as SolidCraft merges them, where that differs from the records'. + let raw = |k: &str| -> u64 { + world + .iter() + .map(|(_, r)| match k { + "faces" => r.faces.len(), + "edges" => r.edges.len(), + _ => r.vertices.len(), + } as u64) + .sum() + }; + for k in ["faces", "edges", "vertices"] { + if let Some(merged) = out["measured"][k].as_u64().filter(|&m| has(k) && m != raw(k)) { + ungraded.push(format!("{k}: graded merged across analytic surfaces ({merged}), the records have {}", raw(k))); + } + } + outcome["raw_counts"] = json!({"faces": raw("faces"), "edges": raw("edges"), "vertices": raw("vertices")}); + } + } + + let mut unknown = BTreeSet::new(); + let mut order = chain(&t, &ends, &mut unknown); + if !unknown.is_empty() { + why_not.push(format!("operands made by nothing traced: {unknown:?}")); + } + if let Some(i) = failed_call.filter(|i| !order.contains(i)) { + order.push(i); + } + // Operand records: every body the chain takes, or the case ends with, that came in as a record. + let mut bodies = BTreeMap::new(); + let given = |id: u64, bodies: &mut BTreeMap| { + if let Some((record, trusted, splines)) = t.imports.get(&id) { + bodies.insert(format!("b{id}"), json!({"trusted": trusted, "keeping_splines": splines, "record": record})); + } + }; + let mut calls: Vec = Vec::new(); + for (op, inputs, params, outputs) in order.iter().filter_map(|&i| t.calls.get(i)) { + for &id in inputs.iter() { + given(id, &mut bodies); + } + let mut c = json!({"op": op, "inputs": inputs.iter().map(|i| format!("b{i}")).collect::>(), "params": params}); + match outputs { + Ok(made) => c["outputs"] = json!(made.iter().map(|i| format!("b{i}")).collect::>()), + Err(e) => c["error"] = json!(e), + } + calls.push(c); + } + for r in &result { + if let Some(id) = r["operand"].as_str().and_then(|b| b.strip_prefix('b')).and_then(|n| n.parse().ok()) { + given(id, &mut bodies); + } + } + let rig = json!({ + "status": out["status"], "error": out["error"], "refused_with": out["refused_with"], "measured": out["measured"], + "known_failing": known_failing(dir, &id), + }); + let operation_expressible = why_not.is_empty(); + let entry = json!({ + "case": id, + "area": area, + "sources": want["sources"], + "what": want["what"], + "expressible": operation_expressible && ungraded.is_empty(), + "operation_expressible": operation_expressible, + "why_not": why_not, + "ungraded": ungraded, + "expected": want, + "rig": rig, + "outcome": outcome, + "calls": calls, + "bodies": bodies, + "result": result, + "traced_ops": t.calls.iter().map(|c| c.0).collect::>(), + }); + let folder: PathBuf = root.join(&area); + std::fs::create_dir_all(&folder).map_err(|e| format!("{}: {e}", folder.display()))?; + let path = folder.join(format!("{id}.json")); + let text = serde_json::to_string(&entry).map_err(|e| e.to_string())?; + std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?; + // Cases run in parallel processes: each writes its own file and renames it over the shared + // one, so no reader sees a torn file (every process writes the same fix set). + let fixes = serde_json::to_string_pretty(&smlib_trace::fixes()).map_err(|e| e.to_string())?; + let own = root.join(format!("fixes.json.{}", std::process::id())); + std::fs::write(&own, fixes).map_err(|e| format!("{}: {e}", own.display()))?; + std::fs::rename(&own, root.join("fixes.json")).map_err(|e| format!("{}: {e}", root.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_area_is_the_path_under_kernel_cases() { + assert_eq!(area_and_id("tests/kernel-cases/booleans/1894-x").unwrap(), ("booleans".into(), "1894-x".into())); + assert_eq!(area_and_id("/r/tests/kernel-cases/ladder/07-fillets/003-y").unwrap(), ("ladder/07-fillets".into(), "003-y".into())); + assert!(area_and_id("/r/other/x").is_err()); + } +} diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index b210b63a9..de03f741d 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -10,12 +10,13 @@ //! solidcraft-cli bench-assistant --connect 127.0.0.1:PORT [--token T] --base-url URL --model NAME [--tasks 1,2,5] [--repeat N] //! [--timeout-s 300] [--json out.json] [--markdown out.md] //! the standard Assistant model test (#4851) on a running app -//! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] +//! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] [--quality LEVEL] //! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] //! solidcraft-cli exec [json-params] run one command on an empty design //! solidcraft-cli commands the command registry as JSON //! solidcraft-cli recipe translate an oracle recipe to a script //! solidcraft-cli oracle ... replay recipes and compare with expected.json +//! solidcraft-cli kernel-cases [--json] [--dumps=DIR] [--validation=MODE] ... the kernel regression rig (tests/kernel-cases) //! solidcraft-cli mcp [--headless] [--in design|script] [--connect HOST:PORT [--token T]] [--allow-path DIR]... [--allow-any-path] //! [--param-check off|warn|strict] //! MCP server on stdio (docs/mcp.md) @@ -33,9 +34,12 @@ mod bench_agent; mod bench_assistant; mod crashes; mod fuzz; +mod kernel_cases; +mod kernel_cases_export; mod logger; mod oracle; mod preview; +mod profiling; mod recipe; mod render; mod spatial; @@ -58,19 +62,19 @@ struct Command { } /// `run`'s lines in the usage. -const USAGE_RUN: &str = " solidcraft-cli run [--in design.sc|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors]\n [--param-check off|warn|strict]\n solidcraft-cli run --in [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--param-check checks each step against its command's contract: warn reports on stderr, strict stops the run)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n"; +const USAGE_RUN: &str = " solidcraft-cli run [--in design.sc|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--profile-out trace.json] [--json-out FILE] [--allow-errors] [--validation each_step|each_feature|off]\n [--param-check off|warn|strict]\n solidcraft-cli run --in [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--validation: when SMLib's full check runs on the features computed (diagnostics.validation), default each_feature)\n (--param-check checks each step against its command's contract: warn reports on stderr, strict stops the run)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n (--profile also records where the time goes, SMLib's calls, kernel operations, features, commands and import stages,\n and prints the table to stderr: count, total, self time and longest per span; --profile-out FILE writes the spans\n as a Chrome trace for chrome://tracing or ui.perfetto.dev; SOLIDCRAFT_PROFILE=1 does the same for any command)\n"; /// `eval`'s lines in the usage. -const USAGE_EVAL: &str = " solidcraft-cli eval [--in design.sc|part.step] [--json-out FILE] (alias: inspect)\n solidcraft-cli eval --in [--json-out FILE]\n (with both inputs, runs the positional script on --in before measuring; does not automatically save the modified design)\n (--json-out FILE writes the JSON that run (with --results, else the measurement) and eval print to FILE instead of stdout,\n as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark)\n"; +const USAGE_EVAL: &str = " solidcraft-cli eval [--in design.sc|part.step] [--json-out FILE] [--profile] [--profile-out trace.json] (alias: inspect)\n solidcraft-cli eval --in [--json-out FILE]\n (with both inputs, runs the positional script on --in before measuring; does not automatically save the modified design)\n (--json-out FILE writes the JSON that run (with --results, else the measurement) and eval print to FILE instead of stdout,\n as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark)\n (--profile and --profile-out as for run)\n"; /// `script`'s lines in the usage. const USAGE_SCRIPT: &str = " solidcraft-cli script [--out script.json]\n (the design's history as a command script that eval and run replay)\n"; /// `bench-open`'s lines in the usage. -const USAGE_BENCH_OPEN: &str = " solidcraft-cli bench-open [--parse-only] [--save OUT.sc] [--display LEVEL [--edit NAME EXPR]] [--ops script.json]\n (--ops: after opening, run each command of the script and undo it, timing the command, the\n evaluations it caused and the view it leaves: placing and meshing what changed)\n"; +const USAGE_BENCH_OPEN: &str = " solidcraft-cli bench-open [--parse-only] [--save OUT.sc] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] [--profile] [--profile-out trace.json]\n (--profile and --profile-out as for run)\n (--ops: after opening, run each command of the script and undo it, timing the command, the\n evaluations it caused and the view it leaves: placing and meshing what changed)\n"; /// `bench-agent`'s lines in the usage. const USAGE_BENCH_AGENT: &str = " solidcraft-cli bench-agent [--scale F] [--save design.sc] [--script-out script.json]\n"; /// `bench-assistant`'s lines in the usage. const USAGE_BENCH_ASSISTANT: &str = " solidcraft-cli bench-assistant --connect 127.0.0.1:PORT [--token T] --base-url URL --model NAME [--tasks 1,2,5] [--repeat N] [--timeout-s 300] [--json out.json] [--markdown out.md]\n"; /// `snapshot`'s lines in the usage. -const USAGE_SNAPSHOT: &str = " solidcraft-cli snapshot [--in design.sc|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes]\n [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27]\n solidcraft-cli snapshot --in --out shot.png ...\n (as with run, --in starts from a design and the script runs on top of it; an option snapshot doesn't take is an error;\n --view: iso, front, back, top, bottom, left, right, or the name of a view saved in the design with view.save;\n --camera: {target: [x,y,z], yaw, pitch, distance, fov?} in mm and radians, as the MCP screenshot takes it (docs/mcp.md);\n --no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture;\n --body: how one body is drawn, as appearance.assign takes it: opacity 0-1 (below 1 is see-through, so what is inside\n it shows) and color #rrggbb, either or both, once per body;\n --tool: draw this body solid in the tool colour and every other body see-through, so a cut's or a join's tool body\n is visible inside the material it meets; a later --body overrides it;\n --section: cut the model as inspect.section does, so the inside shows: z=27 (the plane through that world\n coordinate, keeping the smaller side), add ,flip to keep the other side, or XY, XZ, YZ, or its own JSON)\n"; +const USAGE_SNAPSHOT: &str = " solidcraft-cli snapshot [--in design.sc|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes]\n [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] [--quality coarse|normal|fine|ultra]\n solidcraft-cli snapshot --in --out shot.png ...\n (as with run, --in starts from a design and the script runs on top of it; an option snapshot doesn't take is an error;\n --view: iso, front, back, top, bottom, left, right, or the name of a view saved in the design with view.save;\n --camera: {target: [x,y,z], yaw, pitch, distance, fov?} in mm and radians, as the MCP screenshot takes it (docs/mcp.md);\n --no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture;\n --body: how one body is drawn, as appearance.assign takes it: opacity 0-1 (below 1 is see-through, so what is inside\n it shows) and color #rrggbb, either or both, once per body;\n --tool: draw this body solid in the tool colour and every other body see-through, so a cut's or a join's tool body\n is visible inside the material it meets; a later --body overrides it;\n --section: cut the model as inspect.section does, so the inside shows: z=27 (the plane through that world\n coordinate, keeping the smaller side), add ,flip to keep the other side, or XY, XZ, YZ, or its own JSON;\n --quality: the display quality the bodies are meshed at, as the app's setting (default normal))\n"; /// `render`'s lines in the usage. const USAGE_RENDER: &str = " solidcraft-cli render --out image.png [--setup NAME] [--width W] [--height H] [--transparent] [--overwrite] [--timeout SECONDS]\n [--progressive] [--samples N] [--max-depth N] [--seed N] [--exposure EV] [--lighting FILE.json] [--environment FILE.json] [--tone-map reinhard|aces_fitted]\n"; /// `exec`'s lines in the usage. @@ -81,6 +85,8 @@ const USAGE_COMMANDS: &str = " solidcraft-cli commands\n"; const USAGE_RECIPE: &str = " solidcraft-cli recipe \n"; /// `oracle`'s lines in the usage. const USAGE_ORACLE: &str = " solidcraft-cli oracle ... [--json]\n"; +/// `kernel-cases`'s lines in the usage. +const USAGE_KERNEL_CASES: &str = " solidcraft-cli kernel-cases ... [--json] [--dumps=DIR] [--export=DIR] [--validation=each_step|each_feature|off]\n (the kernel regression rig, tests/kernel-cases, on SMLib; --dumps: each case's\n failing SMLib calls leave their inputs for replay in DIR/-; --export: each case's\n kernel operations, input records and expected values for solidcore's rig, in DIR//.json; --validation: when SMLib's\n full check runs (diagnostics.validation), default each_feature)\n"; /// `fuzz`'s lines in the usage. const USAGE_FUZZ: &str = " solidcraft-cli fuzz [--from N] [--count N] [--jobs J] [--timeout S] [--steps N] [--minimise] [--out DIR] [--report FILE]\n"; @@ -118,6 +124,7 @@ const COMMANDS: &[Command] = &[ Command { name: "commands", usage: USAGE_COMMANDS, listed: true }, Command { name: "recipe", usage: USAGE_RECIPE, listed: true }, Command { name: "oracle", usage: USAGE_ORACLE, listed: true }, + Command { name: "kernel-cases", usage: USAGE_KERNEL_CASES, listed: true }, Command { name: "fuzz", usage: USAGE_FUZZ, listed: true }, Command { name: "fuzz-one", usage: USAGE_FUZZ_ONE, listed: false }, Command { name: "mcp", usage: USAGE_MCP, listed: true }, @@ -133,6 +140,19 @@ const COMMANDS: &[Command] = &[ fn main() -> ExitCode { let mut args: Vec = std::env::args().skip(1).collect(); logger::init(&mut args); + // `--profile` / `--profile-out` (run, eval, bench-open) or SOLIDCRAFT_PROFILE (any command): + // record from here, and print the table when the command ends. + let profiling = match args.first().map(String::as_str) { + Some("run" | "eval" | "inspect" | "bench-open") => profiling::start(&args[1..]), + _ => profiling::start(&[]), + }; + let profiling = match profiling { + Ok(p) => p, + Err(e) => { + eprintln!("error: {e}"); + return ExitCode::FAILURE; + } + }; if let Err(e) = max_file_size(&mut args) { eprintln!("error: {e}"); return ExitCode::FAILURE; @@ -170,9 +190,14 @@ fn main() -> ExitCode { recipe::to_script(&v).map(|s| println!("{}", pretty(&s))) }), Some("oracle") => oracle::run(&args[1..]), + Some("kernel-cases") => kernel_cases::run(&args[1..]), Some("fuzz") => fuzz::run(&args[1..]), Some("fuzz-one") => fuzz::one(&args[1..]), - Some("mcp") => cmd_mcp(&args[1..]), + Some("mcp") => { + let result = cmd_mcp(&args[1..]); + solidcraft_mcp::cleanup_scratch_dir(); + result + } Some("crashes") => crashes::run(&args[1..]), Some("icon") => cmd_icon(&args[1..]), Some("licences" | "licenses") => { @@ -202,6 +227,11 @@ fn main() -> ExitCode { } _ => Err(usage()), }; + // The table also when the command failed: where it spent its time before failing. + let r = match (r, profiling.map(profiling::Profiling::finish)) { + (Ok(()), Some(Err(e))) => Err(e), + (r, _) => r, + }; match r { Ok(()) => ExitCode::SUCCESS, Err(e) => { @@ -282,8 +312,15 @@ pub fn load(path: &str) -> Result { /// `load`, with scripts and recipes run at the parameter-check level `check`, which the /// session keeps. fn load_checked(path: &str, check: solidcraft_engine::schema::ParamCheck) -> Result { + load_with(path, check, solidcraft_engine::kernel::Validation::default()) +} + +/// `load_checked`, the features computed under `validation` (`diagnostics.validation`), which +/// the session keeps. +fn load_with(path: &str, check: solidcraft_engine::schema::ParamCheck, validation: solidcraft_engine::kernel::Validation) -> Result { let mut s = Session::default(); s.param_check = check; + s.set_validation(validation); if solidcraft_engine::io::is_step_path(path) || solidcraft_engine::io::is_mesh_path(path) || solidcraft_engine::io::is_point_cloud_path(path) { s.execute("doc.open", &json!({"path": path})).map_err(|e| e.to_string())?; return Ok(s); @@ -291,7 +328,7 @@ fn load_checked(path: &str, check: solidcraft_engine::schema::ParamCheck) -> Res let bytes = solidcraft_engine::io::limits::read(path, solidcraft_engine::io::limits::Kind::Design).map_err(|e| format!("{path}: {e}"))?; if solidcraft_engine::io::is_design_container(&bytes) { let doc = solidcraft_engine::io::read_design(&bytes).map_err(|e| format!("{path}: {e}"))?; - let mut session = Session::opened_at(doc, None, Some(path)); + let mut session = Session::opened_at_validating(doc, None, Some(path), validation); session.param_check = check; return Ok(session); } @@ -355,6 +392,16 @@ fn positional(args: &[String]) -> Option<&String> { None } +/// Is `path` a command script (or a recipe), not a design: JSON that is no saved design. +fn is_script(path: &str) -> bool { + let Ok(bytes) = solidcraft_engine::io::vfs::read(path, solidcraft_engine::io::MAX_DESIGN_BYTES) else { return false }; + if solidcraft_engine::io::is_design_container(&bytes) { + return false; + } + serde_json::from_slice::(&bytes) + .is_ok_and(|v| !v.get("format").and_then(Value::as_str).is_some_and(|f| solidcraft_engine::doc::format::version_of(f).is_some())) +} + /// `--json-out FILE`: where the JSON a command prints goes instead of stdout. fn json_out(args: &[String]) -> Result, String> { if !args.iter().any(|a| a == "--json-out") { @@ -391,24 +438,31 @@ fn cmd_run(args: &[String]) -> Result<(), String> { known_args( "run", args, - &["--in", "--out", "--save", "--json-out", "--param-check"], + &["--in", "--out", "--save", "--json-out", "--param-check", "--profile-out", "--validation"], &["--quiet", "--results", "--timings", "--profile", "--allow-errors"], true, )?; + let validation = validation_flag("run", args)?; let base = flag(args, "--in"); let path = positional(args); if path.is_none() && base.is_none() { return Err(usage()); } let want_results = args.iter().any(|a| a == "--results"); - // `--profile` times each command and splits out its kernel time; it implies `--timings`. - let profile = args.iter().any(|a| a == "--profile"); + // `--profile` records the profiler's spans (the table goes to stderr, `profiling.rs`); for a + // script it also times each command and splits out its kernel time, implying `--timings`. + let script = path.is_some_and(|p| is_script(p)); + let profile = script && args.iter().any(|a| a == "--profile" || a == "--profile-out"); let timings = profile || args.iter().any(|a| a == "--timings"); let (mut s, results) = if want_results || timings { // Collect every command's result or time (scripts only), then process requested files too. let mut s = match base { - Some(b) => load_checked(b, check)?, - None => Session::default(), + Some(b) => load_with(b, check, validation)?, + None => { + let mut s = Session::default(); + s.set_validation(validation); + s + } }; s.param_check = check; let needs = if want_results { "--results needs a script" } else { "--timings needs a script" }; @@ -425,7 +479,7 @@ fn cmd_run(args: &[String]) -> Result<(), String> { }; (s, Some(out)) } else { - (open(base, path, check)?, None) + (open_validating(base, path, check, validation)?, None) }; // A feature that fails leaves the bodies as they were before it (a parameter change can // break a feature without failing the command that made it): writing them would hand out @@ -452,18 +506,38 @@ fn cmd_run(args: &[String]) -> Result<(), String> { /// The session `run`, `eval` and `snapshot` start from: `--in` (a design or STEP file) with the /// positional script run on top of it, or either one alone, with scripts run at `check`. fn open(base: Option<&str>, path: Option<&String>, check: solidcraft_engine::schema::ParamCheck) -> Result { + open_validating(base, path, check, solidcraft_engine::kernel::Validation::default()) +} + +/// [`open`], the features computed under `validation`. +fn open_validating( + base: Option<&str>, + path: Option<&String>, + check: solidcraft_engine::schema::ParamCheck, + validation: solidcraft_engine::kernel::Validation, +) -> Result { + let load = |p: &str| load_with(p, check, validation); match (base, path) { (Some(b), Some(p)) => { - let mut s = load_checked(b, check)?; + let mut s = load(b)?; run_script_warning(&mut s, p, &read_json(p)?)?; Ok(s) } - (Some(b), None) => load_checked(b, check), - (None, Some(p)) => load_checked(p, check), + (Some(b), None) => load(b), + (None, Some(p)) => load(p), (None, None) => Err(usage()), } } +/// `--validation MODE` (`diagnostics.validation`): the default, each_feature, when not given. +fn validation_flag(cmd: &str, args: &[String]) -> Result { + match flag(args, "--validation") { + Some(m) => solidcraft_engine::kernel::Validation::parse(m) + .ok_or_else(|| format!("{cmd}: --validation must be each_step, each_feature or off, not `{m}`")), + None => Ok(solidcraft_engine::kernel::Validation::default()), + } +} + /// Refuses an option `cmd` doesn't take, and one missing its value: a typo, or another /// command's option, would otherwise be ignored without a word. `positionals` says whether the /// command takes a word of its own (a file, a seed): `fuzz` takes none, and would start a run. @@ -501,7 +575,7 @@ fn timeline_ok(s: &Session) -> Result<(), String> { fn cmd_eval(args: &[String]) -> Result<(), String> { let json_out = json_out(args)?; - known_args("eval", args, &["--in", "--json-out"], &[], true)?; + known_args("eval", args, &["--in", "--json-out", "--profile-out"], &["--profile"], true)?; let mut s = open(flag(args, "--in"), positional(args), solidcraft_engine::schema::ParamCheck::Off)?; let m = s.execute("inspect.measure", &json!({})).map_err(|e| e.to_string())?; let d = s.execute("document.inspect", &json!({})).map_err(|e| e.to_string())?; @@ -583,7 +657,7 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { known_args( "snapshot", args, - &["--in", "--out", "--width", "--height", "--view", "--camera", "--body", "--tool", "--section"], + &["--in", "--out", "--width", "--height", "--view", "--camera", "--body", "--tool", "--section", "--quality"], &["--no-grid", "--no-axes"], true, )?; @@ -596,6 +670,16 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { Some(x) => x.parse().ok().filter(|n| (16..=8192).contains(n)).ok_or_else(|| format!("{name} must be 16 to 8192 pixels, not `{x}`")), }; let (w, h) = (size("--width", 1280)?, size("--height", 800)?); + // The display quality the bodies are meshed at, as the app's Display Quality setting: set + // before the design opens, so every display plan is made at it. + if let Some(q) = flag(args, "--quality") { + use solidcraft_engine::doc::display_quality::{DisplayQuality, set_current}; + let level = DisplayQuality::parse(q).ok_or_else(|| { + let ids: Vec<&str> = DisplayQuality::ALL.iter().map(|q| q.id()).collect(); + format!("--quality must be one of {}, not `{q}`", ids.join(", ")) + })?; + set_current(level); + } let mut s = open(flag(args, "--in"), positional(args), solidcraft_engine::schema::ParamCheck::Off)?; // How the bodies are drawn and where the model is cut, through the commands the app's // Appearance dialog and Section Analysis run (`preview`). @@ -615,9 +699,12 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { } (None, None) => {} } - let cam = s.camera.unwrap_or_else(|| solidcraft_engine::view::home_camera(&s)); + let cam = match s.camera { + Some(cam) => cam, + None => solidcraft_engine::view::home_camera(&s).map_err(|e| e.to_string())?, + }; let guides = Guides { grid: !args.iter().any(|a| a == "--no-grid"), axes: !args.iter().any(|a| a == "--no-axes") }; - let scene = solidcraft_engine::view::scene_with_guides(&s, &cam, s.section, guides); + let scene = solidcraft_engine::view::scene_with_guides(&s, &cam, s.section, guides).map_err(|e| e.to_string())?; let png = solidcraft_engine::capture::png(&scene, &cam, w, h)?; std::fs::write(out, &png.bytes).map_err(|e| format!("{out}: {e}"))?; let mut reply = json!({"path": out, "width": w, "height": h, "bytes": png.bytes.len(), "renderer": png.renderer}); @@ -846,7 +933,7 @@ fn bench_ops(mut s: Session, script: &str) -> Result { let r = s.execute(id, p).map_err(|e| format!("{id}: {e}"))?; let ms = t.elapsed().as_secs_f64() * 1000.0; let t = std::time::Instant::now(); - s.world_state().warm_meshes(|| true); + s.world_state().map_err(|e| e.to_string())?.warm_meshes(|| true); let view_ms = t.elapsed().as_secs_f64() * 1000.0; println!("{}", json!({"step": "op", "command": id, "ms": ms, "view_ms": view_ms})); Ok(r) @@ -902,7 +989,7 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { println!("{}", json!({"step": "feature", "id": r.id, "name": r.name, "ms": r.ms, "error": r.error})); } let t = std::time::Instant::now(); - let st = s.world_state(); + let st = s.world_state().map_err(|e| e.to_string())?; let place_ms = t.elapsed().as_secs_f64() * 1000.0; // As the desktop app prepares a design it opened. st.warm_meshes(|| true); @@ -972,7 +1059,7 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { let t = std::time::Instant::now(); s.execute("parameters.change", &json!({"name": name, "expression": expr})).map_err(|e| e.to_string())?; let eval_ms = t.elapsed().as_secs_f64() * 1000.0; - let st = s.world_state(); + let st = s.world_state().map_err(|e| e.to_string())?; let t = std::time::Instant::now(); st.warm_meshes(|| true); let mesh_ms = t.elapsed().as_secs_f64() * 1000.0; diff --git a/apps/solidcraft-cli/src/oracle.rs b/apps/solidcraft-cli/src/oracle.rs index 37e2853e4..dace772d0 100644 --- a/apps/solidcraft-cli/src/oracle.rs +++ b/apps/solidcraft-cli/src/oracle.rs @@ -5,7 +5,7 @@ #![allow(clippy::needless_range_loop)] use serde_json::{Value, json}; -use solidcraft_engine::geom::Vec3; +use solidcore_record::Vec3; use crate::spatial::{self, Tri}; use crate::{read_json, recipe}; @@ -13,28 +13,28 @@ use crate::{read_json, recipe}; /// Default relative tolerance for volume and area (our curved-face tessellation is within ~2e-4). pub const REL_TOL: f64 = 1e-3; /// Default tolerance for centre of mass and bounding box, as a fraction of the bbox diagonal. -const ABS_FRAC: f64 = 1e-3; +pub(crate) const ABS_FRAC: f64 = 1e-3; /// Chord tolerance used to triangulate our part for the surface-distance check (mm). const MESH_TOL: f64 = 0.01; /// Relative tolerance on the principal second moments of the two triangulations. const INERTIA_REL: f64 = 2e-3; /// What SolidCraft built: totals over every body. -struct Got { - body_count: usize, - volume: f64, - area: f64, - com: [f64; 3], - bbox: ([f64; 3], [f64; 3]), - faces: u64, +pub(crate) struct Got { + pub(crate) body_count: usize, + pub(crate) volume: f64, + pub(crate) area: f64, + pub(crate) com: [f64; 3], + pub(crate) bbox: ([f64; 3], [f64; 3]), + pub(crate) faces: u64, } -fn v3(v: &Value) -> Option<[f64; 3]> { +pub(crate) fn v3(v: &Value) -> Option<[f64; 3]> { let a = v.as_array()?; Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?]) } -fn totals(m: &Value) -> Got { +pub(crate) fn totals(m: &Value) -> Got { let bodies = m["bodies"].as_array().cloned().unwrap_or_default(); let (mut volume, mut area, mut faces) = (0.0, 0.0, 0); let mut moment = [0.0; 3]; @@ -57,21 +57,21 @@ fn totals(m: &Value) -> Got { Got { body_count: bodies.len(), volume, area, com, bbox: (lo, hi), faces } } -struct Checks { - list: Vec, - pass: bool, +pub(crate) struct Checks { + pub(crate) list: Vec, + pub(crate) pass: bool, } impl Checks { - fn push(&mut self, what: &str, got: Value, want: Value, ok: bool) { + pub(crate) fn push(&mut self, what: &str, got: Value, want: Value, ok: bool) { self.pass &= ok; self.list.push(json!({"check": what, "got": got, "want": want, "ok": ok})); } - fn rel(&mut self, what: &str, g: f64, w: Option, rel: f64) { + pub(crate) fn rel(&mut self, what: &str, g: f64, w: Option, rel: f64) { let ok = w.is_some_and(|w| g.is_finite() && (g - w).abs() <= rel * w.abs().max(1.0)); self.push(what, json!(g), json!(w), ok); } - fn vec(&mut self, what: &str, g: [f64; 3], w: Option<[f64; 3]>, tol: f64) { + pub(crate) fn vec(&mut self, what: &str, g: [f64; 3], w: Option<[f64; 3]>, tol: f64) { let ok = w.is_some_and(|w| g.iter().zip(w).all(|(g, w)| g.is_finite() && (g - w).abs() <= tol)); self.push(what, json!(g), json!(w), ok); } @@ -186,8 +186,8 @@ fn step_export_check(s: &solidcraft_engine::Session, volume: f64) -> (bool, Stri /// Our part as a triangle soup (curved faces refined onto the surface). fn our_mesh(s: &solidcraft_engine::Session) -> Result, String> { let mut ours: Vec = Vec::new(); - for b in &s.world_state().bodies { - let m = b.body.tessellate_with(MESH_TOL, true).map_err(|e| e.to_string())?; + for b in &s.world_state().map_err(|e| e.to_string())?.bodies { + let m = b.body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(MESH_TOL)).map_err(|e| e.to_string())?; let p = |i: u32| m.positions.get(i as usize).map(|v: &Vec3| [v.x, v.y, v.z]); for t in &m.triangles { if let (Some(a), Some(b), Some(c)) = (p(t[0]), p(t[1]), p(t[2])) { diff --git a/apps/solidcraft-cli/src/profiling.rs b/apps/solidcraft-cli/src/profiling.rs new file mode 100644 index 000000000..166496de1 --- /dev/null +++ b/apps/solidcraft-cli/src/profiling.rs @@ -0,0 +1,50 @@ +//! `--profile` and `--profile-out FILE` for `run`, `eval` and `bench-open` (and +//! `SOLIDCRAFT_PROFILE=1` for any command): record where the time goes, the kernel's calls to the +//! commands, print the table to stderr when the command ends (stdout stays the command's JSON) +//! and write the spans as a Chrome trace for chrome://tracing or Perfetto. + +use solidcraft_engine::profile; + +/// Rows the table prints. +const TOP: usize = 30; + +/// A recording that prints its table when finished. +pub struct Profiling { + trace: Option, +} + +/// Start recording when `args` (after the command) ask for it, or `SOLIDCRAFT_PROFILE` does. +pub fn start(args: &[String]) -> Result, String> { + let trace = match args.iter().position(|a| a == "--profile-out") { + Some(i) => match args.get(i + 1) { + Some(f) if !f.starts_with("--") => Some(f.clone()), + _ => return Err("--profile-out needs a FILE".into()), + }, + None => None, + }; + let asked = trace.is_some() || args.iter().any(|a| a == "--profile"); + if !asked && !solidcraft_engine::timing::profile_from_env() { + return Ok(None); + } + if !profile::COMPILED { + return Err("this solidcraft-cli was built without the profiler (its `profile` feature)".into()); + } + profile::reset(); + profile::set_enabled(true); + Ok(Some(Profiling { trace })) +} + +impl Profiling { + /// Stop recording, print the table on stderr and write the trace. + pub fn finish(self) -> Result<(), String> { + profile::set_enabled(false); + eprint!("{}", profile::report().table(TOP)); + if let Some(path) = self.trace { + let mut bytes = Vec::new(); + profile::write_chrome_trace(&mut bytes).map_err(|e| format!("{path}: {e}"))?; + std::fs::write(&path, bytes).map_err(|e| format!("{path}: {e}"))?; + eprintln!("profile: trace written to {path} (open it in chrome://tracing or ui.perfetto.dev)"); + } + Ok(()) + } +} diff --git a/apps/solidcraft-cli/tests/action_matrix.rs b/apps/solidcraft-cli/tests/action_matrix.rs index fecbcc267..cacfc6894 100644 --- a/apps/solidcraft-cli/tests/action_matrix.rs +++ b/apps/solidcraft-cli/tests/action_matrix.rs @@ -21,6 +21,7 @@ //! Each design runs in a child process (this test binary, [`action_matrix_worker`]) so an action //! that hangs or aborts is recorded as such and the rest of the design still runs. +use solidcraft_engine::geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; use std::io::{BufRead, Write}; use std::path::{Path, PathBuf}; @@ -28,10 +29,10 @@ use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_engine::Session; use solidcraft_engine::doc::kernel::{FaceSurface, face_surface}; use solidcraft_engine::doc::{FaceAttachmentStatus, ModelBody, naming}; -use solidcraft_engine::geom::Vec3; /// One in this many actions runs on pull requests (by a stable hash of its key). const PR_SAMPLE: u64 = 40; @@ -196,7 +197,7 @@ fn round3(x: f64) -> f64 { /// Every action on every entity of the design's final bodies, in a fixed order. fn actions(s: &Session) -> Vec { - let st = s.world_state(); + let st = s.world_state().unwrap(); let placed = s.placed_document(); let paths: BTreeMap> = placed.body_frames_with_source(&s.model.state()).into_iter().map(|(world, _, _, path, _)| (world, path)).collect(); @@ -1338,7 +1339,9 @@ fn a_fillet_or_chamfer_on_one_edge_ending_at_a_cylinder() { fn a_round_on_a_knuckle_cap_circle() { for (cmd, size, removed) in [("solid.fillet", "radius", (2.4, 2.8)), ("solid.chamfer", "distance", (5.6, 6.3))] { let mut s = load(&root().join("tests/oracle/63-hinge-knuckle/recipe.json")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.tessellate(0.001).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute(cmd, &json!({"edges": [[40.0, 29.837_722, 6.449_490]], size: 0.728})).unwrap_or_else(|e| panic!("{cmd}: {e}")); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{cmd}: {kind}: {e}")); @@ -1358,7 +1361,9 @@ fn a_round_on_a_knuckle_cap_circle() { #[test] fn a_hair_thin_hole_on_a_ledge_beside_a_loft_cut() { let mut s = load(&root().join("examples/regressions/loft_cut_beside_round_hole.json")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.tessellate_with(0.005, true).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.005)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute("solid.hole", &json!({"diameter": 0.133, "position": [357.22, -150.993_333, 730.0]})).unwrap(); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{kind}: {e}")); @@ -1375,7 +1380,9 @@ fn a_hair_thin_hole_on_a_ledge_beside_a_loft_cut() { #[test] fn a_small_hole_through_the_wall_of_a_plastic_rest() { let mut s = load(&root().join("apps/solidcraft-cli/tests/corpus/modern-plastic.solidcraft")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.tessellate_with(0.002, true).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.002)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute("solid.hole", &json!({"diameter": 0.8, "position": [63.069_841_5, 28.333_333, 4.0]})).unwrap(); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{kind}: {e}")); @@ -1390,7 +1397,9 @@ fn a_small_hole_through_the_wall_of_a_plastic_rest() { #[test] fn a_hole_square_to_a_45_degree_flange() { let mut s = load(&root().join("tests/oracle/70-sm-flange-45/recipe.json")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.tessellate_with(0.002, true).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.002)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute("solid.hole", &json!({"diameter": 3.448, "position": [66.666_667, -4.511_845, 4.511_845]})).unwrap(); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{kind}: {e}")); @@ -1648,7 +1657,7 @@ impl TipConstruction { other => panic!("expected an axis, got {other:?}"), } } - fn plane(&self) -> solidcraft_engine::geom::Plane { + fn plane(&self) -> solidcore_record::Plane { match &self.0 { solidcraft_engine::doc::construct::ConstructGeom::Plane(p) => *p, other => panic!("expected a plane, got {other:?}"), @@ -1728,7 +1737,7 @@ fn the_ribbed_lid_builds_the_same_body_every_time() { st.bodies .iter() .map(|b| { - let mesh = b.body.tessellate(0.1).unwrap(); + let mesh = b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.1)).unwrap(); let bits = mesh.positions.iter().fold(0u64, |acc, p| { acc.rotate_left(7).wrapping_add(p.x.to_bits() ^ p.y.to_bits().rotate_left(21) ^ p.z.to_bits().rotate_left(42)) }); diff --git a/apps/solidcraft-cli/tests/bracket_example.rs b/apps/solidcraft-cli/tests/bracket_example.rs index 8056a8786..d0da8187a 100644 --- a/apps/solidcraft-cli/tests/bracket_example.rs +++ b/apps/solidcraft-cli/tests/bracket_example.rs @@ -4,7 +4,7 @@ use std::f64::consts::PI; use serde_json::Value; -use solidcraft_engine::geom::Vec3; +use solidcore_record::Vec3; use solidcraft_engine::{Session, io, kernel}; fn assert_two_through_holes(session: &Session, stage: &str) { @@ -26,8 +26,8 @@ fn assert_two_through_holes(session: &Session, stage: &str) { let expected = 2.0 * PI * 4.0_f64.powi(2) * 6.0; assert!((removed - expected).abs() < expected * 1e-3, "{stage}: the two holes remove {removed} mm³, expected {expected} mm³"); - let before_mesh = uncut.tessellate(0.01).unwrap(); - let after_mesh = bracket.tessellate(0.01).unwrap(); + let before_mesh = uncut.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); + let after_mesh = bracket.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); let down = Vec3::new(0.0, 0.0, -1.0); for y in [-15.0, -45.0] { let center = Vec3::new(25.0, y, 1.0); diff --git a/apps/solidcraft-cli/tests/corpus/README.md b/apps/solidcraft-cli/tests/corpus/README.md index d9266d8b9..31d3f0582 100644 --- a/apps/solidcraft-cli/tests/corpus/README.md +++ b/apps/solidcraft-cli/tests/corpus/README.md @@ -1,10 +1,12 @@ # Design file corpus Designs saved by older SolidCraft builds. `tests/design_corpus.rs` opens each one with the -current build and checks that it evaluates as it did when saved (the `.expected.json` next to -it is `solidcraft-cli eval` of that file by the build that saved it: bodies, volumes, areas, -world bounding boxes), that it is upgraded to the current file format, and that damaged and -hostile variants of it never panic. +current build and checks that it is upgraded to the current file format, that it evaluates +(a feature may fail only by asking for a reference it lost to be picked again; what it rebuilds +to is today's), and that damaged and hostile variants of it never panic. The `.expected.json` +next to each is `solidcraft-cli eval` of that file by the build that saved it (bodies, volumes, +areas, world bounding boxes), kept as a record of what that build made; no test compares with +it. | File | Saved by | Era | |---|---|---| diff --git a/apps/solidcraft-cli/tests/corpus/issue-489-stacked-join.expected.json b/apps/solidcraft-cli/tests/corpus/issue-489-stacked-join.expected.json index a0bc391a6..0a42ab036 100644 --- a/apps/solidcraft-cli/tests/corpus/issue-489-stacked-join.expected.json +++ b/apps/solidcraft-cli/tests/corpus/issue-489-stacked-join.expected.json @@ -90,10 +90,6 @@ ], "timeline": [ { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 1, "ms": 0.131943, @@ -104,10 +100,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 2, "ms": 1.0812709999999999, @@ -118,10 +110,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 3, "ms": 0.450002, @@ -132,10 +120,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 4, "ms": 5.191514000000001, diff --git a/apps/solidcraft-cli/tests/corpus/issue-616-lid-ribs.expected.json b/apps/solidcraft-cli/tests/corpus/issue-616-lid-ribs.expected.json index b605b13cd..cac060415 100644 --- a/apps/solidcraft-cli/tests/corpus/issue-616-lid-ribs.expected.json +++ b/apps/solidcraft-cli/tests/corpus/issue-616-lid-ribs.expected.json @@ -54,10 +54,6 @@ ], "timeline": [ { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 1, "ms": 1.178957, @@ -68,10 +64,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 2, "ms": 83.24342399999999, @@ -82,10 +74,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 3, "ms": 0.150889, @@ -96,10 +84,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 4, "ms": 94.465481, @@ -110,10 +94,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 5, "ms": 50.426736, @@ -124,10 +104,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 6, "ms": 40.383005, @@ -138,10 +114,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 7, "ms": 59.041461000000005, @@ -152,18 +124,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [ - { - "face_shift_mm": 0.0, - "rotation_rad": 0.0, - "strategy": "planar_fallback", - "tolerance_mm": 0.0, - "translation_mm": 0.0 - } - ], - "truncated": false - }, "error": null, "id": 8, "ms": 562.5477970000001, @@ -171,13 +131,9 @@ "rolled_back": false, "suppressed": false, "type": "BoxFeature", - "warning": "Boolean retry: exact planar fallback (no displacement)" + "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 9, "ms": 89.56076, @@ -188,10 +144,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 10, "ms": 65.330634, @@ -202,10 +154,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 11, "ms": 97.229403, diff --git a/apps/solidcraft-cli/tests/corpus/move-bodies.expected.json b/apps/solidcraft-cli/tests/corpus/move-bodies.expected.json index dd2987584..8816a2e8a 100644 --- a/apps/solidcraft-cli/tests/corpus/move-bodies.expected.json +++ b/apps/solidcraft-cli/tests/corpus/move-bodies.expected.json @@ -99,10 +99,6 @@ ], "timeline": [ { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 1, "ms": 0.204585, @@ -113,10 +109,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 2, "ms": 2.318662, @@ -127,10 +119,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 3, "ms": 0.109196, @@ -141,10 +129,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 4, "ms": 0.338859, @@ -155,10 +139,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 5, "ms": 0.312259, @@ -169,10 +149,6 @@ "warning": null }, { - "boolean_diagnostics": { - "events": [], - "truncated": false - }, "error": null, "id": 6, "ms": 0.23144699999999999, diff --git a/apps/solidcraft-cli/tests/design_corpus.rs b/apps/solidcraft-cli/tests/design_corpus.rs index 0e0bdc9d1..a6fe941ce 100644 --- a/apps/solidcraft-cli/tests/design_corpus.rs +++ b/apps/solidcraft-cli/tests/design_corpus.rs @@ -1,6 +1,8 @@ -//! Designs saved by older SolidCraft builds (tests/corpus, see its README) open and evaluate as -//! they did when they were saved; damaged and hostile design files never panic. +//! Designs saved by older SolidCraft builds (tests/corpus, see its README) open, are upgraded to +//! the current format and evaluate (what they rebuild to today is today's, not what the build +//! that saved them made); damaged and hostile design files never panic. +use solidcraft_engine::geom::prelude::*; use std::path::{Path, PathBuf}; use serde_json::{Value, json}; @@ -21,67 +23,24 @@ fn open(path: &Path) -> Session { s } -/// Differences that are deliberate behaviour changes made before the file format had versions -/// (no migration can tell those files apart): (file, check, why). -const KNOWN: [(&str, &str, &str); 2] = [ - ( - "m0-revolve-primitives", - "Body1 bbox", - "partial revolves turn toward the sketch normal since ac43365 (as most parametric CAD tools do); M0 turned them the other way", - ), - ("components-arm", "body_count", "Measure counted only the root component's bodies then; it measures every placed body now"), -]; - -fn known(file: &str, check: &str) -> bool { - KNOWN.iter().any(|(f, c, _)| *f == file && *c == check) -} - -/// Volumes and areas then came from coarser tessellation (and curved booleans and fillets have -/// become exact since): the same part within this relative tolerance (the oracle's). -const REL: f64 = 1e-3; - -fn close(a: f64, b: f64, rel: f64) -> bool { - (a - b).abs() <= rel * b.abs().max(1.0) -} - +/// Every corpus design opens, is upgraded to the current format, evaluates, and saves and reads +/// back the same. A feature may fail only by asking for a reference it lost to be picked again +/// (a name saved before format 14 finds nothing today). #[test] -fn old_designs_open_and_evaluate_as_saved() { +fn old_designs_open_upgrade_and_evaluate() { let mut problems = Vec::new(); for p in corpus() { let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); - let want: Value = serde_json::from_slice(&std::fs::read(p.with_extension("expected.json")).unwrap()).unwrap(); let mut s = open(&p); for r in &s.model.results { - if let Some(e) = &r.error { + if let Some(e) = r.error.as_deref().filter(|e| solidcraft_engine::doc::reselect_parts(e).is_none()) { problems.push(format!("{name}: feature {}: {e}", r.id)); } } assert_eq!(s.doc.format, solidcraft_engine::doc::format::format_string(solidcraft_engine::doc::format::FORMAT), "{name}: upgraded"); let got = s.execute("inspect.measure", &json!({})).unwrap(); - if got["body_count"] != want["body_count"] && !known(&name, "body_count") { - problems.push(format!("{name}: {} bodies, saved with {}", got["body_count"], want["body_count"])); - } - for w in want["bodies"].as_array().into_iter().flatten() { - let bname = w["name"].as_str().unwrap_or_default(); - let Some(g) = got["bodies"].as_array().into_iter().flatten().find(|g| g["name"] == w["name"]) else { - problems.push(format!("{name}: body {bname} missing")); - continue; - }; - for k in ["volume_mm3", "area_mm2"] { - let (a, b) = (g[k].as_f64().unwrap_or(f64::NAN), w[k].as_f64().unwrap_or(f64::NAN)); - if !close(a, b, REL) { - problems.push(format!("{name}: {bname} {k} {a} (saved {b})")); - } - } - if known(&name, &format!("{bname} bbox")) { - continue; - } - for (end, i) in [("min", 0), ("min", 1), ("min", 2), ("max", 0), ("max", 1), ("max", 2)] { - let (a, b) = (g["bbox"][end][i].as_f64().unwrap_or(f64::NAN), w["bbox"][end][i].as_f64().unwrap_or(f64::NAN)); - if (a - b).abs() > 1e-3 * b.abs().max(1.0) { - problems.push(format!("{name}: {bname} bbox {end}[{i}] {a} (saved {b})")); - } - } + if got["body_count"].as_u64().unwrap_or(0) == 0 { + problems.push(format!("{name}: no bodies")); } // Saved again, it reads back the same. let again = solidcraft_engine::doc::Document::from_json(&s.doc.to_json()).unwrap(); @@ -94,40 +53,48 @@ fn old_designs_open_and_evaluate_as_saved() { } /// Names saved before format 14 were worked out from geometry, pieces of a split face numbered by -/// where their centres lay (`F2:top#2`). They keep naming the faces they named: marked as such, -/// they are found as the build that saved them found them, without new notes. +/// where their centres lay (`F2:top#2`). They open marked as such and find no face or edge today: +/// each feature holding one fails, asking for its reference to be picked again, and the rest of +/// the design builds. #[test] -fn names_saved_before_exact_history_find_the_faces_they_named() { +fn names_saved_before_exact_history_ask_for_their_faces_again() { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/naming-split-pieces.solidcraft"); let s = open(&path); let feature = |name: &str| s.doc.features.iter().find(|f| f.name == name).unwrap_or_else(|| panic!("{name}")); assert_eq!(feature("Round").edge_names, vec!["?F2:side:l2|F2:top#2".to_string()]); assert_eq!(feature("Bevel").edge_names, vec!["?F2:side:l4|F2:top#1".to_string()]); assert_eq!(feature("Raise").face_names, vec!["?F2:top#1".to_string()]); - for r in &s.model.results { - assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning); + let asked = |name: &str| { + let r = s.model.result(feature(name).id).unwrap_or_else(|| panic!("{name}")); + r.error.as_deref().and_then(solidcraft_engine::doc::reselect_parts).map(|(f, reference)| (f.to_string(), reference.to_string())) + }; + assert_eq!(asked("Round"), Some(("Round".into(), "?F2:side:l2|F2:top#2".into()))); + assert_eq!(asked("Bevel"), Some(("Bevel".into(), "?F2:side:l4|F2:top#1".into()))); + assert_eq!(asked("Raise"), Some(("Raise".into(), "?F2:top#1".into()))); + for r in s.model.results.iter().filter(|r| !["Round", "Bevel", "Raise"].contains(&r.name.as_str())) { + assert!(r.error.is_none(), "{}: {:?}", r.name, r.error); } - // The raised piece is the left one, as saved (the stored point is on it). - let state = s.model.state(); - let solid = |p: [f64; 3]| state.bodies.iter().any(|b| b.body.contains(solidcraft_engine::geom::Vec3::new(p[0], p[1], p[2]))); - assert!(solid([7.0, 15.0, 11.0]) && !solid([32.0, 15.0, 11.0])); + assert!(!s.model.state().bodies.is_empty()); } -/// Body names saved before format 14 name the pieces of a split body in the kernel's shell order. -/// The features after the split that refer to a piece by its body name still find that piece: -/// the far one stays `Body1` (chamfered), the near one `Body1 (1)` (filleted, coloured). +/// Body names saved before format 14 named the pieces of a split body in the kernel's shell +/// order: such a design opens with every feature marked `shell_piece_order` and evaluates, each +/// body name it stores naming a piece. (Which piece takes which name is not promised to be as it +/// was saved.) Its fillet and chamfer hold edge names saved then, which find nothing today: they +/// ask for their edges to be picked again. #[test] -fn body_names_saved_before_exact_history_keep_their_pieces() { +fn body_names_saved_before_exact_history_open_marked_and_evaluate() { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/split-body-pieces.solidcraft"); let s = open(&path); assert!(s.doc.features.iter().all(|f| f.shell_piece_order), "every saved feature keeps the shell order"); for r in &s.model.results { - assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning); + let asked = r.error.as_deref().and_then(solidcraft_engine::doc::reselect_parts); + assert!(r.error.is_none() || asked.is_some_and(|(_, reference)| reference.starts_with('?')), "{}: {:?}", r.name, r.error); } let state = s.model.state(); - let piece = |name: &str| state.bodies.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("{name}")); - let solid = |name: &str, p: [f64; 3]| piece(name).body.contains(solidcraft_engine::geom::Vec3::new(p[0], p[1], p[2])); - assert!(solid("Body1", [20.0, 24.0, 5.0]) && solid("Body1 (1)", [20.0, 6.0, 5.0])); + for name in ["Body1", "Body1 (1)"] { + assert!(state.bodies.iter().any(|b| b.name == name), "{name}"); + } assert!(s.doc.appearances.bodies.contains_key("Body1 (1)")); } @@ -173,6 +140,7 @@ fn flat_face_attachments() -> Vec<(String, String, usize, Option<(u32, bool)>, O for p in corpus() { let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); let mut s = open(&p); + let failed_on_open: Vec = s.model.results.iter().filter(|r| r.error.is_some()).map(|r| r.id).collect(); let state = s.model.state(); let placed = s.placed_document(); let mut picks = Vec::new(); @@ -180,7 +148,7 @@ fn flat_face_attachments() -> Vec<(String, String, usize, Option<(u32, bool)>, O let Some(body) = state.bodies.iter().find(|b| b.definition_name() == definition && placed.model_body_component(b) == component) else { continue; }; - let mesh = body.body.tessellate(0.01).unwrap(); + let mesh = body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); for index in 0..body.body.face_count() { if body.body.planar_face(index).is_none() { continue; @@ -224,7 +192,8 @@ fn flat_face_attachments() -> Vec<(String, String, usize, Option<(u32, bool)>, O let known = known_without_attachment(&name, &body, normal, distance); out.push((name.clone(), body, index, known, problem)); } - assert!(s.model.results.iter().all(|r| r.error.is_none()), "{name}: left with errors after undo"); + let failed: Vec = s.model.results.iter().filter(|r| r.error.is_some()).map(|r| r.id).collect(); + assert_eq!(failed, failed_on_open, "{name}: undo leaves the features that failed on opening, and only those, failed"); } out } diff --git a/apps/solidcraft-cli/tests/mcp_connect.rs b/apps/solidcraft-cli/tests/mcp_connect.rs index 1475f40d7..26e1ffb16 100644 --- a/apps/solidcraft-cli/tests/mcp_connect.rs +++ b/apps/solidcraft-cli/tests/mcp_connect.rs @@ -263,3 +263,110 @@ mod setup { assert!(json_of(&pkg.join("claude_desktop_config.json"))["mcpServers"]["solidcraft"].is_object()); } } + +/// Scratch files belong to the CLI process; exercise real startup, requests and shutdown. +mod scratch_cleanup { + use super::*; + use std::path::{Path, PathBuf}; + + fn command(case: &str) -> (PathBuf, Command) { + let dir = std::env::temp_dir().join(format!("solidcraft-mcp-lifecycle-{case}-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")); + command + .args(["mcp", "--headless"]) + .env("TMPDIR", &dir) + .env("TMP", &dir) + .env("TEMP", &dir) + .env("SOLIDCRAFT_RECOVERY_DIR", dir.join("recovery")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + (dir, command) + } + + fn scratch_folders(dir: &Path) -> Vec { + std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.file_name().unwrap().to_string_lossy().starts_with("solidcraft-mcp-")) + .collect() + } + + fn initialize() -> Value { + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}) + } + + fn run(mut command: Command, request: Value) -> std::process::Output { + let mut child = command.spawn().unwrap(); + writeln!(child.stdin.take().unwrap(), "{request}").unwrap(); + child.wait_with_output().unwrap() + } + + #[test] + fn eof_removes_only_the_process_scratch_folder() { + let (dir, command) = command("eof"); + let unrelated = dir.join("solidcraft-mcp-unrelated"); + std::fs::create_dir(&unrelated).unwrap(); + let out = run(command, initialize()); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let reply: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert!(reply.get("result").is_some(), "{reply}"); + assert_eq!(scratch_folders(&dir), vec![unrelated]); + assert!(dir.join("recovery").is_dir(), "cleanup must leave the recovery folder alone"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn startup_error_removes_the_process_scratch_folder() { + let (dir, mut command) = command("startup-error"); + let out = command.args(["--param-check", "invalid"]).stdin(Stdio::null()).output().unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success()); + assert!(stderr.contains("--param-check wants off, warn or strict"), "{stderr}"); + assert!(scratch_folders(&dir).is_empty(), "startup error left a scratch folder in {dir:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn shutdown_preserves_nonempty_scratch_folder() { + let (dir, mut command) = command("nonempty"); + let mut child = command.spawn().unwrap(); + let mut input = child.stdin.take().unwrap(); + writeln!(input, "{}", initialize()).unwrap(); + let mut reply = String::new(); + BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap(); + let reply: Value = serde_json::from_str(&reply).unwrap(); + assert!(reply.get("result").is_some(), "{reply}"); + let scratch = scratch_folders(&dir); + assert_eq!(scratch.len(), 1); + let saved = scratch[0].join("keep.txt"); + std::fs::write(&saved, "saved output").unwrap(); + drop(input); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(std::fs::read_to_string(saved).unwrap(), "saved output"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn failed_screenshot_scratch_folder_is_removed_without_a_path_scope() { + let (dir, mut command) = command("screenshot"); + command.arg("--allow-any-path"); + // A headless server cannot capture a window. The request still allocates a scratch + // path before the backend refuses it, without relying on a GPU or installed renderer. + let out = run( + command, + json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "screenshot", "arguments": {"source": "window"}}, + }), + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let reply: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(reply["result"]["isError"], true, "{reply}"); + assert!(reply["result"]["content"][0]["text"].as_str().unwrap().contains("the window gave no picture"), "{reply}"); + assert!(scratch_folders(&dir).is_empty(), "failed screenshot left a scratch folder in {dir:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/apps/solidcraft-cli/tests/model_cache.rs b/apps/solidcraft-cli/tests/model_cache.rs index 6de8c2e89..ff94461d9 100644 --- a/apps/solidcraft-cli/tests/model_cache.rs +++ b/apps/solidcraft-cli/tests/model_cache.rs @@ -63,7 +63,7 @@ fn model(name: &str, s: &Session) -> Value { .iter() .map(|r| json!({"id": r.id, "name": r.name, "error": r.error, "warning": r.warning, "skipped": r.skipped, "state": state(name, &r.state)})) .collect(); - json!({"results": results, "world": state(name, &s.world_state())}) + json!({"results": results, "world": state(name, &s.world_state().unwrap())}) } /// The same edit on both: a parameter's value when the design has one, else a new body. @@ -289,6 +289,60 @@ fn undoing_an_edit_after_opening_reuses_the_saved_results() { let _ = std::fs::remove_file(format!("{}.bak", path.display())); } +/// A saved model holds the results of the body check mode it was evaluated under: opened under +/// the same mode it is taken as it is, under another the design is evaluated again. +#[test] +fn a_model_saved_under_another_check_mode_is_evaluated_again() { + let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap(); + let mut built = Session::default(); + for c in (plate.script)()["commands"].as_array().unwrap() { + built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let path = temp("mode"); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let same = open(&path); + assert_eq!(same.model.validation(), built.model.validation()); + assert_eq!(same.model.recomputed, 0, "taken from the file"); + let mut other = Session::default(); + other.set_validation(solidcraft_engine::kernel::Validation::EachStep); + assert_ne!(other.validation(), built.model.validation()); + other.execute("doc.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(other.validation(), solidcraft_engine::kernel::Validation::EachStep); + assert!(other.model.recomputed > 0, "evaluated again under its own mode"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} + +/// A body made by rounds keeps, in the saved model, the rounds and the body they were made on: a +/// later round at the corner where they meet blends them again with it whether the design was +/// opened from its model or evaluated anew. Two edges of a 20 mm box rounded r2 (a mitre at the +/// corner (20, 0, 20)), saved; opened, the upright edge there rounded r3: the corner all three +/// rounded at once make (SMLib's setback corner, kernel `three_rounds_at_a_corner`), 15 faces and +/// 7928.142563938 mm³, the same body as the design evaluated anew. +#[test] +fn a_later_round_after_opening_blends_the_saved_rounds_again() { + let mut built = Session::default(); + built.execute("solid.box", &json!({"length": 20, "width": 20, "height": 20, "body_name": "Box"})).unwrap(); + built.execute("solid.fillet", &json!({"edges": [[20, 10, 20], [10, 0, 20]], "radius": 2})).unwrap(); + let path = temp("later-round"); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + let mut cached = open(&path); + assert_eq!(cached.model.last_recomputed, 0, "opened without evaluating"); + let mut rebuilt = Session::new(solidcraft_engine::io::read_design(&bytes).unwrap()); + for s in [&mut cached, &mut rebuilt] { + s.execute("solid.fillet", &json!({"edges": [[20, 0, 10]], "radius": 3})).unwrap(); + let st = s.model.state(); + let b = &st.body("Box").unwrap().body; + let v = solidcraft_engine::kernel::measure(b).unwrap().volume; + assert_eq!(b.face_count(), 15); + assert!((v - 7928.142563938).abs() < 1e-6, "{v}"); + } + assert_eq!(model("later round", &cached), model("later round", &rebuilt)); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} + /// A design saved before body names were pinned (#6403) pins them as it opens, as its first /// command would, and opening it is no change. That command pinned them as part of itself, so /// undoing it went back to the unpinned design, which no evaluated result matched: the first diff --git a/apps/solidcraft-cli/tests/naming_corpus.rs b/apps/solidcraft-cli/tests/naming_corpus.rs new file mode 100644 index 000000000..bb43fbe8b --- /dev/null +++ b/apps/solidcraft-cli/tests/naming_corpus.rs @@ -0,0 +1,404 @@ +//! Every design of the corpus loads, two builds of it name its faces and edges alike, and a +//! name it stores that no longer finds its face or edge fails its feature. The stored names are +//! the fillet and chamfer edges, the faces a feature picks, the face a sketch sits on and the +//! sheet metal edges; one that finds nothing (`gone`, a sketch's face `lost`) must leave its +//! feature failed (it asks for the reference to be picked again, never takes another face or +//! edge), and a design that no longer loads fails the test. A build's names are each face's and +//! edge's name with where it is (its area and centre, its length and middle); the second build +//! must give the same, and its stored names must find the same faces and edges. +//! +//! Face and edge indices are left out: they are the kernel's order, which a rebuild need not +//! keep (a fillet's or a boolean's faces come out in another order from one build to the next). +//! How many faces a body has and what each is called is the kernel's business, not this test's. +//! +//! The corpus is the action matrix's (the old design files in `tests/corpus`, the examples, the +//! demo and typical designs in `tests/action_matrix/designs`, the reference recipes), the sample +//! designs, the engine's design fixtures and the older designs kept by the hole matrix, taper +//! and projection tests. + +use solidcraft_engine::geom::prelude::*; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use serde_json::{Value, json}; +use solidcore_record::Vec3; +use solidcraft_engine::Session; +use solidcraft_engine::doc::{FaceAttachmentStatus, Feature, FeatureKind, ModelBody, ModelState, PlaneRef, naming}; + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap() +} + +/// Where a design comes from. +enum Source { + File(PathBuf), + Sample(fn() -> Value), +} + +/// Every design of the corpus: (`/`, where it comes from). +fn designs() -> Vec<(String, Source)> { + let root = root(); + let mut out = Vec::new(); + let mut add = |prefix: &str, dir: PathBuf, ext: &str| { + let Ok(rd) = std::fs::read_dir(&dir) else { return }; + let mut v: Vec = rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == ext)).collect(); + v.sort(); + for p in v { + let stem = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); + out.push((format!("{prefix}/{stem}"), Source::File(p))); + } + }; + add("corpus", root.join("apps/solidcraft-cli/tests/corpus"), "solidcraft"); + add("examples", root.join("examples"), "json"); + add("examples", root.join("examples/acceptance"), "json"); + add("regressions", root.join("examples/regressions"), "json"); + add("demo", root.join("examples/demo"), "json"); + add("typical", root.join("tests/action_matrix/designs"), "json"); + add("demo", root.join("tests/action_matrix/designs"), "solidcraft"); + add("fixtures", root.join("crates/engine/src/tests/fixtures"), "solidcraft"); + add("hole_matrix", root.join("tests/hole_matrix/old-0.9"), "json"); + add("taper", root.join("tests/taper/before-1014"), "json"); + add("projection", root.join("tests/projection/before-1508"), "json"); + let mut cases: Vec = + std::fs::read_dir(root.join("tests/oracle")).unwrap().flatten().map(|e| e.path()).filter(|p| p.join("recipe.json").is_file()).collect(); + cases.sort(); + for c in cases { + out.push((format!("oracle/{}", c.file_name().unwrap_or_default().to_string_lossy()), Source::File(c.join("recipe.json")))); + } + for sample in solidcraft_engine::sample::samples() { + let stem: String = sample.name.to_lowercase().split_whitespace().collect::>().join("-"); + out.push((format!("samples/{stem}"), Source::Sample(sample.script))); + } + out +} + +/// Build a design: a design file (also a design saved as JSON) is opened, a script is run. +fn load(source: &Source) -> Result { + let mut s = Session::default(); + let script = match source { + Source::Sample(script) => script(), + Source::File(path) if path.extension().is_some_and(|x| x == "solidcraft") => { + s.execute("doc.open", &json!({"path": path.to_string_lossy()})).map_err(|e| e.to_string())?; + return Ok(s); + } + Source::File(path) if path.file_name().is_some_and(|n| n == "recipe.json") => { + let out = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).arg("recipe").arg(path).output().map_err(|e| e.to_string())?; + if !out.status.success() { + return Err(format!("recipe: {}", String::from_utf8_lossy(&out.stderr).trim())); + } + serde_json::from_slice(&out.stdout).map_err(|e| e.to_string())? + } + Source::File(path) => { + let v: Value = serde_json::from_slice(&std::fs::read(path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; + if v.get("features").is_some() { + s.execute("doc.open", &json!({"path": path.to_string_lossy()})).map_err(|e| e.to_string())?; + return Ok(s); + } + match v.get("steps").and_then(Value::as_array) { + // The demo's steps: an MCP `execute` each. + Some(steps) => { + json!({"commands": steps.iter().map(|st| json!({"command": st["command"], "params": st["params"]})).collect::>()}) + } + None => v, + } + } + }; + s.run_script(&script).map_err(|e| e.to_string())?; + if s.active_sketch.is_some() { + let _ = s.execute("sketch.finish", &json!({})); + } + Ok(s) +} + +/// What decides a name beyond its text: `[geometric]` when it was worked out from geometry, not +/// exact history. +fn flags(list: &[(bool, &str)]) -> String { + let set: Vec<&str> = list.iter().filter(|(on, _)| *on).map(|(_, f)| *f).collect(); + if set.is_empty() { String::new() } else { format!(" [{}]", set.join(", ")) } +} + +/// Where each named face and edge of a body is, by name, sorted: a face's area and centre, an +/// edge's length and middle, from the body's mesh. Two builds that name their faces alike give +/// the same list. +fn placed_names(b: &ModelBody) -> Vec<(String, [f64; 4])> { + if b.body.is_mesh() { + return Vec::new(); + } + let m = b.mesh(); + let faces = naming::face_names(b); + let mut sums = vec![[0.0f64; 4]; faces.len()]; + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + let [p, q, r] = t.map(|i| m.positions.get(i as usize).copied().unwrap_or(Vec3::ZERO)); + let area = (q - p).cross(r - p).len() / 2.0; + let c = (p + q + r) / 3.0; + if let Some(s) = sums.get_mut(*f as usize) { + *s = [s[0] + area, s[1] + area * c.x, s[2] + area * c.y, s[3] + area * c.z]; + } + } + let mut out: Vec<(String, [f64; 4])> = faces + .iter() + .zip(&sums) + .map(|(n, s)| { + let a = s[0].max(1e-300); + (format!("{} face {n}", b.name), [s[0], s[1] / a, s[2] / a, s[3] / a]) + }) + .collect(); + for (n, line) in naming::edge_names(b).iter().zip(&m.edges) { + let length: f64 = line.windows(2).map(|w| w[1].dist(w[0])).sum(); + let mid = line.iter().fold(Vec3::ZERO, |acc, p| acc + *p) / (line.len().max(1) as f64); + out.push((format!("{} edge {n}", b.name), [length, mid.x, mid.y, mid.z])); + } + out.sort_by(|x, y| x.0.cmp(&y.0).then(x.1.partial_cmp(&y.1).unwrap_or(std::cmp::Ordering::Equal))); + out +} + +fn face_label(st: &ModelState, body: usize, face: usize) -> String { + match st.bodies.get(body) { + Some(b) => format!("{} face {}", b.name, naming::face_names(b).get(face).map(String::as_str).unwrap_or("?")), + None => format!("body #{body} face #{face}"), + } +} + +/// Every name feature `f` stores, with what it finds in the model before it, as a feature +/// rebuilding finds it, and whether it finds anything. +fn record_refs(out: &mut Vec<(String, bool)>, s: &Session, f: &Feature) { + let doc = &*s.doc; + let who = format!("ref {} ({})", f.name, f.id); + let before = s.model.state_before(f.id); + // Faces a feature picks by point and stores by name (shell, draft, hole, …). + let explicit_emboss = matches!(&f.kind, FeatureKind::Emboss { face: Some(_), .. }); + if f.face_names.iter().any(|n| !n.is_empty()) { + let fst = solidcraft_engine::doc::face_point_state(doc, &before, &f.kind, f.component).unwrap(); + for (k, (p, n)) in f.kind.face_points().into_iter().zip(&f.face_names).enumerate() { + if n.is_empty() { + continue; + } + let (found, ok) = if explicit_emboss { + ("not checked (a cylindrical emboss finds its face on its own body)".to_string(), true) + } else { + match naming::locate_face_on_body(&fst, f.kind.face_body(), n, p) { + Some(hit) => (format!("{}{}", face_label(&fst, hit.body, hit.face), flags(&[(!hit.verified, "geometric")])), true), + None => ("gone".into(), false), + } + }; + out.push((format!("{who} face {k} `{n}` -> {found}"), ok)); + } + } + // Edges a feature picks by point and stores by name. + if f.edge_names.iter().any(|n| !n.is_empty()) { + let edge = |out: &mut Vec<(String, bool)>, b: &ModelBody, k: usize, n: &str, p: Vec3| { + let (found, ok) = match naming::locate_edge(b, n, p) { + Ok(hit) => ( + format!( + "{} edge {}{}", + b.name, + naming::edge_names(b).get(hit.edge).map(String::as_str).unwrap_or("?"), + flags(&[(!hit.verified, "geometric")]) + ), + true, + ), + Err(e) => (format!("gone ({e})"), false), + }; + out.push((format!("{who} edge {k} `{n}` -> {found}"), ok)); + }; + let named = |k: usize| f.edge_names.get(k).filter(|n| !n.is_empty()); + match &f.kind { + FeatureKind::Fillet { edges, body, .. } | FeatureKind::Chamfer { edges, body, .. } => { + let pts: Vec = solidcraft_engine::doc::plain(edges); + match solidcraft_engine::doc::blend_target(&before, body, &pts).ok().and_then(|i| before.bodies.get(i)) { + Some(b) => { + for (k, p) in pts.iter().enumerate() { + if let Some(n) = named(k) { + edge(out, b, k, n, *p); + } + } + } + None => out.push((format!("{who} edges: no body to round"), false)), + } + } + FeatureKind::SheetConvert { body, bends, .. } => match before.body(body) { + Some(b) => { + for (k, p) in solidcraft_engine::doc::plain::(bends).iter().enumerate() { + if let Some(n) = named(k) { + edge(out, b, k, n, *p); + } + } + } + None => out.push((format!("{who} bends: body `{body}` gone"), false)), + }, + // Sheet metal edges are named by the sheet's panels, and found on its sheets. + FeatureKind::SheetFlange { .. } | FeatureKind::SheetHem { .. } => { + let pts: Vec = match &f.kind { + FeatureKind::SheetFlange { edges, .. } => edges.iter().map(|e| e.point.0).collect(), + FeatureKind::SheetHem { edges, .. } => solidcraft_engine::doc::plain(edges), + _ => Vec::new(), + }; + for (k, p) in pts.iter().enumerate() { + let Some(n) = named(k) else { continue }; + let on: Vec<&str> = before.sheets.iter().filter(|sh| sh.edge_by_name(n, *p).is_some()).map(|sh| sh.body.as_str()).collect(); + let found = if on.is_empty() { "gone".to_string() } else { format!("sheet edge on {}", on.join(", ")) }; + out.push((format!("{who} sheet edge {k} `{n}` -> {found}"), !on.is_empty())); + } + } + other => { + for (k, n) in f.edge_names.iter().enumerate().filter(|(_, n)| !n.is_empty()) { + out.push((format!("{who} edge {k} `{n}` -> not checked ({})", other.type_name()), true)); + } + } + } + } + // The face a sketch sits on. + if let FeatureKind::Sketch { plane: PlaneRef::Face { name, anchor, at, .. }, .. } = &f.kind { + let mut ok = true; + let status = match doc.sketch_face_attachment(f.id, &s.model) { + FaceAttachmentStatus::Healthy { target, .. } => { + let faces = match before.body(&target.body) { + Some(b) => match doc.anchored_face_indices(&before, b, &target) { + Ok((indices, note)) => { + let names = naming::face_names(b); + let mut list: Vec<&str> = indices.iter().map(|i| names.get(*i).map(String::as_str).unwrap_or("?")).collect(); + list.sort(); + format!("{} faces {}{}", b.name, list.join(", "), flags(&[(note.is_some(), "changed cap")])) + } + Err(e) => { + ok = false; + format!("no faces ({e})") + } + }, + None => { + ok = false; + format!("body `{}` gone", target.body) + } + }; + format!("healthy: {faces}") + } + FaceAttachmentStatus::Lost { message, .. } => { + ok = false; + format!("lost: {message}") + } + FaceAttachmentStatus::Legacy { .. } => match name { + // The face its name finds, as the sketch finds it. + Some(n) => { + let fst = solidcraft_engine::doc::state_in_frame(doc, &before, f.component).unwrap(); + match naming::locate_face(&fst, n, *at) { + Some(hit) => format!("by name: {}{}", face_label(&fst, hit.body, hit.face), flags(&[(!hit.verified, "geometric")])), + None => { + ok = false; + "by name: gone".into() + } + } + } + None => "by its pick".into(), + }, + FaceAttachmentStatus::Sheet { .. } => "sheet face".into(), + FaceAttachmentStatus::Fixed { .. } => "fixed".into(), + }; + let stored = match (anchor, name) { + (Some(a), _) => { + let kind = + a.target.certificate.as_ref().and_then(|c| serde_json::to_value(c).ok()).and_then(|v| v["kind"].as_str().map(String::from)); + format!("`{}` on {} ({})", a.target.name, a.target.body, kind.unwrap_or_else(|| "no certificate".into())) + } + (None, Some(n)) => format!("`{n}`"), + (None, None) => "by its pick".into(), + }; + out.push((format!("{who} plane {stored} -> {status}"), ok)); + } +} + +/// A build of a design: where its faces and edges are by name, and what every name it stores +/// finds. +struct Build { + names: Vec<(String, [f64; 4])>, + refs: Vec<(String, bool)>, +} + +fn build(s: &Session) -> Build { + let names = s.model.state().bodies.iter().flat_map(placed_names).collect(); + let mut refs = Vec::new(); + for f in s.doc.features.iter().filter(|f| !f.suppressed) { + let from = refs.len(); + record_refs(&mut refs, s, f); + // A name that finds nothing is sound when its feature fails: it asks for the reference + // to be picked again. + if s.model.result(f.id).is_some_and(|r| r.error.is_some()) { + refs.iter_mut().skip(from).for_each(|(_, ok)| *ok = true); + } + } + Build { names, refs } +} + +/// Where two builds name their faces and edges apart (at most `cap` of them): a name only one +/// has, or a face or edge of that name somewhere else (1e-6 of its size, to the mesh's rounding). +fn differences(a: &Build, b: &Build, cap: usize) -> Vec { + let mut out = Vec::new(); + if a.names.len() != b.names.len() { + out.push(format!("{} named faces and edges, then {}", a.names.len(), b.names.len())); + } + for ((n, x), (m, y)) in a.names.iter().zip(&b.names) { + let scale = x.iter().chain(y).fold(1.0f64, |s, v| s.max(v.abs())); + if n != m || x.iter().zip(y).any(|(p, q)| (p - q).abs() > 1e-6 * scale) { + out.push(format!("{n} at {x:?}, then {m} at {y:?}")); + } + } + for ((r, _), (q, _)) in a.refs.iter().zip(&b.refs) { + if r != q { + out.push(format!("{r}, then {q}")); + } + } + if a.refs.len() != b.refs.len() { + out.push(format!("{} stored names, then {}", a.refs.len(), b.refs.len())); + } + out.truncate(cap); + out +} + +/// Designs whose names differ from one build to the next today: (design, why). Their +/// differences are printed, not failed on, until the cause is fixed; a stored name that finds +/// nothing still fails. +const UNSTABLE: [(&str, &str); 1] = [( + "regressions/closed_sweep_torus_cut", + "the halves of each swept wall lie level along every axis, so which is `#1` and which `#2` follows the order the kernel gives the faces in, which changes from one build to the next", +)]; + +#[test] +fn corpus_designs_name_alike_every_build_and_fail_where_a_reference_is_gone() { + let designs = designs(); + let next = std::sync::atomic::AtomicUsize::new(0); + let results = std::sync::Mutex::new(Vec::new()); + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(designs.len().max(1)); + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| { + while let Some((name, source)) = designs.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) { + let got = load(source).and_then(|first| Ok((build(&first), build(&load(source)?)))); + results.lock().unwrap_or_else(|e| e.into_inner()).push((name.clone(), got)); + } + }); + } + }); + let mut results = results.into_inner().unwrap_or_else(|e| e.into_inner()); + results.sort_by(|a, b| a.0.cmp(&b.0)); + let mut problems = Vec::new(); + for (name, got) in &results { + let (first, second) = match got { + Ok(builds) => builds, + Err(e) => { + problems.push(format!("{name}: does not load: {e}")); + continue; + } + }; + let lost: Vec<&str> = first.refs.iter().filter(|(_, ok)| !ok).map(|(r, _)| r.as_str()).collect(); + if !lost.is_empty() { + problems.push(format!("{name}: stored names that find nothing, in features that build:\n {}", lost.join("\n "))); + } + let apart = differences(first, second, 40); + if !apart.is_empty() { + match UNSTABLE.iter().find(|(design, _)| design == name) { + Some((_, why)) => eprintln!("{name} (not checked: {why}):\n {}", apart.join("\n ")), + None => problems.push(format!("{name}: two builds name it apart (first, then second):\n {}", apart.join("\n "))), + } + } + } + assert!(problems.is_empty(), "{} of {} design(s) of the corpus:\n{}", problems.len(), results.len(), problems.join("\n")); +} diff --git a/apps/solidcraft-cli/tests/rebuild_topology.rs b/apps/solidcraft-cli/tests/rebuild_topology.rs index 26721787b..4fce82899 100644 --- a/apps/solidcraft-cli/tests/rebuild_topology.rs +++ b/apps/solidcraft-cli/tests/rebuild_topology.rs @@ -9,6 +9,7 @@ use std::path::{Path, PathBuf}; use serde_json::{Value, json}; use solidcraft_engine::Session; use solidcraft_engine::doc::kernel::{FaceSurface, face_surface}; +use solidcraft_engine::geom::prelude::*; fn root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap() @@ -31,7 +32,7 @@ struct Topology { /// Every solid body's topology, by name. fn topology(s: &Session) -> BTreeMap { - let st = s.world_state(); + let st = s.world_state().unwrap(); st.bodies .iter() .filter(|b| !b.body.is_mesh()) @@ -142,16 +143,14 @@ fn a_parameter_edit_rebuilds_like_a_fresh_build_and_reverts_exactly() { assert!(problems.is_empty(), "{}", problems.join("\n")); } -/// The README demo's Raspberry Pi case (`examples/demo/enclosure_ui_mcp.py --story pi`): its -/// face count after each feature, and each outer side (the four walls and the bottom) one face -/// throughout: (a) built at height 24, (b) built at 24 and changed to 32 in Parameters, (c) -/// built at 32. The port cut-outs and the floor vents used to split the long wall (or the end -/// wall at 24) into strips along the openings' tops and bottoms. +/// The README demo's Raspberry Pi case (`examples/demo/enclosure_ui_mcp.py --story pi`): after +/// each feature, each outer side (the four walls and the bottom) is one face and the case is as +/// tall as its height, and a height changed in Parameters rebuilds the same topology as one +/// built at that height: (a) built at height 24, (b) built at 24 and changed to 32, (c) built at +/// 32. The port cut-outs and the floor vents used to split the long wall (or the end wall at 24) +/// into strips along the openings' tops and bottoms. #[test] -fn pi_case_faces_per_step_at_both_heights() { - // Sketch1 (1) .. RectangularPattern2 (14): the faces once features 1..=k are built. - const FACES: [(usize, usize); 13] = - [(2, 6), (3, 10), (4, 19), (5, 19), (6, 25), (7, 43), (8, 43), (9, 55), (10, 55), (11, 59), (12, 59), (13, 63), (14, 79)]; +fn pi_case_sides_stay_whole_at_both_heights() { let dir = scratch_dir("pi"); let design: Value = serde_json::from_slice(&std::fs::read(root().join("tests/action_matrix/designs/pi-case.sc")).unwrap()).unwrap(); let at = |height: &str, file: &str| { @@ -174,12 +173,13 @@ fn pi_case_faces_per_step_at_both_heights() { for (case, s, h) in [("(a) at 24", a, 24.), ("(b) 24 changed to 32", b, 32.), ("(c) at 32", c, 32.)] { assert!(errors(&s).is_empty(), "{case}: features fail: {:?}", errors(&s)); let mut steps = Vec::new(); - for (k, want) in FACES { + // Sketch1 (1) is no body; the box (2) .. RectangularPattern2 (14). + for k in 2..=14 { let mut t = s.scratch(); t.execute("timeline.rollback", &json!({"position": k})).unwrap(); - let st = t.world_state(); + let st = t.world_state().unwrap(); let body = st.bodies.iter().find(|b| b.name == "Body1").unwrap(); - assert_eq!(body.body.face_count(), want, "{case}: faces after feature {k}"); + assert!(body.body.validity().is_empty(), "{case}: after feature {k}: {:?}", body.body.validity()); // Each outer side: the faces in its plane. for (n, d) in [([0., -1., 0.], 33.), ([0., 1., 0.], 33.), ([-1., 0., 0.], 47.5), ([1., 0., 0.], 47.5), ([0., 0., -1.], 0.)] { let on = (0..body.body.face_count()) diff --git a/apps/solidcraft-cli/tests/run_results.rs b/apps/solidcraft-cli/tests/run_results.rs index 9a99a51f1..60131fe3b 100644 --- a/apps/solidcraft-cli/tests/run_results.rs +++ b/apps/solidcraft-cli/tests/run_results.rs @@ -229,7 +229,9 @@ fn known_pending_concepts_and_released_files_round_trip_with_inert_metadata() { assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); let reopened = io::read_design(&std::fs::read(&destination).unwrap()).unwrap(); assert_eq!(reopened.metadata, document.metadata); - assert_eq!(reopened.name, document.name); + // #4907: `run --save` maps to Save As, and a borrowed design name + // follows the destination file's stem instead of keeping the old name. + assert_eq!(reopened.name, format!("resaved-{index}")); assert_eq!(reopened.features, document.features); assert_eq!(std::fs::read(&source).unwrap(), bytes); } diff --git a/apps/solidcraft-cli/tests/run_strict.rs b/apps/solidcraft-cli/tests/run_strict.rs index f76299463..590ae6cb6 100644 --- a/apps/solidcraft-cli/tests/run_strict.rs +++ b/apps/solidcraft-cli/tests/run_strict.rs @@ -65,7 +65,10 @@ fn allow_errors_writes_anyway_and_a_saved_design_keeps_failing() { let output = cli().arg("run").arg(dir.broken_script()).arg("--allow-errors").arg("--out").arg(&step).arg("--save").arg(&saved).output().unwrap(); assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); let measured: Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(measured["total"]["volume_mm3"], json!(4000.0), "the box without its fillet"); + // SMLib integrates the volume (a relative accuracy of 1e-4 asked for; a box comes out within + // a few units in the last place), so the box's 4000 mm³ is checked to 1e-9, not to the bit. + let volume = measured["total"]["volume_mm3"].as_f64().unwrap(); + assert!((volume - 4000.0).abs() < 4000.0 * 1e-9, "the box without its fillet: {volume}"); assert!(std::fs::metadata(&step).unwrap().len() > 0); // The saved design still holds the failing feature: running it fails too, `eval` reports it. let again = dir.0.join("again.step"); diff --git a/apps/solidcraft-cli/tests/script_roundtrip.rs b/apps/solidcraft-cli/tests/script_roundtrip.rs index 568c4bdb3..e959c6e89 100644 --- a/apps/solidcraft-cli/tests/script_roundtrip.rs +++ b/apps/solidcraft-cli/tests/script_roundtrip.rs @@ -123,3 +123,42 @@ fn a_design_naming_a_sketch_and_its_extrude_alike_replays_from_its_script() { assert_eq!(names, ["Block", "Block"], "{first:#}"); assert_eq!(second["commands"], first["commands"], "the replayed design's script has the same steps"); } + +/// #10230: script export must disclose the print-face state that replay leaves out. +#[test] +fn script_export_warns_about_omitted_print_faces_on_stderr() { + let dir = std::env::temp_dir().join(format!("solidcraft-print-face-script-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let saved = dir.join("block.sc"); + let exported = dir.join("block.json"); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap(); + s.execute("body.print_face", &json!({"body": "Block", "point": [10, 5, 0]})).unwrap(); + s.execute("file.save", &json!({"path": saved})).unwrap(); + let native = std::fs::read(&saved).unwrap(); + + for to_file in [false, true] { + let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")); + cmd.arg("script").arg(&saved); + if to_file { + cmd.arg("--out").arg(&exported); + } + let out = cmd.output().unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{stderr}"); + assert!(stderr.contains("note: the script leaves out print-face assignments (body.print_face)"), "{stderr}"); + let script = if to_file { + assert!(out.stdout.is_empty(), "--out must keep stdout empty"); + std::fs::read(&exported).unwrap() + } else { + out.stdout + }; + let script: Value = serde_json::from_slice(&script).unwrap(); + let mut replayed = Session::default(); + replayed.run_script(&script).unwrap(); + assert!(replayed.doc.print_faces.is_empty()); + assert_eq!(replayed.doc.features, s.doc.features); + assert_eq!(std::fs::read(&saved).unwrap(), native, "export must not change the source design"); + } + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/apps/solidcraft-cli/tests/snapshot_camera.rs b/apps/solidcraft-cli/tests/snapshot_camera.rs index 69e4f89b7..b7d655631 100644 --- a/apps/solidcraft-cli/tests/snapshot_camera.rs +++ b/apps/solidcraft-cli/tests/snapshot_camera.rs @@ -171,9 +171,9 @@ fn a_saved_view_is_its_camera_and_a_standard_view_is_unchanged() { let top = dir.snapshot(&script, "top.png", &["--view", "top"]); let mut s = Session::default(); s.run_script(&serde_json::from_slice(&std::fs::read(&script).unwrap()).unwrap()).unwrap(); - let mut cam = solidcraft_engine::view::home_camera(&s); + let mut cam = solidcraft_engine::view::home_camera(&s).unwrap(); cam.set_view(solidcraft_engine::render::StandardView::Top); - let scene = solidcraft_engine::view::scene(&s, &cam); + let scene = solidcraft_engine::view::scene(&s, &cam).unwrap(); assert_same(&top, &solidcraft_engine::capture::png(&scene, &cam, SIZE.0, SIZE.1).unwrap().bytes, "the home camera turned to the top"); assert_same(&top, &dir.mcp(&script, "mcp-top.png", json!({"view": "top"})), "the MCP top view"); assert_differs(&top, &saved, "top and the saved view"); @@ -288,7 +288,7 @@ fn a_snapshot_shows_the_part_where_the_camera_puts_it() { let vp = c.view_proj(f64::from(SIZE.0) / f64::from(SIZE.1), 1000.0); let (mut elo, mut ehi) = ([f64::MAX; 2], [f64::MIN; 2]); for k in 0..8 { - let p = solidcraft_engine::geom::Vec3::new( + let p = solidcore_record::Vec3::new( corner[0] + size[0] * f64::from(k & 1), corner[1] + size[1] * f64::from((k >> 1) & 1), corner[2] + size[2] * f64::from((k >> 2) & 1), @@ -335,9 +335,9 @@ fn a_forced_cpu_snapshot_is_the_cpu_rasterizers_and_says_so() { assert!(stderr.contains("CPU rasterizer"), "{stderr}"); let mut s = Session::default(); s.run_script(&serde_json::from_slice(&std::fs::read(&script).unwrap()).unwrap()).unwrap(); - let mut cam = solidcraft_engine::view::home_camera(&s); + let mut cam = solidcraft_engine::view::home_camera(&s).unwrap(); cam.set_view(solidcraft_engine::render::StandardView::Top); - let scene = solidcraft_engine::view::scene(&s, &cam); + let scene = solidcraft_engine::view::scene(&s, &cam).unwrap(); let cpu = solidcraft_engine::render::render_png(&scene, &cam, SIZE.0 as usize, SIZE.1 as usize).unwrap(); assert_eq!(std::fs::read(dir.0.join("cpu.png")).unwrap(), cpu); } diff --git a/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs b/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs index 14a42c93d..9aa993cc6 100644 --- a/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs +++ b/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs @@ -5,13 +5,14 @@ //! vertices nothing else used, so an edge that is one straight line was drawn (and lit on hover) //! as many pieces, and a sketch on such a face projected every piece. +use solidcraft_engine::geom::prelude::*; use std::collections::HashMap; use std::path::{Path, PathBuf}; use serde_json::json; +use solidcore_record::Vec3; use solidcraft_engine::Session; use solidcraft_engine::doc::kernel::{FaceSurface, face_surface}; -use solidcraft_engine::geom::Vec3; fn design() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/action_matrix/designs/crazy-geom-cuts.sc") @@ -48,11 +49,11 @@ fn key(v: Vec3) -> [i64; 3] { fn straight_edges_are_one_edge_after_many_cuts() { for (what, s) in [("as saved", open(&design())), ("built from scratch", rebuilt())] { assert_eq!(errors(&s), vec![], "{what}: every feature evaluates"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let bodies: Vec<_> = st.bodies.iter().filter(|b| !b.body.is_mesh()).collect(); assert_eq!(bodies.len(), 1, "{what}: one body"); let body = &bodies[0].body; - let mesh = body.tessellate(0.01).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); // Every edge is drawn as one polyline; a straight one as one segment. let mut at: HashMap<[i64; 3], Vec> = HashMap::new(); for (i, e) in mesh.edges.iter().enumerate() { diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.toml index 03eccbe8f..c12cda0f6 100644 --- a/apps/solidcraft-web/Cargo.toml +++ b/apps/solidcraft-web/Cargo.toml @@ -14,8 +14,11 @@ name = "solidcraft-web" path = "src/main.rs" [features] -default = [] +default = ["profile"] bundled-render-library = ["solidcraft-engine/bundled-render-library"] +# The profiler, compiled in so any build can say where its time goes (the Profile operations +# preference, SOLIDCRAFT_PROFILE=1, diagnostics.profile); it records nothing until asked. +profile = ["solidcraft-engine/profile"] [dependencies] solidcraft-engine = { workspace = true } @@ -33,7 +36,7 @@ js-sys = "0.3" serde_json = { workspace = true } web-sys = { version = "0.3", features = [ "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "StorageManager", - "FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemWritableFileStream", + "FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemGetDirectoryOptions", "FileSystemWritableFileStream", "WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage", "StorageEvent", "IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "Headers", "ReadableStream", "ReadableStreamDefaultReader", diff --git a/apps/solidcraft-web/build.rs b/apps/solidcraft-web/build.rs new file mode 100644 index 000000000..a66d6cc00 --- /dev/null +++ b/apps/solidcraft-web/build.rs @@ -0,0 +1,9 @@ +//! Links the browser build with an 8 MiB stack: solidcore's kernel algorithms (subdivision, +//! intersection, filleting) recurse legitimately, and wasm has no guard page to catch an +//! overflow (solidcore's README recommends 8 MiB). + +fn main() { + if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32") { + println!("cargo:rustc-link-arg=-zstack-size=8388608"); + } +} diff --git a/apps/solidcraft-web/channel-storage.txt b/apps/solidcraft-web/channel-storage.txt new file mode 100644 index 000000000..9372905f6 --- /dev/null +++ b/apps/solidcraft-web/channel-storage.txt @@ -0,0 +1,2 @@ +This build keeps its designs and settings apart per release channel (src/channel.rs). +packaging/web-channels.sh only offers a release candidate that has this file. diff --git a/apps/solidcraft-web/index.html b/apps/solidcraft-web/index.html index 90030947f..57c307a56 100644 --- a/apps/solidcraft-web/index.html +++ b/apps/solidcraft-web/index.html @@ -22,6 +22,10 @@ + + + + @@ -30,6 +34,7 @@ + diff --git a/apps/solidcraft-web/src/channel.rs b/apps/solidcraft-web/src/channel.rs new file mode 100644 index 000000000..bdbda2c94 --- /dev/null +++ b/apps/solidcraft-web/src/channel.rs @@ -0,0 +1,61 @@ +//! Release channels. The site serves the stable web app at `/app/`, the release candidate at +//! `/app-rc/` and the bleeding-edge build at `/app-edge/`: one origin, so one set of browser +//! storage. A channel that kept its designs and settings in the same places could save a design +//! in a file format the stable app can't open, or overwrite stable's settings. So each +//! pre-release channel keeps everything under its own name, and stable (and any copy served from +//! another path: the release zip, `trunk serve`) keeps the names it has always used, so what +//! people have saved at `/app/` is untouched. +//! +//! The channel comes from the directory the app is served from, not from the build, so a build +//! taken from a release zip is as separate as one built on the spot. + +/// The channel the app is served as, from the page's path: `"rc"`, `"edge"`, or `""` (stable). +pub fn of_path(pathname: &str) -> &'static str { + match pathname.trim_end_matches("index.html").trim_end_matches('/').rsplit('/').next() { + Some("app-rc") => "rc", + Some("app-edge") => "edge", + _ => "", + } +} + +/// `name` as this channel stores it: unchanged for stable, `rc:name` and `edge:name` otherwise. +pub fn name_in(channel: &str, name: &str) -> String { + if channel.is_empty() { name.to_owned() } else { format!("{channel}:{name}") } +} + +#[cfg(target_arch = "wasm32")] +pub fn current() -> &'static str { + web_sys::window().and_then(|w| w.location().pathname().ok()).map_or("", |p| of_path(&p)) +} + +/// A storage key (local storage, IndexedDB database name) of the running channel. +#[cfg(target_arch = "wasm32")] +pub fn key(name: &str) -> String { + name_in(current(), name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_follows_the_directory() { + assert_eq!(of_path("/app/"), ""); + assert_eq!(of_path("/app/index.html"), ""); + assert_eq!(of_path("/app-rc/"), "rc"); + assert_eq!(of_path("/app-rc"), "rc"); + assert_eq!(of_path("/app-rc/index.html"), "rc"); + assert_eq!(of_path("/app-edge/"), "edge"); + assert_eq!(of_path("/"), ""); + assert_eq!(of_path("/solidcraft-web-0.30.1/"), ""); + assert_eq!(of_path("/app/app-rc/"), "rc", "only the directory's own name counts"); + assert_eq!(of_path("/app-rc/app/"), ""); + } + + #[test] + fn stable_keeps_its_names() { + assert_eq!(name_in("", "solidcraft.prefs"), "solidcraft.prefs"); + assert_eq!(name_in("rc", "solidcraft.prefs"), "rc:solidcraft.prefs"); + assert_ne!(name_in("rc", "x"), name_in("edge", "x")); + } +} diff --git a/apps/solidcraft-web/src/disk.rs b/apps/solidcraft-web/src/disk.rs index 13089700b..7b1cee097 100644 --- a/apps/solidcraft-web/src/disk.rs +++ b/apps/solidcraft-web/src/disk.rs @@ -467,7 +467,7 @@ mod web { async fn open_db() -> Result { let factory = web_sys::window().ok_or("no window")?.indexed_db().map_err(err)?.ok_or("this browser has no IndexedDB")?; - let request: IdbOpenDbRequest = factory.open_with_u32(DB, 1).map_err(err)?; + let request: IdbOpenDbRequest = factory.open_with_u32(&crate::channel::key(DB), 1).map_err(err)?; let target = request.clone(); let upgrade = Closure::once_into_js(move || { if let Ok(db) = target.result().and_then(|r| r.dyn_into::()) { diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rs index b7660968e..1f076ec1f 100644 --- a/apps/solidcraft-web/src/files.rs +++ b/apps/solidcraft-web/src/files.rs @@ -16,7 +16,9 @@ use solidcraft_engine::io::vfs; use crate::disk; use wasm_bindgen::{JsCast as _, JsValue, closure::Closure}; use wasm_bindgen_futures::{JsFuture, spawn_local}; -use web_sys::{FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetFileOptions, FileSystemWritableFileStream}; +use web_sys::{ + FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, FileSystemWritableFileStream, +}; /// Where OPFS files appear to the engine. pub const OPFS: &str = disk::OPFS_PREFIX; @@ -111,7 +113,7 @@ thread_local! { static LOCAL: Cell = const { Cell::new(false) }; } -/// Local storage keys of stored files. +/// Local storage keys of stored files (under the channel's name, see `channel.rs`). const LOCAL_PREFIX: &str = "solidcraft.file."; /// Local-storage files kept by earlier releases (compatibility shim, docs/compatibility.md): /// still listed and opened; removing one removes either key. @@ -169,7 +171,17 @@ fn has(sm: &web_sys::StorageManager, method: &str) -> bool { async fn root() -> Result { let sm = storage_manager().filter(|sm| has(sm, "getDirectory")).ok_or("this page has no private file storage (it needs https or localhost)")?; let dir = JsFuture::from(sm.get_directory()).await.map_err(err)?; - dir.dyn_into::().map_err(|_| "this browser has no private file storage (OPFS)".to_string()) + let dir = dir.dyn_into::().map_err(|_| "this browser has no private file storage (OPFS)".to_string())?; + // Stable keeps its files in the root, where they have always been; a pre-release channel has a folder of its own. + match crate::channel::current() { + "" => Ok(dir), + channel => { + let opts = FileSystemGetDirectoryOptions::new(); + opts.set_create(true); + let sub = JsFuture::from(dir.get_directory_handle_with_options(&format!("channel-{channel}"), &opts)).await.map_err(err)?; + sub.dyn_into::().map_err(|_| "not a folder".to_string()) + } + } } pub(crate) async fn read_handle(h: &FileSystemFileHandle) -> Result, String> { @@ -191,7 +203,7 @@ async fn file_handle(dir: &FileSystemDirectoryHandle, name: &str, create: bool) async fn write_file(name: &str, bytes: &[u8]) -> Result<(), String> { if local_only() { return local()? - .set_item(&format!("{LOCAL_PREFIX}{name}"), &encode(bytes)) + .set_item(&crate::channel::key(&format!("{LOCAL_PREFIX}{name}")), &encode(bytes)) .map_err(|e| format!("local storage is full or blocked: {}", err(e))); } let dir = root().await?; @@ -207,7 +219,7 @@ async fn remove_file(name: &str) -> Result<(), String> { if local_only() { let st = local()?; st.remove_item(&format!("{LEGACY_LOCAL_PREFIX}{name}")).map_err(err)?; - return st.remove_item(&format!("{LOCAL_PREFIX}{name}")).map_err(err); + return st.remove_item(&crate::channel::key(&format!("{LOCAL_PREFIX}{name}"))).map_err(err); } let dir = root().await?; JsFuture::from(dir.remove_entry(name)).await.map_err(err)?; @@ -220,7 +232,10 @@ fn read_local() -> Result, f64)>, String> { let mut out = Vec::new(); for i in 0..st.length().unwrap_or(0).min(10_000) { let Some(k) = st.key(i).ok().flatten() else { continue }; - let Some(name) = k.strip_prefix(LOCAL_PREFIX).or_else(|| k.strip_prefix(LEGACY_LOCAL_PREFIX)) else { continue }; + let own = crate::channel::key(LOCAL_PREFIX); + // The old names belong to stable; a pre-release channel has none. + let legacy = crate::channel::current().is_empty().then_some(LEGACY_LOCAL_PREFIX); + let Some(name) = k.strip_prefix(own.as_str()).or_else(|| legacy.and_then(|l| k.strip_prefix(l))) else { continue }; if let Some(v) = st.get_item(&k).ok().flatten() { out.push((name.to_string(), decode(&v), 0.0)); } diff --git a/apps/solidcraft-web/src/linked.rs b/apps/solidcraft-web/src/linked.rs index 24e073d5d..f75d99446 100644 --- a/apps/solidcraft-web/src/linked.rs +++ b/apps/solidcraft-web/src/linked.rs @@ -15,6 +15,9 @@ type Reply = Result<(String, Vec), String>; pub struct Download { reply: Rc>>, pending: Option<(String, Vec)>, + /// The downloaded design being opened (a few features a frame, #10198): the answer to come, + /// the name it takes and the file it was read from. + opening: Option<(std::sync::mpsc::Receiver, String, String)>, } impl Download { @@ -33,13 +36,14 @@ impl Download { } pub fn tick(&mut self, app: &mut SolveApp, ctx: &egui::Context) { + self.opened(app); if let Some(reply) = self.reply.borrow_mut().take() { match reply { Ok(file) => self.pending = Some(file), Err(error) => app.set_status(format!("Could not open design link: {error}"), true), } } - if self.pending.is_none() || app.file_picker_busy() { + if self.pending.is_none() || self.opening.is_some() || app.file_picker_busy() { return; } if solidcraft_ui_egui::documents::any_dirty(app) { @@ -71,18 +75,33 @@ impl Download { } } let Some((name, bytes)) = self.pending.take() else { return }; - // The extension selects the design loader even when the URL has no extension. - let path = &format!("/linked/design.{}", solidcraft_engine::io::DESIGN_EXT); - vfs::insert(path, bytes); - app.open_path(path); - if app.session.path.as_deref() == Some(path.as_str()) { + // The extension selects the design loader even when the URL has no extension. Named + // after the link, as the progress card shows the file's name. + let file: String = name.chars().map(|c| if matches!(c, '/' | '\\') { '_' } else { c }).collect(); + let path = format!("/linked/{}.{}", if file.is_empty() { "design" } else { &file }, solidcraft_engine::io::DESIGN_EXT); + vfs::insert(&path, bytes); + // Opened as any design is, with its progress and Cancel; finished in `opened`. + self.opening = Some((app.open_path_answered(&path), name, path)); + self.opened(app); + } + + /// The downloaded design is in: it is an unsaved copy under the link's name. + fn opened(&mut self, app: &mut SolveApp) { + let Some((rx, _, _)) = &self.opening else { return }; + let (ok, cancelled) = match rx.try_recv() { + Ok(reply) => (reply["ok"].as_bool() == Some(true), reply["error"].as_str().is_some_and(|e| e.contains("cancelled"))), + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => (false, false), + }; + let Some((_, name, path)) = self.opening.take() else { return }; + if ok && app.session.path.as_deref() == Some(path.as_str()) { app.session.path = None; app.session.doc_mut().name = name; app.session.mark_unsaved(); - } else { + } else if !ok && !cancelled { app.set_status("Could not open design link: the downloaded file is not a valid SolidCraft design", true); } - let _ = vfs::remove(path); + let _ = vfs::remove(&path); } } diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index 4d92b4663..db5799e23 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -9,6 +9,8 @@ #[cfg(target_arch = "wasm32")] mod api; #[cfg(any(target_arch = "wasm32", test))] +mod channel; +#[cfg(any(target_arch = "wasm32", test))] mod disk; #[cfg(target_arch = "wasm32")] mod easyprint; @@ -152,8 +154,15 @@ impl PrefsWriter { /// tab of the page when one tab writes). Other keys, and settings taken away (clearing the site's /// data), leave this tab's settings as they are. #[cfg(any(target_arch = "wasm32", test))] -fn settings_written(key: Option<&str>, value: Option) -> Option { - value.filter(|_| key == Some(solidcraft_ui_egui::prefs::STORAGE_KEY)) +fn settings_written(own_key: &str, key: Option<&str>, value: Option) -> Option { + // Tabs of another channel write to the same storage, under their own key. + value.filter(|_| key == Some(own_key)) +} + +/// The settings key of `channel` (see [`channel`]). +#[cfg(target_arch = "wasm32")] +fn prefs_key() -> String { + channel::key(solidcraft_ui_egui::prefs::STORAGE_KEY) } #[cfg(target_arch = "wasm32")] @@ -162,6 +171,7 @@ mod web { use solidcraft_engine::Session; use solidcraft_engine::io::vfs; + use solidcraft_ui_egui::ui_kit::BackingTooltipExt as _; use solidcraft_ui_egui::{Services, SolveApp, ui_kit}; use wasm_bindgen::JsCast as _; @@ -262,7 +272,7 @@ mod web { fn hear_settings_from_other_tabs(window: &web_sys::Window, ctx: &egui::Context, inbox: PrefsInbox) { let ctx = ctx.clone(); let on_storage = wasm_bindgen::closure::Closure::::new(move |e: web_sys::StorageEvent| { - if let Some(prefs) = crate::settings_written(e.key().as_deref(), e.new_value()) { + if let Some(prefs) = crate::settings_written(&crate::prefs_key(), e.key().as_deref(), e.new_value()) { inbox.set(Some(prefs)); ctx.request_repaint(); } @@ -273,8 +283,10 @@ mod web { } const JAPANESE_FONT_PATH: &str = "./fonts/BIZUDPGothic-Regular.ttf"; + const CHINESE_SC_FONT_PATH: &str = "./fonts/CraftUI-SC.otf"; + const CHINESE_TC_FONT_PATH: &str = "./fonts/CraftUI-TC.otf"; - type FontLoadResult = Rc, String>>>>; + type FontLoadResult = Rc), String>>>>; struct Shell { app: SolveApp, @@ -292,11 +304,17 @@ mod web { rename_focus: bool, /// The start page's recent designs were filled from the stored ones. recents_synced: bool, - /// On-demand CJK font: fetched only when a CJK language is selected. + /// On-demand script fonts: fetched only when a CJK language is selected. font: solidcraft_ui_egui::fonts::CjkFontLoader, font_result: FontLoadResult, - /// The fetched CJK font's bytes: kept so a language change can re-order the fallbacks. + /// The fetched Japanese font's bytes: kept so a language change can re-order the fallbacks. cjk_bytes: Option>, + /// The fetched Chinese font's bytes (Simplified or Traditional for this session). + chinese_bytes: Option>, + /// Which Chinese face `chinese_bytes` is: `"zh"` or `"zh-TW"`. + chinese_kind: Option<&'static str>, + /// Kind requested by the in-flight fetch (`"ja"`, `"zh"`, or `"zh-TW"`). + font_fetch_kind: Option<&'static str>, /// The language the fonts were last set up for (a CJK UI leads with the CJK face). font_language: String, space_mouse: SpaceMouse, @@ -326,8 +344,7 @@ mod web { } let prefs = self.persisted_prefs(); let Some(prefs) = self.prefs_writer.take(prefs) else { return }; - let stored = - web_sys::window().and_then(|w| w.local_storage().ok().flatten()).map(|s| s.set_item(solidcraft_ui_egui::prefs::STORAGE_KEY, &prefs)); + let stored = web_sys::window().and_then(|w| w.local_storage().ok().flatten()).map(|s| s.set_item(&crate::prefs_key(), &prefs)); if !matches!(stored, Some(Ok(()))) { log::warn!("settings: the browser's storage did not take them; they are saved again later"); self.prefs_writer = crate::PrefsWriter::default(); @@ -367,7 +384,8 @@ mod web { // Designs opened from the computer's disk (the files window): open them. let opened: Vec<_> = self.files.opened.borrow_mut().drain(..).collect(); for path in opened { - self.app.open_path(&path); + // A few features a frame, with progress and Cancel (#10198). + self.app.open_path_async(&path); self.files.panel.set(false); } // Recent designs whose file is gone are dropped from the list. @@ -408,7 +426,7 @@ mod web { path }; match intent { - Intent::Open => self.app.open_path(&path), + Intent::Open => self.app.open_path_async(&path), Intent::Insert | Intent::Theme => self.app.drop_path(&path), } self.files.panel.set(false); @@ -483,7 +501,7 @@ mod web { files::pick_from_disk(&self.files, Intent::Open); } if ui_kit::button(ui, "Insert from computer…", ui_kit::Button::Normal) - .on_hover_text(solidcraft_ui_egui::i18n::tr("web.files.insert_drawings_hint")) + .backing_on_hover_text(solidcraft_ui_egui::i18n::tr("web.files.insert_drawings_hint")) .clicked() { files::pick_from_disk(&self.files, Intent::Insert); @@ -537,7 +555,7 @@ mod web { let design = solidcraft_engine::io::is_design_path(&e.name); if !design && ui_kit::button(ui, "Insert", ui_kit::Button::Small) - .on_hover_text(solidcraft_ui_egui::i18n::tr("web.files.insert_stored_drawings_hint")) + .backing_on_hover_text(solidcraft_ui_egui::i18n::tr("web.files.insert_stored_drawings_hint")) .clicked() { act = Some(("insert", e.name.clone())); @@ -547,7 +565,7 @@ mod web { self.rename_focus = true; } if ui_kit::button(ui, "Save to computer…", ui_kit::Button::Small) - .on_hover_text("A copy in a file you choose; the stored design stays here") + .backing_on_hover_text("A copy in a file you choose; the stored design stays here") .clicked() { act = Some(("save_copy", e.name.clone())); @@ -572,7 +590,7 @@ mod web { let path = format!("{}{name}", files::OPFS); match what { "open" => { - self.app.open_path(&path); + self.app.open_path_async(&path); self.files.panel.set(false); } "insert" => { @@ -674,68 +692,107 @@ mod web { files::autosave(&self.files, None); } - /// Fetch and install the CJK font when a CJK language is selected. If that fails, this + /// Whether the shell already has the on-demand face the live language needs. + fn script_font_ready(&self) -> bool { + match solidcraft_ui_egui::fonts::web_script_font_kind(solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language)) { + Some("zh") => self.chinese_bytes.is_some() && self.chinese_kind == Some("zh"), + Some("zh-TW") => self.chinese_bytes.is_some() && self.chinese_kind == Some("zh-TW"), + Some("ja") => self.cjk_bytes.is_some(), + _ => true, + } + } + + /// Fetch and install a script font when a CJK language is selected. If that fails, this /// session falls back to English (no tofu); the saved language preference is kept. fn tick_font(&mut self, ctx: &egui::Context) { let done = self.font_result.borrow_mut().take(); if let Some(res) = done { + let kind = self.font_fetch_kind.take(); let installed = match res { - Ok(bytes) => { - solidcraft_engine::sketch::fallback::provide_web_font(bytes.clone()); - self.cjk_bytes = Some(bytes); + Ok((path, bytes)) => { + match kind { + Some("zh") => { + self.chinese_bytes = Some(bytes); + self.chinese_kind = Some("zh"); + } + Some("zh-TW") => { + self.chinese_bytes = Some(bytes); + self.chinese_kind = Some("zh-TW"); + } + _ => { + solidcraft_engine::sketch::fallback::provide_web_font(bytes.clone()); + self.cjk_bytes = Some(bytes); + } + } + log::info!("loaded web script font from {path}"); true } Err(err) => { - log::warn!("failed to fetch CJK font from {JAPANESE_FONT_PATH}: {err}"); - solidcraft_engine::sketch::fallback::web_font_failed(); + let path = match kind { + Some("zh") => CHINESE_SC_FONT_PATH, + Some("zh-TW") => CHINESE_TC_FONT_PATH, + _ => JAPANESE_FONT_PATH, + }; + log::warn!("failed to fetch script font from {path}: {err}"); + if !matches!(kind, Some("zh" | "zh-TW")) { + solidcraft_engine::sketch::fallback::web_font_failed(); + } false } }; - if installed { - log::info!("loaded web CJK font from {JAPANESE_FONT_PATH}"); - } else if solidcraft_ui_egui::fonts::needs_cjk_font(&self.app.preferences.language) { - log::warn!("CJK font unavailable; showing English for this session"); + let effective = solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language); + if !installed && solidcraft_ui_egui::fonts::needs_cjk_font(effective) { + log::warn!("script font unavailable; showing English for this session"); } self.font.finished(installed, &mut self.app.preferences.language); self.apply_fonts(ctx); ctx.request_repaint(); } - if self.font.tick(&mut self.app.preferences.language) { - self.fetch_font(ctx); + let ready = self.script_font_ready(); + let effective = solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language); + if self.font.tick(&mut self.app.preferences.language, ready) { + self.fetch_font(ctx, solidcraft_ui_egui::fonts::web_script_font_kind(effective).unwrap_or("ja")); } // The CJK face leads only a CJK UI: its Cyrillic glyphs are full-width, so switching // to Ukrainian (or English) must put the Latin face back in front. - if self.app.preferences.language != self.font_language { + if solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language) != self.font_language { self.apply_fonts(ctx); } } - /// Set up the UI fonts for the live language, keeping the fetched CJK font as a fallback - /// (it leads only for a CJK UI, see [`solidcraft_ui_egui::fonts::install_cjk_font_for`]). + /// Set up the UI fonts for the live language, keeping fetched script fonts as fallbacks + /// (Chinese leads a Chinese UI; see [`solidcraft_ui_egui::fonts::install_web_script_fonts`]). fn apply_fonts(&mut self, ctx: &egui::Context) { - match self.cjk_bytes.clone() { - Some(bytes) => { - solidcraft_ui_egui::fonts::install_cjk_font_for(ctx, bytes, &self.app.preferences.language); - } - None => solidcraft_ui_egui::fonts::setup_fonts(ctx), + let effective = solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language); + if self.cjk_bytes.is_none() && self.chinese_bytes.is_none() { + solidcraft_ui_egui::fonts::setup_fonts(ctx); + } else { + solidcraft_ui_egui::fonts::install_web_script_fonts(ctx, self.cjk_bytes.clone(), self.chinese_bytes.clone(), effective); } - self.font_language.clone_from(&self.app.preferences.language); + self.font_language = effective.to_owned(); } - /// CJK text on screen with no CJK font yet (an English UI showing a Japanese name), or a - /// drawing's text waiting for one: fetch the font, so the text does not stay tofu (#720). + /// CJK text on screen with no Japanese font yet (an English UI showing a Japanese name), or a + /// drawing's text waiting for one: fetch the Japanese font, so the text does not stay tofu (#720). fn watch_text_for_font(&mut self, ctx: &egui::Context) { let wanted = solidcraft_ui_egui::fonts::painted_cjk(ctx) || solidcraft_engine::sketch::fallback::web_font_wanted(); if self.font.watching_text() && wanted && self.font.text_needs_font() { - self.fetch_font(ctx); + self.fetch_font(ctx, "ja"); } } - fn fetch_font(&self, ctx: &egui::Context) { + fn fetch_font(&mut self, ctx: &egui::Context, kind: &'static str) { + let path = match kind { + "zh" => CHINESE_SC_FONT_PATH, + "zh-TW" => CHINESE_TC_FONT_PATH, + _ => JAPANESE_FONT_PATH, + }; + self.font_fetch_kind = Some(kind); let slot = self.font_result.clone(); let ctx = ctx.clone(); + let path = path.to_owned(); wasm_bindgen_futures::spawn_local(async move { - let res = fetch_font_bytes(JAPANESE_FONT_PATH).await; + let res = fetch_font_bytes(&path).await.map(|bytes| (path, bytes)); *slot.borrow_mut() = Some(res); ctx.request_repaint(); }); @@ -791,14 +848,15 @@ mod web { self.store_prefs(&ctx); } fn persist_egui_memory(&self) -> bool { - self.launch.persists() + // eframe keeps this under one fixed key: only stable uses it, so a pre-release never rewrites it. + self.launch.persists() && crate::channel::current().is_empty() } fn save(&mut self, storage: &mut dyn eframe::Storage) { if !self.launch.persists() { return; } let prefs = self.persisted_prefs(); - storage.set_string(solidcraft_ui_egui::prefs::STORAGE_KEY, prefs); + storage.set_string(&crate::prefs_key(), prefs); } } @@ -808,7 +866,7 @@ mod web { /// Where `?webgl` is remembered. The installed app starts from its manifest's start URL, which /// has no query, so the choice has to outlive the page it was made on. - const WEBGL_KEY: &str = "solidcraft.webgl"; + const WEBGL_KEY: &str = "solidcraft.webgl"; // stored under crate::channel::key /// Render with WebGL2: asked for now (`?webgl`, remembered) or before (until `?webgpu`). fn webgl() -> bool { @@ -816,17 +874,17 @@ mod web { let q = query(); if crate::query_flag(&q, "webgl") { if let Some(s) = &storage { - let _ = s.set_item(WEBGL_KEY, "1"); + let _ = s.set_item(&crate::channel::key(WEBGL_KEY), "1"); } return true; } if crate::query_flag(&q, "webgpu") { if let Some(s) = &storage { - let _ = s.remove_item(WEBGL_KEY); + let _ = s.remove_item(&crate::channel::key(WEBGL_KEY)); } return false; } - storage.and_then(|s| s.get_item(WEBGL_KEY).ok().flatten()).is_some() + storage.and_then(|s| s.get_item(&crate::channel::key(WEBGL_KEY)).ok().flatten()).is_some() } /// Fetch font bytes asynchronously through the browser. @@ -925,7 +983,7 @@ mod web { if launch.persists() { hear_settings_from_other_tabs(&window, &cc.egui_ctx, other_tab_prefs.clone()); } - if launch.persists() && let Some(p) = cc.storage.and_then(|s| solidcraft_ui_egui::prefs::stored(|k| s.get_string(k))) { + if launch.persists() && let Some(p) = cc.storage.and_then(|s| solidcraft_ui_egui::prefs::stored(|k| s.get_string(&crate::channel::key(k)))) { app.load_prefs(&p); } if let Some(rs) = &cc.wgpu_render_state { @@ -965,6 +1023,9 @@ mod web { font: Default::default(), font_result: Rc::new(std::cell::RefCell::new(None)), cjk_bytes: None, + chinese_bytes: None, + chinese_kind: None, + font_fetch_kind: None, font_language, space_mouse: SpaceMouse::default(), wheel_gestures: solidcraft_ui_egui::WebWheelGestures::default(), @@ -1125,9 +1186,10 @@ mod tests { #[test] fn only_settings_another_tab_wrote_are_loaded() { let key = solidcraft_ui_egui::prefs::STORAGE_KEY; - assert_eq!(settings_written(Some(key), Some("{}".into())).as_deref(), Some("{}")); - assert_eq!(settings_written(Some("solidcraft.webgl"), Some("1".into())), None); - assert_eq!(settings_written(Some(key), None), None, "removed settings leave this tab's"); - assert_eq!(settings_written(None, None), None, "clearing all storage leaves this tab's settings"); + assert_eq!(settings_written(key, Some(key), Some("{}".into())).as_deref(), Some("{}")); + assert_eq!(settings_written(key, Some("solidcraft.webgl"), Some("1".into())), None); + assert_eq!(settings_written(key, Some(key), None), None, "removed settings leave this tab's"); + assert_eq!(settings_written(key, None, None), None, "clearing all storage leaves this tab's settings"); + assert_eq!(settings_written(key, Some("rc:solidcraft.prefs"), Some("{}".into())), None, "another channel's settings are not loaded"); } } diff --git a/apps/solidcraft/Cargo.toml b/apps/solidcraft/Cargo.toml index a39478f40..7182d7af1 100644 --- a/apps/solidcraft/Cargo.toml +++ b/apps/solidcraft/Cargo.toml @@ -8,9 +8,12 @@ publish = false default-run = "solidcraft" [features] -default = ["raytrace-cpu", "bundled-render-library"] +default = ["raytrace-cpu", "bundled-render-library", "profile"] bundled-render-library = ["solidcraft-engine/bundled-render-library"] raytrace-cpu = ["solidcraft-engine/raytrace-cpu"] +# The profiler, compiled in so any build can say where its time goes (the Profile operations +# preference, SOLIDCRAFT_PROFILE=1, diagnostics.profile); it records nothing until asked. +profile = ["solidcraft-engine/profile"] # The workspace lints, except unsafe_code: denied, not forbidden, so that src/open_documents.rs # (macOS file-open events), src/native_crash.rs (Windows exception filter), src/native_crash_macos.rs @@ -78,6 +81,7 @@ windows-sys = { version = "0.61", features = [ "Win32_UI_HiDpi", "Win32_UI_WindowsAndMessaging", ] } +winreg = "0.56" [target.'cfg(target_os = "macos")'.dependencies] muda = { version = "0.21.2", default-features = false } @@ -89,7 +93,7 @@ hidapi = { version = "2.6.7", default-features = false, features = ["macos-share # Files opened from Finder and the Dock (src/open_documents.rs), and the fullscreen title-bar # inset (src/main.rs); all already come with eframe and rfd. objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSResponder", "NSWindow"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSAccessibility", "NSApplication", "NSResponder", "NSWindow", "NSWorkspace"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" # Native crash capture (src/native_crash_macos.rs): the signal handler, the faulting module @@ -104,5 +108,10 @@ winit = { version = "0.30", default-features = false, features = ["x11"] } raw-window-handle = "0.6" x11rb = { version = "0.13", default-features = false } +[target.'cfg(target_os = "linux")'.dependencies] +# The desktop's dark or light preference through the XDG Desktop Portal (src/desktop_theme.rs, +# #7944); already in the tree through eframe's accessibility support (accesskit_unix). +zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] } + [build-dependencies] embed-resource = "3.0.11" diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rs index f7635e17b..996d7c54a 100644 --- a/apps/solidcraft/src/control_server.rs +++ b/apps/solidcraft/src/control_server.rs @@ -22,6 +22,10 @@ const MAX_BAD_LINES: usize = 8; /// How long a subscribed connection waits after a `design.changed` line before the next: what /// changes meanwhile (a parameter dragged) goes out as one line, the latest (#6985). const EVENT_GAP: Duration = Duration::from_millis(100); +/// How long a new connection has to show the token. A client connects when it has a request to +/// send, so this is plenty; one that doesn't send it loses the connection, and its seat among +/// [`MAX_CONNECTIONS`] goes to someone else. +const TOKEN_WAIT: Duration = Duration::from_secs(5); static OPEN: AtomicUsize = AtomicUsize::new(0); /// The token files this launch wrote (its control port, the agent chat's endpoint) and the @@ -225,23 +229,53 @@ fn unauthorized() -> Value { /// Refuse the connection: the reply, then the end of what we send, then what the client had /// already sent read and dropped (a little, briefly). Closing a socket with unread input resets /// the connection, and a reset can reach the client before it has read the refusal. -fn refuse(out: &mut TcpStream, reader: &mut BufReader) { +fn refuse(out: &mut TcpStream, reader: &mut BufReader) { use std::io::Read; let _ = send(out, &unauthorized()); let _ = out.shutdown(std::net::Shutdown::Write); - let _ = reader.get_ref().set_read_timeout(Some(Duration::from_millis(500))); + reader.get_mut().deadline = Some(Instant::now() + Duration::from_millis(500)); let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); } +/// What a client sends. Until it shows the token, all of its reads share one deadline, so neither +/// blank lines nor a line sent a byte at a time buy it more time. After that it may stay idle as +/// long as it likes. +struct ClientInput { + socket: TcpStream, + deadline: Option, +} + +impl ClientInput { + /// No deadline any more: the client showed the token. + fn admit(&mut self) -> std::io::Result<()> { + self.deadline = None; + self.socket.set_read_timeout(None) + } +} + +impl std::io::Read for ClientInput { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if let Some(deadline) = self.deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.socket.set_read_timeout(Some(left))?; + } + self.socket.read(buf) + } +} + /// How long a request waits for the app's reply: most requests, and a batch (or every request, -/// on a patient connection). +/// on a patient connection); and how long a new connection has to show the token. #[derive(Clone, Copy)] struct Waits { short: Duration, long: Duration, + token: Duration, } -const WAITS: Waits = Waits { short: Duration::from_secs(60), long: Duration::from_secs(3600) }; +const WAITS: Waits = Waits { short: Duration::from_secs(60), long: Duration::from_secs(3600), token: TOKEN_WAIT }; /// A request that timed out but is still running in the app (#1618): its id and method, and where /// its reply will land. @@ -413,11 +447,37 @@ impl Lines { } } +/// A subscribed connection's seat on the watch: it leaves exactly once, whichever thread sees +/// the connection's end first — the connection's own thread at the end of the stream, or the +/// events thread at the first write a closed client refuses. The seat used to wait for the +/// events thread alone, and that thread only leaves its wait when the design moves, so the +/// count could outlive the connection by a second or more (#8315). +struct Seat(Mutex>); + +impl Seat { + fn new(counted: Subscriber) -> Self { + Seat(Mutex::new(Some(counted))) + } + + /// Leave the watch now: the seat goes once, whoever gets here first. + fn release(&self) { + let counted = self.0.lock().unwrap_or_else(PoisonError::into_inner).take(); + drop(counted); + } +} + +impl Drop for Seat { + fn drop(&mut self) { + self.release(); + } +} + /// A connection's `control.subscribe` (#6985): its `design.changed` lines, sent from a thread of /// their own until the connection ends. struct Subscription { lines: Arc, stop: Arc, + seat: Arc, } impl Subscription { @@ -433,15 +493,17 @@ impl Subscription { ) -> Option<(Self, std::io::Result<()>)> { let lines = Arc::new(Lines { socket: out.try_clone().ok()?, turn: Mutex::new(()) }); let stop = Arc::new(AtomicBool::new(false)); + let seat = Arc::new(Seat::new(counted)); let first = lines.turn.lock().unwrap_or_else(PoisonError::into_inner); - let (l, s) = (lines.clone(), stop.clone()); + let (l, s, watch_seat) = (lines.clone(), stop.clone(), Arc::clone(&seat)); // The connection's seat on the watch rides the events thread: it leaves when the thread // does, so the next failed write to a closed client retires it even while the connection's - // own thread is slow to see the end of the stream (#7226). - std::thread::Builder::new().stack_size(64 * 1024).spawn(move || send_events(design, &l, &s, seen, counted)).ok()?; + // own thread is slow to see the end of the stream (#7226). The connection's own thread + // leaves it too, so a closed connection stops counting at once (#8315). + std::thread::Builder::new().stack_size(64 * 1024).spawn(move || send_events(design, &l, &s, seen, watch_seat)).ok()?; let sent = send(&mut &lines.socket, reply); drop(first); - Some((Subscription { lines, stop }, sent)) + Some((Subscription { lines, stop, seat }, sent)) } } @@ -454,6 +516,9 @@ fn design_of(reply: &Value) -> Option<(String, u64)> { impl Drop for Subscription { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); + // The seat on the watch goes now: the connection is over, and nothing counts it any more + // (#8315). + self.seat.release(); // The socket closes now, not when the thread next looks; a line blocked on a client that // stopped reading ends too. let _ = self.lines.socket.shutdown(std::net::Shutdown::Both); @@ -461,10 +526,10 @@ impl Drop for Subscription { } /// The `design.changed` lines of a subscribed connection, each time the design differs from the -/// last one it was told of (`seen`), until `stop`. Owns the connection's seat on the watch -/// (`counted`), so the seat leaves exactly when this thread does: on `stop`, or on the first -/// write a closed client refuses (#7226). -fn send_events(design: &DesignWatch, lines: &Lines, stop: &AtomicBool, mut seen: (String, u64), _counted: Subscriber) { +/// last one it was told of (`seen`), until `stop`. Holds the connection's seat on the watch +/// (`seat`), which it leaves when the thread ends: on `stop`, or on the first write a closed +/// client refuses (#7226). +fn send_events(design: &DesignWatch, lines: &Lines, stop: &AtomicBool, mut seen: (String, u64), seat: Arc) { while !stop.load(Ordering::Relaxed) { let Some(now) = design.wait(&seen, stop, Duration::from_secs(1)).filter(|now| *now != seen) else { continue }; if lines.send(&json!({"event": "design.changed", "params": {"document_id": now.0, "revision": now.1}})).is_err() { @@ -473,6 +538,9 @@ fn send_events(design: &DesignWatch, lines: &Lines, stop: &AtomicBool, mut seen: seen = now; std::thread::sleep(EVENT_GAP); } + // The client is gone: it is not counted on the watch any more, whatever the connection's own + // thread still has to notice (#8315). + seat.release(); } /// What this app's control channel does beyond the methods every version has, for a client to @@ -509,7 +577,7 @@ fn serve_with( let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1; let Ok(read) = stream.try_clone() else { return }; let mut out = stream; - let mut reader = BufReader::new(read); + let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(Instant::now() + waits.token) }); let mut bad = 0usize; let mut authenticated = false; let mut pending: Option = None; @@ -520,6 +588,10 @@ fn serve_with( let line = match read_line(&mut reader, MAX_LINE) { Ok(Some(l)) => String::from_utf8_lossy(&l).into_owned(), Ok(None) => break, + // Closed without a word: a client that connected early and only now sends its first + // request would read a line here as the reply to it. It finds the connection closed + // and opens another. + Err(e) if !authenticated && matches!(e.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock) => break, Err(e) => { let _ = answer(&mut out, events.as_ref(), &json!({"ok": false, "error": e.to_string()})); break; @@ -531,7 +603,12 @@ fn serve_with( // The first request must carry the token; later ones on the same connection may. if !authenticated { match token_of(&line) { - Some(t) if control_auth::tokens_match(&t, token) => authenticated = true, + Some(t) if control_auth::tokens_match(&t, token) => { + if reader.get_mut().admit().is_err() { + break; + } + authenticated = true; + } _ => { refuse(&mut out, &mut reader); break; @@ -641,6 +718,80 @@ fn serve_with( mod tests { use super::*; + /// A connection that doesn't show the token in time is closed without a word, however it fills + /// the time. One that does keeps working when it idles for longer than that. + #[test] + fn the_token_has_a_time_limit_and_an_authenticated_client_may_idle() { + use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; + let limit = Duration::from_millis(500); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + static RUNNING: Running = Running::new(); + let waits = Waits { short: Duration::from_secs(10), long: Duration::from_secs(10), token: limit }; + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let tx = tx.clone(); + std::thread::spawn(move || serve_with(stream, token, tx, egui::Context::default(), false, waits, &RUNNING, &DESIGN_WATCH)); + } + }); + let open = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + s + }; + // Sends `drip` every 50 ms until the server closes; what it read, and when it closed. + let closed_after = |drip: &[u8]| { + let mut s = open(); + let start = Instant::now(); + s.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let mut got = Vec::new(); + loop { + let mut buf = [0u8; 256]; + match s.read(&mut buf) { + Ok(0) => break, + Ok(n) => got.extend_from_slice(buf.get(..n).unwrap()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { + assert!(start.elapsed() < Duration::from_secs(20), "still open"); + let _ = s.write_all(drip); + } + Err(_) => break, + } + } + (got, start.elapsed()) + }; + for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] { + let (got, took) = closed_after(drip); + assert!(got.is_empty(), "{drip:?} was answered: {}", String::from_utf8_lossy(&got)); + assert!(took >= limit.saturating_sub(Duration::from_millis(50)), "{drip:?} closed after {took:?}"); + } + + let mut s = open(); + let mut lines = BufReader::new(s.try_clone().unwrap()); + let mut ask = |line: Value| -> Value { + writeln!(s, "{line}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true); + std::thread::sleep(limit * 3); + assert_eq!(ask(json!({"id": 2, "method": "ui.view"}))["ok"], true, "idle for longer than the limit"); + + // A wrong token is still answered, at once. + let mut wrong = open(); + writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap(); + let mut l = String::new(); + BufReader::new(wrong).read_line(&mut l).unwrap(); + assert!(l.contains("unauthorized"), "{l}"); + } + /// #1618: a request that outlasts its wait says it is still running; the connection keeps its /// reply for `control.pending`, and refuses other requests as `busy` until it lands, so none /// is queued to run unseen behind it. @@ -664,7 +815,7 @@ mod tests { let _ = req.reply.send(json!({"ok": true, "result": req.method})); } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100) }; + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; static RUNNING: Running = Running::new(); std::thread::spawn(move || { if let Some(stream) = listener.incoming().flatten().next() { @@ -730,7 +881,7 @@ mod tests { let _ = req.reply.send(json!({"ok": true, "result": req.method})); } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_secs(60) }; + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_secs(60), token: TOKEN_WAIT }; std::thread::spawn(move || { for stream in listener.incoming().flatten() { let tx = tx.clone(); @@ -905,6 +1056,58 @@ mod tests { assert!(!WATCH.subscribed()); } + /// #8315: a closed connection leaves the watch at once. The seat of a subscribed connection + /// goes when the connection's own thread sees the end of the stream, not only when the + /// events thread notices: that thread waits for the design to move, so a connection that + /// closed while the design stood still kept the watch counting it for a second or more. + #[test] + fn a_closed_connection_leaves_the_watch_at_once() { + static RUNNING: Running = Running::new(); + static WATCH: DesignWatch = DesignWatch::new(); + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The window names the design once and then leaves it alone: nothing moves it, so the + // events thread has nothing to write and only the end of the connection can retire it. + std::thread::spawn(move || { + for req in rx { + if req.method == "control.subscribe" { + WATCH.publish("d-1", 3); + let _ = req.reply.send(json!({"ok": true, "result": {"document_id": "d-1", "revision": 3}})); + } else { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + } + }); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let tx = tx.clone(); + std::thread::spawn(move || serve_with(stream, token, tx, egui::Context::default(), false, WAITS, &RUNNING, &WATCH)); + } + }); + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut out = s.try_clone().unwrap(); + let mut lines = BufReader::new(s); + writeln!(out, "{}", json!({"id": 1, "method": "control.subscribe", "token": token})).unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + let reply: Value = serde_json::from_str(&l).unwrap(); + assert!(reply["ok"] == true, "{reply}"); + assert!(WATCH.subscribed(), "the connection is subscribed"); + // Let the events thread settle into its wait: the design stands still, so it has nothing + // to write, and only the end of the connection can retire it. + std::thread::sleep(Duration::from_millis(200)); + // The client goes away without asking anything else. + drop((out, lines)); + let deadline = Instant::now() + Duration::from_millis(400); + while WATCH.subscribed() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!WATCH.subscribed(), "a closed connection is not counted on the watch"); + } + /// A timed-out request that only reads is not said to "still apply", nor is one that only /// writes a file (an export, #1989); a change is, by name. #[test] diff --git a/apps/solidcraft/src/desktop_theme.rs b/apps/solidcraft/src/desktop_theme.rs new file mode 100644 index 000000000..2a0ca24c4 --- /dev/null +++ b/apps/solidcraft/src/desktop_theme.rs @@ -0,0 +1,195 @@ +//! Linux: the desktop's dark or light preference, for Theme: System (#7944). +//! +//! The window toolkit does not pass it on everywhere: on GNOME (Wayland, or X11 through XWayland) +//! the window never learns it, nor when it changes, so the app kept its colours. This reads the +//! freedesktop setting through the XDG Desktop Portal's Settings interface on the session bus +//! (`org.freedesktop.appearance color-scheme`, then GNOME's `color-scheme` and `gtk-theme`), the +//! same setting other applications follow, and inside a Flatpak too. It runs on a thread of its +//! own: the first reading, then the portal's `SettingChanged` signal; where the signal can't be +//! had, a reading every few seconds. Without a portal it asks `gsettings` instead, on the same +//! thread. The window reads the last answer with an atomic load +//! (`solidcraft_ui_egui::Services::desktop_dark`), and the decision from the raw values is +//! `solidcraft_ui_egui::prefs::desktop_prefers_dark`. + +use std::io::Read; +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::Duration; + +use zbus::zvariant::{OwnedValue, Value}; + +const UNKNOWN: u8 = 0; +const DARK: u8 = 1; +const LIGHT: u8 = 2; + +/// How often to read again where the portal's change signal is not available. +const POLL: Duration = Duration::from_secs(5); +/// How long one `gsettings` reading may take before it is given up. +const GSETTINGS_TIMEOUT: Duration = Duration::from_secs(2); + +const PORTAL: &str = "org.freedesktop.portal.Desktop"; +const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; +const SETTINGS: &str = "org.freedesktop.portal.Settings"; +const APPEARANCE: &str = "org.freedesktop.appearance"; +const GNOME: &str = "org.gnome.desktop.interface"; + +/// Start following the desktop's preference; the closure answers the latest reading (`None` +/// until there is one, or when the desktop says nothing). +pub fn start(ctx: &egui::Context) -> Box Option> { + let state = Arc::new(AtomicU8::new(UNKNOWN)); + let (thread_state, ctx) = (state.clone(), ctx.clone()); + if let Err(e) = std::thread::Builder::new().name("desktop-theme".into()).spawn(move || follow(&thread_state, &ctx)) { + log::warn!("desktop theme: no thread to follow it: {e}"); + } + Box::new(move || match state.load(Ordering::Relaxed) { + DARK => Some(true), + LIGHT => Some(false), + _ => None, + }) +} + +/// Keep `state` on the desktop's preference, asking for a frame whenever it changes. +fn follow(state: &AtomicU8, ctx: &egui::Context) { + let publish = |dark: Option| { + let code = match dark { + Some(true) => DARK, + Some(false) => LIGHT, + None => UNKNOWN, + }; + if state.swap(code, Ordering::Relaxed) != code { + ctx.request_repaint(); + } + }; + let portal = match portal() { + Ok(p) => Some(p), + Err(e) => { + log::info!("desktop theme: no settings portal ({e}); asking gsettings"); + None + } + }; + // The portal first; gsettings where there is none or it says nothing (its backend missing). + let read = |portal: Option<&zbus::blocking::Proxy<'static>>| portal.and_then(read_portal).or_else(read_gsettings); + let from_portal = portal.as_ref().and_then(read_portal); + let first = from_portal.or_else(read_gsettings); + publish(first); + // Wait for the portal's signal only when the portal answers: else the reading is gsettings', + // which only a new reading notices. + if let Some(p) = portal.as_ref().filter(|_| from_portal.is_some()) { + match p.receive_signal("SettingChanged") { + Ok(changes) => { + for message in changes { + if relevant(&message) { + publish(read(Some(p))); + } + } + log::info!("desktop theme: the portal's change signal ended; reading every few seconds"); + } + Err(e) => log::info!("desktop theme: no change signal ({e}); reading every few seconds"), + } + } else if portal.is_none() && first.is_none() && !gsettings_available() { + // Neither the portal nor gsettings: nothing to follow; the window toolkit's theme stays. + return; + } + loop { + std::thread::sleep(POLL); + publish(read(portal.as_ref())); + } +} + +/// The portal's Settings interface on the session bus. +fn portal() -> zbus::Result> { + let connection = zbus::blocking::Connection::session()?; + zbus::blocking::Proxy::new(&connection, PORTAL, PORTAL_PATH, SETTINGS) +} + +/// One reading through the portal. +fn read_portal(portal: &zbus::blocking::Proxy<'static>) -> Option { + let appearance = read_setting(portal, APPEARANCE, "color-scheme").and_then(|v| as_u32(&v)); + // The GNOME settings only matter when the freedesktop one has no preference. + if matches!(appearance, Some(1 | 2)) { + return solidcraft_ui_egui::prefs::desktop_prefers_dark(appearance, None, None); + } + let gnome = read_setting(portal, GNOME, "color-scheme").and_then(|v| as_string(&v)); + let gtk_theme = read_setting(portal, GNOME, "gtk-theme").and_then(|v| as_string(&v)); + solidcraft_ui_egui::prefs::desktop_prefers_dark(appearance, gnome.as_deref(), gtk_theme.as_deref()) +} + +/// A setting through `ReadOne` (portal version 2), else the older `Read`. +fn read_setting(portal: &zbus::blocking::Proxy<'static>, namespace: &str, key: &str) -> Option { + let one: zbus::Result = portal.call("ReadOne", &(namespace, key)); + one.or_else(|_| -> zbus::Result { portal.call("Read", &(namespace, key)) }).ok() +} + +/// Whether a `SettingChanged` signal is about a setting the preference is read from. +fn relevant(message: &zbus::Message) -> bool { + let body = message.body(); + let Ok((namespace, key, _)) = body.deserialize::<(String, String, OwnedValue)>() else { return false }; + matches!((namespace.as_str(), key.as_str()), (APPEARANCE, "color-scheme") | (GNOME, "color-scheme" | "gtk-theme")) +} + +/// The value inside the variants `Read` wraps it in (a portal answers one or two deep). +fn unwrap_variants<'v, 'a>(value: &'v Value<'a>) -> &'v Value<'a> { + let mut value = value; + for _ in 0..4 { + match value { + Value::Value(inner) => value = &**inner, + _ => break, + } + } + value +} + +fn as_u32(value: &Value<'_>) -> Option { + match unwrap_variants(value) { + Value::U32(n) => Some(*n), + Value::I32(n) => u32::try_from(*n).ok(), + Value::U8(n) => Some(u32::from(*n)), + _ => None, + } +} + +fn as_string(value: &Value<'_>) -> Option { + match unwrap_variants(value) { + Value::Str(s) => Some(s.as_str().to_string()), + _ => None, + } +} + +/// Without a portal: GNOME's settings through `gsettings` (`None` when it is not there). +fn read_gsettings() -> Option { + let gnome = gsettings("color-scheme"); + let gtk_theme = gsettings("gtk-theme"); + solidcraft_ui_egui::prefs::desktop_prefers_dark(None, gnome.as_deref(), gtk_theme.as_deref()) +} + +fn gsettings_available() -> bool { + gsettings("gtk-theme").is_some() +} + +/// `gsettings get org.gnome.desktop.interface `, its quoted answer, or `None` when the +/// program is missing, fails or does not answer in time. +fn gsettings(key: &str) -> Option { + let mut child = std::process::Command::new("gsettings") + .args(["get", GNOME, key]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .ok()?; + let started = std::time::Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) if status.success() => break, + Ok(None) if started.elapsed() < GSETTINGS_TIMEOUT => std::thread::sleep(Duration::from_millis(20)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + } + let mut out = String::new(); + child.stdout.take()?.take(4096).read_to_string(&mut out).ok()?; + let value = out.trim().trim_matches('\'').to_string(); + (!value.is_empty()).then_some(value) +} diff --git a/apps/solidcraft/src/desktop_transparency.rs b/apps/solidcraft/src/desktop_transparency.rs new file mode 100644 index 000000000..cb0a125cc --- /dev/null +++ b/apps/solidcraft/src/desktop_transparency.rs @@ -0,0 +1,63 @@ +//! Cached accessibility signal, observed only while a theme offers blur. No UI-thread IO. +use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicU8, Ordering}, +}; + +#[derive(Default)] +struct Reading { + needed: AtomicBool, + started: AtomicBool, + value: AtomicU8, +} + +pub fn cached(ctx: &egui::Context) -> Box Option> { + let state = Arc::new(Reading::default()); + let ctx = ctx.clone(); + Box::new(move |needed| { + state.needed.store(needed, Ordering::Relaxed); + if needed && !state.started.swap(true, Ordering::Relaxed) { + let weak = Arc::downgrade(&state); + let ctx = ctx.clone(); + if let Err(error) = std::thread::Builder::new().name("desktop-transparency".into()).spawn(move || { + while let Some(state) = weak.upgrade() { + if state.needed.load(Ordering::Relaxed) { + let code = match read() { + Some(true) => 1, + Some(false) => 2, + None => 0, + }; + if state.value.swap(code, Ordering::Relaxed) != code { + ctx.request_repaint(); + } + } + drop(state); + std::thread::sleep(std::time::Duration::from_secs(5)); + } + }) { + log::warn!("desktop transparency: could not observe accessibility setting: {error}"); + } + } + match state.value.load(Ordering::Relaxed) { + 1 => Some(true), + 2 => Some(false), + _ => None, + } + }) +} + +#[cfg(target_os = "windows")] +fn read() -> Option { + let key = + winreg::RegKey::predef(winreg::enums::HKEY_CURRENT_USER).open_subkey(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").ok()?; + match key.get_value::("EnableTransparency").ok()? { + 0 => Some(true), + 1 => Some(false), + _ => None, + } +} + +#[cfg(target_os = "macos")] +fn read() -> Option { + objc2::rc::autoreleasepool(|_| Some(objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceTransparency())) +} diff --git a/apps/solidcraft/src/device_lost.rs b/apps/solidcraft/src/device_lost.rs index b892723c3..2f598c69c 100644 --- a/apps/solidcraft/src/device_lost.rs +++ b/apps/solidcraft/src/device_lost.rs @@ -5,12 +5,25 @@ //! for recovery as a forced quit does, and starts again ([`restart`]), and the new start says what //! happened ([`note`]). A device lost again soon after such a restart starts the next one on the //! software renderer, which doesn't depend on the graphics driver. +//! +//! The old process ends without tearing down its GPU objects ([`end`]): on a lost NVIDIA device +//! destroying the window's swap chain busy-waits in the driver and never returns (#9044). use crate::startup; /// Set on the start after a lost device: when the device was lost (seconds since 1970). pub const LOST_ENV: &str = "SOLIDCRAFT_DEVICE_LOST"; +/// Set on the start after a lost device: why it was lost, as wgpu said it. The old process's +/// session journal, which recorded it, is gone by then. +pub const REASON_ENV: &str = "SOLIDCRAFT_DEVICE_LOST_REASON"; + +/// The longest reason passed on ([`REASON_ENV`]) and shown, in characters. +const REASON_CHARS: usize = 300; + +/// How long the process may take to end ([`end`]) before it is aborted. +const END_GRACE: std::time::Duration = std::time::Duration::from_secs(3); + /// A loss this recent (seconds) counts for the start after it: its note, and a second loss /// within it starts on the software renderer. Inherited by later starts, an older stamp is /// ignored. @@ -32,27 +45,54 @@ pub fn restart_on_software(after_recent_loss: bool, cpu_renderer: bool) -> bool after_recent_loss || cpu_renderer } +/// `reason` on one line, at most [`REASON_CHARS`] long; None when there is nothing to say. +pub fn reason(reason: Option<&str>) -> Option { + let line = reason?.split_whitespace().collect::>().join(" "); + (!line.is_empty()).then(|| line.chars().take(REASON_CHARS).collect()) +} + /// What the start after a lost device tells the user, `software` when it runs on the software -/// renderer. -pub fn note(software: bool) -> String { +/// renderer, with what the driver reported ([`REASON_ENV`]). +pub fn note(software: bool, reason: Option<&str>) -> String { let mut note = String::from( "The graphics device was reset (the graphics driver stopped responding), so SolidCraft closed and started again. Unsaved changes were kept for recovery.", ); if software { note.push_str(" This start uses software rendering, which doesn't depend on the graphics driver."); } + if let Some(reason) = self::reason(reason) { + note.push_str(&format!(" The graphics driver reported: {reason}")); + } note } -/// Start SolidCraft again with the same arguments, the loss stamped at `lost_at`, on the software -/// renderer when `software`. -pub fn restart(software: bool, lost_at: u64) { - let Ok(exe) = std::env::current_exe() else { return }; +/// The command that starts `exe` again with `args`, the loss stamped at `lost_at` and its +/// `reason`, on the software renderer when `software`. +fn command( + exe: std::path::PathBuf, + args: impl IntoIterator, + software: bool, + lost_at: u64, + reason: &str, +) -> std::process::Command { let mut command = std::process::Command::new(exe); - command.args(std::env::args_os().skip(1)).env(LOST_ENV, lost_at.to_string()); + command.args(args).env(LOST_ENV, lost_at.to_string()); + match self::reason(Some(reason)) { + Some(reason) => command.env(REASON_ENV, reason), + // Not one inherited from an earlier loss. + None => command.env_remove(REASON_ENV), + }; if software { command.env(startup::RENDERER_ENV, "cpu"); } + command +} + +/// Start SolidCraft again with the same arguments, the loss stamped at `lost_at` and its `reason`, +/// on the software renderer when `software`. +pub fn restart(software: bool, lost_at: u64, reason: &str) { + let Ok(exe) = std::env::current_exe() else { return }; + let mut command = command(exe, std::env::args_os().skip(1), software, lost_at, reason); #[cfg(windows)] { use std::os::windows::process::CommandExt; @@ -64,6 +104,23 @@ pub fn restart(software: bool, lost_at: u64) { } } +/// End the process now, without tearing down what is left on the lost device: the window's swap +/// chain, the viewport's buffers and pipelines. On NVIDIA's Vulkan driver destroying the swap +/// chain of a lost device busy-waits forever, which left the old window frozen at 100% of a core +/// beside the new one (#9044). Should the exit itself get stuck in a library's exit handler, the +/// process is aborted after [`END_GRACE`]. +pub fn end() -> ! { + let watchdog = std::thread::Builder::new().name("solidcraft-exit".into()).spawn(|| { + std::thread::sleep(END_GRACE); + eprintln!("SolidCraft graphics: still closing after the device was lost; aborting"); + std::process::abort(); + }); + if let Err(e) = watchdog { + log::warn!("graphics: no exit watchdog: {e}"); + } + std::process::exit(0) +} + #[cfg(test)] mod tests { /// Only a recent, well-formed stamp counts: a later start that inherited it says nothing. @@ -84,8 +141,34 @@ mod tests { assert!(!super::restart_on_software(false, false)); assert!(super::restart_on_software(true, false)); assert!(super::restart_on_software(false, true)); - assert!(super::note(true).contains("software rendering")); - assert!(!super::note(false).contains("software rendering")); - assert!(super::note(false).contains("kept for recovery")); + assert!(super::note(true, None).contains("software rendering")); + assert!(!super::note(false, None).contains("software rendering")); + assert!(super::note(false, None).contains("kept for recovery")); + } + + /// The start after a loss is told why (#9044): the old process's journal held the reason, and + /// it is deleted as that process closes. + #[test] + fn the_next_start_is_told_why_the_device_was_lost() { + let exe = std::path::PathBuf::from("solidcraft"); + let args = ["--control".into(), "7979".into()]; + let command = super::command(exe.clone(), args, true, 1_000, "Lost: Device lost\n (vkQueueSubmit)"); + let env = |command: &std::process::Command, name: &str| { + command.get_envs().find(|(k, _)| *k == name).map(|(_, v)| v.map(|v| v.to_string_lossy().into_owned())) + }; + assert_eq!(env(&command, super::LOST_ENV), Some(Some("1000".into()))); + assert_eq!(env(&command, super::REASON_ENV), Some(Some("Lost: Device lost (vkQueueSubmit)".into())), "on one line"); + assert_eq!(env(&command, crate::startup::RENDERER_ENV), Some(Some("cpu".into()))); + assert_eq!(command.get_args().collect::>(), ["--control", "7979"]); + // No reason: none inherited from an earlier loss either. + let command = super::command(exe, Vec::new(), false, 1_000, " "); + assert_eq!(env(&command, super::REASON_ENV), Some(None)); + assert_eq!(env(&command, crate::startup::RENDERER_ENV), None); + + let note = super::note(false, Some("Lost: Device lost")); + assert!(note.ends_with("The graphics driver reported: Lost: Device lost"), "{note}"); + assert!(!super::note(false, Some(" \n ")).contains("reported")); + let long = "x".repeat(1_000); + assert_eq!(super::reason(Some(&long)).map(|r| r.chars().count()), Some(300)); } } diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 505f1518e..cbead5a1d 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -22,6 +22,10 @@ mod app_icon; mod come_forward; mod control_server; +#[cfg(target_os = "linux")] +mod desktop_theme; +#[cfg(any(target_os = "windows", target_os = "macos"))] +mod desktop_transparency; mod device_lost; #[cfg(target_os = "windows")] mod native_crash; @@ -97,6 +101,86 @@ struct App { nav_bridge: nav_bridge::NavBridge, /// Where the next file dialog opens: it follows the open design (#7756). dialog_folder: DialogFolder, + /// Settings go to `app.ron` in the frame they change (#8275). + prefs_writer: PrefsWriter, +} + +/// Settings written to the settings file soon after they change (#8275). eframe saves them +/// only every 30 s and when the window closes normally, so a change was lost whenever the app +/// did not get that far: ended from the Task Manager, stopped by a sign-out or shutdown, or +/// crashed or hung in the graphics driver on the way out. +/// +/// Some settings change continuously (a panel's width while its edge is dragged), so the file +/// is written at most once per [`PrefsWriter::INTERVAL`], and a change made in between is written +/// when that interval ends. +#[derive(Default)] +struct PrefsWriter { + /// The settings written (or read at start) last. + written: Option, + /// The previous frame had input that can change settings: what it changed shows in this + /// frame's settings. + input_before: bool, + /// When the settings were last written by this writer. + last_write: Option, + /// A change waits until then to be written. + pending_until: Option, +} + +impl PrefsWriter { + /// The least time between two writes of the settings file. + const INTERVAL: std::time::Duration = std::time::Duration::from_secs(1); + + /// The settings as they were read at start: they are on disk already. + fn read(prefs: String) -> Self { + Self { written: Some(prefs), ..Self::default() } + } + + /// Whether this frame's settings are worth comparing: input that can change them came in this + /// frame or the one before, or a waiting change's time has come. Pointer motion alone isn't + /// such input; eframe's own save still catches anything else. + fn due(&mut self, input: bool, now: std::time::Instant) -> bool { + let due = input || self.input_before || self.pending_until.is_some_and(|at| now >= at); + self.input_before = input; + due + } + + /// Write `prefs` and flush them to disk if they differ from the settings written last and the + /// last write is at least [`Self::INTERVAL`] old. Returns how long a change waits otherwise: + /// the caller asks for a frame then, so an idle app still writes it. + fn store(&mut self, storage: &mut dyn eframe::Storage, prefs: String, now: std::time::Instant) -> Option { + if self.written.as_deref() == Some(prefs.as_str()) { + self.pending_until = None; + return None; + } + if let Some(wait) = self.last_write.map(|at| Self::INTERVAL.saturating_sub(now.saturating_duration_since(at))).filter(|w| !w.is_zero()) { + self.pending_until = Some(now + wait); + return Some(wait); + } + storage.set_string(solidcraft_ui_egui::prefs::STORAGE_KEY, prefs.clone()); + storage.flush(); + self.written = Some(prefs); + self.last_write = Some(now); + self.pending_until = None; + None + } +} + +/// Input that can change a setting: a click, a key, typed or pasted text, a wheel or a pinch. +/// Pointer motion, which comes every frame while the mouse moves, cannot by itself. +fn changes_settings(event: &egui::Event) -> bool { + matches!( + event, + egui::Event::PointerButton { .. } + | egui::Event::Key { .. } + | egui::Event::Text(_) + | egui::Event::Paste(_) + | egui::Event::Cut + | egui::Event::Ime(_) + | egui::Event::MouseWheel { .. } + | egui::Event::Zoom(_) + | egui::Event::Rotate(_) + | egui::Event::AccessKitActionRequest(_) + ) } impl eframe::App for App { @@ -184,11 +268,21 @@ impl eframe::App for App { solidcraft_ui_egui::space_mouse::buttons_hook(&mut self.solve, ctx, self.space_mouse.buttons(), raw); self.solve.raw_input_hook(raw); } - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { content_ui(&mut self.solve, ui); + // After the frame's UI, so a setting changed in it (Preferences' OK) is written now. + let now = std::time::Instant::now(); + if self.prefs_writer.due(ui.input(|i| i.events.iter().any(changes_settings)), now) + && let Some(storage) = frame.storage_mut() + && let Some(wait) = self.prefs_writer.store(storage, self.solve.prefs(), now) + { + ui.ctx().request_repaint_after(wait); + } } fn save(&mut self, storage: &mut dyn eframe::Storage) { - storage.set_string(solidcraft_ui_egui::prefs::STORAGE_KEY, self.solve.prefs()); + let prefs = self.solve.prefs(); + storage.set_string(solidcraft_ui_egui::prefs::STORAGE_KEY, prefs.clone()); + self.prefs_writer.written = Some(prefs); } fn on_exit(&mut self) { // The agent chat's agent and everything it started end with the app. @@ -202,13 +296,29 @@ impl eframe::App for App { } solidcraft_ui_egui::recovery_ui::close(&mut self.solve); solidcraft_ui_egui::open_elsewhere::close(&mut self.solve); - // Before a restart below starts the next instance, which would otherwise get nothing from - // the 3D mouse driver (`solidcraft_3dx_client::stop`). + // Before a restart (`Drop for App`) starts the next instance, which would otherwise get + // nothing from the 3D mouse driver (`solidcraft_3dx_client::stop`). #[cfg(target_os = "macos")] solidcraft_3dx_client::stop(); solidcraft_engine::crash::end_session(); - if let Some(lost_at) = self.gpu.as_ref().and_then(|g| g.lost_at) { - device_lost::restart(self.gpu.as_ref().is_some_and(|g| g.restart_on_software), lost_at); + // The next start (after a lost device, or into an update) begins once the app is dropped + // (`Drop for App`), when the settings are on disk. + } +} + +impl Drop for App { + /// eframe drops its settings storage first, which waits for `app.ron` to be written, then the + /// app, then the window and its GPU surface. So the next start begins here: started from + /// `on_exit`, it read `app.ron` while the old process was still writing it, found it + /// unreadable and moved it aside, resetting every setting (#9044). + fn drop(&mut self) { + if let Some(gpu) = &self.gpu + && let Some(lost_at) = gpu.lost_at + { + device_lost::restart(gpu.restart_on_software, lost_at, &gpu.reason); + // The window's GPU surface is still to be dropped, and on a lost device that may + // never return (#9044). + device_lost::end(); } // An update asked to restart into the new version or to run its installer. if let Some((program, args)) = solidcraft_ui_egui::update::take_launch(&mut self.solve) { @@ -236,6 +346,8 @@ struct LostWatch { restart_on_software: bool, /// When the loss was seen: the app is closing to start again. lost_at: Option, + /// Why, as wgpu said it: passed to the next start ([`device_lost::REASON_ENV`]). + reason: String, } impl App { @@ -249,6 +361,7 @@ impl App { eprintln!("SolidCraft graphics: the device was lost ({reason}); starting again"); solidcraft_engine::crash::phase(&format!("graphics device lost: {reason}")); gpu.lost_at = Some(device_lost::now_secs()); + gpu.reason = reason; self.solve.quit_requested = true; } } @@ -422,6 +535,16 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services graphics_adapters: Vec::new(), graphics_path: graphics_path().map(|p| p.to_string_lossy().to_string()), window_system: window_system_now(), + // Linux: the desktop's dark or light setting, which the window is not told on every + // desktop (#7944). Windows and macOS: the window's own theme. + #[cfg(target_os = "linux")] + desktop_dark: Some(desktop_theme::start(&cc.egui_ctx)), + #[cfg(not(target_os = "linux"))] + desktop_dark: None, + #[cfg(any(target_os = "windows", target_os = "macos"))] + reduce_transparency: Some(desktop_transparency::cached(&cc.egui_ctx)), + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + reduce_transparency: None, http_get: Some(std::sync::Arc::new(http_get)), http_download: Some(std::sync::Arc::new(http_download)), // Already an installed app: only the browser build offers to install. @@ -701,6 +824,24 @@ fn msaa() -> Option { /// (`solidcraft_ui_egui::titlebar`). macOS keeps its traffic lights over the integrated bar. const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos"); +/// Linux: the window manager's own decorations (server-side, or the compositor's frame) can be +/// asked for instead of the application bar ([`titlebar_choice`]). Elsewhere always `true`. +fn app_titlebar_wanted() -> bool { + if !cfg!(all(unix, not(target_os = "macos"))) { + return true; + } + let setting = graphics().and_then(|v| v.get("titlebar").and_then(serde_json::Value::as_str).map(str::to_string)); + titlebar_choice(solidcraft_engine::geom::env::var("TITLEBAR").as_deref(), setting.as_deref()) +} + +/// Linux: whether the application bar is the title bar. `SOLIDCRAFT_TITLEBAR` (else +/// `graphics.json`'s `titlebar`) set to `system` gives the window the desktop's own title bar and +/// buttons; `app` (or anything else, or nothing) keeps the application bar as the title bar. +fn titlebar_choice(env: Option<&str>, setting: Option<&str>) -> bool { + let choice = env.map(str::trim).filter(|v| !v.is_empty()).or(setting.map(str::trim)); + !choice.is_some_and(|v| v.eq_ignore_ascii_case("system")) +} + const DEPTH_BITS: u8 = 24; /// A 32-bit float depth buffer, drawn with reversed depth (1 near, 0 far) so its precision follows /// the distance from the eye (#1434). Only where every adapter offers it with a stencil @@ -750,6 +891,18 @@ fn main() -> eframe::Result { #[cfg(target_os = "macos")] objc2_foundation::NSProcessInfo::processInfo().setProcessName(objc2_foundation::ns_string!("SolidCraft")); mark("main"); + // On OCLP-patched Macs, wgpu picks a Metal Shading Language standard that the system's + // compiler refuses (`invalid value 'metal3.2'`), because the patched OS reports a newer + // macOS version than the GPU's Metal compiler supports. Re-launching with + // SYSTEM_VERSION_COMPAT=1 makes the OS report the real (older) version so wgpu selects + // a standard the compiler accepts. The variable must be set before the process starts, so + // we detect OCLP here and re-exec immediately, before any macOS framework call (#3080, #4605). + #[cfg(target_os = "macos")] + if let Err(e) = startup::relaunch_with_version_compat() { + log::warn!("startup: OCLP check failed (continuing normally): {e}"); + } + // SOLIDCRAFT_PROFILE=1: the profiler records from the start (diagnostics.profile reads it). + solidcraft_engine::timing::profile_from_env(); // Validate before legacy adoption, crash markers or any user preference read. let settings = settings_dir().map_err(|error| eframe::Error::AppCreation(error.into()))?; if std::env::var_os("SOLIDCRAFT_SETTINGS_DIR").is_none() { @@ -821,7 +974,11 @@ fn main() -> eframe::Result { // The launch before this one closed because its graphics device was lost (`App::watch_device`). let after_loss = device_lost::recent(std::env::var(device_lost::LOST_ENV).ok().as_deref(), device_lost::now_secs()); if after_loss { - notes.push(device_lost::note(cpu_renderer)); + let reason = std::env::var(device_lost::REASON_ENV).ok(); + if let Some(reason) = device_lost::reason(reason.as_deref()) { + log::warn!("graphics: the last launch lost its device ({reason})"); + } + notes.push(device_lost::note(cpu_renderer, reason.as_deref())); } if safe_mode { notes.push("Safe mode: default settings (yours are kept for the next normal start), no recovery offer, software rendering.".into()); @@ -857,7 +1014,7 @@ fn main() -> eframe::Result { eframe::egui_wgpu::WgpuSetup::CreateNew(setup) => setup.instance_descriptor.backends, _ => eframe::wgpu::Backends::all(), }; - let custom_titlebar = CUSTOM_TITLEBAR && !startup::system_title_bar(cfg!(target_os = "windows"), started); + let custom_titlebar = CUSTOM_TITLEBAR && app_titlebar_wanted() && !startup::system_title_bar(cfg!(target_os = "windows"), started); eframe::egui_wgpu::set_startup_hook(startup_step); solidcraft_engine::crash::phase("window"); let options = eframe::NativeOptions { @@ -961,6 +1118,7 @@ fn main() -> eframe::Result { lost: rs.device_lost.clone(), restart_on_software: device_lost::restart_on_software(after_loss, cpu_renderer), lost_at: None, + reason: String::new(), }); if !safe_mode { app.preferences.graphics_adapter = @@ -976,6 +1134,12 @@ fn main() -> eframe::Result { }) .collect(); let info = rs.adapter.get_info(); + if !app.preferences.graphics_adapter.is_empty() && !info.name.eq_ignore_ascii_case(app.preferences.graphics_adapter.as_str()) { + eprintln!( + "SolidCraft graphics: preferred adapter {:?} was not used; using {:?} instead", + app.preferences.graphics_adapter, info.name + ); + } let samples = scene_msaa_request(saved_samples); let supported = scene_sample_choices(depth_bits, STENCIL_BITS, |depth| { eframe::egui_wgpu::supported_msaa_samples(&rs.adapter, &rs.device, rs.target_format, depth) @@ -1080,6 +1244,8 @@ fn main() -> eframe::Result { mark("app created"); solidcraft_engine::crash::phase("first frame"); Ok(Box::new(App { + // Before `app` moves: the settings as read, already on disk. + prefs_writer: PrefsWriter::read(app.prefs()), solve: app, starting, frames: 0, @@ -1103,12 +1269,13 @@ fn main() -> eframe::Result { } /// egui-wgpu is about to start a step of getting the graphics device and the window's surface up: -/// the crash journal keeps it, and the adapter once it is picked. +/// the crash journal keeps it until the app runs (a window opened later goes through the same +/// steps), and the adapter once it is picked. fn startup_step(step: &'static str, detail: &str) { if step == eframe::egui_wgpu::STEP_ADAPTER_CHOSEN { solidcraft_engine::crash::set_environment(&format!("Renderer: {detail}")); } - solidcraft_engine::crash::phase(step); + solidcraft_engine::crash::startup_step(step); } /// The renderer settings: with `cpu`, the software adapter (WARP, lavapipe, llvmpipe). The @@ -1270,6 +1437,148 @@ mod backend_tests { assert!(!prefer_x11(true, true, Some("GNOME"), over(Some("wayland")))); assert!(prefer_x11(true, true, Some("niri"), over(Some("x11")))); } + + #[test] + fn the_desktops_title_bar_only_when_asked_for() { + use super::titlebar_choice; + // Nothing set: the application bar is the title bar, as before. + assert!(titlebar_choice(None, None)); + // graphics.json's `titlebar`. + assert!(!titlebar_choice(None, Some("system"))); + assert!(titlebar_choice(None, Some("app"))); + // SOLIDCRAFT_TITLEBAR wins over the file; empty counts as unset; case and spaces don't matter. + assert!(!titlebar_choice(Some(" System "), Some("app"))); + assert!(titlebar_choice(Some("app"), Some("system"))); + assert!(!titlebar_choice(Some(""), Some("system"))); + // Anything unknown keeps the application bar. + assert!(titlebar_choice(Some("ssd"), None)); + } +} + +#[cfg(test)] +mod prefs_writer_tests { + use super::PrefsWriter; + use solidcraft_ui_egui::prefs::{NavigatorStyle, STORAGE_KEY}; + use std::collections::HashMap; + use std::time::{Duration, Instant}; + + /// eframe's settings file: what was flushed to disk is what the next start reads. + #[derive(Default)] + struct Disk { + pending: HashMap, + flushed: HashMap, + flushes: usize, + } + + impl eframe::Storage for Disk { + fn get_string(&self, key: &str) -> Option { + self.pending.get(key).cloned() + } + fn set_string(&mut self, key: &str, value: String) { + self.pending.insert(key.into(), value); + } + fn remove_string(&mut self, key: &str) { + self.pending.remove(key); + } + fn flush(&mut self) { + self.flushed = self.pending.clone(); + self.flushes += 1; + } + } + + fn new_app() -> solidcraft_ui_egui::SolveApp { + solidcraft_ui_egui::SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default()) + } + + /// #8275: Preferences' View navigator and Display quality, changed and confirmed, are on disk + /// in that frame, so the next start has them even when this one never closes normally (ended + /// from the Task Manager, a sign-out, a hang or crash in the graphics driver on the way out). + #[test] + fn changed_settings_reach_the_disk_in_the_frame_they_change() { + let mut app = new_app(); + let mut disk = Disk::default(); + let mut writer = PrefsWriter::read(app.prefs()); + let now = Instant::now(); + assert_eq!(writer.store(&mut disk, app.prefs(), now), None); + assert_eq!(disk.flushes, 0, "the settings read at start are not written again"); + app.preferences.navigator_style = NavigatorStyle::Cube; + app.preferences.display_quality = "fine".into(); + assert!(writer.due(true, now), "a frame with input is checked"); + assert_eq!(writer.store(&mut disk, app.prefs(), now), None); + assert_eq!(disk.flushes, 1, "flushed at once, not left for eframe's next save"); + assert_eq!(writer.store(&mut disk, app.prefs(), now + Duration::from_secs(5)), None); + assert_eq!(disk.flushes, 1, "unchanged settings are not written again"); + + // The next start reads them. + let mut next = new_app(); + let stored = solidcraft_ui_egui::prefs::stored(|k| disk.flushed.get(k).cloned()).expect("settings on disk"); + next.load_prefs(&stored); + assert_eq!(next.preferences.navigator_style, NavigatorStyle::Cube); + assert_eq!(next.preferences.display_quality, "fine"); + assert!(disk.flushed.contains_key(STORAGE_KEY)); + } + + /// A frame without input is checked only right after one with input (whose clicks the UI + /// handled in that frame); after that, idle frames cost nothing. Pointer motion, which comes + /// every frame while the mouse moves, doesn't count as input. + #[test] + fn frames_are_checked_with_input_and_once_after_it() { + let now = Instant::now(); + let mut writer = PrefsWriter::default(); + assert!(!writer.due(false, now)); + assert!(writer.due(true, now)); + assert!(writer.due(false, now), "the frame after input"); + assert!(!writer.due(false, now)); + + let click = egui::Event::PointerButton { + pos: egui::Pos2::ZERO, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }; + assert!(super::changes_settings(&click)); + assert!(super::changes_settings(&egui::Event::Text("5".into()))); + assert!(!super::changes_settings(&egui::Event::PointerMoved(egui::Pos2::ZERO))); + assert!(!super::changes_settings(&egui::Event::MouseMoved(egui::Vec2::X))); + } + + /// A setting that changes in every frame (a panel's width while its edge is dragged) doesn't + /// write the file in every frame: at most once a second, and the last change is on disk at + /// most a second after it was made, with a frame asked for then so an idle app writes it. + #[test] + fn a_continuous_change_is_written_once_a_second_and_its_end_soon_after() { + let mut app = new_app(); + let mut disk = Disk::default(); + let mut writer = PrefsWriter::read(app.prefs()); + let start = Instant::now(); + let frame = Duration::from_millis(16); + let mut asked = None; + // 1.5 s of dragging at 60 frames a second, with input in every frame. + for n in 0..94u32 { + let now = start + frame * n; + app.preferences.browser_width = 200.0 + n as f32; + assert!(writer.due(true, now)); + asked = writer.store(&mut disk, app.prefs(), now); + } + assert_eq!(disk.flushes, 2, "the first change at once, then one a second later"); + let wait = asked.expect("the last width waits, and a frame is asked for when it can be written"); + assert!(wait <= PrefsWriter::INTERVAL); + + // The drag ends: no more input. Frames before the wait is over don't even look. + let end = start + frame * 93; + assert!(writer.due(false, end + frame), "the frame right after input"); + assert!(!writer.due(false, end + frame * 2), "an idle frame before the wait is over"); + // The frame asked for writes the last width. + let then = end + wait; + assert!(writer.due(false, then)); + assert_eq!(writer.store(&mut disk, app.prefs(), then), None); + assert_eq!(disk.flushes, 3); + let mut next = new_app(); + let stored = solidcraft_ui_egui::prefs::stored(|k| disk.flushed.get(k).cloned()).expect("settings on disk"); + next.load_prefs(&stored); + assert_eq!(next.preferences.browser_width, 293.0, "the width the drag ended at"); + assert!(!writer.due(false, then + frame), "nothing waits any more"); + } } #[cfg(test)] diff --git a/apps/solidcraft/src/native_menu.rs b/apps/solidcraft/src/native_menu.rs index 1d75df7a8..0e64b5387 100644 --- a/apps/solidcraft/src/native_menu.rs +++ b/apps/solidcraft/src/native_menu.rs @@ -101,6 +101,7 @@ impl NativeMenu { ])?; for (action, label) in [ ("docs", "Documentation"), + ("updates", app.tr("update.check_for_updates")), ("shortcuts", "Keyboard Shortcuts"), ("messages", "Messages\u{2026}"), ("report", "Report an Issue\u{2026}"), diff --git a/apps/solidcraft/src/startup.rs b/apps/solidcraft/src/startup.rs index a5fdbd403..683ded4ad 100644 --- a/apps/solidcraft/src/startup.rs +++ b/apps/solidcraft/src/startup.rs @@ -137,8 +137,11 @@ pub struct AdapterChoice { pub compatible: bool, } -/// Choose only surface-compatible adapters. Names saved in preferences are exact; the -/// environment override follows wgpu's case-insensitive substring convention. +/// Choose an adapter by name. The environment override follows wgpu's case-insensitive +/// substring convention among surface-compatible adapters. A saved preference prefers an +/// exact (then case-insensitive) name among compatible adapters, and if the named card is +/// only listed as incompatible with the surface still picks it (#8341: otherwise the +/// preference is kept in the dialog while wgpu silently uses another GPU). /// No match leaves selection to the normal wgpu request. pub fn choose_adapter(adapters: &[AdapterChoice], environment: Option<&str>, preference: Option<&str>) -> Option { // wgpu's environment helper panics on a missing name; an override must remain recoverable. @@ -149,12 +152,14 @@ pub fn choose_adapter(adapters: &[AdapterChoice], environment: Option<&str>, pre return Some(index); } } - if let Some(name) = preference.filter(|s| !s.is_empty()) - && let Some((index, _)) = compatible().find(|(_, a)| a.name == name) - { - return Some(index); - } - None + let name = preference.filter(|s| !s.is_empty())?; + let find = |pred: &dyn Fn(&AdapterChoice) -> bool, only_compatible: bool| { + adapters.iter().enumerate().find(|(_, a)| (!only_compatible || a.compatible) && pred(a)).map(|(i, _)| i) + }; + find(&|a| a.name == name, true) + .or_else(|| find(&|a| a.name.eq_ignore_ascii_case(name), true)) + .or_else(|| find(&|a| a.name == name, false)) + .or_else(|| find(&|a| a.name.eq_ignore_ascii_case(name), false)) } /// Leave Automatic on wgpu's normal request path; named choices may defer to it too. @@ -292,6 +297,71 @@ pub fn window_instance_flags(flags: eframe::wgpu::InstanceFlags, intel_mac: bool if intel_mac && env.map(str::trim).is_none_or(str::is_empty) { flags - eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL } else { flags } } +/// The environment variable that makes the macOS compatibility shim report an older OS +/// version to wgpu's Metal backend. On OCLP-patched machines the Metal compiler accepts +/// only up to the MSL standard of the original GPU, not the one the patched OS reports, +/// so wgpu picks a standard that the compiler refuses (`invalid value 'metal3.2'`). +/// Setting this variable before the process starts causes the OS to report the older +/// version and wgpu selects a supported MSL standard (#3080, #4605). +#[cfg(target_os = "macos")] +pub const SYSTEM_VERSION_COMPAT_ENV: &str = "SYSTEM_VERSION_COMPAT"; + +/// The NVRAM variable that OpenCore Legacy Patcher writes on every OCLP-booted system. +/// Its presence is the primary signal that `SYSTEM_VERSION_COMPAT=1` is needed. +#[cfg(target_os = "macos")] +pub const OCLP_NVRAM_KEY: &str = "4D1FDA02-38C7-4A6A-9CC6-4BCCA8B30102:OCLP-Version"; + +/// `true` if the OCLP NVRAM key is present on this system. +/// +/// Runs `nvram ` and treats exit 0 as present. Any error (missing binary, +/// permission denied, key absent) returns `false` — this is a best-effort probe. +#[cfg(target_os = "macos")] +pub fn oclp_nvram_present() -> bool { + std::process::Command::new("nvram").arg(OCLP_NVRAM_KEY).output().map(|o| o.status.success()).unwrap_or(false) +} + +/// Whether to re-launch with `SYSTEM_VERSION_COMPAT=1`: it is not set yet and OCLP shows through +/// the NVRAM key. The probe runs only when it is needed, so a re-launched process (variable +/// set) never starts `nvram`. +#[cfg(target_os = "macos")] +fn compat_wanted(compat_set: bool, nvram: impl FnOnce() -> bool) -> bool { + !compat_set && nvram() +} + +/// If this process is running under OCLP and `SYSTEM_VERSION_COMPAT` has not been set, +/// re-launch the current binary with `SYSTEM_VERSION_COMPAT=1` added to the environment, +/// then exit with the child's status code. +/// +/// `SYSTEM_VERSION_COMPAT=1` must be present **before** the process starts: setting it +/// with `std::env::set_var` inside `main` is too late because the macOS frameworks have +/// already queried the OS version by then. Re-launching is the only safe approach that +/// works without `unsafe` (a true `execve` replacement would require it). +/// +/// Returns `Ok(false)` immediately when: +/// - `SYSTEM_VERSION_COMPAT` is already set (re-launched process, no loop), or +/// - the OCLP NVRAM key is absent. +/// +/// Returns `Err` only when `std::env::current_exe()` fails or the child process cannot +/// be spawned; the caller should log the error and continue normally. +/// +/// Never returns `Ok(true)`: a successful re-launch exits the current process. +#[cfg(target_os = "macos")] +pub fn relaunch_with_version_compat() -> Result { + // A set variable means this is the re-launched process: no loop. + if !compat_wanted(std::env::var_os(SYSTEM_VERSION_COMPAT_ENV).is_some(), oclp_nvram_present) { + return Ok(false); + } + log::info!("startup: OCLP detected; re-launching with {}=1", SYSTEM_VERSION_COMPAT_ENV); + eprintln!("SolidCraft: OCLP detected; re-launching with {}=1", SYSTEM_VERSION_COMPAT_ENV); + let exe = std::env::current_exe().map_err(|e| format!("could not find own executable: {e}"))?; + let status = std::process::Command::new(&exe) + .args(std::env::args_os().skip(1)) + .env(SYSTEM_VERSION_COMPAT_ENV, "1") + .status() + .map_err(|e| format!("could not re-launch with {}: {e}", SYSTEM_VERSION_COMPAT_ENV))?; + std::process::exit(status.code().unwrap_or(1)); +} + /// Windows with OpenGL: the window keeps the system title bar (#2063). The window without OS /// decorations keeps its caption style while having no frame, and some OpenGL drivers (older /// Intel HD/UHD) then show the picture a caption's height lower than the window, so it no longer @@ -351,7 +421,8 @@ mod tests { assert_eq!(choose_adapter(&cards, None, Some("removed")), None); assert_eq!(choose_adapter(&cards, Some("missing"), Some("Discrete small")), Some(1)); assert_eq!(choose_adapter(&cards, Some(""), Some("Discrete small")), Some(1)); - assert_eq!(choose_adapter(&cards, None, Some("Discrete")), None, "saved names are exact"); + assert_eq!(choose_adapter(&cards, None, Some("discrete small")), Some(1), "preference matches without regard to case"); + assert_eq!(choose_adapter(&cards, None, Some("Discrete")), None, "a preference is the full name, not a substring"); } #[test] @@ -360,11 +431,20 @@ mod tests { assert_eq!(choose_adapter(&cards, None, None), None); assert_eq!(choose_adapter(&cards, Some(""), Some("")), None); cards[2].compatible = false; - assert_eq!(choose_adapter(&cards, Some("large"), Some("Discrete large")), None); + // Environment still needs a compatible adapter; a preference keeps the named card (#8341). + assert_eq!(choose_adapter(&cards, Some("large"), Some("Discrete large")), Some(2)); assert_eq!(choose_adapter(&cards, Some("small"), None), Some(1)); assert_eq!(choose_adapter(&[], None, None), None); } + #[test] + fn preference_keeps_a_named_card_even_when_surface_says_incompatible() { + let mut cards = cards(); + cards[1].compatible = false; + assert_eq!(choose_adapter(&cards, None, Some("Discrete small")), Some(1)); + assert_eq!(choose_adapter(&cards, None, Some("discrete SMALL")), Some(1)); + } + #[test] fn automatic_adapter_preserves_the_previous_request_configuration() { use eframe::egui_wgpu::WgpuSetupCreateNew; @@ -414,6 +494,27 @@ mod tests { assert_eq!(window_instance_flags(on, false, None), on); } + #[cfg(target_os = "macos")] + #[test] + fn oclp_relaunch_needs_the_signal_and_no_compat_variable() { + use super::compat_wanted; + let probed = std::cell::Cell::new(false); + let probe = |found: bool| { + let probed = &probed; + move || { + probed.set(true); + found + } + }; + // The re-launched process has the variable: no probe, no second re-launch. + assert!(!compat_wanted(true, probe(true))); + assert!(!probed.get()); + // The OCLP NVRAM key is the signal. + assert!(compat_wanted(false, probe(true))); + // No signal: an ordinary Mac starts as it is. + assert!(!compat_wanted(false, probe(false))); + } + #[test] fn switches_read_from_the_environment() { assert!(env_on(Some("1")) && env_on(Some("yes")) && !env_on(Some("0")) && !env_on(Some(" ")) && !env_on(None) && !env_on(Some("false"))); diff --git a/assets/fonts/craft-ui-sc/CraftUI-SC.otf b/assets/fonts/craft-ui-sc/CraftUI-SC.otf new file mode 100644 index 000000000..4763938af Binary files /dev/null and b/assets/fonts/craft-ui-sc/CraftUI-SC.otf differ diff --git a/assets/fonts/craft-ui-sc/OFL.txt b/assets/fonts/craft-ui-sc/OFL.txt new file mode 100644 index 000000000..d71df9fdc --- /dev/null +++ b/assets/fonts/craft-ui-sc/OFL.txt @@ -0,0 +1,96 @@ +Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. +Copyright 2014-2021 Google Inc. with Reserved Font Name 'Noto'. +Subset for SolidCraft web UI (glyphs used by the zh locale); renamed Craft UI SC (no Reserved Font Name). + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/craft-ui-tc/CraftUI-TC.otf b/assets/fonts/craft-ui-tc/CraftUI-TC.otf new file mode 100644 index 000000000..3dae5a020 Binary files /dev/null and b/assets/fonts/craft-ui-tc/CraftUI-TC.otf differ diff --git a/assets/fonts/craft-ui-tc/OFL.txt b/assets/fonts/craft-ui-tc/OFL.txt new file mode 100644 index 000000000..5041faaf5 --- /dev/null +++ b/assets/fonts/craft-ui-tc/OFL.txt @@ -0,0 +1,96 @@ +Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. +Copyright 2014-2021 Google Inc. with Reserved Font Name 'Noto'. +Subset for SolidCraft web UI (glyphs used by the zh-TW locale); renamed Craft UI TC (no Reserved Font Name). + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt index 6c907ab78..3a0b07c8d 100644 --- a/assets/icons/ui/design/requested_icons.txt +++ b/assets/icons/ui/design/requested_icons.txt @@ -182,6 +182,7 @@ placeholder true plane false plane_along_path false plane_angle false +plane_axis_point false plane_midplane false plane_perpendicular false plane_tangent false @@ -201,7 +202,20 @@ point_vertex false polygon false polygon_circumscribed false polygon_edge false +prefs_appearance false +prefs_assistant false +prefs_design false +prefs_general false +prefs_graphics false +prefs_layout false +prefs_mouse3d false +prefs_navigation false +prefs_plugins false +prefs_shortcuts false +prefs_sketch false +prefs_tools false presspull false +print_face false project false project_surface false rack_pinion false @@ -231,11 +245,7 @@ section false select false send false settings false -settings_keyboard false -settings_monitor false -settings_mouse false -settings_palette false -settings_plug false +settings_profile false sheet false sheet_rules false shell false diff --git a/assets/icons/ui/design/svg/flat/prefs_appearance.svg b/assets/icons/ui/design/svg/flat/prefs_appearance.svg new file mode 100644 index 000000000..7b2de0a20 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_appearance.svg @@ -0,0 +1,4 @@ + + Appearance + + diff --git a/assets/icons/ui/design/svg/flat/prefs_assistant.svg b/assets/icons/ui/design/svg/flat/prefs_assistant.svg new file mode 100644 index 000000000..e837db5f2 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_assistant.svg @@ -0,0 +1,4 @@ + + Assistant + + diff --git a/assets/icons/ui/design/svg/flat/prefs_design.svg b/assets/icons/ui/design/svg/flat/prefs_design.svg new file mode 100644 index 000000000..d7779761b --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_design.svg @@ -0,0 +1,4 @@ + + Design + + diff --git a/assets/icons/ui/design/svg/flat/prefs_general.svg b/assets/icons/ui/design/svg/flat/prefs_general.svg new file mode 100644 index 000000000..2af3b2387 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_general.svg @@ -0,0 +1,4 @@ + + General + + diff --git a/assets/icons/ui/design/svg/flat/prefs_graphics.svg b/assets/icons/ui/design/svg/flat/prefs_graphics.svg new file mode 100644 index 000000000..6cebe6617 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_graphics.svg @@ -0,0 +1,4 @@ + + Graphics + + diff --git a/assets/icons/ui/design/svg/flat/prefs_layout.svg b/assets/icons/ui/design/svg/flat/prefs_layout.svg new file mode 100644 index 000000000..33e4fa587 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_layout.svg @@ -0,0 +1,4 @@ + + Layout + + diff --git a/assets/icons/ui/design/svg/flat/prefs_mouse3d.svg b/assets/icons/ui/design/svg/flat/prefs_mouse3d.svg new file mode 100644 index 000000000..718f48a1d --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_mouse3d.svg @@ -0,0 +1,4 @@ + + 3D mouse + + diff --git a/assets/icons/ui/design/svg/flat/prefs_navigation.svg b/assets/icons/ui/design/svg/flat/prefs_navigation.svg new file mode 100644 index 000000000..197108965 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_navigation.svg @@ -0,0 +1,4 @@ + + Navigation + + diff --git a/assets/icons/ui/design/svg/flat/prefs_plugins.svg b/assets/icons/ui/design/svg/flat/prefs_plugins.svg new file mode 100644 index 000000000..9de1501d9 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_plugins.svg @@ -0,0 +1,4 @@ + + Plugins + + diff --git a/assets/icons/ui/design/svg/flat/prefs_shortcuts.svg b/assets/icons/ui/design/svg/flat/prefs_shortcuts.svg new file mode 100644 index 000000000..063bc7585 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_shortcuts.svg @@ -0,0 +1,4 @@ + + Shortcuts + + diff --git a/assets/icons/ui/design/svg/flat/prefs_sketch.svg b/assets/icons/ui/design/svg/flat/prefs_sketch.svg new file mode 100644 index 000000000..3a3dc7a87 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_sketch.svg @@ -0,0 +1,4 @@ + + Sketch + + diff --git a/assets/icons/ui/design/svg/flat/prefs_tools.svg b/assets/icons/ui/design/svg/flat/prefs_tools.svg new file mode 100644 index 000000000..41b8612a7 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/prefs_tools.svg @@ -0,0 +1,4 @@ + + Tools + + diff --git a/assets/icons/ui/design/svg/flat/settings_profile.svg b/assets/icons/ui/design/svg/flat/settings_profile.svg new file mode 100644 index 000000000..0546b069e --- /dev/null +++ b/assets/icons/ui/design/svg/flat/settings_profile.svg @@ -0,0 +1,5 @@ + + Settings profile + + + diff --git a/assets/icons/ui/design/svg/model/plane_axis_point.svg b/assets/icons/ui/design/svg/model/plane_axis_point.svg new file mode 100644 index 000000000..e9be1ff50 --- /dev/null +++ b/assets/icons/ui/design/svg/model/plane_axis_point.svg @@ -0,0 +1,6 @@ + + Plane through axis and point + + + + diff --git a/assets/icons/ui/design/svg/model/print_face.svg b/assets/icons/ui/design/svg/model/print_face.svg new file mode 100644 index 000000000..107dc1256 --- /dev/null +++ b/assets/icons/ui/design/svg/model/print_face.svg @@ -0,0 +1,19 @@ + + Print Face + + + + + + + + + + + + + + + + + diff --git a/assets/icons/ui/source/navigation.rs b/assets/icons/ui/source/navigation.rs index 2a4ac4c00..82ef37ece 100644 --- a/assets/icons/ui/source/navigation.rs +++ b/assets/icons/ui/source/navigation.rs @@ -1,7 +1,8 @@ //! Navigation drawing definitions. Camera projection and picking remain in the UI widgets. use crate::theme::Tokens; use egui::{Color32, FontId, Pos2, Rect, Shape, Stroke, pos2, vec2}; -use solidcraft_engine::geom::{Ring, Vec3}; +use solidcore_record::Vec3; +use solidcraft_engine::geom::Ring; pub(crate) struct Facet { pub(crate) direction: Vec3, pub(crate) points: Ring, @@ -151,6 +152,12 @@ pub(crate) fn curved_arrow(painter: &egui::Painter, at: Pos2, clockwise: bool, h /// The pointer target around a compass end: larger than the drawn disc, so it is easy to hit. pub(crate) const AXIS_RADIUS: f32 = 15.0; pub(crate) fn axis_tip(painter: &egui::Painter, c: Pos2, name: &str, d: &Vec3, at: Pos2, depth: f64, hovered: bool, t: Tokens) { + axis_tip_scaled(painter, c, name, d, at, depth, hovered, t, 1.0); +} + +/// The same compass artwork at a uniform scale, including its lettering and strokes. +#[allow(clippy::too_many_arguments)] +pub(crate) fn axis_tip_scaled(painter: &egui::Painter, c: Pos2, name: &str, d: &Vec3, at: Pos2, depth: f64, hovered: bool, t: Tokens, scale: f32) { let col = if d.x != 0.0 { t.axis_x } else if d.y != 0.0 { @@ -163,11 +170,11 @@ pub(crate) fn axis_tip(painter: &egui::Painter, c: Pos2, name: &str, d: &Vec3, a // Positive shafts are the full axis colour; negative ones are a dimmed tint (and any end // pointing away from the viewer dims further). let ink = if !positive || depth < -0.01 { col.gamma_multiply(0.55) } else { col }; - let radius = if positive { 11.0 } else { 4.8 }; + let radius = if positive { 11.0 } else { 4.8 } * scale; let direction = (at - c).normalized(); - let width = 3.6; + let width = 3.6 * scale; // A negative shaft stops at the outer edge of its ring; a positive one runs under its disc. - let end = if positive { at - direction * radius } else { at - direction * (radius + 1.2) }; + let end = if positive { at - direction * radius } else { at - direction * (radius + 1.2 * scale) }; painter.line_segment([c, end], Stroke::new(width, ink)); // The round cap sits at the origin; the other end is covered by the disc or ring. painter.circle_filled(c, width / 2.0, ink); @@ -179,18 +186,18 @@ pub(crate) fn axis_tip(painter: &egui::Painter, c: Pos2, name: &str, d: &Vec3, a // kind turns fully white. if hovered { // Same outer size as the resting tip: a ring's outline is half its stroke outside. - painter.circle_filled(at, if positive { radius } else { radius + 1.2 }, t.on_accent); + painter.circle_filled(at, if positive { radius } else { radius + 1.2 * scale }, t.on_accent); // On the light theme a white disc vanishes into the compass, so it carries an outline in // the axis colour, drawn inside the disc so it does not grow. if light && positive { - painter.circle_stroke(at, radius - 1.0, Stroke::new(2.0, col)); + painter.circle_stroke(at, radius - scale, Stroke::new(2.0 * scale, col)); } } if positive { // On a hovered (white) disc the letter takes the axis colour. let letter = if hovered { col } else { t.on_accent }; let label = name.to_uppercase(); - let galley = painter.layout_no_wrap(label, crate::fonts::bold(crate::theme::Tokens::get().font_compass), letter); + let galley = painter.layout_no_wrap(label, crate::fonts::bold(crate::theme::Tokens::get().font_compass * scale), letter); let origin = at - galley.size() / 2.0; let ppp = painter.ctx().pixels_per_point().max(0.5); let origin = pos2((origin.x * ppp).round() / ppp, (origin.y * ppp).round() / ppp); @@ -201,7 +208,7 @@ pub(crate) fn axis_tip(painter: &egui::Painter, c: Pos2, name: &str, d: &Vec3, a at, radius, Stroke::new( - 2.4, + 2.4 * scale, if !hovered { ink } else if light { diff --git a/assets/locales/ar.json b/assets/locales/ar.json index e1a8406b9..9484fb062 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "سطح مزج", "BOUNDARY SURFACE": "سطح حدودي", "BROWSER": "المستعرض", + "Back to the original order": "العودة إلى الترتيب الأصلي", "Ball": "كروي", "Bar": "قضيب", "Base Center": "مركز القاعدة", @@ -378,7 +379,7 @@ "Move Type": "نوع التحريك", "Move down": "نقل للأسفل", "Move earlier": "نقل إلى الأقدم", - "Move holes by clicking or dragging": "تحريك الثقوب بالنقر أو السحب", + "Move holes by clicking or dragging": "التحريك بالنقر أو السحب", "Move later": "نقل إلى الأحدث", "Move up": "نقل للأعلى", "Name": "الاسم", @@ -476,6 +477,7 @@ "Rectangular": "مستطيلي", "Rectangular Tube": "أنبوب مستطيل", "Reference face": "الوجه المرجعي", + "Reference plane": "المستوى المرجعي", "Relief Depth": "عمق التفريغ", "Relief Width": "عرض التفريغ", "Remove Tools": "إزالة الأدوات", @@ -493,7 +495,8 @@ "Rename Folder": "إعادة تسمية المجلد", "Render Stage": "مرحلة التصيير", "Reopen designs": "إعادة فتح التصاميم", - "Reopen the designs that were open when SolidCraft was last closed": "إعادة فتح التصاميم التي كانت مفتوحة عند آخر إغلاق لـ SolidCraft", + "Reopen the designs that were open when SolidCraft was last closed": "إعادة فتح التصاميم التي كانت مفتوحة آخر مرة", + "Repair Part": "إصلاح الجزء", "Replace existing library file": "استبدال ملف المكتبة الموجود", "Report a bug — review a screenshot and open a GitHub draft": "الإبلاغ عن خطأ — راجع لقطة الشاشة وافتح مسودة GitHub", "Report copied. Keep this text to submit on GitHub when you are online.": "تم نسخ التقرير. احتفظ بهذا النص لإرساله على GitHub عند الاتصال بالإنترنت.", @@ -555,6 +558,7 @@ "Section": "مقطع", "Section (optional)": "المقطع (اختياري)", "Section position": "موضع المقطع", + "Sections": "المقاطع", "Sections (one sketch each)": "المقاطع (رسم واحد لكل منها)", "Select Other": "تحديد آخر", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "تحديد آخر: أبقِ الزر الأيسر ثابتًا على النموذج (أو انقر بالزر الأيمن › تحديد آخر…) لعرض كل ما تحت المؤشر؛ وانقر مرة أخرى في الموضع نفسه لتحديد العنصر التالي هناك. انقر نقرًا مزدوجًا بالزر الأوسط للانتقال إلى العرض الرئيسي (التفضيلات › التنقل).", @@ -581,7 +585,7 @@ "Show ghost": "إظهار الطيف", "Show in folder": "إظهار في المجلد", "Show the pointer an AI agent moves (#35)": "إظهار المؤشر الذي يحرّكه وكيل الذكاء الاصطناعي (#35)", - "Show tool at cursor": "إظهار الأداة عند المؤشر", + "Show tool at cursor": "الأداة عند المؤشر", "Signed axes": "محاور بإشارة", "Size": "الحجم", "Sketch constraints": "قيود الرسم", @@ -592,9 +596,11 @@ "Sketch points": "نقاط الرسم", "Slider": "منزلق", "Slot width": "عرض الشق", - "Snap to face and edge centres": "الالتقاط إلى مراكز الأوجه والحواف", + "Snap to face and edge centres": "الالتقاط إلى المراكز", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "لا يستطيع SolidCraft إرسال التقارير مباشرةً. أرسلها على GitHub؛ لا حاجة إلى رمز وصول في التطبيق.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "أُغلق SolidCraft قبل حفظ هذه التصاميم. يمكن فتح آخر حفظ تلقائي لها.", + "Sort A to Z": "فرز تصاعدي", + "Sort Z to A": "فرز تنازلي", "Spacing 2 must be a non-zero number": "يجب أن يكون التباعد 2 عددًا غير صفري", "Spacing must be a non-zero number": "يجب أن يكون التباعد عددًا غير صفري", "Specialise": "تخصيص", @@ -733,34 +739,34 @@ "a picked edge's body is gone": "جسم الحافة المحددة لم يعد موجودًا", "add a key for a joint first": "أضف أولًا مفتاحًا لمفصل", "ai.connected_toast": "أصبح SolidCraft متاحًا في {clients}. أعد تشغيلها لاستخدامه (التفضيلات > المساعد).", - "ai.prefs.allow_control": "السماح لوكلاء الذكاء الاصطناعي بالاتصال (قناة التحكم / MCP)", - "ai.prefs.allow_control_note": "يفتح قناة تحكم على هذا الحاسوب فقط (127.0.0.1، المنفذ 27878 أو أول منفذ متاح بعده). على البرنامج الذي يتصل أن يقدّم أيضًا رمزًا سريًا لا يقرؤه إلا حساب المستخدم الخاص بك، ويُنشأ من جديد عند كل تشغيل. يُطبّق في المرة القادمة التي يبدأ فيها SolidCraft. عند الإيقاف: لا شيء يستمع ما لم تشغّل SolidCraft مع --control.", - "ai.prefs.availability": "عناصر تحكم المساعد", - "ai.prefs.background_commands": "تشغيل أوامر الوكيل في الخلفية", - "ai.prefs.connect_apps": "إتاحة SolidCraft لتطبيقات الذكاء الاصطناعي على هذا الحاسوب", - "ai.prefs.connect_apps_note": "عند بدء تشغيل SolidCraft، يُضاف كخادم MCP إلى تطبيقات الذكاء الاصطناعي الموجودة على هذا الحاسوب (OpenCode وClaude Desktop وClaude Code وCursor وCodex وGemini CLI وCopilot CLI وWindsurf وZed وVS Code)، ليتمكن الوكيل من استخدامه دون أي إعداد. لا يُضاف إلا مُدخل solidcraft أو يُحدَّث مساره؛ ويُترك المُدخل الذي غيّرته كما هو، ويُنسخ الملف احتياطيًا أولًا. عند الإيقاف تُزال المُدخلات التي أضافها. الأمر «المساعدة > ربط مساعدي الذكاء الاصطناعي…» يفعل ذلك يدويًا.", - "ai.prefs.connect_at_start": "الاتصال بآخر وكيل مستخدم عند بدء SolidCraft", + "ai.prefs.allow_control": "السماح لوكلاء الذكاء الاصطناعي بالاتصال", + "ai.prefs.allow_control_note": "قناة محلية (MCP). لا شيء يغادر هذا الحاسوب.\n\nيفتح قناة تحكم على هذا الحاسوب فقط (127.0.0.1، المنفذ 27878 أو أول منفذ متاح بعده). على البرنامج الذي يتصل أن يقدّم أيضًا رمزًا سريًا لا يقرؤه إلا حساب المستخدم الخاص بك، ويُنشأ من جديد عند كل تشغيل. يُطبّق في المرة القادمة التي يبدأ فيها SolidCraft. عند الإيقاف: لا شيء يستمع ما لم تشغّل SolidCraft مع --control.", + "ai.prefs.availability": "التوفر", + "ai.prefs.background_commands": "تشغيل الأوامر البطيئة في الخلفية", + "ai.prefs.connect_apps": "إضافة SolidCraft إلى تطبيقات الذكاء الاصطناعي", + "ai.prefs.connect_apps_note": "إيقافه يزيل الإدخالات مجددًا.\n\nعند بدء تشغيل SolidCraft، يُضاف كخادم MCP إلى تطبيقات الذكاء الاصطناعي الموجودة على هذا الحاسوب (OpenCode وClaude Desktop وClaude Code وCursor وCodex وGemini CLI وCopilot CLI وWindsurf وZed وVS Code)، ليتمكن الوكيل من استخدامه دون أي إعداد. لا يُضاف إلا مُدخل solidcraft أو يُحدَّث مساره؛ ويُترك المُدخل الذي غيّرته كما هو، ويُنسخ الملف احتياطيًا أولًا. عند الإيقاف تُزال المُدخلات التي أضافها. الأمر «المساعدة > ربط مساعدي الذكاء الاصطناعي…» يفعل ذلك يدويًا.", + "ai.prefs.connect_at_start": "توصيل آخر وكيل عند البدء", "ai.prefs.connect_at_start_note": "يبدأ في الخلفية الوكيل الذي اتصلت به آخر مرة (أو الوكيل الافتراضي) في كل مرة يبدأ فيها SolidCraft، ليكون جاهزًا للمحادثة. لا يحدث ذلك عند بدء SolidCraft مع --control. إذا تعذّر الاتصال، يعرض المساعد «فشل الاتصال» وزر «إعادة المحاولة».", - "ai.prefs.follow_camera": "توجيه الكاميرا نحو الرسومات", + "ai.prefs.follow_camera": "تتبّع الكاميرا", "ai.prefs.follow_camera_off": "تتبّع الكاميرا التلقائي متوقف.", "ai.prefs.follow_camera_on": "تتجه الكاميرا نحو الرسومات التي ينشئها الوكيل.", - "ai.prefs.intro": "الوكلاء والأذونات وطريقة ظهور عملهم.", - "ai.prefs.make_default": "الاستخدام افتراضيًا", + "ai.prefs.intro": "وكلاء الذكاء الاصطناعي في SolidCraft.", + "ai.prefs.make_default": "تعيين افتراضيًا", "ai.prefs.no_agents": "لا يوجد وكلاء بعد. أضف وكيلًا أو حدّث القائمة للعثور على الوكلاء المثبّتين.", "ai.prefs.no_saved_approvals": "لا توجد موافقات محفوظة.", - "ai.prefs.open_at_start": "فتح لوحة المساعد عند بدء SolidCraft", + "ai.prefs.open_at_start": "فتح المحادثة عند البدء", "ai.prefs.open_at_start_note": "يعرض لوحة المساعد (أو نافذتها المستقلة) في كل مرة يبدأ فيها SolidCraft. لا يحدث ذلك عند بدء SolidCraft مع --control.", "ai.prefs.override_all_warning": "قد يحفظ هذا الوكيل التصميم أو يكتب فوقه أو يصدّره أو يستبدله دون أن يسأل.", - "ai.prefs.permission_all": "السماح بكل شيء", - "ai.prefs.permission_all_summary": "تعمل أدوات SolidCraft المتاحة دون سؤال.", - "ai.prefs.permission_ask": "السؤال قبل التغييرات", - "ai.prefs.permission_ask_summary": "الموافقة على كل تغيير في التصميم وكل إجراء على الملفات.", - "ai.prefs.permission_edits": "السماح بتعديلات النموذج", - "ai.prefs.permission_edits_summary": "تُنفَّذ تعديلات النموذج، وتبقى إجراءات الملفات والإجراءات المدمّرة تتطلب السؤال.", + "ai.prefs.permission_all": "تنفيذ كل شيء", + "ai.prefs.permission_all_summary": "لا يسأل أبدًا", + "ai.prefs.permission_ask": "السؤال أولًا", + "ai.prefs.permission_ask_summary": "يسأل عن كل تغيير", + "ai.prefs.permission_edits": "إجراء تعديلات", + "ai.prefs.permission_edits_summary": "يعدّل بحرية ويسأل عن الباقي", "ai.prefs.permission_scope": "لأدوات SolidCraft فقط. أوامر الطرفية وتعديلات الملفات لدى الوكيل تتبع أذوناته الخاصة.", "ai.prefs.pointer_preview_hidden": "المؤشر مخفي", "ai.prefs.pointer_preview_speed": "مؤشر الوكيل · {speed}", - "ai.prefs.pointer_speed": "سرعة الحركة", + "ai.prefs.pointer_speed": "السرعة", "ai.prefs.privacy_note": "لا يستلم المحادثة إلا الوكيل أو نقطة الاتصال التي تختارها. تُخزَّن مفاتيح نقاط الاتصال في سلسلة مفاتيح النظام.", "ai.prefs.show_pointer": "إظهار مؤشر الوكيل", "ai.prefs.turn_limit_hint": "الحد الأقصى لاستدعاءات الأدوات التي تغيّر التصميم في الرسالة الواحدة.", @@ -785,11 +791,19 @@ "browser.edit_canvas_title": "تعديل اللوحة: {name}", "browser.edit_point_cloud_title": "تحرير سحابة النقاط: {name}", "browser.move_title": "تحريك: {name}", + "browser.needs_repair": "{name}: يحتاج إلى إصلاح", "browser.parameters": "المعاملات ({count})", "browser.precision": "الدقة: {precision}", "browser.sketch_attachment_lost": "{name} (فُقد الارتباط)", "browser.sketch_editing": "{name} (قيد التحرير)", "browser.sketch_name": "رسم {number}", + "browser.sketches_to_parts_already_in_part": "موجودة بالفعل في جزئها", + "browser.sketches_to_parts_design_body": "على جسم من التصميم نفسه", + "browser.sketches_to_parts_moved": "نُقلت {moved} رسومات إلى الجزء الذي رُسمت عليه", + "browser.sketches_to_parts_no_exact_attachment": "على وجه بلا ارتباط دقيق", + "browser.sketches_to_parts_not_on_face": "ليست على وجه جزء", + "browser.sketches_to_parts_part_missing": "جزؤها لم يعد موجودًا", + "browser.sketches_to_parts_result": "نُقلت {moved} رسومات إلى الجزء الذي رُسمت عليه؛ وبقيت {stayed}: {why}", "browser.units": "الوحدات: {units}", "cam.flat": "وجه مسطح", "cam.follower": "التابع", @@ -819,7 +833,10 @@ "cmd.appearance_pick_up": "التقاط المظهر", "cmd.appearance_replace": "استبدال المظهر", "cmd.assembly_bom": "قائمة المواد", + "cmd.assembly_mass_properties": "خصائص الكتلة", + "cmd.body.print_face": "وجه الطباعة", "cmd.body_rename": "إعادة تسمية الجسم", + "cmd.body_repair": "إصلاح الجزء", "cmd.browser_collapse_all": "طي الكل", "cmd.browser_expand_all": "توسيع الكل", "cmd.browser_group": "مجموعة جديدة", @@ -847,6 +864,7 @@ "cmd.component_extract": "استخراج إلى ملف", "cmd.component_finish_edit": "إنهاء التحرير", "cmd.component_from_bodies": "إنشاء مكوّنات من الأجسام", + "cmd.component_hide_history": "إخفاء سجل المكوّن", "cmd.component_insert_design": "إدراج تصميم", "cmd.component_links": "قائمة الروابط", "cmd.component_list": "قائمة المكوّنات", @@ -855,6 +873,7 @@ "cmd.component_move_bodies": "نقل الأجسام إلى مكوّن", "cmd.component_move_features": "نقل الميزات إلى مكوّن", "cmd.component_move_sketches": "نقل الرسومات إلى مكوّن", + "cmd.component_move_sketches_to_parts": "نقل الرسومات إلى أجزائها", "cmd.component_paste_from_design": "لصق من تصميم آخر", "cmd.component_paste_new": "لصق كجديد", "cmd.component_properties": "الخصائص الفيزيائية للمكوّن", @@ -862,6 +881,7 @@ "cmd.component_rename": "إعادة تسمية المكوّن", "cmd.component_replace_with_link": "استبدال برابط", "cmd.component_revert_position": "إرجاع الموضع", + "cmd.component_show_history": "إظهار سجل المكوّن", "cmd.component_unlock": "فتح قفل المحتويات", "cmd.component_update_links": "تحديث الروابط", "cmd.config_activate": "تنشيط التكوين", @@ -872,6 +892,7 @@ "cmd.config_rule": "قاعدة التكوين", "cmd.config_rules": "قواعد التكوين", "cmd.config_table": "عرض جدول التكوينات", + "cmd.construct.plane.axis_point": "مستوى عبر محور ونقطة", "cmd.construct_axis_edge": "محور عبر حافة", "cmd.construct_axis_normal_to_face": "محور عمودي على وجه", "cmd.construct_axis_through_cylinder": "محور عبر أسطوانة/مخروط/طارة", @@ -900,6 +921,8 @@ "cmd.diagnostics_crash_reports": "تقارير الأعطال", "cmd.diagnostics_crash_reports_clear": "حذف تقارير الأعطال", "cmd.diagnostics_crash_test": "اختبار العطل", + "cmd.diagnostics_profile": "التحليل الزمني", + "cmd.diagnostics_validation": "التحقق", "cmd.doc_recover": "استعادة التصميم", "cmd.doc_recovery_discard": "تجاهل التصميم المستعاد", "cmd.doc_recovery_list": "التصاميم القابلة للاستعادة", @@ -920,6 +943,11 @@ "cmd.explode_show": "إظهار العرض المفكك", "cmd.expr_evaluate": "تقييم تعبير", "cmd.face_delete": "حذف وجه", + "cmd.file.export_3mf": "تصدير 3MF", + "cmd.file.export_obj": "تصدير OBJ", + "cmd.file.export_step": "تصدير STEP", + "cmd.file.export_stl": "تصدير STL", + "cmd.file.export_urdf": "تصدير URDF", "cmd.file_export": "تصدير", "cmd.file_insert_mesh": "إدراج شبكة", "cmd.file_insert_step": "إدراج STEP", @@ -932,11 +960,13 @@ "cmd.frame_profile_list": "مكتبة المقاطع", "cmd.frame_profile_properties": "خصائص المقطع", "cmd.inspect_accessibility": "تحليل إمكانية الوصول", + "cmd.inspect_analysis": "تحليل العرض", "cmd.inspect_center_of_mass": "مركز الكتلة", "cmd.inspect_clearance": "الخلوص", "cmd.inspect_colored_components": "تفعيل ألوان المكوّنات", "cmd.inspect_colored_components_disable": "تعطيل ألوان المكوّنات", "cmd.inspect_compare": "مقارنة الأجسام", + "cmd.inspect_compare_picture": "مقارنة بصورة مرجعية", "cmd.inspect_continuity": "تحليل الاستمرارية", "cmd.inspect_curvature_comb": "تحليل مشط الانحناء", "cmd.inspect_curvature_map": "تحليل خريطة الانحناء", @@ -954,6 +984,7 @@ "cmd.joint_delete": "حذف المفصل", "cmd.joint_drive": "تحريك المفاصل", "cmd.joint_edit": "تعديل المفصل", + "cmd.joint_find_limits": "إيجاد حدود المفصل", "cmd.joint_gear": "ترس", "cmd.joint_inspect": "فحص المفصل", "cmd.joint_limits": "حدود المفصل", @@ -966,6 +997,11 @@ "cmd.joint_screw": "لولب", "cmd.joint_solve": "حل المفاصل", "cmd.joint_sweep": "مفصل كنس", + "cmd.layout.apply": "تطبيق التخطيط", + "cmd.layout.get": "فحص التخطيط", + "cmd.layout.reset": "إعادة ضبط التخطيط", + "cmd.layout.save": "حفظ التخطيط", + "cmd.layout.workspace.select": "اختيار مساحة عمل التخطيط", "cmd.library_apply": "تطبيق عنصر من المكتبة المحلية", "cmd.library_export": "تصدير مكتبة التصميم", "cmd.library_inspect": "فحص المكتبة المحلية", @@ -999,6 +1035,21 @@ "cmd.occurrence_move": "تحريك النسخة", "cmd.occurrence_properties": "الخصائص الفيزيائية للنسخة", "cmd.occurrence_reparent": "نقل إلى مكوّن", + "cmd.panel.activate": "تنشيط علامة تبويب اللوحة", + "cmd.panel.close": "إغلاق اللوحة", + "cmd.panel.collapse": "طي قسم اللوحة", + "cmd.panel.dismiss": "إغلاق العرض المؤقت للوحة", + "cmd.panel.float": "تعويم اللوحة", + "cmd.panel.focus": "تركيز اللوحة", + "cmd.panel.list": "سرد اللوحات", + "cmd.panel.move": "نقل اللوحة", + "cmd.panel.native_close": "إعادة إرساء قسم اللوحة من نافذته المستقلة", + "cmd.panel.open": "فتح اللوحة", + "cmd.panel.peek": "عرض اللوحة المطوية مؤقتًا", + "cmd.panel.popout": "نقل اللوحة إلى نافذة مستقلة", + "cmd.panel.reset_pair": "إعادة ضبط فاصل اللوحة", + "cmd.panel.resize": "تغيير حجم قسم اللوحة", + "cmd.panel.resize_pair": "تحريك فاصل اللوحة", "cmd.parameters_add": "إضافة معامل مستخدم", "cmd.parameters_change": "تغيير المعاملات", "cmd.parameters_comment": "التعليق على المعامل", @@ -1027,6 +1078,9 @@ "cmd.pointcloud_edit": "تحرير سحابة النقاط", "cmd.pointcloud_insert": "إدراج سحابة نقاط", "cmd.pointcloud_list": "سحب النقاط", + "cmd.render.compare.divider": "تحريك فاصل مقارنة التصيير", + "cmd.render.result.discard": "تجاهل نتيجة التصيير", + "cmd.render.result.select": "تحديد نتيجة التصيير", "cmd.render_aging_describe": "تقادم السطح بالطبقات", "cmd.render_backends": "محركات التصيير", "cmd.render_batch": "تصيير كل اللقطات", @@ -1190,6 +1244,7 @@ "cmd.sketch_spline_control_point_5": "منحنى شريحي بنقاط تحكم (الدرجة 5)", "cmd.sketch_spline_fit_point": "منحنى شريحي بنقاط ملاءمة", "cmd.sketch_spline_insert_point": "إضافة نقطة إلى المنحنى الشريحي", + "cmd.sketch_spline_remove_point": "إزالة نقطة من المنحنى الشريحي", "cmd.sketch_spline_reverse": "عكس اتجاه المنحنى الشريحي", "cmd.sketch_spun_profile": "مقطع دوراني", "cmd.sketch_toggle_diameter": "تبديل نصف القطر / القطر", @@ -1240,9 +1295,11 @@ "cmd.timeline_rollback": "نقل مؤشر الخط الزمني", "cmd.timeline_stop": "إيقاف السجل", "cmd.timeline_suppress": "تعطيل الميزة", + "cmd.ui.assistant": "إظهار المساعد أو إخفاؤه", "cmd.view.render_browser": "متصفح التصيير", "cmd.view.render_dock": "نقل لوحة التصيير", "cmd.view.render_focus": "عرض تركيز التصيير", + "cmd.view.status_details": "تفاصيل حالة منطقة العرض", "cmd.view.status_items": "عناصر حالة منطقة العرض", "cmd.view_ambient_occlusion": "الإظلال المحيطي", "cmd.view_angle_readout": "زوايا العرض", @@ -1273,17 +1330,28 @@ "cmd.view_tool": "أداة التنقل", "cmd.view_top": "العرض العلوي", "cmd.view_visual_style": "نمط العرض", + "color.blue": "أزرق", "color.copy": "انقر لنسخ قيم اللون", "color.edit": "انقر لتعديل اللون", "color.gamma": "عرض قيم اللون في نطاق جاما 0-255", + "color.green": "أخضر", "color.hex": "Hex", "color.hex_help": "أدخل #rrggbb أو #rrggbbaa؛ مع الخانات الست تبقى العتامة كما هي", "color.hex_hint": "#rrggbb", "color.hue": "درجة اللون", "color.linear": "عرض قيم اللون في النطاق الخطي 0-1", + "color.recent": "الألوان الأخيرة", + "color.recent_help": "تظهر هنا الألوان التي تختارها في أي حقل لون", + "color.red": "أحمر", + "color.saturation": "التشبع (بالمئة)", "color.saturation_value": "التشبع والقيمة", "color.selected": "اللون المحدد", + "color.step_down": "إنقاص خطوة", + "color.step_up": "زيادة خطوة", + "color.value": "القيمة، أي السطوع (بالمئة)", "config.column_filter_empty": "لا توجد أعمدة مطابقة", + "config.rule_parameter_columns": "لا تظهر هنا إلا المعاملات التي لها عمود في الجدول. أضف عمودًا عبر «إضافة عمود» (+) لاستخدام المعامل هنا.", + "config.rule_suppression_columns": "لا تظهر هنا إلا الميزات التي لها عمود «تعطيل» في الجدول. أضف عمودًا عبر «إضافة عمود» (+) للتحكم بالميزة هنا.", "contact.components_count": "{count} مكوّنات", "contact.enabled_label": "مفعّل", "coupling.gear_1": "الترس 1", @@ -1318,6 +1386,7 @@ "crash.unclean_explanation": "اكتُشف عند تشغيل لاحق، ولم يُسجَّل وقت الخروج بدقة. قد يسبب إيقاف تشغيل النظام أو الإيقاف القسري خروجًا غير سليم أيضًا.", "delete.and_more": "… و{count} غيرها", "diagnostic.empty_boolean_component": "لا يوجد جسم للقص أو التقاطع في المكوّن '{component}'؛ قد تتداخل الأداة مع '{body}' في المكوّن '{other}' — نشّط ذلك المكوّن أو اختر الجسم هدفًا", + "diagnostic.reselect_reference": "{feature}: المرجع `{reference}` لم يعد موجودًا كما اختير؛ أعد اختياره", "dialog.bodies_count": "{count} أجسام", "dialog.clearance_invalid": "يجب أن يكون الخلوص طولًا قيمته 0 أو أكثر", "dialog.compute": "احسب", @@ -1327,11 +1396,20 @@ "dialog.custom_axis": "↖ محور مخصص", "dialog.dimension_insert_hint": "انقر على بُعد قائد آخر لإدراج اسمه", "dialog.dimension_name": "البُعد: {name}", + "dialog.dimension_step_down": "إنقاص بمقدار {step}", + "dialog.dimension_step_expression": "يتغير الرقم فقط بالخطوات؛ يبقى التعبير كما كُتب", + "dialog.dimension_step_up": "زيادة بمقدار {step}", "dialog.edit_title": "تعديل {title}", "dialog.no_shown_body": "لا يوجد جسم ظاهر لتغييره: أظهر جسمًا، أو اختر «جسم جديد»", + "dialog.pattern_sketch_not_object": "اختر أجسامًا أو ميزات: الرسم ليس أيًّا منهما. كرّر منحنياته بأداة النمط أو المرآة داخل الرسم، أو ابثقه أولًا.", "dialog.select": "↖ تحديد", "dialog.selected_count": "↖ {count} محدد", + "dialog.selection_constraint": "قيد {id}", + "dialog.selection_external_curve": "{sketch} · منحنى {id}", + "dialog.selection_external_point": "{point} · {sketch}", "dialog.selection_guidance": "حدد مُدخلًا لتغييره. انقر على العناصر المحددة لإزالتها؛ Ctrl/Cmd مع النقر يبدّل تحديدها أيضًا. راجع المعاينة ثم اضغط موافق.", + "dialog.selection_midpoint": "نقطة المنتصف · {id}", + "dialog.selection_profile": "{sketch} · مقطع {number}", "dialog.selection_step": "{step} من {total}: حدد {input}", "dialog.step": "الخطوة", "document.changed_on_disk": "تغيّر {name} على القرص", @@ -1346,6 +1424,7 @@ "document.read_only_save": "فُتح هذا التصميم للقراءة فقط: احفظه كملف جديد", "document.save_changes": "حفظ التغييرات على {name}؟", "document.save_copy": "حفظ نسخة…", + "document.tab_unsaved_changes": "تغييرات غير محفوظة", "document.unsaved_changes": "في {name} تغييرات غير محفوظة. إن لم تحفظها فستضيع.", "drive.rigid": "{joint} مفصل صلب: يثبّت أجزاءه في مكانها، لذا لا يوجد ما يمكن تحريكه. لتتحرك الأجزاء، غيّر نوعه في «تعديل المفصل»: «دوراني» للدوران، «منزلق» للانزلاق، «أسطواني» لكليهما.", "drive.stopped_by_contact": "توقف عند {value}: سيخترق {a} الجسم {b}", @@ -1378,6 +1457,14 @@ "file_load.reading_percent": "قراءة الملف... {percent}%", "file_load.rebuilding": "إعادة بناء الميزة {done} من {total}", "file_load.recovering": "استعادة التصميم", + "file_load.step_build": "جارٍ بناء النموذج", + "file_load.step_feature": "الميزة {done} من {total}", + "file_load.step_part": "الجزء {done} من {total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "جارٍ قراءة الملف", + "file_load.step_rebuild": "جارٍ إعادة بناء الميزات", + "file_load.step_repair": "جارٍ فحص الأجزاء وإصلاحها", + "file_load.step_show": "جارٍ تجهيز العرض", "file_load.stopping": "انتظار توقف العملية السابقة...", "file_load.updating_links": "تحديث الروابط", "file_load.waiting": "انتظار عملية الملف", @@ -1385,22 +1472,190 @@ "from the profile": "من المقطع", "from the rule": "من القاعدة", "help.apache": "رخصة Apache 2.0", - "help.appearance.assign": "يمنح الأجسام أو الأوجه أو المكونات المحددة لونًا أو مظهر مادة، من دون تغيير وزنها. استخدمه للتمييز بين القطع أو لمعاينة التشطيب.", + "help.appearance.assign": "يمنح الأجسام أو الأوجه أو المكوّنات المحددة لونًا أو مظهر مادة، من دون تغيير وزنها. استخدمه للتمييز بين القطع أو لمعاينة التشطيب.", + "help.assembly.bom": "يسرد قطع التصميم أو المكوّن مع أعدادها حسب رقم القطعة، ويمكنه حفظ القائمة بصيغة CSV أو JSON. استخدمه كقائمة قطع للطلب والتجميع.", "help.attributions": "الإسنادات (ATTRIBUTION.md)", "help.build": "الإصدار {version} · الإيداع {commit} · بُني في {date}", + "help.canvas.decal": "يضع صورة على وجه مستوٍ من النموذج مثل ملصق. استخدمه لإظهار تسمية أو شعار أو نمط مطبوع على قطعة.", + "help.canvas.edit": "يغيّر اللوحة المرجعية: موضعها أو حجمها أو زاويتها أو عتامتها أو انعكاسها أو ظهورها أو اسمها. استخدمه لمحاذاة صورة مرجعية مع الرسم الذي تتتبعه فوقها.", + "help.canvas.insert": "يضع صورة PNG أو JPEG على مستوى أو وجه كمرجع شبه شفاف. استخدمه لتتبع صورة أو مخطط في رسم، مع ضبط الصورة على مقاس معلوم.", + "help.component.break_link": "يفصل مكوّنًا مرتبطًا عن ملف تصميمه مع إبقاء أجسامه كما هي. استخدمه عندما ينبغي ألا تتبع القطعة تغييرات الملف الأصلي بعد الآن.", + "help.component.capture_position": "يحفظ مواضع القطع التي حركتها يدويًا لتصبح مواضعها المعتمدة. استخدمه بعد سحب قطع إلى أماكنها دون أن يمسكها أي مفصل.", + "help.component.create": "يضيف مكوّنًا جديدًا فارغًا إلى التصميم داخل المكوّن النشط، ما لم تختر مكوّنًا أبًا آخر. استخدمه لمنح قطعة جديدة في تجميع مكانًا خاصًا لأجسامها ورسومها.", "help.component.finish_edit": "يحفظ الجزء الذي تحرّره في مكانه، ويعود إلى تجميعه ويحدّث التجميع منه. استخدمه عند الانتهاء من تغييراتك على الجزء المرتبط.", + "help.component.from_bodies": "يحوّل كل جسم محدد إلى مكوّن مستقل يحمل اسم الجسم. استخدمه لتحويل تصميم من أجسام منفصلة إلى تجميع يمكن ربط قطعه وتحريكها.", + "help.component.insert_design": "يدرج تصميمًا محفوظًا آخر كمكوّن مرتبط بملفه، مع وضع أجسامه الصلبة كما هي فيه. استخدمه لإعادة استخدام قطعة في تجميع واستيراد تغييراتها اللاحقة عبر تحديث الروابط.", + "help.component.properties": "يعرض الحجم والكتلة ومركز الكتلة وعزوم القصور الذاتي لمكوّن، اعتمادًا على مواد أجسامه. استخدمه للتحقق من وزن التجميع وتوازنه.", + "help.component.revert_position": "يعيد القطع التي حركتها يدويًا إلى مواضعها السابقة، ويتجاهل التحركات التي لم تُثبّت مواضعها. استخدمه للتراجع عن التحركات التجريبية في تجميع.", + "help.component.update_links": "يعيد قراءة ملفات التصميم المرتبطة ويستبدل الأجسام التي تغيّرت. استخدمه بعد تعديل قطعة يستخدمها هذا التجميع.", + "help.config.configure": "يضيف معاملات أو ميزات أو مواد أو مظاهر كأعمدة في جدول التكوينات. استخدمه لبناء نسخ متعددة من تصميم واحد، مثل مقاسات قطعة.", + "help.config.preview": "يتحقق من أن صفًا في جدول التكوينات يُعاد بناؤه بنجاح، دون تغيير التصميم أو سجله. استخدمه قبل التبديل إلى نسخة لست متأكدًا منها.", + "help.config.rules": "يعرض قواعد جدول التكوينات وصفوفه والصف النشط حاليًا. استخدمه لمعرفة كيف أُعدّت نسخ التصميم.", + "help.config.table": "يعرض جدول التكوينات: صف لكل نسخة وعمود لكل معامل أو ميزة، ويبيّن هل ما زال التصميم مطابقًا للصف النشط. استخدمه لمراجعة نسخ التصميم.", "help.connect_note": "أعد تشغيل كل مساعد لتحميل خادم SolidCraft. نُسخ كل ملف احتياطيًا بامتداد .bak قبل تغييره.", "help.connect_title": "ربط مساعدي الذكاء الاصطناعي", + "help.construct.axis.edge": "ينشئ محورًا إنشائيًا على امتداد حافة مستقيمة أو خط رسم. استخدمه كمحور لعملية دوران أو لنمط دائري أو لمفصل.", + "help.construct.axis.normal_to_face": "ينشئ محورًا إنشائيًا يمر بنقطة ويكون عموديًا على وجه. استخدمه كمحور يبرز مستقيمًا من السطح.", + "help.construct.axis.through_cylinder": "ينشئ محورًا إنشائيًا عبر مركز وجه أسطوانة أو مخروط أو طارة، أو حافة دائرية. استخدمه لتدوير الميزات أو تكرارها حول قطعة مستديرة.", + "help.construct.axis.two_planes": "ينشئ محورًا إنشائيًا عند التقاء مستويين أو وجهين مسطحين. استخدمه حين يكون المحور المطلوب هو الخط بين وجهين.", + "help.construct.axis.two_points": "ينشئ محورًا إنشائيًا يمر بنقطتين أو رأسين أو نقطتي رسم. استخدمه لمحور يمتد بين موضعين معروفين.", + "help.construct.plane.along_path": "ينشئ مستوى إنشائيًا عموديًا على حافة أو منحنى عند موضع على امتداده. استخدمه لرسم مقطع من أجل كنس أو لمقطع عرضي للمسار.", + "help.construct.plane.at_angle": "ينشئ مستوى إنشائيًا مائلًا بزاوية عن مستوى أو وجه، حول محور أو حافة. استخدمه للرسوم المائلة، مثل حامل مائل.", + "help.construct.plane.axis_point": "ينشئ مستوى إنشاء يحتوي على محور ونقطة خارجه. اختر محور الأصل أو محور إنشاء أو حافة مستقيمة أو خط رسم، ثم رأسًا أو نقطة رسم أو نقطة إنشاء. النقطة الواقعة على المحور لا تحدد مستوى وحيدًا.", + "help.construct.plane.midplane": "ينشئ مستوى إنشائيًا في منتصف المسافة بين مستويين أو وجهين مسطحين، أو منصّفًا لهما حيث يلتقيان بزاوية. استخدمه كمستوى تناظر عند عمل مرآة.", + "help.construct.plane.offset": "ينشئ مستوى إنشائيًا موازيًا لمستوى أو وجه مسطح، على مسافة محددة أو عبر نقطة. استخدمه للرسم على ارتفاع محدد فوق وجه.", + "help.construct.plane.perpendicular": "ينشئ مستوى إنشائيًا يحوي خطًا أو حافة ويكون عموديًا على مستوى أو وجه. استخدمه للرسم بشكل رأسي على النموذج على امتداد حافة.", + "help.construct.plane.tangent": "ينشئ مستوى إنشائيًا يمس أسطوانة أو مخروطًا أو كرة أو طارة عند نقطة. استخدمه للرسم على جانب قطعة مستديرة.", + "help.construct.plane.three_points": "ينشئ مستوى إنشائيًا يمر بثلاث نقاط. استخدمه لمستوى تحدده مواضع على النموذج، مثل ثلاث زوايا.", + "help.construct.plane.two_edges": "ينشئ مستوى إنشائيًا يمر بحافتين مستقيمتين أو خطين يقعان في مستوى واحد. استخدمه لمستوى يقطع القطعة، مثل مستوى يمر بحافتين متقابلتين.", + "help.construct.point.along_path": "ينشئ نقطة إنشائية عند موضع على امتداد حافة أو منحنى. استخدمها كمرجع في موضع بين طرفي المسار.", + "help.construct.point.center": "ينشئ نقطة إنشائية في مركز حافة دائرية أو دائرة رسم أو قوس أو كرة أو طارة. استخدمها كمرجع للثقوب والمحاور والمفاصل.", + "help.construct.point.edge_plane": "ينشئ نقطة إنشائية حيث تخترق حافة أو خط مستوى أو وجهًا مسطحًا. استخدمها لتحديد موضع عبور المسار للمستوى.", + "help.construct.point.three_planes": "ينشئ نقطة إنشائية حيث تلتقي ثلاثة مستويات أو أوجه مسطحة. استخدمها مرجعًا لزاوية، حتى حيث لا يوجد رأس في النموذج.", + "help.construct.point.two_edges": "ينشئ نقطة إنشائية حيث تلتقي حافتان أو خطان، أو حيث يكونان أقرب ما يمكن. استخدمها مرجعًا عند زاوية افتراضية.", + "help.construct.point.vertex": "ينشئ نقطة إنشائية على رأس أو نقطة رسم. استخدمها مرجعًا يبقى حتى عند إخفاء الرسم أو الجسم المحيط بها.", + "help.contact.check": "يسرد أزواج القطع في مجموعات التلامس التي تتداخل أجسامها في مواضعها الحالية. استخدمه لاكتشاف التصادمات قبل تحريك المفاصل أو تشغيل دراسة الحركة.", + "help.contact.create": "يجمع قطعتين أو أكثر في مجموعة تلامس تمنع أجسامها من اختراق بعضها أثناء حركة المفاصل. استخدمه للقطع التي ينبغي أن تتوقف عند التلامس، مثل ذراع يصطدم بمصدّه.", + "help.contact.disable_all": "يعطّل التلامس، فلا تعود المفاصل المحرّكة ودراسات الحركة تتوقف عند تلامس القطع. استخدمه لتحريك القطع بحرية مجددًا أو للحفاظ على سرعة استجابة تجميع كبير.", + "help.contact.edit": "يعدّل مجموعة تلامس: قطعها أو اسمها أو حالة تعطيلها المؤقت، ويمكنه حذف المجموعة أيضًا. استخدمه لتحديد القطع التي يُمنع تداخل أجسامها.", + "help.contact.enable_all": "يضع كل قطع التجميع في مجموعة تلامس واحدة، فلا يمكن لأي قطعتين اختراق بعضهما أثناء حركة المفاصل. استخدمه لفحص آلية كاملة بسرعة.", + "help.contact.enable_sets": "يفعّل التلامس لمجموعات التلامس التي عرّفتها، فتتوقف المفاصل المحرّكة ودراسات الحركة حيث كانت قطعها ستخترق بعضها. استخدمه لإعادة تفعيل مجموعاتك بعد تعطيل التلامس.", + "help.contact.list": "يسرد مجموعات التلامس في التصميم والقطع في كل مجموعة وحالة تفعيل التلامس. استخدمه لفحص إعداد التلامس قبل تحريك التجميع.", + "help.document.inspect": "يعرض نظرة عامة على التصميم: مكوّناته وأجسامه ورسومه وميزاته ومعاملاته. استخدمه للتعرف على تصميم لم تبنِه بنفسك.", + "help.document.units": "يغيّر الوحدات التي تُعرض بها الأطوال في التصميم، مثل mm أو البوصة. يحتفظ الشكل الهندسي بحجمه؛ ويتغير العرض والأرقام العادية فقط.", + "help.edit.checkpoint": "يحفظ التصميم والرسم النشط وسجل التراجع كما هي الآن. استخدمه قبل تجربة شيء محفوف بالمخاطر قد ترغب في العودة منه.", + "help.edit.restore_checkpoint": "يعود إلى نقطة حفظ مع سجل التراجع. استخدمه لتجاهل كل ما أُجري منذ نقطة الحفظ بخطوة واحدة.", + "help.explode.create": "ينشئ عرضًا مفككًا يباعد القطع عن مركز التجميع أو ينقلها وفق التحركات التي تحددها. استخدمه لإظهار كيفية تركيب التجميع في التعليمات أو العروض التقديمية.", "help.face.delete": "يحذف الأوجه المحددة ويترك الأوجه المجاورة تسد الفجوة، أو يترك الفتحة مفتوحة كسطح. استخدمه لإزالة حافة مقوّسة أو ثقب أو نتوء يعترض الطريق.", + "help.file.insert_mesh": "يضيف ملف 3MF أو STL أو OBJ أو PLY أو glTF إلى التصميم كأجسام شبكية في مكوّن جديد. استخدمه لوضع نموذج منزّل أو ممسوح ضوئيًا بجانب تصميمك كمرجع.", + "help.file.insert_step": "يضيف ملف STEP أو IGES أو FreeCAD أو Rhino إلى التصميم كأجسام صلبة في مكوّن جديد، وتصبح قطع التجميع مكوّنات متداخلة. استخدمه لاستيراد نماذج من المورّدين أو برامج CAD الأخرى.", + "help.file.save_mesh": "يحفظ الأجسام كشبكة STL أو 3MF أو OBJ بدرجة نعومة الوجوه المنحنية التي تختارها. استخدمه لتجهيز القطع للطباعة ثلاثية الأبعاد أو للبرامج التي تقرأ الشبكات.", + "help.file.send_to_slicer": "يحفظ الأجسام المحددة في ملف 3MF ويفتحه في برنامج التقطيع الذي تختاره. استخدمه للانتقال من النموذج إلى الطباعة بخطوة واحدة.", "help.font_details": "تستخدم الواجهة خطوط egui المدمجة (Ubuntu Light وHack، بموجب رخصة Ubuntu Font ورخصة MIT/Bitstream Vera، وNoto Emoji وخط أيقونات الرموز التعبيرية بموجب OFL وMIT). يستخدم نص الرسم خط Liberation Sans (SIL OFL 1.1). حزمة الخطوط الاختيارية craft-fonts لتطبيقات Crafting (BIZ UDPGothic وShippori Mincho وBIZ UDMincho وNoto Sans CJK SC وNoto Sans Arabic، بموجب SIL OFL 1.1) غير مضمّنة في إصدارات SolidCraft.", "help.fonts": "الخطوط", + "help.frame.member": "يضع مقطعًا، مثل أنبوب أو قطاع ألومنيوم مبثوق، على امتداد خطوط رسم هيكل، بعنصر واحد لكل خط. استخدمه لبناء الهياكل والرفوف والمنشآت الملحومة.", + "help.inspect.accessibility": "يلوّن الأوجه التي تستطيع أداة الوصول إليها من اتجاه واحد، وتلك التي لا تستطيع. استخدمه لفحص قطعة للتشغيل الآلي أو القولبة من ذلك الجانب.", + "help.inspect.center_of_mass": "يعرض مركز كتلة الأجسام، كلٍّ على حدة ومجتمعةً، بكثافة منتظمة. استخدمه لفحص التوازن ومعرفة أين ستميل القطعة.", + "help.inspect.colored_components": "يمنح كل مكوّن لونه المؤقت الخاص دون تغيير المظاهر. استخدمه لتمييز قطع التجميع بنظرة واحدة.", + "help.inspect.compare": "يقارن جسمين ويبيّن المواضع التي يحتوي فيها أحدهما مادة لا يحتويها الآخر، مع الحجم والانحراف. استخدمه لمقارنة قطعة معدّلة أو مستوردة بالأصل.", + "help.inspect.continuity": "يفحص مدى نعومة التقاء الأوجه عند حوافها: فجوات أو انكسارات أو قفزات في الانحناء، ويظلّل الدرزات. استخدمه لإيجاد المواضع التي لا تلتقي فيها الأسطح بنظافة.", + "help.inspect.curvature_comb": "يرسم أمشاطًا على المنحنيات أو الحواف أو الأوجه تُظهر أسنانها مدى شدة انحنائها. استخدمه لكشف المواضع المسطحة والانكسارات وعدم انتظام الانحناء.", + "help.inspect.curvature_map": "يلوّن الأوجه بحسب شدة انحنائها، بالأحمر حيث يصغر نصف القطر. استخدمه لإيجاد المواضع الضيقة وللحكم على نعومة السطح.", + "help.inspect.draft": "يلوّن الأوجه بحسب زاوية الميل بالنسبة لاتجاه السحب، ويحدد ذات الميل غير الكافي. استخدمه لفحص القطعة قبل القولبة أو الصب.", + "help.inspect.environment_map": "يعرض النموذج بلمسة نهائية عاكسة تشبه المرآة. استخدمه للحكم على انسياب الأسطح من طريقة مرور الانعكاسات عليها.", + "help.inspect.interference": "يجد الأجسام المتداخلة ويعرض كل تداخل مع حجمه. استخدمه لفحص التجميع بحثًا عن قطع تتصادم.", + "help.inspect.isocurve": "يرسم المنحنيات المتساوية المعاملات للأوجه، أي الشبكة التي بُني عليها السطح. استخدمه لمعرفة كيف ينساب السطح وأين تتجمع الخطوط.", + "help.inspect.measure": "يقيس الأطوال والمسافات والزوايا والمساحات وأنصاف الأقطار بين ما تحدده، أو حجم الأجسام وكتلتها. استخدمه للتحقق من المقاسات والخلوصات.", + "help.inspect.minimum_radius": "يجد أصغر نصف قطر انحناء للمنحنيات أو الحواف أو الأوجه وموضعه. استخدمه للتأكد من أن أداة أو فوهة تستطيع اتباع الشكل.", + "help.inspect.section": "يقطع العرض على امتداد مستوى ويهشّر الأوجه المقطوعة دون تغيير النموذج. استخدمه للنظر داخل القطع والتجميعات.", + "help.inspect.zebra": "يعرض خطوطًا سوداء وبيضاء منعكسة على أوجه النموذج. استخدمه للحكم على النعومة: الخطوط التي تنقطع أو تنكسر عند حافة تدل على انتقال ضعيف.", + "help.joint.as_built": "يربط قطعتين في موضعيهما الحاليين دون تحريك أي منهما، ويحدد الحركة المسموحة لهما. استخدمه للقطع التي وضعتها بالفعل في مواضعها النهائية.", + "help.joint.cam": "يربط كامة دوّارة بتابع، فينزلق التابع أو يتأرجح عندما يمر محيط الكامة تحته. استخدمه للكامات واللامركزيات وآليات تشغيل الصمامات.", + "help.joint.create": "يربط قطعتين عند أصلي المفصل اللذين تختارهما وينقل القطعة الثانية إلى موضعها، ويحدد نوع المفصل الحركة المسموحة لهما. استخدمه لبناء تجميع تتحرك قطعه مثل الآلية الحقيقية.", + "help.joint.drive": "يضبط زاوية المفصل أو مسافته ويحرّك القطع معه ضمن حدوده، وتتبعها المفاصل المرتبطة والحلقات المغلقة. استخدمه للتحقق من أن الآلية تتحرك كما هو مقصود.", + "help.joint.gear": "يربط مفصلين دوّارين بنسبة تروس، بحيث يؤدي تحريك أحدهما إلى دوران الآخر. استخدمه للتروس المستقيمة والحلقية، مع تحديد النسبة من أنصاف أقطار دوائر الخطوة أو أعداد الأسنان.", + "help.joint.limits": "يضبط الحدين الأدنى والأقصى لدوران المفصل أو انزلاقه، أو يزيل هذين الحدين. استخدمه لإبقاء مفصلة أو منزلق أو ذراع ضمن نطاق حركته الحقيقي.", + "help.joint.motion_link": "يربط مفصلين بنسبة وإزاحة، بحيث يؤدي تحريك أحدهما إلى تحريك الآخر. استخدمه لعلاقة ثابتة بين المفاصل لا تغطيها أدوات ترس أو جريدة مسننة وترس أو لولب.", + "help.joint.origin": "يضع أصل مفصل باسم على قطعة، عند مركز وجه أو نهاية دائرية أو منتصف حافة أو ركن أو نقطة. استخدمه لتجهيز مواضع اتصال المفاصل، فالأصل المختار على وجه يتبعه عند تغيير مقاس القطعة.", + "help.joint.rack_pinion": "يربط ترسًا دوّارًا بجريدة مسننة منزلقة، فتتحرك الجريدة بمقدار طول قوس دائرة الخطوة الذي يدور به الترس. استخدمه لمحركات الجريدة المسننة وأنظمة التوجيه ومنصات الحركة الخطية.", + "help.joint.reach": "يحرّك نقطة على قطعة نحو هدف بتغيير مفاصل سلسلتها ضمن حدودها. استخدمه لضبط وضعية آلية حسب الموضع المطلوب لنهايتها، مثل طرف ذراع روبوت.", + "help.joint.rigid_group": "يثبّت القطع المحددة معًا كما هي لتتحرك كقطعة واحدة. استخدمه للقطع التي تنتمي إلى وحدة واحدة ولا تتحرك بالنسبة إلى بعضها.", + "help.joint.screw": "يربط الدوران والانزلاق بخطوة لولبية، بحيث تتقدم القطعة بمقدار تلك المسافة في كل دورة. استخدمه للوالب القيادة والبراغي والمحاور الملولبة.", + "help.layout.apply": "تطبيق تخطيط محفوظ على مساحة العمل الحالية. تحتفظ أدوات التحرير القائمة بمسوداتها.", + "help.layout.get": "قراءة التخطيط المعتمد وعرض مساحات العمل المسجلة.", + "help.layout.reset": "استعادة التخطيط الافتراضي المسجل لمساحة العمل الحالية. تبقى إعدادات المستخدم المسبقة متاحة.", + "help.layout.save": "حفظ التخطيط الكامل باسم محدد. يتطلب استبدال إعداد مسبق للمستخدم إذنًا صريحًا بالكتابة فوقه.", + "help.layout.workspace.select": "اختيار مساحة عمل تخطيط مسجلة وتذكر التخطيط السابق.", + "help.library.apply": "يطبّق مادة أو مظهرًا من ملف مكتبة محلي على أجسام أو أوجه أو مكوّنات. استخدمه لإعادة استخدام مواد حفظتها من تصميم آخر.", + "help.library.export": "يحفظ مواد التصميم ومظاهره في ملف مكتبة. استخدمه لمشاركتها أو إعادة استخدامها في تصميمات أخرى.", + "help.library.inspect": "يفحص ملف مكتبة ويسرد موادّه ومظاهره دون تغيير التصميم. استخدمه لمعرفة ما تحويه المكتبة قبل تطبيقها.", "help.licences": "الرخص", "help.material.assign": "يحدد المادة التي صُنعت منها الأجسام المحددة، مثل الفولاذ أو الألومنيوم أو ABS. استخدمه لتطابق الكتلة والوزن القطعة الحقيقية.", + "help.material.properties.validate": "يفحص بطاقة بيانات مادة بحثًا عن أرقام غير متسقة أو قيم مفقودة. استخدمه قبل الاعتماد على البيانات في حساب الكتلة أو الصلابة.", + "help.mesh.convert": "يعيد بناء جسم شبكي، مثل ملف STL، كجسم صلب قابل للتعديل بأوجه مسطحة وأسطوانية. استخدمه لتعديل القطع الميكانيكية المستوردة كأنها جسم منمذج.", "help.mit": "رخصة MIT", + "help.motion.study": "يضبط قيم المفاصل عند خطوات على خط زمني ويشغّلها كرسوم متحركة. استخدمه لمشاهدة حركة آلية عبر تسلسل وفحص الخلوص أثناء الحركة.", + "help.motion.trace": "يتتبع مسار نقطة على قطعة أثناء تشغيل دراسة الحركة أو تحريك مفصل، ويحفظه كمنحنى رسم ثلاثي الأبعاد عند التأكيد. استخدمه لرؤية مدى وصول آلية أو لبناء أشكال اعتمادًا على مسارها.", "help.notice": "NOTICE", + "help.occurrence.ground": "يثبّت قطعة في موضعها أو يحررها مجددًا، بحيث تحرّك المفاصل القطع الأخرى حولها. استخدمه للإطار أو القاعدة التي يُبنى عليها باقي التجميع.", "help.occurrence.move": "يحرّك جزءًا في التجميع فقط ضمن درجات الحرية التي تسمح بها مفاصله. حدد وجهًا للجزء، ثم اسحب سهمًا أو قوسًا متاحًا.", + "help.panel.activate": "اختيار علامة تبويب لوحة مفتوحة دون طلب تركيز لوحة المفاتيح.", + "help.panel.close": "إغلاق اللوحة بعد التحقق من دورة حياة محتواها. يُحفظ موضعها.", + "help.panel.collapse": "طي قسم اللوحة أو توسيعه مع الاحتفاظ بأبعاده المطلوبة.", + "help.panel.dismiss": "إغلاق العرض المؤقت للوحة مطوية.", + "help.panel.float": "نقل لوحة إلى قسم عائم ذي موضع محدد صراحةً.", + "help.panel.focus": "تركيز لوحة وإعادة فتح حالتها المحفوظة وتوسيع قسمها عند الحاجة.", + "help.panel.list": "قراءة أنواع اللوحات المسجلة والمثيلات المعتمدة وعلامات التبويب النشطة والتوافر وإمكانات المضيف.", + "help.panel.move": "نقل لوحة إلى قسم جديد أو ضمها إلى مجموعة علامات تبويب موجودة.", + "help.panel.native_close": "إعادة قسم لوحة من نافذته المستقلة إلى موضع الإرساء المحفوظ دون إلغاء محتواه.", + "help.panel.open": "فتح نوع لوحة بمعرّف مثيل صريح. يتطلب المثيل الجديد تحديد موضعه.", + "help.panel.peek": "إظهار لوحة مطوية مؤقتًا دون تغيير حجمها المحفوظ أو حالة طيها.", + "help.panel.popout": "نقل لوحة إلى نافذة مستقلة عند دعم ذلك. يستخدم مضيف المتصفح قسمًا عائمًا.", + "help.panel.reset_pair": "استعادة نسبة الحجم الافتراضية لقسمي إرساء متجاورين ضمن حدودهما المشتركة.", + "help.panel.resize": "تعيين العرض والارتفاع الخارجيين لقسم اللوحة ضمن حدود جميع علامات التبويب.", + "help.panel.resize_pair": "تغيير حجم قسمي إرساء متجاورين معًا مع الحفاظ على امتدادهما الكلي المشترك.", "help.parameters.change": "يفتح جدول القيم المسماة والتعبيرات التي تتحكم في أبعاد التصميم. استخدمه لتغيير مقاس في مكان واحد فتتبعه كل الميزات التي تستخدمه.", + "help.parameters.export": "يحفظ معاملات التصميم بصيغة CSV أو JSON. استخدمه لتعديلها في جدول بيانات أو نقلها إلى تصميم آخر.", + "help.parameters.graph": "يبيّن أي المعاملات والميزات تستخدم أيًّا من غيرها، وأي حلقات أو أخطاء بينها. استخدمه لمعرفة ما سيتأثر بتغيير معامل.", + "help.parameters.import": "يقرأ المعاملات من CSV أو JSON إلى التصميم، كلها أو لا شيء منها. استخدمه لإحضار قيم من جدول بيانات أو من تصميم آخر.", + "help.parameters.move": "ينقل معاملًا من معاملات المستخدم قبل معامل آخر أو بعده في القائمة. استخدمه لإبقاء المعاملات المترابطة معًا.", + "help.parts.fastener": "يضيف برغيًا أو مسمار ربط أو صامولة أو وردة أو دبوسًا أو محملًا قياسيًا بالمقاس الذي تختاره. عند وضعه على ثقب يستقر فيه بمفصل، فلا تحتاج إلى نمذجة أدوات التثبيت بنفسك.", + "help.parts.insert": "يدرج قطعة قياسية من الفئة وبالمقاس والطول الذي تختاره. عند وضعها على إطار ثقب أو جداره، تستقر على الثقب بمفصل صلب.", + "help.parts.library": "يفتح القطع القياسية: البراغي ومسامير الربط والصواميل والوردات وبراغي التثبيت ودبابيس التمركز والمحامل بالمقاسات القياسية. استخدمه لإضافة قطعة قياسية بدلًا من نمذجتها بنفسك.", + "help.parts.resize": "يغيّر مقاس قطعة قياسية مدرجة أو طولها ويعيد بناءها، وتبقيها مفاصلها مثبتة في مكانها. استخدمه عندما يتبين أن برغيًا أطول من اللازم أو أن ثقبًا يحتاج إلى مقاس آخر.", + "help.plastic.assign_rule": "يعيّن قاعدة بلاستيك لأجسام، فتأخذ ميزاتها البلاستيكية ميلها وخلوصها منها كقيم افتراضية. استخدمه لإعداد قطعة مقولبة مرة واحدة لكل ميزاتها.", + "help.plastic.boss": "يضيف نتوءًا لمسمار على وجه: عمودًا مع ثقب اختياري وميل وتقويس عند الجذر وأضلاع تقوية. استخدمه لنقاط البراغي في الهياكل المقولبة أو المطبوعة.", + "help.plastic.lip": "يضيف شفة أو أخدودًا مطابقًا على طول حافة جسم مفرَّغ. استخدمه ليتمركز نصفا الهيكل أحدهما على الآخر ويُغلقا بإحكام.", + "help.plastic.manage_rules": "ينشئ قواعد البلاستيك ويعدّلها: المادة وسماكة الجدار وأنصاف الأقطار والخلوص والميل. استخدمها للحفاظ على اتساق ميزات القطعة المقولبة.", + "help.plastic.rest": "يضيف مسندًا على وجه: وسادة مستديرة أو مستطيلة، مصمتة أو مجوفة، مع ميل. استخدمه كدعامة أو مُباعِد في هيكل مقولب.", + "help.plastic.snap_fit": "يضيف خطاف وصلة كبس على وجه، بطوله وسماكته ونتوء التثبيت. استخدمه لتثبيت القطع معًا بلا براغي.", "help.pointcloud.insert": "أدرج مسحًا بصيغة PLY أو XYZ أو PTS كسحابة نقاط بجانب النموذج. استخدمه كمرجع عند النمذجة انطلاقًا من بيانات القياس.", + "help.sheet.convert": "يحوّل لوحًا أو جسمًا مفرَّغًا بسماكة منتظمة إلى جسم صفائح معدنية، مع ثنيات عند الحواف التي تحددها. استخدمه لجعل قطعة موجودة قابلة للفرد.", + "help.sheet.export_bend_table": "يحفظ جدول الثني لجسم صفائح معدنية بصيغة CSV أو JSON: الزوايا وأنصاف الأقطار ومواضع الثني في النمط المسطح. استخدمه لماكينة الثني أو الورشة.", + "help.sheet.export_dxf": "يحفظ النمط المسطح بصيغة DXF، مع الحدود وخطوط الثني وملاحظات الثني الاختيارية. استخدمه للقطع بالليزر أو البلازما أو نفاث الماء.", + "help.sheet.flange": "يضيف حافة مثنية: لوحًا أساسيًا من رسم، أو جدارًا على امتداد محيط رسم مفتوح، أو جدارًا مثنيًا على حواف الصفيحة. استخدمه لبناء قطع الصفائح المعدنية.", + "help.sheet.flat_pattern": "ينشئ النمط المسطح لجسم صفائح معدنية، مع حجمه وفتحاته وخطوط الثني. استخدمه لفحص الشريحة الخام قبل قصها.", + "help.sheet.fold": "يثني صفيحة على امتداد خط رسم بزاوية ونصف قطر محددين. استخدمه لطي صفيحة مسطحة بعد عمل القطوع فيها.", + "help.sheet.hem": "يطوي حافة صفيحة على نفسها. استخدمه لحواف آمنة وصلبة بلا نتوءات حادة.", + "help.sheet.manage_rules": "ينشئ قواعد الصفائح المعدنية ويعدّلها: السماكة ونصف قطر الثني ومعامل K والتفريغات والفجوات. استخدمها لمطابقة مادة ورشتك وأدواتها.", + "help.sheet.path_flange": "يضيف سلسلة من الحواف المثنية على امتداد حافة صفيحة، متتبعًا سلسلة مفتوحة من خطوط الرسم. استخدمها لمقاطع مثل شكل U أو Z بخطوة واحدة.", + "help.sheet.perforate": "يضيف حقلًا من الثقوب على كامل الصفيحة المسطحة، بنمط متدرج أو مربع. استخدمه للتهوية والشبكات والألواح الأخف.", + "help.sheet.refold": "يعيد طي جسم صفائح معدنية مفرود. استخدمه بعد إضافة ميزات إلى الصفيحة المسطحة.", + "help.sheet.unfold": "يفرد جميع ثنيات جسم صفائح معدنية. استخدمه لإضافة ثقوب أو قطوع يجب أن تعبر ثنية، ثم استخدم إعادة الطي.", + "help.sketch.arc.center_point": "يرسم قوسًا دائريًا حول نقطة مركز، من نقطة بداية إلى نقطة نهاية. استخدمه عندما يكون مركز القوس معروفًا، مثل نصف قطر حول ثقب أو محور.", + "help.sketch.arc.tangent": "يرسم قوسًا يبدأ من نهاية خط أو قوس ويكمل مماسًا له. استخدمه لمتابعة السلسلة بانحناء ناعم بدل زاوية حادة.", + "help.sketch.arc.three_point": "يرسم قوسًا من نقطة بداية إلى نقطة نهاية مارًا بنقطة ثالثة. استخدمه عندما يجب أن يمر القوس بنقاط محددة لا حول مركز معروف.", + "help.sketch.arc3d": "يرسم قوسًا دائريًا دقيقًا في الفراغ عبر ثلاث نقاط، مع تفعيل الرسم ثلاثي الأبعاد. استخدمه لانحناءات المسارات وقضبان التوجيه الخارجة عن مستوى الرسم.", + "help.sketch.auto_constrain": "يضيف القيود التي يكاد الرسم يحققها أصلًا، مثل الأفقي أو المتوازي أو المتطابق، ثم يضيف الأبعاد حتى يصبح محددًا بالكامل. استخدمه لتثبيت رسم تقريبي بخطوة واحدة.", + "help.sketch.auto_constrain_from_datum": "يعمل مثل «تقييد تلقائي»، لكنه يقيس المواضع من نقطة مرجعية تختارها بدل نقطة الأصل. استخدمه عندما تُحدَّد أبعاد القطعة انطلاقًا من نقطة مرجعية واحدة، كركن أو ثقب.", + "help.sketch.blend_curve": "يصل نهايتي منحنيين بمنحنى شريحي ناعم مماس لكليهما، أو مستمر الانحناء أيضًا إن اخترت. استخدمه لسد الفجوة بين منحنيين دون التواء.", + "help.sketch.break": "يقسم المنحنى إلى أجزاء عند تقاطع منحنيات أخرى معه، أو عند نقاط تضعها عليه. استخدمه عندما يحتاج جزء من المنحنى إلى قيده الخاص أو إلى حذفه وحده.", + "help.sketch.cancel": "يغادر الرسم ويتجاهل كل ما تغيّر منذ إنشائه أو فتحه للتعديل. ويمكن استعادة التغييرات بأمر «تراجع».", + "help.sketch.centerline": "يبدّل الخطوط بين خطوط عادية وخطوط المركز، وهي محاور لا تدخل في المقاطع. استخدم خط المركز محورًا لأمر «دوران» أو «مرآة» أو لقيد التناظر.", + "help.sketch.chamfer.distance_angle": "يشطف الزاوية بين خطين بمسافة على طول الخط الأول وبزاوية. استخدمه عندما يعطي المخطط الشطف بطول وزاوية، مثل 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "يشطف الزاوية بين خطين بالمسافة نفسها على طول كليهما. استخدمه للشطف المعتاد بزاوية 45° على المحيط.", + "help.sketch.chamfer.two_distance": "يشطف الزاوية بين خطين بمسافة مستقلة على كل خط. استخدمه للشطف بزاوية غير 45°، المعطى بطولين.", + "help.sketch.circle.center": "يرسم دائرة من مركزها وقطرها. استخدمه للثقوب والنتوءات والميزات المستديرة الأخرى المعروف مركزها.", + "help.sketch.circle.three_point": "يرسم دائرة تمر بثلاث نقاط. استخدمه عندما يجب أن تمر الدائرة بنقاط محددة، مثلًا من هندسة موجودة.", + "help.sketch.circle.three_tangent": "يرسم دائرة تمس ثلاثة خطوط أو دوائر أو أقواس. استخدمه لإدخال دائرة في الفراغ بين ثلاثة منحنيات، مثل الدائرة المحاطة بمثلث.", + "help.sketch.circle.two_point": "يرسم دائرة من طرفي قطرها. استخدمه عندما تكون نقطتا حافة الدائرة معروفتين لا مركزها.", + "help.sketch.circle.two_tangent": "يرسم دائرة بحجم محدد تمس خطين أو دائرتين أو قوسين. استخدمه لتقويس ثابت نصف القطر بين منحنيين.", + "help.sketch.conic": "يرسم منحنى مخروطيًا بين نقطتي نهاية، يتشكل بنقطة قمة وقيمة rho. استخدمه لانتقالات ناعمة تضبط امتلاءها من المسطح إلى ما يقارب زاوية حادة.", + "help.sketch.constrainer": "يطبق القيد الذي يكاد منحنى أو منحنيان محددان يحققانه، مثل الأفقي أو التوازي أو التماس أو التساوي. استخدمه لتهذيب رسم يدوي علاقة بعد أخرى.", + "help.sketch.constraint.coincident": "يجعل نقطة تقع على نقطة أخرى أو على منحنى أو على محور الرسم. استخدمه لسد الفجوات في المقطع أو لوضع نقطة على خط.", + "help.sketch.constraint.collinear": "يجعل خطين يقعان على خط مستقيم واحد. استخدمه لمحاذاة الحواف المتقطعة، مثل جانبي حز.", + "help.sketch.constraint.concentric": "يجعل دائرتين أو قوسين يشتركان في المركز نفسه، أو يضع مركز دائرة أو قوس على نقطة في الرسم التخطيطي، بما في ذلك نقطة الأصل. اختر العنصرين بأي ترتيب.", + "help.sketch.constraint.curvature": "يجعل منحنيين يلتقيان عند نقطة نهاية يتابعان بالانحناء نفسه (G2). استخدمه حيث لا يكفي الوصل المماسي نعومة، مثلًا على الأسطح الظاهرة.", + "help.sketch.constraint.equal": "يجعل الخطوط بالطول نفسه، أو الدوائر والأقواس بنصف القطر نفسه. استخدمه ليتحكم بُعد واحد في عدة ميزات متماثلة.", + "help.sketch.constraint.fix": "يثبّت النقاط أو المنحنيات في مكانها، أو يفك تثبيتها. استخدمه للهندسة التي يجب ألا تتحرك عند سحب الرسم أو حله.", + "help.sketch.constraint.horizontal_vertical": "يجعل خطًا، أو الخط بين نقطتين، أفقيًا أو رأسيًا، أيهما أقرب. استخدمه لمحاذاة المحيط مع محاور الرسم.", + "help.sketch.constraint.midpoint": "يضع نقطة في منتصف خط، أو يجعل منتصفي خطين يلتقيان. استخدمه لتوسيط الهندسة على حافة.", + "help.sketch.constraint.parallel": "يجعل خطين متوازيين. استخدمه للأضلاع التي يجب أن تبقى متوازية عند تغيير الأبعاد الأخرى.", + "help.sketch.constraint.perpendicular": "يجعل خطين يلتقيان بزاوية قائمة. استخدمه للزوايا القائمة بين خطوط ليست على محاور الرسم.", + "help.sketch.constraint.polygon": "يجعل سلسلة مغلقة من الخطوط مضلعًا منتظمًا: أضلاع متساوية وكل زاوية على دائرة واحدة. استخدمه لجعل مضلع مرسوم يدويًا منتظمًا والحفاظ على ذلك.", + "help.sketch.constraint.symmetry": "يجعل نقطتين أو منحنيين متناظرين حول خط أو نقطة. استخدمه للحفاظ على تناظر المقطع عند تغيير أحد جانبيه.", + "help.sketch.constraint.tangent": "يجعل منحنيين يتماسان مماسيًا، مثل خط وقوس. استخدمه لوصلات ناعمة بلا التواء.", + "help.sketch.construction": "يبدّل المنحنيات بين الهندسة العادية والهندسة الإنشائية التي تتجاهلها المقاطع. استخدم المنحنيات الإنشائية مساعدات للتخطيط والمراجع والأبعاد.", "help.sketch.construction_line": "أنشئ خطًا إنشائيًا لا نهائيًا يمر بنقطتين. استخدمه لتخطيط الرسم دون تقسيم مقاطعه.", "help.sketch.construction_line.angle": "أنشئ خطًا إنشائيًا لا نهائيًا بزاوية من محور X للرسم. اختر النقطة ثم اكتب الزاوية، أو اختر اتجاهه.", "help.sketch.construction_line.bisector": "اختر خطين مستقيمين متقاطعين في الرسم، ثم اختر أحد منصفي الزاوية. يتبع الناتج الخطين اللذين أُنشئ منهما.", @@ -1411,11 +1666,71 @@ "help.sketch.construction_line.tangent_external": "اختر دائرة أو قوسًا دائريًا، ثم نقطة خارجية وحل المماس. تعرض المعاينة نقاط التماس الواقعة على القوس المرسوم فقط.", "help.sketch.construction_line.tangent_two": "اختر دائرتين أو قوسين دائريين ثم اختر مماسًا مشتركًا من المعاينة. يجب أن تقع نقطتا التماس على المنحنيين المرسومين.", "help.sketch.construction_line.vertical": "أنشئ خطًا إنشائيًا رأسيًا لا نهائيًا يمر بنقطة. يحافظ القيد الرأسي على الاتجاه بعد التعديلات.", - "help.sketch.equation_curve": "يرسم منحنى من صيغ على مدى: x(t) و y(t)، أو y = f(x). يمكن أن تستخدم الصيغ المعلمات فيتبعها المنحنى: استخدمه لموجة جيبية أو لولب أو منحنى انفلات لسن ترس.", + "help.sketch.copy": "ينسخ منحنيات الرسم ونقاطه المحددة مع القيود والأبعاد بينها. الصقها في هذا الرسم أو في رسم آخر.", + "help.sketch.create": "يبدأ رسمًا ثنائي الأبعاد جديدًا على مستوى أو على وجه مسطح من النموذج. يبدأ كل بثق ودوران وكنس برسم.", + "help.sketch.cut": "ينسخ هندسة الرسم المحددة ويحذفها من الرسم بخطوة تراجع واحدة. الصقها في مكان آخر من هذا الرسم أو في رسم آخر.", + "help.sketch.dimension": "يضيف بُعدًا حاكمًا: طولًا أو مسافة أو زاوية أو نصف قطر أو قطرًا بحسب ما تختاره. اكتب قيمة أو اسم معامل فيتبعها الرسم.", + "help.sketch.edit": "يفتح رسمًا موجودًا للتعديل. تتحدّث الميزات المبنية عليه عند إنهاء الرسم.", + "help.sketch.ellipse": "يرسم قطعًا ناقصًا من مركزه ونهاية محوره الأكبر ونقطة على جانبه الأصغر. استخدمه للفتحات البيضاوية والكامات وغيرها من الأشكال المستديرة المتطاولة.", + "help.sketch.equation_curve": "يرسم منحنى من صيغ على مدى: x(t) و y(t)، أو y = f(x). يمكن أن تستخدم الصيغ المعاملات فيتبعها المنحنى: استخدمه لموجة جيبية أو لولب أو منحنى انفلات لسن ترس.", + "help.sketch.extend": "يمدد خطًا أو قوسًا حتى أقرب منحنى في طريقه، أو ينمّي منحنيين حتى يلتقيا. استخدمه لسد الفجوات في المقطع بعد القص أو التعديل.", + "help.sketch.fillet": "يقوّس الزاوية التي يلتقي فيها خطان أو قوسان بقوس ذي نصف قطر محدد. الزوايا المقوّسة معًا تشترك في نصف قطر واحد.", + "help.sketch.finish": "يغادر الرسم ويعود إلى النموذج. تصبح مقاطعه المغلقة جاهزة للبثق والدوران وغيرهما من الميزات.", + "help.sketch.finish_auto_constrain": "يشغّل «تقييد تلقائي» على الرسم ثم ينهيه. استخدمه لترك الرسم محددًا بالكامل بخطوة واحدة.", + "help.sketch.fit_curves_to_section": "يقطع شبكة أو جسمًا صلبًا بمستوى الرسم ويلائم خطوطًا وأقواسًا مع المقطع. استخدمه لإعادة بناء قطعة ممسوحة أو مستوردة كرسم قابل للتعديل.", + "help.sketch.include_3d": "يجلب حواف النموذج ورؤوسه ومنحنيات رسوم أخرى إلى هذا الرسم كمراجع مرتبطة، ويسطّح ما هو خارج مستواه عليه. استخدمه للبناء على هندسة لا تقع في مستوى الرسم.", + "help.sketch.infinite": "يبدّل الخطوط بين خطوط عادية وخطوط إنشائية لا نهائية تمتد عبر العرض كله. استخدمها مراجع للتخطيط لا تقصر عن الحاجة أبدًا.", + "help.sketch.insert_dxf": "يقرأ منحنيات مخطط DXF إلى رسم بالمقياس والدوران والموضع الذي تحدده. استخدمه للبناء على مخطط ثنائي الأبعاد من برنامج آخر، مثل محيط للقطع بالليزر.", + "help.sketch.insert_svg": "يقرأ مسارات مخطط SVG إلى رسم بالمقياس والدوران والموضع الذي تحدده. استخدمه لتحويل شعار أو محيط متجهي إلى منحنيات يمكنك بثقها.", + "help.sketch.inspect": "يفتح تقريرًا عن الرسم المفتوح: عدد درجات الحرية المتبقية وهل هو مقيد بالكامل. استخدمه لمعرفة ما لا يزال يتحرك قبل إنهاء الرسم.", + "help.sketch.intersect": "يضيف المنحنيات أو النقاط التي تقطع فيها أجسام أو أوجه أو حواف أو رسوم أخرى مستوى الرسم. تبقى مرتبطة وتتبع النموذج عندما يتغير.", + "help.sketch.intersection_curve": "ينشئ منحنيات ثلاثية الأبعاد حيث يلتقي جسمان أو وجهان، مرتبطة بهما. استخدمها مسارات أو قضبان توجيه تتبع النموذج.", + "help.sketch.isoparametric_curve": "ينشئ منحنى ثلاثي الأبعاد على اتجاه U أو V للوجه عبر نقطة تختارها، مرتبطًا بالوجه. استخدمه مسارًا أو خط تقسيم يتبع السطح.", + "help.sketch.line": "يرسم خطوطًا متصلة نقطة بنقطة، كسلسلة مفتوحة أو محيط مغلق. هو الأداة الأساسية لمعظم المقاطع.", + "help.sketch.line.midpoint": "يرسم خطًا من منتصفه إلى أحد طرفيه، ويعكس الطرف الآخر. استخدمه للخطوط المتمركزة على نقطة، مثل حافة متناظرة.", + "help.sketch.line3d": "يرسم خطوطًا مستقيمة متصلة بين نقاط في الفراغ، مع تفعيل الرسم ثلاثي الأبعاد. استخدمه للمسارات والإطارات الخارجة عن مستوى الرسم.", + "help.sketch.mirror": "يعكس منحنيات الرسم ونقاطه حول خط أو محور ويضيف قيود تناظر. استخدمه لرسم نصف مقطع متناظر ثم إكماله.", + "help.sketch.move": "يحرّك منحنيات الرسم ونقاطه أو يدوّرها، أو يفعل ذلك بنسخة منها. استخدمه لإعادة وضع الهندسة مع الحفاظ على شكلها وقيودها.", + "help.sketch.offset": "ينشئ نسخة من سلسلة منحنيات على مسافة محددة، من جانب واحد أو من الجانبين. استخدمه للجدران والمحيطات والخلوصات؛ وتبقى المسافة بُعدًا قابلًا للتعديل.", + "help.sketch.paste": "يلصق في الرسم النشط هندسة رسم نسختها أو قصصتها. ضعها عند نقطة أو أزحها بمقدار.", + "help.sketch.pattern.circular": "ينسخ هندسة الرسم حول نقطة مركز، على دائرة كاملة أو زاوية محددة. استخدمه لدوائر البراغي والأذرع والأسنان.", + "help.sketch.pattern.rectangular": "ينسخ هندسة الرسم في صفوف وأعمدة بمسافات محددة. استخدمه لشبكات الثقوب والشقوق وفتحات التهوية.", + "help.sketch.point": "يضع نقطة رسم. استخدمها مرجعًا للأبعاد والقيود ومراكز الثقوب أو الميزات اللاحقة.", + "help.sketch.point3d": "يضع نقطة في الفراغ، مع تفعيل الرسم ثلاثي الأبعاد. استخدمها مرجعًا للمنحنيات والمسارات الثلاثية الأبعاد.", + "help.sketch.polygon.circumscribed": "يرسم مضلعًا منتظمًا حول دائرة، بحجم يُحدد من مركزها إلى منتصف ضلع. استخدمه عندما يكون العرض بين الضلعين المتقابلين معروفًا، كما في صامولة سداسية.", + "help.sketch.polygon.edge": "يرسم مضلعًا منتظمًا من طرفي ضلع واحد. استخدمه عندما يكون طول الضلع وموضعه معروفين.", + "help.sketch.polygon.inscribed": "يرسم مضلعًا منتظمًا داخل دائرة، بحجم يُحدد من مركزها إلى أحد رؤوسه. استخدمه عندما يكون البعد بين الرأسين المتقابلين معروفًا.", + "help.sketch.project": "يجلب حواف النموذج وأوجهه ورؤوسه ومنحنيات رسوم أخرى إلى هذا الرسم، مسقطة على مستواه. تبقى مرتبطة وتتبع النموذج عندما يتغير.", + "help.sketch.project_to_surface": "يسقط منحنيات رسوم أخرى على وجه في اتجاه العمودي على مستوى هذا الرسم، كمنحنيات ثلاثية الأبعاد مرتبطة. استخدمه لوضع شعار أو خط تقسيم أو مسار على سطح منحنٍ.", + "help.sketch.rectangle.center": "يرسم مستطيلًا من مركزه وأحد أركانه. استخدمه للمحيطات المتمركزة على نقطة، مثل نقطة الأصل.", + "help.sketch.rectangle.rounded": "يرسم مستطيلًا بأركان أربعة مدوّرة بنصف قطر واحد. استخدمه للألواح والأغطية والفتحات ذات الأركان المدوّرة.", + "help.sketch.rectangle.three_point": "يرسم مستطيلًا من حافة واحدة ونقطة على الجانب المقابل. استخدمه للمستطيلات المائلة عن محاور الرسم.", + "help.sketch.rectangle.two_point": "يرسم مستطيلًا من ركنين متقابلين. استخدمه لمحيطات الألواح والكتل والجيوب.", + "help.sketch.scale": "يغيّر مقياس منحنيات الرسم ونقاطه بمعامل حول نقطة أساس. استخدمه لتغيير حجم جزء من الرسم دون إعادة رسمه.", + "help.sketch.slot.arc_center": "يرسم شقًا منحنيًا بعرض محدد على امتداد قوس يُحدد بمركزه وبدايته ونهايته. استخدمه لشقوق الضبط حول محور.", + "help.sketch.slot.arc_three_point": "يرسم شقًا منحنيًا بعرض محدد على امتداد قوس يمر بثلاث نقاط. استخدمه عندما يجب أن يمر مسار الشق بنقاط محددة.", + "help.sketch.slot.center_point": "يرسم شقًا مستقيمًا بعرض محدد من مركزه إلى مركز قوس أحد طرفيه. استخدمه للشقوق المتمركزة على نقطة.", + "help.sketch.slot.center_to_center": "يرسم شقًا مستقيمًا بعرض محدد بين مركزي قوسي طرفيه. استخدمه للشقوق المقيّسة من مركز إلى مركز، مثل شقوق ضبط البراغي.", + "help.sketch.slot.overall": "يرسم شقًا مستقيمًا بعرض محدد من طرفه الخارجي إلى الطرف الآخر. استخدمه عندما يكون الطول الكلي للشق هو المهم.", + "help.sketch.spline.control_point": "يرسم منحنى شريحيًا تكعيبيًا يتشكل بنقاط تحكم لا يمر بها. استخدمه للمنحنيات الناعمة المنسابة التي تشكلها بتحريك النقاط.", + "help.sketch.spline.control_point_5": "يرسم منحنى شريحيًا من الدرجة 5 يتشكل بنقاط تحكم. استخدمه حيث يجب أن تلتقي المنحنيات بانحناء أنعم، مثلًا على الأسطح الظاهرة ذات التصميم الانسيابي.", + "help.sketch.spline.fit_point": "يرسم منحنى شريحيًا ناعمًا يمر بكل نقطة تضعها، مفتوحًا أو مغلقًا. استخدمه لتتبع شكل عبر نقاط معروفة.", + "help.sketch.spline3d": "يرسم منحنى ناعمًا في الفراغ عبر نقاط، مع تفعيل الرسم ثلاثي الأبعاد. استخدمه لمسارات الكنس ومسارات الكابلات الخارجة عن مستوى الرسم.", + "help.sketch.spun_profile": "ينشئ في مستوى الرسم المحيط الذي يمسحه جسم عند دورانه حول محور. استخدمه للحصول على صورة ظلية لقطعة مشغولة بالخراطة من أجل أمر «دوران» أو مخطط.", + "help.sketch.text": "يكتب نصًا في الرسم بخط وارتفاع وزاوية تختارها، ويمكن لكلماته أن تتبع المعاملات. ابثقه أو حوّله إلى نقش بارز للملصقات والكتابة.", + "help.sketch.transform": "يغيّر مقياس هندسة الرسم ويدوّرها ويحرّكها حول نقطة مركز بخطوة واحدة. استخدمه لإعادة وضع تحديد وتغيير حجمه معًا.", + "help.sketch.trim": "يزيل الجزء من المنحنى بين أقرب نقطتي تقاطع حول موضع نقرتك. استخدمه لتنظيف الخطوط المتداخلة وتحويلها إلى مقطع مغلق.", "help.solid.align": "يحرّك الأجسام المحددة بحيث تلتقي نقطة أو وجه أو مستوى منها بنقطة أو وجه أو مستوى في مكان آخر. استخدمه لوضع قطعة ملاصقة لأخرى دون قياس المسافة.", + "help.solid.boundary_fill": "ينشئ أجسامًا صلبة من المناطق التي تحيط بها أجسام أدوات متداخلة، مع تعبئة المناطق التي تختارها فقط. استخدمه لبناء شكل من الحيز الذي تحدّه عدة أجسام معًا.", + "help.solid.bounding_solid": "ينشئ صندوقًا يحيط بالأجسام المحددة، مع هامش اختياري. استخدمه لمعرفة الأبعاد الكلية لقطعة أو كخامة أولية تُشغّل منها.", + "help.solid.box": "ينشئ صندوقًا بطول وعرض وارتفاع، انطلاقًا من نقطة ركن أو متمركزًا حول نقطة. استخدمه لإنشاء كتلة سريعة أو شكل مؤقت أو جسم تُقطع فيه ميزات.", "help.solid.chamfer": "يقطع الحواف المحددة بشطفة مستوية بالمسافة التي تحددها. استخدمه لكسر الحواف الحادة أو لتسهيل إدخال مسمار أو برغي.", + "help.solid.coil": "ينشئ جسمًا حلزونيًا مثل النابض من قطر وعدد لفات وارتفاع أو خطوة، وبمقطع دائري أو مربع. استخدمه للنوابض والملفات والنتوءات الحلزونية.", "help.solid.combine": "يضم الأجسام، أو يقتطعها من جسم هدف، أو يُبقي الحجم المشترك بينها فقط، ويمكنه الاحتفاظ بأجسام الأداة. استخدمه لدمج القطع، أو لقطع شكل بشكل آخر، أو لمعرفة موضع تداخل جسمين.", + "help.solid.cone": "ينشئ مخروطًا من دائرة قاعدة وارتفاع، أو مخروطًا ناقصًا عند تحديد نصف قطر للقمة أيضًا. استخدمه للأشكال المستدقة والقمع والتجاويف المخروطية والرؤوس المدببة.", + "help.solid.cylinder": "ينشئ أسطوانة بنصف قطر أو قطر وارتفاع، قائمة عند نقطة على امتداد محور. استخدمه للأعمدة والدبابيس والنتوءات الدائرية والخامات الأسطوانية.", "help.solid.draft": "يميل الأوجه المحددة بالزاوية التي تحددها، مقيسةً من مستوى محايد. استخدمه في القطع المقولبة أو المصبوبة كي تخرج من القالب بسهولة.", + "help.solid.emboss": "يبرز مقاطع رسم مثل نص أو شعار من وجه، أو يغورها فيه. استخدمه للكتابات والتسميات والعلامات على الوجوه المستوية أو المستديرة.", "help.solid.extrude": "يدفع مقطع رسم إلى ثلاثي الأبعاد على مسافة محددة، بإضافة مادة أو إزالتها. استخدمه لتحويل مخطط مسطح إلى كتلة أو نتوء أو تجويف.", "help.solid.fillet": "يقوّس الحواف المحددة بانحناء دائري ناعم بنصف القطر الذي تحدده. استخدمه لتنعيم الحواف الحادة من أجل المتانة أو الراحة أو المظهر.", "help.solid.hole": "يحفر ثقبًا دائريًا بالقطر الذي تحدده عند نقطة مختارة على وجه. استخدمه لفتحات البراغي والمسامير والفتحات الدائرية البسيطة الأخرى.", @@ -1424,20 +1739,61 @@ "help.solid.move": "يحرّك الأجسام المحددة أو يدوّرها، أو نسخة منها، بالمسافة والزاوية اللتين تحددهما. استخدمه لتغيير موضع جسم أو لإنشاء جسم ثانٍ في مكان آخر.", "help.solid.offset_face": "يدفع الأوجه المحددة إلى الداخل أو الخارج بالمسافة التي تحددها، وتتبعها الأوجه المحيطة. استخدمه لزيادة سماكة جدار أو عمق جيب أو ارتفاع نتوء دون تعديل الرسم.", "help.solid.pattern.circular": "يكرر العناصر المحددة حول محور، بالعدد والزاوية الكلية اللذين تحددهما. استخدمه لدوائر البراغي والأذرع والزعانف والأسنان.", + "help.solid.pattern.path": "ينسخ ميزات أو أجسامًا على امتداد مسار رسم، بالعدد والتباعد. استخدمه لثقوب على حافة منحنية أو قطع على سكة.", "help.solid.pattern.rectangular": "يكرر العناصر المحددة في اتجاه واحد أو اتجاهين بالعدد والتباعد اللذين تحددهما. استخدمه لصفوف الثقوب والأضلاع والمسامير والأرجل وشبكاتها.", + "help.solid.pipe": "ينشئ أنبوبًا دائريًا على مسار من منحنيات الرسم، مصمتًا أو مجوفًا بسماكة جدار محددة. استخدمه للأنابيب والأسلاك والكابلات والقضبان.", "help.solid.press_pull": "يضيف المادة أو يزيلها حين تسحب وجهًا، أو يقوّس الحواف حين تسحبها. استخدمه لإجراء تعديلات سريعة على النموذج مباشرة.", "help.solid.remove": "يُخرج الأجسام المحددة من التصميم بدءًا من هذه النقطة في السجل، وتحتفظ بها الخطوات السابقة. استخدمه للتخلص من جسم مساعد، مثل أداة قطع لم تعد تحتاجها.", "help.solid.replace_face": "ينقل الأوجه المستوية المحددة إلى مستوى أو إلى وجه موازٍ، فيطول الجسم أو يقصر ليبلغه. استخدمه لجعل وجه مستويًا مع قطعة أخرى أو مع مستوى إنشائي.", "help.solid.revolve": "يدير مقطع رسم حول محور لصنع جسم دائري. استخدمه للأعمدة والمقابض والأوعية وأي قطعة دائرية حول خط مركزي.", + "help.solid.rib": "يضيف ضلع تقوية رقيقًا على امتداد منحنى رسم مفتوح، ممتدًا حتى الوجوه التالية للجسم. استخدمه لتقوية الجدران والزوايا، مثلًا في القطع المقولبة أو المطبوعة.", "help.solid.scale": "يكبّر الأجسام المحددة أو يصغّرها بمعامل، متساوٍ في كل الاتجاهات أو مختلف لكل محور. استخدمه لتغيير حجم شكل مستورد أو لحساب الانكماش.", "help.solid.shell": "يفرّغ الجسم الصلب تاركًا جدرانًا بالسماكة التي تحددها، ويمكنه فتح الأوجه التي تختارها. استخدمه للصناديق والأغطية والقطع الأخرى رقيقة الجدران.", + "help.solid.sphere": "ينشئ كرة بنصف قطر أو قطر حول نقطة مركز. استخدمه للكرات والمقابض والنهايات المستديرة.", "help.solid.split_body": "يقسم جسمًا إلى أجسام منفصلة بمستوى أو بوجه جسم آخر أو بخط من رسم. استخدمه لصنع قطع تُطبع أو تُشغَّل أو تُلوَّن كلٌّ على حدة.", "help.solid.split_face": "يقسم الأوجه المحددة على طول مستوى أو وجه جسم آخر أو منحنيات رسم، دون قطع الجسم. استخدمه لإعطاء جزء من وجه ميلًا أو لونًا أو إزاحة خاصة به.", "help.solid.sweep": "يسحب مقطع رسم على طول مسار لصنع جسم صلب. استخدمه للأنابيب والقضبان والمقابض وأي قطعة ثابتة المقطع تتبع منحنى.", + "help.solid.thread": "يضيف قلاوظًا متريًا بمعيار ISO إلى وجه أسطواني، إما كتمثيل شكلي أو محفورًا في الجسم. استخدمه للبراغي والثقوب الملولبة والقطع اللولبية المطبوعة.", + "help.solid.torus": "ينشئ حلقة بنصف قطر رئيسي حول محورها ونصف قطر ثانوي لمقطعها الدائري. استخدمه لحلقات منع التسرب والمقابض والنتوءات الحلقية المستديرة.", + "help.solid.web": "يضيف جسر تقوية رقيقًا على امتداد كل منحنى رسم مفتوح، يمتد كل منها حتى الوجوه التالية للجسم. استخدمه لإنشاء شبكة من الجدران الداعمة داخل الأغلفة والصواني.", + "help.surface.blend": "ينشئ سطحًا يصل بين حواف جسمين، مماسًّا أو متصل الانحناء مع كليهما. استخدمه لوصل سطحين بنعومة عبر فجوة.", + "help.surface.boundary": "ينشئ سطحًا يملأ حلقة من منحنيين إلى أربعة منحنيات رسم، أو شبكة من المنحنيات. استخدمه للوحات حرة الشكل تحددها حوافها.", + "help.surface.extend": "يمدّد سطحًا إلى ما بعد حوافه، بمسافة أو حتى مستوى أو وجه. استخدمه لكي تتداخل الأسطح قبل القص أو الخياطة.", + "help.surface.extrude": "يدفع منحنيات أو مقاطع رسم مسافة محددة لتكوين سطح، جدران فقط بلا أغطية. استخدمه للجدران الرقيقة وأدوات القطع أو التقسيم.", + "help.surface.fair": "ينعّم داخل الأوجه حرة الشكل مع بقاء حوافها ثابتة. استخدمه لتسوية النتوءات والانعكاسات المتموجة في السطح.", + "help.surface.loft": "ينشئ سطحًا يمر عبر مقطعين أو أكثر بالترتيب، بلا أغطية. استخدمه للأغلفة والانتقالات بين أشكال مختلفة.", + "help.surface.match": "يعيد بناء حافة سطح لتلتقي بحافة جسم آخر، بمماسية أو انحناء متطابق. استخدمه لإغلاق درزة بنعومة بين سطحين.", + "help.surface.offset": "ينشئ نسخة من الأوجه على مسافة على امتداد اتجاهاتها العمودية، كجسم سطحي جديد. استخدمه للأغلفة أو الخلوصات أو الجانب الآخر من جدار.", + "help.surface.patch": "يملأ منطقة رسم أو حلقة مغلقة من الحواف بوجه، مسطح أو منحنٍ بنعومة. استخدمه لسدّ الثقوب في جسم سطحي.", + "help.surface.reverse_normal": "يقلب أوجه جسم سطحي بحيث يتجه سطحها الخارجي إلى الجهة الأخرى. استخدمه قبل التثخين أو الخياطة حين تتجه الأوجه إلى الداخل.", + "help.surface.revolve": "يدير منحنيات أو مقاطع رسم حول محور ليكوّن سطحًا، بلا أغطية. استخدمه للأغلفة المستديرة مثل أباجورات المصابيح والأوعية والفوهات.", + "help.surface.ruled": "ينشئ شريطًا من خطوط مستقيمة ممتدة من سلسلة حواف، باتجاه عمودي الوجه أو مماسه أو بزاوية. استخدمه لجدران الميل وأسطح الامتداد وأسطح الفصل.", + "help.surface.stitch": "يخيط أجسامًا سطحية معًا على امتداد حوافها المشتركة، وتصبح جسمًا صلبًا إذا أغلقت. استخدمه لتحويل مجموعة أسطح إلى جسم واحد.", + "help.surface.sweep": "يحرّك منحنيات أو مقاطع رسم على امتداد مسار لتكوين سطح، بلا أغطية. استخدمه للمزاريب والأشرطة الزخرفية وسائر الأشكال الرقيقة التي تتبع مسارًا.", + "help.surface.thicken": "يمنح جسمًا سطحيًا سماكة ويحوّله إلى جسم صلب. استخدمه لصنع قطع قابلة للطباعة أو التشغيل من الأسطح.", + "help.surface.trim": "يقص سطحًا بمستوى أو سطح آخر أو منحنيات رسم، ويبقي الجانب الذي تختاره. استخدمه لقص الأسطح إلى الشكل المطلوب قبل الخياطة.", + "help.surface.unstitch": "يفصل أوجه جسم إلى أجسام سطحية مستقلة؛ فيتفكك الجسم الصلب إلى أسطح. استخدمه لإعادة العمل على أوجه مفردة من جسم.", + "help.surface.untrim": "يزيل الثقوب من وجه، أو يستعيد حدوده الخارجية إلى الحدود الطبيعية للسطح. استخدمه لاستعادة السطح الكامل بعد القص.", "help.third_party": "رخص الأطراف الثالثة", "help.timeline.compute_all": "يعيد بناء كل ميزة في السجل من البداية. استخدمه لتحديث النموذج ولمعرفة الميزات التي تفشل.", "help.timeline.delete": "يحذف الميزات المحددة من السجل، وحذف رسمٍ يحذف معه الميزات المبنية عليه. استخدمه لإزالة خطوة لم تعد مطلوبة.", + "help.timeline.dependents": "يسرد الميزات التي ستُحذف مع ميزة ما، وتلك التي ستفشل بدونها. استخدمه قبل حذف ميزة أو تغييرها.", "help.timeline.play": "أعد تشغيل الميزات المتبقية واحدة تلو الأخرى، مع توقف لمدة نصف ثانية بعد كل إعادة بناء. شغّل هذا الأمر مرة أخرى أو اضغط Escape للإيقاف؛ ينتقل «الذهاب إلى النهاية» فورًا إلى النهاية.", + "help.version": "الإصدار {version}", + "help.view.apply": "يدير العرض إلى اتجاه قياسي مثل الأمامي أو العلوي أو الأيزومتري، أو إلى عرض مسمّى محفوظ. استخدمه للنظر إلى النموذج من زاوية ثابتة.", + "help.view.delete": "يحذف عرضًا مسمّى محفوظًا. لا يتغير النموذج.", + "help.view.fit": "يضبط التكبير ويُزيح العرض حتى يملأ النموذج كله أو التحديد منطقة العرض. استخدمه حين يخرج النموذج من مجال الرؤية.", + "help.view.grid": "يُظهر الشبكة في منطقة العرض أو يخفيها. استخدمها كدليل للحجم والاتجاه أثناء النمذجة.", + "help.view.ground_shadow": "يُظهر ظل النموذج على الأرض أو يخفيه. استخدمه لتقدير الارتفاع والموضع بسهولة أكبر.", + "help.view.home": "يعيد العرض إلى الاتجاه الرئيسي ويلائم النموذج. استخدمه للعودة سريعًا إلى عرض معروف.", + "help.view.list": "يسرد العروض المسمّاة المحفوظة في التصميم. استخدمه للعثور على عرض حفظته سابقًا.", + "help.view.navigate": "يدير العرض أو يُزيحه أو يغيّر تكبيره بخطوات، مثل ربع دورة إلى اليسار. استخدمه لتحريك الكاميرا بدقة بدلًا من السحب.", + "help.view.navigation_bar": "يُظهر شريط التنقل أسفل منطقة العرض أو يخفيه. أخفِه لمساحة أكبر، وأظهره للوصول إلى أدوات العرض بالفأرة.", + "help.view.rename": "يمنح عرضًا مسمّى محفوظًا اسمًا جديدًا. يبقى العرض نفسه كما هو.", + "help.view.save": "يحفظ موضع الكاميرا الحالي كعرض مسمّى في التصميم. استخدمه للعودة إلى الزاوية نفسها لاحقًا، مثلًا للقطات الشاشة.", + "help.view.spin": "يدوّر العرض حول النموذج باستمرار حتى النقرة أو المفتاح التالي. استخدمه لعرض النموذج من جميع الجهات.", + "help.view.tool": "يثبّت أداة كاميرا، التدوير أو الإزاحة أو التكبير، بحيث يحرّك السحب بزر الفأرة الأيسر العرض حتى توقفها. استخدمه على لوحة اللمس أو بدون زر فأرة أوسط.", + "help.view.visual_style": "يبدّل طريقة رسم النموذج: مظلَّل مع الحواف أو بدونها، أو إطار سلكي، أو مع الحواف المخفية. استخدم الإطار السلكي لرؤية الداخل، والمظلَّل لمظهر نظيف.", "history.sketch_under_constrained": "قيود ناقصة ({count} درجات حرية)", "history.sketch_under_constrained_one": "قيود ناقصة ({count} درجة حرية)", "hole_presets.confirm_delete": "تأكيد الحذف", @@ -1511,6 +1867,27 @@ "home.start_hint": "أنشئ تصميمًا، أو افتح ملفًا حديثًا، أو استكشف مثالًا.", "home.whats_new": "ما الجديد", "home.yesterday": "أمس", + "import_report.details": "التفاصيل:", + "import_report.file_one": "كانت هناك مشكلة أخرى واحدة في الملف.", + "import_report.file_other": "كانت هناك {count} مشكلات أخرى في الملف.", + "import_report.hint": "قد يحل ذلك تصدير هذه الأجزاء مرة أخرى من البرنامج الذي أنشأها. يحتوي «نسخ رسالة التحذير» على التفاصيل.", + "import_report.left_out_one": "تعذّر إصلاح وجه واحد وهو مفقود.", + "import_report.left_out_other": "تعذّر إصلاح {count} أوجه وهي مفقودة.", + "import_report.needs_repair_one": "يحتاج جزء واحد إلى إصلاح قبل النمذجة عليه.", + "import_report.needs_repair_other": "تحتاج {count} أجزاء إلى إصلاح قبل النمذجة عليها.", + "import_report.not_imported_one": "تعذّر استيراد جزء واحد.", + "import_report.not_imported_other": "تعذّر استيراد {count} أجزاء.", + "import_report.not_shown_one": "تعذّر رسم وجه واحد وهو مخفي.", + "import_report.not_shown_other": "تعذّر رسم {count} أوجه وهي مخفية.", + "import_report.open_one": "في جزء واحد فجوات بين أوجهه، فاستُورد كجسم مفتوح.", + "import_report.open_other": "في {count} أجزاء فجوات بين أوجهها، فاستُوردت كأجسام مفتوحة.", + "import_report.refused_one": "تعذّر تحويل جزء واحد إلى مجسم، فلم يُستورد.", + "import_report.refused_other": "تعذّر تحويل {count} أجزاء إلى مجسمات، فلم تُستورد.", + "import_report.repaired_one": "أُصلحت عيوب صغيرة في جزء واحد.", + "import_report.repaired_other": "أُصلحت عيوب صغيرة في {count} أجزاء.", + "import_report.solids": "استُورد {solids} من {parts} أجزاء كمجسمات.", + "import_report.surfaces_one": "تعذّر تحويل جزء واحد إلى مجسم، فاستُورد كأسطح.", + "import_report.surfaces_other": "تعذّر تحويل {count} أجزاء إلى مجسمات، فاستُوردت كأسطح.", "install.button_tip": "ثبّت SolidCraft كتطبيق: يُفتح في نافذته الخاصة ويعمل دون اتصال", "install.dock_1": "اختر ملف › إضافة إلى Dock.", "install.dock_2": "انقر إضافة.", @@ -1535,26 +1912,39 @@ "issue.note_save_failed": "تعذّر حفظ لقطة الشاشة: {error}", "issue.note_saved": "حُفظت لقطة الشاشة. أرفق ملف PNG في مسودة GitHub.", "issue.save_screenshot": "حفظ لقطة الشاشة…", + "joint.find_limits": "إيجاد الحدود", + "joint.find_limits_failed": "توقف البحث عن الحدود بسبب خطأ", + "joint.find_limits_hint": "يملأ الحدود من الموضع الذي تلمس فيه القطع التي يحرّكها هذا المفصل قطعةً أخرى لأول مرة، بالدوران أو الانزلاق في الاتجاهين من موضعه الحالي. يجري البحث على نسخة: لا يتغيّر شيء حتى الضغط على OK.", + "joint.find_limits_stale": "تغيّر المفصل أو التصميم منذ إيجاد هذه الحدود: ابحث عنها مرة أخرى", + "joint.finding_limits": "جارٍ إيجاد الحدود…", "joint.from_bodies_hint": "ينتقل كل جسم مختار إلى مكوّن جديد خاص به ويبقى في مكانه.", + "joint.limit_contact": "{side} {value}: {a} يلمس {b}", + "joint.limit_limit": "{side} {value}: حدّ قيمة أخرى أو مفصل آخر", + "joint.limit_loop": "{side} {value}: لا يمكن لحلقة مغلقة أن تنغلق بعده", + "joint.limit_range": "{side}: لا تلامس ضمن {range}، تُرك كما كان", + "joint.limit_turn": "{side} {value}: لا تلامس ضمن دورة واحدة", + "joint.limits_overlapping": "متداخلة بالفعل هنا: {pairs}. لا توقف البحث إلا إذا ازداد تداخلها.", "joint.one_body": "كلا الاختيارين على {body}. اختر الثاني على قطعة أخرى.", "joint.one_component": "هذه القطع أجسام لمكوّن واحد: {bodies}. المفصل يحرّك مكوّنًا مقابل آخر، لذا تحتاج كل قطعة إلى مكوّن خاص بها.", "joint.rigid_group_one_component": "هذه الأجسام وعددها {count} كلها في مكوّن واحد (أو في التصميم نفسه): استخدم {command} أولًا.", "joint.rigid_group_select_components": "اختر مكوّنين أو أكثر.", - "joint_move.blocked_hint": "تحقق من نوع المفصل (مثل المفصل الثابت)، وتثبيت الجزء، وحدود المفصل، والقيم التي تتحكم بها المعلمات.", + "joint_move.blocked_hint": "تحقق من نوع المفصل (مثل المفصل الثابت)، وتثبيت الجزء، وحدود المفصل، والقيم التي تتحكم بها المعاملات.", "joint_move.blocked_title": "لا يمكن تحريك هذا الجزء", - "joint_move.coarse": "خطوة الدوران قرب المحور (°)", + "joint_move.coarse": "الخطوة قرب المحور", + "joint_move.conflict": "يتعارض أحد مفاصل هذا الجزء مع المفاصل الأخرى: {joint}.", + "joint_move.conflict_hint": "عدّل المفصل المتعارض أو عطّله أو احذفه حتى تتمكن المفاصل الأخرى من وضع الجزء.", "joint_move.distance": "المسافة من نقطة البداية", "joint_move.done": "تم", - "joint_move.fine": "خطوة الدوران بعيدًا عن المحور (°)", + "joint_move.fine": "الخطوة بعيدًا عن المحور", "joint_move.fixed": "لا يملك هذا الجزء محور مفصل قابلًا للحركة.", "joint_move.help": "تحريك — اسحب سهمًا أو قوسًا. يلغى السحب الحالي بمفتاح Esc.", - "joint_move.legacy_hint": "أوقف هذا الخيار لاستخدام لوحة التحريك السابقة.", - "joint_move.precision": "اسحب خارج الدليل المتقطع لضبط الدوران بدقة.", + "joint_move.legacy_hint": "عند الإيقاف: لوحة التحريك السابقة.", + "joint_move.precision": "اسحب خارج الدليل المتقطع للخطوة الدقيقة.", "joint_move.rotation": "الدوران من نقطة البداية", "joint_move.select": "اختر وجهًا أو جزءًا واحدًا من التجميع، ثم اختر تحريك.", "joint_move.settings": "تحريك التجميع", "joint_move.step": "الخطوة", - "joint_move.use_handles": "استخدام مقابض حركة المفاصل لتحريك التجميع", + "joint_move.use_handles": "استخدام مقابض حركة المفاصل للتحريك", "keymap.command_id": "معرّف الأمر", "keymap.empty": "لا توجد أوامر مطابقة", "keymap.use_anyway": "استخدام {key} هنا على أي حال", @@ -1614,6 +2004,11 @@ "material.selection.mixed": "مواد مختلفة", "measure.at": "عند", "measure.item": "العنصر {number}", + "measure.line_to_centre": "من الخط إلى المركز", + "measure.quick_copied": "تم نسخ القياس", + "measure.quick_copy": "انقر لنسخ القياس", + "measure.quick_edges": "{count} حواف", + "measure.quick_faces": "{count} أوجه", "messages.ago_h": "قبل {n} ساعة", "messages.ago_min": "قبل {n} دقيقة", "messages.ago_s": "قبل {n} ث", @@ -1638,6 +2033,8 @@ "motion.track_name": "المسار {number}", "nav.alias.help": "Shift+Alt مع السحب بالزر الأيسر يدوّر العرض، وShift+Alt مع الأوسط يُزيحه، وShift+Alt مع الأيمن يكبّره؛ والسحب بالزر الأوسط يُزيح أيضًا والسحب بالأيمن يدوّر", "nav.blender.help": "السحب بالزر الأوسط يدوّر العرض، وShift مع الأوسط يُزيحه، وCtrl مع الأوسط يكبّره؛ والسحب بالأيمن لا يحرك الكاميرا", + "nav.creo.help": "السحب بالزر الأوسط يدوّر العرض، وShift مع الأوسط يُزيحه، وCtrl مع السحب العمودي بالأوسط يكبّره أو يصغّره (السحب لأسفل للتكبير)؛ وتدوير العجلة يكبّره أو يصغّره", + "nav.creo.label": "Creo", "nav.free_orbit.help": "الفأرة والفأرة ثلاثية الأبعاد تدوّران العرض عبر القطبين وتحافظان على اللف. يُعطَّل التقاط المحاور بـ Shift.", "nav.free_orbit.label": "تدوير حر", "nav.free_orbit.snap_help": "الفأرة والفأرة ثلاثية الأبعاد تدوّران العرض عبر القطبين وتحافظان على اللف. اضغط مطولًا على Shift أثناء سحب التدوير لالتقاط اتجاه العرض واللف.", @@ -1647,6 +2044,7 @@ "nav.hfss.help": "Alt مع السحب بالزر الأيسر يُزيح العرض، وShift+Alt مع الأيسر يكبّره، وCtrl مع السحب بالأيسر من مساحة فارغة يدوّره", "nav.inventor.help": "السحب بالزر الأوسط يُزيح العرض، وShift مع الأوسط يدوّره، وCtrl مع الأوسط يكبّره، والسحب بالأيمن يدوّره", "nav.maya.help": "Alt مع السحب بالزر الأيسر يدوّر العرض، وAlt مع الأوسط يُزيحه، وAlt مع الأيمن يكبّره؛ والسحب بالزر الأوسط يُزيح أيضًا", + "nav.nx.help": "السحب بالزر الأوسط يدوّر العرض، وShift مع الأوسط يُزيحه (في NX: الأوسط مع الأيمن)، وCtrl مع الأوسط يكبّره (في NX: الأوسط مع الأيسر)؛ والسحب بالأيمن لا يحرك الكاميرا", "nav.openscad.help": "السحب بالزر الأيسر على مساحة فارغة يدوّر العرض، وShift مع السحب بالأيسر يحدد بمربع، وسحب هندسة الرسم يعدّلها؛ والسحب بالأيمن أو الأوسط يُزيح، وShift مع السحب بالأيمن أو الأوسط يكبّر", "nav.perspective.sketch": "تحرير الرسم يستخدم العرض المتعامد. أنهِ الرسم للتبديل إلى المنظور.", "nav.right_drag_orbits.help": "عند الإيقاف: لا يحرّك السحب بالزر الأيمن الكاميرا، ويفتح الزر الأيمن قائمة السياق فقط. اختيار تعيين أزرار الفأرة SolidWorks يوقفه.", @@ -1665,6 +2063,12 @@ "navbar.assistant": "المساعد", "navbar.custom.add_slot": "إضافة {slot}", "navbar.custom.always": "ظاهر دائمًا", + "navbar.custom.anchor.bottom_centre": "أسفل الوسط", + "navbar.custom.anchor.bottom_left": "أسفل اليسار", + "navbar.custom.anchor.bottom_right": "أسفل اليمين", + "navbar.custom.anchor.top_centre": "أعلى الوسط", + "navbar.custom.anchor.top_left": "أعلى اليسار", + "navbar.custom.anchor.top_right": "أعلى اليمين", "navbar.custom.available": "{available} · اسحبها إلى الشريط، أو اضغط إضافة", "navbar.custom.buttons": "الأزرار", "navbar.custom.compact": "مضغوط", @@ -1701,6 +2105,7 @@ "navbar.custom.reset_default": "إعادة الضبط إلى الافتراضي", "navbar.custom.right": "نقل إلى اليمين", "navbar.custom.select": "لم يتم تحديد أي خانة. حدّد خانة على الشريط لنقلها أو إزالتها أو تغيير مظهرها.", + "navbar.custom.separator_hint": "فاصل بين مجموعات الأزرار. اسحبه إلى الشريط، أو اضغط على إضافة؛ يمكنك استخدام أي عدد من الفواصل.", "navbar.custom.separators_full": "يحتوي الشريط بالفعل على أربعة فواصل.", "navbar.custom.show": "إظهار شريط التنقل", "navbar.custom.shows": "يعرض", @@ -1766,6 +2171,11 @@ "not a move": "ليس تحريكًا", "not a number": "ليس عددًا", "open a sketch first": "افتح رسمًا أولًا", + "parameters.apply_live": "تطبيق كل تغيير عند مغادرة حقله", + "parameters.apply_live_tip": "عند الإيقاف: تنتظر التغييرات حتى «تطبيق» أو «موافق»، ثم يُعاد بناء التصميم مرة واحدة لها جميعًا. «إلغاء» أو Escape يلغيها.", + "parameters.held": "{count} تغييرات بانتظار «تطبيق»", + "parameters.held_hint": "عدّل التعابير والوحدات. تنتظر التغييرات «تطبيق» أو «موافق».", + "parameters.held_one": "تغيير واحد بانتظار «تطبيق»", "parts.automatic_name": "تلقائي", "parts.dimension.across_flats": "مقاس المفتاح", "parts.dimension.bore": "قطر الثقب", @@ -1784,10 +2194,19 @@ "parts.family.button_head_cap_screw": "برغي برأس زرّي بتجويف سداسي", "parts.family.dowel_pin": "مسمار توجيه أسطواني", "parts.family.hex_bolt": "برغي سداسي الرأس", + "parts.family.hex_cap_screw_inch": "برغي سداسي الرأس (بوصة)", "parts.family.hex_nut": "صامولة سداسية", + "parts.family.hex_nut_inch": "صامولة سداسية (بوصة)", "parts.family.set_screw": "برغي تثبيت بتجويف سداسي، طرف مسطح", "parts.family.socket_head_cap_screw": "برغي برأس أسطواني بتجويف سداسي", "parts.family.washer": "حلقة مسطحة", + "parts.family.washer_sae": "حلقة مسطحة، SAE (ضيقة)", + "parts.family.washer_uss": "حلقة مسطحة، USS (عريضة)", + "parts.holes": "الثقوب (اختياري)", + "parts.placement_hint": "اختر ثقبًا أو أكثر لتثبيت قطعة في كل منها، أو اضغط موافق لوضعها عند نقطة الأصل", + "parts.system": "نظام الوحدات", + "parts.system.inch": "بوصة", + "parts.system.metric": "متري", "pattern.alignment_2": "المحاذاة 2", "pattern.alignment_hint": "العدد يشمل الأصل. «توسيط» يوازن النسخ؛ و«قلب» يختار الجانب الإضافي عندما يكون العدد زوجيًا.", "pattern.direction_1": "الاتجاه 1", @@ -1826,20 +2245,52 @@ "prefs.alt_frees_manipulators": "Alt / Option يحرر أسهم أدوات التحريك أيضًا", "prefs.anti_aliasing_amd_dx12": "يستخدم تنعيم الحواف 1× لأن فحص بدء التشغيل لم يرسم شيئًا مع أخذ العينات المتعددة ونجح عند 1×. يمكنك اختيار إعداد آخر أعلاه؛ أعد التشغيل لتطبيقه إن نجح الفحص.", "prefs.anti_aliasing_note": "ينعّم الحواف المسننة.", + "prefs.appearance.colour_vision_help": "يغيّر الألوان ذات الدلالة: حالات الرسم والمحاور والثنيات والتحليلات والأيقونات.", + "prefs.appearance.desktop_only": "لتطبيق سطح المكتب فقط", + "prefs.appearance.follow_help": "يعيد التحميل عندما تعيد أداة أخرى كتابة الملف.", + "prefs.appearance.interface_scale": "مقياس الواجهة", + "prefs.appearance.next_themes": "السمات التالية", + "prefs.appearance.option_count": "{count} خيارات", + "prefs.appearance.option_count_one": "{count} خيار", + "prefs.appearance.previous_themes": "السمات السابقة", + "prefs.appearance.theme_count": "{count} سمات", + "prefs.appearance.theme_own": "ألوان السمة", + "prefs.appearance.viewport_colours": "ألوان العرض ثلاثي الأبعاد", + "prefs.appearance.viewport_logo": "منطقة العرض والشعار", "prefs.applies_on_restart": "يُطبَّق عند إعادة التشغيل", "prefs.assistant": "المساعد", + "prefs.assistant_connecting": "الاتصال", + "prefs.assistant_follow_help": "النظر إلى الرسومات يحرّك العرض مع المؤشر.", + "prefs.assistant_limit": "الحد", + "prefs.assistant_limited": "محدود", + "prefs.assistant_pointer_speed": "سرعة المؤشر", + "prefs.assistant_seconds": "ثوانٍ", + "prefs.assistant_seconds_aria": "الثواني", + "prefs.assistant_use_care": "استخدم بحذر", "prefs.auto_operation": "اختيار العملية تلقائيًا", - "prefs.auto_operation_note": "تختار نوافذ الميزات «ضم» أو «جسم جديد» أو «قص» بحسب ما تلامسه المادة الجديدة، إلى أن تختار عملية بنفسك. عند الإيقاف: تحتفظ بالعملية التي تُفتح بها.", + "prefs.auto_operation_note": "ضم أو جسم جديد أو قص، حسب ما تلامسه المادة.", "prefs.axes": "المحاور", "prefs.axis": "المحور", + "prefs.blur_cost": "تكلفة العرض النسبية. زيادة الأشرطة تعني عادةً مزيدًا من العمل.", + "prefs.blur_device": "غير متاح على جهاز الرسوميات أو مسار العرض هذا", + "prefs.blur_guard": "خُفّضت جودة التمويه للحفاظ على استجابة الإطارات. لم يتغير نصف القطر.", + "prefs.blur_off": "إيقاف", + "prefs.blur_reduce_transparency": "معطّل بسبب إعداد تقليل الشفافية في النظام", + "prefs.blur_software": "غير متاح مع الرسوميات البرمجية (gpu-software)", + "prefs.blur_source": "غير متاح في عرض مساحة العمل هذا", + "prefs.blur_web": "غير متاح في مسار عرض الويب هذا", "prefs.bodies_folders": "مجلدات الأجسام", "prefs.bodies_folders_always": "دائمًا", "prefs.bodies_folders_never": "أبدًا", - "prefs.bodies_folders_several": "عند تعدد الأجسام فقط", + "prefs.bodies_folders_several": "عند التعدد", "prefs.bottom": "أسفل", "prefs.bottom_centre": "أسفل الوسط", "prefs.bottom_right": "أسفل اليمين", "prefs.browser": "المستعرض", + "prefs.browser_components_open": "المكوّنات مفتوحة من البداية", + "prefs.browser_components_open_note": "يبدأ كل مكوّن في المستعرض مفتوحًا كما كان من قبل، بدلًا من أن يبقى مغلقًا حتى تفتحه.", + "prefs.browser_eye_left": "أيقونة الإظهار بجانب سهم الطي", + "prefs.browser_eye_left_note": "تعرض صفوف المستعرض أيقونة الإظهار/الإخفاء بجانب سهم الطي كما كانت من قبل، بدلًا من عمود عند نهاية الصفوف.", "prefs.browser_reveal_on_hover": "إظهار عند مرور المؤشر", "prefs.browser_show_note": "«ظاهر» يُبقي المستعرض على الشاشة. «إظهار عند مرور المؤشر» يُخفيه حتى يمر المؤشر فوق مكانه أو فوق الشريط الرفيع عند حافته اليسرى، ويبقى مفتوحًا ما دام المؤشر داخله أو كانت قائمة منه مفتوحة.", "prefs.browser_shown": "ظاهر", @@ -1847,6 +2298,8 @@ "prefs.button_left": "سحب بالزر الأيسر", "prefs.button_middle": "سحب بالزر الأوسط", "prefs.button_right": "سحب بالزر الأيمن", + "prefs.carousel_next": "التالي", + "prefs.carousel_previous": "السابق", "prefs.choose_font": "اختيار ملف خط…", "prefs.click": "نقر", "prefs.contact_shading": "تظليل التلامس الناعم", @@ -1859,27 +2312,63 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "الأسطح المنحنية", "prefs.curves": "الأسطح المنحنية", + "prefs.cut_preview_tint": "إظهار المادة المُزالة باللون الأحمر", + "prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا يُرسم سوى محيطها.", + "prefs.dark_parts_shading": "الحفاظ على شكل الأجزاء الداكنة", + "prefs.dark_parts_shading_help": "تظليل العرض بإضاءة خطية مع إضاءة سماء ناعمة، لتحتفظ الأوجه الداكنة بتدرج بدل أن تصبح سوداء", "prefs.dead_zone_note": "الشريط المخطط هو المنطقة الميتة: تُتجاهل الحركة داخلها.", "prefs.default": "افتراضي", - "prefs.design": "افتراضيات التصميم", - "prefs.design_note": "ما تبدأ به التصاميم الجديدة. التصاميم المفتوحة تحتفظ بإعداداتها.", + "prefs.design": "التصميم", + "prefs.design_note": "ما تبدأ به التصاميم الجديدة.", + "prefs.design_tools.ask": "اسأل", + "prefs.design_tools.degrees": "درجات", + "prefs.design_tools.double_click_help": "أو لتحرير مكوّن مرتبط في موضعه.", + "prefs.design_tools.ghost": "إظهار الموضع القديم للأجزاء المنقولة كشبح", + "prefs.design_tools.hole_moves_help": "اختيار الوجه مجددًا ينقل الثقب بدلًا من إزالته.", + "prefs.design_tools.hole_snaps_help": "منتصف الوجه ومراكز حوافه الدائرية.", + "prefs.design_tools.imported_files": "الملفات المستوردة", + "prefs.design_tools.note": "ملاحظة", + "prefs.design_tools.off": "إيقاف", + "prefs.design_tools.placement_group": "مسند، نتوء، تعشيق مرن", + "prefs.design_tools.rows": "صفوف", "prefs.devices": "الفأرة ثلاثية الأبعاد", "prefs.dialog_buttons": "أزرار مربعات الحوار", "prefs.dialogs": "الحوارات", "prefs.dialogs_edge": "عند حافة العرض", "prefs.dialogs_left_column": "في العمود الأيسر", "prefs.dialogs_note": "مكان فتح حوارات الأوامر: مثبتة عند حافة العرض، أو في العمود الأيسر مكان المستعرض والسجل، اللذين يعودان كما كانا عند إغلاق الحوار.", + "prefs.dimension_step_angle": "ما تضيفه أسهم النافذة وأعلى/أسفل والعجلة إلى الزاوية", + "prefs.dimension_step_length": "ما تضيفه أسهم النافذة وأعلى/أسفل والعجلة إلى الطول", + "prefs.dimension_steps": "خطوات النافذة", + "prefs.dimension_values": "قيم الأبعاد", + "prefs.dimension_values_note": "مكان كتابة قيمة البعد. للنافذة أسهم تغيّرها بخطوات؛ تضع أداة البعد النص أولًا.", + "prefs.dimension_values_view": "في العرض", + "prefs.dimension_values_window": "في نافذة", "prefs.display": "العرض", "prefs.edges": "الحواف والتظليل", "prefs.extend": "توسيع", "prefs.extra_navigation": "Ctrl مع السحب بالزر الأيسر في مساحة فارغة يدوّر العرض، واضغط مطولًا على Space للإزاحة.", + "prefs.extrude_view_isometric": "التحويل إلى العرض المتساوي القياس عند فتح البثق", + "prefs.extrude_view_return": "العودة إلى العرض السابق عند إغلاق البثق", "prefs.follows_os": "يتبع النظام", "prefs.font": "الخط", "prefs.font_fallback": "الرموز التي يفتقدها الخط المختار تُرسم بالخط المدمج، فلا تظهر أي تسمية كمربع فارغ.", "prefs.font_sample": "نص تجريبي للخط · Ø12.50 mm · 45.0° · 0123456789", "prefs.font_unreadable": "تعذّرت قراءة الخط المحدد.", "prefs.general": "عام", - "prefs.general_note": "اللغة والحفظ والتحديثات.", + "prefs.general.active": "نشط", + "prefs.general.crash_reports": "تقارير الأعطال", + "prefs.general.edited": "معدّل", + "prefs.general.held": "المشمول", + "prefs.general.import": "استيراد...", + "prefs.general.last_check": "آخر تحقق: {time}", + "prefs.general.minutes": "دقائق", + "prefs.general.name_setup": "سمِّ هذا الإعداد", + "prefs.general.profile_name": "اسم ملف التعريف", + "prefs.general.save_new": "حفظ كجديد", + "prefs.general.step_import": "STEP والاستيراد", + "prefs.general.this_computer": "هذا الحاسوب", + "prefs.general_note": "ملفات التعريف واللغة والملفات والتحديثات.", "prefs.gesture_orbit": "تدوير العرض", "prefs.gesture_pan": "إزاحة العرض", "prefs.gesture_zoom": "تكبير", @@ -1888,18 +2377,40 @@ "prefs.graphics_card_auto": "تلقائي", "prefs.graphics_card_missing": "بطاقة الرسوميات المحفوظة غير متاحة؛ يُستخدم الخيار «تلقائي».", "prefs.graphics_card_restart": "يُطبَّق بعد إعادة تشغيل SolidCraft. يتجاوز WGPU_ADAPTER_NAME هذا الاختيار.", + "prefs.graphics_card_unused": "لم تُستخدم بطاقة الرسوميات المحفوظة لهذه النافذة؛ البطاقة المستخدمة تظهر في «المساعدة › حول» وفي شريط الحالة. جرّب «تلقائي»، أو عيّن WGPU_ADAPTER_NAME إلى جزء فريد من اسم البطاقة.", "prefs.graphics_note": "وازن بين السرعة والنعومة. كل خيار يعرض أثره على عيّنة.", + "prefs.graphics_page.current_view": "العرض الحالي", + "prefs.graphics_page.fastest": "الأسرع", + "prefs.graphics_page.fold_items": "تلخيص العناصر", + "prefs.graphics_page.in_view": "داخل العرض", + "prefs.graphics_page.live_details": "تفاصيل مباشرة", + "prefs.graphics_page.own_mix": "مزيجك الخاص", + "prefs.graphics_page.quick_measure": "قياس سريع", + "prefs.graphics_page.reference_geometry_through_bodies": "الهندسة المرجعية عبر الأجسام", + "prefs.graphics_page.restart": "تلزم إعادة التشغيل", + "prefs.graphics_page.sharpest": "الأكثر وضوحًا", + "prefs.graphics_page.single_surface_analysis": "تحليل سطح واحد", + "prefs.graphics_page.status_chips": "شارات الحالة", + "prefs.graphics_page.subtitle": "وازن بين السرعة والنعومة.", + "prefs.graphics_page.supersampling": "التنعيم الفائق", + "prefs.graphics_page.supersampling_adaptive": "فقط أثناء سكون العرض", + "prefs.graphics_page.surfaces_edges": "الأسطح والحواف", + "prefs.graphics_page.view_bar": "أيضًا في شريط العرض", "prefs.graphics_presets_note": "الإعدادات المسبقة تضبط الخيارات أدناه معًا.", + "prefs.hide_constraint_glyphs_zoomed_out": "إخفاء رموز القيود عند التصغير", + "prefs.hide_constraint_glyphs_zoomed_out_note": "تختفي رموز القيود من العرض عندما يُصغَّر الرسم بقدر يجعلها تزحمه. معطّل: تبقى بحجم ثابت على الشاشة عند أي مستوى تكبير.", "prefs.history": "السجل", "prefs.history_origin_bodies": "إظهار الأصل والأجسام في الأعلى", "prefs.history_origin_bodies_note": "يبدأ السجل على اليسار أو تحت المستعرض بمجلد الأجسام للمكوّن النشط وبالأصل، مع أيقونات الإظهار والقوائم كما في المستعرض. لا يتغير السجل في الأسفل.", "prefs.history_play_button": "زر تشغيل السجل في عناصر تحكم السجل", "prefs.history_play_button_note": "يضيف تشغيل السجل بين الرجوع خطوة والتقدم خطوة في عناصر تحكم السجل. يمكنك أيضًا النقر بزر الماوس الأيمن على عناصر التحكم لإظهاره أو إخفائه.", - "prefs.history_sketches": "الرسومات", + "prefs.history_sketches": "الرسومات في السجل", "prefs.history_sketches_in_order": "بالترتيب", "prefs.history_sketches_note": "عند ضبط الرسومات على «تحت ميزتها»، يعرض السجل على اليسار كل رسم بمستوى واحد للداخل، تحت أول ميزة بُنيت منه، متى كان عريضًا بما يكفي لإظهار الأسماء. أما الخط الزمني في الأسفل فيحتفظ دائمًا بترتيب الإنشاء.", "prefs.history_sketches_under_feature": "تحت ميزتها", "prefs.hold_stop_snapping": "اضغط مطولًا لإيقاف الالتقاط", + "prefs.home_fit_size": "حجم العرض الرئيسي والملاءمة", + "prefs.home_fit_size_note": "مقدار ما يملؤه النموذج من العرض عندما يُظهره العرض الرئيسي أو الملاءمة أو تصميم مفتوح أو تغيير العرض من متصفح العرض، سواء كان الإعداد أدناه مفعّلًا أم لا. 100 %: يملأ العرض بين اللوحات والبوصلة وشريط التنقل.", "prefs.icons_only": "أيقونات فقط", "prefs.imported_file": "ملف مستورد", "prefs.in_browser": "في المستعرض", @@ -1908,13 +2419,38 @@ "prefs.interface_language": "لغة الواجهة", "prefs.interface_note": "شكل SolidCraft وأماكن أجزائه.", "prefs.interval_minutes": "{n} دقيقة", + "prefs.invert_curved_roll_arrows": "عكس سهمي التدوير المنحنيين", + "prefs.invert_curved_roll_arrows_note": "سهما التدوير المنحنيان عند زاوية المكعب يدوران العرض داخل مستوى الشاشة. عند التشغيل: سهم التدوير مع عقارب الساعة يدور عكسها، وسهم العكس يدور معها. عند الإيقاف: يدور كل سهم بالعرض حسب انحنائه.", + "prefs.invert_navigator_arrows": "عكس أسهم تدوير مكعب العرض", + "prefs.invert_navigator_arrows_note": "تدوّر الأسهم المحيطة بالمكعب الكاميرا في الاتجاه الذي تشير إليه، كما في Fusion وInventor: السهم الموجود على اليسار يشير إلى اليمين ويدوّر الكاميرا إلى اليمين. عند الإيقاف: يدوّر السهم المكعب نحو الجهة التي يقع فيها، فيدوّر السهم الأيسر الكاميرا إلى اليسار. لا يتأثر سهما الدوران المنحنيان.", + "prefs.keep_work_on_tab_switch": "إبقاء مربعات الحوار والأدوات مفتوحة عند التبديل بين التصاميم", + "prefs.keep_work_on_tab_switch_note": "تحتفظ كل علامة تبويب تصميم بمربع الحوار أو الأداة المفتوحة، بما حددته وكتبته فيها، وبعلامة تبويب شريط الأدوات. وتجدها كما هي عند العودة إلى التصميم. عند الإيقاف: يؤدي التبديل بين التصاميم إلى إلغائها وعرض علامة التبويب «النموذج».", "prefs.labels": "التسميات", + "prefs.language_system": "لغة النظام", "prefs.layout": "التخطيط", "prefs.layout_note": "المضغوط يثبّت اللوحات على حواف النافذة. شفافية المستعرض متاحة في الوضع العائم. غيّر جهة المساعد من صفحة المساعد.", + "prefs.layout_page.active_commands": "تمييز الأوامر النشطة", + "prefs.layout_page.always": "دائمًا", + "prefs.layout_page.card": "بطاقة", + "prefs.layout_page.column": "عمود", + "prefs.layout_page.hover": "عند مرور المؤشر", + "prefs.layout_page.icons_labels": "الأيقونات + التسميات", + "prefs.layout_page.ok_cancel": "موافق وإلغاء", + "prefs.layout_page.on_hover": "عند مرور المؤشر", + "prefs.layout_page.open": "تُفتح", + "prefs.layout_page.origin_bodies": "الأصل والأجسام في الأعلى", + "prefs.layout_page.panels": "اللوحات", + "prefs.layout_page.pinned_menus": "استبعاد الأوامر المثبتة من القوائم", + "prefs.layout_page.play_history": "زر تشغيل السجل", + "prefs.layout_page.slot_count": "{count} من {max} خانة", + "prefs.layout_page.view_corner": "أيضًا في زاوية العرض", + "prefs.layout_page.window": "النافذة", "prefs.left": "يسار", "prefs.left_click": "نقر أيسر", "prefs.line_drag_draws_one": "الضغط والسحب يرسم خطًا واحدًا", "prefs.line_drag_draws_one_note": "في أداة الخط، الضغط ثم السحب ثم الإفلات يرسم خطًا واحدًا من نقطة الضغط إلى نقطة الإفلات وينتهي هناك. لا تزال النقرات ترسم سلسلة. عند الإيقاف: يضع السحب نقطة حيث يُفلت، كما تفعل النقرة.", + "prefs.line_hover_tangent_arc": "التوقف عند آخر نقطة في الخط للتبديل إلى قوس مماسي", + "prefs.line_hover_tangent_arc_note": "في أداة الخط، بعد رسم قطعة، ابتعد عن آخر نقطة في السلسلة ثم عد إليها وأبقِ المؤشر ثابتًا عليها: تحدد النقرة التالية نهاية قوس مماسي، والحركة نفسها تعيدك إلى الخطوط. عند الإيقاف: لا يحدث شيء عند التوقف هناك.", "prefs.linked_designs": "التصاميم المرتبطة", "prefs.live_input": "الإدخال المباشر", "prefs.live_preview": "المعاينة المباشرة", @@ -1922,10 +2458,10 @@ "prefs.logo_accent": "لون التمييز", "prefs.logo_theme": "ألوان السمة", "prefs.max_file_size": "أكبر ملف يمكن فتحه", - "prefs.max_file_size_design": "ملفات التصميم", + "prefs.max_file_size_design": "أكبر ملف للفتح: التصميم", "prefs.max_file_size_flag": "بدأ هذا التشغيل بالخيار --max-file-size {size}، ويسري حتى إغلاق SolidCraft. تسري هذه الإعدادات عند تشغيله دون هذا الخيار.", "prefs.max_file_size_note": "القيم الافتراضية: 512 MB و256 MB؛ الحد الأقصى 16 GB. يتطلب فتح ملف ذاكرة تعادل حجمه عدة مرات. قد يحتاج التصميم الذي يحتفظ باستيراد كبير إلى حد أعلى لملف التصميم لحفظه وإعادة فتحه.", - "prefs.max_file_size_step": "ملفات STEP والاستيراد", + "prefs.max_file_size_step": "أكبر ملف للفتح: STEP والاستيراد", "prefs.max_file_size_web": "يفتح تطبيق الويب ملفات STEP والاستيراد حتى 512 MB والتصاميم حتى 256 MB؛ لا يتسع تبويب المتصفح لملفات أكبر. يمكن رفع هذه الحدود في تطبيق سطح المكتب.", "prefs.megabytes": "MB", "prefs.menu_grid": "أيقونات كبيرة", @@ -1937,10 +2473,19 @@ "prefs.mouse_heading": "الفأرة", "prefs.mouse_mapping": "تعيين أزرار الفأرة", "prefs.navigation": "التنقل", + "prefs.navigation.axes_signed": "المحاور", + "prefs.navigation.cube_compact": "المكعب", + "prefs.navigation.device": "الجهاز", + "prefs.navigation.free": "حر", + "prefs.navigation.orbit_style": "نمط التدوير", + "prefs.navigation.radial_help": "اضغط مطولًا أو انقر سريعًا بالزر الأيمن لعرض حلقة من الأدوات.", + "prefs.navigation.turntable": "طاولة دوارة", "prefs.navigation_note": "كيف تحرك الفأرة ولوحة اللمس والفأرة ثلاثية الأبعاد العرض.", + "prefs.navigator_fit": "ملاءمة النموذج بعد تغيير العرض من متصفح العرض", + "prefs.navigator_fit_note": "النقر على وجه أو ركن أو سهم في المكعب، أو على محور في أداة المحاور، يوجّه العرض أيضًا نحو منتصف النموذج من المسافة الواحدة التي تُظهره كاملًا من كل جهة (كرته المحيطة). يستخدم العرض الرئيسي التكبير والمركز ذاتهما ما دام هذا مفعّلًا، فلا تغيّر العروض المختارة بعده سوى الاتجاه. عند الإيقاف: يدور العرض في مكانه محتفظًا بالهدف والتكبير.", "prefs.network_host_remove": "إزالة", "prefs.network_locations": "السماح بمواقع الشبكة في التصاميم", - "prefs.network_locations_note": "عند الإيقاف: الملفات المرتبطة بالتصميم على حاسوب آخر (\\\\server\\share) لا تُفتح إلا من الخوادم المدرجة هنا، أو بعد أن تسمح لأحدها عند السؤال.", + "prefs.network_locations_note": "للمؤسسات التي تحفظ التصاميم على خوادم الملفات. عند الإيقاف: الخوادم التي تسمح بها فقط.", "prefs.network_locations_section": "مواقع الشبكة", "prefs.not_on_gpu": "غير متاح على هذا المعالج الرسومي", "prefs.on": "تشغيل", @@ -1950,20 +2495,32 @@ "prefs.origin_plane_names": "أسماء مستويات الأصل", "prefs.origin_plane_names_note": "الأسماء المعروضة في المستعرض والحوارات والقوائم. {top} هو XY و{front} هو XZ و{right} هو YZ، والمحور Z للأعلى. تحتفظ الأوامر والسكربتات والتصاميم المحفوظة بـ XY وXZ وYZ.", "prefs.overall_speed": "السرعة العامة", + "prefs.parameter_list_rows": "صفوف قائمة المعاملات", + "prefs.parameter_list_rows_tip": "الحد الأقصى للمعاملات التي يسردها السهم لأسفل في مربع تعبير فارغ.", "prefs.persistent_ribbon_pressed": "تمييز أوامر الشريط النشطة", "prefs.persistent_ribbon_pressed_help": "تمييز أوامر الشريط أثناء تفعيل تأثيراتها. أوقف هذا الخيار للاحتفاظ بالمظهر المحايد السابق ومساعدة الأوامر.", "prefs.perspective_fov": "مجال الرؤية", "prefs.placement": "الموضع", + "prefs.plugins_enabled": "مفعّل", + "prefs.plugins_installed": "المثبّتة", + "prefs.plugins_intro": "إضافات معزولة.", + "prefs.plugins_show_folder": "إظهار مجلد الإضافات", "prefs.prefer_free_sketch_points": "تفضيل نقاط الرسم القابلة للتحريك عند تداخل النقاط", "prefs.preview_choices": "معاينة اختياراتك", + "prefs.preview_tint_new_faces": "تلوين السطح الجديد في المعاينة", + "prefs.preview_tint_new_faces_help": "يمكن لمعاينة ميزة تغيّر جسمًا أن ترسم السطح المضاف بلون المعاينة. عند الإيقاف يُرسم الجسم بلونه الأصلي.", + "prefs.print_face_highlight": "إبراز وجه الطباعة", + "prefs.print_face_highlight_tip": "مدى قوة تلوين وجه الطباعة للجسم ورسم حدوده في العرض. القيمة 0 % لا تُظهر أي إبراز.", "prefs.profile_active": "ملف التعريف النشط", "prefs.profile_applied": "تم تطبيق ملف التعريف.", "prefs.profile_changed": "تغيّرت الإعدادات منذ حفظ ملف التعريف. «حفظ» يحفظها فيه.", "prefs.profile_deleted": "تم حذف ملف التعريف.", - "prefs.profile_export": "تصدير…", + "prefs.profile_export": "تصدير", "prefs.profile_exported": "تم تصدير ملف التعريف.", - "prefs.profile_imported": "تم استيراد ملف التعريف. اختره في «ملف التعريف النشط» للتبديل إليه.", + "prefs.profile_imported": "تم استيراد ملف التعريف.", "prefs.profile_name_hint": "اسم ملف التعريف، مثل: حاسوب محمول", + "prefs.profile_operations": "تحليل زمن العمليات", + "prefs.profile_operations_note": "يسجّل المدة التي تستغرقها استدعاءات SMLib وعمليات النواة والميزات والأوامر وعمليات الاستيراد. يقرؤه الوكلاء عبر diagnostics.profile.", "prefs.profile_rename": "إعادة تسمية", "prefs.profile_renamed": "تمت إعادة تسمية ملف التعريف.", "prefs.profile_save": "حفظ", @@ -1977,26 +2534,71 @@ "prefs.quality_fastest": "الأسرع", "prefs.quality_slowest": "الأبطأ", "prefs.quality_smoother": "أنعم", + "prefs.quick_measure": "قياس سريع في زاوية العرض", + "prefs.quick_measure_note": "مقاس العناصر المحددة في الزاوية اليمنى السفلية من العرض: طول الحافة (أو Ø وR للحافة الدائرية)، ومساحة الوجه، وموضع النقطة، والمسافة والزاوية بين عنصرين، ومجموع عدة حواف أو أوجه. النقر ينسخه.", "prefs.render_previous_geometry_budget": "استخدام ميزانية الهندسة السابقة لمعاينة التصيير", "prefs.render_previous_geometry_budget_help": "استعادة حد الهندسة الثابت السابق (512 ميبيبايت على سطح المكتب 64 بت، و128 ميبيبايت على المنصات الأخرى) بدلًا من الميزانية المعتمدة على الجهاز.", "prefs.reports_saved": "{n} محفوظة", + "prefs.restore_page_defaults": "استعادة الإعدادات الافتراضية لهذه الصفحة", + "prefs.ribbon_click_ends_tool": "النقر على زر الأداة قيد التشغيل ينهيها", + "prefs.ribbon_click_ends_tool_note": "النقر على زر الشريط المضيء لأداة الرسم المستخدمة ينهي الأداة، فيعود النقر في العرض إلى التحديد. عند الإيقاف: يبدأ النقر الأداة من جديد.", "prefs.ribbon_reveal": "إظهار مكان نتائج البحث في الشريط", "prefs.ribbon_reveal_note": "عند تمرير المؤشر فوق نتيجة في «البحث في الأوامر» يظهر مكان الأمر في الشريط: تبويبه أو زره أو صفه في القائمة المنسدلة للوحة. ويومض هناك الأمر الذي بدأ من البحث، ويُعلِّم الأمر الجاري من قائمة منسدلة لوحتَه.", "prefs.right_click": "نقر أيمن", - "prefs.saving": "الحفظ التلقائي والاستعادة", + "prefs.saving": "البدء والحفظ", "prefs.scale_note": "أو Ctrl + / Ctrl − في النافذة. الأزرار 28 px عند 100%.", "prefs.scale_text": "الحجم والنص", "prefs.search": "البحث في الإعدادات", "prefs.search_empty": "لا توجد إعدادات مطابقة", + "prefs.section_hatch": "تهشير المقطع", + "prefs.section_hatch_by_part": "حسب الجزء", + "prefs.section_hatch_one": "نمط واحد", "prefs.select": "تحديد", "prefs.select_one_item": "تحديد عنصر واحد", + "prefs.select_other_hidden": "تحديد العناصر الهندسية المخفية باستخدام «تحديد عنصر آخر»", + "prefs.select_other_hidden_help": "عند التفعيل: تضمين الأجسام والمخططات المخفية والحواف المحجوبة قرب المؤشر. عند التعطيل: استخدام القائمة الأصلية للعناصر الهندسية المرئية أسفل المؤشر.", "prefs.selecting": "التحديد", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift يضيف فقط، وCtrl / Cmd يبدّل", "prefs.shift_add_note": "عند التشغيل: Shift يضيف، وCtrl / Cmd يبدّل. عند الإيقاف (الافتراضي): كلاهما يبدّل.", "prefs.shortcuts": "الاختصارات", + "prefs.shortcuts_import": "استيراد", + "prefs.shortcuts_intro": "مفاتيح كل أمر.", + "prefs.shortcuts_not_assigned": "غير معيّن", + "prefs.shortcuts_press": "اضغط مفتاحًا...", "prefs.single_surface_analysis": "استخدام تحليل سطح واحد", "prefs.single_surface_analysis_help": "عند إيقاف هذا الخيار، يمكن إبقاء تظليل السطح وتحليل الاستمرارية مفعّلين معًا. عند تشغيله، يبقى آخر تحليل تم بدؤه أو تغييره فقط.", + "prefs.sketch.align_points": "المحاذاة مع نقاط الرسم الأخرى", + "prefs.sketch.align_points_note": "تتحاذى الخطوط أثناء الرسم مع النقاط على المحورين معًا.", + "prefs.sketch.auto_dimensions": "إضافة كل الأبعاد للأشكال الجديدة", + "prefs.sketch.auto_dimensions_note": "القيم المدخلة وكل بُعد يثبّت الشكل.", + "prefs.sketch.auto_locate": "تحديد الموضع من أصل الرسم", + "prefs.sketch.auto_locate_note": "مع إضافة كل الأبعاد.", + "prefs.sketch.center_arc": "القوس بنقطة مركز يتبع المؤشر", + "prefs.sketch.click_selects": "النقر يحدد", + "prefs.sketch.conflict_colour": "لون التعارض", + "prefs.sketch.drawing": "الرسم", + "prefs.sketch.exit_keep": "إبقاء", + "prefs.sketch.exit_previous": "العودة إلى العرض السابق", + "prefs.sketch.exit_unless_rotated": "إلا إذا تم التدوير", + "prefs.sketch.faces_edges": "الأوجه والحواف", + "prefs.sketch.hide_glyphs": "إخفاء الرموز عند التصغير", + "prefs.sketch.marks": "العلامات في الرسم", + "prefs.sketch.note": "الرسم والالتقاط والتحديد.", + "prefs.sketch.opening_closing": "الفتح والإغلاق", + "prefs.sketch.prefer_free_points": "تفضيل النقاط القابلة للتحريك عند تداخلها", + "prefs.sketch.project_options": "السؤال عن خيارات الإسقاط أولًا", + "prefs.sketch.recent_snap": "الالتقاط عند تقاطع دليلين", + "prefs.sketch.select_other_hidden": "تحديد آخر يشمل الهندسة المخفية", + "prefs.sketch.shortcut_cycles_modes": "الاختصار مجددًا يبدّل الوضع", + "prefs.sketch.shortcut_cycles_modes_tip": "عند الإيقاف: تبدأ الأداة مجددًا.", + "prefs.sketch.snapping_guides": "الالتقاط والأدلة", + "prefs.sketch.state_icons": "أيقونات الحالة", + "prefs.sketch.tracking_guides": "أدلة المراكز ونقاط المنتصف", + "prefs.sketch.tracking_guides_note": "أدلة أفقية وعمودية مؤقتة من المراكز ونقاط منتصف الحواف عند التحويم.", + "prefs.sketch.tracking_points": "أدلة من نقاط الرسم أيضًا", + "prefs.sketch.unless_turned_note": "العودة إذا لم يتم التدوير", + "prefs.sketch.whole_bodies": "الأجسام كاملة", "prefs.sketch_align_points": "المحاذاة مع نقاط الرسم الأخرى أثناء الرسم", "prefs.sketch_align_points_note": "أثناء الرسم، تتحاذى النقطة أفقيًا مع نقطة رسم وعموديًا مع نقطة أخرى في الوقت نفسه، مع خط إرشادي منقط، وتحتفظ النقرة بالمحاذاتين. عند الإيقاف: مع النقطة السابقة فقط، محور واحد في كل مرة.", "prefs.sketch_conflict_colour": "الهندسة المتعارضة بلون التعارض", @@ -2007,6 +2609,8 @@ "prefs.sketch_exit_view.previous": "العودة إلى العرض السابق", "prefs.sketch_exit_view.unless_rotated": "العودة ما لم يُدوَّر العرض", "prefs.sketch_exit_view_note": "أين ينتقل العرض بعد إنهاء الرسم أو الإلغاء أو الضغط على Esc مرتين.", + "prefs.sketch_face_activates_part": "الرسم على وجه جزء يجعل ذلك الجزء نشطًا", + "prefs.sketch_face_activates_part_note": "الرسم الذي يبدأ على وجه جسم في مكوّن آخر ينشّط ذلك المكوّن أولًا، فينتمي الرسم إليه ويبقى مع ذلك الجزء في المستعرض. ويبقى الجزء نشطًا بعد ذلك. عند الإيقاف: ينتمي الرسم إلى المكوّن النشط.", "prefs.sketch_open_look_at": "توجيه العرض نحو الرسم عند فتحه", "prefs.sketch_open_look_at_note": "عند الإيقاف: إنشاء الرسم أو تحريره يُبقي العرض كما هو. يوجّه «النظر إلى» العرض نحو الرسم عند الحاجة.", "prefs.sketch_recent_snap": "الالتقاط التلقائي إلى المراكز ونقاط المنتصف الأخيرة", @@ -2020,22 +2624,42 @@ "prefs.sketch_tab_always_note": "يبقى تبويب الرسم في الشريط بعد تبويب النموذج مباشرة حتى عندما لا يكون أي رسم مفتوحًا. عندها تبدأ أدوات الرسم فيه رسمًا على المستوي أو الوجه المحدد، أو على المستوي الذي تختاره بعد ذلك، وتكون الأداة جاهزة فيه.", "prefs.sketch_tracking_guides": "أدلة محاذاة المراكز ونقاط المنتصف", "prefs.sketch_tracking_guides_note": "مرّر المؤشر فوق مركز دائرة أو نقطة منتصف حافة مستقيمة، ثم حرّكه أفقيًا أو عموديًا لإظهار دليل منقّط مؤقت.", + "prefs.sketch_tracking_points": "أدلة محاذاة من نقاط النهاية والزوايا أثناء الرسم", + "prefs.sketch_tracking_points_note": "عندما تنتظر أداة رسم نقطة، يؤدي تمرير المؤشر فوق نهاية خط أو قوس أو زاوية مستطيل أو نقطة حرة إلى إظهار الدليل المنقّط المؤقت نفسه الذي يظهر للمركز أو نقطة المنتصف. عند الإيقاف: المراكز ونقاط المنتصف فقط.", "prefs.sketching": "الرسم", "prefs.snap_drawing_note": "أثناء الرسم أو سحب نقطة في الرسم.", "prefs.source": "المصدر", "prefs.speed": "السرعة", "prefs.stand_up_note": "بعد فتح ملف STEP أو IGES ومحوره Z للأعلى، يُعرض تدويره ربع دورة حول X.", - "prefs.stand_up_unknown": "للملفات من برامج غير معروفة", + "prefs.stand_up_unknown": "ملفات من برامج غير معروفة", "prefs.stand_up_unknown.ask": "السؤال في مربع حوار", "prefs.stand_up_unknown.note": "عرض ملاحظة", "prefs.stand_up_unknown.off": "عدم العرض", - "prefs.stand_up_unknown_note": "طريقة العرض عندما لا يذكر رأس الملف برنامجًا معروفًا بحفظ المحور Y للأعلى. تظهر الملاحظة فقط عندما يبدو أن الملف ملقى على ظهره؛ أما «السؤال في مربع حوار» فيسأل عن كل ملف كهذا، كما كان سابقًا.", + "prefs.stand_up_unknown_note": "كيفية عرض الاقتراح عندما لا يذكر الملف برنامجًا معروفًا.", "prefs.status_bar": "شريط الحالة", "prefs.status_bar_note": "شريط رفيع على الحافة السفلية للنافذة يعرض ما يجري تحريره، وحالة الرسم المفتوح بلونها، ووحدات التصميم؛ النقر على الوحدات يغيّرها. عندها لا تظهر حالة الرسم في زاوية العرض.", "prefs.status_done": "تم", "prefs.status_error": "خطأ", "prefs.status_selected": "محدد", "prefs.status_warning": "تحذير", + "prefs.structure.appearance": "المظهر", + "prefs.structure.appearance_note": "الألوان والنصوص وإمكانية الوصول.", + "prefs.structure.in_profile": "ضمن ملف التعريف", + "prefs.structure.layout": "التخطيط", + "prefs.structure.layout_note": "مواضع أجزاء النافذة.", + "prefs.structure.look": "العرض", + "prefs.structure.measure_pointer": "القياس والمؤشر", + "prefs.structure.mouse3d": "فأرة ثلاثية الأبعاد", + "prefs.structure.mouse3d_note": "SpaceMouse وSpaceNavigator.", + "prefs.structure.navigation_note": "الفأرة ولوحة اللمس. للفأرة ثلاثية الأبعاد صفحة خاصة بها.", + "prefs.structure.profile": "ملف التعريف", + "prefs.structure.profile_edited": "تغيّر منذ الحفظ", + "prefs.structure.profile_hover": "محفوظ في ملفات تعريف الإعدادات", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "رسم", + "prefs.structure.tools": "الأدوات", + "prefs.structure.tools_note": "كيفية عمل أدوات النمذجة.", + "prefs.structure.work": "العمل", "prefs.supersampling_brief": "يرسم العرض بحجم أكبر ثم يصغّره: حاد جدًا لكنه أثقل.", "prefs.tab_accent_note": "لون التمييز يتبع التبويب النشط", "prefs.theme_file": "ملف السمة", @@ -2047,6 +2671,21 @@ "prefs.theme_follow_off": "إيقاف", "prefs.theme_follow_stop": "إيقاف الاتباع", "prefs.theme_import_hint": "انقر لاختيار ملف سمة، أو أفلت ملفًا هنا، أو اضغط Ctrl+V (Cmd+V على Mac) بعد نسخ سمة", + "prefs.theme_notice_dismiss": "إخفاء", + "prefs.theme_option_blur": "تمويه خلف اللوحات", + "prefs.theme_option_blur_help": "تمويه خلف اللوحات شبه الشفافة، بالبكسل الفعلي. الصفر يوقف التمويه.", + "prefs.theme_option_invalid": "القيمة المحفوظة للخيار {option} غير صالحة؛ تُستخدم القيمة الافتراضية للسمة. تبقى القيمة المحفوظة كما هي.", + "prefs.theme_option_opacity": "العتامة", + "prefs.theme_option_opacity_help": "اضبط عتامة اللوحات العائمة. يُطبّق حد أدنى للعتامة للحفاظ على وضوح النص فوق ألوان منطقة العرض.", + "prefs.theme_option_tab_colours": "ألوان علامات التبويب", + "prefs.theme_option_tab_colours_help": "استخدم ألوان اللوحات ومنطقة العرض من هذه السمة لكل علامة تبويب في الشريط.", + "prefs.theme_option_tab_fade_ms": "انتقال علامات التبويب", + "prefs.theme_option_tab_fade_ms_help": "تتغيّر ألوان اللوحات ومنطقة العرض تدريجيًا عند تبديل علامات التبويب. القيمة صفر تبدّلها فورًا.", + "prefs.theme_options_badge": "الخيارات", + "prefs.theme_options_more": "المزيد · {count}", + "prefs.theme_options_newer": "تتطلب هذه السمة إصدارًا أحدث من SolidCraft. بعد الترقية، أعد استيراد السمة الأصلية لاستعادة تعريفات خياراتها.", + "prefs.theme_options_reset": "إعادة تعيين", + "prefs.theme_options_unavailable": "غير متاح على هذا الجهاز", "prefs.theme_paste": "لصق السمة", "prefs.theme_paste_none": "لا تحتوي الحافظة على سمة SolidCraft", "prefs.timeline_half_hour": "−30 دقيقة", @@ -2068,13 +2707,29 @@ "prefs.under_cursor": "تحت المؤشر", "prefs.units_precision": "الوحدات والدقة", "prefs.updates": "التحديثات", + "prefs.validation": "التحقق من الأجسام", + "prefs.validation.each_feature": "مرة لكل ميزة", + "prefs.validation.each_step": "بعد كل خطوة", + "prefs.validation.label": "فحص النواة الكامل", + "prefs.validation.off": "متوقف (تجريبي)", + "prefs.validation_note": "بعد كل خطوة: يفحص كل عملية كنس وعملية منطقية وتقويس.\nمرة لكل ميزة: يفحص ناتج كل ميزة مرة واحدة.\nمتوقف (تجريبي): لا فحص.", + "prefs.value_boxes_in_view": "إظهار القيم بجانب مقابضها", + "prefs.value_boxes_in_view_tip": "مسافة البثق ونصف قطر التدوير... في مربع داخل العرض.", "prefs.view": "سلوك العرض", "prefs.view_confirm_corner": "موافق وإلغاء في زاوية العرض", "prefs.view_confirm_corner_note": "أثناء فتح مربع حوار أو رسم، تؤدي علامة الصح وعلامة الإكس أعلى يمين العرض ما يؤديه زرّا موافق وإلغاء في مربع الحوار، أو تنهي الرسم وتلغيه. وينتقل متصفح العرض إلى أسفلهما.", "prefs.viewport": "منطقة العرض", + "prefs.viewport_analysis_status": "إظهار حالة التحليل في منطقة العرض", + "prefs.viewport_analysis_status_help": "عرض التحليلات النشطة أعلى منطقة العرض، وفتح مفتاح الألوان لكل تحليل من عنصره، واستخدام Esc لإيقاف أحدث تحليل. أوقف الخيار لاستعادة مفاتيح الألوان في الزاوية وسلوك Esc السابق.", "prefs.viewport_background": "الخلفية", "prefs.viewport_background_colour": "لون", "prefs.viewport_background_theme": "تدرج السمة", + "prefs.viewport_section_status": "إظهار حالة المقطع في منطقة العرض", + "prefs.viewport_section_status_help": "عرض إعداد المقطع في منطقة العرض. يُوقف Escape وزر الشريط النشط المقطع. عطّل الخيار للاحتفاظ بأدوات المقطع السابقة.", + "prefs.viewport_status_details": "تفاصيل منطقة العرض المباشرة", + "prefs.viewport_status_details_help": "حرّر إعدادات التحليل والمقطع النشطين في بطاقات التفاصيل القياسية. عطّل هذا الخيار لاستعادة مفاتيح ألوان التحليل للقراءة فقط ومربع حوار المقطع.", + "prefs.viewport_status_summary": "تلخيص عناصر حالة منطقة العرض", + "prefs.viewport_status_summary_help": "اجمع ثلاثة عناصر أو أكثر لحالة منطقة العرض في شارة ملخّصة واحدة. عطّل الخيار لإبقاء كل عنصر في الصف الكامل.", "prefs.wheel": "العجلة", "prefs.wheel_trackpad": "العجلة ولوحة اللمس", "prefs.workspace": "مساحة العمل", @@ -2092,6 +2747,17 @@ "recovery.just_now": "الآن", "recovery.min_ago": "قبل {count} دقيقة", "recovery.never_saved": "لم يُحفظ قط", + "refused.change": "تعذّر تغيير {body}.", + "refused.cut": "تعذّر قطع {body}.", + "refused.face_curved": "أحد أوجهه المنحنية لا يمكن استخدامه في النمذجة.", + "refused.face_flat": "أحد أوجهه المستوية لا يمكن استخدامه في النمذجة.", + "refused.face_freeform": "أحد أوجهه الحرة لا يمكن استخدامه في النمذجة.", + "refused.face_rounded": "أحد أوجهه المستديرة لا يمكن استخدامه في النمذجة.", + "refused.faces_apart": "أوجهه لا تلتقي بدقة كافية لاستخدامها في النمذجة.", + "refused.intersect": "تعذّر التقاطع مع {body}.", + "refused.join": "تعذّر الضم إلى {body}.", + "refused.repair": "إصلاح الجزء", + "refused.show_face": "إظهار الوجه", "render.adaptive_absolute": "الحد الأدنى المطلق لخطأ RGB", "render.adaptive_coverage": "هدف خطأ التغطية", "render.adaptive_enable": "توزيع العيّنات باستخدام عيّنات استكشافية مستقلة", @@ -2203,6 +2869,10 @@ "render.base_color": "اللون الأساسي · sRGB", "render.base_metallic": "النسبة المعدنية", "render.base_opaque_only": "يحافظ هذا المحرر على دلالات الجسم المعتم. استخدم عناصر التحكم الصريحة للزجاج من أجل النفاذ البصري.", + "render.batch_all_shots": "كل اللقطات ({count})", + "render.batch_empty": "احفظ لقطة قبل تصيير كل اللقطات.", + "render.batch_limit": "تصيير كل اللقطات محدود بـ 32 لقطة.", + "render.batch_status": "{running} قيد التشغيل · {waiting} في الانتظار", "render.bloom_enable": "توهج العرض", "render.bloom_help": "توهج إبداعي للإخراج فقط من الإضاءات الخطية الموجبة، يُنشر بثلاث تمريرات صندوقية مُطبّعة. نصف القطر ببكسلات الإخراج. يُضاف في ضوء العرض الخطي قبل sRGB؛ وليس عدسة ولا تأثيرًا حجميًا ولا تحسينًا للتقارب. يبقى EXR الخام دون تغيير.", "render.bloom_opaque": "يتطلب التوهج إخراجًا معتمًا. يُرفض PNG الشفاف بدل تسطيحه بصمت.", @@ -2313,6 +2983,13 @@ "render.choose_look": "اختر مظهرًا من المظاهر أولًا", "render.chromatic_offset": "إزاحة لونية عند الحواف", "render.clear_stage": "إزالة المنصة المحفوظة", + "render.compare_divider": "فاصل المقارنة", + "render.compare_live": "حي", + "render.compare_live_preview": "معاينة حية", + "render.compare_render": "التصيير {number}", + "render.compare_side": "التصيير {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} ث · {renderer} · التُقطت عند المراجعة {revision}", + "render.compare_swap": "تبديل", "render.copy_request": "نسخ JSON", "render.cpu_aa_help": "العيّنات المكانية: المزيد منها يحسّن الحواف ويزيد زمن التصيير.", "render.cpu_area_add": "إضافة ضوء مستطيل على CPU", @@ -2953,7 +3630,9 @@ "render.output_ready": "جاهز للتصيير", "render.output_run_check": "تشغيل الفحص", "render.output_size_limit": "{method}: حتى {dimension} بكسل لكل ضلع و{pixels} بكسل. أكبر حجم مناسب: {width} × {height}.", + "render.output_size_method_profile": "لتصيير {width} × {height}، اختر {method} مع ملف موارد CPU «{profile}»، أو حجمًا أصغر.", "render.output_size_ok": "الحجم مناسب · {width} × {height} بكسل", + "render.output_size_profile": "لتصيير {width} × {height}، اختر ملف موارد CPU «{profile}»، أو حجمًا أصغر.", "render.output_swap_orientation": "تبديل العرض والارتفاع", "render.output_tools_inspector": "عدّل الحجم والصيغة في مفتش المخرجات.", "render.output_view_image": "عرض الصورة", @@ -3060,6 +3739,10 @@ "render.result_retained": "تُعرض آخر صورة مكتملة؛ ولم يستبدلها تصيير أحدث.", "render.result_sequence": "نقطة التحقق", "render.result_title": "نتيجة التصيير", + "render.results_choose": "النتائج المحتفظ بها", + "render.results_label": "التصيير {number} · {shot} · {seconds} ث", + "render.results_stale_label": "{result} [قديم]", + "render.results_unnamed": "صورة", "render.return_design": "العودة إلى التصميم", "render.review_stale": "هذه المراجعة قديمة. حُلّها أو افحص مرة أخرى قبل التطبيق.", "render.ribbon_aging": "التقادم", @@ -3166,6 +3849,7 @@ "render.size_custom": "مخصص…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · يتطلب «{profile}»", "render.size_presets": "إعدادات الحجم المسبقة", "render.size_presets_pending": "تصل مع محرر المخرجات", "render.size_preview": "معاينة", @@ -3431,11 +4115,11 @@ "select two components": "حدد مكوّنين اثنين", "set by the sketch's lines": "تحدده خطوط الرسم", "settings.display_quality_note": "المستويات الأدق ترسم الأوجه والحواف المنحنية بنعومة أكبر وتستغرق وقتًا أطول لإنشاء الشبكة. يتغير العرض فقط، لا التصميم ولا الملفات المصدّرة.", - "settings.double_click_components": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه", + "settings.double_click_components": "النقر المزدوج على مكوّن لتنشيطه", "settings.frame_rate_details_note": "يضيف رسمًا لأزمنة الإطارات الأخيرة مع المثلثات المرسومة فوقه، ومدرّجًا تكراريًا لأزمنة الإطارات، وما رسمته وحدة GPU. انقر معدل الإطارات في العرض لإظهارها أو إخفائها.", "settings.frame_rate_note": "يعرض الإطارات في الثانية في الزاوية اليمنى السفلية من العرض. أثناء تفعيله يُعاد رسم العرض باستمرار.", - "settings.insert_lists_open_designs": "يعرض إدراج تصميم أولًا التصاميم المفتوحة في علامات التبويب الأخرى", - "settings.measure_axis_distances": "إظهار المسافات على X/Y/Z", + "settings.insert_lists_open_designs": "إدراج تصميم يسرد التصاميم المفتوحة أولًا", + "settings.measure_axis_distances": "مسافات المحاور في القياس", "settings.measure_axis_distances_help": "إظهار مركّبات الأبعاد على محاور العالم بجانب المسافة الكلية أثناء فتح أداة القياس.", "settings.msaa_applies_on_restart": "يُطبّق تنعيم الحواف في المرة القادمة التي يبدأ فيها SolidCraft", "settings.msaa_reset": "{setting}: القيمة {requested}× غير مدعومة في جهاز الرسوميات هذا؛ أصبحت الآن {reset}× (المدعوم: {supported}).", @@ -3445,7 +4129,7 @@ "settings.reset_intro": "هذه الإعدادات لا تعمل على هذا الحاسوب وكانت ستمنع SolidCraft من البدء، لذا غُيّرت:", "settings.reset_title": "تم تغيير الإعدادات", "settings.supersampling_note": "يرسم العرض بدقة أعلى ثم يصفّيه: حواف وخطوط وشبكة أنعم على الشاشات الأقل من 4K. يكلّف وقتًا من معالج الرسوميات: نحو 2.25× من البكسلات عند 1.5× و4× عند 2×.", - "settings.update_changed_links": "تحديث التصاميم المرتبطة التي تغيّرت عند العودة إلى علامة التبويب", + "settings.update_changed_links": "تحديث الروابط المتغيرة عند العودة إلى علامة تبويب", "settings.window_system_details": "التفاصيل", "settings.window_system_note_now": "يُطبَّق بعد إعادة التشغيل. الحالي: {now}.", "settings.window_system_wayland_limited": "بعض الميزات محدودة على Wayland الأصلي.", @@ -3453,6 +4137,24 @@ "sheet.flange_type_contour": "محيط", "sheet.flange_type_edge": "حافة", "sheet.no_body": "لا يوجد جسم صفائح معدنية: ابدأ واحدًا من حافة مثنية > أساسية، أو حوّل لوحًا إلى صفائح معدنية بأمر تحويل إلى صفائح معدنية (اختر وجهه المسطح الكبير)", + "sheet.personal_rules.confirm_delete": "تأكيد الحذف", + "sheet.personal_rules.delete": "حذف", + "sheet.personal_rules.delete_prompt": "هل تحذف هذه القاعدة الشخصية؟ القواعد الموجودة في التصاميم لا تتغير.", + "sheet.personal_rules.full": "المكتبة الشخصية فيها 64 قاعدة بالفعل.", + "sheet.personal_rules.invalid_name": "أدخل اسمًا قصيرًا بلا فواصل أسطر ولا محارف تحكم.", + "sheet.personal_rules.invalid_values": "أكمل قيم القاعدة: يجب أن تُحسب كل قيمة في هذا التصميم، بسماكة موجبة ومعامل K من 0 إلى 1.", + "sheet.personal_rules.missing": "القاعدة الشخصية المحددة لم تعد متاحة.", + "sheet.personal_rules.name": "اسم القاعدة", + "sheet.personal_rules.name_exists": "توجد قاعدة شخصية بهذا الاسم. استخدم اسمًا آخر.", + "sheet.personal_rules.name_hint": "اسم فريد", + "sheet.personal_rules.overwrite": "حفظ التغييرات في القاعدة الشخصية المحددة", + "sheet.personal_rules.rename": "إعادة تسمية", + "sheet.personal_rules.rule": "القاعدة الشخصية", + "sheet.personal_rules.save": "حفظ كجديدة", + "sheet.personal_rules.scope": "محفوظة في ملفك الشخصي لكل التصاميم.", + "sheet.personal_rules.select": "اختر قاعدة", + "sheet.personal_rules.title": "القواعد الشخصية", + "sheet.personal_rules.unsupported": "تحتوي هذه القاعدة على قيم لا يستطيع هذا الإصدار استخدامها.", "shortcut.json_error": "يجب أن تكون المعاملات بصيغة JSON: {error}", "shortcut.no_command": "لا يوجد أمر `{id}`، ويجب أن يكون النص قبل JSON معرّف أمر", "shortcut.pin": "تثبيت في أعلى مربع S", @@ -3489,8 +4191,10 @@ "sketch_text.align_right": "يمين", "sketch_text.bold": "غامق", "sketch_text.builtin_font": "{family} (مدمج)", + "sketch_text.formula": "ابدأ بـ = لتكوين النص من المعاملات: ='W' + number(Width)", "sketch_text.italic": "مائل", "sketch_text.loading_fonts": "جارٍ البحث عن الخطوط المثبتة…", + "sketch_text.no_bold": "الخط المدمج لا يحتوي على نمط غامق: اختر خطًا مثبتًا", "sketch_text.on_path": "النص يتبع مساره: المنحنى يحدد موضعه", "sketch_text.path_clear": "فصل النص عن منحناه", "sketch_text.path_hint": "منحنى من الرسم يتبعه النص: انقر هنا ثم على المنحنى", @@ -3521,11 +4225,20 @@ "the section's profiles must be in one sketch": "يجب أن تكون مقاطع المقطع العرضي في رسم واحد", "the two origins are on the same component": "يقع الأصلان على المكوّن نفسه", "thread.automatic_size": "حجم تلقائي", + "thread.chamfer_depth_needed": "مطلوب لهذا الشكل", "thread.designation": "التسمية", - "thread.direction": "اتجاه السن اللولبي", + "thread.drill_range": "مثقاب التسنين الذي يوصي به صانعو ذكور التسنين {drill} مم. القطر الأصغر القياسي للسن الداخلي {minor} مم. يُقبل مثقاب من {low} إلى {high} مم.", + "thread.drill_range_custom": "المثقاب هو القطر الأكبر ناقص الخطوة، {drill} مم. القطر الأصغر القياسي للسن الداخلي {minor} مم. يُقبل مثقاب من {low} إلى {high} مم.", + "thread.drill_range_taper": "مثقاب التسنين الذي يوصي به صانعو ذكور التسنين {drill} مم. القطر الأصغر القياسي عند نهاية السن {minor} مم. يُقبل مثقاب من {low} إلى {high} مم.", + "thread.end_square": "قائمة", + "thread.fade_short": "1.25 P (ISO 3508)", + "thread.fade_standard": "2.5 P (ISO 3508)", + "thread.fits_the_face": "يناسب الوجه، مثلًا {example}", + "thread.form_bspp": "سن أنابيب G (ISO 228-1)", + "thread.form_bspt": "سن أنابيب مخروطي R، Rc (ISO 7-1)", + "thread.form_npt": "سن أنابيب مخروطي NPT (ASME B1.20.1)", + "thread.form_rp": "سن أنابيب داخلي متوازٍ Rp (ISO 7-1)", "thread.iso_metric": "متري ISO", - "thread.left_hand": "يساري", - "thread.right_hand": "يميني", "thread.select_size": "اختر الحجم", "timeline.delete_after_marker_one": "حذف ميزة واحدة بعد مؤشر السجل", "timeline.delete_after_marker_other": "حذف {count} ميزات بعد مؤشر السجل", @@ -3629,6 +4342,8 @@ "ui.3d_mouse_section": "الفأرة ثلاثية الأبعاد", "ui.3d_mouse_show_in_view": "إظهار الفأرة ثلاثية الأبعاد في العرض ثلاثي الأبعاد", "ui.3d_mouse_show_in_view_tip": "صورة للفأرة ثلاثية الأبعاد في الزاوية السفلية اليسرى، تتحرك كلما حرّكتها.", + "ui.3d_mouse_sketch_orbit": "تدوير الرسومات بالفأرة ثلاثية الأبعاد", + "ui.3d_mouse_sketch_orbit_tip": "تدير الفأرة ثلاثية الأبعاد العرض أيضًا أثناء فتح رسم ورؤيته من الأمام مباشرة، كما تفعل الفأرة. عند الإيقاف: تُزيح الرسم وتكبّره فقط حتى تُميل العرض.", "ui.3d_mouse_skip": "جهازي لا يستطيع ذلك", "ui.3d_mouse_skip_tip": "يتخطى هذه الحركة في الاتجاهين، وتستبعدها المعايرة.", "ui.3d_mouse_speed": "سرعة الفأرة ثلاثية الأبعاد", @@ -3657,6 +4372,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "لُفّ الغطاء عكس عقارب الساعة، وأمسكه، ثم اتركه.", "ui.3d_mouse_switch_cap": "المعايرة كجهاز العودة إلى المركز", "ui.3d_mouse_switch_trackball": "المعايرة ككرة تتبّع", + "ui.3d_mouse_use_direct": "المشغل المباشر", + "ui.3d_mouse_use_direct_tip": "قراءة الفأرة ثلاثية الأبعاد مباشرة (hidraw) بدلًا من المرور عبر spacenavd.", "ui.3d_mouse_view_axis": "محور العرض", "ui.3d_mouse_view_off": "متوقف", "ui.3d_mouse_view_off_tip": "ملف تعريف مشغّل الفأرة ثلاثية الأبعاد يوقف هذا المحور، فلا تحرك حركتُه العرض. اختيار حركة محور آخر هنا يبادل بينهما، فتتوقف تلك الحركة عن تحريك العرض.", @@ -3695,6 +4412,8 @@ "ui.agent_chat_auth_terminal": "شغّل هذا في الطرفية، ثم اضغط «اتصال» مرة أخرى:", "ui.agent_chat_auth_title": "تسجيل الدخول إلى الوكيل", "ui.agent_chat_cancel": "إلغاء", + "ui.agent_chat_cancel_timeout": "لم يستجب الوكيل لطلب الإيقاف، فتم قطع الاتصال به. أعد الاتصال للمتابعة.", + "ui.agent_chat_cannot_start": "مثبّت، لكنه لا يبدأ: {error}", "ui.agent_chat_changes": "التغييرات: {n}، خطوة تراجع واحدة", "ui.agent_chat_changes_n": "{n} تغييرات", "ui.agent_chat_changes_of": "{n}/{limit} تغييرات", @@ -3703,11 +4422,13 @@ "ui.agent_chat_command": "أمر الوكيل", "ui.agent_chat_connect": "اتصال", "ui.agent_chat_copy": "نسخ", + "ui.agent_chat_copy_message": "نسخ الرسالة", "ui.agent_chat_ctx_bodies": "الأجسام", "ui.agent_chat_ctx_elements": "العناصر", "ui.agent_chat_ctx_features": "الميزات", "ui.agent_chat_ctx_more": "+{n} أخرى", "ui.agent_chat_ctx_other": "أخرى", + "ui.agent_chat_custom_heading": "نموذج مخصص", "ui.agent_chat_custom_hint": "أي برنامج يتحدث بروتوكول Agent Client Protocol عبر stdin وstdout. لا تشغّله أي صدفة أوامر.", "ui.agent_chat_denied": "مرفوض", "ui.agent_chat_deny": "رفض", @@ -3751,8 +4472,16 @@ "ui.agent_chat_mode_all": "الكل", "ui.agent_chat_mode_ask": "السؤال", "ui.agent_chat_mode_edits": "التعديلات", + "ui.agent_chat_model_custom": "استخدام المخصص: {model}", "ui.agent_chat_model_no_tools": "لا يستطيع {model} استخدام أدوات SolidCraft، لذا يمكنه المحادثة فقط. اختر نموذجًا يدعم الأدوات.", + "ui.agent_chat_model_rejected": "لم يقبل الوكيل {model}: {error}", + "ui.agent_chat_model_search": "البحث عن النماذج…", "ui.agent_chat_model_tip": "النموذج الذي يستخدمه الوكيل. يُحفظ اختيارك لهذا الوكيل.", + "ui.agent_chat_models_failed": "تعذّر جلب قائمة النماذج: {error}", + "ui.agent_chat_models_heading": "النماذج المتاحة", + "ui.agent_chat_models_listing": "جارٍ جلب قائمة النماذج…", + "ui.agent_chat_models_none": "لا تسرد نقطة النهاية أي نماذج", + "ui.agent_chat_models_not_a_list": "لم يكن الرد قائمة نماذج", "ui.agent_chat_new": "محادثة جديدة", "ui.agent_chat_new_confirm": "بدء محادثة جديدة؟ ستُمسح المحادثة الحالية.", "ui.agent_chat_next_picture": "الصورة التالية", @@ -3761,6 +4490,7 @@ "ui.agent_chat_no_images": "هذا الوكيل لا يقبل الصور", "ui.agent_chat_no_picture": "لا توجد صورة في الحافظة", "ui.agent_chat_no_tool_call": "لم يستخدم النموذج أدوات SolidCraft، لذا لم يتغيّر التصميم. اختر نموذجًا يدعم استدعاء الأدوات؛ راجع «النماذج المحلية» في دليل محادثة الوكيل.", + "ui.agent_chat_node_too_old": "إصدار Node.js {version} قديم جدًا لهذا الوكيل. ثبّت Node.js 20.10 أو أحدث، ثم اضغط تحديث.", "ui.agent_chat_none_found": "لم يُعثر على وكيل برمجي. ثبّت أحد هذه ثم اضغط تحديث:", "ui.agent_chat_none_found_short": "لم يُعثر على وكيل", "ui.agent_chat_not_installed": "غير مثبت", @@ -3787,9 +4517,12 @@ "ui.agent_chat_queued_stopped": "في الانتظار (متوقف، لم يُرسل)", "ui.agent_chat_refresh": "تحديث", "ui.agent_chat_refused": "غير مسموح للوكيل: {reason}", + "ui.agent_chat_reinstall": "{agent} مثبّت ({program})، لكنه لم يبدأ عندما فحصه SolidCraft: {error}\nقد يكون تثبيته غير مكتمل، أو مُعدًّا لنوع آخر من الحواسيب. ثبّته من جديد بالأمر `{install}`، وتحقّق من أنه يعرض رقم إصداره في الطرفية، ثم اضغط تحديث.", "ui.agent_chat_remove": "إزالة من قائمة الانتظار", "ui.agent_chat_remove_file": "إزالته من هذه الرسالة", "ui.agent_chat_remove_imported": "إزالته من هذه الرسالة؛ تبقى القطعة في التصميم (التراجع يزيلها)", + "ui.agent_chat_reply_cut_off": "بلغ الرد حد طوله قبل أن يكتمل، لذا قد يكون ناقصًا. اطلب من الوكيل أن يتابع، أو أن يجيب بإيجاز أكبر.", + "ui.agent_chat_reply_declined": "رفض النموذج الإجابة عن هذه الرسالة.", "ui.agent_chat_retry": "إعادة المحاولة", "ui.agent_chat_right": "يمين", "ui.agent_chat_save": "حفظ", @@ -3798,7 +4531,7 @@ "ui.agent_chat_send_now_tip": "إيقاف خطوة الوكيل الحالية وإرسال هذه بعدها (Ctrl+Enter)", "ui.agent_chat_setup_body": "يتواصل SolidCraft مع وكيل برمجة مثبّت على هذا الحاسوب. اختر واحدًا من التفضيلات › الوكيل.", "ui.agent_chat_setup_title": "إعداد مساعد", - "ui.agent_chat_side": "جانب محادثة الوكيل", + "ui.agent_chat_side": "تثبيت المحادثة", "ui.agent_chat_signed_in": "سجّل الدخول", "ui.agent_chat_state_auth": "يلزم تسجيل الدخول", "ui.agent_chat_state_busy": "جارٍ العمل…", @@ -3848,24 +4581,29 @@ "ui.ai_copy_suffix": "نسخة", "ui.ai_custom_url": "عنوان URL مخصص", "ui.ai_default": "الافتراضي", + "ui.ai_edit": "تعديل", + "ui.ai_edit_agent_title": "تعديل الوكيل", + "ui.ai_edit_gone": "أُزيل هذا الوكيل، لذا لا يوجد ما يُحفظ.", + "ui.ai_edit_tip": "غيّر اسم هذا الوكيل أو أمره أو نقطة الاتصال الخاصة به. يبقى المفتاح المحفوظ مخفيًا.", "ui.ai_http_busy": "نقطة النهاية مشغولة أو تجاوزت حدها؛ حاول لاحقًا", "ui.ai_http_key": "رفضت نقطة النهاية المفتاح: تحقق منه في التفضيلات › الذكاء الاصطناعي", "ui.ai_http_not_found": "لا توجد نقطة نهاية أو نموذج بهذا الاسم: تحقق من عنوان URL الأساسي واسم النموذج", "ui.ai_http_too_large": "المحادثة أكبر من أن تقبلها نقطة النهاية هذه؛ ابدأ محادثة جديدة", "ui.ai_key": "مفتاح API", "ui.ai_key_hint": "اختياري؛ يُحفظ في سلسلة مفاتيح النظام", + "ui.ai_key_keep_hint": "اتركه فارغًا للإبقاء على المفتاح المحفوظ", "ui.ai_key_needs_https": "لا يُرسل المفتاح إلا عبر HTTPS أو إلى هذا الحاسوب.", "ui.ai_key_note": "يُخزّن في سلسلة مفاتيح النظام، وليس في إعدادات SolidCraft أبدًا. اتركه فارغًا لخادم محلي.", "ui.ai_keychain_error": "رفضت سلسلة مفاتيح النظام: {error}", "ui.ai_kind": "النوع", - "ui.ai_mode_all": "السماح بكل شيء", + "ui.ai_mode_all": "تنفيذ كل شيء", "ui.ai_mode_all_note": "لا شيء يسأل أولًا. تبقى تقارير الأعطال محظورة وتظل حدود المجلدات سارية.", "ui.ai_mode_all_warning": "يمكن للوكيل حفظ تصميمك والكتابة فوقه وتصديره واستبداله دون سؤال. استخدم هذا فقط مع وكيل تثق به، وعلى تصاميم حفظتها.", - "ui.ai_mode_ask": "السؤال في كل مرة", + "ui.ai_mode_ask": "السؤال أولًا", "ui.ai_mode_ask_note": "كل تغيير في التصميم وكل إجراء على الملفات ينتظر سماحك.", - "ui.ai_mode_edits": "السماح تلقائيًا بتعديلات النموذج", + "ui.ai_mode_edits": "إجراء تعديلات", "ui.ai_mode_edits_note": "أوامر النمذجة تعمل دون سؤال؛ أما الحفظ والفتح والتصدير وإجراءات الملفات أو الإجراءات الهدّامة الأخرى فتسأل.", - "ui.ai_mode_global": "كما هو مضبوط أعلاه", + "ui.ai_mode_global": "كما في الأعلى", "ui.ai_model": "النموذج", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "هذه الإعدادات تغطي أدوات SolidCraft. أدوات الوكيل الخاصة (الصدفة وتعديل الملفات) تتبع وضع الوكيل الخاص، الذي تختاره في رأس لوحة المحادثة عندما تكون للوكيل أوضاع.", @@ -3880,14 +4618,18 @@ "ui.ai_permissions": "الأذونات", "ui.ai_preset": "إعداد مسبق", "ui.ai_protocol": "البروتوكول", + "ui.ai_reasoning_effort": "جهد الاستدلال", + "ui.ai_reasoning_effort_field_hint": "فارغ = الافتراضي للمزوّد", + "ui.ai_reasoning_effort_hint": "اختياري. يُرسل إلى نقطة النهاية على أنه `reasoning_effort`؛ تختلف القيم المقبولة حسب المزوّد (مثل `low` أو `high` أو `max`). لا تستبدل SolidCraft القيمة التي تحددها هنا أبدًا. اتركه فارغًا لعدم إرسال شيء والاحتفاظ بالافتراضي للمزوّد.", "ui.ai_remove": "إزالة", "ui.ai_request_timed_out": "استغرق النموذج أكثر من {seconds} ثانية. يمكنك رفع مهلة الطلب لنقطة النهاية هذه من التفضيلات › المساعد.", "ui.ai_request_timeout": "مهلة الطلب", "ui.ai_request_timeout_hint": "المدة التي يمكن أن يستغرقها طلب واحد للنموذج إلى نقطة النهاية هذه، من 30 ثانية إلى ساعة. ارفعها للنماذج المحلية البطيئة.", "ui.ai_reset": "إعادة تعيين", + "ui.ai_save": "حفظ", "ui.ai_settings": "إعدادات الذكاء الاصطناعي…", "ui.ai_show_features": "إظهار ميزات الذكاء الاصطناعي", - "ui.ai_show_features_note": "محادثة الوكيل: لوحة يعمل فيها وكيل برمجي تستخدمه أصلًا، أو نقطة نهاية نموذج تختارها، على التصميم المفتوح. عند الإيقاف: لا زر ولا اختصار ولا عنصر قائمة ولا لوحة للذكاء الاصطناعي، ولا يُبحث عن شيء أو يُشغّل.", + "ui.ai_show_features_note": "إيقافه يخفي المساعد في كل مكان ولا يبدأ أي شيء. تصبح كل الخيارات أدناه باهتة.\n\nمحادثة الوكيل: لوحة يعمل فيها وكيل برمجي تستخدمه أصلًا، أو نقطة نهاية نموذج تختارها، على التصميم المفتوح. عند الإيقاف: لا زر ولا اختصار ولا عنصر قائمة ولا لوحة للذكاء الاصطناعي، ولا يُبحث عن شيء أو يُشغّل.", "ui.ai_switch_tip": "تغيير الوكيل لهذه المحادثة", "ui.ai_test": "اختبار", "ui.ai_test_acp_ok": "يجيب: {agent}", @@ -3921,7 +4663,7 @@ "ui.ai_tool_sum_then": "{first}، ثم {next}", "ui.ai_tool_unfold": "انقر لعرض ما أعاده", "ui.ai_tool_waiting": "بالانتظار", - "ui.ai_toolbar_button": "إظهار الزر في شريط الأدوات", + "ui.ai_toolbar_button": "زر المساعد في شريط التطبيق", "ui.ai_toolbar_button_note": "زر الذكاء الاصطناعي في الطرف الأيمن من شريط الأدوات. يظل Ctrl+Shift+A وقائمة العرض يفتحان اللوحة.", "ui.ai_undo_tip": "التراجع عن كل ما غيّره الوكيل لهذه الرسالة، بخطوة واحدة", "ui.ai_url_hint": "https://example.com/v1", @@ -3968,11 +4710,14 @@ "ui.centerline": "خط المركز", "ui.chain": "سلسلة", "ui.chamfer": "شطف", + "ui.chamfer_angle": "زاوية الشطف", + "ui.chamfer_depth": "عمق الشطف", "ui.chamfer_type": "نوع الشطف", "ui.change_workspace": "تغيير مساحة العمل", "ui.circle": "دائرة", "ui.circular_pattern": "نمط دائري", "ui.clear": "مسح", + "ui.clear_print_face": "مسح وجه الطباعة", "ui.clear_recent": "مسح الأخيرة", "ui.clear_the_selection": "مسح التحديد", "ui.click_selects_whole_bodies": "النقر يحدد الأجسام كاملة", @@ -3997,10 +4742,16 @@ "ui.colour_vision_sample": "عيّنة", "ui.colour_vision_tritan": "ضعف الأزرق", "ui.colour_vision_tritan_tip": "لضعف أو غياب الإحساس باللون الأزرق", + "ui.comb_length": "طول المشط", + "ui.comb_length_tip": "طول الأسنان: مضاعف للطول التلقائي الذي يجعل أطول سنّ خُمس حجم المنحنيات المعروضة.", + "ui.comb_teeth": "الأسنان", + "ui.comb_teeth_tip": "عدد أسنان كل مشط، موزّعة بالتساوي على طول المنحنى. كلما زادت الأسنان ظهرت تفاصيل أكثر عن تغيّر الانحناء.", "ui.combine": "دمج", "ui.coming_later": "قريبًا", "ui.command_done": "تم {command}", "ui.command_palette_hint": "اكتب أمرًا، مثل {example} — أو اضغط S للبحث", + "ui.components_from_bodies_hint": "أنشئ مكوّنًا لكل جسم محدد، باسم ذلك الجسم، ضمن المكوّن النشط.", + "ui.components_from_bodies_required": "حدد جسمًا واحدًا على الأقل.", "ui.concentric": "متحد المركز", "ui.cone": "مخروط", "ui.conic_curve": "منحنى مخروطي", @@ -4013,15 +4764,30 @@ "ui.construction.contact_hint": "مماس: اختر دائرة/قوسًا أو منحنى شريحيًا/قطعًا مخروطيًا مفتوحًا ثم نقطة التماس (للمنحنيات الحرة: النهايات فقط)", "ui.construction.external_hint": "مماس: اختر دائرة أو قوسًا ثم نقطة خارجية ثم الحل المطلوب", "ui.construction.free_hint": "خط إنشائي: انقر نقطتين؛ انقر بزر الفأرة الأيمن للبدء من جديد", + "ui.construction.normal_needs_length": "الخط اللانهائي إنشائي دائمًا: اكتب طولًا لرسم خط عادي", "ui.construction.point_hint": "خط إنشائي: انقر نقطة المرور", "ui.construction.reference_hint": "خط إنشائي: اختر خطًا مستقيمًا ثم نقطة؛ انقر بزر الفأرة الأيمن لتغيير المرجع", "ui.construction.ribbon_label": "خطوط مساعدة", + "ui.construction.side_hint": "خط إنشائي: انقر الجهة التي يمتد نحوها الخط؛ انقر بزر الفأرة الأيمن للبدء من جديد", "ui.context_menu": "القائمة السياقية", - "ui.continuity_g0": "G0 تجعّد", + "ui.continuity_crease": "ثنية", + "ui.continuity_curvature": "الانحناء", + "ui.continuity_curvature_change": "تغيّر الانحناء", + "ui.continuity_curvature_change_tip": "تغيّر الانحناء (G3): يتغير الانحناء أيضًا بسلاسة عبر خط الالتقاء.", + "ui.continuity_curvature_tip": "متصل الانحناء (G2): تمر الانعكاسات دون انكسار.", + "ui.continuity_g0": "G0 ثنية", "ui.continuity_g1": "G1 مماس", "ui.continuity_g2": "G2 انحناء", "ui.continuity_gap": "فجوة", + "ui.continuity_position": "الموضع", + "ui.continuity_position_tip": "الموضع (G0): تلتقي الأسطح، مع ثنية عند التقائها.", + "ui.continuity_smooth_curvature_change": "تغيّر انحناء سلس", + "ui.continuity_smooth_curvature_change_tip": "تغيّر انحناء سلس (G4): حتى طريقة تغيّر الانحناء تستمر بسلاسة عبر خط الالتقاء.", + "ui.continuity_tangent": "مماس", + "ui.continuity_tangent_tip": "مماس (G1): لا ثنية، لكن الانحناء يقفز عبر خط الالتقاء.", "ui.copy": "نسخ", + "ui.copy_details": "نسخ التفاصيل", + "ui.copy_details_tip": "انسخ الرسالة كاملة للبحث عنها أو للإبلاغ عنها.", "ui.corner": "زاوية", "ui.corners": "الزوايا", "ui.cosmetic_thread_markings": "علامات السن اللولبي الشكلية", @@ -4043,6 +4809,8 @@ "ui.dark": "داكن", "ui.default_modelling_orientation": "اتجاه النمذجة الافتراضي", "ui.delete": "حذف", + "ui.delete_select_first": "حدّد أولًا ما تريد حذفه: الميزات أو الأجسام أو المكوّنات أو هندسة الرسم", + "ui.dependents_select_first": "حدّد أولًا ما تريد سرد معتمداته", "ui.depth": "العمق", "ui.design": "التصميم", "ui.design_properties.author": "المؤلف", @@ -4057,6 +4825,40 @@ "ui.design_properties.project": "المشروع", "ui.design_properties.revision": "المراجعة", "ui.design_saved": "تم الحفظ في {path}", + "ui.details_access_caption": "توضح الأوجه ما إذا كان بإمكان الأداة الوصول إليها من الاتجاه المحدد.", + "ui.details_angle": "الزاوية", + "ui.details_continuity_caption": "حرّر الوصلة المحددة. تحتفظ الوصلات الأخرى بإعداداتها الخاصة.", + "ui.details_continuity_stale": "هندسة سابقة: أعد تشغيل التحليل لتحرير هذه الوصلة أو ملاءمة العرض لها.", + "ui.details_copy_list": "نسخ القائمة", + "ui.details_curvature": "تفاوت الانحناء", + "ui.details_curvature_caption": "تُلوَّن الأوجه وفقًا لنصف قطر الانحناء المحلي لها.", + "ui.details_direction": "اتجاه الأداة", + "ui.details_draft_caption": "تُلوَّن الأوجه وفقًا لزاويتها بالنسبة إلى اتجاه السحب.", + "ui.details_edit_seam": "تحرير الوصلة", + "ui.details_fixture": "نموذج عرض لمكوّن الواجهة — بيانات توضيحية فقط", + "ui.details_fixture_caption": "نموذج عرض لمكوّن الواجهة بقيم توضيحية؛ هذه ليست نتيجة من النموذج الهندسي.", + "ui.details_fixture_problem": "مثال على نتيجة تشير إلى مشكلة", + "ui.details_fixture_readout": "مثال على قيمة مقاسة", + "ui.details_flip": "قلب", + "ui.details_gap": "الفجوة", + "ui.details_hatch": "تهشير أوجه القطع", + "ui.details_jump": "قفزة الانحناء", + "ui.details_key": "مفتاح الألوان", + "ui.details_offset": "إزاحة", + "ui.details_plane": "مستوى", + "ui.details_pull": "اتجاه السحب", + "ui.details_radius": "نصف القطر", + "ui.details_readout": "القراءات", + "ui.details_samples": "العينات", + "ui.details_seam": "{body} · حافة {edge}", + "ui.details_settings": "الإعدادات", + "ui.details_sharp_gap": "حافة حادة أو فجوة", + "ui.details_show_all": "عرض الكل ({count})", + "ui.details_smooth": "أملس", + "ui.details_stripes": "الخطوط", + "ui.details_target": "ملاءمة العرض للهندسة", + "ui.details_worst_seams": "الوصلات الأقل استمرارية", + "ui.details_zebra_caption": "تُظهر الخطوط المنعكسة مدى سلاسة اتصال الأوجه.", "ui.diameter": "القطر", "ui.dimension": "البُعد", "ui.direct_interaction": "التفاعل المباشر", @@ -4101,39 +4903,78 @@ "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", "ui.edit_in_place_wait": "انتظر حتى ينتهي ما يجري في التصميم", "ui.edit_section_analysis": "تعديل تحليل المقطع", + "ui.edit_sketch_empty": "لا توجد رسومات لتعديلها", "ui.ellipse": "قطع ناقص", "ui.emboss_wrap_note": "تلتف ملامح الخطوط المتعامدة المماسة لأسطوانة مدعومة تلقائيًا. اختر جدارًا لتحديد الهدف.", + "ui.end": "النهاية", "ui.end_radius": "نصف قطر النهاية", "ui.end_scale": "مقياس النهاية", + "ui.ends": "الطرفان", "ui.entities": "العناصر", "ui.equal": "متساوٍ", "ui.equation_end": "النهاية", "ui.equation_explicit": "صريح", "ui.equation_form": "الشكل", "ui.equation_note": "المتغير رقم بلا وحدة: تأخذه sin(t) بالراديان. والنتيجة التي بلا وحدة تكون بوحدة التصميم.", + "ui.equation_note_range": "المتغير طول مثل نطاقه: يمكن دمجه مع معاملات الطول، واقسمه على طول قبل تمريره إلى sin(). والنتيجة التي بلا وحدة تكون بوحدة التصميم.", "ui.equation_parametric": "بارامتري", + "ui.equation_variable_unit": "المتغير يأخذ وحدة النطاق", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "نصف القطر المكافئ", "ui.expand": "توسيع", + "ui.explode_needs_two_components": "يُبعد العرض المفكك المكوّنات بعضها عن بعض، لذا يحتاج التصميم إلى مكوّنين أو أكثر (مكوّن جديد، أو إدراج تصميم، أو إنشاء مكوّنات من الأجسام)", "ui.exportDxf": "تصدير DXF…", "ui.export_ellipsis_keymap": "تصدير…", "ui.export_keymap_tip": "المفاتيح ومفضلات مربع S وشريط الأدوات، كملف", "ui.extend": "تمديد", + "ui.extent": "الامتداد", "ui.extent_type": "نوع الامتداد", "ui.extract_component": "استخراج إلى ملف…", "ui.extract_design_changed": "تغيّر التصميم أثناء اختيار الملف. ابدأ الاستخراج إلى ملف من جديد.", "ui.extract_done": "أصبح المكوّن تصميمًا مستقلًا، مرتبطًا هنا.", "ui.extrude": "بثق", "ui.extrude_auto_to_object": "البثق إلى هدف مختار", - "ui.extrude_auto_to_object_tip": "في البثق، مع اختيار مقطع، يؤدي اختيار وجه أو رأس أو مستوى موازٍ خارج مستواه إلى تبديل الامتداد إلى «إلى كائن»", + "ui.extrude_auto_to_object_tip": "وجه أو رأس أو مستوى موازٍ يغيّر الامتداد إلى «إلى كائن».", "ui.factor": "المعامل", + "ui.fade": "تلاشٍ", + "ui.fade_length": "طول التلاشي", "ui.feature_history": "سجل الميزات", "ui.feature_options": "خيارات الميزة", "ui.features": "الميزات", "ui.file": "ملف", "ui.fillet": "تقويس", + "ui.fillet_corner_ball": "كرة", + "ui.fillet_corner_ball_tip": "جزء من سطح الكرة المتدحرجة، مماسّ (G1) لكل تقويس.", + "ui.fillet_corner_curvature_tip": "الانحناء (G2): رقعة ناعمة. تُرجَع الزاوية على طول كل حافة بمقدار الإرجاع ({factor} ضعف نصف القطر ما لم تكتب قيمة) وتُملأ برقعة، فتمر الانعكاسات عبرها دون انكسار.", + "ui.fillet_corner_needs_constant": "زوايا الرقعة الناعمة (G2) تتطلب نصف قطر ثابتًا وملاءمة دقيقة لنصف القطر.", + "ui.fillet_corner_patch": "رقعة ناعمة", + "ui.fillet_corner_patch_tip": "متصل الانحناء (G2): تُرجَع الزاوية على طول كل حافة وتُملأ برقعة، فتمر الانعكاسات عبرها دون انكسار.", + "ui.fillet_corner_tangent_tip": "مماس (G1): زاوية بالكرة المتدحرجة، جزء من سطح الكرة المتدحرجة مماسّ لكل تقويس.", + "ui.fillet_error_corner": "تعذّر بناء الزاوية الناعمة هنا. جرّب مسافة إرجاع أخرى، أو زوايا مماسّة.", + "ui.fillet_error_failed": "تعذّر بناء هذا التقويس على هذه الحواف. جرّب نصف قطر آخر، أو قوّس حوافّ أقل في المرة الواحدة.", + "ui.fillet_error_setback_short": "مسافة الإرجاع قصيرة جدًا على رقعة هذه الزاوية: تُبنى ابتداءً من {least}. جرّب مسافة إرجاع أطول.", + "ui.fillet_error_too_large": "نصف القطر كبير جدًا على الوجوه المجاورة لهذه الحواف. جرّب نصف قطر أصغر، أو اختر في «حدود الوجوه» الخيار «أكبر نصف قطر».", + "ui.fillet_fit": "حدود الوجوه", + "ui.fillet_fit_exact": "نصف قطر دقيق", + "ui.fillet_fit_needs_constant": "ملاءمة نصف القطر تتطلب نصف قطر ثابتًا.", + "ui.fillet_fit_reduce": "أكبر نصف قطر", + "ui.fillet_fit_taper": "نصف قطر مُضيَّق", + "ui.fillet_fit_tip": "عندما يكون نصف القطر أكبر مما تسمح به الوجوه المجاورة للحافة.\nنصف قطر دقيق: نصف القطر كما هو، أو لا تقويس ورسالة توضّح السبب.\nأكبر نصف قطر: تُقوَّس كل حافة بأكبر نصف قطر يتّسع.\nنصف قطر مُضيَّق: يبقى نصف القطر، ويُضيَّق التقويس فقط حيث تنتهي الوجوه.", + "ui.fillet_options_tip": "سلسلة مماسّة: قوّس أيضًا الحواف التي تتصل بسلاسة بالحواف المختارة.\nمعاينة: اعرض النتيجة في العرض أثناء التحرير.", + "ui.fillet_setback": "مسافة الإرجاع", + "ui.fillet_setback_hint": "{factor} × نصف القطر", + "ui.fillet_setback_least": "أكثر من {least}", + "ui.fillet_setback_tip": "حيث تبدأ رقعة الزاوية الناعمة: المسافة على طول كل حافة من الزاوية. الافتراضي {factor} ضعف نصف القطر. يجب أن تكون أكبر من أقل مسافة إرجاع، وهي التي تلتقي عندها التقويسات دون إرجاع: نصف القطر حين تكون الأوجه متعامدة.", + "ui.fillet_smooth_radius": "تغيّر ناعم لنصف القطر", + "ui.fillet_turn": "الالتفاف", + "ui.fillet_turn_mitre": "وصلة مائلة", + "ui.fillet_turn_swept": "ملتف", + "ui.fillet_turn_tip": "حيث يلتف تقويسان حول حافة ركن حادة بينهما، مثل التقويسات على قاعدة نتوء عند حوافه القائمة.\nوصلة مائلة: يمتد التقويسان حتى يلتقيا في وصلة مائلة.\nملتف: يتوقف التقويسان عند حافة الركن ويلتفان حولها، والركن طارة مماسة لكليهما. فقط لتقويسين بنصف قطر واحد حول حافة ركن مستقيمة ومحدبة.", + "ui.fillet_type_choices_tip": "نصف قطر ثابت: نصف قطر واحد على طول الحافة.\nطول الوتر: يبقى عرض التقويس نفسه مهما كانت الزاوية بين الوجوه.\nنصف قطر متغيّر: نصف قطر عند كل طرف، ومزيد على طول الحافة إن أضفته.\nمتصل الانحناء: مقطع بلا انكسار في الانعكاسات حيث يلتقي بالوجوه المستوية (G2).\nمنحنى شريحي: يتبع نصف القطر على طول الحافة أنصاف أقطار تحكّم تحدّدها.", + "ui.fillet_type_curvature": "متصل الانحناء", + "ui.fillet_type_tip": "المقطع عبر الحافة. متصل الانحناء: مقطع متصل الانحناء (G2) بين وجوه مستوية، فتمر الانعكاسات من الوجوه إلى التقويس دون انكسار.", "ui.filter_commands_or_keys": "تصفية الأوامر أو المفاتيح", "ui.findInTimeline": "البحث في الخط الزمني", "ui.findInWindow": "البحث في النافذة", @@ -4242,13 +5083,15 @@ "ui.hideOrigin": "إخفاء نقطة الأصل", "ui.hidePlanes": "إخفاء المستويات", "ui.hideProfile": "إخفاء المقطع", - "ui.hide_origin_by_default": "إخفاء نقطة الأصل افتراضيًا", + "ui.hide_component_history": "إخفاء سجله", + "ui.hide_origin_by_default": "إخفاء مجلد نقطة الأصل في التصاميم الجديدة", "ui.hide_origin_note": "تبدأ التصاميم الجديدة ومجلد نقطة الأصل مخفي. يحتفظ كل تصميم بإعداد نقطة الأصل الخاص به بمجرد إظهارها أو إخفائها.", "ui.history_back": "الرجوع خطوة", "ui.history_below_browser": "أسفل المستعرض", "ui.history_edge_hint": "انقر مرتين على الحافة", "ui.history_first": "الذهاب إلى البداية", "ui.history_forward": "التقدم خطوة", + "ui.history_hide_hidden": "إخفاء المكوّنات المخفية", "ui.history_hide_names": "إخفاء الأسماء", "ui.history_last": "الذهاب إلى النهاية", "ui.history_marker_tip": "مؤشر السجل: اسحبه لإرجاع النموذج، والميزات الجديدة تُضاف هنا", @@ -4258,10 +5101,12 @@ "ui.history_play_button_show": "إظهار زر التشغيل", "ui.history_play_finish_action": "أكمل الإجراء الحالي قبل تشغيل السجل", "ui.history_play_roll_back": "أعد مؤشر السجل إلى الخلف قبل التشغيل", + "ui.history_show_hidden": "إظهار المكوّنات المخفية", "ui.history_show_names": "إظهار الأسماء", "ui.history_sketch_listed_under": "مدرج تحت {feature}", "ui.history_title": "السجل", "ui.history_toggle_names": "إظهار أسماء الميزات أو إخفاؤها", + "ui.history_waits_for_editor": "ينتظر التراجع والإعادة والسجل حتى يكتمل فتح محرر الميزة", "ui.hole": "ثقب", "ui.hole_tap_type": "نوع لولبة الثقب", "ui.hole_type": "نوع الثقب", @@ -4277,7 +5122,9 @@ "ui.insert_design.saved_file": "في {name} تغييرات غير محفوظة، لذا أُدرج ملفه المحفوظ. احفظه، ثم استخدم تحديث الروابط لإدخال التغييرات.", "ui.insert_design.unsaved": "تغييرات غير محفوظة", "ui.inspect": "فحص", + "ui.instances": "النسخ", "ui.intersect": "تقاطع", + "ui.iso_4753": "ISO 4753", "ui.isolate": "عزل", "ui.join": "ضم", "ui.joint_play": "▶ تشغيل", @@ -4285,12 +5132,14 @@ "ui.joints": "المفاصل", "ui.keyboard_shortcuts": "الاختصارات", "ui.language": "اللغة", + "ui.lasso_select": "التحديد الحر (ارسم حلقة حرة بالسحب: يحدّد ما يقع داخلها بالكامل)", "ui.layout_compact": "مضغوط", "ui.layout_floating": "عائم", "ui.length": "الطول", "ui.length_decimals": "المنازل العشرية للأطوال", "ui.light": "فاتح", "ui.line": "خط", + "ui.line_arc_hint": "قوس مماسي: انقر نهاية القوس. توقف عند آخر نقطة مرة أخرى للعودة إلى الخطوط؛ انقر بالزر الأيمن أو اضغط Esc للإنهاء", "ui.link_copies": "ربط النسخ المتطابقة", "ui.link_copies_keep": "إبقاء", "ui.link_copies_link": "ربط", @@ -4378,7 +5227,9 @@ "ui.part_size_needs_a_part": "حدد قطعة قياسية مُدرجة (برغي أو صامولة أو حلقة مسطحة أو مسمار) لتغيير مقاسها. لتكبير جسم أو تصغيره، استخدم «تحجيم».", "ui.part_size_shared": "يعيد بناء القطعة مستبدلًا أي ميزات مضافة. تتحدث كل نسخ هذا المكوّن.", "ui.paste": "لصق", + "ui.patch_continuity_corner_tip": "تلتقي الرقعة بالأوجه المحيطة بها بالاستمرارية المختارة على طول كل جانب. وعند زاوية تلتقي فيها تلك الأوجه بعضها ببعض بانحناءات مختلفة، تبقى مماسّة (G1) هناك.", "ui.path": "المسار", + "ui.pattern_object_type_tip": "الأجسام: أشكال مصمتة تُختار في العرض أو في المستعرض؛ يُنسخ كل منها كاملًا.\nالميزات: خطوات في السجل، مثل بثق أو ثقب، تُختار في السجل أو على وجه صنعته؛ تتكرر الخطوة.\nالرسم ليس أيًّا منهما: كرّر منحنياته بأداة النمط أو المرآة داخل الرسم، أو ابثقه أولًا.", "ui.pattern_on_path": "نمط على مسار", "ui.perforate_margin_default": "من القطر", "ui.perforate_pitch": "الخطوة", @@ -4393,7 +5244,7 @@ "ui.pitch": "الخطوة", "ui.placement": "الموضع", "ui.placement_handles": "مقابض الموضع", - "ui.placement_handles_tip": "مقابض على معاينة المسند أو النتوء أو وصلة الكبس: اسحب العلامة لتحريكها على النموذج، وأدِرها من حلقتها", + "ui.placement_handles_tip": "علامة لسحب الميزة عبر النموذج وحلقة لتدويرها.", "ui.plane": "المستوى", "ui.plane_at_angle": "مستوى بزاوية", "ui.plugins": "الإضافات", @@ -4405,12 +5256,17 @@ "ui.plugins_skipped": "تعذّرت قراءة {count} مجلد(ات).", "ui.plugins_version": "{version}", "ui.point": "نقطة", + "ui.point_cloud_add_filter": "إضافة مرشح…", "ui.point_cloud_auto_range": "نطاق تلقائي", "ui.point_cloud_color_by": "التلوين حسب", "ui.point_cloud_file_colors": "ألوان الملف", + "ui.point_cloud_filter_by": "التصفية حسب", "ui.point_cloud_height_high": "أعلى ارتفاع", "ui.point_cloud_height_low": "أدنى ارتفاع", + "ui.point_cloud_legend_filter": "تُعرض وتُخفى في وسيلة الإيضاح أعلاه", "ui.point_cloud_no_file_colors": "لا يحتوي الملف على ألوان", + "ui.point_cloud_pause": "إيقاف مؤقت", + "ui.point_cloud_play": "تشغيل", "ui.point_cloud_single_color": "لون واحد", "ui.point_cloud_size": "حجم النقطة", "ui.point_cloud_units": "وحدات الملف", @@ -4419,6 +5275,11 @@ "ui.polygon": "مضلع", "ui.preferences": "التفضيلات", "ui.press_a_key": "اضغط مفتاحًا…", + "ui.print_face_body_not_sent": "جسم هذا الوجه لا يُرسل: أضفه أولًا إلى الأجسام", + "ui.print_face_cleared": "{body}: تم مسح وجه الطباعة", + "ui.print_face_input": "وجه الطباعة", + "ui.print_face_pick": "اختر وجهًا مستويًا واحدًا لجسم صلب لجعله وجه الطباعة", + "ui.print_face_set": "{body}: تم تعيين وجه الطباعة؛ الإرسال إلى برنامج التقطيع يضع الجسم عليه", "ui.profile": "المقطع", "ui.profile_plane": "مستوى المقطع", "ui.profiles": "المقاطع", @@ -4434,6 +5295,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "جارٍ القياس…", + "ui.properties.measuring_bodies": "جارٍ قياس الأجسام… {done} من {total}", "ui.properties.measuring_failed": "توقف القياس قبل أن يكتمل.", "ui.properties.principal_axis": "المحور الرئيسي {number}", "ui.properties.principal_moments": "العزوم الرئيسية", @@ -4501,6 +5363,7 @@ "ui.selectOther": "تحديد آخر…", "ui.selectTangentChain": "تحديد سلسلة مماسية", "ui.select_all": "تحديد الكل", + "ui.select_components_by_face": "تحديد المكوّنات (تحديد وجه يحدّد المكوّن الذي ينتمي إليه)", "ui.selection": "التحديد", "ui.selection_modifiers": "مُعدِّلات التحديد", "ui.selection_shift_add_only": "Shift مع النقر يضيف دون إزالة", @@ -4526,6 +5389,7 @@ "ui.showDimension": "إظهار البُعد", "ui.showOrigin": "إظهار نقطة الأصل", "ui.showPlanes": "إظهار المستويات", + "ui.show_component_history": "إظهار سجله", "ui.show_constraints": "القيود", "ui.show_construction_geometries": "الهندسة المساعدة", "ui.show_dimensions": "الأبعاد", @@ -4540,8 +5404,15 @@ "ui.sketch_intersect_geometry": "الهندسة", "ui.sketch_intersect_projection_link": "رابط الإسقاط", "ui.sketch_intersect_selection_filter": "مرشح التحديد", + "ui.sketch_keys_only": "إبقاء مفاتيح النموذج خارج الرسومات", + "ui.sketch_keys_only_tip": "أثناء تحرير رسم، تعمل مفاتيح الرسم والمفاتيح التي تعمل في كل مكان فقط؛ ولا يفعل مفتاح نموذج مثل E أو F شيئًا، فلا يمكن لمفتاح مضغوط بالخطأ أن يغلق رسمًا ثقيلًا.", "ui.sketch_modifiers": "مُعدِّلات الرسم", "ui.sketch_project_geometry": "الهندسة", + "ui.sketch_report.all_constrained": "كل شيء مقيد بالكامل.", + "ui.sketch_report.dof": "درجات الحرية", + "ui.sketch_report.loose": "غير مقيد بالكامل", + "ui.sketch_report.status": "الحالة", + "ui.sketch_report.title": "تقرير الرسم", "ui.sketch_scale": "تحجيم الرسم", "ui.sketches": "الرسومات", "ui.slice": "تقطيع", @@ -4552,7 +5423,7 @@ "ui.slicer_no_response": "لم يستجب {slicer} في الوقت المحدد. الملف محفوظ مسبقًا في {path}: أرسله مرة أخرى بعد أن يبدأ برنامج التقطيع.", "ui.slicer_resend_hint": "الإرسال مرة أخرى يستبدل الملف المفتوح في برنامج التقطيع.", "ui.slicer_single_instance": "فتح الملفات في برنامج تقطيع يعمل مسبقًا", - "ui.slicer_single_instance_tip": "يحمّل PrusaSlicer وSuperSlicer وCura الملف في النافذة المفتوحة بدلًا من تشغيل نسخة أخرى. أما برامج التقطيع الأخرى فتُشغَّل كما هي. يفعل PrusaSlicer 3.0 هذا دائمًا: لا يقبل مشغّله الملف بأي طريقة أخرى.", + "ui.slicer_single_instance_tip": "لبرامج التقطيع التي تفتح الملف في نافذة قيد التشغيل.", "ui.slicer_starting": "جارٍ تشغيل {slicer}…", "ui.slicer_still_starting": "لا يزال الانتظار جاريًا لبدء {slicer}. لم يُرسل أي شيء آخر.", "ui.slicer_stl_fallback": "تعذّرت كتابة ملف 3MF، لذا هذا ملف STL.", @@ -4571,8 +5442,8 @@ "ui.start": "البداية", "ui.start_over": "البدء من جديد", "ui.start_page": "صفحة البداية", - "ui.step_values": "تغيير القيم بمفاتيح الأسهم وعجلة الفأرة", - "ui.step_values_tip": "في حقل قيمة تكتب فيه، يغيّر السهمان لأعلى ولأسفل الرقم العادي بمقدار 1 (Shift: 10، Alt: 0.1)، وكذلك عجلة الفأرة فوق الحقل. أما التعابير فتبقى كما كُتبت.", + "ui.step_values": "تغيير القيم بالأسهم والعجلة", + "ui.step_values_tip": "يغيّر السهمان لأعلى ولأسفل والعجلة فوق حقل قيمة الرقم فيه.", "ui.stitch_tolerance_hint": "دقيقة", "ui.stretch": "مطّ", "ui.supersampling": "التنعيم الفائق (SSAA)", @@ -4637,19 +5508,31 @@ "ui.view_angles": "زوايا العرض", "ui.view_angles_convention": "درجات حول المحور العلوي. الانعراج 0° هو العرض الأمامي، و90° الأيسر، و−90° الأيمن، و180° الخلفي؛ الانحدار 90° هو العرض العلوي؛ والدوران الموجب يدير النموذج على الشاشة باتجاه عقارب الساعة.", "ui.view_angles_help": "يعرض زوايا الانحدار والانعراج والدوران للعرض بالدرجات ونوع الإسقاط أسفل أداة الاتجاه. انقر على القراءة لكتابة زوايا دقيقة.", + "ui.view_angles_lock": "قفل {axis}", "ui.view_angles_ortho": "متعامد", "ui.view_angles_persp": "منظور", "ui.view_angles_pitch": "الانحدار", "ui.view_angles_readout": "الانحدار {pitch} · الانعراج {yaw} · الدوران {roll}", "ui.view_angles_roll": "الدوران", + "ui.view_angles_unlock": "إلغاء قفل {axis}", "ui.view_angles_yaw": "الانعراج", + "ui.view_angles_zero": "تعيين {axis} إلى 0°", "ui.view_centre": "مركز العرض", "ui.viewport_status_clear": "إيقاف {name}", "ui.viewport_status_clear_hint": "إيقاف {name} · Esc", + "ui.viewport_status_edges": "{count} حواف", + "ui.viewport_status_from": "من {direction}", "ui.viewport_status_key": "إظهار مفتاح الألوان لـ {name}", "ui.viewport_status_minimum_radius": "أقل نصف قطر", "ui.viewport_status_pairs": "{count} أزواج", + "ui.viewport_status_section_hatch": "{setting} · تهشير", + "ui.viewport_status_section_plane": "المستوى الحالي", + "ui.viewport_status_section_tilted": "مائل · {offset}", "ui.viewport_status_stripes": "{count} شريطًا", + "ui.viewport_status_summary_clear": "إيقاف كل شيء", + "ui.viewport_status_summary_heading": "في هذا العرض", + "ui.viewport_status_summary_label": "{name} و{count} عناصر أخرى", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "اتباع السمة", "ui.visual_shaded_hidden_edges": "مظلل مع الحواف المخفية", "ui.visual_shaded_with_edges": "مظلل مع الحواف", @@ -4685,11 +5568,13 @@ "update.available": "SolidCraft {version} متاح", "update.button": "تحديث", "update.button_version": "التحديث إلى {version}", - "update.check_automatically": "التحقق من التحديثات تلقائيًا", + "update.check_automatically": "التحقق عند البدء ومرة يوميًا", + "update.check_for_updates": "التحقق من وجود تحديثات", "update.check_now": "تحقق الآن", + "update.check_unavailable": "التحقق من التحديثات غير متاح لهذا التثبيت.", "update.checking": "جارٍ التحقق…", "update.copy": "نسخ", - "update.dmg_opened": "صورة القرص مفتوحة وموثّقة: اسحب SolidCraft إلى مجلد التطبيقات مستبدلًا النسخة القديمة، ثم أعد تشغيل SolidCraft.", + "update.dmg_opened": "صورة القرص مفتوحة وموثّقة: أنهِ SolidCraft، ثم اسحب SolidCraft الجديد إلى مجلد التطبيقات مستبدلًا النسخة القديمة، ثم افتح SolidCraft من جديد.", "update.download": "تنزيل", "update.download_open": "تنزيل وفتح", "update.downloading": "جارٍ التنزيل والتحقق… {done} من {total} MB", @@ -4733,6 +5618,7 @@ "web.open_link": "فتح التصميم المرتبط؟", "web.open_link_confirm": "توجد تغييرات غير محفوظة. هل تريد فتح التصميم المرتبط في تبويب جديد؟", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ اختيار · Enter / Tab إكمال · Esc إغلاق", + "↑ ↓ choose · Enter applies this value": "↑ ↓ اختيار · Enter يطبّق هذه القيمة", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ اختيار · Enter يطبّق ما كتبته · Esc إغلاق", "⌘Enter continues on GitHub.": "⌘Enter يتابع في GitHub." } diff --git a/assets/locales/bs.json b/assets/locales/bs.json index b025407eb..c620fbe2d 100644 --- a/assets/locales/bs.json +++ b/assets/locales/bs.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "PRELAZNA POVRŠ", "BOUNDARY SURFACE": "GRANIČNA POVRŠ", "BROWSER": "STABLO MODELA", + "Back to the original order": "Nazad na izvorni redoslijed", "Ball": "Kuglasti", "Bar": "Šipka", "Base Center": "Centar osnove", @@ -476,6 +477,7 @@ "Rectangular": "Pravougaoni", "Rectangular Tube": "Pravougaona cijev", "Reference face": "Referentno lice", + "Reference plane": "Referentna ravan", "Relief Depth": "Dubina rasterećenja", "Relief Width": "Širina rasterećenja", "Remove Tools": "Ukloni alate", @@ -555,6 +557,7 @@ "Section": "Presjek", "Section (optional)": "Presjek (neobavezno)", "Section position": "Položaj presjeka", + "Sections": "Presjeci", "Sections (one sketch each)": "Presjeci (po jedna skica)", "Select Other": "Izaberi drugo", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Izaberi drugo: držite lijevo dugme mirno na modelu (ili desni klik › Izaberi drugo…) da prikažete sve ispod pokazivača; ponovo kliknite na isto mjesto da izaberete sljedeći element. Dvaput kliknite srednjim dugmetom za Početni prikaz (Postavke › Navigacija).", @@ -595,6 +598,8 @@ "Snap to face and edge centres": "Privlači na centre lica i ivica", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft ne može slati izvještaje direktno. Pošaljite ih na GitHubu; u aplikaciji nije potreban token.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft se zatvorio prije nego što su ovi dizajni sačuvani. Može se otvoriti njihovo posljednje automatsko čuvanje.", + "Sort A to Z": "Sortiraj od A do Ž", + "Sort Z to A": "Sortiraj od Ž do A", "Spacing 2 must be a non-zero number": "Razmak 2 mora biti broj različit od nule", "Spacing must be a non-zero number": "Razmak mora biti broj različit od nule", "Specialise": "Specijalizuj", @@ -775,6 +780,8 @@ "at the face": "na licu", "bom.group_children": "Poddijelovi u redu svog dijela", "browser.body_name": "Tijelo{number}", + "browser.calibrate_click_a": "Kliknite sliku da zadate tačku A ili upišite njene koordinate.", + "browser.calibrate_click_b": "Kliknite sliku da zadate tačku B ili upišite njene koordinate.", "browser.calibrate_title": "Kalibriši: {name}", "browser.capture_many": "Pomjerene komponente bez zabilježenog položaja: {count}.", "browser.capture_note": "Zabilježi zadržava novi položaj; Vrati ga vraća nazad.", @@ -788,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (pričvršćenje izgubljeno)", "browser.sketch_editing": "{name} (uređuje se)", "browser.sketch_name": "Skica{number}", + "browser.sketches_to_parts_already_in_part": "već u svom dijelu", + "browser.sketches_to_parts_design_body": "na tijelu samog dizajna", + "browser.sketches_to_parts_moved": "Skice premještene u dio na kojem se nalaze: {moved}", + "browser.sketches_to_parts_no_exact_attachment": "na licu bez tačnog pričvršćenja", + "browser.sketches_to_parts_not_on_face": "ne na licu dijela", + "browser.sketches_to_parts_part_missing": "njihov dio više ne postoji", + "browser.sketches_to_parts_result": "Skice premještene u dio na kojem se nalaze: {moved}; ostale na mjestu: {stayed} ({why})", "browser.units": "Jedinice: {units}", "cam.flat": "Ravno lice", "cam.follower": "Pratilac", @@ -817,6 +831,8 @@ "cmd.appearance_pick_up": "Preuzmi izgled", "cmd.appearance_replace": "Zamijeni izgled", "cmd.assembly_bom": "Sastavnica", + "cmd.assembly_mass_properties": "Svojstva mase", + "cmd.body.print_face": "Površina za štampu", "cmd.body_rename": "Preimenuj tijelo", "cmd.browser_collapse_all": "Skupi sve", "cmd.browser_expand_all": "Proširi sve", @@ -845,6 +861,7 @@ "cmd.component_extract": "Izdvoji u datoteku", "cmd.component_finish_edit": "Završi uređivanje", "cmd.component_from_bodies": "Napravi komponente iz tijela", + "cmd.component_hide_history": "Sakrij vremensku traku komponente", "cmd.component_insert_design": "Umetni dizajn", "cmd.component_links": "Popis veza", "cmd.component_list": "Popis komponenti", @@ -853,6 +870,7 @@ "cmd.component_move_bodies": "Premjesti tijela u komponentu", "cmd.component_move_features": "Premjesti operacije u komponentu", "cmd.component_move_sketches": "Premjesti skice u komponentu", + "cmd.component_move_sketches_to_parts": "Premjesti skice u njihove dijelove", "cmd.component_paste_from_design": "Zalijepi iz drugog dizajna", "cmd.component_paste_new": "Zalijepi kao novo", "cmd.component_properties": "Fizička svojstva komponente", @@ -860,6 +878,7 @@ "cmd.component_rename": "Preimenuj komponentu", "cmd.component_replace_with_link": "Zamijeni vezom", "cmd.component_revert_position": "Vrati položaj", + "cmd.component_show_history": "Prikaži vremensku traku komponente", "cmd.component_unlock": "Otključaj sadržaj", "cmd.component_update_links": "Ažuriraj veze", "cmd.config_activate": "Aktiviraj konfiguraciju", @@ -870,6 +889,7 @@ "cmd.config_rule": "Pravilo konfiguracije", "cmd.config_rules": "Pravila konfiguracije", "cmd.config_table": "Prikaži tabelu konfiguracija", + "cmd.construct.plane.axis_point": "Ravan kroz osu i tačku", "cmd.construct_axis_edge": "Osa kroz ivicu", "cmd.construct_axis_normal_to_face": "Osa okomita na lice", "cmd.construct_axis_through_cylinder": "Osa kroz cilindar/konus/torus", @@ -918,6 +938,11 @@ "cmd.explode_show": "Prikaži rastavljeni prikaz", "cmd.expr_evaluate": "Izračunaj izraz", "cmd.face_delete": "Izbriši lice", + "cmd.file.export_3mf": "Izvezi 3MF", + "cmd.file.export_obj": "Izvezi OBJ", + "cmd.file.export_step": "Izvezi STEP", + "cmd.file.export_stl": "Izvezi STL", + "cmd.file.export_urdf": "Izvezi URDF", "cmd.file_export": "Izvoz", "cmd.file_insert_mesh": "Umetni mrežu", "cmd.file_insert_step": "Umetni STEP", @@ -935,6 +960,7 @@ "cmd.inspect_colored_components": "Omogući boje komponenti", "cmd.inspect_colored_components_disable": "Onemogući boje komponenti", "cmd.inspect_compare": "Uporedi tijela", + "cmd.inspect_compare_picture": "Uporedi sliku", "cmd.inspect_continuity": "Analiza kontinuiteta", "cmd.inspect_curvature_comb": "Analiza češlja zakrivljenosti", "cmd.inspect_curvature_map": "Analiza mape zakrivljenosti", @@ -1025,6 +1051,9 @@ "cmd.pointcloud_edit": "Uredi oblak tačaka", "cmd.pointcloud_insert": "Umetni oblak tačaka", "cmd.pointcloud_list": "Oblaci tačaka", + "cmd.render.compare.divider": "Pomjeri razdjelnik poređenja renderovanja", + "cmd.render.result.discard": "Odbaci rezultat renderovanja", + "cmd.render.result.select": "Izaberi rezultat renderovanja", "cmd.render_aging_describe": "Slojevito starenje površine", "cmd.render_backends": "Pozadinski sistemi renderovanja", "cmd.render_batch": "Renderuj sve kadrove", @@ -1188,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Splajn kontrolnih tačaka (stepen 5)", "cmd.sketch_spline_fit_point": "Splajn kroz tačke", "cmd.sketch_spline_insert_point": "Dodaj tačku splajna", + "cmd.sketch_spline_remove_point": "Ukloni tačku splajna", "cmd.sketch_spline_reverse": "Obrni smjer splajna", "cmd.sketch_spun_profile": "Rotirani profil", "cmd.sketch_toggle_diameter": "Prebaci poluprečnik / prečnik", @@ -1238,9 +1268,11 @@ "cmd.timeline_rollback": "Pomjeri oznaku vraćanja", "cmd.timeline_stop": "Zaustavi vremensku traku", "cmd.timeline_suppress": "Potisni operaciju", + "cmd.ui.assistant": "Prikaži ili sakrij Asistenta", "cmd.view.render_browser": "Stablo renderovanja", "cmd.view.render_dock": "Premjesti panel renderovanja", "cmd.view.render_focus": "Prikaz fokusa renderovanja", + "cmd.view.status_details": "Detalji statusa prozora prikaza", "cmd.view.status_items": "Stavke statusa prozora prikaza", "cmd.view_ambient_occlusion": "Ambijentalna okluzija", "cmd.view_angle_readout": "Uglovi prikaza", @@ -1271,17 +1303,28 @@ "cmd.view_tool": "Alat za navigaciju", "cmd.view_top": "Pogled odozgo", "cmd.view_visual_style": "Vizuelni stil", + "color.blue": "Plava", "color.copy": "Kliknite da kopirate vrijednosti boje", "color.edit": "Kliknite da uredite boju", "color.gamma": "Prikaz vrijednosti boje u gama prostoru 0-255", + "color.green": "Zelena", "color.hex": "Hex", "color.hex_help": "Unesite #rrggbb ili #rrggbbaa; šest cifara zadržava neprozirnost", "color.hex_hint": "#rrggbb", "color.hue": "Nijansa", "color.linear": "Prikaz vrijednosti boje u linearnom prostoru 0-1", + "color.recent": "Nedavne boje", + "color.recent_help": "Ovdje se pojavljuju boje koje izaberete u bilo kojem polju boje", + "color.red": "Crvena", + "color.saturation": "Zasićenost (procenat)", "color.saturation_value": "Zasićenost i vrijednost", "color.selected": "Izabrana boja", + "color.step_down": "Smanji za korak", + "color.step_up": "Povećaj za korak", + "color.value": "Vrijednost, svjetlina (procenat)", "config.column_filter_empty": "Nema odgovarajućih kolona", + "config.rule_parameter_columns": "Prikazani su samo parametri koji imaju kolonu u tabeli. Dodajte kolonu pomoću Dodaj kolonu (+) da biste parametar koristili ovdje.", + "config.rule_suppression_columns": "Prikazane su samo operacije koje imaju kolonu Potisni u tabeli. Dodajte kolonu pomoću Dodaj kolonu (+) da biste ovdje mogli upravljati operacijom.", "contact.components_count": "Komponente: {count}", "contact.enabled_label": "omogućeno", "coupling.gear_1": "Zupčanik 1", @@ -1327,9 +1370,14 @@ "dialog.dimension_name": "Kota: {name}", "dialog.edit_title": "UREDI {title}", "dialog.no_shown_body": "Nema prikazanog tijela za izmjenu: prikažite jedno ili izaberite Novo tijelo", + "dialog.pattern_sketch_not_object": "Izaberite tijela ili operacije: skica nije ni jedno ni drugo. Ponovite njene krive pomoću alata Niz ili Preslikaj u samoj skici ili je prvo ekstrudirajte.", "dialog.select": "↖ Izaberi", "dialog.selected_count": "↖ Izabrano: {count}", + "dialog.selection_constraint": "Ograničenje {id}", + "dialog.selection_external_curve": "{sketch} · kriva {id}", "dialog.selection_guidance": "Izaberite ulaz da ga promijenite. Kliknite izabrane objekte da ih uklonite; Ctrl/Cmd-klik ih također uključuje i isključuje. Pogledajte pregled, a zatim pritisnite U redu.", + "dialog.selection_midpoint": "Središnja tačka · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} od {total}: Izaberite {input}", "dialog.step": "Korak", "document.changed_on_disk": "{name} je promijenjen na disku", @@ -1384,26 +1432,244 @@ "from the rule": "iz pravila", "help.apache": "Apache licenca 2.0", "help.appearance.assign": "Daje izabranim tijelima, licima ili komponentama boju ili izgled materijala, bez promjene njihove težine. Koristite ga da razlikujete dijelove ili pregledate završnu obradu.", + "help.assembly.bom": "Navodi dijelove dizajna ili komponente s njihovim količinama, po broju dijela, a popis može sačuvati kao CSV ili JSON. Koristite je kao popis dijelova za naručivanje i montažu.", "help.attributions": "Atribucije (ATTRIBUTION.md)", "help.build": "Verzija {version} · commit {commit} · izgrađeno {date}", + "help.canvas.decal": "Postavlja sliku na ravno lice modela, poput naljepnice. Koristite je da prikažete etiketu, logotip ili štampani uzorak na dijelu.", + "help.canvas.edit": "Mijenja platno: njegov položaj, veličinu, ugao, neprozirnost, preslikavanje, vidljivost ili naziv. Koristite ga da poravnate referentnu sliku sa skicom kojom je precrtavate.", + "help.canvas.insert": "Postavlja PNG ili JPEG sliku na ravan ili lice kao prozirnu referencu. Koristite je da u skici precrtate fotografiju ili crtež, uz sliku skaliranu na poznatu veličinu.", + "help.component.break_link": "Odvaja povezanu komponentu od njene datoteke dizajna, a njena tijela ostavlja kakva jesu. Koristite ga kada dio više ne treba pratiti izmjene izvorne datoteke.", + "help.component.capture_position": "Zadržava položaje dijelova koje ste ručno pomjerili, tako da to postaju njihovi stvarni položaji. Koristite ga nakon što ručno namjestite dijelove koje nijedan spoj ne drži.", + "help.component.create": "Dodaje novu, praznu komponentu u dizajn, unutar aktivne komponente osim ako izaberete drugog roditelja. Koristite je da novi dio sklopa dobije vlastito mjesto za tijela i skice.", "help.component.finish_edit": "Čuva dio koji uređujete na mjestu, vraća se u njegov sklop i ažurira sklop prema njemu. Upotrijebite kada završite izmjene povezanog dijela.", + "help.component.from_bodies": "Pretvara svako izabrano tijelo u zasebnu komponentu, nazvanu po tijelu. Koristite ga kada dizajn izgrađen od odvojenih tijela treba postati sklop čiji se dijelovi mogu spajati i pomjerati.", + "help.component.insert_design": "Umeće drugi sačuvani dizajn kao komponentu povezanu s njegovom datotekom, s njegovim punim tijelima postavljenim onako kako su tamo. Koristite ga da ponovo upotrijebite dio u sklopu i kasnije izmjene preuzmete pomoću Ažuriraj veze.", + "help.component.properties": "Prikazuje zapreminu, masu, centar mase i momente inercije komponente, prema materijalima njenih tijela. Koristite ga da provjerite težinu i uravnoteženost sklopa.", + "help.component.revert_position": "Vraća dijelove koje ste ručno pomjerili tamo gdje su bili, odbacujući pomjeranja koja nisu zadržana. Koristite ga da poništite probna pomjeranja u sklopu.", + "help.component.update_links": "Ponovo čita povezane datoteke dizajna i zamjenjuje tijela tamo gdje su se promijenila. Koristite ga nakon uređivanja dijela koji ovaj sklop koristi.", + "help.config.configure": "Dodaje parametre, operacije, materijale ili izglede kao kolone tabele konfiguracija. Koristite ga da napravite varijante jednog dizajna, npr. veličine nekog dijela.", + "help.config.preview": "Provjerava može li se red tabele konfiguracija ponovo izgraditi, bez promjene dizajna ili njegove vremenske trake. Koristite ga prije prelaska na varijantu u koju niste sigurni.", + "help.config.rules": "Prikazuje pravila tabele konfiguracija, njene redove i koji je red aktivan. Koristite ga da vidite kako su postavljene varijante dizajna.", + "help.config.table": "Prikazuje tabelu konfiguracija: jedan red po varijanti, jednu kolonu po parametru ili operaciji i da li dizajn još odgovara aktivnom redu. Koristite je da pregledate varijante dizajna.", "help.connect_note": "Ponovo pokrenite svaki asistent da učita SolidCraft server. Svaka datoteka je sigurnosno kopirana kao .bak prije promjene.", "help.connect_title": "Poveži AI asistente", + "help.construct.axis.edge": "Pravi pomoćnu osu duž ravne ivice ili linije skice. Koristite je kao osu za rotaciju, kružni niz ili spoj.", + "help.construct.axis.normal_to_face": "Pravi pomoćnu osu kroz tačku, okomitu na lice. Koristite je kao osu koja stoji pravo iz površine.", + "help.construct.axis.through_cylinder": "Pravi pomoćnu osu kroz centar cilindričnog, konusnog ili torusnog lica, ili kružne ivice. Koristite je da operacije okrećete ili ih postavljate u niz oko okruglog dijela.", + "help.construct.axis.two_planes": "Pravi pomoćnu osu gdje se sastaju dvije ravni ili ravna lica. Koristite je kada je osa koja vam treba linija između dva lica.", + "help.construct.axis.two_points": "Pravi pomoćnu osu kroz dvije tačke, vrhove ili tačke skice. Koristite je za osu koja prolazi između dva poznata položaja.", + "help.construct.plane.along_path": "Pravi pomoćnu ravan okomitu na ivicu ili krivu, na nekom položaju duž nje. Koristite je da skicirate profil za povlačenje ili presjek putanje.", + "help.construct.plane.at_angle": "Pravi pomoćnu ravan zakrenutu za ugao u odnosu na ravan ili lice, oko ose ili ivice. Koristite je za nagnute skice, npr. kutni nosač.", + "help.construct.plane.axis_point": "Pravi pomoćnu ravan koja sadrži osu i tačku izvan te ose. Izaberite osu ishodišta ili pomoćnu osu, ravnu ivicu ili liniju skice, pa vrh, tačku skice ili pomoćnu tačku. Tačka na osi ne može odrediti jedinstvenu ravan.", + "help.construct.plane.midplane": "Pravi pomoćnu ravan na pola puta između dvije ravni ili ravna lica, ili koja ih raspolavlja tamo gdje se sastaju pod uglom. Koristite je kao ravan simetrije za preslikavanje.", + "help.construct.plane.offset": "Pravi pomoćnu ravan paralelnu s ravni ili ravnim licem, na određenoj udaljenosti ili kroz tačku. Koristite je da skicirate na zadatoj visini iznad lica.", + "help.construct.plane.perpendicular": "Pravi pomoćnu ravan koja sadrži liniju ili ivicu i okomita je na ravan ili lice. Koristite je da skicirate uspravno na modelu duž ivice.", + "help.construct.plane.tangent": "Pravi pomoćnu ravan koja u jednoj tački dodiruje cilindar, konus, sferu ili torus. Koristite je da skicirate na boku okruglog dijela.", + "help.construct.plane.three_points": "Pravi pomoćnu ravan kroz tri tačke. Koristite je za ravan određenu položajima na modelu, npr. s tri ugla.", + "help.construct.plane.two_edges": "Pravi pomoćnu ravan kroz dvije ravne ivice ili linije koje leže u jednoj ravni. Koristite je za ravan kroz dio, npr. kroz dvije suprotne ivice.", + "help.construct.point.along_path": "Pravi pomoćnu tačku na nekom položaju duž ivice ili krive. Koristite je kao referencu negdje duž putanje.", + "help.construct.point.center": "Pravi pomoćnu tačku u centru kružne ivice, kruga ili luka skice, sfere ili torusa. Koristite je kao referencu za rupe, ose i spojeve.", + "help.construct.point.edge_plane": "Pravi pomoćnu tačku gdje ivica ili linija prolazi kroz ravan ili ravno lice. Koristite je da označite gdje putanja siječe ravan.", + "help.construct.point.three_planes": "Pravi pomoćnu tačku gdje se sastaju tri ravni ili ravna lica. Koristite je kao referencu ugla, čak i tamo gdje model nema vrh.", + "help.construct.point.two_edges": "Pravi pomoćnu tačku gdje se dvije ivice ili linije sastaju ili su najbliže. Koristite je kao referencu u virtualnom uglu.", + "help.construct.point.vertex": "Pravi pomoćnu tačku na vrhu ili tački skice. Koristite je kao referencu koja ostaje kada se skica ili tijelo oko nje sakrije.", + "help.contact.check": "Navodi parove dijelova u skupovima kontakata koji se u trenutnom položaju međusobno presijecaju. Koristite ga da pronađete sudare prije nego što pokrenete spojeve ili studiju kretanja.", + "help.contact.create": "Grupiše dva ili više dijelova u skup kontakata čija se tijela sprečavaju da prolaze jedno kroz drugo dok se spojevi kreću. Koristite ga za dijelove koji treba da se zaustave kad se dodirnu, npr. poluga uz svoj graničnik.", + "help.contact.disable_all": "Isključuje kontakt, pa se pokretani spojevi i studije kretanja više ne zaustavljaju tamo gdje se dijelovi dodiruju. Koristite ga da ponovo slobodno pomjerate dijelove ili da veliki sklop ostane brz u radu.", + "help.contact.edit": "Mijenja skup kontakata: dijelove koje sadrži, njegov naziv ili da li je potisnut; može i izbrisati skup. Koristite ga da podesite koji dijelovi ne smiju prolaziti jedan kroz drugi.", + "help.contact.enable_all": "Stavlja svaki dio sklopa u jedan skup kontakata, pa nijedna dva dijela ne mogu prolaziti jedan kroz drugi dok se spojevi kreću. Koristite ga za brzu provjeru cijelog mehanizma.", + "help.contact.enable_sets": "Uključuje kontakt za skupove kontakata koje ste definisali, pa se pokretani spojevi i studije kretanja zaustavljaju tamo gdje bi njihovi dijelovi prošli jedan kroz drugi. Koristite ga da vratite svoje skupove nakon isključivanja kontakta.", + "help.contact.list": "Navodi skupove kontakata dizajna, dijelove u svakom od njih i da li je kontakt uključen. Koristite ga da provjerite kako je kontakt postavljen prije nego što pokrenete sklop.", + "help.document.inspect": "Prikazuje pregled dizajna: njegove komponente, tijela, skice, operacije i parametre. Koristite ga da se snađete u dizajnu koji niste sami napravili.", + "help.document.units": "Mijenja jedinice u kojima dizajn prikazuje dužine, npr. mm ili inče. Geometrija zadržava veličinu; mijenjaju se samo prikaz i brojevi bez jedinice.", + "help.edit.checkpoint": "Pamti dizajn, aktivnu skicu i historiju poništavanja onakve kakvi su sada. Koristite ga prije nego što isprobate nešto rizično od čega ćete se možda htjeti vratiti.", + "help.edit.restore_checkpoint": "Vraća se na kontrolnu tačku, uključujući historiju poništavanja. Koristite ga da jednim korakom odbacite sve urađeno od kontrolne tačke.", + "help.explode.create": "Pravi rastavljeni prikaz koji odguruje dijelove od centra sklopa ili prema pomjeranjima koja zadate. Koristite ga da pokažete kako se sklop sastavlja, za uputstva ili prezentacije.", "help.face.delete": "Uklanja izabrana lica i pušta da susjedna lica zatvore otvor, ili ostavlja otvor otvorenim kao površ. Koristite ga da uklonite zaobljenu ivicu, rupu ili ispupčenje koje smeta.", + "help.file.insert_mesh": "Dodaje 3MF, STL, OBJ, PLY ili glTF datoteku u dizajn kao mrežna tijela u novoj komponenti. Koristite ga da pored svog dizajna kao referencu postavite preuzeti ili skenirani model.", + "help.file.insert_step": "Dodaje STEP, IGES, FreeCAD ili Rhino datoteku u dizajn kao puna tijela u novoj komponenti; dijelovi sklopa postaju ugniježđene komponente. Koristite ga da uvezete modele od dobavljača ili iz drugih CAD programa.", + "help.file.save_mesh": "Čuva tijela kao STL, 3MF ili OBJ mrežu, s glatkoćom zakrivljenih lica koju izaberete. Koristite ga da pripremite dijelove za 3D štampu ili za programe koji čitaju mreže.", + "help.file.send_to_slicer": "Čuva izabrana tijela kao 3MF datoteku i otvara je u slajseru koji izaberete. Koristite ga da od modela do štampe dođete jednim korakom.", "help.font_details": "Interfejs koristi ugrađene fontove biblioteke egui (Ubuntu Light i Hack, pod licencama Ubuntu Font Licence i MIT/Bitstream Vera; Noto Emoji i font emoji ikona, pod licencama OFL i MIT). Tekst skice koristi Liberation Sans (SIL OFL 1.1). Neobavezni paket fontova Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), nije uključen u izdanja SolidCrafta.", "help.fonts": "Fontovi", + "help.frame.member": "Postavlja profil, npr. cijev ili aluminijski ekstruzioni profil, duž linija skice konstrukcije, po jedan konstrukcioni profil na liniju. Koristite ga za izradu okvira, regala i zavarenih konstrukcija.", + "help.inspect.accessibility": "Boji lica do kojih alat može doći iz jednog smjera i ona do kojih ne može. Koristite ga da provjerite dio za obradu ili izradu u kalupu s te strane.", + "help.inspect.center_of_mass": "Prikazuje centar mase tijela, svakog posebno i svih zajedno, uz ujednačenu gustoću. Koristite ga da provjerite ravnotežu i na koju stranu će se dio prevrnuti.", + "help.inspect.colored_components": "Daje svakoj komponenti vlastitu privremenu boju, bez promjene izgleda. Koristite ga da na prvi pogled razlikujete dijelove sklopa.", + "help.inspect.compare": "Upoređuje dva tijela i pokazuje gdje jedno ima materijala kojeg drugo nema, uz zapreminu i odstupanje. Koristite ga da provjerite izmijenjen ili uvezen dio u odnosu na original.", + "help.inspect.continuity": "Provjerava koliko glatko se lica sastaju duž svojih ivica: otvorene krajeve, pregibe ili skokove zakrivljenosti, i boji spojeve. Koristite ga da pronađete gdje se površi ne spajaju čisto.", + "help.inspect.curvature_comb": "Crta češljeve duž kriva, ivica ili lica čiji zupci pokazuju koliko se jako savijaju. Koristite ga da uočite ravna mjesta, pregibe i neujednačenu zakrivljenost.", + "help.inspect.curvature_map": "Boji lica prema tome koliko su zakrivljena, crveno gdje je poluprečnik mali. Koristite ga da pronađete mjesta oštre zakrivljenosti i procijenite koliko je površ glatka.", + "help.inspect.draft": "Boji lica prema uglu nagiba u odnosu na smjer vađenja iz kalupa i označava ona s premalim nagibom. Koristite ga da provjerite dio prije brizganja ili livenja.", + "help.inspect.environment_map": "Prikazuje model sa sjajnom završnom obradom koja reflektuje poput ogledala. Koristite ga da procijenite tok površi prema načinu na koji se refleksije protežu preko njih.", + "help.inspect.interference": "Pronalazi tijela koja se preklapaju i prikazuje svako preklapanje s njegovom zapreminom. Koristite ga da u sklopu provjerite ima li dijelova koji se sudaraju.", + "help.inspect.isocurve": "Crta izokrive lica (izoparametarske krive), mrežu na kojoj je površ izgrađena. Koristite ga da vidite kako površ teče i gdje se zgušnjava.", + "help.inspect.measure": "Mjeri dužine, udaljenosti, uglove, površine i poluprečnike između onoga što izaberete, ili zapreminu i masu tijela. Koristite ga da provjerite veličine i zazore.", + "help.inspect.minimum_radius": "Pronalazi najmanji poluprečnik zakrivljenosti kriva, ivica ili lica i gdje se nalazi. Koristite ga da provjerite može li alat ili mlaznica pratiti oblik.", + "help.inspect.section": "Otvara prikaz presjekom duž ravni i šrafira presječena lica, bez promjene modela. Koristite ga da pogledate unutrašnjost dijelova i sklopova.", + "help.inspect.zebra": "Prikazuje crno-bijele pruge reflektovane na licima modela. Koristite ga da procijenite glatkoću: pruge koje se prekidaju ili lome na ivici pokazuju loš prelaz.", + "help.joint.as_built": "Spaja dva dijela tamo gdje već jesu, bez pomjeranja ijednog od njih, i određuje kako se još smiju kretati. Koristite ga za dijelove koje ste već postavili u konačni položaj.", + "help.joint.cam": "Povezuje brijeg koji se okreće s pratiocem, pa pratilac klizi ili se ljulja dok obris brijega prolazi ispod njega. Koristite ga za brijegove, ekscentre i pogone ventila.", + "help.joint.create": "Spaja dva dijela u ishodištima spoja koja izaberete i pomjera drugi dio na mjesto; vrsta spoja određuje kako se još smiju kretati. Koristite ga da napravite sklop čiji se dijelovi kreću kao pravi mehanizam.", + "help.joint.drive": "Zadaje ugao ili udaljenost spoja i s njim pomjera dijelove, u okviru njegovih granica; povezani spojevi i zatvorene petlje ga prate. Koristite ga da provjerite kreće li se mehanizam kako je zamišljeno.", + "help.joint.gear": "Povezuje dva rotaciona spoja prijenosnim omjerom, pa pokretanje jednog okreće drugi. Koristite ga za čeone i prstenaste zupčanike, s omjerom iz podionih poluprečnika ili broja zubaca.", + "help.joint.limits": "Zadaje koliko daleko se spoj smije okrenuti ili pomjeriti, kao minimum i maksimum, ili uklanja te granice. Koristite ga da šarku, klizač ili polugu zadržite unutar njihovog stvarnog raspona kretanja.", + "help.joint.motion_link": "Veže dva spoja omjerom i pomakom, pa pokretanje jednog pomjera drugi. Koristite ga za čvrst odnos između spojeva koji Zupčanik, Zupčasta letva i zupčanik ili Vijak ne pokrivaju.", + "help.joint.origin": "Postavlja imenovano ishodište spoja na dio: u centar lica ili okruglog kraja, sredinu ivice, ugao ili tačku. Koristite ga da pripremite gdje se spojevi vezuju; ishodište izabrano na licu prati ga kada dio promijeni veličinu.", + "help.joint.rack_pinion": "Povezuje mali zupčanik koji se okreće sa zupčastom letvom koja klizi, pa se letva pomjera za dužinu podione kružnice koju mali zupčanik prevali. Koristite ga za pogone sa zupčastom letvom, upravljanje i linearne stolove.", + "help.joint.reach": "Pomjera tačku na dijelu prema cilju mijenjajući spojeve u njegovom lancu, u okviru njihovih granica. Koristite ga da namjestite mehanizam prema tome gdje treba biti njegov kraj, npr. vrh robotske ruke.", + "help.joint.rigid_group": "Zaključava izabrane dijelove zajedno onakve kakvi jesu, pa se kreću kao jedan. Koristite ga za dijelove koji zajedno pripadaju i između kojih nema kretanja.", + "help.joint.screw": "Povezuje okretanje i klizanje korakom, pa se svakim okretajem napreduje za tu udaljenost. Koristite ga za navojna vretena, vijke i navojne osovine.", + "help.library.apply": "Primjenjuje materijal ili izgled iz lokalne datoteke biblioteke na tijela, lica ili komponente. Koristite ga da ponovo upotrijebite materijale koje ste sačuvali iz drugog dizajna.", + "help.library.export": "Čuva materijale i izglede dizajna u datoteku biblioteke. Koristite ga da ih dijelite ili ponovo koristite u drugim dizajnima.", + "help.library.inspect": "Provjerava datoteku biblioteke i navodi njene materijale i izglede, bez promjene dizajna. Koristite ga da vidite šta biblioteka sadrži prije nego što je primijenite.", "help.licences": "Licence", "help.material.assign": "Određuje od čega su izabrana tijela napravljena, npr. čelik, aluminij ili ABS. Koristite ga da masa i težina odgovaraju stvarnom dijelu.", + "help.material.properties.validate": "Provjerava karticu podataka materijala na usklađenost brojeva i vrijednosti koje nedostaju. Koristite ga prije nego što se oslonite na podatke za masu ili krutost.", + "help.mesh.convert": "Ponovo gradi mrežno tijelo, npr. STL, kao uredivo puno tijelo s ravnim i cilindričnim licima. Koristite ga da izmijenite uvezene mehaničke dijelove kao modelirano tijelo.", "help.mit": "MIT licenca", + "help.motion.study": "Zadaje vrijednosti spojeva u koracima na vremenskoj traci i reprodukuje ih kao animaciju. Koristite ga da posmatrate kako se mehanizam kreće kroz niz pokreta i usput provjerite zazore.", + "help.motion.trace": "Prati putanju kojom ide tačka na dijelu dok se reprodukuje studija kretanja ili se pokreće spoj i, kada potvrdite, zadržava je kao krivu 3D skice. Koristite ga da vidite dokle mehanizam dosiže ili da nastavite graditi na njegovoj putanji.", "help.notice": "NOTICE", + "help.occurrence.ground": "Učvršćuje dio na mjestu, ili ga ponovo oslobađa, tako da spojevi pomjeraju ostale dijelove oko njega. Koristite ga za okvir ili osnovu na kojoj je izgrađen ostatak sklopa.", "help.occurrence.move": "Pomjera dio sklopa samo duž stepeni slobode koje dozvoljavaju njegovi spojevi. Izaberite lice dijela, a zatim prevucite dostupnu strelicu ili luk.", "help.parameters.change": "Otvara tabelu imenovanih vrijednosti i izraza koji upravljaju kotama dizajna. Koristite je da promijenite mjeru na jednom mjestu, a sve operacije koje je koriste je slijede.", + "help.parameters.export": "Čuva parametre dizajna kao CSV ili JSON. Koristite ga da ih uredite u proračunskoj tabeli ili prenesete u drugi dizajn.", + "help.parameters.graph": "Prikazuje koji parametri i operacije koriste koje druge, te sve petlje ili greške među njima. Koristite ga da vidite šta sve zahvata promjena nekog parametra.", + "help.parameters.import": "Učitava parametre iz CSV ili JSON u dizajn, sve ili nijedan. Koristite ga da unesete vrijednosti iz proračunske tabele ili drugog dizajna.", + "help.parameters.move": "Pomjera korisnički parametar ispred ili iza drugog na popisu. Koristite ga da povezane parametre držite zajedno.", + "help.parts.fastener": "Dodaje standardni vijak, zavrtanj, maticu, podlošku, zatik ili ležaj u izabranoj veličini. Postavljen na rupu, naliježe u rupu pomoću spoja, pa spojne elemente ne morate sami modelirati.", + "help.parts.insert": "Umeće standardni dio u porodici, veličini i dužini koje izaberete. Postavljen na rub ili zid rupe, naliježe na rupu krutim spojem.", + "help.parts.library": "Otvara standardne dijelove: vijke, zavrtnjeve, matice, podloške, bezglave vijke, cilindrične zatike i ležajeve u standardnim veličinama. Koristite ga da dodate standardni dio umjesto da ga sami modelirate.", + "help.parts.resize": "Mijenja veličinu ili dužinu umetnutog standardnog dijela i ponovo ga gradi; njegovi spojevi ga drže na mjestu. Koristite ga kada se vijak pokaže predugim ili rupa traži drugu veličinu.", + "help.plastic.assign_rule": "Dodjeljuje pravilo za plastiku tijelima, pa njihove plastične operacije preuzimaju njegov nagib i zazor kao podrazumijevane vrijednosti. Koristite ga da jednom podesite brizgani dio za sve njegove operacije.", + "help.plastic.boss": "Dodaje ispust za vijak na licu: stub s neobaveznom rupom, nagibom, zaobljenjem u korijenu i potpornim rebrima. Koristite ga za tačke za vijke u brizganim ili štampanim kućištima.", + "help.plastic.lip": "Dodaje usnu ili odgovarajući utor duž ruba izdubljenog tijela. Koristite ga da se dvije polovine kućišta međusobno pozicioniraju i čvrsto zatvore.", + "help.plastic.manage_rules": "Pravi i uređuje pravila za plastiku: materijal, debljinu zida, poluprečnike, zazor i nagib. Koristite ih da operacije brizganog dijela ostanu usklađene.", + "help.plastic.rest": "Dodaje oslonac na licu: okruglu ili pravougaonu podlogu, punu ili šuplju, s nagibom. Koristite ga kao potporu ili odstojnik u brizganom kućištu.", + "help.plastic.snap_fit": "Dodaje kuku škljocajućeg spoja na licu, s njenom dužinom, debljinom i zapinjačem. Koristite ga da dijelove spojite zaklapanjem bez vijaka.", "help.pointcloud.insert": "Umetnite PLY, XYZ ili PTS skeniranje kao oblak tačaka uz model. Koristite ga kao referencu pri izradi modela iz izmjerenih podataka.", + "help.sheet.convert": "Pretvara ploču ili izdubljeno tijelo ujednačene debljine u tijelo od lima, sa savijanjima na ivicama koje izaberete. Koristite ga da postojeći dio učinite razvijivim.", + "help.sheet.export_bend_table": "Čuva tabelu savijanja tijela od lima kao CSV ili JSON: uglove, poluprečnike i položaje savijanja u razvijenom obliku. Koristite ga za presu za savijanje ili radionicu.", + "help.sheet.export_dxf": "Čuva razvijeni oblik kao DXF, s obrisima, linijama savijanja i neobaveznim napomenama o savijanju. Koristite ga za rezanje laserom, plazmom ili vodenim mlazom.", + "help.sheet.flange": "Dodaje prirubnicu: osnovnu ploču iz skice, zid duž otvorene konture skice ili savijeni zid na ivicama lima. Koristite je za izgradnju dijelova od lima.", + "help.sheet.flat_pattern": "Pravi razvijeni oblik tijela od lima, s njegovom veličinom, izrezima i linijama savijanja. Koristite ga da provjerite pripremak prije rezanja.", + "help.sheet.fold": "Savija lim duž linije skice za zadati ugao i poluprečnik. Koristite ga da presavijete ravan lim nakon što u njemu izrežete operacije.", + "help.sheet.hem": "Presavija ivicu lima natrag preko sebe. Koristite ga za sigurne, krute ivice bez oštrih srha.", + "help.sheet.manage_rules": "Pravi i uređuje pravila za lim: debljinu, poluprečnik savijanja, K-faktor, rasterećenja i razmake. Koristite ih da se uskladite s materijalom i alatima svoje radionice.", + "help.sheet.path_flange": "Dodaje lanac prirubnica duž ivice lima, prateći otvoreni lanac linija skice. Koristite ga za profile poput U ili Z oblika u jednom koraku.", + "help.sheet.perforate": "Dodaje polje rupa preko cijelog ravnog lima, u izmaknutom ili kvadratnom rasporedu. Koristite ga za otvore za ventilaciju, rešetke i lakše ploče.", + "help.sheet.refold": "Ponovo presavija razvijeno tijelo od lima. Koristite ga nakon dodavanja operacija na ravan lim.", + "help.sheet.unfold": "Razvija sva savijanja tijela od lima. Koristite ga da dodate rupe ili rezove koji moraju prelaziti preko savijanja, a zatim ga ponovo presavijte.", + "help.sketch.arc.center_point": "Crta kružni luk oko tačke centra, od početne do završne tačke. Koristite ga kada je centar luka poznat, npr. poluprečnik oko rupe ili osovine.", + "help.sketch.arc.tangent": "Crta luk koji počinje na kraju linije ili luka i nastavlja se tangentno na njega. Koristite ga da lanac nastavite glatkim prelazom umjesto ugla.", + "help.sketch.arc.three_point": "Crta luk od početne do završne tačke kroz treću tačku. Koristite ga kada luk mora proći kroz zadate tačke, a ne oko poznatog centra.", + "help.sketch.arc3d": "Crta tačan kružni luk u prostoru kroz tri tačke, uz uključenu 3D skicu. Koristite ga za zavoje putanja i vodilica koji izlaze iz ravni skice.", + "help.sketch.auto_constrain": "Dodaje ograničenja koja skica već gotovo ima, npr. horizontalno, paralelno ili podudarno, a zatim je kotira dok ne bude potpuno definisana. Koristite ga da grubo nacrtanu skicu zaključate u jednom koraku.", + "help.sketch.auto_constrain_from_datum": "Radi kao Automatska ograničenja, ali položaje mjeri od referentne tačke koju izaberete umjesto od ishodišta. Koristite ga kada je dio raspoređen od jedne referentne tačke, npr. ugla ili rupe.", + "help.sketch.blend_curve": "Spaja krajeve dviju kriva glatkim splajnom koji je tangentan na obje, ili i kontinuiran po zakrivljenosti ako tako izaberete. Koristite ga da premostite razmak između kriva bez pregiba.", + "help.sketch.break": "Dijeli krivu na dijelove tamo gdje je presijecaju druge krive, ili na tačkama koje postavite na nju. Koristite ga kada dio krive treba vlastito ograničenje ili ga treba zasebno izbrisati.", + "help.sketch.cancel": "Napušta skicu i odbacuje sve što je promijenjeno otkako je napravljena ili otvorena za uređivanje. Pomoću Poništi možete vratiti promjene.", + "help.sketch.centerline": "Prebacuje linije između običnih linija i središnjih linija, osa koje profili izostavljaju. Središnju liniju koristite kao osu za rotaciju, preslikavanje ili ograničenje simetrije.", + "help.sketch.chamfer.distance_angle": "Skošava ugao između dvije linije, zadat udaljenošću duž prve linije i uglom. Koristite ga kada crtež daje skošenje kao dužinu i ugao, npr. 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Skošava ugao između dvije linije za istu udaljenost unazad duž obje. Koristite ga za uobičajeno skošenje od 45° na obrisu.", + "help.sketch.chamfer.two_distance": "Skošava ugao između dvije linije, zadat posebnom udaljenošću duž svake linije. Koristite ga za skošenja koja nisu 45°, zadana kao dvije dužine.", + "help.sketch.circle.center": "Crta krug iz njegovog centra i prečnika. Koristite ga za rupe, ispuste i druge okrugle oblike čiji je centar poznat.", + "help.sketch.circle.three_point": "Crta krug kroz tri tačke. Koristite ga kada krug mora proći kroz zadate tačke, npr. postojeće geometrije.", + "help.sketch.circle.three_tangent": "Crta krug koji dodiruje tri elementa: linije, krugove ili lukove. Koristite ga da krug uklopite u prostor između triju kriva, npr. upisani krug trougla.", + "help.sketch.circle.two_point": "Crta krug iz dva kraja njegovog prečnika. Koristite ga kada su poznate tačke na rubu kruga, a ne njegov centar.", + "help.sketch.circle.two_tangent": "Crta krug zadate veličine koji dodiruje dva elementa: linije, krugove ili lukove. Koristite ga za zaobljenje stalnog poluprečnika između dvije krive.", + "help.sketch.conic": "Crta konusnu krivu između dvije krajnje tačke, oblikovanu tjemenom tačkom i vrijednošću rho. Koristite je za glatke prelaze čiju punoću želite podesiti, od ravnog do gotovo oštrog ugla.", + "help.sketch.constrainer": "Primjenjuje ograničenje koje jedna ili dvije izabrane krive već gotovo imaju, npr. horizontalno, paralelno, tangentno ili jednako. Koristite ga da uredite ručno nacrtanu skicu, jedan odnos po jedan.", + "help.sketch.constraint.coincident": "Čini da tačka leži na drugoj tački, krivoj ili osi skice. Koristite ga da zatvorite otvore u profilu ili da tačku postavite na liniju.", + "help.sketch.constraint.collinear": "Čini da dvije linije leže na jednoj pravoj. Koristite ga da poravnate prekinute ivice, npr. obje strane zareza.", + "help.sketch.constraint.concentric": "Daje dva kruga ili luka isti centar. Koristite ga za prstenove, cilindrična upuštenja i osovine s ramenima.", + "help.sketch.constraint.curvature": "Čini da dvije krive koje se sastaju u krajnjoj tački nastave istom zakrivljenošću (G2). Koristite ga tamo gdje tangentni spoj nije dovoljno gladak, npr. na vidljivim površima.", + "help.sketch.constraint.equal": "Izjednačava dužine linija, ili poluprečnike krugova i lukova. Koristite ga da jedna kota upravlja s više istovjetnih oblika.", + "help.sketch.constraint.fix": "Fiksira tačke ili krive tamo gdje jesu, ili ih ponovo oslobađa. Koristite ga za geometriju koja se ne smije pomjerati kada povlačite ili rješavate skicu.", + "help.sketch.constraint.horizontal_vertical": "Čini liniju, ili liniju između dvije tačke, horizontalnom ili vertikalnom, zavisno od toga što je bliže. Koristite ga da obris poravnate s osama skice.", + "help.sketch.constraint.midpoint": "Postavlja tačku na sredinu linije, ili spaja središnje tačke dviju linija. Koristite ga da geometriju centrirate na ivici.", + "help.sketch.constraint.parallel": "Čini dvije linije paralelnima. Koristite ga za stranice koje moraju ostati paralelne kada se promijene druge kote.", + "help.sketch.constraint.perpendicular": "Čini da se dvije linije sastaju pod pravim uglom. Koristite ga za prave uglove između linija koje nisu na osama skice.", + "help.sketch.constraint.polygon": "Čini zatvoreni lanac linija pravilnim poligonom: jednake stranice, a svaki ugao na jednom krugu. Koristite ga da ručno nacrtan poligon učinite pravilnim i takvim ga zadržite.", + "help.sketch.constraint.symmetry": "Čini da dvije tačke ili krive budu međusobno preslikane preko linije ili oko tačke. Koristite ga da profil ostane simetričan kada promijenite jednu stranu.", + "help.sketch.constraint.tangent": "Čini da se dvije krive dodiruju tangentno, npr. linija i luk. Koristite ga za glatke spojeve bez pregiba.", + "help.sketch.construction": "Prebacuje krive između obične geometrije i pomoćne geometrije, koju profili izostavljaju. Pomoćne krive koristite kao pomagala za raspored, reference i kote.", + "help.sketch.construction_line": "Napravite beskonačnu pomoćnu pravu kroz dvije tačke. Koristite je da rasporedite skicu bez razdvajanja profila.", + "help.sketch.construction_line.angle": "Napravite beskonačnu pomoćnu pravu pod uglom od ose X skice. Izaberite tačku i upišite ugao ili izaberite smjer.", + "help.sketch.construction_line.bisector": "Izaberite dvije prave linije skice koje se sijeku, pa jednu od dvije simetrale ugla. Rezultat prati izvorne linije.", + "help.sketch.construction_line.horizontal": "Napravite beskonačnu horizontalnu pomoćnu pravu kroz tačku. Njeno ograničenje horizontalnosti ostaje na snazi pri kasnijim izmjenama.", + "help.sketch.construction_line.parallel": "Izaberite pravu liniju skice, pa postavite paralelnu beskonačnu pomoćnu pravu. Desnim klikom izaberite drugu referencu.", + "help.sketch.construction_line.perpendicular": "Izaberite pravu liniju skice, pa postavite okomitu beskonačnu pomoćnu pravu. Desnim klikom izaberite drugu referencu.", + "help.sketch.construction_line.tangent_at": "Napravite tangentu u tački na krugu ili kružnom luku, ili u krajnjoj tački otvorenog splajna ili konike. Izaberite krivu, pa tačku dodira.", + "help.sketch.construction_line.tangent_external": "Izaberite krug ili kružni luk, pa vanjsku tačku i rješenje tangente. Pregledi prikazuju samo dodirne tačke na nacrtanom luku.", + "help.sketch.construction_line.tangent_two": "Izaberite dva kruga ili kružna luka, pa u pregledu izaberite zajedničku tangentu. Dodirne tačke moraju ležati na nacrtanim krivama.", + "help.sketch.construction_line.vertical": "Napravite beskonačnu vertikalnu pomoćnu pravu kroz tačku. Njeno ograničenje vertikalnosti ostaje na snazi pri kasnijim izmjenama.", + "help.sketch.copy": "Kopira izabrane krive i tačke skice, zajedno s ograničenjima i kotama među njima. Zalijepite ih u ovu skicu ili u drugu.", + "help.sketch.create": "Počinje novu 2D skicu na ravni ili na ravnom licu modela. Svako ekstrudiranje, rotiranje i povlačenje počinje skicom.", + "help.sketch.cut": "Kopira izabranu geometriju skice i briše je iz skice, u jednom koraku poništavanja. Zalijepite je drugdje u ovoj skici ili u drugoj.", + "help.sketch.dimension": "Dodaje pogonsku kotu: dužinu, udaljenost, ugao, poluprečnik ili prečnik, zavisno od onoga što izaberete. Upišite vrijednost ili naziv parametra, a skica ih prati.", + "help.sketch.edit": "Otvara postojeću skicu za uređivanje. Operacije izgrađene na njoj se ažuriraju kada završite skicu.", + "help.sketch.ellipse": "Crta elipsu iz njenog centra, kraja velike ose i tačke na maloj strani. Koristite je za ovalne otvore, brijegove i druge izdužene okrugle oblike.", "help.sketch.equation_curve": "Crta krivu iz formula: x(t) i y(t) ili y = f(x), u zadanom rasponu. Formule mogu koristiti parametre i kriva ih prati: koristite je za sinusoidu, spiralu ili evolventu zupca zupčanika.", + "help.sketch.extend": "Produžava liniju ili luk do najbliže krive na putu, ili izdužuje dvije krive dok se ne sastanu. Koristite ga da zatvorite otvore u profilu nakon odsijecanja ili uređivanja.", + "help.sketch.fillet": "Zaobljuje ugao gdje se dvije linije ili lukovi sastaju lukom zadatog poluprečnika. Više uglova zaobljenih zajedno dijeli jedan poluprečnik.", + "help.sketch.finish": "Napušta skicu i vraća se na model. Njeni zatvoreni profili tada su spremni za Ekstrudiraj, Rotiraj i druge operacije.", + "help.sketch.finish_auto_constrain": "Pokreće Automatska ograničenja na skici, a zatim je završava. Koristite ga da skicu ostavite potpuno definisanu u jednom koraku.", + "help.sketch.fit_curves_to_section": "Siječe mrežno ili puno tijelo ravni skice i uklapa linije i lukove u presjek. Koristite ga da skenirani ili uvezeni dio ponovo izgradite kao uredivu skicu.", + "help.sketch.include_3d": "Unosi ivice modela, vrhove i krive drugih skica u ovu skicu kao povezane reference, spljoštavajući one izvan njene ravni na nju. Koristite ga da gradite na geometriji koja ne leži u ravni skice.", + "help.sketch.infinite": "Prebacuje linije između običnih linija i beskonačnih pomoćnih pravih koje se protežu preko cijelog prikaza. Koristite ih kao reference za raspored koje nikada ne završe prekratko.", + "help.sketch.insert_dxf": "Učitava krive DXF crteža u skicu, skalirane, zakrenute i postavljene gdje zadate. Koristite ga da gradite na 2D crtežu iz drugog programa, npr. na obrisu za rezanje laserom.", + "help.sketch.insert_svg": "Učitava putanje SVG crteža u skicu, skalirane, zakrenute i postavljene gdje zadate. Koristite ga da logotip ili vektorski obris pretvorite u krive koje možete ekstrudirati.", + "help.sketch.inspect": "Otvara izvještaj o otvorenoj skici: koliko je stepeni slobode preostalo i je li potpuno ograničena. Koristite ga da saznate šta se još pomjera prije nego što završite skicu.", + "help.sketch.intersect": "Dodaje krive ili tačke gdje tijela, lica, ivice ili druge skice sijeku ravan skice. Ostaju povezane i prate model kada se promijeni.", + "help.sketch.intersection_curve": "Pravi 3D krive tamo gdje se dva tijela ili lica sastaju, povezane s njima. Koristite ih kao putanje ili vodilice koje prate model.", + "help.sketch.isoparametric_curve": "Pravi 3D krivu u smjeru U ili V lica kroz tačku koju izaberete, povezanu s licem. Koristite je kao putanju ili liniju razdvajanja koja prati površ.", + "help.sketch.line": "Crta povezane linije tačku po tačku, kao otvoreni lanac ili zatvoren obris. To je osnovni alat za većinu profila.", + "help.sketch.line.midpoint": "Crta liniju od njene središnje tačke do jednog kraja, a drugi kraj se preslikava. Koristite je za linije centrirane na tački, npr. simetričnu ivicu.", + "help.sketch.line3d": "Crta povezane prave linije između tačaka u prostoru, uz uključenu 3D skicu. Koristite ga za putanje i okvire koji izlaze iz ravni skice.", + "help.sketch.mirror": "Preslikava krive i tačke skice preko linije ili ose i dodaje ograničenja simetrije. Koristite ga da nacrtate pola simetričnog profila i dovršite ga.", + "help.sketch.move": "Pomjera ili rotira krive i tačke skice, ili njihovu kopiju. Koristite ga da promijenite položaj geometrije uz zadržavanje njenog oblika i ograničenja.", + "help.sketch.offset": "Pravi kopiju lanca kriva na zadatoj udaljenosti, s jedne strane ili s obje. Koristite ga za zidove, obrise i zazore; udaljenost ostaje kota koju možete uređivati.", + "help.sketch.paste": "Lijepi geometriju skice koju ste kopirali ili izrezali u aktivnu skicu. Postavite je na tačku ili je pomjerite za odmak.", + "help.sketch.pattern.circular": "Kopira geometriju skice oko tačke centra, preko punog kruga ili zadatog ugla. Koristite ga za kružne rasporede vijaka, paoke i zupce.", + "help.sketch.pattern.rectangular": "Kopira geometriju skice u redovima i kolonama na zadatim razmacima. Koristite ga za mreže rupa, žlijebova ili otvora za ventilaciju.", + "help.sketch.point": "Postavlja tačku skice. Koristite je kao referencu za kote, ograničenja, centre rupa ili kasnije operacije.", + "help.sketch.point3d": "Postavlja tačku u prostoru, uz uključenu 3D skicu. Koristite je kao referencu za 3D krive i putanje.", + "help.sketch.polygon.circumscribed": "Crta pravilan poligon oko kruga, zadat od centra do sredine stranice. Koristite ga kada je poznata širina ključa, npr. za šestougaonu maticu.", + "help.sketch.polygon.edge": "Crta pravilan poligon iz dva kraja jedne stranice. Koristite ga kada su poznate dužina i položaj stranice.", + "help.sketch.polygon.inscribed": "Crta pravilan poligon unutar kruga, zadat od centra do ugla. Koristite ga kada je poznata mjera preko uglova.", + "help.sketch.project": "Unosi ivice modela, lica, vrhove i krive drugih skica u ovu skicu, projektovane na njenu ravan. Ostaju povezani i prate model kada se promijeni.", + "help.sketch.project_to_surface": "Projektuje krive drugih skica duž normale ove skice na lice, kao povezane 3D krive. Koristite ga da logotip, liniju razdvajanja ili putanju postavite na zakrivljenu površ.", + "help.sketch.rectangle.center": "Crta pravougaonik iz njegovog centra i jednog ugla. Koristite ga za obrise centrirane na tački, npr. na ishodištu.", + "help.sketch.rectangle.rounded": "Crta pravougaonik sa sva četiri ugla zaobljena istim poluprečnikom. Koristite ga za ploče, poklopce i otvore sa zaobljenim uglovima.", + "help.sketch.rectangle.three_point": "Crta pravougaonik iz jedne ivice i tačke na suprotnoj strani. Koristite ga za pravougaonike pod uglom u odnosu na ose skice.", + "help.sketch.rectangle.two_point": "Crta pravougaonik iz dva suprotna ugla. Koristite ga za obrise ploča, blokova i džepova.", + "help.sketch.scale": "Skalira krive i tačke skice faktorom oko bazne tačke. Koristite ga da promijenite veličinu dijela skice bez ponovnog crtanja.", + "help.sketch.slot.arc_center": "Crta lučni žlijeb zadate širine duž luka određenog centrom, početkom i krajem. Koristite ga za žlijebove za podešavanje oko osovine.", + "help.sketch.slot.arc_three_point": "Crta lučni žlijeb zadate širine duž luka kroz tri tačke. Koristite ga kada putanja žlijeba mora proći kroz zadate tačke.", + "help.sketch.slot.center_point": "Crta ravni žlijeb zadate širine od njegovog centra do centra jednog krajnjeg luka. Koristite ga za žlijebove centrirane na tački.", + "help.sketch.slot.center_to_center": "Crta ravni žlijeb zadate širine između centara njegova dva krajnja luka. Koristite ga za žlijebove kotirane od centra do centra, npr. žlijebove za podešavanje vijaka.", + "help.sketch.slot.overall": "Crta ravni žlijeb zadate širine od jednog vanjskog kraja do drugog. Koristite ga kada je bitna ukupna dužina žlijeba.", + "help.sketch.spline.control_point": "Crta kubni splajn oblikovan kontrolnim tačkama kroz koje ne prolazi. Koristite ga za glatke, tečne krive koje oblikujete pomjeranjem tačaka.", + "help.sketch.spline.control_point_5": "Crta splajn petog stepena oblikovan kontrolnim tačkama. Koristite ga tamo gdje se krive moraju spajati glađom zakrivljenošću, npr. na vidljivim dizajnerskim površima.", + "help.sketch.spline.fit_point": "Crta glatki splajn koji prolazi kroz svaku tačku koju postavite, otvoren ili zatvoren. Koristite ga da oblik provučete kroz poznate tačke.", + "help.sketch.spline3d": "Crta glatku krivu u prostoru kroz tačke, uz uključenu 3D skicu. Koristite ga za putanje povlačenja i vođenje kablova koji izlaze iz ravni skice.", + "help.sketch.spun_profile": "Pravi u ravni skice obris koji tijelo opisuje kada se okreće oko ose. Koristite ga da dobijete siluetu tokarenog dijela za rotiranje ili crtež.", + "help.sketch.text": "Upisuje tekst u skicu izabranim fontom, visinom i uglom; njegove riječi mogu pratiti parametre. Ekstrudirajte ga ili ga napravite reljefom za etikete i natpise.", + "help.sketch.transform": "Skalira, okreće i pomjera geometriju skice oko tačke centra u jednom koraku. Koristite ga da istovremeno promijenite položaj i veličinu izbora.", + "help.sketch.trim": "Uklanja dio krive između najbližih presjeka oko mjesta na koje kliknete. Koristite ga da preklapajuće linije očistite u zatvoren profil.", "help.solid.align": "Pomjera izabrana tijela tako da se tačka, lice ili ravan na njima poklopi s tačkom, licem ili ravni negdje drugdje. Koristite ga da postavite dio uz drugi bez mjerenja odmaka.", + "help.solid.boundary_fill": "Pravi puna tijela od područja zatvorenih preklapajućim alatnim tijelima, popunjavajući samo područja koja izaberete. Koristite ga da oblik izgradite iz prostora koji nekoliko tijela zajedno ograničava.", + "help.solid.bounding_solid": "Pravi kutiju koja obuhvata izabrana tijela, s neobaveznom marginom. Koristite ga da vidite ukupnu veličinu dijela ili kao pripremak iz kojeg se dio obrađuje.", + "help.solid.box": "Pravi kutiju iz dužine, širine i visine, iz tačke ugla ili centriranu na tački. Koristite je za brz blok, privremeni oblik ili tijelo u koje se urezuju operacije.", "help.solid.chamfer": "Odsijeca izabrane ivice ravnim skošenjem zadate udaljenosti. Koristite ga da ublažite oštre ivice ili olakšate uvođenje zatika ili vijka.", + "help.solid.coil": "Pravi zavojno tijelo, npr. oprugu, iz prečnika, broja zavoja, visine ili koraka i okruglog ili kvadratnog presjeka. Koristite je za opruge, zavojnice i zavojne grebene.", "help.solid.combine": "Spaja tijela, oduzima ih od ciljnog tijela ili zadržava samo zajedničku zapreminu, a može zadržati i alatna tijela. Koristite ga da spojite dijelove, da jednim oblikom odsiječete drugi ili da pronađete gdje se dva tijela preklapaju.", + "help.solid.cone": "Pravi konus iz kruga osnove i visine, ili zarubljeni konus kada i vrh ima poluprečnik. Koristite ga za suženja, lijevke, konusna upuštenja i šiljke.", + "help.solid.cylinder": "Pravi cilindar iz poluprečnika ili prečnika i visine, postavljen na tačku duž ose. Koristite ga za osovine, zatike, ispuste i okrugle pripremke.", "help.solid.draft": "Naginje izabrana lica za ugao koji zadate, mjereno od neutralne ravni. Koristite ga na livenim ili brizganim dijelovima kako bi izašli iz kalupa.", + "help.solid.emboss": "Izdiže profile skice, npr. tekst ili logotip, iz lica, ili ih udubljuje u njega. Koristite ga za natpise, etikete i oznake na ravnim ili okruglim licima.", "help.solid.extrude": "Izvlači profil skice u 3D duž zadate udaljenosti, dodajući ili uklanjajući materijal. Koristite ga da ravni obris pretvorite u blok, ispust ili džep.", "help.solid.fillet": "Zaobljuje izabrane ivice glatkim kružnim prelazom zadatog poluprečnika. Koristite ga da omekšate oštre ivice radi čvrstoće, udobnosti ili izgleda.", "help.solid.hole": "Buši okruglu rupu zadatog prečnika na izabranoj tački lica. Koristite je za prolaze vijaka, zatike i druge jednostavne okrugle otvore.", @@ -1412,20 +1678,60 @@ "help.solid.move": "Pomjera ili rotira izabrana tijela, ili njihovu kopiju, za udaljenost i ugao koje zadate. Koristite ga da premjestite tijelo ili napravite drugo na drugom mjestu.", "help.solid.offset_face": "Gura izabrana lica unutra ili van za udaljenost koju zadate, a okolna lica ih prate. Koristite ga da podebljate zid, produbite džep ili povisite ispupčenje bez uređivanja skice.", "help.solid.pattern.circular": "Ponavlja izabrane objekte oko ose, za zadati broj i ukupni ugao. Koristite ga za krugove vijaka, žbice, rebra hladnjaka i zupce.", + "help.solid.pattern.path": "Kopira operacije ili tijela duž putanje skice, prema broju i razmaku. Koristite ga za rupe duž zakrivljene ivice ili dijelove duž vodilice.", "help.solid.pattern.rectangular": "Ponavlja izabrane objekte u jednom ili dva smjera sa zadatim brojem i razmakom. Koristite ga za redove i mreže rupa, rebara, zatika ili nožica.", + "help.solid.pipe": "Pravi okruglu cijev duž putanje od kriva skice, punu ili šuplju sa zadatom debljinom zida. Koristite je za cijevi, žice, kablove i šine.", "help.solid.press_pull": "Dodaje ili uklanja materijal dok povlačite lice, ili zaobljava ivice dok ih povlačite. Koristite ga za brze izmjene direktno na modelu.", "help.solid.remove": "Uklanja izabrana tijela iz dizajna od ove tačke vremenske trake nadalje; raniji koraci ih zadržavaju. Koristite ga da odbacite pomoćno tijelo, npr. alat za rezanje koji vam više ne treba.", "help.solid.replace_face": "Premješta izabrana ravna lica na ravan ili na paralelno lice, a tijelo raste ili se smanjuje da ga dosegne. Koristite ga da poravnate lice s drugim dijelom ili pomoćnom ravni.", "help.solid.revolve": "Okreće profil skice oko ose i pravi okruglo tijelo. Koristite ga za vratila, dugmad, posude i svaki dio koji je okrugao oko središnje linije.", + "help.solid.rib": "Dodaje tanak zid duž otvorene krive skice, popunjen do sljedećih lica tijela. Koristite ga da ojačate zidove i uglove, npr. u brizganim ili štampanim dijelovima.", "help.solid.scale": "Povećava ili smanjuje izabrana tijela za faktor, jednako u svim smjerovima ili posebno po osi. Koristite ga da promijenite veličinu uvezenog oblika ili uračunate skupljanje.", "help.solid.shell": "Izdubljuje tijelo i ostavlja zidove zadate debljine, a može otvoriti lica koja izaberete. Koristite ga za kutije, poklopce i druge tankozidne dijelove.", + "help.solid.sphere": "Pravi sferu iz poluprečnika ili prečnika oko tačke centra. Koristite je za kugle, ručke i zaobljene krajeve.", "help.solid.split_body": "Reže tijelo na zasebna tijela ravni, licem drugog tijela ili linijom skice. Koristite ga za dijelove koji se zasebno štampaju, obrađuju ili boje.", "help.solid.split_face": "Dijeli izabrana lica po ravni, licu drugog tijela ili krivama skice, bez rezanja tijela. Koristite ga da dijelu lica date vlastiti nagib, boju ili odmak.", "help.solid.sweep": "Povlači profil skice duž putanje i pravi tijelo. Koristite ga za cijevi, šine, ručke i svaki dio konstantnog presjeka koji prati krivu.", + "help.solid.thread": "Dodaje ISO metrički navoj na cilindrično lice, kao kozmetički navoj ili urezan u tijelo. Koristite ga za vijke, navojne rupe i štampane dijelove s navojem.", + "help.solid.torus": "Pravi prsten iz velikog poluprečnika oko njegove ose i malog poluprečnika za okrugli presjek. Koristite ga za O-prstenove, ručke i okrugle perle.", + "help.solid.web": "Dodaje tanak zid duž svake otvorene krive skice, svaki popunjen do sljedećih lica tijela. Koristite ga za mrežu potpornih zidova unutar kućišta i posuda.", + "help.surface.blend": "Pravi površ koja premošćuje ivice dvaju tijela, tangentnu ili kontinuiranu po zakrivljenosti s oba. Koristite je da dvije površi glatko spojite preko razmaka.", + "help.surface.boundary": "Pravi površ koja ispunjava petlju od dvije do četiri krive skice, ili mrežu kriva. Koristite je za slobodne panele određene svojim ivicama.", + "help.surface.extend": "Produžava površ preko njenih ivica, za neku udaljenost ili do ravni ili lica. Koristite ga da se površi preklope prije nego što ih odsiječete ili sašijete.", + "help.surface.extrude": "Izvlači krive ili profile skice na zadatu udaljenost u površ, samo zidove, bez poklopaca. Koristite ga za tanke zidove i za alate za rezanje ili razdvajanje.", + "help.surface.fair": "Izglađuje unutrašnjost slobodnih lica dok njihove ivice ostaju na mjestu. Koristite ga da izravnate izbočine i valovite refleksije u površi.", + "help.surface.loft": "Pravi površ koja redom prolazi kroz dva ili više presjeka, bez poklopaca. Koristite je za ljuske i prelaze između različitih oblika.", + "help.surface.match": "Ponovo gradi ivicu površi tako da se sastaje s ivicom drugog tijela, uz podudarnu tangentu ili zakrivljenost. Koristite ga da glatko zatvorite šav između dvije površi.", + "help.surface.offset": "Pravi kopiju lica na udaljenosti duž njihovih normala, kao novo tijelo površi. Koristite ga za omotače, zazore ili drugu stranu zida.", + "help.surface.patch": "Ispunjava područje skice ili zatvorenu petlju ivica licem, ravnim ili glatko zakrivljenim. Koristite ga da zatvorite rupe u tijelu površi.", + "help.surface.reverse_normal": "Okreće lica tijela površi, pa njihova vanjska strana gleda na drugu stranu. Koristite ga prije podebljanja ili šivenja kada lica gledaju prema unutra.", + "help.surface.revolve": "Okreće krive ili profile skice oko ose u površ, bez poklopaca. Koristite ga za okrugle ljuske poput abažura, zdjela i mlaznica.", + "help.surface.ruled": "Pravi traku pravih linija iz lanca ivica, duž normale lica, tangente ili pod uglom. Koristite ga za zidove s nagibom, odvodne površi i površi razdvajanja.", + "help.surface.stitch": "Šije tijela površi zajedno duž njihovih zajedničkih ivica, u puno tijelo kada se zatvore. Koristite ga da skup površi pretvorite u jedno tijelo.", + "help.surface.sweep": "Pomjera krive ili profile skice duž putanje u površ, bez poklopaca. Koristite ga za žljebove, lajsne i druge tanke oblike koji prate putanju.", + "help.surface.thicken": "Daje tijelu površi debljinu i pretvara ga u puno tijelo. Koristite ga da od površi napravite dijelove pogodne za štampu ili obradu.", + "help.surface.trim": "Siječe površ ravni, drugom površi ili krivama skice i zadržava stranu koju izaberete. Koristite ga da površi oblikujete prije šivenja.", + "help.surface.unstitch": "Razdvaja lica tijela u zasebna tijela površi; puno tijelo se raspada na površi. Koristite ga da preradite pojedinačna lica tijela.", + "help.surface.untrim": "Uklanja rupe iz lica, ili vraća njegovu vanjsku granicu na prirodne granice površi. Koristite ga da nakon odsijecanja vratite cijelu površ.", "help.third_party": "Licence trećih strana", "help.timeline.compute_all": "Ponovo gradi svaku operaciju na vremenskoj traci od početka. Koristite ga da osvježite model i vidite koje operacije ne uspijevaju.", "help.timeline.delete": "Briše izabrane operacije s vremenske trake; brisanje skice briše i operacije napravljene iz nje. Koristite ga da uklonite korak koji više ne želite.", + "help.timeline.dependents": "Navodi operacije koje bi bile izbrisane zajedno s nekom operacijom i one koje bi bez nje otkazale. Koristite ga prije brisanja ili mijenjanja operacije.", "help.timeline.play": "Reprodukuje preostale operacije jednu po jednu, s pauzom od pola sekunde nakon svake ponovne izgradnje. Pokrenite ovu komandu ponovo ili pritisnite Escape da zaustavite; Idi na kraj skače odmah.", + "help.view.apply": "Okreće prikaz u standardni smjer, npr. sprijeda, odozgo ili izometrijski, ili u sačuvani imenovani prikaz. Koristite ga da model posmatrate iz utvrđenog ugla.", + "help.view.delete": "Briše sačuvani imenovani prikaz. Model se ne mijenja.", + "help.view.fit": "Zumira i pomjera prikaz tako da cijeli model, ili izbor, ispuni prikaz. Koristite ga kada model nestane iz vidokruga.", + "help.view.grid": "Prikazuje ili sakriva mrežu u prozoru prikaza. Koristite je kao vodič za veličinu i orijentaciju tokom modeliranja.", + "help.view.ground_shadow": "Prikazuje ili sakriva sjenu modela na podlozi. Koristite je da lakše procijenite visinu i položaj.", + "help.view.home": "Vraća prikaz na početni smjer i uklapa model. Koristite ga da se brzo vratite na poznat prikaz.", + "help.view.list": "Navodi imenovane prikaze sačuvane u dizajnu. Koristite ga da pronađete prikaz koji ste ranije sačuvali.", + "help.view.navigate": "Okreće, pomjera ili zumira prikaz u koracima, npr. četvrtinu okreta ulijevo. Koristite ga da kameru pomjerate precizno umjesto povlačenjem.", + "help.view.navigation_bar": "Prikazuje ili sakriva navigacijsku traku na dnu prozora prikaza. Sakrijte je za više prostora, prikažite je da alatima prikaza pristupate mišem.", + "help.view.rename": "Daje sačuvanom imenovanom prikazu novi naziv. Sam prikaz ostaje isti.", + "help.view.save": "Čuva trenutni položaj kamere kao imenovani prikaz u dizajnu. Koristite ga da se kasnije vratite na isti ugao, npr. za snimke ekrana.", + "help.view.spin": "Neprekidno orbitira prikaz oko modela do sljedećeg klika ili tipke. Koristite ga da model predstavite sa svih strana.", + "help.view.tool": "Zaključava alat kamere, orbitiranje, pomjeranje ili zumiranje, tako da povlačenje lijevim dugmetom miša pomjera prikaz dok ga ne isključite. Koristite ga na touchpadu ili bez srednjeg dugmeta miša.", + "help.view.visual_style": "Mijenja način crtanja modela: osjenčeno sa ili bez ivica, žičani model ili sa skrivenim ivicama. Koristite žičani model da vidite unutra, a osjenčeno za čist izgled.", "history.sketch_under_constrained": "Nedovoljno ograničeno (stepeni slobode: {count})", "history.sketch_under_constrained_one": "Nedovoljno ograničeno ({count} stepen slobode)", "hole_presets.confirm_delete": "Potvrdi brisanje", @@ -1531,6 +1837,8 @@ "joint_move.blocked_hint": "Provjerite vrstu spoja (npr. Kruti), učvršćenje, granice spoja i vrijednosti koje pokreću parametri.", "joint_move.blocked_title": "Ovaj dio se ne može pomjeriti", "joint_move.coarse": "Korak rotacije blizu ose (°)", + "joint_move.conflict": "Jedan spoj ovog dijela je u sukobu s ostalima: {joint}.", + "joint_move.conflict_hint": "Uredite, potisnite ili izbrišite spoj koji je u sukobu da bi ostali spojevi mogli postaviti dio.", "joint_move.distance": "Udaljenost od početka", "joint_move.done": "Gotovo", "joint_move.fine": "Korak rotacije dalje od ose (°)", @@ -1602,6 +1910,10 @@ "material.selection.mixed": "Različiti materijali", "measure.at": "Na", "measure.item": "Stavka {number}", + "measure.quick_copied": "Mjerenje kopirano", + "measure.quick_copy": "Kliknite da kopirate mjerenje", + "measure.quick_edges": "Ivice: {count}", + "measure.quick_faces": "Lica: {count}", "messages.ago_h": "prije {n} h", "messages.ago_min": "prije {n} min", "messages.ago_s": "prije {n} s", @@ -1626,6 +1938,8 @@ "motion.track_name": "Staza {number}", "nav.alias.help": "Shift+Alt+povlačenje lijevim dugmetom orbitira, Shift+Alt+srednjim pomjera, Shift+Alt+desnim zumira; povlačenje srednjim dugmetom također pomjera, a desnim orbitira", "nav.blender.help": "Povlačenje srednjim dugmetom orbitira, Shift+srednje pomjera, Ctrl+srednje zumira; povlačenje desnim dugmetom ne dira kameru", + "nav.creo.help": "Povlačenje srednjim dugmetom orbitira, Shift+srednje pomjera, Ctrl+srednje uz vertikalno povlačenje zumira (prema dolje za približavanje); točkić također zumira", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Miš i 3D miš rotiraju kroz oba pola i čuvaju nagib. Privlačenje osa tipkom Shift je isključeno.", "nav.free_orbit.label": "Slobodno orbitiranje", "nav.free_orbit.snap_help": "Miš i 3D miš rotiraju kroz oba pola i čuvaju nagib. Držite Shift tokom povlačenja za orbitiranje da privučete smjer pogleda i nagib.", @@ -1635,6 +1949,7 @@ "nav.hfss.help": "Alt+lijevo povlačenje pomjera prikaz, Shift+Alt+lijevo zumira, Ctrl+lijevo povlačenje na praznom prostoru orbitira", "nav.inventor.help": "Povlačenje srednjim dugmetom pomjera, Shift+srednje orbitira, Ctrl+srednje zumira, povlačenje desnim orbitira", "nav.maya.help": "Alt+lijevo povlačenje orbitira, Alt+srednje pomjera, Alt+desno zumira; srednje povlačenje također pomjera", + "nav.nx.help": "Povlačenje srednjim dugmetom orbitira, Shift+srednje pomjera (u NX-u srednje + desno), Ctrl+srednje zumira (u NX-u srednje + lijevo); povlačenje desnim dugmetom ne dira kameru", "nav.openscad.help": "Povlačenje lijevim dugmetom po praznom prostoru orbitira, Shift+povlačenje lijevim bira okvirom, povlačenje geometrije skice je uređuje; povlačenje desnim ili srednjim dugmetom pomjera, Shift+desno ili Shift+srednje zumira", "nav.perspective.sketch": "Uređivanje skice koristi ortografski prikaz. Završite skicu da prebacite na perspektivu.", "nav.right_drag_orbits.help": "Isključeno: povlačenje desnim dugmetom ne dira kameru, a desno dugme samo otvara kontekstni meni. Izbor mapiranja miša SolidWorks to isključuje.", @@ -1754,6 +2069,11 @@ "not a move": "nije pomjeranje", "not a number": "nije broj", "open a sketch first": "prvo otvorite skicu", + "parameters.apply_live": "Primijeni svaku promjenu kad napustite njeno polje", + "parameters.apply_live_tip": "Isključeno: promjene čekaju na Primijeni ili U redu, a zatim se dizajn jednom ponovo gradi za sve njih. Otkaži ili Escape ih odbacuje.", + "parameters.held": "Promjene na čekanju za Primijeni: {count}", + "parameters.held_hint": "Uređujte izraze i jedinice. Promjene čekaju na Primijeni ili U redu.", + "parameters.held_one": "1 promjena na čekanju za Primijeni", "parts.automatic_name": "automatski", "parts.dimension.across_flats": "Širina ključa", "parts.dimension.bore": "Provrt", @@ -1772,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Vijak s poluokruglom glavom i imbusom", "parts.family.dowel_pin": "Cilindrični zatik", "parts.family.hex_bolt": "Vijak sa šestougaonom glavom", + "parts.family.hex_cap_screw_inch": "Vijak sa šestougaonom glavom (inč)", "parts.family.hex_nut": "Šestougaona matica", + "parts.family.hex_nut_inch": "Šestougaona matica (inč)", "parts.family.set_screw": "Bezglavi vijak s imbusom, ravni vrh", "parts.family.socket_head_cap_screw": "Vijak s cilindričnom glavom i imbusom", "parts.family.washer": "Obična podloška", + "parts.family.washer_sae": "Obična podloška, SAE (uska)", + "parts.family.washer_uss": "Obična podloška, USS (široka)", + "parts.holes": "Rupe (neobavezno)", + "parts.placement_hint": "izaberite jednu ili više rupa da u svaku postavite dio, ili ga U redu postavlja u ishodište", + "parts.system": "Sistem jedinica", + "parts.system.inch": "Inčni", + "parts.system.metric": "Metrički", "pattern.alignment_2": "Poravnanje 2", "pattern.alignment_hint": "Broj uključuje original. Centar ravnomjerno raspoređuje kopije; Obrni bira dodatnu stranu za parne ukupne brojeve.", "pattern.direction_1": "Smjer 1", @@ -1828,6 +2157,8 @@ "prefs.bottom_centre": "Dolje u sredini", "prefs.bottom_right": "Dolje desno", "prefs.browser": "Stablo modela", + "prefs.browser_eye_left": "Oko pored strelice za skupljanje", + "prefs.browser_eye_left_note": "Redovi stabla modela prikazuju oko za prikazivanje/skrivanje pored strelice za skupljanje, kao ranije, umjesto u koloni na desnom kraju redova.", "prefs.browser_reveal_on_hover": "Prikaži pri prelasku mišem", "prefs.browser_show_note": "Prikazano drži stablo modela na ekranu. Prikaži pri prelasku mišem drži ga skrivenim dok pokazivač ne pređe preko njegovog mjesta ili tankog jezička na njegovom lijevom rubu, a ostaje otvoreno dok je pokazivač u njemu ili dok je otvoren neki meni iz njega.", "prefs.browser_shown": "Prikazano", @@ -1835,6 +2166,8 @@ "prefs.button_left": "Povlačenje lijevim dugmetom", "prefs.button_middle": "Povlačenje srednjim dugmetom", "prefs.button_right": "Povlačenje desnim dugmetom", + "prefs.carousel_next": "Sljedeće", + "prefs.carousel_previous": "Prethodno", "prefs.choose_font": "Izaberi datoteku fonta…", "prefs.click": "Klik", "prefs.contact_shading": "Meko sjenčenje dodira", @@ -1847,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Zakrivljene površi", "prefs.curves": "Zakrivljene površi", + "prefs.cut_preview_tint": "Prikaži uklonjeni materijal u crvenoj boji", + "prefs.cut_preview_tint_help": "Pregled ispunjava materijal koji operacija uklanja i oblik koji zamjenjuje crvenom prozirnom sjenom. Kada je isključeno, te ispune su potpuno prozirne i crtaju se samo njihovi obrisi.", + "prefs.dark_parts_shading": "Zadrži oblik tamnih dijelova", + "prefs.dark_parts_shading_help": "Sjenči prikaz u linearnom svjetlu s mekim dopunskim svjetlom neba, tako da tamna lica zadrže gradijent umjesto da pocrne", "prefs.dead_zone_note": "Šrafirana traka je mrtva zona: kretanje unutar nje se zanemaruje.", "prefs.default": "podrazumijevano", "prefs.design": "Podrazumijevane postavke dizajna", @@ -1861,6 +2198,8 @@ "prefs.edges": "Ivice i sjenčenje", "prefs.extend": "Produži", "prefs.extra_navigation": "Ctrl + povlačenje lijevim dugmetom po praznom prostoru orbitira; držite razmaknicu za pomjeranje.", + "prefs.extrude_view_isometric": "Okreni prikaz u izometrijski kada se otvori Ekstrudiraj", + "prefs.extrude_view_return": "Vrati se na prethodni prikaz kada se Ekstrudiraj zatvori", "prefs.follows_os": "Prati operativni sistem", "prefs.font": "Font", "prefs.font_fallback": "Znakovi koji nedostaju izabranom fontu prikazuju se ugrađenim fontom, tako da nijedna oznaka ne prikazuje prazan kvadrat.", @@ -1876,8 +2215,11 @@ "prefs.graphics_card_auto": "Automatski", "prefs.graphics_card_missing": "Sačuvana grafička kartica nije dostupna; koristi se Automatski.", "prefs.graphics_card_restart": "Stupa na snagu nakon ponovnog pokretanja SolidCrafta. WGPU_ADAPTER_NAME ima prednost nad ovim izborom.", + "prefs.graphics_card_unused": "Sačuvana grafička kartica nije korištena za ovaj prozor; kartica koja se koristi prikazana je u Pomoć › O programu i u statusnoj traci. Pokušajte s opcijom Automatski ili postavite WGPU_ADAPTER_NAME na jedinstveni dio naziva kartice.", "prefs.graphics_note": "Žrtvujte brzinu za glatkoću. Svaki izbor pokazuje svoj učinak na primjeru.", "prefs.graphics_presets_note": "Unaprijed postavljene vrijednosti podešavaju sve izbore ispod odjednom.", + "prefs.hide_constraint_glyphs_zoomed_out": "Sakrij simbole ograničenja kada je prikaz umanjen", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Simboli ograničenja nestaju iz prikaza kada je skica toliko umanjena da bi je zatrpali. Isključeno: ostaju fiksne veličine na ekranu pri svakom zumiranju.", "prefs.history": "Vremenska traka", "prefs.history_origin_bodies": "Prikaži ishodište i tijela na vrhu", "prefs.history_origin_bodies_note": "Vremenska traka lijevo ili ispod stabla modela počinje folderom Tijela aktivne komponente i Ishodištem, s njihovim okom i menijima kao u stablu modela. Vremenska traka na dnu ostaje nepromijenjena.", @@ -1888,6 +2230,8 @@ "prefs.history_sketches_note": "Kada je Skice postavljeno na Ispod svoje operacije, vremenska traka lijevo prikazuje svaku skicu jedan nivo uvučeno, ispod prve operacije napravljene iz nje, kad god je dovoljno široka za nazive. Vremenska traka na dnu uvijek zadržava redoslijed nastanka.", "prefs.history_sketches_under_feature": "Ispod svoje operacije", "prefs.hold_stop_snapping": "Držite da isključite privlačenje", + "prefs.home_fit_size": "Veličina za Početni prikaz i Uklopi", + "prefs.home_fit_size_note": "Koliki dio prikaza model ispunjava kada ga uokviri Početni prikaz, Uklopi, otvaranje dizajna ili promjena prikaza u navigatoru, bez obzira na to je li postavka ispod uključena. 100 %: ispunjava prikaz između panela, kompasa i navigacijske trake.", "prefs.icons_only": "Samo ikone", "prefs.imported_file": "Uvezena datoteka", "prefs.in_browser": "U stablu modela", @@ -1896,13 +2240,22 @@ "prefs.interface_language": "Jezik interfejsa", "prefs.interface_note": "Kako SolidCraft izgleda i gdje su njegovi dijelovi.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Obrni zakrivljene strelice za valjanje", + "prefs.invert_curved_roll_arrows_note": "Dvije zakrivljene strelice u uglu kocke valjaju prikaz unutar ravni ekrana. Uključeno: strelica u smjeru kazaljke na satu valja prikaz suprotno od smjera kazaljke na satu, a strelica suprotno od smjera kazaljke na satu valja ga u smjeru kazaljke na satu. Isključeno: svaka strelica valja prikaz onako kako je zakrivljena.", + "prefs.invert_navigator_arrows": "Obrni strelice za rotaciju kocke prikaza", + "prefs.invert_navigator_arrows_note": "Strelice oko kocke orbitiraju kameru u smjeru u kojem pokazuju, kao u programima Fusion i Inventor: strelica s lijeve strane pokazuje udesno i zakreće kameru udesno. Isključeno: strelica okreće kocku prema strani na kojoj se nalazi, pa lijeva strelica zakreće kameru ulijevo. Postavka ne utiče na zakrivljene strelice za valjanje.", + "prefs.keep_work_on_tab_switch": "Zadrži dijaloge i alate otvorenima pri prebacivanju između dizajna", + "prefs.keep_work_on_tab_switch_note": "Svaka kartica dizajna zadržava svoj otvoreni dijalog ili alat, s onim što ste u njemu izabrali i upisali, te svoju karticu trake s alatima. Kada se vratite na dizajn, ponovo su tu. Isključeno: prebacivanje između dizajna otkazuje ih i prikazuje karticu Model.", "prefs.labels": "Oznake", + "prefs.language_system": "Sistem", "prefs.layout": "Raspored", "prefs.layout_note": "Kompaktno pričvršćuje panele uz ivice prozora. Prozirnost stabla modela dostupna je u opciji Plutajuće. Stranu Asistenta promijenite na stranici Asistent.", "prefs.left": "Lijevo", "prefs.left_click": "Lijevi klik", "prefs.line_drag_draws_one": "Pritisak i povlačenje crta jednu liniju", "prefs.line_drag_draws_one_note": "U alatu Linija pritisak, povlačenje i puštanje crta jednu liniju od mjesta pritiska do mjesta puštanja i tu se završava. Klikovi i dalje crtaju lanac. Isključeno: povlačenje postavlja tačku tamo gdje se pusti, kao i klik.", + "prefs.line_hover_tangent_arc": "Zadržite pokazivač na posljednjoj tački linije da pređete na tangentni luk", + "prefs.line_hover_tangent_arc_note": "U alatu Linija, nakon što je nacrtan segment, odmaknite pokazivač od posljednje tačke lanca, vratite ga na nju i držite ga mirno: sljedeći klik završava tangentni luk, a isti pokret vraća na linije. Isključeno: zadržavanje na toj tački ne radi ništa.", "prefs.linked_designs": "Povezani dizajni", "prefs.live_input": "Ulaz uživo", "prefs.live_preview": "Pregled uživo", @@ -1916,6 +2269,9 @@ "prefs.max_file_size_step": "STEP i uvezene datoteke", "prefs.max_file_size_web": "Web aplikacija otvara STEP i uvezene datoteke do 512 MB i dizajne do 256 MB: kartica preglednika ne može držati veće datoteke. Desktop aplikacija može povećati ove granice.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Velike ikone", + "prefs.menu_list": "Popis", + "prefs.menus": "Meniji", "prefs.minutes": "minuta", "prefs.minutes_suffix": " min", "prefs.mouse": "Miš i trackpad", @@ -1923,6 +2279,8 @@ "prefs.mouse_mapping": "Mapiranje miša", "prefs.navigation": "Navigacija", "prefs.navigation_note": "Kako miš, trackpad i 3D miš pomjeraju prikaz.", + "prefs.navigator_fit": "Uklopi model nakon promjene prikaza u navigatoru", + "prefs.navigator_fit_note": "Lice, ugao ili strelica kocke prikaza, odnosno osa alata za orijentaciju, također usmjerava pogled na sredinu modela s jedne udaljenosti na kojoj se uklapa iz svakog smjera (njegova granična sfera). Početni prikaz koristi isti zum i centar dok je ova opcija uključena, pa se prikazi koje izaberete poslije njega samo okreću. Isključeno: prikaz se okreće na mjestu i zadržava svoj cilj i zum.", "prefs.network_host_remove": "Ukloni", "prefs.network_locations": "Dozvoli mrežne lokacije u dizajnima", "prefs.network_locations_note": "Isključeno: povezane datoteke dizajna na drugom računaru (\\\\server\\share) otvaraju se samo sa servera navedenih ovdje ili nakon što ga dozvolite kada se to zatraži.", @@ -1935,10 +2293,18 @@ "prefs.origin_plane_names": "Nazivi ravni ishodišta", "prefs.origin_plane_names_note": "Nazivi prikazani u stablu modela, dijalozima i listama. {top} je XY, {front} je XZ, a {right} je YZ, sa Z prema gore. Komande, skripte i sačuvani dizajni zadržavaju XY, XZ i YZ.", "prefs.overall_speed": "Ukupna brzina", + "prefs.parameter_list_rows": "Redovi popisa parametara", + "prefs.parameter_list_rows_tip": "Strelica prema dolje u praznom polju vrijednosti navodi parametre, favorite prvo, do ovog broja. Manji broj održava popis laganim u velikom dizajnu.", + "prefs.persistent_ribbon_pressed": "Istakni aktivne komande na traci", + "prefs.persistent_ribbon_pressed_help": "Ističe komande na traci dok su njihovi efekti uključeni. Isključite da biste zadržali prethodni neutralni izgled i pomoć za komande.", "prefs.perspective_fov": "Vidno polje", "prefs.placement": "Postavljanje", "prefs.prefer_free_sketch_points": "Daj prednost pokretnim tačkama skice kada se tačke preklapaju", "prefs.preview_choices": "Pregled vaših izbora", + "prefs.preview_tint_new_faces": "Oboji novu površ u pregledu", + "prefs.preview_tint_new_faces_help": "Pregled operacije koja mijenja tijelo može nacrtati površ koju dodaje u boji pregleda. Kada je isključeno, tijelo se crta kakvo jest.", + "prefs.print_face_highlight": "Isticanje površine za štampu", + "prefs.print_face_highlight_tip": "Koliko se jako površina za štampu tijela boji i obrubljuje u prikazu. 0 % ne prikazuje isticanje.", "prefs.profile_active": "Aktivni profil", "prefs.profile_applied": "Profil je primijenjen.", "prefs.profile_changed": "Postavke su promijenjene otkako je profil sačuvan. Sačuvaj ih upisuje u profil.", @@ -1960,9 +2326,13 @@ "prefs.quality_fastest": "najbrže", "prefs.quality_slowest": "najsporije", "prefs.quality_smoother": "glađe", + "prefs.quick_measure": "Brzo mjerenje u uglu prikaza", + "prefs.quick_measure_note": "Veličina izbora u donjem desnom uglu prikaza: dužina ivice, ili Ø i R za okruglu, površina lica, položaj tačke, udaljenost i ugao dviju stavki, ukupna vrijednost više ivica ili lica. Klik je kopira.", "prefs.render_previous_geometry_budget": "Koristi prethodni budžet geometrije za pregled renderovanja", "prefs.render_previous_geometry_budget_help": "Vraća prethodno fiksno ograničenje geometrije (512 MiB na 64-bitnim desktop računarima, 128 MiB drugdje) umjesto budžeta prema uređaju.", "prefs.reports_saved": "Sačuvano: {n}", + "prefs.ribbon_click_ends_tool": "Klik na dugme aktivnog alata završava ga", + "prefs.ribbon_click_ends_tool_note": "Klik na istaknuto dugme na traci alata za skiciranje koji je u upotrebi završava taj alat, pa klikovi u prikazu ponovo služe za biranje. Isključeno: klik ponovo pokreće alat.", "prefs.ribbon_reveal": "Prikaži rezultate pretrage na traci", "prefs.ribbon_reveal_note": "Zadržavanje pokazivača iznad rezultata u Pretraži komande pokazuje gdje se komanda nalazi na traci: njenu karticu, njeno dugme ili njen red u padajućem meniju panela. Komanda pokrenuta iz pretrage tamo trepće, a pokrenuta komanda iz padajućeg menija označava svoj panel.", "prefs.right_click": "Desni klik", @@ -1973,6 +2343,8 @@ "prefs.search_empty": "Nema odgovarajućih postavki", "prefs.select": "Izbor", "prefs.select_one_item": "Izaberi jednu stavku", + "prefs.select_other_hidden": "Izaberi skrivenu geometriju pomoću Izaberi drugo", + "prefs.select_other_hidden_help": "Uključeno: obuhvata skrivena tijela, skice i zaklonjene ivice u blizini pokazivača. Isključeno: koristi se izvorni popis vidljive geometrije ispod pokazivača.", "prefs.selecting": "Biranje", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift samo dodaje; Ctrl / Cmd uključuje i isključuje", @@ -1984,11 +2356,16 @@ "prefs.sketch_align_points_note": "Tokom crtanja tačka se istovremeno poravnava vodoravno s jednom tačkom skice i okomito s drugom, uz tačkastu pomoćnu liniju, a klik zadržava oba poravnanja. Isključeno: samo s prethodnom tačkom, po jedna osa.", "prefs.sketch_conflict_colour": "Geometrija u sukobu u boji sukoba", "prefs.sketch_conflict_colour_note": "Dok su ograničenja skice u sukobu, krive i tačke koje drži ograničenje koje ne uspijeva crtaju se također u boji sukoba, ne samo njegov simbol ili kota. Isključeno: zadržavaju uobičajene boje.", + "prefs.sketch_construction_lines": "Prošireni alati za pomoćne prave", "prefs.sketch_exit_view": "Kada se skica završi", "prefs.sketch_exit_view.keep": "Zadrži trenutni prikaz", "prefs.sketch_exit_view.previous": "Vrati se na prethodni prikaz", "prefs.sketch_exit_view.unless_rotated": "Vrati se osim ako je rotirano", "prefs.sketch_exit_view_note": "Kuda prikaz ide nakon Završi skicu, Otkaži ili dvostrukog Esc.", + "prefs.sketch_face_activates_part": "Skiciranje na licu dijela čini taj dio aktivnim", + "prefs.sketch_face_activates_part_note": "Skica započeta na licu tijela druge komponente prvo aktivira tu komponentu, pa skica pripada njoj i u stablu modela ostaje uz taj dio. Taj dio nakon toga ostaje aktivan. Isključeno: skica pripada aktivnoj komponenti.", + "prefs.sketch_open_look_at": "Okreni kameru prema skici kad se otvori", + "prefs.sketch_open_look_at_note": "Isključeno: kad napravite ili uredite skicu, prikaz ostaje onakav kakav jest. Pogledaj okreće prikaz prema skici kad to želite.", "prefs.sketch_recent_snap": "Automatski privlači na nedavne centre i središnje tačke", "prefs.sketch_recent_snap_note": "Tokom crtanja pokazivač se privlači tamo gdje se sijeku pomoćne linije dvaju posljednjih centara krugova ili središnjih tačaka pravih ivica. Isključeno: te pomoćne linije služe samo za prikaz i pokazivač se ne pomjera.", "prefs.sketch_selection": "Skica i izbor", @@ -2000,6 +2377,8 @@ "prefs.sketch_tab_always_note": "Kartica Skica ostaje na traci, odmah iza Modela, dok nijedna skica nije otvorena. Njeni alati za crtanje tada pokreću skicu na izabranoj ravni ili licu, ili na ravni koju sljedeću izaberete, s alatom spremnim u njoj.", "prefs.sketch_tracking_guides": "Pomoćne linije poravnanja centra i središnje tačke", "prefs.sketch_tracking_guides_note": "Zadržite pokazivač iznad centra kruga ili središnje tačke prave ivice, pa se pomjerite vodoravno ili okomito da se prikaže privremena tačkasta pomoćna linija.", + "prefs.sketch_tracking_points": "Pomoćne linije poravnanja iz krajnjih tačaka i uglova tokom crtanja", + "prefs.sketch_tracking_points_note": "Dok alat za crtanje čeka tačku, prelazak mišem preko kraja linije ili luka, ugla pravougaonika ili slobodne tačke prikazuje istu privremenu tačkastu pomoćnu liniju kao centar ili središnja tačka. Isključeno: samo centri i središnje tačke.", "prefs.sketching": "Skiciranje", "prefs.snap_drawing_note": "Tokom crtanja ili povlačenja tačke skice.", "prefs.source": "Izvor", @@ -2016,6 +2395,24 @@ "prefs.status_error": "Greška", "prefs.status_selected": "Izabrano", "prefs.status_warning": "Upozorenje", + "prefs.structure.appearance": "Izgled", + "prefs.structure.appearance_note": "Boje, tekst i pristupačnost.", + "prefs.structure.in_profile": "U profilu", + "prefs.structure.layout": "Raspored", + "prefs.structure.layout_note": "Gdje se nalaze dijelovi prozora.", + "prefs.structure.look": "Vizuelno", + "prefs.structure.measure_pointer": "Mjerenje i pokazivač", + "prefs.structure.mouse3d": "3D miš", + "prefs.structure.mouse3d_note": "SpaceMouse i SpaceNavigator.", + "prefs.structure.navigation_note": "Miš i trackpad. 3D miš ima vlastitu stranicu.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Promijenjeno otkako je sačuvano", + "prefs.structure.profile_hover": "Sačuvano u profilima postavki", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Skica", + "prefs.structure.tools": "Alati", + "prefs.structure.tools_note": "Kako se ponašaju alati za modeliranje.", + "prefs.structure.work": "Rad", "prefs.supersampling_brief": "Iscrtava prikaz većim i smanjuje ga filtriranjem: vrlo oštro i zahtjevnije.", "prefs.tab_accent_note": "Naglasna boja prati aktivnu karticu", "prefs.theme_file": "datoteka teme", @@ -2027,6 +2424,16 @@ "prefs.theme_follow_off": "Isključeno", "prefs.theme_follow_stop": "Prestani pratiti", "prefs.theme_import_hint": "Kliknite da izaberete datoteku teme, ispustite je ovdje ili pritisnite Ctrl+V (Cmd+V na Macu) kada je tema kopirana", + "prefs.theme_option_opacity": "Neprozirnost", + "prefs.theme_option_opacity_help": "Podesite neprozirnost plutajućih panela. Donja granica čitljivosti štiti tekst preko boja prozora prikaza.", + "prefs.theme_option_tab_colours": "Boje kartica", + "prefs.theme_option_tab_colours_help": "Koristi boje panela i prozora prikaza ove teme za svaku karticu trake.", + "prefs.theme_option_tab_fade_ms": "Prelaz kartica", + "prefs.theme_option_tab_fade_ms_help": "Boje panela i prozora prikaza postepeno se mijenjaju pri prelasku na drugu karticu. Nula mijenja odmah.", + "prefs.theme_options_badge": "Opcije", + "prefs.theme_options_more": "Više · {count}", + "prefs.theme_options_reset": "Resetuj", + "prefs.theme_options_unavailable": "Nedostupno na ovom uređaju", "prefs.theme_paste": "Zalijepi temu", "prefs.theme_paste_none": "Međuspremnik ne sadrži SolidCraft temu", "prefs.timeline_half_hour": "−30 min", @@ -2048,13 +2455,23 @@ "prefs.under_cursor": "Ispod pokazivača", "prefs.units_precision": "Jedinice i preciznost", "prefs.updates": "Ažuriranja", + "prefs.value_boxes_in_view": "Prikaži vrijednosti pored njihovih ručica u prikazu", + "prefs.value_boxes_in_view_tip": "Vrijednost komande (Udaljenost, Poluprečnik…) u polju pored njene ručice, preko modela. Isključeno: upisujete je u prozoru komande, koji preuzima tastaturu nakon izbora, i ništa ne prekriva model.", "prefs.view": "Ponašanje prikaza", "prefs.view_confirm_corner": "U redu i Otkaži u uglu prikaza", "prefs.view_confirm_corner_note": "Dok je otvoren dijalog ili skica, kvačica i krstić gore desno u prikazu rade isto što i dugmad U redu i Otkaži u dijalogu, odnosno završavaju i otkazuju skicu. Navigator prikaza pomjera se ispod njih.", "prefs.viewport": "Prozor prikaza", + "prefs.viewport_analysis_status": "Prikaži status analize u prozoru prikaza", + "prefs.viewport_analysis_status_help": "Prikazuje aktivne analize iznad prozora prikaza, otvara njihove legende iz svake stavke, a tipka Esc isključuje najnoviju analizu. Isključite da biste vratili legende u uglovima i prethodno ponašanje tipke Esc.", "prefs.viewport_background": "Pozadina", "prefs.viewport_background_colour": "Boja", "prefs.viewport_background_theme": "Gradijent teme", + "prefs.viewport_section_status": "Prikaži status presjeka u prozoru prikaza", + "prefs.viewport_section_status_help": "Prikazuje postavku presjeka u prozoru prikaza. Escape i aktivno dugme na traci je isključuju. Isključite da zadržite prethodne kontrole presjeka.", + "prefs.viewport_status_details": "Detalji prozora prikaza uživo", + "prefs.viewport_status_details_help": "Uređujte postavke aktivne analize i presjeka u standardnim karticama s detaljima. Isključite da vratite legende analize samo za čitanje i dijalog Presjek.", + "prefs.viewport_status_summary": "Sažmi stavke statusa prozora prikaza", + "prefs.viewport_status_summary_help": "Sažima tri ili više stavki statusa prozora prikaza u jednu sažetu oznaku. Isključite da svaka stavka ostane u punom redu.", "prefs.wheel": "Točkić", "prefs.wheel_trackpad": "Točkić i trackpad", "prefs.workspace": "Radni prostor", @@ -2064,6 +2481,10 @@ "properties.title": "Svojstva: {name}", "recovery.days_ago": "prije {count} dana", "recovery.detail": "{file} · operacija: {features} · automatski sačuvano {when}", + "recovery.discard_all": "Odbaci sve", + "recovery.discard_all_detail": "Ovo se ne može poništiti.", + "recovery.discard_all_title": "Odbaciti automatska čuvanja ({count})?", + "recovery.discard_all_title_one": "Odbaciti 1 automatsko čuvanje?", "recovery.hours_ago": "prije {count} h", "recovery.just_now": "upravo sada", "recovery.min_ago": "prije {count} min", @@ -2179,6 +2600,10 @@ "render.base_color": "Osnovna boja · sRGB", "render.base_metallic": "Metalni udio", "render.base_opaque_only": "Ovaj uređivač čuva semantiku neprozirnih tijela. Za optičko propuštanje koristite izričite kontrole stakla.", + "render.batch_all_shots": "Svi kadrovi ({count})", + "render.batch_empty": "Sačuvajte kadar prije renderovanja svih kadrova.", + "render.batch_limit": "Renderovanje svih kadrova ograničeno je na 32 kadra.", + "render.batch_status": "U toku: {running} · Na čekanju: {waiting}", "render.bloom_enable": "Sjaj prikaza", "render.bloom_help": "Kreativni sjaj samo na izlazu iz pozitivnih linearnih svijetlih dijelova, raširen kroz tri normalizovana prolaza kutijastog filtera. Poluprečnik je u pikselima izlaza. Dodaje se u linearnoj svjetlosti prikaza prije sRGB-a; nije objektiv, volumetrijski efekat niti poboljšanje konvergencije. Sirovi EXR ostaje nepromijenjen.", "render.bloom_opaque": "Sjaj zahtijeva neprozirni izlaz. Prozirni PNG se odbija, a ne spljoštava tiho.", @@ -2289,6 +2714,13 @@ "render.choose_look": "Prvo izaberite izgled u Izgledima", "render.chromatic_offset": "Hromatski pomak ivica", "render.clear_stage": "Ukloni sačuvanu scenu", + "render.compare_divider": "Razdjelnik poređenja", + "render.compare_live": "Uživo", + "render.compare_live_preview": "Pregled uživo", + "render.compare_render": "Renderovanje {number}", + "render.compare_side": "Renderovanje {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · zabilježeno u reviziji {revision}", + "render.compare_swap": "Zamijeni strane", "render.copy_request": "Kopiraj JSON", "render.cpu_aa_help": "Prostorni uzorci: više uzoraka poboljšava ivice i produžava renderovanje.", "render.cpu_area_add": "Dodaj pravougaono CPU svjetlo", @@ -2929,7 +3361,9 @@ "render.output_ready": "Spremno za renderovanje", "render.output_run_check": "Pokreni provjeru", "render.output_size_limit": "{method}: do {dimension} px po strani i {pixels} piksela. Najveća veličina koja staje: {width} × {height}.", + "render.output_size_method_profile": "Za renderovanje {width} × {height} izaberite {method} s CPU profilom resursa {profile} ili manju veličinu.", "render.output_size_ok": "Veličina u redu · {width} × {height} px", + "render.output_size_profile": "Za renderovanje {width} × {height} izaberite CPU profil resursa {profile} ili manju veličinu.", "render.output_swap_orientation": "Zamijeni širinu i visinu", "render.output_tools_inspector": "Veličinu i format uredite u inspektoru Izlaz.", "render.output_view_image": "Prikaži sliku", @@ -3036,6 +3470,10 @@ "render.result_retained": "Prikazuje se posljednja završena slika; novije renderovanje je još nije zamijenilo.", "render.result_sequence": "Kontrolna tačka", "render.result_title": "Rezultat renderovanja", + "render.results_choose": "Zadržani rezultati", + "render.results_label": "Renderovanje {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [zastarjelo]", + "render.results_unnamed": "Slika", "render.return_design": "Nazad na Dizajn", "render.review_stale": "Ovaj pregled je zastario. Riješite ga ili ponovo provjerite prije primjene.", "render.ribbon_aging": "Starenje", @@ -3142,6 +3580,7 @@ "render.size_custom": "Prilagođeno…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · potrebno: {profile}", "render.size_presets": "Predlošci veličine", "render.size_presets_pending": "Stiže s uređivačem izlaza", "render.size_preview": "Pregled", @@ -3429,6 +3868,24 @@ "sheet.flange_type_contour": "Kontura", "sheet.flange_type_edge": "Ivica", "sheet.no_body": "nema limenog tijela: napravite ga pomoću Prirubnica > Osnova ili pretvorite ploču u lim pomoću Pretvori u lim (izaberite njeno veliko ravno lice)", + "sheet.personal_rules.confirm_delete": "Potvrdi brisanje", + "sheet.personal_rules.delete": "Izbriši", + "sheet.personal_rules.delete_prompt": "Izbrisati ovo lično pravilo? Pravila već u dizajnima ostaju nepromijenjena.", + "sheet.personal_rules.full": "Lična biblioteka već sadrži 64 pravila.", + "sheet.personal_rules.invalid_name": "Unesite kratak naziv bez prijeloma reda ili kontrolnih znakova.", + "sheet.personal_rules.invalid_values": "Dopunite vrijednosti pravila: svaka se mora izračunati u ovom dizajnu, s pozitivnom debljinom i K-faktorom od 0 do 1.", + "sheet.personal_rules.missing": "Izabrano lično pravilo više nije dostupno.", + "sheet.personal_rules.name": "Naziv pravila", + "sheet.personal_rules.name_exists": "Lično pravilo s ovim nazivom već postoji. Koristite drugi naziv.", + "sheet.personal_rules.name_hint": "Jedinstven naziv", + "sheet.personal_rules.overwrite": "Sačuvaj promjene u izabranom ličnom pravilu", + "sheet.personal_rules.rename": "Preimenuj", + "sheet.personal_rules.rule": "Lično pravilo", + "sheet.personal_rules.save": "Sačuvaj novo", + "sheet.personal_rules.scope": "Čuva se u vašem profilu za sve dizajne.", + "sheet.personal_rules.select": "Izaberite pravilo", + "sheet.personal_rules.title": "Lična pravila", + "sheet.personal_rules.unsupported": "Ovo pravilo ima vrijednosti koje ova verzija ne može koristiti.", "shortcut.json_error": "parametri moraju biti JSON: {error}", "shortcut.no_command": "nema komande `{id}`; tekst prije JSON-a mora biti id komande", "shortcut.pin": "Prikači na vrh S okvira", @@ -3465,8 +3922,10 @@ "sketch_text.align_right": "Desno", "sketch_text.bold": "Podebljano", "sketch_text.builtin_font": "{family} (ugrađeno)", + "sketch_text.formula": "Počnite znakom = da riječi složite iz parametara: ='W' + number(Width)", "sketch_text.italic": "Kurziv", "sketch_text.loading_fonts": "Traženje instaliranih fontova…", + "sketch_text.no_bold": "Ugrađeni font nema podebljanu varijantu: izaberite instalirani font", "sketch_text.on_path": "Tekst prati svoju putanju: kriva ga postavlja", "sketch_text.path_clear": "Skini tekst s njegove krive", "sketch_text.path_hint": "Kriva skice koju tekst prati: kliknite ovdje, a zatim krivu", @@ -3498,10 +3957,7 @@ "the two origins are on the same component": "oba ishodišta su na istoj komponenti", "thread.automatic_size": "Automatska veličina", "thread.designation": "Oznaka", - "thread.direction": "Smjer navoja", "thread.iso_metric": "ISO metrički", - "thread.left_hand": "Lijevi", - "thread.right_hand": "Desni", "thread.select_size": "Izaberite veličinu", "timeline.delete_after_marker_one": "Izbriši 1 operaciju nakon oznake vraćanja", "timeline.delete_after_marker_other": "Izbriši operacije nakon oznake vraćanja: {count}", @@ -3605,6 +4061,8 @@ "ui.3d_mouse_section": "3D miš", "ui.3d_mouse_show_in_view": "Prikaži 3D miš u 3D prikazu", "ui.3d_mouse_show_in_view_tip": "Slika vašeg 3D miša u donjem lijevom uglu, koja se kreće dok ga pomjerate.", + "ui.3d_mouse_sketch_orbit": "Okreći skice 3D mišem", + "ui.3d_mouse_sketch_orbit_tip": "3D miš okreće prikaz i dok je skica otvorena i gledana pod pravim uglom, kao što to može i miš. Isključeno: pomjera i zumira skicu dok ne nagnete prikaz.", "ui.3d_mouse_skip": "Moj uređaj ovo ne može", "ui.3d_mouse_skip_tip": "Preskače ovo kretanje u oba smjera, a kalibracija ga izostavlja.", "ui.3d_mouse_speed": "Brzina 3D miša", @@ -3633,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Zakrenite kapicu suprotno od kazaljke na satu, držite je, a zatim pustite.", "ui.3d_mouse_switch_cap": "Kalibriši kao Povratak u centar", "ui.3d_mouse_switch_trackball": "Kalibriši kao trackball", + "ui.3d_mouse_use_direct": "Koristi direktni drajver", + "ui.3d_mouse_use_direct_tip": "Čitaj 3D miš direktno (hidraw) umjesto preko spacenavd.", "ui.3d_mouse_view_axis": "Osa prikaza", "ui.3d_mouse_view_off": "Isključeno", "ui.3d_mouse_view_off_tip": "Profil drajvera 3D miša isključuje ovu osu, pa njeno kretanje ne pomjera prikaz. Izbor kretanja druge ose ovdje ih zamjenjuje, a to kretanje prestaje pomjerati prikaz.", @@ -3671,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Pokrenite ovo u terminalu, a zatim pritisnite Poveži ponovo:", "ui.agent_chat_auth_title": "Prijavi se kod agenta", "ui.agent_chat_cancel": "Otkaži", + "ui.agent_chat_cancel_timeout": "Agent nije odgovorio na Zaustavi pa je veza s njim prekinuta. Povežite se ponovo da biste nastavili.", + "ui.agent_chat_cannot_start": "Instalirano, ali se ne pokreće: {error}", "ui.agent_chat_changes": "Promjene: {n}, jedan korak poništavanja", "ui.agent_chat_changes_n": "Promjene: {n}", "ui.agent_chat_changes_of": "Promjene: {n}/{limit}", @@ -3679,11 +4141,13 @@ "ui.agent_chat_command": "Komanda agenta", "ui.agent_chat_connect": "Poveži", "ui.agent_chat_copy": "Kopiraj", + "ui.agent_chat_copy_message": "Kopiraj poruku", "ui.agent_chat_ctx_bodies": "Tijela", "ui.agent_chat_ctx_elements": "Elementi", "ui.agent_chat_ctx_features": "Operacije", "ui.agent_chat_ctx_more": "+još {n}", "ui.agent_chat_ctx_other": "Ostalo", + "ui.agent_chat_custom_heading": "Prilagođeni model", "ui.agent_chat_custom_hint": "Bilo koji program koji govori Agent Client Protocol na stdin i stdout. Ne pokreće ga nikakva ljuska.", "ui.agent_chat_denied": "Odbijeno", "ui.agent_chat_deny": "Odbij", @@ -3727,8 +4191,16 @@ "ui.agent_chat_mode_all": "Sve", "ui.agent_chat_mode_ask": "Pitaj", "ui.agent_chat_mode_edits": "Izmjene", + "ui.agent_chat_model_custom": "Koristi prilagođeni: {model}", "ui.agent_chat_model_no_tools": "{model} ne može koristiti SolidCraft alate, pa može samo razgovarati. Izaberite model s podrškom za alate.", + "ui.agent_chat_model_rejected": "Agent nije prihvatio model {model}: {error}", + "ui.agent_chat_model_search": "Pretraži modele…", "ui.agent_chat_model_tip": "Model koji agent koristi. Vaš izbor se pamti za ovog agenta.", + "ui.agent_chat_models_failed": "Popis modela nije moguće učitati: {error}", + "ui.agent_chat_models_heading": "Dostupni modeli", + "ui.agent_chat_models_listing": "Učitavanje popisa modela…", + "ui.agent_chat_models_none": "Krajnja tačka ne navodi nijedan model", + "ui.agent_chat_models_not_a_list": "Odgovor nije popis modela", "ui.agent_chat_new": "Novi razgovor", "ui.agent_chat_new_confirm": "Započeti novi razgovor? Trenutni će biti obrisan.", "ui.agent_chat_next_picture": "Sljedeća slika", @@ -3763,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "U redu čekanja (zaustavljeno, nije poslano)", "ui.agent_chat_refresh": "Osvježi", "ui.agent_chat_refused": "Nije dozvoljeno agentu: {reason}", + "ui.agent_chat_reinstall": "{agent} je instaliran ({program}), ali se nije pokrenuo kada ga je SolidCraft provjerio: {error}\nNjegova instalacija možda nije potpuna ili je napravljena za drugu vrstu računara. Instalirajte ga ponovo naredbom `{install}`, provjerite da li u terminalu ispisuje svoju verziju, a zatim pritisnite Osvježi.", "ui.agent_chat_remove": "Ukloni iz reda", "ui.agent_chat_remove_file": "Skini s ove poruke", "ui.agent_chat_remove_imported": "Skini s ove poruke; dio ostaje u dizajnu (Poništi ga uklanja)", + "ui.agent_chat_reply_cut_off": "Odgovor je dostigao ograničenje dužine prije nego što je završen, pa može biti nepotpun. Zamolite agenta da nastavi ili da da kraći odgovor.", + "ui.agent_chat_reply_declined": "Model je odbio odgovoriti na ovu poruku.", "ui.agent_chat_retry": "Pokušaj ponovo", "ui.agent_chat_right": "Desno", "ui.agent_chat_save": "Sačuvaj", @@ -3824,12 +4299,17 @@ "ui.ai_copy_suffix": "kopiraj", "ui.ai_custom_url": "Prilagođeni URL", "ui.ai_default": "Podrazumijevano", + "ui.ai_edit": "Uredi", + "ui.ai_edit_agent_title": "Uredi agenta", + "ui.ai_edit_gone": "Ovaj agent je uklonjen, pa nema šta da se sačuva.", + "ui.ai_edit_tip": "Promijenite naziv, komandu ili krajnju tačku ovog agenta. Sačuvani ključ ostaje skriven.", "ui.ai_http_busy": "krajnja tačka je zauzeta ili je preko ograničenja; pokušajte ponovo kasnije", "ui.ai_http_key": "krajnja tačka je odbila ključ: provjerite ga u Postavke > AI", "ui.ai_http_not_found": "nema takve krajnje tačke ili modela: provjerite osnovni URL i naziv modela", "ui.ai_http_too_large": "razgovor je prevelik za ovu krajnju tačku; započnite novi razgovor", "ui.ai_key": "API ključ", "ui.ai_key_hint": "neobavezno; čuva se u sistemskom privjesku ključeva", + "ui.ai_key_keep_hint": "ostavite prazno da zadržite sačuvani ključ", "ui.ai_key_needs_https": "Ključ se šalje samo preko HTTPS-a ili na ovaj računar.", "ui.ai_key_note": "Čuva se u sistemskom privjesku ključeva, nikad u postavkama SolidCrafta. Za lokalni server ostavite prazno.", "ui.ai_keychain_error": "Sistemski privjesak ključeva je odbio: {error}", @@ -3856,11 +4336,15 @@ "ui.ai_permissions": "Dozvole", "ui.ai_preset": "Unaprijed postavljeno", "ui.ai_protocol": "Protokol", + "ui.ai_reasoning_effort": "Nivo zaključivanja", + "ui.ai_reasoning_effort_field_hint": "prazno = podrazumijevana vrijednost pružaoca", + "ui.ai_reasoning_effort_hint": "Neobavezno. Šalje se krajnjoj tački kao `reasoning_effort`; prihvaćene vrijednosti razlikuju se od pružaoca do pružaoca (na primjer `low`, `high` ili `max`). SolidCraft nikad ne mijenja vrijednost koju ovdje postavite. Ostavite prazno da se ništa ne šalje i da se zadrži podrazumijevana vrijednost pružaoca.", "ui.ai_remove": "Ukloni", "ui.ai_request_timed_out": "Model je trajao duže od {seconds} s. Vremensko ograničenje zahtjeva za ovu krajnju tačku možete povećati u Postavke › Asistent.", "ui.ai_request_timeout": "Vremensko ograničenje zahtjeva", "ui.ai_request_timeout_hint": "Koliko dugo jedan zahtjev modelu na ovoj krajnjoj tački smije trajati, od 30 s do jednog sata. Povećajte za spori lokalni model.", "ui.ai_reset": "Resetuj", + "ui.ai_save": "Sačuvaj", "ui.ai_settings": "AI postavke…", "ui.ai_show_features": "Prikaži AI funkcije", "ui.ai_show_features_note": "Razgovor s agentom: panel u kojem agent za kodiranje koji već koristite ili krajnja tačka modela koju izaberete radi na otvorenom dizajnu. Isključeno: nema AI dugmeta, prečice, stavke menija ni panela, i ništa se ne traži niti pokreće.", @@ -3949,6 +4433,7 @@ "ui.circle": "Krug", "ui.circular_pattern": "Kružni niz", "ui.clear": "Očisti", + "ui.clear_print_face": "Ukloni površinu za štampu", "ui.clear_recent": "Očisti nedavno", "ui.clear_the_selection": "Poništi izbor", "ui.click_selects_whole_bodies": "Klik bira cijela tijela", @@ -3983,7 +4468,17 @@ "ui.constant": "Konstantno", "ui.constraints_conflict": "Ograničenja su u sukobu", "ui.construction": "Pomoćna", + "ui.construction.angle_hint": "Pomoćna prava: kliknite tačku, pa upišite ugao ili izaberite smjer", + "ui.construction.bisector_hint": "Simetrala: izaberite dvije prave linije koje se sijeku, pa željeno rješenje", + "ui.construction.common_hint": "Zajednička tangenta: izaberite dva kruga ili luka, pa željeno rješenje", + "ui.construction.contact_hint": "Tangenta: izaberite krug/luk ili otvoreni splajn/koniku, pa tačku dodira (krive slobodnog oblika: krajnje tačke)", + "ui.construction.external_hint": "Tangenta: izaberite krug ili luk, vanjsku tačku, pa željeno rješenje", + "ui.construction.free_hint": "Pomoćna prava: kliknite dvije tačke; desnim klikom počnite ispočetka", + "ui.construction.normal_needs_length": "Beskonačna linija je uvijek pomoćna: upišite dužinu da biste nacrtali običnu liniju", + "ui.construction.point_hint": "Pomoćna prava: kliknite tačku kroz koju prolazi", + "ui.construction.reference_hint": "Pomoćna prava: izaberite pravu liniju, pa tačku; desnim klikom promijenite referencu", "ui.construction.ribbon_label": "Pomoćne", + "ui.construction.side_hint": "Pomoćna prava: kliknite stranu prema kojoj linija ide; desnim klikom počnite ispočetka", "ui.context_menu": "Kontekstni meni", "ui.continuity_g0": "G0 pregib", "ui.continuity_g1": "G1 tangentno", @@ -4011,6 +4506,7 @@ "ui.dark": "Tamna", "ui.default_modelling_orientation": "Podrazumijevana orijentacija modeliranja", "ui.delete": "Izbriši", + "ui.delete_select_first": "Prvo izaberite šta želite izbrisati: operacije, tijela, komponente ili geometriju skice", "ui.depth": "Dubina", "ui.design": "Dizajn", "ui.design_properties.author": "Autor", @@ -4025,6 +4521,40 @@ "ui.design_properties.project": "Projekat", "ui.design_properties.revision": "Revizija", "ui.design_saved": "Sačuvano: {path}", + "ui.details_access_caption": "Lica pokazuju može li alat doći do njih iz izabranog smjera.", + "ui.details_angle": "Ugao", + "ui.details_continuity_caption": "Uredite izabrani šav. Ostali šavovi zadržavaju vlastite postavke.", + "ui.details_continuity_stale": "Ranija geometrija: ponovo pokrenite analizu da uredite ili uokvirite ovaj šav.", + "ui.details_copy_list": "Kopiraj popis", + "ui.details_curvature": "Tolerancija zakrivljenosti", + "ui.details_curvature_caption": "Lica su obojena prema svom lokalnom poluprečniku zakrivljenosti.", + "ui.details_direction": "Smjer alata", + "ui.details_draft_caption": "Lica su obojena prema svom uglu u odnosu na smjer vađenja iz kalupa.", + "ui.details_edit_seam": "Uredi šav", + "ui.details_fixture": "Uzorak komponente — samo probni podaci", + "ui.details_fixture_caption": "Uzorak komponente s ilustrativnim vrijednostima; ovo nije rezultat modela.", + "ui.details_fixture_problem": "Primjer nalaza s problemom", + "ui.details_fixture_readout": "Primjer izmjerene vrijednosti", + "ui.details_flip": "Obrni", + "ui.details_gap": "Otvoreni kraj", + "ui.details_hatch": "Šrafiraj presječena lica", + "ui.details_jump": "Skok zakrivljenosti", + "ui.details_key": "Legenda", + "ui.details_offset": "Odmak", + "ui.details_plane": "Ravan", + "ui.details_pull": "Smjer vađenja iz kalupa", + "ui.details_radius": "Poluprečnik", + "ui.details_readout": "Očitanje", + "ui.details_samples": "Uzorci", + "ui.details_seam": "{body} · Ivica {edge}", + "ui.details_settings": "Postavke", + "ui.details_sharp_gap": "Oštro ili otvoreno", + "ui.details_show_all": "Prikaži svih {count}", + "ui.details_smooth": "Glatko", + "ui.details_stripes": "Pruge", + "ui.details_target": "Uokviri geometriju", + "ui.details_worst_seams": "Najgori šavovi", + "ui.details_zebra_caption": "Reflektovane pruge pokazuju koliko se glatko lica spajaju.", "ui.diameter": "Prečnik", "ui.dimension": "Kota", "ui.direct_interaction": "Direktna interakcija", @@ -4069,6 +4599,7 @@ "ui.edit_in_place_saved_elsewhere": "Dio je sačuvan u drugu datoteku; sklop i dalje povezuje: {name}", "ui.edit_in_place_wait": "Pričekajte da se završi ono što se izvršava u dizajnu", "ui.edit_section_analysis": "Uredi analizu presjeka", + "ui.edit_sketch_empty": "Nema skica za uređivanje", "ui.ellipse": "Elipsa", "ui.emboss_wrap_note": "Ortogonalni linijski profili koji tangiraju jedan podržani cilindar obavijaju se automatski. Izaberite zid da izaberete cilj.", "ui.end_radius": "Krajnji poluprečnik", @@ -4079,12 +4610,15 @@ "ui.equation_explicit": "Eksplicitno", "ui.equation_form": "Oblik", "ui.equation_note": "Varijabla je običan broj: sin(t) je uzima u radijanima. Rezultat bez jedinice je u jedinici dizajna.", + "ui.equation_note_range": "Varijabla je dužina, kao i njen raspon: kombinujte je s parametrima dužine, a za sin() je podijelite dužinom. Rezultat bez jedinice je u jedinici dizajna.", "ui.equation_parametric": "Parametarski", + "ui.equation_variable_unit": "Varijabla ima jedinicu raspona", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Ekvivalentni poluprečnik", "ui.expand": "Proširi", + "ui.explode_needs_two_components": "Rastavljeni prikaz razdvaja komponente, pa dizajn treba imati dvije ili više njih (Nova komponenta, Umetni dizajn ili Napravi komponente iz tijela)", "ui.exportDxf": "Izvezi DXF…", "ui.export_ellipsis_keymap": "Izvezi…", "ui.export_keymap_tip": "Tipke, favoriti okvira S i traka s alatima, kao datoteka", @@ -4210,6 +4744,7 @@ "ui.hideOrigin": "Sakrij ishodište", "ui.hidePlanes": "Sakrij ravni", "ui.hideProfile": "Sakrij profil", + "ui.hide_component_history": "Sakrij njenu vremensku traku", "ui.hide_origin_by_default": "Podrazumijevano sakrij ishodište", "ui.hide_origin_note": "Novi dizajni počinju sa skrivenim folderom Ishodište. Dizajn zadržava vlastitu postavku Ishodišta kada ga prikažete ili sakrijete.", "ui.history_back": "Idi korak nazad", @@ -4217,6 +4752,7 @@ "ui.history_edge_hint": "dvaput kliknite ivicu", "ui.history_first": "Idi na početak", "ui.history_forward": "Idi korak naprijed", + "ui.history_hide_hidden": "Sakrij skrivene komponente", "ui.history_hide_names": "Sakrij nazive", "ui.history_last": "Idi na kraj", "ui.history_marker_tip": "Oznaka vraćanja: povucite da vratite model unazad; nove operacije dolaze ovdje", @@ -4226,10 +4762,12 @@ "ui.history_play_button_show": "Prikaži dugme za reprodukciju", "ui.history_play_finish_action": "Završite trenutnu radnju prije reprodukcije vremenske trake", "ui.history_play_roll_back": "Pomjerite oznaku vraćanja unazad prije reprodukcije", + "ui.history_show_hidden": "Prikaži skrivene komponente", "ui.history_show_names": "Prikaži nazive", "ui.history_sketch_listed_under": "Navedeno ispod {feature}", "ui.history_title": "Vremenska traka", "ui.history_toggle_names": "Prikaži ili sakrij nazive operacija", + "ui.history_waits_for_editor": "Poništi, Ponovi i vremenska traka čekaju dok se ne otvori uređivač operacije", "ui.hole": "Rupa", "ui.hole_tap_type": "Vrsta navoja rupe", "ui.hole_type": "Vrsta rupe", @@ -4245,6 +4783,7 @@ "ui.insert_design.saved_file": "{name} ima nesačuvane promjene, pa je umetnuta njegova sačuvana datoteka. Sačuvajte ga, a zatim pokrenite Ažuriraj veze da unesete promjene.", "ui.insert_design.unsaved": "Nesačuvane promjene", "ui.inspect": "Pregledaj", + "ui.instances": "Instance", "ui.intersect": "Presjek", "ui.isolate": "Izoluj", "ui.join": "Spoji", @@ -4253,12 +4792,14 @@ "ui.joints": "Spojevi", "ui.keyboard_shortcuts": "Prečice na tastaturi", "ui.language": "Jezik", + "ui.lasso_select": "Laso (povucite petlju slobodnom rukom: uzima sve što je u cijelosti unutra)", "ui.layout_compact": "Kompaktno", "ui.layout_floating": "Plutajuće", "ui.length": "Dužina", "ui.length_decimals": "Decimale dužine", "ui.light": "Svijetla", "ui.line": "Linija", + "ui.line_arc_hint": "Tangentni luk: kliknite kraj luka. Ponovo se zadržite na posljednjoj tački za linije; desni klik ili Esc za završetak", "ui.link_copies": "Poveži identične kopije", "ui.link_copies_keep": "Zadrži", "ui.link_copies_link": "Poveži", @@ -4347,6 +4888,7 @@ "ui.part_size_shared": "Ponovo gradi dio, zamjenjujući sve dodane operacije. Svi primjerci ove komponente se ažuriraju.", "ui.paste": "Zalijepi", "ui.path": "Putanja", + "ui.pattern_object_type_tip": "Tijela: puni oblici, biraju se u prikazu ili u stablu modela; svako se kopira u cijelosti.\nOperacije: koraci vremenske trake, poput ekstruzije ili rupe, biraju se na vremenskoj traci ili na licu koje su napravili; korak se ponavlja.\nSkica nije ni jedno ni drugo: ponovite njene krive pomoću alata Niz ili Preslikaj u samoj skici ili je prvo ekstrudirajte.", "ui.pattern_on_path": "Niz duž putanje", "ui.perforate_margin_default": "iz prečnika", "ui.perforate_pitch": "Korak", @@ -4373,12 +4915,17 @@ "ui.plugins_skipped": "Foldere nije bilo moguće pročitati: {count}.", "ui.plugins_version": "{version}", "ui.point": "Tačka", + "ui.point_cloud_add_filter": "Dodaj filter…", "ui.point_cloud_auto_range": "Automatski opseg", "ui.point_cloud_color_by": "Boja prema", "ui.point_cloud_file_colors": "Boje iz datoteke", + "ui.point_cloud_filter_by": "Filtriraj prema", "ui.point_cloud_height_high": "Najviše", "ui.point_cloud_height_low": "Najniže", + "ui.point_cloud_legend_filter": "Prikazano i skriveno u legendi iznad", "ui.point_cloud_no_file_colors": "Datoteka nema boje", + "ui.point_cloud_pause": "Pauziraj", + "ui.point_cloud_play": "Reprodukuj", "ui.point_cloud_single_color": "Jedna boja", "ui.point_cloud_size": "Veličina tačke", "ui.point_cloud_units": "Jedinice datoteke", @@ -4387,6 +4934,11 @@ "ui.polygon": "Poligon", "ui.preferences": "Postavke", "ui.press_a_key": "pritisnite tipku…", + "ui.print_face_body_not_sent": "Tijelo te površine se ne šalje: prvo ga dodajte u Tijela", + "ui.print_face_cleared": "{body}: površina za štampu uklonjena", + "ui.print_face_input": "Površina za štampu", + "ui.print_face_pick": "Odaberite ravnu površinu punog tijela da postane površina za štampu", + "ui.print_face_set": "{body}: površina za štampu postavljena; Pošalji u slajser polaže tijelo na nju", "ui.profile": "Profil", "ui.profile_plane": "Ravan profila", "ui.profiles": "Profili", @@ -4402,6 +4954,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Mjerenje…", + "ui.properties.measuring_bodies": "Mjerenje… {done} od {total} tijela", "ui.properties.measuring_failed": "Mjerenje je zaustavljeno prije završetka.", "ui.properties.principal_axis": "Glavna osa {number}", "ui.properties.principal_moments": "Glavni momenti", @@ -4450,6 +5003,7 @@ "ui.revolve": "Rotiraj", "ui.ribbon_exit": "Izađi", "ui.ribbon_labels": "Prikaži tekst ispod ikona na traci", + "ui.ribbon_menus_skip_pinned": "Izostavi prikačene komande iz padajućih menija", "ui.ribbon_pin_footer": "Prikačene komande prikazuju se na traci. Zadržite pokazivač iznad reda da ga prikačite ili otkačite.", "ui.ribbon_workspace": "Radni prostor", "ui.right": "Desno", @@ -4468,6 +5022,7 @@ "ui.selectOther": "Izaberi drugo…", "ui.selectTangentChain": "Izaberi tangentni lanac", "ui.select_all": "Izaberi sve", + "ui.select_components_by_face": "Izaberi komponente (lice bira svoju komponentu)", "ui.selection": "Izbor", "ui.selection_modifiers": "Modifikatori izbora", "ui.selection_shift_add_only": "Shift+klik dodaje bez uklanjanja", @@ -4493,6 +5048,7 @@ "ui.showDimension": "Prikaži kotu", "ui.showOrigin": "Prikaži ishodište", "ui.showPlanes": "Prikaži ravni", + "ui.show_component_history": "Prikaži njenu vremensku traku", "ui.show_constraints": "Ograničenja", "ui.show_construction_geometries": "Pomoćna geometrija", "ui.show_dimensions": "Kote", @@ -4509,6 +5065,11 @@ "ui.sketch_intersect_selection_filter": "Filter izbora", "ui.sketch_modifiers": "Modifikatori skice", "ui.sketch_project_geometry": "Geometrija", + "ui.sketch_report.all_constrained": "Sve je potpuno ograničeno.", + "ui.sketch_report.dof": "Stepeni slobode", + "ui.sketch_report.loose": "Nije potpuno ograničeno", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Izvještaj o skici", "ui.sketch_scale": "Skaliranje skice", "ui.sketches": "Skice", "ui.slice": "Presijeci", @@ -4604,19 +5165,31 @@ "ui.view_angles": "Uglovi prikaza", "ui.view_angles_convention": "Stepeni oko ose prema gore. Skretanje 0° je pogled sprijeda, 90° slijeva, −90° zdesna, 180° straga; nagib 90° je pogled odozgo; pozitivno valjanje okreće model u smjeru kazaljke na satu.", "ui.view_angles_help": "Prikazuje nagib, skretanje i valjanje prikaza u stepenima i njegovu projekciju ispod alata za orijentaciju. Kliknite očitanje da upišete tačne uglove.", + "ui.view_angles_lock": "Zaključaj {axis}", "ui.view_angles_ortho": "Ortogr.", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Nagib", "ui.view_angles_readout": "Nagib {pitch} · Skretanje {yaw} · Valjanje {roll}", "ui.view_angles_roll": "Valjanje", + "ui.view_angles_unlock": "Otključaj {axis}", "ui.view_angles_yaw": "Skretanje", + "ui.view_angles_zero": "Postavi {axis} na 0°", "ui.view_centre": "Centar prikaza", "ui.viewport_status_clear": "Isključi: {name}", "ui.viewport_status_clear_hint": "Isključi: {name} · Esc", + "ui.viewport_status_edges": "Ivice: {count}", + "ui.viewport_status_from": "iz smjera {direction}", "ui.viewport_status_key": "Prikaži legendu: {name}", "ui.viewport_status_minimum_radius": "Minimalni poluprečnik", "ui.viewport_status_pairs": "Parovi: {count}", + "ui.viewport_status_section_hatch": "{setting} · šrafura", + "ui.viewport_status_section_plane": "Trenutna ravan", + "ui.viewport_status_section_tilted": "nagnuto · {offset}", "ui.viewport_status_stripes": "Pruge: {count}", + "ui.viewport_status_summary_clear": "Isključi sve", + "ui.viewport_status_summary_heading": "U ovom prikazu", + "ui.viewport_status_summary_label": "{name} i još stavki: {count}", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Prati temu", "ui.visual_shaded_hidden_edges": "Osjenčeno sa skrivenim ivicama", "ui.visual_shaded_with_edges": "Osjenčeno s ivicama", @@ -4653,7 +5226,9 @@ "update.button": "Ažuriraj", "update.button_version": "Ažuriraj na {version}", "update.check_automatically": "Automatski provjeravaj ažuriranja", + "update.check_for_updates": "Provjeri ažuriranja", "update.check_now": "Provjeri sada", + "update.check_unavailable": "Provjera ažuriranja nije dostupna za ovu instalaciju.", "update.checking": "Provjera…", "update.copy": "Kopiraj", "update.dmg_opened": "Slika diska je otvorena i provjerena: prevucite SolidCraft u Applications, zamijenite staru kopiju, a zatim ponovo pokrenite SolidCraft.", @@ -4700,6 +5275,7 @@ "web.open_link": "Otvoriti povezani dizajn?", "web.open_link_confirm": "Postoje nesačuvane promjene. Otvoriti povezani dizajn u novoj kartici?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ izaberi · Enter / Tab dovrši · Esc odbaci", + "↑ ↓ choose · Enter applies this value": "↑ ↓ izbor · Enter primjenjuje ovu vrijednost", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ izaberi · Enter primjenjuje ono što ste upisali · Esc odbaci", "⌘Enter continues on GitHub.": "⌘Enter nastavlja na GitHubu." } diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 8efed5283..fe43f6af8 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "PŘECHODOVÁ PLOCHA", "BOUNDARY SURFACE": "PLOCHA Z HRANIC", "BROWSER": "PROHLÍŽEČ", + "Back to the original order": "Zpět na původní pořadí", "Ball": "Kulový", "Bar": "Tyč", "Base Center": "Střed základny", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Zde se zobrazí návrhy, které otevřete nebo uložíte.", "Determined by To Object. Choose Angle to edit the angular extent.": "Určeno volbou K objektu. Pro úpravu úhlového rozsahu zvolte Úhel.", "Diameter": "Průměr", + "Did this assembly open the wrong way up?": "Otevřela se tato sestava špatně natočená?", + "Did this part open the wrong way up?": "Otevřel se tento díl špatně natočený?", "Dimension new shapes": "Kótovat nové tvary", "Direction": "Směr", "Discard": "Zahodit", @@ -474,6 +477,7 @@ "Rectangular": "Obdélníkový", "Rectangular Tube": "Obdélníková trubka", "Reference face": "Referenční plocha", + "Reference plane": "Referenční rovina", "Relief Depth": "Hloubka odlehčení", "Relief Width": "Šířka odlehčení", "Remove Tools": "Odstranit nástroje", @@ -553,6 +557,7 @@ "Section": "Řez", "Section (optional)": "Průřez (volitelné)", "Section position": "Poloha průřezu", + "Sections": "Průřezy", "Sections (one sketch each)": "Průřezy (každý jeden náčrt)", "Select Other": "Vybrat jiné", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Vybrat jiné: podržte levé tlačítko na modelu (nebo pravé tlačítko › Vybrat jiné…) a zobrazí se vše pod kurzorem; dalším kliknutím na stejné místo vyberete další prvek. Dvojklikem prostředním tlačítkem přejdete na výchozí pohled (Předvolby › Navigace).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Přichytávat ke středům ploch a hran", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft nemůže odesílat hlášení přímo. Odešlete je na GitHubu; v aplikaci není potřeba žádný token.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft se zavřel dříve, než se tyto návrhy uložily. Lze otevřít jejich poslední automatické uložení.", + "Sort A to Z": "Seřadit od A do Z", + "Sort Z to A": "Seřadit od Z do A", "Spacing 2 must be a non-zero number": "Rozteč 2 musí být nenulové číslo", "Spacing must be a non-zero number": "Rozteč musí být nenulové číslo", "Specialise": "Specializovat", @@ -601,6 +608,7 @@ "Square": "Čtverec", "Stand it up": "Postavit", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Postavit: otočení o čtvrt otáčky kolem osy X jako jeden prvek Posunutí, který lze vrátit.", + "Stand this assembly up?": "Postavit tuto sestavu?", "Stand this part up?": "Postavit tento díl?", "Start angle": "Počáteční úhel", "Start bulge": "Vypouklost začátku", @@ -772,6 +780,8 @@ "at the face": "u plochy", "bom.group_children": "Poddíly v řádku svého dílu", "browser.body_name": "Těleso{number}", + "browser.calibrate_click_a": "Klikněte do obrázku na bod A, nebo zadejte jeho souřadnice.", + "browser.calibrate_click_b": "Klikněte do obrázku na bod B, nebo zadejte jeho souřadnice.", "browser.calibrate_title": "Kalibrovat: {name}", "browser.capture_many": "Byly přesunuty komponenty ({count}), ale jejich polohy nejsou zachyceny.", "browser.capture_note": "Zachycení polohy ponechá novou polohu; vrácení obnoví původní.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (uchycení ztraceno)", "browser.sketch_editing": "{name} (upravuje se)", "browser.sketch_name": "Náčrt{number}", + "browser.sketches_to_parts_already_in_part": "už jsou ve svém dílu", + "browser.sketches_to_parts_design_body": "leží na tělese samotného návrhu", + "browser.sketches_to_parts_moved": "Přesunuto náčrtů do dílu, na kterém leží: {moved}", + "browser.sketches_to_parts_no_exact_attachment": "leží na ploše bez přesného připojení", + "browser.sketches_to_parts_not_on_face": "neleží na ploše dílu", + "browser.sketches_to_parts_part_missing": "jejich díl už neexistuje", + "browser.sketches_to_parts_result": "Přesunuto náčrtů do dílu, na kterém leží: {moved}; na místě zůstalo: {stayed} — {why}", "browser.units": "Jednotky: {units}", "cam.flat": "Ploché čelo", "cam.follower": "Zdvihátko", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Převzít vzhled", "cmd.appearance_replace": "Nahradit vzhled", "cmd.assembly_bom": "Kusovník", + "cmd.assembly_mass_properties": "Hmotnostní vlastnosti", + "cmd.body.print_face": "Tisková plocha", "cmd.body_rename": "Přejmenovat těleso", "cmd.browser_collapse_all": "Sbalit vše", "cmd.browser_expand_all": "Rozbalit vše", @@ -842,6 +861,7 @@ "cmd.component_extract": "Extrahovat do souboru", "cmd.component_finish_edit": "Dokončit úpravu", "cmd.component_from_bodies": "Vytvořit komponenty z těles", + "cmd.component_hide_history": "Skrýt historii komponenty", "cmd.component_insert_design": "Vložit návrh", "cmd.component_links": "Seznam odkazů", "cmd.component_list": "Seznam komponent", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Přesunout tělesa do komponenty", "cmd.component_move_features": "Přesunout prvky do komponenty", "cmd.component_move_sketches": "Přesunout náčrty do komponenty", + "cmd.component_move_sketches_to_parts": "Přesunout náčrty do jejich dílů", "cmd.component_paste_from_design": "Vložit z jiného návrhu", "cmd.component_paste_new": "Vložit jako nové", "cmd.component_properties": "Fyzikální vlastnosti komponenty", @@ -857,6 +878,7 @@ "cmd.component_rename": "Přejmenovat komponentu", "cmd.component_replace_with_link": "Nahradit odkazem", "cmd.component_revert_position": "Vrátit polohu", + "cmd.component_show_history": "Zobrazit historii komponenty", "cmd.component_unlock": "Odemknout obsah", "cmd.component_update_links": "Aktualizovat odkazy", "cmd.config_activate": "Aktivovat konfiguraci", @@ -867,6 +889,7 @@ "cmd.config_rule": "Pravidlo konfigurace", "cmd.config_rules": "Pravidla konfigurace", "cmd.config_table": "Zobrazit tabulku konfigurací", + "cmd.construct.plane.axis_point": "Rovina osou a bodem", "cmd.construct_axis_edge": "Osa hranou", "cmd.construct_axis_normal_to_face": "Osa kolmá k ploše", "cmd.construct_axis_through_cylinder": "Osa válce/kužele/anuloidu", @@ -915,6 +938,11 @@ "cmd.explode_show": "Zobrazit rozložený pohled", "cmd.expr_evaluate": "Vyhodnotit výraz", "cmd.face_delete": "Smazat plochu", + "cmd.file.export_3mf": "Exportovat 3MF", + "cmd.file.export_obj": "Exportovat OBJ", + "cmd.file.export_step": "Exportovat STEP", + "cmd.file.export_stl": "Exportovat STL", + "cmd.file.export_urdf": "Exportovat URDF", "cmd.file_export": "Exportovat", "cmd.file_insert_mesh": "Vložit síť", "cmd.file_insert_step": "Vložit STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Zapnout barvy komponent", "cmd.inspect_colored_components_disable": "Vypnout barvy komponent", "cmd.inspect_compare": "Porovnat tělesa", + "cmd.inspect_compare_picture": "Porovnat obrázek", "cmd.inspect_continuity": "Analýza spojitosti", "cmd.inspect_curvature_comb": "Analýza hřebenu křivosti", "cmd.inspect_curvature_map": "Mapa křivosti", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Upravit mračno bodů", "cmd.pointcloud_insert": "Vložit mračno bodů", "cmd.pointcloud_list": "Mračna bodů", + "cmd.render.compare.divider": "Posunout dělicí čáru porovnání renderů", + "cmd.render.result.discard": "Zahodit výsledek renderu", + "cmd.render.result.select": "Vybrat výsledek renderu", "cmd.render_aging_describe": "Vrstvené stárnutí povrchu", "cmd.render_backends": "Renderovací jádra", "cmd.render_batch": "Renderovat všechny záběry", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Splajn řídicími body (stupeň 5)", "cmd.sketch_spline_fit_point": "Splajn procházející body", "cmd.sketch_spline_insert_point": "Přidat bod splajnu", + "cmd.sketch_spline_remove_point": "Odebrat bod splajnu", "cmd.sketch_spline_reverse": "Obrátit směr splajnu", "cmd.sketch_spun_profile": "Rotační obrys", "cmd.sketch_toggle_diameter": "Přepnout poloměr / průměr", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Přesunout značku časové osy", "cmd.timeline_stop": "Zastavit historii", "cmd.timeline_suppress": "Potlačit prvek", + "cmd.ui.assistant": "Zobrazit nebo skrýt Asistenta", "cmd.view.render_browser": "Prohlížeč renderu", "cmd.view.render_dock": "Přesunout panel renderu", "cmd.view.render_focus": "Soustředěný pohled na render", + "cmd.view.status_details": "Podrobnosti stavu pohledu", "cmd.view.status_items": "Stavové položky pohledu", "cmd.view_ambient_occlusion": "Okolní zastínění", "cmd.view_angle_readout": "Úhly pohledu", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Navigační nástroj", "cmd.view_top": "Pohled shora", "cmd.view_visual_style": "Vizuální styl", + "color.blue": "Modrá", "color.copy": "Kliknutím zkopírujete hodnoty barvy", "color.edit": "Kliknutím upravíte barvu", "color.gamma": "Hodnoty barvy v gama prostoru 0–255", + "color.green": "Zelená", "color.hex": "Hex", "color.hex_help": "Zadejte #rrggbb nebo #rrggbbaa; šest číslic zachová neprůhlednost", "color.hex_hint": "#rrggbb", "color.hue": "Odstín", "color.linear": "Hodnoty barvy v lineárním prostoru 0–1", + "color.recent": "Nedávné barvy", + "color.recent_help": "Barvy, které vyberete v libovolném poli barvy, se zobrazí zde", + "color.red": "Červená", + "color.saturation": "Sytost (v procentech)", "color.saturation_value": "Sytost a jas", "color.selected": "Vybraná barva", + "color.step_down": "Snížit o krok", + "color.step_up": "Zvýšit o krok", + "color.value": "Hodnota, tedy jas (v procentech)", "config.column_filter_empty": "Žádné odpovídající sloupce", + "config.rule_parameter_columns": "Uvedeny jsou jen parametry, které mají v tabulce sloupec. Sloupec přidáte pomocí Přidat sloupec (+), abyste parametr mohli použít zde.", + "config.rule_suppression_columns": "Uvedeny jsou jen prvky, které mají v tabulce sloupec Potlačit. Sloupec přidáte pomocí Přidat sloupec (+), abyste mohli prvek řídit zde.", "contact.components_count": "Počet komponent: {count}", "contact.enabled_label": "povoleno", "coupling.gear_1": "Kolo 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Dvojklikem na jiný řídicí kótu vložíte jeho název", "dialog.dimension_name": "Kóta: {name}", "dialog.edit_title": "UPRAVIT {title}", + "dialog.no_shown_body": "Není zobrazeno žádné těleso ke změně: zobrazte nějaké nebo zvolte Nové těleso", + "dialog.pattern_sketch_not_object": "Vyberte tělesa nebo prvky: náčrt není ani jedno. Opakujte jeho křivky vlastním nástrojem Pole nebo Zrcadlit v náčrtu, nebo jej nejprve vysuňte.", "dialog.select": "↖ Vybrat", "dialog.selected_count": "↖ Vybráno: {count}", + "dialog.selection_constraint": "Vazba {id}", + "dialog.selection_external_curve": "{sketch} · křivka {id}", "dialog.selection_guidance": "Vstup změníte jeho výběrem. Kliknutím na vybraný objekt jej odeberete; Ctrl/Cmd+klik výběr také přepíná. Zkontrolujte náhled a stiskněte OK.", + "dialog.selection_midpoint": "Střed · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} z {total}: Vyberte {input}", "dialog.step": "Krok", "document.changed_on_disk": "Soubor {name} byl změněn na disku", @@ -1380,26 +1432,244 @@ "from the rule": "z pravidla", "help.apache": "Licence Apache 2.0", "help.appearance.assign": "Přiřadí vybraným tělesům, plochám nebo komponentám barvu nebo vzhled materiálu, aniž by se změnila jejich hmotnost. Hodí se k rozlišení dílů nebo k náhledu povrchové úpravy.", + "help.assembly.bom": "Vypíše díly návrhu nebo komponenty s jejich počty podle čísla dílu a může seznam uložit jako CSV nebo JSON. Použijte ho jako soupis dílů pro objednávání a montáž.", "help.attributions": "Uvedení autorství (ATTRIBUTION.md)", "help.build": "Verze {version} · commit {commit} · sestaveno {date}", + "help.canvas.decal": "Umístí obrázek na rovinnou plochu modelu jako nálepku. Hodí se k zobrazení štítku, loga nebo potištěného vzoru na dílu.", + "help.canvas.edit": "Změní plátno: jeho polohu, velikost, úhel, neprůhlednost, zrcadlení, viditelnost nebo název. Hodí se k zarovnání referenčního obrázku s náčrtem, který podle něj obkreslujete.", + "help.canvas.insert": "Umístí obrázek PNG nebo JPEG na rovinu nebo plochu jako průhlednou referenci. Hodí se k obkreslení fotografie nebo výkresu v náčrtu, přičemž obrázek má zadanou známou velikost.", + "help.component.break_link": "Odpojí propojenou komponentu od souboru návrhu a ponechá její tělesa beze změny. Použijte to, když už má díl přestat sledovat změny původního souboru.", + "help.component.capture_position": "Zachová polohy dílů, které jste přesunuli ručně, takže se stanou jejich novými polohami. Použijte to po přetažení dílů na místa, kde je žádný kloub nedrží.", + "help.component.create": "Přidá do návrhu novou prázdnou komponentu, a to do aktivní komponenty, pokud nezvolíte jinou nadřazenou. Použijte to, aby nový díl sestavy měl vlastní místo pro tělesa a náčrty.", "help.component.finish_edit": "Uloží díl upravovaný na místě, vrátí se do jeho sestavy a aktualizuje sestavu podle něj. Použijte ho, až jsou vaše změny propojeného dílu hotové.", + "help.component.from_bodies": "Změní každé vybrané těleso na samostatnou komponentu pojmenovanou podle tělesa. Použijte to, když se návrh vytvořený z volných těles má stát sestavou, jejíž díly lze spojovat a přesouvat.", + "help.component.insert_design": "Vloží jiný uložený návrh jako komponentu propojenou s jeho souborem, s tělesy umístěnými tak, jak jsou v něm. Použijte to k opětovnému použití dílu v sestavě a k převzetí pozdějších změn příkazem Aktualizovat odkazy.", + "help.component.properties": "Zobrazí objem, hmotnost, těžiště a momenty setrvačnosti komponenty podle materiálů jejích těles. Použijte to ke kontrole hmotnosti a vyvážení sestavy.", + "help.component.revert_position": "Vrátí ručně přesunuté díly na původní místo a zahodí přesuny, které nebyly zachyceny. Použijte to k vrácení zkušebních přesunů v sestavě.", + "help.component.update_links": "Znovu načte propojené soubory návrhů a nahradí tělesa, která se změnila. Použijte to po úpravě dílu, který tato sestava používá.", + "help.config.configure": "Přidá parametry, prvky, materiály nebo vzhledy jako sloupce tabulky konfigurací. Použijte to k vytvoření variant jednoho návrhu, například velikostí dílu.", + "help.config.preview": "Ověří, že se řádek tabulky konfigurací přestaví, aniž by změnil návrh nebo jeho historii. Použijte to před přepnutím na variantu, u které si nejste jisti.", + "help.config.rules": "Zobrazí pravidla tabulky konfigurací, její řádky a to, který řádek je aktivní. Použijte to, abyste viděli, jak jsou varianty návrhu nastaveny.", + "help.config.table": "Zobrazí tabulku konfigurací: jeden řádek na variantu, jeden sloupec na parametr nebo prvek a informaci, zda návrh stále odpovídá aktivnímu řádku. Použijte to ke kontrole variant návrhu.", "help.connect_note": "Restartujte každého asistenta, aby se načetl server SolidCraft. Každý soubor byl před změnou zálohován jako .bak.", "help.connect_title": "Připojit AI asistenty", + "help.construct.axis.edge": "Vytvoří konstrukční osu podél přímé hrany nebo úsečky náčrtu. Použijte ji jako osu pro rotaci, kruhové pole nebo kloub.", + "help.construct.axis.normal_to_face": "Vytvoří konstrukční osu procházející bodem a kolmou k ploše. Použijte ji jako osu, která vychází přímo z povrchu.", + "help.construct.axis.through_cylinder": "Vytvoří konstrukční osu středem válcové, kuželové nebo anuloidní plochy, nebo kruhové hrany. Použijte to k otáčení prvků nebo jejich rozmístění v poli kolem kulatého dílu.", + "help.construct.axis.two_planes": "Vytvoří konstrukční osu tam, kde se protínají dvě roviny nebo rovinné plochy. Použijte to, když je potřebná osa průsečnicí dvou ploch.", + "help.construct.axis.two_points": "Vytvoří konstrukční osu procházející dvěma body, vrcholy nebo body náčrtu. Použijte ji pro osu vedoucí mezi dvěma známými polohami.", + "help.construct.plane.along_path": "Vytvoří konstrukční rovinu kolmou k hraně nebo křivce v zadané poloze podél ní. Použijte to k náčrtu profilu pro tažení nebo příčného řezu podél cesty.", + "help.construct.plane.at_angle": "Vytvoří konstrukční rovinu natočenou o úhel od roviny nebo plochy kolem osy nebo hrany. Použijte ji pro šikmé náčrty, například u úhlového držáku.", + "help.construct.plane.axis_point": "Vytvoří konstrukční rovinu obsahující osu a bod mimo tuto osu. Vyberte osu počátku nebo konstrukční osu, přímou hranu nebo úsečku náčrtu a pak vrchol, bod náčrtu nebo konstrukční bod. Bod ležící na ose nemůže určit jednoznačnou rovinu.", + "help.construct.plane.midplane": "Vytvoří konstrukční rovinu uprostřed mezi dvěma rovinami nebo rovinnými plochami, nebo rovinu půlící jejich úhel, když se protínají pod úhlem. Použijte ji jako rovinu souměrnosti pro zrcadlení.", + "help.construct.plane.offset": "Vytvoří konstrukční rovinu rovnoběžnou s rovinou nebo rovinnou plochou ve zvolené vzdálenosti nebo procházející bodem. Použijte ji k náčrtu v dané výšce nad plochou.", + "help.construct.plane.perpendicular": "Vytvoří konstrukční rovinu, která obsahuje přímku nebo hranu a je kolmá k rovině nebo ploše. Použijte ji k náčrtu kolmo na model podél hrany.", + "help.construct.plane.tangent": "Vytvoří konstrukční rovinu, která se v bodě dotýká válce, kužele, koule nebo anuloidu. Použijte ji k náčrtu na boku kulatého dílu.", + "help.construct.plane.three_points": "Vytvoří konstrukční rovinu procházející třemi body. Použijte ji pro rovinu danou polohami na modelu, například třemi rohy.", + "help.construct.plane.two_edges": "Vytvoří konstrukční rovinu procházející dvěma přímými hranami nebo úsečkami, které leží v jedné rovině. Použijte ji pro rovinu napříč dílem, například vedenou dvěma protilehlými hranami.", + "help.construct.point.along_path": "Vytvoří konstrukční bod v zadané poloze podél hrany nebo křivky. Použijte ho jako referenci někde uprostřed cesty.", + "help.construct.point.center": "Vytvoří konstrukční bod ve středu kruhové hrany, kružnice nebo oblouku náčrtu, koule nebo anuloidu. Použijte ho jako referenci pro otvory, osy a klouby.", + "help.construct.point.edge_plane": "Vytvoří konstrukční bod tam, kde hrana nebo úsečka prochází rovinou nebo rovinnou plochou. Použijte ho k označení místa, kde cesta protíná rovinu.", + "help.construct.point.three_planes": "Vytvoří konstrukční bod tam, kde se protínají tři roviny nebo rovinné plochy. Použijte ho jako referenci rohu i tam, kde model žádný vrchol nemá.", + "help.construct.point.two_edges": "Vytvoří konstrukční bod tam, kde se dvě hrany nebo úsečky protínají nebo si jsou nejblíže. Použijte ho jako referenci ve virtuálním rohu.", + "help.construct.point.vertex": "Vytvoří konstrukční bod ve vrcholu nebo v bodě náčrtu. Použijte ho jako referenci, která zůstane, i když se náčrt nebo těleso kolem něj skryje.", + "help.contact.check": "Vypíše dvojice dílů v sadách kontaktů, které se v aktuální poloze navzájem prostupují. Použijte to k nalezení kolizí dříve, než začnete pohánět klouby nebo spustíte studii pohybu.", + "help.contact.create": "Seskupí dva nebo více dílů do sady kontaktů, jejíž tělesa se při pohybu kloubů nesmějí prostupovat. Použijte to pro díly, které se mají při dotyku zastavit, například páku o její zarážku.", + "help.contact.disable_all": "Vypne kontakt, takže poháněné klouby a studie pohybu se už nezastavují tam, kde se díly dotýkají. Použijte to, aby se díly zase mohly pohybovat volně, nebo aby velká sestava zůstala svižná.", + "help.contact.edit": "Změní sadu kontaktů: díly v ní, její název nebo zda je potlačená; sadu lze také smazat. Použijte to k úpravě toho, které díly se nesmějí prostupovat.", + "help.contact.enable_all": "Vloží všechny díly sestavy do jedné sady kontaktů, takže se žádné dva díly nemohou při pohybu kloubů prostupovat. Použijte to pro rychlou kontrolu celého mechanismu.", + "help.contact.enable_sets": "Zapne kontakt pro vámi definované sady kontaktů, takže poháněné klouby a studie pohybu se zastaví tam, kde by se jejich díly prostoupily. Použijte to k obnovení svých sad po vypnutí kontaktu.", + "help.contact.list": "Vypíše sady kontaktů návrhu, díly v každé z nich a informaci, zda je kontakt zapnutý. Použijte to ke kontrole nastavení kontaktu před poháněním sestavy.", + "help.document.inspect": "Zobrazí přehled návrhu: jeho komponenty, tělesa, náčrty, prvky a parametry. Použijte to, abyste se zorientovali v návrhu, který jste nevytvořili sami.", + "help.document.units": "Změní jednotky, ve kterých návrh zobrazuje délky, například mm nebo palce. Geometrie si zachová velikost; řídí se jimi jen zobrazení a holá čísla.", + "help.edit.checkpoint": "Zapamatuje si návrh, aktivní náčrt a historii vrácení zpět tak, jak jsou nyní. Použijte to před zkoušením něčeho riskantního, od čeho se možná budete chtít vrátit.", + "help.edit.restore_checkpoint": "Vrátí se ke kontrolnímu bodu, včetně historie vrácení zpět. Použijte to k zahození všeho, co se od kontrolního bodu udělalo, jedním krokem.", + "help.explode.create": "Vytvoří rozložený pohled, který odsune díly od středu sestavy nebo o zadané posuny. Použijte to k ukázce, jak se sestava skládá, pro návody nebo prezentace.", "help.face.delete": "Odstraní vybrané plochy a nechá sousední plochy uzavřít mezeru, nebo mezeru ponechá otevřenou jako plochu. Hodí se k odstranění zaoblené hrany, otvoru nebo nálitku, které překážejí.", + "help.file.insert_mesh": "Přidá soubor 3MF, STL, OBJ, PLY nebo glTF do návrhu jako síťová tělesa v nové komponentě. Použijte to k umístění staženého nebo naskenovaného modelu vedle návrhu jako reference.", + "help.file.insert_step": "Přidá soubor STEP, IGES, FreeCAD nebo Rhino do návrhu jako plná tělesa v nové komponentě; díly sestavy se stanou vnořenými komponentami. Použijte to k převzetí modelů od dodavatelů nebo z jiných CAD programů.", + "help.file.save_mesh": "Uloží tělesa jako síť STL, 3MF nebo OBJ s vámi zvolenou hladkostí zakřivených ploch. Použijte to k přípravě dílů pro 3D tisk nebo pro programy, které čtou sítě.", + "help.file.send_to_slicer": "Uloží vybraná tělesa jako soubor 3MF a otevře jej ve zvoleném sliceru. Použijte to k přechodu od modelu k tisku jedním krokem.", "help.font_details": "Rozhraní používá vestavěná písma egui (Ubuntu Light a Hack pod licencemi Ubuntu Font Licence a MIT/Bitstream Vera; Noto Emoji a písmo ikon emoji pod licencemi OFL a MIT). Text náčrtu používá Liberation Sans (SIL OFL 1.1). Volitelný balíček písem craft-fonts od The Crafting Apps (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1) není součástí sestavení SolidCraft.", "help.fonts": "Písma", + "help.frame.member": "Umístí profil, například trubku nebo hliníkový profil, podél úseček náčrtu rámu, jeden prvek na každou úsečku. Použijte to k vytváření rámů, regálů a svařovaných konstrukcí.", + "help.inspect.accessibility": "Obarví plochy, ke kterým se nástroj dostane z jednoho směru, a ty, ke kterým ne. Použijte to ke kontrole dílu pro obrábění nebo lisování z této strany.", + "help.inspect.center_of_mass": "Zobrazí těžiště těles, každého zvlášť i všech dohromady, při rovnoměrné hustotě. Použijte to ke kontrole vyvážení a místa, kde se díl převrátí.", + "help.inspect.colored_components": "Dá každé komponentě vlastní dočasnou barvu, aniž by změnil vzhledy. Použijte to k rychlému rozlišení dílů sestavy.", + "help.inspect.compare": "Porovná dvě tělesa a ukáže, kde jedno má materiál, který druhé nemá, s objemem a odchylkou. Použijte to ke kontrole změněného nebo importovaného dílu proti originálu.", + "help.inspect.continuity": "Zkontroluje, jak hladce plochy navazují podél hran: mezery, zlomy nebo skoky křivosti, a spoje obarví. Použijte to k nalezení míst, kde se povrchy nespojují čistě.", + "help.inspect.curvature_comb": "Nakreslí hřebeny podél křivek, hran nebo ploch, jejichž zuby ukazují, jak silně se ohýbají. Použijte to k odhalení plochých míst, zlomů a nerovnoměrné křivosti.", + "help.inspect.curvature_map": "Obarví plochy podle toho, jak silně jsou zakřivené, červeně tam, kde je poloměr malý. Použijte to k nalezení těsných míst a k posouzení hladkosti povrchu.", + "help.inspect.draft": "Obarví plochy podle jejich úhlu úkosu vůči směru vyjímání a označí ty s příliš malým úkosem. Použijte to ke kontrole dílu před lisováním nebo odléváním.", + "help.inspect.environment_map": "Zobrazí model s odrazivým, zrcadlovým povrchem. Použijte to k posouzení průběhu ploch podle toho, jak po nich probíhají odrazy.", + "help.inspect.interference": "Najde tělesa, která se překrývají, a ukáže každé překrytí s jeho objemem. Použijte to ke kontrole sestavy, zda v ní nejsou kolidující díly.", + "help.inspect.isocurve": "Nakreslí izoparametrické křivky ploch, tedy mřížku, na které je povrch postaven. Použijte to k zobrazení toho, jak povrch plyne a kde se zhušťuje.", + "help.inspect.measure": "Změří délky, vzdálenosti, úhly, obsahy a poloměry mezi vybranými objekty, nebo objem a hmotnost těles. Použijte to ke kontrole rozměrů a vůlí.", + "help.inspect.minimum_radius": "Najde nejmenší poloměr křivosti křivek, hran nebo ploch a místo, kde se nachází. Použijte to ke kontrole, zda tvar dokáže sledovat nástroj nebo tryska.", + "help.inspect.section": "Rozřízne pohled podél roviny a vyšrafuje řezné plochy, aniž by změnil model. Použijte to k nahlédnutí dovnitř dílů a sestav.", + "help.inspect.zebra": "Zobrazí na plochách modelu odražené černobílé pruhy. Použijte to k posouzení hladkosti: pruhy, které se na hraně přeruší nebo zlomí, ukazují špatný přechod.", + "help.joint.as_built": "Spojí dva díly tam, kde už jsou, aniž by některý přesunul, a nastaví, jak se mohou dál pohybovat. Použijte to pro díly, které jste už umístili do konečné polohy.", + "help.joint.cam": "Spojí otáčející se vačku se zdvihátkem, které se posouvá nebo kývá podle toho, jak pod ním prochází obrys vačky. Použijte to pro vačky, excentry a rozvody ventilů.", + "help.joint.create": "Spojí dva díly ve zvolených počátcích kloubu a přesune druhý díl na místo; typ kloubu určuje, jak se mohou dál pohybovat. Použijte to k sestavení sestavy, jejíž díly se pohybují jako skutečný mechanismus.", + "help.joint.drive": "Nastaví úhel nebo vzdálenost kloubu a pohne s ním díly v rámci jeho limitů; propojené klouby a uzavřené smyčky ho následují. Použijte to ke kontrole, zda se mechanismus pohybuje, jak má.", + "help.joint.gear": "Spojí dva otáčející se klouby převodovým poměrem, takže pohon jednoho otáčí druhým. Použijte to pro čelní a vnitřní ozubená kola; poměr se vezme z poloměrů roztečných kružnic nebo z počtu zubů.", + "help.joint.limits": "Nastaví, jak daleko se kloub smí otočit nebo posunout, jako minimum a maximum, nebo tyto limity zruší. Použijte to, aby závěs, posuvný člen nebo páka zůstaly ve svém skutečném rozsahu pohybu.", + "help.joint.motion_link": "Spojí dva klouby poměrem a posunutím, takže pohon jednoho pohne druhým. Použijte to pro pevný vztah mezi klouby, který nepokrývají Ozubený převod, Hřeben a pastorek ani Šroubový pohyb.", + "help.joint.origin": "Umístí na díl pojmenovaný počátek kloubu: do středu plochy nebo kulatého konce, do poloviny hrany, do rohu nebo do bodu. Použijte to k přípravě míst, kde se klouby upevní; počátek zvolený na ploše ji sleduje, když se díl změní co do velikosti.", + "help.joint.rack_pinion": "Spojí otáčející se pastorek s posuvným hřebenem tak, že se hřeben posune o délku roztečné kružnice, po které se pastorek odvalí. Použijte to pro hřebenové pohony, řízení a lineární stolky.", + "help.joint.reach": "Přesune bod na dílu k cíli změnou kloubů na jeho řetězci v rámci jejich limitů. Použijte to k nastavení polohy mechanismu podle toho, kde má být jeho konec, například hrot ramene robota.", + "help.joint.rigid_group": "Pevně spojí vybrané díly tak, jak jsou, takže se pohybují jako jeden. Použijte to pro díly, které k sobě patří a nemají mezi sebou žádný pohyb.", + "help.joint.screw": "Spojí otáčení a posuv stoupáním, takže každé otočení posune díl o tuto vzdálenost. Použijte to pro pohybové šrouby, šrouby a závitová vřetena.", + "help.library.apply": "Použije materiál nebo vzhled ze souboru místní knihovny na tělesa, plochy nebo komponenty. Použijte to k opětovnému použití materiálů uložených z jiného návrhu.", + "help.library.export": "Uloží materiály a vzhledy návrhu do souboru knihovny. Použijte to ke sdílení nebo k jejich opětovnému použití v jiných návrzích.", + "help.library.inspect": "Zkontroluje soubor knihovny a vypíše jeho materiály a vzhledy, aniž by změnil návrh. Použijte to, abyste před použitím viděli, co knihovna obsahuje.", "help.licences": "Licence", "help.material.assign": "Určí, z čeho jsou vybraná tělesa vyrobena, například z oceli, hliníku nebo ABS. Hodí se k tomu, aby hmotnost a tíha odpovídaly skutečnému dílu.", + "help.material.properties.validate": "Zkontroluje kartu dat materiálu na shodu čísel a chybějící hodnoty. Použijte to dříve, než se na data spolehnete při výpočtu hmotnosti nebo tuhosti.", + "help.mesh.convert": "Přestaví síťové těleso, například STL, na upravitelné plné těleso s rovinnými a válcovými plochami. Použijte to k úpravě importovaných strojních dílů jako modelovaného tělesa.", "help.mit": "Licence MIT", + "help.motion.study": "Nastaví hodnoty kloubů v krocích na časové ose a přehraje je jako animaci. Použijte to ke sledování pohybu mechanismu v posloupnosti a ke kontrole vůlí po cestě.", + "help.motion.trace": "Sleduje dráhu, kterou opisuje bod na dílu při přehrávání studie pohybu nebo při poháněném kloubu, a po potvrzení ji uloží jako křivku 3D náčrtu. Použijte to k zobrazení dosahu mechanismu nebo k vytváření dalších prvků na jeho dráze.", "help.notice": "NOTICE", + "help.occurrence.ground": "Ukotví díl na místě, nebo ho znovu uvolní, aby klouby pohybovaly ostatními díly kolem něj. Použijte to pro rám nebo základnu, na které je zbytek sestavy postaven.", "help.occurrence.move": "Posouvá díl sestavy jen v těch stupních volnosti, které povolují jeho klouby. Vyberte plochu dílu a pak táhněte za dostupnou šipku nebo oblouk.", "help.parameters.change": "Otevře tabulku pojmenovaných hodnot a výrazů, které řídí rozměry návrhu. Hodí se ke změně rozměru na jednom místě, kterou převezmou všechny prvky, jež jej používají.", + "help.parameters.export": "Uloží parametry návrhu jako CSV nebo JSON. Použijte to k jejich úpravě v tabulkovém procesoru nebo k přenosu do jiného návrhu.", + "help.parameters.graph": "Ukáže, které parametry a prvky používají které jiné, a případné smyčky nebo chyby mezi nimi. Použijte to, abyste viděli, co změna parametru ovlivní.", + "help.parameters.import": "Načte parametry z CSV nebo JSON do návrhu, buď všechny, nebo žádný z nich. Použijte to k převzetí hodnot z tabulky nebo jiného návrhu.", + "help.parameters.move": "Přesune uživatelský parametr před jiný nebo za jiný v seznamu. Použijte to, aby související parametry zůstaly pohromadě.", + "help.parts.fastener": "Přidá normalizovaný šroub, svorník, matici, podložku, kolík nebo ložisko ve zvolené velikosti. Po umístění na otvor se do něj pomocí kloubu usadí, takže spojovací prvky nemusíte modelovat sami.", + "help.parts.insert": "Vloží normalizovaný díl ve zvolené řadě, velikosti a délce. Po umístění na okraj nebo stěnu otvoru se na otvor usadí pevným kloubem.", + "help.parts.library": "Otevře normalizované díly: šrouby, svorníky, matice, podložky, stavěcí šrouby, kolíky a ložiska v normalizovaných velikostech. Použijte to k přidání normalizovaného dílu místo jeho vlastního modelování.", + "help.parts.resize": "Změní velikost nebo délku vloženého normalizovaného dílu a přestaví jej; jeho klouby ho drží usazený. Použijte to, když se ukáže, že je šroub příliš dlouhý nebo že otvor potřebuje jinou velikost.", + "help.plastic.assign_rule": "Přiřadí tělesům pravidlo pro plasty, takže jejich plastové prvky přebírají jeho úkos a vůli jako výchozí hodnoty. Použijte to k nastavení lisovaného dílu jednou pro všechny jeho prvky.", + "help.plastic.boss": "Přidá na plochu nálitek pro šroub: sloupek s volitelným otvorem, úkosem, zaoblením u paty a podpůrnými žebry. Použijte to pro šroubové body v lisovaných nebo tištěných krytech.", + "help.plastic.lip": "Přidá osazení nebo odpovídající drážku podél okraje tělesa vytvořeného skořepinou. Použijte to, aby se dvě poloviny krytu navzájem zaměřily a těsně se zavřely.", + "help.plastic.manage_rules": "Vytvoří a upraví pravidla pro plasty: materiál, tloušťku stěny, poloměry, vůli a úkos. Použijte je k tomu, aby prvky lisovaného dílu byly jednotné.", + "help.plastic.rest": "Přidá na plochu opěrku: kulatou nebo obdélníkovou podložku, plnou nebo dutou, s úkosem. Použijte ji jako podporu nebo distanční sloupek v lisovaném krytu.", + "help.plastic.snap_fit": "Přidá na plochu zacvakávací hák se zadanou délkou, tloušťkou a západkou. Použijte to k sepnutí dílů bez šroubů.", "help.pointcloud.insert": "Vložte sken PLY, XYZ nebo PTS jako mračno bodů vedle modelu. Použijte ho jako referenci při tvorbě modelu z naměřených dat.", + "help.sheet.convert": "Změní desku nebo těleso se skořepinou stejné tloušťky na plechové těleso s ohyby na zvolených hranách. Použijte to, aby šel existující díl rozvinout.", + "help.sheet.export_bend_table": "Uloží tabulku ohybů plechového tělesa jako CSV nebo JSON: úhly, poloměry a polohy ohybů v rozvinu. Použijte to pro ohraňovací lis nebo dílnu.", + "help.sheet.export_dxf": "Uloží rozvin jako DXF s obrysy, čarami ohybů a volitelnými poznámkami k ohybům. Použijte to pro řezání laserem, plazmou nebo vodním paprskem.", + "help.sheet.flange": "Přidá přírubu: základní desku z náčrtu, stěnu podél otevřené kontury náčrtu nebo ohnutou stěnu na hranách plechu. Použijte to k vytváření plechových dílů.", + "help.sheet.flat_pattern": "Vytvoří rozvin plechového tělesa s jeho velikostí, výřezy a čárami ohybů. Použijte to ke kontrole polotovaru před řezáním.", + "help.sheet.fold": "Ohne plech podél úsečky náčrtu o zadaný úhel a poloměr. Použijte to k ohnutí plochého plechu poté, co do něj vyřežete prvky.", + "help.sheet.hem": "Přehne okraj plechu zpět na sebe. Použijte to pro bezpečné, tuhé okraje bez ostrých otřepů.", + "help.sheet.manage_rules": "Vytvoří a upraví pravidla pro plech: tloušťku, poloměr ohybu, K-faktor, odlehčení a mezery. Použijte je, aby odpovídala materiálu a nástrojům vaší dílny.", + "help.sheet.path_flange": "Přidá řetěz přírub podél hrany plechu podle otevřeného řetězce úseček náčrtu. Použijte to pro profily, například tvar U nebo Z, jedním krokem.", + "help.sheet.perforate": "Přidá pole otvorů přes celý plochý plech ve střídavém nebo čtvercovém rozložení. Použijte to pro větrací otvory, mřížky a odlehčené panely.", + "help.sheet.refold": "Znovu ohne rozvinuté plechové těleso zpět. Použijte to po přidání prvků do plochého plechu.", + "help.sheet.unfold": "Rozvine všechny ohyby plechového tělesa. Použijte to k přidání otvorů nebo výřezů, které musí překračovat ohyb, a pak plech znovu ohněte.", + "help.sketch.arc.center_point": "Nakreslí kruhový oblouk kolem středu, od počátečního bodu ke koncovému. Použijte to, když je střed oblouku známý, například poloměr kolem otvoru nebo čepu.", + "help.sketch.arc.tangent": "Nakreslí oblouk, který začíná na konci úsečky nebo oblouku a pokračuje tečně k němu. Použijte to k pokračování řetězce hladkým ohybem místo rohu.", + "help.sketch.arc.three_point": "Nakreslí oblouk od počátečního bodu ke koncovému přes třetí bod. Použijte to, když oblouk musí procházet zadanými body, a ne kolem známého středu.", + "help.sketch.arc3d": "Nakreslí přesný kruhový oblouk v prostoru třemi body, se zapnutým 3D náčrtem. Použijte to pro ohyby cest a vodicích drah, které opouštějí rovinu náčrtu.", + "help.sketch.auto_constrain": "Přidá vazby, které náčrt už skoro má, například vodorovnost, rovnoběžnost nebo totožnost, a pak jej okótuje, dokud není plně určen. Použijte to k zamknutí zhruba nakresleného náčrtu jedním krokem.", + "help.sketch.auto_constrain_from_datum": "Funguje jako Automatické vazby, ale polohy měří od zvoleného referenčního bodu místo počátku. Použijte to, když je díl rozvržen od jednoho referenčního bodu, například rohu nebo otvoru.", + "help.sketch.blend_curve": "Spojí konce dvou křivek hladkým splajnem, který je tečný k oběma, nebo na přání i spojitý v křivosti. Použijte to k překlenutí mezery mezi křivkami bez zlomu.", + "help.sketch.break": "Rozdělí křivku na části tam, kde ji kříží jiné křivky, nebo v bodech, které na ni umístíte. Použijte to, když část křivky potřebuje vlastní vazbu nebo se má smazat samostatně.", + "help.sketch.cancel": "Opustí náčrt a zahodí vše, co se změnilo od jeho vytvoření nebo otevření k úpravám. Zpět změny vrátí.", + "help.sketch.centerline": "Přepíná úsečky mezi běžnými úsečkami a osami, které profily vynechávají. Použijte osu jako osu rotace, zrcadlení nebo vazby symetrie.", + "help.sketch.chamfer.distance_angle": "Zkosí roh mezi dvěma úsečkami podle vzdálenosti podél první úsečky a úhlu. Použijte to, když výkres udává sražení jako délku a úhel, například 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Zkosí roh mezi dvěma úsečkami ve stejné vzdálenosti zpět podél obou. Použijte to pro obvyklé sražení 45° na obrysu.", + "help.sketch.chamfer.two_distance": "Zkosí roh mezi dvěma úsečkami podle samostatné vzdálenosti podél každé úsečky. Použijte to pro sražení jiná než 45°, zadaná dvěma délkami.", + "help.sketch.circle.center": "Nakreslí kružnici ze středu a průměru. Použijte to pro otvory, nálitky a jiné kulaté prvky se známým středem.", + "help.sketch.circle.three_point": "Nakreslí kružnici procházející třemi body. Použijte to, když kružnice musí procházet zadanými body, například existující geometrie.", + "help.sketch.circle.three_tangent": "Nakreslí kružnici, která se dotýká tří úseček, kružnic nebo oblouků. Použijte to k vložení kružnice do prostoru mezi tři křivky, například jako vepsanou kružnici trojúhelníku.", + "help.sketch.circle.two_point": "Nakreslí kružnici ze dvou konců jejího průměru. Použijte to, když jsou známé body na okraji kružnice, a ne její střed.", + "help.sketch.circle.two_tangent": "Nakreslí kružnici zadané velikosti, která se dotýká dvou úseček, kružnic nebo oblouků. Použijte to pro zaoblení pevným poloměrem mezi dvěma křivkami.", + "help.sketch.conic": "Nakreslí kuželosečku mezi dvěma koncovými body, tvarovanou vrcholovým bodem a hodnotou rho. Použijte to pro hladké přechody, jejichž plnost chcete doladit, od ploché až po téměř ostrý roh.", + "help.sketch.constrainer": "Použije vazbu, kterou jedna nebo dvě vybrané křivky už skoro mají, například vodorovnost, rovnoběžnost, tečnost nebo rovnost. Použijte to k uspořádání ručně nakresleného náčrtu po jedné vazbě.", + "help.sketch.constraint.coincident": "Umístí bod na jiný bod, křivku nebo osu náčrtu. Použijte to k zavření mezer v profilu nebo k umístění bodu na úsečku.", + "help.sketch.constraint.collinear": "Umístí dvě úsečky na jednu přímku. Použijte to k zarovnání přerušených hran, například obou stran zářezu.", + "help.sketch.constraint.concentric": "Dá dvěma kružnicím nebo obloukům stejný střed. Použijte to pro kroužky, záhlubky a hřídele s osazením.", + "help.sketch.constraint.curvature": "Zajistí, aby dvě křivky, které se setkávají v koncovém bodě, pokračovaly se stejnou křivostí (G2). Použijte to tam, kde tečné napojení není dost hladké, například na viditelných plochách.", + "help.sketch.constraint.equal": "Vyrovná délky úseček, nebo poloměry kružnic a oblouků. Použijte to, aby jeden rozměr řídil několik shodných prvků.", + "help.sketch.constraint.fix": "Zafixuje body nebo křivky tam, kde jsou, nebo je znovu uvolní. Použijte to pro geometrii, která se nesmí pohnout při tažení nebo řešení náčrtu.", + "help.sketch.constraint.horizontal_vertical": "Učiní úsečku, nebo spojnici dvou bodů, vodorovnou nebo svislou, podle toho, co je blíže. Použijte to k zarovnání obrysu s osami náčrtu.", + "help.sketch.constraint.midpoint": "Umístí bod doprostřed úsečky, nebo spojí středy dvou úseček. Použijte to k vystředění geometrie na hraně.", + "help.sketch.constraint.parallel": "Učiní dvě úsečky rovnoběžnými. Použijte to pro strany, které mají zůstat rovnoběžné při změně jiných rozměrů.", + "help.sketch.constraint.perpendicular": "Zajistí, aby se dvě úsečky protínaly v pravém úhlu. Použijte to pro pravoúhlé rohy mezi úsečkami, které neleží na osách náčrtu.", + "help.sketch.constraint.polygon": "Změní uzavřený řetězec úseček na pravidelný mnohoúhelník: stejné strany, všechny rohy na jedné kružnici. Použijte to, aby se ručně nakreslený mnohoúhelník stal pravidelným a zůstal takový.", + "help.sketch.constraint.symmetry": "Zajistí, aby dva body nebo křivky byly symetrické podle přímky nebo podle bodu. Použijte to, aby profil zůstal symetrický při změně jedné strany.", + "help.sketch.constraint.tangent": "Zajistí, aby se dvě křivky dotýkaly tečně, například úsečka a oblouk. Použijte to pro hladká napojení bez zlomu.", + "help.sketch.construction": "Přepíná křivky mezi běžnou geometrií a konstrukční geometrií, kterou profily vynechávají. Použijte konstrukční křivky jako pomocné prvky pro rozvržení, reference a kóty.", + "help.sketch.construction_line": "Vytvoří nekonečnou konstrukční přímku procházející dvěma body. Použijte ji k rozvržení náčrtu bez rozdělování profilů.", + "help.sketch.construction_line.angle": "Vytvoří nekonečnou konstrukční přímku pod úhlem od osy X náčrtu. Vyberte bod a zadejte úhel, nebo vyberte jeho směr.", + "help.sketch.construction_line.bisector": "Vyberte dvě protínající se přímé úsečky náčrtu a pak jednu ze dvou os úhlu. Výsledek sleduje své zdrojové úsečky.", + "help.sketch.construction_line.horizontal": "Vytvoří nekonečnou vodorovnou konstrukční přímku procházející bodem. Její vodorovná vazba platí i při pozdějších úpravách.", + "help.sketch.construction_line.parallel": "Vyberte přímou úsečku náčrtu a pak umístěte rovnoběžnou nekonečnou konstrukční přímku. Jinou referenci vyberete kliknutím pravým tlačítkem.", + "help.sketch.construction_line.perpendicular": "Vyberte přímou úsečku náčrtu a pak umístěte kolmou nekonečnou konstrukční přímku. Jinou referenci vyberete kliknutím pravým tlačítkem.", + "help.sketch.construction_line.tangent_at": "Vytvoří tečnu v bodě kružnice nebo kruhového oblouku, případně v koncovém bodě otevřeného splajnu nebo kuželosečky. Vyberte křivku a pak bod dotyku.", + "help.sketch.construction_line.tangent_external": "Vyberte kružnici nebo kruhový oblouk, pak vnější bod a řešení tečny. Náhledy ukazují jen body dotyku na nakresleném oblouku.", + "help.sketch.construction_line.tangent_two": "Vyberte dvě kružnice nebo kruhové oblouky a pak v náhledu zvolte společnou tečnu. Body dotyku musí ležet na nakreslených křivkách.", + "help.sketch.construction_line.vertical": "Vytvoří nekonečnou svislou konstrukční přímku procházející bodem. Její svislá vazba platí i při pozdějších úpravách.", + "help.sketch.copy": "Zkopíruje vybrané křivky a body náčrtu spolu s vazbami a kótami mezi nimi. Vložte je do tohoto náčrtu nebo do jiného.", + "help.sketch.create": "Zahájí nový 2D náčrt na rovině nebo na rovinné ploše modelu. Každé vysunutí, rotace a tažení začíná náčrtem.", + "help.sketch.cut": "Zkopíruje vybranou geometrii náčrtu a smaže ji z náčrtu, vše jedním krokem vrácení zpět. Vložte ji jinam v tomto náčrtu nebo do jiného.", + "help.sketch.dimension": "Přidá řídicí kótu: délku, vzdálenost, úhel, poloměr nebo průměr podle toho, co vyberete. Zadejte hodnotu nebo název parametru a náčrt ji následuje.", + "help.sketch.edit": "Otevře existující náčrt k úpravám. Prvky na něm postavené se aktualizují, když náčrt dokončíte.", + "help.sketch.ellipse": "Nakreslí elipsu ze středu, konce hlavní osy a bodu na vedlejší straně. Použijte to pro oválné otvory, vačky a jiné protáhlé oblé tvary.", "help.sketch.equation_curve": "Nakreslí křivku podle vzorců: x(t) a y(t), nebo y = f(x), v zadaném rozsahu. Vzorce mohou používat parametry a křivka se podle nich mění: použijte ji pro sinusovku, spirálu nebo evolventu zubu ozubeného kola.", + "help.sketch.extend": "Prodlouží úsečku nebo oblouk až k nejbližší křivce v cestě, nebo prodlouží dvě křivky, dokud se nesetkají. Použijte to k zavření mezer v profilu po oříznutí nebo úpravách.", + "help.sketch.fillet": "Zaoblí roh, kde se setkávají dvě úsečky nebo oblouky, obloukem zadaného poloměru. Více rohů zaoblených společně sdílí jeden poloměr.", + "help.sketch.finish": "Opustí náčrt a vrátí se k modelu. Jeho uzavřené profily jsou pak připraveny pro Vysunutí, Rotaci a další prvky.", + "help.sketch.finish_auto_constrain": "Spustí Automatické vazby na náčrtu a pak jej dokončí. Použijte to k opuštění plně určeného náčrtu jedním krokem.", + "help.sketch.fit_curves_to_section": "Protne síťové nebo plné těleso rovinou náčrtu a proloží řez úsečkami a oblouky. Použijte to k přestavbě naskenovaného nebo importovaného dílu jako upravitelného náčrtu.", + "help.sketch.include_3d": "Přenese hrany modelu, vrcholy a křivky jiných náčrtů do tohoto náčrtu jako propojené reference, přičemž ty mimo jeho rovinu do ní zploští. Použijte to k tvorbě na geometrii, která neleží v rovině náčrtu.", + "help.sketch.infinite": "Přepíná úsečky mezi běžnými úsečkami a nekonečnými konstrukčními přímkami, které vedou přes celý pohled. Použijte je jako referenční čáry rozvržení, které nikdy nekončí příliš brzy.", + "help.sketch.insert_dxf": "Načte křivky výkresu DXF do náčrtu, ve zvoleném měřítku, natočení a poloze. Použijte to k navázání na 2D výkres z jiného programu, například obrys pro řezání laserem.", + "help.sketch.insert_svg": "Načte cesty výkresu SVG do náčrtu, ve zvoleném měřítku, natočení a poloze. Použijte to k přeměně loga nebo vektorového obrysu na křivky, které lze vysunout.", + "help.sketch.inspect": "Otevře zprávu o otevřeném náčrtu: kolik stupňů volnosti zbývá a zda je plně zavazbený. Použijte to ke zjištění, co se ještě hýbe, než náčrt dokončíte.", + "help.sketch.intersect": "Přidá křivky nebo body, kde tělesa, plochy, hrany nebo jiné náčrty protínají rovinu náčrtu. Zůstanou propojené a sledují model, když se změní.", + "help.sketch.intersection_curve": "Vytvoří 3D křivky tam, kde se setkávají dvě tělesa nebo plochy, propojené s nimi. Použijte je jako cesty nebo vodicí dráhy, které sledují model.", + "help.sketch.isoparametric_curve": "Vytvoří 3D křivku ve směru U nebo V plochy bodem, který vyberete, propojenou s plochou. Použijte ji jako cestu nebo dělicí čáru, která sleduje povrch.", + "help.sketch.line": "Kreslí spojené úsečky bod po bodu, jako otevřený řetězec nebo uzavřený obrys. Je to základní nástroj pro většinu profilů.", + "help.sketch.line.midpoint": "Nakreslí úsečku od jejího středu k jednomu konci, přičemž druhý konec se zrcadlí. Použijte to pro úsečky vystředěné na bod, například souměrnou hranu.", + "help.sketch.line3d": "Nakreslí spojené přímé úsečky mezi body v prostoru, se zapnutým 3D náčrtem. Použijte to pro cesty a rámy, které opouštějí rovinu náčrtu.", + "help.sketch.mirror": "Zrcadlí křivky a body náčrtu podle přímky nebo osy a přidá vazby symetrie. Použijte to k nakreslení poloviny symetrického profilu a jeho doplnění.", + "help.sketch.move": "Přesune nebo otočí křivky a body náčrtu, nebo jejich kopii. Použijte to k přemístění geometrie při zachování jejího tvaru a vazeb.", + "help.sketch.offset": "Vytvoří kopii řetězce křivek v zadané vzdálenosti, na jedné straně nebo na obou. Použijte to pro stěny, obrysy a vůle; vzdálenost zůstává upravitelnou kótou.", + "help.sketch.paste": "Vloží do aktivního náčrtu geometrii náčrtu, kterou jste zkopírovali nebo vyjmuli. Umístěte ji do bodu nebo ji posuňte o odsazení.", + "help.sketch.pattern.circular": "Zkopíruje geometrii náčrtu kolem středu, po celém kruhu nebo o zadaný úhel. Použijte to pro roztečné kružnice šroubů, paprsky a zuby.", + "help.sketch.pattern.rectangular": "Zkopíruje geometrii náčrtu v řádcích a sloupcích v zadaných roztečích. Použijte to pro mřížky otvorů, drážek nebo větracích otvorů.", + "help.sketch.point": "Umístí bod náčrtu. Použijte ho jako referenci pro kóty, vazby, středy otvorů nebo pozdější prvky.", + "help.sketch.point3d": "Umístí bod v prostoru, se zapnutým 3D náčrtem. Použijte ho jako referenci pro 3D křivky a cesty.", + "help.sketch.polygon.circumscribed": "Nakreslí pravidelný mnohoúhelník kolem kružnice, velikost se určuje od středu ke středu strany. Použijte to, když je známé rozevření klíče, například u šestihranné matice.", + "help.sketch.polygon.edge": "Nakreslí pravidelný mnohoúhelník ze dvou konců jedné strany. Použijte to, když je známá délka a poloha strany.", + "help.sketch.polygon.inscribed": "Nakreslí pravidelný mnohoúhelník do kružnice, velikost se určuje od středu k rohu. Použijte to, když je známá velikost přes rohy.", + "help.sketch.project": "Přenese hrany modelu, plochy, vrcholy a křivky jiných náčrtů do tohoto náčrtu, promítnuté do jeho roviny. Zůstanou propojené a sledují model, když se změní.", + "help.sketch.project_to_surface": "Promítne křivky jiných náčrtů ve směru normály tohoto náčrtu na plochu jako propojené 3D křivky. Použijte to k umístění loga, dělicí čáry nebo cesty na zakřivený povrch.", + "help.sketch.rectangle.center": "Nakreslí obdélník ze středu a jednoho rohu. Použijte to pro obrysy vystředěné na bod, například počátek.", + "help.sketch.rectangle.rounded": "Nakreslí obdélník se všemi čtyřmi rohy zaoblenými jedním poloměrem. Použijte to pro desky, víka a otvory se zaoblenými rohy.", + "help.sketch.rectangle.three_point": "Nakreslí obdélník z jedné hrany a bodu na protější straně. Použijte to pro obdélníky pootočené vůči osám náčrtu.", + "help.sketch.rectangle.two_point": "Nakreslí obdélník ze dvou protilehlých rohů. Použijte to pro obrysy desek, bloků a kapes.", + "help.sketch.scale": "Změní měřítko křivek a bodů náčrtu zadaným činitelem kolem základního bodu. Použijte to ke změně velikosti části náčrtu bez nového kreslení.", + "help.sketch.slot.arc_center": "Nakreslí zakřivenou drážku zadané šířky podél oblouku daného středem, začátkem a koncem. Použijte to pro stavěcí drážky kolem čepu.", + "help.sketch.slot.arc_three_point": "Nakreslí zakřivenou drážku zadané šířky podél oblouku procházejícího třemi body. Použijte to, když dráha drážky musí procházet zadanými body.", + "help.sketch.slot.center_point": "Nakreslí přímou drážku zadané šířky od jejího středu ke středu oblouku jednoho konce. Použijte to pro drážky vystředěné na bod.", + "help.sketch.slot.center_to_center": "Nakreslí přímou drážku zadané šířky mezi středy jejích dvou koncových oblouků. Použijte to pro drážky kótované střed–střed, například stavěcí drážky pro šrouby.", + "help.sketch.slot.overall": "Nakreslí přímou drážku zadané šířky od jednoho vnějšího konce k druhému. Použijte to, když záleží na celkové délce drážky.", + "help.sketch.spline.control_point": "Nakreslí kubický splajn tvarovaný řídicími body, kterými neprochází. Použijte to pro hladké, plynulé křivky, které tvarujete přesouváním bodů.", + "help.sketch.spline.control_point_5": "Nakreslí splajn stupně 5 tvarovaný řídicími body. Použijte to tam, kde se křivky musí napojit s hladší křivostí, například na viditelných tvarových plochách.", + "help.sketch.spline.fit_point": "Nakreslí hladký splajn, který prochází každým bodem, který umístíte, otevřený nebo uzavřený. Použijte to k obkreslení tvaru přes známé body.", + "help.sketch.spline3d": "Nakreslí hladkou křivku v prostoru body, se zapnutým 3D náčrtem. Použijte to pro cesty tažení a vedení kabelů, které opouštějí rovinu náčrtu.", + "help.sketch.spun_profile": "Vytvoří v rovině náčrtu obrys, který těleso opíše při otáčení kolem osy. Použijte to k získání siluety soustruženého dílu pro rotaci nebo výkres.", + "help.sketch.text": "Napíše do náčrtu text zvoleným písmem, výškou a úhlem; jeho slova mohou sledovat parametry. Vysuňte jej nebo z něj vytvořte reliéf pro štítky a nápisy.", + "help.sketch.transform": "Změní měřítko, otočí a přesune geometrii náčrtu kolem středu jedním krokem. Použijte to k přemístění a změně velikosti výběru najednou.", + "help.sketch.trim": "Odstraní část křivky mezi nejbližšími průsečíky kolem místa, kam kliknete. Použijte to k vyčištění překrývajících se úseček do uzavřeného profilu.", "help.solid.align": "Posune vybraná tělesa tak, aby se bod, plocha nebo rovina na nich setkala s bodem, plochou nebo rovinou jinde. Hodí se k přiložení dílu k jinému bez měření odsazení.", + "help.solid.boundary_fill": "Vytvoří tělesa z oblastí uzavřených překrývajícími se nástrojovými tělesy, přičemž vyplní jen oblasti, které vyberete. Použijte to k vytvoření tvaru z prostoru, který společně ohraničuje několik těles.", + "help.solid.bounding_solid": "Vytvoří kvádr, který obklopuje vybraná tělesa, s volitelným okrajem. Použijte to k zobrazení celkové velikosti dílu nebo jako polotovar, ze kterého se obrábí.", + "help.solid.box": "Vytvoří kvádr z délky, šířky a výšky, z rohového bodu nebo vystředěný na bod. Použijte to pro rychlý blok, zástupný díl nebo těleso, do kterého se řežou prvky.", "help.solid.chamfer": "Zkosí vybrané hrany plochým sražením o zadanou vzdálenost. Hodí se k otupení ostrých hran nebo ke snadnějšímu zasunutí kolíku či šroubu.", + "help.solid.coil": "Vytvoří šroubovicové těleso, například pružinu, z průměru, počtu závitů, výšky nebo stoupání a kulatého či čtvercového průřezu. Použijte to pro pružiny, cívky a šroubovicové výstupky.", "help.solid.combine": "Sjednotí tělesa, vyjme je z cílového tělesa nebo ponechá jen společný objem; nástrojová tělesa lze ponechat. Hodí se ke slučování dílů, k vyříznutí jednoho tvaru druhým nebo k nalezení místa, kde se dvě tělesa překrývají.", + "help.solid.cone": "Vytvoří kužel z kruhové základny a výšky, nebo komolý kužel, pokud má poloměr i horní strana. Použijte to pro zúžení, nálevky, kuželové záhlubky a hroty.", + "help.solid.cylinder": "Vytvoří válec z poloměru nebo průměru a výšky, stojící na bodě podél osy. Použijte to pro hřídele, kolíky, nálitky a kulaté polotovary.", "help.solid.draft": "Nakloní vybrané plochy o zadaný úhel měřený od neutrální roviny. Hodí se u lisovaných či odlévaných dílů, aby šly snadno vyjmout z formy.", + "help.solid.emboss": "Vytáhne profily náčrtu, například text nebo logo, z plochy ven, nebo je do ní zahloubí. Použijte to pro nápisy, štítky a značení na rovných nebo kulatých plochách.", "help.solid.extrude": "Vysune profil náčrtu do 3D o zadanou vzdálenost a přidá nebo odebere materiál. Hodí se k přeměně plochého obrysu na kvádr, nálitek nebo vybrání.", "help.solid.fillet": "Zaoblí vybrané hrany hladkým kruhovým přechodem o zadaném poloměru. Hodí se ke zjemnění ostrých hran kvůli pevnosti, pohodlí nebo vzhledu.", "help.solid.hole": "Vyvrtá kruhový otvor zadaného průměru ve zvoleném bodě plochy. Hodí se pro průchozí otvory pro šrouby, kolíky a další jednoduché kruhové otvory.", @@ -1408,20 +1678,62 @@ "help.solid.move": "Posune nebo otočí vybraná tělesa, případně jejich kopii, o zadanou vzdálenost a úhel. Hodí se ke změně polohy tělesa nebo k vytvoření dalšího tělesa na jiném místě.", "help.solid.offset_face": "Posune vybrané plochy dovnitř nebo ven o zadanou vzdálenost a okolní plochy je následují. Hodí se k zesílení stěny, prohloubení vybrání nebo zvýšení nálitku bez úprav náčrtu.", "help.solid.pattern.circular": "Opakuje vybrané objekty kolem osy v zadaném počtu a celkovém úhlu. Hodí se pro roztečné kružnice šroubů, paprsky, žebra a zuby.", + "help.solid.pattern.path": "Zkopíruje prvky nebo tělesa podél cesty náčrtu podle počtu a rozteče. Použijte to pro otvory podél zakřivené hrany nebo díly podél kolejnice.", "help.solid.pattern.rectangular": "Zopakuje vybrané objekty v jednom nebo dvou směrech podle zadaného počtu a rozteče. Použijte to pro řady a mřížky otvorů, žeber, kolíků nebo patek.", + "help.solid.pipe": "Vytvoří kulatou trubku podél cesty z křivek náčrtu, plnou nebo dutou se zadanou tloušťkou stěny. Použijte to pro trubky, dráty, kabely a kolejnice.", "help.solid.press_pull": "Přidá nebo odebere materiál při tažení plochy, případně zaoblí hrany při jejich tažení. Použijte to pro rychlé úpravy přímo na modelu.", "help.solid.remove": "Odebere vybraná tělesa z návrhu od tohoto místa na časové ose; dřívější kroky je zachovají. Použijte to k odstranění pomocného tělesa, například řezného nástroje, který už nepotřebujete.", "help.solid.replace_face": "Přesune vybrané rovinné plochy do roviny nebo na rovnoběžnou plochu a těleso se natáhne či zmenší, aby na ni dosáhlo. Použijte to, aby plocha lícovala s jiným dílem nebo konstrukční rovinou.", "help.solid.revolve": "Otočí profil náčrtu kolem osy a vytvoří rotační těleso. Použijte to pro hřídele, knoflíky, misky a každý díl, který je souměrný kolem osy.", + "help.solid.rib": "Přidá tenkou stěnu podél otevřené křivky náčrtu, vyplněnou až k nejbližším plochám tělesa. Použijte to k vyztužení stěn a rohů, například u lisovaných nebo tištěných dílů.", "help.solid.scale": "Zvětší nebo zmenší vybraná tělesa o zadaný činitel, stejný ve všech směrech nebo zvlášť pro každou osu. Použijte to ke změně velikosti importovaného tvaru nebo k započtení smrštění.", "help.solid.shell": "Vytvoří z tělesa skořepinu se stěnami zadané tloušťky a může otevřít vybrané plochy. Použijte to pro krabice, kryty a jiné tenkostěnné díly.", + "help.solid.sphere": "Vytvoří kouli z poloměru nebo průměru kolem středu. Použijte to pro kuličky, knoflíky a zaoblené konce.", "help.solid.split_body": "Rozdělí těleso na samostatná tělesa rovinou, plochou jiného tělesa nebo úsečkou náčrtu. Použijte to pro díly, které se tisknou, obrábějí nebo barví zvlášť.", "help.solid.split_face": "Rozdělí vybrané plochy podél roviny, plochy jiného tělesa nebo křivek náčrtu, aniž by těleso rozřízlo. Použijte to, aby část plochy měla vlastní úkos, barvu nebo odsazení.", "help.solid.sweep": "Protáhne profil náčrtu po cestě a vytvoří těleso. Použijte to pro trubky, lišty, rukojeti a každý díl s konstantním průřezem, který sleduje křivku.", + "help.solid.thread": "Přidá metrický závit ISO na válcovou plochu, buď jako kosmetický závit, nebo vyříznutý do tělesa. Použijte to pro šrouby, závitové otvory a tištěné šroubové díly.", + "help.solid.torus": "Vytvoří anuloid, tedy prstenec, z hlavního poloměru kolem jeho osy a vedlejšího poloměru jeho kulatého průřezu. Použijte to pro O-kroužky, držadla a kulaté korálky.", + "help.solid.web": "Přidá tenkou stěnu podél každé otevřené křivky náčrtu, každou vyplněnou až k nejbližším plochám tělesa. Použijte to pro mřížku podpůrných stěn uvnitř krytů a táců.", + "help.surface.blend": "Vytvoří plochu, která překlenuje hrany dvou těles, tečně nebo spojitě v křivosti k oběma. Použijte to k hladkému spojení dvou ploch přes mezeru.", + "help.surface.boundary": "Vytvoří plochu vyplňující smyčku dvou až čtyř křivek náčrtu, nebo síť křivek. Použijte to pro volné panely dané svými hranami.", + "help.surface.extend": "Prodlouží plochu za její hrany o vzdálenost nebo až k rovině či ploše. Použijte to, aby se plochy před oříznutím nebo sešitím překrývaly.", + "help.surface.extrude": "Vysune křivky nebo profily náčrtu o vzdálenost do plochy, jen stěny, bez čel. Použijte to pro tenké stěny a pro řezné či dělicí nástroje.", + "help.surface.fair": "Vyhladí vnitřek volných ploch, zatímco jejich hrany zůstanou na místě. Použijte to k vyrovnání nerovností a vlnitých odrazů na ploše.", + "help.surface.loft": "Vytvoří plochu, která prochází dvěma nebo více průřezy v pořadí, bez čel. Použijte to pro skořepiny a přechody mezi různými tvary.", + "help.surface.match": "Přestaví hranu plochy tak, aby se setkala s hranou jiného tělesa, se shodnou tečností nebo křivostí. Použijte to k hladkému uzavření spoje mezi dvěma plochami.", + "help.surface.offset": "Vytvoří kopii ploch ve vzdálenosti podél jejich normál jako nové plošné těleso. Použijte to pro povlaky, vůle nebo druhou stranu stěny.", + "help.surface.patch": "Vyplní oblast náčrtu nebo uzavřenou smyčku hran plochou, rovnou nebo hladce zakřivenou. Použijte to k uzavření děr v plošném tělese.", + "help.surface.reverse_normal": "Obrátí plochy plošného tělesa, takže jejich vnější strana směřuje na druhou stranu. Použijte to před zesílením nebo sešitím, když plochy míří dovnitř.", + "help.surface.revolve": "Otočí křivky nebo profily náčrtu kolem osy do plochy, bez čel. Použijte to pro kulaté skořepiny, například stínidla, mísy a trysky.", + "help.surface.ruled": "Vytvoří pás přímek vycházejících z řetězce hran, podél normály plochy, tečně nebo pod úhlem. Použijte to pro úkosové stěny, náběhy a dělicí plochy.", + "help.surface.stitch": "Sešije plošná tělesa podél sdílených hran a pokud se uzavřou, vznikne těleso. Použijte to k přeměně množiny ploch na jedno těleso.", + "help.surface.sweep": "Posune křivky nebo profily náčrtu po cestě do plochy, bez čel. Použijte to pro žlaby, lišty a jiné tenké tvary, které sledují cestu.", + "help.surface.thicken": "Dá plošnému tělesu tloušťku a změní je na těleso. Použijte to k vytvoření tisknutelných nebo obrobitelných dílů z ploch.", + "help.surface.trim": "Řízne plochu rovinou, jinou plochou nebo křivkami náčrtu a ponechá stranu, kterou vyberete. Použijte to k oříznutí ploch do tvaru před sešitím.", + "help.surface.unstitch": "Odděluje plochy tělesa do samostatných plošných těles; těleso se rozpadne na plochy. Použijte to k úpravě jednotlivých ploch tělesa.", + "help.surface.untrim": "Odstraní z plochy otvory, nebo obnoví její vnější hranici na přirozené meze povrchu. Použijte to k získání celé plochy zpět po oříznutí.", "help.third_party": "Licence třetích stran", "help.timeline.compute_all": "Přepočítá všechny prvky na časové ose od začátku. Použijte to k obnovení modelu a ke zjištění, které prvky selhávají.", "help.timeline.delete": "Smaže vybrané prvky z časové osy; smazáním náčrtu se smažou i prvky z něj vytvořené. Použijte to k odstranění kroku, který už nechcete.", + "help.timeline.dependents": "Vypíše prvky, které by se smazaly spolu s prvkem, a ty, které by bez něj selhaly. Použijte to před smazáním nebo změnou prvku.", "help.timeline.play": "Přehraje zbývající prvky jeden po druhém s půlsekundovou pauzou po každém přestavění. Spuštěním tohoto příkazu znovu nebo stisknutím Escape přehrávání zastavíte; Přejít na konec skočí okamžitě.", + "help.view.apply": "Natočí pohled do standardního směru, například zepředu, shora nebo izometricky, nebo do uloženého pojmenovaného pohledu. Použijte to k prohlížení modelu z pevného úhlu.", + "help.view.delete": "Smaže uložený pojmenovaný pohled. Model se nezmění.", + "help.view.fit": "Přiblíží a posune pohled tak, aby celý model nebo výběr vyplnil pohled. Použijte to, když model zmizel z dohledu.", + "help.view.grid": "Zobrazí nebo skryje mřížku v pohledu. Použijte ji jako vodítko velikosti a orientace při modelování.", + "help.view.ground_shadow": "Zobrazí nebo skryje stín modelu na podložce. Použijte to k snazšímu posouzení výšky a polohy.", + "help.view.home": "Vrátí pohled do výchozího směru a přizpůsobí model. Použijte to k rychlému návratu do známého pohledu.", + "help.view.list": "Vypíše pojmenované pohledy uložené v návrhu. Použijte to k nalezení dříve uloženého pohledu.", + "help.view.navigate": "Natočí, posune nebo přiblíží pohled po krocích, například o čtvrt otáčky doleva. Použijte to k přesnému pohybu kamery místo tažení.", + "help.view.navigation_bar": "Zobrazí nebo skryje navigační lištu ve spodní části pohledu. Skryjte ji pro více místa, zobrazte ji pro přístup k nástrojům pohledu myší.", + "help.view.rename": "Dá uloženému pojmenovanému pohledu nový název. Samotný pohled zůstane stejný.", + "help.view.save": "Uloží aktuální polohu kamery jako pojmenovaný pohled v návrhu. Použijte to k pozdějšímu návratu ke stejnému úhlu, například pro snímky obrazovky.", + "help.view.spin": "Otáčí pohled kolem modelu nepřetržitě až do dalšího kliknutí nebo stisku klávesy. Použijte to k prezentaci modelu ze všech stran.", + "help.view.tool": "Zapne nástroj kamery, otáčení, posun nebo přiblížení, takže tažení levým tlačítkem myši pohybuje pohledem, dokud jej nevypnete. Použijte to na trackpadu nebo bez prostředního tlačítka myši.", + "help.view.visual_style": "Přepne způsob zobrazení modelu: stínovaný s hranami nebo bez nich, drátový model, nebo se skrytými hranami. Použijte drátový model pro pohled dovnitř, stínovaný pro čistý vzhled.", + "history.sketch_under_constrained": "Nedourčeno (stupňů volnosti: {count})", + "history.sketch_under_constrained_one": "Nedourčeno ({count} stupeň volnosti)", "hole_presets.confirm_delete": "Potvrdit smazání", "hole_presets.delete": "Smazat", "hole_presets.delete_prompt": "Smazat tuto osobní předvolbu? Existující otvory se nezmění.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Zkontrolujte typ kloubu (např. Pevný), ukotvení, limity kloubu a hodnoty řízené parametry.", "joint_move.blocked_title": "Tento díl nelze posunout", "joint_move.coarse": "Krok otáčení blízko osy (°)", + "joint_move.conflict": "Kloub tohoto dílu je v konfliktu s ostatními: {joint}.", + "joint_move.conflict_hint": "Upravte, potlačte nebo smažte kloub v konfliktu, aby mohly díl umístit ostatní klouby.", "joint_move.distance": "Vzdálenost od začátku", "joint_move.done": "Hotovo", "joint_move.fine": "Krok otáčení daleko od osy (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Různé materiály", "measure.at": "V bodě", "measure.item": "Položka {number}", + "measure.quick_copied": "Měření zkopírováno", + "measure.quick_copy": "Kliknutím zkopírujete měření", + "measure.quick_edges": "Hrany: {count}", + "measure.quick_faces": "Plochy: {count}", "messages.ago_h": "před {n} h", "messages.ago_min": "před {n} min", "messages.ago_s": "před {n} s", @@ -1620,6 +1938,8 @@ "motion.track_name": "Stopa {number}", "nav.alias.help": "Shift+Alt+tažení levým tlačítkem otáčí, Shift+Alt+tažení prostředním posouvá, Shift+Alt+tažení pravým přibližuje; tažení prostředním tlačítkem také posouvá a pravým otáčí", "nav.blender.help": "Tažení prostředním tlačítkem otáčí, Shift+prostřední posouvá, Ctrl+prostřední přibližuje; tažení pravým tlačítkem kameru nemění", + "nav.creo.help": "Tažení prostředním tlačítkem otáčí, Shift+prostřední posouvá, Ctrl+prostřední se svislým tažením přibližuje (tažením dolů přiblížíte); přibližuje i kolečko", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Myš a 3D myš otáčejí přes oba póly a zachovávají natočení. Přichytávání os klávesou Shift je vypnuto.", "nav.free_orbit.label": "Volné otáčení", "nav.free_orbit.snap_help": "Myš a 3D myš otáčejí přes oba póly a zachovávají natočení. Podržením klávesy Shift při otáčení tažením přichytíte směr pohledu a natočení.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+tažení levým tlačítkem posouvá, Shift+Alt+levé tlačítko přibližuje, Ctrl+tažení levým tlačítkem na prázdném místě otáčí", "nav.inventor.help": "Tažení prostředním tlačítkem posouvá, Shift+prostřední otáčí, Ctrl+prostřední přibližuje, tažení pravým tlačítkem otáčí", "nav.maya.help": "Alt+tažení levým tlačítkem otáčí, Alt+prostřední tlačítko posouvá, Alt+pravé tlačítko přibližuje; tažení prostředním tlačítkem také posouvá", + "nav.nx.help": "Tažení prostředním tlačítkem otáčí, Shift+prostřední posouvá (v NX prostřední + pravé), Ctrl+prostřední přibližuje (v NX prostřední + levé); tažení pravým tlačítkem kameru nemění", "nav.openscad.help": "Tažení levým tlačítkem na prázdném místě otáčí, Shift+tažení levým vybírá obdélníkem, tažení geometrie náčrtu ji upravuje; tažení pravým nebo prostředním tlačítkem posouvá, Shift+tažení pravým nebo prostředním přibližuje", "nav.perspective.sketch": "Úpravy náčrtu používají ortografický pohled. Dokončením náčrtu přepnete na perspektivu.", "nav.right_drag_orbits.help": "Vypnuto: tažení pravým tlačítkem kameru nemění a pravé tlačítko jen otevírá kontextovou nabídku. Volba přiřazení myši SolidWorks tuto možnost vypne.", @@ -1748,6 +2069,11 @@ "not a move": "nejde o posun", "not a number": "není číslo", "open a sketch first": "nejprve otevřete náčrt", + "parameters.apply_live": "Použít každou změnu po opuštění jejího pole", + "parameters.apply_live_tip": "Vypnuto: změny čekají na Použít nebo OK, pak se návrh přestaví jednou pro všechny. Zrušit nebo Escape je zahodí.", + "parameters.held": "Změny čekající na Použít: {count}", + "parameters.held_hint": "Upravte výrazy a jednotky. Změny čekají na Použít nebo OK.", + "parameters.held_one": "1 změna čeká na Použít", "parts.automatic_name": "automaticky", "parts.dimension.across_flats": "Rozevření klíče", "parts.dimension.bore": "Otvor", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Šroub s půlkulovou hlavou a vnitřním šestihranem", "parts.family.dowel_pin": "Válcový kolík (lícovaný)", "parts.family.hex_bolt": "Šroub se šestihrannou hlavou", + "parts.family.hex_cap_screw_inch": "Šroub se šestihrannou hlavou (palcový)", "parts.family.hex_nut": "Šestihranná matice", + "parts.family.hex_nut_inch": "Šestihranná matice (palcová)", "parts.family.set_screw": "Stavěcí šroub s vnitřním šestihranem, s plochým koncem", "parts.family.socket_head_cap_screw": "Šroub s válcovou hlavou a vnitřním šestihranem", "parts.family.washer": "Plochá podložka", + "parts.family.washer_sae": "Plochá podložka, SAE (úzká)", + "parts.family.washer_uss": "Plochá podložka, USS (široká)", + "parts.holes": "Otvory (volitelné)", + "parts.placement_hint": "vyberte jeden nebo více otvorů, aby se do každého usadil díl, nebo OK umístí díl do počátku", + "parts.system": "Soustava jednotek", + "parts.system.inch": "Palcová", + "parts.system.metric": "Metrická", "pattern.alignment_2": "Zarovnání 2", "pattern.alignment_hint": "Počty zahrnují originál. Na střed rozloží kopie rovnoměrně; Převrátit volí stranu navíc u sudých počtů.", "pattern.direction_1": "Směr 1", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Vyhlazuje zubaté hrany.", "prefs.applies_on_restart": "Použije se po restartu", "prefs.assistant": "Asistent", + "prefs.auto_operation": "Automaticky vybírat operaci", + "prefs.auto_operation_note": "Okna prvků vyberou Sjednotit, Nové těleso nebo Vyjmout podle toho, čeho se nový materiál dotýká, dokud sami jednu nevyberete. Vypnuto: ponechají si operaci, se kterou se otevřou.", "prefs.axes": "Osy", "prefs.axis": "Osa", "prefs.bodies_folders": "Složky těles", @@ -1820,6 +2157,8 @@ "prefs.bottom_centre": "Dole uprostřed", "prefs.bottom_right": "Vpravo dole", "prefs.browser": "Prohlížeč", + "prefs.browser_eye_left": "Oko vedle šipky sbalení", + "prefs.browser_eye_left_note": "Řádky prohlížeče zobrazují oko pro zobrazení/skrytí vedle šipky sbalení jako dříve, místo ve sloupci na pravém konci řádků.", "prefs.browser_reveal_on_hover": "Odkrýt při najetí myší", "prefs.browser_show_note": "Zobrazeno ponechá prohlížeč na obrazovce. Odkrýt při najetí myší jej skryje, dokud ukazatel nenajede na jeho místo nebo na tenký jazýček u jeho levého okraje, a prohlížeč zůstane otevřený, dokud je ukazatel uvnitř něj nebo je otevřená některá z jeho nabídek.", "prefs.browser_shown": "Zobrazeno", @@ -1827,6 +2166,8 @@ "prefs.button_left": "Tažení levým tlačítkem", "prefs.button_middle": "Tažení prostředním tlačítkem", "prefs.button_right": "Tažení pravým tlačítkem", + "prefs.carousel_next": "Další", + "prefs.carousel_previous": "Předchozí", "prefs.choose_font": "Vybrat soubor písma…", "prefs.click": "Klik", "prefs.contact_shading": "Měkké stínování kontaktů", @@ -1839,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Zakřivené plochy", "prefs.curves": "Zakřivené plochy", + "prefs.cut_preview_tint": "Zobrazit odebraný materiál červeně", + "prefs.cut_preview_tint_help": "Náhled vyplní materiál, který prvek odebírá, i tvar, který nahrazuje, červeným průhledným stínem. Když je vypnuto, jsou tyto výplně zcela průhledné a kreslí se jen jejich obrysy.", + "prefs.dark_parts_shading": "Zachovat tvar tmavých dílů", + "prefs.dark_parts_shading_help": "Stínuje pohled v lineárním světle s jemným světlem oblohy, takže tmavé plochy zachovají přechod a nezčernají", "prefs.dead_zone_note": "Šrafované pásmo je mrtvá zóna: pohyb uvnitř něj se ignoruje.", "prefs.default": "výchozí", "prefs.design": "Výchozí nastavení návrhu", @@ -1853,6 +2198,8 @@ "prefs.edges": "Hrany a stínování", "prefs.extend": "Prodloužit", "prefs.extra_navigation": "Ctrl+tažení levým tlačítkem v prázdném prostoru otáčí pohled; podržením mezerníku pohled posunete.", + "prefs.extrude_view_isometric": "Při otevření Vysunutí otočit pohled do izometrického", + "prefs.extrude_view_return": "Po zavření Vysunutí vrátit dřívější pohled", "prefs.follows_os": "Podle systému", "prefs.font": "Písmo", "prefs.font_fallback": "Znaky, které vybrané písmo neobsahuje, se nahradí vestavěným písmem, takže žádný popisek nezobrazí prázdný čtverec.", @@ -1868,8 +2215,11 @@ "prefs.graphics_card_auto": "Automaticky", "prefs.graphics_card_missing": "Uložená grafická karta není k dispozici; použije se možnost Automaticky.", "prefs.graphics_card_restart": "Projeví se po restartování aplikace SolidCraft. Tuto volbu přepíše WGPU_ADAPTER_NAME.", + "prefs.graphics_card_unused": "Uložená grafická karta se pro toto okno nepoužila; použitá karta je uvedena v nabídce Nápověda › O aplikaci SolidCraft a ve stavovém řádku. Zkuste možnost Automaticky, nebo nastavte WGPU_ADAPTER_NAME na jedinečnou část názvu karty.", "prefs.graphics_note": "Rychlost, nebo hladkost obrazu: každá volba ukazuje svůj účinek na ukázce.", "prefs.graphics_presets_note": "Předvolby nastaví níže uvedené volby najednou.", + "prefs.hide_constraint_glyphs_zoomed_out": "Skrýt symboly vazeb při oddálení", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Symboly vazeb zmizí z pohledu, když je náčrt oddálen natolik, že by ho zahlcovaly. Vypnuto: při každém zvětšení zůstávají ve stejné velikosti na obrazovce.", "prefs.history": "Historie", "prefs.history_origin_bodies": "Zobrazit počátek a tělesa nahoře", "prefs.history_origin_bodies_note": "Historie vlevo nebo pod prohlížečem začíná složkou Tělesa aktivní komponenty a počátkem, s ikonami oka a nabídkami jako v prohlížeči. Historie dole zůstává beze změny.", @@ -1880,6 +2230,8 @@ "prefs.history_sketches_note": "Při nastavení Náčrty na Pod svým prvkem zobrazuje Historie vlevo každý náčrt o úroveň níž, pod prvním prvkem, který z něj vychází, pokud je dost široká pro názvy. Časová osa dole vždy zachovává pořadí vytvoření.", "prefs.history_sketches_under_feature": "Pod svým prvkem", "prefs.hold_stop_snapping": "Podržením vypnout přichytávání", + "prefs.home_fit_size": "Velikost pro Domů a Přizpůsobit", + "prefs.home_fit_size_note": "Kolik pohledu model vyplní, když jej zarámuje Domů, Přizpůsobit, otevřený návrh nebo změna pohledu v navigátoru, ať je nastavení níže zapnuté, nebo ne. 100 %: vyplní pohled mezi panely, kompasem a navigační lištou.", "prefs.icons_only": "Pouze ikony", "prefs.imported_file": "Importovaný soubor", "prefs.in_browser": "V prohlížeči", @@ -1888,13 +2240,22 @@ "prefs.interface_language": "Jazyk rozhraní", "prefs.interface_note": "Vzhled aplikace SolidCraft a rozmístění jejích částí.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Obrátit zakřivené šipky natočení", + "prefs.invert_curved_roll_arrows_note": "Dvě zakřivené šipky v rohu krychle natáčejí pohled v rovině obrazovky. Zapnuto: šipka po směru hodinových ručiček natáčí pohled proti směru hodinových ručiček a šipka proti směru hodinových ručiček ho natáčí po směru. Vypnuto: každá šipka natáčí pohled tak, jak je zakřivená.", + "prefs.invert_navigator_arrows": "Obrátit šipky otáčení krychle pohledu", + "prefs.invert_navigator_arrows_note": "Šipky kolem krychle otáčejí kameru tím směrem, kam míří, jako ve Fusion a Inventor: šipka vlevo míří doprava a stáčí kameru doprava. Vypnuto: šipka otáčí krychli na stranu, na které leží, takže šipka vlevo stáčí kameru doleva. Zakřivené šipky natočení tím nejsou dotčeny.", + "prefs.keep_work_on_tab_switch": "Ponechat dialogy a nástroje otevřené při přepínání návrhů", + "prefs.keep_work_on_tab_switch_note": "Každá karta návrhu si ponechá otevřený dialog nebo nástroj s tím, co jste v něm vybrali a zadali, i svou kartu panelu nástrojů. Po návratu k návrhu jsou zase tam. Vypnuto: přepnutí návrhu je zruší a zobrazí kartu Model.", "prefs.labels": "Popisky", + "prefs.language_system": "Systém", "prefs.layout": "Rozvržení", "prefs.layout_note": "Kompaktní ukotví panely k okrajům okna. Průsvitnost prohlížeče je k dispozici v režimu Plovoucí. Stranu asistenta změníte na stránce Asistent.", "prefs.left": "Vlevo", "prefs.left_click": "Levé kliknutí", "prefs.line_drag_draws_one": "Stisknutí a tažení nakreslí jednu úsečku", "prefs.line_drag_draws_one_note": "V nástroji Úsečka nakreslí stisknutí, tažení a puštění jednu úsečku od místa stisknutí po místo puštění a tím kreslení skončí. Kliknutí stále kreslí řetězec. Vypnuto: tažení umístí bod tam, kde tlačítko pustíte, stejně jako kliknutí.", + "prefs.line_hover_tangent_arc": "Setrvání na posledním bodu úsečky přepne na tečný oblouk", + "prefs.line_hover_tangent_arc_note": "V nástroji Úsečka po nakreslení úseku odsuňte ukazatel od posledního bodu řetězce, vraťte se a podržte jej na něm v klidu: další kliknutí ukončí tečný oblouk a stejné gesto se vrací k úsečkám. Vypnuto: setrvání tam nic nedělá.", "prefs.linked_designs": "Propojené návrhy", "prefs.live_input": "Živý vstup", "prefs.live_preview": "Živý náhled", @@ -1908,6 +2269,9 @@ "prefs.max_file_size_step": "Soubory STEP a importu", "prefs.max_file_size_web": "Webová aplikace otevírá soubory STEP a importu do 512 MB a návrhy do 256 MB: karta prohlížeče větší soubory nepojme. V aplikaci pro počítač lze limity zvýšit.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Velké ikony", + "prefs.menu_list": "Seznam", + "prefs.menus": "Nabídky", "prefs.minutes": "minut", "prefs.minutes_suffix": " min", "prefs.mouse": "Myš a trackpad", @@ -1915,6 +2279,8 @@ "prefs.mouse_mapping": "Přiřazení myši", "prefs.navigation": "Navigace", "prefs.navigation_note": "Jak myš, trackpad a 3D myš pohybují pohledem.", + "prefs.navigator_fit": "Přizpůsobit model po změně pohledu v navigátoru", + "prefs.navigator_fit_note": "Plocha, roh nebo šipka krychle pohledu, případně osa orientačního ovladače, také zaměří pohled na střed modelu z jediné vzdálenosti, ze které je celý vidět ze všech stran (jeho ohraničující koule). Domů při zapnutí používá stejné přiblížení a střed, takže pohledy zvolené po něm se jen otáčejí. Vypnuto: pohled se otáčí na místě a zachovává svůj cíl a přiblížení.", "prefs.network_host_remove": "Odebrat", "prefs.network_locations": "Povolit síťová umístění v návrzích", "prefs.network_locations_note": "Vypnuto: propojené soubory návrhu na jiném počítači (\\\\server\\share) se otevírají jen ze zde uvedených serverů nebo poté, co jeden povolíte na výzvu.", @@ -1927,10 +2293,18 @@ "prefs.origin_plane_names": "Názvy rovin počátku", "prefs.origin_plane_names_note": "Názvy zobrazené v prohlížeči, dialozích a seznamech. {top} je XY, {front} je XZ a {right} je YZ, osa Z směřuje nahoru. Příkazy, skripty a uložené návrhy zachovávají XY, XZ a YZ.", "prefs.overall_speed": "Celková rychlost", + "prefs.parameter_list_rows": "Řádky seznamu parametrů", + "prefs.parameter_list_rows_tip": "Šipka dolů v prázdném poli hodnoty zobrazí seznam parametrů, nejprve oblíbené, nejvýše v tomto počtu. Menší počet udrží seznam přehledný ve velkém návrhu.", + "prefs.persistent_ribbon_pressed": "Zvýrazňovat aktivní příkazy na pásu karet", + "prefs.persistent_ribbon_pressed_help": "Zvýrazní příkazy na pásu karet, dokud jsou jejich účinky zapnuté. Vypnutím zachováte dřívější neutrální vzhled a nápovědu k příkazům.", "prefs.perspective_fov": "Zorný úhel", "prefs.placement": "Umístění", "prefs.prefer_free_sketch_points": "Při překrytí bodů upřednostnit pohyblivé body náčrtu", "prefs.preview_choices": "Náhled vašich voleb", + "prefs.preview_tint_new_faces": "Podbarvit nový povrch v náhledu", + "prefs.preview_tint_new_faces_help": "Náhled prvku, který mění těleso, může vykreslit povrch, který prvek přidává, barvou náhledu. Když je vypnuto, těleso se vykreslí samo o sobě.", + "prefs.print_face_highlight": "Zvýraznění tiskové plochy", + "prefs.print_face_highlight_tip": "Jak výrazně se tisková plocha tělesa v pohledu obarví a obtáhne. 0 % nezobrazí žádné zvýraznění.", "prefs.profile_active": "Aktivní profil", "prefs.profile_applied": "Profil byl použit.", "prefs.profile_changed": "Nastavení se od uložení profilu změnila. Uložit je do něj zapíše.", @@ -1952,9 +2326,13 @@ "prefs.quality_fastest": "nejrychlejší", "prefs.quality_slowest": "nejpomalejší", "prefs.quality_smoother": "hladší", + "prefs.quick_measure": "Rychlé měření v rohu pohledu", + "prefs.quick_measure_note": "Velikost výběru v pravém dolním rohu pohledu: délka hrany, nebo Ø a R u kulaté hrany, obsah plochy, poloha bodu, vzdálenost a úhel dvou položek, celkový součet u několika hran nebo ploch. Kliknutím ji zkopírujete.", "prefs.render_previous_geometry_budget": "Použít předchozí rozpočet geometrie náhledu renderu", "prefs.render_previous_geometry_budget_help": "Obnoví předchozí pevný limit geometrie (512 MiB na 64bitovém desktopu, 128 MiB jinde) místo rozpočtu podle zařízení.", "prefs.reports_saved": "{n} uloženo", + "prefs.ribbon_click_ends_tool": "Kliknutím na tlačítko spuštěného nástroje jej ukončíte", + "prefs.ribbon_click_ends_tool_note": "Kliknutí na zvýrazněné tlačítko právě používaného nástroje náčrtu na pásu karet nástroj ukončí, takže kliknutí v pohledu opět vybírají. Vypnuto: kliknutí nástroj spustí znovu.", "prefs.ribbon_reveal": "Ukazovat výsledky hledání na pásu karet", "prefs.ribbon_reveal_note": "Najetí na výsledek v Hledat příkazy ukáže, kde se příkaz na pásu karet nachází: jeho kartu, tlačítko nebo řádek v rozbalovací nabídce panelu. Příkaz spuštěný z hledání tam zabliká a běžící příkaz z rozbalovací nabídky označí svůj panel.", "prefs.right_click": "Pravé kliknutí", @@ -1965,6 +2343,8 @@ "prefs.search_empty": "Žádná odpovídající nastavení", "prefs.select": "Vybrat", "prefs.select_one_item": "Vybrat jednu položku", + "prefs.select_other_hidden": "Vybírat skrytou geometrii pomocí Vybrat jiné", + "prefs.select_other_hidden_help": "Zapnuto: zahrne skrytá tělesa, náčrty a zakryté hrany v blízkosti ukazatele. Vypnuto: použije původní seznam viditelné geometrie pod ukazatelem.", "prefs.selecting": "Výběr", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift jen přidává; Ctrl / Cmd přepíná", @@ -1976,31 +2356,63 @@ "prefs.sketch_align_points_note": "Při kreslení se bod zarovná vodorovně s jedním bodem náčrtu a zároveň svisle s jiným, s tečkovaným vodítkem, a kliknutí zachová obě zarovnání. Vypnuto: jen s předchozím bodem, vždy v jedné ose.", "prefs.sketch_conflict_colour": "Konfliktní geometrie v barvě konfliktu", "prefs.sketch_conflict_colour_note": "Dokud jsou vazby náčrtu v konfliktu, vykreslují se v barvě konfliktu i křivky a body, které selhávající vazba drží, nejen její symbol nebo kóta. Vypnuto: ponechají si obvyklé barvy.", + "prefs.sketch_construction_lines": "Rozšířené nástroje konstrukčních přímek", "prefs.sketch_exit_view": "Po ukončení náčrtu", "prefs.sketch_exit_view.keep": "Ponechat aktuální pohled", "prefs.sketch_exit_view.previous": "Vrátit se k předchozímu pohledu", "prefs.sketch_exit_view.unless_rotated": "Vrátit, pokud nebyl pohled otočen", "prefs.sketch_exit_view_note": "Kam se pohled přesune po příkazu Dokončit náčrt, Zrušit nebo dvojitém Esc.", + "prefs.sketch_face_activates_part": "Náčrt na ploše dílu tento díl aktivuje", + "prefs.sketch_face_activates_part_note": "Náčrt zahájený na ploše tělesa jiné komponenty nejprve aktivuje tuto komponentu, takže jí náčrt patří a v prohlížeči zůstává u tohoto dílu. Díl zůstane aktivní i poté. Vypnuto: náčrt patří aktivní komponentě.", + "prefs.sketch_open_look_at": "Při otevření náčrtu natočit pohled k němu", + "prefs.sketch_open_look_at_note": "Vypnuto: vytvoření nebo úprava náčrtu ponechá pohled beze změny. Pohled kolmo natočí pohled k náčrtu, kdykoli ho chcete.", "prefs.sketch_recent_snap": "Automaticky přichytávat k nedávným středům a středním bodům", "prefs.sketch_recent_snap_note": "Při kreslení se kurzor přichytí tam, kde se kříží vodítka dvou posledních středů kružnic nebo středů rovných hran. Vypnuto: tato vodítka se jen zobrazují a kurzor se nepohne.", "prefs.sketch_selection": "Náčrt a výběr", "prefs.sketch_selection_heading": "Náčrt a výběr", "prefs.sketch_selection_note": "Jak se v náčrtu přichytává a jak kliknutí vybírá.", + "prefs.sketch_state_icons": "Ikony náčrtů v barvě jejich stavu", + "prefs.sketch_state_icons_note": "V Historii a v prohlížeči má ikona náčrtu barvu jeho stavu (nedourčený, plně zavazbený nebo v konfliktu) a její bublinová nápověda uvádí název stavu. Vypnuto: všechny náčrty mají stejnou ikonu.", "prefs.sketch_tab_always": "Vždy zobrazovat kartu Náčrt", "prefs.sketch_tab_always_note": "Karta Náčrt zůstává na pásu karet hned za kartou Model, i když není otevřený žádný náčrt. Její kreslicí nástroje pak zahájí náčrt na vybrané rovině nebo ploše, nebo na rovině, kterou vyberete jako další, a nástroj je v něm rovnou připraven.", "prefs.sketch_tracking_guides": "Vodítka zarovnání ke středům a středním bodům", "prefs.sketch_tracking_guides_note": "Najeďte na střed kružnice nebo střed rovné hrany a poté se pohybujte vodorovně nebo svisle, aby se zobrazilo dočasné tečkované vodítko.", + "prefs.sketch_tracking_points": "Vodítka zarovnání z koncových bodů a rohů při kreslení", + "prefs.sketch_tracking_points_note": "Když nástroj kreslení čeká na bod, najetí na konec úsečky nebo oblouku, roh obdélníku nebo volný bod ukáže stejné dočasné tečkované vodítko jako střed nebo střední bod. Vypnuto: jen středy a střední body.", "prefs.sketching": "Kreslení", "prefs.snap_drawing_note": "Při kreslení nebo přetahování bodu náčrtu.", "prefs.source": "Zdroj", "prefs.speed": "Rychlost", "prefs.stand_up_note": "Po otevření souboru STEP nebo IGES s osou Z nahoru nabídnout otočení o 90° kolem osy X.", + "prefs.stand_up_unknown": "U souborů z neznámých programů", + "prefs.stand_up_unknown.ask": "Zeptat se v dialogu", + "prefs.stand_up_unknown.note": "Zobrazit poznámku", + "prefs.stand_up_unknown.off": "Nenabízet", + "prefs.stand_up_unknown_note": "Jak se nabídka zobrazí, když hlavička souboru neuvádí žádný program, o kterém je známo, že ukládá s osou Y nahoru. Poznámka se zobrazí jen tehdy, když soubor vypadá, že leží na zádech; volba Zeptat se v dialogu se ptá u každého takového souboru, jako dříve.", "prefs.status_bar": "Stavový řádek", "prefs.status_bar_note": "Tenký pruh na dolním okraji okna ukazuje, co se právě upravuje, stav otevřeného náčrtu svou barvou a jednotky návrhu; kliknutím na jednotky je změníte. Stav náčrtu se pak již nezobrazuje v rohu pohledu.", "prefs.status_done": "Hotovo", "prefs.status_error": "Chyba", "prefs.status_selected": "Vybráno", "prefs.status_warning": "Varování", + "prefs.structure.appearance": "Vzhled", + "prefs.structure.appearance_note": "Barvy, text a usnadnění přístupu.", + "prefs.structure.in_profile": "V profilu", + "prefs.structure.layout": "Rozvržení", + "prefs.structure.layout_note": "Kde jsou umístěné části okna.", + "prefs.structure.look": "Zobrazení", + "prefs.structure.measure_pointer": "Měření a ukazatel", + "prefs.structure.mouse3d": "3D myš", + "prefs.structure.mouse3d_note": "SpaceMouse a SpaceNavigator.", + "prefs.structure.navigation_note": "Myš a touchpad. 3D myš má vlastní stránku.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Změněno od uložení", + "prefs.structure.profile_hover": "Uloženo v profilech nastavení", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Náčrt", + "prefs.structure.tools": "Nástroje", + "prefs.structure.tools_note": "Jak se chovají nástroje pro modelování.", + "prefs.structure.work": "Práce", "prefs.supersampling_brief": "Vykreslí pohled větší a pak jej zmenší s filtrováním: velmi ostré, ale náročnější.", "prefs.tab_accent_note": "Zvýrazňovací barva se řídí aktivní kartou", "prefs.theme_file": "soubor motivu", @@ -2012,6 +2424,16 @@ "prefs.theme_follow_off": "Vypnuto", "prefs.theme_follow_stop": "Ukončit sledování", "prefs.theme_import_hint": "Kliknutím vyberte soubor motivu, přetáhněte ho sem, nebo stiskněte Ctrl+V (na Macu Cmd+V) se zkopírovaným motivem", + "prefs.theme_option_opacity": "Neprůhlednost", + "prefs.theme_option_opacity_help": "Upravte neprůhlednost plovoucích panelů. Minimální čitelnost chrání text nad barvami pohledu.", + "prefs.theme_option_tab_colours": "Barvy karet", + "prefs.theme_option_tab_colours_help": "Použít pro každou kartu pásu karet barvy panelů a pohledu tohoto motivu.", + "prefs.theme_option_tab_fade_ms": "Přechod karet", + "prefs.theme_option_tab_fade_ms_help": "Prolnout barvy panelů a pohledu při přepínání karet. Nula přepíná okamžitě.", + "prefs.theme_options_badge": "Možnosti", + "prefs.theme_options_more": "Více · {count}", + "prefs.theme_options_reset": "Obnovit", + "prefs.theme_options_unavailable": "Na tomto zařízení nedostupné", "prefs.theme_paste": "Vložit motiv", "prefs.theme_paste_none": "Schránka neobsahuje žádný motiv SolidCraft", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2455,23 @@ "prefs.under_cursor": "Pod kurzorem", "prefs.units_precision": "Jednotky a přesnost", "prefs.updates": "Aktualizace", + "prefs.value_boxes_in_view": "Zobrazovat hodnoty vedle jejich úchytů v pohledu", + "prefs.value_boxes_in_view_tip": "Hodnota příkazu (Vzdálenost, Poloměr…) v rámečku vedle jeho úchytu nad modelem. Vypnuto: zadáváte ji v okně příkazu, které po výběru převezme klávesnici, a nic nezakrývá model.", "prefs.view": "Chování pohledu", "prefs.view_confirm_corner": "OK a Zrušit v rohu pohledu", "prefs.view_confirm_corner_note": "Když je otevřen dialog nebo náčrt, zaškrtnutí a křížek vpravo nahoře v pohledu provedou totéž co OK a Zrušit v dialogu, nebo náčrt dokončí a zruší. Navigátor pohledu se posune pod ně.", "prefs.viewport": "Zobrazovací okno", + "prefs.viewport_analysis_status": "Zobrazovat stav analýz nad pohledem", + "prefs.viewport_analysis_status_help": "Zobrazí aktivní analýzy nad pohledem, z každé položky otevře její legendu a klávesou Esc vypne nejnovější analýzu. Vypnutím obnovíte legendy v rozích a předchozí chování klávesy Esc.", "prefs.viewport_background": "Pozadí", "prefs.viewport_background_colour": "Barva", "prefs.viewport_background_theme": "Přechod motivu", + "prefs.viewport_section_status": "Zobrazovat stav řezu v pohledu", + "prefs.viewport_section_status_help": "Zobrazí nastavení řezu v pohledu. Escape a aktivní tlačítko na pásu karet ho vypnou. Vypnutím zůstanou dosavadní ovládací prvky řezu.", + "prefs.viewport_status_details": "Živé podrobnosti pohledu", + "prefs.viewport_status_details_help": "Upravujte nastavení aktivní analýzy a řezu ve standardních kartách podrobností. Vypnutím obnovíte klávesy analýzy jen pro čtení a dialog Řez.", + "prefs.viewport_status_summary": "Sbalit stavové položky pohledu", + "prefs.viewport_status_summary_help": "Sbalí tři nebo více stavových položek pohledu do jednoho souhrnného štítku. Vypnutím zůstanou všechny položky v plné řadě.", "prefs.wheel": "Kolečko", "prefs.wheel_trackpad": "Kolečko a trackpad", "prefs.workspace": "Pracovní prostředí", @@ -2049,6 +2481,10 @@ "properties.title": "Vlastnosti: {name}", "recovery.days_ago": "před {count} dny", "recovery.detail": "{file} · prvků: {features} · automaticky uloženo {when}", + "recovery.discard_all": "Zahodit vše", + "recovery.discard_all_detail": "Tuto akci nelze vrátit zpět.", + "recovery.discard_all_title": "Zahodit automatická uložení: {count}?", + "recovery.discard_all_title_one": "Zahodit 1 automatické uložení?", "recovery.hours_ago": "před {count} h", "recovery.just_now": "právě teď", "recovery.min_ago": "před {count} min", @@ -2164,6 +2600,10 @@ "render.base_color": "Základní barva · sRGB", "render.base_metallic": "Kovový podíl", "render.base_opaque_only": "Tento editor zachovává sémantiku neprůhledných těles. Pro optický průchod světla použijte samostatné ovládací prvky skla.", + "render.batch_all_shots": "Všechny záběry ({count})", + "render.batch_empty": "Před renderováním všech záběrů nejprve uložte záběr.", + "render.batch_limit": "Renderování všech záběrů je omezeno na 32 záběrů.", + "render.batch_status": "Probíhá: {running} · Čeká: {waiting}", "render.bloom_enable": "Záře ve výstupu", "render.bloom_help": "Kreativní záře z lineárních jasů se třemi normalizovanými průchody. Poloměr v pixelech výstupu, přičtení před sRGB. Nejde o simulaci čočky, objemu ani zlepšení konvergence. Surové EXR se nemění.", "render.bloom_opaque": "Záře vyžaduje neprůhledný výstup. Průhledné PNG se odmítne, neprovede se skryté sloučení.", @@ -2274,6 +2714,13 @@ "render.choose_look": "Nejprve vyberte styl ve Vzhledech", "render.chromatic_offset": "Chromatický posun hran", "render.clear_stage": "Odebrat uloženou scénografii", + "render.compare_divider": "Dělicí čára porovnání", + "render.compare_live": "Živě", + "render.compare_live_preview": "Živý náhled", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · zachyceno ve revizi {revision}", + "render.compare_swap": "Prohodit", "render.copy_request": "Kopírovat JSON", "render.cpu_aa_help": "Prostorové vzorky: více vzorků zlepší hrany a prodlouží vykreslení.", "render.cpu_area_add": "Přidat obdélníkové světlo CPU", @@ -2914,7 +3361,9 @@ "render.output_ready": "Připraveno k vykreslení", "render.output_run_check": "Spustit kontrolu", "render.output_size_limit": "{method}: nejvýše {dimension} px na stranu a {pixels} pixelů. Největší vyhovující velikost: {width} × {height}.", + "render.output_size_method_profile": "Pro vykreslení {width} × {height} zvolte {method} s profilem prostředků CPU {profile}, nebo menší velikost.", "render.output_size_ok": "Velikost je v pořádku · {width} × {height} px", + "render.output_size_profile": "Pro vykreslení {width} × {height} zvolte profil prostředků CPU {profile}, nebo menší velikost.", "render.output_swap_orientation": "Prohodit šířku a výšku", "render.output_tools_inspector": "Velikost a formát upravte v inspektoru Výstup.", "render.output_view_image": "Zobrazit obrázek", @@ -3021,6 +3470,10 @@ "render.result_retained": "Zobrazuje se poslední hotový obrázek; novější vykreslení jej zatím nenahradilo.", "render.result_sequence": "Kontrolní bod", "render.result_title": "Výsledek vykreslení", + "render.results_choose": "Ponechané výsledky", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [zastaralý]", + "render.results_unnamed": "Obrázek", "render.return_design": "Zpět k návrhu", "render.review_stale": "Tato kontrola je zastaralá. Před použitím ji vyřešte nebo proveďte znovu.", "render.ribbon_aging": "Stárnutí", @@ -3127,6 +3580,7 @@ "render.size_custom": "Vlastní…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · vyžaduje {profile}", "render.size_presets": "Předvolby velikosti", "render.size_presets_pending": "Přijde s editorem Výstup", "render.size_preview": "Náhled", @@ -3414,6 +3868,24 @@ "sheet.flange_type_contour": "Kontura", "sheet.flange_type_edge": "Hrana", "sheet.no_body": "není žádné plechové těleso: začněte příkazem Příruba > Základ, nebo změňte desku na plech příkazem Převést na plech (vyberte její velkou rovnou plochu)", + "sheet.personal_rules.confirm_delete": "Potvrdit smazání", + "sheet.personal_rules.delete": "Smazat", + "sheet.personal_rules.delete_prompt": "Smazat toto osobní pravidlo? Pravidla, která už jsou v návrzích, se nezmění.", + "sheet.personal_rules.full": "Osobní knihovna už obsahuje 64 pravidel.", + "sheet.personal_rules.invalid_name": "Zadejte krátký název bez zalomení řádků a řídicích znaků.", + "sheet.personal_rules.invalid_values": "Doplňte hodnoty pravidla: všechny se musí v tomto návrhu dát vypočítat, tloušťka musí být kladná a K-faktor od 0 do 1.", + "sheet.personal_rules.missing": "Vybrané osobní pravidlo už není k dispozici.", + "sheet.personal_rules.name": "Název pravidla", + "sheet.personal_rules.name_exists": "Osobní pravidlo s tímto názvem už existuje. Použijte jiný název.", + "sheet.personal_rules.name_hint": "Jedinečný název", + "sheet.personal_rules.overwrite": "Uložit změny do vybraného osobního pravidla", + "sheet.personal_rules.rename": "Přejmenovat", + "sheet.personal_rules.rule": "Osobní pravidlo", + "sheet.personal_rules.save": "Uložit jako nové", + "sheet.personal_rules.scope": "Uloženo ve vašem profilu pro všechny návrhy.", + "sheet.personal_rules.select": "Vyberte pravidlo", + "sheet.personal_rules.title": "Osobní pravidla", + "sheet.personal_rules.unsupported": "Toto pravidlo má hodnoty, které tato verze nedokáže použít.", "shortcut.json_error": "parametry musí být ve formátu JSON: {error}", "shortcut.no_command": "příkaz `{id}` neexistuje; text před JSON musí být ID příkazu", "shortcut.pin": "Připnout nahoru do pole S", @@ -3450,8 +3922,10 @@ "sketch_text.align_right": "Vpravo", "sketch_text.bold": "Tučné", "sketch_text.builtin_font": "{family} (vestavěné)", + "sketch_text.formula": "Začněte znakem = a sestavte slova z parametrů: ='W' + number(Width)", "sketch_text.italic": "Kurzíva", "sketch_text.loading_fonts": "Hledání nainstalovaných písem…", + "sketch_text.no_bold": "Vestavěné písmo nemá tučný řez: zvolte nainstalované písmo", "sketch_text.on_path": "Text sleduje svou cestu: umístění určuje křivka", "sketch_text.path_clear": "Odpojit text od křivky", "sketch_text.path_hint": "Křivka náčrtu, kterou text sleduje: klikněte sem a poté na křivku", @@ -3483,10 +3957,7 @@ "the two origins are on the same component": "oba počátky jsou na téže komponentě", "thread.automatic_size": "Automatická velikost", "thread.designation": "Označení", - "thread.direction": "Směr závitu", "thread.iso_metric": "Metrický ISO", - "thread.left_hand": "Levotočivý", - "thread.right_hand": "Pravotočivý", "thread.select_size": "Vybrat velikost", "timeline.delete_after_marker_one": "Smazat 1 prvek za značkou historie", "timeline.delete_after_marker_other": "Smazat prvky za značkou historie: {count}", @@ -3503,8 +3974,10 @@ "timeline.move_to_group": "Přesunout prvky do složky", "timeline.rename_group": "Přejmenovat složku prvků", "timeline.reorder_many": "Změnit pořadí prvků", + "timeline.suppress_features": "Potlačit prvky", "timeline.suppress_folders_tip": "Potlačí nebo zruší potlačení všech prvků ve složkách a v jejich vnořených složkách", "timeline.ungroup": "Odebrat složky prvků", + "timeline.unsuppress_features": "Zrušit potlačení prvků", "to the face": "k ploše", "to the next face": "k další ploše", "toolbar.customize_note": "Karta {tab}. Zaškrtnutím příkazu přidáte jeho tlačítko na panel nástrojů. Můžete také přetáhnout řádek z rozbalovací nabídky panelu na panel nástrojů, odstranit tlačítko přetažením mimo panel nástrojů nebo použít připínáček na řádku rozbalovací nabídky.", @@ -3588,6 +4061,8 @@ "ui.3d_mouse_section": "3D myš", "ui.3d_mouse_show_in_view": "Zobrazit 3D myš ve 3D pohledu", "ui.3d_mouse_show_in_view_tip": "Obrázek vaší 3D myši v levém dolním rohu, který se hýbe s ní.", + "ui.3d_mouse_sketch_orbit": "Otáčet náčrty 3D myší", + "ui.3d_mouse_sketch_orbit_tip": "3D myš otáčí pohled i při otevřeném náčrtu, na který se díváte zpříma, stejně jako to umí myš. Vypnuto: náčrt posouvá a přibližuje, dokud pohled nenakloníte.", "ui.3d_mouse_skip": "Moje zařízení to neumí", "ui.3d_mouse_skip_tip": "Přeskočí tento pohyb v obou směrech a kalibrace ho vynechá.", "ui.3d_mouse_speed": "Rychlost 3D myši", @@ -3616,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Otočte hlavici proti směru hodinových ručiček, podržte a pusťte.", "ui.3d_mouse_switch_cap": "Kalibrovat jako návrat do středu", "ui.3d_mouse_switch_trackball": "Kalibrovat jako trackball", + "ui.3d_mouse_use_direct": "Použít přímý ovladač", + "ui.3d_mouse_use_direct_tip": "Číst 3D myš přímo (hidraw) místo přes spacenavd.", "ui.3d_mouse_view_axis": "Osa pohledu", "ui.3d_mouse_view_off": "Vypnuto", "ui.3d_mouse_view_off_tip": "Profil ovladače 3D myši tuto osu vypíná, takže její pohyb s pohledem nehýbe. Když tu vyberete pohyb jiné osy, prohodí se s ní a s pohledem přestane hýbat.", @@ -3654,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Spusťte toto v terminálu a pak znovu stiskněte Připojit:", "ui.agent_chat_auth_title": "Přihlásit se k agentovi", "ui.agent_chat_cancel": "Zrušit", + "ui.agent_chat_cancel_timeout": "Agent na Zastavit neodpověděl a byl odpojen. Pro pokračování se připojte znovu.", + "ui.agent_chat_cannot_start": "Nainstalováno, ale nespouští se: {error}", "ui.agent_chat_changes": "Změny: {n}, jeden krok zpět", "ui.agent_chat_changes_n": "Změn: {n}", "ui.agent_chat_changes_of": "Změny: {n}/{limit}", @@ -3662,11 +4141,13 @@ "ui.agent_chat_command": "Příkaz agenta", "ui.agent_chat_connect": "Připojit", "ui.agent_chat_copy": "Kopírovat", + "ui.agent_chat_copy_message": "Kopírovat zprávu", "ui.agent_chat_ctx_bodies": "Tělesa", "ui.agent_chat_ctx_elements": "Elementy", "ui.agent_chat_ctx_features": "Prvky", "ui.agent_chat_ctx_more": "+{n} dalších", "ui.agent_chat_ctx_other": "Jiné", + "ui.agent_chat_custom_heading": "Vlastní model", "ui.agent_chat_custom_hint": "Jakýkoli program, který komunikuje protokolem Agent Client Protocol přes stdin a stdout. Nespouští se přes shell.", "ui.agent_chat_denied": "Zamítnuto", "ui.agent_chat_deny": "Zamítnout", @@ -3710,8 +4191,16 @@ "ui.agent_chat_mode_all": "Vše", "ui.agent_chat_mode_ask": "Ptát se", "ui.agent_chat_mode_edits": "Úpravy", + "ui.agent_chat_model_custom": "Použít vlastní: {model}", "ui.agent_chat_model_no_tools": "{model} nemůže používat nástroje SolidCraftu, takže umí jen chatovat. Vyberte model s podporou nástrojů.", + "ui.agent_chat_model_rejected": "Agent nepřijal model {model}: {error}", + "ui.agent_chat_model_search": "Hledat modely…", "ui.agent_chat_model_tip": "Model, který agent používá. Vaše volba se pro tohoto agenta zapamatuje.", + "ui.agent_chat_models_failed": "Seznam modelů se nepodařilo načíst: {error}", + "ui.agent_chat_models_heading": "Dostupné modely", + "ui.agent_chat_models_listing": "Načítání seznamu modelů…", + "ui.agent_chat_models_none": "Endpoint neuvádí žádné modely", + "ui.agent_chat_models_not_a_list": "Odpověď nebyla seznam modelů", "ui.agent_chat_new": "Nový chat", "ui.agent_chat_new_confirm": "Začít nový chat? Aktuální bude vymazán.", "ui.agent_chat_next_picture": "Další obrázek", @@ -3746,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "Ve frontě (zastaveno, neodesláno)", "ui.agent_chat_refresh": "Obnovit", "ui.agent_chat_refused": "Pro agenta nepovoleno: {reason}", + "ui.agent_chat_reinstall": "{agent} je nainstalován ({program}), ale při kontrole SolidCraftu se nespustil: {error}\nJeho instalace může být neúplná nebo vytvořená pro jiný typ počítače. Nainstalujte jej znovu příkazem `{install}`, ověřte v terminálu, že vypíše svou verzi, a pak stiskněte Obnovit.", "ui.agent_chat_remove": "Odebrat z fronty", "ui.agent_chat_remove_file": "Odebrat z této zprávy", "ui.agent_chat_remove_imported": "Odebrat z této zprávy; díl zůstane v návrhu (Zpět jej odstraní)", + "ui.agent_chat_reply_cut_off": "Odpověď dosáhla limitu délky dříve, než skončila, takže může být neúplná. Požádejte agenta, aby pokračoval, nebo o kratší odpověď.", + "ui.agent_chat_reply_declined": "Model odmítl na tuto zprávu odpovědět.", "ui.agent_chat_retry": "Zkusit znovu", "ui.agent_chat_right": "Vpravo", "ui.agent_chat_save": "Uložit", @@ -3807,12 +4299,17 @@ "ui.ai_copy_suffix": "kopie", "ui.ai_custom_url": "Vlastní URL", "ui.ai_default": "Výchozí", + "ui.ai_edit": "Upravit", + "ui.ai_edit_agent_title": "Upravit agenta", + "ui.ai_edit_gone": "Tento agent byl odebrán, takže není co ukládat.", + "ui.ai_edit_tip": "Změní název, příkaz nebo endpoint tohoto agenta. Uložený klíč zůstane skrytý.", "ui.ai_http_busy": "endpoint je zaneprázdněný nebo překročil limit; zkuste to později", "ui.ai_http_key": "endpoint odmítl klíč: zkontrolujte jej v Předvolby > AI", "ui.ai_http_not_found": "takový endpoint nebo model neexistuje: zkontrolujte základní URL a název modelu", "ui.ai_http_too_large": "konverzace je pro tento endpoint příliš velká; začněte nový chat", "ui.ai_key": "API klíč", "ui.ai_key_hint": "volitelné; uloženo v systémové klíčence", + "ui.ai_key_keep_hint": "nechte prázdné, aby se zachoval uložený klíč", "ui.ai_key_needs_https": "Klíč se odesílá pouze přes HTTPS nebo na tento počítač.", "ui.ai_key_note": "Ukládá se v systémové klíčence, nikdy v nastavení SolidCraftu. Pro místní server nechte prázdné.", "ui.ai_keychain_error": "Systémová klíčenka odmítla: {error}", @@ -3839,11 +4336,15 @@ "ui.ai_permissions": "Oprávnění", "ui.ai_preset": "Předvolba", "ui.ai_protocol": "Protokol", + "ui.ai_reasoning_effort": "Úroveň uvažování", + "ui.ai_reasoning_effort_field_hint": "prázdné = výchozí hodnota poskytovatele", + "ui.ai_reasoning_effort_hint": "Volitelné. Odesílá se na endpoint jako `reasoning_effort`; přípustné hodnoty se u jednotlivých poskytovatelů liší (například `low`, `high` nebo `max`). Hodnotu, kterou zde nastavíte, SolidCraft nikdy nenahradí. Ponechte prázdné, aby se nic neodeslalo a zůstala výchozí hodnota poskytovatele.", "ui.ai_remove": "Odebrat", "ui.ai_request_timed_out": "Model odpovídal déle než {seconds} s. Časový limit požadavku pro tento endpoint můžete zvýšit v Předvolbách › Asistent.", "ui.ai_request_timeout": "Časový limit požadavku", "ui.ai_request_timeout_hint": "Jak dlouho smí trvat jeden požadavek na model tohoto endpointu, od 30 s do hodiny. U pomalého místního modelu jej zvyšte.", "ui.ai_reset": "Obnovit", + "ui.ai_save": "Uložit", "ui.ai_settings": "Nastavení AI…", "ui.ai_show_features": "Zobrazit funkce AI", "ui.ai_show_features_note": "Chat s agentem: panel, ve kterém na otevřeném návrhu pracuje kódovací agent, kterého již používáte, nebo model na zvoleném endpointu. Vypnuto: žádné tlačítko AI, zkratka, položka nabídky ani panel a nic se nehledá ani nespouští.", @@ -3922,6 +4423,8 @@ "ui.cancel": "Zrušit", "ui.canvases": "Plátna", "ui.center": "Střed", + "ui.center_arc_follows_cursor": "Oblouk ze středu sleduje směr kurzoru", + "ui.center_arc_follows_cursor_tip": "Oblouk ze středu se kreslí po směru nebo proti směru hodinových ručiček podle toho, jak kurzor obíhá jeho střed. Vypnuto: vždy proti směru hodinových ručiček od začátku.", "ui.centerline": "Osa", "ui.chain": "Řetězec", "ui.chamfer": "Sražení", @@ -3930,6 +4433,7 @@ "ui.circle": "Kružnice", "ui.circular_pattern": "Kruhové pole", "ui.clear": "Vymazat", + "ui.clear_print_face": "Zrušit tiskovou plochu", "ui.clear_recent": "Vymazat nedávné", "ui.clear_the_selection": "Zrušit výběr", "ui.click_selects_whole_bodies": "Kliknutí vybírá celá tělesa", @@ -3964,12 +4468,27 @@ "ui.constant": "Konstantní", "ui.constraints_conflict": "Konflikt vazeb", "ui.construction": "Konstrukční", + "ui.construction.angle_hint": "Konstrukční přímka: klikněte na bod, pak zadejte úhel nebo vyberte směr", + "ui.construction.bisector_hint": "Osa úhlu: vyberte dvě protínající se přímky, pak požadované řešení", + "ui.construction.common_hint": "Společná tečna: vyberte dvě kružnice/oblouky, pak požadované řešení", + "ui.construction.contact_hint": "Tečna: vyberte kružnici/oblouk nebo otevřený splajn/kuželosečku, pak bod dotyku (volné křivky: koncové body)", + "ui.construction.external_hint": "Tečna: vyberte kružnici nebo oblouk, vnější bod, pak požadované řešení", + "ui.construction.free_hint": "Konstrukční přímka: klikněte na dva body; pravým tlačítkem začnete znovu", + "ui.construction.normal_needs_length": "Nekonečná přímka je vždy konstrukční: zadejte délku, abyste nakreslili běžnou úsečku", + "ui.construction.point_hint": "Konstrukční přímka: klikněte na bod, kterým má procházet", + "ui.construction.reference_hint": "Konstrukční přímka: vyberte přímku, pak bod; pravým tlačítkem změníte referenci", "ui.construction.ribbon_label": "Pom. přímky", + "ui.construction.side_hint": "Konstrukční přímka: klikněte na stranu, kterým směrem přímka vede; pravým tlačítkem začnete znovu", "ui.context_menu": "Místní nabídka", + "ui.continuity_crease": "Hrana", + "ui.continuity_curvature": "Křivost", + "ui.continuity_curvature_change": "Změna křivosti", "ui.continuity_g0": "G0 hrana", "ui.continuity_g1": "G1 tečně", "ui.continuity_g2": "G2 křivost", "ui.continuity_gap": "Mezera", + "ui.continuity_position": "Poloha", + "ui.continuity_tangent": "Tečnost", "ui.copy": "Kopírovat", "ui.corner": "Roh", "ui.corners": "Rohy", @@ -3992,6 +4511,7 @@ "ui.dark": "Tmavý", "ui.default_modelling_orientation": "Výchozí orientace modelování", "ui.delete": "Smazat", + "ui.delete_select_first": "Nejprve vyberte, co smazat: prvky, tělesa, komponenty nebo geometrii náčrtu", "ui.depth": "Hloubka", "ui.design": "Návrh", "ui.design_properties.author": "Autor", @@ -4006,6 +4526,40 @@ "ui.design_properties.project": "Projekt", "ui.design_properties.revision": "Revize", "ui.design_saved": "Uloženo do {path}", + "ui.details_access_caption": "Plochy ukazují, zda se k nim nástroj dostane ze zvoleného směru.", + "ui.details_angle": "Úhel", + "ui.details_continuity_caption": "Upravte vybraný spoj. Ostatní spoje si ponechají svá nastavení.", + "ui.details_continuity_stale": "Dřívější geometrie: spusťte analýzu znovu, abyste mohli tento spoj upravit nebo zarámovat.", + "ui.details_copy_list": "Kopírovat seznam", + "ui.details_curvature": "Tolerance křivosti", + "ui.details_curvature_caption": "Plochy se barví podle místního poloměru křivosti.", + "ui.details_direction": "Směr nástroje", + "ui.details_draft_caption": "Plochy se barví podle úhlu ke směru vyjímání.", + "ui.details_edit_seam": "Upravit spoj", + "ui.details_fixture": "Ukázková komponenta — pouze vzorová data", + "ui.details_fixture_caption": "Ukázková komponenta s ilustračními hodnotami; nejde o výsledek modelu.", + "ui.details_fixture_problem": "Příklad nálezu s problémem", + "ui.details_fixture_readout": "Příklad naměřené hodnoty", + "ui.details_flip": "Převrátit", + "ui.details_gap": "Mezera", + "ui.details_hatch": "Šrafovat řezné plochy", + "ui.details_jump": "Skok křivosti", + "ui.details_key": "Legenda", + "ui.details_offset": "Odsazení", + "ui.details_plane": "Rovina", + "ui.details_pull": "Směr vyjímání", + "ui.details_radius": "Poloměr", + "ui.details_readout": "Odečet", + "ui.details_samples": "Vzorky", + "ui.details_seam": "{body} · Hrana {edge}", + "ui.details_settings": "Nastavení", + "ui.details_sharp_gap": "Zlom nebo mezera", + "ui.details_show_all": "Zobrazit všechny ({count})", + "ui.details_smooth": "Hladký", + "ui.details_stripes": "Pruhy", + "ui.details_target": "Zarámovat geometrii", + "ui.details_worst_seams": "Nejhorší spoje", + "ui.details_zebra_caption": "Odražené pruhy ukazují, jak hladce plochy navazují.", "ui.diameter": "Průměr", "ui.dimension": "Kóta", "ui.direct_interaction": "Přímá interakce", @@ -4050,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "Díl byl uložen do jiného souboru; sestava stále odkazuje na {name}", "ui.edit_in_place_wait": "Počkejte, až skončí to, co v návrhu běží", "ui.edit_section_analysis": "Upravit analýzu řezu", + "ui.edit_sketch_empty": "Žádné náčrty k úpravě", "ui.ellipse": "Elipsa", "ui.emboss_wrap_note": "Profily z navzájem kolmých úseček, tečné k jednomu podporovanému válci, se obalí automaticky. Cíl zvolíte výběrem stěny.", "ui.end_radius": "Koncový poloměr", @@ -4060,12 +4615,15 @@ "ui.equation_explicit": "Explicitní", "ui.equation_form": "Tvar", "ui.equation_note": "Proměnná je prosté číslo: sin(t) ji bere v radiánech. Výsledek bez jednotky je v jednotce návrhu.", + "ui.equation_note_range": "Proměnná je délka, stejně jako její rozsah: kombinujte ji s parametry délky a pro sin() ji vydělte délkou. Výsledek bez jednotky je v jednotce návrhu.", "ui.equation_parametric": "Parametrický", + "ui.equation_variable_unit": "Proměnná má jednotku rozsahu", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Ekvivalentní poloměr", "ui.expand": "Rozbalit", + "ui.explode_needs_two_components": "Rozložený pohled odtahuje komponenty od sebe, takže návrh potřebuje dvě nebo více komponent (Nová komponenta, Vložit návrh nebo Vytvořit komponenty z těles)", "ui.exportDxf": "Exportovat DXF…", "ui.export_ellipsis_keymap": "Exportovat…", "ui.export_keymap_tip": "Klávesy, oblíbené z vyhledávání S a panel nástrojů jako soubor", @@ -4191,6 +4749,7 @@ "ui.hideOrigin": "Skrýt počátek", "ui.hidePlanes": "Skrýt roviny", "ui.hideProfile": "Skrýt profil", + "ui.hide_component_history": "Skrýt její historii", "ui.hide_origin_by_default": "Ve výchozím stavu skrýt počátek", "ui.hide_origin_note": "Nové návrhy začínají se skrytou složkou Počátek. Návrh si ponechá vlastní nastavení počátku, jakmile ho zobrazíte nebo skryjete.", "ui.history_back": "O krok zpět", @@ -4198,6 +4757,7 @@ "ui.history_edge_hint": "dvakrát klikněte na hranu", "ui.history_first": "Přejít na začátek", "ui.history_forward": "O krok vpřed", + "ui.history_hide_hidden": "Skrýt skryté komponenty", "ui.history_hide_names": "Skrýt názvy", "ui.history_last": "Přejít na konec", "ui.history_marker_tip": "Značka historie: přetažením vrátíte model zpět; nové prvky se vkládají sem", @@ -4207,10 +4767,12 @@ "ui.history_play_button_show": "Zobrazit tlačítko Přehrát", "ui.history_play_finish_action": "Před přehráním historie dokončete aktuální akci", "ui.history_play_roll_back": "Před přehráním posuňte značku historie zpět", + "ui.history_show_hidden": "Zobrazit skryté komponenty", "ui.history_show_names": "Zobrazit názvy", "ui.history_sketch_listed_under": "Uvedeno pod prvkem {feature}", "ui.history_title": "Historie", "ui.history_toggle_names": "Zobrazit nebo skrýt názvy prvků", + "ui.history_waits_for_editor": "Zpět, Znovu a Historie počkají, dokud se neotevře editor prvku", "ui.hole": "Otvor", "ui.hole_tap_type": "Typ závitu otvoru", "ui.hole_type": "Typ otvoru", @@ -4226,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} obsahuje neuložené změny, proto byl vložen jeho uložený soubor. Uložte jej a pak použijte Aktualizovat odkazy, aby se změny převzaly.", "ui.insert_design.unsaved": "Neuložené změny", "ui.inspect": "Analýza", + "ui.instances": "Instance", "ui.intersect": "Průnik", "ui.isolate": "Izolovat", "ui.join": "Sjednotit", @@ -4234,12 +4797,14 @@ "ui.joints": "Klouby", "ui.keyboard_shortcuts": "Klávesové zkratky", "ui.language": "Jazyk", + "ui.lasso_select": "Laso (tažením nakreslete volnou smyčku: vybere vše, co leží celé uvnitř)", "ui.layout_compact": "Kompaktní", "ui.layout_floating": "Plovoucí", "ui.length": "Délka", "ui.length_decimals": "Desetinná místa délky", "ui.light": "Světlý", "ui.line": "Úsečka", + "ui.line_arc_hint": "Tečný oblouk: klikněte na konec oblouku. Znovu setrvejte na posledním bodu pro úsečky; dokončíte pravým kliknutím nebo klávesou Esc", "ui.link_copies": "Propojit shodné kopie", "ui.link_copies_keep": "Ponechat", "ui.link_copies_link": "Propojit", @@ -4328,6 +4893,7 @@ "ui.part_size_shared": "Přestaví díl a nahradí všechny přidané prvky. Aktualizují se všechny výskyty této komponenty.", "ui.paste": "Vložit", "ui.path": "Cesta", + "ui.pattern_object_type_tip": "Tělesa: pevné tvary vybrané v pohledu nebo v prohlížeči; každé se zkopíruje celé.\nPrvky: kroky Historie, například vysunutí nebo otvor, vybrané v Historii nebo na ploše, kterou vytvořily; krok se zopakuje.\nNáčrt není ani jedno: opakujte jeho křivky vlastním nástrojem Pole nebo Zrcadlit v náčrtu, nebo jej nejprve vysuňte.", "ui.pattern_on_path": "Pole po cestě", "ui.perforate_margin_default": "z průměru", "ui.perforate_pitch": "Rozteč", @@ -4354,12 +4920,17 @@ "ui.plugins_skipped": "Složek, které nešlo přečíst: {count}.", "ui.plugins_version": "{version}", "ui.point": "Bod", + "ui.point_cloud_add_filter": "Přidat filtr…", "ui.point_cloud_auto_range": "Automatický rozsah", "ui.point_cloud_color_by": "Barva podle", "ui.point_cloud_file_colors": "Barvy ze souboru", + "ui.point_cloud_filter_by": "Filtrovat podle", "ui.point_cloud_height_high": "Nejvyšší", "ui.point_cloud_height_low": "Nejnižší", + "ui.point_cloud_legend_filter": "Zobrazeno a skryto v legendě výše", "ui.point_cloud_no_file_colors": "Soubor neobsahuje žádné barvy", + "ui.point_cloud_pause": "Pozastavit", + "ui.point_cloud_play": "Přehrát", "ui.point_cloud_single_color": "Jedna barva", "ui.point_cloud_size": "Velikost bodů", "ui.point_cloud_units": "Jednotky souboru", @@ -4368,6 +4939,11 @@ "ui.polygon": "Mnohoúhelník", "ui.preferences": "Předvolby", "ui.press_a_key": "stiskněte klávesu…", + "ui.print_face_body_not_sent": "Těleso této plochy se neodesílá: nejprve ho přidejte do Tělesa", + "ui.print_face_cleared": "{body}: tisková plocha zrušena", + "ui.print_face_input": "Tisková plocha", + "ui.print_face_pick": "Vyberte rovinnou plochu objemového tělesa, aby se stala tiskovou plochou", + "ui.print_face_set": "{body}: tisková plocha nastavena; Odeslat do sliceru položí těleso na ni", "ui.profile": "Profil", "ui.profile_plane": "Rovina profilu", "ui.profiles": "Profily", @@ -4383,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Měření…", + "ui.properties.measuring_bodies": "Měření… {done} z {total} těles", "ui.properties.measuring_failed": "Měření se zastavilo před dokončením.", "ui.properties.principal_axis": "Hlavní osa {number}", "ui.properties.principal_moments": "Hlavní momenty setrvačnosti", @@ -4431,6 +5008,7 @@ "ui.revolve": "Rotace", "ui.ribbon_exit": "Ukončit", "ui.ribbon_labels": "Zobrazovat text pod ikonami pásu karet", + "ui.ribbon_menus_skip_pinned": "Vynechat připnuté příkazy v rozbalovacích nabídkách", "ui.ribbon_pin_footer": "Připnuté příkazy se zobrazují na pásu karet. Najetím na řádek jej připnete nebo odepnete.", "ui.ribbon_workspace": "Pracovní prostředí", "ui.right": "Zprava", @@ -4449,6 +5027,7 @@ "ui.selectOther": "Vybrat jiné…", "ui.selectTangentChain": "Vybrat tečný řetězec", "ui.select_all": "Vybrat vše", + "ui.select_components_by_face": "Vybírat komponenty (plocha vybere svou komponentu)", "ui.selection": "Výběr", "ui.selection_modifiers": "Modifikátory výběru", "ui.selection_shift_add_only": "Shift+klik pouze přidává", @@ -4474,6 +5053,7 @@ "ui.showDimension": "Zobrazit kótu", "ui.showOrigin": "Zobrazit počátek", "ui.showPlanes": "Zobrazit roviny", + "ui.show_component_history": "Zobrazit její historii", "ui.show_constraints": "Vazby", "ui.show_construction_geometries": "Konstrukční geometrie", "ui.show_dimensions": "Kóty", @@ -4490,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Filtr výběru", "ui.sketch_modifiers": "Modifikátory náčrtu", "ui.sketch_project_geometry": "Geometrie", + "ui.sketch_report.all_constrained": "Vše je plně zavazbeno.", + "ui.sketch_report.dof": "Stupně volnosti", + "ui.sketch_report.loose": "Není plně zavazbeno", + "ui.sketch_report.status": "Stav", + "ui.sketch_report.title": "Zpráva o náčrtu", "ui.sketch_scale": "Měřítko náčrtu", "ui.sketches": "Náčrty", "ui.slice": "Řez", @@ -4585,19 +5170,31 @@ "ui.view_angles": "Úhly pohledu", "ui.view_angles_convention": "Úhly ve stupních kolem svislé osy. Stáčení 0° je pohled zepředu, 90° zleva, −90° zprava, 180° zezadu; náklon 90° je pohled shora; kladné natočení otáčí model ve směru hodinových ručiček.", "ui.view_angles_help": "Zobrazuje náklon, stáčení a natočení pohledu ve stupních a jeho projekci pod orientačním ovladačem. Kliknutím na údaj zadáte přesné úhly.", + "ui.view_angles_lock": "Zamknout {axis}", "ui.view_angles_ortho": "Orto", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Náklon", "ui.view_angles_readout": "Náklon {pitch} · Stáčení {yaw} · Natočení {roll}", "ui.view_angles_roll": "Natočení", + "ui.view_angles_unlock": "Odemknout {axis}", "ui.view_angles_yaw": "Stáčení", + "ui.view_angles_zero": "Nastavit {axis} na 0°", "ui.view_centre": "Střed pohledu", "ui.viewport_status_clear": "Vypnout {name}", "ui.viewport_status_clear_hint": "Vypnout {name} · Esc", + "ui.viewport_status_edges": "Hrany: {count}", + "ui.viewport_status_from": "ze směru {direction}", "ui.viewport_status_key": "Zobrazit legendu pro {name}", "ui.viewport_status_minimum_radius": "Minimální poloměr", "ui.viewport_status_pairs": "Dvojice: {count}", + "ui.viewport_status_section_hatch": "{setting} · šrafování", + "ui.viewport_status_section_plane": "Aktuální rovina", + "ui.viewport_status_section_tilted": "nakloněno · {offset}", "ui.viewport_status_stripes": "Pruhy: {count}", + "ui.viewport_status_summary_clear": "Vypnout vše", + "ui.viewport_status_summary_heading": "V tomto pohledu", + "ui.viewport_status_summary_label": "{name} a další položky: {count}", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Podle motivu", "ui.visual_shaded_hidden_edges": "Stínovaný se skrytými hranami", "ui.visual_shaded_with_edges": "Stínovaný s hranami", @@ -4634,10 +5231,12 @@ "update.button": "Aktualizovat", "update.button_version": "Aktualizovat na {version}", "update.check_automatically": "Automaticky kontrolovat aktualizace", + "update.check_for_updates": "Zkontrolovat aktualizace", "update.check_now": "Zkontrolovat nyní", + "update.check_unavailable": "Pro tuto instalaci není kontrola aktualizací dostupná.", "update.checking": "Kontrola…", "update.copy": "Kopírovat", - "update.dmg_opened": "Obraz disku je otevřený a ověřený: přetáhněte SolidCraft do Aplikací místo staré kopie a poté SolidCraft restartujte.", + "update.dmg_opened": "Obraz disku je otevřený a ověřený: ukončete SolidCraft, přetáhněte nový SolidCraft do Aplikací místo staré kopie a poté SolidCraft znovu otevřete.", "update.download": "Stáhnout", "update.download_open": "Stáhnout a otevřít", "update.downloading": "Stahování a ověřování… {done} z {total} MB", @@ -4648,11 +5247,13 @@ "update.installed": "SolidCraft {version} je nainstalován. Pro použití restartujte.", "update.installer_started": "Instalátor se spustí po zavření SolidCraftu.", "update.later": "Připomenout později", + "update.managed": "K dispozici je aktualizace: aktualizujte SolidCraft v {manager}", "update.no_notes": "Tato verze nemá poznámky.", "update.package_hint": "Tato kopie pochází z {kind}. Stáhněte nový balíček a nainstalujte jej pomocí:", "update.prefs_dev": "Toto je vývojová verze ({version}): aktualizace nekontroluje.", "update.prefs_flatpak": "Tuto kopii ({version}) aktualizuje Flatpak: spusťte {command} nebo použijte správce softwaru. SolidCraft nekontroluje.", "update.prefs_label": "Aktualizace", + "update.prefs_managed": "Toto je SolidCraft {version}, spravovaný aplikací {manager}. Kontrola se dotáže GitHubu na nejnovější verzi a nic dalšího neodesílá; aktualizujte SolidCraft v {manager}.", "update.prefs_note": "Toto je SolidCraft {version} ({kind}). Kontrola se dotáže GitHubu na nejnovější verzi a nic dalšího neodesílá.", "update.prefs_web": "Znovu načtěte stránku, abyste získali nejnovější webovou aplikaci. Pokud síť není dostupná nebo se aktualizace nestihne včas stáhnout, otevře se uložená verze; probíhající stahování pokračuje pro další načtení.", "update.refresh_checking": "Hledání nejnovější verze…", @@ -4679,6 +5280,7 @@ "web.open_link": "Otevřít propojený návrh?", "web.open_link_confirm": "Existují neuložené změny. Otevřít propojený návrh na nové kartě?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ vybrat · Enter / Tab doplnit · Esc zavřít", + "↑ ↓ choose · Enter applies this value": "↑ ↓ výběr · Enter použije tuto hodnotu", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ výběr · Enter použije, co jste napsali · Esc zavře", "⌘Enter continues on GitHub.": "⌘Enter pokračuje na GitHubu." } diff --git a/assets/locales/da.json b/assets/locales/da.json index 87e569f9b..cb62fd775 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -1,4 +1,5 @@ { + "(active rule)": "(aktiv regel)", "0 turns it off": "0 slår det fra", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Åbn GitHub-kladden nedenfor, og indsæt rapporten fra udklipsholderen.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Åbn GitHub-kladden nedenfor. Titel og rapport udfyldes automatisk.", @@ -8,6 +9,7 @@ "A Single hole snaps to the middle of its face and to the centres of its round edges": "Et enkelt hul snapper til fladens midtpunkt og centrene af dens cirkulære kanter", "A new configuration, a copy of the active one": "Opret en ny konfiguration som en kopi af den aktive", "A placed Single hole has a handle to drag it, and picking its face again moves the hole there instead of taking it out": "Et placeret enkelt hul har et håndtag til at trække i. Hvis fladen vælges igen, flyttes hullet dertil i stedet for at blive fjernet", + "A short title for the problem (optional)": "En kort titel på problemet (valgfri)", "ARRANGE": "ARRANGER", "About SolidCraft": "Om SolidCraft", "Acceleration": "Acceleration", @@ -21,9 +23,12 @@ "Add Mid Radius": "Tilføj mellemradius", "Add Row": "Tilføj række", "Add a tool": "Tilføj et værktøj", + "Add all bodies": "Tilføj alle emner", + "Add bend": "Tilføj bukning", "Add condition": "Tilføj betingelse", "Add or edit rule": "Tilføj eller redigér regel", "Add to New Folder": "Føj til ny mappe", + "Add visible bodies": "Tilføj synlige emner", "Advanced": "Avanceret", "Against": "Mod", "Alignment": "Justering", @@ -36,7 +41,9 @@ "Also place them from the origin (fully constrained)": "Placer dem også fra origo (fuldt fastlåst)", "Anchor": "Forankring", "Angle 2": "Vinkel 2", + "Angle Display": "Visning af vinkel", "Animate": "Animér", + "Another bend on the far edge of the last flange": "Endnu en bukning på den yderste kant af den sidste flange", "App/system information and command settings are included. Review private details before sharing.": "Oplysninger om programmet, systemet og kommandoindstillingerne er inkluderet. Gennemgå private oplysninger, før du deler rapporten.", "Appearance name": "Navn på udseende", "Applied Radius": "Anvendt radius", @@ -46,14 +53,21 @@ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Anvend først dit udseende. Eksporterer tildelte udseender og materialer oprettet i dette design.", "Arc length": "Buelængde", "Area": "Areal", + "As Picked": "Som valgt", "As-Built": "Som bygget", "Assign Rule": "Tildel regel", "Attachment": "Tilknytning", "BLEND SURFACE": "OVERGANGSFLADE", "BOUNDARY SURFACE": "AFGRÆNSET OVERFLADE", "BROWSER": "MODELTRÆ", + "Back to the original order": "Tilbage til den oprindelige rækkefølge", + "Ball": "Kugleled", "Bar": "Stang", + "Base Center": "Bundens centrum", + "Base Height": "Grundhøjde", + "Bend": "Bukning", "Bend Edges": "Bøjningskanter", + "Bend Line": "Bukkelinje", "Bend Line Position": "Bukkelinjens placering", "Bend Position": "Bukningens placering", "Bend Radius": "Bukkeradius", @@ -65,6 +79,7 @@ "Body (last if none)": "Legeme (det sidste, hvis intet er valgt)", "Body to split": "Legeme, der skal opdeles", "Body, or faces to take out": "Legeme eller flader, der skal fjernes", + "Both": "Begge", "Bottom Left": "Nederst til venstre", "Bottom Middle": "Nederst i midten", "Bottom Right": "Nederst til højre", @@ -96,6 +111,7 @@ "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Vælg et nyt plan. Skitsegeometri og mål bevarer deres todimensionelle koordinater.", "Choose…": "Vælg…", "Circle center": "Cirklens centrum", + "Circle or sphere": "Cirkel eller kugle", "Circular": "Cirkulær", "Circumference": "Omkreds", "Clockwise": "Med uret", @@ -112,12 +128,14 @@ "Config Table": "Konfig.tabel", "Configuration": "Konfiguration", "Configuration rules": "Konfigurationsregler", + "Constant radius": "Konstant radius", "Contact": "Kontakt", "Contact Sets": "Kontaktsæt", "Contact sets": "Kontaktsæt", "Continue on GitHub": "Fortsæt på GitHub", "Continuity": "Kontinuitet", "Control Radius": "Styreradius", + "Copies the definition only. Assign it from Physical Material when ready.": "Kopierer kun definitionen. Tildel den fra Fysisk materiale, når den er klar.", "Copy Error Message": "Kopiér fejlmeddelelse", "Copy Warning Message": "Kopiér advarselsmeddelelse", "Copy all licences": "Kopiér alle licenser", @@ -135,17 +153,22 @@ "Create Issue — review draft": "Opret issue — gennemgå kladde", "Create Issue…": "Opret fejlrapport…", "Cross curves": "Tværkurver", + "Ctrl+Enter continues on GitHub.": "Ctrl+Enter fortsætter på GitHub.", "Cube": "Terning", "Current orthographic view (1:1 mm)": "Aktuel visning uden perspektiv (1:1 mm)", "Current perspective view": "Aktuel perspektivvisning", + "Current plane": "Aktuelt plan", "Curv. Comb": "Krumningskam", "Curvature (G2)": "Krumningskontinuitet (G2)", "Curvature change (G3)": "Ændring i krumning (G3)", "Custom": "Brugerdefineret", "Customize Toolbar": "Tilpas værktøjslinje", "Customize…": "Tilpas…", + "Cylindrical": "Cylinderled", "Cylindrical face": "Cylindrisk flade", + "Deboss": "Fordybet prægning", "Delete": "Slet", + "Delete Folders and Features…": "Slet mapper og features…", "Delete Selected Features…": "Slet valgte features…", "Delete Selected Folders": "Slet valgte mapper", "Delete all": "Slet alle", @@ -159,6 +182,8 @@ "Designs you open or save appear here.": "Designs, du åbner eller gemmer, vises her.", "Determined by To Object. Choose Angle to edit the angular extent.": "Bestemmes af Til objekt. Vælg Vinkel for at ændre vinkeludstrækningen.", "Diameter": "Diameter", + "Did this assembly open the wrong way up?": "Blev denne samling åbnet med forkert side opad?", + "Did this part open the wrong way up?": "Blev dette emne åbnet med forkert side opad?", "Dimension new shapes": "Mål nye figurer", "Direction": "Retning", "Discard": "Kassér", @@ -168,19 +193,27 @@ "Don't ask again": "Spørg ikke igen", "Double-click to rename": "Dobbeltklik for at omdøbe", "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Dobbeltklik på den midterste museknap i visningen: Hjem (hjemmevisningen, der indrammer det viste), Tilpas (indrammer det viste og bevarer orienteringen) eller ingen handling", + "Drag to move the boss across the model. It snaps to sketch points on the face.": "Træk for at flytte skruebøsningen hen over modellen. Den snapper til skitsepunkter på fladen.", "Drag to move the hole; click to remove it": "Træk for at flytte hullet; klik for at fjerne det", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "Træk for at flytte understøtningen hen over modellen. Den snapper til skitsepunkter på fladen.", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "Træk for at flytte snapforbindelsen hen over modellen. Den snapper til skitsepunkter på fladen.", + "Drag to point the catch in another direction.": "Træk for at pege låsen i en anden retning.", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "Træk for at dreje understøtningen i trin på 5°. Hold Alt eller Ctrl nede for at dreje den frit.", "Drive Joint": "Bevæg led", "Duration": "Varighed", "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Hver ny figur får også mål fra skitsens origo, indtil intet af den er frit. En figur, der allerede er knyttet til origo eller til placeret geometri, får ingen.", "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Hver figur, du tegner, får alle sine mål i de størrelser, du tegnede (indtastede værdier vinder). En størrelse, som skitsen allerede fastlægger, udelades.", + "Edge": "Kant", "Edges": "Kanter", "Edit": "Redigér", "Edit Profile Sketch": "Redigér profilskitse", + "Edit shortcuts": "Redigér genveje", "Enable rule": "Aktivér regel", "Enabled": "Aktiveret", "End Radius": "Slutradius", "End bulge": "Udbuling ved slutningen", "End continuity": "Overgang ved slutningen", + "Equal Distance": "Ens afstande", "Expand": "Fold ud", "Expected result (optional)": "Forventet resultat (valgfrit)", "Explode": "Adskil", @@ -208,6 +241,8 @@ "Faces": "Flader", "Faces / edges / vertices": "Flader / kanter / hjørnepunkter", "Faces to split": "Flader, der skal opdeles", + "Faces/Body": "Flader/emne", + "Factor must be a positive number": "Faktoren skal være et positivt tal", "Fastener": "Befæstigelse", "Favorites": "Favoritter", "Favourite": "Favorit", @@ -217,38 +252,57 @@ "Filter…": "Filtrér…", "Find in Browser": "Find i modeltræ", "Finish": "Afslut", + "First edge": "Første kant", "First plane": "Første plan", + "First point": "Første punkt", "Fit and G2 corners require Constant radius.": "Tilpasning og G2-hjørner kræver konstant radius.", "Fixed Face": "Fast flade", + "Flange Gap": "Flangemellemrum", "Flange thickness": "Flangetykkelse", + "Flanges": "Flanger", "Flat Pattern": "Flad afvikling", "Flat size": "Bredde mellem flader", + "Flat size X": "Udfoldet størrelse X", + "Flat size Y": "Udfoldet størrelse Y", "Follow camera (Look At sketches)": "Følg kamera (Se på skitser)", "Follow the camera (Look At sketches)": "Følg kameraet (Se på skitser)", "Font": "Skrifttype", + "Free Move": "Fri flytning", "From": "Fra", "From Bodies": "Fra emner", + "From Snap": "Fra snappunkt", "From edges": "Fra kanter", "Full Length": "Fuld længde", + "Full thread depth": "Fuld gevinddybde", + "Further Bends": "Flere bukninger", "G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "G2-hjørner kræver konstant radius og præcis tilpasning. Konstruktion af G2-hjørner understøttes endnu ikke.", "Gap": "Spalte", "Grid": "Gitter", "HISTORY": "HISTORIK", + "Halo under sketch curves": "Halo under skitsekurver", "Height": "Højde", + "Height From": "Højde fra", + "Hem Gap": "Ombukningsmellemrum", "Hidden edges": "Skjulte kanter", "History layout": "Historiklayout", "History names": "Navne i historikken", "Hole (optional)": "Hul (valgfrit)", + "Hole Depth": "Huldybde", + "Hole Diameter": "Huldiameter", "Holes": "Huller", "Holes (edges on them)": "Huller (kanterne omkring dem)", "Home view": "Hjemmevisning", "Horiz./Vert.": "Vandr./Lodr.", "I-Beam": "I-profil", "IMAGES": "BILLEDER", + "If you are offline or GitHub does not open, use Copy report and keep the text to submit later.": "Hvis du er offline, eller GitHub ikke åbner, skal du bruge Kopiér rapport og gemme teksten, så du kan indsende den senere.", + "Import material into design": "Importér materiale i designet", "Import…": "Importér…", "In This Design": "I dette design", "In place (surfaces)": "På stedet (overflader)", "In plane": "I planet", + "Included": "Indesluttet", + "Inner Sharp": "Indvendig skarp", "Inside": "Indvendigt", "Instant": "Øjeblikkelig", "Interface font": "Skrifttype i brugergrænsefladen", @@ -258,12 +312,16 @@ "Issue title": "Titel på issue", "Items": "Elementer", "JOINTS": "LED", + "Joint 1": "Led 1", + "Joint 2": "Led 2", "Joint Origin1": "Lednulpunkt1", + "K Factor": "K-faktor", "Keep (points on it)": "Behold (punkter på fladen)", "Keep Tools": "Behold værktøjsemner", "Keep of the other surface": "Behold fra den anden overflade", "Key a joint's value at this step": "Indsæt en nøgle for leddets værdi på dette trin", "Keys": "Nøgler", + "Knife Edge": "Knivskarp kant", "L-Angle": "L-profil", "LIBRARY": "BIBLIOTEK", "LINKS": "LINKS", @@ -276,15 +334,18 @@ "Letter Spacing": "Tegnafstand", "Library": "Bibliotek", "Library file": "Biblioteksfil", + "Library response is missing": "Svar fra biblioteket mangler", "Limits": "Grænser", "Line Spacing": "Linjeafstand", "Line Type": "Linjetype", + "Line on plane": "Linje på plan", "Lines": "Linjer", "Listing the installed fonts…": "Henter listen over installerede skrifttyper…", "Load library": "Indlæs bibliotek", "Local library": "Lokalt bibliotek", "Loop": "Løkke", "M5 or M5x0.5": "M5 eller M5x0.5", + "M5, M5x0.5, 1/4-20 UNC": "M5, M5x0.5, 1/4-20 UNC", "MANAGE": "ADMINISTRÉR", "MATERIALS": "MATERIALER", "MODEL": "MODEL", @@ -294,12 +355,17 @@ "Mass Center": "Massecentrum", "Matched restrictions check the final values.": "Matchede begrænsninger kontrollerer de endelige værdier.", "Material": "Materiale", + "Material Outside": "Materiale udvendigt", + "Material copied. Existing body assignments are unchanged.": "Materialet er kopieret. Eksisterende tildelinger til emner er uændrede.", "Max": "Maks.", + "Max Thickness": "Maks. tykkelse", "Maximum": "Maksimum", "Mesh body": "Meshlegeme", "Mid Radius": "Mellemradius", "Middle double-click": "Dobbeltklik med midterste museknap", "Min": "Min.", + "Min Draft": "Min. slipvinkel", + "Min Thickness": "Min. tykkelse", "Minimum": "Minimum", "Mirror Plane": "Spejlingsplan", "Mitre": "Gering", @@ -317,7 +383,9 @@ "Move later": "Flyt senere", "Move up": "Flyt op", "Name": "Navn", + "Name on import": "Navn ved import", "Nearest": "Nærmeste", + "Neutral plane": "Neutralt plan", "New": "Ny", "New Comp.": "Ny komp.", "New Sketch": "Ny skitse", @@ -326,45 +394,62 @@ "No crash reports.": "Ingen nedbrudsrapporter.", "No matching appearance presets.": "Ingen matchende udseendeforudindstillinger.", "No matching appearances": "Ingen matchende udseender", + "No matching physical materials.": "Ingen matchende fysiske materialer.", "No visible bodies or sketches to export.": "Der er ingen synlige emner eller skitser at eksportere.", + "Nominal Radius": "Nominel radius", "Nominal diameter": "Nominel diameter", "None": "Ingen", "Not available yet": "Endnu ikke tilgængelig", + "Not saved yet": "Endnu ikke gemt", "Notch": "Udskæring", "OUTPUT": "OUTPUT", "Of": "Af", "On your computer": "På din computer", "Opacity": "Opacitet", + "Open GitHub": "Åbn GitHub", "Open GitHub draft": "Åbn GitHub-kladde", + "Open GitHub issue form": "Åbn GitHubs formular til issues", + "Open bodies (no volume)": "Åbne emner (uden volumen)", "Open library...": "Åbn bibliotek...", "Open local libraries in the desktop app. You can export this design's library here.": "Åbn lokale biblioteker i desktopappen. Du kan eksportere dette designs bibliotek her.", + "Open surface — no volume": "Åben overflade — uden volumen", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Parametrisk 3D-CAD i Rust med åben kildekode. Licenseret under MIT OR Apache-2.0.", "Opens your browser and copies the report text for you to paste into GitHub.": "Åbner din browser og kopierer rapportteksten, så du kan indsætte den på GitHub.", + "Opens your browser and copies the report text. Review and submit your report on GitHub.": "Åbner din browser og kopierer rapportteksten. Gennemgå og indsend rapporten på GitHub.", "Opens your browser. Review and submit your report on GitHub.": "Åbner din browser. Gennemgå og indsend rapporten på GitHub.", "Operator": "Operator", "Orbit (right drag)": "Rotér visningen (træk med højre museknap)", "Other side": "Anden side", "Other surface (mutual trim)": "Anden overflade (trim begge)", + "Other way": "Den anden vej", + "Outer Sharp": "Udvendig skarp", "Outer radius": "Udvendig radius", "Outside": "Udvendigt", "Overall length": "Samlet længde", "Param. Graph": "Param.graf", "Parameter": "Parameter", + "Part length must be greater than zero and at most 2000 mm": "Delens længde skal være større end nul og højst 2000 mm", "Parts": "Dele", "Pass through": "Gå igennem", "Path": "Bane", "Pattern": "Mønster", "Per Edge": "Pr. kant", + "Physical material definitions": "Definitioner af fysiske materialer", + "Pick a part size": "Vælg en delstørrelse", "Pick the tool bodies": "Vælg værktøjsemnerne", "Picked": "Valgt", "Picked point": "Valgt punkt", + "Pin-slot": "Stift i slids", "Pitch": "Stigning", "Pivot": "Drejepunkt", "Place at the origin instead": "Placér ved nulpunktet i stedet", + "Planar": "Planled", "Plastic Rules": "Plastregler", "Play the joint's motion in the view": "Afspil leddets bevægelse i visningen", "Playback": "Afspilning", "Plot": "Diagram", + "Point on line": "Punkt på linje", + "Point on plane": "Punkt på plan", "Position": "Position", "Position (0 to 1)": "Position (0 til 1)", "Position (G0)": "Positionskontinuitet (G0)", @@ -377,6 +462,7 @@ "Profiles or curves": "Profiler eller kurver", "Profiles/Curves": "Profiler/kurver", "Quantity": "Antal", + "Quantity must be at least 2": "Antal skal være mindst 2", "RECENT": "SENESTE", "REFERENCE": "REFERENCE", "RULED SURFACE": "REGELFLADE", @@ -384,12 +470,16 @@ "Radius": "Radius", "Radius Fit": "Tilpasning af radius", "Ratio": "Forhold", + "Read-only list: shortcuts can't be changed here.": "Skrivebeskyttet liste: Genveje kan ikke ændres her.", "Reattach selected face": "Tilknyt den valgte flade igen", "Recover": "Gendan", "Recover unsaved design?": "Gendan design, der ikke er gemt?", "Rectangular": "Rektangulær", "Rectangular Tube": "Rektangulært hulprofil", "Reference face": "Referenceflade", + "Reference plane": "Referenceplan", + "Relief Depth": "Aflastningsdybde", + "Relief Width": "Aflastningsbredde", "Remove Tools": "Fjern værktøjsemner", "Remove condition": "Fjern betingelse", "Remove from Folder": "Fjern fra mappe", @@ -399,11 +489,16 @@ "Remove screenshot": "Fjern skærmbillede", "Remove the column": "Fjern kolonnen", "Remove the track": "Fjern sporet", + "Remove this bend": "Fjern denne bukning", "Remove this point": "Fjern dette punkt", "Rename Feature": "Omdøb feature", "Rename Folder": "Omdøb mappe", + "Render Stage": "Renderingskulisse", + "Reopen designs": "Genåbn designs", + "Reopen the designs that were open when SolidCraft was last closed": "Genåbn de designs, der var åbne, da SolidCraft sidst blev lukket", "Replace existing library file": "Erstat eksisterende biblioteksfil", "Report a bug — review a screenshot and open a GitHub draft": "Rapportér en fejl — gennemgå et skærmbillede, og åbn en GitHub-kladde", + "Report copied. Keep this text to submit on GitHub when you are online.": "Rapporten er kopieret. Gem teksten, så du kan indsende den på GitHub, når du er online.", "Report text copied. Paste it into GitHub and submit your report there.": "Rapportteksten er kopieret. Indsæt den på GitHub, og indsend rapporten der.", "Reports are public. A GitHub account is required.": "Rapporter er offentlige. Du skal have en GitHub-konto.", "Reset Toolbar": "Nulstil værktøjslinje", @@ -414,6 +509,7 @@ "Restore this studio's tools": "Gendan værktøjerne i dette arbejdsområde", "Result": "Resultat", "Retake screenshot": "Tag skærmbillede igen", + "Reveal Height": "Synlig højde", "Reverse": "Vend om", "Reverse Direction": "Vend retning", "Revert": "Tilbagefør", @@ -422,12 +518,15 @@ "Revert Position": "Tilbagefør position", "Review the report and screenshot before opening GitHub.": "Gennemgå rapport og skærmbillede, før du åbner GitHub.", "Review your report on GitHub and click Submit new issue to publish it.": "Gennemgå rapporten på GitHub, og klik på Submit new issue for at offentliggøre den.", + "Revolute": "Drejeled", "Rib Length": "Ribbelængde", "Rib Offset": "Ribbeforskydning", "Rib Thickness": "Ribbetykkelse", "Ribs": "Ribber", "Right Middle": "Til højre i midten", + "Rigid": "Stivt led", "Rim Edge": "Randkant", + "Rim face": "Kantflade", "Ring of tools on the right button": "Værktøjsring på højre museknap", "Roll Back Here": "Rul tilbage hertil", "Roll History Marker Here": "Flyt tilbagerulningsmarkør hertil", @@ -440,6 +539,7 @@ "Rules run from top to bottom. Matched drives change effective values.": "Regler køres oppefra og ned. Matchede drivere ændrer de effektive værdier.", "SECTION": "SNIT", "SURFACE QUALITY": "OVERFLADEKVALITET", + "Same way": "Samme vej", "Save Rule": "Gem regel", "Save View": "Gem visning", "Save screenshot…": "Gem skærmbillede…", @@ -451,16 +551,29 @@ "Search": "Søg", "Search commands": "Søg efter kommandoer", "Search this library": "Søg i dette bibliotek", + "Second edge": "Anden kant", "Second plane": "Andet plan", + "Second point": "Andet punkt", "Section": "Snit", "Section (optional)": "Tværsnit (valgfrit)", "Section position": "Profilets placering", + "Sections": "Tværsnit", "Sections (one sketch each)": "Tværsnit (én skitse til hvert)", "Select Other": "Vælg andet", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Vælg andet: Hold venstre museknap nede uden at flytte markøren på modellen (eller højreklik › Vælg andet…) for at vise alt under markøren. Klik igen samme sted for at vælge næste objekt. Dobbeltklik på den midterste museknap for at gå til Hjem (Indstillinger › Navigation).", + "Select Same Look": "Vælg samme udseende", "Select bodies (a face picks its body)": "Vælg emner (en flade vælger sit emne)", "Select bodies or faces instead": "Vælg emner eller flader i stedet", "Select edges": "Vælg kanter", + "Select points of the sketch being edited": "Vælg punkterne i den skitse, der redigeres", + "Select the centre the pattern turns around first": "Vælg først det centrum, som mønsteret drejer omkring", + "Select the curves to offset first": "Vælg først de kurver, der skal forskydes", + "Select the mirror line": "Vælg spejlingslinjen", + "Select the sketch curves or points to mirror first": "Vælg først de skitsekurver eller punkter, der skal spejles", + "Select the sketch curves or points to move first": "Vælg først de skitsekurver eller punkter, der skal flyttes", + "Select the sketch curves or points to pattern first": "Vælg først de skitsekurver eller punkter, der skal indgå i mønsteret", + "Select the sketch curves or points to scale first": "Vælg først de skitsekurver eller punkter, der skal skaleres", + "Select the sketch curves or points to transform first": "Vælg først de skitsekurver eller punkter, der skal transformeres", "Selection filter": "Markeringsfilter", "Semantic faces share their appearance across instances.": "Semantiske flader deler udseende på tværs af instanser.", "Send your report on GitHub": "Send din rapport på GitHub", @@ -468,6 +581,7 @@ "Shape": "Form", "Sheet Rules": "Pladeregler", "Show Agent Cursor": "Vis agentmarkør", + "Show ghost": "Vis skyggebillede", "Show in folder": "Vis i mappe", "Show the pointer an AI agent moves (#35)": "Vis markøren, som en AI-agent bevæger (#35)", "Show tool at cursor": "Vis værktøj ved markøren", @@ -479,19 +593,27 @@ "Sketch geometry and profiles": "Skitsegeometri og profiler", "Sketch plane has no body-face attachment.": "Skitseplanet er ikke tilknyttet en flade på et emne.", "Sketch points": "Skitsepunkter", + "Slider": "Glideled", "Slot width": "Slidsbredde", "Snap to face and edge centres": "Snap til flade- og kantcentre", + "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft kan ikke indsende rapporter direkte. Indsend dem på GitHub; der skal ikke bruges noget token i appen.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft lukkede, før disse designs blev gemt. Den seneste automatiske lagring kan åbnes.", + "Sort A to Z": "Sortér A til Å", + "Sort Z to A": "Sortér Å til A", + "Spacing 2 must be a non-zero number": "Afstand 2 skal være et tal forskelligt fra nul", + "Spacing must be a non-zero number": "Afstand skal være et tal forskelligt fra nul", "Specialise": "Specialisér", "Speed": "Hastighed", "Splitting tool": "Opdelingsværktøj", "Square": "Kvadrat", "Stand it up": "Stil op", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Stil op: En kvart omdrejning om X som én flyttefeature, der kan fortrydes.", + "Stand this assembly up?": "Stil denne samling op?", "Stand this part up?": "Stil dette emne op?", "Start angle": "Startvinkel", "Start bulge": "Udbuling ved starten", "Start continuity": "Overgang ved starten", + "Stationary Side": "Fast side", "Step": "Trin", "Steps": "Trin", "Steps to reproduce (optional)": "Trin til at genskabe problemet (valgfrit)", @@ -502,33 +624,50 @@ "Style": "Stil", "Summary": "Resumé", "Suppress": "Undertryk", + "Suppress Selected Folders": "Undertryk valgte mapper", "Suppressed": "Undertrykt", "Surface": "Overflade", "Surface, or faces to turn over": "Overflade eller flader, der skal vendes", + "Surfaces": "Overflader", "Swap Ends": "Ombyt ender", "TRIM": "TRIM", + "Tangent": "Tangent", "Tangent (G1)": "Tangentkontinuitet (G1)", "Tangent Chain": "Tangentkæde", "Tangent chain": "Tangentkæde", + "Tangent to Edge": "Tangent til kant", "Tap drill diameter": "Diameter på gevindbor", "Target": "Mål", "Target Body": "Mållegeme", + "Target Face (optional)": "Målflade (valgfri)", "Tear": "Rivning", "Technical details": "Tekniske detaljer", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Den stiplede skitse er en gemt planreference. Vælg en ny flade for at reparere tilknytningen.", + "The design changed. Reopen Change Part Size for the component.": "Designet er ændret. Åbn Skift standarddelens størrelse igen for komponenten.", + "The direction must be an axis or a straight sketch curve that lies in the sketch plane": "Retningen skal være en akse eller en ret skitsekurve, der ligger i skitseplanet", + "The mirror line cannot also be mirrored": "Spejlingslinjen kan ikke også spejles", + "The mirror line must be a straight curve of this sketch, not an origin axis": "Spejlingslinjen skal være en ret kurve i denne skitse og ikke en akse fra nulpunktet", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Den gemte oprindelige komponentforekomst mangler. Vælg en gyldig oprindelig placering før ny tilknytning.", "Then": "Så", "These features will be deleted:": "Disse features slettes:", "These features will fail:": "Disse features vil fejle:", "Thickness Outside": "Tykkelse udad", + "Thickness Variation": "Tykkelsesvariation", "Thin": "Tynd", "Thin Extrude": "Tynd ekstrudering", + "Third plane": "Tredje plan", + "Third point": "Tredje punkt", "This child is shared. Deleting it removes it from every copy of its parent.": "Dette underobjekt er delt. Sletning fjerner det fra alle kopier af dets overordnede objekt.", "This child is shared. Position changes apply to every copy of its parent.": "Dette underobjekt er delt. Positionsændringer gælder for alle kopier af dets overordnede objekt.", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "Denne komponent ligger i en delsamling, der er placeret flere gange: Justering flytter den i alle placeringer.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Denne flade kan ikke give en varig tilknytning. Vælg en anden flade, eller vælg udtrykkeligt et fast plan.", "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "Dette billede er endnu ikke vedhæftet på GitHub. Kopiér eller gem det, og vedhæft det derefter på GitHub.", + "Thread depth": "Gevinddybde", + "Thread diameter": "Gevinddiameter", + "Through point": "Gennem punkt", "To": "Til", "To Offset": "Til forskydning", + "To Snap": "Til snappunkt", "To edges": "Til kanter", "Toe radius": "Tåradius", "Tolerance": "Tolerance", @@ -542,9 +681,11 @@ "Trimming tool (plane, face or curves)": "Trim med plan, flade eller kurver", "Turn off section analysis before exporting the view.": "Slå snitanalyse fra, før visningen eksporteres.", "Type": "Type", + "Type a distance or an angle to move by": "Skriv en afstand eller en vinkel at flytte med", "UNTRIM": "FJERN BESKÆRING", "Unit": "Enhed", "Unsuppress": "Ophæv undertrykkelse", + "Unsuppress Selected Folders": "Ophæv undertrykkelse af valgte mapper", "Updating the preview": "Opdaterer forhåndsvisningen", "Use active author placement": "Brug den aktive komponents placering", "Use fixed plane": "Brug fast plan", @@ -585,10 +726,26 @@ "Z angle": "Z-vinkel", "Z distance": "Z-afstand", "Zebra": "Zebra", + "`joint` must be an id or a name": "`joint` skal være et id eller et navn", + "`params` must be an object": "`params` skal være et objekt", + "`values` must be a list": "`values` skal være en liste", + "a chamfer needs a corner of exactly two lines": "en affasning kræver et hjørne med præcis to linjer", + "a file operation is in progress": "en filhandling er i gang", + "a picked curve is no longer in a sketch": "en valgt kurve er ikke længere i en skitse", + "a picked curve's sketch has not been solved": "skitsen for en valgt kurve er ikke blevet løst", + "a picked edge has no points": "en valgt kant har ingen punkter", + "a picked edge is gone": "en valgt kant findes ikke længere", + "a picked edge's body is gone": "emnet for en valgt kant findes ikke længere", + "add a key for a joint first": "tilføj først et animationspunkt for et led", + "ai.connected_toast": "SolidCraft er nu tilgængeligt i {clients}. Genstart dem for at bruge det (Indstillinger > Assistent).", "ai.prefs.allow_control": "Tillad AI-agenter at oprette forbindelse (kontrolkanal / MCP)", "ai.prefs.allow_control_note": "Åbner kun en kontrolkanal på denne computer (127.0.0.1, port 27878 eller den næste ledige). Et program, der opretter forbindelse, skal også fremvise et hemmeligt token, som kun din brugerkonto kan læse, og som oprettes på ny ved hver start. Træder i kraft, næste gang SolidCraft starter. Fra: Ingen port lytter, medmindre du starter SolidCraft med --control.", "ai.prefs.availability": "Assistentstyring", "ai.prefs.background_commands": "Kør agentkommandoer i baggrunden", + "ai.prefs.connect_apps": "Gør SolidCraft tilgængeligt for AI-apps på denne computer", + "ai.prefs.connect_apps_note": "Når SolidCraft starter, tilføjes det som MCP-server i de AI-apps, der findes på denne computer (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), så en agent kan bruge det uden nogen opsætning. Kun posten solidcraft tilføjes, eller dens sti opdateres; en post, du har ændret, røres ikke, og filen sikkerhedskopieres først. Slået fra: De poster, der blev tilføjet, fjernes. Hjælp > Forbind AI-assistenter… gør dette manuelt.", + "ai.prefs.connect_at_start": "Forbind den senest brugte agent, når SolidCraft starter", + "ai.prefs.connect_at_start_note": "Starter den agent, du forbandt senest (eller standardagenten), i baggrunden, hver gang SolidCraft starter, så den er klar til at chatte. Ikke når SolidCraft startes med --control. Hvis den ikke kan oprette forbindelse, viser Assistenten Forbindelsen mislykkedes og en knap Prøv igen.", "ai.prefs.follow_camera": "Vend kameraet mod skitser", "ai.prefs.follow_camera_off": "Automatisk kamerafølgning er slået fra.", "ai.prefs.follow_camera_on": "Kameraet vender sig mod skitser, som agenten opretter.", @@ -596,6 +753,8 @@ "ai.prefs.make_default": "Brug som standard", "ai.prefs.no_agents": "Ingen agenter endnu. Tilføj en agent, eller opdatér for at finde installerede agenter.", "ai.prefs.no_saved_approvals": "Ingen gemte godkendelser.", + "ai.prefs.open_at_start": "Åbn panelet Assistent, når SolidCraft starter", + "ai.prefs.open_at_start_note": "Viser panelet Assistent (eller dets eget vindue), hver gang SolidCraft starter. Ikke når SolidCraft startes med --control.", "ai.prefs.override_all_warning": "Denne agent kan gemme, overskrive, eksportere eller erstatte designet uden at spørge.", "ai.prefs.permission_all": "Tillad alt", "ai.prefs.permission_all_summary": "Tilgængelige SolidCraft-værktøjer kører uden at spørge.", @@ -619,17 +778,30 @@ "appearance.roughness": "Ruhed", "appearance.surface_response": "Overfladens reaktion på lys", "at the face": "ved fladen", + "bom.group_children": "Underdele i rækken for deres del", "browser.body_name": "Emne{number}", + "browser.calibrate_click_a": "Klik på billedet for punkt A, eller skriv dets koordinater.", + "browser.calibrate_click_b": "Klik på billedet for punkt B, eller skriv dets koordinater.", "browser.calibrate_title": "Kalibrér: {name}", "browser.capture_many": "{count} komponenter er flyttet, men deres positioner er ikke registreret.", "browser.capture_note": "Registrér beholder den nye position; Fortryd sætter den tilbage.", "browser.capture_one": "En komponent er flyttet, men dens position er ikke registreret.", "browser.component_name": "Komponent{number}", "browser.edit_canvas_title": "Redigér lærred: {name}", + "browser.edit_point_cloud_title": "Redigér punktsky: {name}", "browser.move_title": "Flyt: {name}", "browser.parameters": "Parametre ({count})", "browser.precision": "Præcision: {precision}", + "browser.sketch_attachment_lost": "{name} (tilknytning mistet)", + "browser.sketch_editing": "{name} (redigeres)", "browser.sketch_name": "Skitse{number}", + "browser.sketches_to_parts_already_in_part": "allerede i deres del", + "browser.sketches_to_parts_design_body": "på et emne i selve designet", + "browser.sketches_to_parts_moved": "Flyttede {moved} skitser til den del, de ligger på", + "browser.sketches_to_parts_no_exact_attachment": "på en flade uden nøjagtig tilknytning", + "browser.sketches_to_parts_not_on_face": "ikke på en dels flade", + "browser.sketches_to_parts_part_missing": "deres del findes ikke længere", + "browser.sketches_to_parts_result": "Flyttede {moved} skitser til den del, de ligger på; {stayed} blev, hvor de var: {why}", "browser.units": "Enheder: {units}", "cam.flat": "Flad kontaktflade", "cam.follower": "Følger", @@ -638,15 +810,37 @@ "cam.roller": "Rulle", "cam.roller_pick": "Rulle (valgfri)", "cam.tip_pick": "Spids (valgfri)", + "camera.shot_pitch": "Stampning", + "camera.shot_roll": "Rulning", + "camera.shot_yaw": "Krøjning", + "canvas.decal_place_hint": "Klik på en flade for at placere dekalen", + "canvas.place_hint": "Klik på et plan eller en flade for at placere referencebilledet", + "choose a profile": "vælg en profil", + "choose the cam's and the follower's joints": "vælg knastens og følgerens led", + "choose the joints to couple": "vælg de led, der skal kobles", + "click a plane or planar face": "klik på et plan eller en plan flade", + "click sketch curves": "klik på skitsekurver", "cmd.appearance_assign": "Udseende", + "cmd.appearance_chain": "Udseendekæde", + "cmd.appearance_copy": "Kopiér udseende", + "cmd.appearance_favorite": "Favoritudseende", "cmd.appearance_library": "Udseendebibliotek", "cmd.appearance_list": "Vis udseender", + "cmd.appearance_paint": "Påfør udseende", + "cmd.appearance_paste": "Indsæt udseende", + "cmd.appearance_pick_up": "Optag udseende", + "cmd.appearance_replace": "Erstat udseende", "cmd.assembly_bom": "Stykliste", + "cmd.assembly_mass_properties": "Masseegenskaber", + "cmd.body.print_face": "Printflade", "cmd.body_rename": "Omdøb emne", + "cmd.browser_collapse_all": "Fold alle sammen", + "cmd.browser_expand_all": "Fold alle ud", "cmd.browser_group": "Ny gruppe", "cmd.browser_move": "Flyt elementer i modeltræ", "cmd.browser_order": "Sortér elementer i modeltræ", "cmd.browser_rename_group": "Omdøb gruppe", + "cmd.browser_reparent": "Flyt til komponent", "cmd.browser_ungroup": "Ophæv gruppering", "cmd.browser_visibility": "Vis/skjul", "cmd.canvas_calibrate": "Kalibrér referencebillede", @@ -659,23 +853,32 @@ "cmd.component_break_link": "Bryd forbindelse", "cmd.component_capture_position": "Registrér position", "cmd.component_copies": "Find identiske kopier", + "cmd.component_copy_bodies": "Indsæt emner", "cmd.component_create": "Ny komponent", + "cmd.component_cycle_color": "Skift mellem komponentfarver", "cmd.component_delete": "Slet komponent", + "cmd.component_edit_in_place": "Redigér på stedet", "cmd.component_extract": "Udtræk til fil", + "cmd.component_finish_edit": "Afslut redigering", "cmd.component_from_bodies": "Opret komponenter fra emner", + "cmd.component_hide_history": "Skjul komponenthistorik", "cmd.component_insert_design": "Indsæt design", "cmd.component_links": "Vis forbindelser", "cmd.component_list": "Vis komponenter", "cmd.component_metadata": "Egenskaber for delen", "cmd.component_metadata_set": "Redigér delens egenskaber", "cmd.component_move_bodies": "Flyt emner til komponent", + "cmd.component_move_features": "Flyt features til komponent", "cmd.component_move_sketches": "Flyt skitser til komponent", + "cmd.component_move_sketches_to_parts": "Flyt skitser til deres dele", + "cmd.component_paste_from_design": "Indsæt fra et andet design", "cmd.component_paste_new": "Indsæt som ny", "cmd.component_properties": "Komponentens fysiske egenskaber", "cmd.component_relink": "Skift kilde", "cmd.component_rename": "Omdøb komponent", "cmd.component_replace_with_link": "Erstat med link", "cmd.component_revert_position": "Tilbagefør position", + "cmd.component_show_history": "Vis komponenthistorik", "cmd.component_unlock": "Lås indhold op", "cmd.component_update_links": "Opdatér forbindelser", "cmd.config_activate": "Aktivér konfiguration", @@ -686,6 +889,7 @@ "cmd.config_rule": "Konfigurationsregel", "cmd.config_rules": "Konfigurationsregler", "cmd.config_table": "Vis konfigurationstabel", + "cmd.construct.plane.axis_point": "Plan gennem akse og punkt", "cmd.construct_axis_edge": "Akse gennem kant", "cmd.construct_axis_normal_to_face": "Akse vinkelret på flade", "cmd.construct_axis_through_cylinder": "Akse gennem cylinder/kegle/torus", @@ -721,8 +925,10 @@ "cmd.document_metadata": "Designegenskaber", "cmd.document_metadata_remove": "Fjern designegenskab", "cmd.document_metadata_set": "Redigér designegenskaber", + "cmd.document_revision": "Designrevision", "cmd.document_units": "Skift designets enheder", "cmd.edit_checkpoint": "Kontrolpunkt", + "cmd.edit_repeat": "Gentag sidste kommando", "cmd.edit_restore_checkpoint": "Gendan kontrolpunkt", "cmd.engine_commands": "Vis kommandoer", "cmd.engine_describe": "Beskriv kommando", @@ -732,11 +938,17 @@ "cmd.explode_show": "Vis eksploderet visning", "cmd.expr_evaluate": "Beregn udtryk", "cmd.face_delete": "Slet flade", + "cmd.file.export_3mf": "Eksportér 3MF", + "cmd.file.export_obj": "Eksportér OBJ", + "cmd.file.export_step": "Eksportér STEP", + "cmd.file.export_stl": "Eksportér STL", + "cmd.file.export_urdf": "Eksportér URDF", "cmd.file_export": "Eksportér", "cmd.file_insert_mesh": "Indsæt mesh", "cmd.file_insert_step": "Indsæt STEP", "cmd.file_open_in_easyprint": "Åbn med EasyPrint", "cmd.file_save_mesh": "Gem som mesh", + "cmd.file_send_to_slicer": "Send til slicer", "cmd.file_slicers": "Installerede slicere", "cmd.frame_member": "Rammeelement", "cmd.frame_profile_insert": "Indsæt profil", @@ -745,7 +957,10 @@ "cmd.inspect_accessibility": "Tilgængelighedsanalyse", "cmd.inspect_center_of_mass": "Massecentrum", "cmd.inspect_clearance": "Frigangskontrol", + "cmd.inspect_colored_components": "Aktivér komponentfarver", + "cmd.inspect_colored_components_disable": "Deaktivér komponentfarver", "cmd.inspect_compare": "Sammenlign emner", + "cmd.inspect_compare_picture": "Sammenlign billede", "cmd.inspect_continuity": "Kontinuitetsanalyse", "cmd.inspect_curvature_comb": "Krumningskamanalyse", "cmd.inspect_curvature_map": "Krumningskortanalyse", @@ -754,6 +969,7 @@ "cmd.inspect_interference": "Overlap", "cmd.inspect_isocurve": "Isokurveanalyse", "cmd.inspect_minimum_radius": "Analyse af mindste radius", + "cmd.inspect_parameter_sweep": "Parametersweep", "cmd.inspect_silhouette": "Silhuet", "cmd.inspect_zebra": "Zebraanalyse", "cmd.joint_as_built": "Led i eksisterende position", @@ -800,11 +1016,13 @@ "cmd.motion_trace": "Bevægelsesspor", "cmd.motion_trace_edit": "Redigér bevægelsesspor", "cmd.motion_trace_keep": "Behold bevægelsesspor", + "cmd.occurrence_align": "Justér komponentforekomst", "cmd.occurrence_copy": "Indsæt (komponentforekomst)", "cmd.occurrence_drag": "Træk forekomst", "cmd.occurrence_ground": "Fastgør", "cmd.occurrence_move": "Flyt komponentforekomst", "cmd.occurrence_properties": "Komponentforekomstens fysiske egenskaber", + "cmd.occurrence_reparent": "Flyt til komponent", "cmd.parameters_add": "Tilføj brugerparameter", "cmd.parameters_change": "Redigér parametre", "cmd.parameters_comment": "Kommentér parameter", @@ -829,17 +1047,76 @@ "cmd.plastic_rest": "Understøtning", "cmd.plastic_rules": "Vis plastregler", "cmd.plastic_snap_fit": "Snapforbindelse", + "cmd.pointcloud_delete": "Slet punktsky", + "cmd.pointcloud_edit": "Redigér punktsky", + "cmd.pointcloud_insert": "Indsæt punktsky", + "cmd.pointcloud_list": "Punktskyer", + "cmd.render.compare.divider": "Flyt skillelinjen i renderingssammenligningen", + "cmd.render.result.discard": "Kassér renderingsresultat", + "cmd.render.result.select": "Vælg renderingsresultat", + "cmd.render_aging_describe": "Lagdelt overfladeældning", "cmd.render_backends": "Renderingsmotorer", + "cmd.render_batch": "Render alle optagelser", + "cmd.render_camera_fit": "Indram motiv", + "cmd.render_camera_get": "Undersøg renderingskamera", "cmd.render_cancel": "Annullér rendering", + "cmd.render_compare": "Sammenlign billeder", + "cmd.render_effects_describe": "Linse- og kreative effekter", "cmd.render_export": "Eksportér renderet billede", + "cmd.render_hdr_inspect": "Undersøg HDR-kilde", + "cmd.render_library_appearance_apply": "Anvend uigennemsigtigt udseende fra biblioteket", + "cmd.render_library_describe": "Undersøg ressource i renderingsbiblioteket", + "cmd.render_library_environment_apply": "Anvend indbyggede HDR-omgivelser", + "cmd.render_library_list": "Gennemse renderingsbiblioteket", + "cmd.render_library_physical_prepare": "Forbered fysisk reference", + "cmd.render_library_preview": "Undersøg originalt teksturkort", + "cmd.render_library_studio_apply": "Anvend designede studiolys", + "cmd.render_library_studio_prepare": "Forbered designede studiolys", + "cmd.render_library_surface_bind": "Gem overfladebinding", + "cmd.render_library_surface_prepare": "Forbered designede teksturkort", + "cmd.render_library_surface_unbind": "Fjern overfladebinding", + "cmd.render_library_targets": "Find mål i renderingsbiblioteket", + "cmd.render_lights_add": "Tilføj lys", + "cmd.render_lights_duplicate": "Duplikér renderingslys", + "cmd.render_lights_list": "Vis renderingslys", + "cmd.render_lights_mute": "Mute lys", + "cmd.render_lights_remove": "Fjern renderingslys", + "cmd.render_lights_set": "Angiv renderingslys", + "cmd.render_lights_solo": "Solo lys", + "cmd.render_optics_bind": "Gem optisk binding", + "cmd.render_optics_unbind": "Fjern optisk binding", + "cmd.render_output_size": "Angiv outputstørrelse for rendering", "cmd.render_preflight": "Kontrollér, om billedet kan renderes", + "cmd.render_preflight_copy": "Kopiér rapport fra renderingskontrol", + "cmd.render_preset_apply": "Anvend indbygget studio", + "cmd.render_preset_resolve": "Gennemgå indbygget studio", + "cmd.render_quality_prepare": "Gennemgå fast sample-budget", + "cmd.render_result_close": "Luk renderet billede", + "cmd.render_result_copy": "Kopiér renderet billede", + "cmd.render_result_pin": "Bevar vist renderingsresultat", + "cmd.render_result_regrade": "Farvegradér lineær master igen", + "cmd.render_result_view": "Vis renderet billede", "cmd.render_scene": "Vis oplysninger om scenen", "cmd.render_settings_apply": "Brug kamera", + "cmd.render_settings_capture_hdr": "Gem renderingsindstillinger med HDR", "cmd.render_settings_get": "Renderingsindstillinger", "cmd.render_settings_set": "Gem renderingsindstillinger", + "cmd.render_shot_duplicate": "Duplikér renderoptagelse", + "cmd.render_shot_remove": "Fjern renderoptagelse", + "cmd.render_shot_rename": "Omdøb renderoptagelse", + "cmd.render_stage_backdrop": "Gem fysisk renderingsbaggrund", + "cmd.render_stage_clear": "Fjern kulisse", + "cmd.render_stage_ground": "Gem renderingsgrundplan", "cmd.render_start": "Render billede", "cmd.render_status": "Status for rendering", "cmd.select_clear": "Ryd markering", + "cmd.settings_profile_apply": "Anvend indstillingsprofil", + "cmd.settings_profile_delete": "Slet indstillingsprofil", + "cmd.settings_profile_export": "Eksportér indstillingsprofil", + "cmd.settings_profile_import": "Importér indstillingsprofil", + "cmd.settings_profile_list": "Indstillingsprofiler", + "cmd.settings_profile_rename": "Omdøb indstillingsprofil", + "cmd.settings_profile_save": "Gem indstillingsprofil", "cmd.sheet_convert": "Konvertér til plade", "cmd.sheet_export_bend_table": "Eksportér bukketabel", "cmd.sheet_export_dxf": "Eksportér udfoldning som DXF", @@ -848,6 +1125,7 @@ "cmd.sheet_fold": "Buk", "cmd.sheet_hem": "Ombukning", "cmd.sheet_manage_rules": "Pladeregler", + "cmd.sheet_path_flange": "Flange langs bane", "cmd.sheet_perforate": "Perforér", "cmd.sheet_refold": "Buk tilbage", "cmd.sheet_rules": "Vis pladeregler", @@ -862,6 +1140,7 @@ "cmd.sketch.construction_line.tangent_external": "Tangent gennem eksternt punkt", "cmd.sketch.construction_line.tangent_two": "Fælles tangent", "cmd.sketch.construction_line.vertical": "Lodret hjælpelinje", + "cmd.sketch_arc3d": "3D-bue", "cmd.sketch_arc_center_point": "Bue med centrum", "cmd.sketch_arc_tangent": "Tangentbue", "cmd.sketch_arc_three_point": "Trepunktsbue", @@ -890,8 +1169,11 @@ "cmd.sketch_drag": "Træk skitsegeometri", "cmd.sketch_drag_end": "Afslut flytning af skitsen", "cmd.sketch_draw_dimensioned": "Tegn målsat skitsegeometri", + "cmd.sketch_drawing_bounds": "Tegningsstørrelse", "cmd.sketch_edit": "Redigér skitse", "cmd.sketch_edit_text": "Redigér tekst", + "cmd.sketch_equation_curve": "Ligningskurve", + "cmd.sketch_equation_curve_edit": "Redigér ligningskurve", "cmd.sketch_export_dxf": "Gem som DXF", "cmd.sketch_finish_auto_constrain": "Afslut med automatisk binding", "cmd.sketch_fit_curves_to_section": "Tilpas kurver til snit i mesh", @@ -934,9 +1216,13 @@ "cmd.sketch_spline_control_point": "Spline med kontrolpunkter", "cmd.sketch_spline_control_point_5": "Spline med kontrolpunkter (grad 5)", "cmd.sketch_spline_fit_point": "Spline gennem punkter", + "cmd.sketch_spline_insert_point": "Tilføj splinepunkt", + "cmd.sketch_spline_remove_point": "Fjern splinepunkt", "cmd.sketch_spline_reverse": "Vend splinens retning", "cmd.sketch_spun_profile": "Omdrejningsprofil", + "cmd.sketch_toggle_diameter": "Skift mellem radius og diameter", "cmd.sketch_toggle_driven": "Skift mellem styrende og afledt mål", + "cmd.sketch_transform": "Transformér", "cmd.sketch_trim_path": "Trim langs bane", "cmd.solid_align": "Justér", "cmd.solid_boundary_fill": "Afgrænset udfyldning", @@ -974,28 +1260,71 @@ "cmd.timeline_export_script": "Eksportér kommandoscript", "cmd.timeline_inspect": "Undersøg feature", "cmd.timeline_paste": "Indsæt features", + "cmd.timeline_play": "Afspil historik", "cmd.timeline_redefine": "Redigér feature", "cmd.timeline_rename": "Omdøb", "cmd.timeline_reorder": "Flyt feature i rækkefølgen", "cmd.timeline_roll_to": "Flyt tilbagerulningsmarkør", "cmd.timeline_rollback": "Flyt tilbagerulningsmarkør", + "cmd.timeline_stop": "Stop historik", "cmd.timeline_suppress": "Undertryk feature", + "cmd.ui.assistant": "Vis/skjul assistent", + "cmd.view.render_browser": "Renderingsbrowser", + "cmd.view.render_dock": "Flyt renderingsdock", + "cmd.view.render_focus": "Fokusvisning af rendering", + "cmd.view.status_details": "Detaljer om visningsområdets status", + "cmd.view.status_items": "Statuselementer i visningsområdet", "cmd.view_ambient_occlusion": "Ambient occlusion", + "cmd.view_angle_readout": "Visningsvinkler", "cmd.view_apply": "Gendan navngiven visning", + "cmd.view_back": "Visning bagfra", + "cmd.view_bottom": "Visning nedenfra", "cmd.view_delete": "Slet navngiven visning", + "cmd.view_fit": "Tilpas", + "cmd.view_front": "Visning forfra", "cmd.view_graphics_preset": "Grafikprofil", + "cmd.view_grid": "Gitter", + "cmd.view_ground_shadow": "Skygge på grundplan", + "cmd.view_home": "Hjemmevisning", + "cmd.view_isometric": "Isometrisk visning", + "cmd.view_left": "Visning fra venstre", "cmd.view_list": "Vis navngivne visninger", "cmd.view_navigate": "Navigér i visning", + "cmd.view_navigation_bar": "Navigationslinje", + "cmd.view_next_tab": "Næste fane", "cmd.view_normal_to": "Vinkelret på markering", + "cmd.view_previous_tab": "Forrige fane", "cmd.view_rename": "Omdøb navngiven visning", + "cmd.view_render_frame": "Hjælpelinjer til billedudsnit", + "cmd.view_right": "Visning fra højre", "cmd.view_save": "Ny navngiven visning", + "cmd.view_shots_strip": "Optagelsesstrimmel", + "cmd.view_spin": "Kontinuerlig rotation af visningen", + "cmd.view_tool": "Navigationsværktøj", + "cmd.view_top": "Visning ovenfra", + "cmd.view_visual_style": "Visuel stil", + "color.blue": "Blå", "color.copy": "Klik for at kopiere farveværdier", "color.edit": "Klik for at redigere farve", "color.gamma": "Viser farveværdier i 0-255 gammarum", + "color.green": "Grøn", + "color.hex": "Hex", + "color.hex_help": "Angiv #rrggbb eller #rrggbbaa; seks cifre bevarer opaciteten", + "color.hex_hint": "#rrggbb", "color.hue": "Farvetone", "color.linear": "Viser farveværdier i 0-1 lineært rum", + "color.recent": "Seneste farver", + "color.recent_help": "Farver, du vælger i et farvefelt, vises her", + "color.red": "Rød", + "color.saturation": "Mætning (procent)", "color.saturation_value": "Mætning og værdi", "color.selected": "Valgt farve", + "color.step_down": "Ét trin ned", + "color.step_up": "Ét trin op", + "color.value": "Værdi, lysstyrken (procent)", + "config.column_filter_empty": "Ingen matchende kolonner", + "config.rule_parameter_columns": "Kun parametre med en kolonne i tabellen vises. Tilføj en kolonne med Tilføj kolonne (+) for at bruge parameteren her.", + "config.rule_suppression_columns": "Kun features med en Undertryk-kolonne i tabellen vises. Tilføj en kolonne med Tilføj kolonne (+) for at styre undertrykkelsen her.", "contact.components_count": "{count} komponenter", "contact.enabled_label": "aktiveret", "coupling.gear_1": "Tandhjul 1", @@ -1029,6 +1358,7 @@ "crash.report": "Rapportér…", "crash.unclean_explanation": "Registreret ved en senere opstart; det nøjagtige afslutningstidspunkt blev ikke noteret. Et systemnedlukning eller tvunget stop kan også give en uventet afslutning.", "delete.and_more": "… og {count} mere", + "diagnostic.empty_boolean_component": "der er intet emne at skære fra eller danne fællesvolumen med i komponenten '{component}'; værktøjet overlapper muligvis '{body}' i komponenten '{other}' — aktivér den komponent, eller vælg emnet som mål", "dialog.bodies_count": "Antal emner: {count}", "dialog.clearance_invalid": "afstanden skal være 0 eller større", "dialog.compute": "Beregn", @@ -1039,13 +1369,31 @@ "dialog.dimension_insert_hint": "Klik på et andet styrende mål for at indsætte dets navn", "dialog.dimension_name": "Mål: {name}", "dialog.edit_title": "REDIGÉR {title}", + "dialog.no_shown_body": "Intet vist emne at ændre: Vis et, eller vælg Nyt emne", + "dialog.pattern_sketch_not_object": "Vælg emner eller features: En skitse er ingen af delene. Gentag dens kurver med skitsens eget Mønster eller Spejling, eller ekstruder den først.", "dialog.select": "↖ Vælg", "dialog.selected_count": "↖ Valgte: {count}", + "dialog.selection_constraint": "Binding {id}", + "dialog.selection_external_curve": "{sketch} · kurve {id}", "dialog.selection_guidance": "Vælg et input for at ændre det. Klik på valgte objekter for at fjerne dem; Ctrl/Cmd-klik skifter også deres valgstatus. Gennemgå forhåndsvisningen, og tryk derefter på OK.", + "dialog.selection_midpoint": "Midtpunkt · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} af {total}: Vælg {input}", "dialog.step": "Trin", + "document.changed_on_disk": "{name} er ændret på disken", + "document.changed_on_disk_detail": "{name} er blevet ændret af et andet program eller en anden computer, siden du åbnede eller sidst gemte det. Overskriv erstatter de ændringer med dine; Gem en kopi beholder begge.", + "document.copy_name": "Kopi af {name}", + "document.open_anyway": "Åbn alligevel", + "document.open_elsewhere": "{name} er allerede åbent", + "document.open_elsewhere_detail": "{name} er åbent i SolidCraft {app} på {who}, åbnet {when}. Hvis I begge gemmer, mister en af jer arbejde. Åbn det skrivebeskyttet for at se på det uden at gemme oven i det.", + "document.open_read_only": "Åbn skrivebeskyttet", + "document.opened_read_only": "Åbnet skrivebeskyttet: Gem beder om en ny fil", + "document.overwrite": "Overskriv", + "document.read_only_save": "Dette design blev åbnet skrivebeskyttet: Gem det som en ny fil", "document.save_changes": "Gem ændringer i {name}?", + "document.save_copy": "Gem en kopi…", "document.unsaved_changes": "{name} har ændringer, der ikke er gemt. De går tabt, hvis du ikke gemmer.", + "drive.rigid": "{joint} er et stivt led: Det holder sine dele fast, så der er intet at bevæge. For at lade dem bevæge sig skal du ændre ledtypen i Redigér led: Drejeled for at dreje, Glideled for at glide, Cylinderled for begge dele.", "drive.stopped_by_contact": "Stoppet ved {value}: {a} ville gå gennem {b}", "drive.stopped_by_loop": "Stoppet ved {value}: Løkken gennem {joint} kan ikke lukkes yderligere", "drive.unconnected": "Flytter intet: {part} er ikke forbundet til noget fastgjort", @@ -1061,9 +1409,13 @@ "dxf.progress.write": "Skriver DXF (5/5)", "dxf.tolerance": "Kurvetolerance", "dxf.tolerance_help": "Kun synlige emner og viste skitser. Kurver består af rette linjestykker. En mindre tolerance giver finere kurver og kræver mere tid og hukommelse.", + "each rail's curves must be in one sketch": "hver styrekurves kurver skal ligge i én skitse", + "feature computation ended without a result": "beregningen af featuren sluttede uden et resultat", + "file.open.drawing_filter": "Designs, CAD-filer, meshes og tegninger", "file_load.built": "Bygget indtil videre: {built} af {total} features.", "file_load.converting": "Konverterer solid {done} af {total}", "file_load.inserting": "Indsætter geometri", + "file_load.link_item": "{name} ({done} af {total})", "file_load.opening": "Åbner design", "file_load.preparing_thumbnail": "Forbereder miniaturebillede...", "file_load.preparing_view": "Forbereder visningen...", @@ -1073,25 +1425,335 @@ "file_load.rebuilding": "Genopbygger feature {done} af {total}", "file_load.recovering": "Genopretter design", "file_load.stopping": "Venter på, at den forrige handling stopper...", + "file_load.updating_links": "Opdaterer forbindelser", "file_load.waiting": "Venter på filhandling", "fits the face, e.g. M8": "passer til fladen, f.eks. M8", "from the profile": "fra profilen", "from the rule": "fra reglen", "help.apache": "Apache-licens 2.0", + "help.appearance.assign": "Udseende giver de valgte emner, flader eller komponenter en farve eller et materialeudseende uden at ændre deres vægt. Brug det til at skelne dele fra hinanden eller til at se en overflade på forhånd.", + "help.assembly.bom": "Viser delene i designet eller en komponent med deres antal efter varenummer og kan gemme listen som CSV eller JSON. Brug den som stykliste til indkøb og montage.", "help.attributions": "Tilskrivninger (ATTRIBUTION.md)", "help.build": "Version {version} · commit {commit} · bygget {date}", + "help.canvas.decal": "Placerer et billede på en plan flade af modellen som en dekal. Brug den til at vise en etiket, et logo eller et trykt mønster på en del.", + "help.canvas.edit": "Ændrer et referencebillede: dets position, størrelse, vinkel, opacitet, spejling, synlighed eller navn. Brug den til at lægge et referencebillede op ad den skitse, du tegner efter.", + "help.canvas.insert": "Placerer et PNG- eller JPEG-billede på et plan eller en flade som gennemsigtig reference. Brug den til at tegne efter et foto eller en tegning i en skitse, hvor billedet er skaleret til en kendt størrelse.", + "help.component.break_link": "Løsriver en linket komponent fra dens designfil, så emnerne beholdes, som de er. Brug den, når delen ikke længere skal følge ændringer i originalfilen.", + "help.component.capture_position": "Registrerer positionerne af dele, du har flyttet i hånden, så de bliver delenes placering. Brug den, når du har trukket dele på plads, som intet led holder fast.", + "help.component.create": "Tilføjer en ny, tom komponent til designet inde i den aktive komponent, medmindre du vælger en anden overordnet komponent. Brug den til at give en ny del af en samling sin egen plads til emner og skitser.", + "help.component.finish_edit": "Afslut redigering gemmer den del, du redigerer på stedet, vender tilbage til dens samling og opdaterer samlingen ud fra den. Brug den, når dine ændringer af den tilknyttede del er færdige.", + "help.component.from_bodies": "Gør hvert valgt emne til sin egen komponent opkaldt efter emnet. Brug den, når et design bygget af løse emner skal blive en samling, hvis dele kan forbindes og flyttes.", + "help.component.insert_design": "Indsætter et andet gemt design som en komponent, der er linket til dets fil, med dets massive emner placeret som i originalen. Brug den til at genbruge en del i en samling og hente senere ændringer med Opdatér forbindelser.", + "help.component.properties": "Viser volumen, masse, massecentrum og inertimomenter for en komponent ud fra emnernes materialer. Brug den til at kontrollere vægt og balance for en samling.", + "help.component.revert_position": "Sætter dele, du har flyttet i hånden, tilbage, hvor de var, og kasserer flytninger, der ikke er registreret. Brug den til at fortryde prøveflytninger i en samling.", + "help.component.update_links": "Læser de linkede designfiler igen og erstatter emner, der er ændret. Brug den, når du har redigeret en del, som samlingen bruger.", + "help.config.configure": "Tilføjer parametre, features, materialer eller udseender som kolonner i konfigurationstabellen. Brug den til at lave varianter af ét design, f.eks. størrelser af en del.", + "help.config.preview": "Kontrollerer, at en række i konfigurationstabellen kan genopbygges, uden at designet eller dets historik ændres. Brug den, før du skifter til en variant, du er i tvivl om.", + "help.config.rules": "Viser konfigurationstabellens regler, dens rækker og hvilken række der er aktiv. Brug den til at se, hvordan et designs varianter er sat op.", + "help.config.table": "Viser konfigurationstabellen: én række pr. variant, én kolonne pr. parameter eller feature og om designet stadig svarer til den aktive række. Brug den til at gennemgå et designs varianter.", + "help.connect_note": "Genstart hver assistent for at indlæse SolidCraft-serveren. Hver fil blev sikkerhedskopieret som .bak, før den blev ændret.", + "help.connect_title": "Forbind AI-assistenter", + "help.construct.axis.edge": "Opretter en konstruktionsakse langs en ret kant eller skitselinje. Brug den som akse til en omdrejning, et cirkulært mønster eller et led.", + "help.construct.axis.normal_to_face": "Opretter en konstruktionsakse gennem et punkt, vinkelret på en flade. Brug den som en akse, der står lige ud fra en overflade.", + "help.construct.axis.through_cylinder": "Opretter en konstruktionsakse gennem midten af en cylinder-, kegle- eller torusflade eller en cirkulær kant. Brug den til at dreje eller gentage features omkring en rund del.", + "help.construct.axis.two_planes": "Opretter en konstruktionsakse, hvor to planer eller plane flader mødes. Brug den, når den ønskede akse er linjen mellem to flader.", + "help.construct.axis.two_points": "Opretter en konstruktionsakse gennem to punkter, hjørnepunkter eller skitsepunkter. Brug den til en akse mellem to kendte positioner.", + "help.construct.plane.along_path": "Opretter et konstruktionsplan vinkelret på en kant eller kurve i en given position langs den. Brug det til at skitsere en profil til et sweep eller et snit af en bane.", + "help.construct.plane.at_angle": "Opretter et konstruktionsplan, der er drejet med en vinkel fra et plan eller en flade omkring en akse eller kant. Brug det til skrå skitser, f.eks. et vinklet beslag.", + "help.construct.plane.axis_point": "Opretter et konstruktionsplan, der indeholder en akse og et punkt uden for aksen. Vælg en akse fra nulpunktet eller en konstruktionsakse, en ret kant eller skitselinje og derefter et hjørnepunkt, skitsepunkt eller konstruktionspunkt. Et punkt på aksen kan ikke definere et entydigt plan.", + "help.construct.plane.midplane": "Opretter et konstruktionsplan midt mellem to planer eller plane flader eller halverende dem, hvor de mødes i en vinkel. Brug det som symmetriplan til spejling.", + "help.construct.plane.offset": "Opretter et konstruktionsplan parallelt med et plan eller en plan flade i en afstand eller gennem et punkt. Brug det til at skitsere i en bestemt højde over en flade.", + "help.construct.plane.perpendicular": "Opretter et konstruktionsplan, der indeholder en linje eller kant og står vinkelret på et plan eller en flade. Brug det til at skitsere opretstående på en model langs en kant.", + "help.construct.plane.tangent": "Opretter et konstruktionsplan, der berører en cylinder, kegle, kugle eller torus i et punkt. Brug det til at skitsere på siden af en rund del.", + "help.construct.plane.three_points": "Opretter et konstruktionsplan gennem tre punkter. Brug det til et plan, der er givet ved positioner på modellen, f.eks. tre hjørner.", + "help.construct.plane.two_edges": "Opretter et konstruktionsplan gennem to rette kanter eller linjer, der ligger i samme plan. Brug det til et plan på tværs af en del, f.eks. gennem to modstående kanter.", + "help.construct.point.along_path": "Opretter et konstruktionspunkt i en position langs en kant eller kurve. Brug det som reference et stykke henne ad en bane.", + "help.construct.point.center": "Opretter et konstruktionspunkt i midten af en cirkulær kant, en skitsecirkel eller -bue, en kugle eller en torus. Brug det som reference til huller, akser og led.", + "help.construct.point.edge_plane": "Opretter et konstruktionspunkt, hvor en kant eller linje skærer et plan eller en plan flade. Brug det til at markere, hvor en bane krydser et plan.", + "help.construct.point.three_planes": "Opretter et konstruktionspunkt, hvor tre planer eller plane flader mødes. Brug det som hjørnereference, også hvor modellen ikke har noget hjørnepunkt.", + "help.construct.point.two_edges": "Opretter et konstruktionspunkt, hvor to kanter eller linjer mødes eller kommer tættest på hinanden. Brug det som reference i et virtuelt hjørne.", + "help.construct.point.vertex": "Opretter et konstruktionspunkt på et hjørnepunkt eller skitsepunkt. Brug det som reference, der bliver stående, selv om skitsen eller emnet omkring det skjules.", + "help.contact.check": "Viser de par af dele i kontaktsæt, der går gennem hinanden i deres nuværende position. Brug den til at finde kollisioner, før du bevæger led eller kører en bevægelsesanalyse.", + "help.contact.create": "Samler to eller flere dele i et kontaktsæt, hvis emner holdes fra at gå gennem hinanden, mens led bevæger sig. Brug den til dele, der skal stoppe, når de rører hinanden, f.eks. et håndtag mod sit anslag.", + "help.contact.disable_all": "Slår kontakt fra, så ledbevægelser og bevægelsesanalyser ikke længere stopper, hvor dele rører hinanden. Brug den til at flytte dele frit igen eller til at holde en stor samling responsiv.", + "help.contact.edit": "Ændrer et kontaktsæt: de dele, det indeholder, dets navn eller om det er undertrykt; det kan også slette sættet. Brug den til at justere, hvilke dele der holdes fra at gå gennem hinanden.", + "help.contact.enable_all": "Lægger alle samlingens dele i ét kontaktsæt, så ingen to dele kan gå gennem hinanden, mens led bevæger sig. Brug den til et hurtigt tjek af en hel mekanisme.", + "help.contact.enable_sets": "Slår kontakt til for de kontaktsæt, du har defineret, så ledbevægelser og bevægelsesanalyser stopper, hvor deres dele ville gå gennem hinanden. Brug den til at få dine sæt tilbage, efter at du har slået kontakt fra.", + "help.contact.list": "Viser designets kontaktsæt, delene i hvert af dem og om kontakt er slået til. Brug den til at se, hvordan kontakt er sat op, før du bevæger samlingen.", + "help.document.inspect": "Viser et overblik over designet: dets komponenter, emner, skitser, features og parametre. Brug den til at finde rundt i et design, du ikke selv har bygget.", + "help.document.units": "Ændrer de enheder, designet viser længder i, f.eks. mm eller tommer. Geometrien beholder sin størrelse; kun visningen og almindelige tal følger med.", + "help.edit.checkpoint": "Husker designet, den aktive skitse og fortrydelseshistorikken, som de er nu. Brug den, før du prøver noget risikabelt, som du måske vil gå tilbage fra.", + "help.edit.restore_checkpoint": "Går tilbage til et kontrolpunkt, inklusive fortrydelseshistorikken. Brug den til at kassere alt, der er gjort siden kontrolpunktet, i ét trin.", + "help.explode.create": "Opretter en eksploderet visning, der skubber delene væk fra samlingens midte eller med de flytninger, du angiver. Brug den til at vise, hvordan en samling sættes sammen, til vejledninger eller præsentationer.", + "help.face.delete": "Slet flade fjerner de valgte flader og lader de omkringliggende flader lukke åbningen, eller lader åbningen stå åben som en overflade. Brug den til at fjerne en afrundet kant, et hul eller en forhøjning, der er i vejen.", + "help.file.insert_mesh": "Tilføjer en 3MF-, STL-, OBJ-, PLY- eller glTF-fil til designet som meshlegemer i en ny komponent. Brug den til at placere en hentet eller scannet model ved siden af dit design som reference.", + "help.file.insert_step": "Tilføjer en STEP-, IGES-, FreeCAD- eller Rhino-fil til designet som massive emner i en ny komponent; en samlings dele bliver til indlejrede komponenter. Brug den til at hente modeller fra leverandører eller andre CAD-programmer.", + "help.file.save_mesh": "Gemmer emner som et STL-, 3MF- eller OBJ-mesh med den glathed af buede flader, du vælger. Brug den til at klargøre dele til 3D-print eller til programmer, der læser mesh.", + "help.file.send_to_slicer": "Gemmer de valgte emner som en 3MF-fil og åbner den i den slicer, du vælger. Brug den til at gå fra modellen til print i ét trin.", "help.font_details": "Brugerfladen bruger egui's indbyggede skrifttyper (Ubuntu Light og Hack, under Ubuntu Font Licence og MIT/Bitstream Vera-licensen; Noto Emoji og emoji-ikonskrifttypen, under OFL og MIT). Skitsetekst bruger Liberation Sans (SIL OFL 1.1). Crafting Apps' valgfrie skrifttypepakke, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), er ikke inkluderet i SolidCraft-builds.", "help.fonts": "Skrifttyper", + "help.frame.member": "Placerer en profil, f.eks. et rør eller en aluminiumsprofil, langs linjerne i en rammeskitse, ét element pr. linje. Brug den til at bygge rammer, stativer og svejste konstruktioner.", + "help.inspect.accessibility": "Farver de flader, et værktøj kan nå fra én retning, og dem, det ikke kan. Brug den til at kontrollere en del for bearbejdning eller støbning fra den side.", + "help.inspect.center_of_mass": "Viser massecentrum for emner, hvert for sig og alle samlet, ved ensartet massefylde. Brug den til at kontrollere balance og hvor en del vil vælte.", + "help.inspect.colored_components": "Giver hver komponent sin egen midlertidige farve uden at ændre udseender. Brug den til at kende delene i en samling fra hinanden med et enkelt blik.", + "help.inspect.compare": "Sammenligner to emner og viser, hvor det ene har materiale, som det andet ikke har, med volumen og afvigelse. Brug den til at kontrollere en ændret eller importeret del mod originalen.", + "help.inspect.continuity": "Kontrollerer, hvor glat flader mødes langs deres kanter: åbninger, knæk eller spring i krumning, og farver overgangene. Brug den til at finde steder, hvor overflader ikke går rent sammen.", + "help.inspect.curvature_comb": "Tegner kamme langs kurver, kanter eller flader, hvis tænder viser, hvor kraftigt de krummer. Brug den til at spotte flade steder, knæk og ujævn krumning.", + "help.inspect.curvature_map": "Farver flader efter, hvor kraftigt de krummer, rødt hvor radius er lille. Brug den til at finde snævre steder og vurdere, hvor glat en overflade er.", + "help.inspect.draft": "Farver flader efter deres slipvinkel i forhold til en udtræksretning og markerer dem med for lidt. Brug den til at kontrollere en del før sprøjtestøbning eller støbning.", + "help.inspect.environment_map": "Viser modellen med en reflekterende, spejlagtig finish. Brug den til at vurdere overfladernes forløb ud fra, hvordan refleksionerne løber hen over dem.", + "help.inspect.interference": "Finder emner, der overlapper, og viser hvert overlap med dets volumen. Brug den til at kontrollere en samling for dele, der støder sammen.", + "help.inspect.isocurve": "Tegner isoparametriske kurver på flader, det gitter overfladen er bygget på. Brug den til at se, hvordan en overflade forløber, og hvor kurverne samler sig.", + "help.inspect.measure": "Måler længder, afstande, vinkler, arealer og radier mellem det, du vælger, eller volumen og masse af emner. Brug den til at kontrollere størrelser og frigang.", + "help.inspect.minimum_radius": "Finder den mindste krumningsradius på kurver, kanter eller flader og hvor den er. Brug den til at kontrollere, at et værktøj eller en dyse kan følge formen.", + "help.inspect.section": "Skærer visningen op langs et plan og skraverer de snittede flader uden at ændre modellen. Brug den til at kigge ind i dele og samlinger.", + "help.inspect.zebra": "Viser sorte og hvide striber reflekteret på modellens flader. Brug den til at vurdere glathed: Striber, der knækker eller brydes ved en kant, viser en dårlig overgang.", + "help.joint.as_built": "Forbinder to dele, hvor de allerede er, uden at flytte nogen af dem, og angiver, hvordan de stadig må bevæge sig. Brug den til dele, du allerede har placeret i deres endelige position.", + "help.joint.cam": "Forbinder en roterende knast med en følger, så følgeren glider eller svinger, når knastens kontur passerer under den. Brug den til knaster, excentre og ventildrev.", + "help.joint.create": "Forbinder to dele ved de lednulpunkter, du vælger, og flytter den anden del på plads; ledtypen bestemmer, hvordan de stadig må bevæge sig. Brug den til at bygge en samling, hvis dele bevæger sig som den virkelige mekanisme.", + "help.joint.drive": "Sætter et leds vinkel eller afstand og bevæger delene med, inden for dets grænser; forbundne led og lukkede sløjfer følger med. Brug den til at kontrollere, at en mekanisme bevæger sig som tilsigtet.", + "help.joint.gear": "Forbinder to roterende led med et tandhjulsforhold, så drejning af det ene drejer det andet. Brug den til ligetandede tandhjul og ringhjul, med forholdet ud fra delecirkelradier eller tandantal.", + "help.joint.limits": "Angiver, hvor langt et led må dreje eller glide, som minimum og maksimum, eller fjerner grænserne. Brug den til at holde et hængsel, et glideled eller et håndtag inden for dets virkelige bevægelsesområde.", + "help.joint.motion_link": "Kobler to led med et forhold og en forskydning, så bevægelse af det ene flytter det andet. Brug den til en fast sammenhæng mellem led, som Tandhjul, Tandstang og tandhjul eller Skrue ikke dækker.", + "help.joint.origin": "Placerer et navngivet lednulpunkt på en del: i midten af en flade eller rund ende, midt på en kant, i et hjørne eller i et punkt. Brug den til at forberede, hvor led sættes fast; et nulpunkt valgt på en flade følger den, når delen ændrer størrelse.", + "help.joint.rack_pinion": "Forbinder et roterende tandhjul med en glidende tandstang, så tandstangen flytter sig lige så langt, som tandhjulets delecirkel ruller. Brug den til tandstangsdrev, styretøj og lineære slæder.", + "help.joint.reach": "Flytter et punkt på en del mod et mål ved at ændre leddene i dets kæde inden for deres grænser. Brug den til at stille en mekanisme ind efter, hvor dens ende skal være, f.eks. spidsen af en robotarm.", + "help.joint.rigid_group": "Låser de valgte dele sammen, som de er, så de bevæger sig som én. Brug den til dele, der hører sammen og ikke skal have nogen bevægelse mellem sig.", + "help.joint.screw": "Forbinder drejning og glidning ved hjælp af en stigning, så hver omdrejning flytter delen så langt. Brug den til ledeskruer, bolte og gevindspindler.", + "help.library.apply": "Anvender et materiale eller udseende fra en lokal biblioteksfil på emner, flader eller komponenter. Brug den til at genbruge materialer, du har gemt fra et andet design.", + "help.library.export": "Gemmer designets materialer og udseender i en biblioteksfil. Brug den til at dele dem eller genbruge dem i andre designs.", + "help.library.inspect": "Kontrollerer en biblioteksfil og viser dens materialer og udseender uden at ændre designet. Brug den til at se, hvad et bibliotek indeholder, før du anvender det.", "help.licences": "Licenser", + "help.material.assign": "Fysisk materiale angiver, hvad de valgte emner er lavet af, f.eks. stål, aluminium eller ABS. Brug det, så masse og vægt svarer til den virkelige del.", + "help.material.properties.validate": "Kontrollerer et materialedatakort for konsistente tal og manglende værdier. Brug den, før du støtter dig til dataene for masse eller stivhed.", + "help.mesh.convert": "Genopbygger et meshlegeme, f.eks. en STL, som et redigerbart massivt emne med plane og cylindriske flader. Brug den til at ændre importerede mekaniske dele som et modelleret emne.", "help.mit": "MIT-licens", + "help.motion.study": "Sætter ledværdier i trin langs en tidslinje og afspiller dem som en animation. Brug den til at se en mekanisme bevæge sig gennem en sekvens og kontrollere frigang undervejs.", + "help.motion.trace": "Sporer den bane, et punkt på en del følger, mens en bevægelsesanalyse afspilles, eller et led bevæges, og beholder den som en 3D-skitsekurve, når du bekræfter. Brug den til at se, hvor en mekanisme når hen, eller til at bygge videre på dens bane.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fastgør en del på plads eller frigør den igen, så led flytter de andre dele rundt om den. Brug den til stellet eller basen, som resten af samlingen er bygget på.", + "help.occurrence.move": "Flyt komponentforekomst flytter en del i samlingen kun langs de frihedsgrader, som dens led tillader. Vælg en flade på delen, og træk derefter i en tilgængelig pil eller bue.", + "help.parameters.change": "Redigér parametre åbner tabellen med navngivne værdier og udtryk, der styrer designets mål. Brug den til at ændre en størrelse ét sted, så alle features, der bruger den, følger med.", + "help.parameters.export": "Gemmer designets parametre som CSV eller JSON. Brug den til at redigere dem i et regneark eller flytte dem til et andet design.", + "help.parameters.graph": "Viser, hvilke parametre og features der bruger hvilke andre, og eventuelle sløjfer eller fejl imellem dem. Brug den til at se, hvad en ændring af en parameter vil påvirke.", + "help.parameters.import": "Læser parametre fra CSV eller JSON ind i designet, enten alle eller ingen. Brug den til at hente værdier fra et regneark eller et andet design.", + "help.parameters.move": "Flytter en brugerparameter før eller efter en anden på listen. Brug den til at holde beslægtede parametre samlet.", + "help.parts.fastener": "Tilføjer en standardskrue, bolt, møtrik, skive, stift eller leje i den størrelse, du vælger. Placeret på et hul sidder den fast i hullet med et led, så du ikke selv skal modellere befæstelseselementer.", + "help.parts.insert": "Indsætter en standarddel i den familie, størrelse og længde, du vælger. Placeret på kanten eller væggen af et hul sidder den fast på hullet med et stivt led.", + "help.parts.library": "Åbner standarddelene: skruer, bolte, møtrikker, skiver, stilleskruer, dyvler og lejer i standardstørrelser. Brug den til at tilføje en standarddel i stedet for selv at modellere den.", + "help.parts.resize": "Ændrer størrelsen eller længden af en indsat standarddel og genopbygger den; dens led holder den på plads. Brug den, når en skrue viser sig at være for lang, eller et hul skal have en anden størrelse.", + "help.plastic.assign_rule": "Tildeler en plastregel til emner, så deres plastfeatures bruger dens slipvinkel og frigang som standard. Brug den til at sætte en sprøjtestøbt del op én gang for alle dens features.", + "help.plastic.boss": "Tilføjer en skruebøsning på en flade: en søjle med valgfrit hul, slipvinkel, afrunding i foden og understøttende ribber. Brug den til skruepunkter i sprøjtestøbte eller printede kabinetter.", + "help.plastic.lip": "Tilføjer en læbe eller en tilhørende not langs kanten af et udhulet emne. Brug den, så to kabinethalvdele passer ind i hinanden og lukker tæt.", + "help.plastic.manage_rules": "Opretter og redigerer plastregler: materiale, vægtykkelse, radier, frigang og slipvinkel. Brug dem til at holde features på en sprøjtestøbt del ensartede.", + "help.plastic.rest": "Tilføjer en understøtning på en flade: en rund eller rektangulær pude, massiv eller hul, med slipvinkel. Brug den som støtte eller afstandsstykke i et sprøjtestøbt kabinet.", + "help.plastic.snap_fit": "Tilføjer en snapkrog på en flade med dens længde, tykkelse og hage. Brug den til at klikke dele sammen uden skruer.", + "help.pointcloud.insert": "Indsæt en PLY-, XYZ- eller PTS-scanning som en punktsky ved siden af modellen. Brug den som reference, når du bygger en model ud fra målte data.", + "help.sheet.convert": "Gør en flad plade eller et udhulet emne med ensartet tykkelse til et pladelegeme med bukninger ved de kanter, du vælger. Brug den til at gøre en eksisterende del udfoldelig.", + "help.sheet.export_bend_table": "Gemmer bukketabellen for et pladelegeme som CSV eller JSON: vinkler, radier og bukkepositioner i udfoldningen. Brug den til kantpressen eller værkstedet.", + "help.sheet.export_dxf": "Gemmer udfoldningen som DXF med konturer, bukkelinjer og valgfrie bukkenoter. Brug den til laser-, plasma- eller vandskæring.", + "help.sheet.flange": "Tilføjer en flange: en basisplade ud fra en skitse, en væg langs en åben skitsekontur eller en bukket væg på pladens kanter. Brug den til at opbygge pladedele.", + "help.sheet.flat_pattern": "Opretter udfoldningen af et pladelegeme med dets størrelse, udskæringer og bukkelinjer. Brug den til at kontrollere tilskæringen, før du skærer den ud.", + "help.sheet.fold": "Bukker en plade langs en skitselinje med en vinkel og radius. Brug den til at folde en flad plade, efter at du har skåret features i den.", + "help.sheet.hem": "Ombukker en pladekant over sig selv. Brug den til sikre, stive kanter uden skarpe grater.", + "help.sheet.manage_rules": "Opretter og redigerer pladeregler: tykkelse, bukkeradius, K-faktor, aflastninger og mellemrum. Brug dem til at tilpasse materialet og værktøjerne på dit værksted.", + "help.sheet.path_flange": "Tilføjer en kæde af flanger langs en pladekant efter en åben kæde af skitselinjer. Brug den til profiler som en U- eller Z-form i ét trin.", + "help.sheet.perforate": "Tilføjer et felt af huller over hele den flade plade i et forskudt eller kvadratisk mønster. Brug den til ventilationsåbninger, riste og lettere paneler.", + "help.sheet.refold": "Bukker et udfoldet pladelegeme sammen igen. Brug den, når du har tilføjet features til den flade plade.", + "help.sheet.unfold": "Folder alle bukninger i et pladelegeme ud. Brug den til at tilføje huller eller udskæringer, der skal krydse en bukning, og buk derefter tilbage.", + "help.sketch.arc.center_point": "Tegner en cirkelbue omkring et centrumpunkt fra et startpunkt til et slutpunkt. Brug den, når buens centrum er kendt, f.eks. en radius omkring et hul eller en omdrejningstap.", + "help.sketch.arc.tangent": "Tegner en bue, der starter ved enden af en linje eller bue og fortsætter tangentielt til den. Brug den til at føre en kæde videre med en blød bøjning i stedet for et hjørne.", + "help.sketch.arc.three_point": "Tegner en bue fra et startpunkt til et slutpunkt gennem et tredje punkt. Brug den, når buen skal gå gennem givne punkter i stedet for omkring et kendt centrum.", + "help.sketch.arc3d": "Tegner en nøjagtig cirkelbue i rummet gennem tre punkter, med 3D-skitse slået til. Brug den til bøjninger i baner og styrekurver, der forlader skitseplanet.", + "help.sketch.auto_constrain": "Tilføjer de bindinger, skitsen næsten allerede har, f.eks. vandret, parallel eller sammenfaldende, og målsætter den derefter, til den er fuldt bundet. Brug den til at låse en groft tegnet skitse i ét trin.", + "help.sketch.auto_constrain_from_datum": "Virker som Automatisk binding, men måler positionerne fra et referencepunkt, du vælger, i stedet for nulpunktet. Brug den, når delen er tegnet ud fra ét referencepunkt, f.eks. et hjørne eller et hul.", + "help.sketch.blend_curve": "Forbinder enderne af to kurver med en glat spline, der er tangent til begge, eller også krumningskontinuert, hvis du vælger det. Brug den til at bygge bro over et mellemrum mellem kurver uden knæk.", + "help.sketch.break": "Deler en kurve i stykker, hvor andre kurver krydser den, eller i punkter, du placerer på den. Brug den, når en del af en kurve skal have sin egen binding eller slettes for sig.", + "help.sketch.cancel": "Forlader skitsen og kasserer alt, der er ændret, siden den blev oprettet eller åbnet til redigering. Fortryd bringer ændringerne tilbage.", + "help.sketch.centerline": "Skifter linjer mellem normale linjer og centerlinjer, akser som profiler ikke tager med. Brug en centerlinje som akse til en omdrejning, en spejling eller en symmetribinding.", + "help.sketch.chamfer.distance_angle": "Affaser hjørnet mellem to linjer, angivet ved en afstand langs den første linje og en vinkel. Brug den, når en tegning angiver affasningen som en længde og en vinkel, f.eks. 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Affaser hjørnet mellem to linjer med samme afstand tilbage langs begge. Brug den til den sædvanlige 45°-affasning på en kontur.", + "help.sketch.chamfer.two_distance": "Affaser hjørnet mellem to linjer, angivet ved en separat afstand langs hver linje. Brug den til affasninger, der ikke er 45°, angivet som to længder.", + "help.sketch.circle.center": "Tegner en cirkel ud fra dens centrum og diameter. Brug den til huller, bøsninger og andre runde features, hvor centrum er kendt.", + "help.sketch.circle.three_point": "Tegner en cirkel gennem tre punkter. Brug den, når cirklen skal gå gennem givne punkter, f.eks. på eksisterende geometri.", + "help.sketch.circle.three_tangent": "Tegner en cirkel, der berører tre linjer, cirkler eller buer. Brug den til at passe en cirkel ind i rummet mellem tre kurver, f.eks. den indskrevne cirkel i en trekant.", + "help.sketch.circle.two_point": "Tegner en cirkel ud fra de to ender af dens diameter. Brug den, når cirklens kantpunkter er kendt frem for dens centrum.", + "help.sketch.circle.two_tangent": "Tegner en cirkel af en given størrelse, der berører to linjer, cirkler eller buer. Brug den til en afrunding med fast radius mellem to kurver.", + "help.sketch.conic": "Tegner en keglesnitskurve mellem to endepunkter, formet af et toppunkt og en rho-værdi. Brug den til bløde overgange, hvor du vil justere fylden, fra flad til næsten et skarpt hjørne.", + "help.sketch.constrainer": "Anvender den binding, som en eller to valgte kurver næsten allerede har, f.eks. vandret, parallel, tangent eller ens. Brug den til at rydde op i en håndtegnet skitse, én relation ad gangen.", + "help.sketch.constraint.coincident": "Får et punkt til at ligge på et andet punkt, en kurve eller en skitseakse. Brug den til at lukke åbninger i en profil eller til at lægge et punkt på en linje.", + "help.sketch.constraint.collinear": "Får to linjer til at ligge på samme rette linje. Brug den til at stille afbrudte kanter op, f.eks. begge sider af en udskæring.", + "help.sketch.constraint.concentric": "Giver to cirkler eller buer samme centrum. Brug den til ringe, forsænkninger og aksler med skuldre.", + "help.sketch.constraint.curvature": "Får to kurver, der mødes i et endepunkt, til at fortsætte med samme krumning (G2). Brug den, hvor en tangentforbindelse ikke er glat nok, f.eks. på synlige overflader.", + "help.sketch.constraint.equal": "Gør linjer lige lange eller cirkler og buer ens i radius. Brug den, så ét mål styrer flere tilsvarende features.", + "help.sketch.constraint.fix": "Låser punkter eller kurver fast, hvor de er, eller frigør dem igen. Brug den til geometri, der ikke må flytte sig, når du trækker i eller løser skitsen.", + "help.sketch.constraint.horizontal_vertical": "Gør en linje eller linjen mellem to punkter vandret eller lodret, alt efter hvad der er tættest på. Brug den til at rette en kontur ind efter skitsens akser.", + "help.sketch.constraint.midpoint": "Placerer et punkt midt på en linje eller får midtpunkterne af to linjer til at mødes. Brug den til at centrere geometri på en kant.", + "help.sketch.constraint.parallel": "Gør to linjer parallelle. Brug den til sider, der skal forblive parallelle, når andre mål ændres.", + "help.sketch.constraint.perpendicular": "Får to linjer til at mødes i en ret vinkel. Brug den til retvinklede hjørner mellem linjer, der ikke ligger på skitsens akser.", + "help.sketch.constraint.polygon": "Gør en lukket kæde af linjer til en regulær polygon: lige lange sider og alle hjørner på én cirkel. Brug den til at gøre en håndtegnet polygon regulær og holde den sådan.", + "help.sketch.constraint.symmetry": "Får to punkter eller kurver til at spejle hinanden over en linje eller omkring et punkt. Brug den til at holde en profil symmetrisk, når du ændrer den ene side.", + "help.sketch.constraint.tangent": "Får to kurver til at berøre hinanden tangentielt, f.eks. en linje og en bue. Brug den til bløde forbindelser uden knæk.", + "help.sketch.construction": "Skifter kurver mellem normal geometri og konstruktionsgeometri, som profiler ikke tager med. Brug konstruktionskurver som hjælp til layout, referencer og mål.", + "help.sketch.construction_line": "Opret en uendelig hjælpelinje gennem to punkter. Brug den til at lægge en skitse ud uden at dele profiler.", + "help.sketch.construction_line.angle": "Opret en uendelig hjælpelinje i en vinkel fra skitsens X-akse. Vælg punktet, og skriv vinklen, eller vælg dens retning.", + "help.sketch.construction_line.bisector": "Vælg to skærende rette skitselinjer, og vælg derefter en af vinkelhalveringslinjerne. Resultatet følger sine kildelinjer.", + "help.sketch.construction_line.horizontal": "Opret en uendelig vandret hjælpelinje gennem et punkt. Dens vandrette binding følger senere ændringer.", + "help.sketch.construction_line.parallel": "Vælg en ret skitselinje, og placér derefter en parallel uendelig hjælpelinje. Højreklik for at vælge en anden reference.", + "help.sketch.construction_line.perpendicular": "Vælg en ret skitselinje, og placér derefter en vinkelret uendelig hjælpelinje. Højreklik for at vælge en anden reference.", + "help.sketch.construction_line.tangent_at": "Opret en tangent i et punkt på en cirkel eller cirkelbue eller i endepunktet af en åben spline eller et keglesnit. Vælg kurven og derefter dens berøringspunkt.", + "help.sketch.construction_line.tangent_external": "Vælg en cirkel eller cirkelbue, derefter et eksternt punkt og en tangentløsning. Forhåndsvisningerne viser kun berøringspunkter på den tegnede bue.", + "help.sketch.construction_line.tangent_two": "Vælg to cirkler eller cirkelbuer, og vælg derefter en fælles tangent i forhåndsvisningen. Berøringspunkterne skal ligge på de tegnede kurver.", + "help.sketch.construction_line.vertical": "Opret en uendelig lodret hjælpelinje gennem et punkt. Dens lodrette binding følger senere ændringer.", + "help.sketch.copy": "Kopierer de valgte skitsekurver og -punkter sammen med bindingerne og målene imellem dem. Indsæt dem i denne skitse eller i en anden.", + "help.sketch.create": "Starter en ny 2D-skitse på et plan eller en plan flade på modellen. Enhver ekstrudering, omdrejning og sweep begynder med en skitse.", + "help.sketch.cut": "Kopierer den valgte skitsegeometri og sletter den fra skitsen i ét fortrydelsestrin. Indsæt den et andet sted i denne skitse eller i en anden.", + "help.sketch.dimension": "Tilføjer et styrende mål: en længde, afstand, vinkel, radius eller diameter, alt efter hvad du vælger. Skriv en værdi eller et parameternavn, og skitsen følger det.", + "help.sketch.edit": "Åbner en eksisterende skitse til redigering. De features, der er bygget på den, opdateres, når du afslutter skitsen.", + "help.sketch.ellipse": "Tegner en ellipse ud fra dens centrum, enden af dens storakse og et punkt på dens korte side. Brug den til ovale åbninger, knaster og andre aflange runde former.", + "help.sketch.equation_curve": "Ligningskurve tegner en kurve ud fra formler: x(t) og y(t) eller y = f(x) over et interval. Formlerne kan bruge parametre, og kurven følger dem. Brug den til en sinusbølge, en spiral eller evolventen på en tandhjulstand.", + "help.sketch.extend": "Forlænger en linje eller bue op til den nærmeste kurve i vejen eller lader to kurver vokse, til de mødes. Brug den til at lukke åbninger i en profil efter trimning eller redigering.", + "help.sketch.fillet": "Runder hjørnet, hvor to linjer eller buer mødes, af med en bue med en given radius. Flere hjørner, der afrundes sammen, deler én radius.", + "help.sketch.finish": "Forlader skitsen og vender tilbage til modellen. Dens lukkede profiler er derefter klar til Ekstrudering, Omdrejning og andre features.", + "help.sketch.finish_auto_constrain": "Kører Automatisk binding på skitsen og afslutter den derefter. Brug den til at efterlade en skitse fuldt bundet i ét trin.", + "help.sketch.fit_curves_to_section": "Skærer et mesh eller massivt emne med skitseplanet og tilpasser linjer og buer til snittet. Brug den til at genopbygge en scannet eller importeret del som en redigerbar skitse.", + "help.sketch.include_3d": "Henter modelkanter, hjørnepunkter og kurver fra andre skitser ind i denne skitse som linkede referencer og projicerer dem, der ligger uden for dens plan, ned på det. Brug den til at bygge videre på geometri, der ikke ligger i skitseplanet.", + "help.sketch.infinite": "Skifter linjer mellem normale linjer og uendelige hjælpelinjer, der løber hen over hele visningen. Brug dem som layoutreferencer, der aldrig ender for kort.", + "help.sketch.insert_dxf": "Læser kurverne i en DXF-tegning ind i en skitse, skaleret, drejet og placeret, som du angiver. Brug den til at bygge videre på en 2D-tegning fra et andet program, f.eks. en laserskåret kontur.", + "help.sketch.insert_svg": "Læser stierne i en SVG-tegning ind i en skitse, skaleret, drejet og placeret, som du angiver. Brug den til at gøre et logo eller en vektorkontur til kurver, du kan ekstrudere.", + "help.sketch.inspect": "Åbner en rapport om den åbne skitse: hvor mange frihedsgrader der er tilbage, og om den er fuldt bundet. Brug den til at finde ud af, hvad der stadig kan bevæge sig, før du afslutter skitsen.", + "help.sketch.intersect": "Tilføjer de kurver eller punkter, hvor emner, flader, kanter eller andre skitser krydser skitseplanet. De forbliver linkede og følger modellen, når den ændres.", + "help.sketch.intersection_curve": "Opretter 3D-kurver, hvor to emner eller flader mødes, linket til dem. Brug dem som baner eller styrekurver, der følger modellen.", + "help.sketch.isoparametric_curve": "Opretter en 3D-kurve langs en flades U- eller V-retning gennem et punkt, du vælger, linket til fladen. Brug den som bane eller delelinje, der følger overfladen.", + "help.sketch.line": "Tegner forbundne linjer punkt for punkt som en åben kæde eller en lukket kontur. Det er det grundlæggende værktøj til de fleste profiler.", + "help.sketch.line.midpoint": "Tegner en linje fra dens midtpunkt ud til den ene ende, og den anden ende spejles. Brug den til linjer centreret om et punkt, f.eks. en symmetrisk kant.", + "help.sketch.line3d": "Tegner forbundne rette linjer mellem punkter i rummet, med 3D-skitse slået til. Brug den til baner og rammer, der forlader skitseplanet.", + "help.sketch.mirror": "Spejler skitsekurver og -punkter over en linje eller akse og tilføjer symmetribindinger. Brug den til at tegne halvdelen af en symmetrisk profil og fuldende den.", + "help.sketch.move": "Flytter eller roterer skitsekurver og -punkter eller en kopi af dem. Brug den til at flytte geometri og bevare dens form og bindinger.", + "help.sketch.offset": "Opretter en kopi af en kæde af kurver i en given afstand, på den ene side eller begge. Brug den til vægge, konturer og frigang; afstanden forbliver et redigerbart mål.", + "help.sketch.paste": "Indsætter skitsegeometri, du har kopieret eller klippet, i den aktive skitse. Placér den i et punkt, eller forskyd den med en afstand.", + "help.sketch.pattern.circular": "Kopierer skitsegeometri omkring et centrumpunkt over en hel cirkel eller en given vinkel. Brug den til boltcirkler, eger og tænder.", + "help.sketch.pattern.rectangular": "Kopierer skitsegeometri i rækker og kolonner med givne afstande. Brug den til gitre af huller, slidser eller ventilationsåbninger.", + "help.sketch.point": "Placerer et skitsepunkt. Brug det som reference til mål, bindinger, hulcentre eller senere features.", + "help.sketch.point3d": "Placerer et punkt i rummet, med 3D-skitse slået til. Brug det som reference til 3D-kurver og baner.", + "help.sketch.polygon.circumscribed": "Tegner en regulær polygon omkring en cirkel med størrelsen målt fra centrum til midten af en side. Brug den, når nøglevidden er kendt, f.eks. til en sekskantmøtrik.", + "help.sketch.polygon.edge": "Tegner en regulær polygon ud fra de to ender af én side. Brug den, når længden og positionen af en side er kendt.", + "help.sketch.polygon.inscribed": "Tegner en regulær polygon inden i en cirkel med størrelsen målt fra centrum til et hjørne. Brug den, når målet over hjørnerne er kendt.", + "help.sketch.project": "Henter modelkanter, flader, hjørnepunkter og kurver fra andre skitser ind i denne skitse, projiceret ned på dens plan. De forbliver linkede og følger modellen, når den ændres.", + "help.sketch.project_to_surface": "Projicerer kurver fra andre skitser langs denne skitses normal ned på en flade som linkede 3D-kurver. Brug den til at lægge et logo, en delelinje eller en bane på en buet overflade.", + "help.sketch.rectangle.center": "Tegner et rektangel ud fra dets centrum og ét hjørne. Brug det til konturer centreret om et punkt, f.eks. nulpunktet.", + "help.sketch.rectangle.rounded": "Tegner et rektangel med alle fire hjørner afrundet med samme radius. Brug det til plader, låg og åbninger med afrundede hjørner.", + "help.sketch.rectangle.three_point": "Tegner et rektangel ud fra én kant og et punkt på den modsatte side. Brug det til rektangler, der er vinklet i forhold til skitsens akser.", + "help.sketch.rectangle.two_point": "Tegner et rektangel ud fra to modstående hjørner. Brug det til konturer af plader, blokke og lommer.", + "help.sketch.scale": "Skalerer skitsekurver og -punkter med en faktor omkring et basispunkt. Brug den til at ændre størrelsen på en del af en skitse uden at tegne den igen.", + "help.sketch.slot.arc_center": "Tegner en buet slids med en given bredde langs en bue, der er angivet ved dens centrum, start og slut. Brug den til justeringsslidser omkring en omdrejningstap.", + "help.sketch.slot.arc_three_point": "Tegner en buet slids med en given bredde langs en bue gennem tre punkter. Brug den, når slidsens bane skal gå gennem givne punkter.", + "help.sketch.slot.center_point": "Tegner en lige slids med en given bredde fra dens centrum til centrum af den ene endebue. Brug den til slidser centreret om et punkt.", + "help.sketch.slot.center_to_center": "Tegner en lige slids med en given bredde mellem centrene af dens to endebuer. Brug den til slidser, der er målsat fra centrum til centrum, f.eks. justeringsslidser til skruer.", + "help.sketch.slot.overall": "Tegner en lige slids med en given bredde fra den ene ydre ende til den anden. Brug den, når slidsens samlede længde er det vigtige.", + "help.sketch.spline.control_point": "Tegner en kubisk spline formet af kontrolpunkter, som den ikke går igennem. Brug den til bløde, flydende kurver, som du former ved at flytte punkterne.", + "help.sketch.spline.control_point_5": "Tegner en spline af grad 5 formet af kontrolpunkter. Brug den, hvor kurver skal mødes med blødere krumning, f.eks. på synlige formgivne overflader.", + "help.sketch.spline.fit_point": "Tegner en glat spline, der går gennem hvert punkt, du placerer, åben eller lukket. Brug den til at følge en form gennem kendte punkter.", + "help.sketch.spline3d": "Tegner en glat kurve i rummet gennem punkter, med 3D-skitse slået til. Brug den til sweep-baner og kabelføringer, der forlader skitseplanet.", + "help.sketch.spun_profile": "Opretter i skitseplanet den kontur, et emne beskriver, når det drejer om en akse. Brug den til at få silhuetten af en drejet del til en omdrejning eller en tegning.", + "help.sketch.text": "Skriver tekst i skitsen i en valgt skrifttype, højde og vinkel; dens ord kan følge parametre. Ekstrudér eller præg den til etiketter og skrift.", + "help.sketch.transform": "Skalerer, drejer og flytter skitsegeometri omkring et centrumpunkt i ét trin. Brug den til at flytte og ændre størrelsen på en markering på én gang.", + "help.sketch.trim": "Fjerner stykket af en kurve mellem de nærmeste skæringer omkring det sted, du klikker. Brug den til at rydde op i overlappende linjer til en lukket profil.", + "help.solid.align": "Justér flytter de valgte emner, så et punkt, en flade eller et plan på dem møder et punkt, en flade eller et plan et andet sted. Brug den til at placere en del op mod en anden uden at måle forskydningen.", + "help.solid.boundary_fill": "Danner massive emner ud fra de områder, der er indesluttet af overlappende værktøjsemner, og fylder kun de områder, du vælger. Brug den til at bygge en form ud fra det rum, som flere emner tilsammen afgrænser.", + "help.solid.bounding_solid": "Opretter en boks, der omslutter de valgte emner, med en valgfri margin. Brug den til at se en dels samlede størrelse eller som råemnet, den bearbejdes ud af.", + "help.solid.box": "Opretter en boks ud fra længde, bredde og højde, fra et hjørne eller centreret om et punkt. Brug den til en hurtig blok, en pladsholder eller et emne at skære features i.", "help.solid.chamfer": "Affasning skærer de valgte kanter skråt med den angivne afstand. Brug den til at fjerne skarpe kanter eller lette indføringen af en tap eller skrue.", + "help.solid.coil": "Opretter et skruelinjeformet emne, f.eks. en fjeder, ud fra en diameter, vindinger, højde eller stigning og et rundt eller firkantet tværsnit. Brug den til fjedre, spiraler og skruelinjeformede ribber.", + "help.solid.combine": "Kombinér forener emner, skærer dem ud af et målemne eller beholder kun det fælles volumen og kan beholde værktøjsemnerne. Brug den til at samle dele, til at skære en form med en anden eller til at finde ud af, hvor to emner overlapper.", + "help.solid.cone": "Opretter en kegle ud fra en grundcirkel og en højde eller en keglestub, når toppen også har en radius. Brug den til tilspidsninger, tragte, koniske forsænkninger og spidser.", + "help.solid.cylinder": "Opretter en cylinder ud fra en radius eller diameter og en højde, stående på et punkt langs en akse. Brug den til aksler, stifter, bøsninger og runde råemner.", + "help.solid.draft": "Slipvinkel hælder de valgte flader med den angivne vinkel, målt fra et neutralt plan. Brug den på støbte eller formsprøjtede dele, så de kan løsnes fra formen.", + "help.solid.emboss": "Hæver skitseprofiler, f.eks. tekst eller et logo, ud af en flade eller sænker dem ned i den. Brug den til skrift, etiketter og mærkning på plane eller runde flader.", "help.solid.extrude": "Ekstrudering giver en skitseprofil dybde ved at tilføje eller fjerne materiale langs en retning. Angiv afstanden for at danne en klods, en forhøjning eller en lomme. Brug Udhulning, hvis en massiv model i stedet skal gøres hul med en bestemt vægtykkelse.", "help.solid.fillet": "Afrunding erstatter de valgte kanter med en glat, cirkulær overgang med den angivne radius. Den kan blødgøre skarpe kanter af hensyn til styrke, komfort eller udseende.", "help.solid.hole": "Hul opretter et rundt hul ved et valgt punkt på en flade. Angiv diameteren, og vælg eventuelt konisk forsænkning, cylindrisk forsænkning eller gevind. Ved gevind vælges en gevindbetegnelse, f.eks. M6.", + "help.solid.loft": "Loft danner et glat massivt legeme mellem to eller flere skitseprofiler eller fra en profil til et punkt. Brug den til overgange, tragte, håndtag og alle former, hvis tværsnit ændres langs længden.", + "help.solid.mirror": "Spejling laver en spejlet kopi af de valgte emner eller features over et plan og kan forene den med originalen. Brug den til symmetriske dele, så du kun modellerer den ene halvdel og får begge.", + "help.solid.move": "Flyt flytter eller roterer de valgte emner eller en kopi af dem med den afstand og vinkel, du angiver. Brug den til at flytte et emne eller til at lave en kopi på et andet sted.", + "help.solid.offset_face": "Forskyd flade skubber de valgte flader ind eller ud med den afstand, du angiver, og de omkringliggende flader følger med. Brug den til at gøre en væg tykkere, en lomme dybere eller en forhøjning højere uden at redigere skitsen.", + "help.solid.pattern.circular": "Cirkulært mønster gentager de valgte objekter omkring en akse med det antal og den samlede vinkel, du angiver. Brug det til boltcirkler, eger, ribber og tænder.", + "help.solid.pattern.path": "Kopierer features eller emner langs en skitsebane efter antal og afstand. Brug den til huller langs en buet kant eller dele langs en skinne.", + "help.solid.pattern.rectangular": "Rektangulært mønster gentager de valgte objekter i en eller to retninger med det antal og den afstand, du angiver. Brug det til rækker og gitre af huller, ribber, stifter eller fødder.", + "help.solid.pipe": "Opretter et rundt rør langs en bane af skitsekurver, massivt eller hult med en vægtykkelse. Brug den til rør, ledninger, kabler og skinner.", + "help.solid.press_pull": "Tryk/træk tilføjer eller fjerner materiale, når du trækker i en flade, eller afrunder kanter, når du trækker i dem. Brug den til hurtige ændringer direkte på modellen.", + "help.solid.remove": "Fjern tager de valgte emner ud af designet fra dette punkt i tidslinjen; tidligere trin beholder dem. Brug den til at fjerne et hjælpeemne, f.eks. et skærende værktøj, du ikke længere har brug for.", + "help.solid.replace_face": "Erstat flade flytter de valgte plane flader hen på et plan eller en parallel flade, og emnet vokser eller skrumper, så det mødes med den. Brug den til at få en flade i flugt med en anden del eller et konstruktionsplan.", "help.solid.revolve": "Omdrejning drejer en skitseprofil omkring en valgt akse og danner et omdrejningslegeme. Brug den f.eks. til aksler, knopper og skåle, der er runde omkring en centerlinje.", + "help.solid.rib": "Tilføjer en tynd væg langs en åben skitsekurve, fyldt ud til emnets næste flader. Brug den til at afstive vægge og hjørner, f.eks. i sprøjtestøbte eller printede dele.", + "help.solid.scale": "Skalering gør de valgte emner større eller mindre med en faktor, ens i alle retninger eller én pr. akse. Brug den til at ændre størrelsen på en importeret form eller til at tage højde for krympning.", "help.solid.shell": "Udhulning gør et massivt legeme hult med den angivne vægtykkelse. Vælg de flader, der skal åbnes. Indvendig udhulning bevarer de udvendige mål, mens udvendig udhulning bevarer de indvendige mål. Brug den f.eks. til kasser, dæksler og andre tyndvæggede dele.", + "help.solid.sphere": "Opretter en kugle ud fra en radius eller diameter omkring et centrumpunkt. Brug den til kugler, knopper og afrundede ender.", + "help.solid.split_body": "Opdel emne skærer et emne i separate emner med et plan, en flade på et andet emne eller en skitselinje. Brug den til at lave dele, der skal printes, bearbejdes eller farves hver for sig.", + "help.solid.split_face": "Opdel flade deler de valgte flader langs et plan, en flade på et andet emne eller skitsekurver uden at skære i emnet. Brug den til at give en del af en flade sin egen slipvinkel, farve eller forskydning.", + "help.solid.sweep": "Sweep trækker en skitseprofil langs en bane for at danne et massivt legeme. Brug den til rør, skinner, håndtag og alle dele med konstant tværsnit, der følger en kurve.", + "help.solid.thread": "Tilføjer et metrisk ISO-gevind på en cylindrisk flade, enten som kosmetisk gevind eller skåret ind i emnet. Brug det til bolte, gevindhuller og printede skruedele.", + "help.solid.torus": "Opretter en ring ud fra en hovedradius omkring dens akse og en mindre radius til dens runde tværsnit. Brug den til O-ringe, håndtag og runde perler.", + "help.solid.web": "Tilføjer en tynd væg langs hver åben skitsekurve, hver især fyldt ud til emnets næste flader. Brug den til et gitter af understøttende vægge inde i kabinetter og bakker.", + "help.surface.blend": "Opretter en flade, der bygger bro mellem to emners kanter, tangent eller krumningskontinuert til begge. Brug den til at forbinde to overflader glat hen over et mellemrum.", + "help.surface.boundary": "Opretter en flade, der udfylder en sløjfe af to til fire skitsekurver, eller et net af kurver. Brug den til frit formede paneler, som kanterne definerer.", + "help.surface.extend": "Forlænger en overflade ud over dens kanter med en afstand eller op til et plan eller en flade. Brug den, så overflader overlapper, før du trimmer eller syr dem sammen.", + "help.surface.extrude": "Trækker skitsekurver eller profiler en afstand ud til en overflade, kun vægge uden endeflader. Brug den til tynde vægge og til skære- eller deleværktøjer.", + "help.surface.fair": "Udjævner indersiden af frit formede flader, mens deres kanter bliver, hvor de er. Brug den til at udjævne bump og bølgede refleksioner i en overflade.", + "help.surface.loft": "Opretter en overflade, der går gennem to eller flere tværsnit i rækkefølge, uden endeflader. Brug den til skaller og overgange mellem forskellige former.", + "help.surface.match": "Genopbygger en overflades kant, så den mødes med et andet emnes kant med tilsvarende tangent eller krumning. Brug den til at lukke en overgang glat mellem to overflader.", + "help.surface.offset": "Opretter en kopi af flader i en afstand langs deres normaler som et nyt overfladelegeme. Brug den til skind, frigang eller den anden side af en væg.", + "help.surface.patch": "Fylder et skitseområde eller en lukket sløjfe af kanter ud med en flade, plan eller blødt buet. Brug den til at lukke huller i et overfladelegeme.", + "help.surface.reverse_normal": "Vender flader på et overfladelegeme om, så deres yderside vender den anden vej. Brug den, før du giver tykkelse eller syr sammen, når fladerne peger indad.", + "help.surface.revolve": "Drejer skitsekurver eller profiler om en akse til en overflade uden endeflader. Brug den til runde skaller som lampeskærme, skåle og dyser.", + "help.surface.ruled": "Opretter en strimmel af rette linjer ud fra en kæde af kanter langs fladens normal, tangent eller i en vinkel. Brug den til vægge med slipvinkel, udløb og delingsflader.", + "help.surface.stitch": "Syr overfladelegemer sammen langs deres fælles kanter, til et massivt emne, når de lukker sig. Brug den til at gøre et sæt overflader til ét emne.", + "help.surface.sweep": "Fører skitsekurver eller profiler langs en bane til en overflade uden endeflader. Brug den til render, lister og andre tynde former, der følger en bane.", + "help.surface.thicken": "Giver et overfladelegeme en tykkelse og gør det til et massivt emne. Brug den til at lave printbare eller bearbejdelige dele af overflader.", + "help.surface.trim": "Skærer en overflade med et plan, en anden overflade eller skitsekurver og beholder den side, du vælger. Brug den til at skære overflader til form, før du syr dem sammen.", + "help.surface.unstitch": "Adskiller flader på et emne til selvstændige overfladelegemer; et massivt emne falder fra hinanden til overflader. Brug den til at omarbejde enkelte flader på et emne.", + "help.surface.untrim": "Fjerner huller fra en flade eller gendanner dens ydre afgrænsning til overfladens naturlige grænser. Brug den til at få den fulde overflade tilbage efter en trimning.", "help.third_party": "Tredjepartslicenser", + "help.timeline.compute_all": "Beregn alle genopbygger alle features i tidslinjen fra starten. Brug den til at opdatere modellen og se, hvilke features der fejler.", + "help.timeline.delete": "Sletter de valgte features fra tidslinjen; sletning af en skitse sletter også de features, der er bygget på den. Brug den til at fjerne et trin, som ikke længere er ønsket.", + "help.timeline.dependents": "Viser de features, der ville blive slettet sammen med en feature, og dem, der ville fejle uden den. Brug den, før du sletter eller ændrer en feature.", + "help.timeline.play": "Afspil de resterende features én ad gangen med en pause på et halvt sekund efter hver genopbygning. Kør kommandoen igen, eller tryk på Escape for at stoppe; Gå til slutningen hopper med det samme.", + "help.view.apply": "Drejer visningen til en standardretning som forfra, oppefra eller iso eller til en gemt navngiven visning. Brug den til at se på modellen fra en fast vinkel.", + "help.view.delete": "Sletter en gemt navngiven visning. Modellen ændres ikke.", + "help.view.fit": "Zoomer og panorerer, så hele modellen eller markeringen fylder visningen. Brug den, når modellen er røget ud af syne.", + "help.view.grid": "Viser eller skjuler gitteret i visningsområdet. Brug det som hjælp til størrelse og orientering under modellering.", + "help.view.ground_shadow": "Viser eller skjuler modellens skygge på grundplanet. Brug den til lettere at vurdere højde og position.", + "help.view.home": "Drejer visningen tilbage til hjemmeretningen og tilpasser modellen. Brug den til hurtigt at komme tilbage til en kendt visning.", + "help.view.list": "Viser de navngivne visninger, der er gemt i designet. Brug den til at finde en visning, du har gemt tidligere.", + "help.view.navigate": "Drejer, panorerer eller zoomer visningen i trin, f.eks. en kvart omdrejning til venstre. Brug den til at flytte kameraet præcist i stedet for at trække.", + "help.view.navigation_bar": "Viser eller skjuler navigationslinjen nederst i visningsområdet. Skjul den for mere plads, vis den for at nå visningsværktøjerne med musen.", + "help.view.rename": "Giver en gemt navngiven visning et nyt navn. Selve visningen forbliver den samme.", + "help.view.save": "Gemmer den aktuelle kameraposition som en navngiven visning i designet. Brug den til at vende tilbage til samme vinkel senere, f.eks. til skærmbilleder.", + "help.view.spin": "Kører rundt om modellen i visningen kontinuerligt, til næste klik eller tastetryk. Brug den til at præsentere en model fra alle sider.", + "help.view.tool": "Låser et kameraværktøj, rotation, panorering eller zoom, så træk med venstre museknap flytter visningen, til du slår det fra. Brug det på en touchplade eller uden en midterste museknap.", + "help.view.visual_style": "Skifter, hvordan modellen tegnes: skyggelagt med eller uden kanter, trådmodel eller med skjulte kanter. Brug trådmodel til at se ind i modellen, skyggelagt til et rent udseende.", + "history.sketch_under_constrained": "Ikke fuldt bundet ({count} frihedsgrader)", + "history.sketch_under_constrained_one": "Ikke fuldt bundet ({count} frihedsgrad)", + "hole_presets.confirm_delete": "Bekræft sletning", + "hole_presets.delete": "Slet", + "hole_presets.delete_prompt": "Slet denne personlige forudindstilling? Eksisterende huller ændres ikke.", + "hole_presets.full": "Det personlige bibliotek indeholder allerede 64 forudindstillinger.", + "hole_presets.invalid_name": "Angiv et kort navn uden linjeskift eller kontroltegn.", + "hole_presets.invalid_parameters": "Udfyld hulparametrene med gyldige udtryk af rimelig længde.", + "hole_presets.missing": "Den valgte forudindstilling er ikke længere tilgængelig.", + "hole_presets.name": "Navn på forudindstilling", + "hole_presets.name_exists": "Der findes allerede en forudindstilling med dette navn. Brug et andet navn.", + "hole_presets.name_hint": "Et entydigt navn", + "hole_presets.overwrite": "Gem ændringer i den valgte forudindstilling", + "hole_presets.preset": "Forudindstilling", + "hole_presets.recall": "Hent", + "hole_presets.rename": "Omdøb", + "hole_presets.save": "Gem som ny", + "hole_presets.scope": "Gemt i din profil og tilgængelig i alle projekter.", + "hole_presets.select": "Vælg en forudindstilling", + "hole_presets.title": "Personlige forudindstillinger", + "hole_presets.unsupported_options": "Denne forudindstilling bruger gevindindstillinger, som denne version ikke kan hente.", + "hole_presets.unsupported_overwrite": "Denne forudindstilling indeholder indstillinger, der ikke kan overskrives sikkert.", "home.back": "Tilbage til {name}", "home.crashes": "Nedbrudsrapporter", "home.design_workspace": "Design", @@ -1156,6 +1818,9 @@ "install.steps_intro": "Safari installerer webapps via sine egne menuer:", "install.title": "Installér SolidCraft", "issue.body_label": "Rapporttekst", + "issue.note_changed_while_waiting": "Indstillingerne eller modellen blev ændret, mens du ventede på forhåndsvisningen. Tag skærmbilledet igen for at opdatere de tekniske oplysninger til den aktuelle visning.", + "issue.note_details_kept": "Skærmbilledet er optaget lokalt. Dine redigerede tekniske oplysninger er bevaret: Kontrollér, at de stadig passer til den aktuelle visning.", + "issue.note_details_updated": "De tekniske oplysninger er opdateret, så de passer til den aktuelle visning. Skærmbilledet er optaget lokalt. Gennemgå det, før du vedhæfter det på GitHub.", "issue.note_image_copied": "Indsæt billedet i GitHub-kladden, eller gem PNG-filen, hvis billedkopiering ikke er tilgængelig.", "issue.note_opened": "Gennemgå GitHub-kladden, og vedhæft skærmbilledet. GitHubs knap Submit new issue udgiver den.", "issue.note_opened_copied": "Rapport kopieret. Indsæt den i GitHub-kladden, vedhæft skærmbilledet, og klik derefter på Submit new issue på GitHub.", @@ -1167,9 +1832,30 @@ "joint.from_bodies_hint": "Hvert valgt emne flyttes til sin egen nye komponent og bliver på sin plads.", "joint.one_body": "Begge valg er på {body}. Vælg det andet på et andet emne.", "joint.one_component": "Disse emner tilhører samme komponent: {bodies}. Et led bevæger én komponent i forhold til en anden, så hvert emne skal have sin egen komponent.", + "joint.rigid_group_one_component": "Disse {count} emner er alle i én komponent (eller i selve designet): Brug først {command}.", + "joint.rigid_group_select_components": "Vælg to eller flere komponenter.", + "joint_move.blocked_hint": "Kontrollér ledtypen (f.eks. Stiv), fastgørelse, bevægelsesgrænser for led og parameterstyrede værdier.", + "joint_move.blocked_title": "Kan ikke flytte dette emne", + "joint_move.coarse": "Rotationstrin nær aksen (°)", + "joint_move.conflict": "Et led på dette emne er i konflikt med de andre: {joint}.", + "joint_move.conflict_hint": "Redigér, undertryk eller slet det modstridende led, så de andre led kan placere emnet.", + "joint_move.distance": "Afstand fra start", + "joint_move.done": "Færdig", + "joint_move.fine": "Rotationstrin langt fra aksen (°)", + "joint_move.fixed": "Dette emne har ingen bevægelig ledakse.", + "joint_move.help": "Flyt — træk i en pil eller en ring. Esc annullerer det aktuelle træk.", + "joint_move.legacy_hint": "Slå fra for at bruge det tidligere Flyt-panel.", + "joint_move.precision": "Træk uden for den stiplede hjælpelinje for finere rotation.", + "joint_move.rotation": "Rotation fra start", + "joint_move.select": "Vælg en flade eller ét emne i samlingen, og vælg derefter Flyt.", + "joint_move.settings": "Flyt i samling", + "joint_move.step": "Trin", + "joint_move.use_handles": "Brug håndtag til ledbevægelse ved Flyt i samling", "keymap.command_id": "Kommando-ID", "keymap.empty": "Ingen matchende kommandoer", "keymap.use_anyway": "Brug {key} her alligevel", + "label.move_to_left_side": "Flyt til venstre side", + "label.move_to_right_side": "Flyt til højre side", "manage.appearance_hint": "Vælg et udseende til markeringen, eller træk en farveprøve over på et emne eller en flade.", "manage.assign_hint": "Vælg emner, og vælg deres plastdesignregel.", "manage.config_hint": "Redigér konfigurationsrækker, kolonner og regler, og aktivér eller forhåndsvis derefter en række.", @@ -1177,8 +1863,57 @@ "manage.material_hint": "Vælg emner, og vælg deres fysiske materiale.", "manage.parameters_hint": "Redigér udtryk og enheder. Ændringer anvendes ved Enter eller når du forlader et felt.", "manage.rules_hint": "Vælg en regel at redigere, eller opret en ny regel. Bekræft for at gemme reglen.", + "material.editor.add_property": "Tilføj egenskab", + "material.editor.add_source": "Tilføj kilde", + "material.editor.assigned_density": "Tildelt densitet", + "material.editor.axes": "Materialeakser", + "material.editor.axes_numeric": "1 / 2 / 3", + "material.editor.axes_wood": "L / R / T", + "material.editor.copy_name": "Kopi af {name}", + "material.editor.density_range": "Den tildelte densitet skal være over 0 og højst 1000 g/cm³.", + "material.editor.designation": "Betegnelse", + "material.editor.duplicate": "Duplikér", + "material.editor.engineering_card": "Teknisk egenskabskort", + "material.editor.family": "Materialefamilie", + "material.editor.glass": "Glas", + "material.editor.illustrative": "Illustrativ", + "material.editor.invalid_property": "Egenskabstypen understøttes ikke.", + "material.editor.isotropic": "Isotrop", + "material.editor.measurement": "Måling", + "material.editor.metal": "Metal", + "material.editor.moisture": "Fugtindhold, tør basis", + "material.editor.name_required": "Angiv et navn på 1–128 tegn.", + "material.editor.no_draft": "Der er ikke åbnet noget materialeudkast.", + "material.editor.number_required": "Angiv en endelig numerisk værdi.", + "material.editor.orthotropic": "Ortotrop", + "material.editor.other": "Andet", + "material.editor.polymer": "Polymer", + "material.editor.preserved_appearance": "Bevaret udseende", + "material.editor.public_reference": "Offentlig reference", + "material.editor.reference": "Reference", + "material.editor.save_or_discard": "Gem eller kassér materialeudkastet, før du tildeler et materiale.", + "material.editor.saved": "Materialet er gemt. Tildelinger til emner er uændrede.", + "material.editor.scope": "Gem gemmer materialet uden at tildele det til emner. Tomme egenskaber og betingelser forbliver ukendte. Kortets densitet ændrer ikke den tildelte densitet eller massen.", + "material.editor.source_id": "Kilde-id", + "material.editor.source_kind": "Kildetype", + "material.editor.source_title": "Kildetitel", + "material.editor.sources": "Kilder", + "material.editor.stale": "Dette materiale blev ændret, mens udkastet var åbent. Kassér udkastet, og åbn det igen, før du gemmer.", + "material.editor.state": "Materialetilstand", + "material.editor.strain_rate": "Tøjningshastighed", + "material.editor.symmetry": "Elastisk symmetri", + "material.editor.temperature": "Temperatur", + "material.editor.unknown_card": "De tekniske egenskaber er ukendte. Gem beholder muligvis kun den tildelte densitet og det eksisterende udseende.", + "material.editor.user_supplied": "Angivet af brugeren", + "material.editor.wood": "Træ", + "material.selection.choose": "Vælg et materiale", + "material.selection.mixed": "Forskellige materialer", "measure.at": "Ved", "measure.item": "Element {number}", + "measure.quick_copied": "Måling kopieret", + "measure.quick_copy": "Klik for at kopiere målingen", + "measure.quick_edges": "{count} kanter", + "measure.quick_faces": "{count} flader", "messages.ago_h": "For {n} timer siden", "messages.ago_min": "For {n} min. siden", "messages.ago_s": "For {n} sek. siden", @@ -1203,13 +1938,22 @@ "motion.track_name": "Spor {number}", "nav.alias.help": "Shift+Alt+træk med venstre museknap roterer visningen, Shift+Alt+midterste panorerer, Shift+Alt+højre zoomer; træk med midterste museknap panorerer også, og træk med højre roterer visningen", "nav.blender.help": "Træk med midterste museknap roterer visningen, Shift+midterste panorerer, Ctrl+midterste zoomer; træk med højre museknap påvirker ikke kameraet", + "nav.creo.help": "Træk med midterste museknap roterer visningen, Shift+midterste panorerer, Ctrl+træk lodret med midterste zoomer (ned for at zoome ind); rulning med hjulet zoomer", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Musen og 3D-musen roterer gennem begge poler og bevarer rulning. Snap til akser med Shift er slået fra.", "nav.free_orbit.label": "Fri rotation af visningen", + "nav.free_orbit.snap_help": "Musen og 3D-musen roterer gennem begge poler og bevarer rulning. Hold Shift nede under et rotationstræk for at snappe visningsretningen og rulningen.", + "nav.free_orbit_upright.help": "Sidelæns musetræk drejer modellen om verdens lodrette akse. Træk op og ned vipper modellen over toppen uden begrænsning.", + "nav.free_orbit_upright.label": "Drej om den lodrette akse", "nav.fusion.help": "Træk med midterste museknap panorerer, Shift+midterste roterer visningen, træk med højre roterer visningen", "nav.hfss.help": "Alt+træk med venstre museknap panorerer, Shift+Alt+venstre zoomer, Ctrl+træk med venstre fra et tomt område roterer visningen", "nav.inventor.help": "Træk med midterste museknap panorerer, Shift+midterste roterer visningen, Ctrl+midterste zoomer, træk med højre roterer visningen", "nav.maya.help": "Alt+træk med venstre museknap roterer visningen, Alt+midterste panorerer, Alt+højre zoomer; træk med midterste museknap panorerer også", + "nav.nx.help": "Træk med midterste museknap roterer visningen, Shift+midterste panorerer (NX's midterste + højre), Ctrl+midterste zoomer (NX's midterste + venstre); træk med højre museknap påvirker ikke kameraet", "nav.openscad.help": "Træk med venstre museknap i et tomt område roterer visningen, Shift+venstre markerer med en ramme, træk i skitsegeometri redigerer den; træk med højre eller midterste museknap panorerer, Shift+højre eller Shift+midterste zoomer", + "nav.perspective.sketch": "Skitseredigering bruger ortografisk visning. Afslut skitsen for at skifte til perspektiv.", + "nav.right_drag_orbits.help": "Slået fra: Træk med højre museknap påvirker ikke kameraet, og højre knap åbner kun genvejsmenuen. Hvis du vælger SolidWorks-musetildelingen, slås dette fra.", + "nav.right_drag_orbits.label": "Træk med højre museknap roterer visningen", "nav.solidworks.help": "Træk med midterste museknap roterer visningen, Ctrl+midterste panorerer, Shift+midterste zoomer, træk med højre roterer visningen", "nav.tinkercad.help": "Træk med højre museknap roterer visningen, træk med midterste eller Shift+højre panorerer", "nav.touchpad.help": "Hold Shift nede, og bevæg markøren for at panorere; hold Alt/Option nede, og bevæg den for at rotere visningen. Ingen museknap behøver at være trykket ned. Lodret rulning zoomer.", @@ -1218,40 +1962,212 @@ "nav.touchpad.pan": "Panorér (hold Shift nede og bevæg markøren; ingen museknap)", "nav.touchpad.scroll": "Pegefelt bruger lodret rulning til zoom. Din indstilling for panorering med to fingre bevares for andre forudindstillinger.", "nav.touchpad.zoom": "Zoom (lodret rulning eller knibebevægelse)", + "navbar.agent_chat": "Assistentens chatpanel", + "navbar.agent_cursor": "Vis agentmarkør", + "navbar.ambient_occlusion": "Ambient occlusion", + "navbar.assistant": "Assistent", + "navbar.custom.add_slot": "Tilføj {slot}", + "navbar.custom.always": "Altid synlig", + "navbar.custom.available": "{available} · træk til linjen, eller tryk på Tilføj", + "navbar.custom.buttons": "Knapper", + "navbar.custom.compact": "Kompakt", + "navbar.custom.count": "{count} af 16 pladser", + "navbar.custom.customise": "Tilpas navigationslinje…", + "navbar.custom.design": "Design", + "navbar.custom.duplicate": "Denne plads findes allerede på linjen.", + "navbar.custom.edge": "Kant", + "navbar.custom.edge_bottom": "Nederst", + "navbar.custom.edge_top": "Øverst", + "navbar.custom.fade": "Udtoning", + "navbar.custom.full": "Fjern en plads for at tilføje en ny.", + "navbar.custom.hidden_design": "Skjult i Design", + "navbar.custom.hidden_render": "Skjult i Rendering", + "navbar.custom.hide": "Skjul navigationslinjen", + "navbar.custom.hide_idle": "Skjul, indtil musen holdes over", + "navbar.custom.icon_only": "Kun ikon", + "navbar.custom.icon_value": "Ikon og værdi", + "navbar.custom.icons": "Ikoner", + "navbar.custom.idle": "Ved inaktivitet", + "navbar.custom.intro": "Vælg, hvilke knapper der skal være på linjen nederst i 3D-visningen, og i hvilken rækkefølge. Træk en plads for at flytte den, eller træk den væk fra linjen for at fjerne den.", + "navbar.custom.labels": "Ikoner og tekst", + "navbar.custom.left": "Flyt til venstre", + "navbar.custom.position": "Placering", + "navbar.custom.position_centre": "Midt", + "navbar.custom.position_left": "Venstre", + "navbar.custom.position_right": "Højre", + "navbar.custom.preview_as": "Forhåndsvis som", + "navbar.custom.regular": "Normal", + "navbar.custom.remove": "Fjern", + "navbar.custom.remove_bar": "Fjern fra linjen", + "navbar.custom.render": "Rendering", + "navbar.custom.reset": "Nulstil navigationslinje", + "navbar.custom.reset_default": "Nulstil til standard", + "navbar.custom.right": "Flyt til højre", + "navbar.custom.select": "Ingen plads er valgt. Vælg en plads på linjen for at flytte eller fjerne den eller ændre dens udseende.", + "navbar.custom.separators_full": "Linjen har allerede fire skillelinjer.", + "navbar.custom.show": "Vis navigationslinjen", + "navbar.custom.shows": "Viser", + "navbar.custom.size": "Størrelse", + "navbar.custom.stale": "Linjen er ændret. Vælg pladsen igen.", + "navbar.custom.title": "Navigationslinje", + "navbar.custom.unknown": "Denne plads er ikke tilgængelig.", + "navbar.description.ambient_occlusion": "Mørkner folder og hjørner for at give dybde.", + "navbar.description.display": "Samler visningsindstillingerne: grafikprofil, gitter, skygge på grundplan, ambient occlusion og projektion.", + "navbar.description.fit": "Tilpasser visningen til markeringen eller til hele modellen, hvis intet er markeret.", + "navbar.description.grid": "Viser eller skjuler gitteret på grundplanet.", + "navbar.description.ground_shadow": "Viser eller skjuler skyggen under modellen.", + "navbar.description.home": "Vender tilbage til den isometriske visning af hele modellen.", + "navbar.description.look_at": "Drejer visningen, så den vender mod den valgte flade, det valgte plan eller den åbne skitse.", + "navbar.description.orbit": "Drejer visningen rundt om modellen.", + "navbar.description.pan": "Panorerer visningen sidelæns, op eller ned.", + "navbar.description.projection": "Skifter mellem ortografisk visning og perspektivvisning.", + "navbar.description.separator": "En tynd streg, der grupperer nabopladser.", + "navbar.description.spin": "Lader visningen dreje rundt, indtil du klikker eller trykker på en tast.", + "navbar.description.visual_style": "Skifter, hvordan modellen tegnes: skyggelagt, som trådmodel eller med skjulte kanter.", + "navbar.description.zoom": "Flytter visningen tættere på modellen eller længere væk fra den.", + "navbar.display": "Visning", + "navbar.fit": "Tilpas", + "navbar.graphics": "Grafik", + "navbar.grid": "Gitter", + "navbar.ground_shadow": "Skygge på grundplan", + "navbar.home": "Hjem", + "navbar.later": "Senere", + "navbar.look_at": "Se på", + "navbar.more": "Mere", + "navbar.orbit": "Rotér visning", + "navbar.orthographic": "Ortografisk", + "navbar.pan": "Panorér", + "navbar.perspective": "Perspektiv", + "navbar.preset": "Forudindstilling", + "navbar.projection": "Projektion", + "navbar.projection_heading": "Projektion", + "navbar.separator": "Skillelinje", + "navbar.show": "Vis", + "navbar.spin": "Drej", + "navbar.style.shaded": "Skyggelagt", + "navbar.style.shaded_with_edges": "Skyggelagt med kanter", + "navbar.style.shaded_with_hidden_edges": "Skyggelagt med skjulte kanter", + "navbar.style.wireframe": "Trådmodel", + "navbar.translucent": "Halvgennemsigtig", + "navbar.value_tip": "{name} · {value}", + "navbar.visual_style": "Visuel stil", + "navbar.zoom": "Zoom", "needs two joints": "kræver to led", + "network.allow_once": "Tillad én gang", + "network.always_allow": "Tillad altid denne server", + "network.prompt_detail": "Dette design linker til en fil på netværksplaceringen {host}. Når filen åbnes, oprettes der forbindelse til den computer, og dit Windows-login kan blive sendt til den. Tillad kun servere, du har tillid til.", + "network.prompt_title": "Netværksplacering", "new configuration": "ny konfiguration", "new parameter": "ny parameter", "no hole": "intet hul", "no interference": "intet overlap", "no joint that moves yet": "endnu intet bevægeligt led", + "no motion study yet": "ingen bevægelsesanalyse endnu", "no picture": "intet billede", + "no such joint": "der findes intet sådant led", "none": "ingen", + "not a move": "ikke en flytning", + "not a number": "ikke et tal", + "open a sketch first": "åbn en skitse først", + "parameters.apply_live": "Anvend hver ændring, når du forlader dens felt", + "parameters.apply_live_tip": "Slået fra: Ændringer venter, til du vælger Anvend eller OK, og så genopbygges designet én gang for dem alle. Annullér eller Escape kasserer dem.", + "parameters.held": "{count} ændringer venter på Anvend", + "parameters.held_hint": "Redigér udtryk og enheder. Ændringer venter på Anvend eller OK.", + "parameters.held_one": "1 ændring venter på Anvend", "parts.automatic_name": "automatisk", + "parts.dimension.across_flats": "Nøglevidde", + "parts.dimension.bore": "Boring", "parts.dimension.d": "Nominel diameter", + "parts.dimension.head_diameter": "Hovedets diameter", + "parts.dimension.head_height": "Hovedets højde", "parts.dimension.height": "Højde", + "parts.dimension.inner": "Indvendig diameter", + "parts.dimension.outer": "Udvendig diameter", "parts.dimension.pitch": "Stigning", + "parts.dimension.socket": "Størrelse på indvendig sekskant", + "parts.dimension.socket_depth": "Dybde af indvendig sekskant", "parts.dimension.thickness": "Tykkelse", "parts.dimension.width": "Bredde", + "parts.family.bearing": "Rillekuglelejer (omrids)", + "parts.family.button_head_cap_screw": "Rundhovedet skrue med indvendig sekskant", + "parts.family.dowel_pin": "Cylindrisk stift (dyvel)", + "parts.family.hex_bolt": "Sekskanthovedet bolt / skrue", + "parts.family.hex_cap_screw_inch": "Sekskantskrue (tommer)", + "parts.family.hex_nut": "Sekskantmøtrik", + "parts.family.hex_nut_inch": "Sekskantmøtrik (tommer)", + "parts.family.set_screw": "Stilleskrue med indvendig sekskant, flad spids", + "parts.family.socket_head_cap_screw": "Cylinderskrue med indvendig sekskant", + "parts.family.washer": "Almindelig skive", + "parts.family.washer_sae": "Almindelig skive, SAE (smal)", + "parts.family.washer_uss": "Almindelig skive, USS (bred)", + "parts.holes": "Huller (valgfrit)", + "parts.placement_hint": "vælg et eller flere huller for at sætte en del i hvert, eller tryk OK for at placere den ved nulpunktet", + "parts.system": "Enhedssystem", + "parts.system.inch": "Tommer", + "parts.system.metric": "Metrisk", "pattern.alignment_2": "Justering 2", "pattern.alignment_hint": "Antal omfatter originalen. Centrér fordeler kopierne ligeligt; Vend vælger siden med den ekstra kopi ved et lige samlet antal.", "pattern.direction_1": "Retning 1", "pattern.direction_2": "Retning 2", "pattern.flip_direction": "Vend retning", + "perf.click_for_details": "Klik for detaljer: billedtidsgraf, histogram og det, GPU'en har tegnet", + "perf.draw_calls": "Tegnekald", + "perf.line_segments": "Linjesegmenter", + "perf.low_1": "Laveste 1 %", + "perf.renderer": "Renderingsmotor", + "perf.scene_build": "Opbygning af scene", + "perf.triangles": "Trekanter", + "perf.ui_time": "UI-tid", + "perf.viewport": "Visningsområde", + "perf.worst": "værst", + "pick a body or some of its faces": "vælg et emne eller nogle af dets flader", "pick a hole to seat it, or OK places it at the origin": "vælg et hul til placeringen, eller tryk OK for at placere ved nulpunktet", + "pick a planar face": "vælg en plan flade", + "pick a plane or a face as the tool": "vælg et plan eller en flade som værktøj", + "pick a size": "vælg en størrelse", + "pick edges of a body": "vælg kanter på et emne", + "pick edges of one body": "vælg kanter på ét emne", + "pick edges of the holes to remove": "vælg kanter på de huller, der skal fjernes", + "pick faces of one body": "vælg flader på ét emne", + "pick faces to offset": "vælg flader, der skal forskydes", + "pick lines of one sketch": "vælg linjer i én skitse", "pick one or two vertices, edges or faces": "vælg et eller to hjørnepunkter, kanter eller flader", + "pick one plane or face as the tool, or sketch curves": "vælg ét plan eller én flade som værktøj, eller skitsekurver", + "pick sections in two or more sketches": "vælg tværsnit i to eller flere skitser", + "pick sketch curves or edges": "vælg skitsekurver eller kanter", + "pick the face to untrim": "vælg den flade, hvis beskæring skal fjernes", + "pick the path": "vælg banen", + "pick what to keep": "vælg, hvad der skal beholdes", + "pick what to keep of the other surface": "vælg, hvad der skal beholdes af den anden overflade", "prefs.add_item": "Tilføj elementet", "prefs.alt_frees_manipulators": "Alt / Option frigør også manipulatorpilene", + "prefs.anti_aliasing_amd_dx12": "Kantudjævning bruger 1×, fordi startkontrollen ikke tegnede noget med multisampling og bestod ved 1×. Du kan vælge en anden indstilling ovenfor. Genstart for at anvende den, hvis kontrollen består.", "prefs.anti_aliasing_note": "Udjævner takkede kanter.", "prefs.applies_on_restart": "Træder i kraft efter genstart", "prefs.assistant": "Assistent", + "prefs.auto_operation": "Vælg operationen automatisk", + "prefs.auto_operation_note": "Featurevinduer vælger Foren, Nyt emne eller Skær fra ud fra det, det nye materiale berører, indtil du selv vælger en. Slået fra: De beholder den operation, de åbnes med.", "prefs.axes": "Akser", "prefs.axis": "Akse", + "prefs.bodies_folders": "Emnemapper", + "prefs.bodies_folders_always": "Altid", + "prefs.bodies_folders_never": "Aldrig", + "prefs.bodies_folders_several": "Kun ved flere emner", "prefs.bottom": "Bund", + "prefs.bottom_centre": "Nederst i midten", + "prefs.bottom_right": "Nederst til højre", "prefs.browser": "Modelbrowser", + "prefs.browser_eye_left": "Øje ved siden af foldepilen", + "prefs.browser_eye_left_note": "Rækkerne i modeltræet viser deres øje til vis/skjul ved siden af foldepilen som før i stedet for i en kolonne yderst til højre i rækkerne.", + "prefs.browser_reveal_on_hover": "Vis, når musen holdes over", + "prefs.browser_show_note": "Vist holder modeltræet på skærmen. Vis, når musen holdes over skjuler det, indtil markøren kommer hen over dets plads eller den tynde fane ved dets venstre kant. Det forbliver åbent, mens markøren er inde i det, eller en menu fra det er åben.", + "prefs.browser_shown": "Vist", "prefs.built_in": "Indbygget", "prefs.button_left": "Træk med venstre museknap", "prefs.button_middle": "Træk med midterste museknap", "prefs.button_right": "Træk med højre museknap", + "prefs.carousel_next": "Næste", + "prefs.carousel_previous": "Forrige", "prefs.choose_font": "Vælg skrifttypefil…", "prefs.click": "Klik", "prefs.contact_shading": "Blød kontaktskygning", @@ -1264,15 +2180,26 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Krumme overflader", "prefs.curves": "Krumme overflader", + "prefs.cut_preview_tint": "Vis fjernet materiale i rødt", + "prefs.cut_preview_tint_help": "En forhåndsvisning udfylder det materiale, som en feature fjerner, og den form, den erstatter, med et rødt, gennemsigtigt spøgelse. Når indstillingen er slået fra, er udfyldningerne helt gennemsigtige, og kun deres omrids tegnes.", + "prefs.dark_parts_shading": "Bevar formen på mørke dele", + "prefs.dark_parts_shading_help": "Skygger visningen i lineært lys med en blød himmelfyld, så mørke flader beholder et farveforløb i stedet for at blive sorte", "prefs.dead_zone_note": "Det skraverede bånd er dødzonen: Bevægelser inden for det ignoreres.", "prefs.default": "standard", "prefs.design": "Standardindstillinger for design", "prefs.design_note": "Udgangspunktet for nye design. Åbne design beholder deres egne indstillinger.", "prefs.devices": "3D-mus", + "prefs.dialog_buttons": "Dialogknapper", + "prefs.dialogs": "Dialoger", + "prefs.dialogs_edge": "Ved visningens kant", + "prefs.dialogs_left_column": "I venstre kolonne", + "prefs.dialogs_note": "Hvor kommandodialoger åbnes: Fastgjort ved visningens kant eller i venstre kolonne i stedet for modeltræet og historikken, som vender tilbage, som de var, når dialogen lukkes.", "prefs.display": "Visning", "prefs.edges": "Kanter og skygning", "prefs.extend": "Udvid", "prefs.extra_navigation": "Ctrl+træk med venstre museknap i et tomt område roterer visningen; hold mellemrumstasten nede for at panorere.", + "prefs.extrude_view_isometric": "Drej visningen til isometrisk, når Ekstrudering åbnes", + "prefs.extrude_view_return": "Gå tilbage til den tidligere visning, når Ekstrudering lukkes", "prefs.follows_os": "Følger operativsystemet", "prefs.font": "Skrifttype", "prefs.font_fallback": "Tegn, som den valgte skrifttype mangler, vises med den indbyggede skrifttype, så ingen tekst viser en tom firkant.", @@ -1284,24 +2211,57 @@ "prefs.gesture_pan": "Panorér", "prefs.gesture_zoom": "Zoom", "prefs.graphics": "Grafik", + "prefs.graphics_card": "Grafikkort", + "prefs.graphics_card_auto": "Automatisk", + "prefs.graphics_card_missing": "Det gemte grafikkort er ikke tilgængeligt. Automatisk bruges i stedet.", + "prefs.graphics_card_restart": "Træder i kraft efter genstart af SolidCraft. WGPU_ADAPTER_NAME tilsidesætter dette valg.", + "prefs.graphics_card_unused": "Det gemte grafikkort blev ikke brugt til dette vindue. Kortet i brug vises i Hjælp › Om og i statuslinjen. Prøv Automatisk, eller sæt WGPU_ADAPTER_NAME til en entydig del af kortets navn.", "prefs.graphics_note": "Afvej hastighed mod udjævning. Hvert valg viser sin virkning på et eksempel.", "prefs.graphics_presets_note": "Forudindstillinger angiver de nedenstående valg samlet.", + "prefs.hide_constraint_glyphs_zoomed_out": "Skjul bindingssymboler, når der zoomes ud", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Bindingssymboler forsvinder fra visningen, når skitsen er zoomet så langt ud, at de ville fylde for meget. Slået fra: De bevarer en fast størrelse på skærmen ved alle zoomniveauer.", "prefs.history": "Historik", + "prefs.history_origin_bodies": "Vis nulpunkt og emner øverst", + "prefs.history_origin_bodies_note": "Historikken til venstre eller under modeltræet starter med den aktive komponents mappe Emner og Nulpunktet med deres øjne og menuer som i modeltræet. Historikken nederst er uændret.", + "prefs.history_play_button": "Knappen Afspil historik i historikkens kontroller", + "prefs.history_play_button_note": "Placerer Afspil historik mellem Gå ét trin tilbage og Gå ét trin frem i historikkens kontroller. Du kan også højreklikke på kontrollerne for at vise eller skjule knappen.", + "prefs.history_sketches": "Skitser", + "prefs.history_sketches_in_order": "I rækkefølge", + "prefs.history_sketches_note": "Når Skitser er sat til Under deres feature, viser historikken til venstre hver skitse ét niveau inde under den første feature, der er bygget på den, så snart den er bred nok til navne. Tidslinjen nederst bevarer altid oprettelsesrækkefølgen.", + "prefs.history_sketches_under_feature": "Under deres feature", "prefs.hold_stop_snapping": "Hold nede for at slå snapping fra", + "prefs.home_fit_size": "Størrelse ved Hjem og Tilpas", + "prefs.home_fit_size_note": "Hvor meget af visningen modellen fylder, når Hjem, Tilpas, et åbnet design eller et skift af visning i navigatoren rammer den ind, uanset om indstillingen nedenfor er slået til. 100 %: Fylder visningen mellem panelerne, kompasset og navigationslinjen.", "prefs.icons_only": "Kun ikoner", "prefs.imported_file": "Importeret fil", + "prefs.in_browser": "I modeltræet", "prefs.input": "Input", "prefs.interface": "Brugergrænseflade", "prefs.interface_language": "Sprog i brugergrænsefladen", "prefs.interface_note": "SolidCrafts udseende og placeringen af dets dele.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Vend de buede rulningspile om", + "prefs.invert_curved_roll_arrows_note": "De to buede pile i kubens hjørne ruller visningen i skærmplanet. Slået til: Pilen med uret ruller mod uret, og pilen mod uret ruller med uret. Slået fra: Hver pil ruller visningen den vej, den krummer.", + "prefs.invert_navigator_arrows": "Vend visningskubens rotationspile om", + "prefs.invert_navigator_arrows_note": "Pilene rundt om kuben roterer kameraet i den retning, de peger, som i Fusion og Inventor: Pilen til venstre peger mod højre og svinger kameraet til højre. Slået fra: En pil drejer kuben mod den side, den sidder på, så venstre pil svinger kameraet til venstre. De buede rulningspile påvirkes ikke.", + "prefs.keep_work_on_tab_switch": "Behold dialoger og værktøjer åbne, når du skifter design", + "prefs.keep_work_on_tab_switch_note": "Hver designfane beholder sin åbne dialog eller sit åbne værktøj med det, du har valgt og skrevet i den, og sin fane på båndet. De er der igen, når du vender tilbage til designet. Slået fra: Skift af design annullerer dem og viser fanen Model.", "prefs.labels": "Etiketter", + "prefs.language_system": "System", "prefs.layout": "Layout", "prefs.layout_note": "Kompakt fastgør panelerne til vinduets kanter. Gennemsigtighed i modelbrowseren er tilgængelig i Flydende. Skift assistentens side på siden Assistent.", "prefs.left": "Venstre", "prefs.left_click": "Venstreklik", + "prefs.line_drag_draws_one": "Tryk og træk tegner én linje", + "prefs.line_drag_draws_one_note": "I værktøjet Linje tegner tryk, træk og slip én linje fra trykket til slippet, og linjen slutter dér. Klik tegner stadig en kæde. Slået fra: Et træk placerer et punkt, hvor det slippes, ligesom et klik gør.", + "prefs.line_hover_tangent_arc": "Hvil markøren på en linjes sidste punkt for at skifte til en tangentbue", + "prefs.line_hover_tangent_arc_note": "Når et segment er tegnet i værktøjet Linje, så flyt markøren væk fra kædens sidste punkt, kom tilbage, og hold den stille på punktet: Næste klik afslutter en tangentbue, og samme bevægelse går tilbage til linjer. Slået fra: Det gør ingenting at hvile markøren der.", + "prefs.linked_designs": "Linkede designs", "prefs.live_input": "Løbende input", "prefs.live_preview": "Løbende forhåndsvisning", + "prefs.logo": "Logo", + "prefs.logo_accent": "Accentfarve", + "prefs.logo_theme": "Temaets farver", "prefs.max_file_size": "Største fil, der kan åbnes", "prefs.max_file_size_design": "Designfiler", "prefs.max_file_size_flag": "Denne kørsel blev startet med --max-file-size {size}, som gælder, indtil SolidCraft lukkes. Disse indstillinger gælder ved start uden denne valgmulighed.", @@ -1309,6 +2269,9 @@ "prefs.max_file_size_step": "STEP- og importfiler", "prefs.max_file_size_web": "Webappen åbner STEP- og importfiler op til 512 MB og design op til 256 MB: en browserfane kan ikke rumme større filer. Grænserne kan hæves i skrivebordsappen.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Store ikoner", + "prefs.menu_list": "Liste", + "prefs.menus": "Menuer", "prefs.minutes": "minutter", "prefs.minutes_suffix": " min", "prefs.mouse": "Mus og pegefelt", @@ -1316,88 +2279,772 @@ "prefs.mouse_mapping": "Musetildeling", "prefs.navigation": "Navigation", "prefs.navigation_note": "Hvordan musen, pegefeltet og 3D-musen styrer visningen.", + "prefs.navigator_fit": "Tilpas modellen efter et skift af visning i navigatoren", + "prefs.navigator_fit_note": "En flade, et hjørne eller en pil på visningskuben eller en akse på orienteringsgizmoen ser også mod modellens midte fra den ene afstand, der får den til at passe fra alle sider (dens omsluttende kugle). Hjem bruger samme zoom og centrum, mens dette er slået til, så visninger, der vælges bagefter, kun drejer. Slået fra: Visningen drejer på stedet og beholder sit mål og sin zoom.", + "prefs.network_host_remove": "Fjern", + "prefs.network_locations": "Tillad netværksplaceringer i designs", + "prefs.network_locations_note": "Slået fra: Et designs linkede filer på en anden computer (\\\\server\\share) åbnes kun fra de servere, der er angivet her, eller efter at du har tilladt en, når du bliver spurgt.", + "prefs.network_locations_section": "Netværksplaceringer", "prefs.not_on_gpu": "ikke på denne GPU", "prefs.on": "Til", "prefs.opaque": "Uigennemsigtig", "prefs.orbit_snap": "Hold Shift nede under rotation af visningen for at snappe til en akse.", "prefs.orientation": "Orientering", + "prefs.origin_plane_names": "Navne på nulpunktets planer", + "prefs.origin_plane_names_note": "Navne vist i modeltræet, dialoger og lister. {top} er XY, {front} er XZ og {right} er YZ med Z opad. Kommandoer, scripts og gemte designs beholder XY, XZ og YZ.", "prefs.overall_speed": "Samlet hastighed", + "prefs.parameter_list_rows": "Rækker i parameterlisten", + "prefs.parameter_list_rows_tip": "Pil ned i et tomt værdifelt viser parametrene, favoritter først, op til så mange. Færre holder listen let i et stort design.", + "prefs.persistent_ribbon_pressed": "Fremhæv aktive kommandoer på båndet", + "prefs.persistent_ribbon_pressed_help": "Fremhæver kommandoer på båndet, mens deres virkning er slået til. Slå fra for at beholde det tidligere neutrale udseende og den tidligere kommandohjælp.", + "prefs.perspective_fov": "Synsfelt", + "prefs.placement": "Placering", + "prefs.prefer_free_sketch_points": "Foretræk flytbare skitsepunkter, når punkter overlapper", "prefs.preview_choices": "Forhåndsvisning af dine valg", + "prefs.preview_tint_new_faces": "Farv ny overflade i en forhåndsvisning", + "prefs.preview_tint_new_faces_help": "En forhåndsvisning af en feature, der ændrer et emne, kan tegne den overflade, den tilføjer, i forhåndsvisningens farve. Når indstillingen er slået fra, tegnes emnet, som det er.", + "prefs.print_face_highlight": "Fremhævning af printflade", + "prefs.print_face_highlight_tip": "Hvor kraftigt et legemes printflade farves og omrids i visningen. 0 % viser ingen fremhævning.", + "prefs.profile_active": "Aktiv profil", + "prefs.profile_applied": "Profil anvendt.", + "prefs.profile_changed": "Indstillingerne er ændret, siden profilen blev gemt. Gem beholder dem i profilen.", + "prefs.profile_deleted": "Profil slettet.", + "prefs.profile_export": "Eksportér…", + "prefs.profile_exported": "Profil eksporteret.", + "prefs.profile_imported": "Profil importeret. Vælg den under Aktiv profil for at skifte til den.", + "prefs.profile_name_hint": "Profilnavn, f.eks. Bærbar", + "prefs.profile_rename": "Omdøb", + "prefs.profile_renamed": "Profil omdøbt.", + "prefs.profile_save": "Gem", + "prefs.profile_saved": "De aktuelle indstillinger er gemt i profilen.", + "prefs.profile_skipped": "Profil anvendt. {n} indstilling(er) beholdt deres nuværende værdi (se loggen).", + "prefs.profiles": "Indstillingsprofiler", + "prefs.profiles_note": "Genveje, værktøjslinjen, navigation, den radiale menu og indstillinger for brugerfladen gemmes samlet under et navn, så du kan skifte mellem dem med ét klik.", + "prefs.project_options_dialog": "Dialog med projektionsindstillinger", + "prefs.project_options_dialog_note": "Slået til: Vælg Geometri eller Emner og Projektionslink, før du projicerer. Slået fra: Behold den tidligere arbejdsgang med direkte valg.", "prefs.quality_default": "standard", "prefs.quality_fastest": "hurtigst", "prefs.quality_slowest": "langsomst", "prefs.quality_smoother": "mere udjævnet", + "prefs.quick_measure": "Hurtigmåling i visningens hjørne", + "prefs.quick_measure_note": "Markeringens størrelse i visningens nederste højre hjørne: en kants længde eller Ø og R for en rund kant, en flades areal, et punkts position, afstand og vinkel mellem to elementer eller den samlede værdi for flere kanter eller flader. Et klik kopierer den.", + "prefs.render_previous_geometry_budget": "Brug det tidligere geometribudget til forhåndsvisning af rendering", + "prefs.render_previous_geometry_budget_help": "Gendan den tidligere faste geometrigrænse (512 MiB på 64-bit-computere, 128 MiB andre steder) i stedet for det enhedsbaserede budget.", "prefs.reports_saved": "{n} gemt", + "prefs.ribbon_click_ends_tool": "Et klik på det kørende værktøjs knap afslutter det", + "prefs.ribbon_click_ends_tool_note": "Et klik på den lysende knap på båndet for det skitseværktøj, der er i brug, afslutter værktøjet, så klik i visningen markerer igen. Slået fra: Klikket starter værktøjet igen.", + "prefs.ribbon_reveal": "Vis søgeresultater på båndet", + "prefs.ribbon_reveal_note": "Når du holder musen over et resultat i Søg efter kommandoer, vises det, hvor kommandoen sidder på båndet: dens fane, dens knap eller dens række i et panels rullemenu. En kommando, der startes fra søgningen, blinker dér, og en kørende kommando fra en rullemenu markerer sit panel.", "prefs.right_click": "Højreklik", "prefs.saving": "Automatisk lagring og gendannelse", "prefs.scale_note": "Også Ctrl + / Ctrl − i vinduet. Knapper er 28 px ved 100%.", "prefs.scale_text": "Skalering og tekst", + "prefs.search": "Søg i indstillinger", + "prefs.search_empty": "Ingen matchende indstillinger", "prefs.select": "Vælg", "prefs.select_one_item": "Vælg ét element", + "prefs.select_other_hidden": "Vælg skjult geometri med Vælg andet", + "prefs.select_other_hidden_help": "Slået til: Medtag skjulte emner og skitser samt kanter, der er skjult bag andet, nær markøren. Slået fra: Brug den oprindelige liste over synlig geometri under markøren.", "prefs.selecting": "Markering", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift tilføjer kun; Ctrl / Cmd skifter markeringen", "prefs.shift_add_note": "Til: Shift tilføjer, Ctrl / Cmd skifter markeringen. Fra (standard): Begge skifter markeringen.", "prefs.shortcuts": "Genveje", + "prefs.single_surface_analysis": "Brug kun én overfladeanalyse ad gangen", + "prefs.single_surface_analysis_help": "Når den er slået fra, kan overfladeskygning og Kontinuitet være slået til samtidig. Hvis du slår den til, beholdes den sidst startede eller ændrede analyse.", + "prefs.sketch_align_points": "Justér efter andre skitsepunkter under tegning", + "prefs.sketch_align_points_note": "Under tegning justeres et punkt samtidig vandret efter ét skitsepunkt og lodret efter et andet med en punkteret hjælpelinje, og klikket beholder begge justeringer. Slået fra: Kun efter det forrige punkt, én akse ad gangen.", + "prefs.sketch_conflict_colour": "Geometri i konflikt i konfliktfarven", + "prefs.sketch_conflict_colour_note": "Mens en skitses bindinger er i konflikt, tegnes de kurver og punkter, som en fejlende binding holder, også i konfliktfarven og ikke kun dens symbol eller mål. Slået fra: De beholder deres sædvanlige farver.", + "prefs.sketch_construction_lines": "Udvidede værktøjer til hjælpelinjer", + "prefs.sketch_exit_view": "Når en skitse afsluttes", + "prefs.sketch_exit_view.keep": "Behold den aktuelle visning", + "prefs.sketch_exit_view.previous": "Vend tilbage til den forrige visning", + "prefs.sketch_exit_view.unless_rotated": "Vend tilbage, medmindre visningen er roteret", + "prefs.sketch_exit_view_note": "Hvor visningen går hen efter Afslut skitse, Annullér eller et dobbelt tryk på Esc.", + "prefs.sketch_face_activates_part": "Når du skitserer på en dels flade, bliver delen aktiv", + "prefs.sketch_face_activates_part_note": "En skitse, der startes på en flade af en anden komponents emne, aktiverer først den komponent, så skitsen hører til den og bliver hos den del i modeltræet. Delen forbliver aktiv bagefter. Slået fra: Skitsen hører til den aktive komponent.", + "prefs.sketch_open_look_at": "Vend visningen mod en skitse, når den åbnes", + "prefs.sketch_open_look_at_note": "Slået fra: Når en skitse oprettes eller redigeres, forbliver visningen, som den er. Se på vender visningen mod skitsen, når du ønsker det.", + "prefs.sketch_recent_snap": "Automatisk snap til nylige centre og midtpunkter", + "prefs.sketch_recent_snap_note": "Under tegning snappes markøren dér, hvor hjælpelinjerne fra de to seneste cirkelcentre eller midtpunkter på rette kanter krydser hinanden. Slået fra: Hjælpelinjerne er kun visuelle, og markøren flytter sig ikke.", "prefs.sketch_selection": "Skitse og markering", "prefs.sketch_selection_heading": "Skitse og markering", "prefs.sketch_selection_note": "Hvordan skitser snapper, og hvordan klik markerer.", + "prefs.sketch_state_icons": "Skitseikoner i farven for deres tilstand", + "prefs.sketch_state_icons_note": "I historikken og modeltræet får en skitses ikon farven for dens tilstand (ikke fuldt bundet, fuldt bundet eller i konflikt), og værktøjstippet angiver tilstanden. Slået fra: Alle skitser har det samme ikon.", + "prefs.sketch_tab_always": "Vis altid fanen Skitse", + "prefs.sketch_tab_always_note": "Fanen Skitse bliver på båndet lige efter Model, mens ingen skitse er åben. Dens tegneværktøjer starter så en skitse på det valgte plan eller den valgte flade eller på det plan, du vælger næste gang, med værktøjet klar i den.", + "prefs.sketch_tracking_guides": "Hjælpelinjer til justering efter centre og midtpunkter", + "prefs.sketch_tracking_guides_note": "Hold musen over et cirkelcentrum eller midtpunktet på en ret kant, og bevæg den derefter vandret eller lodret for at vise en midlertidig punkteret hjælpelinje.", + "prefs.sketch_tracking_points": "Hjælpelinjer til justering efter endepunkter og hjørner under tegning", + "prefs.sketch_tracking_points_note": "Mens et tegneværktøj venter på et punkt, viser det samme midlertidige punkterede hjælpelinje som ved et centrum eller midtpunkt, når du holder musen over enden af en linje eller bue, et rektangelhjørne eller et frit punkt. Slået fra: kun centre og midtpunkter.", "prefs.sketching": "Skitsering", "prefs.snap_drawing_note": "Mens du tegner eller trækker et skitsepunkt.", "prefs.source": "Kilde", "prefs.speed": "Hastighed", "prefs.stand_up_note": "Når en STEP- eller IGES-fil åbnes med Z opad, tilbydes en kvart omdrejning om X.", + "prefs.stand_up_unknown": "For filer fra ukendte programmer", + "prefs.stand_up_unknown.ask": "Spørg i en dialog", + "prefs.stand_up_unknown.note": "Vis en note", + "prefs.stand_up_unknown.off": "Tilbyd ikke", + "prefs.stand_up_unknown_note": "Hvordan tilbuddet gives, når filens header ikke nævner noget program, der er kendt for at gemme med Y opad. En note vises kun, når filen ser ud til at ligge på ryggen. Spørg i en dialog spørger om hver sådan fil som før.", + "prefs.status_bar": "Statuslinje", + "prefs.status_bar_note": "En tynd linje langs vinduets nederste kant viser, hvad der redigeres, den åbne skitses tilstand i dens farve og designets enheder. Et klik på enhederne ændrer dem. Skitsens tilstand vises så ikke længere i visningens hjørne.", "prefs.status_done": "Færdig", "prefs.status_error": "Fejl", "prefs.status_selected": "Valgt", "prefs.status_warning": "Advarsel", + "prefs.structure.appearance": "Udseende", + "prefs.structure.appearance_note": "Farver, tekst og tilgængelighed.", + "prefs.structure.in_profile": "I profil", + "prefs.structure.layout": "Layout", + "prefs.structure.layout_note": "Hvor vinduets dele sidder.", + "prefs.structure.look": "Look", + "prefs.structure.measure_pointer": "Mål og markør", + "prefs.structure.mouse3d": "3D-mus", + "prefs.structure.mouse3d_note": "SpaceMouse og SpaceNavigator.", + "prefs.structure.navigation_note": "Mus og pegefelt. 3D-musen har sin egen side.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Ændret, siden den blev gemt", + "prefs.structure.profile_hover": "Gemt i indstillingsprofiler", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Skitse", + "prefs.structure.tools": "Værktøjer", + "prefs.structure.tools_note": "Hvordan modelleringsværktøjerne opfører sig.", + "prefs.structure.work": "Arbejde", "prefs.supersampling_brief": "Tegner visningen i større størrelse og nedskalerer den med filtrering: meget skarpt og mere krævende.", "prefs.tab_accent_note": "Accentfarven følger den aktive fane", "prefs.theme_file": "temafil", + "prefs.theme_file_or_paste": "fil eller indsæt", "prefs.theme_follow": "Følg en temafil", "prefs.theme_follow_error": "Ikke anvendt: {error}. Det seneste gyldige tema bevares.", "prefs.theme_follow_launch": "Følges kun denne gang (--theme-file); genindlæses, når et andet værktøj overskriver filen.", "prefs.theme_follow_note": "Genindlæses, når et andet værktøj overskriver filen. Valg af et tema stopper dette.", "prefs.theme_follow_off": "Fra", "prefs.theme_follow_stop": "Stop med at følge", + "prefs.theme_import_hint": "Klik for at vælge en temafil, slip en her, eller tryk på Ctrl+V (Cmd+V på en Mac), mens et tema er kopieret", + "prefs.theme_option_opacity": "Opacitet", + "prefs.theme_option_opacity_help": "Juster opaciteten af flydende paneler. En nedre grænse for læsbarhed beskytter tekst oven på visningsområdets farver.", + "prefs.theme_option_tab_colours": "Fanefarver", + "prefs.theme_option_tab_colours_help": "Brug dette temas panel- og visningsområdefarver for hver fane på båndet.", + "prefs.theme_option_tab_fade_ms": "Faneovergang", + "prefs.theme_option_tab_fade_ms_help": "Tone panel- og visningsområdefarverne over, når du skifter fane. Nul skifter med det samme.", + "prefs.theme_options_badge": "Muligheder", + "prefs.theme_options_more": "Flere · {count}", + "prefs.theme_options_reset": "Nulstil", + "prefs.theme_options_unavailable": "Ikke tilgængelig på denne enhed", + "prefs.theme_paste": "Indsæt tema", + "prefs.theme_paste_none": "Udklipsholderen indeholder intet SolidCraft-tema", "prefs.timeline_half_hour": "−30 min", "prefs.timeline_now": "nu", "prefs.timeline_quarter_hour": "−15", + "prefs.toast_place": "Meddelelser", "prefs.toggle_item": "Tilføj elementet, eller fjern det igen", "prefs.toolbar": "Værktøjslinje", + "prefs.toolbar_tabs": "Værktøjslinjefaner", + "prefs.top": "Top", + "prefs.trackpad_zoom_modifier": "Zoom med rulning med to fingre, mens du holder nede", + "prefs.trackpad_zoom_modifier.alt": "⌥ / Alt", + "prefs.trackpad_zoom_modifier.cmd": "⌘", + "prefs.trackpad_zoom_modifier.ctrl": "Ctrl", + "prefs.trackpad_zoom_modifier.help": "Hold kun denne tast nede for at zoome ved markøren med lodret rulning. Fra beholder den eksisterende rulleadfærd.", + "prefs.trackpad_zoom_modifier.off": "Fra", "prefs.translucent": "Halvgennemsigtig", "prefs.under_browser": "Under modelbrowseren", "prefs.under_cursor": "Under markøren", "prefs.units_precision": "Enheder og præcision", "prefs.updates": "Opdateringer", + "prefs.value_boxes_in_view": "Vis værdier ved siden af deres håndtag i visningen", + "prefs.value_boxes_in_view_tip": "En kommandos værdi (Afstand, Radius…) i en boks ved siden af dens håndtag oven på modellen. Slået fra: Du skriver den i kommandovinduet, som overtager tastaturet efter et valg, og intet dækker modellen.", "prefs.view": "Visningens adfærd", + "prefs.view_confirm_corner": "OK og Annullér i visningens hjørne", + "prefs.view_confirm_corner_note": "Mens en dialog eller en skitse er åben, gør et flueben og et kryds øverst til højre i visningen det samme som dialogens OK og Annullér, eller afslutter og annullerer skitsen. Visningsnavigatoren flyttes ned under dem.", "prefs.viewport": "Visningsområde", + "prefs.viewport_analysis_status": "Vis status for analyser i visningsområdet", + "prefs.viewport_analysis_status_help": "Vis aktive analyser over visningsområdet, åbn deres signaturforklaringer fra hvert element, og brug Esc til at slå den nyeste analyse fra. Slå fra for at gendanne signaturforklaringer i hjørnerne og den tidligere Esc-adfærd.", + "prefs.viewport_background": "Baggrund", + "prefs.viewport_background_colour": "Farve", + "prefs.viewport_background_theme": "Temaets farveforløb", + "prefs.viewport_section_status": "Vis status for snit i visningsområdet", + "prefs.viewport_section_status_help": "Vis snitindstillingen i visningsområdet. Escape og den aktive knap på båndet slår den fra. Slå fra for at beholde de tidligere snitkontroller.", + "prefs.viewport_status_details": "Live-detaljer i visningsområdet", + "prefs.viewport_status_details_help": "Redigér aktive analyse- og snitindstillinger i standarddetaljekort. Slå fra for at gendanne skrivebeskyttede signaturforklaringer til analyser og dialogen Snit.", + "prefs.viewport_status_summary": "Fold statuselementer i visningsområdet sammen", + "prefs.viewport_status_summary_help": "Fold tre eller flere statuselementer i visningsområdet sammen i ét oversigtsmærke. Slå fra for at beholde alle elementer i den fulde række.", "prefs.wheel": "Musehjul", "prefs.wheel_trackpad": "Musehjul og pegefelt", "prefs.workspace": "Arbejdsområde", + "prefs.zoom_stop_at_model": "Stop zoom ved modellen", + "prefs.zoom_stop_at_model_tip": "3D-musen og enhedsappen zoomer mod overfladen midt i visningen; træk-zoom holder fast i det punkt, hvor trækket begyndte. Fra: Zoom kan passere gennem modellen. Hjul og knibebevægelse bruger Zoom mod markøren separat", "prefs.zoom_toward_cursor": "Zoom mod markøren", "properties.title": "Egenskaber: {name}", "recovery.days_ago": "for {count} dage siden", "recovery.detail": "{file} · {features} features · autogemt {when}", + "recovery.discard_all": "Kassér alle", + "recovery.discard_all_detail": "Dette kan ikke fortrydes.", + "recovery.discard_all_title": "Kassér {count} automatiske lagringer?", + "recovery.discard_all_title_one": "Kassér 1 automatisk lagring?", "recovery.hours_ago": "for {count} t siden", "recovery.just_now": "lige nu", "recovery.min_ago": "for {count} min siden", "recovery.never_saved": "aldrig gemt", + "render.adaptive_absolute": "Absolut nedre grænse for RGB-fejl", + "render.adaptive_coverage": "Mål for dækningsfejl", + "render.adaptive_enable": "Fordel samples med uafhængige piloter", + "render.adaptive_help": "Kun GPU. Uafhængige pilot-samples kasseres, hvorefter 16 eller flere produktions-samples pr. pixel fordeles op til Samples pr. pixel. RGB- og dækningsvarians styrer fordelingen; sjældne lysstier kan blive overset, og pixels, der har nået loftet, kan forblive støjende. Den endelige rapport tæller det faktiske arbejde. Ingen certificeret garanti for støj eller tid.", + "render.adaptive_minimum": "Mindste antal produktions-samples", + "render.adaptive_pending": "GPU-baseret adaptiv fordeling med uafhængige piloter og betingede Fresnel-strata er tilgængelig. Certificeret konvergens, garantier for sjældne hændelser og adaptiv CPU-lystransport er stadig ikke tilgængelige.", + "render.adaptive_pilots": "Pilot-samples pr. pixel", + "render.adaptive_relative": "Mål for relativ RGB-fejl", + "render.add_ground": "Tilføj tilpasset grundplan til opsætningen", + "render.advanced_material_scope": "Ét afgrænset, homogent GPU-medium er tilgængeligt inden for eksplicitte grænser. Densitetsgitre, indlejrede kombinationer af glas og volumen, subsurface-overflader, displacement, spektral lystransport og ubundne avancerede materialekoncepter er stadig ikke tilgængelige.", + "render.aging_add": "Tilføj ældningslag", + "render.aging_airborne": "Støv i luften / deltagende medium", + "render.aging_airborne_help": "Støv i luften er et separat, afgrænset og homogent spredningsvolumen. Det ændrer lystransporten og den rå EXR, ikke stakken af overfladeældning. De eksisterende begrænsninger for volumen, glas og støjreduktion gælder fortsat eksplicit; der tilføjes ingen atmosfære automatisk.", + "render.aging_all_bodies": "Alle egnede uigennemsigtige emner", + "render.aging_chips": "Afskallet maling", + "render.aging_class_any": "Alle uigennemsigtige materialeklasser", + "render.aging_class_dielectric": "Kun ikke-metalliske overflader", + "render.aging_class_metal": "Kun metalliske overflader", + "render.aging_color": "Lagets farve · sRGB", + "render.aging_coverage": "Dækning", + "render.aging_dust": "Aflejret støv", + "render.aging_empty": "Ingen ældningslag: de oprindelige overflader forbliver uændrede.", + "render.aging_fading": "Falmet belægning", + "render.aging_grime": "Snavs og pletter", + "render.aging_help": "Kombinér op til otte optiske lag i rækkefølge. Rust og patina er designede udseender, ikke simuleringer af ældning eller korrosion. Skalaen er i mm i verdenskoordinater. Ingen geometri, masse eller teknisk egenskab ændres; glas og passive kulisser er udeladt.", + "render.aging_metallic": "Lagets metalliske andel", + "render.aging_origin": "Feltets nulpunkt · mm i verdenskoordinater", + "render.aging_patina": "Kobbergrøn patina", + "render.aging_refresh_targets": "Undersøg aktuelle emner", + "render.aging_roughness": "Lagets ruhed", + "render.aging_rust": "Oxideret jern / rust", + "render.aging_scale": "Mønsterskala", + "render.aging_scratches": "Fine ridser", + "render.aging_target": "Mål og koordinater", + "render.aging_target_help": "Et navngivet mål skal stadig passe til sit registrerede indeks og navn. Globale masker er forankret i verden; de følger ikke bevægelige dele. Dette er hverken registrering af hulrum eller ægte kantslitage. Filtrér listen for at nå flere emner.", + "render.aging_target_search": "Filtrér emnenavne", + "render.aging_upward": "Aflejring på opadvendte overflader", + "render.all_controls_help": "Tæt oversigt over alle aktuelle indstillinger. Sektionssiderne giver fokuseret redigering uden at ændre den underliggende anmodning.", + "render.all_shots_label": "Alle optagelser", + "render.appearance_editor.absorption": "Absorption", + "render.appearance_editor.base_colour": "Basisfarve", + "render.appearance_editor.body_reason": "Optiske bindinger gælder for ét helt emne. Vælg Emne for at redigere disse indstillinger.", + "render.appearance_editor.boundary": "Afgrænsning", + "render.appearance_editor.box": "Boks", + "render.appearance_editor.choose_image": "Vælg billede…", + "render.appearance_editor.closed": "Lukket solid", + "render.appearance_editor.coat": "Klarlak", + "render.appearance_editor.cpu_reason": "Kræver CPU ray tracing.", + "render.appearance_editor.glass": "Glas og absorption", + "render.appearance_editor.glass_enable": "Brug fysisk glas på dette emne", + "render.appearance_editor.glass_note": "Lukket glas bruger geometrisk afstand. Det kan ikke dele emne med klarlak eller teksturkort.", + "render.appearance_editor.gpu_reason": "Kræver GPU path tracing.", + "render.appearance_editor.ior": "IOR", + "render.appearance_editor.maps": "Teksturkort", + "render.appearance_editor.normal": "Normal", + "render.appearance_editor.normal_strength": "Normalstyrke", + "render.appearance_editor.origin": "Nulpunkt", + "render.appearance_editor.recipe": "Recept", + "render.appearance_editor.reflection_sampling": "Sampling for alle reflekterende emner", + "render.appearance_editor.reflections": "Refleksioner", + "render.appearance_editor.remove": "Fjern gemt", + "render.appearance_editor.remove_note": "Fjern den gemte optik fra denne optagelse. Geometri og tildelte udseender bevares.", + "render.appearance_editor.remove_title": "Fjern gemt optik?", + "render.appearance_editor.replace": "Erstat dette emnes gemte optik", + "render.appearance_editor.revalidate": "Kontrollér dette emne igen", + "render.appearance_editor.save": "Gem denne optik", + "render.appearance_editor.save_reason": "For at gemme denne optik skal der bruges fysisk glas på et aktuelt GPU-emne. Klarlak og lokale billedkort forbliver midlertidige.", + "render.appearance_editor.saved": "Gemt sammen med denne optagelse", + "render.appearance_editor.saved_state": "Denne optik er gemt sammen med denne optagelse.", + "render.appearance_editor.scatter_reason": "Spredning i det indre kræver en lukket solid afgrænsning.", + "render.appearance_editor.temporary": "Denne optik er midlertidig på denne fane. Gem den for at beholde den sammen med optagelsen.", + "render.appearance_editor.thickness": "Tykkelse", + "render.appearance_editor.thickness_reason": "Tykkelse gælder for tynde plader; lukket glas bruger geometrisk afstand.", + "render.appearance_editor.thin": "Tynd plade", + "render.appearance_editor.u_repeat": "U-gentagelse", + "render.appearance_editor.v_repeat": "V-gentagelse", + "render.appearance_editor.v_up": "Teksturens V peger opad", + "render.appearance_editor.weight": "Vægt", + "render.appearance_physics_separate": "Visuelt udseende tildeler hverken densitet, termiske data eller andre tekniske egenskaber.", + "render.appearances": "Udseender", + "render.assign_help": "Klik for at anvende på markeringen; træk for at se en forhåndsvisning og slip for at anvende, eller klik uden markering for at male.", + "render.availability_native": "Indbygget sammensætning; gennemgå, før den anvendes", + "render.availability_projection": "Understøttet overførsel; se omfang og udeladelser", + "render.availability_reference": "Referencedata; ikke en automatisk tildeling", + "render.backdrop_alpha_conflict": "Vælg enten denne kamerabaggrund eller gennemsigtigt PNG-output; renderingsmotoren ignorerer ikke stiltiende nogen af indstillingerne.", + "render.backdrop_enable": "Brug farveforløb som kamerabaggrund", + "render.backdrop_first": "Startfarve / midterfarve", + "render.backdrop_help": "Denne kamerabaggrund i skærmrummet belyser ikke, kaster ikke skygger, optræder ikke i refleksioner og forestiller ikke terræn. Den er udeladt fra den rå EXR. Geometri, lys og HDR-omgivelserne forbliver uafhængige.", + "render.backdrop_horizontal": "Vandret farveforløb", + "render.backdrop_radial": "Radialt farveforløb", + "render.backdrop_radius": "Radius", + "render.backdrop_second": "Slutfarve / kantfarve", + "render.backdrop_vertical": "Lodret farveforløb", + "render.backdrop_x": "Centrum X", + "render.backdrop_y": "Centrum Y", "render.background": "Scenebaggrund", + "render.background_camera_section": "Kamerabaggrund · PNG-præsentation", + "render.background_completed_frozen": "Det viste resultat er et frosset, færdigt billede. Redigering af en baggrund gentegner ikke resultatet automatisk. Brug Gradér igen til ændringer, der kun gælder kameraet, eller Render til en ny fysisk kulisse.", + "render.background_hdr_separate": "De aktuelle HDR-ressourcer belyser overflader og spejler sig i dem; de vises ikke automatisk som et panorama bag motivet. Ændring af et farveforløb roterer eller omfarver ikke belysningen.", + "render.background_lighting_section": "HDR-belysning · adskilt fra kamerabaggrunden", + "render.background_no_alpha_override": "En kamerabaggrund føjes ikke stiltiende til gennemsigtigt output. Ny farvegradering af den rå master bruger registreret dækning og anvender ikke støjreduktion igen; kilde-EXR'en forbliver uændret.", + "render.background_not_light": "Baggrundsfarven er præsentation, ikke en ekstra lyskilde.", + "render.background_regrade": "Anvend på bevaret rå master", + "render.background_stage_occlusion": "Denne optagelse indeholder fysisk kulissegeometri. Et stort gulv eller en stor væg kan fylde billedet og skjule en kamerabaggrund. Fjern kulissen eller ændr dens størrelse bevidst, eller ændr dens fysiske reflektans. Ny farvegradering kan ikke fjerne registreret geometri.", + "render.background_workflow": "Vælg den baggrund, du ønsker: en kamerabaggrund med farve eller farveforløb, en fysisk kulisse, der modtager lys, eller HDR-belysning. De er uafhængige. Live-forhåndsvisning er en modelleringsvisning; render et nyt billede, eller gradér en bevaret master igen for at se kameraets efterbehandling.", + "render.base_appearance": "Redigerbart emneudseende", + "render.base_apply": "Anvend emneudseende", + "render.base_apply_help": "Én tildeling af udseende, som kan fortrydes, til det gennemgåede, præcise emne. Eksisterende fladespecifikke udseender og fysiske materialer forbliver adskilte.", + "render.base_color": "Basisfarve · sRGB", + "render.base_metallic": "Metallisk andel", + "render.base_opaque_only": "Denne editor bevarer emnets uigennemsigtighed. Brug de eksplicitte glasindstillinger til optisk transmission.", + "render.batch_all_shots": "Alle optagelser ({count})", + "render.batch_empty": "Gem en optagelse, før alle optagelser renderes.", + "render.batch_limit": "Rendering af alle optagelser er begrænset til 32 optagelser.", + "render.batch_status": "{running} kører · {waiting} venter", + "render.bloom_enable": "Vis bloom", + "render.bloom_help": "En kreativ glød, der kun påvirker output, ud fra positive lineære højlys og spredt med tre normaliserede box-pas. Radius er i outputpixels. Lægges til i lineært visningslys før sRGB; ikke en linseeffekt, en volumeneffekt eller en forbedring af konvergens. Den rå EXR er uændret.", + "render.bloom_opaque": "Bloom kræver uigennemsigtigt output. Gennemsigtig PNG afvises og gøres ikke stiltiende uigennemsigtig.", + "render.bloom_radius": "Bloom-radius", + "render.bloom_strength": "Bloom-styrke", + "render.bloom_threshold": "Tærskel for lineære højlys", + "render.browse_capabilities": "Undersøg det fulde katalog over muligheder", + "render.browse_environments": "Gennemse originale HDR-omgivelser", + "render.browse_looks": "Gennemse…", + "render.browse_native_scenes": "Gennemse indbyggede studioer", + "render.browse_physical": "Undersøg fysiske referencer", + "render.browse_quality": "Undersøg kvalitetsspecifikationer", + "render.browse_rigs": "Gennemse designede lysrig", + "render.browse_scene_specs": "Gennemse avancerede scenespecifikationer", + "render.browse_surfaces": "Gennemse designede overflader", + "render.browser_library": "Bibliotek", + "render.browser_model": "Model", + "render.camera_distance": "Afstand fra øje til mål", + "render.camera_exact_help": "Mm i verdenskoordinater; vinkler vises i grader og gemmes som radianer. Navigationen bruger samme kamera som visningsområdet.", + "render.camera_fov": "Lodret synsfelt", + "render.camera_pitch": "Stampning", + "render.camera_roll": "Rulning", + "render.camera_set": "Angiv renderingskamera", + "render.camera_target": "Målposition · mm", + "render.camera_yaw": "Krøjning", + "render.category_metal": "Metal", + "render.category_paint": "Maling", + "render.category_plastic": "Plast", + "render.category_wood": "Træ", + "render.check_opaque": "Gennemsigtighed: kun uigennemsigtige overflader; baggrundsalfa understøttes.", + "render.check_sorted_alpha": "Gennemsigtighed: tilnærmelse med sorteret alfa.", + "render.check_transmission": "Gennemsigtighed: fysisk transmission.", + "render.children.absolute_floor": "Absolut grænse", + "render.children.adaptive": "Adaptiv", + "render.children.add_look_reason": "Tilføj et look for at redigere, om det er aktiveret, og dets styrke.", + "render.children.all_shots": "Alle optagelser", + "render.children.bloom": "Bloom", + "render.children.check": "Kontrollér", + "render.children.check_now": "Kontrollér nu", + "render.children.chromatic": "Kromatisk", + "render.children.compact": "Kompakt", + "render.children.contrast": "Kontrast", + "render.children.copy_image": "Kopiér", + "render.children.copy_job": "Kopiér job-JSON", + "render.children.copy_request": "Kopiér anmodnings-JSON", + "render.children.coverage_error": "Dækningsfejl", + "render.children.cpu": "CPU ray tracing", + "render.children.denoise": "Reducér støj i det færdige billede", + "render.children.depth": "Path-dybde", + "render.children.distortion": "Forvrængning", + "render.children.edge_samples": "Kant-samples", + "render.children.effects_banner": "Disse effekter kræver GPU path tracing. Åbning af dette ændrer aldrig metoden.", + "render.children.enable_adaptive": "Aktivér uafhængige piloter for at redigere de adaptive grænser.", + "render.children.enable_bloom": "Aktivér bloom for at redigere dens styrke, tærskel og radius.", + "render.children.finishing": "Efterbehandling", + "render.children.flare": "Flare", + "render.children.fresnel": "Fresnel-strata", + "render.children.ghosts": "Ghost-ringe", + "render.children.glass": "Glas-lystransport", + "render.children.go_to": "Gå til {editor}", + "render.children.grain": "Filmkorn", + "render.children.halo": "Halo", + "render.children.hdr": "HDR", + "render.children.keep_master": "Behold lineær rå master", + "render.children.last_result": "Seneste: {number} · {width} × {height} · {phase}", + "render.children.lens_effects": "Linseeffekter", + "render.children.look_summary": "{tone} · {count} looks", + "render.children.looks": "Kreative looks", + "render.children.memory": "Hukommelse", + "render.children.method": "Metode", + "render.children.minimum": "Minimum", + "render.children.needs_cpu": "Kræver CPU ray tracing. Åbning af dette ændrer aldrig metoden.", + "render.children.nested": "Certificerede indlejrede dielektrika", + "render.children.not_checked": "Ikke kontrolleret", + "render.children.path": "Path tracing", + "render.children.pilots": "Pilot-samples", + "render.children.preview": "Forhåndsvisningsdata", + "render.children.progressive_reason": "Vælg Progressiv for at redigere antal samples og seed.", + "render.children.radius": "Radius", + "render.children.reflect_depth": "Refleksionsdybde", + "render.children.reflect_samples": "Refleksions-samples", + "render.children.regrade": "Gradér igen", + "render.children.relative_error": "Relativ fejl", + "render.children.render": "Render", + "render.children.render_shot": "Render optagelse", + "render.children.renderer": "Renderingsmotor", + "render.children.renderers": "Renderingsmotorer", + "render.children.request": "Denne anmodning", + "render.children.reset_finishing": "Nulstil efterbehandling", + "render.children.review_quality": "Gennemgå en kvalitetsspecifikation…", + "render.children.rgb_gain": "RGB-forstærkning", + "render.children.samples": "Samples", + "render.children.sampling": "Sampling", + "render.children.saturation": "Farvemætning", + "render.children.scene_summary": "{bodies} emner · {triangles} trekanter", + "render.children.seed": "Seed", + "render.children.sharpening": "Skærpning", + "render.children.single_image": "Enkeltbillede", + "render.children.soft_focus": "Blødt fokus", + "render.children.streak": "Striber", + "render.children.strength": "Styrke", + "render.children.studio": "Studio", + "render.children.threshold": "Tærskel", + "render.children.tone": "Tone", + "render.children.under_hood": "Under motorhjelmen", + "render.children.vignette": "Vignettering", + "render.children.workstation": "Arbejdsstation", + "render.choose_look": "Vælg først et udseende under Udseender", + "render.chromatic_offset": "Kromatisk kantforskydning", + "render.clear_stage": "Fjern gemt kulisse", + "render.compare_divider": "Sammenligningens skillelinje", + "render.compare_live": "Live", + "render.compare_live_preview": "Live-forhåndsvisning", + "render.compare_render": "Rendering {number}", + "render.compare_side": "Rendering {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · registreret ved revision {revision}", + "render.compare_swap": "Ombyt", + "render.copy_request": "Kopiér JSON", + "render.cpu_aa_help": "Rumlige samples: flere samples forbedrer kanter og øger renderingstiden.", + "render.cpu_area_add": "Tilføj rektangulært CPU-lys", + "render.cpu_area_editor": "Rektangulære CPU-lys", + "render.cpu_area_editor_help": "Fulde sidevektorer i millimeter; krydsproduktet U × V peger mod den side, der udsender lys. Det adskiller sig fra GPU'ens halvkantvektorer.", + "render.cpu_area_full_u": "Fuld U-side · mm", + "render.cpu_area_full_v": "Fuld V-side · mm", + "render.cpu_area_samples": "Samples for arealys", + "render.cpu_binding_confirm": "Bekræft dette emne", + "render.cpu_binding_stale": "Scenen er ændret. Bekræft dette refleksionsmål igen, før der renderes.", + "render.cpu_body_choose": "Vælg et emne", + "render.cpu_body_filter": "Filtrér emner efter navn", + "render.cpu_body_filter_more": "Forfin filteret for at se flere emner.", + "render.cpu_body_missing": "Et refleksionsmål mangler, er skjult, er flertydigt eller har et navn på mere end 128 bytes. Vælg det igen.", + "render.cpu_budget": "CPU-ressourceprofil", + "render.cpu_budget_bodies": "Grænse for emner", + "render.cpu_budget_compact": "Kompakt (ældre grænser)", + "render.cpu_budget_details": "Ressourcegrænser", + "render.cpu_budget_help": "Vælg eksplicit større grænser. Opløsning og samples reduceres aldrig automatisk.", + "render.cpu_budget_memory": "Grænse for jobbets hukommelse", + "render.cpu_budget_not_guarantee": "Det er adgangsgrænser, ikke en RAM-reservation eller en hastighedsgaranti. Geometri, billedbuffer og bevarede forhåndsvisninger deler hukommelsesbudgettet; rendering kan stadig annulleres.", + "render.cpu_budget_resize": "Kladden overskrider denne CPU-profil eller dens budget for kamera-samples. Acceptér mindre dimensioner eksplicit, eller vælg en større profil.", + "render.cpu_budget_studio": "Studio (store billeder)", + "render.cpu_budget_triangles": "Grænse for trekanter", + "render.cpu_budget_workstation": "Workstation (tunge scener)", + "render.cpu_captured_hdr": "HDR registreret til dette billede", + "render.cpu_check_capture_help": "Kontrollér og Start verificerer samme filhash eller bruger den indlejrede HDR. Hvert billede beholder sin registrerede kilde.", + "render.cpu_check_changed": "Indstillingerne eller modellen blev ændret efter denne kontrol. Kontrollér igen, før der renderes.", + "render.cpu_constant_help": "Konstant strålingstæthed er synlig for reflekterede eller transmitterede stråler. Den giver ikke direkte diffus belysning.", + "render.cpu_custom_directions": "Erstat forudindstilling med brugerdefinerede retningslys", + "render.cpu_direction": "Retning mod lyset (X, Y, Z)", + "render.cpu_directional": "Retningslys", + "render.cpu_directional_add": "Tilføj retningslys", + "render.cpu_environment": "CPU-omgivelser", + "render.cpu_environment_background": "Billedets baggrund er adskilt fra omgivelsesbelysningen.", + "render.cpu_environment_bounds": "CPU-intensiteten skal være 0–64, HDR-rotationen et gyldigt tal inden for ±1.000.000 radianer og HDR-samples 1, 4, 16 eller 64.", + "render.cpu_environment_constant": "Konstante omgivelser for sekundære stråler", + "render.cpu_environment_none": "Ingen CPU-omgivelser", + "render.cpu_environment_samples": "HDR-belysnings-samples", + "render.cpu_exposure_help": "CPU-eksponeringen skal ligge mellem −16 og 16 EV. En GPU-eksponering uden for dette område bevares, indtil du ændrer den.", + "render.cpu_fixed": "Enkeltbillede", + "render.cpu_hdr_help": "Radiance .hdr, 2:1-panorama, op til 2048 × 1024 og 16 MiB. CPU kræver eksplicitte sRGB/D65-primærfarver i filen; uspecificerede primærfarver og EXR afvises.", + "render.cpu_hdr_reflection_help": "Ru HDR-refleksioner kræver fuldt metalliske overflader på emner og flader. Kontrollen rapporterer kombinationer, der ikke understøttes.", + "render.cpu_key_rim": "Hovedlys og kantlys", + "render.cpu_last_check": "Seneste CPU-kontrol", + "render.cpu_light_help": "Op til otte retningslys. En tom brugerdefineret liste slår dem fra; valg af en forudindstilling gendanner dens lys. Farver er lineær RGB, og intensiteten er relativ, ikke i watt.", + "render.cpu_light_intensity": "Relativ intensitet (0–64)", + "render.cpu_light_minimum": "Mindsteafstand for dæmpning", + "render.cpu_light_position": "Position i verdenskoordinater (X, Y, Z)", + "render.cpu_light_reference": "Referenceafstand for intensitet", + "render.cpu_light_remove": "Fjern lys", + "render.cpu_lighting": "Forudindstilling for belysning", + "render.cpu_lights": "CPU-lys", + "render.cpu_linear_color": "Lineær farve (R, G, B)", + "render.cpu_neutral": "Neutral", + "render.cpu_opaque_required": "CPU ray tracing kræver en uigennemsigtig baggrund. Fjern markeringen ved Gennemsigtig baggrund for at fortsætte.", + "render.cpu_options_pending": "Dette CPU-panel kan endnu ikke redigere emission, overfladeeffekter, glas eller anisotropi. Fjern disse API-indstillinger, før du bruger det.", + "render.cpu_point": "Punktlys", + "render.cpu_point_add": "Tilføj punktlys", + "render.cpu_point_help": "Op til otte punktlys, lagt oven i den valgte retningsbelysning. Afstande er i mm; minimumsafstanden må ikke overstige referenceafstanden.", + "render.cpu_primary_samples": "Kant-samples pr. pixel", + "render.cpu_progressive": "CPU progressiv", + "render.cpu_progressive_help": "Akkumulér den eksisterende CPU-integrator i gennemløb med ét primært sample. Valgte refleksioner kræver ét sample; arealys, dielektrika og anisotropi kræver Enkeltbillede.", + "render.cpu_progressive_limits": "Højst 1.048.576 pixels og 16.777.216 pixel × sample-evalueringer. Ændring af samples ændrer aldrig billedets størrelse automatisk.", + "render.cpu_progressive_seed": "CPU-sampling-seed", + "render.cpu_progressive_spp": "samples pr. pixel", + "render.cpu_reflection_add": "Tilføj ru refleksion", + "render.cpu_reflection_depth": "Refleksionsdybde (1–8)", + "render.cpu_reflection_empty": "Ingen emner valgt: scenerefleksioner er slået fra.", + "render.cpu_reflection_help": "Vælg emner, og sæt Fra, Spejl eller Ru. Ru bruger den tildelte overfladeruhed. Flere samples og bounces øger tiden; det er begrænset spekulær lystransport, ikke global belysning.", + "render.cpu_reflection_limit": "Op til 64 reflekterede emner understøttes.", + "render.cpu_reflection_mirror": "Spejl", + "render.cpu_reflection_off": "Fra", + "render.cpu_reflection_rough": "Ru", + "render.cpu_reflection_samples": "Refleksions-samples (1–64)", + "render.cpu_reflections": "CPU-refleksioner", + "render.cpu_runtime_help": "Numeriske indstillinger for lys og omgivelser gemmes sammen med opsætningen. Emnerefleksioner og HDR-filer forbliver midlertidige. Eksisterende værdier for arealys og spotkegler bevares.", + "render.cpu_sampling_mode": "CPU-samplingtilstand", + "render.cpu_shadows": "Kast skygger", + "render.cpu_summary": "CPU ray tracing · refleksioner · HDR · retningslys og punktlys", + "render.cpu_warm_cool": "Varm og kold", + "render.diag_bodies": "Synlige emner", + "render.diag_job_details": "Registrerede jobdetaljer", + "render.diag_last_check": "Seneste forhåndskontrol", + "render.diag_memory": "Logisk estimat for jobadgang", + "render.diag_not_implemented": "Eksplicitte funktionsgrænser", + "render.diag_preflight_details": "Detaljer fra forhåndskontrol", + "render.diag_request": "Den præcise aktuelle anmodning", + "render.diag_triangles": "Trekanter", + "render.discard_continue": "Kassér kladde og fortsæt", + "render.draft_confirm_help": "Den aktuelle renderingskladde har ændringer, der ikke er anvendt. Gem dem, før du skifter, kassér dem eksplicit, eller fortsæt med at redigere.", + "render.draft_confirm_title": "Bevar redigerede renderingsindstillinger", + "render.effects_gpu_only": "Disse effekter kræver GPU path tracing. Ændring af siden skifter aldrig renderingsmotor automatisk.", + "render.effects_help": "Kombinér ordnede farve-looks og linseeffekter i billedplanet. Rendering og ny farvegradering af rå master bruger de samme gemte indstillinger. Rå EXR forbliver uændret. Det er originale kunstneriske værktøjer, ikke kalibrerede emuleringer af bestemte linser eller mærkefilm.", + "render.effects_reset_lens": "Nulstil linseeffekter", + "render.effects_seed": "Mønster-seed", + "render.emitted_axis": "Emissionsakse", + "render.env_advanced": "Avanceret", + "render.env_backdrop": "Kamerabaggrund", + "render.env_backdrop_pending": "Synlighed af omgivelserne og baggrundsslør understøttes endnu ikke af renderingsmotoren.", + "render.env_blur": "Slør", + "render.env_change": "Skift", + "render.env_choose_source": "Vælg omgivelser under Studioer og omgivelser, før belysningen redigeres.", + "render.env_clear": "Ryd", + "render.env_colour": "Farve", + "render.env_environments": "Omgivelser", + "render.env_ground": "Grundplan", + "render.env_ground_pending": "Den fysiske grundplan modtager skygger som en afgrænset diffus overflade. Kun skyggefangst og refleksioner på grundplanen understøttes endnu ikke.", + "render.env_intensity": "Intensitet", + "render.env_invalid_edit": "Ugyldig redigering af omgivelser.", + "render.env_physical_ground": "Fysisk grundplan", + "render.env_preview_help": "Illustrativ eksempelkugle; ikke en forhåndsvisning af de valgte omgivelser.", + "render.env_reflection": "Refleksion", + "render.env_ring_help": "Træk i ringen for at rotere belysningen. Hold Shift nede for at snappe til 15°.", + "render.env_rotate": "Rotér", + "render.env_set": "Angiv omgivelser for rendering", + "render.env_shadow_catcher": "Skyggefanger", + "render.env_show_environment": "Vis omgivelser", + "render.env_source": "Kilde", + "render.env_stage_details": "Ændringer af grundplanen kræver ray tracing og ét enkelt grundpanel. Brug Scene til at redigere andre kulissepaneler.", + "render.env_studios": "Studioer", + "render.environment.albedo": "Albedo", + "render.environment.atmosphere": "Atmosfære", + "render.environment.backdrop_note": "En kamerabaggrund ses kun af kameraet. Den giver aldrig lys, kaster ikke skygger og reflekterer ikke, og den afvises ved gennemsigtigt output.", + "render.environment.blur_pending": "Slør er ikke tilgængeligt: renderingsmotoren har ingen indstilling for baggrundsslør.", + "render.environment.builtin": "Indbygget HDR", + "render.environment.check": "Kontrollér fil", + "render.environment.checked": "HDR-filen er kontrolleret. Ved gemning indlejres disse bytes.", + "render.environment.choose": "Vælg HDR…", + "render.environment.constant": "Konstant", + "render.environment.cyclorama": "Cyklorama", + "render.environment.embedded": "Gemt i dette design", + "render.environment.end": "Slut", + "render.environment.extinction": "Ekstinktion", + "render.environment.file": "Fil", + "render.environment.fit": "Tilpas og gem grundplan", + "render.environment.floor_wall": "Gulv og væg", + "render.environment.gap": "Frigangsafstand", + "render.environment.gradient": "Farveforløb", + "render.environment.gradient_gpu": "Kamerabaggrund med farveforløb kræver GPU path tracing.", + "render.environment.ground": "Grundplan og kulisse", + "render.environment.hdr": "HDR", + "render.environment.hdr_file": "HDR-fil", + "render.environment.horizon": "Horisont", + "render.environment.horizontal": "Vandret", + "render.environment.keep": "Behold", + "render.environment.lighting_samples": "Samples til belysning", + "render.environment.margin": "Udstrækningsmargen", + "render.environment.max": "Maks. grænser", + "render.environment.medium": "Deltagende medium", + "render.environment.min": "Min. grænser", + "render.environment.mode": "Tilstand", + "render.environment.needs_gpu": "Kræver GPU path tracing.", + "render.environment.none": "Ingen", + "render.environment.orientation": "Orientering og styrke", + "render.environment.phase": "Fase", + "render.environment.primaries": "Behandl uspecificerede primærfarver som lineær sRGB", + "render.environment.primaries_gpu": "Fortolkning af uspecificerede primærfarver kræver GPU path tracing.", + "render.environment.radial": "Radial", + "render.environment.radial_only": "Centrum og radius gælder for radial tilstand.", + "render.environment.reflectance": "Reflektans", + "render.environment.remove": "Fjern kulisse", + "render.environment.remove_confirm": "Fjern den gemte kulisse?", + "render.environment.remove_note": "Fjerner de {count} passive paneler fra denne optagelse. Kamerabaggrunden forbliver.", + "render.environment.replace": "Bekræft udskiftning af den eksisterende kulisse", + "render.environment.rotation_hdr": "Rotation kræver en HDR-kilde til CPU ray tracing.", + "render.environment.samples_cpu": "Samples til belysning styres af budgettet for GPU path tracing; denne indstilling kræver CPU ray tracing.", + "render.environment.saved_panels": "Gemte paneler {count}", + "render.environment.sky_ground": "Jord", + "render.environment.sky_note": "Originalt himmelfarveforløb til belysning; ikke en kalibreret atmosfære.", + "render.environment.source_raytrace": "Omgivelseskilder kræver CPU- eller GPU-ray tracing.", + "render.environment.stage_raytrace": "Fysiske kulisser kræver CPU- eller GPU-ray tracing.", + "render.environment.start": "Start", + "render.environment.vertical": "Lodret", + "render.environment.world": "Verden", + "render.environment.world_pending": "Verdensbaggrund er ikke tilgængelig: omgivelsernes synlighed for kameraet har endnu ingen gemt indstilling.", + "render.environment.zenith": "Zenit", + "render.environment_tiles_require_raytrace": "Omgivelser kræver CPU- eller GPU-ray tracing. Vælg det i outputeditoren.", + "render.error_area_samples": "area_samples skal være 1, 4, 16 eller 64", + "render.error_binding_allocation": "kunne ikke reservere materialebinding", + "render.error_body_bound": "produktforhåndsvisningen overstiger grænsen for registrerede emner", + "render.error_checkpoint_dimensions": "checkpointets dimensioner afviger fra den registrerede anmodning", + "render.error_decode_budget": "overløb i budgettet for billedafkodning", + "render.error_denoise_setting": "ugyldig indbygget indstilling for støjreduktion", + "render.error_display_dimensions": "ugyldige dimensioner for billedvisning", + "render.error_display_fit": "billedvisningen kan ikke tilpasses denne enhed", + "render.error_display_height": "overløb i visningshøjde", + "render.error_display_width": "overløb i visningsbredde", + "render.error_duplicate_face": "duplikeret udseende for produktflade", + "render.error_export_document": "Eksportdokumentet for rendering blev ændret, mens destinationen blev valgt", + "render.error_face_cap": "produktforhåndsvisningen overstiger grænsen for tilladte fladeudseender", + "render.error_finish_gesture": "afslut modelleringsbevægelsen før forhåndsvisning", + "render.error_finish_operation": "afslut den aktuelle modelleringshandling, før Rendering åbnes", + "render.error_fixed_preview": "fast studioforhåndsvisning kræver eksponering 0, omgivelsesrotation 0 og intensitet 1", + "render.error_geometry_size": "overløb i produktgeometriens størrelse", + "render.error_glass_recipe": "ukendt glasopskrift", + "render.error_gpu_preview": "GPU-produktforhåndsvisning er ikke tilgængelig på denne vært. Gemte opsætninger er stadig tilgængelige.", + "render.error_gpu_samples": "antallet af GPU-samples understøttes ikke", + "render.error_image_dimensions": "renderingsbilledets dimensioner svarer ikke til dets job", + "render.error_image_profile": "renderingsbilledet overstiger sin registrerede ressourceprofil", + "render.error_interactive_command": "interaktiv Render-kommando uden binding", + "render.error_job_action": "ikke en interaktiv handling for billedjob", + "render.error_job_identity": "ugyldig identitet for renderingsjob: {error}", + "render.error_library_reply": "ugyldigt svar fra renderingsbiblioteket", + "render.error_material_binding": "manglende materialebinding", + "render.error_no_completed_image": "renderingen har intet færdigt billede", + "render.error_no_geometry": "ingen produktgeometri", + "render.error_no_scene": "ingen produktscene", + "render.error_opacity": "ugyldig opacitet for produktudseende", + "render.error_pbr_opacity": "uigennemsigtig PBR kræver opacitet 1", + "render.error_physical_glass": "den valgte opskrift er ikke fysisk glas", + "render.error_preview_device": "produktforhåndsvisning kræver en installeret enhed med dybdebuffer", + "render.error_product_triangle": "ugyldig produkttrekant", + "render.error_provisional_identity": "ugyldig foreløbig renderingsidentitet eller ugyldigt antal samples", + "render.error_quality_bounds": "kvalitetsoverførslen overstiger de indbyggede grænser", + "render.error_quality_method": "kvalitetsoverførslen kræver den samme eksplicitte GPU-metode", + "render.error_quality_projection": "ugyldig indbygget kvalitetsoverførsel", + "render.error_regrade_identity": "ugyldig identitet for ny farvegradering: {error}", + "render.error_scene_bodies": "manglende emner i renderingsscenen", + "render.error_scene_body_limit": "renderingsscenen overstiger sin grænse for emner", + "render.error_scene_identity": "ugyldig identitet for renderingsscene", + "render.error_setup_panicked": "opsætningen af GPU path tracer stoppede uventet", + "render.error_setup_stopped": "opsætningstråden stoppede uden at returnere en vært", + "render.error_setup_worker": "kunne ikke starte opsætningstråd: {error}", + "render.error_source_preview": "kildeforhåndsvisningen overstiger sin bytegrænse", + "render.error_surface_normals": "PBR kræver overfladenormaler, der ikke er nul", + "render.error_surface_reply": "ugyldigt svar om designet overflade", + "render.error_triangle_bound": "produktforhåndsvisningen overstiger kildegrænsen på otte millioner trekanter", + "render.error_triangle_count": "overløb i antallet af produkttrekanter", + "render.error_upload_slot": "uploadplads til produktforhåndsvisning er ikke tilgængelig", + "render.error_vertex_allocation": "allokering af vertices til produktforhåndsvisning mislykkedes", + "render.error_vertex_envelope": "produktforhåndsvisningen overstiger sin grænse på {limit} MiB vertex-data; geometrien blev ikke forenklet", + "render.error_vertex_packing": "pakningen af produktforhåndsvisningen afviger fra de godkendte vertex-data", + "render.error_visible_solid": "Opret et synligt massivt emne i Design for at forhåndsvise det her.", + "render.exit_focus": "Afslut fokus", + "render.export_display": "Eksport: PNG til visning", + "render.export_image_label": "Eksportér billede", + "render.export_linear": "Eksport: rå lineær EXR", + "render.exr_pending": "GPU kan bevare rå lineær EXR. Komprimering, flerlagsbilleder og supplerende renderingspas er endnu ikke tilgængelige.", + "render.film_grain": "Fotografisk korn", "render.fit": "Tilpas til produkt", + "render.fixed_camera": "Kamera", + "render.fixed_world": "Verden", + "render.flare_ghosts": "Ghost-ringe pr. kilde", + "render.flare_halo": "Flare-halo", + "render.flare_streak": "Streak i anamorfisk stil", + "render.flare_strength": "Styrke af flare i højlys", + "render.flare_threshold": "Scenelineær tærskel for flare", + "render.fold_browser": "Fold modeltræet sammen", + "render.frame_aspect": "Sideforhold", + "render.frame_centre_mark": "Midtermarkering", + "render.frame_copy_limit": "Intet ledigt navn til en kopi af optagelsen", + "render.frame_copy_name": "{name} kopi {number}", + "render.frame_custom": "Brugerdefineret", + "render.frame_distance_unit": " × størrelse", + "render.frame_duplicate": "Duplikér", + "render.frame_exposure": "Eksponering", + "render.frame_fov": "Synsfelt", + "render.frame_guides": "Hjælpelinjer", + "render.frame_invalid_aspect": "Ugyldig forudindstilling for sideforhold", + "render.frame_lens": "Synsfelt {fov}° · ≈ {mm} mm", + "render.frame_name": "Navn", + "render.frame_output_size": "Outputstørrelse", + "render.frame_photo": "3:2 · Foto", + "render.frame_portrait": "4:5 · Portræt", + "render.frame_presets": "Forudindstillinger for billedudsnit", + "render.frame_presets_pending": "Kommer med optagelseseditoren", + "render.frame_projection": "Projektion", + "render.frame_render_shot": "Render denne optagelse", + "render.frame_rule_thirds": "Tredjedelsreglen", + "render.frame_safe_area": "Sikkert område", + "render.frame_shot_title": "Optagelse · {name}", + "render.frame_square": "1:1 · Kvadrat", + "render.frame_tall": "9:16 · Lodret", + "render.frame_thirds": "Tredjedele", + "render.frame_wide": "16:9 · Bredformat", + "render.gpu_depth": "Maksimal path-dybde", + "render.gpu_options_help": "Samples, dybde, seed og eksponering gemmes med denne opsætning. Kun den aktive billedmetode gemmes.", + "render.gpu_path_failed": "GPU path tracer er ikke tilgængelig", + "render.gpu_path_first_setup": "Den første opsætning på denne GPU kan tage flere minutter; SolidCraft kan stadig bruges imens. Senere starter genbruger de kompilerede shaders, hvor driveren beholder dem.", + "render.gpu_path_preparing": "GPU path tracer: kompilerer shaders…", + "render.gpu_seed": "Tilfældig seed", + "render.gpu_unavailable": "GPU path tracing er ikke klar på denne enhed.", + "render.ground_apply": "Tilpas og gem grundplan", + "render.ground_gap": "Eksplicit frigangsafstand", + "render.ground_linear_rgb": "Diffus reflektans · lineær RGB", + "render.ground_margin": "Margen for grundplanens udstrækning", + "render.hdr_details": "Detaljer om HDR-kilden", + "render.hdr_embedded": "HDR gemt i dette design", + "render.hdr_embedded_help": "Rendering bruger de bytes, der er inkluderet i designet; den oprindelige fil er ikke længere nødvendig.", + "render.hdr_file_captured": "HDR-filen er kontrolleret. Ved gemning indlejres disse bytes; hvis filen ændres, skal den kontrolleres igen eksplicit.", + "render.hdr_inspect": "Kontrollér HDR-fil", + "render.hdr_inspect_required": "Vælg og kontrollér en HDR-fil, før der gemmes eller renderes.", + "render.hdr_primaries_declared": "Kilden angiver sine primærfarver.", + "render.hdr_primaries_srgb": "Primærfarver: sRGB/D65", + "render.hdr_primaries_undeclared": "Kilden angiver ikke primærfarver; gennemgå renderingsmotorens farvekrav.", + "render.hdr_resource_missing": "Dette design mangler den gemte HDR-ressource.", + "render.heading_batch": "BATCH", + "render.heading_frame": "BILLEDUDSNIT", + "render.heading_lens": "LINSE", + "render.heading_results": "RESULTATER", + "render.heading_shots": "OPTAGELSER", + "render.hide_shots_label": "Skjul optagelsesstriben", + "render.hover_look": "{object} · {look} · klik for at vælge", + "render.image_advanced": "Avancerede GPU-indstillinger", "render.image_cancelled": "Rendering annulleret", "render.image_cancelling": "Annullerer", "render.image_completed": "Billedet er klar til eksport", "render.image_encoding": "Gemmer som PNG", "render.image_export": "Eksportér PNG", + "render.image_exposure": "Eksponering", "render.image_failed": "Rendering mislykkedes", "render.image_height": "Højde", "render.image_help": "CPU-forhåndsvisning · PNG · forenklet gengivelse af gennemsigtighed", + "render.image_host_missing": "Ingen billedvært er installeret.", + "render.image_method": "Billedmetode", "render.image_overwrite": "Erstat eksisterende fil", "render.image_preparing": "Klargør billede", + "render.image_progressive": "Progressiv rendering", "render.image_queued": "Venter på rendering", "render.image_reduce": "Prøv et mindre billede eller en enklere scene.", "render.image_running": "Renderer billede", + "render.image_samples": "Samples pr. pixel", + "render.image_scene_stale": "Afslut modelleringsbevægelsen, eller opdatér scenen, før et billede kontrolleres eller startes.", "render.image_stale": "Dette billede bruger scenen, som den var før efterfølgende ændringer.", "render.image_start": "Start rendering", "render.image_supported": "Renderingsanmodningen understøttes; kø og hukommelsespulje kontrolleres igen ved start.", @@ -1407,17 +3054,519 @@ "render.image_unknown": "Renderingsstatus utilgængelig", "render.image_use_largest": "Brug største størrelse med dette sideforhold:", "render.image_width": "Bredde", + "render.include_rig_cards": "Medtag passive plader og flag", + "render.inner_half_angle": "Indre halvvinkel", + "render.inspect_scene": "Opdatér oversigt over den registrerede scene", + "render.inspector": "Inspektør", + "render.inspector_advanced": "Avanceret", + "render.inspector_all_users": "Alle {count} brugere", + "render.inspector_applies_to": "Gælder for", + "render.inspector_both_users": "Begge brugere", + "render.inspector_chain": "Hvor dette udseende kommer fra", + "render.inspector_colour": "Farve", + "render.inspector_edit": "Redigér", + "render.inspector_finish": "Finish", + "render.inspector_from_material": "Fra materiale", + "render.inspector_gloss": "Blank", + "render.inspector_material": "Materiale", + "render.inspector_matte": "Mat", + "render.inspector_metal": "Metal", + "render.inspector_opacity": "Opacitet", + "render.inspector_opaque_help": "Felter for finish og optik bruger uigennemsigtig PBR (opacitet 1). Lavere opacitet bruger skalar skygning.", + "render.inspector_pick_target": "Vælg et mål af denne type for at se dets udseende.", + "render.inspector_remove": "Fjern tilsidesættelse", + "render.inspector_replace": "Erstat…", + "render.inspector_reset": "Nulstil", + "render.inspector_satin": "Satin", + "render.inspector_save_library": "Gem i bibliotek…", + "render.inspector_set_all": "Blandede udseender. Redigering angiver udseendet på alle valgte mål.", + "render.inspector_soon": "Snart", + "render.inspector_target_limit": "Vælg højst 10000 mål for at se udseender.", + "render.inspector_textures": "Teksturer", + "render.inspector_this_body": "Dette emne", + "render.inspector_this_component": "Denne komponent", + "render.inspector_this_face": "Denne flade", + "render.inspector_this_target": "Dette mål", + "render.inspector_used_by": "Bruges af {count}", + "render.keep_editing": "Fortsæt redigering", + "render.layer_down": "Flyt ned", + "render.layer_enabled": "Lag aktiveret", + "render.layer_off_suffix": " (fra)", + "render.layer_remove": "Fjern lag", + "render.layer_strength": "Lagstyrke", + "render.layer_up": "Flyt op", + "render.lens_effects_help": "Flare bruger op til fire adskilte lyse kilder i det faktiske lineære billede. Ghosts, halo, streaks, kromatiske forskydninger og radial forvrængning er kunstneriske tilnærmelser i billedplanet. Rumlige effekter kræver uigennemsigtigt output; samples uden for billedet forlænger billedets kant. Korn er deterministisk. Hverken fysik, EXR eller geometri ændres.", + "render.lens_effects_title": "Linseinspirerede og fotografiske", + "render.library_all": "Katalog", + "render.library_all_states": "Alle tilgængelighedsstatusser", + "render.library_appearance_available": "Tilgængeligt udseende", + "render.library_applicable": "Anvendelige ressourcer", + "render.library_applied": "Ressourceoverførsel anvendt. Kontrollér hele renderingsanmodningen, før den startes.", + "render.library_apply_appearance": "Anvend udseende", + "render.library_apply_hdr": "Gem med disse HDR-omgivelser", + "render.library_apply_hint": "Klik for at anvende · træk ind på modellen", + "render.library_apply_maps": "Brug designede GPU-teksturkort til overflader", + "render.library_apply_studio": "Gem designet studiooverførsel", + "render.library_apply_uniform": "Anvend ensartet uigennemsigtigt udseende", + "render.library_authored_help": "Originale designede ressourcer er illustrative, ikke målte tekniske data. Hver handling anvender kun sin angivne overførsel.", + "render.library_blocked": "Blokeret / kræver kalibrering", + "render.library_capabilities": "Funktionsspecifikationer", + "render.library_center": "Rigens centrum", + "render.library_clear_search": "Ryd", + "render.library_details": "Specifikation og herkomst", + "render.library_emitters_only_ack": "Brug kun lyskilder; udelad de dokumenterede passive plader", + "render.library_empty": "Ingen matchende ressourcer. Prøv en anden søgning eller et andet tilgængelighedsfilter.", + "render.library_environment_concepts": "Omgivelseskoncepter", + "render.library_extent": "Motivets udstrækning", + "render.library_favorite": "Tilføj favorit", + "render.library_favorites": "Favoritter", + "render.library_filters": "Katalog og tilgængelighed", + "render.library_grid": "Gitter", + "render.library_hdr": "Indbyggede HDR-omgivelser", + "render.library_hdr_help": "Indlejrer den originale HDR i den gemte opsætning. Det designede nulpunkt for længdegrad konverteres eksplicit; ingen ekstern fil er nødvendig efter gemning.", + "render.library_in_design": "I Design", + "render.library_inspect_only": "Vælg for at se nærmere; intet anvendes automatisk. Favoritter og seneste historik hører til denne åbne designsession.", + "render.library_ior": "IOR", + "render.library_light_concepts": "Belysningskoncepter", + "render.library_list": "Liste", + "render.library_maps_help": "Indbyggede teksturkort kan gemmes med fastlåste kilder og lokal mapping af forekomster. Midlertidige optiske tilsidesættelser forbliver en separat tilstand.", + "render.library_material_concepts": "Materialekoncepter", + "render.library_metallic": "Metallisk", + "render.library_native_scenes": "Indbyggede studioer", + "render.library_next": "Næste side", + "render.library_omitted": "Ikke inkluderet", + "render.library_opacity": "Opacitet", + "render.library_other": "Andre udseender", + "render.library_physical_profiles": "Fysiske referenceprofiler", + "render.library_previous": "Forrige side", + "render.library_quality_concepts": "Kvalitetsspecifikationer", + "render.library_recent": "Seneste", + "render.library_replace_environment": "Erstat de eksisterende omgivelser eksplicit", + "render.library_replace_studio": "Erstat gemt belysning, omgivelser og kulisse", + "render.library_results": "Matchende ressourcer", + "render.library_rig_help": "Tilpas én gang ved et eksplicit centrum og en fysisk udstrækning. Komplette lysrig omfatter passive plader; kalibreringsblokeringer medfører stadig afvisning. Konservativ frigang mellem lyskilder og plader kontrolleres før gemning.", + "render.library_rigs": "Designede lysrig", + "render.library_roughness": "Ruhed", + "render.library_save_maps": "Gem teksturkort i denne opsætning", + "render.library_scene_bounds": "Brug registrerede scenegrænser", + "render.library_scenes": "Scenespecifikationer", + "render.library_search": "Søg i bibliotek", + "render.library_select_hint": "Vælg en ressource i biblioteket for at se dens understøttede handlinger og begrænsninger.", + "render.library_selene": "Uigennemsigtige SELENE-udseender", + "render.library_selene_shots": "SELENE-optagelsesspecifikationer", + "render.library_short_blocked": "Ikke tilgængelig", + "render.library_short_native": "Indbygget sammensætning", + "render.library_short_projection": "Understøttet overførsel", + "render.library_short_reference": "Kun reference", + "render.library_short_specification": "Kun specifikation", + "render.library_source_preview": "Indlæs forhåndsvisning af kildekort", + "render.library_source_preview_help": "Designet kildekort til basisfarve. Dette er ikke en renderet eller målt forhåndsvisning af materialet.", + "render.library_specification_only": "Kun specifikation: ikke en komplet, udførbar forudindstilling. Nødvendige effekter, ressourcer og motivroller mangler stadig eksplicit implementering og binding.", + "render.library_specs": "Kun specifikationer", + "render.library_status": "Tilgængelighed", + "render.library_surfaces": "Designede PBR-overflader", + "render.library_target": "Målemne", + "render.library_title": "Bibliotek over renderingsressourcer", + "render.library_unfavorite": "Fjern favorit", + "render.library_uniform_ack": "Brug den ensartede tilnærmelse uden rumlige eller avancerede effekter", + "render.library_usable": "Udførbare overførsler", + "render.library_users": "Bruges af", + "render.light_aim": "Sigt mod", + "render.light_anchor_pending": "Ændring af lysets koordinatsystem understøttes endnu ikke.", + "render.light_azimuth": "Azimut", + "render.light_backend_limit": "Vælg CPU ray tracing eller et eksplicit GPU-studio for at redigere lys. Ældre GPU-studielys forbliver skrivebeskyttede.", + "render.light_behaviour": "ADFÆRD", + "render.light_default_fill": "Fyldlys", + "render.light_default_key": "Hovedlys", + "render.light_default_number": "Lys {number}", + "render.light_default_rim": "Kantlys", + "render.light_delete": "Slet", + "render.light_distance": "Afstand", + "render.light_duplicate": "Duplikér", + "render.light_elevation": "Højdevinkel", + "render.light_gpu_punctual": "Punkt- og spotlys er tilgængelige med CPU ray tracing.", + "render.light_hard_shadow": "Dette lys har hårde skygger; lyskildens blødhed er ikke tilgængelig.", + "render.light_intensity": "Intensitet", + "render.light_missing": "Dette lys findes ikke længere. Vælg et lys i modeltræet.", + "render.light_place_highlight": "Placér efter højlys", + "render.light_place_pending": "Placering efter højlys kræver valg af lys i visningsområdet og understøttes endnu ikke.", + "render.light_position": "POSITION", + "render.light_preview_help": "Live-visningen er uden skygger; arealys bruger en tilnærmelse med centersample. Rendering bruger den fulde lysmodel.", + "render.light_product_centre": "Produktets centrum", + "render.light_size": "Størrelse", + "render.light_softness": "Blødhed", + "render.light_temperature": "Farvetemperatur", + "render.light_temperature_help": "Omtrentlig farvetone for et sort legeme; gemmes som lineær RGB.", + "render.light_type": "Type", + "render.light_type_area": "Arealys", + "render.light_type_point": "Punktlys", + "render.light_type_spot": "Spotlys", + "render.light_type_sun": "Sol", + "render.light_view_only": "Solo og mute påvirker denne visning og dens renderinger; de gemmes aldrig i designet.", + "render.light_world_origin": "Verdens origo", + "render.lighting_aim_point": "Sigtepunkt", + "render.lighting_apply": "Anvend forudindstilling", + "render.lighting_area_samples": "Samples for arealys", + "render.lighting_budget": "Budget", + "render.lighting_budget_help": "Antallene er skrivebeskyttede. Tilføj, duplikér eller slet lys for at ændre dem; metoden sætter grænserne.", + "render.lighting_colour": "Farve", + "render.lighting_consent": "Erstat retningslysene med denne forudindstilling", + "render.lighting_custom": "Brugerdefinerede lys", + "render.lighting_custom_help": "Når du vælger Brugerdefineret, bliver forudindstillingen til redigerbare lys, ét i hver række i modeltræet.", + "render.lighting_direction": "Retning X Y Z", + "render.lighting_direction_help": "Eller skriv en retning mod lyset (X Y Z).", + "render.lighting_distance_unit": " × størrelse", + "render.lighting_edge_u": "Sidevektor U", + "render.lighting_edge_v": "Sidevektor V", + "render.lighting_falloff": "Aftagning", + "render.lighting_falloff_help": "Intensiteten angives ved referenceafstanden.", + "render.lighting_height": "Højde V", + "render.lighting_minimum": "Minimum", + "render.lighting_mute": "Mute dette lys", + "render.lighting_point": "Punktlys", + "render.lighting_preset": "Studioforudindstilling", + "render.lighting_preset_cpu": "Studioforudindstillinger med retningslys kræver CPU ray tracing. GPU-belysning bruger eksplicitte sol- og arealys.", + "render.lighting_preset_row": "Forudindstilling", + "render.lighting_radiance": "Strålingstæthed", + "render.lighting_reference": "Reference", + "render.lighting_review_help": "Erstatter listen over retningslys. Bevarer punkt- og arealys, omgivelser, skygger, kamera og alle andre optagelsesindstillinger.", + "render.lighting_review_title": "Gennemgå forudindstilling for belysning", + "render.lighting_samples_cpu": "Samples for arealys gælder for CPU ray tracing.", + "render.lighting_samples_need_area": "Tilføj et CPU-arealys for at angive samples for arealys.", + "render.lighting_samples_reason": "Samples for arealys skal være 1, 4, 16 eller 64.", + "render.lighting_shadow_cpu": "Skyggeafbryderen kræver CPU ray tracing. GPU path tracing kaster altid skygger.", + "render.lighting_shadows": "Kast skygger", + "render.lighting_shadows_section": "Skygger og sampling", + "render.lighting_shape": "Form", + "render.lighting_solo": "Solo dette lys", + "render.lighting_source": "Kilde", + "render.lighting_source_section": "Lyskilde", + "render.lighting_spot_preserved": "Dette punktlys bevarer sin gemte spotkegle, indtil typen ændres.", + "render.lighting_sun_distance": "Solens retning er uafhængig af afstand og sigtepunkt.", + "render.lighting_unsupported": "understøttes ikke", + "render.lighting_used": "{used} af {limit}", + "render.lighting_width": "Bredde U", + "render.lighting_world_position": "Verden X Y Z", + "render.lights_fixed_to": "Lys fastgjort til", + "render.linear_help": "Bevarer en 32-bit float RGBA-master før støjreduktion, eksponering, tone mapping, filtre og kamerabaggrund. Lineær sRGB/D65; præmultipliceret med dækning. Ekstra hukommelse godkendes eksplicit. Ingen komprimering eller ekstra pass.", + "render.linear_retain": "Bevar rå lineær EXR", + "render.linear_unavailable": "Det valgte færdige billede har ingen bevaret EXR. Slå bevaring til før rendering; en ældre PNG kan ikke genskabe rå strålingstæthed.", + "render.look_add": "Tilføj farvelook", + "render.look_applied": "{name} anvendt", + "render.look_bleach": "Bleach bypass-inspireret", + "render.look_cool": "Kølig", + "render.look_cyanotype": "Cyanotypi-inspireret", + "render.look_faded": "Falmet tryk", + "render.look_material": "Materiale", + "render.look_mono": "Monokrom", + "render.look_pasted": "Look indsat", + "render.look_sepia": "Sepia", + "render.look_strength": "Styrke for look", + "render.look_teal_orange": "Blågrøn / orange", + "render.look_title": "Stak af kreative looks", + "render.look_warm": "Varm", + "render.mapping_scale": "Multiplikator for fysisk gentagelse", + "render.material_absorption": "Absorption R · G · B (pr. mm)", + "render.material_add": "Tilføj eller redigér dette emne", + "render.material_assignments": "Emnetildelinger", + "render.material_binding_enable": "Medtag denne tilsidesættelse for emnet", + "render.material_box": "Akseparallel boks", + "render.material_browse": "Vælg billede…", + "render.material_certification": "Lukket glas bruger geometrisk afstand. Topologi, orientering, overlap og optiske grænser kontrolleres under GPU-forberedelsen; Kontrollér godkender kun anmodningen.", + "render.material_choose_body": "Vælg et emne i scenen", + "render.material_closed": "Lukket massivt mesh", + "render.material_coat": "Klarlak oven på basismaterialet", + "render.material_coat_enable": "Aktivér klarlak", + "render.material_coat_help": "Illustrativ dielektrisk belægning oven på det eksisterende uigennemsigtige udseende. Vægt nul efterlader basen uændret.", + "render.material_color_map": "Basisfarvebillede (sRGB)", + "render.material_color_replace": "Basiskort erstatter emnets farve", + "render.material_custom": "Brugerdefineret illustrativ optik", + "render.material_enable": "Brug disse GPU-tilsidesættelser af materiale", + "render.material_filter": "Filtrér emner i scenen…", + "render.material_filter_help": "Op til 128 matchende emner vises. Præcisér filteret for store scener.", + "render.material_glass": "Glas og optisk absorption", + "render.material_glass_enable": "Brug fysisk glas på dette emne", + "render.material_glass_exclusive": "Glas kan ikke dele emne med klarlak eller runtime-teksturkort i denne renderingsmotor.", + "render.material_glass_help": "Originale illustrative opskrifter. Farveprøver viser transmittans, ikke en renderet forhåndsvisning. Absorption er −ln(lineær transmittans) / referenceafstand; alfa er uændret.", + "render.material_gpu_required": "Disse aktive tilsidesættelser af materiale kræver GPU path tracing. Vælg GPU, eller slå tilsidesættelserne fra, før du kontrollerer eller starter.", + "render.material_ior": "Brydningsindeks (IOR)", + "render.material_limits": "Højst 128 tilsidesættelser af emner, 32 adskilte glasemner, 64 belægninger og 128 teksturbindinger. Identiske kort deler lagerplads; de faktiske grænser for enheden og samlet hukommelse gælder stadig.", + "render.material_map_invalid": "Stier til kort skal være begrænsede lokale stier; normalstyrken skal være et tal mellem 0 og 1.", + "render.material_map_required": "Vælg et farvebillede eller et normalbillede, før du bruger kort.", + "render.material_maps": "Plane farve- og normalkort", + "render.material_maps_enable": "Aktivér kort for dette uigennemsigtige emne", + "render.material_maps_help": "PNG/JPEG op til 1024×1024; 16 MiB kodet i alt. U og V er ortogonale gentagelsesvektorer i mm i verdenskoordinater (højst 128 gentagelser). Farve er sRGB; normaldata bruger OpenGL +Y. Filer registreres ved Kontrollér/Start.", + "render.material_metallic_map": "Metalkort (lineært)", + "render.material_normal_map": "Normalbillede (OpenGL, +Y)", + "render.material_normal_strength": "Normalstyrke (0–1)", + "render.material_origin": "Kortets origo X · Y · Z (mm)", + "render.material_refresh": "Opdatér emner i scenen", + "render.material_refresh_needed": "Scenen er ændret. Opdatér emnelisten, før du tilføjer et mål.", + "render.material_remove": "Fjern denne tildeling", + "render.material_repeat_u": "Én U-gentagelse X · Y · Z (mm)", + "render.material_repeat_v": "Én V-gentagelse X · Y · Z (mm)", + "render.material_revalidate": "Valider dette emne igen", + "render.material_revalidate_needed": "Denne tildeling hører til en tidligere scenerevision. Valider dens præcise emneidentitet igen før rendering.", + "render.material_roughness": "Klarlakkens ruhed (0,045–1)", + "render.material_roughness_map": "Ruhedskort (lineært)", + "render.material_shadow": "Lad lige skyggestråler gå igennem", + "render.material_target_missing": "Emnets ordenstal og navn stemmer ikke længere overens. Fjern denne tildeling, og vælg eksplicit det tilsigtede emne igen.", + "render.material_thickness": "Tykkelse af tynd plade (mm)", + "render.material_thin": "Tynd plade", + "render.material_title": "GPU-billedmaterialer", + "render.material_transient": "Midlertidige optiske tilsidesættelser for denne dokumentfane. De gemmes ikke i designet, renderingsopsætningen eller materialebiblioteket.", + "render.material_v_up": "Tekstur-V peger opad i billedet", + "render.material_weight": "Klarlakkens vægt (0–1)", + "render.method_cpu": "CPU ray tracing", + "render.method_gpu": "GPU path tracing", + "render.method_limit_raster": "Raster bruger den faste uigennemsigtige studieforhåndsvisning. Vælg en eksplicit ray tracing-metode for at få understøttede optiske kontroller.", + "render.method_raster": "CPU-raster", "render.navigation_help": "Kameraet bevæges som i Design (Indstillinger › Navigation). Gem opsætning gemmer det aktuelle kamera.", + "render.nested_enable": "Certificerede indlejrede dielektrika", + "render.nested_help": "Op til 16 omsluttende lag; hvert overordnede lag skal være konvekst, og hvert underordnede skal ligge strengt inde i det. Skæringer, berørende overflader, tynde plader og transmission med lige skygger afvises. Tilstanden med kameraet indeni følger det certificerede hierarki. Opretter ikke en væskeoverflade og fletter ikke berørende CAD-grænser sammen.", "render.opaque_image_summary": "PNG-forhåndsvisning · uigennemsigtig PBR · blandet gennemsigtighed", "render.opaque_preview_help": "Uigennemsigtig PBR og enkle farver; blandet gennemsigtighed. Lysbrydning, HDRI og endelig rendering er endnu ikke tilgængelige.", + "render.optics_remove": "Fjern gemt optik", + "render.optics_replace": "Erstat dette måls gemte optik eksplicit", + "render.optics_save": "Gem denne optik i opsætningen", + "render.optics_saved": "Gemte optiske mål", + "render.optics_saved_help": "Den præcise identitet af definition, feature og forekomst bevares ved genåbning offline. Manglende/erstattede/skjulte mål afvises; fysiske materialer er uændrede. Gem eller kassér numeriske ændringer, før du fjerner et gemt mål.", + "render.outer_half_angle": "Ydre halvvinkel", + "render.output_advanced": "Avanceret", + "render.output_backend_ready": "Klar", + "render.output_check": "Kontrollér", + "render.output_check_failed": "Kontrollér · fejl", + "render.output_check_help": "Kør Kontrollér for at gennemgå denne anmodning uden at starte en rendering.", + "render.output_check_summary": "Kontrollér · Noter: {count}", + "render.output_copy": "Kopiér", + "render.output_copy_report": "Kopiér rapport", + "render.output_destination": "Destination", + "render.output_destination_help": "Vælg destinationsfilen, når du eksporterer det færdige billede.", + "render.output_dimensions": "Størrelse", + "render.output_effects": "Effekter", + "render.output_export": "Eksportér PNG…", + "render.output_exr_unavailable": "Opsætning af EXR-output er ikke tilgængelig her. Lineær EXR-eksport kræver et færdigt GPU-billede med en bevaret lineær master.", + "render.output_fit": "Tilpas", + "render.output_format": "Format", + "render.output_format_status": "PNG er det præcise færdige visningsbillede. Valgfri GPU-EXR bevarer rå scenelineær FLOAT32-strålingstæthed før visningsfiltre. Eksport bruger aldrig forhåndsvisningens cache eller et andet job i stedet.", + "render.output_grading": "Farvegradering", + "render.output_image": "Billede", + "render.output_largest": "maks. {width} × {height}", + "render.output_lock_ratio": "Lås sideforhold", + "render.output_over_budget": "Det ønskede billede overskrider den valgte ressourcegrænse. Vælg eksplicit en kompatibel størrelse eller profil; der sker ingen automatisk nedgradering.", + "render.output_presets_help": "Format, kvalitet og kontrollisten findes i output-editoren.", + "render.output_quality": "Kvalitet", + "render.output_quality_waiting": "venter på kvalitetskontrakten", + "render.output_ratio_refused": "Den sammenkædede dimension overskrider denne metodes størrelsesgrænse. Den forrige størrelse bevares; lås sideforholdet op, eller vælg en mindre værdi.", + "render.output_ready": "Klar til rendering", + "render.output_run_check": "Kør kontrol", + "render.output_size_limit": "{method}: op til {dimension} px pr. side og {pixels} pixels. Største passende størrelse: {width} × {height}.", + "render.output_size_method_profile": "For at rendere {width} × {height} skal du vælge {method} med CPU-ressourceprofilen {profile} eller en mindre størrelse.", + "render.output_size_ok": "Størrelse OK · {width} × {height} px", + "render.output_size_profile": "For at rendere {width} × {height} skal du vælge CPU-ressourceprofilen {profile} eller en mindre størrelse.", + "render.output_swap_orientation": "Byt om på bredde og højde", + "render.output_tools_inspector": "Redigér størrelse og format i output-inspektøren.", + "render.output_view_image": "Vis billede", + "render.page_aging": "Ældning og forurening", + "render.page_all": "Alle kontroller", + "render.page_appearance": "Udseende", + "render.page_background": "Baggrunde", + "render.page_camera": "Kamera", + "render.page_diagnostics": "Diagnostik", + "render.page_effects": "Linse- og efterbehandlingseffekter", + "render.page_environment": "Omgivelser", + "render.page_lighting": "Belysning", + "render.page_output": "Output", + "render.page_scene": "Scene", + "render.paint_label": "Mal", + "render.painting_with": "Maler med {name}", + "render.passive_stage": "Grundplan og passiv kulisse", + "render.passive_stage_help": "Afgrænsede passive paneler hører kun til renderede billeder. De tilføjer hverken CAD-emner eller masse. Placeringen er låst efter anvendelse; paneler, der skærer produktets grænser, afvises. CPU leverer ikke diffus bounce-belysning.", "render.perspective": "Perspektivkamera", + "render.physical_acknowledge": "Jeg forstår, at denne delvise reference kræver gennemgang af kvalitetsklasse, tilstand og kilde", + "render.physical_associations": "Fysiske kandidater og roller", + "render.physical_background_help": "Virkeligt passivt gulv og væg, adskilt fra kamerabaggrunden. Cyklorama bruger 24 polygonale strimler; det er ikke en uendelig eller analytisk glat overflade. Erstatter kun den gemte kulisse med dit samtykke.", + "render.physical_copy_plan": "Kopiér plan med kilder og udeladelser", + "render.physical_cyclorama": "Tilpas polygonalt cyklorama", + "render.physical_floor_wall": "Tilpas fysisk gulv og væg", + "render.physical_material_name": "Foreslået navn på referencemateriale", + "render.physical_omissions": "Egenskaber, der ikke kan repræsenteres i det indbyggede kort", + "render.physical_plan_only": "Skrivebeskyttet plan klargjort. Der blev ikke oprettet eller tildelt noget materiale. Behold den udvidede profil og udeladelserne, når du gennemgår det indbyggede kort.", + "render.physical_prepare_plan": "Klargør oprettelsesplan (anvender ikke)", + "render.physical_separate": "Udseende er ikke materialeidentifikation. Det er referencer med kildeangivelse, ikke certificerede effektive egenskaber. Eksisterende masse, fysiske materialer og optik er uændrede.", + "render.physical_unknown": "Der er ikke fastlagt nogen numerisk kandidat. Kvalitetsklasse, sammensætning eller konstruktion skal angives; ukendt er ikke nul.", + "render.pick_body": "Emne", + "render.pick_component": "Komponent", + "render.pick_face": "Flade", + "render.pick_help": "Vælg Emne, Flade eller Komponent. Klik på et tomt område for at rydde; Shift eller Ctrl tilføjer eller skifter. Fremhævninger vises kun i den levende produktvisning.", + "render.pick_label": "Vælg", + "render.pick_up_label": "Hent", + "render.pick_up_prompt": "Klik på et objekt for at hente dets udseende", + "render.pick_waiting": "Valg i produktet understøttes endnu ikke.", + "render.post_contrast": "Kontrast", + "render.post_gain_b": "Blå forstærkning", + "render.post_gain_g": "Grøn forstærkning", + "render.post_gain_r": "Rød forstærkning", + "render.post_help": "Kun kreativ præsentation. RGB-forstærkninger kommer før tone mapping; kontrast, farvemætning og vignettering følger i visningslineært lys. Start rendering opretter nye samples til lystransport. Gradér igen bruger den valgte bevarede rå master uden støjreduktion eller nye stråler.", + "render.post_reset": "Nulstil præsentationsfiltre", + "render.post_saturation": "Farvemætning", + "render.post_title": "Præsentationsfiltre", + "render.post_vignette": "Vignettering", "render.preview": "Integreret forhåndsvisning", "render.preview_help": "Rasterbaseret skygning og blandet gennemsigtighed. Lysbrydning, HDRI og endelig rendering er endnu ikke tilgængelige.", + "render.preview_image_settings_help": "Live-forhåndsvisningen bruger fast studiebelysning. Eksponering og billedbelysning gælder for billedjobbet, når du kontrollerer eller starter.", + "render.preview_lighting_help": "Live-forhåndsvisningen viser kun direkte lys og ingen skygger.", + "render.preview_retry": "Prøv live-forhåndsvisning igen", + "render.preview_unavailable_help": "Live-forhåndsvisningen er ikke tilgængelig. Gemte opsætninger og kontroller til billedjobbet kan stadig bruges. Ændr scenen, eller prøv eksplicit igen; en afvist scene genopbygges ikke ved hvert billede.", + "render.preview_upload": "Vertexdata til live-forhåndsvisning", + "render.preview_upload_help": "Præcise vertexbytes til forhåndsvisningen, ikke samlet GPU- eller proceshukommelse. Geometrien forenkles ikke. Billedjob har deres egen godkendelse og belysning.", + "render.progressive_image_summary": "PNG-forhåndsvisning · PBR og glas · progressive samples", + "render.property_conditions": "Betingelser: {value}", + "render.property_fallback": "egenskab", + "render.property_qualifier": "Kvalifikator: {value}", + "render.property_source": "Kilde: {id} - {locator}", + "render.property_uncertainty": "Usikkerhed: {value}", + "render.property_unknown": "ukendt", + "render.quality_ack": "Bekræft overførslen med fast budget og udeladelserne", + "render.quality_apply": "Brug dette faste sampling-budget", + "render.quality_balanced": "Afbalanceret", + "render.quality_custom": "Brugerdefineret", + "render.quality_draft": "Kladde", + "render.quality_high": "Høj", + "render.quality_projection_help": "Q-forudindstillinger omfatter fremtidige krav. Denne handling overfører kun et understøttet PNG-budget med faste samples og udelader eksplicit adaptivt stop, rå lineært output og uafhængige transmissionsgrænser.", + "render.quality_review": "Gennemgå sampling-budget", + "render.queue_pending": "Der er ingen automatisk produktionskø eller animationsrenderingsmotor i denne brugerflade. Færdige stillbilleder kan stadig eksporteres enkeltvis.", + "render.radial_assign": "Tildel udseende", + "render.radial_compare": "Sammenlign", + "render.radial_distortion": "Radial forvrængning", + "render.radial_fit": "Tilpas til produkt", + "render.radial_save": "Gem optagelse", + "render.recent_looks": "Seneste looks", + "render.regrade_action": "Gradér rå master igen (uden støjreduktion)", + "render.regrade_help": "Opretter en separat PNG fra den valgte færdige rå master med disse præsentationskontroller. Sporer ikke stråler, ændrer ikke den registrerede størrelse, det registrerede kamera eller lys og overskriver ikke EXR-filen. Støjreduktion anvendes ikke igen: Rå masters bevarer ikke dens hjælpedata. Den afledte fil kan stadig eksporteres via de samme jobkontroller.", + "render.regrade_label": "Gradér igen", "render.reload_settings": "Genindlæs gemte indstillinger", + "render.remove_override": "Fjern tilsidesættelse", + "render.replace_all": "Erstat alle", + "render.replace_ground": "Bekræft erstatning af eksisterende kulisse", + "render.replace_label": "Erstat", + "render.replace_saved_surface": "Erstat en eksisterende gemt binding for dette mål", + "render.replace_with": "Erstat med", "render.restore_camera": "Gendan gemt kamera", + "render.result_actual": "100%", + "render.result_actual_help": "Ét billedpixel pr. visningspixel.", + "render.result_actual_size": "100%", + "render.result_capture": "Registreret revision", + "render.result_current": "Den registrerede modelrevision er aktuel.", + "render.result_empty": "Intet færdigt billede endnu. Kontrollér indstillingerne, og start derefter en rendering.", + "render.result_fit": "Tilpas billede", + "render.result_job": "Job", + "render.result_navigation": "Panorering og zoom følger indstillingerne for Navigation. Mellemrumstasten + træk panorerer.", + "render.result_open": "Åbn det færdige billede i hovedvisningen.", + "render.result_preview": "Live-forhåndsvisning", + "render.result_provisional": "Foreløbigt CPU-billede", + "render.result_provisional_help": "Dette kontrolpunkt kan ikke eksporteres. Eksport bruger det seneste færdige resultat; annullering vender tilbage til dette resultat.", + "render.result_reduced_display": "Visningens forhåndsvisning er reduceret til grænsen for visningsområdets enhed/cache. Den bevarede PNG og eksporten bevarer fuld opløsning; indbygget 100%-inspektion er ikke tilgængelig for denne reducerede visning.", + "render.result_retained": "Viser det seneste færdige billede; en nyere rendering har ikke erstattet det.", + "render.result_sequence": "Kontrolpunkt", + "render.result_title": "Renderingsresultat", + "render.results_choose": "Bevarede resultater", + "render.results_label": "Rendering {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [forældet]", + "render.results_unnamed": "Billede", "render.return_design": "Tilbage til Design", + "render.review_stale": "Denne gennemgang er forældet. Afklar den, eller kontrollér igen, før du anvender den.", + "render.ribbon_aging": "Ældning", + "render.ribbon_backgrounds": "Baggrunde", + "render.ribbon_check": "Kontrollér", + "render.ribbon_check_help": "Validér det præcise aktuelle udkast, som Rendering sender. Ingen reserveløsning i renderingsmotoren, ingen stille ændring af størrelse og ingen udskiftning af ressourcer.", + "render.ribbon_edit_lights": "Redigér lys", + "render.ribbon_effects": "Effekter", + "render.ribbon_environment_help": "HDR-belysning, kamerabaggrunde og fysiske kulisseoverflader er adskilte indstillinger med eksplicit samtykke til udskiftning.", + "render.ribbon_finish_dialog": "Afslut først den aktuelle fil- eller bekræftelsesdialog.", + "render.ribbon_frame": "Billedudsnit", + "render.ribbon_hdr_library": "HDR-bibliotek", + "render.ribbon_job_active": "En rendering kører allerede. Annullér den udtrykkeligt, før du starter en ny.", + "render.ribbon_light_rigs": "Lysrigge", + "render.ribbon_lights_help": "Undersøg designede lysrigge, eller redigér understøttede lys uden at erstatte den aktuelle opsætning, før du udtrykkeligt anvender ændringen.", + "render.ribbon_materials": "Materialer", + "render.ribbon_materials_help": "Åbn den delte udseendeinspektør og det originale overfladebibliotek. Optiske ændringer ændrer aldrig tekniske egenskaber uden varsel.", + "render.ribbon_no_active_job": "Der er ingen aktiv rendering at annullere.", + "render.ribbon_no_result": "Gennemfør en rendering, før du eksporterer det præcise billede.", + "render.ribbon_no_saved_camera": "Gem en optagelse, før du gendanner dens kamera.", + "render.ribbon_saved_camera": "Gemt kamera", + "render.ribbon_shots": "Optagelser", + "render.ribbon_studios": "Studioer", + "render.ribbon_studios_help": "Gennemse implementerede studiokompositioner, og gennemgå deres udskiftninger, før de anvendes. Scener, der kun er koncepter, er fortsat markeret.", + "render.ribbon_surface_maps": "Teksturkort", + "render.sampling_title": "Adaptiv sampling og transmissionssampling", + "render.save_continue": "Gem og fortsæt", "render.save_setup": "Gem opsætning", + "render.save_shot": "Gem optagelse", + "render.saved_maps_runtime_conflict": "Gemte overfladebindinger kan ikke blandes med midlertidige optiske tilsidesættelser eller en HDR, der ikke er gemt. Gem HDR'en, eller fjern de midlertidige input udtrykkeligt.", + "render.saved_surface_remove": "Fjern gemt binding", + "render.saved_surfaces": "Gemte overfladebindinger", + "render.saved_surfaces_help": "Fastgjorte indbyggede teksturkort følger den valgte forekomst i lokale millimeter. Et erstattet eller manglende mål er en fejl og aldrig en automatisk omtildeling.", + "render.scene_all_shots": "Alle optagelser ({count})", + "render.scene_apply": "Anvend gennemgået studio", + "render.scene_batch_reason": "Alle optagelser kræver renderingskøen for gemte optagelser, som endnu ikke er tilgængelig.", + "render.scene_check_now": "Kontrollér nu", + "render.scene_check_passed": "Kontrol bestået · {notes} bemærkninger", + "render.scene_check_stale": "Kontrol forældet · kontrollér igen", + "render.scene_check_unchecked": "Ikke kontrolleret endnu · 0 bemærkninger", + "render.scene_consent": "Bekræft udskiftning af belysning, omgivelser, eksponering og kulisse", + "render.scene_light_summary": "{environment} · {lights} lys", + "render.scene_look_summary": "{looks} udseender · {overrides} tilsidesættelser", + "render.scene_open_check": "Åbn kontrol", + "render.scene_preserved_fields": "Kamera, sampling, dimensioner, optiske bindinger, CAD-geometri og fysiske materialer bevares.", + "render.scene_preserves_design": "Komponér belysning og en passiv kulisse til det synlige motiv. Geometri, fysiske materialer og kameraet forbliver adskilte.", + "render.scene_ready": "Klar til rendering", + "render.scene_reminder": "Scenen bevarer designet. Geometri, tekniske egenskaber og CAD ændres aldrig fra Rendering.", + "render.scene_reminders": "Påmindelser", + "render.scene_renderer_ready": "{renderer} er klar", + "render.scene_replaces": "Erstatter", + "render.scene_review": "Afklar og gennemgå", + "render.scene_review_help": "Gennemgå hele den indbyggede komposition, før den anvendes. Ubundne avancerede SCENE-specifikationer erstattes ikke.", + "render.scene_scope_details": "Kompositionens omfang", + "render.scene_stages": "Kulisser", + "render.search_appearances": "Søg i {count} udseender", + "render.setup_legacy_environment": "Denne ældre opsætning bruger ældre omgivelsesrotation eller -intensitet. Værdierne bevares; konvertér dem udtrykkeligt, før du gemmer et fuldt billedjob.", "render.setup_name": "Opsætningsnavn", + "render.setup_numeric_help": "Gem lagrer den aktive billedmetode og alle dens numeriske indstillinger. Genindlæsning eller valg af en anden opsætning erstatter dette udkast; gendan kameraet separat.", + "render.setup_offline_help": "Du kan redigere og gemme denne metode uden dens renderingsmotor. Kontrollér og Start kræver en tilgængelig vært.", + "render.setup_runtime_unsupported": "Dette fulde job kan endnu ikke gemmes: det indeholder teksturkort eller bindinger til scenens emner. Fjern disse midlertidige input, før du gemmer en portabel opsætning.", + "render.setup_save_missing": "Den gemte renderingskonfiguration kunne ikke findes, efter at kommandoen var afsluttet.", + "render.sharpening": "Skærpelse af detaljer", + "render.shell_tab_appearance": "RENDERINGSUDSEENDE", + "render.shell_tab_camera": "RENDERINGSKAMERA", + "render.shell_tab_lighting": "BELYSNING", + "render.shell_tab_scene": "RENDERINGSSCENE", + "render.shot_aperture": "Blænde", + "render.shot_distance": "Afstand", + "render.shot_dof": "Dybdeskarphed", + "render.shot_duplicate": "Duplikér gemt optagelse", + "render.shot_edit_output": "Redigér i Output", + "render.shot_exposure_reason": "Eksponering kræver CPU ray tracing eller GPU path tracing.", + "render.shot_exposure_section": "Eksponering", + "render.shot_focus_distance": "Fokusafstand", + "render.shot_fov_reason": "Synsfelt kræver perspektivprojektion.", + "render.shot_frame_subject": "Indram motivet", + "render.shot_invalid_camera": "Kameraværdier skal være afgrænsede og ligge inden for intervallet.", + "render.shot_lens": "Linse", + "render.shot_lens_enable_reason": "Aktivér dybdeskarphed for at redigere blænde og fokusafstand.", + "render.shot_lens_gpu_reason": "Dybdeskarphed kræver GPU path tracing.", + "render.shot_lens_perspective_reason": "Dybdeskarphed kræver perspektivprojektion.", + "render.shot_look_selection": "Se mod markering", + "render.shot_manager": "Gemte optagelser", + "render.shot_new_name": "Navn på ny optagelse", + "render.shot_remove": "Fjern gemt optagelse", + "render.shot_remove_help": "Fjerner kun denne gemte opsætning. Kildegeometri og færdige billeder bevares; handlingen kan fortrydes.", + "render.shot_remove_title": "Fjern gemt optagelse?", + "render.shot_rename": "Omdøb gemt optagelse", + "render.shot_saved_only": "Gem først det aktuelle udkast. Duplikering og omdøbning bevarer de præcise gemte indstillinger og ressourcehenvisninger.", + "render.shot_selection_reason": "Vælg et emne eller en flade at sigte mod.", + "render.shot_size": "Størrelse", + "render.shot_target": "Mål", "render.shots_camera_changed": "Kameraet er ændret, siden denne optagelse blev gemt", "render.shots_name_help": "Indtast et unikt navn til den aktuelle optagelse.", "render.shots_no_result": "Ingen rendering endnu", @@ -1425,9 +3574,229 @@ "render.shots_revert": "Gendan", "render.shots_save": "Gem optagelse", "render.shots_update": "Opdater optagelse", + "render.show_shots_label": "Vis optagelsesstrimlen", + "render.size_4k": "4K", + "render.size_4k_uhd": "4K UHD", + "render.size_custom": "Brugerdefineret…", + "render.size_full_hd": "Full HD", + "render.size_hd": "HD", + "render.size_needs_profile": "{size} · kræver {profile}", + "render.size_presets": "Forudindstillinger for størrelse", + "render.size_presets_pending": "Kommer med Output-editoren", + "render.size_preview": "Forhåndsvisning", + "render.size_square": "Kvadrat", + "render.sky_ground": "Jord · lineær RGB", + "render.sky_horizon": "Horisont · lineær RGB", + "render.sky_zenith": "Zenit · lineær RGB", + "render.soft_focus": "Blødt fokus", + "render.spot_cone": "Spotkegle", + "render.stage_frame": "Billedudsnit", + "render.stage_layout.appearance_note": "Klik for at anvende på markeringen.", + "render.stage_layout.studio_note": "Klik for at gennemgå, før det anvendes.", + "render.stage_light": "Lys", + "render.stage_look": "Udseende", + "render.stage_orthographic": "Ortografisk", + "render.stage_output": "Output", + "render.stage_panel_count": "Gemte paneler", + "render.stage_panels.acknowledge": "Jeg har forstået udskiftningen og begrænsningerne", + "render.stage_panels.appearance_note": "Klik for at anvende på markeringen. Træk hen på modellen. Hvis intet er markeret, gør et klik Maling klar.", + "render.stage_panels.apply": "Anvend", + "render.stage_panels.apply_studio": "Anvend studio", + "render.stage_panels.badge_blocked": "blokeret", + "render.stage_panels.badge_native": "indbygget", + "render.stage_panels.badge_projection": "overførsel", + "render.stage_panels.badge_reference": "reference", + "render.stage_panels.badge_specification": "kun spec.", + "render.stage_panels.candidate_summary": "Kandidater: {count} værdier med angivet kilde. Kvalitet og finish skal gennemgås.", + "render.stage_panels.captured_bounds": "Brug registrerede scenegrænser", + "render.stage_panels.centre": "Centrum", + "render.stage_panels.depth": "dybde", + "render.stage_panels.environments": "Omgivelser", + "render.stage_panels.extent": "Udstrækning", + "render.stage_panels.fit_save": "Tilpas og gem", + "render.stage_panels.gpu_required": "Kræver GPU path tracing", + "render.stage_panels.keep": "Behold", + "render.stage_panels.kept": "Beholdt", + "render.stage_panels.kept_fields": "Kamera, sampling, dimensioner, optiske bindinger, CAD-geometri og tekniske egenskaber.", + "render.stage_panels.kept_quality": "Metode, kamera, belysning, omgivelser, kulisse, optik, eksponering og tone mapping.", + "render.stage_panels.mine": "Mine", + "render.stage_panels.mine_pending": "Det understøttes endnu ikke at gemme personlige studioer.", + "render.stage_panels.omits": "Udelader", + "render.stage_panels.paint_pending": "Maling og tildeling ved træk understøttes endnu ikke. Vælg et mål for at anvende et udseende.", + "render.stage_panels.partial_reference": "Kandidater: kun værdier med angivet kilde. Gennemgå kvalitet, tilstand og kilder. Ukendte værdier forbliver ukendte.", + "render.stage_panels.plane": "Plan", + "render.stage_panels.prepare_plan": "Forbered oprettelsesplan", + "render.stage_panels.projects": "Projekter", + "render.stage_panels.quality_ack": "Jeg har forstået det faste budget og dets udeladelser", + "render.stage_panels.quality_omissions": "Adaptiv stop og fejlmål, separat transmissionsdybde, regler for Russian roulette, råt lineært output, EXR-master og konvergenscertificering.", + "render.stage_panels.reference": "Reference", + "render.stage_panels.references": "Referencer", + "render.stage_panels.remove_optics": "Fjern optik", + "render.stage_panels.remove_optics_help": "Fjerner den gemte optik fra denne optagelse. Kildegeometrien bevares.", + "render.stage_panels.remove_optics_title": "Fjern den gemte optik?", + "render.stage_panels.remove_shot": "Fjern optagelse", + "render.stage_panels.remove_stage": "Fjern kulisse", + "render.stage_panels.remove_stage_help": "Fjerner de gemte passive paneler fra denne optagelse. Kamerabaggrunden bevares.", + "render.stage_panels.remove_stage_title": "Fjern den gemte kulisse?", + "render.stage_panels.repeat": "Gentag", + "render.stage_panels.replaces": "Erstatter", + "render.stage_panels.replaces_environment": "Omgivelser", + "render.stage_panels.replaces_maps": "Midlertidige teksturkort på det valgte emne; gemt optik kan give konflikt.", + "render.stage_panels.replaces_physical": "Intet. Denne plan er skrivebeskyttet.", + "render.stage_panels.replaces_quality": "Billeddimensioner, faste samples, path-dybde, seed og støjreduktion.", + "render.stage_panels.replaces_rig": "Belysning, omgivelser og kulisse", + "render.stage_panels.replaces_saved_maps": "Gemte teksturkort på det valgte emne; midlertidige tilsidesættelser kan give konflikt.", + "render.stage_panels.replaces_stage": "Gemt grundplan og passive kulissepaneler", + "render.stage_panels.replaces_studio": "Belysning, omgivelser, eksponering og kulisse", + "render.stage_panels.replaces_uniform": "Uigennemsigtigt udseende på det valgte emne. Rumlige teksturkort tilnærmes med ensartede værdier.", + "render.stage_panels.review_environment": "Gennemgå omgivelser", + "render.stage_panels.review_maps": "Gennemgå GPU-teksturkort", + "render.stage_panels.review_physical": "Fysisk referenceplan", + "render.stage_panels.review_quality": "Brug et fast sample-budget", + "render.stage_panels.review_rig": "Tilpas lysrig", + "render.stage_panels.review_saved_maps": "Gennemgå gemte teksturkort", + "render.stage_panels.review_stage": "Gennemgå grundplan og kulisse", + "render.stage_panels.review_studio": "Gennemgå indbygget studio", + "render.stage_panels.review_uniform": "Gennemgå ensartet udseende", + "render.stage_panels.rig_summary": "Designet lysrig · {emitters} lyskilder, {cards} plader", + "render.stage_panels.rigs": "Lysrigge", + "render.stage_panels.save_maps": "Gem teksturkort i denne optagelse", + "render.stage_panels.scope": "Omfang", + "render.stage_panels.search_studios": "Søg i studioer", + "render.stage_panels.search_surfaces": "Søg i overflader og referencer", + "render.stage_panels.source_note": "Designet kilde-teksturkort for basisfarve. Ikke et målt materiale.", + "render.stage_panels.specifications": "Specifikationer · skrivebeskyttet", + "render.stage_panels.studio_ack": "Bekræft udskiftning af belysning, omgivelser, eksponering og kulisse", + "render.stage_panels.studio_note": "Klik for at gennemgå. Belysning, omgivelser og kulisse erstattes først, når du bekræfter. Lysene kan stadig redigeres.", + "render.stage_panels.studios": "Studioer", + "render.stage_panels.subtitle_environment": "Original HDR-omgivelse · hele scenen", + "render.stage_panels.subtitle_maps": "Designede rumlige teksturkort · midlertidig forhåndsvisning", + "render.stage_panels.subtitle_physical": "Skrivebeskyttet plan · intet materiale oprettet eller tildelt", + "render.stage_panels.subtitle_quality": "Fast GPU-budget · fremtidige krav udeladt", + "render.stage_panels.subtitle_rig": "Designet lysrig · lyskilder og passive plader", + "render.stage_panels.subtitle_saved_maps": "Designede teksturkort · gemt i denne optagelse", + "render.stage_panels.subtitle_stage": "Fysisk grundplan og kulisse · tilpasset produktet", + "render.stage_panels.subtitle_studio": "Indbygget studio · gælder hele scenen", + "render.stage_panels.subtitle_uniform": "Ensartet tilnærmelse · ikke et målt materiale", + "render.stage_panels.surfaces": "Overflader", + "render.stage_panels.surfaces_references": "Overflader og referencer", + "render.stage_panels.target": "Mål", + "render.stage_panels.use_budget": "Brug dette budget", + "render.stage_panels.use_maps": "Brug GPU-teksturkort", + "render.stage_panels.use_uniform": "Brug ensartet", + "render.stage_preview_note": "Integreret forhåndsvisning · direkte lys", + "render.state_completed": "Færdigt billede", + "render.state_in_progress": "Billede i gang", + "render.state_model": "Modelforhåndsvisning", + "render.strip_label": "Strimmel", + "render.studio_add_area": "Tilføj arealys", + "render.studio_ambient": "Konstant strålingstæthed i omgivelserne", + "render.studio_ambient_rgb": "Konstant strålingstæthed i omgivelserne (lineær RGB)", + "render.studio_aperture": "Blænderadius", + "render.studio_area": "Arealys", + "render.studio_area_help": "Op til fire ensidige rektangler. Ortogonale halvkanter U og V bestemmer størrelsen; U × V vender mod den oplyste side. Koordinaterne er mm i verdenskoordinater.", + "render.studio_center": "Centrum X, Y, Z (mm)", + "render.studio_denoise": "Reducér støj i det færdige billede", + "render.studio_denoise_help": "Afsluttende kantbevarende filter; fine detaljer kan blive blødere. Glas og skarpe spekulære overflader springer filteret over.", + "render.studio_direction": "Retning mod solen (X, Y, Z)", + "render.studio_environment": "Omgivelser", + "render.studio_environment_bounds": "Omgivelsesrotation skal være afgrænset og ligge inden for ±1.000.000 radianer, og intensiteten skal ligge mellem 0 og 100.", + "render.studio_environment_none": "Intet omgivelseskort", + "render.studio_focus": "Aksial fokusafstand", + "render.studio_half_u": "Halvkant U (mm)", + "render.studio_half_v": "Halvkant V (mm)", + "render.studio_hdr": "Radiance HDR-fil", + "render.studio_hdr_browse": "Vælg HDR…", + "render.studio_hdr_help": "Radiance .hdr, 2:1-panorama, op til 2048 × 1024. EXR er ikke tilgængelig. Farveantagelsen gælder kun, når primærfarverne er uspecificerede.", + "render.studio_hdr_required": "Vælg en lokal .hdr-fil.", + "render.studio_hdr_srgb": "Tolk uspecificerede primærfarver som lineær sRGB", + "render.studio_intensity": "Omgivelsesintensitet", + "render.studio_lens": "Dybdeskarphed", + "render.studio_lens_perspective": "Dybdeskarphed kræver et perspektivkamera.", + "render.studio_lighting": "Studiobelysning", + "render.studio_lighting_enable": "Brug brugerdefineret studiobelysning", + "render.studio_needs_review": "Gennemgå metode og indstillinger", + "render.studio_radiance": "Lineær RGB-strålingstæthed", + "render.studio_ready": "Klar til kontrol", + "render.studio_remove_area": "Fjern arealys", + "render.studio_rotation": "Omgivelsesrotation", + "render.studio_runtime_help": "Numeriske studioindstillinger og kontrollerede HDR-kilder kan gemmes med opsætningen. Optiske tilsidesættelser og materialetilsidesættelser på emner forbliver midlertidige og ændrer ikke gemte udseender.", + "render.studio_saved": "Gemt opsætning / aktuelt kamera", + "render.studio_sky": "Kunstnerisk himmel", + "render.studio_sky_help": "Originalt himmelfarveforløb til belysning; ikke en kalibreret atmosfæremodel.", + "render.studio_sun": "Sol", + "render.studio_sun_radius": "Vinkelradius", + "render.studio_tiles_require_gpu": "Studioer kræver GPU path tracing. Vælg GPU i Output-editoren.", + "render.studio_title": "Renderingsstudio", + "render.studio_tone_map": "Tone mapping", + "render.studios_environments": "Studioer og omgivelser", + "render.subsurface_enable": "Random walk med indre spredning", + "render.subsurface_help": "Kun lukkede dielektrika. Spredning og RGB-absorption er separate koefficienter pr. mm. Lysstier spredes inde i den faktiske geometri og brydes eller reflekteres derefter ved grænsen. Deaktivér direkte skyggetransmission, støjreduktion af overflader og eksternt volumen; brug ét Fresnel-stratum. Ikke en diffusionsshader, et densitetsgitter eller et målt materiale. Tætte medier kan kræve flere samples og større path-dybde.", + "render.subsurface_rate": "Kollisionsrate for spredning", + "render.tone_aces_fitted": "ACES fitted", + "render.tone_reinhard": "Reinhard", + "render.transmission_scope": "GPU-glas understøtter certificerede disjunkte medier. Ubegrænsede indlejrede medier og en støjfri transmissionsestimator leveres ikke.", + "render.transmission_strata": "Betingede Fresnel-strata", + "render.transmission_strata_help": "1 bevarer den oprindelige strøm. 2 eller 4 delstier stratificerer det første valg mellem glasrefleksion og transmission med uændrede love for Snell og absorption. Flere stier koster mere beregning; det er hverken støjreduktion, understøttelse af indlejrede medier eller et løfte om hurtigere rendering.", + "render.tree_add_light": "Tilføj lys", + "render.tree_add_shot": "Tilføj optagelse", + "render.tree_browser": "Renderingstræ", + "render.tree_by_look": "Efter udseende", + "render.tree_by_object": "Efter objekt", + "render.tree_constant": "Konstante omgivelser", + "render.tree_default": "Standard", + "render.tree_directional": "Retningslys", + "render.tree_environment": "Omgivelser", + "render.tree_environment_values": "{rotation}° · {intensity}×", + "render.tree_face_count": "{count} flader", + "render.tree_face_one": "{count} flade", + "render.tree_fixed_studio": "Fast studio", + "render.tree_hdr": "HDR", + "render.tree_lights": "Lys", + "render.tree_lights_pending": "Kommandoer til navngivne lys er endnu ikke tilgængelige.", + "render.tree_mixed": "Blandet", + "render.tree_more": "{count} flere", + "render.tree_mute": "Mute lys", + "render.tree_no_environment": "Ingen omgivelser", + "render.tree_objects": "Objekter", + "render.tree_output": "Output", + "render.tree_point": "Punktlys", + "render.tree_rectangle": "Rektangel", + "render.tree_search": "Søg i objekter", + "render.tree_selection": "Render markering", + "render.tree_shots": "Optagelser", + "render.tree_sky": "Himmel", + "render.tree_solo": "Solo lys", + "render.tree_spot": "Spotlys", + "render.tree_sun": "Sol", + "render.tree_switch": "Skift", + "render.tree_user_one": "{count} objekt", + "render.tree_users": "{count} objekter", "render.unavailable_preview": "Denne opsætning bruger en type forhåndsvisning, der ikke er tilgængelig.", "render.unsaved": "Ændringer i forhåndsvisning er ikke gemt", "render.use_preview": "Brug integreret forhåndsvisning", + "render.volume_albedo": "Spredningsalbedo · lineær RGB", + "render.volume_anisotropy": "Middelcosinus for fasefunktion", + "render.volume_enable": "Aktivér deltagende medium", + "render.volume_extinction": "Ekstinktionskoefficient", + "render.volume_help": "GPU-lystransport inde i én afgrænset boks, med Beer-dæmpning og HG-spredning på kamerastier og indirekte stier. Bruger eksplicit studio-, HDR- eller himmelbelysning, inklusive skyggedæmpning. Positiv fase-cosinus spreder fremad. Glasgrænser og støjreduktion af overflader skal deaktiveres udtrykkeligt. Nul ekstinktion lader lystransporten være uændret. Ikke en fysisk måneatmosfære, et densitetsgitter, volumenemission, spektral lystransport eller en certificeret materialeegenskab.", + "render.volume_max": "Maksimale grænser · mm i verdenskoordinater", + "render.volume_min": "Minimale grænser · mm i verdenskoordinater", + "render.volume_title": "Afgrænset homogent volumen", + "render.wait_add_light": "understøttes endnu ikke: oprettelse af navngivne lys", + "render.wait_batch": "understøttes endnu ikke: renderingskøen for gemte optagelser", + "render.wait_compare": "understøttes endnu ikke: sammenligning af bevarede billeder", + "render.wait_paint": "understøttes endnu ikke: valg af produkt og maling af udseende", + "render.wait_pick_up": "understøttes endnu ikke: valg af produkt og sampling af udseende", + "render.wait_replace": "understøttes endnu ikke: erstatning af alle anvendelser af et udseende", + "render.wait_solo": "understøttes endnu ikke: lysets synlighed og solo-styring", + "render.wear_applies_to": "Gælder for", + "render.wear_layer_count": "{count} lag", + "render.wear_layer_one": "{count} lag", + "render.wear_layers": "Lag", + "render.wear_no_layers": "Ingen lag", + "render.wear_selected_layer": "Valgt lag", + "render.wear_title": "Slid", "sample.bracket.about": "Grundflange med kantflanger og en ombukning efter en regel med 2 mm tykkelse", "sample.bracket.name": "Pladebeslag", "sample.enclosure.about": "Udhullet kasse med læbe, skruebøsninger, understøtning og snapforbindelse", @@ -1454,8 +3823,33 @@ "search.try": "Skriv et kommandonavn, en feature i dette design eller en parameter. Du kører en kommando med værdier ved at skrive dens id og et JSON-objekt: {example}", "search.valid": "Gyldig", "section.off_hint": "Intet plan valgt: OK slår snittet fra.", + "select a direction (an axis, a sketch line or a straight edge) first": "vælg først en retning (en akse, en skitselinje eller en ret kant)", + "select a direction (an axis, a sketch line or a straight edge) for the profile to follow": "vælg en retning (en akse, en skitselinje eller en ret kant), som profilen skal følge", + "select a point on a component": "vælg et punkt på en komponent", + "select a profile, edges or sketch lines first": "vælg først en profil, kanter eller skitselinjer", + "select an axis": "vælg en akse", + "select an axis, a straight or circular edge, or a cylinder, cone or torus face first": "vælg først en akse, en ret eller cirkulær kant eller en cylinder-, kegle- eller torusflade", + "select bodies first": "vælg først emner", + "select components first": "vælg først komponenter", + "select corner points, or the two lines of one corner": "vælg hjørnepunkter eller de to linjer i et hjørne", + "select one corner point, or the two lines of one corner": "vælg ét hjørnepunkt eller de to linjer i ét hjørne", + "select sheet edges first": "vælg først kanter på pladen", + "select the bend line (a sketch line) first": "vælg først bukkelinjen (en skitselinje)", + "select the cam's profile (a sketch profile or the cam's edges)": "vælg knastens profil (en skitseprofil eller knastens kanter)", + "select the corner to cut first": "vælg først hjørnet, der skal skæres væk", + "select the corners to round first": "vælg først hjørnerne, der skal afrundes", + "select the fixed face first (a plate's large face)": "vælg først den faste flade (pladens store flade)", + "select the frame sketch's lines first": "vælg først linjerne i rammeskitsen", + "select the path (sketch lines across the edge)": "vælg banen (skitselinjer på tværs af kanten)", + "select the rim face first": "vælg først randfladen", + "select the sheet edge first": "vælg først pladekanten", + "select two components": "vælg to komponenter", + "set by the sketch's lines": "bestemt af skitsens linjer", "settings.display_quality_note": "Gælder kun visningen. Design og eksport påvirkes ikke.", + "settings.double_click_components": "Dobbeltklik på en komponent for at aktivere den eller for at redigere en linket komponent på stedet", + "settings.frame_rate_details_note": "Tilføjer en graf over de seneste billeders tider med de tegnede trekanter oven på, et histogram over billedtider og det, GPU'en tegnede. Klik på billedfrekvensen i visningen for at vise eller skjule dem.", "settings.frame_rate_note": "Viser billeder pr. sekund nederst til højre i modelvisningen.", + "settings.insert_lists_open_designs": "Indsæt design viser først de design, der er åbne i andre faner", "settings.measure_axis_distances": "Vis X/Y/Z-afstande", "settings.measure_axis_distances_help": "Vis afstanden langs X-, Y- og Z-aksen sammen med den samlede afstand i Mål.", "settings.msaa_applies_on_restart": "Kantudjævning træder i kraft, næste gang SolidCraft starter", @@ -1466,22 +3860,59 @@ "settings.reset_intro": "Disse indstillinger virker ikke på denne computer og ville forhindre SolidCraft i at starte. De er derfor ændret:", "settings.reset_title": "Indstillinger blev ændret", "settings.supersampling_note": "Tegner visningen med højere opløsning og nedskalerer den: Jævnere kanter, linjer og gitter på skærme under 4K. Det kræver GPU-tid: ca. 2,25× så mange pixels ved 1,5× og 4× ved 2×.", + "settings.update_changed_links": "Opdatér ændrede linkede design, når en fane vender tilbage", + "settings.window_system_details": "Detaljer", + "settings.window_system_note_now": "Træder i kraft efter en genstart. Nu: {now}.", + "settings.window_system_wayland_limited": "Nogle funktioner er begrænsede på native Wayland.", + "sheet.flange_type_base": "Basis", + "sheet.flange_type_contour": "Kontur", + "sheet.flange_type_edge": "Kant", "sheet.no_body": "der er intet pladelegeme: Start et med Flange > Basis, eller omdan en plade til et pladelegeme med Konvertér til plade (vælg dens store plane flade)", + "sheet.personal_rules.confirm_delete": "Bekræft sletning", + "sheet.personal_rules.delete": "Slet", + "sheet.personal_rules.delete_prompt": "Slet denne personlige regel? Regler, der allerede bruges i designs, ændres ikke.", + "sheet.personal_rules.full": "Det personlige bibliotek indeholder allerede 64 regler.", + "sheet.personal_rules.invalid_name": "Angiv et kort navn uden linjeskift eller kontroltegn.", + "sheet.personal_rules.invalid_values": "Udfyld reglens værdier: Hver af dem skal kunne udregnes i dette design, med en positiv tykkelse og en K-faktor fra 0 til 1.", + "sheet.personal_rules.missing": "Den valgte personlige regel er ikke længere tilgængelig.", + "sheet.personal_rules.name": "Navn på regel", + "sheet.personal_rules.name_exists": "Der findes allerede en personlig regel med dette navn. Brug et andet navn.", + "sheet.personal_rules.name_hint": "Et entydigt navn", + "sheet.personal_rules.overwrite": "Gem ændringer i den valgte personlige regel", + "sheet.personal_rules.rename": "Omdøb", + "sheet.personal_rules.rule": "Personlig regel", + "sheet.personal_rules.save": "Gem som ny", + "sheet.personal_rules.scope": "Gemt i din profil og tilgængelig i alle designs.", + "sheet.personal_rules.select": "Vælg en regel", + "sheet.personal_rules.title": "Personlige regler", + "sheet.personal_rules.unsupported": "Denne regel har værdier, som denne version ikke kan bruge.", "shortcut.json_error": "parametre skal være JSON: {error}", "shortcut.no_command": "ingen kommando `{id}`; teksten før JSON skal være et kommando-id", "shortcut.pin": "Fastgør øverst i S-boksen", "shortcut.unpin": "Frigør", + "sketch is missing": "skitsen mangler", "sketch.degrees_of_freedom": "Frihedsgrader: {count}", + "sketch.dimension_added_driven": "Skitsen bestemmer allerede dette mål, så det blev tilføjet som afledt mål (reference)", + "sketch.dimension_applied": "Mål anvendt", + "sketch.dimension_applied_defined": "Mål anvendt; parameteren `{name}` er defineret", + "sketch.dimension_applied_renamed": "Mål anvendt; parameter med navnet `{name}`", "sketch.dof_left": "{count} frihedsgrader tilbage", "sketch.dof_left_one": "{count} frihedsgrad tilbage", "sketch.draw_curves": "Tegn som {linetype}", "sketch.make_selection": "Konvertér markeringen til {linetype}", "sketch.open_ends": "Åbne ender: {count}", + "sketch.status_conflict": "bindinger er i konflikt", + "sketch.status_fully_constrained": "fuldt bundet", "sketch.untied_ends": "Ender uden binding: {count}", "sketch_panel.attached": "Tilknyttet {body} / {path}", "sketch_panel.author": "Forfatterplacering: {path}", "sketch_panel.dimension_hint": "Angiv en værdi eller et udtryk, og tryk derefter på OK.", "sketch_panel.move_hint": "Angiv afstande og en vinkel, og tryk derefter på OK.", + "sketch_panel.plane_angle": "{plane}, drejet med {angle}", + "sketch_panel.plane_fixed": "Et fast plan", + "sketch_panel.plane_flipped": "{plane}, fra dens anden side", + "sketch_panel.plane_offset": "{plane}, forskudt med {distance}", + "sketch_panel.plane_origin": "Planet {plane}", "sketch_panel.redefine_title": "{command}: {name}", "sketch_panel.sheet_attachment": "Tilknyttet en plan flade på et pladeemne; den følger panelet, når pladen ændres.", "sketch_panel.text_hint": "Redigér teksten og dens placering, og tryk derefter på OK.", @@ -1491,36 +3922,80 @@ "sketch_text.align_right": "Højre", "sketch_text.bold": "Fed", "sketch_text.builtin_font": "{family} (indbygget)", + "sketch_text.formula": "Start med = for at bygge ordene ud fra parametre: ='W' + number(Width)", "sketch_text.italic": "Kursiv", "sketch_text.loading_fonts": "Søger efter installerede skrifttyper…", + "sketch_text.no_bold": "Den indbyggede skrifttype har ingen fed udgave: Vælg en installeret skrifttype", "sketch_text.on_path": "Teksten følger sin bane: Kurven bestemmer placeringen", "sketch_text.path_clear": "Frigør teksten fra dens kurve", "sketch_text.path_hint": "En kurve i skitsen, som teksten følger: Klik her og derefter på kurven", "sketch_text.use_font_file": "Brug skrifttypefilen {path}", "solid": "massivt emne", + "status.editing": "Redigerer {name}", + "status.navigation": "Musetildeling: {mapping}", + "status.navigation_tip": "Hvordan musen styrer visningen. Klik for at vælge en anden tildeling", + "status.under_constrained": "Ikke fuldt bundet ({count} frihedsgrader)", + "status.under_constrained_one": "Ikke fuldt bundet ({count} frihedsgrad)", + "status.units_tip": "Designets enheder. Klik for at ændre dem", + "the angle must be a number": "vinklen skal være et tal", + "the curves must be in one sketch": "kurverne skal være i samme skitse", + "the direction must be an axis, a sketch line or a straight edge": "retningen skal være en akse, en skitselinje eller en ret kant", + "the duration must be a number of seconds, 0.001 or more": "varigheden skal være et antal sekunder, 0,001 eller mere", + "the line's sketch is gone": "linjens skitse findes ikke længere", + "the lines must be in one sketch": "linjerne skal være i samme skitse", + "the lines must be in one sketch, not the section's": "linjerne skal være i samme skitse, ikke tværsnittets", + "the parts library is empty": "biblioteket med standarddele er tomt", "the parts library is not available": "biblioteket med standarddele er ikke tilgængeligt", + "the path curves must be in one other sketch": "banekurverne skal være i én anden skitse", + "the path's sketch is gone": "banens skitse findes ikke længere", + "the position must be a number": "positionen skal være et tal", + "the preview failed": "forhåndsvisningen mislykkedes", + "the profiles and curves must be in one sketch": "profilerne og kurverne skal være i samme skitse", + "the reference face must be on the edges' body": "referencefladen skal være på kanternes emne", + "the scale must be above 0": "skaleringen skal være over 0", + "the section's profiles must be in one sketch": "tværsnittets profiler skal være i samme skitse", + "the two origins are on the same component": "de to nulpunkter er på samme komponent", "thread.automatic_size": "Automatisk størrelse", "thread.designation": "Betegnelse", "thread.iso_metric": "ISO-metrisk", "thread.select_size": "Vælg størrelse", "timeline.delete_after_marker_one": "Slet 1 feature efter historikmarkøren", "timeline.delete_after_marker_other": "Slet {count} features efter historikmarkøren", + "timeline.delete_folders_tip": "Behold deres features og indlejrede mapper i historikken", + "timeline.delete_folders_with_features_tip": "Slet mapperne med alle features i dem og deres indlejrede mapper", "timeline.delete_many": "Slet {count} valgte features", + "timeline.edited_rolled_back": "{name} er ændret, men ligger efter historikmarkøren og bliver derfor ikke bygget: Flyt markøren forbi den for at se resultatet", + "timeline.feature_error": "Fejl: {message}", + "timeline.feature_hint": "Dobbeltklik for at redigere · træk for at ændre rækkefølgen · højreklik for mere", + "timeline.feature_rolled_back": "Rullet tilbage: efter historikmarkøren og derfor ikke bygget", + "timeline.feature_warning": "Advarsel: {message}", "timeline.group": "Ny featuremappe", "timeline.move_many": "Flyt elementer i tidslinjen", "timeline.move_to_group": "Flyt features til mappe", "timeline.rename_group": "Omdøb featuremappe", "timeline.reorder_many": "Skift rækkefølge på features", + "timeline.suppress_features": "Undertryk features", + "timeline.suppress_folders_tip": "Undertryk eller ophæv undertrykkelsen af alle features i mapperne og deres indlejrede mapper", "timeline.ungroup": "Fjern featuremapper", + "timeline.unsuppress_features": "Ophæv undertrykkelse af features", "to the face": "til fladen", "to the next face": "til næste flade", "toolbar.customize_note": "Fanen {tab}. Markér en kommando for at give den en værktøjslinjeknap. Du kan også trække en række fra et panels rullemenu over på værktøjslinjen, trække en knap af værktøjslinjen for at fjerne den eller bruge nålen på en rullemenurække.", "toolbar.image": "BILLEDE", "toolbar.render": "RENDERING", + "toolbar.render_appearance": "UDSEENDE", + "toolbar.render_camera": "KAMERA", + "toolbar.render_environment": "OMGIVELSER", + "toolbar.render_lighting": "BELYSNING", + "toolbar.render_lights": "LYS", + "toolbar.render_result": "RESULTAT", "toolbar.render_scene": "SCENE", + "toolbar.render_stage": "OPSTILLING", + "toolbar.render_studio": "STUDIO", "trace.points": "Punkter langs banen: {count}", "trace.stopped_by_contact": "Slutter ved prøve {sample}: {a} ville gå gennem {b}", "trace.stopped_by_loop": "Slutter ved prøve {sample}: Løkken gennem {joint} kan ikke lukkes yderligere", + "trim by sketch curves, or by one plane or face": "trim med skitsekurver eller med ét plan eller én flade", "ui.1_degree_of_freedom": "1 frihedsgrad", "ui.3d_mouse_axes_reassigned": "Akserne er omtildelt i Indstillinger, og det gælder stadig oven på denne kalibrering.", "ui.3d_mouse_button": "Knap {number}", @@ -1574,6 +4049,10 @@ "ui.3d_mouse_offer": "Kalibrering af din 3D-mus retter ombyttede eller vendte akser og indstiller dens hastighed og fornemmelse.", "ui.3d_mouse_offer_never": "Vis ikke igen", "ui.3d_mouse_offer_swap": "Skift til Hidraw (direkte driver)", + "ui.3d_mouse_orbit": "Rotér visning", + "ui.3d_mouse_orbit_classic": "Klassisk", + "ui.3d_mouse_orbit_tip": "Sporet: 3D-musen drejer visningen omkring den del af modellen, der er midt i visningen, når drejningen begynder, markeret med en svag kugle. Klassisk: omkring visningens centrum", + "ui.3d_mouse_orbit_traced": "Sporet", "ui.3d_mouse_reading": "Aflæser", "ui.3d_mouse_reset_axes": "Nulstil aksetildeling", "ui.3d_mouse_reset_view": "Nulstil visning", @@ -1582,6 +4061,8 @@ "ui.3d_mouse_section": "3D-mus", "ui.3d_mouse_show_in_view": "Vis 3D-musen i 3D-visningen", "ui.3d_mouse_show_in_view_tip": "Et billede af din 3D-mus i nederste venstre hjørne, der bevæger sig, når du bevæger den.", + "ui.3d_mouse_sketch_orbit": "Drej skitser med 3D-musen", + "ui.3d_mouse_sketch_orbit_tip": "3D-musen drejer også visningen, mens en skitse er åben og set lige forfra, ligesom musen kan. Slået fra: Den panorerer og zoomer skitsen, indtil du vipper visningen.", "ui.3d_mouse_skip": "Min enhed kan ikke det", "ui.3d_mouse_skip_tip": "Springer bevægelsen over begge veje, og kalibreringen udelader den.", "ui.3d_mouse_speed": "3D-musens hastighed", @@ -1610,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Drej knoppen mod uret, hold den, og slip.", "ui.3d_mouse_switch_cap": "Kalibrer som vend tilbage til midten", "ui.3d_mouse_switch_trackball": "Kalibrér som trackball", + "ui.3d_mouse_use_direct": "Brug direkte driver", + "ui.3d_mouse_use_direct_tip": "Læs 3D-musen direkte (hidraw) i stedet for gennem spacenavd.", "ui.3d_mouse_view_axis": "Visningsakse", "ui.3d_mouse_view_off": "Fra", "ui.3d_mouse_view_off_tip": "3D-musedriverens profil slår denne akse fra, så dens bevægelse flytter ikke visningen. Vælger du en anden akses bevægelse her, bytter de to plads, og den bevægelse flytter ikke længere visningen.", @@ -1635,6 +4118,8 @@ "ui.agent_chat_allowed": "Tilladt", "ui.agent_chat_answered": "Svar: {option}", "ui.agent_chat_approval": "Tillad agenten at gøre dette?", + "ui.agent_chat_attach_selection": "Vedhæft markering", + "ui.agent_chat_attach_selection_tip": "Send det, der er markeret i modellen (flader, kanter, features, emner), sammen med beskeden, så agenten ved, hvad du mener", "ui.agent_chat_attach_view": "Vedhæft visning", "ui.agent_chat_attach_view_tip": "Send et billede af den aktuelle visning sammen med beskeden", "ui.agent_chat_attachable": "Billeder, PDF-filer, tekst og CAD-filer", @@ -1646,12 +4131,23 @@ "ui.agent_chat_auth_terminal": "Kør dette i en terminal, og tryk derefter på Forbind igen:", "ui.agent_chat_auth_title": "Log ind hos agenten", "ui.agent_chat_cancel": "Annullér", + "ui.agent_chat_cancel_timeout": "Agenten svarede ikke på Stop og blev afbrudt. Forbind igen for at fortsætte.", + "ui.agent_chat_cannot_start": "Installeret, men den starter ikke: {error}", "ui.agent_chat_changes": "Ændringer: {n}, ét fortrydelsestrin", + "ui.agent_chat_changes_n": "{n} ændringer", "ui.agent_chat_changes_of": "{n}/{limit} ændringer", + "ui.agent_chat_choose_model": "Vælg en model", "ui.agent_chat_close": "Luk", "ui.agent_chat_command": "Agentkommando", "ui.agent_chat_connect": "Forbind", "ui.agent_chat_copy": "Kopiér", + "ui.agent_chat_copy_message": "Kopiér besked", + "ui.agent_chat_ctx_bodies": "Emner", + "ui.agent_chat_ctx_elements": "Elementer", + "ui.agent_chat_ctx_features": "Features", + "ui.agent_chat_ctx_more": "+{n} flere", + "ui.agent_chat_ctx_other": "Andet", + "ui.agent_chat_custom_heading": "Brugerdefineret model", "ui.agent_chat_custom_hint": "Ethvert program, der bruger Agent Client Protocol via stdin og stdout. Det køres uden en kommandoskal.", "ui.agent_chat_denied": "Afvist", "ui.agent_chat_deny": "Afvis", @@ -1687,13 +4183,24 @@ "ui.agent_chat_import_failed": "{name}: Importen mislykkedes: {error}", "ui.agent_chat_intro": "Chat med en kodeagent, du allerede bruger, eller en modeltjeneste, du vælger. Den arbejder på det åbne design gennem SolidCrafts værktøjer: Ændringer vises undervejs og fortrydes som ét trin pr. besked. Hvad den må gøre uden at spørge, angives i Indstillinger > AI.", "ui.agent_chat_key_in_env": "nøgle angivet", + "ui.agent_chat_last_missing": "Agenten, der sidst blev brugt ({agent}), er ikke længere tilgængelig. Vælg en agent, og tryk derefter på Prøv igen.", "ui.agent_chat_left": "Venstre", "ui.agent_chat_limit": "Agenten nåede grænsen på {limit} ændringer for én besked. Send en ny besked for at lade den fortsætte.", + "ui.agent_chat_login_found": "login fundet", "ui.agent_chat_minimize": "Minimér til en stribe", "ui.agent_chat_mode_all": "Alt", "ui.agent_chat_mode_ask": "Spørg", "ui.agent_chat_mode_edits": "Ændringer", + "ui.agent_chat_model_custom": "Brug brugerdefineret model: {model}", + "ui.agent_chat_model_no_tools": "{model} kan ikke bruge SolidCrafts værktøjer og kan derfor kun chatte. Vælg en model med understøttelse af værktøjer.", + "ui.agent_chat_model_rejected": "Agenten accepterede ikke {model}: {error}", + "ui.agent_chat_model_search": "Søg efter modeller…", "ui.agent_chat_model_tip": "Modellen, som agenten bruger. Dit valg huskes for denne agent.", + "ui.agent_chat_models_failed": "Kunne ikke hente listen over modeller: {error}", + "ui.agent_chat_models_heading": "Tilgængelige modeller", + "ui.agent_chat_models_listing": "Henter modeller…", + "ui.agent_chat_models_none": "Endepunktet viser ingen modeller", + "ui.agent_chat_models_not_a_list": "Svaret var ikke en liste over modeller", "ui.agent_chat_new": "Ny chat", "ui.agent_chat_new_confirm": "Start en ny chat? Den aktuelle chat ryddes.", "ui.agent_chat_next_picture": "Næste billede", @@ -1701,6 +4208,7 @@ "ui.agent_chat_no_control": "Agentchattens endepunkt startede ikke, så agenten kan ikke få adgang til designet.", "ui.agent_chat_no_images": "Denne agent kan ikke modtage billeder", "ui.agent_chat_no_picture": "Der er intet billede i udklipsholderen", + "ui.agent_chat_no_tool_call": "Modellen brugte ikke SolidCrafts værktøjer, så designet blev ikke ændret. Vælg en model, der understøtter værktøjskald; se Lokale modeller i guiden til agentchatten.", "ui.agent_chat_none_found": "Ingen kodeagent fundet. Installér en af disse, og tryk derefter på Opdatér:", "ui.agent_chat_none_found_short": "Ingen agent fundet", "ui.agent_chat_not_installed": "Ikke installeret", @@ -1710,21 +4218,30 @@ "ui.agent_chat_paste_picture": "Indsæt et billede", "ui.agent_chat_permission": "Agenten beder om at køre: {title}", "ui.agent_chat_pick": "Agent", + "ui.agent_chat_pick_context": "Vælg kontekst", + "ui.agent_chat_pick_context_tip": "Vælg flader, kanter, features og emner i modellen, som agenten skal se på, og tryk derefter på OK", "ui.agent_chat_placeholder": "Bed agenten om at ændre designet…", "ui.agent_chat_placeholder_busy": "Sæt en besked i kø til agenten er færdig (Ctrl+Enter: send nu)", "ui.agent_chat_pop_out": "Åbn i eget vindue, som du kan flytte til en anden skærm", "ui.agent_chat_previous_picture": "Forrige billede", "ui.agent_chat_privacy": "Intet sendes andre steder end til den agent, du kører, under din egen konto.", "ui.agent_chat_privacy_note": "Chatten sender selv intet nogen steder: Agenten, du kører, kommunikerer med sin egen tjeneste under din egen konto. SolidCraft ser eller gemmer aldrig en nøgle eller adgangskode.", + "ui.agent_chat_provider_models": "{count} modeller", + "ui.agent_chat_provider_other": "Andet", + "ui.agent_chat_provider_tip": "Udbyderen, hvis modeller den næste liste viser.", "ui.agent_chat_queue": "Sæt i kø", "ui.agent_chat_queue_full": "For mange beskeder venter: Fjern en, eller vent på agenten.", "ui.agent_chat_queued": "I kø", "ui.agent_chat_queued_stopped": "I kø (stoppet, ikke sendt)", "ui.agent_chat_refresh": "Opdatér", "ui.agent_chat_refused": "Ikke tilladt for agenten: {reason}", + "ui.agent_chat_reinstall": "{agent} er installeret ({program}), men den startede ikke, da SolidCraft kontrollerede den: {error}\nInstallationen kan være ufuldstændig eller lavet til en anden type computer. Installér den igen med `{install}`, kontrollér i en terminal, at den udskriver sin version, og tryk derefter på Opdatér.", "ui.agent_chat_remove": "Fjern fra køen", "ui.agent_chat_remove_file": "Fjern fra denne besked", "ui.agent_chat_remove_imported": "Fjern fra denne besked; emnet bliver i designet (Fortryd fjerner det)", + "ui.agent_chat_reply_cut_off": "Svaret nåede sin længdegrænse, før det var færdigt, så det kan være ufuldstændigt. Bed agenten om at fortsætte eller om et kortere svar.", + "ui.agent_chat_reply_declined": "Modellen afviste at svare på denne besked.", + "ui.agent_chat_retry": "Prøv igen", "ui.agent_chat_right": "Højre", "ui.agent_chat_save": "Gem", "ui.agent_chat_send": "Send", @@ -1737,6 +4254,7 @@ "ui.agent_chat_state_auth": "Login kræves", "ui.agent_chat_state_busy": "Arbejder…", "ui.agent_chat_state_exited": "Agent stoppet", + "ui.agent_chat_state_failed": "Forbindelsen mislykkedes", "ui.agent_chat_state_off": "Ikke forbundet", "ui.agent_chat_state_ready": "Klar", "ui.agent_chat_state_starting": "Starter…", @@ -1744,6 +4262,7 @@ "ui.agent_chat_stop_tip": "Stop agenten og alt, hvad den har startet", "ui.agent_chat_stop_turn_tip": "Stop agenten (Esc). Beskeder i kø bliver i køen.", "ui.agent_chat_turn_limit": "Ændringer pr. besked", + "ui.agent_chat_turn_unlimited": "Ubegrænset", "ui.agent_chat_undo_changes": "Fortryd disse ændringer", "ui.agent_chat_undo_label": "Agentchat: {message}", "ui.agent_chat_undone": "(fortrudt)", @@ -1780,12 +4299,17 @@ "ui.ai_copy_suffix": "kopi", "ui.ai_custom_url": "Brugerdefineret URL", "ui.ai_default": "Standard", + "ui.ai_edit": "Redigér", + "ui.ai_edit_agent_title": "Redigér agent", + "ui.ai_edit_gone": "Denne agent er fjernet, så der er intet at gemme.", + "ui.ai_edit_tip": "Ændr denne agents navn, kommando eller endepunkt. En gemt nøgle forbliver skjult.", "ui.ai_http_busy": "endepunktet er optaget eller har nået sin grænse; prøv igen senere", "ui.ai_http_key": "endepunktet afviste nøglen: Kontrollér den i Indstillinger > AI", "ui.ai_http_not_found": "endepunktet eller modellen findes ikke: Kontrollér basis-URL og modelnavn", "ui.ai_http_too_large": "samtalen er for stor til dette endpoint; start en ny chat", "ui.ai_key": "API-nøgle", "ui.ai_key_hint": "valgfri; gemmes i systemets nøglering", + "ui.ai_key_keep_hint": "lad feltet stå tomt for at beholde den gemte nøgle", "ui.ai_key_needs_https": "En nøgle sendes kun via HTTPS eller til denne computer.", "ui.ai_key_note": "Gemmes i systemets nøglering, aldrig i SolidCrafts indstillinger. Lad feltet være tomt ved en lokal server.", "ui.ai_keychain_error": "Systemets nøglering afviste anmodningen: {error}", @@ -1812,8 +4336,15 @@ "ui.ai_permissions": "Tilladelser", "ui.ai_preset": "Forudindstilling", "ui.ai_protocol": "Protokol", + "ui.ai_reasoning_effort": "Ræsonnementsindsats", + "ui.ai_reasoning_effort_field_hint": "tom = udbyderens standard", + "ui.ai_reasoning_effort_hint": "Valgfrit. Sendes til slutpunktet som `reasoning_effort`; accepterede værdier varierer fra udbyder til udbyder (for eksempel `low`, `high` eller `max`). En værdi, du angiver her, erstattes aldrig af SolidCraft. Lad feltet stå tomt for ikke at sende noget og beholde udbyderens standard.", "ui.ai_remove": "Fjern", + "ui.ai_request_timed_out": "Modellen brugte mere end {seconds} s. Du kan hæve tidsgrænsen for anmodninger til dette endepunkt under Indstillinger › Assistent.", + "ui.ai_request_timeout": "Tidsgrænse for anmodning", + "ui.ai_request_timeout_hint": "Hvor lang tid en modelanmodning til dette endepunkt må tage, fra 30 s til en time. Hæv den for en langsom lokal model.", "ui.ai_reset": "Nulstil", + "ui.ai_save": "Gem", "ui.ai_settings": "AI-indstillinger…", "ui.ai_show_features": "Vis AI-funktioner", "ui.ai_show_features_note": "Agentchatten: Et panel, hvor en kodeagent, du allerede bruger, eller en modeltjeneste, du vælger, arbejder på det åbne design. Slået fra: Ingen AI-knap, genvej, menupunkt eller panel, og der søges ikke efter eller startes noget.", @@ -1827,9 +4358,27 @@ "ui.ai_test_no_model": "Forbindelse oprettet: {count} modeller, men ikke {model}", "ui.ai_test_ok": "Forbindelse oprettet: {count} modeller", "ui.ai_testing": "Tester…", + "ui.ai_tool_arguments": "Argumenter", + "ui.ai_tool_details": "Detaljer", "ui.ai_tool_done": "færdig", "ui.ai_tool_failed": "mislykkedes", + "ui.ai_tool_result": "Resultat", "ui.ai_tool_running": "kører", + "ui.ai_tool_sum_bodies_one": "{count} emne", + "ui.ai_tool_sum_bodies_other": "{count} emner", + "ui.ai_tool_sum_by": "med {value}", + "ui.ai_tool_sum_edges_one": "{count} kant", + "ui.ai_tool_sum_edges_other": "{count} kanter", + "ui.ai_tool_sum_faces_one": "{count} flade", + "ui.ai_tool_sum_faces_other": "{count} flader", + "ui.ai_tool_sum_features_one": "{count} feature", + "ui.ai_tool_sum_features_other": "{count} features", + "ui.ai_tool_sum_measured": "Målte {what}", + "ui.ai_tool_sum_more": "{steps} og {count} flere", + "ui.ai_tool_sum_radius": "r {value}", + "ui.ai_tool_sum_saved": "Gemte {file}", + "ui.ai_tool_sum_screenshot": "Skærmbillede", + "ui.ai_tool_sum_then": "{first}, derefter {next}", "ui.ai_tool_unfold": "Klik for at vise svaret", "ui.ai_tool_waiting": "venter", "ui.ai_toolbar_button": "Vis Assistent-knappen på programlinjen", @@ -1859,6 +4408,9 @@ "ui.blocked": "Blokeret", "ui.bodies": "Emner", "ui.bodies_all_if_none": "Emner (alle, hvis ingen er valgt)", + "ui.body_kind_mesh": "Meshlegeme", + "ui.body_kind_solid": "Massivt legeme", + "ui.body_kind_surface": "Overfladelegeme", "ui.bottom": "Nedenfra", "ui.box": "Boks", "ui.break": "Bryd", @@ -1871,6 +4423,8 @@ "ui.cancel": "Annullér", "ui.canvases": "Referencebilleder", "ui.center": "Centrum", + "ui.center_arc_follows_cursor": "Bue med centrum følger markørens retning", + "ui.center_arc_follows_cursor_tip": "En bue med centrum løber med eller mod uret, efter hvordan markøren bevæger sig rundt om dens centrum. Fra: Altid mod uret fra start.", "ui.centerline": "Centerlinje", "ui.chain": "Kæde", "ui.chamfer": "Affasning", @@ -1879,6 +4433,7 @@ "ui.circle": "Cirkel", "ui.circular_pattern": "Cirkulært mønster", "ui.clear": "Ryd", + "ui.clear_print_face": "Ryd printflade", "ui.clear_recent": "Ryd seneste", "ui.clear_the_selection": "Ryd markeringen", "ui.click_selects_whole_bodies": "Klik vælger hele emner", @@ -1913,15 +4468,32 @@ "ui.constant": "Konstant", "ui.constraints_conflict": "Bindinger er i konflikt", "ui.construction": "Konstruktionsgeometri", + "ui.construction.angle_hint": "Hjælpelinje: Klik på et punkt, og skriv derefter en vinkel eller vælg en retning", + "ui.construction.bisector_hint": "Halveringslinje: Vælg to rette linjer, der skærer hinanden, og vælg derefter den ønskede løsning", + "ui.construction.common_hint": "Fælles tangent: Vælg to cirkler/buer, og vælg derefter den ønskede løsning", + "ui.construction.contact_hint": "Tangent: Vælg en cirkel/bue eller en åben spline/keglesnit, og vælg derefter røringspunktet (frie kurver: endepunkter)", + "ui.construction.external_hint": "Tangent: Vælg en cirkel eller bue og et eksternt punkt, og vælg derefter den ønskede løsning", + "ui.construction.free_hint": "Hjælpelinje: Klik på to punkter; højreklik for at starte forfra", + "ui.construction.normal_needs_length": "En uendelig linje er altid en hjælpelinje: Skriv en længde for at tegne en normal linje", + "ui.construction.point_hint": "Hjælpelinje: Klik på det punkt, linjen skal gå igennem", + "ui.construction.reference_hint": "Hjælpelinje: Vælg en ret linje og derefter et punkt; højreklik for at skifte reference", "ui.construction.ribbon_label": "Hjælpelinjer", + "ui.construction.side_hint": "Hjælpelinje: Klik på den side, linjen går mod; højreklik for at starte forfra", "ui.context_menu": "Genvejsmenu", + "ui.continuity_crease": "Knæk", + "ui.continuity_curvature": "Krumning", + "ui.continuity_curvature_change": "Ændring i krumning", "ui.continuity_g0": "G0-knæk", "ui.continuity_g1": "G1-tangentkontinuitet", "ui.continuity_g2": "G2-krumningskontinuitet", "ui.continuity_gap": "Åbning mellem flader", + "ui.continuity_position": "Positionskontinuitet", + "ui.continuity_tangent": "Tangentkontinuitet", "ui.copy": "Kopiér", "ui.corner": "Hjørne", "ui.corners": "Hjørner", + "ui.cosmetic_thread_markings": "Kosmetiske gevindmarkeringer", + "ui.cosmetic_thread_markings_help": "Vis skematiske markeringer på cylindriske vægge med gevind. Ændrer kun visningen, aldrig designet eller eksporterne.", "ui.counterbore": "Cylindrisk forsænkning", "ui.countersink": "Konisk forsænkning", "ui.create": "Opret", @@ -1939,6 +4511,7 @@ "ui.dark": "Mørk", "ui.default_modelling_orientation": "Standardorientering for modellering", "ui.delete": "Slet", + "ui.delete_select_first": "Vælg først, hvad der skal slettes: features, emner, komponenter eller skitsegeometri", "ui.depth": "Dybde", "ui.design": "Design", "ui.design_properties.author": "Forfatter", @@ -1952,8 +4525,45 @@ "ui.design_properties.part_number": "Emnenummer", "ui.design_properties.project": "Projekt", "ui.design_properties.revision": "Revision", + "ui.design_saved": "Gemte {path}", + "ui.details_access_caption": "Flader viser, om et værktøj kan nå dem fra den valgte retning.", + "ui.details_angle": "Vinkel", + "ui.details_continuity_caption": "Redigér den valgte overgang. Andre overgange beholder deres egne indstillinger.", + "ui.details_continuity_stale": "Tidligere geometri: Kør analysen igen for at redigere eller indramme denne overgang.", + "ui.details_copy_list": "Kopiér liste", + "ui.details_curvature": "Krumningstolerance", + "ui.details_curvature_caption": "Flader farves efter deres lokale krumningsradius.", + "ui.details_direction": "Værktøjsretning", + "ui.details_draft_caption": "Flader farves efter deres vinkel til udtræksretningen.", + "ui.details_edit_seam": "Redigér overgang", + "ui.details_fixture": "Komponenteksempel — kun eksempeldata", + "ui.details_fixture_caption": "Komponenteksempel med illustrative værdier; dette er ikke et resultat fra modellen.", + "ui.details_fixture_problem": "Eksempel på fund med et problem", + "ui.details_fixture_readout": "Eksempel på målt værdi", + "ui.details_flip": "Vend", + "ui.details_gap": "Åbning", + "ui.details_hatch": "Skraver snitflader", + "ui.details_jump": "Krumningsspring", + "ui.details_key": "Forklaring", + "ui.details_offset": "Forskydning", + "ui.details_plane": "Plan", + "ui.details_pull": "Udtræksretning", + "ui.details_radius": "Radius", + "ui.details_readout": "Aflæsning", + "ui.details_samples": "Prøvepunkter", + "ui.details_seam": "{body} · Kant {edge}", + "ui.details_settings": "Indstillinger", + "ui.details_sharp_gap": "Skarp eller åbning", + "ui.details_show_all": "Vis alle {count}", + "ui.details_smooth": "Glat", + "ui.details_stripes": "Striber", + "ui.details_target": "Indram geometri", + "ui.details_worst_seams": "Dårligste overgange", + "ui.details_zebra_caption": "Reflekterede striber viser, hvor glat flader går sammen.", "ui.diameter": "Diameter", "ui.dimension": "Målsætning", + "ui.direct_interaction": "Direkte interaktion", + "ui.direct_interaction_note": "Arbejd direkte på modellen i visningsområdet. Tryk på en plan flade eller en profil, og træk: Op ekstruderer, ned i et emne skærer, og sidelæns bevægelse sætter trinstørrelsen", "ui.direction": "Retning", "ui.display_quality": "Visningskvalitet", "ui.display_quality_coarse": "Grov", @@ -1975,14 +4585,45 @@ "ui.easyprint_uploading": "Uploader til Printables…", "ui.edit": "Redigér", "ui.editJointLimits": "Redigér ledgrænser", + "ui.edit_in_place": "Redigér på stedet", + "ui.edit_in_place_after_turn": "Redigeringen afsluttes, når agentens tur er slut", + "ui.edit_in_place_agent_busy": "Agenten arbejder stadig i dette design; prøv igen, når dens tur er slut", + "ui.edit_in_place_already_queued": "En redigering venter allerede på, at agentens tur slutter", + "ui.edit_in_place_assembly_closed": "{name} er ikke længere åben", + "ui.edit_in_place_banner": "Redigerer i {name}", + "ui.edit_in_place_busy": "Afslut eller annullér først det, der er åbent", + "ui.edit_in_place_none": "Intet linket design redigeres på stedet", + "ui.edit_in_place_not_saved": "Delen har ændringer, der ikke er gemt; gem den for at afslutte redigeringen", + "ui.edit_in_place_open_elsewhere": "{name} er åben i et andet SolidCraft", + "ui.edit_in_place_opens_after_turn": "Delen åbnes, når agentens tur er slut", + "ui.edit_in_place_refresh_dropped": "Samlingen blev ændret, mens Opdatér forbindelser kørte; kør den igen", + "ui.edit_in_place_refresh_stopped": "Opdatér forbindelser blev stoppet, før den var færdig", + "ui.edit_in_place_refreshing": "Opdaterer forbindelser i {name}…", + "ui.edit_in_place_save_first": "Gem først samlingen: Dens linkede design findes ud fra dens fil", + "ui.edit_in_place_save_waits": "Opdatér forbindelser kører i {name}; gem den, når den er færdig", + "ui.edit_in_place_saved_elsewhere": "Delen blev gemt i en anden fil; samlingen linker stadig til {name}", + "ui.edit_in_place_wait": "Vent, til det, der kører i designet, er færdigt", "ui.edit_section_analysis": "Redigér snitanalyse", + "ui.edit_sketch_empty": "Ingen skitser at redigere", "ui.ellipse": "Ellipse", + "ui.emboss_wrap_note": "Ortogonale linjeprofiler, der tangerer én understøttet cylinder, vikles automatisk om. Vælg en væg for at vælge et mål.", "ui.end_radius": "Slutradius", "ui.end_scale": "Skalering ved slutningen", "ui.entities": "Elementer", "ui.equal": "Ens", + "ui.equation_end": "Slut", + "ui.equation_explicit": "Eksplicit", + "ui.equation_form": "Form", + "ui.equation_note": "Variablen er et almindeligt tal: sin(t) tager den i radianer. Et resultat uden enhed er i designets enhed.", + "ui.equation_note_range": "Variablen er en længde, ligesom dens interval er det: Kombinér den med længdeparametre, og divider den med en længde for sin(). Et resultat uden enhed er i designets enhed.", + "ui.equation_parametric": "Parametrisk", + "ui.equation_variable_unit": "Variablen har intervallets enhed", + "ui.equation_x_of_t": "x(t)", + "ui.equation_y_of_t": "y(t)", + "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Ækvivalent radius", "ui.expand": "Fold ud", + "ui.explode_needs_two_components": "Eksploderet visning trækker komponenter fra hinanden, så designet skal have to eller flere af dem (Ny komponent, Indsæt design eller Opret komponenter fra emner)", "ui.exportDxf": "Eksportér DXF…", "ui.export_ellipsis_keymap": "Eksportér…", "ui.export_keymap_tip": "Gem tastaturgenveje, favoritter i S-menuen og værktøjslinjen i en fil", @@ -2012,10 +4653,12 @@ "ui.flip": "Vend", "ui.format": "Format", "ui.frame_rate": "Billedfrekvens", + "ui.frame_rate_details": "Detaljer om billedfrekvens", "ui.front": "Forfra", "ui.fully_constrained": "Fuldt bundet", "ui.function": "Funktion", "ui.general": "Generelt", + "ui.gpu_memory_lowered": "Grafikkortet er løbet tør for hukommelse: Visningen tegnes i lavere kvalitet.", "ui.graphics": "Grafik", "ui.graphics_custom": "Brugerdefineret", "ui.graphics_performance": "Ydeevne", @@ -2044,9 +4687,12 @@ "ui.heading_design": "DESIGN", "ui.heading_draft": "SLIPVINKEL", "ui.heading_edit": "REDIGÉR", + "ui.heading_equation_curve": "LIGNINGSKURVE", "ui.heading_extrude": "EKSTRUDERING", "ui.heading_fillet": "AFRUNDING", + "ui.heading_finish_editing": "AFSLUT REDIGERING", "ui.heading_finish_sketch": "AFSLUT SKITSE", + "ui.heading_form": "FORM", "ui.heading_front": "FORFRA", "ui.heading_hole": "HUL", "ui.heading_home": "HJEM", @@ -2103,41 +4749,62 @@ "ui.hideOrigin": "Skjul nulpunkt", "ui.hidePlanes": "Skjul planer", "ui.hideProfile": "Skjul profil", + "ui.hide_component_history": "Skjul dens historik", + "ui.hide_origin_by_default": "Skjul nulpunktet som standard", + "ui.hide_origin_note": "Nye designs starter med mappen Nulpunkt skjult. Et design beholder sin egen indstilling for nulpunktet, når du har vist eller skjult det.", "ui.history_back": "Gå ét trin tilbage", "ui.history_below_browser": "Under browseren", "ui.history_edge_hint": "dobbeltklik på kanten", "ui.history_first": "Gå til begyndelsen", "ui.history_forward": "Gå ét trin frem", + "ui.history_hide_hidden": "Skjul skjulte komponenter", "ui.history_hide_names": "Skjul navne", "ui.history_last": "Gå til slutningen", "ui.history_marker_tip": "Historikmarkør: Træk for at rulle modellen tilbage; nye features indsættes her", "ui.history_names": "Navne", "ui.history_play": "Afspil til slutningen", + "ui.history_play_button_hide": "Skjul afspilningsknappen", + "ui.history_play_button_show": "Vis afspilningsknappen", + "ui.history_play_finish_action": "Afslut den aktuelle handling, før historikken afspilles", + "ui.history_play_roll_back": "Flyt historikmarkøren tilbage, før du afspiller", + "ui.history_show_hidden": "Vis skjulte komponenter", "ui.history_show_names": "Vis navne", + "ui.history_sketch_listed_under": "Vises under {feature}", "ui.history_title": "Historik", "ui.history_toggle_names": "Vis eller skjul featurenavne", + "ui.history_waits_for_editor": "Fortryd, Gentag og Historik venter, indtil featureeditoren er åbnet", "ui.hole": "Hul", "ui.hole_tap_type": "Hullets gevindtype", "ui.hole_type": "Hultype", "ui.home": "Hjem", "ui.homeView": "Hjemmevisning", + "ui.horizontal_constraint": "Vandret binding", "ui.horizontal_vertical": "Vandret/lodret", "ui.import_ellipsis": "Importér…", "ui.infinite": "Uendelig", "ui.insert": "Indsæt", + "ui.insert_design.browse": "Gennemse…", + "ui.insert_design.open_designs": "Åbne designs", + "ui.insert_design.saved_file": "{name} har ændringer, der ikke er gemt, så dens gemte fil blev indsat. Gem den, og kør derefter Opdatér forbindelser for at hente ændringerne.", + "ui.insert_design.unsaved": "Ikke-gemte ændringer", "ui.inspect": "Inspicér", + "ui.instances": "Forekomster", "ui.intersect": "Fællesvolumen", "ui.isolate": "Isolér", "ui.join": "Foren", + "ui.joint_play": "▶ Afspil", + "ui.joint_stop": "■ Stop", "ui.joints": "Led", "ui.keyboard_shortcuts": "Tastaturgenveje", "ui.language": "Sprog", + "ui.lasso_select": "Lasso (træk en frihåndsløkke: Markerer det, der ligger helt indeni)", "ui.layout_compact": "Kompakt", "ui.layout_floating": "Flydende", "ui.length": "Længde", "ui.length_decimals": "Længdedecimaler", "ui.light": "Lys", "ui.line": "Linje", + "ui.line_arc_hint": "Tangentbue: Klik på buens slutpunkt. Hvil markøren på det sidste punkt igen for linjer; højreklik eller Esc for at afslutte", "ui.link_copies": "Link identiske kopier", "ui.link_copies_keep": "Behold", "ui.link_copies_link": "Link", @@ -2146,6 +4813,7 @@ "ui.loft": "Loft", "ui.look_at": "Se på", "ui.look_at_anim_desc": "Aksevisning, Se på, Hjem og Tilpas", + "ui.major_radius": "Større radius", "ui.manipulator_free_alt": "Brug også Alt/Option til at trække frit", "ui.manipulator_free_alt_tip": "Slået til: Hold Alt/Option eller Ctrl/Cmd nede, mens du trækker i pilene ved ekstrudering eller flytning, for at undgå faste værditrin. Slået fra: Kun Ctrl/Cmd.", "ui.manufacture": "Fremstilling", @@ -2175,11 +4843,18 @@ "ui.mesh_format_3mf": "3MF", "ui.mesh_format_3mf_tagged": "3MF med flademærker", "ui.mesh_format_stl": "STL", + "ui.minor_radius": "Mindre radius", "ui.mirror": "Spejling", "ui.mirror_line": "Spejlingslinje", + "ui.modifiers_either": "{first} eller {second}", "ui.move": "Flyt", "ui.multiple": "Flere", "ui.named_views": "Navngivne visninger", + "ui.nav_bridge": "Naviger med en enhedsapp på denne computer", + "ui.nav_bridge_connected": "Forbundet", + "ui.nav_bridge_port": "Port", + "ui.nav_bridge_tip": "En 3D-enheds eget program (for eksempel driveren til en hjemmebygget 3D-mus) flytter visningen over en lokal forbindelse, så musemarkøren forbliver din. SolidCraft opretter forbindelse til den på denne port, kun på denne computer.", + "ui.nav_bridge_waiting": "Venter på enhedsappen", "ui.navigation": "Navigation", "ui.needs_design": "{command}: Åbn først et design", "ui.newSketchGroup": "Ny skitsegruppe", @@ -2198,6 +4873,7 @@ "ui.one_side": "Én side", "ui.open": "Åbn", "ui.open_ends_tip": "Berører intet", + "ui.open_linked_design": "Åbn linket design", "ui.open_preferences": "Åbn indstillinger", "ui.open_recent": "Åbn seneste", "ui.operation": "Operation", @@ -2217,7 +4893,13 @@ "ui.part_size_shared": "Genopbygger delen og erstatter alle tilføjede features. Alle forekomster af komponenten opdateres.", "ui.paste": "Indsæt", "ui.path": "Bane", + "ui.pattern_object_type_tip": "Emner: massive former, der vælges i visningen eller modeltræet; hvert kopieres helt.\nFeatures: trin i historikken, f.eks. en ekstrudering eller et hul, der vælges i historikken eller på en flade, de har lavet; trinnet gentages.\nEn skitse er ingen af delene: Gentag dens kurver med skitsens eget Mønster eller Spejling, eller ekstruder den først.", "ui.pattern_on_path": "Mønster langs bane", + "ui.perforate_margin_default": "ud fra diameteren", + "ui.perforate_pitch": "Deling", + "ui.perforate_square": "Kvadratisk", + "ui.perforate_staggered": "Forskudt (60°)", + "ui.perforate_title": "PERFORÉR", "ui.perpendicular": "Vinkelret", "ui.perspective_view": "Perspektivvisning", "ui.pinToShortcuts": "Fastgør til genveje", @@ -2225,26 +4907,62 @@ "ui.pipe": "Rør", "ui.pitch": "Stigning", "ui.placement": "Placering", + "ui.placement_handles": "Placeringshåndtag", + "ui.placement_handles_tip": "Håndtag på forhåndsvisningen af en Understøtning, Skruebøsning eller Snapforbindelse: Træk i markøren for at flytte den hen over modellen, og drej den ved dens ring", "ui.plane": "Plan", "ui.plane_at_angle": "Plan i vinkel", "ui.plugins": "Plugins", "ui.plugins_desktop": "Plugins er tilgængelige i desktopappen.", "ui.plugins_empty": "Ingen plugins installeret.", + "ui.plugins_none": "Ingen plugins matcher denne søgning.", "ui.plugins_note": "Hvert plugin ligger i sin egen mappe under {path} og indeholder en plugin.json-fil. SolidCraft læser filen uden at køre kode fra mappen. Et plugin forbliver installeret, når du slår det fra.", + "ui.plugins_search": "Søg i plugins", "ui.plugins_skipped": "Kunne ikke læse {count} mapper.", "ui.plugins_version": "{version}", "ui.point": "Punkt", + "ui.point_cloud_add_filter": "Tilføj filter…", + "ui.point_cloud_auto_range": "Automatisk område", + "ui.point_cloud_color_by": "Farvelæg efter", + "ui.point_cloud_file_colors": "Filens farver", + "ui.point_cloud_filter_by": "Filtrér efter", + "ui.point_cloud_height_high": "Højeste", + "ui.point_cloud_height_low": "Laveste", + "ui.point_cloud_legend_filter": "Vist og skjult i signaturforklaringen ovenfor", + "ui.point_cloud_no_file_colors": "Filen har ingen farver", + "ui.point_cloud_pause": "Pause", + "ui.point_cloud_play": "Afspil", + "ui.point_cloud_single_color": "Én farve", + "ui.point_cloud_size": "Punktstørrelse", + "ui.point_cloud_units": "Filens enheder", "ui.point_under_the_cursor": "Punkt under markøren", "ui.points": "Punkter", "ui.polygon": "Polygon", "ui.preferences": "Indstillinger", "ui.press_a_key": "tryk på en tast…", + "ui.print_face_body_not_sent": "Den flades emne sendes ikke: føj det først til Emner", + "ui.print_face_cleared": "{body}: printflade ryddet", + "ui.print_face_input": "Printflade", + "ui.print_face_pick": "Vælg en plan flade på et massivt legeme for at gøre den til printfladen", + "ui.print_face_set": "{body}: printflade sat; Send til slicer lægger legemet på den", "ui.profile": "Profil", "ui.profile_plane": "Profilplan", "ui.profiles": "Profiler", "ui.project": "Projektér", "ui.project_face_edges_sketch": "Projektér fladekanter til nye skitser", "ui.properties": "Egenskaber", + "ui.properties.copy_matrix": "Kopiér matrix", + "ui.properties.first_moments": "Første momenter", + "ui.properties.inertia": "Inertimoment", + "ui.properties.inertia_note": "Om massecentret, i verdensakser (g·{unit}²)", + "ui.properties.inertia_unavailable": "Ikke tilgængeligt: Et emnes mesh er ikke lukket.", + "ui.properties.inertia_x": "Ixx, Ixy, Ixz", + "ui.properties.inertia_y": "Iyx, Iyy, Iyz", + "ui.properties.inertia_z": "Izx, Izy, Izz", + "ui.properties.measuring": "Måler…", + "ui.properties.measuring_bodies": "Måler… {done} af {total} emner", + "ui.properties.measuring_failed": "Målingen blev stoppet, før den var færdig.", + "ui.properties.principal_axis": "Hovedakse {number}", + "ui.properties.principal_moments": "Hovedmomenter", "ui.pull_direction": "Udtræksretning", "ui.quality": "Kvalitet", "ui.quantity": "Antal", @@ -2271,6 +4989,7 @@ "ui.render": "Rendering", "ui.renderer": "Renderingsmotor", "ui.repeat": "Gentag", + "ui.repeat_nothing": "Intet at gentage endnu: Start først et værktøj eller en dialog.", "ui.replace_with_link_done": "Kopierne er nu placeringer af det linkede design.", "ui.report_a_bug": "Rapportér en fejl", "ui.reset": "Nulstil", @@ -2280,15 +4999,22 @@ "ui.restore_defaults": "Gendan standarder", "ui.reverse_horizontal_pan_direction": "Vend vandret panoreringsretning", "ui.reverse_horizontal_pan_tip": "Vandret rulning med to fingre og tommelfingerhjulet panorerer i den modsatte retning", + "ui.reverse_trackpad_orbit_direction": "Vend retningen for rotation med pegefeltet", + "ui.reverse_trackpad_orbit_tip": "Shift med rulning med to fingre roterer visningen den anden vej", + "ui.reverse_vertical_pan_direction": "Vend retningen for lodret panorering", + "ui.reverse_vertical_pan_tip": "Lodret rulning med to fingre panorerer den anden vej", "ui.reverse_zoom_direction": "Vend zoomretning", + "ui.revolutions": "Omdrejninger", "ui.revolve": "Omdrejning", "ui.ribbon_exit": "Afslut", "ui.ribbon_labels": "Vis tekst under ikonerne på båndet", + "ui.ribbon_menus_skip_pinned": "Udelad fastgjorte kommandoer i rullemenuerne", "ui.ribbon_pin_footer": "Fastgjorte kommandoer vises på båndet. Hold musen over en række for at fastgøre eller frigøre den.", "ui.ribbon_workspace": "Arbejdsområde", "ui.right": "Fra højre", "ui.save": "Gem", "ui.save_as": "Gem som", + "ui.save_mesh_no_slicer_open": "Ingen slicer fundet: Vælg Brugerdefineret… og vælg dit slicerprogram", "ui.save_mesh_pick_bodies": "Vælg de emner, der skal gemmes", "ui.saved_to": "Gemt: {path}", "ui.sbox_pin": "Fastgør øverst i S-menuen", @@ -2296,15 +5022,20 @@ "ui.scale": "Skalering", "ui.second_rail": "Anden styrekurve", "ui.section_analysis": "Snitanalyse", + "ui.section_size": "Snittets størrelse", "ui.select": "Vælg", "ui.selectOther": "Vælg andet…", "ui.selectTangentChain": "Vælg tangentkæde", + "ui.select_all": "Vælg alle", + "ui.select_components_by_face": "Vælg komponenter (en flade vælger dens komponent)", "ui.selection": "Markering", "ui.selection_modifiers": "Taster ved markering", "ui.selection_shift_add_only": "Shift+klik tilføjer uden at fjerne", "ui.selection_shift_add_only_tip": "Slået til: Shift tilføjer til markeringen. Ctrl/Cmd tilføjer eller fjerner. Slået fra (standard): Både Shift og Ctrl/Cmd tilføjer eller fjerner.", "ui.send": "Send", + "ui.send_to_slicer_unavailable": "Send til slicer kræver desktopappen: En browser kan ikke starte et program", "ui.sent_to_slicer": "Sendt til {slicer}", + "ui.sent_to_slicer_copy": "Sendt til {slicer} som {file}, fordi den første fil stadig er åben der", "ui.sheet_gap": "Mellemrum", "ui.shell": "Udhulning", "ui.shortcut_capture_add_key": "Tilføj én almindelig tast. Escape annullerer.", @@ -2312,6 +5043,8 @@ "ui.shortcut_capture_press": "Tryk på modifikationstaster og én tast. Escape annullerer.", "ui.shortcut_capture_release": "Slip alle taster for at bekræfte. Escape annullerer.", "ui.shortcut_capture_settling": "Bekræfter genvej… Escape annullerer.", + "ui.shortcut_cycles_modes": "Hvis du trykker på et værktøjs genvej igen, skifter det tilstand", + "ui.shortcut_cycles_modes_tip": "Før det første punkt: Hvis du trykker på et skitseværktøjs genvej igen, gennemgås dets oprettelsestilstande. Fra: Værktøjet starter igen.", "ui.shortcut_multiple_keys": "Brug modifikationstaster og kun én anden tast. Klik på tastetildelingen for at prøve igen.", "ui.show": "Vis", "ui.showAll": "Vis alle", @@ -2320,6 +5053,7 @@ "ui.showDimension": "Vis mål", "ui.showOrigin": "Vis nulpunkt", "ui.showPlanes": "Vis planer", + "ui.show_component_history": "Vis dens historik", "ui.show_constraints": "Bindinger", "ui.show_construction_geometries": "Konstruktionsgeometri", "ui.show_dimensions": "Mål", @@ -2331,12 +5065,30 @@ "ui.sketch": "Skitse", "ui.sketch_dimension": "Skitsemål", "ui.sketch_grid": "Skitsegitter", + "ui.sketch_intersect_geometry": "Geometri", + "ui.sketch_intersect_projection_link": "Projektionslink", + "ui.sketch_intersect_selection_filter": "Markeringsfilter", "ui.sketch_modifiers": "Taster i skitser", + "ui.sketch_project_geometry": "Geometri", + "ui.sketch_report.all_constrained": "Alt er fuldt bundet.", + "ui.sketch_report.dof": "Frihedsgrader", + "ui.sketch_report.loose": "Ikke fuldt bundet", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Skitserapport", "ui.sketch_scale": "Skitseskalering", "ui.sketches": "Skitser", "ui.slice": "Lagdeling", "ui.slicer": "Slicer", "ui.slicer_delete_tip": "{program}\nTryk Delete for at fjerne det fra listen", + "ui.slicer_lost": "{slicer} blev startet, men kan ikke findes igen for at sende filen til den. Filen er gemt i {path}: Åbn den derfra.", + "ui.slicer_no_file": "{slicer} er klar, men der er ingen fil at sende til den.", + "ui.slicer_no_response": "{slicer} svarede ikke i tide. Filen er allerede gemt i {path}: Send den igen, når slicerprogrammet er startet.", + "ui.slicer_resend_hint": "Hvis du sender igen, erstattes den fil, som slicerprogrammet har åben.", + "ui.slicer_single_instance": "Åbn filer i en slicer, der allerede kører", + "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer og Cura indlæser filen i det vindue, der er åbent, i stedet for at starte et nyt. Andre slicere startes, som de er. PrusaSlicer 3.0 gør altid dette: Dens starter kan ikke tage en fil på nogen anden måde.", + "ui.slicer_starting": "Starter {slicer}…", + "ui.slicer_still_starting": "Venter stadig på, at {slicer} starter. Intet andet blev sendt.", + "ui.slicer_stl_fallback": "3MF-filen kunne ikke skrives, så dette er en STL.", "ui.slot": "Slids", "ui.smooth": "Glat", "ui.smooth_wheel_zoom": "Jævn zoom med musehjul", @@ -2352,6 +5104,9 @@ "ui.start": "Start", "ui.start_over": "Start forfra", "ui.start_page": "Startside", + "ui.step_values": "Trin i værdier med piletasterne og hjulet", + "ui.step_values_tip": "I et værdifelt, du skriver i, ændrer Op/Ned et almindeligt tal med 1 (Shift: 10, Alt: 0,1), og det gør musehjulet over feltet også. Udtryk bevares, som de er skrevet.", + "ui.stitch_tolerance_hint": "stram", "ui.stretch": "Stræk", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Kun når visningen står stille", @@ -2370,6 +5125,7 @@ "ui.tab_manage": "Administrér", "ui.tab_sheet_metal": "Plade", "ui.tab_view": "Visning", + "ui.tab_weldments": "Svejsning", "ui.tangent": "Tangent", "ui.taper_angle": "Konusvinkel", "ui.tapped": "Med gevind", @@ -2385,11 +5141,15 @@ "ui.tip_angle": "Spidsvinkel", "ui.to_object": "Til objekt", "ui.tool_direction": "Værktøjsretning", + "ui.toolbar_tabs_hidden": "Alle værktøjslinjefaner er skjult. Klik på + eller højreklik her for at vise en.", "ui.top": "Ovenfra", + "ui.top_diameter": "Topdiameter", + "ui.top_radius": "Topradius", "ui.torus": "Torus", "ui.total_angle": "Samlet vinkel", "ui.trackpad_pan_tip": "Rulning med to fingre panorerer; i Fusion roterer Shift + to fingre visningen. Fra: Rulning zoomer. Musehjul og knibebevægelser zoomer; tommelfingerhjulet panorerer sidelæns.", "ui.trim": "Trim", + "ui.turn_up_axis": "Drej opadgående akse", "ui.twist": "Vridning", "ui.two_finger_scroll_pans": "Rulning med to fingre panorerer", "ui.two_sides": "To sider", @@ -2406,12 +5166,46 @@ "ui.up_axis_note": "Hvilken akse der peger opad i visningerne (aksevisning, Hjem, Se på). Designs ændres ikke.", "ui.updateToCurrentView": "Opdatér til aktuel visning", "ui.upload": "Upload", + "ui.vertical_constraint": "Lodret binding", + "ui.view_angles": "Visningsvinkler", + "ui.view_angles_convention": "Grader om den opadgående akse. Krøjning 0° er visningen Forfra, 90° Fra venstre, −90° Fra højre, 180° Bagfra; stampning 90° er visningen Ovenfra; en positiv rulning drejer modellen med uret.", + "ui.view_angles_help": "Viser visningens stampning, krøjning og rulning i grader samt dens projektion under orienteringsgizmoen. Klik på visningen for at skrive eksakte vinkler.", + "ui.view_angles_lock": "Lås {axis}", + "ui.view_angles_ortho": "Orto", + "ui.view_angles_persp": "Persp", + "ui.view_angles_pitch": "Stampning", + "ui.view_angles_readout": "Stampning {pitch} · Krøjning {yaw} · Rulning {roll}", + "ui.view_angles_roll": "Rulning", + "ui.view_angles_unlock": "Lås {axis} op", + "ui.view_angles_yaw": "Krøjning", + "ui.view_angles_zero": "Sæt {axis} til 0°", "ui.view_centre": "Visningens centrum", + "ui.viewport_status_clear": "Slå {name} fra", + "ui.viewport_status_clear_hint": "Slå {name} fra · Esc", + "ui.viewport_status_edges": "{count} kanter", + "ui.viewport_status_from": "fra {direction}", + "ui.viewport_status_key": "Vis signaturforklaring for {name}", + "ui.viewport_status_minimum_radius": "Mindste radius", + "ui.viewport_status_pairs": "{count} par", + "ui.viewport_status_section_hatch": "{setting} · skravering", + "ui.viewport_status_section_plane": "Aktuelt plan", + "ui.viewport_status_section_tilted": "vippet · {offset}", + "ui.viewport_status_stripes": "{count} striber", + "ui.viewport_status_summary_clear": "Slå alt fra", + "ui.viewport_status_summary_heading": "I denne visning", + "ui.viewport_status_summary_label": "{name} og {count} flere elementer", + "ui.viewport_status_summary_more": "+{count}", + "ui.viewport_theme_follow": "Følg tema", "ui.visual_shaded_hidden_edges": "Skyggelagt med skjulte kanter", "ui.visual_shaded_with_edges": "Skyggelagt med kanter", "ui.visual_style": "Visuel stil", "ui.visual_wireframe": "Trådmodel", + "ui.wheel_zoom_speed": "Zoomhastighed med musehjul", "ui.width": "Bredde", + "ui.window_system": "Vinduessystem", + "ui.window_system_auto": "Automatisk", + "ui.window_system_wayland": "Wayland", + "ui.window_system_x11": "X11", "ui.workspace": "arbejdsområde", "ui.workspace_animation_description": "Eksploderede visninger, bevægelsesstudier og storyboards", "ui.workspace_available": "Tilgængelig", @@ -2437,10 +5231,12 @@ "update.button": "Opdatér", "update.button_version": "Opdatér til {version}", "update.check_automatically": "Søg automatisk efter opdateringer", + "update.check_for_updates": "Søg efter opdateringer", "update.check_now": "Søg nu", + "update.check_unavailable": "Søgning efter opdateringer er ikke tilgængelig for denne installation.", "update.checking": "Søger…", "update.copy": "Kopiér", - "update.dmg_opened": "Diskbilledet er åbnet og verificeret: Træk SolidCraft til Programmer, erstat den gamle kopi, og genstart SolidCraft.", + "update.dmg_opened": "Diskbilledet er åbnet og verificeret: Afslut SolidCraft, træk det nye SolidCraft til Programmer, erstat den gamle kopi, og åbn derefter SolidCraft igen.", "update.download": "Download", "update.download_open": "Download og åbn", "update.downloading": "Downloader og verificerer… {done} af {total} MB", @@ -2451,12 +5247,18 @@ "update.installed": "SolidCraft {version} er installeret. Genstart for at bruge den.", "update.installer_started": "Installationsprogrammet starter, når SolidCraft lukker.", "update.later": "Påmind mig senere", + "update.managed": "Opdatering tilgængelig: Opdatér SolidCraft i {manager}", "update.no_notes": "Der er ingen beskrivelse af denne version.", "update.package_hint": "Denne kopi kom fra en {kind}. Download den nye pakke, og installér den med:", "update.prefs_dev": "Dette er en udviklingsudgave ({version}): Den søger ikke efter opdateringer.", "update.prefs_flatpak": "Flatpak opdaterer denne kopi ({version}): Kør {command}, eller brug dit softwarecenter. SolidCraft søger ikke efter opdateringer.", "update.prefs_label": "Opdateringer", + "update.prefs_managed": "Dette er SolidCraft {version}, administreret af {manager}. En kontrol spørger GitHub om den seneste udgivelse og sender intet andet; opdatér SolidCraft i {manager}.", "update.prefs_note": "Dette er SolidCraft {version} ({kind}). En opdateringskontrol spørger GitHub om den seneste udgivelse og sender intet andet.", + "update.prefs_web": "Genindlæs siden for at få den nyeste webapp. Hvis netværket ikke er tilgængeligt, eller opdateringen ikke kan nå at blive downloadet i tide, åbnes den gemte version i stedet; en igangværende download fortsætter til næste genindlæsning.", + "update.refresh_checking": "Søger efter den nyeste udgivelse…", + "update.refresh_fallback": "Kunne ikke søge efter en nyere udgivelse; opdaterer til {version}, som blev fundet tidligere.", + "update.refresh_selected": "Opdaterer til {version}.", "update.release_page": "Åbn udgivelsesside", "update.restart": "Genstart nu", "update.restart_later": "Senere", @@ -2467,6 +5269,18 @@ "update.up_to_date": "SolidCraft er opdateret.", "update.update_now": "Opdatér nu", "update.you_have": "Du har {version}.", + "use a positive nominal diameter and a pitch smaller than it": "brug en positiv nominel diameter og en stigning, der er mindre end den", + "values must be finite numbers": "værdierne skal være endelige tal", + "values must be numbers or expressions": "værdierne skal være tal eller udtryk", + "view.auto_ortho_faces": "Perspektiv under rotation, ortografisk på flader", + "view.render_inspector": "Renderingsinspektør", + "web.files.insert_drawings_hint": "CAD-filer, meshes, DXF eller SVG ind i det åbne design", + "web.files.insert_stored_drawings_hint": "Ind i det åbne design (CAD-filer, meshes, DXF, SVG)", + "web.open_full": "Åbn i SolidCraft", + "web.open_link": "Åbn linket design?", + "web.open_link_confirm": "Der er ændringer, som ikke er gemt. Skal det linkede design åbnes i en ny fane?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ vælg · Enter / Tab udfyld · Esc luk", - "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ vælg · Enter anvender det indtastede · Esc lukker" + "↑ ↓ choose · Enter applies this value": "↑ ↓ vælg · Enter anvender denne værdi", + "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ vælg · Enter anvender det indtastede · Esc lukker", + "⌘Enter continues on GitHub.": "⌘Enter fortsætter på GitHub." } diff --git a/assets/locales/de.json b/assets/locales/de.json index ac0cecc52..fb18fc1f3 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -60,8 +60,10 @@ "BLEND SURFACE": "ÜBERGANGSFLÄCHE", "BOUNDARY SURFACE": "BERANDUNGSFLÄCHE", "BROWSER": "BROWSER", + "Back to the original order": "Zurück zur ursprünglichen Reihenfolge", "Ball": "Kugelgelenk", "Bar": "Flachstab", + "Base Center": "Mittelpunkt der Basis", "Base Height": "Sockelhöhe", "Bend": "Biegung", "Bend Edges": "Biegekanten", @@ -205,6 +207,7 @@ "Edges": "Kanten", "Edit": "Bearbeiten", "Edit Profile Sketch": "Profile-Skizze bearbeiten", + "Edit shortcuts": "Tastenkürzel bearbeiten", "Enable rule": "Regel aktivieren", "Enabled": "Aktiviert", "End Radius": "Endradius", @@ -259,6 +262,8 @@ "Flanges": "Flansche", "Flat Pattern": "Flachmuster", "Flat size": "Abwicklungsgröße", + "Flat size X": "Abwicklungsmaß X", + "Flat size Y": "Abwicklungsmaß Y", "Follow camera (Look At sketches)": "Kamera folgen (Skizzen ansehen)", "Follow the camera (Look At sketches)": "Der Kamera folgen (Skizzen ansehen)", "Font": "Schriftart", @@ -290,6 +295,7 @@ "Horiz./Vert.": "Horiz./Vert.", "I-Beam": "I-Träger", "IMAGES": "BILDER", + "If you are offline or GitHub does not open, use Copy report and keep the text to submit later.": "Wenn Sie offline sind oder GitHub nicht geöffnet werden kann, verwenden Sie „Bericht kopieren“ und bewahren Sie den Text auf, um ihn später einzureichen.", "Import material into design": "Material ins Design importieren", "Import…": "Importieren…", "In This Design": "In diesem Design", @@ -373,7 +379,7 @@ "Move Type": "Verschiebungstyp", "Move down": "Nach unten", "Move earlier": "Nach vorn verschieben", - "Move holes by clicking or dragging": "Bohrungen durch Anklicken oder Ziehen verschieben", + "Move holes by clicking or dragging": "Durch Klicken oder Ziehen verschieben", "Move later": "Nach hinten verschieben", "Move up": "Nach oben", "Name": "Name", @@ -400,13 +406,16 @@ "Of": "Freiheitsgrad", "On your computer": "Auf diesem Computer", "Opacity": "Deckkraft", + "Open GitHub": "GitHub öffnen", "Open GitHub draft": "GitHub-Entwurf öffnen", + "Open GitHub issue form": "GitHub-Issueformular öffnen", "Open bodies (no volume)": "Offene Körper (ohne Volumen)", "Open library...": "Bibliothek öffnen...", "Open local libraries in the desktop app. You can export this design's library here.": "Öffnen Sie lokale Bibliotheken in der Desktop-App. Die Bibliothek dieses Designs können Sie hier exportieren.", "Open surface — no volume": "Offene Oberfläche – kein Volumen", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Quelloffenes parametrisches 3D-CAD in Rust. Lizenziert unter MIT OR Apache-2.0.", "Opens your browser and copies the report text for you to paste into GitHub.": "Öffnet den Browser und kopiert den Berichtstext, den Sie anschließend auf GitHub einfügen können.", + "Opens your browser and copies the report text. Review and submit your report on GitHub.": "Öffnet den Browser und kopiert den Berichtstext. Prüfen Sie den Bericht und reichen Sie ihn anschließend auf GitHub ein.", "Opens your browser. Review and submit your report on GitHub.": "Öffnet den Browser. Prüfen Sie den Bericht und reichen Sie ihn auf GitHub ein.", "Operator": "Operator", "Orbit (right drag)": "Drehen (mit rechts ziehen)", @@ -461,12 +470,14 @@ "Radius": "Radius", "Radius Fit": "Radiusanpassung", "Ratio": "Verhältnis", + "Read-only list: shortcuts can't be changed here.": "Schreibgeschützte Liste: Tastenkürzel können hier nicht geändert werden.", "Reattach selected face": "Ausgewählte Fläche neu anbinden", "Recover": "Wiederherstellen", "Recover unsaved design?": "Nicht gespeichertes Design wiederherstellen?", "Rectangular": "Rechteckig", "Rectangular Tube": "Rechteckrohr", "Reference face": "Referenzfläche", + "Reference plane": "Referenzebene", "Relief Depth": "Freistellungstiefe", "Relief Width": "Freistellungsbreite", "Remove Tools": "Werkzeuge entfernen", @@ -484,9 +495,11 @@ "Rename Folder": "Ordner umbenennen", "Render Stage": "Renderphase", "Reopen designs": "Designs erneut öffnen", - "Reopen the designs that were open when SolidCraft was last closed": "Die Designs erneut öffnen, die beim letzten Beenden von SolidCraft geöffnet waren", + "Reopen the designs that were open when SolidCraft was last closed": "Die zuletzt geöffneten Entwürfe erneut öffnen", + "Repair Part": "Teil reparieren", "Replace existing library file": "Vorhandene Bibliotheksdatei ersetzen", "Report a bug — review a screenshot and open a GitHub draft": "Fehler melden — Screenshot prüfen und einen GitHub-Entwurf öffnen", + "Report copied. Keep this text to submit on GitHub when you are online.": "Bericht kopiert. Bewahren Sie diesen Text auf, um ihn auf GitHub einzureichen, sobald Sie online sind.", "Report text copied. Paste it into GitHub and submit your report there.": "Berichtstext kopiert. Fügen Sie ihn auf GitHub ein und reichen Sie den Bericht dort ein.", "Reports are public. A GitHub account is required.": "Berichte sind öffentlich. Ein GitHub-Konto ist erforderlich.", "Reset Toolbar": "Symbolleiste zurücksetzen", @@ -545,6 +558,7 @@ "Section": "Schnitt", "Section (optional)": "Abschnitt (optional)", "Section position": "Lage des Querschnitts", + "Sections": "Querschnitte", "Sections (one sketch each)": "Querschnitte (je eine Skizze)", "Select Other": "Andere auswählen", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Anderes auswählen: Halten Sie die linke Taste ruhig auf dem Modell gedrückt (oder Rechtsklick › Anderes auswählen…), um alles unter dem Cursor aufzulisten; klicken Sie erneut an dieselbe Stelle, um das nächste Element dort auszuwählen. Doppelklick mit der mittleren Taste wechselt zur Startansicht (Einstellungen › Navigation).", @@ -571,7 +585,7 @@ "Show ghost": "Geistermodell anzeigen", "Show in folder": "Im Ordner anzeigen", "Show the pointer an AI agent moves (#35)": "Den Zeiger anzeigen, den ein KI-Agent bewegt (#35)", - "Show tool at cursor": "Werkzeug am Cursor anzeigen", + "Show tool at cursor": "Werkzeug am Mauszeiger", "Signed axes": "Vorzeichenbehaftete Achsen", "Size": "Größe", "Sketch constraints": "Skizzenbedingungen", @@ -582,8 +596,11 @@ "Sketch points": "Skizzenpunkte", "Slider": "Schubgelenk", "Slot width": "Langlochbreite", - "Snap to face and edge centres": "An Flächen- und Kantenmittelpunkten einrasten", + "Snap to face and edge centres": "An Mittelpunkten einrasten", + "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft kann Berichte nicht direkt einreichen. Reichen Sie Ihren Bericht auf GitHub ein. In der App wird dafür kein Token benötigt.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft wurde beendet, bevor diese Designs gespeichert wurden. Ihr letzter Autosave kann geöffnet werden.", + "Sort A to Z": "Von A bis Z sortieren", + "Sort Z to A": "Von Z bis A sortieren", "Spacing 2 must be a non-zero number": "Abstand 2 muss eine Zahl ungleich null sein", "Spacing must be a non-zero number": "Der Abstand muss eine Zahl ungleich null sein", "Specialise": "Spezialisieren", @@ -643,6 +660,7 @@ "Third point": "Dritter Punkt", "This child is shared. Deleting it removes it from every copy of its parent.": "Dieses untergeordnete Element ist geteilt. Löschen entfernt es aus jeder Kopie des übergeordneten Elements.", "This child is shared. Position changes apply to every copy of its parent.": "Dieses untergeordnete Element ist geteilt. Positionsänderungen gelten für jede Kopie des übergeordneten Elements.", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "Diese Komponente gehört zu einer Unterbaugruppe, die mehrfach platziert wurde. Beim Ausrichten wird sie an allen Platzierungen verschoben.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Diese Fläche kann keine dauerhafte Anbindung bieten. Wählen Sie eine andere Fläche oder verwenden Sie ausdrücklich eine feste Ebene.", "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "Dieses Bild wurde noch nicht an GitHub angehängt. Kopieren oder speichern Sie es und fügen Sie es anschließend Ihrem GitHub-Bericht hinzu.", "Thread depth": "Gewindetiefe", @@ -721,36 +739,36 @@ "a picked edge's body is gone": "der Körper einer gewählten Kante existiert nicht mehr", "add a key for a joint first": "zuerst einen Schlüssel für ein Gelenk hinzufügen", "ai.connected_toast": "SolidCraft ist jetzt in {clients} verfügbar. Starten Sie diese neu, um es zu nutzen (Einstellungen > Assistent).", - "ai.prefs.allow_control": "Verbindungen von KI-Agenten zulassen (Steuerkanal / MCP)", - "ai.prefs.allow_control_note": "Öffnet einen Steuerkanal nur auf diesem Computer (127.0.0.1, Port 27878 oder der nächste freie). Ein verbindendes Programm muss zusätzlich ein geheimes Token vorweisen, das nur Ihr Benutzerkonto lesen kann und bei jedem Start neu erzeugt wird. Wirkt ab dem nächsten Start von SolidCraft. Aus: Es wartet nichts auf Verbindungen, außer Sie starten SolidCraft mit --control.", - "ai.prefs.availability": "Assistenten-Steuerung", - "ai.prefs.background_commands": "Agentenbefehle im Hintergrund ausführen", - "ai.prefs.connect_apps": "SolidCraft für KI-Apps auf diesem Computer verfügbar machen", - "ai.prefs.connect_apps_note": "Trägt SolidCraft beim Start als MCP-Server in die auf diesem Computer gefundenen KI-Apps ein (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), damit ein Agent es ohne Einrichtung nutzen kann. Nur der Eintrag „solidcraft“ wird hinzugefügt oder sein Pfad aktualisiert; ein von Ihnen geänderter Eintrag bleibt unberührt, und die Datei wird vorher gesichert. Aus: Die hinzugefügten Einträge werden entfernt. Hilfe > KI-Assistenten verbinden… erledigt das von Hand.", - "ai.prefs.connect_at_start": "Zuletzt verwendeten Agenten beim Start von SolidCraft verbinden", + "ai.prefs.allow_control": "KI-Agenten verbinden lassen", + "ai.prefs.allow_control_note": "Ein lokaler Kanal (MCP). Nichts verlässt diesen Computer.\n\nÖffnet einen Steuerkanal nur auf diesem Computer (127.0.0.1, Port 27878 oder der nächste freie). Ein verbindendes Programm muss zusätzlich ein geheimes Token vorweisen, das nur Ihr Benutzerkonto lesen kann und bei jedem Start neu erzeugt wird. Wirkt ab dem nächsten Start von SolidCraft. Aus: Es wartet nichts auf Verbindungen, außer Sie starten SolidCraft mit --control.", + "ai.prefs.availability": "Verfügbarkeit", + "ai.prefs.background_commands": "Langsame Befehle im Hintergrund ausführen", + "ai.prefs.connect_apps": "SolidCraft zu KI-Apps hinzufügen", + "ai.prefs.connect_apps_note": "Aus entfernt die Einträge wieder.\n\nTrägt SolidCraft beim Start als MCP-Server in die auf diesem Computer gefundenen KI-Apps ein (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), damit ein Agent es ohne Einrichtung nutzen kann. Nur der Eintrag „solidcraft“ wird hinzugefügt oder sein Pfad aktualisiert; ein von Ihnen geänderter Eintrag bleibt unberührt, und die Datei wird vorher gesichert. Aus: Die hinzugefügten Einträge werden entfernt. Hilfe > KI-Assistenten verbinden… erledigt das von Hand.", + "ai.prefs.connect_at_start": "Letzten Agenten beim Start verbinden", "ai.prefs.connect_at_start_note": "Verbindet beim Start von SolidCraft automatisch den zuletzt verwendeten Agenten (oder den Standardagenten) im Hintergrund, damit er für den Chat bereitsteht. Diese Funktion ist deaktiviert, wenn SolidCraft mit --control gestartet wird. Kann keine Verbindung hergestellt werden, zeigt der Assistent „Verbindung fehlgeschlagen“ und eine Schaltfläche zum erneuten Verbindungsversuch an.", - "ai.prefs.follow_camera": "Kamera zu Skizzen drehen", + "ai.prefs.follow_camera": "Der Kamera folgen", "ai.prefs.follow_camera_off": "Die automatische Kameraführung ist aus.", "ai.prefs.follow_camera_on": "Die Kamera dreht sich zu Skizzen, die der Agent erstellt.", - "ai.prefs.intro": "Agenten, Berechtigungen und wie ihre Arbeit angezeigt wird.", - "ai.prefs.make_default": "Standardmäßig verwenden", + "ai.prefs.intro": "KI-Agenten in SolidCraft.", + "ai.prefs.make_default": "Als Standard festlegen", "ai.prefs.no_agents": "Noch keine Agenten. Fügen Sie einen Agenten hinzu oder aktualisieren Sie, um installierte Agenten zu finden.", "ai.prefs.no_saved_approvals": "Keine gespeicherten Freigaben.", - "ai.prefs.open_at_start": "Assistentenbereich beim Start von SolidCraft öffnen", + "ai.prefs.open_at_start": "Chat beim Start öffnen", "ai.prefs.open_at_start_note": "Öffnet beim Start von SolidCraft automatisch den Assistentenbereich oder dessen separates Fenster. Diese Funktion ist deaktiviert, wenn SolidCraft mit --control gestartet wird.", "ai.prefs.override_all_warning": "Dieser Agent darf das Design ohne Rückfrage speichern, überschreiben, exportieren oder ersetzen.", - "ai.prefs.permission_all": "Alles erlauben", - "ai.prefs.permission_all_summary": "Verfügbare SolidCraft-Werkzeuge werden ohne Rückfrage ausgeführt.", - "ai.prefs.permission_ask": "Vor Änderungen fragen", - "ai.prefs.permission_ask_summary": "Jede Designänderung und Dateiaktion bestätigen.", - "ai.prefs.permission_edits": "Modelländerungen erlauben", - "ai.prefs.permission_edits_summary": "Modelländerungen werden ohne Rückfrage ausgeführt; Datei- und destruktive Aktionen fragen weiterhin nach.", + "ai.prefs.permission_all": "Alles ausführen", + "ai.prefs.permission_all_summary": "Fragt nie nach", + "ai.prefs.permission_ask": "Zuerst fragen", + "ai.prefs.permission_ask_summary": "Fragt bei jeder Änderung", + "ai.prefs.permission_edits": "Änderungen vornehmen", + "ai.prefs.permission_edits_summary": "Ändert frei, fragt beim Rest", "ai.prefs.permission_scope": "Gilt nur für SolidCraft-Werkzeuge. Shell und Dateiänderungen des Agenten unterliegen dessen eigenen Berechtigungen.", "ai.prefs.pointer_preview_hidden": "Zeiger ausgeblendet", "ai.prefs.pointer_preview_speed": "Agentenzeiger · {speed}", - "ai.prefs.pointer_speed": "Bewegungsgeschwindigkeit", + "ai.prefs.pointer_speed": "Geschwindigkeit", "ai.prefs.privacy_note": "Die Unterhaltung geht nur an den von Ihnen gewählten Agenten oder API-Endpunkt. API-Schlüssel werden im Schlüsselbund des Systems gespeichert.", - "ai.prefs.show_pointer": "Agentenzeiger anzeigen", + "ai.prefs.show_pointer": "Zeiger des Agenten anzeigen", "ai.prefs.turn_limit_hint": "Höchstzahl designändernder Werkzeugaufrufe, die der Assistent für eine Nachricht ausführen darf.", "angle, height": "Winkel, Höhe", "appearance.dielectric_ior": "Brechungsindex des Dielektrikums", @@ -763,6 +781,8 @@ "at the face": "an der Fläche", "bom.group_children": "Unterteile in der Zeile ihres Teils", "browser.body_name": "Körper {number}", + "browser.calibrate_click_a": "Klicken Sie im Bild auf die Position von Punkt A oder geben Sie dessen Koordinaten ein.", + "browser.calibrate_click_b": "Klicken Sie im Bild auf die Position von Punkt B oder geben Sie dessen Koordinaten ein.", "browser.calibrate_title": "Kalibrieren: {name}", "browser.capture_many": "{count} Komponenten wurden verschoben, ihre Positionen sind aber nicht erfasst.", "browser.capture_note": "„Position erfassen“ behält die neue Position bei; „Position zurücksetzen“ stellt die vorherige wieder her.", @@ -771,11 +791,19 @@ "browser.edit_canvas_title": "Leinwand bearbeiten: {name}", "browser.edit_point_cloud_title": "Punktwolke bearbeiten: {name}", "browser.move_title": "Verschieben: {name}", + "browser.needs_repair": "{name}: muss repariert werden", "browser.parameters": "Parameter ({count})", "browser.precision": "Genauigkeit: {precision}", "browser.sketch_attachment_lost": "{name} (Bezug verloren)", "browser.sketch_editing": "{name} (in Bearbeitung)", "browser.sketch_name": "Skizze {number}", + "browser.sketches_to_parts_already_in_part": "bereits in ihrem Teil", + "browser.sketches_to_parts_design_body": "auf einem Körper des Designs selbst", + "browser.sketches_to_parts_moved": "{moved} Skizzen in das Teil verschoben, auf dem sie liegen", + "browser.sketches_to_parts_no_exact_attachment": "auf einer Fläche ohne exakte Anbindung", + "browser.sketches_to_parts_not_on_face": "nicht auf der Fläche eines Teils", + "browser.sketches_to_parts_part_missing": "ihr Teil gibt es nicht mehr", + "browser.sketches_to_parts_result": "{moved} Skizzen in das Teil verschoben, auf dem sie liegen; {stayed} geblieben: {why}", "browser.units": "Einheiten: {units}", "cam.flat": "Flachstößel", "cam.follower": "Stößel", @@ -787,6 +815,8 @@ "camera.shot_pitch": "Nickwinkel", "camera.shot_roll": "Rollwinkel", "camera.shot_yaw": "Gierwinkel", + "canvas.decal_place_hint": "Klicken Sie auf eine Fläche, um das Dekal zu platzieren.", + "canvas.place_hint": "Klicken Sie auf eine Ebene oder Fläche, um die Zeichenfläche zu platzieren.", "choose a profile": "ein Profil wählen", "choose the cam's and the follower's joints": "die Gelenke von Nocken und Stößel wählen", "choose the joints to couple": "die zu koppelnden Gelenke wählen", @@ -805,7 +835,10 @@ "cmd.assembly_bom": "Stückliste", "cmd.assembly_bom_item_set": "Positionsnummer ändern", "cmd.assembly_bom_renumber": "Positionen neu nummerieren", + "cmd.assembly_mass_properties": "Masseeigenschaften", + "cmd.body.print_face": "Auflagefläche", "cmd.body_rename": "Körper umbenennen", + "cmd.body_repair": "Teil reparieren", "cmd.browser_collapse_all": "Alles einklappen", "cmd.browser_expand_all": "Alles ausklappen", "cmd.browser_group": "Neue Gruppe", @@ -841,6 +874,8 @@ "cmd.component_move_bodies": "Körper in Komponente verschieben", "cmd.component_move_features": "Merkmale in Komponente verschieben", "cmd.component_move_sketches": "Skizzen in Komponente verschieben", + "cmd.component_move_sketches_to_parts": "Skizzen in ihre Teile verschieben", + "cmd.component_paste_from_design": "Aus einem anderen Design einfügen", "cmd.component_paste_new": "Neu einfügen", "cmd.component_properties": "Physikalische Eigenschaften der Komponente", "cmd.component_relink": "Quelle neu verknüpfen", @@ -857,6 +892,7 @@ "cmd.config_rule": "Konfigurationsregel", "cmd.config_rules": "Konfigurationsregeln", "cmd.config_table": "Konfigurationstabelle anzeigen", + "cmd.construct.plane.axis_point": "Ebene durch Achse und Punkt", "cmd.construct_axis_edge": "Achse durch Kante", "cmd.construct_axis_normal_to_face": "Achse senkrecht zur Fläche", "cmd.construct_axis_through_cylinder": "Achse durch Zylinder/Kegel/Torus", @@ -885,6 +921,8 @@ "cmd.diagnostics_crash_reports": "Absturzberichte", "cmd.diagnostics_crash_reports_clear": "Absturzberichte löschen", "cmd.diagnostics_crash_test": "Absturztest", + "cmd.diagnostics_profile": "Profil", + "cmd.diagnostics_validation": "Prüfung", "cmd.doc_recover": "Konstruktion wiederherstellen", "cmd.doc_recovery_discard": "Wiederhergestellte Konstruktion verwerfen", "cmd.doc_recovery_list": "Wiederherstellbare Konstruktionen", @@ -905,6 +943,11 @@ "cmd.explode_show": "Explosionsdarstellung anzeigen", "cmd.expr_evaluate": "Ausdruck auswerten", "cmd.face_delete": "Fläche löschen", + "cmd.file.export_3mf": "Als 3MF exportieren", + "cmd.file.export_obj": "Als OBJ exportieren", + "cmd.file.export_step": "Als STEP exportieren", + "cmd.file.export_stl": "Als STL exportieren", + "cmd.file.export_urdf": "Als URDF exportieren", "cmd.file_export": "Exportieren", "cmd.file_insert_mesh": "Netz einfügen", "cmd.file_insert_step": "STEP einfügen", @@ -951,6 +994,11 @@ "cmd.joint_screw": "Schraube", "cmd.joint_solve": "Gelenke lösen", "cmd.joint_sweep": "Gelenk bis zum Kontakt durchfahren", + "cmd.layout.apply": "Layout anwenden", + "cmd.layout.get": "Layout prüfen", + "cmd.layout.reset": "Layout zurücksetzen", + "cmd.layout.save": "Layout speichern", + "cmd.layout.workspace.select": "Layout-Arbeitsbereich auswählen", "cmd.library_apply": "Lokalen Bibliothekseintrag anwenden", "cmd.library_export": "Designbibliothek exportieren", "cmd.library_inspect": "Lokale Bibliothek prüfen", @@ -977,6 +1025,7 @@ "cmd.motion_trace": "Bewegungsbahn", "cmd.motion_trace_edit": "Bewegungsbahn bearbeiten", "cmd.motion_trace_keep": "Bewegungsbahn behalten", + "cmd.occurrence_align": "Instanz ausrichten", "cmd.occurrence_bom_type": "Stücklistentyp", "cmd.occurrence_copy": "Einfügen (Instanz)", "cmd.occurrence_drag": "Instanz ziehen", @@ -984,6 +1033,21 @@ "cmd.occurrence_move": "Instanz verschieben", "cmd.occurrence_properties": "Physikalische Eigenschaften der Instanz", "cmd.occurrence_reparent": "In andere Komponente verschieben", + "cmd.panel.activate": "Panel-Registerkarte aktivieren", + "cmd.panel.close": "Panel schließen", + "cmd.panel.collapse": "Panel-Bereich einklappen", + "cmd.panel.dismiss": "Panel-Vorschau schließen", + "cmd.panel.float": "Panel frei platzieren", + "cmd.panel.focus": "Panel fokussieren", + "cmd.panel.list": "Panels auflisten", + "cmd.panel.move": "Panel verschieben", + "cmd.panel.native_close": "Nativen Panel-Bereich wieder andocken", + "cmd.panel.open": "Panel öffnen", + "cmd.panel.peek": "Eingeklapptes Panel anzeigen", + "cmd.panel.popout": "Panel in eigenes Fenster verschieben", + "cmd.panel.reset_pair": "Panel-Trennlinie zurücksetzen", + "cmd.panel.resize": "Panel-Bereich skalieren", + "cmd.panel.resize_pair": "Panel-Trennlinie verschieben", "cmd.parameters_add": "Benutzerparameter hinzufügen", "cmd.parameters_change": "Parameter ändern", "cmd.parameters_comment": "Parameter kommentieren", @@ -1012,6 +1076,9 @@ "cmd.pointcloud_edit": "Punktwolke bearbeiten", "cmd.pointcloud_insert": "Punktwolke einfügen", "cmd.pointcloud_list": "Punktwolken", + "cmd.render.compare.divider": "Render-Vergleichstrenner verschieben", + "cmd.render.result.discard": "Renderergebnis verwerfen", + "cmd.render.result.select": "Renderergebnis auswählen", "cmd.render_aging_describe": "Mehrschichtige Oberflächenalterung", "cmd.render_backends": "Render-Backends", "cmd.render_batch": "Alle Aufnahmen rendern", @@ -1175,6 +1242,7 @@ "cmd.sketch_spline_control_point_5": "Spline mit Kontrollpunkten (Grad 5)", "cmd.sketch_spline_fit_point": "Spline mit Fitpunkten", "cmd.sketch_spline_insert_point": "Splinepunkt hinzufügen", + "cmd.sketch_spline_remove_point": "Splinepunkt entfernen", "cmd.sketch_spline_reverse": "Splinerichtung umkehren", "cmd.sketch_spun_profile": "Gedrehtes Profil", "cmd.sketch_toggle_diameter": "Radius / Durchmesser umschalten", @@ -1225,9 +1293,11 @@ "cmd.timeline_rollback": "Zeitleistenmarkierung verschieben", "cmd.timeline_stop": "Verlauf anhalten", "cmd.timeline_suppress": "Merkmal unterdrücken", + "cmd.ui.assistant": "Assistenten ein-/ausblenden", "cmd.view.render_browser": "Render-Browser", "cmd.view.render_dock": "Render-Panel verschieben", "cmd.view.render_focus": "Render-Fokusansicht", + "cmd.view.status_details": "Statusdetails des Ansichtsfensters", "cmd.view.status_items": "Ansichtsstatus-Elemente", "cmd.view_ambient_occlusion": "Umgebungsverdeckung", "cmd.view_angle_readout": "Ansichtswinkel", @@ -1258,17 +1328,28 @@ "cmd.view_tool": "Navigationswerkzeug", "cmd.view_top": "Draufsicht", "cmd.view_visual_style": "Darstellungsstil", + "color.blue": "Blau", "color.copy": "Klicken, um Farbwerte zu kopieren", "color.edit": "Klicken, um Farbe zu bearbeiten", "color.gamma": "Farbwerte im Gammaraum 0-255 anzeigen", + "color.green": "Grün", "color.hex": "Hex", "color.hex_help": "#rrggbb oder #rrggbbaa eingeben; sechs Ziffern behalten die Deckkraft bei", "color.hex_hint": "#rrggbb", "color.hue": "Farbton", "color.linear": "Farbwerte im linearen Raum 0-1 anzeigen", + "color.recent": "Zuletzt verwendete Farben", + "color.recent_help": "Farben, die Sie in einem beliebigen Farbfeld wählen, erscheinen hier", + "color.red": "Rot", + "color.saturation": "Sättigung (Prozent)", "color.saturation_value": "Sättigung und Wert", "color.selected": "Ausgewählte Farbe", + "color.step_down": "Schritt nach unten", + "color.step_up": "Schritt nach oben", + "color.value": "Hellwert (Prozent)", "config.column_filter_empty": "Keine passenden Spalten", + "config.rule_parameter_columns": "Hier stehen nur Parameter mit einer Spalte in der Tabelle. Fügen Sie eine mit „Spalte hinzufügen“ (+) hinzu, um den Parameter hier zu verwenden.", + "config.rule_suppression_columns": "Hier stehen nur Funktionen mit einer Spalte „Unterdrücken“ in der Tabelle. Fügen Sie eine mit „Spalte hinzufügen“ (+) hinzu, um die Funktion hier zu steuern.", "contact.components_count": "{count} Komponenten", "contact.enabled_label": "aktiviert", "coupling.gear_1": "Zahnrad 1", @@ -1303,6 +1384,7 @@ "crash.unclean_explanation": "Beim späteren Start erkannt; der genaue Zeitpunkt des Beendens wurde nicht aufgezeichnet. Auch ein Herunterfahren des Systems oder ein erzwungener Stopp kann ein unsauberes Beenden verursachen.", "delete.and_more": "… und {count} weitere", "diagnostic.empty_boolean_component": "In Komponente '{component}' gibt es keinen Körper zum Abziehen oder für eine Schnittmenge; das Werkzeug überschneidet sich eventuell mit '{body}' in Komponente '{other}' – aktivieren Sie diese Komponente oder wählen Sie den Körper als Ziel", + "diagnostic.reselect_reference": "{feature}: Die Referenz `{reference}` existiert nicht mehr so, wie sie ausgewählt wurde; wählen Sie sie erneut aus", "dialog.bodies_count": "{count} Körper", "dialog.clearance_invalid": "der Abstand muss eine Länge von 0 oder mehr sein", "dialog.compute": "Berechnen", @@ -1312,10 +1394,19 @@ "dialog.custom_axis": "↖ Eigene Achse", "dialog.dimension_insert_hint": "Doppelklicken Sie auf eine andere steuernde Bemaßung, um ihren Namen einzufügen", "dialog.dimension_name": "Bemaßung: {name}", + "dialog.dimension_step_down": "Um {step} verringern", + "dialog.dimension_step_expression": "Nur eine Zahl lässt sich schrittweise ändern; ein Ausdruck bleibt, wie er eingegeben ist", + "dialog.dimension_step_up": "Um {step} erhöhen", "dialog.edit_title": "{title} bearbeiten", + "dialog.no_shown_body": "Kein sichtbarer Körper zum Ändern vorhanden. Blenden Sie einen Körper ein oder wählen Sie „Neuer Körper“.", + "dialog.pattern_sketch_not_object": "Körper oder Funktionen wählen: Eine Skizze ist keines von beiden. Ihre Kurven mit Muster oder Spiegeln in der Skizze wiederholen oder sie zuerst extrudieren.", "dialog.select": "↖ Auswählen", "dialog.selected_count": "↖ {count} ausgewählt", + "dialog.selection_constraint": "Bedingung {id}", + "dialog.selection_external_curve": "{sketch} · Kurve {id}", "dialog.selection_guidance": "Wählen Sie eine Eingabe aus, um sie zu ändern. Klicken Sie auf ausgewählte Objekte, um sie zu entfernen; Strg/Cmd-Klick schaltet sie ebenfalls um. Prüfen Sie die Vorschau und drücken Sie dann OK.", + "dialog.selection_midpoint": "Mittelpunkt · {id}", + "dialog.selection_profile": "{sketch} · Profil {number}", "dialog.selection_step": "{step} von {total}: {input} auswählen", "dialog.step": "Schritt", "document.changed_on_disk": "{name} wurde auf dem Datenträger geändert", @@ -1330,6 +1421,7 @@ "document.read_only_save": "Dieses Design wurde schreibgeschützt geöffnet: Speichern Sie es als neue Datei", "document.save_changes": "Änderungen in {name} speichern?", "document.save_copy": "Kopie speichern…", + "document.tab_unsaved_changes": "Ungespeicherte Änderungen", "document.unsaved_changes": "{name} enthält ungespeicherte Änderungen. Wenn Sie nicht speichern, gehen sie verloren.", "drive.rigid": "{joint} ist ein starres Gelenk. Es hält die verbundenen Teile fest zusammen und ermöglicht daher keine Bewegung. Um die Teile beweglich zu machen, ändern Sie den Gelenktyp unter „Gelenk bearbeiten“: Drehgelenk für Drehbewegungen, Schubgelenk für lineare Bewegungen oder Zylindergelenk für beides.", "drive.stopped_by_contact": "Angehalten bei {value}: {a} würde {b} durchdringen", @@ -1362,6 +1454,14 @@ "file_load.reading_percent": "Datei wird gelesen... {percent} %", "file_load.rebuilding": "Merkmal {done} von {total} wird neu aufgebaut", "file_load.recovering": "Design wird wiederhergestellt", + "file_load.step_build": "Modell wird aufgebaut", + "file_load.step_feature": "Merkmal {done} von {total}", + "file_load.step_part": "Teil {done} von {total}", + "file_load.step_percent": "{percent} %", + "file_load.step_read": "Datei wird gelesen", + "file_load.step_rebuild": "Merkmale werden neu aufgebaut", + "file_load.step_repair": "Teile werden geprüft und repariert", + "file_load.step_show": "Ansicht wird vorbereitet", "file_load.stopping": "Warten, bis der vorherige Vorgang beendet ist...", "file_load.updating_links": "Verknüpfungen werden aktualisiert", "file_load.waiting": "Warten auf Dateivorgang", @@ -1369,17 +1469,190 @@ "from the profile": "aus dem Profil", "from the rule": "aus der Regel", "help.apache": "Apache-Lizenz 2.0", + "help.appearance.assign": "Weist den ausgewählten Körpern, Flächen oder Komponenten eine Farbe oder ein Erscheinungsbild zu, ohne ihre Masse zu verändern. So können Sie Bauteile optisch unterscheiden oder das Aussehen einer Oberfläche vorab prüfen.", + "help.assembly.bom": "Listet die Teile des Designs oder einer Komponente mit ihrer Anzahl nach Teilenummer auf und kann die Liste als CSV oder JSON speichern. Als Stückliste für Bestellung und Montage.", "help.attributions": "Quellenangaben (ATTRIBUTION.md)", "help.build": "Version {version} · Commit {commit} · erstellt am {date}", + "help.canvas.decal": "Bringt ein Bild wie einen Aufkleber auf eine ebene Fläche des Modells. Damit zeigen Sie ein Etikett, ein Logo oder einen Aufdruck auf einem Teil.", + "help.canvas.edit": "Ändert eine Zeichenfläche: Lage, Größe, Winkel, Deckkraft, Spiegelung, Sichtbarkeit oder Namen. Damit richten Sie ein Referenzbild an der Skizze aus, die Sie darüber nachzeichnen.", + "help.canvas.insert": "Legt ein PNG- oder JPEG-Bild als durchscheinende Referenz auf eine Ebene oder Fläche. Damit zeichnen Sie ein Foto oder eine Zeichnung in einer Skizze nach, mit dem Bild auf eine bekannte Größe skaliert.", + "help.component.break_link": "Löst eine verknüpfte Komponente von ihrer Konstruktionsdatei und behält ihre Körper unverändert. Damit folgt das Teil Änderungen an der Originaldatei nicht mehr.", + "help.component.capture_position": "Übernimmt die Lage von Teilen, die Sie von Hand verschoben haben, als ihre neue Position. Für Teile, die von keinem Gelenk gehalten und von Hand an ihren Platz gezogen wurden.", + "help.component.create": "Fügt der Konstruktion eine neue, leere Komponente hinzu, in der aktiven Komponente, sofern Sie kein anderes übergeordnetes Element wählen. Damit bekommt ein neues Teil einer Baugruppe einen eigenen Platz für Körper und Skizzen.", "help.component.finish_edit": "Speichert das an Ort und Stelle bearbeitete Teil, kehrt zu seiner Baugruppe zurück und aktualisiert die Baugruppe daraus. Verwenden Sie es, wenn Ihre Änderungen am verknüpften Teil fertig sind.", + "help.component.from_bodies": "Macht aus jedem gewählten Körper eine eigene Komponente, benannt nach dem Körper. Für Konstruktionen aus losen Körpern, die zu einer Baugruppe mit verbindbaren, beweglichen Teilen werden sollen.", + "help.component.insert_design": "Fügt eine andere gespeicherte Konstruktion als Komponente ein, die mit ihrer Datei verknüpft ist; ihre Volumenkörper liegen so wie dort. Damit verwenden Sie ein Teil in einer Baugruppe wieder und übernehmen spätere Änderungen mit „Verknüpfungen aktualisieren“.", + "help.component.properties": "Zeigt Volumen, Masse, Schwerpunkt und Trägheitsmomente einer Komponente anhand der Materialien ihrer Körper. Damit prüfen Sie Gewicht und Balance einer Baugruppe.", + "help.component.revert_position": "Setzt von Hand verschobene Teile an ihre vorige Stelle zurück und verwirft nicht erfasste Verschiebungen. Damit machen Sie Probebewegungen in einer Baugruppe rückgängig.", + "help.component.update_links": "Liest die verknüpften Konstruktionsdateien neu ein und ersetzt Körper, wo sie sich geändert haben. Damit übernehmen Sie Änderungen an einem Teil, das diese Baugruppe verwendet.", + "help.config.configure": "Fügt Parameter, Elemente, Materialien oder Darstellungen als Spalten der Konfigurationstabelle hinzu. Damit bauen Sie Varianten eines Designs, etwa Baugrößen eines Teils.", + "help.config.preview": "Prüft, ob sich eine Zeile der Konfigurationstabelle aufbauen lässt, ohne das Design oder seinen Verlauf zu ändern. Vor dem Wechsel zu einer Variante, bei der Sie unsicher sind.", + "help.config.rules": "Zeigt die Regeln der Konfigurationstabelle, ihre Zeilen und die aktive Zeile. Damit sehen Sie, wie die Varianten eines Designs aufgebaut sind.", + "help.config.table": "Zeigt die Konfigurationstabelle: eine Zeile je Variante, eine Spalte je Parameter oder Element, und ob das Design noch der aktiven Zeile entspricht. Damit überblicken Sie die Varianten eines Designs.", "help.connect_note": "Starten Sie jeden Assistenten neu, damit er den SolidCraft-Server lädt. Jede Datei wurde vor der Änderung als .bak gesichert.", "help.connect_title": "KI-Assistenten verbinden", + "help.construct.axis.edge": "Erzeugt eine Konstruktionsachse entlang einer geraden Kante oder Skizzenlinie. Als Achse für Drehung, Kreismuster oder Verbindung.", + "help.construct.axis.normal_to_face": "Erzeugt eine Konstruktionsachse durch einen Punkt, senkrecht zu einer Fläche. Als Achse, die gerade aus einer Fläche heraussteht.", + "help.construct.axis.through_cylinder": "Erzeugt eine Konstruktionsachse durch die Mitte einer Zylinder-, Kegel- oder Torusfläche oder einer Kreiskante. Damit drehen oder mustern Sie Elemente um ein rundes Teil.", + "help.construct.axis.two_planes": "Erzeugt eine Konstruktionsachse, wo sich zwei Ebenen oder ebene Flächen schneiden. Wenn die benötigte Achse die Schnittlinie zweier Flächen ist.", + "help.construct.axis.two_points": "Erzeugt eine Konstruktionsachse durch zwei Punkte, Eckpunkte oder Skizzenpunkte. Für eine Achse zwischen zwei bekannten Lagen.", + "help.construct.plane.along_path": "Erzeugt eine Konstruktionsebene senkrecht zu einer Kante oder Kurve, an einer Stelle entlang dieser. Damit skizzieren Sie ein Profil für eine Austragung oder einen Querschnitt eines Pfads.", + "help.construct.plane.at_angle": "Erzeugt eine Konstruktionsebene, die gegenüber einer Ebene oder Fläche um eine Achse oder Kante gedreht ist. Für schräge Skizzen, etwa eines Winkelhalters.", + "help.construct.plane.axis_point": "Erstellt eine Konstruktionsebene durch eine Achse und einen Punkt außerhalb der Achse. Zuerst eine Ursprungs- oder Konstruktionsachse, gerade Kante oder Skizzenlinie wählen, dann einen Eckpunkt, Skizzenpunkt oder Konstruktionspunkt. Ein Punkt auf der Achse legt keine eindeutige Ebene fest.", + "help.construct.plane.midplane": "Erzeugt eine Konstruktionsebene mittig zwischen zwei Ebenen oder ebenen Flächen oder als Winkelhalbierende, wo sie schräg zueinander stehen. Als Symmetrieebene zum Spiegeln.", + "help.construct.plane.offset": "Erzeugt eine Konstruktionsebene parallel zu einer Ebene oder ebenen Fläche, in einem Abstand oder durch einen Punkt. Damit skizzieren Sie in fester Höhe über einer Fläche.", + "help.construct.plane.perpendicular": "Erzeugt eine Konstruktionsebene, die eine Linie oder Kante enthält und senkrecht auf einer Ebene oder Fläche steht. Damit skizzieren Sie aufrecht entlang einer Kante am Modell.", + "help.construct.plane.tangent": "Erzeugt eine Konstruktionsebene, die einen Zylinder, Kegel, eine Kugel oder einen Torus in einem Punkt berührt. Damit skizzieren Sie seitlich an einem runden Teil.", + "help.construct.plane.three_points": "Erzeugt eine Konstruktionsebene durch drei Punkte. Für eine Ebene, die durch Lagen am Modell bestimmt ist, etwa drei Ecken.", + "help.construct.plane.two_edges": "Erzeugt eine Konstruktionsebene durch zwei gerade Kanten oder Linien, die in einer Ebene liegen. Für eine Ebene quer durch ein Teil, etwa durch zwei gegenüberliegende Kanten.", + "help.construct.point.along_path": "Erzeugt einen Konstruktionspunkt an einer Stelle entlang einer Kante oder Kurve. Als Bezug auf halbem oder beliebigem Weg entlang eines Pfads.", + "help.construct.point.center": "Erzeugt einen Konstruktionspunkt im Mittelpunkt einer Kreiskante, eines Skizzenkreises oder -bogens, einer Kugel oder eines Torus. Als Bezug für Bohrungen, Achsen und Verbindungen.", + "help.construct.point.edge_plane": "Erzeugt einen Konstruktionspunkt, wo eine Kante oder Linie eine Ebene oder ebene Fläche durchstößt. Damit markieren Sie, wo ein Pfad eine Ebene kreuzt.", + "help.construct.point.three_planes": "Erzeugt einen Konstruktionspunkt, wo sich drei Ebenen oder ebene Flächen treffen. Als Eckbezug, auch wo das Modell keinen Eckpunkt hat.", + "help.construct.point.two_edges": "Erzeugt einen Konstruktionspunkt, wo sich zwei Kanten oder Linien treffen oder am nächsten kommen. Als Bezug an einer virtuellen Ecke.", + "help.construct.point.vertex": "Erzeugt einen Konstruktionspunkt auf einem Eckpunkt oder Skizzenpunkt. Als Bezug, der bleibt, wenn Skizze oder Körper darum ausgeblendet sind.", + "help.contact.check": "Listet die Teilepaare in Kontaktsätzen auf, die sich in der aktuellen Stellung durchdringen. Damit finden Sie Kollisionen, bevor Sie Gelenke antreiben oder eine Bewegungsuntersuchung abspielen.", + "help.contact.create": "Fasst zwei oder mehr Teile zu einem Kontaktsatz zusammen, dessen Körper sich beim Bewegen der Gelenke nicht durchdringen. Für Teile, die beim Berühren anhalten sollen, etwa ein Hebel an seinem Anschlag.", + "help.contact.disable_all": "Schaltet den Kontakt aus, sodass angetriebene Gelenke und Bewegungsuntersuchungen nicht mehr anhalten, wo sich Teile berühren. Damit bewegen Sie Teile wieder frei oder halten eine große Baugruppe flüssig.", + "help.contact.edit": "Ändert einen Kontaktsatz: die enthaltenen Teile, den Namen oder ob er unterdrückt ist; der Satz lässt sich auch löschen. Damit passen Sie an, welche Teile sich nicht durchdringen dürfen.", + "help.contact.enable_all": "Nimmt alle Teile der Baugruppe in einen gemeinsamen Kontaktsatz, sodass sich beim Bewegen der Gelenke keine zwei Teile durchdringen. Für eine schnelle Prüfung des ganzen Mechanismus.", + "help.contact.enable_sets": "Schaltet den Kontakt für Ihre definierten Kontaktsätze ein, sodass angetriebene Gelenke und Bewegungsuntersuchungen anhalten, wo sich deren Teile durchdringen würden. Damit holen Sie Ihre Sätze zurück, nachdem der Kontakt aus war.", + "help.contact.list": "Listet die Kontaktsätze der Konstruktion auf, die Teile in jedem Satz und ob der Kontakt eingeschaltet ist. Damit prüfen Sie die Kontakteinstellung, bevor Sie die Baugruppe antreiben.", + "help.document.inspect": "Zeigt eine Übersicht des Designs: Komponenten, Körper, Skizzen, Elemente und Parameter. Damit finden Sie sich in einem Design zurecht, das Sie nicht selbst gebaut haben.", + "help.document.units": "Ändert die Einheit, in der die Konstruktion Längen anzeigt, etwa mm oder Zoll. Die Geometrie behält ihre Größe; nur Anzeige und Zahlen ohne Einheit folgen.", + "help.edit.checkpoint": "Merkt sich das Design, die aktive Skizze und den Rückgängig-Verlauf im jetzigen Zustand. Vor einem riskanten Versuch, von dem Sie vielleicht zurück wollen.", + "help.edit.restore_checkpoint": "Kehrt zu einem Prüfpunkt zurück, samt Rückgängig-Verlauf. Damit verwerfen Sie alles seit dem Prüfpunkt in einem Schritt.", + "help.explode.create": "Erstellt eine Explosionsdarstellung, die die Teile vom Mittelpunkt der Baugruppe wegschiebt oder um die von Ihnen festgelegten Wege verschiebt. Damit zeigen Sie, wie eine Baugruppe zusammengesetzt wird, für Anleitungen oder Präsentationen.", + "help.face.delete": "Entfernt die ausgewählten Flächen. Die angrenzenden Flächen schließen dabei die entstandene Lücke, oder sie bleibt als offene Fläche bestehen. So können Sie beispielsweise eine Rundung, eine Bohrung oder einen störenden Ansatz entfernen.", + "help.file.insert_mesh": "Fügt eine 3MF-, STL-, OBJ-, PLY- oder glTF-Datei als Netzkörper in einer neuen Komponente in die Konstruktion ein. Damit stellen Sie ein heruntergeladenes oder gescanntes Modell als Referenz neben Ihre Konstruktion.", + "help.file.insert_step": "Fügt eine STEP-, IGES-, FreeCAD- oder Rhino-Datei als Volumenkörper in einer neuen Komponente in die Konstruktion ein; die Teile einer Baugruppe werden zu verschachtelten Komponenten. Damit übernehmen Sie Modelle von Herstellern oder aus anderen CAD-Programmen.", + "help.file.save_mesh": "Speichert Körper als STL-, 3MF- oder OBJ-Netz, mit der gewählten Glätte gekrümmter Flächen. Damit bereiten Sie Teile für den 3D-Druck oder für Programme vor, die Netze lesen.", + "help.file.send_to_slicer": "Speichert die gewählten Körper als 3MF-Datei und öffnet sie im gewählten Slicer. Damit kommen Sie in einem Schritt vom Modell zum Druck.", "help.font_details": "Die Oberfläche verwendet die integrierten Schriftarten von egui (Ubuntu Light und Hack unter der Ubuntu Font Licence und der MIT/Bitstream-Vera-Lizenz; Noto Emoji und die Emoji-Symbolschrift unter OFL und MIT). Skizzentext verwendet Liberation Sans (SIL OFL 1.1). Das optionale Schriftpaket craft-fonts von The Crafting Apps (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1) ist nicht in SolidCraft-Builds enthalten.", "help.fonts": "Schriftarten", + "help.frame.member": "Setzt ein Profil, etwa ein Rohr oder ein Aluprofil, entlang der Linien einer Rahmenskizze, ein Stab je Linie. Für Rahmen, Gestelle und Schweißkonstruktionen.", + "help.inspect.accessibility": "Färbt die Flächen, die ein Werkzeug aus einer Richtung erreicht, und die, die es nicht erreicht. Damit prüfen Sie ein Teil auf Fräsen oder Formen von dieser Seite.", + "help.inspect.center_of_mass": "Zeigt den Schwerpunkt von Körpern, einzeln und zusammen, bei gleichmäßiger Dichte. Damit prüfen Sie die Balance und wohin ein Teil kippt.", + "help.inspect.colored_components": "Gibt jeder Komponente vorübergehend eine eigene Farbe, ohne die Darstellungen zu ändern. Damit unterscheiden Sie die Teile einer Baugruppe auf einen Blick.", + "help.inspect.compare": "Vergleicht zwei Körper und zeigt, wo einer Material hat, das dem anderen fehlt, mit Volumen und Abweichung. Damit prüfen Sie ein geändertes oder importiertes Teil gegen das Original.", + "help.inspect.continuity": "Prüft, wie glatt Flächen an ihren Kanten ineinander übergehen: Lücken, Knicke oder Krümmungssprünge, und färbt die Nähte. Damit finden Sie Stellen, an denen Flächen nicht sauber anschließen.", + "help.inspect.curvature_comb": "Zeichnet Kämme an Kurven, Kanten oder Flächen, deren Zinken zeigen, wie stark sie gekrümmt sind. Damit erkennen Sie flache Stellen, Knicke und ungleichmäßige Krümmung.", + "help.inspect.curvature_map": "Färbt Flächen danach, wie stark sie gekrümmt sind, rot bei kleinem Radius. Damit finden Sie enge Stellen und beurteilen, wie glatt eine Fläche ist.", + "help.inspect.draft": "Färbt Flächen nach ihrem Formschrägenwinkel zur Entformungsrichtung und markiert die mit zu wenig. Damit prüfen Sie ein Teil vor dem Spritzgießen oder Gießen.", + "help.inspect.environment_map": "Zeigt das Modell mit spiegelnder Oberfläche. Damit beurteilen Sie den Verlauf von Flächen an der Art, wie Spiegelungen darüber laufen.", + "help.inspect.interference": "Findet Körper, die sich überschneiden, und zeigt jede Überschneidung mit ihrem Volumen. Damit prüfen Sie eine Baugruppe auf kollidierende Teile.", + "help.inspect.isocurve": "Zeichnet die isoparametrischen Kurven von Flächen, das Raster, auf dem die Fläche aufbaut. Damit sehen Sie, wie eine Fläche verläuft und wo sie sich staucht.", + "help.inspect.measure": "Misst Längen, Abstände, Winkel, Flächen und Radien zwischen den gewählten Elementen oder Volumen und Masse von Körpern. Damit prüfen Sie Maße und Abstände.", + "help.inspect.minimum_radius": "Findet den kleinsten Krümmungsradius von Kurven, Kanten oder Flächen und seine Lage. Damit prüfen Sie, ob ein Werkzeug oder eine Düse der Form folgen kann.", + "help.inspect.section": "Schneidet die Ansicht entlang einer Ebene auf und schraffiert die Schnittflächen, ohne das Modell zu ändern. Damit schauen Sie in Teile und Baugruppen hinein.", + "help.inspect.zebra": "Zeigt schwarze und weiße Streifen, die sich auf den Flächen des Modells spiegeln. Damit beurteilen Sie Glätte: Streifen, die an einer Kante brechen oder knicken, zeigen einen schlechten Übergang.", + "help.joint.as_built": "Verbindet zwei Teile dort, wo sie bereits liegen, ohne eines davon zu verschieben, und legt fest, wie sie sich noch bewegen dürfen. Für Teile, die Sie schon an ihre endgültige Stelle gesetzt haben.", + "help.joint.cam": "Koppelt eine sich drehende Kurvenscheibe mit einem Stößel, der gleitet oder schwenkt, während die Kontur der Scheibe unter ihm durchläuft. Für Nocken, Exzenter und Ventiltriebe.", + "help.joint.create": "Verbindet zwei Teile an den gewählten Gelenkursprüngen und bewegt das zweite Teil an seine Stelle; der Gelenktyp legt fest, wie sie sich noch bewegen dürfen. Damit bauen Sie eine Baugruppe, deren Teile sich wie der echte Mechanismus bewegen.", + "help.joint.drive": "Setzt Winkel oder Weg eines Gelenks und bewegt die Teile mit, innerhalb der Grenzen; gekoppelte Gelenke und geschlossene Schleifen folgen. Damit prüfen Sie, ob sich ein Mechanismus wie gewünscht bewegt.", + "help.joint.gear": "Koppelt zwei Drehgelenke mit einer Übersetzung, sodass das Antreiben des einen das andere dreht. Für Stirn- und Hohlräder, mit der Übersetzung aus Teilkreisradien oder Zähnezahlen.", + "help.joint.limits": "Legt fest, wie weit sich ein Gelenk drehen oder schieben darf, als Minimum und Maximum, oder hebt diese Grenzen auf. Damit bleibt ein Scharnier, Schieber oder Hebel in seinem echten Bewegungsbereich.", + "help.joint.motion_link": "Koppelt zwei Gelenke über ein Verhältnis und einen Versatz, sodass das Antreiben des einen das andere bewegt. Für feste Beziehungen zwischen Gelenken, die Zahnrad, Zahnstange und Ritzel oder Schraube nicht abdecken.", + "help.joint.origin": "Setzt einen benannten Gelenkursprung auf ein Teil: in die Mitte einer Fläche oder eines runden Endes, auf die Mitte einer Kante, an eine Ecke oder einen Punkt. Damit bereiten Sie vor, wo Gelenke ansetzen; auf einer Fläche gewählt, folgt er ihr, wenn sich die Größe des Teils ändert.", + "help.joint.rack_pinion": "Koppelt ein drehendes Ritzel mit einer gleitenden Zahnstange, die sich um die abgewälzte Länge des Teilkreises verschiebt. Für Zahnstangenantriebe, Lenkungen und Lineartische.", + "help.joint.reach": "Bewegt einen Punkt eines Teils auf ein Ziel zu, indem die Gelenke seiner Kette innerhalb ihrer Grenzen verstellt werden. Damit stellen Sie einen Mechanismus über die Lage seines Endes ein, etwa der Spitze eines Roboterarms.", + "help.joint.rigid_group": "Verbindet die gewählten Teile starr in ihrer jetzigen Lage, sodass sie sich als Einheit bewegen. Für Teile, die zusammengehören und sich gegeneinander nicht bewegen.", + "help.joint.screw": "Koppelt Drehen und Schieben über eine Steigung, sodass jede Umdrehung um diesen Weg vorrückt. Für Gewindespindeln, Schrauben und Trapezspindeln.", + "help.layout.apply": "Ein gespeichertes Layout auf den aktuellen Arbeitsbereich anwenden. Geöffnete Editoren behalten ihre Entwürfe.", + "help.layout.get": "Das übernommene Layout lesen und registrierte Arbeitsbereiche anzeigen.", + "help.layout.reset": "Das registrierte Standardlayout des aktuellen Arbeitsbereichs wiederherstellen. Eigene Vorlagen bleiben erhalten.", + "help.layout.save": "Das vollständige Layout unter einem Namen speichern. Eine vorhandene eigene Vorlage wird nur mit ausdrücklicher Erlaubnis überschrieben.", + "help.layout.workspace.select": "Einen registrierten Layout-Arbeitsbereich auswählen und das bisherige Layout merken.", + "help.library.apply": "Wendet ein Material oder eine Darstellung aus einer lokalen Bibliotheksdatei auf Körper, Flächen oder Komponenten an. Damit nutzen Sie Materialien aus einem anderen Design wieder.", + "help.library.export": "Speichert die Materialien und Darstellungen des Designs in einer Bibliotheksdatei. Damit teilen Sie sie oder nutzen sie in anderen Designs wieder.", + "help.library.inspect": "Prüft eine Bibliotheksdatei und listet ihre Materialien und Darstellungen auf, ohne das Design zu ändern. Damit sehen Sie vor dem Anwenden, was eine Bibliothek enthält.", "help.licences": "Lizenzen", + "help.material.assign": "Legt fest, aus welchem Werkstoff die ausgewählten Körper bestehen, beispielsweise Stahl, Aluminium oder ABS. Dadurch entspricht die berechnete Masse derjenigen des realen Bauteils.", + "help.material.properties.validate": "Prüft eine Materialdatenkarte auf stimmige Werte und fehlende Angaben. Bevor Sie sich für Masse oder Steifigkeit auf die Daten verlassen.", + "help.mesh.convert": "Baut einen Netzkörper, etwa aus einer STL, als bearbeitbaren Volumenkörper mit ebenen und zylindrischen Flächen nach. Damit ändern Sie importierte Maschinenteile wie einen modellierten Körper.", "help.mit": "MIT-Lizenz", + "help.motion.study": "Legt Gelenkwerte an Schritten entlang einer Zeitleiste fest und spielt sie als Animation ab. Damit sehen Sie einen Mechanismus einen Ablauf durchlaufen und prüfen unterwegs die Abstände.", + "help.motion.trace": "Verfolgt die Bahn eines Punkts auf einem Teil, während eine Bewegungsuntersuchung läuft oder ein Gelenk angetrieben wird, und behält sie beim Bestätigen als 3D-Skizzenkurve. Damit sehen Sie, wohin ein Mechanismus reicht, oder bauen auf seiner Bahn auf.", "help.notice": "NOTICE", + "help.occurrence.ground": "Setzt ein Teil an seiner Stelle fest oder gibt es wieder frei, sodass Gelenke die übrigen Teile um es herum bewegen. Für den Rahmen oder Sockel, auf dem der Rest der Baugruppe aufbaut.", + "help.occurrence.move": "Bewegt eine Baugruppeninstanz ausschließlich entlang der Freiheitsgrade, die ihre Gelenke zulassen. Wählen Sie eine Fläche des Bauteils aus und ziehen Sie anschließend einen der verfügbaren Pfeile oder Bögen.", + "help.panel.activate": "Eine geöffnete Panel-Registerkarte auswählen, ohne den Tastaturfokus anzufordern.", + "help.panel.close": "Ein Panel unter Beachtung seines Inhaltslebenszyklus schließen. Seine Platzierung wird gespeichert.", + "help.panel.collapse": "Einen Panel-Bereich ein- oder ausklappen und seine gewünschten Abmessungen beibehalten.", + "help.panel.dismiss": "Die vorübergehende Ansicht eines eingeklappten Panels schließen.", + "help.panel.float": "Ein Panel in einen frei positionierten Bereich verschieben.", + "help.panel.focus": "Ein Panel fokussieren, seinen gespeicherten Zustand bei Bedarf wieder öffnen und seinen Bereich ausklappen.", + "help.panel.list": "Registrierte Panel-Arten, übernommene Instanzen, aktive Registerkarten, Verfügbarkeit und Host-Funktionen lesen.", + "help.panel.move": "Ein Panel in einen neuen Bereich verschieben oder einer vorhandenen Registerkartengruppe hinzufügen.", + "help.panel.native_close": "Einen nativen Panel-Bereich an seine gespeicherte Position zurückbringen, ohne seinen Inhalt abzubrechen.", + "help.panel.open": "Eine Panel-Art mit einer ausdrücklichen Instanzkennung öffnen. Neue Instanzen benötigen eine Platzierung.", + "help.panel.peek": "Ein eingeklapptes Panel vorübergehend anzeigen, ohne seine gespeicherte Größe oder seinen Klappzustand zu ändern.", + "help.panel.popout": "Ein Panel bei Unterstützung in ein natives Fenster verschieben. Im Browser wird ein frei positionierter Bereich verwendet.", + "help.panel.reset_pair": "Das Standardgrößenverhältnis zweier benachbarter Andockbereiche innerhalb ihrer gemeinsamen Grenzen wiederherstellen.", + "help.panel.resize": "Die äußere Breite und Höhe eines Panel-Bereichs innerhalb der Grenzen aller Registerkarten festlegen.", + "help.panel.resize_pair": "Benachbarte Andockbereiche gemeinsam skalieren und ihre gemeinsame Ausdehnung beibehalten.", + "help.parameters.change": "Öffnet die Tabelle mit benannten Parametern und Ausdrücken, die die Abmessungen des Designs steuern. Ändern Sie einen Wert an einer zentralen Stelle, werden alle Features, die diesen Wert verwenden, entsprechend aktualisiert.", + "help.parameters.export": "Speichert die Parameter des Designs als CSV oder JSON. Damit bearbeiten Sie sie in einer Tabellenkalkulation oder übertragen sie in ein anderes Design.", + "help.parameters.graph": "Zeigt, welche Parameter und Elemente welche anderen nutzen, samt Schleifen oder Fehlern. Damit sehen Sie, was eine Parameteränderung beeinflusst.", + "help.parameters.import": "Liest Parameter aus CSV oder JSON in das Design ein, alle oder keine. Damit übernehmen Sie Werte aus einer Tabelle oder einem anderen Design.", + "help.parameters.move": "Verschiebt einen Benutzerparameter vor oder hinter einen anderen in der Liste. So bleiben zusammengehörige Parameter beieinander.", + "help.parts.fastener": "Fügt eine genormte Schraube, Mutter, Unterlegscheibe, einen Stift oder ein Lager in der gewählten Größe ein. Auf ein Loch gesetzt, sitzt es mit einem Gelenk darin, sodass Sie Verbindungselemente nicht selbst modellieren müssen.", + "help.parts.insert": "Fügt ein Normteil in der gewählten Art, Größe und Länge ein. Auf den Rand oder die Wand eines Lochs gesetzt, sitzt es mit einem starren Gelenk auf dem Loch.", + "help.parts.library": "Öffnet die Standardbauteile: Schrauben, Muttern, Unterlegscheiben, Gewindestifte, Passstifte und Lager in Normgrößen. Damit fügen Sie ein Normteil ein, statt es selbst zu modellieren.", + "help.parts.resize": "Ändert Größe oder Länge eines eingefügten Normteils und baut es neu auf; seine Gelenke halten es an seinem Platz. Für den Fall, dass eine Schraube zu lang ist oder ein Loch eine andere Größe braucht.", + "help.plastic.assign_rule": "Weist Körpern eine Kunststoffregel zu, sodass ihre Kunststoffelemente deren Formschräge und Spiel als Vorgabe nehmen. Damit richten Sie ein Spritzgussteil einmal für alle seine Elemente ein.", + "help.plastic.boss": "Fügt einen Ansatz (Schraubdom) auf einer Fläche hinzu: einen Zapfen mit optionaler Bohrung, Formschräge, Fußrundung und Stützrippen. Für Schraubstellen in gespritzten oder gedruckten Gehäusen.", + "help.plastic.lip": "Fügt entlang des Rands eines ausgehöhlten Körpers eine Lippe oder eine passende Nut hinzu. Damit zentrieren sich zwei Gehäusehälften aufeinander und schließen dicht.", + "help.plastic.manage_rules": "Erstellt und bearbeitet Kunststoffregeln: Material, Wandstärke, Radien, Spiel und Formschräge. Damit halten Sie die Elemente eines Spritzgussteils einheitlich.", + "help.plastic.rest": "Fügt eine Auflage auf einer Fläche hinzu: ein rundes oder rechteckiges Polster, voll oder hohl, mit Formschräge. Als Stütze oder Abstandshalter in einem Spritzgussgehäuse.", + "help.plastic.snap_fit": "Fügt eine Rastverbindung auf einer Fläche hinzu: einen Schnapphaken mit Länge, Dicke und Rastnase. Damit klipsen Sie Teile ohne Schrauben zusammen.", "help.pointcloud.insert": "Fügt einen PLY-, XYZ- oder PTS-Scan als Punktwolke neben dem Modell ein. Verwenden Sie ihn als Referenz beim Modellieren anhand von Messdaten.", + "help.sheet.convert": "Macht aus einer Platte oder einem ausgehöhlten Körper gleichmäßiger Dicke einen Blechkörper, mit Biegungen an den gewählten Kanten. Damit wird ein vorhandenes Teil abwickelbar.", + "help.sheet.export_bend_table": "Speichert die Biegungstabelle eines Blechkörpers als CSV oder JSON: Winkel, Radien und Lage der Biegungen im Flachmuster. Für die Abkantpresse oder die Werkstatt.", + "help.sheet.export_dxf": "Speichert das Flachmuster als DXF, mit Konturen, Biegelinien und optionalen Biegevermerken. Für Laser-, Plasma- oder Wasserstrahlschneiden.", + "help.sheet.flange": "Fügt einen Flansch hinzu: eine Grundplatte aus einer Skizze, eine Wand entlang einer offenen Skizzenkontur oder eine gebogene Wand an Blechkanten. Damit bauen Sie Blechteile auf.", + "help.sheet.flat_pattern": "Erstellt das Flachmuster eines Blechkörpers mit Größe, Ausschnitten und Biegelinien. Damit prüfen Sie den Zuschnitt, bevor Sie ihn schneiden.", + "help.sheet.fold": "Faltet ein Blech entlang einer Skizzenlinie um einen Winkel und Radius. Damit falten Sie ein flaches Blech, nachdem Sie Elemente hineingeschnitten haben.", + "help.sheet.hem": "Faltet eine Blechkante auf sich selbst zurück. Für sichere, steife Kanten ohne scharfen Grat.", + "help.sheet.manage_rules": "Erstellt und bearbeitet Blechregeln: Dicke, Biegeradius, K-Faktor, Freischnitte und Spalte. Damit passen Sie die Teile an Material und Werkzeuge Ihrer Werkstatt an.", + "help.sheet.path_flange": "Fügt entlang einer Blechkante eine Kette von Flanschen hinzu, die einer offenen Kette von Skizzenlinien folgt. Für Profile wie eine U- oder Z-Form in einem Schritt.", + "help.sheet.perforate": "Fügt über das ganze flache Blech ein Lochfeld hinzu, versetzt oder quadratisch. Für Lüftungen, Gitter und leichtere Bleche.", + "help.sheet.refold": "Faltet einen entfalteten Blechkörper wieder auf. Nachdem Sie dem flachen Blech Elemente hinzugefügt haben.", + "help.sheet.unfold": "Entfaltet alle Biegungen eines Blechkörpers. Damit fügen Sie Bohrungen oder Schnitte hinzu, die über eine Biegung laufen müssen, und falten dann wieder.", + "help.sketch.arc.center_point": "Zeichnet einen Kreisbogen um einen Mittelpunkt, von einem Start- zu einem Endpunkt. Für Bögen mit bekanntem Mittelpunkt, etwa einen Radius um eine Bohrung oder einen Drehpunkt.", + "help.sketch.arc.tangent": "Zeichnet einen Bogen, der am Ende einer Linie oder eines Bogens tangential weiterläuft. Damit setzen Sie eine Kette mit einer weichen Biegung statt einer Ecke fort.", + "help.sketch.arc.three_point": "Zeichnet einen Bogen von einem Start- zu einem Endpunkt durch einen dritten Punkt. Für Bögen, die durch vorgegebene Punkte laufen sollen statt um einen bekannten Mittelpunkt.", + "help.sketch.arc3d": "Zeichnet bei eingeschalteter 3D-Skizze einen exakten Kreisbogen im Raum durch drei Punkte. Für Biegungen in Pfaden und Leitkurven, die die Skizzenebene verlassen.", + "help.sketch.auto_constrain": "Fügt die Bedingungen hinzu, die die Skizze schon fast erfüllt, etwa horizontal, parallel oder koinzident, und bemaßt sie dann vollständig. Damit legen Sie eine grob gezeichnete Skizze in einem Schritt fest.", + "help.sketch.auto_constrain_from_datum": "Arbeitet wie Auto-Bedingung, misst die Lagen aber von einem gewählten Bezugspunkt statt vom Ursprung. Für Teile, die von einem Bezugspunkt aus bemaßt werden, etwa einer Ecke oder einer Bohrung.", + "help.sketch.blend_curve": "Verbindet die Enden zweier Kurven mit einem glatten Spline, der an beide tangential oder auf Wunsch auch krümmungsstetig anschließt. Damit überbrücken Sie eine Lücke zwischen Kurven ohne Knick.", + "help.sketch.break": "Teilt eine Kurve an den Stellen, an denen andere Kurven sie kreuzen, oder an Punkten, die Sie auf ihr setzen. Wenn ein Stück der Kurve eine eigene Bedingung braucht oder einzeln gelöscht werden soll.", + "help.sketch.cancel": "Verlässt die Skizze und verwirft alles, was seit dem Erstellen oder Öffnen zum Bearbeiten geändert wurde. Mit Rückgängig holen Sie die Änderungen zurück.", + "help.sketch.centerline": "Schaltet Linien zwischen normalen Linien und Mittellinien um, also Achsen, die nicht zu Profilen gehören. Eine Mittellinie dient als Achse für Drehen, Spiegeln oder eine Symmetriebedingung.", + "help.sketch.chamfer.distance_angle": "Schrägt die Ecke zwischen zwei Linien ab, bestimmt durch einen Abstand entlang der ersten Linie und einen Winkel. Wenn eine Zeichnung die Fase als Länge und Winkel angibt, etwa 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Schrägt die Ecke zwischen zwei Linien mit gleichem Abstand auf beiden Seiten ab. Für die übliche 45°-Fase an einer Kontur.", + "help.sketch.chamfer.two_distance": "Schrägt die Ecke zwischen zwei Linien mit je einem eigenen Abstand entlang jeder Linie ab. Für Fasen, die nicht 45° haben und mit zwei Längen angegeben sind.", + "help.sketch.circle.center": "Zeichnet einen Kreis aus Mittelpunkt und Durchmesser. Für Bohrungen, Zapfen und andere runde Formen mit bekanntem Mittelpunkt.", + "help.sketch.circle.three_point": "Zeichnet einen Kreis durch drei Punkte. Wenn der Kreis durch vorgegebene Punkte laufen soll, etwa auf vorhandener Geometrie.", + "help.sketch.circle.three_tangent": "Zeichnet einen Kreis, der drei Linien, Kreise oder Bögen berührt. Damit setzen Sie einen Kreis passend zwischen drei Kurven, etwa den Inkreis eines Dreiecks.", + "help.sketch.circle.two_point": "Zeichnet einen Kreis aus den beiden Enden seines Durchmessers. Wenn die Randpunkte des Kreises bekannt sind statt seines Mittelpunkts.", + "help.sketch.circle.two_tangent": "Zeichnet einen Kreis vorgegebener Größe, der zwei Linien, Kreise oder Bögen berührt. Für eine Rundung mit festem Radius zwischen zwei Kurven.", + "help.sketch.conic": "Zeichnet einen Kegelschnitt zwischen zwei Endpunkten, geformt durch einen Scheitelpunkt und einen Rho-Wert. Für weiche Übergänge, deren Völle Sie einstellen wollen, von flach bis fast zur scharfen Ecke.", + "help.sketch.constrainer": "Setzt die Bedingung, die eine oder zwei gewählte Kurven schon fast erfüllen, etwa horizontal, parallel, tangential oder gleich. Damit räumen Sie eine frei gezeichnete Skizze Beziehung für Beziehung auf.", + "help.sketch.constraint.coincident": "Legt einen Punkt auf einen anderen Punkt, eine Kurve oder eine Skizzenachse. Damit schließen Sie Lücken in einem Profil oder setzen einen Punkt auf eine Linie.", + "help.sketch.constraint.collinear": "Legt zwei Linien auf eine gemeinsame Gerade. Damit richten Sie unterbrochene Kanten aus, etwa die beiden Seiten einer Kerbe.", + "help.sketch.constraint.concentric": "Gibt zwei Kreisen oder Bögen denselben Mittelpunkt oder zentriert einen Kreis oder Bogen auf einem Skizzenpunkt, auch dem Ursprung. Die Auswahlreihenfolge ist beliebig.", + "help.sketch.constraint.curvature": "Lässt zwei Kurven, die sich an einem Endpunkt treffen, mit gleicher Krümmung ineinander übergehen (G2). Wo ein tangentialer Übergang nicht glatt genug ist, etwa an Sichtflächen.", + "help.sketch.constraint.equal": "Macht Linien gleich lang oder Kreise und Bögen gleich groß im Radius. So steuert ein Maß mehrere gleiche Elemente.", + "help.sketch.constraint.fix": "Fixiert Punkte oder Kurven an ihrer Stelle oder löst sie wieder. Für Geometrie, die sich beim Ziehen oder Lösen der Skizze nicht bewegen darf.", + "help.sketch.constraint.horizontal_vertical": "Macht eine Linie oder die Verbindung zweier Punkte horizontal oder vertikal, je nachdem, was näher liegt. Damit richten Sie eine Kontur an den Skizzenachsen aus.", + "help.sketch.constraint.midpoint": "Setzt einen Punkt auf die Mitte einer Linie oder lässt die Mittelpunkte zweier Linien zusammenfallen. Damit mitten Sie Geometrie auf einer Kante ein.", + "help.sketch.constraint.parallel": "Macht zwei Linien parallel. Für Seiten, die parallel bleiben müssen, wenn sich andere Maße ändern.", + "help.sketch.constraint.perpendicular": "Stellt zwei Linien rechtwinklig zueinander. Für rechte Winkel zwischen Linien, die nicht an den Skizzenachsen liegen.", + "help.sketch.constraint.polygon": "Macht eine geschlossene Linienkette zum regelmäßigen Polygon: gleich lange Seiten, alle Ecken auf einem Kreis. Damit machen Sie ein frei gezeichnetes Vieleck regelmäßig und halten es so.", + "help.sketch.constraint.symmetry": "Lässt zwei Punkte oder Kurven an einer Linie oder einem Punkt gespiegelt liegen. So bleibt ein Profil symmetrisch, wenn Sie eine Seite ändern.", + "help.sketch.constraint.tangent": "Lässt zwei Kurven tangential aneinanderstoßen, etwa eine Linie und einen Bogen. Für glatte Übergänge ohne Knick.", + "help.sketch.construction": "Schaltet Kurven zwischen normaler Geometrie und Konstruktionsgeometrie um, die nicht zu Profilen gehört. Konstruktionskurven dienen als Hilfen für Aufteilung, Bezüge und Maße.", "help.sketch.construction_line": "Erstellt eine unendliche Konstruktionslinie durch zwei Punkte, ohne Skizzenprofile zu teilen.", "help.sketch.construction_line.angle": "Erstellt eine unendliche Konstruktionslinie in einem Winkel zur Skizzen-X-Achse. Punkt wählen und Winkel eingeben oder Richtung wählen.", "help.sketch.construction_line.bisector": "Zwei sich schneidende gerade Skizzenlinien wählen, dann eine der beiden Winkelhalbierenden. Das Ergebnis folgt den Ausgangslinien.", @@ -1390,21 +1663,133 @@ "help.sketch.construction_line.tangent_external": "Kreis oder Kreisbogen wählen, dann einen äußeren Punkt und eine Tangentenlösung. Die Vorschau zeigt nur Berührpunkte auf dem gezeichneten Bogen.", "help.sketch.construction_line.tangent_two": "Zwei Kreise oder Kreisbögen wählen, dann eine gemeinsame Tangente in der Vorschau. Die Berührpunkte müssen auf den gezeichneten Kurven liegen.", "help.sketch.construction_line.vertical": "Erstellt eine unendliche vertikale Konstruktionslinie durch einen Punkt. Die Vertikalbedingung bleibt bei späteren Änderungen erhalten.", + "help.sketch.copy": "Kopiert die gewählten Skizzenkurven und -punkte samt den Bedingungen und Maßen zwischen ihnen. Fügen Sie sie in diese oder eine andere Skizze ein.", + "help.sketch.create": "Beginnt eine neue 2D-Skizze auf einer Ebene oder einer ebenen Fläche des Modells. Jede Extrusion, Drehung und Austragung beginnt mit einer Skizze.", + "help.sketch.cut": "Kopiert die gewählte Skizzengeometrie und löscht sie aus der Skizze, in einem Rückgängig-Schritt. Fügen Sie sie an anderer Stelle oder in eine andere Skizze ein.", + "help.sketch.dimension": "Fügt ein steuerndes Maß hinzu: Länge, Abstand, Winkel, Radius oder Durchmesser, je nachdem, was Sie wählen. Geben Sie einen Wert oder Parameternamen ein, und die Skizze folgt ihm.", + "help.sketch.edit": "Öffnet eine vorhandene Skizze zum Bearbeiten. Die darauf aufbauenden Elemente werden aktualisiert, wenn Sie die Skizze fertigstellen.", + "help.sketch.ellipse": "Zeichnet eine Ellipse aus Mittelpunkt, dem Ende der Hauptachse und einem Punkt auf der Nebenseite. Für ovale Öffnungen, Nocken und andere längliche Rundformen.", "help.sketch.equation_curve": "Zeichnet eine Kurve aus Formeln über einen Bereich: x(t) und y(t) oder y = f(x). Die Formeln können Parameter verwenden, und die Kurve folgt ihnen: für eine Sinuswelle, eine Spirale oder die Evolvente eines Zahnrads.", + "help.sketch.extend": "Verlängert eine Linie oder einen Bogen bis zur nächsten Kurve im Weg oder zwei Kurven, bis sie sich treffen. Damit schließen Sie Lücken in einem Profil nach dem Kürzen oder Ändern.", + "help.sketch.fillet": "Rundet die Ecke zwischen zwei Linien oder Bögen mit einem Bogen vorgegebenen Radius ab. Mehrere zusammen gerundete Ecken teilen sich einen Radius.", + "help.sketch.finish": "Verlässt die Skizze und kehrt zum Modell zurück. Ihre geschlossenen Profile stehen dann für Extrusion, Drehung und weitere Elemente bereit.", + "help.sketch.finish_auto_constrain": "Wendet Auto-Bedingung auf die Skizze an und stellt sie dann fertig. Damit verlassen Sie eine Skizze in einem Schritt vollständig bestimmt.", + "help.sketch.fit_curves_to_section": "Schneidet einen Netz- oder Volumenkörper mit der Skizzenebene und passt Linien und Bögen an den Querschnitt an. Damit bauen Sie ein gescanntes oder importiertes Teil als bearbeitbare Skizze nach.", + "help.sketch.include_3d": "Holt Modellkanten, Eckpunkte und Kurven anderer Skizzen als verknüpfte Bezüge in diese Skizze und legt Teile außerhalb der Ebene flach auf sie. Damit bauen Sie auf Geometrie auf, die nicht in der Skizzenebene liegt.", + "help.sketch.infinite": "Schaltet Linien zwischen normalen Linien und unendlichen Konstruktionslinien um, die über die ganze Ansicht laufen. Als Bezugslinien für die Aufteilung, die nie zu kurz enden.", + "help.sketch.insert_dxf": "Liest die Kurven einer DXF-Zeichnung in eine Skizze ein, skaliert, gedreht und an der gewünschten Stelle. Damit bauen Sie auf einer 2D-Zeichnung aus einem anderen Programm auf, etwa einer Laserschnitt-Kontur.", + "help.sketch.insert_svg": "Liest die Pfade einer SVG-Zeichnung in eine Skizze ein, skaliert, gedreht und an der gewünschten Stelle. Damit machen Sie aus einem Logo oder einer Vektorkontur Kurven, die sich extrudieren lassen.", + "help.sketch.inspect": "Öffnet einen Bericht zur offenen Skizze: wie viele Freiheitsgrade übrig sind und ob sie vollständig bestimmt ist. Damit sehen Sie, was sich noch bewegt, bevor Sie die Skizze abschließen.", + "help.sketch.intersect": "Fügt die Kurven oder Punkte hinzu, an denen Körper, Flächen, Kanten oder andere Skizzen die Skizzenebene schneiden. Sie bleiben verknüpft und folgen Änderungen am Modell.", + "help.sketch.intersection_curve": "Erzeugt 3D-Kurven, wo sich zwei Körper oder Flächen treffen, mit diesen verknüpft. Als Pfade oder Leitkurven, die dem Modell folgen.", + "help.sketch.isoparametric_curve": "Erzeugt eine 3D-Kurve in U- oder V-Richtung einer Fläche durch einen gewählten Punkt, mit der Fläche verknüpft. Als Pfad oder Trennlinie, die der Fläche folgt.", + "help.sketch.line": "Zeichnet verbundene Linien Punkt für Punkt, als offene Kette oder geschlossene Kontur. Das Grundwerkzeug für die meisten Profile.", + "help.sketch.line.midpoint": "Zeichnet eine Linie von ihrem Mittelpunkt zu einem Ende, das andere Ende gespiegelt. Für Linien, die auf einem Punkt mittig liegen, etwa eine symmetrische Kante.", + "help.sketch.line3d": "Zeichnet bei eingeschalteter 3D-Skizze verbundene gerade Linien zwischen Punkten im Raum. Für Pfade und Rahmen, die die Skizzenebene verlassen.", + "help.sketch.mirror": "Spiegelt Skizzenkurven und -punkte an einer Linie oder Achse und fügt Symmetriebedingungen hinzu. Damit zeichnen Sie ein symmetrisches Profil zur Hälfte und ergänzen es.", + "help.sketch.move": "Verschiebt oder dreht Skizzenkurven und -punkte oder eine Kopie davon. Damit setzen Sie Geometrie um, ohne Form und Bedingungen zu verlieren.", + "help.sketch.offset": "Erzeugt eine Kopie einer Kurvenkette in festem Abstand, auf einer oder beiden Seiten. Für Wände, Konturen und Spiele; der Abstand bleibt ein änderbares Maß.", + "help.sketch.paste": "Fügt kopierte oder ausgeschnittene Skizzengeometrie in die aktive Skizze ein. Setzen Sie sie an einen Punkt oder verschieben Sie sie um einen Versatz.", + "help.sketch.pattern.circular": "Kopiert Skizzengeometrie um einen Mittelpunkt, über einen vollen Kreis oder einen festen Winkel. Für Lochkreise, Speichen und Zähne.", + "help.sketch.pattern.rectangular": "Kopiert Skizzengeometrie in Reihen und Spalten mit festen Abständen. Für Raster aus Bohrungen, Schlitzen oder Lüftungsöffnungen.", + "help.sketch.point": "Setzt einen Skizzenpunkt. Als Bezug für Maße, Bedingungen, Bohrungsmitten oder spätere Elemente.", + "help.sketch.point3d": "Setzt bei eingeschalteter 3D-Skizze einen Punkt im Raum. Als Bezug für 3D-Kurven und Pfade.", + "help.sketch.polygon.circumscribed": "Zeichnet ein regelmäßiges Polygon um einen Kreis, bemessen vom Mittelpunkt zur Mitte einer Seite. Wenn die Schlüsselweite bekannt ist, etwa bei einer Sechskantmutter.", + "help.sketch.polygon.edge": "Zeichnet ein regelmäßiges Polygon aus den beiden Enden einer Seite. Wenn Länge und Lage einer Seite bekannt sind.", + "help.sketch.polygon.inscribed": "Zeichnet ein regelmäßiges Polygon in einen Kreis, bemessen vom Mittelpunkt zu einer Ecke. Wenn das Eckmaß bekannt ist.", + "help.sketch.project": "Projiziert Modellkanten, Flächen, Eckpunkte und Kurven anderer Skizzen auf die Ebene dieser Skizze. Sie bleiben verknüpft und folgen Änderungen am Modell.", + "help.sketch.project_to_surface": "Projiziert Kurven anderer Skizzen entlang der Normalen dieser Skizze auf eine Fläche, als verknüpfte 3D-Kurven. Damit bringen Sie ein Logo, eine Trennlinie oder einen Pfad auf eine gekrümmte Fläche.", + "help.sketch.rectangle.center": "Zeichnet ein Rechteck aus Mittelpunkt und einer Ecke. Für Konturen, die mittig auf einem Punkt liegen, etwa dem Ursprung.", + "help.sketch.rectangle.rounded": "Zeichnet ein Rechteck, dessen vier Ecken mit einem Radius gerundet sind. Für Platten, Deckel und Öffnungen mit runden Ecken.", + "help.sketch.rectangle.three_point": "Zeichnet ein Rechteck aus einer Kante und einem Punkt auf der gegenüberliegenden Seite. Für Rechtecke, die schräg zu den Skizzenachsen liegen.", + "help.sketch.rectangle.two_point": "Zeichnet ein Rechteck aus zwei gegenüberliegenden Ecken. Für die Konturen von Platten, Blöcken und Taschen.", + "help.sketch.scale": "Skaliert Skizzenkurven und -punkte mit einem Faktor um einen Basispunkt. Damit ändern Sie die Größe eines Skizzenteils, ohne ihn neu zu zeichnen.", + "help.sketch.slot.arc_center": "Zeichnet einen gebogenen Schlitz vorgegebener Breite entlang eines Bogens aus Mittelpunkt, Start und Ende. Für Verstellschlitze um einen Drehpunkt.", + "help.sketch.slot.arc_three_point": "Zeichnet einen gebogenen Schlitz vorgegebener Breite entlang eines Bogens durch drei Punkte. Wenn der Verlauf des Schlitzes durch vorgegebene Punkte gehen soll.", + "help.sketch.slot.center_point": "Zeichnet einen geraden Schlitz vorgegebener Breite von seiner Mitte zum Mittelpunkt eines Endbogens. Für Schlitze, die mittig auf einem Punkt liegen.", + "help.sketch.slot.center_to_center": "Zeichnet einen geraden Schlitz vorgegebener Breite zwischen den Mittelpunkten seiner beiden Endbögen. Für Schlitze, die von Mitte zu Mitte bemaßt sind, etwa Langlöcher für Schrauben.", + "help.sketch.slot.overall": "Zeichnet einen geraden Schlitz vorgegebener Breite von einem äußeren Ende zum anderen. Wenn es auf die Gesamtlänge des Schlitzes ankommt.", + "help.sketch.spline.control_point": "Zeichnet einen kubischen Spline, den Kontrollpunkte formen, ohne dass er durch sie läuft. Für glatte, fließende Kurven, die Sie durch Verschieben der Punkte formen.", + "help.sketch.spline.control_point_5": "Zeichnet einen Spline vom Grad 5, den Kontrollpunkte formen. Wo Kurven mit glatterer Krümmung anschließen müssen, etwa an gestalteten Sichtflächen.", + "help.sketch.spline.fit_point": "Zeichnet einen glatten Spline durch alle gesetzten Punkte, offen oder geschlossen. Damit zeichnen Sie eine Form durch bekannte Punkte nach.", + "help.sketch.spline3d": "Zeichnet bei eingeschalteter 3D-Skizze eine glatte Kurve durch Punkte im Raum. Für Austragungspfade und Kabelwege, die die Skizzenebene verlassen.", + "help.sketch.spun_profile": "Erzeugt in der Skizzenebene die Kontur, die ein Körper bei einer Drehung um eine Achse überstreicht. Damit erhalten Sie den Umriss eines Drehteils für eine Drehung oder eine Zeichnung.", + "help.sketch.text": "Schreibt Text in die Skizze, mit Schriftart, Höhe und Winkel; der Wortlaut kann Parametern folgen. Extrudieren oder prägen Sie ihn für Beschriftungen und Schriftzüge.", + "help.sketch.transform": "Skaliert, dreht und verschiebt Skizzengeometrie um einen Mittelpunkt in einem Schritt. Damit setzen Sie eine Auswahl gleichzeitig um und ändern ihre Größe.", + "help.sketch.trim": "Entfernt das Stück einer Kurve zwischen den nächsten Schnittpunkten um die angeklickte Stelle. Damit räumen Sie sich überlappende Linien zu einem geschlossenen Profil auf.", + "help.solid.align": "Verschiebt die ausgewählten Körper so, dass ein Punkt, eine Fläche oder eine Ebene eines Körpers mit einem entsprechenden Punkt, einer Fläche oder Ebene an anderer Stelle zusammenfällt. So können Sie Bauteile aneinander ausrichten, ohne Abstände messen zu müssen.", + "help.solid.boundary_fill": "Erzeugt Volumenkörper aus den Bereichen, die sich überlappende Werkzeugkörper einschließen, und füllt nur die gewählten Bereiche. Damit bauen Sie eine Form aus dem Raum, den mehrere Körper gemeinsam begrenzen.", + "help.solid.bounding_solid": "Erzeugt einen Quader, der die gewählten Körper umschließt, auf Wunsch mit Aufmaß. Damit sehen Sie die Gesamtgröße eines Teils oder erhalten das Rohteil, aus dem es gefertigt wird.", + "help.solid.box": "Erzeugt einen Quader aus Länge, Breite und Höhe, ab einem Eckpunkt oder um einen Punkt zentriert. Für einen schnellen Block, einen Platzhalter oder einen Körper, in den Sie Features schneiden.", "help.solid.chamfer": "Schneidet die gewählten Kanten mit einer ebenen Fase im eingestellten Abstand ab. Damit brechen Sie scharfe Kanten oder erleichtern das Einführen eines Stifts oder einer Schraube.", + "help.solid.coil": "Erzeugt einen schraubenförmigen Körper, etwa eine Feder, aus Durchmesser, Windungen, Höhe oder Steigung und einem runden oder eckigen Querschnitt. Für Federn, Spulen und schraubenförmige Stege.", "help.solid.combine": "Kombiniert Körper: vereinigt sie, zieht sie von einem Zielkörper ab oder behält nur das gemeinsame Volumen; die Werkzeugkörper können erhalten bleiben. Damit fügen Sie Teile zusammen, schneiden eine Form mit einer anderen aus oder finden, wo sich zwei Körper überschneiden.", + "help.solid.cone": "Erzeugt einen Kegel aus Grundkreis und Höhe, oder einen Kegelstumpf, wenn auch die Oberseite einen Radius hat. Für Verjüngungen, Trichter, Senkungen und Spitzen.", + "help.solid.cylinder": "Erzeugt einen Zylinder aus Radius oder Durchmesser und Höhe, auf einem Punkt entlang einer Achse stehend. Für Wellen, Stifte, Dome und runde Rohlinge.", + "help.solid.draft": "Schrägt die ausgewählten Flächen um den eingestellten Winkel gegenüber einer neutralen Ebene ab. Diese Funktion wird bei Guss- und Spritzgussteilen verwendet, damit sich die Bauteile leichter aus der Form lösen lassen.", + "help.solid.emboss": "Hebt Skizzenprofile wie Text oder ein Logo aus einer Fläche heraus oder senkt sie hinein. Für Beschriftungen, Etiketten und Markierungen auf ebenen oder runden Flächen.", "help.solid.extrude": "Zieht ein Skizzenprofil über eine Strecke in die dritte Dimension und fügt dabei Material hinzu oder entfernt es. Damit machen Sie aus einer flachen Kontur einen Block, eine Erhebung oder eine Tasche.", "help.solid.fillet": "Rundet die gewählten Kanten mit einem glatten Kreisübergang im eingestellten Radius ab. Damit entschärfen Sie scharfe Kanten für Festigkeit, Griffigkeit oder Optik.", "help.solid.hole": "Bohrt an einem gewählten Punkt auf einer Fläche ein rundes Loch im eingestellten Durchmesser. Für Durchgangsbohrungen für Schrauben, Stifte und andere einfache runde Öffnungen.", "help.solid.loft": "Erzeugt einen glatten Übergangskörper zwischen zwei oder mehr Skizzenprofilen oder von einem Profil zu einem Punkt. Für Übergänge, Trichter, Griffe und alle Formen, deren Querschnitt sich über die Länge ändert.", "help.solid.mirror": "Erzeugt eine gespiegelte Kopie der gewählten Körper oder Features an einer Ebene und kann sie mit dem Original vereinigen. Für symmetrische Teile: Sie modellieren eine Hälfte und erhalten beide.", + "help.solid.move": "Verschiebt oder dreht die ausgewählten Körper oder deren Kopien um den eingestellten Abstand und Winkel. So können Sie einen Körper neu positionieren oder an anderer Stelle eine Kopie erstellen.", + "help.solid.offset_face": "Versetzt die ausgewählten Flächen um den eingestellten Abstand nach innen oder außen. Die angrenzenden Flächen werden entsprechend angepasst. So können Sie beispielsweise eine Wand verdicken, eine Tasche vertiefen oder einen Ansatz erhöhen, ohne die Skizze bearbeiten zu müssen.", "help.solid.pattern.circular": "Wiederholt die gewählten Objekte um eine Achse, mit der eingestellten Anzahl und dem Gesamtwinkel. Für Lochkreise, Speichen, Kühlrippen und Zähne.", + "help.solid.pattern.path": "Kopiert Elemente oder Körper entlang eines Skizzenpfads, nach Anzahl und Abstand. Für Bohrungen entlang einer gebogenen Kante oder Teile entlang einer Schiene.", "help.solid.pattern.rectangular": "Wiederholt die gewählten Objekte in einer oder zwei Richtungen mit der eingestellten Anzahl und dem Abstand. Für Reihen und Raster von Bohrungen, Rippen, Stiften oder Füßen.", + "help.solid.pipe": "Erzeugt ein rundes Rohr entlang eines Pfads aus Skizzenkurven, massiv oder hohl mit Wandstärke. Für Rohre, Drähte, Kabel und Geländer.", + "help.solid.press_pull": "Fügt Material hinzu oder trägt es ab, indem Sie eine Fläche ziehen. Durch Ziehen an einer Kante können Sie diese abrunden. So lassen sich schnelle Änderungen direkt am Modell vornehmen.", + "help.solid.remove": "Entfernt die ausgewählten Körper ab dieser Stelle der Timeline aus dem Design. In den vorherigen Schritten bleiben sie erhalten. So können Sie beispielsweise einen nicht mehr benötigten Hilfs- oder Schneidkörper entfernen.", + "help.solid.replace_face": "Verschiebt die ausgewählten ebenen Flächen auf eine Ebene oder eine parallele Fläche. Der Körper wird dabei entsprechend vergrößert oder verkleinert. So können Sie eine Fläche bündig zu einem anderen Bauteil oder einer Konstruktionsebene ausrichten.", "help.solid.revolve": "Dreht ein Skizzenprofil um eine Achse und erzeugt so einen runden Körper. Für Wellen, Knöpfe, Schalen und alle Teile, die um eine Mittellinie rund sind.", + "help.solid.rib": "Fügt entlang einer offenen Skizzenkurve eine dünne Wand hinzu, die bis zu den nächsten Flächen des Körpers reicht. Damit versteifen Sie Wände und Ecken, etwa bei Spritzguss- oder Druckteilen.", + "help.solid.scale": "Skaliert die ausgewählten Körper mit einem festgelegten Faktor, gleichmäßig in alle Richtungen oder getrennt entlang der einzelnen Achsen. So können Sie beispielsweise importierte Geometrien anpassen oder Materialschwindung berücksichtigen.", "help.solid.shell": "Höhlt einen Körper aus, lässt Wände in der eingestellten Dicke stehen und kann gewählte Flächen öffnen. Für Kästen, Deckel und andere dünnwandige Teile.", + "help.solid.sphere": "Erzeugt eine Kugel aus Radius oder Durchmesser um einen Mittelpunkt. Für Kugeln, Knäufe und abgerundete Enden.", + "help.solid.split_body": "Teilt einen Körper mithilfe einer Ebene, der Fläche eines anderen Körpers oder einer Skizzenlinie in mehrere getrennte Körper. So können Sie Bauteile erstellen, die einzeln gedruckt, bearbeitet oder eingefärbt werden können.", + "help.solid.split_face": "Teilt die ausgewählten Flächen entlang einer Ebene, der Fläche eines anderen Körpers oder von Skizzenkurven, ohne den Körper selbst zu teilen. So können Sie Teilbereiche einer Fläche mit einer eigenen Formschräge, Farbe oder einem Versatz versehen.", "help.solid.sweep": "Führt ein Skizzenprofil entlang eines Pfads und erzeugt so einen Körper. Für Rohre, Schienen, Griffe und alle Teile mit gleichbleibendem Querschnitt entlang einer Kurve.", + "help.solid.thread": "Versieht eine zylindrische Fläche mit einem metrischen ISO-Gewinde, als kosmetisches Gewinde oder in den Körper geschnitten. Für Schrauben, Gewindebohrungen und gedruckte Schraubteile.", + "help.solid.torus": "Erzeugt einen Ring aus einem großen Radius um seine Achse und einem kleinen Radius für seinen runden Querschnitt. Für O-Ringe, Griffe und runde Wülste.", + "help.solid.web": "Fügt entlang jeder offenen Skizzenkurve eine dünne Wand hinzu, jede bis zu den nächsten Flächen des Körpers. Für ein Gitter aus Stützwänden in Gehäusen und Schalen.", + "help.surface.blend": "Erzeugt eine Fläche, die die Kanten zweier Körper überbrückt, tangential oder krümmungsstetig zu beiden. Damit verbinden Sie zwei Flächen glatt über eine Lücke.", + "help.surface.boundary": "Erzeugt eine Fläche, die eine Schleife aus zwei bis vier Skizzenkurven oder ein Kurvennetz füllt. Für Freiformflächen, die durch ihre Ränder bestimmt sind.", + "help.surface.extend": "Verlängert eine Fläche über ihre Kanten hinaus, um einen Abstand oder bis zu einer Ebene oder Fläche. Damit überlappen sich Flächen, bevor Sie sie trimmen oder vernähen.", + "help.surface.extrude": "Zieht Skizzenkurven oder Profile über eine Strecke zu einer Fläche, nur Wände ohne Deckel. Für dünne Wände und als Werkzeug zum Schneiden oder Teilen.", + "help.surface.fair": "Glättet das Innere von Freiformflächen, während ihre Kanten an Ort und Stelle bleiben. Damit gleichen Sie Beulen und wellige Spiegelungen in einer Fläche aus.", + "help.surface.loft": "Erzeugt eine Fläche, die der Reihe nach durch zwei oder mehr Querschnitte läuft, ohne Deckel. Für Schalen und Übergänge zwischen verschiedenen Formen.", + "help.surface.match": "Baut die Kante einer Fläche so neu auf, dass sie an die Kante eines anderen Körpers anschließt, mit passender Tangente oder Krümmung. Damit schließen Sie eine Naht zwischen zwei Flächen glatt.", + "help.surface.offset": "Erzeugt eine Kopie von Flächen in einem Abstand entlang ihrer Normalen, als neuen Flächenkörper. Für Häute, Spiele oder die Gegenseite einer Wand.", + "help.surface.patch": "Füllt einen Skizzenbereich oder eine geschlossene Kantenschleife mit einer Fläche, eben oder glatt gekrümmt. Damit schließen Sie Löcher in einem Flächenkörper.", + "help.surface.reverse_normal": "Dreht Flächen eines Flächenkörpers um, sodass ihre Außenseite in die andere Richtung zeigt. Vor dem Aufdicken oder Vernähen, wenn die Flächen nach innen zeigen.", + "help.surface.revolve": "Dreht Skizzenkurven oder Profile um eine Achse zu einer Fläche, ohne Deckel. Für runde Schalen wie Lampenschirme, Schüsseln und Düsen.", + "help.surface.ruled": "Erzeugt einen Streifen aus geraden Linien, der von einer Kantenkette ausgeht, entlang der Flächennormalen, tangential oder unter einem Winkel. Für Schrägwände, Ausläufe und Trennflächen.", + "help.surface.stitch": "Vernäht Flächenkörper entlang gemeinsamer Kanten, zu einem Volumenkörper, wenn sie sich schließen. Damit machen Sie aus mehreren Flächen einen Körper.", + "help.surface.sweep": "Führt Skizzenkurven oder Profile entlang eines Pfads zu einer Fläche, ohne Deckel. Für Rinnen, Leisten und andere dünne Formen, die einem Pfad folgen.", + "help.surface.thicken": "Gibt einem Flächenkörper eine Dicke und macht ihn so zum Volumenkörper. Damit machen Sie aus Flächen druck- oder fräsbare Teile.", + "help.surface.trim": "Schneidet eine Fläche mit einer Ebene, einer anderen Fläche oder Skizzenkurven und behält die gewählte Seite. Damit schneiden Sie Flächen vor dem Vernähen in Form.", + "help.surface.unstitch": "Löst Flächen eines Körpers als eigene Flächenkörper heraus; ein Volumenkörper zerfällt dabei in Flächen. Damit überarbeiten Sie einzelne Flächen eines Körpers.", + "help.surface.untrim": "Entfernt Löcher aus einer Fläche oder stellt ihren äußeren Rand auf die natürlichen Grenzen der Fläche zurück. Damit holen Sie nach einem Trimmen die volle Fläche zurück.", "help.third_party": "Drittanbieterlizenzen", + "help.timeline.compute_all": "Berechnet alle Features der Timeline von Anfang an neu. Dadurch wird das Modell aktualisiert und Sie sehen, bei welchen Features Berechnungsfehler auftreten.", + "help.timeline.delete": "Löscht die ausgewählten Features aus der Timeline. Beim Löschen einer Skizze werden auch alle daraus erstellten Features gelöscht. So können Sie nicht mehr benötigte Konstruktionsschritte entfernen.", + "help.timeline.dependents": "Listet die Elemente, die mit einem Element gelöscht würden, und die, die ohne es fehlschlagen würden. Bevor Sie ein Element löschen oder ändern.", "help.timeline.play": "Die verbleibenden Features nacheinander abspielen, mit einer halben Sekunde Pause nach jedem Neuaufbau. Diesen Befehl erneut ausführen oder Escape drücken, um anzuhalten; Zum Ende springt sofort ans Ende.", + "help.view.apply": "Dreht die Ansicht in eine Standardrichtung wie vorne, oben oder iso oder zu einer gespeicherten Ansicht. Damit betrachten Sie das Modell aus einem festen Winkel.", + "help.view.delete": "Löscht eine gespeicherte Ansicht. Das Modell bleibt unverändert.", + "help.view.fit": "Zoomt und verschiebt so, dass das ganze Modell oder die Auswahl die Ansicht füllt. Wenn das Modell aus dem Blick geraten ist.", + "help.view.grid": "Blendet das Raster im Ansichtsfenster ein oder aus. Als Größen- und Orientierungshilfe beim Modellieren.", + "help.view.ground_shadow": "Blendet den Schatten des Modells auf dem Boden ein oder aus. Damit schätzen Sie Höhe und Lage leichter ein.", + "help.view.home": "Dreht die Ansicht zurück in die Ausgangsrichtung und zeigt das ganze Modell. Damit kommen Sie schnell zu einer bekannten Ansicht zurück.", + "help.view.list": "Listet die im Design gespeicherten Ansichten auf. Damit finden Sie eine früher gespeicherte Ansicht.", + "help.view.navigate": "Dreht, verschiebt oder zoomt die Ansicht schrittweise, etwa eine Vierteldrehung nach links. Damit bewegen Sie die Kamera genau statt durch Ziehen.", + "help.view.navigation_bar": "Blendet die Navigationsleiste unten im Ansichtsfenster ein oder aus. Ausblenden für mehr Platz, einblenden, um die Ansichtswerkzeuge per Maus zu erreichen.", + "help.view.rename": "Gibt einer gespeicherten Ansicht einen neuen Namen. Die Ansicht selbst bleibt gleich.", + "help.view.save": "Speichert die aktuelle Kameraposition als benannte Ansicht im Design. Damit kehren Sie später zum selben Blickwinkel zurück, etwa für Screenshots.", + "help.view.spin": "Dreht die Ansicht fortlaufend um das Modell, bis zum nächsten Klick oder Tastendruck. Damit präsentieren Sie ein Modell von allen Seiten.", + "help.view.tool": "Schaltet ein Kamerawerkzeug fest, Drehen, Verschieben oder Zoomen, sodass Ziehen mit der linken Maustaste die Ansicht bewegt, bis Sie es abschalten. Für Touchpads oder Mäuse ohne mittlere Taste.", + "help.view.visual_style": "Schaltet um, wie das Modell gezeichnet wird: schattiert mit oder ohne Kanten, Drahtmodell oder mit verdeckten Kanten. Drahtmodell zum Hineinschauen, schattiert für ein sauberes Bild.", "history.sketch_under_constrained": "Unterbestimmt ({count} Freiheitsgrade)", "history.sketch_under_constrained_one": "Unterbestimmt ({count} Freiheitsgrad)", "hole_presets.confirm_delete": "Löschen bestätigen", @@ -1478,6 +1863,27 @@ "home.start_hint": "Erstellen Sie einen Entwurf, öffnen Sie eine zuletzt verwendete Datei oder erkunden Sie ein Beispiel.", "home.whats_new": "Neuigkeiten", "home.yesterday": "Gestern", + "import_report.details": "Details:", + "import_report.file_one": "Die Datei hatte 1 weiteres Problem.", + "import_report.file_other": "Die Datei hatte {count} weitere Probleme.", + "import_report.hint": "Die Teile erneut aus dem Programm zu exportieren, mit dem sie erstellt wurden, kann das beheben. „Warnmeldung kopieren“ enthält die Details.", + "import_report.left_out_one": "1 Fläche konnte nicht repariert werden und fehlt.", + "import_report.left_out_other": "{count} Flächen konnten nicht repariert werden und fehlen.", + "import_report.needs_repair_one": "1 Teil muss repariert werden, bevor daran modelliert werden kann.", + "import_report.needs_repair_other": "{count} Teile müssen repariert werden, bevor daran modelliert werden kann.", + "import_report.not_imported_one": "1 Teil konnte nicht importiert werden.", + "import_report.not_imported_other": "{count} Teile konnten nicht importiert werden.", + "import_report.not_shown_one": "1 Fläche konnte nicht gezeichnet werden und ist ausgeblendet.", + "import_report.not_shown_other": "{count} Flächen konnten nicht gezeichnet werden und sind ausgeblendet.", + "import_report.open_one": "1 Teil hat Lücken zwischen seinen Flächen und kam als offener Körper herein.", + "import_report.open_other": "{count} Teile haben Lücken zwischen ihren Flächen und kamen als offene Körper herein.", + "import_report.refused_one": "1 Teil konnte nicht zu einem Volumenkörper werden und wurde nicht importiert.", + "import_report.refused_other": "{count} Teile konnten nicht zu Volumenkörpern werden und wurden nicht importiert.", + "import_report.repaired_one": "Kleine Fehler wurden an 1 Teil repariert.", + "import_report.repaired_other": "Kleine Fehler wurden an {count} Teilen repariert.", + "import_report.solids": "{solids} von {parts} Teilen als Volumenkörper importiert.", + "import_report.surfaces_one": "1 Teil konnte nicht zu einem Volumenkörper werden und kam als Flächen herein.", + "import_report.surfaces_other": "{count} Teile konnten nicht zu Volumenkörpern werden und kamen als Flächen herein.", "install.button_tip": "SolidCraft als App installieren: eigenes Fenster, funktioniert auch offline", "install.dock_1": "Wählen Sie Ablage › Zum Dock hinzufügen.", "install.dock_2": "Klicken Sie auf „Hinzufügen“.", @@ -1507,6 +1913,23 @@ "joint.one_component": "Diese Teile sind Körper einer Komponente: {bodies}. Ein Gelenk bewegt eine Komponente gegenüber einer anderen, daher braucht jedes Teil eine eigene Komponente.", "joint.rigid_group_one_component": "Diese {count} Körper liegen alle in einer Komponente (oder direkt im Design): Verwenden Sie zuerst {command}.", "joint.rigid_group_select_components": "Wählen Sie zwei oder mehr Komponenten aus.", + "joint_move.blocked_hint": "Prüfen Sie den Gelenktyp (z. B. „Starr“), die Fixierung, die Gelenkgrenzen und die durch Parameter gesteuerten Werte.", + "joint_move.blocked_title": "Dieses Bauteil kann nicht bewegt werden", + "joint_move.coarse": "Schritt nahe der Achse", + "joint_move.conflict": "Ein Gelenk dieses Bauteils steht im Konflikt mit den anderen: {joint}.", + "joint_move.conflict_hint": "Bearbeiten, unterdrücken oder löschen Sie das widersprüchliche Gelenk, damit die anderen Gelenke das Bauteil platzieren können.", + "joint_move.distance": "Abstand vom Ausgangspunkt", + "joint_move.done": "Fertig", + "joint_move.fine": "Schritt fern der Achse", + "joint_move.fixed": "Dieses Bauteil verfügt über keine bewegliche Gelenkachse.", + "joint_move.help": "Verschieben: Ziehen Sie einen Pfeil oder Ring. Mit Esc brechen Sie den aktuellen Ziehvorgang ab.", + "joint_move.legacy_hint": "Aus: das bisherige Verschieben-Panel.", + "joint_move.precision": "Für den feinen Schritt außerhalb der gestrichelten Führung ziehen.", + "joint_move.rotation": "Drehwinkel vom Ausgangspunkt", + "joint_move.select": "Wählen Sie eine Fläche oder eine Baugruppenkomponente aus und anschließend „Verschieben“.", + "joint_move.settings": "Baugruppe verschieben", + "joint_move.step": "Schrittweite", + "joint_move.use_handles": "Gelenkbewegungsgriffe für Verschieben verwenden", "keymap.command_id": "Befehls-ID", "keymap.empty": "Keine passenden Befehle", "keymap.use_anyway": "{key} hier trotzdem verwenden", @@ -1566,6 +1989,11 @@ "material.selection.mixed": "Unterschiedliche Materialien", "measure.at": "Bei", "measure.item": "Element {number}", + "measure.line_to_centre": "Linie zum Mittelpunkt", + "measure.quick_copied": "Messwert kopiert", + "measure.quick_copy": "Klicken, um den Messwert zu kopieren", + "measure.quick_edges": "{count} Kanten", + "measure.quick_faces": "{count} Flächen", "messages.ago_h": "vor {n} Std.", "messages.ago_min": "vor {n} Min.", "messages.ago_s": "vor {n} Sek.", @@ -1590,6 +2018,8 @@ "motion.track_name": "Spur {number}", "nav.alias.help": "Umschalt+Alt+Linksziehen dreht, Umschalt+Alt+Mitte verschiebt, Umschalt+Alt+Rechtsziehen zoomt; mittleres Ziehen verschiebt ebenfalls und rechtes Ziehen dreht", "nav.blender.help": "Mittlere Maustaste dreht, Umschalt+Mitte verschiebt, Strg+Mitte zoomt; rechtes Ziehen lässt die Kamera unverändert", + "nav.creo.help": "Ziehen mit der mittleren Maustaste dreht, Umschalt+Mitte verschiebt, Strg+Mitte zoomt beim vertikalen Ziehen (nach unten zum Vergrößern); das Mausrad zoomt", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Maus und 3D-Maus drehen über beide Pole hinweg und behalten die Rollneigung bei. Das Einrasten mit Umschalt ist deaktiviert.", "nav.free_orbit.label": "Freie Drehung", "nav.free_orbit.snap_help": "Maus und 3D-Maus drehen über beide Pole hinweg und behalten die Rollausrichtung bei. Halten Sie beim Ziehen zum Drehen die Umschalttaste gedrückt, um Blickrichtung und Rollausrichtung einrasten zu lassen.", @@ -1599,6 +2029,7 @@ "nav.hfss.help": "Alt+Linksziehen verschiebt, Umschalt+Alt+Linksziehen zoomt, Strg+Linksziehen auf leerer Fläche dreht", "nav.inventor.help": "Mittlere Maustaste verschiebt, Umschalt+Mitte dreht, Strg+Mitte zoomt, rechte Maustaste dreht", "nav.maya.help": "Alt+Linksziehen dreht, Alt+Mitte verschiebt, Alt+Rechtsziehen zoomt; mittleres Ziehen verschiebt ebenfalls", + "nav.nx.help": "Mittlere Maustaste dreht, Umschalt+Mitte verschiebt (in NX Mitte + rechts), Strg+Mitte zoomt (in NX Mitte + links); rechtes Ziehen lässt die Kamera unverändert", "nav.openscad.help": "Linksziehen auf leerem Hintergrund dreht, Umschalt+Linksziehen zieht ein Auswahlrechteck auf, Skizzengeometrie wird durch Ziehen bearbeitet; rechtes oder mittleres Ziehen verschiebt, Umschalt+rechtes oder Umschalt+mittleres Ziehen zoomt", "nav.perspective.sketch": "Beim Bearbeiten einer Skizze wird die orthografische Ansicht verwendet. Beenden Sie die Skizze, um die Perspektive umzuschalten.", "nav.right_drag_orbits.help": "Aus: rechtes Ziehen lässt die Kamera unverändert, die rechte Maustaste öffnet nur das Kontextmenü. Die Mausbelegung SolidWorks schaltet es beim Auswählen aus.", @@ -1617,6 +2048,12 @@ "navbar.assistant": "Assistent", "navbar.custom.add_slot": "{slot} hinzufügen", "navbar.custom.always": "Immer sichtbar", + "navbar.custom.anchor.bottom_centre": "Unten mittig", + "navbar.custom.anchor.bottom_left": "Unten links", + "navbar.custom.anchor.bottom_right": "Unten rechts", + "navbar.custom.anchor.top_centre": "Oben mittig", + "navbar.custom.anchor.top_left": "Oben links", + "navbar.custom.anchor.top_right": "Oben rechts", "navbar.custom.available": "{available} · auf die Leiste ziehen oder auf Hinzufügen klicken", "navbar.custom.buttons": "Schaltflächen", "navbar.custom.compact": "Kompakt", @@ -1653,6 +2090,7 @@ "navbar.custom.reset_default": "Auf Standard zurücksetzen", "navbar.custom.right": "Nach rechts", "navbar.custom.select": "Kein Feld ausgewählt. Wählen Sie ein Feld in der Leiste, um es zu verschieben, zu entfernen oder sein Aussehen zu ändern.", + "navbar.custom.separator_hint": "Eine Trennlinie zwischen Gruppen von Schaltflächen. Auf die Leiste ziehen oder auf Hinzufügen klicken; beliebig oft verwendbar.", "navbar.custom.separators_full": "Die Leiste hat bereits vier Trennlinien.", "navbar.custom.show": "Navigationsleiste anzeigen", "navbar.custom.shows": "Zeigt", @@ -1718,6 +2156,11 @@ "not a move": "keine Verschiebung", "not a number": "keine Zahl", "open a sketch first": "zuerst eine Skizze öffnen", + "parameters.apply_live": "Jede Änderung beim Verlassen des Feldes übernehmen", + "parameters.apply_live_tip": "Aus: Änderungen warten auf Übernehmen oder OK, dann wird das Modell einmal für alle neu aufgebaut. Abbrechen oder Esc verwirft sie.", + "parameters.held": "{count} Änderungen warten auf Übernehmen", + "parameters.held_hint": "Bearbeiten Sie Ausdrücke und Einheiten. Änderungen warten auf Übernehmen oder OK.", + "parameters.held_one": "1 Änderung wartet auf Übernehmen", "parts.automatic_name": "automatisch", "parts.dimension.across_flats": "Schlüsselweite", "parts.dimension.bore": "Bohrung", @@ -1736,10 +2179,19 @@ "parts.family.button_head_cap_screw": "Linsenkopfschraube mit Innensechskant", "parts.family.dowel_pin": "Zylinderstift", "parts.family.hex_bolt": "Sechskantschraube", + "parts.family.hex_cap_screw_inch": "Sechskantschraube (Zoll)", "parts.family.hex_nut": "Sechskantmutter", + "parts.family.hex_nut_inch": "Sechskantmutter (Zoll)", "parts.family.set_screw": "Gewindestift mit Innensechskant und Kegelstumpf", "parts.family.socket_head_cap_screw": "Zylinderschraube mit Innensechskant", "parts.family.washer": "Unterlegscheibe", + "parts.family.washer_sae": "Unterlegscheibe, SAE (schmal)", + "parts.family.washer_uss": "Unterlegscheibe, USS (breit)", + "parts.holes": "Bohrungen (optional)", + "parts.placement_hint": "Wählen Sie eine oder mehrere Bohrungen, um in jede ein Teil einzusetzen, oder OK platziert es im Ursprung", + "parts.system": "Maßsystem", + "parts.system.inch": "Zoll", + "parts.system.metric": "Metrisch", "pattern.alignment_2": "Ausrichtung 2", "pattern.alignment_hint": "Die Anzahl enthält das Original. Die zentrierte Anordnung verteilt Kopien auf beide Seiten; bei gerader Anzahl legt die Richtungsumkehr die Seite mit der zusätzlichen Kopie fest.", "pattern.direction_1": "Richtung 1", @@ -1778,18 +2230,52 @@ "prefs.alt_frees_manipulators": "Alt / Option schaltet auch an Manipulatorpfeilen das Einrasten ab", "prefs.anti_aliasing_amd_dx12": "Die Kantenglättung verwendet 1×, da der Starttest mit Multisampling keine Ausgabe erzeugt hat, während der Test mit 1× erfolgreich war. Sie können oben eine andere Einstellung wählen. Starten Sie SolidCraft neu, damit die Änderung übernommen wird, sofern der Test erfolgreich ist.", "prefs.anti_aliasing_note": "Glättet gezackte Kanten.", + "prefs.appearance.colour_vision_help": "Ändert die bedeutungstragenden Farben: Skizzenzustände, Achsen, Biegungen, Analysen und Symbole.", + "prefs.appearance.desktop_only": "Nur Desktop", + "prefs.appearance.follow_help": "Wird neu geladen, wenn ein anderes Werkzeug die Datei überschreibt.", + "prefs.appearance.interface_scale": "Oberflächenskalierung", + "prefs.appearance.next_themes": "Nächste Designs", + "prefs.appearance.option_count": "{count} Optionen", + "prefs.appearance.option_count_one": "{count} Option", + "prefs.appearance.previous_themes": "Vorherige Designs", + "prefs.appearance.theme_count": "{count} Designs", + "prefs.appearance.theme_own": "Eigene Designfarben", + "prefs.appearance.viewport_colours": "Farben der 3D-Ansicht", + "prefs.appearance.viewport_logo": "Ansichtsfenster und Logo", "prefs.applies_on_restart": "Wird nach einem Neustart übernommen", "prefs.assistant": "Assistent", + "prefs.assistant_connecting": "Verbindung", + "prefs.assistant_follow_help": "Look At bei Skizzen bewegt die Ansicht mit dem Zeiger.", + "prefs.assistant_limit": "Limit", + "prefs.assistant_limited": "Begrenzt", + "prefs.assistant_pointer_speed": "Zeigergeschwindigkeit", + "prefs.assistant_seconds": "Sekunden", + "prefs.assistant_seconds_aria": "Sekunden", + "prefs.assistant_use_care": "Mit Vorsicht verwenden", + "prefs.auto_operation": "Operation automatisch auswählen", + "prefs.auto_operation_note": "Vereinigung, Neuer Körper oder Schnitt, je nachdem, was das Material berührt.", "prefs.axes": "Achsen", "prefs.axis": "Achse", + "prefs.blur_cost": "Relativer Renderaufwand. Mehr Balken bedeuten meist mehr Arbeit.", + "prefs.blur_device": "Auf diesem Grafikgerät oder Renderpfad nicht verfügbar", + "prefs.blur_guard": "Die Unschärfequalität wurde für flüssigere Bilder verringert. Der Radius bleibt unverändert.", + "prefs.blur_off": "Aus", + "prefs.blur_reduce_transparency": "Durch die Systemeinstellung zur Transparenzreduzierung deaktiviert", + "prefs.blur_software": "Mit Softwaregrafik nicht verfügbar (gpu-software)", + "prefs.blur_source": "In dieser Arbeitsbereichsansicht nicht verfügbar", + "prefs.blur_web": "Auf diesem Web-Renderpfad nicht verfügbar", "prefs.bodies_folders": "Körperordner", "prefs.bodies_folders_always": "Immer", "prefs.bodies_folders_never": "Nie", - "prefs.bodies_folders_several": "Nur bei mehreren Körpern", + "prefs.bodies_folders_several": "Mehrere", "prefs.bottom": "Unten", "prefs.bottom_centre": "Unten mittig", "prefs.bottom_right": "Unten rechts", "prefs.browser": "Browser", + "prefs.browser_components_open": "Komponenten zu Beginn aufgeklappt", + "prefs.browser_components_open_note": "Jede Komponente im Browser ist wie bisher von Anfang an aufgeklappt, statt zugeklappt zu bleiben, bis du sie aufklappst.", + "prefs.browser_eye_left": "Auge neben dem Aufklapppfeil", + "prefs.browser_eye_left_note": "Browserzeilen zeigen ihr Auge zum Ein- und Ausblenden wie bisher neben dem Aufklapppfeil statt in einer Spalte am rechten Zeilenende.", "prefs.browser_reveal_on_hover": "Beim Überfahren einblenden", "prefs.browser_show_note": "Angezeigt lässt den Browser auf dem Bildschirm. Beim Überfahren einblenden blendet ihn aus, bis der Zeiger über seinen Platz oder die schmale Lasche an seinem linken Rand kommt; er bleibt offen, solange der Zeiger darin ist oder ein Menü daraus offen ist.", "prefs.browser_shown": "Angezeigt", @@ -1797,6 +2283,8 @@ "prefs.button_left": "Ziehen mit der linken Maustaste", "prefs.button_middle": "Ziehen mit der mittleren Maustaste", "prefs.button_right": "Ziehen mit der rechten Maustaste", + "prefs.carousel_next": "Weiter", + "prefs.carousel_previous": "Zurück", "prefs.choose_font": "Schriftdatei auswählen…", "prefs.click": "Klicken", "prefs.contact_shading": "Weiche Kontaktschattierung", @@ -1809,28 +2297,64 @@ "prefs.ctrl_cmd": "Strg / Cmd", "prefs.curved_surfaces": "Gekrümmte Flächen", "prefs.curves": "Gekrümmte Flächen", + "prefs.cut_preview_tint": "Entferntes Material rot anzeigen", + "prefs.cut_preview_tint_help": "Eine Vorschau füllt das Material, das ein Feature entfernt, sowie die ersetzte Form mit einem roten, durchscheinenden Geist. Wenn deaktiviert, sind diese Füllungen völlig transparent und es werden nur ihre Umrisse gezeichnet.", + "prefs.dark_parts_shading": "Form dunkler Teile erhalten", + "prefs.dark_parts_shading_help": "Die Ansicht in linearem Licht mit sanftem Himmelslicht schattieren, damit dunkle Flächen einen Verlauf behalten statt schwarz zu werden", "prefs.dead_zone_note": "Der schraffierte Bereich kennzeichnet die Totzone. Bewegungen innerhalb dieses Bereichs werden ignoriert.", "prefs.default": "Standard", - "prefs.design": "Design-Vorgaben", - "prefs.design_note": "Legt fest, mit welchen Einstellungen neue Designs beginnen. Bereits geöffnete Designs behalten ihre eigenen Einstellungen.", + "prefs.design": "Konstruktion", + "prefs.design_note": "Womit neue Konstruktionen beginnen.", + "prefs.design_tools.ask": "Fragen", + "prefs.design_tools.degrees": "Grad", + "prefs.design_tools.double_click_help": "Oder zum Bearbeiten einer verknüpften Komponente an Ort und Stelle.", + "prefs.design_tools.ghost": "Alte Position verschobener Teile als Geisterbild zeigen", + "prefs.design_tools.hole_moves_help": "Erneutes Auswählen der Fläche verschiebt die Bohrung, statt sie zu entfernen.", + "prefs.design_tools.hole_snaps_help": "Die Mitte einer Fläche und die Mittelpunkte ihrer kreisförmigen Kanten.", + "prefs.design_tools.imported_files": "Importierte Dateien", + "prefs.design_tools.note": "Hinweis", + "prefs.design_tools.off": "Aus", + "prefs.design_tools.placement_group": "Auflage, Zapfen, Schnappverbindung", + "prefs.design_tools.rows": "Zeilen", "prefs.devices": "3D-Maus", "prefs.dialog_buttons": "Dialogschaltflächen", "prefs.dialogs": "Dialoge", "prefs.dialogs_edge": "Am Rand der Ansicht", "prefs.dialogs_left_column": "In der linken Spalte", "prefs.dialogs_note": "Wo Befehlsdialoge öffnen: am Rand der Ansicht angedockt oder in der linken Spalte anstelle von Browser und Verlauf, die beim Schließen des Dialogs wie zuvor zurückkehren.", + "prefs.dimension_step_angle": "Was die Pfeile des Fensters, Auf/Ab und das Mausrad zu einem Winkel addieren", + "prefs.dimension_step_length": "Was die Pfeile des Fensters, Auf/Ab und das Mausrad zu einer Länge addieren", + "prefs.dimension_steps": "Schritte im Fenster", + "prefs.dimension_values": "Bemaßungswerte", + "prefs.dimension_values_note": "Wo der Wert einer Bemaßung eingegeben wird. Ein Fenster hat Pfeile, die ihn schrittweise ändern; das Bemaßungswerkzeug platziert zuerst den Text.", + "prefs.dimension_values_view": "In der Ansicht", + "prefs.dimension_values_window": "In einem Fenster", "prefs.display": "Anzeige", "prefs.drawings": "Zeichnungen", "prefs.edges": "Kanten und Schattierung", "prefs.extend": "Erweitern", "prefs.extra_navigation": "Mit Strg und gedrückter linker Maustaste auf einer freien Fläche drehen. Leertaste gedrückt halten, um die Ansicht zu verschieben.", + "prefs.extrude_view_isometric": "Beim Öffnen von Extrudieren isometrisch ausrichten", + "prefs.extrude_view_return": "Beim Schließen von Extrudieren zur vorigen Ansicht zurück", "prefs.follows_os": "Wie im Betriebssystem", "prefs.font": "Schrift", "prefs.font_fallback": "Zeichen, die in der ausgewählten Schrift fehlen, werden mit der integrierten Ersatzschrift dargestellt. So werden keine Beschriftungen als leere Kästchen angezeigt.", "prefs.font_sample": "Zwölf Boxkämpfer jagen Viktor quer über den großen Sylter Deich · Ø12,50 mm · 45,0° · 0123456789", "prefs.font_unreadable": "Die ausgewählte Schriftdatei konnte nicht gelesen werden.", "prefs.general": "Allgemein", - "prefs.general_note": "Sprache, Speichern und Updates.", + "prefs.general.active": "Aktiv", + "prefs.general.crash_reports": "Absturzberichte", + "prefs.general.edited": "Geändert", + "prefs.general.held": "Enthalten", + "prefs.general.import": "Importieren...", + "prefs.general.last_check": "Zuletzt geprüft: {time}", + "prefs.general.minutes": "Minuten", + "prefs.general.name_setup": "Dieses Setup benennen", + "prefs.general.profile_name": "Profilname", + "prefs.general.save_new": "Als neu speichern", + "prefs.general.step_import": "STEP und Import", + "prefs.general.this_computer": "Dieser Computer", + "prefs.general_note": "Profile, Sprache, Dateien und Updates.", "prefs.gesture_orbit": "Ansicht drehen", "prefs.gesture_pan": "Ansicht verschieben", "prefs.gesture_zoom": "Ansicht zoomen", @@ -1839,18 +2363,40 @@ "prefs.graphics_card_auto": "Automatisch", "prefs.graphics_card_missing": "Die gespeicherte Grafikkarte ist nicht verfügbar. Stattdessen wird „Automatisch“ verwendet.", "prefs.graphics_card_restart": "Diese Einstellung wird nach einem Neustart von SolidCraft wirksam. Die Umgebungsvariable WGPU_ADAPTER_NAME hat Vorrang vor dieser Auswahl.", + "prefs.graphics_card_unused": "Die gespeicherte Grafikkarte wurde für dieses Fenster nicht verwendet; die tatsächlich genutzte Karte steht unter Hilfe › Info und in der Statuszeile. Versuchen Sie Automatisch, oder setzen Sie WGPU_ADAPTER_NAME auf einen eindeutigen Teil des Kartennamens.", "prefs.graphics_note": "Wägen Sie Leistung und Darstellungsqualität gegeneinander ab. Jede Option veranschaulicht ihre Wirkung anhand eines Beispiels.", + "prefs.graphics_page.current_view": "Aktuelle Ansicht", + "prefs.graphics_page.fastest": "Am schnellsten", + "prefs.graphics_page.fold_items": "Elemente einklappen", + "prefs.graphics_page.in_view": "In der Ansicht", + "prefs.graphics_page.live_details": "Live-Details", + "prefs.graphics_page.own_mix": "Eigene Mischung", + "prefs.graphics_page.quick_measure": "Schnellmessung", + "prefs.graphics_page.reference_geometry_through_bodies": "Referenzgeometrie durch Körper hindurch", + "prefs.graphics_page.restart": "Neustart erforderlich", + "prefs.graphics_page.sharpest": "Am schärfsten", + "prefs.graphics_page.single_surface_analysis": "Einzelne Flächenanalyse", + "prefs.graphics_page.status_chips": "Status-Chips", + "prefs.graphics_page.subtitle": "Geschwindigkeit gegen Glätte abwägen.", + "prefs.graphics_page.supersampling": "Supersampling", + "prefs.graphics_page.supersampling_adaptive": "Nur solange die Ansicht stillsteht", + "prefs.graphics_page.surfaces_edges": "Flächen und Kanten", + "prefs.graphics_page.view_bar": "Auch in der Ansichtsleiste", "prefs.graphics_presets_note": "Mit den Profilen werden die unten aufgeführten Optionen gemeinsam eingestellt.", + "prefs.hide_constraint_glyphs_zoomed_out": "Bindungssymbole bei starkem Herauszoomen ausblenden", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Bindungssymbole verschwinden, wenn die Skizze so weit herausgezoomt ist, dass sie sie überladen würden. Aus: sie behalten bei jedem Zoom eine feste Bildschirmgröße.", "prefs.history": "Verlauf", "prefs.history_origin_bodies": "Ursprung und Körper oben zeigen", "prefs.history_origin_bodies_note": "Der Verlauf links oder unter dem Browser beginnt mit dem Körper-Ordner der aktiven Komponente und dem Ursprung, mit Augen und Menüs wie im Browser. Der Verlauf unten bleibt unverändert.", "prefs.history_play_button": "Schaltfläche „Verlauf abspielen“ in den Verlaufssteuerelementen", "prefs.history_play_button_note": "Fügt „Verlauf abspielen“ zwischen „Einen Schritt zurück“ und „Einen Schritt vor“ in die Verlaufssteuerelemente ein. Mit einem Rechtsklick auf die Steuerelemente lässt sich die Schaltfläche auch ein- oder ausblenden.", - "prefs.history_sketches": "Skizzen", + "prefs.history_sketches": "Skizzen im Verlauf", "prefs.history_sketches_in_order": "In Erstellungsreihenfolge", "prefs.history_sketches_note": "Wenn „Skizzen“ auf „Unter dem zugehörigen Feature“ eingestellt ist, wird jede Skizze im linken Verlauf eine Ebene unter dem ersten daraus erstellten Feature angezeigt, sofern der Bereich breit genug für die Namen ist. Die Timeline unten zeigt weiterhin die Reihenfolge, in der die Elemente erstellt wurden.", "prefs.history_sketches_under_feature": "Unter dem zugehörigen Feature", "prefs.hold_stop_snapping": "Gedrückt halten, um das Einrasten zu deaktivieren", + "prefs.home_fit_size": "Größe bei Home und Einpassen", + "prefs.home_fit_size_note": "Wie viel der Ansicht das Modell füllt, wenn Home, Einpassen, ein geöffnetes Design oder ein Ansichtswechsel am Navigator es einrahmt, unabhängig von der Einstellung darunter. 100 %: füllt die Ansicht zwischen den Leisten, dem Kompass und der Navigationsleiste.", "prefs.icons_only": "Nur Symbole", "prefs.imported_file": "Importierte Datei", "prefs.in_browser": "Im Browser", @@ -1859,38 +2405,106 @@ "prefs.interface_language": "Oberflächensprache", "prefs.interface_note": "Legt das Erscheinungsbild von SolidCraft und die Anordnung seiner Bereiche fest.", "prefs.interval_minutes": "{n} min", + "prefs.invert_navigator_arrows": "Drehpfeile des Ansichtswürfels umkehren", + "prefs.invert_navigator_arrows_note": "Die Pfeile um den Würfel drehen die Kamera in die Richtung, in die sie zeigen, wie in Fusion und Inventor: Der linke Pfeil zeigt nach rechts und schwenkt die Kamera nach rechts. Aus: Ein Pfeil dreht den Würfel zu der Seite hin, an der er sitzt, sodass der linke Pfeil die Kamera nach links schwenkt. Die gebogenen Rollpfeile sind davon nicht betroffen.", + "prefs.keep_work_on_tab_switch": "Dialoge und Werkzeuge beim Wechsel zwischen Konstruktionen offen lassen", + "prefs.keep_work_on_tab_switch_note": "Jeder Konstruktions-Tab behält seinen offenen Dialog oder sein Werkzeug mit allem, was darin ausgewählt und eingegeben wurde, sowie seinen Werkzeugleisten-Tab. Beim Zurückkehren zur Konstruktion ist alles wieder da. Aus: Ein Wechsel bricht sie ab und zeigt den Tab Modell.", "prefs.labels": "Beschriftungen", + "prefs.language_system": "System", "prefs.layout": "Layout", "prefs.layout_note": "Im Layout „Kompakt“ werden Bereiche an den Fensterrändern angedockt. Transparenz für den Browser ist nur im Layout „Schwebend“ verfügbar. Die Position des Assistenten ändern Sie auf der Seite „Assistent“.", + "prefs.layout_page.active_commands": "Aktive Befehle hervorheben", + "prefs.layout_page.always": "Immer", + "prefs.layout_page.card": "Karte", + "prefs.layout_page.column": "Spalte", + "prefs.layout_page.hover": "Bei Mauszeiger", + "prefs.layout_page.icons_labels": "Symbole + Beschriftungen", + "prefs.layout_page.ok_cancel": "OK und Abbrechen", + "prefs.layout_page.on_hover": "Bei Mauszeiger", + "prefs.layout_page.open": "Öffnen", + "prefs.layout_page.origin_bodies": "Ursprung und Körper oben", + "prefs.layout_page.panels": "Bereiche", + "prefs.layout_page.pinned_menus": "Angeheftete Befehle aus Menüs ausblenden", + "prefs.layout_page.play_history": "Verlaufswiedergabe", + "prefs.layout_page.slot_count": "{count} von {max} Plätzen", + "prefs.layout_page.view_corner": "Auch in der Ansichtsecke", + "prefs.layout_page.window": "Fenster", "prefs.left": "Links", "prefs.left_click": "Linksklick", "prefs.line_drag_draws_one": "Drücken und Ziehen zeichnet eine Linie", "prefs.line_drag_draws_one_note": "Im Linienwerkzeug zeichnet Drücken, Ziehen und Loslassen eine Linie vom Drückpunkt bis zum Loslassen, und dort endet sie. Klicks zeichnen weiterhin eine Kette. Aus: Ein Ziehen setzt wie ein Klick einen Punkt dort, wo losgelassen wird.", + "prefs.line_hover_tangent_arc": "Auf dem letzten Linienpunkt verweilen, um zum Tangentialbogen zu wechseln", + "prefs.line_hover_tangent_arc_note": "Im Linienwerkzeug: Nach einem Segment vom letzten Punkt der Kette wegbewegen, zurückkehren und den Zeiger still darauf halten. Der nächste Klick beendet dann einen Tangentialbogen, und dieselbe Geste wechselt zurück zu Linien. Aus: Das Verweilen bewirkt nichts.", "prefs.linked_designs": "Verknüpfte Designs", + "prefs.live_input": "Live-Eingabe", + "prefs.live_preview": "Live-Vorschau", + "prefs.logo": "Logo", + "prefs.logo_accent": "Akzentfarbe", + "prefs.logo_theme": "Designfarben", "prefs.max_file_size": "Maximale Dateigröße zum Öffnen", - "prefs.max_file_size_design": "Designdateien", + "prefs.max_file_size_design": "Größte zu öffnende Datei: Entwurf", "prefs.max_file_size_flag": "Dieser Lauf wurde mit --max-file-size {size} gestartet. Der Wert gilt, bis SolidCraft geschlossen wird. Diese Einstellungen gelten beim Start ohne diese Option.", "prefs.max_file_size_note": "Standard: 512 MB und 256 MB; höchstens 16 GB. Das Öffnen einer Datei benötigt ein Mehrfaches ihrer Größe im Arbeitsspeicher. Ein Design mit großem Import benötigt zum Speichern und erneuten Öffnen eventuell eine höhere Grenze für Designdateien.", - "prefs.max_file_size_step": "STEP- und Importdateien", + "prefs.max_file_size_step": "Größte zu öffnende Datei: STEP und Import", "prefs.max_file_size_web": "Die Web-App öffnet STEP- und Importdateien bis 512 MB und Designs bis 256 MB: Ein Browser-Tab kann keine größeren Dateien aufnehmen. In der Desktop-App lassen sich diese Grenzen erhöhen.", "prefs.megabytes": "MB", "prefs.menu_grid": "Große Symbole", "prefs.menu_list": "Liste", "prefs.menus": "Menüs", + "prefs.minutes": "Minuten", "prefs.minutes_suffix": " min", + "prefs.mouse": "Maus und Trackpad", + "prefs.mouse_heading": "Maus", + "prefs.mouse_mapping": "Mausbelegung", + "prefs.navigation": "Navigation", + "prefs.navigation.axes_signed": "Achsen", + "prefs.navigation.cube_compact": "Würfel", + "prefs.navigation.device": "Gerät", + "prefs.navigation.free": "Frei", + "prefs.navigation.orbit_style": "Drehstil", + "prefs.navigation.radial_help": "Die rechte Taste halten oder kurz bewegen, um einen Werkzeugring zu öffnen.", + "prefs.navigation.turntable": "Drehteller", + "prefs.navigation_note": "Legt fest, wie Maus, Trackpad und 3D-Maus die Ansicht steuern.", + "prefs.navigator_fit": "Modell nach einem Ansichtswechsel am Navigator einpassen", + "prefs.navigator_fit_note": "Eine Fläche, Ecke oder ein Pfeil des Würfels oder eine Achse des Gizmos blickt auch auf die Mitte des Modells, aus dem einen Abstand, der es von jeder Seite einpasst (seine Hüllkugel). Home nutzt denselben Zoom und dieselbe Mitte, solange dies an ist, sodass danach gewählte Ansichten sich nur drehen. Aus: Die Ansicht dreht sich an Ort und Stelle und behält Ziel und Zoom.", + "prefs.network_host_remove": "Entfernen", + "prefs.network_locations": "Netzwerkspeicherorte in Designs zulassen", + "prefs.network_locations_note": "Für Organisationen, die Entwürfe auf Dateiservern speichern. Aus: nur erlaubte Server.", + "prefs.network_locations_section": "Netzwerkspeicherorte", + "prefs.not_on_gpu": "Auf dieser GPU nicht verfügbar", + "prefs.on": "An", + "prefs.opaque": "Undurchsichtig", + "prefs.orbit_snap": "Halten Sie beim Drehen die Umschalttaste gedrückt, um die Ansicht an einer Achse einrasten zu lassen.", + "prefs.orientation": "Ausrichtung", "prefs.origin_plane_names": "Namen der Ursprungsebenen", "prefs.origin_plane_names_note": "Namen in Browser, Dialogen und Listen. {top} ist XY, {front} ist XZ und {right} ist YZ, mit Z nach oben. Befehle, Skripte und gespeicherte Konstruktionen behalten XY, XZ und YZ.", + "prefs.overall_speed": "Gesamtgeschwindigkeit", + "prefs.parameter_list_rows": "Zeilen der Parameterliste", + "prefs.parameter_list_rows_tip": "Maximale Anzahl der Parameter, die Pfeil abwärts in einem leeren Ausdrucksfeld auflistet.", "prefs.persistent_ribbon_pressed": "Aktive Menübandbefehle hervorheben", "prefs.persistent_ribbon_pressed_help": "Hebt Befehle im Menüband hervor, solange ihre Effekte eingeschaltet sind. Deaktivieren Sie diese Option, um die bisherige neutrale Darstellung und Befehlshilfe beizubehalten.", "prefs.perspective_fov": "Sichtfeld", + "prefs.placement": "Platzierung", + "prefs.plugins_enabled": "Aktiviert", + "prefs.plugins_installed": "Installiert", + "prefs.plugins_intro": "Isolierte Erweiterungen.", + "prefs.plugins_show_folder": "Plugin-Ordner anzeigen", + "prefs.prefer_free_sketch_points": "Bei überlappenden Punkten bewegliche Skizzenpunkte bevorzugen", + "prefs.preview_choices": "Vorschau Ihrer Einstellungen", + "prefs.preview_tint_new_faces": "Neue Fläche in der Vorschau einfärben", + "prefs.preview_tint_new_faces_help": "Eine Vorschau eines Features, das einen Körper ändert, kann die hinzugefügte Fläche in der Vorschaufarbe zeichnen. Wenn deaktiviert, wird der Körper wie er ist gezeichnet.", + "prefs.print_face_highlight": "Hervorhebung der Auflagefläche", + "prefs.print_face_highlight_tip": "Wie stark die Auflagefläche eines Körpers in der Ansicht eingefärbt und umrandet wird. 0 % zeigt keine Hervorhebung.", "prefs.profile_active": "Aktives Profil", "prefs.profile_applied": "Profil angewendet.", "prefs.profile_changed": "Die Einstellungen wurden seit dem Speichern des Profils geändert. „Speichern“ übernimmt sie ins Profil.", "prefs.profile_deleted": "Profil gelöscht.", - "prefs.profile_export": "Exportieren…", + "prefs.profile_export": "Exportieren", "prefs.profile_exported": "Profil exportiert.", - "prefs.profile_imported": "Profil importiert. Unter „Aktives Profil“ auswählen, um dazu zu wechseln.", + "prefs.profile_imported": "Profil importiert.", "prefs.profile_name_hint": "Profilname, z. B. Laptop", + "prefs.profile_operations": "Vorgänge profilieren", + "prefs.profile_operations_note": "Zeichnet auf, wie lange SMLib-Aufrufe, Kernel-Vorgänge, Features, Befehle und Importe dauern. Agenten lesen es mit diagnostics.profile.", "prefs.profile_rename": "Umbenennen", "prefs.profile_renamed": "Profil umbenannt.", "prefs.profile_save": "Speichern", @@ -1900,34 +2514,136 @@ "prefs.profiles_note": "Tastenkürzel, Werkzeugleiste, Navigation, Radialmenü und Oberflächeneinstellungen, gemeinsam unter einem Namen gespeichert und auf einmal umgeschaltet.", "prefs.project_options_dialog": "Project-Optionendialog", "prefs.project_options_dialog_note": "Ein: Vor dem Projizieren Geometrie oder Körper und die Projektionsverknüpfung auswählen. Aus: Den bisherigen Direktwahl-Ablauf beibehalten.", + "prefs.quality_default": "Standard", + "prefs.quality_fastest": "Am schnellsten", + "prefs.quality_slowest": "Am langsamsten", + "prefs.quality_smoother": "Stärker geglättet", + "prefs.quick_measure": "Schnellmessung in der Ecke der Ansicht", + "prefs.quick_measure_note": "Zeigt unten rechts in der Ansicht die Größe der Auswahl an: bei einer Kante die Länge, bei einer kreisförmigen Kante zusätzlich Durchmesser (Ø) und Radius (R), bei einer Fläche den Flächeninhalt, bei einem Punkt die Position, bei zwei Elementen Abstand und Winkel sowie bei mehreren Kanten oder Flächen die Gesamtlänge bzw. Gesamtfläche. Ein Klick kopiert den Messwert.", + "prefs.render_previous_geometry_budget": "Bisheriges Geometriebudget für die Render-Vorschau verwenden", + "prefs.render_previous_geometry_budget_help": "Stellt die bisherige feste Obergrenze für die Geometrie wieder her (512 MiB auf 64-Bit-Desktop-Systemen, andernfalls 128 MiB) anstelle des geräteabhängigen Budgets.", + "prefs.reports_saved": "{n} gespeichert", + "prefs.restore_page_defaults": "Seitenstandardwerte wiederherstellen", + "prefs.ribbon_click_ends_tool": "Klick auf die Schaltfläche des laufenden Werkzeugs beendet es", + "prefs.ribbon_click_ends_tool_note": "Ein Klick auf die hervorgehobene Schaltfläche des aktiven Skizzenwerkzeugs beendet das Werkzeug, sodass Klicks in die Ansicht wieder auswählen. Aus: Der Klick startet das Werkzeug neu.", "prefs.ribbon_reveal": "Suchergebnisse im Menüband zeigen", "prefs.ribbon_reveal_note": "Steht der Zeiger über einem Ergebnis in Befehle suchen, zeigt das Menüband, wo der Befehl liegt: seine Registerkarte, seine Schaltfläche oder seine Zeile im Aufklappmenü eines Panels. Ein aus der Suche gestarteter Befehl blinkt dort, und ein laufender Befehl aus einem Aufklappmenü markiert sein Panel.", + "prefs.right_click": "Rechtsklick", + "prefs.saving": "Starten und Speichern", + "prefs.scale_note": "Die Skalierung lässt sich auch mit Strg + / Strg − im Fenster ändern. Bei 100 % sind die Schaltflächen 28 px groß.", + "prefs.scale_text": "Skalierung und Text", "prefs.search": "Einstellungen suchen", "prefs.search_empty": "Keine passenden Einstellungen", + "prefs.select": "Auswählen", + "prefs.select_one_item": "Ein Element auswählen", + "prefs.select_other_hidden": "Verborgene Geometrie mit „Andere auswählen“ auswählen", + "prefs.select_other_hidden_help": "Ein: Verborgene Körper, Skizzen und verdeckte Kanten nahe dem Zeiger einbeziehen. Aus: Die ursprüngliche Liste sichtbarer Geometrie direkt unter dem Zeiger verwenden.", + "prefs.selecting": "Auswahl", + "prefs.shift": "Umschalt", + "prefs.shift_add_ctrl_toggle": "Umschalt fügt nur hinzu; Strg / Cmd schaltet die Auswahl um", + "prefs.shift_add_note": "Aktiviert: Umschalt fügt Elemente zur Auswahl hinzu, Strg / Cmd schaltet ihre Auswahl um. Deaktiviert (Standard): Beide Tasten schalten die Auswahl um.", + "prefs.shortcuts": "Tastenkürzel", + "prefs.shortcuts_import": "Importieren", + "prefs.shortcuts_intro": "Tasten für jeden Befehl.", + "prefs.shortcuts_not_assigned": "Nicht zugewiesen", + "prefs.shortcuts_press": "Taste drücken...", "prefs.single_surface_analysis": "Nur eine Flächenanalyse verwenden", "prefs.single_surface_analysis_help": "Wenn deaktiviert, können Flächenschattierung und Stetigkeitsanalyse gleichzeitig aktiv bleiben. Beim Aktivieren bleibt die zuletzt gestartete oder geänderte Analyse erhalten.", + "prefs.sketch.align_points": "An anderen Skizzenpunkten ausrichten", + "prefs.sketch.align_points_note": "Beim Zeichnen richten sich Linien gleichzeitig an Punkten auf beiden Achsen aus.", + "prefs.sketch.auto_dimensions": "Neue Formen vollständig bemaßen", + "prefs.sketch.auto_dimensions_note": "Eingegebene Werte und alle Maße, die die Form festlegen.", + "prefs.sketch.auto_locate": "Vom Skizzenursprung aus positionieren", + "prefs.sketch.auto_locate_note": "Mit vollständiger Bemaßung.", + "prefs.sketch.center_arc": "Mittelpunktbogen folgt dem Zeiger", + "prefs.sketch.click_selects": "Klick wählt", + "prefs.sketch.conflict_colour": "Konfliktfarbe", + "prefs.sketch.drawing": "Zeichnen", + "prefs.sketch.exit_keep": "Beibehalten", + "prefs.sketch.exit_previous": "Zur Ansicht davor zurückkehren", + "prefs.sketch.exit_unless_rotated": "Außer bei Drehung", + "prefs.sketch.faces_edges": "Flächen und Kanten", + "prefs.sketch.hide_glyphs": "Symbole beim Herauszoomen ausblenden", + "prefs.sketch.marks": "Markierungen in der Skizze", + "prefs.sketch.note": "Zeichnen, Fangen und Auswählen.", + "prefs.sketch.opening_closing": "Öffnen und Schließen", + "prefs.sketch.prefer_free_points": "Bei Überlappung bewegliche Punkte bevorzugen", + "prefs.sketch.project_options": "Zuerst Projektionsoptionen abfragen", + "prefs.sketch.recent_snap": "Am Schnittpunkt zweier Hilfslinien fangen", + "prefs.sketch.select_other_hidden": "Andere auswählen erfasst verdeckte Geometrie", + "prefs.sketch.shortcut_cycles_modes": "Erneuter Kurzbefehl wechselt den Modus", + "prefs.sketch.shortcut_cycles_modes_tip": "Aus: Das Werkzeug startet erneut.", + "prefs.sketch.snapping_guides": "Fangen und Hilfslinien", + "prefs.sketch.state_icons": "Statussymbole", + "prefs.sketch.tracking_guides": "Hilfslinien für Mittelpunkte und Kantenmitten", + "prefs.sketch.tracking_guides_note": "Temporäre waagerechte und senkrechte Hilfslinien von überfahrenen Mittelpunkten und Kantenmitten.", + "prefs.sketch.tracking_points": "Hilfslinien auch von Skizzenpunkten", + "prefs.sketch.unless_turned_note": "zurück, wenn nicht gedreht", + "prefs.sketch.whole_bodies": "Ganze Körper", "prefs.sketch_align_points": "Beim Zeichnen an anderen Skizzenpunkten ausrichten", "prefs.sketch_align_points_note": "Beim Zeichnen richtet sich ein Punkt zugleich waagerecht an einem Skizzenpunkt und senkrecht an einem anderen aus, mit einer gepunkteten Hilfslinie; der Klick behält beide Ausrichtungen. Aus: nur am vorherigen Punkt, jeweils eine Achse.", "prefs.sketch_conflict_colour": "Widersprüchliche Geometrie in der Konfliktfarbe", "prefs.sketch_conflict_colour_note": "Solange die Bedingungen einer Skizze im Konflikt stehen, werden auch die Kurven und Punkte, die eine nicht erfüllte Bedingung hält, in der Konfliktfarbe gezeichnet, nicht nur ihr Symbol oder ihre Bemaßung. Aus: Sie behalten ihre üblichen Farben.", "prefs.sketch_construction_lines": "Erweiterte Konstruktionslinien-Werkzeuge", + "prefs.sketch_exit_view": "Ansicht nach dem Beenden einer Skizze", + "prefs.sketch_exit_view.keep": "Aktuelle Ansicht beibehalten", + "prefs.sketch_exit_view.previous": "Zur vorherigen Ansicht zurückkehren", + "prefs.sketch_exit_view.unless_rotated": "Zurückkehren, sofern nicht gedreht", + "prefs.sketch_exit_view_note": "Legt fest, zu welcher Ansicht nach „Skizze beenden“, „Abbrechen“ oder zweimaligem Drücken der Esc-Taste gewechselt wird.", + "prefs.sketch_face_activates_part": "Skizzieren auf der Fläche eines Teils aktiviert dieses Teil", + "prefs.sketch_face_activates_part_note": "Eine Skizze, die auf einer Fläche am Körper einer anderen Komponente begonnen wird, aktiviert zuerst diese Komponente, sodass die Skizze zu ihr gehört und im Browser bei diesem Teil bleibt. Das Teil bleibt danach aktiv. Aus: Die Skizze gehört zur aktiven Komponente.", "prefs.sketch_open_look_at": "Beim Öffnen einer Skizze auf sie ausrichten", "prefs.sketch_open_look_at_note": "Aus: Beim Erstellen oder Bearbeiten einer Skizze bleibt die Ansicht, wie sie ist. „Ansehen“ richtet die Ansicht bei Bedarf auf die Skizze aus.", "prefs.sketch_recent_snap": "Automatisch an zuletzt verwendete Mittelpunkte fangen", "prefs.sketch_recent_snap_note": "Fängt den Zeiger beim Zeichnen dort ein, wo sich die Hilfslinien der beiden zuletzt verwendeten Kreismittelpunkte oder Kantenmitten kreuzen. Aus: die Hilfslinien bleiben sichtbar und der Zeiger bewegt sich nicht.", + "prefs.sketch_selection": "Skizzen und Auswahl", + "prefs.sketch_selection_heading": "Skizzen und Auswahl", + "prefs.sketch_selection_note": "Legt fest, wie Skizzenelemente einrasten und wie Klicks Elemente auswählen.", "prefs.sketch_state_icons": "Skizzensymbole in der Farbe ihres Zustands", "prefs.sketch_state_icons_note": "Im Verlauf und im Browser nimmt das Symbol einer Skizze die Farbe ihres Zustands an (unterbestimmt, vollständig bestimmt oder im Konflikt), und ihr Tooltip nennt den Zustand. Aus: Alle Skizzen haben dasselbe Symbol.", "prefs.sketch_tab_always": "Registerkarte Skizze immer zeigen", "prefs.sketch_tab_always_note": "Die Registerkarte Skizze bleibt im Menüband direkt nach Modell, auch wenn keine Skizze offen ist. Ihre Zeichenwerkzeuge beginnen dann eine Skizze auf der ausgewählten Ebene oder Fläche oder auf der Ebene, die Sie als Nächstes wählen, und das Werkzeug ist darin bereit.", "prefs.sketch_tracking_guides": "Ausrichtungshilfen für Mittelpunkte", "prefs.sketch_tracking_guides_note": "Den Mauszeiger über einen Kreismittelpunkt oder eine Kantenmitte bewegen und dann waagerecht oder senkrecht bewegen, um eine temporäre gepunktete Hilfslinie anzuzeigen.", - "prefs.stand_up_unknown": "Für Dateien aus unbekannten Programmen", + "prefs.sketch_tracking_points": "Ausrichtungshilfen von Endpunkten und Ecken beim Zeichnen", + "prefs.sketch_tracking_points_note": "Während ein Zeichenwerkzeug auf einen Punkt wartet, zeigt das Überfahren eines Linien- oder Bogenendes, einer Rechteckecke oder eines freien Punkts dieselbe temporäre gepunktete Hilfslinie wie ein Mittelpunkt. Aus: nur Mittelpunkte.", + "prefs.sketching": "Skizzieren", + "prefs.snap_drawing_note": "Gilt beim Zeichnen oder Verschieben eines Skizzenpunkts.", + "prefs.source": "Quelle", + "prefs.speed": "Geschwindigkeit", + "prefs.stand_up_note": "Wenn eine STEP- oder IGES-Datei mit der Z-Achse nach oben geöffnet wird, wird eine Vierteldrehung um die X-Achse angeboten.", + "prefs.stand_up_unknown": "Dateien aus unbekannten Programmen", "prefs.stand_up_unknown.ask": "In einem Dialog fragen", "prefs.stand_up_unknown.note": "Einen Hinweis zeigen", "prefs.stand_up_unknown.off": "Nicht anbieten", - "prefs.stand_up_unknown_note": "Wie das Aufrichten angeboten wird, wenn der Dateikopf kein Programm nennt, das bekanntlich mit Y nach oben speichert. Ein Hinweis erscheint nur, wenn die Datei auf dem Rücken zu liegen scheint; „In einem Dialog fragen“ fragt wie bisher bei jeder solchen Datei.", + "prefs.stand_up_unknown_note": "Wie der Vorschlag erscheint, wenn die Datei kein bekanntes Programm nennt.", "prefs.status_bar": "Statusleiste", "prefs.status_bar_note": "Eine schmale Leiste am unteren Fensterrand zeigt, was gerade bearbeitet wird, den Zustand der offenen Skizze in seiner Farbe und die Einheiten der Konstruktion; ein Klick auf die Einheiten ändert sie. Der Zustand der Skizze steht dann nicht mehr in der Ecke der Ansicht.", + "prefs.status_done": "Fertig", + "prefs.status_error": "Fehler", + "prefs.status_selected": "Ausgewählt", + "prefs.status_warning": "Warnung", + "prefs.structure.appearance": "Erscheinungsbild", + "prefs.structure.appearance_note": "Farben, Text und Barrierefreiheit.", + "prefs.structure.in_profile": "Im Profil", + "prefs.structure.layout": "Layout", + "prefs.structure.layout_note": "Anordnung der Fensterbereiche.", + "prefs.structure.look": "Ansicht", + "prefs.structure.measure_pointer": "Messen und Zeiger", + "prefs.structure.mouse3d": "3D-Maus", + "prefs.structure.mouse3d_note": "SpaceMouse und SpaceNavigator.", + "prefs.structure.navigation_note": "Maus und Trackpad. Die 3D-Maus hat eine eigene Seite.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Seit dem Speichern geändert", + "prefs.structure.profile_hover": "Wird in Einstellungsprofilen gespeichert", + "prefs.structure.scale_percent": "{percent} %", + "prefs.structure.sketch": "Skizze", + "prefs.structure.tools": "Werkzeuge", + "prefs.structure.tools_note": "Verhalten der Modellierungswerkzeuge.", + "prefs.structure.work": "Arbeit", + "prefs.supersampling_brief": "Rendert die Ansicht größer und verkleinert sie dann: sehr scharf, aber rechenintensiver.", + "prefs.tab_accent_note": "Die Akzentfarbe richtet sich nach dem aktiven Tab.", + "prefs.theme_file": "Designdatei", "prefs.theme_file_or_paste": "Datei oder Einfügen", "prefs.theme_follow": "Einer Designdatei folgen", "prefs.theme_follow_error": "Nicht angewendet: {error}. Das letzte gültige Design bleibt aktiv.", @@ -1936,21 +2652,71 @@ "prefs.theme_follow_off": "Aus", "prefs.theme_follow_stop": "Nicht mehr folgen", "prefs.theme_import_hint": "Klicken, um eine Designdatei zu wählen, eine hierher ziehen oder mit kopiertem Design Strg+V (Cmd+V auf dem Mac) drücken", + "prefs.theme_notice_dismiss": "Ausblenden", + "prefs.theme_option_blur": "Unschärfe hinter Panels", + "prefs.theme_option_blur_help": "Unschärfe hinter durchscheinenden Panels in physischen Pixeln. Null bedeutet aus.", + "prefs.theme_option_invalid": "Der gespeicherte Wert für {option} ist ungültig; der Designstandard wird verwendet. Der gespeicherte Wert bleibt erhalten.", + "prefs.theme_option_opacity": "Deckkraft", + "prefs.theme_option_opacity_help": "Deckkraft schwebender Bedienfelder anpassen. Eine Mindestdeckkraft schützt die Lesbarkeit über den Ansichtsfarben.", + "prefs.theme_option_tab_colours": "Tabfarben", + "prefs.theme_option_tab_colours_help": "Panel- und Ansichtsfarben dieses Designs je Registerkarte verwenden.", + "prefs.theme_option_tab_fade_ms": "Tabübergang", + "prefs.theme_option_tab_fade_ms_help": "Panel- und Ansichtsfarben beim Tabwechsel überblenden. Null wechselt sofort.", + "prefs.theme_options_badge": "Optionen", + "prefs.theme_options_more": "Mehr · {count}", + "prefs.theme_options_newer": "Dieses Design benötigt eine neuere Version von SolidCraft. Nach dem Upgrade das Originaldesign erneut importieren, um seine Optionsdefinitionen wiederherzustellen.", + "prefs.theme_options_reset": "Zurücksetzen", + "prefs.theme_options_unavailable": "Auf diesem Gerät nicht verfügbar", "prefs.theme_paste": "Design einfügen", "prefs.theme_paste_none": "Die Zwischenablage enthält kein SolidCraft-Design", + "prefs.timeline_half_hour": "−30 min", + "prefs.timeline_now": "Jetzt", + "prefs.timeline_quarter_hour": "−15", "prefs.toast_place": "Hinweise", + "prefs.toggle_item": "Element hinzufügen oder wieder entfernen", + "prefs.toolbar": "Werkzeugleiste", "prefs.toolbar_tabs": "Werkzeugleisten-Registerkarten", + "prefs.top": "Oben", "prefs.trackpad_zoom_modifier": "Mit zwei Fingern zoomen bei gedrückter Taste", "prefs.trackpad_zoom_modifier.alt": "⌥ / Alt", "prefs.trackpad_zoom_modifier.cmd": "⌘", "prefs.trackpad_zoom_modifier.ctrl": "Strg", "prefs.trackpad_zoom_modifier.help": "Nur diese Taste gedrückt halten, um durch vertikales Scrollen am Zeiger zu zoomen. Aus behält das bisherige Scrollverhalten bei.", "prefs.trackpad_zoom_modifier.off": "Aus", + "prefs.translucent": "Durchscheinend", + "prefs.under_browser": "Unter dem Browser", + "prefs.under_cursor": "Unter dem Cursor", + "prefs.units_precision": "Einheiten und Genauigkeit", + "prefs.updates": "Updates", + "prefs.validation": "Körperprüfung", + "prefs.validation.each_feature": "Einmal je Feature", + "prefs.validation.each_step": "Nach jedem Schritt", + "prefs.validation.label": "Vollständige Kernel-Prüfung", + "prefs.validation.off": "Aus (experimentell)", + "prefs.validation_note": "Nach jedem Schritt: prüft jeden Sweep, jede Boolesche Operation und jede Rundung.\nEinmal je Feature: prüft das Ergebnis jedes Features einmal.\nAus (experimentell): keine Prüfung.", + "prefs.value_boxes_in_view": "Werte neben ihren Griffen anzeigen", + "prefs.value_boxes_in_view_tip": "Abstand beim Extrudieren, Radius beim Verrunden … als Feld in der Ansicht.", + "prefs.view": "Ansichtsverhalten", + "prefs.view_confirm_corner": "OK und Abbrechen in der Ansichtsecke", + "prefs.view_confirm_corner_note": "Solange ein Dialog oder eine Skizze geöffnet ist, übernehmen ein Häkchen und ein Kreuz oben rechts in der Ansicht dieselben Funktionen wie „OK“ und „Abbrechen“ des Dialogs. Eine Skizze wird damit beendet oder verworfen. Der Ansichtsnavigator rückt darunter.", + "prefs.viewport": "Ansichtsfenster", + "prefs.viewport_analysis_status": "Analysestatus im Ansichtsfenster anzeigen", + "prefs.viewport_analysis_status_help": "Zeigt aktive Analysen über dem Ansichtsfenster und ihre Legenden am jeweiligen Eintrag. Esc beendet die neueste Analyse. Ausschalten stellt Ecklegenden und das bisherige Esc-Verhalten wieder her.", "prefs.viewport_background": "Hintergrund", "prefs.viewport_background_colour": "Farbe", "prefs.viewport_background_theme": "Verlauf des Designs", + "prefs.viewport_section_status": "Schnittstatus im Ansichtsfenster anzeigen", + "prefs.viewport_section_status_help": "Die Schnitteinstellung im Ansichtsfenster anzeigen. Escape und die aktive Schaltfläche schalten den Schnitt aus. Deaktivieren, um die bisherigen Schnittbedienelemente zu behalten.", + "prefs.viewport_status_details": "Live-Details im Ansichtsfenster", + "prefs.viewport_status_details_help": "Aktive Analyse- und Schnitteinstellungen in standardisierten Detailkarten bearbeiten. Deaktivieren, um schreibgeschützte Analyselegenden und den Schnittdialog wiederherzustellen.", + "prefs.viewport_status_summary": "Status im Ansichtsfenster zusammenfassen", + "prefs.viewport_status_summary_help": "Drei oder mehr Statuselemente in einer Zusammenfassung anzeigen. Deaktivieren, um jedes Element in der vollständigen Zeile zu behalten.", + "prefs.wheel": "Mausrad", + "prefs.wheel_trackpad": "Mausrad und Trackpad", + "prefs.workspace": "Arbeitsbereich", "prefs.zoom_stop_at_model": "Zoom am Modell stoppen", "prefs.zoom_stop_at_model_tip": "3D-Maus und Geräte-App zoomen zur Oberfläche in der Ansichtsmitte; Zieh-Zoom hält den Punkt am Beginn des Ziehens fest. Aus: Zoom kann durch das Modell gehen. Mausrad und Pinch verwenden separat Zoom zum Mauszeiger", + "prefs.zoom_toward_cursor": "Zoomen zum Mauszeiger hin", "properties.title": "Eigenschaften: {name}", "recovery.days_ago": "vor {count} Tagen", "recovery.detail": "{file} · {features} Merkmale · automatisch gespeichert {when}", @@ -1962,7 +2728,55 @@ "recovery.just_now": "gerade eben", "recovery.min_ago": "vor {count} Min.", "recovery.never_saved": "nie gespeichert", + "refused.change": "{body} konnte nicht geändert werden.", + "refused.cut": "{body} konnte nicht geschnitten werden.", + "refused.face_curved": "Eine seiner gekrümmten Flächen kann nicht zum Modellieren verwendet werden.", + "refused.face_flat": "Eine seiner ebenen Flächen kann nicht zum Modellieren verwendet werden.", + "refused.face_freeform": "Eine seiner Freiformflächen kann nicht zum Modellieren verwendet werden.", + "refused.face_rounded": "Eine seiner gerundeten Flächen kann nicht zum Modellieren verwendet werden.", + "refused.faces_apart": "Seine Flächen treffen nicht genau genug aufeinander, um damit zu modellieren.", + "refused.intersect": "Schnittmenge mit {body} nicht möglich.", + "refused.join": "Konnte nicht mit {body} vereinigt werden.", + "refused.repair": "Teil reparieren", + "refused.show_face": "Fläche zeigen", + "render.adaptive_absolute": "Absolute RGB-Fehleruntergrenze", + "render.adaptive_coverage": "Zielwert für den Abdeckungsfehler", + "render.adaptive_enable": "Samples mithilfe unabhängiger Pilot-Samples zuteilen", + "render.adaptive_help": "Nur GPU. Unabhängige Pilot-Samples werden verworfen. Anschließend werden pro Pixel 16 oder mehr Produktions-Samples zugeteilt, bis zu den Samples pro Pixel. Die Zuteilung richtet sich nach der RGB- und Abdeckungsvarianz; seltene Pfade können übersehen werden, und Pixel, die ihr Limit erreicht haben, können verrauscht bleiben. Der Abschlussbericht zählt den tatsächlichen Aufwand. Keine zertifizierte Garantie für ein bestimmtes Rauschniveau oder eine bestimmte Renderzeit.", + "render.adaptive_minimum": "Minimale Produktions-Samples", + "render.adaptive_pending": "Die adaptive Zuteilung mit unabhängigen GPU-Pilot-Samples und bedingte Fresnel-Schichten sind verfügbar. Zertifizierte Konvergenz, Garantien für seltene Ereignisse und adaptiver Lichttransport auf der CPU bleiben nicht verfügbar.", + "render.adaptive_pilots": "Pilot-Samples pro Pixel", + "render.adaptive_relative": "Zielwert für den relativen RGB-Fehler", "render.add_ground": "Add fitted ground to setup", + "render.advanced_material_scope": "Ein endliches, homogenes GPU-Medium ist innerhalb ausdrücklich festgelegter Grenzen verfügbar. Dichtegitter, verschachtelte Glas-/Volumen-Kombinationen, Subsurface-Oberflächen, Displacement, spektraler Lichttransport und nicht zugeordnete erweiterte Materialkonzepte bleiben nicht verfügbar.", + "render.aging_add": "Alterungsschicht hinzufügen", + "render.aging_airborne": "Luftgetragener Staub / teilnehmendes Medium", + "render.aging_airborne_help": "Luftgetragener Staub bildet ein separates, endliches und homogenes Streuvolumen. Er beeinflusst den Lichttransport und das unbearbeitete EXR-Bild, nicht jedoch die Oberflächenalterungsschichten. Die bestehenden Einschränkungen für Volumen, Glas und Entrauschen gelten weiterhin. Eine Atmosphäre wird nicht automatisch hinzugefügt.", + "render.aging_all_bodies": "Alle geeigneten undurchsichtigen Körper", + "render.aging_chips": "Abgeplatzter Lack", + "render.aging_class_any": "Alle undurchsichtigen Materialklassen", + "render.aging_class_dielectric": "Nur nichtmetallische Oberflächen", + "render.aging_class_metal": "Nur metallische Oberflächen", + "render.aging_color": "Schichtfarbe · sRGB", + "render.aging_coverage": "Abdeckung", + "render.aging_dust": "Abgelagerter Staub", + "render.aging_empty": "Keine Alterungsschichten: Die ursprünglichen Oberflächen bleiben unverändert.", + "render.aging_fading": "Ausgeblichene Beschichtung", + "render.aging_grime": "Schmutz und Verfärbungen", + "render.aging_help": "Bis zu acht optische Schichten der Reihe nach kombinieren. Rost und Patina sind gestaltete Erscheinungsbilder, keine Simulationen von Alterung oder Korrosion. Die Mustergröße wird in Weltmillimetern angegeben. Geometrie, Masse und technische Eigenschaften bleiben unverändert; Glas und passive Bühnenflächen sind ausgenommen.", + "render.aging_metallic": "Metallanteil der Schicht", + "render.aging_origin": "Feldursprung · Weltkoordinaten (mm)", + "render.aging_patina": "Kupfergrüne Patina", + "render.aging_refresh_targets": "Aktuelle Körper prüfen", + "render.aging_roughness": "Rauheit der Schicht", + "render.aging_rust": "Oxidiertes Eisen / Rost", + "render.aging_scale": "Mustergröße", + "render.aging_scratches": "Feine Kratzer", + "render.aging_target": "Ziel und Koordinaten", + "render.aging_target_help": "Ein benanntes Ziel muss weiterhin zu seinem erfassten Index und Namen passen. Globale Masken sind im Weltkoordinatensystem verankert und folgen bewegten Teilen nicht. Die Funktion erkennt weder Hohlräume noch echten Kantenverschleiß. Filtern Sie die Liste, um weitere Körper zu erreichen.", + "render.aging_target_search": "Körpernamen filtern", + "render.aging_upward": "Ablagerung auf nach oben zeigenden Flächen", + "render.all_controls_help": "Kompakte Übersicht aller aktuellen Einstellungen. Die Abschnittsseiten erlauben eine gezielte Bearbeitung, ohne die zugrunde liegende Anfrage zu ändern.", "render.all_shots_label": "Alle Aufnahmen", "render.appearance_editor.absorption": "Absorption", "render.appearance_editor.base_colour": "Grundfarbe", @@ -2003,18 +2817,68 @@ "render.appearance_editor.v_repeat": "V-Wiederholung", "render.appearance_editor.v_up": "Textur-V zeigt nach oben", "render.appearance_editor.weight": "Gewicht", + "render.appearance_physics_separate": "Das visuelle Aussehen weist weder Dichte noch thermische Daten oder andere technische Eigenschaften zu.", "render.appearances": "Erscheinungsbilder", "render.assign_help": "Klicken wendet den Look auf die Auswahl an. Ziehen zeigt eine Vorschau; ohne Auswahl startet Malen.", + "render.availability_native": "Native Zusammenstellung; vor dem Anwenden prüfen", + "render.availability_projection": "Unterstützte Projektion; Umfang und Auslassungen beachten", + "render.availability_reference": "Referenzdaten; keine automatische Zuweisung", + "render.backdrop_alpha_conflict": "Wählen Sie entweder diesen Hintergrund oder die Ausgabe als transparentes PNG; der Renderer ignoriert keine der beiden Einstellungen stillschweigend.", + "render.backdrop_enable": "Verlaufshintergrund nur für die Kamera verwenden", + "render.backdrop_first": "Start-/Mittelfarbe", + "render.backdrop_help": "Dieser Hintergrund im Bildschirmraum beleuchtet nicht, wirft keine Schatten, spiegelt nicht und stellt kein Gelände dar. Er ist im unbearbeiteten EXR-Bild nicht enthalten. Geometrie, Lichter und die HDR-Umgebung bleiben unabhängig.", + "render.backdrop_horizontal": "Horizontaler Verlauf", + "render.backdrop_radial": "Radialer Verlauf", + "render.backdrop_radius": "Radius", + "render.backdrop_second": "End-/Randfarbe", + "render.backdrop_vertical": "Vertikaler Verlauf", + "render.backdrop_x": "Mittelpunkt X", + "render.backdrop_y": "Mittelpunkt Y", "render.background": "Szenenhintergrund", + "render.background_camera_section": "Kamerahintergrund · PNG-Darstellung", + "render.background_completed_frozen": "Das angezeigte Ergebnis ist ein eingefrorenes, fertiges Bild. Eine Änderung des Hintergrunds zeichnet dieses Ergebnis nicht automatisch neu. Verwenden Sie „Neu graden“ für reine Kameraänderungen oder „Rendern“ für eine neue physische Bühne.", + "render.background_hdr_separate": "Die aktuellen HDR-Ressourcen beleuchten Oberflächen und spiegeln sich darin; sie werden nicht automatisch als Panorama hinter dem Motiv angezeigt. Das Ändern eines Verlaufs dreht oder verfärbt die Beleuchtung nicht.", + "render.background_lighting_section": "HDR-Beleuchtung · getrennt vom Kamerahintergrund", + "render.background_no_alpha_override": "Ein Kamerahintergrund wird einer transparenten Ausgabe nicht stillschweigend hinzugefügt. Beim Neu-Graden des linearen Rohbilds wird die erfasste Abdeckung verwendet und das Entrauschen nicht erneut angewendet; das Quell-EXR bleibt unverändert.", + "render.background_not_light": "Die Hintergrundfarbe dient der Darstellung und ist keine zusätzliche Lichtquelle.", + "render.background_regrade": "Auf das behaltene lineare Rohbild anwenden", + "render.background_stage_occlusion": "Diese Aufnahme enthält physische Bühnengeometrie. Ein großer Boden oder eine große Wand kann das Bild füllen und einen reinen Kamerahintergrund verdecken. Entfernen oder verkleinern Sie die Bühne gezielt oder ändern Sie ihren physikalischen Reflexionsgrad. Neu graden kann bereits erfasste Geometrie nicht entfernen.", + "render.background_workflow": "Wählen Sie den gewünschten Hintergrund: eine reine Kamerafarbe bzw. einen Verlauf, eine physische Bühne, die Licht empfängt, oder HDR-Beleuchtung. Sie sind voneinander unabhängig. Die Live-Vorschau ist eine Modellieransicht; rendern Sie ein neues Bild oder graden Sie ein behaltenes lineares Rohbild neu, um die Nachbearbeitung der Kamera zu sehen.", + "render.base_appearance": "Bearbeitbares Aussehen des Körpers", + "render.base_apply": "Aussehen des Körpers anwenden", + "render.base_apply_help": "Eine rückgängig machbare visuelle Zuweisung an genau den geprüften Körper. Bestehende flächenspezifische Looks und technische Materialien bleiben davon getrennt.", + "render.base_color": "Grundfarbe · sRGB", + "render.base_metallic": "Metallanteil", + "render.base_opaque_only": "Dieser Editor lässt Körper undurchsichtig. Für optische Transmission verwenden Sie die gesonderten Glaseinstellungen.", + "render.batch_all_shots": "Alle Ansichten ({count})", + "render.batch_empty": "Vor dem Rendern aller Ansichten eine Ansicht speichern.", + "render.batch_limit": "Es können höchstens 32 Ansichten gerendert werden.", + "render.batch_status": "{running} läuft · {waiting} warten", "render.bloom_enable": "Darstellungs-Bloom", "render.bloom_help": "Kreativer Ausgabeglanz aus linearen Glanzlichtern mit drei normierten Durchläufen. Radius in Ausgabepixeln; Addition vor sRGB. Keine Linsen-, Volumen- oder Konvergenzsimulation. Das rohe EXR bleibt unverändert.", "render.bloom_opaque": "Bloom benötigt eine deckende Ausgabe. Transparentes PNG wird abgelehnt, nicht still abgeflacht.", "render.bloom_radius": "Bloom-Radius", "render.bloom_strength": "Bloom-Stärke", "render.bloom_threshold": "Linearer Glanzlichtschwellwert", + "render.browse_capabilities": "Vollständigen Funktionskatalog ansehen", + "render.browse_environments": "Originale HDR-Umgebungen durchsuchen", "render.browse_looks": "Durchsuchen…", + "render.browse_native_scenes": "Native Studios durchsuchen", + "render.browse_physical": "Physikalische Referenzen ansehen", + "render.browse_quality": "Qualitätsspezifikationen ansehen", + "render.browse_rigs": "Erstellte Lichtaufbauten durchsuchen", + "render.browse_scene_specs": "Erweiterte Szenenspezifikationen durchsuchen", + "render.browse_surfaces": "Erstellte Oberflächen durchsuchen", + "render.browser_library": "Bibliothek", + "render.browser_model": "Modell", + "render.camera_distance": "Abstand zwischen Kamera und Ziel", + "render.camera_exact_help": "Weltmillimeter; Winkel werden in Grad angezeigt und als Bogenmaß gespeichert. Die Navigation verwendet dieselbe Kamera wie die Ansicht.", + "render.camera_fov": "Vertikaler Bildwinkel", "render.camera_pitch": "Kameraneigung", + "render.camera_roll": "Rollwinkel", "render.camera_set": "Render-Kamera einstellen", + "render.camera_target": "Zielposition · mm", + "render.camera_yaw": "Gierwinkel", "render.category_metal": "Metall", "render.category_paint": "Lack", "render.category_plastic": "Kunststoff", @@ -2098,7 +2962,29 @@ "render.children.vignette": "Vignette", "render.children.workstation": "Workstation", "render.choose_look": "Zuerst einen Look in der Bibliothek wählen", + "render.chromatic_offset": "Chromatischer Kantenversatz", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "Vergleichstrenner", + "render.compare_live": "Live", + "render.compare_live_preview": "Live-Vorschau", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · aufgenommen bei Revision {revision}", + "render.compare_swap": "Tauschen", + "render.copy_request": "JSON kopieren", + "render.cpu_aa_help": "Räumliche Samples: Mehr Samples verbessern die Kantenglättung, verlängern jedoch die Renderzeit.", + "render.cpu_area_add": "Rechteckiges CPU-Flächenlicht hinzufügen", + "render.cpu_area_editor": "Rechteckige CPU-Flächenlichter", + "render.cpu_area_editor_help": "Vollständige Seitenvektoren in Millimetern; das Kreuzprodukt U × V zeigt zur abstrahlenden Seite. Das unterscheidet sich von den halben Kantenvektoren der GPU.", + "render.cpu_area_full_u": "Volle Seite U · mm", + "render.cpu_area_full_v": "Volle Seite V · mm", + "render.cpu_area_samples": "Flächenlicht-Samples", + "render.cpu_binding_confirm": "Diesen Körper bestätigen", + "render.cpu_binding_stale": "Die Szene hat sich geändert. Bestätigen Sie dieses Reflexionsziel vor dem Rendern erneut.", + "render.cpu_body_choose": "Körper wählen", + "render.cpu_body_filter": "Körper nach Namen filtern", + "render.cpu_body_filter_more": "Verfeinern Sie den Filter, um weitere Körper zu sehen.", + "render.cpu_body_missing": "Ein Reflexionsziel fehlt, ist ausgeblendet, mehrdeutig oder hat einen Namen von mehr als 128 Byte. Wählen Sie es erneut.", "render.cpu_budget": "CPU-Ressourcenprofil", "render.cpu_budget_bodies": "Körperobergrenze", "render.cpu_budget_compact": "Kompakt (bisherige Grenzen)", @@ -2110,7 +2996,77 @@ "render.cpu_budget_studio": "Studio (große Bilder)", "render.cpu_budget_triangles": "Dreiecksobergrenze", "render.cpu_budget_workstation": "Workstation (komplexe Szenen)", + "render.cpu_captured_hdr": "Für dieses Bild erfasstes HDR", + "render.cpu_check_capture_help": "Prüfen und Starten verifizieren dieselbe Datei-Prüfsumme oder verwenden das eingebettete HDR. Jedes Bild behält seine erfasste Quelle.", + "render.cpu_check_changed": "Die Einstellungen oder das Modell haben sich nach dieser Prüfung geändert. Prüfen Sie erneut, bevor Sie rendern.", + "render.cpu_constant_help": "Konstante Strahldichte ist für reflektierte oder durchgelassene Strahlen sichtbar. Sie liefert keine direkte diffuse Beleuchtung.", + "render.cpu_custom_directions": "Vorgabe durch eigene Richtungslichter ersetzen", + "render.cpu_direction": "Richtung zum Licht (X, Y, Z)", + "render.cpu_directional": "Richtungslicht", + "render.cpu_directional_add": "Richtungslicht hinzufügen", + "render.cpu_environment": "CPU-Umgebung", + "render.cpu_environment_background": "Der Bildhintergrund bleibt von der Umgebungsbeleuchtung getrennt.", + "render.cpu_environment_bounds": "Die CPU-Intensität muss 0–64 betragen, die HDR-Drehung endlich innerhalb von ±1.000.000 Radiant liegen, und die HDR-Samples müssen 1, 4, 16 oder 64 sein.", + "render.cpu_environment_constant": "Konstante Umgebung für Sekundärstrahlen", + "render.cpu_environment_none": "Keine CPU-Umgebung", + "render.cpu_environment_samples": "HDR-Beleuchtungs-Samples", + "render.cpu_exposure_help": "Die CPU-Belichtung muss zwischen −16 und 16 EV liegen. Eine GPU-Belichtung außerhalb dieses Bereichs bleibt erhalten, bis Sie sie ändern.", + "render.cpu_fixed": "Einzelbild", + "render.cpu_hdr_help": "Radiance-HDR-Datei (.hdr), Panorama im Format 2:1, bis zu 2048 × 1024 Pixel und 16 MiB. Für die CPU müssen die sRGB/D65-Primärfarben ausdrücklich in der Datei angegeben sein. Dateien ohne Angabe der Primärfarben sowie EXR-Dateien werden abgelehnt.", + "render.cpu_hdr_reflection_help": "Raue HDR-Reflexionen erfordern vollständig metallische Körper- und Flächenoberflächen. Die Prüfung meldet nicht unterstützte Kombinationen.", + "render.cpu_key_rim": "Haupt- und Konturlicht", + "render.cpu_last_check": "Letzte CPU-Prüfung", + "render.cpu_light_help": "Bis zu acht Richtungslichter. Eine leere eigene Liste schaltet sie aus; die Wahl einer Vorgabe stellt deren Lichter wieder her. Farben sind lineares RGB, und die Intensität ist ein relativer Wert, keine Leistungsangabe in Watt.", + "render.cpu_light_intensity": "Relative Intensität (0–64)", + "render.cpu_light_minimum": "Mindestabstand für die Abschwächung", + "render.cpu_light_position": "Weltposition (X, Y, Z)", + "render.cpu_light_reference": "Referenzabstand für die Intensität", + "render.cpu_light_remove": "Licht entfernen", + "render.cpu_lighting": "Beleuchtungsvorgabe", + "render.cpu_lights": "CPU-Lichter", + "render.cpu_linear_color": "Lineare Farbe (R, G, B)", + "render.cpu_neutral": "Neutral", + "render.cpu_opaque_required": "CPU-Raytracing benötigt einen undurchsichtigen Hintergrund. Entfernen Sie das Häkchen bei „Transparenter Hintergrund“, um fortzufahren.", + "render.cpu_options_pending": "Dieses CPU-Bedienfeld kann Emission, Oberflächeneffekte, Glas oder Anisotropie noch nicht bearbeiten. Entfernen Sie diese API-Optionen, bevor Sie es verwenden.", + "render.cpu_point": "Punktlicht", + "render.cpu_point_add": "Punktlicht hinzufügen", + "render.cpu_point_help": "Bis zu acht Punktlichter, zusätzlich zur gewählten Richtungsbeleuchtung. Abstände in mm; der Mindestabstand darf den Referenzabstand nicht überschreiten.", + "render.cpu_primary_samples": "Kanten-Samples pro Pixel", + "render.cpu_progressive": "CPU progressiv", + "render.cpu_progressive_help": "Den vorhandenen CPU-Integrator in Durchgängen mit je einem Primär-Sample akkumulieren. Ausgewählte Reflexionen erfordern ein Sample; Flächenlichter, Dielektrika und Anisotropie erfordern „Einzelbild“.", + "render.cpu_progressive_limits": "Höchstens 1.048.576 Pixel und 16.777.216 Auswertungen von Pixel × Sample. Das Ändern der Samples passt die Bildgröße nie automatisch an.", + "render.cpu_progressive_seed": "Startwert für das CPU-Sampling", + "render.cpu_progressive_spp": "Samples pro Pixel", + "render.cpu_reflection_add": "Raue Reflexion hinzufügen", + "render.cpu_reflection_depth": "Reflexionstiefe (1–8)", + "render.cpu_reflection_empty": "Keine Körper ausgewählt: Szenenreflexionen sind aus.", + "render.cpu_reflection_help": "Wählen Sie Körper und stellen Sie „Aus“, „Spiegelnd“ oder „Rau“ ein. „Rau“ verwendet die zugewiesene Oberflächenrauheit. Mehr Samples und Reflexionsstufen verlängern die Rechenzeit; dies ist begrenzter spiegelnder Transport, keine globale Beleuchtung.", + "render.cpu_reflection_limit": "Bis zu 64 reflektierte Körper werden unterstützt.", + "render.cpu_reflection_mirror": "Spiegelnd", + "render.cpu_reflection_off": "Aus", + "render.cpu_reflection_rough": "Rau", + "render.cpu_reflection_samples": "Reflexions-Samples (1–64)", + "render.cpu_reflections": "CPU-Reflexionen", + "render.cpu_runtime_help": "Numerische Licht- und Umgebungseinstellungen werden mit dem Setup gespeichert. Körperreflexionen und HDR-Dateien bleiben vorübergehend. Vorhandene Werte für Flächenlicht und Spotkegel bleiben erhalten.", + "render.cpu_sampling_mode": "CPU-Sampling-Modus", + "render.cpu_shadows": "Schatten werfen", + "render.cpu_summary": "CPU-Raytracing · Reflexionen · HDR · Richtungs- und Punktlichter", + "render.cpu_warm_cool": "Warm und kühl", + "render.diag_bodies": "Sichtbare Körper", + "render.diag_job_details": "Erfasste Auftragsdetails", + "render.diag_last_check": "Letzte Vorabprüfung", + "render.diag_memory": "Geschätzter logischer Speicherbedarf", + "render.diag_not_implemented": "Ausdrückliche Funktionsgrenzen", + "render.diag_preflight_details": "Details der Vorabprüfung", + "render.diag_request": "Aktuelle Anfrage im Wortlaut", + "render.diag_triangles": "Dreiecke", + "render.discard_continue": "Entwurf verwerfen und fortfahren", + "render.draft_confirm_help": "Der aktuelle Render-Entwurf enthält nicht angewendete Änderungen. Speichern Sie sie vor dem Wechsel, verwerfen Sie sie ausdrücklich oder bearbeiten Sie weiter.", + "render.draft_confirm_title": "Bearbeitete Rendereinstellungen beibehalten", "render.effects_gpu_only": "Diese Effekte erfordern GPU-Pfadverfolgung. Ein Seitenwechsel schaltet den Renderer niemals automatisch um.", + "render.effects_help": "Geordnete Farb-Looks und Objektiveffekte im Bildraum kombinieren. Das Rendern und das Neu-Graden des linearen Rohbilds verwenden dieselben gespeicherten Einstellungen. Das unbearbeitete EXR bleibt unverändert. Dies sind eigene künstlerische Regler, keine kalibrierten Objektiv- oder Filmemulationen bestimmter Marken.", + "render.effects_reset_lens": "Objektiveffekte zurücksetzen", + "render.effects_seed": "Startwert des Musters", "render.emitted_axis": "Abstrahlachse", "render.env_advanced": "Erweitert", "render.env_backdrop": "Hintergrund", @@ -2250,11 +3206,19 @@ "render.error_vertex_packing": "Produktvorschau stimmt nicht mit den zugelassenen Scheitelpunktdaten überein", "render.error_visible_solid": "In Design einen sichtbaren Volumenkörper erstellen, um ihn hier anzuzeigen.", "render.exit_focus": "Fokus beenden", + "render.export_display": "Export: Anzeige-PNG", "render.export_image_label": "Bild exportieren", + "render.export_linear": "Export: lineares Roh-EXR", "render.exr_pending": "Die GPU kann rohe lineare EXR-Dateien behalten. Kompression, mehrschichtige Bilder und zusätzliche Renderpässe bleiben nicht verfügbar.", + "render.film_grain": "Fotografisches Korn", "render.fit": "Produkt einpassen", "render.fixed_camera": "Kamera", "render.fixed_world": "Welt", + "render.flare_ghosts": "Geisterringe pro Quelle", + "render.flare_halo": "Reflex-Lichthof", + "render.flare_streak": "Streifen im anamorphen Stil", + "render.flare_strength": "Lichtreflex-Stärke an Glanzlichtern", + "render.flare_threshold": "Szenenlinearer Lichtreflex-Schwellwert", "render.fold_browser": "Browser einklappen", "render.frame_aspect": "Seitenverhältnis", "render.frame_centre_mark": "Mittelpunkt", @@ -2283,6 +3247,27 @@ "render.frame_tall": "9:16 · Vertikal", "render.frame_thirds": "Drittellinien", "render.frame_wide": "16:9 · Breitbild", + "render.gpu_depth": "Maximale Pfadtiefe", + "render.gpu_options_help": "Samples, Tiefe, Startwert und Belichtung werden mit diesem Setup gespeichert. Es wird nur die aktive Bildmethode gespeichert.", + "render.gpu_path_failed": "GPU-Pathtracer nicht verfügbar", + "render.gpu_path_first_setup": "Das erste Setup auf dieser GPU kann mehrere Minuten dauern; SolidCraft bleibt währenddessen bedienbar. Spätere Starts verwenden die kompilierten Shader erneut, sofern der Treiber sie behält.", + "render.gpu_path_preparing": "GPU-Pathtracer: Shader werden kompiliert…", + "render.gpu_seed": "Zufallsstartwert", + "render.gpu_unavailable": "GPU-Pathtracing ist auf diesem Gerät nicht bereit.", + "render.ground_apply": "Boden anpassen und speichern", + "render.ground_gap": "Definierter Abstand", + "render.ground_linear_rgb": "Diffuser Reflexionsgrad · lineares RGB", + "render.ground_margin": "Randzugabe der Bodenfläche", + "render.hdr_details": "Details zur HDR-Quelle", + "render.hdr_embedded": "In diesem Design gespeichertes HDR", + "render.hdr_embedded_help": "Das Rendern verwendet die im Design enthaltenen Bytes; die Originaldatei wird nicht mehr benötigt.", + "render.hdr_file_captured": "HDR-Datei geprüft. Beim Speichern werden diese Bytes eingebettet; ändert sich die Datei, prüfen Sie sie erneut ausdrücklich.", + "render.hdr_inspect": "HDR-Datei prüfen", + "render.hdr_inspect_required": "Wählen und prüfen Sie eine HDR-Datei, bevor Sie speichern oder rendern.", + "render.hdr_primaries_declared": "Die Quelle gibt ihre Primärfarben an.", + "render.hdr_primaries_srgb": "Primärfarben: sRGB/D65", + "render.hdr_primaries_undeclared": "Die Quelle gibt keine Primärfarben an; prüfen Sie die Farbanforderungen des Renderers.", + "render.hdr_resource_missing": "In diesem Design fehlt die gespeicherte HDR-Ressource.", "render.heading_batch": "Stapel", "render.heading_frame": "Bildrahmen", "render.heading_lens": "Objektiv", @@ -2290,19 +3275,26 @@ "render.heading_shots": "Aufnahmen", "render.hide_shots_label": "Aufnahmenleiste ausblenden", "render.hover_look": "{object} · {look} · Zum Auswählen klicken", + "render.image_advanced": "Erweiterte GPU-Einstellungen", "render.image_cancelled": "Rendering abgebrochen", "render.image_cancelling": "Wird abgebrochen", "render.image_completed": "Bild bereit zum Export", "render.image_encoding": "PNG wird kodiert", "render.image_export": "Fertiges Bild exportieren", + "render.image_exposure": "Belichtung", "render.image_failed": "Rendering fehlgeschlagen", "render.image_height": "Höhe", "render.image_help": "CPU-Vorschaubild · PNG · angenäherte Transparenz", + "render.image_host_missing": "Es ist kein Bild-Host installiert.", + "render.image_method": "Bildmethode", "render.image_overwrite": "Vorhandene Datei ersetzen", "render.image_preparing": "Bild wird vorbereitet", + "render.image_progressive": "Progressives Rendering", "render.image_queued": "Warten auf Rendering", "render.image_reduce": "Kleineres Bild oder einfachere Szene versuchen.", "render.image_running": "Bild wird gerendert", + "render.image_samples": "Samples pro Pixel", + "render.image_scene_stale": "Schließen Sie die Modellierungsgeste ab oder aktualisieren Sie die Szene, bevor Sie ein Bild prüfen oder starten.", "render.image_stale": "Dieses Bild verwendet die Szene vor den nachfolgenden Änderungen.", "render.image_start": "Rendering starten", "render.image_supported": "Renderanfrage unterstützt; Warteschlange und Speicher werden beim Start erneut geprüft.", @@ -2314,6 +3306,7 @@ "render.image_width": "Breite", "render.include_rig_cards": "Include passive cards and flags", "render.inner_half_angle": "Innerer Halbwinkel", + "render.inspect_scene": "Erfasste Szenenübersicht aktualisieren", "render.inspector": "Inspektor", "render.inspector_advanced": "Erweitert", "render.inspector_all_users": "Alle {count} Nutzer", @@ -2345,7 +3338,17 @@ "render.inspector_this_face": "Diese Fläche", "render.inspector_this_target": "Dieses Ziel", "render.inspector_used_by": "Verwendet von {count}", + "render.keep_editing": "Weiter bearbeiten", + "render.layer_down": "Nach unten", + "render.layer_enabled": "Schicht aktiviert", "render.layer_off_suffix": " (aus)", + "render.layer_remove": "Schicht entfernen", + "render.layer_strength": "Schichtstärke", + "render.layer_up": "Nach oben", + "render.lens_effects_help": "Lichtreflexe nutzen bis zu vier getrennte helle Quellen im tatsächlichen linearen Bild. Geisterringe, Lichthof, Streifen, chromatische Versätze und radiale Verzeichnung sind künstlerische Näherungen im Bildraum. Räumliche Effekte benötigen eine undurchsichtige Ausgabe; Samples außerhalb setzen den Bildrand fort. Das Korn ist deterministisch. Physik, EXR und Geometrie bleiben unverändert.", + "render.lens_effects_title": "Objektivinspiriert und fotografisch", + "render.library_all": "Katalog", + "render.library_all_states": "Alle Verfügbarkeitszustände", "render.library_appearance_available": "Verfügbares Erscheinungsbild", "render.library_applicable": "Passende Ressourcen", "render.library_applied": "Ressourcenvariante angewendet. Vollständigen Renderauftrag vor dem Start prüfen.", @@ -2357,10 +3360,16 @@ "render.library_apply_uniform": "Einheitliches opakes Aussehen anwenden", "render.library_authored_help": "Original erstellte Ressourcen dienen der Darstellung, nicht als gemessene technische Daten. Jede Aktion wendet nur ihre angegebene Variante an.", "render.library_blocked": "Diese Ressource benötigt noch Kalibrierung oder eine externe Sonne und kann noch nicht angewendet werden.", + "render.library_capabilities": "Funktionsspezifikationen", "render.library_center": "Mittelpunkt des Lichtaufbaus", + "render.library_clear_search": "Leeren", + "render.library_details": "Spezifikation und Herkunft", "render.library_emitters_only_ack": "Nur Strahler verwenden; dokumentierte passive Karten auslassen", + "render.library_empty": "Keine passenden Ressourcen. Versuchen Sie eine andere Suche oder einen anderen Verfügbarkeitsfilter.", "render.library_environment_concepts": "Umgebungskonzepte", "render.library_extent": "Objektausdehnung", + "render.library_favorite": "Zu Favoriten hinzufügen", + "render.library_favorites": "Favoriten", "render.library_filters": "Katalog und Verfügbarkeit", "render.library_grid": "Raster", "render.library_hdr": "Integrierte HDR-Umgebungen", @@ -2373,12 +3382,15 @@ "render.library_maps_help": "Built-in maps can be saved with pinned sources and local occurrence mapping. Temporary optical overrides remain a separate mode.", "render.library_material_concepts": "Materialkonzepte", "render.library_metallic": "Metallisch", + "render.library_native_scenes": "Native Studios", "render.library_next": "Nächste Seite", + "render.library_omitted": "Nicht enthalten", "render.library_opacity": "Deckkraft", "render.library_other": "Weitere Erscheinungsbilder", "render.library_physical_profiles": "Physical reference profiles", "render.library_previous": "Vorherige Seite", "render.library_quality_concepts": "Qualitätsspezifikationen", + "render.library_recent": "Zuletzt", "render.library_replace_environment": "Vorhandene Umgebung ausdrücklich ersetzen", "render.library_replace_studio": "Replace saved lighting, environment and stage", "render.library_results": "Passende Ressourcen", @@ -2389,12 +3401,25 @@ "render.library_scene_bounds": "Erfasste Szenengrenzen verwenden", "render.library_scenes": "Szenenspezifikationen", "render.library_search": "Bibliothek durchsuchen", + "render.library_select_hint": "Wählen Sie eine Ressource in der Bibliothek, um ihre unterstützten Aktionen und Einschränkungen zu sehen.", "render.library_selene": "SELENE: opake Oberflächen", + "render.library_selene_shots": "SELENE-Aufnahmespezifikationen", + "render.library_short_blocked": "Nicht verfügbar", + "render.library_short_native": "Native Zusammenstellung", + "render.library_short_projection": "Unterstützte Projektion", + "render.library_short_reference": "Nur Referenz", + "render.library_short_specification": "Nur Spezifikation", + "render.library_source_preview": "Vorschau der Quellmap laden", + "render.library_source_preview_help": "Erstellte Quellmap der Grundfarbe. Dies ist keine gerenderte oder gemessene Materialvorschau.", "render.library_specification_only": "Nur Spezifikation: keine vollständig ausführbare Voreinstellung. Erforderliche Effekte, Ressourcen und Objektrollen müssen noch implementiert und gebunden werden.", + "render.library_specs": "Nur Spezifikationen", + "render.library_status": "Verfügbarkeit", "render.library_surfaces": "Erstellte PBR-Oberflächen", "render.library_target": "Zielkörper", "render.library_title": "Render-Ressourcenbibliothek", + "render.library_unfavorite": "Aus Favoriten entfernen", "render.library_uniform_ack": "Einheitliche Näherung ohne räumliche oder erweiterte Effekte verwenden", + "render.library_usable": "Ausführbare Projektionen", "render.library_users": "Verwendungen", "render.light_aim": "Ausrichten auf", "render.light_anchor_pending": "Das Koordinatensystem der Lichter kann noch nicht geändert werden.", @@ -2473,17 +3498,89 @@ "render.lighting_width": "Breite U", "render.lighting_world_position": "Welt X Y Z", "render.lights_fixed_to": "Lichter gebunden an", + "render.linear_help": "Behält ein lineares 32-Bit-Gleitkomma-RGBA-Rohbild vor Entrauschen, Belichtung, Tone-Mapping, Filtern und Hintergrund. Lineares sRGB/D65; Abdeckung vormultipliziert. Zusätzlicher Speicher wird ausdrücklich zugelassen. Keine Komprimierung und keine zusätzlichen Durchgänge.", + "render.linear_retain": "Lineares Roh-EXR behalten", + "render.linear_unavailable": "Für das gewählte fertige Bild wurde kein EXR behalten. Aktivieren Sie das Behalten vor dem Rendern; ein älteres PNG kann die rohe Strahldichte nicht wiederherstellen.", + "render.look_add": "Farblook hinzufügen", "render.look_applied": "{name} angewendet", + "render.look_bleach": "Von Bleach-Bypass inspiriert", + "render.look_cool": "Kühl", + "render.look_cyanotype": "Von Cyanotypie inspiriert", + "render.look_faded": "Verblasster Abzug", "render.look_material": "Material", + "render.look_mono": "Monochrom", "render.look_pasted": "Look eingefügt", + "render.look_sepia": "Sepia", + "render.look_strength": "Look-Stärke", + "render.look_teal_orange": "Türkis / Orange", + "render.look_title": "Stapel kreativer Looks", + "render.look_warm": "Warm", + "render.mapping_scale": "Physischer Wiederholungsfaktor", + "render.material_absorption": "Absorption R · G · B (pro mm)", + "render.material_add": "Diesen Körper hinzufügen oder bearbeiten", + "render.material_assignments": "Körperzuweisungen", + "render.material_binding_enable": "Diese Körperüberschreibung einbeziehen", + "render.material_box": "Achsparalleler Quader", + "render.material_browse": "Bild wählen…", + "render.material_certification": "Geschlossenes Glas verwendet geometrische Abstände. Topologie, Ausrichtung, Überlappung und optische Grenzflächen werden bei der GPU-Vorbereitung geprüft; „Prüfen“ lässt die Anfrage lediglich zu.", + "render.material_choose_body": "Szenenkörper wählen", + "render.material_closed": "Geschlossenes Körpernetz", + "render.material_coat": "Klarlack über dem Grundmaterial", + "render.material_coat_enable": "Klarlack aktivieren", + "render.material_coat_help": "Illustrative dielektrische Beschichtung über dem vorhandenen undurchsichtigen Erscheinungsbild. Gewicht null lässt das Grundmaterial unverändert.", + "render.material_color_map": "Grundfarbentextur (sRGB)", "render.material_color_replace": "Basismap ersetzt Körperfarbe", + "render.material_custom": "Eigene illustrative Optik", + "render.material_enable": "Diese GPU-Materialüberschreibungen verwenden", + "render.material_filter": "Szenenkörper filtern…", + "render.material_filter_help": "Es werden bis zu 128 passende Körper angezeigt. Verfeinern Sie den Filter bei großen Szenen.", + "render.material_glass": "Glas und optische Absorption", + "render.material_glass_enable": "Physikalisches Glas für diesen Körper verwenden", + "render.material_glass_exclusive": "Glas kann in diesem Renderer nicht zusammen mit Klarlack oder Laufzeittexturen auf einem Körper verwendet werden.", + "render.material_glass_help": "Eigene illustrative Rezepte. Farbfelder zeigen die Transmission, keine gerenderte Vorschau. Die Absorption ist −ln(lineare Transmission) / Referenzabstand; Alpha bleibt unverändert.", + "render.material_gpu_required": "Diese aktiven Materialüberschreibungen erfordern GPU-Pathtracing. Wählen Sie GPU oder deaktivieren Sie die Überschreibungen, bevor Sie „Prüfen“ oder „Start“ verwenden.", + "render.material_ior": "Brechungsindex (IOR)", "render.material_limits": "Höchstens 128 Körperüberschreibungen, 32 getrennte Glaskörper, 64 Beschichtungen und 128 Texturbindungen. Identische Maps teilen Speicher; Geräte- und Gesamtspeichergrenzen bleiben aktiv.", + "render.material_map_invalid": "Texturpfade müssen begrenzte lokale Pfade sein; die Normalenstärke muss endlich sein und zwischen 0 und 1 liegen.", + "render.material_map_required": "Wählen Sie ein Farbbild oder ein Normalenbild, bevor Sie Texturen verwenden.", + "render.material_maps": "Planare Farb- und Normalentexturen", + "render.material_maps_enable": "Texturen für diesen undurchsichtigen Körper aktivieren", + "render.material_maps_help": "PNG/JPEG bis 1024×1024; insgesamt 16 MiB codiert. U und V sind orthogonale Wiederholungsvektoren in Welt-mm (höchstens 128 Wiederholungen). Die Farbe ist sRGB; Normalendaten verwenden OpenGL +Y. Die Dateien werden bei „Prüfen“/„Start“ erfasst.", "render.material_metallic_map": "Metallanteil-Map (linear)", + "render.material_normal_map": "Normalenbild (OpenGL, +Y)", + "render.material_normal_strength": "Normalenstärke (0–1)", + "render.material_origin": "Texturursprung X · Y · Z (mm)", + "render.material_refresh": "Szenenkörper aktualisieren", + "render.material_refresh_needed": "Die Szene hat sich geändert. Aktualisieren Sie die Körperliste, bevor Sie ein Ziel hinzufügen.", + "render.material_remove": "Diese Zuweisung entfernen", + "render.material_repeat_u": "Eine U-Wiederholung X · Y · Z (mm)", + "render.material_repeat_v": "Eine V-Wiederholung X · Y · Z (mm)", + "render.material_revalidate": "Diesen Körper erneut prüfen", + "render.material_revalidate_needed": "Diese Zuweisung gehört zu einer früheren Szenenrevision. Prüfen Sie die genaue Körperidentität erneut, bevor Sie rendern.", + "render.material_roughness": "Rauheit des Klarlacks (0,045–1)", "render.material_roughness_map": "Rauheitsmap (linear)", + "render.material_shadow": "Gerade Schattenstrahlen durchlassen", + "render.material_target_missing": "Ordnungsnummer und Name des Körpers stimmen nicht mehr überein. Entfernen Sie diese Zuweisung und wählen Sie den gewünschten Körper ausdrücklich erneut.", + "render.material_thickness": "Dicke der dünnen Schicht (mm)", + "render.material_thin": "Dünne Schicht", + "render.material_title": "GPU-Bildmaterialien", + "render.material_transient": "Vorübergehende optische Überschreibungen für diesen Dokument-Tab. Sie werden weder im Design noch im Render-Setup oder in der Materialbibliothek gespeichert.", "render.material_v_up": "Textur-V zeigt im Bild nach oben", + "render.material_weight": "Klarlack-Gewicht (0–1)", + "render.method_cpu": "CPU-Raytracing", + "render.method_gpu": "GPU-Pathtracing", + "render.method_limit_raster": "Die Rasterung verwendet die feste undurchsichtige Studiovorschau. Wählen Sie ausdrücklich eine Raytracing-Methode für die unterstützten optischen Einstellungen.", + "render.method_raster": "CPU-Rasterung", "render.navigation_help": "Die Kamera bewegt sich wie im Konstruieren (Einstellungen › Navigation). Setup speichern übernimmt die aktuelle Kamera.", + "render.nested_enable": "Zertifizierte verschachtelte Dielektrika", + "render.nested_help": "Bis zu 16 umschließende Schichten; jedes übergeordnete Element muss konvex und jedes untergeordnete strikt darin enthalten sein. Überschneidungen, sich berührende Flächen, dünne Schichten und die Transmission gerader Schattenstrahlen werden abgelehnt. Der Zustand „Kamera im Inneren“ folgt der zertifizierten Hierarchie. Erzeugt keine Flüssigkeitsoberfläche und verschmilzt keine sich berührenden CAD-Grenzflächen.", "render.opaque_image_summary": "Vorschau-PNG · opakes PBR · Transparenz durch Blending", "render.opaque_preview_help": "Opakes PBR und einfache Farben; Transparenz durch Blending. Brechung, HDRI und finales Rendering sind noch nicht verfügbar.", + "render.optics_remove": "Gespeicherte Optik entfernen", + "render.optics_replace": "Gespeicherte Optik dieses Ziels ausdrücklich ersetzen", + "render.optics_save": "Diese Optik im Setup speichern", + "render.optics_saved": "Gespeicherte optische Ziele", + "render.optics_saved_help": "Die genaue Identität von Definition, Feature und Instanz bleibt beim Wiederöffnen ohne Verbindung erhalten. Fehlende, ersetzte oder ausgeblendete Ziele werden abgelehnt; technische Materialien bleiben unverändert. Speichern oder verwerfen Sie numerische Änderungen, bevor Sie ein gespeichertes Ziel entfernen.", "render.outer_half_angle": "Äußerer Halbwinkel", "render.output_advanced": "Erweitert", "render.output_backend_ready": "Bereit", @@ -2505,15 +3602,32 @@ "render.output_grading": "Farbkorrektur", "render.output_image": "Bild", "render.output_largest": "{width} × {height} max.", + "render.output_lock_ratio": "Seitenverhältnis sperren", + "render.output_over_budget": "Das angeforderte Bild überschreitet den gewählten Ressourcenrahmen. Wählen Sie ausdrücklich eine passende Größe oder ein passendes Profil; es erfolgt keine automatische Herabstufung.", "render.output_presets_help": "Format, Qualität und Prüfliste befinden sich im Ausgabeeditor.", "render.output_quality": "Qualität", "render.output_quality_waiting": "Qualitätsdefinition steht noch aus", + "render.output_ratio_refused": "Die verknüpfte Abmessung überschreitet das Größenlimit dieser Methode. Die vorherige Größe bleibt erhalten; entsperren Sie das Verhältnis oder wählen Sie einen kleineren Wert.", "render.output_ready": "Bereit zum Rendern", "render.output_run_check": "Prüfung starten", "render.output_size_limit": "{method}: bis zu {dimension} px pro Seite und {pixels} Pixel. Größte passende Größe: {width} × {height}.", + "render.output_size_method_profile": "Für {width} × {height} {method} mit dem CPU-Ressourcenprofil {profile} wählen oder eine kleinere Größe.", "render.output_size_ok": "Größe OK · {width} × {height} px", + "render.output_size_profile": "Für {width} × {height} das CPU-Ressourcenprofil {profile} wählen oder eine kleinere Größe.", + "render.output_swap_orientation": "Breite und Höhe tauschen", "render.output_tools_inspector": "Größe und Format im Ausgabe-Inspektor bearbeiten.", "render.output_view_image": "Bild anzeigen", + "render.page_aging": "Alterung und Verschmutzung", + "render.page_all": "Alle Einstellungen", + "render.page_appearance": "Erscheinungsbild", + "render.page_background": "Hintergründe", + "render.page_camera": "Kamera", + "render.page_diagnostics": "Diagnose", + "render.page_effects": "Objektiv- und Nachbearbeitungseffekte", + "render.page_environment": "Umgebung", + "render.page_lighting": "Beleuchtung", + "render.page_output": "Ausgabe", + "render.page_scene": "Szene", "render.paint_label": "Aufmalen", "render.painting_with": "Malen mit {name}", "render.passive_stage": "Render-only stage", @@ -2521,7 +3635,10 @@ "render.perspective": "Perspektivische Kamera", "render.physical_acknowledge": "I understand this partial reference needs grade, condition and source review", "render.physical_associations": "Physical candidates and roles", + "render.physical_background_help": "Echter passiver Boden und echte Wand, getrennt vom Kamerahintergrund. Der Rundhorizont besteht aus 24 polygonalen Streifen; er ist keine unendliche oder analytisch glatte Fläche. Ersetzt die gespeicherte Bühne nur mit Ihrer Zustimmung.", "render.physical_copy_plan": "Copy plan with sources and omissions", + "render.physical_cyclorama": "Polygonalen Rundhorizont anpassen", + "render.physical_floor_wall": "Physischen Boden und Wand anpassen", "render.physical_material_name": "Proposed reference material name", "render.physical_omissions": "Properties not representable in the native card", "render.physical_plan_only": "Read-only plan prepared. No material was created or assigned. Keep its extended profile and omissions when reviewing the native card.", @@ -2536,40 +3653,85 @@ "render.pick_up_label": "Aufnehmen", "render.pick_up_prompt": "Ein Objekt anklicken, um seinen Look aufzunehmen", "render.pick_waiting": "Die Produktauswahl wird noch nicht unterstützt.", + "render.post_contrast": "Kontrast", + "render.post_gain_b": "Blauverstärkung", + "render.post_gain_g": "Grünverstärkung", + "render.post_gain_r": "Rotverstärkung", + "render.post_help": "Nur kreative Darstellung. RGB-Verstärkungen wirken vor dem Tone-Mapping; Kontrast, Sättigung und Vignettierung folgen im anzeigelinearen Licht. „Rendering starten“ erzeugt neue Transport-Samples. „Neu graden“ verwendet das gewählte behaltene lineare Rohbild ohne Entrauschen oder neue Strahlen.", + "render.post_reset": "Darstellungsfilter zurücksetzen", + "render.post_saturation": "Sättigung", + "render.post_title": "Darstellungsfilter", + "render.post_vignette": "Vignettierung", "render.preview": "Integrierte Vorschau", "render.preview_help": "Rasterdarstellung mit gemischter Transparenz. Brechung, HDRI und finales Rendering sind noch nicht verfügbar.", + "render.preview_image_settings_help": "Die Live-Vorschau behält eine feste Studiobeleuchtung. Belichtung und Bildbeleuchtung gelten für den Bildauftrag, wenn Sie „Prüfen“ oder „Start“ verwenden.", "render.preview_lighting_help": "Die Live-Vorschau zeigt nur direktes Licht und keine Schatten.", + "render.preview_retry": "Live-Vorschau erneut versuchen", + "render.preview_unavailable_help": "Die Live-Vorschau ist nicht verfügbar. Gespeicherte Setups und Bildauftragseinstellungen bleiben zugänglich. Ändern Sie die Szene oder versuchen Sie es ausdrücklich erneut; eine abgelehnte Szene wird nicht bei jedem Frame neu aufgebaut.", + "render.preview_upload": "Vertex-Daten der Live-Vorschau", + "render.preview_upload_help": "Genaue Vertex-Bytes der Vorschau, nicht der gesamte GPU- oder Prozessspeicher. Die Geometrie wird nicht vereinfacht. Bildaufträge verwenden eigene Zulassung und Beleuchtung.", + "render.progressive_image_summary": "Vorschau-PNG · PBR und Glas · progressive Samples", "render.property_conditions": "Bedingungen: {value}", "render.property_fallback": "Eigenschaft", "render.property_qualifier": "Qualifikator: {value}", "render.property_source": "Quelle: {id} - {locator}", "render.property_uncertainty": "Unsicherheit: {value}", "render.property_unknown": "unbekannt", + "render.quality_ack": "Die Projektion mit festem Budget und ihre Auslassungen bestätigen", + "render.quality_apply": "Dieses feste Sampling-Budget verwenden", "render.quality_balanced": "Ausgewogen", "render.quality_custom": "Benutzerdefiniert", "render.quality_draft": "Entwurf", "render.quality_high": "Hoch", + "render.quality_projection_help": "Q-Vorgaben enthalten künftige Anforderungen. Diese Aktion projiziert nur ein unterstütztes PNG-Budget mit festen Samples und lässt adaptives Stoppen, rohe lineare Ausgabe und unabhängige Transmissionslimits ausdrücklich aus.", + "render.quality_review": "Sampling-Budget prüfen", + "render.queue_pending": "In dieser Oberfläche gibt es keine automatische Produktionswarteschlange und keinen Animations-Renderer. Fertige Einzelbilder bleiben separat exportierbar.", "render.radial_assign": "Erscheinungsbild zuweisen", "render.radial_compare": "Vergleichen", + "render.radial_distortion": "Radiale Verzeichnung", "render.radial_fit": "Produkt einpassen", "render.radial_save": "Aufnahme speichern", "render.recent_looks": "Letzte Looks", + "render.regrade_action": "Lineares Rohbild neu graden (ohne Entrauschen)", + "render.regrade_help": "Erzeugt aus dem gewählten fertigen linearen Rohbild mit diesen Darstellungseinstellungen ein separates PNG. Es werden keine Strahlen verfolgt, Größe, Kamera und Lichter der Aufnahme nicht geändert und das EXR nicht überschrieben. Das Entrauschen wird nicht erneut angewendet: Rohbilder behalten dessen Führungsdaten nicht. Das abgeleitete Bild bleibt über dieselben Auftragssteuerungen exportierbar.", "render.regrade_label": "Neu abstimmen", "render.reload_settings": "Gespeicherte Einstellungen laden", "render.remove_override": "Überschreibung entfernen", "render.replace_all": "Alle ersetzen", + "render.replace_ground": "Ersetzen der vorhandenen Bühne bestätigen", "render.replace_label": "Ersetzen", "render.replace_saved_surface": "Replace an existing saved binding for this target", "render.replace_with": "Ersetzen durch", "render.restore_camera": "Gespeicherte Kamera laden", "render.result_actual": "100%", + "render.result_actual_help": "Ein Bildpixel pro Bildschirmpixel.", "render.result_actual_size": "100%", + "render.result_capture": "Erfasste Revision", + "render.result_current": "Die erfasste Modellrevision ist aktuell.", + "render.result_empty": "Noch kein fertiges Bild. Prüfen Sie die Einstellungen und starten Sie dann ein Rendering.", + "render.result_fit": "Bild einpassen", + "render.result_job": "Auftrag", + "render.result_navigation": "Verschieben und Zoomen folgen den Navigationseinstellungen. Leertaste + Ziehen verschiebt.", + "render.result_open": "Das fertige Bild in der Hauptansicht öffnen.", + "render.result_preview": "Live-Vorschau", + "render.result_provisional": "Vorläufiges CPU-Bild", + "render.result_provisional_help": "Dieser Zwischenstand ist nicht exportierbar. Der Export behält das letzte fertige Ergebnis; ein Abbruch kehrt zu diesem Ergebnis zurück.", "render.result_reduced_display": "Anzeigevorschau auf die Geräte-/Cachegrenze reduziert. PNG und Export behalten die volle Auflösung; native 100%-Ansicht ist hier nicht verfügbar.", + "render.result_retained": "Das zuletzt fertiggestellte Bild wird angezeigt; ein neueres Rendering hat es noch nicht ersetzt.", + "render.result_sequence": "Prüfpunkt", + "render.result_title": "Render-Ergebnis", + "render.results_choose": "Behaltene Ergebnisse", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [veraltet]", + "render.results_unnamed": "Bild", "render.return_design": "Zurück zu Design", + "render.review_stale": "Diese Prüfung ist veraltet. Lösen Sie sie auf oder prüfen Sie erneut, bevor Sie sie anwenden.", + "render.ribbon_aging": "Alterung", "render.ribbon_backgrounds": "Hintergründe", "render.ribbon_check": "Prüfen", "render.ribbon_check_help": "Genau den aktuellen Renderentwurf prüfen. Kein stiller Rendererwechsel, keine Verkleinerung oder Ersetzung.", "render.ribbon_edit_lights": "Licht ändern", + "render.ribbon_effects": "Effekte", "render.ribbon_environment_help": "HDR-Beleuchtung, Kamerahintergründe und physische Bühnen sind getrennte Einstellungen mit ausdrücklicher Ersetzungsbestätigung.", "render.ribbon_finish_dialog": "Zuerst den Datei- oder Bestätigungsdialog abschließen.", "render.ribbon_frame": "Einpassen", @@ -2587,6 +3749,8 @@ "render.ribbon_studios": "Studios", "render.ribbon_studios_help": "Implementierte Studios durchsuchen und Ersetzungen vor dem Anwenden prüfen. Konzepte bleiben gekennzeichnet.", "render.ribbon_surface_maps": "Oberflächen", + "render.sampling_title": "Adaptives Sampling und Transmissions-Sampling", + "render.save_continue": "Speichern und fortfahren", "render.save_setup": "Setup speichern", "render.save_shot": "Aufnahme speichern", "render.saved_maps_runtime_conflict": "Saved surface bindings cannot be mixed with temporary optical overrides or an unsaved HDR. Save the HDR or remove the temporary inputs explicitly.", @@ -2594,27 +3758,43 @@ "render.saved_surfaces": "Saved surface bindings", "render.saved_surfaces_help": "Pinned built-in maps follow the selected occurrence in local millimeters. A replaced or missing target is an error, never an automatic reassignment.", "render.scene_all_shots": "Alle Aufnahmen ({count})", + "render.scene_apply": "Geprüftes Studio anwenden", "render.scene_batch_reason": "Alle Aufnahmen benötigen die noch nicht verfügbare Renderwarteschlange.", "render.scene_check_now": "Jetzt prüfen", "render.scene_check_passed": "Prüfung bestanden · {notes} Hinweise", "render.scene_check_stale": "Prüfung veraltet · erneut prüfen", "render.scene_check_unchecked": "Noch nicht geprüft · 0 Hinweise", + "render.scene_consent": "Ersetzen von Beleuchtung, Umgebung, Belichtung und Bühne bestätigen", "render.scene_light_summary": "{environment} · {lights} Lichter", "render.scene_look_summary": "{looks} Looks · {overrides} Überschreibungen", "render.scene_open_check": "Prüfung öffnen", + "render.scene_preserved_fields": "Kamera, Sampling, Abmessungen, optische Bindungen, CAD-Geometrie und technische Materialien bleiben erhalten.", + "render.scene_preserves_design": "Beleuchtung und eine passive Bühne für das sichtbare Motiv zusammenstellen. Geometrie, technische Materialien und die Kamera bleiben getrennt.", "render.scene_ready": "Bereit zum Rendern", "render.scene_reminder": "Die Szene bewahrt den Entwurf. Geometrie, technische Eigenschaften und CAD werden in Render nie verändert.", "render.scene_reminders": "Hinweise", "render.scene_renderer_ready": "{renderer} bereit", + "render.scene_replaces": "Ersetzt", + "render.scene_review": "Auflösen und prüfen", + "render.scene_review_help": "Prüfen Sie die vollständige native Zusammenstellung, bevor Sie sie anwenden. Nicht zugeordnete erweiterte SCENE-Spezifikationen werden nicht ersetzt.", + "render.scene_scope_details": "Umfang der Zusammenstellung", "render.scene_stages": "Phasen", "render.search_appearances": "{count} Erscheinungsbilder durchsuchen", + "render.setup_legacy_environment": "Dieses ältere Setup verwendet eine veraltete Umgebungsdrehung oder -intensität. Diese Werte bleiben erhalten; wandeln Sie sie ausdrücklich um, bevor Sie einen vollständigen Bildauftrag speichern.", "render.setup_name": "Name des Setups", + "render.setup_numeric_help": "„Speichern“ hält die aktive Bildmethode und alle ihre numerischen Einstellungen fest. Erneutes Laden oder die Wahl eines anderen Setups ersetzt diesen Entwurf; stellen Sie die Kamera separat wieder her.", + "render.setup_offline_help": "Sie können diese Methode ohne ihren Renderer bearbeiten und speichern. „Prüfen“ und „Start“ erfordern einen verfügbaren Host.", + "render.setup_runtime_unsupported": "Dieser vollständige Auftrag kann noch nicht gespeichert werden: Er enthält Texturen oder Szenenkörper-Bindungen. Entfernen Sie diese temporären Eingaben, bevor Sie ein portables Setup speichern.", + "render.setup_save_missing": "Die gespeicherte Render-Konfiguration konnte nach Abschluss des Befehls nicht gefunden werden.", + "render.sharpening": "Detailschärfung", "render.shell_tab_appearance": "Aussehen", "render.shell_tab_camera": "Kamera", + "render.shell_tab_lighting": "BELEUCHTUNG", "render.shell_tab_scene": "SZENE", "render.shot_aperture": "Blende", "render.shot_distance": "Abstand", "render.shot_dof": "Schärfentiefe", + "render.shot_duplicate": "Gespeicherte Aufnahme duplizieren", "render.shot_edit_output": "In Ausgabe bearbeiten", "render.shot_exposure_reason": "Belichtung benötigt CPU-Strahlverfolgung oder GPU-Pfadverfolgung.", "render.shot_exposure_section": "Belichtung", @@ -2627,6 +3807,13 @@ "render.shot_lens_gpu_reason": "Schärfentiefe benötigt GPU-Pfadverfolgung.", "render.shot_lens_perspective_reason": "Schärfentiefe benötigt perspektivische Projektion.", "render.shot_look_selection": "Auswahl anvisieren", + "render.shot_manager": "Gespeicherte Aufnahmen", + "render.shot_new_name": "Neuer Aufnahmename", + "render.shot_remove": "Gespeicherte Aufnahme entfernen", + "render.shot_remove_help": "Nur dieses gespeicherte Setup entfernen. Quellgeometrie und fertige Bilder bleiben erhalten; die Aktion lässt sich rückgängig machen.", + "render.shot_remove_title": "Gespeicherte Aufnahme entfernen?", + "render.shot_rename": "Gespeicherte Aufnahme umbenennen", + "render.shot_saved_only": "Speichern Sie zuerst den aktuellen Entwurf. Duplizieren und Umbenennen behalten die genauen gespeicherten Optionen und Ressourcenverweise bei.", "render.shot_selection_reason": "Einen Körper oder eine Fläche als Ziel auswählen.", "render.shot_size": "Größe", "render.shot_target": "Ziel", @@ -2643,10 +3830,15 @@ "render.size_custom": "Benutzerdefiniert…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · erfordert {profile}", "render.size_presets": "Größenvorlagen", "render.size_presets_pending": "Kommt mit dem Ausgabeeditor", "render.size_preview": "Vorschau", "render.size_square": "Quadrat", + "render.sky_ground": "Boden · lineares RGB", + "render.sky_horizon": "Horizont · lineares RGB", + "render.sky_zenith": "Zenit · lineares RGB", + "render.soft_focus": "Weichzeichnung", "render.spot_cone": "Spotkegel", "render.stage_frame": "Bildausschnitt", "render.stage_layout.appearance_note": "Zum Anwenden auf die Auswahl klicken.", @@ -2747,10 +3939,55 @@ "render.state_in_progress": "Bild in Bearbeitung", "render.state_model": "Modellvorschau", "render.strip_label": "Leiste", + "render.studio_add_area": "Flächenlicht hinzufügen", + "render.studio_ambient": "Konstante Umgebungsstrahldichte", + "render.studio_ambient_rgb": "Konstante Umgebungsstrahldichte (lineares RGB)", + "render.studio_aperture": "Blendenradius", + "render.studio_area": "Flächenlicht", + "render.studio_area_help": "Bis zu vier einseitige Rechtecke. Orthogonale Halbkanten U und V bestimmen die Größe; U × V zeigt zur beleuchteten Seite. Die Koordinaten sind Weltmillimeter.", + "render.studio_center": "Mittelpunkt X, Y, Z (mm)", + "render.studio_denoise": "Rauschen im fertigen Bild reduzieren", + "render.studio_denoise_help": "Abschließender kantenerhaltender Filter; feine Details können weicher werden. Glas und scharfe spiegelnde Oberflächen umgehen den Filter.", + "render.studio_direction": "Richtung zur Sonne (X, Y, Z)", + "render.studio_environment": "Umgebung", + "render.studio_environment_bounds": "Die Umgebungsdrehung muss endlich und innerhalb von ±1.000.000 Radiant liegen, die Intensität zwischen 0 und 100.", + "render.studio_environment_none": "Keine Umgebungskarte", + "render.studio_focus": "Axialer Fokusabstand", + "render.studio_half_u": "Halbkante U (mm)", + "render.studio_half_v": "Halbkante V (mm)", + "render.studio_hdr": "Radiance-HDR-Datei", + "render.studio_hdr_browse": "HDR wählen…", + "render.studio_hdr_help": "Radiance-.hdr-Datei, 2:1-Panorama, bis zu 2048 × 1024. EXR ist nicht verfügbar. Die Farbannahme gilt nur, wenn keine Primärfarben angegeben sind.", + "render.studio_hdr_required": "Wählen Sie eine lokale .hdr-Datei.", + "render.studio_hdr_srgb": "Nicht angegebene Primärfarben als lineares sRGB interpretieren", + "render.studio_intensity": "Umgebungsintensität", + "render.studio_lens": "Schärfentiefe", + "render.studio_lens_perspective": "Die Schärfentiefe erfordert eine perspektivische Kamera.", + "render.studio_lighting": "Studiobeleuchtung", + "render.studio_lighting_enable": "Eigene Studiobeleuchtung verwenden", + "render.studio_needs_review": "Methode und Einstellungen prüfen", + "render.studio_radiance": "Strahldichte in linearem RGB", + "render.studio_ready": "Bereit zur Prüfung", + "render.studio_remove_area": "Flächenlicht entfernen", + "render.studio_rotation": "Umgebungsdrehung", + "render.studio_runtime_help": "Numerische Studioeinstellungen und geprüfte HDR-Quellen können mit dem Setup gespeichert werden. Optische bzw. Materialüberschreibungen von Körpern bleiben vorübergehend und ändern gespeicherte Erscheinungsbilder nicht.", + "render.studio_saved": "Gespeichertes Setup / aktuelle Kamera", + "render.studio_sky": "Künstlerischer Himmel", + "render.studio_sky_help": "Originaler Himmelsverlauf für die Beleuchtung; kein kalibriertes Atmosphärenmodell.", + "render.studio_sun": "Sonne", + "render.studio_sun_radius": "Winkelradius", "render.studio_tiles_require_gpu": "Studios benötigen GPU-Pfadverfolgung. Im Ausgabeeditor GPU wählen.", + "render.studio_title": "Render-Studio", + "render.studio_tone_map": "Tone-Mapping", "render.studios_environments": "Studios und Umgebungen", + "render.subsurface_enable": "Random Walk für innere Streuung", + "render.subsurface_help": "Nur für geschlossene Dielektrika. Streuung und RGB-Absorption sind getrennte Koeffizienten pro mm. Pfade streuen innerhalb der tatsächlichen Geometrie und werden dann an der Grenzfläche gebrochen oder reflektiert. Deaktivieren Sie die Transmission gerader Schattenstrahlen, das Entrauschen von Oberflächen und das äußere Volumen; verwenden Sie eine Fresnel-Schicht. Kein Diffusions-Shader, kein Dichtegitter und kein gemessenes Material. Dichte Medien können mehr Samples und Pfadtiefe benötigen.", + "render.subsurface_rate": "Streukollisionsrate", "render.tone_aces_fitted": "ACES angepasst", "render.tone_reinhard": "Reinhard", + "render.transmission_scope": "GPU-Glas unterstützt zertifizierte getrennte Medien. Unbeschränkt verschachtelte Medien und ein rauschfreier Transmissionsschätzer werden nicht bereitgestellt.", + "render.transmission_strata": "Bedingte Fresnel-Schichten", + "render.transmission_strata_help": "1 behält die ursprüngliche Zufallsfolge bei. 2 oder 4 Teilpfade stratifizieren die erste Wahl zwischen Reflexion und Transmission am Glas bei unveränderten Snell- und Absorptionsgesetzen. Mehr Pfade kosten mehr Rechenaufwand; das ist weder Entrauschen noch Unterstützung für verschachtelte Medien noch ein Versprechen schnelleren Renderns.", "render.tree_add_light": "Licht hinzufügen", "render.tree_add_shot": "Aufnahme hinzufügen", "render.tree_browser": "Render-Browser", @@ -2788,6 +4025,14 @@ "render.unavailable_preview": "Dieses Setup verlangt ein nicht verfügbares Vorschauprofil.", "render.unsaved": "Ungespeicherte Vorschauänderungen", "render.use_preview": "Integrierte Vorschau verwenden", + "render.volume_albedo": "Streualbedo · lineares RGB", + "render.volume_anisotropy": "Mittlerer Phasenkosinus", + "render.volume_enable": "Teilnehmendes Medium aktivieren", + "render.volume_extinction": "Extinktionskoeffizient", + "render.volume_help": "GPU-Transport innerhalb einer endlichen Box, mit Beer-Lambert-Abschwächung und HG-Streuung auf Kamera- und indirekten Pfaden. Verwendet ausdrückliche Studio-, HDR- und Himmelsbeleuchtung einschließlich Schattenabschwächung. Ein positiver Phasenkosinus streut nach vorn. Glasgrenzflächen und Oberflächenentrauschen müssen ausdrücklich deaktiviert werden. Extinktion null lässt den Transport unverändert. Keine physikalische Mondatmosphäre, kein Dichtegitter, keine Volumenemission, kein spektraler Transport und keine zertifizierte Materialeigenschaft.", + "render.volume_max": "Obere Grenzen · Weltkoordinaten (mm)", + "render.volume_min": "Untere Grenzen · Weltkoordinaten (mm)", + "render.volume_title": "Begrenztes homogenes Volumen", "render.wait_add_light": "Noch nicht unterstützt: benannte Lichtquellen erstellen", "render.wait_batch": "Noch nicht unterstützt: Renderwarteschlange gespeicherter Aufnahmen", "render.wait_compare": "Noch nicht unterstützt: Vergleich gespeicherter Bilder", @@ -2827,6 +4072,7 @@ "search.suggest": "Meinten Sie {label}?", "search.try": "Geben Sie einen Befehlsnamen, ein Merkmal in diesem Design oder einen Parameter ein. Um einen Befehl mit Werten auszuführen, geben Sie seine ID und ein JSON-Objekt ein: {example}", "search.valid": "Gültig", + "section.off_hint": "Keine Ebene gewählt: „OK“ schaltet den Schnitt aus.", "select a direction (an axis, a sketch line or a straight edge) first": "zuerst eine Richtung auswählen (eine Achse, eine Skizzenlinie oder eine gerade Kante)", "select a direction (an axis, a sketch line or a straight edge) for the profile to follow": "eine Richtung auswählen (eine Achse, eine Skizzenlinie oder eine gerade Kante), der das Profil folgen soll", "select a point on a component": "einen Punkt auf einer Komponente auswählen", @@ -2834,6 +4080,7 @@ "select an axis": "eine Achse auswählen", "select an axis, a straight or circular edge, or a cylinder, cone or torus face first": "zuerst eine Achse, eine gerade oder kreisförmige Kante oder eine Zylinder-, Kegel- oder Torusfläche auswählen", "select bodies first": "zuerst Körper auswählen", + "select components first": "zuerst Komponenten auswählen", "select corner points, or the two lines of one corner": "Eckpunkte oder die zwei Linien einer Ecke auswählen", "select one corner point, or the two lines of one corner": "einen Eckpunkt oder die zwei Linien einer Ecke auswählen", "select sheet edges first": "zuerst Blechkanten auswählen", @@ -2847,11 +4094,13 @@ "select the rim face first": "zuerst die Randfläche auswählen", "select the sheet edge first": "zuerst die Blechkante auswählen", "select two components": "zwei Komponenten auswählen", + "set by the sketch's lines": "durch die Skizzenlinien festgelegt", "settings.display_quality_note": "Feinere Stufen zeigen gekrümmte Flächen und Kanten glatter und brauchen länger zum Vernetzen. Nur die Ansicht ändert sich, nie das Design oder Exporte.", - "settings.double_click_components": "Doppelklick auf eine Komponente aktiviert sie oder bearbeitet eine verknüpfte an Ort und Stelle", + "settings.double_click_components": "Komponente zum Aktivieren doppelklicken", + "settings.frame_rate_details_note": "Fügt ein Diagramm der Bildzeiten der letzten Bilder hinzu, darüber die gezeichneten Dreiecke, dazu ein Histogramm der Bildzeiten und was die GPU gezeichnet hat. Ein Klick auf die Bildrate in der Ansicht blendet sie ein oder aus.", "settings.frame_rate_note": "Zeigt die Bilder pro Sekunde unten rechts in der Ansicht.", - "settings.insert_lists_open_designs": "Konstruktion einfügen zeigt zuerst die in anderen Tabs geöffneten Konstruktionen", - "settings.measure_axis_distances": "X/Y/Z-Maße anzeigen", + "settings.insert_lists_open_designs": "Konstruktion einfügen listet offene Konstruktionen zuerst", + "settings.measure_axis_distances": "Achsabstände beim Messen", "settings.measure_axis_distances_help": "Bei geöffneter Messung die Abstände entlang der Weltachsen zusätzlich zum Gesamtabstand anzeigen.", "settings.msaa_applies_on_restart": "Die Kantenglättung wird beim nächsten Start von SolidCraft übernommen", "settings.msaa_reset": "{setting}: {requested}× wird von diesem Grafikgerät nicht unterstützt; jetzt {reset}× (unterstützt: {supported}).", @@ -2861,10 +4110,32 @@ "settings.reset_intro": "Diese Einstellungen funktionieren auf diesem Computer nicht und würden den Start von SolidCraft verhindern. Sie wurden daher geändert:", "settings.reset_title": "Einstellungen wurden geändert", "settings.supersampling_note": "Zeichnet die Ansicht in höherer Auflösung und rechnet sie herunter: glattere Kanten, Linien und Raster auf Bildschirmen unter 4K. Kostet GPU-Zeit: etwa 2,25-mal so viele Pixel bei 1,5× und 4-mal bei 2×.", - "settings.update_changed_links": "Geänderte verknüpfte Designs aktualisieren, wenn ein Tab wieder angezeigt wird", + "settings.update_changed_links": "Geänderte Verknüpfungen bei Rückkehr zum Tab aktualisieren", + "settings.window_system_details": "Details", + "settings.window_system_note_now": "Wird nach einem Neustart wirksam. Aktuell: {now}.", + "settings.window_system_wayland_limited": "Einige Funktionen sind unter nativem Wayland eingeschränkt.", "sheet.flange_type_base": "Basislasche", "sheet.flange_type_contour": "Konturlasche", "sheet.flange_type_edge": "Kantenlasche", + "sheet.no_body": "es gibt keinen Blechkörper: Beginnen Sie einen mit Flansch > Basislasche oder wandeln Sie eine Platte mit „In Blech umwandeln“ in Blech um (ihre große ebene Fläche wählen)", + "sheet.personal_rules.confirm_delete": "Löschen bestätigen", + "sheet.personal_rules.delete": "Löschen", + "sheet.personal_rules.delete_prompt": "Möchten Sie diese persönliche Regel wirklich löschen? Regeln, die bereits in Entwürfen sind, bleiben unverändert.", + "sheet.personal_rules.full": "Die persönliche Bibliothek enthält bereits 64 Regeln.", + "sheet.personal_rules.invalid_name": "Geben Sie einen kurzen Namen ohne Zeilenumbrüche oder Steuerzeichen ein.", + "sheet.personal_rules.invalid_values": "Vervollständigen Sie die Werte der Regel: Jeder muss sich in diesem Entwurf berechnen lassen, mit positiver Dicke und einem K-Faktor von 0 bis 1.", + "sheet.personal_rules.missing": "Die ausgewählte persönliche Regel ist nicht mehr verfügbar.", + "sheet.personal_rules.name": "Regelname", + "sheet.personal_rules.name_exists": "Eine persönliche Regel mit diesem Namen existiert bereits. Wählen Sie einen anderen Namen.", + "sheet.personal_rules.name_hint": "Eindeutigen Namen eingeben", + "sheet.personal_rules.overwrite": "Änderungen in der ausgewählten persönlichen Regel speichern", + "sheet.personal_rules.rename": "Umbenennen", + "sheet.personal_rules.rule": "Persönliche Regel", + "sheet.personal_rules.save": "Als neue Regel speichern", + "sheet.personal_rules.scope": "In Ihrem Profil gespeichert und für alle Entwürfe verfügbar.", + "sheet.personal_rules.select": "Regel auswählen", + "sheet.personal_rules.title": "Persönliche Regeln", + "sheet.personal_rules.unsupported": "Diese Regel enthält Werte, die diese Version nicht verwenden kann.", "shortcut.json_error": "Parameter müssen JSON sein: {error}", "shortcut.no_command": "kein Befehl `{id}`; der Text vor dem JSON muss eine Befehls-ID sein", "shortcut.pin": "Oben im S-Feld anheften", @@ -2887,6 +4158,11 @@ "sketch_panel.author": "Autorenplatzierung: {path}", "sketch_panel.dimension_hint": "Einen Wert oder Ausdruck eingeben, dann OK drücken.", "sketch_panel.move_hint": "Abstände und einen Winkel eingeben, dann OK drücken.", + "sketch_panel.plane_angle": "{plane}, gedreht um {angle}", + "sketch_panel.plane_fixed": "Eine feste Ebene", + "sketch_panel.plane_flipped": "{plane}, von ihrer anderen Seite", + "sketch_panel.plane_offset": "{plane}, versetzt um {distance}", + "sketch_panel.plane_origin": "Die {plane}-Ebene", "sketch_panel.redefine_title": "{command}: {name}", "sketch_panel.sheet_attachment": "An eine ebene Fläche eines Blechkörpers angehängt; folgt diesem Bereich bei Änderungen am Blech.", "sketch_panel.text_hint": "Text und Platzierung bearbeiten, dann OK drücken.", @@ -2896,8 +4172,10 @@ "sketch_text.align_right": "Rechts", "sketch_text.bold": "Fett", "sketch_text.builtin_font": "{family} (integriert)", + "sketch_text.formula": "Mit = beginnen, um den Text aus Parametern aufzubauen: ='W' + number(Width)", "sketch_text.italic": "Kursiv", "sketch_text.loading_fonts": "Installierte Schriftarten werden gesucht…", + "sketch_text.no_bold": "Die integrierte Schrift hat keinen fetten Schnitt: Wählen Sie eine installierte Schriftart", "sketch_text.on_path": "Der Text folgt seiner Kurve: sie bestimmt seine Lage", "sketch_text.path_clear": "Text von der Kurve lösen", "sketch_text.path_hint": "Eine Skizzenkurve, der der Text folgt: hier klicken, dann die Kurve", @@ -2928,13 +4206,30 @@ "the section's profiles must be in one sketch": "die Profile des Querschnitts müssen in einer Skizze liegen", "the two origins are on the same component": "die beiden Ursprünge liegen auf derselben Komponente", "thread.automatic_size": "Automatische Größe", + "thread.chamfer_depth_needed": "für diese Form erforderlich", "thread.designation": "Bezeichnung", + "thread.drill_range": "Der Bohrer des Gewindebohrerherstellers ist {drill} mm. Der genormte Kerndurchmesser des Innengewindes ist {minor} mm. Ein Bohrer von {low} bis {high} mm wird angenommen.", + "thread.drill_range_custom": "Der Bohrer ist der Nenndurchmesser minus Steigung, {drill} mm. Der genormte Kerndurchmesser des Innengewindes ist {minor} mm. Ein Bohrer von {low} bis {high} mm wird angenommen.", + "thread.drill_range_taper": "Der Bohrer des Gewindebohrerherstellers ist {drill} mm. Der genormte Kerndurchmesser am Gewindeende ist {minor} mm. Ein Bohrer von {low} bis {high} mm wird angenommen.", + "thread.end_square": "Rechtwinklig", + "thread.fade_short": "1,25 P (ISO 3508)", + "thread.fade_standard": "2,5 P (ISO 3508)", + "thread.form_bspp": "Rohrgewinde G (ISO 228-1)", + "thread.form_bspt": "Kegeliges Rohrgewinde R, Rc (ISO 7-1)", + "thread.form_npt": "Kegeliges Rohrgewinde NPT (ASME B1.20.1)", + "thread.form_rp": "Zylindrisches Innenrohrgewinde Rp (ISO 7-1)", "thread.iso_metric": "ISO metrisch", "thread.select_size": "Größe wählen", + "timeline.delete_after_marker_one": "1 Merkmal nach der Verlaufsmarkierung löschen", + "timeline.delete_after_marker_other": "{count} Merkmale nach der Verlaufsmarkierung löschen", + "timeline.delete_folders_tip": "Ihre Merkmale und verschachtelten Ordner im Verlauf behalten", "timeline.delete_folders_with_features_tip": "Löscht die Ordner mit allen Features darin und ihren Unterordnern", + "timeline.delete_many": "{count} ausgewählte Merkmale löschen", "timeline.edited_rolled_back": "{name} geändert, liegt aber hinter der Verlaufsmarke und wird daher nicht erzeugt: Marke dahinter ziehen, um das Ergebnis zu sehen", + "timeline.feature_error": "Fehler: {message}", "timeline.feature_hint": "Doppelklicken zum Bearbeiten · Ziehen zum Neuordnen · Rechtsklicken für weitere Optionen", "timeline.feature_rolled_back": "Zurückgesetzt: hinter der Verlaufsmarke, daher nicht erzeugt", + "timeline.feature_warning": "Warnung: {message}", "timeline.group": "Neuen Merkmalsordner anlegen", "timeline.move_many": "Zeitleistenelemente verschieben", "timeline.move_to_group": "Merkmale in Ordner verschieben", @@ -3027,6 +4322,8 @@ "ui.3d_mouse_section": "3D-Maus", "ui.3d_mouse_show_in_view": "3D-Maus in der 3D-Ansicht anzeigen", "ui.3d_mouse_show_in_view_tip": "Ein Bild Ihrer 3D-Maus unten links, das sich mit ihr bewegt.", + "ui.3d_mouse_sketch_orbit": "Skizzen mit der 3D-Maus drehen", + "ui.3d_mouse_sketch_orbit_tip": "Die 3D-Maus dreht die Ansicht auch, solange eine Skizze offen ist und frontal gesehen wird, wie es die Maus kann. Aus: Sie verschiebt und zoomt die Skizze, bis Sie die Ansicht neigen.", "ui.3d_mouse_skip": "Mein Gerät kann das nicht", "ui.3d_mouse_skip_tip": "Überspringt diese Bewegung in beide Richtungen; die Kalibrierung lässt sie aus.", "ui.3d_mouse_speed": "Geschwindigkeit der 3D-Maus", @@ -3055,6 +4352,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Kappe gegen den Uhrzeigersinn drehen, halten, dann loslassen.", "ui.3d_mouse_switch_cap": "Als Zurück zur Mitte kalibrieren", "ui.3d_mouse_switch_trackball": "Als Trackball kalibrieren", + "ui.3d_mouse_use_direct": "Direkten Treiber verwenden", + "ui.3d_mouse_use_direct_tip": "Die 3D-Maus direkt lesen (hidraw) statt über spacenavd.", "ui.3d_mouse_view_axis": "Ansichtsachse", "ui.3d_mouse_view_off": "Aus", "ui.3d_mouse_view_off_tip": "Das Profil des 3D-Maus-Treibers schaltet diese Achse ab, daher bewegt ihre Bewegung die Ansicht nicht. Wählen Sie hier die Bewegung einer anderen Achse, werden die beiden getauscht und sie bewegt die Ansicht nicht mehr.", @@ -3080,6 +4379,8 @@ "ui.agent_chat_allowed": "Erlaubt", "ui.agent_chat_answered": "Antwort: {option}", "ui.agent_chat_approval": "Darf der Agent das tun?", + "ui.agent_chat_attach_selection": "Auswahl anhängen", + "ui.agent_chat_attach_selection_tip": "Das im Modell Ausgewählte (Flächen, Kanten, Merkmale, Körper) mit der Nachricht senden, damit der Agent weiß, was Sie meinen", "ui.agent_chat_attach_view": "Ansicht anhängen", "ui.agent_chat_attach_view_tip": "Ein Bild der aktuellen Ansicht mit der Nachricht senden", "ui.agent_chat_attachable": "Bilder, PDFs, Text- und CAD-Dateien", @@ -3091,12 +4392,23 @@ "ui.agent_chat_auth_terminal": "Führen Sie dies in einem Terminal aus und klicken Sie dann erneut auf Verbinden:", "ui.agent_chat_auth_title": "Beim Agenten anmelden", "ui.agent_chat_cancel": "Abbrechen", + "ui.agent_chat_cancel_timeout": "Der Agent hat nicht auf Stopp reagiert und wurde getrennt. Zum Fortfahren erneut verbinden.", + "ui.agent_chat_cannot_start": "Installiert, startet aber nicht: {error}", "ui.agent_chat_changes": "Änderungen: {n}, ein Rückgängig-Schritt", + "ui.agent_chat_changes_n": "{n} Änderungen", "ui.agent_chat_changes_of": "{n}/{limit} Änderungen", + "ui.agent_chat_choose_model": "Modell wählen", "ui.agent_chat_close": "Schließen", "ui.agent_chat_command": "Agentenbefehl", "ui.agent_chat_connect": "Verbinden", "ui.agent_chat_copy": "Kopieren", + "ui.agent_chat_copy_message": "Nachricht kopieren", + "ui.agent_chat_ctx_bodies": "Körper", + "ui.agent_chat_ctx_elements": "Elemente", + "ui.agent_chat_ctx_features": "Funktionen", + "ui.agent_chat_ctx_more": "+{n} weitere", + "ui.agent_chat_ctx_other": "Sonstiges", + "ui.agent_chat_custom_heading": "Eigenes Modell", "ui.agent_chat_custom_hint": "Jedes Programm, das das Agent Client Protocol über stdin und stdout spricht. Es läuft ohne Shell.", "ui.agent_chat_denied": "Abgelehnt", "ui.agent_chat_deny": "Ablehnen", @@ -3132,13 +4444,24 @@ "ui.agent_chat_import_failed": "{name}: Der Import ist fehlgeschlagen: {error}", "ui.agent_chat_intro": "Chatten Sie mit einem Coding-Agenten, den Sie schon nutzen, oder einem Modell-Endpunkt Ihrer Wahl. Er arbeitet über die Werkzeuge von SolidCraft am geöffneten Design: Seine Änderungen erscheinen sofort und lassen sich pro Nachricht in einem Schritt rückgängig machen. Was er ohne Nachfrage darf, legen Sie unter Einstellungen > KI fest.", "ui.agent_chat_key_in_env": "Schlüssel gesetzt", + "ui.agent_chat_last_missing": "Der zuletzt verwendete Agent ({agent}) ist nicht mehr verfügbar. Wählen Sie einen Agenten und klicken Sie dann auf „Erneut versuchen“.", "ui.agent_chat_left": "Links", "ui.agent_chat_limit": "Der Agent hat die Grenze von {limit} Änderungen für eine Nachricht erreicht. Senden Sie eine weitere Nachricht, damit er weitermacht.", + "ui.agent_chat_login_found": "Anmeldung gefunden", "ui.agent_chat_minimize": "Zu einer Leiste minimieren", "ui.agent_chat_mode_all": "Alles", "ui.agent_chat_mode_ask": "Fragen", "ui.agent_chat_mode_edits": "Ändern", + "ui.agent_chat_model_custom": "Eigenes verwenden: {model}", + "ui.agent_chat_model_no_tools": "{model} kann die Werkzeuge von SolidCraft nicht verwenden und daher nur chatten. Wählen Sie ein Modell mit Werkzeugunterstützung.", + "ui.agent_chat_model_rejected": "Der Agent hat {model} nicht akzeptiert: {error}", + "ui.agent_chat_model_search": "Modelle suchen…", "ui.agent_chat_model_tip": "Das vom Agenten verwendete Modell. Ihre Auswahl wird für diesen Agenten gespeichert.", + "ui.agent_chat_models_failed": "Modelle konnten nicht abgerufen werden: {error}", + "ui.agent_chat_models_heading": "Verfügbare Modelle", + "ui.agent_chat_models_listing": "Modelle werden abgerufen…", + "ui.agent_chat_models_none": "Der Endpunkt listet keine Modelle", + "ui.agent_chat_models_not_a_list": "Die Antwort war keine Modellliste", "ui.agent_chat_new": "Neuer Chat", "ui.agent_chat_new_confirm": "Neuen Chat starten? Der aktuelle wird geleert.", "ui.agent_chat_next_picture": "Nächstes Bild", @@ -3146,6 +4469,8 @@ "ui.agent_chat_no_control": "Der Endpunkt des Agenten-Chats ist nicht gestartet, daher kann der Agent das Design nicht erreichen.", "ui.agent_chat_no_images": "Dieser Agent nimmt keine Bilder an", "ui.agent_chat_no_picture": "In der Zwischenablage befindet sich kein Bild", + "ui.agent_chat_no_tool_call": "Das Modell hat die Werkzeuge von SolidCraft nicht verwendet, daher wurde das Design nicht geändert. Wählen Sie ein Modell, das Werkzeugaufrufe unterstützt; siehe „Lokale Modelle“ im Leitfaden zum Agenten-Chat.", + "ui.agent_chat_node_too_old": "Node.js {version} ist für diesen Agenten zu alt. Installieren Sie Node.js 20.10 oder neuer und klicken Sie dann auf Aktualisieren.", "ui.agent_chat_none_found": "Kein Coding-Agent gefunden. Installieren Sie einen davon und klicken Sie dann auf Aktualisieren:", "ui.agent_chat_none_found_short": "Kein Agent gefunden", "ui.agent_chat_not_installed": "Nicht installiert", @@ -3155,21 +4480,30 @@ "ui.agent_chat_paste_picture": "Bild einfügen", "ui.agent_chat_permission": "Der Agent möchte ausführen: {title}", "ui.agent_chat_pick": "Agent", + "ui.agent_chat_pick_context": "Kontext wählen", + "ui.agent_chat_pick_context_tip": "Flächen, Kanten, Merkmale und Körper im Modell wählen, die der Agent ansehen soll, dann auf OK klicken", "ui.agent_chat_placeholder": "Bitten Sie den Agenten, das Design zu ändern…", "ui.agent_chat_placeholder_busy": "Nachricht einreihen, bis der Agent fertig ist (Strg+Eingabe: jetzt senden)", "ui.agent_chat_pop_out": "In eigenem Fenster öffnen, das Sie auf einen anderen Bildschirm verschieben können", "ui.agent_chat_previous_picture": "Vorheriges Bild", "ui.agent_chat_privacy": "Nichts geht irgendwohin außer an den Agenten, den Sie unter Ihrem eigenen Konto ausführen.", "ui.agent_chat_privacy_note": "Der Chat sendet von sich aus nichts irgendwohin: Der Agent, den Sie starten, spricht unter Ihrem eigenen Konto mit seinem eigenen Dienst. SolidCraft sieht und speichert nie einen Schlüssel oder ein Passwort.", + "ui.agent_chat_provider_models": "{count} Modelle", + "ui.agent_chat_provider_other": "Sonstiges", + "ui.agent_chat_provider_tip": "Der Anbieter, dessen Modelle die nächste Liste zeigt.", "ui.agent_chat_queue": "Einreihen", "ui.agent_chat_queue_full": "Zu viele Nachrichten warten: Entfernen Sie eine oder warten Sie auf den Agenten.", "ui.agent_chat_queued": "Eingereiht", "ui.agent_chat_queued_stopped": "Eingereiht (gestoppt, nicht gesendet)", "ui.agent_chat_refresh": "Aktualisieren", "ui.agent_chat_refused": "Für den Agenten nicht erlaubt: {reason}", + "ui.agent_chat_reinstall": "{agent} ist installiert ({program}), ist aber beim Prüfen durch SolidCraft nicht gestartet: {error}\nDie Installation ist vielleicht unvollständig oder für einen anderen Computertyp. Installieren Sie es erneut mit `{install}`, prüfen Sie, dass es im Terminal seine Version ausgibt, und klicken Sie dann auf Aktualisieren.", "ui.agent_chat_remove": "Aus der Warteschlange entfernen", "ui.agent_chat_remove_file": "Von dieser Nachricht entfernen", "ui.agent_chat_remove_imported": "Von dieser Nachricht entfernen; das Teil bleibt im Design (Rückgängig entfernt es)", + "ui.agent_chat_reply_cut_off": "Die Antwort hat ihre Längengrenze erreicht, bevor sie fertig war, und ist daher vielleicht unvollständig. Bitten Sie den Agenten weiterzumachen oder kürzer zu antworten.", + "ui.agent_chat_reply_declined": "Das Modell hat abgelehnt, auf diese Nachricht zu antworten.", + "ui.agent_chat_retry": "Erneut versuchen", "ui.agent_chat_right": "Rechts", "ui.agent_chat_save": "Speichern", "ui.agent_chat_send": "Senden", @@ -3177,11 +4511,12 @@ "ui.agent_chat_send_now_tip": "Den aktuellen Schritt des Agenten stoppen und dies als Nächstes senden (Strg+Eingabe)", "ui.agent_chat_setup_body": "SolidCraft kommuniziert mit einem auf diesem Computer installierten Programmieragenten. Wählen Sie einen unter Einstellungen › KI aus.", "ui.agent_chat_setup_title": "Assistenten einrichten", - "ui.agent_chat_side": "Seite des Agenten-Chats", + "ui.agent_chat_side": "Chat andocken", "ui.agent_chat_signed_in": "angemeldet", "ui.agent_chat_state_auth": "Anmeldung nötig", "ui.agent_chat_state_busy": "Arbeitet…", "ui.agent_chat_state_exited": "Agent beendet", + "ui.agent_chat_state_failed": "Verbindung fehlgeschlagen", "ui.agent_chat_state_off": "Nicht verbunden", "ui.agent_chat_state_ready": "Bereit", "ui.agent_chat_state_starting": "Startet…", @@ -3189,18 +4524,23 @@ "ui.agent_chat_stop_tip": "Den Agenten und alles, was er gestartet hat, beenden", "ui.agent_chat_stop_turn_tip": "Agenten stoppen (Esc). Eingereihte Nachrichten bleiben eingereiht.", "ui.agent_chat_turn_limit": "Änderungen pro Nachricht", + "ui.agent_chat_turn_unlimited": "Unbegrenzt", "ui.agent_chat_undo_changes": "Diese Änderungen rückgängig machen", "ui.agent_chat_undo_label": "Agenten-Chat: {message}", "ui.agent_chat_undone": "(rückgängig gemacht)", "ui.agent_chat_view_attached": "Ansicht angehängt", "ui.agent_chat_waiting": "Wartet auf Sie", - "ui.agent_cursor": "Agent-Cursor", + "ui.agent_cursor": "Agentenzeiger", "ui.agent_cursor_speed": "Agent-Cursor-Geschwindigkeit", + "ui.agent_off_thread": "Fenster bedienbar halten, während Agenten Befehle ausführen", + "ui.agent_off_thread_note": "Langsame Befehle eines Agenten (aus dem Assistentenbereich oder von einem MCP-Client) werden neben dem Fenster berechnet: Sie können die Ansicht weiter drehen und prüfen und einen Befehl über den Chip in der Ansicht stoppen. Aus: Jeder läuft im Thread des Fensters, und das Fenster wartet darauf.", "ui.ai_add": "Hinzufügen", "ui.ai_add_agent": "Agent hinzufügen…", "ui.ai_add_agent_title": "Agent hinzufügen", + "ui.ai_add_anthropic": "Anthropic-kompatible API", "ui.ai_add_api": "OpenAI-kompatible API", "ui.ai_add_custom": "Eigener Befehl", + "ui.ai_add_endpoint": "API-Endpunkt", "ui.ai_add_installed": "Installierter Agent", "ui.ai_add_installed_note": "Ein eigener Eintrag für einen installierten Agenten, zum Beispiel mit anderen Argumenten. Installierte Agenten erscheinen von selbst.", "ui.ai_added": "hinzugefügt", @@ -3221,23 +4561,29 @@ "ui.ai_copy_suffix": "Kopie", "ui.ai_custom_url": "Eigene URL", "ui.ai_default": "Standard", + "ui.ai_edit": "Bearbeiten", + "ui.ai_edit_agent_title": "Agent bearbeiten", + "ui.ai_edit_gone": "Dieser Agent wurde entfernt, es gibt also nichts zu speichern.", + "ui.ai_edit_tip": "Name, Befehl oder Endpunkt dieses Agenten ändern. Ein gespeicherter Schlüssel bleibt verborgen.", "ui.ai_http_busy": "der Endpunkt ist ausgelastet oder am Limit; versuchen Sie es später", "ui.ai_http_key": "der Endpunkt hat den Schlüssel abgelehnt: prüfen Sie ihn unter Einstellungen > KI", "ui.ai_http_not_found": "Endpunkt oder Modell nicht gefunden: prüfen Sie Basis-URL und Modellnamen", "ui.ai_http_too_large": "die Unterhaltung ist für diesen Endpunkt zu groß; beginnen Sie einen neuen Chat", "ui.ai_key": "API-Schlüssel", "ui.ai_key_hint": "optional; im Schlüsselbund des Systems gespeichert", + "ui.ai_key_keep_hint": "leer lassen, um den gespeicherten Schlüssel zu behalten", "ui.ai_key_needs_https": "Ein Schlüssel wird nur über HTTPS oder an diesen Computer gesendet.", "ui.ai_key_note": "Im Schlüsselbund des Systems gespeichert, nie in den Einstellungen von SolidCraft. Für einen lokalen Server leer lassen.", "ui.ai_keychain_error": "Der Schlüsselbund des Systems hat abgelehnt: {error}", - "ui.ai_mode_all": "Alles erlauben", + "ui.ai_kind": "Art", + "ui.ai_mode_all": "Alles ausführen", "ui.ai_mode_all_note": "Nichts fragt vorher. Absturzberichte bleiben tabu, und die Ordnergrenzen gelten weiter.", "ui.ai_mode_all_warning": "Der Agent kann Ihr Design ohne Nachfrage speichern, überschreiben, exportieren und ersetzen. Nutzen Sie das nur mit einem Agenten, dem Sie vertrauen, und mit gespeicherten Designs.", - "ui.ai_mode_ask": "Jedes Mal fragen", + "ui.ai_mode_ask": "Zuerst fragen", "ui.ai_mode_ask_note": "Jede Änderung am Design und jede Dateiaktion wartet auf Ihr Erlauben.", - "ui.ai_mode_edits": "Modelländerungen automatisch erlauben", + "ui.ai_mode_edits": "Änderungen vornehmen", "ui.ai_mode_edits_note": "Modellierbefehle laufen ohne Nachfrage; Speichern, Öffnen, Exportieren und andere Datei- oder destruktive Aktionen fragen weiterhin.", - "ui.ai_mode_global": "Wie oben eingestellt", + "ui.ai_mode_global": "Wie oben", "ui.ai_model": "Modell", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "Diese Einstellungen gelten für die Werkzeuge von SolidCraft. Die eigenen Werkzeuge eines Agenten (seine Shell, seine Dateiänderungen) folgen seinem eigenen Modus, den Sie im Kopf des Chat-Panels wählen, wenn der Agent Modi hat.", @@ -3251,25 +4597,53 @@ "ui.ai_panel": "Panel", "ui.ai_permissions": "Berechtigungen", "ui.ai_preset": "Vorlage", + "ui.ai_protocol": "Protokoll", + "ui.ai_reasoning_effort": "Denkaufwand", + "ui.ai_reasoning_effort_field_hint": "leer = Standard des Anbieters", + "ui.ai_reasoning_effort_hint": "Optional. Wird als `reasoning_effort` an den Endpunkt gesendet; die zulässigen Werte unterscheiden sich je nach Anbieter (zum Beispiel `low`, `high` oder `max`). Einen hier gesetzten Wert ersetzt SolidCraft nie. Leer lassen, um nichts zu senden und den Standard des Anbieters zu behalten.", "ui.ai_remove": "Entfernen", + "ui.ai_request_timed_out": "Das Modell hat länger als {seconds} s gebraucht. Sie können das Anfrage-Zeitlimit für diesen Endpunkt unter Einstellungen › Assistent erhöhen.", + "ui.ai_request_timeout": "Anfrage-Zeitlimit", + "ui.ai_request_timeout_hint": "Wie lange eine Modellanfrage an diesen Endpunkt dauern darf, von 30 s bis zu einer Stunde. Erhöhen Sie den Wert für ein langsames lokales Modell.", "ui.ai_reset": "Zurücksetzen", + "ui.ai_save": "Speichern", "ui.ai_settings": "KI-Einstellungen…", "ui.ai_show_features": "KI-Funktionen anzeigen", - "ui.ai_show_features_note": "Der Agenten-Chat: ein Panel, in dem ein Coding-Agent, den Sie schon nutzen, oder ein Modell-Endpunkt Ihrer Wahl am geöffneten Design arbeitet. Aus: keine KI-Schaltfläche, kein Kürzel, kein Menüeintrag, kein Panel, und nichts wird gesucht oder gestartet.", + "ui.ai_show_features_note": "Aus blendet den Assistenten überall aus und startet nichts. Alles darunter wird gedimmt.\n\nDer Agenten-Chat: ein Panel, in dem ein Coding-Agent, den Sie schon nutzen, oder ein Modell-Endpunkt Ihrer Wahl am geöffneten Design arbeitet. Aus: keine KI-Schaltfläche, kein Kürzel, kein Menüeintrag, kein Panel, und nichts wird gesucht oder gestartet.", "ui.ai_switch_tip": "Den Agenten für dieses Gespräch wechseln", "ui.ai_test": "Testen", "ui.ai_test_acp_ok": "Antwortet: {agent}", "ui.ai_test_acp_tip": "Startet den Agenten kurz und bittet um eine Sitzung; beendet ihn wieder", + "ui.ai_test_answered": "Erreicht: {model} hat geantwortet", + "ui.ai_test_anthropic_tip": "Sendet eine kurze Nachricht an den Endpunkt", "ui.ai_test_api_tip": "Fragt den Endpunkt nach seinen Modellen", "ui.ai_test_no_model": "Erreicht: {count} Modelle, aber nicht {model}", "ui.ai_test_ok": "Erreicht: {count} Modelle", "ui.ai_testing": "Teste…", + "ui.ai_tool_arguments": "Argumente", + "ui.ai_tool_details": "Details", "ui.ai_tool_done": "fertig", "ui.ai_tool_failed": "fehlgeschlagen", + "ui.ai_tool_result": "Ergebnis", "ui.ai_tool_running": "läuft", + "ui.ai_tool_sum_bodies_one": "{count} Körper", + "ui.ai_tool_sum_bodies_other": "{count} Körper", + "ui.ai_tool_sum_by": "um {value}", + "ui.ai_tool_sum_edges_one": "{count} Kante", + "ui.ai_tool_sum_edges_other": "{count} Kanten", + "ui.ai_tool_sum_faces_one": "{count} Fläche", + "ui.ai_tool_sum_faces_other": "{count} Flächen", + "ui.ai_tool_sum_features_one": "{count} Merkmal", + "ui.ai_tool_sum_features_other": "{count} Merkmale", + "ui.ai_tool_sum_measured": "Gemessen: {what}", + "ui.ai_tool_sum_more": "{steps} und {count} weitere", + "ui.ai_tool_sum_radius": "r {value}", + "ui.ai_tool_sum_saved": "{file} gespeichert", + "ui.ai_tool_sum_screenshot": "Screenshot", + "ui.ai_tool_sum_then": "{first}, dann {next}", "ui.ai_tool_unfold": "Klicken, um das Ergebnis zu zeigen", "ui.ai_tool_waiting": "wartet", - "ui.ai_toolbar_button": "Schaltfläche in der Werkzeugleiste anzeigen", + "ui.ai_toolbar_button": "Assistent-Schaltfläche in der Anwendungsleiste", "ui.ai_toolbar_button_note": "Die KI-Schaltfläche am rechten Ende der Werkzeugleiste. Strg+Umschalt+A und das Ansicht-Menü öffnen das Panel weiterhin.", "ui.ai_undo_tip": "Alles, was der Agent für diese Nachricht geändert hat, in einem Schritt rückgängig machen", "ui.ai_url_hint": "https://example.com/v1", @@ -3321,6 +4695,7 @@ "ui.circle": "Kreis", "ui.circular_pattern": "Radiales Muster", "ui.clear": "Leeren", + "ui.clear_print_face": "Auflagefläche entfernen", "ui.clear_recent": "Zuletzt verwendet leeren", "ui.clear_the_selection": "Auswahl aufheben", "ui.click_selects_whole_bodies": "Klick wählt ganze Körper aus", @@ -3345,10 +4720,16 @@ "ui.colour_vision_sample": "Beispiel", "ui.colour_vision_tritan": "Tritan", "ui.colour_vision_tritan_tip": "Bei schwachem oder fehlendem Blausinn", + "ui.comb_length": "Kammlänge", + "ui.comb_length_tip": "Wie lang die Zähne sind: ein Vielfaches der automatischen Länge, bei der der längste Zahn ein Fünftel der Größe der gezeigten Kurven ist.", + "ui.comb_teeth": "Zähne", + "ui.comb_teeth_tip": "Wie viele Zähne jeder Kamm hat, gleichmäßig entlang der Kurve verteilt. Mehr Zähne zeigen genauer, wie sich die Krümmung ändert.", "ui.combine": "Kombinieren", "ui.coming_later": "bald verfügbar", "ui.command_done": "{command} fertig", "ui.command_palette_hint": "Befehl eingeben, z. B. {example} — oder S drücken, um zu suchen", + "ui.components_from_bodies_hint": "Für jeden ausgewählten Körper eine gleichnamige Komponente unter der aktiven Komponente erstellen.", + "ui.components_from_bodies_required": "Mindestens einen Körper auswählen.", "ui.concentric": "Konzentrisch", "ui.cone": "Kegel", "ui.conic_curve": "Kegelschnitt", @@ -3361,17 +4742,34 @@ "ui.construction.contact_hint": "Tangente: Kreis/Bogen oder offenen Spline/Kegelschnitt wählen, dann Berührpunkt (Freiformkurven: Endpunkte)", "ui.construction.external_hint": "Tangente: Kreis oder Bogen, äußeren Punkt, dann gewünschte Lösung wählen", "ui.construction.free_hint": "Konstruktionslinie: zwei Punkte anklicken; Rechtsklick beginnt neu", + "ui.construction.normal_needs_length": "Eine unendliche Linie ist immer Konstruktion: Länge eingeben, um eine normale Linie zu zeichnen", "ui.construction.point_hint": "Konstruktionslinie: Durchgangspunkt anklicken", "ui.construction.reference_hint": "Konstruktionslinie: Gerade wählen, dann Punkt; Rechtsklick wechselt die Referenz", "ui.construction.ribbon_label": "Hilfslinien", + "ui.construction.side_hint": "Konstruktionslinie: die Seite anklicken, zu der die Linie läuft; Rechtsklick beginnt neu", "ui.context_menu": "Kontextmenü", + "ui.continuity_crease": "Knick", + "ui.continuity_curvature": "Krümmung", + "ui.continuity_curvature_change": "Krümmungsänderung", + "ui.continuity_curvature_change_tip": "Krümmungsänderung (G3): Auch die Krümmung ändert sich an der Naht glatt.", + "ui.continuity_curvature_tip": "Krümmungsstetig (G2): Spiegelungen laufen ohne Knick hindurch.", "ui.continuity_g0": "G0 Knick", "ui.continuity_g1": "G1 Tangente", "ui.continuity_g2": "G2 Krümmung", "ui.continuity_gap": "Lücke", + "ui.continuity_position": "Position", + "ui.continuity_position_tip": "Position (G0): Die Flächen treffen sich, mit einem Knick an der Naht.", + "ui.continuity_smooth_curvature_change": "Glatte Krümmungsänderung", + "ui.continuity_smooth_curvature_change_tip": "Glatte Krümmungsänderung (G4): Selbst die Art, wie sich die Krümmung ändert, läuft an der Naht glatt weiter.", + "ui.continuity_tangent": "Tangential", + "ui.continuity_tangent_tip": "Tangential (G1): kein Knick, aber die Krümmung springt an der Naht.", "ui.copy": "Kopieren", + "ui.copy_details": "Details kopieren", + "ui.copy_details_tip": "Die vollständige Meldung kopieren, um sie nachzuschlagen oder zu melden.", "ui.corner": "Ecke", "ui.corners": "Ecken", + "ui.cosmetic_thread_markings": "Kosmetische Gewindemarkierungen", + "ui.cosmetic_thread_markings_help": "Schematische Markierungen an zylindrischen Gewindewänden anzeigen. Ändert nur die Anzeige, nie das Design oder Exporte.", "ui.counterbore": "Tiefenbohrung", "ui.countersink": "Senkung", "ui.create": "Erstellen", @@ -3389,6 +4787,8 @@ "ui.dark": "Dunkel", "ui.default_modelling_orientation": "Standard-Modellierungsorientierung", "ui.delete": "Löschen", + "ui.delete_select_first": "Wählen Sie zuerst aus, was gelöscht werden soll: Features, Körper, Komponenten oder Skizzengeometrie", + "ui.dependents_select_first": "Wählen Sie zuerst aus, wessen Abhängige aufgelistet werden sollen", "ui.depth": "Tiefe", "ui.design": "Design", "ui.design_properties.author": "Autor", @@ -3403,6 +4803,40 @@ "ui.design_properties.project": "Projekt", "ui.design_properties.revision": "Revision", "ui.design_saved": "Gespeichert unter {path}", + "ui.details_access_caption": "Flächen zeigen, ob ein Werkzeug sie aus der gewählten Richtung erreichen kann.", + "ui.details_angle": "Winkel", + "ui.details_continuity_caption": "Ausgewählte Naht bearbeiten. Andere Nähte behalten ihre eigenen Einstellungen.", + "ui.details_continuity_stale": "Frühere Geometrie: Analyse erneut ausführen, um diese Naht zu bearbeiten oder in die Ansicht einzupassen.", + "ui.details_copy_list": "Liste kopieren", + "ui.details_curvature": "Krümmungstoleranz", + "ui.details_curvature_caption": "Flächen werden anhand ihres lokalen Krümmungsradius eingefärbt.", + "ui.details_direction": "Werkzeugrichtung", + "ui.details_draft_caption": "Flächen werden anhand ihres Winkels zur Entformungsrichtung eingefärbt.", + "ui.details_edit_seam": "Naht bearbeiten", + "ui.details_fixture": "UI-Bausteinbeispiel — nur Beispieldaten", + "ui.details_fixture_caption": "UI-Bausteinbeispiel mit veranschaulichenden Werten; dies ist kein Modellergebnis.", + "ui.details_fixture_problem": "Beispielbefund mit einem Problem", + "ui.details_fixture_readout": "Beispielmesswert", + "ui.details_flip": "Umkehren", + "ui.details_gap": "Spalt", + "ui.details_hatch": "Schnittflächen schraffieren", + "ui.details_jump": "Krümmungssprung", + "ui.details_key": "Legende", + "ui.details_offset": "Versatz", + "ui.details_plane": "Ebene", + "ui.details_pull": "Entformungsrichtung", + "ui.details_radius": "Radius", + "ui.details_readout": "Messwerte", + "ui.details_samples": "Abtastpunkte", + "ui.details_seam": "{body} · Kante {edge}", + "ui.details_settings": "Einstellungen", + "ui.details_sharp_gap": "Scharfe Kante oder Spalt", + "ui.details_show_all": "Alle {count} anzeigen", + "ui.details_smooth": "Glatt", + "ui.details_stripes": "Streifen", + "ui.details_target": "Geometrie in Ansicht einpassen", + "ui.details_worst_seams": "Schlechteste Nähte", + "ui.details_zebra_caption": "Reflektierte Streifen zeigen, wie glatt die Flächen ineinander übergehen.", "ui.diameter": "Durchmesser", "ui.dimension": "Maß", "ui.direct_interaction": "Direkte Bearbeitung", @@ -3447,8 +4881,10 @@ "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", "ui.edit_in_place_wait": "Warten, bis abgeschlossen ist, was im Design läuft", "ui.edit_section_analysis": "Querschnittsanalyse bearbeiten", + "ui.edit_sketch_empty": "Keine Skizzen zum Bearbeiten", "ui.ellipse": "Ellipse", "ui.emboss_wrap_note": "Senkrechte Linienprofile, die einen unterstützten Zylinder berühren, werden automatisch aufgewickelt. Eine Wand auswählen, um ein Ziel festzulegen.", + "ui.end": "Ende", "ui.end_radius": "Endradius", "ui.end_scale": "Endskalierung", "ui.entities": "Elemente", @@ -3457,12 +4893,15 @@ "ui.equation_explicit": "Explizit", "ui.equation_form": "Form", "ui.equation_note": "Die Variable ist eine Zahl ohne Einheit: sin(t) liest sie im Bogenmaß. Ein Ergebnis ohne Einheit ist in der Einheit der Konstruktion.", + "ui.equation_note_range": "Die Variable ist eine Länge, wie ihr Bereich: Sie lässt sich mit Längenparametern kombinieren; für sin() durch eine Länge teilen. Ein Ergebnis ohne Einheit gilt in der Einheit der Konstruktion.", "ui.equation_parametric": "Parametrisch", + "ui.equation_variable_unit": "Variable hat die Einheit des Bereichs", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Äquivalenter Radius", "ui.expand": "Aufklappen", + "ui.explode_needs_two_components": "Die Explosionsdarstellung zieht Komponenten auseinander, daher braucht die Konstruktion mindestens zwei davon (Neue Komponente, Konstruktion einfügen oder Komponenten aus Körpern erstellen)", "ui.exportDxf": "Als DXF exportieren…", "ui.export_ellipsis_keymap": "Exportieren…", "ui.export_keymap_tip": "Tasten, S-Box-Favoriten und die Symbolleiste als Datei", @@ -3472,12 +4911,46 @@ "ui.extract_design_changed": "Das Design hat sich beim Wählen einer Datei geändert. Starten Sie In Datei extrahieren erneut.", "ui.extract_done": "Die Komponente ist jetzt ein eigenes Design und hier verknüpft.", "ui.extrude": "Extrudieren", + "ui.extrude_auto_to_object": "Bis zu einem gewählten Ziel extrudieren", + "ui.extrude_auto_to_object_tip": "Eine Fläche, ein Scheitelpunkt oder eine parallele Ebene stellt die Ausdehnung auf Bis Objekt um.", "ui.factor": "Faktor", + "ui.fade": "Auslauf", + "ui.fade_length": "Auslauflänge", "ui.feature_history": "Feature-Verlauf", "ui.feature_options": "Funktionsoptionen", "ui.features": "Funktionen", "ui.file": "Datei", "ui.fillet": "Vollrundung", + "ui.fillet_corner_ball": "Kugel", + "ui.fillet_corner_ball_tip": "Ein Stück der Kugel des rollenden Balls, tangential (G1) zu jeder Rundung.", + "ui.fillet_corner_curvature_tip": "Krümmung (G2): ein glattes Flächenstück. Die Ecke wird entlang jeder Kante um den Rücksprung zurückgesetzt ({factor} × der Radius, sofern Sie keinen eingeben) und mit einem Flächenstück gefüllt, sodass Spiegelungen ohne Knick hindurchlaufen.", + "ui.fillet_corner_needs_constant": "Ecken mit glattem Flächenstück (G2) brauchen einen konstanten Radius und exakte Radiusanpassung.", + "ui.fillet_corner_patch": "Glattes Flächenstück", + "ui.fillet_corner_patch_tip": "Krümmungsstetig (G2): Die Ecke wird entlang jeder Kante zurückgesetzt und mit einem Flächenstück gefüllt, sodass Spiegelungen ohne Knick hindurchlaufen.", + "ui.fillet_corner_tangent_tip": "Tangential (G1): eine Kugelecke, ein Stück der Kugel des rollenden Balls, tangential zu jeder Rundung.", + "ui.fillet_error_corner": "Die glatte Ecke ließ sich hier nicht bauen. Versuchen Sie einen anderen Rücksprung oder tangentiale Ecken.", + "ui.fillet_error_failed": "Diese Rundung ließ sich an diesen Kanten nicht bauen. Versuchen Sie einen anderen Radius oder runden Sie weniger Kanten auf einmal.", + "ui.fillet_error_setback_short": "Der Rücksprung ist für das Eckstück zu kurz: Es lässt sich ab {least} bauen. Versuchen Sie einen längeren Rücksprung.", + "ui.fillet_error_too_large": "Der Radius ist zu groß für die Flächen neben diesen Kanten. Versuchen Sie einen kleineren Radius oder stellen Sie „Flächengrenzen“ auf „Größter Radius“.", + "ui.fillet_fit": "Flächengrenzen", + "ui.fillet_fit_exact": "Exakter Radius", + "ui.fillet_fit_needs_constant": "Radiusanpassung braucht einen konstanten Radius.", + "ui.fillet_fit_reduce": "Größter Radius", + "ui.fillet_fit_taper": "Verjüngter Radius", + "ui.fillet_fit_tip": "Wenn der Radius größer ist, als die Flächen neben einer Kante zulassen.\nExakter Radius: der angegebene Radius, oder keine Rundung und eine Meldung mit dem Grund.\nGrößter Radius: jede Kante mit dem größten passenden Radius gerundet.\nVerjüngter Radius: der Radius bleibt, die Rundung wird nur dort verjüngt, wo die Flächen enden.", + "ui.fillet_options_tip": "Tangentenkette: auch die Kanten runden, die glatt an die gewählten anschließen.\nVorschau: das Ergebnis beim Bearbeiten in der Ansicht zeigen.", + "ui.fillet_setback": "Rücksprung", + "ui.fillet_setback_hint": "{factor} × Radius", + "ui.fillet_setback_least": "Mehr als {least}", + "ui.fillet_setback_tip": "Wo das glatte Eckflächenstück beginnt: wie weit von der Ecke entlang jeder Kante. Standard ist {factor} × der Radius. Er muss größer sein als der kleinste Rücksprung, wo sich die Rundungen ohne ihn treffen: der Radius, wo die Flächen rechtwinklig zueinander stehen.", + "ui.fillet_smooth_radius": "Radius glatt ändern", + "ui.fillet_turn": "Wendungen", + "ui.fillet_turn_mitre": "Gehrung", + "ui.fillet_turn_swept": "Geschwenkt", + "ui.fillet_turn_tip": "Wo zwei Rundungen um eine scharfe Eckkante zwischen ihnen herumlaufen, etwa die Rundungen am Fuß eines Zapfens an seinen senkrechten Kanten.\nGehrung: Die Rundungen laufen weiter, bis sie sich in einer Gehrung treffen.\nGeschwenkt: Die Rundungen enden an der Eckkante und schwenken um sie herum; die Ecke ist ein Torus, tangential zu beiden. Nur für Rundungen mit einem Radius um eine gerade, konvexe Eckkante.", + "ui.fillet_type_choices_tip": "Konstanter Radius: ein Radius entlang der ganzen Kante.\nSehnenlänge: die Breite der Rundung bleibt gleich, in welchem Winkel die Flächen auch aufeinandertreffen.\nVariabler Radius: ein Radius an jedem Ende und weitere entlang der Kante, wenn Sie sie hinzufügen.\nKrümmungsstetig: ein Querschnitt ohne Knick in den Spiegelungen, wo er auf ebene Flächen trifft (G2).\nSpline: der Radius entlang der Kante folgt Steuerradien, die Sie festlegen.", + "ui.fillet_type_curvature": "Krümmungsstetig", + "ui.fillet_type_tip": "Der Querschnitt über die Kante. Krümmungsstetig: ein krümmungsstetiger Querschnitt (G2) zwischen ebenen Flächen, sodass Spiegelungen ohne Knick von den Flächen in die Rundung laufen.", "ui.filter_commands_or_keys": "Befehle oder Tasten filtern", "ui.findInTimeline": "In der Zeitleiste suchen", "ui.findInWindow": "Im Fenster suchen", @@ -3491,6 +4964,7 @@ "ui.flip": "Umkehren", "ui.format": "Format", "ui.frame_rate": "Bildrate", + "ui.frame_rate_details": "Bildratendetails", "ui.front": "Vorne", "ui.fully_constrained": "Vollständig bestimmt", "ui.function": "Funktion", @@ -3586,21 +5060,33 @@ "ui.hideOrigin": "Ursprung ausblenden", "ui.hidePlanes": "Ebenen ausblenden", "ui.hideProfile": "Profil ausblenden", + "ui.hide_origin_by_default": "Ursprungsordner in neuen Konstruktionen ausblenden", + "ui.hide_origin_note": "Neue Designs beginnen mit ausgeblendetem Ordner „Ursprung“. Ein Design behält seine eigene Ursprungseinstellung, sobald Sie ihn ein- oder ausblenden.", "ui.history_back": "Einen Schritt zurück", "ui.history_below_browser": "Unter dem Browser", + "ui.history_edge_hint": "Kante doppelklicken", "ui.history_first": "Zum Anfang", "ui.history_forward": "Einen Schritt vor", + "ui.history_hide_names": "Namen ausblenden", "ui.history_last": "Zum Ende", + "ui.history_marker_tip": "Verlaufsmarkierung: Ziehen setzt das Modell zurück; neue Merkmale kommen hierhin", + "ui.history_names": "Namen", + "ui.history_play": "Bis zum Ende abspielen", "ui.history_play_button_hide": "Wiedergabe-Schaltfläche ausblenden", "ui.history_play_button_show": "Wiedergabe-Schaltfläche einblenden", "ui.history_play_finish_action": "Die aktuelle Aktion abschließen, bevor der Verlauf abgespielt wird", "ui.history_play_roll_back": "Die Verlaufsmarkierung vor dem Abspielen zurücksetzen", + "ui.history_show_names": "Namen anzeigen", + "ui.history_sketch_listed_under": "Aufgeführt unter {feature}", "ui.history_title": "Verlauf", + "ui.history_toggle_names": "Merkmalsnamen ein- oder ausblenden", + "ui.history_waits_for_editor": "Rückgängig, Wiederholen und Verlauf warten, bis der Feature-Editor geöffnet ist", "ui.hole": "Bohrung", "ui.hole_tap_type": "Gewindetyp", "ui.hole_type": "Bohrungstyp", "ui.home": "Start", "ui.homeView": "Startansicht", + "ui.horizontal_constraint": "Horizontale Bedingung", "ui.horizontal_vertical": "Horizontal/Vertikal", "ui.import_ellipsis": "Importieren…", "ui.infinite": "Unendlich", @@ -3610,6 +5096,7 @@ "ui.insert_design.saved_file": "{name} hat ungespeicherte Änderungen, daher wurde die gespeicherte Datei eingefügt. Speichern Sie sie und wählen Sie dann Verknüpfungen aktualisieren, um die Änderungen zu übernehmen.", "ui.insert_design.unsaved": "Ungespeicherte Änderungen", "ui.inspect": "Prüfen", + "ui.instances": "Instanzen", "ui.intersect": "Schnitt", "ui.isolate": "Isolieren", "ui.join": "Verbinden", @@ -3618,12 +5105,14 @@ "ui.joints": "Gelenke", "ui.keyboard_shortcuts": "Tastenkürzel", "ui.language": "Sprache", + "ui.lasso_select": "Lasso (freihändig umfahren: wählt, was ganz innen liegt)", "ui.layout_compact": "Kompakt", "ui.layout_floating": "Schwebend", "ui.length": "Länge", "ui.length_decimals": "Längen-Dezimalstellen", "ui.light": "Hell", "ui.line": "Linie", + "ui.line_arc_hint": "Tangentialbogen: Ende des Bogens anklicken. Für Linien erneut auf dem letzten Punkt verweilen; Rechtsklick oder Esc beendet", "ui.link_copies": "Identische Kopien verknüpfen", "ui.link_copies_keep": "Behalten", "ui.link_copies_link": "Verknüpfen", @@ -3669,6 +5158,11 @@ "ui.move": "Verschieben", "ui.multiple": "Mehrfach", "ui.named_views": "Benannte Ansichten", + "ui.nav_bridge": "Mit einer Geräte-App auf diesem Computer navigieren", + "ui.nav_bridge_connected": "Verbunden", + "ui.nav_bridge_port": "Port", + "ui.nav_bridge_tip": "Das eigene Programm eines 3D-Eingabegeräts (zum Beispiel der Treiber einer selbstgebauten 3D-Maus) bewegt die Ansicht über eine lokale Verbindung, sodass der Mauszeiger Ihnen bleibt. SolidCraft verbindet sich nur auf diesem Computer über diesen Port damit.", + "ui.nav_bridge_waiting": "Warten auf die Geräte-App", "ui.navigation": "Navigation", "ui.needs_design": "{command}: Öffnen Sie zuerst ein Design", "ui.newSketchGroup": "Neue Skizzengruppe", @@ -3706,8 +5200,15 @@ "ui.part_size_needs_a_part": "Wählen Sie ein eingefügtes Standardbauteil (Schraube, Mutter, Scheibe oder Stift) aus, um seine Größe zu ändern. Einen Körper vergrößern oder verkleinern Sie mit Skalieren.", "ui.part_size_shared": "Baut das Teil neu auf und ersetzt alle hinzugefügten Merkmale. Alle Vorkommen dieser Komponente werden aktualisiert.", "ui.paste": "Einfügen", + "ui.patch_continuity_corner_tip": "Der Patch schließt entlang jeder Seite mit der gewählten Stetigkeit an die umgebenden Flächen an. An einer Ecke, an der diese Flächen mit unterschiedlicher Krümmung aufeinandertreffen, bleibt er dort tangential (G1).", "ui.path": "Pfad", + "ui.pattern_object_type_tip": "Körper: feste Formen, in der Ansicht oder im Browser gewählt; jeder wird ganz kopiert.\nFunktionen: Schritte im Verlauf, etwa eine Extrusion oder eine Bohrung, im Verlauf oder auf einer von ihnen erzeugten Fläche gewählt; der Schritt wird wiederholt.\nEine Skizze ist keines von beiden: Ihre Kurven mit Muster oder Spiegeln in der Skizze wiederholen oder sie zuerst extrudieren.", "ui.pattern_on_path": "Pfadmuster", + "ui.perforate_margin_default": "aus dem Durchmesser", + "ui.perforate_pitch": "Teilung", + "ui.perforate_square": "Quadrat", + "ui.perforate_staggered": "Versetzt (60°)", + "ui.perforate_title": "PERFORIEREN", "ui.perpendicular": "Senkrecht", "ui.perspective_view": "Perspektivische Ansicht", "ui.pinToShortcuts": "An Verknüpfungen anheften", @@ -3715,21 +5216,30 @@ "ui.pipe": "Rohr", "ui.pitch": "Steigung", "ui.placement": "Platzierung", + "ui.placement_handles": "Platzierungsgriffe", + "ui.placement_handles_tip": "Eine Markierung zum Verschieben des Features über das Modell und ein Ring zum Drehen.", "ui.plane": "Ebene", "ui.plane_at_angle": "Ebene im Winkel", "ui.plugins": "Plugins", "ui.plugins_desktop": "Plugins sind in der Desktop-App verfügbar.", "ui.plugins_empty": "Keine Plugins installiert.", + "ui.plugins_none": "Keine Plugins entsprechen dieser Suche.", "ui.plugins_note": "Jedes Plugin ist ein Ordner in {path} mit einer plugin.json. SolidCraft liest diese Datei und führt keinen Code aus dem Ordner aus. Das Ausschalten eines Plugins lässt es installiert.", + "ui.plugins_search": "Plugins suchen", "ui.plugins_skipped": "{count} Ordner konnte(n) nicht gelesen werden.", "ui.plugins_version": "{version}", "ui.point": "Punkt", + "ui.point_cloud_add_filter": "Filter hinzufügen…", "ui.point_cloud_auto_range": "Bereich automatisch", "ui.point_cloud_color_by": "Färben nach", "ui.point_cloud_file_colors": "Farben der Datei", + "ui.point_cloud_filter_by": "Filtern nach", "ui.point_cloud_height_high": "Oberste Höhe", "ui.point_cloud_height_low": "Unterste Höhe", + "ui.point_cloud_legend_filter": "In der Legende oben ein- und ausgeblendet", "ui.point_cloud_no_file_colors": "Die Datei hat keine Farben", + "ui.point_cloud_pause": "Pause", + "ui.point_cloud_play": "Abspielen", "ui.point_cloud_single_color": "Einheitliche Farbe", "ui.point_cloud_size": "Punktgröße", "ui.point_cloud_units": "Einheit der Datei", @@ -3738,6 +5248,11 @@ "ui.polygon": "Polygon", "ui.preferences": "Einstellungen", "ui.press_a_key": "Taste drücken…", + "ui.print_face_body_not_sent": "Der Körper dieser Fläche wird nicht gesendet: Füge ihn zuerst bei Körper hinzu", + "ui.print_face_cleared": "{body}: Auflagefläche entfernt", + "ui.print_face_input": "Auflagefläche", + "ui.print_face_pick": "Eine plane Fläche eines Volumenkörpers auswählen, um sie zur Auflagefläche zu machen", + "ui.print_face_set": "{body}: Auflagefläche gesetzt; An Slicer senden legt den Körper darauf", "ui.profile": "Profil", "ui.profile_plane": "Profilebene", "ui.profiles": "Profile", @@ -3754,6 +5269,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Wird gemessen…", + "ui.properties.measuring_bodies": "Wird gemessen… {done} von {total} Körpern", "ui.properties.measuring_failed": "Die Messung wurde vor dem Ende abgebrochen.", "ui.properties.principal_axis": "Hauptachse {number}", "ui.properties.principal_moments": "Hauptträgheitsmomente", @@ -3770,6 +5286,9 @@ "ui.rectangle": "Rechteck", "ui.rectangular_pattern": "Rechteckmuster", "ui.redo": "Wiederholen", + "ui.reference_1": "Referenz 1", + "ui.reference_2": "Referenz 2", + "ui.reference_distance": "Referenzabstand", "ui.relink_design_changed": "Die Baugruppe hat sich beim Wählen einer Quelle geändert. Starten Sie Quelle neu verknüpfen erneut.", "ui.relink_done": "Quelle für alle Instanzen neu verknüpft.", "ui.relink_not_linked": "Diese Komponente ist nicht mit einem Quelldesign verknüpft.", @@ -3805,6 +5324,7 @@ "ui.right": "Rechts", "ui.save": "Speichern", "ui.save_as": "Speichern unter", + "ui.save_mesh_no_slicer_open": "Kein Slicer gefunden: Wählen Sie „Benutzerdefiniert…“ und wählen Sie Ihr Slicer-Programm", "ui.save_mesh_pick_bodies": "Wähle die Körper zum Speichern aus", "ui.saved_to": "Gespeichert: {path}", "ui.sbox_pin": "Oben im S-Feld anheften", @@ -3817,12 +5337,15 @@ "ui.selectOther": "Andere auswählen…", "ui.selectTangentChain": "Tangentialkette auswählen", "ui.select_all": "Alles auswählen", + "ui.select_components_by_face": "Komponenten auswählen (eine Fläche wählt ihre Komponente)", "ui.selection": "Auswahl", "ui.selection_modifiers": "Auswahlmodifikatoren", "ui.selection_shift_add_only": "Umschalt+Klick fügt hinzu, ohne zu entfernen", "ui.selection_shift_add_only_tip": "An: Umschalt fügt Elemente hinzu, Strg/Cmd schaltet um. Aus (Standard): Umschalt und Strg/Cmd schalten beide um.", "ui.send": "Senden", + "ui.send_to_slicer_unavailable": "„An Slicer senden“ benötigt die Desktop-App: Ein Browser kann kein Programm starten", "ui.sent_to_slicer": "An {slicer} gesendet", + "ui.sent_to_slicer_copy": "An {slicer} als {file} gesendet, weil die erste Datei dort noch geöffnet ist", "ui.sheet_gap": "Spalt", "ui.shell": "Hülle", "ui.shortcut_capture_add_key": "Eine normale Taste hinzufügen. Escape bricht ab.", @@ -3830,6 +5353,8 @@ "ui.shortcut_capture_press": "Modifikatortasten und eine Taste drücken. Escape bricht ab.", "ui.shortcut_capture_release": "Zum Bestätigen alle Tasten loslassen. Escape bricht ab.", "ui.shortcut_capture_settling": "Tastenkürzel wird bestätigt… Escape bricht ab.", + "ui.shortcut_cycles_modes": "Erneutes Drücken des Tastenkürzels eines Werkzeugs wechselt dessen Modus", + "ui.shortcut_cycles_modes_tip": "Vor dem ersten Punkt schaltet erneutes Drücken des Tastenkürzels eines Skizzenwerkzeugs durch dessen Erstellungsmodi. Aus: Es startet das Werkzeug erneut.", "ui.shortcut_multiple_keys": "Modifikatortasten und nur eine weitere Taste verwenden. Zum Wiederholen die Belegung anklicken.", "ui.show": "Einblenden", "ui.showAll": "Alle einblenden", @@ -3854,11 +5379,25 @@ "ui.sketch_intersect_selection_filter": "Auswahlfilter", "ui.sketch_modifiers": "Skizzenmodifikatoren", "ui.sketch_project_geometry": "Geometrie", + "ui.sketch_report.all_constrained": "Alles ist vollständig bestimmt.", + "ui.sketch_report.dof": "Freiheitsgrade", + "ui.sketch_report.loose": "Nicht vollständig bestimmt", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Skizzenbericht", "ui.sketch_scale": "Skizzenskalierung", "ui.sketches": "Skizzen", "ui.slice": "Scheibe", "ui.slicer": "Slicer", "ui.slicer_delete_tip": "{program}\nMit Entf aus der Liste entfernen", + "ui.slicer_lost": "{slicer} wurde gestartet, kann aber nicht mehr gefunden werden, um ihm die Datei zu senden. Die Datei ist unter {path} gespeichert: Öffnen Sie sie von dort.", + "ui.slicer_no_file": "{slicer} ist bereit, aber es gibt keine Datei, die gesendet werden könnte.", + "ui.slicer_no_response": "{slicer} hat nicht rechtzeitig geantwortet. Die Datei ist bereits unter {path} gespeichert: Senden Sie sie erneut, sobald der Slicer gestartet ist.", + "ui.slicer_resend_hint": "Erneutes Senden ersetzt die Datei, die der Slicer geöffnet hat.", + "ui.slicer_single_instance": "Dateien in einem bereits laufenden Slicer öffnen", + "ui.slicer_single_instance_tip": "Für Slicer, die Dateien in ein laufendes Fenster laden.", + "ui.slicer_starting": "{slicer} wird gestartet…", + "ui.slicer_still_starting": "Es wird weiter darauf gewartet, dass {slicer} startet. Sonst wurde nichts gesendet.", + "ui.slicer_stl_fallback": "Das 3MF konnte nicht geschrieben werden, daher ist dies ein STL.", "ui.slot": "Langloch", "ui.smooth": "Glatt", "ui.smooth_wheel_zoom": "Sanftes Zoomen mit dem Rad", @@ -3874,6 +5413,8 @@ "ui.start": "Start", "ui.start_over": "Von vorn beginnen", "ui.start_page": "Startseite", + "ui.step_values": "Werte mit Pfeilen und Mausrad ändern", + "ui.step_values_tip": "Pfeil auf/ab und das Mausrad über einem Wertefeld ändern dessen Zahl.", "ui.stitch_tolerance_hint": "eng", "ui.stretch": "Strecken", "ui.supersampling": "Supersampling (SSAA)", @@ -3918,6 +5459,7 @@ "ui.total_angle": "Gesamtwinkel", "ui.trackpad_pan_tip": "Scrollen mit zwei Fingern verschiebt die Ansicht; bei Fusion dreht Umschalt + zwei Finger die Ansicht. Aus: Scrollen zoomt. Mausrad und Pinch-Geste zoomen; das Daumenrad verschiebt seitlich.", "ui.trim": "Kürzen", + "ui.turn_up_axis": "Achse nach oben drehen", "ui.twist": "Verdrehung", "ui.two_finger_scroll_pans": "Zwei-Finger-Scrollen schwenkt", "ui.two_sides": "Beidseitig", @@ -3934,22 +5476,35 @@ "ui.up_axis_note": "Welche Achse in den Ansichten nach oben zeigt (Achsenansicht, Home, Ansehen). Designs bleiben unverändert.", "ui.updateToCurrentView": "Auf aktuelle Ansicht aktualisieren", "ui.upload": "Hochladen", + "ui.vertical_constraint": "Vertikale Bedingung", "ui.view_angles": "Ansichtswinkel", "ui.view_angles_convention": "Grad um die Hochachse. Gieren 0° ist die Vorderansicht, 90° links, −90° rechts, 180° die Rückansicht; Nicken 90° ist die Draufsicht; ein positives Rollen dreht das Modell im Uhrzeigersinn.", "ui.view_angles_help": "Zeigt Nick-, Gier- und Rollwinkel der Ansicht in Grad sowie die Projektion unter dem Orientierungs-Gizmo. Klicken Sie auf die Anzeige, um genaue Winkel einzugeben.", + "ui.view_angles_lock": "{axis} sperren", "ui.view_angles_ortho": "Ortho", "ui.view_angles_persp": "Persp", "ui.view_angles_pitch": "Nicken", "ui.view_angles_readout": "Nicken {pitch} · Gieren {yaw} · Rollen {roll}", "ui.view_angles_roll": "Rollen", + "ui.view_angles_unlock": "{axis} entsperren", "ui.view_angles_yaw": "Gieren", + "ui.view_angles_zero": "{axis} auf 0° setzen", "ui.view_centre": "Ansichtszentrum", "ui.viewport_status_clear": "{name} ausschalten", "ui.viewport_status_clear_hint": "{name} ausschalten · Esc", + "ui.viewport_status_edges": "{count} Kanten", + "ui.viewport_status_from": "aus {direction}", "ui.viewport_status_key": "Legende für {name} anzeigen", "ui.viewport_status_minimum_radius": "Mindestradius", "ui.viewport_status_pairs": "{count} Paare", + "ui.viewport_status_section_hatch": "{setting} · Schraffur", + "ui.viewport_status_section_plane": "Aktuelle Ebene", + "ui.viewport_status_section_tilted": "geneigt · {offset}", "ui.viewport_status_stripes": "{count} Streifen", + "ui.viewport_status_summary_clear": "Alles ausschalten", + "ui.viewport_status_summary_heading": "In dieser Ansicht", + "ui.viewport_status_summary_label": "{name} und {count} weitere Elemente", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Dem Design folgen", "ui.visual_shaded_hidden_edges": "Schattiert mit verdeckten Kanten", "ui.visual_shaded_with_edges": "Schattiert mit Kanten", @@ -3957,6 +5512,10 @@ "ui.visual_wireframe": "Drahtmodell", "ui.wheel_zoom_speed": "Zoomgeschwindigkeit des Mausrads", "ui.width": "Breite", + "ui.window_system": "Fenstersystem", + "ui.window_system_auto": "Automatisch", + "ui.window_system_wayland": "Wayland", + "ui.window_system_x11": "X11", "ui.workspace": "Arbeitsbereich", "ui.workspace_animation_description": "Explosionsansichten, Bewegungsstudien und Storyboards", "ui.workspace_available": "Verfügbar", @@ -3981,11 +5540,13 @@ "update.available": "SolidCraft {version} ist verfügbar", "update.button": "Update", "update.button_version": "Auf {version} aktualisieren", - "update.check_automatically": "Automatisch nach Updates suchen", + "update.check_automatically": "Beim Start und einmal täglich prüfen", + "update.check_for_updates": "Nach Updates suchen", "update.check_now": "Jetzt suchen", + "update.check_unavailable": "Für diese Installation ist keine Update-Prüfung verfügbar.", "update.checking": "Suche läuft…", "update.copy": "Kopieren", - "update.dmg_opened": "Das Disk-Image ist geöffnet und geprüft: SolidCraft in „Programme“ ziehen, die alte Version ersetzen und SolidCraft neu starten.", + "update.dmg_opened": "Das Disk-Image ist geöffnet und geprüft: SolidCraft beenden, das neue SolidCraft in „Programme“ ziehen, die alte Version ersetzen und SolidCraft wieder öffnen.", "update.download": "Herunterladen", "update.download_open": "Herunterladen und öffnen", "update.downloading": "Herunterladen und prüfen… {done} von {total} MB", @@ -3996,11 +5557,13 @@ "update.installed": "SolidCraft {version} ist installiert. Zum Verwenden neu starten.", "update.installer_started": "Das Installationsprogramm startet, wenn SolidCraft geschlossen wird.", "update.later": "Später erinnern", + "update.managed": "Aktualisierung verfügbar: Aktualisieren Sie SolidCraft in {manager}", "update.no_notes": "Zu diesem Release gibt es keine Hinweise.", "update.package_hint": "Diese Installation stammt aus einem {kind}. Neues Paket herunterladen und installieren mit:", "update.prefs_dev": "Dies ist ein Entwicklungs-Build ({version}): er sucht nicht nach Updates.", "update.prefs_flatpak": "Flatpak aktualisiert diese Installation ({version}): {command} ausführen oder die Softwareverwaltung nutzen. SolidCraft sucht nicht selbst.", "update.prefs_label": "Updates", + "update.prefs_managed": "Dies ist SolidCraft {version}, verwaltet von {manager}. Die Prüfung fragt GitHub nach der neuesten Version und sendet nichts weiter; aktualisieren Sie SolidCraft in {manager}.", "update.prefs_note": "Dies ist SolidCraft {version} ({kind}). Die Suche fragt GitHub nach dem neuesten Release und sendet sonst nichts.", "update.prefs_web": "Laden Sie die Seite neu, um die neueste Web-App zu erhalten. Ist das Netzwerk nicht verfügbar oder kann das Update nicht rechtzeitig vollständig heruntergeladen werden, wird die gespeicherte Version geöffnet. Ein laufender Download wird für das nächste Neuladen fortgesetzt.", "update.refresh_checking": "Neueste Version wird gesucht…", @@ -4019,7 +5582,15 @@ "use a positive nominal diameter and a pitch smaller than it": "einen positiven Nenndurchmesser und eine kleinere Steigung verwenden", "values must be finite numbers": "Werte müssen endliche Zahlen sein", "values must be numbers or expressions": "Werte müssen Zahlen oder Ausdrücke sein", + "view.auto_ortho_faces": "Perspektivisch beim Drehen, orthografisch auf Flächen", "view.render_inspector": "Render-Inspektor", + "web.files.insert_drawings_hint": "CAD-Dateien, Netze, DXF oder SVG in das geöffnete Design", + "web.files.insert_stored_drawings_hint": "In das geöffnete Design (CAD-Dateien, Netze, DXF, SVG)", + "web.open_full": "In SolidCraft öffnen", + "web.open_link": "Verknüpftes Design öffnen?", + "web.open_link_confirm": "Es gibt nicht gespeicherte Änderungen. Das verknüpfte Design in einem neuen Tab öffnen?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ auswählen · Eingabe / Tab vervollständigen · Esc schließen", + "↑ ↓ choose · Enter applies this value": "↑ ↓ auswählen · Eingabe übernimmt diesen Wert", + "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ wählen · Enter wendet das Getippte an · Esc schließt", "⌘Enter continues on GitHub.": "⌘Enter geht weiter zu GitHub." } diff --git a/assets/locales/en-GB.json b/assets/locales/en-GB.json index 2d254b4de..109f2fa0b 100644 --- a/assets/locales/en-GB.json +++ b/assets/locales/en-GB.json @@ -16,7 +16,7 @@ "Mass Center": "Mass Centre", "Modeled": "Modelled", "Select the centre the pattern turns around first": "Select the centre the pattern turns around first", - "Snap to face and edge centres": "Snap to face and edge centres", + "Snap to face and edge centres": "Snap to centres", "Specialise": "Specialise", "cmd.appearance_favorite": "Favourite Look", "cmd.component_cycle_color": "Cycle Component Colour", @@ -47,7 +47,13 @@ "color.edit": "Click to edit colour", "color.gamma": "Showing colour values in 0-255 gamma space", "color.linear": "Showing colour values in 0-1 linear space", + "color.recent": "Recent colours", + "color.recent_help": "Colours you pick in any colour field appear here", + "color.saturation": "Saturation (per cent)", "color.selected": "Selected colour", + "color.step_down": "Step down", + "color.step_up": "Step up", + "color.value": "Value, the brightness (per cent)", "dxf.cancelled": "DXF export cancelled", "dxf.cancelling": "Cancelling DXF export", "help.apache": "Apache licence 2.0", @@ -63,19 +69,28 @@ "help.solid.split_face": "Divides the selected faces along a plane, the face of another body or sketch curves, without cutting the body. Use it to give part of a face its own draft, colour or offset.", "help.third_party": "Third-party licences", "home.new_mm_hint": "Millimetres · opens in Design", + "measure.line_to_centre": "Line to centre", + "navbar.custom.anchor.bottom_centre": "Bottom centre", + "navbar.custom.anchor.top_centre": "Top centre", "navbar.custom.customise": "Customise navigation bar…", "navbar.custom.position_centre": "Centre", "navbar.description.separator": "A thin line that groups neighbouring slots.", "pattern.alignment_hint": "Counts include the original. Centre balances copies; Flip chooses the extra side for even totals.", + "prefs.appearance.colour_vision_help": "Changes the colours that carry a meaning: sketch states, axes, bends, analyses and icons.", + "prefs.appearance.viewport_colours": "3D view colours", "prefs.bottom_centre": "Bottom centre", + "prefs.design_tools.hole_snaps_help": "The middle of a face and the centres of its round edges.", "prefs.logo_theme": "Theme's colours", "prefs.max_file_size": "Largest file to open", - "prefs.max_file_size_design": "Design files", "prefs.max_file_size_flag": "This run started with --max-file-size {size}, which applies until SolidCraft closes. These settings apply when it starts without it.", "prefs.max_file_size_note": "Defaults: 512 MB and 256 MB; at most 16 GB. Opening a file takes several times its size in memory. A design that keeps a large import may need a higher design file limit to save and reopen.", - "prefs.max_file_size_step": "STEP and import files", "prefs.max_file_size_web": "The web app opens STEP and import files up to 512 MB and designs up to 256 MB: a browser tab can't hold larger files. The desktop app can raise these limits.", "prefs.megabytes": "MB", + "prefs.network_locations_note": "For organisations that keep designs on file servers. Off: only servers you allow.", + "prefs.sketch.center_arc": "Centre-point arc follows the cursor", + "prefs.sketch.conflict_colour": "Conflict colour", + "prefs.sketch.tracking_guides": "Centre and midpoint guides", + "prefs.sketch.tracking_guides_note": "Temporary horizontal and vertical guides from hovered centres and edge midpoints.", "prefs.sketch_conflict_colour": "Conflicting geometry in the conflict colour", "prefs.sketch_conflict_colour_note": "While a sketch's constraints conflict, the curves and points a failing constraint holds are drawn in the conflict colour too, not only its glyph or dimension. Off: they keep their usual colours.", "prefs.sketch_construction_lines": "Extended construction line tools", @@ -86,12 +101,18 @@ "prefs.sketch_tracking_guides": "Centre and midpoint alignment guides", "prefs.sketch_tracking_guides_note": "Hover over a circle centre or straight-edge midpoint, then move horizontally or vertically to show a temporary dotted guide.", "prefs.status_bar_note": "A thin bar along the window's bottom edge shows what is being edited, the open sketch's state in its colour and the design's units; a click on the units changes them. The sketch's state then no longer shows in the view's corner.", + "prefs.structure.appearance_note": "Colours, text and accessibility.", + "prefs.structure.tools_note": "How modelling tools behave.", "prefs.theme_follow": "Follow a theme file", "prefs.theme_follow_error": "Not applied: {error}. The last good theme stays on.", "prefs.theme_follow_launch": "Followed for this run only (--theme-file); reloaded whenever another tool rewrites it.", "prefs.theme_follow_note": "Reloaded whenever another tool rewrites it. Choosing a theme stops following it.", "prefs.theme_follow_off": "Off", "prefs.theme_follow_stop": "Stop following", + "prefs.theme_option_opacity_help": "Adjust floating panel opacity. A readability floor protects text over viewport colours.", + "prefs.theme_option_tab_colours": "Tab colours", + "prefs.theme_option_tab_colours_help": "Use this theme’s panel and viewport colours for each ribbon tab.", + "prefs.theme_option_tab_fade_ms_help": "Fade panel and viewport colours when switching tabs. Zero switches instantly.", "prefs.trackpad_zoom_modifier.help": "Hold only this key to zoom at the pointer with vertical scroll. Off keeps the existing scroll behaviour.", "prefs.view": "View behaviour", "prefs.viewport_background_colour": "Colour", @@ -234,7 +255,10 @@ "ui.default_modelling_orientation": "Default modelling orientation", "ui.design_properties.license": "Licence", "ui.design_properties.organization": "Organisation", + "ui.details_curvature_caption": "Faces are coloured by their local radius of curvature.", + "ui.details_draft_caption": "Faces are coloured by their angle to the pull direction.", "ui.export_keymap_tip": "Keys, S box favourites and the toolbar, as a file", + "ui.instances": "Instances", "ui.layout_compact": "Compact", "ui.layout_floating": "Floating", "ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.", diff --git a/assets/locales/en.json b/assets/locales/en.json index b583a827a..91b914f50 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "BLEND SURFACE", "BOUNDARY SURFACE": "BOUNDARY SURFACE", "BROWSER": "BROWSER", + "Back to the original order": "Back to the original order", "Ball": "Ball", "Bar": "Bar", "Base Center": "Base Center", @@ -378,7 +379,7 @@ "Move Type": "Move Type", "Move down": "Move down", "Move earlier": "Move earlier", - "Move holes by clicking or dragging": "Move holes by clicking or dragging", + "Move holes by clicking or dragging": "Move by click or drag", "Move later": "Move later", "Move up": "Move up", "Name": "Name", @@ -476,6 +477,7 @@ "Rectangular": "Rectangular", "Rectangular Tube": "Rectangular Tube", "Reference face": "Reference face", + "Reference plane": "Reference plane", "Relief Depth": "Relief Depth", "Relief Width": "Relief Width", "Remove Tools": "Remove Tools", @@ -493,7 +495,8 @@ "Rename Folder": "Rename Folder", "Render Stage": "Render Stage", "Reopen designs": "Reopen designs", - "Reopen the designs that were open when SolidCraft was last closed": "Reopen the designs that were open when SolidCraft was last closed", + "Reopen the designs that were open when SolidCraft was last closed": "Reopen the designs that were open last time", + "Repair Part": "Repair Part", "Replace existing library file": "Replace existing library file", "Report a bug — review a screenshot and open a GitHub draft": "Report a bug — review a screenshot and open a GitHub draft", "Report copied. Keep this text to submit on GitHub when you are online.": "Report copied. Keep this text to submit on GitHub when you are online.", @@ -555,6 +558,7 @@ "Section": "Section", "Section (optional)": "Section (optional)", "Section position": "Section position", + "Sections": "Sections", "Sections (one sketch each)": "Sections (one sketch each)", "Select Other": "Select Other", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).", @@ -581,7 +585,7 @@ "Show ghost": "Show ghost", "Show in folder": "Show in folder", "Show the pointer an AI agent moves (#35)": "Show the pointer an AI agent moves (#35)", - "Show tool at cursor": "Show tool at cursor", + "Show tool at cursor": "Tool at the cursor", "Signed axes": "Signed axes", "Size": "Size", "Sketch constraints": "Sketch constraints", @@ -592,9 +596,11 @@ "Sketch points": "Sketch points", "Slider": "Slider", "Slot width": "Slot width", - "Snap to face and edge centres": "Snap to face and edge centers", + "Snap to face and edge centres": "Snap to centers", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft closed before these designs were saved. Their last autosave can be opened.", + "Sort A to Z": "Sort A to Z", + "Sort Z to A": "Sort Z to A", "Spacing 2 must be a non-zero number": "Spacing 2 must be a non-zero number", "Spacing must be a non-zero number": "Spacing must be a non-zero number", "Specialise": "Specialize", @@ -733,36 +739,36 @@ "a picked edge's body is gone": "a picked edge's body is gone", "add a key for a joint first": "add a key for a joint first", "ai.connected_toast": "SolidCraft is now available in {clients}. Restart them to use it (Preferences > Assistant).", - "ai.prefs.allow_control": "Let AI agents connect (control channel / MCP)", - "ai.prefs.allow_control_note": "Opens a control channel on this computer only (127.0.0.1, port 27878 or the next free one). A program that connects must also show a secret token that only your user account can read, made fresh at every start. Takes effect the next time SolidCraft starts. Off: nothing listens unless you start SolidCraft with --control.", - "ai.prefs.availability": "Assistant controls", - "ai.prefs.background_commands": "Run agent commands in the background", - "ai.prefs.connect_apps": "Make SolidCraft available to AI apps on this computer", - "ai.prefs.connect_apps_note": "When SolidCraft starts, adds it as an MCP server to the AI apps found on this computer (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), so an agent can use it without any setup. Only the solidcraft entry is added or its path refreshed; an entry you changed is left alone, and the file is backed up first. Off: the entries it added are removed. Help > Connect AI assistants… does this by hand.", - "ai.prefs.connect_at_start": "Connect the last-used agent when SolidCraft starts", + "ai.prefs.allow_control": "Let AI agents connect", + "ai.prefs.allow_control_note": "A local channel (MCP). Nothing leaves this computer.\n\nOpens a control channel on this computer only (127.0.0.1, port 27878 or the next free one). A program that connects must also show a secret token that only your user account can read, made fresh at every start. Takes effect the next time SolidCraft starts. Off: nothing listens unless you start SolidCraft with --control.", + "ai.prefs.availability": "Availability", + "ai.prefs.background_commands": "Run slow commands in the background", + "ai.prefs.connect_apps": "Add SolidCraft to AI apps", + "ai.prefs.connect_apps_note": "Off takes the entries out again.\n\nWhen SolidCraft starts, adds it as an MCP server to the AI apps found on this computer (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), so an agent can use it without any setup. Only the solidcraft entry is added or its path refreshed; an entry you changed is left alone, and the file is backed up first. Off: the entries it added are removed. Help > Connect AI assistants… does this by hand.", + "ai.prefs.connect_at_start": "Connect the last agent at start", "ai.prefs.connect_at_start_note": "Starts the agent you connected last (or the default one) in the background each time SolidCraft starts, so it is ready for chatting. Not when SolidCraft is started with --control. If it cannot connect, the Assistant shows Connection failed and a Retry button.", - "ai.prefs.follow_camera": "Turn the camera to sketches", + "ai.prefs.follow_camera": "Follow the camera", "ai.prefs.follow_camera_off": "Automatic camera following is off.", "ai.prefs.follow_camera_on": "The camera turns to face sketches the agent creates.", - "ai.prefs.intro": "Agents, permissions and how their work appears.", - "ai.prefs.make_default": "Use by default", + "ai.prefs.intro": "AI agents in SolidCraft.", + "ai.prefs.make_default": "Make default", "ai.prefs.no_agents": "No agents yet. Add an agent or refresh to find installed agents.", "ai.prefs.no_saved_approvals": "No saved approvals.", - "ai.prefs.open_at_start": "Open the Assistant panel when SolidCraft starts", + "ai.prefs.open_at_start": "Open the chat at start", "ai.prefs.open_at_start_note": "Shows the Assistant panel (or its own window) each time SolidCraft starts. Not when SolidCraft is started with --control.", "ai.prefs.override_all_warning": "This agent may save, overwrite, export or replace the design without asking.", - "ai.prefs.permission_all": "Allow everything", - "ai.prefs.permission_all_summary": "Available SolidCraft tools run without asking.", - "ai.prefs.permission_ask": "Ask before changes", - "ai.prefs.permission_ask_summary": "Approve every design change and file action.", - "ai.prefs.permission_edits": "Allow model edits", - "ai.prefs.permission_edits_summary": "Model edits run; file and destructive actions still ask.", + "ai.prefs.permission_all": "Do everything", + "ai.prefs.permission_all_summary": "Never asks", + "ai.prefs.permission_ask": "Ask first", + "ai.prefs.permission_ask_summary": "Asks for every change", + "ai.prefs.permission_edits": "Make edits", + "ai.prefs.permission_edits_summary": "Edits freely, asks for the rest", "ai.prefs.permission_scope": "For SolidCraft tools only. The agent’s shell and file edits use its own permissions.", "ai.prefs.pointer_preview_hidden": "Pointer hidden", "ai.prefs.pointer_preview_speed": "Agent pointer · {speed}", - "ai.prefs.pointer_speed": "Motion speed", + "ai.prefs.pointer_speed": "Speed", "ai.prefs.privacy_note": "Only your chosen agent or endpoint receives the conversation. Endpoint keys are stored in your system keychain.", - "ai.prefs.show_pointer": "Show agent pointer", + "ai.prefs.show_pointer": "Show the agent's pointer", "ai.prefs.turn_limit_hint": "Maximum design-changing tool calls the Assistant may make for one message.", "angle, height": "angle, height", "appearance.dielectric_ior": "Dielectric IOR", @@ -785,11 +791,19 @@ "browser.edit_canvas_title": "Edit Canvas: {name}", "browser.edit_point_cloud_title": "Edit Point Cloud: {name}", "browser.move_title": "Move: {name}", + "browser.needs_repair": "{name}: needs repair", "browser.parameters": "Parameters ({count})", "browser.precision": "Precision: {precision}", "browser.sketch_attachment_lost": "{name} (attachment lost)", "browser.sketch_editing": "{name} (editing)", "browser.sketch_name": "Sketch{number}", + "browser.sketches_to_parts_already_in_part": "already in their part", + "browser.sketches_to_parts_design_body": "on a body of the design itself", + "browser.sketches_to_parts_moved": "Moved {moved} sketches to the part they're on", + "browser.sketches_to_parts_no_exact_attachment": "on a face without an exact attachment", + "browser.sketches_to_parts_not_on_face": "not on a part's face", + "browser.sketches_to_parts_part_missing": "their part is gone", + "browser.sketches_to_parts_result": "Moved {moved} sketches to the part they're on; {stayed} stayed: {why}", "browser.units": "Units: {units}", "cam.flat": "Flat face", "cam.follower": "Follower", @@ -821,7 +835,10 @@ "cmd.assembly_bom": "Bill of Materials", "cmd.assembly_bom_item_set": "Change Item Number", "cmd.assembly_bom_renumber": "Renumber Items", + "cmd.assembly_mass_properties": "Mass Properties", + "cmd.body.print_face": "Print Face", "cmd.body_rename": "Rename Body", + "cmd.body_repair": "Repair Part", "cmd.browser_collapse_all": "Collapse All", "cmd.browser_expand_all": "Expand All", "cmd.browser_group": "New Group", @@ -849,6 +866,7 @@ "cmd.component_extract": "Extract to File", "cmd.component_finish_edit": "Finish Edit", "cmd.component_from_bodies": "Create Components from Bodies", + "cmd.component_hide_history": "Hide Component History", "cmd.component_insert_design": "Insert Design", "cmd.component_links": "List Links", "cmd.component_list": "List Components", @@ -857,6 +875,7 @@ "cmd.component_move_bodies": "Move Bodies to Component", "cmd.component_move_features": "Move Features to Component", "cmd.component_move_sketches": "Move Sketches to Component", + "cmd.component_move_sketches_to_parts": "Move Sketches to Their Parts", "cmd.component_paste_from_design": "Paste from Another Design", "cmd.component_paste_new": "Paste New", "cmd.component_properties": "Component Physical Properties", @@ -864,6 +883,7 @@ "cmd.component_rename": "Rename Component", "cmd.component_replace_with_link": "Replace with Link", "cmd.component_revert_position": "Revert Position", + "cmd.component_show_history": "Show Component History", "cmd.component_unlock": "Unlock Contents", "cmd.component_update_links": "Update Links", "cmd.config_activate": "Activate Configuration", @@ -874,6 +894,7 @@ "cmd.config_rule": "Configuration Rule", "cmd.config_rules": "Configuration Rules", "cmd.config_table": "Display Configuration Table", + "cmd.construct.plane.axis_point": "Plane Through Axis And Point", "cmd.construct_axis_edge": "Axis Through Edge", "cmd.construct_axis_normal_to_face": "Axis Perpendicular To Face", "cmd.construct_axis_through_cylinder": "Axis Through Cylinder/Cone/Torus", @@ -902,6 +923,8 @@ "cmd.diagnostics_crash_reports": "Crash Reports", "cmd.diagnostics_crash_reports_clear": "Delete Crash Reports", "cmd.diagnostics_crash_test": "Crash Test", + "cmd.diagnostics_profile": "Profile", + "cmd.diagnostics_validation": "Validation", "cmd.doc_recover": "Recover Design", "cmd.doc_recovery_discard": "Discard Recovered Design", "cmd.doc_recovery_list": "Recoverable Designs", @@ -952,6 +975,11 @@ "cmd.explode_show": "Show Exploded View", "cmd.expr_evaluate": "Evaluate Expression", "cmd.face_delete": "Delete Face", + "cmd.file.export_3mf": "Export 3MF", + "cmd.file.export_obj": "Export OBJ", + "cmd.file.export_step": "Export STEP", + "cmd.file.export_stl": "Export STL", + "cmd.file.export_urdf": "Export URDF", "cmd.file_export": "Export", "cmd.file_insert_mesh": "Insert Mesh", "cmd.file_insert_step": "Insert STEP", @@ -964,11 +992,13 @@ "cmd.frame_profile_list": "Profile Library", "cmd.frame_profile_properties": "Profile Properties", "cmd.inspect_accessibility": "Accessibility Analysis", + "cmd.inspect_analysis": "View Analysis", "cmd.inspect_center_of_mass": "Center of Mass", "cmd.inspect_clearance": "Clearance", "cmd.inspect_colored_components": "Enable Component Colors", "cmd.inspect_colored_components_disable": "Disable Component Colors", "cmd.inspect_compare": "Compare Bodies", + "cmd.inspect_compare_picture": "Compare Picture", "cmd.inspect_continuity": "Continuity Analysis", "cmd.inspect_curvature_comb": "Curvature Comb Analysis", "cmd.inspect_curvature_map": "Curvature Map Analysis", @@ -986,6 +1016,7 @@ "cmd.joint_delete": "Delete Joint", "cmd.joint_drive": "Drive Joints", "cmd.joint_edit": "Edit Joint", + "cmd.joint_find_limits": "Find Joint Limits", "cmd.joint_gear": "Gear", "cmd.joint_inspect": "Inspect Joint", "cmd.joint_limits": "Joint Limits", @@ -998,6 +1029,11 @@ "cmd.joint_screw": "Screw", "cmd.joint_solve": "Solve Joints", "cmd.joint_sweep": "Sweep Joint", + "cmd.layout.apply": "Apply Layout", + "cmd.layout.get": "Inspect Layout", + "cmd.layout.reset": "Reset Layout", + "cmd.layout.save": "Save Layout", + "cmd.layout.workspace.select": "Select Layout Workspace", "cmd.library_apply": "Apply Local Library Entry", "cmd.library_export": "Export Design Library", "cmd.library_inspect": "Inspect Local Library", @@ -1032,6 +1068,21 @@ "cmd.occurrence_move": "Move Occurrence", "cmd.occurrence_properties": "Occurrence Physical Properties", "cmd.occurrence_reparent": "Move to Component", + "cmd.panel.activate": "Activate Panel Tab", + "cmd.panel.close": "Close Panel", + "cmd.panel.collapse": "Collapse Panel Section", + "cmd.panel.dismiss": "Dismiss Panel Peek", + "cmd.panel.float": "Float Panel", + "cmd.panel.focus": "Focus Panel", + "cmd.panel.list": "List Panels", + "cmd.panel.move": "Move Panel", + "cmd.panel.native_close": "Redock Native Panel Section", + "cmd.panel.open": "Open Panel", + "cmd.panel.peek": "Peek Collapsed Panel", + "cmd.panel.popout": "Pop Out Panel", + "cmd.panel.reset_pair": "Reset Panel Sash", + "cmd.panel.resize": "Resize Panel Section", + "cmd.panel.resize_pair": "Resize Panel Sash", "cmd.parameters_add": "Add User Parameter", "cmd.parameters_change": "Change Parameters", "cmd.parameters_comment": "Comment Parameter", @@ -1060,6 +1111,9 @@ "cmd.pointcloud_edit": "Edit Point Cloud", "cmd.pointcloud_insert": "Insert Point Cloud", "cmd.pointcloud_list": "Point Clouds", + "cmd.render.compare.divider": "Move Render Comparison Divider", + "cmd.render.result.discard": "Discard Render Result", + "cmd.render.result.select": "Select Render Result", "cmd.render_aging_describe": "Layered Surface Aging", "cmd.render_backends": "Render Backends", "cmd.render_batch": "Render All Shots", @@ -1223,6 +1277,7 @@ "cmd.sketch_spline_control_point_5": "Control Point Spline (Degree 5)", "cmd.sketch_spline_fit_point": "Fit Point Spline", "cmd.sketch_spline_insert_point": "Add Spline Point", + "cmd.sketch_spline_remove_point": "Remove Spline Point", "cmd.sketch_spline_reverse": "Reverse Spline Direction", "cmd.sketch_spun_profile": "Spun Profile", "cmd.sketch_toggle_diameter": "Toggle Radius / Diameter", @@ -1273,9 +1328,11 @@ "cmd.timeline_rollback": "Move Timeline Marker", "cmd.timeline_stop": "Stop History", "cmd.timeline_suppress": "Suppress Feature", + "cmd.ui.assistant": "Toggle Assistant", "cmd.view.render_browser": "Render Browser", "cmd.view.render_dock": "Move Render Dock", "cmd.view.render_focus": "Render Focus View", + "cmd.view.status_details": "Viewport Status Details", "cmd.view.status_items": "Viewport Status Items", "cmd.view_ambient_occlusion": "Ambient Occlusion", "cmd.view_angle_readout": "View Angles", @@ -1306,17 +1363,28 @@ "cmd.view_tool": "Navigation tool", "cmd.view_top": "Top View", "cmd.view_visual_style": "Visual style", + "color.blue": "Blue", "color.copy": "Click to copy color values", "color.edit": "Click to edit color", "color.gamma": "Showing color values in 0-255 gamma space", + "color.green": "Green", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", "color.hue": "Hue", "color.linear": "Showing color values in 0-1 linear space", + "color.recent": "Recent colors", + "color.recent_help": "Colors you pick in any color field appear here", + "color.red": "Red", + "color.saturation": "Saturation (percent)", "color.saturation_value": "Saturation and value", "color.selected": "Selected color", + "color.step_down": "Step down", + "color.step_up": "Step up", + "color.value": "Value, the brightness (percent)", "config.column_filter_empty": "No matching columns", + "config.rule_parameter_columns": "Only parameters with a column in the table are listed. Add one with Add Column (+) to use it here.", + "config.rule_suppression_columns": "Only features with a Suppress column in the table are listed. Add one with Add Column (+) to drive it here.", "contact.components_count": "{count} components", "contact.enabled_label": "enabled", "coupling.gear_1": "Gear 1", @@ -1351,6 +1419,7 @@ "crash.unclean_explanation": "Detected on a later launch; the exact exit time was not recorded. A system shutdown or forced stop can also cause an unclean exit.", "delete.and_more": "… and {count} more", "diagnostic.empty_boolean_component": "there is no body to cut or intersect in component '{component}'; the tool may overlap '{body}' in component '{other}' — activate that component or pick the body as a target", + "diagnostic.reselect_reference": "{feature}: the reference `{reference}` no longer exists as it was picked; reselect it", "dialog.bodies_count": "{count} bodies", "dialog.clearance_invalid": "the clearance must be a length of 0 or more", "dialog.compute": "Compute", @@ -1360,11 +1429,20 @@ "dialog.custom_axis": "↖ Custom Axis", "dialog.dimension_insert_hint": "Click another driving dimension to insert its name", "dialog.dimension_name": "Dimension: {name}", + "dialog.dimension_step_down": "Down by {step}", + "dialog.dimension_step_expression": "Only a number steps; an expression stays as typed", + "dialog.dimension_step_up": "Up by {step}", "dialog.edit_title": "EDIT {title}", "dialog.no_shown_body": "No shown body to change: show one, or choose New Body", + "dialog.pattern_sketch_not_object": "Pick bodies or features: a sketch is neither. Repeat its curves with the sketch's own Pattern or Mirror, or extrude it first.", "dialog.select": "↖ Select", "dialog.selected_count": "↖ {count} selected", + "dialog.selection_constraint": "Constraint {id}", + "dialog.selection_external_curve": "{sketch} · curve {id}", + "dialog.selection_external_point": "{point} · {sketch}", "dialog.selection_guidance": "Select an input to change it. Click selected objects to remove them; Ctrl/Cmd-click also toggles them. Review the preview, then press OK.", + "dialog.selection_midpoint": "Midpoint · {id}", + "dialog.selection_profile": "{sketch} · profile {number}", "dialog.selection_step": "{step} of {total}: Select {input}", "dialog.step": "Step", "document.changed_on_disk": "{name} changed on disk", @@ -1379,6 +1457,7 @@ "document.read_only_save": "This design was opened read-only: save it as a new file", "document.save_changes": "Save changes to {name}?", "document.save_copy": "Save a Copy…", + "document.tab_unsaved_changes": "Unsaved changes", "document.unsaved_changes": "{name} has unsaved changes. If you don't save, they are lost.", "drive.rigid": "{joint} is a rigid joint: it holds its parts still, so it has nothing to drive. To let them move, change its type in Edit Joint: Revolute to rotate, Slider to slide, Cylindrical for both.", "drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}", @@ -1411,6 +1490,14 @@ "file_load.reading_percent": "Reading the file... {percent}%", "file_load.rebuilding": "Rebuilding feature {done} of {total}", "file_load.recovering": "Recovering design", + "file_load.step_build": "Building the model", + "file_load.step_feature": "Feature {done} of {total}", + "file_load.step_part": "Part {done} of {total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "Reading the file", + "file_load.step_rebuild": "Rebuilding the features", + "file_load.step_repair": "Checking and repairing the parts", + "file_load.step_show": "Preparing the view", "file_load.stopping": "Waiting for the previous operation to stop...", "file_load.updating_links": "Updating links", "file_load.waiting": "Waiting for file operation", @@ -1419,21 +1506,189 @@ "from the rule": "from the rule", "help.apache": "Apache license 2.0", "help.appearance.assign": "Gives the selected bodies, faces or components a color or a material look, without changing their weight. Use it to tell parts apart or to preview a finish.", + "help.assembly.bom": "Lists the parts of the design or a component with their counts, by part number, and can save the list as CSV or JSON. Use it as the parts list for ordering and assembly.", "help.attributions": "Attributions (ATTRIBUTION.md)", "help.build": "Version {version} · commit {commit} · built {date}", + "help.canvas.decal": "Places an image on a planar face of the model, like a sticker. Use it to show a label, logo or printed pattern on a part.", + "help.canvas.edit": "Changes a canvas: its position, size, angle, opacity, mirroring, visibility or name. Use it to line up a reference image with the sketch you trace over it.", + "help.canvas.insert": "Places a PNG or JPEG image on a plane or face as a see-through reference. Use it to trace a photo or drawing in a sketch, with the image scaled to a known size.", + "help.component.break_link": "Cuts a linked component loose from its design file, keeping its bodies as they are. Use it when the part should no longer follow changes to the original file.", + "help.component.capture_position": "Keeps the positions of parts you moved by hand, so they become where those parts are. Use it after dragging parts into place that no joint holds.", + "help.component.create": "Adds a new, empty component to the design, inside the active component unless you choose another parent. Use it to give a new part of an assembly its own place for bodies and sketches.", "help.component.finish_edit": "Saves the part you are editing in place, returns to its assembly and updates the assembly from it. Use it when your changes to the linked part are done.", + "help.component.from_bodies": "Turns each selected body into a component of its own, named after the body. Use it when a design built as loose bodies should become an assembly whose parts can be joined and moved.", + "help.component.insert_design": "Inserts another saved design as a component linked to its file, with its solid bodies placed as they are there. Use it to reuse a part in an assembly and pick up later changes with Update Links.", + "help.component.properties": "Shows the volume, mass, centre of mass and moments of inertia of a component, using its bodies' materials. Use it to check weight and balance of an assembly.", + "help.component.revert_position": "Puts parts you moved by hand back where they were, dropping moves that were not captured. Use it to undo trial moves in an assembly.", + "help.component.update_links": "Reads the linked design files again and replaces bodies where they changed. Use it after editing a part that this assembly uses.", + "help.config.configure": "Adds parameters, features, materials or appearances as columns of the configuration table. Use it to build variants of one design, such as sizes of a part.", + "help.config.preview": "Checks that a row of the configuration table rebuilds, without changing the design or its history. Use it before switching to a variant you are not sure of.", + "help.config.rules": "Shows the rules of the configuration table, its rows and which row is active. Use it to see how the variants of a design are set up.", + "help.config.table": "Shows the configuration table: one row per variant, one column per parameter or feature, and whether the design still matches the active row. Use it to review the variants of a design.", "help.connect_note": "Restart each assistant to load the SolidCraft server. Each file was backed up as .bak before it changed.", "help.connect_title": "Connect AI assistants", + "help.construct.axis.edge": "Creates a construction axis along a straight edge or sketch line. Use it as the axis for a revolve, a circular pattern or a joint.", + "help.construct.axis.normal_to_face": "Creates a construction axis through a point, square to a face. Use it as an axis that stands straight out of a surface.", + "help.construct.axis.through_cylinder": "Creates a construction axis through the centre of a cylinder, cone or torus face, or a circular edge. Use it to turn or pattern features around a round part.", + "help.construct.axis.two_planes": "Creates a construction axis where two planes or flat faces meet. Use it when the axis you need is the line between two faces.", + "help.construct.axis.two_points": "Creates a construction axis through two points, vertices or sketch points. Use it for an axis that runs between two known positions.", + "help.construct.plane.along_path": "Creates a construction plane square to an edge or curve, at a position along it. Use it to sketch a profile for a sweep or a section of a path.", + "help.construct.plane.at_angle": "Creates a construction plane turned by an angle from a plane or face, about an axis or edge. Use it for sloped sketches, such as an angled bracket.", + "help.construct.plane.axis_point": "Creates a construction plane containing an axis and a point off that axis. Pick an origin or construction axis, a straight edge or sketch line, then a vertex, sketch point or construction point. A point on the axis cannot define a unique plane.", + "help.construct.plane.midplane": "Creates a construction plane halfway between two planes or flat faces, or bisecting them where they meet at an angle. Use it as a symmetry plane for mirroring.", + "help.construct.plane.offset": "Creates a construction plane parallel to a plane or flat face, at a distance or through a point. Use it to sketch at a set height above a face.", + "help.construct.plane.perpendicular": "Creates a construction plane that holds a line or edge and stands square to a plane or face. Use it to sketch upright on a model along an edge.", + "help.construct.plane.tangent": "Creates a construction plane that touches a cylinder, cone, sphere or torus at a point. Use it to sketch on the side of a round part.", + "help.construct.plane.three_points": "Creates a construction plane through three points. Use it for a plane set by positions on the model, such as three corners.", + "help.construct.plane.two_edges": "Creates a construction plane through two straight edges or lines that lie in one plane. Use it for a plane across a part, such as through two opposite edges.", + "help.construct.point.along_path": "Creates a construction point at a position along an edge or curve. Use it as a reference partway along a path.", + "help.construct.point.center": "Creates a construction point at the centre of a circular edge, sketch circle or arc, sphere or torus. Use it as a reference for holes, axes and joints.", + "help.construct.point.edge_plane": "Creates a construction point where an edge or line passes through a plane or flat face. Use it to mark where a path crosses a plane.", + "help.construct.point.three_planes": "Creates a construction point where three planes or flat faces meet. Use it as a corner reference, even where the model has no vertex.", + "help.construct.point.two_edges": "Creates a construction point where two edges or lines meet, or come closest. Use it as a reference at a virtual corner.", + "help.construct.point.vertex": "Creates a construction point on a vertex or sketch point. Use it as a reference that stays when the sketch or body around it is hidden.", + "help.contact.check": "Lists the pairs of parts in contact sets that pass through each other in their current position. Use it to find collisions before you drive joints or run a motion study.", + "help.contact.create": "Groups two or more parts into a contact set, whose bodies are kept from passing through each other while joints move. Use it for parts that should stop when they touch, such as a lever against its stop.", + "help.contact.disable_all": "Turns contact off, so driven joints and motion studies no longer stop where parts touch. Use it to move parts freely again, or to keep a large assembly responsive.", + "help.contact.edit": "Changes a contact set: the parts it holds, its name, or whether it is suppressed; it can also delete the set. Use it to adjust which parts are kept from passing through each other.", + "help.contact.enable_all": "Puts every part of the assembly into one contact set, so no two parts can pass through each other while joints move. Use it for a quick check of a whole mechanism.", + "help.contact.enable_sets": "Turns contact on for the contact sets you defined, so driven joints and motion studies stop where their parts would pass through each other. Use it to bring your sets back after turning contact off.", + "help.contact.list": "Lists the contact sets of the design, the parts in each one and whether contact is on. Use it to check how contact is set up before you drive the assembly.", + "help.document.inspect": "Shows an overview of the design: its components, bodies, sketches, features and parameters. Use it to get your bearings in a design you did not build yourself.", + "help.document.units": "Changes the units the design shows lengths in, such as mm or inches. The geometry keeps its size; only the display and plain numbers follow.", + "help.edit.checkpoint": "Remembers the design, the active sketch and the undo history as they are now. Use it before trying something risky that you may want to go back from.", + "help.edit.restore_checkpoint": "Goes back to a checkpoint, undo history included. Use it to drop everything done since the checkpoint in one step.", + "help.explode.create": "Creates an exploded view that pushes the parts away from the assembly's centre, or by the moves you set. Use it to show how an assembly goes together, for instructions or presentations.", "help.face.delete": "Removes the selected faces and lets the neighboring faces close the gap, or leaves the gap open as a surface. Use it to take off a rounded edge, a hole or a boss that is in the way.", + "help.file.insert_mesh": "Adds a 3MF, STL, OBJ, PLY or glTF file to the design as mesh bodies in a new component. Use it to place a downloaded or scanned model beside your design as a reference.", + "help.file.insert_step": "Adds a STEP, IGES, FreeCAD or Rhino file to the design as solid bodies in a new component; an assembly's parts become nested components. Use it to bring in models from suppliers or other CAD programs.", + "help.file.save_mesh": "Saves bodies as an STL, 3MF or OBJ mesh, with the smoothness of curved faces you choose. Use it to prepare parts for 3D printing or for programs that read meshes.", + "help.file.send_to_slicer": "Saves the selected bodies as a 3MF file and opens it in the slicer you choose. Use it to go from the model to printing in one step.", "help.font_details": "The interface uses egui's built-in fonts (Ubuntu Light and Hack, under the Ubuntu Font Licence and the MIT/Bitstream Vera license; Noto Emoji and the emoji icon font, under the OFL and MIT). Sketch text uses Liberation Sans (SIL OFL 1.1). The Crafting Apps' optional font pack, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), is not bundled in SolidCraft builds.", "help.fonts": "Fonts", + "help.frame.member": "Places a profile, such as a tube or an aluminium extrusion, along the lines of a frame sketch, one member per line. Use it to build frames, racks and welded structures.", + "help.inspect.accessibility": "Colours the faces a tool can reach from one direction, and those it cannot. Use it to check a part for machining or moulding from that side.", + "help.inspect.center_of_mass": "Shows the centre of mass of bodies, each on its own and all together, at uniform density. Use it to check balance and where a part will tip.", + "help.inspect.colored_components": "Gives each component its own temporary colour, without changing appearances. Use it to tell the parts of an assembly apart at a glance.", + "help.inspect.compare": "Compares two bodies and shows where one has material the other does not, with volume and deviation. Use it to check a changed or imported part against the original.", + "help.inspect.continuity": "Checks how smoothly faces meet along their edges: gaps, kinks or curvature jumps, and shades the seams. Use it to find where surfaces do not join cleanly.", + "help.inspect.curvature_comb": "Draws combs along curves, edges or faces whose teeth show how strongly they bend. Use it to spot flat spots, kinks and uneven curvature.", + "help.inspect.curvature_map": "Colours faces by how strongly they curve, red where the radius is small. Use it to find tight spots and to judge how smooth a surface is.", + "help.inspect.draft": "Colours faces by their draft angle to a pull direction, marking those with too little. Use it to check a part before moulding or casting.", + "help.inspect.environment_map": "Shows the model with a reflective, mirror-like finish. Use it to judge the flow of surfaces by the way reflections run across them.", + "help.inspect.interference": "Finds bodies that overlap and shows each overlap with its volume. Use it to check an assembly for parts that collide.", + "help.inspect.isocurve": "Draws the isoparametric curves of faces, the grid the surface is built on. Use it to see how a surface flows and where it bunches up.", + "help.inspect.measure": "Measures lengths, distances, angles, areas and radii between what you pick, or the volume and mass of bodies. Use it to check sizes and clearances.", + "help.inspect.minimum_radius": "Finds the smallest radius of curvature of curves, edges or faces, and where it is. Use it to check that a tool or nozzle can follow the shape.", + "help.inspect.section": "Cuts the view open along a plane and hatches the cut faces, without changing the model. Use it to look inside parts and assemblies.", + "help.inspect.zebra": "Shows black and white stripes reflected on the model's faces. Use it to judge smoothness: stripes that break or kink at an edge show a poor transition.", + "help.joint.as_built": "Joins two parts where they already are, without moving either one, and sets how they may still move. Use it for parts you have already placed in their final position.", + "help.joint.cam": "Links a turning cam to a follower, so the follower slides or swings as the cam's outline passes under it. Use it for cams, eccentrics and valve drives.", + "help.joint.create": "Joins two parts at the joint origins you pick and moves the second part into place; the joint type sets how they may still move. Use it to build an assembly whose parts move like the real mechanism.", + "help.joint.drive": "Sets a joint's angle or distance and moves the parts with it, within its limits; linked joints and closed loops follow. Use it to check that a mechanism moves as intended.", + "help.joint.gear": "Links two turning joints with a gear ratio, so driving one turns the other. Use it for spur and ring gears, with the ratio from pitch radii or tooth counts.", + "help.joint.limits": "Sets how far a joint may turn or slide, as a minimum and a maximum, or clears those limits. Use it to keep a hinge, slider or lever within its real range of travel.", + "help.joint.motion_link": "Couples two joints with a ratio and an offset, so driving one moves the other. Use it for a fixed relation between joints that Gear, Rack and Pinion or Screw do not cover.", + "help.joint.origin": "Places a named joint origin on a part: at the centre of a face or round end, the middle of an edge, a corner or a point. Use it to prepare where joints attach; one picked on a face follows it when the part changes size.", + "help.joint.rack_pinion": "Links a turning pinion to a sliding rack, so the rack moves by the length of pitch circle the pinion rolls through. Use it for rack drives, steering and linear stages.", + "help.joint.reach": "Moves a point on a part toward a target by changing the joints on its chain, within their limits. Use it to pose a mechanism by where its end should be, such as the tip of a robot arm.", + "help.joint.rigid_group": "Locks the selected parts together as they are, so they move as one. Use it for parts that belong together and have no motion between them.", + "help.joint.screw": "Links turning and sliding by a pitch, so each turn advances by that distance. Use it for lead screws, bolts and threaded spindles.", + "help.layout.apply": "Apply a saved layout to the current workspace. Retained editors keep their drafts.", + "help.layout.get": "Read the committed layout and discover registered workspaces.", + "help.layout.reset": "Restore the current workspace's registered default layout. User presets remain available.", + "help.layout.save": "Save the complete layout under a name. Replacing a user preset requires explicit overwrite permission.", + "help.layout.workspace.select": "Select a registered layout workspace and remember the outgoing layout.", + "help.library.apply": "Applies a material or appearance from a local library file to bodies, faces or components. Use it to reuse materials you saved from another design.", + "help.library.export": "Saves the design's materials and appearances to a library file. Use it to share them or reuse them in other designs.", + "help.library.inspect": "Checks a library file and lists its materials and appearances, without changing the design. Use it to see what a library holds before applying it.", "help.licences": "Licenses", "help.material.assign": "Sets what the selected bodies are made of, such as steel, aluminum or ABS. Use it so that the mass and weight match the real part.", + "help.material.properties.validate": "Checks a material data card for consistent numbers and missing values. Use it before relying on the data for mass or stiffness.", + "help.mesh.convert": "Rebuilds a mesh body, such as an STL, as an editable solid with flat and cylindrical faces. Use it to modify imported mechanical parts like a modelled body.", "help.mit": "MIT license", + "help.motion.study": "Sets joint values at steps along a timeline and plays them back as an animation. Use it to watch a mechanism move through a sequence and check clearances along the way.", + "help.motion.trace": "Traces the path a point on a part follows while a motion study plays or a joint is driven, and keeps it as a 3D sketch curve when you confirm. Use it to see where a mechanism reaches, or to build on its path.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fixes a part in place, or frees it again, so that joints move the other parts around it. Use it for the frame or base that the rest of the assembly is built on.", "help.occurrence.move": "Moves an assembly part only along freedoms allowed by its joints. Select a part face, then drag an available arrow or arc.", + "help.panel.activate": "Select an open panel tab without requesting keyboard focus.", + "help.panel.close": "Close a panel through its content lifecycle guard. Its placement is remembered.", + "help.panel.collapse": "Collapse or expand a panel section while retaining its requested dimensions.", + "help.panel.dismiss": "Dismiss the temporary view of a collapsed panel.", + "help.panel.float": "Move a panel into an explicitly positioned floating section.", + "help.panel.focus": "Focus a panel, reopening its retained state and expanding its section when needed.", + "help.panel.list": "Read registered panel kinds, committed instances, active tabs, availability and host capabilities.", + "help.panel.move": "Move a panel into a new section or join an existing tab group.", + "help.panel.native_close": "Return a native panel section to its remembered dock without cancelling its content.", + "help.panel.open": "Open a panel kind with an explicit instance identity and placement for a new instance.", + "help.panel.peek": "Temporarily show a collapsed panel without changing its saved size or collapse state.", + "help.panel.popout": "Move a panel to a native host when supported. Browser hosts use a floating section.", + "help.panel.reset_pair": "Restore an adjacent dock pair's default size ratio within its shared bounds.", + "help.panel.resize": "Set a panel section's outer width and height within every tab's bounds.", + "help.panel.resize_pair": "Resize adjacent dock sections together while conserving their shared extent.", "help.parameters.change": "Opens the table of named values and expressions that drive the dimensions of the design. Use it to change a size in one place and let every feature that uses it follow.", + "help.parameters.export": "Saves the design's parameters as CSV or JSON. Use it to edit them in a spreadsheet or move them to another design.", + "help.parameters.graph": "Shows which parameters and features use which others, and any loops or errors among them. Use it to see what a change to a parameter will affect.", + "help.parameters.import": "Reads parameters from CSV or JSON into the design, all or none of them. Use it to bring in values from a spreadsheet or another design.", + "help.parameters.move": "Moves a user parameter before or after another in the list. Use it to keep related parameters together.", + "help.parts.fastener": "Adds a standard screw, bolt, nut, washer, pin or bearing in the size you pick. Placed on a hole, it seats in the hole with a joint, so you need not model fasteners yourself.", + "help.parts.insert": "Inserts a standard part in the family, size and length you pick. Placed on the rim or wall of a hole, it seats on the hole with a rigid joint.", + "help.parts.library": "Opens the standard parts: screws, bolts, nuts, washers, set screws, dowel pins and bearings in standard sizes. Use it to add a standard part instead of modelling it yourself.", + "help.parts.resize": "Changes the size or length of an inserted standard part and rebuilds it; its joints keep it seated. Use it when a screw turns out too long or a hole needs another size.", + "help.plastic.assign_rule": "Assigns a plastic rule to bodies, so their plastic features take its draft and clearance as defaults. Use it to set up a moulded part once for all its features.", + "help.plastic.boss": "Adds a screw boss on a face: a post with an optional hole, draft, root fillet and supporting ribs. Use it for screw points in moulded or printed housings.", + "help.plastic.lip": "Adds a lip or a matching groove along the rim of a shelled body (Shell a face open first, then pick the rim around that opening). Use it so that two housing halves locate on each other and close tightly.", + "help.plastic.manage_rules": "Creates and edits plastic rules: material, wall thickness, radii, clearance and draft. Use them to keep the features of a moulded part consistent.", + "help.plastic.rest": "Adds a rest on a face: a round or rectangular pad, solid or hollow, with draft. Use it as a support or standoff in a moulded housing.", + "help.plastic.snap_fit": "Adds a snap-fit hook on a face, with its length, thickness and catch. Use it to clip parts together without screws.", "help.pointcloud.insert": "Insert a PLY, XYZ or PTS scan as a point cloud alongside the model. Use it as a reference when building a model from measured data.", + "help.sheet.convert": "Turns a plate or shelled body of even thickness into a sheet metal body, with bends at the edges you pick. Use it to make an existing part unfoldable.", + "help.sheet.export_bend_table": "Saves the bend table of a sheet metal body as CSV or JSON: angles, radii and bend positions in the flat. Use it for the press brake or the workshop.", + "help.sheet.export_dxf": "Saves the flat pattern as a DXF, with outlines, bend lines and optional bend notes. Use it for laser, plasma or waterjet cutting.", + "help.sheet.flange": "Adds a flange: a base plate from a sketch, a wall along an open sketch contour, or a bent wall on sheet edges. Use it to build up sheet metal parts.", + "help.sheet.flat_pattern": "Creates the flat pattern of a sheet metal body, with its size, cut-outs and bend lines. Use it to check the blank before you cut it.", + "help.sheet.fold": "Bends a sheet along a sketch line by an angle and radius. Use it to fold a flat sheet after cutting features into it.", + "help.sheet.hem": "Folds a sheet edge back on itself. Use it for safe, stiff edges without sharp burrs.", + "help.sheet.manage_rules": "Creates and edits sheet metal rules: thickness, bend radius, K-factor, reliefs and gaps. Use them to match the material and tools of your workshop.", + "help.sheet.path_flange": "Adds a chain of flanges along a sheet edge, following an open chain of sketch lines. Use it for profiles such as a U or Z shape in one step.", + "help.sheet.perforate": "Adds a field of holes over the whole flat sheet, in a staggered or square pattern. Use it for vents, grilles and lighter panels.", + "help.sheet.refold": "Folds an unfolded sheet metal body back up. Use it after adding features to the flat sheet.", + "help.sheet.unfold": "Unfolds all bends of a sheet metal body. Use it to add holes or cuts that have to cross a bend, then refold.", + "help.sketch.arc.center_point": "Draws a circular arc around a centre point, from a start point to an end point. Use it when the arc's centre is known, such as a radius around a hole or a pivot.", + "help.sketch.arc.tangent": "Draws an arc that starts at the end of a line or arc and continues tangent to it. Use it to carry on a chain with a smooth bend instead of a corner.", + "help.sketch.arc.three_point": "Draws an arc from a start point to an end point through a third point. Use it when the arc has to pass through given points rather than around a known centre.", + "help.sketch.arc3d": "Draws an exact circular arc in space through three points, with 3D Sketch on. Use it for bends in paths and guide rails that leave the sketch plane.", + "help.sketch.auto_constrain": "Adds the constraints the sketch nearly has already, such as horizontal, parallel or coincident, then dimensions it until it is fully defined. Use it to lock a roughly drawn sketch in one step.", + "help.sketch.auto_constrain_from_datum": "Works like AutoConstrain, but measures the positions from a datum point you pick instead of the origin. Use it when the part is laid out from one reference point, such as a corner or a hole.", + "help.sketch.blend_curve": "Joins the ends of two curves with a smooth spline that is tangent to both, or also curvature continuous if you choose. Use it to bridge a gap between curves without a kink.", + "help.sketch.break": "Splits a curve into pieces where other curves cross it, or at points you place on it. Use it when part of a curve needs its own constraint or should be deleted on its own.", + "help.sketch.cancel": "Leaves the sketch and discards everything changed since it was created or opened for editing. Undo brings the changes back.", + "help.sketch.centerline": "Switches lines between normal lines and centerlines, axes that profiles leave out. Use a centerline as the axis for a revolve, a mirror or a symmetry constraint.", + "help.sketch.chamfer.distance_angle": "Bevels the corner between two lines, set by a distance along the first line and an angle. Use it when a drawing gives the chamfer as a length and an angle, such as 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Bevels the corner between two lines the same distance back along both. Use it for the usual 45° chamfer on an outline.", + "help.sketch.chamfer.two_distance": "Bevels the corner between two lines, set by a separate distance along each line. Use it for chamfers that are not 45°, given as two lengths.", + "help.sketch.circle.center": "Draws a circle from its centre and its diameter. Use it for holes, bosses and other round features whose centre is known.", + "help.sketch.circle.three_point": "Draws a circle through three points. Use it when the circle has to pass through given points, for example of existing geometry.", + "help.sketch.circle.three_tangent": "Draws a circle that touches three lines, circles or arcs. Use it to fit a circle into the space between three curves, such as the inscribed circle of a triangle.", + "help.sketch.circle.two_point": "Draws a circle from the two ends of its diameter. Use it when the circle's edge points are known rather than its centre.", + "help.sketch.circle.two_tangent": "Draws a circle of a given size that touches two lines, circles or arcs. Use it for a rounding of fixed radius between two curves.", + "help.sketch.conic": "Draws a conic curve between two end points, shaped by an apex point and a rho value. Use it for smooth transitions whose fullness you want to tune, from flat to nearly a sharp corner.", + "help.sketch.constrainer": "Applies the constraint that one or two picked curves nearly have already, such as horizontal, parallel, tangent or equal. Use it to tidy a hand-drawn sketch one relation at a time.", + "help.sketch.constraint.coincident": "Makes a point lie on another point, a curve or a sketch axis. Use it to close gaps in a profile or to put a point on a line.", + "help.sketch.constraint.collinear": "Makes two lines lie on one straight line. Use it to line up interrupted edges, such as both sides of a notch.", + "help.sketch.constraint.concentric": "Gives two circles or arcs the same centre, or centres a circle or arc on a sketch point, including the origin. Pick either pair in either order.", + "help.sketch.constraint.curvature": "Makes two curves that meet at an end point continue with the same curvature (G2). Use it where a tangent join is not smooth enough, for example on visible surfaces.", + "help.sketch.constraint.equal": "Makes lines the same length, or circles and arcs the same radius. Use it so that one dimension drives several matching features.", + "help.sketch.constraint.fix": "Fixes points or curves where they are, or frees them again. Use it for geometry that must not move when you drag or solve the sketch.", + "help.sketch.constraint.horizontal_vertical": "Makes a line, or the line between two points, horizontal or vertical, whichever is closer. Use it to square an outline up to the sketch axes.", + "help.sketch.constraint.midpoint": "Puts a point on the middle of a line, or makes the midpoints of two lines meet. Use it to centre geometry on an edge.", + "help.sketch.constraint.parallel": "Makes two lines parallel. Use it for sides that must stay parallel when other dimensions change.", + "help.sketch.constraint.perpendicular": "Makes two lines meet at a right angle. Use it for square corners between lines that are not on the sketch axes.", + "help.sketch.constraint.polygon": "Makes a closed chain of lines a regular polygon: equal sides, with every corner on one circle. Use it to make a hand-drawn polygon regular and keep it so.", + "help.sketch.constraint.symmetry": "Makes two points or curves mirror each other across a line or about a point. Use it to keep a profile symmetric when you change one side.", + "help.sketch.constraint.tangent": "Makes two curves touch tangentially, such as a line and an arc. Use it for smooth joins without a kink.", + "help.sketch.construction": "Switches curves between normal geometry and construction geometry, which profiles leave out. Use construction curves as helpers for layout, references and dimensions.", "help.sketch.construction_line": "Create an infinite construction line through two points. Use it to lay out a sketch without splitting profiles.", "help.sketch.construction_line.angle": "Create an infinite construction line at an angle from sketch X. Pick the point and type the angle, or pick its direction.", "help.sketch.construction_line.bisector": "Pick two intersecting straight sketch lines, then choose either angle bisector. The result follows its source lines.", @@ -1444,11 +1699,71 @@ "help.sketch.construction_line.tangent_external": "Pick a circle or circular arc, then an external point and a tangent solution. The previews show only contacts on the drawn arc.", "help.sketch.construction_line.tangent_two": "Pick two circles or circular arcs, then choose a common tangent in the preview. Contacts must lie on the drawn curves.", "help.sketch.construction_line.vertical": "Create an infinite vertical construction line through a point. Its vertical constraint follows later edits.", + "help.sketch.copy": "Copies the selected sketch curves and points, together with the constraints and dimensions among them. Paste them into this sketch or another one.", + "help.sketch.create": "Starts a new 2D sketch on a plane or on a flat face of the model. Every extrude, revolve and sweep begins with a sketch.", + "help.sketch.cut": "Copies the selected sketch geometry and deletes it from the sketch, in one undo step. Paste it elsewhere in this sketch or into another one.", + "help.sketch.dimension": "Adds a driving dimension: a length, distance, angle, radius or diameter, depending on what you pick. Type a value or a parameter name, and the sketch follows it.", + "help.sketch.edit": "Opens an existing sketch for editing. The features built on it update when you finish the sketch.", + "help.sketch.ellipse": "Draws an ellipse from its centre, the end of its major axis and a point on its minor side. Use it for oval openings, cams and other elongated round shapes.", "help.sketch.equation_curve": "Draws a curve from formulas: x(t) and y(t), or y = f(x), over a range. The formulas can use parameters and the curve follows them: use it for a sine wave, a spiral or a gear tooth's involute.", + "help.sketch.extend": "Lengthens a line or arc up to the nearest curve in its way, or grows two curves until they meet. Use it to close gaps in a profile after trimming or editing.", + "help.sketch.fillet": "Rounds the corner where two lines or arcs meet with an arc of a given radius. Several corners rounded together share one radius.", + "help.sketch.finish": "Leaves the sketch and returns to the model. Its closed profiles are then ready for Extrude, Revolve and other features.", + "help.sketch.finish_auto_constrain": "Runs AutoConstrain on the sketch, then finishes it. Use it to leave a sketch fully defined in one step.", + "help.sketch.fit_curves_to_section": "Cuts a mesh or solid body with the sketch plane and fits lines and arcs to the section. Use it to rebuild a scanned or imported part as an editable sketch.", + "help.sketch.include_3d": "Brings model edges, vertices and curves of other sketches into this sketch as linked references, flattening those off its plane onto it. Use it to build on geometry that does not lie in the sketch plane.", + "help.sketch.infinite": "Switches lines between normal lines and infinite construction lines that run across the whole view. Use them as layout references that never end too short.", + "help.sketch.insert_dxf": "Reads the curves of a DXF drawing into a sketch, scaled, turned and placed where you set. Use it to build on a 2D drawing from another program, such as a laser-cut outline.", + "help.sketch.insert_svg": "Reads the paths of an SVG drawing into a sketch, scaled, turned and placed where you set. Use it to turn a logo or vector outline into curves you can extrude.", + "help.sketch.inspect": "Opens a report on the open sketch: how many degrees of freedom are left and whether it is fully constrained. Use it to find out what still moves before you finish the sketch.", + "help.sketch.intersect": "Adds the curves or points where bodies, faces, edges or other sketches cross the sketch plane. They stay linked and follow the model when it changes.", + "help.sketch.intersection_curve": "Creates 3D curves where two bodies or faces meet, linked to them. Use them as paths or guide rails that follow the model.", + "help.sketch.isoparametric_curve": "Creates a 3D curve along a face's U or V direction through a point you pick, linked to the face. Use it as a path or split line that follows the surface.", + "help.sketch.line": "Draws connected lines point by point, as an open chain or a closed outline. It is the basic tool for most profiles.", + "help.sketch.line.midpoint": "Draws a line from its midpoint out to one end, with the other end mirrored. Use it for lines centred on a point, such as a symmetric edge.", + "help.sketch.line3d": "Draws connected straight lines between points in space, with 3D Sketch on. Use it for paths and frames that leave the sketch plane.", + "help.sketch.mirror": "Mirrors sketch curves and points across a line or axis and adds symmetry constraints. Use it to draw half of a symmetric profile and complete it.", + "help.sketch.move": "Moves or rotates sketch curves and points, or a copy of them. Use it to reposition geometry while keeping its shape and constraints.", + "help.sketch.offset": "Creates a copy of a chain of curves at a set distance, on one side or both. Use it for walls, outlines and clearances; the distance stays an editable dimension.", + "help.sketch.paste": "Pastes sketch geometry you copied or cut into the active sketch. Place it at a point or shift it by an offset.", + "help.sketch.pattern.circular": "Copies sketch geometry around a centre point, over a full circle or a set angle. Use it for bolt circles, spokes and teeth.", + "help.sketch.pattern.rectangular": "Copies sketch geometry in rows and columns at set spacings. Use it for grids of holes, slots or vents.", + "help.sketch.point": "Places a sketch point. Use it as a reference for dimensions, constraints, hole centres or later features.", + "help.sketch.point3d": "Places a point in space, with 3D Sketch on. Use it as a reference for 3D curves and paths.", + "help.sketch.polygon.circumscribed": "Draws a regular polygon around a circle, sized from its centre to the middle of a side. Use it when the width across flats is known, as for a hex nut.", + "help.sketch.polygon.edge": "Draws a regular polygon from the two ends of one side. Use it when the length and position of a side are known.", + "help.sketch.polygon.inscribed": "Draws a regular polygon inside a circle, sized from its centre to a corner. Use it when the size across corners is known.", + "help.sketch.project": "Brings model edges, faces, vertices and curves of other sketches into this sketch, projected onto its plane. They stay linked and follow the model when it changes.", + "help.sketch.project_to_surface": "Projects curves of other sketches along this sketch's normal onto a face, as linked 3D curves. Use it to put a logo, split line or path onto a curved surface.", + "help.sketch.rectangle.center": "Draws a rectangle from its centre and one corner. Use it for outlines centred on a point, such as the origin.", + "help.sketch.rectangle.rounded": "Draws a rectangle with all four corners rounded to one radius. Use it for plates, lids and openings with rounded corners.", + "help.sketch.rectangle.three_point": "Draws a rectangle from one edge and a point on the opposite side. Use it for rectangles at an angle to the sketch axes.", + "help.sketch.rectangle.two_point": "Draws a rectangle from two opposite corners. Use it for the outlines of plates, blocks and pockets.", + "help.sketch.scale": "Scales sketch curves and points by a factor about a base point. Use it to resize part of a sketch without drawing it again.", + "help.sketch.slot.arc_center": "Draws a curved slot of a given width along an arc set by its centre, start and end. Use it for adjustment slots around a pivot.", + "help.sketch.slot.arc_three_point": "Draws a curved slot of a given width along an arc through three points. Use it when the slot's path has to pass through given points.", + "help.sketch.slot.center_point": "Draws a straight slot of a given width from its centre to the centre of one end arc. Use it for slots centred on a point.", + "help.sketch.slot.center_to_center": "Draws a straight slot of a given width between the centres of its two end arcs. Use it for slots dimensioned centre to centre, such as adjustment slots for screws.", + "help.sketch.slot.overall": "Draws a straight slot of a given width from one outer end to the other. Use it when the slot's overall length is what matters.", + "help.sketch.spline.control_point": "Draws a cubic spline shaped by control points that it does not pass through. Use it for smooth, flowing curves that you shape by moving the points.", + "help.sketch.spline.control_point_5": "Draws a degree 5 spline shaped by control points. Use it where curves have to join with smoother curvature, for example on visible styled surfaces.", + "help.sketch.spline.fit_point": "Draws a smooth spline that passes through every point you place, open or closed. Use it to trace a shape through known points.", + "help.sketch.spline3d": "Draws a smooth curve in space through points, with 3D Sketch on. Use it for sweep paths and cable runs that leave the sketch plane.", + "help.sketch.spun_profile": "Creates in the sketch plane the outline a body sweeps when it turns about an axis. Use it to get the silhouette of a turned part for a revolve or a drawing.", + "help.sketch.text": "Writes text in the sketch in a chosen font, height and angle; its words can follow parameters. Extrude or emboss it for labels and lettering.", + "help.sketch.transform": "Scales, turns and moves sketch geometry about a centre point in one step. Use it to reposition and resize a selection at once.", + "help.sketch.trim": "Removes the piece of a curve between the nearest crossings around where you click. Use it to clean up overlapping lines into a closed profile.", "help.solid.align": "Moves the selected bodies so that a point, face or plane on them meets a point, face or plane elsewhere. Use it to place a part against another one without measuring the offset.", + "help.solid.boundary_fill": "Makes solids from the regions enclosed by overlapping tool bodies, filling only the regions you pick. Use it to build a shape from the space that several bodies bound together.", + "help.solid.bounding_solid": "Creates a box that encloses the selected bodies, with an optional margin. Use it to see a part's overall size, or as the stock it is machined from.", + "help.solid.box": "Creates a box from a length, width and height, from a corner point or centred on a point. Use it for a quick block, a placeholder or a body to cut features into.", "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.coil": "Creates a helical body, such as a spring, from a diameter, turns, height or pitch and a round or square section. Use it for springs, coils and helical ridges.", "help.solid.combine": "Joins bodies, cuts them out of a target body, or keeps only the volume they share, and can keep the tool bodies. Use it to merge parts, to cut one shape with another or to find where two bodies overlap.", + "help.solid.cone": "Creates a cone from a base circle and a height, or a truncated cone when the top has a radius too. Use it for tapers, funnels, countersinks and points.", + "help.solid.cylinder": "Creates a cylinder from a radius or diameter and a height, standing on a point along an axis. Use it for shafts, pins, bosses and round blanks.", "help.solid.draft": "Tilts the selected faces by the angle you set, measured from a neutral plane. Use it on molded or cast parts so that they slide out of the mold.", + "help.solid.emboss": "Raises sketch profiles, such as text or a logo, out of a face, or sinks them into it. Use it for lettering, labels and markings on flat or round faces.", "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.", @@ -1457,20 +1772,61 @@ "help.solid.move": "Moves or rotates the selected bodies, or a copy of them, by the distance and angle you set. Use it to reposition a body or to make a second one in another place.", "help.solid.offset_face": "Pushes the selected faces in or out by the distance you set, and the faces around them follow. Use it to make a wall thicker, a pocket deeper or a boss taller without editing the sketch.", "help.solid.pattern.circular": "Repeats the selected objects around an axis, for the count and total angle you set. Use it for bolt circles, spokes, fins and teeth.", + "help.solid.pattern.path": "Copies features or bodies along a sketch path, by count and spacing. Use it for holes along a curved edge or parts along a rail.", "help.solid.pattern.rectangular": "Repeats the selected objects in one or two directions with the count and spacing you set. Use it for rows and grids of holes, ribs, pins or feet.", + "help.solid.pipe": "Creates a round tube along a path of sketch curves, solid or hollow with a wall thickness. Use it for tubes, wires, cables and rails.", "help.solid.press_pull": "Adds or removes material as you drag a face, or rounds edges as you drag them. Use it for quick changes straight on the model.", "help.solid.remove": "Takes the selected bodies out of the design from this point in the timeline on; earlier steps keep them. Use it to drop a helper body, such as a cutting tool you no longer need.", "help.solid.replace_face": "Moves the selected flat faces onto a plane or onto a parallel face, and the body grows or shrinks to meet it. Use it to bring a face flush with another part or a construction plane.", "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 center line.", + "help.solid.rib": "Adds a thin wall along an open sketch curve, filled out to the next faces of the body. Use it to stiffen walls and corners, for example in moulded or printed parts.", "help.solid.scale": "Makes the selected bodies larger or smaller by a factor, the same in every direction or one per axis. Use it to resize an imported shape or to allow for shrinkage.", "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.solid.sphere": "Creates a sphere from a radius or diameter around a centre point. Use it for balls, knobs and rounded ends.", "help.solid.split_body": "Cuts a body into separate bodies with a plane, the face of another body or a sketch line. Use it to make parts that are printed, machined or colored on their own.", "help.solid.split_face": "Divides the selected faces along a plane, the face of another body or sketch curves, without cutting the body. Use it to give part of a face its own draft, color or offset.", "help.solid.sweep": "Drags a sketch profile along a path to make a solid. Use it for pipes, rails, handles and any part of constant section that follows a curve.", + "help.solid.thread": "Adds an ISO metric thread to a cylindrical face, either as a cosmetic thread or cut into the body. Use it for bolts, threaded holes and printed screw parts.", + "help.solid.torus": "Creates a ring from a major radius around its axis and a minor radius for its round section. Use it for O-rings, handles and round beads.", + "help.solid.web": "Adds a thin wall along each open sketch curve, each filled out to the next faces of the body. Use it for a grid of supporting walls inside housings and trays.", + "help.surface.blend": "Creates a surface that bridges the edges of two bodies, tangent or curvature continuous to both. Use it to join two surfaces smoothly across a gap.", + "help.surface.boundary": "Creates a surface filling a loop of two to four sketch curves, or a network of curves. Use it for free-form panels defined by their edges.", + "help.surface.extend": "Lengthens a surface past its edges, by a distance or up to a plane or face. Use it so that surfaces overlap before you trim or stitch them.", + "help.surface.extrude": "Pushes sketch curves or profiles along a distance into a surface, walls only, without caps. Use it for thin walls and for cutting or splitting tools.", + "help.surface.fair": "Smooths the inside of free-form faces while their edges stay put. Use it to even out bumps and wavy reflections in a surface.", + "help.surface.loft": "Creates a surface that passes through two or more sections in order, without caps. Use it for shells and transitions between different shapes.", + "help.surface.match": "Rebuilds the edge of a surface so it meets another body's edge, with matching tangent or curvature. Use it to close a seam smoothly between two surfaces.", + "help.surface.offset": "Creates a copy of faces at a distance along their normals, as a new surface body. Use it for skins, clearances or the other side of a wall.", + "help.surface.patch": "Fills a sketch region or a closed loop of edges with a face, flat or smoothly curved. Use it to close holes in a surface body.", + "help.surface.reverse_normal": "Turns faces of a surface body over, so their outside faces the other way. Use it before thickening or stitching when the faces point inward.", + "help.surface.revolve": "Turns sketch curves or profiles about an axis into a surface, without caps. Use it for round shells such as lampshades, bowls and nozzles.", + "help.surface.ruled": "Creates a strip of straight lines out from a chain of edges, along the face's normal, tangent or at an angle. Use it for draft walls, run-offs and parting surfaces.", + "help.surface.stitch": "Sews surface bodies together along their shared edges, into a solid when they close. Use it to turn a set of surfaces into one body.", + "help.surface.sweep": "Moves sketch curves or profiles along a path into a surface, without caps. Use it for gutters, trims and other thin shapes that follow a path.", + "help.surface.thicken": "Gives a surface body a thickness, turning it into a solid. Use it to make printable or machinable parts from surfaces.", + "help.surface.trim": "Cuts a surface with a plane, another surface or sketch curves, and keeps the side you pick. Use it to cut surfaces to shape before stitching.", + "help.surface.unstitch": "Separates faces of a body into surface bodies of their own; a solid comes apart into surfaces. Use it to rework single faces of a body.", + "help.surface.untrim": "Removes holes from a face, or restores its outer boundary to the surface's natural bounds. Use it to get back the full surface after a trim.", "help.third_party": "Third-party licenses", "help.timeline.compute_all": "Rebuilds every feature in the timeline from the start. Use it to refresh the model and to see which features fail.", "help.timeline.delete": "Deletes the selected features from the timeline; deleting a sketch also deletes the features built from it. Use it to remove a step that is no longer wanted.", + "help.timeline.dependents": "Lists the features that would be deleted with a feature, and those that would fail without it. Use it before deleting or changing a feature.", "help.timeline.play": "Replay the remaining features one at a time, with a half-second pause after each rebuild. Run this command again or press Escape to stop; Go to end jumps immediately.", + "help.version": "Version {version}", + "help.view.apply": "Turns the view to a standard direction such as front, top or iso, or to a saved named view. Use it to look at the model from a fixed angle.", + "help.view.delete": "Deletes a saved named view. The model is not changed.", + "help.view.fit": "Zooms and pans so the whole model, or the selection, fills the view. Use it when the model has gone out of sight.", + "help.view.grid": "Shows or hides the grid in the viewport. Use it as a size and orientation guide while modelling.", + "help.view.ground_shadow": "Shows or hides the model's shadow on the ground. Use it to judge height and position more easily.", + "help.view.home": "Turns the view back to the home direction and fits the model. Use it to get back to a known view quickly.", + "help.view.list": "Lists the named views saved in the design. Use it to find a view you saved earlier.", + "help.view.navigate": "Turns, pans or zooms the view by steps, such as a quarter turn left. Use it to move the camera precisely instead of dragging.", + "help.view.navigation_bar": "Shows or hides the navigation bar at the bottom of the viewport. Hide it for more room, show it to reach the view tools by mouse.", + "help.view.rename": "Gives a saved named view a new name. The view itself stays the same.", + "help.view.save": "Saves the current camera position as a named view in the design. Use it to come back to the same angle later, for example for screenshots.", + "help.view.spin": "Orbits the view around the model continuously until the next click or key. Use it to present a model from all sides.", + "help.view.tool": "Latches a camera tool, orbit, pan or zoom, so that dragging with the left mouse button moves the view until you switch it off. Use it on a trackpad or without a middle mouse button.", + "help.view.visual_style": "Switches how the model is drawn: shaded with or without edges, wireframe, or with hidden edges. Use wireframe to see inside, shaded for a clean look.", "history.sketch_under_constrained": "Under constrained ({count} degrees of freedom)", "history.sketch_under_constrained_one": "Under constrained ({count} degree of freedom)", "hole_presets.confirm_delete": "Confirm delete", @@ -1544,6 +1900,27 @@ "home.start_hint": "Create a design, open a recent file, or explore a sample.", "home.whats_new": "What's new", "home.yesterday": "Yesterday", + "import_report.details": "Details:", + "import_report.file_one": "There was 1 other problem with the file.", + "import_report.file_other": "There were {count} other problems with the file.", + "import_report.hint": "Exporting these parts again from the program that made them may fix this. Copy Warning Message has the details.", + "import_report.left_out_one": "1 face couldn't be repaired and is missing.", + "import_report.left_out_other": "{count} faces couldn't be repaired and are missing.", + "import_report.needs_repair_one": "1 part needs repair before it can be modelled on.", + "import_report.needs_repair_other": "{count} parts need repair before they can be modelled on.", + "import_report.not_imported_one": "1 part couldn't be imported.", + "import_report.not_imported_other": "{count} parts couldn't be imported.", + "import_report.not_shown_one": "1 face couldn't be drawn and is hidden.", + "import_report.not_shown_other": "{count} faces couldn't be drawn and are hidden.", + "import_report.open_one": "1 part has gaps between its faces and came in as an open body.", + "import_report.open_other": "{count} parts have gaps between their faces and came in as open bodies.", + "import_report.refused_one": "1 part couldn't be made into a solid and was not imported.", + "import_report.refused_other": "{count} parts couldn't be made into solids and were not imported.", + "import_report.repaired_one": "Small flaws were repaired in 1 part.", + "import_report.repaired_other": "Small flaws were repaired in {count} parts.", + "import_report.solids": "Imported {solids} of {parts} parts as solids.", + "import_report.surfaces_one": "1 part couldn't be made into a solid and came in as surfaces.", + "import_report.surfaces_other": "{count} parts couldn't be made into solids and came in as surfaces.", "install.button_tip": "Install SolidCraft as an app: it opens in its own window and works offline", "install.dock_1": "Choose File › Add to Dock.", "install.dock_2": "Click Add.", @@ -1568,26 +1945,39 @@ "issue.note_save_failed": "Could not save screenshot: {error}", "issue.note_saved": "Screenshot saved. Attach the PNG in the GitHub draft.", "issue.save_screenshot": "Save screenshot…", + "joint.find_limits": "Find Limits", + "joint.find_limits_failed": "The search for the limits stopped with an error", + "joint.find_limits_hint": "Fill in the limits from where the parts this joint moves first touch another part, turning or sliding each way from where it is now. It runs on a copy: nothing changes until OK.", + "joint.find_limits_stale": "The joint or the design has changed since these limits were found: find them again", + "joint.finding_limits": "Finding limits…", "joint.from_bodies_hint": "Each picked body moves into a new component of its own and stays where it is.", + "joint.limit_contact": "{side} {value}: {a} touches {b}", + "joint.limit_limit": "{side} {value}: the limit of another value or joint", + "joint.limit_loop": "{side} {value}: a closed loop cannot close past it", + "joint.limit_range": "{side}: no contact within {range}, left as it was", + "joint.limit_turn": "{side} {value}: no contact within one turn", + "joint.limits_overlapping": "Already in each other here: {pairs}. They stop the search only if they go deeper.", "joint.one_body": "Both picks are on {body}. Pick the second one on another part.", "joint.one_component": "These parts are bodies of one component: {bodies}. A joint moves one component against another, so each part needs a component of its own.", "joint.rigid_group_one_component": "These {count} bodies are all in one component (or in the design itself): use {command} first.", "joint.rigid_group_select_components": "Select two or more components.", "joint_move.blocked_hint": "Check the joint type (such as Rigid), grounding, joint limits, and parameter-driven values.", "joint_move.blocked_title": "Cannot move this part", - "joint_move.coarse": "Near-axis rotation step (°)", + "joint_move.coarse": "Near-axis step", + "joint_move.conflict": "A joint of this part conflicts with the others: {joint}.", + "joint_move.conflict_hint": "Edit, suppress or delete the conflicting joint so the other joints can place the part.", "joint_move.distance": "Distance from start", "joint_move.done": "Done", - "joint_move.fine": "Far-axis rotation step (°)", + "joint_move.fine": "Far-axis step", "joint_move.fixed": "This part has no movable joint axis.", "joint_move.help": "Move — drag an arrow or ring. Esc cancels the current drag.", - "joint_move.legacy_hint": "Turn off to use the previous Move panel.", - "joint_move.precision": "Pull outside the dashed guide for fine rotation.", + "joint_move.legacy_hint": "Off: the previous Move panel.", + "joint_move.precision": "Pull outside the dashed guide for the fine step.", "joint_move.rotation": "Rotation from start", "joint_move.select": "Select a face or one assembly part, then choose Move.", "joint_move.settings": "Assembly Move", "joint_move.step": "Step", - "joint_move.use_handles": "Use joint motion handles for assembly Move", + "joint_move.use_handles": "Use joint motion handles for Move", "keymap.command_id": "Command ID", "keymap.empty": "No matching commands", "keymap.use_anyway": "Use {key} here anyway", @@ -1647,6 +2037,11 @@ "material.selection.mixed": "Different materials", "measure.at": "At", "measure.item": "Item {number}", + "measure.line_to_centre": "Line to center", + "measure.quick_copied": "Measurement copied", + "measure.quick_copy": "Click to copy the measurement", + "measure.quick_edges": "{count} edges", + "measure.quick_faces": "{count} faces", "messages.ago_h": "{n} h ago", "messages.ago_min": "{n} min ago", "messages.ago_s": "{n} s ago", @@ -1671,6 +2066,8 @@ "motion.track_name": "Track {number}", "nav.alias.help": "Shift+Alt+left drag orbits, Shift+Alt+middle pans, Shift+Alt+right zooms; middle drag also pans and right drag orbits", "nav.blender.help": "Middle drag orbits, Shift+middle pans, Ctrl+middle zooms; right drag leaves the camera alone", + "nav.creo.help": "Middle drag orbits, Shift+middle pans, Ctrl+middle drag vertically zooms (down to zoom in); scroll the wheel to zoom", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Mouse and 3D mouse rotate through both poles and preserve roll. Shift axis snapping is disabled.", "nav.free_orbit.label": "Free orbit", "nav.free_orbit.snap_help": "Mouse and 3D mouse rotate through both poles and preserve roll. Hold Shift during an orbit drag to snap the view direction and roll.", @@ -1680,6 +2077,7 @@ "nav.hfss.help": "Alt+left drag pans, Shift+Alt+left zooms, Ctrl+left drag on empty space orbits", "nav.inventor.help": "Middle drag pans, Shift+middle orbits, Ctrl+middle zooms, right drag orbits", "nav.maya.help": "Alt+left drag orbits, Alt+middle pans, Alt+right zooms; middle drag also pans", + "nav.nx.help": "Middle drag orbits, Shift+middle pans (NX's middle + right), Ctrl+middle zooms (NX's middle + left); right drag leaves the camera", "nav.openscad.help": "Left drag on empty space orbits, Shift+left drag box-selects, sketch geometry drags edit; right or middle drag pans, Shift+right or Shift+middle drag zooms", "nav.perspective.sketch": "Sketch editing uses orthographic view. Finish the sketch to switch perspective.", "nav.right_drag_orbits.help": "Off: a right drag leaves the camera alone and the right button only opens the context menu. Picking the SolidWorks mouse mapping turns it off.", @@ -1698,6 +2096,12 @@ "navbar.assistant": "Assistant", "navbar.custom.add_slot": "Add {slot}", "navbar.custom.always": "Always visible", + "navbar.custom.anchor.bottom_centre": "Bottom center", + "navbar.custom.anchor.bottom_left": "Bottom left", + "navbar.custom.anchor.bottom_right": "Bottom right", + "navbar.custom.anchor.top_centre": "Top center", + "navbar.custom.anchor.top_left": "Top left", + "navbar.custom.anchor.top_right": "Top right", "navbar.custom.available": "{available} · drag onto the bar, or press Add", "navbar.custom.buttons": "Buttons", "navbar.custom.compact": "Compact", @@ -1734,6 +2138,7 @@ "navbar.custom.reset_default": "Reset to default", "navbar.custom.right": "Move right", "navbar.custom.select": "No slot selected. Select a slot on the bar to move it, remove it or change how it looks.", + "navbar.custom.separator_hint": "A divider between groups of buttons. Drag it onto the bar, or press Add; use as many as you like.", "navbar.custom.separators_full": "The bar already has four separators.", "navbar.custom.show": "Show navigation bar", "navbar.custom.shows": "Shows", @@ -1799,6 +2204,11 @@ "not a move": "not a move", "not a number": "not a number", "open a sketch first": "open a sketch first", + "parameters.apply_live": "Apply each change as you leave its field", + "parameters.apply_live_tip": "Off: changes wait until Apply or OK, then the design rebuilds once for all of them. Cancel or Escape drops them.", + "parameters.held": "{count} changes waiting for Apply", + "parameters.held_hint": "Edit expressions and units. Changes wait for Apply or OK.", + "parameters.held_one": "1 change waiting for Apply", "parts.automatic_name": "automatic", "parts.dimension.across_flats": "Across flats", "parts.dimension.bore": "Bore", @@ -1817,10 +2227,19 @@ "parts.family.button_head_cap_screw": "Button head cap screw", "parts.family.dowel_pin": "Parallel pin (dowel)", "parts.family.hex_bolt": "Hex head bolt / screw", + "parts.family.hex_cap_screw_inch": "Hex cap screw (inch)", "parts.family.hex_nut": "Hex nut", + "parts.family.hex_nut_inch": "Hex nut (inch)", "parts.family.set_screw": "Hex socket set screw, flat point", "parts.family.socket_head_cap_screw": "Socket head cap screw", "parts.family.washer": "Plain washer", + "parts.family.washer_sae": "Plain washer, SAE (narrow)", + "parts.family.washer_uss": "Plain washer, USS (wide)", + "parts.holes": "Holes (optional)", + "parts.placement_hint": "pick one or more holes to seat a part in each, or OK places it at the origin", + "parts.system": "Unit system", + "parts.system.inch": "Inch", + "parts.system.metric": "Metric", "pattern.alignment_2": "Alignment 2", "pattern.alignment_hint": "Counts include the original. Center balances copies; Flip chooses the extra side for even totals.", "pattern.direction_1": "Direction 1", @@ -1859,20 +2278,52 @@ "prefs.alt_frees_manipulators": "Alt / Option also frees manipulator arrows", "prefs.anti_aliasing_amd_dx12": "Anti-aliasing uses 1× because the startup check drew nothing with multisampling and passed at 1×. You can choose another setting above; restart to apply it if the check passes.", "prefs.anti_aliasing_note": "Smooths jagged edges.", + "prefs.appearance.colour_vision_help": "Changes the colors that carry a meaning: sketch states, axes, bends, analyses and icons.", + "prefs.appearance.desktop_only": "Desktop only", + "prefs.appearance.follow_help": "Reloads when another tool rewrites the file.", + "prefs.appearance.interface_scale": "Interface scale", + "prefs.appearance.next_themes": "Next themes", + "prefs.appearance.option_count": "{count} options", + "prefs.appearance.option_count_one": "{count} option", + "prefs.appearance.previous_themes": "Previous themes", + "prefs.appearance.theme_count": "{count} themes", + "prefs.appearance.theme_own": "Theme's own", + "prefs.appearance.viewport_colours": "3D view colors", + "prefs.appearance.viewport_logo": "Viewport and logo", "prefs.applies_on_restart": "Applies on restart", "prefs.assistant": "Assistant", + "prefs.assistant_connecting": "Connecting", + "prefs.assistant_follow_help": "Look At sketches move the view with the pointer.", + "prefs.assistant_limit": "Limit", + "prefs.assistant_limited": "Limited", + "prefs.assistant_pointer_speed": "Pointer speed", + "prefs.assistant_seconds": "seconds", + "prefs.assistant_seconds_aria": "Seconds", + "prefs.assistant_use_care": "Use with care", "prefs.auto_operation": "Choose the operation automatically", - "prefs.auto_operation_note": "Feature windows pick Join, New Body or Cut from what the new material touches, until you pick one. Off: they keep the operation they open with.", + "prefs.auto_operation_note": "Join, New Body or Cut, from what the material touches.", "prefs.axes": "Axes", "prefs.axis": "Axis", + "prefs.blur_cost": "Relative rendering cost. More bars usually mean more work.", + "prefs.blur_device": "Unavailable on this graphics device or rendering path", + "prefs.blur_guard": "Blur quality was reduced to keep frames responsive. The radius is unchanged.", + "prefs.blur_off": "Off", + "prefs.blur_reduce_transparency": "Disabled by the system's Reduce transparency setting", + "prefs.blur_software": "Unavailable with software graphics (gpu-software)", + "prefs.blur_source": "Unavailable in this workspace view", + "prefs.blur_web": "Unavailable on this web rendering path", "prefs.bodies_folders": "Bodies folders", "prefs.bodies_folders_always": "Always", "prefs.bodies_folders_never": "Never", - "prefs.bodies_folders_several": "Several bodies only", + "prefs.bodies_folders_several": "Several", "prefs.bottom": "Bottom", "prefs.bottom_centre": "Bottom center", "prefs.bottom_right": "Bottom right", "prefs.browser": "Browser", + "prefs.browser_components_open": "Components start open", + "prefs.browser_components_open_note": "Every component in the browser starts open, as before, instead of closed until you open it.", + "prefs.browser_eye_left": "Eye beside the fold arrow", + "prefs.browser_eye_left_note": "Browser rows show their show/hide eye next to the fold arrow, as before, instead of in a column at the right end of the rows.", "prefs.browser_reveal_on_hover": "Reveal on hover", "prefs.browser_show_note": "Shown keeps the browser on screen. Reveal on hover keeps it out of sight until the pointer comes over its place or the thin tab at its left edge, and it stays open while the pointer is inside it or a menu from it is open.", "prefs.browser_shown": "Shown", @@ -1880,6 +2331,8 @@ "prefs.button_left": "Left drag", "prefs.button_middle": "Middle drag", "prefs.button_right": "Right drag", + "prefs.carousel_next": "Next", + "prefs.carousel_previous": "Previous", "prefs.choose_font": "Choose font file…", "prefs.click": "Click", "prefs.contact_shading": "Soft contact shading", @@ -1892,28 +2345,64 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Curved surfaces", "prefs.curves": "Curved surfaces", + "prefs.cut_preview_tint": "Show removed material in red", + "prefs.cut_preview_tint_help": "A preview fills the material a feature removes, and the shape it replaces, with a red see-through ghost. When off, those fills are fully transparent and only their outlines are drawn.", + "prefs.dark_parts_shading": "Keep the shape of dark parts", + "prefs.dark_parts_shading_help": "Shade the view in linear light with a soft sky fill, so dark faces keep a gradient instead of turning black", "prefs.dead_zone_note": "The hatched band is the dead zone: motion inside it is ignored.", "prefs.default": "default", - "prefs.design": "Design defaults", - "prefs.design_note": "What new designs start with. Open designs keep their own.", + "prefs.design": "Design", + "prefs.design_note": "What new designs start with.", + "prefs.design_tools.ask": "Ask", + "prefs.design_tools.degrees": "Degrees", + "prefs.design_tools.double_click_help": "Or to edit a linked one in place.", + "prefs.design_tools.ghost": "Show moved parts' old place as a ghost", + "prefs.design_tools.hole_moves_help": "Picking the face again moves the hole instead of removing it.", + "prefs.design_tools.hole_snaps_help": "The middle of a face and the centers of its round edges.", + "prefs.design_tools.imported_files": "Imported files", + "prefs.design_tools.note": "Note", + "prefs.design_tools.off": "Off", + "prefs.design_tools.placement_group": "Rest, Boss, Snap Fit", + "prefs.design_tools.rows": "Rows", "prefs.devices": "3D mouse", "prefs.dialog_buttons": "Dialog buttons", "prefs.dialogs": "Dialogs", "prefs.dialogs_edge": "At the view's edge", "prefs.dialogs_left_column": "In the left column", "prefs.dialogs_note": "Where command dialogs open: docked at the view's edge, or in the left column in place of the browser and the History, which come back as they were when the dialog closes.", + "prefs.dimension_step_angle": "What the window's arrows, Up/Down and the wheel add to an angle", + "prefs.dimension_step_length": "What the window's arrows, Up/Down and the wheel add to a length", + "prefs.dimension_steps": "Window steps", + "prefs.dimension_values": "Dimension values", + "prefs.dimension_values_note": "Where you type a dimension's value. A window has arrows that step it; the Dimension tool places the text first.", + "prefs.dimension_values_view": "In the view", + "prefs.dimension_values_window": "In a window", "prefs.display": "Display", "prefs.drawings": "Drawings", "prefs.edges": "Edges and shading", "prefs.extend": "Extend", "prefs.extra_navigation": "Ctrl+left drag on empty space orbits; hold Space to pan.", + "prefs.extrude_view_isometric": "Turn the view to isometric when Extrude opens", + "prefs.extrude_view_return": "Go back to the earlier view when Extrude closes", "prefs.follows_os": "Follows the OS", "prefs.font": "Font", "prefs.font_fallback": "Glyphs the chosen font lacks fall back to the built-in font, so no label shows an empty box.", "prefs.font_sample": "The quick brown fox · Ø12.50 mm · 45.0° · 0123456789", "prefs.font_unreadable": "The selected font could not be read.", "prefs.general": "General", - "prefs.general_note": "Language, saving and updates.", + "prefs.general.active": "Active", + "prefs.general.crash_reports": "Crash reports", + "prefs.general.edited": "Edited", + "prefs.general.held": "Held", + "prefs.general.import": "Import...", + "prefs.general.last_check": "Last checked: {time}", + "prefs.general.minutes": "Minutes", + "prefs.general.name_setup": "Name this setup", + "prefs.general.profile_name": "Profile name", + "prefs.general.save_new": "Save as new", + "prefs.general.step_import": "STEP and import", + "prefs.general.this_computer": "This computer", + "prefs.general_note": "Profiles, language, files and updates.", "prefs.gesture_orbit": "Orbit", "prefs.gesture_pan": "Pan", "prefs.gesture_zoom": "Zoom", @@ -1922,18 +2411,40 @@ "prefs.graphics_card_auto": "Automatic", "prefs.graphics_card_missing": "The saved graphics card is unavailable; Automatic is used.", "prefs.graphics_card_restart": "Takes effect after restarting SolidCraft. WGPU_ADAPTER_NAME overrides this choice.", + "prefs.graphics_card_unused": "The saved graphics card was not used for this window; the card in use is shown in Help › About and in the status line. Try Automatic, or set WGPU_ADAPTER_NAME to a unique part of the card's name.", "prefs.graphics_note": "Trade speed for smoothness. Each choice shows its effect on a sample.", + "prefs.graphics_page.current_view": "Current view", + "prefs.graphics_page.fastest": "Fastest", + "prefs.graphics_page.fold_items": "Fold items", + "prefs.graphics_page.in_view": "In the view", + "prefs.graphics_page.live_details": "Live details", + "prefs.graphics_page.own_mix": "Your own mix", + "prefs.graphics_page.quick_measure": "Quick measurement", + "prefs.graphics_page.reference_geometry_through_bodies": "Reference geometry through bodies", + "prefs.graphics_page.restart": "Restart needed", + "prefs.graphics_page.sharpest": "Sharpest", + "prefs.graphics_page.single_surface_analysis": "Single surface analysis", + "prefs.graphics_page.status_chips": "Status chips", + "prefs.graphics_page.subtitle": "Trade speed for smoothness.", + "prefs.graphics_page.supersampling": "Supersampling", + "prefs.graphics_page.supersampling_adaptive": "Only while the view is still", + "prefs.graphics_page.surfaces_edges": "Surfaces and edges", + "prefs.graphics_page.view_bar": "Also in the view bar", "prefs.graphics_presets_note": "Presets set the choices below together.", + "prefs.hide_constraint_glyphs_zoomed_out": "Hide constraint glyphs when zoomed out", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Constraint glyphs leave the view when the sketch is zoomed out far enough that they would clutter it. Off: they stay at a fixed screen size at every zoom.", "prefs.history": "History", "prefs.history_origin_bodies": "Show origin and bodies at the top", "prefs.history_origin_bodies_note": "The History on the left or under the browser starts with the active component's Bodies folder and the Origin, with their eyes and menus as in the browser. The History at the bottom is unchanged.", "prefs.history_play_button": "Play History button in the History controls", "prefs.history_play_button_note": "Puts Play History between Go back one step and Go forward one step in the History controls. You can also right-click the controls to show or hide it.", - "prefs.history_sketches": "Sketches", + "prefs.history_sketches": "Sketches in History", "prefs.history_sketches_in_order": "In order", "prefs.history_sketches_note": "With Sketches set to Under their feature, the History at the left lists each sketch one level in, under the first feature built from it, whenever it is wide enough for names. The timeline at the bottom always keeps the creation order.", "prefs.history_sketches_under_feature": "Under their feature", "prefs.hold_stop_snapping": "Hold to stop snapping", + "prefs.home_fit_size": "Home and Fit size", + "prefs.home_fit_size_note": "How much of the view the model fills when Home, Fit, an opened design or a navigator view change frames it, whether or not the setting below is on. 100 %: fills the view between the panels, the compass and the navigation bar.", "prefs.icons_only": "Icons only", "prefs.imported_file": "Imported file", "prefs.in_browser": "In browser", @@ -1942,13 +2453,38 @@ "prefs.interface_language": "Interface language", "prefs.interface_note": "How SolidCraft looks and where its parts sit.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Invert the curved roll arrows", + "prefs.invert_curved_roll_arrows_note": "The two curved arrows at the cube's corner roll the view within the screen plane. On: the clockwise arrow rolls counterclockwise and the counterclockwise arrow rolls clockwise. Off: each arrow rolls the view the way it curls.", + "prefs.invert_navigator_arrows": "Invert the view cube rotation arrows", + "prefs.invert_navigator_arrows_note": "The arrows around the cube orbit the camera the way they point, as in Fusion and Inventor: the arrow on the left points right and swings the camera right. Off: an arrow rotates the cube toward the side it sits on, so the left arrow swings the camera left. The curved roll arrows are not affected.", + "prefs.keep_work_on_tab_switch": "Keep dialogs and tools open when switching designs", + "prefs.keep_work_on_tab_switch_note": "Each design tab keeps its open dialog or tool, with what you picked and typed in it, and its toolbar tab. They are there again when you come back to the design. Off: switching designs cancels them and shows the Model tab.", "prefs.labels": "Labels", + "prefs.language_system": "System", "prefs.layout": "Layout", "prefs.layout_note": "Compact docks panels to the window edges. Browser translucency is available in Floating. Change the Assistant side on the Assistant page.", + "prefs.layout_page.active_commands": "Highlight active commands", + "prefs.layout_page.always": "Always", + "prefs.layout_page.card": "Card", + "prefs.layout_page.column": "Column", + "prefs.layout_page.hover": "Hover", + "prefs.layout_page.icons_labels": "Icons + labels", + "prefs.layout_page.ok_cancel": "OK and Cancel", + "prefs.layout_page.on_hover": "On hover", + "prefs.layout_page.open": "Open", + "prefs.layout_page.origin_bodies": "Origin and bodies on top", + "prefs.layout_page.panels": "Panels", + "prefs.layout_page.pinned_menus": "Pinned commands out of menus", + "prefs.layout_page.play_history": "Play History button", + "prefs.layout_page.slot_count": "{count} of {max} slots", + "prefs.layout_page.view_corner": "Also in the view's corner", + "prefs.layout_page.window": "Window", "prefs.left": "Left", "prefs.left_click": "Left click", "prefs.line_drag_draws_one": "Press and drag draws one line", "prefs.line_drag_draws_one_note": "In the Line tool, pressing, dragging and letting go draws one line from the press to the release, and it ends there. Clicks still draw a chain. Off: a drag places a point where it is let go, as a click does.", + "prefs.line_hover_tangent_arc": "Rest on a line's last point to switch to a tangent arc", + "prefs.line_hover_tangent_arc_note": "In the Line tool, once a segment is drawn, move away from the chain's last point, come back and hold the pointer still on it: the next click ends a tangent arc, and the same gesture goes back to lines. Off: resting there does nothing.", "prefs.linked_designs": "Linked designs", "prefs.live_input": "Live input", "prefs.live_preview": "Live preview", @@ -1956,10 +2492,10 @@ "prefs.logo_accent": "Accent", "prefs.logo_theme": "Theme's colors", "prefs.max_file_size": "Largest file to open", - "prefs.max_file_size_design": "Design files", + "prefs.max_file_size_design": "Largest file to open: Design", "prefs.max_file_size_flag": "This run started with --max-file-size {size}, which applies until SolidCraft closes. These settings apply when it starts without it.", "prefs.max_file_size_note": "Defaults: 512 MB and 256 MB; at most 16 GB. Opening a file takes several times its size in memory. A design that keeps a large import may need a higher design file limit to save and reopen.", - "prefs.max_file_size_step": "STEP and import files", + "prefs.max_file_size_step": "Largest file to open: STEP and import", "prefs.max_file_size_web": "The web app opens STEP and import files up to 512 MB and designs up to 256 MB: a browser tab can't hold larger files. The desktop app can raise these limits.", "prefs.megabytes": "MB", "prefs.menu_grid": "Large icons", @@ -1971,10 +2507,19 @@ "prefs.mouse_heading": "Mouse", "prefs.mouse_mapping": "Mouse mapping", "prefs.navigation": "Navigation", + "prefs.navigation.axes_signed": "Axes", + "prefs.navigation.cube_compact": "Cube", + "prefs.navigation.device": "Device", + "prefs.navigation.free": "Free", + "prefs.navigation.orbit_style": "Orbit style", + "prefs.navigation.radial_help": "Hold or flick the right button for a ring of tools.", + "prefs.navigation.turntable": "Turntable", "prefs.navigation_note": "How the mouse, trackpad and 3D mouse move the view.", + "prefs.navigator_fit": "Fit the model after a navigator view change", + "prefs.navigator_fit_note": "A face, corner or arrow of the view cube, or an axis of the gizmo, also looks at the middle of the model from the one distance that fits it from every side (its bounding sphere). Home uses the same zoom and centre while this is on, so views chosen after it only turn. Off: the view turns in place, keeping its target and zoom.", "prefs.network_host_remove": "Remove", "prefs.network_locations": "Allow network locations in designs", - "prefs.network_locations_note": "Off: a design's linked files on another computer (\\\\server\\share) are opened only from the servers listed here, or after you allow one when asked.", + "prefs.network_locations_note": "For organizations that keep designs on file servers. Off: only servers you allow.", "prefs.network_locations_section": "Network locations", "prefs.not_on_gpu": "not on this GPU", "prefs.on": "On", @@ -1984,20 +2529,32 @@ "prefs.origin_plane_names": "Origin plane names", "prefs.origin_plane_names_note": "Names shown in the browser, dialogs and lists. {top} is XY, {front} is XZ and {right} is YZ, with Z up. Commands, scripts and saved designs keep XY, XZ and YZ.", "prefs.overall_speed": "Overall speed", + "prefs.parameter_list_rows": "Parameter list rows", + "prefs.parameter_list_rows_tip": "The most parameters Down arrow lists in an empty expression box.", "prefs.persistent_ribbon_pressed": "Highlight active ribbon commands", "prefs.persistent_ribbon_pressed_help": "Highlight ribbon commands while their effects are on. Turn off to keep the previous neutral appearance and command help.", "prefs.perspective_fov": "Field of view", "prefs.placement": "Placement", + "prefs.plugins_enabled": "Enabled", + "prefs.plugins_installed": "Installed", + "prefs.plugins_intro": "Sandboxed add-ons.", + "prefs.plugins_show_folder": "Show plugins folder", "prefs.prefer_free_sketch_points": "Prefer movable sketch points when points overlap", "prefs.preview_choices": "Preview of your choices", + "prefs.preview_tint_new_faces": "Tint new surface in a preview", + "prefs.preview_tint_new_faces_help": "A preview of a feature that changes a body can draw the surface it adds in the preview colour. When off, the body is drawn as itself.", + "prefs.print_face_highlight": "Print face highlight", + "prefs.print_face_highlight_tip": "How strongly the print face of a body is tinted and outlined in the view. 0 % shows no highlight.", "prefs.profile_active": "Active profile", "prefs.profile_applied": "Profile applied.", "prefs.profile_changed": "Settings changed since the profile was saved. Save keeps them in it.", "prefs.profile_deleted": "Profile deleted.", - "prefs.profile_export": "Export…", + "prefs.profile_export": "Export", "prefs.profile_exported": "Profile exported.", - "prefs.profile_imported": "Profile imported. Choose it under Active profile to switch to it.", + "prefs.profile_imported": "Profile imported.", "prefs.profile_name_hint": "Profile name, e.g. Laptop", + "prefs.profile_operations": "Profile operations", + "prefs.profile_operations_note": "Records how long SMLib calls, kernel operations, features, commands and imports take. Agents read it with diagnostics.profile.", "prefs.profile_rename": "Rename", "prefs.profile_renamed": "Profile renamed.", "prefs.profile_save": "Save", @@ -2011,26 +2568,71 @@ "prefs.quality_fastest": "fastest", "prefs.quality_slowest": "slowest", "prefs.quality_smoother": "smoother", + "prefs.quick_measure": "Quick measurement in the view's corner", + "prefs.quick_measure_note": "The selection's size in the view's bottom right corner: an edge's length, or Ø and R for a round one, a face's area, a point's position, two items' distance and angle, several edges' or faces' total. A click copies it.", "prefs.render_previous_geometry_budget": "Use previous Render preview geometry budget", "prefs.render_previous_geometry_budget_help": "Restore the previous fixed geometry limit (512 MiB on 64-bit desktop, 128 MiB elsewhere) instead of the device-based budget.", "prefs.reports_saved": "{n} saved", + "prefs.restore_page_defaults": "Restore page defaults", + "prefs.ribbon_click_ends_tool": "Clicking the running tool's button ends it", + "prefs.ribbon_click_ends_tool_note": "A click on the lit ribbon button of the sketch tool in use ends the tool, so clicks in the view select again. Off: the click starts the tool again.", "prefs.ribbon_reveal": "Show search results in the ribbon", "prefs.ribbon_reveal_note": "Hovering a result in Search commands shows where the command sits in the ribbon: its tab, its button or its row in a panel's drop-down. A command started from the search blinks there, and a running command from a drop-down marks its panel.", "prefs.right_click": "Right click", - "prefs.saving": "Autosave and recovery", + "prefs.saving": "Start and save", "prefs.scale_note": "Also Ctrl + / Ctrl − in the window. Buttons are 28 px at 100%.", "prefs.scale_text": "Scale and text", "prefs.search": "Search preferences", "prefs.search_empty": "No matching preferences", + "prefs.section_hatch": "Section hatch", + "prefs.section_hatch_by_part": "By part", + "prefs.section_hatch_one": "One style", "prefs.select": "Select", "prefs.select_one_item": "Select one item", + "prefs.select_other_hidden": "Select hidden geometry with Select Other", + "prefs.select_other_hidden_help": "On: include hidden bodies, sketches and occluded edges near the pointer. Off: use the original list of visible geometry under the pointer.", "prefs.selecting": "Selecting", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift adds only; Ctrl / Cmd toggles", "prefs.shift_add_note": "On: Shift adds, Ctrl / Cmd toggles. Off (default): both toggle.", "prefs.shortcuts": "Shortcuts", + "prefs.shortcuts_import": "Import", + "prefs.shortcuts_intro": "Keys for each command.", + "prefs.shortcuts_not_assigned": "Not assigned", + "prefs.shortcuts_press": "Press a key...", "prefs.single_surface_analysis": "Use a single surface analysis", "prefs.single_surface_analysis_help": "When off, surface shading and Continuity can stay on together. Turning this on keeps the last analysis started or changed.", + "prefs.sketch.align_points": "Line up with other sketch points", + "prefs.sketch.align_points_note": "Drawing lines align with points on both axes at once.", + "prefs.sketch.auto_dimensions": "Dimension new shapes fully", + "prefs.sketch.auto_dimensions_note": "Typed values plus every dimension that fixes the shape.", + "prefs.sketch.auto_locate": "Place from the sketch origin", + "prefs.sketch.auto_locate_note": "With full dimensions.", + "prefs.sketch.center_arc": "Center-point arc follows the cursor", + "prefs.sketch.click_selects": "Click selects", + "prefs.sketch.conflict_colour": "Conflict color", + "prefs.sketch.drawing": "Drawing", + "prefs.sketch.exit_keep": "Keep", + "prefs.sketch.exit_previous": "Return to the view before", + "prefs.sketch.exit_unless_rotated": "Unless turned", + "prefs.sketch.faces_edges": "Faces and edges", + "prefs.sketch.hide_glyphs": "Hide glyphs zoomed out", + "prefs.sketch.marks": "Marks in the sketch", + "prefs.sketch.note": "Drawing, snapping and selecting.", + "prefs.sketch.opening_closing": "Opening and closing", + "prefs.sketch.prefer_free_points": "Prefer movable points where they overlap", + "prefs.sketch.project_options": "Ask for Project options first", + "prefs.sketch.recent_snap": "Snap to where two guides cross", + "prefs.sketch.select_other_hidden": "Select Other reaches hidden geometry", + "prefs.sketch.shortcut_cycles_modes": "Shortcut again switches mode", + "prefs.sketch.shortcut_cycles_modes_tip": "Off: it starts the tool again.", + "prefs.sketch.snapping_guides": "Snapping and guides", + "prefs.sketch.state_icons": "State icons", + "prefs.sketch.tracking_guides": "Center and midpoint guides", + "prefs.sketch.tracking_guides_note": "Temporary horizontal and vertical guides from hovered centers and edge midpoints.", + "prefs.sketch.tracking_points": "Guides from sketch points too", + "prefs.sketch.unless_turned_note": "return if not rotated", + "prefs.sketch.whole_bodies": "Whole bodies", "prefs.sketch_align_points": "Line up with other sketch points while drawing", "prefs.sketch_align_points_note": "While drawing, a point lines up horizontally with one sketch point and vertically with another at the same time, with a dotted guide, and the click keeps both alignments. Off: only with the previous point, one axis at a time.", "prefs.sketch_conflict_colour": "Conflicting geometry in the conflict color", @@ -2041,6 +2643,8 @@ "prefs.sketch_exit_view.previous": "Return to the previous view", "prefs.sketch_exit_view.unless_rotated": "Return unless rotated", "prefs.sketch_exit_view_note": "Where the view goes after Finish Sketch, Cancel or a double Esc.", + "prefs.sketch_face_activates_part": "Sketching on a part's face makes that part active", + "prefs.sketch_face_activates_part_note": "A sketch started on a face of another component's body activates that component first, so the sketch belongs to it and stays with that part in the browser. The part stays active afterwards. Off: the sketch belongs to the active component.", "prefs.sketch_open_look_at": "Turn to face a sketch when it opens", "prefs.sketch_open_look_at_note": "Off: creating or editing a sketch leaves the view as it is. Look At faces the sketch when you want it.", "prefs.sketch_recent_snap": "Auto snap to recent centers and midpoints", @@ -2054,22 +2658,42 @@ "prefs.sketch_tab_always_note": "The Sketch tab stays in the ribbon, right after Model, while no sketch is open. Its drawing tools then start a sketch on the selected plane or face, or on the plane you pick next, with the tool ready in it.", "prefs.sketch_tracking_guides": "Center and midpoint alignment guides", "prefs.sketch_tracking_guides_note": "Hover over a circle center or straight-edge midpoint, then move horizontally or vertically to show a temporary dotted guide.", + "prefs.sketch_tracking_points": "Alignment guides from end points and corners while drawing", + "prefs.sketch_tracking_points_note": "While a drawing tool waits for a point, hovering a line or arc end, a rectangle corner or a free point shows the same temporary dotted guide as a center or midpoint. Off: only centers and midpoints.", "prefs.sketching": "Sketching", "prefs.snap_drawing_note": "While drawing or dragging a sketch point.", "prefs.source": "Source", "prefs.speed": "Speed", "prefs.stand_up_note": "After a STEP or IGES file opens with Z up, offer a quarter turn about X.", - "prefs.stand_up_unknown": "For files from unknown programs", + "prefs.stand_up_unknown": "Files from unknown programs", "prefs.stand_up_unknown.ask": "Ask in a dialog", "prefs.stand_up_unknown.note": "Show a note", "prefs.stand_up_unknown.off": "Don't offer", - "prefs.stand_up_unknown_note": "How the offer is made when the file's header names no program known to save Y up. A note is shown only when the file seems to lie on its back; Ask in a dialog asks about every such file, as before.", + "prefs.stand_up_unknown_note": "How the offer is made when the file names no known program.", "prefs.status_bar": "Status bar", "prefs.status_bar_note": "A thin bar along the window's bottom edge shows what is being edited, the open sketch's state in its color and the design's units; a click on the units changes them. The sketch's state then no longer shows in the view's corner.", "prefs.status_done": "Done", "prefs.status_error": "Error", "prefs.status_selected": "Selected", "prefs.status_warning": "Warning", + "prefs.structure.appearance": "Appearance", + "prefs.structure.appearance_note": "Colors, text and accessibility.", + "prefs.structure.in_profile": "In profile", + "prefs.structure.layout": "Layout", + "prefs.structure.layout_note": "Where the parts of the window sit.", + "prefs.structure.look": "Look", + "prefs.structure.measure_pointer": "Measure and pointer", + "prefs.structure.mouse3d": "3D mouse", + "prefs.structure.mouse3d_note": "SpaceMouse and SpaceNavigator.", + "prefs.structure.navigation_note": "Mouse and trackpad. The 3D mouse has its own page.", + "prefs.structure.profile": "Profile", + "prefs.structure.profile_edited": "Changed since saved", + "prefs.structure.profile_hover": "Saved in settings profiles", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Sketch", + "prefs.structure.tools": "Tools", + "prefs.structure.tools_note": "How modeling tools behave.", + "prefs.structure.work": "Work", "prefs.supersampling_brief": "Draws the view larger and filters it down: very crisp, and heavier.", "prefs.tab_accent_note": "The accent follows the active tab", "prefs.theme_file": "theme file", @@ -2081,6 +2705,21 @@ "prefs.theme_follow_off": "Off", "prefs.theme_follow_stop": "Stop following", "prefs.theme_import_hint": "Click to choose a theme file, drop one here, or press Ctrl+V (Cmd+V on a Mac) with a theme copied", + "prefs.theme_notice_dismiss": "Dismiss", + "prefs.theme_option_blur": "Blur behind panels", + "prefs.theme_option_blur_help": "Blur behind translucent panels, in physical pixels. Zero is off.", + "prefs.theme_option_invalid": "Saved value for {option} is invalid; using the theme default. The saved value is kept.", + "prefs.theme_option_opacity": "Opacity", + "prefs.theme_option_opacity_help": "Adjust floating panel opacity. A readability floor protects text over viewport colors.", + "prefs.theme_option_tab_colours": "Tab colors", + "prefs.theme_option_tab_colours_help": "Use this theme’s panel and viewport colors for each ribbon tab.", + "prefs.theme_option_tab_fade_ms": "Tab transition", + "prefs.theme_option_tab_fade_ms_help": "Fade panel and viewport colors when switching tabs. Zero switches instantly.", + "prefs.theme_options_badge": "Options", + "prefs.theme_options_more": "More · {count}", + "prefs.theme_options_newer": "This theme requires a newer SolidCraft. Upgrade, then reimport the original theme to recover its option definitions.", + "prefs.theme_options_reset": "Reset", + "prefs.theme_options_unavailable": "Unavailable on this device", "prefs.theme_paste": "Paste theme", "prefs.theme_paste_none": "The clipboard holds no SolidCraft theme", "prefs.timeline_half_hour": "−30 min", @@ -2102,13 +2741,29 @@ "prefs.under_cursor": "Under cursor", "prefs.units_precision": "Units and precision", "prefs.updates": "Updates", + "prefs.validation": "Body check", + "prefs.validation.each_feature": "Once per feature", + "prefs.validation.each_step": "After every step", + "prefs.validation.label": "Full kernel check", + "prefs.validation.off": "Off (experimental)", + "prefs.validation_note": "After every step: checks each sweep, boolean and blend.\nOnce per feature: checks each feature's result once.\nOff (experimental): no check.", + "prefs.value_boxes_in_view": "Show values beside their handles", + "prefs.value_boxes_in_view_tip": "Extrude's Distance, Fillet's Radius... as a box in the view.", "prefs.view": "View behavior", "prefs.view_confirm_corner": "OK and Cancel in the view's corner", "prefs.view_confirm_corner_note": "While a dialog or a sketch is open, a check and a cross at the top right of the view do what the dialog's OK and Cancel do, or finish and cancel the sketch. The view navigator moves down below them.", "prefs.viewport": "Viewport", + "prefs.viewport_analysis_status": "Show viewport analysis status", + "prefs.viewport_analysis_status_help": "Show active analyses above the viewport, open their legends from each item, and use Esc to turn off the newest analysis. Turn off to restore corner legends and the previous Esc behaviour.", "prefs.viewport_background": "Background", "prefs.viewport_background_colour": "Color", "prefs.viewport_background_theme": "Theme's gradient", + "prefs.viewport_section_status": "Show viewport section status", + "prefs.viewport_section_status_help": "Show the section setting in the viewport. Escape and the active ribbon button turn it off. Disable to keep the previous section controls.", + "prefs.viewport_status_details": "Live viewport details", + "prefs.viewport_status_details_help": "Edit active analysis and section settings in standard details cards. Disable to restore read-only analysis keys and the Section dialog.", + "prefs.viewport_status_summary": "Fold viewport status items", + "prefs.viewport_status_summary_help": "Fold three or more viewport status items into one summary badge. Disable to keep every item in the full row.", "prefs.wheel": "Wheel", "prefs.wheel_trackpad": "Wheel and trackpad", "prefs.workspace": "Workspace", @@ -2126,6 +2781,17 @@ "recovery.just_now": "just now", "recovery.min_ago": "{count} min ago", "recovery.never_saved": "never saved", + "refused.change": "Couldn't change {body}.", + "refused.cut": "Couldn't cut {body}.", + "refused.face_curved": "One of its curved faces can't be used for modelling.", + "refused.face_flat": "One of its flat faces can't be used for modelling.", + "refused.face_freeform": "One of its freeform faces can't be used for modelling.", + "refused.face_rounded": "One of its rounded faces can't be used for modelling.", + "refused.faces_apart": "Its faces don't meet closely enough to be used for modelling.", + "refused.intersect": "Couldn't intersect with {body}.", + "refused.join": "Couldn't join to {body}.", + "refused.repair": "Repair part", + "refused.show_face": "Show face", "render.adaptive_absolute": "Absolute RGB error floor", "render.adaptive_coverage": "Coverage error target", "render.adaptive_enable": "Allocate samples with independent pilots", @@ -2237,6 +2903,10 @@ "render.base_color": "Base color · sRGB", "render.base_metallic": "Metallic fraction", "render.base_opaque_only": "This editor preserves opaque body semantics. Use the explicit glass controls for optical transmission.", + "render.batch_all_shots": "All shots ({count})", + "render.batch_empty": "Save a shot before rendering all shots.", + "render.batch_limit": "Render all shots is limited to 32 shots.", + "render.batch_status": "{running} running · {waiting} waiting", "render.bloom_enable": "Display bloom", "render.bloom_help": "Creative output-only glow from positive linear highlights, spread with three normalized box passes. Radius is in output pixels. Added in linear display light before sRGB; not a lens, volumetric effect or convergence improvement. The raw EXR is unchanged.", "render.bloom_opaque": "Bloom requires opaque output. Transparent PNG is refused, not silently flattened.", @@ -2347,6 +3017,13 @@ "render.choose_look": "Choose a look in Appearances first", "render.chromatic_offset": "Chromatic edge offset", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "Comparison divider", + "render.compare_live": "Live", + "render.compare_live_preview": "Live preview", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · captured at revision {revision}", + "render.compare_swap": "Swap", "render.copy_request": "Copy JSON", "render.cpu_aa_help": "Spatial samples: more samples improve edges and increase render time.", "render.cpu_area_add": "Add rectangular CPU light", @@ -2987,7 +3664,9 @@ "render.output_ready": "Ready to render", "render.output_run_check": "Run check", "render.output_size_limit": "{method}: up to {dimension} px per side and {pixels} pixels. Largest fitting size: {width} × {height}.", + "render.output_size_method_profile": "To render {width} × {height}, choose {method} with the {profile} CPU resource profile, or a smaller size.", "render.output_size_ok": "Size OK · {width} × {height} px", + "render.output_size_profile": "To render {width} × {height}, choose the {profile} CPU resource profile, or a smaller size.", "render.output_swap_orientation": "Swap width and height", "render.output_tools_inspector": "Edit size and format in the Output inspector.", "render.output_view_image": "View image", @@ -3094,6 +3773,10 @@ "render.result_retained": "Showing the last completed image; a newer render has not replaced it.", "render.result_sequence": "Checkpoint", "render.result_title": "Render Result", + "render.results_choose": "Retained results", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [stale]", + "render.results_unnamed": "Image", "render.return_design": "Return to Design", "render.review_stale": "This review is stale. Resolve or check again before applying.", "render.ribbon_aging": "Aging", @@ -3200,6 +3883,7 @@ "render.size_custom": "Custom…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · needs {profile}", "render.size_presets": "Size presets", "render.size_presets_pending": "Arrives with the Output editor", "render.size_preview": "Preview", @@ -3465,11 +4149,11 @@ "select two components": "select two components", "set by the sketch's lines": "set by the sketch's lines", "settings.display_quality_note": "Only the display. Designs and exports are not affected.", - "settings.double_click_components": "Double-click a component to activate it, or to edit a linked one in place", + "settings.double_click_components": "Double-click a component to activate it", "settings.frame_rate_details_note": "Adds a graph of the last frames' times with the triangles drawn over it, a histogram of frame times and what the GPU drew. Click the frame rate in the view to show or hide them.", "settings.frame_rate_note": "Shows frames per second in the view's bottom-right corner.", - "settings.insert_lists_open_designs": "Insert Design lists the designs open in other tabs first", - "settings.measure_axis_distances": "Show X/Y/Z distances", + "settings.insert_lists_open_designs": "Insert Design lists open designs first", + "settings.measure_axis_distances": "Axis distances in Measure", "settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.", "settings.msaa_applies_on_restart": "Anti-aliasing applies the next time SolidCraft starts", "settings.msaa_reset": "{setting}: {requested}× isn't supported by this graphics device; it is now {reset}× (supported: {supported}).", @@ -3479,7 +4163,7 @@ "settings.reset_intro": "These settings don't work on this computer and would keep SolidCraft from starting, so they were changed:", "settings.reset_title": "Settings were changed", "settings.supersampling_note": "Draws the view at a higher resolution and filters it down: smoother edges, lines and grid on screens below 4K. It costs GPU time: about 2.25× the pixels at 1.5× and 4× at 2×.", - "settings.update_changed_links": "Update changed linked designs when a tab comes back", + "settings.update_changed_links": "Update changed links when a tab comes back", "settings.window_system_details": "Details", "settings.window_system_note_now": "Applies after a restart. Now: {now}.", "settings.window_system_wayland_limited": "Some features are limited on native Wayland.", @@ -3487,6 +4171,24 @@ "sheet.flange_type_contour": "Contour", "sheet.flange_type_edge": "Edge", "sheet.no_body": "there is no sheet metal body: start one with Flange > Base, or turn a plate into sheet metal with Convert to Sheet Metal (pick its large flat face)", + "sheet.personal_rules.confirm_delete": "Confirm delete", + "sheet.personal_rules.delete": "Delete", + "sheet.personal_rules.delete_prompt": "Delete this personal rule? Rules already in designs are unchanged.", + "sheet.personal_rules.full": "The personal library already contains 64 rules.", + "sheet.personal_rules.invalid_name": "Enter a short name without line breaks or control characters.", + "sheet.personal_rules.invalid_values": "Complete the rule's values: each must work out in this design, with a positive thickness and a K factor from 0 to 1.", + "sheet.personal_rules.missing": "The selected personal rule is no longer available.", + "sheet.personal_rules.name": "Rule name", + "sheet.personal_rules.name_exists": "A personal rule with this name already exists. Use a different name.", + "sheet.personal_rules.name_hint": "A unique name", + "sheet.personal_rules.overwrite": "Save changes to selected personal rule", + "sheet.personal_rules.rename": "Rename", + "sheet.personal_rules.rule": "Personal rule", + "sheet.personal_rules.save": "Save new", + "sheet.personal_rules.scope": "Saved in your profile for all designs.", + "sheet.personal_rules.select": "Select a rule", + "sheet.personal_rules.title": "Personal rules", + "sheet.personal_rules.unsupported": "This rule has values that this version can't use.", "shortcut.json_error": "parameters must be JSON: {error}", "shortcut.no_command": "no command `{id}`; the text before the JSON must be a command id", "shortcut.pin": "Pin to the top of the S box", @@ -3523,8 +4225,10 @@ "sketch_text.align_right": "Right", "sketch_text.bold": "Bold", "sketch_text.builtin_font": "{family} (built-in)", + "sketch_text.formula": "Start with = to build the words from parameters: ='W' + number(Width)", "sketch_text.italic": "Italic", "sketch_text.loading_fonts": "Looking for installed fonts…", + "sketch_text.no_bold": "The built-in font has no bold face: choose an installed font", "sketch_text.on_path": "The text follows its path: the curve places it", "sketch_text.path_clear": "Take the text off its curve", "sketch_text.path_hint": "A curve of the sketch the text follows: click here, then the curve", @@ -3555,11 +4259,20 @@ "the section's profiles must be in one sketch": "the section's profiles must be in one sketch", "the two origins are on the same component": "the two origins are on the same component", "thread.automatic_size": "Automatic size", + "thread.chamfer_depth_needed": "required for this form", "thread.designation": "Designation", - "thread.direction": "Thread direction", + "thread.drill_range": "The tap maker's drill is {drill} mm. The internal thread's standard minor diameter is {minor} mm. A drill from {low} to {high} mm is accepted.", + "thread.drill_range_custom": "The drill is the major diameter less the pitch, {drill} mm. The internal thread's standard minor diameter is {minor} mm. A drill from {low} to {high} mm is accepted.", + "thread.drill_range_taper": "The tap maker's drill is {drill} mm. The standard's minor diameter where the thread ends is {minor} mm. A drill from {low} to {high} mm is accepted.", + "thread.end_square": "Square", + "thread.fade_short": "1.25 P (ISO 3508)", + "thread.fade_standard": "2.5 P (ISO 3508)", + "thread.fits_the_face": "fits the face, e.g. {example}", + "thread.form_bspp": "Pipe G (ISO 228-1)", + "thread.form_bspt": "Pipe taper R, Rc (ISO 7-1)", + "thread.form_npt": "Pipe taper NPT (ASME B1.20.1)", + "thread.form_rp": "Pipe Rp (ISO 7-1)", "thread.iso_metric": "ISO metric", - "thread.left_hand": "Left-hand", - "thread.right_hand": "Right-hand", "thread.select_size": "Select size", "timeline.delete_after_marker_one": "Delete 1 Feature After History Marker", "timeline.delete_after_marker_other": "Delete {count} Features After History Marker", @@ -3663,6 +4376,8 @@ "ui.3d_mouse_section": "3D mouse", "ui.3d_mouse_show_in_view": "Show the 3D mouse in the 3D view", "ui.3d_mouse_show_in_view_tip": "A picture of your 3D mouse in the lower left corner, moving as you move it.", + "ui.3d_mouse_sketch_orbit": "Turn sketches with the 3D mouse", + "ui.3d_mouse_sketch_orbit_tip": "The 3D mouse also turns the view while a sketch is open and seen square on, as the mouse can. Off: it pans and zooms the sketch until you tilt the view.", "ui.3d_mouse_skip": "My device can't do this", "ui.3d_mouse_skip_tip": "Skips this motion both ways, and the calibration leaves it out.", "ui.3d_mouse_speed": "3D mouse speed", @@ -3691,6 +4406,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Twist the cap anticlockwise, hold it, then let go.", "ui.3d_mouse_switch_cap": "Calibrate as Return to Center", "ui.3d_mouse_switch_trackball": "Calibrate as a trackball", + "ui.3d_mouse_use_direct": "Use Direct Driver", + "ui.3d_mouse_use_direct_tip": "Read the 3D mouse directly (hidraw) instead of through spacenavd.", "ui.3d_mouse_view_axis": "View axis", "ui.3d_mouse_view_off": "Off", "ui.3d_mouse_view_off_tip": "The 3D mouse driver's profile turns this axis off, so its motion doesn't move the view. Picking another axis's motion here swaps the two, and that motion stops moving the view.", @@ -3729,6 +4446,8 @@ "ui.agent_chat_auth_terminal": "Run this in a terminal, then press Connect again:", "ui.agent_chat_auth_title": "Sign in to the agent", "ui.agent_chat_cancel": "Cancel", + "ui.agent_chat_cancel_timeout": "The agent did not respond to Stop and was disconnected. Reconnect to continue.", + "ui.agent_chat_cannot_start": "Installed, but it does not start: {error}", "ui.agent_chat_changes": "Changes: {n}, one undo step", "ui.agent_chat_changes_n": "{n} changes", "ui.agent_chat_changes_of": "{n}/{limit} changes", @@ -3737,11 +4456,13 @@ "ui.agent_chat_command": "Agent command", "ui.agent_chat_connect": "Connect", "ui.agent_chat_copy": "Copy", + "ui.agent_chat_copy_message": "Copy message", "ui.agent_chat_ctx_bodies": "Bodies", "ui.agent_chat_ctx_elements": "Elements", "ui.agent_chat_ctx_features": "Features", "ui.agent_chat_ctx_more": "+{n} more", "ui.agent_chat_ctx_other": "Other", + "ui.agent_chat_custom_heading": "Custom model", "ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.", "ui.agent_chat_denied": "Denied", "ui.agent_chat_deny": "Deny", @@ -3785,8 +4506,16 @@ "ui.agent_chat_mode_all": "All", "ui.agent_chat_mode_ask": "Ask", "ui.agent_chat_mode_edits": "Edits", + "ui.agent_chat_model_custom": "Use custom: {model}", "ui.agent_chat_model_no_tools": "{model} can't use SolidCraft's tools, so it can only chat. Pick a model with tool support.", + "ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}", + "ui.agent_chat_model_search": "Search models…", "ui.agent_chat_model_tip": "The model the agent uses. Your choice is remembered for this agent.", + "ui.agent_chat_models_failed": "Couldn't list models: {error}", + "ui.agent_chat_models_heading": "Available models", + "ui.agent_chat_models_listing": "Listing models…", + "ui.agent_chat_models_none": "The endpoint lists no models", + "ui.agent_chat_models_not_a_list": "The answer was no model list", "ui.agent_chat_new": "New chat", "ui.agent_chat_new_confirm": "Start a new chat? The current one is cleared.", "ui.agent_chat_next_picture": "Next picture", @@ -3795,6 +4524,7 @@ "ui.agent_chat_no_images": "This agent doesn't take pictures", "ui.agent_chat_no_picture": "There is no picture on the clipboard", "ui.agent_chat_no_tool_call": "The model didn't use SolidCraft's tools, so the design wasn't changed. Choose a model that supports tool calling; see Local models in the agent chat guide.", + "ui.agent_chat_node_too_old": "Node.js {version} is too old for this agent. Install Node.js 20.10 or newer, then press Refresh.", "ui.agent_chat_none_found": "No coding agent found. Install one of these, then press Refresh:", "ui.agent_chat_none_found_short": "No agent found", "ui.agent_chat_not_installed": "Not installed", @@ -3821,9 +4551,12 @@ "ui.agent_chat_queued_stopped": "Queued (stopped, not sent)", "ui.agent_chat_refresh": "Refresh", "ui.agent_chat_refused": "Not allowed for the agent: {reason}", + "ui.agent_chat_reinstall": "{agent} is installed ({program}), but it did not start when SolidCraft checked it: {error}\nIts installation may be incomplete, or made for another kind of computer. Install it again with `{install}`, check that it prints its version in a terminal, then press Refresh.", "ui.agent_chat_remove": "Remove from the queue", "ui.agent_chat_remove_file": "Take it off this message", "ui.agent_chat_remove_imported": "Take it off this message; the part stays in the design (Undo removes it)", + "ui.agent_chat_reply_cut_off": "The reply reached its length limit before it finished, so it may be incomplete. Ask the agent to go on, or for a shorter answer.", + "ui.agent_chat_reply_declined": "The model declined to answer this message.", "ui.agent_chat_retry": "Retry", "ui.agent_chat_right": "Right", "ui.agent_chat_save": "Save", @@ -3832,7 +4565,7 @@ "ui.agent_chat_send_now_tip": "Stop the agent's current step and send this next (Ctrl+Enter)", "ui.agent_chat_setup_body": "SolidCraft talks to a coding agent installed on this computer. Pick one in Preferences › AI.", "ui.agent_chat_setup_title": "Set up an assistant", - "ui.agent_chat_side": "Agent chat side", + "ui.agent_chat_side": "Dock the chat", "ui.agent_chat_signed_in": "signed in", "ui.agent_chat_state_auth": "Sign-in needed", "ui.agent_chat_state_busy": "Working…", @@ -3851,7 +4584,7 @@ "ui.agent_chat_undone": "(undone)", "ui.agent_chat_view_attached": "View attached", "ui.agent_chat_waiting": "Waiting for you", - "ui.agent_cursor": "Agent cursor", + "ui.agent_cursor": "Agent pointer", "ui.agent_cursor_speed": "Agent cursor speed", "ui.agent_off_thread": "Keep the window responsive while agents run commands", "ui.agent_off_thread_note": "An agent's slow commands (from the AI panel or an MCP client) compute beside the window: you can keep turning and inspecting the view, and stop one from the chip in the view. Off: each runs on the window's thread and the window waits for it.", @@ -3882,24 +4615,29 @@ "ui.ai_copy_suffix": "copy", "ui.ai_custom_url": "Custom URL", "ui.ai_default": "Default", + "ui.ai_edit": "Edit", + "ui.ai_edit_agent_title": "Edit agent", + "ui.ai_edit_gone": "This agent was removed, so there is nothing to save.", + "ui.ai_edit_tip": "Change this agent's name, command or endpoint. A saved key stays hidden.", "ui.ai_http_busy": "the endpoint is busy or over its limit; try again later", "ui.ai_http_key": "the endpoint refused the key: check it in Preferences > AI", "ui.ai_http_not_found": "no such endpoint or model: check the base URL and the model name", "ui.ai_http_too_large": "the conversation is too large for this endpoint; start a new chat", "ui.ai_key": "API key", "ui.ai_key_hint": "optional; kept in the system keychain", + "ui.ai_key_keep_hint": "leave empty to keep the saved key", "ui.ai_key_needs_https": "A key is only sent over HTTPS, or to this computer.", "ui.ai_key_note": "Stored in the system keychain, never in SolidCraft's settings. Leave it empty for a local server.", "ui.ai_keychain_error": "The system keychain refused: {error}", "ui.ai_kind": "Kind", - "ui.ai_mode_all": "Allow everything", + "ui.ai_mode_all": "Do everything", "ui.ai_mode_all_note": "Nothing asks first. Crash reports stay off limits and the folder limits still apply.", "ui.ai_mode_all_warning": "The agent can save, overwrite, export and replace your design without asking. Use this only with an agent you trust, on designs you have saved.", - "ui.ai_mode_ask": "Ask every time", + "ui.ai_mode_ask": "Ask first", "ui.ai_mode_ask_note": "Every change to the design, and every file action, waits for your Allow.", - "ui.ai_mode_edits": "Auto-allow model edits", + "ui.ai_mode_edits": "Make edits", "ui.ai_mode_edits_note": "Modeling commands run without asking; saving, opening, exporting and other file or destructive actions still ask.", - "ui.ai_mode_global": "As set above", + "ui.ai_mode_global": "Same as above", "ui.ai_model": "Model", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "These settings cover SolidCraft's tools. An agent's own tools (its shell, its file edits) follow the agent's own mode, which you pick in the chat panel's header when the agent has modes.", @@ -3914,14 +4652,18 @@ "ui.ai_permissions": "Permissions", "ui.ai_preset": "Preset", "ui.ai_protocol": "Protocol", + "ui.ai_reasoning_effort": "Reasoning effort", + "ui.ai_reasoning_effort_field_hint": "empty = provider default", + "ui.ai_reasoning_effort_hint": "Optional. Sent to the endpoint as `reasoning_effort`; accepted values differ per provider (for example `low`, `high` or `max`). A value you set here is never replaced by SolidCraft. Leave empty to send nothing and keep the provider's default.", "ui.ai_remove": "Remove", "ui.ai_request_timed_out": "The model took longer than {seconds} s. You can raise the request timeout for this endpoint in Preferences › Assistant.", "ui.ai_request_timeout": "Request timeout", "ui.ai_request_timeout_hint": "How long one model request to this endpoint may take, from 30 s to an hour. Raise it for a slow local model.", "ui.ai_reset": "Reset", + "ui.ai_save": "Save", "ui.ai_settings": "AI settings…", "ui.ai_show_features": "Show AI features", - "ui.ai_show_features_note": "The agent chat: a panel where a coding agent you already use, or a model endpoint you choose, works on the open design. Off: no AI button, shortcut, menu entry or panel, and nothing is looked for or started.", + "ui.ai_show_features_note": "Off hides the Assistant everywhere and starts nothing. Everything below dims.\n\nThe agent chat: a panel where a coding agent you already use, or a model endpoint you choose, works on the open design. Off: no AI button, shortcut, menu entry or panel, and nothing is looked for or started.", "ui.ai_switch_tip": "Change the agent for this conversation", "ui.ai_test": "Test", "ui.ai_test_acp_ok": "Answers: {agent}", @@ -3955,7 +4697,7 @@ "ui.ai_tool_sum_then": "{first}, then {next}", "ui.ai_tool_unfold": "Click to show what it returned", "ui.ai_tool_waiting": "waiting", - "ui.ai_toolbar_button": "Show Assistant button in application bar", + "ui.ai_toolbar_button": "Assistant button in the application bar", "ui.ai_toolbar_button_note": "The Assistant button in the application bar. Ctrl+Shift+A and the View menu still open the panel.", "ui.ai_undo_tip": "Undo everything the agent changed for this message, as one step", "ui.ai_url_hint": "https://example.com/v1", @@ -4002,11 +4744,14 @@ "ui.centerline": "Centerline", "ui.chain": "Chain", "ui.chamfer": "Chamfer", + "ui.chamfer_angle": "Chamfer Angle", + "ui.chamfer_depth": "Chamfer Depth", "ui.chamfer_type": "Chamfer Type", "ui.change_workspace": "Change workspace", "ui.circle": "Circle", "ui.circular_pattern": "Circular Pattern", "ui.clear": "Clear", + "ui.clear_print_face": "Clear Print Face", "ui.clear_recent": "Clear Recent", "ui.clear_the_selection": "Clear the selection", "ui.click_selects_whole_bodies": "Click selects whole bodies", @@ -4031,10 +4776,16 @@ "ui.colour_vision_sample": "Sample", "ui.colour_vision_tritan": "Tritan", "ui.colour_vision_tritan_tip": "For a weak or missing blue sense", + "ui.comb_length": "Comb length", + "ui.comb_length_tip": "How long the teeth are: a multiple of the automatic length, which makes the longest tooth a fifth of the size of the curves shown.", + "ui.comb_teeth": "Teeth", + "ui.comb_teeth_tip": "How many teeth each comb has, evenly spaced along the curve. More teeth show more detail of how the curvature changes.", "ui.combine": "Combine", "ui.coming_later": "coming later", "ui.command_done": "{command} done", "ui.command_palette_hint": "Type a command, e.g. {example} — or press S to search", + "ui.components_from_bodies_hint": "Create one component per selected body, named after that body, under the active component.", + "ui.components_from_bodies_required": "Select at least one body.", "ui.concentric": "Concentric", "ui.cone": "Cone", "ui.conic_curve": "Conic Curve", @@ -4047,15 +4798,30 @@ "ui.construction.contact_hint": "Tangent: pick a circle/arc or open spline/conic, then the contact point (free-form curves: endpoints)", "ui.construction.external_hint": "Tangent: pick a circle or arc, an external point, then the desired solution", "ui.construction.free_hint": "Construction line: click two points; right-click to restart", + "ui.construction.normal_needs_length": "An infinite line is always construction: type a length to draw a normal line", "ui.construction.point_hint": "Construction line: click the point to pass through", "ui.construction.reference_hint": "Construction line: pick a straight line, then a point; right-click to change the reference", "ui.construction.ribbon_label": "X-Lines", + "ui.construction.side_hint": "Construction line: click the side the line runs towards; right-click to restart", "ui.context_menu": "Context menu", + "ui.continuity_crease": "Crease", + "ui.continuity_curvature": "Curvature", + "ui.continuity_curvature_change": "Curvature change", + "ui.continuity_curvature_change_tip": "Curvature change (G3): the curvature also changes smoothly across the seam.", + "ui.continuity_curvature_tip": "Curvature-continuous (G2): reflections run through without a kink.", "ui.continuity_g0": "G0 crease", "ui.continuity_g1": "G1 tangent", "ui.continuity_g2": "G2 curvature", "ui.continuity_gap": "Gap", + "ui.continuity_position": "Position", + "ui.continuity_position_tip": "Position (G0): the surfaces meet, with a crease where they do.", + "ui.continuity_smooth_curvature_change": "Smooth curvature change", + "ui.continuity_smooth_curvature_change_tip": "Smooth curvature change (G4): even the way the curvature changes runs on smoothly across the seam.", + "ui.continuity_tangent": "Tangent", + "ui.continuity_tangent_tip": "Tangent (G1): no crease, though the curvature jumps across the seam.", "ui.copy": "Copy", + "ui.copy_details": "Copy Details", + "ui.copy_details_tip": "Copy the full message, to look it up or to report it.", "ui.corner": "Corner", "ui.corners": "Corners", "ui.cosmetic_thread_markings": "Cosmetic thread markings", @@ -4077,6 +4843,8 @@ "ui.dark": "Dark", "ui.default_modelling_orientation": "Default modeling orientation", "ui.delete": "Delete", + "ui.delete_select_first": "Select what to delete first: features, bodies, components or sketch geometry", + "ui.dependents_select_first": "Select what to list the dependents of first", "ui.depth": "Depth", "ui.design": "Design", "ui.design_properties.author": "Author", @@ -4091,6 +4859,40 @@ "ui.design_properties.project": "Project", "ui.design_properties.revision": "Revision", "ui.design_saved": "Saved {path}", + "ui.details_access_caption": "Faces show whether a tool can reach them from the chosen direction.", + "ui.details_angle": "Angle", + "ui.details_continuity_caption": "Edit the selected seam. Other seams keep their own settings.", + "ui.details_continuity_stale": "Earlier geometry: rerun the analysis to edit or frame this seam.", + "ui.details_copy_list": "Copy list", + "ui.details_curvature": "Curvature tolerance", + "ui.details_curvature_caption": "Faces are colored by their local radius of curvature.", + "ui.details_direction": "Tool direction", + "ui.details_draft_caption": "Faces are colored by their angle to the pull direction.", + "ui.details_edit_seam": "Edit seam", + "ui.details_fixture": "Component specimen — sample data only", + "ui.details_fixture_caption": "Component specimen with illustrative values; this is not a model result.", + "ui.details_fixture_problem": "Example finding with a problem", + "ui.details_fixture_readout": "Example measured value", + "ui.details_flip": "Flip", + "ui.details_gap": "Gap", + "ui.details_hatch": "Hatch cut faces", + "ui.details_jump": "Curvature jump", + "ui.details_key": "Key", + "ui.details_offset": "Offset", + "ui.details_plane": "Plane", + "ui.details_pull": "Pull direction", + "ui.details_radius": "Radius", + "ui.details_readout": "Readout", + "ui.details_samples": "Samples", + "ui.details_seam": "{body} · Edge {edge}", + "ui.details_settings": "Settings", + "ui.details_sharp_gap": "Sharp or gap", + "ui.details_show_all": "Show all {count}", + "ui.details_smooth": "Smooth", + "ui.details_stripes": "Stripes", + "ui.details_target": "Frame geometry", + "ui.details_worst_seams": "Worst seams", + "ui.details_zebra_caption": "Reflected stripes show how smoothly faces join.", "ui.diameter": "Diameter", "ui.dimension": "Dimension", "ui.direct_interaction": "Direct interaction", @@ -4135,39 +4937,78 @@ "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", "ui.edit_in_place_wait": "Wait until what is running in the design is done", "ui.edit_section_analysis": "Edit Section Analysis", + "ui.edit_sketch_empty": "No sketches to edit", "ui.ellipse": "Ellipse", "ui.emboss_wrap_note": "Orthogonal line profiles tangent to one supported cylinder wrap automatically. Pick a wall to choose a target.", + "ui.end": "End", "ui.end_radius": "End Radius", "ui.end_scale": "End Scale", + "ui.ends": "Ends", "ui.entities": "Entities", "ui.equal": "Equal", "ui.equation_end": "End", "ui.equation_explicit": "Explicit", "ui.equation_form": "Form", "ui.equation_note": "The variable is a plain number: sin(t) takes it in radians. A result without a unit is in the design's unit.", + "ui.equation_note_range": "The variable is a length, as its range is: mix it with length parameters, and divide it by a length for sin(). A result without a unit is in the design's unit.", "ui.equation_parametric": "Parametric", + "ui.equation_variable_unit": "Variable has the range's unit", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Equivalent Radius", "ui.expand": "Expand", + "ui.explode_needs_two_components": "Exploded View pulls components apart, so the design needs two or more of them (New Component, Insert Design or Create Components from Bodies)", "ui.exportDxf": "Export DXF…", "ui.export_ellipsis_keymap": "Export…", "ui.export_keymap_tip": "Keys, S box favorites and the toolbar, as a file", "ui.extend": "Extend", + "ui.extent": "Extent", "ui.extent_type": "Extent Type", "ui.extract_component": "Extract to File…", "ui.extract_design_changed": "The design changed while choosing a file. Start Extract to File again.", "ui.extract_done": "The component is now its own design, linked here.", "ui.extrude": "Extrude", "ui.extrude_auto_to_object": "Extrude to a picked target", - "ui.extrude_auto_to_object_tip": "In Extrude, with a profile picked, picking a face, vertex or parallel plane off its plane switches the extent to To Object", + "ui.extrude_auto_to_object_tip": "A face, vertex or parallel plane switches the extent to To Object.", "ui.factor": "Factor", + "ui.fade": "Fade", + "ui.fade_length": "Fade Length", "ui.feature_history": "Feature history", "ui.feature_options": "Feature Options", "ui.features": "Features", "ui.file": "File", "ui.fillet": "Fillet", + "ui.fillet_corner_ball": "Ball", + "ui.fillet_corner_ball_tip": "A piece of the rolling ball's sphere, tangent (G1) to each round.", + "ui.fillet_corner_curvature_tip": "Curvature (G2): a smooth patch. The corner is set back along each edge by the Setback ({factor} × the radius unless you type one) and filled with a patch, so reflections run through it without a kink.", + "ui.fillet_corner_needs_constant": "Smooth patch corners (G2) need Constant radius and Exact fit.", + "ui.fillet_corner_patch": "Smooth patch", + "ui.fillet_corner_patch_tip": "Curvature-continuous (G2): the corner is set back along each edge and filled with a patch, so reflections run through it without a kink.", + "ui.fillet_corner_tangent_tip": "Tangent (G1): a rolling-ball corner, a piece of the rolling ball's sphere tangent to each round.", + "ui.fillet_error_corner": "The smooth corner could not be built here. Try another Setback, or Tangent corners.", + "ui.fillet_error_failed": "This fillet could not be built on these edges. Try another radius, or round fewer edges at once.", + "ui.fillet_error_setback_short": "The setback is too short for this corner's patch: it builds from {least} on. Try a longer Setback.", + "ui.fillet_error_too_large": "The radius is too large for the faces beside these edges. Try a smaller radius, or set Face limits to Largest radius.", + "ui.fillet_fit": "Face limits", + "ui.fillet_fit_exact": "Exact radius", + "ui.fillet_fit_needs_constant": "Radius fit needs Constant radius.", + "ui.fillet_fit_reduce": "Largest radius", + "ui.fillet_fit_taper": "Narrowed radius", + "ui.fillet_fit_tip": "When the radius is larger than the faces beside an edge allow.\nExact radius: the radius as given, or nothing rounded and a message saying why.\nLargest radius: every edge rounded with the largest radius that fits.\nNarrowed radius: the radius kept, the round narrowed only where the faces run out.", + "ui.fillet_options_tip": "Tangent chain: also round the edges that continue smoothly from the picked ones.\nPreview: show the result in the view while you edit.", + "ui.fillet_setback": "Setback", + "ui.fillet_setback_hint": "{factor} × radius", + "ui.fillet_setback_least": "More than {least}", + "ui.fillet_setback_tip": "Where the smooth corner patch starts: how far along each edge from the corner. The default is {factor} × the radius. It must be more than the least setback, where the rounds meet without one: the radius where the faces are square to each other.", + "ui.fillet_smooth_radius": "Smooth radius change", + "ui.fillet_turn": "Turns", + "ui.fillet_turn_mitre": "Mitre", + "ui.fillet_turn_swept": "Swept", + "ui.fillet_turn_tip": "Where two rounds turn round a sharp corner edge between them, such as the rounds along a boss's base at its upright edges.\nMitre: the rounds run on until they meet in a mitre.\nSwept: the rounds stop at the corner edge and turn round it, the corner a torus tangent to both. Only for rounds of one radius round a straight, convex corner edge.", + "ui.fillet_type_choices_tip": "Constant radius: one radius all along the edge.\nChord length: the width across the round stays the same, whatever angle the faces meet at.\nVariable radius: a radius at each end, and more along the edge if you add them.\nCurvature continuous: a section without a kink in reflections where it meets flat faces (G2).\nSpline: the radius along the edge follows control radii you set.", + "ui.fillet_type_curvature": "Curvature continuous", + "ui.fillet_type_tip": "The section across the edge. Curvature continuous: a curvature-continuous (G2) section between planar faces, so reflections run from the faces into the round without a kink.", "ui.filter_commands_or_keys": "Filter commands or keys", "ui.findInTimeline": "Find in Timeline", "ui.findInWindow": "Find in Window", @@ -4277,13 +5118,15 @@ "ui.hideOrigin": "Hide Origin", "ui.hidePlanes": "Hide Planes", "ui.hideProfile": "Hide Profile", - "ui.hide_origin_by_default": "Hide origin by default", + "ui.hide_component_history": "Hide its History", + "ui.hide_origin_by_default": "Hide the Origin folder in new designs", "ui.hide_origin_note": "New designs start with the Origin folder hidden. A design keeps its own Origin setting once you show or hide it.", "ui.history_back": "Go back one step", "ui.history_below_browser": "Below browser", "ui.history_edge_hint": "double-click the edge", "ui.history_first": "Go to beginning", "ui.history_forward": "Go forward one step", + "ui.history_hide_hidden": "Hide Hidden Components", "ui.history_hide_names": "Hide names", "ui.history_last": "Go to end", "ui.history_marker_tip": "History marker: drag to roll the model back; new features go here", @@ -4293,10 +5136,12 @@ "ui.history_play_button_show": "Show Play Button", "ui.history_play_finish_action": "Finish the current action before playing History", "ui.history_play_roll_back": "Move the History marker back before playing", + "ui.history_show_hidden": "Show Hidden Components", "ui.history_show_names": "Show names", "ui.history_sketch_listed_under": "Listed under {feature}", "ui.history_title": "History", "ui.history_toggle_names": "Show or hide feature names", + "ui.history_waits_for_editor": "Undo, Redo and History wait until the feature editor has opened", "ui.hole": "Hole", "ui.hole_tap_type": "Hole Tap Type", "ui.hole_type": "Hole Type", @@ -4312,7 +5157,9 @@ "ui.insert_design.saved_file": "{name} has unsaved changes, so its saved file was inserted. Save it, then Update Links to bring the changes in.", "ui.insert_design.unsaved": "Unsaved changes", "ui.inspect": "Inspect", + "ui.instances": "Instances", "ui.intersect": "Intersect", + "ui.iso_4753": "ISO 4753", "ui.isolate": "Isolate", "ui.join": "Join", "ui.joint_play": "▶ Play", @@ -4320,12 +5167,14 @@ "ui.joints": "Joints", "ui.keyboard_shortcuts": "Keyboard Shortcuts", "ui.language": "Language", + "ui.lasso_select": "Lasso (drag a freehand loop: takes what is wholly inside)", "ui.layout_compact": "Compact", "ui.layout_floating": "Floating", "ui.length": "Length", "ui.length_decimals": "Length decimals", "ui.light": "Light", "ui.line": "Line", + "ui.line_arc_hint": "Tangent arc: click the arc's end. Rest on the last point again for lines; right-click or Esc to finish", "ui.link_copies": "Link Identical Copies", "ui.link_copies_keep": "Keep", "ui.link_copies_link": "Link", @@ -4413,7 +5262,9 @@ "ui.part_size_needs_a_part": "Select an inserted standard part (a screw, nut, washer or pin) to change its size. To make a body larger or smaller, use Scale.", "ui.part_size_shared": "Rebuilds the part, replacing any added features. All occurrences of this component update.", "ui.paste": "Paste", + "ui.patch_continuity_corner_tip": "The patch meets the faces round it at the chosen continuity along each side. At a corner where those faces meet each other with different curvatures, it stays tangent (G1) there.", "ui.path": "Path", + "ui.pattern_object_type_tip": "Bodies: solid shapes, picked in the view or the Browser; each is copied whole.\nFeatures: steps of the History, such as an extrude or a hole, picked in the History or on a face they made; the step is repeated.\nA sketch is neither: repeat its curves with the sketch's own Pattern or Mirror, or extrude it first.", "ui.pattern_on_path": "Pattern on Path", "ui.perforate_margin_default": "from the diameter", "ui.perforate_pitch": "Pitch", @@ -4428,7 +5279,7 @@ "ui.pitch": "Pitch", "ui.placement": "Placement", "ui.placement_handles": "Placement handles", - "ui.placement_handles_tip": "Handles on the preview of a Rest, Boss or Snap Fit: drag the marker to move it across the model, turn it by its ring", + "ui.placement_handles_tip": "A marker to drag the feature across the model and a ring to turn it.", "ui.plane": "Plane", "ui.plane_at_angle": "Plane at Angle", "ui.plugins": "Plugins", @@ -4440,12 +5291,17 @@ "ui.plugins_skipped": "{count} folder(s) could not be read.", "ui.plugins_version": "{version}", "ui.point": "Point", + "ui.point_cloud_add_filter": "Add filter…", "ui.point_cloud_auto_range": "Automatic Range", "ui.point_cloud_color_by": "Color By", "ui.point_cloud_file_colors": "File Colors", + "ui.point_cloud_filter_by": "Filter by", "ui.point_cloud_height_high": "Highest", "ui.point_cloud_height_low": "Lowest", + "ui.point_cloud_legend_filter": "Shown and hidden in the legend above", "ui.point_cloud_no_file_colors": "The file has no colors", + "ui.point_cloud_pause": "Pause", + "ui.point_cloud_play": "Play", "ui.point_cloud_single_color": "Single Color", "ui.point_cloud_size": "Point Size", "ui.point_cloud_units": "File Units", @@ -4454,6 +5310,11 @@ "ui.polygon": "Polygon", "ui.preferences": "Preferences", "ui.press_a_key": "press a key…", + "ui.print_face_body_not_sent": "That face's body is not being sent: add it to Bodies first", + "ui.print_face_cleared": "{body}: print face cleared", + "ui.print_face_input": "Print face", + "ui.print_face_pick": "Select one flat face of a solid body to make it the print face", + "ui.print_face_set": "{body}: print face set; Send to Slicer lays the body on it", "ui.profile": "Profile", "ui.profile_plane": "Profile Plane", "ui.profiles": "Profiles", @@ -4470,6 +5331,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Measuring…", + "ui.properties.measuring_bodies": "Measuring… {done} of {total} bodies", "ui.properties.measuring_failed": "Measuring stopped before it finished.", "ui.properties.principal_axis": "Principal axis {number}", "ui.properties.principal_moments": "Principal moments", @@ -4537,6 +5399,7 @@ "ui.selectOther": "Select Other…", "ui.selectTangentChain": "Select Tangent Chain", "ui.select_all": "Select All", + "ui.select_components_by_face": "Select components (a face picks its component)", "ui.selection": "Selection", "ui.selection_modifiers": "Selection modifiers", "ui.selection_shift_add_only": "Shift+click adds without removing", @@ -4562,6 +5425,7 @@ "ui.showDimension": "Show Dimension", "ui.showOrigin": "Show Origin", "ui.showPlanes": "Show Planes", + "ui.show_component_history": "Show its History", "ui.show_constraints": "Constraints", "ui.show_construction_geometries": "Construction Geometries", "ui.show_dimensions": "Dimensions", @@ -4576,8 +5440,15 @@ "ui.sketch_intersect_geometry": "Geometry", "ui.sketch_intersect_projection_link": "Projection Link", "ui.sketch_intersect_selection_filter": "Selection Filter", + "ui.sketch_keys_only": "Keep model keys out of sketches", + "ui.sketch_keys_only_tip": "While editing a sketch, only sketch keys and keys that work everywhere run; a model key such as E or F does nothing, so a stray key can't close a heavy sketch.", "ui.sketch_modifiers": "Sketch modifiers", "ui.sketch_project_geometry": "Geometry", + "ui.sketch_report.all_constrained": "Everything is fully constrained.", + "ui.sketch_report.dof": "Degrees of freedom", + "ui.sketch_report.loose": "Not fully constrained", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Sketch Report", "ui.sketch_scale": "Sketch Scale", "ui.sketches": "Sketches", "ui.slice": "Slice", @@ -4588,7 +5459,7 @@ "ui.slicer_no_response": "{slicer} didn't respond in time. The file is already saved at {path}: send it again once the slicer has started.", "ui.slicer_resend_hint": "Sending again replaces the file the slicer has open.", "ui.slicer_single_instance": "Open files in a slicer that is already running", - "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer and Cura load the file in the window that is open instead of starting another. Other slicers are started as they are. PrusaSlicer 3.0 always does this: its launcher can't take a file any other way.", + "ui.slicer_single_instance_tip": "For slicers that load a file into a running window.", "ui.slicer_starting": "Starting {slicer}…", "ui.slicer_still_starting": "Still waiting for {slicer} to start. Nothing else was sent.", "ui.slicer_stl_fallback": "The 3MF could not be written, so this is an STL.", @@ -4607,8 +5478,8 @@ "ui.start": "Start", "ui.start_over": "Start over", "ui.start_page": "Start page", - "ui.step_values": "Step values with the arrow keys and the wheel", - "ui.step_values_tip": "In a value field you are typing in, Up/Down change a plain number by 1 (Shift: 10, Alt: 0.1), and so does the mouse wheel over the field. Expressions are left as typed.", + "ui.step_values": "Step values with arrows and wheel", + "ui.step_values_tip": "Up/Down and the wheel over a value field change its number.", "ui.stitch_tolerance_hint": "tight", "ui.stretch": "Stretch", "ui.supersampling": "Supersampling (SSAA)", @@ -4674,19 +5545,31 @@ "ui.view_angles": "View angles", "ui.view_angles_convention": "Degrees about the up axis. Yaw 0° is the Front view, 90° Left, −90° Right, 180° Back; pitch 90° is the Top view; a positive roll turns the model clockwise.", "ui.view_angles_help": "Shows the view's pitch, yaw and roll in degrees and its projection under the orientation gizmo. Click the readout to type exact angles.", + "ui.view_angles_lock": "Lock {axis}", "ui.view_angles_ortho": "Ortho", "ui.view_angles_persp": "Persp", "ui.view_angles_pitch": "Pitch", "ui.view_angles_readout": "Pitch {pitch} · Yaw {yaw} · Roll {roll}", "ui.view_angles_roll": "Roll", + "ui.view_angles_unlock": "Unlock {axis}", "ui.view_angles_yaw": "Yaw", + "ui.view_angles_zero": "Set {axis} to 0°", "ui.view_centre": "View center", "ui.viewport_status_clear": "Turn off {name}", "ui.viewport_status_clear_hint": "Turn off {name} · Esc", + "ui.viewport_status_edges": "{count} edges", + "ui.viewport_status_from": "from {direction}", "ui.viewport_status_key": "Show key for {name}", "ui.viewport_status_minimum_radius": "Minimum radius", "ui.viewport_status_pairs": "{count} pairs", + "ui.viewport_status_section_hatch": "{setting} · hatch", + "ui.viewport_status_section_plane": "Current plane", + "ui.viewport_status_section_tilted": "tilted · {offset}", "ui.viewport_status_stripes": "{count} stripes", + "ui.viewport_status_summary_clear": "Turn everything off", + "ui.viewport_status_summary_heading": "In this view", + "ui.viewport_status_summary_label": "{name} and {count} more items", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Follow theme", "ui.visual_shaded_hidden_edges": "Shaded with hidden edges", "ui.visual_shaded_with_edges": "Shaded with edges", @@ -4722,11 +5605,13 @@ "update.available": "SolidCraft {version} is available", "update.button": "Update", "update.button_version": "Update to {version}", - "update.check_automatically": "Check for updates automatically", + "update.check_automatically": "Check at start and once a day", + "update.check_for_updates": "Check for updates", "update.check_now": "Check now", + "update.check_unavailable": "Update checks are not available for this installation.", "update.checking": "Checking…", "update.copy": "Copy", - "update.dmg_opened": "The disk image is open and verified: drag SolidCraft to Applications, replacing the old copy, then restart SolidCraft.", + "update.dmg_opened": "The disk image is open and verified: quit SolidCraft, drag the new SolidCraft to Applications, replacing the old copy, then open SolidCraft again.", "update.download": "Download", "update.download_open": "Download and open", "update.downloading": "Downloading and verifying… {done} of {total} MB", @@ -4770,6 +5655,7 @@ "web.open_link": "Open linked design?", "web.open_link_confirm": "There are unsaved changes. Open the linked design in a new tab?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss", + "↑ ↓ choose · Enter applies this value": "↑ ↓ choose · Enter applies this value", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ choose · Enter applies what you typed · Esc dismiss", "⌘Enter continues on GitHub.": "⌘Enter continues on GitHub." } diff --git a/assets/locales/es.json b/assets/locales/es.json index 9051103b1..a96bfadb5 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "SUPERFICIE DE TRANSICIÓN", "BOUNDARY SURFACE": "SUPERFICIE DE CONTORNO", "BROWSER": "EXPLORADOR", + "Back to the original order": "Volver al orden original", "Ball": "Rótula", "Bar": "Barra", "Base Center": "Centro de la base", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Aquí aparecen los diseños que abras o guardes.", "Determined by To Object. Choose Angle to edit the angular extent.": "Determinado por «Hasta objeto». Elige «Ángulo» para modificar la extensión angular.", "Diameter": "Diámetro", + "Did this assembly open the wrong way up?": "¿Este ensamblaje se abrió del revés?", + "Did this part open the wrong way up?": "¿Esta pieza se abrió del revés?", "Dimension new shapes": "Acotar las formas nuevas", "Direction": "Dirección", "Discard": "Descartar", @@ -204,6 +207,7 @@ "Edges": "Aristas", "Edit": "Editar", "Edit Profile Sketch": "Editar boceto del perfil", + "Edit shortcuts": "Editar atajos", "Enable rule": "Activar regla", "Enabled": "Activado", "End Radius": "Radio final", @@ -258,6 +262,8 @@ "Flanges": "Pestañas", "Flat Pattern": "Desarrollo plano", "Flat size": "Tamaño del desarrollo", + "Flat size X": "Tamaño plano X", + "Flat size Y": "Tamaño plano Y", "Follow camera (Look At sketches)": "Seguir cámara (orientar hacia los bocetos)", "Follow the camera (Look At sketches)": "Seguir la cámara (orientar hacia los bocetos)", "Font": "Fuente", @@ -289,6 +295,7 @@ "Horiz./Vert.": "Horiz./Vert.", "I-Beam": "Perfil I", "IMAGES": "IMÁGENES", + "If you are offline or GitHub does not open, use Copy report and keep the text to submit later.": "Si estás sin conexión o no se abre GitHub, usa Copiar informe y guarda el texto para enviarlo luego.", "Import material into design": "Importar material al diseño", "Import…": "Importar…", "In This Design": "En este diseño", @@ -399,13 +406,16 @@ "Of": "Grado", "On your computer": "En tu equipo", "Opacity": "Opacidad", + "Open GitHub": "Abrir GitHub", "Open GitHub draft": "Abrir borrador de GitHub", + "Open GitHub issue form": "Abrir formulario de issue en GitHub", "Open bodies (no volume)": "Cuerpos abiertos (sin volumen)", "Open library...": "Abrir biblioteca…", "Open local libraries in the desktop app. You can export this design's library here.": "Abra las bibliotecas locales en la aplicación de escritorio. Aquí puede exportar la biblioteca de este diseño.", "Open surface — no volume": "Superficie abierta: sin volumen", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código abierto desarrollado en Rust. Licencia MIT O Apache-2.0.", "Opens your browser and copies the report text for you to paste into GitHub.": "Abre tu navegador y copia el texto del informe para que lo pegues en GitHub.", + "Opens your browser and copies the report text. Review and submit your report on GitHub.": "Abre el navegador y copia el texto del informe. Revisa y envía tu informe en GitHub.", "Opens your browser. Review and submit your report on GitHub.": "Abre tu navegador. Revisa y envía tu informe en GitHub.", "Operator": "Operador", "Orbit (right drag)": "Orbitar (arrastrar con el botón derecho)", @@ -460,6 +470,7 @@ "Radius": "Radio", "Radius Fit": "Ajuste de radio", "Ratio": "Relación", + "Read-only list: shortcuts can't be changed here.": "Lista de solo lectura: los atajos no se pueden cambiar aquí.", "Reattach selected face": "Volver a vincular la cara seleccionada", "Recover": "Recuperar", "Recover unsaved design?": "¿Recuperar el diseño sin guardar?", @@ -486,6 +497,7 @@ "Reopen the designs that were open when SolidCraft was last closed": "Reabrir los diseños que estaban abiertos cuando se cerró SolidCraft por última vez", "Replace existing library file": "Sustituir el archivo de biblioteca existente", "Report a bug — review a screenshot and open a GitHub draft": "Notificar un error — revisar una captura y abrir un borrador de GitHub", + "Report copied. Keep this text to submit on GitHub when you are online.": "Informe copiado. Guarda este texto para enviarlo en GitHub cuando estés en línea.", "Report text copied. Paste it into GitHub and submit your report there.": "Informe copiado. Pégalo en GitHub y envíalo allí.", "Reports are public. A GitHub account is required.": "Los informes son públicos. Se necesita una cuenta de GitHub.", "Reset Toolbar": "Restablecer barra de herramientas", @@ -547,6 +559,7 @@ "Sections (one sketch each)": "Secciones (un boceto cada una)", "Select Other": "Seleccionar otro", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Seleccionar otro: mantén pulsado el botón izquierdo sobre el modelo (o haz clic derecho › Seleccionar otro…) para ver todo lo que hay bajo el cursor; vuelve a pulsar en el mismo lugar para seleccionar el siguiente elemento. Haz doble clic con el botón central para volver a Inicio (Preferencias › Navegación).", + "Select Same Look": "Seleccionar mismo aspecto", "Select bodies (a face picks its body)": "Selecciona cuerpos (al seleccionar una cara se selecciona su cuerpo)", "Select bodies or faces instead": "Selecciona cuerpos o caras en su lugar", "Select edges": "Selecciona aristas", @@ -581,7 +594,10 @@ "Slider": "Deslizante", "Slot width": "Anchura de la ranura", "Snap to face and edge centres": "Ajustar a centros de caras y aristas", + "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft no puede enviar informes directamente. Envíalos en GitHub; no se necesita token en la aplicación.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft se cerró antes de guardar estos diseños. Puedes abrir su último guardado automático.", + "Sort A to Z": "Ordenar de la A a la Z", + "Sort Z to A": "Ordenar de la Z a la A", "Spacing 2 must be a non-zero number": "El espaciado 2 debe ser un número distinto de cero", "Spacing must be a non-zero number": "El espaciado debe ser un número distinto de cero", "Specialise": "Especializar", @@ -590,6 +606,7 @@ "Square": "Cuadrado", "Stand it up": "Poner en vertical", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Poner en vertical: un cuarto de vuelta alrededor del eje X, como una única operación Mover que puedes deshacer.", + "Stand this assembly up?": "¿Enderezar este ensamblaje?", "Stand this part up?": "¿Poner esta pieza en vertical?", "Start angle": "Ángulo inicial", "Start bulge": "Abombamiento inicial", @@ -640,6 +657,7 @@ "Third point": "Tercer punto", "This child is shared. Deleting it removes it from every copy of its parent.": "Este elemento secundario es compartido. Si lo eliminas, desaparecerá de todas las copias de su elemento principal.", "This child is shared. Position changes apply to every copy of its parent.": "Este elemento secundario es compartido. Los cambios de posición se aplican a todas las copias de su elemento principal.", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "Este componente está dentro de un subensamblaje colocado más de una vez: alinearlo lo mueve en todas las colocaciones.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta cara no permite una vinculación persistente. Elige otra cara o utiliza expresamente un plano fijo.", "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "Esta imagen todavía no está adjunta en GitHub. Cópiala o guárdala y adjúntala en GitHub.", "Thread depth": "Profundidad de la rosca", @@ -760,12 +778,15 @@ "at the face": "en la cara", "bom.group_children": "Subpiezas en la fila de su pieza", "browser.body_name": "Cuerpo{number}", + "browser.calibrate_click_a": "Haz clic en la imagen para el Punto A, o escribe sus coordenadas.", + "browser.calibrate_click_b": "Haz clic en la imagen para el Punto B, o escribe sus coordenadas.", "browser.calibrate_title": "Calibrar: {name}", "browser.capture_many": "Se han movido {count} componentes, pero sus posiciones no se han capturado.", "browser.capture_note": "Capturar posición conserva la nueva posición; Revertir posición restaura la anterior.", "browser.capture_one": "Se ha movido un componente, pero su posición no se ha capturado.", "browser.component_name": "Componente{number}", "browser.edit_canvas_title": "Editar lienzo: {name}", + "browser.edit_point_cloud_title": "Editar nube de puntos: {name}", "browser.move_title": "Mover: {name}", "browser.parameters": "Parámetros ({count})", "browser.precision": "Precisión: {precision}", @@ -780,18 +801,29 @@ "cam.roller": "Rodillo", "cam.roller_pick": "Rodillo (opcional)", "cam.tip_pick": "Punta (opcional)", + "camera.shot_pitch": "Inclinación", + "camera.shot_roll": "Giro", + "camera.shot_yaw": "Rumbo", + "canvas.decal_place_hint": "Haz clic en una cara para colocar la calcamonía", + "canvas.place_hint": "Haz clic en un plano o cara para colocar el lienzo", "choose a profile": "elige un perfil", "choose the cam's and the follower's joints": "elige las uniones de la leva y del seguidor", "choose the joints to couple": "elige las uniones que acoplar", "click a plane or planar face": "hacer clic en un plano o una cara plana", "click sketch curves": "hacer clic en curvas del boceto", "cmd.appearance_assign": "Apariencia", + "cmd.appearance_chain": "Cadena de aspecto", + "cmd.appearance_copy": "Copiar aspecto", + "cmd.appearance_favorite": "Aspecto favorito", "cmd.appearance_library": "Biblioteca de apariencias", "cmd.appearance_list": "Listar apariencias", "cmd.appearance_paint": "Pintar apariencia", + "cmd.appearance_paste": "Pegar aspecto", "cmd.appearance_pick_up": "Tomar apariencia", "cmd.appearance_replace": "Reemplazar apariencia", "cmd.assembly_bom": "Lista de materiales", + "cmd.assembly_mass_properties": "Propiedades de masa", + "cmd.body.print_face": "Cara de impresión", "cmd.body_rename": "Cambiar nombre del cuerpo", "cmd.browser_collapse_all": "Contraer todo", "cmd.browser_expand_all": "Expandir todo", @@ -799,6 +831,7 @@ "cmd.browser_move": "Mover elementos del explorador", "cmd.browser_order": "Ordenar elementos del explorador", "cmd.browser_rename_group": "Cambiar nombre del grupo", + "cmd.browser_reparent": "Mover a componente", "cmd.browser_ungroup": "Desagrupar", "cmd.browser_visibility": "Mostrar/ocultar", "cmd.canvas_calibrate": "Calibrar lienzo", @@ -815,7 +848,9 @@ "cmd.component_create": "Nuevo componente", "cmd.component_cycle_color": "Ciclar color de componente", "cmd.component_delete": "Eliminar componente", + "cmd.component_edit_in_place": "Editar en contexto", "cmd.component_extract": "Extraer a archivo", + "cmd.component_finish_edit": "Finalizar edición", "cmd.component_from_bodies": "Crear componentes a partir de cuerpos", "cmd.component_insert_design": "Insertar diseño", "cmd.component_links": "Listar vínculos", @@ -823,7 +858,9 @@ "cmd.component_metadata": "Propiedades de la pieza", "cmd.component_metadata_set": "Cambiar propiedades de la pieza", "cmd.component_move_bodies": "Mover cuerpos al componente", + "cmd.component_move_features": "Mover operaciones a componente", "cmd.component_move_sketches": "Mover bocetos al componente", + "cmd.component_paste_from_design": "Pegar desde otro diseño", "cmd.component_paste_new": "Pegar nuevo", "cmd.component_properties": "Propiedades físicas del componente", "cmd.component_relink": "Revincular origen", @@ -960,6 +997,7 @@ "cmd.motion_trace": "Trayectoria de movimiento", "cmd.motion_trace_edit": "Editar traza de movimiento", "cmd.motion_trace_keep": "Conservar trayectoria de movimiento", + "cmd.occurrence_align": "Alinear instancia", "cmd.occurrence_copy": "Pegar (instancia)", "cmd.occurrence_drag": "Arrastrar instancia", "cmd.occurrence_ground": "Fijar", @@ -990,6 +1028,10 @@ "cmd.plastic_rest": "Apoyo", "cmd.plastic_rules": "Listar reglas de plástico", "cmd.plastic_snap_fit": "Encaje a presión", + "cmd.pointcloud_delete": "Eliminar nube de puntos", + "cmd.pointcloud_edit": "Editar nube de puntos", + "cmd.pointcloud_insert": "Insertar nube de puntos", + "cmd.pointcloud_list": "Nubes de puntos", "cmd.render_aging_describe": "Envejecimiento por capas", "cmd.render_backends": "Motores de renderizado", "cmd.render_batch": "Renderizar todas las tomas", @@ -1012,15 +1054,26 @@ "cmd.render_library_surface_prepare": "Preparar mapas de superficie", "cmd.render_library_surface_unbind": "Eliminar vinculación de superficie", "cmd.render_library_targets": "Buscar destinos de recursos de renderizado", + "cmd.render_lights_add": "Añadir luz", + "cmd.render_lights_duplicate": "Duplicar luz de render", + "cmd.render_lights_list": "Listar luces de render", + "cmd.render_lights_mute": "Silenciar luz", + "cmd.render_lights_remove": "Eliminar luz de render", + "cmd.render_lights_set": "Configurar luz de render", "cmd.render_lights_solo": "Solo luz", "cmd.render_optics_bind": "Guardar asignación óptica", "cmd.render_optics_unbind": "Quitar asignación óptica", + "cmd.render_output_size": "Tamaño de salida de render", "cmd.render_preflight": "Comprobar solicitud de renderizado", + "cmd.render_preflight_copy": "Copiar informe de comprobación de render", "cmd.render_preset_apply": "Aplicar estudio nativo", "cmd.render_preset_resolve": "Revisar estudio nativo", "cmd.render_quality_prepare": "Revisar presupuesto fijo de muestras", + "cmd.render_result_close": "Cerrar imagen de render", + "cmd.render_result_copy": "Copiar imagen de render", "cmd.render_result_pin": "Conservar el resultado mostrado", "cmd.render_result_regrade": "Reeditar máster lineal", + "cmd.render_result_view": "Ver imagen de render", "cmd.render_scene": "Inspeccionar escena de renderizado", "cmd.render_settings_apply": "Aplicar cámara de renderizado", "cmd.render_settings_capture_hdr": "Guardar configuración de renderizado con HDR", @@ -1035,6 +1088,13 @@ "cmd.render_start": "Renderizar imagen", "cmd.render_status": "Progreso del renderizado", "cmd.select_clear": "Borrar selección", + "cmd.settings_profile_apply": "Aplicar perfil de ajustes", + "cmd.settings_profile_delete": "Eliminar perfil de ajustes", + "cmd.settings_profile_export": "Exportar perfil de ajustes", + "cmd.settings_profile_import": "Importar perfil de ajustes", + "cmd.settings_profile_list": "Lista de perfiles de ajustes", + "cmd.settings_profile_rename": "Renombrar perfil de ajustes", + "cmd.settings_profile_save": "Guardar perfil de ajustes", "cmd.sheet_convert": "Convertir a chapa", "cmd.sheet_export_bend_table": "Exportar tabla de plegados", "cmd.sheet_export_dxf": "Exportar desarrollo como DXF", @@ -1048,16 +1108,16 @@ "cmd.sheet_refold": "Volver a plegar", "cmd.sheet_rules": "Listar reglas de chapa", "cmd.sheet_unfold": "Desplegar", - "cmd.sketch.construction_line": "Recta de construcción", - "cmd.sketch.construction_line.angle": "Recta de construcción con ángulo", - "cmd.sketch.construction_line.bisector": "Bisectriz", - "cmd.sketch.construction_line.horizontal": "Recta de construcción horizontal", - "cmd.sketch.construction_line.parallel": "Recta de construcción paralela", - "cmd.sketch.construction_line.perpendicular": "Recta de construcción perpendicular", - "cmd.sketch.construction_line.tangent_at": "Tangente en un punto de la curva", - "cmd.sketch.construction_line.tangent_external": "Tangente por un punto exterior", + "cmd.sketch.construction_line": "Línea de construcción", + "cmd.sketch.construction_line.angle": "Línea de construcción en ángulo", + "cmd.sketch.construction_line.bisector": "Bisectriz de ángulo", + "cmd.sketch.construction_line.horizontal": "Línea de construcción horizontal", + "cmd.sketch.construction_line.parallel": "Línea de construcción paralela", + "cmd.sketch.construction_line.perpendicular": "Línea de construcción perpendicular", + "cmd.sketch.construction_line.tangent_at": "Tangente en punto de curva", + "cmd.sketch.construction_line.tangent_external": "Tangente por punto externo", "cmd.sketch.construction_line.tangent_two": "Tangente común", - "cmd.sketch.construction_line.vertical": "Recta de construcción vertical", + "cmd.sketch.construction_line.vertical": "Línea de construcción vertical", "cmd.sketch_arc3d": "Arco 3D", "cmd.sketch_arc_center_point": "Arco de centro y punto", "cmd.sketch_arc_tangent": "Arco tangente", @@ -1090,6 +1150,8 @@ "cmd.sketch_drawing_bounds": "Tamaño del dibujo", "cmd.sketch_edit": "Editar boceto", "cmd.sketch_edit_text": "Editar texto", + "cmd.sketch_equation_curve": "Curva ecuación", + "cmd.sketch_equation_curve_edit": "Editar curva ecuación", "cmd.sketch_export_dxf": "Guardar como DXF", "cmd.sketch_finish_auto_constrain": "Finalizar con restricciones automáticas", "cmd.sketch_fit_curves_to_section": "Ajustar curvas a sección de malla", @@ -1133,6 +1195,7 @@ "cmd.sketch_spline_control_point_5": "Spline por puntos de control (grado 5)", "cmd.sketch_spline_fit_point": "Spline por puntos de ajuste", "cmd.sketch_spline_insert_point": "Añadir punto de spline", + "cmd.sketch_spline_remove_point": "Eliminar punto de spline", "cmd.sketch_spline_reverse": "Invertir dirección del spline", "cmd.sketch_spun_profile": "Perfil de revolución", "cmd.sketch_toggle_diameter": "Alternar radio / diámetro", @@ -1175,13 +1238,20 @@ "cmd.timeline_export_script": "Exportar script de comandos", "cmd.timeline_inspect": "Inspeccionar operación", "cmd.timeline_paste": "Pegar operaciones", + "cmd.timeline_play": "Reproducir historial", "cmd.timeline_redefine": "Editar operación", "cmd.timeline_rename": "Cambiar nombre", "cmd.timeline_reorder": "Reordenar operación", "cmd.timeline_roll_to": "Desplazar marcador de la línea de tiempo", "cmd.timeline_rollback": "Mover marcador de la línea de tiempo", + "cmd.timeline_stop": "Detener historial", "cmd.timeline_suppress": "Suprimir operación", + "cmd.view.render_browser": "Explorador de render", + "cmd.view.render_dock": "Mover acople de render", + "cmd.view.render_focus": "Vista de foco de render", + "cmd.view.status_items": "Elementos de estado del visor", "cmd.view_ambient_occlusion": "Oclusión ambiental", + "cmd.view_angle_readout": "Ángulos de vista", "cmd.view_apply": "Restaurar vista guardada", "cmd.view_back": "Vista posterior", "cmd.view_bottom": "Vista inferior", @@ -1201,6 +1271,7 @@ "cmd.view_normal_to": "Normal a la selección", "cmd.view_previous_tab": "Pestaña anterior", "cmd.view_rename": "Cambiar nombre de vista guardada", + "cmd.view_render_frame": "Guías de encuadre de render", "cmd.view_right": "Vista derecha", "cmd.view_save": "Nueva vista guardada", "cmd.view_shots_strip": "Tira de tomas", @@ -1211,10 +1282,20 @@ "color.copy": "Haz clic para copiar los valores del color", "color.edit": "Haz clic para editar el color", "color.gamma": "Mostrando los valores de color en espacio gamma 0-255", + "color.hex": "Hex", + "color.hex_help": "Color en notación hexadecimal (#RRGGBB o #RRGGBBAA).", + "color.hex_hint": "#rrggbb", "color.hue": "Tono", "color.linear": "Mostrando los valores de color en espacio lineal 0-1", + "color.recent": "Colores recientes", + "color.recent_help": "Los colores que elija en cualquier campo de color aparecen aquí", + "color.saturation": "Saturación (porcentaje)", "color.saturation_value": "Saturación y valor", "color.selected": "Color seleccionado", + "color.step_down": "Bajar un paso", + "color.step_up": "Subir un paso", + "color.value": "Valor, el brillo (porcentaje)", + "config.column_filter_empty": "Sin columnas coincidentes", "contact.components_count": "{count} componentes", "contact.enabled_label": "activado", "coupling.gear_1": "Engranaje 1", @@ -1259,6 +1340,7 @@ "dialog.dimension_insert_hint": "Haga doble clic en otra cota de control para insertar su nombre", "dialog.dimension_name": "Cota: {name}", "dialog.edit_title": "EDITAR {title}", + "dialog.no_shown_body": "No hay cuerpo mostrado para cambiar: muestra uno, o elige Nuevo cuerpo", "dialog.select": "↖ Seleccionar", "dialog.selected_count": "↖ {count} seleccionados", "dialog.selection_guidance": "Selecciona una entrada para cambiarla. Haz clic en los objetos seleccionados para quitarlos; Ctrl/Cmd+clic también alterna su selección. Revisa la vista previa y pulsa Aceptar.", @@ -1276,6 +1358,7 @@ "document.read_only_save": "Este diseño se abrió en solo lectura: guárdalo como un archivo nuevo", "document.save_changes": "¿Guardar los cambios de {name}?", "document.save_copy": "Guardar una copia…", + "document.tab_unsaved_changes": "Cambios sin guardar", "document.unsaved_changes": "{name} tiene cambios sin guardar. Si no los guardas, se perderán.", "drive.rigid": "{joint} es una junta rígida: mantiene sus partes quietas, así que no tiene nada que impulsar.", "drive.stopped_by_contact": "Detenido en {value}: {a} atravesaría {b}", @@ -1318,6 +1401,7 @@ "help.appearance.assign": "Da a los cuerpos, caras o componentes seleccionados un color o un aspecto de material, con", "help.attributions": "Atribuciones (ATTRIBUTION.md)", "help.build": "Versión {version} · commit {commit} · compilada el {date}", + "help.component.finish_edit": "Guarda la pieza que estás editando en contexto, vuelve a su ensamblaje y actualiza el", "help.connect_note": "Reinicia cada asistente para que cargue el servidor de SolidCraft. Cada archivo se guardó como .bak antes de modificarlo.", "help.connect_title": "Conectar asistentes de IA", "help.face.delete": "Elimina las caras seleccionadas y deja que las caras vecinas cierren el hueco, o deja", @@ -1327,7 +1411,21 @@ "help.material.assign": "Define de qué están hechos los cuerpos seleccionados, como acero, aluminio o ABS. Usa", "help.mit": "Licencia MIT", "help.notice": "AVISO", + "help.occurrence.move": "Mueve una pieza de ensamblaje solo por las libertades permitidas por sus uniones. Selecciona una pieza", "help.parameters.change": "Abre la tabla de valores y expresiones con nombre que controlan las dimensiones del", + "help.pointcloud.insert": "Inserta un escaneo PLY, XYZ o PTS como nube de puntos junto al modelo. Úsala como", + "help.sketch.construction_line": "Crea una línea de construcción infinita a través de dos puntos. Úsala para organizar un boceto.", + "help.sketch.construction_line.angle": "Crea una línea de construcción infinita en un ángulo desde el eje X del boceto. Elige el punto a", + "help.sketch.construction_line.bisector": "Elige dos líneas rectas de boceto que se intersecten, luego elige una de las dos bisectrices del ángulo.", + "help.sketch.construction_line.horizontal": "Crea una línea de construcción horizontal infinita a través de un punto. Su dirección horizontal", + "help.sketch.construction_line.parallel": "Elige una línea recta de boceto, luego coloca una línea de construcción paralela infinita. R", + "help.sketch.construction_line.perpendicular": "Elige una línea recta de boceto, luego coloca una línea de construcción perpendicular infinita.", + "help.sketch.construction_line.tangent_at": "Crea una tangente en un punto de un círculo o arco circular, o en un extremo de una curva abierta.", + "help.sketch.construction_line.tangent_external": "Elige un círculo o arco circular, luego un punto externo y una solución de tangente. Th", + "help.sketch.construction_line.tangent_two": "Elige dos círculos o arcos circulares, luego elige una tangente común en la previsualización.", + "help.sketch.construction_line.vertical": "Crea una línea de construcción vertical infinita a través de un punto. Su dirección vertical", + "help.sketch.equation_curve": "Dibuja una curva a partir de fórmulas: x(t) e y(t), o y = f(x), sobre un rango. La fórmula", + "help.sketch.inspect": "Abre un informe sobre el boceto abierto: cuántos grados de libertad quedan y qué", "help.solid.align": "Mueve los cuerpos seleccionados para que un punto, cara o plano de ellos coincida con un punto,", "help.solid.chamfer": "Corta las aristas seleccionadas con un chaflán plano de la distancia que indiques. Úsalo para romper aristas vivas o para facilitar la entrada de un pasador o un tornillo.", "help.solid.combine": "Combina cuerpos: los une, los recorta de un cuerpo de destino o conserva solo el volumen que comparten, y puede mantener los cuerpos de herramienta. Úsalo para fusionar piezas, recortar una forma con otra o encontrar dónde se solapan dos cuerpos.", @@ -1353,6 +1451,9 @@ "help.third_party": "Licencias de terceros", "help.timeline.compute_all": "Reconstruye cada operación de la línea de tiempo desde el inicio. Úsalo para refrescar el modelo", "help.timeline.delete": "Elimina las operaciones seleccionadas de la línea de tiempo; borrar un boceto también elimina", + "help.timeline.play": "Reproduce las operaciones restantes una a una, con una pausa de medio segundo tras cada una", + "history.sketch_under_constrained": "Bajo restricción ({count} grados de libertad)", + "history.sketch_under_constrained_one": "Bajo restricción ({count} grado de libertad)", "hole_presets.confirm_delete": "Confirmar eliminación", "hole_presets.delete": "Eliminar", "hole_presets.delete_prompt": "Eliminar esta preconfiguración personal? Los agujeros existentes no cambian.", @@ -1453,9 +1554,26 @@ "joint.one_component": "Estas piezas son cuerpos de un mismo componente: {bodies}. Una unión mueve un componente respecto a otro, por lo que cada pieza debe tener su propio componente.", "joint.rigid_group_one_component": "Estos {count} cuerpos están todos en un componente (o en el propio diseño): usa antes {command}.", "joint.rigid_group_select_components": "Selecciona dos o más componentes.", + "joint_move.blocked_hint": "Comprueba el tipo de unión (como Rígida), anclaje, límites de la unión y accionamientos por parámetro", + "joint_move.blocked_title": "No se puede mover esta pieza", + "joint_move.coarse": "Paso de rotación cerca del eje (°)", + "joint_move.distance": "Distancia desde el inicio", + "joint_move.done": "Listo", + "joint_move.fine": "Paso de rotación lejos del eje (°)", + "joint_move.fixed": "Esta pieza no tiene eje de unión móvil.", + "joint_move.help": "Mover — arrastra una flecha o anillo. Esc cancela el arrastre actual.", + "joint_move.legacy_hint": "Desactiva para usar el panel Mover anterior.", + "joint_move.precision": "Tira fuera de la guía discontinua para rotación fina.", + "joint_move.rotation": "Rotación desde el inicio", + "joint_move.select": "Selecciona una cara o una pieza de ensamblaje, luego elige Mover.", + "joint_move.settings": "Mover ensamblaje", + "joint_move.step": "Paso", + "joint_move.use_handles": "Usar mangos de movimiento de unión para Mover ensamblaje", "keymap.command_id": "ID del comando", "keymap.empty": "No hay comandos coincidentes", "keymap.use_anyway": "Usar {key} aquí de todos modos", + "label.move_to_left_side": "Mover a la izquierda", + "label.move_to_right_side": "Mover a la derecha", "manage.appearance_hint": "Elija una apariencia para la selección o arrastre una muestra a un cuerpo o una cara.", "manage.assign_hint": "Seleccione cuerpos y elija su regla de diseño de piezas de plástico.", "manage.config_hint": "Edite las filas, columnas y reglas de configuración y luego active una fila o muestre su vista previa.", @@ -1510,6 +1628,10 @@ "material.selection.mixed": "Materiales distintos", "measure.at": "En", "measure.item": "Elemento {number}", + "measure.quick_copied": "Medición copiada", + "measure.quick_copy": "Haz clic para copiar la medición", + "measure.quick_edges": "{count} aristas", + "measure.quick_faces": "{count} caras", "messages.ago_h": "hace {n} h", "messages.ago_min": "hace {n} min", "messages.ago_s": "hace {n} s", @@ -1540,9 +1662,13 @@ "nav.free_orbit_upright.help": "Arrastrar el ratón de lado gira el modelo alrededor del eje vertical del mundo; arriba y abajo", "nav.free_orbit_upright.label": "Girar alrededor del eje vertical", "nav.fusion.help": "Arrastrar con el botón central desplaza, Mayús+central orbita y arrastrar con el derecho orbita", + "nav.hfss.help": "Alt+arrastre izq. desplaza, Mayús+Alt+arrastre izq. hace zoom, Ctrl+arrastre izq. en espacio vacío orbita", "nav.inventor.help": "Arrastrar con el botón central desplaza, Mayús+central orbita, Ctrl+central hace zoom y arrastrar con el derecho orbita", + "nav.maya.help": "Alt+arrastre izq. orbita, Alt+arrastre central desplaza, Alt+arrastre der. hace zoom; arrastre central también desplaza", "nav.openscad.help": "Arrastrar con el botón izquierdo sobre un espacio vacío orbita, Mayús+izquierdo selecciona con un recuadro y arrastrar geometría del boceto la edita; arrastrar con el derecho o el central desplaza, y Mayús+derecho o Mayús+central hace zoom", "nav.perspective.sketch": "La edición de bocetos usa vista ortográfica. Termina el boceto para cambiar a perspectiva.", + "nav.right_drag_orbits.help": "Desactivado: un arrastre derecho deja la cámara sola y el botón derecho solo abre el menú contextual", + "nav.right_drag_orbits.label": "Arrastre derecho orbita", "nav.solidworks.help": "Arrastrar con el botón central orbita, Ctrl+central desplaza, Mayús+central hace zoom y arrastrar con el derecho orbita", "nav.tinkercad.help": "Arrastrar con el botón derecho orbita; con el central o con Mayús+derecho desplaza", "nav.touchpad.help": "Mantén pulsado Mayús y mueve el puntero para encuadrar; mantén Alt/Opción y muévelo para orbitar. No hace falta pulsar ningún botón del ratón. El desplazamiento vertical hace zoom.", @@ -1551,9 +1677,96 @@ "nav.touchpad.pan": "Desplazar (mantén Mayús y mueve el puntero; sin pulsar botones)", "nav.touchpad.scroll": "El panel táctil usa el desplazamiento vertical para hacer zoom. La opción de desplazamiento con dos dedos se conserva para otros ajustes predefinidos.", "nav.touchpad.zoom": "Zoom (desplazamiento vertical o gesto de pellizco)", + "navbar.agent_chat": "Panel de chat del Asistente", + "navbar.agent_cursor": "Mostrar cursor del agente", + "navbar.ambient_occlusion": "Oclusión ambiental", + "navbar.assistant": "Asistente", + "navbar.custom.add_slot": "Añadir {slot}", + "navbar.custom.always": "Siempre visible", + "navbar.custom.available": "{available} · arrastra a la barra, o pulsa Añadir", + "navbar.custom.buttons": "Botones", + "navbar.custom.compact": "Compacto", + "navbar.custom.count": "{count} de 16 huecos", + "navbar.custom.customise": "Personalizar barra de navegación…", + "navbar.custom.design": "Diseño", + "navbar.custom.duplicate": "Este hueco ya está en la barra.", "navbar.custom.edge": "Borde", "navbar.custom.edge_bottom": "Abajo", "navbar.custom.edge_top": "Arriba", + "navbar.custom.fade": "Desvanecer", + "navbar.custom.full": "Quita un hueco para añadir otro.", + "navbar.custom.hidden_design": "Oculto en Diseño", + "navbar.custom.hidden_render": "Oculto en Render", + "navbar.custom.hide": "Ocultar barra de navegación", + "navbar.custom.hide_idle": "Ocultar hasta pasar el ratón", + "navbar.custom.icon_only": "Solo icono", + "navbar.custom.icon_value": "Icono y valor", + "navbar.custom.icons": "Iconos", + "navbar.custom.idle": "En reposo", + "navbar.custom.intro": "Elige los controles en la barra en la parte inferior de la vista 3D, y en qué orden.", + "navbar.custom.labels": "Iconos y etiquetas", + "navbar.custom.left": "Mover a la izquierda", + "navbar.custom.position": "Posición", + "navbar.custom.position_centre": "Centro", + "navbar.custom.position_left": "Izquierda", + "navbar.custom.position_right": "Derecha", + "navbar.custom.preview_as": "Previsualizar como", + "navbar.custom.regular": "Normal", + "navbar.custom.remove": "Eliminar", + "navbar.custom.remove_bar": "Quitar de la barra", + "navbar.custom.render": "Render", + "navbar.custom.reset": "Restablecer barra de navegación", + "navbar.custom.reset_default": "Restablecer a predeterminado", + "navbar.custom.right": "Mover a la derecha", + "navbar.custom.select": "Ningún hueco seleccionado. Selecciona un hueco en la barra para moverlo, quitarlo o cambiar cómo se muestra.", + "navbar.custom.separators_full": "La barra ya tiene cuatro separadores.", + "navbar.custom.show": "Mostrar barra de navegación", + "navbar.custom.shows": "Muestra", + "navbar.custom.size": "Tamaño", + "navbar.custom.stale": "La barra cambió. Selecciona el hueco de nuevo.", + "navbar.custom.title": "Barra de navegación", + "navbar.custom.unknown": "Este hueco no está disponible.", + "navbar.description.ambient_occlusion": "Oscurece pliegues y esquinas para dar profundidad.", + "navbar.description.display": "Contiene los ajustes de vista: preestablecido gráfico, rejilla, sombra de suelo, oclusión ambiental", + "navbar.description.fit": "Encuadra la selección, o todo el modelo si no hay nada seleccionado.", + "navbar.description.grid": "Muestra u oculta la rejilla de suelo.", + "navbar.description.ground_shadow": "Muestra u oculta la sombra bajo el modelo.", + "navbar.description.home": "Vuelve a la vista isométrica del modelo completo.", + "navbar.description.look_at": "Gira la vista para que mire la cara, plano o boceto abierto seleccionado.", + "navbar.description.orbit": "Gira la vista alrededor del modelo.", + "navbar.description.pan": "Desliza la vista lateral, arriba o abajo.", + "navbar.description.projection": "Cambia entre vistas ortográfica y perspectiva.", + "navbar.description.separator": "Una línea fina que agrupa huecos vecinos.", + "navbar.description.spin": "Mantiene la vista girando hasta que haces clic o pulsas una tecla.", + "navbar.description.visual_style": "Cambia cómo se dibuja el modelo: sombreado, alambre o con aristas ocultas.", + "navbar.description.zoom": "Acerca o aleja la vista del modelo.", + "navbar.display": "Visualización", + "navbar.fit": "Ajustar", + "navbar.graphics": "Gráficos", + "navbar.grid": "Rejilla", + "navbar.ground_shadow": "Sombra de suelo", + "navbar.home": "Inicio", + "navbar.later": "Luego", + "navbar.look_at": "Mirar", + "navbar.more": "Más", + "navbar.orbit": "Orbitar", + "navbar.orthographic": "Ortográfica", + "navbar.pan": "Desplazar", + "navbar.perspective": "Perspectiva", + "navbar.preset": "Preestablecido", + "navbar.projection": "Proyección", + "navbar.projection_heading": "Proyección", + "navbar.separator": "Separador", + "navbar.show": "Mostrar", + "navbar.spin": "Giro continuo", + "navbar.style.shaded": "Sombreado", + "navbar.style.shaded_with_edges": "Sombreado con aristas", + "navbar.style.shaded_with_hidden_edges": "Sombreado con aristas ocultas", + "navbar.style.wireframe": "Alambre", + "navbar.translucent": "Translúcido", + "navbar.value_tip": "{name} · {value}", + "navbar.visual_style": "Estilo visual", + "navbar.zoom": "Zoom", "needs two joints": "necesita dos uniones", "network.allow_once": "Permitir una vez", "network.always_allow": "Permitir siempre este servidor", @@ -1571,25 +1784,42 @@ "not a move": "no es un movimiento", "not a number": "no es un número", "open a sketch first": "abre primero un boceto", + "parameters.apply_live": "Aplicar en vivo", + "parameters.apply_live_tip": "Aplica los cambios de parámetros mientras los editas", + "parameters.held": "Mantenidos ({count})", + "parameters.held_hint": "Parámetros mantenidos durante la edición", + "parameters.held_one": "Uno mantenido", "parts.automatic_name": "automático", "parts.dimension.across_flats": "Entrecaras", "parts.dimension.bore": "Diámetro interior", + "parts.dimension.d": "Diámetro nominal", "parts.dimension.head_diameter": "Diámetro cabeza", "parts.dimension.head_height": "Altura cabeza", "parts.dimension.height": "Altura", "parts.dimension.inner": "Diámetro interior", "parts.dimension.outer": "Diámetro exterior", + "parts.dimension.pitch": "Paso", "parts.dimension.socket": "Hexágono interior", "parts.dimension.socket_depth": "Profundidad hexágono", "parts.dimension.thickness": "Espesor", "parts.dimension.width": "Anchura", "parts.family.bearing": "Rodamiento rígido de bolas (envolvente)", + "parts.family.button_head_cap_screw": "Tornillo cabeza botón", "parts.family.dowel_pin": "Pasador cilíndrico", "parts.family.hex_bolt": "Tornillo de cabeza hexagonal", + "parts.family.hex_cap_screw_inch": "Tornillo de cabeza hexagonal (pulgadas)", "parts.family.hex_nut": "Tuerca hexagonal", + "parts.family.hex_nut_inch": "Tuerca hexagonal (pulgadas)", "parts.family.set_screw": "Prisionero con hexágono interior, punta plana", "parts.family.socket_head_cap_screw": "Tornillo cilíndrico con hexágono interior", "parts.family.washer": "Arandela plana", + "parts.family.washer_sae": "Arandela plana, SAE (estrecha)", + "parts.family.washer_uss": "Arandela plana, USS (ancha)", + "parts.holes": "Agujeros (opcional)", + "parts.placement_hint": "elige uno o más agujeros para colocar una pieza en cada uno, o Aceptar la coloca en el origen", + "parts.system": "Sistema de unidades", + "parts.system.inch": "Pulgadas", + "parts.system.metric": "Métrico", "pattern.alignment_2": "Alineación 2", "pattern.alignment_hint": "Los recuentos incluyen el original. Centrar equilibra las copias; Invertir elige el lado adicional cuando el total es par.", "pattern.direction_1": "Dirección 1", @@ -1630,10 +1860,22 @@ "prefs.anti_aliasing_note": "Suaviza los bordes dentados.", "prefs.applies_on_restart": "Se aplica al reiniciar", "prefs.assistant": "Asistente", + "prefs.auto_operation": "Elegir la operación automáticamente", + "prefs.auto_operation_note": "Las ventanas de operación eligen Unir, Nuevo cuerpo o Cortar según lo que toque el nuevo material, u", "prefs.axes": "Ejes", "prefs.axis": "Eje", + "prefs.bodies_folders": "Carpetas de cuerpos", + "prefs.bodies_folders_always": "Siempre", + "prefs.bodies_folders_never": "Nunca", + "prefs.bodies_folders_several": "Solo varios cuerpos", "prefs.bottom": "Abajo", + "prefs.bottom_centre": "Centro abajo", + "prefs.bottom_right": "Derecha abajo", "prefs.browser": "Explorador", + "prefs.browser_components_open": "Componentes abiertos al inicio", + "prefs.browser_components_open_note": "Cada componente del explorador empieza abierto, como antes, en lugar de cerrado hasta que lo abras.", + "prefs.browser_eye_left": "Ojo junto a la flecha de plegado", + "prefs.browser_eye_left_note": "Las filas del explorador muestran su ojo de mostrar/ocultar junto a la flecha de plegado, como antes, en lugar de", "prefs.browser_reveal_on_hover": "Mostrar al pasar el puntero", "prefs.browser_show_note": "Visible mantiene el navegador en pantalla. Mostrar al pasar el puntero lo oculta hasta que el puntero llega a su lugar o a la pestaña fina de su borde izquierdo, y sigue abierto mientras el puntero está dentro o hay un menú suyo abierto.", "prefs.browser_shown": "Visible", @@ -1684,9 +1926,13 @@ "prefs.graphics_card_restart": "Surte efecto al reiniciar SolidCraft. WGPU_ADAPTER_NAME tiene prioridad sobre esta opción.", "prefs.graphics_note": "Cambia velocidad por suavidad. Cada opción muestra su efecto en una muestra.", "prefs.graphics_presets_note": "Los preajustes configuran juntas las opciones de abajo.", + "prefs.hide_constraint_glyphs_zoomed_out": "Ocultar glifos de restricción al hacer zoom out", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Los glifos de restricción salen de la vista cuando el boceto tiene suficiente zoom out como para que", "prefs.history": "Historial", "prefs.history_origin_bodies": "Mostrar origen y cuerpos al principio", "prefs.history_origin_bodies_note": "El Historial a la izquierda o bajo el explorador empieza con la carpeta Cuerpos del componente activo y el Origen, con sus ojos y menús como en el explorador. El Historial en la parte inferior no cambia.", + "prefs.history_play_button": "Botón Reproducir historial en los controles del Historial", + "prefs.history_play_button_note": "Pone Reproducir historial entre Retroceder un paso y Avanzar un paso en el Historial", "prefs.history_sketches": "Bocetos", "prefs.history_sketches_in_order": "En orden", "prefs.history_sketches_note": "Con Bocetos en Debajo de su operación, el Historial de la izquierda lista cada boceto un nivel dentro, bajo la primera operación construida a partir de él, siempre que haya ancho para nombres. La línea de tiempo en la parte inferior mantiene siempre el orden de creación.", @@ -1694,6 +1940,7 @@ "prefs.hold_stop_snapping": "Mantén pulsado para desactivar el ajuste", "prefs.icons_only": "Solo iconos", "prefs.imported_file": "Archivo importado", + "prefs.in_browser": "En explorador", "prefs.input": "Entrada", "prefs.interface": "Interfaz", "prefs.interface_language": "Idioma de la interfaz", @@ -1704,8 +1951,14 @@ "prefs.layout_note": "Compacta acopla los paneles a los bordes de la ventana. La translucidez del explorador solo está disponible en Flotante. Cambia el lado del Asistente en la página Asistente.", "prefs.left": "Izquierda", "prefs.left_click": "Clic izquierdo", + "prefs.line_drag_draws_one": "Pulsar y arrastrar dibuja una línea", + "prefs.line_drag_draws_one_note": "En la herramienta Línea, pulsar, arrastrar y soltar dibuja una línea desde el punto", + "prefs.linked_designs": "Diseños vinculados", "prefs.live_input": "Entrada en vivo", "prefs.live_preview": "Vista previa en vivo", + "prefs.logo": "Logotipo", + "prefs.logo_accent": "Acento", + "prefs.logo_theme": "Colores del tema", "prefs.max_file_size": "Tamaño máximo de archivo al abrir", "prefs.max_file_size_design": "Archivos de diseño", "prefs.max_file_size_flag": "Esta ejecución se inició con --max-file-size {size}, que se aplica hasta cerrar SolidCraft. Estos ajustes se aplican al iniciar sin esa opción.", @@ -1713,6 +1966,9 @@ "prefs.max_file_size_step": "Archivos STEP y de importación", "prefs.max_file_size_web": "La aplicación web abre archivos STEP y de importación de hasta 512 MB y diseños de hasta 256 MB: una pestaña del navegador no admite archivos mayores. La aplicación de escritorio permite aumentar estos límites.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Iconos grandes", + "prefs.menu_list": "Lista", + "prefs.menus": "Menús", "prefs.minutes": "minutos", "prefs.minutes_suffix": " min", "prefs.mouse": "Ratón y panel táctil", @@ -1732,38 +1988,98 @@ "prefs.origin_plane_names": "Nombres de los planos de origen", "prefs.origin_plane_names_note": "Nombres que se muestran en el explorador, diálogos y listas. {top} es XY, {front} es XZ y {right} es YZ", "prefs.overall_speed": "Velocidad general", + "prefs.parameter_list_rows": "Filas de la lista de parámetros", + "prefs.parameter_list_rows_tip": "Número de filas visibles en la lista de parámetros", + "prefs.persistent_ribbon_pressed": "Resaltar comandos activos de la cinta", + "prefs.persistent_ribbon_pressed_help": "Resaltar comandos de la cinta mientras sus efectos están activos. Desactivar para mantener el comportamiento anterior.", + "prefs.perspective_fov": "Campo de visión", "prefs.placement": "Colocación", "prefs.prefer_free_sketch_points": "Preferir los puntos de boceto móviles cuando los puntos se solapan", "prefs.preview_choices": "Vista previa de tus opciones", + "prefs.print_face_highlight": "Resalte de cara de impresión", + "prefs.print_face_highlight_tip": "Con qué intensidad se tiñe y contornea la cara de impresión de un cuerpo en la vista. 0 % s", + "prefs.profile_active": "Perfil activo", + "prefs.profile_applied": "Perfil aplicado", + "prefs.profile_changed": "Ajustes cambiados desde que se guardó el perfil. Guardar los mantiene en él.", + "prefs.profile_deleted": "Perfil eliminado.", + "prefs.profile_export": "Exportar perfil", + "prefs.profile_exported": "Perfil exportado.", + "prefs.profile_imported": "Perfil importado. Elígelo en Perfil activo para cambiar a él.", + "prefs.profile_name_hint": "Nombre del perfil, p. ej. Portátil", + "prefs.profile_rename": "Renombrar", + "prefs.profile_renamed": "Perfil renombrado.", + "prefs.profile_save": "Guardar", + "prefs.profile_saved": "Los ajustes actuales se han guardado en el perfil.", + "prefs.profile_skipped": "Perfil aplicado; {n} ajuste(s) conservaron su valor actual (ver registro).", + "prefs.profiles": "Perfiles de ajustes", + "prefs.profiles_note": "Atajos, barra de herramientas, navegación, menú radial y ajustes de interfaz, agrupados bajo un nombre y conmutables de una vez.", + "prefs.project_options_dialog": "Diálogo de opciones del proyecto", + "prefs.project_options_dialog_note": "Activado: elegir Geometría o Cuerpos y Vinculación de proyección antes de proyectar. Desactivado: mantener el flujo directo anterior.", "prefs.quality_default": "predeterminada", "prefs.quality_fastest": "la más rápida", "prefs.quality_slowest": "la más lenta", "prefs.quality_smoother": "más suave", + "prefs.quick_measure": "Medición rápida en la esquina de la vista", + "prefs.quick_measure_note": "El tamaño de la selección en la esquina inferior derecha de la vista: longitud de una arista, o Ø un", + "prefs.render_previous_geometry_budget": "Usar presupuesto de geometría previo de Render", + "prefs.render_previous_geometry_budget_help": "Restaurar el límite fijo previo (512 MiB en escritorio de 64 bits, 128 MiB en otros) en lugar del presupuesto basado en dispositivo.", "prefs.reports_saved": "{n} guardados", + "prefs.ribbon_reveal": "Mostrar resultados en la cinta", + "prefs.ribbon_reveal_note": "Al pasar el ratón por un resultado en Buscar comandos se muestra dónde está en la cinta: su pestaña, su botón o su fila en el desplegable de un panel. Un comando iniciado desde la búsqueda parpadea allí, y uno en ejecución desde un desplegable marca su panel.", "prefs.right_click": "Clic derecho", "prefs.saving": "Guardado automático y recuperación", "prefs.scale_note": "También Ctrl + / Ctrl − en la ventana. Los botones miden 28 px al 100%.", "prefs.scale_text": "Escala y texto", + "prefs.search": "Buscar preferencias", + "prefs.search_empty": "Sin coincidencias", "prefs.select": "Seleccionar", "prefs.select_one_item": "Selecciona un elemento", + "prefs.select_other_hidden": "Seleccionar geometría oculta con Seleccionar otro", + "prefs.select_other_hidden_help": "Activado: incluir cuerpos, bocetos y aristas ocultas u ocluidas cerca del puntero. Desactivado: us", "prefs.selecting": "Selección", "prefs.shift": "Mayús", "prefs.shift_add_ctrl_toggle": "Mayús solo añade; Ctrl/Cmd alterna", "prefs.shift_add_note": "Activado: Mayús añade y Ctrl/Cmd alterna. Desactivado (predeterminado): ambos alternan.", "prefs.shortcuts": "Atajos de teclado", + "prefs.single_surface_analysis": "Usar un solo análisis de superficie", + "prefs.single_surface_analysis_help": "Desactivado: el sombreado de superficie y la Continuidad pueden estar activos juntos. Activado: se mantiene el último análisis iniciado o modificado.", + "prefs.sketch_align_points": "Alinear con otros puntos del boceto al dibujar", + "prefs.sketch_align_points_note": "Al dibujar, un punto se alinea horizontalmente con un punto del boceto y verticalmente con otro a la vez, con una guía punteada, y el clic mantiene ambas alineaciones. Desactivado: solo con el punto anterior, un eje a la vez.", + "prefs.sketch_conflict_colour": "Geometría conflictiva en el color de conflicto", + "prefs.sketch_conflict_colour_note": "Mientras las restricciones de un boceto entran en conflicto, las curvas y puntos que una restricción fallida sujeta se dibujan en el color de conflicto, no solo su glifo o cota. Desactivado: conservan sus colores habituales.", + "prefs.sketch_construction_lines": "Herramientas extendidas de líneas de construcción", "prefs.sketch_exit_view": "Al terminar un boceto", "prefs.sketch_exit_view.keep": "Mantener la vista actual", "prefs.sketch_exit_view.previous": "Volver a la vista anterior", "prefs.sketch_exit_view.unless_rotated": "Volver salvo que se haya rotado", "prefs.sketch_exit_view_note": "A dónde va la vista tras Terminar boceto, Cancelar o doble Esc.", + "prefs.sketch_open_look_at": "Girar para mirar el boceto al abrirlo", + "prefs.sketch_open_look_at_note": "Desactivado: crear o editar un boceto deja la vista como está. Mirar orienta la vista hacia la cara del boceto.", + "prefs.sketch_recent_snap": "Auto-ajuste a centros y puntos medios recientes", + "prefs.sketch_recent_snap_note": "Al dibujar, ajusta el cursor donde las guías de los dos centros de círculo más recientes", "prefs.sketch_selection": "Boceto y selección", "prefs.sketch_selection_heading": "Boceto y selección", "prefs.sketch_selection_note": "Cómo se ajustan los bocetos y cómo seleccionan los clics.", + "prefs.sketch_state_icons": "Iconos de boceto en el color de su estado", + "prefs.sketch_state_icons_note": "En Historial y el explorador, el icono de un boceto toma el color de su estado (bajo restricción, totalmente restringido o en conflicto) y su info muestra el estado. Desactivado: todos los bocetos tienen el mismo icono.", + "prefs.sketch_tab_always": "Mantener la pestaña Boceto visible", + "prefs.sketch_tab_always_note": "La pestaña Boceto permanece en la cinta, tras Modelo, mientras no haya ningún boceto abierto. Sus herramientas de dibujo inician un boceto en el plano o cara seleccionados, o en el que elijas a continuación, con la herramienta lista.", + "prefs.sketch_tracking_guides": "Guías de alineación a centro y punto medio", + "prefs.sketch_tracking_guides_note": "Al pasar el ratón por el centro de un círculo o el punto medio de un borde recto, muévete horizontal o verticalmente para mostrar una guía punteada temporal.", + "prefs.sketch_tracking_points": "Guías de alineación desde extremos y esquinas al dibujar", + "prefs.sketch_tracking_points_note": "Mientras una herramienta de dibujo espera un punto, al pasar el ratón por el extremo de una línea o un arco, la esquina de un rectángulo o un punto libre se muestra la misma guía punteada temporal que en un centro o punto medio. Desactivado: solo centros y puntos medios.", "prefs.sketching": "Bocetos", "prefs.snap_drawing_note": "Mientras dibujas o arrastras un punto del boceto.", "prefs.source": "Origen", "prefs.speed": "Velocidad", "prefs.stand_up_note": "Cuando un archivo STEP o IGES se abre con Z hacia arriba, ofrece un cuarto de giro sobre X.", + "prefs.stand_up_unknown": "Para archivos de programas desconocidos", + "prefs.stand_up_unknown.ask": "Preguntar en un diálogo", + "prefs.stand_up_unknown.note": "Mostrar aviso", + "prefs.stand_up_unknown.off": "No ofrecer", + "prefs.stand_up_unknown_note": "Cómo se hace la oferta cuando la cabecera del archivo no nombra ningún programa conocido que guarde con Y arriba. El aviso solo se muestra cuando el archivo parece boca abajo; Preguntar en un diálogo pregunta sobre cada uno, como antes.", + "prefs.status_bar": "Barra de estado", + "prefs.status_bar_note": "Una barra fina en el borde inferior de la ventana muestra qué se está editando, el estado del boceto abierto en su color y las unidades del diseño; clic en las unidades las cambia. El estado del boceto ya no se muestra en la esquina de la vista.", "prefs.status_done": "Completado", "prefs.status_error": "Error", "prefs.status_selected": "Seleccionado", @@ -1771,37 +2087,63 @@ "prefs.supersampling_brief": "Dibuja la vista a mayor tamaño y la reduce con un filtro: muy nítida, pero más pesada.", "prefs.tab_accent_note": "El color de acento sigue a la pestaña activa", "prefs.theme_file": "archivo de tema", + "prefs.theme_file_or_paste": "archivo o pegar", "prefs.theme_follow": "Seguir un archivo de tema", "prefs.theme_follow_error": "No aplicado: {error}. Se mantiene el último tema válido.", "prefs.theme_follow_launch": "Solo en esta sesión (--theme-file); se recarga cada vez que otra herramienta reescribe el archivo.", "prefs.theme_follow_note": "Se recarga cada vez que otra herramienta reescribe el archivo. Elegir un tema deja de seguirlo.", "prefs.theme_follow_off": "Desactivado", "prefs.theme_follow_stop": "Dejar de seguir", + "prefs.theme_import_hint": "Haz clic para elegir un archivo de tema, arrastra uno aquí, o pulsa Ctrl+V (Cmd+V en Mac) con un tema copiado", + "prefs.theme_paste": "Pegar tema", + "prefs.theme_paste_none": "El portapapeles no contiene ningún tema de SolidCraft", "prefs.timeline_half_hour": "−30 min", "prefs.timeline_now": "ahora", "prefs.timeline_quarter_hour": "−15", + "prefs.toast_place": "Avisos", "prefs.toggle_item": "Añade el elemento o vuelve a quitarlo", "prefs.toolbar": "Barra de herramientas", + "prefs.toolbar_tabs": "Pestañas de la barra de herramientas", "prefs.top": "Arriba", + "prefs.trackpad_zoom_modifier": "Zoom con scroll de dos dedos manteniendo", + "prefs.trackpad_zoom_modifier.alt": "⌥ / Alt", + "prefs.trackpad_zoom_modifier.cmd": "⌘", + "prefs.trackpad_zoom_modifier.ctrl": "Ctrl", + "prefs.trackpad_zoom_modifier.help": "Mantén solo esta tecla para hacer zoom en el puntero con scroll vertical. Desactivado mantiene el comportamiento de scroll actual.", + "prefs.trackpad_zoom_modifier.off": "Desactivado", "prefs.translucent": "Translúcido", "prefs.under_browser": "Debajo del explorador", "prefs.under_cursor": "Bajo el cursor", "prefs.units_precision": "Unidades y precisión", "prefs.updates": "Actualizaciones", + "prefs.value_boxes_in_view": "Cuadros de valor en la vista", + "prefs.value_boxes_in_view_tip": "Muestra los cuadros de valor de los parámetros en la vista 3D", "prefs.view": "Comportamiento de la vista", "prefs.view_confirm_corner": "Aceptar y Cancelar en la esquina de la vista", "prefs.view_confirm_corner_note": "Mientras un diálogo o un boceto está abierto, una marca y una equis en la esquina superior derecha de la vista hacen lo que el Aceptar y el Cancelar del diálogo, o terminan y cancelan el boceto. El navegador de vistas se mueve debajo.", "prefs.viewport": "Visor", + "prefs.viewport_analysis_status": "Mostrar estado de análisis del visor", + "prefs.viewport_analysis_status_help": "Mostrar análisis activos sobre el visor, abrir sus leyendas desde cada elemento, y", "prefs.viewport_background": "Fondo", "prefs.viewport_background_colour": "Color", "prefs.viewport_background_theme": "Degradado del tema", + "prefs.viewport_section_status": "Estado de la sección del visor", + "prefs.viewport_section_status_help": "Muestra el estado de la sección activa en la barra de estado", + "prefs.viewport_status_summary": "Resumen del estado del visor", + "prefs.viewport_status_summary_help": "Muestra un resumen del estado en la barra de estado del visor", "prefs.wheel": "Rueda", "prefs.wheel_trackpad": "Rueda y panel táctil", "prefs.workspace": "Espacio de trabajo", + "prefs.zoom_stop_at_model": "Detener zoom en el modelo", + "prefs.zoom_stop_at_model_tip": "El ratón 3D y el zoom de la app del dispositivo van hacia la superficie central de la vista; el zoom por arrastre mantiene el punto donde empezó el arrastre. Desactivado: el zoom puede atravesar el modelo. Rueda y pellizco usan Zoom al cursor por separado", "prefs.zoom_toward_cursor": "Zoom hacia el cursor", "properties.title": "Propiedades: {name}", "recovery.days_ago": "hace {count} días", "recovery.detail": "{file} · {features} operaciones · autoguardado {when}", + "recovery.discard_all": "Descartar todo", + "recovery.discard_all_detail": "Esto no se puede deshacer.", + "recovery.discard_all_title": "¿Descartar {count} autoguardados?", + "recovery.discard_all_title_one": "¿Descartar 1 autoguardado?", "recovery.hours_ago": "hace {count} h", "recovery.just_now": "justo ahora", "recovery.min_ago": "hace {count} min", @@ -1845,7 +2187,48 @@ "render.aging_upward": "Depósito en caras superiores", "render.all_controls_help": "Inspección de todos los controles. Las secciones permiten editar por contexto sin cambiar la petición subyacente.", "render.all_shots_label": "Todas las tomas", + "render.appearance_editor.absorption": "Absorción", + "render.appearance_editor.base_colour": "Color base", + "render.appearance_editor.body_reason": "Las vinculaciones ópticas afectan a un cuerpo entero. Elige Cuerpo para editar estos controles.", + "render.appearance_editor.boundary": "Límite", + "render.appearance_editor.box": "Caja", + "render.appearance_editor.choose_image": "Elegir imagen…", + "render.appearance_editor.closed": "Sólido cerrado", + "render.appearance_editor.coat": "Capa transparente", + "render.appearance_editor.cpu_reason": "Requiere ray tracing en CPU.", + "render.appearance_editor.glass": "Vidrio y absorción", + "render.appearance_editor.glass_enable": "Usar vidrio físico en este cuerpo", + "render.appearance_editor.glass_note": "El vidrio cerrado usa distancia geométrica. No puede compartir cuerpo con capa transparente o mapas.", + "render.appearance_editor.gpu_reason": "Requiere path tracing en GPU.", + "render.appearance_editor.ior": "IOR", + "render.appearance_editor.maps": "Mapas", + "render.appearance_editor.normal": "Normal", + "render.appearance_editor.normal_strength": "Intensidad de normal", + "render.appearance_editor.origin": "Origen", + "render.appearance_editor.recipe": "Receta", + "render.appearance_editor.reflection_sampling": "Muestreo para todos los cuerpos reflectivos", + "render.appearance_editor.reflections": "Reflexiones", + "render.appearance_editor.remove": "Eliminar guardado", + "render.appearance_editor.remove_note": "Elimina la óptica guardada de esta toma. La geometría y los aspectos asignados se conservan.", + "render.appearance_editor.remove_title": "¿Eliminar óptica guardada?", + "render.appearance_editor.replace": "Reemplazar la óptica guardada de este cuerpo", + "render.appearance_editor.revalidate": "Revalidar este cuerpo", + "render.appearance_editor.save": "Guardar esta óptica", + "render.appearance_editor.save_reason": "Guardar esta óptica requiere vidrio físico en un cuerpo de GPU actual. La capa y los mapas de imagen locales quedan temporales.", + "render.appearance_editor.saved": "Guardado con esta toma", + "render.appearance_editor.saved_state": "Esta óptica está guardada con esta toma.", + "render.appearance_editor.scatter_reason": "La dispersión interior necesita un límite de sólido cerrado.", + "render.appearance_editor.temporary": "Esta óptica es temporal en esta pestaña. Guárdala para conservarla con la toma.", + "render.appearance_editor.thickness": "Espesor", + "render.appearance_editor.thickness_reason": "El espesor se aplica a láminas finas; el vidrio cerrado usa distancia geométrica.", + "render.appearance_editor.thin": "Lámina fina", + "render.appearance_editor.u_repeat": "Repetición U", + "render.appearance_editor.v_repeat": "Repetición V", + "render.appearance_editor.v_up": "Textura V hacia arriba", + "render.appearance_editor.weight": "Peso", "render.appearance_physics_separate": "El aspecto visual no asigna densidad, propiedades térmicas ni otros datos de ingeniería.", + "render.appearances": "Aspectos", + "render.assign_help": "Haz clic para aplicar a la selección; arrastra para previsualizar y soltar, o haz clic sin selección para pintar.", "render.availability_native": "Composición nativa; revisar antes de aplicar", "render.availability_projection": "Proyección compatible; consulta alcance y omisiones", "render.availability_reference": "Datos de referencia; no es una asignación automática", @@ -1884,6 +2267,7 @@ "render.bloom_threshold": "Umbral lineal de altas luces", "render.browse_capabilities": "Consultar catálogo completo de capacidades", "render.browse_environments": "Explorar entornos HDR originales", + "render.browse_looks": "Explorar…", "render.browse_native_scenes": "Explorar estudios nativos", "render.browse_physical": "Consultar referencias físicas", "render.browse_quality": "Consultar especificaciones de calidad", @@ -1900,6 +2284,89 @@ "render.camera_set": "Establecer cámara de render", "render.camera_target": "Posición del objetivo · mm", "render.camera_yaw": "Azimut", + "render.category_metal": "Metal", + "render.category_paint": "Pintura", + "render.category_plastic": "Plástico", + "render.category_wood": "Madera", + "render.check_opaque": "Transparencia: solo superficies opacas; se admite alfa de fondo.", + "render.check_sorted_alpha": "Transparencia: aproximación alfa ordenada.", + "render.check_transmission": "Transparencia: transmisión física.", + "render.children.absolute_floor": "Suelo absoluto", + "render.children.adaptive": "Adaptativo", + "render.children.add_look_reason": "Añade un aspecto para editar su estado activado e intensidad.", + "render.children.all_shots": "Todas las tomas", + "render.children.bloom": "Bloom", + "render.children.check": "Comprobar", + "render.children.check_now": "Comprobar ahora", + "render.children.chromatic": "Cromático", + "render.children.compact": "Compacto", + "render.children.contrast": "Contraste", + "render.children.copy_image": "Copiar", + "render.children.copy_job": "Copiar JSON de trabajo", + "render.children.copy_request": "Copiar JSON de petición", + "render.children.coverage_error": "Error de cobertura", + "render.children.cpu": "Ray tracing en CPU", + "render.children.denoise": "Reducir ruido en la imagen final", + "render.children.depth": "Profundidad de trayecto", + "render.children.distortion": "Distorsión", + "render.children.edge_samples": "Muestras de borde", + "render.children.effects_banner": "Estos efectos necesitan path tracing en GPU. Abrir esto nunca cambia el método.", + "render.children.enable_adaptive": "Activar pilotos independientes para editar los límites adaptativos.", + "render.children.enable_bloom": "Activar bloom para editar su intensidad, umbral y radio.", + "render.children.finishing": "Acabado", + "render.children.flare": "Fogonazo", + "render.children.fresnel": "Estratos de Fresnel", + "render.children.ghosts": "Anillos fantasma", + "render.children.glass": "Transporte de vidrio", + "render.children.go_to": "Ir a {editor}", + "render.children.grain": "Grano", + "render.children.halo": "Halo", + "render.children.hdr": "HDR", + "render.children.keep_master": "Conservar máster lineal bruto", + "render.children.last_result": "Último: {number} · {width} × {height} · {phase}", + "render.children.lens_effects": "Efectos de lente", + "render.children.look_summary": "{tone} · {count} aspectos", + "render.children.looks": "Aspectos creativos", + "render.children.memory": "Memoria", + "render.children.method": "Método", + "render.children.minimum": "Mínimo", + "render.children.needs_cpu": "Requiere ray tracing en CPU. Abrir esto nunca cambia el método.", + "render.children.nested": "Dieléctricos anidados certificados", + "render.children.not_checked": "Sin comprobar", + "render.children.path": "Path tracing", + "render.children.pilots": "Muestras piloto", + "render.children.preview": "Carga de previsualización", + "render.children.progressive_reason": "Elige Progresivo para editar su cuenta de muestras y semilla.", + "render.children.radius": "Radio", + "render.children.reflect_depth": "Profundidad de reflexión", + "render.children.reflect_samples": "Muestras de reflexión", + "render.children.regrade": "Regradado", + "render.children.relative_error": "Error relativo", + "render.children.render": "Renderizar", + "render.children.render_shot": "Renderizar toma", + "render.children.renderer": "Renderizador", + "render.children.renderers": "Renderizadores", + "render.children.request": "Esta petición", + "render.children.reset_finishing": "Restablecer acabado", + "render.children.review_quality": "Revisar una especificación de calidad…", + "render.children.rgb_gain": "Ganancia RGB", + "render.children.samples": "Muestras", + "render.children.sampling": "Muestreo", + "render.children.saturation": "Saturación", + "render.children.scene_summary": "{bodies} cuerpos · {triangles} triángulos", + "render.children.seed": "Semilla", + "render.children.sharpening": "Enfoque", + "render.children.single_image": "Imagen única", + "render.children.soft_focus": "Enfoque suave", + "render.children.streak": "Estela", + "render.children.strength": "Intensidad", + "render.children.studio": "Estudio", + "render.children.threshold": "Umbral", + "render.children.tone": "Tono", + "render.children.under_hood": "Bajo el capó", + "render.children.vignette": "Vigneteo", + "render.children.workstation": "Estación de trabajo", + "render.choose_look": "Elige un aspecto en Aspectos primero", "render.chromatic_offset": "Separación cromática", "render.clear_stage": "Eliminar el escenario guardado", "render.copy_request": "Copiar JSON", @@ -1998,6 +2465,145 @@ "render.effects_help": "Combina filtros de color ordenados y efectos de lente en imagen. Render y reedición del máster usan los mismos ajustes guardados. El EXR bruto no cambia. Son controles artísticos originales, no emulaciones calibradas de lentes o películas comerciales.", "render.effects_reset_lens": "Restablecer efectos de lente", "render.effects_seed": "Semilla del patrón", + "render.emitted_axis": "Eje emitido", + "render.env_advanced": "Avanzado", + "render.env_backdrop": "Fondo", + "render.env_backdrop_pending": "La visibilidad del entorno y el desenfoque de fondo no los admite el renderizador todavía.", + "render.env_blur": "Desenfoque", + "render.env_change": "Cambiar", + "render.env_choose_source": "Elige un entorno en Estudios y Entornos antes de editar la iluminación.", + "render.env_clear": "Limpiar", + "render.env_colour": "Color", + "render.env_environments": "Entornos", + "render.env_ground": "Suelo", + "render.env_ground_pending": "El suelo físico recibe sombras como superficie difusa finita. La captura solo de sombras y los reflejos de suelo no se admiten todavía.", + "render.env_intensity": "Intensidad", + "render.env_invalid_edit": "Edición de entorno no válida.", + "render.env_physical_ground": "Suelo físico", + "render.env_preview_help": "Muestra ilustrativa de esfera; no es una previsualización del entorno seleccionado.", + "render.env_reflection": "Reflexión", + "render.env_ring_help": "Arrastra el anillo para rotar la iluminación. Mantén Mayús para saltos de 15°.", + "render.env_rotate": "Rotar", + "render.env_set": "Configurar entorno de render", + "render.env_shadow_catcher": "Capturador de sombras", + "render.env_show_environment": "Mostrar entorno", + "render.env_source": "Fuente", + "render.env_stage_details": "Las ediciones de suelo requieren ray tracing y un solo panel de suelo. Usa Escena para editar otros paneles de escenario.", + "render.env_studios": "Estudios", + "render.environment.albedo": "Albedo", + "render.environment.atmosphere": "Atmósfera", + "render.environment.backdrop_note": "Un fondo solo lo ve la cámara. Nunca ilumina, proyecta sombras ni refleja, y se rechaza con salida transparente.", + "render.environment.blur_pending": "El desenfoque no está disponible: el renderizador no tiene ajuste de desenfoque de fondo.", + "render.environment.builtin": "HDR integrado", + "render.environment.check": "Comprobar archivo", + "render.environment.checked": "Archivo HDR comprobado. Guardar incrusta estos bytes.", + "render.environment.choose": "Elegir HDR…", + "render.environment.constant": "Constante", + "render.environment.cyclorama": "Ciclorama", + "render.environment.embedded": "Guardado dentro de este diseño", + "render.environment.end": "Fin", + "render.environment.extinction": "Extinción", + "render.environment.file": "Archivo", + "render.environment.fit": "Ajustar y guardar suelo", + "render.environment.floor_wall": "Suelo y pared", + "render.environment.gap": "Separación", + "render.environment.gradient": "Gradiente", + "render.environment.gradient_gpu": "El fondo gradiente necesita path tracing en GPU.", + "render.environment.ground": "Suelo y escenario", + "render.environment.hdr": "HDR", + "render.environment.hdr_file": "Archivo HDR", + "render.environment.horizon": "Horizonte", + "render.environment.horizontal": "Horizontal", + "render.environment.keep": "Conservar", + "render.environment.lighting_samples": "Muestras de iluminación", + "render.environment.margin": "Margen de extensión", + "render.environment.max": "Límite máximo", + "render.environment.medium": "Medio participante", + "render.environment.min": "Límite mínimo", + "render.environment.mode": "Modo", + "render.environment.needs_gpu": "Requiere path tracing en GPU.", + "render.environment.none": "Ninguno", + "render.environment.orientation": "Orientación e intensidad", + "render.environment.phase": "Fase", + "render.environment.primaries": "Tratar primarias no especificadas como sRGB lineal", + "render.environment.primaries_gpu": "Interpretar primarias no especificadas necesita path tracing en GPU.", + "render.environment.radial": "Radial", + "render.environment.radial_only": "Centro y radio se aplican al modo Radial.", + "render.environment.reflectance": "Reflectancia", + "render.environment.remove": "Eliminar escenario", + "render.environment.remove_confirm": "¿Eliminar el escenario guardado?", + "render.environment.remove_note": "Elimina los {count} paneles pasivos de esta toma. El fondo de cámara se mantiene.", + "render.environment.replace": "Confirmar reemplazo del escenario existente", + "render.environment.rotation_hdr": "La rotación necesita una fuente HDR para ray tracing en CPU.", + "render.environment.samples_cpu": "Las muestras de iluminación las fija el presupuesto de path tracing en GPU; este ajuste necesita ray tracing en CPU.", + "render.environment.saved_panels": "Paneles guardados {count}", + "render.environment.sky_ground": "Suelo", + "render.environment.sky_note": "Gradiente de cielo original para iluminación; no es una atmósfera calibrada.", + "render.environment.source_raytrace": "Las fuentes de entorno necesitan ray tracing en CPU o GPU.", + "render.environment.stage_raytrace": "Los escenarios físicos necesitan ray tracing en CPU o GPU.", + "render.environment.start": "Inicio", + "render.environment.vertical": "Vertical", + "render.environment.world": "Mundo", + "render.environment.world_pending": "El fondo mundial no está disponible: la visibilidad de cámara del entorno no tiene ajuste guardado aún.", + "render.environment.zenith": "Cenit", + "render.environment_tiles_require_raytrace": "Los entornos requieren ray tracing en CPU o GPU. Selecciónalo en el editor de Salida.", + "render.error_area_samples": "area_samples debe ser 1, 4, 16 o 64", + "render.error_binding_allocation": "no se pudo reservar la vinculación de material", + "render.error_body_bound": "la previsualización del producto supera su límite de cuerpo capturado", + "render.error_checkpoint_dimensions": "las dimensiones del punto de control difieren de la petición capturada", + "render.error_decode_budget": "desbordamiento del presupuesto de decodificación de imagen", + "render.error_denoise_setting": "ajuste de denoising nativo no válido", + "render.error_display_dimensions": "dimensiones de visualización de imagen no válidas", + "render.error_display_fit": "la visualización de imagen no puede ajustarse a este dispositivo", + "render.error_display_height": "desbordamiento de altura de visualización", + "render.error_display_width": "desbordamiento de ancho de visualización", + "render.error_duplicate_face": "aspecto de cara de producto duplicado", + "render.error_export_document": "el documento de exportación de render cambió al elegir su destino", + "render.error_face_cap": "la previsualización del producto supera el límite de admisión de aspectos de cara", + "render.error_finish_gesture": "finaliza el gesto de modelado antes de previsualizar", + "render.error_finish_operation": "finaliza la operación de modelado actual antes de entrar en Render", + "render.error_fixed_preview": "la previsualización de estudio fija requiere exposición 0, rotación de entorno 0 e intensidad 1", + "render.error_geometry_size": "desbordamiento de tamaño de geometría de producto", + "render.error_glass_recipe": "receta de vidrio desconocida", + "render.error_gpu_preview": "la previsualización de producto en GPU no está disponible en este host. Los ajustes guardados siguen disponibles.", + "render.error_gpu_samples": "cuenta de muestras en GPU no admitida", + "render.error_image_dimensions": "las dimensiones de imagen de render no coinciden con su trabajo", + "render.error_image_profile": "la imagen de render supera su perfil de recursos capturado", + "render.error_interactive_command": "comando interactivo de Render no vinculado", + "render.error_job_action": "no es una acción interactiva de trabajo de imagen", + "render.error_job_identity": "identidad de trabajo de render no válida: {error}", + "render.error_library_reply": "respuesta de biblioteca de render no válida", + "render.error_material_binding": "vinculación de material faltante", + "render.error_no_completed_image": "el render no tiene imagen completada", + "render.error_no_geometry": "sin geometría de producto", + "render.error_no_scene": "sin escena de producto", + "render.error_opacity": "opacidad de aspecto de producto no válida", + "render.error_pbr_opacity": "PBR opaco requiere opacidad 1", + "render.error_physical_glass": "la receta seleccionada no es vidrio físico", + "render.error_preview_device": "la previsualización de producto requiere un dispositivo instalado con búfer de profundidad", + "render.error_product_triangle": "triángulo de producto no válido", + "render.error_provisional_identity": "identidad provisional de render o cuenta de muestras no válida", + "render.error_quality_bounds": "la proyección de calidad supera los límites nativos", + "render.error_quality_method": "la proyección de calidad requiere el mismo método GPU explícito", + "render.error_quality_projection": "proyección de calidad nativa no válida", + "render.error_regrade_identity": "identidad de regradado no válida: {error}", + "render.error_scene_bodies": "cuerpos de escena de render faltantes", + "render.error_scene_body_limit": "la escena de render supera su límite de cuerpos", + "render.error_scene_identity": "identidad de escena de render no válida", + "render.error_setup_panicked": "el setup de path tracer en GPU entró en pánico", + "render.error_setup_stopped": "el trabajador de setup se detuvo sin devolver un host", + "render.error_setup_worker": "no se pudo iniciar el trabajador de setup: {error}", + "render.error_source_preview": "la previsualización de fuente supera su sobre de bytes", + "render.error_surface_normals": "PBR requiere normales de superficie no nulas", + "render.error_surface_reply": "respuesta de superficie autorizada no válida", + "render.error_triangle_bound": "la previsualización del producto supera su límite de origen de ocho millones de triángulos", + "render.error_triangle_count": "desbordamiento de cuenta de triángulos de producto", + "render.error_upload_slot": "ranura de subida de previsualización de producto no disponible", + "render.error_vertex_allocation": "falló la asignación de vértices de previsualización de producto", + "render.error_vertex_envelope": "la previsualización del producto supera su sobre de carga de vértices de {limit} MiB; la geometría no se simplificó", + "render.error_vertex_packing": "el empaquetado de previsualización de producto difiere de su carga de vértices admitida", + "render.error_visible_solid": "Crea un sólido visible en Diseño para previsualizarlo aquí.", + "render.exit_focus": "Salir de foco", "render.export_display": "Exportar: PNG de visualización", "render.export_image_label": "Exportar imagen", "render.export_linear": "Exportar: EXR lineal", @@ -2011,6 +2617,34 @@ "render.flare_streak": "Estela estilo anamórfico", "render.flare_strength": "Intensidad del flare", "render.flare_threshold": "Umbral lineal del flare", + "render.fold_browser": "Plegar explorador", + "render.frame_aspect": "Proporción", + "render.frame_centre_mark": "Marca central", + "render.frame_copy_limit": "Sin nombre disponible para toma duplicada", + "render.frame_copy_name": "{name} copia {number}", + "render.frame_custom": "Personalizado", + "render.frame_distance_unit": " × tamaño", + "render.frame_duplicate": "Duplicar", + "render.frame_exposure": "Exposición", + "render.frame_fov": "Campo de visión", + "render.frame_guides": "Guías", + "render.frame_invalid_aspect": "Preestablecido de proporción no válido", + "render.frame_lens": "FOV {fov}° · ≈ {mm} mm", + "render.frame_name": "Nombre", + "render.frame_output_size": "Tamaño de salida", + "render.frame_photo": "3:2 · Foto", + "render.frame_portrait": "4:5 · Retrato", + "render.frame_presets": "Preestablecidos de encuadre", + "render.frame_presets_pending": "Llega con el editor de Toma", + "render.frame_projection": "Proyección", + "render.frame_render_shot": "Renderizar esta toma", + "render.frame_rule_thirds": "Regla de los tercios", + "render.frame_safe_area": "Área segura", + "render.frame_shot_title": "Toma · {name}", + "render.frame_square": "1:1 · Cuadrado", + "render.frame_tall": "9:16 · Vertical", + "render.frame_thirds": "Tercios", + "render.frame_wide": "16:9 · Panorámico", "render.gpu_depth": "Profundidad máxima del trazado", "render.gpu_options_help": "Las muestras, la profundidad, la semilla y la exposición se guardan con esta configuración. Solo se guarda el método de imagen activo.", "render.gpu_path_failed": "Trazado GPU no disponible", @@ -2038,6 +2672,7 @@ "render.heading_results": "RESULTADOS", "render.heading_shots": "TOMAS", "render.hide_shots_label": "Ocultar tira de tomas", + "render.hover_look": "{object} · {look} · clic para seleccionar", "render.image_advanced": "Opciones avanzadas de GPU", "render.image_cancelled": "Renderizado cancelado", "render.image_cancelling": "Cancelando", @@ -2068,11 +2703,43 @@ "render.image_use_largest": "Usar el tamaño máximo para esta proporción:", "render.image_width": "Anchura", "render.include_rig_cards": "Incluir tarjetas y banderas pasivas", + "render.inner_half_angle": "Semángulo interior", "render.inspect_scene": "Actualizar resumen de la escena", "render.inspector": "Inspector", + "render.inspector_advanced": "Avanzado", + "render.inspector_all_users": "Todos los {count} usuarios", + "render.inspector_applies_to": "Se aplica a", + "render.inspector_both_users": "Ambos usuarios", + "render.inspector_chain": "De dónde viene este aspecto", + "render.inspector_colour": "Color", + "render.inspector_edit": "Editar", + "render.inspector_finish": "Finalizar", + "render.inspector_from_material": "Desde Material", + "render.inspector_gloss": "Brillo", + "render.inspector_material": "Material", + "render.inspector_matte": "Mate", + "render.inspector_metal": "Metal", + "render.inspector_opacity": "Opacidad", + "render.inspector_opaque_help": "El acabado y los campos ópticos usan PBR opaco (opacidad 1). Opacidad menor usa sombreado escalar.", + "render.inspector_pick_target": "Elige un objetivo de este tipo para inspeccionar su aspecto.", + "render.inspector_remove": "Eliminar sobreescritura", + "render.inspector_replace": "Reemplazar…", + "render.inspector_reset": "Restablecer", + "render.inspector_satin": "Satén", + "render.inspector_save_library": "Guardar en biblioteca…", + "render.inspector_set_all": "Aspectos mezclados. Editar establece el aspecto en todos los objetivos seleccionados.", + "render.inspector_soon": "Pronto", + "render.inspector_target_limit": "Selecciona como máximo 10000 objetivos para inspeccionar aspectos.", + "render.inspector_textures": "Texturas", + "render.inspector_this_body": "Este cuerpo", + "render.inspector_this_component": "Este componente", + "render.inspector_this_face": "Esta cara", + "render.inspector_this_target": "Este objetivo", + "render.inspector_used_by": "Usado por {count}", "render.keep_editing": "Seguir editando", "render.layer_down": "Bajar", "render.layer_enabled": "Capa activada", + "render.layer_off_suffix": " (apagado)", "render.layer_remove": "Eliminar capa", "render.layer_strength": "Intensidad de capa", "render.layer_up": "Subir", @@ -2080,8 +2747,12 @@ "render.lens_effects_title": "Lente y fotografía", "render.library_all": "Catálogo", "render.library_all_states": "Todos los estados", + "render.library_appearance_available": "Aspecto disponible", + "render.library_applicable": "Recursos aplicables", "render.library_applied": "Variante del recurso aplicada. Comprueba la solicitud completa antes de renderizar.", + "render.library_apply_appearance": "Aplicar aspecto", "render.library_apply_hdr": "Guardar con este entorno HDR", + "render.library_apply_hint": "Clic para aplicar · arrastrar sobre el modelo", "render.library_apply_maps": "Usar mapas de superficie GPU", "render.library_apply_studio": "Guardar la variante de iluminación", "render.library_apply_uniform": "Aplicar aspecto opaco uniforme", @@ -2097,15 +2768,23 @@ "render.library_extent": "Extensión del objeto", "render.library_favorite": "Añadir favorito", "render.library_favorites": "Favoritos", + "render.library_filters": "Catálogo y disponibilidad", + "render.library_grid": "Cuadrícula", "render.library_hdr": "Entornos HDR incluidos", "render.library_hdr_help": "Incorpora el HDR original a la configuración guardada. Convierte explícitamente el origen azimutal; tras guardar no se necesita ningún archivo externo.", + "render.library_in_design": "En Diseño", "render.library_inspect_only": "Selecciona para inspeccionar; no se aplica nada automáticamente. Favoritos e historial pertenecen a la sesión de este documento.", + "render.library_ior": "IOR", "render.library_light_concepts": "Conceptos de iluminación", + "render.library_list": "Lista", "render.library_maps_help": "Los mapas integrados se pueden guardar con fuentes fijadas y una correspondencia local de instancias. Los ajustes ópticos temporales siguen siendo un modo aparte.", "render.library_material_concepts": "Conceptos de materiales", + "render.library_metallic": "Metálico", "render.library_native_scenes": "Estudios nativos", "render.library_next": "Página siguiente", "render.library_omitted": "No incluido", + "render.library_opacity": "Opacidad", + "render.library_other": "Otros aspectos", "render.library_physical_profiles": "Perfiles de referencia física", "render.library_previous": "Página anterior", "render.library_quality_concepts": "Especificaciones de calidad", @@ -2115,6 +2794,7 @@ "render.library_results": "Recursos encontrados", "render.library_rig_help": "Se ajusta una sola vez a un centro y una extensión física explícitos. Los conjuntos completos incluyen tarjetas pasivas; los bloqueos de calibración siguen impidiendo el guardado. Antes de guardar se comprueba una separación conservadora entre emisores y tarjetas.", "render.library_rigs": "Configuraciones de iluminación creadas", + "render.library_roughness": "Rugosidad", "render.library_save_maps": "Guardar los mapas en esta configuración", "render.library_scene_bounds": "Usar los límites de la escena capturada", "render.library_scenes": "Especificaciones de escenas", @@ -2138,17 +2818,96 @@ "render.library_unfavorite": "Quitar favorito", "render.library_uniform_ack": "Usar la aproximación uniforme sin efectos espaciales ni avanzados", "render.library_usable": "Proyecciones ejecutables", + "render.library_users": "Usuarios", + "render.light_aim": "Apuntar a", "render.light_anchor_pending": "Cambiar el sistema de coordenadas de la luz no está soportado aún.", + "render.light_azimuth": "Azimut", + "render.light_backend_limit": "Elige ray tracing en CPU o un estudio GPU explícito para editar luces. Las luces de estudio GPU heredadas permanecen de solo lectura.", + "render.light_behaviour": "COMPORTAMIENTO", + "render.light_default_fill": "Relleno", + "render.light_default_key": "Principal", + "render.light_default_number": "Luz {number}", + "render.light_default_rim": "Contorno", + "render.light_delete": "Eliminar", + "render.light_distance": "Distancia", + "render.light_duplicate": "Duplicar", + "render.light_elevation": "Elevación", + "render.light_gpu_punctual": "Luces Puntual y Focal están disponibles con ray tracing en CPU.", + "render.light_hard_shadow": "Esta luz tiene sombras duras; la suavidad del emisor no está disponible.", + "render.light_intensity": "Intensidad", + "render.light_missing": "Esta luz ya no existe. Selecciona una luz en el Explorador.", + "render.light_place_highlight": "Colocar por destello", + "render.light_place_pending": "La colocación por destello necesita selección de luz en el visor y no se admite todavía.", + "render.light_position": "POSICIÓN", + "render.light_preview_help": "La vista en vivo no tiene sombras; las luces de Área usan una aproximación de muestra central. El render usa el modelo de luz completo.", + "render.light_product_centre": "Centro del producto", + "render.light_size": "Tamaño", + "render.light_softness": "Suavidad", + "render.light_temperature": "Temperatura de color", + "render.light_temperature_help": "Tinte de cuerpo negro aproximado; se guarda como RGB lineal.", + "render.light_type": "Tipo", + "render.light_type_area": "Área", + "render.light_type_point": "Puntual", + "render.light_type_spot": "Focal", + "render.light_type_sun": "Solar", + "render.light_view_only": "Solo y silenciar afectan a esta vista y sus renders; nunca se guardan en el diseño.", + "render.light_world_origin": "Origen mundial", + "render.lighting_aim_point": "Punto de mira", + "render.lighting_apply": "Aplicar preestablecido", + "render.lighting_area_samples": "Muestras de área", + "render.lighting_budget": "Presupuesto", + "render.lighting_budget_help": "Las cuentas son de solo lectura. Añade, duplica o elimina luces para cambiarlas; el método fija los límites.", + "render.lighting_colour": "Color", + "render.lighting_consent": "Reemplazar las luces direccionales con este preestablecido", + "render.lighting_custom": "Luces personalizadas", + "render.lighting_custom_help": "Elegir Personalizado convierte el preestablecido en luces editables, una fila cada una en el árbol.", + "render.lighting_direction": "Dirección X Y Z", + "render.lighting_direction_help": "O escribe una dirección hacia la luz (X Y Z).", + "render.lighting_distance_unit": " × tamaño", + "render.lighting_edge_u": "Vector lateral U", + "render.lighting_edge_v": "Vector lateral V", + "render.lighting_falloff": "Caída", + "render.lighting_falloff_help": "La intensidad se cita en la distancia de referencia.", + "render.lighting_height": "Altura V", + "render.lighting_minimum": "Mínimo", + "render.lighting_mute": "Silenciar esta luz", + "render.lighting_point": "Punto", + "render.lighting_preset": "Preestablecido de estudio", + "render.lighting_preset_cpu": "Los preestablecidos de estudio direccionales requieren ray tracing en CPU. La iluminación GPU usa luces Solar y de Área explícitas.", + "render.lighting_preset_row": "Preestablecido", + "render.lighting_radiance": "Radiancia", + "render.lighting_reference": "Referencia", + "render.lighting_review_help": "Reemplaza la lista de luces direccionales. Conserva luces puntuales y de área, entorno, sombras, cámara y todos los demás ajustes de la toma.", + "render.lighting_review_title": "Revisar preestablecido de iluminación", + "render.lighting_samples_cpu": "Las muestras de luz de área se aplican a ray tracing en CPU.", + "render.lighting_samples_need_area": "Añade una luz de área en CPU para ajustar muestras de área.", + "render.lighting_samples_reason": "Las muestras de área deben ser 1, 4, 16 o 64.", + "render.lighting_shadow_cpu": "El interruptor de sombras requiere ray tracing en CPU. El path tracing en GPU siempre proyecta sombras.", + "render.lighting_shadows": "Proyectar sombras", + "render.lighting_shadows_section": "Sombras y muestreo", + "render.lighting_shape": "Forma", + "render.lighting_solo": "Solo esta luz", + "render.lighting_source": "Fuente", + "render.lighting_source_section": "Fuente de luz", + "render.lighting_spot_preserved": "Esta luz puntual conserva su cono focal guardado hasta que se cambie su tipo.", + "render.lighting_sun_distance": "La dirección solar es independiente de la distancia y el punto de mira.", + "render.lighting_unsupported": "no admitido", + "render.lighting_used": "{used} de {limit}", + "render.lighting_width": "Ancho U", + "render.lighting_world_position": "Mundial X Y Z", "render.lights_fixed_to": "Luces fijadas a", "render.linear_help": "Conserva un máster RGBA de 32 bits en coma flotante antes de la reducción de ruido, exposición, mapeo tonal, filtros y fondo. sRGB lineal/D65, premultiplicado por cobertura. Requiere memoria adicional. Sin compresión ni pases extra.", "render.linear_retain": "Conservar EXR lineal sin procesar", "render.linear_unavailable": "La imagen terminada seleccionada no conserva EXR. Activa la opción antes de renderizar; no se puede recuperar la radiancia original de un PNG.", "render.look_add": "Añadir filtro de color", + "render.look_applied": "Aplicado {name}", "render.look_bleach": "Inspirado en bleach bypass", "render.look_cool": "Frío", "render.look_cyanotype": "Inspirado en cianotipia", "render.look_faded": "Copia desvanecida", + "render.look_material": "Material", "render.look_mono": "Monocromo", + "render.look_pasted": "Aspecto pegado", "render.look_sepia": "Sepia", "render.look_strength": "Intensidad del filtro", "render.look_teal_orange": "Verde azulado / naranja", @@ -2220,12 +2979,42 @@ "render.optics_save": "Guardar esta óptica en la toma", "render.optics_saved": "Objetivos ópticos guardados", "render.optics_saved_help": "La identidad exacta de definición, operación e instancia se conserva al reabrir sin conexión. Los objetivos ausentes, sustituidos u ocultos se rechazan; los materiales de ingeniería no cambian. Guarda o descarta los cambios numéricos antes de quitar un objetivo.", + "render.outer_half_angle": "Semángulo exterior", + "render.output_advanced": "Avanzado", + "render.output_backend_ready": "Listo", + "render.output_check": "Comprobar", + "render.output_check_failed": "Comprobar · error", + "render.output_check_help": "Ejecuta Comprobar para revisar esta petición sin iniciar un render.", + "render.output_check_summary": "Comprobar · Notas: {count}", + "render.output_copy": "Copiar", + "render.output_copy_report": "Copiar informe", + "render.output_destination": "Destino", + "render.output_destination_help": "Elige el archivo de destino al exportar la imagen completada.", + "render.output_dimensions": "Tamaño", + "render.output_effects": "Efectos", + "render.output_export": "Exportar PNG…", + "render.output_exr_unavailable": "La configuración de salida EXR no está disponible aquí. La exportación EXR lineal requiere una imagen GPU completada con máster lineal retenido.", + "render.output_fit": "Ajustar", + "render.output_format": "Formato", "render.output_format_status": "PNG es la imagen final exacta. El EXR opcional de GPU conserva radiancia lineal FLOAT32 antes de los filtros. La exportación no sustituye el resultado por la previsualización ni por otro trabajo.", + "render.output_grading": "Graduación", + "render.output_image": "Imagen", + "render.output_largest": "{width} × {height} máx.", "render.output_lock_ratio": "Bloquear proporción", "render.output_over_budget": "La imagen supera el presupuesto seleccionado. Elige explícitamente otro tamaño o perfil; no se reduce automáticamente.", + "render.output_presets_help": "Formato, calidad y la lista de Comprobar están en el editor de Salida.", + "render.output_quality": "Calidad", + "render.output_quality_waiting": "esperando el contrato de calidad", "render.output_ratio_refused": "La dimensión vinculada supera el límite del método. Se conserva el tamaño anterior; desbloquea la proporción o elige un valor menor.", + "render.output_ready": "Listo para renderizar", + "render.output_run_check": "Ejecutar comprobación", + "render.output_size_limit": "{method}: hasta {dimension} px por lado y {pixels} píxeles. Tamaño máximo que cabe: {width} × {height}.", + "render.output_size_method_profile": "Método: {method}, perfil: {profile}, {width}x{height}", + "render.output_size_ok": "Tamaño OK · {width} × {height} px", + "render.output_size_profile": "Perfil: {profile}, {width}x{height}", "render.output_swap_orientation": "Intercambiar ancho y alto", "render.output_tools_inspector": "Edita el tamaño y el formato en el inspector de Salida.", + "render.output_view_image": "Ver imagen", "render.page_aging": "Envejecimiento y depósitos", "render.page_all": "Todos los controles", "render.page_appearance": "Aspecto", @@ -2238,6 +3027,7 @@ "render.page_output": "Salida", "render.page_scene": "Escena", "render.paint_label": "Pintar", + "render.painting_with": "Pintando con {name}", "render.passive_stage": "Suelo y escenario pasivo", "render.passive_stage_help": "Los paneles pasivos finitos solo pertenecen a las imágenes renderizadas. No añaden cuerpos CAD ni masa. La colocación queda fija tras aplicarlos; si se cruza con los límites del producto, se rechaza. La CPU no proporciona iluminación difusa rebotada.", "render.perspective": "Cámara en perspectiva", @@ -2253,9 +3043,13 @@ "render.physical_prepare_plan": "Preparar el plan de creación (no se aplica)", "render.physical_separate": "La apariencia no identifica el material. Son referencias con fuente, no propiedades efectivas certificadas. La masa, los materiales de ingeniería y la óptica existentes no cambian.", "render.physical_unknown": "No se ha establecido ningún candidato numérico. Hay que especificar el grado, la formulación o la construcción; desconocido no significa cero.", + "render.pick_body": "Cuerpo", "render.pick_component": "Componente", + "render.pick_face": "Cara", + "render.pick_help": "Elige Cuerpo, Cara o Componente. Haz clic en espacio vacío para limpiar; Mayús o Ctrl añade o alterna. Los destellos solo aparecen en la vista de producto en vivo.", "render.pick_label": "Seleccionar", "render.pick_up_label": "Tomar", + "render.pick_up_prompt": "Haz clic en un objeto para tomar su aspecto", "render.pick_waiting": "La selección de producto no está soportada aún.", "render.post_contrast": "Contraste", "render.post_gain_b": "Ganancia azul", @@ -2275,21 +3069,41 @@ "render.preview_upload": "Datos de vértices de la vista previa", "render.preview_upload_help": "Bytes exactos de los vértices de vista previa, no memoria total de GPU o proceso. No se simplifica la geometría. Los trabajos de imagen tienen admisión e iluminación propias.", "render.progressive_image_summary": "Vista previa PNG · PBR opaco · muestreo progresivo", + "render.property_conditions": "Condiciones: {value}", + "render.property_fallback": "propiedad", + "render.property_qualifier": "Calificador: {value}", + "render.property_source": "Fuente: {id} - {locator}", + "render.property_uncertainty": "Incertidumbre: {value}", + "render.property_unknown": "desconocido", "render.quality_ack": "Aceptar la proyección de presupuesto fijo y sus omisiones", "render.quality_apply": "Usar este presupuesto fijo", + "render.quality_balanced": "Equilibrado", + "render.quality_custom": "Personalizado", + "render.quality_draft": "Boceto", + "render.quality_high": "Alto", "render.quality_projection_help": "Los perfiles Q incluyen requisitos futuros. Esta acción proyecta solo un presupuesto PNG de muestras fijas y omite parada adaptativa, salida lineal y límites de transmisión independientes.", "render.quality_review": "Revisar presupuesto de muestras", "render.queue_pending": "Esta interfaz no contiene cola automática de producción ni renderizador de animaciones. Las imágenes terminadas se exportan por separado.", + "render.radial_assign": "Asignar Aspecto", + "render.radial_compare": "Comparar", "render.radial_distortion": "Distorsión radial", + "render.radial_fit": "Ajustar Producto", + "render.radial_save": "Guardar Toma", + "render.recent_looks": "Aspectos recientes", "render.regrade_action": "Reeditar máster bruto (sin reducción de ruido)", "render.regrade_help": "Crea un PNG independiente a partir del máster bruto del resultado seleccionado y estos controles de presentación. No traza rayos, cambia tamaño, cámara o luces capturados, ni sobrescribe el EXR. No vuelve a reducir el ruido: el máster no conserva las guías del filtro. El resultado se exporta mediante los controles habituales.", "render.regrade_label": "Regraduar", "render.reload_settings": "Recargar ajustes guardados", + "render.remove_override": "Eliminar Sobreescritura", + "render.replace_all": "Reemplazar Todo", "render.replace_ground": "Confirmar sustitución del escenario existente", "render.replace_label": "Reemplazar", "render.replace_saved_surface": "Sustituir una vinculación guardada de este destino", + "render.replace_with": "Reemplazar con", "render.restore_camera": "Restaurar cámara guardada", + "render.result_actual": "100%", "render.result_actual_help": "Un píxel de la imagen por cada píxel de la pantalla.", + "render.result_actual_size": "100%", "render.result_capture": "Revisión capturada", "render.result_current": "La revisión capturada del modelo está actualizada.", "render.result_empty": "Todavía no hay ninguna imagen terminada. Comprueba los ajustes e inicia un renderizado.", @@ -2337,14 +3151,29 @@ "render.saved_surface_remove": "Eliminar la vinculación guardada", "render.saved_surfaces": "Vinculaciones de superficie guardadas", "render.saved_surfaces_help": "Los mapas integrados fijados siguen a la instancia seleccionada en milímetros locales. Un destino sustituido o ausente es un error, nunca una reasignación automática.", + "render.scene_all_shots": "Todas las tomas ({count})", "render.scene_apply": "Aplicar estudio revisado", + "render.scene_batch_reason": "Todas las tomas necesita la cola de render de tomas guardadas, que no está disponible aún.", + "render.scene_check_now": "Comprobar ahora", + "render.scene_check_passed": "Comprobación superada · {notes} notas", + "render.scene_check_stale": "Comprobación desactualizada · comprobar de nuevo", + "render.scene_check_unchecked": "Sin comprobar aún · 0 notas", "render.scene_consent": "Confirmar sustitución de iluminación, entorno, exposición y escenario", + "render.scene_light_summary": "{environment} · {lights} luces", + "render.scene_look_summary": "{looks} aspectos · {overrides} sobreescrituras", + "render.scene_open_check": "Abrir Comprobar", "render.scene_preserved_fields": "Se conservan cámara, muestreo, dimensiones, asignaciones ópticas, geometría CAD y materiales físicos.", "render.scene_preserves_design": "Compón iluminación y escenario pasivo para el objeto visible. Geometría, materiales físicos y cámara se mantienen separados.", + "render.scene_ready": "Listo para renderizar", + "render.scene_reminder": "La escena preserva el diseño. La geometría, propiedades de ingeniería y CAD nunca cambian desde Render.", + "render.scene_reminders": "Recordatorios", + "render.scene_renderer_ready": "{renderer} listo", "render.scene_replaces": "Sustituye", "render.scene_review": "Resolver y revisar", "render.scene_review_help": "Revisa la composición nativa completa antes de aplicar. No se sustituyen las especificaciones SCENE avanzadas sin resolver.", "render.scene_scope_details": "Alcance de la composición", + "render.scene_stages": "Escenarios", + "render.search_appearances": "Buscar {count} aspectos", "render.setup_legacy_environment": "Esta configuración antigua usa rotación o intensidad de entorno heredadas. Se conservan esos valores; conviértelos explícitamente antes de guardar un trabajo de imagen completo.", "render.setup_name": "Nombre de configuración", "render.setup_numeric_help": "Guardar conserva el método de imagen activo y todos sus ajustes numéricos. Recargar o elegir otra configuración sustituye este borrador; la cámara se restaura por separado.", @@ -2354,8 +3183,24 @@ "render.sharpening": "Realce de detalle", "render.shell_tab_appearance": "APARIENCIA DE RENDER", "render.shell_tab_camera": "CÁMARA DE RENDER", + "render.shell_tab_lighting": "ILUMINACIÓN", "render.shell_tab_scene": "ESCENA DE RENDER", + "render.shot_aperture": "Apertura", + "render.shot_distance": "Distancia", + "render.shot_dof": "Profundidad de campo", "render.shot_duplicate": "Duplicar toma guardada", + "render.shot_edit_output": "Editar en Salida", + "render.shot_exposure_reason": "La exposición requiere ray tracing en CPU o path tracing en GPU.", + "render.shot_exposure_section": "Exposición", + "render.shot_focus_distance": "Distancia de foco", + "render.shot_fov_reason": "El campo de visión requiere proyección perspectiva.", + "render.shot_frame_subject": "Encuadrar sujeto", + "render.shot_invalid_camera": "Los valores de cámara deben ser finitos y estar en rango.", + "render.shot_lens": "Objetivo", + "render.shot_lens_enable_reason": "Activa profundidad de campo para editar apertura y distancia de foco.", + "render.shot_lens_gpu_reason": "La profundidad de campo necesita path tracing en GPU.", + "render.shot_lens_perspective_reason": "La profundidad de campo requiere proyección perspectiva.", + "render.shot_look_selection": "Mirar selección", "render.shot_manager": "Tomas guardadas", "render.shot_new_name": "Nombre de la nueva toma", "render.shot_remove": "Eliminar toma guardada", @@ -2363,18 +3208,130 @@ "render.shot_remove_title": "¿Eliminar toma guardada?", "render.shot_rename": "Renombrar toma guardada", "render.shot_saved_only": "Guarda primero el borrador. Duplicar y renombrar conservan los ajustes y las referencias de recursos.", + "render.shot_selection_reason": "Selecciona un cuerpo o cara para apuntar.", + "render.shot_size": "Tamaño", + "render.shot_target": "Objetivo", + "render.shots_camera_changed": "La cámara cambió desde que se guardó esta toma", + "render.shots_name_help": "Escribe un nombre único para la toma actual.", + "render.shots_no_result": "Sin render aún", + "render.shots_result": "Render {number} · {width} × {height}", + "render.shots_revert": "Revertir", + "render.shots_save": "Guardar Toma", + "render.shots_update": "Actualizar toma", "render.show_shots_label": "Mostrar tira de tomas", + "render.size_4k": "4K", + "render.size_4k_uhd": "4K UHD", + "render.size_custom": "Personalizado…", + "render.size_full_hd": "Full HD", + "render.size_hd": "HD", + "render.size_needs_profile": "El tamaño {size} necesita el perfil {profile}", + "render.size_presets": "Preestablecidos de tamaño", + "render.size_presets_pending": "Llega con el editor de Salida", + "render.size_preview": "Previsualización", + "render.size_square": "Cuadrado", "render.sky_ground": "Suelo · RGB lineal", "render.sky_horizon": "Horizonte · RGB lineal", "render.sky_zenith": "Cénit · RGB lineal", "render.soft_focus": "Enfoque suave", + "render.spot_cone": "Cono focal", "render.stage_frame": "Fotograma", + "render.stage_layout.appearance_note": "Clic para aplicar a la selección.", + "render.stage_layout.studio_note": "Clic para revisar antes de aplicar.", "render.stage_light": "Luz", "render.stage_look": "Aspecto", "render.stage_orthographic": "Ortográfica", "render.stage_output": "Salida", "render.stage_panel_count": "Paneles guardados", + "render.stage_panels.acknowledge": "Reconozco el reemplazo y las limitaciones", + "render.stage_panels.appearance_note": "Clic para aplicar a la selección. Arrastrar sobre el modelo. Sin nada seleccionado, un clic arma Pintar.", + "render.stage_panels.apply": "Aplicar", + "render.stage_panels.apply_studio": "Aplicar estudio", + "render.stage_panels.badge_blocked": "bloqueado", + "render.stage_panels.badge_native": "nativo", + "render.stage_panels.badge_projection": "proyección", + "render.stage_panels.badge_reference": "referencia", + "render.stage_panels.badge_specification": "solo especificación", + "render.stage_panels.candidate_summary": "Candidatos: {count} valores origen. Revisar grado y acabado.", + "render.stage_panels.captured_bounds": "Usar límites de escena capturados", + "render.stage_panels.centre": "Centro", + "render.stage_panels.depth": "profundidad", + "render.stage_panels.environments": "Entornos", + "render.stage_panels.extent": "Extensión", + "render.stage_panels.fit_save": "Ajustar y guardar", + "render.stage_panels.gpu_required": "Requiere path tracing en GPU", + "render.stage_panels.keep": "Conservar", + "render.stage_panels.kept": "Conservado", + "render.stage_panels.kept_fields": "Cámara, muestreo, dimensiones, vinculaciones ópticas, geometría CAD y propiedades de ingeniería.", + "render.stage_panels.kept_quality": "Método, cámara, iluminación, entorno, escenario, ópticas, exposición y mapeo de tonos.", + "render.stage_panels.mine": "Míos", + "render.stage_panels.mine_pending": "Guardar estudios personales no se admite aún.", + "render.stage_panels.omits": "Omite", + "render.stage_panels.paint_pending": "Pintar y asignación por arrastre no se admiten aún. Elige un objetivo para aplicar un aspecto.", + "render.stage_panels.partial_reference": "Candidatos: solo valores origen; revisar grado, condiciones y fuentes. Valores desconocidos permanecen desconocidos.", + "render.stage_panels.plane": "Plano", + "render.stage_panels.prepare_plan": "Preparar plan de creación", + "render.stage_panels.projects": "Proyectos", + "render.stage_panels.quality_ack": "Reconozco el presupuesto fijo y sus omisiones", + "render.stage_panels.quality_omissions": "Parada adaptativa y objetivos de error, profundidad de transmisión separada, reglas de ruleta rusa, salida lineal bruta, máster EXR y certificación de convergencia.", + "render.stage_panels.reference": "Referencia", + "render.stage_panels.references": "Referencias", + "render.stage_panels.remove_optics": "Eliminar ópticas", + "render.stage_panels.remove_optics_help": "Elimina las ópticas guardadas de esta toma. La geometría de origen se conserva.", + "render.stage_panels.remove_optics_title": "¿Eliminar ópticas guardadas?", + "render.stage_panels.remove_shot": "Eliminar toma", + "render.stage_panels.remove_stage": "Eliminar escenario", + "render.stage_panels.remove_stage_help": "Elimina los paneles pasivos guardados de esta toma. El fondo de cámara se mantiene.", + "render.stage_panels.remove_stage_title": "¿Eliminar el escenario guardado?", + "render.stage_panels.repeat": "Repetir", + "render.stage_panels.replaces": "Reemplaza", + "render.stage_panels.replaces_environment": "Entorno", + "render.stage_panels.replaces_maps": "Mapas temporales en el cuerpo elegido; las ópticas guardadas pueden entrar en conflicto.", + "render.stage_panels.replaces_physical": "Nada. Este plan es de solo lectura.", + "render.stage_panels.replaces_quality": "Dimensiones de imagen, muestras fijas, profundidad de trayecto, semilla y denoising.", + "render.stage_panels.replaces_rig": "Iluminación, entorno y escenario", + "render.stage_panels.replaces_saved_maps": "Mapas de superficie guardados en el cuerpo elegido; las sobreescrituras temporales pueden entrar en conflicto.", + "render.stage_panels.replaces_stage": "Suelo guardado y paneles de escenario pasivos", + "render.stage_panels.replaces_studio": "Iluminación, entorno, exposición y escenario", + "render.stage_panels.replaces_uniform": "Aspecto opaco en el cuerpo elegido. Los mapas espaciales se aproximan por valores uniformes.", + "render.stage_panels.review_environment": "Revisar entorno", + "render.stage_panels.review_maps": "Revisar mapas GPU", + "render.stage_panels.review_physical": "Plan de referencia física", + "render.stage_panels.review_quality": "Usar presupuesto de muestreo fijo", + "render.stage_panels.review_rig": "Ajustar rig de luces", + "render.stage_panels.review_saved_maps": "Revisar mapas guardados", + "render.stage_panels.review_stage": "Revisar suelo y escenario", + "render.stage_panels.review_studio": "Revisar estudio nativo", + "render.stage_panels.review_uniform": "Revisar aspecto uniforme", + "render.stage_panels.rig_summary": "Rig de luces autoría · {emitters} emisores, {cards} tarjetas", + "render.stage_panels.rigs": "Rigs", + "render.stage_panels.save_maps": "Guardar mapas en esta toma", + "render.stage_panels.scope": "Ámbito", + "render.stage_panels.search_studios": "Buscar estudios", + "render.stage_panels.search_surfaces": "Buscar superficies y referencias", + "render.stage_panels.source_note": "Mapa de color base autoría. No es un material medido.", + "render.stage_panels.specifications": "Especificaciones · solo lectura", + "render.stage_panels.studio_ack": "Confirmar reemplazo de iluminación, entorno, exposición y escenario", + "render.stage_panels.studio_note": "Clic para revisar. Aplicar reemplaza iluminación, entorno y escenario solo tras confirmar. Las luces siguen editables.", + "render.stage_panels.studios": "Estudios", + "render.stage_panels.subtitle_environment": "Entorno HDR original · escena completa", + "render.stage_panels.subtitle_maps": "Mapas espaciales autoría · previsualización temporal", + "render.stage_panels.subtitle_physical": "Plan de solo lectura · no se crea ni asigna material", + "render.stage_panels.subtitle_quality": "Presupuesto GPU fijo · requisitos futuros omitidos", + "render.stage_panels.subtitle_rig": "Rig de luces autoría · emisores y tarjetas pasivas", + "render.stage_panels.subtitle_saved_maps": "Mapas autoría · guardados con esta toma", + "render.stage_panels.subtitle_stage": "Suelo físico y escenario · ajustado al producto", + "render.stage_panels.subtitle_studio": "Estudio nativo · se aplica a toda la escena", + "render.stage_panels.subtitle_uniform": "Aproximación uniforme · no es un material medido", + "render.stage_panels.surfaces": "Superficies", + "render.stage_panels.surfaces_references": "Superficies y referencias", + "render.stage_panels.target": "Objetivo", + "render.stage_panels.use_budget": "Usar este presupuesto", + "render.stage_panels.use_maps": "Usar mapas GPU", + "render.stage_panels.use_uniform": "Usar uniforme", "render.stage_preview_note": "Vista previa integrada · luz directa", + "render.state_completed": "Imagen completada", + "render.state_in_progress": "Imagen en curso", + "render.state_model": "Previsualización Modelo", "render.strip_label": "Tira", "render.studio_add_area": "Añadir luz de área", "render.studio_ambient": "Radiancia constante del entorno", @@ -2413,14 +3370,52 @@ "render.studio_sky_help": "Gradiente de cielo para iluminar la escena; no es un modelo atmosférico calibrado.", "render.studio_sun": "Sol", "render.studio_sun_radius": "Radio angular", + "render.studio_tiles_require_gpu": "Los estudios requieren path tracing en GPU. Selecciona GPU en el editor de Salida.", "render.studio_title": "Estudio de renderizado", "render.studio_tone_map": "Mapeo de tonos", + "render.studios_environments": "Estudios y Entornos", "render.subsurface_enable": "Recorrido aleatorio de dispersión interna", "render.subsurface_help": "Solo dieléctricos cerrados. Dispersión y absorción RGB son coeficientes separados por mm. Las trayectorias se dispersan dentro de la geometría y se refractan o reflejan en la frontera. Desactiva sombras rectas, reducción de ruido de superficies y volumen exterior; usa un estrato Fresnel. No es un filtro de difusión, rejilla de densidad ni material medido. Los medios densos pueden requerir más muestras y profundidad.", "render.subsurface_rate": "Tasa de colisiones de dispersión", + "render.tone_aces_fitted": "ACES ajustado", + "render.tone_reinhard": "Reinhard", "render.transmission_scope": "El vidrio GPU admite medios separados certificados. No se admiten medios anidados sin restricciones ni un estimador de transmisión sin ruido.", "render.transmission_strata": "Estratos de Fresnel condicionales", "render.transmission_strata_help": "1 conserva la secuencia original. 2 o 4 subtrayectorias estratifican la primera decisión de reflexión o transmisión del vidrio, sin cambiar Snell ni la absorción. Aumentan el trabajo; no son un filtro, soporte de medios anidados ni una garantía de mayor velocidad.", + "render.tree_add_light": "Añadir luz", + "render.tree_add_shot": "Añadir toma", + "render.tree_browser": "Explorador de Render", + "render.tree_by_look": "Por aspecto", + "render.tree_by_object": "Por objeto", + "render.tree_constant": "Entorno constante", + "render.tree_default": "Predeterminado", + "render.tree_directional": "Direccional", + "render.tree_environment": "Entorno", + "render.tree_environment_values": "{rotation}° · {intensity}×", + "render.tree_face_count": "{count} caras", + "render.tree_face_one": "{count} cara", + "render.tree_fixed_studio": "Estudio fijo", + "render.tree_hdr": "HDR", + "render.tree_lights": "Luces", + "render.tree_lights_pending": "Los comandos de luz nombrados no están disponibles aún.", + "render.tree_mixed": "Mixto", + "render.tree_more": "{count} más", + "render.tree_mute": "Silenciar luz", + "render.tree_no_environment": "Sin entorno", + "render.tree_objects": "Objetos", + "render.tree_output": "Salida", + "render.tree_point": "Puntual", + "render.tree_rectangle": "Rectángulo", + "render.tree_search": "Buscar objetos", + "render.tree_selection": "Selección de render", + "render.tree_shots": "Tomas", + "render.tree_sky": "Cielo", + "render.tree_solo": "Solo luz", + "render.tree_spot": "Focal", + "render.tree_sun": "Solar", + "render.tree_switch": "Cambiar", + "render.tree_user_one": "{count} objeto", + "render.tree_users": "{count} objetos", "render.unavailable_preview": "Esta configuración solicita un perfil de vista previa no disponible.", "render.unsaved": "Cambios de vista previa sin guardar", "render.use_preview": "Usar vista previa integrada", @@ -2432,12 +3427,20 @@ "render.volume_max": "Límites máximos · mm globales", "render.volume_min": "Límites mínimos · mm globales", "render.volume_title": "Volumen homogéneo acotado", + "render.wait_add_light": "no admitido aún: creación de luz nombrada", "render.wait_batch": "no soportado aún: la cola de renderizado de tomas guardadas", "render.wait_compare": "no soportado aún: comparación de imágenes retenidas", "render.wait_paint": "no soportado aún: selección de producto y pintura de apariencias", "render.wait_pick_up": "no soportado aún: selección de producto y toma de apariencias", "render.wait_replace": "no soportado aún: reemplazar todos los usos de una apariencia", "render.wait_solo": "no soportado aún: visibilidad y solo de luces", + "render.wear_applies_to": "Se aplica a", + "render.wear_layer_count": "{count} capas", + "render.wear_layer_one": "{count} capa", + "render.wear_layers": "Capas", + "render.wear_no_layers": "Sin capas", + "render.wear_selected_layer": "Capa seleccionada", + "render.wear_title": "Desgaste", "sample.bracket.about": "Brida base con pestañas laterales y reborde, según una regla de 2 mm", "sample.bracket.name": "Soporte de chapa", "sample.enclosure.about": "Caja vaciada con labio, salientes para tornillos, apoyo y encaje a presión", @@ -2471,6 +3474,7 @@ "select an axis": "selecciona un eje", "select an axis, a straight or circular edge, or a cylinder, cone or torus face first": "selecciona primero un eje, una arista recta o circular, o una cara cilíndrica, cónica o toroidal", "select bodies first": "selecciona primero cuerpos", + "select components first": "selecciona componentes primero", "select corner points, or the two lines of one corner": "selecciona puntos de esquina, o las dos líneas de una esquina", "select one corner point, or the two lines of one corner": "selecciona un punto de esquina, o las dos líneas de una esquina", "select sheet edges first": "selecciona primero aristas de chapa", @@ -2486,8 +3490,10 @@ "select two components": "selecciona dos componentes", "set by the sketch's lines": "definido por las líneas del boceto", "settings.display_quality_note": "Los niveles más finos muestran las caras y aristas curvas con mayor suavidad, pero tardan más en generar la malla. Solo cambia el visor, nunca el diseño ni las exportaciones.", + "settings.double_click_components": "Doble clic en un componente para activarlo, o para editar uno vinculado en contexto", "settings.frame_rate_details_note": "Añade un gráfico con los tiempos de los últimos fotogramas y los triángulos dibujados encima, un histograma de tiempos de fotograma y lo que dibujó la GPU. Haz clic en la tasa de fotogramas de la vista para mostrarlos u ocultarlos.", "settings.frame_rate_note": "Muestra los fotogramas por segundo en la esquina inferior derecha de la vista.", + "settings.insert_lists_open_designs": "Insertar Diseño lista primero los diseños abiertos en otras pestañas", "settings.measure_axis_distances": "Mostrar distancias X/Y/Z", "settings.measure_axis_distances_help": "Mostrar las cotas de cada eje global junto a la distancia total mientras está abierta la herramienta Medir.", "settings.msaa_applies_on_restart": "El suavizado de bordes se aplicará la próxima vez que se inicie SolidCraft", @@ -2498,6 +3504,7 @@ "settings.reset_intro": "Estos ajustes no funcionan en este ordenador e impedirían iniciar SolidCraft, por lo que se han cambiado:", "settings.reset_title": "Se han cambiado los ajustes", "settings.supersampling_note": "Dibuja la vista a mayor resolución y después la reduce: bordes, líneas y cuadrícula más suaves en pantallas inferiores a 4K. Consume recursos de GPU: unos 2,25× píxeles a 1,5× y 4× a 2×.", + "settings.update_changed_links": "Actualizar diseños vinculados cambiados al volver a la pestaña", "settings.window_system_details": "Detalles", "settings.window_system_note_now": "Se aplica tras reiniciar. Ahora: {now}.", "settings.window_system_wayland_limited": "Algunas funciones tienen limitaciones en Wayland nativo.", @@ -2505,12 +3512,34 @@ "sheet.flange_type_contour": "Contorno", "sheet.flange_type_edge": "Arista", "sheet.no_body": "no hay ningún cuerpo de chapa: crea uno con Pestaña > Base o convierte una placa en chapa con Convertir a chapa (elige su cara plana grande)", + "sheet.personal_rules.confirm_delete": "Confirmar eliminación", + "sheet.personal_rules.delete": "Eliminar", + "sheet.personal_rules.delete_prompt": "¿Eliminar esta regla personal?", + "sheet.personal_rules.full": "Completa", + "sheet.personal_rules.invalid_name": "Nombre no válido", + "sheet.personal_rules.invalid_values": "Valores no válidos", + "sheet.personal_rules.missing": "Falta", + "sheet.personal_rules.name": "Nombre", + "sheet.personal_rules.name_exists": "El nombre ya existe", + "sheet.personal_rules.name_hint": "Nombre de la regla personal", + "sheet.personal_rules.overwrite": "Sobrescribir", + "sheet.personal_rules.rename": "Cambiar nombre", + "sheet.personal_rules.rule": "Regla", + "sheet.personal_rules.save": "Guardar", + "sheet.personal_rules.scope": "Ámbito", + "sheet.personal_rules.select": "Seleccionar", + "sheet.personal_rules.title": "Título", + "sheet.personal_rules.unsupported": "No compatible", "shortcut.json_error": "los parámetros deben estar en formato JSON: {error}", "shortcut.no_command": "no existe el comando `{id}`; el texto anterior al JSON debe ser un ID de comando", "shortcut.pin": "Fijar en la parte superior del cuadro S", "shortcut.unpin": "Desfijar", "sketch is missing": "falta el boceto", "sketch.degrees_of_freedom": "{count} grados de libertad", + "sketch.dimension_added_driven": "El boceto ya determina esa cota, así que se añadió como cota dependiente (de referencia)", + "sketch.dimension_applied": "Cota aplicada", + "sketch.dimension_applied_defined": "Cota aplicada; parámetro `{name}` definido", + "sketch.dimension_applied_renamed": "Cota aplicada; parámetro nombrado `{name}`", "sketch.dof_left": "Quedan {count} grados de libertad", "sketch.dof_left_one": "Queda {count} grado de libertad", "sketch.draw_curves": "Dibujar como {linetype}", @@ -2537,6 +3566,7 @@ "sketch_text.align_right": "Alinear a la derecha", "sketch_text.bold": "Negrita", "sketch_text.builtin_font": "{family} (integrada)", + "sketch_text.formula": "Fórmula", "sketch_text.italic": "Cursiva", "sketch_text.loading_fonts": "Buscando fuentes instaladas…", "sketch_text.on_path": "El texto sigue su trayectoria: la curva determina su posición", @@ -2544,8 +3574,12 @@ "sketch_text.path_hint": "Curva del boceto que seguirá el texto: haz clic aquí y después en la curva", "sketch_text.use_font_file": "Usar el archivo de fuente {path}", "solid": "sólido", + "status.editing": "Editando {name}", "status.navigation": "Asignación del ratón: {mapping}", "status.navigation_tip": "Cómo mueve el ratón la vista. Haz clic para elegir otra asignación", + "status.under_constrained": "Bajo restricción ({count} grados de libertad)", + "status.under_constrained_one": "Bajo restricción ({count} grado de libertad)", + "status.units_tip": "Las unidades del diseño. Haz clic para cambiarlas", "the angle must be a number": "el ángulo debe ser un número", "the curves must be in one sketch": "las curvas deben estar en un solo boceto", "the direction must be an axis, a sketch line or a straight edge": "la dirección debe ser un eje, una línea de boceto o una arista recta", @@ -2566,26 +3600,27 @@ "the two origins are on the same component": "los dos orígenes están en el mismo componente", "thread.automatic_size": "Tamaño automático", "thread.designation": "Designación", - "thread.direction": "Dirección de la rosca", "thread.iso_metric": "Métrica ISO", - "thread.left_hand": "Zurda", - "thread.right_hand": "Diestra", "thread.select_size": "Seleccionar tamaño", "timeline.delete_after_marker_one": "Eliminar 1 operación después del marcador de la línea de tiempo", "timeline.delete_after_marker_other": "Eliminar {count} operaciones después del marcador de la línea de tiempo", "timeline.delete_folders_tip": "Conservar sus operaciones y carpetas anidadas en el historial", "timeline.delete_folders_with_features_tip": "Elimina las carpetas con todas sus operaciones y sus carpetas anidadas", "timeline.delete_many": "Eliminar {count} operaciones seleccionadas", + "timeline.edited_rolled_back": "{name} cambiado, pero está después del marcador del historial, así que no se construye: mueve el marcador pasado para ver el resultado", "timeline.feature_error": "Error: {message}", "timeline.feature_hint": "Doble clic para editar · arrastra para reordenar · clic derecho para ver más opciones", + "timeline.feature_rolled_back": "Retrocedido: después del marcador del historial, así que no se construye", "timeline.feature_warning": "Advertencia: {message}", "timeline.group": "Nueva carpeta de operaciones", "timeline.move_many": "Mover elementos de la línea de tiempo", "timeline.move_to_group": "Mover operaciones a la carpeta", "timeline.rename_group": "Cambiar nombre de carpeta de operaciones", "timeline.reorder_many": "Reordenar operaciones", + "timeline.suppress_features": "Desactivar operaciones", "timeline.suppress_folders_tip": "Desactiva o reactiva todas las operaciones de las carpetas y sus carpetas anidadas", "timeline.ungroup": "Quitar carpetas de operaciones", + "timeline.unsuppress_features": "Reactivar operaciones", "to the face": "a la cara", "to the next face": "hasta la siguiente cara", "toolbar.customize_note": "Pestaña {tab}. Marque un comando para añadir su botón a la barra de herramientas. También puede arrastrar una fila del desplegable de un panel a la barra, arrastrar un botón fuera de la barra para quitarlo o usar la chincheta de una fila del desplegable.", @@ -2657,6 +3692,10 @@ "ui.3d_mouse_offer": "Calibrar tu ratón 3D corrige los ejes intercambiados o invertidos y ajusta su velocidad y sensación.", "ui.3d_mouse_offer_never": "No volver a mostrar", "ui.3d_mouse_offer_swap": "Cambiar a Hidraw (controlador directo)", + "ui.3d_mouse_orbit": "Órbita", + "ui.3d_mouse_orbit_classic": "Clásica", + "ui.3d_mouse_orbit_tip": "Rastreada: el ratón 3D gira la vista alrededor de la parte del modelo en el centro de la vista al empezar el giro, marcada por una bola tenue. Clásica: alrededor del centro de la vista", + "ui.3d_mouse_orbit_traced": "Rastreada", "ui.3d_mouse_reading": "Lectura", "ui.3d_mouse_reset_axes": "Restablecer asignación de ejes", "ui.3d_mouse_reset_view": "Restablecer vista", @@ -2665,6 +3704,8 @@ "ui.3d_mouse_section": "Ratón 3D", "ui.3d_mouse_show_in_view": "Mostrar el ratón 3D en la vista 3D", "ui.3d_mouse_show_in_view_tip": "Una imagen de tu ratón 3D en la esquina inferior izquierda que se mueve cuando lo mueves.", + "ui.3d_mouse_sketch_orbit": "Órbita de boceto con ratón 3D", + "ui.3d_mouse_sketch_orbit_tip": "Usa el ratón 3D para orbitar en el boceto", "ui.3d_mouse_skip": "Mi dispositivo no puede hacer esto", "ui.3d_mouse_skip_tip": "Omite este movimiento en ambos sentidos; la calibración lo deja fuera.", "ui.3d_mouse_speed": "Velocidad del ratón 3D", @@ -2693,6 +3734,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Gira el capuchón en sentido antihorario, mantenlo y suéltalo.", "ui.3d_mouse_switch_cap": "Calibrar como retorno al centro", "ui.3d_mouse_switch_trackball": "Calibrar como trackball", + "ui.3d_mouse_use_direct": "Usar controlador directo", + "ui.3d_mouse_use_direct_tip": "Leer el ratón 3D directamente (hidraw) en lugar de a través de spacenavd.", "ui.3d_mouse_view_axis": "Eje de la vista", "ui.3d_mouse_view_off": "Desactivado", "ui.3d_mouse_view_off_tip": "El perfil del controlador del ratón 3D desactiva este eje, así que su movimiento no mueve la vista. Si eliges aquí el movimiento de otro eje, se intercambian y ese movimiento deja de mover la vista.", @@ -2826,6 +3869,8 @@ "ui.agent_chat_remove": "Quitar de la cola", "ui.agent_chat_remove_file": "Quitar de este mensaje", "ui.agent_chat_remove_imported": "Quitar de este mensaje; la pieza permanece en el diseño (Deshacer la elimina)", + "ui.agent_chat_reply_cut_off": "Respuesta del agente cortada", + "ui.agent_chat_reply_declined": "Respuesta del agente rechazada", "ui.agent_chat_retry": "Reintentar", "ui.agent_chat_right": "Derecha", "ui.agent_chat_save": "Guardar", @@ -2884,12 +3929,17 @@ "ui.ai_copy_suffix": "copia", "ui.ai_custom_url": "URL personalizada", "ui.ai_default": "Predeterminado", + "ui.ai_edit": "Editar", + "ui.ai_edit_agent_title": "Editar agente", + "ui.ai_edit_gone": "Este agente se eliminó, así que no hay nada que guardar.", + "ui.ai_edit_tip": "Cambia el nombre, el comando o el endpoint de este agente. La clave guardada sigue oculta.", "ui.ai_http_busy": "el servicio está ocupado o ha superado su límite; inténtalo más tarde", "ui.ai_http_key": "el servicio ha rechazado la clave: compruébala en Preferencias > IA", "ui.ai_http_not_found": "no existe ese servicio o modelo: comprueba la URL base y el nombre del modelo", "ui.ai_http_too_large": "la conversación es demasiado grande para este endpoint; empieza un chat nuevo", "ui.ai_key": "Clave de API", "ui.ai_key_hint": "opcional; se guarda en el llavero del sistema", + "ui.ai_key_keep_hint": "déjalo vacío para conservar la clave guardada", "ui.ai_key_needs_https": "La clave solo se envía mediante HTTPS o a este ordenador.", "ui.ai_key_note": "Se guarda en el llavero del sistema, nunca en los ajustes de SolidCraft. Déjalo vacío para un servidor local.", "ui.ai_keychain_error": "El llavero del sistema ha rechazado la operación: {error}", @@ -2921,6 +3971,7 @@ "ui.ai_request_timeout": "Tiempo de espera de las peticiones", "ui.ai_request_timeout_hint": "Cuánto puede tardar una petición al modelo en esta API: de 30 s a una hora. Auméntalo para un modelo local lento.", "ui.ai_reset": "Restablecer", + "ui.ai_save": "Guardar", "ui.ai_settings": "Ajustes de IA…", "ui.ai_show_features": "Mostrar funciones de IA", "ui.ai_show_features_note": "Chat del agente: panel en el que un agente de programación que ya utilices, o un servicio de modelos que elijas, trabaja sobre el diseño abierto. Desactivado: no hay botón, atajo, entrada de menú ni panel de IA, y no se busca ni inicia nada.", @@ -2984,6 +4035,9 @@ "ui.blocked": "Bloqueado", "ui.bodies": "Cuerpos", "ui.bodies_all_if_none": "Cuerpos (todos si no hay ninguno)", + "ui.body_kind_mesh": "Cuerpo de malla", + "ui.body_kind_solid": "Cuerpo sólido", + "ui.body_kind_surface": "Cuerpo de superficie", "ui.bottom": "Inferior", "ui.box": "Caja", "ui.break": "Romper", @@ -2996,6 +4050,8 @@ "ui.cancel": "Cancelar", "ui.canvases": "Lienzos", "ui.center": "Centro", + "ui.center_arc_follows_cursor": "Arco por centro sigue la dirección del cursor", + "ui.center_arc_follows_cursor_tip": "Un arco por centro va en el sentido de las agujas del reloj o contrario según el cursor rodea su centro. Desactivado: siempre contrario a las agujas del reloj desde el inicio.", "ui.centerline": "Línea de centro", "ui.chain": "Cadena", "ui.chamfer": "Chaflán", @@ -3004,6 +4060,7 @@ "ui.circle": "Círculo", "ui.circular_pattern": "Patrón circular", "ui.clear": "Borrar", + "ui.clear_print_face": "Limpiar cara de impresión", "ui.clear_recent": "Borrar recientes", "ui.clear_the_selection": "Borrar la selección", "ui.click_selects_whole_bodies": "Un clic selecciona cuerpos completos", @@ -3038,12 +4095,25 @@ "ui.constant": "Constante", "ui.constraints_conflict": "Conflicto entre restricciones", "ui.construction": "Construcción", - "ui.construction.ribbon_label": "Líneas aux.", + "ui.construction.angle_hint": "Línea de construcción: haz clic en un punto, luego escribe un ángulo o elige una dirección", + "ui.construction.bisector_hint": "Bisectriz: elige dos líneas rectas que se intersecten, luego la solución deseada", + "ui.construction.common_hint": "Tangente común: elige dos círculos/arcos, luego la solución deseada", + "ui.construction.contact_hint": "Tangente: elige un círculo/arco o spline/cónica abierta, luego el punto de contacto (libre)", + "ui.construction.external_hint": "Tangente: elige un círculo o arco, un punto externo, luego la solución deseada", + "ui.construction.free_hint": "Línea de construcción: haz clic en dos puntos; clic derecho para reiniciar", + "ui.construction.point_hint": "Línea de construcción: haz clic en el punto por el que debe pasar", + "ui.construction.reference_hint": "Línea de construcción: elige una línea recta, luego un punto; clic derecho para cambiar la", + "ui.construction.ribbon_label": "X-Líneas", "ui.context_menu": "Menú contextual", + "ui.continuity_crease": "Arista", + "ui.continuity_curvature": "Curvatura", + "ui.continuity_curvature_change": "Cambio de curvatura", "ui.continuity_g0": "G0 arista", "ui.continuity_g1": "G1 tangencia", "ui.continuity_g2": "G2 curvatura", "ui.continuity_gap": "Separación", + "ui.continuity_position": "Posición", + "ui.continuity_tangent": "Tangente", "ui.copy": "Copiar", "ui.corner": "Esquina", "ui.corners": "Esquinas", @@ -3105,6 +4175,24 @@ "ui.easyprint_uploading": "Subiendo a Printables…", "ui.edit": "Editar", "ui.editJointLimits": "Editar límites de unión", + "ui.edit_in_place": "Editar en contexto", + "ui.edit_in_place_after_turn": "La edición finaliza cuando termina el turno del agente", + "ui.edit_in_place_agent_busy": "El agente sigue trabajando en este diseño; inténtalo de nuevo cuando termine su turno", + "ui.edit_in_place_already_queued": "Ya hay una edición esperando al final del turno del agente", + "ui.edit_in_place_assembly_closed": "{name} ya no está abierto", + "ui.edit_in_place_banner": "Editando en {name}", + "ui.edit_in_place_busy": "Finaliza o cancela lo que esté abierto primero", + "ui.edit_in_place_none": "Ningún diseño vinculado se edita en contexto", + "ui.edit_in_place_not_saved": "La pieza tiene cambios sin guardar; guárdala para finalizar la edición", + "ui.edit_in_place_open_elsewhere": "{name} está abierto en otro SolidCraft", + "ui.edit_in_place_opens_after_turn": "La pieza se abre cuando termina el turno del agente", + "ui.edit_in_place_refresh_dropped": "El ensamblaje cambió mientras se ejecutaba Actualizar vínculos; ejecútalo de nuevo", + "ui.edit_in_place_refresh_stopped": "Actualizar vínculos se detuvo antes de terminar", + "ui.edit_in_place_refreshing": "Actualizando vínculos en {name}…", + "ui.edit_in_place_save_first": "Guarda el ensamblaje primero: sus diseños vinculados se encuentran desde su archivo", + "ui.edit_in_place_save_waits": "Actualizar vínculos se está ejecutando en {name}; guárdalo cuando termine", + "ui.edit_in_place_saved_elsewhere": "La pieza se guardó en otro archivo; el ensamblaje sigue vinculando {name}", + "ui.edit_in_place_wait": "Espera a que termine lo que se está ejecutando en el diseño", "ui.edit_section_analysis": "Editar análisis de sección", "ui.ellipse": "Elipse", "ui.emboss_wrap_note": "Los perfiles de líneas ortogonales tangentes a un cilindro compatible se envuelven automáticamente. Elegir una pared para definir el destino.", @@ -3112,6 +4200,14 @@ "ui.end_scale": "Escala final", "ui.entities": "Entidades", "ui.equal": "Igual", + "ui.equation_end": "Fin", + "ui.equation_explicit": "Explícita", + "ui.equation_form": "Forma", + "ui.equation_note": "La variable es un número simple: sen(t) la toma en radianes. Un resultado sin unidad está en la unidad del diseño.", + "ui.equation_parametric": "Paramétrica", + "ui.equation_x_of_t": "x(t)", + "ui.equation_y_of_t": "y(t)", + "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Radio equivalente", "ui.expand": "Expandir", "ui.exportDxf": "Exportar DXF…", @@ -3177,8 +4273,10 @@ "ui.heading_design": "DISEÑO", "ui.heading_draft": "ÁNGULO DE SALIDA", "ui.heading_edit": "EDITAR", + "ui.heading_equation_curve": "CURVA ECUACIÓN", "ui.heading_extrude": "EXTRUIR", "ui.heading_fillet": "REDONDEO", + "ui.heading_finish_editing": "FINALIZAR EDICIÓN", "ui.heading_finish_sketch": "FINALIZAR BOCETO", "ui.heading_form": "FORMA", "ui.heading_front": "FRONTAL", @@ -3249,6 +4347,10 @@ "ui.history_marker_tip": "Marcador del historial: arrastra para retroceder el modelo; las nuevas operaciones se insertan aquí", "ui.history_names": "Nombres", "ui.history_play": "Reproducir hasta el final", + "ui.history_play_button_hide": "Ocultar botón Reproducir", + "ui.history_play_button_show": "Mostrar botón Reproducir", + "ui.history_play_finish_action": "Finaliza la acción actual antes de reproducir el Historial", + "ui.history_play_roll_back": "Mueve el marcador del Historial atrás antes de reproducir", "ui.history_show_names": "Mostrar nombres", "ui.history_sketch_listed_under": "Listado bajo {feature}", "ui.history_title": "Historial", @@ -3263,7 +4365,12 @@ "ui.import_ellipsis": "Importar…", "ui.infinite": "Infinito", "ui.insert": "Insertar", + "ui.insert_design.browse": "Examinar…", + "ui.insert_design.open_designs": "Diseños abiertos", + "ui.insert_design.saved_file": "{name} tiene cambios sin guardar, así que se insertó su archivo guardado. Guárdalo y luego Actualizar vínculos para traer los cambios.", + "ui.insert_design.unsaved": "Cambios sin guardar", "ui.inspect": "Inspeccionar", + "ui.instances": "Instancias", "ui.intersect": "Intersecar", "ui.isolate": "Aislar", "ui.join": "Unir", @@ -3377,6 +4484,7 @@ "ui.pinToShortcuts": "Fijar en accesos directos", "ui.pinToToolbar": "Fijar en barra de herramientas", "ui.pipe": "Tubo", + "ui.pitch": "Inclinación", "ui.placement": "Colocación", "ui.placement_handles": "Tiradores de colocación", "ui.placement_handles_tip": "Tiradores en la vista previa de un Refuerzo, Saliente o Encaje a presión: arrastra el marcador para moverlo por el modelo, gíralo por su anillo.", @@ -3391,17 +4499,49 @@ "ui.plugins_skipped": "No se pudieron leer {count} carpeta(s).", "ui.plugins_version": "{version}", "ui.point": "Punto", + "ui.point_cloud_add_filter": "Añadir filtro…", + "ui.point_cloud_auto_range": "Rango automático", + "ui.point_cloud_color_by": "Color por", + "ui.point_cloud_file_colors": "Colores del archivo", + "ui.point_cloud_filter_by": "Filtrar por", + "ui.point_cloud_height_high": "Más alto", + "ui.point_cloud_height_low": "Más bajo", + "ui.point_cloud_legend_filter": "Mostrados y ocultos en la leyenda de arriba", + "ui.point_cloud_no_file_colors": "El archivo no tiene colores", + "ui.point_cloud_pause": "Pausa", + "ui.point_cloud_play": "Reproducir", + "ui.point_cloud_single_color": "Color único", + "ui.point_cloud_size": "Tamaño de punto", + "ui.point_cloud_units": "Unidades del archivo", "ui.point_under_the_cursor": "Punto bajo el cursor", "ui.points": "Puntos", "ui.polygon": "Polígono", "ui.preferences": "Preferencias", "ui.press_a_key": "pulsa una tecla…", + "ui.print_face_body_not_sent": "El cuerpo de esa cara no se envía: añádelo primero a Cuerpos", + "ui.print_face_cleared": "{body}: cara de impresión limpiada", + "ui.print_face_input": "Cara de impresión", + "ui.print_face_pick": "Selecciona una cara plana de un cuerpo sólido para hacerla la cara de impresión", + "ui.print_face_set": "{body}: cara de impresión establecida; Enviar a Laminador coloca el cuerpo sobre ella", "ui.profile": "Perfil", "ui.profile_plane": "Plano de perfil", "ui.profiles": "Perfiles", "ui.project": "Proyecto", "ui.project_face_edges_sketch": "Proyectar aristas de caras en bocetos nuevos", "ui.properties": "Propiedades", + "ui.properties.copy_matrix": "Copiar matriz", + "ui.properties.first_moments": "Primeros momentos", + "ui.properties.inertia": "Momento de inercia", + "ui.properties.inertia_note": "Respecto al centro de masas, en ejes mundiales (g·{unit}²)", + "ui.properties.inertia_unavailable": "No disponible: la malla de un cuerpo no cierra.", + "ui.properties.inertia_x": "Ixx, Ixy, Ixz", + "ui.properties.inertia_y": "Iyx, Iyy, Iyz", + "ui.properties.inertia_z": "Izx, Izy, Izz", + "ui.properties.measuring": "Midiendo…", + "ui.properties.measuring_bodies": "Midiendo… {done} de {total} cuerpos", + "ui.properties.measuring_failed": "La medición se detuvo antes de terminar.", + "ui.properties.principal_axis": "Eje principal {number}", + "ui.properties.principal_moments": "Momentos principales", "ui.pull_direction": "Dirección de tracción", "ui.quality": "Calidad", "ui.quantity": "Cantidad", @@ -3438,11 +4578,16 @@ "ui.restore_defaults": "Restaurar valores predeterminados", "ui.reverse_horizontal_pan_direction": "Invertir dirección del desplazamiento horizontal", "ui.reverse_horizontal_pan_tip": "El desplazamiento horizontal con dos dedos y la rueda de pulgar desplazan en sentido contrario", + "ui.reverse_trackpad_orbit_direction": "Invertir dirección de órbita en panel táctil", + "ui.reverse_trackpad_orbit_tip": "Mayús con scroll de dos dedos orbita en sentido contrario", + "ui.reverse_vertical_pan_direction": "Invertir dirección de desplazamiento vertical", + "ui.reverse_vertical_pan_tip": "El scroll vertical de dos dedos desplaza en sentido contrario", "ui.reverse_zoom_direction": "Invertir dirección del zoom", "ui.revolutions": "Vueltas", "ui.revolve": "Revolución", "ui.ribbon_exit": "Salir", "ui.ribbon_labels": "Mostrar texto bajo los iconos de la cinta", + "ui.ribbon_menus_skip_pinned": "Dejar comandos anclados fuera de los menús desplegables", "ui.ribbon_pin_footer": "Los comandos anclados se muestran en la cinta. Pasa el ratón sobre una fila para anclarla o desanclarla.", "ui.ribbon_workspace": "Espacio de trabajo", "ui.right": "Derecha", @@ -3461,6 +4606,7 @@ "ui.selectOther": "Seleccionar otro…", "ui.selectTangentChain": "Seleccionar cadena tangente", "ui.select_all": "Seleccionar todo", + "ui.select_components_by_face": "Seleccionar componentes por cara", "ui.selection": "Selección", "ui.selection_modifiers": "Modificadores de selección", "ui.selection_shift_add_only": "Mayús+clic añade sin quitar", @@ -3497,7 +4643,16 @@ "ui.sketch": "Boceto", "ui.sketch_dimension": "Cota de boceto", "ui.sketch_grid": "Cuadrícula de boceto", + "ui.sketch_intersect_geometry": "Geometría", + "ui.sketch_intersect_projection_link": "Vinculación de proyección", + "ui.sketch_intersect_selection_filter": "Filtro de selección", "ui.sketch_modifiers": "Modificadores del boceto", + "ui.sketch_project_geometry": "Geometría", + "ui.sketch_report.all_constrained": "Todo está totalmente restringido.", + "ui.sketch_report.dof": "Grados de libertad", + "ui.sketch_report.loose": "No totalmente restringido", + "ui.sketch_report.status": "Estado", + "ui.sketch_report.title": "Informe de boceto", "ui.sketch_scale": "Escala del boceto", "ui.sketches": "Bocetos", "ui.slice": "Laminar", @@ -3548,6 +4703,7 @@ "ui.tab_manage": "Gestionar", "ui.tab_sheet_metal": "Chapa", "ui.tab_view": "Vista", + "ui.tab_weldments": "Soldaduras", "ui.tangent": "Tangente", "ui.taper_angle": "Ángulo de conicidad", "ui.tapped": "Roscado", @@ -3563,6 +4719,7 @@ "ui.tip_angle": "Ángulo de punta", "ui.to_object": "Hasta objeto", "ui.tool_direction": "Dirección de herramienta", + "ui.toolbar_tabs_hidden": "Todas las pestañas de la barra de herramientas están ocultas. Haz clic en + o clic derecho aquí para mostrar una.", "ui.top": "Superior", "ui.top_diameter": "Diámetro superior", "ui.top_radius": "Radio superior", @@ -3588,12 +4745,37 @@ "ui.updateToCurrentView": "Actualizar a vista actual", "ui.upload": "Subir", "ui.vertical_constraint": "Restricción vertical", + "ui.view_angles": "Ángulos de vista", + "ui.view_angles_convention": "Grados sobre el eje vertical. Rumbo 0° es la vista Frontal, 90° Izquierda, −90° Derecha, 180° Trasera; inclinación 90° es la vista Superior; un giro positivo rota el modelo en el sentido de las agujas del reloj.", + "ui.view_angles_help": "Muestra la inclinación, rumbo y giro de la vista en grados y su proyección bajo el gizmo de orientación. Haz clic en la lectura para escribir ángulos exactos.", + "ui.view_angles_ortho": "Ortogonal", + "ui.view_angles_persp": "Perspectiva", + "ui.view_angles_pitch": "Inclinación", + "ui.view_angles_readout": "Inclinación {pitch} · Rumbo {yaw} · Giro {roll}", + "ui.view_angles_roll": "Giro", + "ui.view_angles_yaw": "Rumbo", "ui.view_centre": "Centro de la vista", + "ui.viewport_status_clear": "Desactivar {name}", + "ui.viewport_status_clear_hint": "Desactivar {name} · Esc", + "ui.viewport_status_edges": "{count} aristas", + "ui.viewport_status_from": "desde {direction}", + "ui.viewport_status_key": "Mostrar tecla para {name}", + "ui.viewport_status_minimum_radius": "Radio mínimo", + "ui.viewport_status_pairs": "{count} pares", + "ui.viewport_status_section_hatch": "Sombreado de sección: {setting}", + "ui.viewport_status_section_plane": "Plano de sección", + "ui.viewport_status_section_tilted": "Sección inclinada ({offset})", + "ui.viewport_status_stripes": "{count} franjas", + "ui.viewport_status_summary_clear": "Limpiar resumen", + "ui.viewport_status_summary_heading": "Encabezado del resumen", + "ui.viewport_status_summary_label": "Etiqueta del resumen: {name} ({count})", + "ui.viewport_status_summary_more": "Más del resumen ({count})", "ui.viewport_theme_follow": "Seguir tema", "ui.visual_shaded_hidden_edges": "Sombreado con aristas ocultas", "ui.visual_shaded_with_edges": "Sombreado con aristas", "ui.visual_style": "Estilo visual", "ui.visual_wireframe": "Estructura alámbrica", + "ui.wheel_zoom_speed": "Velocidad de zoom con rueda del ratón", "ui.width": "Anchura", "ui.window_system": "Sistema de ventanas", "ui.window_system_auto": "Automático", @@ -3624,10 +4806,12 @@ "update.button": "Actualizar", "update.button_version": "Actualizar a {version}", "update.check_automatically": "Buscar actualizaciones automáticamente", + "update.check_for_updates": "Buscar actualizaciones", "update.check_now": "Comprobar ahora", + "update.check_unavailable": "Las comprobaciones de actualización no están disponibles para esta instalación.", "update.checking": "Comprobando…", "update.copy": "Copiar", - "update.dmg_opened": "La imagen de disco está abierta y verificada: arrastra SolidCraft a Aplicaciones, sustituye la copia anterior y reinicia SolidCraft.", + "update.dmg_opened": "La imagen de disco está abierta y verificada: sal de SolidCraft, arrastra el nuevo SolidCraft a Aplicaciones, sustituye la copia anterior y vuelve a abrir SolidCraft.", "update.download": "Descargar", "update.download_open": "Descargar y abrir", "update.downloading": "Descargando y verificando… {done} de {total} MB", @@ -3638,13 +4822,18 @@ "update.installed": "SolidCraft {version} está instalado. Reinicia para utilizarlo.", "update.installer_started": "El instalador se iniciará cuando se cierre SolidCraft.", "update.later": "Recordármelo más tarde", + "update.managed": "Actualización disponible: actualiza SolidCraft en {manager}", "update.no_notes": "Esta versión no tiene notas.", "update.package_hint": "Esta copia procede de {kind}. Descarga el paquete nuevo e instálalo con:", "update.prefs_dev": "Esta es una compilación de desarrollo ({version}): no busca actualizaciones.", "update.prefs_flatpak": "Flatpak actualiza esta copia ({version}): ejecuta {command} o utiliza el centro de software. SolidCraft no lo comprueba.", "update.prefs_label": "Actualizaciones", + "update.prefs_managed": "Este es SolidCraft {version}, gestionado por {manager}. Una comprobación pide a GitHub la última versión y no envía nada más; actualiza SolidCraft en {manager}.", "update.prefs_note": "Esta es la versión {version} de SolidCraft ({kind}). La comprobación consulta en GitHub la última versión y no envía ningún otro dato.", "update.prefs_web": "Recarga la página para obtener la última aplicación web. Si la red no está disponible o la actualización no termina de descargarse a tiempo, se abrirá la versión guardada; una descarga en curso continúa para la próxima recarga.", + "update.refresh_checking": "Comprobando la versión más reciente…", + "update.refresh_fallback": "No se ha podido comprobar una versión más reciente; actualizando a {version}, encontrada antes.", + "update.refresh_selected": "Actualizando a {version}.", "update.release_page": "Abrir página de la versión", "update.restart": "Reiniciar ahora", "update.restart_later": "Más tarde", @@ -3659,6 +4848,7 @@ "values must be finite numbers": "los valores deben ser números finitos", "values must be numbers or expressions": "los valores deben ser números o expresiones", "view.auto_ortho_faces": "Perspectiva al orbitar, orto en caras", + "view.render_inspector": "Inspector de render", "web.files.insert_drawings_hint": "Archivos CAD, mallas, DXF o SVG en el diseño abierto", "web.files.insert_stored_drawings_hint": "En el diseño abierto (archivos CAD, mallas, DXF, SVG)", "web.open_full": "Abrir en SolidCraft", diff --git a/assets/locales/fi.json b/assets/locales/fi.json new file mode 100644 index 000000000..72995e5df --- /dev/null +++ b/assets/locales/fi.json @@ -0,0 +1,4803 @@ +{ + "(active rule)": "(aktiivinen sääntö)", + "0 turns it off": "0 poistaa sen käytöstä", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Avaa alla oleva GitHub-luonnos ja liitä sitten leikepöydälle kopioitu raportti.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Avaa alla oleva GitHub-luonnos. Otsikkosi ja raporttisi täytetään valmiiksi.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Liitä kuvakaappaus: kopioi ja liitä se tai tallenna ja lataa PNG-tiedosto.", + "2D": "2D", + "3. Click Submit new issue on GitHub to send your report.": "3. Lähetä raportti napsauttamalla GitHubissa Submit new issue.", + "A Single hole snaps to the middle of its face and to the centres of its round edges": "Yksittäinen reikä tarttuu pintansa keskelle ja pyöreiden särmiensä keskipisteisiin", + "A new configuration, a copy of the active one": "Uusi konfiguraatio, kopio aktiivisesta", + "A placed Single hole has a handle to drag it, and picking its face again moves the hole there instead of taking it out": "Sijoitetulla yksittäisellä reiällä on vetokahva, ja sen pinnan valitseminen uudelleen siirtää reiän sinne sen sijaan, että reikä poistettaisiin", + "A short title for the problem (optional)": "Ongelman lyhyt otsikko (valinnainen)", + "ARRANGE": "JÄRJESTÄ", + "About SolidCraft": "Tietoja SolidCraftista", + "Acceleration": "Kiihtyvyys", + "Access": "Käyttöoikeus", + "Actions": "Toiminnot", + "Active": "Aktiivinen", + "Active rule": "Aktiivinen sääntö", + "Add": "Lisää", + "Add Column": "Lisää sarake", + "Add Key": "Lisää avain", + "Add Mid Radius": "Lisää keskisäde", + "Add Row": "Lisää rivi", + "Add a tool": "Lisää työkalu", + "Add all bodies": "Lisää kaikki kappaleet", + "Add bend": "Lisää taivutus", + "Add condition": "Lisää ehto", + "Add or edit rule": "Lisää tai muokkaa sääntöä", + "Add to New Folder": "Lisää uuteen kansioon", + "Add visible bodies": "Lisää näkyvät kappaleet", + "Advanced": "Lisäasetukset", + "Against": "Vastakkain", + "Alignment": "Tasaus", + "All Lines": "Kaikki viivat", + "All Sketch Points": "Kaikki luonnospisteet", + "All components": "Kaikki komponentit", + "All open designs": "Kaikki avoimet mallit", + "Allowed expressions, separated by semicolons": "Sallitut lausekkeet puolipisteillä erotettuina", + "Also deletes": "Poistaa myös", + "Also place them from the origin (fully constrained)": "Sijoita ne myös origosta (täysin määritelty)", + "Anchor": "Ankkuri", + "Angle 2": "Kulma 2", + "Angle Display": "Kulman näyttö", + "Animate": "Animoi", + "Another bend on the far edge of the last flange": "Uusi taivutus viimeisen laipan kauempaan särmään", + "App/system information and command settings are included. Review private details before sharing.": "Mukana ovat sovellus- ja järjestelmätiedot sekä komentoasetukset. Tarkista yksityiset tiedot ennen jakamista.", + "Appearance name": "Ulkoasun nimi", + "Applied Radius": "Käytetty säde", + "Apply To": "Kohdista", + "Apply library appearance": "Käytä kirjaston ulkoasua", + "Apply to selection": "Käytä valintaan", + "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Käytä ulkoasua ensin. Vie määritetyt ulkoasut ja tässä mallissa luodut materiaalit.", + "Arc length": "Kaaren pituus", + "Area": "Pinta-ala", + "As Picked": "Valinnan mukaan", + "As-Built": "Nykyasennon mukainen", + "Assign Rule": "Määritä sääntö", + "Attachment": "Kiinnitys", + "BLEND SURFACE": "SULAUTUSPINTA", + "BOUNDARY SURFACE": "REUNAPINTA", + "BROWSER": "SELAIN", + "Ball": "Pallo", + "Bar": "Tanko", + "Base Center": "Pohjan keskipiste", + "Base Height": "Pohjan korkeus", + "Bend": "Taivutus", + "Bend Edges": "Taivutussärmät", + "Bend Line": "Taivutusviiva", + "Bend Line Position": "Taivutusviivan sijainti", + "Bend Position": "Taivutuksen sijainti", + "Bend Radius": "Taivutussäde", + "Bend Table": "Taivutustaulukko", + "Bends": "Taivutukset", + "Bodies": "Kappaleet", + "Bodies (optional)": "Kappaleet (valinnainen)", + "Body": "Kappale", + "Body (last if none)": "Kappale (viimeinen, jos ei valittu)", + "Body to split": "Jaettava kappale", + "Body, or faces to take out": "Kappale tai poistettavat pinnat", + "Both": "Molemmat", + "Bottom Left": "Alhaalla vasemmalla", + "Bottom Middle": "Alhaalla keskellä", + "Bottom Right": "Alhaalla oikealla", + "Boundary": "Reuna", + "Bounding box": "Rajauslaatikko", + "CHECK": "TARKISTA", + "COMPONENTS": "KOMPONENTIT", + "CONFIGURATIONS": "KONFIGURAATIOT", + "CONSTRAIN": "RAJOITA", + "CONTACT": "KOSKETUS", + "CONVERT": "MUUNNA", + "CSV or JSON: updates existing parameters, adds new ones": "CSV tai JSON: päivittää olemassa olevat parametrit ja lisää uudet", + "Capture All Positions": "Tallenna kaikki asennot", + "Capture Pos.": "Tallenna as.", + "Catch Depth": "Salvan syvyys", + "Catch Direction": "Salvan suunta", + "Catch Length": "Salvan pituus", + "Cells": "Solut", + "Center X": "Keskipiste X", + "Center Y": "Keskipiste Y", + "Center of mass": "Massakeskipiste", + "Centre to centre": "Keskeltä keskelle", + "Centroid": "Pintakeskiö", + "Chamfer Type": "Viisteen tyyppi", + "Channel": "U-profiili", + "Check collisions": "Tarkista törmäykset", + "Checked": "Valittu", + "Choose Variable radius or Spline in Type.": "Valitse Tyyppi-kohdasta Muuttuva säde tai Splini.", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Valitse uusi taso. Luonnoksen geometria ja mitat säilyvät ennallaan sen kaksiulotteisissa koordinaateissa.", + "Choose…": "Valitse…", + "Circle center": "Ympyrän keskipiste", + "Circle or sphere": "Ympyrä tai pallo", + "Circular": "Ympyrä", + "Circumference": "Kehä", + "Clockwise": "Myötäpäivään", + "Close draft": "Sulje luonnos", + "Collapse": "Kutista", + "Collisions": "Törmäykset", + "Colour": "Väri", + "Command": "Komento", + "Comment": "Kommentti", + "Component 1": "Komponentti 1", + "Component 2": "Komponentti 2", + "Component1": "Komponentti1", + "Components": "Komponentit", + "Config Table": "Konfiguraatiotaulukko", + "Configuration": "Konfiguraatio", + "Configuration rules": "Konfiguraatiosäännöt", + "Constant radius": "Vakiosäde", + "Contact": "Kosketus", + "Contact Sets": "Kosketusjoukot", + "Contact sets": "Kosketusjoukot", + "Continue on GitHub": "Jatka GitHubissa", + "Continuity": "Jatkuvuus", + "Control Radius": "Ohjaussäde", + "Copies the definition only. Assign it from Physical Material when ready.": "Kopioi vain määrityksen. Määritä se Fyysinen materiaali -kohdasta, kun olet valmis.", + "Copy Error Message": "Kopioi virheilmoitus", + "Copy Warning Message": "Kopioi varoitusilmoitus", + "Copy all licences": "Kopioi kaikki lisenssit", + "Copy diagnostic information": "Kopioi diagnostiikkatiedot", + "Copy report": "Kopioi raportti", + "Copy screenshot": "Kopioi kuvakaappaus", + "Corner Relief": "Kulmavapautus", + "Corner Relief Shape": "Kulmavapautuksen muoto", + "Corner radius": "Kulmasäde", + "Counterbore depth": "Upotuksen syvyys", + "Counterbore Ø": "Upotuksen Ø", + "Countersink angle": "Kartioupotuksen kulma", + "Countersink Ø": "Kartioupotuksen Ø", + "Create Hole": "Luo reikä", + "Create Issue — review draft": "Luo ilmoitus — tarkista luonnos", + "Create Issue…": "Luo ilmoitus…", + "Cross curves": "Poikkikäyrät", + "Ctrl+Enter continues on GitHub.": "Ctrl+Enter jatkaa GitHubissa.", + "Cube": "Kuutio", + "Current orthographic view (1:1 mm)": "Nykyinen ortografinen näkymä (1:1 mm)", + "Current perspective view": "Nykyinen perspektiivinäkymä", + "Current plane": "Nykyinen taso", + "Curv. Comb": "Kaar.kampa", + "Curvature (G2)": "Kaarevuus (G2)", + "Curvature change (G3)": "Kaarevuuden muutos (G3)", + "Custom": "Mukautettu", + "Customize Toolbar": "Mukauta työkaluriviä", + "Customize…": "Mukauta…", + "Cylindrical": "Sylinterimäinen", + "Cylindrical face": "Sylinteripinta", + "Deboss": "Painauma", + "Delete": "Poista", + "Delete Folders and Features…": "Poista kansiot ja piirteet…", + "Delete Selected Features…": "Poista valitut piirteet…", + "Delete Selected Folders": "Poista valitut kansiot", + "Delete all": "Poista kaikki", + "Delete rule": "Poista sääntö", + "Delete the row": "Poista rivi", + "Delete the set": "Poista joukko", + "Density": "Tiheys", + "Dependents": "Riippuvat kohteet", + "Describe the problem you saw": "Kuvaile havaitsemasi ongelma", + "Describe what happened before continuing.": "Kuvaile tapahtunut ennen kuin jatkat.", + "Designs you open or save appear here.": "Avaamasi tai tallentamasi mallit näkyvät tässä.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Määräytyy Kohteeseen-asetuksesta. Valitse Kulma, jos haluat muokata kulmalaajuutta.", + "Diameter": "Halkaisija", + "Did this assembly open the wrong way up?": "Avautuiko tämä kokoonpano väärin päin?", + "Did this part open the wrong way up?": "Avautuiko tämä osa väärin päin?", + "Dimension new shapes": "Mitoita uudet muodot", + "Direction": "Suunta", + "Discard": "Hylkää", + "Distance": "Etäisyys", + "Distance 1": "Etäisyys 1", + "Do not export hidden edges": "Älä vie piilosärmiä", + "Don't ask again": "Älä kysy uudelleen", + "Double-click to rename": "Nimeä uudelleen kaksoisnapsauttamalla", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Keskipainikkeen kaksoisnapsautus näkymässä: Koti (kotinäkymä, rajaa näytettävät kohteet), Sovita (rajaa näytettävät kohteet suunta säilyttäen) tai ei mitään", + "Drag to move the boss across the model. It snaps to sketch points on the face.": "Siirrä tappia mallin päällä vetämällä. Se tarttuu pinnan luonnospisteisiin.", + "Drag to move the hole; click to remove it": "Siirrä reikää vetämällä, poista se napsauttamalla", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "Siirrä tukea mallin päällä vetämällä. Se tarttuu pinnan luonnospisteisiin.", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "Siirrä napsautusliitosta mallin päällä vetämällä. Se tarttuu pinnan luonnospisteisiin.", + "Drag to point the catch in another direction.": "Käännä salpa toiseen suuntaan vetämällä.", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "Käännä tukea 5° askelin vetämällä. Pidä Alt tai Ctrl painettuna, niin voit kääntää sitä vapaasti.", + "Drive Joint": "Ohjaa niveltä", + "Duration": "Kesto", + "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Jokainen uusi muoto mitoitetaan myös luonnoksen origosta, kunnes mikään sen osa ei jää vapaaksi. Muoto, joka on jo kiinnitetty origoon tai sijoitettuun geometriaan, ei saa mittoja.", + "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Jokainen piirtämäsi muoto saa kaikki mittansa piirtämäsi kokoisina (kirjoitetut arvot ovat etusijalla). Kokoa, jonka luonnos jo määrää, ei lisätä.", + "Edge": "Särmä", + "Edges": "Särmät", + "Edit": "Muokkaa", + "Edit Profile Sketch": "Muokkaa profiililuonnosta", + "Edit shortcuts": "Muokkaa pikanäppäimiä", + "Enable rule": "Ota sääntö käyttöön", + "Enabled": "Käytössä", + "End Radius": "Loppusäde", + "End bulge": "Pään pullistuma", + "End continuity": "Pään jatkuvuus", + "Equal Distance": "Tasaetäisyys", + "Expand": "Laajenna", + "Expected result (optional)": "Odotettu tulos (valinnainen)", + "Explode": "Räjäytä", + "Explode Text": "Pura teksti", + "Export Animation…": "Vie animaatio…", + "Export Bend Table…": "Vie taivutustaulukko…", + "Export CSV…": "Vie CSV…", + "Export Current View as DXF": "Vie nykyinen näkymä DXF-muodossa", + "Export Current View as DXF…": "Vie nykyinen näkymä DXF-muodossa…", + "Export DXF": "Vie DXF", + "Export DXF…": "Vie DXF…", + "Export JSON…": "Vie JSON…", + "Export design library...": "Vie mallin kirjasto...", + "Export hidden edges as dashed lines": "Vie piilosärmät katkoviivoina", + "Exported by SolidWorks, which usually saves Y up": "Viety SolidWorksista, joka tallentaa yleensä Y ylöspäin", + "Expression": "Lauseke", + "Extend to meet": "Jatka kohtaamiseen", + "Extents": "Ulottuvuus", + "FILES": "TIEDOSTOT", + "FLAT": "LEVITYS", + "Face": "Pinta", + "Face Appearance": "Pinnan ulkoasu", + "Face attachment lost": "Pintakiinnitys menetetty", + "Face center": "Pinnan keskipiste", + "Faces": "Pinnat", + "Faces / edges / vertices": "Pinnat / särmät / kärkipisteet", + "Faces to split": "Jaettavat pinnat", + "Faces/Body": "Pinnat/kappale", + "Factor must be a positive number": "Kertoimen on oltava positiivinen luku", + "Fastener": "Kiinnike", + "Favorites": "Suosikit", + "Favourite": "Suosikki", + "Feature": "Piirre", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Monien CAD-ohjelmien tiedostoissa Y on ylöspäin, joten ne avautuvat täällä selällään (Z ylöspäin).", + "Filter": "Suodatin", + "Filter…": "Suodata…", + "Find in Browser": "Etsi selaimesta", + "Finish": "Valmis", + "First edge": "Ensimmäinen särmä", + "First plane": "Ensimmäinen taso", + "First point": "Ensimmäinen piste", + "Fit and G2 corners require Constant radius.": "Sovitus- ja G2-kulmat edellyttävät vakiosädettä.", + "Fixed Face": "Kiinteä pinta", + "Flange Gap": "Laipan rako", + "Flange thickness": "Laipan paksuus", + "Flanges": "Laipat", + "Flat Pattern": "Levityskuva", + "Flat size": "Levityskoko", + "Flat size X": "Levityskoko X", + "Flat size Y": "Levityskoko Y", + "Follow camera (Look At sketches)": "Seuraa kameraa (Katso kohti -luonnokset)", + "Follow the camera (Look At sketches)": "Seuraa kameraa (Katso kohti -luonnokset)", + "Font": "Fontti", + "Free Move": "Vapaa siirto", + "From": "Mistä", + "From Bodies": "Kappaleista", + "From Snap": "Tartunnasta", + "From edges": "Särmistä", + "Full Length": "Koko pituus", + "Full thread depth": "Täysi kierteen syvyys", + "Further Bends": "Lisätaivutukset", + "G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "G2-kulmat edellyttävät vakiosädettä ja tarkkaa sovitusta. G2-kulmien muodostusta ei vielä tueta.", + "Gap": "Rako", + "Grid": "Ruudukko", + "HISTORY": "HISTORIA", + "Halo under sketch curves": "Korostusreunus luonnoskäyrien alla", + "Height": "Korkeus", + "Height From": "Korkeus alkaen", + "Hem Gap": "Huuloksen rako", + "Hidden edges": "Piilosärmät", + "History layout": "Historian asettelu", + "History names": "Historian nimet", + "Hole (optional)": "Reikä (valinnainen)", + "Hole Depth": "Reiän syvyys", + "Hole Diameter": "Reiän halkaisija", + "Holes": "Reiät", + "Holes (edges on them)": "Reiät (niiden särmät)", + "Home view": "Aloitusnäkymä", + "Horiz./Vert.": "Vaaka/pysty", + "I-Beam": "I-palkki", + "IMAGES": "KUVAT", + "If you are offline or GitHub does not open, use Copy report and keep the text to submit later.": "Jos olet offline-tilassa tai GitHub ei avaudu, käytä Kopioi raportti -toimintoa ja säilytä teksti myöhempää lähettämistä varten.", + "Import material into design": "Tuo materiaali malliin", + "Import…": "Tuo…", + "In This Design": "Tässä mallissa", + "In place (surfaces)": "Paikallaan (pinnat)", + "In plane": "Tasossa", + "Included": "Mukana", + "Inner Sharp": "Terävä sisäkulma", + "Inside": "Sisäpuoli", + "Instant": "Välitön", + "Interface font": "Käyttöliittymän fontti", + "Interferes": "Törmää", + "Invert": "Käänteinen", + "Isocurve": "Isokäyrä", + "Issue title": "Ilmoituksen otsikko", + "Items": "Kohteet", + "JOINTS": "NIVELET", + "Joint 1": "Nivel 1", + "Joint 2": "Nivel 2", + "Joint Origin1": "Nivelorigo1", + "K Factor": "K-kerroin", + "Keep (points on it)": "Säilytä (sen pisteet)", + "Keep Tools": "Säilytä työkalut", + "Keep of the other surface": "Säilytettävä osa toisesta pinnasta", + "Key a joint's value at this step": "Tallenna nivelen arvo avaimeksi tässä vaiheessa", + "Keys": "Avaimet", + "Knife Edge": "Veitsenterä", + "L-Angle": "L-profiili", + "LIBRARY": "KIRJASTO", + "LINKS": "LINKIT", + "Later": "Myöhemmin", + "Leave it": "Jätä ennalleen", + "Left Middle": "Vasemmalla keskellä", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Vanhanmallinen pintakiinnitys. Uudelleensidonta varmennettuun pintaan luo tarkan kiinnityksen.", + "Length": "Pituus", + "Length units": "Pituusyksiköt", + "Letter Spacing": "Merkkiväli", + "Library": "Kirjasto", + "Library file": "Kirjastotiedosto", + "Library response is missing": "Kirjaston vastaus puuttuu", + "Limits": "Raja-arvot", + "Line Spacing": "Riviväli", + "Line Type": "Viivatyyppi", + "Line on plane": "Viiva tasolla", + "Lines": "Viivat", + "Listing the installed fonts…": "Haetaan asennettuja fontteja…", + "Load library": "Lataa kirjasto", + "Local library": "Paikallinen kirjasto", + "Loop": "Silmukka", + "M5 or M5x0.5": "M5 tai M5x0.5", + "M5, M5x0.5, 1/4-20 UNC": "M5, M5x0.5, 1/4-20 UNC", + "MANAGE": "HALLITSE", + "MATERIALS": "MATERIAALIT", + "MODEL": "MALLI", + "MOTION": "LIIKE", + "Margin": "Marginaali", + "Mass": "Massa", + "Mass Center": "Massakeskipiste", + "Matched restrictions check the final values.": "Täsmäävät rajaukset tarkistavat lopulliset arvot.", + "Material": "Materiaali", + "Material Outside": "Materiaali ulkopuolella", + "Material copied. Existing body assignments are unchanged.": "Materiaali kopioitu. Kappaleiden nykyiset määritykset eivät muuttuneet.", + "Max": "Maks.", + "Max Thickness": "Suurin paksuus", + "Maximum": "Enimmäisarvo", + "Mesh body": "Verkkokappale", + "Mid Radius": "Keskisäde", + "Middle double-click": "Keskipainikkeen kaksoisnapsautus", + "Min": "Min.", + "Min Draft": "Pienin päästö", + "Min Thickness": "Pienin paksuus", + "Minimum": "Vähimmäisarvo", + "Mirror Plane": "Peilaustaso", + "Mitre": "Jiiri", + "Model Parameters": "Mallin parametrit", + "Modeled": "Mallinnettu", + "More toolbar panels": "Lisää työkalurivin paneeleja", + "Motion": "Liike", + "Mouse gestures": "Hiirieleet", + "Mouse gestures only work with the SolidWorks mouse mode (the wheel orbits, Ctrl + wheel pans).": "Hiirieleet toimivat vain SolidWorks-hiiritilassa (rulla kiertää, Ctrl + rulla panoroi).", + "Move / Copy": "Siirrä / kopioi", + "Move Type": "Siirron tyyppi", + "Move down": "Siirrä alas", + "Move earlier": "Siirrä aiemmaksi", + "Move holes by clicking or dragging": "Siirrä reikiä napsauttamalla tai vetämällä", + "Move later": "Siirrä myöhemmäksi", + "Move up": "Siirrä ylös", + "Name": "Nimi", + "Name on import": "Nimi tuotaessa", + "Nearest": "Lähin", + "Neutral plane": "Neutraalitaso", + "New": "Uusi", + "New Comp.": "Uusi komp.", + "New Sketch": "Uusi luonnos", + "New rule…": "Uusi sääntö…", + "New study": "Uusi tutkimus", + "No crash reports.": "Ei kaatumisraportteja.", + "No matching appearance presets.": "Ei vastaavia ulkoasun esiasetuksia.", + "No matching appearances": "Ei vastaavia ulkoasuja", + "No matching physical materials.": "Ei vastaavia fyysisiä materiaaleja.", + "No visible bodies or sketches to export.": "Ei näkyviä kappaleita tai luonnoksia vietäväksi.", + "Nominal Radius": "Nimellissäde", + "Nominal diameter": "Nimellishalkaisija", + "None": "Ei mitään", + "Not available yet": "Ei vielä käytettävissä", + "Not saved yet": "Ei vielä tallennettu", + "Notch": "Lovi", + "OUTPUT": "TULOSTE", + "Of": "/", + "On your computer": "Tietokoneellasi", + "Opacity": "Peittävyys", + "Open GitHub": "Avaa GitHub", + "Open GitHub draft": "Avaa GitHub-luonnos", + "Open GitHub issue form": "Avaa GitHubin ilmoituslomake", + "Open bodies (no volume)": "Avoimet kappaleet (ei tilavuutta)", + "Open library...": "Avaa kirjasto...", + "Open local libraries in the desktop app. You can export this design's library here.": "Avaa paikalliset kirjastot työpöytäsovelluksessa. Tämän mallin kirjaston voit viedä täällä.", + "Open surface — no volume": "Avoin pinta — ei tilavuutta", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Avoimen lähdekoodin parametrinen 3D-CAD, kirjoitettu Rustilla. Lisenssi: MIT OR Apache-2.0.", + "Opens your browser and copies the report text for you to paste into GitHub.": "Avaa selaimen ja kopioi raportin tekstin, jotta voit liittää sen GitHubiin.", + "Opens your browser and copies the report text. Review and submit your report on GitHub.": "Avaa selaimen ja kopioi raportin tekstin. Tarkista ja lähetä raportti GitHubissa.", + "Opens your browser. Review and submit your report on GitHub.": "Avaa selaimen. Tarkista ja lähetä raportti GitHubissa.", + "Operator": "Operaattori", + "Orbit (right drag)": "Kierrä (veto oikealla painikkeella)", + "Other side": "Toinen puoli", + "Other surface (mutual trim)": "Toinen pinta (keskinäinen katkaisu)", + "Other way": "Toiseen suuntaan", + "Outer Sharp": "Terävä ulkokulma", + "Outer radius": "Ulkosäde", + "Outside": "Ulkopuoli", + "Overall length": "Kokonaispituus", + "Param. Graph": "Param.kuvaaja", + "Parameter": "Parametri", + "Part length must be greater than zero and at most 2000 mm": "Osan pituuden on oltava suurempi kuin nolla ja enintään 2000 mm", + "Parts": "Osat", + "Pass through": "Läpi", + "Path": "Polku", + "Pattern": "Kuvio", + "Per Edge": "Särmäkohtainen", + "Physical material definitions": "Fyysisten materiaalien määritykset", + "Pick a part size": "Valitse osan koko", + "Pick the tool bodies": "Valitse työkalukappaleet", + "Picked": "Valittu", + "Picked point": "Valittu piste", + "Pin-slot": "Tappi-ura", + "Pitch": "Nousu", + "Pivot": "Kääntöpiste", + "Place at the origin instead": "Sijoita sen sijaan origoon", + "Planar": "Tasomainen", + "Plastic Rules": "Muovisäännöt", + "Play the joint's motion in the view": "Toista nivelen liike näkymässä", + "Playback": "Toisto", + "Plot": "Kuvaaja", + "Point on line": "Piste viivalla", + "Point on plane": "Piste tasolla", + "Position": "Sijainti", + "Position (0 to 1)": "Sijainti (0–1)", + "Position (G0)": "Sijainti (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "Sijainti särmää pitkin: 0 alkupäässä, 1 toisessa päässä", + "Preferences › Design turns the offer back on": "Asetukset › Suunnittelu ottaa ehdotuksen taas käyttöön", + "Preview": "Esikatselu", + "Preview Row": "Esikatsele riviä", + "Preview leaves the current design unchanged.": "Esikatselu ei muuta nykyistä mallia.", + "Profile / Edges": "Profiili / särmät", + "Profiles or curves": "Profiilit tai käyrät", + "Profiles/Curves": "Profiilit/käyrät", + "Quantity": "Määrä", + "Quantity must be at least 2": "Määrän on oltava vähintään 2", + "RECENT": "VIIMEISIMMÄT", + "REFERENCE": "VIITE", + "RULED SURFACE": "VIIVOITINPINTA", + "RULES": "SÄÄNNÖT", + "Radius": "Säde", + "Radius Fit": "Säteen sovitus", + "Ratio": "Suhde", + "Read-only list: shortcuts can't be changed here.": "Vain luku -luettelo: pikanäppäimiä ei voi muuttaa täällä.", + "Reattach selected face": "Kiinnitä valittu pinta uudelleen", + "Recover": "Palauta", + "Recover unsaved design?": "Palautetaanko tallentamaton malli?", + "Rectangular": "Suorakulmainen", + "Rectangular Tube": "Suorakaideputki", + "Reference face": "Referenssipinta", + "Relief Depth": "Vapautuksen syvyys", + "Relief Width": "Vapautuksen leveys", + "Remove Tools": "Poista työkalut", + "Remove condition": "Poista ehto", + "Remove from Folder": "Poista kansiosta", + "Remove from list": "Poista luettelosta", + "Remove override": "Poista ohitus", + "Remove private design details or paths before sharing.": "Poista mallin yksityiset tiedot ja polut ennen jakamista.", + "Remove screenshot": "Poista kuvakaappaus", + "Remove the column": "Poista sarake", + "Remove the track": "Poista raita", + "Remove this bend": "Poista tämä taivutus", + "Remove this point": "Poista tämä piste", + "Rename Feature": "Nimeä piirre uudelleen", + "Rename Folder": "Nimeä kansio uudelleen", + "Render Stage": "Renderöintinäyttämö", + "Reopen designs": "Avaa mallit uudelleen", + "Reopen the designs that were open when SolidCraft was last closed": "Avaa uudelleen mallit, jotka olivat auki, kun SolidCraft viimeksi suljettiin", + "Replace existing library file": "Korvaa olemassa oleva kirjastotiedosto", + "Report a bug — review a screenshot and open a GitHub draft": "Ilmoita virheestä — tarkista kuvakaappaus ja avaa GitHub-luonnos", + "Report copied. Keep this text to submit on GitHub when you are online.": "Raportti kopioitu. Säilytä tämä teksti ja lähetä se GitHubissa, kun olet verkossa.", + "Report text copied. Paste it into GitHub and submit your report there.": "Raportin teksti kopioitu. Liitä se GitHubiin ja lähetä raportti siellä.", + "Reports are public. A GitHub account is required.": "Raportit ovat julkisia. GitHub-tili vaaditaan.", + "Reset Toolbar": "Palauta työkalurivin oletukset", + "Resize Part": "Muuta osan kokoa", + "Restore View": "Palauta näkymä", + "Restore outer boundary": "Palauta ulkoreuna", + "Restore the inherited component or physical material appearance": "Palauta komponentilta tai fyysiseltä materiaalilta peritty ulkoasu", + "Restore this studio's tools": "Palauta tämän studion työkalut", + "Result": "Tulos", + "Retake screenshot": "Ota kuvakaappaus uudelleen", + "Reveal Height": "Esiin jäävä korkeus", + "Reverse": "Käännä", + "Reverse Direction": "Käännä suunta", + "Revert": "Palauta", + "Revert All Positions": "Palauta kaikki asennot", + "Revert Pos.": "Palauta as.", + "Revert Position": "Palauta sijainti", + "Review the report and screenshot before opening GitHub.": "Tarkista raportti ja kuvakaappaus ennen GitHubin avaamista.", + "Review your report on GitHub and click Submit new issue to publish it.": "Tarkista raporttisi GitHubissa ja julkaise se napsauttamalla Submit new issue.", + "Revolute": "Kiertyvä", + "Rib Length": "Rivan pituus", + "Rib Offset": "Rivan siirtymä", + "Rib Thickness": "Rivan paksuus", + "Ribs": "Rivat", + "Right Middle": "Oikealla keskellä", + "Rigid": "Jäykkä", + "Rim Edge": "Reunasärmä", + "Rim face": "Reunapinta", + "Ring of tools on the right button": "Työkalurengas hiiren oikeassa painikkeessa", + "Roll Back Here": "Palauta tähän", + "Roll History Marker Here": "Siirrä historiamerkki tähän", + "Root radius": "Pohjan säde", + "Round": "Pyöreä", + "Round Bar": "Pyörötanko", + "Round Tube": "Pyöröputki", + "Rule": "Sääntö", + "Rule name": "Säännön nimi", + "Rules run from top to bottom. Matched drives change effective values.": "Säännöt suoritetaan ylhäältä alas. Täsmäävät ohjaukset muuttavat voimassa olevia arvoja.", + "SECTION": "LEIKKAUS", + "SURFACE QUALITY": "PINNAN LAATU", + "Same way": "Samaan suuntaan", + "Save Rule": "Tallenna sääntö", + "Save View": "Tallenna näkymä", + "Save screenshot…": "Tallenna kuvakaappaus…", + "Save the study as an animated GIF, seen as the viewport shows it": "Tallenna tutkimus animoituna GIF-kuvana sellaisena kuin näkymäikkuna sen näyttää", + "Saved preview. Geometry is being checked before editing.": "Tallennettu esikatselu. Geometriaa tarkistetaan ennen muokkausta.", + "Scale factor": "Skaalauskerroin", + "Scene": "Kohtaus", + "Screenshot (optional)": "Kuvakaappaus (valinnainen)", + "Search": "Hae", + "Search commands": "Hae komentoja", + "Search this library": "Hae tästä kirjastosta", + "Second edge": "Toinen särmä", + "Second plane": "Toinen taso", + "Second point": "Toinen piste", + "Section": "Leikkaus", + "Section (optional)": "Leikkaus (valinnainen)", + "Section position": "Leikkauksen sijainti", + "Sections (one sketch each)": "Poikkileikkaukset (yksi luonnos kukin)", + "Select Other": "Valitse muu", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Valitse muu: pidä vasenta painiketta paikallaan mallin päällä (tai napsauta hiiren oikealla › Valitse muu…), niin kaikki kohdistimen alla olevat kohteet luetellaan; napsauta uudelleen samaa kohtaa, niin seuraava kohde valitaan. Kaksoisnapsauta keskipainiketta siirtyäksesi kotinäkymään (Asetukset › Navigointi).", + "Select Same Look": "Valitse sama ulkoasu", + "Select bodies (a face picks its body)": "Valitse kappaleet (pinta valitsee kappaleensa)", + "Select bodies or faces instead": "Valitse sen sijaan kappaleet tai pinnat", + "Select edges": "Valitse särmät", + "Select points of the sketch being edited": "Valitse muokattavan luonnoksen pisteet", + "Select the centre the pattern turns around first": "Valitse ensin keskipiste, jonka ympäri kuvio kiertää", + "Select the curves to offset first": "Valitse ensin siirrettävät käyrät", + "Select the mirror line": "Valitse peilausviiva", + "Select the sketch curves or points to mirror first": "Valitse ensin peilattavat luonnoskäyrät tai -pisteet", + "Select the sketch curves or points to move first": "Valitse ensin siirrettävät luonnoskäyrät tai -pisteet", + "Select the sketch curves or points to pattern first": "Valitse ensin kuvioitavat luonnoskäyrät tai -pisteet", + "Select the sketch curves or points to scale first": "Valitse ensin skaalattavat luonnoskäyrät tai -pisteet", + "Select the sketch curves or points to transform first": "Valitse ensin muunnettavat luonnoskäyrät tai -pisteet", + "Selection filter": "Valintasuodatin", + "Semantic faces share their appearance across instances.": "Semanttiset pinnat jakavat ulkoasunsa kaikkien esiintymien kesken.", + "Send your report on GitHub": "Lähetä raporttisi GitHubissa", + "Shaded": "Varjostettu", + "Shape": "Muoto", + "Sheet Rules": "Levysäännöt", + "Show Agent Cursor": "Näytä agentin kohdistin", + "Show ghost": "Näytä haamukuva", + "Show in folder": "Näytä kansiossa", + "Show the pointer an AI agent moves (#35)": "Näytä tekoälyagentin liikuttama osoitin (#35)", + "Show tool at cursor": "Näytä työkalu kohdistimen kohdalla", + "Signed axes": "Etumerkilliset akselit", + "Size": "Koko", + "Sketch constraints": "Luonnoksen rajoitteet", + "Sketch curves": "Luonnoskäyrät", + "Sketch dimensions": "Luonnoksen mitat", + "Sketch geometry and profiles": "Luonnoksen geometria ja profiilit", + "Sketch plane has no body-face attachment.": "Luonnostasolla ei ole kiinnitystä kappaleen pintaan.", + "Sketch points": "Luonnospisteet", + "Slider": "Liukuva", + "Slot width": "Uran leveys", + "Snap to face and edge centres": "Tartu pintojen ja särmien keskipisteisiin", + "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft ei voi lähettää raportteja suoraan. Lähetä GitHubissa; sovelluksessa ei tarvita tunnusta.", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft suljettiin ennen kuin nämä mallit tallennettiin. Niiden viimeisin automaattinen tallennus voidaan avata.", + "Spacing 2 must be a non-zero number": "Välin 2 on oltava nollasta poikkeava luku", + "Spacing must be a non-zero number": "Välin on oltava nollasta poikkeava luku", + "Specialise": "Erikoista", + "Speed": "Nopeus", + "Splitting tool": "Jakotyökalu", + "Square": "Neliö", + "Stand it up": "Nosta pystyyn", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Nosta pystyyn: neljänneskierros X-akselin ympäri yhtenä Siirrä-piirteenä, jonka voit kumota.", + "Stand this assembly up?": "Nostetaanko tämä kokoonpano pystyyn?", + "Stand this part up?": "Nostetaanko tämä osa pystyyn?", + "Start angle": "Alkukulma", + "Start bulge": "Alun pullistuma", + "Start continuity": "Alun jatkuvuus", + "Stationary Side": "Kiinteä puoli", + "Step": "Vaihe", + "Steps": "Vaiheet", + "Steps to reproduce (optional)": "Toistamisen vaiheet (valinnainen)", + "Stitch the kept pieces": "Ompele säilytetyt palat", + "Stitch to both bodies": "Ompele molempiin kappaleisiin", + "Studio": "Studio", + "Study": "Tutkimus", + "Style": "Tyyli", + "Summary": "Yhteenveto", + "Suppress": "Ohita", + "Suppress Selected Folders": "Ohita valitut kansiot", + "Suppressed": "Ohitettu", + "Surface": "Pinta", + "Surface, or faces to turn over": "Pinta tai käännettävät pinnat", + "Surfaces": "Pinnat", + "Swap Ends": "Vaihda päät", + "TRIM": "KATKAISE", + "Tangent": "Tangentti", + "Tangent (G1)": "Tangentti (G1)", + "Tangent Chain": "Tangenttiketju", + "Tangent chain": "Tangenttiketju", + "Tangent to Edge": "Tangentti särmään", + "Tap drill diameter": "Kierreporan halkaisija", + "Target": "Kohde", + "Target Body": "Kohdekappale", + "Target Face (optional)": "Kohdepinta (valinnainen)", + "Tear": "Repäisy", + "Technical details": "Tekniset tiedot", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Katkoviivainen luonnos on tallennettu tasoapu. Korjaa kiinnitys valitsemalla uusi pinta.", + "The design changed. Reopen Change Part Size for the component.": "Malli muuttui. Avaa Muuta osan kokoa uudelleen komponentille.", + "The direction must be an axis or a straight sketch curve that lies in the sketch plane": "Suunnan on oltava akseli tai suora luonnoskäyrä, joka on luonnostasossa", + "The mirror line cannot also be mirrored": "Peilausviivaa ei voi myös peilata", + "The mirror line must be a straight curve of this sketch, not an origin axis": "Peilausviivan on oltava tämän luonnoksen suora käyrä, ei origon akseli", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Tallennettu laatijan esiintymä puuttuu. Valitse kelvollinen laatijan sijoitus ennen uudelleensidontaa.", + "Then": "Sitten", + "These features will be deleted:": "Nämä piirteet poistetaan:", + "These features will fail:": "Nämä piirteet epäonnistuvat:", + "Thickness Outside": "Paksuus ulospäin", + "Thickness Variation": "Paksuuden vaihtelu", + "Thin": "Ohut", + "Thin Extrude": "Ohut pursotus", + "Third plane": "Kolmas taso", + "Third point": "Kolmas piste", + "This child is shared. Deleting it removes it from every copy of its parent.": "Tämä alikohde on jaettu. Sen poistaminen poistaa sen jokaisesta yläkohteen kopiosta.", + "This child is shared. Position changes apply to every copy of its parent.": "Tämä alikohde on jaettu. Sijaintimuutokset koskevat jokaista yläkohteen kopiota.", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "Tämä komponentti on alikokoonpanossa, joka on sijoitettu useammin kuin kerran: kohdistaminen siirtää sitä jokaisessa sijoituksessa.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Tämä pinta ei anna pysyvää kiinnitystä. Valitse toinen pinta tai käytä nimenomaisesti kiinteää tasoa.", + "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "Tätä kuvaa ei ole vielä liitetty GitHubiin. Kopioi tai tallenna se ja liitä se sitten GitHubissa.", + "Thread depth": "Kierteen syvyys", + "Thread diameter": "Kierteen halkaisija", + "Through point": "Pisteen kautta", + "To": "Kohteeseen", + "To Offset": "Siirtymään", + "To Snap": "Tartuntaan", + "To edges": "Särmiin", + "Toe radius": "Kärjen säde", + "Tolerance": "Toleranssi", + "Too close": "Liian lähellä", + "Tool Bodies": "Työkalukappaleet", + "Tools": "Työkalut", + "Tools, clockwise from the top": "Työkalut myötäpäivään ylhäältä alkaen", + "Top Left": "Ylhäällä vasemmalla", + "Top Middle": "Ylhäällä keskellä", + "Top Right": "Ylhäällä oikealla", + "Trimming tool (plane, face or curves)": "Katkaisutyökalu (taso, pinta tai käyrät)", + "Turn off section analysis before exporting the view.": "Poista leikkausanalyysi käytöstä ennen näkymän vientiä.", + "Type": "Tyyppi", + "Type a distance or an angle to move by": "Kirjoita siirron etäisyys tai kulma", + "UNTRIM": "PERU KATKAISU", + "Unit": "Yksikkö", + "Unsuppress": "Palauta käyttöön", + "Unsuppress Selected Folders": "Palauta valitut kansiot käyttöön", + "Updating the preview": "Päivitetään esikatselua", + "Use active author placement": "Käytä aktiivista laatijan sijoitusta", + "Use fixed plane": "Käytä kiinteää tasoa", + "Use saved fixed plane": "Käytä tallennettua kiinteää tasoa", + "Use selected face as fixed plane": "Käytä valittua pintaa kiinteänä tasona", + "Use the SolidWorks mouse mode": "Käytä SolidWorksin hiiritilaa", + "User Parameters": "Käyttäjän parametrit", + "VIEW": "NÄKYMÄ", + "VIEWS": "NÄKYMÄT", + "Value": "Arvo", + "Variable Radius": "Muuttuva säde", + "Velocity": "Nopeus", + "Vertices": "Kärkipisteet", + "View navigator": "Näkymänavigaattori", + "Volume": "Tilavuus", + "Wall": "Seinämä", + "Wall Location": "Seinämän sijainti", + "Wall Thickness": "Seinämän paksuus", + "Web thickness": "Uuman paksuus", + "What did you do just before the problem? A short list is enough": "Mitä teit juuri ennen ongelmaa? Lyhyt luettelo riittää", + "What did you expect to see?": "Mitä odotit näkeväsi?", + "What happened?": "Mitä tapahtui?", + "When": "Kun", + "Width": "Leveys", + "Will fail": "Epäonnistuu", + "With gestures on, the right button no longer orbits the view: hold it and move to open the ring, then touch a tool's zone. A plain right-click still opens the menu.": "Kun eleet ovat käytössä, oikea painike ei enää kierrä näkymää: pidä sitä painettuna ja liikuta hiirtä avataksesi renkaan, ja kosketa sitten työkalun aluetta. Pelkkä oikea napsautus avaa edelleen valikon.", + "X": "X", + "X Angle": "X-kulma", + "X angle": "X-kulma", + "X distance": "X-etäisyys", + "Y": "Y", + "Y Angle": "Y-kulma", + "Y angle": "Y-kulma", + "Y distance": "Y-etäisyys", + "Z": "Z", + "Z Angle": "Z-kulma", + "Z Distance": "Z-etäisyys", + "Z angle": "Z-kulma", + "Z distance": "Z-etäisyys", + "Zebra": "Seepra", + "`joint` must be an id or a name": "`joint` on oltava tunniste tai nimi", + "`params` must be an object": "`params` on oltava olio", + "`values` must be a list": "`values` on oltava lista", + "a chamfer needs a corner of exactly two lines": "viiste tarvitsee kulman, jossa on täsmälleen kaksi viivaa", + "a file operation is in progress": "tiedostotoiminto on käynnissä", + "a picked curve is no longer in a sketch": "valittu käyrä ei ole enää luonnoksessa", + "a picked curve's sketch has not been solved": "valitun käyrän luonnosta ei ole ratkaistu", + "a picked edge has no points": "valitulla särmällä ei ole pisteitä", + "a picked edge is gone": "valittu särmä on poistunut", + "a picked edge's body is gone": "valitun särmän kappale on poistunut", + "add a key for a joint first": "lisää ensin avain nivelelle", + "ai.connected_toast": "SolidCraft on nyt käytettävissä sovelluksissa {clients}. Käynnistä ne uudelleen ottaaksesi sen käyttöön (Asetukset > Avustaja).", + "ai.prefs.allow_control": "Salli tekoälyagenttien yhdistää (ohjauskanava / MCP)", + "ai.prefs.allow_control_note": "Avaa ohjauskanavan vain tälle tietokoneelle (127.0.0.1, portti 27878 tai seuraava vapaa). Yhdistävän ohjelman on myös esitettävä salainen tunniste, jonka vain käyttäjätilisi voi lukea ja joka luodaan uutena jokaisella käynnistyksellä. Tulee voimaan, kun SolidCraft käynnistetään seuraavan kerran. Pois: mikään ei kuuntele, ellei SolidCraftia käynnistetä valitsimella --control.", + "ai.prefs.availability": "Avustajan hallinta", + "ai.prefs.background_commands": "Suorita agentin komennot taustalla", + "ai.prefs.connect_apps": "Tuo SolidCraft tämän tietokoneen tekoälysovellusten käyttöön", + "ai.prefs.connect_apps_note": "Kun SolidCraft käynnistyy, se lisätään MCP-palvelimeksi tältä tietokoneelta löytyviin tekoälysovelluksiin (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), jotta agentti voi käyttää sitä ilman asetuksia. Vain solidcraft-merkintä lisätään tai sen polku päivitetään; muuttamaasi merkintään ei kosketa, ja tiedostosta otetaan ensin varmuuskopio. Pois: lisätyt merkinnät poistetaan. Ohje > Yhdistä tekoälyavustajat… tekee tämän käsin.", + "ai.prefs.connect_at_start": "Yhdistä viimeksi käytetty agentti, kun SolidCraft käynnistyy", + "ai.prefs.connect_at_start_note": "Käynnistää viimeksi yhdistämäsi agentin (tai oletusagentin) taustalle aina, kun SolidCraft käynnistyy, jotta se on valmiina keskusteluun. Ei, kun SolidCraft käynnistetään valitsimella --control. Jos yhteys ei onnistu, Avustaja näyttää ilmoituksen Yhteys epäonnistui ja Yritä uudelleen -painikkeen.", + "ai.prefs.follow_camera": "Käännä kamera luonnoksiin", + "ai.prefs.follow_camera_off": "Kameran automaattinen seuraaminen on pois käytöstä.", + "ai.prefs.follow_camera_on": "Kamera kääntyy kohti agentin luomia luonnoksia.", + "ai.prefs.intro": "Agentit, käyttöoikeudet ja miten niiden työ näkyy.", + "ai.prefs.make_default": "Käytä oletuksena", + "ai.prefs.no_agents": "Ei vielä agentteja. Lisää agentti tai päivitä löytääksesi asennetut agentit.", + "ai.prefs.no_saved_approvals": "Ei tallennettuja hyväksyntöjä.", + "ai.prefs.open_at_start": "Avaa Avustaja-paneeli, kun SolidCraft käynnistyy", + "ai.prefs.open_at_start_note": "Näyttää Avustaja-paneelin (tai sen oman ikkunan) aina, kun SolidCraft käynnistyy. Ei, kun SolidCraft käynnistetään valitsimella --control.", + "ai.prefs.override_all_warning": "Tämä agentti voi tallentaa, korvata, viedä tai vaihtaa mallin kysymättä.", + "ai.prefs.permission_all": "Salli kaikki", + "ai.prefs.permission_all_summary": "Käytettävissä olevat SolidCraft-työkalut suoritetaan kysymättä.", + "ai.prefs.permission_ask": "Kysy ennen muutoksia", + "ai.prefs.permission_ask_summary": "Hyväksy jokainen mallimuutos ja tiedostotoiminto.", + "ai.prefs.permission_edits": "Salli mallin muokkaukset", + "ai.prefs.permission_edits_summary": "Mallin muokkaukset suoritetaan; tiedostotoiminnot ja tuhoavat toiminnot kysytään edelleen.", + "ai.prefs.permission_scope": "Koskee vain SolidCraft-työkaluja. Agentin komentotulkki ja tiedostomuokkaukset käyttävät sen omia käyttöoikeuksia.", + "ai.prefs.pointer_preview_hidden": "Osoitin piilotettu", + "ai.prefs.pointer_preview_speed": "Agentin osoitin · {speed}", + "ai.prefs.pointer_speed": "Liikenopeus", + "ai.prefs.privacy_note": "Vain valitsemasi agentti tai päätepiste saa keskustelun. Päätepisteiden avaimet tallennetaan järjestelmän avainnippuun.", + "ai.prefs.show_pointer": "Näytä agentin osoitin", + "ai.prefs.turn_limit_hint": "Mallia muuttavien työkalukutsujen enimmäismäärä, jonka Avustaja voi tehdä yhtä viestiä kohden.", + "angle, height": "kulma, korkeus", + "appearance.dielectric_ior": "Dielektrinen IOR", + "appearance.metallic": "Metallisuus", + "appearance.only_available": "Vain käytettävissä olevat ulkoasut", + "appearance.pbr_help": "Näytä tämä pinta renderöinnissä tai tuote-PNG:ssä. Ei taittumista eikä läpäisyä.", + "appearance.pbr_opaque": "Läpinäkymätön PBR", + "appearance.roughness": "Karheus", + "appearance.surface_response": "Pinnan vaste", + "at the face": "pinnassa", + "bom.group_children": "Alaosat osansa rivillä", + "browser.body_name": "Kappale{number}", + "browser.calibrate_click_a": "Napsauta kuvaa kohdassa Piste A tai kirjoita sen koordinaatit.", + "browser.calibrate_click_b": "Napsauta kuvaa kohdassa Piste B tai kirjoita sen koordinaatit.", + "browser.calibrate_title": "Kalibroi: {name}", + "browser.capture_many": "{count} komponenttia siirrettiin, mutta niiden sijainteja ei ole tallennettu.", + "browser.capture_note": "Tallenna sijainti säilyttää uuden sijainnin; Palauta siirtää sen takaisin.", + "browser.capture_one": "Komponenttia siirrettiin, mutta sen sijaintia ei ole tallennettu.", + "browser.component_name": "Komponentti{number}", + "browser.edit_canvas_title": "Muokkaa pohjakuvaa: {name}", + "browser.edit_point_cloud_title": "Muokkaa pistepilveä: {name}", + "browser.move_title": "Siirrä: {name}", + "browser.parameters": "Parametrit ({count})", + "browser.precision": "Tarkkuus: {precision}", + "browser.sketch_attachment_lost": "{name} (kiinnitys kadonnut)", + "browser.sketch_editing": "{name} (muokataan)", + "browser.sketch_name": "Luonnos{number}", + "browser.units": "Yksiköt: {units}", + "cam.flat": "Tasainen pinta", + "cam.follower": "Seuraaja", + "cam.knife": "Veitsisärmä", + "cam.needs_joints": "tarvitsee nivelen, joka pyörii, ja nivelen, joka liukuu tai heilahtaa", + "cam.roller": "Rulla", + "cam.roller_pick": "Rulla (valinnainen)", + "cam.tip_pick": "Kärki (valinnainen)", + "camera.shot_pitch": "Nyökkäys", + "camera.shot_roll": "Kallistus", + "camera.shot_yaw": "Kääntö", + "canvas.decal_place_hint": "Sijoita tarra napsauttamalla pintaa", + "canvas.place_hint": "Sijoita pohjakuva napsauttamalla tasoa tai pintaa", + "choose a profile": "valitse profiili", + "choose the cam's and the follower's joints": "valitse nokan ja seuraajan nivelet", + "choose the joints to couple": "valitse kytkettävät nivelet", + "click a plane or planar face": "napsauta tasoa tai tasopintaa", + "click sketch curves": "napsauta luonnoskäyriä", + "cmd.appearance_assign": "Ulkoasu", + "cmd.appearance_chain": "Ulkoasuketju", + "cmd.appearance_copy": "Kopioi ulkoasu", + "cmd.appearance_favorite": "Suosikkiulkoasu", + "cmd.appearance_library": "Ulkoasukirjasto", + "cmd.appearance_list": "Luettele ulkoasut", + "cmd.appearance_paint": "Maalaa ulkoasu", + "cmd.appearance_paste": "Liitä ulkoasu", + "cmd.appearance_pick_up": "Poimi ulkoasu", + "cmd.appearance_replace": "Korvaa ulkoasu", + "cmd.assembly_bom": "Osaluettelo", + "cmd.body.print_face": "Tulostuspinta", + "cmd.body_rename": "Nimeä kappale uudelleen", + "cmd.browser_collapse_all": "Kutista kaikki", + "cmd.browser_expand_all": "Laajenna kaikki", + "cmd.browser_group": "Uusi ryhmä", + "cmd.browser_move": "Siirrä selaimen kohteita", + "cmd.browser_order": "Järjestä selaimen kohteet", + "cmd.browser_rename_group": "Nimeä ryhmä uudelleen", + "cmd.browser_reparent": "Siirrä komponenttiin", + "cmd.browser_ungroup": "Pura ryhmä", + "cmd.browser_visibility": "Näytä/piilota", + "cmd.canvas_calibrate": "Kalibroi pohjakuva", + "cmd.canvas_decal": "Tarra", + "cmd.canvas_delete": "Poista pohjakuva", + "cmd.canvas_edit": "Muokkaa pohjakuvaa", + "cmd.canvas_insert": "Pohjakuva", + "cmd.canvas_to_sketch": "Pohjakuva luonnokseksi", + "cmd.component_activate": "Aktivoi komponentti", + "cmd.component_break_link": "Katkaise linkki", + "cmd.component_capture_position": "Tallenna sijainti", + "cmd.component_copies": "Etsi identtiset kopiot", + "cmd.component_copy_bodies": "Liitä kappaleet", + "cmd.component_create": "Uusi komponentti", + "cmd.component_cycle_color": "Vaihda komponentin väriä", + "cmd.component_delete": "Poista komponentti", + "cmd.component_edit_in_place": "Muokkaa paikallaan", + "cmd.component_extract": "Irrota tiedostoksi", + "cmd.component_finish_edit": "Lopeta muokkaus", + "cmd.component_from_bodies": "Luo komponentit kappaleista", + "cmd.component_insert_design": "Lisää malli", + "cmd.component_links": "Luettele linkit", + "cmd.component_list": "Luettele komponentit", + "cmd.component_metadata": "Osan ominaisuudet", + "cmd.component_metadata_set": "Muuta osan ominaisuuksia", + "cmd.component_move_bodies": "Siirrä kappaleet komponenttiin", + "cmd.component_move_features": "Siirrä piirteet komponenttiin", + "cmd.component_move_sketches": "Siirrä luonnokset komponenttiin", + "cmd.component_paste_from_design": "Liitä toisesta mallista", + "cmd.component_paste_new": "Liitä uutena", + "cmd.component_properties": "Komponentin fysikaaliset ominaisuudet", + "cmd.component_relink": "Linkitä lähde uudelleen", + "cmd.component_rename": "Nimeä komponentti uudelleen", + "cmd.component_replace_with_link": "Korvaa linkillä", + "cmd.component_revert_position": "Palauta sijainti", + "cmd.component_unlock": "Avaa sisällön lukitus", + "cmd.component_update_links": "Päivitä linkit", + "cmd.config_activate": "Aktivoi konfiguraatio", + "cmd.config_column": "Konfiguraatiosarake", + "cmd.config_configure": "Konfiguroi", + "cmd.config_preview": "Esikatsele konfiguraatiota", + "cmd.config_row": "Konfiguraatiorivi", + "cmd.config_rule": "Konfiguraatiosääntö", + "cmd.config_rules": "Konfiguraatiosäännöt", + "cmd.config_table": "Näytä konfiguraatiotaulukko", + "cmd.construct_axis_edge": "Akseli särmän kautta", + "cmd.construct_axis_normal_to_face": "Akseli kohtisuoraan pintaan", + "cmd.construct_axis_through_cylinder": "Akseli sylinterin/kartion/toruksen kautta", + "cmd.construct_axis_two_planes": "Akseli kahden tason kautta", + "cmd.construct_axis_two_points": "Akseli kahden pisteen kautta", + "cmd.construct_plane_along_path": "Taso polkua pitkin", + "cmd.construct_plane_midplane": "Keskitaso", + "cmd.construct_plane_perpendicular": "Kohtisuora taso", + "cmd.construct_plane_tangent": "Tangenttitaso", + "cmd.construct_plane_three_points": "Taso kolmen pisteen kautta", + "cmd.construct_plane_two_edges": "Taso kahden särmän kautta", + "cmd.construct_point_along_path": "Piste polkua pitkin", + "cmd.construct_point_center": "Piste ympyrän/pallon/toruksen keskipisteeseen", + "cmd.construct_point_edge_plane": "Piste särmän ja tason leikkaukseen", + "cmd.construct_point_three_planes": "Piste kolmen tason kautta", + "cmd.construct_point_two_edges": "Piste kahden särmän kautta", + "cmd.construct_point_vertex": "Piste kärkipisteeseen", + "cmd.contact_check": "Tarkista kosketus", + "cmd.contact_create": "Uusi kosketusjoukko", + "cmd.contact_disable_all": "Poista kosketus käytöstä", + "cmd.contact_edit": "Muokkaa kosketusjoukkoa", + "cmd.contact_enable_all": "Ota kaikki kosketus käyttöön", + "cmd.contact_enable_sets": "Ota kosketusjoukot käyttöön", + "cmd.contact_list": "Luettele kosketusjoukot", + "cmd.diagnostics_crash_report": "Kaatumisraportti", + "cmd.diagnostics_crash_reports": "Kaatumisraportit", + "cmd.diagnostics_crash_reports_clear": "Poista kaatumisraportit", + "cmd.diagnostics_crash_test": "Kaatumistesti", + "cmd.doc_recover": "Palauta malli", + "cmd.doc_recovery_discard": "Hylkää palautettu malli", + "cmd.doc_recovery_list": "Palautettavat mallit", + "cmd.document_inspect": "Tarkastele mallia", + "cmd.document_metadata": "Mallin ominaisuudet", + "cmd.document_metadata_remove": "Poista mallin ominaisuus", + "cmd.document_metadata_set": "Muuta mallin ominaisuuksia", + "cmd.document_revision": "Mallin revisio", + "cmd.document_units": "Muuta mallin yksiköitä", + "cmd.edit_checkpoint": "Tarkistuspiste", + "cmd.edit_repeat": "Toista edellinen komento", + "cmd.edit_restore_checkpoint": "Palauta tarkistuspiste", + "cmd.engine_commands": "Luettele komennot", + "cmd.engine_describe": "Kuvaile komento", + "cmd.explode_create": "Räjäytyskuva", + "cmd.explode_delete": "Poista räjäytyskuva", + "cmd.explode_list": "Luettele räjäytyskuvat", + "cmd.explode_show": "Näytä räjäytyskuva", + "cmd.expr_evaluate": "Laske lauseke", + "cmd.face_delete": "Poista pinta", + "cmd.file_export": "Vie", + "cmd.file_insert_mesh": "Lisää verkko", + "cmd.file_insert_step": "Lisää STEP", + "cmd.file_open_in_easyprint": "Avaa EasyPrintillä", + "cmd.file_save_mesh": "Tallenna verkkona", + "cmd.file_send_to_slicer": "Lähetä viipalointiohjelmaan", + "cmd.file_slicers": "Asennetut viipalointiohjelmat", + "cmd.frame_member": "Runkopalkki", + "cmd.frame_profile_insert": "Lisää profiili", + "cmd.frame_profile_list": "Profiilikirjasto", + "cmd.frame_profile_properties": "Profiilin ominaisuudet", + "cmd.inspect_accessibility": "Saavutettavuusanalyysi", + "cmd.inspect_center_of_mass": "Massakeskipiste", + "cmd.inspect_clearance": "Välys", + "cmd.inspect_colored_components": "Ota komponenttivärit käyttöön", + "cmd.inspect_colored_components_disable": "Poista komponenttivärit käytöstä", + "cmd.inspect_compare": "Vertaa kappaleita", + "cmd.inspect_continuity": "Jatkuvuusanalyysi", + "cmd.inspect_curvature_comb": "Kaarevuuskampa-analyysi", + "cmd.inspect_curvature_map": "Kaarevuuskartta-analyysi", + "cmd.inspect_draft": "Päästöanalyysi", + "cmd.inspect_environment_map": "Ympäristökartta-analyysi", + "cmd.inspect_interference": "Päällekkäisyys", + "cmd.inspect_isocurve": "Isokäyräanalyysi", + "cmd.inspect_minimum_radius": "Pienimmän säteen analyysi", + "cmd.inspect_parameter_sweep": "Parametrin läpikäynti", + "cmd.inspect_silhouette": "Ääriviiva", + "cmd.inspect_zebra": "Seepra-analyysi", + "cmd.joint_as_built": "Nykyasennon mukainen nivel", + "cmd.joint_cam": "Nokka", + "cmd.joint_create": "Nivel", + "cmd.joint_delete": "Poista nivel", + "cmd.joint_drive": "Ohjaa niveliä", + "cmd.joint_edit": "Muokkaa niveltä", + "cmd.joint_gear": "Hammaspyörä", + "cmd.joint_inspect": "Tarkastele niveltä", + "cmd.joint_limits": "Nivelen rajat", + "cmd.joint_list": "Luettele nivelet", + "cmd.joint_motion_link": "Liikelinkki", + "cmd.joint_origin": "Nivelen origo", + "cmd.joint_rack_pinion": "Hammastanko ja -pyörä", + "cmd.joint_reach": "Tavoita piste", + "cmd.joint_rigid_group": "Jäykkä ryhmä", + "cmd.joint_screw": "Ruuvi", + "cmd.joint_solve": "Ratkaise nivelet", + "cmd.joint_sweep": "Käy nivel läpi", + "cmd.library_apply": "Käytä paikallisen kirjaston kohdetta", + "cmd.library_export": "Vie mallikirjasto", + "cmd.library_inspect": "Tarkastele paikallista kirjastoa", + "cmd.material_assign": "Fysikaalinen materiaali", + "cmd.material_create": "Uusi fysikaalinen materiaali", + "cmd.material_delete": "Poista fysikaalinen materiaali", + "cmd.material_edit": "Muokkaa fysikaalista materiaalia", + "cmd.material_inspect": "Tarkastele fysikaalista materiaalia", + "cmd.material_list": "Luettele materiaalit", + "cmd.material_properties_directional": "Suuntakohtainen kimmokerroin", + "cmd.material_properties_validate": "Tarkista fysikaalisen materiaalin tiedot", + "cmd.mesh_convert": "Muunna verkko", + "cmd.model_edges": "Luettele särmät", + "cmd.model_faces": "Luettele pinnat", + "cmd.model_threads": "Luettele kierteet", + "cmd.motion_delete": "Poista liiketutkimus", + "cmd.motion_export": "Vie liiketutkimus", + "cmd.motion_export_animation": "Vie liikeanimaatio", + "cmd.motion_interference": "Liikkeen päällekkäisyys", + "cmd.motion_list": "Luettele liiketutkimukset", + "cmd.motion_play": "Toista liiketutkimus", + "cmd.motion_plot": "Piirrä liiketutkimuksen kuvaaja", + "cmd.motion_study": "Liiketutkimus", + "cmd.motion_trace": "Liikerata", + "cmd.motion_trace_edit": "Muokkaa liikerataa", + "cmd.motion_trace_keep": "Säilytä liikerata", + "cmd.occurrence_align": "Kohdista esiintymä", + "cmd.occurrence_copy": "Liitä (esiintymä)", + "cmd.occurrence_drag": "Vedä esiintymää", + "cmd.occurrence_ground": "Kiinnitä maahan", + "cmd.occurrence_move": "Siirrä esiintymää", + "cmd.occurrence_properties": "Esiintymän fysikaaliset ominaisuudet", + "cmd.occurrence_reparent": "Siirrä komponenttiin", + "cmd.parameters_add": "Lisää käyttäjäparametri", + "cmd.parameters_change": "Muuta parametreja", + "cmd.parameters_comment": "Kommentoi parametria", + "cmd.parameters_complete": "Täydennä lauseke", + "cmd.parameters_delete": "Poista parametri", + "cmd.parameters_export": "Vie parametrit", + "cmd.parameters_favorite": "Suosikkiparametri", + "cmd.parameters_graph": "Parametrikaavio", + "cmd.parameters_import": "Tuo parametrit", + "cmd.parameters_list": "Luettele parametrit", + "cmd.parameters_move": "Siirrä parametri", + "cmd.parameters_rename": "Nimeä parametri uudelleen", + "cmd.parameters_users": "Parametrin käyttäjät", + "cmd.parts_fastener": "Lisää kiinnitin", + "cmd.parts_insert": "Lisää osa", + "cmd.parts_library": "Vakio-osat", + "cmd.parts_resize": "Muuta osan kokoa", + "cmd.plastic_assign_rule": "Määritä muovisääntö", + "cmd.plastic_boss": "Tappi", + "cmd.plastic_lip": "Huuli", + "cmd.plastic_manage_rules": "Hallitse muovisääntöjä", + "cmd.plastic_rest": "Tuki", + "cmd.plastic_rules": "Luettele muovisäännöt", + "cmd.plastic_snap_fit": "Napsautusliitos", + "cmd.pointcloud_delete": "Poista pistepilvi", + "cmd.pointcloud_edit": "Muokkaa pistepilveä", + "cmd.pointcloud_insert": "Lisää pistepilvi", + "cmd.pointcloud_list": "Pistepilvet", + "cmd.render_aging_describe": "Kerroksellinen pinnan vanhentaminen", + "cmd.render_backends": "Renderöintimoottorit", + "cmd.render_batch": "Renderöi kaikki kuvakulmat", + "cmd.render_camera_fit": "Rajaa renderöinnin kohde", + "cmd.render_camera_get": "Tarkastele renderöintikameraa", + "cmd.render_cancel": "Peruuta renderöinti", + "cmd.render_compare": "Vertaa kuvia", + "cmd.render_effects_describe": "Linssi- ja luovat tehosteet", + "cmd.render_export": "Vie renderöity kuva", + "cmd.render_hdr_inspect": "Tarkastele HDR-lähdettä", + "cmd.render_library_appearance_apply": "Käytä kirjaston läpinäkymätöntä ulkoasua", + "cmd.render_library_describe": "Tarkastele renderöintikirjaston resurssia", + "cmd.render_library_environment_apply": "Käytä sisäänrakennettua HDR-ympäristöä", + "cmd.render_library_list": "Selaa renderöintikirjastoa", + "cmd.render_library_physical_prepare": "Valmistele fysikaalinen viite", + "cmd.render_library_preview": "Tarkastele alkuperäistä pintakarttaa", + "cmd.render_library_studio_apply": "Käytä laadittuja studiovaloja", + "cmd.render_library_studio_prepare": "Valmistele laaditut studiovalot", + "cmd.render_library_surface_bind": "Tallenna pintasidonta", + "cmd.render_library_surface_prepare": "Valmistele laaditut pintakartat", + "cmd.render_library_surface_unbind": "Poista pintasidonta", + "cmd.render_library_targets": "Etsi renderöintikirjaston kohteet", + "cmd.render_lights_add": "Lisää valo", + "cmd.render_lights_duplicate": "Monista renderöintivalo", + "cmd.render_lights_list": "Luettele renderöintivalot", + "cmd.render_lights_mute": "Mykistä valo", + "cmd.render_lights_remove": "Poista renderöintivalo", + "cmd.render_lights_set": "Aseta renderöintivalo", + "cmd.render_lights_solo": "Vain tämä valo", + "cmd.render_optics_bind": "Tallenna optinen sidonta", + "cmd.render_optics_unbind": "Poista optinen sidonta", + "cmd.render_output_size": "Aseta renderöinnin tulostekoko", + "cmd.render_preflight": "Tarkista renderöintipyyntö", + "cmd.render_preflight_copy": "Kopioi renderöinnin tarkistusraportti", + "cmd.render_preset_apply": "Käytä natiivistudiota", + "cmd.render_preset_resolve": "Tarkista natiivistudio", + "cmd.render_quality_prepare": "Tarkista kiinteä näytteistysbudjetti", + "cmd.render_result_close": "Sulje renderöity kuva", + "cmd.render_result_copy": "Kopioi renderöity kuva", + "cmd.render_result_pin": "Säilytä näytetty renderöintitulos", + "cmd.render_result_regrade": "Sävytä lineaarinen master uudelleen", + "cmd.render_result_view": "Näytä renderöity kuva", + "cmd.render_scene": "Tarkastele renderöintinäkymää", + "cmd.render_settings_apply": "Käytä renderöintikameraa", + "cmd.render_settings_capture_hdr": "Tallenna renderöintiasetukset HDR:n kanssa", + "cmd.render_settings_get": "Renderöintiasetukset", + "cmd.render_settings_set": "Tallenna renderöintiasetukset", + "cmd.render_shot_duplicate": "Monista renderöinnin kuvakulma", + "cmd.render_shot_remove": "Poista renderöinnin kuvakulma", + "cmd.render_shot_rename": "Nimeä renderöinnin kuvakulma uudelleen", + "cmd.render_stage_backdrop": "Tallenna fysikaalinen renderöintitausta", + "cmd.render_stage_clear": "Poista renderöintilava", + "cmd.render_stage_ground": "Tallenna renderöinnin maapinta", + "cmd.render_start": "Renderöi kuva", + "cmd.render_status": "Renderöinnin edistyminen", + "cmd.select_clear": "Tyhjennä valinta", + "cmd.settings_profile_apply": "Käytä asetusprofiilia", + "cmd.settings_profile_delete": "Poista asetusprofiili", + "cmd.settings_profile_export": "Vie asetusprofiili", + "cmd.settings_profile_import": "Tuo asetusprofiili", + "cmd.settings_profile_list": "Asetusprofiilit", + "cmd.settings_profile_rename": "Nimeä asetusprofiili uudelleen", + "cmd.settings_profile_save": "Tallenna asetusprofiili", + "cmd.sheet_convert": "Muunna ohutlevyksi", + "cmd.sheet_export_bend_table": "Vie taivutustaulukko", + "cmd.sheet_export_dxf": "Vie levityskuva DXF-muodossa", + "cmd.sheet_flange": "Laippa", + "cmd.sheet_flat_pattern": "Luo levityskuva", + "cmd.sheet_fold": "Taita", + "cmd.sheet_hem": "Huulos", + "cmd.sheet_manage_rules": "Ohutlevysäännöt", + "cmd.sheet_path_flange": "Polkulaippa", + "cmd.sheet_perforate": "Rei'itä", + "cmd.sheet_refold": "Taita uudelleen", + "cmd.sheet_rules": "Luettele ohutlevysäännöt", + "cmd.sheet_unfold": "Avaa", + "cmd.sketch.construction_line": "Apuviiva", + "cmd.sketch.construction_line.angle": "Apuviiva kulmassa", + "cmd.sketch.construction_line.bisector": "Kulman puolittaja", + "cmd.sketch.construction_line.horizontal": "Vaakasuora apuviiva", + "cmd.sketch.construction_line.parallel": "Yhdensuuntainen apuviiva", + "cmd.sketch.construction_line.perpendicular": "Kohtisuora apuviiva", + "cmd.sketch.construction_line.tangent_at": "Tangentti käyrän pisteessä", + "cmd.sketch.construction_line.tangent_external": "Tangentti ulkoisen pisteen kautta", + "cmd.sketch.construction_line.tangent_two": "Yhteinen tangentti", + "cmd.sketch.construction_line.vertical": "Pystysuora apuviiva", + "cmd.sketch_arc3d": "3D-kaari", + "cmd.sketch_arc_center_point": "Keskipistekaari", + "cmd.sketch_arc_tangent": "Tangenttikaari", + "cmd.sketch_arc_three_point": "3 pisteen kaari", + "cmd.sketch_auto_constrain": "Automaattirajoitus", + "cmd.sketch_auto_constrain_from_datum": "Automaattirajoitus perustasosta", + "cmd.sketch_auto_project": "Projisoi särmät automaattisesti viitteelle", + "cmd.sketch_blend_curve": "Liukukäyrä", + "cmd.sketch_cancel": "Peruuta luonnos", + "cmd.sketch_chain": "Ketju", + "cmd.sketch_chamfer_distance_angle": "Etäisyys ja kulma -viiste", + "cmd.sketch_chamfer_equal_distance": "Yhtä suurten etäisyyksien viiste", + "cmd.sketch_chamfer_two_distance": "Kahden etäisyyden viiste", + "cmd.sketch_circle_center": "Keskipiste ja halkaisija -ympyrä", + "cmd.sketch_circle_three_point": "3 pisteen ympyrä", + "cmd.sketch_circle_three_tangent": "3 tangentin ympyrä", + "cmd.sketch_circle_two_point": "2 pisteen ympyrä", + "cmd.sketch_circle_two_tangent": "2 tangentin ympyrä", + "cmd.sketch_constrainer": "Luonnoksen rajoitin", + "cmd.sketch_constraint_fix": "Kiinnitä/vapauta", + "cmd.sketch_constraint_midpoint": "Keskipiste", + "cmd.sketch_construction": "Normaali/apu", + "cmd.sketch_copy": "Kopioi luonnoksen entiteetit", + "cmd.sketch_cut": "Leikkaa luonnoksen entiteetit", + "cmd.sketch_delete": "Poista luonnoksen entiteetit", + "cmd.sketch_dimension_text": "Siirrä mittatekstiä", + "cmd.sketch_drag": "Vedä luonnosgeometriaa", + "cmd.sketch_drag_end": "Lopeta luonnoksen veto", + "cmd.sketch_draw_dimensioned": "Piirrä mitoitettua luonnosgeometriaa", + "cmd.sketch_drawing_bounds": "Piirustuksen koko", + "cmd.sketch_edit": "Muokkaa luonnosta", + "cmd.sketch_edit_text": "Muokkaa tekstiä", + "cmd.sketch_equation_curve": "Yhtälökäyrä", + "cmd.sketch_equation_curve_edit": "Muokkaa yhtälökäyrää", + "cmd.sketch_export_dxf": "Tallenna DXF-muodossa", + "cmd.sketch_finish_auto_constrain": "Lopeta automaattirajoituksella", + "cmd.sketch_fit_curves_to_section": "Sovita käyrät verkon leikkaukseen", + "cmd.sketch_glyphs": "Rajoitesymbolit", + "cmd.sketch_include_3d": "Sisällytä 3D-geometria", + "cmd.sketch_infinite": "Ääretön viiva", + "cmd.sketch_insert_dxf": "Lisää DXF", + "cmd.sketch_insert_svg": "Lisää SVG", + "cmd.sketch_inspect": "Tarkastele luonnosta", + "cmd.sketch_intersection_curve": "Leikkauskäyrä", + "cmd.sketch_isoparametric_curve": "Isoparametrinen käyrä", + "cmd.sketch_line3d": "3D-viiva", + "cmd.sketch_line_midpoint": "Keskipisteviiva", + "cmd.sketch_loose_ends": "Irralliset päät", + "cmd.sketch_loose_ends_tie": "Yhdistä irralliset päät", + "cmd.sketch_move": "Siirrä/kopioi luonnoksen entiteetit", + "cmd.sketch_move3d": "Siirrä 3D-pistettä", + "cmd.sketch_move_point": "Vedä luonnospistettä", + "cmd.sketch_offset_break": "Katkaise siirtymän yhteys", + "cmd.sketch_options": "Luonnospaletin asetukset", + "cmd.sketch_paste": "Liitä luonnoksen entiteetit", + "cmd.sketch_point3d": "3D-piste", + "cmd.sketch_polygon_circumscribed": "Ympäri piirretty monikulmio", + "cmd.sketch_polygon_edge": "Sivun mukainen monikulmio", + "cmd.sketch_polygon_inscribed": "Sisään piirretty monikulmio", + "cmd.sketch_project_to_surface": "Projisoi pinnalle", + "cmd.sketch_rectangle_center": "Keskipistesuorakulmio", + "cmd.sketch_rectangle_rounded": "Pyöristetty suorakulmio", + "cmd.sketch_rectangle_three_point": "3 pisteen suorakulmio", + "cmd.sketch_rectangle_two_point": "2 pisteen suorakulmio", + "cmd.sketch_redefine": "Määritä luonnostaso uudelleen", + "cmd.sketch_slot_arc_center": "Keskipistekaariura", + "cmd.sketch_slot_arc_three_point": "Kolmen pisteen kaariura", + "cmd.sketch_slot_center_point": "Keskipisteura", + "cmd.sketch_slot_center_to_center": "Keskeltä keskelle -ura", + "cmd.sketch_slot_overall": "Kokonaismitan ura", + "cmd.sketch_snap": "Tartuntapäättely", + "cmd.sketch_solve": "Ratkaise luonnos", + "cmd.sketch_spline3d": "3D-splini", + "cmd.sketch_spline_control_point": "Ohjauspistesplini", + "cmd.sketch_spline_control_point_5": "Ohjauspistesplini (aste 5)", + "cmd.sketch_spline_fit_point": "Sovituspistesplini", + "cmd.sketch_spline_insert_point": "Lisää splinipiste", + "cmd.sketch_spline_remove_point": "Poista splinipiste", + "cmd.sketch_spline_reverse": "Käännä splinin suunta", + "cmd.sketch_spun_profile": "Pyöräytysprofiili", + "cmd.sketch_toggle_diameter": "Vaihda säde / halkaisija", + "cmd.sketch_toggle_driven": "Vaihda ohjattu mitta", + "cmd.sketch_transform": "Muunna", + "cmd.sketch_trim_path": "Katkaise polkua pitkin", + "cmd.solid_align": "Kohdista", + "cmd.solid_boundary_fill": "Rajatäyttö", + "cmd.solid_bounding_solid": "Ympäröivä kappale", + "cmd.solid_emboss": "Kohokuvio", + "cmd.solid_move": "Siirrä/kopioi", + "cmd.solid_offset_face": "Pinnan siirtymä", + "cmd.solid_press_pull": "Työnnä/vedä", + "cmd.solid_remove": "Poista", + "cmd.solid_replace_face": "Korvaa pinta", + "cmd.solid_rib": "Ripa", + "cmd.solid_split_face": "Jaa pinta", + "cmd.solid_web": "Uuma", + "cmd.surface_blend": "Sovituspinta", + "cmd.surface_boundary": "Reunapinta", + "cmd.surface_extrude": "Pintapursotus", + "cmd.surface_fair": "Silota pinta", + "cmd.surface_fillet": "Pintapyöristys", + "cmd.surface_loft": "Pintalofttaus", + "cmd.surface_match": "Sovita pinta", + "cmd.surface_offset": "Siirtymäpinta", + "cmd.surface_patch": "Paikkapinta", + "cmd.surface_reverse_normal": "Käännä normaali", + "cmd.surface_revolve": "Pintapyöräytys", + "cmd.surface_ruled": "Viivapinta", + "cmd.surface_stitch": "Ompele", + "cmd.surface_sweep": "Pintapyyhkäisy", + "cmd.surface_thicken": "Paksunna", + "cmd.surface_unstitch": "Pura ommel", + "cmd.surface_untrim": "Poista katkaisu", + "cmd.timeline_add": "Lisää tallennettu piirre", + "cmd.timeline_compute_all": "Laske kaikki", + "cmd.timeline_copy": "Kopioi piirteet", + "cmd.timeline_dependents": "Piirteestä riippuvat", + "cmd.timeline_export_script": "Vie komentoskripti", + "cmd.timeline_inspect": "Tarkastele piirrettä", + "cmd.timeline_paste": "Liitä piirteet", + "cmd.timeline_play": "Toista historia", + "cmd.timeline_redefine": "Muokkaa piirrettä", + "cmd.timeline_rename": "Nimeä uudelleen", + "cmd.timeline_reorder": "Järjestä piirre uudelleen", + "cmd.timeline_roll_to": "Siirrä historiamerkkiä", + "cmd.timeline_rollback": "Siirrä aikajanan merkkiä", + "cmd.timeline_stop": "Pysäytä historia", + "cmd.timeline_suppress": "Ohita piirre", + "cmd.view.render_browser": "Renderöintiselain", + "cmd.view.render_dock": "Siirrä renderöintitelakkaa", + "cmd.view.render_focus": "Renderöinnin kohdistusnäkymä", + "cmd.view.status_items": "Näkymäikkunan tilakohteet", + "cmd.view_ambient_occlusion": "Ympäristön peittovarjostus", + "cmd.view_angle_readout": "Näkymän kulmat", + "cmd.view_apply": "Palauta nimetty näkymä", + "cmd.view_back": "Takanäkymä", + "cmd.view_bottom": "Alanäkymä", + "cmd.view_delete": "Poista nimetty näkymä", + "cmd.view_fit": "Sovita", + "cmd.view_front": "Etunäkymä", + "cmd.view_graphics_preset": "Grafiikan esiasetus", + "cmd.view_grid": "Ruudukko", + "cmd.view_ground_shadow": "Maavarjo", + "cmd.view_home": "Aloitusnäkymä", + "cmd.view_isometric": "Isometrinen näkymä", + "cmd.view_left": "Vasen näkymä", + "cmd.view_list": "Luettele nimetyt näkymät", + "cmd.view_navigate": "Navigoi näkymää", + "cmd.view_navigation_bar": "Navigointipalkki", + "cmd.view_next_tab": "Seuraava välilehti", + "cmd.view_normal_to": "Kohtisuoraan valintaan", + "cmd.view_previous_tab": "Edellinen välilehti", + "cmd.view_rename": "Nimeä nimetty näkymä uudelleen", + "cmd.view_render_frame": "Renderöintikehyksen apuviivat", + "cmd.view_right": "Oikea näkymä", + "cmd.view_save": "Uusi nimetty näkymä", + "cmd.view_shots_strip": "Kuvakulmanauha", + "cmd.view_spin": "Jatkuva kierto", + "cmd.view_tool": "Navigointityökalu", + "cmd.view_top": "Ylänäkymä", + "cmd.view_visual_style": "Visuaalinen tyyli", + "color.copy": "Kopioi väriarvot napsauttamalla", + "color.edit": "Muokkaa väriä napsauttamalla", + "color.gamma": "Väriarvot näytetään gamma-avaruudessa 0-255", + "color.hex": "Heksa", + "color.hex_help": "Syötä #rrggbb tai #rrggbbaa; kuusi numeroa säilyttää peittävyyden", + "color.hex_hint": "#rrggbb", + "color.hue": "Sävy", + "color.linear": "Väriarvot näytetään lineaarisessa avaruudessa 0-1", + "color.saturation_value": "Kylläisyys ja kirkkaus", + "color.selected": "Valittu väri", + "config.column_filter_empty": "Ei vastaavia sarakkeita", + "contact.components_count": "{count} komponenttia", + "contact.enabled_label": "käytössä", + "coupling.gear_1": "Hammaspyörä 1", + "coupling.gear_1_pick": "Hammaspyörä 1 (valinnainen)", + "coupling.gear_2": "Hammaspyörä 2", + "coupling.gear_2_pick": "Hammaspyörä 2 (valinnainen)", + "coupling.internal": "Sisähammaspyörä", + "coupling.needs_turn_and_slide": "tarvitsee yhden kiertyvän ja yhden liukuvan nivelen", + "coupling.needs_turns": "tarvitsee kaksi kiertyvää niveltä", + "coupling.not_round": "ei ole pyöreä pinta", + "coupling.nut": "Mutteri", + "coupling.picked": "valittu", + "coupling.pinion": "Pinioni", + "coupling.pinion_pick": "Pinioni (valinnainen)", + "coupling.pitch": "Nousu", + "coupling.rack": "Hammastanko", + "coupling.radius_1": "Säde 1", + "coupling.radius_2": "Säde 2", + "crash.announce": "SolidCraft sulkeutui viime kerralla odottamatta tai kohtasi sisäisen virheen. Kaatumisraportti tallennettiin (Ohje > Kaatumisraportit…).", + "crash.copy_folder": "Kopioi kansion polku", + "crash.copy_path": "Kopioi polku", + "crash.deleted": "Poistettiin {count} raporttia.", + "crash.detected_time": "Havaittu {time} UTC", + "crash.intro": "Kaatumisraportit pysyvät tällä tietokoneella, eikä niitä lähetetä minnekään. Raportoi… avaa luonnoksen, jonka tarkistat ennen kuin mitään jaetaan.", + "crash.kind_command": "Sisäinen virhe komennossa", + "crash.kind_internal": "Sisäinen virhe", + "crash.kind_kernel": "Ytimen virhe (palautettu)", + "crash.kind_unclean": "Sulkeutui odottamatta", + "crash.previous_session": "Aiempi SolidCraft-istunto päättyi odottamatta tai kohtasi sisäisen virheen. Hallitsemattomat lopetukset havaitaan käynnistyksessä. Kohdasta Ohje > Kaatumisraportit… näet lisätietoja.", + "crash.replayable": "toistettavissa", + "crash.report": "Raportoi…", + "crash.unclean_explanation": "Havaittu myöhemmässä käynnistyksessä; tarkkaa lopetusaikaa ei tallennettu. Myös järjestelmän sammutus tai pakotettu pysäytys voi aiheuttaa hallitsemattoman lopetuksen.", + "delete.and_more": "… ja {count} muuta", + "diagnostic.empty_boolean_component": "komponentissa '{component}' ei ole kappaletta, josta leikata tai jonka kanssa muodostaa leikkaus; työkalu saattaa olla päällekkäin kappaleen '{body}' kanssa komponentissa '{other}' – aktivoi kyseinen komponentti tai valitse kappale kohteeksi", + "dialog.bodies_count": "{count} kappaletta", + "dialog.clearance_invalid": "välyksen on oltava pituus, joka on vähintään 0", + "dialog.compute": "Laske", + "dialog.compute_again": "Laske uudelleen", + "dialog.computing": "Lasketaan… {seconds} s", + "dialog.could_not_be_checked": "ei voitu tarkistaa", + "dialog.custom_axis": "↖ Mukautettu akseli", + "dialog.dimension_insert_hint": "Lisää toisen ohjaavan mitan nimi napsauttamalla sitä", + "dialog.dimension_name": "Mitta: {name}", + "dialog.edit_title": "MUOKKAA {title}", + "dialog.no_shown_body": "Ei näkyvää kappaletta muutettavaksi: tuo jokin näkyviin tai valitse Uusi kappale", + "dialog.select": "↖ Valitse", + "dialog.selected_count": "↖ {count} valittu", + "dialog.selection_guidance": "Valitse syöte muuttaaksesi sitä. Poista valittuja kohteita napsauttamalla niitä; myös Ctrl/Cmd-napsautus vaihtaa valintaa. Tarkista esikatselu ja paina sitten OK.", + "dialog.selection_step": "{step}/{total}: Valitse {input}", + "dialog.step": "Vaihe", + "document.changed_on_disk": "{name} muuttui levyllä", + "document.changed_on_disk_detail": "Toinen ohjelma tai tietokone on muuttanut tiedostoa {name} sen jälkeen, kun avasit tai viimeksi tallensit sen. Korvaa vaihtaa ne muutokset omiisi; Tallenna kopio säilyttää molemmat.", + "document.copy_name": "{name} kopio", + "document.open_anyway": "Avaa silti", + "document.open_elsewhere": "{name} on jo auki", + "document.open_elsewhere_detail": "{name} on auki SolidCraftissa {app} käyttäjällä {who}, avattu {when}. Jos tallennatte molemmat, toisen työ menetetään. Avaa se vain luku -tilassa, niin voit katsoa sitä tallentamatta sen päälle.", + "document.open_read_only": "Avaa vain luku -tilassa", + "document.opened_read_only": "Avattu vain luku -tilassa: tallennus kysyy uutta tiedostoa", + "document.overwrite": "Korvaa", + "document.read_only_save": "Tämä malli avattiin vain luku -tilassa: tallenna se uutena tiedostona", + "document.save_changes": "Tallennetaanko muutokset tiedostoon {name}?", + "document.save_copy": "Tallenna kopio…", + "document.unsaved_changes": "Tiedostossa {name} on tallentamattomia muutoksia. Jos et tallenna, ne menetetään.", + "drive.rigid": "{joint} on jäykkä nivel: se pitää osansa paikallaan, joten sillä ei ole mitään ohjattavaa. Jos haluat niiden liikkuvan, vaihda sen tyyppi kohdassa Muokkaa niveltä: Kiertyvä kiertoon, Liukuva liukumiseen, Sylinterimäinen molempiin.", + "drive.stopped_by_contact": "Pysähtyi arvoon {value}: {a} kulkisi kohteen {b} läpi", + "drive.stopped_by_loop": "Pysähtyi arvoon {value}: nivelen {joint} kautta kulkeva silmukka ei voi sulkeutua enempää", + "drive.unconnected": "Ei liikuta mitään: {part} ei ole yhteydessä mihinkään maadoitettuun", + "dxf.cancel_wait": "Odotetaan viennin pysähtymistä…", + "dxf.cancelled": "DXF-vienti peruttu", + "dxf.cancelling": "Perutaan DXF-vientiä", + "dxf.exporting": "Viedään DXF", + "dxf.invalid_tolerance": "Käyrätoleranssin on oltava välillä 0.0001–1 mm.", + "dxf.progress.index": "Valmistellaan pintoja (2/5)", + "dxf.progress.meshes": "Valmistellaan verkkoja (1/5)", + "dxf.progress.occlusion": "Selvitetään piiloviivoja (4/5)", + "dxf.progress.projection": "Projisoidaan geometriaa (3/5)", + "dxf.progress.write": "Kirjoitetaan DXF (5/5)", + "dxf.tolerance": "Käyrätoleranssi", + "dxf.tolerance_help": "Vain näkyvät kappaleet ja näytetyt luonnokset. Käyrät muodostetaan suorista osista. Pienempi toleranssi antaa tarkemmat käyrät ja vie enemmän aikaa ja muistia.", + "each rail's curves must be in one sketch": "kunkin ohjauskäyrän käyrien on oltava samassa luonnoksessa", + "feature computation ended without a result": "piirteen laskenta päättyi ilman tulosta", + "file.open.drawing_filter": "Mallit, CAD-tiedostot, verkot ja piirustukset", + "file_load.built": "Rakennettu tähän mennessä: {built}/{total} piirrettä.", + "file_load.converting": "Muunnetaan kappaletta {done}/{total}", + "file_load.inserting": "Lisätään geometriaa", + "file_load.link_item": "{name} ({done}/{total})", + "file_load.opening": "Avataan mallia", + "file_load.preparing_thumbnail": "Valmistellaan pikkukuvaa...", + "file_load.preparing_view": "Valmistellaan näkymää...", + "file_load.preview_note": "Tallennettu esikatselu. Geometriaa tarkistetaan ennen muokkausta.", + "file_load.reading": "Luetaan tiedostoa...", + "file_load.reading_percent": "Luetaan tiedostoa... {percent} %", + "file_load.rebuilding": "Rakennetaan uudelleen piirrettä {done}/{total}", + "file_load.recovering": "Palautetaan mallia", + "file_load.stopping": "Odotetaan edellisen toiminnon pysähtymistä...", + "file_load.updating_links": "Päivitetään linkkejä", + "file_load.waiting": "Odotetaan tiedostotoimintoa", + "fits the face, e.g. M8": "sopii pintaan, esim. M8", + "from the profile": "profiilista", + "from the rule": "säännöstä", + "help.apache": "Apache-lisenssi 2.0", + "help.appearance.assign": "Antaa valituille kappaleille, pinnoille tai komponenteille värin tai materiaalin ulkoasun muuttamatta niiden painoa. Käytä sitä osien erottamiseen toisistaan tai pintakäsittelyn esikatseluun.", + "help.attributions": "Tekijätiedot (ATTRIBUTION.md)", + "help.build": "Versio {version} · commit {commit} · koottu {date}", + "help.component.finish_edit": "Tallentaa paikallaan muokattavan osan, palaa sen kokoonpanoon ja päivittää kokoonpanon sen mukaan. Käytä sitä, kun linkitetyn osan muutokset ovat valmiit.", + "help.connect_note": "Käynnistä kukin avustaja uudelleen, jotta SolidCraft-palvelin latautuu. Jokaisesta tiedostosta otettiin varmuuskopio .bak ennen muutosta.", + "help.connect_title": "Yhdistä tekoälyavustajat", + "help.face.delete": "Poistaa valitut pinnat ja antaa viereisten pintojen sulkea aukon tai jättää aukon auki pintana. Käytä sitä poistamaan tiellä oleva pyöristetty särmä, reikä tai napa.", + "help.font_details": "Käyttöliittymä käyttää eguin sisäänrakennettuja fontteja (Ubuntu Light ja Hack, Ubuntu Font Licence- ja MIT/Bitstream Vera -lisenssein; Noto Emoji ja emoji-kuvakefontti, OFL- ja MIT-lisenssein). Luonnosteksti käyttää Liberation Sans -fonttia (SIL OFL 1.1). Crafting Appsin valinnaista fonttipakettia craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1) ei sisällytetä SolidCraft-koontiversioihin.", + "help.fonts": "Fontit", + "help.licences": "Lisenssit", + "help.material.assign": "Määrittää, mistä valitut kappaleet on tehty, kuten teräs, alumiini tai ABS. Käytä sitä, jotta massa ja paino vastaavat todellista osaa.", + "help.mit": "MIT-lisenssi", + "help.notice": "NOTICE", + "help.occurrence.move": "Siirtää kokoonpanon osaa vain sen nivelten sallimia vapausasteita pitkin. Valitse osan pinta ja vedä sitten käytettävissä olevaa nuolta tai kaarta.", + "help.parameters.change": "Avaa taulukon nimetyistä arvoista ja lausekkeista, jotka ohjaavat mallin mittoja. Käytä sitä muuttamaan kokoa yhdessä paikassa niin, että jokainen sitä käyttävä piirre seuraa.", + "help.pointcloud.insert": "Lisää PLY-, XYZ- tai PTS-skannaus pistepilvenä mallin rinnalle. Käytä sitä apuna, kun rakennat mallia mitatusta datasta.", + "help.sketch.construction_line": "Luo kahden pisteen kautta kulkeva ääretön apuviiva. Käytä sitä luonnoksen asetteluun jakamatta profiileja.", + "help.sketch.construction_line.angle": "Luo ääretön apuviiva kulmaan luonnoksen X-akselista. Valitse piste ja kirjoita kulma tai valitse sen suunta.", + "help.sketch.construction_line.bisector": "Valitse kaksi leikkaavaa suoraa luonnosviivaa ja valitse sitten jompikumpi kulmanpuolittaja. Tulos seuraa lähdeviivojaan.", + "help.sketch.construction_line.horizontal": "Luo pisteen kautta kulkeva ääretön vaakasuora apuviiva. Sen vaakasuoruusrajoite seuraa myöhempiä muokkauksia.", + "help.sketch.construction_line.parallel": "Valitse suora luonnosviiva ja sijoita sitten sen kanssa yhdensuuntainen ääretön apuviiva. Valitse toinen referenssi napsauttamalla hiiren oikeaa painiketta.", + "help.sketch.construction_line.perpendicular": "Valitse suora luonnosviiva ja sijoita sitten sitä vastaan kohtisuora ääretön apuviiva. Valitse toinen referenssi napsauttamalla hiiren oikeaa painiketta.", + "help.sketch.construction_line.tangent_at": "Luo tangentti ympyrän tai ympyränkaaren pisteeseen tai avoimen splinin tai kartioleikkauskäyrän päätepisteeseen. Valitse käyrä ja sitten sen kosketuspiste.", + "help.sketch.construction_line.tangent_external": "Valitse ympyrä tai ympyränkaari, sitten ulkopuolinen piste ja tangenttiratkaisu. Esikatselut näyttävät vain piirretyllä kaarella olevat kosketuskohdat.", + "help.sketch.construction_line.tangent_two": "Valitse kaksi ympyrää tai ympyränkaarta ja valitse sitten yhteinen tangentti esikatselusta. Kosketuskohtien on oltava piirretyillä käyrillä.", + "help.sketch.construction_line.vertical": "Luo pisteen kautta kulkeva ääretön pystysuora apuviiva. Sen pystysuoruusrajoite seuraa myöhempiä muokkauksia.", + "help.sketch.equation_curve": "Piirtää käyrän kaavoista: x(t) ja y(t) tai y = f(x) annetulla välillä. Kaavoissa voi käyttää parametreja, ja käyrä seuraa niitä: käytä sitä siniaaltoon, spiraaliin tai hampaan evolventtiin.", + "help.sketch.inspect": "Avaa raportin avoimesta luonnoksesta: montako vapausastetta on jäljellä ja onko se täysin määritelty. Käytä sitä selvittämään, mikä vielä liikkuu, ennen kuin viimeistelet luonnoksen.", + "help.solid.align": "Siirtää valittuja kappaleita niin, että niiden piste, pinta tai taso kohtaa pisteen, pinnan tai tason muualla. Käytä sitä sijoittamaan osa toista vasten mittaamatta siirtymää.", + "help.solid.chamfer": "Leikkaa valittuihin särmiin asettamasi etäisyyden suoran viisteen. Käytä sitä terävien särmien katkaisuun tai helpottamaan tapin tai ruuvin sisäänmenoa.", + "help.solid.combine": "Yhdistää kappaleita, leikkaa ne pois kohdekappaleesta tai säilyttää vain niiden yhteisen tilavuuden, ja voi säilyttää työkalukappaleet. Käytä sitä osien yhdistämiseen, muodon leikkaamiseen toisella tai sen selvittämiseen, missä kaksi kappaletta ovat päällekkäin.", + "help.solid.draft": "Kallistaa valittuja pintoja asettamasi kulman verran neutraalitasosta mitattuna. Käytä sitä valetuissa tai muotissa tehdyissä osissa, jotta ne irtoavat muotista.", + "help.solid.extrude": "Työntää luonnosprofiilin 3D:ksi annetun matkan verran, lisäten tai poistaen materiaalia. Käytä sitä tasaisen ääriviivan muuttamiseen kappaleeksi, navaksi tai taskuksi.", + "help.solid.fillet": "Pyöristää valitut särmät tasaisella, asettamasi säteen ympyräpyöristyksellä. Käytä sitä pehmentämään teräviä särmiä lujuuden, mukavuuden tai ulkonäön vuoksi.", + "help.solid.hole": "Poraa asettamasi halkaisijan pyöreän reiän valittuun kohtaan pinnalla. Käytä sitä ruuvien välysrei'ille, tapeille ja muille yksinkertaisille pyöreille aukoille.", + "help.solid.loft": "Muodostaa tasaisen kappaleen kahden tai useamman luonnosprofiilin välille tai profiilista pisteeseen. Käytä sitä siirtymiin, suppiloihin, kahvoihin ja muihin muotoihin, joiden poikkileikkaus muuttuu pituuden mukaan.", + "help.solid.mirror": "Tekee valituista kappaleista tai piirteistä peilikopion tason suhteen ja voi yhdistää sen alkuperäiseen. Käytä sitä symmetrisiin osiin, jolloin mallinnat yhden puolikkaan ja saat molemmat.", + "help.solid.move": "Siirtää tai kiertää valittuja kappaleita tai niiden kopiota asettamasi etäisyyden ja kulman verran. Käytä sitä kappaleen uudelleensijoittamiseen tai toisen kappaleen tekemiseen toiseen paikkaan.", + "help.solid.offset_face": "Työntää valittuja pintoja sisään tai ulos asettamasi etäisyyden verran, ja ympäröivät pinnat seuraavat. Käytä sitä tekemään seinästä paksumpi, taskusta syvempi tai navasta korkeampi muokkaamatta luonnosta.", + "help.solid.pattern.circular": "Toistaa valittuja kohteita akselin ympäri asettamallasi määrällä ja kokonaiskulmalla. Käytä sitä pulttiympyröihin, puolaan, ripoihin ja hampaisiin.", + "help.solid.pattern.rectangular": "Toistaa valittuja kohteita yhteen tai kahteen suuntaan asettamallasi määrällä ja välillä. Käytä sitä reikien, ripojen, tappien tai jalkojen riveihin ja ruudukoihin.", + "help.solid.press_pull": "Lisää tai poistaa materiaalia, kun vedät pintaa, tai pyöristää särmiä, kun vedät niitä. Käytä sitä nopeisiin muutoksiin suoraan mallissa.", + "help.solid.remove": "Poistaa valitut kappaleet mallista tästä aikajanan kohdasta eteenpäin; aiemmat vaiheet säilyttävät ne. Käytä sitä apukappaleen, kuten tarpeettoman leikkaustyökalun, poistamiseen.", + "help.solid.replace_face": "Siirtää valitut tasopinnat tasolle tai yhdensuuntaiselle pinnalle, ja kappale kasvaa tai kutistuu sen mukaan. Käytä sitä tuomaan pinta samaan tasoon toisen osan tai aputason kanssa.", + "help.solid.revolve": "Pyöräyttää luonnosprofiilin akselin ympäri pyörähdyskappaleeksi. Käytä sitä akseleihin, nuppeihin, kulhoihin ja muihin keskiviivan suhteen pyöreisiin osiin.", + "help.solid.scale": "Suurentaa tai pienentää valittuja kappaleita kertoimella, joka on sama kaikkiin suuntiin tai oma kullekin akselille. Käytä sitä tuodun muodon koon muuttamiseen tai kutistumisen huomioimiseen.", + "help.solid.shell": "Koverraa kappaleen ontoksi jättäen asettamasi paksuiset seinämät ja voi avata valitsemasi pinnat. Käytä sitä laatikoihin, kansiin ja muihin ohutseinäisiin osiin.", + "help.solid.split_body": "Jakaa kappaleen erillisiksi kappaleiksi tasolla, toisen kappaleen pinnalla tai luonnosviivalla. Käytä sitä tekemään osia, jotka tulostetaan, koneistetaan tai väritetään erikseen.", + "help.solid.split_face": "Jakaa valitut pinnat tasoa, toisen kappaleen pintaa tai luonnoskäyriä pitkin leikkaamatta kappaletta. Käytä sitä antamaan pinnan osalle oma päästö, väri tai siirtymä.", + "help.solid.sweep": "Vetää luonnosprofiilia polkua pitkin kappaleeksi. Käytä sitä putkiin, kiskoihin, kahvoihin ja muihin vakiopoikkileikkauksisiin osiin, jotka seuraavat käyrää.", + "help.third_party": "Kolmannen osapuolen lisenssit", + "help.timeline.compute_all": "Rakentaa jokaisen aikajanan piirteen uudelleen alusta alkaen. Käytä sitä mallin päivittämiseen ja nähdäksesi, mitkä piirteet epäonnistuvat.", + "help.timeline.delete": "Poistaa valitut piirteet aikajanalta; luonnoksen poistaminen poistaa myös siitä rakennetut piirteet. Käytä sitä poistamaan vaihe, jota ei enää tarvita.", + "help.timeline.play": "Toista jäljellä olevat piirteet yksi kerrallaan puolen sekunnin tauolla kunkin uudelleenrakennuksen jälkeen. Pysäytä suorittamalla komento uudelleen tai painamalla Escape; Siirry loppuun hyppää heti loppuun.", + "history.sketch_under_constrained": "Alimääritelty ({count} vapausastetta)", + "history.sketch_under_constrained_one": "Alimääritelty ({count} vapausaste)", + "hole_presets.confirm_delete": "Vahvista poisto", + "hole_presets.delete": "Poista", + "hole_presets.delete_prompt": "Poistetaanko tämä henkilökohtainen esiasetus? Olemassa olevat reiät eivät muutu.", + "hole_presets.full": "Henkilökohtaisessa kirjastossa on jo 64 esiasetusta.", + "hole_presets.invalid_name": "Kirjoita lyhyt nimi ilman rivinvaihtoja tai ohjausmerkkejä.", + "hole_presets.invalid_parameters": "Täydennä reiän parametrit kelvollisilla, kohtuullisen pituisilla lausekkeilla.", + "hole_presets.missing": "Valittu esiasetus ei ole enää käytettävissä.", + "hole_presets.name": "Esiasetuksen nimi", + "hole_presets.name_exists": "Tämänniminen esiasetus on jo olemassa. Käytä eri nimeä.", + "hole_presets.name_hint": "Yksilöllinen nimi", + "hole_presets.overwrite": "Tallenna muutokset valittuun esiasetukseen", + "hole_presets.preset": "Esiasetus", + "hole_presets.recall": "Palauta", + "hole_presets.rename": "Nimeä uudelleen", + "hole_presets.save": "Tallenna uutena", + "hole_presets.scope": "Tallennettu profiiliisi kaikkia projekteja varten.", + "hole_presets.select": "Valitse esiasetus", + "hole_presets.title": "Henkilökohtaiset esiasetukset", + "hole_presets.unsupported_options": "Tämä esiasetus käyttää kierreasetuksia, joita tämä versio ei pysty palauttamaan.", + "hole_presets.unsupported_overwrite": "Tämä esiasetus sisältää asetuksia, joita ei voi korvata turvallisesti.", + "home.back": "Takaisin: {name}", + "home.crashes": "Kaatumisraportit", + "home.design_workspace": "Suunnittelu", + "home.documentation": "Dokumentaatio", + "home.export": "Vie", + "home.export_hint": "Valitse muoto nykyiselle mallille.", + "home.export_json_hint": "Muokattava malli ja komentohistoria", + "home.export_mesh_hint": "Verkko tulostukseen tai jakamiseen", + "home.export_step_hint": "Tarkka kappalegeometria", + "home.import": "Tuo…", + "home.import_hint": "STEP, IGES tai verkko uuteen malliin", + "home.in_this_browser": "tässä selaimessa", + "home.missing": "puuttuu", + "home.month_01": "tammi", + "home.month_02": "helmi", + "home.month_03": "maalis", + "home.month_04": "huhti", + "home.month_05": "touko", + "home.month_06": "kesä", + "home.month_07": "heinä", + "home.month_08": "elo", + "home.month_09": "syys", + "home.month_10": "loka", + "home.month_11": "marras", + "home.month_12": "joulu", + "home.new_inches": "Uusi malli, tuumat", + "home.new_inches_hint": "Tuumat · avautuu Suunnittelu-työtilaan", + "home.new_mm": "Uusi malli", + "home.new_mm_hint": "Millimetrit · avautuu Suunnittelu-työtilaan", + "home.open": "Avaa…", + "home.open_hint": ".sc-malli ({shortcut})", + "home.open_now": "Avaa nyt", + "home.opened_days_ago": "{count} päivää sitten", + "home.opened_hours_ago": "{count} h sitten", + "home.opened_just_now": "Juuri nyt", + "home.opened_minutes_ago": "{count} min sitten", + "home.opening": "avataan…", + "home.properties": "Mallin ominaisuudet", + "home.recent": "Viimeisimmät", + "home.recent_empty": "Avaamasi tai tallentamasi mallit näkyvät tässä.", + "home.recovery_count": "Palautettavia malleja: {count}", + "home.recovery_empty": "Ei palautettavia malleja.", + "home.recovery_hint": "SolidCraft sulkeutui ennen kuin nämä mallit tallennettiin.", + "home.report_issue": "Ilmoita ongelmasta", + "home.samples": "Esimerkit", + "home.settings": "Asetukset", + "home.short_date": "{day}. {month}", + "home.shortcuts": "Pikanäppäimet", + "home.start_hint": "Luo malli, avaa viimeaikainen tiedosto tai tutustu esimerkkiin.", + "home.whats_new": "Uutta", + "home.yesterday": "Eilen", + "install.button_tip": "Asenna SolidCraft sovellukseksi: se avautuu omaan ikkunaansa ja toimii ilman verkkoyhteyttä", + "install.dock_1": "Valitse Arkisto › Lisää Dockiin.", + "install.dock_2": "Napsauta Lisää.", + "install.dock_after": "Sen jälkeen SolidCraft avautuu Dockista omaan ikkunaansa ja toimii ilman verkkoyhteyttä.", + "install.done": "Valmis", + "install.home_screen_1": "Napauta Jaa (… -valikossa, jos se ei ole työkalurivillä).", + "install.home_screen_2": "Valitse Lisää Koti-valikkoon.", + "install.home_screen_3": "Napauta Lisää.", + "install.home_screen_after": "Sen jälkeen SolidCraft avautuu kuvakkeestaan Koti-valikossa ilman Safarin työkalurivejä ja toimii ilman verkkoyhteyttä.", + "install.menu": "Asenna sovellus…", + "install.steps_intro": "Safari asentaa verkkosovellukset omista valikoistaan:", + "install.title": "Asenna SolidCraft", + "issue.body_label": "Raportin teksti", + "issue.note_changed_while_waiting": "Asetukset tai malli muuttuivat esikatselua odotettaessa. Ota kuvakaappaus uudelleen, jotta tekniset tiedot päivittyvät nykyistä näkymää vastaaviksi.", + "issue.note_details_kept": "Kuvakaappaus otettu paikallisesti. Muokkaamasi tekniset tiedot säilytettiin: tarkista, että ne vastaavat yhä nykyistä näkymää.", + "issue.note_details_updated": "Tekniset tiedot päivitettiin vastaamaan nykyistä näkymää. Kuvakaappaus otettu paikallisesti. Tarkista se ennen kuin liität sen GitHubissa.", + "issue.note_image_copied": "Liitä kuva GitHub-luonnokseen tai tallenna PNG, jos kuvan kopiointi ei ole käytettävissä.", + "issue.note_opened": "Tarkista GitHub-luonnos ja liitä kuvakaappaus. GitHubin Submit new issue -painike julkaisee sen.", + "issue.note_opened_copied": "Raportti kopioitu. Liitä se GitHub-luonnokseen, liitä kuvakaappaus ja napsauta sitten GitHubissa Submit new issue.", + "issue.note_removed": "Kuvakaappaus poistettiin tästä luonnoksesta.", + "issue.note_report_copied": "Raportti kopioitu. Liitä se tarvittaessa GitHub-luonnokseen.", + "issue.note_save_failed": "Kuvakaappausta ei voitu tallentaa: {error}", + "issue.note_saved": "Kuvakaappaus tallennettu. Liitä PNG GitHub-luonnokseen.", + "issue.save_screenshot": "Tallenna kuvakaappaus…", + "joint.from_bodies_hint": "Jokainen valittu kappale siirtyy omaan uuteen komponenttiinsa ja pysyy paikallaan.", + "joint.one_body": "Molemmat valinnat ovat kappaleessa {body}. Valitse toinen kohta toisesta osasta.", + "joint.one_component": "Nämä osat ovat saman komponentin kappaleita: {bodies}. Nivel liikuttaa komponenttia toista vasten, joten jokainen osa tarvitsee oman komponentin.", + "joint.rigid_group_one_component": "Nämä {count} kappaletta ovat kaikki samassa komponentissa (tai itse mallissa): käytä ensin komentoa {command}.", + "joint.rigid_group_select_components": "Valitse kaksi tai useampia komponentteja.", + "joint_move.blocked_hint": "Tarkista nivelen tyyppi (kuten Jäykkä), maadoitus, nivelen rajat ja parametriohjatut arvot.", + "joint_move.blocked_title": "Tätä osaa ei voi siirtää", + "joint_move.coarse": "Kiertoaskel akselin lähellä (°)", + "joint_move.distance": "Etäisyys alusta", + "joint_move.done": "Valmis", + "joint_move.fine": "Kiertoaskel kaukana akselista (°)", + "joint_move.fixed": "Tällä osalla ei ole liikkuvaa nivelakselia.", + "joint_move.help": "Siirrä – vedä nuolta tai rengasta. Esc peruu nykyisen vedon.", + "joint_move.legacy_hint": "Poista käytöstä, jos haluat käyttää edellistä Siirrä-paneelia.", + "joint_move.precision": "Vedä katkoviivaohjaimen ulkopuolelle tarkkaa kiertoa varten.", + "joint_move.rotation": "Kierto alusta", + "joint_move.select": "Valitse pinta tai yksi kokoonpanon osa ja valitse sitten Siirrä.", + "joint_move.settings": "Kokoonpanon siirto", + "joint_move.step": "Askel", + "joint_move.use_handles": "Käytä nivelliikkeen kahvoja kokoonpanon siirrossa", + "keymap.command_id": "Komennon tunnus", + "keymap.empty": "Ei vastaavia komentoja", + "keymap.use_anyway": "Käytä {key} tässä silti", + "label.move_to_left_side": "Siirrä vasemmalle puolelle", + "label.move_to_right_side": "Siirrä oikealle puolelle", + "manage.appearance_hint": "Valitse valinnalle ulkoasu tai vedä värimalli kappaleen tai pinnan päälle.", + "manage.assign_hint": "Valitse kappaleet ja valitse niille muovisuunnittelusääntö.", + "manage.config_hint": "Muokkaa konfiguraation rivejä, sarakkeita ja sääntöjä ja aktivoi tai esikatsele sitten riviä.", + "manage.empty": "Ei vastaavia rivejä.", + "manage.material_hint": "Valitse kappaleet ja valitse niiden fyysinen materiaali.", + "manage.parameters_hint": "Muokkaa lausekkeita ja yksiköitä. Muutokset tulevat voimaan Enterillä tai kentästä poistuttaessa.", + "manage.rules_hint": "Valitse muokattava sääntö tai luo uusi sääntö. Tallenna sääntö vahvistamalla.", + "material.editor.add_property": "Lisää ominaisuus", + "material.editor.add_source": "Lisää lähde", + "material.editor.assigned_density": "Määritetty tiheys", + "material.editor.axes": "Materiaaliakselit", + "material.editor.axes_numeric": "1 / 2 / 3", + "material.editor.axes_wood": "L / R / T", + "material.editor.copy_name": "Kopio: {name}", + "material.editor.density_range": "Määritetyn tiheyden on oltava yli 0 ja enintään 1000 g/cm³.", + "material.editor.designation": "Merkintä", + "material.editor.duplicate": "Monista", + "material.editor.engineering_card": "Teknisten ominaisuuksien kortti", + "material.editor.family": "Materiaaliryhmä", + "material.editor.glass": "Lasi", + "material.editor.illustrative": "Havainnollistava", + "material.editor.invalid_property": "Ominaisuustyyppiä ei tueta.", + "material.editor.isotropic": "Isotrooppinen", + "material.editor.measurement": "Mittaus", + "material.editor.metal": "Metalli", + "material.editor.moisture": "Kosteus, kuiva-aineesta", + "material.editor.name_required": "Kirjoita nimi, jossa on 1–128 merkkiä.", + "material.editor.no_draft": "Materiaaliluonnosta ei ole auki.", + "material.editor.number_required": "Kirjoita äärellinen numeroarvo.", + "material.editor.orthotropic": "Ortotrooppinen", + "material.editor.other": "Muu", + "material.editor.polymer": "Polymeeri", + "material.editor.preserved_appearance": "Säilytetty ulkoasu", + "material.editor.public_reference": "Julkinen lähde", + "material.editor.reference": "Viite", + "material.editor.save_or_discard": "Tallenna tai hylkää materiaaliluonnos ennen materiaalin määrittämistä.", + "material.editor.saved": "Materiaali tallennettu. Kappaleiden määritykset eivät muuttuneet.", + "material.editor.scope": "Tallennus tallentaa tämän materiaalin määrittämättä sitä kappaleille. Tyhjät ominaisuudet ja olosuhteet jäävät tuntemattomiksi. Kortin tiheys ei muuta määritettyä tiheyttä tai massaa.", + "material.editor.source_id": "Lähteen tunnus", + "material.editor.source_kind": "Lähteen tyyppi", + "material.editor.source_title": "Lähteen nimi", + "material.editor.sources": "Lähteet", + "material.editor.stale": "Tämä materiaali muuttui luonnoksen ollessa auki. Hylkää luonnos ja avaa materiaali uudelleen ennen tallennusta.", + "material.editor.state": "Materiaalin tila", + "material.editor.strain_rate": "Venymänopeus", + "material.editor.symmetry": "Elastinen symmetria", + "material.editor.temperature": "Lämpötila", + "material.editor.unknown_card": "Tekniset ominaisuudet ovat tuntemattomia. Tallennus voi säilyttää vain määritetyn tiheyden ja nykyisen ulkoasun.", + "material.editor.user_supplied": "Käyttäjän antama", + "material.editor.wood": "Puu", + "material.selection.choose": "Valitse materiaali", + "material.selection.mixed": "Eri materiaaleja", + "measure.at": "Kohdassa", + "measure.item": "Kohde {number}", + "measure.quick_copied": "Mittaus kopioitu", + "measure.quick_copy": "Kopioi mittaus napsauttamalla", + "measure.quick_edges": "{count} särmää", + "measure.quick_faces": "{count} pintaa", + "messages.ago_h": "{n} h sitten", + "messages.ago_min": "{n} min sitten", + "messages.ago_s": "{n} s sitten", + "messages.chip_hint": "Näytä kaikki tämän istunnon viestit napsauttamalla", + "messages.clear": "Tyhjennä", + "messages.copy_all": "Kopioi kaikki", + "messages.menu": "Viestit…", + "messages.none": "Ei vielä viestejä.", + "messages.title": "Viestit", + "motion.checked_to": "Tarkistettu vain vaiheeseen {step} asti: tarkistuksen laskentabudjetti loppui", + "motion.collision": "{a} · {b}: vaiheet {steps}", + "motion.delete_key": "Poista avainkehys", + "motion.duration_hint": "sekuntia (tyhjä: vaihekohtainen)", + "motion.key_here": "Avainkehys tähän", + "motion.key_here_hint": "Lisää tähän vaiheeseen avainkehys nivelen nykyisellä arvolla", + "motion.no_collisions": "Ei törmäyksiä tutkimuksen aikana", + "motion.plot_quantity": "Suure", + "motion.step_back": "Askel taaksepäin", + "motion.step_forward": "Askel eteenpäin", + "motion.to_end": "Loppuun", + "motion.to_start": "Alkuun", + "motion.track_name": "Raita {number}", + "nav.alias.help": "Shift+Alt+vasen veto kiertää, Shift+Alt+keski panoroi, Shift+Alt+oikea zoomaa; keskiveto myös panoroi ja oikea veto kiertää", + "nav.blender.help": "Keskiveto kiertää, Shift+keski panoroi, Ctrl+keski zoomaa; oikea veto ei liikuta kameraa", + "nav.free_orbit.help": "Hiiri ja 3D-hiiri kiertävät molempien napojen yli ja säilyttävät kallistuksen. Shift-akselitartunta on poissa käytöstä.", + "nav.free_orbit.label": "Vapaa kierto", + "nav.free_orbit.snap_help": "Hiiri ja 3D-hiiri kiertävät molempien napojen yli ja säilyttävät kallistuksen. Pidä Shift painettuna kiertovedon aikana, niin katselusuunta ja kallistus tarttuvat.", + "nav.free_orbit_upright.help": "Sivuttaiset hiirivedot pyörittävät mallia maailman pystyakselin ympäri; ylös- ja alasvedot kallistavat yläkautta ilman rajaa.", + "nav.free_orbit_upright.label": "Kierrä pystyakselin ympäri", + "nav.fusion.help": "Keskiveto panoroi, Shift+keski kiertää, oikea veto kiertää", + "nav.hfss.help": "Alt+vasen veto panoroi, Shift+Alt+vasen zoomaa, Ctrl+vasen veto tyhjässä kohdassa kiertää", + "nav.inventor.help": "Keskiveto panoroi, Shift+keski kiertää, Ctrl+keski zoomaa, oikea veto kiertää", + "nav.maya.help": "Alt+vasen veto kiertää, Alt+keski panoroi, Alt+oikea zoomaa; keskiveto myös panoroi", + "nav.openscad.help": "Vasen veto tyhjässä kohdassa kiertää, Shift+vasen veto valitsee laatikolla, luonnosgeometrian vetäminen muokkaa; oikea tai keskiveto panoroi, Shift+oikea tai Shift+keskiveto zoomaa", + "nav.perspective.sketch": "Luonnoksen muokkaus käyttää ortografista näkymää. Viimeistele luonnos vaihtaaksesi perspektiiviin.", + "nav.right_drag_orbits.help": "Pois: oikea veto ei liikuta kameraa, ja oikea painike vain avaa pikavalikon. SolidWorks-hiirikartoituksen valinta poistaa tämän käytöstä.", + "nav.right_drag_orbits.label": "Oikea veto kiertää", + "nav.solidworks.help": "Keskiveto kiertää, Ctrl+keski panoroi, Shift+keski zoomaa, oikea veto kiertää", + "nav.tinkercad.help": "Oikea veto kiertää, keski- tai Shift+oikea veto panoroi", + "nav.touchpad.help": "Panoroi pitämällä Shift painettuna ja liikuttamalla osoitinta; kierrä pitämällä Alt/Option painettuna ja liikuttamalla sitä. Hiiren painiketta ei tarvita. Pystyvieritys zoomaa.", + "nav.touchpad.label": "Kosketuslevy", + "nav.touchpad.orbit": "Kierto (pidä Alt/Option painettuna ja liikuta; ei hiiren painiketta)", + "nav.touchpad.pan": "Panorointi (pidä Shift painettuna ja liikuta; ei hiiren painiketta)", + "nav.touchpad.scroll": "Kosketuslevy zoomaa pystyvierityksellä. Kahden sormen panorointiasetuksesi säilyy muita esiasetuksia varten.", + "nav.touchpad.zoom": "Zoomaus (pystyvieritys tai nipistys)", + "navbar.agent_chat": "Avustajan keskustelupaneeli", + "navbar.agent_cursor": "Näytä agentin kohdistin", + "navbar.ambient_occlusion": "Ympäristön peittovarjostus", + "navbar.assistant": "Avustaja", + "navbar.custom.add_slot": "Lisää {slot}", + "navbar.custom.always": "Aina näkyvissä", + "navbar.custom.available": "{available} · vedä palkkiin tai paina Lisää", + "navbar.custom.buttons": "Painikkeet", + "navbar.custom.compact": "Tiivis", + "navbar.custom.count": "{count}/16 paikkaa", + "navbar.custom.customise": "Mukauta navigointipalkkia…", + "navbar.custom.design": "Suunnittelu", + "navbar.custom.duplicate": "Tämä paikka on jo palkissa.", + "navbar.custom.edge": "Reuna", + "navbar.custom.edge_bottom": "Ala", + "navbar.custom.edge_top": "Ylä", + "navbar.custom.fade": "Häivytä", + "navbar.custom.full": "Poista paikka lisätäksesi toisen.", + "navbar.custom.hidden_design": "Piilotettu Suunnittelussa", + "navbar.custom.hidden_render": "Piilotettu Renderöinnissä", + "navbar.custom.hide": "Piilota navigointipalkki", + "navbar.custom.hide_idle": "Piilota, kunnes osoitin viedään päälle", + "navbar.custom.icon_only": "Vain kuvake", + "navbar.custom.icon_value": "Kuvake ja arvo", + "navbar.custom.icons": "Kuvakkeet", + "navbar.custom.idle": "Käyttämättömänä", + "navbar.custom.intro": "Valitse 3D-näkymän alareunan palkin säätimet ja niiden järjestys. Siirrä paikkaa vetämällä sitä tai poista se vetämällä se pois palkista.", + "navbar.custom.labels": "Kuvakkeet ja nimiöt", + "navbar.custom.left": "Siirrä vasemmalle", + "navbar.custom.position": "Sijainti", + "navbar.custom.position_centre": "Keskellä", + "navbar.custom.position_left": "Vasemmalla", + "navbar.custom.position_right": "Oikealla", + "navbar.custom.preview_as": "Esikatsele tilassa", + "navbar.custom.regular": "Normaali", + "navbar.custom.remove": "Poista", + "navbar.custom.remove_bar": "Poista palkista", + "navbar.custom.render": "Renderöinti", + "navbar.custom.reset": "Palauta navigointipalkki", + "navbar.custom.reset_default": "Palauta oletus", + "navbar.custom.right": "Siirrä oikealle", + "navbar.custom.select": "Paikkaa ei ole valittu. Valitse palkista paikka siirtääksesi tai poistaaksesi sen tai muuttaaksesi sen ulkoasua.", + "navbar.custom.separators_full": "Palkissa on jo neljä erotinta.", + "navbar.custom.show": "Näytä navigointipalkki", + "navbar.custom.shows": "Näyttää", + "navbar.custom.size": "Koko", + "navbar.custom.stale": "Palkki muuttui. Valitse paikka uudelleen.", + "navbar.custom.title": "Navigointipalkki", + "navbar.custom.unknown": "Tämä paikka ei ole käytettävissä.", + "navbar.description.ambient_occlusion": "Tummentaa uria ja nurkkia syvyysvaikutelman lisäämiseksi.", + "navbar.description.display": "Sisältää näkymäasetukset: grafiikan esiasetus, ruudukko, maavarjo, ympäristön peittovarjostus ja projektio.", + "navbar.description.fit": "Rajaa näkymään valinnan tai koko mallin, jos mitään ei ole valittu.", + "navbar.description.grid": "Näyttää tai piilottaa maaruudukon.", + "navbar.description.ground_shadow": "Näyttää tai piilottaa mallin alla olevan varjon.", + "navbar.description.home": "Palaa koko mallin isometriseen näkymään.", + "navbar.description.look_at": "Kääntää näkymän kohti valittua pintaa, tasoa tai avointa luonnosta.", + "navbar.description.orbit": "Kiertää näkymää mallin ympäri.", + "navbar.description.pan": "Liu'uttaa näkymää sivuttain, ylös tai alas.", + "navbar.description.projection": "Vaihtaa ortografisen ja perspektiivinäkymän välillä.", + "navbar.description.separator": "Ohut viiva, joka ryhmittelee vierekkäisiä paikkoja.", + "navbar.description.spin": "Pitää näkymän pyörimässä, kunnes napsautat tai painat näppäintä.", + "navbar.description.visual_style": "Vaihtaa mallin piirtotapaa: varjostettu, rautalanka tai piilosärmin.", + "navbar.description.zoom": "Siirtää näkymää lähemmäs mallia tai kauemmas siitä.", + "navbar.display": "Näyttö", + "navbar.fit": "Sovita", + "navbar.graphics": "Grafiikka", + "navbar.grid": "Ruudukko", + "navbar.ground_shadow": "Maavarjo", + "navbar.home": "Aloitus", + "navbar.later": "Myöhemmin", + "navbar.look_at": "Katso kohti", + "navbar.more": "Lisää", + "navbar.orbit": "Kierrä", + "navbar.orthographic": "Ortografinen", + "navbar.pan": "Panoroi", + "navbar.perspective": "Perspektiivi", + "navbar.preset": "Esiasetus", + "navbar.projection": "Projektio", + "navbar.projection_heading": "Projektio", + "navbar.separator": "Erotin", + "navbar.show": "Näytä", + "navbar.spin": "Pyöritä", + "navbar.style.shaded": "Varjostettu", + "navbar.style.shaded_with_edges": "Varjostettu särmineen", + "navbar.style.shaded_with_hidden_edges": "Varjostettu, piilosärmät näkyvissä", + "navbar.style.wireframe": "Rautalanka", + "navbar.translucent": "Läpikuultava", + "navbar.value_tip": "{name} · {value}", + "navbar.visual_style": "Visuaalinen tyyli", + "navbar.zoom": "Zoomaa", + "needs two joints": "tarvitsee kaksi niveltä", + "network.allow_once": "Salli kerran", + "network.always_allow": "Salli tämä palvelin aina", + "network.prompt_detail": "Tämä malli linkittää tiedostoon verkkosijainnissa {host}. Sen avaaminen muodostaa yhteyden kyseiseen tietokoneeseen ja voi lähettää sille Windows-kirjautumistietosi. Salli vain luotettavat palvelimet.", + "network.prompt_title": "Verkkosijainti", + "new configuration": "uusi konfiguraatio", + "new parameter": "uusi parametri", + "no hole": "ei reikää", + "no interference": "ei päällekkäisyyttä", + "no joint that moves yet": "ei vielä liikkuvaa niveltä", + "no motion study yet": "ei vielä liiketutkimusta", + "no picture": "ei kuvaa", + "no such joint": "niveltä ei ole", + "none": "ei mitään", + "not a move": "ei siirto", + "not a number": "ei luku", + "open a sketch first": "avaa ensin luonnos", + "parts.automatic_name": "automaattinen", + "parts.dimension.across_flats": "Avainväli", + "parts.dimension.bore": "Reiän halkaisija", + "parts.dimension.d": "Nimellishalkaisija", + "parts.dimension.head_diameter": "Kannan halkaisija", + "parts.dimension.head_height": "Kannan korkeus", + "parts.dimension.height": "Korkeus", + "parts.dimension.inner": "Sisähalkaisija", + "parts.dimension.outer": "Ulkohalkaisija", + "parts.dimension.pitch": "Nousu", + "parts.dimension.socket": "Kolon koko", + "parts.dimension.socket_depth": "Kolon syvyys", + "parts.dimension.thickness": "Paksuus", + "parts.dimension.width": "Leveys", + "parts.family.bearing": "Urakuulalaakeri (ulkomitat)", + "parts.family.button_head_cap_screw": "Kupukantainen kuusiokoloruuvi", + "parts.family.dowel_pin": "Lieriötappi (ohjaintappi)", + "parts.family.hex_bolt": "Kuusiokantapultti / -ruuvi", + "parts.family.hex_nut": "Kuusiomutteri", + "parts.family.set_screw": "Kuusiokolostoppiruuvi, tasapää", + "parts.family.socket_head_cap_screw": "Kuusiokoloruuvi", + "parts.family.washer": "Tavallinen aluslevy", + "parts.holes": "Reiät (valinnainen)", + "parts.placement_hint": "valitse yksi tai useampi reikä, johon kuhunkin asetetaan osa, tai OK sijoittaa sen origoon", + "pattern.alignment_2": "Kohdistus 2", + "pattern.alignment_hint": "Määriin sisältyy alkuperäinen. Keskitä tasapainottaa kopiot; Käännä valitsee ylimääräisen puolen parillisilla määrillä.", + "pattern.direction_1": "Suunta 1", + "pattern.direction_2": "Suunta 2", + "pattern.flip_direction": "Käännä suunta", + "perf.click_for_details": "Napsauta nähdäksesi tiedot: ruutuaikakaavio, histogrammi ja mitä GPU piirsi", + "perf.draw_calls": "Piirtokutsut", + "perf.line_segments": "Viivasegmentit", + "perf.low_1": "1 % alin", + "perf.renderer": "Renderöijä", + "perf.scene_build": "Näkymän rakennus", + "perf.triangles": "Kolmiot", + "perf.ui_time": "Käyttöliittymän aika", + "perf.viewport": "Näkymäikkuna", + "perf.worst": "huonoin", + "pick a body or some of its faces": "valitse kappale tai osa sen pinnoista", + "pick a hole to seat it, or OK places it at the origin": "valitse reikä, johon se asetetaan, tai OK sijoittaa sen origoon", + "pick a planar face": "valitse tasomainen pinta", + "pick a plane or a face as the tool": "valitse työkaluksi taso tai pinta", + "pick a size": "valitse koko", + "pick edges of a body": "valitse kappaleen särmiä", + "pick edges of one body": "valitse yhden kappaleen särmiä", + "pick edges of the holes to remove": "valitse poistettavien reikien särmät", + "pick faces of one body": "valitse yhden kappaleen pintoja", + "pick faces to offset": "valitse siirrettävät pinnat", + "pick lines of one sketch": "valitse yhden luonnoksen viivoja", + "pick one or two vertices, edges or faces": "valitse yksi tai kaksi kärkipistettä, särmää tai pintaa", + "pick one plane or face as the tool, or sketch curves": "valitse työkaluksi yksi taso tai pinta, tai luonnoskäyriä", + "pick sections in two or more sketches": "valitse profiileja kahdesta tai useammasta luonnoksesta", + "pick sketch curves or edges": "valitse luonnoskäyriä tai särmiä", + "pick the face to untrim": "valitse pinta, jonka katkaisu poistetaan", + "pick the path": "valitse polku", + "pick what to keep": "valitse säilytettävä osa", + "pick what to keep of the other surface": "valitse toisesta pinnasta säilytettävä osa", + "prefs.add_item": "Lisää kohde", + "prefs.alt_frees_manipulators": "Alt / Option vapauttaa myös manipulaattorin nuolet", + "prefs.anti_aliasing_amd_dx12": "Reunanpehmennys käyttää tasoa 1×, koska käynnistystarkistus ei piirtänyt mitään moninäytteistyksellä ja onnistui tasolla 1×. Voit valita toisen asetuksen yllä; käynnistä uudelleen ottaaksesi sen käyttöön, jos tarkistus onnistuu.", + "prefs.anti_aliasing_note": "Tasoittaa rosoiset reunat.", + "prefs.applies_on_restart": "Tulee voimaan uudelleenkäynnistyksessä", + "prefs.assistant": "Avustaja", + "prefs.auto_operation": "Valitse toiminto automaattisesti", + "prefs.auto_operation_note": "Piirreikkunat valitsevat Yhdistä, Uusi kappale tai Leikkaa sen mukaan, mihin uusi materiaali koskee, kunnes valitset jonkin. Pois: ne säilyttävät toiminnon, jolla ne avautuvat.", + "prefs.axes": "Akselit", + "prefs.axis": "Akseli", + "prefs.bodies_folders": "Kappalekansiot", + "prefs.bodies_folders_always": "Aina", + "prefs.bodies_folders_never": "Ei koskaan", + "prefs.bodies_folders_several": "Vain useita kappaleita", + "prefs.bottom": "Ala", + "prefs.bottom_centre": "Alas keskelle", + "prefs.bottom_right": "Alas oikealle", + "prefs.browser": "Selain", + "prefs.browser_eye_left": "Silmä taittonuolen vieressä", + "prefs.browser_eye_left_note": "Selaimen rivien näytä/piilota-silmä on taittonuolen vieressä kuten ennenkin, eikä sarakkeessa rivien oikeassa reunassa.", + "prefs.browser_reveal_on_hover": "Näytä osoitettaessa", + "prefs.browser_show_note": "Näytetty pitää selaimen näytöllä. Näytä osoitettaessa pitää sen piilossa, kunnes osoitin tulee sen paikalle tai sen vasemman reunan ohuen kielekkeen päälle, ja se pysyy auki, kun osoitin on sen sisällä tai sen valikko on auki.", + "prefs.browser_shown": "Näytetty", + "prefs.built_in": "Sisäänrakennettu", + "prefs.button_left": "Vasen veto", + "prefs.button_middle": "Keskiveto", + "prefs.button_right": "Oikea veto", + "prefs.choose_font": "Valitse fonttitiedosto…", + "prefs.click": "Napsautus", + "prefs.contact_shading": "Pehmeä kosketusvarjostus", + "prefs.contact_shading_note": "Pehmeä varjostus kohdissa, joissa osat ovat lähellä toisiaan.", + "prefs.context_menu": "Pikavalikko", + "prefs.context_menu_ring": "Pikavalikko · pidä painettuna rengasvalikkoa varten", + "prefs.cpu": "CPU (ohjelmisto)", + "prefs.crash_reports": "Avaa kaatumisraportit…", + "prefs.crash_reports_note": "Raportit säilytetään tällä tietokoneella yhdessä mallin ja ongelman toistavien komentojen kanssa.", + "prefs.ctrl_cmd": "Ctrl / Cmd", + "prefs.curved_surfaces": "Kaarevat pinnat", + "prefs.curves": "Kaarevat pinnat", + "prefs.dead_zone_note": "Viivoitettu kaista on kuollut alue: sen sisäinen liike ohitetaan.", + "prefs.default": "oletus", + "prefs.design": "Mallin oletukset", + "prefs.design_note": "Millä uudet mallit alkavat. Avoimet mallit säilyttävät omansa.", + "prefs.devices": "3D-hiiri", + "prefs.dialog_buttons": "Valintaikkunan painikkeet", + "prefs.dialogs": "Valintaikkunat", + "prefs.dialogs_edge": "Näkymän reunassa", + "prefs.dialogs_left_column": "Vasemmassa sarakkeessa", + "prefs.dialogs_note": "Mihin komentojen valintaikkunat avautuvat: telakoituna näkymän reunaan tai vasempaan sarakkeeseen selaimen ja historian tilalle, jotka palaavat ennalleen, kun valintaikkuna suljetaan.", + "prefs.display": "Näyttö", + "prefs.edges": "Särmät ja varjostus", + "prefs.extend": "Jatka", + "prefs.extra_navigation": "Ctrl+vasen veto tyhjässä kohdassa kiertää; pidä välilyöntiä painettuna panoroidaksesi.", + "prefs.follows_os": "Seuraa käyttöjärjestelmää", + "prefs.font": "Fontti", + "prefs.font_fallback": "Merkit, joita valitussa fontissa ei ole, näytetään sisäänrakennetulla fontilla, joten mikään nimiö ei näytä tyhjää ruutua.", + "prefs.font_sample": "Vikkelä ruskea kettu · Ø12.50 mm · 45.0° · 0123456789", + "prefs.font_unreadable": "Valittua fonttia ei voitu lukea.", + "prefs.general": "Yleiset", + "prefs.general_note": "Kieli, tallennus ja päivitykset.", + "prefs.gesture_orbit": "Kierrä", + "prefs.gesture_pan": "Panoroi", + "prefs.gesture_zoom": "Zoomaa", + "prefs.graphics": "Grafiikka", + "prefs.graphics_card": "Näytönohjain", + "prefs.graphics_card_auto": "Automaattinen", + "prefs.graphics_card_missing": "Tallennettu näytönohjain ei ole käytettävissä; käytetään automaattista.", + "prefs.graphics_card_restart": "Tulee voimaan, kun SolidCraft käynnistetään uudelleen. WGPU_ADAPTER_NAME ohittaa tämän valinnan.", + "prefs.graphics_note": "Vaihda nopeutta sulavuuteen. Kunkin valinnan vaikutus näkyy näytteessä.", + "prefs.graphics_presets_note": "Esiasetukset asettavat alla olevat valinnat yhdessä.", + "prefs.hide_constraint_glyphs_zoomed_out": "Piilota rajoitesymbolit loitonnettaessa", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Rajoitesymbolit poistuvat näkymästä, kun luonnos on loitonnettu niin kauas, että ne sotkisivat sen. Pois: ne pysyvät kiinteän kokoisina näytöllä kaikilla zoomaustasoilla.", + "prefs.history": "Historia", + "prefs.history_origin_bodies": "Näytä origo ja kappaleet ylimpänä", + "prefs.history_origin_bodies_note": "Vasemmalla tai selaimen alla oleva historia alkaa aktiivisen komponentin Kappaleet-kansiolla ja origolla, joiden silmät ja valikot ovat kuten selaimessa. Alareunan historia ei muutu.", + "prefs.history_play_button": "Toista historia -painike historian ohjaimissa", + "prefs.history_play_button_note": "Lisää Toista historia -painikkeen Siirry askel taaksepäin- ja Siirry askel eteenpäin -painikkeiden väliin historian ohjaimissa. Voit myös näyttää tai piilottaa sen napsauttamalla ohjaimia hiiren oikealla painikkeella.", + "prefs.history_sketches": "Luonnokset", + "prefs.history_sketches_in_order": "Järjestyksessä", + "prefs.history_sketches_note": "Kun Luonnokset-asetuksena on Piirteensä alla, vasemman reunan historia näyttää kunkin luonnoksen tason sisempänä ensimmäisen siitä tehdyn piirteen alla aina, kun se on tarpeeksi leveä nimille. Alareunan aikajana säilyttää aina luontijärjestyksen.", + "prefs.history_sketches_under_feature": "Piirteensä alla", + "prefs.hold_stop_snapping": "Pidä painettuna tartunnan estämiseksi", + "prefs.icons_only": "Vain kuvakkeet", + "prefs.imported_file": "Tuotu tiedosto", + "prefs.in_browser": "Selaimessa", + "prefs.input": "Syöttö", + "prefs.interface": "Käyttöliittymä", + "prefs.interface_language": "Käyttöliittymän kieli", + "prefs.interface_note": "Miltä SolidCraft näyttää ja missä sen osat sijaitsevat.", + "prefs.interval_minutes": "{n} min", + "prefs.labels": "Nimiöt", + "prefs.layout": "Asettelu", + "prefs.layout_note": "Tiivis telakoi paneelit ikkunan reunoihin. Selaimen läpikuultavuus on käytettävissä Kelluva-asettelussa. Vaihda avustajan puolta Avustaja-sivulla.", + "prefs.left": "Vasen", + "prefs.left_click": "Vasen napsautus", + "prefs.line_drag_draws_one": "Painaminen ja vetäminen piirtää yhden viivan", + "prefs.line_drag_draws_one_note": "Viiva-työkalussa painaminen, vetäminen ja vapauttaminen piirtää yhden viivan painalluskohdasta vapautuskohtaan, ja se päättyy siihen. Napsautukset piirtävät edelleen ketjun. Pois: veto sijoittaa pisteen vapautuskohtaan kuten napsautus.", + "prefs.linked_designs": "Linkitetyt mallit", + "prefs.live_input": "Reaaliaikainen syöttö", + "prefs.live_preview": "Reaaliaikainen esikatselu", + "prefs.logo": "Logo", + "prefs.logo_accent": "Korostusväri", + "prefs.logo_theme": "Teeman värit", + "prefs.max_file_size": "Suurin avattava tiedosto", + "prefs.max_file_size_design": "Mallitiedostot", + "prefs.max_file_size_flag": "Tämä ajokerta käynnistettiin valitsimella --max-file-size {size}, joka on voimassa, kunnes SolidCraft suljetaan. Nämä asetukset ovat voimassa, kun se käynnistetään ilman sitä.", + "prefs.max_file_size_note": "Oletukset: 512 MB ja 256 MB; enintään 16 GB. Tiedoston avaaminen vie muistia useita kertoja sen koon verran. Malli, joka säilyttää suuren tuonnin, voi tarvita suuremman mallitiedostorajan tallentuakseen ja avautuakseen uudelleen.", + "prefs.max_file_size_step": "STEP- ja tuontitiedostot", + "prefs.max_file_size_web": "Verkkosovellus avaa enintään 512 MB:n STEP- ja tuontitiedostot ja enintään 256 MB:n mallit: selaimen välilehti ei pysty käsittelemään suurempia tiedostoja. Työpöytäsovellus voi nostaa näitä rajoja.", + "prefs.megabytes": "MB", + "prefs.menu_grid": "Suuret kuvakkeet", + "prefs.menu_list": "Luettelo", + "prefs.menus": "Valikot", + "prefs.minutes": "minuuttia", + "prefs.minutes_suffix": " min", + "prefs.mouse": "Hiiri ja kosketuslevy", + "prefs.mouse_heading": "Hiiri", + "prefs.mouse_mapping": "Hiiren toiminnot", + "prefs.navigation": "Navigointi", + "prefs.navigation_note": "Miten hiiri, kosketuslevy ja 3D-hiiri liikuttavat näkymää.", + "prefs.network_host_remove": "Poista", + "prefs.network_locations": "Salli verkkosijainnit malleissa", + "prefs.network_locations_note": "Pois: mallin linkitetyt tiedostot toisella tietokoneella (\\\\server\\share) avataan vain tässä luetelluilta palvelimilta tai sen jälkeen, kun sallit palvelimen kysyttäessä.", + "prefs.network_locations_section": "Verkkosijainnit", + "prefs.not_on_gpu": "ei tällä GPU:lla", + "prefs.on": "Päällä", + "prefs.opaque": "Läpinäkymätön", + "prefs.orbit_snap": "Pidä Shift painettuna kierrettäessä tarttuaksesi akseliin.", + "prefs.orientation": "Suunta", + "prefs.origin_plane_names": "Origotasojen nimet", + "prefs.origin_plane_names_note": "Selaimessa, valintaikkunoissa ja luetteloissa näkyvät nimet. {top} on XY, {front} on XZ ja {right} on YZ, Z ylöspäin. Komennot, skriptit ja tallennetut mallit säilyttävät nimet XY, XZ ja YZ.", + "prefs.overall_speed": "Kokonaisnopeus", + "prefs.persistent_ribbon_pressed": "Korosta aktiiviset valintanauhan komennot", + "prefs.persistent_ribbon_pressed_help": "Korosta valintanauhan komennot, kun niiden vaikutukset ovat päällä. Poista käytöstä säilyttääksesi aiemman neutraalin ulkoasun ja komentojen ohjeen.", + "prefs.perspective_fov": "Näkökenttä", + "prefs.placement": "Sijoitus", + "prefs.prefer_free_sketch_points": "Suosi siirrettäviä luonnospisteitä, kun pisteet ovat päällekkäin", + "prefs.preview_choices": "Valintojesi esikatselu", + "prefs.print_face_highlight": "Tulostuspinnan korostus", + "prefs.print_face_highlight_tip": "Kuinka voimakkaasti kappaleen tulostuspinta sävytetään ja ääriviivataan näkymässä. 0 % ei näytä korostusta.", + "prefs.profile_active": "Aktiivinen profiili", + "prefs.profile_applied": "Profiili otettu käyttöön.", + "prefs.profile_changed": "Asetuksia on muutettu profiilin tallentamisen jälkeen. Tallenna säilyttää ne siinä.", + "prefs.profile_deleted": "Profiili poistettu.", + "prefs.profile_export": "Vie…", + "prefs.profile_exported": "Profiili viety.", + "prefs.profile_imported": "Profiili tuotu. Vaihda siihen valitsemalla se kohdassa Aktiivinen profiili.", + "prefs.profile_name_hint": "Profiilin nimi, esim. Kannettava", + "prefs.profile_rename": "Nimeä uudelleen", + "prefs.profile_renamed": "Profiili nimetty uudelleen.", + "prefs.profile_save": "Tallenna", + "prefs.profile_saved": "Nykyiset asetukset tallennettu profiiliin.", + "prefs.profile_skipped": "Profiili otettu käyttöön; {n} asetus(ta) säilytti nykyisen arvonsa (katso loki).", + "prefs.profiles": "Asetusprofiilit", + "prefs.profiles_note": "Pikanäppäimet, työkalurivi, navigointi, rengasvalikko ja käyttöliittymän asetukset yhdessä nimen alla, vaihdettavissa kerralla.", + "prefs.project_options_dialog": "Projisoinnin asetukset -valintaikkuna", + "prefs.project_options_dialog_note": "Päällä: valitse Geometria tai Kappaleet ja projisointilinkki ennen projisointia. Pois: säilytä aiempi suoravalintatyönkulku.", + "prefs.quality_default": "oletus", + "prefs.quality_fastest": "nopein", + "prefs.quality_slowest": "hitain", + "prefs.quality_smoother": "sulavampi", + "prefs.quick_measure": "Pikamittaus näkymän kulmassa", + "prefs.quick_measure_note": "Valinnan koko näkymän oikeassa alakulmassa: särmän pituus tai pyöreän särmän Ø ja R, pinnan ala, pisteen sijainti, kahden kohteen etäisyys ja kulma, useiden särmien tai pintojen yhteismäärä. Napsautus kopioi sen.", + "prefs.render_previous_geometry_budget": "Käytä aiempaa renderöinnin esikatselun geometriabudjettia", + "prefs.render_previous_geometry_budget_help": "Palauta aiempi kiinteä geometriaraja (512 MiB 64-bittisellä työpöydällä, muualla 128 MiB) laitekohtaisen budjetin sijaan.", + "prefs.reports_saved": "{n} tallennettu", + "prefs.ribbon_reveal": "Näytä hakutulokset valintanauhassa", + "prefs.ribbon_reveal_note": "Kun osoitat tulosta Hae komentoja -haussa, näytetään, missä komento on valintanauhassa: sen välilehti, painike tai rivi paneelin pudotusvalikossa. Haun kautta käynnistetty komento vilkkuu siellä, ja pudotusvalikosta käynnistetty käynnissä oleva komento merkitsee paneelinsa.", + "prefs.right_click": "Oikea napsautus", + "prefs.saving": "Automaattinen tallennus ja palautus", + "prefs.scale_note": "Myös Ctrl + / Ctrl − ikkunassa. Painikkeet ovat 28 px tasolla 100 %.", + "prefs.scale_text": "Skaalaus ja teksti", + "prefs.search": "Hae asetuksista", + "prefs.search_empty": "Ei vastaavia asetuksia", + "prefs.select": "Valitse", + "prefs.select_one_item": "Valitse yksi kohde", + "prefs.select_other_hidden": "Valitse piilotettu geometria Valitse muu -toiminnolla", + "prefs.select_other_hidden_help": "Päällä: mukaan piilotetut kappaleet, luonnokset ja peittyvät särmät osoittimen lähellä. Pois: käytä alkuperäistä luetteloa osoittimen alla näkyvästä geometriasta.", + "prefs.selecting": "Valitseminen", + "prefs.shift": "Shift", + "prefs.shift_add_ctrl_toggle": "Shift vain lisää; Ctrl / Cmd vaihtaa", + "prefs.shift_add_note": "Päällä: Shift lisää, Ctrl / Cmd vaihtaa valinnan. Pois (oletus): molemmat vaihtavat.", + "prefs.shortcuts": "Pikanäppäimet", + "prefs.single_surface_analysis": "Käytä yhtä pinta-analyysiä kerrallaan", + "prefs.single_surface_analysis_help": "Kun asetus on pois, pintavarjostus ja jatkuvuus voivat olla päällä yhtä aikaa. Kun tämä on päällä, säilytetään viimeksi käynnistetty tai muutettu analyysi.", + "prefs.sketch_align_points": "Kohdista muihin luonnospisteisiin piirrettäessä", + "prefs.sketch_align_points_note": "Piirrettäessä piste kohdistuu samanaikaisesti vaakasuoraan yhden luonnospisteen ja pystysuoraan toisen kanssa pisteviivaohjaimella, ja napsautus säilyttää molemmat kohdistukset. Pois: vain edellisen pisteen kanssa, yksi akseli kerrallaan.", + "prefs.sketch_conflict_colour": "Ristiriitainen geometria ristiriitavärillä", + "prefs.sketch_conflict_colour_note": "Kun luonnoksen rajoitteet ovat ristiriidassa, myös epäonnistuneen rajoitteen pitämät käyrät ja pisteet piirretään ristiriitavärillä, eikä vain sen symbolia tai mittaa. Pois: ne säilyttävät tavalliset värinsä.", + "prefs.sketch_construction_lines": "Laajennetut apuviivatyökalut", + "prefs.sketch_exit_view": "Kun luonnos päättyy", + "prefs.sketch_exit_view.keep": "Säilytä nykyinen näkymä", + "prefs.sketch_exit_view.previous": "Palaa edelliseen näkymään", + "prefs.sketch_exit_view.unless_rotated": "Palaa, ellei kierretty", + "prefs.sketch_exit_view_note": "Mihin näkymä siirtyy Lopeta luonnos- tai Peruuta-toiminnon tai kaksinkertaisen Esc-painalluksen jälkeen.", + "prefs.sketch_open_look_at": "Käänny luonnosta kohti, kun se avautuu", + "prefs.sketch_open_look_at_note": "Pois: luonnoksen luominen tai muokkaaminen jättää näkymän ennalleen. Katso kohti kääntää näkymän luonnosta kohti, kun haluat.", + "prefs.sketch_recent_snap": "Automaattinen tartunta viimeisimpiin keskipisteisiin ja keskikohtiin", + "prefs.sketch_recent_snap_note": "Piirrettäessä kohdistin tarttuu kohtaan, jossa kahden viimeisimmän ympyrän keskipisteen tai suoran särmän keskikohdan ohjaimet risteävät. Pois: ohjaimet näkyvät vain visuaalisesti eikä kohdistin liiku.", + "prefs.sketch_selection": "Luonnos ja valinta", + "prefs.sketch_selection_heading": "Luonnos ja valinta", + "prefs.sketch_selection_note": "Miten luonnokset tarttuvat ja miten napsautukset valitsevat.", + "prefs.sketch_state_icons": "Luonnosten kuvakkeet tilansa värillä", + "prefs.sketch_state_icons_note": "Historiassa ja selaimessa luonnoksen kuvake saa tilansa värin (alimääritelty, täysin määritelty tai ristiriitainen) ja sen työkaluvihje kertoo tilan. Pois: kaikilla luonnoksilla on sama kuvake.", + "prefs.sketch_tab_always": "Pidä Luonnos-välilehti näkyvissä", + "prefs.sketch_tab_always_note": "Luonnos-välilehti pysyy valintanauhassa heti Malli-välilehden jälkeen, vaikka mikään luonnos ei ole auki. Sen piirtotyökalut aloittavat silloin luonnoksen valitulle tasolle tai pinnalle tai seuraavaksi valitsemallesi tasolle, työkalu valmiina.", + "prefs.sketch_tracking_guides": "Keskipisteiden ja keskikohtien kohdistusohjaimet", + "prefs.sketch_tracking_guides_note": "Osoita ympyrän keskipistettä tai suoran särmän keskikohtaa ja liiku sitten vaaka- tai pystysuunnassa näyttääksesi tilapäisen pisteviivaohjaimen.", + "prefs.sketching": "Luonnostelu", + "prefs.snap_drawing_note": "Piirrettäessä tai vedettäessä luonnospistettä.", + "prefs.source": "Lähde", + "prefs.speed": "Nopeus", + "prefs.stand_up_note": "Kun STEP- tai IGES-tiedosto avautuu Z ylöspäin, tarjoa neljänneskierrosta X-akselin ympäri.", + "prefs.stand_up_unknown": "Tuntemattomien ohjelmien tiedostoille", + "prefs.stand_up_unknown.ask": "Kysy valintaikkunassa", + "prefs.stand_up_unknown.note": "Näytä huomautus", + "prefs.stand_up_unknown.off": "Älä tarjoa", + "prefs.stand_up_unknown_note": "Miten tarjous tehdään, kun tiedoston otsake ei nimeä ohjelmaa, jonka tiedetään tallentavan Y ylöspäin. Huomautus näytetään vain, kun tiedosto näyttää olevan selällään; Kysy valintaikkunassa kysyy jokaisesta tällaisesta tiedostosta kuten ennenkin.", + "prefs.status_bar": "Tilarivi", + "prefs.status_bar_note": "Ohut palkki ikkunan alareunassa näyttää, mitä muokataan, avoimen luonnoksen tilan sen värillä ja mallin yksiköt; yksiköitä napsauttamalla ne vaihdetaan. Luonnoksen tila ei silloin enää näy näkymän kulmassa.", + "prefs.status_done": "Valmis", + "prefs.status_error": "Virhe", + "prefs.status_selected": "Valittu", + "prefs.status_warning": "Varoitus", + "prefs.structure.scale_percent": "{percent} %", + "prefs.supersampling_brief": "Piirtää näkymän suurempana ja suodattaa sen pienemmäksi: erittäin terävä ja raskaampi.", + "prefs.tab_accent_note": "Korostusväri seuraa aktiivista välilehteä", + "prefs.theme_file": "teematiedosto", + "prefs.theme_file_or_paste": "tiedosto tai liitä", + "prefs.theme_follow": "Seuraa teematiedostoa", + "prefs.theme_follow_error": "Ei otettu käyttöön: {error}. Viimeisin toimiva teema pysyy käytössä.", + "prefs.theme_follow_launch": "Seurataan vain tämän ajokerran ajan (--theme-file); ladataan uudelleen aina, kun jokin toinen työkalu kirjoittaa sen uudelleen.", + "prefs.theme_follow_note": "Ladataan uudelleen aina, kun jokin toinen työkalu kirjoittaa sen uudelleen. Teeman valitseminen lopettaa sen seuraamisen.", + "prefs.theme_follow_off": "Pois", + "prefs.theme_follow_stop": "Lopeta seuraaminen", + "prefs.theme_import_hint": "Napsauta valitaksesi teematiedoston, pudota se tähän tai paina Ctrl+V (Macissa Cmd+V), kun teema on kopioituna", + "prefs.theme_paste": "Liitä teema", + "prefs.theme_paste_none": "Leikepöydällä ei ole SolidCraft-teemaa", + "prefs.timeline_half_hour": "−30 min", + "prefs.timeline_now": "nyt", + "prefs.timeline_quarter_hour": "−15", + "prefs.toast_place": "Ilmoitukset", + "prefs.toggle_item": "Lisää kohde tai poista se uudelleen", + "prefs.toolbar": "Työkalurivi", + "prefs.toolbar_tabs": "Työkalurivin välilehdet", + "prefs.top": "Ylä", + "prefs.trackpad_zoom_modifier": "Zoomaa kahden sormen vierityksellä pitäen painettuna", + "prefs.trackpad_zoom_modifier.alt": "⌥ / Alt", + "prefs.trackpad_zoom_modifier.cmd": "⌘", + "prefs.trackpad_zoom_modifier.ctrl": "Ctrl", + "prefs.trackpad_zoom_modifier.help": "Pidä vain tätä näppäintä painettuna zoomataksesi osoittimen kohdalla pystyvierityksellä. Pois säilyttää nykyisen vierityskäyttäytymisen.", + "prefs.trackpad_zoom_modifier.off": "Pois", + "prefs.translucent": "Läpikuultava", + "prefs.under_browser": "Selaimen alla", + "prefs.under_cursor": "Kohdistimen alla", + "prefs.units_precision": "Yksiköt ja tarkkuus", + "prefs.updates": "Päivitykset", + "prefs.view": "Näkymän toiminta", + "prefs.view_confirm_corner": "OK ja Peruuta näkymän kulmassa", + "prefs.view_confirm_corner_note": "Kun valintaikkuna tai luonnos on auki, näkymän oikeassa yläkulmassa oleva valintamerkki ja risti tekevät saman kuin valintaikkunan OK ja Peruuta, tai lopettavat ja peruuttavat luonnoksen. Näkymän navigaattori siirtyy niiden alapuolelle.", + "prefs.viewport": "Näkymäikkuna", + "prefs.viewport_analysis_status": "Näytä näkymäikkunan analyysien tila", + "prefs.viewport_analysis_status_help": "Näytä aktiiviset analyysit näkymäikkunan yläpuolella, avaa niiden selitteet kustakin kohteesta ja sammuta uusin analyysi Esc-näppäimellä. Poista käytöstä palauttaaksesi kulmaselitteet ja aiemman Esc-toiminnan.", + "prefs.viewport_background": "Tausta", + "prefs.viewport_background_colour": "Väri", + "prefs.viewport_background_theme": "Teeman liukuväri", + "prefs.viewport_section_status": "Näytä näkymäikkunan leikkauksen tila", + "prefs.viewport_section_status_help": "Näytä leikkausasetus näkymäikkunassa. Esc ja aktiivinen valintanauhan painike sammuttavat sen. Poista käytöstä säilyttääksesi aiemmat leikkauksen ohjaimet.", + "prefs.wheel": "Rulla", + "prefs.wheel_trackpad": "Rulla ja kosketuslevy", + "prefs.workspace": "Työtila", + "prefs.zoom_stop_at_model": "Pysäytä zoomaus malliin", + "prefs.zoom_stop_at_model_tip": "3D-hiiri ja laitesovellus zoomaavat kohti näkymän keskellä olevaa pintaa; vetozoomaus pitää kohdan, josta veto alkoi. Pois: zoomaus voi kulkea mallin läpi. Rulla ja nipistys käyttävät erikseen asetusta Zoomaa kohdistinta kohti", + "prefs.zoom_toward_cursor": "Zoomaa kohdistinta kohti", + "properties.title": "Ominaisuudet: {name}", + "recovery.days_ago": "{count} päivää sitten", + "recovery.detail": "{file} · {features} piirrettä · tallennettu automaattisesti {when}", + "recovery.discard_all": "Hylkää kaikki", + "recovery.discard_all_detail": "Tätä ei voi kumota.", + "recovery.discard_all_title": "Hylätäänkö {count} automaattista tallennusta?", + "recovery.discard_all_title_one": "Hylätäänkö 1 automaattinen tallennus?", + "recovery.hours_ago": "{count} h sitten", + "recovery.just_now": "juuri nyt", + "recovery.min_ago": "{count} min sitten", + "recovery.never_saved": "ei koskaan tallennettu", + "render.adaptive_absolute": "RGB-virheen absoluuttinen alaraja", + "render.adaptive_coverage": "Peittovirheen tavoite", + "render.adaptive_enable": "Jaa näytteet itsenäisten pilottien avulla", + "render.adaptive_help": "Vain GPU. Itsenäiset pilottinäytteet hylätään, minkä jälkeen kullekin pikselille jaetaan vähintään 16 tuotantonäytettä enintään asetuksen Näytteitä pikseliä kohden verran. RGB- ja peittovarianssi ohjaavat jakoa; harvinaiset polut voivat jäädä huomaamatta ja rajoitetut pikselit voivat jäädä kohinaisiksi. Loppuraportti laskee todellisen työn. Kohinalle tai ajalle ei ole varmennettua takuuta.", + "render.adaptive_minimum": "Tuotantonäytteiden vähimmäismäärä", + "render.adaptive_pending": "GPU:n itsenäisiin pilotteihin perustuva mukautuva jako ja ehdolliset Fresnel-kerrostumat ovat käytettävissä. Varmennettu konvergenssi, harvinaisten tapahtumien takuut ja CPU:n mukautuva kuljetus eivät ole käytettävissä.", + "render.adaptive_pilots": "Pilottinäytteitä pikseliä kohden", + "render.adaptive_relative": "RGB-virheen suhteellinen tavoite", + "render.add_ground": "Lisää sovitettu maapinta asetelmaan", + "render.advanced_material_scope": "Yksi rajallinen homogeeninen GPU-väliaine on käytettävissä tarkoin rajoin. Tiheysruudukot, sisäkkäiset lasi- ja tilavuusyhdistelmät, pinnanalaiset pinnat, siirtymäkartoitus, spektrinen kuljetus ja sitomattomat edistyneet materiaalikäsitteet eivät ole käytettävissä.", + "render.aging_add": "Lisää vanhenemiskerros", + "render.aging_airborne": "Ilmassa oleva pöly / osallistuva väliaine", + "render.aging_airborne_help": "Ilmassa oleva pöly on erillinen rajallinen homogeeninen sirottava tilavuus. Se muuttaa kuljetusta ja raakaa EXR:ää, ei pinnan vanhenemiskerroksia. Nykyiset tilavuus-, lasi- ja kohinanpoistorajoitukset pysyvät näkyvinä; ilmakehää ei lisätä automaattisesti.", + "render.aging_all_bodies": "Kaikki kelpoiset läpinäkymättömät kappaleet", + "render.aging_chips": "Lohkeillut maali", + "render.aging_class_any": "Kaikki läpinäkymättömät materiaaliluokat", + "render.aging_class_dielectric": "Vain ei-metalliset pinnat", + "render.aging_class_metal": "Vain metalliset pinnat", + "render.aging_color": "Kerroksen väri · sRGB", + "render.aging_coverage": "Peitto", + "render.aging_dust": "Kerrostunut pöly", + "render.aging_empty": "Ei vanhenemiskerroksia: alkuperäiset pinnat pysyvät ennallaan.", + "render.aging_fading": "Haalistunut pinnoite", + "render.aging_grime": "Lika ja tahrat", + "render.aging_help": "Yhdistä enintään kahdeksan optista kerrosta järjestyksessä. Ruoste ja patina ovat laadittuja ulkoasuja, eivät ikääntymis- tai korroosiosimulaatioita. Mittakaava on maailman millimetreinä. Geometriaa, massaa tai teknisiä ominaisuuksia ei muuteta; lasi ja passiiviset näyttämöt jätetään pois.", + "render.aging_metallic": "Kerroksen metallisuusosuus", + "render.aging_origin": "Kentän origo · maailman mm", + "render.aging_patina": "Kuparinvihreä patina", + "render.aging_refresh_targets": "Tarkastele nykyisiä kappaleita", + "render.aging_roughness": "Kerroksen karheus", + "render.aging_rust": "Hapettunut rauta / ruoste", + "render.aging_scale": "Kuvion mittakaava", + "render.aging_scratches": "Hienot naarmut", + "render.aging_target": "Kohde ja koordinaatit", + "render.aging_target_help": "Nimetyn kohteen on edelleen vastattava tallennettua indeksiään ja nimeään. Yleiset maskit on ankkuroitu maailmaan; ne eivät seuraa liikkuvia osia. Tämä ei ole onkaloiden tunnistusta eikä todellista särmien kulumista. Suodata luetteloa päästäksesi muihin kappaleisiin.", + "render.aging_target_search": "Suodata kappaleiden nimiä", + "render.aging_upward": "Ylöspäin suuntautuva kerrostuminen", + "render.all_controls_help": "Kaikkien nykyisten ohjaimien tiivis tarkastelu. Osiosivuilla voi muokata kohdennetusti muuttamatta taustalla olevaa pyyntöä.", + "render.all_shots_label": "Kaikki kuvakulmat", + "render.appearance_editor.absorption": "Absorptio", + "render.appearance_editor.base_colour": "Perusväri", + "render.appearance_editor.body_reason": "Optiset sidonnat kohdistuvat yhteen kokonaiseen kappaleeseen. Muokkaa näitä ohjaimia valitsemalla Kappale.", + "render.appearance_editor.boundary": "Raja", + "render.appearance_editor.box": "Laatikko", + "render.appearance_editor.choose_image": "Valitse kuva…", + "render.appearance_editor.closed": "Suljettu kiinteä kappale", + "render.appearance_editor.coat": "Kirkaslakka", + "render.appearance_editor.cpu_reason": "Vaatii CPU-säteenjäljityksen.", + "render.appearance_editor.glass": "Lasi ja absorptio", + "render.appearance_editor.glass_enable": "Käytä fysikaalista lasia tässä kappaleessa", + "render.appearance_editor.glass_note": "Suljettu lasi käyttää geometrista etäisyyttä. Se ei voi jakaa kappaletta kirkaslakan tai karttojen kanssa.", + "render.appearance_editor.gpu_reason": "Vaatii GPU-polunjäljityksen.", + "render.appearance_editor.ior": "IOR", + "render.appearance_editor.maps": "Kartat", + "render.appearance_editor.normal": "Normaali", + "render.appearance_editor.normal_strength": "Normaalin voimakkuus", + "render.appearance_editor.origin": "Origo", + "render.appearance_editor.recipe": "Resepti", + "render.appearance_editor.reflection_sampling": "Näytteistys kaikille heijastaville kappaleille", + "render.appearance_editor.reflections": "Heijastukset", + "render.appearance_editor.remove": "Poista tallennettu", + "render.appearance_editor.remove_note": "Poista tallennettu optiikka tästä kuvakulmasta. Geometria ja määritetyt ulkoasut säilytetään.", + "render.appearance_editor.remove_title": "Poistetaanko tallennettu optiikka?", + "render.appearance_editor.replace": "Korvaa tämän kappaleen tallennettu optiikka", + "render.appearance_editor.revalidate": "Vahvista tämä kappale uudelleen", + "render.appearance_editor.save": "Tallenna tämä optiikka", + "render.appearance_editor.save_reason": "Tämän optiikan tallentaminen vaatii fysikaalisen lasin nykyisessä GPU-kappaleessa. Lakka ja paikalliset kuvakartat pysyvät tilapäisinä.", + "render.appearance_editor.saved": "Tallennettu tämän kuvakulman kanssa", + "render.appearance_editor.saved_state": "Tämä optiikka on tallennettu tämän kuvakulman kanssa.", + "render.appearance_editor.scatter_reason": "Sisäinen sironta vaatii suljetun kiinteän rajan.", + "render.appearance_editor.temporary": "Tämä optiikka on tilapäinen tällä välilehdellä. Tallenna se säilyttääksesi sen kuvakulman kanssa.", + "render.appearance_editor.thickness": "Paksuus", + "render.appearance_editor.thickness_reason": "Paksuus koskee ohuita levyjä; suljettu lasi käyttää geometrista etäisyyttä.", + "render.appearance_editor.thin": "Ohut levy", + "render.appearance_editor.u_repeat": "U-toisto", + "render.appearance_editor.v_repeat": "V-toisto", + "render.appearance_editor.v_up": "Tekstuurin V osoittaa ylöspäin", + "render.appearance_editor.weight": "Paino", + "render.appearance_physics_separate": "Visuaalinen ulkoasu ei määritä tiheyttä, lämpötietoja tai muita teknisiä ominaisuuksia.", + "render.appearances": "Ulkoasut", + "render.assign_help": "Napsauta käyttääksesi valintaan; vedä esikatsellaksesi ja pudota, tai napsauta ilman valintaa maalataksesi.", + "render.availability_native": "Alkuperäinen koostumus; tarkista ennen käyttöä", + "render.availability_projection": "Tuettu projektio; katso laajuus ja puutteet", + "render.availability_reference": "Viitetietoa; ei automaattinen määritys", + "render.backdrop_alpha_conflict": "Valitse tämä tausta tai läpinäkyvä PNG-tuloste; renderöijä ei ohita kumpaakaan asetusta huomaamatta.", + "render.backdrop_enable": "Käytä vain kameran liukuväritaustaa", + "render.backdrop_first": "Alku- / keskiväri", + "render.backdrop_help": "Tämä näyttötilan tausta ei valaise, luo varjoja, heijastu eikä kuvaa maastoa. Se jätetään pois raa'asta EXR:stä. Geometria, valot ja HDR-ympäristö pysyvät erillisinä.", + "render.backdrop_horizontal": "Vaakasuora liukuväri", + "render.backdrop_radial": "Säteittäinen liukuväri", + "render.backdrop_radius": "Säde", + "render.backdrop_second": "Loppu- / reunaväri", + "render.backdrop_vertical": "Pystysuora liukuväri", + "render.backdrop_x": "Keskipiste X", + "render.backdrop_y": "Keskipiste Y", + "render.background": "Kohtauksen tausta", + "render.background_camera_section": "Kameran tausta · PNG-esitys", + "render.background_completed_frozen": "Näytetty tulos on jäädytetty valmis kuva. Taustan muokkaaminen ei piirrä tulosta uudelleen automaattisesti. Käytä Uudelleensävytystä vain kameraa koskeviin muutoksiin tai Renderöintiä uutta fysikaalista näyttämöä varten.", + "render.background_hdr_separate": "Nykyiset HDR-resurssit valaisevat pintoja ja heijastuvat niistä; niitä ei näytetä automaattisesti panoraamana kohteen takana. Liukuvärin muuttaminen ei kierrä eikä värjää valaistusta.", + "render.background_lighting_section": "HDR-valaistus · erillään kameran taustasta", + "render.background_no_alpha_override": "Kameran taustaa ei lisätä läpinäkyvään tulosteeseen huomaamatta. Raakamasterin uudelleensävytys käyttää tallennettua peittoa eikä käytä kohinanpoistoa uudelleen; lähde-EXR pysyy ennallaan.", + "render.background_not_light": "Taustaväri on esitystä, ei lisävalonlähde.", + "render.background_regrade": "Käytä säilytettyyn raakamasteriin", + "render.background_stage_occlusion": "Tämä kuvakulma sisältää fysikaalisen näyttämön geometriaa. Suuri lattia tai seinä voi täyttää kuvan ja peittää vain kameran taustan. Tyhjennä tai muuta näyttämön kokoa tarkoituksella tai muuta sen fysikaalista heijastavuutta. Uudelleensävytys ei voi poistaa tallennettua geometriaa.", + "render.background_workflow": "Valitse haluamasi tausta: vain kameran väri tai liukuväri, valoa vastaanottava fysikaalinen näyttämö tai HDR-valaistus. Ne ovat toisistaan riippumattomia. Reaaliaikainen esikatselu on mallinnusnäkymä; renderöi uusi kuva tai sävytä säilytetty master uudelleen nähdäksesi kameran viimeistelyn.", + "render.base_appearance": "Muokattava kappaleen ulkoasu", + "render.base_apply": "Käytä kappaleen ulkoasua", + "render.base_apply_help": "Yksi kumottavissa oleva visuaalinen määritys tarkistettuun täsmälliseen kappaleeseen. Nykyiset pintakohtaiset ulkoasut ja tekniset materiaalit pysyvät erillisinä.", + "render.base_color": "Perusväri · sRGB", + "render.base_metallic": "Metallisuusosuus", + "render.base_opaque_only": "Tämä editori säilyttää läpinäkymättömän kappaleen merkityksen. Käytä optiseen läpäisyyn erillisiä lasin ohjaimia.", + "render.bloom_enable": "Näytön hehku", + "render.bloom_help": "Luova, vain tulosteeseen vaikuttava hehku positiivisista lineaarisista kohokohdista, levitetty kolmella normalisoidulla laatikkoajolla. Säde on tulosteen pikseleinä. Lisätään lineaariseen näyttövaloon ennen sRGB:tä; ei linssi- tai tilavuusefekti eikä konvergenssin parannus. Raaka EXR pysyy ennallaan.", + "render.bloom_opaque": "Hehku vaatii läpinäkymättömän tulosteen. Läpinäkyvä PNG hylätään, sitä ei litisteä huomaamatta.", + "render.bloom_radius": "Hehkun säde", + "render.bloom_strength": "Hehkun voimakkuus", + "render.bloom_threshold": "Lineaarisen kohokohdan kynnys", + "render.browse_capabilities": "Tarkastele koko ominaisuusluetteloa", + "render.browse_environments": "Selaa alkuperäisiä HDR-ympäristöjä", + "render.browse_looks": "Selaa…", + "render.browse_native_scenes": "Selaa valmiita studioita", + "render.browse_physical": "Tarkastele fysikaalisia viitteitä", + "render.browse_quality": "Tarkastele laatumäärityksiä", + "render.browse_rigs": "Selaa laadittuja valaistusasetelmia", + "render.browse_scene_specs": "Selaa edistyneitä kohtausmäärityksiä", + "render.browse_surfaces": "Selaa laadittuja pintoja", + "render.browser_library": "Kirjasto", + "render.browser_model": "Malli", + "render.camera_distance": "Silmän etäisyys kohteesta", + "render.camera_exact_help": "Maailman millimetrit; kulmat näytetään asteina ja tallennetaan radiaaneina. Navigointi käyttää samaa kameraa kuin näkymäikkuna.", + "render.camera_fov": "Pystysuora näkökenttä", + "render.camera_pitch": "Kameran nyökkäys", + "render.camera_roll": "Kallistus", + "render.camera_set": "Aseta renderöintikamera", + "render.camera_target": "Kohteen sijainti · mm", + "render.camera_yaw": "Kääntö", + "render.category_metal": "Metalli", + "render.category_paint": "Maali", + "render.category_plastic": "Muovi", + "render.category_wood": "Puu", + "render.check_opaque": "Läpinäkyvyys: vain läpinäkymättömät pinnat; taustan alfaa tuetaan.", + "render.check_sorted_alpha": "Läpinäkyvyys: lajiteltu alfa-approksimaatio.", + "render.check_transmission": "Läpinäkyvyys: fysikaalinen läpäisy.", + "render.children.absolute_floor": "Absoluuttinen alaraja", + "render.children.adaptive": "Mukautuva", + "render.children.add_look_reason": "Lisää sävy muokataksesi sen käyttötilaa ja voimakkuutta.", + "render.children.all_shots": "Kaikki kuvakulmat", + "render.children.bloom": "Hehku", + "render.children.check": "Tarkista", + "render.children.check_now": "Tarkista nyt", + "render.children.chromatic": "Kromaattinen", + "render.children.compact": "Tiivis", + "render.children.contrast": "Kontrasti", + "render.children.copy_image": "Kopioi", + "render.children.copy_job": "Kopioi työn JSON", + "render.children.copy_request": "Kopioi pyynnön JSON", + "render.children.coverage_error": "Peittovirhe", + "render.children.cpu": "CPU-säteenjäljitys", + "render.children.denoise": "Vähennä kohinaa valmiissa kuvassa", + "render.children.depth": "Polun syvyys", + "render.children.distortion": "Vääristymä", + "render.children.edge_samples": "Särmänäytteet", + "render.children.effects_banner": "Nämä efektit vaativat GPU-polunjäljityksen. Tämän avaaminen ei koskaan muuta menetelmää.", + "render.children.enable_adaptive": "Ota itsenäiset pilotit käyttöön muokataksesi mukautuvia rajoja.", + "render.children.enable_bloom": "Ota hehku käyttöön muokataksesi sen voimakkuutta, kynnystä ja sädettä.", + "render.children.finishing": "Viimeistely", + "render.children.flare": "Linssiheijastus", + "render.children.fresnel": "Fresnel-kerrostumat", + "render.children.ghosts": "Haamurenkaat", + "render.children.glass": "Lasikuljetus", + "render.children.go_to": "Siirry: {editor}", + "render.children.grain": "Rae", + "render.children.halo": "Kehä", + "render.children.hdr": "HDR", + "render.children.keep_master": "Säilytä raaka lineaarinen master", + "render.children.last_result": "Viimeisin: {number} · {width} × {height} · {phase}", + "render.children.lens_effects": "Linssiefektit", + "render.children.look_summary": "{tone} · {count} sävyä", + "render.children.looks": "Luovat sävyt", + "render.children.memory": "Muisti", + "render.children.method": "Menetelmä", + "render.children.minimum": "Vähintään", + "render.children.needs_cpu": "Vaatii CPU-säteenjäljityksen. Tämän avaaminen ei koskaan muuta menetelmää.", + "render.children.nested": "Varmennetut sisäkkäiset dielektrit", + "render.children.not_checked": "Ei tarkistettu", + "render.children.path": "Polunseuranta", + "render.children.pilots": "Pilottinäytteet", + "render.children.preview": "Esikatselun hyötykuorma", + "render.children.progressive_reason": "Valitse Progressiivinen muokataksesi sen näytemäärää ja siementä.", + "render.children.radius": "Säde", + "render.children.reflect_depth": "Heijastussyvyys", + "render.children.reflect_samples": "Heijastusnäytteet", + "render.children.regrade": "Sävytä uudelleen", + "render.children.relative_error": "Suhteellinen virhe", + "render.children.render": "Renderöi", + "render.children.render_shot": "Renderöi kuvakulma", + "render.children.renderer": "Renderöijä", + "render.children.renderers": "Renderöijät", + "render.children.request": "Tämä pyyntö", + "render.children.reset_finishing": "Palauta viimeistely", + "render.children.review_quality": "Tarkista laatumääritys…", + "render.children.rgb_gain": "RGB-vahvistus", + "render.children.samples": "Näytteet", + "render.children.sampling": "Näytteistys", + "render.children.saturation": "Kylläisyys", + "render.children.scene_summary": "{bodies} kappaletta · {triangles} kolmiota", + "render.children.seed": "Siemen", + "render.children.sharpening": "Terävöinti", + "render.children.single_image": "Yksittäinen kuva", + "render.children.soft_focus": "Pehmeä tarkennus", + "render.children.streak": "Juova", + "render.children.strength": "Voimakkuus", + "render.children.studio": "Studio", + "render.children.threshold": "Kynnys", + "render.children.tone": "Sävy", + "render.children.under_hood": "Konepellin alla", + "render.children.vignette": "Vinjetti", + "render.children.workstation": "Työasema", + "render.choose_look": "Valitse ensin ulkoasu Ulkoasuista", + "render.chromatic_offset": "Kromaattinen reunasiirtymä", + "render.clear_stage": "Poista tallennettu näyttämö", + "render.copy_request": "Kopioi JSON", + "render.cpu_aa_help": "Spatiaaliset näytteet: lisänäytteet parantavat reunoja ja pidentävät renderöintiaikaa.", + "render.cpu_area_add": "Lisää suorakulmainen CPU-valo", + "render.cpu_area_editor": "CPU:n suorakulmaiset valot", + "render.cpu_area_editor_help": "Täydet sivuvektorit millimetreinä; U ristitulo V osoittaa säteilevää puolta kohti. Tämä poikkeaa GPU:n puolisärmävektoreista.", + "render.cpu_area_full_u": "Täysi U-sivu · mm", + "render.cpu_area_full_v": "Täysi V-sivu · mm", + "render.cpu_area_samples": "Aluevalon näytteet", + "render.cpu_binding_confirm": "Vahvista tämä kappale", + "render.cpu_binding_stale": "Kohtaus muuttui. Vahvista tämä heijastuskohde uudelleen ennen renderöintiä.", + "render.cpu_body_choose": "Valitse kappale", + "render.cpu_body_filter": "Suodata kappaleita nimen mukaan", + "render.cpu_body_filter_more": "Tarkenna suodatinta nähdäksesi lisää kappaleita.", + "render.cpu_body_missing": "Heijastuskohde puuttuu, on piilotettu tai monitulkintainen tai sen nimi on yli 128 tavua pitkä. Valitse se uudelleen.", + "render.cpu_budget": "CPU-resurssiprofiili", + "render.cpu_budget_bodies": "Kappaleiden yläraja", + "render.cpu_budget_compact": "Tiivis (vanhat rajat)", + "render.cpu_budget_details": "Resurssirajat", + "render.cpu_budget_help": "Valitse suuremmat rajat erikseen. Tarkkuutta ja näytteitä ei koskaan pienennetä automaattisesti.", + "render.cpu_budget_memory": "Työn muistin yläraja", + "render.cpu_budget_not_guarantee": "Nämä ovat hyväksymisen ylärajoja, eivät muistivaraus tai nopeustakuu. Geometria, filmi ja säilytetyt esikatselut jakavat muistibudjetin; renderöinnin voi aina peruuttaa.", + "render.cpu_budget_resize": "Luonnos ylittää tämän CPU-profiilin tai sen kameranäytebudjetin. Hyväksy pienemmät mitat erikseen tai valitse suurempi profiili.", + "render.cpu_budget_studio": "Studio (suuret kuvat)", + "render.cpu_budget_triangles": "Kolmioiden yläraja", + "render.cpu_budget_workstation": "Työasema (raskaat kohtaukset)", + "render.cpu_captured_hdr": "Tätä kuvaa varten tallennettu HDR", + "render.cpu_check_capture_help": "Tarkista ja Aloita varmistavat saman tiedostotiivisteen tai käyttävät upotettua HDR:ää. Kukin kuva säilyttää tallennetun lähteensä.", + "render.cpu_check_changed": "Ohjaimet tai malli muuttuivat tämän tarkistuksen jälkeen. Tarkista uudelleen ennen renderöintiä.", + "render.cpu_constant_help": "Vakiosäteily näkyy heijastuneille tai läpäisseille säteille. Se ei anna suoraa diffuusia valaistusta.", + "render.cpu_custom_directions": "Korvaa esiasetus omilla suunnatuilla valoilla", + "render.cpu_direction": "Suunta valoa kohti (X, Y, Z)", + "render.cpu_directional": "Suunnattu valo", + "render.cpu_directional_add": "Lisää suunnattu valo", + "render.cpu_environment": "CPU-ympäristö", + "render.cpu_environment_background": "Kuvan tausta pysyy erillään ympäristövalaistuksesta.", + "render.cpu_environment_bounds": "CPU-voimakkuuden on oltava 0–64, HDR-kierron äärellinen ±1,000,000 radiaanin sisällä ja HDR-näytteitä 1, 4, 16 tai 64.", + "render.cpu_environment_constant": "Vakio toissijaisten säteiden ympäristö", + "render.cpu_environment_none": "Ei CPU-ympäristöä", + "render.cpu_environment_samples": "HDR-valaistuksen näytteet", + "render.cpu_exposure_help": "CPU-valotuksen on oltava välillä −16 ja 16 EV. Tämän välin ulkopuolinen GPU-valotus säilytetään, kunnes muutat sitä.", + "render.cpu_fixed": "Yksittäinen kuva", + "render.cpu_hdr_help": "Radiance .hdr, 2:1-panoraama, enintään 2048 × 1024 ja 16 MiB. CPU vaatii tiedostoon eksplisiittiset sRGB/D65-pääväripisteet; määrittämättömät pääväripisteet ja EXR hylätään.", + "render.cpu_hdr_reflection_help": "HDR:n karheat heijastukset vaativat täysin metalliset kappaleen ja pintojen materiaalit. Tarkistus raportoi tukemattomat yhdistelmät.", + "render.cpu_key_rim": "Pää- ja reunavalo", + "render.cpu_last_check": "Viimeisin CPU-tarkistus", + "render.cpu_light_help": "Enintään kahdeksan suunnattua valoa. Tyhjä oma luettelo sammuttaa ne; esiasetuksen valitseminen palauttaa sen valot. Värit ovat lineaarista RGB:tä ja voimakkuus on suhteellinen, ei watteja.", + "render.cpu_light_intensity": "Suhteellinen voimakkuus (0–64)", + "render.cpu_light_minimum": "Vaimenemisen vähimmäisetäisyys", + "render.cpu_light_position": "Maailman sijainti (X, Y, Z)", + "render.cpu_light_reference": "Voimakkuuden viite-etäisyys", + "render.cpu_light_remove": "Poista valo", + "render.cpu_lighting": "Valaistuksen esiasetus", + "render.cpu_lights": "CPU-valot", + "render.cpu_linear_color": "Lineaarinen väri (R, G, B)", + "render.cpu_neutral": "Neutraali", + "render.cpu_opaque_required": "CPU-säteenjäljitys vaatii läpinäkymättömän taustan. Jatka poistamalla valinta Läpinäkyvä tausta.", + "render.cpu_options_pending": "Tällä CPU-paneelilla ei voi vielä muokata emissiota, pintatehosteita, lasia eikä anisotropiaa. Tyhjennä nämä API-asetukset ennen sen käyttöä.", + "render.cpu_point": "Pistevalo", + "render.cpu_point_add": "Lisää pistevalo", + "render.cpu_point_help": "Enintään kahdeksan pistevaloa, jotka lisätään valitun suuntavalaistuksen päälle. Etäisyydet ovat millimetreinä; vähimmäisetäisyys ei saa ylittää viite-etäisyyttä.", + "render.cpu_primary_samples": "Särmänäytteitä pikseliä kohden", + "render.cpu_progressive": "CPU progressiivinen", + "render.cpu_progressive_help": "Kerryttää nykyisen CPU-integraattorin tulosta yhden ensisijaisen näytteen kierroksina. Valitut heijastukset edellyttävät yhtä näytettä; aluevalot, dielektrit ja anisotropia edellyttävät yksittäiskuvaa.", + "render.cpu_progressive_limits": "Enintään 1 048 576 pikseliä ja 16 777 216 pikseli × näyte -laskentaa. Näytemäärän muuttaminen ei koskaan muuta kuvan kokoa automaattisesti.", + "render.cpu_progressive_seed": "CPU-näytteistyksen siemenluku", + "render.cpu_progressive_spp": "näytettä pikseliä kohden", + "render.cpu_reflection_add": "Lisää karhea heijastus", + "render.cpu_reflection_depth": "Heijastussyvyys (1–8)", + "render.cpu_reflection_empty": "Kappaleita ei ole valittu: näkymän heijastukset ovat pois päältä.", + "render.cpu_reflection_help": "Valitse kappaleet ja aseta Pois, Peili tai Karhea. Karhea käyttää määritettyä pinnan karheutta. Useammat näytteet ja heijastuskerrat pidentävät laskenta-aikaa; tämä on rajattua peiliheijastusten kulkua, ei globaalia valaistusta.", + "render.cpu_reflection_limit": "Enintään 64 heijastavaa kappaletta on tuettu.", + "render.cpu_reflection_mirror": "Peili", + "render.cpu_reflection_off": "Pois", + "render.cpu_reflection_rough": "Karhea", + "render.cpu_reflection_samples": "Heijastusnäytteet (1–64)", + "render.cpu_reflections": "CPU-heijastukset", + "render.cpu_runtime_help": "Numeeriset valaistus- ja ympäristöasetukset tallennetaan asetelman mukana. Kappaleiden heijastukset ja HDR-tiedostot ovat väliaikaisia. Olemassa olevat aluevalo- ja kohdevalokartioarvot säilytetään.", + "render.cpu_sampling_mode": "CPU-näytteistystila", + "render.cpu_shadows": "Heitä varjot", + "render.cpu_summary": "CPU-säteenjäljitys · heijastukset · HDR · suunta- ja pistevalot", + "render.cpu_warm_cool": "Lämmin ja viileä", + "render.diag_bodies": "Näkyvät kappaleet", + "render.diag_job_details": "Tallennetun työn tiedot", + "render.diag_last_check": "Viimeisin esitarkistus", + "render.diag_memory": "Looginen hyväksyntäarvio", + "render.diag_not_implemented": "Ominaisuuksien rajat", + "render.diag_preflight_details": "Esitarkistuksen tiedot", + "render.diag_request": "Nykyinen pyyntö tarkalleen", + "render.diag_triangles": "Kolmiot", + "render.discard_continue": "Hylkää luonnos ja jatka", + "render.draft_confirm_help": "Nykyisessä renderöintiluonnoksessa on käyttämättömiä muutoksia. Tallenna ne ennen vaihtamista, hylkää ne erikseen tai jatka muokkaamista.", + "render.draft_confirm_title": "Säilytä muokatut renderöintiasetukset", + "render.effects_gpu_only": "Nämä tehosteet edellyttävät GPU-polunjäljitystä. Sivun vaihtaminen ei koskaan vaihda renderöijää automaattisesti.", + "render.effects_help": "Yhdistä järjestettyjä värisävyjä ja kuva-avaruuden objektiivitehosteita. Renderöinti ja raakamasterin uudelleenvärimäärittely käyttävät samoja tallennettuja asetuksia. Raaka-EXR pysyy muuttumattomana. Nämä ovat alkuperäisiä taiteellisia säätimiä, eivät kalibroituja objektiivi- tai tuotemerkkifilmijäljitelmiä.", + "render.effects_reset_lens": "Palauta objektiivitehosteet", + "render.effects_seed": "Kuvion siemenluku", + "render.emitted_axis": "Säteilyakseli", + "render.env_advanced": "Lisäasetukset", + "render.env_backdrop": "Taustakulissi", + "render.env_backdrop_pending": "Renderöijä ei vielä tue ympäristön näkyvyyttä eikä taustan sumennusta.", + "render.env_blur": "Sumennus", + "render.env_change": "Vaihda", + "render.env_choose_source": "Valitse ympäristö kohdasta Studiot ja ympäristöt ennen valaistuksen muokkaamista.", + "render.env_clear": "Tyhjennä", + "render.env_colour": "Väri", + "render.env_environments": "Ympäristöt", + "render.env_ground": "Maa", + "render.env_ground_pending": "Fyysinen maa vastaanottaa varjot rajallisena diffuusina pintana. Pelkkien varjojen sieppausta ja maaheijastuksia ei vielä tueta.", + "render.env_intensity": "Voimakkuus", + "render.env_invalid_edit": "Virheellinen ympäristön muokkaus.", + "render.env_physical_ground": "Fyysinen maa", + "render.env_preview_help": "Havainnollistava pallonäyte; ei valitun ympäristön esikatselu.", + "render.env_reflection": "Heijastus", + "render.env_ring_help": "Kierrä valaistusta vetämällä rengasta. Pidä Shift painettuna, niin kierto tarttuu 15° välein.", + "render.env_rotate": "Kierrä", + "render.env_set": "Aseta renderöintiympäristö", + "render.env_shadow_catcher": "Varjonsieppaaja", + "render.env_show_environment": "Näytä ympäristö", + "render.env_source": "Lähde", + "render.env_stage_details": "Maan muokkaus edellyttää säteenjäljitystä ja yhtä maapaneelia. Muokkaa muita näyttämöpaneeleja kohdassa Näkymä.", + "render.env_studios": "Studiot", + "render.environment.albedo": "Albedo", + "render.environment.atmosphere": "Ilmakehä", + "render.environment.backdrop_note": "Taustakulissi näkyy vain kameralle. Se ei koskaan valaise, heitä varjoja eikä heijastu, ja se hylätään läpinäkyvän tulosteen kanssa.", + "render.environment.blur_pending": "Sumennus ei ole käytettävissä: renderöijässä ei ole taustakulissin sumennusasetusta.", + "render.environment.builtin": "Sisäänrakennettu HDR", + "render.environment.check": "Tarkista tiedosto", + "render.environment.checked": "HDR-tiedosto tarkistettu. Tallennus upottaa nämä tavut.", + "render.environment.choose": "Valitse HDR…", + "render.environment.constant": "Vakio", + "render.environment.cyclorama": "Syklorama", + "render.environment.embedded": "Tallennettu tämän mallin sisään", + "render.environment.end": "Loppu", + "render.environment.extinction": "Ekstinktio", + "render.environment.file": "Tiedosto", + "render.environment.fit": "Sovita ja tallenna maa", + "render.environment.floor_wall": "Lattia ja seinä", + "render.environment.gap": "Välys", + "render.environment.gradient": "Liukuväri", + "render.environment.gradient_gpu": "Liukuvärinen taustakulissi edellyttää GPU-polunjäljitystä.", + "render.environment.ground": "Maa ja näyttämö", + "render.environment.hdr": "HDR", + "render.environment.hdr_file": "HDR-tiedosto", + "render.environment.horizon": "Horisontti", + "render.environment.horizontal": "Vaakasuora", + "render.environment.keep": "Säilytä", + "render.environment.lighting_samples": "Valaistusnäytteet", + "render.environment.margin": "Laajuuden marginaali", + "render.environment.max": "Enimmäisrajat", + "render.environment.medium": "Osallistuva väliaine", + "render.environment.min": "Vähimmäisrajat", + "render.environment.mode": "Tila", + "render.environment.needs_gpu": "Edellyttää GPU-polunjäljitystä.", + "render.environment.none": "Ei mitään", + "render.environment.orientation": "Suunta ja voimakkuus", + "render.environment.phase": "Vaihe", + "render.environment.primaries": "Käsittele määrittelemättömät päävärit lineaarisena sRGB:nä", + "render.environment.primaries_gpu": "Määrittelemättömien päävärien tulkinta edellyttää GPU-polunjäljitystä.", + "render.environment.radial": "Säteittäinen", + "render.environment.radial_only": "Keskipiste ja säde koskevat säteittäistä tilaa.", + "render.environment.reflectance": "Heijastavuus", + "render.environment.remove": "Poista näyttämö", + "render.environment.remove_confirm": "Poistetaanko tallennettu näyttämö?", + "render.environment.remove_note": "Poistaa tästä kuvakulmasta {count} passiivista paneelia. Kameran taustakulissi säilyy.", + "render.environment.replace": "Vahvista olemassa olevan näyttämön korvaaminen", + "render.environment.rotation_hdr": "Kierto edellyttää HDR-lähdettä CPU-säteenjäljityksessä.", + "render.environment.samples_cpu": "GPU-polunjäljityksen budjetti määrää valaistusnäytteet; tämä asetus edellyttää CPU-säteenjäljitystä.", + "render.environment.saved_panels": "Tallennetut paneelit {count}", + "render.environment.sky_ground": "Maa", + "render.environment.sky_note": "Alkuperäinen taivasliukuväri valaistukseen; ei kalibroitu ilmakehä.", + "render.environment.source_raytrace": "Ympäristölähteet edellyttävät CPU- tai GPU-säteenjäljitystä.", + "render.environment.stage_raytrace": "Fyysiset näyttämöt edellyttävät CPU- tai GPU-säteenjäljitystä.", + "render.environment.start": "Alku", + "render.environment.vertical": "Pystysuora", + "render.environment.world": "Maailma", + "render.environment.world_pending": "Maailmataustaa ei ole käytettävissä: ympäristön kameranäkyvyydellä ei ole vielä tallennettavaa asetusta.", + "render.environment.zenith": "Zeniitti", + "render.environment_tiles_require_raytrace": "Ympäristöt edellyttävät CPU- tai GPU-säteenjäljitystä. Valitse se Tuloste-editorissa.", + "render.error_area_samples": "area_samples-arvon on oltava 1, 4, 16 tai 64", + "render.error_binding_allocation": "materiaalisidontaa ei voitu varata", + "render.error_body_bound": "tuote-esikatselu ylittää tallennettujen kappaleiden rajan", + "render.error_checkpoint_dimensions": "tarkistuspisteen mitat poikkeavat tallennetusta pyynnöstä", + "render.error_decode_budget": "kuvan purkubudjetti ylittyi", + "render.error_denoise_setting": "virheellinen natiivi kohinanpoistoasetus", + "render.error_display_dimensions": "virheelliset kuvan näyttömitat", + "render.error_display_fit": "kuvan näyttö ei mahdu tälle laitteelle", + "render.error_display_height": "näytön korkeus ylittyi", + "render.error_display_width": "näytön leveys ylittyi", + "render.error_duplicate_face": "tuotteen pinnan ulkoasu on kahteen kertaan", + "render.error_export_document": "Renderöinnin vientiasiakirja muuttui kohteen valinnan aikana", + "render.error_face_cap": "tuote-esikatselu ylittää pintojen ulkoasujen hyväksyntärajan", + "render.error_finish_gesture": "viimeistele mallinnuseleet ennen esikatselua", + "render.error_finish_operation": "viimeistele nykyinen mallinnustoiminto ennen siirtymistä renderöintiin", + "render.error_fixed_preview": "kiinteä studioesikatselu edellyttää valotusta 0, ympäristön kiertoa 0 ja voimakkuutta 1", + "render.error_geometry_size": "tuotegeometrian koko ylittyi", + "render.error_glass_recipe": "tuntematon lasiresepti", + "render.error_gpu_preview": "GPU-tuote-esikatselu ei ole käytettävissä tässä isännässä. Tallennetut asetelmat ovat edelleen käytettävissä.", + "render.error_gpu_samples": "GPU-näytemäärää ei tueta", + "render.error_image_dimensions": "renderöidyn kuvan mitat eivät vastaa sen työtä", + "render.error_image_profile": "renderöity kuva ylittää tallennetun resurssiprofiilinsa", + "render.error_interactive_command": "sitomaton interaktiivinen renderöintikomento", + "render.error_job_action": "ei interaktiivinen kuvatyötoiminto", + "render.error_job_identity": "virheellinen renderöintityön tunniste: {error}", + "render.error_library_reply": "virheellinen renderöintikirjaston vastaus", + "render.error_material_binding": "materiaalisidonta puuttuu", + "render.error_no_completed_image": "renderöinnillä ei ole valmista kuvaa", + "render.error_no_geometry": "ei tuotegeometriaa", + "render.error_no_scene": "ei tuotenäkymää", + "render.error_opacity": "virheellinen tuotteen ulkoasun peittävyys", + "render.error_pbr_opacity": "peittävä PBR edellyttää peittävyyttä 1", + "render.error_physical_glass": "valittu resepti ei ole fyysinen lasi", + "render.error_preview_device": "tuote-esikatselu edellyttää asennettua laitetta, jossa on syvyyspuskuri", + "render.error_product_triangle": "virheellinen tuotekolmio", + "render.error_provisional_identity": "virheellinen väliaikainen renderöintitunniste tai näytemäärä", + "render.error_quality_bounds": "laatuprojektio ylittää natiivit rajat", + "render.error_quality_method": "laatuprojektio edellyttää samaa eksplisiittistä GPU-menetelmää", + "render.error_quality_projection": "virheellinen natiivi laatuprojektio", + "render.error_regrade_identity": "virheellinen uudelleenvärimäärittelyn tunniste: {error}", + "render.error_scene_bodies": "renderöintinäkymän kappaleet puuttuvat", + "render.error_scene_body_limit": "renderöintinäkymä ylittää kappalerajansa", + "render.error_scene_identity": "virheellinen renderöintinäkymän tunniste", + "render.error_setup_panicked": "GPU-polunjäljittimen alustus kaatui", + "render.error_setup_stopped": "alustustyöprosessi pysähtyi palauttamatta isäntää", + "render.error_setup_worker": "alustustyöprosessia ei voitu käynnistää: {error}", + "render.error_source_preview": "lähde-esikatselu ylittää tavurajansa", + "render.error_surface_normals": "PBR edellyttää nollasta poikkeavia pintanormaaleja", + "render.error_surface_reply": "virheellinen laaditun pinnan vastaus", + "render.error_triangle_bound": "tuote-esikatselu ylittää kahdeksan miljoonan kolmion lähderajan", + "render.error_triangle_count": "tuotteen kolmiomäärä ylittyi", + "render.error_upload_slot": "tuote-esikatselun latauspaikka ei ole käytettävissä", + "render.error_vertex_allocation": "tuote-esikatselun kärkipisteiden varaus epäonnistui", + "render.error_vertex_envelope": "tuote-esikatselu ylittää {limit} MiB:n kärkipistedatan rajan; geometriaa ei yksinkertaistettu", + "render.error_vertex_packing": "tuote-esikatselun pakkaus poikkeaa hyväksytystä kärkipistedatasta", + "render.error_visible_solid": "Luo näkyvä kiinteä kappale Suunnittelu-tilassa, niin voit esikatsella sitä täällä.", + "render.exit_focus": "Poistu kohdistuksesta", + "render.export_display": "Vie: näyttö-PNG", + "render.export_image_label": "Vie kuva", + "render.export_linear": "Vie: lineaarinen raaka-EXR", + "render.exr_pending": "GPU voi säilyttää lineaarisen raaka-EXR:n. Pakkaus, monikerroksiset kuvat ja apurenderöintikierrokset eivät ole käytettävissä.", + "render.film_grain": "Valokuvarakeisuus", + "render.fit": "Sovita tuote", + "render.fixed_camera": "Kamera", + "render.fixed_world": "Maailma", + "render.flare_ghosts": "Haamurenkaita lähdettä kohden", + "render.flare_halo": "Heijastuman halo", + "render.flare_streak": "Anamorfinen juova", + "render.flare_strength": "Kohokohtien heijastuman voimakkuus", + "render.flare_threshold": "Heijastuman kynnys (näkymälineaarinen)", + "render.fold_browser": "Kutista selain", + "render.frame_aspect": "Kuvasuhde", + "render.frame_centre_mark": "Keskimerkki", + "render.frame_copy_limit": "Vapaata kuvakulman kopionimeä ei ole käytettävissä", + "render.frame_copy_name": "{name} kopio {number}", + "render.frame_custom": "Mukautettu", + "render.frame_distance_unit": " × koko", + "render.frame_duplicate": "Monista", + "render.frame_exposure": "Valotus", + "render.frame_fov": "Näkökenttä", + "render.frame_guides": "Apuviivat", + "render.frame_invalid_aspect": "Virheellinen kuvasuhde-esiasetus", + "render.frame_lens": "Näkökenttä {fov}° · ≈ {mm} mm", + "render.frame_name": "Nimi", + "render.frame_output_size": "Tulosteen koko", + "render.frame_photo": "3:2 · Valokuva", + "render.frame_portrait": "4:5 · Pysty", + "render.frame_presets": "Rajausesiasetukset", + "render.frame_presets_pending": "Tulee kuvakulmaeditorin myötä", + "render.frame_projection": "Projektio", + "render.frame_render_shot": "Renderöi tämä kuvakulma", + "render.frame_rule_thirds": "Kolmanneksen sääntö", + "render.frame_safe_area": "Turva-alue", + "render.frame_shot_title": "Kuvakulma · {name}", + "render.frame_square": "1:1 · Neliö", + "render.frame_tall": "9:16 · Pysty", + "render.frame_thirds": "Kolmannekset", + "render.frame_wide": "16:9 · Laajakuva", + "render.gpu_depth": "Polun enimmäissyvyys", + "render.gpu_options_help": "Näytteet, syvyys, siemenluku ja valotus tallennetaan tämän asetelman mukana. Vain aktiivinen kuvamenetelmä tallennetaan.", + "render.gpu_path_failed": "GPU-polunjäljitin ei ole käytettävissä", + "render.gpu_path_first_setup": "Ensimmäinen alustus tällä GPU:lla voi kestää useita minuutteja; SolidCraftia voi käyttää sillä aikaa. Myöhemmät käynnistykset käyttävät käännettyjä varjostimia uudelleen, jos ajuri säilyttää ne.", + "render.gpu_path_preparing": "GPU-polunjäljitin: käännetään varjostimia…", + "render.gpu_seed": "Satunnaissiemen", + "render.gpu_unavailable": "GPU-polunjäljitys ei ole valmis tällä laitteella.", + "render.ground_apply": "Sovita ja tallenna maa", + "render.ground_gap": "Eksplisiittinen välys", + "render.ground_linear_rgb": "Diffuusi heijastavuus · lineaarinen RGB", + "render.ground_margin": "Maan laajuuden marginaali", + "render.hdr_details": "HDR-lähteen tiedot", + "render.hdr_embedded": "HDR tallennettu tämän mallin sisään", + "render.hdr_embedded_help": "Renderöinti käyttää malliin sisällytettyjä tavuja; alkuperäistä tiedostoa ei enää tarvita.", + "render.hdr_file_captured": "HDR-tiedosto tarkistettu. Tallennus upottaa nämä tavut; jos tiedosto muuttuu, tarkista se uudelleen erikseen.", + "render.hdr_inspect": "Tarkista HDR-tiedosto", + "render.hdr_inspect_required": "Valitse ja tarkista HDR-tiedosto ennen tallennusta tai renderöintiä.", + "render.hdr_primaries_declared": "Lähde ilmoittaa päävärinsä.", + "render.hdr_primaries_srgb": "Päävärit: sRGB/D65", + "render.hdr_primaries_undeclared": "Lähde ei ilmoita päävärejä; tarkista renderöijän värivaatimukset.", + "render.hdr_resource_missing": "Tästä mallista puuttuu tallennettu HDR-resurssi.", + "render.heading_batch": "ERÄ", + "render.heading_frame": "RAJAUS", + "render.heading_lens": "OBJEKTIIVI", + "render.heading_results": "TULOKSET", + "render.heading_shots": "KUVAKULMAT", + "render.hide_shots_label": "Piilota kuvakulmanauha", + "render.hover_look": "{object} · {look} · valitse napsauttamalla", + "render.image_advanced": "GPU:n lisäsäätimet", + "render.image_cancelled": "Renderöinti peruttu", + "render.image_cancelling": "Perutaan", + "render.image_completed": "Kuva valmis vietäväksi", + "render.image_encoding": "Koodataan PNG:tä", + "render.image_export": "Vie valmis kuva", + "render.image_exposure": "Valotus", + "render.image_failed": "Renderöinti epäonnistui", + "render.image_height": "Korkeus", + "render.image_help": "CPU-esikatselukuva · PNG · likimääräinen läpinäkyvyys", + "render.image_host_missing": "Kuvaisäntää ei ole asennettu.", + "render.image_method": "Kuvamenetelmä", + "render.image_overwrite": "Korvaa olemassa oleva tiedosto", + "render.image_preparing": "Valmistellaan kuvaa", + "render.image_progressive": "Progressiivinen renderöinti", + "render.image_queued": "Odottaa renderöintiä", + "render.image_reduce": "Kokeile pienempää kuvaa tai yksinkertaisempaa näkymää.", + "render.image_running": "Renderöidään kuvaa", + "render.image_samples": "Näytteitä pikseliä kohden", + "render.image_scene_stale": "Viimeistele mallinnuseleet tai päivitä näkymä ennen kuvan tarkistamista tai aloittamista.", + "render.image_stale": "Tämä kuva käyttää näkymää, joka tallennettiin ennen myöhempiä muutoksia.", + "render.image_start": "Aloita renderöinti", + "render.image_supported": "Renderöintipyyntö on tuettu; jono ja muistivaranto tarkistetaan uudelleen aloitettaessa.", + "render.image_title": "Renderöi kuva", + "render.image_too_large": "Kuvaraja ylittyy: 4096 pikseliä sivua kohden ja yhteensä 4 194 304 pikseliä.", + "render.image_transparent": "Läpinäkyvä tausta", + "render.image_unknown": "Renderöinnin tila ei ole saatavilla", + "render.image_use_largest": "Käytä suurinta kokoa tällä kuvasuhteella:", + "render.image_width": "Leveys", + "render.include_rig_cards": "Sisällytä passiiviset heijastinlevyt ja varjostimet", + "render.inner_half_angle": "Sisempi puolikulma", + "render.inspect_scene": "Päivitä tallennetun näkymän yhteenveto", + "render.inspector": "Tarkastelija", + "render.inspector_advanced": "Lisäasetukset", + "render.inspector_all_users": "Kaikki {count} käyttäjää", + "render.inspector_applies_to": "Koskee kohdetta", + "render.inspector_both_users": "Molemmat käyttäjät", + "render.inspector_chain": "Mistä tämä ulkoasu tulee", + "render.inspector_colour": "Väri", + "render.inspector_edit": "Muokkaa", + "render.inspector_finish": "Pintakäsittely", + "render.inspector_from_material": "Materiaalista", + "render.inspector_gloss": "Kiiltävä", + "render.inspector_material": "Materiaali", + "render.inspector_matte": "Matta", + "render.inspector_metal": "Metalli", + "render.inspector_opacity": "Peittävyys", + "render.inspector_opaque_help": "Pintakäsittely- ja optiset kentät käyttävät peittävää PBR:ää (peittävyys 1). Pienempi peittävyys käyttää skalaarivarjostusta.", + "render.inspector_pick_target": "Valitse tämäntyyppinen kohde tarkastellaksesi sen ulkoasua.", + "render.inspector_remove": "Poista ohitus", + "render.inspector_replace": "Korvaa…", + "render.inspector_reset": "Palauta", + "render.inspector_satin": "Satiini", + "render.inspector_save_library": "Tallenna kirjastoon…", + "render.inspector_set_all": "Sekalaisia ulkoasuja. Muokkaus asettaa ulkoasun kaikille valituille kohteille.", + "render.inspector_soon": "Tulossa", + "render.inspector_target_limit": "Valitse enintään 10000 kohdetta ulkoasujen tarkastelua varten.", + "render.inspector_textures": "Tekstuurit", + "render.inspector_this_body": "Tämä kappale", + "render.inspector_this_component": "Tämä komponentti", + "render.inspector_this_face": "Tämä pinta", + "render.inspector_this_target": "Tämä kohde", + "render.inspector_used_by": "Käyttäjiä {count}", + "render.keep_editing": "Jatka muokkaamista", + "render.layer_down": "Siirrä alas", + "render.layer_enabled": "Kerros käytössä", + "render.layer_off_suffix": " (pois)", + "render.layer_remove": "Poista kerros", + "render.layer_strength": "Kerroksen voimakkuus", + "render.layer_up": "Siirrä ylös", + "render.lens_effects_help": "Heijastuma käyttää enintään neljää erillistä kirkasta lähdettä varsinaisessa lineaarisessa kuvassa. Haamut, halo, juovat, kromaattiset siirtymät ja säteittäinen vääristymä ovat taiteellisia kuva-avaruuden likiarvoja. Tilatehosteet edellyttävät peittävää tulostetta; reunan ulkopuoliset näytteet jatkavat kuvan reunaa. Rakeisuus on deterministinen. Fysiikkaa, EXR:ää tai geometriaa ei muuteta.", + "render.lens_effects_title": "Objektiivi- ja valokuvatehosteet", + "render.library_all": "Luettelo", + "render.library_all_states": "Kaikki saatavuustilat", + "render.library_appearance_available": "Käytettävissä oleva ulkoasu", + "render.library_applicable": "Sovellettavat resurssit", + "render.library_applied": "Resurssiprojektio otettu käyttöön. Tarkista koko renderöintipyyntö ennen aloittamista.", + "render.library_apply_appearance": "Käytä ulkoasua", + "render.library_apply_hdr": "Tallenna tällä HDR-ympäristöllä", + "render.library_apply_hint": "Käytä napsauttamalla · vedä mallin päälle", + "render.library_apply_maps": "Käytä laadittuja GPU-pintakarttoja", + "render.library_apply_studio": "Tallenna laadittu studioprojektio", + "render.library_apply_uniform": "Käytä yhtenäistä peittävää ulkoasua", + "render.library_authored_help": "Alkuperäiset laaditut resurssit ovat havainnollistavia, eivät mitattua suunnittelutietoa. Kukin toiminto soveltaa vain ilmoitettua projektiotaan.", + "render.library_blocked": "Estetty / edellyttää kalibrointia", + "render.library_capabilities": "Ominaisuusmäärittelyt", + "render.library_center": "Valaisinasetelman keskipiste", + "render.library_clear_search": "Tyhjennä", + "render.library_details": "Määrittely ja alkuperä", + "render.library_emitters_only_ack": "Käytä vain valonlähteitä; jätä dokumentoidut passiiviset heijastinlevyt pois", + "render.library_empty": "Ei vastaavia resursseja. Kokeile toista hakua tai saatavuussuodatinta.", + "render.library_environment_concepts": "Ympäristökonseptit", + "render.library_extent": "Kohteen laajuus", + "render.library_favorite": "Lisää suosikkeihin", + "render.library_favorites": "Suosikit", + "render.library_filters": "Luettelo ja saatavuus", + "render.library_grid": "Ruudukko", + "render.library_hdr": "Sisäänrakennetut HDR-ympäristöt", + "render.library_hdr_help": "Upottaa alkuperäisen HDR:n tallennettuun asetelmaan. Laadittu pituusasteen origo muunnetaan erikseen; ulkoista tiedostoa ei tarvita tallennuksen jälkeen.", + "render.library_in_design": "Suunnittelussa", + "render.library_inspect_only": "Valitse tarkastellaksesi; mitään ei oteta käyttöön automaattisesti. Suosikit ja viimeaikainen historia kuuluvat tähän avoimeen asiakirjaistuntoon.", + "render.library_ior": "Taitekerroin", + "render.library_light_concepts": "Valaistuskonseptit", + "render.library_list": "Luettelo", + "render.library_maps_help": "Sisäänrakennetut kartat voidaan tallentaa kiinnitettyjen lähteiden ja paikallisen esiintymäkohdistuksen kanssa. Väliaikaiset optiset ohitukset ovat edelleen erillinen tila.", + "render.library_material_concepts": "Materiaalikonseptit", + "render.library_metallic": "Metallisuus", + "render.library_native_scenes": "Natiivit studiot", + "render.library_next": "Seuraava sivu", + "render.library_omitted": "Ei sisällytetty", + "render.library_opacity": "Peittävyys", + "render.library_other": "Muut ulkoasut", + "render.library_physical_profiles": "Fyysiset viiteprofiilit", + "render.library_previous": "Edellinen sivu", + "render.library_quality_concepts": "Laatumäärittelyt", + "render.library_recent": "Viimeaikaiset", + "render.library_replace_environment": "Korvaa olemassa oleva ympäristö erikseen", + "render.library_replace_studio": "Korvaa tallennettu valaistus, ympäristö ja näyttämö", + "render.library_results": "Vastaavat resurssit", + "render.library_rig_help": "Sovita kerran eksplisiittiseen keskipisteeseen ja fyysiseen laajuuteen. Täydelliset valaisinasetelmat sisältävät passiiviset heijastinlevyt; kalibrointiesteet hylkäävät edelleen. Valonlähteiden ja levyjen varovainen välys tarkistetaan ennen tallennusta.", + "render.library_rigs": "Laaditut valaisinasetelmat", + "render.library_roughness": "Karheus", + "render.library_save_maps": "Tallenna kartat tähän asetelmaan", + "render.library_scene_bounds": "Käytä tallennettuja kohtauksen rajoja", + "render.library_scenes": "Näkymämäärittelyt", + "render.library_search": "Hae kirjastosta", + "render.library_select_hint": "Valitse resurssi kirjastosta tarkastellaksesi sen tuettuja toimintoja ja rajoituksia.", + "render.library_selene": "SELENE-peittävät ulkoasut", + "render.library_selene_shots": "SELENE-kuvakulmamäärittelyt", + "render.library_short_blocked": "Ei käytettävissä", + "render.library_short_native": "Natiivi koostumus", + "render.library_short_projection": "Tuettu projektio", + "render.library_short_reference": "Vain viite", + "render.library_short_specification": "Vain määrittely", + "render.library_source_preview": "Lataa lähdekartan esikatselu", + "render.library_source_preview_help": "Laadittu perusvärin lähdekartta. Tämä ei ole renderöity eikä mitattu materiaalin esikatselu.", + "render.library_specification_only": "Vain määrittely: ei täydellinen suoritettava esiasetus. Vaaditut tehosteet, resurssit ja kohderoolit tarvitsevat yhä eksplisiittisen toteutuksen ja sidonnan.", + "render.library_specs": "Vain määrittelyt", + "render.library_status": "Saatavuus", + "render.library_surfaces": "Laaditut PBR-pinnat", + "render.library_target": "Kohdekappale", + "render.library_title": "Renderöinnin resurssikirjasto", + "render.library_unfavorite": "Poista suosikeista", + "render.library_uniform_ack": "Käytä yhtenäistä likiarvoa ilman tila- tai lisätehosteita", + "render.library_usable": "Suoritettavat projektiot", + "render.library_users": "Käyttäjät", + "render.light_aim": "Suuntaa kohteeseen", + "render.light_anchor_pending": "Valon koordinaatiston vaihtamista ei vielä tueta.", + "render.light_azimuth": "Atsimuutti", + "render.light_backend_limit": "Valitse CPU-säteenjäljitys tai eksplisiittinen GPU-studio valojen muokkaamiseksi. Vanhat GPU-studiovalot ovat vain luku -tilassa.", + "render.light_behaviour": "KÄYTTÄYTYMINEN", + "render.light_default_fill": "Täyttövalo", + "render.light_default_key": "Päävalo", + "render.light_default_number": "Valo {number}", + "render.light_default_rim": "Reunavalo", + "render.light_delete": "Poista", + "render.light_distance": "Etäisyys", + "render.light_duplicate": "Monista", + "render.light_elevation": "Korotuskulma", + "render.light_gpu_punctual": "Piste- ja kohdevalot ovat käytettävissä CPU-säteenjäljityksessä.", + "render.light_hard_shadow": "Tällä valolla on terävät varjot; valonlähteen pehmeys ei ole käytettävissä.", + "render.light_intensity": "Voimakkuus", + "render.light_missing": "Tätä valoa ei enää ole. Valitse valo selaimesta.", + "render.light_place_highlight": "Sijoita kohokohdan mukaan", + "render.light_place_pending": "Kohokohtasijoitus edellyttää valon valintaa näkymäikkunassa, eikä sitä vielä tueta.", + "render.light_position": "SIJAINTI", + "render.light_preview_help": "Live-näkymä on varjoton; aluevalot käyttävät keskinäytteeseen perustuvaa likiarvoa. Renderöinti käyttää täydellistä valomallia.", + "render.light_product_centre": "Tuotteen keskipiste", + "render.light_size": "Koko", + "render.light_softness": "Pehmeys", + "render.light_temperature": "Värilämpötila", + "render.light_temperature_help": "Likimääräinen mustan kappaleen sävy; tallennetaan lineaarisena RGB:nä.", + "render.light_type": "Tyyppi", + "render.light_type_area": "Aluevalo", + "render.light_type_point": "Pistevalo", + "render.light_type_spot": "Kohdevalo", + "render.light_type_sun": "Aurinko", + "render.light_view_only": "Soolo ja mykistys vaikuttavat tähän näkymään ja sen renderöinteihin; niitä ei koskaan tallenneta malliin.", + "render.light_world_origin": "Maailman origo", + "render.lighting_aim_point": "Kohdistuspiste", + "render.lighting_apply": "Käytä esiasetusta", + "render.lighting_area_samples": "Aluenäytteet", + "render.lighting_budget": "Budjetti", + "render.lighting_budget_help": "Määrät ovat vain luku -tilassa. Muuta niitä lisäämällä, monistamalla tai poistamalla valoja; menetelmä määrää rajat.", + "render.lighting_colour": "Väri", + "render.lighting_consent": "Korvaa suuntavalot tällä esiasetuksella", + "render.lighting_custom": "Mukautetut valot", + "render.lighting_custom_help": "Kun valitset Mukautettu, esiasetus muuttuu muokattaviksi valoiksi, kukin omalle rivilleen puussa.", + "render.lighting_direction": "Suunta X Y Z", + "render.lighting_direction_help": "Tai kirjoita suunta valoa kohti (X Y Z).", + "render.lighting_distance_unit": " × koko", + "render.lighting_edge_u": "Sivun U-vektori", + "render.lighting_edge_v": "Sivun V-vektori", + "render.lighting_falloff": "Vaimeneminen", + "render.lighting_falloff_help": "Voimakkuus ilmoitetaan viite-etäisyydellä.", + "render.lighting_height": "Korkeus V", + "render.lighting_minimum": "Vähimmäisarvo", + "render.lighting_mute": "Mykistä tämä valo", + "render.lighting_point": "Pistevalo", + "render.lighting_preset": "Studioesiasetus", + "render.lighting_preset_cpu": "Suuntavalojen studioesiasetukset edellyttävät CPU-säteenjäljitystä. GPU-valaistus käyttää eksplisiittisiä aurinko- ja aluevaloja.", + "render.lighting_preset_row": "Esiasetus", + "render.lighting_radiance": "Radianssi", + "render.lighting_reference": "Viite", + "render.lighting_review_help": "Korvaa suuntavalojen luettelon. Säilyttää piste- ja aluevalot, ympäristön, varjot, kameran ja kaikki muut kuvakulman asetukset.", + "render.lighting_review_title": "Tarkista valaistusesiasetus", + "render.lighting_samples_cpu": "Aluevalonäytteet koskevat CPU-säteenjäljitystä.", + "render.lighting_samples_need_area": "Lisää CPU-aluevalo, jotta voit asettaa aluenäytteet.", + "render.lighting_samples_reason": "Aluenäytteiden on oltava 1, 4, 16 tai 64.", + "render.lighting_shadow_cpu": "Varjokytkin edellyttää CPU-säteenjäljitystä. GPU-polunjäljitys heittää aina varjot.", + "render.lighting_shadows": "Heitä varjot", + "render.lighting_shadows_section": "Varjot ja näytteistys", + "render.lighting_shape": "Muoto", + "render.lighting_solo": "Soolo tälle valolle", + "render.lighting_source": "Lähde", + "render.lighting_source_section": "Valonlähde", + "render.lighting_spot_preserved": "Tämä pistevalo säilyttää tallennetun valokartionsa, kunnes sen tyyppiä muutetaan.", + "render.lighting_sun_distance": "Auringon suunta ei riipu etäisyydestä eikä kohdistuspisteestä.", + "render.lighting_unsupported": "ei tuettu", + "render.lighting_used": "{used}/{limit}", + "render.lighting_width": "Leveys U", + "render.lighting_world_position": "Maailma X Y Z", + "render.lights_fixed_to": "Valot kiinnitetty kohteeseen", + "render.linear_help": "Säilyttää 32-bittisen liukuluku-RGBA-masterin ennen kohinanpoistoa, valotusta, sävykartoitusta, suodattimia ja taustakulissia. Lineaarinen sRGB/D65; peittoalalla esikerrottu. Lisämuisti hyväksytään erikseen. Ei pakkausta eikä lisäkierroksia.", + "render.linear_retain": "Säilytä lineaarinen raaka-EXR", + "render.linear_unavailable": "Valitulla valmiilla kuvalla ei ole säilytettyä EXR:ää. Ota säilytys käyttöön ennen renderöintiä; vanhemmasta PNG:stä ei voi palauttaa raakaa radianssia.", + "render.look_add": "Lisää värisävy", + "render.look_applied": "Käytetty: {name}", + "render.look_bleach": "Bleach bypass -henkinen", + "render.look_cool": "Viileä", + "render.look_cyanotype": "Syanotypia-henkinen", + "render.look_faded": "Haalistunut vedos", + "render.look_material": "Materiaali", + "render.look_mono": "Mustavalkoinen", + "render.look_pasted": "Ulkoasu liitetty", + "render.look_sepia": "Seepia", + "render.look_strength": "Sävyn voimakkuus", + "render.look_teal_orange": "Sinivihreä / oranssi", + "render.look_title": "Luova sävypino", + "render.look_warm": "Lämmin", + "render.mapping_scale": "Fyysisen toiston kerroin", + "render.material_absorption": "Absorptio R · G · B (per mm)", + "render.material_add": "Lisää tai muokkaa tätä kappaletta", + "render.material_assignments": "Kappalemääritykset", + "render.material_binding_enable": "Sisällytä tämän kappaleen ohitus", + "render.material_box": "Akselien suuntainen laatikko", + "render.material_browse": "Valitse kuva…", + "render.material_certification": "Suljettu lasi käyttää geometrista etäisyyttä. Topologia, suunta, päällekkäisyys ja optiset rajat tarkistetaan GPU-valmistelun aikana; Tarkista vain hyväksyy pyynnön.", + "render.material_choose_body": "Valitse näkymän kappale", + "render.material_closed": "Suljettu umpinainen verkko", + "render.material_coat": "Kirkaslakka perusmateriaalin päällä", + "render.material_coat_enable": "Ota kirkaslakka käyttöön", + "render.material_coat_help": "Havainnollistava dielektrinen pinnoite olemassa olevan peittävän ulkoasun päällä. Nollapaino jättää perustan ennalleen.", + "render.material_color_map": "Perusvärikuva (sRGB)", + "render.material_color_replace": "Peruskartta korvaa kappaleen värin", + "render.material_custom": "Mukautettu havainnollistava optiikka", + "render.material_enable": "Käytä näitä GPU-materiaaliohituksia", + "render.material_filter": "Suodata näkymän kappaleita…", + "render.material_filter_help": "Enintään 128 vastaavaa kappaletta näytetään. Tarkenna suodatinta suurissa näkymissä.", + "render.material_glass": "Lasi ja optinen absorptio", + "render.material_glass_enable": "Käytä fysikaalista lasia tässä kappaleessa", + "render.material_glass_exclusive": "Lasi ei voi jakaa kappaletta kirkaslakan tai ajonaikaisten karttojen kanssa tässä renderöijässä.", + "render.material_glass_help": "Alkuperäisiä havainnollistavia reseptejä. Värimallit näyttävät läpäisyn, eivät renderöityä esikatselua. Absorptio on −ln(lineaarinen läpäisy) / viite-etäisyys; alfa ei muutu.", + "render.material_gpu_required": "Nämä aktiiviset materiaaliohitukset edellyttävät GPU-polunjäljitystä. Valitse GPU tai poista ohitukset käytöstä ennen Tarkista- tai Aloita-toimintoa.", + "render.material_ior": "Taitekerroin (IOR)", + "render.material_limits": "Enintään 128 kappaleohitusta, 32 erillistä lasikappaletta, 64 pinnoitetta ja 128 tekstuurisidontaa. Identtiset kartat jakavat tallennustilan; laitteen ja kokonaismuistin todelliset rajat ovat silti voimassa.", + "render.material_map_invalid": "Karttapolkujen on oltava rajattuja paikallisia polkuja; normaalin voimakkuuden on oltava äärellinen ja välillä 0–1.", + "render.material_map_required": "Valitse värikuva tai normaalikuva ennen karttojen käyttöä.", + "render.material_maps": "Tasomaiset väri- ja normaalikartat", + "render.material_maps_enable": "Ota kartat käyttöön tälle peittävälle kappaleelle", + "render.material_maps_help": "PNG/JPEG enintään 1024×1024; koodattuna yhteensä 16 MiB. U ja V ovat kohtisuoria maailman millimetreinä ilmaistuja toistovektoreita (enintään 128 toistoa). Väri on sRGB; normaalidata käyttää OpenGL +Y -käytäntöä. Tiedostot luetaan Tarkista/Aloita-vaiheessa.", + "render.material_metallic_map": "Metallisuuskartta (lineaarinen)", + "render.material_normal_map": "Normaalikuva (OpenGL, +Y)", + "render.material_normal_strength": "Normaalin voimakkuus (0–1)", + "render.material_origin": "Kohdistuksen origo X · Y · Z (mm)", + "render.material_refresh": "Päivitä näkymän kappaleet", + "render.material_refresh_needed": "Näkymä muuttui. Päivitä kappaleluettelo ennen kohteen lisäämistä.", + "render.material_remove": "Poista tämä määritys", + "render.material_repeat_u": "Yksi U-toisto X · Y · Z (mm)", + "render.material_repeat_v": "Yksi V-toisto X · Y · Z (mm)", + "render.material_revalidate": "Vahvista tämä kappale uudelleen", + "render.material_revalidate_needed": "Tämä määritys kuuluu aiempaan näkymäversioon. Vahvista sen tarkka kappaletunniste uudelleen ennen renderöintiä.", + "render.material_roughness": "Pinnoitteen karheus (0.045–1)", + "render.material_roughness_map": "Karheuskartta (lineaarinen)", + "render.material_shadow": "Päästä suorat varjosäteet läpi", + "render.material_target_missing": "Kappaleen järjestysnumero ja nimi eivät enää täsmää. Poista tämä määritys ja valitse aiottu kappale uudelleen erikseen.", + "render.material_thickness": "Ohuen levyn paksuus (mm)", + "render.material_thin": "Ohut levy", + "render.material_title": "GPU-kuvamateriaalit", + "render.material_transient": "Väliaikaiset optiset ohitukset tälle asiakirjavälilehdelle. Niitä ei tallenneta malliin, renderöintiasetelmaan eikä materiaalikirjastoon.", + "render.material_v_up": "Tekstuurin V osoittaa kuvassa ylöspäin", + "render.material_weight": "Pinnoitteen paino (0–1)", + "render.method_cpu": "CPU-säteenjäljitys", + "render.method_gpu": "GPU-polunjäljitys", + "render.method_limit_raster": "Rasterointi käyttää kiinteää peittävää studioesikatselua. Valitse eksplisiittinen säteenjäljitysmenetelmä tuettuja optisia säätimiä varten.", + "render.method_raster": "CPU-rasterointi", + "render.navigation_help": "Kamera liikkuu kuten Suunnittelu-tilassa (Asetukset › Navigointi). Tallenna asetelma tallentaa nykyisen kameran.", + "render.nested_enable": "Varmennetut sisäkkäiset dielektrit", + "render.nested_help": "Enintään 16 sisäkkäistä kerrosta; jokaisen vanhemman on oltava kupera ja jokaisen lapsen kokonaan sen sisällä. Leikkaukset, koskettavat pinnat, ohuet levyt ja suorien varjojen läpäisy hylätään. Kameran sisällä olon tila seuraa varmennettua hierarkiaa. Ei luo nestepintaa eikä yhdistä koskettavia CAD-rajoja.", + "render.opaque_image_summary": "Esikatselu-PNG · peittävä PBR · sekoitettu läpinäkyvyys", + "render.opaque_preview_help": "Peittävä PBR ja yksinkertaiset värit; sekoitettu läpinäkyvyys. Taittuminen, HDRI ja lopullinen renderöinti eivät ole vielä käytettävissä.", + "render.optics_remove": "Poista tallennettu optiikka", + "render.optics_replace": "Korvaa tämän kohteen tallennettu optiikka erikseen", + "render.optics_save": "Tallenna tämä optiikka asetelmaan", + "render.optics_saved": "Tallennetut optiset kohteet", + "render.optics_saved_help": "Tarkka määrittely-, piirre- ja esiintymätunniste säilyy avattaessa uudelleen offline-tilassa. Puuttuvat/korvatut/piilotetut kohteet hylätään; suunnittelumateriaalit eivät muutu. Tallenna tai hylkää numeeriset muokkaukset ennen tallennetun kohteen poistamista.", + "render.outer_half_angle": "Ulompi puolikulma", + "render.output_advanced": "Lisäasetukset", + "render.output_backend_ready": "Valmis", + "render.output_check": "Tarkista", + "render.output_check_failed": "Tarkistus · virhe", + "render.output_check_help": "Suorita Tarkista, niin voit tarkastella tätä pyyntöä aloittamatta renderöintiä.", + "render.output_check_summary": "Tarkistus · Huomioita: {count}", + "render.output_copy": "Kopioi", + "render.output_copy_report": "Kopioi raportti", + "render.output_destination": "Kohde", + "render.output_destination_help": "Valitse kohdetiedosto, kun viet valmiin kuvan.", + "render.output_dimensions": "Koko", + "render.output_effects": "Tehosteet", + "render.output_export": "Vie PNG…", + "render.output_exr_unavailable": "EXR-tulosteen asetus ei ole käytettävissä tässä. Lineaarisen EXR:n vienti edellyttää valmista GPU-kuvaa, jossa on säilytetty lineaarinen master.", + "render.output_fit": "Sovita", + "render.output_format": "Muoto", + "render.output_format_status": "PNG on täsmälleen valmis näyttökuva. Valinnainen GPU-EXR säilyttää raa'an näkymälineaarisen FLOAT32-radianssin ennen näyttösuodattimia. Vienti ei koskaan korvaa sitä esikatseluvälimuistilla tai toisella työllä.", + "render.output_grading": "Värimäärittely", + "render.output_image": "Kuva", + "render.output_largest": "enintään {width} × {height}", + "render.output_lock_ratio": "Lukitse kuvasuhde", + "render.output_over_budget": "Pyydetty kuva ylittää valitun resurssirajan. Valitse yhteensopiva koko tai profiili erikseen; automaattista heikennystä ei tehdä.", + "render.output_presets_help": "Muoto, laatu ja tarkistusluettelo ovat Tuloste-editorissa.", + "render.output_quality": "Laatu", + "render.output_quality_waiting": "odotetaan laatusopimusta", + "render.output_ratio_refused": "Linkitetty mitta ylittää tämän menetelmän kokorajan. Edellinen koko säilytetään; avaa kuvasuhteen lukitus tai valitse pienempi arvo.", + "render.output_ready": "Valmis renderöitäväksi", + "render.output_run_check": "Suorita tarkistus", + "render.output_size_limit": "{method}: enintään {dimension} px sivua kohden ja {pixels} pikseliä. Suurin sopiva koko: {width} × {height}.", + "render.output_size_ok": "Koko kunnossa · {width} × {height} px", + "render.output_swap_orientation": "Vaihda leveys ja korkeus", + "render.output_tools_inspector": "Muokkaa kokoa ja muotoa Tuloste-tarkastelijassa.", + "render.output_view_image": "Näytä kuva", + "render.page_aging": "Ikääntyminen ja lika", + "render.page_all": "Kaikki säätimet", + "render.page_appearance": "Ulkoasu", + "render.page_background": "Taustat", + "render.page_camera": "Kamera", + "render.page_diagnostics": "Diagnostiikka", + "render.page_effects": "Objektiivi- ja viimeistelytehosteet", + "render.page_environment": "Ympäristö", + "render.page_lighting": "Valaistus", + "render.page_output": "Tuloste", + "render.page_scene": "Kohtaus", + "render.paint_label": "Maalaa", + "render.painting_with": "Maalataan ulkoasulla {name}", + "render.passive_stage": "Maa ja passiivinen näyttämö", + "render.passive_stage_help": "Rajalliset passiiviset paneelit kuuluvat vain renderöityihin kuviin. Ne eivät lisää CAD-kappaleita eivätkä massaa. Sijainti on kiinteä käytön jälkeen; tuotteen rajojen kanssa leikkaavat hylätään. CPU ei tuota diffuusia heijastusvalaistusta.", + "render.perspective": "Perspektiivikamera", + "render.physical_acknowledge": "Ymmärrän, että tämä osittainen viite vaatii laadun, kunnon ja lähteiden tarkistuksen", + "render.physical_associations": "Fyysiset ehdokkaat ja roolit", + "render.physical_background_help": "Todellinen passiivinen lattia ja seinä, erillään kameran taustasta. Syklorama käyttää 24 monikulmionauhaa; se ei ole ääretön eikä analyyttisesti sileä pinta. Korvaa tallennetun näyttämön vain suostumuksellasi.", + "render.physical_copy_plan": "Kopioi suunnitelma lähteineen ja puutteineen", + "render.physical_cyclorama": "Sovita monikulmiosyklorama", + "render.physical_floor_wall": "Sovita fyysinen lattia ja seinä", + "render.physical_material_name": "Ehdotettu viitemateriaalin nimi", + "render.physical_omissions": "Ominaisuudet, joita ei voi esittää alkuperäisessä kortissa", + "render.physical_plan_only": "Vain luku -suunnitelma valmisteltu. Materiaalia ei luotu eikä määritetty. Säilytä sen laajennettu profiili ja puutteet, kun tarkistat alkuperäistä korttia.", + "render.physical_prepare_plan": "Valmistele luontisuunnitelma (ei ota käyttöön)", + "render.physical_separate": "Ulkoasu ei ole materiaalin tunnistus. Nämä ovat lähteistettyjä viitteitä, eivät sertifioituja efektiivisiä ominaisuuksia. Nykyinen massa, tekniset materiaalit ja optiikka pysyvät ennallaan.", + "render.physical_unknown": "Numeerista ehdokasta ei ole vahvistettu. Laatu, koostumus tai rakenne on määritettävä; tuntematon ei ole nolla.", + "render.pick_body": "Kappale", + "render.pick_component": "Komponentti", + "render.pick_face": "Pinta", + "render.pick_help": "Valitse kappale, pinta tai komponentti. Tyhjennä napsauttamalla tyhjää kohtaa; Shift tai Ctrl lisää tai vaihtaa valintaa. Korostukset näkyvät vain tuotteen live-näkymässä.", + "render.pick_label": "Valitse", + "render.pick_up_label": "Poimi", + "render.pick_up_prompt": "Poimi ulkoasu napsauttamalla objektia", + "render.pick_waiting": "Tuotteen valintaa ei vielä tueta.", + "render.post_contrast": "Kontrasti", + "render.post_gain_b": "Sinisen vahvistus", + "render.post_gain_g": "Vihreän vahvistus", + "render.post_gain_r": "Punaisen vahvistus", + "render.post_help": "Vain luovaan esitykseen. RGB-vahvistukset tehdään ennen sävykartoitusta; kontrasti, kylläisyys ja vinjetti sen jälkeen näytön lineaarisessa valossa. Aloita renderöinti luo uusia kuljetusnäytteitä. Uudelleensävytys käyttää valittua säilytettyä raakamasteria ilman kohinanpoistoa tai uusia säteitä.", + "render.post_reset": "Palauta esityssuodattimet", + "render.post_saturation": "Kylläisyys", + "render.post_title": "Esityssuodattimet", + "render.post_vignette": "Vinjetti", + "render.preview": "Integroitu esikatselu", + "render.preview_help": "Rasterivarjostus ja sekoitettu läpinäkyvyys. Taittuminen, HDRI ja lopullinen renderöinti eivät ole vielä käytettävissä.", + "render.preview_image_settings_help": "Live-esikatselu käyttää kiinteää studiovalaistusta. Valotus ja kuvan valaistus koskevat kuvatyötä, kun valitset Tarkista tai Aloita.", + "render.preview_lighting_help": "Live-esikatselu näyttää vain suoran valon eikä varjoja.", + "render.preview_retry": "Yritä live-esikatselua uudelleen", + "render.preview_unavailable_help": "Live-esikatselu ei ole käytettävissä. Tallennetut asetelmat ja kuvatyön säätimet ovat edelleen käytettävissä. Muuta näkymää tai yritä uudelleen erikseen; hylättyä näkymää ei rakenneta uudelleen joka kehyksessä.", + "render.preview_upload": "Live-esikatselun kärkipistedata", + "render.preview_upload_help": "Esikatselun kärkipisteiden tarkka tavumäärä, ei GPU:n tai prosessin kokonaismuistia. Geometriaa ei yksinkertaisteta. Kuvatöillä on oma hyväksyntänsä ja valaistuksensa.", + "render.progressive_image_summary": "Esikatselu-PNG · PBR ja lasi · progressiiviset näytteet", + "render.property_conditions": "Olosuhteet: {value}", + "render.property_fallback": "ominaisuus", + "render.property_qualifier": "Tarkenne: {value}", + "render.property_source": "Lähde: {id} - {locator}", + "render.property_uncertainty": "Epävarmuus: {value}", + "render.property_unknown": "tuntematon", + "render.quality_ack": "Kuittaa kiinteän budjetin projektio ja puutteet", + "render.quality_apply": "Käytä tätä kiinteää näytteistysbudjettia", + "render.quality_balanced": "Tasapainoinen", + "render.quality_custom": "Mukautettu", + "render.quality_draft": "Luonnos", + "render.quality_high": "Korkea", + "render.quality_projection_help": "Q-esiasetukset sisältävät tulevia vaatimuksia. Tämä toiminto projisoi vain tuetun kiinteänäytteisen PNG-budjetin ja jättää nimenomaisesti pois mukautuvan pysäytyksen, lineaarisen raakatulosteen ja erilliset läpäisyrajat.", + "render.quality_review": "Tarkista näytteistysbudjetti", + "render.queue_pending": "Tässä käyttöliittymässä ei ole automaattista tuotantojonoa eikä animaatiorenderöijää. Valmiit still-kuvat voi edelleen viedä erikseen.", + "render.radial_assign": "Määritä ulkoasu", + "render.radial_compare": "Vertaa", + "render.radial_distortion": "Säteittäinen vääristymä", + "render.radial_fit": "Sovita tuote", + "render.radial_save": "Tallenna kuvakulma", + "render.recent_looks": "Viimeisimmät ulkoasut", + "render.regrade_action": "Sävytä raakamaster uudelleen (ei kohinanpoistoa)", + "render.regrade_help": "Luo erillisen PNG:n valitusta valmiista raakamasterista näillä esityssäätimillä. Ei jäljitä säteitä, muuta tallennettua kokoa, kameraa tai valoja eikä korvaa EXR:ää. Kohinanpoistoa ei tehdä uudelleen: raakamasterit eivät säilytä sen apukuvia. Johdannainen on vietävissä samoilla työn säätimillä.", + "render.regrade_label": "Sävytä uudelleen", + "render.reload_settings": "Lataa tallennetut asetukset uudelleen", + "render.remove_override": "Poista ohitus", + "render.replace_all": "Korvaa kaikki", + "render.replace_ground": "Vahvista nykyisen näyttämön korvaaminen", + "render.replace_label": "Korvaa", + "render.replace_saved_surface": "Korvaa tämän kohteen olemassa oleva tallennettu sidonta", + "render.replace_with": "Korvaa tällä", + "render.restore_camera": "Palauta tallennettu kamera", + "render.result_actual": "100 %", + "render.result_actual_help": "Yksi kuvan pikseli näytön pikseliä kohden.", + "render.result_actual_size": "100 %", + "render.result_capture": "Tallennettu revisio", + "render.result_current": "Tallennettu mallin revisio on ajan tasalla.", + "render.result_empty": "Valmista kuvaa ei vielä ole. Tarkista asetukset ja aloita sitten renderöinti.", + "render.result_fit": "Sovita kuva", + "render.result_job": "Työ", + "render.result_navigation": "Panorointi ja zoomaus noudattavat navigointiasetuksia. Välilyönti + veto panoroi.", + "render.result_open": "Avaa valmis kuva pääpiirtoalueelle.", + "render.result_preview": "Live-esikatselu", + "render.result_provisional": "Väliaikainen CPU-kuva", + "render.result_provisional_help": "Tätä välitallennetta ei voi viedä. Vienti säilyttää viimeisimmän valmiin tuloksen; peruutus palaa siihen tulokseen.", + "render.result_reduced_display": "Näytön esikatselu pienennetty näkymäikkunan laitteen/välimuistin rajaan. Säilytetty PNG ja vienti säilyttävät täyden resoluution; alkuperäinen 100 %:n tarkastelu ei ole käytettävissä tässä pienennetyssä näkymässä.", + "render.result_retained": "Näytetään viimeisin valmis kuva; uudempi renderöinti ei ole korvannut sitä.", + "render.result_sequence": "Välitallenne", + "render.result_title": "Renderöinnin tulos", + "render.return_design": "Palaa suunnitteluun", + "render.review_stale": "Tämä tarkistus on vanhentunut. Ratkaise tai tarkista uudelleen ennen käyttöönottoa.", + "render.ribbon_aging": "Vanhentaminen", + "render.ribbon_backgrounds": "Taustat", + "render.ribbon_check": "Tarkista", + "render.ribbon_check_help": "Tarkista täsmälleen se nykyinen luonnos, jonka Renderöi lähettää. Ei varalla olevaa renderöijää, hiljaista koon muutosta tai resurssien korvaamista.", + "render.ribbon_edit_lights": "Muokkaa valoja", + "render.ribbon_effects": "Tehosteet", + "render.ribbon_environment_help": "HDR-valaistus, vain kameralle näkyvät taustat ja fyysiset näyttämöpinnat ovat erillisiä säätimiä, joiden korvaaminen vaatii nimenomaisen suostumuksen.", + "render.ribbon_finish_dialog": "Viimeistele ensin nykyinen tiedosto- tai vahvistusikkuna.", + "render.ribbon_frame": "Rajaa", + "render.ribbon_hdr_library": "HDR-kirjasto", + "render.ribbon_job_active": "Renderöinti on jo käynnissä; peruuta se erikseen ennen uuden aloittamista.", + "render.ribbon_light_rigs": "Valoasetelmat", + "render.ribbon_lights_help": "Tarkastele laadittuja valoasetelmia tai muokkaa tuettuja valoja korvaamatta nykyistä asetelmaa, kunnes otat muutoksen erikseen käyttöön.", + "render.ribbon_materials": "Materiaalit", + "render.ribbon_materials_help": "Avaa jaettu ulkoasutarkastin ja alkuperäinen pintakirjasto. Optiset muokkaukset eivät koskaan muuta teknisiä ominaisuuksia huomaamatta.", + "render.ribbon_no_active_job": "Peruutettavaa aktiivista renderöintiä ei ole.", + "render.ribbon_no_result": "Viimeistele renderöinti ennen sen tarkan kuvan vientiä.", + "render.ribbon_no_saved_camera": "Tallenna kuvakulma ennen sen kameran palauttamista.", + "render.ribbon_saved_camera": "Tallennettu kamera", + "render.ribbon_shots": "Kuvakulmat", + "render.ribbon_studios": "Studiot", + "render.ribbon_studios_help": "Selaa toteutettuja studiokoostumuksia ja tarkista niiden korvaukset ennen käyttöönottoa. Pelkät konseptinäkymät pysyvät merkittyinä.", + "render.ribbon_surface_maps": "Pintakartat", + "render.sampling_title": "Mukautuva ja läpäisynäytteistys", + "render.save_continue": "Tallenna ja jatka", + "render.save_setup": "Tallenna asetelma", + "render.save_shot": "Tallenna kuvakulma", + "render.saved_maps_runtime_conflict": "Tallennettuja pintasidontoja ei voi yhdistää väliaikaisiin optisiin ohituksiin tai tallentamattomaan HDR:ään. Tallenna HDR tai poista väliaikaiset syötteet erikseen.", + "render.saved_surface_remove": "Poista tallennettu sidonta", + "render.saved_surfaces": "Tallennetut pintasidonnat", + "render.saved_surfaces_help": "Kiinnitetyt sisäiset kartat seuraavat valittua esiintymää paikallisissa millimetreissä. Korvattu tai puuttuva kohde on virhe, ei koskaan automaattinen uudelleenmääritys.", + "render.scene_all_shots": "Kaikki kuvakulmat ({count})", + "render.scene_apply": "Ota tarkistettu studio käyttöön", + "render.scene_batch_reason": "Kaikki kuvakulmat vaatii tallennettujen kuvakulmien renderöintijonon, joka ei ole vielä käytettävissä.", + "render.scene_check_now": "Tarkista nyt", + "render.scene_check_passed": "Tarkistus läpäisty · {notes} huomautusta", + "render.scene_check_stale": "Tarkistus vanhentunut · tarkista uudelleen", + "render.scene_check_unchecked": "Ei vielä tarkistettu · 0 huomautusta", + "render.scene_consent": "Vahvista valaistuksen, ympäristön, valotuksen ja näyttämön korvaaminen", + "render.scene_light_summary": "{environment} · {lights} valoa", + "render.scene_look_summary": "{looks} ulkoasua · {overrides} ohitusta", + "render.scene_open_check": "Avaa tarkistus", + "render.scene_preserved_fields": "Kamera, näytteistys, mitat, optiset sidonnat, CAD-geometria ja tekniset materiaalit säilytetään.", + "render.scene_preserves_design": "Sommittele valaistus ja passiivinen näyttämö näkyvälle kohteelle. Geometria, tekniset materiaalit ja kamera pysyvät erillään.", + "render.scene_ready": "Valmis renderöitäväksi", + "render.scene_reminder": "Näkymä säilyttää mallin. Geometriaa, teknisiä ominaisuuksia tai CAD:ia ei koskaan muuteta renderöinnistä käsin.", + "render.scene_reminders": "Muistutukset", + "render.scene_renderer_ready": "{renderer} valmis", + "render.scene_replaces": "Korvaa", + "render.scene_review": "Ratkaise ja tarkista", + "render.scene_review_help": "Tarkista koko alkuperäinen koostumus ennen käyttöönottoa. Sitomattomia edistyneitä SCENE-määrityksiä ei korvata.", + "render.scene_scope_details": "Koostumuksen laajuus", + "render.scene_stages": "Näyttämöt", + "render.search_appearances": "Hae {count} ulkoasusta", + "render.setup_legacy_environment": "Tämä vanhempi asetelma käyttää vanhaa ympäristön kiertoa tai voimakkuutta. Arvot säilytetään; muunna ne erikseen ennen täyden kuvatyön tallentamista.", + "render.setup_name": "Asetelman nimi", + "render.setup_numeric_help": "Tallennus kirjaa aktiivisen kuvamenetelmän ja kaikki sen numeeriset asetukset. Uudelleenlataus tai toisen asetelman valinta korvaa tämän luonnoksen; palauta kamera erikseen.", + "render.setup_offline_help": "Voit muokata ja tallentaa tämän menetelmän ilman sen renderöijää. Tarkista ja Aloita vaativat käytettävissä olevan isännän.", + "render.setup_runtime_unsupported": "Tätä täyttä työtä ei voi vielä tallentaa: se sisältää karttoja tai näkymän kappalesidontoja. Poista nämä väliaikaiset syötteet ennen siirrettävän asetelman tallentamista.", + "render.setup_save_missing": "Tallennettua renderöintikonfiguraatiota ei löytynyt komennon suorituksen jälkeen.", + "render.sharpening": "Yksityiskohtien terävöinti", + "render.shell_tab_appearance": "RENDERÖINNIN ULKOASU", + "render.shell_tab_camera": "RENDERÖINNIN KAMERA", + "render.shell_tab_lighting": "VALAISTUS", + "render.shell_tab_scene": "RENDERÖINNIN NÄKYMÄ", + "render.shot_aperture": "Aukko", + "render.shot_distance": "Etäisyys", + "render.shot_dof": "Syväterävyys", + "render.shot_duplicate": "Monista tallennettu kuvakulma", + "render.shot_edit_output": "Muokkaa tulosteessa", + "render.shot_exposure_reason": "Valotus vaatii CPU-säteenjäljityksen tai GPU-polunjäljityksen.", + "render.shot_exposure_section": "Valotus", + "render.shot_focus_distance": "Tarkennusetäisyys", + "render.shot_fov_reason": "Näkökenttä vaatii perspektiiviprojektion.", + "render.shot_frame_subject": "Rajaa kohde", + "render.shot_invalid_camera": "Kameran arvojen on oltava äärellisiä ja sallitulla alueella.", + "render.shot_lens": "Objektiivi", + "render.shot_lens_enable_reason": "Ota syväterävyys käyttöön muokataksesi aukkoa ja tarkennusetäisyyttä.", + "render.shot_lens_gpu_reason": "Syväterävyys vaatii GPU-polunjäljityksen.", + "render.shot_lens_perspective_reason": "Syväterävyys vaatii perspektiiviprojektion.", + "render.shot_look_selection": "Katso valintaa kohti", + "render.shot_manager": "Tallennetut kuvakulmat", + "render.shot_new_name": "Uuden kuvakulman nimi", + "render.shot_remove": "Poista tallennettu kuvakulma", + "render.shot_remove_help": "Poista vain tämä tallennettu asetelma. Lähdegeometria ja valmiit kuvat säilytetään; toiminnon voi kumota.", + "render.shot_remove_title": "Poistetaanko tallennettu kuvakulma?", + "render.shot_rename": "Nimeä tallennettu kuvakulma uudelleen", + "render.shot_saved_only": "Tallenna nykyinen luonnos ensin. Monistus ja uudelleennimeäminen säilyttävät tallennetut asetukset ja resurssiviittaukset täsmälleen.", + "render.shot_selection_reason": "Valitse kappale tai pinta, johon tähdätään.", + "render.shot_size": "Koko", + "render.shot_target": "Kohde", + "render.shots_camera_changed": "Kamera muuttunut kuvakulman tallennuksen jälkeen", + "render.shots_name_help": "Anna nykyiselle kuvakulmalle yksilöllinen nimi.", + "render.shots_no_result": "Ei vielä renderöintiä", + "render.shots_result": "Renderöinti {number} · {width} × {height}", + "render.shots_revert": "Palauta", + "render.shots_save": "Tallenna kuvakulma", + "render.shots_update": "Päivitä kuvakulma", + "render.show_shots_label": "Näytä kuvakulmanauha", + "render.size_4k": "4K", + "render.size_4k_uhd": "4K UHD", + "render.size_custom": "Mukautettu…", + "render.size_full_hd": "Full HD", + "render.size_hd": "HD", + "render.size_presets": "Kokoesiasetukset", + "render.size_presets_pending": "Tulee Tuloste-editorin mukana", + "render.size_preview": "Esikatselu", + "render.size_square": "Neliö", + "render.sky_ground": "Maa · lineaarinen RGB", + "render.sky_horizon": "Horisontti · lineaarinen RGB", + "render.sky_zenith": "Zeniitti · lineaarinen RGB", + "render.soft_focus": "Pehmeä tarkennus", + "render.spot_cone": "Spottivalon kartio", + "render.stage_frame": "Rajaa", + "render.stage_layout.appearance_note": "Ota käyttöön valintaan napsauttamalla.", + "render.stage_layout.studio_note": "Napsauta tarkistaaksesi ennen käyttöönottoa.", + "render.stage_light": "Valo", + "render.stage_look": "Ulkoasu", + "render.stage_orthographic": "Ortografinen", + "render.stage_output": "Tuloste", + "render.stage_panel_count": "Tallennetut paneelit", + "render.stage_panels.acknowledge": "Kuittaan korvaamisen ja rajoitukset", + "render.stage_panels.appearance_note": "Ota käyttöön valintaan napsauttamalla. Vedä malliin. Kun mitään ei ole valittu, napsautus aktivoi maalauksen.", + "render.stage_panels.apply": "Käytä", + "render.stage_panels.apply_studio": "Ota studio käyttöön", + "render.stage_panels.badge_blocked": "estetty", + "render.stage_panels.badge_native": "alkuperäinen", + "render.stage_panels.badge_projection": "projektio", + "render.stage_panels.badge_reference": "viite", + "render.stage_panels.badge_specification": "vain määritys", + "render.stage_panels.candidate_summary": "Ehdokkaat: {count} lähteistettyä arvoa. Laatu ja viimeistely vaativat tarkistuksen.", + "render.stage_panels.captured_bounds": "Käytä tallennettuja kohtauksen rajoja", + "render.stage_panels.centre": "Keskipiste", + "render.stage_panels.depth": "syvyys", + "render.stage_panels.environments": "Ympäristöt", + "render.stage_panels.extent": "Laajuus", + "render.stage_panels.fit_save": "Sovita ja tallenna", + "render.stage_panels.gpu_required": "Vaatii GPU-polunjäljityksen", + "render.stage_panels.keep": "Säilytä", + "render.stage_panels.kept": "Säilytetään", + "render.stage_panels.kept_fields": "Kamera, näytteistys, mitat, optiset sidonnat, CAD-geometria ja tekniset ominaisuudet.", + "render.stage_panels.kept_quality": "Menetelmä, kamera, valaistus, ympäristö, näyttämö, optiikka, valotus ja sävykartoitus.", + "render.stage_panels.mine": "Omat", + "render.stage_panels.mine_pending": "Omien studioiden tallentamista ei vielä tueta.", + "render.stage_panels.omits": "Jättää pois", + "render.stage_panels.paint_pending": "Maalausta ja vetämällä määrittämistä ei vielä tueta. Valitse kohde ulkoasun käyttöönottoa varten.", + "render.stage_panels.partial_reference": "Ehdokkaat: vain lähteistettyjä arvoja; tarkista laatu, kunto ja lähteet. Tuntemattomat arvot pysyvät tuntemattomina.", + "render.stage_panels.plane": "Taso", + "render.stage_panels.prepare_plan": "Valmistele luontisuunnitelma", + "render.stage_panels.projects": "Projektit", + "render.stage_panels.quality_ack": "Kuittaan kiinteän budjetin ja sen puutteet", + "render.stage_panels.quality_omissions": "Mukautuva pysäytys ja virhetavoitteet, erillinen läpäisysyvyys, venäläisen ruletin säännöt, lineaarinen raakatuloste, EXR-master ja konvergenssin sertifiointi.", + "render.stage_panels.reference": "Viite", + "render.stage_panels.references": "Viitteet", + "render.stage_panels.remove_optics": "Poista optiikka", + "render.stage_panels.remove_optics_help": "Poistaa tallennetun optiikan tästä kuvakulmasta. Lähdegeometria säilytetään.", + "render.stage_panels.remove_optics_title": "Poistetaanko tallennettu optiikka?", + "render.stage_panels.remove_shot": "Poista kuvakulma", + "render.stage_panels.remove_stage": "Poista näyttämö", + "render.stage_panels.remove_stage_help": "Poistaa tallennetut passiiviset paneelit tästä kuvakulmasta. Kameran tausta säilyy.", + "render.stage_panels.remove_stage_title": "Poistetaanko tallennettu näyttämö?", + "render.stage_panels.repeat": "Toista", + "render.stage_panels.replaces": "Korvaa", + "render.stage_panels.replaces_environment": "Ympäristö", + "render.stage_panels.replaces_maps": "Väliaikaiset kartat valitussa kappaleessa; tallennettu optiikka voi olla ristiriidassa.", + "render.stage_panels.replaces_physical": "Ei mitään. Tämä suunnitelma on vain luku -tilassa.", + "render.stage_panels.replaces_quality": "Kuvan mitat, kiinteät näytteet, polkusyvyys, siemen ja kohinanpoisto.", + "render.stage_panels.replaces_rig": "Valaistus, ympäristö ja näyttämö", + "render.stage_panels.replaces_saved_maps": "Tallennetut pintakartat valitussa kappaleessa; väliaikaiset ohitukset voivat olla ristiriidassa.", + "render.stage_panels.replaces_stage": "Tallennettu maa ja passiiviset näyttämöpaneelit", + "render.stage_panels.replaces_studio": "Valaistus, ympäristö, valotus ja näyttämö", + "render.stage_panels.replaces_uniform": "Läpinäkymätön ulkoasu valitussa kappaleessa. Spatiaaliset kartat arvioidaan tasaisilla arvoilla.", + "render.stage_panels.review_environment": "Tarkista ympäristö", + "render.stage_panels.review_maps": "Tarkista GPU-kartat", + "render.stage_panels.review_physical": "Fyysinen viitesuunnitelma", + "render.stage_panels.review_quality": "Käytä kiinteää näytteistysbudjettia", + "render.stage_panels.review_rig": "Sovita valoasetelma", + "render.stage_panels.review_saved_maps": "Tarkista tallennetut kartat", + "render.stage_panels.review_stage": "Tarkista maa ja näyttämö", + "render.stage_panels.review_studio": "Tarkista alkuperäinen studio", + "render.stage_panels.review_uniform": "Tarkista tasainen ulkoasu", + "render.stage_panels.rig_summary": "Laadittu valoasetelma · {emitters} säteilijää, {cards} korttia", + "render.stage_panels.rigs": "Valoasetelmat", + "render.stage_panels.save_maps": "Tallenna kartat tähän kuvakulmaan", + "render.stage_panels.scope": "Laajuus", + "render.stage_panels.search_studios": "Hae studioita", + "render.stage_panels.search_surfaces": "Hae pintoja ja viitteitä", + "render.stage_panels.source_note": "Laadittu perusvärin lähdekartta. Ei mitattu materiaali.", + "render.stage_panels.specifications": "Määritykset · vain luku", + "render.stage_panels.studio_ack": "Vahvista valaistuksen, ympäristön, valotuksen ja näyttämön korvaaminen", + "render.stage_panels.studio_note": "Napsauta tarkistaaksesi. Käyttöönotto korvaa valaistuksen, ympäristön ja näyttämön vasta vahvistuksesi jälkeen. Valot pysyvät muokattavina.", + "render.stage_panels.studios": "Studiot", + "render.stage_panels.subtitle_environment": "Alkuperäinen HDR-ympäristö · koko näkymä", + "render.stage_panels.subtitle_maps": "Laaditut spatiaaliset kartat · väliaikainen esikatselu", + "render.stage_panels.subtitle_physical": "Vain luku -suunnitelma · materiaalia ei luotu eikä määritetty", + "render.stage_panels.subtitle_quality": "Kiinteä GPU-budjetti · tulevat vaatimukset jätetty pois", + "render.stage_panels.subtitle_rig": "Laadittu valoasetelma · säteilijät ja passiiviset kortit", + "render.stage_panels.subtitle_saved_maps": "Laaditut kartat · tallennettu tämän kuvakulman kanssa", + "render.stage_panels.subtitle_stage": "Fyysinen maa ja näyttämö · sovitettu tuotteeseen", + "render.stage_panels.subtitle_studio": "Alkuperäinen studio · koskee koko näkymää", + "render.stage_panels.subtitle_uniform": "Tasainen likiarvo · ei mitattu materiaali", + "render.stage_panels.surfaces": "Pinnat", + "render.stage_panels.surfaces_references": "Pinnat ja viitteet", + "render.stage_panels.target": "Kohde", + "render.stage_panels.use_budget": "Käytä tätä budjettia", + "render.stage_panels.use_maps": "Käytä GPU-karttoja", + "render.stage_panels.use_uniform": "Käytä tasaista", + "render.stage_preview_note": "Integroitu esikatselu · suora valo", + "render.state_completed": "Valmis kuva", + "render.state_in_progress": "Kuva työn alla", + "render.state_model": "Mallin esikatselu", + "render.strip_label": "Nauha", + "render.studio_add_area": "Lisää aluevalo", + "render.studio_ambient": "Vakio ympäristön radianssi", + "render.studio_ambient_rgb": "Vakio ympäristön radianssi (lineaarinen RGB)", + "render.studio_aperture": "Aukon säde", + "render.studio_area": "Aluevalo", + "render.studio_area_help": "Enintään neljä yksipuolista suorakulmiota. Kohtisuorat puolisärmät U ja V määrittävät koon; U × V osoittaa valaistulle puolelle. Koordinaatit ovat maailman millimetreinä.", + "render.studio_center": "Keskipiste X, Y, Z (mm)", + "render.studio_denoise": "Vähennä kohinaa valmiissa kuvassa", + "render.studio_denoise_help": "Lopullinen reunat huomioiva suodatin; hienot yksityiskohdat voivat pehmentyä. Lasi ja terävät peilipinnat ohittavat suodattimen.", + "render.studio_direction": "Suunta aurinkoa kohti (X, Y, Z)", + "render.studio_environment": "Ympäristö", + "render.studio_environment_bounds": "Ympäristön kierron on oltava äärellinen välillä ±1 000 000 radiaania ja voimakkuuden välillä 0–100.", + "render.studio_environment_none": "Ei ympäristökarttaa", + "render.studio_focus": "Aksiaalinen tarkennusetäisyys", + "render.studio_half_u": "Puolisärmä U (mm)", + "render.studio_half_v": "Puolisärmä V (mm)", + "render.studio_hdr": "Radiance HDR -tiedosto", + "render.studio_hdr_browse": "Valitse HDR…", + "render.studio_hdr_help": "Radiance .hdr, 2:1-panoraama, enintään 2048 × 1024. EXR ei ole käytettävissä. Väri-oletus koskee vain tapauksia, joissa pääväriä ei ole määritetty.", + "render.studio_hdr_required": "Valitse paikallinen .hdr-tiedosto.", + "render.studio_hdr_srgb": "Tulkitse määrittämättömät päävärit lineaariseksi sRGB:ksi", + "render.studio_intensity": "Ympäristön voimakkuus", + "render.studio_lens": "Syväterävyys", + "render.studio_lens_perspective": "Syväterävyys vaatii perspektiivikameran.", + "render.studio_lighting": "Studiovalaistus", + "render.studio_lighting_enable": "Käytä mukautettua studiovalaistusta", + "render.studio_needs_review": "Tarkista menetelmä ja asetukset", + "render.studio_radiance": "Lineaarinen RGB-radianssi", + "render.studio_ready": "Valmis tarkistettavaksi", + "render.studio_remove_area": "Poista aluevalo", + "render.studio_rotation": "Ympäristön kierto", + "render.studio_runtime_help": "Numeeriset studioasetukset ja tarkistetut HDR-lähteet voi tallentaa asetelman mukana. Kappaleiden optiset/materiaaliohitukset pysyvät väliaikaisina eivätkä muuta tallennettuja ulkoasuja.", + "render.studio_saved": "Tallennettu asetelma / nykyinen kamera", + "render.studio_sky": "Taiteellinen taivas", + "render.studio_sky_help": "Alkuperäinen taivasliukuväri valaistukseen; ei kalibroitu ilmakehämalli.", + "render.studio_sun": "Aurinko", + "render.studio_sun_radius": "Kulmasäde", + "render.studio_tiles_require_gpu": "Studiot vaativat GPU-polunjäljityksen. Valitse GPU Tuloste-editorissa.", + "render.studio_title": "Renderöintistudio", + "render.studio_tone_map": "Sävykartoitus", + "render.studios_environments": "Studiot ja ympäristöt", + "render.subsurface_enable": "Sisäinen sironnan satunnaiskulku", + "render.subsurface_help": "Vain suljetut dielektriset kappaleet. Sironta ja RGB-absorptio ovat erillisiä mm-kohtaisia kertoimia. Polut siroavat todellisen geometrian sisällä ja taittuvat tai heijastuvat sitten rajapinnalla. Poista käytöstä suora varjojen läpäisy, pintojen kohinanpoisto ja ulkoinen tilavuus; käytä yhtä Fresnel-kerrosta. Ei diffuusiovarjostin, tiheysruudukko eikä mitattu materiaali. Tiheät väliaineet voivat vaatia enemmän näytteitä ja polkusyvyyttä.", + "render.subsurface_rate": "Sironnan törmäystaajuus", + "render.tone_aces_fitted": "ACES fitted", + "render.tone_reinhard": "Reinhard", + "render.transmission_scope": "GPU-lasi tukee sertifioituja erillisiä väliaineita. Rajoittamattomia sisäkkäisiä väliaineita ja kohinatonta läpäisyestimaattoria ei tarjota.", + "render.transmission_strata": "Ehdolliset Fresnel-kerrokset", + "render.transmission_strata_help": "1 säilyttää alkuperäisen virran. 2 tai 4 alipolkua kerrostavat ensimmäisen lasin heijastus-/läpäisyvalinnan muuttamatta Snellin ja absorption lakeja. Useampi polku vaatii enemmän työtä; tämä ei ole kohinanpoisto, sisäkkäisten väliaineiden tuki eikä lupaus nopeammasta renderöinnistä.", + "render.tree_add_light": "Lisää valo", + "render.tree_add_shot": "Lisää kuvakulma", + "render.tree_browser": "Renderöintiselain", + "render.tree_by_look": "Ulkoasun mukaan", + "render.tree_by_object": "Objektin mukaan", + "render.tree_constant": "Vakioympäristö", + "render.tree_default": "Oletus", + "render.tree_directional": "Suuntavalo", + "render.tree_environment": "Ympäristö", + "render.tree_environment_values": "{rotation}° · {intensity}×", + "render.tree_face_count": "{count} pintaa", + "render.tree_face_one": "{count} pinta", + "render.tree_fixed_studio": "Kiinteä studio", + "render.tree_hdr": "HDR", + "render.tree_lights": "Valot", + "render.tree_lights_pending": "Nimettyjen valojen komennot eivät ole vielä käytettävissä.", + "render.tree_mixed": "Sekalainen", + "render.tree_more": "{count} lisää", + "render.tree_mute": "Mykistä valo", + "render.tree_no_environment": "Ei ympäristöä", + "render.tree_objects": "Objektit", + "render.tree_output": "Tuloste", + "render.tree_point": "Pistevalo", + "render.tree_rectangle": "Suorakulmio", + "render.tree_search": "Hae objekteja", + "render.tree_selection": "Renderöinnin valinta", + "render.tree_shots": "Kuvakulmat", + "render.tree_sky": "Taivas", + "render.tree_solo": "Vain tämä valo", + "render.tree_spot": "Kohdevalo", + "render.tree_sun": "Aurinko", + "render.tree_switch": "Vaihda", + "render.tree_user_one": "{count} objekti", + "render.tree_users": "{count} objektia", + "render.unavailable_preview": "Tämä asetelma pyytää esikatseluprofiilia, joka ei ole käytettävissä.", + "render.unsaved": "Tallentamattomia esikatselumuutoksia", + "render.use_preview": "Käytä integroitua esikatselua", + "render.volume_albedo": "Sironta-albedo · lineaarinen RGB", + "render.volume_anisotropy": "Vaihefunktion keskikosini", + "render.volume_enable": "Ota osallistuva väliaine käyttöön", + "render.volume_extinction": "Ekstinktiokerroin", + "render.volume_help": "GPU-kuljetus yhden rajallisen laatikon sisällä Beerin vaimennuksella ja HG-sironnalla kamera- ja epäsuorilla poluilla. Käyttää nimenomaista studio-/HDR-/taivasvalaistusta, myös varjojen vaimennusta. Positiivinen vaihekosini sirottaa eteenpäin. Lasirajapinnat ja pintojen kohinanpoisto on poistettava käytöstä erikseen. Nolla-ekstinktio jättää kuljetuksen ennalleen. Ei fyysinen kuun ilmakehä, tiheysruudukko, tilavuussäteily, spektrikuljetus eikä sertifioitu materiaaliominaisuus.", + "render.volume_max": "Enimmäisrajat · maailman mm", + "render.volume_min": "Vähimmäisrajat · maailman mm", + "render.volume_title": "Rajattu homogeeninen tilavuus", + "render.wait_add_light": "ei vielä tuettu: nimettyjen valojen luonti", + "render.wait_batch": "ei vielä tuettu: tallennettujen kuvakulmien renderöintijono", + "render.wait_compare": "ei vielä tuettu: säilytettyjen kuvien vertailu", + "render.wait_paint": "ei vielä tuettu: tuotteen valinta ja ulkoasun maalaus", + "render.wait_pick_up": "ei vielä tuettu: tuotteen valinta ja ulkoasun näytteistys", + "render.wait_replace": "ei vielä tuettu: ulkoasun kaikkien käyttökertojen korvaaminen", + "render.wait_solo": "ei vielä tuettu: valojen näkyvyys- ja soolosäätimet", + "render.wear_applies_to": "Koskee", + "render.wear_layer_count": "{count} kerrosta", + "render.wear_layer_one": "{count} kerros", + "render.wear_layers": "Kerrokset", + "render.wear_no_layers": "Ei kerroksia", + "render.wear_selected_layer": "Valittu kerros", + "render.wear_title": "Kuluminen", + "sample.bracket.about": "Pohjalaippa, jossa reunalaipat ja huulos 2 mm:n säännöllä", + "sample.bracket.name": "Ohutlevykiinnike", + "sample.enclosure.about": "Kuorittu laatikko, jossa huuli, ruuvitornit, tuki ja napsautusliitos", + "sample.enclosure.name": "Muovikotelo", + "sample.flange.about": "Napa ja laippa, jossa parametrilla ohjattu ympyräkuvio", + "sample.flange.name": "Pultattu laippa", + "sample.hinge.about": "Kaksi komponenttia ja kiertonivel, ohjattu 60°:seen", + "sample.hinge.name": "Saranakokoonpano", + "sample.plate.about": "Parametrinen levy, jossa pyöristykset, reiät ja porattu tappi", + "sample.plate.name": "Esimerkkilevy", + "sample.vents.about": "Urat suorakulmaisessa kuviossa: rivit, sarakkeet ja jako ovat parametreja", + "sample.vents.name": "Tuuletuslevy", + "search.command_keys": "Enter suorita Shift+Enter suorita ja pidä auki Esc sulje", + "search.commands": "Komennot", + "search.design": "Tässä mallissa", + "search.feature": "Piirre", + "search.invalid": "Ei kelvollinen", + "search.keys": "↑ ↓ valitse Enter suorita Tab täydennä nimi Esc sulje", + "search.no_match": "Mikään komento ei vastaa hakua '{query}'", + "search.parameter": "Parametri", + "search.recent": "Viimeisimmät", + "search.run": "Suorita komento", + "search.suggest": "Tarkoititko {label}?", + "search.try": "Kirjoita komennon nimi, tämän mallin piirre tai parametri. Jos haluat suorittaa komennon arvoilla, kirjoita sen tunnus ja JSON-olio: {example}", + "search.valid": "Kelvollinen", + "section.off_hint": "Tasoa ei valittu: OK poistaa leikkauksen käytöstä.", + "select a direction (an axis, a sketch line or a straight edge) first": "valitse ensin suunta (akseli, luonnosviiva tai suora särmä)", + "select a direction (an axis, a sketch line or a straight edge) for the profile to follow": "valitse suunta (akseli, luonnosviiva tai suora särmä), jota profiili seuraa", + "select a point on a component": "valitse piste komponentista", + "select a profile, edges or sketch lines first": "valitse ensin profiili, särmät tai luonnosviivat", + "select an axis": "valitse akseli", + "select an axis, a straight or circular edge, or a cylinder, cone or torus face first": "valitse ensin akseli, suora tai ympyränmuotoinen särmä tai sylinteri-, kartio- tai toruspinta", + "select bodies first": "valitse ensin kappaleet", + "select components first": "valitse ensin komponentit", + "select corner points, or the two lines of one corner": "valitse kulmapisteet tai yhden kulman kaksi viivaa", + "select one corner point, or the two lines of one corner": "valitse yksi kulmapiste tai yhden kulman kaksi viivaa", + "select sheet edges first": "valitse ensin levyn särmät", + "select the bend line (a sketch line) first": "valitse ensin taivutusviiva (luonnosviiva)", + "select the cam's profile (a sketch profile or the cam's edges)": "valitse nokan profiili (luonnosprofiili tai nokan särmät)", + "select the corner to cut first": "valitse ensin leikattava kulma", + "select the corners to round first": "valitse ensin pyöristettävät kulmat", + "select the fixed face first (a plate's large face)": "valitse ensin kiinteä pinta (levyn suuri pinta)", + "select the frame sketch's lines first": "valitse ensin runkoluonnoksen viivat", + "select the path (sketch lines across the edge)": "valitse polku (särmän yli kulkevat luonnosviivat)", + "select the rim face first": "valitse ensin reunapinta", + "select the sheet edge first": "valitse ensin levyn särmä", + "select two components": "valitse kaksi komponenttia", + "set by the sketch's lines": "luonnoksen viivojen määräämä", + "settings.display_quality_note": "Vain näyttö. Malleihin ja vienteihin tämä ei vaikuta.", + "settings.double_click_components": "Aktivoi komponentti kaksoisnapsauttamalla tai muokkaa linkitettyä komponenttia paikallaan", + "settings.frame_rate_details_note": "Lisää kaavion viimeisimpien kehysten ajoista ja niiden päälle piirrettyjen kolmioiden määrästä, kehysaikojen histogrammin sekä tiedot siitä, mitä GPU piirsi. Näytä tai piilota ne napsauttamalla näkymän kehysnopeutta.", + "settings.frame_rate_note": "Näyttää kehysnopeuden (kehystä sekunnissa) näkymän oikeassa alakulmassa.", + "settings.insert_lists_open_designs": "Lisää malli -luettelo näyttää ensin muissa välilehdissä avoinna olevat mallit", + "settings.measure_axis_distances": "Näytä X/Y/Z-etäisyydet", + "settings.measure_axis_distances_help": "Näytä maailman akselien suuntaiset komponenttimitat kokonaisetäisyyden rinnalla, kun Mittaa on auki.", + "settings.msaa_applies_on_restart": "Reunanpehmennys tulee voimaan, kun SolidCraft käynnistetään seuraavan kerran", + "settings.msaa_reset": "{setting}: {requested}× ei ole tämän näytönohjaimen tukema; asetus on nyt {reset}× (tuetut: {supported}).", + "settings.msaa_unsupported": "Tämä näytönohjain ei tue", + "settings.reference_geometry_through_bodies": "Näytä apugeometria kappaleiden läpi", + "settings.reference_geometry_through_bodies_help": "Piirrä passiivisten luonnosten ääriviivat ja aputasot varjostettujen kappaleiden päälle", + "settings.reset_intro": "Nämä asetukset eivät toimi tällä tietokoneella ja estäisivät SolidCraftin käynnistymisen, joten niitä muutettiin:", + "settings.reset_title": "Asetuksia muutettiin", + "settings.supersampling_note": "Piirtää näkymän suuremmalla resoluutiolla ja suodattaa sen alas: tasaisemmat särmät, viivat ja ruudukko alle 4K-näytöillä. Se kuluttaa GPU-aikaa: noin 2,25× pikseleitä kertoimella 1,5× ja 4× kertoimella 2×.", + "settings.update_changed_links": "Päivitä muuttuneet linkitetyt mallit, kun välilehdelle palataan", + "settings.window_system_details": "Tiedot", + "settings.window_system_note_now": "Tulee voimaan uudelleenkäynnistyksen jälkeen. Nyt: {now}.", + "settings.window_system_wayland_limited": "Osa ominaisuuksista on rajoitettu natiivissa Waylandissa.", + "sheet.flange_type_base": "Pohja", + "sheet.flange_type_contour": "Ääriviiva", + "sheet.flange_type_edge": "Särmä", + "sheet.no_body": "ohutlevykappaletta ei ole: aloita sellainen komennolla Laippa > Pohja tai muuta levy ohutlevyksi komennolla Muunna ohutlevyksi (valitse sen suuri tasopinta)", + "sheet.personal_rules.confirm_delete": "Vahvista poisto", + "sheet.personal_rules.delete": "Poista", + "sheet.personal_rules.delete_prompt": "Poistetaanko tämä henkilökohtainen sääntö? Malleissa jo olevat säännöt eivät muutu.", + "sheet.personal_rules.full": "Henkilökohtaisessa kirjastossa on jo 64 sääntöä.", + "sheet.personal_rules.invalid_name": "Anna lyhyt nimi ilman rivinvaihtoja tai ohjausmerkkejä.", + "sheet.personal_rules.invalid_values": "Täydennä säännön arvot: jokaisen on toimittava tässä mallissa, paksuuden on oltava positiivinen ja K-kertoimen välillä 0–1.", + "sheet.personal_rules.missing": "Valittu henkilökohtainen sääntö ei ole enää käytettävissä.", + "sheet.personal_rules.name": "Säännön nimi", + "sheet.personal_rules.name_exists": "Samanniminen henkilökohtainen sääntö on jo olemassa. Käytä eri nimeä.", + "sheet.personal_rules.name_hint": "Yksilöllinen nimi", + "sheet.personal_rules.overwrite": "Tallenna muutokset valittuun henkilökohtaiseen sääntöön", + "sheet.personal_rules.rename": "Nimeä uudelleen", + "sheet.personal_rules.rule": "Henkilökohtainen sääntö", + "sheet.personal_rules.save": "Tallenna uutena", + "sheet.personal_rules.scope": "Tallennettu profiiliisi kaikkia malleja varten.", + "sheet.personal_rules.select": "Valitse sääntö", + "sheet.personal_rules.title": "Henkilökohtaiset säännöt", + "sheet.personal_rules.unsupported": "Säännössä on arvoja, joita tämä versio ei voi käyttää.", + "shortcut.json_error": "parametrien on oltava JSONia: {error}", + "shortcut.no_command": "komentoa `{id}` ei ole; JSONia edeltävän tekstin on oltava komennon tunnus", + "shortcut.pin": "Kiinnitä S-ruudun ylälaitaan", + "shortcut.unpin": "Irrota", + "sketch is missing": "luonnos puuttuu", + "sketch.degrees_of_freedom": "{count} vapausastetta", + "sketch.dimension_added_driven": "Luonnos määrää jo tämän mitan, joten se lisättiin ohjattuna (viite)mittana", + "sketch.dimension_applied": "Mitta lisätty", + "sketch.dimension_applied_defined": "Mitta lisätty; parametri `{name}` määritelty", + "sketch.dimension_applied_renamed": "Mitta lisätty; parametrin nimi `{name}`", + "sketch.dof_left": "{count} vapausastetta jäljellä", + "sketch.dof_left_one": "{count} vapausaste jäljellä", + "sketch.draw_curves": "Piirrä tyypillä {linetype}", + "sketch.make_selection": "Muunna valinta tyypiksi {linetype}", + "sketch.open_ends": "Avoimia {count}", + "sketch.status_conflict": "rajoitteet ovat ristiriidassa", + "sketch.status_fully_constrained": "täysin rajoitettu", + "sketch.untied_ends": "Irrallisia {count}", + "sketch_panel.attached": "Kiinnitetty: {body} / {path}", + "sketch_panel.author": "Laatijan sijoittelu: {path}", + "sketch_panel.dimension_hint": "Anna arvo tai lauseke ja paina OK.", + "sketch_panel.move_hint": "Anna etäisyydet ja kulma ja paina OK.", + "sketch_panel.plane_angle": "{plane}, käännetty kulmaan {angle}", + "sketch_panel.plane_fixed": "Kiinteä taso", + "sketch_panel.plane_flipped": "{plane}, sen toiselta puolelta", + "sketch_panel.plane_offset": "{plane}, siirtymä {distance}", + "sketch_panel.plane_origin": "Taso {plane}", + "sketch_panel.redefine_title": "{command}: {name}", + "sketch_panel.sheet_attachment": "Kiinnitetty ohutlevykappaleen tasopintaan; seuraa kyseistä paneelia, kun levy muuttuu.", + "sketch_panel.text_hint": "Muokkaa tekstiä ja sen sijoittelua ja paina OK.", + "sketch_panel.use_plane": "Käytä tasoa {plane}", + "sketch_text.align_center": "Keskitetty", + "sketch_text.align_left": "Vasen", + "sketch_text.align_right": "Oikea", + "sketch_text.bold": "Lihavoitu", + "sketch_text.builtin_font": "{family} (sisäinen)", + "sketch_text.italic": "Kursivoitu", + "sketch_text.loading_fonts": "Etsitään asennettuja fontteja…", + "sketch_text.on_path": "Teksti seuraa polkuaan: käyrä sijoittaa sen", + "sketch_text.path_clear": "Irrota teksti käyrältään", + "sketch_text.path_hint": "Luonnoksen käyrä, jota teksti seuraa: napsauta tätä ja sitten käyrää", + "sketch_text.use_font_file": "Käytä fonttitiedostoa {path}", + "solid": "yhtenäinen", + "status.editing": "Muokataan: {name}", + "status.navigation": "Hiiren toiminnot: {mapping}", + "status.navigation_tip": "Miten hiiri liikuttaa näkymää. Valitse toinen määritys napsauttamalla", + "status.under_constrained": "Alimääritelty ({count} vapausastetta)", + "status.under_constrained_one": "Alimääritelty ({count} vapausaste)", + "status.units_tip": "Mallin yksiköt. Muuta niitä napsauttamalla", + "the angle must be a number": "kulman on oltava luku", + "the curves must be in one sketch": "käyrien on oltava samassa luonnoksessa", + "the direction must be an axis, a sketch line or a straight edge": "suunnan on oltava akseli, luonnosviiva tai suora särmä", + "the duration must be a number of seconds, 0.001 or more": "keston on oltava sekunteina annettu luku, vähintään 0.001", + "the line's sketch is gone": "viivan luonnos on poistunut", + "the lines must be in one sketch": "viivojen on oltava samassa luonnoksessa", + "the lines must be in one sketch, not the section's": "viivojen on oltava samassa luonnoksessa, ei leikkauksen luonnoksessa", + "the parts library is empty": "osakirjasto on tyhjä", + "the parts library is not available": "osakirjasto ei ole käytettävissä", + "the path curves must be in one other sketch": "polkukäyrien on oltava yhdessä toisessa luonnoksessa", + "the path's sketch is gone": "polun luonnos on poistunut", + "the position must be a number": "sijainnin on oltava luku", + "the preview failed": "esikatselu epäonnistui", + "the profiles and curves must be in one sketch": "profiilien ja käyrien on oltava samassa luonnoksessa", + "the reference face must be on the edges' body": "viitepinnan on oltava särmien kappaleessa", + "the scale must be above 0": "mittakaavan on oltava suurempi kuin 0", + "the section's profiles must be in one sketch": "poikkileikkauksen profiilien on oltava samassa luonnoksessa", + "the two origins are on the same component": "molemmat origot ovat samassa komponentissa", + "thread.automatic_size": "Automaattinen koko", + "thread.designation": "Merkintä", + "thread.iso_metric": "ISO-metrinen", + "thread.select_size": "Valitse koko", + "timeline.delete_after_marker_one": "Poista 1 piirre historiamerkin jälkeen", + "timeline.delete_after_marker_other": "Poista {count} piirrettä historiamerkin jälkeen", + "timeline.delete_folders_tip": "Säilytä niiden piirteet ja sisäkkäiset kansiot historiassa", + "timeline.delete_folders_with_features_tip": "Poista kansiot kaikkine niiden piirteineen ja sisäkkäisine kansioineen", + "timeline.delete_many": "Poista {count} valittua piirrettä", + "timeline.edited_rolled_back": "{name} muuttui, mutta se on historiamerkin jälkeen, joten sitä ei rakenneta: siirrä merkki sen ohi nähdäksesi tuloksen", + "timeline.feature_error": "Virhe: {message}", + "timeline.feature_hint": "Kaksoisnapsauta muokataksesi · vedä järjestääksesi · napsauta hiiren kakkospainikkeella lisää", + "timeline.feature_rolled_back": "Palautettu: historiamerkin jälkeen, joten ei rakennettu", + "timeline.feature_warning": "Varoitus: {message}", + "timeline.group": "Uusi piirrekansio", + "timeline.move_many": "Siirrä aikajanan kohteita", + "timeline.move_to_group": "Siirrä piirteet kansioon", + "timeline.rename_group": "Nimeä piirrekansio uudelleen", + "timeline.reorder_many": "Järjestä piirteet uudelleen", + "timeline.suppress_features": "Ohita piirteet", + "timeline.suppress_folders_tip": "Ohita tai palauta käyttöön kaikki kansioiden ja niiden sisäkkäisten kansioiden piirteet", + "timeline.ungroup": "Poista piirrekansiot", + "timeline.unsuppress_features": "Palauta piirteet käyttöön", + "to the face": "pintaan", + "to the next face": "seuraavaan pintaan", + "toolbar.customize_note": "Välilehti {tab}. Rastita komento antaaksesi sille työkalurivin painikkeen. Voit myös vetää paneelin pudotusvalikon rivin työkaluriville, vetää painikkeen pois työkaluriviltä poistaaksesi sen tai käyttää pudotusvalikon rivin kiinnitysnastaa.", + "toolbar.image": "KUVA", + "toolbar.render": "RENDERÖINTI", + "toolbar.render_appearance": "ULKOASU", + "toolbar.render_camera": "KAMERA", + "toolbar.render_environment": "YMPÄRISTÖ", + "toolbar.render_lighting": "VALAISTUS", + "toolbar.render_lights": "VALOT", + "toolbar.render_result": "TULOS", + "toolbar.render_scene": "NÄKYMÄ", + "toolbar.render_stage": "NÄYTTÄMÖ", + "toolbar.render_studio": "STUDIO", + "trace.points": "{count} pistettä polkua pitkin", + "trace.stopped_by_contact": "Päättyy näytteeseen {sample}: {a} kulkisi kohteen {b} läpi", + "trace.stopped_by_loop": "Päättyy näytteeseen {sample}: nivelen {joint} kautta kulkeva silmukka ei voi sulkeutua enempää", + "trim by sketch curves, or by one plane or face": "katkaise luonnoskäyrillä tai yhdellä tasolla tai pinnalla", + "ui.1_degree_of_freedom": "1 vapausaste", + "ui.3d_mouse_axes_reassigned": "Akselit on määritetty uudelleen asetuksissa, ja se pätee edelleen tämän kalibroinnin päälle.", + "ui.3d_mouse_button": "Painike {number}", + "ui.3d_mouse_button_nothing": "Ei mitään", + "ui.3d_mouse_button_settings": "3D-hiiren asetukset", + "ui.3d_mouse_buttons": "Painikkeet", + "ui.3d_mouse_buttons_hint": "Paina 3D-hiiren painiketta löytääksesi sen tästä ja valitse sitten, mitä se tekee.", + "ui.3d_mouse_buttons_no_device": "Liitä 3D-hiiri, jotta voit määrittää sen painikkeiden toiminnot.", + "ui.3d_mouse_buttons_reset": "Palauta oletuspainikkeet", + "ui.3d_mouse_calibrate": "Kalibroi…", + "ui.3d_mouse_calibrate_tip": "Liikuta nuppia ikkunan ohjeiden mukaan, jotta SolidCraft oppii, mihin suuntaan ja kuinka pitkälle tämän 3D-hiiren kukin akseli liikkuu. Tallennetaan tälle 3D-hiirelle.", + "ui.3d_mouse_calibrate_title": "Kalibroi 3D-hiiri", + "ui.3d_mouse_calibrate_wait": "Liikuta 3D-hiirtä kerran, jotta SolidCraft havaitsee sen.", + "ui.3d_mouse_calibrated": "Kalibroitu", + "ui.3d_mouse_calibration": "Kalibrointi", + "ui.3d_mouse_calibration_done": "Valmis. Tallenna se, niin sitä käytetään aina, kun tämä 3D-hiiri on liitettynä.", + "ui.3d_mouse_calibration_no_response": "Yksi akseli liikkui tuskin lainkaan, joten sitä ei voi kalibroida. Aloita alusta ja liikuta nuppia joka kerta pidemmälle.", + "ui.3d_mouse_circles_help": "Ympyrät näyttävät, mitä laite lähettää kalibroinnin jälkeen. Testimalli näyttää, mitä näkymä tekee sillä käännön, nopeuden ja akselimäärityksen jälkeen.", + "ui.3d_mouse_dead_zone": "Kuollut alue", + "ui.3d_mouse_dead_zone_tip": "Kuinka paljon nupin on liikuttava ennen kuin näkymä liikkuu, osuutena sen koko liikealueesta. Suurenna arvoa, jos näkymä ajelehtii nupin ollessa levossa.", + "ui.3d_mouse_denied": "SolidCraft havaitsee 3D-hiiren, mutta sillä ei ole lupaa lukea sitä. Katso udev-sääntö 3D-hiiren asennusohjeista.", + "ui.3d_mouse_denied_short": "Löytyi, mutta ei luettavissa", + "ui.3d_mouse_driven_by": "Mikä laitteen kalibroitu liike ohjaa tätä akselia. Jos valitset liikkeen, jota toinen akseli jo käyttää, ne vaihtavat paikkaa.", + "ui.3d_mouse_driven_by_label": "ohjaa", + "ui.3d_mouse_driver": "Ajuri", + "ui.3d_mouse_driver_auto": "Automaattinen", + "ui.3d_mouse_driver_direct": "Suora (hidraw)", + "ui.3d_mouse_driver_fallback": "Luetaan toistaiseksi spacenavd:n kautta: itse laitetta ei voitu avata.", + "ui.3d_mouse_driver_only_direct": "Laite luetaan suoraan; spacenavd ei ole käynnissä", + "ui.3d_mouse_driver_only_spacenavd": "Luetaan spacenavd:n kautta, ainoa käytettävissä oleva tapa", + "ui.3d_mouse_forget": "Unohda kalibrointi", + "ui.3d_mouse_ghost_left_viewport": "Vasen näkymäikkuna", + "ui.3d_mouse_ghost_left_window": "Vasen ikkuna", + "ui.3d_mouse_ghost_position": "Sijainti", + "ui.3d_mouse_ghost_right_viewport": "Oikea näkymäikkuna", + "ui.3d_mouse_hint": "Siirrä ja kierrä näkymää samanaikaisesti; luonnoksissa vain panorointi ja zoomaus.", + "ui.3d_mouse_kind_cap": "Palautuu keskelle", + "ui.3d_mouse_kind_question": "Millainen 3D-hiiri on kyseessä?", + "ui.3d_mouse_kind_trackball": "Ohjauspallo", + "ui.3d_mouse_looks_like_cap": "Lukema pysyy paikallaan, kun pidät otetta, kuten keskelle palautuvassa laitteessa.", + "ui.3d_mouse_looks_like_trackball": "Lukema palautuu heti, kun lopetat liikuttamisen, kuten ohjauspallossa.", + "ui.3d_mouse_motion_rotation_x": "Kierto X", + "ui.3d_mouse_motion_rotation_y": "Kierto Y", + "ui.3d_mouse_motion_rotation_z": "Kierto Z", + "ui.3d_mouse_motion_translation_x": "Siirto X", + "ui.3d_mouse_motion_translation_y": "Siirto Y", + "ui.3d_mouse_motion_translation_z": "Siirto Z", + "ui.3d_mouse_navigate": "Liiku 3D-hiirellä", + "ui.3d_mouse_none": "3D-hiirtä ei löytynyt", + "ui.3d_mouse_not_calibrated": "Ei kalibroitu", + "ui.3d_mouse_offer": "3D-hiiren kalibrointi korjaa vaihtuneet tai käänteiset akselit ja asettaa sen nopeuden ja tuntuman.", + "ui.3d_mouse_offer_never": "Älä näytä enää", + "ui.3d_mouse_offer_swap": "Vaihda hidraw-ajuriin (suora ajuri)", + "ui.3d_mouse_orbit": "Kiertoliike", + "ui.3d_mouse_orbit_classic": "Perinteinen", + "ui.3d_mouse_orbit_tip": "Jäljitetty: 3D-hiiri kiertää näkymää sen mallin kohdan ympäri, joka on näkymän keskellä kierron alkaessa, merkittynä himmeällä pallolla. Perinteinen: näkymän keskipisteen ympäri", + "ui.3d_mouse_orbit_traced": "Jäljitetty", + "ui.3d_mouse_reading": "Lukema", + "ui.3d_mouse_reset_axes": "Nollaa akselimääritys", + "ui.3d_mouse_reset_view": "Nollaa näkymä", + "ui.3d_mouse_restore": "Palauta 3D-hiiren oletukset", + "ui.3d_mouse_restore_ask": "Palautetaanko 3D-hiiren asetukset oletuksiin? Kalibrointi ja painikemääritykset säilyvät.", + "ui.3d_mouse_section": "3D-hiiri", + "ui.3d_mouse_show_in_view": "Näytä 3D-hiiri 3D-näkymässä", + "ui.3d_mouse_show_in_view_tip": "Kuva 3D-hiirestäsi vasemmassa alakulmassa, liikkuu kun liikutat hiirtä.", + "ui.3d_mouse_skip": "Laitteeni ei pysty tähän", + "ui.3d_mouse_skip_tip": "Ohittaa tämän liikkeen molempiin suuntiin, ja kalibrointi jättää sen pois.", + "ui.3d_mouse_speed": "3D-hiiren nopeus", + "ui.3d_mouse_step_lift": "Nosta nuppia ylös, pidä ja päästä sitten irti.", + "ui.3d_mouse_step_press": "Paina nuppia alas, pidä ja päästä sitten irti.", + "ui.3d_mouse_step_pull": "Vedä nuppia itseäsi kohti, pidä ja päästä sitten irti.", + "ui.3d_mouse_step_push": "Työnnä nuppia itsestäsi poispäin, pidä ja päästä sitten irti.", + "ui.3d_mouse_step_rest": "Ota käsi pois nupilta ja anna sen olla paikallaan.", + "ui.3d_mouse_step_rest_trackball": "Ota käsi pois pallolta ja anna sen olla paikallaan.", + "ui.3d_mouse_step_ring_clockwise": "Käännä vierityskehää myötäpäivään muutama napsaus.", + "ui.3d_mouse_step_ring_counterclockwise": "Käännä vierityskehää vastapäivään muutama napsaus.", + "ui.3d_mouse_step_roll_away": "Pyöritä palloa itsestäsi poispäin muutaman kerran ja anna sen sitten pysähtyä.", + "ui.3d_mouse_step_roll_left": "Pyöritä palloa vasemmalle muutaman kerran ja anna sen sitten pysähtyä.", + "ui.3d_mouse_step_roll_right": "Pyöritä palloa oikealle muutaman kerran ja anna sen sitten pysähtyä.", + "ui.3d_mouse_step_roll_toward": "Pyöritä palloa itseäsi kohti muutaman kerran ja anna sen sitten pysähtyä.", + "ui.3d_mouse_step_slide_left": "Liu'uta nuppia vasemmalle, pidä ja päästä sitten irti.", + "ui.3d_mouse_step_slide_right": "Liu'uta nuppia oikealle, pidä ja päästä sitten irti.", + "ui.3d_mouse_step_spin_clockwise": "Kierrä palloa myötäpäivään muutaman kerran ja anna sen sitten pysähtyä.", + "ui.3d_mouse_step_spin_counterclockwise": "Kierrä palloa vastapäivään muutaman kerran ja anna sen sitten pysähtyä.", + "ui.3d_mouse_step_tilt_away": "Kallista nupin yläosaa itsestäsi poispäin (lähin reuna nousee), pidä ja päästä sitten irti.", + "ui.3d_mouse_step_tilt_left": "Kallista nuppia vasemmalle (vasen reuna alas), pidä ja päästä sitten irti.", + "ui.3d_mouse_step_tilt_right": "Kallista nuppia oikealle (oikea reuna alas), pidä ja päästä sitten irti.", + "ui.3d_mouse_step_tilt_toward": "Kallista nupin yläosaa itseäsi kohti (lähin reuna laskee), pidä ja päästä sitten irti.", + "ui.3d_mouse_step_touch": "Lepuuta kättäsi nupilla painamatta sitä.", + "ui.3d_mouse_step_twist_clockwise": "Kierrä nuppia myötäpäivään, pidä ja päästä sitten irti.", + "ui.3d_mouse_step_twist_counterclockwise": "Kierrä nuppia vastapäivään, pidä ja päästä sitten irti.", + "ui.3d_mouse_switch_cap": "Kalibroi keskelle palautuvana", + "ui.3d_mouse_switch_trackball": "Kalibroi ohjauspallona", + "ui.3d_mouse_use_direct": "Käytä suoraa ajuria", + "ui.3d_mouse_use_direct_tip": "Lue 3D-hiirtä suoraan (hidraw) spacenavd:n sijaan.", + "ui.3d_mouse_view_axis": "Näkymän akseli", + "ui.3d_mouse_view_off": "Pois", + "ui.3d_mouse_view_off_tip": "3D-hiiren ajurin profiili poistaa tämän akselin käytöstä, joten sen liike ei liikuta näkymää. Jos valitset tähän toisen akselin liikkeen, ne vaihtavat paikkaa, ja se liike lakkaa liikuttamasta näkymää.", + "ui.3d_mouse_view_orbit_sideways": "Kierto Y", + "ui.3d_mouse_view_orbit_up_down": "Kierto X", + "ui.3d_mouse_view_pan_sideways": "Panorointi X", + "ui.3d_mouse_view_pan_up_down": "Panorointi Y", + "ui.3d_mouse_view_roll": "Kallistus", + "ui.3d_mouse_view_unmapped": "Akseli {n}", + "ui.3d_mouse_view_zoom": "Zoomaus", + "ui.3d_mouse_waiting": "Odotetaan liikettä", + "ui.3d_mouse_wiggle": "Jos sellainen on liitettynä, heiluttele sitä.", + "ui.3d_sketch": "3D-luonnos", + "ui.activate": "Aktivoi", + "ui.active_component": "Aktiivinen komponentti", + "ui.add_configuration": "Lisää konfiguraatio", + "ui.add_parameter": "Lisää parametri", + "ui.agent_chat": "Agenttikeskustelu", + "ui.agent_chat_add": "Liitä tiedostoja", + "ui.agent_chat_add_file": "Valitse tiedosto…", + "ui.agent_chat_allow": "Salli", + "ui.agent_chat_allow_once": "Salli kerran", + "ui.agent_chat_allowed": "Sallittu", + "ui.agent_chat_answered": "Vastaus: {option}", + "ui.agent_chat_approval": "Sallitaanko agentin tehdä tämä?", + "ui.agent_chat_attach_selection": "Liitä valinta", + "ui.agent_chat_attach_selection_tip": "Lähetä mallista valitut kohteet (pinnat, särmät, piirteet, kappaleet) viestin mukana, jotta agentti tietää, mitä tarkoitat", + "ui.agent_chat_attach_view": "Liitä näkymä", + "ui.agent_chat_attach_view_tip": "Lähetä kuva nykyisestä näkymästä viestin mukana", + "ui.agent_chat_attachable": "Kuvat, PDF:t, teksti- ja CAD-tiedostot", + "ui.agent_chat_auth_agent": "Kirjaudu palvelulla {name}", + "ui.agent_chat_auth_env": "Aseta {vars} ympäristöösi ja käynnistä SolidCraft uudelleen.", + "ui.agent_chat_auth_needed": "Agentti pyytää sinua kirjautumaan. Kirjaudut agentin itsensä kautta; SolidCraft ei koskaan näe salasanaasi tai avaimiasi.", + "ui.agent_chat_auth_none": "Agentti ei tarjoa tässä kirjautumistapaa: kirjaudu sen omien ohjeiden mukaisesti.", + "ui.agent_chat_auth_retry": "Olen kirjautunut: yhdistä uudelleen", + "ui.agent_chat_auth_terminal": "Suorita tämä päätteessä ja paina sitten Yhdistä uudelleen:", + "ui.agent_chat_auth_title": "Kirjaudu agenttiin", + "ui.agent_chat_cancel": "Peruuta", + "ui.agent_chat_changes": "Muutoksia: {n}, yksi kumoamisvaihe", + "ui.agent_chat_changes_n": "{n} muutosta", + "ui.agent_chat_changes_of": "{n}/{limit} muutosta", + "ui.agent_chat_choose_model": "Valitse tekoälymalli", + "ui.agent_chat_close": "Sulje", + "ui.agent_chat_command": "Agentin komento", + "ui.agent_chat_connect": "Yhdistä", + "ui.agent_chat_copy": "Kopioi", + "ui.agent_chat_ctx_bodies": "Kappaleet", + "ui.agent_chat_ctx_elements": "Elementit", + "ui.agent_chat_ctx_features": "Piirteet", + "ui.agent_chat_ctx_more": "+{n} lisää", + "ui.agent_chat_ctx_other": "Muut", + "ui.agent_chat_custom_hint": "Mikä tahansa ohjelma, joka puhuu Agent Client Protocolia stdinissä ja stdoutissa. Sitä ei ajeta komentotulkin kautta.", + "ui.agent_chat_denied": "Estetty", + "ui.agent_chat_deny": "Estä", + "ui.agent_chat_desktop_only": "Agenttikeskustelu vaatii työpöytäsovelluksen.", + "ui.agent_chat_detecting": "Etsitään agentteja…", + "ui.agent_chat_dock": "Telakoi sivupaneeliin", + "ui.agent_chat_dock_left": "Telakoi vasemmalle", + "ui.agent_chat_dock_right": "Telakoi oikealle", + "ui.agent_chat_drop_hint": "Pudota liittääksesi seuraavaan viestiin", + "ui.agent_chat_edit": "Muokkaa", + "ui.agent_chat_exited": "Agentti pysähtyi.", + "ui.agent_chat_failed_start": "Agenttia ei voitu käynnistää: {error}", + "ui.agent_chat_file_cad_not_read": "{name}: CAD-tiedosto tuodaan malliin, sitä ei lueta", + "ui.agent_chat_file_empty_picture": "{name}: tyhjä kuva", + "ui.agent_chat_file_error": "{name}: {error}", + "ui.agent_chat_file_heic": "{name}: HEIC-kuvia ei voi lukea tässä; vie se ensin JPEG- tai PNG-muotoon", + "ui.agent_chat_file_importing": "Tuodaan malliin…", + "ui.agent_chat_file_kinds": "{name}: liitettävissä ovat kuvat (PNG, JPEG, GIF, WebP, BMP, TIFF), tekstitiedostot (myös SVG) ja CAD-tiedostot (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF)", + "ui.agent_chat_file_loading": "Luetaan tiedostoa…", + "ui.agent_chat_file_not_a_file": "{name}: ei ole tiedosto", + "ui.agent_chat_file_not_a_picture": "{name}: ei ole kuva", + "ui.agent_chat_file_not_utf8": "{name}: ei ole UTF-8-tekstiä", + "ui.agent_chat_file_picture_too_big": "{name}: kuva voi olla enintään {max} Mt", + "ui.agent_chat_file_text_too_big": "{name}: tekstitiedosto voi olla enintään {max} kt", + "ui.agent_chat_file_too_large": "{name}: liian suuri", + "ui.agent_chat_file_too_large_to_send": "{name}: liian suuri lähetettäväksi, pienennettynäkin", + "ui.agent_chat_file_unreadable_picture": "{name}: kuva, jota ei voi lukea", + "ui.agent_chat_files": "Tiedostot: {files}", + "ui.agent_chat_files_left_out": "Yhden viestin mukana voi olla enintään {max} tiedostoa; pois jätetyt: {files}", + "ui.agent_chat_files_loading": "Odotetaan tiedostojen lukemista", + "ui.agent_chat_files_max": "Enintään {max} tiedostoa yhdessä viestissä", + "ui.agent_chat_flatpak_none_found": "Koodausagenttia ei löytynyt. Flatpak-hiekkalaatikko ei näe kotikansioosi asennettuja agentteja, eikä sillä oletuksena ole verkkoyhteyttä. Jos haluat sallia nvm:n tai ~/.local/bin:n kautta asennetun Claude Coden ja sen ACP-sovittimen, suorita tämä komento päätteessä ja käynnistä sitten SolidCraft uudelleen. Se antaa pääsyn luetteloituun ohjelmaan ja kirjautumistiedostoihin sekä verkkoon:", + "ui.agent_chat_import_failed": "{name}: tuonti epäonnistui: {error}", + "ui.agent_chat_intro": "Keskustele jo käyttämäsi koodausagentin tai valitsemasi mallipalvelun kanssa. Se työskentelee avoimen mallin parissa SolidCraftin työkaluilla: sen muutokset näkyvät sitä mukaa kuin se tekee niitä, ja ne kumotaan yhtenä vaiheena viestiä kohden. Mitä se saa tehdä kysymättä, määritetään kohdassa Asetukset > AI.", + "ui.agent_chat_key_in_env": "avain asetettu", + "ui.agent_chat_last_missing": "Viimeksi käytetty agentti ({agent}) ei ole enää käytettävissä. Valitse agentti ja paina sitten Yritä uudelleen.", + "ui.agent_chat_left": "Vasen", + "ui.agent_chat_limit": "Agentti saavutti yhden viestin {limit} muutoksen rajan. Lähetä uusi viesti, niin se voi jatkaa.", + "ui.agent_chat_login_found": "kirjautuminen löytyi", + "ui.agent_chat_minimize": "Pienennä palkiksi", + "ui.agent_chat_mode_all": "Kaikki", + "ui.agent_chat_mode_ask": "Kysy", + "ui.agent_chat_mode_edits": "Muokkaukset", + "ui.agent_chat_model_no_tools": "{model} ei osaa käyttää SolidCraftin työkaluja, joten se voi vain keskustella. Valitse tekoälymalli, joka tukee työkaluja.", + "ui.agent_chat_model_tip": "Agentin käyttämä tekoälymalli. Valintasi muistetaan tälle agentille.", + "ui.agent_chat_new": "Uusi keskustelu", + "ui.agent_chat_new_confirm": "Aloitetaanko uusi keskustelu? Nykyinen tyhjennetään.", + "ui.agent_chat_next_picture": "Seuraava kuva", + "ui.agent_chat_no_cli": "solidcraft-cli:tä ei löytynyt sovelluksen vierestä, joten agentti ei pääse malliin.", + "ui.agent_chat_no_control": "Agenttikeskustelun päätepiste ei käynnistynyt, joten agentti ei pääse malliin.", + "ui.agent_chat_no_images": "Tämä agentti ei vastaanota kuvia", + "ui.agent_chat_no_picture": "Leikepöydällä ei ole kuvaa", + "ui.agent_chat_no_tool_call": "Tekoälymalli ei käyttänyt SolidCraftin työkaluja, joten mallia ei muutettu. Valitse tekoälymalli, joka tukee työkalukutsuja; katso agenttikeskustelun oppaasta kohta Paikalliset mallit.", + "ui.agent_chat_none_found": "Koodausagenttia ei löytynyt. Asenna jokin näistä ja paina sitten Päivitä:", + "ui.agent_chat_none_found_short": "Agenttia ei löytynyt", + "ui.agent_chat_not_installed": "Ei asennettu", + "ui.agent_chat_not_signed_in": "ei kirjautunut", + "ui.agent_chat_open_settings": "Avaa asetukset", + "ui.agent_chat_own_window": "Oma ikkuna", + "ui.agent_chat_paste_picture": "Liitä kuva", + "ui.agent_chat_permission": "Agentti pyytää lupaa suorittaa: {title}", + "ui.agent_chat_pick": "Agentti", + "ui.agent_chat_pick_context": "Valitse konteksti", + "ui.agent_chat_pick_context_tip": "Valitse mallista pinnat, särmät, piirteet ja kappaleet agentin tarkasteltaviksi ja paina sitten OK", + "ui.agent_chat_placeholder": "Pyydä agenttia muuttamaan mallia…", + "ui.agent_chat_placeholder_busy": "Lisää viesti jonoon odottamaan agentin valmistumista (Ctrl+Enter: lähetä heti)", + "ui.agent_chat_pop_out": "Avaa omaan ikkunaan, jonka voit siirtää toiselle näytölle", + "ui.agent_chat_previous_picture": "Edellinen kuva", + "ui.agent_chat_privacy": "Mitään ei lähetetä minnekään muualle kuin käyttämällesi agentille omalla tililläsi.", + "ui.agent_chat_privacy_note": "Keskustelu itse ei lähetä mitään minnekään: käyttämäsi agentti kommunikoi oman palvelunsa kanssa omalla tililläsi. SolidCraft ei koskaan näe eikä tallenna avainta tai salasanaa.", + "ui.agent_chat_provider_models": "{count} mallia", + "ui.agent_chat_provider_other": "Muu", + "ui.agent_chat_provider_tip": "Palveluntarjoaja, jonka mallit seuraava luettelo näyttää.", + "ui.agent_chat_queue": "Jono", + "ui.agent_chat_queue_full": "Liian monta viestiä odottaa: poista yksi tai odota agenttia.", + "ui.agent_chat_queued": "Jonossa", + "ui.agent_chat_queued_stopped": "Jonossa (pysäytetty, ei lähetetty)", + "ui.agent_chat_refresh": "Päivitä", + "ui.agent_chat_refused": "Ei sallittu agentille: {reason}", + "ui.agent_chat_remove": "Poista jonosta", + "ui.agent_chat_remove_file": "Poista tästä viestistä", + "ui.agent_chat_remove_imported": "Poista tästä viestistä; osa jää malliin (Kumoa poistaa sen)", + "ui.agent_chat_retry": "Yritä uudelleen", + "ui.agent_chat_right": "Oikea", + "ui.agent_chat_save": "Tallenna", + "ui.agent_chat_send": "Lähetä", + "ui.agent_chat_send_now": "Lähetä heti", + "ui.agent_chat_send_now_tip": "Keskeytä agentin nykyinen vaihe ja lähetä tämä seuraavaksi (Ctrl+Enter)", + "ui.agent_chat_setup_body": "SolidCraft keskustelee tähän tietokoneeseen asennetun koodausagentin kanssa. Valitse se kohdassa Asetukset › AI.", + "ui.agent_chat_setup_title": "Ota avustaja käyttöön", + "ui.agent_chat_side": "Agenttikeskustelun puoli", + "ui.agent_chat_signed_in": "kirjautunut", + "ui.agent_chat_state_auth": "Kirjautuminen tarvitaan", + "ui.agent_chat_state_busy": "Työskennellään…", + "ui.agent_chat_state_exited": "Agentti pysähtyi", + "ui.agent_chat_state_failed": "Yhteys epäonnistui", + "ui.agent_chat_state_off": "Ei yhdistetty", + "ui.agent_chat_state_ready": "Valmis", + "ui.agent_chat_state_starting": "Käynnistetään…", + "ui.agent_chat_stop": "Pysäytä", + "ui.agent_chat_stop_tip": "Pysäytä agentti ja kaikki, mitä se käynnisti", + "ui.agent_chat_stop_turn_tip": "Pysäytä agentti (Esc). Jonossa olevat viestit pysyvät jonossa.", + "ui.agent_chat_turn_limit": "Muutoksia viestiä kohden", + "ui.agent_chat_turn_unlimited": "Rajoittamaton", + "ui.agent_chat_undo_changes": "Kumoa nämä muutokset", + "ui.agent_chat_undo_label": "Agenttikeskustelu: {message}", + "ui.agent_chat_undone": "(kumottu)", + "ui.agent_chat_view_attached": "Näkymä liitetty", + "ui.agent_chat_waiting": "Odottaa sinua", + "ui.agent_cursor": "Agentin kohdistin", + "ui.agent_cursor_speed": "Agentin kohdistimen nopeus", + "ui.agent_off_thread": "Pidä ikkuna reagoivana agenttien suorittaessa komentoja", + "ui.agent_off_thread_note": "Agentin hitaat komennot (AI-paneelista tai MCP-asiakkaasta) lasketaan ikkunan rinnalla: voit edelleen kääntää ja tarkastella näkymää ja pysäyttää komennon näkymän merkistä. Pois: kukin suoritetaan ikkunan säikeessä, ja ikkuna odottaa sitä.", + "ui.ai_add": "Lisää", + "ui.ai_add_agent": "Lisää agentti…", + "ui.ai_add_agent_title": "Lisää agentti", + "ui.ai_add_anthropic": "Anthropic-yhteensopiva API", + "ui.ai_add_api": "OpenAI-yhteensopiva API", + "ui.ai_add_custom": "Mukautettu komento", + "ui.ai_add_endpoint": "API-päätepiste", + "ui.ai_add_installed": "Asennettu agentti", + "ui.ai_add_installed_note": "Oma merkintä asennetulle agentille, esimerkiksi muilla argumenteilla. Asennetut agentit luetellaan automaattisesti.", + "ui.ai_added": "lisätty", + "ui.ai_agent_mode_tip": "Agentin oma tila: sen omat työkalut (komentotulkki, tiedostomuokkaukset) noudattavat sitä. SolidCraftin työkalut noudattavat käyttöoikeuksia kohdassa Asetukset > AI.", + "ui.ai_agents": "Agentit", + "ui.ai_always_allow": "Salli aina", + "ui.ai_always_allow_tip": "Salli {tool} tälle agentille tästä lähtien kysymättä", + "ui.ai_always_allowed": "Aina sallitut", + "ui.ai_always_allowed_none": "Mitään ei ole vielä sallittu aina. Keskustelussa antamasi \"Salli aina\" -vastaukset luetellaan tässä.", + "ui.ai_auto_allowed": "Sallittu automaattisesti: {title} ({why})", + "ui.ai_auto_mode": "käyttöoikeusasetuksesi", + "ui.ai_auto_ours": "SolidCraft tarkistaa omat työkalunsa itse", + "ui.ai_auto_remembered": "valitsit Salli aina", + "ui.ai_bad_url": "Anna URL, joka alkaa http:// tai https://", + "ui.ai_base_url": "Perus-URL", + "ui.ai_button": "AI", + "ui.ai_command_hint": "my-agent --acp", + "ui.ai_copy_suffix": "kopio", + "ui.ai_custom_url": "Mukautettu URL", + "ui.ai_default": "Oletus", + "ui.ai_http_busy": "päätepiste on varattu tai ylittänyt rajansa; yritä myöhemmin uudelleen", + "ui.ai_http_key": "päätepiste hylkäsi avaimen: tarkista se kohdassa Asetukset > AI", + "ui.ai_http_not_found": "päätepistettä tai tekoälymallia ei ole: tarkista perus-URL ja tekoälymallin nimi", + "ui.ai_http_too_large": "keskustelu on liian suuri tälle päätepisteelle; aloita uusi keskustelu", + "ui.ai_key": "API-avain", + "ui.ai_key_hint": "valinnainen; säilytetään järjestelmän avainnipussa", + "ui.ai_key_needs_https": "Avain lähetetään vain HTTPS:n kautta tai tähän tietokoneeseen.", + "ui.ai_key_note": "Tallennetaan järjestelmän avainnippuun, ei koskaan SolidCraftin asetuksiin. Jätä tyhjäksi paikalliselle palvelimelle.", + "ui.ai_keychain_error": "Järjestelmän avainnippu kieltäytyi: {error}", + "ui.ai_kind": "Tyyppi", + "ui.ai_mode_all": "Salli kaikki", + "ui.ai_mode_all_note": "Mitään ei kysytä etukäteen. Kaatumisraportit pysyvät kiellettyinä, ja kansiorajoitukset ovat edelleen voimassa.", + "ui.ai_mode_all_warning": "Agentti voi tallentaa, korvata, viedä ja vaihtaa mallisi kysymättä. Käytä tätä vain luotettavan agentin kanssa ja tallennetuissa malleissa.", + "ui.ai_mode_ask": "Kysy joka kerta", + "ui.ai_mode_ask_note": "Jokainen mallin muutos ja jokainen tiedostotoiminto odottaa Salli-hyväksyntääsi.", + "ui.ai_mode_edits": "Salli mallimuokkaukset automaattisesti", + "ui.ai_mode_edits_note": "Mallinnuskomennot suoritetaan kysymättä; tallennus, avaaminen, vienti ja muut tiedosto- tai tuhoavat toiminnot kysytään edelleen.", + "ui.ai_mode_global": "Kuten yllä asetettu", + "ui.ai_model": "Malli", + "ui.ai_model_hint": "qwen3:14b", + "ui.ai_modes_scope": "Nämä asetukset koskevat SolidCraftin työkaluja. Agentin omat työkalut (sen komentotulkki, sen tiedostomuokkaukset) noudattavat agentin omaa tilaa, jonka valitset keskustelupaneelin otsikosta, kun agentilla on tiloja.", + "ui.ai_name": "Nimi", + "ui.ai_name_hint": "Oma agenttini", + "ui.ai_need_command": "Anna komento, joka käynnistää agentin", + "ui.ai_need_model": "Anna tekoälymallin nimi", + "ui.ai_no_answer": "Agentti ei vastannut ajoissa", + "ui.ai_no_http": "Tämä versio ei voi muodostaa yhteyttä API-päätepisteisiin", + "ui.ai_no_keychain": "Järjestelmän avainnippu ei ole käytettävissä, joten avainta ei voi tallentaa. Paikallinen palvelin ilman avainta toimii silti.", + "ui.ai_panel": "Paneeli", + "ui.ai_permissions": "Käyttöoikeudet", + "ui.ai_preset": "Esiasetus", + "ui.ai_protocol": "Protokolla", + "ui.ai_remove": "Poista", + "ui.ai_request_timed_out": "Tekoälymalli käytti yli {seconds} s. Voit pidentää tämän päätepisteen pyynnön aikakatkaisua kohdassa Asetukset › Avustaja.", + "ui.ai_request_timeout": "Pyynnön aikakatkaisu", + "ui.ai_request_timeout_hint": "Kuinka kauan yksi mallipyyntö tähän päätepisteeseen saa kestää, 30 s:sta tuntiin. Pidennä hitaalle paikalliselle tekoälymallille.", + "ui.ai_reset": "Nollaa", + "ui.ai_settings": "AI-asetukset…", + "ui.ai_show_features": "Näytä AI-toiminnot", + "ui.ai_show_features_note": "Agenttikeskustelu: paneeli, jossa jo käyttämäsi koodausagentti tai valitsemasi mallipalvelu työskentelee avoimen mallin parissa. Pois: ei AI-painiketta, pikanäppäintä, valikkokohtaa tai paneelia, eikä mitään etsitä tai käynnistetä.", + "ui.ai_switch_tip": "Vaihda tämän keskustelun agentti", + "ui.ai_test": "Testaa", + "ui.ai_test_acp_ok": "Vastaa: {agent}", + "ui.ai_test_acp_tip": "Käynnistää agentin hetkeksi, pyytää siltä istunnon ja lopettaa sen taas", + "ui.ai_test_answered": "Yhteys saatu: {model} vastasi", + "ui.ai_test_anthropic_tip": "Lähettää lyhyen viestin päätepisteeseen", + "ui.ai_test_api_tip": "Pyytää päätepisteeltä sen mallit", + "ui.ai_test_no_model": "Yhteys saatu: {count} tekoälymallia, mutta ei {model}", + "ui.ai_test_ok": "Yhteys saatu: {count} mallia", + "ui.ai_testing": "Testataan…", + "ui.ai_tool_arguments": "Argumentit", + "ui.ai_tool_details": "Tiedot", + "ui.ai_tool_done": "valmis", + "ui.ai_tool_failed": "epäonnistui", + "ui.ai_tool_result": "Tulos", + "ui.ai_tool_running": "käynnissä", + "ui.ai_tool_sum_bodies_one": "{count} kappale", + "ui.ai_tool_sum_bodies_other": "{count} kappaletta", + "ui.ai_tool_sum_by": "{value} verran", + "ui.ai_tool_sum_edges_one": "{count} särmä", + "ui.ai_tool_sum_edges_other": "{count} särmää", + "ui.ai_tool_sum_faces_one": "{count} pinta", + "ui.ai_tool_sum_faces_other": "{count} pintaa", + "ui.ai_tool_sum_features_one": "{count} piirre", + "ui.ai_tool_sum_features_other": "{count} piirrettä", + "ui.ai_tool_sum_measured": "Mitattu {what}", + "ui.ai_tool_sum_more": "{steps} ja {count} muuta", + "ui.ai_tool_sum_radius": "r {value}", + "ui.ai_tool_sum_saved": "Tallennettu {file}", + "ui.ai_tool_sum_screenshot": "Kuvakaappaus", + "ui.ai_tool_sum_then": "{first}, sitten {next}", + "ui.ai_tool_unfold": "Napsauta nähdäksesi, mitä se palautti", + "ui.ai_tool_waiting": "odottaa", + "ui.ai_toolbar_button": "Näytä Avustaja-painike sovelluspalkissa", + "ui.ai_toolbar_button_note": "Avustaja-painike sovelluspalkissa. Ctrl+Shift+A ja Näytä-valikko avaavat paneelin edelleen.", + "ui.ai_undo_tip": "Kumoa kaikki, mitä agentti muutti tämän viestin osalta, yhtenä vaiheena", + "ui.ai_url_hint": "https://example.com/v1", + "ui.all": "Kaikki", + "ui.ambient_occlusion": "Ympäristön peittovarjostus", + "ui.ambient_occlusion_help": "Pehmeä varjostus kohdissa, joissa läpinäkymättömät pinnat kohtaavat. Vaatii GPU-näkymäikkunan.", + "ui.analysis": "Analyysi", + "ui.angle": "Kulma", + "ui.angle_decimals": "Kulman desimaalit", + "ui.animateJoint": "Animoi nivel", + "ui.animate_view_changes": "Animoi näkymän muutokset", + "ui.animation": "Animaatio", + "ui.animation_speed": "Animaation nopeus", + "ui.anti_aliasing": "Reunanpehmennys", + "ui.apply": "Käytä", + "ui.arc": "Kaari", + "ui.assistant": "Avustaja", + "ui.assistant_waiting": "{count} hyväksyntää odottaa", + "ui.autosave_every": "Automaattitallennus joka", + "ui.axes": "Akselit", + "ui.axis": "Akseli", + "ui.back": "Takaa", + "ui.base_point": "Peruspiste", + "ui.blocked": "Estetty", + "ui.bodies": "Kappaleet", + "ui.bodies_all_if_none": "Kappaleet (kaikki, jos ei valittu)", + "ui.body_kind_mesh": "Verkkokappale", + "ui.body_kind_solid": "Solidikappale", + "ui.body_kind_surface": "Pintakappale", + "ui.bottom": "Alta", + "ui.box": "Laatikko", + "ui.break": "Katko", + "ui.browser_bodies_one": "{count} kappale", + "ui.browser_bodies_other": "{count} kappaletta", + "ui.browser_collapse": "Kutista selain", + "ui.browser_expand": "Laajenna selain", + "ui.browser_title": "Selain", + "ui.calibrate": "Kalibroi", + "ui.cancel": "Peruuta", + "ui.canvases": "Kankaat", + "ui.center": "Keskipiste", + "ui.center_arc_follows_cursor": "Keskipistekaari seuraa kohdistimen suuntaa", + "ui.center_arc_follows_cursor_tip": "Keskipistekaari kulkee myötä- tai vastapäivään sen mukaan, kumpaan suuntaan kohdistin kiertää keskipisteen. Pois: aina vastapäivään alusta lähtien.", + "ui.centerline": "Keskiviiva", + "ui.chain": "Ketju", + "ui.chamfer": "Viiste", + "ui.chamfer_type": "Viisteen tyyppi", + "ui.change_workspace": "Vaihda työtilaa", + "ui.circle": "Ympyrä", + "ui.circular_pattern": "Ympyräkuvio", + "ui.clear": "Tyhjennä", + "ui.clear_print_face": "Tyhjennä tulostuspinta", + "ui.clear_recent": "Tyhjennä viimeisimmät", + "ui.clear_the_selection": "Tyhjennä valinta", + "ui.click_selects_whole_bodies": "Napsautus valitsee kokonaiset kappaleet", + "ui.click_then_press_key": "Napsauta ja paina sitten uutta näppäintä", + "ui.close": "Sulje", + "ui.coil": "Kierukka", + "ui.coincident": "Yhtenevä", + "ui.collapse": "Kutista", + "ui.collinear": "Kollineaarinen", + "ui.colour_vision": "Värinäkö", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "Heikolle tai puuttuvalle vihreän aistimiselle", + "ui.colour_vision_failed": "Epäonnistunut", + "ui.colour_vision_fixed": "Kiinnitetty", + "ui.colour_vision_mode": "Tila", + "ui.colour_vision_note": "Muuttaa merkitystä kantavia värejä: luonnosten tilat, akselit, taivutukset, analyysit ja kuvakkeet. Jos käytät Windowsin värisuodattimia, pidä tämä Pois-tilassa.", + "ui.colour_vision_off": "Pois", + "ui.colour_vision_off_tip": "Teeman omat värit", + "ui.colour_vision_projected": "Projisoitu", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "Heikolle tai puuttuvalle punaisen aistimiselle", + "ui.colour_vision_sample": "Näyte", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "Heikolle tai puuttuvalle sinisen aistimiselle", + "ui.combine": "Yhdistäminen", + "ui.coming_later": "tulossa myöhemmin", + "ui.command_done": "{command} valmis", + "ui.command_palette_hint": "Kirjoita komento, esim. {example} — tai paina S hakeaksesi", + "ui.concentric": "Samankeskinen", + "ui.cone": "Kartio", + "ui.conic_curve": "Kartioleikkauskäyrä", + "ui.constant": "Vakio", + "ui.constraints_conflict": "Rajoitteet ovat ristiriidassa", + "ui.construction": "Apugeometria", + "ui.construction.angle_hint": "Apuviiva: napsauta pistettä ja kirjoita sitten kulma tai valitse suunta", + "ui.construction.bisector_hint": "Puolittaja: valitse kaksi leikkaavaa suoraa viivaa ja sitten haluttu ratkaisu", + "ui.construction.common_hint": "Yhteinen tangentti: valitse kaksi ympyrää/kaarta ja sitten haluttu ratkaisu", + "ui.construction.contact_hint": "Tangentti: valitse ympyrä/kaari tai avoin splini/kartioleikkauskäyrä ja sitten kosketuspiste (vapaamuotoiset käyrät: päätepisteet)", + "ui.construction.external_hint": "Tangentti: valitse ympyrä tai kaari, ulkopuolinen piste ja sitten haluttu ratkaisu", + "ui.construction.free_hint": "Apuviiva: napsauta kahta pistettä; aloita alusta hiiren oikealla painikkeella", + "ui.construction.point_hint": "Apuviiva: napsauta pistettä, jonka kautta viiva kulkee", + "ui.construction.reference_hint": "Apuviiva: valitse suora viiva ja sitten piste; vaihda referenssiä hiiren oikealla painikkeella", + "ui.construction.ribbon_label": "Apuviivat", + "ui.context_menu": "Pikavalikko", + "ui.continuity_g0": "G0 taite", + "ui.continuity_g1": "G1 tangentti", + "ui.continuity_g2": "G2 kaarevuus", + "ui.continuity_gap": "Rako", + "ui.copy": "Kopioi", + "ui.corner": "Kulma", + "ui.corners": "Kulmat", + "ui.cosmetic_thread_markings": "Kosmeettiset kierremerkinnät", + "ui.cosmetic_thread_markings_help": "Näytä kaavamaiset merkinnät kierteitetyissä sylinteriseinämissä. Muuttaa vain näyttöä, ei koskaan mallia tai vientejä.", + "ui.counterbore": "Upotus", + "ui.countersink": "Kartioupotus", + "ui.create": "Luo", + "ui.create_copy": "Luo kopio", + "ui.create_sketch": "Luo luonnos", + "ui.current": "nykyinen", + "ui.curvature": "Kaarevuus", + "ui.curvature_g2": "Kaarevuus (G2)", + "ui.curves": "Käyrät", + "ui.custom_program": "Mukautettu…", + "ui.custom_program_tip": "Valitse luetteloon lisättävä viipalointiohjelma", + "ui.customizeToolbar": "Mukauta työkaluriviä…", + "ui.cut": "Leikkaa", + "ui.cylinder": "Sylinteri", + "ui.dark": "Tumma", + "ui.default_modelling_orientation": "Oletusmallinnussuunta", + "ui.delete": "Poista", + "ui.depth": "Syvyys", + "ui.design": "Suunnittelu", + "ui.design_properties.author": "Tekijä", + "ui.design_properties.description": "Kuvaus", + "ui.design_properties.exports": "STEP-, IGES- ja 3MF-viennit sisältävät nämä, jos muodossa on niille paikka.", + "ui.design_properties.license": "Lisenssi", + "ui.design_properties.not_text": "Tallennettu muuna kuin tekstinä; tähän kirjoittaminen korvaa sen.", + "ui.design_properties.organization": "Organisaatio", + "ui.design_properties.others": "Muiden työkalujen tiedot", + "ui.design_properties.others_note": "Säilytetään mallissa sellaisenaan eikä viedä koskaan.", + "ui.design_properties.part_number": "Osanumero", + "ui.design_properties.project": "Projekti", + "ui.design_properties.revision": "Revisio", + "ui.design_saved": "Tallennettu {path}", + "ui.diameter": "Halkaisija", + "ui.dimension": "Mitta", + "ui.direct_interaction": "Suora vuorovaikutus", + "ui.direct_interaction_note": "Työskentele mallin parissa suoraan näkymäikkunassa. Paina tasaista pintaa tai profiilia ja vedä: ylöspäin pursottaa, alas kappaleeseen leikkaa, ja sivuttaisliike asettaa askelkoon", + "ui.direction": "Suunta", + "ui.display_quality": "Näytön laatu", + "ui.display_quality_coarse": "Karkea", + "ui.display_quality_fine": "Tarkka", + "ui.display_quality_normal": "Normaali", + "ui.display_quality_ultra": "Erittäin tarkka", + "ui.distance": "Etäisyys", + "ui.distance_1": "Etäisyys 1", + "ui.distance_2": "Etäisyys 2", + "ui.document_settings": "Asiakirjan asetukset", + "ui.don_t_save": "Älä tallenna", + "ui.draft": "Päästö", + "ui.drawing": "Piirustus", + "ui.drill_point": "Poran kärki", + "ui.easyprint_consent": "EasyPrint on Printablesin selaimessa toimiva viipalointiohjelma. Avatakseen mallin siellä SolidCraft lataa sen Printablesin palvelimille. Linkki vanhenee 30 minuutin kuluttua, ja sinun on oltava kirjautuneena Printablesiin. Jatketaanko?", + "ui.easyprint_failed": "EasyPrint-lataus epäonnistui: {error}", + "ui.easyprint_opened": "Avattu EasyPrintissä", + "ui.easyprint_row": "EasyPrint (Printables, selaimessa)", + "ui.easyprint_uploading": "Ladataan Printablesiin…", + "ui.edit": "Muokkaa", + "ui.editJointLimits": "Muokkaa nivelen rajoja", + "ui.edit_in_place": "Muokkaa paikallaan", + "ui.edit_in_place_after_turn": "Muokkaus päättyy, kun agentin vuoro päättyy", + "ui.edit_in_place_agent_busy": "Agentti työskentelee yhä tässä mallissa; yritä uudelleen, kun sen vuoro on päättynyt", + "ui.edit_in_place_already_queued": "Muokkaus odottaa jo agentin vuoron päättymistä", + "ui.edit_in_place_assembly_closed": "{name} ei ole enää auki", + "ui.edit_in_place_banner": "Muokataan kohteessa {name}", + "ui.edit_in_place_busy": "Viimeistele tai peruuta ensin auki oleva toiminto", + "ui.edit_in_place_none": "Mitään linkitettyä mallia ei muokata paikallaan", + "ui.edit_in_place_not_saved": "Osassa on tallentamattomia muutoksia; tallenna se lopettaaksesi muokkauksen", + "ui.edit_in_place_open_elsewhere": "{name} on auki toisessa SolidCraftissa", + "ui.edit_in_place_opens_after_turn": "Osa avautuu, kun agentin vuoro päättyy", + "ui.edit_in_place_refresh_dropped": "Kokoonpano muuttui Päivitä linkit -toiminnon aikana; suorita se uudelleen", + "ui.edit_in_place_refresh_stopped": "Päivitä linkit pysähtyi ennen kuin se oli valmis", + "ui.edit_in_place_refreshing": "Päivitetään linkkejä kohteessa {name}…", + "ui.edit_in_place_save_first": "Tallenna kokoonpano ensin: sen linkitetyt mallit haetaan sen tiedostosta", + "ui.edit_in_place_save_waits": "Päivitä linkit on käynnissä kohteessa {name}; tallenna se, kun se on valmis", + "ui.edit_in_place_saved_elsewhere": "Osa tallennettiin toiseen tiedostoon; kokoonpano linkittää yhä kohteeseen {name}", + "ui.edit_in_place_wait": "Odota, kunnes mallissa käynnissä oleva toiminto on valmis", + "ui.edit_section_analysis": "Muokkaa leikkausanalyysiä", + "ui.ellipse": "Ellipsi", + "ui.emboss_wrap_note": "Yhtä tuettua sylinteriä sivuavat kohtisuorat viivaprofiilit kiedotaan automaattisesti. Valitse seinämä valitaksesi kohteen.", + "ui.end_radius": "Loppusäde", + "ui.end_scale": "Loppuskaala", + "ui.entities": "Entiteetit", + "ui.equal": "Yhtä suuri", + "ui.equation_end": "Loppu", + "ui.equation_explicit": "Eksplisiittinen", + "ui.equation_form": "Muoto", + "ui.equation_note": "Muuttuja on pelkkä luku: sin(t) tulkitsee sen radiaaneina. Tulos ilman yksikköä on mallin yksikössä.", + "ui.equation_parametric": "Parametrinen", + "ui.equation_x_of_t": "x(t)", + "ui.equation_y_of_t": "y(t)", + "ui.equation_y_of_x": "y(x)", + "ui.equivalent_radius": "Vastaava säde", + "ui.expand": "Laajenna", + "ui.exportDxf": "Vie DXF…", + "ui.export_ellipsis_keymap": "Vie…", + "ui.export_keymap_tip": "Näppäimet, S-ruudun suosikit ja työkalurivi tiedostona", + "ui.extend": "Jatka", + "ui.extent_type": "Ulottuman tyyppi", + "ui.extract_component": "Erota tiedostoon…", + "ui.extract_design_changed": "Malli muuttui tiedostoa valittaessa. Aloita Erota tiedostoon uudelleen.", + "ui.extract_done": "Komponentti on nyt oma mallinsa, linkitettynä tähän.", + "ui.extrude": "Pursotus", + "ui.extrude_auto_to_object": "Pursota valittuun kohteeseen", + "ui.extrude_auto_to_object_tip": "Pursotuksessa, kun profiili on valittu, sen tason ulkopuolisen pinnan, kärkipisteen tai yhdensuuntaisen tason valitseminen vaihtaa ulottumaksi Kohteeseen", + "ui.factor": "Kerroin", + "ui.feature_history": "Piirrehistoria", + "ui.feature_options": "Piirteen asetukset", + "ui.features": "Piirteet", + "ui.file": "Tiedosto", + "ui.fillet": "Pyöristys", + "ui.filter_commands_or_keys": "Suodata komentoja tai näppäimiä", + "ui.findInTimeline": "Etsi aikajanalta", + "ui.findInWindow": "Etsi ikkunasta", + "ui.fine": "Tarkka", + "ui.finest": "Tarkin", + "ui.finish_sketch": "Lopeta luonnos", + "ui.fit": "Sovita", + "ui.fix_unfix": "Kiinnitä/vapauta", + "ui.flat": "Tasainen", + "ui.flip": "Käännä", + "ui.format": "Muoto", + "ui.frame_rate": "Kuvataajuus", + "ui.frame_rate_details": "Kuvataajuuden tiedot", + "ui.front": "Edestä", + "ui.fully_constrained": "Täysin rajoitettu", + "ui.function": "Funktio", + "ui.general": "Yleiset", + "ui.gpu_memory_lowered": "Näytönohjaimen muisti on lopussa: näkymä piirretään heikommalla laadulla.", + "ui.graphics": "Grafiikka", + "ui.graphics_custom": "Mukautettu", + "ui.graphics_performance": "Suorituskyky", + "ui.graphics_preset": "Grafiikan esiasetus", + "ui.graphics_preset_help": "Laatu: ympäristön peittovarjostus, näytön laatu Tarkka ja mukautuva 2× ylinäytteistys. Suorituskyky: ei ympäristön peittovarjostusta, näytön laatu Normaali ja ylinäytteistys pois. Käsin tehdyt muutokset näkyvät Mukautettuna. MSAA pysyy ennallaan.", + "ui.graphics_quality": "Laatu", + "ui.grid_follows_view": "Ruudukko seuraa näkymää", + "ui.grid_follows_view_hint": "Sivunäkymät näyttävät ruudukon niitä kohti olevalla pystytasolla maatason sijaan", + "ui.ground_shadow": "Maavarjo", + "ui.groupSelected": "Ryhmitä valitut", + "ui.hatch": "Viivoitus", + "ui.heading_add_ins": "LISÄOSAT", + "ui.heading_assemble": "KOKOA", + "ui.heading_box": "LAATIKKO", + "ui.heading_chamfer": "VIISTE", + "ui.heading_circular_pattern": "YMPYRÄKUVIO", + "ui.heading_coil": "KIERUKKA", + "ui.heading_combine": "YHDISTÄ", + "ui.heading_cone": "KARTIO", + "ui.heading_configure": "KONFIGUROI", + "ui.heading_constraints": "RAJOITTEET", + "ui.heading_construct": "RAKENNA", + "ui.heading_create": "LUO", + "ui.heading_create_sketch": "LUO LUONNOS", + "ui.heading_cylinder": "SYLINTERI", + "ui.heading_design": "SUUNNITTELU", + "ui.heading_draft": "PÄÄSTÖ", + "ui.heading_edit": "MUOKKAA", + "ui.heading_equation_curve": "YHTÄLÖKÄYRÄ", + "ui.heading_extrude": "PURSOTUS", + "ui.heading_fillet": "PYÖRISTYS", + "ui.heading_finish_editing": "LOPETA MUOKKAUS", + "ui.heading_finish_sketch": "LOPETA LUONNOS", + "ui.heading_form": "MUOTO", + "ui.heading_front": "EDESTÄ", + "ui.heading_hole": "REIKÄ", + "ui.heading_home": "ALKU", + "ui.heading_insert": "LISÄÄ", + "ui.heading_inspect": "TARKASTELE", + "ui.heading_interference": "PÄÄLLEKKÄISYYS", + "ui.heading_loft": "LOFTTAUS", + "ui.heading_make": "VALMISTA", + "ui.heading_measure": "MITTAA", + "ui.heading_mesh": "VERKKO", + "ui.heading_mirror": "PEILAUS", + "ui.heading_modify": "MUOKKAA", + "ui.heading_move": "SIIRRÄ", + "ui.heading_move_copy": "SIIRRÄ/KOPIOI", + "ui.heading_offset": "SIIRTYMÄ", + "ui.heading_offset_plane": "SIIRTYMÄTASO", + "ui.heading_ok": "OK", + "ui.heading_parameters": "PARAMETRIT", + "ui.heading_pattern": "KUVIO", + "ui.heading_pattern_on_path": "KUVIO POLULLA", + "ui.heading_pipe": "PUTKI", + "ui.heading_plane_at_angle": "TASO KULMASSA", + "ui.heading_plastic": "MUOVI", + "ui.heading_position": "SIJAINTI", + "ui.heading_prepare": "VALMISTELE", + "ui.heading_rectangular_pattern": "SUORAKULMAINEN KUVIO", + "ui.heading_revolve": "PYÖRÄYTYS", + "ui.heading_right": "OIKEALTA", + "ui.heading_save_mesh": "TALLENNA VERKKONA", + "ui.heading_scale": "SKAALAA", + "ui.heading_section_analysis": "LEIKKAUSANALYYSI", + "ui.heading_select": "VALITSE", + "ui.heading_setup": "ASETUS", + "ui.heading_sheet_metal": "OHUTLEVY", + "ui.heading_shell": "KUORI", + "ui.heading_sketch": "LUONNOS", + "ui.heading_sketch_scale": "LUONNOKSEN SKAALAUS", + "ui.heading_solid": "KIINTEÄ", + "ui.heading_sphere": "PALLO", + "ui.heading_split_body": "JAA KAPPALE", + "ui.heading_surface": "PINTA", + "ui.heading_sweep": "PYYHKÄISY", + "ui.heading_thread": "KIERRE", + "ui.heading_top": "YLHÄÄLTÄ", + "ui.heading_torus": "TORUS", + "ui.heading_utilities": "APUVÄLINEET", + "ui.heading_utility": "APUVÄLINE", + "ui.heading_weldments": "HITSAUSRAKENTEET", + "ui.height": "Korkeus", + "ui.help": "Ohje", + "ui.hide": "Piilota", + "ui.hideAxes": "Piilota akselit", + "ui.hideDimension": "Piilota mitta", + "ui.hideOrigin": "Piilota origo", + "ui.hidePlanes": "Piilota tasot", + "ui.hideProfile": "Piilota profiili", + "ui.hide_origin_by_default": "Piilota origo oletuksena", + "ui.hide_origin_note": "Uusissa malleissa Origo-kansio on aluksi piilotettu. Malli säilyttää oman Origo-asetuksensa, kun näytät tai piilotat sen.", + "ui.history_back": "Siirry askel taaksepäin", + "ui.history_below_browser": "Selaimen alla", + "ui.history_edge_hint": "kaksoisnapsauta reunaa", + "ui.history_first": "Siirry alkuun", + "ui.history_forward": "Siirry askel eteenpäin", + "ui.history_hide_names": "Piilota nimet", + "ui.history_last": "Siirry loppuun", + "ui.history_marker_tip": "Historiamerkki: palauta malli vetämällä taaksepäin; uudet piirteet tulevat tähän", + "ui.history_names": "Nimet", + "ui.history_play": "Toista loppuun", + "ui.history_play_button_hide": "Piilota toistopainike", + "ui.history_play_button_show": "Näytä toistopainike", + "ui.history_play_finish_action": "Lopeta nykyinen toiminto ennen historian toistamista", + "ui.history_play_roll_back": "Siirrä historiamerkkiä taaksepäin ennen toistamista", + "ui.history_show_names": "Näytä nimet", + "ui.history_sketch_listed_under": "Kohteen {feature} alla", + "ui.history_title": "Historia", + "ui.history_toggle_names": "Näytä tai piilota piirteiden nimet", + "ui.hole": "Reikä", + "ui.hole_tap_type": "Reiän kierteitys", + "ui.hole_type": "Reiän tyyppi", + "ui.home": "Alkuun", + "ui.homeView": "Alkunäkymä", + "ui.horizontal_constraint": "Vaakasuora-rajoite", + "ui.horizontal_vertical": "Vaakasuora/pystysuora", + "ui.import_ellipsis": "Tuo…", + "ui.infinite": "Ääretön", + "ui.insert": "Lisää", + "ui.insert_design.browse": "Selaa…", + "ui.insert_design.open_designs": "Avoimet mallit", + "ui.insert_design.saved_file": "Mallissa {name} on tallentamattomia muutoksia, joten sen tallennettu tiedosto lisättiin. Tallenna se ja tuo muutokset valitsemalla Päivitä linkit.", + "ui.insert_design.unsaved": "Tallentamattomia muutoksia", + "ui.inspect": "Tarkastele", + "ui.instances": "Esiintymät", + "ui.intersect": "Leikkaus", + "ui.isolate": "Eristä", + "ui.join": "Yhdistä", + "ui.joint_play": "▶ Toista", + "ui.joint_stop": "■ Pysäytä", + "ui.joints": "Nivelet", + "ui.keyboard_shortcuts": "Pikanäppäimet", + "ui.language": "Kieli", + "ui.layout_compact": "Tiivis", + "ui.layout_floating": "Kelluva", + "ui.length": "Pituus", + "ui.length_decimals": "Pituuden desimaalit", + "ui.light": "Vaalea", + "ui.line": "Viiva", + "ui.link_copies": "Linkitä identtiset kopiot", + "ui.link_copies_keep": "Säilytä", + "ui.link_copies_link": "Linkitä", + "ui.link_copies_text": "Nämä komponentit muodostavat samat kappaleet kuin {name}. Muutetaanko ne sen linkin sijoituksiksi?", + "ui.lock": "Lukitse", + "ui.loft": "Lofttaus", + "ui.look_at": "Katso kohti", + "ui.look_at_anim_desc": "Akselinäkymä, Katso kohti, Alkuun ja Sovita", + "ui.major_radius": "Suuri säde", + "ui.manipulator_free_alt": "Manipulaattorin vapaa veto myös Alt/Option-näppäimellä", + "ui.manipulator_free_alt_tip": "Päällä: Alt/Option tai Ctrl/Cmd pursotuksen / manipulaattorin nuolissa poistaa arvojen tartunnan. Pois: vain Ctrl/Cmd.", + "ui.manufacture": "Valmistus", + "ui.material_review.axes": "Materiaalin omat akselit; kappaleen suuntaa ei ole määritetty.", + "ui.material_review.claims": "Lähteet ja lisenssit ovat tarkistamattomia väitteitä. Puuttuvat arvot jäävät tuntemattomiksi.", + "ui.material_review.compressive_strength": "Puristuslujuus", + "ui.material_review.conditions": "Ilmoitetut olosuhteet", + "ui.material_review.density": "Tiheys", + "ui.material_review.derived": "Johdetut isotrooppiset moduulit", + "ui.material_review.elasticity": "Kimmoisuus", + "ui.material_review.input": "Liitä schema-1-materiaalikortti (JSON)", + "ui.material_review.limit": "Kortti ylittää 256 KiB:n syöterajan.", + "ui.material_review.moisture_unit": "kg vettä / kg kuivaa materiaalia", + "ui.material_review.properties": "Ominaisuudet", + "ui.material_review.review": "Tarkista kortti", + "ui.material_review.scope": "Vain ehdokas: ei määritetty eikä tallennettu. Numeerinen validointi ei ole teknistä sertifiointia.", + "ui.material_review.shear_strength": "Leikkauslujuus", + "ui.material_review.source": "Lähde", + "ui.material_review.specific_heat": "Ominaislämpökapasiteetti", + "ui.material_review.tensile_strength": "Vetolujuus", + "ui.material_review.thermal_conductivity": "Lämmönjohtavuus", + "ui.material_review.thermal_expansion": "Lämpölaajeneminen", + "ui.material_review.title": "Tarkista materiaalin fysikaaliset tiedot", + "ui.material_review.unknown": "Tuntematon", + "ui.material_review.yield_strength": "Myötölujuus", + "ui.measure": "Mittaa", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF pintatunnisteilla", + "ui.mesh_format_stl": "STL", + "ui.minor_radius": "Pieni säde", + "ui.mirror": "Peilaus", + "ui.mirror_line": "Peilausviiva", + "ui.modifiers_either": "{first} tai {second}", + "ui.move": "Siirrä", + "ui.multiple": "Useita", + "ui.named_views": "Nimetyt näkymät", + "ui.nav_bridge": "Navigoi tämän tietokoneen laitesovelluksella", + "ui.nav_bridge_connected": "Yhdistetty", + "ui.nav_bridge_port": "Portti", + "ui.nav_bridge_tip": "3D-syöttölaitteen oma ohjelma (esimerkiksi itse tehdyn 3D-hiiren ajuri) liikuttaa näkymää paikallisen yhteyden kautta, joten hiiren osoitin pysyy sinun käytössäsi. SolidCraft muodostaa yhteyden siihen tässä portissa vain tällä tietokoneella.", + "ui.nav_bridge_waiting": "Odotetaan laitesovellusta", + "ui.navigation": "Navigointi", + "ui.needs_design": "{command}: avaa ensin malli", + "ui.newSketchGroup": "Uusi luonnosryhmä", + "ui.new_body": "Uusi kappale", + "ui.new_design": "Uusi malli", + "ui.no_geometry_yet": "Ei vielä geometriaa", + "ui.no_slicer_found": "Viipalointiohjelmaa ei löytynyt", + "ui.normal": "Normaali", + "ui.normalConstruction": "Normaali / apugeometria", + "ui.not_a_program": "{path} ei ole käynnistettävä ohjelma", + "ui.object_type": "Objektin tyyppi", + "ui.objects": "Objektit", + "ui.offer_to_stand_up_y_up_files": "Tarjoa Y ylös -tiedostojen pystyttämistä", + "ui.offset": "Siirtymä", + "ui.offset_plane": "Siirtymätaso", + "ui.one_side": "Yksi puoli", + "ui.open": "Avaa", + "ui.open_ends_tip": "Ei kosketa mitään", + "ui.open_linked_design": "Avaa linkitetty malli", + "ui.open_preferences": "Avaa asetukset", + "ui.open_recent": "Avaa viimeaikainen", + "ui.operation": "Toiminto", + "ui.options": "Valinnat", + "ui.orbit": "Kierrä", + "ui.orbit_around": "Kierrä kohteen ympäri", + "ui.orientation": "Suunta", + "ui.origin": "Origo", + "ui.palette_construction_mode": "Apugeometriatila (X)", + "ui.palette_more": "Lisää", + "ui.palette_sketch_options": "Luonnoksen valinnat", + "ui.pan": "Panoroi", + "ui.pan_zoom_orbit": "Panoroi, zoomaa, kierrä", + "ui.parallel": "Yhdensuuntainen", + "ui.parameters": "Parametrit", + "ui.part_size_needs_a_part": "Valitse lisätty standardiosa (ruuvi, mutteri, aluslevy tai tappi) muuttaaksesi sen kokoa. Jos haluat suurentaa tai pienentää kappaletta, käytä Skaalaa-toimintoa.", + "ui.part_size_shared": "Rakentaa osan uudelleen ja korvaa lisätyt piirteet. Kaikki tämän komponentin esiintymät päivittyvät.", + "ui.paste": "Liitä", + "ui.path": "Polku", + "ui.pattern_on_path": "Kuvio polulla", + "ui.perforate_margin_default": "halkaisijasta", + "ui.perforate_pitch": "Jako", + "ui.perforate_square": "Neliö", + "ui.perforate_staggered": "Lomitettu (60°)", + "ui.perforate_title": "REI'ITÄ", + "ui.perpendicular": "Kohtisuora", + "ui.perspective_view": "Perspektiivinäkymä", + "ui.pinToShortcuts": "Kiinnitä pikavalintoihin", + "ui.pinToToolbar": "Kiinnitä työkaluriville", + "ui.pipe": "Putki", + "ui.pitch": "Nousu", + "ui.placement": "Sijoitus", + "ui.placement_handles": "Sijoituskahvat", + "ui.placement_handles_tip": "Kahvat tuen, tapin tai napsautusliitoksen esikatselussa: siirrä merkkiä mallin pinnalla vetämällä ja käännä sitä renkaasta", + "ui.plane": "Taso", + "ui.plane_at_angle": "Taso kulmassa", + "ui.plugins": "Laajennukset", + "ui.plugins_desktop": "Laajennukset ovat käytettävissä työpöytäsovelluksessa.", + "ui.plugins_empty": "Laajennuksia ei ole asennettu.", + "ui.plugins_none": "Mikään laajennus ei vastaa hakua.", + "ui.plugins_note": "Jokainen laajennus on kansio sijainnissa {path}, ja siinä on plugin.json. SolidCraft lukee tämän tiedoston eikä suorita kansiosta mitään koodia. Kun laajennus poistetaan käytöstä, se pysyy asennettuna.", + "ui.plugins_search": "Hae laajennuksia", + "ui.plugins_skipped": "{count} kansiota ei voitu lukea.", + "ui.plugins_version": "{version}", + "ui.point": "Piste", + "ui.point_cloud_add_filter": "Lisää suodatin…", + "ui.point_cloud_auto_range": "Automaattinen alue", + "ui.point_cloud_color_by": "Väritysperuste", + "ui.point_cloud_file_colors": "Tiedoston värit", + "ui.point_cloud_filter_by": "Suodatusperuste", + "ui.point_cloud_height_high": "Korkein", + "ui.point_cloud_height_low": "Matalin", + "ui.point_cloud_legend_filter": "Näytetty ja piilotettu yllä olevassa selitteessä", + "ui.point_cloud_no_file_colors": "Tiedostossa ei ole värejä", + "ui.point_cloud_pause": "Tauko", + "ui.point_cloud_play": "Toista", + "ui.point_cloud_single_color": "Yksi väri", + "ui.point_cloud_size": "Pisteen koko", + "ui.point_cloud_units": "Tiedoston yksiköt", + "ui.point_under_the_cursor": "Osoittimen alla oleva piste", + "ui.points": "Pisteet", + "ui.polygon": "Monikulmio", + "ui.preferences": "Asetukset", + "ui.press_a_key": "paina näppäintä…", + "ui.print_face_body_not_sent": "Tämän pinnan kappaletta ei lähetetä: lisää se ensin kohtaan Kappaleet", + "ui.print_face_cleared": "{body}: tulostuspinta poistettu", + "ui.print_face_input": "Tulostuspinta", + "ui.print_face_pick": "Valitse kiinteän kappaleen yksi tasainen pinta tulostuspinnaksi", + "ui.print_face_set": "{body}: tulostuspinta asetettu; Lähetä viipalointiohjelmaan asettaa kappaleen sen varaan", + "ui.profile": "Profiili", + "ui.profile_plane": "Profiilin taso", + "ui.profiles": "Profiilit", + "ui.project": "Projisoi", + "ui.project_face_edges_sketch": "Projisoi pinnan särmät uusiin luonnoksiin", + "ui.properties": "Ominaisuudet", + "ui.properties.copy_matrix": "Kopioi matriisi", + "ui.properties.first_moments": "Ensimmäiset momentit", + "ui.properties.inertia": "Hitausmomentti", + "ui.properties.inertia_note": "Massakeskipisteen suhteen, maailman akseleissa (g·{unit}²)", + "ui.properties.inertia_unavailable": "Ei käytettävissä: kappaleen verkko ei ole suljettu.", + "ui.properties.inertia_x": "Ixx, Ixy, Ixz", + "ui.properties.inertia_y": "Iyx, Iyy, Iyz", + "ui.properties.inertia_z": "Izx, Izy, Izz", + "ui.properties.measuring": "Mitataan…", + "ui.properties.measuring_failed": "Mittaus pysähtyi ennen valmistumista.", + "ui.properties.principal_axis": "Pääakseli {number}", + "ui.properties.principal_moments": "Päähitausmomentit", + "ui.pull_direction": "Vetosuunta", + "ui.quality": "Laatu", + "ui.quantity": "Määrä", + "ui.quantity_2": "Määrä 2", + "ui.quit": "Lopeta", + "ui.radial_context_menu": "Säteittäinen pikavalikko", + "ui.radius": "Säde", + "ui.rail": "Johde", + "ui.rail_fit": "Johteen sovitus", + "ui.reachable": "Saavutettavissa", + "ui.rectangle": "Suorakulmio", + "ui.rectangular_pattern": "Suorakulmainen kuvio", + "ui.redo": "Tee uudelleen", + "ui.reference_1": "Viite 1", + "ui.reference_2": "Viite 2", + "ui.reference_distance": "Viite-etäisyys", + "ui.relink_design_changed": "Kokoonpano muuttui lähdettä valittaessa. Aloita Linkitä lähde uudelleen alusta.", + "ui.relink_done": "Lähde linkitetty uudelleen kaikille esiintymille.", + "ui.relink_not_linked": "Tätä komponenttia ei ole linkitetty lähdemalliin.", + "ui.relink_select_one": "Valitse ensin yksi linkitetty komponentti tai jokin sen esiintymistä.", + "ui.relink_source_all": "Linkitä lähde uudelleen (kaikki esiintymät)…", + "ui.removeFromToolbar": "Poista työkaluriviltä", + "ui.removeSection": "Poista leikkaus", + "ui.render": "Renderöi", + "ui.renderer": "Renderöijä", + "ui.repeat": "Toista", + "ui.repeat_nothing": "Ei vielä toistettavaa: käynnistä ensin työkalu tai valintaikkuna.", + "ui.replace_with_link_done": "Kopiot ovat nyt linkitetyn mallin sijoituksia.", + "ui.report_a_bug": "Ilmoita virheestä", + "ui.reset": "Palauta", + "ui.reset_all": "Palauta kaikki", + "ui.reset_the_settings_on_this_page": "Palauta tämän sivun asetukset", + "ui.restore": "Palauta", + "ui.restore_defaults": "Palauta oletukset", + "ui.reverse_horizontal_pan_direction": "Käännä vaakapanoroinnin suunta", + "ui.reverse_horizontal_pan_tip": "Vaakasuuntainen kahden sormen vieritys ja peukalorulla panoroivat vastakkaiseen suuntaan", + "ui.reverse_trackpad_orbit_direction": "Käännä kosketuslevyn kiertosuunta", + "ui.reverse_trackpad_orbit_tip": "Shift ja kahden sormen vieritys kiertävät vastakkaiseen suuntaan", + "ui.reverse_vertical_pan_direction": "Käännä pystypanoroinnin suunta", + "ui.reverse_vertical_pan_tip": "Pystysuuntainen kahden sormen vieritys panoroi vastakkaiseen suuntaan", + "ui.reverse_zoom_direction": "Käännä zoomaussuunta", + "ui.revolutions": "Kierrokset", + "ui.revolve": "Pyöräytys", + "ui.ribbon_exit": "Poistu", + "ui.ribbon_labels": "Näytä teksti valintanauhan kuvakkeiden alla", + "ui.ribbon_menus_skip_pinned": "Jätä kiinnitetyt komennot pois pudotusvalikoista", + "ui.ribbon_pin_footer": "Kiinnitetyt komennot näkyvät valintanauhassa. Kiinnitä rivi tai poista kiinnitys viemällä osoitin rivin päälle.", + "ui.ribbon_workspace": "Työtila", + "ui.right": "Oikealta", + "ui.save": "Tallenna", + "ui.save_as": "Tallenna nimellä", + "ui.save_mesh_no_slicer_open": "Viipalointiohjelmaa ei löytynyt: valitse Mukautettu… ja valitse viipalointiohjelmasi", + "ui.save_mesh_pick_bodies": "Valitse tallennettavat kappaleet", + "ui.saved_to": "Tallennettu {path}", + "ui.sbox_pin": "Kiinnitä S-ruudun ylälaitaan", + "ui.sbox_unpin": "Poista kiinnitys", + "ui.scale": "Skaalaus", + "ui.second_rail": "Toinen johde", + "ui.section_analysis": "Leikkausanalyysi", + "ui.section_size": "Poikkileikkauksen koko", + "ui.select": "Valitse", + "ui.selectOther": "Valitse muu…", + "ui.selectTangentChain": "Valitse tangenttiketju", + "ui.select_all": "Valitse kaikki", + "ui.selection": "Valinta", + "ui.selection_modifiers": "Valinnan muokkausnäppäimet", + "ui.selection_shift_add_only": "Shift+napsautus lisää poistamatta", + "ui.selection_shift_add_only_tip": "Päällä: Shift lisää kohteita, Ctrl/Cmd vaihtaa valintaa. Pois (oletus): sekä Shift että Ctrl/Cmd vaihtavat valintaa.", + "ui.send": "Lähetä", + "ui.send_to_slicer_unavailable": "Lähetä viipalointiohjelmaan vaatii työpöytäsovelluksen: selain ei voi käynnistää ohjelmaa", + "ui.sent_to_slicer": "Lähetetty ohjelmaan {slicer}", + "ui.sent_to_slicer_copy": "Lähetetty ohjelmaan {slicer} tiedostona {file}, koska ensimmäinen tiedosto on yhä auki siellä", + "ui.sheet_gap": "Rako", + "ui.shell": "Kuori", + "ui.shortcut_capture_add_key": "Lisää yksi tavallinen näppäin. Escape peruuttaa.", + "ui.shortcut_capture_hint": "Napsauta pikanäppäintä ja paina sitten muokkausnäppäimiä ja yhtä näppäintä. Lisää muokkausnäppäimet sekunnin sisällä; vahvista vapauttamalla kaikki näppäimet. Escape peruuttaa.", + "ui.shortcut_capture_press": "Paina muokkausnäppäimiä ja yhtä näppäintä. Escape peruuttaa.", + "ui.shortcut_capture_release": "Vahvista vapauttamalla kaikki näppäimet. Escape peruuttaa.", + "ui.shortcut_capture_settling": "Vahvistetaan pikanäppäintä… Escape peruuttaa.", + "ui.shortcut_cycles_modes": "Työkalun pikanäppäimen painaminen uudelleen vaihtaa sen tilaa", + "ui.shortcut_cycles_modes_tip": "Ennen ensimmäistä pistettä luonnostyökalun pikanäppäimen painaminen uudelleen käy läpi sen luontitilat. Pois: työkalu käynnistyy uudelleen.", + "ui.shortcut_multiple_keys": "Käytä muokkausnäppäimiä ja vain yhtä muuta näppäintä. Yritä uudelleen napsauttamalla pikanäppäintä.", + "ui.show": "Näytä", + "ui.showAll": "Näytä kaikki", + "ui.showAllBodies": "Näytä kaikki kappaleet", + "ui.showAxes": "Näytä akselit", + "ui.showDimension": "Näytä mitta", + "ui.showOrigin": "Näytä origo", + "ui.showPlanes": "Näytä tasot", + "ui.show_constraints": "Rajoitteet", + "ui.show_construction_geometries": "Apugeometriat", + "ui.show_dimensions": "Mitat", + "ui.show_profile": "Näytä profiili", + "ui.show_projected_geometries": "Projisoidut geometriat", + "ui.simple": "Yksinkertainen", + "ui.simulation": "Simulointi", + "ui.single": "Yksi", + "ui.sketch": "Luonnos", + "ui.sketch_dimension": "Luonnoksen mitta", + "ui.sketch_grid": "Luonnosruudukko", + "ui.sketch_intersect_geometry": "Geometria", + "ui.sketch_intersect_projection_link": "Projisointilinkki", + "ui.sketch_intersect_selection_filter": "Valintasuodatin", + "ui.sketch_modifiers": "Luonnoksen muokkausnäppäimet", + "ui.sketch_project_geometry": "Geometria", + "ui.sketch_report.all_constrained": "Kaikki on täysin rajoitettu.", + "ui.sketch_report.dof": "Vapausasteet", + "ui.sketch_report.loose": "Ei täysin rajoitettu", + "ui.sketch_report.status": "Tila", + "ui.sketch_report.title": "Luonnosraportti", + "ui.sketch_scale": "Luonnoksen skaalaus", + "ui.sketches": "Luonnokset", + "ui.slice": "Viipaloi", + "ui.slicer": "Viipalointiohjelma", + "ui.slicer_delete_tip": "{program}\nPoista se luettelosta painamalla Delete", + "ui.slicer_lost": "{slicer} käynnistettiin, mutta sitä ei löydetä uudelleen tiedoston lähettämiseksi. Tiedosto on tallennettu sijaintiin {path}: avaa se sieltä.", + "ui.slicer_no_file": "{slicer} on valmiina, mutta sille ei ole lähetettävää tiedostoa.", + "ui.slicer_no_response": "{slicer} ei vastannut ajoissa. Tiedosto on jo tallennettu sijaintiin {path}: lähetä se uudelleen, kun viipalointiohjelma on käynnistynyt.", + "ui.slicer_resend_hint": "Uudelleenlähetys korvaa viipalointiohjelmassa auki olevan tiedoston.", + "ui.slicer_single_instance": "Avaa tiedostot jo käynnissä olevassa viipalointiohjelmassa", + "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer ja Cura lataavat tiedoston avoinna olevaan ikkunaan sen sijaan, että käynnistäisivät uuden. Muut viipalointiohjelmat käynnistetään sellaisenaan. PrusaSlicer 3.0 toimii aina näin: sen käynnistin ei voi ottaa tiedostoa vastaan muulla tavalla.", + "ui.slicer_starting": "Käynnistetään {slicer}…", + "ui.slicer_still_starting": "Odotetaan yhä, että {slicer} käynnistyy. Mitään muuta ei lähetetty.", + "ui.slicer_stl_fallback": "3MF-tiedostoa ei voitu kirjoittaa, joten tämä on STL.", + "ui.slot": "Ura", + "ui.smooth": "Pehmeä", + "ui.smooth_wheel_zoom": "Pehmeä rullazoomaus", + "ui.smooth_wheel_zoom_tip": "Poista käytöstä, jos haluat jokaisen rullatapahtuman vaikuttavan heti ilman pehmennystä", + "ui.snap": "Tartunta", + "ui.spacing": "Väli", + "ui.spacing_2": "Väli 2", + "ui.sphere": "Pallo", + "ui.spline": "Splini", + "ui.split_body": "Jaa kappale", + "ui.stand_up_tip": "Kun STEP- tai IGES-tiedosto avautuu Z ylöspäin, tarjoa neljänneskierrosta X:n ympäri", + "ui.standard": "Vakio", + "ui.start": "Aloita", + "ui.start_over": "Aloita alusta", + "ui.start_page": "Aloitussivu", + "ui.step_values": "Muuta arvoja nuolinäppäimillä ja rullalla", + "ui.step_values_tip": "Kun kirjoitat arvokenttään, ylä- ja alanuoli muuttavat pelkkää lukua 1:llä (Shift: 10, Alt: 0.1), samoin hiiren rulla kentän päällä. Lausekkeet jätetään kirjoitetun mukaisiksi.", + "ui.stitch_tolerance_hint": "tiukka", + "ui.stretch": "Venytä", + "ui.supersampling": "Ylinäytteistys (SSAA)", + "ui.supersampling_adaptive": "Vain kun näkymä on paikallaan", + "ui.supersampling_off": "Pois (1×)", + "ui.suppress": "Ohita", + "ui.suppress_auto_snap": "Estä automaattinen tartunta piirrettäessä / vedettäessä", + "ui.suppress_auto_snap_note": "Oletus: Ctrl/Cmd tai Alt/Option estää kumpikin luonnostartunnan. Rajaa valitsemalla yksi näppäin.", + "ui.sweep": "Pyyhkäisy", + "ui.sweep_follow_direction": "Seuraa suuntaa", + "ui.sweep_keep_as_drawn": "Säilytä piirretyn mukaisena", + "ui.sweep_turn_with_path": "Käänny polun mukana", + "ui.symmetric": "Symmetrinen", + "ui.symmetry": "Symmetria", + "ui.system": "Järjestelmä", + "ui.tab_assemble": "Kokoonpano", + "ui.tab_manage": "Hallinta", + "ui.tab_sheet_metal": "Ohutlevy", + "ui.tab_view": "Näkymä", + "ui.tab_weldments": "Hitsausrakenteet", + "ui.tangent": "Tangentti", + "ui.taper_angle": "Kartiokulma", + "ui.tapped": "Kierteitetty", + "ui.text": "Teksti", + "ui.theme": "Teema", + "ui.thickness": "Paksuus", + "ui.thread": "Kierre", + "ui.tie_ends": "Sido", + "ui.tie_ends_tip": "Rajoita kaikki sitomattomat päät", + "ui.timeline_bottom": "Aikajana alhaalla", + "ui.timeline_left_note": "Pystysuuntainen historia on selaimen vasemmalla puolella. Piirteiden nimet näytetään tai piilotetaan palkista.", + "ui.timeline_left_sidebar": "Vasen sivupalkki", + "ui.tip_angle": "Kärkikulma", + "ui.to_object": "Kohteeseen", + "ui.tool_direction": "Työkalun suunta", + "ui.toolbar_tabs_hidden": "Kaikki työkalurivin välilehdet on piilotettu. Näytä jokin napsauttamalla + tai napsauttamalla tätä hiiren kakkospainikkeella.", + "ui.top": "Ylhäältä", + "ui.top_diameter": "Yläosan halkaisija", + "ui.top_radius": "Yläosan säde", + "ui.torus": "Torus", + "ui.total_angle": "Kokonaiskulma", + "ui.trackpad_pan_tip": "Kahden sormen vieritys panoroi; Fusion-tilassa Shift + kaksi sormea kiertää. Pois: vieritys zoomaa. Hiiren rulla ja nipistys zoomaavat; peukalorulla panoroi sivuttain.", + "ui.trim": "Katkaise", + "ui.turn_up_axis": "Käännä ylöspäin osoittava akseli", + "ui.twist": "Kierto", + "ui.two_finger_scroll_pans": "Kahden sormen vieritys panoroi", + "ui.two_sides": "Kaksi puolta", + "ui.ui_scale": "Käyttöliittymän skaalaus", + "ui.undo": "Kumoa", + "ui.unground": "Vapauta kiinnitys maahan", + "ui.unisolate": "Poista eristys", + "ui.units": "Yksiköt", + "ui.units_of_new_designs": "Uusien mallien yksiköt", + "ui.unlock": "Avaa lukitus", + "ui.unsuppress": "Palauta käyttöön", + "ui.untied_ends_tip": "Koskettaa vain sijainnin perusteella", + "ui.untitled": "Nimetön", + "ui.up_axis_note": "Mikä akseli osoittaa ylöspäin näkymissä (akselinäkymä, Alkuun, Katso kohti). Mallit eivät muutu.", + "ui.updateToCurrentView": "Päivitä nykyiseen näkymään", + "ui.upload": "Lataa palvelimelle", + "ui.vertical_constraint": "Pystysuora-rajoite", + "ui.view_angles": "Näkymän kulmat", + "ui.view_angles_convention": "Asteina ylöspäin osoittavan akselin ympäri. Kääntö 0° on edestä-näkymä, 90° vasemmalta, −90° oikealta, 180° takaa; kallistus 90° on ylhäältä-näkymä; positiivinen kierto kääntää mallia myötäpäivään.", + "ui.view_angles_help": "Näyttää näkymän nyökkäyksen, käännön ja kallistuksen asteina sekä projektion suuntamanipulaattorin alla. Kirjoita tarkat kulmat napsauttamalla lukemaa.", + "ui.view_angles_ortho": "Orto", + "ui.view_angles_persp": "Persp.", + "ui.view_angles_pitch": "Nyökkäys", + "ui.view_angles_readout": "Nyökkäys {pitch} · Kääntö {yaw} · Kallistus {roll}", + "ui.view_angles_roll": "Kallistus", + "ui.view_angles_yaw": "Kääntö", + "ui.view_centre": "Näkymän keskipiste", + "ui.viewport_status_clear": "Poista {name} käytöstä", + "ui.viewport_status_clear_hint": "Poista {name} käytöstä · Esc", + "ui.viewport_status_edges": "{count} särmää", + "ui.viewport_status_from": "suunnasta {direction}", + "ui.viewport_status_key": "Näytä selite: {name}", + "ui.viewport_status_minimum_radius": "Pienin säde", + "ui.viewport_status_pairs": "{count} paria", + "ui.viewport_status_section_hatch": "{setting} · viivoitus", + "ui.viewport_status_section_plane": "Nykyinen taso", + "ui.viewport_status_section_tilted": "kallistettu · {offset}", + "ui.viewport_status_stripes": "{count} raitaa", + "ui.viewport_theme_follow": "Seuraa teemaa", + "ui.visual_shaded_hidden_edges": "Varjostettu, piilosärmät näkyvissä", + "ui.visual_shaded_with_edges": "Varjostettu särmineen", + "ui.visual_style": "Visuaalinen tyyli", + "ui.visual_wireframe": "Rautalanka", + "ui.wheel_zoom_speed": "Hiiren rullan zoomausnopeus", + "ui.width": "Leveys", + "ui.window_system": "Ikkunajärjestelmä", + "ui.window_system_auto": "Automaattinen", + "ui.window_system_wayland": "Wayland", + "ui.window_system_x11": "X11", + "ui.workspace": "työtila", + "ui.workspace_animation_description": "Räjäytyskuvat, liiketutkimukset ja kuvakäsikirjoitukset", + "ui.workspace_available": "Käytettävissä", + "ui.workspace_current": "Nykyinen", + "ui.workspace_design_description": "Luonnostele, mallinna, kokoa ja tarkastele", + "ui.workspace_design_tabs": "Malli · Pinta · Kokoonpano · Lisää · Tarkastele · Hallinta · Näkymä", + "ui.workspace_drawing_description": "2D-piirustukset näkymineen, mittoineen ja nimiöineen", + "ui.workspace_footer": "Kaikki työtilat käsittelevät samaa mallia, historiaa ja valintaa; vain valintanauhan välilehdet vaihtuvat. Vaihdin on lukittu, kun luonnosta tai piirrettä muokataan.", + "ui.workspace_layout": "Työtilan asettelu", + "ui.workspace_manufacture_description": "Viipalointi, työstöradat ja asetukset", + "ui.workspace_planned": "Suunnitteilla", + "ui.workspace_render_description": "Tuotteen esikatselu, näkymäasetukset ja renderöidyt kuvat", + "ui.workspace_render_tabs": "Näkymä · Kuva", + "ui.workspace_simulation_description": "Kuormat, rajoitteet ja tulokset", + "ui.x_distance": "X-etäisyys", + "ui.y_distance": "Y-etäisyys", + "ui.y_up": "Y ylös", + "ui.z_up": "Z ylös", + "ui.zoom": "Zoomaa", + "ui.zoom_to_cursor_tip": "Rulla zoomaa osoittimen alla olevaa pistettä kohti (pois: näkymän keskipistettä kohti)", + "ui.zoom_to_the_cursor": "Zoomaa osoittimeen", + "update.available": "SolidCraft {version} on saatavilla", + "update.button": "Päivitä", + "update.button_version": "Päivitä versioon {version}", + "update.check_automatically": "Tarkista päivitykset automaattisesti", + "update.check_for_updates": "Tarkista päivitykset", + "update.check_now": "Tarkista nyt", + "update.check_unavailable": "Päivitysten tarkistus ei ole käytettävissä tässä asennuksessa.", + "update.checking": "Tarkistetaan…", + "update.copy": "Kopioi", + "update.dmg_opened": "Levykuva on avattu ja tarkistettu: vedä SolidCraft Ohjelmat-kansioon vanhan kopion tilalle ja käynnistä SolidCraft uudelleen.", + "update.download": "Lataa", + "update.download_open": "Lataa ja avaa", + "update.downloading": "Ladataan ja tarkistetaan… {done}/{total} Mt", + "update.failed": "Tarkistus epäonnistui: {error}", + "update.file": "Lataa hakee tiedoston {file}.", + "update.install_failed": "Päivitys ei asentunut: {error}. Mitään ei muutettu; Lataa hakee sen sijaan paketin.", + "update.install_msi": "Asenna (sulkee SolidCraftin)", + "update.installed": "SolidCraft {version} on asennettu. Ota se käyttöön käynnistämällä uudelleen.", + "update.installer_started": "Asennusohjelma käynnistyy, kun SolidCraft suljetaan.", + "update.later": "Muistuta myöhemmin", + "update.managed": "Päivitys saatavilla: päivitä SolidCraft ohjelmassa {manager}", + "update.no_notes": "Tällä julkaisulla ei ole julkaisutietoja.", + "update.package_hint": "Tämä kopio on peräisin lähteestä {kind}. Lataa uusi paketti ja asenna se komennolla:", + "update.prefs_dev": "Tämä on kehitysversio ({version}): se ei tarkista päivityksiä.", + "update.prefs_flatpak": "Flatpak päivittää tämän kopion ({version}): suorita {command} tai käytä ohjelmistokeskusta. SolidCraft ei tarkista päivityksiä.", + "update.prefs_label": "Päivitykset", + "update.prefs_managed": "Tämä on SolidCraft {version}, jota hallitsee {manager}. Tarkistus kysyy GitHubilta uusinta julkaisua eikä lähetä mitään muuta; päivitä SolidCraft ohjelmassa {manager}.", + "update.prefs_note": "Tämä on SolidCraft {version} ({kind}). Tarkistus kysyy GitHubilta uusinta julkaisua eikä lähetä mitään muuta.", + "update.prefs_web": "Lataa sivu uudelleen saadaksesi uusimman verkkosovelluksen. Jos verkko ei ole käytettävissä tai päivityksen lataus ei ehdi valmistua ajoissa, avautuu tallennettu versio; keskeneräinen lataus jatkuu seuraavaa uudelleenlatausta varten.", + "update.refresh_checking": "Etsitään uusinta julkaisua…", + "update.refresh_fallback": "Uudempaa julkaisua ei voitu tarkistaa; päivitetään aiemmin löydettyyn versioon {version}.", + "update.refresh_selected": "Päivitetään versioon {version}.", + "update.release_page": "Avaa julkaisusivu", + "update.restart": "Käynnistä uudelleen nyt", + "update.restart_later": "Myöhemmin", + "update.show": "Näytä päivitys versioon {version}", + "update.skip": "Ohita tämä versio", + "update.system_hint": "Tämä kopio on {kind}. Päivitä se komennolla:", + "update.title": "Päivitys saatavilla", + "update.up_to_date": "SolidCraft on ajan tasalla.", + "update.update_now": "Päivitä nyt", + "update.you_have": "Käytössäsi on {version}.", + "use a positive nominal diameter and a pitch smaller than it": "käytä positiivista nimellishalkaisijaa ja sitä pienempää nousua", + "values must be finite numbers": "arvojen on oltava äärellisiä lukuja", + "values must be numbers or expressions": "arvojen on oltava lukuja tai lausekkeita", + "view.auto_ortho_faces": "Perspektiivi kierrettäessä, ortografinen pinnoille", + "view.render_inspector": "Renderöinnin tarkastelu", + "web.files.insert_drawings_hint": "CAD-tiedostot, verkot, DXF tai SVG avoimeen malliin", + "web.files.insert_stored_drawings_hint": "Avoimeen malliin (CAD-tiedostot, verkot, DXF, SVG)", + "web.open_full": "Avaa SolidCraftissa", + "web.open_link": "Avataanko linkitetty malli?", + "web.open_link_confirm": "Muutoksia on tallentamatta. Avataanko linkitetty malli uudessa välilehdessä?", + "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ valitse · Enter / Tab täydennä · Esc sulje", + "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ valitse · Enter käyttää kirjoittamaasi · Esc sulje", + "⌘Enter continues on GitHub.": "⌘Enter jatkaa GitHubissa." +} diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 94baacf1e..7feae89f0 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "SURFACE DE RACCORD", "BOUNDARY SURFACE": "SURFACE FRONTIÈRE", "BROWSER": "NAVIGATEUR", + "Back to the original order": "Revenir à l'ordre d'origine", "Ball": "Rotule", "Bar": "Plat", "Base Center": "Centre de la base", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Les conceptions que vous ouvrez ou enregistrez apparaissent ici.", "Determined by To Object. Choose Angle to edit the angular extent.": "Déterminé par Jusqu'à l'objet. Choisir Angle pour modifier l'étendue angulaire.", "Diameter": "Diamètre", + "Did this assembly open the wrong way up?": "Cet assemblage s'est-il ouvert dans le mauvais sens ?", + "Did this part open the wrong way up?": "Cette pièce s'est-elle ouverte dans le mauvais sens ?", "Dimension new shapes": "Coter les nouvelles formes", "Direction": "Direction", "Discard": "Abandonner", @@ -553,6 +556,7 @@ "Section": "Coupe", "Section (optional)": "Section (facultative)", "Section position": "Position de la section", + "Sections": "Sections", "Sections (one sketch each)": "Sections (une esquisse chacune)", "Select Other": "Sélectionner un autre", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Sélectionner un autre élément : maintenir le bouton gauche immobile sur le modèle (ou clic droit › Sélectionner un autre…) pour lister tout ce qui se trouve sous le curseur ; cliquer de nouveau au même endroit pour sélectionner l'élément suivant. Double-cliquer avec le bouton du milieu pour revenir à l'accueil (Préférences › Navigation).", @@ -593,6 +597,8 @@ "Snap to face and edge centres": "Accrocher aux centres des faces et des arêtes", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft ne peut pas soumettre directement les rapports. Soumettez-les sur GitHub ; aucun jeton n'est nécessaire dans l'application.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft s'est fermé avant l'enregistrement de ces conceptions. Leur dernier enregistrement automatique peut être ouvert.", + "Sort A to Z": "Trier de A à Z", + "Sort Z to A": "Trier de Z à A", "Spacing 2 must be a non-zero number": "L'espacement 2 doit être un nombre non nul", "Spacing must be a non-zero number": "L'espacement doit être un nombre non nul", "Specialise": "Spécialiser", @@ -601,6 +607,7 @@ "Square": "Carré", "Stand it up": "Redresser", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Redresser : un quart de tour autour de X, sous forme d'une fonction Déplacer que vous pouvez annuler.", + "Stand this assembly up?": "Redresser cet assemblage ?", "Stand this part up?": "Redresser cette pièce ?", "Start angle": "Angle de départ", "Start bulge": "Renflement de début", @@ -772,6 +779,8 @@ "at the face": "sur la face", "bom.group_children": "Sous-pièces dans la ligne de leur pièce", "browser.body_name": "Corps{number}", + "browser.calibrate_click_a": "Cliquez sur l'image pour le point A, ou saisissez ses coordonnées.", + "browser.calibrate_click_b": "Cliquez sur l'image pour le point B, ou saisissez ses coordonnées.", "browser.calibrate_title": "Calibrer : {name}", "browser.capture_many": "{count} composants ont été déplacés, mais leurs positions ne sont pas capturées.", "browser.capture_note": "Capturer la position conserve la nouvelle position ; Rétablir la position restaure la précédente.", @@ -785,6 +794,13 @@ "browser.sketch_attachment_lost": "{name} (attache perdue)", "browser.sketch_editing": "{name} (en cours de modification)", "browser.sketch_name": "Esquisse{number}", + "browser.sketches_to_parts_already_in_part": "déjà dans leur pièce", + "browser.sketches_to_parts_design_body": "sur un corps de la conception elle-même", + "browser.sketches_to_parts_moved": "{moved} esquisses déplacées vers la pièce sur laquelle elles se trouvent", + "browser.sketches_to_parts_no_exact_attachment": "sur une face sans rattachement exact", + "browser.sketches_to_parts_not_on_face": "pas sur la face d'une pièce", + "browser.sketches_to_parts_part_missing": "leur pièce n'existe plus", + "browser.sketches_to_parts_result": "{moved} esquisses déplacées vers la pièce sur laquelle elles se trouvent ; {stayed} sont restées en place : {why}", "browser.units": "Unités : {units}", "cam.flat": "Plateau", "cam.follower": "Suiveur", @@ -814,6 +830,8 @@ "cmd.appearance_pick_up": "Prélever l'apparence", "cmd.appearance_replace": "Remplacer l'apparence", "cmd.assembly_bom": "Nomenclature", + "cmd.assembly_mass_properties": "Propriétés de masse", + "cmd.body.print_face": "Face d’impression", "cmd.body_rename": "Renommer le corps", "cmd.browser_collapse_all": "Tout réduire", "cmd.browser_expand_all": "Tout développer", @@ -842,6 +860,7 @@ "cmd.component_extract": "Extraire dans un fichier", "cmd.component_finish_edit": "Terminer la modification", "cmd.component_from_bodies": "Créer des composants à partir des corps", + "cmd.component_hide_history": "Masquer l'historique du composant", "cmd.component_insert_design": "Insérer une conception", "cmd.component_links": "Lister les liens", "cmd.component_list": "Lister les composants", @@ -850,6 +869,7 @@ "cmd.component_move_bodies": "Déplacer les corps vers le composant", "cmd.component_move_features": "Déplacer les fonctions vers le composant", "cmd.component_move_sketches": "Déplacer les esquisses vers le composant", + "cmd.component_move_sketches_to_parts": "Déplacer les esquisses vers leurs pièces", "cmd.component_paste_from_design": "Coller depuis une autre conception", "cmd.component_paste_new": "Coller comme nouveau", "cmd.component_properties": "Propriétés physiques du composant", @@ -857,6 +877,7 @@ "cmd.component_rename": "Renommer le composant", "cmd.component_replace_with_link": "Remplacer par un lien", "cmd.component_revert_position": "Rétablir la position", + "cmd.component_show_history": "Afficher l'historique du composant", "cmd.component_unlock": "Déverrouiller le contenu", "cmd.component_update_links": "Mettre à jour les liens", "cmd.config_activate": "Activer la configuration", @@ -867,6 +888,7 @@ "cmd.config_rule": "Règle de configuration", "cmd.config_rules": "Règles de configuration", "cmd.config_table": "Afficher la table des configurations", + "cmd.construct.plane.axis_point": "Plan passant par un axe et un point", "cmd.construct_axis_edge": "Axe passant par une arête", "cmd.construct_axis_normal_to_face": "Axe perpendiculaire à une face", "cmd.construct_axis_through_cylinder": "Axe d'un cylindre/cône/tore", @@ -915,6 +937,11 @@ "cmd.explode_show": "Afficher la vue éclatée", "cmd.expr_evaluate": "Évaluer une expression", "cmd.face_delete": "Supprimer la face", + "cmd.file.export_3mf": "Exporter en 3MF", + "cmd.file.export_obj": "Exporter en OBJ", + "cmd.file.export_step": "Exporter en STEP", + "cmd.file.export_stl": "Exporter en STL", + "cmd.file.export_urdf": "Exporter en URDF", "cmd.file_export": "Exporter", "cmd.file_insert_mesh": "Insérer un maillage", "cmd.file_insert_step": "Insérer un STEP", @@ -932,6 +959,7 @@ "cmd.inspect_colored_components": "Activer les couleurs des composants", "cmd.inspect_colored_components_disable": "Désactiver les couleurs des composants", "cmd.inspect_compare": "Comparer les corps", + "cmd.inspect_compare_picture": "Comparer les images", "cmd.inspect_continuity": "Analyse de continuité", "cmd.inspect_curvature_comb": "Analyse par peigne de courbure", "cmd.inspect_curvature_map": "Analyse par carte de courbure", @@ -1022,6 +1050,9 @@ "cmd.pointcloud_edit": "Modifier le nuage de points", "cmd.pointcloud_insert": "Insérer un nuage de points", "cmd.pointcloud_list": "Nuages de points", + "cmd.render.compare.divider": "Déplacer le séparateur de comparaison des rendus", + "cmd.render.result.discard": "Écarter le résultat de rendu", + "cmd.render.result.select": "Sélectionner le résultat de rendu", "cmd.render_aging_describe": "Vieillissement de surface en couches", "cmd.render_backends": "Moteurs de rendu", "cmd.render_batch": "Rendre toutes les prises de vue", @@ -1185,6 +1216,7 @@ "cmd.sketch_spline_control_point_5": "Spline par points de contrôle (degré 5)", "cmd.sketch_spline_fit_point": "Spline par points", "cmd.sketch_spline_insert_point": "Ajouter un point de spline", + "cmd.sketch_spline_remove_point": "Supprimer un point de spline", "cmd.sketch_spline_reverse": "Inverser le sens de la spline", "cmd.sketch_spun_profile": "Profil de révolution", "cmd.sketch_toggle_diameter": "Basculer rayon / diamètre", @@ -1235,9 +1267,11 @@ "cmd.timeline_rollback": "Déplacer le marqueur de chronologie", "cmd.timeline_stop": "Arrêter l'historique", "cmd.timeline_suppress": "Désactiver la fonction", + "cmd.ui.assistant": "Afficher/masquer l'assistant", "cmd.view.render_browser": "Navigateur de rendu", "cmd.view.render_dock": "Déplacer le panneau de rendu", "cmd.view.render_focus": "Vue de rendu ciblée", + "cmd.view.status_details": "Détails d'état de la vue 3D", "cmd.view.status_items": "Éléments d'état de la vue 3D", "cmd.view_ambient_occlusion": "Occlusion ambiante", "cmd.view_angle_readout": "Angles de vue", @@ -1268,17 +1302,28 @@ "cmd.view_tool": "Outil de navigation", "cmd.view_top": "Vue de dessus", "cmd.view_visual_style": "Style visuel", + "color.blue": "Bleu", "color.copy": "Cliquer pour copier les valeurs de couleur", "color.edit": "Cliquer pour modifier la couleur", "color.gamma": "Valeurs de couleur affichées en espace gamma 0-255", + "color.green": "Vert", "color.hex": "Hex", "color.hex_help": "Saisissez #rrggbb ou #rrggbbaa ; six chiffres conservent l'opacité", "color.hex_hint": "#rrggbb", "color.hue": "Teinte", "color.linear": "Valeurs de couleur affichées en espace linéaire 0-1", + "color.recent": "Couleurs récentes", + "color.recent_help": "Les couleurs choisies dans n'importe quel champ de couleur apparaissent ici", + "color.red": "Rouge", + "color.saturation": "Saturation (pour cent)", "color.saturation_value": "Saturation et valeur", "color.selected": "Couleur sélectionnée", + "color.step_down": "Diminuer d'un pas", + "color.step_up": "Augmenter d'un pas", + "color.value": "Valeur, la luminosité (pour cent)", "config.column_filter_empty": "Aucune colonne correspondante", + "config.rule_parameter_columns": "Seuls les paramètres ayant une colonne dans la table sont listés. Ajouter une colonne avec Ajouter une colonne (+) pour l'utiliser ici.", + "config.rule_suppression_columns": "Seules les fonctions ayant une colonne Désactiver dans la table sont listées. Ajouter une colonne avec Ajouter une colonne (+) pour la piloter ici.", "contact.components_count": "{count} composants", "contact.enabled_label": "activé", "coupling.gear_1": "Engrenage 1", @@ -1323,9 +1368,15 @@ "dialog.dimension_insert_hint": "Double-cliquez sur une autre cote pilotante pour insérer son nom", "dialog.dimension_name": "Cote : {name}", "dialog.edit_title": "MODIFIER {title}", + "dialog.no_shown_body": "Aucun corps affiché à modifier : affichez-en un ou choisissez Nouveau corps", + "dialog.pattern_sketch_not_object": "Choisissez des corps ou des fonctions : une esquisse n'est ni l'un ni l'autre. Répétez ses courbes avec la Répétition ou la Symétrie de l'esquisse, ou extrudez-la d'abord.", "dialog.select": "↖ Sélectionner", "dialog.selected_count": "↖ {count} sélectionné(s)", + "dialog.selection_constraint": "Contrainte {id}", + "dialog.selection_external_curve": "{sketch} · courbe {id}", "dialog.selection_guidance": "Sélectionner une entrée pour la modifier. Cliquer sur un objet sélectionné pour le retirer ; Ctrl/Cmd-clic le bascule aussi. Vérifier l'aperçu, puis appuyer sur OK.", + "dialog.selection_midpoint": "Point milieu · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} sur {total} : sélectionner {input}", "dialog.step": "Étape", "document.changed_on_disk": "{name} a été modifié sur le disque", @@ -1340,6 +1391,7 @@ "document.read_only_save": "Cette conception a été ouverte en lecture seule : enregistrez-la dans un nouveau fichier", "document.save_changes": "Enregistrer les modifications de {name} ?", "document.save_copy": "Enregistrer une copie…", + "document.tab_unsaved_changes": "Modifications non enregistrées", "document.unsaved_changes": "{name} contient des modifications non enregistrées. Si vous n'enregistrez pas, elles seront perdues.", "drive.rigid": "{joint} est une liaison rigide : elle maintient ses pièces immobiles, il n'y a donc rien à piloter. Pour les laisser bouger, changer son type dans Modifier la liaison : Revolute pour tourner, Slider pour coulisser, Cylindrical pour les deux.", "drive.stopped_by_contact": "Arrêté à {value} : {a} traverserait {b}", @@ -1380,26 +1432,244 @@ "from the rule": "selon la règle", "help.apache": "Licence Apache 2.0", "help.appearance.assign": "Donne aux corps, faces ou composants sélectionnés une couleur ou l'apparence d'un matériau, sans changer leur poids. À utiliser pour distinguer des pièces ou prévisualiser une finition.", + "help.assembly.bom": "Liste les pièces de la conception ou d'un composant avec leurs quantités, par référence, et peut enregistrer la liste en CSV ou JSON. À utiliser comme nomenclature pour la commande et l'assemblage.", "help.attributions": "Attributions (ATTRIBUTION.md)", "help.build": "Version {version} · commit {commit} · compilée le {date}", + "help.canvas.decal": "Place une image sur une face plane du modèle, comme un autocollant. À utiliser pour afficher une étiquette, un logo ou un motif imprimé sur une pièce.", + "help.canvas.edit": "Modifie un canevas : sa position, sa taille, son angle, son opacité, sa symétrie, sa visibilité ou son nom. À utiliser pour aligner une image de référence sur l'esquisse que vous décalquez.", + "help.canvas.insert": "Place une image PNG ou JPEG sur un plan ou une face comme référence translucide. À utiliser pour décalquer une photo ou un dessin dans une esquisse, l'image étant mise à une échelle connue.", + "help.component.break_link": "Détache un composant lié de son fichier de conception en conservant ses corps tels quels. À utiliser lorsque la pièce ne doit plus suivre les modifications du fichier d'origine.", + "help.component.capture_position": "Conserve les positions des pièces que vous avez déplacées à la main, qui deviennent leur nouvelle position. À utiliser après avoir fait glisser en place des pièces qu'aucune liaison ne maintient.", + "help.component.create": "Ajoute un composant vide à la conception, dans le composant actif sauf si vous choisissez un autre parent. À utiliser pour donner à une nouvelle pièce d'un assemblage son propre espace pour les corps et les esquisses.", "help.component.finish_edit": "Enregistre la pièce que vous modifiez sur place, revient à son assemblage et met à jour l'assemblage à partir d'elle. À utiliser lorsque vos modifications de la pièce liée sont terminées.", + "help.component.from_bodies": "Transforme chaque corps sélectionné en composant à part entière, portant le nom du corps. À utiliser lorsqu'une conception faite de corps isolés doit devenir un assemblage dont les pièces peuvent être reliées et déplacées.", + "help.component.insert_design": "Insère une autre conception enregistrée comme composant lié à son fichier, avec ses corps solides placés comme dans ce fichier. À utiliser pour réutiliser une pièce dans un assemblage et récupérer les modifications ultérieures avec Mettre à jour les liens.", + "help.component.properties": "Affiche le volume, la masse, le centre de gravité et les moments d'inertie d'un composant, d'après les matériaux de ses corps. À utiliser pour vérifier le poids et l'équilibre d'un assemblage.", + "help.component.revert_position": "Remet à leur place les pièces que vous avez déplacées à la main, en abandonnant les déplacements non capturés. À utiliser pour annuler des essais de déplacement dans un assemblage.", + "help.component.update_links": "Relit les fichiers de conception liés et remplace les corps qui ont changé. À utiliser après avoir modifié une pièce utilisée par cet assemblage.", + "help.config.configure": "Ajoute des paramètres, des fonctions, des matériaux ou des apparences comme colonnes de la table des configurations. À utiliser pour créer des variantes d'une conception, par exemple les tailles d'une pièce.", + "help.config.preview": "Vérifie qu'une ligne de la table des configurations se reconstruit, sans modifier la conception ni son historique. À utiliser avant de basculer vers une variante incertaine.", + "help.config.rules": "Affiche les règles de la table des configurations, ses lignes et la ligne active. À utiliser pour voir comment les variantes d'une conception sont définies.", + "help.config.table": "Affiche la table des configurations : une ligne par variante, une colonne par paramètre ou fonction, et si la conception correspond toujours à la ligne active. À utiliser pour passer en revue les variantes d'une conception.", "help.connect_note": "Redémarrez chaque assistant pour charger le serveur SolidCraft. Chaque fichier a été sauvegardé en .bak avant d'être modifié.", "help.connect_title": "Connecter les assistants IA", + "help.construct.axis.edge": "Crée un axe de construction le long d'une arête droite ou d'une ligne d'esquisse. À utiliser comme axe pour une révolution, une répétition circulaire ou une liaison.", + "help.construct.axis.normal_to_face": "Crée un axe de construction passant par un point, perpendiculaire à une face. À utiliser comme axe qui sort droit d'une surface.", + "help.construct.axis.through_cylinder": "Crée un axe de construction passant par le centre d'une face cylindrique, conique ou torique, ou d'une arête circulaire. À utiliser pour faire tourner ou répéter des fonctions autour d'une pièce ronde.", + "help.construct.axis.two_planes": "Crée un axe de construction là où deux plans ou faces planes se rencontrent. À utiliser lorsque l'axe voulu est la droite entre deux faces.", + "help.construct.axis.two_points": "Crée un axe de construction passant par deux points, sommets ou points d'esquisse. À utiliser pour un axe qui relie deux positions connues.", + "help.construct.plane.along_path": "Crée un plan de construction perpendiculaire à une arête ou une courbe, à une position choisie le long de celle-ci. À utiliser pour esquisser le profil d'un balayage ou une coupe d'une trajectoire.", + "help.construct.plane.at_angle": "Crée un plan de construction tourné d'un angle par rapport à un plan ou une face, autour d'un axe ou d'une arête. À utiliser pour des esquisses inclinées, par exemple une équerre à angle.", + "help.construct.plane.axis_point": "Crée un plan de construction contenant un axe et un point situé hors de cet axe. Sélectionner une origine ou un axe de construction, une arête rectiligne ou une ligne d'esquisse, puis un sommet, un point d'esquisse ou un point de construction. Un point situé sur l'axe ne définit pas un plan unique.", + "help.construct.plane.midplane": "Crée un plan de construction à mi-distance entre deux plans ou faces planes, ou bissecteur lorsqu'ils se rencontrent en formant un angle. À utiliser comme plan de symétrie.", + "help.construct.plane.offset": "Crée un plan de construction parallèle à un plan ou une face plane, à une distance donnée ou passant par un point. À utiliser pour esquisser à une hauteur précise au-dessus d'une face.", + "help.construct.plane.perpendicular": "Crée un plan de construction qui contient une droite ou une arête et qui est perpendiculaire à un plan ou une face. À utiliser pour esquisser à la verticale sur un modèle, le long d'une arête.", + "help.construct.plane.tangent": "Crée un plan de construction qui touche un cylindre, un cône, une sphère ou un tore en un point. À utiliser pour esquisser sur le flanc d'une pièce ronde.", + "help.construct.plane.three_points": "Crée un plan de construction passant par trois points. À utiliser pour un plan défini par des positions du modèle, comme trois coins.", + "help.construct.plane.two_edges": "Crée un plan de construction passant par deux arêtes droites ou lignes situées dans un même plan. À utiliser pour un plan à travers une pièce, par exemple par deux arêtes opposées.", + "help.construct.point.along_path": "Crée un point de construction à une position donnée le long d'une arête ou d'une courbe. À utiliser comme référence à mi-chemin sur une trajectoire.", + "help.construct.point.center": "Crée un point de construction au centre d'une arête circulaire, d'un cercle ou arc d'esquisse, d'une sphère ou d'un tore. À utiliser comme référence pour des perçages, des axes et des liaisons.", + "help.construct.point.edge_plane": "Crée un point de construction là où une arête ou une ligne traverse un plan ou une face plane. À utiliser pour repérer où une trajectoire coupe un plan.", + "help.construct.point.three_planes": "Crée un point de construction là où trois plans ou faces planes se rencontrent. À utiliser comme référence de coin, même lorsque le modèle n'a pas de sommet à cet endroit.", + "help.construct.point.two_edges": "Crée un point de construction là où deux arêtes ou lignes se rencontrent, ou se rapprochent le plus. À utiliser comme référence à un coin virtuel.", + "help.construct.point.vertex": "Crée un point de construction sur un sommet ou un point d'esquisse. À utiliser comme référence qui subsiste lorsque l'esquisse ou le corps qui l'entoure est masqué.", + "help.contact.check": "Liste les paires de pièces des jeux de contact qui se traversent dans leur position actuelle. À utiliser pour trouver les collisions avant de piloter les liaisons ou de lancer une étude de mouvement.", + "help.contact.create": "Regroupe deux pièces ou plus dans un jeu de contact, dont les corps ne peuvent pas se traverser pendant le mouvement des liaisons. À utiliser pour des pièces qui doivent s'arrêter au contact, comme un levier contre sa butée.", + "help.contact.disable_all": "Désactive le contact : les liaisons pilotées et les études de mouvement ne s'arrêtent plus là où les pièces se touchent. À utiliser pour déplacer à nouveau les pièces librement, ou pour garder un grand assemblage réactif.", + "help.contact.edit": "Modifie un jeu de contact : les pièces qu'il contient, son nom, ou s'il est désactivé ; peut aussi supprimer le jeu. À utiliser pour ajuster les pièces qui ne doivent pas se traverser.", + "help.contact.enable_all": "Place toutes les pièces de l'assemblage dans un seul jeu de contact, de sorte qu'aucune paire de pièces ne puisse se traverser pendant le mouvement des liaisons. À utiliser pour une vérification rapide d'un mécanisme entier.", + "help.contact.enable_sets": "Active le contact pour les jeux de contact que vous avez définis, de sorte que les liaisons pilotées et les études de mouvement s'arrêtent là où leurs pièces se traverseraient. À utiliser pour retrouver vos jeux après avoir désactivé le contact.", + "help.contact.list": "Liste les jeux de contact de la conception, les pièces de chacun et si le contact est activé. À utiliser pour vérifier la configuration du contact avant de piloter l'assemblage.", + "help.document.inspect": "Affiche une vue d'ensemble de la conception : ses composants, corps, esquisses, fonctions et paramètres. À utiliser pour se repérer dans une conception que vous n'avez pas créée vous-même.", + "help.document.units": "Change les unités dans lesquelles la conception affiche les longueurs, par exemple mm ou pouces. La géométrie garde sa taille ; seuls l'affichage et les nombres bruts suivent.", + "help.edit.checkpoint": "Mémorise la conception, l'esquisse active et l'historique d'annulation dans leur état actuel. À utiliser avant un essai risqué dont vous voudrez peut-être revenir.", + "help.edit.restore_checkpoint": "Revient à un point de restauration, historique d'annulation compris. À utiliser pour abandonner en une seule étape tout ce qui a été fait depuis ce point.", + "help.explode.create": "Crée une vue éclatée qui écarte les pièces du centre de l'assemblage, ou selon les déplacements que vous définissez. À utiliser pour montrer comment un assemblage se monte, pour des notices ou des présentations.", "help.face.delete": "Supprime les faces sélectionnées et laisse les faces voisines refermer le vide, ou laisse le trou ouvert. À utiliser pour retirer un arrondi, un trou ou un bossage qui gêne.", + "help.file.insert_mesh": "Ajoute un fichier 3MF, STL, OBJ, PLY ou glTF à la conception sous forme de corps maillés dans un nouveau composant. À utiliser pour placer à côté de votre conception un modèle téléchargé ou numérisé comme référence.", + "help.file.insert_step": "Ajoute un fichier STEP, IGES, FreeCAD ou Rhino à la conception sous forme de corps solides dans un nouveau composant ; les pièces d'un assemblage deviennent des composants imbriqués. À utiliser pour importer des modèles de fournisseurs ou d'autres logiciels de CAO.", + "help.file.save_mesh": "Enregistre des corps en maillage STL, 3MF ou OBJ, avec la finesse des faces courbes que vous choisissez. À utiliser pour préparer des pièces à l'impression 3D ou pour des logiciels qui lisent des maillages.", + "help.file.send_to_slicer": "Enregistre les corps sélectionnés en fichier 3MF et l'ouvre dans le slicer de votre choix. À utiliser pour passer du modèle à l'impression en une seule étape.", "help.font_details": "L’interface utilise les polices intégrées d’egui (Ubuntu Light et Hack, sous les licences Ubuntu Font Licence et MIT/Bitstream Vera ; Noto Emoji et la police d’icônes emoji, sous OFL et MIT). Le texte des esquisses utilise Liberation Sans (SIL OFL 1.1). Le pack de polices facultatif de The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic ; SIL OFL 1.1), n’est pas inclus dans les versions de SolidCraft.", "help.fonts": "Polices", + "help.frame.member": "Place un profilé, tel qu'un tube ou un profilé d'aluminium, le long des lignes d'une esquisse de structure, un élément par ligne. À utiliser pour construire des châssis, des racks et des structures soudées.", + "help.inspect.accessibility": "Colore les faces qu'un outil peut atteindre depuis une direction, et celles qu'il ne peut pas atteindre. À utiliser pour vérifier l'usinabilité ou le moulage d'une pièce depuis ce côté.", + "help.inspect.center_of_mass": "Affiche le centre de gravité des corps, de chacun séparément et de l'ensemble, à densité uniforme. À utiliser pour vérifier l'équilibre et l'endroit où une pièce basculera.", + "help.inspect.colored_components": "Donne à chaque composant sa propre couleur temporaire, sans modifier les apparences. À utiliser pour distinguer d'un coup d'œil les pièces d'un assemblage.", + "help.inspect.compare": "Compare deux corps et montre où l'un a de la matière que l'autre n'a pas, avec le volume et l'écart. À utiliser pour comparer une pièce modifiée ou importée à l'original.", + "help.inspect.continuity": "Vérifie la douceur de raccord des faces le long de leurs arêtes : jeux, cassures ou sauts de courbure, et colore les raccords. À utiliser pour trouver où des surfaces ne se raccordent pas proprement.", + "help.inspect.curvature_comb": "Trace des peignes le long de courbes, d'arêtes ou de faces, dont les dents montrent l'intensité de la courbure. À utiliser pour repérer les méplats, les cassures et les courbures irrégulières.", + "help.inspect.curvature_map": "Colore les faces selon l'intensité de leur courbure, en rouge là où le rayon est petit. À utiliser pour trouver les zones serrées et juger la douceur d'une surface.", + "help.inspect.draft": "Colore les faces selon leur angle de dépouille par rapport à une direction de démoulage, et signale celles qui en manquent. À utiliser pour vérifier une pièce avant moulage ou coulée.", + "help.inspect.environment_map": "Affiche le modèle avec une finition réfléchissante, de type miroir. À utiliser pour juger la fluidité des surfaces d'après la façon dont les reflets les parcourent.", + "help.inspect.interference": "Trouve les corps qui se chevauchent et montre chaque chevauchement avec son volume. À utiliser pour vérifier qu'aucune pièce d'un assemblage n'entre en collision.", + "help.inspect.isocurve": "Trace les courbes isoparamétriques des faces, c'est-à-dire la grille sur laquelle la surface est construite. À utiliser pour voir comment une surface s'écoule et où elle se resserre.", + "help.inspect.measure": "Mesure des longueurs, distances, angles, aires et rayons entre les éléments choisis, ou le volume et la masse de corps. À utiliser pour vérifier des dimensions et des jeux.", + "help.inspect.minimum_radius": "Trouve le plus petit rayon de courbure de courbes, d'arêtes ou de faces, et son emplacement. À utiliser pour vérifier qu'un outil ou une buse peut suivre la forme.", + "help.inspect.section": "Ouvre la vue selon un plan de coupe et hachure les faces coupées, sans modifier le modèle. À utiliser pour regarder à l'intérieur des pièces et des assemblages.", + "help.inspect.zebra": "Affiche des bandes noires et blanches réfléchies sur les faces du modèle. À utiliser pour juger la douceur : des bandes qui se cassent ou se brisent sur une arête révèlent une mauvaise transition.", + "help.joint.as_built": "Relie deux pièces là où elles se trouvent déjà, sans déplacer aucune des deux, et définit comment elles peuvent encore bouger. À utiliser pour des pièces déjà placées dans leur position finale.", + "help.joint.cam": "Relie une came tournante à un suiveur, qui glisse ou pivote lorsque le contour de la came passe dessous. À utiliser pour des cames, des excentriques et des commandes de soupapes.", + "help.joint.create": "Relie deux pièces aux origines de liaison que vous choisissez et déplace la seconde pièce en place ; le type de liaison définit comment elles peuvent encore bouger. À utiliser pour construire un assemblage dont les pièces se déplacent comme le vrai mécanisme.", + "help.joint.drive": "Définit l'angle ou la distance d'une liaison et déplace les pièces en conséquence, dans ses limites ; les liaisons couplées et les boucles fermées suivent. À utiliser pour vérifier qu'un mécanisme se déplace comme prévu.", + "help.joint.gear": "Couple deux liaisons rotatives avec un rapport d'engrenage, de sorte que piloter l'une fait tourner l'autre. À utiliser pour des engrenages droits et des couronnes, avec le rapport tiré des rayons primitifs ou des nombres de dents.", + "help.joint.limits": "Définit jusqu'où une liaison peut tourner ou coulisser, par un minimum et un maximum, ou supprime ces limites. À utiliser pour garder une charnière, une glissière ou un levier dans sa course réelle.", + "help.joint.motion_link": "Couple deux liaisons avec un rapport et un décalage, de sorte que piloter l'une déplace l'autre. À utiliser pour une relation fixe entre liaisons que Engrenage, Pignon et crémaillère ou Vis ne couvrent pas.", + "help.joint.origin": "Place sur une pièce une origine de liaison nommée : au centre d'une face ou d'une extrémité ronde, au milieu d'une arête, à un coin ou en un point. À utiliser pour préparer l'emplacement des liaisons ; une origine choisie sur une face la suit lorsque la pièce change de taille.", + "help.joint.rack_pinion": "Relie un pignon tournant à une crémaillère coulissante, de sorte que la crémaillère avance de la longueur de cercle primitif que le pignon parcourt en roulant. À utiliser pour des commandes à crémaillère, des directions et des axes linéaires.", + "help.joint.reach": "Déplace un point d'une pièce vers une cible en modifiant les liaisons de sa chaîne, dans leurs limites. À utiliser pour positionner un mécanisme selon l'endroit où doit se trouver son extrémité, comme le bout d'un bras de robot.", + "help.joint.rigid_group": "Verrouille ensemble les pièces sélectionnées telles qu'elles sont, pour qu'elles se déplacent d'un seul bloc. À utiliser pour des pièces qui vont ensemble et qui n'ont aucun mouvement entre elles.", + "help.joint.screw": "Couple rotation et translation par un pas, de sorte que chaque tour avance de cette distance. À utiliser pour des vis mères, des boulons et des broches filetées.", + "help.library.apply": "Applique un matériau ou une apparence d'un fichier de bibliothèque local à des corps, des faces ou des composants. À utiliser pour réutiliser des matériaux enregistrés depuis une autre conception.", + "help.library.export": "Enregistre les matériaux et apparences de la conception dans un fichier de bibliothèque. À utiliser pour les partager ou les réutiliser dans d'autres conceptions.", + "help.library.inspect": "Vérifie un fichier de bibliothèque et liste ses matériaux et apparences, sans modifier la conception. À utiliser pour voir ce que contient une bibliothèque avant de l'appliquer.", "help.licences": "Licences", "help.material.assign": "Applique le matériau choisi aux corps sélectionnés, par exemple acier, aluminium ou ABS. À utiliser pour que la masse et le poids correspondent à la pièce réelle.", + "help.material.properties.validate": "Vérifie qu'une fiche de données de matériau a des valeurs cohérentes et qu'aucune n'est manquante. À utiliser avant de se fier aux données pour la masse ou la rigidité.", + "help.mesh.convert": "Reconstruit un corps maillé, tel qu'un STL, en solide modifiable avec des faces planes et cylindriques. À utiliser pour modifier une pièce mécanique importée comme un corps modélisé.", "help.mit": "Licence MIT", + "help.motion.study": "Définit des valeurs de liaison à des étapes le long d'une chronologie et les rejoue sous forme d'animation. À utiliser pour voir un mécanisme se déplacer selon une séquence et vérifier les jeux en chemin.", + "help.motion.trace": "Trace le chemin que suit un point d'une pièce pendant la lecture d'une étude de mouvement ou le pilotage d'une liaison, et le conserve comme courbe d'esquisse 3D lorsque vous confirmez. À utiliser pour voir où arrive un mécanisme, ou pour construire à partir de sa trajectoire.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fixe une pièce en place, ou la libère, de sorte que les liaisons déplacent les autres pièces autour d'elle. À utiliser pour le châssis ou la base sur laquelle le reste de l'assemblage est construit.", "help.occurrence.move": "Déplace une pièce d’assemblage selon les seules libertés permises par ses liaisons. Sélectionnez une face de la pièce, puis faites glisser une flèche ou un arc disponible.", "help.parameters.change": "Ouvre le tableau des valeurs nommées et des expressions qui pilotent les cotes de la conception. À utiliser pour changer une dimension à un seul endroit et faire suivre toutes les fonctions qui l'utilisent.", + "help.parameters.export": "Enregistre les paramètres de la conception en CSV ou JSON. À utiliser pour les modifier dans un tableur ou les transférer vers une autre conception.", + "help.parameters.graph": "Montre quels paramètres et fonctions en utilisent quels autres, ainsi que les boucles ou erreurs entre eux. À utiliser pour voir ce que la modification d'un paramètre va affecter.", + "help.parameters.import": "Lit des paramètres depuis un CSV ou un JSON dans la conception, tous ou aucun. À utiliser pour importer des valeurs d'un tableur ou d'une autre conception.", + "help.parameters.move": "Déplace un paramètre utilisateur avant ou après un autre dans la liste. À utiliser pour garder ensemble les paramètres liés.", + "help.parts.fastener": "Ajoute une vis, un boulon, un écrou, une rondelle, une goupille ou un roulement standard à la taille choisie. Placé sur un perçage, il s'y loge avec une liaison, ce qui évite de modéliser soi-même les fixations.", + "help.parts.insert": "Insère une pièce standard de la famille, de la taille et de la longueur choisies. Placée sur le bord ou la paroi d'un perçage, elle s'y loge avec une liaison rigide.", + "help.parts.library": "Ouvre les pièces standard : vis, boulons, écrous, rondelles, vis sans tête, goupilles cylindriques et roulements en tailles normalisées. À utiliser pour ajouter une pièce standard plutôt que de la modéliser soi-même.", + "help.parts.resize": "Change la taille ou la longueur d'une pièce standard insérée et la reconstruit ; ses liaisons la maintiennent en place. À utiliser lorsqu'une vis se révèle trop longue ou qu'un perçage demande une autre taille.", + "help.plastic.assign_rule": "Affecte une règle plastique à des corps, de sorte que leurs fonctions plastique prennent sa dépouille et son jeu par défaut. À utiliser pour configurer une pièce moulée une fois pour toutes ses fonctions.", + "help.plastic.boss": "Ajoute un bossage de vis sur une face : un plot avec perçage, dépouille, congé de pied et nervures de soutien facultatifs. À utiliser pour les points de vissage des boîtiers moulés ou imprimés.", + "help.plastic.lip": "Ajoute une lèvre ou une rainure correspondante le long du bord d'un corps évidé. À utiliser pour que deux moitiés de boîtier se positionnent l'une sur l'autre et se ferment hermétiquement.", + "help.plastic.manage_rules": "Crée et modifie des règles plastique : matériau, épaisseur de paroi, rayons, jeu et dépouille. À utiliser pour garder cohérentes les fonctions d'une pièce moulée.", + "help.plastic.rest": "Ajoute un appui sur une face : un plot rond ou rectangulaire, plein ou creux, avec dépouille. À utiliser comme support ou entretoise dans un boîtier moulé.", + "help.plastic.snap_fit": "Ajoute un crochet de clip sur une face, avec sa longueur, son épaisseur et son ergot. À utiliser pour assembler des pièces par encliquetage sans vis.", "help.pointcloud.insert": "Insère un scan PLY, XYZ ou PTS sous forme de nuage de points à côté du modèle. Utilisez-le comme référence pour construire un modèle à partir de données mesurées.", + "help.sheet.convert": "Transforme une plaque ou un corps évidé d'épaisseur uniforme en corps de tôlerie, avec des plis aux arêtes choisies. À utiliser pour rendre une pièce existante dépliable.", + "help.sheet.export_bend_table": "Enregistre la table des plis d'un corps de tôlerie en CSV ou JSON : angles, rayons et positions des plis à plat. À utiliser pour la plieuse ou l'atelier.", + "help.sheet.export_dxf": "Enregistre la mise à plat en DXF, avec contours, lignes de pli et annotations de pli facultatives. À utiliser pour la découpe laser, plasma ou jet d'eau.", + "help.sheet.flange": "Ajoute un bord tombé : une plaque de base à partir d'une esquisse, une paroi le long d'un contour d'esquisse ouvert, ou une paroi pliée sur des arêtes de tôle. À utiliser pour construire des pièces de tôlerie.", + "help.sheet.flat_pattern": "Crée la mise à plat d'un corps de tôlerie, avec sa taille, ses découpes et ses lignes de pli. À utiliser pour vérifier le flan avant de le découper.", + "help.sheet.fold": "Plie une tôle le long d'une ligne d'esquisse selon un angle et un rayon. À utiliser pour plier une tôle plate après y avoir découpé des fonctions.", + "help.sheet.hem": "Replie un bord de tôle sur lui-même. À utiliser pour obtenir des bords sûrs et rigides, sans bavures coupantes.", + "help.sheet.manage_rules": "Crée et modifie des règles de tôlerie : épaisseur, rayon de pli, facteur K, dégagements et jeux. À utiliser pour s'adapter au matériau et aux outils de votre atelier.", + "help.sheet.path_flange": "Ajoute une chaîne de bords tombés le long d'une arête de tôle, en suivant une chaîne ouverte de lignes d'esquisse. À utiliser pour des profils en U ou en Z en une seule étape.", + "help.sheet.perforate": "Ajoute un champ de trous sur toute la tôle à plat, en motif décalé ou carré. À utiliser pour des aérations, des grilles et des panneaux allégés.", + "help.sheet.refold": "Replie un corps de tôlerie déplié. À utiliser après avoir ajouté des fonctions à la tôle à plat.", + "help.sheet.unfold": "Déplie tous les plis d'un corps de tôlerie. À utiliser pour ajouter des trous ou des découpes qui doivent traverser un pli, puis replier.", + "help.sketch.arc.center_point": "Dessine un arc de cercle autour d'un centre, d'un point de départ à un point d'arrivée. À utiliser lorsque le centre de l'arc est connu, comme un rayon autour d'un perçage ou d'un pivot.", + "help.sketch.arc.tangent": "Dessine un arc qui part de l'extrémité d'une ligne ou d'un arc et continue en tangence avec lui. À utiliser pour poursuivre une chaîne avec une courbe douce plutôt qu'un angle.", + "help.sketch.arc.three_point": "Dessine un arc d'un point de départ à un point d'arrivée en passant par un troisième point. À utiliser lorsque l'arc doit passer par des points donnés plutôt qu'autour d'un centre connu.", + "help.sketch.arc3d": "Dessine un arc de cercle exact dans l'espace par trois points, avec Esquisse 3D activée. À utiliser pour des courbes de trajectoires et de rails guides qui sortent du plan d'esquisse.", + "help.sketch.auto_constrain": "Ajoute les contraintes que l'esquisse a presque déjà, comme horizontale, parallèle ou coïncidente, puis la cote jusqu'à ce qu'elle soit entièrement définie. À utiliser pour verrouiller en une étape une esquisse dessinée approximativement.", + "help.sketch.auto_constrain_from_datum": "Fonctionne comme Contraintes automatiques, mais mesure les positions depuis un point de référence que vous choisissez plutôt que depuis l'origine. À utiliser lorsque la pièce est tracée à partir d'un point de référence, comme un coin ou un perçage.", + "help.sketch.blend_curve": "Relie les extrémités de deux courbes par une spline douce, tangente aux deux, ou aussi continue en courbure si vous le choisissez. À utiliser pour combler un écart entre des courbes sans cassure.", + "help.sketch.break": "Scinde une courbe en morceaux là où d'autres courbes la croisent, ou en des points que vous placez dessus. À utiliser lorsqu'une partie d'une courbe a besoin de sa propre contrainte ou doit être supprimée seule.", + "help.sketch.cancel": "Quitte l'esquisse et abandonne tout ce qui a été modifié depuis sa création ou son ouverture pour modification. Annuler rétablit les modifications.", + "help.sketch.centerline": "Bascule des lignes entre lignes normales et lignes d'axe, des axes que les profils ignorent. Utilisez une ligne d'axe comme axe pour une révolution, une symétrie ou une contrainte de symétrie.", + "help.sketch.chamfer.distance_angle": "Biseaute le coin entre deux lignes, défini par une distance le long de la première ligne et un angle. À utiliser lorsqu'un dessin donne le chanfrein sous forme de longueur et d'angle, comme 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Biseaute le coin entre deux lignes sur la même distance le long des deux. À utiliser pour le chanfrein habituel à 45° sur un contour.", + "help.sketch.chamfer.two_distance": "Biseaute le coin entre deux lignes, défini par une distance distincte le long de chaque ligne. À utiliser pour des chanfreins qui ne sont pas à 45°, donnés sous forme de deux longueurs.", + "help.sketch.circle.center": "Dessine un cercle à partir de son centre et de son diamètre. À utiliser pour des perçages, des bossages et d'autres formes rondes dont le centre est connu.", + "help.sketch.circle.three_point": "Dessine un cercle passant par trois points. À utiliser lorsque le cercle doit passer par des points donnés, par exemple de la géométrie existante.", + "help.sketch.circle.three_tangent": "Dessine un cercle qui touche trois lignes, cercles ou arcs. À utiliser pour inscrire un cercle dans l'espace entre trois courbes, comme le cercle inscrit d'un triangle.", + "help.sketch.circle.two_point": "Dessine un cercle à partir des deux extrémités de son diamètre. À utiliser lorsque les points du bord du cercle sont connus plutôt que son centre.", + "help.sketch.circle.two_tangent": "Dessine un cercle de taille donnée qui touche deux lignes, cercles ou arcs. À utiliser pour un arrondi de rayon fixe entre deux courbes.", + "help.sketch.conic": "Dessine une courbe conique entre deux extrémités, façonnée par un point sommet et une valeur rho. À utiliser pour des transitions douces dont vous voulez ajuster la tension, de presque plate à presque anguleuse.", + "help.sketch.constrainer": "Applique la contrainte qu'une ou deux courbes choisies ont presque déjà, comme horizontale, parallèle, tangente ou égale. À utiliser pour mettre au propre une esquisse à main levée, une relation à la fois.", + "help.sketch.constraint.coincident": "Place un point sur un autre point, une courbe ou un axe d'esquisse. À utiliser pour fermer les écarts d'un profil ou pour poser un point sur une ligne.", + "help.sketch.constraint.collinear": "Place deux lignes sur une même droite. À utiliser pour aligner des arêtes interrompues, comme les deux côtés d'une encoche.", + "help.sketch.constraint.concentric": "Donne le même centre à deux cercles ou arcs. À utiliser pour des bagues, des lamages et des arbres à épaulements.", + "help.sketch.constraint.curvature": "Fait que deux courbes qui se rejoignent en une extrémité continuent avec la même courbure (G2). À utiliser lorsqu'un raccord tangent n'est pas assez doux, par exemple sur des surfaces visibles.", + "help.sketch.constraint.equal": "Donne la même longueur à des lignes, ou le même rayon à des cercles et arcs. À utiliser pour qu'une seule cote pilote plusieurs formes identiques.", + "help.sketch.constraint.fix": "Fixe des points ou des courbes là où ils sont, ou les libère. À utiliser pour la géométrie qui ne doit pas bouger lorsque vous faites glisser ou résolvez l'esquisse.", + "help.sketch.constraint.horizontal_vertical": "Rend une ligne, ou la ligne entre deux points, horizontale ou verticale, selon la plus proche. À utiliser pour redresser un contour sur les axes de l'esquisse.", + "help.sketch.constraint.midpoint": "Place un point au milieu d'une ligne, ou fait coïncider les milieux de deux lignes. À utiliser pour centrer de la géométrie sur une arête.", + "help.sketch.constraint.parallel": "Rend deux lignes parallèles. À utiliser pour des côtés qui doivent rester parallèles lorsque d'autres cotes changent.", + "help.sketch.constraint.perpendicular": "Fait se rencontrer deux lignes à angle droit. À utiliser pour des coins d'équerre entre des lignes qui ne sont pas sur les axes de l'esquisse.", + "help.sketch.constraint.polygon": "Transforme une chaîne fermée de lignes en polygone régulier : côtés égaux, avec tous les coins sur un même cercle. À utiliser pour rendre régulier un polygone dessiné à main levée et le garder ainsi.", + "help.sketch.constraint.symmetry": "Fait que deux points ou courbes sont symétriques par rapport à une ligne ou à un point. À utiliser pour garder un profil symétrique lorsque vous modifiez un côté.", + "help.sketch.constraint.tangent": "Fait que deux courbes se touchent en tangence, comme une ligne et un arc. À utiliser pour des raccords doux sans cassure.", + "help.sketch.construction": "Bascule des courbes entre géométrie normale et géométrie de construction, que les profils ignorent. Utilisez les courbes de construction comme aides pour l'implantation, les références et les cotes.", + "help.sketch.construction_line": "Crée une droite de construction infinie passant par deux points. À utiliser pour structurer une esquisse sans diviser les profils.", + "help.sketch.construction_line.angle": "Crée une droite de construction infinie inclinée d'un angle par rapport à l'axe X de l'esquisse. Choisissez le point puis saisissez l'angle, ou choisissez sa direction.", + "help.sketch.construction_line.bisector": "Sélectionnez deux lignes droites sécantes de l'esquisse, puis choisissez l'une des deux bissectrices. Le résultat suit les lignes dont il provient.", + "help.sketch.construction_line.horizontal": "Crée une droite de construction horizontale infinie passant par un point. Sa contrainte horizontale est conservée lors des modifications ultérieures.", + "help.sketch.construction_line.parallel": "Sélectionnez une ligne droite de l'esquisse, puis placez une droite de construction infinie parallèle. Clic droit pour choisir une autre référence.", + "help.sketch.construction_line.perpendicular": "Sélectionnez une ligne droite de l'esquisse, puis placez une droite de construction infinie perpendiculaire. Clic droit pour choisir une autre référence.", + "help.sketch.construction_line.tangent_at": "Crée une tangente en un point d'un cercle ou d'un arc de cercle, ou à l'extrémité d'une spline ouverte ou d'une conique. Sélectionnez la courbe, puis son point de contact.", + "help.sketch.construction_line.tangent_external": "Sélectionnez un cercle ou un arc de cercle, puis un point extérieur et une solution de tangente. Les aperçus n'affichent que les points de contact situés sur l'arc dessiné.", + "help.sketch.construction_line.tangent_two": "Sélectionnez deux cercles ou arcs de cercle, puis choisissez une tangente commune dans l'aperçu. Les points de contact doivent se trouver sur les courbes dessinées.", + "help.sketch.construction_line.vertical": "Crée une droite de construction verticale infinie passant par un point. Sa contrainte verticale est conservée lors des modifications ultérieures.", + "help.sketch.copy": "Copie les courbes et points d'esquisse sélectionnés, avec les contraintes et cotes qui les relient. Collez-les dans cette esquisse ou dans une autre.", + "help.sketch.create": "Démarre une nouvelle esquisse 2D sur un plan ou sur une face plane du modèle. Toute extrusion, révolution et balayage commence par une esquisse.", + "help.sketch.cut": "Copie la géométrie d'esquisse sélectionnée et la supprime de l'esquisse, en une seule étape d'annulation. Collez-la ailleurs dans cette esquisse ou dans une autre.", + "help.sketch.dimension": "Ajoute une cote pilotante : une longueur, une distance, un angle, un rayon ou un diamètre, selon ce que vous choisissez. Saisissez une valeur ou un nom de paramètre, et l'esquisse la suit.", + "help.sketch.edit": "Ouvre une esquisse existante pour la modifier. Les fonctions construites dessus se mettent à jour lorsque vous terminez l'esquisse.", + "help.sketch.ellipse": "Dessine une ellipse à partir de son centre, de l'extrémité de son grand axe et d'un point côté petit axe. À utiliser pour des ouvertures ovales, des cames et d'autres formes rondes allongées.", "help.sketch.equation_curve": "Dessine une courbe à partir de formules : x(t) et y(t), ou y = f(x), sur un intervalle. Les formules peuvent utiliser des paramètres et la courbe les suit : à utiliser pour une sinusoïde, une spirale ou la développante d'une dent d'engrenage.", + "help.sketch.extend": "Prolonge une ligne ou un arc jusqu'à la courbe la plus proche sur son chemin, ou fait croître deux courbes jusqu'à ce qu'elles se rejoignent. À utiliser pour fermer des jeux dans un profil après ajustement ou modification.", + "help.sketch.fillet": "Arrondit le coin où deux lignes ou arcs se rejoignent par un arc de rayon donné. Plusieurs coins arrondis ensemble partagent un même rayon.", + "help.sketch.finish": "Quitte l'esquisse et revient au modèle. Ses profils fermés sont alors prêts pour Extrusion, Révolution et d'autres fonctions.", + "help.sketch.finish_auto_constrain": "Lance Contraintes automatiques sur l'esquisse, puis la termine. À utiliser pour laisser une esquisse entièrement définie en une seule étape.", + "help.sketch.fit_curves_to_section": "Coupe un corps maillé ou solide avec le plan d'esquisse et ajuste des lignes et des arcs à la section. À utiliser pour reconstruire une pièce numérisée ou importée sous forme d'esquisse modifiable.", + "help.sketch.include_3d": "Amène des arêtes du modèle, des sommets et des courbes d'autres esquisses dans cette esquisse comme références liées, en aplatissant sur son plan celles qui en sont hors. À utiliser pour construire à partir d'une géométrie qui n'est pas dans le plan d'esquisse.", + "help.sketch.infinite": "Bascule des lignes entre lignes normales et lignes de construction infinies qui traversent toute la vue. À utiliser comme références d'implantation qui ne s'arrêtent jamais trop court.", + "help.sketch.insert_dxf": "Lit les courbes d'un dessin DXF dans une esquisse, mises à l'échelle, tournées et placées comme vous le définissez. À utiliser pour construire à partir d'un dessin 2D d'un autre logiciel, comme un contour de découpe laser.", + "help.sketch.insert_svg": "Lit les tracés d'un dessin SVG dans une esquisse, mis à l'échelle, tournés et placés comme vous le définissez. À utiliser pour transformer un logo ou un contour vectoriel en courbes que vous pouvez extruder.", + "help.sketch.inspect": "Ouvre un rapport sur l'esquisse ouverte : combien de degrés de liberté il reste et si elle est entièrement contrainte. À utiliser pour savoir ce qui bouge encore avant de terminer l'esquisse.", + "help.sketch.intersect": "Ajoute les courbes ou points où des corps, faces, arêtes ou d'autres esquisses traversent le plan d'esquisse. Ils restent liés et suivent le modèle lorsqu'il change.", + "help.sketch.intersection_curve": "Crée des courbes 3D là où deux corps ou faces se rencontrent, liées à eux. À utiliser comme trajectoires ou rails guides qui suivent le modèle.", + "help.sketch.isoparametric_curve": "Crée une courbe 3D le long de la direction U ou V d'une face, par un point que vous choisissez, liée à la face. À utiliser comme trajectoire ou ligne de partage qui suit la surface.", + "help.sketch.line": "Dessine des lignes connectées point par point, en chaîne ouverte ou en contour fermé. C'est l'outil de base de la plupart des profils.", + "help.sketch.line.midpoint": "Dessine une ligne de son milieu vers une extrémité, l'autre extrémité étant son symétrique. À utiliser pour des lignes centrées sur un point, comme une arête symétrique.", + "help.sketch.line3d": "Dessine des lignes droites connectées entre des points de l'espace, avec Esquisse 3D activée. À utiliser pour des trajectoires et des structures qui sortent du plan d'esquisse.", + "help.sketch.mirror": "Symétrise des courbes et points d'esquisse par rapport à une ligne ou un axe et ajoute des contraintes de symétrie. À utiliser pour dessiner la moitié d'un profil symétrique et le compléter.", + "help.sketch.move": "Déplace ou fait tourner des courbes et points d'esquisse, ou une copie. À utiliser pour repositionner de la géométrie en gardant sa forme et ses contraintes.", + "help.sketch.offset": "Crée une copie d'une chaîne de courbes à une distance donnée, d'un côté ou des deux. À utiliser pour des parois, des contours et des jeux ; la distance reste une cote modifiable.", + "help.sketch.paste": "Colle dans l'esquisse active la géométrie d'esquisse copiée ou coupée. Placez-la en un point ou décalez-la d'une valeur.", + "help.sketch.pattern.circular": "Copie la géométrie d'esquisse autour d'un centre, sur un cercle complet ou un angle donné. À utiliser pour des cercles de perçages, des rayons et des dents.", + "help.sketch.pattern.rectangular": "Copie la géométrie d'esquisse en lignes et colonnes à des espacements donnés. À utiliser pour des grilles de trous, de rainures ou d'aérations.", + "help.sketch.point": "Place un point d'esquisse. À utiliser comme référence pour des cotes, des contraintes, des centres de perçage ou des fonctions ultérieures.", + "help.sketch.point3d": "Place un point dans l'espace, avec Esquisse 3D activée. À utiliser comme référence pour des courbes et trajectoires 3D.", + "help.sketch.polygon.circumscribed": "Dessine un polygone régulier autour d'un cercle, dimensionné du centre au milieu d'un côté. À utiliser lorsque la largeur sur plats est connue, comme pour un écrou hexagonal.", + "help.sketch.polygon.edge": "Dessine un polygone régulier à partir des deux extrémités d'un côté. À utiliser lorsque la longueur et la position d'un côté sont connues.", + "help.sketch.polygon.inscribed": "Dessine un polygone régulier à l'intérieur d'un cercle, dimensionné du centre à un coin. À utiliser lorsque la dimension sur coins est connue.", + "help.sketch.project": "Amène des arêtes du modèle, des faces, des sommets et des courbes d'autres esquisses dans cette esquisse, projetés sur son plan. Ils restent liés et suivent le modèle lorsqu'il change.", + "help.sketch.project_to_surface": "Projette des courbes d'autres esquisses selon la normale de cette esquisse sur une face, sous forme de courbes 3D liées. À utiliser pour poser un logo, une ligne de partage ou une trajectoire sur une surface courbe.", + "help.sketch.rectangle.center": "Dessine un rectangle à partir de son centre et d'un coin. À utiliser pour des contours centrés sur un point, comme l'origine.", + "help.sketch.rectangle.rounded": "Dessine un rectangle dont les quatre coins sont arrondis au même rayon. À utiliser pour des plaques, des couvercles et des ouvertures à coins arrondis.", + "help.sketch.rectangle.three_point": "Dessine un rectangle à partir d'un côté et d'un point du côté opposé. À utiliser pour des rectangles inclinés par rapport aux axes de l'esquisse.", + "help.sketch.rectangle.two_point": "Dessine un rectangle à partir de deux coins opposés. À utiliser pour les contours de plaques, de blocs et de poches.", + "help.sketch.scale": "Met à l'échelle des courbes et points d'esquisse selon un facteur autour d'un point de base. À utiliser pour redimensionner une partie d'une esquisse sans la redessiner.", + "help.sketch.slot.arc_center": "Dessine une rainure courbe de largeur donnée le long d'un arc défini par son centre, son début et sa fin. À utiliser pour des rainures de réglage autour d'un pivot.", + "help.sketch.slot.arc_three_point": "Dessine une rainure courbe de largeur donnée le long d'un arc passant par trois points. À utiliser lorsque le tracé de la rainure doit passer par des points donnés.", + "help.sketch.slot.center_point": "Dessine une rainure droite de largeur donnée de son centre au centre d'un arc d'extrémité. À utiliser pour des rainures centrées sur un point.", + "help.sketch.slot.center_to_center": "Dessine une rainure droite de largeur donnée entre les centres de ses deux arcs d'extrémité. À utiliser pour des rainures cotées de centre à centre, comme les rainures de réglage de vis.", + "help.sketch.slot.overall": "Dessine une rainure droite de largeur donnée d'une extrémité extérieure à l'autre. À utiliser lorsque c'est la longueur hors tout de la rainure qui compte.", + "help.sketch.spline.control_point": "Dessine une spline cubique façonnée par des points de contrôle qu'elle ne traverse pas. À utiliser pour des courbes douces et fluides que vous façonnez en déplaçant les points.", + "help.sketch.spline.control_point_5": "Dessine une spline de degré 5 façonnée par des points de contrôle. À utiliser lorsque des courbes doivent se raccorder avec une courbure plus douce, par exemple sur des surfaces de style visibles.", + "help.sketch.spline.fit_point": "Dessine une spline douce qui passe par chaque point que vous placez, ouverte ou fermée. À utiliser pour décalquer une forme à travers des points connus.", + "help.sketch.spline3d": "Dessine une courbe douce dans l'espace par des points, avec Esquisse 3D activée. À utiliser pour des trajectoires de balayage et des cheminements de câbles qui sortent du plan d'esquisse.", + "help.sketch.spun_profile": "Crée dans le plan d'esquisse le contour qu'un corps balaie en tournant autour d'un axe. À utiliser pour obtenir la silhouette d'une pièce tournée pour une révolution ou un dessin.", + "help.sketch.text": "Écrit du texte dans l'esquisse avec une police, une hauteur et un angle au choix ; ses mots peuvent suivre des paramètres. À extruder ou embosser pour des étiquettes et des lettrages.", + "help.sketch.transform": "Met à l'échelle, fait tourner et déplace de la géométrie d'esquisse autour d'un centre en une seule étape. À utiliser pour repositionner et redimensionner une sélection d'un coup.", + "help.sketch.trim": "Supprime le morceau d'une courbe entre les croisements les plus proches autour de l'endroit où vous cliquez. À utiliser pour nettoyer des lignes qui se chevauchent et obtenir un profil fermé.", "help.solid.align": "Déplace les corps sélectionnés pour qu'un de leurs points, faces ou plans rejoigne un point, une face ou un plan ailleurs. À utiliser pour poser une pièce contre une autre sans mesurer le décalage.", + "help.solid.boundary_fill": "Crée des solides à partir des régions délimitées par des corps outils qui se chevauchent, en ne remplissant que les régions que vous choisissez. À utiliser pour construire une forme à partir de l'espace que plusieurs corps délimitent ensemble.", + "help.solid.bounding_solid": "Crée un parallélépipède qui englobe les corps sélectionnés, avec une marge facultative. À utiliser pour voir l'encombrement d'une pièce, ou comme brut dans lequel elle est usinée.", + "help.solid.box": "Crée un parallélépipède à partir d'une longueur, d'une largeur et d'une hauteur, depuis un coin ou centré sur un point. À utiliser pour un bloc rapide, un volume provisoire ou un corps dans lequel tailler des fonctions.", "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.coil": "Crée un corps hélicoïdal, comme un ressort, à partir d'un diamètre, d'un nombre de tours, d'une hauteur ou d'un pas et d'une section ronde ou carrée. À utiliser pour des ressorts, des spires et des nervures hélicoïdales.", "help.solid.combine": "Joint des corps, les retire d'un corps cible ou ne garde que le volume qu'ils ont en commun, et peut conserver les corps outils. À utiliser pour fusionner des pièces, tailler une forme avec une autre ou repérer où deux corps se recouvrent.", + "help.solid.cone": "Crée un cône à partir d'un cercle de base et d'une hauteur, ou un tronc de cône lorsque le sommet a aussi un rayon. À utiliser pour des conicités, des entonnoirs, des fraisages et des pointes.", + "help.solid.cylinder": "Crée un cylindre à partir d'un rayon ou d'un diamètre et d'une hauteur, posé sur un point selon un axe. À utiliser pour des arbres, des goupilles, des bossages et des bruts ronds.", "help.solid.draft": "Incline les faces sélectionnées de l'angle indiqué, mesuré depuis un plan neutre. À utiliser sur les pièces moulées ou coulées pour qu'elles sortent du moule.", + "help.solid.emboss": "Fait saillir des profils d'esquisse, comme du texte ou un logo, hors d'une face, ou les enfonce dedans. À utiliser pour des lettrages, des étiquettes et des marquages sur des faces planes ou rondes.", "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.", @@ -1408,20 +1678,62 @@ "help.solid.move": "Déplace ou fait tourner les corps sélectionnés, ou une copie, selon la distance et l'angle indiqués. À utiliser pour repositionner un corps ou en créer un second ailleurs.", "help.solid.offset_face": "Pousse les faces sélectionnées vers l'intérieur ou l'extérieur de la distance indiquée, et les faces voisines suivent. À utiliser pour épaissir une paroi, creuser une poche ou rehausser un bossage sans modifier l'esquisse.", "help.solid.pattern.circular": "Répète les objets sélectionnés autour d'un axe, selon le nombre et l'angle total indiqués. À utiliser pour les cercles de perçages, rayons, ailettes et dents.", + "help.solid.pattern.path": "Copie des fonctions ou des corps le long d'une trajectoire d'esquisse, selon un nombre et un espacement. À utiliser pour des trous le long d'une arête courbe ou des pièces le long d'un rail.", "help.solid.pattern.rectangular": "Répète les objets sélectionnés dans une ou deux directions, selon le nombre et l'espacement indiqués. À utiliser pour les rangées et grilles de trous, nervures, goupilles ou pieds.", + "help.solid.pipe": "Crée un tube rond le long d'une trajectoire de courbes d'esquisse, plein ou creux avec une épaisseur de paroi. À utiliser pour des tubes, des fils, des câbles et des rails.", "help.solid.press_pull": "Ajoute ou retire de la matière quand on fait glisser une face, ou arrondit des arêtes quand on les fait glisser. À utiliser pour des modifications rapides directement sur le modèle.", "help.solid.remove": "Retire les corps sélectionnés de la conception à partir de ce point de la chronologie ; les étapes précédentes les gardent. À utiliser pour écarter un corps d'aide, comme un outil de découpe devenu inutile.", "help.solid.replace_face": "Amène les faces planes sélectionnées sur un plan ou une face parallèle, et le corps s'allonge ou se raccourcit pour la rejoindre. À utiliser pour mettre une face au ras d'une autre pièce ou d'un plan de construction.", "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.rib": "Ajoute une paroi mince le long d'une courbe d'esquisse ouverte, prolongée jusqu'aux faces suivantes du corps. À utiliser pour rigidifier des parois et des coins, par exemple dans des pièces moulées ou imprimées.", "help.solid.scale": "Agrandit ou réduit les corps sélectionnés d'un facteur, identique dans toutes les directions ou propre à chaque axe. À utiliser pour redimensionner une forme importée ou compenser un retrait.", "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.solid.sphere": "Crée une sphère à partir d'un rayon ou d'un diamètre autour d'un centre. À utiliser pour des billes, des boutons et des extrémités arrondies.", "help.solid.split_body": "Scinde un corps en corps séparés avec un plan, la face d'un autre corps ou une ligne d'esquisse. À utiliser pour obtenir des pièces imprimées, usinées ou colorées séparément.", "help.solid.split_face": "Scinde les faces sélectionnées le long d'un plan, de la face d'un autre corps ou de courbes d'esquisse, sans scinder le corps. À utiliser pour donner à une partie de face sa propre dépouille, couleur ou décalage.", "help.solid.sweep": "Entraîne le profil d'une esquisse le long d'une trajectoire pour obtenir un solide. À utiliser pour les tuyaux, rails, poignées et toute pièce de section constante qui suit une courbe.", + "help.solid.thread": "Ajoute un filetage métrique ISO sur une face cylindrique, soit sous forme de filetage cosmétique, soit taillé dans le corps. À utiliser pour des boulons, des trous taraudés et des pièces vissées imprimées.", + "help.solid.torus": "Crée un anneau à partir d'un grand rayon autour de son axe et d'un petit rayon pour sa section ronde. À utiliser pour des joints toriques, des poignées et des perles rondes.", + "help.solid.web": "Ajoute une paroi mince le long de chaque courbe d'esquisse ouverte, chacune prolongée jusqu'aux faces suivantes du corps. À utiliser pour une grille de parois de soutien à l'intérieur de boîtiers et de plateaux.", + "help.surface.blend": "Crée une surface qui relie les arêtes de deux corps, en tangence ou en continuité de courbure avec les deux. À utiliser pour joindre en douceur deux surfaces à travers un écart.", + "help.surface.boundary": "Crée une surface remplissant une boucle de deux à quatre courbes d'esquisse, ou un réseau de courbes. À utiliser pour des panneaux de forme libre définis par leurs bords.", + "help.surface.extend": "Prolonge une surface au-delà de ses bords, d'une distance ou jusqu'à un plan ou une face. À utiliser pour que des surfaces se chevauchent avant de les ajuster ou de les coudre.", + "help.surface.extrude": "Pousse des courbes ou profils d'esquisse sur une distance pour former une surface, parois seulement, sans fonds. À utiliser pour des parois minces et pour des outils de coupe ou de partage.", + "help.surface.fair": "Lisse l'intérieur de faces de forme libre tandis que leurs bords restent en place. À utiliser pour atténuer les bosses et les reflets ondulés d'une surface.", + "help.surface.loft": "Crée une surface qui passe par deux sections ou plus dans l'ordre, sans fonds. À utiliser pour des coques et des transitions entre des formes différentes.", + "help.surface.match": "Reconstruit le bord d'une surface pour qu'il rejoigne le bord d'un autre corps, avec une tangence ou une courbure concordante. À utiliser pour fermer en douceur un raccord entre deux surfaces.", + "help.surface.offset": "Crée une copie de faces à une distance le long de leurs normales, sous forme de nouveau corps surfacique. À utiliser pour des peaux, des jeux ou l'autre côté d'une paroi.", + "help.surface.patch": "Remplit une région d'esquisse ou une boucle fermée d'arêtes par une face, plane ou courbe et douce. À utiliser pour boucher des trous dans un corps surfacique.", + "help.surface.reverse_normal": "Retourne des faces d'un corps surfacique, de sorte que leur côté extérieur soit orienté dans l'autre sens. À utiliser avant d'épaissir ou de coudre lorsque les faces pointent vers l'intérieur.", + "help.surface.revolve": "Fait tourner des courbes ou profils d'esquisse autour d'un axe pour former une surface, sans fonds. À utiliser pour des coques rondes comme des abat-jour, des bols et des buses.", + "help.surface.ruled": "Crée une bande de droites à partir d'une chaîne d'arêtes, selon la normale de la face, la tangente ou un angle. À utiliser pour des parois de dépouille, des dégagements et des surfaces de joint.", + "help.surface.stitch": "Coud des corps surfaciques le long de leurs arêtes communes, en un solide lorsqu'ils se referment. À utiliser pour transformer un ensemble de surfaces en un seul corps.", + "help.surface.sweep": "Déplace des courbes ou profils d'esquisse le long d'une trajectoire pour former une surface, sans fonds. À utiliser pour des gouttières, des moulures et d'autres formes minces qui suivent une trajectoire.", + "help.surface.thicken": "Donne une épaisseur à un corps surfacique et le transforme en solide. À utiliser pour fabriquer des pièces imprimables ou usinables à partir de surfaces.", + "help.surface.trim": "Coupe une surface avec un plan, une autre surface ou des courbes d'esquisse, et garde le côté que vous choisissez. À utiliser pour ajuster des surfaces à leur forme avant de les coudre.", + "help.surface.unstitch": "Sépare des faces d'un corps en corps surfaciques distincts ; un solide se décompose en surfaces. À utiliser pour retravailler des faces isolées d'un corps.", + "help.surface.untrim": "Supprime des trous d'une face, ou rétablit son contour extérieur aux limites naturelles de la surface. À utiliser pour retrouver la surface complète après un ajustement.", "help.third_party": "Licences tierces", "help.timeline.compute_all": "Recalcule toutes les fonctions de la chronologie depuis le début. À utiliser pour rafraîchir le modèle et voir quelles fonctions échouent.", "help.timeline.delete": "Supprime les fonctions sélectionnées de la chronologie ; supprimer une esquisse supprime aussi les fonctions construites à partir d'elle. À utiliser pour retirer une étape devenue inutile.", + "help.timeline.dependents": "Liste les fonctions qui seraient supprimées avec une fonction, et celles qui échoueraient sans elle. À utiliser avant de supprimer ou de modifier une fonction.", "help.timeline.play": "Rejoue les fonctions restantes une par une, avec une pause d'une demi-seconde après chaque reconstruction. Relancez cette commande ou appuyez sur Échap pour arrêter ; Aller à la fin saute immédiatement.", + "help.view.apply": "Oriente la vue selon une direction standard comme face, dessus ou iso, ou selon une vue nommée enregistrée. À utiliser pour regarder le modèle sous un angle fixe.", + "help.view.delete": "Supprime une vue nommée enregistrée. Le modèle n'est pas modifié.", + "help.view.fit": "Zoome et déplace la vue pour que tout le modèle, ou la sélection, remplisse la vue. À utiliser lorsque le modèle est sorti du champ.", + "help.view.grid": "Affiche ou masque la grille dans la vue 3D. À utiliser comme repère de taille et d'orientation pendant la modélisation.", + "help.view.ground_shadow": "Affiche ou masque l'ombre du modèle sur le sol. À utiliser pour juger plus facilement la hauteur et la position.", + "help.view.home": "Remet la vue dans la direction d'accueil et ajuste le modèle. À utiliser pour revenir rapidement à une vue connue.", + "help.view.list": "Liste les vues nommées enregistrées dans la conception. À utiliser pour retrouver une vue enregistrée plus tôt.", + "help.view.navigate": "Fait tourner, déplace ou zoome la vue par étapes, comme un quart de tour à gauche. À utiliser pour déplacer la caméra avec précision plutôt qu'en faisant glisser.", + "help.view.navigation_bar": "Affiche ou masque la barre de navigation en bas de la vue 3D. Masquez-la pour gagner de la place, affichez-la pour accéder aux outils de vue à la souris.", + "help.view.rename": "Donne un nouveau nom à une vue nommée enregistrée. La vue elle-même reste inchangée.", + "help.view.save": "Enregistre la position actuelle de la caméra comme vue nommée dans la conception. À utiliser pour revenir plus tard au même angle, par exemple pour des captures d'écran.", + "help.view.spin": "Fait orbiter la vue autour du modèle en continu jusqu'au prochain clic ou à la prochaine touche. À utiliser pour présenter un modèle sous tous les angles.", + "help.view.tool": "Verrouille un outil de caméra, orbite, déplacement ou zoom, de sorte que faire glisser avec le bouton gauche de la souris déplace la vue jusqu'à ce que vous le désactiviez. À utiliser sur un trackpad ou sans bouton central de souris.", + "help.view.visual_style": "Change le mode d'affichage du modèle : ombré avec ou sans arêtes, filaire, ou avec arêtes cachées. Utilisez le filaire pour voir à l'intérieur, l'ombré pour un rendu net.", + "history.sketch_under_constrained": "Sous-contraint ({count} degrés de liberté)", + "history.sketch_under_constrained_one": "Sous-contraint ({count} degré de liberté)", "hole_presets.confirm_delete": "Confirmer la suppression", "hole_presets.delete": "Supprimer", "hole_presets.delete_prompt": "Supprimer ce préréglage personnel ? Les perçages existants ne changent pas.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Vérifiez le type de liaison (par exemple rigide), la fixation de la pièce, les limites de la liaison et les valeurs pilotées par des paramètres.", "joint_move.blocked_title": "Impossible de déplacer cette pièce", "joint_move.coarse": "Pas de rotation près de l’axe (°)", + "joint_move.conflict": "Une liaison de cette pièce est en conflit avec les autres : {joint}.", + "joint_move.conflict_hint": "Modifier, désactiver ou supprimer la liaison en conflit pour que les autres liaisons puissent placer la pièce.", "joint_move.distance": "Distance depuis le départ", "joint_move.done": "Terminé", "joint_move.fine": "Pas de rotation loin de l’axe (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Matériaux différents", "measure.at": "À", "measure.item": "Élément {number}", + "measure.quick_copied": "Mesure copiée", + "measure.quick_copy": "Cliquer pour copier la mesure", + "measure.quick_edges": "{count} arêtes", + "measure.quick_faces": "{count} faces", "messages.ago_h": "il y a {n} h", "messages.ago_min": "il y a {n} min", "messages.ago_s": "il y a {n} s", @@ -1620,6 +1938,8 @@ "motion.track_name": "Piste {number}", "nav.alias.help": "Maj+Alt+glisser gauche fait orbiter, Maj+Alt+milieu fait un panoramique, Maj+Alt+droit zoome ; glisser avec le milieu fait aussi un panoramique et glisser avec le droit fait orbiter", "nav.blender.help": "Glisser avec le milieu fait orbiter, Maj+milieu fait un panoramique, Ctrl+milieu zoome ; glisser avec le droit ne touche pas la caméra", + "nav.creo.help": "Glisser avec le milieu fait orbiter, Maj+milieu fait un panoramique, Ctrl+glisser avec le milieu zoome verticalement (vers le bas pour zoomer) ; la molette zoome", + "nav.creo.label": "Creo", "nav.free_orbit.help": "La souris et la souris 3D tournent en passant par les deux pôles et conservent le roulis. L'alignement des axes avec Maj est désactivé.", "nav.free_orbit.label": "Orbite libre", "nav.free_orbit.snap_help": "La souris et la souris 3D tournent en passant par les deux pôles et conservent le roulis. Maintenir Maj pendant un glissement d'orbite pour aligner la direction de vue et le roulis.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+glisser gauche fait un panoramique, Maj+Alt+gauche zoome, Ctrl+glisser gauche sur un espace vide fait orbiter", "nav.inventor.help": "Glisser avec le milieu fait un panoramique, Maj+milieu fait orbiter, Ctrl+milieu zoome, glisser avec le droit fait orbiter", "nav.maya.help": "Alt+glisser gauche fait orbiter, Alt+milieu fait un panoramique, Alt+droit zoome ; glisser avec le milieu fait aussi un panoramique", + "nav.nx.help": "Glisser avec le milieu fait orbiter, Maj+milieu fait un panoramique (milieu + droit dans NX), Ctrl+milieu zoome (milieu + gauche dans NX) ; glisser avec le droit ne touche pas la caméra", "nav.openscad.help": "Glisser avec le gauche dans le vide fait orbiter, Maj+glisser gauche sélectionne par rectangle, glisser la géométrie d'esquisse la modifie ; glisser avec le droit ou le milieu fait un panoramique, Maj+droit ou Maj+milieu zoome", "nav.perspective.sketch": "La modification d'une esquisse utilise la vue orthographique. Terminer l'esquisse pour passer en perspective.", "nav.right_drag_orbits.help": "Désactivé : glisser avec le droit ne touche pas la caméra et le bouton droit ouvre seulement le menu contextuel. Choisir l'affectation des boutons de la souris SolidWorks le désactive.", @@ -1748,6 +2069,11 @@ "not a move": "pas un déplacement", "not a number": "pas un nombre", "open a sketch first": "ouvrir d'abord une esquisse", + "parameters.apply_live": "Appliquer chaque modification en quittant son champ", + "parameters.apply_live_tip": "Désactivé : les modifications attendent Appliquer ou OK, puis le modèle est reconstruit une seule fois pour toutes. Annuler ou Échap les abandonne.", + "parameters.held": "{count} modifications en attente d’Appliquer", + "parameters.held_hint": "Modifiez les expressions et les unités. Les modifications attendent Appliquer ou OK.", + "parameters.held_one": "1 modification en attente d’Appliquer", "parts.automatic_name": "automatique", "parts.dimension.across_flats": "Sur plats", "parts.dimension.bore": "Alésage", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Vis à tête bombée à six pans creux", "parts.family.dowel_pin": "Goupille cylindrique", "parts.family.hex_bolt": "Vis à tête hexagonale", + "parts.family.hex_cap_screw_inch": "Vis à tête hexagonale (pouces)", "parts.family.hex_nut": "Écrou hexagonal", + "parts.family.hex_nut_inch": "Écrou hexagonal (pouces)", "parts.family.set_screw": "Vis sans tête à six pans creux, bout plat", "parts.family.socket_head_cap_screw": "Vis à tête cylindrique à six pans creux", "parts.family.washer": "Rondelle plate", + "parts.family.washer_sae": "Rondelle plate, SAE (étroite)", + "parts.family.washer_uss": "Rondelle plate, USS (large)", + "parts.holes": "Trous (facultatif)", + "parts.placement_hint": "choisissez un ou plusieurs trous pour y loger une pièce chacun, ou OK la place à l'origine", + "parts.system": "Système d'unités", + "parts.system.inch": "Pouces", + "parts.system.metric": "Métrique", "pattern.alignment_2": "Alignement 2", "pattern.alignment_hint": "La quantité inclut l’original. Le centrage répartit les copies de chaque côté ; si la quantité est paire, l’inversion choisit le côté qui reçoit la copie supplémentaire.", "pattern.direction_1": "Direction 1", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Adoucit les bords crénelés.", "prefs.applies_on_restart": "Appliqué au redémarrage", "prefs.assistant": "Assistant", + "prefs.auto_operation": "Choisir l'opération automatiquement", + "prefs.auto_operation_note": "Les boîtes de dialogue des fonctions choisissent Joindre, Nouveau corps ou Couper d'après ce que touche la nouvelle matière, tant que vous n'en choisissez pas une vous-même. Désactivé : elles gardent l'opération avec laquelle elles s'ouvrent.", "prefs.axes": "Axes", "prefs.axis": "Axe", "prefs.bodies_folders": "Dossiers Corps", @@ -1820,6 +2157,10 @@ "prefs.bottom_centre": "Bas centre", "prefs.bottom_right": "Bas droite", "prefs.browser": "Navigateur", + "prefs.browser_components_open": "Composants dépliés au départ", + "prefs.browser_components_open_note": "Chaque composant du navigateur commence déplié, comme avant, au lieu de rester replié jusqu'à ce que vous le dépliiez.", + "prefs.browser_eye_left": "Œil à côté de la flèche de dépliage", + "prefs.browser_eye_left_note": "Les lignes du navigateur affichent leur œil d'affichage et de masquage à côté de la flèche de dépliage, comme avant, au lieu d'une colonne à l'extrémité droite des lignes.", "prefs.browser_reveal_on_hover": "Révéler au survol", "prefs.browser_show_note": "Affiché garde le navigateur à l'écran. Révéler au survol le cache jusqu'à ce que le pointeur passe sur sa place ou sur le fin onglet à son bord gauche, et il reste ouvert tant que le pointeur est dedans ou qu'un de ses menus est ouvert.", "prefs.browser_shown": "Affiché", @@ -1827,6 +2168,8 @@ "prefs.button_left": "Glisser gauche", "prefs.button_middle": "Glisser milieu", "prefs.button_right": "Glisser droit", + "prefs.carousel_next": "Suivant", + "prefs.carousel_previous": "Précédent", "prefs.choose_font": "Choisir un fichier de police…", "prefs.click": "Clic", "prefs.contact_shading": "Ombrage de contact doux", @@ -1839,6 +2182,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Surfaces courbes", "prefs.curves": "Surfaces courbes", + "prefs.cut_preview_tint": "Afficher en rouge la matière retirée", + "prefs.cut_preview_tint_help": "Un aperçu remplit la matière qu'une fonction retire, et la forme qu'elle remplace, d'un fantôme rouge translucide. Désactivée, ces remplissages sont entièrement transparents et seuls leurs contours sont tracés.", + "prefs.dark_parts_shading": "Conserver la forme des pièces sombres", + "prefs.dark_parts_shading_help": "Ombrer la vue en lumière linéaire avec un léger éclairage de ciel, pour que les faces sombres gardent un dégradé au lieu de devenir noires", "prefs.dead_zone_note": "La bande hachurée est la zone morte : les mouvements à l'intérieur sont ignorés.", "prefs.default": "par défaut", "prefs.design": "Valeurs par défaut des conceptions", @@ -1853,6 +2200,8 @@ "prefs.edges": "Arêtes et ombrage", "prefs.extend": "Étendre", "prefs.extra_navigation": "Ctrl+glisser gauche dans le vide fait orbiter ; maintenir Espace pour un panoramique.", + "prefs.extrude_view_isometric": "Passer la vue en isométrique à l'ouverture de l'extrusion", + "prefs.extrude_view_return": "Revenir à la vue précédente à la fermeture de l'extrusion", "prefs.follows_os": "Suit le système", "prefs.font": "Police", "prefs.font_fallback": "Les caractères absents de la police choisie utilisent la police intégrée, pour qu'aucun libellé n'affiche de case vide.", @@ -1868,8 +2217,11 @@ "prefs.graphics_card_auto": "Automatique", "prefs.graphics_card_missing": "La carte graphique enregistrée n'est pas disponible ; Automatique est utilisé.", "prefs.graphics_card_restart": "Prend effet après le redémarrage de SolidCraft. WGPU_ADAPTER_NAME prévaut sur ce choix.", + "prefs.graphics_card_unused": "La carte graphique enregistrée n'a pas été utilisée pour cette fenêtre ; la carte utilisée est indiquée dans Aide › À propos et dans la barre d'état. Essayer Automatique, ou définir WGPU_ADAPTER_NAME avec une partie unique du nom de la carte.", "prefs.graphics_note": "Compromis entre vitesse et fluidité. Chaque choix montre son effet sur un exemple.", "prefs.graphics_presets_note": "Les préréglages définissent ensemble les choix ci-dessous.", + "prefs.hide_constraint_glyphs_zoomed_out": "Masquer les symboles de contraintes en cas de zoom arrière", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Les symboles de contraintes quittent la vue lorsque le zoom arrière sur l'esquisse est assez important pour qu'ils l'encombrent. Désactivé : ils gardent une taille fixe à l'écran quel que soit le zoom.", "prefs.history": "Historique", "prefs.history_origin_bodies": "Afficher l'origine et les corps en haut", "prefs.history_origin_bodies_note": "L'historique à gauche ou sous le navigateur commence par le dossier Corps et l'Origine du composant actif, avec leurs yeux et leurs menus comme dans le navigateur. L'historique en bas ne change pas.", @@ -1880,6 +2232,8 @@ "prefs.history_sketches_note": "Avec Esquisses réglé sur Sous leur fonction, l'historique de gauche liste chaque esquisse un niveau en retrait, sous la première fonction construite à partir d'elle, dès qu'il est assez large pour les noms. La chronologie en bas garde toujours l'ordre de création.", "prefs.history_sketches_under_feature": "Sous leur fonction", "prefs.hold_stop_snapping": "Maintenir pour désactiver l'accrochage", + "prefs.home_fit_size": "Taille de Accueil et Cadrer", + "prefs.home_fit_size_note": "Part de la vue que remplit le modèle quand Accueil, Cadrer, l'ouverture d'une conception ou une vue du repère de navigation recadre la vue, que le réglage ci-dessous soit activé ou non. 100 % : remplit la vue entre les panneaux, la boussole et la barre de navigation.", "prefs.icons_only": "Icônes seules", "prefs.imported_file": "Fichier importé", "prefs.in_browser": "Dans le navigateur", @@ -1888,13 +2242,22 @@ "prefs.interface_language": "Langue de l'interface", "prefs.interface_note": "L'apparence de SolidCraft et la place de ses éléments.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Inverser les flèches courbes de roulis", + "prefs.invert_curved_roll_arrows_note": "Les deux flèches courbes au coin du cube font rouler la vue dans le plan de l'écran. Activé : la flèche horaire fait rouler dans le sens antihoraire et la flèche antihoraire dans le sens horaire. Désactivé : chaque flèche fait rouler la vue dans le sens de sa courbure.", + "prefs.invert_navigator_arrows": "Inverser les flèches de rotation du cube de vue", + "prefs.invert_navigator_arrows_note": "Les flèches autour du cube font orbiter la caméra dans le sens où elles pointent, comme dans Fusion et Inventor : la flèche de gauche pointe vers la droite et fait pivoter la caméra vers la droite. Désactivé : une flèche fait tourner le cube vers le côté où elle se trouve, donc la flèche de gauche fait pivoter la caméra vers la gauche. Les flèches courbes de roulis ne sont pas concernées.", + "prefs.keep_work_on_tab_switch": "Garder dialogues et outils ouverts en changeant de conception", + "prefs.keep_work_on_tab_switch_note": "Chaque onglet de conception garde son dialogue ou son outil ouvert, avec ce que vous y avez sélectionné et saisi, ainsi que son onglet de barre d'outils. Vous les retrouvez en revenant à la conception. Désactivé : changer de conception les annule et affiche l'onglet Modèle.", "prefs.labels": "Libellés", + "prefs.language_system": "Système", "prefs.layout": "Disposition", "prefs.layout_note": "Compacte : ancre les panneaux aux bords de la fenêtre. La transparence du navigateur est disponible en mode Flottante. Changez le côté de l'assistant dans la page Assistant.", "prefs.left": "Gauche", "prefs.left_click": "Clic gauche", "prefs.line_drag_draws_one": "Appuyer et glisser trace une seule ligne", "prefs.line_drag_draws_one_note": "Dans l'outil Ligne, appuyer, faire glisser puis relâcher trace une seule ligne, du point d'appui au point de relâchement, et le tracé s'arrête là. Les clics tracent toujours une chaîne. Désactivé : un glissement place un point là où il est relâché, comme un clic.", + "prefs.line_hover_tangent_arc": "S'arrêter sur le dernier point d'une ligne pour passer à un arc tangent", + "prefs.line_hover_tangent_arc_note": "Dans l'outil Ligne, une fois un segment tracé, éloigner le pointeur du dernier point de la chaîne, revenir et le maintenir immobile dessus : le clic suivant termine un arc tangent, et le même geste revient aux lignes. Désactivé : s'arrêter là ne fait rien.", "prefs.linked_designs": "Conceptions liées", "prefs.live_input": "Saisie en direct", "prefs.live_preview": "Aperçu en direct", @@ -1908,6 +2271,9 @@ "prefs.max_file_size_step": "Fichiers STEP et d’importation", "prefs.max_file_size_web": "L’application web ouvre les fichiers STEP et d’importation jusqu’à 512 Mo et les conceptions jusqu’à 256 Mo : un onglet du navigateur ne peut pas contenir de fichiers plus volumineux. L’application de bureau permet de relever ces limites.", "prefs.megabytes": "Mo", + "prefs.menu_grid": "Grandes icônes", + "prefs.menu_list": "Liste", + "prefs.menus": "Menus", "prefs.minutes": "minutes", "prefs.minutes_suffix": " min", "prefs.mouse": "Souris et pavé tactile", @@ -1915,6 +2281,8 @@ "prefs.mouse_mapping": "Affectation des boutons de la souris", "prefs.navigation": "Navigation", "prefs.navigation_note": "Comment la souris, le pavé tactile et la souris 3D déplacent la vue.", + "prefs.navigator_fit": "Cadrer le modèle après un changement de vue du repère de navigation", + "prefs.navigator_fit_note": "Une face, un coin ou une flèche du cube de vue, ou un axe du gizmo, regarde aussi le milieu du modèle depuis la distance unique qui le cadre sous tous les côtés (sa sphère englobante). Accueil utilise le même zoom et le même centre tant que cette option est activée, de sorte que les vues choisies ensuite ne font que tourner. Désactivé : la vue tourne sur place, en gardant sa cible et son zoom.", "prefs.network_host_remove": "Retirer", "prefs.network_locations": "Autoriser les emplacements réseau dans les conceptions", "prefs.network_locations_note": "Désactivé : les fichiers liés d'une conception situés sur un autre ordinateur (\\\\server\\share) ne sont ouverts que depuis les serveurs listés ici, ou après en avoir autorisé un sur demande.", @@ -1927,10 +2295,18 @@ "prefs.origin_plane_names": "Noms des plans d'origine", "prefs.origin_plane_names_note": "Noms affichés dans le navigateur, les boîtes de dialogue et les listes. {top} est XY, {front} est XZ et {right} est YZ, avec Z vers le haut. Les commandes, les scripts et les conceptions enregistrées gardent XY, XZ et YZ.", "prefs.overall_speed": "Vitesse globale", + "prefs.parameter_list_rows": "Paramètres listés", + "prefs.parameter_list_rows_tip": "La flèche bas dans un champ de valeur vide liste les paramètres, favoris en premier, jusqu'à ce nombre. Moins allège la liste dans un gros design.", + "prefs.persistent_ribbon_pressed": "Mettre en surbrillance les commandes actives du ruban", + "prefs.persistent_ribbon_pressed_help": "Met en surbrillance les commandes du ruban tant que leurs effets sont actifs. Désactivez cette option pour conserver l'apparence neutre précédente et l'aide des commandes.", "prefs.perspective_fov": "Champ de vision", "prefs.placement": "Placement", "prefs.prefer_free_sketch_points": "Privilégier les points d'esquisse déplaçables quand des points se superposent", "prefs.preview_choices": "Aperçu de vos choix", + "prefs.preview_tint_new_faces": "Teinter la nouvelle surface dans un aperçu", + "prefs.preview_tint_new_faces_help": "L'aperçu d'une fonction qui modifie un corps peut tracer la surface qu'elle ajoute dans la couleur d'aperçu. Désactivée, le corps est tracé tel quel.", + "prefs.print_face_highlight": "Mise en évidence de la face d’impression", + "prefs.print_face_highlight_tip": "Intensité de la teinte et du contour de la face d’impression d’un corps dans la vue. 0 % n’affiche aucune mise en évidence.", "prefs.profile_active": "Profil actif", "prefs.profile_applied": "Profil appliqué.", "prefs.profile_changed": "Les réglages ont changé depuis l'enregistrement du profil. Enregistrer les y conserve.", @@ -1952,9 +2328,13 @@ "prefs.quality_fastest": "le plus rapide", "prefs.quality_slowest": "le plus lent", "prefs.quality_smoother": "plus fluide", + "prefs.quick_measure": "Mesure rapide dans le coin de la vue", + "prefs.quick_measure_note": "La taille de la sélection, dans le coin inférieur droit de la vue : la longueur d'une arête, ou Ø et R pour une arête ronde, l'aire d'une face, la position d'un point, la distance et l'angle entre deux éléments, le total de plusieurs arêtes ou faces. Un clic la copie.", "prefs.render_previous_geometry_budget": "Utiliser l'ancien budget de géométrie de l'aperçu Rendu", "prefs.render_previous_geometry_budget_help": "Rétablir l'ancienne limite fixe de géométrie (512 Mio sur un ordinateur 64 bits, 128 Mio ailleurs) au lieu du budget basé sur l'appareil.", "prefs.reports_saved": "Enregistrés : {n}", + "prefs.ribbon_click_ends_tool": "Cliquer sur le bouton de l'outil en cours le termine", + "prefs.ribbon_click_ends_tool_note": "Un clic sur le bouton allumé du ruban de l'outil d'esquisse en cours termine l'outil, et les clics dans la vue sélectionnent de nouveau. Désactivé : le clic relance l'outil.", "prefs.ribbon_reveal": "Montrer les résultats de recherche dans le ruban", "prefs.ribbon_reveal_note": "Survoler un résultat dans Rechercher des commandes montre où se trouve la commande dans le ruban : son onglet, son bouton ou sa ligne dans le menu déroulant d'un panneau. Une commande lancée depuis la recherche y clignote, et une commande en cours issue d'un menu déroulant signale son panneau.", "prefs.right_click": "Clic droit", @@ -1965,6 +2345,8 @@ "prefs.search_empty": "Aucun paramètre correspondant", "prefs.select": "Sélectionner", "prefs.select_one_item": "Sélectionner un élément", + "prefs.select_other_hidden": "Sélectionner la géométrie masquée avec Sélectionner un autre", + "prefs.select_other_hidden_help": "Activé : inclure les corps et les esquisses masqués ainsi que les arêtes occultées près du pointeur. Désactivé : utiliser la liste d'origine de la géométrie visible sous le pointeur.", "prefs.selecting": "Sélection", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Maj ajoute seulement ; Ctrl / Cmd bascule", @@ -1976,31 +2358,63 @@ "prefs.sketch_align_points_note": "Pendant le dessin, un point s'aligne à la fois horizontalement sur un point d'esquisse et verticalement sur un autre, avec un guide en pointillés, et le clic conserve les deux alignements. Désactivé : uniquement sur le point précédent, un axe à la fois.", "prefs.sketch_conflict_colour": "Géométrie en conflit dans la couleur de conflit", "prefs.sketch_conflict_colour_note": "Tant que les contraintes d'une esquisse sont en conflit, les courbes et les points que retient une contrainte en échec sont aussi dessinés dans la couleur de conflit, et pas seulement son symbole ou sa cote. Désactivé : ils gardent leurs couleurs habituelles.", + "prefs.sketch_construction_lines": "Outils étendus de droites de construction", "prefs.sketch_exit_view": "À la fin d'une esquisse", "prefs.sketch_exit_view.keep": "Garder la vue actuelle", "prefs.sketch_exit_view.previous": "Revenir à la vue précédente", "prefs.sketch_exit_view.unless_rotated": "Revenir, sauf si la vue a été tournée", "prefs.sketch_exit_view_note": "Où va la vue après Terminer l'esquisse, Annuler ou un double Échap.", + "prefs.sketch_face_activates_part": "Esquisser sur la face d'une pièce active cette pièce", + "prefs.sketch_face_activates_part_note": "Une esquisse commencée sur une face du corps d'un autre composant active d'abord ce composant, de sorte que l'esquisse lui appartient et reste avec cette pièce dans le navigateur. La pièce reste ensuite active. Désactivé : l'esquisse appartient au composant actif.", + "prefs.sketch_open_look_at": "Se placer face à l'esquisse à son ouverture", + "prefs.sketch_open_look_at_note": "Désactivé : créer ou modifier une esquisse laisse la vue telle quelle. Vue normale place la vue face à l'esquisse quand vous le souhaitez.", "prefs.sketch_recent_snap": "Accrocher automatiquement aux centres et points milieux récents", "prefs.sketch_recent_snap_note": "Pendant le dessin, le curseur s'accroche là où se croisent les guides des deux derniers centres de cercle ou points milieux de segment droit. Désactivé : ces guides restent purement visuels et le curseur ne bouge pas.", "prefs.sketch_selection": "Esquisse et sélection", "prefs.sketch_selection_heading": "Esquisse et sélection", "prefs.sketch_selection_note": "Comment les esquisses s'accrochent et comment les clics sélectionnent.", + "prefs.sketch_state_icons": "Icônes d'esquisse dans la couleur de leur état", + "prefs.sketch_state_icons_note": "Dans l'historique et le navigateur, l'icône d'une esquisse prend la couleur de son état (sous-contraint, entièrement contrainte ou en conflit) et son infobulle nomme cet état. Désactivé : toutes les esquisses ont la même icône.", "prefs.sketch_tab_always": "Toujours afficher l'onglet Esquisse", "prefs.sketch_tab_always_note": "L'onglet Esquisse reste dans le ruban, juste après Modèle, tant qu'aucune esquisse n'est ouverte. Ses outils de dessin démarrent alors une esquisse sur le plan ou la face sélectionnés, ou sur le plan que vous choisissez ensuite, avec l'outil prêt à l'emploi.", "prefs.sketch_tracking_guides": "Guides d'alignement sur le centre et le point milieu", "prefs.sketch_tracking_guides_note": "Survolez le centre d'un cercle ou le point milieu d'un segment droit, puis déplacez le pointeur horizontalement ou verticalement pour afficher un guide pointillé temporaire.", + "prefs.sketch_tracking_points": "Guides d'alignement depuis les extrémités et les coins pendant le dessin", + "prefs.sketch_tracking_points_note": "Quand un outil de dessin attend un point, survoler l'extrémité d'une ligne ou d'un arc, le coin d'un rectangle ou un point libre affiche le même guide pointillé temporaire qu'un centre ou un point milieu. Désactivé : seulement les centres et les points milieux.", "prefs.sketching": "Esquisse", "prefs.snap_drawing_note": "Pendant le dessin ou le déplacement d'un point d'esquisse.", "prefs.source": "Source", "prefs.speed": "Vitesse", "prefs.stand_up_note": "Après l'ouverture d'un fichier STEP ou IGES en Z vers le haut, proposer un quart de tour autour de X.", + "prefs.stand_up_unknown": "Pour les fichiers de programmes inconnus", + "prefs.stand_up_unknown.ask": "Demander dans une boîte de dialogue", + "prefs.stand_up_unknown.note": "Afficher une note", + "prefs.stand_up_unknown.off": "Ne pas proposer", + "prefs.stand_up_unknown_note": "Comment la proposition est faite quand l'en-tête du fichier ne nomme aucun programme connu pour enregistrer en Y vers le haut. Une note ne s'affiche que lorsque le fichier semble couché sur le dos ; Demander dans une boîte de dialogue pose la question pour chaque fichier de ce genre, comme avant.", "prefs.status_bar": "Barre d'état", "prefs.status_bar_note": "Une barre fine en bas de la fenêtre indique ce qui est en cours de modification, l'état de l'esquisse ouverte par sa couleur et les unités de la conception ; un clic sur les unités permet de les changer. L'état de l'esquisse n'apparaît alors plus dans le coin de la vue.", "prefs.status_done": "Terminé", "prefs.status_error": "Erreur", "prefs.status_selected": "Sélectionné", "prefs.status_warning": "Avertissement", + "prefs.structure.appearance": "Apparence", + "prefs.structure.appearance_note": "Couleurs, texte et accessibilité.", + "prefs.structure.in_profile": "Dans le profil", + "prefs.structure.layout": "Disposition", + "prefs.structure.layout_note": "Où se placent les parties de la fenêtre.", + "prefs.structure.look": "Aspect", + "prefs.structure.measure_pointer": "Mesure et pointeur", + "prefs.structure.mouse3d": "Souris 3D", + "prefs.structure.mouse3d_note": "SpaceMouse et SpaceNavigator.", + "prefs.structure.navigation_note": "Souris et pavé tactile. La souris 3D a sa propre page.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Modifié depuis l'enregistrement", + "prefs.structure.profile_hover": "Enregistré dans les profils de réglages", + "prefs.structure.scale_percent": "{percent} %", + "prefs.structure.sketch": "Esquisse", + "prefs.structure.tools": "Outils", + "prefs.structure.tools_note": "Comportement des outils de modélisation.", + "prefs.structure.work": "Travail", "prefs.supersampling_brief": "Dessine la vue en plus grand puis la réduit par filtrage : très net, mais plus lourd.", "prefs.tab_accent_note": "La couleur d'accent suit l'onglet actif", "prefs.theme_file": "fichier de thème", @@ -2012,6 +2426,16 @@ "prefs.theme_follow_off": "Désactivé", "prefs.theme_follow_stop": "Arrêter le suivi", "prefs.theme_import_hint": "Cliquez pour choisir un fichier de thème, déposez-en un ici, ou appuyez sur Ctrl+V (Cmd+V sur Mac) avec un thème copié", + "prefs.theme_option_opacity": "Opacité", + "prefs.theme_option_opacity_help": "Règle l'opacité des panneaux flottants. Un seuil de lisibilité protège le texte placé sur les couleurs de la vue 3D.", + "prefs.theme_option_tab_colours": "Couleurs des onglets", + "prefs.theme_option_tab_colours_help": "Utilise les couleurs de panneau et de vue 3D de ce thème pour chaque onglet du ruban.", + "prefs.theme_option_tab_fade_ms": "Transition des onglets", + "prefs.theme_option_tab_fade_ms_help": "Fait passer progressivement les couleurs du panneau et de la vue 3D au changement d'onglet. Zéro bascule instantanément.", + "prefs.theme_options_badge": "Options", + "prefs.theme_options_more": "Plus · {count}", + "prefs.theme_options_reset": "Réinitialiser", + "prefs.theme_options_unavailable": "Indisponible sur cet appareil", "prefs.theme_paste": "Coller le thème", "prefs.theme_paste_none": "Le presse-papiers ne contient aucun thème SolidCraft", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2457,23 @@ "prefs.under_cursor": "Sous le curseur", "prefs.units_precision": "Unités et précision", "prefs.updates": "Mises à jour", + "prefs.value_boxes_in_view": "Afficher les valeurs à côté de leurs poignées dans la vue", + "prefs.value_boxes_in_view_tip": "La valeur d'une commande (distance, rayon…) dans une case à côté de sa poignée, par-dessus le modèle. Désactivé : vous la saisissez dans la fenêtre de la commande, qui prend le clavier après une sélection, et rien ne masque le modèle.", "prefs.view": "Comportement de la vue", "prefs.view_confirm_corner": "OK et Annuler dans le coin de la vue", "prefs.view_confirm_corner_note": "Lorsqu'une boîte de dialogue ou une esquisse est ouverte, une coche et une croix en haut à droite de la vue font la même chose que OK et Annuler, ou terminent et annulent l'esquisse. Le repère de navigation se place en dessous.", "prefs.viewport": "Vue 3D", + "prefs.viewport_analysis_status": "Afficher l'état d'analyse de la vue 3D", + "prefs.viewport_analysis_status_help": "Afficher les analyses actives au-dessus de la vue 3D, ouvrir leur légende depuis chaque élément et utiliser Échap pour désactiver l'analyse la plus récente. Désactiver pour rétablir les légendes dans les coins et l'ancien comportement d'Échap.", "prefs.viewport_background": "Fond", "prefs.viewport_background_colour": "Couleur", "prefs.viewport_background_theme": "Dégradé du thème", + "prefs.viewport_section_status": "Afficher l'état de la coupe dans la vue 3D", + "prefs.viewport_section_status_help": "Affiche le réglage de coupe dans la vue 3D. Échap et le bouton actif du ruban le désactivent. Désactivez cette option pour conserver les contrôles de coupe précédents.", + "prefs.viewport_status_details": "Détails de la vue 3D modifiables", + "prefs.viewport_status_details_help": "Modifie les réglages de l'analyse et de la coupe actives dans des fiches de détails standard. Désactivez cette option pour retrouver les légendes d'analyse en lecture seule et la boîte de dialogue Coupe.", + "prefs.viewport_status_summary": "Regrouper les éléments d'état de la vue 3D", + "prefs.viewport_status_summary_help": "Regroupe trois éléments d'état de la vue 3D ou plus dans un seul badge de synthèse. Désactivez cette option pour garder tous les éléments sur la ligne complète.", "prefs.wheel": "Molette", "prefs.wheel_trackpad": "Molette et pavé tactile", "prefs.workspace": "Espace de travail", @@ -2168,6 +2602,10 @@ "render.base_color": "Couleur de base · sRVB", "render.base_metallic": "Fraction métallique", "render.base_opaque_only": "Cet éditeur conserve la sémantique des corps opaques. Utilisez les commandes de verre dédiées pour la transmission optique.", + "render.batch_all_shots": "Toutes les prises de vue ({count})", + "render.batch_empty": "Enregistrer une prise de vue avant de rendre toutes les prises de vue.", + "render.batch_limit": "Le rendu de toutes les prises de vue est limité à 32 prises de vue.", + "render.batch_status": "{running} en cours · {waiting} en attente", "render.bloom_enable": "Halo lumineux (bloom) à l'affichage", "render.bloom_help": "Lueur créative appliquée à la sortie seulement, à partir des hautes lumières linéaires positives, étalée par trois passes de flou normalisées. Le rayon est en pixels de sortie. Ajoutée en lumière d'affichage linéaire avant sRVB ; ce n'est ni un effet d'objectif, ni un effet volumétrique, ni une amélioration de la convergence. L'EXR brut est inchangé.", "render.bloom_opaque": "Le halo lumineux nécessite une sortie opaque. Un PNG transparent est refusé, pas aplati en silence.", @@ -2278,6 +2716,13 @@ "render.choose_look": "Choisissez d'abord un aspect dans Apparences", "render.chromatic_offset": "Décalage chromatique des bords", "render.clear_stage": "Supprimer le décor enregistré", + "render.compare_divider": "Séparateur de comparaison", + "render.compare_live": "En direct", + "render.compare_live_preview": "Aperçu en direct", + "render.compare_render": "Rendu {number}", + "render.compare_side": "Rendu {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · capturé à la révision {revision}", + "render.compare_swap": "Inverser", "render.copy_request": "Copier le JSON", "render.cpu_aa_help": "Échantillons spatiaux : plus d'échantillons améliorent les bords et allongent le rendu.", "render.cpu_area_add": "Ajouter une lumière CPU rectangulaire", @@ -2918,7 +3363,9 @@ "render.output_ready": "Prêt à lancer le rendu", "render.output_run_check": "Lancer la vérification", "render.output_size_limit": "{method} : jusqu'à {dimension} px par côté et {pixels} pixels. Plus grande taille possible : {width} × {height}.", + "render.output_size_method_profile": "Pour un rendu en {width} × {height}, choisissez {method} avec le profil de ressources CPU {profile}, ou une taille plus petite.", "render.output_size_ok": "Taille correcte · {width} × {height} px", + "render.output_size_profile": "Pour un rendu en {width} × {height}, choisissez le profil de ressources CPU {profile}, ou une taille plus petite.", "render.output_swap_orientation": "Permuter largeur et hauteur", "render.output_tools_inspector": "Modifier la taille et le format dans l'inspecteur Sortie.", "render.output_view_image": "Afficher l'image", @@ -3025,6 +3472,10 @@ "render.result_retained": "Affichage de la dernière image terminée ; un rendu plus récent ne l'a pas remplacée.", "render.result_sequence": "Point de restauration", "render.result_title": "Résultat du rendu", + "render.results_choose": "Résultats conservés", + "render.results_label": "Rendu {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [obsolète]", + "render.results_unnamed": "Image", "render.return_design": "Revenir à la conception", "render.review_stale": "Cet examen est périmé. Résolvez ou vérifiez à nouveau avant d'appliquer.", "render.ribbon_aging": "Vieillissement", @@ -3131,6 +3582,7 @@ "render.size_custom": "Personnalisé…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · nécessite {profile}", "render.size_presets": "Préréglages de taille", "render.size_presets_pending": "Arrive avec l'éditeur Sortie", "render.size_preview": "Aperçu", @@ -3418,6 +3870,24 @@ "sheet.flange_type_contour": "Contour", "sheet.flange_type_edge": "Arête", "sheet.no_body": "il n'y a pas de corps de tôlerie : commencez-en un avec Bord tombé > Base, ou transformez une plaque en tôlerie avec Convertir en tôlerie (choisissez sa grande face plane)", + "sheet.personal_rules.confirm_delete": "Confirmer la suppression", + "sheet.personal_rules.delete": "Supprimer", + "sheet.personal_rules.delete_prompt": "Supprimer cette règle personnelle ? Les règles déjà présentes dans les conceptions ne changent pas.", + "sheet.personal_rules.full": "La bibliothèque personnelle contient déjà 64 règles.", + "sheet.personal_rules.invalid_name": "Saisissez un nom court, sans saut de ligne ni caractère de contrôle.", + "sheet.personal_rules.invalid_values": "Complétez les valeurs de la règle : chacune doit pouvoir être calculée dans cette conception, avec une épaisseur positive et un facteur K compris entre 0 et 1.", + "sheet.personal_rules.missing": "La règle personnelle sélectionnée n'est plus disponible.", + "sheet.personal_rules.name": "Nom de la règle", + "sheet.personal_rules.name_exists": "Une règle personnelle porte déjà ce nom. Choisissez-en un autre.", + "sheet.personal_rules.name_hint": "Un nom unique", + "sheet.personal_rules.overwrite": "Enregistrer les modifications de la règle personnelle sélectionnée", + "sheet.personal_rules.rename": "Renommer", + "sheet.personal_rules.rule": "Règle personnelle", + "sheet.personal_rules.save": "Enregistrer comme nouvelle", + "sheet.personal_rules.scope": "Enregistrée dans votre profil, pour toutes les conceptions.", + "sheet.personal_rules.select": "Choisir une règle", + "sheet.personal_rules.title": "Règles personnelles", + "sheet.personal_rules.unsupported": "Cette règle contient des valeurs que cette version ne peut pas utiliser.", "shortcut.json_error": "les paramètres doivent être au format JSON : {error}", "shortcut.no_command": "la commande `{id}` n’existe pas ; le texte avant le JSON doit être un ID de commande", "shortcut.pin": "Épingler en haut de la boîte S", @@ -3454,8 +3924,10 @@ "sketch_text.align_right": "Droite", "sketch_text.bold": "Gras", "sketch_text.builtin_font": "{family} (intégrée)", + "sketch_text.formula": "Commencez par = pour composer le texte avec des paramètres : ='L' + number(Largeur)", "sketch_text.italic": "Italique", "sketch_text.loading_fonts": "Recherche des polices installées…", + "sketch_text.no_bold": "La police intégrée n'a pas de graisse grasse : choisir une police installée", "sketch_text.on_path": "Le texte suit sa trajectoire : la courbe le positionne", "sketch_text.path_clear": "Détacher le texte de sa courbe", "sketch_text.path_hint": "Une courbe de l'esquisse que le texte suit : cliquer ici, puis sur la courbe", @@ -3487,10 +3959,7 @@ "the two origins are on the same component": "les deux origines se trouvent sur le même composant", "thread.automatic_size": "Taille automatique", "thread.designation": "Désignation", - "thread.direction": "Sens du filetage", "thread.iso_metric": "Métrique ISO", - "thread.left_hand": "À gauche", - "thread.right_hand": "À droite", "thread.select_size": "Sélectionner la taille", "timeline.delete_after_marker_one": "Supprimer 1 fonction après le marqueur d'historique", "timeline.delete_after_marker_other": "Supprimer {count} fonctions après le marqueur d'historique", @@ -3507,8 +3976,10 @@ "timeline.move_to_group": "Déplacer les fonctions vers le dossier", "timeline.rename_group": "Renommer le dossier de fonctions", "timeline.reorder_many": "Réordonner les fonctions", + "timeline.suppress_features": "Désactiver les fonctions", "timeline.suppress_folders_tip": "Désactiver ou réactiver toutes les fonctions des dossiers et de leurs dossiers imbriqués", "timeline.ungroup": "Supprimer les dossiers de fonctions", + "timeline.unsuppress_features": "Réactiver les fonctions", "to the face": "jusqu'à la face", "to the next face": "jusqu'à la face suivante", "toolbar.customize_note": "Onglet {tab}. Cochez une commande pour lui attribuer un bouton dans la barre d’outils. Vous pouvez aussi faire glisser une ligne du menu déroulant d’un panneau vers la barre d’outils, retirer un bouton en le faisant glisser hors de la barre ou utiliser l’épingle d’une ligne du menu déroulant.", @@ -3592,6 +4063,8 @@ "ui.3d_mouse_section": "Souris 3D", "ui.3d_mouse_show_in_view": "Afficher la souris 3D dans la vue 3D", "ui.3d_mouse_show_in_view_tip": "Une image de votre souris 3D dans le coin inférieur gauche, qui bouge quand vous la bougez.", + "ui.3d_mouse_sketch_orbit": "Faire pivoter les esquisses avec la souris 3D", + "ui.3d_mouse_sketch_orbit_tip": "La souris 3D fait aussi pivoter la vue quand une esquisse est ouverte et vue de face, comme la souris. Désactivé : elle déplace et zoome l'esquisse jusqu'à ce que vous incliniez la vue.", "ui.3d_mouse_skip": "Mon appareil ne peut pas le faire", "ui.3d_mouse_skip_tip": "Ignore ce mouvement dans les deux sens ; la calibration le laisse de côté.", "ui.3d_mouse_speed": "Vitesse de la souris 3D", @@ -3620,6 +4093,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Tournez le capuchon dans le sens antihoraire, maintenez, puis relâchez.", "ui.3d_mouse_switch_cap": "Calibrer comme retour au centre", "ui.3d_mouse_switch_trackball": "Calibrer comme un trackball", + "ui.3d_mouse_use_direct": "Utiliser le pilote direct", + "ui.3d_mouse_use_direct_tip": "Lire la souris 3D directement (hidraw) au lieu de passer par spacenavd.", "ui.3d_mouse_view_axis": "Axe de la vue", "ui.3d_mouse_view_off": "Désactivé", "ui.3d_mouse_view_off_tip": "Le profil du pilote de la souris 3D désactive cet axe : son mouvement ne déplace pas la vue. Choisir ici le mouvement d'un autre axe les échange, et ce mouvement cesse de déplacer la vue.", @@ -3658,6 +4133,7 @@ "ui.agent_chat_auth_terminal": "Exécuter ceci dans un terminal, puis appuyer de nouveau sur Connecter :", "ui.agent_chat_auth_title": "Authentification auprès de l'agent", "ui.agent_chat_cancel": "Annuler", + "ui.agent_chat_cannot_start": "Installé, mais ne démarre pas : {error}", "ui.agent_chat_changes": "Modifications : {n}, en une seule étape d'annulation", "ui.agent_chat_changes_n": "Modifications : {n}", "ui.agent_chat_changes_of": "{n}/{limit} modifications", @@ -3666,11 +4142,13 @@ "ui.agent_chat_command": "Commande de l'agent", "ui.agent_chat_connect": "Connecter", "ui.agent_chat_copy": "Copier", + "ui.agent_chat_copy_message": "Copier le message", "ui.agent_chat_ctx_bodies": "Corps", "ui.agent_chat_ctx_elements": "Éléments", "ui.agent_chat_ctx_features": "Fonctions", "ui.agent_chat_ctx_more": "+{n} de plus", "ui.agent_chat_ctx_other": "Autre", + "ui.agent_chat_custom_heading": "Modèle personnalisé", "ui.agent_chat_custom_hint": "Tout programme qui parle l'Agent Client Protocol sur stdin et stdout. Aucun shell ne le lance.", "ui.agent_chat_denied": "Refusé", "ui.agent_chat_deny": "Refuser", @@ -3714,8 +4192,16 @@ "ui.agent_chat_mode_all": "Tout", "ui.agent_chat_mode_ask": "Demander", "ui.agent_chat_mode_edits": "Édition", + "ui.agent_chat_model_custom": "Utiliser le modèle personnalisé : {model}", "ui.agent_chat_model_no_tools": "{model} ne peut pas utiliser les outils de SolidCraft : il peut seulement discuter. Choisissez un modèle qui prend en charge les outils.", + "ui.agent_chat_model_rejected": "L'agent n'a pas accepté {model} : {error}", + "ui.agent_chat_model_search": "Rechercher des modèles…", "ui.agent_chat_model_tip": "Le modèle utilisé par l'agent. Votre choix est mémorisé pour cet agent.", + "ui.agent_chat_models_failed": "Impossible de lister les modèles : {error}", + "ui.agent_chat_models_heading": "Modèles disponibles", + "ui.agent_chat_models_listing": "Liste des modèles en cours…", + "ui.agent_chat_models_none": "Le point d'accès ne liste aucun modèle", + "ui.agent_chat_models_not_a_list": "La réponse n'était pas une liste de modèles", "ui.agent_chat_new": "Nouveau chat", "ui.agent_chat_new_confirm": "Démarrer un nouveau chat ? Le chat actuel sera effacé.", "ui.agent_chat_next_picture": "Image suivante", @@ -3750,9 +4236,12 @@ "ui.agent_chat_queued_stopped": "En file d'attente (arrêté, non envoyé)", "ui.agent_chat_refresh": "Actualiser", "ui.agent_chat_refused": "Interdit à l'agent : {reason}", + "ui.agent_chat_reinstall": "{agent} est installé ({program}), mais n'a pas démarré quand SolidCraft l'a vérifié : {error}\nSon installation est peut-être incomplète, ou prévue pour un autre type d'ordinateur. Réinstallez-le avec `{install}`, vérifiez qu'il affiche sa version dans un terminal, puis cliquez sur Actualiser.", "ui.agent_chat_remove": "Retirer de la file d'attente", "ui.agent_chat_remove_file": "Retirer de ce message", "ui.agent_chat_remove_imported": "Retirer de ce message ; la pièce reste dans la conception (Annuler la retire)", + "ui.agent_chat_reply_cut_off": "La réponse a atteint sa longueur maximale avant la fin : elle est peut-être incomplète. Demandez à l'agent de continuer, ou une réponse plus courte.", + "ui.agent_chat_reply_declined": "Le modèle a refusé de répondre à ce message.", "ui.agent_chat_retry": "Réessayer", "ui.agent_chat_right": "Droite", "ui.agent_chat_save": "Enregistrer", @@ -3811,12 +4300,17 @@ "ui.ai_copy_suffix": "copie", "ui.ai_custom_url": "URL personnalisée", "ui.ai_default": "Par défaut", + "ui.ai_edit": "Modifier", + "ui.ai_edit_agent_title": "Modifier l'agent", + "ui.ai_edit_gone": "Cet agent a été retiré : il n'y a rien à enregistrer.", + "ui.ai_edit_tip": "Modifier le nom, la commande ou le point d'accès de cet agent. La clé enregistrée reste masquée.", "ui.ai_http_busy": "le point d'accès est occupé ou a dépassé sa limite ; réessayez plus tard", "ui.ai_http_key": "le point d'accès a refusé la clé : vérifiez-la dans Préférences › IA", "ui.ai_http_not_found": "point d'accès ou modèle introuvable : vérifiez l'URL de base et le nom du modèle", "ui.ai_http_too_large": "la conversation est trop volumineuse pour ce point d'accès ; commencez une nouvelle discussion", "ui.ai_key": "Clé d'API", "ui.ai_key_hint": "facultative ; conservée dans le trousseau de clés du système", + "ui.ai_key_keep_hint": "laisser vide pour garder la clé enregistrée", "ui.ai_key_needs_https": "Une clé n'est envoyée qu'en HTTPS, ou vers cet ordinateur.", "ui.ai_key_note": "Stockée dans le trousseau de clés du système, jamais dans les réglages de SolidCraft. Laisser vide pour un serveur local.", "ui.ai_keychain_error": "Le trousseau de clés du système a refusé : {error}", @@ -3843,11 +4337,15 @@ "ui.ai_permissions": "Autorisations", "ui.ai_preset": "Préréglage", "ui.ai_protocol": "Protocole", + "ui.ai_reasoning_effort": "Effort de raisonnement", + "ui.ai_reasoning_effort_field_hint": "vide = valeur par défaut du fournisseur", + "ui.ai_reasoning_effort_hint": "Facultatif. Envoyé au point d'accès sous le nom `reasoning_effort` ; les valeurs acceptées varient selon le fournisseur (par exemple `low`, `high` ou `max`). Une valeur saisie ici n'est jamais remplacée par SolidCraft. Laisser vide pour ne rien envoyer et garder la valeur par défaut du fournisseur.", "ui.ai_remove": "Retirer", "ui.ai_request_timed_out": "Le modèle a mis plus de {seconds} s. Vous pouvez augmenter le délai d'expiration des requêtes de ce point d'accès dans Préférences › Assistant.", "ui.ai_request_timeout": "Délai d'expiration des requêtes", "ui.ai_request_timeout_hint": "Durée maximale d'une requête au modèle de ce point d'accès, de 30 s à une heure. Augmentez-la pour un modèle local lent.", "ui.ai_reset": "Réinitialiser", + "ui.ai_save": "Enregistrer", "ui.ai_settings": "Réglages IA…", "ui.ai_show_features": "Afficher les fonctionnalités IA", "ui.ai_show_features_note": "Le chat de l'agent : un panneau où un agent de programmation que vous utilisez déjà, ou un point d'accès de modèle de votre choix, travaille sur la conception ouverte. Désactivé : ni bouton IA, ni raccourci, ni entrée de menu, ni panneau, et rien n'est recherché ni lancé.", @@ -3926,6 +4424,8 @@ "ui.cancel": "Annuler", "ui.canvases": "Canevas", "ui.center": "Centre", + "ui.center_arc_follows_cursor": "L'arc par centre suit le sens du curseur", + "ui.center_arc_follows_cursor_tip": "Un arc par centre tourne dans le sens horaire ou antihoraire selon la façon dont le curseur tourne autour de son centre. Désactivé : toujours dans le sens antihoraire depuis le début.", "ui.centerline": "Ligne de construction", "ui.chain": "Chaîne", "ui.chamfer": "Chanfrein", @@ -3934,6 +4434,7 @@ "ui.circle": "Cercle", "ui.circular_pattern": "Répétition circulaire", "ui.clear": "Effacer", + "ui.clear_print_face": "Effacer la face d’impression", "ui.clear_recent": "Effacer les récents", "ui.clear_the_selection": "Effacer la sélection", "ui.click_selects_whole_bodies": "Un clic sélectionne des corps entiers", @@ -3968,12 +4469,27 @@ "ui.constant": "Constant", "ui.constraints_conflict": "Contraintes en conflit", "ui.construction": "Construction", + "ui.construction.angle_hint": "Droite de construction : cliquez sur un point, puis saisissez un angle ou choisissez une direction", + "ui.construction.bisector_hint": "Bissectrice : sélectionnez deux lignes droites sécantes, puis la solution souhaitée", + "ui.construction.common_hint": "Tangente commune : sélectionnez deux cercles/arcs, puis la solution souhaitée", + "ui.construction.contact_hint": "Tangente : sélectionnez un cercle/arc ou une spline/conique ouverte, puis le point de contact (courbes libres : extrémités)", + "ui.construction.external_hint": "Tangente : sélectionnez un cercle ou un arc, un point extérieur, puis la solution souhaitée", + "ui.construction.free_hint": "Droite de construction : cliquez sur deux points ; clic droit pour recommencer", + "ui.construction.normal_needs_length": "Une ligne infinie est toujours de construction : saisir une longueur pour tracer une ligne normale", + "ui.construction.point_hint": "Droite de construction : cliquez sur le point de passage", + "ui.construction.reference_hint": "Droite de construction : sélectionnez une ligne droite, puis un point ; clic droit pour changer la référence", "ui.construction.ribbon_label": "Lignes aux.", + "ui.construction.side_hint": "Ligne de construction : cliquer du côté vers lequel la ligne s'étend ; clic droit pour recommencer", "ui.context_menu": "Menu contextuel", + "ui.continuity_crease": "Angle vif", + "ui.continuity_curvature": "Courbure", + "ui.continuity_curvature_change": "Variation de courbure", "ui.continuity_g0": "G0 angle vif", "ui.continuity_g1": "G1 tangence", "ui.continuity_g2": "G2 courbure", "ui.continuity_gap": "Écart", + "ui.continuity_position": "Position", + "ui.continuity_tangent": "Tangence", "ui.copy": "Copier", "ui.corner": "Angle", "ui.corners": "Angles", @@ -3996,6 +4512,7 @@ "ui.dark": "Sombre", "ui.default_modelling_orientation": "Orientation de modélisation par défaut", "ui.delete": "Supprimer", + "ui.delete_select_first": "Sélectionner d'abord ce qu'il faut supprimer : fonctions, corps, composants ou géométrie d'esquisse", "ui.depth": "Profondeur", "ui.design": "Conception", "ui.design_properties.author": "Auteur", @@ -4010,6 +4527,40 @@ "ui.design_properties.project": "Projet", "ui.design_properties.revision": "Indice", "ui.design_saved": "Enregistré dans {path}", + "ui.details_access_caption": "Les faces indiquent si un outil peut les atteindre depuis la direction choisie.", + "ui.details_angle": "Angle", + "ui.details_continuity_caption": "Modifie la jonction sélectionnée. Les autres jonctions gardent leurs propres réglages.", + "ui.details_continuity_stale": "Géométrie antérieure : relancez l'analyse pour modifier ou cadrer cette jonction.", + "ui.details_copy_list": "Copier la liste", + "ui.details_curvature": "Tolérance de courbure", + "ui.details_curvature_caption": "Les faces sont colorées selon leur rayon de courbure local.", + "ui.details_direction": "Direction de l'outil", + "ui.details_draft_caption": "Les faces sont colorées selon leur angle avec la direction de démoulage.", + "ui.details_edit_seam": "Modifier la jonction", + "ui.details_fixture": "Spécimen de composant — données d'exemple uniquement", + "ui.details_fixture_caption": "Spécimen de composant avec des valeurs d'illustration ; ce n'est pas un résultat du modèle.", + "ui.details_fixture_problem": "Exemple de constat signalant un problème", + "ui.details_fixture_readout": "Exemple de valeur mesurée", + "ui.details_flip": "Inverser", + "ui.details_gap": "Écart", + "ui.details_hatch": "Hachurer les faces coupées", + "ui.details_jump": "Saut de courbure", + "ui.details_key": "Légende", + "ui.details_offset": "Décalage", + "ui.details_plane": "Plan", + "ui.details_pull": "Direction de démoulage", + "ui.details_radius": "Rayon", + "ui.details_readout": "Valeur affichée", + "ui.details_samples": "Échantillons", + "ui.details_seam": "{body} · Arête {edge}", + "ui.details_settings": "Réglages", + "ui.details_sharp_gap": "Vive ou ouverte", + "ui.details_show_all": "Tout afficher ({count})", + "ui.details_smooth": "Lisse", + "ui.details_stripes": "Bandes", + "ui.details_target": "Cadrer la géométrie", + "ui.details_worst_seams": "Pires jonctions", + "ui.details_zebra_caption": "Les bandes réfléchies montrent la régularité du raccord entre les faces.", "ui.diameter": "Diamètre", "ui.dimension": "Cote", "ui.direct_interaction": "Interaction directe", @@ -4054,6 +4605,7 @@ "ui.edit_in_place_saved_elsewhere": "La pièce a été enregistrée dans un autre fichier ; l'assemblage reste lié à {name}", "ui.edit_in_place_wait": "Attendez la fin de ce qui s'exécute dans la conception", "ui.edit_section_analysis": "Modifier l'analyse de coupe", + "ui.edit_sketch_empty": "Aucune esquisse à modifier", "ui.ellipse": "Ellipse", "ui.emboss_wrap_note": "Les profils de lignes orthogonales tangents à un cylindre pris en charge s'enroulent automatiquement. Choisir une paroi pour définir une cible.", "ui.end_radius": "Rayon final", @@ -4064,12 +4616,15 @@ "ui.equation_explicit": "Explicite", "ui.equation_form": "Forme", "ui.equation_note": "La variable est un simple nombre : sin(t) la prend en radians. Un résultat sans unité est dans l'unité de la conception.", + "ui.equation_note_range": "La variable est une longueur, comme sa plage : la combiner avec des paramètres de longueur, et la diviser par une longueur pour sin(). Un résultat sans unité est dans l'unité de la conception.", "ui.equation_parametric": "Paramétrique", + "ui.equation_variable_unit": "La variable a l'unité de la plage", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Rayon équivalent", "ui.expand": "Développer", + "ui.explode_needs_two_components": "La vue éclatée écarte les composants les uns des autres : la conception doit en contenir au moins deux (Nouveau composant, Insérer une conception ou Créer des composants à partir des corps)", "ui.exportDxf": "Exporter en DXF…", "ui.export_ellipsis_keymap": "Exporter…", "ui.export_keymap_tip": "Raccourcis, favoris de la boîte S et barre d'outils, dans un fichier", @@ -4195,6 +4750,7 @@ "ui.hideOrigin": "Masquer l'origine", "ui.hidePlanes": "Masquer les plans", "ui.hideProfile": "Masquer le profil", + "ui.hide_component_history": "Masquer son historique", "ui.hide_origin_by_default": "Masquer l'origine par défaut", "ui.hide_origin_note": "Les nouvelles conceptions démarrent avec le dossier Origine masqué. Une conception garde son propre réglage d'Origine dès que vous l'affichez ou la masquez.", "ui.history_back": "Reculer d’une étape", @@ -4202,6 +4758,7 @@ "ui.history_edge_hint": "double-cliquer sur le bord", "ui.history_first": "Aller au début", "ui.history_forward": "Avancer d’une étape", + "ui.history_hide_hidden": "Masquer les composants masqués", "ui.history_hide_names": "Masquer les noms", "ui.history_last": "Aller à la fin", "ui.history_marker_tip": "Marqueur d'historique : faire glisser pour ramener le modèle en arrière ; les nouvelles fonctions s'insèrent ici", @@ -4211,6 +4768,7 @@ "ui.history_play_button_show": "Afficher le bouton Lire", "ui.history_play_finish_action": "Terminez l'action en cours avant de lire l'historique", "ui.history_play_roll_back": "Reculez le marqueur d'historique avant de lire", + "ui.history_show_hidden": "Afficher les composants masqués", "ui.history_show_names": "Afficher les noms", "ui.history_sketch_listed_under": "Listé sous {feature}", "ui.history_title": "Historique", @@ -4230,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} contient des modifications non enregistrées ; c'est donc son fichier enregistré qui a été inséré. Enregistrez-le, puis utilisez Mettre à jour les liens pour intégrer les modifications.", "ui.insert_design.unsaved": "Modifications non enregistrées", "ui.inspect": "Inspecter", + "ui.instances": "Instances", "ui.intersect": "Intersection", "ui.isolate": "Isoler", "ui.join": "Joindre", @@ -4238,12 +4797,14 @@ "ui.joints": "Liaisons", "ui.keyboard_shortcuts": "Raccourcis clavier", "ui.language": "Langue", + "ui.lasso_select": "Lasso (faire glisser une boucle libre : prend ce qui est entièrement à l'intérieur)", "ui.layout_compact": "Compacte", "ui.layout_floating": "Flottante", "ui.length": "Longueur", "ui.length_decimals": "Décimales des longueurs", "ui.light": "Clair", "ui.line": "Ligne", + "ui.line_arc_hint": "Arc tangent : cliquer sur l'extrémité de l'arc. S'arrêter de nouveau sur le dernier point pour revenir aux lignes ; clic droit ou Échap pour terminer", "ui.link_copies": "Lier les copies identiques", "ui.link_copies_keep": "Conserver", "ui.link_copies_link": "Lier", @@ -4332,6 +4893,7 @@ "ui.part_size_shared": "Reconstruit la pièce en remplaçant les entités ajoutées. Toutes les occurrences de ce composant sont mises à jour.", "ui.paste": "Coller", "ui.path": "Trajectoire", + "ui.pattern_object_type_tip": "Corps : formes pleines, choisies dans la vue ou le Navigateur ; chacun est copié en entier.\nFonctions : étapes de l'Historique, comme une extrusion ou un perçage, choisies dans l'Historique ou sur une face qu'elles ont créée ; l'étape est répétée.\nUne esquisse n'est ni l'un ni l'autre : répétez ses courbes avec la Répétition ou la Symétrie de l'esquisse, ou extrudez-la d'abord.", "ui.pattern_on_path": "Répétition sur trajectoire", "ui.perforate_margin_default": "depuis le diamètre", "ui.perforate_pitch": "Pas", @@ -4358,12 +4920,17 @@ "ui.plugins_skipped": "{count} dossier(s) illisible(s).", "ui.plugins_version": "{version}", "ui.point": "Point", + "ui.point_cloud_add_filter": "Ajouter un filtre…", "ui.point_cloud_auto_range": "Plage automatique", "ui.point_cloud_color_by": "Colorer par", "ui.point_cloud_file_colors": "Couleurs du fichier", + "ui.point_cloud_filter_by": "Filtrer par", "ui.point_cloud_height_high": "Plus haut", "ui.point_cloud_height_low": "Plus bas", + "ui.point_cloud_legend_filter": "Affichées et masquées dans la légende ci-dessus", "ui.point_cloud_no_file_colors": "Le fichier n'a pas de couleurs", + "ui.point_cloud_pause": "Pause", + "ui.point_cloud_play": "Lire", "ui.point_cloud_single_color": "Couleur unique", "ui.point_cloud_size": "Taille des points", "ui.point_cloud_units": "Unités du fichier", @@ -4372,6 +4939,11 @@ "ui.polygon": "Polygone", "ui.preferences": "Préférences", "ui.press_a_key": "appuyez sur une touche…", + "ui.print_face_body_not_sent": "Le corps de cette face n’est pas envoyé : ajoutez-le d’abord à Corps", + "ui.print_face_cleared": "{body} : face d’impression effacée", + "ui.print_face_input": "Face d’impression", + "ui.print_face_pick": "Sélectionnez une face plane d’un corps solide pour en faire la face d’impression", + "ui.print_face_set": "{body} : face d’impression définie ; Envoyer au slicer pose le corps sur cette face", "ui.profile": "Profil", "ui.profile_plane": "Plan du profil", "ui.profiles": "Profils", @@ -4387,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Mesure en cours…", + "ui.properties.measuring_bodies": "Mesure en cours… {done} corps sur {total}", "ui.properties.measuring_failed": "La mesure s'est arrêtée avant la fin.", "ui.properties.principal_axis": "Axe principal {number}", "ui.properties.principal_moments": "Moments principaux", @@ -4435,6 +5008,7 @@ "ui.revolve": "Révolution", "ui.ribbon_exit": "Quitter", "ui.ribbon_labels": "Afficher le texte sous les icônes du ruban", + "ui.ribbon_menus_skip_pinned": "Laisser les commandes épinglées hors des menus déroulants", "ui.ribbon_pin_footer": "Les commandes épinglées s’affichent dans le ruban. Survolez une ligne pour l’épingler ou la détacher.", "ui.ribbon_workspace": "Espace de travail", "ui.right": "Droite", @@ -4453,6 +5027,7 @@ "ui.selectOther": "Sélectionner un autre…", "ui.selectTangentChain": "Sélectionner la chaîne tangente", "ui.select_all": "Tout sélectionner", + "ui.select_components_by_face": "Sélectionner des composants (une face sélectionne son composant)", "ui.selection": "Sélection", "ui.selection_modifiers": "Modificateurs de sélection", "ui.selection_shift_add_only": "Maj+clic ajoute sans retirer", @@ -4478,6 +5053,7 @@ "ui.showDimension": "Afficher la cote", "ui.showOrigin": "Afficher l'origine", "ui.showPlanes": "Afficher les plans", + "ui.show_component_history": "Afficher son historique", "ui.show_constraints": "Contraintes", "ui.show_construction_geometries": "Géométries de construction", "ui.show_dimensions": "Cotes", @@ -4494,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Filtre de sélection", "ui.sketch_modifiers": "Modificateurs d’esquisse", "ui.sketch_project_geometry": "Géométrie", + "ui.sketch_report.all_constrained": "Tout est entièrement contraint.", + "ui.sketch_report.dof": "Degrés de liberté", + "ui.sketch_report.loose": "Pas entièrement contrainte", + "ui.sketch_report.status": "État", + "ui.sketch_report.title": "Rapport d'esquisse", "ui.sketch_scale": "Échelle d'esquisse", "ui.sketches": "Esquisses", "ui.slice": "Trancher", @@ -4589,19 +5170,31 @@ "ui.view_angles": "Angles de vue", "ui.view_angles_convention": "Degrés autour de l'axe vertical. Lacet 0° = vue de face, 90° = vue de gauche, −90° = vue de droite, 180° = vue arrière ; tangage 90° = vue de dessus ; un roulis positif fait tourner le modèle dans le sens horaire.", "ui.view_angles_help": "Affiche le tangage, le lacet et le roulis de la vue en degrés, ainsi que sa projection, sous le gizmo d'orientation. Cliquez sur l'indicateur pour saisir des angles exacts.", + "ui.view_angles_lock": "Verrouiller {axis}", "ui.view_angles_ortho": "Ortho", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Tangage", "ui.view_angles_readout": "Tangage {pitch} · Lacet {yaw} · Roulis {roll}", "ui.view_angles_roll": "Roulis", + "ui.view_angles_unlock": "Déverrouiller {axis}", "ui.view_angles_yaw": "Lacet", + "ui.view_angles_zero": "Mettre {axis} à 0°", "ui.view_centre": "Centre de la vue", "ui.viewport_status_clear": "Désactiver {name}", "ui.viewport_status_clear_hint": "Désactiver {name} · Échap", + "ui.viewport_status_edges": "{count} arêtes", + "ui.viewport_status_from": "depuis {direction}", "ui.viewport_status_key": "Afficher la légende de {name}", "ui.viewport_status_minimum_radius": "Rayon minimum", "ui.viewport_status_pairs": "{count} paires", + "ui.viewport_status_section_hatch": "{setting} · hachures", + "ui.viewport_status_section_plane": "Plan actuel", + "ui.viewport_status_section_tilted": "inclinée · {offset}", "ui.viewport_status_stripes": "{count} bandes", + "ui.viewport_status_summary_clear": "Tout désactiver", + "ui.viewport_status_summary_heading": "Dans cette vue", + "ui.viewport_status_summary_label": "{name} et {count} autres éléments", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Suivre le thème", "ui.visual_shaded_hidden_edges": "Ombré avec arêtes cachées", "ui.visual_shaded_with_edges": "Ombré avec arêtes", @@ -4638,10 +5231,12 @@ "update.button": "Mettre à jour", "update.button_version": "Mettre à jour vers {version}", "update.check_automatically": "Rechercher automatiquement les mises à jour", + "update.check_for_updates": "Rechercher des mises à jour", "update.check_now": "Vérifier maintenant", + "update.check_unavailable": "La recherche de mises à jour n’est pas disponible pour cette installation.", "update.checking": "Vérification…", "update.copy": "Copier", - "update.dmg_opened": "L'image disque est ouverte et vérifiée : faites glisser SolidCraft dans Applications en remplaçant l'ancienne copie, puis redémarrez SolidCraft.", + "update.dmg_opened": "L'image disque est ouverte et vérifiée : quittez SolidCraft, faites glisser le nouveau SolidCraft dans Applications en remplaçant l'ancienne copie, puis rouvrez SolidCraft.", "update.download": "Télécharger", "update.download_open": "Télécharger et ouvrir", "update.downloading": "Téléchargement et vérification… {done} sur {total} Mo", @@ -4652,11 +5247,13 @@ "update.installed": "SolidCraft {version} est installé. Redémarrez pour l'utiliser.", "update.installer_started": "L'installateur démarre à la fermeture de SolidCraft.", "update.later": "Me le rappeler plus tard", + "update.managed": "Mise à jour disponible : mettez à jour SolidCraft dans {manager}", "update.no_notes": "Cette version n'a pas de notes.", "update.package_hint": "Cette copie provient d'un {kind}. Téléchargez le nouveau paquet, puis installez-le avec :", "update.prefs_dev": "Ceci est une version de développement ({version}) : elle ne vérifie pas les mises à jour.", "update.prefs_flatpak": "Flatpak met à jour cette copie ({version}) : exécutez {command} ou utilisez votre logithèque. SolidCraft ne vérifie pas.", "update.prefs_label": "Mises à jour", + "update.prefs_managed": "Ceci est SolidCraft {version}, géré par {manager}. Une vérification interroge GitHub sur la dernière version et n'envoie rien d'autre ; mettez à jour SolidCraft dans {manager}.", "update.prefs_note": "Ceci est SolidCraft {version} ({kind}). Une vérification interroge GitHub sur la dernière version et n'envoie rien d'autre.", "update.prefs_web": "Rechargez la page pour obtenir la dernière version de l'application web. Si le réseau est indisponible ou si la mise à jour ne peut pas finir de se télécharger à temps, la version enregistrée s'ouvre à la place ; un téléchargement en cours se poursuit pour le prochain rechargement.", "update.refresh_checking": "Recherche de la dernière version…", @@ -4683,6 +5280,7 @@ "web.open_link": "Ouvrir la conception liée ?", "web.open_link_confirm": "Il y a des modifications non enregistrées. Ouvrir la conception liée dans un nouvel onglet ?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choisir · Entrée / Tab compléter · Échap fermer", + "↑ ↓ choose · Enter applies this value": "↑ ↓ choisir · Entrée applique cette valeur", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ choisir · Entrée applique la saisie · Échap fermer", "⌘Enter continues on GitHub.": "⌘Entrée continue sur GitHub." } diff --git a/assets/locales/gl.json b/assets/locales/gl.json index f23b370fc..c7726c46a 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "SUPERFICIE DE UNIÓN", "BOUNDARY SURFACE": "SUPERFICIE DE CONTORNO", "BROWSER": "NAVEGADOR", + "Back to the original order": "Volver á orde orixinal", "Ball": "Esférica", "Bar": "Barra", "Base Center": "Centro da base", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Os deseños que abras ou gardes aparecen aquí.", "Determined by To Object. Choose Angle to edit the angular extent.": "Determinado por Ata o obxecto. Escolle Ángulo para editar a extensión angular.", "Diameter": "Diámetro", + "Did this assembly open the wrong way up?": "Abriuse esta ensamblaxe mal orientada?", + "Did this part open the wrong way up?": "Abriuse esta peza mal orientada?", "Dimension new shapes": "Cotar as formas novas", "Direction": "Dirección", "Discard": "Descartar", @@ -474,6 +477,7 @@ "Rectangular": "Rectangular", "Rectangular Tube": "Tubo rectangular", "Reference face": "Cara de referencia", + "Reference plane": "Plano de referencia", "Relief Depth": "Profundidade do desafogo", "Relief Width": "Largura do desafogo", "Remove Tools": "Quitar as ferramentas", @@ -553,6 +557,7 @@ "Section": "Sección", "Section (optional)": "Sección (opcional)", "Section position": "Posición da sección", + "Sections": "Seccións", "Sections (one sketch each)": "Seccións (un bosquexo cada unha)", "Select Other": "Seleccionar outro", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Seleccionar outro: mantén o botón esquerdo quieto sobre o modelo (ou clic dereito › Seleccionar outro…) para listar todo o que hai baixo o cursor; fai clic de novo no mesmo punto para seleccionar o seguinte. Fai dobre clic co botón central para ir ao Inicio (Preferencias › Navegación).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Axustar aos centros de caras e arestas", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft non pode enviar informes directamente. Envía o informe en GitHub; non se necesita ningún token na aplicación.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft pechouse antes de gardar estes deseños. Pódese abrir a súa última gravación automática.", + "Sort A to Z": "Ordenar de A a Z", + "Sort Z to A": "Ordenar de Z a A", "Spacing 2 must be a non-zero number": "O espazado 2 debe ser un número distinto de cero", "Spacing must be a non-zero number": "O espazado debe ser un número distinto de cero", "Specialise": "Especializar", @@ -601,6 +608,7 @@ "Square": "Cadrado", "Stand it up": "Poñela de pé", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Poñela de pé: un cuarto de volta arredor de X, como unha operación Mover que podes desfacer.", + "Stand this assembly up?": "Poñer esta ensamblaxe de pé?", "Stand this part up?": "Poñer esta peza de pé?", "Start angle": "Ángulo inicial", "Start bulge": "Abaulamento inicial", @@ -772,6 +780,8 @@ "at the face": "na cara", "bom.group_children": "Subpezas na fila da súa peza", "browser.body_name": "Corpo{number}", + "browser.calibrate_click_a": "Fai clic na imaxe para o punto A, ou escribe as súas coordenadas.", + "browser.calibrate_click_b": "Fai clic na imaxe para o punto B, ou escribe as súas coordenadas.", "browser.calibrate_title": "Calibrar: {name}", "browser.capture_many": "Movéronse {count} compoñentes, pero as súas posicións non se capturaron.", "browser.capture_note": "Capturar a posición conserva a nova posición; Reverter a posición restaura a anterior.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (ancoraxe perdida)", "browser.sketch_editing": "{name} (en edición)", "browser.sketch_name": "Bosquexo{number}", + "browser.sketches_to_parts_already_in_part": "xa na súa peza", + "browser.sketches_to_parts_design_body": "nun corpo do propio deseño", + "browser.sketches_to_parts_moved": "Movéronse {moved} bosquexos á peza na que están", + "browser.sketches_to_parts_no_exact_attachment": "nunha cara sen unha ancoraxe exacta", + "browser.sketches_to_parts_not_on_face": "non na cara dunha peza", + "browser.sketches_to_parts_part_missing": "a súa peza desapareceu", + "browser.sketches_to_parts_result": "Movéronse {moved} bosquexos á peza na que están; {stayed} non se moveron: {why}", "browser.units": "Unidades: {units}", "cam.flat": "Cara plana", "cam.follower": "Seguidor", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Tomar aparencia", "cmd.appearance_replace": "Substituír aparencia", "cmd.assembly_bom": "Lista de materiais", + "cmd.assembly_mass_properties": "Propiedades de masa", + "cmd.body.print_face": "Cara de impresión", "cmd.body_rename": "Renomear o corpo", "cmd.browser_collapse_all": "Contraer todo", "cmd.browser_expand_all": "Expandir todo", @@ -842,6 +861,7 @@ "cmd.component_extract": "Extraer a un ficheiro", "cmd.component_finish_edit": "Rematar a edición", "cmd.component_from_bodies": "Crear compoñentes a partir de corpos", + "cmd.component_hide_history": "Ocultar o historial do compoñente", "cmd.component_insert_design": "Inserir deseño", "cmd.component_links": "Listar as ligazóns", "cmd.component_list": "Listar os compoñentes", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Mover corpos ao compoñente", "cmd.component_move_features": "Mover operacións ao compoñente", "cmd.component_move_sketches": "Mover bosquexos ao compoñente", + "cmd.component_move_sketches_to_parts": "Mover os bosquexos ás súas pezas", "cmd.component_paste_from_design": "Pegar desde outro deseño", "cmd.component_paste_new": "Pegar como novo", "cmd.component_properties": "Propiedades físicas do compoñente", @@ -857,6 +878,7 @@ "cmd.component_rename": "Renomear o compoñente", "cmd.component_replace_with_link": "Substituír por unha ligazón", "cmd.component_revert_position": "Reverter a posición", + "cmd.component_show_history": "Mostrar o historial do compoñente", "cmd.component_unlock": "Desbloquear o contido", "cmd.component_update_links": "Actualizar as ligazóns", "cmd.config_activate": "Activar a configuración", @@ -867,6 +889,7 @@ "cmd.config_rule": "Regra de configuración", "cmd.config_rules": "Regras de configuración", "cmd.config_table": "Mostrar a táboa de configuracións", + "cmd.construct.plane.axis_point": "Plano por un eixe e un punto", "cmd.construct_axis_edge": "Eixe pola aresta", "cmd.construct_axis_normal_to_face": "Eixe perpendicular á cara", "cmd.construct_axis_through_cylinder": "Eixe por cilindro/cono/toro", @@ -915,6 +938,11 @@ "cmd.explode_show": "Mostrar a vista explosionada", "cmd.expr_evaluate": "Avaliar a expresión", "cmd.face_delete": "Eliminar a cara", + "cmd.file.export_3mf": "Exportar 3MF", + "cmd.file.export_obj": "Exportar OBJ", + "cmd.file.export_step": "Exportar STEP", + "cmd.file.export_stl": "Exportar STL", + "cmd.file.export_urdf": "Exportar URDF", "cmd.file_export": "Exportar", "cmd.file_insert_mesh": "Inserir malla", "cmd.file_insert_step": "Inserir STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Activar as cores dos compoñentes", "cmd.inspect_colored_components_disable": "Desactivar as cores dos compoñentes", "cmd.inspect_compare": "Comparar corpos", + "cmd.inspect_compare_picture": "Comparar a imaxe", "cmd.inspect_continuity": "Análise de continuidade", "cmd.inspect_curvature_comb": "Análise con pente de curvatura", "cmd.inspect_curvature_map": "Análise con mapa de curvatura", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Editar a nube de puntos", "cmd.pointcloud_insert": "Inserir nube de puntos", "cmd.pointcloud_list": "Nubes de puntos", + "cmd.render.compare.divider": "Mover o divisor da comparación de renders", + "cmd.render.result.discard": "Descartar o resultado do render", + "cmd.render.result.select": "Seleccionar o resultado do render", "cmd.render_aging_describe": "Envellecemento da superficie por capas", "cmd.render_backends": "Motores de render", "cmd.render_batch": "Renderizar todas as tomas", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline por puntos de control (grao 5)", "cmd.sketch_spline_fit_point": "Spline por puntos de paso", "cmd.sketch_spline_insert_point": "Engadir punto ao spline", + "cmd.sketch_spline_remove_point": "Eliminar punto do spline", "cmd.sketch_spline_reverse": "Inverter a dirección do spline", "cmd.sketch_spun_profile": "Perfil de revolución", "cmd.sketch_toggle_diameter": "Alternar raio / diámetro", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Mover o marcador da liña de tempo", "cmd.timeline_stop": "Deter a reprodución do historial", "cmd.timeline_suppress": "Suprimir a operación", + "cmd.ui.assistant": "Mostrar/Ocultar o asistente", "cmd.view.render_browser": "Navegador de render", "cmd.view.render_dock": "Mover o panel de render", "cmd.view.render_focus": "Vista de foco do render", + "cmd.view.status_details": "Detalles de estado da ventá gráfica", "cmd.view.status_items": "Elementos de estado da ventá gráfica", "cmd.view_ambient_occlusion": "Oclusión ambiental", "cmd.view_angle_readout": "Ángulos da vista", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Ferramenta de navegación", "cmd.view_top": "Vista superior", "cmd.view_visual_style": "Estilo visual", + "color.blue": "Azul", "color.copy": "Preme para copiar os valores da cor", "color.edit": "Preme para editar a cor", "color.gamma": "Mostrando os valores da cor no espazo gamma 0-255", + "color.green": "Verde", "color.hex": "Hex", "color.hex_help": "Escribe #rrggbb ou #rrggbbaa; con seis díxitos consérvase a opacidade", "color.hex_hint": "#rrggbb", "color.hue": "Ton", "color.linear": "Mostrando os valores da cor no espazo lineal 0-1", + "color.recent": "Cores recentes", + "color.recent_help": "As cores que escolles en calquera campo de cor aparecen aquí", + "color.red": "Vermello", + "color.saturation": "Saturación (porcentaxe)", "color.saturation_value": "Saturación e valor", "color.selected": "Cor seleccionada", + "color.step_down": "Diminuír un paso", + "color.step_up": "Aumentar un paso", + "color.value": "Valor, a luminosidade (porcentaxe)", "config.column_filter_empty": "Non hai columnas que coincidan", + "config.rule_parameter_columns": "Só se listan os parámetros que teñen unha columna na táboa. Engade unha con Engadir columna (+) para usala aquí.", + "config.rule_suppression_columns": "Só se listan as operacións que teñen unha columna Suprimir na táboa. Engade unha con Engadir columna (+) para controlalas desde aquí.", "contact.components_count": "{count} compoñentes", "contact.enabled_label": "activado", "coupling.gear_1": "Engrenaxe 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Faga dobre clic noutra cota de control para inserir o seu nome", "dialog.dimension_name": "Cota: {name}", "dialog.edit_title": "EDITAR {title}", + "dialog.no_shown_body": "Non hai ningún corpo visible para modificar: mostra un ou escolle Corpo novo", + "dialog.pattern_sketch_not_object": "Escolle corpos ou operacións: un bosquexo non é ningunha das dúas cousas. Repite as súas curvas co Patrón ou a Simetría do propio bosquexo, ou extrúeo primeiro.", "dialog.select": "↖ Seleccionar", "dialog.selected_count": "↖ {count} seleccionados", + "dialog.selection_constraint": "Restrición {id}", + "dialog.selection_external_curve": "{sketch} · curva {id}", "dialog.selection_guidance": "Selecciona unha entrada para cambiala. Fai clic nos obxectos seleccionados para quitalos; Ctrl/Cmd-clic tamén os alterna. Revisa a previsualización e preme Aceptar.", + "dialog.selection_midpoint": "Punto medio · {id}", + "dialog.selection_profile": "{sketch} · perfil {number}", "dialog.selection_step": "{step} de {total}: selecciona {input}", "dialog.step": "Paso", "document.changed_on_disk": "{name} cambiou no disco", @@ -1380,26 +1432,244 @@ "from the rule": "da regra", "help.apache": "Licenza Apache 2.0", "help.appearance.assign": "Dá aos corpos, caras ou compoñentes seleccionados unha cor ou un aspecto de material, sen cambiar o seu peso. Úsao para distinguir pezas ou para previsualizar un acabado.", + "help.assembly.bom": "Lista as pezas do deseño ou dun compoñente coas súas cantidades, por número de peza, e pode gardar a lista como CSV ou JSON. Úsaa como lista de pezas para encargar e montar.", "help.attributions": "Atribucións (ATTRIBUTION.md)", "help.build": "Versión {version} · commit {commit} · compilada o {date}", + "help.canvas.decal": "Coloca unha imaxe nunha cara plana do modelo, como unha pegatina. Úsaa para mostrar unha etiqueta, un logotipo ou un debuxo impreso nunha peza.", + "help.canvas.edit": "Cambia un lenzo: a súa posición, tamaño, ángulo, opacidade, simetría, visibilidade ou nome. Úsao para aliñar unha imaxe de referencia co bosquexo que calcas sobre ela.", + "help.canvas.insert": "Coloca unha imaxe PNG ou JPEG nun plano ou nunha cara como referencia transparente. Úsao para calcar unha foto ou un debuxo nun bosquexo, coa imaxe a un tamaño coñecido.", + "help.component.break_link": "Separa un compoñente ligado do seu ficheiro de deseño e conserva os seus corpos tal como están. Úsao cando a peza xa non deba seguir os cambios do ficheiro orixinal.", + "help.component.capture_position": "Conserva as posicións das pezas que moveches a man, para que esas sexan as súas posicións. Úsao despois de arrastrar ata o seu sitio pezas que ningunha unión sostén.", + "help.component.create": "Engade un compoñente novo e baleiro ao deseño, dentro do compoñente activo salvo que escollas outro compoñente superior. Úsao para dar a unha peza nova da ensamblaxe o seu propio lugar para corpos e bosquexos.", "help.component.finish_edit": "Garda a peza que estás editando in situ, volve á súa ensamblaxe e actualiza a ensamblaxe a partir dela. Úsao cando remates os cambios na peza ligada.", + "help.component.from_bodies": "Converte cada corpo seleccionado nun compoñente propio, co nome do corpo. Úsao cando un deseño feito con corpos soltos deba pasar a ser unha ensamblaxe cuxas pezas se poidan unir e mover.", + "help.component.insert_design": "Insire outro deseño gardado como un compoñente ligado ao seu ficheiro, cos seus corpos sólidos colocados tal como están alí. Úsao para reutilizar unha peza nunha ensamblaxe e recibir os cambios posteriores con Actualizar as ligazóns.", + "help.component.properties": "Mostra o volume, a masa, o centro de masas e os momentos de inercia dun compoñente, segundo os materiais dos seus corpos. Úsao para comprobar o peso e o equilibrio dunha ensamblaxe.", + "help.component.revert_position": "Devolve ao seu sitio as pezas que moveches a man e descarta os movementos que non se capturaron. Úsao para desfacer movementos de proba nunha ensamblaxe.", + "help.component.update_links": "Le de novo os ficheiros de deseño ligados e substitúe os corpos que cambiaron. Úsao despois de editar unha peza que usa esta ensamblaxe.", + "help.config.configure": "Engade parámetros, operacións, materiais ou aparencias como columnas da táboa de configuracións. Úsao para crear variantes dun deseño, como tamaños dunha peza.", + "help.config.preview": "Comproba que unha fila da táboa de configuracións se reconstrúe, sen cambiar o deseño nin o seu historial. Úsao antes de cambiar a unha variante da que non estás seguro.", + "help.config.rules": "Mostra as regras da táboa de configuracións, as súas filas e cal é a fila activa. Úsao para ver como están definidas as variantes dun deseño.", + "help.config.table": "Mostra a táboa de configuracións: unha fila por variante, unha columna por parámetro ou operación, e se o deseño aínda coincide coa fila activa. Úsao para revisar as variantes dun deseño.", "help.connect_note": "Reinicia cada asistente para cargar o servidor de SolidCraft. De cada ficheiro fíxose unha copia de seguranza como .bak antes de cambialo.", "help.connect_title": "Conectar asistentes de IA", + "help.construct.axis.edge": "Crea un eixe de construción ao longo dunha aresta recta ou dunha liña do bosquexo. Úsao como eixe para unha revolución, un patrón circular ou unha unión.", + "help.construct.axis.normal_to_face": "Crea un eixe de construción por un punto, perpendicular a unha cara. Úsao como un eixe que sae directamente dunha superficie.", + "help.construct.axis.through_cylinder": "Crea un eixe de construción polo centro dunha cara de cilindro, cono ou toro, ou dunha aresta circular. Úsao para xirar operacións ou repetilas arredor dunha peza redonda.", + "help.construct.axis.two_planes": "Crea un eixe de construción onde se atopan dous planos ou caras planas. Úsao cando o eixe que precisas é a liña entre dúas caras.", + "help.construct.axis.two_points": "Crea un eixe de construción por dous puntos, vértices ou puntos do bosquexo. Úsao para un eixe que vai entre dúas posicións coñecidas.", + "help.construct.plane.along_path": "Crea un plano de construción perpendicular a unha aresta ou curva, nunha posición ao longo dela. Úsao para debuxar o perfil dun varrido ou unha sección dunha traxectoria.", + "help.construct.plane.at_angle": "Crea un plano de construción xirado un ángulo a partir dun plano ou dunha cara, arredor dun eixe ou dunha aresta. Úsao para bosquexos inclinados, como unha escuadra en ángulo.", + "help.construct.plane.axis_point": "Crea un plano de construción que contén un eixe e un punto fóra dese eixe. Escolle unha orixe ou un eixe de construción, unha aresta recta ou unha liña do bosquexo e despois un vértice, un punto do bosquexo ou un punto de construción. Un punto sobre o eixe non pode definir un plano único.", + "help.construct.plane.midplane": "Crea un plano de construción a medio camiño entre dous planos ou caras planas, ou que os bisecta onde se atopan formando un ángulo. Úsao como plano de simetría.", + "help.construct.plane.offset": "Crea un plano de construción paralelo a un plano ou a unha cara plana, a unha distancia ou por un punto. Úsao para debuxar a unha altura fixa sobre unha cara.", + "help.construct.plane.perpendicular": "Crea un plano de construción que contén unha liña ou aresta e é perpendicular a un plano ou a unha cara. Úsao para debuxar en vertical sobre un modelo ao longo dunha aresta.", + "help.construct.plane.tangent": "Crea un plano de construción que toca un cilindro, cono, esfera ou toro nun punto. Úsao para debuxar no lado dunha peza redonda.", + "help.construct.plane.three_points": "Crea un plano de construción por tres puntos. Úsao para un plano definido por posicións do modelo, como tres esquinas.", + "help.construct.plane.two_edges": "Crea un plano de construción por dúas arestas ou liñas rectas que están nun mesmo plano. Úsao para un plano que atravesa unha peza, como por dúas arestas opostas.", + "help.construct.point.along_path": "Crea un punto de construción nunha posición ao longo dunha aresta ou curva. Úsao como referencia a medio camiño dunha traxectoria.", + "help.construct.point.center": "Crea un punto de construción no centro dunha aresta circular, dun círculo ou arco do bosquexo, dunha esfera ou dun toro. Úsao como referencia para furados, eixes e unións.", + "help.construct.point.edge_plane": "Crea un punto de construción onde unha aresta ou liña atravesa un plano ou unha cara plana. Úsao para marcar onde unha traxectoria cruza un plano.", + "help.construct.point.three_planes": "Crea un punto de construción onde se atopan tres planos ou caras planas. Úsao como referencia de esquina, mesmo onde o modelo non ten vértice.", + "help.construct.point.two_edges": "Crea un punto de construción onde se atopan dúas arestas ou liñas, ou onde están máis preto. Úsao como referencia nunha esquina virtual.", + "help.construct.point.vertex": "Crea un punto de construción nun vértice ou punto do bosquexo. Úsao como referencia que se mantén cando se oculta o bosquexo ou o corpo ao seu redor.", + "help.contact.check": "Lista os pares de pezas dos conxuntos de contacto que se atravesan na súa posición actual. Úsao para atopar colisións antes de accionar as unións ou executar un estudo de movemento.", + "help.contact.create": "Agrupa dúas ou máis pezas nun conxunto de contacto, cuxos corpos non se poden atravesar mentres as unións se moven. Úsao para pezas que deben parar ao tocarse, como unha panca contra o seu tope.", + "help.contact.disable_all": "Desactiva o contacto, de modo que as unións accionadas e os estudos de movemento xa non paran onde as pezas se tocan. Úsao para volver mover as pezas con liberdade, ou para manter áxil unha ensamblaxe grande.", + "help.contact.edit": "Cambia un conxunto de contacto: as pezas que contén, o seu nome ou se está suprimido; tamén pode eliminar o conxunto. Úsao para axustar que pezas non se poden atravesar.", + "help.contact.enable_all": "Mete todas as pezas da ensamblaxe nun só conxunto de contacto, de modo que ningunhas dúas pezas se poden atravesar mentres as unións se moven. Úsao para unha comprobación rápida de todo un mecanismo.", + "help.contact.enable_sets": "Activa o contacto para os conxuntos de contacto que definiches, de modo que as unións accionadas e os estudos de movemento paran onde as súas pezas se atravesarían. Úsao para recuperar os teus conxuntos despois de desactivar o contacto.", + "help.contact.list": "Lista os conxuntos de contacto do deseño, as pezas de cada un e se o contacto está activado. Úsao para comprobar como está configurado o contacto antes de accionar a ensamblaxe.", + "help.document.inspect": "Mostra unha visión xeral do deseño: os seus compoñentes, corpos, bosquexos, operacións e parámetros. Úsao para orientarte nun deseño que non fixeches ti.", + "help.document.units": "Cambia as unidades nas que o deseño mostra as lonxitudes, como mm ou polgadas. A xeometría mantén o seu tamaño; só seguen o cambio a visualización e os números simples.", + "help.edit.checkpoint": "Recorda o deseño, o bosquexo activo e o historial de desfacer tal como están agora. Úsao antes de probar algo arriscado do que quizais queiras volver atrás.", + "help.edit.restore_checkpoint": "Volve a un punto de control, historial de desfacer incluído. Úsao para descartar de golpe todo o feito desde o punto de control.", + "help.explode.create": "Crea unha vista explosionada que separa as pezas do centro da ensamblaxe, ou segundo os movementos que fixes. Úsao para mostrar como se monta unha ensamblaxe, en instrucións ou presentacións.", "help.face.delete": "Elimina as caras seleccionadas e deixa que as caras veciñas pechen o oco, ou deixa o oco aberto como unha superficie. Úsao para quitar unha aresta arredondada, un furado ou un saínte que estorba.", + "help.file.insert_mesh": "Engade un ficheiro 3MF, STL, OBJ, PLY ou glTF ao deseño como corpos de malla nun compoñente novo. Úsao para colocar un modelo descargado ou dixitalizado xunto ao teu deseño como referencia.", + "help.file.insert_step": "Engade un ficheiro STEP, IGES, FreeCAD ou Rhino ao deseño como corpos sólidos nun compoñente novo; as pezas dunha ensamblaxe pasan a ser compoñentes aniñados. Úsao para traer modelos de provedores ou doutros programas CAD.", + "help.file.save_mesh": "Garda corpos como malla STL, 3MF ou OBJ, coa suavidade das caras curvas que escollas. Úsao para preparar pezas para a impresión 3D ou para programas que len mallas.", + "help.file.send_to_slicer": "Garda os corpos seleccionados como ficheiro 3MF e ábreo no laminador que escollas. Úsao para ir do modelo á impresión nun só paso.", "help.font_details": "A interface usa as fontes integradas de egui (Ubuntu Light e Hack, baixo as licenzas Ubuntu Font Licence e MIT/Bitstream Vera; Noto Emoji e a fonte de iconas emoji, baixo OFL e MIT). O texto dos bosquexos usa Liberation Sans (SIL OFL 1.1). O paquete opcional de fontes de The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), non se inclúe nas compilacións de SolidCraft.", "help.fonts": "Fontes", + "help.frame.member": "Coloca un perfil, como un tubo ou un perfil de aluminio extruído, ao longo das liñas dun bosquexo de estrutura, un membro por liña. Úsao para construír estruturas, bastidores e conxuntos soldados.", + "help.inspect.accessibility": "Colorea as caras ás que unha ferramenta pode chegar desde unha dirección, e aquelas ás que non. Úsao para comprobar unha peza para mecanizado ou moldeo desde ese lado.", + "help.inspect.center_of_mass": "Mostra o centro de masas dos corpos, cada un por separado e todos xuntos, con densidade uniforme. Úsao para comprobar o equilibrio e onde vai envorcar unha peza.", + "help.inspect.colored_components": "Dá a cada compoñente a súa propia cor temporal, sen cambiar as aparencias. Úsao para distinguir dunha ollada as pezas dunha ensamblaxe.", + "help.inspect.compare": "Compara dous corpos e mostra onde un ten material que o outro non, con volume e desviación. Úsao para comprobar unha peza modificada ou importada contra a orixinal.", + "help.inspect.continuity": "Comproba con que suavidade se unen as caras ao longo das súas arestas: separacións, quebras ou saltos de curvatura, e colorea as xuntas. Úsao para atopar onde as superficies non se unen limpamente.", + "help.inspect.curvature_comb": "Debuxa pentes ao longo de curvas, arestas ou caras, cuxos dentes mostran canto se curvan. Úsao para detectar zonas planas, quebras e curvatura irregular.", + "help.inspect.curvature_map": "Colorea as caras segundo canto se curvan, en vermello onde o raio é pequeno. Úsao para atopar zonas axustadas e xulgar a suavidade dunha superficie.", + "help.inspect.draft": "Colorea as caras segundo o seu ángulo de desmoldaxe respecto dunha dirección de extracción e marca as que teñen demasiado pouco. Úsao para comprobar unha peza antes do moldeo ou da fundición.", + "help.inspect.environment_map": "Mostra o modelo cun acabado reflectante, como de espello. Úsao para xulgar o fluxo das superficies polo xeito en que os reflexos as percorren.", + "help.inspect.interference": "Atopa corpos que se solapan e mostra cada solapamento co seu volume. Úsao para comprobar se hai pezas que chocan nunha ensamblaxe.", + "help.inspect.isocurve": "Debuxa as curvas isoparamétricas das caras, a grella sobre a que se constrúe a superficie. Úsao para ver como flúe unha superficie e onde se amorea.", + "help.inspect.measure": "Mide lonxitudes, distancias, ángulos, áreas e raios entre o que escollas, ou o volume e a masa dos corpos. Úsao para comprobar tamaños e folgas.", + "help.inspect.minimum_radius": "Atopa o raio de curvatura máis pequeno de curvas, arestas ou caras, e onde está. Úsao para comprobar que unha ferramenta ou unha boquilla pode seguir a forma.", + "help.inspect.section": "Corta a vista ao longo dun plano e raia as caras cortadas, sen cambiar o modelo. Úsao para mirar dentro de pezas e ensamblaxes.", + "help.inspect.zebra": "Mostra raias brancas e negras reflectidas nas caras do modelo. Úsao para xulgar a suavidade: as raias que se rompen ou fan unha quebra nunha aresta indican unha transición deficiente.", + "help.joint.as_built": "Une dúas pezas onde xa están, sen mover ningunha, e define como poden seguir movéndose. Úsao para pezas que xa colocaches na súa posición final.", + "help.joint.cam": "Liga unha leva que xira cun seguidor, de modo que o seguidor se desliza ou oscila segundo lle pasa por baixo o contorno da leva. Úsao para levas, excéntricas e accionamentos de válvulas.", + "help.joint.create": "Une dúas pezas nas orixes de unión que escollas e move a segunda peza ao seu sitio; o tipo de unión define como poden seguir movéndose. Úsao para construír unha ensamblaxe cuxas pezas se moven como o mecanismo real.", + "help.joint.drive": "Define o ángulo ou a distancia dunha unión e move as pezas con ela, dentro dos seus límites; as unións ligadas e os bucles pechados seguen o movemento. Úsao para comprobar que un mecanismo se move como se pretende.", + "help.joint.gear": "Liga dúas unións xiratorias cunha relación de engrenaxe, de modo que accionar unha fai xirar a outra. Úsao para engrenaxes rectas e coroas dentadas, coa relación calculada a partir dos raios primitivos ou do número de dentes.", + "help.joint.limits": "Define canto pode xirar ou deslizar unha unión, cun mínimo e un máximo, ou borra eses límites. Úsao para manter unha charnela, unha corredoira ou unha panca dentro do seu rango real de percorrido.", + "help.joint.motion_link": "Acopla dúas unións cunha relación e un desfase, de modo que accionar unha move a outra. Úsao para unha relación fixa entre unións que Engrenaxe, Cremalleira e piñón ou Parafuso non cobren.", + "help.joint.origin": "Coloca unha orixe de unión con nome nunha peza: no centro dunha cara ou dun extremo redondo, no medio dunha aresta, nunha esquina ou nun punto. Úsao para preparar onde se fixan as unións; a orixe escollida nunha cara segue a cara cando a peza cambia de tamaño.", + "help.joint.rack_pinion": "Liga un piñón que xira cunha cremalleira que se desliza, de modo que a cremalleira se move tanto como a lonxitude de circunferencia primitiva que percorre o piñón. Úsao para accionamentos de cremalleira, dirección e eixes lineais.", + "help.joint.reach": "Move un punto dunha peza cara a un obxectivo cambiando as unións da súa cadea, dentro dos seus límites. Úsao para poñer un mecanismo en postura segundo onde debe acabar a súa punta, como a dun brazo robótico.", + "help.joint.rigid_group": "Bloquea xuntas as pezas seleccionadas tal como están, para que se movan como unha soa. Úsao para pezas que van xuntas e non teñen movemento entre elas.", + "help.joint.screw": "Liga o xiro e o deslizamento mediante un paso, de modo que cada volta avance esa distancia. Úsao para fusos de avance, parafusos e fusos roscados.", + "help.library.apply": "Aplica un material ou unha aparencia dun ficheiro de biblioteca local a corpos, caras ou compoñentes. Úsao para reutilizar materiais que gardaches doutro deseño.", + "help.library.export": "Garda os materiais e as aparencias do deseño nun ficheiro de biblioteca. Úsao para compartilos ou reutilizalos noutros deseños.", + "help.library.inspect": "Comproba un ficheiro de biblioteca e lista os seus materiais e aparencias, sen cambiar o deseño. Úsao para ver o que contén unha biblioteca antes de aplicala.", "help.licences": "Licenzas", "help.material.assign": "Define de que material están feitos os corpos seleccionados, como aceiro, aluminio ou ABS. Úsao para que a masa e o peso coincidan coa peza real.", + "help.material.properties.validate": "Comproba que unha ficha de datos de material teña números coherentes e non lle falten valores. Úsao antes de fiarte dos datos para a masa ou a rixidez.", + "help.mesh.convert": "Reconstrúe un corpo de malla, como un STL, como un sólido editable con caras planas e cilíndricas. Úsao para modificar pezas mecánicas importadas como se fosen un corpo modelado.", "help.mit": "Licenza MIT", + "help.motion.study": "Define valores das unións en pasos ao longo dunha liña de tempo e reprodúceos como animación. Úsao para ver como se move un mecanismo nunha secuencia e comprobar as folgas durante o percorrido.", + "help.motion.trace": "Traza o camiño que segue un punto dunha peza mentres se reproduce un estudo de movemento ou se acciona unha unión, e consérvao como curva de bosquexo 3D cando o confirmas. Úsao para ver ata onde chega un mecanismo, ou para construír sobre a súa traxectoria.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fixa unha peza no seu sitio, ou volve liberala, para que as unións movan arredor dela as outras pezas. Úsao para o bastidor ou a base sobre a que se constrúe o resto da ensamblaxe.", "help.occurrence.move": "Move unha peza da ensamblaxe só segundo os graos de liberdade que permiten as súas unións. Selecciona unha cara da peza e despois arrastra unha frecha ou un arco dispoñible.", "help.parameters.change": "Abre a táboa de valores con nome e expresións que controlan as cotas do deseño. Úsao para cambiar un tamaño nun só lugar e que o sigan todas as operacións que o usan.", + "help.parameters.export": "Garda os parámetros do deseño como CSV ou JSON. Úsao para editalos nunha folla de cálculo ou levalos a outro deseño.", + "help.parameters.graph": "Mostra que parámetros e operacións usan cales outros, e os bucles ou erros que haxa entre eles. Úsao para ver a que afectará un cambio nun parámetro.", + "help.parameters.import": "Le parámetros dun CSV ou JSON no deseño, todos ou ningún. Úsao para traer valores dunha folla de cálculo ou doutro deseño.", + "help.parameters.move": "Move un parámetro de usuario antes ou despois doutro na lista. Úsao para manter xuntos os parámetros relacionados.", + "help.parts.fastener": "Engade un parafuso, perno, porca, arandela, pasador ou rodamento estándar no tamaño que escollas. Colocado nun furado, asenta nel cunha unión, así que non precisas modelar eses elementos de fixación ti mesmo.", + "help.parts.insert": "Insire unha peza estándar na familia, tamaño e lonxitude que escollas. Colocada no bordo ou na parede dun furado, asenta nel cunha unión ríxida.", + "help.parts.library": "Abre as pezas normalizadas: parafusos, pernos, porcas, arandelas, parafusos sen cabeza, pasadores de espiga e rodamentos en tamaños normalizados. Úsao para engadir unha peza normalizada en vez de modelala ti.", + "help.parts.resize": "Cambia o tamaño ou a lonxitude dunha peza normalizada inserida e reconstrúea; as súas unións mantérana asentada. Úsao cando un parafuso resulta longo de máis ou un furado precisa outro tamaño.", + "help.plastic.assign_rule": "Asigna unha regra de plástico a corpos, para que as súas operacións de plástico tomen o seu desmoldaxe e a súa folga como valores predeterminados. Úsao para configurar unha peza moldeada unha soa vez para todas as súas operacións.", + "help.plastic.boss": "Engade un saínte para parafuso nunha cara: un poste cun furado opcional, desmoldaxe, arredondamento da raíz e nervios de apoio. Úsao para puntos de parafuso en carcasas moldeadas ou impresas.", + "help.plastic.lip": "Engade un beizo ou unha ranura correspondente ao longo do bordo dun corpo baleirado. Úsao para que dúas metades dunha carcasa se aliñen entre si e pechen ben.", + "help.plastic.manage_rules": "Crea e edita regras de plástico: material, espesor de parede, raios, folga e desmoldaxe. Úsao para manter coherentes as operacións dunha peza moldeada.", + "help.plastic.rest": "Engade un apoio nunha cara: unha base redonda ou rectangular, maciza ou oca, con desmoldaxe. Úsao como soporte ou separador nunha carcasa moldeada.", + "help.plastic.snap_fit": "Engade un gancho de encaixe a presión nunha cara, coa súa lonxitude, espesor e retén. Úsao para suxeitar pezas sen parafusos.", "help.pointcloud.insert": "Insire unha dixitalización PLY, XYZ ou PTS como nube de puntos xunto ao modelo. Úsaa como referencia ao construír un modelo a partir de datos medidos.", + "help.sheet.convert": "Converte unha placa ou un corpo baleirado de espesor uniforme nun corpo de chapa, con dobras nas arestas que escollas. Úsao para poder despregar unha peza existente.", + "help.sheet.export_bend_table": "Garda a táboa de dobras dun corpo de chapa como CSV ou JSON: ángulos, raios e posicións das dobras no desenvolvemento. Úsao para a prensa plegadora ou o taller.", + "help.sheet.export_dxf": "Garda o desenvolvemento como DXF, con contornos, liñas de dobra e notas de dobra opcionais. Úsao para o corte por láser, plasma ou chorro de auga.", + "help.sheet.flange": "Engade unha pestana: unha placa base a partir dun bosquexo, unha parede ao longo dun contorno aberto do bosquexo ou unha parede dobrada nas arestas da chapa. Úsao para construír pezas de chapa.", + "help.sheet.flat_pattern": "Crea o desenvolvemento dun corpo de chapa, co seu tamaño, recortes e liñas de dobra. Úsao para comprobar a peza en bruto antes de cortala.", + "help.sheet.fold": "Dobra unha chapa ao longo dunha liña do bosquexo cun ángulo e un raio. Úsao para dobrar unha chapa plana despois de facerlle os cortes.", + "help.sheet.hem": "Dobra o bordo dunha chapa sobre si mesmo. Úsao para bordos seguros e ríxidos sen rebabas afiadas.", + "help.sheet.manage_rules": "Crea e edita regras de chapa: espesor, raio de dobra, factor K, desafogos e separacións. Úsao para axustalas ao material e ás ferramentas do teu taller.", + "help.sheet.path_flange": "Engade unha cadea de pestanas ao longo do bordo dunha chapa, seguindo unha cadea aberta de liñas do bosquexo. Úsao para perfís como unha forma de U ou de Z nun só paso.", + "help.sheet.perforate": "Engade un campo de furados por toda a chapa plana, nun patrón ao tresbolillo ou cadrado. Úsao para ventilacións, reixas e paneis máis lixeiros.", + "help.sheet.refold": "Volve dobrar un corpo de chapa despregado. Úsao despois de engadir operacións á chapa plana.", + "help.sheet.unfold": "Desprega todas as dobras dun corpo de chapa. Úsao para engadir furados ou cortes que teñen que cruzar unha dobra e despois volver dobrar.", + "help.sketch.arc.center_point": "Debuxa un arco circular arredor dun punto central, desde un punto inicial ata un punto final. Úsao cando se coñece o centro do arco, como un raio arredor dun furado ou dun pivote.", + "help.sketch.arc.tangent": "Debuxa un arco que comeza no extremo dunha liña ou dun arco e continúa tanxente a ela. Úsao para seguir unha cadea cunha curva suave en vez dunha esquina.", + "help.sketch.arc.three_point": "Debuxa un arco desde un punto inicial ata un punto final pasando por un terceiro punto. Úsao cando o arco ten que pasar por puntos dados en vez de arredor dun centro coñecido.", + "help.sketch.arc3d": "Debuxa un arco circular exacto no espazo por tres puntos, co Bosquexo 3D activado. Úsao para curvas en traxectorias e guías que saen do plano do bosquexo.", + "help.sketch.auto_constrain": "Engade as restricións que o bosquexo case ten xa, como horizontal, paralela ou coincidente, e despois acótao ata que quede totalmente definido. Úsao para fixar nun paso un bosquexo debuxado a man alzada.", + "help.sketch.auto_constrain_from_datum": "Funciona como Restrición automática, pero mide as posicións desde un punto de referencia que escollas en vez da orixe. Úsao cando a peza se dispón a partir dun só punto de referencia, como unha esquina ou un furado.", + "help.sketch.blend_curve": "Une os extremos de dúas curvas cunha spline suave tanxente a ambas, ou tamén continua en curvatura se o escolles. Úsao para salvar un oco entre curvas sen quebra.", + "help.sketch.break": "Divide unha curva en anacos onde a cruzan outras curvas, ou en puntos que coloques nela. Úsao cando unha parte dunha curva precisa a súa propia restrición ou debe eliminarse por separado.", + "help.sketch.cancel": "Sae do bosquexo e descarta todo o que cambiou desde que se creou ou se abriu para editalo. Desfacer recupera os cambios.", + "help.sketch.centerline": "Cambia as liñas entre liñas normais e liñas centrais, eixes que os perfís deixan fóra. Usa unha liña central como eixe para unha revolución, unha simetría ou unha restrición de simetría.", + "help.sketch.chamfer.distance_angle": "Biséla a esquina entre dúas liñas, definida por unha distancia ao longo da primeira liña e un ángulo. Úsao cando un debuxo dá o chafrán como lonxitude e ángulo, como 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Biséla a esquina entre dúas liñas á mesma distancia ao longo de ambas. Úsao para o chafrán habitual de 45° nun contorno.", + "help.sketch.chamfer.two_distance": "Biséla a esquina entre dúas liñas, definida por unha distancia distinta ao longo de cada liña. Úsao para chafráns que non son de 45°, dados como dúas lonxitudes.", + "help.sketch.circle.center": "Debuxa un círculo a partir do seu centro e do seu diámetro. Úsao para furados, saíntes e outros elementos redondos cuxo centro se coñece.", + "help.sketch.circle.three_point": "Debuxa un círculo por tres puntos. Úsao cando o círculo ten que pasar por puntos dados, por exemplo dunha xeometría existente.", + "help.sketch.circle.three_tangent": "Debuxa un círculo que toca tres liñas, círculos ou arcos. Úsao para encaixar un círculo no espazo entre tres curvas, como o círculo inscrito dun triángulo.", + "help.sketch.circle.two_point": "Debuxa un círculo a partir dos dous extremos do seu diámetro. Úsao cando se coñecen os puntos do bordo do círculo en vez do seu centro.", + "help.sketch.circle.two_tangent": "Debuxa un círculo dun tamaño dado que toca dúas liñas, círculos ou arcos. Úsao para un arredondamento de raio fixo entre dúas curvas.", + "help.sketch.conic": "Debuxa unha curva cónica entre dous puntos extremos, definida por un punto ápice e un valor rho. Úsao para transicións suaves cuxa convexidade queres axustar, desde plana ata case unha esquina viva.", + "help.sketch.constrainer": "Aplica a restrición que unha ou dúas curvas escollidas case teñen xa, como horizontal, paralela, tanxente ou igual. Úsao para ordenar un bosquexo debuxado a man, unha relación cada vez.", + "help.sketch.constraint.coincident": "Fai que un punto estea sobre outro punto, unha curva ou un eixe do bosquexo. Úsao para pechar ocos nun perfil ou para pór un punto sobre unha liña.", + "help.sketch.constraint.collinear": "Fai que dúas liñas estean sobre unha mesma recta. Úsao para aliñar arestas interrompidas, como os dous lados dunha entalla.", + "help.sketch.constraint.concentric": "Dá a dous círculos ou arcos o mesmo centro. Úsao para aneis, avellanados cilíndricos e eixes con ombreiras.", + "help.sketch.constraint.curvature": "Fai que dúas curvas que se atopan nun punto extremo continúen coa mesma curvatura (G2). Úsao onde unha unión tanxente non é abondo de suave, por exemplo en superficies visibles.", + "help.sketch.constraint.equal": "Fai que as liñas teñan a mesma lonxitude, ou os círculos e arcos o mesmo raio. Úsao para que unha cota controle varios elementos iguais.", + "help.sketch.constraint.fix": "Fixa puntos ou curvas onde están, ou volve liberalos. Úsao para xeometría que non debe moverse cando arrastras ou resolves o bosquexo.", + "help.sketch.constraint.horizontal_vertical": "Fai horizontal ou vertical, o que estea máis preto, unha liña ou a liña entre dous puntos. Úsao para aliñar un contorno cos eixes do bosquexo.", + "help.sketch.constraint.midpoint": "Pon un punto no medio dunha liña, ou fai que coincidan os puntos medios de dúas liñas. Úsao para centrar xeometría nunha aresta.", + "help.sketch.constraint.parallel": "Fai paralelas dúas liñas. Úsao para lados que deben seguir paralelos cando cambian outras cotas.", + "help.sketch.constraint.perpendicular": "Fai que dúas liñas se atopen en ángulo recto. Úsao para esquinas en escuadra entre liñas que non están sobre os eixes do bosquexo.", + "help.sketch.constraint.polygon": "Converte unha cadea pechada de liñas nun polígono regular: lados iguais, con todas as esquinas nun mesmo círculo. Úsao para facer regular un polígono debuxado a man e mantelo así.", + "help.sketch.constraint.symmetry": "Fai que dous puntos ou curvas sexan simétricos respecto dunha liña ou dun punto. Úsao para manter simétrico un perfil cando cambias un lado.", + "help.sketch.constraint.tangent": "Fai que dúas curvas se toquen tanxencialmente, como unha liña e un arco. Úsao para unións suaves sen quebra.", + "help.sketch.construction": "Cambia as curvas entre xeometría normal e xeometría de construción, que os perfís deixan fóra. Usa curvas de construción como axudas para a disposición, referencias e cotas.", + "help.sketch.construction_line": "Crea unha recta de construción infinita por dous puntos. Úsaa para organizar un bosquexo sen dividir os perfís.", + "help.sketch.construction_line.angle": "Crea unha recta de construción infinita cun ángulo respecto do eixe X do bosquexo. Escolle o punto e escribe o ángulo, ou escolle a súa dirección.", + "help.sketch.construction_line.bisector": "Escolle dúas rectas do bosquexo que se crucen e despois unha das dúas bisectrices. O resultado segue as súas rectas de orixe.", + "help.sketch.construction_line.horizontal": "Crea unha recta de construción horizontal infinita por un punto. A súa restrición horizontal mantense nas edicións posteriores.", + "help.sketch.construction_line.parallel": "Escolle unha recta do bosquexo e despois coloca unha recta de construción infinita paralela. Fai clic co botón dereito para escoller outra referencia.", + "help.sketch.construction_line.perpendicular": "Escolle unha recta do bosquexo e despois coloca unha recta de construción infinita perpendicular. Fai clic co botón dereito para escoller outra referencia.", + "help.sketch.construction_line.tangent_at": "Crea unha tanxente nun punto dun círculo ou dun arco circular, ou no extremo dunha spline ou dunha cónica abertas. Escolle a curva e despois o seu punto de tanxencia.", + "help.sketch.construction_line.tangent_external": "Escolle un círculo ou un arco circular e despois un punto exterior e unha solución de tanxente. As vistas previas só mostran os puntos de tanxencia sobre o arco debuxado.", + "help.sketch.construction_line.tangent_two": "Escolle dous círculos ou arcos circulares e despois unha tanxente común na vista previa. Os puntos de tanxencia deben estar sobre as curvas debuxadas.", + "help.sketch.construction_line.vertical": "Crea unha recta de construción vertical infinita por un punto. A súa restrición vertical mantense nas edicións posteriores.", + "help.sketch.copy": "Copia as curvas e os puntos do bosquexo seleccionados, xunto coas restricións e cotas que hai entre eles. Pégaos neste bosquexo ou noutro.", + "help.sketch.create": "Inicia un bosquexo 2D novo nun plano ou nunha cara plana do modelo. Toda extrusión, revolución e varrido comeza cun bosquexo.", + "help.sketch.cut": "Copia a xeometría do bosquexo seleccionada e bórraa do bosquexo, nun só paso de desfacer. Pégaa noutro lugar deste bosquexo ou noutro.", + "help.sketch.dimension": "Engade unha cota de control: unha lonxitude, distancia, ángulo, raio ou diámetro, segundo o que escollas. Escribe un valor ou o nome dun parámetro e o bosquexo séguea.", + "help.sketch.edit": "Abre un bosquexo existente para editalo. As operacións construídas sobre el actualízanse cando remates o bosquexo.", + "help.sketch.ellipse": "Debuxa unha elipse a partir do seu centro, do extremo do seu eixe maior e dun punto do seu lado menor. Úsao para aberturas ovaladas, levas e outras formas redondas alongadas.", "help.sketch.equation_curve": "Debuxa unha curva a partir de fórmulas: x(t) e y(t), ou y = f(x), nun intervalo. As fórmulas poden usar parámetros e a curva segue os seus cambios: úsaa para unha onda senoidal, unha espiral ou a evolvente do dente dunha engrenaxe.", + "help.sketch.extend": "Alonga unha liña ou un arco ata a curva máis próxima que lle sae ao paso, ou fai crecer dúas curvas ata que se atopan. Úsao para pechar ocos nun perfil despois de recortar ou editar.", + "help.sketch.fillet": "Arredonda a esquina onde se atopan dúas liñas ou arcos cun arco dun raio dado. Varias esquinas arredondadas xuntas comparten un só raio.", + "help.sketch.finish": "Sae do bosquexo e volve ao modelo. Os seus perfís pechados quedan listos para Extruír, Revolución e outras operacións.", + "help.sketch.finish_auto_constrain": "Executa Restrición automática no bosquexo e despois remátao. Úsao para deixar un bosquexo totalmente definido nun só paso.", + "help.sketch.fit_curves_to_section": "Corta un corpo de malla ou un sólido co plano do bosquexo e axusta liñas e arcos á sección. Úsao para reconstruír como bosquexo editable unha peza dixitalizada ou importada.", + "help.sketch.include_3d": "Trae arestas do modelo, vértices e curvas doutros bosquexos a este bosquexo como referencias ligadas, aplanando sobre o seu plano as que están fóra del. Úsao para construír sobre xeometría que non está no plano do bosquexo.", + "help.sketch.infinite": "Cambia as liñas entre liñas normais e liñas de construción infinitas que cruzan toda a vista. Úsaas como referencias de disposición que nunca quedan curtas.", + "help.sketch.insert_dxf": "Le as curvas dun debuxo DXF nun bosquexo, escaladas, xiradas e colocadas onde indiques. Úsao para construír sobre un debuxo 2D doutro programa, como un contorno de corte por láser.", + "help.sketch.insert_svg": "Le os trazados dun debuxo SVG nun bosquexo, escalados, xirados e colocados onde indiques. Úsao para converter un logotipo ou un contorno vectorial en curvas que podes extruír.", + "help.sketch.inspect": "Abre un informe do bosquexo aberto: cantos graos de liberdade quedan e se está totalmente restrinxido. Úsao para saber o que aínda se move antes de rematar o bosquexo.", + "help.sketch.intersect": "Engade as curvas ou os puntos onde corpos, caras, arestas ou outros bosquexos cruzan o plano do bosquexo. Quedan ligados e seguen o modelo cando cambia.", + "help.sketch.intersection_curve": "Crea curvas 3D onde se atopan dous corpos ou caras, ligadas a eles. Úsaas como traxectorias ou guías que seguen o modelo.", + "help.sketch.isoparametric_curve": "Crea unha curva 3D na dirección U ou V dunha cara por un punto que escollas, ligada á cara. Úsaa como traxectoria ou liña de división que segue a superficie.", + "help.sketch.line": "Debuxa liñas conectadas punto a punto, como cadea aberta ou como contorno pechado. É a ferramenta básica para a maioría dos perfís.", + "help.sketch.line.midpoint": "Debuxa unha liña desde o seu punto medio ata un extremo, co outro extremo reflectido. Úsao para liñas centradas nun punto, como unha aresta simétrica.", + "help.sketch.line3d": "Debuxa liñas rectas conectadas entre puntos do espazo, co Bosquexo 3D activado. Úsao para traxectorias e estruturas que saen do plano do bosquexo.", + "help.sketch.mirror": "Reflicte curvas e puntos do bosquexo respecto dunha liña ou dun eixe e engade restricións de simetría. Úsao para debuxar a metade dun perfil simétrico e completalo.", + "help.sketch.move": "Move ou xira curvas e puntos do bosquexo, ou unha copia deles. Úsao para recolocar xeometría mantendo a súa forma e as súas restricións.", + "help.sketch.offset": "Crea unha copia dunha cadea de curvas a unha distancia dada, nun lado ou en ambos. Úsao para paredes, contornos e folgas; a distancia segue sendo unha cota editable.", + "help.sketch.paste": "Pega no bosquexo activo a xeometría de bosquexo que copiaches ou cortaches. Colócaa nun punto ou despráxaa unha distancia.", + "help.sketch.pattern.circular": "Copia xeometría do bosquexo arredor dun punto central, nun círculo completo ou nun ángulo dado. Úsao para círculos de parafusos, radios e dentes.", + "help.sketch.pattern.rectangular": "Copia xeometría do bosquexo en filas e columnas con separacións dadas. Úsao para grellas de furados, ranuras ou ventilacións.", + "help.sketch.point": "Coloca un punto de bosquexo. Úsao como referencia para cotas, restricións, centros de furados ou operacións posteriores.", + "help.sketch.point3d": "Coloca un punto no espazo, co Bosquexo 3D activado. Úsao como referencia para curvas e traxectorias 3D.", + "help.sketch.polygon.circumscribed": "Debuxa un polígono regular arredor dun círculo, de tamaño medido desde o seu centro ata o medio dun lado. Úsao cando se coñece a anchura entre planos, como nunha porca hexagonal.", + "help.sketch.polygon.edge": "Debuxa un polígono regular a partir dos dous extremos dun lado. Úsao cando se coñecen a lonxitude e a posición dun lado.", + "help.sketch.polygon.inscribed": "Debuxa un polígono regular dentro dun círculo, de tamaño medido desde o seu centro ata unha esquina. Úsao cando se coñece o tamaño entre esquinas.", + "help.sketch.project": "Trae arestas do modelo, caras, vértices e curvas doutros bosquexos a este bosquexo, proxectadas sobre o seu plano. Quedan ligadas e seguen o modelo cando cambia.", + "help.sketch.project_to_surface": "Proxecta curvas doutros bosquexos ao longo da normal deste bosquexo sobre unha cara, como curvas 3D ligadas. Úsao para poñer un logotipo, unha liña de división ou unha traxectoria sobre unha superficie curva.", + "help.sketch.rectangle.center": "Debuxa un rectángulo a partir do seu centro e dunha esquina. Úsao para contornos centrados nun punto, como a orixe.", + "help.sketch.rectangle.rounded": "Debuxa un rectángulo coas catro esquinas arredondadas a un mesmo raio. Úsao para placas, tapas e aberturas con esquinas arredondadas.", + "help.sketch.rectangle.three_point": "Debuxa un rectángulo a partir dun lado e dun punto do lado oposto. Úsao para rectángulos en ángulo cos eixes do bosquexo.", + "help.sketch.rectangle.two_point": "Debuxa un rectángulo a partir de dúas esquinas opostas. Úsao para os contornos de placas, bloques e rebaixes.", + "help.sketch.scale": "Escala curvas e puntos do bosquexo por un factor respecto dun punto base. Úsao para cambiar o tamaño dunha parte do bosquexo sen volver debuxala.", + "help.sketch.slot.arc_center": "Debuxa unha ranura curva dun ancho dado ao longo dun arco definido polo seu centro, inicio e fin. Úsao para ranuras de axuste arredor dun pivote.", + "help.sketch.slot.arc_three_point": "Debuxa unha ranura curva dun ancho dado ao longo dun arco por tres puntos. Úsao cando a traxectoria da ranura ten que pasar por puntos dados.", + "help.sketch.slot.center_point": "Debuxa unha ranura recta dun ancho dado desde o seu centro ata o centro dun arco extremo. Úsao para ranuras centradas nun punto.", + "help.sketch.slot.center_to_center": "Debuxa unha ranura recta dun ancho dado entre os centros dos seus dous arcos extremos. Úsao para ranuras acotadas de centro a centro, como as ranuras de axuste para parafusos.", + "help.sketch.slot.overall": "Debuxa unha ranura recta dun ancho dado desde un extremo exterior ata o outro. Úsao cando importa a lonxitude total da ranura.", + "help.sketch.spline.control_point": "Debuxa unha spline cúbica definida por puntos de control polos que non pasa. Úsao para curvas suaves e fluídas que moldeas movendo os puntos.", + "help.sketch.spline.control_point_5": "Debuxa unha spline de grao 5 definida por puntos de control. Úsao onde as curvas deben unirse cunha curvatura máis suave, por exemplo en superficies estilizadas visibles.", + "help.sketch.spline.fit_point": "Debuxa unha spline suave que pasa por cada punto que coloques, aberta ou pechada. Úsao para calcar unha forma a través de puntos coñecidos.", + "help.sketch.spline3d": "Debuxa unha curva suave no espazo a través de puntos, co Bosquexo 3D activado. Úsao para traxectorias de varrido e tendidos de cable que saen do plano do bosquexo.", + "help.sketch.spun_profile": "Crea no plano do bosquexo o contorno que describe un corpo ao xirar arredor dun eixe. Úsao para obter a silueta dunha peza torneada para unha revolución ou un debuxo.", + "help.sketch.text": "Escribe texto no bosquexo cunha fonte, altura e ángulo escollidos; as súas palabras poden seguir parámetros. Extrúeo ou grávao en relevo para etiquetas e letreiros.", + "help.sketch.transform": "Escala, xira e move xeometría do bosquexo arredor dun punto central nun só paso. Úsao para recolocar e redimensionar unha selección á vez.", + "help.sketch.trim": "Elimina a parte dunha curva entre os cruzamentos máis próximos ao redor de onde fas clic. Úsao para limpar liñas solapadas ata obter un perfil pechado.", "help.solid.align": "Move os corpos seleccionados para que un punto, cara ou plano deles coincida cun punto, cara ou plano doutro lugar. Úsao para colocar unha peza contra outra sen medir o desprazamento.", + "help.solid.boundary_fill": "Crea sólidos a partir das rexións delimitadas por corpos ferramenta solapados, enchendo só as rexións que escollas. Úsao para construír unha forma a partir do espazo que varios corpos limitan xuntos.", + "help.solid.bounding_solid": "Crea unha caixa que envolve os corpos seleccionados, cunha marxe opcional. Úsao para ver o tamaño total dunha peza, ou como bloque en bruto do que se mecaniza.", + "help.solid.box": "Crea unha caixa a partir dunha lonxitude, largura e altura, desde un punto de esquina ou centrada nun punto. Úsao para un bloque rápido, un marcador de posición ou un corpo no que cortar operacións.", "help.solid.chamfer": "Corta as arestas seleccionadas cun bisel plano da distancia que indiques. Úsao para romper arestas vivas ou para facilitar a entrada dun pasador ou dun parafuso.", + "help.solid.coil": "Crea un corpo helicoidal, como unha mola, a partir dun diámetro, voltas, altura ou paso e unha sección redonda ou cadrada. Úsao para molas, bobinas e cristas helicoidais.", "help.solid.combine": "Une corpos, córtaos dun corpo de destino ou conserva só o volume que comparten, e pode manter os corpos ferramenta. Úsao para fusionar pezas, para cortar unha forma con outra ou para atopar onde se solapan dous corpos.", + "help.solid.cone": "Crea un cono a partir dun círculo de base e unha altura, ou un tronco de cono cando a parte superior tamén ten raio. Úsao para conicidades, funís, avellanados cónicos e puntas.", + "help.solid.cylinder": "Crea un cilindro a partir dun raio ou diámetro e unha altura, apoiado nun punto ao longo dun eixe. Úsao para eixes, pasadores, saíntes e pezas redondas en bruto.", "help.solid.draft": "Inclina as caras seleccionadas segundo o ángulo que indiques, medido desde un plano neutro. Úsao en pezas moldeadas ou fundidas para que saian do molde.", + "help.solid.emboss": "Levanta perfís do bosquexo, como texto ou un logotipo, fóra dunha cara, ou húndeos nela. Úsao para letreiros, etiquetas e marcas en caras planas ou redondas.", "help.solid.extrude": "Empurra un perfil de bosquexo cara ao 3D ao longo dunha distancia, engadindo ou quitando material. Úsao para converter un contorno plano nun bloque, un saínte ou unha cavidade.", "help.solid.fillet": "Arredonda as arestas seleccionadas cunha transición circular suave do raio que indiques. Úsao para suavizar arestas vivas por resistencia, comodidade ou estética.", "help.solid.hole": "Fai un furado redondo do diámetro que indiques nun punto escollido dunha cara. Úsao para folgas de parafusos, pasadores e outras aberturas redondas sinxelas.", @@ -1408,20 +1678,62 @@ "help.solid.move": "Move ou xira os corpos seleccionados, ou unha copia deles, segundo a distancia e o ángulo que indiques. Úsao para recolocar un corpo ou para crear un segundo noutro lugar.", "help.solid.offset_face": "Empurra as caras seleccionadas cara a dentro ou cara a fóra segundo a distancia que indiques, e as caras que as rodean seguen o movemento. Úsao para engrosar unha parede, afondar un rebaixe ou alzar un saínte sen editar o bosquexo.", "help.solid.pattern.circular": "Repite os obxectos seleccionados arredor dun eixe, co número de copias e o ángulo total que indiques. Úsao para circunferencias de parafusos, radios, aletas e dentes.", + "help.solid.pattern.path": "Copia operacións ou corpos ao longo dunha traxectoria de bosquexo, por cantidade e separación. Úsao para furados ao longo dunha aresta curva ou pezas ao longo dun carril.", "help.solid.pattern.rectangular": "Repite os obxectos seleccionados nunha ou en dúas direccións co número de copias e o espazado que indiques. Úsao para filas e grellas de furados, nervios, pasadores ou pés.", + "help.solid.pipe": "Crea un tubo redondo ao longo dunha traxectoria de curvas de bosquexo, macizo ou oco cun espesor de parede. Úsao para tubos, fíos, cables e carrís.", "help.solid.press_pull": "Engade ou retira material ao arrastrar unha cara, ou arredonda as arestas ao arrastralas. Úsao para facer cambios rápidos directamente sobre o modelo.", "help.solid.remove": "Quita os corpos seleccionados do deseño desde este punto da liña de tempo; os pasos anteriores seguen conservándoos. Úsao para descartar un corpo auxiliar, como unha ferramenta de corte que xa non fai falta.", "help.solid.replace_face": "Move as caras planas seleccionadas a un plano ou a unha cara paralela, e o corpo medra ou encolle para chegar a el. Úsao para deixar unha cara a ras doutra peza ou dun plano de construción.", "help.solid.revolve": "Fai xirar un perfil de bosquexo arredor dun eixe para crear un sólido redondo. Úsao para eixes de transmisión, pomos, cuncas e calquera peza redonda arredor dunha liña central.", + "help.solid.rib": "Engade unha parede delgada ao longo dunha curva de bosquexo aberta, chea ata as seguintes caras do corpo. Úsao para reforzar paredes e esquinas, por exemplo en pezas moldeadas ou impresas.", "help.solid.scale": "Fai os corpos seleccionados máis grandes ou máis pequenos segundo un factor, igual en todas as direccións ou un por eixe. Úsao para cambiar o tamaño dunha forma importada ou para compensar a contracción.", "help.solid.shell": "Baleira un sólido deixando paredes co espesor que indiques, e pode abrir as caras que escollas. Úsao para caixas, tapas e outras pezas de parede fina.", + "help.solid.sphere": "Crea unha esfera a partir dun raio ou diámetro arredor dun punto central. Úsao para bólas, pomos e extremos arredondados.", "help.solid.split_body": "Corta un corpo en varios corpos cun plano, a cara doutro corpo ou unha liña de bosquexo. Úsao para facer pezas que se imprimen, mecanizan ou colorean por separado.", "help.solid.split_face": "Divide as caras seleccionadas segundo un plano, a cara doutro corpo ou curvas de bosquexo, sen cortar o corpo. Úsao para dar a unha parte dunha cara o seu propio ángulo de desmoldaxe, cor ou desprazamento.", "help.solid.sweep": "Arrastra un perfil de bosquexo ao longo dunha traxectoria para crear un sólido. Úsao para tubos, carrís, asas e calquera peza de sección constante que siga unha curva.", + "help.solid.thread": "Engade unha rosca métrica ISO a unha cara cilíndrica, como rosca cosmética ou cortada no corpo. Úsao para parafusos, furados roscados e pezas impresas con rosca.", + "help.solid.torus": "Crea un anel a partir dun raio maior arredor do seu eixe e un raio menor para a súa sección redonda. Úsao para xuntas tóricas, asas e contas redondas.", + "help.solid.web": "Engade unha parede delgada ao longo de cada curva de bosquexo aberta, cada unha chea ata as seguintes caras do corpo. Úsao para unha grella de paredes de apoio dentro de carcasas e bandexas.", + "help.surface.blend": "Crea unha superficie que une as arestas de dous corpos, tanxente ou continua en curvatura con ambos. Úsao para unir suavemente dúas superficies a través dun oco.", + "help.surface.boundary": "Crea unha superficie que enche un bucle de dúas a catro curvas de bosquexo, ou unha rede de curvas. Úsao para paneis de forma libre definidos polas súas arestas.", + "help.surface.extend": "Alonga unha superficie máis alá das súas arestas, nunha distancia ou ata un plano ou unha cara. Úsao para que as superficies se solapen antes de recortalas ou coselas.", + "help.surface.extrude": "Empurra curvas ou perfís do bosquexo ao longo dunha distancia ata formar unha superficie, só paredes, sen tapas. Úsao para paredes delgadas e para ferramentas de corte ou división.", + "help.surface.fair": "Suaviza o interior de caras de forma libre mentres as súas arestas quedan onde están. Úsao para igualar bultos e reflexos ondulados nunha superficie.", + "help.surface.loft": "Crea unha superficie que pasa por dúas ou máis seccións en orde, sen tapas. Úsao para carcasas e transicións entre formas diferentes.", + "help.surface.match": "Reconstrúe a aresta dunha superficie para que coincida coa aresta doutro corpo, con tanxencia ou curvatura coincidentes. Úsao para pechar suavemente unha xunta entre dúas superficies.", + "help.surface.offset": "Crea unha copia de caras a unha distancia ao longo das súas normais, como un corpo de superficie novo. Úsao para coberturas, folgas ou o outro lado dunha parede.", + "help.surface.patch": "Enche unha rexión do bosquexo ou un bucle pechado de arestas cunha cara, plana ou suavemente curva. Úsao para pechar furados nun corpo de superficie.", + "help.surface.reverse_normal": "Dá a volta ás caras dun corpo de superficie, de modo que o seu exterior mire ao outro lado. Úsao antes de engrosar ou coser cando as caras apuntan cara a dentro.", + "help.surface.revolve": "Xira curvas ou perfís do bosquexo arredor dun eixe ata formar unha superficie, sen tapas. Úsao para carcasas redondas como pantallas de lámpada, cuncas e boquillas.", + "help.surface.ruled": "Crea unha tira de rectas a partir dunha cadea de arestas, ao longo da normal da cara, da tanxente ou nun ángulo. Úsao para paredes de desmoldaxe, zonas de saída e superficies de partición.", + "help.surface.stitch": "Cose corpos de superficie ao longo das súas arestas compartidas, ata formar un sólido cando se pechan. Úsao para converter un conxunto de superficies nun só corpo.", + "help.surface.sweep": "Move curvas ou perfís do bosquexo ao longo dunha traxectoria ata formar unha superficie, sen tapas. Úsao para canaletas, molduras e outras formas delgadas que seguen unha traxectoria.", + "help.surface.thicken": "Dá espesor a un corpo de superficie e convérteo nun sólido. Úsao para facer pezas imprimibles ou mecanizables a partir de superficies.", + "help.surface.trim": "Corta unha superficie cun plano, outra superficie ou curvas de bosquexo, e conserva o lado que escollas. Úsao para cortar superficies á súa forma antes de coser.", + "help.surface.unstitch": "Separa caras dun corpo en corpos de superficie propios; un sólido desfaise en superficies. Úsao para retocar caras soas dun corpo.", + "help.surface.untrim": "Elimina furados dunha cara, ou restaura o seu contorno exterior aos límites naturais da superficie. Úsao para recuperar a superficie completa despois dun recorte.", "help.third_party": "Licenzas de terceiros", "help.timeline.compute_all": "Reconstrúe todas as operacións da liña de tempo desde o principio. Úsao para actualizar o modelo e ver que operacións fallan.", "help.timeline.delete": "Elimina as operacións seleccionadas da liña de tempo; ao eliminar un bosquexo tamén se eliminan as operacións construídas a partir del. Úsao para quitar un paso que xa non se quere.", + "help.timeline.dependents": "Lista as operacións que se eliminarían con unha operación, e as que fallarían sen ela. Úsao antes de eliminar ou cambiar unha operación.", "help.timeline.play": "Reproduce as operacións restantes unha a unha, cunha pausa de medio segundo despois de cada reconstrución. Executa este comando de novo ou preme Escape para deter a reprodución; Ir ao final salta de inmediato.", + "help.view.apply": "Xira a vista a unha dirección estándar como frontal, superior ou isométrica, ou a unha vista con nome gardada. Úsao para mirar o modelo desde un ángulo fixo.", + "help.view.delete": "Elimina unha vista con nome gardada. O modelo non cambia.", + "help.view.fit": "Fai zoom e desprázase para que todo o modelo, ou a selección, encha a vista. Úsao cando o modelo saíu da vista.", + "help.view.grid": "Mostra ou oculta a grella na ventá gráfica. Úsao como guía de tamaño e orientación ao modelar.", + "help.view.ground_shadow": "Mostra ou oculta a sombra do modelo no chan. Úsao para xulgar máis facilmente a altura e a posición.", + "help.view.home": "Devolve a vista á dirección de inicio e axusta o modelo. Úsao para volver rapidamente a unha vista coñecida.", + "help.view.list": "Lista as vistas con nome gardadas no deseño. Úsao para atopar unha vista que gardaches antes.", + "help.view.navigate": "Xira, despraza ou aplica zoom á vista por pasos, como un cuarto de volta á esquerda. Úsao para mover a cámara con precisión en vez de arrastrar.", + "help.view.navigation_bar": "Mostra ou oculta a barra de navegación na parte inferior da ventá gráfica. Ocúltaa para ter máis espazo e móstraa para acceder co rato ás ferramentas da vista.", + "help.view.rename": "Dálle un nome novo a unha vista con nome gardada. A vista en si non cambia.", + "help.view.save": "Garda a posición actual da cámara como unha vista con nome no deseño. Úsao para volver máis tarde ao mesmo ángulo, por exemplo para capturas de pantalla.", + "help.view.spin": "Orbita a vista arredor do modelo de forma continua ata o seguinte clic ou tecla. Úsao para presentar un modelo desde todos os lados.", + "help.view.tool": "Fixa unha ferramenta de cámara, órbita, desprazamento ou zoom, de modo que arrastrar co botón esquerdo do rato move a vista ata que a desactives. Úsao nun panel táctil ou sen botón central do rato.", + "help.view.visual_style": "Cambia como se debuxa o modelo: sombreado con ou sen arestas, arames ou con arestas ocultas. Usa arames para ver o interior e sombreado para un aspecto limpo.", + "history.sketch_under_constrained": "Subrestrinxido ({count} graos de liberdade)", + "history.sketch_under_constrained_one": "Subrestrinxido ({count} grao de liberdade)", "hole_presets.confirm_delete": "Confirmar a eliminación", "hole_presets.delete": "Eliminar", "hole_presets.delete_prompt": "Eliminar este axuste predefinido persoal? Os furados existentes non cambian.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Comproba o tipo de unión (como Ríxida), a fixación ao chan, os límites da unión e os valores controlados por parámetros.", "joint_move.blocked_title": "Non se pode mover esta peza", "joint_move.coarse": "Paso de rotación preto do eixe (°)", + "joint_move.conflict": "Unha unión desta peza está en conflito coas outras: {joint}.", + "joint_move.conflict_hint": "Edita, suprime ou elimina a unión en conflito para que as outras unións poidan colocar a peza.", "joint_move.distance": "Distancia desde o inicio", "joint_move.done": "Feito", "joint_move.fine": "Paso de rotación lonxe do eixe (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Materiais diferentes", "measure.at": "En", "measure.item": "Elemento {number}", + "measure.quick_copied": "Medición copiada", + "measure.quick_copy": "Fai clic para copiar a medición", + "measure.quick_edges": "{count} arestas", + "measure.quick_faces": "{count} caras", "messages.ago_h": "hai {n} h", "messages.ago_min": "hai {n} min", "messages.ago_s": "hai {n} s", @@ -1620,6 +1938,8 @@ "motion.track_name": "Pista {number}", "nav.alias.help": "Shift+Alt+arrastrar co botón esquerdo orbita, Shift+Alt+botón central desprázase, Shift+Alt+botón dereito fai zoom; arrastrar co botón central tamén desprázase e arrastrar co botón dereito orbita", "nav.blender.help": "Arrastrar co botón central orbita, Shift+botón central desprázase, Ctrl+botón central fai zoom; arrastrar co botón dereito non move a cámara", + "nav.creo.help": "Arrastrar co botón central orbita, Shift+botón central desprázase, Ctrl+botón central arrastrando en vertical fai zoom (cara abaixo para achegar); xira a roda do rato para facer zoom", + "nav.creo.label": "Creo", "nav.free_orbit.help": "O rato e o rato 3D xiran a vista a través dos dous polos e conservan o xiro sobre a vista. O axuste dos eixes con Shift está desactivado.", "nav.free_orbit.label": "Órbita libre", "nav.free_orbit.snap_help": "O rato e o rato 3D xiran a vista a través dos dous polos e conservan o xiro sobre a vista. Mantén Shift durante un arrastre de órbita para axustar a dirección da vista e o xiro.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+arrastrar co botón esquerdo desprázase, Shift+Alt+botón esquerdo fai zoom, Ctrl+arrastrar co botón esquerdo sobre un espazo baleiro orbita", "nav.inventor.help": "Arrastrar co botón central desprázase, Shift+botón central orbita, Ctrl+botón central fai zoom, arrastrar co botón dereito orbita", "nav.maya.help": "Alt+arrastrar co botón esquerdo orbita, Alt+botón central desprázase, Alt+botón dereito fai zoom; arrastrar co botón central tamén desprázase", + "nav.nx.help": "Arrastrar co botón central orbita, Shift+botón central desprázase (botón central + dereito de NX), Ctrl+botón central fai zoom (botón central + esquerdo de NX); arrastrar co botón dereito non move a cámara", "nav.openscad.help": "Arrastrar co botón esquerdo sobre un espazo baleiro orbita, Shift+arrastrar co botón esquerdo selecciona por caixa, arrastrar a xeometría do bosquexo edítaa; arrastrar co botón dereito ou central desprázase, Shift+arrastrar co botón dereito ou central fai zoom", "nav.perspective.sketch": "A edición de bosquexos usa a vista ortogonal. Remata o bosquexo para cambiar á perspectiva.", "nav.right_drag_orbits.help": "Desactivado: arrastrar co botón dereito non move a cámara e o botón dereito só abre o menú contextual. Escoller a asignación do rato de SolidWorks desactívao.", @@ -1748,6 +2069,11 @@ "not a move": "non é un movemento", "not a number": "non é un número", "open a sketch first": "abre primeiro un bosquexo", + "parameters.apply_live": "Aplicar cada cambio ao saír do seu campo", + "parameters.apply_live_tip": "Desactivado: os cambios agardan a Aplicar ou Aceptar, e entón o deseño reconstrúese unha soa vez para todos. Cancelar ou Esc descártaos.", + "parameters.held": "{count} cambios pendentes de Aplicar", + "parameters.held_hint": "Edita expresións e unidades. Os cambios agardan a Aplicar ou Aceptar.", + "parameters.held_one": "1 cambio pendente de Aplicar", "parts.automatic_name": "automático", "parts.dimension.across_flats": "Ancho entre planos", "parts.dimension.bore": "Diámetro do furado", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Parafuso de cabeza abombada con hexágono interior", "parts.family.dowel_pin": "Pasador paralelo (espiga)", "parts.family.hex_bolt": "Parafuso / perno de cabeza hexagonal", + "parts.family.hex_cap_screw_inch": "Parafuso de cabeza hexagonal (polgadas)", "parts.family.hex_nut": "Porca hexagonal", + "parts.family.hex_nut_inch": "Porca hexagonal (polgadas)", "parts.family.set_screw": "Parafuso sen cabeza de hexágono interior, punta plana", "parts.family.socket_head_cap_screw": "Parafuso de cabeza cilíndrica con hexágono interior", "parts.family.washer": "Arandela plana", + "parts.family.washer_sae": "Arandela plana, SAE (estreita)", + "parts.family.washer_uss": "Arandela plana, USS (ancha)", + "parts.holes": "Furados (opcional)", + "parts.placement_hint": "escolle un ou máis furados para asentar unha peza en cada un, ou Aceptar colócaa na orixe", + "parts.system": "Sistema de unidades", + "parts.system.inch": "Polgadas", + "parts.system.metric": "Métrico", "pattern.alignment_2": "Aliñamento 2", "pattern.alignment_hint": "O número inclúe o orixinal. Centrar equilibra as copias; Inverter escolle o lado da copia extra cando o total é par.", "pattern.direction_1": "Dirección 1", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Suaviza as arestas dentadas.", "prefs.applies_on_restart": "Aplícase ao reiniciar", "prefs.assistant": "Asistente", + "prefs.auto_operation": "Escoller a operación automaticamente", + "prefs.auto_operation_note": "Os diálogos das operacións escollen Unir, Corpo novo ou Cortar segundo o que toque o material novo, ata que escollas unha. Desactivado: manteñen a operación coa que se abren.", "prefs.axes": "Eixes", "prefs.axis": "Eixe", "prefs.bodies_folders": "Cartafoles de corpos", @@ -1820,6 +2157,8 @@ "prefs.bottom_centre": "Inferior centro", "prefs.bottom_right": "Inferior dereita", "prefs.browser": "Navegador", + "prefs.browser_eye_left": "Ollo xunto á frecha de expansión", + "prefs.browser_eye_left_note": "As filas do navegador mostran o seu ollo de mostrar/ocultar xunto á frecha de expansión, como antes, en vez de nunha columna no extremo dereito das filas.", "prefs.browser_reveal_on_hover": "Mostrar ao pasar o punteiro", "prefs.browser_show_note": "Visible mantén o navegador na pantalla. Con Mostrar ao pasar o punteiro, queda oculto ata que o punteiro pasa polo seu lugar ou pola lapela estreita do seu bordo esquerdo, e segue aberto mentres o punteiro está dentro del ou hai aberto un menú del.", "prefs.browser_shown": "Visible", @@ -1827,6 +2166,8 @@ "prefs.button_left": "Arrastrar co botón esquerdo", "prefs.button_middle": "Arrastrar co botón central", "prefs.button_right": "Arrastrar co botón dereito", + "prefs.carousel_next": "Seguinte", + "prefs.carousel_previous": "Anterior", "prefs.choose_font": "Escoller ficheiro de tipo de letra…", "prefs.click": "Clic", "prefs.contact_shading": "Sombreado suave de contacto", @@ -1839,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Superficies curvas", "prefs.curves": "Superficies curvas", + "prefs.cut_preview_tint": "Mostrar en vermello o material retirado", + "prefs.cut_preview_tint_help": "Unha vista previa énchea o material que retira unha operación, e a forma que substitúe, cun fantasma vermello translúcido. Se está desactivado, eses recheos son totalmente transparentes e só se debuxan os seus contornos.", + "prefs.dark_parts_shading": "Conservar a forma das pezas escuras", + "prefs.dark_parts_shading_help": "Sombrea a vista en luz lineal cunha luz de recheo suave do ceo, para que as caras escuras manteñan un degradado en vez de volverse negras", "prefs.dead_zone_note": "A banda raiada é a zona morta: o movemento dentro dela ignórase.", "prefs.default": "predeterminado", "prefs.design": "Valores predeterminados do deseño", @@ -1853,6 +2198,8 @@ "prefs.edges": "Arestas e sombreado", "prefs.extend": "Estender", "prefs.extra_navigation": "Ctrl+arrastrar co botón esquerdo no espazo baleiro orbita; mantén premida a barra espaciadora para desprazar.", + "prefs.extrude_view_isometric": "Cambiar a vista a isométrica ao abrir Extruír", + "prefs.extrude_view_return": "Volver á vista anterior ao pechar Extruír", "prefs.follows_os": "Segue o sistema operativo", "prefs.font": "Tipo de letra", "prefs.font_fallback": "Os glifos que lle faltan ao tipo de letra escollido substitúense polos do tipo de letra integrado, así que ningunha etiqueta mostra unha caixa baleira.", @@ -1868,8 +2215,11 @@ "prefs.graphics_card_auto": "Automático", "prefs.graphics_card_missing": "A tarxeta gráfica gardada non está dispoñible; úsase Automático.", "prefs.graphics_card_restart": "Aplícase despois de reiniciar SolidCraft. WGPU_ADAPTER_NAME anula esta opción.", + "prefs.graphics_card_unused": "A tarxeta gráfica gardada non se usou para esta xanela; a tarxeta en uso móstrase en Axuda › Acerca de e na barra de estado. Proba Automático ou define WGPU_ADAPTER_NAME cunha parte única do nome da tarxeta.", "prefs.graphics_note": "Troca velocidade por suavidade. Cada opción mostra o seu efecto nunha mostra.", "prefs.graphics_presets_note": "Os axustes predefinidos configuran xuntas as opcións de abaixo.", + "prefs.hide_constraint_glyphs_zoomed_out": "Ocultar as iconas de restricións ao reducir o zoom", + "prefs.hide_constraint_glyphs_zoomed_out_note": "As iconas de restricións desaparecen da vista cando o zoom do bosquexo está tan afastado que o sobrecargarían. Desactivado: manteñen un tamaño fixo na pantalla con calquera zoom.", "prefs.history": "Historial", "prefs.history_origin_bodies": "Mostrar a orixe e os corpos na parte superior", "prefs.history_origin_bodies_note": "O Historial da esquerda ou baixo o navegador comeza co cartafol Corpos do compoñente activo e coa Orixe, cos seus ollos e menús coma no navegador. O Historial da parte inferior non cambia.", @@ -1880,6 +2230,8 @@ "prefs.history_sketches_note": "Con Bosquexos configurado en Baixo a súa operación, o Historial da esquerda lista cada bosquexo un nivel máis adentro, baixo a primeira operación construída a partir del, sempre que sexa o bastante ancho para mostrar os nomes. A liña de tempo da parte inferior mantén sempre a orde de creación.", "prefs.history_sketches_under_feature": "Baixo a súa operación", "prefs.hold_stop_snapping": "Manter premido para deixar de axustar", + "prefs.home_fit_size": "Tamaño de Inicio e Axustar", + "prefs.home_fit_size_note": "Canto da vista ocupa o modelo cando Inicio, Axustar, un deseño aberto ou un cambio de vista do navegador de vistas o encadran, estea ou non activado o axuste de abaixo. 100 %: ocupa a vista entre os paneis, a brúxula e a barra de navegación.", "prefs.icons_only": "Só iconas", "prefs.imported_file": "Ficheiro importado", "prefs.in_browser": "No navegador", @@ -1888,13 +2240,22 @@ "prefs.interface_language": "Idioma da interface", "prefs.interface_note": "Como se ve SolidCraft e onde están as súas partes.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Inverter as frechas curvas de balanceo", + "prefs.invert_curved_roll_arrows_note": "As dúas frechas curvas da esquina do cubo fan xirar a vista no plano da pantalla. Activado: a frecha en sentido horario xira en sentido antihorario e a frecha en sentido antihorario xira en sentido horario. Desactivado: cada frecha xira a vista no sentido en que se curva.", + "prefs.invert_navigator_arrows": "Invertir as frechas de rotación do cubo de vistas", + "prefs.invert_navigator_arrows_note": "As frechas arredor do cubo fan orbitar a cámara na dirección na que apuntan, como en Fusion e Inventor: a frecha da esquerda apunta á dereita e move a cámara cara á dereita. Desactivado: unha frecha xira o cubo cara ao lado no que está, así que a frecha da esquerda move a cámara cara á esquerda. As frechas curvas de balanceo non se ven afectadas.", + "prefs.keep_work_on_tab_switch": "Manter abertos os diálogos e as ferramentas ao cambiar de deseño", + "prefs.keep_work_on_tab_switch_note": "Cada lapela de deseño conserva o seu diálogo ou ferramenta aberto, co que escolliches e escribiches nel, e a súa lapela da barra de ferramentas. Volven estar aí cando regresas ao deseño. Desactivado: cambiar de deseño cancélaos e mostra a lapela Modelo.", "prefs.labels": "Etiquetas", + "prefs.language_system": "Sistema", "prefs.layout": "Disposición", "prefs.layout_note": "Compacta acopla os paneis aos bordos da xanela. A translucidez do navegador está dispoñible en Flotante. Cambia o lado do Asistente na páxina do Asistente.", "prefs.left": "Esquerda", "prefs.left_click": "Clic esquerdo", "prefs.line_drag_draws_one": "Premer e arrastrar debuxa unha liña", "prefs.line_drag_draws_one_note": "Na ferramenta Liña, premer, arrastrar e soltar debuxa unha liña desde onde se preme ata onde se solta, e remata alí. Os clics seguen debuxando unha cadea. Desactivado: un arrastre coloca un punto onde se solta, como fai un clic.", + "prefs.line_hover_tangent_arc": "Manter o punteiro quieto no último punto dunha liña para cambiar a un arco tanxente", + "prefs.line_hover_tangent_arc_note": "Na ferramenta Liña, unha vez debuxado un segmento, afástate do último punto da cadea, volve e mantén o punteiro quieto nel: o seguinte clic remata un arco tanxente, e o mesmo xesto volve ás liñas. Desactivado: manter o punteiro aí non fai nada.", "prefs.linked_designs": "Deseños ligados", "prefs.live_input": "Entrada en directo", "prefs.live_preview": "Vista previa en directo", @@ -1908,6 +2269,9 @@ "prefs.max_file_size_step": "Ficheiros STEP e de importación", "prefs.max_file_size_web": "A aplicación web abre ficheiros STEP e de importación de ata 512 MB e deseños de ata 256 MB: unha lapela do navegador non admite ficheiros maiores. A aplicación de escritorio permite aumentar estes límites.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Iconas grandes", + "prefs.menu_list": "Lista", + "prefs.menus": "Menús", "prefs.minutes": "minutos", "prefs.minutes_suffix": " min", "prefs.mouse": "Rato e panel táctil", @@ -1915,6 +2279,8 @@ "prefs.mouse_mapping": "Asignación do rato", "prefs.navigation": "Navegación", "prefs.navigation_note": "Como moven a vista o rato, o panel táctil e o rato 3D.", + "prefs.navigator_fit": "Axustar o modelo despois dun cambio de vista do navegador", + "prefs.navigator_fit_note": "Unha cara, esquina ou frecha do cubo de vistas, ou un eixe do gizmo, tamén mira ao centro do modelo desde a única distancia que o abarca por todos os lados (a súa esfera delimitadora). Inicio usa o mesmo zoom e centro mentres isto está activado, así que as vistas escollidas despois só xiran. Desactivado: a vista xira no sitio, conservando o seu punto de mira e o seu zoom.", "prefs.network_host_remove": "Quitar", "prefs.network_locations": "Permitir ubicacións de rede nos deseños", "prefs.network_locations_note": "Desactivado: os ficheiros ligados dun deseño que están noutro ordenador (\\\\server\\share) só se abren desde os servidores listados aquí, ou despois de que permitas un cando se che pregunte.", @@ -1927,10 +2293,18 @@ "prefs.origin_plane_names": "Nomes dos planos de orixe", "prefs.origin_plane_names_note": "Nomes que se mostran no navegador, nos diálogos e nas listas. {top} é XY, {front} é XZ e {right} é YZ, co eixe Z cara arriba. Os comandos, os scripts e os deseños gardados manteñen XY, XZ e YZ.", "prefs.overall_speed": "Velocidade xeral", + "prefs.parameter_list_rows": "Filas da lista de parámetros", + "prefs.parameter_list_rows_tip": "A frecha cara abaixo nun campo de valor baleiro lista os parámetros, primeiro os favoritos, ata este número. Un número menor mantén áxil a lista nun deseño grande.", + "prefs.persistent_ribbon_pressed": "Resaltar as ordes activas da cinta", + "prefs.persistent_ribbon_pressed_help": "Resalta as ordes da cinta mentres os seus efectos están activados. Desactívao para manter o aspecto neutro e a axuda das ordes anteriores.", "prefs.perspective_fov": "Campo de visión", "prefs.placement": "Colocación", "prefs.prefer_free_sketch_points": "Preferir os puntos de bosquexo móbiles cando os puntos se solapan", "prefs.preview_choices": "Vista previa das túas opcións", + "prefs.preview_tint_new_faces": "Colorear a superficie nova nunha vista previa", + "prefs.preview_tint_new_faces_help": "A vista previa dunha operación que cambia un corpo pode debuxar a superficie que engade coa cor da vista previa. Se está desactivado, o corpo debúxase tal e como é.", + "prefs.print_face_highlight": "Resaltado da cara de impresión", + "prefs.print_face_highlight_tip": "Intensidade da tinguidura e do contorno da cara de impresión dun corpo na vista. 0 % non mostra resaltado.", "prefs.profile_active": "Perfil activo", "prefs.profile_applied": "Perfil aplicado.", "prefs.profile_changed": "Os axustes cambiaron desde que se gardou o perfil. Gardar consérvaos nel.", @@ -1952,9 +2326,13 @@ "prefs.quality_fastest": "máis rápido", "prefs.quality_slowest": "máis lento", "prefs.quality_smoother": "máis suave", + "prefs.quick_measure": "Medición rápida na esquina da vista", + "prefs.quick_measure_note": "O tamaño da selección na esquina inferior dereita da vista: a lonxitude dunha aresta, ou Ø e R se é redonda, a área dunha cara, a posición dun punto, a distancia e o ángulo entre dous elementos, o total de varias arestas ou caras. Un clic cópiao.", "prefs.render_previous_geometry_budget": "Usar o orzamento de xeometría anterior da vista previa de Render", "prefs.render_previous_geometry_budget_help": "Restaura o límite fixo de xeometría anterior (512 MiB en escritorio de 64 bits, 128 MiB noutros casos) en lugar do orzamento baseado no dispositivo.", "prefs.reports_saved": "{n} gardados", + "prefs.ribbon_click_ends_tool": "Facer clic no botón da ferramenta en uso remata a ferramenta", + "prefs.ribbon_click_ends_tool_note": "Un clic no botón resaltado da cinta da ferramenta de bosquexo en uso remata a ferramenta, e así os clics na vista volven seleccionar. Desactivado: o clic inicia a ferramenta de novo.", "prefs.ribbon_reveal": "Mostrar os resultados da busca na cinta", "prefs.ribbon_reveal_note": "Ao pasar o punteiro sobre un resultado en Buscar ordes, móstrase onde está a orde na cinta: a súa lapela, o seu botón ou a súa fila no despregable dun panel. Unha orde iniciada desde a busca escintila alí, e unha orde en execución desde un despregable marca o seu panel.", "prefs.right_click": "Clic dereito", @@ -1965,6 +2343,8 @@ "prefs.search_empty": "Non hai axustes que coincidan", "prefs.select": "Seleccionar", "prefs.select_one_item": "Seleccionar un elemento", + "prefs.select_other_hidden": "Seleccionar a xeometría oculta con Seleccionar outro", + "prefs.select_other_hidden_help": "Activado: inclúe os corpos e os bosquexos ocultos e as arestas ocluídas preto do punteiro. Desactivado: usa a lista orixinal de xeometría visible baixo o punteiro.", "prefs.selecting": "Selección", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift só engade; Ctrl / Cmd alterna", @@ -1976,31 +2356,63 @@ "prefs.sketch_align_points_note": "Ao debuxar, un punto alíñase en horizontal cun punto do bosquexo e en vertical con outro á vez, cunha guía punteada, e o clic conserva os dous aliñamentos. Desactivado: só co punto anterior, un eixe de cada vez.", "prefs.sketch_conflict_colour": "Xeometría en conflito na cor de conflito", "prefs.sketch_conflict_colour_note": "Mentres as restricións dun bosquexo están en conflito, as curvas e os puntos que suxeita unha restrición que falla tamén se debuxan na cor de conflito, non só o seu símbolo ou a súa cota. Desactivado: manteñen as súas cores habituais.", + "prefs.sketch_construction_lines": "Ferramentas ampliadas de rectas de construción", "prefs.sketch_exit_view": "Ao rematar un bosquexo", "prefs.sketch_exit_view.keep": "Manter a vista actual", "prefs.sketch_exit_view.previous": "Volver á vista anterior", "prefs.sketch_exit_view.unless_rotated": "Volver, salvo que se xirase", "prefs.sketch_exit_view_note": "A onde vai a vista despois de Finalizar o bosquexo, Cancelar ou un dobre Esc.", + "prefs.sketch_face_activates_part": "Crear un bosquexo na cara dunha peza activa esa peza", + "prefs.sketch_face_activates_part_note": "Un bosquexo iniciado na cara dun corpo doutro compoñente activa primeiro ese compoñente, de modo que o bosquexo lle pertence e queda con esa peza no navegador. Despois a peza segue activa. Desactivado: o bosquexo pertence ao compoñente activo.", + "prefs.sketch_open_look_at": "Xirar para mirar cara ao bosquexo cando se abre", + "prefs.sketch_open_look_at_note": "Desactivado: crear ou editar un bosquexo deixa a vista tal e como está. Mirar cara a orienta a vista cara ao bosquexo cando o queres.", "prefs.sketch_recent_snap": "Axustar automaticamente aos centros e puntos medios recentes", "prefs.sketch_recent_snap_note": "Ao debuxar, o cursor axústase onde se cruzan as guías dos dous últimos centros de círculo ou puntos medios de liña recta. Desactivado: esas guías só se mostran e o cursor non se move.", "prefs.sketch_selection": "Bosquexo e selección", "prefs.sketch_selection_heading": "Bosquexo e selección", "prefs.sketch_selection_note": "Como se axustan os bosquexos e como seleccionan os clics.", + "prefs.sketch_state_icons": "Iconas dos bosquexos na cor do seu estado", + "prefs.sketch_state_icons_note": "No Historial e no navegador, a icona dun bosquexo toma a cor do seu estado (subrestrinxido, totalmente restrinxido ou en conflito) e a súa información emerxente nomea o estado. Desactivado: todos os bosquexos teñen a mesma icona.", "prefs.sketch_tab_always": "Manter visible a lapela Bosquexo", "prefs.sketch_tab_always_note": "A lapela Bosquexo permanece na cinta de opcións, xusto despois de Modelo, mentres non haxa ningún bosquexo aberto. As súas ferramentas de debuxo inician entón un bosquexo no plano ou na cara seleccionados, ou no plano que escollas a continuación, coa ferramenta lista nel.", "prefs.sketch_tracking_guides": "Guías de aliñamento de centro e punto medio", "prefs.sketch_tracking_guides_note": "Pasa o rato sobre o centro dun círculo ou o punto medio dunha liña recta e despois móvete en horizontal ou en vertical para mostrar unha guía punteada temporal.", + "prefs.sketch_tracking_points": "Guías de aliñamento desde extremos e esquinas ao debuxar", + "prefs.sketch_tracking_points_note": "Mentres unha ferramenta de debuxo agarda un punto, ao pasar o cursor sobre o extremo dunha liña ou dun arco, unha esquina de rectángulo ou un punto libre aparece a mesma guía de puntos temporal que para un centro ou un punto medio. Desactivado: só centros e puntos medios.", "prefs.sketching": "Creación de bosquexos", "prefs.snap_drawing_note": "Ao debuxar ou arrastrar un punto de bosquexo.", "prefs.source": "Fonte", "prefs.speed": "Velocidade", "prefs.stand_up_note": "Despois de abrir un ficheiro STEP ou IGES con Z cara arriba, ofrece un cuarto de volta arredor de X.", + "prefs.stand_up_unknown": "Para ficheiros de programas descoñecidos", + "prefs.stand_up_unknown.ask": "Preguntar nun diálogo", + "prefs.stand_up_unknown.note": "Mostrar unha nota", + "prefs.stand_up_unknown.off": "Non ofrecer", + "prefs.stand_up_unknown_note": "Como se fai a oferta cando a cabeceira do ficheiro non nomea ningún programa que se saiba que garda con Y cara arriba. Só se mostra unha nota cando o ficheiro parece estar deitado; Preguntar nun diálogo pregunta por cada ficheiro así, como antes.", "prefs.status_bar": "Barra de estado", "prefs.status_bar_note": "Unha barra fina ao longo do bordo inferior da xanela mostra o que se está a editar, o estado do bosquexo aberto na súa cor e as unidades do deseño; un clic nas unidades cámbiaas. O estado do bosquexo xa non aparece entón na esquina da vista.", "prefs.status_done": "Feito", "prefs.status_error": "Erro", "prefs.status_selected": "Seleccionado", "prefs.status_warning": "Aviso", + "prefs.structure.appearance": "Aparencia", + "prefs.structure.appearance_note": "Cores, texto e accesibilidade.", + "prefs.structure.in_profile": "No perfil", + "prefs.structure.layout": "Disposición", + "prefs.structure.layout_note": "Onde se colocan as partes da xanela.", + "prefs.structure.look": "Estilo", + "prefs.structure.measure_pointer": "Medición e punteiro", + "prefs.structure.mouse3d": "Rato 3D", + "prefs.structure.mouse3d_note": "SpaceMouse e SpaceNavigator.", + "prefs.structure.navigation_note": "Rato e panel táctil. O rato 3D ten a súa propia páxina.", + "prefs.structure.profile": "Perfil", + "prefs.structure.profile_edited": "Cambiado desde que se gardou", + "prefs.structure.profile_hover": "Gardado nos perfís de axustes", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Bosquexo", + "prefs.structure.tools": "Ferramentas", + "prefs.structure.tools_note": "Como se comportan as ferramentas de modelado.", + "prefs.structure.work": "Traballo", "prefs.supersampling_brief": "Debuxa a vista máis grande e redúcea con filtrado: moi nítida, pero máis pesada.", "prefs.tab_accent_note": "O realce segue a pestana activa", "prefs.theme_file": "ficheiro de tema", @@ -2012,6 +2424,16 @@ "prefs.theme_follow_off": "Desactivado", "prefs.theme_follow_stop": "Deixar de seguir", "prefs.theme_import_hint": "Fai clic para escoller un ficheiro de tema, solta un aquí ou preme Ctrl+V (Cmd+V nun Mac) con un tema copiado", + "prefs.theme_option_opacity": "Opacidade", + "prefs.theme_option_opacity_help": "Axusta a opacidade dos paneis flotantes. Un mínimo de lexibilidade protexe o texto sobre as cores da ventá gráfica.", + "prefs.theme_option_tab_colours": "Cores das lapelas", + "prefs.theme_option_tab_colours_help": "Usa as cores de panel e de ventá gráfica deste tema para cada lapela da cinta.", + "prefs.theme_option_tab_fade_ms": "Transición entre lapelas", + "prefs.theme_option_tab_fade_ms_help": "Funde as cores do panel e da ventá gráfica ao cambiar de lapela. Cero cambia ao instante.", + "prefs.theme_options_badge": "Opcións", + "prefs.theme_options_more": "Máis · {count}", + "prefs.theme_options_reset": "Restablecer", + "prefs.theme_options_unavailable": "Non dispoñible neste dispositivo", "prefs.theme_paste": "Pegar tema", "prefs.theme_paste_none": "O portapapeis non contén ningún tema de SolidCraft", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2455,23 @@ "prefs.under_cursor": "Baixo o cursor", "prefs.units_precision": "Unidades e precisión", "prefs.updates": "Actualizacións", + "prefs.value_boxes_in_view": "Mostrar os valores xunto ás súas asas na vista", + "prefs.value_boxes_in_view_tip": "O valor dunha orde (Distancia, Raio…) nunha caixa xunto á súa asa, sobre o modelo. Desactivado: escríbese na xanela da orde, que toma o teclado despois de escoller, e nada cobre o modelo.", "prefs.view": "Comportamento da vista", "prefs.view_confirm_corner": "Aceptar e Cancelar na esquina da vista", "prefs.view_confirm_corner_note": "Mentres hai un diálogo ou un bosquexo aberto, unha marca de verificación e unha cruz na parte superior dereita da vista fan o mesmo que Aceptar e Cancelar do diálogo, ou finalizan e cancelan o bosquexo. O navegador da vista desprázase cara abaixo, debaixo delas.", "prefs.viewport": "Ventá gráfica", + "prefs.viewport_analysis_status": "Mostrar o estado de análise da ventá gráfica", + "prefs.viewport_analysis_status_help": "Mostra as análises activas sobre a ventá gráfica, abre as súas lendas desde cada elemento e usa Esc para desactivar a análise máis recente. Desactiva para restaurar as lendas nas esquinas e o comportamento anterior de Esc.", "prefs.viewport_background": "Fondo", "prefs.viewport_background_colour": "Cor", "prefs.viewport_background_theme": "Degradado do tema", + "prefs.viewport_section_status": "Mostrar o estado da sección na ventá gráfica", + "prefs.viewport_section_status_help": "Mostra o axuste da sección na ventá gráfica. Esc e o botón activo da cinta desactívano. Desactiva para manter os controis de sección anteriores.", + "prefs.viewport_status_details": "Detalles da ventá gráfica en directo", + "prefs.viewport_status_details_help": "Edita os axustes activos de análise e de sección en tarxetas de detalles estándar. Desactiva para restaurar as lendas de análise de só lectura e o diálogo Sección.", + "prefs.viewport_status_summary": "Agrupar os elementos de estado da ventá gráfica", + "prefs.viewport_status_summary_help": "Agrupa tres ou máis elementos de estado da ventá gráfica nun só distintivo de resumo. Desactiva para manter todos os elementos na fila completa.", "prefs.wheel": "Roda", "prefs.wheel_trackpad": "Roda e panel táctil", "prefs.workspace": "Espazo de traballo", @@ -2049,6 +2481,10 @@ "properties.title": "Propiedades: {name}", "recovery.days_ago": "hai {count} días", "recovery.detail": "{file} · {features} operacións · gardado automaticamente {when}", + "recovery.discard_all": "Descartar todo", + "recovery.discard_all_detail": "Esta acción non se pode desfacer.", + "recovery.discard_all_title": "Descartar {count} gardados automáticos?", + "recovery.discard_all_title_one": "Descartar 1 gardado automático?", "recovery.hours_ago": "hai {count} h", "recovery.just_now": "agora mesmo", "recovery.min_ago": "hai {count} min", @@ -2164,6 +2600,10 @@ "render.base_color": "Cor base · sRGB", "render.base_metallic": "Fracción metálica", "render.base_opaque_only": "Este editor mantén a semántica de corpo opaco. Usa os controis explícitos de vidro para a transmisión óptica.", + "render.batch_all_shots": "Todas as tomas ({count})", + "render.batch_empty": "Garda unha toma antes de renderizar todas as tomas.", + "render.batch_limit": "Renderizar todas as tomas está limitado a 32 tomas.", + "render.batch_status": "{running} en curso · {waiting} en espera", "render.bloom_enable": "Mostrar resplandor", "render.bloom_help": "Brillo creativo só de saída a partir de realces lineais positivos, esparexido con tres pasadas de caixa normalizadas. O raio está en píxeles de saída. Engádese na luz de visualización lineal antes de sRGB; non é unha lente, un efecto volumétrico nin unha mellora da converxencia. O EXR en bruto non cambia.", "render.bloom_opaque": "O resplandor require unha saída opaca. O PNG transparente rexéitase; non se aplana sen avisar.", @@ -2274,6 +2714,13 @@ "render.choose_look": "Escolle primeiro un estilo en Aparencias", "render.chromatic_offset": "Desprazamento cromático dos bordos", "render.clear_stage": "Quitar o escenario gardado", + "render.compare_divider": "Divisor da comparación", + "render.compare_live": "En directo", + "render.compare_live_preview": "Vista previa en directo", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · capturado na revisión {revision}", + "render.compare_swap": "Intercambiar", "render.copy_request": "Copiar JSON", "render.cpu_aa_help": "Mostras espaciais: máis mostras melloran os bordos e aumentan o tempo de renderizado.", "render.cpu_area_add": "Engadir luz rectangular da CPU", @@ -2914,7 +3361,9 @@ "render.output_ready": "Listo para renderizar", "render.output_run_check": "Executar a comprobación", "render.output_size_limit": "{method}: ata {dimension} px por lado e {pixels} píxeles. Tamaño máximo que cabe: {width} × {height}.", + "render.output_size_method_profile": "Para renderizar {width} × {height}, escolle {method} co perfil de recursos de CPU {profile}, ou un tamaño menor.", "render.output_size_ok": "Tamaño correcto · {width} × {height} px", + "render.output_size_profile": "Para renderizar {width} × {height}, escolle o perfil de recursos de CPU {profile}, ou un tamaño menor.", "render.output_swap_orientation": "Intercambiar largura e altura", "render.output_tools_inspector": "Edita o tamaño e o formato no inspector de Saída.", "render.output_view_image": "Ver a imaxe", @@ -3021,6 +3470,10 @@ "render.result_retained": "Móstrase a última imaxe completada; un renderizado máis recente non a substituíu.", "render.result_sequence": "Punto de control", "render.result_title": "Resultado do renderizado", + "render.results_choose": "Resultados conservados", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [desactualizado]", + "render.results_unnamed": "Imaxe", "render.return_design": "Volver a Deseño", "render.review_stale": "Esta revisión está obsoleta. Resólvea ou comproba de novo antes de aplicar.", "render.ribbon_aging": "Envellecemento", @@ -3127,6 +3580,7 @@ "render.size_custom": "Personalizado…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · necesita {profile}", "render.size_presets": "Axustes predefinidos de tamaño", "render.size_presets_pending": "Chegará co editor de Saída", "render.size_preview": "Vista previa", @@ -3414,6 +3868,24 @@ "sheet.flange_type_contour": "Contorno", "sheet.flange_type_edge": "Aresta", "sheet.no_body": "non hai ningún corpo de chapa: crea un con Pestana > Base, ou converte unha placa en chapa con Converter en chapa (escolle a súa cara plana grande)", + "sheet.personal_rules.confirm_delete": "Confirmar a eliminación", + "sheet.personal_rules.delete": "Eliminar", + "sheet.personal_rules.delete_prompt": "Eliminar esta regra persoal? As regras que xa están en deseños non cambian.", + "sheet.personal_rules.full": "A biblioteca persoal xa contén 64 regras.", + "sheet.personal_rules.invalid_name": "Introduce un nome curto sen saltos de liña nin caracteres de control.", + "sheet.personal_rules.invalid_values": "Completa os valores da regra: cada un debe poder calcularse neste deseño, cun espesor positivo e un factor K de 0 a 1.", + "sheet.personal_rules.missing": "A regra persoal seleccionada xa non está dispoñible.", + "sheet.personal_rules.name": "Nome da regra", + "sheet.personal_rules.name_exists": "Xa existe unha regra persoal con este nome. Usa un nome diferente.", + "sheet.personal_rules.name_hint": "Un nome único", + "sheet.personal_rules.overwrite": "Gardar os cambios na regra persoal seleccionada", + "sheet.personal_rules.rename": "Renomear", + "sheet.personal_rules.rule": "Regra persoal", + "sheet.personal_rules.save": "Gardar como nova", + "sheet.personal_rules.scope": "Gárdase no teu perfil para todos os deseños.", + "sheet.personal_rules.select": "Selecciona unha regra", + "sheet.personal_rules.title": "Regras persoais", + "sheet.personal_rules.unsupported": "Esta regra ten valores que esta versión non pode usar.", "shortcut.json_error": "os parámetros deben estar en formato JSON: {error}", "shortcut.no_command": "non existe o comando `{id}`; o texto anterior ao JSON debe ser un ID de comando", "shortcut.pin": "Fixar na parte superior da caixa S", @@ -3450,8 +3922,10 @@ "sketch_text.align_right": "Dereita", "sketch_text.bold": "Negra", "sketch_text.builtin_font": "{family} (integrado)", + "sketch_text.formula": "Comeza con = para construír as palabras a partir de parámetros: ='W' + number(Width)", "sketch_text.italic": "Cursiva", "sketch_text.loading_fonts": "Buscando os tipos de letra instalados…", + "sketch_text.no_bold": "O tipo de letra integrado non ten versión en negra: escolle un tipo de letra instalado", "sketch_text.on_path": "O texto segue a súa traxectoria: a curva colócao", "sketch_text.path_clear": "Separar o texto da súa curva", "sketch_text.path_hint": "Unha curva do bosquexo que segue o texto: fai clic aquí e despois na curva", @@ -3483,10 +3957,7 @@ "the two origins are on the same component": "as dúas orixes están no mesmo compoñente", "thread.automatic_size": "Tamaño automático", "thread.designation": "Designación", - "thread.direction": "Dirección da rosca", "thread.iso_metric": "Métrica ISO", - "thread.left_hand": "Á esquerda", - "thread.right_hand": "Á dereita", "thread.select_size": "Seleccionar o tamaño", "timeline.delete_after_marker_one": "Eliminar 1 operación despois do marcador de historial", "timeline.delete_after_marker_other": "Eliminar {count} operacións despois do marcador de historial", @@ -3503,8 +3974,10 @@ "timeline.move_to_group": "Mover operacións ao cartafol", "timeline.rename_group": "Renomear o cartafol de operacións", "timeline.reorder_many": "Reordenar operacións", + "timeline.suppress_features": "Suprimir as operacións", "timeline.suppress_folders_tip": "Suprime ou deixa de suprimir todas as operacións dos cartafoles e dos seus cartafoles aniñados", "timeline.ungroup": "Quitar os cartafoles de operacións", + "timeline.unsuppress_features": "Deixar de suprimir as operacións", "to the face": "á cara", "to the next face": "ata a seguinte cara", "toolbar.customize_note": "Lapela {tab}. Marque un comando para engadir o seu botón á barra de ferramentas. Tamén pode arrastrar unha fila do despregable dun panel á barra, arrastrar un botón fóra da barra para retiralo ou usar a chincheta dunha fila do despregable.", @@ -3588,6 +4061,8 @@ "ui.3d_mouse_section": "Rato 3D", "ui.3d_mouse_show_in_view": "Mostrar o rato 3D na vista 3D", "ui.3d_mouse_show_in_view_tip": "Unha imaxe do teu rato 3D na esquina inferior esquerda que se move cando o moves.", + "ui.3d_mouse_sketch_orbit": "Xirar os bosquexos co rato 3D", + "ui.3d_mouse_sketch_orbit_tip": "O rato 3D tamén xira a vista mentres hai un bosquexo aberto e visto de fronte, como pode facelo o rato. Desactivado: despraza o bosquexo e aplícalle zoom ata que inclines a vista.", "ui.3d_mouse_skip": "O meu dispositivo non fai isto", "ui.3d_mouse_skip_tip": "Omite este movemento nos dous sentidos; a calibración déixao fóra.", "ui.3d_mouse_speed": "Velocidade do rato 3D", @@ -3616,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Xira o capuchón no sentido antihorario, mantén a posición e despois sóltao.", "ui.3d_mouse_switch_cap": "Calibrar como retorno ao centro", "ui.3d_mouse_switch_trackball": "Calibrar como trackball", + "ui.3d_mouse_use_direct": "Usar controlador directo", + "ui.3d_mouse_use_direct_tip": "Ler o rato 3D directamente (hidraw) en vez de a través de spacenavd.", "ui.3d_mouse_view_axis": "Eixe da vista", "ui.3d_mouse_view_off": "Desactivado", "ui.3d_mouse_view_off_tip": "O perfil do controlador do rato 3D desactiva este eixe, así que o seu movemento non move a vista. Se escolles aquí o movemento doutro eixe, intercámbianse e ese movemento deixa de mover a vista.", @@ -3654,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Executa isto nun terminal e despois preme Conectar de novo:", "ui.agent_chat_auth_title": "Iniciar sesión no axente", "ui.agent_chat_cancel": "Cancelar", + "ui.agent_chat_cancel_timeout": "O axente non respondeu a Deter e desconectouse. Volve conectar para continuar.", + "ui.agent_chat_cannot_start": "Instalado, pero non se inicia: {error}", "ui.agent_chat_changes": "Cambios: {n}, un só paso de desfacer", "ui.agent_chat_changes_n": "{n} cambios", "ui.agent_chat_changes_of": "{n}/{limit} cambios", @@ -3662,11 +4141,13 @@ "ui.agent_chat_command": "Orde do axente", "ui.agent_chat_connect": "Conectar", "ui.agent_chat_copy": "Copiar", + "ui.agent_chat_copy_message": "Copiar a mensaxe", "ui.agent_chat_ctx_bodies": "Corpos", "ui.agent_chat_ctx_elements": "Elementos", "ui.agent_chat_ctx_features": "Operacións", "ui.agent_chat_ctx_more": "+{n} máis", "ui.agent_chat_ctx_other": "Outros", + "ui.agent_chat_custom_heading": "Modelo personalizado", "ui.agent_chat_custom_hint": "Calquera programa que fale o Agent Client Protocol por stdin e stdout. Non se executa en ningún shell.", "ui.agent_chat_denied": "Denegado", "ui.agent_chat_deny": "Denegar", @@ -3710,8 +4191,16 @@ "ui.agent_chat_mode_all": "Todo", "ui.agent_chat_mode_ask": "Preguntar", "ui.agent_chat_mode_edits": "Edicións", + "ui.agent_chat_model_custom": "Usar o personalizado: {model}", "ui.agent_chat_model_no_tools": "{model} non pode usar as ferramentas de SolidCraft, así que só pode conversar. Escolle un modelo que admita ferramentas.", + "ui.agent_chat_model_rejected": "O axente non aceptou {model}: {error}", + "ui.agent_chat_model_search": "Buscar modelos…", "ui.agent_chat_model_tip": "O modelo que usa o axente. A túa escolla lémbrase para este axente.", + "ui.agent_chat_models_failed": "Non se puideron listar os modelos: {error}", + "ui.agent_chat_models_heading": "Modelos dispoñibles", + "ui.agent_chat_models_listing": "Listando os modelos…", + "ui.agent_chat_models_none": "O punto de acceso non lista ningún modelo", + "ui.agent_chat_models_not_a_list": "A resposta non era unha lista de modelos", "ui.agent_chat_new": "Chat novo", "ui.agent_chat_new_confirm": "Comezar un chat novo? Borrarase o actual.", "ui.agent_chat_next_picture": "Imaxe seguinte", @@ -3746,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "Na cola (detido, sen enviar)", "ui.agent_chat_refresh": "Actualizar", "ui.agent_chat_refused": "Non permitido ao axente: {reason}", + "ui.agent_chat_reinstall": "{agent} está instalado ({program}), pero non se iniciou cando SolidCraft o comprobou: {error}\nPode que a instalación estea incompleta ou feita para outro tipo de ordenador. Instálao de novo con `{install}`, comproba que mostra a súa versión nun terminal e preme Actualizar.", "ui.agent_chat_remove": "Quitar da cola", "ui.agent_chat_remove_file": "Quitar desta mensaxe", "ui.agent_chat_remove_imported": "Quitar desta mensaxe; a peza queda no deseño (Desfacer quítaa)", + "ui.agent_chat_reply_cut_off": "A resposta chegou ao seu límite de lonxitude antes de acabar, así que pode estar incompleta. Pídelle ao axente que continúe, ou que dea unha resposta máis curta.", + "ui.agent_chat_reply_declined": "O modelo rexeitou responder a esta mensaxe.", "ui.agent_chat_retry": "Reintentar", "ui.agent_chat_right": "Dereita", "ui.agent_chat_save": "Gardar", @@ -3807,12 +4299,17 @@ "ui.ai_copy_suffix": "copia", "ui.ai_custom_url": "URL personalizado", "ui.ai_default": "Predeterminado", + "ui.ai_edit": "Editar", + "ui.ai_edit_agent_title": "Editar axente", + "ui.ai_edit_gone": "Este axente quitouse, así que non hai nada que gardar.", + "ui.ai_edit_tip": "Cambia o nome, a orde ou o punto de acceso deste axente. A clave gardada segue oculta.", "ui.ai_http_busy": "o punto de acceso está ocupado ou superou o seu límite; téntao de novo máis tarde", "ui.ai_http_key": "o punto de acceso rexeitou a clave: compróbaa en Preferencias > IA", "ui.ai_http_not_found": "non existe ese punto de acceso ou modelo: comproba o URL base e o nome do modelo", "ui.ai_http_too_large": "a conversa é demasiado grande para este punto de acceso; comeza un chat novo", "ui.ai_key": "Clave da API", "ui.ai_key_hint": "opcional; gárdase no chaveiro do sistema", + "ui.ai_key_keep_hint": "déixao baleiro para manter a clave gardada", "ui.ai_key_needs_https": "A clave só se envía por HTTPS ou a este ordenador.", "ui.ai_key_note": "Gárdase no chaveiro do sistema, nunca nos axustes de SolidCraft. Déixaa baleira para un servidor local.", "ui.ai_keychain_error": "O chaveiro do sistema rexeitouno: {error}", @@ -3839,11 +4336,15 @@ "ui.ai_permissions": "Permisos", "ui.ai_preset": "Axuste predefinido", "ui.ai_protocol": "Protocolo", + "ui.ai_reasoning_effort": "Esforzo de razoamento", + "ui.ai_reasoning_effort_field_hint": "baleiro = valor predeterminado do provedor", + "ui.ai_reasoning_effort_hint": "Opcional. Envíase ao punto de acceso como `reasoning_effort`; os valores aceptados difiren segundo o provedor (por exemplo `low`, `high` ou `max`). SolidCraft nunca substitúe un valor que definas aquí. Déixao baleiro para non enviar nada e manter o valor predeterminado do provedor.", "ui.ai_remove": "Quitar", "ui.ai_request_timed_out": "O modelo tardou máis de {seconds} s. Podes aumentar o tempo límite da solicitude deste punto de acceso en Preferencias › Asistente.", "ui.ai_request_timeout": "Tempo límite da solicitude", "ui.ai_request_timeout_hint": "Canto pode tardar unha solicitude ao modelo neste punto de acceso, de 30 s a unha hora. Aumenta o valor para un modelo local lento.", "ui.ai_reset": "Restablecer", + "ui.ai_save": "Gardar", "ui.ai_settings": "Axustes de IA…", "ui.ai_show_features": "Mostrar as funcións de IA", "ui.ai_show_features_note": "O chat co axente: un panel onde un axente de programación que xa usas, ou un punto de acceso de modelo que escollas, traballa no deseño aberto. Desactivado: sen botón de IA, atallo, entrada de menú nin panel, e non se busca nin se inicia nada.", @@ -3922,6 +4423,8 @@ "ui.cancel": "Cancelar", "ui.canvases": "Lenzos", "ui.center": "Centro", + "ui.center_arc_follows_cursor": "O arco por punto central segue a dirección do cursor", + "ui.center_arc_follows_cursor_tip": "Un arco por punto central vai no sentido horario ou antihorario segundo como o cursor xira arredor do seu centro. Desactivado: sempre no sentido antihorario desde o inicio.", "ui.centerline": "Liña central", "ui.chain": "Cadea", "ui.chamfer": "Chafrán", @@ -3930,6 +4433,7 @@ "ui.circle": "Círculo", "ui.circular_pattern": "Patrón circular", "ui.clear": "Borrar", + "ui.clear_print_face": "Quitar cara de impresión", "ui.clear_recent": "Borrar recentes", "ui.clear_the_selection": "Borrar a selección", "ui.click_selects_whole_bodies": "Un clic selecciona corpos enteiros", @@ -3964,12 +4468,27 @@ "ui.constant": "Constante", "ui.constraints_conflict": "Conflito de restricións", "ui.construction": "Construción", + "ui.construction.angle_hint": "Recta de construción: fai clic nun punto e despois escribe un ángulo ou escolle unha dirección", + "ui.construction.bisector_hint": "Bisectriz: escolle dúas rectas que se crucen e despois a solución desexada", + "ui.construction.common_hint": "Tanxente común: escolle dous círculos/arcos e despois a solución desexada", + "ui.construction.contact_hint": "Tanxente: escolle un círculo/arco ou unha spline/cónica aberta e despois o punto de tanxencia (curvas de forma libre: extremos)", + "ui.construction.external_hint": "Tanxente: escolle un círculo ou arco, un punto exterior e despois a solución desexada", + "ui.construction.free_hint": "Recta de construción: fai clic en dous puntos; clic dereito para reiniciar", + "ui.construction.normal_needs_length": "Unha recta infinita é sempre de construción: escribe unha lonxitude para debuxar unha liña normal", + "ui.construction.point_hint": "Recta de construción: fai clic no punto polo que debe pasar", + "ui.construction.reference_hint": "Recta de construción: escolle unha recta e despois un punto; clic dereito para cambiar a referencia", "ui.construction.ribbon_label": "Liñas aux.", + "ui.construction.side_hint": "Recta de construción: fai clic no lado cara ao que segue a recta; clic dereito para comezar de novo", "ui.context_menu": "Menú contextual", + "ui.continuity_crease": "Aresta", + "ui.continuity_curvature": "Curvatura", + "ui.continuity_curvature_change": "Cambio de curvatura", "ui.continuity_g0": "G0 aresta", "ui.continuity_g1": "G1 tanxente", "ui.continuity_g2": "G2 curvatura", "ui.continuity_gap": "Separación", + "ui.continuity_position": "Posición", + "ui.continuity_tangent": "Tanxente", "ui.copy": "Copiar", "ui.corner": "Esquina", "ui.corners": "Esquinas", @@ -3992,6 +4511,7 @@ "ui.dark": "Escuro", "ui.default_modelling_orientation": "Orientación de modelado predeterminada", "ui.delete": "Eliminar", + "ui.delete_select_first": "Selecciona primeiro o que queres eliminar: operacións, corpos, compoñentes ou xeometría do bosquexo", "ui.depth": "Profundidade", "ui.design": "Deseño", "ui.design_properties.author": "Autor", @@ -4006,6 +4526,40 @@ "ui.design_properties.project": "Proxecto", "ui.design_properties.revision": "Revisión", "ui.design_saved": "Gardado en {path}", + "ui.details_access_caption": "As caras mostran se unha ferramenta pode chegar a elas desde a dirección escollida.", + "ui.details_angle": "Ángulo", + "ui.details_continuity_caption": "Edita a xunta seleccionada. As outras xuntas manteñen os seus propios axustes.", + "ui.details_continuity_stale": "Xeometría anterior: volve executar a análise para editar ou encadrar esta xunta.", + "ui.details_copy_list": "Copiar a lista", + "ui.details_curvature": "Tolerancia de curvatura", + "ui.details_curvature_caption": "As caras coloréanse segundo o seu raio de curvatura local.", + "ui.details_direction": "Dirección da ferramenta", + "ui.details_draft_caption": "As caras coloréanse segundo o seu ángulo coa dirección de extracción.", + "ui.details_edit_seam": "Editar a xunta", + "ui.details_fixture": "Mostra de compoñente — só datos de exemplo", + "ui.details_fixture_caption": "Mostra de compoñente con valores ilustrativos; non é un resultado do modelo.", + "ui.details_fixture_problem": "Exemplo de resultado cun problema", + "ui.details_fixture_readout": "Exemplo de valor medido", + "ui.details_flip": "Inverter", + "ui.details_gap": "Separación", + "ui.details_hatch": "Raiar as caras cortadas", + "ui.details_jump": "Salto de curvatura", + "ui.details_key": "Lenda", + "ui.details_offset": "Desprazamento", + "ui.details_plane": "Plano", + "ui.details_pull": "Dirección de extracción", + "ui.details_radius": "Raio", + "ui.details_readout": "Lectura", + "ui.details_samples": "Mostras", + "ui.details_seam": "{body} · Aresta {edge}", + "ui.details_settings": "Axustes", + "ui.details_sharp_gap": "Quebra ou separación", + "ui.details_show_all": "Mostrar todos ({count})", + "ui.details_smooth": "Suave", + "ui.details_stripes": "Raias", + "ui.details_target": "Encadrar a xeometría", + "ui.details_worst_seams": "Peores xuntas", + "ui.details_zebra_caption": "As raias reflectidas mostran con que suavidade se unen as caras.", "ui.diameter": "Diámetro", "ui.dimension": "Cota", "ui.direct_interaction": "Interacción directa", @@ -4050,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "A peza gardouse noutro ficheiro; a ensamblaxe segue ligando {name}", "ui.edit_in_place_wait": "Agarda a que remate o que se está a executar no deseño", "ui.edit_section_analysis": "Editar a análise de sección", + "ui.edit_sketch_empty": "Non hai bosquexos para editar", "ui.ellipse": "Elipse", "ui.emboss_wrap_note": "Os perfís de liñas ortogonais tanxentes a un cilindro compatible envólvense automaticamente. Escolle unha parede para elixir un destino.", "ui.end_radius": "Raio final", @@ -4060,12 +4615,15 @@ "ui.equation_explicit": "Explícita", "ui.equation_form": "Forma", "ui.equation_note": "A variable é un número sen unidade: sin(t) tómaa en radiáns. Un resultado sen unidade está na unidade do deseño.", + "ui.equation_note_range": "A variable é unha lonxitude, igual que o seu intervalo: combínaa con parámetros de lonxitude e divídea entre unha lonxitude para sin(). Un resultado sen unidade está na unidade do deseño.", "ui.equation_parametric": "Paramétrica", + "ui.equation_variable_unit": "A variable ten a unidade do intervalo", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Raio equivalente", "ui.expand": "Expandir", + "ui.explode_needs_two_components": "A vista explosionada separa compoñentes, así que o deseño necesita dous ou máis (Compoñente novo, Inserir deseño ou Crear compoñentes a partir de corpos)", "ui.exportDxf": "Exportar DXF…", "ui.export_ellipsis_keymap": "Exportar…", "ui.export_keymap_tip": "Teclas, favoritos da caixa S e a barra de ferramentas, como un ficheiro", @@ -4191,6 +4749,7 @@ "ui.hideOrigin": "Ocultar a orixe", "ui.hidePlanes": "Ocultar os planos", "ui.hideProfile": "Ocultar o perfil", + "ui.hide_component_history": "Ocultar o seu historial", "ui.hide_origin_by_default": "Ocultar a orixe de forma predeterminada", "ui.hide_origin_note": "Os deseños novos comezan co cartafol Orixe oculto. Un deseño conserva o seu propio axuste de Orixe cando o mostras ou o ocultas.", "ui.history_back": "Retroceder un paso", @@ -4198,6 +4757,7 @@ "ui.history_edge_hint": "fai dobre clic na aresta", "ui.history_first": "Ir ao comezo", "ui.history_forward": "Avanzar un paso", + "ui.history_hide_hidden": "Ocultar os compoñentes ocultos", "ui.history_hide_names": "Ocultar os nomes", "ui.history_last": "Ir ao final", "ui.history_marker_tip": "Marcador de historial: arrastra para retroceder o modelo; as operacións novas van aquí", @@ -4207,10 +4767,12 @@ "ui.history_play_button_show": "Mostrar o botón Reproducir", "ui.history_play_finish_action": "Remata a acción actual antes de reproducir o historial", "ui.history_play_roll_back": "Move o marcador do historial cara atrás antes de reproducir", + "ui.history_show_hidden": "Mostrar os compoñentes ocultos", "ui.history_show_names": "Mostrar os nomes", "ui.history_sketch_listed_under": "Listado en {feature}", "ui.history_title": "Historial", "ui.history_toggle_names": "Mostrar ou ocultar os nomes das operacións", + "ui.history_waits_for_editor": "Desfacer, Refacer e Historial agardan ata que se abra o editor da operación", "ui.hole": "Furado", "ui.hole_tap_type": "Tipo de roscado do furado", "ui.hole_type": "Tipo de furado", @@ -4226,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} ten cambios sen gardar, así que se inseriu o seu ficheiro gardado. Gárdao e despois usa Actualizar as ligazóns para incorporar os cambios.", "ui.insert_design.unsaved": "Cambios sen gardar", "ui.inspect": "Inspeccionar", + "ui.instances": "Instancias", "ui.intersect": "Intersecar", "ui.isolate": "Illar", "ui.join": "Unir", @@ -4234,12 +4797,14 @@ "ui.joints": "Unións", "ui.keyboard_shortcuts": "Atallos de teclado", "ui.language": "Idioma", + "ui.lasso_select": "Lazo (arrastra un bucle a man alzada: colle o que queda totalmente dentro)", "ui.layout_compact": "Compacta", "ui.layout_floating": "Flotante", "ui.length": "Lonxitude", "ui.length_decimals": "Decimais das lonxitudes", "ui.light": "Claro", "ui.line": "Liña", + "ui.line_arc_hint": "Arco tanxente: fai clic no final do arco. Mantén o punteiro quieto de novo no último punto para volver ás liñas; clic dereito ou Esc para finalizar", "ui.link_copies": "Ligar copias idénticas", "ui.link_copies_keep": "Manter", "ui.link_copies_link": "Ligar", @@ -4328,6 +4893,7 @@ "ui.part_size_shared": "Reconstrúe a peza, substituíndo as operacións engadidas. Actualízanse todas as ocorrencias deste compoñente.", "ui.paste": "Pegar", "ui.path": "Traxectoria", + "ui.pattern_object_type_tip": "Corpos: formas sólidas, escollidas na vista ou no Navegador; cada un cópiase enteiro.\nOperacións: pasos do Historial, como unha extrusión ou un furado, escollidos no Historial ou nunha cara que crearon; repítese o paso.\nUn bosquexo non é ningunha das dúas cousas: repite as súas curvas co Patrón ou a Simetría do propio bosquexo, ou extrúeo primeiro.", "ui.pattern_on_path": "Patrón nunha traxectoria", "ui.perforate_margin_default": "a partir do diámetro", "ui.perforate_pitch": "Paso", @@ -4354,12 +4920,17 @@ "ui.plugins_skipped": "Non se puido ler {count} cartafol(es).", "ui.plugins_version": "{version}", "ui.point": "Punto", + "ui.point_cloud_add_filter": "Engadir filtro…", "ui.point_cloud_auto_range": "Intervalo automático", "ui.point_cloud_color_by": "Colorear por", "ui.point_cloud_file_colors": "Cores do ficheiro", + "ui.point_cloud_filter_by": "Filtrar por", "ui.point_cloud_height_high": "Máis alto", "ui.point_cloud_height_low": "Máis baixo", + "ui.point_cloud_legend_filter": "Mostrado e oculto na lenda de arriba", "ui.point_cloud_no_file_colors": "O ficheiro non ten cores", + "ui.point_cloud_pause": "Pausa", + "ui.point_cloud_play": "Reproducir", "ui.point_cloud_single_color": "Cor única", "ui.point_cloud_size": "Tamaño do punto", "ui.point_cloud_units": "Unidades do ficheiro", @@ -4368,6 +4939,11 @@ "ui.polygon": "Polígono", "ui.preferences": "Preferencias", "ui.press_a_key": "preme unha tecla…", + "ui.print_face_body_not_sent": "O corpo desa cara non se envía: engádeo primeiro a Corpos", + "ui.print_face_cleared": "{body}: cara de impresión quitada", + "ui.print_face_input": "Cara de impresión", + "ui.print_face_pick": "Selecciona unha cara plana dun corpo sólido para facela a cara de impresión", + "ui.print_face_set": "{body}: cara de impresión definida; Enviar ao laminador apoia o corpo sobre ela", "ui.profile": "Perfil", "ui.profile_plane": "Plano do perfil", "ui.profiles": "Perfís", @@ -4383,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Medindo…", + "ui.properties.measuring_bodies": "Medindo… {done} de {total} corpos", "ui.properties.measuring_failed": "A medición detívose antes de rematar.", "ui.properties.principal_axis": "Eixe principal {number}", "ui.properties.principal_moments": "Momentos principais", @@ -4431,6 +5008,7 @@ "ui.revolve": "Revolución", "ui.ribbon_exit": "Saír", "ui.ribbon_labels": "Mostrar texto baixo as iconas da cinta", + "ui.ribbon_menus_skip_pinned": "Deixar as ordes fixadas fóra dos menús despregables", "ui.ribbon_pin_footer": "As ordes fixadas móstranse na cinta. Pasa o cursor sobre unha fila para fixala ou soltala.", "ui.ribbon_workspace": "Espazo de traballo", "ui.right": "Dereita", @@ -4449,6 +5027,7 @@ "ui.selectOther": "Seleccionar outro…", "ui.selectTangentChain": "Seleccionar cadea tanxente", "ui.select_all": "Seleccionar todo", + "ui.select_components_by_face": "Seleccionar compoñentes (unha cara escolle o seu compoñente)", "ui.selection": "Selección", "ui.selection_modifiers": "Modificadores de selección", "ui.selection_shift_add_only": "Maiús+clic engade sen quitar", @@ -4474,6 +5053,7 @@ "ui.showDimension": "Mostrar a cota", "ui.showOrigin": "Mostrar a orixe", "ui.showPlanes": "Mostrar os planos", + "ui.show_component_history": "Mostrar o seu historial", "ui.show_constraints": "Restricións", "ui.show_construction_geometries": "Xeometrías de construción", "ui.show_dimensions": "Cotas", @@ -4490,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Filtro de selección", "ui.sketch_modifiers": "Modificadores de bosquexo", "ui.sketch_project_geometry": "Xeometría", + "ui.sketch_report.all_constrained": "Todo está totalmente restrinxido.", + "ui.sketch_report.dof": "Graos de liberdade", + "ui.sketch_report.loose": "Non totalmente restrinxido", + "ui.sketch_report.status": "Estado", + "ui.sketch_report.title": "Informe do bosquexo", "ui.sketch_scale": "Escala do bosquexo", "ui.sketches": "Bosquexos", "ui.slice": "Laminar", @@ -4585,19 +5170,31 @@ "ui.view_angles": "Ángulos da vista", "ui.view_angles_convention": "Graos arredor do eixe cara arriba. A guiñada 0° é a vista frontal, 90° a esquerda, −90° a dereita, 180° a posterior; un cabeceo de 90° é a vista superior; un balanceo positivo fai xirar o modelo en sentido horario.", "ui.view_angles_help": "Mostra o cabeceo, a guiñada e o balanceo da vista en graos e a súa proxección baixo o indicador de orientación. Fai clic na lectura para escribir ángulos exactos.", + "ui.view_angles_lock": "Bloquear {axis}", "ui.view_angles_ortho": "Orto", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Cabeceo", "ui.view_angles_readout": "Cabeceo {pitch} · Guiñada {yaw} · Balanceo {roll}", "ui.view_angles_roll": "Balanceo", + "ui.view_angles_unlock": "Desbloquear {axis}", "ui.view_angles_yaw": "Guiñada", + "ui.view_angles_zero": "Poñer {axis} a 0°", "ui.view_centre": "Centro da vista", "ui.viewport_status_clear": "Desactivar {name}", "ui.viewport_status_clear_hint": "Desactivar {name} · Esc", + "ui.viewport_status_edges": "{count} arestas", + "ui.viewport_status_from": "desde {direction}", "ui.viewport_status_key": "Mostrar a lenda de {name}", "ui.viewport_status_minimum_radius": "Raio mínimo", "ui.viewport_status_pairs": "{count} pares", + "ui.viewport_status_section_hatch": "{setting} · raiado", + "ui.viewport_status_section_plane": "Plano actual", + "ui.viewport_status_section_tilted": "inclinado · {offset}", "ui.viewport_status_stripes": "{count} raias", + "ui.viewport_status_summary_clear": "Desactivar todo", + "ui.viewport_status_summary_heading": "Nesta vista", + "ui.viewport_status_summary_label": "{name} e {count} elementos máis", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Seguir o tema", "ui.visual_shaded_hidden_edges": "Sombreado con arestas ocultas", "ui.visual_shaded_with_edges": "Sombreado con arestas", @@ -4634,10 +5231,12 @@ "update.button": "Actualizar", "update.button_version": "Actualizar a {version}", "update.check_automatically": "Buscar actualizacións automaticamente", + "update.check_for_updates": "Buscar actualizacións", "update.check_now": "Comprobar agora", + "update.check_unavailable": "A busca de actualizacións non está dispoñible para esta instalación.", "update.checking": "Comprobando…", "update.copy": "Copiar", - "update.dmg_opened": "A imaxe de disco está aberta e verificada: arrastra SolidCraft a Aplicacións, substituíndo a copia antiga, e despois reinicia SolidCraft.", + "update.dmg_opened": "A imaxe de disco está aberta e verificada: sae de SolidCraft, arrastra o novo SolidCraft a Aplicacións, substituíndo a copia antiga, e despois volve abrir SolidCraft.", "update.download": "Descargar", "update.download_open": "Descargar e abrir", "update.downloading": "Descargando e verificando… {done} de {total} MB", @@ -4648,11 +5247,13 @@ "update.installed": "SolidCraft {version} está instalado. Reinicia para usalo.", "update.installer_started": "O instalador iníciase cando se pecha SolidCraft.", "update.later": "Lembrarmo máis tarde", + "update.managed": "Actualización dispoñible: actualiza SolidCraft en {manager}", "update.no_notes": "Esta versión non ten notas.", "update.package_hint": "Esta copia veu dun {kind}. Descarga o paquete novo e despois instálao con:", "update.prefs_dev": "Esta é unha compilación de desenvolvemento ({version}): non busca actualizacións.", "update.prefs_flatpak": "Flatpak actualiza esta copia ({version}): executa {command} ou usa o teu centro de software. SolidCraft non comproba.", "update.prefs_label": "Actualizacións", + "update.prefs_managed": "Esta é a versión {version} de SolidCraft, xestionada por {manager}. Unha comprobación pídelle a GitHub a última versión e non envía nada máis; actualiza SolidCraft en {manager}.", "update.prefs_note": "Esta é a versión {version} de SolidCraft ({kind}). Unha comprobación pídelle a GitHub a última versión e non envía nada máis.", "update.prefs_web": "Recarga a páxina para obter a última versión da aplicación web. Se a rede non está dispoñible ou a actualización non pode rematar de descargarse a tempo, ábrese a versión gardada; unha descarga en curso continúa para a seguinte recarga.", "update.refresh_checking": "Buscando a versión máis recente…", @@ -4679,6 +5280,7 @@ "web.open_link": "Abrir o deseño ligado?", "web.open_link_confirm": "Hai cambios sen gardar. Abrir o deseño ligado nunha pestana nova?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ escoller · Intro / Tab completar · Esc pechar", + "↑ ↓ choose · Enter applies this value": "↑ ↓ escoller · Enter aplica este valor", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ escoller · Enter aplica o que escribiches · Esc pechar", "⌘Enter continues on GitHub.": "⌘Enter continúa en GitHub." } diff --git a/assets/locales/he.json b/assets/locales/he.json index 5406d3e30..95b65b5b7 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "משטח מעבר", "BOUNDARY SURFACE": "משטח גבול", "BROWSER": "עץ התכן", + "Back to the original order": "חזרה לסדר המקורי", "Ball": "כדורי", "Bar": "מוט", "Base Center": "מרכז הבסיס", @@ -378,7 +379,7 @@ "Move Type": "סוג הזזה", "Move down": "הזזה למטה", "Move earlier": "הקדמה", - "Move holes by clicking or dragging": "הזזת חורים בלחיצה או בגרירה", + "Move holes by clicking or dragging": "הזזה בלחיצה או בגרירה", "Move later": "דחייה", "Move up": "הזזה למעלה", "Name": "שם", @@ -476,6 +477,7 @@ "Rectangular": "מלבני", "Rectangular Tube": "צינור מלבני", "Reference face": "פאת ייחוס", + "Reference plane": "מישור ייחוס", "Relief Depth": "עומק הקלה", "Relief Width": "רוחב הקלה", "Remove Tools": "הסרת הכלים", @@ -493,7 +495,8 @@ "Rename Folder": "שינוי שם תיקייה", "Render Stage": "שלב הרינדור", "Reopen designs": "פתיחה מחדש של תכנים", - "Reopen the designs that were open when SolidCraft was last closed": "פתיחה מחדש של התכנים שהיו פתוחים כש־SolidCraft נסגרה בפעם האחרונה", + "Reopen the designs that were open when SolidCraft was last closed": "פתיחה מחדש של התכנונים שהיו פתוחים בפעם הקודמת", + "Repair Part": "תיקון חלק", "Replace existing library file": "החלפת קובץ הספרייה הקיים", "Report a bug — review a screenshot and open a GitHub draft": "דיווח על באג — בדיקת צילום מסך ופתיחת טיוטה ב־GitHub", "Report copied. Keep this text to submit on GitHub when you are online.": "הדיווח הועתק. יש לשמור את הטקסט כדי לשלוח אותו ב-GitHub כשהחיבור לאינטרנט יהיה זמין.", @@ -555,6 +558,7 @@ "Section": "חתך", "Section (optional)": "חתך (אופציונלי)", "Section position": "מיקום החתך", + "Sections": "חתכים", "Sections (one sketch each)": "חתכים (סקיצה אחת לכל אחד)", "Select Other": "בחירת אחר", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "בחירת אחר: החזקת הכפתור השמאלי ללא תזוזה על המודל (או לחיצה ימנית › בחירת אחר…) מציגה את כל מה שמתחת לסמן; לחיצה נוספת באותה נקודה בוחרת את הפריט הבא שם. לחיצה כפולה על הכפתור האמצעי חוזרת לתצוגת הבית (העדפות › ניווט).", @@ -581,7 +585,7 @@ "Show ghost": "הצגת צללית", "Show in folder": "הצגה בתיקייה", "Show the pointer an AI agent moves (#35)": "הצגת הסמן שסוכן הבינה המלאכותית מזיז (#35)", - "Show tool at cursor": "הצגת הכלי ליד הסמן", + "Show tool at cursor": "כלי ליד הסמן", "Signed axes": "צירים עם סימן", "Size": "גודל", "Sketch constraints": "אילוצי סקיצה", @@ -592,9 +596,11 @@ "Sketch points": "נקודות סקיצה", "Slider": "הזזה", "Slot width": "רוחב חריץ", - "Snap to face and edge centres": "הצמדה למרכזי פאות ומקצועות", + "Snap to face and edge centres": "הצמדה למרכזים", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "אין אפשרות לשלוח דיווחים ישירות מתוך SolidCraft. יש לשלוח אותם ב-GitHub; אין צורך באסימון גישה באפליקציה.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft נסגרה לפני שתכנים אלה נשמרו. אפשר לפתוח את השמירה האוטומטית האחרונה שלהם.", + "Sort A to Z": "מיון בסדר עולה", + "Sort Z to A": "מיון בסדר יורד", "Spacing 2 must be a non-zero number": "מרווח 2 חייב להיות מספר שונה מאפס", "Spacing must be a non-zero number": "המרווח חייב להיות מספר שונה מאפס", "Specialise": "התמחות", @@ -733,36 +739,36 @@ "a picked edge's body is gone": "הגוף של המקצוע שנבחר כבר לא קיים", "add a key for a joint first": "יש להוסיף תחילה מפתח למפרק", "ai.connected_toast": "SolidCraft זמין עכשיו ב־{clients}. יש להפעיל אותם מחדש כדי להשתמש בו (הגדרות > עוזר).", - "ai.prefs.allow_control": "התרת חיבור לסוכני בינה מלאכותית (ערוץ בקרה / MCP)", - "ai.prefs.allow_control_note": "פותח ערוץ בקרה במחשב זה בלבד (127.0.0.1, פורט 27878 או הפנוי הבא). תוכנה שמתחברת צריכה גם להציג אסימון סודי שרק חשבון המשתמש שלך יכול לקרוא, ונוצר מחדש בכל הפעלה. ייכנס לתוקף בהפעלה הבאה של SolidCraft. כבוי: שום דבר אינו מאזין, אלא אם SolidCraft מופעל עם --control.", - "ai.prefs.availability": "פקדי העוזר", - "ai.prefs.background_commands": "הרצת פקודות הסוכן ברקע", - "ai.prefs.connect_apps": "הנגשת SolidCraft ליישומי בינה מלאכותית במחשב זה", - "ai.prefs.connect_apps_note": "בהפעלת SolidCraft הוא מתווסף כשרת MCP ליישומי הבינה המלאכותית שנמצאו במחשב זה (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), כך שסוכן יכול להשתמש בו בלי שום הגדרה. רק הרשומה solidcraft נוספת או שהנתיב שלה מתעדכן; רשומה ששינית נשארת כפי שהיא, ולפני כן נשמר גיבוי של הקובץ. כבוי: הרשומות שנוספו מוסרות. הפקודה עזרה > חיבור עוזרי בינה מלאכותית… עושה זאת ידנית.", - "ai.prefs.connect_at_start": "התחברות לסוכן האחרון שבו השתמשת בהפעלת SolidCraft", + "ai.prefs.allow_control": "לאפשר לסוכני AI להתחבר", + "ai.prefs.allow_control_note": "ערוץ מקומי (MCP). שום דבר לא יוצא מהמחשב הזה.\n\nפותח ערוץ בקרה במחשב זה בלבד (127.0.0.1, פורט 27878 או הפנוי הבא). תוכנה שמתחברת צריכה גם להציג אסימון סודי שרק חשבון המשתמש שלך יכול לקרוא, ונוצר מחדש בכל הפעלה. ייכנס לתוקף בהפעלה הבאה של SolidCraft. כבוי: שום דבר אינו מאזין, אלא אם SolidCraft מופעל עם --control.", + "ai.prefs.availability": "זמינות", + "ai.prefs.background_commands": "להפעיל פקודות איטיות ברקע", + "ai.prefs.connect_apps": "להוסיף את SolidCraft ליישומי AI", + "ai.prefs.connect_apps_note": "כיבוי מסיר שוב את הרשומות.\n\nבהפעלת SolidCraft הוא מתווסף כשרת MCP ליישומי הבינה המלאכותית שנמצאו במחשב זה (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), כך שסוכן יכול להשתמש בו בלי שום הגדרה. רק הרשומה solidcraft נוספת או שהנתיב שלה מתעדכן; רשומה ששינית נשארת כפי שהיא, ולפני כן נשמר גיבוי של הקובץ. כבוי: הרשומות שנוספו מוסרות. הפקודה עזרה > חיבור עוזרי בינה מלאכותית… עושה זאת ידנית.", + "ai.prefs.connect_at_start": "לחבר את הסוכן האחרון בהפעלה", "ai.prefs.connect_at_start_note": "מפעיל ברקע את הסוכן שאליו התחברת לאחרונה (או את סוכן ברירת המחדל) בכל הפעלה של SolidCraft, כך שהוא מוכן לשיחה. לא כש-SolidCraft מופעל עם --control. אם ההתחברות נכשלת, העוזר מציג „ההתחברות נכשלה” ולחצן „ניסיון חוזר”.", - "ai.prefs.follow_camera": "הפניית המצלמה אל סקיצות", + "ai.prefs.follow_camera": "לעקוב אחר המצלמה", "ai.prefs.follow_camera_off": "מעקב המצלמה האוטומטי כבוי.", "ai.prefs.follow_camera_on": "המצלמה פונה אל הסקיצות שהסוכן יוצר.", - "ai.prefs.intro": "סוכנים, הרשאות ואופן הצגת העבודה שלהם.", - "ai.prefs.make_default": "שימוש כברירת מחדל", + "ai.prefs.intro": "סוכני AI ב־SolidCraft.", + "ai.prefs.make_default": "לקבוע כברירת מחדל", "ai.prefs.no_agents": "אין עדיין סוכנים. אפשר להוסיף סוכן או לרענן כדי למצוא סוכנים מותקנים.", "ai.prefs.no_saved_approvals": "אין אישורים שמורים.", - "ai.prefs.open_at_start": "פתיחת חלונית העוזר בהפעלת SolidCraft", + "ai.prefs.open_at_start": "לפתוח את הצ'אט בהפעלה", "ai.prefs.open_at_start_note": "מציג את חלונית העוזר (או את החלון הנפרד שלה) בכל הפעלה של SolidCraft. לא כש-SolidCraft מופעל עם --control.", "ai.prefs.override_all_warning": "הסוכן הזה עשוי לשמור, לדרוס, לייצא או להחליף את התכן בלי לשאול.", - "ai.prefs.permission_all": "התרת הכול", - "ai.prefs.permission_all_summary": "כלי SolidCraft הזמינים פועלים בלי לשאול.", - "ai.prefs.permission_ask": "שאלה לפני שינויים", - "ai.prefs.permission_ask_summary": "אישור כל שינוי בתכן וכל פעולה על קבצים.", - "ai.prefs.permission_edits": "התרת עריכות מודל", - "ai.prefs.permission_edits_summary": "עריכות מודל מתבצעות; פעולות קבצים ופעולות הרסניות עדיין דורשות אישור.", + "ai.prefs.permission_all": "לעשות הכול", + "ai.prefs.permission_all_summary": "אף פעם לא שואל", + "ai.prefs.permission_ask": "לשאול קודם", + "ai.prefs.permission_ask_summary": "שואל על כל שינוי", + "ai.prefs.permission_edits": "לבצע עריכות", + "ai.prefs.permission_edits_summary": "עורך בחופשיות, שואל על השאר", "ai.prefs.permission_scope": "לכלי SolidCraft בלבד. פקודות המעטפת ועריכות הקבצים של הסוכן כפופות להרשאות שלו.", "ai.prefs.pointer_preview_hidden": "הסמן מוסתר", "ai.prefs.pointer_preview_speed": "סמן הסוכן · {speed}", - "ai.prefs.pointer_speed": "מהירות התנועה", + "ai.prefs.pointer_speed": "מהירות", "ai.prefs.privacy_note": "רק הסוכן או נקודת הקצה שבחרת מקבלים את השיחה. מפתחות נקודות הקצה נשמרים במחזיק המפתחות של המערכת.", - "ai.prefs.show_pointer": "הצגת סמן הסוכן", + "ai.prefs.show_pointer": "להציג את מצביע הסוכן", "ai.prefs.turn_limit_hint": "מספר מרבי של קריאות לכלים שמשנים את התכן שהעוזר רשאי לבצע להודעה אחת.", "angle, height": "זווית, גובה", "appearance.dielectric_ior": "מקדם שבירה דיאלקטרי", @@ -785,11 +791,19 @@ "browser.edit_canvas_title": "עריכת קנבס: {name}", "browser.edit_point_cloud_title": "עריכת ענן נקודות: {name}", "browser.move_title": "הזזה: {name}", + "browser.needs_repair": "{name}: דרוש תיקון", "browser.parameters": "פרמטרים ({count})", "browser.precision": "דיוק: {precision}", "browser.sketch_attachment_lost": "{name} (ההצמדה אבדה)", "browser.sketch_editing": "{name} (בעריכה)", "browser.sketch_name": "סקיצה{number}", + "browser.sketches_to_parts_already_in_part": "כבר בחלק שלהם", + "browser.sketches_to_parts_design_body": "על גוף של התכן עצמו", + "browser.sketches_to_parts_moved": "{moved} שרטוטים הועברו לחלק שעליו הם נמצאים", + "browser.sketches_to_parts_no_exact_attachment": "על פאה ללא הצמדה מדויקת", + "browser.sketches_to_parts_not_on_face": "לא על פאה של חלק", + "browser.sketches_to_parts_part_missing": "החלק שלהם כבר לא קיים", + "browser.sketches_to_parts_result": "{moved} שרטוטים הועברו לחלק שעליו הם נמצאים; {stayed} נשארו: {why}", "browser.units": "יחידות: {units}", "cam.flat": "פאה שטוחה", "cam.follower": "עוקב", @@ -819,7 +833,10 @@ "cmd.appearance_pick_up": "בחירת מראה", "cmd.appearance_replace": "החלפת מראה", "cmd.assembly_bom": "רשימת חלקים", + "cmd.assembly_mass_properties": "תכונות מסה", + "cmd.body.print_face": "פאת הדפסה", "cmd.body_rename": "שינוי שם גוף", + "cmd.body_repair": "תיקון חלק", "cmd.browser_collapse_all": "כיווץ הכול", "cmd.browser_expand_all": "הרחבת הכול", "cmd.browser_group": "קבוצה חדשה", @@ -847,6 +864,7 @@ "cmd.component_extract": "חילוץ לקובץ", "cmd.component_finish_edit": "סיום עריכה", "cmd.component_from_bodies": "יצירת רכיבים מגופים", + "cmd.component_hide_history": "הסתר היסטוריית רכיב", "cmd.component_insert_design": "הוספת תכן", "cmd.component_links": "רשימת קישורים", "cmd.component_list": "רשימת רכיבים", @@ -855,6 +873,7 @@ "cmd.component_move_bodies": "העברת גופים לרכיב", "cmd.component_move_features": "העברת פיצ'רים לרכיב", "cmd.component_move_sketches": "העברת סקיצות לרכיב", + "cmd.component_move_sketches_to_parts": "העברת שרטוטים לחלקים שלהם", "cmd.component_paste_from_design": "הדבק מעיצוב אחר", "cmd.component_paste_new": "הדבקה כחדש", "cmd.component_properties": "תכונות פיזיקליות של רכיב", @@ -862,6 +881,7 @@ "cmd.component_rename": "שינוי שם רכיב", "cmd.component_replace_with_link": "החלפה בקישור", "cmd.component_revert_position": "החזרת מיקום", + "cmd.component_show_history": "הצג היסטוריית רכיב", "cmd.component_unlock": "ביטול נעילת התוכן", "cmd.component_update_links": "עדכון קישורים", "cmd.config_activate": "הפעלת תצורה", @@ -872,6 +892,7 @@ "cmd.config_rule": "כלל תצורה", "cmd.config_rules": "כללי תצורה", "cmd.config_table": "הצגת טבלת תצורות", + "cmd.construct.plane.axis_point": "מישור דרך ציר ונקודה", "cmd.construct_axis_edge": "ציר דרך מקצוע", "cmd.construct_axis_normal_to_face": "ציר ניצב לפאה", "cmd.construct_axis_through_cylinder": "ציר דרך גליל/חרוט/טורוס", @@ -900,6 +921,8 @@ "cmd.diagnostics_crash_reports": "דוחות קריסה", "cmd.diagnostics_crash_reports_clear": "מחיקת דוחות קריסה", "cmd.diagnostics_crash_test": "בדיקת קריסה", + "cmd.diagnostics_profile": "פרופיל ביצועים", + "cmd.diagnostics_validation": "אימות", "cmd.doc_recover": "שחזור תכן", "cmd.doc_recovery_discard": "השלכת תכן משוחזר", "cmd.doc_recovery_list": "תכנים לשחזור", @@ -920,6 +943,11 @@ "cmd.explode_show": "הצגת תצוגה מפוצצת", "cmd.expr_evaluate": "חישוב ביטוי", "cmd.face_delete": "מחיקת פאה", + "cmd.file.export_3mf": "ייצוא 3MF", + "cmd.file.export_obj": "ייצוא OBJ", + "cmd.file.export_step": "ייצוא STEP", + "cmd.file.export_stl": "ייצוא STL", + "cmd.file.export_urdf": "ייצוא URDF", "cmd.file_export": "ייצוא", "cmd.file_insert_mesh": "הוספת רשת משולשים", "cmd.file_insert_step": "הוספת STEP", @@ -932,11 +960,13 @@ "cmd.frame_profile_list": "ספריית פרופילים", "cmd.frame_profile_properties": "מאפייני פרופיל", "cmd.inspect_accessibility": "ניתוח נגישות", + "cmd.inspect_analysis": "ניתוח תצוגה", "cmd.inspect_center_of_mass": "מרכז מסה", "cmd.inspect_clearance": "מרווח", "cmd.inspect_colored_components": "הפעלת צבעי רכיבים", "cmd.inspect_colored_components_disable": "ביטול צבעי רכיבים", "cmd.inspect_compare": "השוואת גופים", + "cmd.inspect_compare_picture": "השוואה לתמונת ייחוס", "cmd.inspect_continuity": "ניתוח רציפות", "cmd.inspect_curvature_comb": "ניתוח מסרק עקמומיות", "cmd.inspect_curvature_map": "ניתוח מפת עקמומיות", @@ -954,6 +984,7 @@ "cmd.joint_delete": "מחיקת מפרק", "cmd.joint_drive": "הנעת מפרקים", "cmd.joint_edit": "עריכת מפרק", + "cmd.joint_find_limits": "מציאת גבולות מפרק", "cmd.joint_gear": "גלגל שיניים", "cmd.joint_inspect": "בדיקת מפרק", "cmd.joint_limits": "גבולות מפרק", @@ -966,6 +997,11 @@ "cmd.joint_screw": "בורג", "cmd.joint_solve": "פתרון מפרקים", "cmd.joint_sweep": "סריקת טווח מפרק", + "cmd.layout.apply": "החלת פריסה", + "cmd.layout.get": "בדיקת פריסה", + "cmd.layout.reset": "איפוס פריסה", + "cmd.layout.save": "שמירת פריסה", + "cmd.layout.workspace.select": "בחירת סביבת עבודה לפריסה", "cmd.library_apply": "החלת פריט מהספרייה המקומית", "cmd.library_export": "ייצוא ספריית התכן", "cmd.library_inspect": "בדיקת הספרייה המקומית", @@ -999,6 +1035,21 @@ "cmd.occurrence_move": "הזזת מופע", "cmd.occurrence_properties": "תכונות פיזיקליות של מופע", "cmd.occurrence_reparent": "העברה לרכיב", + "cmd.panel.activate": "הפעלת לשונית חלונית", + "cmd.panel.close": "סגירת חלונית", + "cmd.panel.collapse": "כיווץ מקטע חלונית", + "cmd.panel.dismiss": "סגירת תצוגה זמנית של חלונית", + "cmd.panel.float": "הצפת חלונית", + "cmd.panel.focus": "מיקוד חלונית", + "cmd.panel.list": "הצגת רשימת חלוניות", + "cmd.panel.move": "העברת חלונית", + "cmd.panel.native_close": "עיגון מחדש של מקטע חלונית מחלון נפרד", + "cmd.panel.open": "פתיחת חלונית", + "cmd.panel.peek": "הצגה זמנית של חלונית מכווצת", + "cmd.panel.popout": "העברת חלונית לחלון נפרד", + "cmd.panel.reset_pair": "איפוס מפריד חלוניות", + "cmd.panel.resize": "שינוי גודל מקטע חלונית", + "cmd.panel.resize_pair": "הזזת מפריד חלוניות", "cmd.parameters_add": "הוספת פרמטר משתמש", "cmd.parameters_change": "שינוי פרמטרים", "cmd.parameters_comment": "הערה לפרמטר", @@ -1027,6 +1078,9 @@ "cmd.pointcloud_edit": "עריכת ענן נקודות", "cmd.pointcloud_insert": "הוספת ענן נקודות", "cmd.pointcloud_list": "ענני נקודות", + "cmd.render.compare.divider": "הזז את מחיצת ההשוואה של הרינדור", + "cmd.render.result.discard": "השלך תוצאת רינדור", + "cmd.render.result.select": "בחר תוצאת רינדור", "cmd.render_aging_describe": "הזדקנות משטח בשכבות", "cmd.render_backends": "מנועי הדמיה", "cmd.render_batch": "רינדור כל הצילומים", @@ -1190,6 +1244,7 @@ "cmd.sketch_spline_control_point_5": "ספליין נקודות בקרה (מעלה 5)", "cmd.sketch_spline_fit_point": "ספליין נקודות התאמה", "cmd.sketch_spline_insert_point": "הוספת נקודה לספליין", + "cmd.sketch_spline_remove_point": "הסרת נקודה מהספליין", "cmd.sketch_spline_reverse": "היפוך כיוון הספליין", "cmd.sketch_spun_profile": "פרופיל סיבובי", "cmd.sketch_toggle_diameter": "מעבר בין רדיוס לקוטר", @@ -1240,9 +1295,11 @@ "cmd.timeline_rollback": "הזזת סמן ציר הזמן", "cmd.timeline_stop": "עצירת ציר הזמן", "cmd.timeline_suppress": "השבתת פיצ'ר", + "cmd.ui.assistant": "הצגה או הסתרה של העוזר", "cmd.view.render_browser": "דפדפן רינדור", "cmd.view.render_dock": "הזז את עגינת הרינדור", "cmd.view.render_focus": "תצוגת מיקוד רינדור", + "cmd.view.status_details": "פרטי מצב חלון התצוגה", "cmd.view.status_items": "פריטי מצב תצוגה", "cmd.view_ambient_occlusion": "הצללה סביבתית", "cmd.view_angle_readout": "זוויות תצוגה", @@ -1273,17 +1330,28 @@ "cmd.view_tool": "כלי ניווט", "cmd.view_top": "תצוגה עליונה", "cmd.view_visual_style": "סגנון תצוגה", + "color.blue": "כחול", "color.copy": "לחיצה מעתיקה את ערכי הצבע", "color.edit": "לחיצה לעריכת הצבע", "color.gamma": "ערכי הצבע מוצגים במרחב גמא 0-255", + "color.green": "ירוק", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", "color.hue": "גוון", "color.linear": "ערכי הצבע מוצגים במרחב לינארי 0-1", + "color.recent": "צבעים אחרונים", + "color.recent_help": "צבעים שבוחרים בכל שדה צבע מופיעים כאן", + "color.red": "אדום", + "color.saturation": "רוויה (אחוזים)", "color.saturation_value": "רוויה ובהירות", "color.selected": "הצבע שנבחר", + "color.step_down": "צעד למטה", + "color.step_up": "צעד למעלה", + "color.value": "ערך, הבהירות (אחוזים)", "config.column_filter_empty": "אין עמודות תואמות", + "config.rule_parameter_columns": "מוצגים כאן רק פרמטרים שיש להם עמודה בטבלה. הוסיפו עמודה דרך \"הוספת עמודה\" (+) כדי להשתמש בפרמטר כאן.", + "config.rule_suppression_columns": "מוצגים כאן רק פיצ'רים שיש להם עמודת \"השבתה\" בטבלה. הוסיפו עמודה דרך \"הוספת עמודה\" (+) כדי לשלוט בפיצ'ר כאן.", "contact.components_count": "{count} רכיבים", "contact.enabled_label": "מופעל", "coupling.gear_1": "גלגל שיניים 1", @@ -1318,6 +1386,7 @@ "crash.unclean_explanation": "זוהה בהפעלה מאוחרת יותר; זמן היציאה המדויק לא נרשם. גם כיבוי של המערכת או עצירה בכפייה עלולים לגרום ליציאה לא תקינה.", "delete.and_more": "… ועוד {count}", "diagnostic.empty_boolean_component": "אין גוף להסרה או לחיתוך משותף ברכיב '{component}'; ייתכן שהכלי חופף ל־'{body}' ברכיב '{other}' — יש להפעיל את הרכיב הזה או לבחור את הגוף כיעד", + "diagnostic.reselect_reference": "{feature}: ההפניה `{reference}` כבר אינה קיימת כפי שנבחרה; יש לבחור אותה מחדש", "dialog.bodies_count": "{count} גופים", "dialog.clearance_invalid": "המרווח חייב להיות אורך של 0 ומעלה", "dialog.compute": "חישוב", @@ -1327,11 +1396,20 @@ "dialog.custom_axis": "↖ ציר מותאם", "dialog.dimension_insert_hint": "יש ללחוץ על מידה מניעה אחרת כדי להוסיף את שמה", "dialog.dimension_name": "מידה: {name}", + "dialog.dimension_step_down": "הפחתה ב־{step}", + "dialog.dimension_step_expression": "רק מספר משתנה בצעדים; ביטוי נשאר כפי שנכתב", + "dialog.dimension_step_up": "הוספה של {step}", "dialog.edit_title": "עריכת {title}", "dialog.no_shown_body": "אין גוף מוצג לשינוי: הציגו גוף, או בחרו „גוף חדש”", + "dialog.pattern_sketch_not_object": "בחרו גופים או פיצ'רים: סקיצה אינה אף אחד מהם. חזרו על העקומות שלה בעזרת המערך או השיקוף של הסקיצה עצמה, או בצעו לה שליפה קודם.", "dialog.select": "↖ בחירה", "dialog.selected_count": "↖ {count} נבחרו", + "dialog.selection_constraint": "אילוץ {id}", + "dialog.selection_external_curve": "{sketch} · עקומה {id}", + "dialog.selection_external_point": "{point} · {sketch}", "dialog.selection_guidance": "יש לבחור קלט כדי לשנות אותו. לחיצה על אובייקט שנבחר מסירה אותו; גם Ctrl/Cmd+לחיצה מחליפה את מצבו. לאחר בדיקת התצוגה המקדימה יש ללחוץ על אישור.", + "dialog.selection_midpoint": "נקודת אמצע · {id}", + "dialog.selection_profile": "{sketch} · פרופיל {number}", "dialog.selection_step": "{step} מתוך {total}: בחירת {input}", "dialog.step": "שלב", "document.changed_on_disk": "{name} השתנה בדיסק", @@ -1346,6 +1424,7 @@ "document.read_only_save": "התכן הזה נפתח לקריאה בלבד: יש לשמור אותו כקובץ חדש", "document.save_changes": "לשמור את השינויים ב־{name}?", "document.save_copy": "שמירת עותק…", + "document.tab_unsaved_changes": "שינויים שלא נשמרו", "document.unsaved_changes": "ב־{name} יש שינויים שלא נשמרו. ללא שמירה, הם יאבדו.", "drive.rigid": "{joint} הוא מפרק קשיח: הוא מחזיק את החלקים שלו במקומם, ולכן אין מה להניע. כדי שהחלקים יזוזו, שנו את הסוג שלו ב״עריכת מפרק״: Revolute לסיבוב, Slider להחלקה, Cylindrical לשניהם.", "drive.stopped_by_contact": "נעצר ב־{value}: {a} היה עובר דרך {b}", @@ -1378,6 +1457,14 @@ "file_load.reading_percent": "קורא את הקובץ... {percent}%", "file_load.rebuilding": "בונה מחדש פיצ'ר {done} מתוך {total}", "file_load.recovering": "משחזר את התכן", + "file_load.step_build": "בונה את המודל", + "file_load.step_feature": "תכונה {done} מתוך {total}", + "file_load.step_part": "חלק {done} מתוך {total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "קורא את הקובץ", + "file_load.step_rebuild": "בונה מחדש את התכונות", + "file_load.step_repair": "בודק ומתקן את החלקים", + "file_load.step_show": "מכין את התצוגה", "file_load.stopping": "ממתין לעצירת הפעולה הקודמת...", "file_load.updating_links": "עדכון קישורים", "file_load.waiting": "ממתין לפעולת קובץ", @@ -1386,21 +1473,189 @@ "from the rule": "לפי הכלל", "help.apache": "רישיון Apache 2.0", "help.appearance.assign": "מתן צבע או מראה של חומר לגופים, לפאות או לרכיבים שנבחרו, בלי לשנות את משקלם. מתאים להבחנה בין חלקים או לתצוגה מקדימה של גימור.", + "help.assembly.bom": "רישום חלקי התכן או הרכיב עם הכמויות שלהם לפי מק״ט, עם אפשרות לשמור את הרשימה כ־CSV או JSON. משמש כרשימת חלקים להזמנה ולהרכבה.", "help.attributions": "ייחוסים (ATTRIBUTION.md)", "help.build": "גרסה {version} · קומיט {commit} · נבנתה ב־{date}", + "help.canvas.decal": "הנחת תמונה על פאה מישורית של המודל, כמו מדבקה. מתאים להצגת תווית, לוגו או דוגמה מודפסת על חלק.", + "help.canvas.edit": "שינוי קנבס: מיקום, גודל, זווית, אטימות, שיקוף, נראות או שם. כך מיישרים תמונת ייחוס עם הסקיצה שמשרטטים מעליה.", + "help.canvas.insert": "הנחת תמונת PNG או JPEG על מישור או פאה כייחוס שקוף למחצה. כך מעתיקים קווי מתאר מתצלום או מציור לסקיצה, כשהתמונה מותאמת למידה ידועה.", + "help.component.break_link": "ניתוק רכיב מקושר מקובץ התכן שלו, תוך השארת הגופים כפי שהם. מתאים כשהחלק אינו אמור עוד להתעדכן בעקבות שינויים בקובץ המקורי.", + "help.component.capture_position": "שמירת המיקומים של חלקים שהוזזו ידנית כמיקומים הקבועים שלהם. מתאים לאחר גרירת חלקים למקומם כשאין מפרק שמחזיק אותם.", + "help.component.create": "הוספת רכיב חדש וריק לתכן, בתוך הרכיב הפעיל אלא אם נבחר רכיב אב אחר. כך מקצים לחלק חדש בהרכבה מקום משלו לגופים ולסקיצות.", "help.component.finish_edit": "שומר את החלק שנערך במקומו, חוזר להרכבה שלו ומעדכן ממנו את ההרכבה. יש להשתמש בו כשהשינויים בחלק המקושר הושלמו.", + "help.component.from_bodies": "הפיכת כל גוף שנבחר לרכיב נפרד שנקרא על שם הגוף. מתאים להפיכת תכן של גופים נפרדים להרכבה שחלקיה ניתנים לחיבור ולהזזה.", + "help.component.insert_design": "הוספת תכן שמור אחר כרכיב מקושר לקובץ שלו, כשהגופים המוצקים ממוקמים כפי שהם בו. כך משתמשים שוב בחלק בהרכבה ומקבלים שינויים מאוחרים יותר באמצעות עדכון קישורים.", + "help.component.properties": "הצגת הנפח, המסה, מרכז המסה ומומנטי האינרציה של רכיב, לפי החומרים של הגופים שבו. מתאים לבדיקת המשקל והאיזון של הרכבה.", + "help.component.revert_position": "החזרת חלקים שהוזזו ידנית למיקומם הקודם וביטול הזזות שמיקומן לא נלכד. כך מבטלים הזזות ניסיוניות בהרכבה.", + "help.component.update_links": "קריאה מחדש של קובצי התכן המקושרים והחלפת גופים שהשתנו. מתאים לאחר עריכת חלק שמשמש בהרכבה זו.", + "help.config.configure": "הוספת פרמטרים, פיצ'רים, חומרים או מראות כעמודות בטבלת התצורות. כך בונים גרסאות של תכן אחד, למשל מידות שונות של חלק.", + "help.config.preview": "בדיקה שאחת משורות טבלת התצורות נבנית מחדש, בלי לשנות את התכן או את ההיסטוריה שלו. מתאים לפני מעבר לגרסה שאינך בטוח בה.", + "help.config.rules": "הצגת הכללים של טבלת התצורות, השורות שלה והשורה הפעילה. כך רואים איך מוגדרות הגרסאות של התכן.", + "help.config.table": "הצגת טבלת התצורות: שורה לכל גרסה, עמודה לכל פרמטר או פיצ'ר, ואם התכן עדיין תואם לשורה הפעילה. מתאים לסקירת הגרסאות של התכן.", "help.connect_note": "יש להפעיל מחדש כל עוזר כדי לטעון את שרת SolidCraft. לכל קובץ נשמר גיבוי בסיומת .bak לפני השינוי.", "help.connect_title": "חיבור עוזרי בינה מלאכותית", + "help.construct.axis.edge": "יצירת ציר עזר לאורך מקצוע ישר או קו של סקיצה. משמש כציר לסיבוב, לשכפול מעגלי או למפרק.", + "help.construct.axis.normal_to_face": "יצירת ציר עזר דרך נקודה, ניצב לפאה. משמש כציר שיוצא ישר מתוך משטח.", + "help.construct.axis.through_cylinder": "יצירת ציר עזר דרך מרכז פאה של גליל, חרוט או טורוס, או מקצוע עגול. מתאים לסיבוב או לשכפול פיצ'רים סביב חלק עגול.", + "help.construct.axis.two_planes": "יצירת ציר עזר במפגש של שני מישורים או שתי פאות שטוחות. מתאים כשהציר הדרוש הוא הקו שבין שתי פאות.", + "help.construct.axis.two_points": "יצירת ציר עזר דרך שתי נקודות, קודקודים או נקודות סקיצה. מתאים לציר שעובר בין שני מיקומים ידועים.", + "help.construct.plane.along_path": "יצירת מישור עזר ניצב למקצוע או לעקומה, במיקום לאורכם. משמש לשרטוט פרופיל לסחיפה או חתך של מסלול.", + "help.construct.plane.at_angle": "יצירת מישור עזר מוטה בזווית ממישור או מפאה, סביב ציר או מקצוע. מתאים לסקיצות משופעות, כמו תמוכה בזווית.", + "help.construct.plane.axis_point": "יוצר מישור עזר המכיל ציר ונקודה שאינה עליו. יש לבחור ציר ראשי או ציר עזר, קצה ישר או קו סקיצה, ואז קודקוד, נקודת סקיצה או נקודת עזר. נקודה על הציר אינה מגדירה מישור יחיד.", + "help.construct.plane.midplane": "יצירת מישור עזר באמצע בין שני מישורים או פאות שטוחות, או חוצה אותם במקום שבו הם נפגשים בזווית. משמש כמישור סימטריה לשיקוף.", + "help.construct.plane.offset": "יצירת מישור עזר מקביל למישור או לפאה שטוחה, במרחק נתון או דרך נקודה. מתאים לשרטוט בגובה קבוע מעל פאה.", + "help.construct.plane.perpendicular": "יצירת מישור עזר שמכיל קו או מקצוע וניצב למישור או לפאה. מתאים לשרטוט זקוף על המודל לאורך מקצוע.", + "help.construct.plane.tangent": "יצירת מישור עזר שמשיק לגליל, לחרוט, לכדור או לטורוס בנקודה. מתאים לשרטוט על צידו של חלק עגול.", + "help.construct.plane.three_points": "יצירת מישור עזר דרך שלוש נקודות. מתאים למישור שנקבע לפי מיקומים על המודל, כמו שלוש פינות.", + "help.construct.plane.two_edges": "יצירת מישור עזר דרך שני מקצועות ישרים או קווים הנמצאים באותו מישור. מתאים למישור שחותך חלק, למשל דרך שני מקצועות מנוגדים.", + "help.construct.point.along_path": "יצירת נקודת עזר במיקום לאורך מקצוע או עקומה. משמשת כנקודת ייחוס בחלק כלשהו של המסלול.", + "help.construct.point.center": "יצירת נקודת עזר במרכז של מקצוע עגול, מעגל או קשת בסקיצה, כדור או טורוס. משמשת כנקודת ייחוס לחורים, לצירים ולמפרקים.", + "help.construct.point.edge_plane": "יצירת נקודת עזר במקום שבו מקצוע או קו חוצים מישור או פאה שטוחה. משמשת לסימון המקום שבו מסלול חוצה מישור.", + "help.construct.point.three_planes": "יצירת נקודת עזר במפגש של שלושה מישורים או פאות שטוחות. משמשת כנקודת ייחוס לפינה, גם כשאין במודל קודקוד.", + "help.construct.point.two_edges": "יצירת נקודת עזר במפגש של שני מקצועות או קווים, או במקום שבו הם הכי קרובים. משמשת כנקודת ייחוס בפינה וירטואלית.", + "help.construct.point.vertex": "יצירת נקודת עזר על קודקוד או נקודת סקיצה. משמשת כנקודת ייחוס שנשארת גם כשהסקיצה או הגוף שסביבה מוסתרים.", + "help.contact.check": "הצגת זוגות החלקים בקבוצות מגע שחודרים זה לזה במיקומם הנוכחי. כך מוצאים התנגשויות לפני הנעת מפרקים או הפעלת חקר תנועה.", + "help.contact.create": "קיבוץ שני חלקים או יותר לקבוצת מגע, שמונעת מגופיהם לחדור זה לזה בזמן תנועת המפרקים. מתאים לחלקים שצריכים לעצור כשהם נוגעים זה בזה, כגון מנוף כנגד המעצור שלו.", + "help.contact.disable_all": "ביטול המגע, כך שמפרקים מונעים וחקר תנועה אינם נעצרים עוד במקום שבו החלקים נוגעים. כך מזיזים שוב חלקים בחופשיות או שומרים על תגובתיות של הרכבה גדולה.", + "help.contact.edit": "שינוי קבוצת מגע: החלקים שבה, שמה או מצב ההשבתה שלה, עם אפשרות גם למחוק אותה. כך משנים אילו חלקים מנועים מלחדור זה לזה.", + "help.contact.enable_all": "הכנסת כל חלקי ההרכבה לקבוצת מגע אחת, כך ששום שני חלקים אינם יכולים לחדור זה לזה בזמן תנועת המפרקים. מתאים לבדיקה מהירה של מנגנון שלם.", + "help.contact.enable_sets": "הפעלת מגע לקבוצות המגע שהוגדרו, כך שמפרקים מונעים וחקר תנועה נעצרים במקום שבו חלקיהן היו חודרים זה לזה. כך מפעילים שוב את הקבוצות לאחר ביטול המגע.", + "help.contact.list": "הצגת קבוצות המגע בתכן, החלקים בכל קבוצה והאם המגע פעיל. כך בודקים את הגדרת המגע לפני הנעת ההרכבה.", + "help.document.inspect": "הצגת סקירה של התכן: הרכיבים, הגופים, הסקיצות, הפיצ'רים והפרמטרים שבו. מתאים כדי להתמצא בתכן שלא בנית בעצמך.", + "help.document.units": "שינוי היחידות שבהן מוצגים אורכים בתכן, כמו mm או אינצ'ים. הגיאומטריה נשארת באותו גודל; רק התצוגה והמספרים הפשוטים משתנים.", + "help.edit.checkpoint": "שמירת התכן, הסקיצה הפעילה והיסטוריית הביטולים כפי שהם עכשיו. מתאים לפני ניסיון מסוכן שאולי תרצה לחזור ממנו.", + "help.edit.restore_checkpoint": "חזרה לנקודת שמירה, כולל היסטוריית הביטולים. מתאים כדי לבטל בצעד אחד את כל מה שנעשה מאז נקודת השמירה.", + "help.explode.create": "יצירת תצוגה מפוצצת שמרחיקה את החלקים ממרכז ההרכבה או מזיזה אותם לפי ההזזות שנקבעו. כך מציגים כיצד מרכיבים את החלקים, לצורך הוראות או מצגות.", "help.face.delete": "מחיקת הפאות שנבחרו, כשהפאות השכנות סוגרות את הפער, או השארת הפתח פתוח כמשטח. מתאים להסרת עיגול, חור או בליטה שמפריעים.", + "help.file.insert_mesh": "הוספת קובץ 3MF, STL, OBJ, PLY או glTF לתכן כגופי רשת משולשים ברכיב חדש. כך ממקמים מודל שהורד או נסרק לצד התכן כייחוס.", + "help.file.insert_step": "הוספת קובץ STEP, IGES, FreeCAD או Rhino לתכן כגופים מוצקים ברכיב חדש, כשחלקי הרכבה הופכים לרכיבים מקוננים. כך מייבאים מודלים מספקים או מתוכנות CAD אחרות.", + "help.file.save_mesh": "שמירת גופים כרשת משולשים מסוג STL, 3MF או OBJ, עם רמת החלקות שנבחרה לפאות מעוקלות. כך מכינים חלקים להדפסת תלת־ממד או לתוכנות שקוראות רשתות משולשים.", + "help.file.send_to_slicer": "שמירת הגופים שנבחרו כקובץ 3MF ופתיחתו בסלייסר שנבחר. כך עוברים מהמודל להדפסה בצעד אחד.", "help.font_details": "הממשק משתמש בגופנים המובנים של egui (Ubuntu Light ו־Hack, תחת Ubuntu Font Licence ותחת רישיון MIT/Bitstream Vera; Noto Emoji וגופן סמלי האימוג'י, תחת OFL ו־MIT). טקסט בסקיצות משתמש ב־Liberation Sans (SIL OFL 1.1). חבילת הגופנים האופציונלית של Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), אינה כלולה בגרסאות של SolidCraft.", "help.fonts": "גופנים", + "help.frame.member": "הצבת פרופיל, כמו צינור או פרופיל אלומיניום שחול, לאורך קווי סקיצה של מסגרת, איבר אחד לכל קו. מתאים לבניית מסגרות, מדפים ומבנים מולחמים.", + "help.inspect.accessibility": "צביעת הפאות שכלי יכול להגיע אליהן מכיוון אחד, ואלה שאינו יכול. מתאים לבדיקת חלק לעיבוד שבבי או להזרקה מאותו צד.", + "help.inspect.center_of_mass": "הצגת מרכז המסה של גופים, כל אחד לחוד וכולם יחד, בצפיפות אחידה. מתאים לבדיקת איזון ולזיהוי המקום שבו חלק יתהפך.", + "help.inspect.colored_components": "מתן צבע זמני נפרד לכל רכיב, בלי לשנות את המראות. מתאים להבחנה במבט אחד בין חלקי ההרכבה.", + "help.inspect.compare": "השוואה בין שני גופים והצגת המקומות שבהם לאחד יש חומר שאין לשני, עם נפח וסטייה. מתאים לבדיקת חלק ששונה או יובא מול המקור.", + "help.inspect.continuity": "בדיקה עד כמה חלק המפגש בין פאות לאורך המקצועות: רווחים, שברים או קפיצות בעקמומיות, וצביעת התפרים. מתאים לאיתור מקומות שבהם משטחים לא מתחברים בצורה נקייה.", + "help.inspect.curvature_comb": "שרטוט מסרקים על עקומות, מקצועות או פאות, ושיניהם מראות עד כמה הם מתעקלים. מתאים לאיתור אזורים שטוחים, שברים ועקמומיות לא אחידה.", + "help.inspect.curvature_map": "צביעת פאות לפי עוצמת העקמומיות שלהן, באדום היכן שהרדיוס קטן. מתאים לאיתור נקודות חדות ולהערכת חלקות המשטח.", + "help.inspect.draft": "צביעת פאות לפי זווית השיפוע שלהן ביחס לכיוון ההוצאה מהתבנית, וסימון אלה שהשיפוע שלהן קטן מדי. מתאים לבדיקת חלק לפני הזרקה או יציקה.", + "help.inspect.environment_map": "הצגת המודל בגימור מחזיר אור, כמו מראה. מתאים להערכת הזרימה של משטחים לפי הדרך שבה ההשתקפויות עוברות עליהם.", + "help.inspect.interference": "איתור גופים שחופפים והצגת כל חפיפה עם נפחה. מתאים לבדיקת הרכבה כדי למצוא חלקים שמתנגשים.", + "help.inspect.isocurve": "שרטוט האיזו־עקומות של פאות, הרשת שעליה בנוי המשטח. מתאים כדי לראות איך המשטח זורם והיכן הקווים מצטופפים.", + "help.inspect.measure": "מדידת אורכים, מרחקים, זוויות, שטחים ורדיוסים בין מה שנבחר, או נפח ומסה של גופים. מתאים לבדיקת מידות ומרווחים.", + "help.inspect.minimum_radius": "איתור רדיוס העקמומיות הקטן ביותר של עקומות, מקצועות או פאות, והמקום שבו הוא נמצא. מתאים לוודא שכלי או נחיר יכולים לעקוב אחרי הצורה.", + "help.inspect.section": "חיתוך התצוגה לאורך מישור וקווקו הפאות החתוכות, בלי לשנות את המודל. מתאים להצצה לתוך חלקים והרכבות.", + "help.inspect.zebra": "הצגת פסים שחורים ולבנים המשתקפים על פאות המודל. מתאים להערכת חלקות: פסים שנקטעים או נשברים במקצוע מעידים על מעבר גרוע.", + "help.joint.as_built": "חיבור שני חלקים במיקומם הנוכחי, ללא הזזת אף אחד מהם, והגדרת התנועה שעדיין מותרת להם. מתאים לחלקים שכבר מוקמו במיקומם הסופי.", + "help.joint.cam": "קישור פיקה מסתובבת לעוקב, כך שהעוקב מחליק או מתנדנד כשקו המתאר של הפיקה עובר מתחתיו. מתאים לפיקות, לאקסצנטרים ולמנגנוני הנעת שסתומים.", + "help.joint.create": "חיבור שני חלקים בראשיות המפרק שנבחרו והזזת החלק השני למקומו, כשסוג המפרק קובע את התנועה שעדיין מותרת להם. כך בונים הרכבה שחלקיה נעים כמו במנגנון האמיתי.", + "help.joint.drive": "קביעת הזווית או המרחק של מפרק והזזת החלקים איתו בתוך גבולותיו, תוך מעקב של מפרקים מקושרים ולולאות סגורות. כך בודקים שהמנגנון נע כמתוכנן.", + "help.joint.gear": "קישור שני מפרקים מסתובבים ביחס תמסורת, כך שהנעת אחד מסובבת את האחר. מתאים לגלגלי שיניים ישרים וטבעתיים, עם יחס לפי רדיוסי מעגלי החלוקה או מספרי השיניים.", + "help.joint.limits": "קביעת גבולות מינימום ומקסימום לסיבוב או להחלקה של מפרק, או הסרת הגבולות. כך שומרים ציר, מחליק או מנוף בתוך טווח התנועה האמיתי שלו.", + "help.joint.motion_link": "צימוד שני מפרקים ביחס ובהיסט, כך שהנעת אחד מזיזה את האחר. מתאים ליחס קבוע בין מפרקים שהכלים גלגל שיניים, מסרק וגלגל שיניים או בורג אינם מכסים.", + "help.joint.origin": "הנחת ראשית מפרק בעלת שם על חלק: במרכז פאה או קצה עגול, באמצע מקצוע, בפינה או בנקודה. כך מכינים את מיקומי חיבור המפרקים, וראשית שנבחרה על פאה עוקבת אחריה כשגודל החלק משתנה.", + "help.joint.rack_pinion": "קישור גלגל שיניים מסתובב למסרק מחליק, כך שהמסרק נע באורך הקשת שגלגל השיניים עובר על מעגל החלוקה. מתאים להנעות מסרק, למנגנוני היגוי ולבמות תנועה קוויות.", + "help.joint.reach": "הזזת נקודה על חלק לעבר יעד על ידי שינוי המפרקים בשרשרת שלה, בתוך גבולותיהם. כך קובעים תנוחה של מנגנון לפי המיקום הרצוי של קצהו, כגון קצה זרוע רובוט.", + "help.joint.rigid_group": "נעילת החלקים שנבחרו יחד כפי שהם, כך שינועו כיחידה אחת. מתאים לחלקים השייכים יחד ואינם נעים זה ביחס לזה.", + "help.joint.screw": "קישור סיבוב והחלקה לפי פסיעה, כך שכל סיבוב מקדם באותו מרחק. מתאים לבורגי הנעה, לברגים ולכושים בעלי תבריג.", + "help.layout.apply": "החלת פריסה שמורה על סביבת העבודה הנוכחית. העורכים הקיימים שומרים על הטיוטות שלהם.", + "help.layout.get": "קריאת הפריסה שאושרה והצגת סביבות העבודה הרשומות.", + "help.layout.reset": "שחזור פריסת ברירת המחדל הרשומה של סביבת העבודה הנוכחית. הגדרות המשתמש השמורות נשארות זמינות.", + "help.layout.save": "שמירת הפריסה המלאה בשם. החלפת הגדרה שמורה של משתמש מחייבת הרשאה מפורשת לדריסה.", + "help.layout.workspace.select": "בחירת סביבת עבודה רשומה לפריסה ושמירת הפריסה שממנה יוצאים.", + "help.library.apply": "החלת חומר או מראה מקובץ ספרייה מקומי על גופים, פאות או רכיבים. מתאים לשימוש חוזר בחומרים ששמרת מתכן אחר.", + "help.library.export": "שמירת החומרים והמראות של התכן בקובץ ספרייה. מתאים לשיתוף או לשימוש חוזר בתכן אחר.", + "help.library.inspect": "בדיקת קובץ ספרייה והצגת החומרים והמראות שבו, בלי לשנות את התכן. מתאים כדי לראות מה הספרייה מכילה לפני החלתה.", "help.licences": "רישיונות", "help.material.assign": "קביעת החומר שממנו עשויים הגופים שנבחרו, למשל פלדה, אלומיניום או ABS. כך המסה והמשקל תואמים את החלק האמיתי.", + "help.material.properties.validate": "בדיקת כרטיס נתונים של חומר לאיתור מספרים לא עקביים וערכים חסרים. מתאים לפני הסתמכות על הנתונים לחישוב מסה או קשיחות.", + "help.mesh.convert": "בנייה מחדש של גוף רשת, כמו STL, כגוף מוצק הניתן לעריכה עם פאות שטוחות וגליליות. מתאים לעריכת חלקים מכניים שיובאו כמו גוף שעוצב מאפס.", "help.mit": "רישיון MIT", + "help.motion.study": "קביעת ערכי מפרקים בשלבים לאורך ציר זמן והפעלתם כהנפשה. כך צופים ברצף תנועות של מנגנון ובודקים מרווחים לאורך הדרך.", + "help.motion.trace": "מעקב אחר המסלול של נקודה על חלק בזמן חקר תנועה או הנעת מפרק, ושמירתו כעקומת סקיצה תלת־ממדית לאחר האישור. כך רואים לאן מנגנון מגיע או בונים על בסיס מסלולו.", "help.notice": "NOTICE", + "help.occurrence.ground": "עיגון חלק במקומו או שחרורו מחדש, כך שהמפרקים מניעים את החלקים האחרים סביבו. מתאים למסגרת או לבסיס שעליהם נבנית שאר ההרכבה.", "help.occurrence.move": "מזיז חלק בהרכבה רק בכיוונים שהמפרקים שלו מאפשרים. בחרו פאה של החלק, ואז גררו חץ או קשת זמינים.", + "help.panel.activate": "בחירת לשונית חלונית פתוחה בלי לבקש מיקוד מקלדת.", + "help.panel.close": "סגירת חלונית דרך בדיקת מחזור החיים של התוכן שלה. המיקום שלה נשמר.", + "help.panel.collapse": "כיווץ או הרחבה של מקטע חלונית תוך שמירת המידות המבוקשות.", + "help.panel.dismiss": "סגירת התצוגה הזמנית של חלונית מכווצת.", + "help.panel.float": "העברת חלונית למקטע צף שמיקומו מוגדר במפורש.", + "help.panel.focus": "מיקוד חלונית, פתיחה מחדש של מצבה השמור והרחבת המקטע שלה לפי הצורך.", + "help.panel.list": "קריאת סוגי החלוניות הרשומים, המופעים שאושרו, הלשוניות הפעילות, הזמינות ויכולות המארח.", + "help.panel.move": "העברת חלונית למקטע חדש או צירופה לקבוצת לשוניות קיימת.", + "help.panel.native_close": "החזרת מקטע חלונית מחלון נפרד למיקום העיגון השמור בלי לבטל את התוכן שלו.", + "help.panel.open": "פתיחת סוג חלונית עם מזהה מופע מפורש. מופע חדש דורש מיקום.", + "help.panel.peek": "הצגה זמנית של חלונית מכווצת בלי לשנות את הגודל השמור או את מצב הכיווץ שלה.", + "help.panel.popout": "העברת חלונית לחלון נפרד כאשר יש תמיכה בכך. במארח דפדפן נעשה שימוש במקטע צף.", + "help.panel.reset_pair": "שחזור יחס הגדלים המוגדר כברירת מחדל לשני מקטעי עיגון סמוכים, במסגרת הגבולות המשותפים שלהם.", + "help.panel.resize": "הגדרת הרוחב והגובה החיצוניים של מקטע חלונית במסגרת המגבלות של כל הלשוניות.", + "help.panel.resize_pair": "שינוי גודלם של מקטעי עיגון סמוכים יחד תוך שמירה על האורך הכולל המשותף שלהם.", "help.parameters.change": "פתיחת הטבלה של ערכים בעלי שם וביטויים שקובעים את מידות התכנון. כך משנים מידה במקום אחד וכל הפיצ'רים שמשתמשים בה מתעדכנים.", + "help.parameters.export": "שמירת הפרמטרים של התכן כ־CSV או JSON. מתאים לעריכתם בגיליון אלקטרוני או להעברתם לתכן אחר.", + "help.parameters.graph": "הצגת אילו פרמטרים ופיצ'רים משתמשים באילו אחרים, ואילו לולאות או שגיאות יש ביניהם. מתאים כדי לראות על מה ישפיע שינוי בפרמטר.", + "help.parameters.import": "קריאת פרמטרים מ־CSV או JSON אל התכן, כולם או אף אחד. מתאים להבאת ערכים מגיליון אלקטרוני או מתכן אחר.", + "help.parameters.move": "הזזת פרמטר משתמש לפני פרמטר אחר או אחריו ברשימה. מתאים כדי לשמור פרמטרים קשורים יחד.", + "help.parts.fastener": "הוספת בורג, בורג עם אום, אום, דסקית, פין או מיסב סטנדרטיים בגודל שנבחר. בהנחה על חור, המחבר מתיישב בו עם מפרק, וכך אין צורך למדל מחברים בעצמכם.", + "help.parts.insert": "הוספת חלק סטנדרטי מהמשפחה, בגודל ובאורך שנבחרו. בהנחה על שפת חור או על דופנו, החלק מתיישב על החור עם מפרק קשיח.", + "help.parts.library": "פתיחת החלקים הסטנדרטיים: ברגים, ברגים עם אומים, אומים, דסקיות, בורגי קיבוע, פיני מיקום ומיסבים במידות סטנדרטיות. כך מוסיפים חלק סטנדרטי במקום למדל אותו בעצמכם.", + "help.parts.resize": "שינוי הגודל או האורך של חלק סטנדרטי שהוכנס ובנייתו מחדש, כשהמפרקים שומרים אותו במקומו. מתאים כשבורג מתגלה כארוך מדי או כשחור דורש מידה אחרת.", + "help.plastic.assign_rule": "הקצאת כלל פלסטיק לגופים, כך שפיצ'רי הפלסטיק שלהם יקבלו ממנו שיפוע ומרווח כברירת מחדל. מתאים כדי להגדיר חלק מוזרק פעם אחת לכל הפיצ'רים שלו.", + "help.plastic.boss": "הוספת בליטה לבורג על פאה: עמוד עם חור אופציונלי, שיפוע, עיגול פינה בבסיס וצלעות תמיכה. מתאים לנקודות בורג בבתים מוזרקים או מודפסים.", + "help.plastic.lip": "הוספת שפה או חריץ תואם לאורך שפת גוף חלול. מתאים כדי ששני חצאי בית יתמקמו זה על זה וייסגרו היטב.", + "help.plastic.manage_rules": "יצירה ועריכה של כללי פלסטיק: חומר, עובי דופן, רדיוסים, מרווח ושיפוע. מתאים כדי לשמור על עקביות הפיצ'רים של חלק מוזרק.", + "help.plastic.rest": "הוספת משען על פאה: כרית עגולה או מלבנית, מלאה או חלולה, עם שיפוע. משמש כתמיכה או כדוכן מרווח בבית מוזרק.", + "help.plastic.snap_fit": "הוספת וו הצמדה על פאה, עם אורכו, עוביו והבליטה הנועלת. מתאים לחיבור חלקים בלחיצה בלי ברגים.", "help.pointcloud.insert": "הוספת סריקה בפורמט PLY, XYZ או PTS כענן נקודות לצד המודל. משמש כעזר למידול על סמך נתוני מדידה.", + "help.sheet.convert": "הפיכת לוח או גוף חלול בעובי אחיד לגוף פח, עם כיפופים במקצועות שנבחרו. מתאים כדי להפוך חלק קיים לבר־פריסה.", + "help.sheet.export_bend_table": "שמירת טבלת הכיפופים של גוף פח כ־CSV או JSON: זוויות, רדיוסים ומיקומי כיפוף בפריסה. מתאים למכונת הכיפוף או לסדנה.", + "help.sheet.export_dxf": "שמירת הפריסה כ־DXF, עם קווי מתאר, קווי כיפוף והערות כיפוף אופציונליות. מתאים לחיתוך בלייזר, בפלזמה או בסילון מים.", + "help.sheet.flange": "הוספת אוגן: לוח בסיס מסקיצה, דופן לאורך קו מתאר פתוח של סקיצה, או דופן מכופפת על מקצועות הפח. מתאים לבניית חלקי פח.", + "help.sheet.flat_pattern": "יצירת הפריסה של גוף פח, עם הגודל, החיתוכים וקווי הכיפוף. מתאים לבדיקת הפח הפרוס לפני החיתוך.", + "help.sheet.fold": "כיפוף פח לאורך קו סקיצה בזווית וברדיוס שנקבעו. מתאים לקיפול פח שטוח אחרי שנוספו בו חיתוכים.", + "help.sheet.hem": "קיפול שפת פח חזרה על עצמה. מתאים לשפות בטוחות וקשיחות, בלי קצוות חדים.", + "help.sheet.manage_rules": "יצירה ועריכה של כללי פח: עובי, רדיוס כיפוף, K-factor, חריצי הקלה ורווחים. מתאים כדי להתאים לחומר ולכלים של הסדנה שלך.", + "help.sheet.path_flange": "הוספת שרשרת אוגנים לאורך שפת פח, לפי שרשרת פתוחה של קווי סקיצה. מתאים לפרופילים כמו צורת U או Z בצעד אחד.", + "help.sheet.perforate": "הוספת שדה של חורים על כל הפח הפרוס, בתבנית מוסטת או מרובעת. מתאים לפתחי אוורור, לרשתות ולפאנלים קלים יותר.", + "help.sheet.refold": "קיפול חוזר של גוף פח שנפתח. מתאים אחרי הוספת פיצ'רים לפח הפרוס.", + "help.sheet.unfold": "פתיחת כל הכיפופים של גוף פח. מתאים להוספת חורים או חיתוכים שחייבים לעבור דרך כיפוף, ואז קיפול מחדש.", + "help.sketch.arc.center_point": "משרטט קשת מעגלית סביב נקודת מרכז, מנקודת התחלה לנקודת סיום. מתאים כשמרכז הקשת ידוע, למשל רדיוס סביב חור או ציר.", + "help.sketch.arc.tangent": "משרטט קשת שמתחילה בקצה של ישר או קשת וממשיכה משיקה לו. מתאים להמשכת שרשרת בעיקול חלק במקום בפינה.", + "help.sketch.arc.three_point": "משרטט קשת מנקודת התחלה לנקודת סיום דרך נקודה שלישית. מתאים כשהקשת חייבת לעבור בנקודות נתונות ולא סביב מרכז ידוע.", + "help.sketch.arc3d": "משרטט קשת מעגלית מדויקת במרחב דרך שלוש נקודות, כשסקיצה תלת־ממדית פעילה. מתאים לעיקולים במסלולים ובמסילות הנחיה שיוצאים ממישור הסקיצה.", + "help.sketch.auto_constrain": "מוסיף את האילוצים שהסקיצה כמעט מקיימת ממילא, כמו אופקי, מקביל או מתלכד, ואז מוסיף מידות עד שהיא מוגדרת במלואה. מתאים לנעילת סקיצה גסה בצעד אחד.", + "help.sketch.auto_constrain_from_datum": "פועל כמו אילוץ אוטומטי, אך מודד את המיקומים מנקודת ייחוס שבחרתם ולא מהראשית. מתאים כשהחלק מתוכנן מנקודת ייחוס אחת, כמו פינה או חור.", + "help.sketch.blend_curve": "מחבר את הקצוות של שתי עקומות בספליין חלק המשיק לשתיהן, או גם רציף עקמומיות אם בוחרים. מתאים לגישור על פער בין עקומות בלי שבר.", + "help.sketch.break": "מפצל עקומה לחלקים במקומות שבהם עקומות אחרות חוצות אותה, או בנקודות שמניחים עליה. מתאים כשחלק מהעקומה צריך אילוץ משלו או צריך להימחק לבדו.", + "help.sketch.cancel": "יוצא מהסקיצה ומבטל כל מה ששונה בה מאז שנוצרה או נפתחה לעריכה. ביטול הפעולה מחזיר את השינויים.", + "help.sketch.centerline": "מחליף ישרים בין ישרים רגילים לקווי מרכז, שהפרופילים מתעלמים מהם. השתמשו בקו מרכז כציר לסיבוב, לשיקוף או לאילוץ סימטריה.", + "help.sketch.chamfer.distance_angle": "יוצר פאזה בפינה בין שני ישרים לפי מרחק לאורך הישר הראשון וזווית. מתאים כשהשרטוט נותן את הפאזה כאורך וזווית, כמו 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "יוצר פאזה בפינה בין שני ישרים באותו מרחק לאורך שניהם. מתאים לפאזת 45° הרגילה בקו מתאר.", + "help.sketch.chamfer.two_distance": "יוצר פאזה בפינה בין שני ישרים לפי מרחק נפרד לאורך כל ישר. מתאים לפאזות שאינן של 45°, הנתונות בשני אורכים.", + "help.sketch.circle.center": "משרטט מעגל לפי מרכזו וקוטרו. מתאים לחורים, לבליטות ולמאפיינים עגולים אחרים שמרכזם ידוע.", + "help.sketch.circle.three_point": "משרטט מעגל העובר בשלוש נקודות. מתאים כשהמעגל חייב לעבור בנקודות נתונות, למשל של גאומטריה קיימת.", + "help.sketch.circle.three_tangent": "משרטט מעגל המשיק לשלושה ישרים, מעגלים או קשתות. מתאים להכנסת מעגל לחלל שבין שלוש עקומות, כמו המעגל החסום במשולש.", + "help.sketch.circle.two_point": "משרטט מעגל משני קצות הקוטר שלו. מתאים כשנקודות הקצה של המעגל ידועות ולא מרכזו.", + "help.sketch.circle.two_tangent": "משרטט מעגל בגודל נתון המשיק לשני ישרים, מעגלים או קשתות. מתאים לעיגול ברדיוס קבוע בין שתי עקומות.", + "help.sketch.conic": "משרטט עקומת חתך חרוט בין שתי נקודות קצה, שצורתה נקבעת לפי נקודת קדקוד וערך rho. מתאים למעברים חלקים שמכוונים את מלאותם, משטוח ועד כמעט פינה חדה.", + "help.sketch.constrainer": "מחיל את האילוץ שעקומה אחת או שתיים שנבחרו כמעט מקיימות, כמו אופקי, מקביל, משיק או שווה. מתאים לסידור סקיצה שנוצרה ביד, יחס אחד בכל פעם.", + "help.sketch.constraint.coincident": "גורם לנקודה להתלכד עם נקודה אחרת, עם עקומה או עם ציר הסקיצה. מתאים לסגירת פערים בפרופיל או להנחת נקודה על ישר.", + "help.sketch.constraint.collinear": "גורם לשני ישרים לשכב על ישר אחד. מתאים ליישור קצוות מקוטעים, כמו שני צדי מגרעת.", + "help.sketch.constraint.concentric": "מעניק לשני מעגלים או קשתות מרכז משותף, או ממקם את מרכזו של מעגל או קשת בנקודה בסקיצה, כולל הראשית. אפשר לבחור את שני הפריטים בכל סדר.", + "help.sketch.constraint.curvature": "גורם לשתי עקומות שנפגשות בנקודת קצה להמשיך באותה עקמומיות (G2). מתאים כשחיבור משיק אינו חלק מספיק, למשל על משטחים גלויים.", + "help.sketch.constraint.equal": "גורם לישרים להיות באותו אורך, ולמעגלים ולקשתות באותו רדיוס. מתאים כדי שמידה אחת תניע כמה מאפיינים תואמים.", + "help.sketch.constraint.fix": "מקבע נקודות או עקומות במקומן, או משחרר אותן שוב. מתאים לגאומטריה שאסור שתזוז בגרירה או בפתרון הסקיצה.", + "help.sketch.constraint.horizontal_vertical": "גורם לישר, או לישר שבין שתי נקודות, להיות אופקי או אנכי, לפי הקרוב יותר. מתאים ליישור קו מתאר לצירי הסקיצה.", + "help.sketch.constraint.midpoint": "מציב נקודה באמצע ישר, או גורם לנקודות האמצע של שני ישרים להיפגש. מתאים למירכוז גאומטריה על קצה.", + "help.sketch.constraint.parallel": "גורם לשני ישרים להיות מקבילים. מתאים לצלעות שחייבות להישאר מקבילות כשמידות אחרות משתנות.", + "help.sketch.constraint.perpendicular": "גורם לשני ישרים להיפגש בזווית ישרה. מתאים לפינות ישרות בין ישרים שאינם על צירי הסקיצה.", + "help.sketch.constraint.polygon": "הופך שרשרת סגורה של ישרים למצולע משוכלל: צלעות שוות וכל פינה על מעגל אחד. מתאים להפיכת מצולע שצויר ביד למשוכלל ולשמירה על כך.", + "help.sketch.constraint.symmetry": "גורם לשתי נקודות או עקומות להיות תמונת מראה זו של זו סביב ישר או נקודה. מתאים לשמירה על פרופיל סימטרי כששינוי נעשה בצד אחד.", + "help.sketch.constraint.tangent": "גורם לשתי עקומות לגעת זו בזו כמשיקות, כמו ישר וקשת. מתאים לחיבורים חלקים בלי שבר.", + "help.sketch.construction": "מחליף עקומות בין גאומטריה רגילה לגאומטריית עזר, שהפרופילים מתעלמים ממנה. השתמשו בעקומות עזר לתכנון, לייחוסים ולמידות.", "help.sketch.construction_line": "יצירת ישר עזר אינסופי דרך שתי נקודות, לתכנון הסקיצה בלי לפצל את הפרופילים.", "help.sketch.construction_line.angle": "יצירת ישר עזר אינסופי בזווית מציר X של הסקיצה. יש לבחור נקודה ולהקליד זווית או לבחור כיוון.", "help.sketch.construction_line.bisector": "יש לבחור שני ישרים נחתכים בסקיצה ואז אחד משני חוצי הזווית. התוצאה עוקבת אחר עריכת ישרי המקור.", @@ -1411,11 +1666,71 @@ "help.sketch.construction_line.tangent_external": "יש לבחור מעגל או קשת מעגלית, נקודה חיצונית ואז פתרון למשיק. התצוגה המקדימה מציגה רק נקודות השקה על הקשת המצוירת.", "help.sketch.construction_line.tangent_two": "יש לבחור שני מעגלים או קשתות מעגליות ואז משיק משותף בתצוגה המקדימה. נקודות ההשקה חייבות להיות על העקומות המצוירות.", "help.sketch.construction_line.vertical": "יצירת ישר עזר אנכי אינסופי דרך נקודה. האילוץ האנכי נשמר בעריכות מאוחרות יותר.", + "help.sketch.copy": "מעתיק את עקומות הסקיצה והנקודות שנבחרו, יחד עם האילוצים והמידות שביניהן. אפשר להדביק אותן בסקיצה הזו או באחרת.", + "help.sketch.create": "מתחיל סקיצה דו־ממדית חדשה על מישור או על פאה שטוחה של המודל. כל שליפה, סיבוב וסחיפה מתחילים בסקיצה.", + "help.sketch.cut": "מעתיק את גאומטריית הסקיצה שנבחרה ומוחק אותה מהסקיצה, בצעד ביטול אחד. אפשר להדביק במקום אחר בסקיצה הזו או באחרת.", + "help.sketch.dimension": "מוסיף מידה מניעה: אורך, מרחק, זווית, רדיוס או קוטר, לפי מה שבוחרים. מקלידים ערך או שם פרמטר והסקיצה עוקבת אחריו.", + "help.sketch.edit": "פותח סקיצה קיימת לעריכה. המאפיינים שנבנו עליה מתעדכנים כשמסיימים את הסקיצה.", + "help.sketch.ellipse": "משרטט אליפסה לפי מרכזה, קצה הציר הראשי שלה ונקודה בצד הציר המשני. מתאים לפתחים אליפטיים, לזיזים ולצורות עגולות מוארכות אחרות.", "help.sketch.equation_curve": "משרטט עקומה מנוסחאות על פני טווח: x(t) ו־y(t), או y = f(x). הנוסחאות יכולות להשתמש בפרמטרים והעקומה עוקבת אחריהם: לגל סינוס, לספירלה או לאבולבנטה של שן גלגל שיניים.", + "help.sketch.extend": "מאריך ישר או קשת עד העקומה הקרובה ביותר בדרכם, או מגדיל שתי עקומות עד שייפגשו. מתאים לסגירת פערים בפרופיל אחרי גיזום או עריכה.", + "help.sketch.fillet": "מעגל את הפינה שבה נפגשים שני ישרים או קשתות בקשת ברדיוס נתון. פינות שמעגלים יחד חולקות רדיוס אחד.", + "help.sketch.finish": "יוצא מהסקיצה וחוזר למודל. הפרופילים הסגורים שלה מוכנים אז לשליפה, לסיבוב ולמאפיינים אחרים.", + "help.sketch.finish_auto_constrain": "מריץ אילוץ אוטומטי על הסקיצה ואז מסיים אותה. מתאים להשארת סקיצה מוגדרת במלואה בצעד אחד.", + "help.sketch.fit_curves_to_section": "חותך רשת משולשים או גוף מוצק במישור הסקיצה ומתאים ישרים וקשתות לחתך. מתאים לשחזור חלק שנסרק או יובא כסקיצה הניתנת לעריכה.", + "help.sketch.include_3d": "מביא קצוות, קדקודים ועקומות של סקיצות אחרות אל הסקיצה הזו כייחוסים מקושרים, ומשטח אותם למישור שלה. מתאים לבנייה על גאומטריה שאינה במישור הסקיצה.", + "help.sketch.infinite": "מחליף ישרים בין ישרים רגילים לישרי עזר אינסופיים שחוצים את כל התצוגה. מתאים לייחוסי תכנון שלעולם אינם קצרים מדי.", + "help.sketch.insert_dxf": "קריאת העקומות של שרטוט DXF לתוך סקיצה, בקנה המידה, בסיבוב ובמיקום שנקבעו. כך ממשיכים לעבוד על שרטוט דו־ממדי מתוכנה אחרת, כגון קו מתאר לחיתוך בלייזר.", + "help.sketch.insert_svg": "קריאת הנתיבים של שרטוט SVG לתוך סקיצה, בקנה המידה, בסיבוב ובמיקום שנקבעו. כך הופכים לוגו או קו מתאר וקטורי לעקומות שניתן לשחל.", + "help.sketch.inspect": "פותח דוח על הסקיצה הפתוחה: כמה דרגות חופש נותרו והאם היא מאולצת במלואה. השתמשו בו כדי לגלות מה עדיין זז לפני שמסיימים את הסקיצה.", + "help.sketch.intersect": "מוסיף את העקומות או הנקודות שבהן גופים, פאות, קצוות או סקיצות אחרות חותכים את מישור הסקיצה. הן נשארות מקושרות ועוקבות אחר המודל כשהוא משתנה.", + "help.sketch.intersection_curve": "יוצר עקומות תלת־ממדיות במקום שבו שני גופים או פאות נפגשים, מקושרות אליהם. מתאים למסלולים או למסילות הנחיה שעוקבים אחר המודל.", + "help.sketch.isoparametric_curve": "יוצר עקומה תלת־ממדית לאורך כיוון U או V של פאה דרך נקודה שבוחרים, מקושרת לפאה. מתאים למסלול או לקו פיצול שעוקבים אחר המשטח.", + "help.sketch.line": "משרטט ישרים מחוברים נקודה אחר נקודה, כשרשרת פתוחה או כקו מתאר סגור. זה הכלי הבסיסי לרוב הפרופילים.", + "help.sketch.line.midpoint": "משרטט ישר מנקודת האמצע שלו אל אחד הקצוות, כשהקצה השני משוקף. מתאים לישרים הממורכזים סביב נקודה, כמו קצה סימטרי.", + "help.sketch.line3d": "משרטט ישרים מחוברים בין נקודות במרחב, כשסקיצה תלת־ממדית פעילה. מתאים למסלולים ולמסגרות שיוצאים ממישור הסקיצה.", + "help.sketch.mirror": "משקף עקומות ונקודות של סקיצה סביב ישר או ציר ומוסיף אילוצי סימטריה. מתאים לשרטוט חצי מפרופיל סימטרי והשלמתו.", + "help.sketch.move": "מזיז או מסובב עקומות ונקודות של סקיצה, או עותק שלהן. מתאים לשינוי מיקום גאומטריה תוך שמירה על צורתה ועל האילוצים.", + "help.sketch.offset": "יוצר עותק של שרשרת עקומות במרחק קבוע, בצד אחד או בשניהם. מתאים לדפנות, לקווי מתאר ולמרווחים; המרחק נשאר מידה הניתנת לעריכה.", + "help.sketch.paste": "מדביק בסקיצה הפעילה גאומטריית סקיצה שהועתקה או נגזרה. אפשר למקם אותה בנקודה או להזיז אותה בהיסט.", + "help.sketch.pattern.circular": "מעתיק גאומטריית סקיצה סביב נקודת מרכז, על פני מעגל שלם או זווית נתונה. מתאים למעגלי ברגים, לחישורים ולשיניים.", + "help.sketch.pattern.rectangular": "מעתיק גאומטריית סקיצה בשורות ובעמודות במרווחים קבועים. מתאים לרשתות של חורים, חריצים או פתחי אוורור.", + "help.sketch.point": "מציב נקודת סקיצה. משמש כייחוס למידות, לאילוצים, למרכזי חורים או למאפיינים מאוחרים יותר.", + "help.sketch.point3d": "מציב נקודה במרחב, כשסקיצה תלת־ממדית פעילה. משמש כייחוס לעקומות ולמסלולים תלת־ממדיים.", + "help.sketch.polygon.circumscribed": "משרטט מצולע משוכלל סביב מעגל, בגודל שנקבע ממרכזו ועד אמצע צלע. מתאים כשהרוחב בין הצלעות ידוע, כמו באום משושה.", + "help.sketch.polygon.edge": "משרטט מצולע משוכלל משני קצותיה של צלע אחת. מתאים כשאורך הצלע ומיקומה ידועים.", + "help.sketch.polygon.inscribed": "משרטט מצולע משוכלל בתוך מעגל, בגודל שנקבע ממרכזו ועד פינה. מתאים כשהגודל בין הפינות ידוע.", + "help.sketch.project": "מביא קצוות, פאות, קדקודים ועקומות של סקיצות אחרות אל הסקיצה הזו, מוטלים על מישורה. הם נשארים מקושרים ועוקבים אחר המודל כשהוא משתנה.", + "help.sketch.project_to_surface": "מטיל עקומות של סקיצות אחרות לאורך הנורמל של הסקיצה הזו על פאה, כעקומות תלת־ממדיות מקושרות. מתאים להנחת לוגו, קו פיצול או מסלול על משטח מעוקל.", + "help.sketch.rectangle.center": "משרטט מלבן לפי מרכזו ואחת מפינותיו. מתאים לקווי מתאר הממורכזים סביב נקודה, כמו הראשית.", + "help.sketch.rectangle.rounded": "משרטט מלבן ובו ארבע פינות מעוגלות ברדיוס אחד. מתאים ללוחות, למכסים ולפתחים עם פינות מעוגלות.", + "help.sketch.rectangle.three_point": "משרטט מלבן לפי צלע אחת ונקודה בצד הנגדי. מתאים למלבנים שנטויים ביחס לצירי הסקיצה.", + "help.sketch.rectangle.two_point": "משרטט מלבן משתי פינות נגדיות. מתאים לקווי המתאר של לוחות, גושים וכיסים.", + "help.sketch.scale": "משנה קנה מידה של עקומות ונקודות בסקיצה בפקטור סביב נקודת בסיס. מתאים לשינוי גודל של חלק מהסקיצה בלי לשרטט אותו מחדש.", + "help.sketch.slot.arc_center": "משרטט חריץ מעוקל ברוחב נתון לאורך קשת שנקבעת לפי מרכזה, תחילתה וסופה. מתאים לחריצי כוונון סביב ציר.", + "help.sketch.slot.arc_three_point": "משרטט חריץ מעוקל ברוחב נתון לאורך קשת העוברת בשלוש נקודות. מתאים כשמסלול החריץ חייב לעבור בנקודות נתונות.", + "help.sketch.slot.center_point": "משרטט חריץ ישר ברוחב נתון ממרכזו ועד מרכז קשת הקצה האחת. מתאים לחריצים הממורכזים סביב נקודה.", + "help.sketch.slot.center_to_center": "משרטט חריץ ישר ברוחב נתון בין מרכזי קשתות שני קצותיו. מתאים לחריצים שמידותיהם ממרכז למרכז, כמו חריצי כוונון לברגים.", + "help.sketch.slot.overall": "משרטט חריץ ישר ברוחב נתון מקצהו החיצוני האחד אל השני. מתאים כשהאורך הכולל של החריץ הוא העיקר.", + "help.sketch.spline.control_point": "משרטט ספליין מעוקב שצורתו נקבעת על ידי נקודות בקרה שהוא אינו עובר בהן. מתאים לעקומות חלקות וזורמות שמעצבים בהזזת הנקודות.", + "help.sketch.spline.control_point_5": "משרטט ספליין ממעלה 5 שצורתו נקבעת על ידי נקודות בקרה. מתאים כשעקומות צריכות להתחבר בעקמומיות חלקה יותר, למשל במשטחים מעוצבים גלויים.", + "help.sketch.spline.fit_point": "משרטט ספליין חלק שעובר בכל נקודה שמניחים, פתוח או סגור. מתאים למעקב אחר צורה דרך נקודות ידועות.", + "help.sketch.spline3d": "משרטט עקומה חלקה במרחב דרך נקודות, כשסקיצה תלת־ממדית פעילה. מתאים למסלולי סחיפה ולמסלולי כבלים שיוצאים ממישור הסקיצה.", + "help.sketch.spun_profile": "יוצר במישור הסקיצה את קו המתאר שגוף סוחף כשהוא מסתובב סביב ציר. מתאים לקבלת צללית של חלק מחרטה לצורך סיבוב או שרטוט.", + "help.sketch.text": "כותב טקסט בסקיצה בגופן, בגובה ובזווית שבוחרים, ואפשר שהמילים יעקבו אחר פרמטרים. שלפו אותו או השתמשו בהבלטה לתוויות ולכיתובים.", + "help.sketch.transform": "משנה קנה מידה, מסובב ומזיז גאומטריית סקיצה סביב נקודת מרכז בצעד אחד. מתאים לשינוי מיקום וגודל של בחירה בבת אחת.", + "help.sketch.trim": "מסיר את קטע העקומה שבין החיתוכים הקרובים ביותר סביב המקום שלחצתם עליו. מתאים לניקוי ישרים חופפים עד לפרופיל סגור.", "help.solid.align": "הזזת הגופים שנבחרו כך שנקודה, פאה או מישור שלהם יפגשו נקודה, פאה או מישור במקום אחר. מתאים להצמדת חלק לחלק אחר בלי למדוד את המרחק.", + "help.solid.boundary_fill": "יצירת מוצקים מהאזורים הסגורים בין גופי כלי חופפים, תוך מילוי האזורים שנבחרו בלבד. כך בונים צורה מהחלל שכמה גופים תוחמים יחד.", + "help.solid.bounding_solid": "יצירת תיבה שחוסמת את הגופים שנבחרו, עם אפשרות לתוספת שוליים. כך רואים את המידות הכוללות של חלק או יוצרים את חומר הגלם שממנו הוא יעובד.", + "help.solid.box": "יצירת תיבה לפי אורך, רוחב וגובה, החל מנקודת פינה או ממורכזת סביב נקודה. מתאים ליצירה מהירה של גוש, מציין מקום או גוף לחיתוך מאפיינים בתוכו.", "help.solid.chamfer": "חיתוך המקצועות שנבחרו בשיפוע ישר במרחק שנקבע. כך שוברים מקצועות חדים או מקלים על הכנסה של פין או בורג.", + "help.solid.coil": "יצירת גוף סלילי, כגון קפיץ, לפי קוטר, מספר כריכות, גובה או פסיעה וחתך עגול או מרובע. מתאים לקפיצים, לסלילים ולבליטות סליליות.", "help.solid.combine": "איחוד גופים, חיסורם מגוף יעד או השארת הנפח המשותף להם בלבד, עם אפשרות לשמור את גופי הכלי. מתאים למיזוג חלקים, לחיתוך צורה אחת בעזרת אחרת או למציאת החפיפה בין שני גופים.", + "help.solid.cone": "יצירת חרוט ממעגל בסיס וגובה, או חרוט קטום כשנקבע גם רדיוס בחלק העליון. מתאים לצורות מתחדדות, למשפכים, לשיקועים חרוטיים ולחודים.", + "help.solid.cylinder": "יצירת גליל לפי רדיוס או קוטר וגובה, הניצב בנקודה לאורך ציר. מתאים לצירים, לפינים, לבליטות גליליות ולגולמים עגולים.", "help.solid.draft": "הטיית הפאות שנבחרו בזווית שנקבעה, הנמדדת ממישור ניטרלי. מתאים לחלקים יצוקים או מוזרקים, כדי שישתחררו מהתבנית.", + "help.solid.emboss": "הבלטת פרופילי סקיצה, כגון טקסט או לוגו, מתוך פאה או השקעתם בתוכה. מתאים לאותיות, לתוויות ולסימונים על פאות שטוחות או עגולות.", "help.solid.extrude": "דחיפת פרופיל של סקיצה לתלת־ממד לאורך מרחק, להוספה או להסרה של חומר. כך הופכים קו מתאר שטוח לגוש, לבליטה או לכיס.", "help.solid.fillet": "עיגול המקצועות שנבחרו במעבר מעגלי חלק ברדיוס שנקבע. כך מרככים מקצועות חדים לטובת חוזק, נוחות או מראה.", "help.solid.hole": "קידוח חור עגול בקוטר שנקבע בנקודה שנבחרה על פאה. מתאים לחורי מעבר לברגים, לפינים ולפתחים עגולים פשוטים אחרים.", @@ -1424,20 +1739,61 @@ "help.solid.move": "הזזה או סיבוב של הגופים שנבחרו, או של עותק שלהם, במרחק ובזווית שנקבעו. מתאים לשינוי מיקום של גוף או ליצירת גוף נוסף במקום אחר.", "help.solid.offset_face": "דחיפת הפאות שנבחרו פנימה או החוצה במרחק שנקבע, והפאות שסביבן מתאימות את עצמן. כך מעבים דופן, מעמיקים כיס או מגביהים בליטה בלי לערוך את הסקיצה.", "help.solid.pattern.circular": "שכפול הפריטים שנבחרו סביב ציר, לפי המספר והזווית הכוללת שנקבעו. מתאים למעגלי ברגים, לחישורים, לצלעות קירור ולשיניים.", + "help.solid.pattern.path": "העתקת פיצ'רים או גופים לאורך מסלול סקיצה, לפי כמות ומרווח. מתאים לחורים לאורך מקצוע מעוקל או לחלקים לאורך מסילה.", "help.solid.pattern.rectangular": "שכפול הפריטים שנבחרו בכיוון אחד או בשניים, לפי המספר והמרווח שנקבעו. מתאים לשורות ולרשתות של חורים, צלעות, פינים או רגליות.", + "help.solid.pipe": "יצירת צינור עגול לאורך נתיב של עקומות סקיצה, מלא או חלול עם עובי דופן. מתאים לצינורות, לחוטים, לכבלים ולמסילות.", "help.solid.press_pull": "הוספה או הסרה של חומר בגרירת פאה, או עיגול מקצועות בגרירתם. מתאים לשינויים מהירים ישירות על המודל.", "help.solid.remove": "הוצאת הגופים שנבחרו מהתכנון מנקודה זו בציר הזמן והלאה; השלבים הקודמים שומרים אותם. מתאים להסרת גוף עזר, כמו כלי חיתוך שכבר אין בו צורך.", "help.solid.replace_face": "העברת הפאות השטוחות שנבחרו אל מישור או אל פאה מקבילה, והגוף מתארך או מתקצר כדי להגיע אליהם. מתאים ליישור פאה בקו אחד עם חלק אחר או עם מישור עזר.", "help.solid.revolve": "סיבוב פרופיל של סקיצה סביב ציר ליצירת גוף מוצק עגול. מתאים לגלים, לכפתורים, לקערות ולכל חלק שעגול סביב קו מרכז.", + "help.solid.rib": "הוספת צלע דקה לאורך עקומת סקיצה פתוחה, הנמשכת עד לפאות הבאות של הגוף. כך מחזקים דפנות ופינות, למשל בחלקים יצוקים או מודפסים.", "help.solid.scale": "הגדלה או הקטנה של הגופים שנבחרו לפי מקדם, זהה בכל הכיוונים או שונה לכל ציר. מתאים לשינוי גודל של צורה מיובאת או להתחשבות בהתכווצות.", "help.solid.shell": "חלילת גוף מוצק תוך השארת דפנות בעובי שנקבע, עם אפשרות לפתוח את הפאות שנבחרו. מתאים לקופסאות, למכסים ולחלקים אחרים בעלי דופן דקה.", + "help.solid.sphere": "יצירת כדור לפי רדיוס או קוטר סביב נקודת מרכז. מתאים לכדורים, לכפתורי אחיזה ולקצוות מעוגלים.", "help.solid.split_body": "פיצול גוף לגופים נפרדים בעזרת מישור, פאה של גוף אחר או קו בסקיצה. מתאים ליצירת חלקים שמודפסים, מעובדים או נצבעים כל אחד בנפרד.", "help.solid.split_face": "פיצול הפאות שנבחרו לאורך מישור, פאה של גוף אחר או עקומות של סקיצה, בלי לחתוך את הגוף. כך נותנים לחלק מפאה שיפוע, צבע או היסט משלו.", "help.solid.sweep": "גרירת פרופיל של סקיצה לאורך מסלול ליצירת גוף מוצק. מתאים לצינורות, למסילות, לידיות ולכל חלק בעל חתך קבוע שעוקב אחרי עקומה.", + "help.solid.thread": "הוספת תבריג מטרי לפי ISO לפאה גלילית, כתבריג סמלי או כחיתוך בגוף. מתאים לברגים, לחורים בעלי תבריג ולחלקי הברגה מודפסים.", + "help.solid.torus": "יצירת טבעת לפי רדיוס ראשי סביב הציר שלה ורדיוס משני לחתך העגול. מתאים לטבעות אטימה, לידיות ולבליטות טבעתיות עגולות.", + "help.solid.web": "הוספת דופן דקה לאורך כל עקומת סקיצה פתוחה, כשכל אחת נמשכת עד לפאות הבאות של הגוף. מתאים לרשת דפנות תמיכה בתוך מארזים ומגשים.", + "help.surface.blend": "יצירת משטח שמגשר בין מקצועות של שני גופים, משיק או רציף בעקמומיות לשניהם. מתאים לחיבור חלק בין שני משטחים מעל רווח.", + "help.surface.boundary": "יצירת משטח שממלא לולאה של שניים עד ארבעה עקומות סקיצה, או רשת של עקומות. מתאים ללוחות בצורה חופשית שמוגדרים לפי הקצוות שלהם.", + "help.surface.extend": "הארכת משטח מעבר לקצוותיו, במרחק נתון או עד מישור או פאה. מתאים כדי שמשטחים יחפפו לפני גיזום או תפירה.", + "help.surface.extrude": "דחיפת עקומות או פרופילים של סקיצה לאורך מרחק למשטח, דפנות בלבד בלי מכסים. מתאים לדפנות דקות ולכלי חיתוך או פיצול.", + "help.surface.fair": "החלקת פנים הפאות החופשיות כשהקצוות שלהן נשארים במקומם. מתאים ליישור בליטות והשתקפויות גליות במשטח.", + "help.surface.loft": "יצירת משטח שעובר דרך שני חתכים או יותר לפי הסדר, בלי מכסים. מתאים לקליפות ולמעברים בין צורות שונות.", + "help.surface.match": "בנייה מחדש של קצה משטח כך שייפגש עם קצה של גוף אחר, בהתאמת משיק או עקמומיות. מתאים לסגירה חלקה של תפר בין שני משטחים.", + "help.surface.offset": "יצירת עותק של פאות במרחק לאורך הנורמלים שלהן, כגוף משטח חדש. מתאים לקליפות, למרווחים או לצדו השני של דופן.", + "help.surface.patch": "מילוי אזור סקיצה או לולאה סגורה של מקצועות בפאה, שטוחה או מעוקלת בעדינות. מתאים לסגירת חורים בגוף משטח.", + "help.surface.reverse_normal": "היפוך פאות של גוף משטח כך שצדן החיצוני יפנה לכיוון ההפוך. מתאים לפני עיבוי או תפירה כשהפאות פונות פנימה.", + "help.surface.revolve": "סיבוב עקומות או פרופילים של סקיצה סביב ציר למשטח, בלי מכסים. מתאים לקליפות עגולות כמו אהילים, קערות וזרבובים.", + "help.surface.ruled": "יצירת רצועה של קווים ישרים היוצאים משרשרת מקצועות, בכיוון הנורמל של הפאה, המשיק או בזווית. מתאים לדפנות שיפוע, לאזורי מעבר ולמשטחי חלוקה.", + "help.surface.stitch": "תפירת גופי משטח זה לזה לאורך המקצועות המשותפים, לגוף מוצק אם הם סוגרים נפח. מתאים להפיכת קבוצת משטחים לגוף אחד.", + "help.surface.sweep": "הזזת עקומות או פרופילים של סקיצה לאורך מסלול למשטח, בלי מכסים. מתאים למרזבים, לפסי קישוט ולצורות דקות אחרות שעוקבות אחרי מסלול.", + "help.surface.thicken": "מתן עובי לגוף משטח והפיכתו לגוף מוצק. מתאים ליצירת חלקים להדפסה או לעיבוד שבבי ממשטחים.", + "help.surface.trim": "חיתוך משטח בעזרת מישור, משטח אחר או עקומות סקיצה, ושמירת הצד שנבחר. מתאים לגיזום משטחים לצורה לפני תפירה.", + "help.surface.unstitch": "הפרדת פאות של גוף לגופי משטח נפרדים; גוף מוצק מתפרק למשטחים. מתאים לעיבוד מחדש של פאות בודדות בגוף.", + "help.surface.untrim": "הסרת חורים מפאה, או החזרת הגבול החיצוני שלה לגבולות הטבעיים של המשטח. מתאים לשחזור המשטח המלא אחרי גיזום.", "help.third_party": "רישיונות צד שלישי", "help.timeline.compute_all": "בנייה מחדש של כל הפיצ'רים בציר הזמן מההתחלה. מתאים לרענון המודל ולבדיקה אילו פיצ'רים נכשלים.", "help.timeline.delete": "מחיקת הפיצ'רים שנבחרו מציר הזמן; מחיקת סקיצה מוחקת גם את הפיצ'רים שנבנו ממנה. מתאים להסרת שלב שכבר אין בו צורך.", + "help.timeline.dependents": "הצגת הפיצ'רים שיימחקו יחד עם פיצ'ר, ואלה שייכשלו בלעדיו. מתאים לפני מחיקה או שינוי של פיצ'ר.", "help.timeline.play": "הפעלה מחדש של הפיצ'רים שנותרו, אחד בכל פעם, עם השהיה של חצי שנייה לאחר כל בנייה מחדש. להפסקה יש להפעיל שוב את הפקודה או ללחוץ על Escape; מעבר לסוף מתבצע מיד.", + "help.version": "גרסה {version}", + "help.view.apply": "סיבוב התצוגה לכיוון סטנדרטי כמו חזית, מבט עליון או איזומטרי, או לתצוגה שמורה בשם. מתאים להתבוננות במודל מזווית קבועה.", + "help.view.delete": "מחיקת תצוגה שמורה. המודל אינו משתנה.", + "help.view.fit": "זום והזזה כך שכל המודל, או הבחירה, ימלאו את התצוגה. מתאים כשהמודל יצא מהטווח הנראה.", + "help.view.grid": "הצגה או הסתרה של הרשת בחלון התצוגה. משמשת כמדריך לגודל ולכיוון בזמן המידול.", + "help.view.ground_shadow": "הצגה או הסתרה של צל המודל על הקרקע. מתאים כדי להעריך גובה ומיקום ביתר קלות.", + "help.view.home": "החזרת התצוגה לכיוון הבית והתאמת המודל לחלון. מתאים לחזרה מהירה לתצוגה מוכרת.", + "help.view.list": "הצגת רשימת התצוגות השמורות בתכן. מתאים כדי למצוא תצוגה ששמרת קודם.", + "help.view.navigate": "סיבוב, הזזה או זום של התצוגה בצעדים, כמו רבע סיבוב שמאלה. מתאים להזזה מדויקת של המצלמה במקום גרירה.", + "help.view.navigation_bar": "הצגה או הסתרה של סרגל הניווט בתחתית חלון התצוגה. אפשר להסתיר אותו לשטח נוסף, או להציג אותו כדי להגיע אל כלי התצוגה בעכבר.", + "help.view.rename": "מתן שם חדש לתצוגה שמורה. התצוגה עצמה נשארת כפי שהיא.", + "help.view.save": "שמירת מיקום המצלמה הנוכחי כתצוגה בשם בתכן. מתאים לחזרה לאותה זווית בהמשך, למשל לצילומי מסך.", + "help.view.spin": "הקפת המודל בתצוגה באופן רציף עד ללחיצה או למקש הבא. מתאים להצגת מודל מכל הצדדים.", + "help.view.tool": "נעילת כלי מצלמה, מסלול, הזזה או זום, כך שגרירה בכפתור השמאלי של העכבר מזיזה את התצוגה עד שמכבים אותו. מתאים למשטח מגע או כשאין כפתור עכבר אמצעי.", + "help.view.visual_style": "החלפת אופן הציור של המודל: מוצלל עם מקצועות או בלעדיהם, מסגרת תיל, או עם מקצועות מוסתרים. מסגרת תיל מאפשרת לראות פנימה, ומוצלל נותן מראה נקי.", "history.sketch_under_constrained": "אילוצים חסרים ({count} דרגות חופש)", "history.sketch_under_constrained_one": "אילוצים חסרים (דרגת חופש {count})", "hole_presets.confirm_delete": "אישור מחיקה", @@ -1511,6 +1867,27 @@ "home.start_hint": "אפשר ליצור תכן, לפתוח קובץ אחרון או לעיין בדוגמה.", "home.whats_new": "מה חדש", "home.yesterday": "אתמול", + "import_report.details": "פרטים:", + "import_report.file_one": "הייתה בעיה נוספת אחת בקובץ.", + "import_report.file_other": "היו {count} בעיות נוספות בקובץ.", + "import_report.hint": "ייצוא מחדש של החלקים האלה מהתוכנה שיצרה אותם עשוי לפתור זאת. ב„העתקת הודעת האזהרה” יש את הפרטים.", + "import_report.left_out_one": "לא ניתן היה לתקן פאה אחת והיא חסרה.", + "import_report.left_out_other": "לא ניתן היה לתקן {count} פאות והן חסרות.", + "import_report.needs_repair_one": "חלק אחד דורש תיקון לפני שאפשר למדל עליו.", + "import_report.needs_repair_other": "{count} חלקים דורשים תיקון לפני שאפשר למדל עליהם.", + "import_report.not_imported_one": "לא ניתן היה לייבא חלק אחד.", + "import_report.not_imported_other": "לא ניתן היה לייבא {count} חלקים.", + "import_report.not_shown_one": "לא ניתן היה לצייר פאה אחת והיא מוסתרת.", + "import_report.not_shown_other": "לא ניתן היה לצייר {count} פאות והן מוסתרות.", + "import_report.open_one": "בחלק אחד יש רווחים בין הפאות והוא יובא כגוף פתוח.", + "import_report.open_other": "ב-{count} חלקים יש רווחים בין הפאות והם יובאו כגופים פתוחים.", + "import_report.refused_one": "לא ניתן היה להפוך חלק אחד לגוף מוצק והוא לא יובא.", + "import_report.refused_other": "לא ניתן היה להפוך {count} חלקים לגופים מוצקים והם לא יובאו.", + "import_report.repaired_one": "תוקנו פגמים קטנים בחלק אחד.", + "import_report.repaired_other": "תוקנו פגמים קטנים ב-{count} חלקים.", + "import_report.solids": "{solids} מתוך {parts} חלקים יובאו כגופים מוצקים.", + "import_report.surfaces_one": "לא ניתן היה להפוך חלק אחד לגוף מוצק והוא יובא כמשטחים.", + "import_report.surfaces_other": "לא ניתן היה להפוך {count} חלקים לגופים מוצקים והם יובאו כמשטחים.", "install.button_tip": "התקנת SolidCraft כיישום: נפתח בחלון משלו ועובד גם ללא חיבור לרשת", "install.dock_1": "יש לבחור קובץ › הוספה ל־Dock.", "install.dock_2": "יש ללחוץ על הוספה.", @@ -1535,26 +1912,39 @@ "issue.note_save_failed": "לא ניתן לשמור את צילום המסך: {error}", "issue.note_saved": "צילום המסך נשמר. יש לצרף את קובץ ה־PNG בטיוטה ב־GitHub.", "issue.save_screenshot": "שמירת צילום המסך…", + "joint.find_limits": "מציאת גבולות", + "joint.find_limits_failed": "החיפוש אחר הגבולות נעצר עקב שגיאה", + "joint.find_limits_hint": "ממלא את הגבולות לפי המקום שבו החלקים שהמפרק מזיז נוגעים לראשונה בחלק אחר, בסיבוב או בהחלקה לשני הכיוונים מהמקום הנוכחי. החיפוש רץ על עותק: דבר אינו משתנה עד ללחיצה על OK.", + "joint.find_limits_stale": "המפרק או התכן השתנו מאז שהגבולות האלה נמצאו: חפשו אותם שוב", + "joint.finding_limits": "מחפש גבולות…", "joint.from_bodies_hint": "כל גוף שנבחר עובר לרכיב חדש משלו ונשאר במקומו.", + "joint.limit_contact": "{side} {value}: {a} נוגע ב-{b}", + "joint.limit_limit": "{side} {value}: הגבול של ערך אחר או של מפרק אחר", + "joint.limit_loop": "{side} {value}: לולאה סגורה אינה יכולה להיסגר מעבר לכך", + "joint.limit_range": "{side}: אין מגע בטווח {range}, נשאר כפי שהיה", + "joint.limit_turn": "{side} {value}: אין מגע בסיבוב אחד", + "joint.limits_overlapping": "כבר חודרים זה לזה כאן: {pairs}. הם עוצרים את החיפוש רק אם יחדרו עמוק יותר.", "joint.one_body": "שתי הבחירות נמצאות על {body}. יש לבחור את השנייה על חלק אחר.", "joint.one_component": "חלקים אלה הם גופים של רכיב אחד: {bodies}. מפרק מזיז רכיב אחד ביחס לרכיב אחר, ולכן כל חלק צריך רכיב משלו.", "joint.rigid_group_one_component": "כל {count} הגופים האלה נמצאים ברכיב אחד (או בתכן עצמו): יש להשתמש קודם ב־{command}.", "joint.rigid_group_select_components": "יש לבחור שני רכיבים או יותר.", "joint_move.blocked_hint": "בדקו את סוג המפרק (למשל מפרק קשיח), את קיבוע החלק, את מגבלות המפרק ואת הערכים הנשלטים על ידי פרמטרים.", "joint_move.blocked_title": "אי אפשר להזיז את החלק הזה", - "joint_move.coarse": "צעד סיבוב קרוב לציר (°)", + "joint_move.coarse": "צעד בקרבת הציר", + "joint_move.conflict": "אחד המפרקים של החלק הזה מתנגש עם האחרים: {joint}.", + "joint_move.conflict_hint": "ערכו, השביתו או מחקו את המפרק המתנגש כדי שהמפרקים האחרים יוכלו למקם את החלק.", "joint_move.distance": "מרחק מנקודת ההתחלה", "joint_move.done": "סיום", - "joint_move.fine": "צעד סיבוב רחוק מהציר (°)", + "joint_move.fine": "צעד הרחק מהציר", "joint_move.fixed": "לחלק הזה אין ציר מפרק שניתן להזיז.", "joint_move.help": "הזזה — גררו חץ או קשת. Esc מבטל את הגרירה הנוכחית.", - "joint_move.legacy_hint": "כבו כדי להשתמש בחלונית ההזזה הקודמת.", - "joint_move.precision": "משכו אל מחוץ למנחה המקווקו כדי לכוון את הסיבוב בעדינות.", + "joint_move.legacy_hint": "כבוי: חלונית ההזזה הקודמת.", + "joint_move.precision": "לצעד העדין יש למשוך מחוץ לקו העזר המקווקו.", "joint_move.rotation": "סיבוב מנקודת ההתחלה", "joint_move.select": "בחרו פאה או חלק אחד בהרכבה, ואז בחרו הזזה.", "joint_move.settings": "הזזה בהרכבה", "joint_move.step": "צעד", - "joint_move.use_handles": "שימוש בידיות תנועת מפרקים להזזה בהרכבה", + "joint_move.use_handles": "שימוש בידיות תנועת מפרקים להזזה", "keymap.command_id": "מזהה פקודה", "keymap.empty": "אין פקודות תואמות", "keymap.use_anyway": "שימוש ב־{key} כאן בכל זאת", @@ -1614,6 +2004,11 @@ "material.selection.mixed": "חומרים שונים", "measure.at": "מיקום", "measure.item": "פריט {number}", + "measure.line_to_centre": "מהקו למרכז", + "measure.quick_copied": "המדידה הועתקה", + "measure.quick_copy": "לחיצה מעתיקה את המדידה", + "measure.quick_edges": "{count} מקצועות", + "measure.quick_faces": "{count} פאות", "messages.ago_h": "לפני {n} שע'", "messages.ago_min": "לפני {n} דק'", "messages.ago_s": "לפני {n} שנ'", @@ -1638,6 +2033,8 @@ "motion.track_name": "רצועה {number}", "nav.alias.help": "Shift+Alt וגרירה שמאלית מסובבים, Shift+Alt וגרירה אמצעית מזיזים, Shift+Alt וגרירה ימנית מבצעים זום; גם גרירה אמצעית מזיזה וגרירה ימנית מסובבת", "nav.blender.help": "גרירה אמצעית מסובבת, Shift וגרירה אמצעית מזיזים, Ctrl וגרירה אמצעית מבצעים זום; גרירה ימנית לא מזיזה את המצלמה", + "nav.creo.help": "גרירה בלחצן האמצעי מסובבת את התצוגה, Shift והלחצן האמצעי מזיזים אותה, Ctrl וגרירה אנכית בלחצן האמצעי משנים את הזום (גרירה מטה להגדלה); גלילת הגלגלת משנה גם היא את הזום", + "nav.creo.label": "Creo", "nav.free_orbit.help": "העכבר והעכבר התלת־ממדי מסובבים דרך שני הקטבים ושומרים על הגלגול. הצמדת הצירים עם Shift מושבתת.", "nav.free_orbit.label": "סיבוב חופשי", "nav.free_orbit.snap_help": "העכבר והעכבר התלת־ממדי מסובבים דרך שני הקטבים ושומרים על הגלגול. יש להחזיק את Shift בזמן גרירת סיבוב כדי להצמיד את כיוון התצוגה ואת הגלגול.", @@ -1647,6 +2044,7 @@ "nav.hfss.help": "Alt וגרירה שמאלית מזיזים, Shift+Alt וגרירה שמאלית מבצעים זום, Ctrl וגרירה שמאלית משטח ריק מסובבים", "nav.inventor.help": "גרירה אמצעית מזיזה, Shift וגרירה אמצעית מסובבים, Ctrl וגרירה אמצעית מבצעים זום, גרירה ימנית מסובבת", "nav.maya.help": "Alt וגרירה שמאלית מסובבים, Alt וגרירה אמצעית מזיזים, Alt וגרירה ימנית מבצעים זום; גם גרירה אמצעית מזיזה", + "nav.nx.help": "גרירה בלחצן האמצעי מסובבת, Shift+האמצעי מזיז את התצוגה (ב-NX: אמצעי + ימני), Ctrl+האמצעי מקרב ומרחיק (ב-NX: אמצעי + שמאלי); גרירה בלחצן הימני לא מזיזה את המצלמה", "nav.openscad.help": "גרירה שמאלית על שטח ריק מסובבת, Shift וגרירה שמאלית בוחרים במלבן, גרירת גאומטריית סקיצה עורכת אותה; גרירה ימנית או אמצעית מזיזה, Shift וגרירה ימנית או אמצעית מבצעים זום", "nav.perspective.sketch": "עריכת סקיצה משתמשת בתצוגה אורתוגרפית. יש לסיים את הסקיצה כדי לעבור לפרספקטיבה.", "nav.right_drag_orbits.help": "כבוי: גרירה בכפתור הימני לא מזיזה את המצלמה, והכפתור הימני רק פותח את תפריט ההקשר. בחירת מיפוי העכבר SolidWorks מכבה זאת.", @@ -1665,6 +2063,12 @@ "navbar.assistant": "עוזר", "navbar.custom.add_slot": "הוספת {slot}", "navbar.custom.always": "תמיד מוצג", + "navbar.custom.anchor.bottom_centre": "למטה במרכז", + "navbar.custom.anchor.bottom_left": "למטה משמאל", + "navbar.custom.anchor.bottom_right": "למטה מימין", + "navbar.custom.anchor.top_centre": "למעלה במרכז", + "navbar.custom.anchor.top_left": "למעלה משמאל", + "navbar.custom.anchor.top_right": "למעלה מימין", "navbar.custom.available": "{available} · גררו אל הסרגל או לחצו על הוספה", "navbar.custom.buttons": "לחצנים", "navbar.custom.compact": "דחוס", @@ -1701,6 +2105,7 @@ "navbar.custom.reset_default": "איפוס לברירת מחדל", "navbar.custom.right": "הזזה ימינה", "navbar.custom.select": "לא נבחרה משבצת. בחרו משבצת בסרגל כדי להזיז אותה, להסיר אותה או לשנות את המראה שלה.", + "navbar.custom.separator_hint": "מפריד בין קבוצות כפתורים. גררו אותו לסרגל או לחצו על הוספה; אפשר להשתמש בכמה מפרידים שתרצו.", "navbar.custom.separators_full": "בסרגל כבר יש ארבעה מפרידים.", "navbar.custom.show": "הצגת סרגל הניווט", "navbar.custom.shows": "מציג", @@ -1766,6 +2171,11 @@ "not a move": "זו אינה הזזה", "not a number": "לא מספר", "open a sketch first": "יש לפתוח סקיצה תחילה", + "parameters.apply_live": "להחיל כל שינוי ביציאה מהשדה שלו", + "parameters.apply_live_tip": "כבוי: השינויים ממתינים עד ל„החל” או „אישור”, ואז התכן נבנה מחדש פעם אחת עבור כולם. „ביטול” או Escape משליכים אותם.", + "parameters.held": "{count} שינויים ממתינים ל„החל”", + "parameters.held_hint": "עריכת ביטויים ויחידות. השינויים ממתינים ל„החל” או ל„אישור”.", + "parameters.held_one": "שינוי אחד ממתין ל„החל”", "parts.automatic_name": "אוטומטי", "parts.dimension.across_flats": "מידת מפתח", "parts.dimension.bore": "קוטר קדח", @@ -1784,10 +2194,19 @@ "parts.family.button_head_cap_screw": "בורג ראש כפתור עם שקע משושה", "parts.family.dowel_pin": "פין גלילי", "parts.family.hex_bolt": "בורג ראש משושה", + "parts.family.hex_cap_screw_inch": "בורג ראש משושה (אינץ')", "parts.family.hex_nut": "אום משושה", + "parts.family.hex_nut_inch": "אום משושה (אינץ')", "parts.family.set_screw": "בורג אלן ללא ראש, קצה שטוח", "parts.family.socket_head_cap_screw": "בורג ראש גלילי עם משושה פנימי", "parts.family.washer": "דסקית שטוחה", + "parts.family.washer_sae": "דסקית שטוחה, SAE (צרה)", + "parts.family.washer_uss": "דסקית שטוחה, USS (רחבה)", + "parts.holes": "חורים (אופציונלי)", + "parts.placement_hint": "בחרו חור אחד או יותר כדי להושיב חלק בכל אחד, או לחצו אישור כדי למקם אותו בראשית", + "parts.system": "מערכת יחידות", + "parts.system.inch": "אינץ'", + "parts.system.metric": "מטרי", "pattern.alignment_2": "יישור 2", "pattern.alignment_hint": "הספירה כוללת את המקור. מרכוז מאזן את העותקים; היפוך בוחר את הצד שמקבל את העותק הנוסף כשהסך זוגי.", "pattern.direction_1": "כיוון 1", @@ -1826,20 +2245,52 @@ "prefs.alt_frees_manipulators": "Alt / Option משחרר גם את חיצי המניפולטור", "prefs.anti_aliasing_amd_dx12": "החלקת הקצוות משתמשת ב־1× כי בדיקת ההפעלה לא ציירה דבר עם דגימה מרובה ועברה ב־1×. אפשר לבחור הגדרה אחרת למעלה; יש להפעיל מחדש כדי להחיל אותה אם הבדיקה עוברת.", "prefs.anti_aliasing_note": "מחליק קצוות משוננים.", + "prefs.appearance.colour_vision_help": "משנה צבעים בעלי משמעות: מצבי סקיצה, צירים, כיפופים, ניתוחים וסמלים.", + "prefs.appearance.desktop_only": "למחשב בלבד", + "prefs.appearance.follow_help": "טוען מחדש כאשר כלי אחר משכתב את הקובץ.", + "prefs.appearance.interface_scale": "קנה מידה של הממשק", + "prefs.appearance.next_themes": "ערכות העיצוב הבאות", + "prefs.appearance.option_count": "{count} אפשרויות", + "prefs.appearance.option_count_one": "{count} אפשרות", + "prefs.appearance.previous_themes": "ערכות העיצוב הקודמות", + "prefs.appearance.theme_count": "{count} ערכות עיצוב", + "prefs.appearance.theme_own": "צבעי ערכת העיצוב", + "prefs.appearance.viewport_colours": "צבעי תצוגת תלת־ממד", + "prefs.appearance.viewport_logo": "חלון התצוגה והלוגו", "prefs.applies_on_restart": "ייכנס לתוקף בהפעלה מחדש", "prefs.assistant": "עוזר", + "prefs.assistant_connecting": "חיבור", + "prefs.assistant_follow_help": "פעולות Look At בסקיצות מזיזות את התצוגה עם המצביע.", + "prefs.assistant_limit": "מגבלה", + "prefs.assistant_limited": "מוגבל", + "prefs.assistant_pointer_speed": "מהירות המצביע", + "prefs.assistant_seconds": "שניות", + "prefs.assistant_seconds_aria": "שניות", + "prefs.assistant_use_care": "להשתמש בזהירות", "prefs.auto_operation": "בחירת הפעולה באופן אוטומטי", - "prefs.auto_operation_note": "חלונות הפיצ'רים בוחרים „איחוד”, „גוף חדש” או „הסרה” לפי מה שהחומר החדש נוגע בו, עד שתבחרו פעולה בעצמכם. כבוי: הם שומרים על הפעולה שאיתה נפתחו.", + "prefs.auto_operation_note": "איחוד, גוף חדש או חיתוך, לפי מה שהחומר נוגע בו.", "prefs.axes": "צירים", "prefs.axis": "ציר", + "prefs.blur_cost": "עלות עיבוד יחסית. יותר פסים מציינים בדרך כלל יותר עבודה.", + "prefs.blur_device": "לא זמין בהתקן הגרפי או בנתיב העיבוד הזה", + "prefs.blur_guard": "איכות הטשטוש הופחתה כדי לשמור על תגובתיות הפריימים. הרדיוס לא השתנה.", + "prefs.blur_off": "כבוי", + "prefs.blur_reduce_transparency": "מושבת עקב הגדרת הפחתת השקיפות של המערכת", + "prefs.blur_software": "לא זמין עם עיבוד גרפי בתוכנה (gpu-software)", + "prefs.blur_source": "לא זמין בתצוגת סביבת העבודה הזו", + "prefs.blur_web": "לא זמין בנתיב העיבוד הזה בדפדפן", "prefs.bodies_folders": "תיקיות גופים", "prefs.bodies_folders_always": "תמיד", "prefs.bodies_folders_never": "אף פעם", - "prefs.bodies_folders_several": "רק כשיש כמה גופים", + "prefs.bodies_folders_several": "כמה", "prefs.bottom": "למטה", "prefs.bottom_centre": "למטה במרכז", "prefs.bottom_right": "למטה מימין", "prefs.browser": "עץ התכן", + "prefs.browser_components_open": "רכיבים פתוחים מההתחלה", + "prefs.browser_components_open_note": "כל רכיב בעץ התכן מתחיל פתוח, כמו קודם, במקום סגור עד שתפתח אותו.", + "prefs.browser_eye_left": "סמל העין ליד חץ הקיפול", + "prefs.browser_eye_left_note": "שורות עץ התכן מציגות את סמל העין ליד חץ הקיפול, כמו קודם, במקום בעמודה בקצה הימני של השורות.", "prefs.browser_reveal_on_hover": "הצגה בריחוף", "prefs.browser_show_note": "״מוצג״ משאיר את הדפדפן על המסך. ״הצגה בריחוף״ מסתיר אותו עד שהמצביע מגיע למקומו או ללשונית הדקה בקצהו השמאלי, והוא נשאר פתוח כל עוד המצביע בתוכו או שתפריט ממנו פתוח.", "prefs.browser_shown": "מוצג", @@ -1847,6 +2298,8 @@ "prefs.button_left": "גרירה שמאלית", "prefs.button_middle": "גרירה אמצעית", "prefs.button_right": "גרירה ימנית", + "prefs.carousel_next": "הבא", + "prefs.carousel_previous": "הקודם", "prefs.choose_font": "בחירת קובץ גופן…", "prefs.click": "לחיצה", "prefs.contact_shading": "הצללת מגע רכה", @@ -1859,27 +2312,63 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "משטחים מעוקלים", "prefs.curves": "משטחים מעוקלים", + "prefs.cut_preview_tint": "הצגת חומר שהוסר באדום", + "prefs.cut_preview_tint_help": "תצוגה מקדימה ממלאת את החומר שהפעולה מסירה, ואת הצורה שהיא מחליפה, ברוח אדומה שקופה. כשהאפשרות כבויה המילויים האלה שקופים לחלוטין ומצוירים רק קווי המתאר שלהם.", + "prefs.dark_parts_shading": "שמירה על צורת חלקים כהים", + "prefs.dark_parts_shading_help": "הצללת התצוגה באור ליניארי עם תאורת שמיים רכה, כך שפאות כהות שומרות על מעבר גוונים במקום להפוך לשחורות", "prefs.dead_zone_note": "הפס המקווקו הוא האזור המת: תנועה בתוכו לא נלקחת בחשבון.", "prefs.default": "ברירת מחדל", - "prefs.design": "ברירות מחדל לתכן", - "prefs.design_note": "ההגדרות שתכנים חדשים מתחילים איתן. תכנים פתוחים שומרים על ההגדרות שלהם.", + "prefs.design": "תכנון", + "prefs.design_note": "במה מתחילים תכנונים חדשים.", + "prefs.design_tools.ask": "שאלה", + "prefs.design_tools.degrees": "מעלות", + "prefs.design_tools.double_click_help": "או לעריכת רכיב מקושר במקומו.", + "prefs.design_tools.ghost": "הצגת המיקום הקודם של חלקים שהוזזו כרפאים", + "prefs.design_tools.hole_moves_help": "בחירה חוזרת בפאה מזיזה את החור במקום להסירו.", + "prefs.design_tools.hole_snaps_help": "אמצע הפאה ומרכזי הקצוות העגולים שלה.", + "prefs.design_tools.imported_files": "קבצים מיובאים", + "prefs.design_tools.note": "הערה", + "prefs.design_tools.off": "כבוי", + "prefs.design_tools.placement_group": "משען, בליטה, חיבור נצמד", + "prefs.design_tools.rows": "שורות", "prefs.devices": "עכבר תלת־ממדי", "prefs.dialog_buttons": "לחצני תיבות דו־שיח", "prefs.dialogs": "תיבות דו־שיח", "prefs.dialogs_edge": "בקצה התצוגה", "prefs.dialogs_left_column": "בעמודה השמאלית", "prefs.dialogs_note": "היכן נפתחות תיבות הדו־שיח של הפקודות: מעוגנות בקצה התצוגה, או בעמודה השמאלית במקום הדפדפן וההיסטוריה, שחוזרים כפי שהיו כשהתיבה נסגרת.", + "prefs.dimension_step_angle": "מה שהחצים בחלון, למעלה/למטה והגלגלת מוסיפים לזווית", + "prefs.dimension_step_length": "מה שהחצים בחלון, למעלה/למטה והגלגלת מוסיפים לאורך", + "prefs.dimension_steps": "צעדי החלון", + "prefs.dimension_values": "ערכי מידות", + "prefs.dimension_values_note": "היכן מקלידים את ערך המידה. לחלון יש חצים שמשנים אותו בצעדים; כלי המידה מציב קודם את הטקסט.", + "prefs.dimension_values_view": "בתצוגה", + "prefs.dimension_values_window": "בחלון", "prefs.display": "תצוגה", "prefs.edges": "מקצועות והצללה", "prefs.extend": "הרחבה", "prefs.extra_navigation": "Ctrl עם גרירה שמאלית במקום ריק מסובב את המבט; החזקת Space מזיזה אותו.", + "prefs.extrude_view_isometric": "סיבוב התצוגה לאיזומטרית בפתיחת שליפה", + "prefs.extrude_view_return": "חזרה לתצוגה הקודמת בסגירת שליפה", "prefs.follows_os": "לפי מערכת ההפעלה", "prefs.font": "גופן", "prefs.font_fallback": "תווים שחסרים בגופן הנבחר מוצגים בגופן המובנה, כך שאף תווית לא מופיעה כריבוע ריק.", "prefs.font_sample": "טקסט לדוגמה בגופן · Ø12.50 mm · 45.0° · 0123456789", "prefs.font_unreadable": "לא ניתן היה לקרוא את הגופן שנבחר.", "prefs.general": "כללי", - "prefs.general_note": "שפה, שמירה ועדכונים.", + "prefs.general.active": "פעיל", + "prefs.general.crash_reports": "דוחות קריסה", + "prefs.general.edited": "נערך", + "prefs.general.held": "נכלל", + "prefs.general.import": "ייבוא...", + "prefs.general.last_check": "בדיקה אחרונה: {time}", + "prefs.general.minutes": "דקות", + "prefs.general.name_setup": "תנו שם להגדרה זו", + "prefs.general.profile_name": "שם הפרופיל", + "prefs.general.save_new": "שמירה כחדש", + "prefs.general.step_import": "STEP וייבוא", + "prefs.general.this_computer": "מחשב זה", + "prefs.general_note": "פרופילים, שפה, קבצים ועדכונים.", "prefs.gesture_orbit": "סיבוב מבט", "prefs.gesture_pan": "הזזת מבט", "prefs.gesture_zoom": "זום", @@ -1888,18 +2377,40 @@ "prefs.graphics_card_auto": "אוטומטי", "prefs.graphics_card_missing": "הכרטיס הגרפי השמור אינו זמין; נעשה שימוש באפשרות אוטומטי.", "prefs.graphics_card_restart": "ייכנס לתוקף אחרי הפעלה מחדש של SolidCraft. WGPU_ADAPTER_NAME גובר על בחירה זו.", + "prefs.graphics_card_unused": "כרטיס המסך השמור לא שימש לחלון זה; הכרטיס שבשימוש מוצג בעזרה › אודות ובשורת המצב. נסו אוטומטי, או הגדירו את WGPU_ADAPTER_NAME לחלק ייחודי משם הכרטיס.", "prefs.graphics_note": "איזון בין מהירות לחלקות. כל בחירה מציגה את השפעתה על דוגמה.", + "prefs.graphics_page.current_view": "התצוגה הנוכחית", + "prefs.graphics_page.fastest": "המהיר ביותר", + "prefs.graphics_page.fold_items": "קיפול פריטים", + "prefs.graphics_page.in_view": "בתצוגה", + "prefs.graphics_page.live_details": "פרטים בזמן אמת", + "prefs.graphics_page.own_mix": "התמהיל שלך", + "prefs.graphics_page.quick_measure": "מדידה מהירה", + "prefs.graphics_page.reference_geometry_through_bodies": "גאומטריית ייחוס דרך גופים", + "prefs.graphics_page.restart": "נדרשת הפעלה מחדש", + "prefs.graphics_page.sharpest": "החד ביותר", + "prefs.graphics_page.single_surface_analysis": "ניתוח משטח יחיד", + "prefs.graphics_page.status_chips": "תגיות מצב", + "prefs.graphics_page.subtitle": "איזון בין מהירות לחלקות.", + "prefs.graphics_page.supersampling": "דגימת־על", + "prefs.graphics_page.supersampling_adaptive": "רק כל עוד התצוגה נייחת", + "prefs.graphics_page.surfaces_edges": "משטחים וקצוות", + "prefs.graphics_page.view_bar": "גם בסרגל התצוגה", "prefs.graphics_presets_note": "הגדרות קבועות מראש קובעות יחד את הבחירות שלמטה.", + "prefs.hide_constraint_glyphs_zoomed_out": "הסתרת סמלי אילוצים בהקטנה", + "prefs.hide_constraint_glyphs_zoomed_out_note": "סמלי האילוצים נעלמים כשהשרטוט מוקטן מספיק כדי שלא יעמיסו על התצוגה. כבוי: הם נשארים בגודל מסך קבוע בכל זום.", "prefs.history": "ציר הזמן", "prefs.history_origin_bodies": "הצגת הראשית והגופים למעלה", "prefs.history_origin_bodies_note": "ההיסטוריה משמאל או מתחת לדפדפן מתחילה בתיקיית הגופים של הרכיב הפעיל ובראשית, עם סמלי העין והתפריטים כמו בדפדפן. ההיסטוריה למטה לא משתנה.", "prefs.history_play_button": "כפתור הפעלת ציר הזמן בפקדי ציר הזמן", "prefs.history_play_button_note": "מוסיף את הפעלת ציר הזמן בין צעד אחד אחורה לצעד אחד קדימה בפקדי ציר הזמן. אפשר גם ללחוץ לחיצה ימנית על הפקדים כדי להציג או להסתיר אותו.", - "prefs.history_sketches": "סקיצות", + "prefs.history_sketches": "סקיצות בציר הזמן", "prefs.history_sketches_in_order": "לפי הסדר", "prefs.history_sketches_note": "כשהסקיצות מוגדרות ל„מתחת לפיצ'ר שלהן”, ציר הזמן משמאל מציג כל סקיצה רמה אחת פנימה, מתחת לפיצ'ר הראשון שנבנה ממנה, בכל פעם שהוא רחב מספיק להצגת שמות. ציר הזמן בתחתית שומר תמיד על סדר היצירה.", "prefs.history_sketches_under_feature": "מתחת לפיצ'ר שלהן", "prefs.hold_stop_snapping": "החזקה לעצירת ההצמדה", + "prefs.home_fit_size": "גודל בתצוגת בית ובהתאמה", + "prefs.home_fit_size_note": "כמה מהתצוגה המודל ממלא כשתצוגת בית, התאמה, עיצוב שנפתח או שינוי תצוגה בניווט ממסגרים אותו, בין אם ההגדרה שלמטה פעילה ובין אם לא. 100 %: ממלא את התצוגה שבין הלוחות, המצפן וסרגל הניווט.", "prefs.icons_only": "סמלים בלבד", "prefs.imported_file": "קובץ מיובא", "prefs.in_browser": "בעץ התכן", @@ -1908,13 +2419,38 @@ "prefs.interface_language": "שפת הממשק", "prefs.interface_note": "איך SolidCraft נראה והיכן חלקיו ממוקמים.", "prefs.interval_minutes": "{n} דק׳", + "prefs.invert_curved_roll_arrows": "היפוך חצי הגלילה המעוגלים", + "prefs.invert_curved_roll_arrows_note": "שני החצים המעוגלים בפינת הקובייה מסובבים את התצוגה במישור המסך. פועל: החץ עם כיוון השעון מסובב נגד כיוון השעון, והחץ נגד כיוון השעון מסובב עם כיוון השעון. כבוי: כל חץ מסובב את התצוגה לפי העקום שלו.", + "prefs.invert_navigator_arrows": "היפוך חצי סיבוב קוביית התצוגה", + "prefs.invert_navigator_arrows_note": "החצים סביב הקובייה מחוויים את המצלמה לכיוון שהחץ מצביע, כמו ב-Fusion ו-Inventor: החץ שמשמאל מצביע ימימה ומניע את המצלמה ימימה. כבוי: החץ מסובב את הקובייה אל הצד שבו הוא יושב, כך שחץ שמאל מניע את המצלמה שמאלה. חצי הגלילה המעוגלים אינם מושפעים.", + "prefs.keep_work_on_tab_switch": "השארת תיבות דו־שיח וכלים פתוחים במעבר בין עיצובים", + "prefs.keep_work_on_tab_switch_note": "כל לשונית עיצוב שומרת את תיבת הדו־שיח או הכלי הפתוחים בה, עם מה שבחרת והקלדת בהם, ואת לשונית סרגל הכלים שלה. הם מחכים לך כשתחזור לעיצוב. כבוי: מעבר בין עיצובים מבטל אותם ומציג את הלשונית מודל.", "prefs.labels": "תוויות", + "prefs.language_system": "מערכת", "prefs.layout": "פריסה", "prefs.layout_note": "הפריסה הדחוסה מצמידה חלוניות לשולי החלון. שקיפות עץ התכן זמינה בפריסה הצפה. את צד העוזר אפשר לשנות בעמוד העוזר.", + "prefs.layout_page.active_commands": "הדגשת פקודות פעילות", + "prefs.layout_page.always": "תמיד", + "prefs.layout_page.card": "כרטיס", + "prefs.layout_page.column": "עמודה", + "prefs.layout_page.hover": "מעבר עכבר", + "prefs.layout_page.icons_labels": "סמלים + תוויות", + "prefs.layout_page.ok_cancel": "אישור וביטול", + "prefs.layout_page.on_hover": "בעת מעבר עכבר", + "prefs.layout_page.open": "פתיחה", + "prefs.layout_page.origin_bodies": "הראשית והגופים למעלה", + "prefs.layout_page.panels": "חלוניות", + "prefs.layout_page.pinned_menus": "השמטת פקודות מוצמדות מהתפריטים", + "prefs.layout_page.play_history": "כפתור הפעלת ציר הזמן", + "prefs.layout_page.slot_count": "{count} מתוך {max} משבצות", + "prefs.layout_page.view_corner": "גם בפינת התצוגה", + "prefs.layout_page.window": "חלון", "prefs.left": "שמאל", "prefs.left_click": "לחיצה שמאלית", "prefs.line_drag_draws_one": "לחיצה וגרירה משרטטות קו אחד", "prefs.line_drag_draws_one_note": "בכלי הקו, לחיצה, גרירה ושחרור משרטטים קו אחד מנקודת הלחיצה עד נקודת השחרור, והוא מסתיים שם. לחיצות עדיין משרטטות שרשרת. כבוי: גרירה מציבה נקודה היכן שמשחררים, כמו לחיצה.", + "prefs.line_hover_tangent_arc": "השהיה על הנקודה האחרונה של קו עוברת לקשת משיקה", + "prefs.line_hover_tangent_arc_note": "בכלי הקו, אחרי ציור מקטע, התרחקו מהנקודה האחרונה של השרשרת, חזרו אליה והחזיקו את הסמן עליה ללא תנועה: הלחיצה הבאה תסיים קשת משיקה, ואותה מחווה מחזירה לקווים. כבוי: השהיה שם אינה עושה דבר.", "prefs.linked_designs": "תכנים מקושרים", "prefs.live_input": "קלט חי", "prefs.live_preview": "תצוגה מקדימה חיה", @@ -1922,10 +2458,10 @@ "prefs.logo_accent": "צבע הדגשה", "prefs.logo_theme": "צבעי ערכת הנושא", "prefs.max_file_size": "גודל קובץ מרבי לפתיחה", - "prefs.max_file_size_design": "קובצי תכן", + "prefs.max_file_size_design": "הקובץ הגדול ביותר לפתיחה: תכנון", "prefs.max_file_size_flag": "ההפעלה הנוכחית החלה עם --max-file-size {size}, שחל עד סגירת SolidCraft. הגדרות אלה חלות בהפעלה ללא אפשרות זו.", "prefs.max_file_size_note": "ברירות מחדל: 512 MB ו־256 MB; לכל היותר 16 GB. פתיחת קובץ דורשת זיכרון בנפח גדול פי כמה מגודלו. תכן ששומר ייבוא גדול עשוי לדרוש מגבלה גבוהה יותר לקובצי תכן כדי לשמור ולפתוח אותו מחדש.", - "prefs.max_file_size_step": "קובצי STEP וייבוא", + "prefs.max_file_size_step": "הקובץ הגדול ביותר לפתיחה: STEP וייבוא", "prefs.max_file_size_web": "יישום הדפדפן פותח קובצי STEP וייבוא עד 512 MB וקובצי תכן עד 256 MB: לשונית דפדפן אינה יכולה להכיל קבצים גדולים יותר. ביישום למחשב ניתן להעלות מגבלות אלה.", "prefs.megabytes": "MB", "prefs.menu_grid": "סמלים גדולים", @@ -1937,10 +2473,19 @@ "prefs.mouse_heading": "עכבר", "prefs.mouse_mapping": "מיפוי העכבר", "prefs.navigation": "ניווט", + "prefs.navigation.axes_signed": "צירים", + "prefs.navigation.cube_compact": "קובייה", + "prefs.navigation.device": "התקן", + "prefs.navigation.free": "חופשי", + "prefs.navigation.orbit_style": "סגנון סיבוב", + "prefs.navigation.radial_help": "יש להחזיק או להניע במהירות את הלחצן הימני להצגת טבעת כלים.", + "prefs.navigation.turntable": "שולחן מסתובב", "prefs.navigation_note": "איך העכבר, משטח המגע והעכבר התלת־ממדי מזיזים את המבט.", + "prefs.navigator_fit": "התאמת המודל לאחר שינוי תצוגה בניווט התצוגה", + "prefs.navigator_fit_note": "לחיצה על פאה, פינה או חץ בקובייה, או על ציר בגיזמו, גם מביטה אל מרכז המודל מהמרחק האחד שמכיל אותו מכל צד (הכדור החוסם שלו). תצוגת בית משתמשת באותו זום ובאותו מרכז כל עוד זה פעיל, כך שתצוגות שנבחרות אחריה רק מסתובבות. כבוי: התצוגה מסתובבת במקומה ושומרת על היעד ועל הזום.", "prefs.network_host_remove": "הסרה", "prefs.network_locations": "התרת מיקומי רשת בתכנים", - "prefs.network_locations_note": "כבוי: קבצים מקושרים של תכן במחשב אחר (\\\\server\\share) נפתחים רק מהשרתים הרשומים כאן, או אחרי שמתירים שרת כשנשאלים.", + "prefs.network_locations_note": "לארגונים השומרים תכנונים בשרתי קבצים. כשהאפשרות כבויה: רק שרתים שאישרתם.", "prefs.network_locations_section": "מיקומי רשת", "prefs.not_on_gpu": "לא זמין במעבד הגרפי הזה", "prefs.on": "פועל", @@ -1950,20 +2495,32 @@ "prefs.origin_plane_names": "שמות מישורי הראשית", "prefs.origin_plane_names_note": "השמות המוצגים בדפדפן, בתיבות הדו־שיח וברשימות. {top} הוא XY, {front} הוא XZ ו־{right} הוא YZ, כש־Z למעלה. פקודות, סקריפטים ותכנונים שמורים שומרים על XY, XZ ו־YZ.", "prefs.overall_speed": "מהירות כללית", + "prefs.parameter_list_rows": "שורות ברשימת הפרמטרים", + "prefs.parameter_list_rows_tip": "מספר הפרמטרים המרבי שמקש חץ למטה מציג בתיבת ביטוי ריקה.", "prefs.persistent_ribbon_pressed": "הדגשת פקודות פעילות ברצועת הכלים", "prefs.persistent_ribbon_pressed_help": "הדגשת פקודות ברצועת הכלים כל עוד ההשפעות שלהן פעילות. כבו אפשרות זו כדי לשמור על המראה הניטרלי הקודם ועל עזרת הפקודות.", "prefs.perspective_fov": "שדה ראייה", "prefs.placement": "מיקום", + "prefs.plugins_enabled": "מופעל", + "prefs.plugins_installed": "מותקנים", + "prefs.plugins_intro": "תוספים מבודדים.", + "prefs.plugins_show_folder": "להציג את תיקיית התוספים", "prefs.prefer_free_sketch_points": "העדפת נקודות סקיצה ניתנות להזזה כשנקודות חופפות", "prefs.preview_choices": "תצוגה מקדימה של הבחירות שלך", + "prefs.preview_tint_new_faces": "צביעת משטח חדש בתצוגה מקדימה", + "prefs.preview_tint_new_faces_help": "תצוגה מקדימה של פעולה שמשנה גוף יכולה לצבוע את המשטח שנוסף בצבע התצוגה המקדימה. כשהאפשרות כבויה הגוף מצויר בצבעו שלו.", + "prefs.print_face_highlight": "הדגשת פאת ההדפסה", + "prefs.print_face_highlight_tip": "עד כמה חזק צובעים ומקיפים את פאת ההדפסה של גוף בתצוגה. ‏0 % אינו מציג הדגשה.", "prefs.profile_active": "פרופיל פעיל", "prefs.profile_applied": "הפרופיל הוחל.", "prefs.profile_changed": "ההגדרות השתנו מאז שהפרופיל נשמר. „שמירה“ מכניסה אותן לפרופיל.", "prefs.profile_deleted": "הפרופיל נמחק.", - "prefs.profile_export": "ייצוא…", + "prefs.profile_export": "ייצוא", "prefs.profile_exported": "הפרופיל יוצא.", - "prefs.profile_imported": "הפרופיל יובא. בחרו בו תחת „פרופיל פעיל“ כדי לעבור אליו.", + "prefs.profile_imported": "הפרופיל יובא.", "prefs.profile_name_hint": "שם הפרופיל, למשל מחשב נייד", + "prefs.profile_operations": "מדידת זמני פעולות", + "prefs.profile_operations_note": "מתעד כמה זמן לוקחות קריאות SMLib, פעולות ליבה, תכונות, פקודות וייבוא. סוכנים קוראים זאת עם diagnostics.profile.", "prefs.profile_rename": "שינוי שם", "prefs.profile_renamed": "שם הפרופיל שונה.", "prefs.profile_save": "שמירה", @@ -1977,26 +2534,71 @@ "prefs.quality_fastest": "המהיר ביותר", "prefs.quality_slowest": "האיטי ביותר", "prefs.quality_smoother": "חלק יותר", + "prefs.quick_measure": "מדידה מהירה בפינת התצוגה", + "prefs.quick_measure_note": "מציג את מידות הבחירה בפינה הימנית התחתונה של התצוגה, מעל ההיסטוריה: אורך מקצוע (או Ø ו-R למקצוע עגול), שטח פאה, מיקום נקודה, המרחק והזווית בין שני פריטים, והסכום של כמה מקצועות או פאות. לחיצה מעתיקה אותו.", "prefs.render_previous_geometry_budget": "שימוש בתקציב הגאומטריה הקודם לתצוגה מקדימה של רינדור", "prefs.render_previous_geometry_budget_help": "שחזור מגבלת הגאומטריה הקבועה הקודמת (512 MiB במחשב שולחני של 64 סיביות, 128 MiB בפלטפורמות אחרות) במקום התקציב המבוסס על ההתקן.", "prefs.reports_saved": "{n} שמורים", + "prefs.restore_page_defaults": "שחזור ברירות המחדל של עמוד זה", + "prefs.ribbon_click_ends_tool": "לחיצה על הלחצן של הכלי הפעיל מסיימת אותו", + "prefs.ribbon_click_ends_tool_note": "לחיצה על לחצן הסרט המודגש של כלי השרטוט שבשימוש מסיימת את הכלי, כך שלחיצות בתצוגה בוחרות שוב. כבוי: הלחיצה מפעילה את הכלי מחדש.", "prefs.ribbon_reveal": "הצגת תוצאות חיפוש בסרט", "prefs.ribbon_reveal_note": "מעבר עם הסמן מעל תוצאה בחיפוש פקודות מראה היכן הפקודה נמצאת בסרט: הלשונית, הכפתור או השורה שלה בתפריט הנפתח של לוח. פקודה שהופעלה מהחיפוש מהבהבת שם, ופקודה פעילה מתפריט נפתח מסמנת את הלוח שלה.", "prefs.right_click": "לחיצה ימנית", - "prefs.saving": "שמירה אוטומטית ושחזור", + "prefs.saving": "הפעלה ושמירה", "prefs.scale_note": "גם Ctrl + / Ctrl − בחלון. הכפתורים בגודל 28 px ב־100%.", "prefs.scale_text": "קנה מידה וטקסט", "prefs.search": "חיפוש הגדרות", "prefs.search_empty": "אין הגדרות תואמות", + "prefs.section_hatch": "קווקוו חתך", + "prefs.section_hatch_by_part": "לפי חלק", + "prefs.section_hatch_one": "סגנון אחד", "prefs.select": "בחירה", "prefs.select_one_item": "בחירת פריט אחד", + "prefs.select_other_hidden": "בחירת גאומטריה מוסתרת באמצעות בחירה אחרת", + "prefs.select_other_hidden_help": "מופעל: כולל גופים, סקיצות וקצוות מוסתרים בקרבת הסמן. כבוי: שימוש ברשימה המקורית של גאומטריה גלויה מתחת לסמן.", "prefs.selecting": "בחירה", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift מוסיף בלבד; Ctrl / Cmd מחליף מצב", "prefs.shift_add_note": "כשפועל: Shift מוסיף, Ctrl / Cmd מחליף מצב. כשכבוי (ברירת מחדל): שניהם מחליפים מצב.", "prefs.shortcuts": "קיצורים", + "prefs.shortcuts_import": "ייבוא", + "prefs.shortcuts_intro": "מקשים לכל פקודה.", + "prefs.shortcuts_not_assigned": "לא הוקצה", + "prefs.shortcuts_press": "יש ללחוץ על מקש...", "prefs.single_surface_analysis": "שימוש בניתוח משטח יחיד", "prefs.single_surface_analysis_help": "כשהאפשרות כבויה, הצללת המשטח וניתוח הרציפות יכולים להישאר פעילים יחד. הפעלתה משאירה רק את הניתוח האחרון שהופעל או שונה.", + "prefs.sketch.align_points": "יישור עם נקודות אחרות בסקיצה", + "prefs.sketch.align_points_note": "קווים בשרטוט מיושרים עם נקודות בשני הצירים בו־זמנית.", + "prefs.sketch.auto_dimensions": "הוספת כל המידות לצורות חדשות", + "prefs.sketch.auto_dimensions_note": "ערכים מוקלדים וכל מידה שמקבעת את הצורה.", + "prefs.sketch.auto_locate": "מיקום ביחס לראשית הסקיצה", + "prefs.sketch.auto_locate_note": "עם כל המידות.", + "prefs.sketch.center_arc": "קשת מנקודת מרכז עוקבת אחר הסמן", + "prefs.sketch.click_selects": "לחיצה בוחרת", + "prefs.sketch.conflict_colour": "צבע התנגשות", + "prefs.sketch.drawing": "שרטוט", + "prefs.sketch.exit_keep": "שמירה", + "prefs.sketch.exit_previous": "חזרה לתצוגה הקודמת", + "prefs.sketch.exit_unless_rotated": "אלא אם סובבה", + "prefs.sketch.faces_edges": "פאות וקצוות", + "prefs.sketch.hide_glyphs": "הסתרת סמלים בהתרחקות", + "prefs.sketch.marks": "סימונים בסקיצה", + "prefs.sketch.note": "שרטוט, הצמדה ובחירה.", + "prefs.sketch.opening_closing": "פתיחה וסגירה", + "prefs.sketch.prefer_free_points": "העדפת נקודות ניתנות להזזה כשהן חופפות", + "prefs.sketch.project_options": "בקשת אפשרויות ההיטל תחילה", + "prefs.sketch.recent_snap": "הצמדה למפגש שני קווי עזר", + "prefs.sketch.select_other_hidden": "בחירת אחר כוללת גאומטריה מוסתרת", + "prefs.sketch.shortcut_cycles_modes": "לחיצה חוזרת על קיצור מחליפה מצב", + "prefs.sketch.shortcut_cycles_modes_tip": "כבוי: הכלי מתחיל מחדש.", + "prefs.sketch.snapping_guides": "הצמדה וקווי עזר", + "prefs.sketch.state_icons": "סמלי מצב", + "prefs.sketch.tracking_guides": "קווי עזר למרכזים ולנקודות אמצע", + "prefs.sketch.tracking_guides_note": "קווי עזר אופקיים ואנכיים זמניים ממרכזים ומנקודות אמצע של קצוות בעת ריחוף.", + "prefs.sketch.tracking_points": "קווי עזר גם מנקודות הסקיצה", + "prefs.sketch.unless_turned_note": "חזרה אם לא סובבה", + "prefs.sketch.whole_bodies": "גופים שלמים", "prefs.sketch_align_points": "יישור לנקודות סקיצה אחרות בזמן השרטוט", "prefs.sketch_align_points_note": "בזמן השרטוט, נקודה מתיישרת אופקית עם נקודת סקיצה אחת ואנכית עם אחרת בו-זמנית, עם קו עזר מנוקד, והלחיצה שומרת את שני היישורים. כבוי: רק עם הנקודה הקודמת, ציר אחד בכל פעם.", "prefs.sketch_conflict_colour": "גאומטריה סותרת בצבע הסתירה", @@ -2007,6 +2609,8 @@ "prefs.sketch_exit_view.previous": "חזרה לתצוגה הקודמת", "prefs.sketch_exit_view.unless_rotated": "חזרה אלא אם התצוגה סובבה", "prefs.sketch_exit_view_note": "לאן התצוגה עוברת אחרי סיום סקיצה, ביטול או Esc כפול.", + "prefs.sketch_face_activates_part": "שרטוט על פאה של חלק הופך את החלק לפעיל", + "prefs.sketch_face_activates_part_note": "שרטוט שמתחיל על פאה של גוף ברכיב אחר מפעיל קודם את הרכיב הזה, כך שהשרטוט שייך לו ונשאר עם החלק בסייר. החלק נשאר פעיל אחר כך. כבוי: השרטוט שייך לרכיב הפעיל.", "prefs.sketch_open_look_at": "הפניית התצוגה אל הסקיצה בפתיחתה", "prefs.sketch_open_look_at_note": "כבוי: יצירה או עריכה של סקיצה משאירות את התצוגה כפי שהיא. «מבט אל» מפנה את התצוגה אל הסקיצה כשרוצים.", "prefs.sketch_recent_snap": "הצמדה אוטומטית למרכזים ולנקודות אמצע אחרונים", @@ -2020,22 +2624,42 @@ "prefs.sketch_tab_always_note": "לשונית הסקיצה נשארת ברצועה, מיד אחרי מודל, גם כשאין סקיצה פתוחה. כלי השרטוט בה מתחילים אז סקיצה על המישור או הפאה שנבחרו, או על המישור שתבחרו בהמשך, והכלי מוכן בה.", "prefs.sketch_tracking_guides": "קווי עזר ליישור מרכזים ונקודות אמצע", "prefs.sketch_tracking_guides_note": "יש לרחף עם הסמן מעל מרכז מעגל או נקודת אמצע של צלע ישרה, ואז להזיז אותו אופקית או אנכית כדי להציג קו עזר מקווקו זמני.", + "prefs.sketch_tracking_points": "קווי עזר ליישור מנקודות קצה ומפינות בזמן שרטוט", + "prefs.sketch_tracking_points_note": "כשכלי שרטוט ממתין לנקודה, ריחוף מעל קצה של קו או קשת, פינה של מלבן או נקודה חופשית מציג את אותו קו עזר מקווקו זמני כמו במרכז או בנקודת אמצע. כבוי: מרכזים ונקודות אמצע בלבד.", "prefs.sketching": "שרטוט סקיצות", "prefs.snap_drawing_note": "בזמן ציור או גרירה של נקודת סקיצה.", "prefs.source": "מקור", "prefs.speed": "מהירות", "prefs.stand_up_note": "אחרי שקובץ STEP או IGES נפתח כש־Z למעלה, להציע רבע סיבוב סביב X.", - "prefs.stand_up_unknown": "לקבצים מתוכנות לא מוכרות", + "prefs.stand_up_unknown": "קבצים מתוכנות לא מוכרות", "prefs.stand_up_unknown.ask": "לשאול בתיבת דו־שיח", "prefs.stand_up_unknown.note": "להציג הערה", "prefs.stand_up_unknown.off": "לא להציע", - "prefs.stand_up_unknown_note": "איך ההצעה מוצגת כשכותרת הקובץ לא מציינת תוכנה שידוע שהיא שומרת עם Y למעלה. הערה מוצגת רק כשנראה שהקובץ שוכב על גבו; ״לשאול בתיבת דו־שיח״ שואל על כל קובץ כזה, כמו קודם.", + "prefs.stand_up_unknown_note": "כיצד מוצעת האפשרות כשהקובץ אינו מציין תוכנה מוכרת.", "prefs.status_bar": "שורת מצב", "prefs.status_bar_note": "פס דק לאורך הקצה התחתון של החלון מציג מה נערך, את מצב הסקיצה הפתוחה בצבע שלו ואת יחידות התכנון; לחיצה על היחידות משנה אותן. מצב הסקיצה לא מוצג אז עוד בפינת התצוגה.", "prefs.status_done": "הושלם", "prefs.status_error": "שגיאה", "prefs.status_selected": "נבחר", "prefs.status_warning": "אזהרה", + "prefs.structure.appearance": "מראה", + "prefs.structure.appearance_note": "צבעים, טקסט ונגישות.", + "prefs.structure.in_profile": "כלול בפרופיל", + "prefs.structure.layout": "פריסה", + "prefs.structure.layout_note": "מיקום חלקי החלון.", + "prefs.structure.look": "מראה", + "prefs.structure.measure_pointer": "מדידה ומצביע", + "prefs.structure.mouse3d": "עכבר תלת־ממדי", + "prefs.structure.mouse3d_note": "SpaceMouse ו־SpaceNavigator.", + "prefs.structure.navigation_note": "עכבר ומשטח מגע. לעכבר התלת־ממדי יש עמוד משלו.", + "prefs.structure.profile": "פרופיל", + "prefs.structure.profile_edited": "השתנה מאז השמירה", + "prefs.structure.profile_hover": "נשמר בפרופילי הגדרות", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "סקיצה", + "prefs.structure.tools": "כלים", + "prefs.structure.tools_note": "אופן הפעולה של כלי המידול.", + "prefs.structure.work": "עבודה", "prefs.supersampling_brief": "מצייר את המבט גדול יותר ומקטין אותו: חד מאוד, וכבד יותר.", "prefs.tab_accent_note": "צבע ההדגשה עוקב אחר הלשונית הפעילה", "prefs.theme_file": "קובץ ערכת נושא", @@ -2047,6 +2671,21 @@ "prefs.theme_follow_off": "כבוי", "prefs.theme_follow_stop": "הפסקת המעקב", "prefs.theme_import_hint": "לחצו כדי לבחור קובץ ערכת נושא, שחררו קובץ כאן, או הקישו Ctrl+V ‏(Cmd+V ב-Mac) אחרי שהעתקתם ערכת נושא", + "prefs.theme_notice_dismiss": "הסתרה", + "prefs.theme_option_blur": "טשטוש מאחורי לוחות", + "prefs.theme_option_blur_help": "טשטוש מאחורי לוחות שקופים למחצה, בפיקסלים פיזיים. אפס מכבה את הטשטוש.", + "prefs.theme_option_invalid": "הערך השמור עבור {option} אינו תקין; נעשה שימוש בברירת המחדל של ערכת הנושא. הערך השמור נשמר ללא שינוי.", + "prefs.theme_option_opacity": "אטימות", + "prefs.theme_option_opacity_help": "כוונון אטימות הלוחות הצפים. רמת אטימות מינימלית שומרת על קריאות הטקסט על רקע צבעי חלון התצוגה.", + "prefs.theme_option_tab_colours": "צבעי כרטיסיות", + "prefs.theme_option_tab_colours_help": "השתמש בצבעי הלוח ואזור התצוגה של ערכת נושא זו עבור כל כרטיסייה ברצועת הכלים.", + "prefs.theme_option_tab_fade_ms": "מעבר בין כרטיסיות", + "prefs.theme_option_tab_fade_ms_help": "שנה בהדרגה את צבעי הלוח ואזור התצוגה בעת מעבר בין כרטיסיות. ערך אפס מבצע את המעבר מיד.", + "prefs.theme_options_badge": "אפשרויות", + "prefs.theme_options_more": "עוד · {count}", + "prefs.theme_options_newer": "ערכת נושא זו דורשת גרסה חדשה יותר של SolidCraft. לאחר השדרוג יש לייבא שוב את ערכת הנושא המקורית כדי לשחזר את הגדרות האפשרויות שלה.", + "prefs.theme_options_reset": "איפוס", + "prefs.theme_options_unavailable": "לא זמין במכשיר זה", "prefs.theme_paste": "הדבקת ערכת נושא", "prefs.theme_paste_none": "בלוח אין ערכת נושא של SolidCraft", "prefs.timeline_half_hour": "−30 דק׳", @@ -2068,13 +2707,29 @@ "prefs.under_cursor": "מתחת לסמן", "prefs.units_precision": "יחידות ודיוק", "prefs.updates": "עדכונים", + "prefs.validation": "בדיקת גופים", + "prefs.validation.each_feature": "פעם אחת לכל תכונה", + "prefs.validation.each_step": "אחרי כל שלב", + "prefs.validation.label": "הבדיקה המלאה של הקרנל", + "prefs.validation.off": "כבוי (ניסיוני)", + "prefs.validation_note": "אחרי כל שלב: בודק כל סחיפה, פעולה בוליאנית ועיגול.\nפעם אחת לכל תכונה: בודק את התוצאה של כל תכונה פעם אחת.\nכבוי (ניסיוני): אין בדיקה.", + "prefs.value_boxes_in_view": "הצגת ערכים לצד הידיות שלהם", + "prefs.value_boxes_in_view_tip": "מרחק ההבלטה, רדיוס העיגול... בתיבה בתצוגה.", "prefs.view": "התנהגות המבט", "prefs.view_confirm_corner": "אישור וביטול בפינת התצוגה", "prefs.view_confirm_corner_note": "כשתיבת דו־שיח או סקיצה פתוחות, סימן וי וסימן איקס בפינה הימנית העליונה של התצוגה עושים את מה שעושים אישור וביטול של תיבת הדו־שיח, או מסיימים ומבטלים את הסקיצה. ניווט התצוגה זז אל מתחתיהם.", "prefs.viewport": "אזור התצוגה", + "prefs.viewport_analysis_status": "הצגת מצב ניתוח בחלון התצוגה", + "prefs.viewport_analysis_status_help": "הצגת ניתוחים פעילים מעל חלון התצוגה ופתיחת המקרא מכל פריט. Esc מכבה את הניתוח האחרון. כיבוי האפשרות משחזר את המקרא בפינה ואת פעולת Esc הקודמת.", "prefs.viewport_background": "רקע", "prefs.viewport_background_colour": "צבע", "prefs.viewport_background_theme": "מעבר הצבעים של ערכת הנושא", + "prefs.viewport_section_status": "הצגת מצב חתך בחלון התצוגה", + "prefs.viewport_section_status_help": "הצגת הגדרת החתך בחלון התצוגה. Escape ולחצן הסרט הפעיל מכבים את החתך. כיבוי האפשרות שומר על בקרי החתך הקודמים.", + "prefs.viewport_status_details": "פרטים בזמן אמת בחלון התצוגה", + "prefs.viewport_status_details_help": "עריכת הגדרות הניתוח והחתך הפעילים בכרטיסי פרטים אחידים. השבתה מחזירה את מקראי הניתוח לקריאה בלבד ואת תיבת הדו-שיח של חתך.", + "prefs.viewport_status_summary": "סיכום פריטי מצב בחלון התצוגה", + "prefs.viewport_status_summary_help": "קיבוץ שלושה פריטי מצב או יותר לתג סיכום אחד. כיבוי האפשרות משאיר כל פריט בשורה המלאה.", "prefs.wheel": "גלגלת", "prefs.wheel_trackpad": "גלגלת ומשטח מגע", "prefs.workspace": "סביבת עבודה", @@ -2092,6 +2747,17 @@ "recovery.just_now": "זה עתה", "recovery.min_ago": "לפני {count} דק'", "recovery.never_saved": "לא נשמר מעולם", + "refused.change": "לא ניתן היה לשנות את {body}.", + "refused.cut": "לא ניתן היה לחתוך את {body}.", + "refused.face_curved": "אחת הפאות המעוקלות שלו אינה ניתנת לשימוש במידול.", + "refused.face_flat": "אחת הפאות השטוחות שלו אינה ניתנת לשימוש במידול.", + "refused.face_freeform": "אחת הפאות החופשיות שלו אינה ניתנת לשימוש במידול.", + "refused.face_rounded": "אחת הפאות המעוגלות שלו אינה ניתנת לשימוש במידול.", + "refused.faces_apart": "הפאות שלו אינן נפגשות בצמידות מספקת לשימוש במידול.", + "refused.intersect": "לא ניתן היה לחתוך עם {body}.", + "refused.join": "לא ניתן היה לחבר אל {body}.", + "refused.repair": "תיקון חלק", + "refused.show_face": "הצגת הפאה", "render.adaptive_absolute": "רצפת שגיאת RGB מוחלטת", "render.adaptive_coverage": "יעד שגיאת כיסוי", "render.adaptive_enable": "הקצאת דגימות באמצעות דגימות גישוש עצמאיות", @@ -2203,6 +2869,10 @@ "render.base_color": "צבע בסיס · sRGB", "render.base_metallic": "שיעור מתכתיות", "render.base_opaque_only": "עורך זה שומר על משמעות של גוף אטום. להעברה אופטית יש להשתמש בפקדי הזכוכית המפורשים.", + "render.batch_all_shots": "כל הצילומים ({count})", + "render.batch_empty": "שמור צילום לפני רינדור כל הצילומים.", + "render.batch_limit": "רינדור כל הצילומים מוגבל ל-32 צילומים.", + "render.batch_status": "{running} רצים · {waiting} ממתינים", "render.bloom_enable": "זוהר בתצוגה", "render.bloom_help": "זוהר יצירתי לפלט בלבד מהבהרות ליניאריות חיוביות, המתפשט בשלושה מעברי תיבה מנורמלים. הרדיוס בפיקסלים של הפלט. נוסף באור תצוגה ליניארי לפני sRGB; אינו עדשה, אינו אפקט נפחי ואינו שיפור התכנסות. ה־EXR הגולמי אינו משתנה.", "render.bloom_opaque": "זוהר דורש פלט אטום. PNG שקוף נדחה, ואינו משוטח בשקט.", @@ -2313,6 +2983,13 @@ "render.choose_look": "בחר קודם מראה במראות", "render.chromatic_offset": "היסט כרומטי בקצוות", "render.clear_stage": "הסרת הבמה השמורה", + "render.compare_divider": "מחיצת השוואה", + "render.compare_live": "חי", + "render.compare_live_preview": "תצוגה חיה", + "render.compare_render": "רינדור {number}", + "render.compare_side": "רינדור {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} שנ׳ · {renderer} · נקלט בגרסה {revision}", + "render.compare_swap": "החלף", "render.copy_request": "העתקת JSON", "render.cpu_aa_help": "דגימות מרחביות: יותר דגימות משפרות קצוות ומאריכות את זמן ההדמיה.", "render.cpu_area_add": "הוספת אור מלבני ב־CPU", @@ -2953,7 +3630,9 @@ "render.output_ready": "מוכן לרינדור", "render.output_run_check": "הפעל בדיקה", "render.output_size_limit": "{method}: עד {dimension} פיקסלים לצלע ו-{pixels} פיקסלים. הגודל הגדול ביותר שמתאים: {width} × {height}.", + "render.output_size_method_profile": "כדי לרנדר {width} × {height}, יש לבחור ב-{method} עם פרופיל משאבי CPU {profile} או בגודל קטן יותר.", "render.output_size_ok": "הגודל תקין · {width} × {height} פיקסלים", + "render.output_size_profile": "כדי לרנדר {width} × {height}, יש לבחור בפרופיל משאבי CPU {profile} או בגודל קטן יותר.", "render.output_swap_orientation": "החלפת רוחב וגובה", "render.output_tools_inspector": "ערוך גודל ופורמט במפקח הפלט.", "render.output_view_image": "הצג תמונה", @@ -3060,6 +3739,10 @@ "render.result_retained": "מוצגת התמונה הגמורה האחרונה; הדמיה חדשה יותר לא החליפה אותה.", "render.result_sequence": "נקודת ביקורת", "render.result_title": "תוצאת הדמיה", + "render.results_choose": "תוצאות שנשמרו", + "render.results_label": "רינדור {number} · {shot} · {seconds} שנ׳", + "render.results_stale_label": "{result} [ישן]", + "render.results_unnamed": "תמונה", "render.return_design": "חזרה לתכן", "render.review_stale": "סקירה זו אינה עדכנית. יש לפתור או לבדוק שוב לפני ההחלה.", "render.ribbon_aging": "הזדקנות", @@ -3166,6 +3849,7 @@ "render.size_custom": "מותאם…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · נדרש {profile}", "render.size_presets": "הגדרות גודל מוכנות", "render.size_presets_pending": "יגיע עם עורך הפלט", "render.size_preview": "תצוגה מקדימה", @@ -3431,11 +4115,11 @@ "select two components": "יש לבחור שני רכיבים", "set by the sketch's lines": "נקבע לפי קווי הסקיצה", "settings.display_quality_note": "ברמות עדינות יותר, פאות ומקצועות מעוקלים מוצגים חלקים יותר ויצירת הרשת אורכת זמן רב יותר. רק אזור התצוגה משתנה, לא התכן ולא קובצי הייצוא.", - "settings.double_click_components": "לחיצה כפולה על רכיב מפעילה אותו, או עורכת רכיב מקושר במקומו", + "settings.double_click_components": "לחיצה כפולה על רכיב להפעלתו", "settings.frame_rate_details_note": "מוסיף גרף של זמני התמונות האחרונות עם המשולשים שצוירו מעליו, היסטוגרמה של זמני התמונות ואת מה שה־GPU צייר. לחיצה על קצב התמונות בתצוגה מציגה או מסתירה אותם.", "settings.frame_rate_note": "הצגת מספר הפריימים לשנייה בפינה הימנית התחתונה של התצוגה. כל עוד האפשרות פעילה, התצוגה מצוירת מחדש ברציפות.", - "settings.insert_lists_open_designs": "הוספת תכן מציגה קודם את התכנים הפתוחים בלשוניות אחרות", - "settings.measure_axis_distances": "הצגת מרחקי X/Y/Z", + "settings.insert_lists_open_designs": "הוספת תכנון מציגה תחילה תכנונים פתוחים", + "settings.measure_axis_distances": "מרחקי צירים במדידה", "settings.measure_axis_distances_help": "הצגת המרחקים לאורך צירי העולם לצד המרחק הכולל כשכלי המדידה פתוח.", "settings.msaa_applies_on_restart": "החלקת הקצוות תחול בהפעלה הבאה של SolidCraft", "settings.msaa_reset": "{setting}: {requested}× אינו נתמך בהתקן הגרפי הזה; הערך הוא כעת {reset}× (נתמכים: {supported}).", @@ -3445,7 +4129,7 @@ "settings.reset_intro": "ההגדרות האלה לא פועלות במחשב הזה והיו מונעות מ־SolidCraft לעלות, ולכן הן שונו:", "settings.reset_title": "ההגדרות שונו", "settings.supersampling_note": "התצוגה מצוירת ברזולוציה גבוהה יותר ומסוננת כלפי מטה: מקצוות, קווים ורשת חלקים יותר במסכים שמתחת ל־4K. הדבר צורך זמן GPU: בערך 2.25× פיקסלים ב־1.5×, ו־4× ב־2×.", - "settings.update_changed_links": "עדכון תכנים מקושרים שהשתנו כשלשונית מוצגת שוב", + "settings.update_changed_links": "עדכון קישורים שהשתנו בחזרה ללשונית", "settings.window_system_details": "פרטים", "settings.window_system_note_now": "ייכנס לתוקף אחרי הפעלה מחדש. כעת: {now}.", "settings.window_system_wayland_limited": "חלק מהתכונות מוגבלות ב־Wayland מקורי.", @@ -3453,6 +4137,24 @@ "sheet.flange_type_contour": "מתאר", "sheet.flange_type_edge": "מקצוע", "sheet.no_body": "אין גוף פח: יש להתחיל אחד עם אוגן > בסיס, או להמיר לוח לפח עם המרה לפח (יש לבחור את הפאה השטוחה הגדולה שלו)", + "sheet.personal_rules.confirm_delete": "אישור מחיקה", + "sheet.personal_rules.delete": "מחיקה", + "sheet.personal_rules.delete_prompt": "למחוק את הכלל האישי הזה? כללים שכבר נמצאים בתכנים לא ישתנו.", + "sheet.personal_rules.full": "הספרייה האישית כבר מכילה 64 כללים.", + "sheet.personal_rules.invalid_name": "יש להזין שם קצר ללא מעברי שורה או תווי בקרה.", + "sheet.personal_rules.invalid_values": "יש להשלים את ערכי הכלל: כל ערך צריך להיות ניתן לחישוב בתכן זה, עם עובי חיובי ומקדם K בין 0 ל־1.", + "sheet.personal_rules.missing": "הכלל האישי שנבחר כבר אינו זמין.", + "sheet.personal_rules.name": "שם הכלל", + "sheet.personal_rules.name_exists": "כבר קיים כלל אישי בשם הזה. יש להשתמש בשם אחר.", + "sheet.personal_rules.name_hint": "שם ייחודי", + "sheet.personal_rules.overwrite": "שמירת השינויים בכלל האישי שנבחר", + "sheet.personal_rules.rename": "שינוי שם", + "sheet.personal_rules.rule": "כלל אישי", + "sheet.personal_rules.save": "שמירה כחדש", + "sheet.personal_rules.scope": "נשמרים בפרופיל שלך לכל התכנים.", + "sheet.personal_rules.select": "בחירת כלל", + "sheet.personal_rules.title": "כללים אישיים", + "sheet.personal_rules.unsupported": "לכלל הזה יש ערכים שהגרסה הזו אינה יכולה להשתמש בהם.", "shortcut.json_error": "הפרמטרים חייבים להיות JSON: {error}", "shortcut.no_command": "אין פקודה `{id}`; הטקסט שלפני ה־JSON חייב להיות מזהה פקודה", "shortcut.pin": "הצמדה לראש תיבת S", @@ -3489,8 +4191,10 @@ "sketch_text.align_right": "ימין", "sketch_text.bold": "מודגש", "sketch_text.builtin_font": "{family} (מובנה)", + "sketch_text.formula": "התחילו ב־= כדי לבנות את הטקסט מפרמטרים: ='W' + number(Width)", "sketch_text.italic": "נטוי", "sketch_text.loading_fonts": "מחפש גופנים מותקנים…", + "sketch_text.no_bold": "לגופן המובנה אין משקל מודגש: בחר גופן מותקן", "sketch_text.on_path": "הטקסט עוקב אחר המסלול שלו: העקומה קובעת את מיקומו", "sketch_text.path_clear": "הסרת הטקסט מהעקומה", "sketch_text.path_hint": "עקומה בסקיצה שהטקסט עוקב אחריה: יש ללחוץ כאן ואז על העקומה", @@ -3521,11 +4225,20 @@ "the section's profiles must be in one sketch": "הפרופילים של החתך חייבים להיות בסקיצה אחת", "the two origins are on the same component": "שתי הראשיות נמצאות על אותו רכיב", "thread.automatic_size": "גודל אוטומטי", + "thread.chamfer_depth_needed": "נדרש לצורה זו", "thread.designation": "סימון", - "thread.direction": "כיוון ההברגה", + "thread.drill_range": "מקדח יצרן המברז הוא {drill} מ\"מ. הקוטר הקטן התקני של התבריג הפנימי הוא {minor} מ\"מ. מתקבל מקדח מ-{low} עד {high} מ\"מ.", + "thread.drill_range_custom": "המקדח הוא הקוטר הגדול פחות הפסיעה, {drill} מ\"מ. הקוטר הקטן התקני של התבריג הפנימי הוא {minor} מ\"מ. מתקבל מקדח מ-{low} עד {high} מ\"מ.", + "thread.drill_range_taper": "מקדח יצרן המברז הוא {drill} מ\"מ. הקוטר הקטן התקני בסוף התבריג הוא {minor} מ\"מ. מתקבל מקדח מ-{low} עד {high} מ\"מ.", + "thread.end_square": "ישר", + "thread.fade_short": "1.25 P (ISO 3508)", + "thread.fade_standard": "2.5 P (ISO 3508)", + "thread.fits_the_face": "מתאים לפאה, למשל {example}", + "thread.form_bspp": "תבריג צנרת G (ISO 228-1)", + "thread.form_bspt": "תבריג צנרת קוני R, Rc (ISO 7-1)", + "thread.form_npt": "תבריג צנרת קוני NPT (ASME B1.20.1)", + "thread.form_rp": "תבריג צנרת פנימי מקביל Rp (ISO 7-1)", "thread.iso_metric": "ISO מטרי", - "thread.left_hand": "שמאלית", - "thread.right_hand": "ימנית", "thread.select_size": "בחירת גודל", "timeline.delete_after_marker_one": "מחיקת פיצ'ר אחד אחרי סמן ציר הזמן", "timeline.delete_after_marker_other": "מחיקת {count} פיצ'רים אחרי סמן ציר הזמן", @@ -3629,6 +4342,8 @@ "ui.3d_mouse_section": "עכבר תלת־ממדי", "ui.3d_mouse_show_in_view": "הצגת העכבר התלת־ממדי בתצוגה התלת־ממדית", "ui.3d_mouse_show_in_view_tip": "תמונה של העכבר התלת־ממדי בפינה השמאלית התחתונה, שזזה כשמזיזים אותו.", + "ui.3d_mouse_sketch_orbit": "סיבוב סקיצות בעכבר התלת־ממדי", + "ui.3d_mouse_sketch_orbit_tip": "העכבר התלת־ממדי מסובב את התצוגה גם כשסקיצה פתוחה ונראית חזיתית, כמו שהעכבר יכול. כבוי: הוא מזיז ומגדיל את הסקיצה עד שתטה את התצוגה.", "ui.3d_mouse_skip": "ההתקן שלי לא יכול לעשות את זה", "ui.3d_mouse_skip_tip": "מדלג על התנועה הזאת בשני הכיוונים, והכיול משמיט אותה.", "ui.3d_mouse_speed": "מהירות עכבר תלת־ממדי", @@ -3657,6 +4372,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "יש לסובב את הכיפה נגד כיוון השעון, להחזיק ואז לשחרר.", "ui.3d_mouse_switch_cap": "כיול כהתקן חזרה למרכז", "ui.3d_mouse_switch_trackball": "כיול ככדור עקיבה", + "ui.3d_mouse_use_direct": "שימוש במנהל ישיר", + "ui.3d_mouse_use_direct_tip": "קריאת העכבר התלת־ממדי ישירות (hidraw) במקום דרך spacenavd.", "ui.3d_mouse_view_axis": "ציר מבט", "ui.3d_mouse_view_off": "כבוי", "ui.3d_mouse_view_off_tip": "הפרופיל של מנהל ההתקן לעכבר התלת־ממדי מכבה את הציר הזה, ולכן התנועה שלו לא מזיזה את המבט. בחירה כאן בתנועה של ציר אחר מחליפה בין השניים, והתנועה ההיא מפסיקה להזיז את המבט.", @@ -3695,6 +4412,8 @@ "ui.agent_chat_auth_terminal": "יש להריץ את זה במסוף ואז ללחוץ שוב על התחברות:", "ui.agent_chat_auth_title": "התחברות לסוכן", "ui.agent_chat_cancel": "ביטול", + "ui.agent_chat_cancel_timeout": "הסוכן לא הגיב לבקשת העצירה ונותק. יש להתחבר מחדש כדי להמשיך.", + "ui.agent_chat_cannot_start": "מותקן, אך אינו מופעל: {error}", "ui.agent_chat_changes": "שינויים: {n}, צעד ביטול אחד", "ui.agent_chat_changes_n": "{n} שינויים", "ui.agent_chat_changes_of": "{n}/{limit} שינויים", @@ -3703,11 +4422,13 @@ "ui.agent_chat_command": "פקודת הסוכן", "ui.agent_chat_connect": "התחברות", "ui.agent_chat_copy": "העתקה", + "ui.agent_chat_copy_message": "העתק הודעה", "ui.agent_chat_ctx_bodies": "גופים", "ui.agent_chat_ctx_elements": "אלמנטים", "ui.agent_chat_ctx_features": "פיצ'רים", "ui.agent_chat_ctx_more": "+{n} נוספים", "ui.agent_chat_ctx_other": "אחר", + "ui.agent_chat_custom_heading": "מודל מותאם אישית", "ui.agent_chat_custom_hint": "כל תוכנה שמדברת Agent Client Protocol דרך stdin ו־stdout. היא לא מורצת דרך מעטפת (shell).", "ui.agent_chat_denied": "נדחה", "ui.agent_chat_deny": "דחייה", @@ -3751,8 +4472,16 @@ "ui.agent_chat_mode_all": "הכול", "ui.agent_chat_mode_ask": "שאלה", "ui.agent_chat_mode_edits": "עריכות", + "ui.agent_chat_model_custom": "שימוש במותאם אישית: {model}", "ui.agent_chat_model_no_tools": "{model} לא יכול להשתמש בכלים של SolidCraft, ולכן הוא יכול רק לשוחח. יש לבחור מודל שתומך בכלים.", + "ui.agent_chat_model_rejected": "הסוכן לא קיבל את {model}: {error}", + "ui.agent_chat_model_search": "חיפוש מודלים…", "ui.agent_chat_model_tip": "המודל שבו הסוכן משתמש. הבחירה נשמרת עבור הסוכן הזה.", + "ui.agent_chat_models_failed": "לא ניתן היה לטעון את רשימת המודלים: {error}", + "ui.agent_chat_models_heading": "מודלים זמינים", + "ui.agent_chat_models_listing": "טוען רשימת מודלים…", + "ui.agent_chat_models_none": "נקודת הקצה אינה מציגה מודלים", + "ui.agent_chat_models_not_a_list": "התשובה לא הייתה רשימת מודלים", "ui.agent_chat_new": "צ'אט חדש", "ui.agent_chat_new_confirm": "להתחיל צ'אט חדש? הצ'אט הנוכחי יימחק.", "ui.agent_chat_next_picture": "התמונה הבאה", @@ -3761,6 +4490,7 @@ "ui.agent_chat_no_images": "הסוכן הזה לא מקבל תמונות", "ui.agent_chat_no_picture": "אין תמונה בלוח", "ui.agent_chat_no_tool_call": "המודל לא השתמש בכלים של SolidCraft, ולכן התכן לא השתנה. יש לבחור מודל שתומך בקריאה לכלים; ראו „מודלים מקומיים” במדריך צ'אט הסוכן.", + "ui.agent_chat_node_too_old": "גרסת Node.js ‏{version} ישנה מדי עבור סוכן זה. יש להתקין Node.js 20.10 ומעלה, ואז ללחוץ על רענון.", "ui.agent_chat_none_found": "לא נמצא סוכן קוד. יש להתקין אחד מאלה ואז ללחוץ על רענון:", "ui.agent_chat_none_found_short": "לא נמצא סוכן", "ui.agent_chat_not_installed": "לא מותקן", @@ -3787,9 +4517,12 @@ "ui.agent_chat_queued_stopped": "בתור (נעצר, לא נשלח)", "ui.agent_chat_refresh": "רענון", "ui.agent_chat_refused": "אסור לסוכן: {reason}", + "ui.agent_chat_reinstall": "{agent} מותקן ({program}), אך לא הופעל כאשר SolidCraft בדק אותו: {error}\nייתכן שההתקנה שלו חלקית, או שהיא מיועדת לסוג אחר של מחשב. יש להתקין אותו מחדש עם `{install}`, לוודא שהוא מציג את הגרסה שלו במסוף, ואז ללחוץ על רענון.", "ui.agent_chat_remove": "הסרה מהתור", "ui.agent_chat_remove_file": "הסרה מההודעה הזו", "ui.agent_chat_remove_imported": "הסרה מההודעה הזו; החלק נשאר בתכן (ביטול מסיר אותו)", + "ui.agent_chat_reply_cut_off": "התשובה הגיעה למגבלת האורך שלה לפני שהסתיימה, ולכן ייתכן שהיא חלקית. יש לבקש מהסוכן להמשיך, או לענות בקצרה יותר.", + "ui.agent_chat_reply_declined": "המודל סירב לענות על ההודעה הזו.", "ui.agent_chat_retry": "ניסיון חוזר", "ui.agent_chat_right": "ימין", "ui.agent_chat_save": "שמירה", @@ -3798,7 +4531,7 @@ "ui.agent_chat_send_now_tip": "עצירת הצעד הנוכחי של הסוכן ושליחת הודעה זו כבאה בתור (Ctrl+Enter)", "ui.agent_chat_setup_body": "SolidCraft מדבר עם סוכן קוד שמותקן במחשב הזה. אפשר לבחור אחד בהעדפות › AI.", "ui.agent_chat_setup_title": "הגדרת עוזר", - "ui.agent_chat_side": "צד הצ'אט עם הסוכן", + "ui.agent_chat_side": "לעגן את הצ'אט", "ui.agent_chat_signed_in": "מחובר", "ui.agent_chat_state_auth": "נדרשת התחברות", "ui.agent_chat_state_busy": "עובד…", @@ -3817,7 +4550,7 @@ "ui.agent_chat_undone": "(בוטל)", "ui.agent_chat_view_attached": "התצוגה צורפה", "ui.agent_chat_waiting": "ממתין לך", - "ui.agent_cursor": "סמן הסוכן", + "ui.agent_cursor": "מצביע הסוכן", "ui.agent_cursor_speed": "מהירות סמן הסוכן", "ui.agent_off_thread": "שמירה על תגובתיות החלון בזמן שסוכנים מריצים פקודות", "ui.agent_off_thread_note": "פקודות איטיות של סוכן (מחלונית ה־AI או מלקוח MCP) מחושבות לצד החלון: אפשר להמשיך לסובב ולבחון את התצוגה, ולעצור פקודה מהתג שבתצוגה. כבוי: כל פקודה רצה בתהליכון של החלון, והחלון ממתין לה.", @@ -3848,24 +4581,29 @@ "ui.ai_copy_suffix": "עותק", "ui.ai_custom_url": "URL מותאם אישית", "ui.ai_default": "ברירת מחדל", + "ui.ai_edit": "עריכה", + "ui.ai_edit_agent_title": "עריכת סוכן", + "ui.ai_edit_gone": "הסוכן הזה הוסר, ולכן אין מה לשמור.", + "ui.ai_edit_tip": "שינוי השם, הפקודה או נקודת הקצה של סוכן זה. מפתח שמור נשאר מוסתר.", "ui.ai_http_busy": "נקודת הקצה עמוסה או חרגה מהמגבלה שלה; יש לנסות שוב מאוחר יותר", "ui.ai_http_key": "נקודת הקצה דחתה את המפתח: יש לבדוק אותו בהעדפות > AI", "ui.ai_http_not_found": "נקודת הקצה או המודל לא קיימים: יש לבדוק את URL הבסיס ואת שם המודל", "ui.ai_http_too_large": "השיחה גדולה מדי עבור נקודת קצה זו; יש להתחיל צ'אט חדש", "ui.ai_key": "מפתח API", "ui.ai_key_hint": "רשות; נשמר במחזיק המפתחות של המערכת", + "ui.ai_key_keep_hint": "יש להשאיר ריק כדי לשמור על המפתח השמור", "ui.ai_key_needs_https": "מפתח נשלח רק דרך HTTPS, או למחשב הזה.", "ui.ai_key_note": "נשמר במחזיק המפתחות של המערכת, לעולם לא בהגדרות של SolidCraft. יש להשאיר ריק עבור שרת מקומי.", "ui.ai_keychain_error": "מחזיק המפתחות של המערכת סירב: {error}", "ui.ai_kind": "סוג", - "ui.ai_mode_all": "התרת הכול", + "ui.ai_mode_all": "לעשות הכול", "ui.ai_mode_all_note": "שום דבר לא שואל קודם. דוחות קריסה נשארים חסומים ומגבלות התיקיות עדיין חלות.", "ui.ai_mode_all_warning": "הסוכן יכול לשמור, לדרוס, לייצא ולהחליף את התכן בלי לשאול. יש להשתמש בזה רק עם סוכן אמין, ועל תכנים שנשמרו.", - "ui.ai_mode_ask": "שאלה בכל פעם", + "ui.ai_mode_ask": "לשאול קודם", "ui.ai_mode_ask_note": "כל שינוי בתכן, וכל פעולת קובץ, ממתינים לאישור התרה.", - "ui.ai_mode_edits": "התרה אוטומטית של עריכות מודל", + "ui.ai_mode_edits": "לבצע עריכות", "ui.ai_mode_edits_note": "פקודות מידול רצות בלי לשאול; שמירה, פתיחה, ייצוא ופעולות קובץ או פעולות הרסניות אחרות עדיין שואלות.", - "ui.ai_mode_global": "כפי שהוגדר למעלה", + "ui.ai_mode_global": "כמו למעלה", "ui.ai_model": "מודל", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "ההגדרות האלה חלות על הכלים של SolidCraft. הכלים של הסוכן עצמו (המעטפת שלו, עריכת הקבצים שלו) כפופים למצב של הסוכן, שנבחר בכותרת חלונית הצ'אט כשלסוכן יש מצבים.", @@ -3880,14 +4618,18 @@ "ui.ai_permissions": "הרשאות", "ui.ai_preset": "תצורה מוכנה", "ui.ai_protocol": "פרוטוקול", + "ui.ai_reasoning_effort": "מאמץ ההסקה", + "ui.ai_reasoning_effort_field_hint": "ריק = ברירת המחדל של הספק", + "ui.ai_reasoning_effort_hint": "אופציונלי. נשלח לנקודת הקצה כ־`reasoning_effort`; הערכים המקובלים שונים מספק לספק (למשל `low`, `high` או `max`). SolidCraft לעולם לא תחליף את הערך שבחרת כאן. השאירו ריק כדי לא לשלוח דבר ולשמור על ברירת המחדל של הספק.", "ui.ai_remove": "הסרה", "ui.ai_request_timed_out": "המודל נזקק ליותר מ־{seconds} שניות. ניתן להגדיל את זמן ההמתנה לבקשה עבור נקודת קצה זו בהעדפות › עוזר.", "ui.ai_request_timeout": "זמן המתנה לבקשה", "ui.ai_request_timeout_hint": "כמה זמן מותר לבקשה אחת למודל בנקודת קצה זו, מ־30 שניות עד שעה. כדאי להגדיל עבור מודל מקומי איטי.", "ui.ai_reset": "איפוס", + "ui.ai_save": "שמירה", "ui.ai_settings": "הגדרות AI…", "ui.ai_show_features": "הצגת תכונות AI", - "ui.ai_show_features_note": "הצ'אט עם הסוכן: חלונית שבה סוכן קוד שכבר נמצא בשימוש, או נקודת קצה של מודל לבחירתך, עובדים על התכן הפתוח. כבוי: אין לחצן AI, קיצור דרך, פריט תפריט או חלונית, ושום דבר לא מחופש או מופעל.", + "ui.ai_show_features_note": "כיבוי מסתיר את העוזר בכל מקום ולא מפעיל דבר. כל מה שמתחת מעומעם.\n\nהצ'אט עם הסוכן: חלונית שבה סוכן קוד שכבר נמצא בשימוש, או נקודת קצה של מודל לבחירתך, עובדים על התכן הפתוח. כבוי: אין לחצן AI, קיצור דרך, פריט תפריט או חלונית, ושום דבר לא מחופש או מופעל.", "ui.ai_switch_tip": "החלפת הסוכן לשיחה הזו", "ui.ai_test": "בדיקה", "ui.ai_test_acp_ok": "עונה: {agent}", @@ -3921,7 +4663,7 @@ "ui.ai_tool_sum_then": "{first}, ואז {next}", "ui.ai_tool_unfold": "יש ללחוץ כדי להציג מה הוחזר", "ui.ai_tool_waiting": "ממתין", - "ui.ai_toolbar_button": "הצגת לחצן העוזר בסרגל היישום", + "ui.ai_toolbar_button": "כפתור העוזר בסרגל היישום", "ui.ai_toolbar_button_note": "לחצן העוזר בסרגל היישום. Ctrl+Shift+A ותפריט התצוגה עדיין פותחים את החלונית.", "ui.ai_undo_tip": "ביטול כל מה שהסוכן שינה בהודעה הזו, כצעד אחד", "ui.ai_url_hint": "https://example.com/v1", @@ -3968,11 +4710,14 @@ "ui.centerline": "קו מרכז", "ui.chain": "שרשרת", "ui.chamfer": "פאזה", + "ui.chamfer_angle": "זווית פאזה", + "ui.chamfer_depth": "עומק פאזה", "ui.chamfer_type": "סוג פאזה", "ui.change_workspace": "החלפת סביבת עבודה", "ui.circle": "מעגל", "ui.circular_pattern": "מערך מעגלי", "ui.clear": "ניקוי", + "ui.clear_print_face": "נקה פאת הדפסה", "ui.clear_recent": "ניקוי האחרונים", "ui.clear_the_selection": "ניקוי הבחירה", "ui.click_selects_whole_bodies": "לחיצה בוחרת גופים שלמים", @@ -3997,10 +4742,16 @@ "ui.colour_vision_sample": "דוגמה", "ui.colour_vision_tritan": "טריטן", "ui.colour_vision_tritan_tip": "לתחושת כחול חלשה או חסרה", + "ui.comb_length": "אורך המסרק", + "ui.comb_length_tip": "אורך השיניים: כפולה של האורך האוטומטי, שבו השן הארוכה ביותר היא חמישית מגודל העקומות המוצגות.", + "ui.comb_teeth": "שיניים", + "ui.comb_teeth_tip": "כמה שיניים יש לכל מסרק, במרווחים שווים לאורך העקומה. יותר שיניים מראות בפירוט רב יותר איך העקמומיות משתנה.", "ui.combine": "שילוב", "ui.coming_later": "בקרוב", "ui.command_done": "{command} הושלם", "ui.command_palette_hint": "יש להקליד פקודה, למשל {example} — או ללחוץ S לחיפוש", + "ui.components_from_bodies_hint": "יצירת רכיב לכל גוף שנבחר, בשם הגוף, תחת הרכיב הפעיל.", + "ui.components_from_bodies_required": "יש לבחור גוף אחד לפחות.", "ui.concentric": "משותף מרכז", "ui.cone": "חרוט", "ui.conic_curve": "עקום חרוטי", @@ -4013,15 +4764,30 @@ "ui.construction.contact_hint": "משיק: בחירת מעגל/קשת או ספליין/חתך חרוט פתוח ואז נקודת השקה (לעקומות חופשיות: קצוות בלבד)", "ui.construction.external_hint": "משיק: בחירת מעגל או קשת, נקודה חיצונית ואז הפתרון הרצוי", "ui.construction.free_hint": "ישר עזר: לחיצה על שתי נקודות; לחיצה ימנית להתחלה מחדש", + "ui.construction.normal_needs_length": "קו אינסופי הוא תמיד קו עזר: הקלדת אורך משרטטת קו רגיל", "ui.construction.point_hint": "ישר עזר: לחיצה על נקודת המעבר", "ui.construction.reference_hint": "ישר עזר: בחירת ישר ואז נקודה; לחיצה ימנית להחלפת הייחוס", "ui.construction.ribbon_label": "קווי עזר", + "ui.construction.side_hint": "ישר עזר: לחיצה על הצד שאליו הקו נמשך; לחיצה ימנית להתחלה מחדש", "ui.context_menu": "תפריט הקשר", + "ui.continuity_crease": "שבר", + "ui.continuity_curvature": "עקמומיות", + "ui.continuity_curvature_change": "שינוי עקמומיות", + "ui.continuity_curvature_change_tip": "שינוי עקמומיות (G3): גם העקמומיות משתנה בצורה חלקה לאורך התפר.", + "ui.continuity_curvature_tip": "רציף בעקמומיות (G2): ההשתקפויות עוברות בלי שבר.", "ui.continuity_g0": "G0 שבר", "ui.continuity_g1": "G1 משיק", "ui.continuity_g2": "G2 עקמומיות", "ui.continuity_gap": "פער", + "ui.continuity_position": "מיקום", + "ui.continuity_position_tip": "מיקום (G0): המשטחים נפגשים, עם שבר במקום המפגש.", + "ui.continuity_smooth_curvature_change": "שינוי עקמומיות חלק", + "ui.continuity_smooth_curvature_change_tip": "שינוי עקמומיות חלק (G4): גם האופן שבו העקמומיות משתנה ממשיך בצורה חלקה לאורך התפר.", + "ui.continuity_tangent": "משיק", + "ui.continuity_tangent_tip": "משיק (G1): אין שבר, אך העקמומיות קופצת לאורך התפר.", "ui.copy": "העתקה", + "ui.copy_details": "העתקת פרטים", + "ui.copy_details_tip": "העתקת ההודעה המלאה, כדי לחפש אותה או לדווח עליה.", "ui.corner": "פינה", "ui.corners": "פינות", "ui.cosmetic_thread_markings": "סימוני הברגה קוסמטיים", @@ -4043,6 +4809,8 @@ "ui.dark": "כהה", "ui.default_modelling_orientation": "כיוון מידול ברירת מחדל", "ui.delete": "מחיקה", + "ui.delete_select_first": "בחרו קודם מה למחוק: תכונות, גופים, רכיבים או גאומטריית סקיצה", + "ui.dependents_select_first": "בחרו קודם מה להציג את התלויים שלו", "ui.depth": "עומק", "ui.design": "תכן", "ui.design_properties.author": "מחבר", @@ -4057,6 +4825,40 @@ "ui.design_properties.project": "פרויקט", "ui.design_properties.revision": "גרסה", "ui.design_saved": "נשמר ב־{path}", + "ui.details_access_caption": "הפאות מציגות אם כלי יכול להגיע אליהן מהכיוון שנבחר.", + "ui.details_angle": "זווית", + "ui.details_continuity_caption": "עריכת התפר שנבחר. שאר התפרים שומרים על ההגדרות שלהם.", + "ui.details_continuity_stale": "גאומטריה קודמת: יש להריץ שוב את הניתוח כדי לערוך את התפר הזה או להתאים את התצוגה אליו.", + "ui.details_copy_list": "העתקת הרשימה", + "ui.details_curvature": "סבולת עקמומיות", + "ui.details_curvature_caption": "הפאות נצבעות לפי רדיוס העקמומיות המקומי שלהן.", + "ui.details_direction": "כיוון הכלי", + "ui.details_draft_caption": "הפאות נצבעות לפי הזווית שלהן ביחס לכיוון החליצה.", + "ui.details_edit_seam": "עריכת תפר", + "ui.details_fixture": "דוגמת רכיב ממשק — נתוני דוגמה בלבד", + "ui.details_fixture_caption": "דוגמת רכיב ממשק עם ערכים להמחשה; זו אינה תוצאה של מודל.", + "ui.details_fixture_problem": "ממצא לדוגמה עם בעיה", + "ui.details_fixture_readout": "ערך מדידה לדוגמה", + "ui.details_flip": "היפוך", + "ui.details_gap": "פער", + "ui.details_hatch": "קיווקוו פאות החתך", + "ui.details_jump": "קפיצת עקמומיות", + "ui.details_key": "מקרא", + "ui.details_offset": "היסט", + "ui.details_plane": "מישור", + "ui.details_pull": "כיוון החליצה", + "ui.details_radius": "רדיוס", + "ui.details_readout": "ערכים נמדדים", + "ui.details_samples": "דגימות", + "ui.details_seam": "{body} · מקצוע {edge}", + "ui.details_settings": "הגדרות", + "ui.details_sharp_gap": "חד או בעל פער", + "ui.details_show_all": "הצגת הכול ({count})", + "ui.details_smooth": "חלק", + "ui.details_stripes": "פסים", + "ui.details_target": "התאמת התצוגה לגאומטריה", + "ui.details_worst_seams": "התפרים הגרועים ביותר", + "ui.details_zebra_caption": "פסי ההשתקפות מראים באיזו מידה הפאות מתחברות בצורה חלקה.", "ui.diameter": "קוטר", "ui.dimension": "מידה", "ui.direct_interaction": "אינטראקציה ישירה", @@ -4101,39 +4903,78 @@ "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", "ui.edit_in_place_wait": "יש להמתין עד שמה שפועל בתכן יסתיים", "ui.edit_section_analysis": "עריכת ניתוח חתך", + "ui.edit_sketch_empty": "אין סקיצות לעריכה", "ui.ellipse": "אליפסה", "ui.emboss_wrap_note": "פרופילי קווים ניצבים המשיקים לגליל נתמך נכרכים אוטומטית. יש לבחור דופן כדי לקבוע יעד.", + "ui.end": "סוף", "ui.end_radius": "רדיוס סיום", "ui.end_scale": "קנה מידה בסיום", + "ui.ends": "קצוות", "ui.entities": "ישויות", "ui.equal": "שווה", "ui.equation_end": "סוף", "ui.equation_explicit": "מפורשת", "ui.equation_form": "צורה", "ui.equation_note": "המשתנה הוא מספר ללא יחידה: sin(t) מקבלת אותו ברדיאנים. תוצאה ללא יחידה היא ביחידה של התכנון.", + "ui.equation_note_range": "המשתנה הוא אורך, כמו הטווח שלו: אפשר לשלב אותו עם פרמטרי אורך, ולחלק אותו באורך עבור sin(). תוצאה ללא יחידה היא ביחידת התכן.", "ui.equation_parametric": "פרמטרית", + "ui.equation_variable_unit": "המשתנה ביחידת הטווח", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "רדיוס שקול", "ui.expand": "הרחבה", + "ui.explode_needs_two_components": "תצוגה מפוצצת מרחיקה רכיבים זה מזה, ולכן התכן צריך שניים או יותר מהם (רכיב חדש, הוספת תכן או יצירת רכיבים מגופים)", "ui.exportDxf": "ייצוא DXF…", "ui.export_ellipsis_keymap": "ייצוא…", "ui.export_keymap_tip": "מקשים, מועדפי תיבת S וסרגל הכלים, כקובץ", "ui.extend": "הארכה", + "ui.extent": "גבול", "ui.extent_type": "סוג גבול", "ui.extract_component": "חילוץ לקובץ…", "ui.extract_design_changed": "התכן השתנה בזמן בחירת הקובץ. יש להפעיל שוב את חילוץ לקובץ.", "ui.extract_done": "הרכיב הוא עכשיו תכן נפרד, מקושר לכאן.", "ui.extrude": "שליפה", "ui.extrude_auto_to_object": "שליפה עד יעד שנבחר", - "ui.extrude_auto_to_object_tip": "בשליפה, כשנבחר פרופיל, בחירת פאה, קודקוד או מישור מקביל מחוץ למישור שלו מעבירה את התחום ל\"עד אובייקט\"", + "ui.extrude_auto_to_object_tip": "פאה, קודקוד או מישור מקביל מעבירים את ההיקף למצב עד אובייקט.", "ui.factor": "מקדם", + "ui.fade": "דעיכה", + "ui.fade_length": "אורך דעיכה", "ui.feature_history": "ציר הזמן", "ui.feature_options": "אפשרויות פיצ'ר", "ui.features": "פיצ'רים", "ui.file": "קובץ", "ui.fillet": "עיגול פינה", + "ui.fillet_corner_ball": "כדור", + "ui.fillet_corner_ball_tip": "חלק מספירת הכדור המתגלגל, משיק (G1) לכל עיגול.", + "ui.fillet_corner_curvature_tip": "עקמומיות (G2): טלאי חלק. הפינה נסוגה לאורך כל קצה במרחק הנסיגה (פי {factor} מהרדיוס אלא אם תקלידו ערך) ומתמלאת בטלאי, כך שההשתקפויות עוברות בה בלי שבר.", + "ui.fillet_corner_needs_constant": "פינות עם טלאי חלק (G2) דורשות רדיוס קבוע והתאמת רדיוס מדויקת.", + "ui.fillet_corner_patch": "טלאי חלק", + "ui.fillet_corner_patch_tip": "רציף בעקמומיות (G2): הפינה נסוגה לאורך כל קצה ומתמלאת בטלאי, כך שההשתקפויות עוברות בה בלי שבר.", + "ui.fillet_corner_tangent_tip": "משיק (G1): פינת כדור מתגלגל, חלק מספירת הכדור המתגלגל, משיק לכל עיגול.", + "ui.fillet_error_corner": "לא ניתן היה לבנות כאן את הפינה החלקה. נסו נסיגה אחרת, או פינות משיקות.", + "ui.fillet_error_failed": "לא ניתן היה לבנות את העיגול הזה על הקצוות האלה. נסו רדיוס אחר, או עגלו פחות קצוות בבת אחת.", + "ui.fillet_error_setback_short": "הנסיגה קצרה מדי עבור הטלאי של פינה זו: הוא נבנה החל מ-{least}. נסו נסיגה ארוכה יותר.", + "ui.fillet_error_too_large": "הרדיוס גדול מדי עבור הפאות שליד הקצוות האלה. נסו רדיוס קטן יותר, או בחרו ב„גבולות הפאות” את „הרדיוס הגדול ביותר”.", + "ui.fillet_fit": "גבולות הפאות", + "ui.fillet_fit_exact": "רדיוס מדויק", + "ui.fillet_fit_needs_constant": "התאמת רדיוס דורשת רדיוס קבוע.", + "ui.fillet_fit_reduce": "הרדיוס הגדול ביותר", + "ui.fillet_fit_taper": "רדיוס מוצר", + "ui.fillet_fit_tip": "כשהרדיוס גדול ממה שהפאות שליד הקצה מאפשרות.\nרדיוס מדויק: הרדיוס כפי שניתן, או ללא עיגול והודעה שמסבירה למה.\nהרדיוס הגדול ביותר: כל קצה מעוגל ברדיוס הגדול ביותר שנכנס.\nרדיוס מוצר: הרדיוס נשמר, והעיגול מוצר רק היכן שהפאות נגמרות.", + "ui.fillet_options_tip": "שרשרת משיקה: לעגל גם את הקצוות שממשיכים בחלקות מהקצוות שנבחרו.\nתצוגה מקדימה: להציג את התוצאה בתצוגה בזמן העריכה.", + "ui.fillet_setback": "נסיגה", + "ui.fillet_setback_hint": "{factor} × רדיוס", + "ui.fillet_setback_least": "יותר מ-{least}", + "ui.fillet_setback_tip": "היכן מתחיל טלאי הפינה החלק: המרחק לאורך כל קצה מהפינה. ברירת המחדל היא פי {factor} מהרדיוס. עליה להיות גדולה מהנסיגה המזערית, שבה העיגולים נפגשים בלעדיה: הרדיוס כשהפאות ניצבות זו לזו.", + "ui.fillet_smooth_radius": "שינוי רדיוס חלק", + "ui.fillet_turn": "פניות", + "ui.fillet_turn_mitre": "מיטר", + "ui.fillet_turn_swept": "מסובב", + "ui.fillet_turn_tip": "היכן ששני עיגולים מסתובבים סביב קצה פינה חד ביניהם, כמו העיגולים בבסיס בליטה ליד הקצוות הזקופים שלה.\nמיטר: העיגולים נמשכים עד שהם נפגשים במיטר.\nמסובב: העיגולים נעצרים בקצה הפינה ומסתובבים סביבו, והפינה היא טורוס המשיק לשניהם. רק לעיגולים ברדיוס אחד סביב קצה פינה ישר וקמור.", + "ui.fillet_type_choices_tip": "רדיוס קבוע: רדיוס אחד לכל אורך הקצה.\nאורך מיתר: רוחב העיגול נשאר זהה, בכל זווית שבה הפאות נפגשות.\nרדיוס משתנה: רדיוס בכל קצה, ועוד לאורך הקצה אם מוסיפים.\nרציף בעקמומיות: חתך בלי שבר בהשתקפויות היכן שהוא פוגש פאות מישוריות (G2).\nספליין: הרדיוס לאורך הקצה עוקב אחרי רדיוסי בקרה שאתם קובעים.", + "ui.fillet_type_curvature": "רציף בעקמומיות", + "ui.fillet_type_tip": "החתך לרוחב הקצה. רציף בעקמומיות: חתך רציף בעקמומיות (G2) בין פאות מישוריות, כך שההשתקפויות עוברות מהפאות אל העיגול בלי שבר.", "ui.filter_commands_or_keys": "סינון פקודות או מקשים", "ui.findInTimeline": "איתור בציר הזמן", "ui.findInWindow": "איתור בחלון", @@ -4242,13 +5083,15 @@ "ui.hideOrigin": "הסתרת ראשית", "ui.hidePlanes": "הסתרת מישורים", "ui.hideProfile": "הסתרת פרופיל", - "ui.hide_origin_by_default": "הסתרת הראשית כברירת מחדל", + "ui.hide_component_history": "הסתר את ההיסטוריה שלו", + "ui.hide_origin_by_default": "הסתרת תיקיית הראשית בתכנונים חדשים", "ui.hide_origin_note": "תכנים חדשים מתחילים כשתיקיית הראשית מוסתרת. כל תכן שומר על הגדרת הראשית שלו אחרי שמציגים או מסתירים אותה.", "ui.history_back": "צעד אחד אחורה", "ui.history_below_browser": "מתחת לעץ התכן", "ui.history_edge_hint": "לחיצה כפולה על הקצה", "ui.history_first": "מעבר להתחלה", "ui.history_forward": "צעד אחד קדימה", + "ui.history_hide_hidden": "הסתר רכיבים מוסתרים", "ui.history_hide_names": "הסתרת שמות", "ui.history_last": "מעבר לסוף", "ui.history_marker_tip": "סמן ציר הזמן: יש לגרור כדי להחזיר את המודל לאחור; פיצ'רים חדשים נוספים כאן", @@ -4258,10 +5101,12 @@ "ui.history_play_button_show": "הצגת כפתור ההפעלה", "ui.history_play_finish_action": "יש לסיים את הפעולה הנוכחית לפני הפעלת ציר הזמן", "ui.history_play_roll_back": "יש להזיז את סמן ציר הזמן לאחור לפני ההפעלה", + "ui.history_show_hidden": "הצג רכיבים מוסתרים", "ui.history_show_names": "הצגת שמות", "ui.history_sketch_listed_under": "מופיעה תחת {feature}", "ui.history_title": "ציר הזמן", "ui.history_toggle_names": "הצגה או הסתרה של שמות הפיצ'רים", + "ui.history_waits_for_editor": "ביטול, ביצוע מחדש וציר הזמן ממתינים עד שעורך הפעולה ייפתח", "ui.hole": "חור", "ui.hole_tap_type": "סוג הברגת חור", "ui.hole_type": "סוג חור", @@ -4277,7 +5122,9 @@ "ui.insert_design.saved_file": "ב-{name} יש שינויים שלא נשמרו, ולכן נוסף הקובץ השמור שלו. שמרו אותו ואז בחרו עדכון קישורים כדי להכניס את השינויים.", "ui.insert_design.unsaved": "שינויים שלא נשמרו", "ui.inspect": "בדיקה", + "ui.instances": "מופעים", "ui.intersect": "חיתוך משותף", + "ui.iso_4753": "ISO 4753", "ui.isolate": "בידוד", "ui.join": "איחוד", "ui.joint_play": "▶ הפעלה", @@ -4285,12 +5132,14 @@ "ui.joints": "מפרקים", "ui.keyboard_shortcuts": "קיצורי מקלדת", "ui.language": "שפה", + "ui.lasso_select": "לאסו (גרירת לולאה חופשית: בוחר את מה שנמצא כולו בתוכה)", "ui.layout_compact": "דחוס", "ui.layout_floating": "צף", "ui.length": "אורך", "ui.length_decimals": "ספרות עשרוניות באורך", "ui.light": "בהיר", "ui.line": "קו", + "ui.line_arc_hint": "קשת משיקה: לחצו על קצה הקשת. השהו שוב על הנקודה האחרונה כדי לחזור לקווים; לחיצה ימנית או Esc לסיום", "ui.link_copies": "קישור עותקים זהים", "ui.link_copies_keep": "השארה", "ui.link_copies_link": "קישור", @@ -4378,7 +5227,9 @@ "ui.part_size_needs_a_part": "בחרו חלק סטנדרטי שהוכנס (בורג, אום, דסקית או פין) כדי לשנות את גודלו. כדי להגדיל או להקטין גוף, השתמשו בשינוי קנה מידה.", "ui.part_size_shared": "בונה מחדש את החלק ומחליף פיצ'רים שנוספו. כל המופעים של רכיב זה מתעדכנים.", "ui.paste": "הדבקה", + "ui.patch_continuity_corner_tip": "הטלאי פוגש את הפאות שסביבו ברציפות שנבחרה לאורך כל צלע. בפינה שבה הפאות האלה נפגשות זו עם זו בעקמומיות שונה, הוא נשאר משיק (G1) שם.", "ui.path": "מסלול", + "ui.pattern_object_type_tip": "גופים: צורות מלאות, נבחרות בתצוגה או בעץ התכן; כל אחד מועתק בשלמותו.\nפיצ'רים: שלבים בציר הזמן, כמו שליפה או חור, נבחרים בציר הזמן או על פאה שהם יצרו; השלב חוזר על עצמו.\nסקיצה אינה אף אחד מהם: חזרו על העקומות שלה בעזרת המערך או השיקוף של הסקיצה עצמה, או בצעו לה שליפה קודם.", "ui.pattern_on_path": "מערך לאורך מסלול", "ui.perforate_margin_default": "לפי הקוטר", "ui.perforate_pitch": "פסיעה", @@ -4393,7 +5244,7 @@ "ui.pitch": "פסיעה", "ui.placement": "מיקום", "ui.placement_handles": "ידיות מיקום", - "ui.placement_handles_tip": "ידיות בתצוגה המקדימה של משען, בליטה או חיבור הצמדה: יש לגרור את הסמן כדי להזיז על פני המודל, ולסובב בעזרת הטבעת", + "ui.placement_handles_tip": "סמן לגרירת התכונה על המודל וטבעת לסיבובה.", "ui.plane": "מישור", "ui.plane_at_angle": "מישור בזווית", "ui.plugins": "תוספים", @@ -4405,12 +5256,17 @@ "ui.plugins_skipped": "לא ניתן היה לקרוא {count} תיקיות.", "ui.plugins_version": "{version}", "ui.point": "נקודה", + "ui.point_cloud_add_filter": "הוספת מסנן…", "ui.point_cloud_auto_range": "טווח אוטומטי", "ui.point_cloud_color_by": "צביעה לפי", "ui.point_cloud_file_colors": "צבעי הקובץ", + "ui.point_cloud_filter_by": "סינון לפי", "ui.point_cloud_height_high": "הגובה המרבי", "ui.point_cloud_height_low": "הגובה המזערי", + "ui.point_cloud_legend_filter": "מוצגים ומוסתרים במקרא שלמעלה", "ui.point_cloud_no_file_colors": "אין בקובץ צבעים", + "ui.point_cloud_pause": "השהיה", + "ui.point_cloud_play": "הפעלה", "ui.point_cloud_single_color": "צבע אחיד", "ui.point_cloud_size": "גודל נקודה", "ui.point_cloud_units": "יחידות הקובץ", @@ -4419,6 +5275,11 @@ "ui.polygon": "מצולע", "ui.preferences": "העדפות", "ui.press_a_key": "יש ללחוץ על מקש…", + "ui.print_face_body_not_sent": "הגוף של פאה זו אינו נשלח: הוסף אותו קודם לגופים", + "ui.print_face_cleared": "{body}: פאת ההדפסה נוקתה", + "ui.print_face_input": "פאת הדפסה", + "ui.print_face_pick": "בחר פאה שטוחה אחת של גוף מוצק כדי להפוך אותה לפאת ההדפסה", + "ui.print_face_set": "{body}: פאת ההדפסה הוגדרה; שליחה לסלייסר מניחה את הגוף עליה", "ui.profile": "פרופיל", "ui.profile_plane": "מישור הפרופיל", "ui.profiles": "פרופילים", @@ -4434,6 +5295,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "מודד…", + "ui.properties.measuring_bodies": "מודד… {done} מתוך {total} גופים", "ui.properties.measuring_failed": "המדידה נעצרה לפני שהסתיימה.", "ui.properties.principal_axis": "ציר ראשי {number}", "ui.properties.principal_moments": "מומנטים ראשיים", @@ -4501,6 +5363,7 @@ "ui.selectOther": "בחירת אחר…", "ui.selectTangentChain": "בחירת שרשרת משיקה", "ui.select_all": "בחירת הכול", + "ui.select_components_by_face": "בחירת רכיבים (בחירת פאה בוחרת את הרכיב שלה)", "ui.selection": "בחירה", "ui.selection_modifiers": "מקשי שינוי לבחירה", "ui.selection_shift_add_only": "Shift+לחיצה מוסיף בלי להסיר", @@ -4526,6 +5389,7 @@ "ui.showDimension": "הצגת מידה", "ui.showOrigin": "הצגת ראשית", "ui.showPlanes": "הצגת מישורים", + "ui.show_component_history": "הצג את ההיסטוריה שלו", "ui.show_constraints": "אילוצים", "ui.show_construction_geometries": "גאומטריית עזר", "ui.show_dimensions": "מידות", @@ -4540,8 +5404,15 @@ "ui.sketch_intersect_geometry": "גאומטריה", "ui.sketch_intersect_projection_link": "קישור הטלה", "ui.sketch_intersect_selection_filter": "מסנן בחירה", + "ui.sketch_keys_only": "להשאיר את מקשי המודל מחוץ לסקיצות", + "ui.sketch_keys_only_tip": "בזמן עריכת סקיצה פועלים רק מקשי סקיצה ומקשים שפועלים בכל מקום; מקש של המודל כמו E או F לא עושה דבר, כך שמקש שנלחץ בטעות לא יסגור סקיצה כבדה.", "ui.sketch_modifiers": "מקשי שינוי בסקיצה", "ui.sketch_project_geometry": "גאומטריה", + "ui.sketch_report.all_constrained": "הכול מאולץ במלואו.", + "ui.sketch_report.dof": "דרגות חופש", + "ui.sketch_report.loose": "לא מאולץ במלואו", + "ui.sketch_report.status": "מצב", + "ui.sketch_report.title": "דוח סקיצה", "ui.sketch_scale": "קנה מידה של סקיצה", "ui.sketches": "סקיצות", "ui.slice": "חתך", @@ -4552,7 +5423,7 @@ "ui.slicer_no_response": "{slicer} לא הגיב בזמן. הקובץ כבר שמור ב־{path}: יש לשלוח אותו שוב אחרי שהסלייסר יופעל.", "ui.slicer_resend_hint": "שליחה חוזרת מחליפה את הקובץ שפתוח בסלייסר.", "ui.slicer_single_instance": "פתיחת קבצים בסלייסר שכבר פועל", - "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer ו־Cura טוענים את הקובץ בחלון הפתוח במקום להפעיל חלון נוסף. סלייסרים אחרים מופעלים כרגיל. PrusaSlicer 3.0 עושה זאת תמיד: המפעיל שלו לא יכול לקבל קובץ בדרך אחרת.", + "ui.slicer_single_instance_tip": "לסלייסרים שטוענים קובץ לחלון שכבר פועל.", "ui.slicer_starting": "מפעיל את {slicer}…", "ui.slicer_still_starting": "עדיין ממתין להפעלת {slicer}. שום דבר נוסף לא נשלח.", "ui.slicer_stl_fallback": "לא ניתן היה לכתוב את קובץ ה־3MF, ולכן זהו קובץ STL.", @@ -4571,8 +5442,8 @@ "ui.start": "התחלה", "ui.start_over": "התחלה מחדש", "ui.start_page": "דף פתיחה", - "ui.step_values": "שינוי ערכים בעזרת מקשי החצים והגלגלת", - "ui.step_values_tip": "בשדה ערך שמקלידים בו, החצים למעלה ולמטה משנים מספר רגיל ב־1 (Shift: 10, Alt: 0.1), וכך גם גלגלת העכבר מעל השדה. ביטויים נשארים כפי שהוקלדו.", + "ui.step_values": "שינוי ערכים בחצים ובגלגלת", + "ui.step_values_tip": "מקשי מעלה/מטה והגלגלת מעל שדה ערך משנים את המספר בו.", "ui.stitch_tolerance_hint": "הדוקה", "ui.stretch": "מתיחה", "ui.supersampling": "דגימת־על (SSAA)", @@ -4637,19 +5508,31 @@ "ui.view_angles": "זוויות תצוגה", "ui.view_angles_convention": "מעלות סביב הציר העליון. סבסוב 0° הוא התצוגה הקדמית, 90° שמאלית, −90° ימנית, 180° אחורית; עלרוד 90° הוא התצוגה העליונה; גלגול חיובי מסובב את המודל על המסך עם כיוון השעון.", "ui.view_angles_help": "מציג מתחת לגיזמו הכיוון את זוויות העלרוד, הסבסוב והגלגול של התצוגה במעלות ואת סוג ההטלה. לחצו על התצוגה כדי להקליד זוויות מדויקות.", + "ui.view_angles_lock": "נעל את {axis}", "ui.view_angles_ortho": "אורתוגרפי", "ui.view_angles_persp": "פרספקטיבה", "ui.view_angles_pitch": "עלרוד", "ui.view_angles_readout": "עלרוד {pitch} · סבסוב {yaw} · גלגול {roll}", "ui.view_angles_roll": "גלגול", + "ui.view_angles_unlock": "בטל נעילת {axis}", "ui.view_angles_yaw": "סבסוב", + "ui.view_angles_zero": "הגדר את {axis} ל-0°", "ui.view_centre": "מרכז המבט", "ui.viewport_status_clear": "כיבוי {name}", "ui.viewport_status_clear_hint": "כיבוי {name} · Esc", + "ui.viewport_status_edges": "{count} קצוות", + "ui.viewport_status_from": "מכיוון {direction}", "ui.viewport_status_key": "הצגת מקרא עבור {name}", "ui.viewport_status_minimum_radius": "רדיוס מינימלי", "ui.viewport_status_pairs": "{count} זוגות", + "ui.viewport_status_section_hatch": "{setting} · קווקוו", + "ui.viewport_status_section_plane": "המישור הנוכחי", + "ui.viewport_status_section_tilted": "נטוי · {offset}", "ui.viewport_status_stripes": "{count} פסים", + "ui.viewport_status_summary_clear": "כיבוי הכול", + "ui.viewport_status_summary_heading": "בתצוגה זו", + "ui.viewport_status_summary_label": "{name} ועוד {count} פריטים", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "לפי ערכת הנושא", "ui.visual_shaded_hidden_edges": "מוצלל עם מקצועות נסתרים", "ui.visual_shaded_with_edges": "מוצלל עם מקצועות", @@ -4685,11 +5568,13 @@ "update.available": "SolidCraft {version} זמין", "update.button": "עדכון", "update.button_version": "עדכון ל־{version}", - "update.check_automatically": "בדיקת עדכונים אוטומטית", + "update.check_automatically": "בדיקה בהפעלה ופעם ביום", + "update.check_for_updates": "בדיקת עדכונים", "update.check_now": "בדיקה עכשיו", + "update.check_unavailable": "בדיקת עדכונים אינה זמינה עבור התקנה זו.", "update.checking": "בבדיקה…", "update.copy": "העתקה", - "update.dmg_opened": "תמונת הדיסק פתוחה ואומתה: יש לגרור את SolidCraft לתיקיית היישומים במקום העותק הישן, ואז להפעיל מחדש את SolidCraft.", + "update.dmg_opened": "תמונת הדיסק פתוחה ואומתה: יש לצאת מ-SolidCraft, לגרור את SolidCraft החדש לתיקיית היישומים במקום העותק הישן, ואז לפתוח את SolidCraft מחדש.", "update.download": "הורדה", "update.download_open": "הורדה ופתיחה", "update.downloading": "הורדה ואימות… {done} מתוך {total} MB", @@ -4733,6 +5618,7 @@ "web.open_link": "לפתוח את התכן המקושר?", "web.open_link_confirm": "יש שינויים שלא נשמרו. לפתוח את התכן המקושר בלשונית חדשה?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ בחירה · Enter / Tab השלמה · Esc סגירה", + "↑ ↓ choose · Enter applies this value": "↑ ↓ בחירה · Enter מחיל את הערך הזה", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ בחירה · Enter מחיל את מה שהוקלד · Esc סגירה", "⌘Enter continues on GitHub.": "⌘Enter ממשיך ב־GitHub." } diff --git a/assets/locales/hr.json b/assets/locales/hr.json index 1606b9ba6..01836c358 100644 --- a/assets/locales/hr.json +++ b/assets/locales/hr.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "PRIJELAZNA PLOHA", "BOUNDARY SURFACE": "GRANIČNA PLOHA", "BROWSER": "STABLO MODELA", + "Back to the original order": "Natrag na izvorni redoslijed", "Ball": "Kuglasti", "Bar": "Šipka", "Base Center": "Središte osnove", @@ -476,6 +477,7 @@ "Rectangular": "Pravokutni", "Rectangular Tube": "Pravokutna cijev", "Reference face": "Referentno lice", + "Reference plane": "Referentna ravnina", "Relief Depth": "Dubina rasterećenja", "Relief Width": "Širina rasterećenja", "Remove Tools": "Ukloni alate", @@ -555,6 +557,7 @@ "Section": "Presjek", "Section (optional)": "Presjek (neobavezno)", "Section position": "Položaj presjeka", + "Sections": "Presjeci", "Sections (one sketch each)": "Presjeci (po jedna skica)", "Select Other": "Odaberi drugo", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Odaberi drugo: držite lijevu tipku mirno na modelu (ili desni klik › Odaberi drugo…) kako biste prikazali sve ispod pokazivača; ponovno kliknite na isto mjesto kako biste odabrali sljedeći element. Dvaput kliknite srednjom tipkom za Početni prikaz (Postavke › Navigacija).", @@ -595,6 +598,8 @@ "Snap to face and edge centres": "Privlači na središta lica i bridova", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft ne može izravno slati izvješća. Pošaljite ih na GitHubu; u aplikaciji nije potreban token.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft se zatvorio prije nego što su ovi dizajni spremljeni. Može se otvoriti njihovo posljednje automatsko spremanje.", + "Sort A to Z": "Poredaj od A do Ž", + "Sort Z to A": "Poredaj od Ž do A", "Spacing 2 must be a non-zero number": "Razmak 2 mora biti broj različit od nule", "Spacing must be a non-zero number": "Razmak mora biti broj različit od nule", "Specialise": "Specijaliziraj", @@ -775,6 +780,8 @@ "at the face": "na licu", "bom.group_children": "Podređeni dijelovi u retku svojeg dijela", "browser.body_name": "Tijelo{number}", + "browser.calibrate_click_a": "Kliknite sliku kako biste zadali točku A ili upišite njezine koordinate.", + "browser.calibrate_click_b": "Kliknite sliku kako biste zadali točku B ili upišite njezine koordinate.", "browser.calibrate_title": "Kalibriraj: {name}", "browser.capture_many": "Pomaknute komponente bez zabilježenog položaja: {count}.", "browser.capture_note": "Zabilježi zadržava novi položaj; Vrati ga vraća nazad.", @@ -788,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (pričvršćenje izgubljeno)", "browser.sketch_editing": "{name} (uređuje se)", "browser.sketch_name": "Skica{number}", + "browser.sketches_to_parts_already_in_part": "već u svojem dijelu", + "browser.sketches_to_parts_design_body": "na tijelu samog dizajna", + "browser.sketches_to_parts_moved": "Skice premještene u dio na kojem se nalaze: {moved}", + "browser.sketches_to_parts_no_exact_attachment": "na licu bez točnog pričvršćenja", + "browser.sketches_to_parts_not_on_face": "ne na licu dijela", + "browser.sketches_to_parts_part_missing": "njihov dio više ne postoji", + "browser.sketches_to_parts_result": "Skice premještene u dio na kojem se nalaze: {moved}; ostale na mjestu: {stayed} ({why})", "browser.units": "Jedinice: {units}", "cam.flat": "Ravno lice", "cam.follower": "Pratitelj", @@ -817,6 +831,8 @@ "cmd.appearance_pick_up": "Preuzmi izgled", "cmd.appearance_replace": "Zamijeni izgled", "cmd.assembly_bom": "Sastavnica", + "cmd.assembly_mass_properties": "Svojstva mase", + "cmd.body.print_face": "Ploha ispisa", "cmd.body_rename": "Preimenuj tijelo", "cmd.browser_collapse_all": "Sažmi sve", "cmd.browser_expand_all": "Proširi sve", @@ -845,6 +861,7 @@ "cmd.component_extract": "Izdvoji u datoteku", "cmd.component_finish_edit": "Završi uređivanje", "cmd.component_from_bodies": "Izradi komponente iz tijela", + "cmd.component_hide_history": "Sakrij vremensku traku komponente", "cmd.component_insert_design": "Umetni dizajn", "cmd.component_links": "Popis veza", "cmd.component_list": "Popis komponenti", @@ -853,6 +870,7 @@ "cmd.component_move_bodies": "Premjesti tijela u komponentu", "cmd.component_move_features": "Premjesti značajke u komponentu", "cmd.component_move_sketches": "Premjesti skice u komponentu", + "cmd.component_move_sketches_to_parts": "Premjesti skice u njihove dijelove", "cmd.component_paste_from_design": "Zalijepi iz drugog dizajna", "cmd.component_paste_new": "Zalijepi kao novo", "cmd.component_properties": "Fizička svojstva komponente", @@ -860,6 +878,7 @@ "cmd.component_rename": "Preimenuj komponentu", "cmd.component_replace_with_link": "Zamijeni vezom", "cmd.component_revert_position": "Vrati položaj", + "cmd.component_show_history": "Prikaži vremensku traku komponente", "cmd.component_unlock": "Otključaj sadržaj", "cmd.component_update_links": "Ažuriraj veze", "cmd.config_activate": "Aktiviraj konfiguraciju", @@ -870,6 +889,7 @@ "cmd.config_rule": "Pravilo konfiguracije", "cmd.config_rules": "Pravila konfiguracije", "cmd.config_table": "Prikaži tablicu konfiguracija", + "cmd.construct.plane.axis_point": "Ravnina kroz os i točku", "cmd.construct_axis_edge": "Os kroz brid", "cmd.construct_axis_normal_to_face": "Os okomita na lice", "cmd.construct_axis_through_cylinder": "Os kroz valjak/stožac/torus", @@ -918,6 +938,11 @@ "cmd.explode_show": "Prikaži rastavljeni prikaz", "cmd.expr_evaluate": "Izračunaj izraz", "cmd.face_delete": "Izbriši lice", + "cmd.file.export_3mf": "Izvezi 3MF", + "cmd.file.export_obj": "Izvezi OBJ", + "cmd.file.export_step": "Izvezi STEP", + "cmd.file.export_stl": "Izvezi STL", + "cmd.file.export_urdf": "Izvezi URDF", "cmd.file_export": "Izvoz", "cmd.file_insert_mesh": "Umetni mrežu", "cmd.file_insert_step": "Umetni STEP", @@ -935,6 +960,7 @@ "cmd.inspect_colored_components": "Omogući boje komponenti", "cmd.inspect_colored_components_disable": "Onemogući boje komponenti", "cmd.inspect_compare": "Usporedi tijela", + "cmd.inspect_compare_picture": "Usporedi sliku", "cmd.inspect_continuity": "Analiza kontinuiteta", "cmd.inspect_curvature_comb": "Analiza češlja zakrivljenosti", "cmd.inspect_curvature_map": "Analiza mape zakrivljenosti", @@ -1025,6 +1051,9 @@ "cmd.pointcloud_edit": "Uredi oblak točaka", "cmd.pointcloud_insert": "Umetni oblak točaka", "cmd.pointcloud_list": "Oblaci točaka", + "cmd.render.compare.divider": "Pomakni razdjelnik usporedbe renderiranja", + "cmd.render.result.discard": "Odbaci rezultat renderiranja", + "cmd.render.result.select": "Odaberi rezultat renderiranja", "cmd.render_aging_describe": "Slojevito starenje površine", "cmd.render_backends": "Pozadinski sustavi renderiranja", "cmd.render_batch": "Renderiraj sve kadrove", @@ -1188,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline kontrolnih točaka (stupanj 5)", "cmd.sketch_spline_fit_point": "Spline kroz točke", "cmd.sketch_spline_insert_point": "Dodaj točku splinea", + "cmd.sketch_spline_remove_point": "Ukloni točku splinea", "cmd.sketch_spline_reverse": "Obrni smjer splinea", "cmd.sketch_spun_profile": "Rotirani profil", "cmd.sketch_toggle_diameter": "Prebaci polumjer / promjer", @@ -1238,9 +1268,11 @@ "cmd.timeline_rollback": "Pomakni oznaku vraćanja", "cmd.timeline_stop": "Zaustavi vremensku traku", "cmd.timeline_suppress": "Potisni značajku", + "cmd.ui.assistant": "Prikaži ili sakrij Asistenta", "cmd.view.render_browser": "Stablo renderiranja", "cmd.view.render_dock": "Premjesti panel renderiranja", "cmd.view.render_focus": "Fokusni prikaz renderiranja", + "cmd.view.status_details": "Detalji statusa prozora prikaza", "cmd.view.status_items": "Statusne stavke prozora prikaza", "cmd.view_ambient_occlusion": "Ambijentalna okluzija", "cmd.view_angle_readout": "Kutovi prikaza", @@ -1271,17 +1303,28 @@ "cmd.view_tool": "Alat za navigaciju", "cmd.view_top": "Pogled odozgo", "cmd.view_visual_style": "Vizualni stil", + "color.blue": "Plava", "color.copy": "Kliknite za kopiranje vrijednosti boje", "color.edit": "Kliknite za uređivanje boje", "color.gamma": "Prikaz vrijednosti boje u gama prostoru 0-255", + "color.green": "Zelena", "color.hex": "Hex", "color.hex_help": "Unesite #rrggbb ili #rrggbbaa; šest znamenki zadržava neprozirnost", "color.hex_hint": "#rrggbb", "color.hue": "Nijansa", "color.linear": "Prikaz vrijednosti boje u linearnom prostoru 0-1", + "color.recent": "Nedavne boje", + "color.recent_help": "Ovdje se pojavljuju boje koje odaberete u bilo kojem polju za boju", + "color.red": "Crvena", + "color.saturation": "Zasićenost (postotak)", "color.saturation_value": "Zasićenost i vrijednost", "color.selected": "Odabrana boja", + "color.step_down": "Smanji za korak", + "color.step_up": "Povećaj za korak", + "color.value": "Vrijednost, svjetlina (postotak)", "config.column_filter_empty": "Nema odgovarajućih stupaca", + "config.rule_parameter_columns": "Navedeni su samo parametri koji imaju stupac u tablici. Dodajte stupac pomoću Dodaj stupac (+) kako biste parametar mogli upotrijebiti ovdje.", + "config.rule_suppression_columns": "Navedene su samo značajke koje imaju stupac Potisni u tablici. Dodajte stupac pomoću Dodaj stupac (+) kako biste ovdje mogli upravljati značajkom.", "contact.components_count": "Komponente: {count}", "contact.enabled_label": "omogućeno", "coupling.gear_1": "Zupčanik 1", @@ -1327,9 +1370,14 @@ "dialog.dimension_name": "Kota: {name}", "dialog.edit_title": "UREDI {title}", "dialog.no_shown_body": "Nema prikazanog tijela za promjenu: prikažite jedno ili odaberite Novo tijelo", + "dialog.pattern_sketch_not_object": "Odaberite tijela ili značajke: skica nije ni jedno ni drugo. Ponovite njezine krivulje pomoću alata Niz ili Zrcali u samoj skici ili je najprije ekstrudirajte.", "dialog.select": "↖ Odaberi", "dialog.selected_count": "↖ Odabrano: {count}", + "dialog.selection_constraint": "Ograničenje {id}", + "dialog.selection_external_curve": "{sketch} · krivulja {id}", "dialog.selection_guidance": "Odaberite ulaz kako biste ga promijenili. Kliknite odabrane objekte kako biste ih uklonili; Ctrl/Cmd-klik ih također uključuje i isključuje. Pogledajte pretpregled, a zatim pritisnite U redu.", + "dialog.selection_midpoint": "Središnja točka · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} od {total}: Odaberite {input}", "dialog.step": "Korak", "document.changed_on_disk": "{name} je promijenjen na disku", @@ -1384,26 +1432,244 @@ "from the rule": "iz pravila", "help.apache": "Apache licenca 2.0", "help.appearance.assign": "Daje odabranim tijelima, licima ili komponentama boju ili izgled materijala, bez promjene njihove težine. Upotrijebite ga kako biste razlikovali dijelove ili pregledali završnu obradu.", + "help.assembly.bom": "Navodi dijelove dizajna ili komponente s količinama, po broju dijela, a popis može spremiti kao CSV ili JSON. Upotrijebite ga kao popis dijelova za narudžbu i montažu.", "help.attributions": "Atribucije (ATTRIBUTION.md)", "help.build": "Verzija {version} · commit {commit} · izgrađeno {date}", + "help.canvas.decal": "Postavlja sliku na ravno lice modela, poput naljepnice. Upotrijebite ga kako biste na dijelu prikazali oznaku, logotip ili otisnuti uzorak.", + "help.canvas.edit": "Mijenja platno: njegov položaj, veličinu, kut, neprozirnost, zrcaljenje, vidljivost ili naziv. Upotrijebite ga kako biste referentnu sliku poravnali sa skicom koju po njoj ocrtavate.", + "help.canvas.insert": "Postavlja PNG ili JPEG sliku na ravninu ili lice kao prozirnu referencu. Upotrijebite ga kako biste u skici ocrtali fotografiju ili crtež, sa slikom skaliranom na poznatu veličinu.", + "help.component.break_link": "Odvaja povezanu komponentu od njezine datoteke dizajna, a njezina tijela ostaju onakva kakva jesu. Upotrijebite ga kad dio više ne treba pratiti promjene u izvornoj datoteci.", + "help.component.capture_position": "Zadržava položaje dijelova koje ste ručno pomaknuli, tako da ti dijelovi ostaju na tim mjestima. Upotrijebite ga nakon povlačenja dijelova na mjesto koje nijedan spoj ne drži.", + "help.component.create": "Dodaje novu, praznu komponentu u dizajn, unutar aktivne komponente osim ako odaberete drugu nadređenu komponentu. Upotrijebite ga kako biste novom dijelu sklopa dali vlastito mjesto za tijela i skice.", "help.component.finish_edit": "Sprema dio koji uređujete na mjestu, vraća se u njegov sklop i ažurira sklop prema njemu. Upotrijebite je kad završite izmjene povezanog dijela.", + "help.component.from_bodies": "Pretvara svako odabrano tijelo u zasebnu komponentu, nazvanu po tijelu. Upotrijebite ga kad dizajn izgrađen od samostalnih tijela treba postati sklop čije se dijelove može spajati i pomicati.", + "help.component.insert_design": "Umeće drugi spremljeni dizajn kao komponentu povezanu s njegovom datotekom, a njegova puna tijela postavlja onako kako su u njemu. Upotrijebite ga kako biste dio ponovno upotrijebili u sklopu i preuzeli kasnije promjene naredbom Ažuriraj veze.", + "help.component.properties": "Prikazuje volumen, masu, središte mase i momente tromosti komponente, prema materijalima njezinih tijela. Upotrijebite ga kako biste provjerili težinu i ravnotežu sklopa.", + "help.component.revert_position": "Vraća ručno pomaknute dijelove na mjesto na kojem su bili, odbacujući pomake koji nisu zabilježeni. Upotrijebite ga kako biste poništili probne pomake u sklopu.", + "help.component.update_links": "Ponovno čita povezane datoteke dizajna i zamjenjuje tijela koja su se promijenila. Upotrijebite ga nakon uređivanja dijela koji ovaj sklop koristi.", + "help.config.configure": "Dodaje parametre, značajke, materijale ili izglede kao stupce tablice konfiguracija. Upotrijebite ga kako biste izradili inačice jednog dizajna, primjerice veličine nekog dijela.", + "help.config.preview": "Provjerava može li se redak tablice konfiguracija ponovno izgraditi, bez promjene dizajna ili njegove vremenske trake. Upotrijebite ga prije prebacivanja na inačicu u čiju ispravnost niste sigurni.", + "help.config.rules": "Prikazuje pravila tablice konfiguracija, njezine retke i koji je redak aktivan. Upotrijebite ga kako biste vidjeli kako su postavljene inačice dizajna.", + "help.config.table": "Prikazuje tablicu konfiguracija: jedan redak po inačici, jedan stupac po parametru ili značajki, te podudara li se dizajn još s aktivnim retkom. Upotrijebite ga za pregled inačica dizajna.", "help.connect_note": "Ponovno pokrenite svakog asistenta kako bi učitao SolidCraft poslužitelj. Svaka datoteka sigurnosno je kopirana kao .bak prije promjene.", "help.connect_title": "Poveži AI asistente", + "help.construct.axis.edge": "Izrađuje pomoćnu os duž ravnog brida ili linije skice. Upotrijebite je kao os za rotaciju, kružni niz ili spoj.", + "help.construct.axis.normal_to_face": "Izrađuje pomoćnu os kroz točku, okomito na lice. Upotrijebite je kao os koja stoji ravno iz površine.", + "help.construct.axis.through_cylinder": "Izrađuje pomoćnu os kroz središte lica valjka, stošca ili torusa ili kružnog brida. Upotrijebite je za okretanje ili umnožavanje značajki oko okruglog dijela.", + "help.construct.axis.two_planes": "Izrađuje pomoćnu os na mjestu gdje se dvije ravnine ili ravna lica sijeku. Upotrijebite je kad je potrebna os pravac između dvaju lica.", + "help.construct.axis.two_points": "Izrađuje pomoćnu os kroz dvije točke, vrhove ili točke skice. Upotrijebite je za os koja prolazi između dvaju poznatih položaja.", + "help.construct.plane.along_path": "Izrađuje pomoćnu ravninu okomitu na brid ili krivulju, na položaju duž njih. Upotrijebite je za skiciranje profila za povlačenje ili presjeka putanje.", + "help.construct.plane.at_angle": "Izrađuje pomoćnu ravninu zakrenutu za kut u odnosu na ravninu ili lice, oko osi ili brida. Upotrijebite je za nagnute skice, primjerice kutnog nosača.", + "help.construct.plane.axis_point": "Izrađuje pomoćnu ravninu koja sadrži os i točku izvan te osi. Odaberite os ishodišta ili pomoćnu os, ravni brid ili liniju skice, pa vrh, točku skice ili pomoćnu točku. Točka na osi ne može odrediti jedinstvenu ravninu.", + "help.construct.plane.midplane": "Izrađuje pomoćnu ravninu na pola puta između dviju ravnina ili ravnih lica, ili ravninu koja raspolavlja kut kad se one sijeku pod kutom. Upotrijebite je kao ravninu simetrije za zrcaljenje.", + "help.construct.plane.offset": "Izrađuje pomoćnu ravninu paralelnu s ravninom ili ravnim licem, na određenoj udaljenosti ili kroz točku. Upotrijebite je za skiciranje na zadanoj visini iznad lica.", + "help.construct.plane.perpendicular": "Izrađuje pomoćnu ravninu koja sadrži liniju ili brid i okomita je na ravninu ili lice. Upotrijebite je za skiciranje uspravno na modelu duž brida.", + "help.construct.plane.tangent": "Izrađuje pomoćnu ravninu koja u jednoj točki dodiruje valjak, stožac, kuglu ili torus. Upotrijebite je za skiciranje na boku okruglog dijela.", + "help.construct.plane.three_points": "Izrađuje pomoćnu ravninu kroz tri točke. Upotrijebite je za ravninu određenu položajima na modelu, primjerice trima kutovima.", + "help.construct.plane.two_edges": "Izrađuje pomoćnu ravninu kroz dva ravna brida ili linije koji leže u istoj ravnini. Upotrijebite je za ravninu kroz dio, primjerice kroz dva nasuprotna brida.", + "help.construct.point.along_path": "Izrađuje pomoćnu točku na položaju duž brida ili krivulje. Upotrijebite je kao referencu negdje na putanji.", + "help.construct.point.center": "Izrađuje pomoćnu točku u središtu kružnog brida, kružnice ili luka skice, kugle ili torusa. Upotrijebite je kao referencu za provrte, osi i spojeve.", + "help.construct.point.edge_plane": "Izrađuje pomoćnu točku na mjestu gdje brid ili linija prolazi kroz ravninu ili ravno lice. Upotrijebite je za označavanje mjesta gdje putanja siječe ravninu.", + "help.construct.point.three_planes": "Izrađuje pomoćnu točku na mjestu gdje se sijeku tri ravnine ili ravna lica. Upotrijebite je kao referencu kuta, čak i tamo gdje model nema vrh.", + "help.construct.point.two_edges": "Izrađuje pomoćnu točku na mjestu gdje se dva brida ili linije sijeku ili si najviše približe. Upotrijebite je kao referencu u virtualnom kutu.", + "help.construct.point.vertex": "Izrađuje pomoćnu točku na vrhu ili točki skice. Upotrijebite je kao referencu koja ostaje kad se skica ili tijelo oko nje sakriju.", + "help.contact.check": "Navodi parove dijelova u skupovima kontakata koji u svojem trenutnom položaju prolaze jedan kroz drugi. Upotrijebite ga za pronalaženje sudara prije pokretanja spojeva ili studije kretanja.", + "help.contact.create": "Grupira dva ili više dijelova u skup kontakata čija se tijela tijekom pomicanja spojeva sprječavaju da prolaze jedno kroz drugo. Upotrijebite ga za dijelove koji se trebaju zaustaviti kad se dodirnu, primjerice polugu uz njezin graničnik.", + "help.contact.disable_all": "Isključuje kontakt, pa se pokretani spojevi i studije kretanja više ne zaustavljaju tamo gdje se dijelovi dodiruju. Upotrijebite ga za ponovno slobodno pomicanje dijelova ili za bolji odziv velikog sklopa.", + "help.contact.edit": "Mijenja skup kontakata: dijelove koje sadrži, njegov naziv ili je li potisnut; može i izbrisati skup. Upotrijebite ga kako biste prilagodili koji se dijelovi sprječavaju da prolaze jedan kroz drugi.", + "help.contact.enable_all": "Stavlja svaki dio sklopa u jedan skup kontakata, pa nijedna dva dijela ne mogu proći jedan kroz drugi tijekom pomicanja spojeva. Upotrijebite ga za brzu provjeru cijelog mehanizma.", + "help.contact.enable_sets": "Uključuje kontakt za skupove kontakata koje ste definirali, pa se pokretani spojevi i studije kretanja zaustavljaju tamo gdje bi njihovi dijelovi prošli jedan kroz drugi. Upotrijebite ga kako biste vratili svoje skupove nakon isključivanja kontakta.", + "help.contact.list": "Navodi skupove kontakata dizajna, dijelove u svakome od njih i je li kontakt uključen. Upotrijebite ga za provjeru kako je kontakt postavljen prije pokretanja sklopa.", + "help.document.inspect": "Prikazuje pregled dizajna: njegove komponente, tijela, skice, značajke i parametre. Upotrijebite ga kako biste se snašli u dizajnu koji niste sami izradili.", + "help.document.units": "Mijenja jedinice u kojima dizajn prikazuje duljine, primjerice mm ili inče. Geometrija zadržava svoju veličinu; mijenjaju se samo prikaz i obični brojevi.", + "help.edit.checkpoint": "Pamti dizajn, aktivnu skicu i povijest poništavanja onakve kakvi su sada. Upotrijebite ga prije isprobavanja nečeg rizičnog od čega ćete se možda htjeti vratiti.", + "help.edit.restore_checkpoint": "Vraća se na kontrolnu točku, uključujući povijest poništavanja. Upotrijebite ga kako biste jednim korakom odbacili sve učinjeno od kontrolne točke.", + "help.explode.create": "Izrađuje rastavljeni prikaz koji dijelove odmiče od središta sklopa ili prema pomacima koje zadate. Upotrijebite ga za prikaz sastavljanja sklopa, za upute ili prezentacije.", "help.face.delete": "Uklanja odabrana lica i pušta da susjedna lica zatvore otvor, ili ostavlja otvor otvorenim kao plohu. Upotrijebite ga kako biste uklonili zaobljeni brid, provrt ili ispupčenje koje smeta.", + "help.file.insert_mesh": "Dodaje 3MF, STL, OBJ, PLY ili glTF datoteku u dizajn kao mrežna tijela u novoj komponenti. Upotrijebite ga kako biste preuzeti ili skenirani model postavili uz svoj dizajn kao referencu.", + "help.file.insert_step": "Dodaje STEP, IGES, FreeCAD ili Rhino datoteku u dizajn kao puna tijela u novoj komponenti; dijelovi sklopa postaju ugniježđene komponente. Upotrijebite ga za unos modela od dobavljača ili iz drugih CAD programa.", + "help.file.save_mesh": "Sprema tijela kao STL, 3MF ili OBJ mrežu, s glatkoćom zakrivljenih lica po vašem izboru. Upotrijebite ga za pripremu dijelova za 3D ispis ili za programe koji čitaju mreže.", + "help.file.send_to_slicer": "Sprema odabrana tijela kao 3MF datoteku i otvara je u slicer programu koji odaberete. Upotrijebite ga za prijelaz s modela na ispis u jednom koraku.", "help.font_details": "Sučelje koristi ugrađene fontove biblioteke egui (Ubuntu Light i Hack, pod licencama Ubuntu Font Licence i MIT/Bitstream Vera; Noto Emoji i font emoji ikona, pod licencama OFL i MIT). Tekst skice koristi Liberation Sans (SIL OFL 1.1). Neobavezni paket fontova Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), nije uključen u izdanja SolidCrafta.", "help.fonts": "Fontovi", + "help.frame.member": "Postavlja profil, primjerice cijev ili aluminijski ekstrudirani profil, duž linija skice okvira, jedan element po liniji. Upotrijebite ga za izradu okvira, regala i zavarenih konstrukcija.", + "help.inspect.accessibility": "Boji lica do kojih alat može doći iz jednog smjera i ona do kojih ne može. Upotrijebite ga za provjeru dijela za strojnu obradu ili kalupljenje s te strane.", + "help.inspect.center_of_mass": "Prikazuje središte mase tijela, svakog zasebno i svih zajedno, pri jednolikoj gustoći. Upotrijebite ga za provjeru ravnoteže i mjesta na kojem će se dio prevrnuti.", + "help.inspect.colored_components": "Daje svakoj komponenti vlastitu privremenu boju, bez promjene izgleda. Upotrijebite ga kako biste na prvi pogled razlikovali dijelove sklopa.", + "help.inspect.compare": "Uspoređuje dva tijela i prikazuje gdje jedno ima materijala kojeg drugo nema, s volumenom i odstupanjem. Upotrijebite ga za provjeru izmijenjenog ili uvezenog dijela u odnosu na izvornik.", + "help.inspect.continuity": "Provjerava koliko glatko se lica spajaju duž svojih bridova (razmake, lomove ili skokove zakrivljenosti) i sjenčanjem označava šavove. Upotrijebite ga za pronalaženje mjesta na kojima se plohe ne spajaju čisto.", + "help.inspect.curvature_comb": "Crta češljeve duž krivulja, bridova ili lica čiji zupci pokazuju koliko se snažno savijaju. Upotrijebite ga za uočavanje ravnih mjesta, lomova i neujednačene zakrivljenosti.", + "help.inspect.curvature_map": "Boji lica prema jakosti zakrivljenosti, crveno tamo gdje je polumjer malen. Upotrijebite ga za pronalaženje uskih mjesta i procjenu glatkoće plohe.", + "help.inspect.draft": "Boji lica prema kutu nagiba u odnosu na smjer vađenja iz kalupa i označava ona s premalo nagiba. Upotrijebite ga za provjeru dijela prije kalupljenja ili lijevanja.", + "help.inspect.environment_map": "Prikazuje model s reflektirajućom završnom obradom nalik zrcalu. Upotrijebite ga za procjenu toka ploha prema načinu na koji se odrazi pružaju preko njih.", + "help.inspect.interference": "Pronalazi tijela koja se preklapaju i prikazuje svako preklapanje s njegovim volumenom. Upotrijebite ga za provjeru sudaraju li se dijelovi u sklopu.", + "help.inspect.isocurve": "Crta izoparametarske krivulje lica, mrežu na kojoj je ploha izgrađena. Upotrijebite ga kako biste vidjeli kako ploha teče i gdje se zgušnjava.", + "help.inspect.measure": "Mjeri duljine, udaljenosti, kutove, površine i polumjere među elementima koje odaberete, ili volumen i masu tijela. Upotrijebite ga za provjeru mjera i zazora.", + "help.inspect.minimum_radius": "Pronalazi najmanji polumjer zakrivljenosti krivulja, bridova ili lica i mjesto na kojem se nalazi. Upotrijebite ga kako biste provjerili može li alat ili mlaznica pratiti oblik.", + "help.inspect.section": "Presijeca prikaz duž ravnine i šrafira presječena lica, bez promjene modela. Upotrijebite ga za pogled u unutrašnjost dijelova i sklopova.", + "help.inspect.zebra": "Prikazuje crne i bijele pruge odražene na licima modela. Upotrijebite ga za procjenu glatkoće: pruge koje se prekidaju ili lome na bridu upućuju na loš prijelaz.", + "help.joint.as_built": "Spaja dva dijela tamo gdje već jesu, bez pomicanja ijednog od njih, i određuje kako se još smiju kretati. Upotrijebite ga za dijelove koje ste već postavili u konačni položaj.", + "help.joint.cam": "Povezuje rotirajući brijeg sa sljedbenikom, pa sljedbenik klizi ili se njiše dok ispod njega prolazi obris brijega. Upotrijebite ga za brijegove, ekscentre i pogone ventila.", + "help.joint.create": "Spaja dva dijela na ishodištima spojeva koja odaberete i pomiče drugi dio na mjesto; vrsta spoja određuje kako se još smiju kretati. Upotrijebite ga za izradu sklopa čiji se dijelovi kreću poput stvarnog mehanizma.", + "help.joint.drive": "Postavlja kut ili udaljenost spoja i s njim pomiče dijelove, unutar njegovih granica; povezani spojevi i zatvorene petlje slijede ga. Upotrijebite ga za provjeru kreće li se mehanizam kako je zamišljeno.", + "help.joint.gear": "Povezuje dva rotirajuća spoja prijenosnim omjerom, pa pokretanje jednog okreće drugi. Upotrijebite ga za čelne zupčanike i zupčanike s unutarnjim ozubljenjem, s omjerom iz polumjera diobenih kružnica ili broja zubaca.", + "help.joint.limits": "Određuje koliko se spoj smije zakrenuti ili pomaknuti, kao najmanju i najveću vrijednost, ili briše te granice. Upotrijebite ga kako bi šarka, klizač ili poluga ostali unutar svojeg stvarnog raspona kretanja.", + "help.joint.motion_link": "Povezuje dva spoja omjerom i odmakom, pa pokretanje jednog pomiče drugi. Upotrijebite ga za čvrst odnos među spojevima koji nije pokriven naredbama Zupčanik, Zupčasta letva i zupčanik ili Vijak.", + "help.joint.origin": "Postavlja imenovano ishodište spoja na dio: u središte lica ili okruglog kraja, sredinu brida, kut ili točku. Upotrijebite ga za pripremu mjesta na kojima se spojevi vežu; ishodište odabrano na licu prati ga kad dio promijeni veličinu.", + "help.joint.rack_pinion": "Povezuje rotirajući mali zupčanik s kliznom zupčastom letvom, pa se letva pomiče za duljinu diobene kružnice koju mali zupčanik prevali. Upotrijebite ga za pogone s letvom, upravljanje i linearne stolove.", + "help.joint.reach": "Pomiče točku na dijelu prema cilju mijenjajući spojeve na njezinu lancu, unutar njihovih granica. Upotrijebite ga za namještanje mehanizma prema tome gdje mu treba biti kraj, primjerice vrh ruke robota.", + "help.joint.rigid_group": "Zaključava odabrane dijelove zajedno onakve kakvi jesu, pa se pomiču kao jedan. Upotrijebite ga za dijelove koji pripadaju zajedno i među kojima nema kretanja.", + "help.joint.screw": "Povezuje okretanje i klizanje korakom, pa svaki okretaj pomiče za tu udaljenost. Upotrijebite ga za vodeće vijke, vijke i navojna vretena.", + "help.library.apply": "Primjenjuje materijal ili izgled iz lokalne datoteke biblioteke na tijela, lica ili komponente. Upotrijebite ga za ponovnu upotrebu materijala koje ste spremili iz drugog dizajna.", + "help.library.export": "Sprema materijale i izglede dizajna u datoteku biblioteke. Upotrijebite ga za njihovo dijeljenje ili ponovnu upotrebu u drugim dizajnima.", + "help.library.inspect": "Provjerava datoteku biblioteke i navodi njezine materijale i izglede, bez promjene dizajna. Upotrijebite ga kako biste prije primjene vidjeli što biblioteka sadrži.", "help.licences": "Licence", "help.material.assign": "Određuje od čega su odabrana tijela izrađena, npr. čelik, aluminij ili ABS. Upotrijebite ga kako bi masa i težina odgovarale stvarnom dijelu.", + "help.material.properties.validate": "Provjerava karticu podataka o materijalu radi dosljednosti brojeva i vrijednosti koje nedostaju. Upotrijebite ga prije nego se na podatke oslonite za masu ili krutost.", + "help.mesh.convert": "Ponovno izrađuje mrežno tijelo, primjerice STL, kao uredivo puno tijelo s ravnim i cilindričnim licima. Upotrijebite ga za izmjenu uvezenih strojnih dijelova kao da su modelirano tijelo.", "help.mit": "MIT licenca", + "help.motion.study": "Postavlja vrijednosti spojeva u koracima duž vremenske trake i reproducira ih kao animaciju. Upotrijebite ga za praćenje kretanja mehanizma kroz slijed i provjeru zazora usput.", + "help.motion.trace": "Prati putanju kojom ide točka na dijelu dok se reproducira studija kretanja ili pokreće spoj i, nakon potvrde, zadržava je kao krivulju 3D skice. Upotrijebite ga kako biste vidjeli dokle mehanizam doseže ili kako biste gradili na njegovoj putanji.", "help.notice": "NOTICE", + "help.occurrence.ground": "Učvršćuje dio na mjestu ili ga ponovno oslobađa, pa spojevi pomiču ostale dijelove oko njega. Upotrijebite ga za okvir ili podnožje na kojem je izgrađen ostatak sklopa.", "help.occurrence.move": "Pomiče dio sklopa samo u stupnjevima slobode koje dopuštaju njegovi spojevi. Odaberite lice dijela, a zatim povucite dostupnu strelicu ili luk.", "help.parameters.change": "Otvara tablicu imenovanih vrijednosti i izraza koji upravljaju kotama dizajna. Upotrijebite je kako biste promijenili mjeru na jednom mjestu, a sve značajke koje je koriste je slijede.", + "help.parameters.export": "Sprema parametre dizajna kao CSV ili JSON. Upotrijebite ga za uređivanje u proračunskoj tablici ili prijenos u drugi dizajn.", + "help.parameters.graph": "Prikazuje koji parametri i značajke koriste koje druge, te petlje ili pogreške među njima. Upotrijebite ga kako biste vidjeli na što će utjecati promjena parametra.", + "help.parameters.import": "Čita parametre iz CSV ili JSON datoteke u dizajn, i to sve ili nijedan. Upotrijebite ga za unos vrijednosti iz proračunske tablice ili drugog dizajna.", + "help.parameters.move": "Premješta korisnički parametar ispred ili iza drugog na popisu. Upotrijebite ga za držanje povezanih parametara zajedno.", + "help.parts.fastener": "Dodaje standardni vijak, svornjak, maticu, podlošku, zatik ili ležaj u odabranoj veličini. Postavljen na provrt, smješta se u njega spojem, pa spojne elemente ne morate modelirati sami.", + "help.parts.insert": "Umeće standardni dio u odabranoj obitelji, veličini i duljini. Postavljen na rub ili stijenku provrta, smješta se na provrt krutim spojem.", + "help.parts.library": "Otvara standardne dijelove: vijke, svornjake, matice, podloške, bezglave vijke, cilindrične zatike i ležajeve u standardnim veličinama. Upotrijebite ga za dodavanje standardnog dijela umjesto da ga sami modelirate.", + "help.parts.resize": "Mijenja veličinu ili duljinu umetnutog standardnog dijela i ponovno ga izgrađuje; njegovi spojevi ga drže na mjestu. Upotrijebite ga kad se vijak pokaže predugim ili provrtu treba druga veličina.", + "help.plastic.assign_rule": "Dodjeljuje pravilo za plastiku tijelima, pa njihove značajke za plastiku preuzimaju njegov nagib i zazor kao zadane vrijednosti. Upotrijebite ga za jednokratno postavljanje oblikovanog dijela za sve njegove značajke.", + "help.plastic.boss": "Dodaje ispust za vijak na licu: stup s neobaveznim provrtom, nagibom, zaobljenjem korijena i potpornim rebrima. Upotrijebite ga za točke vijaka u kalupljenim ili ispisanim kućištima.", + "help.plastic.lip": "Dodaje usnu ili odgovarajući utor uz rub tijela s ljuskom. Upotrijebite ga kako bi se dvije polovice kućišta naslanjale jedna na drugu i čvrsto zatvarale.", + "help.plastic.manage_rules": "Izrađuje i uređuje pravila za plastiku: materijal, debljinu stijenke, polumjere, zazor i nagib. Upotrijebite ih kako bi značajke oblikovanog dijela ostale dosljedne.", + "help.plastic.rest": "Dodaje oslonac na licu: okruglu ili pravokutnu podlogu, punu ili šuplju, s nagibom. Upotrijebite ga kao potporu ili distancu u oblikovanom kućištu.", + "help.plastic.snap_fit": "Dodaje kuku za škljocajući spoj na licu, s njezinom duljinom, debljinom i zapinjačem. Upotrijebite ga za spajanje dijelova kopčanjem, bez vijaka.", "help.pointcloud.insert": "Umetnite PLY, XYZ ili PTS skeniranje kao oblak točaka uz model. Koristite ga kao referencu pri izradi modela iz izmjerenih podataka.", + "help.sheet.convert": "Pretvara ploču ili tijelo s ljuskom ujednačene debljine u tijelo od lima, sa savijanjima na bridovima koje odaberete. Upotrijebite ga kako biste postojeći dio učinili razvijivim.", + "help.sheet.export_bend_table": "Sprema tablicu savijanja tijela od lima kao CSV ili JSON: kutove, polumjere i položaje savijanja u razvijenom obliku. Upotrijebite ga za stroj za savijanje ili radionicu.", + "help.sheet.export_dxf": "Sprema razvijeni oblik kao DXF, s obrisima, linijama savijanja i neobaveznim bilješkama o savijanju. Upotrijebite ga za lasersko, plazma ili vodenim mlazom rezanje.", + "help.sheet.flange": "Dodaje prirubnicu: osnovnu ploču iz skice, stijenku duž otvorene konture skice ili savijenu stijenku na bridovima lima. Upotrijebite je za izgradnju dijelova od lima.", + "help.sheet.flat_pattern": "Izrađuje razvijeni oblik tijela od lima, s njegovom veličinom, izrezima i linijama savijanja. Upotrijebite ga za provjeru pripremka prije rezanja.", + "help.sheet.fold": "Presavija lim duž linije skice za zadani kut i polumjer. Upotrijebite ga za savijanje ravnog lima nakon što ste u njega urezali značajke.", + "help.sheet.hem": "Preklapa rub lima sam na sebe. Upotrijebite ga za sigurne, krute rubove bez oštrih srha.", + "help.sheet.manage_rules": "Izrađuje i uređuje pravila za lim: debljinu, polumjer savijanja, K-faktor, rasterećenja i razmake. Upotrijebite ih za usklađivanje s materijalom i alatima vaše radionice.", + "help.sheet.path_flange": "Dodaje lanac prirubnica duž ruba lima, prateći otvoreni lanac linija skice. Upotrijebite je za profile poput U ili Z oblika u jednom koraku.", + "help.sheet.perforate": "Dodaje polje provrta po cijelom ravnom limu, u pomaknutom ili kvadratnom rasporedu. Upotrijebite ga za ventilacijske otvore, rešetke i lakše ploče.", + "help.sheet.refold": "Ponovno savija razvijeno tijelo od lima. Upotrijebite ga nakon dodavanja značajki ravnom limu.", + "help.sheet.unfold": "Razvija sva savijanja tijela od lima. Upotrijebite ga za dodavanje provrta ili izreza koji moraju prelaziti preko savijanja, a zatim ponovno presavijte.", + "help.sketch.arc.center_point": "Crta kružni luk oko središnje točke, od početne do završne točke. Upotrijebite ga kad je središte luka poznato, primjerice za polumjer oko provrta ili okretišta.", + "help.sketch.arc.tangent": "Crta luk koji počinje na kraju linije ili luka i nastavlja se tangentno na njega. Upotrijebite ga za nastavak lanca glatkim zavojem umjesto kutom.", + "help.sketch.arc.three_point": "Crta luk od početne do završne točke kroz treću točku. Upotrijebite ga kad luk mora prolaziti kroz zadane točke, a ne oko poznatog središta.", + "help.sketch.arc3d": "Crta točan kružni luk u prostoru kroz tri točke, uz uključenu 3D skicu. Upotrijebite ga za zavoje u putanjama i vodilicama koji izlaze iz ravnine skice.", + "help.sketch.auto_constrain": "Dodaje ograničenja koja skica već gotovo ima, primjerice vodoravnost, paralelnost ili podudarnost, a zatim je kotira dok nije potpuno ograničena. Upotrijebite ga za učvršćivanje grubo nacrtane skice u jednom koraku.", + "help.sketch.auto_constrain_from_datum": "Radi kao Automatska ograničenja, ali položaje mjeri od referentne točke koju odaberete umjesto od ishodišta. Upotrijebite ga kad je dio raspoređen od jedne referentne točke, primjerice kuta ili provrta.", + "help.sketch.blend_curve": "Spaja krajeve dviju krivulja glatkim splineom koji je tangentan na obje, ili i kontinuiran po zakrivljenosti ako tako odaberete. Upotrijebite ga za premošćivanje razmaka među krivuljama bez loma.", + "help.sketch.break": "Dijeli krivulju na dijelove tamo gdje je sijeku druge krivulje ili u točkama koje na nju postavite. Upotrijebite ga kad dio krivulje treba vlastito ograničenje ili ga treba zasebno izbrisati.", + "help.sketch.cancel": "Napušta skicu i odbacuje sve promjene učinjene od njezina stvaranja ili otvaranja za uređivanje. Naredba Poništi vraća promjene.", + "help.sketch.centerline": "Prebacuje linije između običnih linija i središnjih linija, osi koje profili izostavljaju. Središnju liniju upotrijebite kao os za rotaciju, zrcaljenje ili ograničenje simetrije.", + "help.sketch.chamfer.distance_angle": "Skošuje kut između dviju linija, zadan udaljenošću duž prve linije i kutom. Upotrijebite ga kad crtež daje skošenje kao duljinu i kut, primjerice 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Skošuje kut između dviju linija jednakom udaljenošću unatrag duž obiju. Upotrijebite ga za uobičajeno skošenje od 45° na obrisu.", + "help.sketch.chamfer.two_distance": "Skošuje kut između dviju linija, zadan zasebnom udaljenošću duž svake linije. Upotrijebite ga za skošenja koja nisu 45°, zadana kao dvije duljine.", + "help.sketch.circle.center": "Crta kružnicu iz njezina središta i promjera. Upotrijebite ga za provrte, ispuste i druge okrugle značajke čije je središte poznato.", + "help.sketch.circle.three_point": "Crta kružnicu kroz tri točke. Upotrijebite ga kad kružnica mora prolaziti kroz zadane točke, primjerice postojeće geometrije.", + "help.sketch.circle.three_tangent": "Crta kružnicu koja dodiruje tri elementa (linije, kružnice ili lukove). Upotrijebite ga za uklapanje kružnice u prostor među tri krivulje, primjerice upisane kružnice trokuta.", + "help.sketch.circle.two_point": "Crta kružnicu iz dvaju krajeva njezina promjera. Upotrijebite ga kad su poznate rubne točke kružnice, a ne njezino središte.", + "help.sketch.circle.two_tangent": "Crta kružnicu zadane veličine koja dodiruje dva elementa (linije, kružnice ili lukove). Upotrijebite ga za zaobljenje stalnog polumjera između dviju krivulja.", + "help.sketch.conic": "Crta koniku između dviju krajnjih točaka, oblikovanu vršnom točkom i vrijednošću rho. Upotrijebite ga za glatke prijelaze čiju punoću želite podesiti, od ravnog do gotovo oštrog kuta.", + "help.sketch.constrainer": "Primjenjuje ograničenje koje jedna ili dvije odabrane krivulje već gotovo imaju, primjerice vodoravnost, paralelnost, tangentnost ili jednakost. Upotrijebite ga za sređivanje ručno nacrtane skice jedan po jedan odnos.", + "help.sketch.constraint.coincident": "Čini da točka leži na drugoj točki, krivulji ili osi skice. Upotrijebite ga za zatvaranje razmaka u profilu ili za postavljanje točke na liniju.", + "help.sketch.constraint.collinear": "Čini da dvije linije leže na istom pravcu. Upotrijebite ga za poravnanje prekinutih rubova, primjerice obiju strana zareza.", + "help.sketch.constraint.concentric": "Daje dvjema kružnicama ili lukovima isto središte. Upotrijebite ga za prstenove, cilindrična upuštenja i stepenaste osovine.", + "help.sketch.constraint.curvature": "Čini da dvije krivulje koje se susreću u krajnjoj točki nastave s istom zakrivljenošću (G2). Upotrijebite ga tamo gdje tangentni prijelaz nije dovoljno gladak, primjerice na vidljivim plohama.", + "help.sketch.constraint.equal": "Izjednačuje duljine linija ili polumjere kružnica i lukova. Upotrijebite ga kako bi jedna kota upravljala s više istovjetnih elemenata.", + "help.sketch.constraint.fix": "Fiksira točke ili krivulje tamo gdje jesu ili ih ponovno oslobađa. Upotrijebite ga za geometriju koja se ne smije pomaknuti kad povlačite ili rješavate skicu.", + "help.sketch.constraint.horizontal_vertical": "Čini liniju, ili liniju između dviju točaka, vodoravnom ili okomitom, što god je bliže. Upotrijebite ga za poravnanje obrisa s osima skice.", + "help.sketch.constraint.midpoint": "Postavlja točku na sredinu linije ili spaja središnje točke dviju linija. Upotrijebite ga za centriranje geometrije na bridu.", + "help.sketch.constraint.parallel": "Čini dvije linije paralelnima. Upotrijebite ga za stranice koje moraju ostati paralelne kad se druge kote promijene.", + "help.sketch.constraint.perpendicular": "Čini da se dvije linije susreću pod pravim kutom. Upotrijebite ga za pravokutne kutove između linija koje nisu na osima skice.", + "help.sketch.constraint.polygon": "Pretvara zatvoreni lanac linija u pravilni mnogokut: jednake stranice, a svaki vrh na istoj kružnici. Upotrijebite ga kako biste ručno nacrtani mnogokut učinili pravilnim i takvim ga zadržali.", + "help.sketch.constraint.symmetry": "Čini da dvije točke ili krivulje budu zrcalne jedna drugoj preko linije ili oko točke. Upotrijebite ga za održavanje simetričnosti profila kad mijenjate jednu stranu.", + "help.sketch.constraint.tangent": "Čini da se dvije krivulje, primjerice linija i luk, dodiruju tangentno. Upotrijebite ga za glatke prijelaze bez loma.", + "help.sketch.construction": "Prebacuje krivulje između obične i pomoćne geometrije, koju profili izostavljaju. Pomoćne krivulje upotrijebite kao pomagala za raspored, reference i kote.", + "help.sketch.construction_line": "Izradite beskonačni pomoćni pravac kroz dvije točke. Upotrijebite ga kako biste rasporedili skicu bez razdvajanja profila.", + "help.sketch.construction_line.angle": "Izradite beskonačni pomoćni pravac pod kutom od osi X skice. Odaberite točku i upišite kut ili odaberite smjer.", + "help.sketch.construction_line.bisector": "Odaberite dvije ravne linije skice koje se sijeku, pa jednu od dviju simetrala kuta. Rezultat prati izvorne linije.", + "help.sketch.construction_line.horizontal": "Izradite beskonačni vodoravni pomoćni pravac kroz točku. Njegovo ograničenje vodoravnosti ostaje na snazi pri kasnijim promjenama.", + "help.sketch.construction_line.parallel": "Odaberite ravnu liniju skice, pa postavite paralelni beskonačni pomoćni pravac. Desnim klikom odaberite drugu referencu.", + "help.sketch.construction_line.perpendicular": "Odaberite ravnu liniju skice, pa postavite beskonačni pomoćni pravac okomit na nju. Desnim klikom odaberite drugu referencu.", + "help.sketch.construction_line.tangent_at": "Izradite tangentu u točki na kružnici ili kružnom luku, ili u krajnjoj točki otvorenog splinea ili konike. Odaberite krivulju, pa točku dodira.", + "help.sketch.construction_line.tangent_external": "Odaberite kružnicu ili kružni luk, pa vanjsku točku i rješenje tangente. Pregledi prikazuju samo dodirne točke na nacrtanom luku.", + "help.sketch.construction_line.tangent_two": "Odaberite dvije kružnice ili kružna luka, pa u pregledu odaberite zajedničku tangentu. Dodirne točke moraju ležati na nacrtanim krivuljama.", + "help.sketch.construction_line.vertical": "Izradite beskonačni okomiti pomoćni pravac kroz točku. Njegovo ograničenje okomitosti ostaje na snazi pri kasnijim promjenama.", + "help.sketch.copy": "Kopira odabrane krivulje i točke skice zajedno s ograničenjima i kotama među njima. Zalijepite ih u ovu ili u drugu skicu.", + "help.sketch.create": "Započinje novu 2D skicu na ravnini ili ravnom licu modela. Svaka naredba Ekstrudiraj, Rotiraj i Povlačenje počinje skicom.", + "help.sketch.cut": "Kopira odabranu geometriju skice i briše je iz skice, u jednom koraku poništavanja. Zalijepite je drugdje u ovoj skici ili u drugu skicu.", + "help.sketch.dimension": "Dodaje upravljačku kotu: duljinu, udaljenost, kut, polumjer ili promjer, ovisno o tome što odaberete. Upišite vrijednost ili naziv parametra, a skica će je slijediti.", + "help.sketch.edit": "Otvara postojeću skicu za uređivanje. Značajke izgrađene na njoj ažuriraju se kad dovršite skicu.", + "help.sketch.ellipse": "Crta elipsu iz njezina središta, kraja velike osi i točke na maloj strani. Upotrijebite ga za ovalne otvore, brijegove i druge izdužene okrugle oblike.", "help.sketch.equation_curve": "Crta krivulju prema formulama: x(t) i y(t) ili y = f(x), u zadanom rasponu. Formule mogu koristiti parametre i krivulja ih prati: upotrijebite je za sinusoidu, spiralu ili evolventu zuba zupčanika.", + "help.sketch.extend": "Produljuje liniju ili luk do najbliže krivulje na njegovu putu ili produljuje dvije krivulje dok se ne susretnu. Upotrijebite ga za zatvaranje razmaka u profilu nakon odsijecanja ili uređivanja.", + "help.sketch.fillet": "Zaobljuje kut na kojem se susreću dvije linije ili dva luka lukom zadanog polumjera. Više kutova zaobljenih zajedno dijeli jedan polumjer.", + "help.sketch.finish": "Napušta skicu i vraća se na model. Njezini zatvoreni profili tada su spremni za Ekstrudiraj, Rotiraj i druge značajke.", + "help.sketch.finish_auto_constrain": "Pokreće Automatska ograničenja na skici, a zatim je dovršava. Upotrijebite ga kako biste skicu ostavili potpuno ograničenom u jednom koraku.", + "help.sketch.fit_curves_to_section": "Presijeca mrežno ili puno tijelo ravninom skice i uklapa linije i lukove u presjek. Upotrijebite ga za ponovnu izradu skeniranog ili uvezenog dijela kao uredive skice.", + "help.sketch.include_3d": "Unosi bridove modela, vrhove i krivulje drugih skica u ovu skicu kao povezane reference, spljoštavajući one izvan njezine ravnine na nju. Upotrijebite ga za gradnju na geometriji koja ne leži u ravnini skice.", + "help.sketch.infinite": "Prebacuje linije između običnih linija i beskonačnih pomoćnih linija koje prolaze cijelim prikazom. Upotrijebite ih kao reference rasporeda koje nikad nisu prekratke.", + "help.sketch.insert_dxf": "Čita krivulje DXF crteža u skicu, skalirane, zakrenute i postavljene kako zadate. Upotrijebite ga za gradnju na 2D crtežu iz drugog programa, primjerice na obrisu za lasersko rezanje.", + "help.sketch.insert_svg": "Čita putanje SVG crteža u skicu, skalirane, zakrenute i postavljene kako zadate. Upotrijebite ga za pretvaranje logotipa ili vektorskog obrisa u krivulje koje možete ekstrudirati.", + "help.sketch.inspect": "Otvara izvješće o otvorenoj skici: koliko je stupnjeva slobode preostalo i je li potpuno ograničena. Upotrijebite ga kako biste saznali što se još pomiče prije dovršetka skice.", + "help.sketch.intersect": "Dodaje krivulje ili točke u kojima tijela, lica, bridovi ili druge skice presijecaju ravninu skice. Ostaju povezane i prate model kad se promijeni.", + "help.sketch.intersection_curve": "Izrađuje 3D krivulje na mjestu gdje se dva tijela ili lica susreću, povezane s njima. Upotrijebite ih kao putanje ili vodilice koje prate model.", + "help.sketch.isoparametric_curve": "Izrađuje 3D krivulju u smjeru U ili V lica kroz točku koju odaberete, povezanu s licem. Upotrijebite je kao putanju ili liniju razdvajanja koja prati plohu.", + "help.sketch.line": "Crta povezane linije točku po točku, kao otvoreni lanac ili zatvoreni obris. To je osnovni alat za većinu profila.", + "help.sketch.line.midpoint": "Crta liniju od njezine središnje točke do jednog kraja, a drugi kraj zrcali. Upotrijebite ga za linije centrirane na točku, primjerice simetričan brid.", + "help.sketch.line3d": "Crta povezane ravne linije između točaka u prostoru, uz uključenu 3D skicu. Upotrijebite ga za putanje i okvire koji izlaze iz ravnine skice.", + "help.sketch.mirror": "Zrcali krivulje i točke skice preko linije ili osi i dodaje ograničenja simetrije. Upotrijebite ga za crtanje polovice simetričnog profila i njegovo dovršavanje.", + "help.sketch.move": "Pomiče ili zakreće krivulje i točke skice, ili njihovu kopiju. Upotrijebite ga za premještanje geometrije uz zadržavanje njezina oblika i ograničenja.", + "help.sketch.offset": "Izrađuje kopiju lanca krivulja na zadanoj udaljenosti, s jedne ili obje strane. Upotrijebite ga za stijenke, obrise i zazore; udaljenost ostaje uređiva kota.", + "help.sketch.paste": "Lijepi geometriju skice koju ste kopirali ili izrezali u aktivnu skicu. Postavite je u točku ili je pomaknite za odmak.", + "help.sketch.pattern.circular": "Kopira geometriju skice oko središnje točke, po punom krugu ili zadanom kutu. Upotrijebite ga za kružne rasporede vijaka, žbice i zube.", + "help.sketch.pattern.rectangular": "Kopira geometriju skice u retke i stupce na zadanim razmacima. Upotrijebite ga za mreže provrta, utora ili otvora za ventilaciju.", + "help.sketch.point": "Postavlja točku skice. Upotrijebite je kao referencu za kote, ograničenja, središta provrta ili kasnije značajke.", + "help.sketch.point3d": "Postavlja točku u prostoru, uz uključenu 3D skicu. Upotrijebite je kao referencu za 3D krivulje i putanje.", + "help.sketch.polygon.circumscribed": "Crta pravilni mnogokut oko kružnice, veličine određene od središta do sredine stranice. Upotrijebite ga kad je poznata širina ključa, kao kod šesterokutne matice.", + "help.sketch.polygon.edge": "Crta pravilni mnogokut iz dvaju krajeva jedne stranice. Upotrijebite ga kad su poznate duljina i položaj stranice.", + "help.sketch.polygon.inscribed": "Crta pravilni mnogokut unutar kružnice, veličine određene od središta do vrha. Upotrijebite ga kad je poznata mjera preko vrhova.", + "help.sketch.project": "Unosi bridove modela, lica, vrhove i krivulje drugih skica u ovu skicu, projicirane na njezinu ravninu. Ostaju povezani i prate model kad se promijeni.", + "help.sketch.project_to_surface": "Projicira krivulje drugih skica duž normale ove skice na lice, kao povezane 3D krivulje. Upotrijebite ga za nanošenje logotipa, linije razdvajanja ili putanje na zakrivljenu plohu.", + "help.sketch.rectangle.center": "Crta pravokutnik iz njegova središta i jednog kuta. Upotrijebite ga za obrise centrirane na točku, primjerice ishodište.", + "help.sketch.rectangle.rounded": "Crta pravokutnik sa sva četiri kuta zaobljena istim polumjerom. Upotrijebite ga za ploče, poklopce i otvore sa zaobljenim kutovima.", + "help.sketch.rectangle.three_point": "Crta pravokutnik iz jednog brida i točke na suprotnoj strani. Upotrijebite ga za pravokutnike pod kutom u odnosu na osi skice.", + "help.sketch.rectangle.two_point": "Crta pravokutnik iz dvaju nasuprotnih kutova. Upotrijebite ga za obrise ploča, blokova i džepova.", + "help.sketch.scale": "Skalira krivulje i točke skice faktorom oko osnovne točke. Upotrijebite ga za promjenu veličine dijela skice bez ponovnog crtanja.", + "help.sketch.slot.arc_center": "Crta zakrivljeni utor zadane širine duž luka određenog njegovim središtem, početkom i krajem. Upotrijebite ga za utore za podešavanje oko okretišta.", + "help.sketch.slot.arc_three_point": "Crta zakrivljeni utor zadane širine duž luka kroz tri točke. Upotrijebite ga kad putanja utora mora prolaziti kroz zadane točke.", + "help.sketch.slot.center_point": "Crta ravni utor zadane širine od njegova središta do središta jednog završnog luka. Upotrijebite ga za utore centrirane na točku.", + "help.sketch.slot.center_to_center": "Crta ravni utor zadane širine između središta njegovih dvaju završnih lukova. Upotrijebite ga za utore kotirane od središta do središta, primjerice za utore za podešavanje vijaka.", + "help.sketch.slot.overall": "Crta ravni utor zadane širine od jednog vanjskog kraja do drugog. Upotrijebite ga kad je važna ukupna duljina utora.", + "help.sketch.spline.control_point": "Crta kubični spline oblikovan kontrolnim točkama kroz koje ne prolazi. Upotrijebite ga za glatke, tekuće krivulje koje oblikujete pomicanjem točaka.", + "help.sketch.spline.control_point_5": "Crta spline stupnja 5 oblikovan kontrolnim točkama. Upotrijebite ga tamo gdje se krivulje moraju spajati s glađom zakrivljenošću, primjerice na vidljivim oblikovanim plohama.", + "help.sketch.spline.fit_point": "Crta glatki spline koji prolazi kroz svaku točku koju postavite, otvoren ili zatvoren. Upotrijebite ga za ocrtavanje oblika kroz poznate točke.", + "help.sketch.spline3d": "Crta glatku krivulju u prostoru kroz točke, uz uključenu 3D skicu. Upotrijebite ga za putanje povlačenja i trase kabela koje izlaze iz ravnine skice.", + "help.sketch.spun_profile": "Izrađuje u ravnini skice obris koji tijelo opiše okretanjem oko osi. Upotrijebite ga za dobivanje siluete tokarenog dijela za Rotiraj ili za crtež.", + "help.sketch.text": "Piše tekst u skici odabranim fontom, visinom i kutom; njegove riječi mogu pratiti parametre. Ekstrudirajte ga ili primijenite Reljef za oznake i natpise.", + "help.sketch.transform": "Skalira, zakreće i pomiče geometriju skice oko središnje točke u jednom koraku. Upotrijebite ga za istodobno premještanje i promjenu veličine odabira.", + "help.sketch.trim": "Uklanja dio krivulje između najbližih sjecišta oko mjesta na koje kliknete. Upotrijebite ga za čišćenje linija koje se preklapaju u zatvoreni profil.", "help.solid.align": "Pomiče odabrana tijela tako da se točka, lice ili ravnina na njima poklopi s točkom, licem ili ravninom negdje drugdje. Upotrijebite ga kako biste postavili dio uz drugi bez mjerenja odmaka.", + "help.solid.boundary_fill": "Izrađuje puna tijela iz područja zatvorenih preklapajućim alatnim tijelima, ispunjavajući samo područja koja odaberete. Upotrijebite ga za izradu oblika iz prostora koji zajedno omeđuje više tijela.", + "help.solid.bounding_solid": "Izrađuje kutiju koja obuhvaća odabrana tijela, s neobaveznom marginom. Upotrijebite ga za uvid u ukupnu veličinu dijela ili kao sirovac iz kojeg se obrađuje.", + "help.solid.box": "Izrađuje kutiju iz duljine, širine i visine, iz kutne točke ili centriranu na točku. Upotrijebite ga za brzi blok, privremeni oblik ili tijelo u koje urezujete značajke.", "help.solid.chamfer": "Odsijeca odabrane bridove ravnim skošenjem zadane udaljenosti. Koristite ga kako biste ublažili oštre bridove ili olakšali uvođenje zatika ili vijka.", + "help.solid.coil": "Izrađuje zavojito tijelo, primjerice oprugu, iz promjera, broja zavoja, visine ili koraka te okruglog ili kvadratnog presjeka. Upotrijebite ga za opruge, zavojnice i zavojne grebene.", "help.solid.combine": "Spaja tijela, oduzima ih od ciljnog tijela ili zadržava samo zajednički volumen, a može zadržati i alatna tijela. Koristite ga kako biste spojili dijelove, jednim oblikom odrezali drugi ili pronašli gdje se dva tijela preklapaju.", + "help.solid.cone": "Izrađuje stožac iz osnovne kružnice i visine, ili krnji stožac kad i vrh ima polumjer. Upotrijebite ga za suženja, lijevke, upuštenja i šiljke.", + "help.solid.cylinder": "Izrađuje valjak iz polumjera ili promjera i visine, koji stoji na točki duž osi. Upotrijebite ga za osovine, zatike, ispuste i okrugle pripremke.", "help.solid.draft": "Naginje odabrana lica za kut koji zadate, mjereno od neutralne ravnine. Upotrijebite ga na lijevanim ili brizganim dijelovima kako bi izašli iz kalupa.", + "help.solid.emboss": "Izdiže profile skice, primjerice tekst ili logotip, iz lica ili ih utiskuje u njega. Upotrijebite ga za natpise, oznake i markiranje na ravnim ili okruglim licima.", "help.solid.extrude": "Izvlači profil skice u 3D duž zadane udaljenosti, dodajući ili uklanjajući materijal. Koristite ga kako biste ravni obris pretvorili u blok, ispust ili džep.", "help.solid.fillet": "Zaobljuje odabrane bridove glatkim kružnim prijelazom zadanog polumjera. Koristite ga kako biste omekšali oštre bridove radi čvrstoće, udobnosti ili izgleda.", "help.solid.hole": "Buši okrugli provrt zadanog promjera na odabranoj točki lica. Koristite ga za prolaze vijaka, zatike i druge jednostavne okrugle otvore.", @@ -1412,20 +1678,60 @@ "help.solid.move": "Pomiče ili rotira odabrana tijela, ili njihovu kopiju, za udaljenost i kut koje zadate. Upotrijebite ga kako biste premjestili tijelo ili izradili drugo na drugom mjestu.", "help.solid.offset_face": "Gura odabrana lica unutra ili van za udaljenost koju zadate, a okolna lica ih prate. Upotrijebite ga kako biste podebljali stijenku, produbili džep ili povisili ispupčenje bez uređivanja skice.", "help.solid.pattern.circular": "Ponavlja odabrane objekte oko osi, za zadani broj i ukupni kut. Koristite ga za kružne rasporede vijaka, žbice, rebra hladnjaka i zupce.", + "help.solid.pattern.path": "Kopira značajke ili tijela duž putanje skice, prema broju i razmaku. Upotrijebite ga za provrte duž zakrivljenog brida ili dijelove duž vodilice.", "help.solid.pattern.rectangular": "Ponavlja odabrane objekte u jednom ili dva smjera sa zadanim brojem i razmakom. Koristite ga za redove i mreže provrta, rebara, zatika ili nožica.", + "help.solid.pipe": "Izrađuje okruglu cijev duž putanje krivulja skice, punu ili šuplju s debljinom stijenke. Upotrijebite ga za cijevi, žice, kabele i vodilice.", "help.solid.press_pull": "Dodaje ili uklanja materijal dok povlačite lice, ili zaobljuje bridove dok ih povlačite. Upotrijebite ga za brze izmjene izravno na modelu.", "help.solid.remove": "Uklanja odabrana tijela iz dizajna od ove točke vremenske trake nadalje; raniji koraci ih zadržavaju. Upotrijebite ga kako biste odbacili pomoćno tijelo, npr. alat za rezanje koji vam više ne treba.", "help.solid.replace_face": "Premješta odabrana ravna lica na ravninu ili na paralelno lice, a tijelo raste ili se smanjuje da ga dosegne. Upotrijebite ga kako biste poravnali lice s drugim dijelom ili pomoćnom ravninom.", "help.solid.revolve": "Okreće profil skice oko osi i izrađuje okruglo tijelo. Koristite ga za vratila, gumbe, posude i svaki dio koji je okrugao oko središnje linije.", + "help.solid.rib": "Dodaje tanku stijenku duž otvorene krivulje skice, produljenu do sljedećih lica tijela. Upotrijebite ga za ukrućivanje stijenki i kutova, primjerice u kalupljenim ili ispisanim dijelovima.", "help.solid.scale": "Povećava ili smanjuje odabrana tijela za faktor, jednako u svim smjerovima ili posebno po osi. Upotrijebite ga kako biste promijenili veličinu uvezenog oblika ili uračunali skupljanje.", "help.solid.shell": "Izdubljuje tijelo i ostavlja stijenke zadane debljine, a može otvoriti lica koja odaberete. Koristite ga za kutije, poklopce i druge tankostijene dijelove.", + "help.solid.sphere": "Izrađuje kuglu iz polumjera ili promjera oko središnje točke. Upotrijebite ga za kugle, gumbe i zaobljene krajeve.", "help.solid.split_body": "Reže tijelo na zasebna tijela ravninom, licem drugog tijela ili linijom skice. Upotrijebite ga za dijelove koji se zasebno ispisuju, obrađuju ili boje.", "help.solid.split_face": "Dijeli odabrana lica po ravnini, licu drugog tijela ili krivuljama skice, bez rezanja tijela. Upotrijebite ga kako biste dijelu lica dali vlastiti nagib, boju ili odmak.", "help.solid.sweep": "Povlači profil skice duž putanje i izrađuje tijelo. Koristite ga za cijevi, tračnice, ručke i svaki dio konstantnog presjeka koji prati krivulju.", + "help.solid.thread": "Dodaje ISO metrički navoj na cilindrično lice, kao kozmetički navoj ili urezan u tijelo. Upotrijebite ga za vijke, navojne provrte i ispisane dijelove s vijkom.", + "help.solid.torus": "Izrađuje prsten iz velikog polumjera oko njegove osi i malog polumjera za njegov okrugli presjek. Upotrijebite ga za O-prstenove, ručke i okrugle perle.", + "help.solid.web": "Dodaje tanku stijenku duž svake otvorene krivulje skice, svaku produljenu do sljedećih lica tijela. Upotrijebite ga za mrežu potpornih stijenki unutar kućišta i posuda.", + "help.surface.blend": "Izrađuje plohu koja premošćuje bridove dvaju tijela, tangentnu ili kontinuiranu po zakrivljenosti s oba. Upotrijebite ga za glatko spajanje dviju ploha preko razmaka.", + "help.surface.boundary": "Izrađuje plohu koja ispunjava petlju od dvije do četiri krivulje skice ili mrežu krivulja. Upotrijebite ga za ploče slobodnog oblika određene svojim bridovima.", + "help.surface.extend": "Produljuje plohu preko njezinih bridova, za zadanu udaljenost ili do ravnine ili lica. Upotrijebite ga kako bi se plohe preklapale prije odsijecanja ili sašivanja.", + "help.surface.extrude": "Potiskuje krivulje ili profile skice na zadanu udaljenost u plohu, samo stijenke, bez zatvaranja krajeva. Upotrijebite ga za tanke stijenke te alate za rezanje ili razdvajanje.", + "help.surface.fair": "Zaglađuje unutrašnjost ploha slobodnog oblika dok njihovi bridovi ostaju na mjestu. Upotrijebite ga za izravnavanje izbočina i valovitih odraza na plohi.", + "help.surface.loft": "Izrađuje plohu koja redom prolazi kroz dva ili više presjeka, bez zatvaranja krajeva. Upotrijebite ga za ljuske i prijelaze između različitih oblika.", + "help.surface.match": "Ponovno izrađuje brid plohe tako da se susreće s bridom drugog tijela, uz usklađenu tangentnost ili zakrivljenost. Upotrijebite ga za glatko zatvaranje šava između dviju ploha.", + "help.surface.offset": "Izrađuje kopiju lica na udaljenosti duž njihovih normala, kao novo plošno tijelo. Upotrijebite ga za oplate, zazore ili drugu stranu stijenke.", + "help.surface.patch": "Ispunjava područje skice ili zatvorenu petlju bridova licem, ravnim ili glatko zakrivljenim. Upotrijebite ga za zatvaranje otvora u plošnom tijelu.", + "help.surface.reverse_normal": "Okreće lica plošnog tijela, pa im se vanjska strana okrene na drugu stranu. Upotrijebite ga prije podebljavanja ili sašivanja kad lica gledaju prema unutra.", + "help.surface.revolve": "Okreće krivulje ili profile skice oko osi u plohu, bez zatvaranja krajeva. Upotrijebite ga za okrugle ljuske poput sjenila svjetiljki, zdjela i mlaznica.", + "help.surface.ruled": "Izrađuje traku ravnih linija koje izlaze iz lanca bridova, duž normale lica, tangente ili pod kutom. Upotrijebite ga za stijenke s nagibom, izlazne plohe i plohe razdvajanja.", + "help.surface.stitch": "Sašiva plošna tijela duž njihovih zajedničkih bridova, u puno tijelo kad se zatvore. Upotrijebite ga za pretvaranje skupa ploha u jedno tijelo.", + "help.surface.sweep": "Pomiče krivulje ili profile skice duž putanje u plohu, bez zatvaranja krajeva. Upotrijebite ga za oluke, obrube i druge tanke oblike koji prate putanju.", + "help.surface.thicken": "Daje plošnom tijelu debljinu i pretvara ga u puno tijelo. Upotrijebite ga za izradu dijelova za ispis ili obradu iz ploha.", + "help.surface.trim": "Odsijeca plohu ravninom, drugom plohom ili krivuljama skice i zadržava stranu koju odaberete. Upotrijebite ga za rezanje ploha na oblik prije sašivanja.", + "help.surface.unstitch": "Odvaja lica tijela u zasebna plošna tijela; puno tijelo se raspada na plohe. Upotrijebite ga za preradu pojedinačnih lica tijela.", + "help.surface.untrim": "Uklanja otvore iz lica ili vraća njegovu vanjsku granicu na prirodne granice plohe. Upotrijebite ga za povrat cijele plohe nakon odsijecanja.", "help.third_party": "Licence trećih strana", "help.timeline.compute_all": "Ponovno gradi svaku značajku na vremenskoj traci od početka. Upotrijebite ga kako biste osvježili model i vidjeli koje značajke ne uspijevaju.", "help.timeline.delete": "Briše odabrane značajke s vremenske trake; brisanje skice briše i značajke izrađene iz nje. Upotrijebite ga kako biste uklonili korak koji više ne želite.", + "help.timeline.dependents": "Navodi značajke koje bi se izbrisale zajedno s nekom značajkom i one koje bi bez nje zakazale. Upotrijebite ga prije brisanja ili promjene značajke.", "help.timeline.play": "Ponavlja preostale značajke jednu po jednu, s pauzom od pola sekunde nakon svake ponovne izgradnje. Ponovno pokrenite ovu naredbu ili pritisnite Escape za zaustavljanje; Idi na kraj skače odmah.", + "help.view.apply": "Okreće prikaz u standardni smjer, primjerice pogled sprijeda, odozgo ili izometrijski, ili u spremljeni imenovani prikaz. Upotrijebite ga za gledanje modela iz stalnog kuta.", + "help.view.delete": "Briše spremljeni imenovani prikaz. Model se ne mijenja.", + "help.view.fit": "Zumira i pomiče prikaz tako da cijeli model, ili odabir, ispuni prikaz. Upotrijebite ga kad je model izašao iz vidnog polja.", + "help.view.grid": "Prikazuje ili skriva mrežu u prozoru prikaza. Upotrijebite je kao vodič za veličinu i orijentaciju pri modeliranju.", + "help.view.ground_shadow": "Prikazuje ili skriva sjenu modela na podlozi. Upotrijebite je kako biste lakše procijenili visinu i položaj.", + "help.view.home": "Vraća prikaz u početni smjer i uklapa model. Upotrijebite ga za brz povratak na poznat prikaz.", + "help.view.list": "Navodi imenovane prikaze spremljene u dizajnu. Upotrijebite ga za pronalaženje prikaza koji ste ranije spremili.", + "help.view.navigate": "Okreće, pomiče ili zumira prikaz u koracima, primjerice za četvrtinu okreta ulijevo. Upotrijebite ga za precizno pomicanje kamere umjesto povlačenja.", + "help.view.navigation_bar": "Prikazuje ili skriva navigacijsku traku na dnu prozora prikaza. Sakrijte je za više prostora, prikažite je za pristup alatima prikaza mišem.", + "help.view.rename": "Daje spremljenom imenovanom prikazu novi naziv. Sam se prikaz ne mijenja.", + "help.view.save": "Sprema trenutni položaj kamere kao imenovani prikaz u dizajnu. Upotrijebite ga za kasniji povratak na isti kut, primjerice za snimke zaslona.", + "help.view.spin": "Neprekidno orbitira prikaz oko modela do sljedećeg klika ili tipke. Upotrijebite ga za predstavljanje modela sa svih strana.", + "help.view.tool": "Uključuje alat kamere, orbitiranje, pomicanje ili zumiranje, pa povlačenje lijevom tipkom miša pomiče prikaz dok ga ne isključite. Upotrijebite ga na dodirnoj pločici ili bez srednje tipke miša.", + "help.view.visual_style": "Mijenja način crtanja modela: osjenčano sa ili bez bridova, žičani model ili sa skrivenim bridovima. Žičani model upotrijebite za pogled unutra, osjenčano za čist izgled.", "history.sketch_under_constrained": "Nedovoljno ograničeno (stupnjevi slobode: {count})", "history.sketch_under_constrained_one": "Nedovoljno ograničeno (stupanj slobode: {count})", "hole_presets.confirm_delete": "Potvrdi brisanje", @@ -1531,6 +1837,8 @@ "joint_move.blocked_hint": "Provjerite vrstu spoja (npr. Kruti), učvršćenje, granice spoja i vrijednosti kojima upravljaju parametri.", "joint_move.blocked_title": "Ovaj dio nije moguće pomaknuti", "joint_move.coarse": "Korak rotacije blizu osi (°)", + "joint_move.conflict": "Jedan spoj ovog dijela u sukobu je s ostalima: {joint}.", + "joint_move.conflict_hint": "Uredite, potisnite ili izbrišite spoj koji je u sukobu kako bi ostali spojevi mogli postaviti dio.", "joint_move.distance": "Udaljenost od početka", "joint_move.done": "Gotovo", "joint_move.fine": "Korak rotacije daleko od osi (°)", @@ -1602,6 +1910,10 @@ "material.selection.mixed": "Različiti materijali", "measure.at": "Na", "measure.item": "Stavka {number}", + "measure.quick_copied": "Mjerenje kopirano", + "measure.quick_copy": "Kliknite za kopiranje mjerenja", + "measure.quick_edges": "Bridovi: {count}", + "measure.quick_faces": "Lica: {count}", "messages.ago_h": "prije {n} h", "messages.ago_min": "prije {n} min", "messages.ago_s": "prije {n} s", @@ -1626,6 +1938,8 @@ "motion.track_name": "Staza {number}", "nav.alias.help": "Shift+Alt+povlačenje lijevom tipkom orbitira, Shift+Alt+srednjom pomiče, Shift+Alt+desnom zumira; povlačenje srednjom tipkom također pomiče, a desnom orbitira", "nav.blender.help": "Povlačenje srednjom tipkom orbitira, Shift+srednja pomiče, Ctrl+srednja zumira; povlačenje desnom tipkom ne dira kameru", + "nav.creo.help": "Povlačenje srednjom tipkom orbitira, Shift+srednja pomiče, Ctrl+srednja uz okomito povlačenje zumira (prema dolje za približavanje); kotačić također zumira", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Miš i 3D miš rotiraju kroz oba pola i čuvaju nagib. Privlačenje osi tipkom Shift isključeno je.", "nav.free_orbit.label": "Slobodno orbitiranje", "nav.free_orbit.snap_help": "Miš i 3D miš rotiraju kroz oba pola i čuvaju nagib. Držite Shift tijekom povlačenja za orbitiranje kako biste privukli smjer pogleda i nagib.", @@ -1635,6 +1949,7 @@ "nav.hfss.help": "Alt+povlačenje lijevom tipkom pomiče, Shift+Alt+lijeva tipka zumira, Ctrl+povlačenje lijevom tipkom na praznom prostoru orbitira", "nav.inventor.help": "Povlačenje srednjom tipkom pomiče, Shift+srednja orbitira, Ctrl+srednja zumira, povlačenje desnom orbitira", "nav.maya.help": "Alt+povlačenje lijevom tipkom orbitira, Alt+srednja tipka pomiče, Alt+desna tipka zumira; povlačenje srednjom tipkom također pomiče", + "nav.nx.help": "Povlačenje srednjom tipkom orbitira, Shift+srednja pomiče (u NX-u srednja + desna), Ctrl+srednja zumira (u NX-u srednja + lijeva); povlačenje desnom tipkom ne dira kameru", "nav.openscad.help": "Povlačenje lijevom tipkom po praznom prostoru orbitira, Shift+povlačenje lijevom odabire okvirom, povlačenje geometrije skice uređuje je; povlačenje desnom ili srednjom tipkom pomiče, Shift+desna ili Shift+srednja zumira", "nav.perspective.sketch": "Uređivanje skice koristi ortografski prikaz. Završite skicu kako biste prešli na perspektivu.", "nav.right_drag_orbits.help": "Isključeno: povlačenje desnom tipkom ne dira kameru, a desna tipka samo otvara kontekstni izbornik. Odabir mapiranja miša SolidWorks isključuje ovu opciju.", @@ -1754,6 +2069,11 @@ "not a move": "nije pomak", "not a number": "nije broj", "open a sketch first": "najprije otvorite skicu", + "parameters.apply_live": "Primijeni svaku promjenu čim napustite njezino polje", + "parameters.apply_live_tip": "Isključeno: promjene čekaju Primijeni ili U redu, a zatim se dizajn jednom ponovno izgradi za sve njih. Odustani ili Escape ih odbacuje.", + "parameters.held": "Promjene koje čekaju Primijeni: {count}", + "parameters.held_hint": "Uređujte izraze i jedinice. Promjene čekaju Primijeni ili U redu.", + "parameters.held_one": "1 promjena čeka Primijeni", "parts.automatic_name": "automatski", "parts.dimension.across_flats": "Mjera ključa", "parts.dimension.bore": "Provrt", @@ -1772,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Vijak s poluokruglom glavom i unutarnjim šesterokutom", "parts.family.dowel_pin": "Cilindrični zatik", "parts.family.hex_bolt": "Vijak sa šesterokutnom glavom", + "parts.family.hex_cap_screw_inch": "Vijak sa šesterokutnom glavom (inč)", "parts.family.hex_nut": "Šesterokutna matica", + "parts.family.hex_nut_inch": "Šesterokutna matica (inč)", "parts.family.set_screw": "Bezglavi vijak s unutarnjim šesterokutom, ravni vrh", "parts.family.socket_head_cap_screw": "Vijak s cilindričnom glavom i unutarnjim šesterokutom", "parts.family.washer": "Obična podloška", + "parts.family.washer_sae": "Obična podloška, SAE (uska)", + "parts.family.washer_uss": "Obična podloška, USS (široka)", + "parts.holes": "Provrti (neobavezno)", + "parts.placement_hint": "odaberite jedan ili više provrta kako biste u svaki smjestili dio, ili U redu postavlja dio u ishodište", + "parts.system": "Sustav jedinica", + "parts.system.inch": "Inčni", + "parts.system.metric": "Metrički", "pattern.alignment_2": "Poravnanje 2", "pattern.alignment_hint": "Broj uključuje izvornik. Središte ravnomjerno raspoređuje kopije; Obrni bira dodatnu stranu za parne ukupne brojeve.", "pattern.direction_1": "Smjer 1", @@ -1828,6 +2157,8 @@ "prefs.bottom_centre": "Dolje u sredini", "prefs.bottom_right": "Dolje desno", "prefs.browser": "Stablo modela", + "prefs.browser_eye_left": "Oko pored strelice za sažimanje", + "prefs.browser_eye_left_note": "Redci stabla modela prikazuju oko za prikazivanje/skrivanje pored strelice za sažimanje, kao prije, umjesto u stupcu na desnom kraju redaka.", "prefs.browser_reveal_on_hover": "Prikaži pri prelasku mišem", "prefs.browser_show_note": "Prikazano drži stablo modela na zaslonu. Prikaži pri prelasku mišem skriva ga dok pokazivač ne dođe na njegovo mjesto ili na tanku karticu uz njegov lijevi rub, a ostaje otvoreno dok je pokazivač unutar njega ili dok je otvoren izbornik iz njega.", "prefs.browser_shown": "Prikazano", @@ -1835,6 +2166,8 @@ "prefs.button_left": "Povlačenje lijevom tipkom", "prefs.button_middle": "Povlačenje srednjom tipkom", "prefs.button_right": "Povlačenje desnom tipkom", + "prefs.carousel_next": "Sljedeće", + "prefs.carousel_previous": "Prethodno", "prefs.choose_font": "Odaberi datoteku fonta…", "prefs.click": "Klik", "prefs.contact_shading": "Meko sjenčanje dodira", @@ -1847,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Zakrivljene plohe", "prefs.curves": "Zakrivljene plohe", + "prefs.cut_preview_tint": "Prikaži uklonjeni materijal u crvenoj boji", + "prefs.cut_preview_tint_help": "Pregled ispunjava materijal koji značajka uklanja i oblik koji zamjenjuje crvenom prozirnom sjenom. Kada je isključeno, te su ispune potpuno prozirne i crtaju se samo njihovi obrisi.", + "prefs.dark_parts_shading": "Zadrži oblik tamnih dijelova", + "prefs.dark_parts_shading_help": "Sjenča prikaz u linearnom svjetlu uz meko dopunsko svjetlo neba, tako da tamna lica zadrže gradijent umjesto da pocrne", "prefs.dead_zone_note": "Šrafirana traka je mrtva zona: kretanje unutar nje se zanemaruje.", "prefs.default": "zadano", "prefs.design": "Zadane postavke dizajna", @@ -1861,6 +2198,8 @@ "prefs.edges": "Bridovi i sjenčanje", "prefs.extend": "Produži", "prefs.extra_navigation": "Ctrl + povlačenje lijevom tipkom po praznom prostoru orbitira; držite razmaknicu za pomicanje.", + "prefs.extrude_view_isometric": "Okreni prikaz u izometrijski kad se otvori Ekstrudiraj", + "prefs.extrude_view_return": "Vrati se na prethodni prikaz kad se Ekstrudiraj zatvori", "prefs.follows_os": "Prati operacijski sustav", "prefs.font": "Font", "prefs.font_fallback": "Znakovi koji nedostaju odabranom fontu prikazuju se ugrađenim fontom, tako da nijedna oznaka ne prikazuje prazan kvadrat.", @@ -1876,8 +2215,11 @@ "prefs.graphics_card_auto": "Automatski", "prefs.graphics_card_missing": "Spremljena grafička kartica nije dostupna; koristi se Automatski.", "prefs.graphics_card_restart": "Stupa na snagu nakon ponovnog pokretanja SolidCrafta. WGPU_ADAPTER_NAME ima prednost nad ovim odabirom.", + "prefs.graphics_card_unused": "Spremljena grafička kartica nije korištena za ovaj prozor; kartica koja se koristi prikazana je u Pomoć › O programu i u statusnoj traci. Pokušajte s opcijom Automatski ili postavite WGPU_ADAPTER_NAME na jedinstveni dio naziva kartice.", "prefs.graphics_note": "Žrtvujte brzinu za glatkoću. Svaki odabir pokazuje svoj učinak na primjeru.", "prefs.graphics_presets_note": "Unaprijed zadane vrijednosti postavljaju sve odabire ispod odjednom.", + "prefs.hide_constraint_glyphs_zoomed_out": "Sakrij simbole ograničenja kada je prikaz umanjen", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Simboli ograničenja nestaju iz prikaza kada je skica toliko umanjena da bi je zatrpali. Isključeno: ostaju fiksne veličine na zaslonu pri svakom zumiranju.", "prefs.history": "Vremenska traka", "prefs.history_origin_bodies": "Prikaži ishodište i tijela na vrhu", "prefs.history_origin_bodies_note": "Vremenska traka lijevo ili ispod stabla modela počinje mapom Tijela aktivne komponente i Ishodištem, s njihovim okom i izbornicima kao u stablu modela. Vremenska traka na dnu ostaje nepromijenjena.", @@ -1888,6 +2230,8 @@ "prefs.history_sketches_note": "Kad je Skice postavljeno na Ispod svoje značajke, vremenska traka lijevo prikazuje svaku skicu jednu razinu uvučeno, ispod prve značajke izrađene iz nje, kad god je dovoljno široka za nazive. Vremenska traka na dnu uvijek zadržava redoslijed nastanka.", "prefs.history_sketches_under_feature": "Ispod svoje značajke", "prefs.hold_stop_snapping": "Držite kako biste isključili privlačenje", + "prefs.home_fit_size": "Veličina za Početni prikaz i Uklopi", + "prefs.home_fit_size_note": "Koliki dio prikaza model ispunjava kad ga uokviri Početni prikaz, Uklopi, otvaranje dizajna ili promjena prikaza u navigatoru, bez obzira na to je li postavka ispod uključena. 100 %: ispunjava prikaz između panela, kompasa i navigacijske trake.", "prefs.icons_only": "Samo ikone", "prefs.imported_file": "Uvezena datoteka", "prefs.in_browser": "U stablu modela", @@ -1896,13 +2240,22 @@ "prefs.interface_language": "Jezik sučelja", "prefs.interface_note": "Kako SolidCraft izgleda i gdje su njegovi dijelovi.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Obrni zakrivljene strelice za valjanje", + "prefs.invert_curved_roll_arrows_note": "Dvije zakrivljene strelice u kutu kocke valjaju prikaz unutar ravnine zaslona. Uključeno: strelica u smjeru kazaljke na satu valja prikaz suprotno od smjera kazaljke na satu, a strelica suprotno od smjera kazaljke na satu valja ga u smjeru kazaljke na satu. Isključeno: svaka strelica valja prikaz onako kako je zakrivljena.", + "prefs.invert_navigator_arrows": "Obrni strelice za rotaciju kocke prikaza", + "prefs.invert_navigator_arrows_note": "Strelice oko kocke orbitiraju kameru u smjeru u kojem pokazuju, kao u programima Fusion i Inventor: strelica s lijeve strane pokazuje udesno i zakreće kameru udesno. Isključeno: strelica okreće kocku prema strani na kojoj se nalazi, pa lijeva strelica zakreće kameru ulijevo. Postavka ne utječe na zakrivljene strelice za valjanje.", + "prefs.keep_work_on_tab_switch": "Zadrži dijaloge i alate otvorenima pri prebacivanju između dizajna", + "prefs.keep_work_on_tab_switch_note": "Svaka kartica dizajna zadržava svoj otvoreni dijalog ili alat, s onim što ste u njemu odabrali i upisali, te svoju karticu alatne trake. Kad se vratite na dizajn, ponovno su tu. Isključeno: prebacivanje između dizajna poništava ih i prikazuje karticu Model.", "prefs.labels": "Oznake", + "prefs.language_system": "Sustav", "prefs.layout": "Raspored", "prefs.layout_note": "Kompaktno pričvršćuje panele uz rubove prozora. Prozirnost stabla modela dostupna je u opciji Plutajuće. Stranu Asistenta promijenite na stranici Asistent.", "prefs.left": "Lijevo", "prefs.left_click": "Lijevi klik", "prefs.line_drag_draws_one": "Pritisak i povlačenje crta jednu liniju", "prefs.line_drag_draws_one_note": "U alatu Linija pritisak, povlačenje i otpuštanje crta jednu liniju od mjesta pritiska do mjesta otpuštanja i ondje završava. Klikovi i dalje crtaju lanac. Isključeno: povlačenje postavlja točku ondje gdje se otpusti, kao i klik.", + "prefs.line_hover_tangent_arc": "Zadržite pokazivač na posljednjoj točki linije kako biste prešli na tangentni luk", + "prefs.line_hover_tangent_arc_note": "U alatu Linija, nakon što je nacrtan segment, odmaknite pokazivač od posljednje točke lanca, vratite ga na nju i držite ga mirno: sljedeći klik završava tangentni luk, a isti pokret vraća na linije. Isključeno: zadržavanje na toj točki ne radi ništa.", "prefs.linked_designs": "Povezani dizajni", "prefs.live_input": "Ulaz uživo", "prefs.live_preview": "Pregled uživo", @@ -1916,6 +2269,9 @@ "prefs.max_file_size_step": "STEP i uvezene datoteke", "prefs.max_file_size_web": "Web aplikacija otvara STEP i uvezene datoteke do 512 MB te dizajne do 256 MB: kartica preglednika ne može primiti veće datoteke. Desktop aplikacija može podići ove granice.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Velike ikone", + "prefs.menu_list": "Popis", + "prefs.menus": "Izbornici", "prefs.minutes": "minuta", "prefs.minutes_suffix": " min", "prefs.mouse": "Miš i dodirna pločica", @@ -1923,6 +2279,8 @@ "prefs.mouse_mapping": "Mapiranje miša", "prefs.navigation": "Navigacija", "prefs.navigation_note": "Kako miš, dodirna pločica i 3D miš pomiču prikaz.", + "prefs.navigator_fit": "Uklopi model nakon promjene prikaza u navigatoru", + "prefs.navigator_fit_note": "Lice, kut ili strelica kocke prikaza, odnosno os orijentacijskog gizma, također usmjerava pogled na sredinu modela s jedne udaljenosti na kojoj se uklapa iz svakog smjera (njegova granična sfera). Početni prikaz koristi isti zum i središte dok je ova opcija uključena, pa se prikazi koje odaberete poslije njega samo okreću. Isključeno: prikaz se okreće na mjestu i zadržava svoj cilj i zum.", "prefs.network_host_remove": "Ukloni", "prefs.network_locations": "Dopusti mrežne lokacije u dizajnima", "prefs.network_locations_note": "Isključeno: povezane datoteke dizajna na drugom računalu (\\\\server\\share) otvaraju se samo s poslužitelja navedenih ovdje ili nakon što ga dopustite kad se to zatraži.", @@ -1935,10 +2293,18 @@ "prefs.origin_plane_names": "Nazivi ravnina ishodišta", "prefs.origin_plane_names_note": "Nazivi prikazani u stablu modela, dijalozima i popisima. {top} je XY, {front} je XZ, a {right} je YZ, sa Z prema gore. Naredbe, skripte i spremljeni dizajni zadržavaju XY, XZ i YZ.", "prefs.overall_speed": "Ukupna brzina", + "prefs.parameter_list_rows": "Retci popisa parametara", + "prefs.parameter_list_rows_tip": "Strelica prema dolje u praznom polju vrijednosti prikazuje popis parametara, prvo favorite, do ovoliko njih. Manje održava popis laganim u velikom dizajnu.", + "prefs.persistent_ribbon_pressed": "Istakni aktivne naredbe na vrpci", + "prefs.persistent_ribbon_pressed_help": "Ističe naredbe na vrpci dok su njihovi efekti uključeni. Isključite kako biste zadržali prethodni neutralni izgled i pomoć za naredbe.", "prefs.perspective_fov": "Vidno polje", "prefs.placement": "Postavljanje", "prefs.prefer_free_sketch_points": "Daj prednost pomičnim točkama skice kad se točke preklapaju", "prefs.preview_choices": "Pregled vaših odabira", + "prefs.preview_tint_new_faces": "Oboji novu plohu u pregledu", + "prefs.preview_tint_new_faces_help": "Pregled značajke koja mijenja tijelo može nacrtati plohu koju dodaje u boji pregleda. Kada je isključeno, tijelo se crta kakvo jest.", + "prefs.print_face_highlight": "Isticanje plohe ispisa", + "prefs.print_face_highlight_tip": "Koliko se jako ploha ispisa tijela boji i obrubljuje u prikazu. 0 % ne prikazuje isticanje.", "prefs.profile_active": "Aktivni profil", "prefs.profile_applied": "Profil je primijenjen.", "prefs.profile_changed": "Postavke su se promijenile otkako je profil spremljen. Spremi ih zadržava u njemu.", @@ -1960,9 +2326,13 @@ "prefs.quality_fastest": "najbrže", "prefs.quality_slowest": "najsporije", "prefs.quality_smoother": "glađe", + "prefs.quick_measure": "Brzo mjerenje u kutu prikaza", + "prefs.quick_measure_note": "Veličina odabira u donjem desnom kutu prikaza: duljina brida, ili Ø i R za okrugli, površina lica, položaj točke, udaljenost i kut dviju stavki, zbroj više bridova ili lica. Klik ga kopira.", "prefs.render_previous_geometry_budget": "Koristi prethodni proračun geometrije za pregled renderiranja", "prefs.render_previous_geometry_budget_help": "Vrati prethodnu fiksnu granicu geometrije (512 MiB na 64-bitnom desktopu, 128 MiB drugdje) umjesto proračuna prema uređaju.", "prefs.reports_saved": "Spremljeno: {n}", + "prefs.ribbon_click_ends_tool": "Klik na gumb aktivnog alata završava ga", + "prefs.ribbon_click_ends_tool_note": "Klik na istaknuti gumb na vrpci alata za skiciranje koji je u uporabi završava taj alat, pa klikovi u prikazu ponovno služe za odabir. Isključeno: klik ponovno pokreće alat.", "prefs.ribbon_reveal": "Prikaži rezultate pretraživanja na vrpci", "prefs.ribbon_reveal_note": "Zadržavanje pokazivača iznad rezultata u Pretraži naredbe pokazuje gdje se naredba nalazi na vrpci: njezinu karticu, gumb ili redak u padajućem izborniku panela. Naredba pokrenuta iz pretraživanja ondje zatreperi, a pokrenuta naredba iz padajućeg izbornika označava svoj panel.", "prefs.right_click": "Desni klik", @@ -1973,6 +2343,8 @@ "prefs.search_empty": "Nema odgovarajućih postavki", "prefs.select": "Odabir", "prefs.select_one_item": "Odaberi jednu stavku", + "prefs.select_other_hidden": "Odaberi skrivenu geometriju pomoću Odaberi drugo", + "prefs.select_other_hidden_help": "Uključeno: obuhvaća skrivena tijela, skice i zaklonjene bridove u blizini pokazivača. Isključeno: koristi se izvorni popis vidljive geometrije ispod pokazivača.", "prefs.selecting": "Odabiranje", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift samo dodaje; Ctrl / Cmd uključuje i isključuje", @@ -1984,11 +2356,16 @@ "prefs.sketch_align_points_note": "Tijekom crtanja točka se istodobno poravnava vodoravno s jednom točkom skice i okomito s drugom, uz točkastu vodilicu, a klik zadržava oba poravnanja. Isključeno: samo s prethodnom točkom, po jedna os.", "prefs.sketch_conflict_colour": "Geometrija u sukobu u boji sukoba", "prefs.sketch_conflict_colour_note": "Dok su ograničenja skice u sukobu, krivulje i točke koje drži neuspjelo ograničenje crtaju se i u boji sukoba, a ne samo njegov simbol ili kota. Isključeno: zadržavaju uobičajene boje.", + "prefs.sketch_construction_lines": "Prošireni alati za pomoćne pravce", "prefs.sketch_exit_view": "Kad se skica završi", "prefs.sketch_exit_view.keep": "Zadrži trenutni prikaz", "prefs.sketch_exit_view.previous": "Vrati se na prethodni prikaz", "prefs.sketch_exit_view.unless_rotated": "Vrati se osim ako je rotirano", "prefs.sketch_exit_view_note": "Kamo prikaz ide nakon Završi skicu, Odustani ili dvostrukog Esc.", + "prefs.sketch_face_activates_part": "Skiciranje na licu dijela čini taj dio aktivnim", + "prefs.sketch_face_activates_part_note": "Skica započeta na licu tijela druge komponente najprije aktivira tu komponentu, pa skica pripada njoj i u stablu modela ostaje uz taj dio. Taj dio nakon toga ostaje aktivan. Isključeno: skica pripada aktivnoj komponenti.", + "prefs.sketch_open_look_at": "Okreni kameru prema skici pri otvaranju", + "prefs.sketch_open_look_at_note": "Isključeno: kad izradite ili uredite skicu, prikaz ostaje onakav kakav jest. Pogledaj okreće prikaz prema skici kad to želite.", "prefs.sketch_recent_snap": "Automatski privlači na nedavna središta i središnje točke", "prefs.sketch_recent_snap_note": "Tijekom crtanja pokazivač se privlači ondje gdje se sijeku vodilice dvaju posljednjih središta kružnica ili središnjih točaka ravnih bridova. Isključeno: te vodilice služe samo za prikaz i pokazivač se ne pomiče.", "prefs.sketch_selection": "Skica i odabir", @@ -2000,6 +2377,8 @@ "prefs.sketch_tab_always_note": "Kartica Skica ostaje na vrpci, odmah iza kartice Model, dok nijedna skica nije otvorena. Njezini alati za crtanje tada pokreću skicu na odabranoj ravnini ili licu, ili na ravnini koju sljedeću odaberete, s alatom spremnim u njoj.", "prefs.sketch_tracking_guides": "Vodilice poravnanja središta i središnje točke", "prefs.sketch_tracking_guides_note": "Zadržite pokazivač iznad središta kružnice ili središnje točke ravnog brida, zatim se pomaknite vodoravno ili okomito da se prikaže privremena točkasta vodilica.", + "prefs.sketch_tracking_points": "Vodilice poravnanja iz krajnjih točaka i kutova tijekom crtanja", + "prefs.sketch_tracking_points_note": "Dok alat za crtanje čeka točku, zadržavanje pokazivača iznad kraja linije ili luka, kuta pravokutnika ili slobodne točke prikazuje istu privremenu točkastu vodilicu kao i za središte ili središnju točku. Isključeno: samo središta i središnje točke.", "prefs.sketching": "Skiciranje", "prefs.snap_drawing_note": "Tijekom crtanja ili povlačenja točke skice.", "prefs.source": "Izvor", @@ -2016,6 +2395,24 @@ "prefs.status_error": "Pogreška", "prefs.status_selected": "Odabrano", "prefs.status_warning": "Upozorenje", + "prefs.structure.appearance": "Izgled", + "prefs.structure.appearance_note": "Boje, tekst i pristupačnost.", + "prefs.structure.in_profile": "U profilu", + "prefs.structure.layout": "Raspored", + "prefs.structure.layout_note": "Gdje se nalaze dijelovi prozora.", + "prefs.structure.look": "Vizualno", + "prefs.structure.measure_pointer": "Mjerenje i pokazivač", + "prefs.structure.mouse3d": "3D miš", + "prefs.structure.mouse3d_note": "SpaceMouse i SpaceNavigator.", + "prefs.structure.navigation_note": "Miš i dodirna pločica. 3D miš ima vlastitu stranicu.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Promijenjeno otkako je spremljeno", + "prefs.structure.profile_hover": "Spremljeno u profilima postavki", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Skica", + "prefs.structure.tools": "Alati", + "prefs.structure.tools_note": "Kako se ponašaju alati za modeliranje.", + "prefs.structure.work": "Rad", "prefs.supersampling_brief": "Iscrtava prikaz većim i smanjuje ga filtriranjem: vrlo oštro i zahtjevnije.", "prefs.tab_accent_note": "Naglasna boja prati aktivnu karticu", "prefs.theme_file": "datoteka teme", @@ -2027,6 +2424,16 @@ "prefs.theme_follow_off": "Isključeno", "prefs.theme_follow_stop": "Prestani pratiti", "prefs.theme_import_hint": "Kliknite za odabir datoteke teme, ispustite je ovdje ili pritisnite Ctrl+V (Cmd+V na Macu) s kopiranom temom", + "prefs.theme_option_opacity": "Neprozirnost", + "prefs.theme_option_opacity_help": "Podešava neprozirnost plutajućih panela. Donja granica čitljivosti štiti tekst preko boja prozora prikaza.", + "prefs.theme_option_tab_colours": "Boje kartica", + "prefs.theme_option_tab_colours_help": "Koristi boje panela i prozora prikaza ove teme za svaku karticu vrpce.", + "prefs.theme_option_tab_fade_ms": "Prijelaz kartica", + "prefs.theme_option_tab_fade_ms_help": "Postupno prelijeva boje panela i prozora prikaza pri promjeni kartice. Nula mijenja trenutno.", + "prefs.theme_options_badge": "Opcije", + "prefs.theme_options_more": "Više · {count}", + "prefs.theme_options_reset": "Vrati zadano", + "prefs.theme_options_unavailable": "Nedostupno na ovom uređaju", "prefs.theme_paste": "Zalijepi temu", "prefs.theme_paste_none": "Međuspremnik ne sadrži SolidCraft temu", "prefs.timeline_half_hour": "−30 min", @@ -2048,13 +2455,23 @@ "prefs.under_cursor": "Ispod pokazivača", "prefs.units_precision": "Jedinice i preciznost", "prefs.updates": "Ažuriranja", + "prefs.value_boxes_in_view": "Prikaži vrijednosti pokraj njihovih ručica u prikazu", + "prefs.value_boxes_in_view_tip": "Vrijednost naredbe (Udaljenost, Polumjer…) u okviru pokraj njezine ručice, preko modela. Isključeno: upisujete je u prozor naredbe, koji preuzima tipkovnicu nakon odabira, i ništa ne prekriva model.", "prefs.view": "Ponašanje prikaza", "prefs.view_confirm_corner": "U redu i Odustani u kutu prikaza", "prefs.view_confirm_corner_note": "Dok je otvoren dijalog ili skica, kvačica i križić gore desno u prikazu rade isto što i gumbi U redu i Odustani u dijalogu, odnosno završavaju i poništavaju skicu. Navigator prikaza pomiče se ispod njih.", "prefs.viewport": "Prozor prikaza", + "prefs.viewport_analysis_status": "Prikaži status analize u prozoru prikaza", + "prefs.viewport_analysis_status_help": "Prikazuje aktivne analize iznad prozora prikaza, otvara njihove legende iz svake stavke, a tipka Esc isključuje najnoviju analizu. Isključite kako biste vratili legende u kutovima i prethodno ponašanje tipke Esc.", "prefs.viewport_background": "Pozadina", "prefs.viewport_background_colour": "Boja", "prefs.viewport_background_theme": "Gradijent teme", + "prefs.viewport_section_status": "Prikaži status presjeka u prozoru prikaza", + "prefs.viewport_section_status_help": "Prikazuje postavku presjeka u prozoru prikaza. Escape i aktivni gumb na vrpci isključuju je. Isključite kako biste zadržali prethodne kontrole presjeka.", + "prefs.viewport_status_details": "Detalji prozora prikaza uživo", + "prefs.viewport_status_details_help": "Uređuje postavke aktivne analize i presjeka u standardnim karticama detalja. Isključite kako biste vratili legende analize samo za čitanje i dijaloški prozor Presjek.", + "prefs.viewport_status_summary": "Sažmi statusne stavke prozora prikaza", + "prefs.viewport_status_summary_help": "Sažima tri ili više statusnih stavki prozora prikaza u jednu zbirnu oznaku. Isključite kako bi svaka stavka ostala u punom retku.", "prefs.wheel": "Kotačić", "prefs.wheel_trackpad": "Kotačić i dodirna pločica", "prefs.workspace": "Radni prostor", @@ -2064,6 +2481,10 @@ "properties.title": "Svojstva: {name}", "recovery.days_ago": "prije {count} dana", "recovery.detail": "{file} · značajki: {features} · automatski spremljeno {when}", + "recovery.discard_all": "Odbaci sve", + "recovery.discard_all_detail": "Ovo se ne može poništiti.", + "recovery.discard_all_title": "Odbaciti automatska spremanja ({count})?", + "recovery.discard_all_title_one": "Odbaciti 1 automatsko spremanje?", "recovery.hours_ago": "prije {count} h", "recovery.just_now": "upravo", "recovery.min_ago": "prije {count} min", @@ -2179,6 +2600,10 @@ "render.base_color": "Osnovna boja · sRGB", "render.base_metallic": "Metalni udio", "render.base_opaque_only": "Ovaj uređivač čuva semantiku neprozirnih tijela. Za optičko propuštanje upotrijebite izričite kontrole stakla.", + "render.batch_all_shots": "Svi kadrovi ({count})", + "render.batch_empty": "Spremite kadar prije renderiranja svih kadrova.", + "render.batch_limit": "Renderiranje svih kadrova ograničeno je na 32 kadra.", + "render.batch_status": "U tijeku: {running} · Na čekanju: {waiting}", "render.bloom_enable": "Sjaj prikaza", "render.bloom_help": "Kreativni sjaj samo na izlazu iz pozitivnih linearnih svijetlih dijelova, raširen kroz tri normalizirana prolaza kutijastog filtra. Polumjer je u pikselima izlaza. Dodaje se u linearnoj svjetlosti prikaza prije sRGB-a; nije objektiv, volumetrijski efekt niti poboljšanje konvergencije. Sirovi EXR ostaje nepromijenjen.", "render.bloom_opaque": "Sjaj zahtijeva neprozirni izlaz. Prozirni PNG odbija se, a ne spljoštava tiho.", @@ -2289,6 +2714,13 @@ "render.choose_look": "Najprije odaberite izgled u Izgledima", "render.chromatic_offset": "Kromatski pomak rubova", "render.clear_stage": "Ukloni spremljenu scenu", + "render.compare_divider": "Razdjelnik usporedbe", + "render.compare_live": "Uživo", + "render.compare_live_preview": "Pregled uživo", + "render.compare_render": "Renderiranje {number}", + "render.compare_side": "Renderiranje {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · zabilježeno u reviziji {revision}", + "render.compare_swap": "Zamijeni strane", "render.copy_request": "Kopiraj JSON", "render.cpu_aa_help": "Prostorni uzorci: više uzoraka poboljšava rubove i produljuje renderiranje.", "render.cpu_area_add": "Dodaj pravokutno CPU svjetlo", @@ -2929,7 +3361,9 @@ "render.output_ready": "Spremno za renderiranje", "render.output_run_check": "Pokreni provjeru", "render.output_size_limit": "{method}: do {dimension} px po strani i {pixels} piksela. Najveća veličina koja stane: {width} × {height}.", + "render.output_size_method_profile": "Za renderiranje {width} × {height} odaberite {method} s CPU profilom resursa {profile} ili manju veličinu.", "render.output_size_ok": "Veličina u redu · {width} × {height} px", + "render.output_size_profile": "Za renderiranje {width} × {height} odaberite CPU profil resursa {profile} ili manju veličinu.", "render.output_swap_orientation": "Zamijeni širinu i visinu", "render.output_tools_inspector": "Veličinu i format uredite u inspektoru Izlaz.", "render.output_view_image": "Prikaži sliku", @@ -3036,6 +3470,10 @@ "render.result_retained": "Prikazuje se posljednja dovršena slika; novije renderiranje još je nije zamijenilo.", "render.result_sequence": "Kontrolna točka", "render.result_title": "Rezultat renderiranja", + "render.results_choose": "Zadržani rezultati", + "render.results_label": "Renderiranje {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [zastarjelo]", + "render.results_unnamed": "Slika", "render.return_design": "Natrag na Dizajn", "render.review_stale": "Ovaj pregled je zastario. Riješite ga ili ponovno provjerite prije primjene.", "render.ribbon_aging": "Starenje", @@ -3142,6 +3580,7 @@ "render.size_custom": "Prilagođeno…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · treba {profile}", "render.size_presets": "Unaprijed zadane veličine", "render.size_presets_pending": "Stiže s uređivačem Izlaz", "render.size_preview": "Pregled", @@ -3429,6 +3868,24 @@ "sheet.flange_type_contour": "Kontura", "sheet.flange_type_edge": "Brid", "sheet.no_body": "nema limenog tijela: izradite ga pomoću Prirubnica > Osnova ili pretvorite ploču u lim pomoću Pretvori u lim (odaberite njezino veliko ravno lice)", + "sheet.personal_rules.confirm_delete": "Potvrdi brisanje", + "sheet.personal_rules.delete": "Izbriši", + "sheet.personal_rules.delete_prompt": "Izbrisati ovo osobno pravilo? Pravila koja su već u dizajnima ostaju nepromijenjena.", + "sheet.personal_rules.full": "Osobna biblioteka već sadrži 64 pravila.", + "sheet.personal_rules.invalid_name": "Unesite kratak naziv bez prijeloma redaka ili kontrolnih znakova.", + "sheet.personal_rules.invalid_values": "Dovršite vrijednosti pravila: svaka se mora moći izračunati u ovom dizajnu, uz pozitivnu debljinu i K-faktor od 0 do 1.", + "sheet.personal_rules.missing": "Odabrano osobno pravilo više nije dostupno.", + "sheet.personal_rules.name": "Naziv pravila", + "sheet.personal_rules.name_exists": "Osobno pravilo s ovim nazivom već postoji. Upotrijebite drugi naziv.", + "sheet.personal_rules.name_hint": "Jedinstven naziv", + "sheet.personal_rules.overwrite": "Spremi promjene u odabrano osobno pravilo", + "sheet.personal_rules.rename": "Preimenuj", + "sheet.personal_rules.rule": "Osobno pravilo", + "sheet.personal_rules.save": "Spremi novo", + "sheet.personal_rules.scope": "Spremljeno u vašem profilu za sve dizajne.", + "sheet.personal_rules.select": "Odaberite pravilo", + "sheet.personal_rules.title": "Osobna pravila", + "sheet.personal_rules.unsupported": "Ovo pravilo ima vrijednosti koje ova verzija ne može upotrijebiti.", "shortcut.json_error": "parametri moraju biti JSON: {error}", "shortcut.no_command": "nema naredbe `{id}`; tekst prije JSON-a mora biti id naredbe", "shortcut.pin": "Prikvači na vrh okvira S", @@ -3465,8 +3922,10 @@ "sketch_text.align_right": "Desno", "sketch_text.bold": "Podebljano", "sketch_text.builtin_font": "{family} (ugrađeno)", + "sketch_text.formula": "Počnite znakom = kako biste riječi izgradili iz parametara: ='W' + number(Width)", "sketch_text.italic": "Kurziv", "sketch_text.loading_fonts": "Traženje instaliranih fontova…", + "sketch_text.no_bold": "Ugrađeni font nema podebljanu varijantu: odaberite instalirani font", "sketch_text.on_path": "Tekst prati svoju putanju: krivulja ga postavlja", "sketch_text.path_clear": "Skini tekst s njegove krivulje", "sketch_text.path_hint": "Krivulja skice koju tekst prati: kliknite ovdje, a zatim krivulju", @@ -3498,10 +3957,7 @@ "the two origins are on the same component": "oba ishodišta nalaze se na istoj komponenti", "thread.automatic_size": "Automatska veličina", "thread.designation": "Oznaka", - "thread.direction": "Smjer navoja", "thread.iso_metric": "ISO metrički", - "thread.left_hand": "Lijevi", - "thread.right_hand": "Desni", "thread.select_size": "Odaberite veličinu", "timeline.delete_after_marker_one": "Izbriši 1 značajku nakon oznake vraćanja", "timeline.delete_after_marker_other": "Izbriši značajke nakon oznake vraćanja: {count}", @@ -3605,6 +4061,8 @@ "ui.3d_mouse_section": "3D miš", "ui.3d_mouse_show_in_view": "Prikaži 3D miš u 3D prikazu", "ui.3d_mouse_show_in_view_tip": "Slika vašeg 3D miša u donjem lijevom kutu, koja se kreće dok ga pomičete.", + "ui.3d_mouse_sketch_orbit": "Okreći skice 3D mišem", + "ui.3d_mouse_sketch_orbit_tip": "3D miš okreće prikaz i dok je skica otvorena i gleda se okomito, kao što to može i miš. Isključeno: pomiče i zumira skicu dok ne nagnete prikaz.", "ui.3d_mouse_skip": "Moj uređaj ovo ne može", "ui.3d_mouse_skip_tip": "Preskače ovo kretanje u oba smjera, a kalibracija ga izostavlja.", "ui.3d_mouse_speed": "Brzina 3D miša", @@ -3633,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Zakrenite kapicu suprotno od kazaljke na satu, držite je, a zatim pustite.", "ui.3d_mouse_switch_cap": "Kalibriraj kao Povratak u središte", "ui.3d_mouse_switch_trackball": "Kalibriraj kao kuglični miš", + "ui.3d_mouse_use_direct": "Koristi izravni upravljački program", + "ui.3d_mouse_use_direct_tip": "Čitaj 3D miš izravno (hidraw) umjesto preko spacenavd.", "ui.3d_mouse_view_axis": "Os prikaza", "ui.3d_mouse_view_off": "Isključeno", "ui.3d_mouse_view_off_tip": "Profil upravljačkog programa 3D miša isključuje ovu os, pa njezino kretanje ne pomiče prikaz. Odabir kretanja druge osi ovdje ih zamjenjuje, a to kretanje prestaje pomicati prikaz.", @@ -3671,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Pokrenite ovo u terminalu, a zatim pritisnite Poveži ponovno:", "ui.agent_chat_auth_title": "Prijavi se kod agenta", "ui.agent_chat_cancel": "Odustani", + "ui.agent_chat_cancel_timeout": "Agent nije odgovorio na Zaustavi pa je veza s njim prekinuta. Ponovno se povežite kako biste nastavili.", + "ui.agent_chat_cannot_start": "Instalirano, ali se ne pokreće: {error}", "ui.agent_chat_changes": "Promjene: {n}, jedan korak poništavanja", "ui.agent_chat_changes_n": "Promjene: {n}", "ui.agent_chat_changes_of": "Promjene: {n}/{limit}", @@ -3679,11 +4141,13 @@ "ui.agent_chat_command": "Naredba agenta", "ui.agent_chat_connect": "Poveži", "ui.agent_chat_copy": "Kopiraj", + "ui.agent_chat_copy_message": "Kopiraj poruku", "ui.agent_chat_ctx_bodies": "Tijela", "ui.agent_chat_ctx_elements": "Elementi", "ui.agent_chat_ctx_features": "Značajke", "ui.agent_chat_ctx_more": "+još {n}", "ui.agent_chat_ctx_other": "Ostalo", + "ui.agent_chat_custom_heading": "Prilagođeni model", "ui.agent_chat_custom_hint": "Bilo koji program koji govori Agent Client Protocol na stdin i stdout. Ne pokreće ga nikakva ljuska.", "ui.agent_chat_denied": "Odbijeno", "ui.agent_chat_deny": "Odbij", @@ -3727,8 +4191,16 @@ "ui.agent_chat_mode_all": "Sve", "ui.agent_chat_mode_ask": "Pitaj", "ui.agent_chat_mode_edits": "Izmjene", + "ui.agent_chat_model_custom": "Koristi prilagođeni: {model}", "ui.agent_chat_model_no_tools": "{model} ne može koristiti SolidCraft alate, pa može samo razgovarati. Odaberite model s podrškom za alate.", + "ui.agent_chat_model_rejected": "Agent nije prihvatio model {model}: {error}", + "ui.agent_chat_model_search": "Pretraži modele…", "ui.agent_chat_model_tip": "Model koji agent koristi. Vaš odabir pamti se za ovog agenta.", + "ui.agent_chat_models_failed": "Popis modela nije moguće učitati: {error}", + "ui.agent_chat_models_heading": "Dostupni modeli", + "ui.agent_chat_models_listing": "Učitavanje popisa modela…", + "ui.agent_chat_models_none": "Krajnja točka ne navodi nijedan model", + "ui.agent_chat_models_not_a_list": "Odgovor nije popis modela", "ui.agent_chat_new": "Novi razgovor", "ui.agent_chat_new_confirm": "Započeti novi razgovor? Trenutni će biti obrisan.", "ui.agent_chat_next_picture": "Sljedeća slika", @@ -3763,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "U redu čekanja (zaustavljeno, nije poslano)", "ui.agent_chat_refresh": "Osvježi", "ui.agent_chat_refused": "Nije dopušteno agentu: {reason}", + "ui.agent_chat_reinstall": "{agent} je instaliran ({program}), ali se nije pokrenuo kad ga je SolidCraft provjerio: {error}\nInstalacija je možda nepotpuna ili izrađena za drugu vrstu računala. Ponovno ga instalirajte naredbom `{install}`, provjerite ispisuje li u terminalu svoju verziju, a zatim pritisnite Osvježi.", "ui.agent_chat_remove": "Ukloni iz reda", "ui.agent_chat_remove_file": "Skini s ove poruke", "ui.agent_chat_remove_imported": "Skini s ove poruke; dio ostaje u dizajnu (Poništi ga uklanja)", + "ui.agent_chat_reply_cut_off": "Odgovor je dosegnuo ograničenje duljine prije nego što je završio pa je možda nepotpun. Zamolite agenta da nastavi ili da odgovori kraće.", + "ui.agent_chat_reply_declined": "Model je odbio odgovoriti na ovu poruku.", "ui.agent_chat_retry": "Pokušaj ponovno", "ui.agent_chat_right": "Desno", "ui.agent_chat_save": "Spremi", @@ -3824,12 +4299,17 @@ "ui.ai_copy_suffix": "kopiraj", "ui.ai_custom_url": "Prilagođeni URL", "ui.ai_default": "Zadano", + "ui.ai_edit": "Uredi", + "ui.ai_edit_agent_title": "Uredi agenta", + "ui.ai_edit_gone": "Ovaj agent je uklonjen pa nema što spremiti.", + "ui.ai_edit_tip": "Promijenite naziv, naredbu ili krajnju točku ovog agenta. Spremljeni ključ ostaje skriven.", "ui.ai_http_busy": "krajnja točka je zauzeta ili je preko ograničenja; pokušajte ponovno kasnije", "ui.ai_http_key": "krajnja točka odbila je ključ: provjerite ga u Postavke > AI", "ui.ai_http_not_found": "nema takve krajnje točke ili modela: provjerite osnovni URL i naziv modela", "ui.ai_http_too_large": "razgovor je prevelik za ovu krajnju točku; započnite novi razgovor", "ui.ai_key": "API ključ", "ui.ai_key_hint": "neobavezno; čuva se u sustavskom privjesku ključeva", + "ui.ai_key_keep_hint": "ostavite prazno kako biste zadržali spremljeni ključ", "ui.ai_key_needs_https": "Ključ se šalje samo preko HTTPS-a ili na ovo računalo.", "ui.ai_key_note": "Čuva se u sustavskom privjesku ključeva, nikad u postavkama SolidCrafta. Za lokalni poslužitelj ostavite prazno.", "ui.ai_keychain_error": "Sustavski privjesak ključeva odbio je: {error}", @@ -3856,11 +4336,15 @@ "ui.ai_permissions": "Dopuštenja", "ui.ai_preset": "Unaprijed zadano", "ui.ai_protocol": "Protokol", + "ui.ai_reasoning_effort": "Razina zaključivanja", + "ui.ai_reasoning_effort_field_hint": "prazno = zadana vrijednost pružatelja", + "ui.ai_reasoning_effort_hint": "Neobavezno. Šalje se krajnjoj točki kao `reasoning_effort`; prihvaćene vrijednosti razlikuju se od pružatelja do pružatelja (na primjer `low`, `high` ili `max`). SolidCraft nikad ne mijenja vrijednost koju ovdje postavite. Ostavite prazno da se ništa ne šalje i da se zadrži zadana vrijednost pružatelja.", "ui.ai_remove": "Ukloni", "ui.ai_request_timed_out": "Model je trajao dulje od {seconds} s. Vremensko ograničenje zahtjeva za ovu krajnju točku možete povećati u Postavke › Asistent.", "ui.ai_request_timeout": "Vremensko ograničenje zahtjeva", "ui.ai_request_timeout_hint": "Koliko dugo jedan zahtjev modelu na ovoj krajnjoj točki smije trajati, od 30 s do jednog sata. Povećajte za spori lokalni model.", "ui.ai_reset": "Vrati zadano", + "ui.ai_save": "Spremi", "ui.ai_settings": "AI postavke…", "ui.ai_show_features": "Prikaži AI funkcije", "ui.ai_show_features_note": "Razgovor s agentom: ploča u kojoj agent za kodiranje koji već koristite ili krajnja točka modela koju odaberete radi na otvorenom dizajnu. Isključeno: nema AI gumba, prečaca, stavke izbornika ni ploče, i ništa se ne traži niti pokreće.", @@ -3949,6 +4433,7 @@ "ui.circle": "Kružnica", "ui.circular_pattern": "Kružni niz", "ui.clear": "Očisti", + "ui.clear_print_face": "Ukloni plohu ispisa", "ui.clear_recent": "Očisti nedavno", "ui.clear_the_selection": "Poništi odabir", "ui.click_selects_whole_bodies": "Klik odabire cijela tijela", @@ -3983,7 +4468,17 @@ "ui.constant": "Konstantno", "ui.constraints_conflict": "Ograničenja su u sukobu", "ui.construction": "Pomoćna", + "ui.construction.angle_hint": "Pomoćni pravac: kliknite točku, pa upišite kut ili odaberite smjer", + "ui.construction.bisector_hint": "Simetrala: odaberite dvije ravne linije koje se sijeku, pa željeno rješenje", + "ui.construction.common_hint": "Zajednička tangenta: odaberite dvije kružnice ili dva luka, pa željeno rješenje", + "ui.construction.contact_hint": "Tangenta: odaberite kružnicu/luk ili otvoreni spline/koniku, pa točku dodira (krivulje slobodnog oblika: krajnje točke)", + "ui.construction.external_hint": "Tangenta: odaberite kružnicu ili luk, vanjsku točku, pa željeno rješenje", + "ui.construction.free_hint": "Pomoćni pravac: kliknite dvije točke; desnim klikom počnite ispočetka", + "ui.construction.normal_needs_length": "Beskonačna linija uvijek je pomoćna: upišite duljinu kako biste nacrtali običnu liniju", + "ui.construction.point_hint": "Pomoćni pravac: kliknite točku kroz koju prolazi", + "ui.construction.reference_hint": "Pomoćni pravac: odaberite ravnu liniju, pa točku; desnim klikom promijenite referencu", "ui.construction.ribbon_label": "Pomoćne", + "ui.construction.side_hint": "Pomoćni pravac: kliknite stranu prema kojoj pravac ide; desnim klikom počnite ispočetka", "ui.context_menu": "Kontekstni izbornik", "ui.continuity_g0": "G0 pregib", "ui.continuity_g1": "G1 tangentno", @@ -4011,6 +4506,7 @@ "ui.dark": "Tamna", "ui.default_modelling_orientation": "Zadana orijentacija modeliranja", "ui.delete": "Izbriši", + "ui.delete_select_first": "Najprije odaberite što želite izbrisati: značajke, tijela, komponente ili geometriju skice", "ui.depth": "Dubina", "ui.design": "Dizajn", "ui.design_properties.author": "Autor", @@ -4025,6 +4521,40 @@ "ui.design_properties.project": "Projekt", "ui.design_properties.revision": "Revizija", "ui.design_saved": "Spremljeno: {path}", + "ui.details_access_caption": "Lica pokazuju može li alat doći do njih iz odabranog smjera.", + "ui.details_angle": "Kut", + "ui.details_continuity_caption": "Uredite odabrani šav. Ostali šavovi zadržavaju vlastite postavke.", + "ui.details_continuity_stale": "Ranija geometrija: ponovno pokrenite analizu kako biste uredili ili uokvirili ovaj šav.", + "ui.details_copy_list": "Kopiraj popis", + "ui.details_curvature": "Tolerancija zakrivljenosti", + "ui.details_curvature_caption": "Lica su obojena prema svojem lokalnom polumjeru zakrivljenosti.", + "ui.details_direction": "Smjer alata", + "ui.details_draft_caption": "Lica su obojena prema kutu u odnosu na smjer vađenja iz kalupa.", + "ui.details_edit_seam": "Uredi šav", + "ui.details_fixture": "Uzorak komponente — samo primjer podataka", + "ui.details_fixture_caption": "Uzorak komponente s ilustrativnim vrijednostima; ovo nije rezultat modela.", + "ui.details_fixture_problem": "Primjer nalaza s problemom", + "ui.details_fixture_readout": "Primjer izmjerene vrijednosti", + "ui.details_flip": "Obrni", + "ui.details_gap": "Otvoreni kraj", + "ui.details_hatch": "Šrafiraj presječena lica", + "ui.details_jump": "Skok zakrivljenosti", + "ui.details_key": "Legenda", + "ui.details_offset": "Odmak", + "ui.details_plane": "Ravnina", + "ui.details_pull": "Smjer vađenja iz kalupa", + "ui.details_radius": "Polumjer", + "ui.details_readout": "Očitanje", + "ui.details_samples": "Uzorci", + "ui.details_seam": "{body} · Brid {edge}", + "ui.details_settings": "Postavke", + "ui.details_sharp_gap": "Oštro ili otvoreno", + "ui.details_show_all": "Prikaži sve ({count})", + "ui.details_smooth": "Glatko", + "ui.details_stripes": "Pruge", + "ui.details_target": "Uokviri geometriju", + "ui.details_worst_seams": "Najgori šavovi", + "ui.details_zebra_caption": "Odražene pruge pokazuju koliko se glatko lica spajaju.", "ui.diameter": "Promjer", "ui.dimension": "Kota", "ui.direct_interaction": "Izravna interakcija", @@ -4069,6 +4599,7 @@ "ui.edit_in_place_saved_elsewhere": "Dio je spremljen u drugu datoteku; sklop i dalje povezuje {name}", "ui.edit_in_place_wait": "Pričekajte da završi ono što se izvodi u dizajnu", "ui.edit_section_analysis": "Uredi analizu presjeka", + "ui.edit_sketch_empty": "Nema skica za uređivanje", "ui.ellipse": "Elipsa", "ui.emboss_wrap_note": "Ortogonalni linijski profili tangentni na jedan podržani valjak automatski se omataju. Odaberite stijenku kako biste odabrali cilj.", "ui.end_radius": "Krajnji polumjer", @@ -4079,12 +4610,15 @@ "ui.equation_explicit": "Eksplicitni", "ui.equation_form": "Oblik", "ui.equation_note": "Varijabla je običan broj: sin(t) je uzima u radijanima. Rezultat bez jedinice izražen je u jedinici dizajna.", + "ui.equation_note_range": "Varijabla je duljina, kao i njezin raspon: kombinirajte je s parametrima duljine, a za sin() je podijelite duljinom. Rezultat bez jedinice izražen je u jedinici dizajna.", "ui.equation_parametric": "Parametarski", + "ui.equation_variable_unit": "Varijabla ima jedinicu raspona", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Ekvivalentni polumjer", "ui.expand": "Proširi", + "ui.explode_needs_two_components": "Rastavljeni prikaz razmiče komponente, pa dizajn treba imati dvije ili više njih (Nova komponenta, Umetni dizajn ili Izradi komponente iz tijela)", "ui.exportDxf": "Izvezi DXF…", "ui.export_ellipsis_keymap": "Izvezi…", "ui.export_keymap_tip": "Tipke, favoriti okvira S i alatna traka, kao datoteka", @@ -4210,6 +4744,7 @@ "ui.hideOrigin": "Sakrij ishodište", "ui.hidePlanes": "Sakrij ravnine", "ui.hideProfile": "Sakrij profil", + "ui.hide_component_history": "Sakrij njezinu vremensku traku", "ui.hide_origin_by_default": "Zadano sakrij ishodište", "ui.hide_origin_note": "Novi dizajni počinju sa skrivenom mapom Ishodište. Dizajn zadržava vlastitu postavku Ishodišta kad ga prikažete ili sakrijete.", "ui.history_back": "Idi korak natrag", @@ -4217,6 +4752,7 @@ "ui.history_edge_hint": "dvaput kliknite brid", "ui.history_first": "Idi na početak", "ui.history_forward": "Idi korak naprijed", + "ui.history_hide_hidden": "Sakrij skrivene komponente", "ui.history_hide_names": "Sakrij nazive", "ui.history_last": "Idi na kraj", "ui.history_marker_tip": "Oznaka vraćanja: povucite kako biste vratili model unatrag; nove značajke dolaze ovdje", @@ -4226,10 +4762,12 @@ "ui.history_play_button_show": "Prikaži tipku za reprodukciju", "ui.history_play_finish_action": "Završite trenutnu radnju prije reprodukcije vremenske trake", "ui.history_play_roll_back": "Pomaknite oznaku vraćanja unatrag prije reprodukcije", + "ui.history_show_hidden": "Prikaži skrivene komponente", "ui.history_show_names": "Prikaži nazive", "ui.history_sketch_listed_under": "Navedeno ispod {feature}", "ui.history_title": "Vremenska traka", "ui.history_toggle_names": "Prikaži ili sakrij nazive značajki", + "ui.history_waits_for_editor": "Poništi, Ponovi i vremenska traka čekaju dok se ne otvori uređivač značajke", "ui.hole": "Provrt", "ui.hole_tap_type": "Vrsta navoja provrta", "ui.hole_type": "Vrsta provrta", @@ -4245,6 +4783,7 @@ "ui.insert_design.saved_file": "{name} ima nespremljene promjene, pa je umetnuta njegova spremljena datoteka. Spremite ga, a zatim pokrenite Ažuriraj veze kako biste unijeli promjene.", "ui.insert_design.unsaved": "Nespremljene promjene", "ui.inspect": "Pregledaj", + "ui.instances": "Instance", "ui.intersect": "Presjek", "ui.isolate": "Izoliraj", "ui.join": "Spoji", @@ -4253,12 +4792,14 @@ "ui.joints": "Spojevi", "ui.keyboard_shortcuts": "Tipkovnički prečaci", "ui.language": "Jezik", + "ui.lasso_select": "Laso (povucite petlju slobodnom rukom: obuhvaća sve što je u cijelosti unutra)", "ui.layout_compact": "Kompaktno", "ui.layout_floating": "Plutajuće", "ui.length": "Duljina", "ui.length_decimals": "Decimale duljine", "ui.light": "Svijetla", "ui.line": "Linija", + "ui.line_arc_hint": "Tangentni luk: kliknite kraj luka. Ponovno se zadržite na posljednjoj točki za linije; desni klik ili Esc za završetak", "ui.link_copies": "Poveži identične kopije", "ui.link_copies_keep": "Zadrži", "ui.link_copies_link": "Poveži", @@ -4347,6 +4888,7 @@ "ui.part_size_shared": "Ponovno gradi dio, zamjenjujući sve dodane značajke. Svi primjerci ove komponente ažuriraju se.", "ui.paste": "Zalijepi", "ui.path": "Putanja", + "ui.pattern_object_type_tip": "Tijela: puni oblici, odabiru se u prikazu ili u stablu modela; svako se kopira u cijelosti.\nZnačajke: koraci vremenske trake, poput ekstruzije ili provrta, odabiru se na vremenskoj traci ili na licu koje su izradili; korak se ponavlja.\nSkica nije ni jedno ni drugo: ponovite njezine krivulje pomoću alata Niz ili Zrcali u samoj skici ili je najprije ekstrudirajte.", "ui.pattern_on_path": "Niz duž putanje", "ui.perforate_margin_default": "iz promjera", "ui.perforate_pitch": "Korak", @@ -4373,12 +4915,17 @@ "ui.plugins_skipped": "Mape nije bilo moguće pročitati: {count}.", "ui.plugins_version": "{version}", "ui.point": "Točka", + "ui.point_cloud_add_filter": "Dodaj filter…", "ui.point_cloud_auto_range": "Automatski raspon", "ui.point_cloud_color_by": "Boja prema", "ui.point_cloud_file_colors": "Boje iz datoteke", + "ui.point_cloud_filter_by": "Filtriraj prema", "ui.point_cloud_height_high": "Najviše", "ui.point_cloud_height_low": "Najniže", + "ui.point_cloud_legend_filter": "Prikazano i skriveno u legendi iznad", "ui.point_cloud_no_file_colors": "Datoteka nema boja", + "ui.point_cloud_pause": "Pauziraj", + "ui.point_cloud_play": "Reproduciraj", "ui.point_cloud_single_color": "Jedna boja", "ui.point_cloud_size": "Veličina točke", "ui.point_cloud_units": "Jedinice datoteke", @@ -4387,6 +4934,11 @@ "ui.polygon": "Mnogokut", "ui.preferences": "Postavke", "ui.press_a_key": "pritisnite tipku…", + "ui.print_face_body_not_sent": "Tijelo te plohe ne šalje se: najprije ga dodajte u Tijela", + "ui.print_face_cleared": "{body}: ploha ispisa uklonjena", + "ui.print_face_input": "Ploha ispisa", + "ui.print_face_pick": "Odaberite ravnu plohu punog tijela da postane ploha ispisa", + "ui.print_face_set": "{body}: ploha ispisa postavljena; Pošalji u slicer polaže tijelo na nju", "ui.profile": "Profil", "ui.profile_plane": "Ravnina profila", "ui.profiles": "Profili", @@ -4402,6 +4954,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Mjerenje…", + "ui.properties.measuring_bodies": "Mjerenje… {done} od {total} tijela", "ui.properties.measuring_failed": "Mjerenje je zaustavljeno prije završetka.", "ui.properties.principal_axis": "Glavna os {number}", "ui.properties.principal_moments": "Glavni momenti tromosti", @@ -4450,6 +5003,7 @@ "ui.revolve": "Rotiraj", "ui.ribbon_exit": "Izlaz", "ui.ribbon_labels": "Prikaži tekst ispod ikona na traci", + "ui.ribbon_menus_skip_pinned": "Izostavi prikvačene naredbe iz padajućih izbornika", "ui.ribbon_pin_footer": "Prikvačene naredbe prikazuju se na traci. Zadržite pokazivač iznad retka kako biste ga prikvačili ili otkvačili.", "ui.ribbon_workspace": "Radni prostor", "ui.right": "Desno", @@ -4468,6 +5022,7 @@ "ui.selectOther": "Odaberi drugo…", "ui.selectTangentChain": "Odaberi tangentni lanac", "ui.select_all": "Odaberi sve", + "ui.select_components_by_face": "Odaberi komponente (lice bira svoju komponentu)", "ui.selection": "Odabir", "ui.selection_modifiers": "Modifikatori odabira", "ui.selection_shift_add_only": "Shift+klik dodaje bez uklanjanja", @@ -4493,6 +5048,7 @@ "ui.showDimension": "Prikaži kotu", "ui.showOrigin": "Prikaži ishodište", "ui.showPlanes": "Prikaži ravnine", + "ui.show_component_history": "Prikaži njezinu vremensku traku", "ui.show_constraints": "Ograničenja", "ui.show_construction_geometries": "Pomoćna geometrija", "ui.show_dimensions": "Kote", @@ -4509,6 +5065,11 @@ "ui.sketch_intersect_selection_filter": "Filtar odabira", "ui.sketch_modifiers": "Modifikatori skice", "ui.sketch_project_geometry": "Geometrija", + "ui.sketch_report.all_constrained": "Sve je potpuno ograničeno.", + "ui.sketch_report.dof": "Stupnjevi slobode", + "ui.sketch_report.loose": "Nije potpuno ograničeno", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Izvješće o skici", "ui.sketch_scale": "Skaliranje skice", "ui.sketches": "Skice", "ui.slice": "Presijeci", @@ -4604,19 +5165,31 @@ "ui.view_angles": "Kutovi prikaza", "ui.view_angles_convention": "Stupnjevi oko osi prema gore. Skretanje 0° je Pogled sprijeda, 90° Pogled slijeva, −90° Pogled zdesna, 180° Pogled straga; nagib 90° je Pogled odozgo; pozitivno valjanje okreće model u smjeru kazaljke na satu.", "ui.view_angles_help": "Prikazuje nagib, skretanje i valjanje prikaza u stupnjevima te njegovu projekciju ispod orijentacijskog gizma. Kliknite očitanje kako biste upisali točne kutove.", + "ui.view_angles_lock": "Zaključaj {axis}", "ui.view_angles_ortho": "Ortogr.", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Nagib", "ui.view_angles_readout": "Nagib {pitch} · Skretanje {yaw} · Valjanje {roll}", "ui.view_angles_roll": "Valjanje", + "ui.view_angles_unlock": "Otključaj {axis}", "ui.view_angles_yaw": "Skretanje", + "ui.view_angles_zero": "Postavi {axis} na 0°", "ui.view_centre": "Središte prikaza", "ui.viewport_status_clear": "Isključi {name}", "ui.viewport_status_clear_hint": "Isključi {name} · Esc", + "ui.viewport_status_edges": "Bridovi: {count}", + "ui.viewport_status_from": "iz smjera {direction}", "ui.viewport_status_key": "Prikaži legendu za {name}", "ui.viewport_status_minimum_radius": "Minimalni polumjer", "ui.viewport_status_pairs": "Parovi: {count}", + "ui.viewport_status_section_hatch": "{setting} · šrafura", + "ui.viewport_status_section_plane": "Trenutna ravnina", + "ui.viewport_status_section_tilted": "nagnuto · {offset}", "ui.viewport_status_stripes": "Pruge: {count}", + "ui.viewport_status_summary_clear": "Isključi sve", + "ui.viewport_status_summary_heading": "U ovom prikazu", + "ui.viewport_status_summary_label": "{name} i još stavki: {count}", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Prati temu", "ui.visual_shaded_hidden_edges": "Osjenčano sa skrivenim bridovima", "ui.visual_shaded_with_edges": "Osjenčano s bridovima", @@ -4653,7 +5226,9 @@ "update.button": "Ažuriraj", "update.button_version": "Ažuriraj na {version}", "update.check_automatically": "Automatski provjeravaj ažuriranja", + "update.check_for_updates": "Provjeri ažuriranja", "update.check_now": "Provjeri sada", + "update.check_unavailable": "Provjera ažuriranja nije dostupna za ovu instalaciju.", "update.checking": "Provjera…", "update.copy": "Kopiraj", "update.dmg_opened": "Slika diska je otvorena i provjerena: povucite SolidCraft u Programe, zamijenite staru kopiju, a zatim ponovno pokrenite SolidCraft.", @@ -4700,6 +5275,7 @@ "web.open_link": "Otvoriti povezani dizajn?", "web.open_link_confirm": "Postoje nespremljene promjene. Otvoriti povezani dizajn u novoj kartici?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ odaberi · Enter / Tab dovrši · Esc odbaci", + "↑ ↓ choose · Enter applies this value": "↑ ↓ odabir · Enter primjenjuje ovu vrijednost", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ odaberi · Enter primjenjuje ono što ste upisali · Esc odbaci", "⌘Enter continues on GitHub.": "⌘Enter nastavlja na GitHubu." } diff --git a/assets/locales/hu.json b/assets/locales/hu.json index 6a4179c12..bda2dc4e3 100644 --- a/assets/locales/hu.json +++ b/assets/locales/hu.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "ÁTMENETI FELÜLET", "BOUNDARY SURFACE": "HATÁRFELÜLET", "BROWSER": "BÖNGÉSZŐ", + "Back to the original order": "Vissza az eredeti sorrendhez", "Ball": "Gömbcsukló", "Bar": "Rúd", "Base Center": "Alap középpontja", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Itt jelennek meg a megnyitott vagy mentett tervek.", "Determined by To Object. Choose Angle to edit the angular extent.": "Az Objektumig érték határozza meg. A szögtartomány szerkesztéséhez válassza a Szög lehetőséget.", "Diameter": "Átmérő", + "Did this assembly open the wrong way up?": "Rossz tájolással nyílt meg ez az összeállítás?", + "Did this part open the wrong way up?": "Rossz tájolással nyílt meg ez az alkatrész?", "Dimension new shapes": "Új alakzatok méretezése", "Direction": "Irány", "Discard": "Elvetés", @@ -474,6 +477,7 @@ "Rectangular": "Téglalap alakú", "Rectangular Tube": "Téglalap alakú cső", "Reference face": "Referencialap", + "Reference plane": "Referenciasík", "Relief Depth": "Tehermentesítés mélysége", "Relief Width": "Tehermentesítés szélessége", "Remove Tools": "Szerszámok eltávolítása", @@ -553,6 +557,7 @@ "Section": "Metszet", "Section (optional)": "Keresztmetszet (nem kötelező)", "Section position": "Szelvény helyzete", + "Sections": "Keresztmetszetek", "Sections (one sketch each)": "Keresztmetszetek (egy-egy vázlat)", "Select Other": "Másik kijelölése", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Más kijelölése: tartsa nyomva a bal gombot egy helyen a modellen (vagy jobb kattintás › Más kijelölése…) a kurzor alatti elemek listázásához; kattintson újra ugyanarra a helyre a következő elem kijelöléséhez. A középső gomb dupla kattintása a kezdőnézetre vált (Beállítások › Navigáció).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Illesztés a lapok és élek középpontjához", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "A SolidCraft nem tud közvetlenül jelentést beküldeni. Küldje be a GitHubon; az alkalmazásban nincs szükség tokenre.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "A SolidCraft bezárult, mielőtt ezek a tervek mentve lettek volna. Az utolsó automatikus mentésük megnyitható.", + "Sort A to Z": "Rendezés A-tól Z-ig", + "Sort Z to A": "Rendezés Z-től A-ig", "Spacing 2 must be a non-zero number": "A 2. térköznek nullától eltérő számnak kell lennie", "Spacing must be a non-zero number": "A térköznek nullától eltérő számnak kell lennie", "Specialise": "Specializálás", @@ -601,6 +608,7 @@ "Square": "Négyzet", "Stand it up": "Felállítás", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Felállítás: negyedfordulat az X körül, egyetlen visszavonható Mozgatás elemként.", + "Stand this assembly up?": "Felállítja ezt az összeállítást?", "Stand this part up?": "Felállítja ezt az alkatrészt?", "Start angle": "Kezdőszög", "Start bulge": "Kezdő ívelés", @@ -772,6 +780,8 @@ "at the face": "a lapnál", "bom.group_children": "Részalkatrészek az alkatrészük sorában", "browser.body_name": "Test{number}", + "browser.calibrate_click_a": "Kattintson a képen az A pontra, vagy adja meg a koordinátáit.", + "browser.calibrate_click_b": "Kattintson a képen a B pontra, vagy adja meg a koordinátáit.", "browser.calibrate_title": "Kalibrálás: {name}", "browser.capture_many": "{count} komponens el lett mozgatva, de a pozíciójuk nincs rögzítve.", "browser.capture_note": "A rögzítés megtartja az új pozíciót; a visszaállítás visszateszi.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (rögzítés elveszett)", "browser.sketch_editing": "{name} (szerkesztés alatt)", "browser.sketch_name": "Vázlat{number}", + "browser.sketches_to_parts_already_in_part": "már az alkatrészükben vannak", + "browser.sketches_to_parts_design_body": "magának a tervnek egy testén vannak", + "browser.sketches_to_parts_moved": "{moved} vázlat áthelyezve abba az alkatrészbe, amelyen van", + "browser.sketches_to_parts_no_exact_attachment": "pontos rögzítés nélküli lapon vannak", + "browser.sketches_to_parts_not_on_face": "nem egy alkatrész lapján vannak", + "browser.sketches_to_parts_part_missing": "az alkatrészük már nincs meg", + "browser.sketches_to_parts_result": "{moved} vázlat áthelyezve abba az alkatrészbe, amelyen van; {stayed} a helyén maradt: {why}", "browser.units": "Egységek: {units}", "cam.flat": "Sík lap", "cam.follower": "Követő", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Megjelenés felvétele", "cmd.appearance_replace": "Megjelenés cseréje", "cmd.assembly_bom": "Anyagjegyzék", + "cmd.assembly_mass_properties": "Tömegjellemzők", + "cmd.body.print_face": "Nyomtatási lap", "cmd.body_rename": "Test átnevezése", "cmd.browser_collapse_all": "Összes összecsukása", "cmd.browser_expand_all": "Összes kibontása", @@ -842,6 +861,7 @@ "cmd.component_extract": "Kivonás fájlba", "cmd.component_finish_edit": "Szerkesztés befejezése", "cmd.component_from_bodies": "Komponensek létrehozása testekből", + "cmd.component_hide_history": "Komponens előzményeinek elrejtése", "cmd.component_insert_design": "Terv beszúrása", "cmd.component_links": "Kapcsolatok listázása", "cmd.component_list": "Komponensek listázása", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Testek áthelyezése komponensbe", "cmd.component_move_features": "Elemek áthelyezése komponensbe", "cmd.component_move_sketches": "Vázlatok áthelyezése komponensbe", + "cmd.component_move_sketches_to_parts": "Vázlatok áthelyezése az alkatrészükbe", "cmd.component_paste_from_design": "Beillesztés másik tervből", "cmd.component_paste_new": "Beillesztés újként", "cmd.component_properties": "Komponens fizikai tulajdonságai", @@ -857,6 +878,7 @@ "cmd.component_rename": "Komponens átnevezése", "cmd.component_replace_with_link": "Csere hivatkozásra", "cmd.component_revert_position": "Pozíció visszaállítása", + "cmd.component_show_history": "Komponens előzményeinek megjelenítése", "cmd.component_unlock": "Tartalom feloldása", "cmd.component_update_links": "Kapcsolatok frissítése", "cmd.config_activate": "Konfiguráció aktiválása", @@ -867,6 +889,7 @@ "cmd.config_rule": "Konfigurációs szabály", "cmd.config_rules": "Konfigurációs szabályok", "cmd.config_table": "Konfigurációs táblázat megjelenítése", + "cmd.construct.plane.axis_point": "Sík tengelyen és ponton át", "cmd.construct_axis_edge": "Tengely élen át", "cmd.construct_axis_normal_to_face": "Lapra merőleges tengely", "cmd.construct_axis_through_cylinder": "Tengely hengeren/kúpon/tóruszon át", @@ -915,6 +938,11 @@ "cmd.explode_show": "Robbantott nézet megjelenítése", "cmd.expr_evaluate": "Kifejezés kiértékelése", "cmd.face_delete": "Lap törlése", + "cmd.file.export_3mf": "3MF exportálása", + "cmd.file.export_obj": "OBJ exportálása", + "cmd.file.export_step": "STEP exportálása", + "cmd.file.export_stl": "STL exportálása", + "cmd.file.export_urdf": "URDF exportálása", "cmd.file_export": "Exportálás", "cmd.file_insert_mesh": "Háló beszúrása", "cmd.file_insert_step": "STEP beszúrása", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Komponensszínek bekapcsolása", "cmd.inspect_colored_components_disable": "Komponensszínek kikapcsolása", "cmd.inspect_compare": "Testek összehasonlítása", + "cmd.inspect_compare_picture": "Kép összehasonlítása", "cmd.inspect_continuity": "Folytonosságelemzés", "cmd.inspect_curvature_comb": "Görbületi fésű elemzése", "cmd.inspect_curvature_map": "Görbülettérkép-elemzés", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Pontfelhő szerkesztése", "cmd.pointcloud_insert": "Pontfelhő beszúrása", "cmd.pointcloud_list": "Pontfelhők", + "cmd.render.compare.divider": "Renderösszehasonlító elválasztó mozgatása", + "cmd.render.result.discard": "Renderelési eredmény elvetése", + "cmd.render.result.select": "Renderelési eredmény kiválasztása", "cmd.render_aging_describe": "Rétegzett felületöregedés", "cmd.render_backends": "Renderelő motorok", "cmd.render_batch": "Összes felvétel renderelése", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Vezérlőpontos spline (5. fokú)", "cmd.sketch_spline_fit_point": "Illesztőpontos spline", "cmd.sketch_spline_insert_point": "Splinepont hozzáadása", + "cmd.sketch_spline_remove_point": "Splinepont eltávolítása", "cmd.sketch_spline_reverse": "Spline irányának megfordítása", "cmd.sketch_spun_profile": "Forgatott profil", "cmd.sketch_toggle_diameter": "Sugár / átmérő váltása", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Idővonal-marker mozgatása", "cmd.timeline_stop": "Előzmények leállítása", "cmd.timeline_suppress": "Elem elnyomása", + "cmd.ui.assistant": "Asszisztens megjelenítése/elrejtése", "cmd.view.render_browser": "Renderböngésző", "cmd.view.render_dock": "Renderpanel áthelyezése", "cmd.view.render_focus": "Renderfókusz nézet", + "cmd.view.status_details": "Nézetablak állapotának részletei", "cmd.view.status_items": "Nézetablak állapotelemei", "cmd.view_ambient_occlusion": "Környezeti takarás", "cmd.view_angle_readout": "Nézetszögek", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Navigációs eszköz", "cmd.view_top": "Felülnézet", "cmd.view_visual_style": "Vizuális stílus", + "color.blue": "Kék", "color.copy": "Kattintson a színértékek másolásához", "color.edit": "Kattintson a szín szerkesztéséhez", "color.gamma": "Színértékek megjelenítése 0–255 gamma térben", + "color.green": "Zöld", "color.hex": "Hex", "color.hex_help": "Adja meg: #rrggbb vagy #rrggbbaa; hat számjegy esetén az átlátszatlanság megmarad", "color.hex_hint": "#rrggbb", "color.hue": "Árnyalat", "color.linear": "Színértékek megjelenítése 0–1 lineáris térben", + "color.recent": "Legutóbbi színek", + "color.recent_help": "A bármelyik színmezőben kiválasztott színek itt jelennek meg", + "color.red": "Piros", + "color.saturation": "Telítettség (százalék)", "color.saturation_value": "Telítettség és érték", "color.selected": "Kijelölt szín", + "color.step_down": "Lépés lefelé", + "color.step_up": "Lépés felfelé", + "color.value": "Érték, a fényerő (százalék)", "config.column_filter_empty": "Nincs egyező oszlop", + "config.rule_parameter_columns": "Csak azok a paraméterek szerepelnek, amelyeknek van oszlopa a táblázatban. Az Oszlop hozzáadása (+) paranccsal vehet fel egyet, hogy itt használhassa.", + "config.rule_suppression_columns": "Csak azok az elemek szerepelnek, amelyeknek van Elnyomás oszlopa a táblázatban. Az Oszlop hozzáadása (+) paranccsal vehet fel egyet, hogy innen vezérelje.", "contact.components_count": "{count} komponens", "contact.enabled_label": "engedélyezve", "coupling.gear_1": "1. fogaskerék", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Kattintson egy másik hajtó méretre a neve beszúrásához", "dialog.dimension_name": "Méret: {name}", "dialog.edit_title": "{title} SZERKESZTÉSE", + "dialog.no_shown_body": "Nincs módosítható megjelenített test: jelenítsen meg egyet, vagy válassza az Új test lehetőséget", + "dialog.pattern_sketch_not_object": "Válasszon testeket vagy elemeket: a vázlat egyik sem. Ismételje a görbéit a vázlat saját Minta vagy Tükrözés parancsával, vagy húzza ki előbb.", "dialog.select": "↖ Kijelölés", "dialog.selected_count": "↖ {count} kijelölve", + "dialog.selection_constraint": "Kényszer {id}", + "dialog.selection_external_curve": "{sketch} · görbe {id}", "dialog.selection_guidance": "Válasszon ki egy bemenetet a módosításhoz. A kijelölt objektumokra kattintva eltávolíthatja őket; a Ctrl/Cmd-kattintás is váltja a kijelölést. Tekintse át az előnézetet, majd nyomja meg az OK gombot.", + "dialog.selection_midpoint": "Felezőpont · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step}/{total}: {input} kijelölése", "dialog.step": "Lépés", "document.changed_on_disk": "A(z) {name} megváltozott a lemezen", @@ -1380,26 +1432,244 @@ "from the rule": "a szabályból", "help.apache": "Apache 2.0 licenc", "help.appearance.assign": "A kijelölt testeknek, lapoknak vagy komponenseknek színt vagy anyagjellegű megjelenést ad, a tömegük megváltoztatása nélkül. Használja az alkatrészek megkülönböztetésére vagy egy felület előnézetéhez.", + "help.assembly.bom": "Felsorolja a terv vagy egy komponens alkatrészeit darabszámukkal, cikkszám szerint, és a listát CSV- vagy JSON-fájlba mentheti. Használja rendelési és összeszerelési alkatrészlistaként.", "help.attributions": "Forrásmegjelölések (ATTRIBUTION.md)", "help.build": "{version} verzió · commit: {commit} · készült: {date}", + "help.canvas.decal": "Képet helyez a modell egy sík lapjára, mint egy matricát. Használja címke, logó vagy nyomtatott minta megjelenítésére egy alkatrészen.", + "help.canvas.edit": "Módosít egy vásznat: a helyzetét, méretét, szögét, átlátszatlanságát, tükrözését, láthatóságát vagy nevét. A referenciakép és a fölé rajzolt vázlat egymáshoz igazítására használja.", + "help.canvas.insert": "PNG- vagy JPEG-képet helyez egy síkra vagy lapra átlátszó referenciaként. Használja fénykép vagy rajz átrajzolására egy vázlatban, a képet ismert méretre skálázva.", + "help.component.break_link": "Leválaszt egy kapcsolt komponenst a tervfájljáról, a testeit változatlanul meghagyva. Akkor használja, ha az alkatrésznek már nem kell követnie az eredeti fájl módosításait.", + "help.component.capture_position": "Megtartja a kézzel mozgatott alkatrészek helyzetét, így az lesz az alkatrészek új helye. Akkor használja, ha olyan alkatrészeket húzott a helyükre, amelyeket egyetlen csukló sem tart.", + "help.component.create": "Új, üres komponenst ad a tervhez az aktív komponensen belül, hacsak nem választ másik szülőt. Használja, hogy az összeállítás új alkatrésze saját helyet kapjon a testei és vázlatai számára.", "help.component.finish_edit": "Elmenti a helyben szerkesztett alkatrészt, visszatér az összeállításhoz, és frissíti azt az alkatrész alapján. Akkor használja, ha végzett a kapcsolt alkatrész módosításaival.", + "help.component.from_bodies": "Minden kijelölt testből külön komponenst készít, a test nevén. Használja, ha egy különálló testekből épített tervből olyan összeállítást szeretne, amelynek alkatrészei összekapcsolhatók és mozgathatók.", + "help.component.insert_design": "Beszúr egy másik mentett tervet a fájljához kapcsolt komponensként, a szilárd testeivel úgy, ahogy ott el vannak helyezve. Használja egy alkatrész újrafelhasználására egy összeállításban; a későbbi módosításokat a Kapcsolatok frissítése veszi át.", + "help.component.properties": "Megmutatja egy komponens térfogatát, tömegét, tömegközéppontját és tehetetlenségi nyomatékait a testei anyagai alapján. Használja egy összeállítás súlyának és egyensúlyának ellenőrzésére.", + "help.component.revert_position": "Visszateszi a kézzel mozgatott alkatrészeket oda, ahol voltak, elvetve a nem rögzített mozgatásokat. Használja egy összeállításban végzett próbamozgatások visszavonására.", + "help.component.update_links": "Újra beolvassa a kapcsolt tervfájlokat, és lecseréli a testeket, ahol megváltoztak. Használja, miután szerkesztett egy olyan alkatrészt, amelyet ez az összeállítás használ.", + "help.config.configure": "Paramétereket, elemeket, anyagokat vagy megjelenéseket ad a konfigurációs táblázathoz oszlopként. Használja egy terv változatainak elkészítésére, például egy alkatrész méretváltozataihoz.", + "help.config.preview": "Ellenőrzi, hogy a konfigurációs táblázat egy sora újraépíthető-e, a terv és az előzmények módosítása nélkül. Használja, mielőtt olyan változatra vált, amelyben nem biztos.", + "help.config.rules": "Megmutatja a konfigurációs táblázat szabályait, sorait és azt, hogy melyik sor az aktív. Használja annak megtekintésére, hogyan vannak beállítva egy terv változatai.", + "help.config.table": "Megjeleníti a konfigurációs táblázatot: változatonként egy sort, paraméterenként vagy elemenként egy oszlopot, és azt, hogy a terv még egyezik-e az aktív sorral. Használja egy terv változatainak áttekintésére.", "help.connect_note": "Indítsa újra az egyes asszisztenseket a SolidCraft szerver betöltéséhez. Minden fájlról .bak biztonsági másolat készült a módosítás előtt.", "help.connect_title": "AI-asszisztensek csatlakoztatása", + "help.construct.axis.edge": "Szerkesztőtengelyt hoz létre egy egyenes él vagy vázlatvonal mentén. Használja forgatás, körminta vagy csukló tengelyeként.", + "help.construct.axis.normal_to_face": "Szerkesztőtengelyt hoz létre egy ponton át, a laphoz merőlegesen. Használja olyan tengelyként, amely egyenesen kiáll egy felületből.", + "help.construct.axis.through_cylinder": "Szerkesztőtengelyt hoz létre egy henger-, kúp- vagy tóruszlap, illetve egy kör alakú él középpontján át. Használja elemek forgatására vagy mintázására egy kerek alkatrész körül.", + "help.construct.axis.two_planes": "Szerkesztőtengelyt hoz létre ott, ahol két sík vagy sík lap találkozik. Használja, ha a szükséges tengely a két lap közötti vonal.", + "help.construct.axis.two_points": "Szerkesztőtengelyt hoz létre két ponton, csúcson vagy vázlatponton át. Használja két ismert helyzet között húzódó tengelyhez.", + "help.construct.plane.along_path": "Szerkesztősíkot hoz létre egy élre vagy görbére merőlegesen, annak egy adott helyén. Használja söpréshez való profil vagy egy útvonal keresztmetszetének megrajzolására.", + "help.construct.plane.at_angle": "Szerkesztősíkot hoz létre, amely egy síktól vagy laptól egy tengely vagy él körül adott szöggel van elforgatva. Használja ferde vázlatokhoz, például szögben álló konzolhoz.", + "help.construct.plane.axis_point": "Szerkesztősíkot hoz létre, amely tartalmaz egy tengelyt és egy, a tengelyen kívül eső pontot. Válasszon egy origótengelyt vagy szerkesztőtengelyt, egy egyenes élt vagy vázlatvonalat, majd egy csúcsot, vázlatpontot vagy szerkesztőpontot. A tengelyen lévő pont nem határoz meg egyértelmű síkot.", + "help.construct.plane.midplane": "Szerkesztősíkot hoz létre két sík vagy sík lap között félúton, vagy, ha szögben találkoznak, felezve őket. Használja tükrözés szimmetriasíkjaként.", + "help.construct.plane.offset": "Szerkesztősíkot hoz létre egy síkkal vagy sík lappal párhuzamosan, adott távolságra vagy egy ponton át. Használja, hogy egy lap fölött meghatározott magasságban rajzoljon vázlatot.", + "help.construct.plane.perpendicular": "Szerkesztősíkot hoz létre, amely tartalmaz egy egyenest vagy élt, és merőleges egy síkra vagy lapra. Használja, hogy egy modellen egy él mentén függőlegesen álló vázlatot rajzoljon.", + "help.construct.plane.tangent": "Szerkesztősíkot hoz létre, amely egy pontban érint egy hengert, kúpot, gömböt vagy tórust. Használja egy kerek alkatrész oldalán való vázlatrajzoláshoz.", + "help.construct.plane.three_points": "Szerkesztősíkot hoz létre három ponton át. Használja olyan síkhoz, amelyet a modell pontjai határoznak meg, például három sarok.", + "help.construct.plane.two_edges": "Szerkesztősíkot hoz létre két olyan egyenes élen vagy vonalon át, amelyek egy síkban fekszenek. Használja egy alkatrészen átmenő síkhoz, például két szemközti élen át.", + "help.construct.point.along_path": "Szerkesztőpontot hoz létre egy él vagy görbe egy adott helyén. Használja referenciaként egy útvonal valamely pontján.", + "help.construct.point.center": "Szerkesztőpontot hoz létre egy kör alakú él, vázlatkör vagy -ív, gömb vagy tórusz középpontjában. Használja referenciaként furatokhoz, tengelyekhez és csuklókhoz.", + "help.construct.point.edge_plane": "Szerkesztőpontot hoz létre ott, ahol egy él vagy vonal áthalad egy síkon vagy sík lapon. Használja annak megjelölésére, hogy egy útvonal hol metsz egy síkot.", + "help.construct.point.three_planes": "Szerkesztőpontot hoz létre ott, ahol három sík vagy sík lap találkozik. Használja sarokreferenciaként akkor is, ha a modellnek ott nincs csúcsa.", + "help.construct.point.two_edges": "Szerkesztőpontot hoz létre ott, ahol két él vagy vonal találkozik, illetve ahol a legközelebb kerülnek egymáshoz. Használja referenciaként egy virtuális sarokban.", + "help.construct.point.vertex": "Szerkesztőpontot hoz létre egy csúcson vagy vázlatponton. Használja olyan referenciaként, amely megmarad akkor is, ha a körülötte lévő vázlat vagy test el van rejtve.", + "help.contact.check": "Felsorolja az érintkezési készletekben azokat az alkatrészpárokat, amelyek a jelenlegi helyzetükben áthatják egymást. Használja az ütközések megkeresésére, mielőtt csuklókat hajtana meg vagy mozgásvizsgálatot futtatna.", + "help.contact.create": "Két vagy több alkatrészt érintkezési készletbe csoportosít; a testeik nem hatolhatnak egymásba, miközben a csuklók mozognak. Használja olyan alkatrészekhez, amelyeknek érintkezéskor meg kell állniuk, például egy kar és az ütközője.", + "help.contact.disable_all": "Kikapcsolja az érintkezést, így a meghajtott csuklók és a mozgásvizsgálatok már nem állnak meg ott, ahol az alkatrészek érintkeznek. Használja az alkatrészek újbóli szabad mozgatásához, vagy egy nagy összeállítás gyors válaszkészségének megtartásához.", + "help.contact.edit": "Módosít egy érintkezési készletet: a benne lévő alkatrészeket, a nevét, vagy azt, hogy el van-e nyomva; a készletet törölni is tudja. Használja annak beállítására, mely alkatrészek ne hatolhassanak egymásba.", + "help.contact.enable_all": "Az összeállítás minden alkatrészét egyetlen érintkezési készletbe teszi, így a csuklók mozgása közben két alkatrész sem hatolhat egymásba. Használja egy egész mechanizmus gyors ellenőrzésére.", + "help.contact.enable_sets": "Bekapcsolja az érintkezést az Ön által megadott érintkezési készletekre, így a meghajtott csuklók és a mozgásvizsgálatok megállnak ott, ahol az alkatrészeik egymásba hatolnának. Használja a készletek visszakapcsolására az érintkezés kikapcsolása után.", + "help.contact.list": "Felsorolja a terv érintkezési készleteit, a bennük lévő alkatrészeket és azt, hogy be van-e kapcsolva az érintkezés. Használja annak ellenőrzésére, hogyan van beállítva az érintkezés, mielőtt az összeállítást meghajtja.", + "help.document.inspect": "Áttekintést ad a tervről: a komponenseiről, testeiről, vázlatairól, elemeiről és paramétereiről. Használja, hogy eligazodjon egy olyan tervben, amelyet nem Ön épített.", + "help.document.units": "Megváltoztatja azt a mértékegységet, amelyben a terv a hosszakat mutatja, például mm vagy hüvelyk. A geometria mérete nem változik; csak a megjelenítés és a mértékegység nélküli számok követik.", + "help.edit.checkpoint": "Megjegyzi a tervet, az aktív vázlatot és a visszavonási előzményeket a jelenlegi állapotukban. Használja, mielőtt valami kockázatosat próbál ki, amelyből később vissza szeretne térni.", + "help.edit.restore_checkpoint": "Visszatér egy ellenőrzőponthoz, a visszavonási előzményekkel együtt. Használja az ellenőrzőpont óta végzett összes művelet egyetlen lépésben való elvetésére.", + "help.explode.create": "Robbantott nézetet hoz létre, amely az alkatrészeket eltolja az összeállítás középpontjától, vagy az Ön által megadott mozgatásokkal. Használja annak bemutatására, hogyan áll össze egy összeállítás, útmutatókhoz vagy prezentációkhoz.", "help.face.delete": "Eltávolítja a kijelölt lapokat, és hagyja, hogy a szomszédos lapok bezárják a rést, vagy felületként nyitva hagyja a rést. Használja egy útban lévő lekerekített él, furat vagy dudor eltávolítására.", + "help.file.insert_mesh": "3MF-, STL-, OBJ-, PLY- vagy glTF-fájlt ad a tervhez hálótestekként egy új komponensben. Használja egy letöltött vagy szkennelt modell referenciaként a terv mellé helyezésére.", + "help.file.insert_step": "STEP-, IGES-, FreeCAD- vagy Rhino-fájlt ad a tervhez szilárd testekként egy új komponensben; egy összeállítás alkatrészei beágyazott komponensek lesznek. Használja beszállítók vagy más CAD-programok modelljeinek behozatalára.", + "help.file.save_mesh": "A testeket STL-, 3MF- vagy OBJ-hálóként menti, a görbült lapok Ön által választott simaságával. Használja alkatrészek 3D nyomtatásra vagy hálót olvasó programokhoz való előkészítésére.", + "help.file.send_to_slicer": "A kijelölt testeket 3MF-fájlként menti, és megnyitja a kiválasztott szeletelőben. Használja, hogy egyetlen lépésben jusson el a modelltől a nyomtatásig.", "help.font_details": "A felület az egui beépített betűtípusait használja (Ubuntu Light és Hack, az Ubuntu Font Licence és az MIT/Bitstream Vera licenc alatt; Noto Emoji és az emoji ikonbetűtípus, OFL és MIT alatt). A vázlatszöveg a Liberation Sans betűtípust használja (SIL OFL 1.1). A Crafting Apps opcionális betűtípuscsomagja, a craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1) nincs a SolidCraft-buildekbe csomagolva.", "help.fonts": "Betűtípusok", + "help.frame.member": "Profilt, például csövet vagy alumínium extrudált profilt helyez egy keretvázlat vonalai mentén, vonalanként egy szerkezeti elemet. Használja keretek, állványok és hegesztett szerkezetek építésére.", + "help.inspect.accessibility": "Megszínezi azokat a lapokat, amelyeket egy szerszám egy irányból elér, és azokat, amelyeket nem. Használja annak ellenőrzésére, hogy az alkatrész megmunkálható vagy önthető-e arról az oldalról.", + "help.inspect.center_of_mass": "Megmutatja a testek tömegközéppontját külön-külön és együtt, egyenletes sűrűség mellett. Használja az egyensúly ellenőrzésére és annak megállapítására, hol borul fel egy alkatrész.", + "help.inspect.colored_components": "Minden komponensnek külön ideiglenes színt ad, a megjelenések módosítása nélkül. Használja egy összeállítás alkatrészeinek első pillantásra való megkülönböztetésére.", + "help.inspect.compare": "Összehasonlít két testet, és megmutatja, hol van az egyiken olyan anyag, amely a másikon nincs, a térfogattal és az eltéréssel együtt. Használja egy módosított vagy importált alkatrész eredetivel való összevetésére.", + "help.inspect.continuity": "Ellenőrzi, milyen simán találkoznak a lapok az éleik mentén: réseket, töréseket vagy görbületugrásokat keres, és a varratokat beszínezi. Használja annak megkeresésére, hol nem csatlakoznak tisztán a felületek.", + "help.inspect.curvature_comb": "Fésűket rajzol görbék, élek vagy lapok mentén; a fogaik azt mutatják, mennyire hajlanak. Használja a lapos részek, törések és az egyenetlen görbület felismerésére.", + "help.inspect.curvature_map": "A lapokat aszerint színezi, mennyire görbülnek, pirossal ott, ahol kicsi a sugár. Használja a szűk helyek megkeresésére és egy felület simaságának megítélésére.", + "help.inspect.draft": "A lapokat a húzási irányhoz mért dőlésszögük szerint színezi, és megjelöli azokat, amelyeknek túl kicsi. Használja egy alkatrész ellenőrzésére öntés vagy fröccsöntés előtt.", + "help.inspect.environment_map": "Tükröző, tükörszerű felülettel jeleníti meg a modellt. Használja a felületek lefutásának megítélésére abból, ahogyan a tükröződések végigfutnak rajtuk.", + "help.inspect.interference": "Megkeresi az átfedő testeket, és minden átfedést a térfogatával együtt megmutat. Használja egy összeállítás ütköző alkatrészeinek ellenőrzésére.", + "help.inspect.isocurve": "Megrajzolja a lapok izoparametrikus görbéit, vagyis azt a rácsot, amelyre a felület épül. Használja annak megtekintésére, hogyan fut egy felület, és hol sűrűsödik össze.", + "help.inspect.measure": "Hosszakat, távolságokat, szögeket, területeket és sugarakat mér a kiválasztott elemek között, vagy testek térfogatát és tömegét. Használja méretek és hézagok ellenőrzésére.", + "help.inspect.minimum_radius": "Megkeresi a görbék, élek vagy lapok legkisebb görbületi sugarát, és azt, hogy hol van. Használja annak ellenőrzésére, hogy egy szerszám vagy fúvóka követni tudja-e az alakot.", + "help.inspect.section": "Egy sík mentén felvágja a nézetet, és sraffozza a vágott lapokat, a modell módosítása nélkül. Használja alkatrészek és összeállítások belsejének megtekintésére.", + "help.inspect.zebra": "Fekete-fehér csíkokat tükröz a modell lapjain. Használja a simaság megítélésére: az élnél megszakadó vagy megtörő csíkok rossz átmenetet jeleznek.", + "help.joint.as_built": "Összekapcsol két alkatrészt ott, ahol már vannak, egyiket sem mozgatva, és beállítja, hogyan mozoghatnak még. Használja olyan alkatrészekhez, amelyeket már a végleges helyükre tett.", + "help.joint.cam": "Egy forgó bütyköt kapcsol a követőhöz, így a követő elcsúszik vagy kileng, ahogy a bütyök körvonala elhalad alatta. Használja bütykökhöz, excenterekhez és szelephajtásokhoz.", + "help.joint.create": "Összekapcsol két alkatrészt a kiválasztott csuklóeredeteknél, és a másodikat a helyére mozgatja; a csukló típusa határozza meg, hogyan mozoghatnak még. Használja olyan összeállítás építésére, amelynek alkatrészei úgy mozognak, mint a valódi mechanizmus.", + "help.joint.drive": "Beállítja egy csukló szögét vagy távolságát, és vele együtt mozgatja az alkatrészeket a korlátain belül; a kapcsolt csuklók és a zárt hurkok követik. Használja annak ellenőrzésére, hogy a mechanizmus a tervezett módon mozog-e.", + "help.joint.gear": "Két forgó csuklót kapcsol egy áttétellel, így az egyik meghajtása elforgatja a másikat. Használja homlokfogaskerekekhez és belső fogazású kerekekhez; az áttétel az osztókör sugarából vagy a fogszámból adódik.", + "help.joint.limits": "Beállítja, meddig foroghat vagy csúszhat egy csukló, minimum- és maximumértékkel, vagy törli ezeket a korlátokat. Használja, hogy egy zsanér, csúszka vagy kar a valódi mozgástartományán belül maradjon.", + "help.joint.motion_link": "Két csuklót kapcsol össze egy aránnyal és egy eltolással, így az egyik meghajtása mozgatja a másikat. Használja olyan állandó összefüggéshez a csuklók között, amelyet a Fogaskerék, a Fogasléc és fogaskerék vagy a Csavar nem fed le.", + "help.joint.origin": "Elnevezett csuklóeredetet helyez egy alkatrészre: egy lap vagy kerek vég középpontjában, egy él közepén, egy sarokban vagy egy pontban. Használja annak előkészítésére, hol kapcsolódjanak a csuklók; a lapon kijelölt eredet követi a lapot, ha az alkatrész mérete változik.", + "help.joint.rack_pinion": "Egy forgó fogaskereket kapcsol egy csúszó fogaslécre, így a fogasléc annyit mozdul, amekkora osztókör-hosszon a fogaskerék legördül. Használja fogaslécmeghajtásokhoz, kormányzáshoz és lineáris szánokhoz.", + "help.joint.reach": "Egy alkatrész egy pontját a cél felé mozgatja a láncán lévő csuklók módosításával, a korlátaikon belül. Használja egy mechanizmus beállítására aszerint, hová kell érnie a végének, például egy robotkar hegyének.", + "help.joint.rigid_group": "A kijelölt alkatrészeket úgy, ahogy vannak, összezárja, így egyként mozognak. Használja olyan alkatrészekhez, amelyek összetartoznak, és nincs köztük mozgás.", + "help.joint.screw": "Összekapcsolja a forgást és a csúszást egy menetemelkedéssel, így minden fordulat ennyivel halad előre. Használja vezetőorsókhoz, csavarokhoz és menetes orsókhoz.", + "help.library.apply": "Anyagot vagy megjelenést alkalmaz egy helyi könyvtárfájlból testekre, lapokra vagy komponensekre. Használja egy másik tervből elmentett anyagok újrafelhasználására.", + "help.library.export": "Elmenti a terv anyagait és megjelenéseit egy könyvtárfájlba. Használja a megosztásukra vagy más tervekben való újrafelhasználásukra.", + "help.library.inspect": "Ellenőriz egy könyvtárfájlt, és felsorolja az anyagait és megjelenéseit, a terv módosítása nélkül. Használja annak megtekintésére, mit tartalmaz egy könyvtár, mielőtt alkalmazza.", "help.licences": "Licencek", "help.material.assign": "Megadja, miből készültek a kijelölt testek, például acélból, alumíniumból vagy ABS-ből. Használja, hogy a tömeg és a súly megegyezzen a valódi alkatrészével.", + "help.material.properties.validate": "Ellenőrzi egy anyagadatlap számainak következetességét és a hiányzó értékeket. Használja, mielőtt az adatokra támaszkodik a tömeg vagy a merevség számításánál.", + "help.mesh.convert": "Egy hálótestet, például egy STL-t szerkeszthető szilárd testként épít újra, sík és hengeres lapokkal. Használja importált gépalkatrészek módosítására úgy, mintha modellezett testek lennének.", "help.mit": "MIT licenc", + "help.motion.study": "Csuklóértékeket állít be egy idővonal lépésein, és animációként lejátssza őket. Használja egy mechanizmus mozgásának végignézésére egy sorozaton át, és közben a hézagok ellenőrzésére.", + "help.motion.trace": "Követi azt az utat, amelyet egy alkatrész egy pontja bejár, miközben a mozgásvizsgálat lejátszódik vagy egy csuklót meghajtanak, és a megerősítéskor 3D vázlatgörbeként megtartja. Használja annak megtekintésére, hová ér el egy mechanizmus, vagy az útvonalára építeni.", "help.notice": "NOTICE", + "help.occurrence.ground": "Egy alkatrészt a helyén rögzít, vagy újra felold, így a csuklók a többi alkatrészt mozgatják körülötte. Használja a vázhoz vagy alaphoz, amelyre az összeállítás többi része épül.", "help.occurrence.move": "Az összeállítás egy alkatrészét csak a csuklói által megengedett szabadságfokok mentén mozgatja. Jelölje ki az alkatrész egy lapját, majd húzza az egyik elérhető nyilat vagy ívet.", "help.parameters.change": "Megnyitja a terv méreteit vezérlő elnevezett értékek és kifejezések táblázatát. Használja egy méret egy helyen való módosítására, hogy az azt használó összes elem kövesse.", + "help.parameters.export": "A terv paramétereit CSV- vagy JSON-fájlba menti. Használja táblázatkezelőben való szerkesztésükre, vagy másik tervbe való átvitelükre.", + "help.parameters.graph": "Megmutatja, mely paraméterek és elemek mely másokat használják, valamint a köztük lévő hurkokat vagy hibákat. Használja annak megtekintésére, mit érint egy paraméter módosítása.", + "help.parameters.import": "CSV- vagy JSON-fájlból olvas be paramétereket a tervbe, vagy mindet, vagy egyet sem. Használja értékek táblázatkezelőből vagy másik tervből való behozatalára.", + "help.parameters.move": "Egy felhasználói paramétert a listában egy másik elé vagy mögé helyez. Használja az összetartozó paraméterek együtt tartására.", + "help.parts.fastener": "Szabványos csavart, anyát, alátétet, csapot vagy csapágyat ad hozzá a kiválasztott méretben. Furatra helyezve csuklóval illeszkedik a furatba, így nem kell magának modelleznie a kötőelemeket.", + "help.parts.insert": "Szabványos alkatrészt szúr be a kiválasztott családban, méretben és hosszban. Egy furat peremére vagy falára helyezve merev csuklóval illeszkedik a furathoz.", + "help.parts.library": "Megnyitja a szabványos alkatrészeket: csavarokat, anyákat, alátéteket, szárnélküli csavarokat, illesztőcsapokat és csapágyakat szabványos méretekben. Használja szabványos alkatrész hozzáadására ahelyett, hogy maga modellezné.", + "help.parts.resize": "Megváltoztatja egy beszúrt szabványos alkatrész méretét vagy hosszát, és újraépíti; a csuklói a helyén tartják. Használja, ha egy csavar túl hosszúnak bizonyul, vagy egy furathoz másik méret kell.", + "help.plastic.assign_rule": "Műanyag szabályt rendel testekhez, így a műanyag elemeik ennek dőlését és hézagát veszik alapértelmezettnek. Használja egy öntött alkatrész egyszeri beállítására az összes elemére.", + "help.plastic.boss": "Csavardudort ad egy lapra: oszlopot opcionális furattal, dőléssel, tövi lekerekítéssel és támasztó bordákkal. Használja csavarpontokhoz öntött vagy nyomtatott házakban.", + "help.plastic.lip": "Peremet vagy hozzá illő hornyot ad egy héjazott test pereme mentén. Használja, hogy két házfél egymáson pozicionálódjon, és szorosan záródjon.", + "help.plastic.manage_rules": "Műanyag szabályokat hoz létre és szerkeszt: anyag, falvastagság, sugarak, hézag és dőlés. Használja őket egy öntött alkatrész elemeinek egységesen tartására.", + "help.plastic.rest": "Támaszt ad egy lapra: kerek vagy téglalap alakú, tömör vagy üreges párnát dőléssel. Használja alátámasztásként vagy távtartóként egy öntött házban.", + "help.plastic.snap_fit": "Pattintós illesztésű kampót ad egy lapra, megadott hosszal, vastagsággal és reteszeléssel. Használja alkatrészek csavar nélküli összepattintására.", "help.pointcloud.insert": "PLY, XYZ vagy PTS szkennelést szúr be pontfelhőként a modell mellé. Használja referenciaként, amikor mért adatokból épít modellt.", + "help.sheet.convert": "Egyenletes vastagságú lemezt vagy héjazott testet lemeztestté alakít, a kiválasztott éleken hajlításokkal. Használja egy meglévő alkatrész kiteríthetővé tételére.", + "help.sheet.export_bend_table": "Egy lemeztest hajlítási táblázatát CSV- vagy JSON-fájlba menti: szögeket, sugarakat és a hajlítások helyzetét a kiterített állapotban. Használja a lemezhajlító géphez vagy a műhelynek.", + "help.sheet.export_dxf": "A lapmintát DXF-fájlba menti, körvonalakkal, hajlítási vonalakkal és opcionális hajlítási megjegyzésekkel. Használja lézeres, plazma- vagy vízsugaras vágáshoz.", + "help.sheet.flange": "Peremet ad hozzá: alaplemezt egy vázlatból, falat egy nyitott vázlatkontúr mentén, vagy hajlított falat a lemez élein. Használja lemezalkatrészek felépítésére.", + "help.sheet.flat_pattern": "Létrehozza egy lemeztest lapmintáját a méretével, kivágásaival és hajlítási vonalaival. Használja a kiterített darab ellenőrzésére a kivágás előtt.", + "help.sheet.fold": "Meghajlít egy lemezt egy vázlatvonal mentén adott szöggel és sugárral. Használja egy sík lemez behajtására, miután kivágásokat készített rajta.", + "help.sheet.hem": "Egy lemezélt visszahajt önmagára. Használja biztonságos, merev élekhez, éles sorják nélkül.", + "help.sheet.manage_rules": "Lemezszabályokat hoz létre és szerkeszt: vastagság, hajlítási sugár, K-tényező, kiengedések és rések. Használja őket a műhelye anyagaihoz és szerszámaihoz igazítására.", + "help.sheet.path_flange": "Peremek láncát adja egy lemezél mentén, egy nyitott vázlatvonal-lánc nyomán. Használja U vagy Z alakú profilokhoz egyetlen lépésben.", + "help.sheet.perforate": "Furatmezőt ad a teljes sík lemezre, eltolt vagy négyzetes mintában. Használja szellőzőnyílásokhoz, rácsokhoz és könnyebb panelekhez.", + "help.sheet.refold": "Egy kiterített lemeztestet visszahajt. Használja, miután elemeket adott a sík lemezhez.", + "help.sheet.unfold": "Kiterít egy lemeztest összes hajlítását. Használja olyan furatok vagy vágások hozzáadásához, amelyeknek át kell menniük egy hajlításon, majd az Újrahajlítással hajtsa vissza.", + "help.sketch.arc.center_point": "Körívet rajzol egy középpont körül, egy kezdőponttól egy végpontig. Használja, ha az ív középpontja ismert, például egy furat vagy egy forgáspont körüli sugárhoz.", + "help.sketch.arc.tangent": "Olyan ívet rajzol, amely egy vonal vagy ív végén indul, és érintőlegesen folytatódik. Használja a lánc folytatására sima hajlattal sarok helyett.", + "help.sketch.arc.three_point": "Ívet rajzol egy kezdőponttól egy végpontig egy harmadik ponton át. Használja, ha az ívnek adott pontokon kell áthaladnia, nem pedig egy ismert középpont körül futnia.", + "help.sketch.arc3d": "Pontos körívet rajzol a térben három ponton át, bekapcsolt 3D vázlattal. Használja útvonalak és vezérgörbék hajlataihoz, amelyek elhagyják a vázlatsíkot.", + "help.sketch.auto_constrain": "Hozzáadja azokat a kényszereket, amelyek a vázlatban már majdnem megvannak, például vízszintest, párhuzamost vagy egybeesőt, majd addig méretezi, amíg teljesen kényszerezett nem lesz. Használja egy hozzávetőlegesen megrajzolt vázlat egy lépésben való rögzítésére.", + "help.sketch.auto_constrain_from_datum": "Úgy működik, mint az Automatikus kényszerezés, de a helyzeteket az origó helyett egy Ön által kiválasztott viszonyítási pontból méri. Használja, ha az alkatrész egyetlen referenciapontból van kiosztva, például egy sarokból vagy egy furatból.", + "help.sketch.blend_curve": "Két görbe végét egy sima spline-nal köti össze, amely mindkettőt érinti, kívánság szerint görbületfolytonosan is. Használja görbék közötti rés áthidalására törés nélkül.", + "help.sketch.break": "Darabokra vágja a görbét ott, ahol más görbék keresztezik, vagy a rajta elhelyezett pontoknál. Használja, ha a görbe egy részének saját kényszerre van szüksége, vagy külön kell törölni.", + "help.sketch.cancel": "Elhagyja a vázlatot, és elvet mindent, ami a létrehozása vagy szerkesztésre való megnyitása óta megváltozott. A Visszavonás visszahozza a módosításokat.", + "help.sketch.centerline": "Vonalakat vált normál vonal és középvonal között; a középvonalak olyan tengelyek, amelyeket a profilok kihagynak. Használja a középvonalat forgatás, tükrözés vagy szimmetriakényszer tengelyeként.", + "help.sketch.chamfer.distance_angle": "Letöri a két vonal közötti sarkot, az első vonal menti távolsággal és egy szöggel megadva. Használja, ha a rajz a letörést hosszal és szöggel adja meg, például 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Letöri a két vonal közötti sarkot úgy, hogy mindkét vonal mentén ugyanannyit vesz vissza. Használja a körvonalak szokásos 45°-os letöréséhez.", + "help.sketch.chamfer.two_distance": "Letöri a két vonal közötti sarkot, mindkét vonal mentén külön távolsággal megadva. Használja a nem 45°-os, két hosszal megadott letörésekhez.", + "help.sketch.circle.center": "Kört rajzol a középpontjából és az átmérőjéből. Használja furatokhoz, dudorokhoz és más kerek elemekhez, amelyeknek ismert a középpontja.", + "help.sketch.circle.three_point": "Kört rajzol három ponton át. Használja, ha a körnek adott pontokon kell áthaladnia, például meglévő geometria pontjain.", + "help.sketch.circle.three_tangent": "Olyan kört rajzol, amely három vonalat, kört vagy ívet érint. Használja, hogy egy kört három görbe közötti térbe illesszen, például egy háromszög beírt körét.", + "help.sketch.circle.two_point": "Kört rajzol az átmérője két végpontjából. Használja, ha a kör szélének pontjai ismertek, nem a középpontja.", + "help.sketch.circle.two_tangent": "Adott méretű kört rajzol, amely két vonalat, kört vagy ívet érint. Használja két görbe közötti állandó sugarú lekerekítéshez.", + "help.sketch.conic": "Kúpgörbét rajzol két végpont között, amelyet egy csúcspont és egy ró (ρ) érték alakít. Használja olyan sima átmenetekhez, amelyek teltségét hangolni szeretné, a lapostól a csaknem éles sarokig.", + "help.sketch.constrainer": "Alkalmazza azt a kényszert, amely egy vagy két kijelölt görbénél már majdnem fennáll, például vízszintes, párhuzamos, érintő vagy egyenlő. Használja egy kézzel rajzolt vázlat rendbetételére, egyszerre egy összefüggéssel.", + "help.sketch.constraint.coincident": "Egy pontot egy másik pontra, görbére vagy vázlattengelyre illeszt. Használja egy profil réseinek lezárására, vagy egy pont vonalra helyezésére.", + "help.sketch.constraint.collinear": "Két vonalat egy egyenesre illeszt. Használja megszakított élek egy vonalba hozására, például egy bevágás két oldalán.", + "help.sketch.constraint.concentric": "Két körnek vagy ívnek ugyanazt a középpontot adja. Használja gyűrűkhöz, süllyesztett furatokhoz és vállas tengelyekhez.", + "help.sketch.constraint.curvature": "Azt éri el, hogy a végpontban találkozó két görbe ugyanazzal a görbülettel folytatódjon (G2). Használja ott, ahol az érintős csatlakozás nem elég sima, például látható felületeken.", + "help.sketch.constraint.equal": "A vonalakat azonos hosszúságúvá, a köröket és íveket azonos sugarúvá teszi. Használja, hogy egy méret több egyező elemet vezéreljen.", + "help.sketch.constraint.fix": "Pontokat vagy görbéket rögzít a helyükön, vagy újra felold. Használja olyan geometriához, amelynek nem szabad elmozdulnia a vázlat húzásakor vagy megoldásakor.", + "help.sketch.constraint.horizontal_vertical": "Egy vonalat, vagy két pont közötti vonalat vízszintessé vagy függőlegessé tesz, amelyikhez közelebb áll. Használja egy körvonal vázlattengelyekhez igazítására.", + "help.sketch.constraint.midpoint": "Egy pontot egy vonal közepére helyez, vagy két vonal felezőpontját egybeejti. Használja geometria egy élre való középre igazítására.", + "help.sketch.constraint.parallel": "Két vonalat párhuzamossá tesz. Használja olyan oldalakhoz, amelyeknek párhuzamosnak kell maradniuk, amikor más méretek változnak.", + "help.sketch.constraint.perpendicular": "Két vonalat derékszögben találkoztat. Használja derékszögű sarkokhoz olyan vonalak között, amelyek nem a vázlattengelyeken vannak.", + "help.sketch.constraint.polygon": "Egy zárt vonalláncot szabályos sokszöggé tesz: egyenlő oldalak, minden sarok egy körön. Használja egy kézzel rajzolt sokszög szabályossá tételére és olyannak megtartására.", + "help.sketch.constraint.symmetry": "Két pontot vagy görbét egymás tükörképévé tesz egy vonalra vagy egy pontra nézve. Használja, hogy egy profil szimmetrikus maradjon, amikor az egyik oldalát módosítja.", + "help.sketch.constraint.tangent": "Két görbét érintőlegesen illeszt egymáshoz, például egy vonalat és egy ívet. Használja sima csatlakozásokhoz törés nélkül.", + "help.sketch.construction": "A görbéket normál geometria és szerkesztőgeometria között váltja; a profilok a szerkesztőgeometriát kihagyják. Használja a szerkesztőgörbéket segédvonalként a kiosztáshoz, referenciákhoz és méretekhez.", + "help.sketch.construction_line": "Végtelen szerkesztőegyenest hoz létre két ponton át. Használja a vázlat megtervezéséhez a profilok szétvágása nélkül.", + "help.sketch.construction_line.angle": "Végtelen szerkesztőegyenest hoz létre a vázlat X tengelyéhez képest adott szögben. Válassza ki a pontot, és adja meg a szöget, vagy válassza ki az irányát.", + "help.sketch.construction_line.bisector": "Válasszon ki két egymást metsző egyenes vázlatvonalat, majd bármelyik szögfelezőt. Az eredmény követi a forrásvonalait.", + "help.sketch.construction_line.horizontal": "Végtelen vízszintes szerkesztőegyenest hoz létre egy ponton át. Vízszintes kényszere a későbbi módosítások után is megmarad.", + "help.sketch.construction_line.parallel": "Válasszon ki egy egyenes vázlatvonalat, majd helyezzen el egy vele párhuzamos, végtelen szerkesztőegyenest. Másik referencia kiválasztásához kattintson jobb gombbal.", + "help.sketch.construction_line.perpendicular": "Válasszon ki egy egyenes vázlatvonalat, majd helyezzen el egy rá merőleges, végtelen szerkesztőegyenest. Másik referencia kiválasztásához kattintson jobb gombbal.", + "help.sketch.construction_line.tangent_at": "Érintőt hoz létre egy kör vagy körív pontjában, illetve egy nyitott spline vagy kúpgörbe végpontjában. Válassza ki a görbét, majd az érintési pontját.", + "help.sketch.construction_line.tangent_external": "Válasszon ki egy kört vagy körívet, majd egy külső pontot és egy érintőmegoldást. Az előnézetek csak a megrajzolt íven lévő érintési pontokat mutatják.", + "help.sketch.construction_line.tangent_two": "Válasszon ki két kört vagy körívet, majd az előnézetben válasszon közös érintőt. Az érintési pontoknak a megrajzolt görbéken kell lenniük.", + "help.sketch.construction_line.vertical": "Végtelen függőleges szerkesztőegyenest hoz létre egy ponton át. Függőleges kényszere a későbbi módosítások után is megmarad.", + "help.sketch.copy": "Másolja a kijelölt vázlatgörbéket és -pontokat a közöttük lévő kényszerekkel és méretekkel együtt. Illessze be őket ebbe a vázlatba vagy egy másikba.", + "help.sketch.create": "Új 2D vázlatot kezd egy síkon vagy a modell egy sík lapján. Minden kihúzás, forgatás és söprés vázlattal kezdődik.", + "help.sketch.cut": "Másolja a kijelölt vázlatgeometriát, és törli a vázlatból, egyetlen visszavonási lépésben. Illessze be máshová ebben a vázlatban vagy egy másikba.", + "help.sketch.dimension": "Vezérlő méretet ad hozzá: hosszt, távolságot, szöget, sugarat vagy átmérőt, attól függően, mit jelöl ki. Írjon be egy értéket vagy egy paraméternevet, és a vázlat követi.", + "help.sketch.edit": "Megnyit egy meglévő vázlatot szerkesztésre. A rá épülő elemek frissülnek, amikor befejezi a vázlatot.", + "help.sketch.ellipse": "Ellipszist rajzol a középpontjából, a nagytengelye végpontjából és a kistengelye felőli egy pontból. Használja ovális nyílásokhoz, bütykökhöz és más elnyújtott kerek alakzatokhoz.", "help.sketch.equation_curve": "Görbét rajzol képletekből: x(t) és y(t), vagy y = f(x) alapján, egy tartományon. A képletek paramétereket is használhatnak, és a görbe követi őket: használja szinuszhullámhoz, spirálhoz vagy fogaskerékfog evolvenséhez.", + "help.sketch.extend": "Meghosszabbít egy vonalat vagy ívet a legközelebbi, útjába eső görbéig, vagy két görbét addig növeszt, amíg találkoznak. Használja egy profil réseinek lezárására vágás vagy szerkesztés után.", + "help.sketch.fillet": "Lekerekíti a két vonal vagy ív találkozásánál lévő sarkot egy adott sugarú ívvel. Az együtt lekerekített több sarok egy sugáron osztozik.", + "help.sketch.finish": "Elhagyja a vázlatot, és visszatér a modellhez. A zárt profiljai ezután készen állnak a Kihúzásra, a Forgatásra és más elemekre.", + "help.sketch.finish_auto_constrain": "Lefuttatja az Automatikus kényszerezést a vázlaton, majd befejezi. Használja, hogy a vázlat egyetlen lépésben teljesen kényszerezett állapotban maradjon.", + "help.sketch.fit_curves_to_section": "Elvág egy háló- vagy szilárd testet a vázlatsíkkal, és vonalakat és íveket illeszt a metszethez. Használja egy szkennelt vagy importált alkatrész szerkeszthető vázlatként való újjáépítésére.", + "help.sketch.include_3d": "A modell éleit, csúcsait és más vázlatok görbéit hozza be ebbe a vázlatba kapcsolt referenciaként, a síkján kívül esőket arra lelapítva. Használja olyan geometriára való építéshez, amely nem a vázlatsíkban fekszik.", + "help.sketch.infinite": "A vonalakat normál vonal és végtelen szerkesztőegyenes között váltja, amely az egész nézeten átfut. Használja őket kiosztási referenciaként, amely sosem ér véget túl korán.", + "help.sketch.insert_dxf": "Beolvassa egy DXF-rajz görbéit egy vázlatba, az Ön által megadott léptékkel, elforgatással és helyen. Használja egy másik programból származó 2D rajzra való építéshez, például lézerrel vágott körvonalhoz.", + "help.sketch.insert_svg": "Beolvassa egy SVG-rajz útvonalait egy vázlatba, az Ön által megadott léptékkel, elforgatással és helyen. Használja egy logó vagy vektoros körvonal kihúzható görbékké alakítására.", + "help.sketch.inspect": "Jelentést nyit a megnyitott vázlatról: hány szabadságfok maradt, és teljesen kényszerezett-e. Használja annak kiderítésére, mi mozdul még, mielőtt befejezi a vázlatot.", + "help.sketch.intersect": "Hozzáadja azokat a görbéket vagy pontokat, ahol testek, lapok, élek vagy más vázlatok metszik a vázlatsíkot. Kapcsoltak maradnak, és követik a modellt, ha az megváltozik.", + "help.sketch.intersection_curve": "3D görbéket hoz létre ott, ahol két test vagy lap találkozik, hozzájuk kapcsolva. Használja őket útvonalként vagy vezérgörbeként, amely követi a modellt.", + "help.sketch.isoparametric_curve": "3D görbét hoz létre egy lap U vagy V iránya mentén egy kiválasztott ponton át, a laphoz kapcsolva. Használja útvonalként vagy osztóvonalként, amely követi a felületet.", + "help.sketch.line": "Összefüggő vonalakat rajzol pontról pontra, nyitott láncként vagy zárt körvonalként. Ez a legtöbb profil alapeszköze.", + "help.sketch.line.midpoint": "Vonalat rajzol a felezőpontjától az egyik végéig, a másik véget tükrözve. Használja egy pontra középen álló vonalakhoz, például szimmetrikus élhez.", + "help.sketch.line3d": "Összefüggő egyeneseket rajzol a térben lévő pontok között, bekapcsolt 3D vázlattal. Használja útvonalakhoz és keretekhez, amelyek elhagyják a vázlatsíkot.", + "help.sketch.mirror": "Tükrözi a vázlatgörbéket és -pontokat egy vonalra vagy tengelyre, és szimmetriakényszereket ad hozzá. Használja egy szimmetrikus profil felének megrajzolására és kiegészítésére.", + "help.sketch.move": "Mozgatja vagy forgatja a vázlatgörbéket és -pontokat, vagy azok másolatát. Használja a geometria áthelyezésére, miközben az megtartja az alakját és a kényszereit.", + "help.sketch.offset": "Másolatot készít egy görbelánc adott távolságban, az egyik vagy mindkét oldalon. Használja falakhoz, körvonalakhoz és hézagokhoz; a távolság szerkeszthető méret marad.", + "help.sketch.paste": "Beilleszti a másolt vagy kivágott vázlatgeometriát az aktív vázlatba. Helyezze el egy pontban, vagy tolja el egy eltolással.", + "help.sketch.pattern.circular": "Másolja a vázlatgeometriát egy középpont körül, teljes körön vagy adott szögön át. Használja csavarkörökhöz, küllőkhöz és fogakhoz.", + "help.sketch.pattern.rectangular": "Másolja a vázlatgeometriát sorokban és oszlopokban, megadott térközökkel. Használja furatok, hornyok vagy szellőzőnyílások rácsaihoz.", + "help.sketch.point": "Vázlatpontot helyez el. Használja referenciaként méretekhez, kényszerekhez, furatközéppontokhoz vagy későbbi elemekhez.", + "help.sketch.point3d": "Pontot helyez el a térben, bekapcsolt 3D vázlattal. Használja referenciaként 3D görbékhez és útvonalakhoz.", + "help.sketch.polygon.circumscribed": "Szabályos sokszöget rajzol egy kör köré, a középponttól egy oldal közepéig mérve. Használja, ha a kulcsnyílás ismert, például egy hatlapú anyánál.", + "help.sketch.polygon.edge": "Szabályos sokszöget rajzol egy oldal két végpontjából. Használja, ha egy oldal hossza és helyzete ismert.", + "help.sketch.polygon.inscribed": "Szabályos sokszöget rajzol egy körbe, a középponttól egy sarokig mérve. Használja, ha a sarkok közötti méret ismert.", + "help.sketch.project": "A modell éleit, lapjait, csúcsait és más vázlatok görbéit hozza be ebbe a vázlatba, a síkjára vetítve. Kapcsoltak maradnak, és követik a modellt, ha az megváltozik.", + "help.sketch.project_to_surface": "Más vázlatok görbéit ennek a vázlatnak a normálisa mentén egy lapra vetíti, kapcsolt 3D görbékként. Használja logó, osztóvonal vagy útvonal görbült felületre helyezésére.", + "help.sketch.rectangle.center": "Téglalapot rajzol a középpontjából és egy sarkából. Használja egy pontra, például az origóra középen álló körvonalakhoz.", + "help.sketch.rectangle.rounded": "Téglalapot rajzol, amelynek mind a négy sarka egy sugárral le van kerekítve. Használja lemezekhez, fedelekhez és lekerekített sarkú nyílásokhoz.", + "help.sketch.rectangle.three_point": "Téglalapot rajzol egy élből és a szemközti oldal egy pontjából. Használja a vázlattengelyekhez képest szögben álló téglalapokhoz.", + "help.sketch.rectangle.two_point": "Téglalapot rajzol két szemközti sarokból. Használja lemezek, tömbök és zsebek körvonalaihoz.", + "help.sketch.scale": "Átléptékezi a vázlatgörbéket és -pontokat egy tényezővel egy alappont körül. Használja egy vázlat egy részének átméretezésére újrarajzolás nélkül.", + "help.sketch.slot.arc_center": "Adott szélességű íves hornyot rajzol egy ív mentén, amelyet a középpontja, a kezdő- és a végpontja határoz meg. Használja forgáspont körüli állítóhornyokhoz.", + "help.sketch.slot.arc_three_point": "Adott szélességű íves hornyot rajzol egy három ponton átmenő ív mentén. Használja, ha a horony pályájának adott pontokon kell áthaladnia.", + "help.sketch.slot.center_point": "Adott szélességű egyenes hornyot rajzol a középpontjától az egyik végív középpontjáig. Használja egy pontra középen álló hornyokhoz.", + "help.sketch.slot.center_to_center": "Adott szélességű egyenes hornyot rajzol a két végívének középpontja között. Használja a középponttól középpontig méretezett hornyokhoz, például csavarok állítóhornyaihoz.", + "help.sketch.slot.overall": "Adott szélességű egyenes hornyot rajzol az egyik külső végétől a másikig. Használja, ha a horony teljes hossza a lényeg.", + "help.sketch.spline.control_point": "Harmadfokú spline-t rajzol, amelyet olyan vezérlőpontok alakítanak, amelyeken nem halad át. Használja sima, folyó görbékhez, amelyeket a pontok mozgatásával alakít.", + "help.sketch.spline.control_point_5": "5. fokú spline-t rajzol, amelyet vezérlőpontok alakítanak. Használja ott, ahol a görbéknek simább görbülettel kell csatlakozniuk, például látható, formatervezett felületeken.", + "help.sketch.spline.fit_point": "Sima spline-t rajzol, amely áthalad minden elhelyezett ponton, nyitottat vagy zártat. Használja egy alak ismert pontokon át való követésére.", + "help.sketch.spline3d": "Sima görbét rajzol a térben pontokon át, bekapcsolt 3D vázlattal. Használja söprési útvonalakhoz és kábelvezetésekhez, amelyek elhagyják a vázlatsíkot.", + "help.sketch.spun_profile": "A vázlatsíkban létrehozza azt a körvonalat, amelyet egy test súrol, amikor egy tengely körül forog. Használja egy esztergált alkatrész körvonalának megszerzésére forgatáshoz vagy rajzhoz.", + "help.sketch.text": "Szöveget ír a vázlatba a választott betűtípussal, magassággal és szöggel; a szavai követhetik a paramétereket. Húzza ki vagy domborítsa címkékhez és feliratokhoz.", + "help.sketch.transform": "Egy lépésben átméretezi, elforgatja és mozgatja a vázlatgeometriát egy középpont körül. Használja egy kijelölés egyszerre történő áthelyezésére és átméretezésére.", + "help.sketch.trim": "Eltávolítja a görbének a kattintás helye körüli legközelebbi keresztezések közötti darabját. Használja az átfedő vonalak zárt profillá tisztítására.", "help.solid.align": "Úgy mozgatja a kijelölt testeket, hogy egy rajtuk lévő pont, lap vagy sík találkozzon máshol lévő ponttal, lappal vagy síkkal. Használja egy alkatrész másikhoz illesztésére az eltolás lemérése nélkül.", + "help.solid.boundary_fill": "Szilárd testeket készít az egymást átfedő szerszámtestek által bezárt tartományokból, csak a kijelölt tartományokat kitöltve. Használja olyan alak építésére, amelyet több test együtt határol.", + "help.solid.bounding_solid": "Dobozt hoz létre, amely körbeveszi a kijelölt testeket, opcionális ráhagyással. Használja egy alkatrész teljes méretének megtekintésére, vagy alapanyagként, amelyből megmunkálják.", + "help.solid.box": "Dobozt hoz létre hosszból, szélességből és magasságból, egy sarokpontból vagy egy pontra középre. Használja gyors tömbhöz, helyőrzőhöz vagy olyan testhez, amelybe elemeket vág.", "help.solid.chamfer": "A kijelölt éleket lapos letöréssel vágja le a megadott távolságban. Használja éles élek tompítására, illetve egy csap vagy csavar bevezetésének megkönnyítésére.", + "help.solid.coil": "Csavarvonalú testet, például rugót hoz létre átmérőből, menetszámból, magasságból vagy emelkedésből, valamint kerek vagy négyzetes keresztmetszetből. Használja rugókhoz, tekercsekhez és csavarvonalú bordákhoz.", "help.solid.combine": "Egyesíti a testeket, kivágja őket egy céltestből, vagy csak a közös térfogatukat tartja meg, és megtarthatja a szerszámtesteket. Használja alkatrészek összeolvasztására, egy alak másikkal való kivágására, vagy két test átfedésének megkeresésére.", + "help.solid.cone": "Kúpot hoz létre egy alapkörből és egy magasságból, vagy csonkakúpot, ha a tetejének is van sugara. Használja kúpos szűkületekhez, tölcsérekhez, süllyesztésekhez és hegyekhez.", + "help.solid.cylinder": "Hengert hoz létre sugárból vagy átmérőből és magasságból, egy ponton állva egy tengely mentén. Használja tengelyekhez, csapokhoz, dudorokhoz és kerek előgyártmányokhoz.", "help.solid.draft": "A kijelölt lapokat a megadott szöggel megdönti, a semleges síktól mérve. Használja fröccsöntött vagy öntött alkatrészeken, hogy kicsússzanak a formából.", + "help.solid.emboss": "A vázlatprofilokat, például szöveget vagy logót kiemel egy lapból, vagy belesüllyeszt. Használja feliratokhoz, címkékhez és jelölésekhez sík vagy kerek lapokon.", "help.solid.extrude": "Egy vázlatprofilt a megadott távolságon át 3D-ssé húz, anyagot adva hozzá vagy eltávolítva. Használja egy lapos körvonal tömbbé, dudorrá vagy mélyedéssé alakítására.", "help.solid.fillet": "A kijelölt éleket a megadott sugarú, sima körív alakú átmenettel lekerekíti. Használja az éles élek lágyítására szilárdság, kényelem vagy megjelenés érdekében.", "help.solid.hole": "A megadott átmérőjű kerek furatot fúr egy lap kiválasztott pontján. Használja csavarok átbújtatására, csapokhoz és más egyszerű kerek nyílásokhoz.", @@ -1408,20 +1678,62 @@ "help.solid.move": "A kijelölt testeket vagy azok másolatát mozgatja vagy forgatja a megadott távolsággal és szöggel. Egy test áthelyezésére vagy egy második példány más helyen való elkészítésére használja.", "help.solid.offset_face": "A kijelölt lapokat a megadott távolsággal befelé vagy kifelé tolja, a környező lapok követik. Fal vastagabbá, zseb mélyebbé vagy dudor magasabbá tételére használja a vázlat szerkesztése nélkül.", "help.solid.pattern.circular": "A kijelölt objektumokat egy tengely körül ismétli a megadott darabszámmal és teljes szöggel. Csavarkörökhöz, küllőkhöz, bordákhoz és fogakhoz használja.", + "help.solid.pattern.path": "Elemeket vagy testeket másol egy vázlatútvonal mentén, darabszám és térköz szerint. Használja görbült él menti furatokhoz vagy sín menti alkatrészekhez.", "help.solid.pattern.rectangular": "A kijelölt objektumokat egy vagy két irányban ismétli a megadott darabszámmal és térközzel. Furatok, bordák, csapok vagy lábak soraihoz és rácsaihoz használja.", + "help.solid.pipe": "Kerek csövet hoz létre vázlatgörbékből álló útvonal mentén, tömören vagy falvastagsággal üregesen. Használja csövekhez, huzalokhoz, kábelekhez és sínekhez.", "help.solid.press_pull": "Anyagot ad hozzá vagy távolít el egy lap húzásakor, illetve lekerekíti az éleket, ha húzza őket. Közvetlenül a modellen végzett gyors módosításokhoz használja.", "help.solid.remove": "A kijelölt testeket az idővonal ezen pontjától kezdve kiveszi a tervből; a korábbi lépések megtartják őket. Segédtest, például egy már nem szükséges vágószerszám elhagyására használja.", "help.solid.replace_face": "A kijelölt sík lapokat egy síkra vagy egy párhuzamos lapra mozgatja, és a test annak megfelelően nő vagy zsugorodik. Egy lap másik alkatrésszel vagy szerkesztő síkkal egy vonalba hozására használja.", "help.solid.revolve": "Egy vázlatprofilt egy tengely körül forgat el, hogy kerek szilárd testet hozzon létre. Tengelyekhez, gombokhoz, tálakhoz és minden olyan alkatrészhez használja, amely egy középvonal körül kerek.", + "help.solid.rib": "Vékony falat ad egy nyitott vázlatgörbe mentén, kitöltve a test következő lapjaiig. Használja falak és sarkok merevítésére, például öntött vagy nyomtatott alkatrészekben.", "help.solid.scale": "A kijelölt testeket egy tényezővel nagyítja vagy kicsinyíti, minden irányban egyformán vagy tengelyenként külön-külön. Importált alak átméretezésére vagy a zsugorodás figyelembevételére használja.", "help.solid.shell": "Kiüregez egy szilárd testet, a megadott vastagságú falakat meghagyva, és a kiválasztott lapokat megnyithatja. Dobozokhoz, fedelekhez és más vékony falú alkatrészekhez használja.", + "help.solid.sphere": "Gömböt hoz létre sugárból vagy átmérőből egy középpont körül. Használja golyókhoz, gombokhoz és lekerekített végekhez.", "help.solid.split_body": "Egy testet külön testekre vág egy síkkal, egy másik test lapjával vagy egy vázlatvonallal. Önállóan nyomtatott, megmunkált vagy színezett alkatrészek készítéséhez használja.", "help.solid.split_face": "A kijelölt lapokat egy sík, egy másik test lapja vagy vázlatgörbék mentén osztja fel, a test elvágása nélkül. Egy lap egy részének saját dőlés, szín vagy eltolás adásához használja.", "help.solid.sweep": "Egy vázlatprofilt egy útvonal mentén húz végig, hogy szilárd testet hozzon létre. Csövekhez, sínekhez, fogantyúkhoz és minden olyan alkatrészhez használja, amelynek állandó a keresztmetszete, és egy görbét követ.", + "help.solid.thread": "ISO metrikus menetet ad egy hengeres laphoz, kozmetikus menetként vagy a testbe vágva. Használja csavarokhoz, menetes furatokhoz és nyomtatott csavaralkatrészekhez.", + "help.solid.torus": "Gyűrűt hoz létre a tengelye körüli nagy sugárból és a kerek keresztmetszetének kis sugarából. Használja O-gyűrűkhöz, fogantyúkhoz és kerek gyöngyökhöz.", + "help.solid.web": "Vékony falat ad minden nyitott vázlatgörbe mentén, mindegyiket a test következő lapjaiig kitöltve. Használja házakban és tálcákban támasztó falak rácsához.", + "help.surface.blend": "Olyan felületet hoz létre, amely áthidalja két test éleit, mindkettőhöz érintő vagy görbületfolytonos módon. Használja két felület sima összekötésére egy résen át.", + "help.surface.boundary": "Felületet hoz létre, amely kitölt két-négy vázlatgörbéből álló hurkot vagy egy görbehálót. Használja szabadformájú panelekhez, amelyeket az éleik határoznak meg.", + "help.surface.extend": "Meghosszabbít egy felületet az élein túl, adott távolsággal vagy egy síkig vagy lapig. Használja, hogy a felületek átfedjék egymást, mielőtt levágja vagy összevarrja őket.", + "help.surface.extrude": "Vázlatgörbéket vagy profilokat tol egy távolságon át felületté, csak falakkal, fedőlapok nélkül. Használja vékony falakhoz, valamint vágó- vagy osztószerszámokhoz.", + "help.surface.fair": "Kisimítja a szabadformájú lapok belsejét, miközben az éleik a helyükön maradnak. Használja egy felület dudorainak és hullámos tükröződéseinek kiegyenlítésére.", + "help.surface.loft": "Olyan felületet hoz létre, amely sorban áthalad két vagy több szelvényen, fedőlapok nélkül. Használja héjakhoz és különböző alakzatok közötti átmenetekhez.", + "help.surface.match": "Újraépíti egy felület szélét, hogy találkozzon egy másik test élével, egyező érintővel vagy görbülettel. Használja két felület közötti varrat sima lezárására.", + "help.surface.offset": "Lapok másolatát hozza létre a normálisaik mentén adott távolságban, új felülettestként. Használja burkolatokhoz, hézagokhoz vagy egy fal másik oldalához.", + "help.surface.patch": "Egy vázlattartományt vagy élek zárt hurkát tölt ki egy lappal, laposan vagy simán görbítve. Használja egy felülettest lyukainak lezárására.", + "help.surface.reverse_normal": "Megfordítja egy felülettest lapjait, így a külső oldaluk a másik irányba néz. Használja vastagítás vagy összevarrás előtt, ha a lapok befelé néznek.", + "help.surface.revolve": "Vázlatgörbéket vagy profilokat forgat egy tengely körül felületté, fedőlapok nélkül. Használja kerek héjakhoz, például lámpaernyőkhöz, tálakhoz és fúvókákhoz.", + "help.surface.ruled": "Egyenes vonalakból álló sávot hoz létre élek láncából kiindulva, a lap normálisa vagy érintője mentén, vagy szögben. Használja dőlt falakhoz, lefutásokhoz és osztófelületekhez.", + "help.surface.stitch": "Összevarrja a felülettesteket a közös éleik mentén, szilárd testté, ha zárt teret alkotnak. Használja felületek egy csoportjának egyetlen testté alakítására.", + "help.surface.sweep": "Vázlatgörbéket vagy profilokat mozgat egy útvonal mentén felületté, fedőlapok nélkül. Használja ereszcsatornákhoz, szegélyekhez és más vékony alakzatokhoz, amelyek egy útvonalat követnek.", + "help.surface.thicken": "Vastagságot ad egy felülettestnek, szilárd testté alakítva. Használja felületekből nyomtatható vagy megmunkálható alkatrészek készítésére.", + "help.surface.trim": "Elvág egy felületet egy síkkal, egy másik felülettel vagy vázlatgörbékkel, és a kiválasztott oldalt tartja meg. Használja felületek alakra vágására az összevarrás előtt.", + "help.surface.unstitch": "Egy test lapjait különálló felülettestekbe választja szét; egy szilárd test felületekre esik szét. Használja egy test egyes lapjainak átdolgozására.", + "help.surface.untrim": "Eltávolítja a lyukakat egy lapról, vagy visszaállítja a külső határát a felület természetes határaira. Használja a teljes felület visszanyerésére vágás után.", "help.third_party": "Harmadik felek licencei", "help.timeline.compute_all": "Az idővonal minden elemét az elejétől újraépíti. A modell frissítésére és a sikertelen elemek megtekintésére használja.", "help.timeline.delete": "Törli a kijelölt elemeket az idővonalról; egy vázlat törlése a belőle épített elemeket is törli. Egy már nem kívánt lépés eltávolítására használja.", + "help.timeline.dependents": "Felsorolja azokat az elemeket, amelyek egy elemmel együtt törlődnének, és azokat, amelyek nélküle hibára futnának. Használja egy elem törlése vagy módosítása előtt.", "help.timeline.play": "Egyenként újrajátssza a hátralévő elemeket, minden újraépítés után fél másodperc szünettel. A leállításhoz futtassa újra ezt a parancsot, vagy nyomja meg az Esc billentyűt; az Ugrás a végére azonnal a végére ugrik.", + "help.view.apply": "A nézetet egy szabványos irányba fordítja, például elölről, felülről vagy izometrikusra, vagy egy mentett elnevezett nézetre. Használja, hogy a modellt rögzített szögből nézze.", + "help.view.delete": "Töröl egy mentett elnevezett nézetet. A modell nem változik.", + "help.view.fit": "Nagyít és pásztáz, hogy az egész modell vagy a kijelölés kitöltse a nézetet. Használja, ha a modell kikerült a látómezőből.", + "help.view.grid": "Megjeleníti vagy elrejti a rácsot a nézetablakban. Használja méret- és tájékozódási segédletként modellezés közben.", + "help.view.ground_shadow": "Megjeleníti vagy elrejti a modell árnyékát a talajon. Használja a magasság és a helyzet könnyebb megítéléséhez.", + "help.view.home": "Visszafordítja a nézetet a kezdőirányba, és illeszti a modellt. Használja egy ismert nézethez való gyors visszatéréshez.", + "help.view.list": "Felsorolja a tervben mentett elnevezett nézeteket. Használja egy korábban mentett nézet megkeresésére.", + "help.view.navigate": "Lépésenként forgatja, pásztázza vagy nagyítja a nézetet, például negyedfordulatot balra. Használja a kamera pontos mozgatására húzás helyett.", + "help.view.navigation_bar": "Megjeleníti vagy elrejti a navigációs sávot a nézetablak alján. Rejtse el a több helyért, jelenítse meg, hogy egérrel elérje a nézeteszközöket.", + "help.view.rename": "Új nevet ad egy mentett elnevezett nézetnek. Maga a nézet változatlan marad.", + "help.view.save": "Elmenti a kamera jelenlegi helyzetét elnevezett nézetként a tervben. Használja, hogy később ugyanahhoz a szöghöz térjen vissza, például képernyőképekhez.", + "help.view.spin": "Folyamatosan körbeforgatja a nézetet a modell körül a következő kattintásig vagy billentyűleütésig. Használja egy modell minden oldalról való bemutatására.", + "help.view.tool": "Rögzít egy kameraeszközt, keringést, pásztázást vagy nagyítást, így a bal egérgombbal való húzás mozgatja a nézetet, amíg ki nem kapcsolja. Használja érintőpadon vagy középső egérgomb nélkül.", + "help.view.visual_style": "Átváltja a modell megjelenítési módját: árnyalt élekkel vagy anélkül, drótváz, vagy rejtett élekkel. Használja a drótvázat a belső megtekintésére, az árnyaltat a tiszta megjelenéshez.", + "history.sketch_under_constrained": "Alulkényszerezett ({count} szabadságfok)", + "history.sketch_under_constrained_one": "Alulkényszerezett ({count} szabadságfok)", "hole_presets.confirm_delete": "Törlés megerősítése", "hole_presets.delete": "Törlés", "hole_presets.delete_prompt": "Törli ezt a személyes előbeállítást? A meglévő furatok nem változnak.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Ellenőrizze a csukló típusát (például Merev), a földhöz rögzítést, a csuklókorlátokat és a paraméterrel vezérelt értékeket.", "joint_move.blocked_title": "Ez az alkatrész nem mozgatható", "joint_move.coarse": "Forgatási lépés a tengely közelében (°)", + "joint_move.conflict": "Ennek az alkatrésznek egy csuklója ütközik a többivel: {joint}.", + "joint_move.conflict_hint": "Szerkessze, nyomja el vagy törölje az ütköző csuklót, hogy a többi csukló elhelyezhesse az alkatrészt.", "joint_move.distance": "Távolság a kezdőponttól", "joint_move.done": "Kész", "joint_move.fine": "Forgatási lépés a tengelytől távol (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Különböző anyagok", "measure.at": "Itt", "measure.item": "{number}. elem", + "measure.quick_copied": "Mérés átmásolva", + "measure.quick_copy": "Kattintson a mérés másolásához", + "measure.quick_edges": "{count} él", + "measure.quick_faces": "{count} lap", "messages.ago_h": "{n} órája", "messages.ago_min": "{n} perce", "messages.ago_s": "{n} másodperce", @@ -1620,6 +1938,8 @@ "motion.track_name": "{number}. sáv", "nav.alias.help": "Shift+Alt+bal húzás: keringés, Shift+Alt+középső húzás: pásztázás, Shift+Alt+jobb húzás: nagyítás; a középső húzás is pásztáz, a jobb húzás is keringést végez", "nav.blender.help": "Középső húzás: keringés, Shift+középső húzás: pásztázás, Ctrl+középső húzás: nagyítás; a jobb húzás nem mozgatja a kamerát", + "nav.creo.help": "Középső húzás: keringés, Shift+középső húzás: pásztázás, Ctrl+középső függőleges húzás: nagyítás (lefelé húzva közelít); az egérgörgő görgetése: nagyítás", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Az egér és a 3D-egér mindkét póluson átforgat, és megőrzi az elfordulást. A Shiftre történő tengelyhez illesztés ki van kapcsolva.", "nav.free_orbit.label": "Szabad keringés", "nav.free_orbit.snap_help": "Az egér és a 3D-egér mindkét póluson átforgat, és megőrzi az elfordulást. Keringéskor tartsa lenyomva a Shiftet a nézetirány és az elfordulás illesztéséhez.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+bal húzás: pásztázás, Shift+Alt+bal húzás: nagyítás, Ctrl+bal húzás üres területen: keringés", "nav.inventor.help": "Középső húzás: pásztázás, Shift+középső húzás: keringés, Ctrl+középső húzás: nagyítás, jobb húzás: keringés", "nav.maya.help": "Alt+bal húzás: keringés, Alt+középső húzás: pásztázás, Alt+jobb húzás: nagyítás; a középső húzás is pásztáz", + "nav.nx.help": "Középső húzás: keringés, Shift+középső húzás: pásztázás (az NX-ben középső + jobb gomb), Ctrl+középső húzás: nagyítás (az NX-ben középső + bal gomb); a jobb húzás nem mozgatja a kamerát", "nav.openscad.help": "Bal húzás üres helyen: keringés, Shift+bal húzás: kijelölés kerettel, a vázlatgeometria húzása szerkeszt; jobb vagy középső húzás: pásztázás, Shift+jobb vagy Shift+középső húzás: nagyítás", "nav.perspective.sketch": "A vázlatszerkesztés ortografikus nézetet használ. A perspektívára váltáshoz fejezze be a vázlatot.", "nav.right_drag_orbits.help": "Ki: a jobb gombos húzás nem mozgatja a kamerát, és a jobb gomb csak a helyi menüt nyitja meg. A SolidWorks egérkiosztás kiválasztása kikapcsolja.", @@ -1748,6 +2069,11 @@ "not a move": "nem mozgatás", "not a number": "nem szám", "open a sketch first": "előbb nyisson meg egy vázlatot", + "parameters.apply_live": "Minden módosítás alkalmazása a mező elhagyásakor", + "parameters.apply_live_tip": "Kikapcsolva: a módosítások az Alkalmaz vagy az OK megnyomásáig várnak, majd a terv egyszer épül újra mindegyikkel. A Mégse vagy az Esc elveti őket.", + "parameters.held": "{count} módosítás vár az Alkalmazásra", + "parameters.held_hint": "Kifejezések és egységek szerkesztése. A módosítások az Alkalmaz vagy az OK megnyomásáig várnak.", + "parameters.held_one": "1 módosítás vár az Alkalmazásra", "parts.automatic_name": "automatikus", "parts.dimension.across_flats": "Kulcsnyílás", "parts.dimension.bore": "Furat", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Belső kulcsnyílású lencsefejű csavar", "parts.family.dowel_pin": "Hengeres illesztőcsap", "parts.family.hex_bolt": "Hatlapfejű csavar", + "parts.family.hex_cap_screw_inch": "Hatlapfejű csavar (hüvelykes)", "parts.family.hex_nut": "Hatlapú anya", + "parts.family.hex_nut_inch": "Hatlapú anya (hüvelykes)", "parts.family.set_screw": "Belső kulcsnyílású szárnélküli csavar, lapos végű", "parts.family.socket_head_cap_screw": "Belső kulcsnyílású hengeresfejű csavar", "parts.family.washer": "Sima alátét", + "parts.family.washer_sae": "Sima alátét, SAE (keskeny)", + "parts.family.washer_uss": "Sima alátét, USS (széles)", + "parts.holes": "Furatok (opcionális)", + "parts.placement_hint": "jelöljön ki egy vagy több furatot, hogy mindegyikbe beillesszen egy alkatrészt, vagy az OK az origóba helyezi", + "parts.system": "Mértékegység-rendszer", + "parts.system.inch": "Hüvelyk", + "parts.system.metric": "Metrikus", "pattern.alignment_2": "2. igazítás", "pattern.alignment_hint": "A darabszám tartalmazza az eredetit. A Közép kiegyensúlyozza a másolatokat; a Megfordítás páros összegnél kijelöli a többletoldalt.", "pattern.direction_1": "1. irány", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Elsimítja a recés éleket.", "prefs.applies_on_restart": "Újraindításkor lép érvénybe", "prefs.assistant": "Asszisztens", + "prefs.auto_operation": "A művelet automatikus kiválasztása", + "prefs.auto_operation_note": "Az elemablakok aszerint választják az Egyesítés, Új test vagy Kivágás műveletet, hogy mit érint az új anyag, amíg Ön nem választ egyet. Kikapcsolva: megtartják a megnyitáskor kapott műveletet.", "prefs.axes": "Tengelyek", "prefs.axis": "Tengely", "prefs.bodies_folders": "Testmappák", @@ -1820,6 +2157,8 @@ "prefs.bottom_centre": "Alsó közép", "prefs.bottom_right": "Jobb alsó", "prefs.browser": "Böngésző", + "prefs.browser_eye_left": "Szem az összecsukó nyíl mellett", + "prefs.browser_eye_left_note": "A böngésző sorai a megjelenítés/elrejtés szemét az összecsukó nyíl mellett mutatják, mint korábban, nem a sorok jobb végén lévő oszlopban.", "prefs.browser_reveal_on_hover": "Megjelenítés rámutatáskor", "prefs.browser_show_note": "A Megjelenítve beállítás a képernyőn tartja a böngészőt. A Megjelenítés rámutatáskor elrejti, amíg a mutató a helye vagy a bal szélén lévő keskeny fül fölé nem kerül, és nyitva marad, amíg a mutató rajta van, vagy amíg egy belőle nyitott menü nyitva van.", "prefs.browser_shown": "Megjelenítve", @@ -1827,6 +2166,8 @@ "prefs.button_left": "Húzás bal gombbal", "prefs.button_middle": "Húzás középső gombbal", "prefs.button_right": "Húzás jobb gombbal", + "prefs.carousel_next": "Következő", + "prefs.carousel_previous": "Előző", "prefs.choose_font": "Betűtípusfájl kiválasztása…", "prefs.click": "Kattintás", "prefs.contact_shading": "Lágy érintkezési árnyalás", @@ -1839,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Görbült felületek", "prefs.curves": "Görbült felületek", + "prefs.cut_preview_tint": "Az eltávolított anyag megjelenítése pirossal", + "prefs.cut_preview_tint_help": "Az előnézet az elem által eltávolított anyagot és a lecserélt alakzatot piros, áttetsző szellemképpel tölti ki. Kikapcsolva ezek a kitöltések teljesen átlátszóak, és csak a körvonalaik láthatók.", + "prefs.dark_parts_shading": "A sötét alkatrészek formájának megőrzése", + "prefs.dark_parts_shading_help": "A nézet árnyalása lineáris fényben, lágy égbolt-kitöltéssel, hogy a sötét lapokon megmaradjon az átmenet, és ne váljanak feketévé", "prefs.dead_zone_note": "A sraffozott sáv a holtsáv: az azon belüli mozgást figyelmen kívül hagyja.", "prefs.default": "alapértelmezett", "prefs.design": "Terv alapbeállításai", @@ -1853,6 +2198,8 @@ "prefs.edges": "Élek és árnyalás", "prefs.extend": "Meghosszabbítás", "prefs.extra_navigation": "A Ctrl+bal egérgombos húzás az üres területen keringést végez; a Szóköz nyomva tartásával pásztázhat.", + "prefs.extrude_view_isometric": "A nézet izometrikusra fordítása a Kihúzás megnyitásakor", + "prefs.extrude_view_return": "Visszatérés a korábbi nézethez a Kihúzás bezárásakor", "prefs.follows_os": "Az operációs rendszert követi", "prefs.font": "Betűtípus", "prefs.font_fallback": "A kiválasztott betűtípusból hiányzó karakterek a beépített betűtípusból pótlódnak, így egyetlen felirat sem mutat üres négyzetet.", @@ -1868,8 +2215,11 @@ "prefs.graphics_card_auto": "Automatikus", "prefs.graphics_card_missing": "A mentett videokártya nem érhető el; az Automatikus beállítás van használatban.", "prefs.graphics_card_restart": "A SolidCraft újraindítása után lép életbe. A WGPU_ADAPTER_NAME felülbírálja ezt a választást.", + "prefs.graphics_card_unused": "A mentett videokártyát nem használta ez az ablak; a ténylegesen használt kártya a Súgó › A SolidCraftról ablakban és az állapotsorban látható. Próbálja az Automatikus beállítást, vagy a WGPU_ADAPTER_NAME értékét állítsa a kártya nevének egy egyedi részletére.", "prefs.graphics_note": "Cserélje a sebességet simaságra. Minden választás hatását egy minta mutatja.", "prefs.graphics_presets_note": "Az előbeállítások az alábbi beállításokat együtt állítják be.", + "prefs.hide_constraint_glyphs_zoomed_out": "Kényszerjelek elrejtése kicsinyítéskor", + "prefs.hide_constraint_glyphs_zoomed_out_note": "A kényszerjelek eltűnnek a nézetből, ha a vázlat annyira ki van kicsinyítve, hogy zsúfolttá tennék. Kikapcsolva: minden nagyításnál változatlan képernyőméretűek maradnak.", "prefs.history": "Előzmények", "prefs.history_origin_bodies": "Az origó és a testek megjelenítése felül", "prefs.history_origin_bodies_note": "A bal oldali vagy a Böngésző alatti Előzmények az aktív komponens Testek mappájával és az Origóval kezdődik, szem ikonjaikkal és menüikkel, ahogy a Böngészőben. Az alul lévő Előzmények nem változik.", @@ -1880,6 +2230,8 @@ "prefs.history_sketches_note": "Ha a Vázlatok beállítása „Elemük alatt”, a bal oldali Előzmények minden vázlatot egy szinttel beljebb, az első belőle készült elem alatt sorol fel, ha elég széles a nevekhez. Az alul lévő idővonal mindig a létrehozás sorrendjét tartja meg.", "prefs.history_sketches_under_feature": "Elemük alatt", "prefs.hold_stop_snapping": "Nyomva tartva leállítja az illesztést", + "prefs.home_fit_size": "A Kezdőnézet és az Illesztés mérete", + "prefs.home_fit_size_note": "Mekkora részét tölti ki a modell a nézetnek, amikor a Kezdőnézet, az Illesztés, egy megnyitott terv vagy egy navigátornézet-váltás keretezi, függetlenül attól, hogy az alábbi beállítás be van-e kapcsolva. 100 %: kitölti a nézetet a panelek, az iránytű és a navigációs sáv között.", "prefs.icons_only": "Csak ikonok", "prefs.imported_file": "Importált fájl", "prefs.in_browser": "A böngészőben", @@ -1888,13 +2240,22 @@ "prefs.interface_language": "Felület nyelve", "prefs.interface_note": "A SolidCraft megjelenése és elemeinek elhelyezése.", "prefs.interval_minutes": "{n} perc", + "prefs.invert_curved_roll_arrows": "Az íves gördülőnyilak megfordítása", + "prefs.invert_curved_roll_arrows_note": "A nézetkocka sarkában lévő két íves nyíl a nézetet a képernyő síkjában gördíti. Be: az óramutató járásával megegyező nyíl ellentétes irányba gördít, az ellentétes nyíl pedig az óramutató járásával megegyező irányba. Ki: minden nyíl abba az irányba gördíti a nézetet, amerre ível.", + "prefs.invert_navigator_arrows": "A nézetkocka forgatónyilainak megfordítása", + "prefs.invert_navigator_arrows_note": "A kocka körüli nyilak úgy keringetik a kamerát, ahogy mutatnak, mint a Fusion és az Inventor esetében: a bal oldali nyíl jobbra mutat, és a kamerát jobbra lendíti. Ki: a nyíl a kockát afelé az oldal felé forgatja, amelyiken van, így a bal nyíl a kamerát balra lendíti. Az íves gördülőnyilakat ez nem érinti.", + "prefs.keep_work_on_tab_switch": "A párbeszédablakok és eszközök nyitva tartása tervek közötti váltáskor", + "prefs.keep_work_on_tab_switch_note": "Minden tervfül megtartja a nyitott párbeszédablakát vagy eszközét azzal együtt, amit kijelölt és beírt benne, valamint a menüszalag-fülét. A tervhez visszatérve újra ott vannak. Ki: a tervek közötti váltás megszakítja őket, és a Modell fület mutatja.", "prefs.labels": "Feliratok", + "prefs.language_system": "Rendszer", "prefs.layout": "Elrendezés", "prefs.layout_note": "A Kompakt a paneleket az ablak széleihez rögzíti. A Böngésző áttetszősége Lebegő módban érhető el. Az Asszisztens oldalát az Asszisztens oldalon módosíthatja.", "prefs.left": "Bal", "prefs.left_click": "Bal kattintás", "prefs.line_drag_draws_one": "Lenyomás és húzás egy vonalat rajzol", "prefs.line_drag_draws_one_note": "A Vonal eszközben a lenyomás, húzás és felengedés egyetlen vonalat rajzol a lenyomás helyétől a felengedés helyéig, és ott véget ér. A kattintások továbbra is láncot rajzolnak. Ki: a húzás a felengedés helyén pontot helyez el, ahogy a kattintás.", + "prefs.line_hover_tangent_arc": "Egy vonal utolsó pontján megállva váltás érintő ívre", + "prefs.line_hover_tangent_arc_note": "A Vonal eszközben, miután megrajzolt egy szakaszt, mozdítsa el a mutatót a lánc utolsó pontjától, térjen vissza, és tartsa mozdulatlanul rajta: a következő kattintás egy érintő ívet fejez be, ugyanez a mozdulat pedig visszavált vonalakra. Ki: az ott megállás nem csinál semmit.", "prefs.linked_designs": "Kapcsolt tervek", "prefs.live_input": "Élő bevitel", "prefs.live_preview": "Élő előnézet", @@ -1908,6 +2269,9 @@ "prefs.max_file_size_step": "STEP- és importfájlok", "prefs.max_file_size_web": "A webalkalmazás legfeljebb 512 MB-os STEP- és importfájlokat, valamint 256 MB-os terveket nyit meg: egy böngészőlap nem tud nagyobb fájlokat tárolni. Az asztali alkalmazásban e korlátok növelhetők.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Nagy ikonok", + "prefs.menu_list": "Lista", + "prefs.menus": "Menük", "prefs.minutes": "perc", "prefs.minutes_suffix": " perc", "prefs.mouse": "Egér és érintőpad", @@ -1915,6 +2279,8 @@ "prefs.mouse_mapping": "Egérkiosztás", "prefs.navigation": "Navigáció", "prefs.navigation_note": "Hogyan mozgatja a nézetet az egér, az érintőpad és a 3D-egér.", + "prefs.navigator_fit": "A modell illesztése navigátornézet-váltás után", + "prefs.navigator_fit_note": "A nézetkocka egy lapja, sarka vagy nyila, illetve a gizmo egy tengelye a modell közepére is ránéz abból az egyetlen távolságból, amelyből minden oldalról belefér (a határoló gömbje). Amíg ez be van kapcsolva, a Kezdőnézet ugyanazt a nagyítást és középpontot használja, így az utána választott nézetek csak elfordulnak. Ki: a nézet a helyén fordul el, megtartva a célpontját és a nagyítását.", "prefs.network_host_remove": "Eltávolítás", "prefs.network_locations": "Hálózati helyek engedélyezése a tervekben", "prefs.network_locations_note": "Ki: egy terv másik számítógépen lévő hivatkozott fájljai (\\\\server\\share) csak az itt felsorolt kiszolgálókról nyílnak meg, vagy miután kérdésre engedélyez egyet.", @@ -1927,10 +2293,18 @@ "prefs.origin_plane_names": "Origósíkok nevei", "prefs.origin_plane_names_note": "A Böngészőben, a párbeszédablakokban és a listákban megjelenő nevek. A {top} az XY, a {front} az XZ, a {right} pedig az YZ, a Z felfelé mutat. A parancsok, szkriptek és mentett tervek az XY, XZ és YZ jelölést tartják meg.", "prefs.overall_speed": "Összsebesség", + "prefs.parameter_list_rows": "Paraméterlista sorai", + "prefs.parameter_list_rows_tip": "Az üres értékmezőben a Lefelé nyíl felsorolja a paramétereket, a kedvenceket előre, legfeljebb ennyit. Kevesebb sor esetén a lista könnyű marad egy nagy tervben.", + "prefs.persistent_ribbon_pressed": "Az aktív menüszalag-parancsok kiemelése", + "prefs.persistent_ribbon_pressed_help": "Kiemeli a menüszalag parancsait, amíg a hatásuk be van kapcsolva. Kapcsolja ki a korábbi semleges megjelenés és parancssúgó megtartásához.", "prefs.perspective_fov": "Látószög", "prefs.placement": "Elhelyezés", "prefs.prefer_free_sketch_points": "Átfedő pontoknál a mozgatható vázlatpontok előnyben részesítése", "prefs.preview_choices": "A választások előnézete", + "prefs.preview_tint_new_faces": "Az új felület színezése az előnézetben", + "prefs.preview_tint_new_faces_help": "Egy testet módosító elem előnézete az általa hozzáadott felületet az előnézeti színnel rajzolhatja ki. Kikapcsolva a test önmagaként jelenik meg.", + "prefs.print_face_highlight": "Nyomtatási lap kiemelése", + "prefs.print_face_highlight_tip": "Milyen erősen színezi és körvonalazza a nézet a test nyomtatási lapját. 0 % esetén nincs kiemelés.", "prefs.profile_active": "Aktív profil", "prefs.profile_applied": "Profil alkalmazva.", "prefs.profile_changed": "A beállítások a profil mentése óta megváltoztak. A Mentés eltárolja őket a profilban.", @@ -1952,9 +2326,13 @@ "prefs.quality_fastest": "leggyorsabb", "prefs.quality_slowest": "leglassabb", "prefs.quality_smoother": "simább", + "prefs.quick_measure": "Gyorsmérés a nézet sarkában", + "prefs.quick_measure_note": "A kijelölés mérete a nézet jobb alsó sarkában: egy él hossza, kerek él esetén Ø és R, egy lap területe, egy pont helyzete, két elem távolsága és szöge, több él vagy lap összege. Egy kattintás átmásolja.", "prefs.render_previous_geometry_budget": "Korábbi geometriakeret használata a renderelési előnézethez", "prefs.render_previous_geometry_budget_help": "A korábbi rögzített geometriakorlát visszaállítása (64 bites asztali gépen 512 MiB, máshol 128 MiB) az eszközalapú keret helyett.", "prefs.reports_saved": "{n} mentve", + "prefs.ribbon_click_ends_tool": "A futó eszköz gombjára kattintva az eszköz befejeződik", + "prefs.ribbon_click_ends_tool_note": "A használatban lévő vázlateszköz kivilágított menüszalag-gombjára kattintva az eszköz befejeződik, így a nézetben a kattintások újra kijelölnek. Ki: a kattintás újra elindítja az eszközt.", "prefs.ribbon_reveal": "Keresési találatok megmutatása a menüszalagon", "prefs.ribbon_reveal_note": "Ha a Parancsok keresése egy találata fölé viszi a mutatót, megjelenik, hol található a parancs a menüszalagon: a füle, a gombja vagy a sora egy panel legördülő listájában. A keresésből indított parancs ott felvillan, a legördülő listából futó parancs pedig megjelöli a panelját.", "prefs.right_click": "Jobb kattintás", @@ -1965,6 +2343,8 @@ "prefs.search_empty": "Nincs egyező beállítás", "prefs.select": "Kijelölés", "prefs.select_one_item": "Egy elem kijelölése", + "prefs.select_other_hidden": "Rejtett geometria kijelölése a Más kijelölése paranccsal", + "prefs.select_other_hidden_help": "Bekapcsolva: a mutató közelében lévő rejtett testeket, vázlatokat és takart éleket is tartalmazza. Kikapcsolva: a mutató alatti látható geometria eredeti listáját használja.", "prefs.selecting": "Kijelölés", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "A Shift csak hozzáad; a Ctrl / Cmd átkapcsol", @@ -1976,31 +2356,63 @@ "prefs.sketch_align_points_note": "Rajzolás közben egy pont egyszerre igazodhat vízszintesen az egyik vázlatponthoz és függőlegesen egy másikhoz, pontozott segédvonallal, és a kattintás mindkét igazítást megtartja. Ki: csak az előző ponthoz, egyszerre egy tengely mentén.", "prefs.sketch_conflict_colour": "Ütköző geometria az ütközés színével", "prefs.sketch_conflict_colour_note": "Amíg egy vázlat kényszerei ütköznek, a hibás kényszer által megfogott görbék és pontok is az ütközés színével jelennek meg, nem csak a kényszer szimbóluma vagy mérete. Kikapcsolva: megtartják szokásos színüket.", + "prefs.sketch_construction_lines": "Bővített szerkesztőegyenes-eszközök", "prefs.sketch_exit_view": "Vázlat befejezésekor", "prefs.sketch_exit_view.keep": "A jelenlegi nézet megtartása", "prefs.sketch_exit_view.previous": "Visszatérés az előző nézethez", "prefs.sketch_exit_view.unless_rotated": "Visszatérés, ha nem lett forgatva", "prefs.sketch_exit_view_note": "Hová kerül a nézet a Vázlat befejezése, a Mégse vagy a dupla Esc után.", + "prefs.sketch_face_activates_part": "Ha egy alkatrész lapjára rajzol vázlatot, az az alkatrész aktív lesz", + "prefs.sketch_face_activates_part_note": "Egy másik komponens testének lapján indított vázlat előbb aktiválja azt a komponenst, így a vázlat ahhoz tartozik, és a böngészőben ennél az alkatrésznél marad. Az alkatrész utána is aktív marad. Ki: a vázlat az aktív komponenshez tartozik.", + "prefs.sketch_open_look_at": "Vázlat megnyitásakor a nézet a vázlatra fordul", + "prefs.sketch_open_look_at_note": "Ki: vázlat létrehozása vagy szerkesztése nem változtatja a nézetet. A Ránézés a vázlatra fordítja a nézetet, amikor szeretné.", "prefs.sketch_recent_snap": "Automatikus illesztés a legutóbbi középpontokhoz és felezőpontokhoz", "prefs.sketch_recent_snap_note": "Rajzolás közben a kurzor oda illeszkedik, ahol a két legutóbbi pont (kör középpontja vagy egyenes él felezőpontja) segédvonalai keresztezik egymást. Kikapcsolva: ezek a segédvonalak csak megjelennek, és a kurzor nem mozdul el.", "prefs.sketch_selection": "Vázlat és kijelölés", "prefs.sketch_selection_heading": "Vázlat és kijelölés", "prefs.sketch_selection_note": "Hogyan illeszkednek a vázlatok, és hogyan jelölnek ki a kattintások.", + "prefs.sketch_state_icons": "A vázlatok ikonjai az állapotuk színével", + "prefs.sketch_state_icons_note": "Az Előzményekben és a böngészőben a vázlat ikonja az állapotának színét veszi fel (alulkényszerezett, teljesen kényszerezett vagy ütköző), a buboréksúgója pedig megnevezi az állapotot. Kikapcsolva: minden vázlat ikonja egyforma.", "prefs.sketch_tab_always": "A Vázlat fül mindig látható", "prefs.sketch_tab_always_note": "A Vázlat fül a szalagon marad, közvetlenül a Modell után, akkor is, ha nincs megnyitott vázlat. Rajzszerszámai ilyenkor a kijelölt síkon vagy lapon, illetve a következőként kiválasztott síkon indítanak vázlatot, benne a kiválasztott szerszámmal.", "prefs.sketch_tracking_guides": "Középpont- és felezőpont-igazítási segédvonalak", "prefs.sketch_tracking_guides_note": "Vigye az egérmutatót egy kör középpontja vagy egy egyenes él felezőpontja fölé, majd mozgassa vízszintesen vagy függőlegesen, hogy ideiglenes pontozott segédvonal jelenjen meg.", + "prefs.sketch_tracking_points": "Igazítási segédvonalak végpontokból és sarkokból rajzolás közben", + "prefs.sketch_tracking_points_note": "Amíg egy rajzeszköz pontra vár, egy vonal vagy ív végpontja, egy téglalap sarka vagy egy szabad pont fölé víve ugyanaz az ideiglenes pontozott segédvonal jelenik meg, mint egy középpontnál vagy felezőpontnál. Kikapcsolva: csak a középpontoknál és felezőpontoknál.", "prefs.sketching": "Vázlatkészítés", "prefs.snap_drawing_note": "Vázlatpont rajzolása vagy húzása közben.", "prefs.source": "Forrás", "prefs.speed": "Sebesség", "prefs.stand_up_note": "Miután egy STEP- vagy IGES-fájl Z felfelé tájolással megnyílik, negyedfordulat felajánlása az X körül.", + "prefs.stand_up_unknown": "Ismeretlen programokból származó fájloknál", + "prefs.stand_up_unknown.ask": "Rákérdezés párbeszédpanelben", + "prefs.stand_up_unknown.note": "Megjegyzés megjelenítése", + "prefs.stand_up_unknown.off": "Ne ajánlja fel", + "prefs.stand_up_unknown_note": "Az ajánlat módja, ha a fájl fejléce nem nevez meg olyan programot, amelyről ismert, hogy Y felfelé tájolással ment. Megjegyzés csak akkor jelenik meg, ha a fájl hanyatt fekvőnek látszik; a Rákérdezés párbeszédpanelben minden ilyen fájlnál rákérdez, mint korábban.", "prefs.status_bar": "Állapotsor", "prefs.status_bar_note": "Az ablak alsó szélén lévő vékony sáv megmutatja, hogy mit szerkeszt, a megnyitott vázlat állapotát a színével, valamint a terv egységeit; az egységekre kattintva módosíthatók. A vázlat állapota ilyenkor már nem jelenik meg a nézet sarkában.", "prefs.status_done": "Kész", "prefs.status_error": "Hiba", "prefs.status_selected": "Kijelölve", "prefs.status_warning": "Figyelmeztetés", + "prefs.structure.appearance": "Megjelenés", + "prefs.structure.appearance_note": "Színek, szöveg és kisegítő lehetőségek.", + "prefs.structure.in_profile": "Profilban", + "prefs.structure.layout": "Elrendezés", + "prefs.structure.layout_note": "Az ablak részeinek elhelyezkedése.", + "prefs.structure.look": "Kinézet", + "prefs.structure.measure_pointer": "Mérés és mutató", + "prefs.structure.mouse3d": "3D-egér", + "prefs.structure.mouse3d_note": "SpaceMouse és SpaceNavigator.", + "prefs.structure.navigation_note": "Egér és érintőpad. A 3D-egérnek saját oldala van.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "A mentés óta módosítva", + "prefs.structure.profile_hover": "Mentve a beállításprofilokban", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Vázlat", + "prefs.structure.tools": "Szerszámok", + "prefs.structure.tools_note": "Hogyan viselkednek a modellezőszerszámok.", + "prefs.structure.work": "Munka", "prefs.supersampling_brief": "A nézetet nagyobbra rajzolja, majd leszűri: nagyon éles, de erőforrásigényesebb.", "prefs.tab_accent_note": "A hangsúlyszín az aktív fület követi", "prefs.theme_file": "témafájl", @@ -2012,6 +2424,16 @@ "prefs.theme_follow_off": "Ki", "prefs.theme_follow_stop": "Követés leállítása", "prefs.theme_import_hint": "Kattintson egy témafájl kiválasztásához, húzzon ide egyet, vagy nyomja meg a Ctrl+V (Macen Cmd+V) billentyűkombinációt egy kimásolt témával", + "prefs.theme_option_opacity": "Átlátszatlanság", + "prefs.theme_option_opacity_help": "A lebegő panelek átlátszatlanságának beállítása. Az olvashatósági alsó határ védi a szöveget a nézetablak színei fölött.", + "prefs.theme_option_tab_colours": "Fülek színei", + "prefs.theme_option_tab_colours_help": "A téma panel- és nézetablak-színeinek használata minden menüszalag-fülhöz.", + "prefs.theme_option_tab_fade_ms": "Fülváltás átmenete", + "prefs.theme_option_tab_fade_ms_help": "A panel- és nézetablak-színek áttűnése fülváltáskor. A nulla azonnal vált.", + "prefs.theme_options_badge": "Beállítások", + "prefs.theme_options_more": "Továbbiak · {count}", + "prefs.theme_options_reset": "Visszaállítás", + "prefs.theme_options_unavailable": "Ezen az eszközön nem érhető el", "prefs.theme_paste": "Téma beillesztése", "prefs.theme_paste_none": "A vágólap nem tartalmaz SolidCraft-témát", "prefs.timeline_half_hour": "−30 perc", @@ -2033,13 +2455,23 @@ "prefs.under_cursor": "A kurzor alatt", "prefs.units_precision": "Egységek és pontosság", "prefs.updates": "Frissítések", + "prefs.value_boxes_in_view": "Értékek megjelenítése a fogantyúik mellett a nézetben", + "prefs.value_boxes_in_view_tip": "A parancs értéke (Távolság, Sugár…) egy mezőben a fogantyúja mellett, a modell fölött. Kikapcsolva: a parancsablakban írja be, amely kijelölés után átveszi a billentyűzetet, és semmi sem takarja a modellt.", "prefs.view": "Nézet viselkedése", "prefs.view_confirm_corner": "OK és Mégse a nézet sarkában", "prefs.view_confirm_corner_note": "Amíg egy párbeszédablak vagy vázlat nyitva van, a nézet jobb felső részén egy pipa és egy kereszt a párbeszédablak OK és Mégse gombját működteti, illetve befejezi vagy megszakítja a vázlatot. A nézetnavigátor lejjebb kerül alattuk.", "prefs.viewport": "Nézetablak", + "prefs.viewport_analysis_status": "Elemzési állapot megjelenítése a nézetablak fölött", + "prefs.viewport_analysis_status_help": "A nézetablak fölött megjeleníti az aktív elemzéseket, minden elemből megnyitja a jelmagyarázatát, az Esc billentyűvel pedig kikapcsolja a legutóbbi elemzést. Kikapcsolva: visszaáll a sarokban lévő jelmagyarázat és az Esc korábbi működése.", "prefs.viewport_background": "Háttér", "prefs.viewport_background_colour": "Szín", "prefs.viewport_background_theme": "A téma színátmenete", + "prefs.viewport_section_status": "Nézetablak-metszet állapotának megjelenítése", + "prefs.viewport_section_status_help": "A metszet beállításának megjelenítése a nézetablakban. Az Esc és az aktív menüszalag-gomb kikapcsolja. Kapcsolja ki az előző metszetvezérlők megtartásához.", + "prefs.viewport_status_details": "Élő nézetablak-részletek", + "prefs.viewport_status_details_help": "Az aktív elemzés és metszet beállításainak szerkesztése szabványos részletkártyákon. Kapcsolja ki a csak olvasható elemzési jelmagyarázatok és a Metszet párbeszédpanel visszaállításához.", + "prefs.viewport_status_summary": "Nézetablak-állapotelemek összevonása", + "prefs.viewport_status_summary_help": "Három vagy több nézetablak-állapotelem összevonása egyetlen összefoglaló jelvénybe. Kapcsolja ki, hogy minden elem a teljes sorban maradjon.", "prefs.wheel": "Görgő", "prefs.wheel_trackpad": "Görgő és érintőpad", "prefs.workspace": "Munkaterület", @@ -2049,6 +2481,10 @@ "properties.title": "Tulajdonságok: {name}", "recovery.days_ago": "{count} napja", "recovery.detail": "{file} · {features} elem · automatikusan mentve: {when}", + "recovery.discard_all": "Összes elvetése", + "recovery.discard_all_detail": "Ez a művelet nem vonható vissza.", + "recovery.discard_all_title": "{count} automatikus mentés elvetése?", + "recovery.discard_all_title_one": "1 automatikus mentés elvetése?", "recovery.hours_ago": "{count} órája", "recovery.just_now": "épp most", "recovery.min_ago": "{count} perce", @@ -2164,6 +2600,10 @@ "render.base_color": "Alapszín · sRGB", "render.base_metallic": "Fémes hányad", "render.base_opaque_only": "Ez a szerkesztő megőrzi az átlátszatlan test szemantikáját. Az optikai áteresztéshez használja a külön üvegvezérlőket.", + "render.batch_all_shots": "Összes felvétel ({count})", + "render.batch_empty": "Mentsen el egy felvételt, mielőtt az összes felvételt renderelné.", + "render.batch_limit": "Az összes felvétel renderelése legfeljebb 32 felvételre korlátozott.", + "render.batch_status": "{running} fut · {waiting} vár", "render.bloom_enable": "Bloom megjelenítése", "render.bloom_help": "Kreatív, csak a kimenetre vonatkozó fénykisugárzás a pozitív lineáris csúcsfényekből, három normalizált dobozszűrő-menettel szétterítve. A sugár kimeneti pixelben értendő. Lineáris megjelenítési fényhez adódik az sRGB előtt; nem lencsehatás, nem térfogati effektus és nem javítja a konvergenciát. A nyers EXR változatlan.", "render.bloom_opaque": "A bloomhoz átlátszatlan kimenet szükséges. Az átlátszó PNG-t a program elutasítja, nem lapítja csendben.", @@ -2274,6 +2714,13 @@ "render.choose_look": "Először válasszon stílust a Megjelenések között", "render.chromatic_offset": "Kromatikus éleltolás", "render.clear_stage": "Mentett díszlet eltávolítása", + "render.compare_divider": "Összehasonlító elválasztó", + "render.compare_live": "Élő", + "render.compare_live_preview": "Élő előnézet", + "render.compare_render": "{number}. render", + "render.compare_side": "{number}. render · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · rögzítve, revízió: {revision}", + "render.compare_swap": "Csere", "render.copy_request": "JSON másolása", "render.cpu_aa_help": "Térbeli minták: a több minta javítja az éleket, és növeli a renderelési időt.", "render.cpu_area_add": "Téglalap alakú CPU-fényforrás hozzáadása", @@ -2914,7 +3361,9 @@ "render.output_ready": "Készen áll a renderelésre", "render.output_run_check": "Ellenőrzés futtatása", "render.output_size_limit": "{method}: oldalanként legfeljebb {dimension} px és összesen {pixels} képpont. A legnagyobb beleférő méret: {width} × {height}.", + "render.output_size_method_profile": "{width} × {height} rendereléséhez válassza a(z) {method} módot a(z) {profile} CPU-erőforrásprofillal, vagy kisebb méretet.", "render.output_size_ok": "Méret rendben · {width} × {height} px", + "render.output_size_profile": "{width} × {height} rendereléséhez válassza a(z) {profile} CPU-erőforrásprofilt, vagy kisebb méretet.", "render.output_swap_orientation": "Szélesség és magasság felcserélése", "render.output_tools_inspector": "A méretet és a formátumot a Kimenet panelen szerkesztheti.", "render.output_view_image": "Kép megtekintése", @@ -3021,6 +3470,10 @@ "render.result_retained": "Az utolsó kész kép látható; újabb renderelés még nem váltotta le.", "render.result_sequence": "Ellenőrzőpont", "render.result_title": "Renderelési eredmény", + "render.results_choose": "Megtartott eredmények", + "render.results_label": "{number}. render · {shot} · {seconds} s", + "render.results_stale_label": "{result} [elavult]", + "render.results_unnamed": "Kép", "render.return_design": "Vissza a Tervezéshez", "render.review_stale": "Ez az áttekintés elavult. Az alkalmazás előtt oldja fel, vagy ellenőrizze újra.", "render.ribbon_aging": "Öregítés", @@ -3127,6 +3580,7 @@ "render.size_custom": "Egyéni…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · szükséges: {profile}", "render.size_presets": "Méretelőbeállítások", "render.size_presets_pending": "A Kimenet szerkesztővel érkezik", "render.size_preview": "Előnézet", @@ -3414,6 +3868,24 @@ "sheet.flange_type_contour": "Kontúr", "sheet.flange_type_edge": "Él", "sheet.no_body": "nincs lemeztest: kezdje a Perem > Alap paranccsal, vagy alakítson át egy lemezt lemezzé az Átalakítás lemezzé paranccsal (jelölje ki a nagy, sík lapját)", + "sheet.personal_rules.confirm_delete": "Törlés megerősítése", + "sheet.personal_rules.delete": "Törlés", + "sheet.personal_rules.delete_prompt": "Törli ezt a személyes szabályt? A tervekben már meglévő szabályok nem változnak.", + "sheet.personal_rules.full": "A személyes könyvtár már 64 szabályt tartalmaz.", + "sheet.personal_rules.invalid_name": "Adjon meg egy rövid nevet sortörések és vezérlőkarakterek nélkül.", + "sheet.personal_rules.invalid_values": "Egészítse ki a szabály értékeit: mindegyiknek kiértékelhetőnek kell lennie ebben a tervben, pozitív vastagsággal és 0 és 1 közötti K-tényezővel.", + "sheet.personal_rules.missing": "A kijelölt személyes szabály már nem érhető el.", + "sheet.personal_rules.name": "Szabály neve", + "sheet.personal_rules.name_exists": "Már van ilyen nevű személyes szabály. Használjon másik nevet.", + "sheet.personal_rules.name_hint": "Egyedi név", + "sheet.personal_rules.overwrite": "Módosítások mentése a kijelölt személyes szabályba", + "sheet.personal_rules.rename": "Átnevezés", + "sheet.personal_rules.rule": "Személyes szabály", + "sheet.personal_rules.save": "Mentés újként", + "sheet.personal_rules.scope": "A profiljában van elmentve, minden tervhez.", + "sheet.personal_rules.select": "Válasszon szabályt", + "sheet.personal_rules.title": "Személyes szabályok", + "sheet.personal_rules.unsupported": "Ennek a szabálynak olyan értékei vannak, amelyeket ez a verzió nem tud használni.", "shortcut.json_error": "a paramétereknek JSON-nak kell lenniük: {error}", "shortcut.no_command": "nincs `{id}` parancs; a JSON előtti szövegnek parancsazonosítónak kell lennie", "shortcut.pin": "Rögzítés az S doboz tetejére", @@ -3450,8 +3922,10 @@ "sketch_text.align_right": "Jobbra", "sketch_text.bold": "Félkövér", "sketch_text.builtin_font": "{family} (beépített)", + "sketch_text.formula": "Kezdje egyenlőségjellel (=), hogy a szavakat paraméterekből építse fel: ='W' + number(Width)", "sketch_text.italic": "Dőlt", "sketch_text.loading_fonts": "Telepített betűtípusok keresése…", + "sketch_text.no_bold": "A beépített betűtípusnak nincs félkövér változata: válasszon telepített betűtípust", "sketch_text.on_path": "A szöveg követi az útvonalát: a görbe helyezi el", "sketch_text.path_clear": "Szöveg levétele a görbéről", "sketch_text.path_hint": "A vázlat egy görbéje, amelyet a szöveg követ: kattintson ide, majd a görbére", @@ -3483,10 +3957,7 @@ "the two origins are on the same component": "a két origó ugyanazon a komponensen van", "thread.automatic_size": "Automatikus méret", "thread.designation": "Jelölés", - "thread.direction": "Menet iránya", "thread.iso_metric": "ISO metrikus", - "thread.left_hand": "Balmenetes", - "thread.right_hand": "Jobbmenetes", "thread.select_size": "Méret kiválasztása", "timeline.delete_after_marker_one": "1 elem törlése az előzményjelölő után", "timeline.delete_after_marker_other": "{count} elem törlése az előzményjelölő után", @@ -3503,8 +3974,10 @@ "timeline.move_to_group": "Elemek áthelyezése mappába", "timeline.rename_group": "Elemmappa átnevezése", "timeline.reorder_many": "Elemek átrendezése", + "timeline.suppress_features": "Elemek elnyomása", "timeline.suppress_folders_tip": "A mappákban és a beágyazott mappákban lévő összes elem elnyomása vagy elnyomásának megszüntetése", "timeline.ungroup": "Elemmappák eltávolítása", + "timeline.unsuppress_features": "Elemek elnyomásának megszüntetése", "to the face": "a laphoz", "to the next face": "a következő laphoz", "toolbar.customize_note": "{tab} lap. Jelöljön be egy parancsot, hogy eszköztárgombot kapjon. Húzhat egy panel legördülő menüjének sorát is az eszköztárra, húzhat egy gombot le az eszköztárról az eltávolításhoz, vagy használhatja a legördülő sor rögzítő tűjét.", @@ -3588,6 +4061,8 @@ "ui.3d_mouse_section": "3D-egér", "ui.3d_mouse_show_in_view": "A 3D-egér megjelenítése a 3D nézetben", "ui.3d_mouse_show_in_view_tip": "A 3D-egere képe a bal alsó sarokban, amely a mozgatásával együtt mozog.", + "ui.3d_mouse_sketch_orbit": "Vázlatok forgatása a 3D-egérrel", + "ui.3d_mouse_sketch_orbit_tip": "A 3D-egér akkor is forgatja a nézetet, amikor egy vázlat meg van nyitva és merőlegesen látszik, ahogy az egér is tudja. Kikapcsolva: a vázlatot pásztázza és nagyítja, amíg meg nem dönti a nézetet.", "ui.3d_mouse_skip": "Az eszközöm erre nem képes", "ui.3d_mouse_skip_tip": "Mindkét irányban kihagyja ezt a mozgást, és a kalibráció nem veszi figyelembe.", "ui.3d_mouse_speed": "3D-egér sebessége", @@ -3616,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Csavarja el a kupakot az óramutató járásával ellentétesen, tartsa, majd engedje el.", "ui.3d_mouse_switch_cap": "Kalibrálás középre visszatérőként", "ui.3d_mouse_switch_trackball": "Kalibrálás trackballként", + "ui.3d_mouse_use_direct": "Közvetlen illesztőprogram", + "ui.3d_mouse_use_direct_tip": "A 3D-egér közvetlen olvasása (hidraw) a spacenavd helyett.", "ui.3d_mouse_view_axis": "Nézettengely", "ui.3d_mouse_view_off": "Ki", "ui.3d_mouse_view_off_tip": "A 3D-egér illesztőprogramjának profilja kikapcsolja ezt a tengelyt, ezért a mozgása nem mozgatja a nézetet. Ha itt egy másik tengely mozgását választja, a kettő felcserélődik, és az a mozgás már nem mozgatja a nézetet.", @@ -3654,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Futtassa ezt egy terminálban, majd nyomja meg újra a Csatlakozás gombot:", "ui.agent_chat_auth_title": "Bejelentkezés az ügynökbe", "ui.agent_chat_cancel": "Mégse", + "ui.agent_chat_cancel_timeout": "Az ügynök nem válaszolt a Leállításra, ezért le lett választva. A folytatáshoz csatlakozzon újra.", + "ui.agent_chat_cannot_start": "Telepítve van, de nem indul el: {error}", "ui.agent_chat_changes": "Módosítások: {n}, egy visszavonási lépés", "ui.agent_chat_changes_n": "{n} módosítás", "ui.agent_chat_changes_of": "{n}/{limit} módosítás", @@ -3662,11 +4141,13 @@ "ui.agent_chat_command": "Ügynök parancsa", "ui.agent_chat_connect": "Csatlakozás", "ui.agent_chat_copy": "Másolás", + "ui.agent_chat_copy_message": "Üzenet másolása", "ui.agent_chat_ctx_bodies": "Testek", "ui.agent_chat_ctx_elements": "Geometriai elemek", "ui.agent_chat_ctx_features": "Elemek", "ui.agent_chat_ctx_more": "+{n} további", "ui.agent_chat_ctx_other": "Egyéb", + "ui.agent_chat_custom_heading": "Egyéni modell", "ui.agent_chat_custom_hint": "Bármely program, amely az Agent Client Protocolt használja stdin-en és stdout-on. Shell nem futtatja.", "ui.agent_chat_denied": "Elutasítva", "ui.agent_chat_deny": "Elutasítás", @@ -3710,8 +4191,16 @@ "ui.agent_chat_mode_all": "Minden", "ui.agent_chat_mode_ask": "Kérdez", "ui.agent_chat_mode_edits": "Szerkesztés", + "ui.agent_chat_model_custom": "Egyéni használata: {model}", "ui.agent_chat_model_no_tools": "A(z) {model} nem tudja használni a SolidCraft eszközeit, ezért csak csevegni lehet vele. Válasszon eszköztámogatással rendelkező modellt.", + "ui.agent_chat_model_rejected": "Az ügynök nem fogadta el a(z) {model} modellt: {error}", + "ui.agent_chat_model_search": "Modellek keresése…", "ui.agent_chat_model_tip": "Az ügynök által használt modell. A választás megmarad ennél az ügynöknél.", + "ui.agent_chat_models_failed": "A modellek nem listázhatók: {error}", + "ui.agent_chat_models_heading": "Elérhető modellek", + "ui.agent_chat_models_listing": "Modellek listázása…", + "ui.agent_chat_models_none": "A végpont nem listáz modelleket", + "ui.agent_chat_models_not_a_list": "A válasz nem modellek listája volt", "ui.agent_chat_new": "Új csevegés", "ui.agent_chat_new_confirm": "Új csevegést indít? A jelenlegi törlődik.", "ui.agent_chat_next_picture": "Következő kép", @@ -3746,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "Sorban (leállítva, nem küldve)", "ui.agent_chat_refresh": "Frissítés", "ui.agent_chat_refused": "Az ügynöknek nem engedélyezett: {reason}", + "ui.agent_chat_reinstall": "A(z) {agent} telepítve van ({program}), de a SolidCraft ellenőrzésekor nem indult el: {error}\nLehet, hogy a telepítése hiányos, vagy másféle számítógéphez készült. Telepítse újra a következővel: `{install}`, ellenőrizze, hogy egy terminálban kiírja a verzióját, majd nyomja meg a Frissítés gombot.", "ui.agent_chat_remove": "Eltávolítás a sorból", "ui.agent_chat_remove_file": "Levétel erről az üzenetről", "ui.agent_chat_remove_imported": "Levétel erről az üzenetről; az alkatrész a tervben marad (a Visszavonás eltávolítja)", + "ui.agent_chat_reply_cut_off": "A válasz elérte a hosszkorlátot, mielőtt befejeződött volna, ezért hiányos lehet. Kérje meg az ügynököt, hogy folytassa, vagy adjon rövidebb választ.", + "ui.agent_chat_reply_declined": "A modell megtagadta a válaszadást erre az üzenetre.", "ui.agent_chat_retry": "Újrapróbálás", "ui.agent_chat_right": "Jobb", "ui.agent_chat_save": "Mentés", @@ -3807,12 +4299,17 @@ "ui.ai_copy_suffix": "másolat", "ui.ai_custom_url": "Egyéni URL", "ui.ai_default": "Alapértelmezett", + "ui.ai_edit": "Szerkesztés", + "ui.ai_edit_agent_title": "Ügynök szerkesztése", + "ui.ai_edit_gone": "Ez az ügynök el lett távolítva, így nincs mit menteni.", + "ui.ai_edit_tip": "Az ügynök nevének, parancsának vagy végpontjának módosítása. Az elmentett kulcs rejtve marad.", "ui.ai_http_busy": "a végpont foglalt vagy túllépte a korlátját; próbálja később", "ui.ai_http_key": "a végpont elutasította a kulcsot: ellenőrizze a Beállítások > AI menüben", "ui.ai_http_not_found": "nincs ilyen végpont vagy modell: ellenőrizze az alap-URL-t és a modell nevét", "ui.ai_http_too_large": "a beszélgetés túl nagy ehhez a végponthoz; kezdjen új csevegést", "ui.ai_key": "API-kulcs", "ui.ai_key_hint": "opcionális; a rendszer kulcstartójában tárolódik", + "ui.ai_key_keep_hint": "hagyja üresen az elmentett kulcs megtartásához", "ui.ai_key_needs_https": "A kulcs csak HTTPS-en vagy erre a számítógépre kerül elküldésre.", "ui.ai_key_note": "A rendszer kulcstartójában tárolódik, soha nem a SolidCraft beállításaiban. Helyi szervernél hagyja üresen.", "ui.ai_keychain_error": "A rendszer kulcstartója elutasította: {error}", @@ -3839,11 +4336,15 @@ "ui.ai_permissions": "Jogosultságok", "ui.ai_preset": "Előbeállítás", "ui.ai_protocol": "Protokoll", + "ui.ai_reasoning_effort": "Gondolkodási szint", + "ui.ai_reasoning_effort_field_hint": "üres = a szolgáltató alapértelmezése", + "ui.ai_reasoning_effort_hint": "Nem kötelező. `reasoning_effort` néven kerül elküldésre a végpontnak; az elfogadott értékek szolgáltatónként eltérnek (például `low`, `high` vagy `max`). Az itt megadott értéket a SolidCraft soha nem cseréli le. Hagyja üresen, ha nem szeretne semmit küldeni, és meg szeretné tartani a szolgáltató alapértelmezését.", "ui.ai_remove": "Eltávolítás", "ui.ai_request_timed_out": "A modell nem válaszolt {seconds} s alatt. A kérés időkorlátját ehhez a végponthoz a Beállítások › Asszisztens alatt emelheti meg.", "ui.ai_request_timeout": "Kérés időkorlátja", "ui.ai_request_timeout_hint": "Mennyi ideig tarthat egy modellkérés ehhez a végponthoz, 30 s-tól egy óráig. Lassú helyi modellnél emelje meg.", "ui.ai_reset": "Visszaállítás", + "ui.ai_save": "Mentés", "ui.ai_settings": "AI-beállítások…", "ui.ai_show_features": "AI-funkciók megjelenítése", "ui.ai_show_features_note": "Az ügynök-csevegés: egy panel, ahol egy már használt kódolóügynök vagy egy választott modellvégpont a megnyitott terven dolgozik. Kikapcsolva: nincs AI-gomb, gyorsbillentyű, menüpont vagy panel, és semmi sem keresődik vagy indul el.", @@ -3922,6 +4423,8 @@ "ui.cancel": "Mégse", "ui.canvases": "Vásznak", "ui.center": "Középpont", + "ui.center_arc_follows_cursor": "A középpontos ív követi a kurzor irányát", + "ui.center_arc_follows_cursor_tip": "A középpontos ív az óramutató járásával megegyező vagy azzal ellentétes irányban halad, aszerint, hogy a kurzor merre kerüli meg a középpontját. Kikapcsolva: mindig az óramutató járásával ellentétes irányban, a kezdőponttól.", "ui.centerline": "Középvonal", "ui.chain": "Lánc", "ui.chamfer": "Letörés", @@ -3930,6 +4433,7 @@ "ui.circle": "Kör", "ui.circular_pattern": "Körminta", "ui.clear": "Törlés", + "ui.clear_print_face": "Nyomtatási lap törlése", "ui.clear_recent": "Legutóbbiak törlése", "ui.clear_the_selection": "Kijelölés törlése", "ui.click_selects_whole_bodies": "A kattintás teljes testeket jelöl ki", @@ -3964,12 +4468,27 @@ "ui.constant": "Állandó", "ui.constraints_conflict": "Kényszerek ütköznek", "ui.construction": "Szerkesztő", + "ui.construction.angle_hint": "Szerkesztőegyenes: kattintson egy pontra, majd adjon meg szöget, vagy válasszon irányt", + "ui.construction.bisector_hint": "Szögfelező: válasszon két egymást metsző egyenest, majd a kívánt megoldást", + "ui.construction.common_hint": "Közös érintő: válasszon két kört/ívet, majd a kívánt megoldást", + "ui.construction.contact_hint": "Érintő: válasszon egy kört/ívet vagy nyitott spline-t/kúpgörbét, majd az érintési pontot (szabadformájú görbék: végpontok)", + "ui.construction.external_hint": "Érintő: válasszon egy kört vagy ívet, egy külső pontot, majd a kívánt megoldást", + "ui.construction.free_hint": "Szerkesztőegyenes: kattintson két pontra; jobb kattintással újrakezdheti", + "ui.construction.normal_needs_length": "A végtelen egyenes mindig szerkesztőegyenes: normál vonal rajzolásához adjon meg hosszt", + "ui.construction.point_hint": "Szerkesztőegyenes: kattintson arra a pontra, amelyen át kell haladnia", + "ui.construction.reference_hint": "Szerkesztőegyenes: válasszon egy egyenest, majd egy pontot; jobb kattintással módosíthatja a referenciát", "ui.construction.ribbon_label": "Segédvonalak", + "ui.construction.side_hint": "Szerkesztőegyenes: kattintson arra az oldalra, amerre a vonal halad; jobb kattintással újrakezdheti", "ui.context_menu": "Helyi menü", + "ui.continuity_crease": "Törés", + "ui.continuity_curvature": "Görbület", + "ui.continuity_curvature_change": "Görbületváltozás", "ui.continuity_g0": "G0 törés", "ui.continuity_g1": "G1 érintő", "ui.continuity_g2": "G2 görbület", "ui.continuity_gap": "Rés", + "ui.continuity_position": "Pozíció", + "ui.continuity_tangent": "Érintő", "ui.copy": "Másolás", "ui.corner": "Sarok", "ui.corners": "Sarkok", @@ -3992,6 +4511,7 @@ "ui.dark": "Sötét", "ui.default_modelling_orientation": "Alapértelmezett modellezési tájolás", "ui.delete": "Törlés", + "ui.delete_select_first": "Először jelölje ki a törlendőt: elemeket, testeket, komponenseket vagy vázlatgeometriát", "ui.depth": "Mélység", "ui.design": "Tervezés", "ui.design_properties.author": "Szerző", @@ -4006,6 +4526,40 @@ "ui.design_properties.project": "Projekt", "ui.design_properties.revision": "Revízió", "ui.design_saved": "Mentve ide: {path}", + "ui.details_access_caption": "A lapok megmutatják, hogy egy szerszám eléri-e őket a kiválasztott irányból.", + "ui.details_angle": "Szög", + "ui.details_continuity_caption": "A kijelölt varrat szerkesztése. A többi varrat megtartja a saját beállításait.", + "ui.details_continuity_stale": "Korábbi geometria: futtassa újra az elemzést a varrat szerkesztéséhez vagy a nézet ráállításához.", + "ui.details_copy_list": "Lista másolása", + "ui.details_curvature": "Görbülettűrés", + "ui.details_curvature_caption": "A lapok színe a helyi görbületi sugarukat mutatja.", + "ui.details_direction": "Szerszámirány", + "ui.details_draft_caption": "A lapok színe a húzási irányhoz mért szögüket mutatja.", + "ui.details_edit_seam": "Varrat szerkesztése", + "ui.details_fixture": "Komponensminta – csak mintaadatok", + "ui.details_fixture_caption": "Komponensminta szemléltető értékekkel; ez nem modelleredmény.", + "ui.details_fixture_problem": "Példa megállapítás hibával", + "ui.details_fixture_readout": "Példa mért érték", + "ui.details_flip": "Megfordítás", + "ui.details_gap": "Rés", + "ui.details_hatch": "Vágott lapok sraffozása", + "ui.details_jump": "Görbületugrás", + "ui.details_key": "Jelmagyarázat", + "ui.details_offset": "Eltolás", + "ui.details_plane": "Sík", + "ui.details_pull": "Húzási irány", + "ui.details_radius": "Sugár", + "ui.details_readout": "Leolvasás", + "ui.details_samples": "Minták", + "ui.details_seam": "{body} · {edge}. él", + "ui.details_settings": "Beállítások", + "ui.details_sharp_gap": "Éles vagy rés", + "ui.details_show_all": "Mind a(z) {count} megjelenítése", + "ui.details_smooth": "Sima", + "ui.details_stripes": "Csíkok", + "ui.details_target": "Geometriára állítás", + "ui.details_worst_seams": "Legrosszabb varratok", + "ui.details_zebra_caption": "A tükröződő csíkok megmutatják, milyen simán csatlakoznak a lapok.", "ui.diameter": "Átmérő", "ui.dimension": "Méret", "ui.direct_interaction": "Közvetlen interakció", @@ -4050,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "Az alkatrész másik fájlba lett mentve; az összeállítás továbbra is ide hivatkozik: {name}", "ui.edit_in_place_wait": "Várja meg, amíg a tervben futó művelet befejeződik", "ui.edit_section_analysis": "Metszetelemzés szerkesztése", + "ui.edit_sketch_empty": "Nincs szerkeszthető vázlat", "ui.ellipse": "Ellipszis", "ui.emboss_wrap_note": "Az egyetlen támogatott hengerhez érintő, merőleges vonalprofilok automatikusan a henger köré tekerednek. Válasszon ki egy falat a cél kiválasztásához.", "ui.end_radius": "Végi sugár", @@ -4060,12 +4615,15 @@ "ui.equation_explicit": "Explicit", "ui.equation_form": "Alak", "ui.equation_note": "A változó egyszerű szám: a sin(t) radiánban értelmezi. A mértékegység nélküli eredmény a terv mértékegységében értendő.", + "ui.equation_note_range": "A változó hossz, ahogy a tartománya is: keverje hosszparaméterekkel, és a sin() előtt ossza el egy hosszal. A mértékegység nélküli eredmény a terv mértékegységében értendő.", "ui.equation_parametric": "Parametrikus", + "ui.equation_variable_unit": "A változó a tartomány mértékegységét használja", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Egyenértékű sugár", "ui.expand": "Kibontás", + "ui.explode_needs_two_components": "A Robbantott nézet széthúzza a komponenseket, ezért a tervben legalább kettő kell belőlük (Új komponens, Terv beszúrása vagy Komponensek létrehozása testekből)", "ui.exportDxf": "DXF exportálása…", "ui.export_ellipsis_keymap": "Exportálás…", "ui.export_keymap_tip": "Billentyűk, S doboz kedvencei és az eszköztár, fájlként", @@ -4191,6 +4749,7 @@ "ui.hideOrigin": "Origó elrejtése", "ui.hidePlanes": "Síkok elrejtése", "ui.hideProfile": "Profil elrejtése", + "ui.hide_component_history": "Előzményeinek elrejtése", "ui.hide_origin_by_default": "Origó elrejtése alapértelmezetten", "ui.hide_origin_note": "Az új tervek az Origó mappa elrejtésével indulnak. A terv megtartja a saját Origó-beállítását, amint megjeleníti vagy elrejti.", "ui.history_back": "Egy lépéssel vissza", @@ -4198,6 +4757,7 @@ "ui.history_edge_hint": "kattintson duplán az élre", "ui.history_first": "Ugrás az elejére", "ui.history_forward": "Egy lépéssel előre", + "ui.history_hide_hidden": "Rejtett komponensek elrejtése", "ui.history_hide_names": "Nevek elrejtése", "ui.history_last": "Ugrás a végére", "ui.history_marker_tip": "Előzményjelölő: húzással visszagörgetheti a modellt; az új elemek ide kerülnek", @@ -4207,10 +4767,12 @@ "ui.history_play_button_show": "Lejátszás gomb megjelenítése", "ui.history_play_finish_action": "Az Előzmények lejátszása előtt fejezze be az aktuális műveletet", "ui.history_play_roll_back": "Lejátszás előtt mozgassa vissza az előzménymarkert", + "ui.history_show_hidden": "Rejtett komponensek megjelenítése", "ui.history_show_names": "Nevek megjelenítése", "ui.history_sketch_listed_under": "Itt szerepel: {feature}", "ui.history_title": "Előzmények", "ui.history_toggle_names": "Elemnevek megjelenítése vagy elrejtése", + "ui.history_waits_for_editor": "A Visszavonás, a Mégis és az Előzmények addig várnak, amíg az elemszerkesztő meg nem nyílik", "ui.hole": "Furat", "ui.hole_tap_type": "Furat menettípusa", "ui.hole_type": "Furat típusa", @@ -4226,6 +4788,7 @@ "ui.insert_design.saved_file": "A(z) {name} nem mentett módosításokat tartalmaz, ezért a mentett fájlja lett beszúrva. Mentse el, majd a Kapcsolatok frissítése paranccsal hozza át a módosításokat.", "ui.insert_design.unsaved": "Nem mentett módosítások", "ui.inspect": "Vizsgálat", + "ui.instances": "Példányok", "ui.intersect": "Metszet", "ui.isolate": "Elkülönítés", "ui.join": "Egyesítés", @@ -4234,12 +4797,14 @@ "ui.joints": "Csuklók", "ui.keyboard_shortcuts": "Billentyűparancsok", "ui.language": "Nyelv", + "ui.lasso_select": "Lasszó (húzzon szabadkézi hurkot: azt jelöli ki, ami teljesen belül van)", "ui.layout_compact": "Kompakt", "ui.layout_floating": "Lebegő", "ui.length": "Hossz", "ui.length_decimals": "Hossz tizedesjegyei", "ui.light": "Világos", "ui.line": "Vonal", + "ui.line_arc_hint": "Érintő ív: kattintson az ív végpontjára. Vonalakhoz álljon meg újra az utolsó ponton; jobb kattintás vagy Esc a befejezéshez", "ui.link_copies": "Azonos másolatok összekapcsolása", "ui.link_copies_keep": "Megtartás", "ui.link_copies_link": "Összekapcsolás", @@ -4328,6 +4893,7 @@ "ui.part_size_shared": "Újraépíti az alkatrészt, a hozzáadott elemeket lecserélve. A komponens minden előfordulása frissül.", "ui.paste": "Beillesztés", "ui.path": "Útvonal", + "ui.pattern_object_type_tip": "Testek: tömör alakzatok, a nézetben vagy a Böngészőben kijelölve; mindegyik egészében másolódik.\nElemek: az Előzmények lépései, például egy kihúzás vagy egy furat, az Előzményekben vagy az általuk létrehozott lapon kijelölve; a lépés megismétlődik.\nA vázlat egyik sem: a görbéit a vázlat saját Minta vagy Tükrözés parancsával ismételje, vagy húzza ki előbb.", "ui.pattern_on_path": "Minta útvonalon", "ui.perforate_margin_default": "az átmérőből", "ui.perforate_pitch": "Osztás", @@ -4354,12 +4920,17 @@ "ui.plugins_skipped": "{count} mappa nem olvasható.", "ui.plugins_version": "{version}", "ui.point": "Pont", + "ui.point_cloud_add_filter": "Szűrő hozzáadása…", "ui.point_cloud_auto_range": "Automatikus tartomány", "ui.point_cloud_color_by": "Színezés alapja", "ui.point_cloud_file_colors": "Fájl színei", + "ui.point_cloud_filter_by": "Szűrés alapja", "ui.point_cloud_height_high": "Legmagasabb", "ui.point_cloud_height_low": "Legalacsonyabb", + "ui.point_cloud_legend_filter": "A fenti jelmagyarázatban megjelenítve és elrejtve", "ui.point_cloud_no_file_colors": "A fájlnak nincsenek színei", + "ui.point_cloud_pause": "Szünet", + "ui.point_cloud_play": "Lejátszás", "ui.point_cloud_single_color": "Egyetlen szín", "ui.point_cloud_size": "Pontméret", "ui.point_cloud_units": "Fájl egységei", @@ -4368,6 +4939,11 @@ "ui.polygon": "Sokszög", "ui.preferences": "Beállítások", "ui.press_a_key": "nyomjon meg egy billentyűt…", + "ui.print_face_body_not_sent": "Ennek a lapnak a teste nincs elküldve: előbb add hozzá a Testekhez", + "ui.print_face_cleared": "{body}: nyomtatási lap törölve", + "ui.print_face_input": "Nyomtatási lap", + "ui.print_face_pick": "Válassz ki egy tömör test egy sík lapját, hogy az legyen a nyomtatási lap", + "ui.print_face_set": "{body}: nyomtatási lap beállítva; a Küldés szeletelőnek erre a lapra fekteti a testet", "ui.profile": "Profil", "ui.profile_plane": "Profilsík", "ui.profiles": "Profilok", @@ -4383,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Mérés…", + "ui.properties.measuring_bodies": "Mérés… {done} / {total} test", "ui.properties.measuring_failed": "A mérés leállt, mielőtt befejeződött volna.", "ui.properties.principal_axis": "{number}. főtengely", "ui.properties.principal_moments": "Fő tehetetlenségi nyomatékok", @@ -4431,6 +5008,7 @@ "ui.revolve": "Forgatás", "ui.ribbon_exit": "Kilépés", "ui.ribbon_labels": "Szöveg megjelenítése a menüszalag ikonjai alatt", + "ui.ribbon_menus_skip_pinned": "A rögzített parancsok kihagyása a legördülő menükből", "ui.ribbon_pin_footer": "A rögzített parancsok megjelennek a menüszalagon. Egy sor fölé víve rögzíthető vagy feloldható.", "ui.ribbon_workspace": "Munkaterület", "ui.right": "Jobb", @@ -4449,6 +5027,7 @@ "ui.selectOther": "Más kijelölése…", "ui.selectTangentChain": "Érintőlánc kijelölése", "ui.select_all": "Összes kijelölése", + "ui.select_components_by_face": "Komponensek kijelölése (egy lap a komponensét jelöli ki)", "ui.selection": "Kijelölés", "ui.selection_modifiers": "Kijelölési módosítók", "ui.selection_shift_add_only": "Shift+kattintás eltávolítás nélkül hozzáad", @@ -4474,6 +5053,7 @@ "ui.showDimension": "Méret megjelenítése", "ui.showOrigin": "Origó megjelenítése", "ui.showPlanes": "Síkok megjelenítése", + "ui.show_component_history": "Előzményeinek megjelenítése", "ui.show_constraints": "Kényszerek", "ui.show_construction_geometries": "Szerkesztő geometriák", "ui.show_dimensions": "Méretek", @@ -4490,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Kijelölési szűrő", "ui.sketch_modifiers": "Vázlatmódosítók", "ui.sketch_project_geometry": "Geometria", + "ui.sketch_report.all_constrained": "Minden teljesen kényszerezett.", + "ui.sketch_report.dof": "Szabadságfokok", + "ui.sketch_report.loose": "Nem teljesen kényszerezett", + "ui.sketch_report.status": "Állapot", + "ui.sketch_report.title": "Vázlatjelentés", "ui.sketch_scale": "Vázlat léptéke", "ui.sketches": "Vázlatok", "ui.slice": "Szeletelés", @@ -4585,19 +5170,31 @@ "ui.view_angles": "Nézetszögek", "ui.view_angles_convention": "Fok a felfelé mutató tengely körül. Az elfordulás 0° az elölnézet, 90° a bal oldali, −90° a jobb oldali, 180° a hátulnézet; a 90°-os billentés a felülnézet; a pozitív gördülés az óramutató járásával megegyező irányba forgatja a modellt.", "ui.view_angles_help": "Megjeleníti a nézet billentését, elfordulását és gördülését fokban, valamint a vetítési módját a tájolásjelző alatt. Kattintson a kijelzőre a pontos szögek beírásához.", + "ui.view_angles_lock": "{axis} zárolása", "ui.view_angles_ortho": "Ortog.", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Billentés", "ui.view_angles_readout": "Billentés {pitch} · Elfordulás {yaw} · Gördülés {roll}", "ui.view_angles_roll": "Gördülés", + "ui.view_angles_unlock": "{axis} feloldása", "ui.view_angles_yaw": "Elfordulás", + "ui.view_angles_zero": "{axis} beállítása 0°-ra", "ui.view_centre": "Nézet középpontja", "ui.viewport_status_clear": "Kikapcsolás: {name}", "ui.viewport_status_clear_hint": "Kikapcsolás: {name} · Esc", + "ui.viewport_status_edges": "{count} él", + "ui.viewport_status_from": "{direction} felől", "ui.viewport_status_key": "Jelmagyarázat megjelenítése: {name}", "ui.viewport_status_minimum_radius": "Minimális sugár", "ui.viewport_status_pairs": "{count} pár", + "ui.viewport_status_section_hatch": "{setting} · sraffozás", + "ui.viewport_status_section_plane": "Aktuális sík", + "ui.viewport_status_section_tilted": "megdöntve · {offset}", "ui.viewport_status_stripes": "{count} csík", + "ui.viewport_status_summary_clear": "Minden kikapcsolása", + "ui.viewport_status_summary_heading": "Ebben a nézetben", + "ui.viewport_status_summary_label": "{name} és még {count} elem", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Téma követése", "ui.visual_shaded_hidden_edges": "Árnyalt rejtett élekkel", "ui.visual_shaded_with_edges": "Árnyalt élekkel", @@ -4634,10 +5231,12 @@ "update.button": "Frissítés", "update.button_version": "Frissítés erre: {version}", "update.check_automatically": "Frissítések automatikus keresése", + "update.check_for_updates": "Frissítések keresése", "update.check_now": "Keresés most", + "update.check_unavailable": "Ehhez a telepítéshez nem érhető el a frissítések keresése.", "update.checking": "Keresés…", "update.copy": "Másolás", - "update.dmg_opened": "A lemezkép meg van nyitva és ellenőrizve: húzza a SolidCraftot az Alkalmazások mappába, lecserélve a régi példányt, majd indítsa újra a SolidCraftot.", + "update.dmg_opened": "A lemezkép meg van nyitva és ellenőrizve: lépjen ki a SolidCraftból, húzza az új SolidCraftot az Alkalmazások mappába, lecserélve a régi példányt, majd nyissa meg újra a SolidCraftot.", "update.download": "Letöltés", "update.download_open": "Letöltés és megnyitás", "update.downloading": "Letöltés és ellenőrzés… {done}/{total} MB", @@ -4648,11 +5247,13 @@ "update.installed": "A SolidCraft {version} telepítve. Indítsa újra a használatához.", "update.installer_started": "A telepítő a SolidCraft bezárásakor indul.", "update.later": "Emlékeztessen később", + "update.managed": "Frissítés érhető el: frissítse a SolidCraftot itt: {manager}", "update.no_notes": "Ehhez a kiadáshoz nincs megjegyzés.", "update.package_hint": "Ez a példány egy {kind} csomagból származik. Töltse le az új csomagot, majd telepítse ezzel:", "update.prefs_dev": "Ez fejlesztői build ({version}): nem keres frissítéseket.", "update.prefs_flatpak": "A Flatpak frissíti ezt a példányt ({version}): futtassa a(z) {command} parancsot, vagy használja a szoftverközpontot. A SolidCraft nem keres.", "update.prefs_label": "Frissítések", + "update.prefs_managed": "Ez a SolidCraft {version}, kezelője: {manager}. A keresés a GitHubtól kéri a legújabb kiadást, és semmi mást nem küld; a SolidCraftot itt frissítse: {manager}.", "update.prefs_note": "Ez a SolidCraft {version} ({kind}). A keresés a GitHubtól kéri a legújabb kiadást, és semmi mást nem küld.", "update.prefs_web": "Töltse újra az oldalt a legújabb webalkalmazás megszerzéséhez. Ha a hálózat nem érhető el, vagy a frissítés időben nem tud letöltődni, a mentett verzió nyílik meg; a folyamatban lévő letöltés a következő újratöltéshez folytatódik.", "update.refresh_checking": "A legújabb kiadás keresése…", @@ -4679,6 +5280,7 @@ "web.open_link": "Megnyitja a csatolt tervet?", "web.open_link_confirm": "Mentetlen módosítások vannak. Megnyitja a csatolt tervet új fülön?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ választás · Enter / Tab kiegészítés · Esc elvetés", + "↑ ↓ choose · Enter applies this value": "↑ ↓ választás · Enter alkalmazza ezt az értéket", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ választás · Enter alkalmazza a beírtakat · Esc elvetés", "⌘Enter continues on GitHub.": "A ⌘Enter a GitHubon folytatja." } diff --git a/assets/locales/id.json b/assets/locales/id.json index f416c69cf..4df00ea85 100644 --- a/assets/locales/id.json +++ b/assets/locales/id.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "PERMUKAAN BLEND", "BOUNDARY SURFACE": "PERMUKAAN BATAS", "BROWSER": "PENJELAJAH", + "Back to the original order": "Kembali ke urutan asli", "Ball": "Bola", "Bar": "Batang", "Base Center": "Pusat Dasar", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Desain yang Anda buka atau simpan muncul di sini.", "Determined by To Object. Choose Angle to edit the angular extent.": "Ditentukan oleh To Object. Pilih Angle untuk mengedit rentang sudut.", "Diameter": "Diameter", + "Did this assembly open the wrong way up?": "Apakah rakitan ini terbuka dengan orientasi yang salah?", + "Did this part open the wrong way up?": "Apakah part ini terbuka dengan orientasi yang salah?", "Dimension new shapes": "Beri dimensi bentuk baru", "Direction": "Arah", "Discard": "Buang", @@ -474,6 +477,7 @@ "Rectangular": "Persegi panjang", "Rectangular Tube": "Pipa Persegi Panjang", "Reference face": "Muka referensi", + "Reference plane": "Bidang referensi", "Relief Depth": "Kedalaman Relief", "Relief Width": "Lebar Relief", "Remove Tools": "Hapus Alat", @@ -553,6 +557,7 @@ "Section": "Penampang", "Section (optional)": "Penampang (opsional)", "Section position": "Posisi penampang", + "Sections": "Penampang", "Sections (one sketch each)": "Penampang (satu sketsa per penampang)", "Select Other": "Pilih Lainnya", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: tahan tombol kiri diam di model (atau klik kanan › Select Other…) untuk mendaftar semua yang ada di bawah kursor; klik lagi di titik yang sama untuk memilih benda berikutnya. Klik dua kali tombol tengah untuk ke Home (Preferensi › Navigasi).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Snap ke pusat muka dan tepi", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft tidak dapat mengirim laporan secara langsung. Kirim di GitHub; token tidak diperlukan di aplikasi.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft tertutup sebelum desain ini disimpan. Simpan otomatis terakhirnya dapat dibuka.", + "Sort A to Z": "Urutkan A ke Z", + "Sort Z to A": "Urutkan Z ke A", "Spacing 2 must be a non-zero number": "Jarak antar 2 harus berupa bilangan bukan nol", "Spacing must be a non-zero number": "Jarak antar harus berupa bilangan bukan nol", "Specialise": "Spesialisasikan", @@ -601,6 +608,7 @@ "Square": "Persegi", "Stand it up": "Tegakkan", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Tegakkan: putaran seperempat terhadap X, sebagai satu fitur Move yang dapat dibatalkan.", + "Stand this assembly up?": "Tegakkan rakitan ini?", "Stand this part up?": "Tegakkan part ini?", "Start angle": "Sudut awal", "Start bulge": "Bulge awal", @@ -772,6 +780,8 @@ "at the face": "di muka", "bom.group_children": "Sub-part dalam baris part induknya", "browser.body_name": "Bodi{number}", + "browser.calibrate_click_a": "Klik gambar untuk Titik A, atau ketik koordinatnya.", + "browser.calibrate_click_b": "Klik gambar untuk Titik B, atau ketik koordinatnya.", "browser.calibrate_title": "Kalibrasi: {name}", "browser.capture_many": "{count} komponen dipindahkan tetapi posisinya belum ditangkap.", "browser.capture_note": "Tangkap menyimpan posisi baru; Kembalikan memulihkannya.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (lampiran hilang)", "browser.sketch_editing": "{name} (sedang diedit)", "browser.sketch_name": "Sketsa{number}", + "browser.sketches_to_parts_already_in_part": "sudah berada di part-nya", + "browser.sketches_to_parts_design_body": "pada bodi desain itu sendiri", + "browser.sketches_to_parts_moved": "{moved} sketsa dipindahkan ke part tempat sketsa itu berada", + "browser.sketches_to_parts_no_exact_attachment": "pada muka tanpa lampiran yang tepat", + "browser.sketches_to_parts_not_on_face": "tidak berada di muka sebuah part", + "browser.sketches_to_parts_part_missing": "part-nya sudah tidak ada", + "browser.sketches_to_parts_result": "{moved} sketsa dipindahkan ke part tempat sketsa itu berada; {stayed} tetap di tempatnya: {why}", "browser.units": "Satuan: {units}", "cam.flat": "Muka datar", "cam.follower": "Pengikut", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Ambil Tampilan", "cmd.appearance_replace": "Ganti Tampilan", "cmd.assembly_bom": "Daftar Material (BOM)", + "cmd.assembly_mass_properties": "Properti massa", + "cmd.body.print_face": "Permukaan cetak", "cmd.body_rename": "Ganti Nama Bodi", "cmd.browser_collapse_all": "Ciutkan Semua", "cmd.browser_expand_all": "Perluas Semua", @@ -842,6 +861,7 @@ "cmd.component_extract": "Ekstrak ke File", "cmd.component_finish_edit": "Selesai Edit", "cmd.component_from_bodies": "Buat Komponen dari Bodi", + "cmd.component_hide_history": "Sembunyikan Riwayat Komponen", "cmd.component_insert_design": "Sisipkan Desain", "cmd.component_links": "Daftar Tautan", "cmd.component_list": "Daftar Komponen", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Pindahkan Bodi ke Komponen", "cmd.component_move_features": "Pindahkan Fitur ke Komponen", "cmd.component_move_sketches": "Pindahkan Sketsa ke Komponen", + "cmd.component_move_sketches_to_parts": "Pindahkan Sketsa ke Part Masing-masing", "cmd.component_paste_from_design": "Tempel dari Desain Lain", "cmd.component_paste_new": "Tempel Baru", "cmd.component_properties": "Properti Fisik Komponen", @@ -857,6 +878,7 @@ "cmd.component_rename": "Ganti Nama Komponen", "cmd.component_replace_with_link": "Ganti dengan Tautan", "cmd.component_revert_position": "Kembalikan Posisi", + "cmd.component_show_history": "Tampilkan Riwayat Komponen", "cmd.component_unlock": "Buka Kunci Isi", "cmd.component_update_links": "Perbarui Tautan", "cmd.config_activate": "Aktifkan Konfigurasi", @@ -867,6 +889,7 @@ "cmd.config_rule": "Aturan Konfigurasi", "cmd.config_rules": "Aturan Konfigurasi", "cmd.config_table": "Tampilkan Tabel Konfigurasi", + "cmd.construct.plane.axis_point": "Bidang Melalui Sumbu dan Titik", "cmd.construct_axis_edge": "Sumbu Melalui Tepi", "cmd.construct_axis_normal_to_face": "Sumbu Tegak Lurus Muka", "cmd.construct_axis_through_cylinder": "Sumbu Melalui Silinder/Kerucut/Torus", @@ -915,6 +938,11 @@ "cmd.explode_show": "Tampilkan Tampilan Urai", "cmd.expr_evaluate": "Evaluasi Ekspresi", "cmd.face_delete": "Hapus Muka", + "cmd.file.export_3mf": "Ekspor 3MF", + "cmd.file.export_obj": "Ekspor OBJ", + "cmd.file.export_step": "Ekspor STEP", + "cmd.file.export_stl": "Ekspor STL", + "cmd.file.export_urdf": "Ekspor URDF", "cmd.file_export": "Ekspor", "cmd.file_insert_mesh": "Sisipkan Mesh", "cmd.file_insert_step": "Sisipkan STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Aktifkan Warna Komponen", "cmd.inspect_colored_components_disable": "Nonaktifkan Warna Komponen", "cmd.inspect_compare": "Bandingkan Bodi", + "cmd.inspect_compare_picture": "Bandingkan dengan Gambar", "cmd.inspect_continuity": "Analisis Kontinuitas", "cmd.inspect_curvature_comb": "Analisis Sisir Kelengkungan", "cmd.inspect_curvature_map": "Analisis Peta Kelengkungan", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Edit Awan Titik", "cmd.pointcloud_insert": "Sisipkan Awan Titik", "cmd.pointcloud_list": "Awan Titik", + "cmd.render.compare.divider": "Pindahkan Pembagi Perbandingan Render", + "cmd.render.result.discard": "Buang Hasil Render", + "cmd.render.result.select": "Pilih Hasil Render", "cmd.render_aging_describe": "Penuaan Permukaan Berlapis", "cmd.render_backends": "Backend Render", "cmd.render_batch": "Render Semua Bidikan", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline Titik Kontrol (Derajat 5)", "cmd.sketch_spline_fit_point": "Spline Titik Fit", "cmd.sketch_spline_insert_point": "Tambah Titik Spline", + "cmd.sketch_spline_remove_point": "Hapus Titik Spline", "cmd.sketch_spline_reverse": "Balik Arah Spline", "cmd.sketch_spun_profile": "Profil Putar", "cmd.sketch_toggle_diameter": "Beralih Radius / Diameter", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Pindahkan Penanda Linimasa", "cmd.timeline_stop": "Hentikan Riwayat", "cmd.timeline_suppress": "Tekan Fitur", + "cmd.ui.assistant": "Alihkan Asisten", "cmd.view.render_browser": "Penjelajah Render", "cmd.view.render_dock": "Pindah Dok Render", "cmd.view.render_focus": "Tampilan Fokus Render", + "cmd.view.status_details": "Detail Status Viewport", "cmd.view.status_items": "Item Status Viewport", "cmd.view_ambient_occlusion": "Ambient Occlusion", "cmd.view_angle_readout": "Sudut Tampilan", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Alat navigasi", "cmd.view_top": "Tampilan Atas", "cmd.view_visual_style": "Gaya visual", + "color.blue": "Biru", "color.copy": "Klik untuk menyalin nilai warna", "color.edit": "Klik untuk mengedit warna", "color.gamma": "Menampilkan nilai warna dalam ruang gamma 0-255", + "color.green": "Hijau", "color.hex": "Hex", "color.hex_help": "Masukkan #rrggbb atau #rrggbbaa; enam digit mempertahankan opasitas", "color.hex_hint": "#rrggbb", "color.hue": "Rona", "color.linear": "Menampilkan nilai warna dalam ruang linear 0-1", + "color.recent": "Warna terbaru", + "color.recent_help": "Warna yang Anda pilih di kolom warna mana pun muncul di sini", + "color.red": "Merah", + "color.saturation": "Saturasi (persen)", "color.saturation_value": "Saturasi dan nilai", "color.selected": "Warna terpilih", + "color.step_down": "Turunkan", + "color.step_up": "Naikkan", + "color.value": "Nilai, yaitu kecerahan (persen)", "config.column_filter_empty": "Tidak ada kolom yang cocok", + "config.rule_parameter_columns": "Hanya parameter yang memiliki kolom di tabel yang dicantumkan. Tambahkan satu dengan Tambah Kolom (+) untuk memakainya di sini.", + "config.rule_suppression_columns": "Hanya fitur yang memiliki kolom Tekan di tabel yang dicantumkan. Tambahkan satu dengan Tambah Kolom (+) untuk mengendalikannya di sini.", "contact.components_count": "{count} komponen", "contact.enabled_label": "aktif", "coupling.gear_1": "Roda Gigi 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Klik dimensi penggerak lain untuk menyisipkan namanya", "dialog.dimension_name": "Dimensi: {name}", "dialog.edit_title": "EDIT {title}", + "dialog.no_shown_body": "Tidak ada bodi yang ditampilkan untuk diubah: tampilkan satu, atau pilih Bodi Baru", + "dialog.pattern_sketch_not_object": "Pilih bodi atau fitur: sketsa bukan keduanya. Ulangi kurvanya dengan Pola atau Cermin milik sketsa itu sendiri, atau ekstrusi dulu.", "dialog.select": "↖ Pilih", "dialog.selected_count": "↖ {count} terpilih", + "dialog.selection_constraint": "Batasan {id}", + "dialog.selection_external_curve": "{sketch} · kurva {id}", "dialog.selection_guidance": "Pilih input untuk mengubahnya. Klik objek terpilih untuk menghapusnya; Ctrl/Cmd-klik juga mengalihkannya. Tinjau pratinjau, lalu tekan OK.", + "dialog.selection_midpoint": "Titik tengah · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} dari {total}: Pilih {input}", "dialog.step": "Langkah", "document.changed_on_disk": "{name} berubah di disk", @@ -1380,26 +1432,244 @@ "from the rule": "dari aturan", "help.apache": "Lisensi Apache 2.0", "help.appearance.assign": "Memberi bodi, muka, atau komponen terpilih warna atau tampilan material, tanpa mengubah bobotnya. Gunakan untuk membedakan part atau melihat pratinjau hasil akhir.", + "help.assembly.bom": "Mencantumkan part dalam desain atau komponen beserta jumlahnya, menurut nomor part, dan dapat menyimpan daftar itu sebagai CSV atau JSON. Gunakan sebagai daftar part untuk pemesanan dan perakitan.", "help.attributions": "Atribusi (ATTRIBUTION.md)", "help.build": "Versi {version} · commit {commit} · dibangun {date}", + "help.canvas.decal": "Menempatkan gambar pada muka datar model, seperti stiker. Gunakan untuk menampilkan label, logo, atau pola cetak pada sebuah part.", + "help.canvas.edit": "Mengubah sebuah kanvas: posisi, ukuran, sudut, opasitas, pencerminan, visibilitas, atau namanya. Gunakan untuk menyelaraskan gambar referensi dengan sketsa yang Anda jiplak di atasnya.", + "help.canvas.insert": "Menempatkan gambar PNG atau JPEG pada bidang atau muka sebagai referensi tembus pandang. Gunakan untuk menjiplak foto atau gambar di dalam sketsa, dengan gambar diskalakan ke ukuran yang diketahui.", + "help.component.break_link": "Memutus komponen tertaut dari file desainnya, dengan bodinya dibiarkan apa adanya. Gunakan bila part tidak perlu lagi mengikuti perubahan pada file aslinya.", + "help.component.capture_position": "Mempertahankan posisi part yang Anda pindahkan secara manual, sehingga posisi itu menjadi letak part tersebut. Gunakan setelah menyeret part ke tempatnya yang tidak ditahan sambungan apa pun.", + "help.component.create": "Menambahkan komponen baru yang kosong ke desain, di dalam komponen aktif kecuali Anda memilih induk lain. Gunakan untuk memberi bagian baru dari rakitan tempatnya sendiri bagi bodi dan sketsa.", "help.component.finish_edit": "Menyimpan part yang sedang diedit di tempat, kembali ke rakitannya, dan memperbarui rakitan dari part tersebut. Gunakan setelah perubahan Anda pada part tertaut selesai.", + "help.component.from_bodies": "Mengubah setiap bodi terpilih menjadi komponen tersendiri, dinamai sesuai bodinya. Gunakan bila desain yang dibangun dari bodi lepas perlu menjadi rakitan yang part-nya dapat disambung dan dipindahkan.", + "help.component.insert_design": "Menyisipkan desain tersimpan lain sebagai komponen yang tertaut ke filenya, dengan bodi solidnya ditempatkan seperti di sana. Gunakan untuk memakai ulang part dalam rakitan dan menerima perubahan berikutnya lewat Perbarui Tautan.", + "help.component.properties": "Menampilkan volume, massa, pusat massa, dan momen inersia sebuah komponen, berdasarkan material bodinya. Gunakan untuk memeriksa bobot dan keseimbangan sebuah rakitan.", + "help.component.revert_position": "Mengembalikan part yang Anda pindahkan secara manual ke tempat semula, dengan membuang perpindahan yang tidak ditangkap. Gunakan untuk membatalkan percobaan pemindahan dalam rakitan.", + "help.component.update_links": "Membaca ulang file desain tertaut dan mengganti bodi yang berubah. Gunakan setelah mengedit part yang dipakai rakitan ini.", + "help.config.configure": "Menambahkan parameter, fitur, material, atau tampilan sebagai kolom tabel konfigurasi. Gunakan untuk membuat varian dari satu desain, seperti berbagai ukuran sebuah part.", + "help.config.preview": "Memeriksa bahwa satu baris tabel konfigurasi dapat dibangun ulang, tanpa mengubah desain atau riwayatnya. Gunakan sebelum beralih ke varian yang belum Anda yakini.", + "help.config.rules": "Menampilkan aturan tabel konfigurasi, barisnya, dan baris mana yang aktif. Gunakan untuk melihat bagaimana varian sebuah desain diatur.", + "help.config.table": "Menampilkan tabel konfigurasi: satu baris per varian, satu kolom per parameter atau fitur, dan apakah desain masih cocok dengan baris aktif. Gunakan untuk meninjau varian sebuah desain.", "help.connect_note": "Mulai ulang setiap asisten untuk memuat server SolidCraft. Setiap file dicadangkan sebagai .bak sebelum diubah.", "help.connect_title": "Hubungkan asisten AI", + "help.construct.axis.edge": "Membuat sumbu konstruksi sepanjang tepi lurus atau garis sketsa. Gunakan sebagai sumbu untuk revolve, pola melingkar, atau sambungan.", + "help.construct.axis.normal_to_face": "Membuat sumbu konstruksi melalui sebuah titik, tegak lurus terhadap sebuah muka. Gunakan sebagai sumbu yang menjulur lurus keluar dari permukaan.", + "help.construct.axis.through_cylinder": "Membuat sumbu konstruksi melalui pusat muka silinder, kerucut, atau torus, atau tepi melingkar. Gunakan untuk memutar fitur atau membuat polanya mengelilingi part bulat.", + "help.construct.axis.two_planes": "Membuat sumbu konstruksi di tempat dua bidang atau muka datar bertemu. Gunakan bila sumbu yang Anda perlukan adalah garis di antara dua muka.", + "help.construct.axis.two_points": "Membuat sumbu konstruksi melalui dua titik, titik sudut, atau titik sketsa. Gunakan untuk sumbu yang membentang di antara dua posisi yang diketahui.", + "help.construct.plane.along_path": "Membuat bidang konstruksi tegak lurus terhadap sebuah tepi atau kurva, pada suatu posisi di sepanjangnya. Gunakan untuk menggambar sketsa profil bagi sweep atau penampang sebuah jalur.", + "help.construct.plane.at_angle": "Membuat bidang konstruksi yang diputar dengan suatu sudut dari sebuah bidang atau muka, terhadap sebuah sumbu atau tepi. Gunakan untuk sketsa miring, seperti braket bersudut.", + "help.construct.plane.axis_point": "Membuat bidang konstruksi yang memuat sebuah sumbu dan sebuah titik di luar sumbu itu. Pilih sebuah origin atau sumbu konstruksi, sebuah tepi lurus atau garis sketsa, lalu sebuah titik sudut, titik sketsa, atau titik konstruksi. Titik yang berada pada sumbu tidak dapat menentukan satu bidang yang unik.", + "help.construct.plane.midplane": "Membuat bidang konstruksi tepat di tengah antara dua bidang atau muka datar, atau membagi dua keduanya di tempat mereka bertemu pada suatu sudut. Gunakan sebagai bidang simetri untuk pencerminan.", + "help.construct.plane.offset": "Membuat bidang konstruksi yang sejajar dengan sebuah bidang atau muka datar, pada suatu jarak atau melalui sebuah titik. Gunakan untuk menggambar sketsa pada ketinggian tertentu di atas sebuah muka.", + "help.construct.plane.perpendicular": "Membuat bidang konstruksi yang memuat sebuah garis atau tepi dan berdiri tegak lurus terhadap sebuah bidang atau muka. Gunakan untuk menggambar sketsa tegak pada model sepanjang sebuah tepi.", + "help.construct.plane.tangent": "Membuat bidang konstruksi yang menyentuh silinder, kerucut, bola, atau torus pada sebuah titik. Gunakan untuk menggambar sketsa di sisi part bulat.", + "help.construct.plane.three_points": "Membuat bidang konstruksi melalui tiga titik. Gunakan untuk bidang yang ditentukan oleh posisi pada model, seperti tiga sudut.", + "help.construct.plane.two_edges": "Membuat bidang konstruksi melalui dua tepi lurus atau garis yang terletak pada satu bidang. Gunakan untuk bidang yang melintasi sebuah part, misalnya melalui dua tepi yang berseberangan.", + "help.construct.point.along_path": "Membuat titik konstruksi pada suatu posisi di sepanjang tepi atau kurva. Gunakan sebagai referensi di suatu titik pada jalur.", + "help.construct.point.center": "Membuat titik konstruksi di pusat tepi melingkar, lingkaran atau busur sketsa, bola, atau torus. Gunakan sebagai referensi untuk lubang, sumbu, dan sambungan.", + "help.construct.point.edge_plane": "Membuat titik konstruksi di tempat sebuah tepi atau garis menembus sebuah bidang atau muka datar. Gunakan untuk menandai tempat sebuah jalur memotong bidang.", + "help.construct.point.three_planes": "Membuat titik konstruksi di tempat tiga bidang atau muka datar bertemu. Gunakan sebagai referensi sudut, bahkan bila model tidak memiliki titik sudut di sana.", + "help.construct.point.two_edges": "Membuat titik konstruksi di tempat dua tepi atau garis bertemu, atau paling berdekatan. Gunakan sebagai referensi pada sudut virtual.", + "help.construct.point.vertex": "Membuat titik konstruksi pada titik sudut atau titik sketsa. Gunakan sebagai referensi yang tetap ada saat sketsa atau bodi di sekitarnya disembunyikan.", + "help.contact.check": "Mencantumkan pasangan part dalam set kontak yang saling menembus pada posisinya saat ini. Gunakan untuk menemukan tabrakan sebelum Anda menggerakkan sambungan atau menjalankan studi gerak.", + "help.contact.create": "Mengelompokkan dua part atau lebih ke dalam satu set kontak, yang bodinya dijaga agar tidak saling menembus saat sambungan bergerak. Gunakan untuk part yang harus berhenti saat bersentuhan, seperti tuas terhadap penahannya.", + "help.contact.disable_all": "Mematikan kontak, sehingga sambungan yang digerakkan dan studi gerak tidak lagi berhenti di tempat part bersentuhan. Gunakan untuk menggerakkan part dengan bebas lagi, atau agar rakitan besar tetap responsif.", + "help.contact.edit": "Mengubah sebuah set kontak: part yang dimuatnya, namanya, atau apakah ditekan; set juga dapat dihapus. Gunakan untuk menyesuaikan part mana yang dijaga agar tidak saling menembus.", + "help.contact.enable_all": "Memasukkan setiap part rakitan ke dalam satu set kontak, sehingga tidak ada dua part yang dapat saling menembus saat sambungan bergerak. Gunakan untuk pemeriksaan cepat seluruh mekanisme.", + "help.contact.enable_sets": "Menyalakan kontak untuk set kontak yang Anda definisikan, sehingga sambungan yang digerakkan dan studi gerak berhenti di tempat part-nya akan saling menembus. Gunakan untuk mengembalikan set Anda setelah kontak dimatikan.", + "help.contact.list": "Mencantumkan set kontak dalam desain, part di setiap set, dan apakah kontak menyala. Gunakan untuk memeriksa bagaimana kontak diatur sebelum Anda menggerakkan rakitan.", + "help.document.inspect": "Menampilkan ringkasan desain: komponen, bodi, sketsa, fitur, dan parameternya. Gunakan untuk memahami isi desain yang tidak Anda buat sendiri.", + "help.document.units": "Mengubah satuan yang dipakai desain untuk menampilkan panjang, seperti mm atau inci. Geometri tetap berukuran sama; hanya tampilan dan angka polos yang mengikuti.", + "help.edit.checkpoint": "Mengingat desain, sketsa aktif, dan riwayat urungkan sebagaimana keadaannya sekarang. Gunakan sebelum mencoba sesuatu yang berisiko dan mungkin ingin Anda urungkan.", + "help.edit.restore_checkpoint": "Kembali ke sebuah checkpoint, termasuk riwayat urungkan. Gunakan untuk membuang semua yang dilakukan sejak checkpoint dalam satu langkah.", + "help.explode.create": "Membuat tampilan urai yang mendorong part menjauh dari pusat rakitan, atau sesuai perpindahan yang Anda atur. Gunakan untuk menunjukkan cara rakitan dipasang, untuk petunjuk atau presentasi.", "help.face.delete": "Menghapus muka terpilih dan membiarkan muka di sekitarnya menutup celah, atau membiarkan celah terbuka sebagai permukaan. Gunakan untuk menghilangkan tepi membulat, lubang, atau boss yang menghalangi.", + "help.file.insert_mesh": "Menambahkan file 3MF, STL, OBJ, PLY, atau glTF ke desain sebagai bodi mesh dalam komponen baru. Gunakan untuk menaruh model hasil unduhan atau hasil pindai di samping desain Anda sebagai referensi.", + "help.file.insert_step": "Menambahkan file STEP, IGES, FreeCAD, atau Rhino ke desain sebagai bodi solid dalam komponen baru; part sebuah rakitan menjadi komponen bersarang. Gunakan untuk membawa masuk model dari pemasok atau program CAD lain.", + "help.file.save_mesh": "Menyimpan bodi sebagai mesh STL, 3MF, atau OBJ, dengan kehalusan muka lengkung sesuai pilihan Anda. Gunakan untuk menyiapkan part untuk pencetakan 3D atau untuk program yang membaca mesh.", + "help.file.send_to_slicer": "Menyimpan bodi terpilih sebagai file 3MF dan membukanya di slicer yang Anda pilih. Gunakan untuk beralih dari model ke pencetakan dalam satu langkah.", "help.font_details": "Antarmuka memakai font bawaan egui (Ubuntu Light dan Hack, di bawah Ubuntu Font Licence dan lisensi MIT/Bitstream Vera; Noto Emoji dan font ikon emoji, di bawah OFL dan MIT). Teks sketsa memakai Liberation Sans (SIL OFL 1.1). Paket font opsional Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), tidak disertakan dalam build SolidCraft.", "help.fonts": "Font", + "help.frame.member": "Menempatkan profil, seperti tabung atau ekstrusi aluminium, sepanjang garis sketsa rangka, satu batang per garis. Gunakan untuk membangun rangka, rak, dan struktur las.", + "help.inspect.accessibility": "Mewarnai muka yang dapat dijangkau alat dari satu arah, dan yang tidak. Gunakan untuk memeriksa part untuk pemesinan atau pencetakan dari sisi itu.", + "help.inspect.center_of_mass": "Menampilkan pusat massa bodi, masing-masing sendiri dan semuanya bersama, dengan massa jenis seragam. Gunakan untuk memeriksa keseimbangan dan di mana part akan terguling.", + "help.inspect.colored_components": "Memberi setiap komponen warna sementaranya sendiri, tanpa mengubah tampilan yang ditetapkan. Gunakan untuk membedakan part rakitan sekilas pandang.", + "help.inspect.compare": "Membandingkan dua bodi dan menampilkan di mana yang satu memiliki material yang tidak dimiliki yang lain, beserta volume dan deviasinya. Gunakan untuk memeriksa part yang diubah atau diimpor terhadap aslinya.", + "help.inspect.continuity": "Memeriksa seberapa mulus muka bertemu di sepanjang tepinya: celah, patahan, atau lompatan kelengkungan, dan mewarnai jahitannya. Gunakan untuk menemukan tempat permukaan tidak menyatu dengan bersih.", + "help.inspect.curvature_comb": "Menggambar sisir pada kurva, tepi, atau muka yang giginya menunjukkan seberapa kuat kelengkungannya. Gunakan untuk menemukan bagian datar, patahan, dan kelengkungan yang tidak rata.", + "help.inspect.curvature_map": "Mewarnai muka menurut seberapa kuat kelengkungannya, merah di tempat radiusnya kecil. Gunakan untuk menemukan bagian yang lengkungannya tajam dan menilai kehalusan permukaan.", + "help.inspect.draft": "Mewarnai muka menurut sudut draft-nya terhadap arah tarik, dan menandai yang sudutnya terlalu kecil. Gunakan untuk memeriksa part sebelum pencetakan atau pengecoran.", + "help.inspect.environment_map": "Menampilkan model dengan hasil akhir reflektif seperti cermin. Gunakan untuk menilai alur permukaan dari cara pantulan mengalir di atasnya.", + "help.inspect.interference": "Menemukan bodi yang tumpang tindih dan menampilkan setiap tumpang tindih beserta volumenya. Gunakan untuk memeriksa rakitan terhadap part yang bertabrakan.", + "help.inspect.isocurve": "Menggambar kurva isoparametrik pada muka, yaitu grid tempat permukaan dibangun. Gunakan untuk melihat bagaimana permukaan mengalir dan di mana ia menumpuk.", + "help.inspect.measure": "Mengukur panjang, jarak, sudut, luas, dan radius antara apa yang Anda pilih, atau volume dan massa bodi. Gunakan untuk memeriksa ukuran dan kelonggaran.", + "help.inspect.minimum_radius": "Menemukan radius kelengkungan terkecil pada kurva, tepi, atau muka, beserta letaknya. Gunakan untuk memeriksa apakah alat atau nosel dapat mengikuti bentuknya.", + "help.inspect.section": "Memotong tampilan terbuka sepanjang sebuah bidang dan mengarsir muka potongnya, tanpa mengubah model. Gunakan untuk melihat bagian dalam part dan rakitan.", + "help.inspect.zebra": "Menampilkan lajur hitam putih yang terpantul pada muka model. Gunakan untuk menilai kehalusan: lajur yang terputus atau patah di sebuah tepi menandakan transisi yang buruk.", + "help.joint.as_built": "Menyambung dua part di tempat keduanya berada, tanpa memindahkan salah satunya, dan mengatur bagaimana keduanya masih boleh bergerak. Gunakan untuk part yang sudah Anda tempatkan di posisi akhirnya.", + "help.joint.cam": "Menghubungkan cam yang berputar ke pengikut, sehingga pengikut bergeser atau berayun saat kontur cam lewat di bawahnya. Gunakan untuk cam, eksentrik, dan penggerak katup.", + "help.joint.create": "Menyambung dua part pada origin sambungan yang Anda pilih dan memindahkan part kedua ke tempatnya; jenis sambungan menentukan bagaimana keduanya masih boleh bergerak. Gunakan untuk membangun rakitan yang part-nya bergerak seperti mekanisme sebenarnya.", + "help.joint.drive": "Mengatur sudut atau jarak sebuah sambungan dan menggerakkan part bersamanya, dalam batasnya; sambungan terkait dan loop tertutup ikut bergerak. Gunakan untuk memeriksa bahwa mekanisme bergerak sesuai maksud.", + "help.joint.gear": "Menghubungkan dua sambungan berputar dengan rasio roda gigi, sehingga menggerakkan satu akan memutar yang lain. Gunakan untuk roda gigi lurus dan roda gigi dalam, dengan rasio dari radius pitch atau jumlah gigi.", + "help.joint.limits": "Mengatur sejauh mana sambungan boleh berputar atau bergeser, sebagai minimum dan maksimum, atau menghapus batas itu. Gunakan agar engsel, sambungan geser, atau tuas tetap berada dalam rentang geraknya yang sebenarnya.", + "help.joint.motion_link": "Menggandengkan dua sambungan dengan rasio dan offset, sehingga menggerakkan satu akan menggerakkan yang lain. Gunakan untuk hubungan tetap antar sambungan yang tidak tercakup oleh Roda Gigi, Rack dan Pinion, atau Sekrup.", + "help.joint.origin": "Menempatkan origin sambungan bernama pada sebuah part: di pusat sebuah muka atau ujung bulat, tengah sebuah tepi, sebuah sudut, atau sebuah titik. Gunakan untuk menyiapkan tempat sambungan menempel; origin yang dipilih pada sebuah muka mengikuti muka itu saat ukuran part berubah.", + "help.joint.rack_pinion": "Menghubungkan pinion yang berputar ke rack yang bergeser, sehingga rack bergerak sejauh panjang lingkaran pitch yang digelindingi pinion. Gunakan untuk penggerak rack, kemudi, dan tahap linear.", + "help.joint.reach": "Menggerakkan sebuah titik pada part ke arah sasaran dengan mengubah sambungan pada rantainya, dalam batasnya. Gunakan untuk memposisikan mekanisme berdasarkan di mana ujungnya harus berada, seperti ujung lengan robot.", + "help.joint.rigid_group": "Mengunci part terpilih bersama sebagaimana adanya, sehingga bergerak sebagai satu kesatuan. Gunakan untuk part yang menyatu dan tidak memiliki gerakan di antaranya.", + "help.joint.screw": "Menghubungkan gerak putar dan gerak geser dengan sebuah pitch, sehingga setiap putaran maju sejauh jarak itu. Gunakan untuk lead screw, baut, dan poros berulir.", + "help.library.apply": "Menerapkan material atau tampilan dari file pustaka lokal ke bodi, muka, atau komponen. Gunakan untuk memakai ulang material yang Anda simpan dari desain lain.", + "help.library.export": "Menyimpan material dan tampilan desain ke file pustaka. Gunakan untuk membagikannya atau memakainya ulang di desain lain.", + "help.library.inspect": "Memeriksa file pustaka dan mencantumkan material serta tampilannya, tanpa mengubah desain. Gunakan untuk melihat isi sebuah pustaka sebelum menerapkannya.", "help.licences": "Lisensi", "help.material.assign": "Menetapkan bahan pembuat bodi terpilih, seperti baja, aluminium, atau ABS. Gunakan agar massa dan bobot sesuai dengan part sebenarnya.", + "help.material.properties.validate": "Memeriksa kartu data material untuk angka yang konsisten dan nilai yang hilang. Gunakan sebelum mengandalkan data itu untuk massa atau kekakuan.", + "help.mesh.convert": "Membangun ulang bodi mesh, seperti STL, menjadi solid yang dapat diedit dengan muka datar dan silindris. Gunakan untuk memodifikasi part mekanis impor seperti bodi yang dimodelkan.", "help.mit": "Lisensi MIT", + "help.motion.study": "Mengatur nilai sambungan pada langkah-langkah di sepanjang linimasa dan memutarnya sebagai animasi. Gunakan untuk melihat mekanisme bergerak melalui suatu urutan dan memeriksa kelonggaran di sepanjang jalannya.", + "help.motion.trace": "Menelusuri jalur yang diikuti sebuah titik pada part selama studi gerak diputar atau sambungan digerakkan, dan menyimpannya sebagai kurva sketsa 3D saat Anda mengonfirmasi. Gunakan untuk melihat jangkauan mekanisme, atau membangun di atas jalurnya.", "help.notice": "NOTICE", + "help.occurrence.ground": "Memasang part tetap di tempatnya, atau membebaskannya lagi, sehingga sambungan menggerakkan part lain di sekitarnya. Gunakan untuk rangka atau dasar tempat seluruh rakitan lainnya dibangun.", "help.occurrence.move": "Memindahkan part rakitan hanya sepanjang kebebasan yang diizinkan oleh sambungannya. Pilih sebuah muka part, lalu seret panah atau busur yang tersedia.", "help.parameters.change": "Membuka tabel nilai dan ekspresi bernama yang menggerakkan dimensi desain. Gunakan untuk mengubah ukuran di satu tempat dan membuat semua fitur yang memakainya mengikuti.", + "help.parameters.export": "Menyimpan parameter desain sebagai CSV atau JSON. Gunakan untuk mengeditnya di spreadsheet atau memindahkannya ke desain lain.", + "help.parameters.graph": "Menampilkan parameter dan fitur mana yang memakai yang lain, beserta loop atau error di antaranya. Gunakan untuk melihat apa yang akan terpengaruh oleh perubahan sebuah parameter.", + "help.parameters.import": "Membaca parameter dari CSV atau JSON ke dalam desain, semuanya atau tidak sama sekali. Gunakan untuk membawa masuk nilai dari spreadsheet atau desain lain.", + "help.parameters.move": "Memindahkan parameter pengguna ke sebelum atau sesudah parameter lain dalam daftar. Gunakan untuk menjaga parameter yang berkaitan tetap berdekatan.", + "help.parts.fastener": "Menambahkan sekrup, baut, mur, washer, pin, atau bearing standar dengan ukuran yang Anda pilih. Bila ditempatkan pada sebuah lubang, ia duduk di lubang itu dengan sebuah sambungan, jadi Anda tidak perlu memodelkan pengencang sendiri.", + "help.parts.insert": "Menyisipkan part standar dengan keluarga, ukuran, dan panjang yang Anda pilih. Bila ditempatkan pada tepi atau dinding sebuah lubang, ia duduk pada lubang itu dengan sambungan kaku.", + "help.parts.library": "Membuka part standar: sekrup, baut, mur, washer, sekrup set, pin dowel, dan bearing dengan ukuran standar. Gunakan untuk menambahkan part standar alih-alih memodelkannya sendiri.", + "help.parts.resize": "Mengubah ukuran atau panjang part standar yang disisipkan dan membangunnya ulang; sambungannya menjaganya tetap terpasang. Gunakan bila sekrup ternyata terlalu panjang atau lubang memerlukan ukuran lain.", + "help.plastic.assign_rule": "Menetapkan aturan plastik ke bodi, sehingga fitur plastiknya memakai draft dan kelonggarannya sebagai nilai bawaan. Gunakan untuk menyiapkan part cetakan sekali untuk semua fiturnya.", + "help.plastic.boss": "Menambahkan boss sekrup pada sebuah muka: tiang dengan lubang opsional, draft, fillet pangkal, dan rusuk penopang. Gunakan untuk titik sekrup pada casing hasil cetakan atau cetak 3D.", + "help.plastic.lip": "Menambahkan lip atau alur pasangannya sepanjang tepi bodi yang di-shell. Gunakan agar dua belahan casing saling terkunci posisinya dan menutup rapat.", + "help.plastic.manage_rules": "Membuat dan mengedit aturan plastik: material, tebal dinding, radius, kelonggaran, dan draft. Gunakan untuk menjaga fitur-fitur part cetakan tetap konsisten.", + "help.plastic.rest": "Menambahkan rest pada sebuah muka: bantalan bulat atau persegi panjang, padat atau berongga, dengan draft. Gunakan sebagai penopang atau standoff pada casing cetakan.", + "help.plastic.snap_fit": "Menambahkan kait snap-fit pada sebuah muka, dengan panjang, ketebalan, dan pengaitnya. Gunakan untuk mengait part satu sama lain tanpa sekrup.", "help.pointcloud.insert": "Sisipkan hasil pindai PLY, XYZ, atau PTS sebagai awan titik di samping model. Gunakan sebagai referensi saat membangun model dari data hasil pengukuran.", + "help.sheet.convert": "Mengubah pelat atau bodi yang di-shell dengan ketebalan merata menjadi bodi pelat logam, dengan tekukan pada tepi yang Anda pilih. Gunakan untuk membuat part yang sudah ada dapat dibuka lipatannya.", + "help.sheet.export_bend_table": "Menyimpan tabel tekukan bodi pelat logam sebagai CSV atau JSON: sudut, radius, dan posisi tekukan pada bentuk datar. Gunakan untuk mesin tekuk (press brake) atau bengkel.", + "help.sheet.export_dxf": "Menyimpan pola datar sebagai DXF, dengan kontur, garis tekukan, dan catatan tekukan opsional. Gunakan untuk pemotongan laser, plasma, atau waterjet.", + "help.sheet.flange": "Menambahkan flens: pelat dasar dari sketsa, dinding sepanjang kontur sketsa terbuka, atau dinding tertekuk pada tepi pelat. Gunakan untuk membangun part pelat logam.", + "help.sheet.flat_pattern": "Membuat pola datar bodi pelat logam, lengkap dengan ukuran, potongan, dan garis tekukannya. Gunakan untuk memeriksa blanko sebelum Anda memotongnya.", + "help.sheet.fold": "Melipat pelat sepanjang garis sketsa dengan sudut dan radius tertentu. Gunakan untuk melipat pelat datar setelah fitur potongan dibuat padanya.", + "help.sheet.hem": "Melipat tepi pelat kembali menutupi dirinya sendiri. Gunakan untuk tepi yang aman dan kaku tanpa duri tajam.", + "help.sheet.manage_rules": "Membuat dan mengedit aturan pelat logam: ketebalan, radius tekukan, faktor K, relief, dan celah. Gunakan agar sesuai dengan material dan perkakas bengkel Anda.", + "help.sheet.path_flange": "Menambahkan rangkaian flens sepanjang tepi pelat, mengikuti rantai terbuka garis sketsa. Gunakan untuk profil seperti bentuk U atau Z dalam satu langkah.", + "help.sheet.perforate": "Menambahkan hamparan lubang di seluruh pelat datar, dalam pola selang-seling atau persegi. Gunakan untuk ventilasi, kisi, dan panel yang lebih ringan.", + "help.sheet.refold": "Melipat kembali bodi pelat logam yang sudah dibuka lipatannya. Gunakan setelah menambahkan fitur pada pelat datar.", + "help.sheet.unfold": "Membuka lipatan semua tekukan bodi pelat logam. Gunakan untuk menambahkan lubang atau potongan yang harus melintasi tekukan, lalu lipat ulang.", + "help.sketch.arc.center_point": "Menggambar busur lingkaran mengelilingi titik pusat, dari titik awal ke titik akhir. Gunakan bila pusat busur diketahui, seperti radius di sekeliling lubang atau pivot.", + "help.sketch.arc.tangent": "Menggambar busur yang dimulai di ujung garis atau busur dan berlanjut secara tangen terhadapnya. Gunakan untuk melanjutkan rantai dengan lengkungan halus, bukan sudut.", + "help.sketch.arc.three_point": "Menggambar busur dari titik awal ke titik akhir melalui titik ketiga. Gunakan bila busur harus melewati titik-titik tertentu, bukan mengelilingi pusat yang diketahui.", + "help.sketch.arc3d": "Menggambar busur lingkaran eksak di ruang melalui tiga titik, dengan Sketsa 3D aktif. Gunakan untuk lengkungan pada jalur dan rel pemandu yang keluar dari bidang sketsa.", + "help.sketch.auto_constrain": "Menambahkan batasan yang hampir sudah dimiliki sketsa, seperti horizontal, paralel, atau berimpit, lalu memberinya dimensi hingga terbatasi penuh. Gunakan untuk mengunci sketsa yang digambar kasar dalam satu langkah.", + "help.sketch.auto_constrain_from_datum": "Bekerja seperti AutoConstrain, tetapi mengukur posisi dari titik datum yang Anda pilih, bukan dari origin. Gunakan bila part ditata dari satu titik referensi, seperti sudut atau lubang.", + "help.sketch.blend_curve": "Menyambung ujung dua kurva dengan spline halus yang tangen terhadap keduanya, atau juga kontinu kelengkungannya bila Anda memilihnya. Gunakan untuk menjembatani celah antar kurva tanpa patahan.", + "help.sketch.break": "Memecah kurva menjadi potongan di tempat kurva lain memotongnya, atau pada titik yang Anda tempatkan di atasnya. Gunakan bila sebagian kurva memerlukan batasannya sendiri atau harus dihapus tersendiri.", + "help.sketch.cancel": "Meninggalkan sketsa dan membuang semua yang diubah sejak sketsa dibuat atau dibuka untuk diedit. Urungkan mengembalikan perubahan itu.", + "help.sketch.centerline": "Mengalihkan garis antara garis normal dan garis tengah, yaitu sumbu yang tidak disertakan profil. Gunakan garis tengah sebagai sumbu untuk revolve, cermin, atau batasan simetri.", + "help.sketch.chamfer.distance_angle": "Memberi bevel pada sudut di antara dua garis, ditentukan oleh jarak sepanjang garis pertama dan sebuah sudut. Gunakan bila gambar kerja menyatakan chamfer sebagai panjang dan sudut, seperti 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Memberi bevel pada sudut di antara dua garis dengan jarak yang sama ke belakang sepanjang keduanya. Gunakan untuk chamfer 45° yang lazim pada sebuah kontur.", + "help.sketch.chamfer.two_distance": "Memberi bevel pada sudut di antara dua garis, ditentukan oleh jarak terpisah sepanjang setiap garis. Gunakan untuk chamfer yang bukan 45°, yang dinyatakan sebagai dua panjang.", + "help.sketch.circle.center": "Menggambar lingkaran dari pusat dan diameternya. Gunakan untuk lubang, boss, dan fitur bulat lain yang pusatnya diketahui.", + "help.sketch.circle.three_point": "Menggambar lingkaran melalui tiga titik. Gunakan bila lingkaran harus melewati titik-titik tertentu, misalnya dari geometri yang sudah ada.", + "help.sketch.circle.three_tangent": "Menggambar lingkaran yang menyentuh tiga garis, lingkaran, atau busur. Gunakan untuk memasukkan lingkaran ke ruang di antara tiga kurva, seperti lingkaran dalam sebuah segitiga.", + "help.sketch.circle.two_point": "Menggambar lingkaran dari kedua ujung diameternya. Gunakan bila titik tepi lingkaran diketahui, bukan pusatnya.", + "help.sketch.circle.two_tangent": "Menggambar lingkaran dengan ukuran tertentu yang menyentuh dua garis, lingkaran, atau busur. Gunakan untuk pembulatan dengan radius tetap di antara dua kurva.", + "help.sketch.conic": "Menggambar kurva konik di antara dua titik ujung, dibentuk oleh titik puncak dan nilai rho. Gunakan untuk transisi halus yang kepenuhannya ingin Anda atur, dari datar hingga hampir menjadi sudut tajam.", + "help.sketch.constrainer": "Menerapkan batasan yang hampir sudah dimiliki satu atau dua kurva terpilih, seperti horizontal, paralel, tangen, atau sama. Gunakan untuk merapikan sketsa gambar tangan, satu relasi demi satu.", + "help.sketch.constraint.coincident": "Membuat sebuah titik berada pada titik lain, kurva, atau sumbu sketsa. Gunakan untuk menutup celah pada profil atau menaruh titik pada garis.", + "help.sketch.constraint.collinear": "Membuat dua garis berada pada satu garis lurus. Gunakan untuk menyejajarkan tepi yang terputus, seperti kedua sisi sebuah takik.", + "help.sketch.constraint.concentric": "Memberi dua lingkaran atau busur pusat yang sama. Gunakan untuk cincin, counterbore, dan poros dengan bahu.", + "help.sketch.constraint.curvature": "Membuat dua kurva yang bertemu di titik ujung berlanjut dengan kelengkungan yang sama (G2). Gunakan bila sambungan tangen belum cukup halus, misalnya pada permukaan yang terlihat.", + "help.sketch.constraint.equal": "Membuat garis sama panjang, atau lingkaran dan busur sama radius. Gunakan agar satu dimensi mengendalikan beberapa fitur yang sama.", + "help.sketch.constraint.fix": "Mengunci titik atau kurva di tempatnya, atau membebaskannya lagi. Gunakan untuk geometri yang tidak boleh bergerak saat Anda menyeret atau me-solve sketsa.", + "help.sketch.constraint.horizontal_vertical": "Membuat sebuah garis, atau garis di antara dua titik, menjadi horizontal atau vertikal, mana yang lebih dekat. Gunakan untuk meluruskan kontur terhadap sumbu sketsa.", + "help.sketch.constraint.midpoint": "Menempatkan titik di tengah garis, atau membuat titik tengah dua garis bertemu. Gunakan untuk memusatkan geometri pada sebuah tepi.", + "help.sketch.constraint.parallel": "Membuat dua garis paralel. Gunakan untuk sisi yang harus tetap paralel saat dimensi lain berubah.", + "help.sketch.constraint.perpendicular": "Membuat dua garis bertemu pada sudut siku-siku. Gunakan untuk sudut tegak lurus antara garis yang tidak berada pada sumbu sketsa.", + "help.sketch.constraint.polygon": "Menjadikan rantai garis tertutup sebagai poligon beraturan: sisi sama panjang, dengan setiap sudut berada pada satu lingkaran. Gunakan untuk membuat poligon gambar tangan menjadi beraturan dan menjaganya tetap begitu.", + "help.sketch.constraint.symmetry": "Membuat dua titik atau kurva saling mencerminkan di seberang sebuah garis atau terhadap sebuah titik. Gunakan untuk menjaga profil tetap simetris saat Anda mengubah satu sisi.", + "help.sketch.constraint.tangent": "Membuat dua kurva bersentuhan secara tangen, seperti garis dan busur. Gunakan untuk sambungan halus tanpa patahan.", + "help.sketch.construction": "Mengalihkan kurva antara geometri normal dan geometri konstruksi, yang tidak disertakan profil. Gunakan kurva konstruksi sebagai bantuan untuk tata letak, referensi, dan dimensi.", + "help.sketch.construction_line": "Buat garis bantu tak hingga melalui dua titik. Gunakan untuk menata sketsa tanpa memecah profil.", + "help.sketch.construction_line.angle": "Buat garis bantu tak hingga dengan sudut terhadap sumbu X sketsa. Pilih titiknya dan ketik sudutnya, atau pilih arahnya.", + "help.sketch.construction_line.bisector": "Pilih dua garis sketsa lurus yang berpotongan, lalu pilih salah satu garis bagi sudut. Hasilnya mengikuti garis sumbernya.", + "help.sketch.construction_line.horizontal": "Buat garis bantu horizontal tak hingga melalui sebuah titik. Batasan horizontalnya tetap berlaku pada pengeditan berikutnya.", + "help.sketch.construction_line.parallel": "Pilih sebuah garis sketsa lurus, lalu tempatkan garis bantu tak hingga yang sejajar. Klik kanan untuk memilih referensi lain.", + "help.sketch.construction_line.perpendicular": "Pilih sebuah garis sketsa lurus, lalu tempatkan garis bantu tak hingga yang tegak lurus. Klik kanan untuk memilih referensi lain.", + "help.sketch.construction_line.tangent_at": "Buat garis singgung pada sebuah titik di lingkaran atau busur lingkaran, atau pada titik ujung spline atau kurva konik yang terbuka. Pilih kurvanya, lalu titik singgungnya.", + "help.sketch.construction_line.tangent_external": "Pilih lingkaran atau busur lingkaran, lalu sebuah titik luar dan satu solusi garis singgung. Pratinjau hanya menampilkan titik singgung pada busur yang digambar.", + "help.sketch.construction_line.tangent_two": "Pilih dua lingkaran atau busur lingkaran, lalu pilih garis singgung persekutuan di pratinjau. Titik singgung harus berada pada kurva yang digambar.", + "help.sketch.construction_line.vertical": "Buat garis bantu vertikal tak hingga melalui sebuah titik. Batasan vertikalnya tetap berlaku pada pengeditan berikutnya.", + "help.sketch.copy": "Menyalin kurva dan titik sketsa terpilih, beserta batasan dan dimensi di antaranya. Tempelkan ke sketsa ini atau sketsa lain.", + "help.sketch.create": "Memulai sketsa 2D baru pada sebuah bidang atau muka datar model. Setiap ekstrusi, revolve, dan sweep dimulai dengan sebuah sketsa.", + "help.sketch.cut": "Menyalin geometri sketsa terpilih dan menghapusnya dari sketsa, dalam satu langkah urungkan. Tempelkan di tempat lain di sketsa ini atau ke sketsa lain.", + "help.sketch.dimension": "Menambahkan dimensi driving: panjang, jarak, sudut, radius, atau diameter, tergantung apa yang Anda pilih. Ketik nilai atau nama parameter, dan sketsa mengikutinya.", + "help.sketch.edit": "Membuka sketsa yang sudah ada untuk diedit. Fitur yang dibangun di atasnya diperbarui saat Anda menyelesaikan sketsa.", + "help.sketch.ellipse": "Menggambar elips dari pusatnya, ujung sumbu utamanya, dan sebuah titik pada sisi minornya. Gunakan untuk bukaan oval, cam, dan bentuk bulat memanjang lainnya.", "help.sketch.equation_curve": "Menggambar kurva dari rumus: x(t) dan y(t), atau y = f(x), pada suatu rentang. Rumusnya dapat memakai parameter dan kurva mengikutinya: gunakan untuk gelombang sinus, spiral, atau involut gigi roda gigi.", + "help.sketch.extend": "Memperpanjang garis atau busur hingga kurva terdekat yang menghalanginya, atau memanjangkan dua kurva hingga bertemu. Gunakan untuk menutup celah pada profil setelah trim atau pengeditan.", + "help.sketch.fillet": "Membulatkan sudut tempat dua garis atau busur bertemu dengan busur berradius tertentu. Beberapa sudut yang dibulatkan bersama memakai satu radius yang sama.", + "help.sketch.finish": "Meninggalkan sketsa dan kembali ke model. Profil tertutupnya lalu siap untuk Ekstrusi, Revolve, dan fitur lain.", + "help.sketch.finish_auto_constrain": "Menjalankan AutoConstrain pada sketsa, lalu menyelesaikannya. Gunakan untuk meninggalkan sketsa yang terbatasi penuh dalam satu langkah.", + "help.sketch.fit_curves_to_section": "Memotong bodi mesh atau solid dengan bidang sketsa dan mencocokkan garis dan busur dengan penampangnya. Gunakan untuk membangun ulang part hasil pindai atau impor sebagai sketsa yang dapat diedit.", + "help.sketch.include_3d": "Membawa tepi model, titik sudut, dan kurva sketsa lain ke sketsa ini sebagai referensi tertaut, dengan meratakan yang berada di luar bidangnya ke atasnya. Gunakan untuk membangun di atas geometri yang tidak terletak pada bidang sketsa.", + "help.sketch.infinite": "Mengalihkan garis antara garis normal dan garis konstruksi tak hingga yang membentang di seluruh tampilan. Gunakan sebagai referensi tata letak yang tidak pernah berakhir terlalu pendek.", + "help.sketch.insert_dxf": "Membaca kurva gambar DXF ke dalam sketsa, diskalakan, diputar, dan ditempatkan sesuai pengaturan Anda. Gunakan untuk membangun di atas gambar 2D dari program lain, seperti kontur potong laser.", + "help.sketch.insert_svg": "Membaca path gambar SVG ke dalam sketsa, diskalakan, diputar, dan ditempatkan sesuai pengaturan Anda. Gunakan untuk mengubah logo atau kontur vektor menjadi kurva yang dapat diekstrusi.", + "help.sketch.inspect": "Membuka laporan tentang sketsa yang terbuka: berapa derajat kebebasan yang tersisa dan apakah sketsa terbatasi penuh. Gunakan untuk mengetahui apa yang masih bergerak sebelum Anda menyelesaikan sketsa.", + "help.sketch.intersect": "Menambahkan kurva atau titik tempat bodi, muka, tepi, atau sketsa lain memotong bidang sketsa. Semuanya tetap tertaut dan mengikuti model saat model berubah.", + "help.sketch.intersection_curve": "Membuat kurva 3D di tempat dua bodi atau muka bertemu, tertaut padanya. Gunakan sebagai jalur atau rel pemandu yang mengikuti model.", + "help.sketch.isoparametric_curve": "Membuat kurva 3D sepanjang arah U atau V sebuah muka melalui titik yang Anda pilih, tertaut ke muka itu. Gunakan sebagai jalur atau garis pisah yang mengikuti permukaan.", + "help.sketch.line": "Menggambar garis-garis tersambung titik demi titik, sebagai rantai terbuka atau kontur tertutup. Ini alat dasar untuk sebagian besar profil.", + "help.sketch.line.midpoint": "Menggambar garis dari titik tengahnya ke satu ujung, dengan ujung lainnya dicerminkan. Gunakan untuk garis yang dipusatkan pada sebuah titik, seperti tepi simetris.", + "help.sketch.line3d": "Menggambar garis lurus tersambung di antara titik-titik di ruang, dengan Sketsa 3D aktif. Gunakan untuk jalur dan rangka yang keluar dari bidang sketsa.", + "help.sketch.mirror": "Mencerminkan kurva dan titik sketsa terhadap sebuah garis atau sumbu dan menambahkan batasan simetri. Gunakan untuk menggambar setengah profil simetris lalu melengkapinya.", + "help.sketch.move": "Memindahkan atau memutar kurva dan titik sketsa, atau salinannya. Gunakan untuk memposisikan ulang geometri sambil mempertahankan bentuk dan batasannya.", + "help.sketch.offset": "Membuat salinan rantai kurva pada jarak tertentu, di satu sisi atau kedua sisi. Gunakan untuk dinding, kontur, dan kelonggaran; jaraknya tetap menjadi dimensi yang dapat diedit.", + "help.sketch.paste": "Menempelkan geometri sketsa yang Anda salin atau potong ke sketsa aktif. Tempatkan di sebuah titik atau geser dengan offset.", + "help.sketch.pattern.circular": "Menyalin geometri sketsa mengelilingi titik pusat, sepanjang satu lingkaran penuh atau sudut tertentu. Gunakan untuk lingkaran baut, jari-jari, dan gigi.", + "help.sketch.pattern.rectangular": "Menyalin geometri sketsa dalam baris dan kolom dengan jarak tertentu. Gunakan untuk grid lubang, slot, atau ventilasi.", + "help.sketch.point": "Menempatkan titik sketsa. Gunakan sebagai referensi untuk dimensi, batasan, pusat lubang, atau fitur berikutnya.", + "help.sketch.point3d": "Menempatkan titik di ruang, dengan Sketsa 3D aktif. Gunakan sebagai referensi untuk kurva dan jalur 3D.", + "help.sketch.polygon.circumscribed": "Menggambar poligon beraturan di sekeliling lingkaran, berukuran dari pusatnya hingga tengah sebuah sisi. Gunakan bila lebar antar sisi datar diketahui, seperti pada mur segi enam.", + "help.sketch.polygon.edge": "Menggambar poligon beraturan dari kedua ujung satu sisinya. Gunakan bila panjang dan posisi satu sisi diketahui.", + "help.sketch.polygon.inscribed": "Menggambar poligon beraturan di dalam lingkaran, berukuran dari pusatnya hingga sebuah sudut. Gunakan bila ukuran antar sudut diketahui.", + "help.sketch.project": "Membawa tepi model, muka, titik sudut, dan kurva sketsa lain ke sketsa ini, diproyeksikan ke bidangnya. Semuanya tetap tertaut dan mengikuti model saat model berubah.", + "help.sketch.project_to_surface": "Memproyeksikan kurva sketsa lain sepanjang normal sketsa ini ke sebuah muka, sebagai kurva 3D tertaut. Gunakan untuk menaruh logo, garis pisah, atau jalur pada permukaan lengkung.", + "help.sketch.rectangle.center": "Menggambar persegi panjang dari pusat dan satu sudutnya. Gunakan untuk kontur yang dipusatkan pada sebuah titik, seperti origin.", + "help.sketch.rectangle.rounded": "Menggambar persegi panjang dengan keempat sudut dibulatkan pada satu radius. Gunakan untuk pelat, tutup, dan bukaan dengan sudut membulat.", + "help.sketch.rectangle.three_point": "Menggambar persegi panjang dari satu sisi dan sebuah titik di sisi seberangnya. Gunakan untuk persegi panjang yang miring terhadap sumbu sketsa.", + "help.sketch.rectangle.two_point": "Menggambar persegi panjang dari dua sudut yang berseberangan. Gunakan untuk kontur pelat, blok, dan kantong.", + "help.sketch.scale": "Menskalakan kurva dan titik sketsa dengan suatu faktor terhadap titik dasar. Gunakan untuk mengubah ukuran sebagian sketsa tanpa menggambarnya lagi.", + "help.sketch.slot.arc_center": "Menggambar slot melengkung dengan lebar tertentu sepanjang busur yang ditentukan oleh pusat, titik awal, dan titik akhirnya. Gunakan untuk slot penyetelan di sekeliling pivot.", + "help.sketch.slot.arc_three_point": "Menggambar slot melengkung dengan lebar tertentu sepanjang busur melalui tiga titik. Gunakan bila lintasan slot harus melewati titik-titik tertentu.", + "help.sketch.slot.center_point": "Menggambar slot lurus dengan lebar tertentu dari pusatnya ke pusat salah satu busur ujung. Gunakan untuk slot yang dipusatkan pada sebuah titik.", + "help.sketch.slot.center_to_center": "Menggambar slot lurus dengan lebar tertentu di antara pusat kedua busur ujungnya. Gunakan untuk slot yang didimensikan dari pusat ke pusat, seperti slot penyetelan untuk sekrup.", + "help.sketch.slot.overall": "Menggambar slot lurus dengan lebar tertentu dari satu ujung luar ke ujung lainnya. Gunakan bila panjang total slot yang terpenting.", + "help.sketch.spline.control_point": "Menggambar spline kubik yang dibentuk oleh titik kontrol yang tidak dilaluinya. Gunakan untuk kurva halus yang mengalir, yang Anda bentuk dengan menggeser titik-titiknya.", + "help.sketch.spline.control_point_5": "Menggambar spline derajat 5 yang dibentuk oleh titik kontrol. Gunakan bila kurva harus menyambung dengan kelengkungan yang lebih halus, misalnya pada permukaan bergaya yang terlihat.", + "help.sketch.spline.fit_point": "Menggambar spline halus yang melewati setiap titik yang Anda tempatkan, terbuka atau tertutup. Gunakan untuk menjiplak bentuk melalui titik-titik yang diketahui.", + "help.sketch.spline3d": "Menggambar kurva halus di ruang melalui titik-titik, dengan Sketsa 3D aktif. Gunakan untuk jalur sweep dan jalur kabel yang keluar dari bidang sketsa.", + "help.sketch.spun_profile": "Membuat di bidang sketsa kontur yang disapu sebuah bodi saat berputar mengelilingi sumbu. Gunakan untuk mendapatkan siluet part bubutan untuk revolve atau gambar.", + "help.sketch.text": "Menulis teks di dalam sketsa dengan font, tinggi, dan sudut tertentu; katanya dapat mengikuti parameter. Ekstrusi atau beri emboss untuk label dan tulisan huruf.", + "help.sketch.transform": "Menskalakan, memutar, dan memindahkan geometri sketsa terhadap titik pusat dalam satu langkah. Gunakan untuk memposisikan ulang dan mengubah ukuran sebuah pilihan sekaligus.", + "help.sketch.trim": "Menghapus potongan kurva di antara perpotongan terdekat di sekitar tempat Anda mengklik. Gunakan untuk merapikan garis yang tumpang tindih menjadi profil tertutup.", "help.solid.align": "Memindahkan bodi terpilih sehingga titik, muka, atau bidang padanya bertemu titik, muka, atau bidang di tempat lain. Gunakan untuk menempatkan part pada part lain tanpa mengukur offset.", + "help.solid.boundary_fill": "Membuat solid dari wilayah yang dikelilingi bodi alat yang tumpang tindih, dengan hanya mengisi wilayah yang Anda pilih. Gunakan untuk membangun bentuk dari ruang yang dibatasi bersama oleh beberapa bodi.", + "help.solid.bounding_solid": "Membuat kotak yang membungkus bodi terpilih, dengan margin opsional. Gunakan untuk melihat ukuran keseluruhan sebuah part, atau sebagai bahan baku tempat part itu dimesin.", + "help.solid.box": "Membuat kotak dari panjang, lebar, dan tinggi, dari sebuah titik sudut atau dipusatkan pada sebuah titik. Gunakan untuk blok cepat, pengganti sementara, atau bodi tempat fitur akan dipotongkan.", "help.solid.chamfer": "Memotong tepi terpilih dengan bevel datar sejauh jarak yang Anda atur. Gunakan untuk menumpulkan tepi tajam atau mempermudah masuknya pin atau sekrup.", + "help.solid.coil": "Membuat bodi heliks, seperti pegas, dari diameter, jumlah putaran, tinggi atau pitch, dan penampang bulat atau persegi. Gunakan untuk pegas, koil, dan rusuk heliks.", "help.solid.combine": "Menggabungkan bodi, memotongnya dari bodi target, atau hanya menyimpan volume yang dimiliki bersama, dan dapat mempertahankan bodi alat. Gunakan untuk menyatukan part, memotong satu bentuk dengan bentuk lain, atau menemukan tempat dua bodi bertumpang tindih.", + "help.solid.cone": "Membuat kerucut dari lingkaran dasar dan tinggi, atau kerucut terpancung bila bagian atasnya juga memiliki radius. Gunakan untuk taper, corong, countersink, dan ujung runcing.", + "help.solid.cylinder": "Membuat silinder dari radius atau diameter dan tinggi, berdiri pada sebuah titik sepanjang sumbu. Gunakan untuk poros, pin, boss, dan blanko bulat.", "help.solid.draft": "Memiringkan muka terpilih sebesar sudut yang Anda atur, diukur dari bidang netral. Gunakan pada part cetakan atau cor agar mudah dilepas dari cetakannya.", + "help.solid.emboss": "Menaikkan profil sketsa, seperti teks atau logo, dari sebuah muka, atau membenamkannya ke dalamnya. Gunakan untuk tulisan, label, dan tanda pada muka datar atau bulat.", "help.solid.extrude": "Mendorong profil sketsa menjadi 3D sejauh jarak tertentu, menambah atau menghilangkan material. Gunakan untuk mengubah garis bentuk datar menjadi blok, boss, atau kantong.", "help.solid.fillet": "Membulatkan tepi terpilih dengan perpaduan melingkar yang halus sebesar radius yang Anda atur. Gunakan untuk memperhalus tepi tajam demi kekuatan, kenyamanan, atau tampilan.", "help.solid.hole": "Membor lubang bulat dengan diameter yang Anda atur pada titik pilihan di sebuah muka. Gunakan untuk celah sekrup, pin, dan bukaan bulat sederhana lainnya.", @@ -1408,20 +1678,62 @@ "help.solid.move": "Memindahkan atau memutar bodi terpilih, atau salinannya, sesuai jarak dan sudut yang Anda atur. Gunakan untuk memposisikan ulang bodi atau membuat bodi kedua di tempat lain.", "help.solid.offset_face": "Mendorong muka terpilih ke dalam atau ke luar sejauh jarak yang Anda atur, dan muka di sekitarnya mengikuti. Gunakan untuk menebalkan dinding, memperdalam kantong, atau meninggikan boss tanpa mengedit sketsa.", "help.solid.pattern.circular": "Mengulang objek terpilih mengelilingi sumbu, sesuai jumlah dan sudut total yang Anda atur. Gunakan untuk lingkaran baut, jari-jari, sirip, dan gigi.", + "help.solid.pattern.path": "Menyalin fitur atau bodi sepanjang jalur sketsa, menurut jumlah dan jarak. Gunakan untuk lubang di sepanjang tepi lengkung atau part di sepanjang rel.", "help.solid.pattern.rectangular": "Mengulang objek terpilih dalam satu atau dua arah dengan jumlah dan jarak yang Anda atur. Gunakan untuk baris dan grid lubang, rusuk, pin, atau kaki.", + "help.solid.pipe": "Membuat pipa bulat sepanjang jalur kurva sketsa, padat atau berongga dengan ketebalan dinding. Gunakan untuk tabung, kawat, kabel, dan rel.", "help.solid.press_pull": "Menambah atau menghilangkan material saat Anda menyeret muka, atau membulatkan tepi saat Anda menyeretnya. Gunakan untuk perubahan cepat langsung pada model.", "help.solid.remove": "Mengeluarkan bodi terpilih dari desain mulai titik ini di timeline; langkah sebelumnya tetap memilikinya. Gunakan untuk membuang bodi bantu, seperti alat potong yang tidak diperlukan lagi.", "help.solid.replace_face": "Memindahkan muka datar terpilih ke sebuah bidang atau ke muka yang sejajar, dan bodi bertambah atau menyusut hingga bertemu. Gunakan untuk meratakan muka dengan part lain atau bidang konstruksi.", "help.solid.revolve": "Memutar profil sketsa mengelilingi sumbu untuk membuat solid bulat. Gunakan untuk poros, kenop, mangkuk, dan part apa pun yang bulat terhadap garis tengah.", + "help.solid.rib": "Menambahkan dinding tipis sepanjang kurva sketsa terbuka, diisi hingga muka-muka bodi berikutnya. Gunakan untuk memperkaku dinding dan sudut, misalnya pada part cetakan atau cetak 3D.", "help.solid.scale": "Membuat bodi terpilih lebih besar atau lebih kecil dengan suatu faktor, sama ke segala arah atau satu per sumbu. Gunakan untuk mengubah ukuran bentuk impor atau memperhitungkan penyusutan.", "help.solid.shell": "Mengosongkan solid, menyisakan dinding setebal yang Anda atur, dan dapat membuka muka yang Anda pilih. Gunakan untuk kotak, penutup, dan part berdinding tipis lainnya.", + "help.solid.sphere": "Membuat bola dari radius atau diameter di sekeliling titik pusat. Gunakan untuk bola, kenop, dan ujung membulat.", "help.solid.split_body": "Memotong sebuah bodi menjadi bodi terpisah dengan bidang, muka bodi lain, atau garis sketsa. Gunakan untuk membuat part yang dicetak, dimesin, atau diwarnai sendiri-sendiri.", "help.solid.split_face": "Membagi muka terpilih sepanjang bidang, muka bodi lain, atau kurva sketsa, tanpa memotong bodi. Gunakan untuk memberi sebagian muka drafnya, warnanya, atau offset-nya sendiri.", "help.solid.sweep": "Menyeret profil sketsa sepanjang jalur untuk membuat solid. Gunakan untuk pipa, rel, gagang, dan part berpenampang tetap yang mengikuti kurva.", + "help.solid.thread": "Menambahkan ulir metrik ISO pada muka silindris, sebagai ulir kosmetik atau dipotong ke dalam bodi. Gunakan untuk baut, lubang berulir, dan part sekrup cetak 3D.", + "help.solid.torus": "Membuat cincin dari radius mayor di sekeliling sumbunya dan radius minor untuk penampang bulatnya. Gunakan untuk O-ring, gagang, dan manik bulat.", + "help.solid.web": "Menambahkan dinding tipis sepanjang setiap kurva sketsa terbuka, masing-masing diisi hingga muka-muka bodi berikutnya. Gunakan untuk grid dinding penopang di dalam casing dan baki.", + "help.surface.blend": "Membuat permukaan yang menjembatani tepi dua bodi, tangen atau kontinu kelengkungannya terhadap keduanya. Gunakan untuk menyambung dua permukaan dengan halus melintasi celah.", + "help.surface.boundary": "Membuat permukaan yang mengisi loop dua sampai empat kurva sketsa, atau jaringan kurva. Gunakan untuk panel bentuk bebas yang ditentukan oleh tepinya.", + "help.surface.extend": "Memperpanjang permukaan melewati tepinya, sejauh jarak tertentu atau hingga sebuah bidang atau muka. Gunakan agar permukaan saling tumpang tindih sebelum Anda trim atau menjahitnya.", + "help.surface.extrude": "Mendorong kurva atau profil sketsa sejauh jarak tertentu menjadi permukaan, hanya dinding, tanpa tutup. Gunakan untuk dinding tipis dan untuk alat pemotong atau pemisah.", + "help.surface.fair": "Menghaluskan bagian dalam muka bentuk bebas sementara tepinya tetap di tempat. Gunakan untuk meratakan tonjolan dan pantulan bergelombang pada permukaan.", + "help.surface.loft": "Membuat permukaan yang melewati dua penampang atau lebih secara berurutan, tanpa tutup. Gunakan untuk shell dan transisi antar bentuk yang berbeda.", + "help.surface.match": "Membangun ulang tepi permukaan agar bertemu dengan tepi bodi lain, dengan tangen atau kelengkungan yang cocok. Gunakan untuk menutup jahitan secara halus di antara dua permukaan.", + "help.surface.offset": "Membuat salinan muka pada jarak tertentu sepanjang normalnya, sebagai bodi permukaan baru. Gunakan untuk kulit, kelonggaran, atau sisi lain sebuah dinding.", + "help.surface.patch": "Mengisi wilayah sketsa atau loop tepi tertutup dengan sebuah muka, datar atau melengkung halus. Gunakan untuk menutup lubang pada bodi permukaan.", + "help.surface.reverse_normal": "Membalik muka bodi permukaan, sehingga sisi luarnya menghadap arah lain. Gunakan sebelum menebalkan atau menjahit bila muka-mukanya mengarah ke dalam.", + "help.surface.revolve": "Memutar kurva atau profil sketsa mengelilingi sumbu menjadi permukaan, tanpa tutup. Gunakan untuk shell bulat seperti kap lampu, mangkuk, dan nosel.", + "help.surface.ruled": "Membuat pita garis lurus yang keluar dari rantai tepi, sepanjang normal muka, tangen, atau pada suatu sudut. Gunakan untuk dinding draft, run-off, dan permukaan pemisah.", + "help.surface.stitch": "Menjahit bodi permukaan bersama di sepanjang tepi yang dipakai bersama, menjadi solid bila tertutup. Gunakan untuk mengubah sekumpulan permukaan menjadi satu bodi.", + "help.surface.sweep": "Menggerakkan kurva atau profil sketsa sepanjang jalur menjadi permukaan, tanpa tutup. Gunakan untuk talang, trim, dan bentuk tipis lain yang mengikuti jalur.", + "help.surface.thicken": "Memberi ketebalan pada bodi permukaan, mengubahnya menjadi solid. Gunakan untuk membuat part yang dapat dicetak atau dimesin dari permukaan.", + "help.surface.trim": "Memotong permukaan dengan bidang, permukaan lain, atau kurva sketsa, dan mempertahankan sisi yang Anda pilih. Gunakan untuk memotong permukaan menjadi bentuk sebelum dijahit.", + "help.surface.unstitch": "Memisahkan muka sebuah bodi menjadi bodi permukaan tersendiri; solid terurai menjadi permukaan. Gunakan untuk mengerjakan ulang muka tunggal sebuah bodi.", + "help.surface.untrim": "Menghapus lubang dari sebuah muka, atau memulihkan batas luarnya ke batas alami permukaan. Gunakan untuk mendapatkan kembali permukaan penuh setelah trim.", "help.third_party": "Lisensi pihak ketiga", "help.timeline.compute_all": "Membangun ulang setiap fitur di timeline dari awal. Gunakan untuk menyegarkan model dan melihat fitur mana yang gagal.", "help.timeline.delete": "Menghapus fitur terpilih dari timeline; menghapus sketsa juga menghapus fitur yang dibangun darinya. Gunakan untuk membuang langkah yang tidak diinginkan lagi.", + "help.timeline.dependents": "Mencantumkan fitur yang akan ikut terhapus bersama sebuah fitur, dan yang akan gagal tanpanya. Gunakan sebelum menghapus atau mengubah sebuah fitur.", "help.timeline.play": "Putar ulang fitur yang tersisa satu per satu, dengan jeda setengah detik setelah setiap pembangunan ulang. Jalankan perintah ini lagi atau tekan Escape untuk berhenti; Ke akhir langsung melompat.", + "help.view.apply": "Memutar tampilan ke arah standar seperti depan, atas, atau iso, atau ke tampilan bernama yang tersimpan. Gunakan untuk melihat model dari sudut tetap.", + "help.view.delete": "Menghapus tampilan bernama yang tersimpan. Model tidak berubah.", + "help.view.fit": "Melakukan zoom dan pan agar seluruh model, atau pilihan, memenuhi tampilan. Gunakan bila model menghilang dari pandangan.", + "help.view.grid": "Menampilkan atau menyembunyikan grid di viewport. Gunakan sebagai panduan ukuran dan orientasi saat memodelkan.", + "help.view.ground_shadow": "Menampilkan atau menyembunyikan bayangan model di lantai. Gunakan untuk menilai tinggi dan posisi dengan lebih mudah.", + "help.view.home": "Memutar tampilan kembali ke arah awal dan memasukkan model ke dalam tampilan. Gunakan untuk kembali ke tampilan yang dikenal dengan cepat.", + "help.view.list": "Mencantumkan tampilan bernama yang tersimpan di desain. Gunakan untuk menemukan tampilan yang Anda simpan sebelumnya.", + "help.view.navigate": "Memutar, menggeser, atau memperbesar tampilan dengan langkah-langkah, seperti seperempat putaran ke kiri. Gunakan untuk menggerakkan kamera dengan tepat alih-alih menyeret.", + "help.view.navigation_bar": "Menampilkan atau menyembunyikan bilah navigasi di bagian bawah viewport. Sembunyikan untuk ruang lebih luas, tampilkan untuk menjangkau alat tampilan dengan mouse.", + "help.view.rename": "Memberi nama baru pada tampilan bernama yang tersimpan. Tampilannya sendiri tetap sama.", + "help.view.save": "Menyimpan posisi kamera saat ini sebagai tampilan bernama di desain. Gunakan untuk kembali ke sudut yang sama nanti, misalnya untuk tangkapan layar.", + "help.view.spin": "Memutar tampilan mengelilingi model secara terus-menerus hingga klik atau tombol berikutnya. Gunakan untuk mempresentasikan model dari segala sisi.", + "help.view.tool": "Mengunci alat kamera, yaitu orbit, pan, atau zoom, sehingga menyeret dengan tombol kiri mouse menggerakkan tampilan sampai Anda mematikannya. Gunakan pada trackpad atau tanpa tombol tengah mouse.", + "help.view.visual_style": "Mengganti cara model digambar: berbayang dengan atau tanpa tepi, wireframe, atau dengan tepi tersembunyi. Gunakan wireframe untuk melihat bagian dalam, berbayang untuk tampilan bersih.", + "history.sketch_under_constrained": "Kurang dibatasi ({count} derajat kebebasan)", + "history.sketch_under_constrained_one": "Kurang dibatasi ({count} derajat kebebasan)", "hole_presets.confirm_delete": "Konfirmasi hapus", "hole_presets.delete": "Hapus", "hole_presets.delete_prompt": "Hapus preset pribadi ini? Lubang yang sudah ada tidak berubah.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Periksa tipe sambungan (misalnya Kaku), status ground, batas sambungan, dan nilai yang digerakkan parameter.", "joint_move.blocked_title": "Tidak dapat memindahkan part ini", "joint_move.coarse": "Langkah rotasi dekat sumbu (°)", + "joint_move.conflict": "Sebuah sambungan part ini berkonflik dengan yang lain: {joint}.", + "joint_move.conflict_hint": "Edit, tekan, atau hapus sambungan yang berkonflik agar sambungan lain dapat menempatkan part.", "joint_move.distance": "Jarak dari awal", "joint_move.done": "Selesai", "joint_move.fine": "Langkah rotasi jauh dari sumbu (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Material berbeda", "measure.at": "Pada", "measure.item": "Item {number}", + "measure.quick_copied": "Pengukuran disalin", + "measure.quick_copy": "Klik untuk menyalin pengukuran", + "measure.quick_edges": "{count} tepi", + "measure.quick_faces": "{count} muka", "messages.ago_h": "{n} j lalu", "messages.ago_min": "{n} mnt lalu", "messages.ago_s": "{n} d lalu", @@ -1620,6 +1938,8 @@ "motion.track_name": "Track {number}", "nav.alias.help": "Shift+Alt+seret kiri memutar orbit, Shift+Alt+tombol tengah menggeser, Shift+Alt+klik kanan memperbesar/memperkecil; seret tombol tengah juga menggeser dan seret kanan memutar orbit", "nav.blender.help": "Seret tombol tengah memutar orbit, Shift+tombol tengah menggeser, Ctrl+tombol tengah memperbesar/memperkecil; seret kanan tidak menggerakkan kamera", + "nav.creo.help": "Seret tombol tengah memutar orbit, Shift+tombol tengah menggeser, Ctrl+seret tombol tengah secara vertikal memperbesar/memperkecil (ke bawah untuk memperbesar); gulir roda untuk zoom", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Mouse dan mouse 3D berputar melewati kedua kutub dan mempertahankan roll. Penjepretan sumbu dengan Shift dinonaktifkan.", "nav.free_orbit.label": "Orbit bebas", "nav.free_orbit.snap_help": "Mouse dan mouse 3D berputar melewati kedua kutub dan mempertahankan roll. Tahan Shift saat menyeret orbit untuk menjepret arah tampilan dan roll.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+seret kiri menggeser, Shift+Alt+kiri memperbesar/memperkecil, Ctrl+seret kiri di area kosong mengorbit", "nav.inventor.help": "Seret tombol tengah menggeser, Shift+tombol tengah memutar orbit, Ctrl+tombol tengah memperbesar/memperkecil, seret kanan memutar orbit", "nav.maya.help": "Alt+seret kiri mengorbit, Alt+tengah menggeser, Alt+kanan memperbesar/memperkecil; seret tengah juga menggeser", + "nav.nx.help": "Seret tombol tengah memutar orbit, Shift+tombol tengah menggeser (tombol tengah + kanan di NX), Ctrl+tombol tengah memperbesar/memperkecil (tombol tengah + kiri di NX); seret kanan tidak menggerakkan kamera", "nav.openscad.help": "Seret kiri di ruang kosong memutar orbit, Shift+seret kiri memilih dengan kotak, seret geometri sketsa mengeditnya; seret kanan atau tombol tengah menggeser, Shift+seret kanan atau Shift+seret tombol tengah memperbesar/memperkecil", "nav.perspective.sketch": "Pengeditan sketsa memakai tampilan ortografis. Selesaikan sketsa untuk beralih ke perspektif.", "nav.right_drag_orbits.help": "Mati: seret kanan tidak menggerakkan kamera dan tombol kanan hanya membuka menu konteks. Memilih pemetaan mouse SolidWorks akan mematikannya.", @@ -1748,6 +2069,11 @@ "not a move": "bukan pemindahan", "not a number": "bukan angka", "open a sketch first": "buka sketsa terlebih dahulu", + "parameters.apply_live": "Terapkan setiap perubahan saat Anda meninggalkan kolomnya", + "parameters.apply_live_tip": "Mati: perubahan menunggu sampai Terapkan atau OK, lalu desain dibangun ulang sekali untuk semuanya. Batal atau Escape membuangnya.", + "parameters.held": "{count} perubahan menunggu Terapkan", + "parameters.held_hint": "Edit ekspresi dan satuan. Perubahan menunggu Terapkan atau OK.", + "parameters.held_one": "1 perubahan menunggu Terapkan", "parts.automatic_name": "otomatis", "parts.dimension.across_flats": "Lebar antar sisi datar", "parts.dimension.bore": "Diameter lubang", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Sekrup kepala bulat (button head)", "parts.family.dowel_pin": "Pin paralel (dowel)", "parts.family.hex_bolt": "Baut / sekrup kepala segi enam", + "parts.family.hex_cap_screw_inch": "Sekrup kepala segi enam (cap screw, inci)", "parts.family.hex_nut": "Mur segi enam", + "parts.family.hex_nut_inch": "Mur segi enam (inci)", "parts.family.set_screw": "Sekrup set soket segi enam, ujung datar", "parts.family.socket_head_cap_screw": "Sekrup kepala soket (cap screw)", "parts.family.washer": "Ring datar (washer)", + "parts.family.washer_sae": "Ring datar (washer), SAE (sempit)", + "parts.family.washer_uss": "Ring datar (washer), USS (lebar)", + "parts.holes": "Lubang (opsional)", + "parts.placement_hint": "pilih satu lubang atau lebih untuk menempatkan part di masing-masing, atau OK menempatkannya di origin", + "parts.system": "Sistem satuan", + "parts.system.inch": "Inci", + "parts.system.metric": "Metrik", "pattern.alignment_2": "Perataan 2", "pattern.alignment_hint": "Jumlah termasuk yang asli. Center menyeimbangkan salinan; Flip memilih sisi tambahan untuk total genap.", "pattern.direction_1": "Arah 1", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Menghaluskan tepi bergerigi.", "prefs.applies_on_restart": "Berlaku setelah dimulai ulang", "prefs.assistant": "Asisten", + "prefs.auto_operation": "Pilih operasi secara otomatis", + "prefs.auto_operation_note": "Jendela fitur memilih Gabung, Bodi Baru, atau Potong berdasarkan apa yang disentuh material baru, sampai Anda memilih salah satu. Mati: jendela mempertahankan operasi yang dipakai saat dibuka.", "prefs.axes": "Sumbu", "prefs.axis": "Sumbu", "prefs.bodies_folders": "Folder bodi", @@ -1820,6 +2157,8 @@ "prefs.bottom_centre": "Tengah bawah", "prefs.bottom_right": "Kanan bawah", "prefs.browser": "Penjelajah", + "prefs.browser_eye_left": "Ikon mata di sebelah panah perluas/ciutkan", + "prefs.browser_eye_left_note": "Baris penjelajah menampilkan ikon mata tampilkan/sembunyikan di sebelah panah perluas/ciutkan, seperti sebelumnya, bukan dalam satu kolom di ujung kanan baris.", "prefs.browser_reveal_on_hover": "Tampilkan saat disorot", "prefs.browser_show_note": "Ditampilkan menjaga penjelajah tetap di layar. Tampilkan saat disorot menyembunyikannya sampai penunjuk berada di atas tempatnya atau di atas tab tipis di tepi kirinya, dan penjelajah tetap terbuka selama penunjuk ada di dalamnya atau ada menu darinya yang terbuka.", "prefs.browser_shown": "Ditampilkan", @@ -1827,6 +2166,8 @@ "prefs.button_left": "Seret kiri", "prefs.button_middle": "Seret tengah", "prefs.button_right": "Seret kanan", + "prefs.carousel_next": "Berikutnya", + "prefs.carousel_previous": "Sebelumnya", "prefs.choose_font": "Pilih file font…", "prefs.click": "Klik", "prefs.contact_shading": "Bayangan kontak lembut", @@ -1839,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Permukaan melengkung", "prefs.curves": "Permukaan melengkung", + "prefs.cut_preview_tint": "Tampilkan material yang dihilangkan dengan warna merah", + "prefs.cut_preview_tint_help": "Pratinjau mengisi material yang dihilangkan sebuah fitur, dan bentuk yang digantikannya, dengan bayangan merah tembus pandang. Jika mati, isian itu sepenuhnya transparan dan hanya garis luarnya yang digambar.", + "prefs.dark_parts_shading": "Pertahankan bentuk part yang gelap", + "prefs.dark_parts_shading_help": "Melakukan pewarnaan tampilan dalam cahaya linear dengan cahaya pengisi langit yang lembut, sehingga muka yang gelap tetap memiliki gradasi dan tidak menjadi hitam", "prefs.dead_zone_note": "Pita berarsir adalah zona mati: gerakan di dalamnya diabaikan.", "prefs.default": "default", "prefs.design": "Default desain", @@ -1853,6 +2198,8 @@ "prefs.edges": "Tepi dan pewarnaan", "prefs.extend": "Perpanjang", "prefs.extra_navigation": "Ctrl+seret kiri pada ruang kosong untuk orbit; tahan Space untuk geser.", + "prefs.extrude_view_isometric": "Putar tampilan ke isometrik saat Ekstrusi dibuka", + "prefs.extrude_view_return": "Kembali ke tampilan sebelumnya saat Ekstrusi ditutup", "prefs.follows_os": "Mengikuti OS", "prefs.font": "Font", "prefs.font_fallback": "Glif yang tidak dimiliki font pilihan akan memakai font bawaan, sehingga tidak ada label yang menampilkan kotak kosong.", @@ -1868,8 +2215,11 @@ "prefs.graphics_card_auto": "Otomatis", "prefs.graphics_card_missing": "Kartu grafis yang disimpan tidak tersedia; Otomatis dipakai.", "prefs.graphics_card_restart": "Berlaku setelah SolidCraft dimulai ulang. WGPU_ADAPTER_NAME menggantikan pilihan ini.", + "prefs.graphics_card_unused": "Kartu grafis yang tersimpan tidak dipakai untuk jendela ini; kartu yang sedang dipakai ditampilkan di Bantuan › Tentang dan di bilah status. Coba Otomatis, atau atur WGPU_ADAPTER_NAME ke bagian unik dari nama kartu.", "prefs.graphics_note": "Tukar kecepatan dengan kehalusan. Setiap pilihan menampilkan efeknya pada sebuah contoh.", "prefs.graphics_presets_note": "Preset mengatur pilihan di bawah secara bersamaan.", + "prefs.hide_constraint_glyphs_zoomed_out": "Sembunyikan glif batasan saat zoom out", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Glif batasan menghilang dari tampilan saat sketsa di-zoom out cukup jauh sehingga glif itu membuat tampilan berantakan. Mati: glif tetap berukuran sama di layar pada setiap tingkat zoom.", "prefs.history": "Riwayat", "prefs.history_origin_bodies": "Tampilkan origin dan bodi di bagian atas", "prefs.history_origin_bodies_note": "Riwayat di sisi kiri atau di bawah penjelajah dimulai dengan folder Bodi komponen aktif dan Origin, lengkap dengan ikon mata dan menunya seperti di penjelajah. Riwayat di bagian bawah tidak berubah.", @@ -1880,6 +2230,8 @@ "prefs.history_sketches_note": "Jika Sketsa diatur ke Di bawah fiturnya, Riwayat di sisi kiri mencantumkan setiap sketsa satu tingkat ke dalam, di bawah fitur pertama yang dibuat darinya, selama cukup lebar untuk menampilkan nama. Timeline di bagian bawah selalu mempertahankan urutan pembuatan.", "prefs.history_sketches_under_feature": "Di bawah fiturnya", "prefs.hold_stop_snapping": "Tahan untuk menghentikan snap", + "prefs.home_fit_size": "Ukuran Awal dan Pas", + "prefs.home_fit_size_note": "Seberapa besar bagian tampilan yang diisi model saat Awal, Pas, desain yang baru dibuka, atau perubahan tampilan lewat navigator tampilan membingkainya, baik pengaturan di bawah ini aktif maupun tidak. 100 %: mengisi tampilan di antara panel, kompas, dan bilah navigasi.", "prefs.icons_only": "Hanya ikon", "prefs.imported_file": "File yang diimpor", "prefs.in_browser": "Di dalam penjelajah", @@ -1888,13 +2240,22 @@ "prefs.interface_language": "Bahasa antarmuka", "prefs.interface_note": "Tampilan SolidCraft dan letak bagian-bagiannya.", "prefs.interval_minutes": "{n} mnt", + "prefs.invert_curved_roll_arrows": "Balikkan panah roll melengkung", + "prefs.invert_curved_roll_arrows_note": "Dua panah melengkung di sudut kubus memutar (roll) tampilan di dalam bidang layar. Aktif: panah searah jarum jam memutar berlawanan arah jarum jam dan panah berlawanan arah jarum jam memutar searah jarum jam. Mati: tiap panah memutar tampilan sesuai arah lengkungannya.", + "prefs.invert_navigator_arrows": "Balikkan panah rotasi kubus tampilan", + "prefs.invert_navigator_arrows_note": "Panah di sekeliling kubus memutar orbit kamera ke arah yang ditunjuknya, seperti di Fusion dan Inventor: panah di kiri menunjuk ke kanan dan mengayunkan kamera ke kanan. Mati: panah memutar kubus ke sisi tempatnya berada, sehingga panah kiri mengayunkan kamera ke kiri. Panah roll yang melengkung tidak terpengaruh.", + "prefs.keep_work_on_tab_switch": "Biarkan dialog dan alat tetap terbuka saat berpindah desain", + "prefs.keep_work_on_tab_switch_note": "Setiap tab desain mempertahankan dialog atau alat yang terbuka, beserta apa yang Anda pilih dan ketik di dalamnya, dan tab toolbar-nya. Semuanya kembali saat Anda kembali ke desain itu. Mati: berpindah desain membatalkannya dan menampilkan tab Model.", "prefs.labels": "Label", + "prefs.language_system": "Sistem", "prefs.layout": "Tata letak", "prefs.layout_note": "Ringkas menempelkan panel ke tepi jendela. Translusensi penjelajah tersedia di Mengambang. Ubah sisi Asisten di halaman Asisten.", "prefs.left": "Kiri", "prefs.left_click": "Klik kiri", "prefs.line_drag_draws_one": "Tekan dan seret menggambar satu garis", "prefs.line_drag_draws_one_note": "Di alat Garis, menekan, menyeret, lalu melepas menggambar satu garis dari titik tekan hingga titik lepas, dan garis berakhir di sana. Klik tetap menggambar rantai. Mati: seretan menaruh titik di tempat dilepas, seperti klik.", + "prefs.line_hover_tangent_arc": "Diamkan penunjuk di titik terakhir garis untuk beralih ke busur tangen", + "prefs.line_hover_tangent_arc_note": "Di alat Garis, setelah satu segmen digambar, jauhkan penunjuk dari titik terakhir rantai, kembali, lalu diamkan penunjuk di titik itu: klik berikutnya menentukan ujung busur tangen, dan gerakan yang sama kembali ke garis. Mati: berdiam di sana tidak berpengaruh.", "prefs.linked_designs": "Desain tertaut", "prefs.live_input": "Input langsung", "prefs.live_preview": "Pratinjau langsung", @@ -1908,6 +2269,9 @@ "prefs.max_file_size_step": "File STEP dan impor", "prefs.max_file_size_web": "Aplikasi web membuka file STEP dan impor hingga 512 MB serta desain hingga 256 MB: tab peramban tidak dapat menampung file yang lebih besar. Aplikasi desktop dapat menaikkan batas ini.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Ikon besar", + "prefs.menu_list": "Daftar", + "prefs.menus": "Menu", "prefs.minutes": "menit", "prefs.minutes_suffix": " mnt", "prefs.mouse": "Mouse dan trackpad", @@ -1915,6 +2279,8 @@ "prefs.mouse_mapping": "Pemetaan mouse", "prefs.navigation": "Navigasi", "prefs.navigation_note": "Cara mouse, trackpad, dan mouse 3D menggerakkan tampilan.", + "prefs.navigator_fit": "Buat model pas di tampilan setelah perubahan tampilan lewat navigator", + "prefs.navigator_fit_note": "Sebuah muka, sudut, atau panah pada kubus tampilan, atau sumbu pada gizmo, juga menghadap ke tengah model dari satu jarak yang membuatnya pas dari segala sisi (bola pembatasnya). Awal memakai zoom dan pusat yang sama selama opsi ini aktif, sehingga tampilan yang dipilih setelahnya hanya berputar. Mati: tampilan berputar di tempat, dengan target dan zoom tetap.", "prefs.network_host_remove": "Hapus", "prefs.network_locations": "Izinkan lokasi jaringan di desain", "prefs.network_locations_note": "Nonaktif: file tertaut sebuah desain di komputer lain (\\\\server\\share) hanya dibuka dari server yang tercantum di sini, atau setelah Anda mengizinkan salah satunya saat ditanya.", @@ -1927,10 +2293,18 @@ "prefs.origin_plane_names": "Nama bidang origin", "prefs.origin_plane_names_note": "Nama yang ditampilkan di penjelajah, dialog, dan daftar. {top} adalah XY, {front} adalah XZ, dan {right} adalah YZ, dengan Z ke atas. Perintah, skrip, dan desain tersimpan tetap memakai XY, XZ, dan YZ.", "prefs.overall_speed": "Kecepatan keseluruhan", + "prefs.parameter_list_rows": "Baris daftar parameter", + "prefs.parameter_list_rows_tip": "Panah bawah di kolom nilai yang kosong menampilkan daftar parameter, favorit lebih dulu, hingga sebanyak baris ini. Lebih sedikit menjaga daftar tetap ringan di desain besar.", + "prefs.persistent_ribbon_pressed": "Sorot perintah ribbon yang aktif", + "prefs.persistent_ribbon_pressed_help": "Sorot perintah ribbon selama efeknya aktif. Matikan untuk mempertahankan tampilan netral dan bantuan perintah sebelumnya.", "prefs.perspective_fov": "Bidang pandang", "prefs.placement": "Penempatan", "prefs.prefer_free_sketch_points": "Utamakan titik sketsa yang dapat digerakkan saat titik saling tumpang tindih", "prefs.preview_choices": "Pratinjau pilihan Anda", + "prefs.preview_tint_new_faces": "Warnai permukaan baru di pratinjau", + "prefs.preview_tint_new_faces_help": "Pratinjau fitur yang mengubah sebuah bodi dapat menggambar permukaan yang ditambahkannya dengan warna pratinjau. Jika mati, bodi digambar apa adanya.", + "prefs.print_face_highlight": "Sorotan permukaan cetak", + "prefs.print_face_highlight_tip": "Seberapa kuat permukaan cetak sebuah bodi diwarnai dan diberi garis tepi di tampilan. 0 % tidak menampilkan sorotan.", "prefs.profile_active": "Profil aktif", "prefs.profile_applied": "Profil diterapkan.", "prefs.profile_changed": "Pengaturan berubah sejak profil disimpan. Simpan akan menyimpannya ke profil.", @@ -1952,9 +2326,13 @@ "prefs.quality_fastest": "tercepat", "prefs.quality_slowest": "paling lambat", "prefs.quality_smoother": "lebih halus", + "prefs.quick_measure": "Pengukuran cepat di sudut tampilan", + "prefs.quick_measure_note": "Ukuran pilihan di sudut kanan bawah tampilan: panjang sebuah tepi, atau Ø dan R untuk tepi bulat, luas sebuah muka, posisi sebuah titik, jarak dan sudut antara dua item, total beberapa tepi atau muka. Klik menyalinnya.", "prefs.render_previous_geometry_budget": "Gunakan anggaran geometri pratinjau Render sebelumnya", "prefs.render_previous_geometry_budget_help": "Pulihkan batas geometri tetap sebelumnya (512 MiB di desktop 64-bit, 128 MiB di tempat lain) alih-alih anggaran berbasis perangkat.", "prefs.reports_saved": "{n} tersimpan", + "prefs.ribbon_click_ends_tool": "Mengklik tombol alat yang sedang berjalan mengakhirinya", + "prefs.ribbon_click_ends_tool_note": "Klik pada tombol ribbon yang menyala dari alat sketsa yang sedang dipakai mengakhiri alat itu, sehingga klik di tampilan kembali memilih. Mati: klik memulai alat itu lagi.", "prefs.ribbon_reveal": "Tampilkan hasil pencarian di ribbon", "prefs.ribbon_reveal_note": "Mengarahkan kursor ke hasil di Cari perintah menunjukkan letak perintah itu di ribbon: tab-nya, tombolnya, atau barisnya di dropdown panel. Perintah yang dimulai dari pencarian berkedip di sana, dan perintah yang berjalan dari dropdown menandai panelnya.", "prefs.right_click": "Klik kanan", @@ -1965,6 +2343,8 @@ "prefs.search_empty": "Tidak ada pengaturan yang cocok", "prefs.select": "Pilih", "prefs.select_one_item": "Pilih satu item", + "prefs.select_other_hidden": "Pilih geometri tersembunyi dengan Pilih Lainnya", + "prefs.select_other_hidden_help": "Aktif: sertakan bodi, sketsa, dan tepi tersembunyi di dekat penunjuk. Mati: pakai daftar asli geometri terlihat di bawah penunjuk.", "prefs.selecting": "Pemilihan", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift hanya menambah; Ctrl / Cmd mengalihkan", @@ -1976,31 +2356,63 @@ "prefs.sketch_align_points_note": "Saat menggambar, sebuah titik sejajar secara horizontal dengan satu titik sketsa dan secara vertikal dengan titik lain sekaligus, dengan pemandu titik-titik, dan klik mempertahankan kedua perataan itu. Mati: hanya dengan titik sebelumnya, satu sumbu setiap kali.", "prefs.sketch_conflict_colour": "Geometri yang konflik dengan warna konflik", "prefs.sketch_conflict_colour_note": "Saat batasan sketsa saling konflik, kurva dan titik yang ditahan oleh batasan yang gagal juga digambar dengan warna konflik, bukan hanya glif atau dimensinya. Mati: warnanya tetap seperti biasa.", + "prefs.sketch_construction_lines": "Alat garis bantu lanjutan", "prefs.sketch_exit_view": "Saat sketsa selesai", "prefs.sketch_exit_view.keep": "Pertahankan tampilan saat ini", "prefs.sketch_exit_view.previous": "Kembali ke tampilan sebelumnya", "prefs.sketch_exit_view.unless_rotated": "Kembali kecuali diputar", "prefs.sketch_exit_view_note": "Ke mana tampilan beralih setelah Selesai Sketsa, Batal, atau Esc dua kali.", + "prefs.sketch_face_activates_part": "Menggambar sketsa di muka part membuat part itu aktif", + "prefs.sketch_face_activates_part_note": "Sketsa yang dimulai di muka bodi milik komponen lain mengaktifkan komponen itu lebih dulu, sehingga sketsa menjadi milik komponen tersebut dan tetap bersama part itu di penjelajah. Part itu tetap aktif setelahnya. Mati: sketsa menjadi milik komponen aktif.", + "prefs.sketch_open_look_at": "Putar untuk menghadap sketsa saat dibuka", + "prefs.sketch_open_look_at_note": "Mati: membuat atau mengedit sketsa membiarkan tampilan apa adanya. Look At menghadapkan tampilan ke sketsa saat Anda menginginkannya.", "prefs.sketch_recent_snap": "Snap otomatis ke pusat dan titik tengah terbaru", "prefs.sketch_recent_snap_note": "Saat menggambar, kursor melakukan snap ke titik persilangan pemandu dari dua pusat lingkaran atau titik tengah tepi lurus terbaru. Mati: pemandu tersebut hanya bersifat visual dan kursor tidak bergerak.", "prefs.sketch_selection": "Sketsa & pilihan", "prefs.sketch_selection_heading": "Sketsa dan pilihan", "prefs.sketch_selection_note": "Cara sketsa melakukan snap dan cara klik memilih.", + "prefs.sketch_state_icons": "Ikon sketsa dengan warna statusnya", + "prefs.sketch_state_icons_note": "Di Riwayat dan penjelajah, ikon sketsa mengambil warna statusnya (kurang dibatasi, terbatasi penuh, atau bertentangan) dan tooltip-nya menyebut statusnya. Mati: setiap sketsa memakai ikon yang sama.", "prefs.sketch_tab_always": "Selalu tampilkan tab Sketsa", "prefs.sketch_tab_always_note": "Tab Sketsa tetap ada di ribbon, tepat setelah Model, selama tidak ada sketsa yang terbuka. Alat gambarnya lalu memulai sketsa pada bidang atau muka yang dipilih, atau pada bidang yang Anda pilih berikutnya, dengan alat yang sudah siap di dalamnya.", "prefs.sketch_tracking_guides": "Pemandu perataan pusat dan titik tengah", "prefs.sketch_tracking_guides_note": "Arahkan kursor ke pusat lingkaran atau titik tengah tepi lurus, lalu gerakkan secara horizontal atau vertikal untuk menampilkan pemandu titik-titik sementara.", + "prefs.sketch_tracking_points": "Pemandu penyejajaran dari titik ujung dan sudut saat menggambar", + "prefs.sketch_tracking_points_note": "Saat alat gambar menunggu sebuah titik, mengarahkan kursor ke ujung garis atau busur, sudut persegi panjang, atau titik bebas menampilkan pemandu bertitik sementara yang sama seperti untuk pusat atau titik tengah. Mati: hanya pusat dan titik tengah.", "prefs.sketching": "Menggambar sketsa", "prefs.snap_drawing_note": "Saat menggambar atau menyeret titik sketsa.", "prefs.source": "Sumber", "prefs.speed": "Kecepatan", "prefs.stand_up_note": "Setelah file STEP atau IGES terbuka dengan Z ke atas, tawarkan seperempat putaran mengelilingi X.", + "prefs.stand_up_unknown": "Untuk file dari program yang tidak dikenal", + "prefs.stand_up_unknown.ask": "Tanya di dialog", + "prefs.stand_up_unknown.note": "Tampilkan catatan", + "prefs.stand_up_unknown.off": "Jangan tawarkan", + "prefs.stand_up_unknown_note": "Cara tawaran diberikan saat header file tidak menyebut program yang dikenal menyimpan dengan Y ke atas. Catatan hanya ditampilkan saat file tampak telentang; Tanya di dialog menanyakan setiap file semacam itu, seperti sebelumnya.", "prefs.status_bar": "Bilah status", "prefs.status_bar_note": "Bilah tipis di sepanjang tepi bawah jendela menampilkan apa yang sedang diedit, status sketsa yang terbuka dengan warnanya, dan satuan desain; klik pada satuan akan mengubahnya. Status sketsa lalu tidak lagi tampil di sudut tampilan.", "prefs.status_done": "Selesai", "prefs.status_error": "Error", "prefs.status_selected": "Terpilih", "prefs.status_warning": "Peringatan", + "prefs.structure.appearance": "Tampilan", + "prefs.structure.appearance_note": "Warna, teks, dan aksesibilitas.", + "prefs.structure.in_profile": "Dalam profil", + "prefs.structure.layout": "Tata letak", + "prefs.structure.layout_note": "Letak bagian-bagian jendela.", + "prefs.structure.look": "Rupa", + "prefs.structure.measure_pointer": "Ukur dan penunjuk", + "prefs.structure.mouse3d": "Mouse 3D", + "prefs.structure.mouse3d_note": "SpaceMouse dan SpaceNavigator.", + "prefs.structure.navigation_note": "Mouse dan trackpad. Mouse 3D punya halamannya sendiri.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Berubah sejak disimpan", + "prefs.structure.profile_hover": "Disimpan di profil pengaturan", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Sketsa", + "prefs.structure.tools": "Alat", + "prefs.structure.tools_note": "Cara kerja alat pemodelan.", + "prefs.structure.work": "Kerja", "prefs.supersampling_brief": "Menggambar tampilan lebih besar lalu menyaringnya turun: sangat tajam, tetapi lebih berat.", "prefs.tab_accent_note": "Aksen mengikuti tab aktif", "prefs.theme_file": "file tema", @@ -2012,6 +2424,16 @@ "prefs.theme_follow_off": "Nonaktif", "prefs.theme_follow_stop": "Berhenti mengikuti", "prefs.theme_import_hint": "Klik untuk memilih file tema, seret satu ke sini, atau tekan Ctrl+V (Cmd+V di Mac) setelah menyalin tema", + "prefs.theme_option_opacity": "Opasitas", + "prefs.theme_option_opacity_help": "Atur opasitas panel mengambang. Batas minimum keterbacaan melindungi teks di atas warna viewport.", + "prefs.theme_option_tab_colours": "Warna tab", + "prefs.theme_option_tab_colours_help": "Pakai warna panel dan viewport tema ini untuk setiap tab ribbon.", + "prefs.theme_option_tab_fade_ms": "Transisi tab", + "prefs.theme_option_tab_fade_ms_help": "Memudarkan warna panel dan viewport saat berpindah tab. Nol berpindah seketika.", + "prefs.theme_options_badge": "Opsi", + "prefs.theme_options_more": "Lainnya · {count}", + "prefs.theme_options_reset": "Reset", + "prefs.theme_options_unavailable": "Tidak tersedia di perangkat ini", "prefs.theme_paste": "Tempel tema", "prefs.theme_paste_none": "Papan klip tidak berisi tema SolidCraft", "prefs.timeline_half_hour": "−30 mnt", @@ -2033,13 +2455,23 @@ "prefs.under_cursor": "Di bawah kursor", "prefs.units_precision": "Satuan dan presisi", "prefs.updates": "Pembaruan", + "prefs.value_boxes_in_view": "Tampilkan nilai di samping handle-nya di tampilan", + "prefs.value_boxes_in_view_tip": "Nilai sebuah perintah (Jarak, Radius…) dalam kotak di samping handle-nya, di atas model. Mati: Anda mengetiknya di jendela perintah, yang menerima keyboard setelah pemilihan, dan tidak ada yang menutupi model.", "prefs.view": "Perilaku tampilan", "prefs.view_confirm_corner": "OK dan Batal di sudut tampilan", "prefs.view_confirm_corner_note": "Saat dialog atau sketsa terbuka, tanda centang dan tanda silang di kanan atas tampilan melakukan hal yang sama seperti OK dan Batal pada dialog, atau menyelesaikan dan membatalkan sketsa. Navigator tampilan bergeser ke bawahnya.", "prefs.viewport": "Viewport", + "prefs.viewport_analysis_status": "Tampilkan status analisis viewport", + "prefs.viewport_analysis_status_help": "Tampilkan analisis yang aktif di atas viewport, buka legendanya dari setiap item, dan gunakan Esc untuk mematikan analisis terbaru. Matikan untuk mengembalikan legenda di sudut dan perilaku Esc sebelumnya.", "prefs.viewport_background": "Latar belakang", "prefs.viewport_background_colour": "Warna", "prefs.viewport_background_theme": "Gradasi tema", + "prefs.viewport_section_status": "Tampilkan status penampang viewport", + "prefs.viewport_section_status_help": "Tampilkan pengaturan penampang di viewport. Escape dan tombol ribbon yang aktif mematikannya. Matikan untuk mempertahankan kontrol penampang sebelumnya.", + "prefs.viewport_status_details": "Detail viewport langsung", + "prefs.viewport_status_details_help": "Edit pengaturan analisis dan penampang yang aktif di kartu detail standar. Matikan untuk memulihkan tombol analisis hanya-baca dan dialog Penampang.", + "prefs.viewport_status_summary": "Lipat item status viewport", + "prefs.viewport_status_summary_help": "Lipat tiga item status viewport atau lebih menjadi satu lencana ringkasan. Matikan untuk mempertahankan setiap item di baris penuh.", "prefs.wheel": "Roda", "prefs.wheel_trackpad": "Roda dan trackpad", "prefs.workspace": "Workspace", @@ -2049,6 +2481,10 @@ "properties.title": "Properti: {name}", "recovery.days_ago": "{count} hari lalu", "recovery.detail": "{file} · {features} fitur · disimpan otomatis {when}", + "recovery.discard_all": "Buang semua", + "recovery.discard_all_detail": "Aksi ini tidak dapat diurungkan.", + "recovery.discard_all_title": "Buang {count} simpan otomatis?", + "recovery.discard_all_title_one": "Buang 1 simpan otomatis?", "recovery.hours_ago": "{count} jam lalu", "recovery.just_now": "baru saja", "recovery.min_ago": "{count} mnt lalu", @@ -2164,6 +2600,10 @@ "render.base_color": "Warna dasar · sRGB", "render.base_metallic": "Fraksi metalik", "render.base_opaque_only": "Editor ini mempertahankan semantik bodi opak. Gunakan kontrol kaca eksplisit untuk transmisi optik.", + "render.batch_all_shots": "Semua bidikan ({count})", + "render.batch_empty": "Simpan sebuah bidikan sebelum merender semua bidikan.", + "render.batch_limit": "Render Semua Bidikan dibatasi hingga 32 bidikan.", + "render.batch_status": "{running} berjalan · {waiting} menunggu", "render.bloom_enable": "Tampilkan bloom", "render.bloom_help": "Cahaya kreatif khusus keluaran dari sorotan linear positif, disebar dengan tiga lintasan kotak ternormalisasi. Radius dalam piksel keluaran. Ditambahkan dalam cahaya tampilan linear sebelum sRGB; bukan lensa, efek volumetrik, atau peningkatan konvergensi. EXR mentah tidak berubah.", "render.bloom_opaque": "Bloom memerlukan keluaran opak. PNG transparan ditolak, tidak diratakan secara diam-diam.", @@ -2274,6 +2714,13 @@ "render.choose_look": "Pilih look di Tampilan terlebih dahulu", "render.chromatic_offset": "Offset tepi kromatik", "render.clear_stage": "Hapus panggung tersimpan", + "render.compare_divider": "Pembagi perbandingan", + "render.compare_live": "Langsung", + "render.compare_live_preview": "Pratinjau langsung", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} d · {renderer} · ditangkap pada revisi {revision}", + "render.compare_swap": "Tukar", "render.copy_request": "Salin JSON", "render.cpu_aa_help": "Sampel spasial: lebih banyak sampel memperbaiki tepi dan menambah waktu render.", "render.cpu_area_add": "Tambah lampu persegi panjang CPU", @@ -2914,7 +3361,9 @@ "render.output_ready": "Siap dirender", "render.output_run_check": "Jalankan pemeriksaan", "render.output_size_limit": "{method}: hingga {dimension} px per sisi dan {pixels} piksel. Ukuran terbesar yang muat: {width} × {height}.", + "render.output_size_method_profile": "Untuk merender {width} × {height}, pilih {method} dengan profil sumber daya CPU {profile}, atau ukuran yang lebih kecil.", "render.output_size_ok": "Ukuran OK · {width} × {height} px", + "render.output_size_profile": "Untuk merender {width} × {height}, pilih profil sumber daya CPU {profile}, atau ukuran yang lebih kecil.", "render.output_swap_orientation": "Tukar lebar dan tinggi", "render.output_tools_inspector": "Edit ukuran dan format di Inspektor Keluaran.", "render.output_view_image": "Lihat gambar", @@ -3021,6 +3470,10 @@ "render.result_retained": "Menampilkan gambar selesai terakhir; render yang lebih baru belum menggantikannya.", "render.result_sequence": "Checkpoint", "render.result_title": "Hasil Render", + "render.results_choose": "Hasil yang dipertahankan", + "render.results_label": "Render {number} · {shot} · {seconds} d", + "render.results_stale_label": "{result} [usang]", + "render.results_unnamed": "Gambar", "render.return_design": "Kembali ke Desain", "render.review_stale": "Tinjauan ini sudah usang. Selesaikan atau periksa lagi sebelum menerapkan.", "render.ribbon_aging": "Penuaan", @@ -3127,6 +3580,7 @@ "render.size_custom": "Kustom…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · memerlukan {profile}", "render.size_presets": "Preset ukuran", "render.size_presets_pending": "Hadir bersama editor Keluaran", "render.size_preview": "Pratinjau", @@ -3414,6 +3868,24 @@ "sheet.flange_type_contour": "Kontur", "sheet.flange_type_edge": "Tepi", "sheet.no_body": "tidak ada bodi pelat logam: mulai satu dengan Flens > Base, atau ubah pelat menjadi pelat logam dengan Konversi ke Pelat Logam (pilih muka datar besarnya)", + "sheet.personal_rules.confirm_delete": "Konfirmasi hapus", + "sheet.personal_rules.delete": "Hapus", + "sheet.personal_rules.delete_prompt": "Hapus aturan pribadi ini? Aturan yang sudah ada di desain tidak berubah.", + "sheet.personal_rules.full": "Pustaka pribadi sudah berisi 64 aturan.", + "sheet.personal_rules.invalid_name": "Masukkan nama singkat tanpa jeda baris atau karakter kontrol.", + "sheet.personal_rules.invalid_values": "Lengkapi nilai aturan: masing-masing harus dapat dihitung di desain ini, dengan ketebalan positif dan faktor K dari 0 sampai 1.", + "sheet.personal_rules.missing": "Aturan pribadi terpilih sudah tidak tersedia.", + "sheet.personal_rules.name": "Nama aturan", + "sheet.personal_rules.name_exists": "Aturan pribadi dengan nama ini sudah ada. Gunakan nama lain.", + "sheet.personal_rules.name_hint": "Nama yang unik", + "sheet.personal_rules.overwrite": "Simpan perubahan ke aturan pribadi terpilih", + "sheet.personal_rules.rename": "Ganti nama", + "sheet.personal_rules.rule": "Aturan pribadi", + "sheet.personal_rules.save": "Simpan baru", + "sheet.personal_rules.scope": "Disimpan di profil Anda untuk semua desain.", + "sheet.personal_rules.select": "Pilih aturan", + "sheet.personal_rules.title": "Aturan pribadi", + "sheet.personal_rules.unsupported": "Aturan ini memiliki nilai yang tidak dapat dipakai versi ini.", "shortcut.json_error": "parameter harus berupa JSON: {error}", "shortcut.no_command": "tidak ada perintah `{id}`; teks sebelum JSON harus berupa id perintah", "shortcut.pin": "Sematkan di atas kotak S", @@ -3450,8 +3922,10 @@ "sketch_text.align_right": "Kanan", "sketch_text.bold": "Tebal", "sketch_text.builtin_font": "{family} (bawaan)", + "sketch_text.formula": "Mulai dengan = untuk menyusun kata dari parameter: ='W' + number(Width)", "sketch_text.italic": "Miring", "sketch_text.loading_fonts": "Mencari font terpasang…", + "sketch_text.no_bold": "Font bawaan tidak memiliki varian tebal: pilih font yang terpasang", "sketch_text.on_path": "Teks mengikuti jalurnya: kurva yang menempatkannya", "sketch_text.path_clear": "Lepaskan teks dari kurvanya", "sketch_text.path_hint": "Kurva sketsa yang diikuti teks: klik di sini, lalu kurvanya", @@ -3483,10 +3957,7 @@ "the two origins are on the same component": "kedua origin berada pada komponen yang sama", "thread.automatic_size": "Ukuran otomatis", "thread.designation": "Penunjukan", - "thread.direction": "Arah ulir", "thread.iso_metric": "ISO metrik", - "thread.left_hand": "Ulir kiri", - "thread.right_hand": "Ulir kanan", "thread.select_size": "Pilih ukuran", "timeline.delete_after_marker_one": "Hapus 1 Fitur Setelah Penanda Riwayat", "timeline.delete_after_marker_other": "Hapus {count} Fitur Setelah Penanda Riwayat", @@ -3503,8 +3974,10 @@ "timeline.move_to_group": "Pindahkan Fitur ke Folder", "timeline.rename_group": "Ganti Nama Folder Fitur", "timeline.reorder_many": "Urutkan Ulang Fitur", + "timeline.suppress_features": "Tekan Fitur", "timeline.suppress_folders_tip": "Tekan atau lepas penekanan setiap fitur di folder dan folder bersarangnya", "timeline.ungroup": "Hapus Folder Fitur", + "timeline.unsuppress_features": "Lepas Tekan Fitur", "to the face": "ke muka", "to the next face": "ke muka berikutnya", "toolbar.customize_note": "Tab {tab}. Centang perintah untuk memberinya tombol toolbar. Anda juga dapat menyeret baris dropdown panel ke toolbar, menyeret tombol keluar dari toolbar untuk menghapusnya, atau memakai pin pada baris dropdown.", @@ -3588,6 +4061,8 @@ "ui.3d_mouse_section": "Mouse 3D", "ui.3d_mouse_show_in_view": "Tampilkan mouse 3D di tampilan 3D", "ui.3d_mouse_show_in_view_tip": "Gambar mouse 3D Anda di sudut kiri bawah, bergerak mengikuti gerakan Anda.", + "ui.3d_mouse_sketch_orbit": "Putar sketsa dengan mouse 3D", + "ui.3d_mouse_sketch_orbit_tip": "Mouse 3D juga memutar tampilan saat sketsa terbuka dan dilihat tegak lurus, seperti yang dapat dilakukan mouse biasa. Mati: mouse 3D hanya menggeser dan men-zoom sketsa sampai Anda memiringkan tampilan.", "ui.3d_mouse_skip": "Perangkat saya tidak bisa ini", "ui.3d_mouse_skip_tip": "Melewati gerakan ini ke kedua arah, dan kalibrasi tidak menyertakannya.", "ui.3d_mouse_speed": "Kecepatan mouse 3D", @@ -3616,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Putar cap berlawanan arah jarum jam, tahan, lalu lepaskan.", "ui.3d_mouse_switch_cap": "Kalibrasi sebagai Kembali ke Tengah", "ui.3d_mouse_switch_trackball": "Kalibrasi sebagai trackball", + "ui.3d_mouse_use_direct": "Gunakan driver langsung", + "ui.3d_mouse_use_direct_tip": "Baca mouse 3D secara langsung (hidraw), bukan melalui spacenavd.", "ui.3d_mouse_view_axis": "Sumbu tampilan", "ui.3d_mouse_view_off": "Mati", "ui.3d_mouse_view_off_tip": "Profil driver mouse 3D mematikan sumbu ini, sehingga gerakannya tidak menggerakkan tampilan. Memilih gerakan sumbu lain di sini akan menukar keduanya, dan gerakan itu berhenti menggerakkan tampilan.", @@ -3654,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Jalankan ini di terminal, lalu tekan Hubungkan lagi:", "ui.agent_chat_auth_title": "Masuk ke agen", "ui.agent_chat_cancel": "Batal", + "ui.agent_chat_cancel_timeout": "Agen tidak merespons Berhenti dan terputus. Hubungkan lagi untuk melanjutkan.", + "ui.agent_chat_cannot_start": "Terpasang, tetapi tidak dapat dimulai: {error}", "ui.agent_chat_changes": "Perubahan: {n}, satu langkah urung", "ui.agent_chat_changes_n": "{n} perubahan", "ui.agent_chat_changes_of": "{n}/{limit} perubahan", @@ -3662,11 +4141,13 @@ "ui.agent_chat_command": "Perintah agen", "ui.agent_chat_connect": "Hubungkan", "ui.agent_chat_copy": "Salin", + "ui.agent_chat_copy_message": "Salin pesan", "ui.agent_chat_ctx_bodies": "Bodi", "ui.agent_chat_ctx_elements": "Elemen", "ui.agent_chat_ctx_features": "Fitur", "ui.agent_chat_ctx_more": "+{n} lagi", "ui.agent_chat_ctx_other": "Lainnya", + "ui.agent_chat_custom_heading": "Model kustom", "ui.agent_chat_custom_hint": "Program apa pun yang berbicara Agent Client Protocol lewat stdin dan stdout. Tidak dijalankan oleh shell.", "ui.agent_chat_denied": "Ditolak", "ui.agent_chat_deny": "Tolak", @@ -3710,8 +4191,16 @@ "ui.agent_chat_mode_all": "Semua", "ui.agent_chat_mode_ask": "Tanya", "ui.agent_chat_mode_edits": "Edit", + "ui.agent_chat_model_custom": "Gunakan kustom: {model}", "ui.agent_chat_model_no_tools": "{model} tidak dapat memakai alat SolidCraft, jadi hanya bisa mengobrol. Pilih model yang mendukung alat.", + "ui.agent_chat_model_rejected": "Agen tidak menerima {model}: {error}", + "ui.agent_chat_model_search": "Cari model…", "ui.agent_chat_model_tip": "Model yang dipakai agen. Pilihan Anda diingat untuk agen ini.", + "ui.agent_chat_models_failed": "Tidak dapat mencantumkan model: {error}", + "ui.agent_chat_models_heading": "Model yang tersedia", + "ui.agent_chat_models_listing": "Mencantumkan model…", + "ui.agent_chat_models_none": "Endpoint tidak mencantumkan model", + "ui.agent_chat_models_not_a_list": "Jawabannya bukan daftar model", "ui.agent_chat_new": "Chat baru", "ui.agent_chat_new_confirm": "Mulai chat baru? Chat saat ini akan dibersihkan.", "ui.agent_chat_next_picture": "Gambar berikutnya", @@ -3746,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "Mengantre (dihentikan, belum dikirim)", "ui.agent_chat_refresh": "Segarkan", "ui.agent_chat_refused": "Tidak diizinkan untuk agen: {reason}", + "ui.agent_chat_reinstall": "{agent} terpasang ({program}), tetapi tidak dapat dimulai saat SolidCraft memeriksanya: {error}\nInstalasinya mungkin tidak lengkap, atau dibuat untuk jenis komputer lain. Pasang lagi dengan `{install}`, periksa bahwa ia menampilkan versinya di terminal, lalu tekan Segarkan.", "ui.agent_chat_remove": "Hapus dari antrean", "ui.agent_chat_remove_file": "Lepaskan dari pesan ini", "ui.agent_chat_remove_imported": "Lepaskan dari pesan ini; part tetap berada di desain (Urungkan menghapusnya)", + "ui.agent_chat_reply_cut_off": "Balasan mencapai batas panjangnya sebelum selesai, jadi mungkin tidak lengkap. Minta agen untuk melanjutkan, atau untuk jawaban yang lebih singkat.", + "ui.agent_chat_reply_declined": "Model menolak menjawab pesan ini.", "ui.agent_chat_retry": "Coba lagi", "ui.agent_chat_right": "Kanan", "ui.agent_chat_save": "Simpan", @@ -3807,12 +4299,17 @@ "ui.ai_copy_suffix": "salinan", "ui.ai_custom_url": "URL kustom", "ui.ai_default": "Default", + "ui.ai_edit": "Edit", + "ui.ai_edit_agent_title": "Edit agen", + "ui.ai_edit_gone": "Agen ini telah dihapus, jadi tidak ada yang perlu disimpan.", + "ui.ai_edit_tip": "Ubah nama, perintah, atau endpoint agen ini. Key yang tersimpan tetap tersembunyi.", "ui.ai_http_busy": "endpoint sibuk atau melebihi batas; coba lagi nanti", "ui.ai_http_key": "endpoint menolak key: periksa di Preferensi > AI", "ui.ai_http_not_found": "endpoint atau model tidak ada: periksa URL dasar dan nama model", "ui.ai_http_too_large": "percakapan terlalu besar untuk endpoint ini; mulai obrolan baru", "ui.ai_key": "Key API", "ui.ai_key_hint": "opsional; disimpan di keychain sistem", + "ui.ai_key_keep_hint": "kosongkan untuk mempertahankan key yang tersimpan", "ui.ai_key_needs_https": "Key hanya dikirim lewat HTTPS, atau ke komputer ini.", "ui.ai_key_note": "Disimpan di keychain sistem, tidak pernah di pengaturan SolidCraft. Kosongkan untuk server lokal.", "ui.ai_keychain_error": "Keychain sistem menolak: {error}", @@ -3839,11 +4336,15 @@ "ui.ai_permissions": "Izin", "ui.ai_preset": "Preset", "ui.ai_protocol": "Protokol", + "ui.ai_reasoning_effort": "Upaya penalaran", + "ui.ai_reasoning_effort_field_hint": "kosong = default penyedia", + "ui.ai_reasoning_effort_hint": "Opsional. Dikirim ke endpoint sebagai `reasoning_effort`; nilai yang diterima berbeda untuk setiap penyedia (misalnya `low`, `high`, atau `max`). Nilai yang Anda atur di sini tidak pernah diganti oleh SolidCraft. Biarkan kosong agar tidak ada yang dikirim dan default penyedia tetap berlaku.", "ui.ai_remove": "Hapus", "ui.ai_request_timed_out": "Model membutuhkan waktu lebih dari {seconds} s. Anda dapat menaikkan batas waktu permintaan untuk endpoint ini di Preferensi › Asisten.", "ui.ai_request_timeout": "Batas waktu permintaan", "ui.ai_request_timeout_hint": "Berapa lama satu permintaan model ke endpoint ini boleh berlangsung, dari 30 s sampai satu jam. Naikkan untuk model lokal yang lambat.", "ui.ai_reset": "Reset", + "ui.ai_save": "Simpan", "ui.ai_settings": "Pengaturan AI…", "ui.ai_show_features": "Tampilkan fitur AI", "ui.ai_show_features_note": "Chat agen: panel tempat agen coding yang sudah Anda pakai, atau endpoint model pilihan Anda, bekerja pada desain yang terbuka. Nonaktif: tidak ada tombol AI, pintasan, entri menu, atau panel, dan tidak ada yang dicari atau dimulai.", @@ -3922,6 +4423,8 @@ "ui.cancel": "Batal", "ui.canvases": "Kanvas", "ui.center": "Pusat", + "ui.center_arc_follows_cursor": "Busur titik pusat mengikuti arah kursor", + "ui.center_arc_follows_cursor_tip": "Busur titik pusat berjalan searah atau berlawanan arah jarum jam sesuai arah kursor mengitari pusatnya. Mati: selalu berlawanan arah jarum jam dari awal.", "ui.centerline": "Garis tengah", "ui.chain": "Rantai", "ui.chamfer": "Chamfer", @@ -3930,6 +4433,7 @@ "ui.circle": "Lingkaran", "ui.circular_pattern": "Pola Melingkar", "ui.clear": "Bersihkan", + "ui.clear_print_face": "Hapus permukaan cetak", "ui.clear_recent": "Bersihkan Terbaru", "ui.clear_the_selection": "Hapus pilihan", "ui.click_selects_whole_bodies": "Klik memilih seluruh bodi", @@ -3964,12 +4468,27 @@ "ui.constant": "Konstan", "ui.constraints_conflict": "Batasan bertentangan", "ui.construction": "Konstruksi", + "ui.construction.angle_hint": "Garis bantu: klik sebuah titik, lalu ketik sudut atau pilih arah", + "ui.construction.bisector_hint": "Garis bagi sudut: pilih dua garis lurus yang berpotongan, lalu solusi yang diinginkan", + "ui.construction.common_hint": "Garis singgung persekutuan: pilih dua lingkaran/busur, lalu solusi yang diinginkan", + "ui.construction.contact_hint": "Garis singgung: pilih lingkaran/busur atau spline/kurva konik terbuka, lalu titik singgung (kurva bentuk bebas: titik ujung)", + "ui.construction.external_hint": "Garis singgung: pilih lingkaran atau busur, sebuah titik luar, lalu solusi yang diinginkan", + "ui.construction.free_hint": "Garis bantu: klik dua titik; klik kanan untuk mengulang", + "ui.construction.normal_needs_length": "Garis tak hingga selalu berupa garis bantu: ketik panjang untuk menggambar garis normal", + "ui.construction.point_hint": "Garis bantu: klik titik yang akan dilalui", + "ui.construction.reference_hint": "Garis bantu: pilih garis lurus, lalu sebuah titik; klik kanan untuk mengganti referensi", "ui.construction.ribbon_label": "Garis bantu", + "ui.construction.side_hint": "Garis bantu: klik sisi tempat garis mengarah; klik kanan untuk mengulang", "ui.context_menu": "Menu konteks", + "ui.continuity_crease": "Lipatan", + "ui.continuity_curvature": "Kelengkungan", + "ui.continuity_curvature_change": "Perubahan kelengkungan", "ui.continuity_g0": "Lipatan G0", "ui.continuity_g1": "Tangen G1", "ui.continuity_g2": "Kelengkungan G2", "ui.continuity_gap": "Celah", + "ui.continuity_position": "Posisi", + "ui.continuity_tangent": "Tangen", "ui.copy": "Salin", "ui.corner": "Sudut", "ui.corners": "Sudut", @@ -3992,6 +4511,7 @@ "ui.dark": "Gelap", "ui.default_modelling_orientation": "Orientasi pemodelan default", "ui.delete": "Hapus", + "ui.delete_select_first": "Pilih dulu yang akan dihapus: fitur, bodi, komponen, atau geometri sketsa", "ui.depth": "Kedalaman", "ui.design": "Desain", "ui.design_properties.author": "Pembuat", @@ -4006,6 +4526,40 @@ "ui.design_properties.project": "Proyek", "ui.design_properties.revision": "Revisi", "ui.design_saved": "Disimpan ke {path}", + "ui.details_access_caption": "Muka menunjukkan apakah alat dapat menjangkaunya dari arah yang dipilih.", + "ui.details_angle": "Sudut", + "ui.details_continuity_caption": "Edit jahitan terpilih. Jahitan lain mempertahankan pengaturannya sendiri.", + "ui.details_continuity_stale": "Geometri sebelumnya: jalankan ulang analisis untuk mengedit jahitan ini atau mengepaskan tampilan padanya.", + "ui.details_copy_list": "Salin daftar", + "ui.details_curvature": "Toleransi kelengkungan", + "ui.details_curvature_caption": "Muka diberi warna menurut radius kelengkungan lokalnya.", + "ui.details_direction": "Arah alat", + "ui.details_draft_caption": "Muka diberi warna menurut sudutnya terhadap arah tarik.", + "ui.details_edit_seam": "Edit jahitan", + "ui.details_fixture": "Spesimen komponen — hanya data contoh", + "ui.details_fixture_caption": "Spesimen komponen dengan nilai ilustratif; ini bukan hasil model.", + "ui.details_fixture_problem": "Contoh temuan dengan masalah", + "ui.details_fixture_readout": "Contoh nilai terukur", + "ui.details_flip": "Balik", + "ui.details_gap": "Celah", + "ui.details_hatch": "Arsir muka potongan", + "ui.details_jump": "Lompatan kelengkungan", + "ui.details_key": "Legenda", + "ui.details_offset": "Offset", + "ui.details_plane": "Bidang", + "ui.details_pull": "Arah tarik", + "ui.details_radius": "Radius", + "ui.details_readout": "Pembacaan", + "ui.details_samples": "Sampel", + "ui.details_seam": "{body} · Tepi {edge}", + "ui.details_settings": "Pengaturan", + "ui.details_sharp_gap": "Tajam atau celah", + "ui.details_show_all": "Tampilkan semua {count}", + "ui.details_smooth": "Halus", + "ui.details_stripes": "Lajur", + "ui.details_target": "Pas ke geometri", + "ui.details_worst_seams": "Jahitan terburuk", + "ui.details_zebra_caption": "Lajur terpantul menunjukkan seberapa mulus muka bertemu.", "ui.diameter": "Diameter", "ui.dimension": "Dimensi", "ui.direct_interaction": "Interaksi langsung", @@ -4050,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "Part disimpan ke file lain; rakitan masih menautkan {name}", "ui.edit_in_place_wait": "Tunggu sampai proses yang berjalan di desain selesai", "ui.edit_section_analysis": "Edit Analisis Penampang", + "ui.edit_sketch_empty": "Tidak ada sketsa untuk diedit", "ui.ellipse": "Elips", "ui.emboss_wrap_note": "Profil garis ortogonal yang tangen pada satu silinder yang didukung dibungkus otomatis. Pilih dinding untuk menentukan target.", "ui.end_radius": "Radius Akhir", @@ -4060,12 +4615,15 @@ "ui.equation_explicit": "Eksplisit", "ui.equation_form": "Bentuk", "ui.equation_note": "Variabelnya berupa angka biasa: sin(t) menganggapnya dalam radian. Hasil tanpa satuan memakai satuan desain.", + "ui.equation_note_range": "Variabelnya berupa panjang, seperti rentangnya: campurkan dengan parameter panjang, dan bagi dengan sebuah panjang untuk sin(). Hasil tanpa satuan memakai satuan desain.", "ui.equation_parametric": "Parametrik", + "ui.equation_variable_unit": "Variabel memakai satuan rentang", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Radius Ekuivalen", "ui.expand": "Perluas", + "ui.explode_needs_two_components": "Tampilan Urai menarik komponen terpisah, jadi desain memerlukan dua komponen atau lebih (Komponen Baru, Sisipkan Desain, atau Buat Komponen dari Bodi)", "ui.exportDxf": "Ekspor DXF…", "ui.export_ellipsis_keymap": "Ekspor…", "ui.export_keymap_tip": "Tombol, favorit kotak S, dan toolbar, sebagai file", @@ -4191,6 +4749,7 @@ "ui.hideOrigin": "Sembunyikan Origin", "ui.hidePlanes": "Sembunyikan Bidang", "ui.hideProfile": "Sembunyikan Profil", + "ui.hide_component_history": "Sembunyikan Riwayatnya", "ui.hide_origin_by_default": "Sembunyikan origin secara default", "ui.hide_origin_note": "Desain baru dimulai dengan folder Origin tersembunyi. Desain mempertahankan pengaturan Origin-nya sendiri setelah Anda menampilkan atau menyembunyikannya.", "ui.history_back": "Mundur satu langkah", @@ -4198,6 +4757,7 @@ "ui.history_edge_hint": "klik dua kali tepinya", "ui.history_first": "Ke awal", "ui.history_forward": "Maju satu langkah", + "ui.history_hide_hidden": "Sembunyikan Komponen Tersembunyi", "ui.history_hide_names": "Sembunyikan nama", "ui.history_last": "Ke akhir", "ui.history_marker_tip": "Penanda riwayat: seret untuk memundurkan model; fitur baru ditaruh di sini", @@ -4207,10 +4767,12 @@ "ui.history_play_button_show": "Tampilkan Tombol Putar", "ui.history_play_finish_action": "Selesaikan aksi saat ini sebelum memutar Riwayat", "ui.history_play_roll_back": "Pindahkan penanda Riwayat ke belakang sebelum memutar", + "ui.history_show_hidden": "Tampilkan Komponen Tersembunyi", "ui.history_show_names": "Tampilkan nama", "ui.history_sketch_listed_under": "Terdaftar di bawah {feature}", "ui.history_title": "Riwayat", "ui.history_toggle_names": "Tampilkan atau sembunyikan nama fitur", + "ui.history_waits_for_editor": "Urungkan, Ulangi, dan Riwayat menunggu hingga editor fitur terbuka", "ui.hole": "Lubang", "ui.hole_tap_type": "Tipe Tap Lubang", "ui.hole_type": "Tipe Lubang", @@ -4226,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} memiliki perubahan yang belum disimpan, sehingga file tersimpannya yang disisipkan. Simpan desain itu, lalu jalankan Perbarui Tautan untuk memasukkan perubahannya.", "ui.insert_design.unsaved": "Perubahan belum disimpan", "ui.inspect": "Inspeksi", + "ui.instances": "Instans", "ui.intersect": "Irisan", "ui.isolate": "Isolasi", "ui.join": "Gabung", @@ -4234,12 +4797,14 @@ "ui.joints": "Sambungan", "ui.keyboard_shortcuts": "Pintasan Keyboard", "ui.language": "Bahasa", + "ui.lasso_select": "Lasso (seret lengkung tertutup bebas: memilih yang seluruhnya berada di dalam)", "ui.layout_compact": "Ringkas", "ui.layout_floating": "Mengambang", "ui.length": "Panjang", "ui.length_decimals": "Desimal panjang", "ui.light": "Terang", "ui.line": "Garis", + "ui.line_arc_hint": "Busur tangen: klik ujung busur. Diamkan lagi di titik terakhir untuk garis; klik kanan atau Esc untuk selesai", "ui.link_copies": "Tautkan Salinan Identik", "ui.link_copies_keep": "Pertahankan", "ui.link_copies_link": "Tautkan", @@ -4328,6 +4893,7 @@ "ui.part_size_shared": "Membangun ulang part, menggantikan fitur tambahan apa pun. Semua kemunculan komponen ini diperbarui.", "ui.paste": "Tempel", "ui.path": "Jalur", + "ui.pattern_object_type_tip": "Bodi: bentuk solid, dipilih di tampilan atau Penjelajah; masing-masing disalin utuh.\nFitur: langkah-langkah Riwayat, seperti ekstrusi atau lubang, dipilih di Riwayat atau pada muka yang dibuatnya; langkah itu diulang.\nSketsa bukan keduanya: ulangi kurvanya dengan Pola atau Cermin milik sketsa itu sendiri, atau ekstrusi dulu.", "ui.pattern_on_path": "Pola pada Jalur", "ui.perforate_margin_default": "dari diameter", "ui.perforate_pitch": "Pitch", @@ -4354,12 +4920,17 @@ "ui.plugins_skipped": "{count} folder tidak dapat dibaca.", "ui.plugins_version": "{version}", "ui.point": "Titik", + "ui.point_cloud_add_filter": "Tambah filter…", "ui.point_cloud_auto_range": "Rentang Otomatis", "ui.point_cloud_color_by": "Warnai Menurut", "ui.point_cloud_file_colors": "Warna File", + "ui.point_cloud_filter_by": "Filter menurut", "ui.point_cloud_height_high": "Tertinggi", "ui.point_cloud_height_low": "Terendah", + "ui.point_cloud_legend_filter": "Ditampilkan dan disembunyikan di legenda di atas", "ui.point_cloud_no_file_colors": "File tidak memiliki warna", + "ui.point_cloud_pause": "Jeda", + "ui.point_cloud_play": "Putar", "ui.point_cloud_single_color": "Satu Warna", "ui.point_cloud_size": "Ukuran Titik", "ui.point_cloud_units": "Satuan File", @@ -4368,6 +4939,11 @@ "ui.polygon": "Poligon", "ui.preferences": "Preferensi", "ui.press_a_key": "tekan tombol…", + "ui.print_face_body_not_sent": "Bodi permukaan itu tidak dikirim: tambahkan dulu ke Bodi", + "ui.print_face_cleared": "{body}: permukaan cetak dihapus", + "ui.print_face_input": "Permukaan cetak", + "ui.print_face_pick": "Pilih satu permukaan datar dari bodi padat untuk dijadikan permukaan cetak", + "ui.print_face_set": "{body}: permukaan cetak diatur; Kirim ke slicer meletakkan bodi di atasnya", "ui.profile": "Profil", "ui.profile_plane": "Bidang Profil", "ui.profiles": "Profil", @@ -4383,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Mengukur…", + "ui.properties.measuring_bodies": "Mengukur… {done} dari {total} bodi", "ui.properties.measuring_failed": "Pengukuran berhenti sebelum selesai.", "ui.properties.principal_axis": "Sumbu utama {number}", "ui.properties.principal_moments": "Momen utama", @@ -4431,6 +5008,7 @@ "ui.revolve": "Revolve", "ui.ribbon_exit": "Keluar", "ui.ribbon_labels": "Tampilkan teks di bawah ikon pita", + "ui.ribbon_menus_skip_pinned": "Kecualikan perintah yang disematkan dari dropdown", "ui.ribbon_pin_footer": "Perintah yang disematkan tampil di ribbon. Arahkan kursor ke baris untuk menyematkan atau melepas sematan.", "ui.ribbon_workspace": "Workspace", "ui.right": "Kanan", @@ -4449,6 +5027,7 @@ "ui.selectOther": "Pilih Lainnya…", "ui.selectTangentChain": "Pilih Rantai Tangen", "ui.select_all": "Pilih Semua", + "ui.select_components_by_face": "Pilih komponen (sebuah muka memilih komponennya)", "ui.selection": "Pilihan", "ui.selection_modifiers": "Pengubah pilihan", "ui.selection_shift_add_only": "Shift+klik menambah tanpa menghapus", @@ -4474,6 +5053,7 @@ "ui.showDimension": "Tampilkan Dimensi", "ui.showOrigin": "Tampilkan Origin", "ui.showPlanes": "Tampilkan Bidang", + "ui.show_component_history": "Tampilkan Riwayatnya", "ui.show_constraints": "Batasan", "ui.show_construction_geometries": "Geometri Konstruksi", "ui.show_dimensions": "Dimensi", @@ -4490,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Filter Pilihan", "ui.sketch_modifiers": "Pengubah sketsa", "ui.sketch_project_geometry": "Geometri", + "ui.sketch_report.all_constrained": "Semuanya terbatasi penuh.", + "ui.sketch_report.dof": "Derajat kebebasan", + "ui.sketch_report.loose": "Belum terbatasi penuh", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Laporan Sketsa", "ui.sketch_scale": "Skala Sketsa", "ui.sketches": "Sketsa", "ui.slice": "Iris", @@ -4585,19 +5170,31 @@ "ui.view_angles": "Sudut tampilan", "ui.view_angles_convention": "Derajat terhadap sumbu atas. Yaw 0° adalah tampilan Depan, 90° Kiri, −90° Kanan, 180° Belakang; pitch 90° adalah tampilan Atas; roll positif memutar model searah jarum jam.", "ui.view_angles_help": "Menampilkan pitch, yaw, dan roll tampilan dalam derajat serta proyeksinya di bawah gizmo orientasi. Klik pembacaan untuk mengetik sudut yang tepat.", + "ui.view_angles_lock": "Kunci {axis}", "ui.view_angles_ortho": "Ortho", "ui.view_angles_persp": "Persp", "ui.view_angles_pitch": "Pitch", "ui.view_angles_readout": "Pitch {pitch} · Yaw {yaw} · Roll {roll}", "ui.view_angles_roll": "Roll", + "ui.view_angles_unlock": "Buka kunci {axis}", "ui.view_angles_yaw": "Yaw", + "ui.view_angles_zero": "Atur {axis} ke 0°", "ui.view_centre": "Pusat tampilan", "ui.viewport_status_clear": "Matikan {name}", "ui.viewport_status_clear_hint": "Matikan {name} · Esc", + "ui.viewport_status_edges": "{count} tepi", + "ui.viewport_status_from": "dari {direction}", "ui.viewport_status_key": "Tampilkan legenda untuk {name}", "ui.viewport_status_minimum_radius": "Radius minimum", "ui.viewport_status_pairs": "{count} pasang", + "ui.viewport_status_section_hatch": "{setting} · arsir", + "ui.viewport_status_section_plane": "Bidang saat ini", + "ui.viewport_status_section_tilted": "miring · {offset}", "ui.viewport_status_stripes": "{count} lajur", + "ui.viewport_status_summary_clear": "Matikan semuanya", + "ui.viewport_status_summary_heading": "Di tampilan ini", + "ui.viewport_status_summary_label": "{name} dan {count} item lainnya", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Ikuti tema", "ui.visual_shaded_hidden_edges": "Shaded dengan tepi tersembunyi", "ui.visual_shaded_with_edges": "Shaded dengan tepi", @@ -4634,10 +5231,12 @@ "update.button": "Perbarui", "update.button_version": "Perbarui ke {version}", "update.check_automatically": "Periksa pembaruan secara otomatis", + "update.check_for_updates": "Periksa pembaruan", "update.check_now": "Periksa sekarang", + "update.check_unavailable": "Pemeriksaan pembaruan tidak tersedia untuk instalasi ini.", "update.checking": "Memeriksa…", "update.copy": "Salin", - "update.dmg_opened": "Disk image terbuka dan terverifikasi: seret SolidCraft ke Applications, ganti salinan lama, lalu mulai ulang SolidCraft.", + "update.dmg_opened": "Disk image terbuka dan terverifikasi: keluar dari SolidCraft, seret SolidCraft yang baru ke Applications, ganti salinan lama, lalu buka SolidCraft lagi.", "update.download": "Unduh", "update.download_open": "Unduh dan buka", "update.downloading": "Mengunduh dan memverifikasi… {done} dari {total} MB", @@ -4648,11 +5247,13 @@ "update.installed": "SolidCraft {version} terpasang. Mulai ulang untuk memakainya.", "update.installer_started": "Penginstal dimulai saat SolidCraft ditutup.", "update.later": "Ingatkan saya nanti", + "update.managed": "Pembaruan tersedia: perbarui SolidCraft di {manager}", "update.no_notes": "Rilis ini tidak memiliki catatan.", "update.package_hint": "Salinan ini berasal dari {kind}. Unduh paket baru, lalu pasang dengan:", "update.prefs_dev": "Ini adalah build pengembangan ({version}): tidak memeriksa pembaruan.", "update.prefs_flatpak": "Flatpak memperbarui salinan ini ({version}): jalankan {command} atau gunakan software center Anda. SolidCraft tidak memeriksa.", "update.prefs_label": "Pembaruan", + "update.prefs_managed": "Ini adalah SolidCraft {version}, dikelola oleh {manager}. Pemeriksaan meminta rilis terbaru ke GitHub dan tidak mengirim apa pun lagi; perbarui SolidCraft di {manager}.", "update.prefs_note": "Ini adalah SolidCraft {version} ({kind}). Pemeriksaan meminta rilis terbaru ke GitHub dan tidak mengirim apa pun lagi.", "update.prefs_web": "Muat ulang halaman untuk mendapatkan aplikasi web terbaru. Jika jaringan tidak tersedia atau pembaruan tidak selesai diunduh tepat waktu, versi tersimpan akan terbuka; unduhan yang sedang berjalan berlanjut untuk muat ulang berikutnya.", "update.refresh_checking": "Memeriksa rilis terbaru…", @@ -4679,6 +5280,7 @@ "web.open_link": "Buka desain tertaut?", "web.open_link_confirm": "Ada perubahan yang belum disimpan. Buka desain tertaut di tab baru?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ pilih · Enter / Tab lengkapi · Esc tutup", + "↑ ↓ choose · Enter applies this value": "↑ ↓ pilih · Enter menerapkan nilai ini", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ pilih · Enter menerapkan yang Anda ketik · Esc tutup", "⌘Enter continues on GitHub.": "⌘Enter melanjutkan di GitHub." } diff --git a/assets/locales/it.json b/assets/locales/it.json index bb35baf6a..244a73c08 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "SUPERFICIE DI RACCORDO", "BOUNDARY SURFACE": "SUPERFICIE DA CONTORNI", "BROWSER": "STRUTTURA", + "Back to the original order": "Torna all'ordine originale", "Ball": "Sferico", "Bar": "Barra", "Base Center": "Centro della base", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "I progetti aperti o salvati vengono visualizzati qui.", "Determined by To Object. Choose Angle to edit the angular extent.": "Determinato da Fino all'oggetto. Scegli Angolo per modificare l'estensione angolare.", "Diameter": "Diametro", + "Did this assembly open the wrong way up?": "Questo assieme si è aperto nel verso sbagliato?", + "Did this part open the wrong way up?": "Questa parte si è aperta nel verso sbagliato?", "Dimension new shapes": "Quota le nuove forme", "Direction": "Direzione", "Discard": "Scarta", @@ -474,6 +477,7 @@ "Rectangular": "Rettangolare", "Rectangular Tube": "Tubo rettangolare", "Reference face": "Faccia di riferimento", + "Reference plane": "Piano di riferimento", "Relief Depth": "Profondità di scarico", "Relief Width": "Larghezza di scarico", "Remove Tools": "Rimuovi corpi utensile", @@ -553,6 +557,7 @@ "Section": "Sezione", "Section (optional)": "Sezione (facoltativa)", "Section position": "Posizione della sezione", + "Sections": "Sezioni", "Sections (one sketch each)": "Sezioni (uno schizzo ciascuna)", "Select Other": "Seleziona altro", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Seleziona altro: tieni premuto il pulsante sinistro senza muovere il puntatore sul modello (o fai clic destro › Seleziona altro…) per elencare gli oggetti sotto il cursore; fai di nuovo clic nello stesso punto per selezionare l'oggetto successivo. Fai doppio clic con il pulsante centrale per tornare alla vista iniziale (Preferenze › Navigazione).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Aggancia ai centri di facce e spigoli", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft non può inviare direttamente le segnalazioni. Inviale su GitHub; nell'app non serve alcun token.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft si è chiuso prima del salvataggio di questi progetti. È possibile aprire il loro ultimo salvataggio automatico.", + "Sort A to Z": "Ordina dalla A alla Z", + "Sort Z to A": "Ordina dalla Z alla A", "Spacing 2 must be a non-zero number": "La spaziatura 2 deve essere un numero diverso da zero", "Spacing must be a non-zero number": "La spaziatura deve essere un numero diverso da zero", "Specialise": "Specializza", @@ -601,6 +608,7 @@ "Square": "Quadrato", "Stand it up": "Raddrizza", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Raddrizza: un quarto di giro attorno a X, come singola lavorazione Sposta annullabile.", + "Stand this assembly up?": "Raddrizzare questo assieme?", "Stand this part up?": "Raddrizzare questa parte?", "Start angle": "Angolo iniziale", "Start bulge": "Rigonfiamento iniziale", @@ -772,6 +780,8 @@ "at the face": "sulla faccia", "bom.group_children": "Sottoparti nella riga della loro parte", "browser.body_name": "Corpo{number}", + "browser.calibrate_click_a": "Fai clic sull'immagine per il punto A, oppure digitane le coordinate.", + "browser.calibrate_click_b": "Fai clic sull'immagine per il punto B, oppure digitane le coordinate.", "browser.calibrate_title": "Calibra: {name}", "browser.capture_many": "Sono stati spostati {count} componenti, ma le loro posizioni non sono state acquisite.", "browser.capture_note": "Acquisisci posizione mantiene la nuova posizione; Ripristina posizione riporta a quella precedente.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (aggancio perso)", "browser.sketch_editing": "{name} (in modifica)", "browser.sketch_name": "Schizzo{number}", + "browser.sketches_to_parts_already_in_part": "già nella loro parte", + "browser.sketches_to_parts_design_body": "su un corpo del progetto stesso", + "browser.sketches_to_parts_moved": "Spostati {moved} schizzi nella parte su cui si trovano", + "browser.sketches_to_parts_no_exact_attachment": "su una faccia senza un collegamento esatto", + "browser.sketches_to_parts_not_on_face": "non sulla faccia di una parte", + "browser.sketches_to_parts_part_missing": "la loro parte non esiste più", + "browser.sketches_to_parts_result": "Spostati {moved} schizzi nella parte su cui si trovano; {stayed} sono rimasti dove erano: {why}", "browser.units": "Unità: {units}", "cam.flat": "Faccia piana", "cam.follower": "Cedente", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Preleva aspetto", "cmd.appearance_replace": "Sostituisci aspetto", "cmd.assembly_bom": "Distinta base", + "cmd.assembly_mass_properties": "Proprietà di massa", + "cmd.body.print_face": "Faccia di stampa", "cmd.body_rename": "Rinomina corpo", "cmd.browser_collapse_all": "Comprimi tutto", "cmd.browser_expand_all": "Espandi tutto", @@ -842,6 +861,7 @@ "cmd.component_extract": "Estrai in file", "cmd.component_finish_edit": "Termina modifica", "cmd.component_from_bodies": "Crea componenti da corpi", + "cmd.component_hide_history": "Nascondi cronologia del componente", "cmd.component_insert_design": "Inserisci progetto", "cmd.component_links": "Elenca collegamenti", "cmd.component_list": "Elenca componenti", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Sposta corpi nel componente", "cmd.component_move_features": "Sposta lavorazioni nel componente", "cmd.component_move_sketches": "Sposta schizzi nel componente", + "cmd.component_move_sketches_to_parts": "Sposta schizzi nelle rispettive parti", "cmd.component_paste_from_design": "Incolla da un altro progetto", "cmd.component_paste_new": "Incolla come nuovo", "cmd.component_properties": "Proprietà fisiche del componente", @@ -857,6 +878,7 @@ "cmd.component_rename": "Rinomina componente", "cmd.component_replace_with_link": "Sostituisci con collegamento", "cmd.component_revert_position": "Ripristina posizione", + "cmd.component_show_history": "Mostra cronologia del componente", "cmd.component_unlock": "Sblocca contenuto", "cmd.component_update_links": "Aggiorna collegamenti", "cmd.config_activate": "Attiva configurazione", @@ -867,6 +889,7 @@ "cmd.config_rule": "Regola di configurazione", "cmd.config_rules": "Regole di configurazione", "cmd.config_table": "Mostra tabella delle configurazioni", + "cmd.construct.plane.axis_point": "Piano per un asse e un punto", "cmd.construct_axis_edge": "Asse lungo uno spigolo", "cmd.construct_axis_normal_to_face": "Asse perpendicolare a una faccia", "cmd.construct_axis_through_cylinder": "Asse di cilindro/cono/toro", @@ -915,6 +938,11 @@ "cmd.explode_show": "Mostra vista esplosa", "cmd.expr_evaluate": "Valuta espressione", "cmd.face_delete": "Elimina faccia", + "cmd.file.export_3mf": "Esporta 3MF", + "cmd.file.export_obj": "Esporta OBJ", + "cmd.file.export_step": "Esporta STEP", + "cmd.file.export_stl": "Esporta STL", + "cmd.file.export_urdf": "Esporta URDF", "cmd.file_export": "Esporta", "cmd.file_insert_mesh": "Inserisci mesh", "cmd.file_insert_step": "Inserisci STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Attiva colori dei componenti", "cmd.inspect_colored_components_disable": "Disattiva colori dei componenti", "cmd.inspect_compare": "Confronta corpi", + "cmd.inspect_compare_picture": "Confronta immagine", "cmd.inspect_continuity": "Analisi di continuità", "cmd.inspect_curvature_comb": "Analisi del pettine di curvatura", "cmd.inspect_curvature_map": "Analisi della mappa di curvatura", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Modifica nuvola di punti", "cmd.pointcloud_insert": "Inserisci nuvola di punti", "cmd.pointcloud_list": "Nuvole di punti", + "cmd.render.compare.divider": "Sposta divisore del confronto di rendering", + "cmd.render.result.discard": "Scarta risultato di rendering", + "cmd.render.result.select": "Seleziona risultato di rendering", "cmd.render_aging_describe": "Invecchiamento a strati delle superfici", "cmd.render_backends": "Motori di rendering", "cmd.render_batch": "Renderizza tutte le inquadrature", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline per punti di controllo (grado 5)", "cmd.sketch_spline_fit_point": "Spline interpolante", "cmd.sketch_spline_insert_point": "Aggiungi punto alla spline", + "cmd.sketch_spline_remove_point": "Rimuovi punto dalla spline", "cmd.sketch_spline_reverse": "Inverti direzione della spline", "cmd.sketch_spun_profile": "Profilo di tornitura", "cmd.sketch_toggle_diameter": "Alterna raggio / diametro", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Sposta marcatore della sequenza temporale", "cmd.timeline_stop": "Arresta riproduzione cronologia", "cmd.timeline_suppress": "Sospendi lavorazione", + "cmd.ui.assistant": "Mostra/Nascondi assistente", "cmd.view.render_browser": "Struttura del rendering", "cmd.view.render_dock": "Sposta pannello di rendering", "cmd.view.render_focus": "Vista focalizzata sul rendering", + "cmd.view.status_details": "Dettagli di stato della vista", "cmd.view.status_items": "Elementi di stato della vista", "cmd.view_ambient_occlusion": "Occlusione ambientale", "cmd.view_angle_readout": "Angoli della vista", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Strumento di navigazione", "cmd.view_top": "Vista dall'alto", "cmd.view_visual_style": "Stile di visualizzazione", + "color.blue": "Blu", "color.copy": "Fai clic per copiare i valori del colore", "color.edit": "Fai clic per modificare il colore", "color.gamma": "Valori del colore mostrati nello spazio gamma 0-255", + "color.green": "Verde", "color.hex": "Hex", "color.hex_help": "Inserisci #rrggbb o #rrggbbaa; con sei cifre l'opacità resta invariata", "color.hex_hint": "#rrggbb", "color.hue": "Tonalità", "color.linear": "Valori del colore mostrati nello spazio lineare 0-1", + "color.recent": "Colori recenti", + "color.recent_help": "I colori scelti in qualsiasi campo colore compaiono qui", + "color.red": "Rosso", + "color.saturation": "Saturazione (percentuale)", "color.saturation_value": "Saturazione e valore", "color.selected": "Colore selezionato", + "color.step_down": "Diminuisci di un passo", + "color.step_up": "Aumenta di un passo", + "color.value": "Valore, la luminosità (percentuale)", "config.column_filter_empty": "Nessuna colonna corrispondente", + "config.rule_parameter_columns": "Sono elencati solo i parametri che hanno una colonna nella tabella. Aggiungine una con Aggiungi colonna (+) per usarla qui.", + "config.rule_suppression_columns": "Sono elencate solo le lavorazioni che hanno una colonna Sospendi nella tabella. Aggiungine una con Aggiungi colonna (+) per comandarle da qui.", "contact.components_count": "{count} componenti", "contact.enabled_label": "abilitato", "coupling.gear_1": "Ruota dentata 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Fai doppio clic su un’altra quota di controllo per inserirne il nome", "dialog.dimension_name": "Quota: {name}", "dialog.edit_title": "MODIFICA {title}", + "dialog.no_shown_body": "Nessun corpo visibile da modificare: mostrane uno o scegli Nuovo corpo", + "dialog.pattern_sketch_not_object": "Seleziona corpi o lavorazioni: uno schizzo non è nessuno dei due. Ripeti le sue curve con Ripetizione o Specchia dello schizzo stesso, oppure estrudilo prima.", "dialog.select": "↖ Seleziona", "dialog.selected_count": "↖ Selezionati: {count}", + "dialog.selection_constraint": "Vincolo {id}", + "dialog.selection_external_curve": "{sketch} · curva {id}", "dialog.selection_guidance": "Seleziona un dato di ingresso per modificarlo. Fai clic sugli oggetti selezionati per rimuoverli; anche Ctrl/Cmd-clic ne alterna la selezione. Controlla l'anteprima, poi premi OK.", + "dialog.selection_midpoint": "Punto medio · {id}", + "dialog.selection_profile": "{sketch} · profilo {number}", "dialog.selection_step": "{step} di {total}: seleziona {input}", "dialog.step": "Passo", "document.changed_on_disk": "{name} è stato modificato sul disco", @@ -1340,6 +1392,7 @@ "document.read_only_save": "Questa progettazione è stata aperta in sola lettura: salvala come nuovo file", "document.save_changes": "Salvare le modifiche a {name}?", "document.save_copy": "Salva una copia…", + "document.tab_unsaved_changes": "Modifiche non salvate", "document.unsaved_changes": "{name} contiene modifiche non salvate. Se non salvi, andranno perse.", "drive.rigid": "{joint} è un giunto rigido: tiene ferme le sue parti, quindi non c'è nulla da azionare. Per farle muovere, cambia il suo tipo in Modifica giunto: Rotante per ruotare, Scorrevole per scorrere, Cilindrico per entrambi.", "drive.stopped_by_contact": "Arrestato a {value}: {a} attraverserebbe {b}", @@ -1380,26 +1433,244 @@ "from the rule": "dalla regola", "help.apache": "Licenza Apache 2.0", "help.appearance.assign": "Dà ai corpi, alle facce o ai componenti selezionati un colore o un aspetto di materiale, senza cambiarne il peso. Usalo per distinguere le parti o per vedere in anteprima una finitura.", + "help.assembly.bom": "Elenca le parti del progetto o di un componente con le relative quantità, per numero di parte, e può salvare l'elenco come CSV o JSON. Usalo come distinta delle parti per ordini e montaggio.", "help.attributions": "Attribuzioni (ATTRIBUTION.md)", "help.build": "Versione {version} · commit {commit} · compilata il {date}", + "help.canvas.decal": "Applica un'immagine su una faccia piana del modello, come un adesivo. Usalo per mostrare un'etichetta, un logo o un motivo stampato su un pezzo.", + "help.canvas.edit": "Modifica un'immagine di riferimento: posizione, dimensione, angolo, opacità, specchiatura, visibilità o nome. Usalo per allineare l'immagine allo schizzo che ci ricalchi sopra.", + "help.canvas.insert": "Colloca un'immagine PNG o JPEG su un piano o una faccia come riferimento semitrasparente. Usalo per ricalcare una foto o un disegno in uno schizzo, con l'immagine scalata a una dimensione nota.", + "help.component.break_link": "Interrompe il collegamento di un componente con il suo file di progetto, mantenendone i corpi così come sono. Usalo quando la parte non deve più seguire le modifiche del file originale.", + "help.component.capture_position": "Acquisisce le posizioni delle parti spostate a mano, che diventano la loro nuova posizione. Usalo dopo aver trascinato in posizione parti che nessun giunto trattiene.", + "help.component.create": "Aggiunge al progetto un nuovo componente vuoto, dentro il componente attivo a meno che tu non scelga un altro padre. Usalo per dare a una nuova parte di un assieme il proprio spazio per corpi e schizzi.", "help.component.finish_edit": "Salva la parte che stai modificando sul posto, torna al suo assieme e lo aggiorna con le modifiche. Usalo quando hai finito di modificare la parte collegata.", + "help.component.from_bodies": "Trasforma ogni corpo selezionato in un componente a sé, con il nome del corpo. Usalo quando un progetto costruito con corpi sciolti deve diventare un assieme le cui parti possono essere collegate con giunti e spostate.", + "help.component.insert_design": "Inserisce un altro progetto salvato come componente collegato al suo file, con i suoi corpi solidi posizionati come nel file originale. Usalo per riutilizzare una parte in un assieme e recepire le modifiche successive con Aggiorna collegamenti.", + "help.component.properties": "Mostra volume, massa, centro di massa e momenti d'inerzia di un componente, in base ai materiali dei suoi corpi. Usalo per controllare peso e bilanciamento di un assieme.", + "help.component.revert_position": "Riporta dove erano le parti spostate a mano, scartando gli spostamenti non acquisiti. Usalo per annullare gli spostamenti di prova in un assieme.", + "help.component.update_links": "Rilegge i file di progetto collegati e sostituisce i corpi che sono cambiati. Usalo dopo aver modificato una parte usata da questo assieme.", + "help.config.configure": "Aggiunge parametri, lavorazioni, materiali o aspetti come colonne della tabella delle configurazioni. Usalo per creare varianti di uno stesso progetto, ad esempio le misure di un pezzo.", + "help.config.preview": "Verifica che una riga della tabella delle configurazioni si ricostruisca, senza modificare il progetto né la sua cronologia. Usalo prima di passare a una variante di cui non sei sicuro.", + "help.config.rules": "Mostra le regole della tabella delle configurazioni, le sue righe e quale riga è attiva. Usalo per vedere come sono impostate le varianti di un progetto.", + "help.config.table": "Mostra la tabella delle configurazioni: una riga per variante, una colonna per parametro o lavorazione, e se il progetto corrisponde ancora alla riga attiva. Usalo per esaminare le varianti di un progetto.", "help.connect_note": "Riavvia ogni assistente per caricare il server SolidCraft. Ogni file è stato salvato come .bak prima della modifica.", "help.connect_title": "Collega assistenti AI", + "help.construct.axis.edge": "Crea un asse di costruzione lungo uno spigolo rettilineo o una linea dello schizzo. Usalo come asse per una rivoluzione, una serie circolare o un giunto.", + "help.construct.axis.normal_to_face": "Crea un asse di costruzione passante per un punto, perpendicolare a una faccia. Usalo come asse che esce dritto da una superficie.", + "help.construct.axis.through_cylinder": "Crea un asse di costruzione passante per il centro di una faccia cilindrica, conica o torica, o di uno spigolo circolare. Usalo per ruotare lavorazioni o ripeterle in serie attorno a un pezzo tondo.", + "help.construct.axis.two_planes": "Crea un asse di costruzione dove si incontrano due piani o facce piane. Usalo quando l'asse che ti serve è la linea tra due facce.", + "help.construct.axis.two_points": "Crea un asse di costruzione passante per due punti, vertici o punti dello schizzo. Usalo per un asse che collega due posizioni note.", + "help.construct.plane.along_path": "Crea un piano di costruzione perpendicolare a uno spigolo o a una curva, in una posizione lungo di essa. Usalo per disegnare il profilo di uno sweep o una sezione di un percorso.", + "help.construct.plane.at_angle": "Crea un piano di costruzione ruotato di un angolo rispetto a un piano o a una faccia, attorno a un asse o a uno spigolo. Usalo per schizzi inclinati, ad esempio una staffa angolata.", + "help.construct.plane.axis_point": "Crea un piano di costruzione che contiene un asse e un punto esterno all'asse. Seleziona un'origine o un asse di costruzione, uno spigolo rettilineo o una linea dello schizzo, poi un vertice, un punto dello schizzo o un punto di costruzione. Un punto sull'asse non può definire un piano univoco.", + "help.construct.plane.midplane": "Crea un piano di costruzione a metà tra due piani o facce piane, oppure che li biseca dove si incontrano ad angolo. Usalo come piano di simmetria per specchiare.", + "help.construct.plane.offset": "Crea un piano di costruzione parallelo a un piano o a una faccia piana, a una certa distanza o passante per un punto. Usalo per disegnare a un'altezza stabilita sopra una faccia.", + "help.construct.plane.perpendicular": "Crea un piano di costruzione che contiene una linea o uno spigolo ed è perpendicolare a un piano o a una faccia. Usalo per disegnare in verticale sul modello lungo uno spigolo.", + "help.construct.plane.tangent": "Crea un piano di costruzione tangente a un cilindro, un cono, una sfera o un toro in un punto. Usalo per disegnare sul lato di un pezzo tondo.", + "help.construct.plane.three_points": "Crea un piano di costruzione passante per tre punti. Usalo per un piano definito da posizioni sul modello, ad esempio tre angoli.", + "help.construct.plane.two_edges": "Crea un piano di costruzione passante per due spigoli rettilinei o linee che giacciono sullo stesso piano. Usalo per un piano che attraversa un pezzo, ad esempio per due spigoli opposti.", + "help.construct.point.along_path": "Crea un punto di costruzione in una posizione lungo uno spigolo o una curva. Usalo come riferimento in un punto intermedio di un percorso.", + "help.construct.point.center": "Crea un punto di costruzione al centro di uno spigolo circolare, di un cerchio o arco dello schizzo, di una sfera o di un toro. Usalo come riferimento per fori, assi e giunti.", + "help.construct.point.edge_plane": "Crea un punto di costruzione dove uno spigolo o una linea attraversa un piano o una faccia piana. Usalo per segnare dove un percorso incrocia un piano.", + "help.construct.point.three_planes": "Crea un punto di costruzione dove si incontrano tre piani o facce piane. Usalo come riferimento d'angolo, anche dove il modello non ha un vertice.", + "help.construct.point.two_edges": "Crea un punto di costruzione dove due spigoli o linee si incontrano, o si avvicinano di più. Usalo come riferimento in un angolo virtuale.", + "help.construct.point.vertex": "Crea un punto di costruzione su un vertice o su un punto dello schizzo. Usalo come riferimento che resta anche quando lo schizzo o il corpo intorno è nascosto.", + "help.contact.check": "Elenca le coppie di parti nei gruppi di contatto che si compenetrano nella posizione attuale. Usalo per trovare le collisioni prima di azionare i giunti o avviare uno studio del movimento.", + "help.contact.create": "Raggruppa due o più parti in un gruppo di contatto, i cui corpi non possono compenetrarsi mentre i giunti si muovono. Usalo per parti che devono fermarsi quando si toccano, come una leva contro il suo fermo.", + "help.contact.disable_all": "Disattiva il contatto, così i giunti azionati e gli studi del movimento non si fermano più dove le parti si toccano. Usalo per muovere di nuovo le parti liberamente, o per mantenere reattivo un assieme grande.", + "help.contact.edit": "Modifica un gruppo di contatto: le parti che contiene, il nome o se è sospeso; può anche eliminare il gruppo. Usalo per regolare quali parti non possono compenetrarsi.", + "help.contact.enable_all": "Mette ogni parte dell'assieme in un unico gruppo di contatto, così nessuna coppia di parti può compenetrarsi mentre i giunti si muovono. Usalo per un controllo rapido di un intero meccanismo.", + "help.contact.enable_sets": "Attiva il contatto per i gruppi di contatto che hai definito, così i giunti azionati e gli studi del movimento si fermano dove le loro parti si compenetrerebbero. Usalo per riattivare i tuoi gruppi dopo aver disattivato il contatto.", + "help.contact.list": "Elenca i gruppi di contatto del progetto, le parti di ciascuno e se il contatto è attivo. Usalo per controllare come è impostato il contatto prima di azionare l'assieme.", + "help.document.inspect": "Mostra una panoramica del progetto: componenti, corpi, schizzi, lavorazioni e parametri. Usalo per orientarti in un progetto che non hai realizzato tu.", + "help.document.units": "Cambia le unità in cui il progetto mostra le lunghezze, come mm o pollici. La geometria mantiene le sue dimensioni; si adattano solo la visualizzazione e i numeri semplici.", + "help.edit.checkpoint": "Memorizza il progetto, lo schizzo attivo e la cronologia di annullamento così come sono ora. Usalo prima di tentare qualcosa di rischioso da cui potresti voler tornare indietro.", + "help.edit.restore_checkpoint": "Torna a un punto di ripristino, compresa la cronologia di annullamento. Usalo per scartare in un solo passo tutto ciò che è stato fatto dopo il punto di ripristino.", + "help.explode.create": "Crea una vista esplosa che allontana le parti dal centro dell'assieme, oppure con gli spostamenti che imposti. Usalo per mostrare come si monta un assieme, per istruzioni o presentazioni.", "help.face.delete": "Rimuove le facce selezionate e lascia che le facce vicine chiudano il vuoto, oppure lascia il vuoto aperto come superficie. Usalo per togliere uno spigolo arrotondato, un foro o una sporgenza che è d'intralcio.", + "help.file.insert_mesh": "Aggiunge al progetto un file 3MF, STL, OBJ, PLY o glTF come corpi a mesh in un nuovo componente. Usalo per affiancare al progetto, come riferimento, un modello scaricato o scansionato.", + "help.file.insert_step": "Aggiunge al progetto un file STEP, IGES, FreeCAD o Rhino come corpi solidi in un nuovo componente; le parti di un assieme diventano componenti annidati. Usalo per importare modelli di fornitori o di altri programmi CAD.", + "help.file.save_mesh": "Salva i corpi come mesh STL, 3MF o OBJ, con la finezza che scegli per le facce curve. Usalo per preparare pezzi per la stampa 3D o per programmi che leggono mesh.", + "help.file.send_to_slicer": "Salva i corpi selezionati come file 3MF e lo apre nello slicer che scegli. Usalo per passare dal modello alla stampa in un solo passo.", "help.font_details": "L’interfaccia usa i caratteri integrati di egui (Ubuntu Light e Hack, con licenze Ubuntu Font Licence e MIT/Bitstream Vera; Noto Emoji e il carattere per icone emoji, con licenze OFL e MIT). Il testo degli schizzi usa Liberation Sans (SIL OFL 1.1). Il pacchetto di caratteri facoltativo di The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), non è incluso nelle build di SolidCraft.", "help.fonts": "Caratteri", + "help.frame.member": "Posiziona un profilo, come un tubo o un profilato di alluminio, lungo le linee di uno schizzo del telaio, un membro per linea. Usalo per costruire telai, scaffalature e strutture saldate.", + "help.inspect.accessibility": "Colora le facce che un utensile può raggiungere da una direzione e quelle che non può raggiungere. Usalo per verificare un pezzo per la lavorazione meccanica o lo stampaggio da quel lato.", + "help.inspect.center_of_mass": "Mostra il centro di massa dei corpi, ciascuno da solo e tutti insieme, a densità uniforme. Usalo per controllare il bilanciamento e dove un pezzo si ribalterà.", + "help.inspect.colored_components": "Dà a ogni componente un proprio colore temporaneo, senza modificare gli aspetti. Usalo per distinguere a colpo d'occhio le parti di un assieme.", + "help.inspect.compare": "Confronta due corpi e mostra dove uno ha materiale che l'altro non ha, con volume e scostamento. Usalo per verificare un pezzo modificato o importato rispetto all'originale.", + "help.inspect.continuity": "Verifica come si raccordano le facce lungo i loro spigoli: giochi, spigoli vivi o salti di curvatura, e colora le giunzioni. Usalo per trovare dove le superfici non si raccordano bene.", + "help.inspect.curvature_comb": "Disegna pettini lungo curve, spigoli o facce i cui denti mostrano quanto si curvano. Usalo per individuare zone piatte, spigoli vivi e curvatura irregolare.", + "help.inspect.curvature_map": "Colora le facce in base a quanto si curvano, in rosso dove il raggio è piccolo. Usalo per trovare i punti stretti e valutare quanto è liscia una superficie.", + "help.inspect.draft": "Colora le facce in base all'angolo di sformo rispetto a una direzione di estrazione, segnalando quelle con sformo insufficiente. Usalo per controllare un pezzo prima dello stampaggio o della fusione.", + "help.inspect.environment_map": "Mostra il modello con una finitura riflettente, simile a uno specchio. Usalo per valutare l'andamento delle superfici dal modo in cui scorrono i riflessi.", + "help.inspect.interference": "Trova i corpi che si sovrappongono e mostra ogni sovrapposizione con il suo volume. Usalo per controllare se in un assieme ci sono parti che si scontrano.", + "help.inspect.isocurve": "Disegna le curve isoparametriche delle facce, la griglia su cui è costruita la superficie. Usalo per vedere come scorre una superficie e dove si addensa.", + "help.inspect.measure": "Misura lunghezze, distanze, angoli, aree e raggi tra gli elementi che selezioni, oppure il volume e la massa dei corpi. Usalo per controllare dimensioni e distanze libere.", + "help.inspect.minimum_radius": "Trova il raggio di curvatura minimo di curve, spigoli o facce e dove si trova. Usalo per verificare che un utensile o un ugello possa seguire la forma.", + "help.inspect.section": "Apre la vista con un taglio lungo un piano e tratteggia le facce tagliate, senza modificare il modello. Usalo per guardare dentro pezzi e assiemi.", + "help.inspect.zebra": "Mostra strisce bianche e nere riflesse sulle facce del modello. Usalo per valutare la levigatezza: strisce che si spezzano o si piegano su uno spigolo indicano una transizione scadente.", + "help.joint.as_built": "Collega due parti dove si trovano già, senza spostarne nessuna, e imposta come possono ancora muoversi. Usalo per parti che hai già posizionato nella loro posizione finale.", + "help.joint.cam": "Collega una camma rotante a un seguicamma, che scorre o oscilla mentre il profilo della camma gli passa sotto. Usalo per camme, eccentrici e comandi delle valvole.", + "help.joint.create": "Collega due parti alle origini del giunto che selezioni e sposta la seconda parte al suo posto; il tipo di giunto stabilisce come possono ancora muoversi. Usalo per costruire un assieme le cui parti si muovono come il meccanismo reale.", + "help.joint.drive": "Imposta l'angolo o la distanza di un giunto e sposta di conseguenza le parti, entro i suoi limiti; i giunti collegati e le catene cinematiche chiuse seguono il movimento. Usalo per verificare che un meccanismo si muova come previsto.", + "help.joint.gear": "Collega due giunti rotanti con un rapporto di trasmissione, così azionarne uno fa ruotare l'altro. Usalo per ingranaggi cilindrici e dentature interne, con il rapporto ricavato dai raggi primitivi o dal numero di denti.", + "help.joint.limits": "Imposta fin dove un giunto può ruotare o scorrere, con un minimo e un massimo, oppure rimuove questi limiti. Usalo per mantenere una cerniera, un cursore o una leva entro la sua reale corsa.", + "help.joint.motion_link": "Accoppia due giunti con un rapporto e uno scostamento, così azionarne uno muove l'altro. Usalo per una relazione fissa tra giunti che Ingranaggio, Pignone e cremagliera o Vite non coprono.", + "help.joint.origin": "Colloca un'origine del giunto con nome su una parte: al centro di una faccia o di un'estremità tonda, a metà di uno spigolo, su un angolo o su un punto. Usalo per preparare i punti in cui si attaccano i giunti; un'origine scelta su una faccia segue la faccia quando la parte cambia dimensione.", + "help.joint.rack_pinion": "Collega un pignone rotante a una cremagliera scorrevole, così la cremagliera si sposta della lunghezza di circonferenza primitiva percorsa dal pignone. Usalo per trasmissioni a cremagliera, sterzi e slitte lineari.", + "help.joint.reach": "Sposta un punto di una parte verso una destinazione modificando i giunti della sua catena, entro i loro limiti. Usalo per posizionare un meccanismo in base a dove deve arrivare la sua estremità, come la punta di un braccio robotico.", + "help.joint.rigid_group": "Blocca insieme le parti selezionate così come sono, in modo che si muovano come un tutt'uno. Usalo per parti che stanno insieme e non hanno moto relativo.", + "help.joint.screw": "Collega rotazione e scorrimento tramite un passo, così ogni giro avanza di quella distanza. Usalo per viti madri, bulloni e alberi filettati.", + "help.library.apply": "Applica un materiale o un aspetto da un file di libreria locale a corpi, facce o componenti. Usalo per riutilizzare materiali salvati da un altro progetto.", + "help.library.export": "Salva i materiali e gli aspetti del progetto in un file di libreria. Usalo per condividerli o riutilizzarli in altri progetti.", + "help.library.inspect": "Controlla un file di libreria ed elenca i suoi materiali e aspetti, senza modificare il progetto. Usalo per vedere cosa contiene una libreria prima di applicarla.", "help.licences": "Licenze", "help.material.assign": "Imposta di che cosa sono fatti i corpi selezionati, per esempio acciaio, alluminio o ABS. Usalo perché massa e peso corrispondano al pezzo reale.", + "help.material.properties.validate": "Controlla la coerenza dei numeri e i valori mancanti in una scheda dati di un materiale. Usalo prima di affidarti ai dati per massa o rigidità.", + "help.mesh.convert": "Ricostruisce un corpo a mesh, come un STL, come solido modificabile con facce piane e cilindriche. Usalo per modificare parti meccaniche importate come un corpo modellato.", "help.mit": "Licenza MIT", + "help.motion.study": "Imposta i valori dei giunti a intervalli lungo una sequenza temporale e li riproduce come animazione. Usalo per osservare un meccanismo muoversi in una sequenza e controllare le distanze libere lungo il percorso.", + "help.motion.trace": "Traccia il percorso seguito da un punto di una parte mentre uno studio del movimento viene riprodotto o un giunto viene azionato, e lo conserva come curva di schizzo 3D quando confermi. Usalo per vedere dove arriva un meccanismo, o per costruire a partire dal suo percorso.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fissa una parte al suo posto, o la libera di nuovo, in modo che i giunti muovano le altre parti attorno a essa. Usalo per il telaio o la base su cui è costruito il resto dell'assieme.", "help.occurrence.move": "Sposta una parte dell'assieme solo lungo i gradi di libertà consentiti dai suoi giunti. Seleziona una faccia della parte, poi trascina una freccia o un arco disponibile.", "help.parameters.change": "Apre la tabella dei valori con nome e delle espressioni che guidano le quote della progettazione. Usala per cambiare una misura in un solo punto e far seguire tutte le lavorazioni che la usano.", + "help.parameters.export": "Salva i parametri del progetto come CSV o JSON. Usalo per modificarli in un foglio di calcolo o spostarli in un altro progetto.", + "help.parameters.graph": "Mostra quali parametri e lavorazioni ne usano altri, ed eventuali cicli o errori tra di loro. Usalo per vedere cosa influenzerà la modifica di un parametro.", + "help.parameters.import": "Legge i parametri da CSV o JSON nel progetto, tutti o nessuno. Usalo per importare valori da un foglio di calcolo o da un altro progetto.", + "help.parameters.move": "Sposta un parametro utente prima o dopo un altro nell'elenco. Usalo per tenere insieme i parametri correlati.", + "help.parts.fastener": "Aggiunge una vite, un bullone, un dado, una rondella, un perno o un cuscinetto standard della misura che scegli. Posizionato su un foro, si assesta nel foro con un giunto, così non devi modellare da solo gli elementi di fissaggio.", + "help.parts.insert": "Inserisce una parte standard della famiglia, misura e lunghezza che scegli. Posizionata sul bordo o sulla parete di un foro, si assesta sul foro con un giunto rigido.", + "help.parts.library": "Apre le parti standard: viti, bulloni, dadi, rondelle, grani, spine cilindriche e cuscinetti nelle misure standard. Usalo per aggiungere una parte standard invece di modellarla da solo.", + "help.parts.resize": "Cambia la misura o la lunghezza di una parte standard inserita e la ricostruisce; i suoi giunti la mantengono in sede. Usalo quando una vite risulta troppo lunga o un foro richiede un'altra misura.", + "help.plastic.assign_rule": "Assegna una regola per plastica ai corpi, così le loro lavorazioni in plastica ne usano come valori predefiniti lo sformo e il gioco. Usalo per impostare una sola volta un pezzo stampato per tutte le sue lavorazioni.", + "help.plastic.boss": "Aggiunge un risalto per vite su una faccia: un montante con foro, sformo, raccordo di base e nervature di sostegno facoltativi. Usalo per i punti di avvitamento in involucri stampati o stampati in 3D.", + "help.plastic.lip": "Aggiunge un labbro o una scanalatura corrispondente lungo il bordo di un corpo svuotato. Usalo perché due metà di un involucro si centrino tra loro e chiudano bene.", + "help.plastic.manage_rules": "Crea e modifica le regole per plastica: materiale, spessore della parete, raggi, gioco e sformo. Usale per mantenere coerenti le lavorazioni di un pezzo stampato.", + "help.plastic.rest": "Aggiunge un appoggio su una faccia: un tampone tondo o rettangolare, pieno o cavo, con sformo. Usalo come supporto o distanziale in un involucro stampato.", + "help.plastic.snap_fit": "Aggiunge un gancio a scatto su una faccia, con lunghezza, spessore e dente di aggancio. Usalo per fissare a scatto le parti senza viti.", "help.pointcloud.insert": "Inserisci una scansione PLY, XYZ o PTS come nuvola di punti accanto al modello. Usala come riferimento quando costruisci un modello a partire da dati misurati.", + "help.sheet.convert": "Trasforma una piastra o un corpo svuotato di spessore uniforme in un corpo in lamiera, con pieghe sugli spigoli che scegli. Usalo per rendere sviluppabile un pezzo esistente.", + "help.sheet.export_bend_table": "Salva la tabella delle pieghe di un corpo in lamiera come CSV o JSON: angoli, raggi e posizioni delle pieghe nello sviluppo piano. Usalo per la pressopiegatrice o per l'officina.", + "help.sheet.export_dxf": "Salva lo sviluppo piano come DXF, con contorni, linee di piega e note di piega facoltative. Usalo per il taglio laser, al plasma o a getto d'acqua.", + "help.sheet.flange": "Aggiunge una flangia: una piastra di base da uno schizzo, una parete lungo un contorno aperto dello schizzo o una parete piegata sugli spigoli della lamiera. Usalo per costruire pezzi in lamiera.", + "help.sheet.flat_pattern": "Crea lo sviluppo piano di un corpo in lamiera, con dimensioni, tagli e linee di piega. Usalo per controllare il grezzo prima di tagliarlo.", + "help.sheet.fold": "Piega una lamiera lungo una linea dello schizzo con un angolo e un raggio. Usalo per piegare una lamiera piana dopo avervi praticato i tagli.", + "help.sheet.hem": "Ripiega su se stesso il bordo di una lamiera. Usalo per bordi sicuri e rigidi, senza bave taglienti.", + "help.sheet.manage_rules": "Crea e modifica le regole per lamiera: spessore, raggio di piega, fattore K, scarichi e giochi. Usale per adattarle al materiale e agli utensili della tua officina.", + "help.sheet.path_flange": "Aggiunge una catena di flange lungo uno spigolo della lamiera, seguendo una catena aperta di linee dello schizzo. Usalo per profili a U o a Z in un solo passo.", + "help.sheet.perforate": "Aggiunge un campo di fori su tutta la lamiera piana, con disposizione sfalsata o quadrata. Usalo per prese d'aria, griglie e pannelli più leggeri.", + "help.sheet.refold": "Ripiega un corpo in lamiera sviluppato. Usalo dopo aver aggiunto lavorazioni alla lamiera piana.", + "help.sheet.unfold": "Spiega tutte le pieghe di un corpo in lamiera. Usalo per aggiungere fori o tagli che devono attraversare una piega, poi ripiega.", + "help.sketch.arc.center_point": "Disegna un arco di cerchio attorno a un punto centrale, da un punto iniziale a un punto finale. Usalo quando il centro dell'arco è noto, ad esempio un raggio attorno a un foro o a un perno.", + "help.sketch.arc.tangent": "Disegna un arco che parte dall'estremità di una linea o di un arco e prosegue tangente a essa. Usalo per continuare una catena con una curva dolce invece di un angolo vivo.", + "help.sketch.arc.three_point": "Disegna un arco da un punto iniziale a un punto finale passando per un terzo punto. Usalo quando l'arco deve passare per punti dati invece che attorno a un centro noto.", + "help.sketch.arc3d": "Disegna un arco di cerchio esatto nello spazio passante per tre punti, con Schizzo 3D attivo. Usalo per le curve di percorsi e guide che escono dal piano dello schizzo.", + "help.sketch.auto_constrain": "Aggiunge i vincoli che lo schizzo ha già quasi, come orizzontale, parallelo o coincidente, poi lo quota finché non è completamente definito. Usalo per bloccare in un solo passo uno schizzo disegnato a mano libera.", + "help.sketch.auto_constrain_from_datum": "Funziona come Vincola automaticamente, ma misura le posizioni da un punto di riferimento scelto invece che dall'origine. Usalo quando il pezzo è impostato a partire da un unico punto di riferimento, come un angolo o un foro.", + "help.sketch.blend_curve": "Unisce le estremità di due curve con una spline dolce tangente a entrambe, o anche continua in curvatura se lo scegli. Usalo per colmare un vuoto tra curve senza angoli vivi.", + "help.sketch.break": "Divide una curva in parti dove la attraversano altre curve, oppure nei punti che vi collochi. Usalo quando una parte di una curva ha bisogno di un proprio vincolo o deve essere eliminata da sola.", + "help.sketch.cancel": "Esce dallo schizzo e scarta tutto ciò che è stato modificato da quando è stato creato o aperto per la modifica. Le modifiche si recuperano con Annulla.", + "help.sketch.centerline": "Alterna le linee tra linee normali e linee d'asse, assi che i profili non includono. Usa una linea d'asse come asse per una rivoluzione, una specchiatura o un vincolo di simmetria.", + "help.sketch.chamfer.distance_angle": "Smussa l'angolo tra due linee, definito da una distanza lungo la prima linea e da un angolo. Usalo quando un disegno indica lo smusso come lunghezza e angolo, ad esempio 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Smussa l'angolo tra due linee alla stessa distanza lungo entrambe. Usalo per il normale smusso a 45° su un contorno.", + "help.sketch.chamfer.two_distance": "Smussa l'angolo tra due linee, definito da una distanza separata lungo ciascuna linea. Usalo per smussi diversi da 45°, indicati con due lunghezze.", + "help.sketch.circle.center": "Disegna un cerchio a partire dal centro e dal diametro. Usalo per fori, risalti e altre lavorazioni tonde il cui centro è noto.", + "help.sketch.circle.three_point": "Disegna un cerchio passante per tre punti. Usalo quando il cerchio deve passare per punti dati, ad esempio di una geometria esistente.", + "help.sketch.circle.three_tangent": "Disegna un cerchio tangente a tre linee, cerchi o archi. Usalo per inserire un cerchio nello spazio tra tre curve, come il cerchio inscritto di un triangolo.", + "help.sketch.circle.two_point": "Disegna un cerchio a partire dai due estremi del suo diametro. Usalo quando sono noti i punti del bordo del cerchio invece del centro.", + "help.sketch.circle.two_tangent": "Disegna un cerchio di dimensione data tangente a due linee, cerchi o archi. Usalo per un arrotondamento a raggio fisso tra due curve.", + "help.sketch.conic": "Disegna una curva conica tra due punti finali, definita da un punto di vertice e da un valore rho. Usalo per transizioni dolci di cui vuoi regolare la pienezza, da piatta a quasi un angolo vivo.", + "help.sketch.constrainer": "Applica il vincolo che una o due curve selezionate hanno già quasi, come orizzontale, parallelo, tangente o uguale. Usalo per mettere in ordine uno schizzo disegnato a mano, un vincolo alla volta.", + "help.sketch.constraint.coincident": "Fa giacere un punto su un altro punto, una curva o un asse dello schizzo. Usalo per chiudere i vuoti in un profilo o per mettere un punto su una linea.", + "help.sketch.constraint.collinear": "Fa giacere due linee sulla stessa retta. Usalo per allineare bordi interrotti, come i due lati di un intaglio.", + "help.sketch.constraint.concentric": "Dà lo stesso centro a due cerchi o archi. Usalo per anelli, lamature e alberi con spallamenti.", + "help.sketch.constraint.curvature": "Fa proseguire con la stessa curvatura (G2) due curve che si incontrano in un punto finale. Usalo dove un raccordo tangente non è abbastanza dolce, ad esempio sulle superfici in vista.", + "help.sketch.constraint.equal": "Rende uguali in lunghezza le linee, o uguali in raggio cerchi e archi. Usalo perché una sola quota governi più elementi corrispondenti.", + "help.sketch.constraint.fix": "Fissa punti o curve dove si trovano, oppure li libera di nuovo. Usalo per la geometria che non deve muoversi quando trascini o risolvi lo schizzo.", + "help.sketch.constraint.horizontal_vertical": "Rende orizzontale o verticale, a seconda di quale è più vicino, una linea o la linea tra due punti. Usalo per squadrare un contorno rispetto agli assi dello schizzo.", + "help.sketch.constraint.midpoint": "Mette un punto a metà di una linea, oppure fa coincidere i punti medi di due linee. Usalo per centrare la geometria su un bordo.", + "help.sketch.constraint.parallel": "Rende parallele due linee. Usalo per i lati che devono restare paralleli quando cambiano altre quote.", + "help.sketch.constraint.perpendicular": "Fa incontrare due linee ad angolo retto. Usalo per angoli retti tra linee che non sono sugli assi dello schizzo.", + "help.sketch.constraint.polygon": "Rende poligono regolare una catena chiusa di linee: lati uguali, con ogni vertice su un unico cerchio. Usalo per rendere regolare un poligono disegnato a mano e mantenerlo tale.", + "help.sketch.constraint.symmetry": "Rende due punti o curve speculari tra loro rispetto a una linea o a un punto. Usalo per mantenere simmetrico un profilo quando modifichi un lato.", + "help.sketch.constraint.tangent": "Fa toccare tangenzialmente due curve, come una linea e un arco. Usalo per raccordi dolci senza angoli vivi.", + "help.sketch.construction": "Alterna le curve tra geometria normale e geometria di costruzione, che i profili non includono. Usa le curve di costruzione come ausilio per l'impostazione, i riferimenti e le quote.", + "help.sketch.construction_line": "Crea una retta di costruzione infinita passante per due punti. Usala per impostare uno schizzo senza dividere i profili.", + "help.sketch.construction_line.angle": "Crea una retta di costruzione infinita con un angolo rispetto all'asse X dello schizzo. Seleziona il punto e digita l'angolo, oppure scegli la direzione.", + "help.sketch.construction_line.bisector": "Seleziona due linee rette dello schizzo che si intersecano, poi scegli una delle due bisettrici. Il risultato segue le linee di origine.", + "help.sketch.construction_line.horizontal": "Crea una retta di costruzione orizzontale infinita passante per un punto. Il suo vincolo orizzontale resta valido anche nelle modifiche successive.", + "help.sketch.construction_line.parallel": "Seleziona una linea retta dello schizzo, poi posiziona una retta di costruzione infinita parallela. Fai clic destro per scegliere un altro riferimento.", + "help.sketch.construction_line.perpendicular": "Seleziona una linea retta dello schizzo, poi posiziona una retta di costruzione infinita perpendicolare. Fai clic destro per scegliere un altro riferimento.", + "help.sketch.construction_line.tangent_at": "Crea una tangente in un punto di un cerchio o di un arco di cerchio, oppure in un estremo di una spline aperta o di una conica. Seleziona la curva, poi il suo punto di contatto.", + "help.sketch.construction_line.tangent_external": "Seleziona un cerchio o un arco di cerchio, poi un punto esterno e una soluzione di tangente. Le anteprime mostrano solo i contatti sull'arco disegnato.", + "help.sketch.construction_line.tangent_two": "Seleziona due cerchi o archi di cerchio, poi scegli una tangente comune nell'anteprima. I contatti devono trovarsi sulle curve disegnate.", + "help.sketch.construction_line.vertical": "Crea una retta di costruzione verticale infinita passante per un punto. Il suo vincolo verticale resta valido anche nelle modifiche successive.", + "help.sketch.copy": "Copia le curve e i punti dello schizzo selezionati, insieme ai vincoli e alle quote tra di essi. Incollali in questo schizzo o in un altro.", + "help.sketch.create": "Avvia un nuovo schizzo 2D su un piano o su una faccia piana del modello. Ogni estrusione, rivoluzione e sweep inizia con uno schizzo.", + "help.sketch.cut": "Copia la geometria dello schizzo selezionata e la elimina dallo schizzo, in un solo passo di annullamento. Incollala altrove in questo schizzo o in un altro.", + "help.sketch.dimension": "Aggiunge una quota di controllo: una lunghezza, una distanza, un angolo, un raggio o un diametro, a seconda di ciò che selezioni. Digita un valore o il nome di un parametro e lo schizzo lo segue.", + "help.sketch.edit": "Apre uno schizzo esistente per la modifica. Le lavorazioni costruite su di esso si aggiornano quando termini lo schizzo.", + "help.sketch.ellipse": "Disegna un'ellisse a partire dal centro, dall'estremità del suo asse maggiore e da un punto sul lato minore. Usalo per aperture ovali, camme e altre forme tonde allungate.", "help.sketch.equation_curve": "Disegna una curva da formule: x(t) e y(t), oppure y = f(x), su un intervallo. Le formule possono usare parametri e la curva li segue: usala per un'onda sinusoidale, una spirale o l'evolvente del dente di un ingranaggio.", + "help.sketch.extend": "Allunga una linea o un arco fino alla curva più vicina sul suo percorso, oppure estende due curve finché non si incontrano. Usalo per chiudere i vuoti in un profilo dopo un ritaglio o una modifica.", + "help.sketch.fillet": "Arrotonda con un arco di raggio dato l'angolo in cui si incontrano due linee o archi. Più angoli arrotondati insieme condividono lo stesso raggio.", + "help.sketch.finish": "Esce dallo schizzo e torna al modello. I suoi profili chiusi sono poi pronti per Estrusione, Rivoluzione e altre lavorazioni.", + "help.sketch.finish_auto_constrain": "Esegue Vincola automaticamente sullo schizzo, poi lo termina. Usalo per lasciare uno schizzo completamente definito in un solo passo.", + "help.sketch.fit_curves_to_section": "Taglia un corpo a mesh o solido con il piano dello schizzo e adatta linee e archi alla sezione. Usalo per ricostruire come schizzo modificabile un pezzo scansionato o importato.", + "help.sketch.include_3d": "Porta in questo schizzo spigoli e vertici del modello e curve di altri schizzi come riferimenti collegati, appiattendo su di esso quelli fuori dal suo piano. Usalo per costruire su una geometria che non giace sul piano dello schizzo.", + "help.sketch.infinite": "Alterna le linee tra linee normali e rette di costruzione infinite che attraversano tutta la vista. Usale come riferimenti di impostazione che non finiscono mai troppo presto.", + "help.sketch.insert_dxf": "Legge le curve di un disegno DXF in uno schizzo, scalate, ruotate e posizionate come imposti. Usalo per costruire a partire da un disegno 2D di un altro programma, come un contorno da tagliare al laser.", + "help.sketch.insert_svg": "Legge i tracciati di un disegno SVG in uno schizzo, scalati, ruotati e posizionati come imposti. Usalo per trasformare un logo o un contorno vettoriale in curve che puoi estrudere.", + "help.sketch.inspect": "Apre un rapporto sullo schizzo aperto: quanti gradi di libertà restano e se è completamente vincolato. Usalo per scoprire cosa si muove ancora prima di terminare lo schizzo.", + "help.sketch.intersect": "Aggiunge le curve o i punti in cui corpi, facce, spigoli o altri schizzi attraversano il piano dello schizzo. Restano collegati e seguono il modello quando cambia.", + "help.sketch.intersection_curve": "Crea curve 3D dove si incontrano due corpi o facce, collegate a essi. Usale come percorsi o guide che seguono il modello.", + "help.sketch.isoparametric_curve": "Crea una curva 3D lungo la direzione U o V di una faccia passante per un punto che scegli, collegata alla faccia. Usala come percorso o linea di divisione che segue la superficie.", + "help.sketch.line": "Disegna linee collegate punto per punto, come catena aperta o contorno chiuso. È lo strumento di base per la maggior parte dei profili.", + "help.sketch.line.midpoint": "Disegna una linea dal suo punto medio fino a un'estremità, con l'altra estremità speculare. Usalo per linee centrate su un punto, come un bordo simmetrico.", + "help.sketch.line3d": "Disegna linee rette collegate tra punti nello spazio, con Schizzo 3D attivo. Usalo per percorsi e telai che escono dal piano dello schizzo.", + "help.sketch.mirror": "Specchia curve e punti dello schizzo rispetto a una linea o a un asse e aggiunge vincoli di simmetria. Usalo per disegnare metà di un profilo simmetrico e completarlo.", + "help.sketch.move": "Sposta o ruota curve e punti dello schizzo, oppure una loro copia. Usalo per riposizionare la geometria mantenendone forma e vincoli.", + "help.sketch.offset": "Crea una copia di una catena di curve a una distanza stabilita, su un lato o su entrambi. Usalo per pareti, contorni e giochi; la distanza resta una quota modificabile.", + "help.sketch.paste": "Incolla nello schizzo attivo la geometria dello schizzo che hai copiato o tagliato. Posizionala in un punto o spostala di uno scostamento.", + "help.sketch.pattern.circular": "Copia la geometria dello schizzo attorno a un punto centrale, su un cerchio completo o su un angolo stabilito. Usalo per cerchi di bulloni, raggi e denti.", + "help.sketch.pattern.rectangular": "Copia la geometria dello schizzo in righe e colonne con spaziature stabilite. Usalo per griglie di fori, asole o prese d'aria.", + "help.sketch.point": "Colloca un punto dello schizzo. Usalo come riferimento per quote, vincoli, centri di fori o lavorazioni successive.", + "help.sketch.point3d": "Colloca un punto nello spazio, con Schizzo 3D attivo. Usalo come riferimento per curve e percorsi 3D.", + "help.sketch.polygon.circumscribed": "Disegna un poligono regolare attorno a un cerchio, dimensionato dal centro al punto medio di un lato. Usalo quando è nota l'apertura chiave, come per un dado esagonale.", + "help.sketch.polygon.edge": "Disegna un poligono regolare a partire dai due estremi di un lato. Usalo quando sono note la lunghezza e la posizione di un lato.", + "help.sketch.polygon.inscribed": "Disegna un poligono regolare dentro un cerchio, dimensionato dal centro a un vertice. Usalo quando è nota la dimensione tra i vertici opposti.", + "help.sketch.project": "Porta in questo schizzo spigoli, facce e vertici del modello e curve di altri schizzi, proiettati sul suo piano. Restano collegati e seguono il modello quando cambia.", + "help.sketch.project_to_surface": "Proietta le curve di altri schizzi lungo la normale di questo schizzo su una faccia, come curve 3D collegate. Usalo per applicare un logo, una linea di divisione o un percorso su una superficie curva.", + "help.sketch.rectangle.center": "Disegna un rettangolo a partire dal centro e da un angolo. Usalo per contorni centrati su un punto, come l'origine.", + "help.sketch.rectangle.rounded": "Disegna un rettangolo con tutti e quattro gli angoli arrotondati con lo stesso raggio. Usalo per piastre, coperchi e aperture con angoli arrotondati.", + "help.sketch.rectangle.three_point": "Disegna un rettangolo a partire da un lato e da un punto sul lato opposto. Usalo per rettangoli inclinati rispetto agli assi dello schizzo.", + "help.sketch.rectangle.two_point": "Disegna un rettangolo a partire da due angoli opposti. Usalo per i contorni di piastre, blocchi e tasche.", + "help.sketch.scale": "Scala curve e punti dello schizzo di un fattore rispetto a un punto base. Usalo per ridimensionare una parte di uno schizzo senza ridisegnarla.", + "help.sketch.slot.arc_center": "Disegna un'asola curva di larghezza data lungo un arco definito da centro, inizio e fine. Usalo per asole di regolazione attorno a un perno.", + "help.sketch.slot.arc_three_point": "Disegna un'asola curva di larghezza data lungo un arco passante per tre punti. Usalo quando il percorso dell'asola deve passare per punti dati.", + "help.sketch.slot.center_point": "Disegna un'asola retta di larghezza data dal suo centro al centro di un arco di estremità. Usalo per asole centrate su un punto.", + "help.sketch.slot.center_to_center": "Disegna un'asola retta di larghezza data tra i centri dei suoi due archi di estremità. Usalo per asole quotate per interasse, come le asole di regolazione per viti.", + "help.sketch.slot.overall": "Disegna un'asola retta di larghezza data da un'estremità esterna all'altra. Usalo quando conta la lunghezza complessiva dell'asola.", + "help.sketch.spline.control_point": "Disegna una spline cubica modellata da punti di controllo per i quali non passa. Usalo per curve dolci e fluide che modelli spostando i punti.", + "help.sketch.spline.control_point_5": "Disegna una spline di grado 5 modellata da punti di controllo. Usalo dove le curve devono raccordarsi con una curvatura più dolce, ad esempio su superfici di design in vista.", + "help.sketch.spline.fit_point": "Disegna una spline dolce che passa per ogni punto che collochi, aperta o chiusa. Usalo per tracciare una forma attraverso punti noti.", + "help.sketch.spline3d": "Disegna una curva dolce nello spazio passante per dei punti, con Schizzo 3D attivo. Usalo per percorsi di sweep e tracciati di cavi che escono dal piano dello schizzo.", + "help.sketch.spun_profile": "Crea nel piano dello schizzo il contorno descritto da un corpo quando ruota attorno a un asse. Usalo per ottenere la silhouette di un pezzo tornito per una rivoluzione o un disegno.", + "help.sketch.text": "Scrive del testo nello schizzo con il carattere, l'altezza e l'angolo scelti; le sue parole possono seguire i parametri. Estrudilo o mettilo in rilievo per etichette e scritte.", + "help.sketch.transform": "Scala, ruota e sposta la geometria dello schizzo rispetto a un punto centrale in un solo passo. Usalo per riposizionare e ridimensionare una selezione in una volta.", + "help.sketch.trim": "Rimuove il tratto di una curva compreso tra gli incroci più vicini attorno al punto in cui fai clic. Usalo per ripulire linee sovrapposte e ottenere un profilo chiuso.", "help.solid.align": "Sposta i corpi selezionati in modo che un punto, una faccia o un piano su di essi coincida con un punto, una faccia o un piano altrove. Usalo per posizionare un pezzo contro un altro senza misurare lo scostamento.", + "help.solid.boundary_fill": "Crea solidi dalle regioni racchiuse da corpi utensile sovrapposti, riempiendo solo le regioni che scegli. Usalo per costruire una forma dallo spazio delimitato insieme da più corpi.", + "help.solid.bounding_solid": "Crea un parallelepipedo che racchiude i corpi selezionati, con un margine facoltativo. Usalo per vedere l'ingombro complessivo di un pezzo, o come grezzo da cui viene lavorato.", + "help.solid.box": "Crea un parallelepipedo da lunghezza, larghezza e altezza, a partire da un angolo o centrato su un punto. Usalo per un blocco veloce, un segnaposto o un corpo in cui ricavare lavorazioni.", "help.solid.chamfer": "Taglia gli spigoli selezionati con uno smusso piano della distanza impostata. Usalo per eliminare gli spigoli vivi o per facilitare l'ingresso di un perno o di una vite.", + "help.solid.coil": "Crea un corpo elicoidale, come una molla, da un diametro, dal numero di spire, dall'altezza o dal passo e da una sezione tonda o quadrata. Usalo per molle, eliche e creste elicoidali.", "help.solid.combine": "Unisce i corpi, li sottrae da un corpo di destinazione oppure tiene solo il volume che hanno in comune, e può conservare i corpi utensile. Usalo per fondere parti, per tagliare una forma con un'altra o per trovare dove due corpi si sovrappongono.", + "help.solid.cone": "Crea un cono da un cerchio di base e un'altezza, oppure un tronco di cono se anche la sommità ha un raggio. Usalo per rastremazioni, imbuti, svasature e punte.", + "help.solid.cylinder": "Crea un cilindro da un raggio o un diametro e un'altezza, poggiato su un punto lungo un asse. Usalo per alberi, perni, risalti e grezzi tondi.", "help.solid.draft": "Dà uno sformo alle facce selezionate con l'angolo impostato, misurato da un piano neutro. Usalo su pezzi stampati o fusi perché escano dallo stampo.", + "help.solid.emboss": "Solleva da una faccia i profili dello schizzo, come un testo o un logo, oppure li incide al suo interno. Usalo per scritte, etichette e marcature su facce piane o tonde.", "help.solid.extrude": "Spinge il profilo di uno schizzo nel 3D lungo una distanza, aggiungendo o togliendo materiale. Usalo per trasformare un contorno piatto in un blocco, una sporgenza o una tasca.", "help.solid.fillet": "Arrotonda gli spigoli selezionati con un raccordo circolare liscio del raggio impostato. Usalo per addolcire gli spigoli vivi per resistenza, comodità o estetica.", "help.solid.hole": "Crea un foro tondo del diametro impostato in un punto scelto di una faccia. Usalo per i passaggi delle viti, i perni e altre semplici aperture tonde.", @@ -1408,20 +1679,62 @@ "help.solid.move": "Sposta o ruota i corpi selezionati, o una loro copia, della distanza e dell'angolo impostati. Usalo per riposizionare un corpo o per crearne un secondo in un altro punto.", "help.solid.offset_face": "Spinge le facce selezionate verso l'interno o l'esterno della distanza impostata e le facce intorno le seguono. Usalo per ispessire una parete, approfondire una tasca o alzare una sporgenza senza modificare lo schizzo.", "help.solid.pattern.circular": "Ripete gli oggetti selezionati intorno a un asse, per il numero e l'angolo totale impostati. Usalo per cerchi di bulloni, raggi, alette e denti.", + "help.solid.pattern.path": "Copia lavorazioni o corpi lungo un percorso dello schizzo, per numero e spaziatura. Usalo per fori lungo uno spigolo curvo o parti lungo una guida.", "help.solid.pattern.rectangular": "Ripete gli oggetti selezionati in una o due direzioni con il numero e la spaziatura impostati. Usalo per file e griglie di fori, nervature, perni o piedini.", + "help.solid.pipe": "Crea un tubo tondo lungo un percorso di curve dello schizzo, pieno o cavo con uno spessore di parete. Usalo per tubi, fili, cavi e guide.", "help.solid.press_pull": "Aggiunge o toglie materiale mentre trascini una faccia, oppure arrotonda gli spigoli mentre li trascini. Usalo per modifiche rapide direttamente sul modello.", "help.solid.remove": "Toglie i corpi selezionati dalla progettazione da questo punto della cronologia in poi; i passaggi precedenti li mantengono. Usalo per scartare un corpo ausiliario, come un utensile da taglio che non serve più.", "help.solid.replace_face": "Porta le facce piane selezionate su un piano o su una faccia parallela, e il corpo cresce o si riduce per raggiungerlo. Usalo per portare una faccia a filo con un altro pezzo o con un piano di costruzione.", "help.solid.revolve": "Fa ruotare il profilo di uno schizzo intorno a un asse per creare un solido rotondo. Usalo per alberi, manopole, ciotole e qualsiasi pezzo tondo attorno a una linea d'asse.", + "help.solid.rib": "Aggiunge una parete sottile lungo una curva aperta dello schizzo, estesa fino alle facce successive del corpo. Usalo per irrigidire pareti e angoli, ad esempio in pezzi stampati.", "help.solid.scale": "Ingrandisce o rimpicciolisce i corpi selezionati di un fattore, uguale in ogni direzione oppure uno per asse. Usalo per ridimensionare una forma importata o per compensare il ritiro.", "help.solid.shell": "Svuota un solido lasciando pareti dello spessore impostato e può aprire le facce che scegli. Usalo per scatole, coperchi e altri pezzi a parete sottile.", + "help.solid.sphere": "Crea una sfera da un raggio o un diametro attorno a un punto centrale. Usalo per palline, manopole ed estremità arrotondate.", "help.solid.split_body": "Taglia un corpo in corpi separati con un piano, la faccia di un altro corpo o una linea dello schizzo. Usalo per ottenere pezzi che vengono stampati, lavorati o colorati separatamente.", "help.solid.split_face": "Divide le facce selezionate lungo un piano, la faccia di un altro corpo o delle curve di schizzo, senza tagliare il corpo. Usalo per dare a una parte di una faccia il proprio sformo, colore o offset.", "help.solid.sweep": "Trascina il profilo di uno schizzo lungo un percorso per creare un solido. Usalo per tubi, guide, maniglie e qualsiasi pezzo a sezione costante che segue una curva.", + "help.solid.thread": "Aggiunge una filettatura metrica ISO a una faccia cilindrica, come filettatura cosmetica o ricavata nel corpo. Usalo per bulloni, fori filettati e parti a vite stampate.", + "help.solid.torus": "Crea un anello da un raggio maggiore attorno al suo asse e un raggio minore per la sua sezione tonda. Usalo per O-ring, maniglie e perline tonde.", + "help.solid.web": "Aggiunge una parete sottile lungo ogni curva aperta dello schizzo, ciascuna estesa fino alle facce successive del corpo. Usalo per un reticolo di pareti di sostegno all'interno di involucri e vassoi.", + "help.surface.blend": "Crea una superficie che collega gli spigoli di due corpi, tangente o continua in curvatura a entrambi. Usalo per unire dolcemente due superfici attraverso un vuoto.", + "help.surface.boundary": "Crea una superficie che riempie un contorno chiuso di due-quattro curve dello schizzo, o una rete di curve. Usalo per pannelli a forma libera definiti dai loro bordi.", + "help.surface.extend": "Allunga una superficie oltre i suoi bordi, di una distanza o fino a un piano o a una faccia. Usalo per far sovrapporre le superfici prima di ritagliarle o cucirle.", + "help.surface.extrude": "Spinge curve o profili dello schizzo lungo una distanza fino a formare una superficie, solo pareti, senza chiusure. Usalo per pareti sottili e per utensili di taglio o di divisione.", + "help.surface.fair": "Regolarizza l'interno delle facce a forma libera mentre i loro bordi restano fermi. Usalo per eliminare gobbe e riflessi ondulati in una superficie.", + "help.surface.loft": "Crea una superficie che passa in ordine per due o più sezioni, senza chiusure. Usalo per gusci e transizioni tra forme diverse.", + "help.surface.match": "Ricostruisce il bordo di una superficie in modo che incontri il bordo di un altro corpo, con tangenza o curvatura corrispondenti. Usalo per chiudere dolcemente una giunzione tra due superfici.", + "help.surface.offset": "Crea una copia delle facce a una distanza lungo le loro normali, come nuovo corpo di superficie. Usalo per rivestimenti, giochi o l'altro lato di una parete.", + "help.surface.patch": "Riempie una regione dello schizzo o un anello chiuso di spigoli con una faccia, piana o dolcemente curva. Usalo per chiudere i fori in un corpo di superficie.", + "help.surface.reverse_normal": "Rovescia le facce di un corpo di superficie, in modo che il loro lato esterno sia rivolto dall'altra parte. Usalo prima di ispessire o cucire quando le facce sono rivolte verso l'interno.", + "help.surface.revolve": "Fa ruotare curve o profili dello schizzo attorno a un asse per ottenere una superficie, senza chiusure. Usalo per gusci rotondi come paralumi, ciotole e ugelli.", + "help.surface.ruled": "Crea una striscia di rette a partire da una catena di spigoli, lungo la normale o la tangente della faccia oppure ad angolo. Usalo per pareti con sformo, prolungamenti e superfici di divisione.", + "help.surface.stitch": "Cuce insieme i corpi di superficie lungo i loro spigoli condivisi, formando un solido quando si chiudono. Usalo per trasformare un insieme di superfici in un unico corpo.", + "help.surface.sweep": "Muove curve o profili dello schizzo lungo un percorso per ottenere una superficie, senza chiusure. Usalo per grondaie, rifiniture e altre forme sottili che seguono un percorso.", + "help.surface.thicken": "Dà uno spessore a un corpo di superficie, trasformandolo in un solido. Usalo per ottenere da superfici pezzi stampabili o lavorabili.", + "help.surface.trim": "Taglia una superficie con un piano, un'altra superficie o curve dello schizzo, e mantiene il lato che scegli. Usalo per dare forma alle superfici prima di cucirle.", + "help.surface.unstitch": "Separa le facce di un corpo in corpi di superficie indipendenti; un solido si scompone in superfici. Usalo per rielaborare singole facce di un corpo.", + "help.surface.untrim": "Rimuove i fori da una faccia, oppure riporta il suo contorno esterno ai limiti naturali della superficie. Usalo per recuperare la superficie intera dopo un ritaglio.", "help.third_party": "Licenze di terze parti", "help.timeline.compute_all": "Ricostruisce ogni lavorazione della cronologia dall'inizio. Usalo per aggiornare il modello e vedere quali lavorazioni falliscono.", "help.timeline.delete": "Elimina le lavorazioni selezionate dalla cronologia; eliminando uno schizzo si eliminano anche le lavorazioni costruite su di esso. Usalo per togliere un passaggio che non serve più.", + "help.timeline.dependents": "Elenca le lavorazioni che verrebbero eliminate insieme a una lavorazione, e quelle che fallirebbero senza di essa. Usalo prima di eliminare o modificare una lavorazione.", "help.timeline.play": "Riproduce le lavorazioni rimanenti una alla volta, con una pausa di mezzo secondo dopo ogni ricostruzione. Esegui di nuovo questo comando o premi Escape per arrestare; Vai alla fine salta subito alla fine.", + "help.view.apply": "Ruota la vista verso una direzione standard come frontale, dall'alto o isometrica, oppure verso una vista con nome salvata. Usalo per guardare il modello da un'angolazione fissa.", + "help.view.delete": "Elimina una vista con nome salvata. Il modello non viene modificato.", + "help.view.fit": "Esegue zoom e panoramica in modo che l'intero modello, o la selezione, riempia la vista. Usalo quando il modello è uscito dall'inquadratura.", + "help.view.grid": "Mostra o nasconde la griglia nella vista. Usala come guida per dimensioni e orientamento durante la modellazione.", + "help.view.ground_shadow": "Mostra o nasconde l'ombra del modello sul suolo. Usala per valutare più facilmente altezza e posizione.", + "help.view.home": "Riporta la vista alla direzione iniziale e inquadra tutto il modello. Usalo per tornare rapidamente a una vista nota.", + "help.view.list": "Elenca le viste con nome salvate nel progetto. Usalo per trovare una vista salvata in precedenza.", + "help.view.navigate": "Ruota, sposta o ingrandisce la vista a passi, come un quarto di giro a sinistra. Usalo per muovere la camera con precisione invece di trascinare.", + "help.view.navigation_bar": "Mostra o nasconde la barra di navigazione in basso nella vista. Nascondila per avere più spazio, mostrala per raggiungere con il mouse gli strumenti della vista.", + "help.view.rename": "Dà un nuovo nome a una vista con nome salvata. La vista in sé resta la stessa.", + "help.view.save": "Salva la posizione attuale della camera come vista con nome nel progetto. Usalo per tornare in seguito alla stessa angolazione, ad esempio per le schermate.", + "help.view.spin": "Fa orbitare la vista attorno al modello in modo continuo fino al clic o al tasto successivo. Usalo per presentare un modello da tutti i lati.", + "help.view.tool": "Mantiene attivo uno strumento della camera (orbita, panoramica o zoom), così trascinando con il pulsante sinistro del mouse si muove la vista finché non lo disattivi. Usalo su un trackpad o senza pulsante centrale del mouse.", + "help.view.visual_style": "Cambia il modo in cui il modello viene disegnato: ombreggiato con o senza spigoli, reticolo, oppure con gli spigoli nascosti. Usa il reticolo per vedere all'interno, l'ombreggiato per un aspetto pulito.", + "history.sketch_under_constrained": "Sottovincolato ({count} gradi di libertà)", + "history.sketch_under_constrained_one": "Sottovincolato ({count} grado di libertà)", "hole_presets.confirm_delete": "Conferma eliminazione", "hole_presets.delete": "Elimina", "hole_presets.delete_prompt": "Eliminare questo preset personale? I fori esistenti restano invariati.", @@ -1525,6 +1838,8 @@ "joint_move.blocked_hint": "Controlla il tipo di giunto (ad esempio Rigido), il fissaggio a terra, i limiti del giunto e i valori comandati da parametri.", "joint_move.blocked_title": "Impossibile spostare questa parte", "joint_move.coarse": "Passo di rotazione vicino all'asse (°)", + "joint_move.conflict": "Un giunto di questa parte è in conflitto con gli altri: {joint}.", + "joint_move.conflict_hint": "Modifica, sospendi o elimina il giunto in conflitto, così gli altri giunti potranno posizionare la parte.", "joint_move.distance": "Distanza dall'inizio", "joint_move.done": "Fatto", "joint_move.fine": "Passo di rotazione lontano dall'asse (°)", @@ -1596,6 +1911,10 @@ "material.selection.mixed": "Materiali diversi", "measure.at": "In", "measure.item": "Elemento {number}", + "measure.quick_copied": "Misura copiata", + "measure.quick_copy": "Fai clic per copiare la misura", + "measure.quick_edges": "{count} spigoli", + "measure.quick_faces": "{count} facce", "messages.ago_h": "{n} h fa", "messages.ago_min": "{n} min fa", "messages.ago_s": "{n} s fa", @@ -1620,6 +1939,8 @@ "motion.track_name": "Traccia {number}", "nav.alias.help": "Shift+Alt+trascinamento sinistro orbita, Shift+Alt+centrale fa la panoramica, Shift+Alt+destro fa lo zoom; anche il trascinamento centrale fa la panoramica e il destro orbita", "nav.blender.help": "Il trascinamento centrale orbita, Shift+centrale fa la panoramica, Ctrl+centrale fa lo zoom; il trascinamento destro lascia ferma la vista", + "nav.creo.help": "Il trascinamento centrale orbita, Shift+centrale fa la panoramica, il trascinamento verticale con Ctrl+centrale fa lo zoom (verso il basso per avvicinare); scorri la rotellina per fare lo zoom", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Mouse e mouse 3D ruotano oltre entrambi i poli e conservano il rollio. L'aggancio degli assi con Shift è disattivato.", "nav.free_orbit.label": "Orbita libera", "nav.free_orbit.snap_help": "Mouse e mouse 3D ruotano oltre entrambi i poli e conservano il rollio. Tieni premuto Shift durante il trascinamento dell'orbita per agganciare la direzione della vista e il rollio.", @@ -1629,6 +1950,7 @@ "nav.hfss.help": "Alt+trascinamento con il pulsante sinistro esegue la panoramica, Shift+Alt+pulsante sinistro lo zoom, Ctrl+trascinamento con il pulsante sinistro su uno spazio vuoto orbita", "nav.inventor.help": "Il trascinamento centrale fa la panoramica, Shift+centrale orbita, Ctrl+centrale fa lo zoom, il trascinamento destro orbita", "nav.maya.help": "Alt+trascinamento con il pulsante sinistro orbita, Alt+pulsante centrale esegue la panoramica, Alt+pulsante destro lo zoom; anche il trascinamento con il pulsante centrale esegue la panoramica", + "nav.nx.help": "Il trascinamento centrale orbita, Shift+centrale fa la panoramica (centrale + destro di NX), Ctrl+centrale fa lo zoom (centrale + sinistro di NX); il trascinamento destro lascia ferma la vista", "nav.openscad.help": "Il trascinamento sinistro nello spazio vuoto orbita, Shift+trascinamento sinistro seleziona con un riquadro, il trascinamento sulla geometria dello schizzo la modifica; il trascinamento destro o centrale fa la panoramica, Shift+destro o Shift+centrale fa lo zoom", "nav.perspective.sketch": "La modifica dello schizzo usa la vista ortogonale. Termina lo schizzo per passare alla prospettiva.", "nav.right_drag_orbits.help": "Disattivato: il trascinamento con il pulsante destro non muove la camera e il pulsante destro apre solo il menu contestuale. Scegliendo l'assegnazione del mouse SolidWorks l'opzione si disattiva.", @@ -1748,6 +2070,11 @@ "not a move": "non è uno spostamento", "not a number": "non è un numero", "open a sketch first": "apri prima uno schizzo", + "parameters.apply_live": "Applica ogni modifica quando esci dal campo", + "parameters.apply_live_tip": "Disattivato: le modifiche restano in attesa fino ad Applica o OK, poi il progetto si ricostruisce una sola volta per tutte. Annulla o Escape le scarta.", + "parameters.held": "{count} modifiche in attesa di Applica", + "parameters.held_hint": "Modifica espressioni e unità. Le modifiche restano in attesa di Applica o OK.", + "parameters.held_one": "1 modifica in attesa di Applica", "parts.automatic_name": "automatico", "parts.dimension.across_flats": "Apertura chiave", "parts.dimension.bore": "Foro", @@ -1766,10 +2093,19 @@ "parts.family.button_head_cap_screw": "Vite a testa bombata con esagono incassato", "parts.family.dowel_pin": "Spina cilindrica", "parts.family.hex_bolt": "Vite a testa esagonale", + "parts.family.hex_cap_screw_inch": "Vite a testa esagonale (pollici)", "parts.family.hex_nut": "Dado esagonale", + "parts.family.hex_nut_inch": "Dado esagonale (pollici)", "parts.family.set_screw": "Grano a esagono incassato, punta piana", "parts.family.socket_head_cap_screw": "Vite a testa cilindrica con esagono incassato", "parts.family.washer": "Rondella piana", + "parts.family.washer_sae": "Rondella piana, SAE (stretta)", + "parts.family.washer_uss": "Rondella piana, USS (larga)", + "parts.holes": "Fori (facoltativo)", + "parts.placement_hint": "scegli uno o più fori per alloggiare una parte in ciascuno, oppure OK la colloca nell'origine", + "parts.system": "Sistema di unità", + "parts.system.inch": "Pollici", + "parts.system.metric": "Metrico", "pattern.alignment_2": "Allineamento 2", "pattern.alignment_hint": "Il conteggio include l'originale. Centro distribuisce le copie sui due lati; Inverti sceglie il lato con la copia in più per totali pari.", "pattern.direction_1": "Direzione 1", @@ -1810,6 +2146,8 @@ "prefs.anti_aliasing_note": "Ammorbidisce i bordi seghettati.", "prefs.applies_on_restart": "Si applica al riavvio", "prefs.assistant": "Assistente", + "prefs.auto_operation": "Scegli l'operazione automaticamente", + "prefs.auto_operation_note": "Le finestre delle lavorazioni scelgono Unisci, Nuovo corpo o Taglia in base a ciò che tocca il nuovo materiale, finché non ne scegli una tu. Disattivato: mantengono l'operazione con cui si aprono.", "prefs.axes": "Assi", "prefs.axis": "Asse", "prefs.bodies_folders": "Cartelle dei corpi", @@ -1820,6 +2158,10 @@ "prefs.bottom_centre": "In basso al centro", "prefs.bottom_right": "In basso a destra", "prefs.browser": "Struttura", + "prefs.browser_components_open": "Componenti aperti all'inizio", + "prefs.browser_components_open_note": "Ogni componente nel browser inizia aperto, come prima, invece che chiuso finché non lo apri.", + "prefs.browser_eye_left": "Occhio accanto alla freccia di espansione", + "prefs.browser_eye_left_note": "Le righe della Struttura mostrano l'occhio mostra/nascondi accanto alla freccia di espansione, come prima, invece che in una colonna all'estremità destra delle righe.", "prefs.browser_reveal_on_hover": "Mostra al passaggio del puntatore", "prefs.browser_show_note": "Visibile mantiene la Struttura sullo schermo. Mostra al passaggio del puntatore la tiene nascosta finché il puntatore non passa sulla sua posizione o sulla sottile linguetta al suo bordo sinistro, e resta aperta finché il puntatore è al suo interno o un suo menu è aperto.", "prefs.browser_shown": "Visibile", @@ -1827,6 +2169,8 @@ "prefs.button_left": "Trascinamento sinistro", "prefs.button_middle": "Trascinamento centrale", "prefs.button_right": "Trascinamento destro", + "prefs.carousel_next": "Successivo", + "prefs.carousel_previous": "Precedente", "prefs.choose_font": "Scegli il file del carattere…", "prefs.click": "Clic", "prefs.contact_shading": "Ombreggiatura di contatto morbida", @@ -1839,6 +2183,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Superfici curve", "prefs.curves": "Superfici curve", + "prefs.cut_preview_tint": "Mostra in rosso il materiale rimosso", + "prefs.cut_preview_tint_help": "Un'anteprima riempie il materiale che una lavorazione rimuove, e la forma che sostituisce, con un fantasma rosso semitrasparente. Se disattivato, questi riempimenti sono completamente trasparenti e vengono disegnati solo i loro contorni.", + "prefs.dark_parts_shading": "Mantieni la forma delle parti scure", + "prefs.dark_parts_shading_help": "Ombreggia la vista in luce lineare con un morbido riempimento di luce dal cielo, così le facce scure mantengono una sfumatura invece di diventare nere", "prefs.dead_zone_note": "La fascia tratteggiata è la zona morta: il movimento al suo interno viene ignorato.", "prefs.default": "predefinito", "prefs.design": "Impostazioni predefinite del progetto", @@ -1853,6 +2201,8 @@ "prefs.edges": "Spigoli e ombreggiatura", "prefs.extend": "Estendi", "prefs.extra_navigation": "Ctrl+trascina con il sinistro sullo spazio vuoto per orbitare; tieni premuto Space per la panoramica.", + "prefs.extrude_view_isometric": "Porta la vista in isometrica all'apertura di Estrusione", + "prefs.extrude_view_return": "Torna alla vista precedente alla chiusura di Estrusione", "prefs.follows_os": "Segue il sistema operativo", "prefs.font": "Carattere", "prefs.font_fallback": "I simboli che mancano nel carattere scelto passano a quello integrato, così nessuna etichetta mostra un riquadro vuoto.", @@ -1868,8 +2218,11 @@ "prefs.graphics_card_auto": "Automatica", "prefs.graphics_card_missing": "La scheda grafica salvata non è disponibile; viene usata Automatica.", "prefs.graphics_card_restart": "Ha effetto dopo il riavvio di SolidCraft. WGPU_ADAPTER_NAME prevale su questa scelta.", + "prefs.graphics_card_unused": "La scheda grafica salvata non è stata usata per questa finestra; la scheda in uso è indicata in Aiuto › Informazioni su e nella barra di stato. Prova Automatica, oppure imposta WGPU_ADAPTER_NAME su una parte univoca del nome della scheda.", "prefs.graphics_note": "Scegli tra velocità e fluidità dell'immagine. Ogni scelta mostra il suo effetto su un esempio.", "prefs.graphics_presets_note": "Una preimpostazione regola insieme le scelte qui sotto.", + "prefs.hide_constraint_glyphs_zoomed_out": "Nascondi i simboli dei vincoli quando lo zoom è ridotto", + "prefs.hide_constraint_glyphs_zoomed_out_note": "I simboli dei vincoli scompaiono dalla vista quando lo zoom sullo schizzo è ridotto al punto da affollarlo. Disattivato: restano a una dimensione fissa sullo schermo a qualsiasi zoom.", "prefs.history": "Cronologia", "prefs.history_origin_bodies": "Mostra origine e corpi in alto", "prefs.history_origin_bodies_note": "La Cronologia a sinistra o sotto la Struttura inizia con la cartella Corpi del componente attivo e con l'Origine, con occhi e menu come nella Struttura. La Cronologia in basso non cambia.", @@ -1880,6 +2233,8 @@ "prefs.history_sketches_note": "Con Schizzi impostato su Sotto la lavorazione, la Cronologia a sinistra elenca ogni schizzo rientrato di un livello, sotto la prima lavorazione creata a partire da esso, quando è abbastanza larga da mostrare i nomi. La cronologia in basso mantiene sempre l'ordine di creazione.", "prefs.history_sketches_under_feature": "Sotto la lavorazione", "prefs.hold_stop_snapping": "Tieni premuto per disattivare l'aggancio", + "prefs.home_fit_size": "Dimensione di Inizio e Adatta", + "prefs.home_fit_size_note": "Quanta parte della vista occupa il modello quando Inizio, Adatta, un progetto aperto o un cambio di vista dal navigatore della vista ne impostano l'inquadratura, sia o no attiva l'impostazione qui sotto. 100 %: riempie la vista tra i pannelli, la bussola e la barra di navigazione.", "prefs.icons_only": "Solo icone", "prefs.imported_file": "File importato", "prefs.in_browser": "Nella Struttura", @@ -1888,13 +2243,22 @@ "prefs.interface_language": "Lingua dell'interfaccia", "prefs.interface_note": "Aspetto di SolidCraft e disposizione dei suoi elementi.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Inverti le frecce curve di rollio", + "prefs.invert_curved_roll_arrows_note": "Le due frecce curve all'angolo del cubo fanno ruotare la vista nel piano dello schermo. Attivato: la freccia oraria ruota in senso antiorario e la freccia antioraria ruota in senso orario. Disattivato: ogni freccia ruota la vista nel verso in cui si curva.", + "prefs.invert_navigator_arrows": "Inverti le frecce di rotazione del cubo della vista", + "prefs.invert_navigator_arrows_note": "Le frecce attorno al cubo fanno orbitare la camera nella direzione in cui puntano, come in Fusion e Inventor: la freccia a sinistra punta a destra e sposta la camera a destra. Disattivato: una freccia ruota il cubo verso il lato in cui si trova, quindi la freccia sinistra sposta la camera a sinistra. Le frecce curve di rollio non sono interessate.", + "prefs.keep_work_on_tab_switch": "Mantieni aperti finestre di dialogo e strumenti quando cambi progetto", + "prefs.keep_work_on_tab_switch_note": "Ogni scheda di progetto conserva la finestra di dialogo o lo strumento aperto, con ciò che hai scelto e digitato, e la propria scheda della barra degli strumenti. Li ritrovi quando torni al progetto. Disattivato: cambiando progetto vengono annullati e compare la scheda Modella.", "prefs.labels": "Etichette", + "prefs.language_system": "Sistema", "prefs.layout": "Disposizione", "prefs.layout_note": "Compatta: pannelli ancorati ai bordi della finestra. La trasparenza della Struttura è disponibile in Flottante. Cambia il lato dell'Assistente nella pagina Assistente.", "prefs.left": "Sinistra", "prefs.left_click": "Clic sinistro", "prefs.line_drag_draws_one": "Premi e trascina per disegnare una linea", "prefs.line_drag_draws_one_note": "Nello strumento Linea, premere, trascinare e rilasciare disegna una linea dal punto di pressione a quello di rilascio, e il disegno termina lì. I clic disegnano comunque una catena. Disattivato: un trascinamento posiziona un punto dove viene rilasciato, come un clic.", + "prefs.line_hover_tangent_arc": "Fermati sull'ultimo punto di una linea per passare a un arco tangente", + "prefs.line_hover_tangent_arc_note": "Nello strumento Linea, dopo aver disegnato un segmento, allontanati dall'ultimo punto della catena, torna indietro e tieni fermo il puntatore su di esso: il clic successivo termina un arco tangente, e lo stesso gesto riporta alle linee. Disattivato: fermarsi lì non fa nulla.", "prefs.linked_designs": "Progetti collegati", "prefs.live_input": "Input in tempo reale", "prefs.live_preview": "Anteprima dal vivo", @@ -1908,6 +2272,9 @@ "prefs.max_file_size_step": "File STEP e di importazione", "prefs.max_file_size_web": "L’app web apre file STEP e di importazione fino a 512 MB e progetti fino a 256 MB: una scheda del browser non può contenere file più grandi. L’app desktop permette di aumentare questi limiti.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Icone grandi", + "prefs.menu_list": "Elenco", + "prefs.menus": "Menu", "prefs.minutes": "minuti", "prefs.minutes_suffix": " min", "prefs.mouse": "Mouse e trackpad", @@ -1915,6 +2282,8 @@ "prefs.mouse_mapping": "Assegnazione del mouse", "prefs.navigation": "Navigazione", "prefs.navigation_note": "Come mouse, trackpad e mouse 3D spostano la vista.", + "prefs.navigator_fit": "Adatta il modello dopo un cambio di vista dal navigatore", + "prefs.navigator_fit_note": "Una faccia, un angolo o una freccia del cubo della vista, o un asse del gizmo, guarda anche il centro del modello dall'unica distanza che lo inquadra da ogni lato (la sua sfera di ingombro). Inizio usa lo stesso zoom e lo stesso centro finché questa opzione è attiva, quindi le viste scelte dopo si limitano a ruotare. Disattivato: la vista ruota sul posto, mantenendo punto di mira e zoom.", "prefs.network_host_remove": "Rimuovi", "prefs.network_locations": "Consenti posizioni di rete nei progetti", "prefs.network_locations_note": "Disattivato: i file collegati di un progetto su un altro computer (\\\\server\\share) vengono aperti solo dai server elencati qui, o dopo che ne consenti uno quando richiesto.", @@ -1927,10 +2296,18 @@ "prefs.origin_plane_names": "Nomi dei piani di origine", "prefs.origin_plane_names_note": "Nomi mostrati nella Struttura, nelle finestre di dialogo e negli elenchi. {top} è XY, {front} è XZ e {right} è YZ, con Z verso l'alto. Comandi, script e progetti salvati mantengono XY, XZ e YZ.", "prefs.overall_speed": "Velocità complessiva", + "prefs.parameter_list_rows": "Righe dell'elenco dei parametri", + "prefs.parameter_list_rows_tip": "La freccia giù in un campo valore vuoto elenca i parametri, prima i preferiti, fino a questo numero. Un numero minore mantiene leggero l'elenco in un progetto grande.", + "prefs.persistent_ribbon_pressed": "Evidenzia i comandi attivi della barra multifunzione", + "prefs.persistent_ribbon_pressed_help": "Evidenzia i comandi della barra multifunzione finché i loro effetti sono attivi. Disattiva per mantenere l'aspetto neutro precedente e la guida dei comandi.", "prefs.perspective_fov": "Campo visivo", "prefs.placement": "Posizione", "prefs.prefer_free_sketch_points": "Preferisci i punti dello schizzo mobili quando i punti si sovrappongono", "prefs.preview_choices": "Anteprima delle tue scelte", + "prefs.preview_tint_new_faces": "Colora la nuova superficie in un'anteprima", + "prefs.preview_tint_new_faces_help": "L'anteprima di una lavorazione che modifica un corpo può disegnare la superficie aggiunta con il colore dell'anteprima. Se disattivato, il corpo viene disegnato com'è.", + "prefs.print_face_highlight": "Evidenziazione della faccia di stampa", + "prefs.print_face_highlight_tip": "Intensità della tinta e del contorno della faccia di stampa di un corpo nella vista. 0 % non mostra evidenziazione.", "prefs.profile_active": "Profilo attivo", "prefs.profile_applied": "Profilo applicato.", "prefs.profile_changed": "Le impostazioni sono cambiate da quando il profilo è stato salvato. Salva le conserva nel profilo.", @@ -1952,9 +2329,13 @@ "prefs.quality_fastest": "più veloce", "prefs.quality_slowest": "più lento", "prefs.quality_smoother": "più fluido", + "prefs.quick_measure": "Misura rapida nell'angolo della vista", + "prefs.quick_measure_note": "La dimensione della selezione nell'angolo in basso a destra della vista: la lunghezza di uno spigolo, oppure Ø e R per uno tondo, l'area di una faccia, la posizione di un punto, la distanza e l'angolo tra due elementi, il totale di più spigoli o facce. Un clic la copia.", "prefs.render_previous_geometry_budget": "Usa il budget di geometria precedente per l'anteprima di Rendering", "prefs.render_previous_geometry_budget_help": "Ripristina il limite fisso di geometria precedente (512 MiB su desktop a 64 bit, 128 MiB altrove) invece del budget basato sul dispositivo.", "prefs.reports_saved": "{n} salvati", + "prefs.ribbon_click_ends_tool": "Un clic sul pulsante dello strumento in uso lo termina", + "prefs.ribbon_click_ends_tool_note": "Un clic sul pulsante evidenziato nella barra multifunzione dello strumento di schizzo in uso termina lo strumento, così i clic nella vista tornano a selezionare. Disattivato: il clic avvia di nuovo lo strumento.", "prefs.ribbon_reveal": "Mostra i risultati della ricerca nella barra multifunzione", "prefs.ribbon_reveal_note": "Passando il puntatore su un risultato in Cerca comandi si vede dove si trova il comando nella barra multifunzione: la sua scheda, il suo pulsante o la sua riga nel menu a discesa di un pannello. Un comando avviato dalla ricerca lampeggia lì, e un comando in esecuzione da un menu a discesa ne evidenzia il pannello.", "prefs.right_click": "Clic destro", @@ -1965,6 +2346,8 @@ "prefs.search_empty": "Nessuna impostazione corrispondente", "prefs.select": "Seleziona", "prefs.select_one_item": "Seleziona un elemento", + "prefs.select_other_hidden": "Seleziona la geometria nascosta con Seleziona altro", + "prefs.select_other_hidden_help": "Attivo: include i corpi e gli schizzi nascosti e gli spigoli occlusi vicino al puntatore. Disattivato: usa l'elenco originale della geometria visibile sotto il puntatore.", "prefs.selecting": "Selezione", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift solo aggiunge; Ctrl / Cmd alterna", @@ -1976,31 +2359,63 @@ "prefs.sketch_align_points_note": "Durante il disegno, un punto si allinea contemporaneamente in orizzontale con un punto dello schizzo e in verticale con un altro, con una guida punteggiata, e il clic mantiene entrambi gli allineamenti. Disattivato: solo con il punto precedente, un asse alla volta.", "prefs.sketch_conflict_colour": "Geometria in conflitto nel colore di conflitto", "prefs.sketch_conflict_colour_note": "Quando i vincoli di uno schizzo sono in conflitto, anche le curve e i punti interessati da un vincolo in errore vengono disegnati con il colore di conflitto, non solo il suo simbolo o la sua quota. Disattivato: mantengono i colori abituali.", + "prefs.sketch_construction_lines": "Strumenti estesi per le rette di costruzione", "prefs.sketch_exit_view": "Al termine di uno schizzo", "prefs.sketch_exit_view.keep": "Mantieni la vista attuale", "prefs.sketch_exit_view.previous": "Torna alla vista precedente", "prefs.sketch_exit_view.unless_rotated": "Torna, se non ruotata", "prefs.sketch_exit_view_note": "Dove va la vista dopo Termina schizzo, Annulla o un doppio Esc.", + "prefs.sketch_face_activates_part": "Creare uno schizzo sulla faccia di una parte rende attiva quella parte", + "prefs.sketch_face_activates_part_note": "Uno schizzo avviato sulla faccia di un corpo di un altro componente attiva prima quel componente, così lo schizzo gli appartiene e resta con quella parte nella Struttura. In seguito la parte resta attiva. Disattivato: lo schizzo appartiene al componente attivo.", + "prefs.sketch_open_look_at": "Ruota la vista verso lo schizzo quando si apre", + "prefs.sketch_open_look_at_note": "Disattivato: creando o modificando uno schizzo la vista resta com'è. Vista normale orienta la vista sullo schizzo quando vuoi.", "prefs.sketch_recent_snap": "Aggancia automaticamente ai centri e punti medi recenti", "prefs.sketch_recent_snap_note": "Durante il disegno, il cursore si aggancia dove si incrociano le guide degli ultimi due centri di cerchio o punti medi di segmento. Disattivato: queste guide restano solo visive e il cursore non si sposta.", "prefs.sketch_selection": "Schizzo e selezione", "prefs.sketch_selection_heading": "Schizzo e selezione", "prefs.sketch_selection_note": "Come si agganciano gli schizzi e come selezionano i clic.", + "prefs.sketch_state_icons": "Icone degli schizzi nel colore del loro stato", + "prefs.sketch_state_icons_note": "Nella Cronologia e nella Struttura, l'icona di uno schizzo assume il colore del suo stato (sottovincolato, completamente vincolato o in conflitto) e il suo suggerimento indica lo stato. Disattivato: ogni schizzo ha la stessa icona.", "prefs.sketch_tab_always": "Mantieni visibile la scheda Schizzo", "prefs.sketch_tab_always_note": "La scheda Schizzo resta nella barra multifunzione, subito dopo Modella, finché nessuno schizzo è aperto. I suoi strumenti di disegno avviano allora uno schizzo sul piano o sulla faccia selezionati, oppure sul piano che selezioni subito dopo, con lo strumento già attivo.", "prefs.sketch_tracking_guides": "Guide di allineamento di centro e punto medio", "prefs.sketch_tracking_guides_note": "Passa il puntatore sul centro di un cerchio o sul punto medio di un segmento, poi spostati in orizzontale o in verticale per mostrare una guida punteggiata temporanea.", + "prefs.sketch_tracking_points": "Guide di allineamento da estremità e angoli durante il disegno", + "prefs.sketch_tracking_points_note": "Mentre uno strumento di disegno attende un punto, passando il puntatore sull'estremità di una linea o di un arco, sull'angolo di un rettangolo o su un punto libero compare la stessa guida punteggiata temporanea di un centro o di un punto medio. Disattivato: solo centri e punti medi.", "prefs.sketching": "Schizzi", "prefs.snap_drawing_note": "Mentre disegni o trascini un punto dello schizzo.", "prefs.source": "Fonte", "prefs.speed": "Velocità", "prefs.stand_up_note": "Dopo l'apertura di un file STEP o IGES con Z verso l'alto, proponi un quarto di giro attorno a X.", + "prefs.stand_up_unknown": "Per i file di programmi sconosciuti", + "prefs.stand_up_unknown.ask": "Chiedi in una finestra di dialogo", + "prefs.stand_up_unknown.note": "Mostra una nota", + "prefs.stand_up_unknown.off": "Non proporre", + "prefs.stand_up_unknown_note": "Come viene fatta la proposta quando l'intestazione del file non indica alcun programma noto per salvare con Y verso l'alto. Una nota viene mostrata solo quando il file sembra coricato; Chiedi in una finestra di dialogo chiede per ogni file di questo tipo, come prima.", "prefs.status_bar": "Barra di stato", "prefs.status_bar_note": "Una barra sottile lungo il bordo inferiore della finestra mostra cosa si sta modificando, lo stato dello schizzo aperto nel suo colore e le unità del progetto; un clic sulle unità le cambia. Lo stato dello schizzo non compare più nell'angolo della vista.", "prefs.status_done": "Fatto", "prefs.status_error": "Errore", "prefs.status_selected": "Selezionato", "prefs.status_warning": "Avviso", + "prefs.structure.appearance": "Aspetto", + "prefs.structure.appearance_note": "Colori, testo e accessibilità.", + "prefs.structure.in_profile": "Nel profilo", + "prefs.structure.layout": "Disposizione", + "prefs.structure.layout_note": "Dove si trovano le parti della finestra.", + "prefs.structure.look": "Aspetto visivo", + "prefs.structure.measure_pointer": "Misura e puntatore", + "prefs.structure.mouse3d": "Mouse 3D", + "prefs.structure.mouse3d_note": "SpaceMouse e SpaceNavigator.", + "prefs.structure.navigation_note": "Mouse e trackpad. Il mouse 3D ha una pagina propria.", + "prefs.structure.profile": "Profilo", + "prefs.structure.profile_edited": "Modificato dopo il salvataggio", + "prefs.structure.profile_hover": "Salvato nei profili delle impostazioni", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Schizzo", + "prefs.structure.tools": "Strumenti", + "prefs.structure.tools_note": "Come si comportano gli strumenti di modellazione.", + "prefs.structure.work": "Lavoro", "prefs.supersampling_brief": "Disegna la vista più grande e poi la riduce con un filtro: molto nitida, ma più pesante.", "prefs.tab_accent_note": "L'accento segue la scheda attiva", "prefs.theme_file": "file del tema", @@ -2012,6 +2427,16 @@ "prefs.theme_follow_off": "Disattivato", "prefs.theme_follow_stop": "Smetti di seguire", "prefs.theme_import_hint": "Fai clic per scegliere un file di tema, trascinane uno qui oppure premi Ctrl+V (Cmd+V su Mac) con un tema copiato", + "prefs.theme_option_opacity": "Opacità", + "prefs.theme_option_opacity_help": "Regola l'opacità dei pannelli flottanti. Una soglia minima di leggibilità protegge il testo sopra i colori della vista.", + "prefs.theme_option_tab_colours": "Colori delle schede", + "prefs.theme_option_tab_colours_help": "Usa i colori dei pannelli e della vista di questo tema per ogni scheda della barra multifunzione.", + "prefs.theme_option_tab_fade_ms": "Transizione tra schede", + "prefs.theme_option_tab_fade_ms_help": "Sfuma i colori dei pannelli e della vista quando si cambia scheda. Zero cambia all'istante.", + "prefs.theme_options_badge": "Opzioni", + "prefs.theme_options_more": "Altro · {count}", + "prefs.theme_options_reset": "Reimposta", + "prefs.theme_options_unavailable": "Non disponibile su questo dispositivo", "prefs.theme_paste": "Incolla tema", "prefs.theme_paste_none": "Negli appunti non c'è nessun tema SolidCraft", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2458,23 @@ "prefs.under_cursor": "Sotto il cursore", "prefs.units_precision": "Unità e precisione", "prefs.updates": "Aggiornamenti", + "prefs.value_boxes_in_view": "Mostra i valori accanto alle maniglie nella vista", + "prefs.value_boxes_in_view_tip": "Il valore di un comando (Distanza, Raggio…) in un riquadro accanto alla sua maniglia, sopra il modello. Disattivato: lo digiti nella finestra del comando, che riceve la tastiera dopo una selezione, e niente copre il modello.", "prefs.view": "Comportamento della vista", "prefs.view_confirm_corner": "OK e Annulla nell'angolo della vista", "prefs.view_confirm_corner_note": "Mentre è aperta una finestra di dialogo o uno schizzo, una spunta e una croce in alto a destra nella vista fanno ciò che fanno OK e Annulla della finestra, oppure terminano e annullano lo schizzo. Il navigatore della vista scende sotto di esse.", "prefs.viewport": "Vista", + "prefs.viewport_analysis_status": "Mostra lo stato di analisi della vista", + "prefs.viewport_analysis_status_help": "Mostra le analisi attive sopra la vista, apri le loro legende da ogni elemento e usa Esc per disattivare l'analisi più recente. Disattiva per ripristinare le legende negli angoli e il comportamento precedente di Esc.", "prefs.viewport_background": "Sfondo", "prefs.viewport_background_colour": "Colore", "prefs.viewport_background_theme": "Sfumatura del tema", + "prefs.viewport_section_status": "Mostra lo stato di sezione della vista", + "prefs.viewport_section_status_help": "Mostra l'impostazione della sezione nella vista. Escape e il pulsante attivo della barra multifunzione la disattivano. Disattiva per mantenere i controlli di sezione precedenti.", + "prefs.viewport_status_details": "Dettagli della vista in tempo reale", + "prefs.viewport_status_details_help": "Modifica le impostazioni di analisi e sezione attive nelle schede di dettaglio standard. Disattiva per ripristinare le legende di analisi in sola lettura e la finestra di dialogo Sezione.", + "prefs.viewport_status_summary": "Raggruppa gli elementi di stato della vista", + "prefs.viewport_status_summary_help": "Raggruppa tre o più elementi di stato della vista in un unico indicatore di riepilogo. Disattiva per mantenere ogni elemento nella riga completa.", "prefs.wheel": "Rotellina", "prefs.wheel_trackpad": "Rotellina e trackpad", "prefs.workspace": "Area di lavoro", @@ -2049,6 +2484,10 @@ "properties.title": "Proprietà: {name}", "recovery.days_ago": "{count} giorni fa", "recovery.detail": "{file} · {features} feature · salvato automaticamente {when}", + "recovery.discard_all": "Scarta tutto", + "recovery.discard_all_detail": "Questa azione non può essere annullata.", + "recovery.discard_all_title": "Scartare {count} salvataggi automatici?", + "recovery.discard_all_title_one": "Scartare 1 salvataggio automatico?", "recovery.hours_ago": "{count} h fa", "recovery.just_now": "proprio ora", "recovery.min_ago": "{count} min fa", @@ -2164,6 +2603,10 @@ "render.base_color": "Colore di base · sRGB", "render.base_metallic": "Frazione metallica", "render.base_opaque_only": "Questo editor mantiene la semantica dei corpi opachi. Per la trasmissione ottica usa i controlli espliciti del vetro.", + "render.batch_all_shots": "Tutte le inquadrature ({count})", + "render.batch_empty": "Salva un'inquadratura prima di renderizzare tutte le inquadrature.", + "render.batch_limit": "Il rendering di tutte le inquadrature è limitato a 32 inquadrature.", + "render.batch_status": "{running} in corso · {waiting} in attesa", "render.bloom_enable": "Bloom di visualizzazione", "render.bloom_help": "Alone creativo solo in uscita, ricavato dalle alte luci lineari positive e diffuso con tre passate box normalizzate. Il raggio è in pixel di uscita. Viene aggiunto nella luce di visualizzazione lineare prima della conversione sRGB; non è un effetto di lente o volumetrico né un miglioramento della convergenza. L'EXR grezzo resta invariato.", "render.bloom_opaque": "Il bloom richiede un'uscita opaca. Il PNG trasparente viene rifiutato, non appiattito in silenzio.", @@ -2274,6 +2717,13 @@ "render.choose_look": "Scegli prima un aspetto in Aspetti", "render.chromatic_offset": "Scostamento cromatico dei bordi", "render.clear_stage": "Rimuovi la scenografia salvata", + "render.compare_divider": "Divisore del confronto", + "render.compare_live": "Live", + "render.compare_live_preview": "Anteprima dal vivo", + "render.compare_render": "Rendering {number}", + "render.compare_side": "Rendering {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · acquisito alla revisione {revision}", + "render.compare_swap": "Scambia", "render.copy_request": "Copia JSON", "render.cpu_aa_help": "Campioni spaziali: più campioni migliorano i bordi e aumentano il tempo di rendering.", "render.cpu_area_add": "Aggiungi luce rettangolare CPU", @@ -2914,7 +3364,9 @@ "render.output_ready": "Pronto per il rendering", "render.output_run_check": "Esegui verifica", "render.output_size_limit": "{method}: fino a {dimension} px per lato e {pixels} pixel. Dimensioni massime consentite: {width} × {height}.", + "render.output_size_method_profile": "Per renderizzare {width} × {height}, scegli {method} con il profilo di risorse della CPU {profile}, oppure una dimensione minore.", "render.output_size_ok": "Dimensioni OK · {width} × {height} px", + "render.output_size_profile": "Per renderizzare {width} × {height}, scegli il profilo di risorse della CPU {profile}, oppure una dimensione minore.", "render.output_swap_orientation": "Scambia larghezza e altezza", "render.output_tools_inspector": "Modifica dimensioni e formato nell'ispettore Uscita.", "render.output_view_image": "Visualizza immagine", @@ -3021,6 +3473,10 @@ "render.result_retained": "Viene mostrata l'ultima immagine completata; un rendering più recente non l'ha ancora sostituita.", "render.result_sequence": "Punto di ripristino", "render.result_title": "Risultato del rendering", + "render.results_choose": "Risultati conservati", + "render.results_label": "Rendering {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [obsoleto]", + "render.results_unnamed": "Immagine", "render.return_design": "Torna a Progettazione", "render.review_stale": "Questa revisione è obsoleta. Risolvi o verifica di nuovo prima di applicare.", "render.ribbon_aging": "Invecchiamento", @@ -3127,6 +3583,7 @@ "render.size_custom": "Personalizzato…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · richiede {profile}", "render.size_presets": "Preimpostazioni delle dimensioni", "render.size_presets_pending": "In arrivo con l'editor Uscita", "render.size_preview": "Anteprima", @@ -3414,6 +3871,24 @@ "sheet.flange_type_contour": "Contorno", "sheet.flange_type_edge": "Spigolo", "sheet.no_body": "non c'è nessun corpo in lamiera: creane uno con Flangia > Base, oppure trasforma una piastra in lamiera con Converti in lamiera (scegli la sua faccia piana più grande)", + "sheet.personal_rules.confirm_delete": "Conferma eliminazione", + "sheet.personal_rules.delete": "Elimina", + "sheet.personal_rules.delete_prompt": "Eliminare questa regola personale? Le regole già presenti nei progetti non cambiano.", + "sheet.personal_rules.full": "La libreria personale contiene già 64 regole.", + "sheet.personal_rules.invalid_name": "Inserisci un nome breve senza interruzioni di riga né caratteri di controllo.", + "sheet.personal_rules.invalid_values": "Completa i valori della regola: ciascuno deve risultare valido in questo progetto, con uno spessore positivo e un fattore K da 0 a 1.", + "sheet.personal_rules.missing": "La regola personale selezionata non è più disponibile.", + "sheet.personal_rules.name": "Nome della regola", + "sheet.personal_rules.name_exists": "Esiste già una regola personale con questo nome. Usa un nome diverso.", + "sheet.personal_rules.name_hint": "Un nome univoco", + "sheet.personal_rules.overwrite": "Salva le modifiche nella regola personale selezionata", + "sheet.personal_rules.rename": "Rinomina", + "sheet.personal_rules.rule": "Regola personale", + "sheet.personal_rules.save": "Salva come nuova", + "sheet.personal_rules.scope": "Salvata nel tuo profilo per tutti i progetti.", + "sheet.personal_rules.select": "Seleziona una regola", + "sheet.personal_rules.title": "Regole personali", + "sheet.personal_rules.unsupported": "Questa regola ha valori che questa versione non può usare.", "shortcut.json_error": "i parametri devono essere in formato JSON: {error}", "shortcut.no_command": "nessun comando `{id}`; il testo prima del JSON deve essere un ID comando", "shortcut.pin": "Fissa in cima al riquadro S", @@ -3450,8 +3925,10 @@ "sketch_text.align_right": "Destra", "sketch_text.bold": "Grassetto", "sketch_text.builtin_font": "{family} (integrato)", + "sketch_text.formula": "Inizia con = per costruire le parole dai parametri: ='W' + number(Width)", "sketch_text.italic": "Corsivo", "sketch_text.loading_fonts": "Ricerca dei caratteri installati…", + "sketch_text.no_bold": "Il carattere integrato non ha il grassetto: scegli un carattere installato", "sketch_text.on_path": "Il testo segue il percorso: la curva ne determina la posizione", "sketch_text.path_clear": "Scollega il testo dalla curva", "sketch_text.path_hint": "Una curva dello schizzo seguita dal testo: fai clic qui, poi sulla curva", @@ -3483,10 +3960,7 @@ "the two origins are on the same component": "le due origini sono sullo stesso componente", "thread.automatic_size": "Dimensione automatica", "thread.designation": "Designazione", - "thread.direction": "Verso del filetto", "thread.iso_metric": "Metrica ISO", - "thread.left_hand": "Sinistro", - "thread.right_hand": "Destro", "thread.select_size": "Seleziona dimensione", "timeline.delete_after_marker_one": "Elimina 1 lavorazione dopo il marcatore della cronologia", "timeline.delete_after_marker_other": "Elimina {count} lavorazioni dopo il marcatore della cronologia", @@ -3503,8 +3977,10 @@ "timeline.move_to_group": "Sposta lavorazioni nella cartella", "timeline.rename_group": "Rinomina cartella di lavorazioni", "timeline.reorder_many": "Riordina lavorazioni", + "timeline.suppress_features": "Sospendi lavorazioni", "timeline.suppress_folders_tip": "Sospendi o riattiva ogni lavorazione nelle cartelle e nelle cartelle annidate", "timeline.ungroup": "Rimuovi cartelle di lavorazioni", + "timeline.unsuppress_features": "Riattiva lavorazioni", "to the face": "alla faccia", "to the next face": "fino alla faccia successiva", "toolbar.customize_note": "Scheda {tab}. Seleziona un comando per assegnargli un pulsante nella barra degli strumenti. Puoi anche trascinare una riga dal menu a discesa di un pannello sulla barra, trascinare un pulsante fuori dalla barra per rimuoverlo o usare la puntina di una riga del menu a discesa.", @@ -3588,6 +4064,8 @@ "ui.3d_mouse_section": "Mouse 3D", "ui.3d_mouse_show_in_view": "Mostra il mouse 3D nella vista 3D", "ui.3d_mouse_show_in_view_tip": "Un'immagine del tuo mouse 3D nell'angolo in basso a sinistra, che si muove quando lo muovi.", + "ui.3d_mouse_sketch_orbit": "Ruota gli schizzi con il mouse 3D", + "ui.3d_mouse_sketch_orbit_tip": "Il mouse 3D ruota la vista anche mentre uno schizzo è aperto e visto frontalmente, come può fare il mouse. Disattivato: sposta e ingrandisce lo schizzo finché non inclini la vista.", "ui.3d_mouse_skip": "Il mio dispositivo non può farlo", "ui.3d_mouse_skip_tip": "Salta questo movimento in entrambi i versi; la calibrazione lo esclude.", "ui.3d_mouse_speed": "Velocità del mouse 3D", @@ -3616,6 +4094,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Ruota la manopola in senso antiorario, tienila, poi lasciala.", "ui.3d_mouse_switch_cap": "Calibra come ritorno al centro", "ui.3d_mouse_switch_trackball": "Calibra come trackball", + "ui.3d_mouse_use_direct": "Usa driver diretto", + "ui.3d_mouse_use_direct_tip": "Leggi il mouse 3D direttamente (hidraw) invece che tramite spacenavd.", "ui.3d_mouse_view_axis": "Asse della vista", "ui.3d_mouse_view_off": "Disattivato", "ui.3d_mouse_view_off_tip": "Il profilo del driver del mouse 3D disattiva questo asse, quindi il suo movimento non muove la vista. Se qui scegli il movimento di un altro asse, i due si scambiano e quel movimento smette di muovere la vista.", @@ -3654,6 +4134,8 @@ "ui.agent_chat_auth_terminal": "Esegui questo comando in un terminale, poi premi di nuovo Connetti:", "ui.agent_chat_auth_title": "Accedi all'agente", "ui.agent_chat_cancel": "Annulla", + "ui.agent_chat_cancel_timeout": "L'agente non ha risposto ad Arresta ed è stato disconnesso. Riconnetti per continuare.", + "ui.agent_chat_cannot_start": "Installato, ma non si avvia: {error}", "ui.agent_chat_changes": "Modifiche: {n}, un solo passo di annullamento", "ui.agent_chat_changes_n": "{n} modifiche", "ui.agent_chat_changes_of": "{n}/{limit} modifiche", @@ -3662,11 +4144,13 @@ "ui.agent_chat_command": "Comando dell'agente", "ui.agent_chat_connect": "Connetti", "ui.agent_chat_copy": "Copia", + "ui.agent_chat_copy_message": "Copia messaggio", "ui.agent_chat_ctx_bodies": "Corpi", "ui.agent_chat_ctx_elements": "Elementi", "ui.agent_chat_ctx_features": "Lavorazioni", "ui.agent_chat_ctx_more": "+{n} altri", "ui.agent_chat_ctx_other": "Altro", + "ui.agent_chat_custom_heading": "Modello personalizzato", "ui.agent_chat_custom_hint": "Qualsiasi programma che comunica tramite Agent Client Protocol su stdin e stdout. Non viene eseguito da una shell.", "ui.agent_chat_denied": "Negato", "ui.agent_chat_deny": "Nega", @@ -3710,8 +4194,16 @@ "ui.agent_chat_mode_all": "Tutto", "ui.agent_chat_mode_ask": "Chiedi", "ui.agent_chat_mode_edits": "Modifiche", + "ui.agent_chat_model_custom": "Usa personalizzato: {model}", "ui.agent_chat_model_no_tools": "{model} non può usare gli strumenti di SolidCraft, quindi può solo chattare. Scegli un modello con supporto per gli strumenti.", + "ui.agent_chat_model_rejected": "L'agente non ha accettato {model}: {error}", + "ui.agent_chat_model_search": "Cerca modelli…", "ui.agent_chat_model_tip": "Il modello usato dall'agente. La scelta viene memorizzata per questo agente.", + "ui.agent_chat_models_failed": "Impossibile elencare i modelli: {error}", + "ui.agent_chat_models_heading": "Modelli disponibili", + "ui.agent_chat_models_listing": "Elenco dei modelli in corso…", + "ui.agent_chat_models_none": "L'endpoint non elenca alcun modello", + "ui.agent_chat_models_not_a_list": "La risposta non era un elenco di modelli", "ui.agent_chat_new": "Nuova chat", "ui.agent_chat_new_confirm": "Avviare una nuova chat? Quella corrente verrà cancellata.", "ui.agent_chat_next_picture": "Immagine successiva", @@ -3746,9 +4238,12 @@ "ui.agent_chat_queued_stopped": "In coda (arrestato, non inviato)", "ui.agent_chat_refresh": "Aggiorna", "ui.agent_chat_refused": "Non consentito all'agente: {reason}", + "ui.agent_chat_reinstall": "{agent} è installato ({program}), ma non si è avviato quando SolidCraft lo ha controllato: {error}\nLa sua installazione potrebbe essere incompleta o creata per un altro tipo di computer. Installalo di nuovo con `{install}`, verifica in un terminale che stampi la sua versione, poi premi Aggiorna.", "ui.agent_chat_remove": "Rimuovi dalla coda", "ui.agent_chat_remove_file": "Rimuovi da questo messaggio", "ui.agent_chat_remove_imported": "Rimuovi da questo messaggio; la parte resta nel progetto (Annulla la rimuove)", + "ui.agent_chat_reply_cut_off": "La risposta ha raggiunto il limite di lunghezza prima di terminare, quindi potrebbe essere incompleta. Chiedi all'agente di proseguire, oppure di dare una risposta più breve.", + "ui.agent_chat_reply_declined": "Il modello ha rifiutato di rispondere a questo messaggio.", "ui.agent_chat_retry": "Riprova", "ui.agent_chat_right": "Destra", "ui.agent_chat_save": "Salva", @@ -3807,12 +4302,17 @@ "ui.ai_copy_suffix": "copia", "ui.ai_custom_url": "URL personalizzato", "ui.ai_default": "Predefinito", + "ui.ai_edit": "Modifica", + "ui.ai_edit_agent_title": "Modifica agente", + "ui.ai_edit_gone": "Questo agente è stato rimosso, quindi non c'è nulla da salvare.", + "ui.ai_edit_tip": "Cambia il nome, il comando o l'endpoint di questo agente. Una chiave salvata resta nascosta.", "ui.ai_http_busy": "l'endpoint è occupato o ha superato il limite; riprova più tardi", "ui.ai_http_key": "l'endpoint ha rifiutato la chiave: controllala in Preferenze > IA", "ui.ai_http_not_found": "endpoint o modello inesistente: controlla l'URL di base e il nome del modello", "ui.ai_http_too_large": "la conversazione è troppo grande per questo endpoint; inizia una nuova chat", "ui.ai_key": "Chiave API", "ui.ai_key_hint": "facoltativa; conservata nel portachiavi di sistema", + "ui.ai_key_keep_hint": "lascia vuoto per mantenere la chiave salvata", "ui.ai_key_needs_https": "La chiave viene inviata solo tramite HTTPS o a questo computer.", "ui.ai_key_note": "Memorizzata nel portachiavi di sistema, mai nelle impostazioni di SolidCraft. Lascia vuoto per un server locale.", "ui.ai_keychain_error": "Il portachiavi di sistema ha rifiutato l'operazione: {error}", @@ -3839,11 +4339,15 @@ "ui.ai_permissions": "Autorizzazioni", "ui.ai_preset": "Preimpostazione", "ui.ai_protocol": "Protocollo", + "ui.ai_reasoning_effort": "Livello di ragionamento", + "ui.ai_reasoning_effort_field_hint": "vuoto = predefinito del provider", + "ui.ai_reasoning_effort_hint": "Facoltativo. Inviato all'endpoint come `reasoning_effort`; i valori accettati differiscono da provider a provider (ad esempio `low`, `high` o `max`). Un valore impostato qui non viene mai sostituito da SolidCraft. Lascia vuoto per non inviare nulla e mantenere il valore predefinito del provider.", "ui.ai_remove": "Rimuovi", "ui.ai_request_timed_out": "Il modello ha impiegato più di {seconds} s. Puoi aumentare il timeout della richiesta per questo endpoint in Preferenze › Assistente.", "ui.ai_request_timeout": "Timeout della richiesta", "ui.ai_request_timeout_hint": "Quanto può durare una richiesta al modello verso questo endpoint, da 30 s a un'ora. Aumentalo per un modello locale lento.", "ui.ai_reset": "Reimposta", + "ui.ai_save": "Salva", "ui.ai_settings": "Impostazioni IA…", "ui.ai_show_features": "Mostra funzioni IA", "ui.ai_show_features_note": "La chat con l'agente: un pannello in cui un agente di programmazione che già usi o un endpoint di modello a tua scelta opera sul progetto aperto. Se disattivata: nessun pulsante IA, scorciatoia, voce di menu o pannello, e nessuna ricerca o avvio.", @@ -3922,6 +4426,8 @@ "ui.cancel": "Annulla", "ui.canvases": "Immagini di riferimento", "ui.center": "Centro", + "ui.center_arc_follows_cursor": "L'arco per centro segue la direzione del cursore", + "ui.center_arc_follows_cursor_tip": "Un arco per centro procede in senso orario o antiorario a seconda di come il cursore gira attorno al suo centro. Disattivato: sempre in senso antiorario dall'inizio.", "ui.centerline": "Linea d'asse", "ui.chain": "Catena", "ui.chamfer": "Smusso", @@ -3930,6 +4436,7 @@ "ui.circle": "Cerchio", "ui.circular_pattern": "Ripetizione circolare", "ui.clear": "Cancella", + "ui.clear_print_face": "Rimuovi faccia di stampa", "ui.clear_recent": "Cancella recenti", "ui.clear_the_selection": "Deseleziona tutto", "ui.click_selects_whole_bodies": "Il clic seleziona corpi interi", @@ -3964,12 +4471,27 @@ "ui.constant": "Costante", "ui.constraints_conflict": "Vincoli in conflitto", "ui.construction": "Costruzione", + "ui.construction.angle_hint": "Retta di costruzione: fai clic su un punto, poi digita un angolo o seleziona una direzione", + "ui.construction.bisector_hint": "Bisettrice: seleziona due linee rette che si intersecano, poi la soluzione desiderata", + "ui.construction.common_hint": "Tangente comune: seleziona due cerchi/archi, poi la soluzione desiderata", + "ui.construction.contact_hint": "Tangente: seleziona un cerchio/arco o una spline/conica aperta, poi il punto di contatto (curve a forma libera: estremi)", + "ui.construction.external_hint": "Tangente: seleziona un cerchio o un arco, un punto esterno, poi la soluzione desiderata", + "ui.construction.free_hint": "Retta di costruzione: fai clic su due punti; clic destro per ricominciare", + "ui.construction.normal_needs_length": "Una retta infinita è sempre di costruzione: digita una lunghezza per disegnare una linea normale", + "ui.construction.point_hint": "Retta di costruzione: fai clic sul punto di passaggio", + "ui.construction.reference_hint": "Retta di costruzione: seleziona una linea retta, poi un punto; clic destro per cambiare il riferimento", "ui.construction.ribbon_label": "Linee aus.", + "ui.construction.side_hint": "Retta di costruzione: fai clic sul lato verso cui prosegue la retta; clic destro per ricominciare", "ui.context_menu": "Menu contestuale", + "ui.continuity_crease": "Spigolo vivo", + "ui.continuity_curvature": "Curvatura", + "ui.continuity_curvature_change": "Variazione di curvatura", "ui.continuity_g0": "G0 spigolo vivo", "ui.continuity_g1": "G1 tangenza", "ui.continuity_g2": "G2 curvatura", "ui.continuity_gap": "Gioco", + "ui.continuity_position": "Posizione", + "ui.continuity_tangent": "Tangente", "ui.copy": "Copia", "ui.corner": "Angolo", "ui.corners": "Angoli", @@ -3992,6 +4514,7 @@ "ui.dark": "Scuro", "ui.default_modelling_orientation": "Orientamento di modellazione predefinito", "ui.delete": "Elimina", + "ui.delete_select_first": "Seleziona prima cosa eliminare: lavorazioni, corpi, componenti o geometria dello schizzo", "ui.depth": "Profondità", "ui.design": "Progettazione", "ui.design_properties.author": "Autore", @@ -4006,6 +4529,40 @@ "ui.design_properties.project": "Progetto", "ui.design_properties.revision": "Revisione", "ui.design_saved": "Salvato in {path}", + "ui.details_access_caption": "Le facce indicano se un utensile può raggiungerle dalla direzione scelta.", + "ui.details_angle": "Angolo", + "ui.details_continuity_caption": "Modifica la giunzione selezionata. Le altre giunzioni mantengono le proprie impostazioni.", + "ui.details_continuity_stale": "Geometria precedente: ripeti l'analisi per modificare o inquadrare questa giunzione.", + "ui.details_copy_list": "Copia elenco", + "ui.details_curvature": "Tolleranza di curvatura", + "ui.details_curvature_caption": "Le facce sono colorate in base al loro raggio di curvatura locale.", + "ui.details_direction": "Direzione dell'utensile", + "ui.details_draft_caption": "Le facce sono colorate in base al loro angolo rispetto alla direzione di estrazione.", + "ui.details_edit_seam": "Modifica giunzione", + "ui.details_fixture": "Esempio di componente — solo dati di prova", + "ui.details_fixture_caption": "Esempio di componente con valori illustrativi; non è un risultato del modello.", + "ui.details_fixture_problem": "Esempio di rilevamento con un problema", + "ui.details_fixture_readout": "Esempio di valore misurato", + "ui.details_flip": "Inverti", + "ui.details_gap": "Gioco", + "ui.details_hatch": "Tratteggia le facce tagliate", + "ui.details_jump": "Salto di curvatura", + "ui.details_key": "Legenda", + "ui.details_offset": "Offset", + "ui.details_plane": "Piano", + "ui.details_pull": "Direzione di estrazione", + "ui.details_radius": "Raggio", + "ui.details_readout": "Lettura", + "ui.details_samples": "Campioni", + "ui.details_seam": "{body} · Spigolo {edge}", + "ui.details_settings": "Impostazioni", + "ui.details_sharp_gap": "Spigolo vivo o gioco", + "ui.details_show_all": "Mostra tutti ({count})", + "ui.details_smooth": "Liscia", + "ui.details_stripes": "Strisce", + "ui.details_target": "Inquadra la geometria", + "ui.details_worst_seams": "Giunzioni peggiori", + "ui.details_zebra_caption": "Le strisce riflesse mostrano quanto dolcemente si raccordano le facce.", "ui.diameter": "Diametro", "ui.dimension": "Quota", "ui.direct_interaction": "Interazione diretta", @@ -4050,6 +4607,7 @@ "ui.edit_in_place_saved_elsewhere": "La parte è stata salvata in un altro file; l'assieme è ancora collegato a {name}", "ui.edit_in_place_wait": "Attendi il termine di ciò che è in esecuzione nel progetto", "ui.edit_section_analysis": "Modifica analisi in sezione", + "ui.edit_sketch_empty": "Nessuno schizzo da modificare", "ui.ellipse": "Ellisse", "ui.emboss_wrap_note": "I profili di linee ortogonali tangenti a un cilindro supportato si avvolgono automaticamente. Scegliere una parete per definire la destinazione.", "ui.end_radius": "Raggio finale", @@ -4060,12 +4618,15 @@ "ui.equation_explicit": "Esplicita", "ui.equation_form": "Forma", "ui.equation_note": "La variabile è un numero puro: sin(t) la interpreta in radianti. Un risultato senza unità è nell'unità del progetto.", + "ui.equation_note_range": "La variabile è una lunghezza, come il suo intervallo: combinala con parametri di lunghezza e dividila per una lunghezza per sin(). Un risultato senza unità è nell'unità del progetto.", "ui.equation_parametric": "Parametrica", + "ui.equation_variable_unit": "La variabile ha l'unità dell'intervallo", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Raggio equivalente", "ui.expand": "Espandi", + "ui.explode_needs_two_components": "Vista esplosa allontana i componenti tra loro, quindi il progetto ne richiede due o più (Nuovo componente, Inserisci progetto o Crea componenti da corpi)", "ui.exportDxf": "Esporta DXF…", "ui.export_ellipsis_keymap": "Esporta…", "ui.export_keymap_tip": "Tasti, preferiti del riquadro S e barra degli strumenti, in un file", @@ -4191,6 +4752,7 @@ "ui.hideOrigin": "Nascondi origine", "ui.hidePlanes": "Nascondi piani", "ui.hideProfile": "Nascondi profilo", + "ui.hide_component_history": "Nascondi la sua cronologia", "ui.hide_origin_by_default": "Nascondi l'origine per impostazione predefinita", "ui.hide_origin_note": "I nuovi progetti partono con la cartella Origine nascosta. Un progetto conserva la propria impostazione dell'origine dopo che l'hai mostrata o nascosta.", "ui.history_back": "Indietro di un passaggio", @@ -4198,6 +4760,7 @@ "ui.history_edge_hint": "fai doppio clic sullo spigolo", "ui.history_first": "Vai all’inizio", "ui.history_forward": "Avanti di un passaggio", + "ui.history_hide_hidden": "Nascondi componenti nascosti", "ui.history_hide_names": "Nascondi i nomi", "ui.history_last": "Vai alla fine", "ui.history_marker_tip": "Marcatore della cronologia: trascinalo per far tornare indietro il modello; le nuove lavorazioni vanno qui", @@ -4207,10 +4770,12 @@ "ui.history_play_button_show": "Mostra pulsante Riproduci", "ui.history_play_finish_action": "Termina l'azione corrente prima di riprodurre la cronologia", "ui.history_play_roll_back": "Sposta indietro il marcatore della cronologia prima di riprodurre", + "ui.history_show_hidden": "Mostra componenti nascosti", "ui.history_show_names": "Mostra nomi", "ui.history_sketch_listed_under": "Elencato sotto {feature}", "ui.history_title": "Cronologia", "ui.history_toggle_names": "Mostra o nascondi i nomi delle lavorazioni", + "ui.history_waits_for_editor": "Annulla, Ripeti e Cronologia restano in attesa finché l'editor della lavorazione non si è aperto", "ui.hole": "Foro", "ui.hole_tap_type": "Tipo di maschiatura del foro", "ui.hole_type": "Tipo di foro", @@ -4226,6 +4791,7 @@ "ui.insert_design.saved_file": "{name} contiene modifiche non salvate, quindi è stato inserito il file salvato. Salvalo, poi usa Aggiorna collegamenti per includere le modifiche.", "ui.insert_design.unsaved": "Modifiche non salvate", "ui.inspect": "Esamina", + "ui.instances": "Istanze", "ui.intersect": "Interseca", "ui.isolate": "Isola", "ui.join": "Unisci", @@ -4234,12 +4800,14 @@ "ui.joints": "Giunti", "ui.keyboard_shortcuts": "Scorciatoie da tastiera", "ui.language": "Lingua", + "ui.lasso_select": "Lazo (trascina un anello a mano libera: prende ciò che sta interamente all'interno)", "ui.layout_compact": "Compatta", "ui.layout_floating": "Flottante", "ui.length": "Lunghezza", "ui.length_decimals": "Decimali delle lunghezze", "ui.light": "Chiaro", "ui.line": "Linea", + "ui.line_arc_hint": "Arco tangente: fai clic sulla fine dell'arco. Fermati di nuovo sull'ultimo punto per tornare alle linee; clic destro o Esc per terminare", "ui.link_copies": "Collega copie identiche", "ui.link_copies_keep": "Mantieni", "ui.link_copies_link": "Collega", @@ -4328,6 +4896,7 @@ "ui.part_size_shared": "Ricostruisce la parte, sostituendo le eventuali lavorazioni aggiunte. Si aggiornano tutte le occorrenze del componente.", "ui.paste": "Incolla", "ui.path": "Percorso", + "ui.pattern_object_type_tip": "Corpi: forme solide, selezionate nella vista o nella Struttura; ciascuno viene copiato per intero.\nLavorazioni: passaggi della Cronologia, come un'estrusione o un foro, selezionati nella Cronologia o su una faccia da essi creata; il passaggio viene ripetuto.\nUno schizzo non è nessuno dei due: ripeti le sue curve con Ripetizione o Specchia dello schizzo stesso, oppure estrudilo prima.", "ui.pattern_on_path": "Ripetizione su percorso", "ui.perforate_margin_default": "dal diametro", "ui.perforate_pitch": "Passo", @@ -4354,12 +4923,17 @@ "ui.plugins_skipped": "Impossibile leggere {count} cartelle.", "ui.plugins_version": "{version}", "ui.point": "Punto", + "ui.point_cloud_add_filter": "Aggiungi filtro…", "ui.point_cloud_auto_range": "Intervallo automatico", "ui.point_cloud_color_by": "Colora per", "ui.point_cloud_file_colors": "Colori del file", + "ui.point_cloud_filter_by": "Filtra per", "ui.point_cloud_height_high": "Più alto", "ui.point_cloud_height_low": "Più basso", + "ui.point_cloud_legend_filter": "Mostrati e nascosti nella legenda sopra", "ui.point_cloud_no_file_colors": "Il file non contiene colori", + "ui.point_cloud_pause": "Pausa", + "ui.point_cloud_play": "Riproduci", "ui.point_cloud_single_color": "Colore singolo", "ui.point_cloud_size": "Dimensione dei punti", "ui.point_cloud_units": "Unità del file", @@ -4368,6 +4942,11 @@ "ui.polygon": "Poligono", "ui.preferences": "Preferenze", "ui.press_a_key": "premi un tasto…", + "ui.print_face_body_not_sent": "Il corpo di quella faccia non viene inviato: aggiungilo prima a Corpi", + "ui.print_face_cleared": "{body}: faccia di stampa rimossa", + "ui.print_face_input": "Faccia di stampa", + "ui.print_face_pick": "Seleziona una faccia piana di un corpo solido per renderla la faccia di stampa", + "ui.print_face_set": "{body}: faccia di stampa impostata; Invia allo slicer appoggia il corpo su di essa", "ui.profile": "Profilo", "ui.profile_plane": "Piano del profilo", "ui.profiles": "Profili", @@ -4383,6 +4962,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Misurazione…", + "ui.properties.measuring_bodies": "Misurazione… {done} di {total} corpi", "ui.properties.measuring_failed": "La misurazione si è interrotta prima del termine.", "ui.properties.principal_axis": "Asse principale {number}", "ui.properties.principal_moments": "Momenti principali", @@ -4431,6 +5011,7 @@ "ui.revolve": "Rivoluzione", "ui.ribbon_exit": "Esci", "ui.ribbon_labels": "Mostra il testo sotto le icone della barra multifunzione", + "ui.ribbon_menus_skip_pinned": "Escludi i comandi fissati dai menu a discesa", "ui.ribbon_pin_footer": "I comandi fissati compaiono sulla barra multifunzione. Passa sopra una riga per fissarla o rimuoverla.", "ui.ribbon_workspace": "Area di lavoro", "ui.right": "Destra", @@ -4449,6 +5030,7 @@ "ui.selectOther": "Seleziona altro…", "ui.selectTangentChain": "Seleziona catena tangente", "ui.select_all": "Seleziona tutto", + "ui.select_components_by_face": "Seleziona componenti (una faccia seleziona il suo componente)", "ui.selection": "Selezione", "ui.selection_modifiers": "Modificatori di selezione", "ui.selection_shift_add_only": "Maiusc+clic aggiunge senza rimuovere", @@ -4474,6 +5056,7 @@ "ui.showDimension": "Mostra quota", "ui.showOrigin": "Mostra origine", "ui.showPlanes": "Mostra piani", + "ui.show_component_history": "Mostra la sua cronologia", "ui.show_constraints": "Vincoli", "ui.show_construction_geometries": "Geometrie di costruzione", "ui.show_dimensions": "Quote", @@ -4490,6 +5073,11 @@ "ui.sketch_intersect_selection_filter": "Filtro di selezione", "ui.sketch_modifiers": "Modificatori dello schizzo", "ui.sketch_project_geometry": "Geometria", + "ui.sketch_report.all_constrained": "Tutto è completamente vincolato.", + "ui.sketch_report.dof": "Gradi di libertà", + "ui.sketch_report.loose": "Non completamente vincolato", + "ui.sketch_report.status": "Stato", + "ui.sketch_report.title": "Rapporto dello schizzo", "ui.sketch_scale": "Scala schizzo", "ui.sketches": "Schizzi", "ui.slice": "Genera sezioni", @@ -4585,19 +5173,31 @@ "ui.view_angles": "Angoli della vista", "ui.view_angles_convention": "Gradi attorno all'asse verticale. Imbardata 0° è la vista frontale, 90° sinistra, −90° destra, 180° posteriore; beccheggio 90° è la vista dall'alto; un rollio positivo ruota il modello in senso orario.", "ui.view_angles_help": "Mostra il beccheggio, l'imbardata e il rollio della vista in gradi e la sua proiezione sotto il gizmo di orientamento. Fai clic sull'indicatore per digitare angoli esatti.", + "ui.view_angles_lock": "Blocca {axis}", "ui.view_angles_ortho": "Ortogonale", "ui.view_angles_persp": "Prospettica", "ui.view_angles_pitch": "Beccheggio", "ui.view_angles_readout": "Beccheggio {pitch} · Imbardata {yaw} · Rollio {roll}", "ui.view_angles_roll": "Rollio", + "ui.view_angles_unlock": "Sblocca {axis}", "ui.view_angles_yaw": "Imbardata", + "ui.view_angles_zero": "Imposta {axis} a 0°", "ui.view_centre": "Centro della vista", "ui.viewport_status_clear": "Disattiva {name}", "ui.viewport_status_clear_hint": "Disattiva {name} · Esc", + "ui.viewport_status_edges": "{count} spigoli", + "ui.viewport_status_from": "da {direction}", "ui.viewport_status_key": "Mostra la legenda di {name}", "ui.viewport_status_minimum_radius": "Raggio minimo", "ui.viewport_status_pairs": "{count} coppie", + "ui.viewport_status_section_hatch": "{setting} · tratteggio", + "ui.viewport_status_section_plane": "Piano attuale", + "ui.viewport_status_section_tilted": "inclinato · {offset}", "ui.viewport_status_stripes": "{count} strisce", + "ui.viewport_status_summary_clear": "Disattiva tutto", + "ui.viewport_status_summary_heading": "In questa vista", + "ui.viewport_status_summary_label": "{name} e altri {count} elementi", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Segui il tema", "ui.visual_shaded_hidden_edges": "Ombreggiato con spigoli nascosti", "ui.visual_shaded_with_edges": "Ombreggiato con spigoli", @@ -4634,10 +5234,12 @@ "update.button": "Aggiorna", "update.button_version": "Aggiorna a {version}", "update.check_automatically": "Controlla automaticamente gli aggiornamenti", + "update.check_for_updates": "Verifica aggiornamenti", "update.check_now": "Controlla ora", + "update.check_unavailable": "La verifica degli aggiornamenti non è disponibile per questa installazione.", "update.checking": "Controllo…", "update.copy": "Copia", - "update.dmg_opened": "L'immagine disco è aperta e verificata: trascina SolidCraft in Applicazioni sostituendo la copia precedente, poi riavvia SolidCraft.", + "update.dmg_opened": "L'immagine disco è aperta e verificata: esci da SolidCraft, trascina il nuovo SolidCraft in Applicazioni sostituendo la copia precedente, poi riapri SolidCraft.", "update.download": "Scarica", "update.download_open": "Scarica e apri", "update.downloading": "Download e verifica… {done} di {total} MB", @@ -4648,11 +5250,13 @@ "update.installed": "SolidCraft {version} è installato. Riavvia per usarlo.", "update.installer_started": "Il programma di installazione si avvia alla chiusura di SolidCraft.", "update.later": "Ricordamelo più tardi", + "update.managed": "Aggiornamento disponibile: aggiorna SolidCraft in {manager}", "update.no_notes": "Questa versione non contiene note.", "update.package_hint": "Questa copia proviene da un {kind}. Scarica il nuovo pacchetto, poi installalo con:", "update.prefs_dev": "Questa è una build di sviluppo ({version}): non controlla gli aggiornamenti.", "update.prefs_flatpak": "Questa copia ({version}) viene aggiornata da Flatpak: esegui {command} o usa il centro software. SolidCraft non effettua controlli.", "update.prefs_label": "Aggiornamenti", + "update.prefs_managed": "Questa è la versione SolidCraft {version}, gestita da {manager}. Il controllo richiede a GitHub l'ultima versione e non invia altri dati; aggiorna SolidCraft in {manager}.", "update.prefs_note": "Questa è la versione SolidCraft {version} ({kind}). Il controllo richiede a GitHub l'ultima versione e non invia altri dati.", "update.prefs_web": "Ricarica la pagina per ottenere l'ultima versione dell'app web. Se la rete non è disponibile o l'aggiornamento non riesce a finire il download in tempo, si apre invece la versione salvata; un download in corso continua per il prossimo ricaricamento.", "update.refresh_checking": "Ricerca della versione più recente…", @@ -4679,6 +5283,7 @@ "web.open_link": "Aprire il progetto collegato?", "web.open_link_confirm": "Ci sono modifiche non salvate. Aprire il progetto collegato in una nuova scheda?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ scegli · Invio / Tab completa · Esc chiudi", + "↑ ↓ choose · Enter applies this value": "↑ ↓ scegli · Enter applica questo valore", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ scegli · Enter applica quanto digitato · Esc chiudi", "⌘Enter continues on GitHub.": "⌘Enter continua su GitHub." } diff --git a/assets/locales/ja.json b/assets/locales/ja.json index aad655b32..d08cbca65 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "ブレンドサーフェス", "BOUNDARY SURFACE": "境界サーフェス", "BROWSER": "ブラウザ", + "Back to the original order": "元の順序に戻す", "Ball": "ボール", "Bar": "平鋼", "Base Center": "底面の中心", @@ -378,7 +379,7 @@ "Move Type": "移動タイプ", "Move down": "下へ移動", "Move earlier": "前へ移動", - "Move holes by clicking or dragging": "クリックやドラッグで穴を移動", + "Move holes by clicking or dragging": "クリックまたはドラッグで移動", "Move later": "後へ移動", "Move up": "上へ移動", "Name": "名前", @@ -476,6 +477,7 @@ "Rectangular": "長方形", "Rectangular Tube": "角形鋼管", "Reference face": "参照面", + "Reference plane": "参照平面", "Relief Depth": "リリーフ深さ", "Relief Width": "リリーフ幅", "Remove Tools": "ツールボディを削除", @@ -493,7 +495,8 @@ "Rename Folder": "フォルダーの名前を変更", "Render Stage": "レンダリング段階", "Reopen designs": "デザインを再度開く", - "Reopen the designs that were open when SolidCraft was last closed": "前回 SolidCraft を閉じたときに開いていたデザインを再度開く", + "Reopen the designs that were open when SolidCraft was last closed": "前回開いていたデザインを再び開く", + "Repair Part": "パーツを修復", "Replace existing library file": "既存のライブラリファイルを置き換える", "Report a bug — review a screenshot and open a GitHub draft": "バグを報告 — スクリーンショットを確認してGitHub下書きを作成", "Report copied. Keep this text to submit on GitHub when you are online.": "レポートをコピーしました。このテキストを保存し、オンラインになったらGitHubで送信してください。", @@ -555,6 +558,7 @@ "Section": "断面", "Section (optional)": "断面(任意)", "Section position": "断面の位置", + "Sections": "セクション", "Sections (one sketch each)": "セクション (各1スケッチ)", "Select Other": "その他を選択", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。", @@ -581,7 +585,7 @@ "Show ghost": "ゴーストを表示", "Show in folder": "フォルダに表示", "Show the pointer an AI agent moves (#35)": "エージェントが操作するポインターを表示 (#35)", - "Show tool at cursor": "カーソルの横にツールを表示", + "Show tool at cursor": "カーソル位置にツールを表示", "Signed axes": "符号付き座標軸", "Size": "サイズ", "Sketch constraints": "スケッチ拘束", @@ -592,9 +596,11 @@ "Sketch points": "スケッチ点", "Slider": "スライダ", "Slot width": "長穴の幅", - "Snap to face and edge centres": "面とエッジの中心にスナップ", + "Snap to face and edge centres": "中心にスナップ", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraftからレポートを直接送信することはできません。GitHubで送信してください。アプリにトークンは必要ありません。", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "これらのデザインが保存される前にSolidCraftが終了しました。最後の自動保存ファイルを開くことができます。", + "Sort A to Z": "昇順で並べ替え", + "Sort Z to A": "降順で並べ替え", "Spacing 2 must be a non-zero number": "間隔 2は0以外の数値にしてください", "Spacing must be a non-zero number": "間隔は0以外の数値にしてください", "Specialise": "特殊操作", @@ -733,34 +739,34 @@ "a picked edge's body is gone": "選択したエッジのボディが存在しなくなりました", "add a key for a joint first": "先にジョイントのキーを追加してください", "ai.connected_toast": "SolidCraft が {clients} で使えるようになりました。使うには再起動してください(設定 > アシスタント)。", - "ai.prefs.allow_control": "AI エージェントの接続を許可(コントロールチャンネル / MCP)", - "ai.prefs.allow_control_note": "このコンピューター内だけのコントロールチャンネル(127.0.0.1、ポート 27878 または次に空いているポート)を開きます。接続するプログラムは、起動のたびに作られ、あなたのユーザーアカウントだけが読める秘密のトークンも提示する必要があります。次に SolidCraft を起動したときから有効です。オフ:--control を付けて起動しない限り、何も待ち受けません。", - "ai.prefs.availability": "アシスタントの操作", - "ai.prefs.background_commands": "エージェントのコマンドをバックグラウンドで実行", - "ai.prefs.connect_apps": "このコンピューターの AI アプリで SolidCraft を使えるようにする", - "ai.prefs.connect_apps_note": "SolidCraft の起動時に、このコンピューターで見つかった AI アプリ(OpenCode、Claude Desktop、Claude Code、Cursor、Codex、Gemini CLI、Copilot CLI、Windsurf、Zed、VS Code)へ MCP サーバーとして追加します。追加または更新するのは solidcraft のエントリのみで、変更済みのエントリには触れず、ファイルは先にバックアップされます。オフにすると追加したエントリを削除します。", - "ai.prefs.connect_at_start": "SolidCraft の起動時に前回使用したエージェントに接続", + "ai.prefs.allow_control": "AIエージェントの接続を許可", + "ai.prefs.allow_control_note": "ローカルチャネル(MCP)です。このコンピューターから外には何も送信しません。\n\nこのコンピューター内だけのコントロールチャンネル(127.0.0.1、ポート 27878 または次に空いているポート)を開きます。接続するプログラムは、起動のたびに作られ、あなたのユーザーアカウントだけが読める秘密のトークンも提示する必要があります。次に SolidCraft を起動したときから有効です。オフ:--control を付けて起動しない限り、何も待ち受けません。", + "ai.prefs.availability": "利用設定", + "ai.prefs.background_commands": "時間のかかるコマンドをバックグラウンドで実行", + "ai.prefs.connect_apps": "SolidCraftをAIアプリに追加", + "ai.prefs.connect_apps_note": "オフにすると追加した項目を削除します。\n\nSolidCraft の起動時に、このコンピューターで見つかった AI アプリ(OpenCode、Claude Desktop、Claude Code、Cursor、Codex、Gemini CLI、Copilot CLI、Windsurf、Zed、VS Code)へ MCP サーバーとして追加します。追加または更新するのは solidcraft のエントリのみで、変更済みのエントリには触れず、ファイルは先にバックアップされます。オフにすると追加したエントリを削除します。", + "ai.prefs.connect_at_start": "起動時に前回のエージェントに接続", "ai.prefs.connect_at_start_note": "SolidCraft を起動するたびに、前回接続したエージェント (またはデフォルトのエージェント) をバックグラウンドで起動し、すぐにチャットできるようにします。--control を付けて起動した場合は行いません。接続できない場合、アシスタントに「接続に失敗しました」と「再試行」ボタンが表示されます。", - "ai.prefs.follow_camera": "カメラをスケッチに向ける", + "ai.prefs.follow_camera": "カメラを追従", "ai.prefs.follow_camera_off": "カメラの自動追従はオフです。", "ai.prefs.follow_camera_on": "エージェントが作成するスケッチにカメラを向けます。", - "ai.prefs.intro": "エージェント、権限、作業の表示方法を設定します。", + "ai.prefs.intro": "SolidCraftのAIエージェント。", "ai.prefs.make_default": "既定にする", "ai.prefs.no_agents": "エージェントはまだありません。追加するか、更新してインストール済みのエージェントを検索してください。", "ai.prefs.no_saved_approvals": "保存された許可はありません。", - "ai.prefs.open_at_start": "SolidCraft の起動時にアシスタントパネルを開く", + "ai.prefs.open_at_start": "起動時にチャットを開く", "ai.prefs.open_at_start_note": "SolidCraft を起動するたびにアシスタントパネル (または独立したウィンドウ) を表示します。--control を付けて起動した場合は行いません。", "ai.prefs.override_all_warning": "このエージェントは確認せずに設計を保存、上書き、書き出し、置換できます。", - "ai.prefs.permission_all": "すべて許可", - "ai.prefs.permission_all_summary": "利用可能なSolidCraftツールを確認せず実行します。", - "ai.prefs.permission_ask": "変更前に確認", - "ai.prefs.permission_ask_summary": "設計の変更とファイル操作を毎回確認します。", - "ai.prefs.permission_edits": "モデル編集を許可", - "ai.prefs.permission_edits_summary": "モデル編集は自動実行。ファイル操作や破壊的な操作は確認します。", + "ai.prefs.permission_all": "すべて実行", + "ai.prefs.permission_all_summary": "確認しない", + "ai.prefs.permission_ask": "先に確認", + "ai.prefs.permission_ask_summary": "変更ごとに確認", + "ai.prefs.permission_edits": "編集を許可", + "ai.prefs.permission_edits_summary": "自由に編集し、その他は確認", "ai.prefs.permission_scope": "SolidCraftツールのみに適用されます。エージェントのシェルやファイル編集には、そのエージェント自身の権限設定が適用されます。", "ai.prefs.pointer_preview_hidden": "ポインターは非表示", "ai.prefs.pointer_preview_speed": "エージェントのポインター · {speed}", - "ai.prefs.pointer_speed": "移動速度", + "ai.prefs.pointer_speed": "速度", "ai.prefs.privacy_note": "会話は選択したエージェントまたはエンドポイントにのみ送信されます。エンドポイントのキーはシステムのキーチェーンに保存されます。", "ai.prefs.show_pointer": "エージェントのポインターを表示", "ai.prefs.turn_limit_hint": "アシスタントが1件のメッセージで行える、設計を変更するツール呼び出しの上限です。", @@ -785,11 +791,19 @@ "browser.edit_canvas_title": "キャンバスを編集: {name}", "browser.edit_point_cloud_title": "点群を編集: {name}", "browser.move_title": "移動: {name}", + "browser.needs_repair": "{name}: 修復が必要", "browser.parameters": "パラメータ ({count})", "browser.precision": "精度: {precision}", "browser.sketch_attachment_lost": "{name} (アタッチメント消失)", "browser.sketch_editing": "{name} (編集中)", "browser.sketch_name": "スケッチ{number}", + "browser.sketches_to_parts_already_in_part": "すでにその部品にある", + "browser.sketches_to_parts_design_body": "デザイン自体のボディ上にある", + "browser.sketches_to_parts_moved": "{moved} 個のスケッチを描かれている部品に移動しました", + "browser.sketches_to_parts_no_exact_attachment": "正確なアタッチメントのない面上にある", + "browser.sketches_to_parts_not_on_face": "部品の面上にない", + "browser.sketches_to_parts_part_missing": "部品がもうない", + "browser.sketches_to_parts_result": "{moved} 個のスケッチを描かれている部品に移動しました。{stayed} 個はそのまま:{why}", "browser.units": "単位: {units}", "cam.flat": "平面", "cam.follower": "従動節", @@ -821,7 +835,10 @@ "cmd.assembly_bom": "部品表", "cmd.assembly_bom_item_set": "項目番号の変更", "cmd.assembly_bom_renumber": "項目番号の振り直し", + "cmd.assembly_mass_properties": "質量特性", + "cmd.body.print_face": "造形面", "cmd.body_rename": "ボディの名前を変更", + "cmd.body_repair": "パーツを修復", "cmd.browser_collapse_all": "すべて折りたたむ", "cmd.browser_expand_all": "すべて展開", "cmd.browser_group": "新規グループ", @@ -849,6 +866,7 @@ "cmd.component_extract": "ファイルに抽出", "cmd.component_finish_edit": "編集を終了", "cmd.component_from_bodies": "ボディからコンポーネントを作成", + "cmd.component_hide_history": "コンポーネントの履歴を非表示", "cmd.component_insert_design": "デザインを挿入", "cmd.component_links": "リンクを一覧表示", "cmd.component_list": "コンポーネントを一覧表示", @@ -857,6 +875,7 @@ "cmd.component_move_bodies": "ボディをコンポーネントに移動", "cmd.component_move_features": "フィーチャーをコンポーネントに移動", "cmd.component_move_sketches": "スケッチをコンポーネントに移動", + "cmd.component_move_sketches_to_parts": "スケッチをそれぞれの部品に移動", "cmd.component_paste_from_design": "別のデザインから貼り付け", "cmd.component_paste_new": "新規として貼り付け", "cmd.component_properties": "コンポーネントの物理的プロパティ", @@ -864,6 +883,7 @@ "cmd.component_rename": "コンポーネントの名前を変更", "cmd.component_replace_with_link": "リンクに置き換え", "cmd.component_revert_position": "位置を元に戻す", + "cmd.component_show_history": "コンポーネントの履歴を表示", "cmd.component_unlock": "内容のロックを解除", "cmd.component_update_links": "リンクを更新", "cmd.config_activate": "構成をアクティブ化", @@ -874,6 +894,7 @@ "cmd.config_rule": "構成ルール", "cmd.config_rules": "構成ルール一覧", "cmd.config_table": "構成テーブルを表示", + "cmd.construct.plane.axis_point": "軸と点を通る平面", "cmd.construct_axis_edge": "エッジを通る軸", "cmd.construct_axis_normal_to_face": "面に垂直な軸", "cmd.construct_axis_through_cylinder": "円柱/円錐/トーラスを通る軸", @@ -902,6 +923,8 @@ "cmd.diagnostics_crash_reports": "クラッシュレポート一覧", "cmd.diagnostics_crash_reports_clear": "クラッシュレポートを消去", "cmd.diagnostics_crash_test": "クラッシュテスト", + "cmd.diagnostics_profile": "プロファイル", + "cmd.diagnostics_validation": "検証", "cmd.doc_recover": "デザインを復元", "cmd.doc_recovery_discard": "復元デザインを破棄", "cmd.doc_recovery_list": "復元可能なデザイン", @@ -952,6 +975,11 @@ "cmd.explode_show": "分解図を表示", "cmd.expr_evaluate": "式を評価", "cmd.face_delete": "面を削除", + "cmd.file.export_3mf": "3MF をエクスポート", + "cmd.file.export_obj": "OBJ をエクスポート", + "cmd.file.export_step": "STEP をエクスポート", + "cmd.file.export_stl": "STL をエクスポート", + "cmd.file.export_urdf": "URDF をエクスポート", "cmd.file_export": "エクスポート", "cmd.file_insert_mesh": "メッシュを挿入", "cmd.file_insert_step": "STEP を挿入", @@ -964,11 +992,13 @@ "cmd.frame_profile_list": "形材ライブラリ", "cmd.frame_profile_properties": "形材のプロパティ", "cmd.inspect_accessibility": "アクセシビリティ解析", + "cmd.inspect_analysis": "表示解析", "cmd.inspect_center_of_mass": "重心", "cmd.inspect_clearance": "クリアランス", "cmd.inspect_colored_components": "コンポーネントの色分けを有効化", "cmd.inspect_colored_components_disable": "コンポーネントの色分けを無効化", "cmd.inspect_compare": "ボディを比較", + "cmd.inspect_compare_picture": "参考画像と比較", "cmd.inspect_continuity": "連続性解析", "cmd.inspect_curvature_comb": "曲率コーム解析", "cmd.inspect_curvature_map": "曲率マップ解析", @@ -986,6 +1016,7 @@ "cmd.joint_delete": "ジョイントを削除", "cmd.joint_drive": "ジョイントを駆動", "cmd.joint_edit": "ジョイントを編集", + "cmd.joint_find_limits": "ジョイントの制限を検出", "cmd.joint_gear": "ギア", "cmd.joint_inspect": "ジョイントを検査", "cmd.joint_limits": "ジョイントの制限", @@ -998,6 +1029,11 @@ "cmd.joint_screw": "ねじ", "cmd.joint_solve": "ジョイントを解決", "cmd.joint_sweep": "ジョイントをスイープ", + "cmd.layout.apply": "レイアウトを適用", + "cmd.layout.get": "レイアウトを確認", + "cmd.layout.reset": "レイアウトをリセット", + "cmd.layout.save": "レイアウトを保存", + "cmd.layout.workspace.select": "レイアウトのワークスペースを選択", "cmd.library_apply": "ローカルライブラリ項目を適用", "cmd.library_export": "デザインライブラリを書き出す", "cmd.library_inspect": "ローカルライブラリを確認", @@ -1032,6 +1068,21 @@ "cmd.occurrence_move": "オカレンスを移動", "cmd.occurrence_properties": "オカレンスの物理的プロパティ", "cmd.occurrence_reparent": "コンポーネントへ移動", + "cmd.panel.activate": "パネルのタブをアクティブ化", + "cmd.panel.close": "パネルを閉じる", + "cmd.panel.collapse": "パネルのセクションを折りたたむ", + "cmd.panel.dismiss": "パネルの一時表示を閉じる", + "cmd.panel.float": "パネルをフロート表示", + "cmd.panel.focus": "パネルにフォーカス", + "cmd.panel.list": "パネルを一覧表示", + "cmd.panel.move": "パネルを移動", + "cmd.panel.native_close": "別ウィンドウのパネルを再ドッキング", + "cmd.panel.open": "パネルを開く", + "cmd.panel.peek": "折りたたんだパネルを一時表示", + "cmd.panel.popout": "パネルを別ウィンドウに移動", + "cmd.panel.reset_pair": "パネルの区切りをリセット", + "cmd.panel.resize": "パネルのセクションのサイズを変更", + "cmd.panel.resize_pair": "パネルの区切りを移動", "cmd.parameters_add": "ユーザー パラメータを追加", "cmd.parameters_change": "パラメータを変更", "cmd.parameters_comment": "パラメータにコメントを付与", @@ -1060,6 +1111,9 @@ "cmd.pointcloud_edit": "点群を編集", "cmd.pointcloud_insert": "点群を挿入", "cmd.pointcloud_list": "点群", + "cmd.render.compare.divider": "レンダー比較の境界を移動", + "cmd.render.result.discard": "レンダリング結果を破棄", + "cmd.render.result.select": "レンダリング結果を選択", "cmd.render_aging_describe": "レイヤー式表面エイジング", "cmd.render_backends": "レンダリング バックエンド", "cmd.render_batch": "すべてのショットをレンダリング", @@ -1223,6 +1277,7 @@ "cmd.sketch_spline_control_point_5": "制御点スプライン (次数 5)", "cmd.sketch_spline_fit_point": "通過点スプライン", "cmd.sketch_spline_insert_point": "スプライン点を追加", + "cmd.sketch_spline_remove_point": "スプライン点を削除", "cmd.sketch_spline_reverse": "スプラインの方向を反転", "cmd.sketch_spun_profile": "回転プロファイル", "cmd.sketch_toggle_diameter": "半径 / 直径の切り替え", @@ -1273,9 +1328,11 @@ "cmd.timeline_rollback": "タイムライン マーカーを移動", "cmd.timeline_stop": "履歴を停止", "cmd.timeline_suppress": "フィーチャーを抑制", + "cmd.ui.assistant": "アシスタントの表示切り替え", "cmd.view.render_browser": "Renderブラウザー", "cmd.view.render_dock": "レンダードックを移動", "cmd.view.render_focus": "Renderフォーカス表示", + "cmd.view.status_details": "ビューポートの状態の詳細", "cmd.view.status_items": "ビューポートの状態項目", "cmd.view_ambient_occlusion": "アンビエントオクルージョン", "cmd.view_angle_readout": "ビュー角度", @@ -1306,17 +1363,28 @@ "cmd.view_tool": "ナビゲーションツール", "cmd.view_top": "上面ビュー", "cmd.view_visual_style": "表示スタイル", + "color.blue": "青", "color.copy": "クリックして色の値をコピー", "color.edit": "クリックして色を編集", "color.gamma": "0〜255のガンマ空間で色の値を表示", + "color.green": "緑", "color.hex": "Hex", "color.hex_help": "#rrggbb または #rrggbbaa を入力。6 桁の場合は不透明度を維持", "color.hex_hint": "#rrggbb", "color.hue": "色相", "color.linear": "0〜1の線形空間で色の値を表示", + "color.recent": "最近使った色", + "color.recent_help": "どの色フィールドで選んだ色もここに表示されます", + "color.red": "赤", + "color.saturation": "彩度(パーセント)", "color.saturation_value": "彩度と明度", "color.selected": "選択した色", + "color.step_down": "1 ステップ下げる", + "color.step_up": "1 ステップ上げる", + "color.value": "明度(パーセント)", "config.column_filter_empty": "一致する列がありません", + "config.rule_parameter_columns": "表に列があるパラメータのみが表示されます。ここで使うには「列を追加」(+) で列を追加してください。", + "config.rule_suppression_columns": "表に「抑制」列があるフィーチャーのみが表示されます。ここで制御するには「列を追加」(+) で列を追加してください。", "contact.components_count": "{count}個のコンポーネント", "contact.enabled_label": "有効", "coupling.gear_1": "ギア 1", @@ -1351,6 +1419,7 @@ "crash.unclean_explanation": "次回以降の起動時に検出されました。正確な終了時刻は記録されていません。システムのシャットダウンや強制停止によっても、正常終了が記録されない場合があります。", "delete.and_more": "…ほか{count}件", "diagnostic.empty_boolean_component": "コンポーネント '{component}' に切り取りまたは交差の対象となるボディがありません。ツールはコンポーネント '{other}' の '{body}' と重なる可能性があります。そのコンポーネントをアクティブにするか、ボディを対象として選択してください", + "diagnostic.reselect_reference": "{feature}: 参照 `{reference}` は選択したときのままでは存在しません。選択し直してください", "dialog.bodies_count": "{count} ボディ", "dialog.clearance_invalid": "クリアランスは 0 以上の長さにしてください", "dialog.compute": "計算", @@ -1360,11 +1429,20 @@ "dialog.custom_axis": "↖ カスタム軸", "dialog.dimension_insert_hint": "別の駆動寸法をクリックして名前を挿入", "dialog.dimension_name": "寸法: {name}", + "dialog.dimension_step_down": "{step} 減らす", + "dialog.dimension_step_expression": "増減できるのは数値だけです。式はそのまま残ります", + "dialog.dimension_step_up": "{step} 増やす", "dialog.edit_title": "{title}を編集", "dialog.no_shown_body": "変更できる表示中のボディがありません。ボディを表示するか、新規ボディを選択してください", + "dialog.pattern_sketch_not_object": "ボディかフィーチャーを選んでください。スケッチはどちらでもありません。曲線はスケッチ内のパターンかミラーで繰り返すか、先に押し出してください。", "dialog.select": "↖ 選択", "dialog.selected_count": "↖ {count} 個選択中", + "dialog.selection_constraint": "拘束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲線 {id}", + "dialog.selection_external_point": "{point} · {sketch}", "dialog.selection_guidance": "入力欄を選んで変更します。選択済みのオブジェクトをクリックすると解除できます。Ctrl/Cmd を押しながらクリックしても切り替えられます。プレビューを確認してから OK を押してください。", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · プロファイル {number}", "dialog.selection_step": "{total} ステップ中 {step}: {input} を選択", "dialog.step": "ステップ", "document.changed_on_disk": "{name} がディスク上で変更されました", @@ -1379,6 +1457,7 @@ "document.read_only_save": "このデザインは読み取り専用で開かれています:新しいファイルとして保存してください", "document.save_changes": "{name} への変更を保存しますか?", "document.save_copy": "コピーを保存…", + "document.tab_unsaved_changes": "未保存の変更", "document.unsaved_changes": "{name} には保存されていない変更があります。保存しない場合、変更内容は失われます。", "drive.rigid": "{joint} は剛体ジョイントです。部品をその場に固定するため、駆動するものがありません。動かすには「ジョイントを編集」で種類を変更してください: 回転させるなら Revolute、スライドさせるなら Slider、両方なら Cylindrical。", "drive.stopped_by_contact": "{value} で停止: {a} が {b} を通り抜けてしまいます", @@ -1411,6 +1490,14 @@ "file_load.reading_percent": "ファイルを読み込み中... {percent}%", "file_load.rebuilding": "フィーチャーを再構築中: {done}/{total}", "file_load.recovering": "デザインを復元中", + "file_load.step_build": "モデルを構築中", + "file_load.step_feature": "フィーチャー {done}/{total}", + "file_load.step_part": "パーツ {done}/{total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "ファイルを読み込み中", + "file_load.step_rebuild": "フィーチャーを再構築中", + "file_load.step_repair": "パーツを確認・修復中", + "file_load.step_show": "ビューを準備中", "file_load.stopping": "前の操作の停止を待っています...", "file_load.updating_links": "リンクを更新中", "file_load.waiting": "ファイル操作を待っています", @@ -1419,21 +1506,189 @@ "from the rule": "ルールから", "help.apache": "Apacheライセンス2.0", "help.appearance.assign": "選択した立体、面、コンポーネントに、重さを変えずに色や材質の見た目を付けます。部品を見分けるときや仕上げを確認するときに使います。", + "help.assembly.bom": "デザインまたはコンポーネントの部品を品番ごとに数量付きで一覧にし、リストをCSVまたはJSONで保存できます。発注や組み立て用の部品表として使います。", "help.attributions": "帰属表示 (ATTRIBUTION.md)", "help.build": "バージョン {version} · コミット {commit} · ビルド日 {date}", + "help.canvas.decal": "モデルの平面にステッカーのように画像を貼ります。ラベル、ロゴ、印刷柄を部品上に表示するときに使います。", + "help.canvas.edit": "キャンバスの位置、サイズ、角度、不透明度、反転、表示、名前を変更します。参照画像を、その上でトレースするスケッチに合わせるときに使います。", + "help.canvas.insert": "PNG または JPEG 画像を、半透明の参照として平面や面に配置します。既知のサイズに合わせた画像をもとに、写真や図面をスケッチでトレースするときに使います。", + "help.component.break_link": "リンクされたコンポーネントをデザイン ファイルから切り離し、ボディはそのまま残します。部品が元ファイルの変更に追従しないようにするときに使います。", + "help.component.capture_position": "手で動かした部品の位置を、その部品の新しい位置として確定します。ジョイントで保持されていない部品をドラッグして配置した後に使います。", + "help.component.create": "新しい空のコンポーネントをデザインに追加します。別の親を選ばない限り、アクティブなコンポーネントの中に作られます。アセンブリの新しい部品に、ボディやスケッチをまとめる場所を用意するときに使います。", "help.component.finish_edit": "その場で編集中の部品を保存し、アセンブリに戻って、その部品でアセンブリを更新します。リンクされた部品への変更が終わったときに使います。", + "help.component.from_bodies": "選択した各ボディを、そのボディ名を付けた個別のコンポーネントにします。ばらばらのボディで作ったデザインを、ジョイントで結合して動かせるアセンブリにするときに使います。", + "help.component.insert_design": "保存済みの別のデザインを、そのファイルにリンクしたコンポーネントとして挿入します。ソリッド ボディは元のデザインと同じ位置に置かれます。部品をアセンブリで再利用し、後の変更を「リンクを更新」で取り込むときに使います。", + "help.component.properties": "コンポーネントの体積、質量、重心、慣性モーメントを、各ボディの材料から求めて表示します。アセンブリの重さやバランスを確かめるときに使います。", + "help.component.revert_position": "手で動かした部品を元の位置に戻し、キャプチャしていない移動を破棄します。アセンブリで試しに動かした部品を元に戻すときに使います。", + "help.component.update_links": "リンクされたデザイン ファイルを読み込み直し、変更されたボディを置き換えます。このアセンブリで使っている部品を編集した後に使います。", + "help.config.configure": "パラメータ、フィーチャー、材料、外観を構成テーブルの列として追加します。部品のサイズ違いなど、1つのデザインのバリエーションを作るときに使います。", + "help.config.preview": "構成テーブルの行が、デザインや履歴を変えずに再構築できるか確認します。自信のないバリエーションに切り替える前に使います。", + "help.config.rules": "構成テーブルのルールと行、現在有効な行を表示します。デザインのバリエーションがどう設定されているかを確認するときに使います。", + "help.config.table": "構成テーブルを表示します。1行が1つのバリエーション、1列が1つのパラメータまたはフィーチャーで、デザインが有効な行と一致しているかも分かります。デザインのバリエーションを見直すときに使います。", "help.connect_note": "各アシスタントを再起動すると SolidCraft サーバーが読み込まれます。変更したファイルは .bak としてバックアップされています。", "help.connect_title": "AI アシスタントを接続", + "help.construct.axis.edge": "直線のエッジまたはスケッチ線に沿って構築軸を作ります。回転、円形パターン、ジョイントの軸として使います。", + "help.construct.axis.normal_to_face": "指定した点を通り、面に垂直な構築軸を作ります。表面からまっすぐ立ち上がる軸として使います。", + "help.construct.axis.through_cylinder": "円柱、円錐、トーラスの面、または円形のエッジの中心を通る構築軸を作ります。丸い部品のまわりでフィーチャーを回転させたりパターン化したりするときに使います。", + "help.construct.axis.two_planes": "2つの平面または平らな面が交わる位置に構築軸を作ります。必要な軸が2つの面の間の線であるときに使います。", + "help.construct.axis.two_points": "2つの点、頂点、スケッチ点を通る構築軸を作ります。位置が分かっている2か所の間を通る軸に使います。", + "help.construct.plane.along_path": "エッジまたは曲線に垂直な構築平面を、その上の指定位置に作ります。スイープ用のプロファイルや、パスの断面をスケッチするときに使います。", + "help.construct.plane.at_angle": "平面または面を、軸またはエッジを中心に指定した角度だけ傾けた構築平面を作ります。斜めのブラケットなど、傾いたスケッチに使います。", + "help.construct.plane.axis_point": "軸と、その軸上にない点を含む構築平面を作成します。原点軸、構築軸、直線エッジまたはスケッチの直線を選択し、次に頂点、スケッチ点または構築点を選択します。軸上の点では平面が一意に定まりません。", + "help.construct.plane.midplane": "2つの平面または平らな面の中間、または角度をなして交わる場合はその二等分に構築平面を作ります。ミラーの対称面として使います。", + "help.construct.plane.offset": "平面または平らな面に平行な構築平面を、指定した距離または点を通る位置に作ります。面から一定の高さの位置にスケッチするときに使います。", + "help.construct.plane.perpendicular": "線またはエッジを含み、平面または面に垂直な構築平面を作ります。エッジに沿ってモデル上に垂直にスケッチするときに使います。", + "help.construct.plane.tangent": "円柱、円錐、球、トーラスに1点で接する構築平面を作ります。丸い部品の側面にスケッチするときに使います。", + "help.construct.plane.three_points": "3つの点を通る構築平面を作ります。3つの角など、モデル上の位置で決まる平面に使います。", + "help.construct.plane.two_edges": "同一平面上にある2本の直線エッジまたは線を通る構築平面を作ります。向かい合う2本のエッジを通る面など、部品を横切る平面に使います。", + "help.construct.point.along_path": "エッジまたは曲線上の指定位置に構築点を作ります。パスの途中の基準として使います。", + "help.construct.point.center": "円形のエッジ、スケッチの円や円弧、球、トーラスの中心に構築点を作ります。穴、軸、ジョイントの基準として使います。", + "help.construct.point.edge_plane": "エッジまたは線が平面や平らな面を通る位置に構築点を作ります。パスが平面と交わる位置を示すときに使います。", + "help.construct.point.three_planes": "3つの平面または平らな面が交わる位置に構築点を作ります。モデルに頂点がない場所でも、角の基準として使えます。", + "help.construct.point.two_edges": "2本のエッジまたは線が交わる位置、または最も近づく位置に構築点を作ります。仮想の角の基準として使います。", + "help.construct.point.vertex": "頂点またはスケッチ点の上に構築点を作ります。周囲のスケッチやボディを非表示にしても残る基準として使います。", + "help.contact.check": "接触セット内で、現在の位置で互いに食い込んでいる部品の組を一覧表示します。ジョイントを駆動したりモーション スタディを再生したりする前に、干渉を見つけるときに使います。", + "help.contact.create": "2つ以上の部品を接触セットにまとめ、ジョイントが動くときにボディどうしが食い込まないようにします。レバーとストッパーのように、触れたところで止まるべき部品に使います。", + "help.contact.disable_all": "接触をオフにします。ジョイントの駆動やモーション スタディは、部品が触れても止まらなくなります。部品を再び自由に動かしたいときや、大きなアセンブリの動作を軽くしたいときに使います。", + "help.contact.edit": "接触セットを変更します。含まれる部品、名前、抑制の有無を変えられ、セットを削除することもできます。互いに食い込まないようにする部品を調整するときに使います。", + "help.contact.enable_all": "アセンブリのすべての部品を1つの接触セットに入れ、ジョイントが動くときにどの部品どうしも食い込まないようにします。機構全体をすばやく確認するときに使います。", + "help.contact.enable_sets": "定義した接触セットで接触をオンにします。ジョイントの駆動やモーション スタディは、セット内の部品が食い込む位置で止まります。接触をオフにした後、設定したセットに戻すときに使います。", + "help.contact.list": "デザインの接触セット、各セットに含まれる部品、接触がオンかどうかを一覧表示します。アセンブリを駆動する前に、接触の設定を確認するときに使います。", + "help.document.inspect": "デザインのコンポーネント、ボディ、スケッチ、フィーチャー、パラメータの概要を表示します。自分で作っていないデザインの全体像をつかむときに使います。", + "help.document.units": "デザインで長さを表示する単位を、mmやインチなどに変更します。形状の大きさは変わらず、表示と数値だけが単位に合わせて変わります。", + "help.edit.checkpoint": "現在のデザイン、アクティブなスケッチ、元に戻す履歴をそのまま記憶します。元に戻したくなるかもしれない危険な操作を試す前に使います。", + "help.edit.restore_checkpoint": "元に戻す履歴も含めて、チェックポイントの状態に戻ります。チェックポイント以降の作業をまとめて破棄するときに使います。", + "help.explode.create": "部品をアセンブリの中心から外側へ、または指定した移動量だけ離した分解図を作成します。組立手順書やプレゼンテーションで、アセンブリの組み立て方を示すときに使います。", "help.face.delete": "選択した面を削除し、隣の面でその穴をふさぎます。穴を開いたまま面として残すこともできます。じゃまな丸み、穴、突起を取り除くときに使います。", + "help.file.insert_mesh": "3MF、STL、OBJ、PLY、glTF ファイルを、新しいコンポーネント内のメッシュ ボディとしてデザインに追加します。ダウンロードやスキャンで得たモデルを、参照としてデザインの横に置くときに使います。", + "help.file.insert_step": "STEP、IGES、FreeCAD、Rhino ファイルを、新しいコンポーネント内のソリッド ボディとしてデザインに追加します。アセンブリの部品は入れ子のコンポーネントになります。メーカーやほかの CAD プログラムのモデルを取り込むときに使います。", + "help.file.save_mesh": "ボディを STL、3MF、OBJ のメッシュとして保存します。曲面のなめらかさは選択できます。3D プリント用や、メッシュを読み込むプログラム用に部品を用意するときに使います。", + "help.file.send_to_slicer": "選択したボディを 3MF ファイルとして保存し、選んだスライサーで開きます。モデルからプリントまでを1ステップで進めるときに使います。", "help.font_details": "インターフェースにはegui組み込みのフォントを使用しています(Ubuntu Font LicenceおよびMIT/Bitstream VeraライセンスのUbuntu LightとHack、OFLおよびMITのNoto Emojiと絵文字アイコンフォント)。スケッチのテキストにはLiberation Sans(SIL OFL 1.1)を使用しています。The Crafting Appsのオプションフォントパックcraft-fonts(BIZ UDPGothic、Shippori Mincho、BIZ UDMincho、Noto Sans CJK SC、Noto Sans Arabic、SIL OFL 1.1)はSolidCraftのビルドに同梱されていません。", "help.fonts": "フォント", + "help.frame.member": "チューブやアルミ押し出し材などのプロファイルを、フレームスケッチの線に沿って1本につき1部材ずつ配置します。フレーム、ラック、溶接構造を作るときに使います。", + "help.inspect.accessibility": "ツールが一方向から届く面と届かない面を色分けします。その方向からの切削加工や成形が可能か、部品を確認するときに使います。", + "help.inspect.center_of_mass": "一様な密度を仮定して、各ボディと全体の重心を表示します。バランスや、部品が倒れる位置を確認するときに使います。", + "help.inspect.colored_components": "外観を変えずに、コンポーネントごとに一時的な色を付けます。アセンブリの部品をひと目で見分けるときに使います。", + "help.inspect.compare": "2つのボディを比較し、一方にだけある材料の位置を体積と偏差とともに表示します。変更した部品やインポートした部品を元のものと照合するときに使います。", + "help.inspect.continuity": "面どうしがエッジに沿ってどれだけなめらかにつながるか(隙間、折れ、曲率の飛び)を調べ、継ぎ目を色分けします。サーフェスがきれいにつながっていない箇所を見つけるときに使います。", + "help.inspect.curvature_comb": "曲線、エッジ、面に、曲がりの強さを歯の長さで示すコームを描きます。平らな部分、折れ、曲率のむらを見つけるときに使います。", + "help.inspect.curvature_map": "面を曲がりの強さで色分けし、半径が小さいところを赤で示します。きつい箇所を見つけたり、サーフェスのなめらかさを判断したりするときに使います。", + "help.inspect.draft": "面を抜き方向に対する勾配角で色分けし、不足している面を示します。成形や鋳造の前に部品を確認するときに使います。", + "help.inspect.environment_map": "モデルを鏡のような反射する仕上げで表示します。反射の流れ方から、サーフェスの流れを判断するときに使います。", + "help.inspect.interference": "重なっているボディを見つけ、それぞれの重なりを体積とともに表示します。アセンブリで部品が干渉していないか確認するときに使います。", + "help.inspect.isocurve": "面のアイソパラメトリック曲線、つまりサーフェスのもとになるグリッドを描きます。サーフェスの流れや、線が密集している箇所を確認するときに使います。", + "help.inspect.measure": "選択したものの間の長さ、距離、角度、面積、半径、またはボディの体積と質量を測定します。寸法やクリアランスを確認するときに使います。", + "help.inspect.minimum_radius": "曲線、エッジ、面の最小曲率半径とその位置を求めます。工具やノズルが形状に沿って動けるか確認するときに使います。", + "help.inspect.section": "モデルを変更せずに、平面でビューを切断し、切断面にハッチングを付けます。部品やアセンブリの内部を見るときに使います。", + "help.inspect.zebra": "モデルの面に映る白黒のストライプを表示します。なめらかさの判断に使い、エッジでストライプが途切れたり折れたりする箇所は、つながりが悪いことを示します。", + "help.joint.as_built": "2つの部品を、どちらも動かさずに現在の位置で結合し、残る動きを設定します。すでに最終的な位置に置いた部品に使います。", + "help.joint.cam": "回転するカムとフォロワを連動させ、カムの輪郭に沿ってフォロワがスライドまたは揺動するようにします。カム、偏心機構、バルブ駆動に使います。", + "help.joint.create": "選んだジョイント原点で2つの部品を結合し、2つ目の部品をその位置へ移動します。残る動きはジョイントの種類で決まります。実際の機構と同じように動くアセンブリを作るときに使います。", + "help.joint.drive": "ジョイントの角度または距離を制限の範囲内で設定し、部品をそれに合わせて動かします。連動するジョイントや閉ループも追従します。機構が意図どおりに動くか確認するときに使います。", + "help.joint.gear": "2つの回転ジョイントをギア比で連動させ、一方を駆動するともう一方が回るようにします。平歯車や内歯車に使い、ギア比はピッチ半径または歯数から決めます。", + "help.joint.limits": "ジョイントが回転またはスライドできる範囲を最小値と最大値で設定するか、その制限を解除します。ヒンジ、スライダー、レバーを実際の可動範囲内に収めるときに使います。", + "help.joint.motion_link": "2つのジョイントを比率とオフセットで連動させ、一方を駆動するともう一方が動くようにします。「ギア」「ラック アンド ピニオン」「ねじ」では表せない、ジョイント間の一定の関係に使います。", + "help.joint.origin": "部品に名前付きのジョイント原点を置きます。面や丸い端の中心、エッジの中点、角、または点に置けます。ジョイントの取り付け位置を準備するときに使います。面上で選んだ原点は、部品のサイズが変わってもその面に追従します。", + "help.joint.rack_pinion": "回転するピニオンとスライドするラックを連動させ、ピニオンのピッチ円が転がった長さだけラックが移動するようにします。ラック駆動、ステアリング、リニア ステージに使います。", + "help.joint.reach": "部品上の点を目標に向けて動かし、そのチェーン上のジョイントを制限の範囲内で変化させます。ロボット アームの先端のように、先端の位置から機構の姿勢を決めるときに使います。", + "help.joint.rigid_group": "選択した部品を現在の配置のまま固定し、一体として動くようにします。互いに動きのない、ひとまとまりの部品に使います。", + "help.joint.screw": "回転とスライドをピッチで連動させ、1回転ごとにその距離だけ進むようにします。送りねじ、ボルト、ねじ軸に使います。", + "help.layout.apply": "保存したレイアウトを現在のワークスペースに適用します。保持されているエディターの下書きは維持されます。", + "help.layout.get": "確定したレイアウトと登録済みのワークスペースを確認します。", + "help.layout.reset": "現在のワークスペースに登録された既定のレイアウトを復元します。ユーザープリセットは保持されます。", + "help.layout.save": "レイアウト全体に名前を付けて保存します。ユーザープリセットの置き換えには明示的な上書き許可が必要です。", + "help.layout.workspace.select": "登録済みのレイアウト用ワークスペースを選択し、移動前のレイアウトを記憶します。", + "help.library.apply": "ローカルのライブラリファイルから材料または外観を、ボディ、面、コンポーネントに適用します。別のデザインで保存した材料を再利用するときに使います。", + "help.library.export": "デザインの材料と外観をライブラリファイルに保存します。共有したり、ほかのデザインで再利用したりするときに使います。", + "help.library.inspect": "デザインを変更せずに、ライブラリファイルを確認して材料と外観を一覧にします。適用する前にライブラリの中身を確認するときに使います。", "help.licences": "ライセンス", "help.material.assign": "選択した立体の材料を、鋼、アルミニウム、ABS などに設定します。質量と重さを実際の部品に合わせるときに使います。", + "help.material.properties.validate": "材料データカードの数値に矛盾や欠けがないか確認します。質量や剛性の計算にデータを使う前に使います。", + "help.mesh.convert": "STLなどのメッシュボディを、平面と円柱面を持つ編集可能なソリッドに作り直します。インポートした機械部品を、モデリングしたボディのように変更するときに使います。", "help.mit": "MITライセンス", + "help.motion.study": "タイムライン上のステップごとにジョイントの値を設定し、アニメーションとして再生します。機構が一連の動作をする様子を見て、途中のすき間を確認するときに使います。", + "help.motion.trace": "モーション スタディの再生中やジョイントの駆動中に部品上の点がたどる軌跡を求め、確定すると3D スケッチ曲線として残します。機構の届く範囲を確認したり、その軌跡をモデリングに利用したりするときに使います。", "help.notice": "NOTICE", + "help.occurrence.ground": "部品をその場に固定するか、固定を解除します。ジョイントはほかの部品をこの部品の周りで動かします。アセンブリの残りが組み付けられるフレームやベースに使います。", "help.occurrence.move": "アセンブリ部品をジョイントが許す自由度だけで動かします。部品の面を選択してから、操作可能な矢印または円弧をドラッグしてください。", + "help.panel.activate": "キーボードフォーカスを要求せずに、開いているパネルのタブを選択します。", + "help.panel.close": "内容のライフサイクルの確認を経てパネルを閉じます。配置は記憶されます。", + "help.panel.collapse": "要求された寸法を保持したまま、パネルのセクションを折りたたむか展開します。", + "help.panel.dismiss": "折りたたんだパネルの一時表示を閉じます。", + "help.panel.float": "パネルを明示的に指定した位置のフローティングセクションに移動します。", + "help.panel.focus": "パネルにフォーカスします。必要に応じて保持された状態を再度開き、セクションを展開します。", + "help.panel.list": "登録済みのパネル種類、確定したインスタンス、アクティブなタブ、利用可否、ホストの機能を確認します。", + "help.panel.move": "パネルを新しいセクションに移動するか、既存のタブグループに追加します。", + "help.panel.native_close": "別ウィンドウのパネルセクションを、内容をキャンセルせずに記憶されたドックに戻します。", + "help.panel.open": "パネルの種類と明示的なインスタンス識別子を指定して開きます。新しいインスタンスには配置を指定します。", + "help.panel.peek": "保存されたサイズや折りたたみ状態を変更せずに、折りたたんだパネルを一時表示します。", + "help.panel.popout": "対応している場合はパネルを別ウィンドウに移動します。ブラウザーではフローティングセクションを使用します。", + "help.panel.reset_pair": "隣接するドックのペアを、共通の制約内で既定のサイズ比率に戻します。", + "help.panel.resize": "すべてのタブの制約内で、パネルセクションの外側の幅と高さを設定します。", + "help.panel.resize_pair": "共有する全体の長さを維持しながら、隣接するドックセクションのサイズを同時に変更します。", "help.parameters.change": "デザインの寸法を決める名前付きの値と式の表を開きます。1か所で寸法を変え、それを使うすべてのフィーチャに反映させるときに使います。", + "help.parameters.export": "デザインのパラメータをCSVまたはJSONで保存します。表計算ソフトで編集したり、別のデザインに移したりするときに使います。", + "help.parameters.graph": "どのパラメータとフィーチャーがほかのどれを使っているか、その間のループやエラーも表示します。パラメータを変更すると何に影響するかを確認するときに使います。", + "help.parameters.import": "CSVまたはJSONからパラメータをデザインに読み込みます。すべて読み込むか、まったく読み込まないかのどちらかです。表計算ソフトや別のデザインの値を取り込むときに使います。", + "help.parameters.move": "ユーザーパラメータを、一覧内の別のパラメータの前または後ろに移動します。関連するパラメータをまとめておくときに使います。", + "help.parts.fastener": "選んだサイズの標準のボルト、ナット、ワッシャー、ピン、ベアリングを追加します。穴の上に置くとジョイントで穴に収まるので、締結部品を自分でモデリングする必要はありません。", + "help.parts.insert": "選んだ種類、サイズ、長さの標準パーツを挿入します。穴の縁や内壁に置くと、剛体ジョイントで穴に取り付けられます。", + "help.parts.library": "標準パーツを開きます。ボルト、ナット、ワッシャー、止めねじ、ダウエル ピン、ベアリングを規格サイズで用意しています。標準部品を自分でモデリングせずに追加するときに使います。", + "help.parts.resize": "挿入済みの標準パーツのサイズや長さを変更して再構築します。ジョイントにより取り付け位置は保たれます。ボルトが長すぎたときや、穴に別のサイズが必要なときに使います。", + "help.plastic.assign_rule": "プラスチック ルールをボディに割り当て、そのプラスチックフィーチャーが勾配とクリアランスを初期値として使うようにします。成形品を一度の設定ですべてのフィーチャーに反映するときに使います。", + "help.plastic.boss": "面にスクリューボスを追加します。穴、勾配、根元のフィレット、補強リブを任意で付けられる円柱です。成形品や3Dプリントのハウジングのねじ止め箇所に使います。", + "help.plastic.lip": "シェルしたボディの縁に沿って、リップまたはそれに合う溝を追加します。ハウジングの2つの半体が互いに位置決めされ、しっかり閉じるようにするときに使います。", + "help.plastic.manage_rules": "プラスチック ルール(材料、肉厚、半径、クリアランス、勾配)を作成・編集します。成形品のフィーチャーの一貫性を保つときに使います。", + "help.plastic.rest": "面にレストを追加します。丸または四角のパッドで、中実でも中空でも、勾配を付けられます。成形ハウジングの支えやスタンドオフとして使います。", + "help.plastic.snap_fit": "面にスナップフィットのフックを、長さ、厚さ、爪とともに追加します。ねじを使わずに部品を留めるときに使います。", "help.pointcloud.insert": "PLY・XYZ・PTS形式のスキャンを点群としてモデルと一緒に挿入します。計測データを参考にモデリングするときに使います。", + "help.sheet.convert": "厚さが均一なプレートまたはシェルしたボディを、選択したエッジで曲げた板金ボディにします。既存の部品を展開できるようにするときに使います。", + "help.sheet.export_bend_table": "板金ボディの曲げテーブル、つまり角度、半径、展開図上の曲げ位置をCSVまたはJSONで保存します。プレスブレーキや工場向けに使います。", + "help.sheet.export_dxf": "展開図を、外形、曲げ線、必要に応じて曲げの注記付きでDXFに保存します。レーザー、プラズマ、ウォータージェット切断用に使います。", + "help.sheet.flange": "フランジを追加します。スケッチから作るベースプレート、開いたスケッチ輪郭に沿った壁、または板のエッジに曲げた壁があります。板金部品を作り上げるときに使います。", + "help.sheet.flat_pattern": "板金ボディの展開図を、寸法、切り欠き、曲げ線とともに作成します。切断する前にブランクを確認するときに使います。", + "help.sheet.fold": "板をスケッチ線に沿って、指定した角度と半径で曲げます。フィーチャーを切り込んだ平らな板を折り曲げるときに使います。", + "help.sheet.hem": "板のエッジを自身に折り返します。鋭いバリのない、安全で剛性のあるエッジにするときに使います。", + "help.sheet.manage_rules": "板金ルール(厚さ、曲げ半径、Kファクター、逃げ、隙間)を作成・編集します。工場の材料や工具に合わせるときに使います。", + "help.sheet.path_flange": "板のエッジに沿って、開いたスケッチ線の連なりに従い、連続したフランジを追加します。UやZ形のプロファイルを1ステップで作るときに使います。", + "help.sheet.perforate": "展開した板全体に、千鳥またはグリッド状に穴のフィールドを追加します。通気口、グリル、軽量化したパネルに使います。", + "help.sheet.refold": "展開した板金ボディを折り戻します。展開した板にフィーチャーを追加した後に使います。", + "help.sheet.unfold": "板金ボディのすべての曲げを展開します。曲げをまたぐ穴や切り込みを追加するときに使い、その後で折り戻します。", + "help.sketch.arc.center_point": "中心点まわりに、始点から終点までの円弧を描きます。穴や回転軸まわりの半径など、円弧の中心が決まっているときに使います。", + "help.sketch.arc.tangent": "直線または円弧の端点から、それに正接する円弧を続けて描きます。角ではなく滑らかな曲がりでつなぎたいときに使います。", + "help.sketch.arc.three_point": "始点から終点まで、3つ目の点を通る円弧を描きます。中心ではなく、通る点が決まっているときに使います。", + "help.sketch.arc3d": "3D スケッチをオンにして、3点を通る正確な円弧を空間内に描きます。スケッチ平面から外れるパスやガイドレールの曲がりに使います。", + "help.sketch.auto_constrain": "水平、平行、一致など、スケッチがほぼ満たしている拘束を追加し、完全に定義されるまで寸法を付けます。ラフに描いたスケッチを一度で固定したいときに使います。", + "help.sketch.auto_constrain_from_datum": "自動拘束と同様ですが、原点ではなく、選んだ基準点から位置を測ります。角や穴など、1つの基準点から部品を配置するときに使います。", + "help.sketch.blend_curve": "2本の曲線の端を、両方に正接する滑らかなスプラインでつなぎます。選べば曲率連続にもできます。曲線の間の隙間を折れ目なく埋めるときに使います。", + "help.sketch.break": "曲線を、ほかの曲線と交差する位置、または置いた点で分割します。曲線の一部に別の拘束を付けたり、その部分だけ削除したりするときに使います。", + "help.sketch.cancel": "スケッチを終了し、作成または編集を始めてからの変更をすべて破棄します。元に戻すで変更を復元できます。", + "help.sketch.centerline": "直線を、通常の直線と中心線(輪郭に含まれない軸)に切り替えます。回転、ミラー、対称拘束の軸として中心線を使います。", + "help.sketch.chamfer.distance_angle": "2本の直線の角を、1本目の直線に沿った距離と角度で面取りします。2 mm × 30° のように、図面で長さと角度が指定されているときに使います。", + "help.sketch.chamfer.equal_distance": "2本の直線の角を、両方に同じ距離だけ戻って面取りします。外形の一般的な 45° 面取りに使います。", + "help.sketch.chamfer.two_distance": "2本の直線の角を、それぞれの直線に沿った別々の距離で面取りします。45° ではない、2つの長さで指定された面取りに使います。", + "help.sketch.circle.center": "中心と直径から円を描きます。中心が決まっている穴、ボス、そのほかの丸い形状に使います。", + "help.sketch.circle.three_point": "3点を通る円を描きます。既存のジオメトリ上の点など、円が通る点が決まっているときに使います。", + "help.sketch.circle.three_tangent": "3つの直線、円、円弧に接する円を描きます。三角形の内接円のように、3本の曲線の間に円をはめ込むときに使います。", + "help.sketch.circle.two_point": "直径の両端の2点から円を描きます。中心ではなく、円周上の点が決まっているときに使います。", + "help.sketch.circle.two_tangent": "2つの直線、円、円弧に接する、指定サイズの円を描きます。2本の曲線の間に半径一定の丸みを付けるときに使います。", + "help.sketch.conic": "2つの端点の間に、頂点と rho 値で形が決まる円錐曲線を描きます。平らな形からほぼ鋭い角まで、ふくらみを調整できる滑らかな遷移に使います。", + "help.sketch.constrainer": "選んだ1〜2本の曲線がほぼ満たしている拘束(水平、平行、正接、等長など)を適用します。手描きのスケッチを1つずつ整えるときに使います。", + "help.sketch.constraint.coincident": "点を、別の点、曲線、スケッチ軸の上に載せます。輪郭の隙間を閉じたり、点を直線上に置いたりするときに使います。", + "help.sketch.constraint.collinear": "2本の直線を同一直線上に揃えます。切り欠きの両側など、途切れたエッジを揃えるときに使います。", + "help.sketch.constraint.concentric": "2つの円または円弧の中心を揃えるか、円または円弧の中心をスケッチ点(原点を含む)に一致させます。選択する順序は問いません。", + "help.sketch.constraint.curvature": "端点で接する2本の曲線を、同じ曲率で続けます (G2)。正接では滑らかさが足りない、見える面などに使います。", + "help.sketch.constraint.equal": "直線を同じ長さに、円や円弧を同じ半径にします。1つの寸法で複数の同じ形状を制御するときに使います。", + "help.sketch.constraint.fix": "点や曲線を現在の位置に固定、または固定を解除します。ドラッグやスケッチの解決で動いてはいけないジオメトリに使います。", + "help.sketch.constraint.horizontal_vertical": "直線、または2点を結ぶ線を、近いほうに合わせて水平または垂直にします。外形をスケッチの軸に揃えるときに使います。", + "help.sketch.constraint.midpoint": "点を直線の中央に置く、または2本の直線の中点を一致させます。エッジに対してジオメトリを中央に配置するときに使います。", + "help.sketch.constraint.parallel": "2本の直線を平行にします。ほかの寸法を変えても平行を保つ辺に使います。", + "help.sketch.constraint.perpendicular": "2本の直線を直角に交わらせます。スケッチ軸上にない直線同士の直角の角に使います。", + "help.sketch.constraint.polygon": "閉じた直線の連なりを正多角形にします。辺の長さが等しく、すべての角が1つの円上に載ります。手描きの多角形を正多角形にして、そのまま保つときに使います。", + "help.sketch.constraint.symmetry": "2つの点または曲線を、直線を挟んで、または点を中心に対称にします。片側を変更しても輪郭の対称性を保つときに使います。", + "help.sketch.constraint.tangent": "直線と円弧など、2本の曲線を正接させます。折れ目のない滑らかな接続に使います。", + "help.sketch.construction": "曲線を、通常のジオメトリと、輪郭に含まれないコンストラクション ジオメトリに切り替えます。レイアウト、参照、寸法の補助としてコンストラクション曲線を使います。", "help.sketch.construction_line": "2点を通る無限の補助直線を作成します。スケッチの輪郭を分割せずに作図できます。", "help.sketch.construction_line.angle": "スケッチのX軸に対して角度を指定し、無限の補助直線を作成します。点を選び、角度を入力するか方向を選びます。", "help.sketch.construction_line.bisector": "交差する2本のスケッチ直線を選び、2つの角の二等分線から選びます。結果は元の直線の編集に追従します。", @@ -1444,11 +1699,71 @@ "help.sketch.construction_line.tangent_external": "円または円弧、外部点、接線の解を順に選びます。プレビューには描かれた円弧上の接点のみが表示されます。", "help.sketch.construction_line.tangent_two": "2つの円または円弧を選び、プレビューから共通接線を選びます。接点は描かれた曲線上にある必要があります。", "help.sketch.construction_line.vertical": "指定点を通る無限の垂直補助直線を作成します。後で編集しても垂直拘束が維持されます。", + "help.sketch.copy": "選んだスケッチの曲線と点を、その間の拘束や寸法とともにコピーします。このスケッチまたは別のスケッチに貼り付けられます。", + "help.sketch.create": "平面、またはモデルの平らな面に、新しい 2D スケッチを開始します。押し出し、回転、スイープはすべてスケッチから始まります。", + "help.sketch.cut": "選んだスケッチ ジオメトリをコピーしてスケッチから削除します。操作は1回で元に戻せます。このスケッチ内の別の場所や別のスケッチに貼り付けられます。", + "help.sketch.dimension": "選んだ対象に応じて、長さ、距離、角度、半径、直径の駆動寸法を追加します。値またはパラメーター名を入力すると、スケッチがそれに追従します。", + "help.sketch.edit": "既存のスケッチを開いて編集します。スケッチを終了すると、それをもとにしたフィーチャが更新されます。", + "help.sketch.ellipse": "中心、長軸の端、短軸側の1点から楕円を描きます。長円形の開口部、カム、そのほか細長い丸い形に使います。", "help.sketch.equation_curve": "x(t) と y(t)、または y = f(x) の式から、範囲を指定して曲線を描きます。式にはパラメーターを使え、曲線はその変更に追従します。正弦波、らせん、歯車のインボリュートなどに使います。", + "help.sketch.extend": "直線または円弧を、行く手にある最も近い曲線まで延長します。2本の曲線を交わるまで伸ばすこともできます。トリムや編集のあとに輪郭の隙間を閉じるときに使います。", + "help.sketch.fillet": "2本の直線または円弧が交わる角を、指定した半径の円弧で丸めます。まとめて丸めた複数の角は同じ半径になります。", + "help.sketch.finish": "スケッチを終了してモデルに戻ります。閉じた輪郭は、押し出し、回転などのフィーチャに使えるようになります。", + "help.sketch.finish_auto_constrain": "スケッチに自動拘束を実行してから終了します。スケッチを完全に定義した状態で一度に終えるときに使います。", + "help.sketch.fit_curves_to_section": "メッシュまたはソリッド ボディをスケッチ平面で切り、断面に直線と円弧をフィットさせます。スキャンや読み込んだ部品を編集可能なスケッチとして作り直すときに使います。", + "help.sketch.include_3d": "モデルのエッジ、頂点、ほかのスケッチの曲線を、リンクされた参照としてこのスケッチに取り込み、平面外のものは平面上に平坦化します。スケッチ平面上にないジオメトリをもとに作図するときに使います。", + "help.sketch.infinite": "直線を、通常の直線と、ビュー全体に伸びる無限の補助直線に切り替えます。短すぎて足りなくなることのない、レイアウトの参照として使います。", + "help.sketch.insert_dxf": "DXF 図面の曲線をスケッチに読み込み、指定した位置に拡大縮小・回転して配置します。レーザー加工の外形など、ほかのプログラムで作った2D 図面をもとにモデリングするときに使います。", + "help.sketch.insert_svg": "SVG 図面のパスをスケッチに読み込み、指定した位置に拡大縮小・回転して配置します。ロゴやベクター輪郭を、押し出しできる曲線にするときに使います。", + "help.sketch.inspect": "開いているスケッチのレポートを開きます。残りの自由度と、完全に拘束されているかどうかを表示します。スケッチを終える前に、まだ動く部分を確認するときに使います。", + "help.sketch.intersect": "ボディ、面、エッジ、ほかのスケッチがスケッチ平面と交差する曲線または点を追加します。リンクが保たれ、モデルが変わると追従します。", + "help.sketch.intersection_curve": "2つのボディまたは面が接する位置に、それらにリンクした 3D 曲線を作成します。モデルに追従するパスやガイドレールとして使います。", + "help.sketch.isoparametric_curve": "選んだ点を通る面の U または V 方向に沿った 3D 曲線を、面にリンクして作成します。表面に追従するパスや分割線として使います。", + "help.sketch.line": "点を順に指定して、つながった直線を開いた連なりまたは閉じた外形として描きます。ほとんどの輪郭に使う基本のツールです。", + "help.sketch.line.midpoint": "中点から一方の端まで直線を描き、もう一方の端は反対側に対称に作られます。対称なエッジなど、点を中心にした直線に使います。", + "help.sketch.line3d": "3D スケッチをオンにして、空間内の点の間につながった直線を描きます。スケッチ平面から外れるパスやフレームに使います。", + "help.sketch.mirror": "スケッチの曲線と点を直線または軸に対してミラーし、対称拘束を追加します。対称な輪郭の半分を描いて完成させるときに使います。", + "help.sketch.move": "スケッチの曲線と点、またはそのコピーを移動または回転します。形状と拘束を保ったままジオメトリの位置を変えるときに使います。", + "help.sketch.offset": "曲線の連なりを、指定した距離で片側または両側にコピーします。壁、外形、クリアランスに使い、距離は編集可能な寸法のままです。", + "help.sketch.paste": "コピーまたは切り取ったスケッチ ジオメトリを、アクティブなスケッチに貼り付けます。点を指定して配置するか、オフセットでずらせます。", + "help.sketch.pattern.circular": "スケッチ ジオメトリを中心点まわりに、全周または指定角度でコピーします。ボルト円、スポーク、歯に使います。", + "help.sketch.pattern.rectangular": "スケッチ ジオメトリを、指定した間隔で行と列にコピーします。穴、スロット、通気口の格子に使います。", + "help.sketch.point": "スケッチ点を配置します。寸法、拘束、穴の中心、後のフィーチャの参照として使います。", + "help.sketch.point3d": "3D スケッチをオンにして、空間内に点を配置します。3D 曲線やパスの参照として使います。", + "help.sketch.polygon.circumscribed": "円の外側に接する正多角形を、中心から辺の中央までのサイズで描きます。六角ナットのように、二面幅が決まっているときに使います。", + "help.sketch.polygon.edge": "1辺の両端から正多角形を描きます。辺の長さと位置が決まっているときに使います。", + "help.sketch.polygon.inscribed": "円に内接する正多角形を、中心から角までのサイズで描きます。対角のサイズが決まっているときに使います。", + "help.sketch.project": "モデルのエッジ、面、頂点、ほかのスケッチの曲線を、このスケッチの平面に投影して取り込みます。リンクが保たれ、モデルが変わると追従します。", + "help.sketch.project_to_surface": "ほかのスケッチの曲線を、このスケッチの法線方向に沿って面へ投影し、リンクされた 3D 曲線にします。ロゴ、分割線、パスを曲面に載せるときに使います。", + "help.sketch.rectangle.center": "中心と1つの角から長方形を描きます。原点など、点を中心にした外形に使います。", + "help.sketch.rectangle.rounded": "4つの角をすべて同じ半径で丸めた長方形を描きます。角の丸いプレート、フタ、開口部に使います。", + "help.sketch.rectangle.three_point": "1辺と、反対側の1点から長方形を描きます。スケッチ軸に対して傾いた長方形に使います。", + "help.sketch.rectangle.two_point": "対角の2点から長方形を描きます。プレート、ブロック、ポケットの外形に使います。", + "help.sketch.scale": "スケッチの曲線と点を、基準点を中心に倍率で拡大縮小します。描き直さずにスケッチの一部のサイズを変えるときに使います。", + "help.sketch.slot.arc_center": "中心、始点、終点で決まる円弧に沿って、指定幅の曲線スロットを描きます。回転軸まわりの調整用スロットに使います。", + "help.sketch.slot.arc_three_point": "3点を通る円弧に沿って、指定幅の曲線スロットを描きます。スロットの経路が決まった点を通る必要があるときに使います。", + "help.sketch.slot.center_point": "中心から一方の端の円弧の中心まで、指定幅の直線スロットを描きます。点を中心にしたスロットに使います。", + "help.sketch.slot.center_to_center": "両端の円弧の中心の間に、指定幅の直線スロットを描きます。ネジの調整用スロットなど、中心間で寸法を指定するスロットに使います。", + "help.sketch.slot.overall": "一方の外端からもう一方の外端まで、指定幅の直線スロットを描きます。スロットの全長が重要なときに使います。", + "help.sketch.spline.control_point": "通らない制御点で形が決まる3次スプラインを描きます。点を動かして形を整える、滑らかで流れるような曲線に使います。", + "help.sketch.spline.control_point_5": "制御点で形が決まる5次スプラインを描きます。見えるスタイリング面など、より滑らかな曲率で曲線をつなぎたいときに使います。", + "help.sketch.spline.fit_point": "置いたすべての点を通る滑らかなスプラインを、開いた形または閉じた形で描きます。既知の点を通して形をなぞるときに使います。", + "help.sketch.spline3d": "3D スケッチをオンにして、点を通る滑らかな曲線を空間内に描きます。スケッチ平面から外れるスイープ パスやケーブルの経路に使います。", + "help.sketch.spun_profile": "軸まわりに回転したボディが描く外形を、スケッチ平面上に作成します。回転や図面のために、旋削部品のシルエットを得るときに使います。", + "help.sketch.text": "選んだフォント、高さ、角度でスケッチに文字を書きます。文字はパラメーターに追従させられます。押し出しやエンボスでラベルや文字にします。", + "help.sketch.transform": "スケッチ ジオメトリを、中心点まわりに拡大縮小、回転、移動を一度に行います。選択した対象の位置とサイズをまとめて変えるときに使います。", + "help.sketch.trim": "クリックした位置の前後で、最も近い交差の間にある曲線の部分を削除します。重なった線を整えて閉じた輪郭にするときに使います。", "help.solid.align": "選択した立体を動かし、その点、面、平面を別の場所の点、面、平面に合わせます。距離を測らずに部品を別の部品に当てて配置するときに使います。", + "help.solid.boundary_fill": "重なり合うツール ボディに囲まれた領域からソリッドを作成し、選んだ領域だけを埋めます。複数のボディが囲む空間から形状を作るときに使います。", + "help.solid.bounding_solid": "選択したボディを囲むボックスを作成します。余裕寸法も指定できます。部品の全体寸法の確認や、加工前の素材形状として使います。", + "help.solid.box": "長さ、幅、高さからボックスを作成します。角の点から、または点を中心に配置できます。簡単なブロック、仮の形状、フィーチャを切り込む元のボディに使います。", "help.solid.chamfer": "選択した辺を、指定した距離で平らに斜めに削ります。鋭い角を落とすときや、ピンやねじを入れやすくするときに使います。", + "help.solid.coil": "直径、巻数、高さまたはピッチと、丸または角の断面から、ばねのようならせん状のボディを作成します。ばね、コイル、らせん状の突起に使います。", "help.solid.combine": "複数の立体を結合したり、対象の立体から切り取ったり、共通する体積だけを残したりでき、工具の立体を残すこともできます。部品の結合、ある形での切り抜き、2つの立体が重なる範囲の確認に使います。", + "help.solid.cone": "底面の円と高さから円錐を作成します。上面にも半径を指定すると円錐台になります。テーパー、漏斗、皿穴、先端部に使います。", + "help.solid.cylinder": "半径または直径と高さから、点の上に軸方向に立つ円柱を作成します。シャフト、ピン、ボス、丸い素材に使います。", "help.solid.draft": "選択した面を、中立面から測った指定の角度だけ傾けます。成形品や鋳物の部品を型から抜けるようにするときに使います。", + "help.solid.emboss": "テキストやロゴなどのスケッチ プロファイルを、面から浮き出させるか面に彫り込みます。平面や円筒面の文字、ラベル、刻印に使います。", "help.solid.extrude": "スケッチの輪郭を指定した距離だけ立体方向に押し出し、材料を足したり削ったりします。平面の図形をブロック、突起、ポケットにするときに使います。", "help.solid.fillet": "選択した辺を、指定した半径のなめらかな円弧で丸めます。強度や持ちやすさ、見た目のために鋭い角を和らげるときに使います。", "help.solid.hole": "面上の指定した位置に、指定した直径の丸い穴をあけます。ねじのクリアランスやピン穴など、単純な丸い開口に使います。", @@ -1457,20 +1772,61 @@ "help.solid.move": "選択した立体、またはそのコピーを、指定した距離と角度で移動・回転します。立体の位置を変えるときや、別の場所にもう1つ作るときに使います。", "help.solid.offset_face": "選択した面を指定した距離だけ内側または外側へ動かし、周りの面もそれに合わせます。スケッチを編集せずに、壁を厚く、ポケットを深く、突起を高くするときに使います。", "help.solid.pattern.circular": "選択したオブジェクトを、指定した数と全体の角度で軸のまわりに繰り返し配置します。ボルト円、スポーク、フィン、歯などに使います。", + "help.solid.pattern.path": "フィーチャーまたはボディを、スケッチのパスに沿って個数と間隔を指定してコピーします。曲線エッジに沿った穴や、レールに沿った部品に使います。", "help.solid.pattern.rectangular": "選択したオブジェクトを、指定した数と間隔で1方向または2方向に繰り返し配置します。穴、リブ、ピン、脚の列や格子状の配置に使います。", + "help.solid.pipe": "スケッチ曲線の経路に沿って、中実または肉厚付きの中空の丸パイプを作成します。チューブ、ワイヤー、ケーブル、手すりに使います。", "help.solid.press_pull": "面をドラッグして材料を足したり削ったりし、辺をドラッグして丸めます。モデル上で直接すばやく変更するときに使います。", "help.solid.remove": "タイムラインのこの位置から先で、選択した立体をデザインから取り除きます。それより前のステップには残ります。不要になった切り取り用の立体など、補助の立体を外すときに使います。", "help.solid.replace_face": "選択した平らな面を平面または平行な面の位置へ動かし、立体はそこまで伸び縮みします。面を別の部品や作業平面と面一にするときに使います。", "help.solid.revolve": "スケッチの輪郭を軸のまわりに回転させ、丸い立体を作ります。軸、つまみ、ボウルなど、中心線まわりに丸い部品に使います。", + "help.solid.rib": "開いたスケッチ曲線に沿って、ボディの次の面まで届く薄い壁を追加します。成形品や 3D プリント部品などで、壁や角を補強するときに使います。", "help.solid.scale": "選択した立体を、全方向に同じ倍率、または軸ごとの倍率で拡大・縮小します。読み込んだ形状の大きさを変えるときや、収縮分を見込むときに使います。", "help.solid.shell": "立体の中をくり抜き、指定した厚さの壁を残します。選んだ面を開口にすることもできます。箱、カバーなどの薄肉の部品に使います。", + "help.solid.sphere": "中心点の周りに、半径または直径から球を作成します。ボール、つまみ、丸い端部に使います。", "help.solid.split_body": "平面、別の立体の面、またはスケッチの線で、立体を別々の立体に分割します。別々に印刷、加工、着色する部品を作るときに使います。", "help.solid.split_face": "選択した面を、平面、別の立体の面、またはスケッチの曲線に沿って分割します。立体そのものは切りません。面の一部にだけ抜き勾配、色、オフセットを付けるときに使います。", "help.solid.sweep": "スケッチの輪郭をパスに沿って動かし、立体を作ります。パイプ、レール、ハンドルなど、一定の断面で曲線をたどる部品に使います。", + "help.solid.thread": "円筒面に ISO メートルねじを追加します。表示上のねじにするか、ボディに切り込むかを選べます。ボルト、ねじ穴、3D プリントのねじ部品に使います。", + "help.solid.torus": "軸周りの大半径と、丸い断面の小半径からリングを作成します。O リング、取っ手、丸いビードに使います。", + "help.solid.web": "開いたスケッチ曲線ごとに、ボディの次の面まで届く薄い壁を追加します。ハウジングやトレイ内部の格子状の補強壁に使います。", + "help.surface.blend": "2つのボディのエッジを橋渡しするサーフェスを、両方に接線連続または曲率連続で作ります。隙間を越えて2つのサーフェスをなめらかにつなぐときに使います。", + "help.surface.boundary": "2〜4本のスケッチ曲線のループ、または曲線ネットワークを埋めるサーフェスを作ります。エッジで定義される自由曲面のパネルに使います。", + "help.surface.extend": "サーフェスをエッジの先へ、指定した距離または平面や面まで延長します。トリムやステッチの前に、サーフェスどうしを重ねるために使います。", + "help.surface.extrude": "スケッチ曲線またはプロファイルを指定した距離だけ押し出し、キャップのない壁だけのサーフェスにします。薄い壁や、切断・分割用のツールに使います。", + "help.surface.fair": "エッジを動かさずに、自由曲面の内部をなめらかにします。サーフェスの凹凸や、波打つ反射をならすときに使います。", + "help.surface.loft": "2つ以上の断面を順に通るサーフェスを、キャップなしで作ります。シェルや、異なる形状の間の移行部に使います。", + "help.surface.match": "サーフェスのエッジを作り直し、別のボディのエッジに接線または曲率を合わせてつなぎます。2つのサーフェスの継ぎ目をなめらかに閉じるときに使います。", + "help.surface.offset": "面を法線方向に指定した距離だけ離したコピーを、新しいサーフェスボディとして作ります。スキン、クリアランス、壁の反対側を作るときに使います。", + "help.surface.patch": "スケッチ領域またはエッジの閉ループを、平らな面またはなめらかに湾曲した面で埋めます。サーフェスボディの穴を塞ぐときに使います。", + "help.surface.reverse_normal": "サーフェスボディの面を裏返して、外側の向きを反対にします。面が内向きになっているとき、厚み付けやステッチの前に使います。", + "help.surface.revolve": "スケッチ曲線またはプロファイルを軸のまわりに回転させ、キャップのないサーフェスにします。ランプシェード、ボウル、ノズルなどの丸いシェルに使います。", + "help.surface.ruled": "エッジの連なりから、面の法線方向、接線方向、または指定した角度に、直線でできた帯を作ります。勾配のある壁、ランオフ、分割面に使います。", + "help.surface.stitch": "サーフェスボディを共有するエッジで縫い合わせ、閉じる場合はソリッドにします。複数のサーフェスを1つのボディにまとめるときに使います。", + "help.surface.sweep": "スケッチ曲線またはプロファイルをパスに沿って動かし、キャップのないサーフェスにします。雨どいやトリムなど、パスに沿う薄い形状に使います。", + "help.surface.thicken": "サーフェスボディに厚みを与えて、ソリッドにします。サーフェスから3Dプリントや機械加工ができる部品を作るときに使います。", + "help.surface.trim": "平面、別のサーフェス、スケッチ曲線でサーフェスを切断し、選んだ側を残します。ステッチの前にサーフェスを形に切り出すときに使います。", + "help.surface.unstitch": "ボディの面を、個別のサーフェスボディに分離します。ソリッドはサーフェスにばらばらになります。ボディの一部の面だけを作り直すときに使います。", + "help.surface.untrim": "面から穴を取り除くか、外側の境界をサーフェス本来の範囲に戻します。トリムした後で、元のサーフェス全体を取り戻すときに使います。", "help.third_party": "サードパーティライセンス", "help.timeline.compute_all": "タイムラインのすべてのフィーチャを最初から作り直します。モデルを更新し、どのフィーチャが失敗するかを確認するときに使います。", "help.timeline.delete": "選択したフィーチャをタイムラインから削除します。スケッチを削除すると、そこから作ったフィーチャも削除されます。不要になったステップを取り除くときに使います。", + "help.timeline.dependents": "フィーチャーと一緒に削除されるフィーチャーと、それがないと失敗するフィーチャーを一覧にします。フィーチャーを削除または変更する前に使います。", "help.timeline.play": "残りのフィーチャを一つずつ再生し、再構築のたびに0.5秒間停止します。このコマンドをもう一度実行するかEscキーで停止し、「最後へ」で直ちに最後へ移動します。", + "help.version": "バージョン {version}", + "help.view.apply": "ビューをフロント、トップ、アイソメなどの標準方向、または保存した名前付きビューに回転します。固定した角度からモデルを見るときに使います。", + "help.view.delete": "保存した名前付きビューを削除します。モデルは変更されません。", + "help.view.fit": "モデル全体、または選択したものがビューいっぱいになるように、ズームと移動をします。モデルが視界から外れたときに使います。", + "help.view.grid": "ビューポートのグリッドを表示または非表示にします。モデリング中の大きさと向きの目安として使います。", + "help.view.ground_shadow": "地面に落ちるモデルの影を表示または非表示にします。高さや位置を判断しやすくするときに使います。", + "help.view.home": "ビューをホームの方向に戻し、モデルをフィットさせます。決まったビューにすばやく戻るときに使います。", + "help.view.list": "デザインに保存されている名前付きビューを一覧にします。以前に保存したビューを探すときに使います。", + "help.view.navigate": "左に90度回転するなど、ステップごとにビューを回転、移動、ズームします。ドラッグではなく、カメラを正確に動かすときに使います。", + "help.view.navigation_bar": "ビューポート下部のナビゲーションバーを表示または非表示にします。広く使いたいときは非表示に、マウスでビューツールを使うときは表示にします。", + "help.view.rename": "保存した名前付きビューの名前を変更します。ビュー自体は変わりません。", + "help.view.save": "現在のカメラ位置を名前付きビューとしてデザインに保存します。スクリーンショット用など、後で同じ角度に戻るときに使います。", + "help.view.spin": "次のクリックまたはキー操作まで、モデルのまわりでビューを連続して周回させます。モデルをあらゆる方向から見せるときに使います。", + "help.view.tool": "オービット、パン、ズームのカメラツールを固定し、オフにするまで左ボタンのドラッグでビューを動かせるようにします。トラックパッドや、中ボタンのないマウスで使います。", + "help.view.visual_style": "モデルの描画方法(エッジ付きまたはなしのシェード、ワイヤーフレーム、隠線付き)を切り替えます。内部を見るにはワイヤーフレーム、すっきり見せるにはシェードを使います。", "history.sketch_under_constrained": "拘束不足(自由度 {count})", "history.sketch_under_constrained_one": "拘束不足(自由度 {count})", "hole_presets.confirm_delete": "削除を確認", @@ -1544,6 +1900,27 @@ "home.start_hint": "デザインを作成するか、最近使ったファイルを開くか、サンプルをご覧ください。", "home.whats_new": "新機能", "home.yesterday": "昨日", + "import_report.details": "詳細:", + "import_report.file_one": "ファイルにほかに 1 件の問題がありました。", + "import_report.file_other": "ファイルにほかに {count} 件の問題がありました。", + "import_report.hint": "作成元のプログラムからこれらのパーツを書き出し直すと直ることがあります。詳細は「警告メッセージをコピー」で確認できます。", + "import_report.left_out_one": "1 個の面を修復できず、欠けています。", + "import_report.left_out_other": "{count} 個の面を修復できず、欠けています。", + "import_report.needs_repair_one": "1 個のパーツはモデリングの前に修復が必要です。", + "import_report.needs_repair_other": "{count} 個のパーツはモデリングの前に修復が必要です。", + "import_report.not_imported_one": "1 個のパーツを読み込めませんでした。", + "import_report.not_imported_other": "{count} 個のパーツを読み込めませんでした。", + "import_report.not_shown_one": "1 個の面を描画できず、非表示です。", + "import_report.not_shown_other": "{count} 個の面を描画できず、非表示です。", + "import_report.open_one": "1 個のパーツは面の間にすき間があり、開いたボディとして読み込まれました。", + "import_report.open_other": "{count} 個のパーツは面の間にすき間があり、開いたボディとして読み込まれました。", + "import_report.refused_one": "1 個のパーツをソリッドにできず、読み込みませんでした。", + "import_report.refused_other": "{count} 個のパーツをソリッドにできず、読み込みませんでした。", + "import_report.repaired_one": "1 個のパーツの小さな不具合を修復しました。", + "import_report.repaired_other": "{count} 個のパーツの小さな不具合を修復しました。", + "import_report.solids": "{parts} 個のパーツのうち {solids} 個をソリッドとして読み込みました。", + "import_report.surfaces_one": "1 個のパーツをソリッドにできず、サーフェスとして読み込みました。", + "import_report.surfaces_other": "{count} 個のパーツをソリッドにできず、サーフェスとして読み込みました。", "install.button_tip": "SolidCraft をアプリとしてインストールします。専用のウィンドウで開き、オフラインでも使えます", "install.dock_1": "「ファイル」›「Dockに追加」を選びます。", "install.dock_2": "「追加」をクリックします。", @@ -1568,26 +1945,39 @@ "issue.note_save_failed": "スクリーンショットを保存できませんでした: {error}", "issue.note_saved": "スクリーンショットを保存しました。GitHubの下書きにPNGを添付してください。", "issue.save_screenshot": "スクリーンショットを保存…", + "joint.find_limits": "制限を検出", + "joint.find_limits_failed": "制限の検出がエラーで停止しました", + "joint.find_limits_hint": "このジョイントが動かす部品が他の部品に最初に触れる位置から制限を入力します。現在の位置から両方向に回転またはスライドして調べます。コピー上で行うため、OK を押すまで何も変わりません。", + "joint.find_limits_stale": "制限を検出した後にジョイントまたは設計が変更されました。もう一度検出してください", + "joint.finding_limits": "制限を検出中…", "joint.from_bodies_hint": "選択した各ボディを、位置はそのままで専用の新しいコンポーネントに移動します。", + "joint.limit_contact": "{side} {value}: {a} が {b} に接触", + "joint.limit_limit": "{side} {value}: 別の値またはジョイントの制限", + "joint.limit_loop": "{side} {value}: これを超えると閉ループが閉じません", + "joint.limit_range": "{side}: {range} 以内に接触なし、そのままにしました", + "joint.limit_turn": "{side} {value}: 1 回転以内に接触なし", + "joint.limits_overlapping": "この位置ですでに重なっています: {pairs}。さらに深く入り込んだ場合にのみ検出が止まります。", "joint.one_body": "両方の選択が {body} 上にあります。2 つ目は別の部品で選択してください。", "joint.one_component": "これらの部品は 1 つのコンポーネントのボディです: {bodies}。ジョイントはコンポーネント同士を動かすため、部品ごとに専用のコンポーネントが必要です。", "joint.rigid_group_one_component": "これらの {count} 個のボディは、すべて 1 つのコンポーネント内(またはデザイン自体)にあります。先に「{command}」を使用してください。", "joint.rigid_group_select_components": "2 つ以上のコンポーネントを選択してください。", "joint_move.blocked_hint": "Rigid合致、部品の固定状態、ジョイントの制限値、パラメーターでの拘束を確認してください。", "joint_move.blocked_title": "この部品は移動できません", - "joint_move.coarse": "軸に近い位置の回転刻み(°)", + "joint_move.coarse": "軸の近くのステップ", + "joint_move.conflict": "この部品のジョイントが他のジョイントと競合しています: {joint}。", + "joint_move.conflict_hint": "競合しているジョイントを編集、抑制、または削除して、他のジョイントで部品を配置できるようにしてください。", "joint_move.distance": "開始位置からの移動距離", "joint_move.done": "完了", - "joint_move.fine": "軸から遠い位置の回転刻み(°)", + "joint_move.fine": "軸から離れたステップ", "joint_move.fixed": "この部品には操作できるジョイントの自由度がありません。", "joint_move.help": "移動 — 矢印または円弧をドラッグ。Escでドラッグを取消。", - "joint_move.legacy_hint": "オフにすると従来の移動パネルを使います。", - "joint_move.precision": "破線ガイドの外側へ引くと回転を微調整できます。", + "joint_move.legacy_hint": "オフ:従来の移動パネル。", + "joint_move.precision": "破線のガイドの外へ引くと細かいステップになります。", "joint_move.rotation": "開始位置からの回転角", "joint_move.select": "面またはアセンブリ部品を1つ選択してから移動を実行してください。", "joint_move.settings": "アセンブリの移動", "joint_move.step": "刻み", - "joint_move.use_handles": "アセンブリの移動にジョイントの操作ハンドルを使う", + "joint_move.use_handles": "移動にジョイントのモーションハンドルを使用", "keymap.command_id": "コマンドID", "keymap.empty": "一致するコマンドはありません", "keymap.use_anyway": "ここでは{key}をそのまま使用", @@ -1647,6 +2037,11 @@ "material.selection.mixed": "異なる材料", "measure.at": "位置", "measure.item": "項目 {number}", + "measure.line_to_centre": "線から中心まで", + "measure.quick_copied": "測定値をコピーしました", + "measure.quick_copy": "クリックで測定値をコピー", + "measure.quick_edges": "エッジ {count} 本", + "measure.quick_faces": "面 {count} 個", "messages.ago_h": "{n} 時間前", "messages.ago_min": "{n} 分前", "messages.ago_s": "{n} 秒前", @@ -1671,6 +2066,8 @@ "motion.track_name": "トラック {number}", "nav.alias.help": "Shift+Alt+左ドラッグで回転、Shift+Alt+中ドラッグでパン、Shift+Alt+右ドラッグでズーム。中ドラッグでもパン、右ドラッグで回転。", "nav.blender.help": "中ドラッグで回転、Shift+中ドラッグでパン、Ctrl+中ドラッグでズーム。右ドラッグではカメラは動きません。", + "nav.creo.help": "マウスの中ボタンドラッグで回転、Shift+中ボタンで平行移動、Ctrl+中ボタンの上下ドラッグでズーム(下方向で拡大)。ホイールの回転でもズーム", + "nav.creo.label": "Creo", "nav.free_orbit.help": "マウスと3Dマウスで、極点を越えて回転し、ロールを保ちます。\nShiftによる軸スナップは無効になります。", "nav.free_orbit.label": "自由回転", "nav.free_orbit.snap_help": "マウスと3Dマウスで両極を越えて回転でき、ロールも保持されます。オービットのドラッグ中にShiftを押すと、視線方向とロールがスナップします。", @@ -1680,6 +2077,7 @@ "nav.hfss.help": "Alt+左ドラッグでパン、Shift+Alt+左ドラッグでズーム、何もない所からの Ctrl+左ドラッグで回転。", "nav.inventor.help": "中ドラッグでパン、Shift+中ドラッグで回転、Ctrl+中ドラッグでズーム、右ドラッグで回転。", "nav.maya.help": "Alt+左ドラッグで回転、Alt+中ドラッグでパン、Alt+右ドラッグでズーム。中ドラッグでもパン。", + "nav.nx.help": "中ボタンのドラッグで回転、Shift+中ボタンで平行移動(NXの中ボタン+右ボタン)、Ctrl+中ボタンでズーム(NXの中ボタン+左ボタン)。右ボタンのドラッグではカメラは動きません", "nav.openscad.help": "空きスペースで左ドラッグすると回転、Shift+左ドラッグで矩形選択、スケッチ ジオメトリはドラッグで編集。右または中ドラッグでパン、Shift+右または Shift+中ドラッグでズーム。", "nav.perspective.sketch": "スケッチ編集中は平行投影で表示されます。透視投影に切り替えるにはスケッチを終了してください。", "nav.right_drag_orbits.help": "オフ:右ドラッグではカメラは動かず、右ボタンはコンテキストメニューを開くだけです。マウス割り当てで SolidWorks を選ぶとオフになります。", @@ -1698,6 +2096,12 @@ "navbar.assistant": "アシスタント", "navbar.custom.add_slot": "{slot} を追加", "navbar.custom.always": "常に表示", + "navbar.custom.anchor.bottom_centre": "下中央", + "navbar.custom.anchor.bottom_left": "左下", + "navbar.custom.anchor.bottom_right": "右下", + "navbar.custom.anchor.top_centre": "上中央", + "navbar.custom.anchor.top_left": "左上", + "navbar.custom.anchor.top_right": "右上", "navbar.custom.available": "{available} · バーへドラッグ、または「追加」", "navbar.custom.buttons": "ボタン", "navbar.custom.compact": "コンパクト", @@ -1734,6 +2138,7 @@ "navbar.custom.reset_default": "既定値に戻す", "navbar.custom.right": "右へ移動", "navbar.custom.select": "スロットが選択されていません。バーのスロットを選択して移動、削除、表示の変更ができます。", + "navbar.custom.separator_hint": "ボタンのグループ間の区切りです。バーにドラッグするか、「追加」を押してください。いくつでも使用できます。", "navbar.custom.separators_full": "区切りは既に4個あります。", "navbar.custom.show": "ナビゲーションバーを表示", "navbar.custom.shows": "表示内容", @@ -1799,6 +2204,11 @@ "not a move": "移動ではありません", "not a number": "数値ではありません", "open a sketch first": "先にスケッチを開いてください", + "parameters.apply_live": "フィールドを離れるたびに変更を適用", + "parameters.apply_live_tip": "オフ: 変更は「適用」または「OK」まで保留され、その後すべてをまとめて一度だけ再構築します。「キャンセル」または Esc で破棄します。", + "parameters.held": "{count} 件の変更が適用待ちです", + "parameters.held_hint": "式と単位を編集してください。変更は「適用」または「OK」まで保留されます。", + "parameters.held_one": "1 件の変更が適用待ちです", "parts.automatic_name": "自動", "parts.dimension.across_flats": "二面幅", "parts.dimension.bore": "内径", @@ -1817,10 +2227,19 @@ "parts.family.button_head_cap_screw": "ボタンヘッド六角穴付きボルト", "parts.family.dowel_pin": "平行ピン", "parts.family.hex_bolt": "六角ボルト", + "parts.family.hex_cap_screw_inch": "六角ボルト(インチ)", "parts.family.hex_nut": "六角ナット", + "parts.family.hex_nut_inch": "六角ナット(インチ)", "parts.family.set_screw": "六角穴付き止めねじ 平先", "parts.family.socket_head_cap_screw": "六角穴付きボルト", "parts.family.washer": "平座金", + "parts.family.washer_sae": "平座金、SAE(小形)", + "parts.family.washer_uss": "平座金、USS(大形)", + "parts.holes": "穴 (省略可)", + "parts.placement_hint": "1 つ以上の穴を選ぶとそれぞれに部品を取り付けます。選ばずに OK を押すと原点に配置します", + "parts.system": "単位系", + "parts.system.inch": "インチ", + "parts.system.metric": "メートル", "pattern.alignment_2": "配置 2", "pattern.alignment_hint": "個数には元の図形が含まれます。中央配置ではコピーを両側に配置し、反転で偶数個の場合に多く配置する側を切り替えます。", "pattern.direction_1": "方向 1", @@ -1859,20 +2278,52 @@ "prefs.alt_frees_manipulators": "Alt / Option でマニピュレーターの矢印も自由に動かす", "prefs.anti_aliasing_amd_dx12": "起動時のチェックでマルチサンプリングでは何も描画されず、1×では正常に描画されたため、アンチエイリアシングを1×に設定しました。上で別の設定を選択できます。再起動後のチェックに合格すると、その設定が適用されます。", "prefs.anti_aliasing_note": "輪郭のぎざぎざを滑らかにします。", + "prefs.appearance.colour_vision_help": "意味を持つ色を変更します:スケッチ状態、軸、曲げ、解析、アイコン。", + "prefs.appearance.desktop_only": "デスクトップのみ", + "prefs.appearance.follow_help": "別のツールがファイルを書き換えると再読み込みします。", + "prefs.appearance.interface_scale": "インターフェースの倍率", + "prefs.appearance.next_themes": "次のテーマ", + "prefs.appearance.option_count": "{count} 個のオプション", + "prefs.appearance.option_count_one": "{count} 個のオプション", + "prefs.appearance.previous_themes": "前のテーマ", + "prefs.appearance.theme_count": "{count} 個のテーマ", + "prefs.appearance.theme_own": "テーマ独自", + "prefs.appearance.viewport_colours": "3D ビューの色", + "prefs.appearance.viewport_logo": "ビューポートとロゴ", "prefs.applies_on_restart": "再起動後に適用", "prefs.assistant": "アシスタント", + "prefs.assistant_connecting": "接続", + "prefs.assistant_follow_help": "スケッチのLook At操作で、ポインターに合わせてビューが移動します。", + "prefs.assistant_limit": "上限", + "prefs.assistant_limited": "制限あり", + "prefs.assistant_pointer_speed": "ポインターの速度", + "prefs.assistant_seconds": "秒", + "prefs.assistant_seconds_aria": "秒", + "prefs.assistant_use_care": "注意して使用", "prefs.auto_operation": "操作を自動で選択", - "prefs.auto_operation_note": "フィーチャーのウィンドウは、新しい形状が何に接するかから結合・新規ボディ・切り取りを選びます(手動で選ぶまで)。オフ:開いたときの操作のままです。", + "prefs.auto_operation_note": "材料が接触する対象に応じて結合、新規ボディ、切り取りを選びます。", "prefs.axes": "軸", "prefs.axis": "軸", + "prefs.blur_cost": "相対的な描画負荷です。バーが多いほど、通常は処理量が増えます。", + "prefs.blur_device": "このグラフィックスデバイスまたは描画経路では利用できません", + "prefs.blur_guard": "画面の応答性を保つため、ぼかしの品質を下げました。半径は変更されていません。", + "prefs.blur_off": "オフ", + "prefs.blur_reduce_transparency": "システムの透明度を下げる設定により無効です", + "prefs.blur_software": "ソフトウェア描画では利用できません (gpu-software)", + "prefs.blur_source": "このワークスペース表示では利用できません", + "prefs.blur_web": "このウェブ描画経路では利用できません", "prefs.bodies_folders": "ボディフォルダー", "prefs.bodies_folders_always": "常に表示", "prefs.bodies_folders_never": "表示しない", - "prefs.bodies_folders_several": "複数ボディのみ", + "prefs.bodies_folders_several": "複数", "prefs.bottom": "下", "prefs.bottom_centre": "下中央", "prefs.bottom_right": "右下", "prefs.browser": "ブラウザー", + "prefs.browser_components_open": "コンポーネントを最初から展開", + "prefs.browser_components_open_note": "ブラウザーのすべてのコンポーネントを以前と同じく最初から展開して表示します。オフの場合は展開するまで折りたたまれています。", + "prefs.browser_eye_left": "折りたたみ矢印の隣の目のアイコン", + "prefs.browser_eye_left_note": "ブラウザーの各行の表示切り替えを、行の右端の列ではなく、以前のように折りたたみ矢印の隣に表示します。", "prefs.browser_reveal_on_hover": "ホバーで表示", "prefs.browser_show_note": "「表示」はブラウザーを常に画面に表示します。「ホバーで表示」はポインターがその位置か左端の細いタブに来るまで隠し、ポインターが中にある間やそのメニューが開いている間は表示したままにします。", "prefs.browser_shown": "表示", @@ -1880,6 +2331,8 @@ "prefs.button_left": "左ドラッグ", "prefs.button_middle": "中央ドラッグ", "prefs.button_right": "右ドラッグ", + "prefs.carousel_next": "次へ", + "prefs.carousel_previous": "前へ", "prefs.choose_font": "フォントファイルを選択…", "prefs.click": "クリック", "prefs.contact_shading": "柔らかな接触陰影", @@ -1892,28 +2345,64 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "曲面", "prefs.curves": "曲面", + "prefs.cut_preview_tint": "除去される材料を赤で表示", + "prefs.cut_preview_tint_help": "プレビューでは、フィーチャーが除去する材料と置き換えられる形状を、赤い透過ゴーストで塗りつぶします。オフにすると、この塗りつぶしは完全に透明になり、輪郭のみが描画されます。", + "prefs.dark_parts_shading": "暗い部品の形状を保つ", + "prefs.dark_parts_shading_help": "リニア光と柔らかいスカイライトでビューをシェーディングし、暗い面が黒くつぶれずにグラデーションを保つようにします", "prefs.dead_zone_note": "斜線の帯はデッドゾーンです。この範囲内の動きは無視されます。", "prefs.default": "既定", - "prefs.design": "設計の既定値", - "prefs.design_note": "新しいデザインの初期設定です。開いているデザインはそれぞれの設定を保持します。", + "prefs.design": "デザイン", + "prefs.design_note": "新規デザインの初期設定。", + "prefs.design_tools.ask": "確認", + "prefs.design_tools.degrees": "度", + "prefs.design_tools.double_click_help": "リンクされたコンポーネントをその場で編集することもできます。", + "prefs.design_tools.ghost": "移動したパーツの元の位置をゴースト表示", + "prefs.design_tools.hole_moves_help": "面をもう一度選ぶと穴を削除せずに移動します。", + "prefs.design_tools.hole_snaps_help": "面の中央と円形エッジの中心。", + "prefs.design_tools.imported_files": "インポートしたファイル", + "prefs.design_tools.note": "通知", + "prefs.design_tools.off": "オフ", + "prefs.design_tools.placement_group": "レスト、ボス、スナップフィット", + "prefs.design_tools.rows": "行数", "prefs.devices": "3D マウス", "prefs.dialog_buttons": "ダイアログのボタン", "prefs.dialogs": "ダイアログ", "prefs.dialogs_edge": "ビューの端", "prefs.dialogs_left_column": "左の列", "prefs.dialogs_note": "コマンドダイアログを開く場所:ビューの端にドッキングするか、左の列でブラウザーと履歴の代わりに表示します。ダイアログを閉じるとブラウザーと履歴は元どおりに戻ります。", + "prefs.dimension_step_angle": "ウィンドウの矢印、上下キー、ホイールで角度に加える量", + "prefs.dimension_step_length": "ウィンドウの矢印、上下キー、ホイールで長さに加える量", + "prefs.dimension_steps": "ウィンドウの増減量", + "prefs.dimension_values": "寸法値の入力", + "prefs.dimension_values_note": "寸法値を入力する場所です。ウィンドウでは矢印で値を増減でき、寸法ツールは先に文字を配置します。", + "prefs.dimension_values_view": "ビュー内", + "prefs.dimension_values_window": "ウィンドウ", "prefs.display": "表示", "prefs.drawings": "図面", "prefs.edges": "エッジと陰影", "prefs.extend": "拡張", "prefs.extra_navigation": "何もない場所でCtrl+左ドラッグすると回転し、Spaceを押しながらドラッグすると移動します。", + "prefs.extrude_view_isometric": "押し出しを開いたときに等角ビューにする", + "prefs.extrude_view_return": "押し出しを閉じたときに元のビューに戻す", "prefs.follows_os": "OS の設定に従う", "prefs.font": "フォント", "prefs.font_fallback": "選択したフォントにない文字は組み込みフォントで表示し、ラベルが空の四角になるのを防ぎます。", "prefs.font_sample": "いろはにほへと · Ø12.50 mm · 45.0° · 0123456789", "prefs.font_unreadable": "選択したフォントを読み込めませんでした。", "prefs.general": "一般", - "prefs.general_note": "言語、保存、更新。", + "prefs.general.active": "使用中", + "prefs.general.crash_reports": "クラッシュレポート", + "prefs.general.edited": "変更あり", + "prefs.general.held": "保存対象", + "prefs.general.import": "インポート...", + "prefs.general.last_check": "最終確認: {time}", + "prefs.general.minutes": "分", + "prefs.general.name_setup": "この設定に名前を付ける", + "prefs.general.profile_name": "プロファイル名", + "prefs.general.save_new": "新規保存", + "prefs.general.step_import": "STEP とインポート", + "prefs.general.this_computer": "このコンピューター", + "prefs.general_note": "プロファイル、言語、ファイル、更新。", "prefs.gesture_orbit": "回転", "prefs.gesture_pan": "移動", "prefs.gesture_zoom": "ズーム", @@ -1922,18 +2411,40 @@ "prefs.graphics_card_auto": "自動", "prefs.graphics_card_missing": "保存されたグラフィックスカードが利用できないため、自動選択を使用します。", "prefs.graphics_card_restart": "SolidCraft の再起動後に有効になります。WGPU_ADAPTER_NAME がこの選択より優先されます。", + "prefs.graphics_card_unused": "保存したグラフィックスカードはこのウィンドウでは使われていません。使用中のカードは「ヘルプ › SolidCraft について」とステータス行に表示されます。自動を試すか、カード名の一意な部分を WGPU_ADAPTER_NAME に設定してください。", "prefs.graphics_note": "速度と滑らかさのバランスを調整します。各選択肢の効果をサンプルで確認できます。", + "prefs.graphics_page.current_view": "現在のビュー", + "prefs.graphics_page.fastest": "最速", + "prefs.graphics_page.fold_items": "項目を折りたたむ", + "prefs.graphics_page.in_view": "ビュー内", + "prefs.graphics_page.live_details": "リアルタイムの詳細", + "prefs.graphics_page.own_mix": "独自の組み合わせ", + "prefs.graphics_page.quick_measure": "クイック測定", + "prefs.graphics_page.reference_geometry_through_bodies": "ボディ越しの参照ジオメトリ", + "prefs.graphics_page.restart": "再起動が必要", + "prefs.graphics_page.sharpest": "最も鮮明", + "prefs.graphics_page.single_surface_analysis": "単一のサーフェス解析", + "prefs.graphics_page.status_chips": "ステータスチップ", + "prefs.graphics_page.subtitle": "速度と滑らかさのバランスを調整します。", + "prefs.graphics_page.supersampling": "スーパーサンプリング", + "prefs.graphics_page.supersampling_adaptive": "ビューが静止している間のみ", + "prefs.graphics_page.surfaces_edges": "サーフェスとエッジ", + "prefs.graphics_page.view_bar": "ビューバーにも表示", "prefs.graphics_presets_note": "プリセットは以下の設定をまとめて変更します。", + "prefs.hide_constraint_glyphs_zoomed_out": "ズームアウト時に拘束グリフを隠す", + "prefs.hide_constraint_glyphs_zoomed_out_note": "スケッチを十分にズームアウトすると、拘束グリフは表示されず画面を散らかしません。オフ: ズームに関係なく固定の画面サイズのままです。", "prefs.history": "履歴", "prefs.history_origin_bodies": "原点とボディを先頭に表示", "prefs.history_origin_bodies_note": "左側またはブラウザー下の履歴の先頭に、アクティブなコンポーネントのボディフォルダーと原点を、ブラウザーと同じ表示切り替えとメニュー付きで表示します。下部の履歴は変わりません。", "prefs.history_play_button": "履歴コントロールに「履歴を再生」ボタンを表示", "prefs.history_play_button_note": "履歴コントロールの「1ステップ戻る」と「1ステップ進む」の間に「履歴を再生」を追加します。コントロールを右クリックして表示/非表示を切り替えることもできます。", - "prefs.history_sketches": "スケッチ", + "prefs.history_sketches": "履歴のスケッチ", "prefs.history_sketches_in_order": "作成順", "prefs.history_sketches_note": "スケッチ:「フィーチャーの下」では、左側の履歴に名前が表示される幅があるとき、スケッチをそれから作成した最初のフィーチャーの下に 1 段字下げして表示します。下部のタイムラインは常に作成順です。", "prefs.history_sketches_under_feature": "フィーチャーの下", "prefs.hold_stop_snapping": "押している間スナップを解除", + "prefs.home_fit_size": "ホームと全体表示の大きさ", + "prefs.home_fit_size_note": "ホーム、全体表示、開いたデザイン、ナビゲーターでの視点変更がモデルを画面に収めるときに、モデルがビューに占める割合。下の設定のオン・オフにかかわらず適用されます。100 %: パネル、コンパス、ナビゲーションバーの間のビューをいっぱいに使います。", "prefs.icons_only": "アイコンのみ", "prefs.imported_file": "読み込んだファイル", "prefs.in_browser": "ブラウザー内", @@ -1942,13 +2453,38 @@ "prefs.interface_language": "表示言語", "prefs.interface_note": "SolidCraft の外観と各パネルの配置。", "prefs.interval_minutes": "{n} 分", + "prefs.invert_curved_roll_arrows": "カーブしたロール矢印を反転", + "prefs.invert_curved_roll_arrows_note": "キューブの隅にある2つのカーブした矢印は、画面内でビューをロールします。オン: 時計回りの矢印が反時計回りに、反時計回りの矢印が時計回りにロールします。オフ: 各矢印は、そのカーブの向きにビューをロールします。", + "prefs.invert_navigator_arrows": "ビューキューブの回転矢印を反転", + "prefs.invert_navigator_arrows_note": "キューブの周りの矢印が、矢印の指す方向にカメラを回します(Fusion や Inventor と同じ動き):左の矢印は右を指し、カメラを右に振ります。オフ: 矢印は、そのある面の方へキューブを回すため、左の矢印はカメラを左に振ります。カーブしたロール矢印は影響を受けません。", + "prefs.keep_work_on_tab_switch": "デザインを切り替えてもダイアログとツールを開いたままにする", + "prefs.keep_work_on_tab_switch_note": "各デザインのタブが、開いているダイアログまたはツール(選択や入力した内容を含む)とツールバーのタブを保持します。デザインに戻ると元のまま表示されます。オフ: デザインを切り替えるとそれらはキャンセルされ、モデル タブが表示されます。", "prefs.labels": "ラベル", + "prefs.language_system": "システム", "prefs.layout": "レイアウト", "prefs.layout_note": "コンパクトではパネルをウィンドウの端に固定します。ブラウザーの半透明表示はフローティングで使用できます。アシスタントの配置はアシスタントページで変更します。", + "prefs.layout_page.active_commands": "アクティブなコマンドを強調", + "prefs.layout_page.always": "常に", + "prefs.layout_page.card": "カード", + "prefs.layout_page.column": "列", + "prefs.layout_page.hover": "ホバー時", + "prefs.layout_page.icons_labels": "アイコン+ラベル", + "prefs.layout_page.ok_cancel": "OK とキャンセル", + "prefs.layout_page.on_hover": "ホバー時", + "prefs.layout_page.open": "開く位置", + "prefs.layout_page.origin_bodies": "原点とボディを上に表示", + "prefs.layout_page.panels": "パネル", + "prefs.layout_page.pinned_menus": "固定コマンドをメニューから除外", + "prefs.layout_page.play_history": "履歴の再生ボタン", + "prefs.layout_page.slot_count": "{max} スロット中 {count}", + "prefs.layout_page.view_corner": "ビューの隅にも表示", + "prefs.layout_page.window": "ウィンドウ", "prefs.left": "左", "prefs.left_click": "左クリック", "prefs.line_drag_draws_one": "押してドラッグすると線を 1 本描く", "prefs.line_drag_draws_one_note": "線ツールで押してドラッグし、離すと、押した位置から離した位置まで線を 1 本描いてそこで終わります。クリックでは従来どおり連続した線を描きます。オフ: ドラッグはクリックと同じく、離した位置に点を置きます。", + "prefs.line_hover_tangent_arc": "線の最後の点で止めると接線円弧に切り替える", + "prefs.line_hover_tangent_arc_note": "線ツールで線分を描いたあと、連続線の最後の点から一度離れて戻り、その点の上でポインターを止めると、次のクリックで接線円弧の終点を指定します。同じ操作で線に戻ります。オフ: 止めても何も起こりません。", "prefs.linked_designs": "リンクされたデザイン", "prefs.live_input": "現在の入力", "prefs.live_preview": "ライブプレビュー", @@ -1956,10 +2492,10 @@ "prefs.logo_accent": "アクセント", "prefs.logo_theme": "テーマの色", "prefs.max_file_size": "開けるファイルの最大サイズ", - "prefs.max_file_size_design": "デザインファイル", + "prefs.max_file_size_design": "開くファイルの上限: デザイン", "prefs.max_file_size_flag": "今回は --max-file-size {size} を指定して起動したため、SolidCraft を閉じるまでその値が適用されます。この設定は、そのオプションなしで起動したときに適用されます。", "prefs.max_file_size_note": "既定値は 512 MB と 256 MB、上限は 16 GB です。ファイルを開くには、サイズの数倍のメモリが必要です。大きなインポートを保持するデザインの保存と再読み込みには、デザインファイルの上限を上げる必要がある場合があります。", - "prefs.max_file_size_step": "STEP・インポートファイル", + "prefs.max_file_size_step": "開くファイルの上限: STEP・インポート", "prefs.max_file_size_web": "ウェブ版で開けるのは STEP・インポートファイルが 512 MB、デザインが 256 MB までです。ブラウザーのタブはそれ以上のファイルを保持できません。デスクトップ版では上限を上げられます。", "prefs.megabytes": "MB", "prefs.menu_grid": "大きなアイコン", @@ -1971,10 +2507,19 @@ "prefs.mouse_heading": "マウス", "prefs.mouse_mapping": "マウスの割り当て", "prefs.navigation": "ナビゲーション", + "prefs.navigation.axes_signed": "軸", + "prefs.navigation.cube_compact": "キューブ", + "prefs.navigation.device": "デバイス", + "prefs.navigation.free": "自由", + "prefs.navigation.orbit_style": "回転方式", + "prefs.navigation.radial_help": "右ボタンを長押しするかフリックすると、ツールのリングを表示します。", + "prefs.navigation.turntable": "ターンテーブル", "prefs.navigation_note": "マウス、トラックパッド、3Dマウスによるビューの操作。", + "prefs.navigator_fit": "ナビゲーターでの視点変更後にモデルを全体表示", + "prefs.navigator_fit_note": "キューブの面・角・矢印やギズモの軸をクリックすると、どの方向からでも全体が収まる一定の距離(外接球)からモデルの中心を見ます。オンの間はホームビューも同じズームと中心を使うため、その後に選んだ視点は向きだけが変わります。オフ: 視点はその場で回転し、注視点とズームを保ちます。", "prefs.network_host_remove": "削除", "prefs.network_locations": "デザイン内のネットワーク上の場所を許可", - "prefs.network_locations_note": "オフ: 別のコンピューター (\\\\server\\share) にあるデザインのリンク先ファイルは、ここに表示されたサーバー、または確認時に許可したサーバーからのみ開きます。", + "prefs.network_locations_note": "ファイルサーバーでデザインを管理する組織向け。オフの場合は許可したサーバーのみ。", "prefs.network_locations_section": "ネットワーク上の場所", "prefs.not_on_gpu": "この GPU は非対応", "prefs.on": "オン", @@ -1984,20 +2529,32 @@ "prefs.origin_plane_names": "原点平面の名前", "prefs.origin_plane_names_note": "ブラウザー、ダイアログ、一覧に表示される名前です。{top} は XY、{front} は XZ、{right} は YZ です (Z が上)。コマンド、スクリプト、保存されたデザインでは XY、XZ、YZ のままです。", "prefs.overall_speed": "全体の速度", + "prefs.parameter_list_rows": "パラメーター一覧の行数", + "prefs.parameter_list_rows_tip": "空の式入力欄で下矢印キーを押したときに表示するパラメータの最大数。", "prefs.persistent_ribbon_pressed": "有効なリボンコマンドを強調表示", "prefs.persistent_ribbon_pressed_help": "効果が有効な間、リボンのコマンドを強調表示します。無効にすると、従来の中立的な表示とコマンドのヘルプを保持します。", "prefs.perspective_fov": "画角", "prefs.placement": "配置", + "prefs.plugins_enabled": "有効", + "prefs.plugins_installed": "インストール済み", + "prefs.plugins_intro": "サンドボックス化されたアドオン。", + "prefs.plugins_show_folder": "プラグインフォルダーを表示", "prefs.prefer_free_sketch_points": "スケッチ点が重なったときは移動可能な点を優先する", "prefs.preview_choices": "選択した設定のプレビュー", + "prefs.preview_tint_new_faces": "プレビューで新しい面に色を付ける", + "prefs.preview_tint_new_faces_help": "ボディを変更するフィーチャーのプレビューで、追加される面をプレビュー色で描画できます。オフにすると、ボディはそのままの色で描画されます。", + "prefs.print_face_highlight": "造形面の強調", + "prefs.print_face_highlight_tip": "ビューでボディの造形面を色付けし輪郭を描く強さ。0 % で強調しません。", "prefs.profile_active": "使用中のプロファイル", "prefs.profile_applied": "プロファイルを適用しました。", "prefs.profile_changed": "プロファイルの保存後に設定が変更されています。「保存」でプロファイルに反映されます。", "prefs.profile_deleted": "プロファイルを削除しました。", - "prefs.profile_export": "エクスポート…", + "prefs.profile_export": "エクスポート", "prefs.profile_exported": "プロファイルをエクスポートしました。", - "prefs.profile_imported": "プロファイルをインポートしました。切り替えるには「使用中のプロファイル」で選択してください。", + "prefs.profile_imported": "プロファイルをインポートしました。", "prefs.profile_name_hint": "プロファイル名(例: ノートPC)", + "prefs.profile_operations": "処理をプロファイル", + "prefs.profile_operations_note": "SMLib の呼び出し、カーネル処理、フィーチャー、コマンド、インポートにかかる時間を記録します。エージェントは diagnostics.profile で読み取ります。", "prefs.profile_rename": "名前を変更", "prefs.profile_renamed": "プロファイルの名前を変更しました。", "prefs.profile_save": "保存", @@ -2011,26 +2568,71 @@ "prefs.quality_fastest": "最速", "prefs.quality_slowest": "最も低速", "prefs.quality_smoother": "より滑らか", + "prefs.quick_measure": "ビューの隅にクイック測定", + "prefs.quick_measure_note": "選択したものの寸法をビューの右下、履歴の上に表示します: エッジの長さ(円形のものは Ø と R)、面の面積、点の位置、2 つの項目の距離と角度、複数のエッジや面の合計。クリックでコピーします。", "prefs.render_previous_geometry_budget": "レンダープレビューで以前のジオメトリ予算を使用", "prefs.render_previous_geometry_budget_help": "デバイスに基づく予算の代わりに、以前の固定ジオメトリ上限(64ビットデスクトップでは512 MiB、その他では128 MiB)に戻します。", "prefs.reports_saved": "{n} 件保存済み", + "prefs.restore_page_defaults": "このページを既定値に戻す", + "prefs.ribbon_click_ends_tool": "実行中のツールのボタンをクリックすると終了する", + "prefs.ribbon_click_ends_tool_note": "使用中のスケッチツールの点灯したリボンボタンをクリックするとツールが終了し、ビューのクリックで再び選択できます。オフ: クリックするとツールが最初から開始されます。", "prefs.ribbon_reveal": "検索結果をリボンに表示", "prefs.ribbon_reveal_note": "コマンド検索で結果にポインターを合わせると、そのコマンドがリボンのどこにあるか(タブ、ボタン、またはパネルのドロップダウン内の行)を表示します。検索から開始したコマンドはそこで点滅し、ドロップダウンから実行中のコマンドはそのパネルに印が付きます。", "prefs.right_click": "右クリック", - "prefs.saving": "自動保存と復元", + "prefs.saving": "起動と保存", "prefs.scale_note": "ウィンドウ内では Ctrl + / Ctrl − でも変更できます。100% のボタンは 28 px です。", "prefs.scale_text": "拡大率と文字", "prefs.search": "設定を検索", "prefs.search_empty": "一致する設定がありません", + "prefs.section_hatch": "断面ハッチング", + "prefs.section_hatch_by_part": "部品ごと", + "prefs.section_hatch_one": "単一スタイル", "prefs.select": "選択", "prefs.select_one_item": "項目を 1 つ選択", + "prefs.select_other_hidden": "「他を選択」で非表示のジオメトリを選択", + "prefs.select_other_hidden_help": "オン: ポインター付近の非表示のボディやスケッチ、遮られたエッジを含めます。オフ: ポインター直下の表示中のジオメトリだけを元のリストに表示します。", "prefs.selecting": "選択", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift は追加のみ、Ctrl / Cmd は選択を切り替え", "prefs.shift_add_note": "オン:Shift は追加、Ctrl / Cmd は選択を切り替えます。オフ(既定):どちらも選択を切り替えます。", "prefs.shortcuts": "ショートカット", + "prefs.shortcuts_import": "インポート", + "prefs.shortcuts_intro": "各コマンドのキー。", + "prefs.shortcuts_not_assigned": "未割り当て", + "prefs.shortcuts_press": "キーを押してください...", "prefs.single_surface_analysis": "サーフェス解析を1つだけ使用", "prefs.single_surface_analysis_help": "オフの場合、サーフェスのシェーディングと連続性解析を同時に有効にできます。オンにすると、最後に開始または変更した解析が残ります。", + "prefs.sketch.align_points": "他のスケッチ点に整列", + "prefs.sketch.align_points_note": "作図中の線を両軸の点に同時に整列します。", + "prefs.sketch.auto_dimensions": "新しい形状にすべての寸法を付ける", + "prefs.sketch.auto_dimensions_note": "入力値と、形状を確定するすべての寸法。", + "prefs.sketch.auto_locate": "スケッチ原点を基準に配置", + "prefs.sketch.auto_locate_note": "すべての寸法を付ける場合。", + "prefs.sketch.center_arc": "中心点指定の円弧がカーソルに追従", + "prefs.sketch.click_selects": "クリックで選択", + "prefs.sketch.conflict_colour": "競合色", + "prefs.sketch.drawing": "作図", + "prefs.sketch.exit_keep": "維持", + "prefs.sketch.exit_previous": "開始前のビューに戻る", + "prefs.sketch.exit_unless_rotated": "回転した場合を除く", + "prefs.sketch.faces_edges": "面とエッジ", + "prefs.sketch.hide_glyphs": "ズームアウト時に記号を非表示", + "prefs.sketch.marks": "スケッチ内のマーク", + "prefs.sketch.note": "作図、スナップ、選択。", + "prefs.sketch.opening_closing": "開始と終了", + "prefs.sketch.prefer_free_points": "重なる場合は移動可能な点を優先", + "prefs.sketch.project_options": "投影オプションを先に確認", + "prefs.sketch.recent_snap": "2本のガイドの交点にスナップ", + "prefs.sketch.select_other_hidden": "他を選択で非表示のジオメトリも対象に", + "prefs.sketch.shortcut_cycles_modes": "ショートカットの再入力でモード切替", + "prefs.sketch.shortcut_cycles_modes_tip": "オフの場合はツールを再起動します。", + "prefs.sketch.snapping_guides": "スナップとガイド", + "prefs.sketch.state_icons": "状態アイコン", + "prefs.sketch.tracking_guides": "中心と中点のガイド", + "prefs.sketch.tracking_guides_note": "ホバーした中心やエッジの中点から、一時的な水平・垂直ガイドを表示します。", + "prefs.sketch.tracking_points": "スケッチ点からもガイドを表示", + "prefs.sketch.unless_turned_note": "回転していなければ戻る", + "prefs.sketch.whole_bodies": "ボディ全体", "prefs.sketch_align_points": "描画中にほかのスケッチ点に揃える", "prefs.sketch_align_points_note": "描画中、点が一つのスケッチ点と水平に、別の点と垂直に同時に揃い、点線のガイドが表示されます。クリックすると両方の整列が保持されます。オフ: 直前の点にのみ、一度に一方向だけ揃えます。", "prefs.sketch_conflict_colour": "競合するジオメトリを競合色で表示", @@ -2041,6 +2643,8 @@ "prefs.sketch_exit_view.previous": "前のビューに戻る", "prefs.sketch_exit_view.unless_rotated": "回転していなければ戻る", "prefs.sketch_exit_view_note": "「スケッチを終了」、キャンセル、Esc の 2 回押しの後にビューが移る先です。", + "prefs.sketch_face_activates_part": "部品の面にスケッチするとその部品をアクティブにする", + "prefs.sketch_face_activates_part_note": "別のコンポーネントのボディの面で始めたスケッチは、先にそのコンポーネントをアクティブにし、スケッチはそのコンポーネントに属してブラウザでその部品の下に表示されます。部品はその後もアクティブのままです。オフ:スケッチはアクティブなコンポーネントに属します。", "prefs.sketch_open_look_at": "スケッチを開いたときに正対させる", "prefs.sketch_open_look_at_note": "オフ: スケッチの作成や編集でビューを動かしません。必要なときは「正面視」でスケッチに正対します。", "prefs.sketch_recent_snap": "最近使った中心と中点へ自動スナップ", @@ -2054,6 +2658,8 @@ "prefs.sketch_tab_always_note": "スケッチを開いていないときも、スケッチ タブをリボンのモデルのすぐ後に表示します。そこにある作図ツールは、選択した平面または面に、なければ次に選ぶ平面にスケッチを開始し、そのスケッチでツールをすぐ使える状態にします。", "prefs.sketch_tracking_guides": "中心・中点の整列ガイド", "prefs.sketch_tracking_guides_note": "円の中心や直線辺の中点にカーソルを合わせ、水平・垂直に移動すると一時的な点線ガイドを表示します。", + "prefs.sketch_tracking_points": "作図中は端点と角からも整列ガイド", + "prefs.sketch_tracking_points_note": "作図ツールが点を待っている間、線や円弧の端点、長方形の角、独立した点にカーソルを合わせると、中心や中点と同じ一時的な点線ガイドを表示します。オフ: 中心と中点のみ。", "prefs.sketching": "スケッチ", "prefs.snap_drawing_note": "スケッチの描画中または点のドラッグ中に使用します。", "prefs.source": "入力元", @@ -2063,13 +2669,31 @@ "prefs.stand_up_unknown.ask": "ダイアログで確認", "prefs.stand_up_unknown.note": "メモを表示", "prefs.stand_up_unknown.off": "確認しない", - "prefs.stand_up_unknown_note": "ファイルのヘッダーに Y 上向きで保存することが知られているプログラム名がない場合の確認方法です。メモはファイルが横倒しに見える場合にのみ表示されます。「ダイアログで確認」は従来どおり、このようなファイルすべてについて確認します。", + "prefs.stand_up_unknown_note": "ファイルに既知のプログラム名がない場合の提案方法。", "prefs.status_bar": "ステータスバー", "prefs.status_bar_note": "ウィンドウの下端の細いバーに、編集中のもの、開いているスケッチの状態(その色で)、デザインの単位を表示します。単位をクリックすると変更できます。スケッチの状態はビューの隅には表示されなくなります。", "prefs.status_done": "完了", "prefs.status_error": "エラー", "prefs.status_selected": "選択中", "prefs.status_warning": "警告", + "prefs.structure.appearance": "外観", + "prefs.structure.appearance_note": "色、文字、アクセシビリティ。", + "prefs.structure.in_profile": "プロファイルに保存", + "prefs.structure.layout": "レイアウト", + "prefs.structure.layout_note": "ウィンドウ内の配置。", + "prefs.structure.look": "表示", + "prefs.structure.measure_pointer": "計測とポインター", + "prefs.structure.mouse3d": "3Dマウス", + "prefs.structure.mouse3d_note": "SpaceMouse と SpaceNavigator。", + "prefs.structure.navigation_note": "マウスとトラックパッド。3Dマウスは専用ページにあります。", + "prefs.structure.profile": "プロファイル", + "prefs.structure.profile_edited": "保存後に変更あり", + "prefs.structure.profile_hover": "設定プロファイルに保存されます", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "スケッチ", + "prefs.structure.tools": "ツール", + "prefs.structure.tools_note": "モデリングツールの動作。", + "prefs.structure.work": "作業", "prefs.supersampling_brief": "大きく描画して縮小するため、非常に鮮明になりますが負荷も増えます。", "prefs.tab_accent_note": "アクセント色はアクティブなタブに従います", "prefs.theme_file": "テーマファイル", @@ -2081,6 +2705,21 @@ "prefs.theme_follow_off": "オフ", "prefs.theme_follow_stop": "追従を停止", "prefs.theme_import_hint": "クリックしてテーマファイルを選ぶか、ここにドロップするか、テーマをコピーした状態で Ctrl+V(Mac では Cmd+V)を押します", + "prefs.theme_notice_dismiss": "非表示", + "prefs.theme_option_blur": "パネル背面のぼかし", + "prefs.theme_option_blur_help": "半透明パネルの背面のぼかしを物理ピクセル単位で指定します。0でオフになります。", + "prefs.theme_option_invalid": "{option} の保存値が無効なため、テーマの既定値を使用します。保存値は保持されます。", + "prefs.theme_option_opacity": "不透明度", + "prefs.theme_option_opacity_help": "フローティングパネルの不透明度を調整します。ビューポートの色に重なっても文字が読めるように下限が適用されます。", + "prefs.theme_option_tab_colours": "タブの色", + "prefs.theme_option_tab_colours_help": "リボンタブごとにテーマのパネルとビューポートの色を使用します。", + "prefs.theme_option_tab_fade_ms": "タブの切り替え", + "prefs.theme_option_tab_fade_ms_help": "タブの切り替え時にパネルとビューポートの色を徐々に変えます。0で即座に切り替えます。", + "prefs.theme_options_badge": "オプション", + "prefs.theme_options_more": "その他 · {count}", + "prefs.theme_options_newer": "このテーマには新しいバージョンの SolidCraft が必要です。更新後、元のテーマを再インポートしてオプション定義を復元してください。", + "prefs.theme_options_reset": "リセット", + "prefs.theme_options_unavailable": "このデバイスでは利用できません", "prefs.theme_paste": "テーマを貼り付け", "prefs.theme_paste_none": "クリップボードに SolidCraft のテーマがありません", "prefs.timeline_half_hour": "−30 分", @@ -2102,13 +2741,29 @@ "prefs.under_cursor": "カーソル下", "prefs.units_precision": "単位と精度", "prefs.updates": "更新", + "prefs.validation": "ボディのチェック", + "prefs.validation.each_feature": "フィーチャーごとに 1 回", + "prefs.validation.each_step": "各ステップの後", + "prefs.validation.label": "カーネルの完全チェック", + "prefs.validation.off": "オフ (試験的)", + "prefs.validation_note": "各ステップの後: スイープ、ブーリアン、ブレンドのたびにチェックします。\nフィーチャーごとに 1 回: 各フィーチャーの結果を 1 回チェックします。\nオフ (試験的): チェックしません。", + "prefs.value_boxes_in_view": "ハンドルの横に値を表示", + "prefs.value_boxes_in_view_tip": "押し出しの距離、フィレットの半径などをビュー内のボックスに表示します。", "prefs.view": "ビューの動作", "prefs.view_confirm_corner": "ビューの隅に OK とキャンセル", "prefs.view_confirm_corner_note": "ダイアログまたはスケッチを開いている間、ビュー右上のチェックとバツが、ダイアログの OK とキャンセルと同じ操作を行うか、スケッチを終了またはキャンセルします。ビューナビゲーターはその下に移動します。", "prefs.viewport": "ビューポート", + "prefs.viewport_analysis_status": "ビューポートの解析状態を表示", + "prefs.viewport_analysis_status_help": "有効な解析をビューポートの上部に表示し、各項目から凡例を開きます。Esc で最新の解析を解除します。無効にすると隅の凡例と従来の Esc 動作に戻ります。", "prefs.viewport_background": "背景", "prefs.viewport_background_colour": "色", "prefs.viewport_background_theme": "テーマのグラデーション", + "prefs.viewport_section_status": "ビューポートの断面状態を表示", + "prefs.viewport_section_status_help": "ビューポートに断面設定を表示します。Escape または有効なリボンボタンで断面を解除します。無効にすると従来の断面操作を維持します。", + "prefs.viewport_status_details": "ビューポートのライブ詳細", + "prefs.viewport_status_details_help": "標準の詳細カードで、実行中の解析と断面の設定を編集します。無効にすると、読み取り専用の解析凡例と断面ダイアログに戻ります。", + "prefs.viewport_status_summary": "ビューポートの状態項目をまとめる", + "prefs.viewport_status_summary_help": "3 個以上の状態項目を 1 つのサマリーバッジにまとめます。無効にすると、すべての項目を従来の行に表示します。", "prefs.wheel": "ホイール", "prefs.wheel_trackpad": "ホイールとトラックパッド", "prefs.workspace": "ワークスペース", @@ -2126,6 +2781,17 @@ "recovery.just_now": "たった今", "recovery.min_ago": "{count}分前", "recovery.never_saved": "未保存", + "refused.change": "{body} を変更できませんでした。", + "refused.cut": "{body} をカットできませんでした。", + "refused.face_curved": "曲面の 1 つがモデリングに使えません。", + "refused.face_flat": "平らな面の 1 つがモデリングに使えません。", + "refused.face_freeform": "自由曲面の 1 つがモデリングに使えません。", + "refused.face_rounded": "丸みのある面の 1 つがモデリングに使えません。", + "refused.faces_apart": "面どうしが十分に合っておらず、モデリングに使えません。", + "refused.intersect": "{body} と交差できませんでした。", + "refused.join": "{body} に結合できませんでした。", + "refused.repair": "パーツを修復", + "refused.show_face": "面を表示", "render.adaptive_absolute": "RGB 絶対誤差の下限", "render.adaptive_coverage": "被覆率の誤差目標", "render.adaptive_enable": "独立した予備サンプルで配分", @@ -2237,6 +2903,10 @@ "render.base_color": "ベースカラー・sRGB", "render.base_metallic": "金属成分の割合", "render.base_opaque_only": "この編集では不透明ボディの意味を保持します。透過には明示的なガラス設定を使用してください。", + "render.batch_all_shots": "すべてのショット ({count})", + "render.batch_empty": "すべてのショットをレンダリングする前にショットを保存してください。", + "render.batch_limit": "一度にレンダリングできるショットは32個までです。", + "render.batch_status": "{running} 実行中 · {waiting} 待機中", "render.bloom_enable": "表示ブルーム", "render.bloom_help": "正の線形ハイライトを3回の正規化フィルターで広げる表示専用の効果です。半径は出力ピクセル単位。sRGB変換前に加算され、レンズ・体積・収束の改善ではありません。生EXRは変わりません。", "render.bloom_opaque": "ブルームには不透明な出力が必要です。透明PNGを暗黙に統合せず拒否します。", @@ -2347,6 +3017,13 @@ "render.choose_look": "まず外観ライブラリで外観を選択", "render.chromatic_offset": "色収差のずれ", "render.clear_stage": "保存済みステージを削除", + "render.compare_divider": "比較の境界", + "render.compare_live": "ライブ", + "render.compare_live_preview": "ライブプレビュー", + "render.compare_render": "レンダー {number}", + "render.compare_side": "レンダー {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · リビジョン {revision} で取得", + "render.compare_swap": "入れ替え", "render.copy_request": "JSONをコピー", "render.cpu_aa_help": "空間サンプル数を増やすと輪郭が滑らかになりますが、描画時間も増えます。", "render.cpu_area_add": "CPU矩形ライトを追加", @@ -2987,7 +3664,9 @@ "render.output_ready": "レンダーの準備完了", "render.output_run_check": "チェックを実行", "render.output_size_limit": "{method}:各辺 {dimension} px、合計 {pixels} ピクセルまで。対応する最大サイズ:{width} × {height}。", + "render.output_size_method_profile": "{width} × {height} をレンダリングするには、{method} と CPUリソースプロファイル「{profile}」を選ぶか、より小さいサイズを選んでください。", "render.output_size_ok": "サイズOK · {width} × {height} px", + "render.output_size_profile": "{width} × {height} をレンダリングするには、CPUリソースプロファイル「{profile}」を選ぶか、より小さいサイズを選んでください。", "render.output_swap_orientation": "幅と高さを交換", "render.output_tools_inspector": "サイズと形式は出力インスペクターで編集してください。", "render.output_view_image": "画像を表示", @@ -3094,6 +3773,10 @@ "render.result_retained": "最後に完成した画像を表示しています。新しいレンダリングにはまだ置き換わっていません。", "render.result_sequence": "中間結果", "render.result_title": "レンダリング結果", + "render.results_choose": "保持した結果", + "render.results_label": "レンダー {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [更新前]", + "render.results_unnamed": "画像", "render.return_design": "設計に戻る", "render.review_stale": "この確認結果は古くなっています。適用前に再解決または再確認してください。", "render.ribbon_aging": "エイジング", @@ -3200,6 +3883,7 @@ "render.size_custom": "カスタム…", "render.size_full_hd": "フルHD", "render.size_hd": "HD", + "render.size_needs_profile": "{size}・「{profile}」が必要", "render.size_presets": "サイズプリセット", "render.size_presets_pending": "出力エディターとともに追加予定", "render.size_preview": "プレビュー", @@ -3465,11 +4149,11 @@ "select two components": "2つのコンポーネントを選択してください", "set by the sketch's lines": "スケッチの線で決まります", "settings.display_quality_note": "表示だけに影響します。設計や書き出しは変わりません。", - "settings.double_click_components": "コンポーネントをダブルクリックしてアクティブにする、またはリンクされたものをその場で編集する", + "settings.double_click_components": "コンポーネントをダブルクリックしてアクティブ化", "settings.frame_rate_details_note": "直近のフレーム時間のグラフ(描画した三角形数を重ねて表示)、フレーム時間のヒストグラム、GPU が描画した内容を追加します。ビューのフレームレートをクリックすると表示/非表示を切り替えます。", "settings.frame_rate_note": "ビューの右下に 1 秒あたりのフレーム数を表示します。", - "settings.insert_lists_open_designs": "デザインを挿入で、ほかのタブで開いているデザインを先に表示する", - "settings.measure_axis_distances": "計測のX・Y・Z距離を表示", + "settings.insert_lists_open_designs": "デザインを挿入で開いているデザインを先に表示", + "settings.measure_axis_distances": "計測で軸方向の距離を表示", "settings.measure_axis_distances_help": "計測ダイアログを開いている間、2点間距離に加えてワールドX・Y・Z軸方向の寸法線と距離を表示します。", "settings.msaa_applies_on_restart": "アンチエイリアスは次回 SolidCraft を起動したときに適用されます", "settings.msaa_reset": "{setting}: {requested}× はこのグラフィックスデバイスではサポートされていないため、{reset}× に変更しました(サポート: {supported})。", @@ -3479,7 +4163,7 @@ "settings.reset_intro": "次の設定はこのコンピューターでは使用できず、SolidCraft が起動できなくなるため変更されました:", "settings.reset_title": "設定が変更されました", "settings.supersampling_note": "ビューを高い解像度で描画してから縮小します。4K 未満の画面でエッジ、線、グリッドが滑らかになります。GPU の負荷が増えます(1.5× で約 2.25 倍、2× で 4 倍のピクセル)。", - "settings.update_changed_links": "タブに戻ったときに変更されたリンク先デザインを更新", + "settings.update_changed_links": "タブに戻ったときに変更されたリンクを更新", "settings.window_system_details": "詳細", "settings.window_system_note_now": "再起動後に適用されます。現在: {now}。", "settings.window_system_wayland_limited": "ネイティブ Wayland では一部の機能が制限されます。", @@ -3487,6 +4171,24 @@ "sheet.flange_type_contour": "輪郭", "sheet.flange_type_edge": "エッジ", "sheet.no_body": "板金ボディがありません。フランジ > Base で作成するか、板金に変換でプレートを板金に変換してください(広い平面を選択)。", + "sheet.personal_rules.confirm_delete": "削除を確認", + "sheet.personal_rules.delete": "削除", + "sheet.personal_rules.delete_prompt": "この個人用ルールを削除しますか?デザインに既にあるルールは変更されません。", + "sheet.personal_rules.full": "個人用ライブラリには既に64個のルールがあります。", + "sheet.personal_rules.invalid_name": "改行や制御文字を含まない短い名前を入力してください。", + "sheet.personal_rules.invalid_values": "ルールの値をすべて入力してください。各値はこのデザインで計算でき、板厚は正の値、K係数は0〜1である必要があります。", + "sheet.personal_rules.missing": "選択した個人用ルールは利用できなくなりました。", + "sheet.personal_rules.name": "ルール名", + "sheet.personal_rules.name_exists": "同じ名前の個人用ルールが既にあります。別の名前を指定してください。", + "sheet.personal_rules.name_hint": "一意の名前", + "sheet.personal_rules.overwrite": "選択した個人用ルールの変更を保存", + "sheet.personal_rules.rename": "名前を変更", + "sheet.personal_rules.rule": "個人用ルール", + "sheet.personal_rules.save": "新規保存", + "sheet.personal_rules.scope": "すべてのデザインで使えるようにプロファイルに保存します。", + "sheet.personal_rules.select": "ルールを選択", + "sheet.personal_rules.title": "個人用ルール", + "sheet.personal_rules.unsupported": "このルールには、このバージョンで使用できない値が含まれています。", "shortcut.json_error": "パラメータはJSON形式で指定してください: {error}", "shortcut.no_command": "コマンド`{id}`がありません。JSONの前のテキストはコマンドIDである必要があります", "shortcut.pin": "Sボックスの先頭にピン留め", @@ -3523,8 +4225,10 @@ "sketch_text.align_right": "右", "sketch_text.bold": "太字", "sketch_text.builtin_font": "{family}(内蔵)", + "sketch_text.formula": "= で始めるとパラメーターから文字列を組み立てられます: ='W' + number(Width)", "sketch_text.italic": "斜体", "sketch_text.loading_fonts": "インストール済みフォントを検索中…", + "sketch_text.no_bold": "組み込みフォントには太字がありません: インストール済みのフォントを選択してください", "sketch_text.on_path": "文字はパスに沿います: 位置は曲線で決まります", "sketch_text.path_clear": "文字を曲線から外す", "sketch_text.path_hint": "文字が沿うスケッチの曲線: ここをクリックしてから曲線をクリック", @@ -3555,11 +4259,20 @@ "the section's profiles must be in one sketch": "セクションのプロファイルは1つのスケッチ内にある必要があります", "the two origins are on the same component": "2つの原点が同じコンポーネント上にあります", "thread.automatic_size": "サイズを自動選択", + "thread.chamfer_depth_needed": "この形状では必須", "thread.designation": "ねじの呼び", - "thread.direction": "ねじの方向", + "thread.drill_range": "タップメーカーの下穴ドリルは {drill} mm です。めねじの規格の内径は {minor} mm です。{low}~{high} mm のドリルを使用できます。", + "thread.drill_range_custom": "下穴ドリルは外径からピッチを引いた {drill} mm です。めねじの規格の内径は {minor} mm です。{low}~{high} mm のドリルを使用できます。", + "thread.drill_range_taper": "タップメーカーの下穴ドリルは {drill} mm です。ねじ終端での規格の内径は {minor} mm です。{low}~{high} mm のドリルを使用できます。", + "thread.end_square": "直角", + "thread.fade_short": "1.25 P(ISO 3508)", + "thread.fade_standard": "2.5 P(ISO 3508)", + "thread.fits_the_face": "面に合うサイズ。例: {example}", + "thread.form_bspp": "管用平行ねじ G(ISO 228-1)", + "thread.form_bspt": "管用テーパねじ R、Rc(ISO 7-1)", + "thread.form_npt": "管用テーパねじ NPT(ASME B1.20.1)", + "thread.form_rp": "管用平行めねじ Rp(ISO 7-1)", "thread.iso_metric": "ISOメートルねじ", - "thread.left_hand": "左ねじ", - "thread.right_hand": "右ねじ", "thread.select_size": "サイズを選択", "timeline.delete_after_marker_one": "履歴マーカー以降の 1 個のフィーチャーを削除", "timeline.delete_after_marker_other": "履歴マーカー以降の {count} 個のフィーチャーを削除", @@ -3663,6 +4376,8 @@ "ui.3d_mouse_section": "3Dマウス", "ui.3d_mouse_show_in_view": "3Dビューに3Dマウスを表示", "ui.3d_mouse_show_in_view_tip": "左下に3Dマウスの絵を表示し、操作に合わせて動かします。", + "ui.3d_mouse_sketch_orbit": "3D マウスでスケッチを回転", + "ui.3d_mouse_sketch_orbit_tip": "スケッチを開いて正面から見ているときも、マウスと同じように 3D マウスでビューを回転します。オフ: ビューを傾けるまで、スケッチのパンとズームのみ行います。", "ui.3d_mouse_skip": "このデバイスではできません", "ui.3d_mouse_skip_tip": "この動きを両方向とも飛ばし、キャリブレーションから外します。", "ui.3d_mouse_speed": "3D マウス速度", @@ -3691,6 +4406,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "キャップを反時計回りにひねって保持し、離してください。", "ui.3d_mouse_switch_cap": "センターに戻るタイプとしてキャリブレーション", "ui.3d_mouse_switch_trackball": "トラックボールとしてキャリブレーション", + "ui.3d_mouse_use_direct": "直接ドライバーを使用", + "ui.3d_mouse_use_direct_tip": "spacenavd を経由せず、3Dマウスを直接 (hidraw) 読み取ります。", "ui.3d_mouse_view_axis": "ビューの軸", "ui.3d_mouse_view_off": "オフ", "ui.3d_mouse_view_off_tip": "3D マウスのドライバーのプロファイルがこの軸をオフにしているため、この軸の動きではビューは動きません。ここで他の軸の動きを選ぶと 2 つが入れ替わり、その動きではビューが動かなくなります。", @@ -3729,6 +4446,8 @@ "ui.agent_chat_auth_terminal": "ターミナルでこれを実行してから、もう一度「接続」を押してください:", "ui.agent_chat_auth_title": "エージェントにサインイン", "ui.agent_chat_cancel": "キャンセル", + "ui.agent_chat_cancel_timeout": "エージェントが停止要求に応答しなかったため、接続を切断しました。続行するには再接続してください。", + "ui.agent_chat_cannot_start": "インストールされていますが、起動しません: {error}", "ui.agent_chat_changes": "{n} 件の変更(元に戻すは1回)", "ui.agent_chat_changes_n": "{n} 件の変更", "ui.agent_chat_changes_of": "変更 {n}/{limit}", @@ -3737,11 +4456,13 @@ "ui.agent_chat_command": "エージェントのコマンド", "ui.agent_chat_connect": "接続", "ui.agent_chat_copy": "コピー", + "ui.agent_chat_copy_message": "メッセージをコピー", "ui.agent_chat_ctx_bodies": "ボディ", "ui.agent_chat_ctx_elements": "要素", "ui.agent_chat_ctx_features": "フィーチャ", "ui.agent_chat_ctx_more": "ほか{n}件", "ui.agent_chat_ctx_other": "その他", + "ui.agent_chat_custom_heading": "カスタムモデル", "ui.agent_chat_custom_hint": "標準入出力で Agent Client Protocol を話す任意のプログラム。シェルは使いません。", "ui.agent_chat_denied": "拒否しました", "ui.agent_chat_deny": "拒否", @@ -3785,8 +4506,16 @@ "ui.agent_chat_mode_all": "すべて", "ui.agent_chat_mode_ask": "確認", "ui.agent_chat_mode_edits": "編集", + "ui.agent_chat_model_custom": "カスタムを使用: {model}", "ui.agent_chat_model_no_tools": "{model} は SolidCraft のツールを使えず、チャットのみ可能です。ツール対応のモデルを選んでください。", + "ui.agent_chat_model_rejected": "エージェントは {model} を受け付けませんでした: {error}", + "ui.agent_chat_model_search": "モデルを検索…", "ui.agent_chat_model_tip": "エージェントが使うモデル。選択はこのエージェントに対して記憶されます。", + "ui.agent_chat_models_failed": "モデルを一覧表示できませんでした: {error}", + "ui.agent_chat_models_heading": "利用可能なモデル", + "ui.agent_chat_models_listing": "モデルを一覧表示中…", + "ui.agent_chat_models_none": "エンドポイントにモデルがありません", + "ui.agent_chat_models_not_a_list": "応答はモデル一覧ではありませんでした", "ui.agent_chat_new": "新しいチャット", "ui.agent_chat_new_confirm": "新しいチャットを始めますか? 現在のチャットは消去されます。", "ui.agent_chat_next_picture": "次の画像", @@ -3795,6 +4524,7 @@ "ui.agent_chat_no_images": "このエージェントは画像を受け付けません", "ui.agent_chat_no_picture": "クリップボードに画像がありません", "ui.agent_chat_no_tool_call": "モデルが SolidCraft のツールを使わなかったため、デザインは変更されませんでした。ツール呼び出しに対応したモデルを選んでください。エージェントチャットのガイドの「ローカルモデル」を参照してください。", + "ui.agent_chat_node_too_old": "Node.js {version} はこのエージェントには古すぎます。Node.js 20.10 以降をインストールしてから、更新を押してください。", "ui.agent_chat_none_found": "コーディングエージェントが見つかりません。次のいずれかをインストールしてから「再検索」を押してください:", "ui.agent_chat_none_found_short": "エージェントが見つかりません", "ui.agent_chat_not_installed": "未インストール", @@ -3821,9 +4551,12 @@ "ui.agent_chat_queued_stopped": "待機中(停止済み・未送信)", "ui.agent_chat_refresh": "再検索", "ui.agent_chat_refused": "エージェントには許可されていません: {reason}", + "ui.agent_chat_reinstall": "{agent} はインストールされています ({program}) が、SolidCraft が確認したときに起動しませんでした: {error}\nインストールが不完全か、別の種類のコンピューター用の可能性があります。`{install}` で再インストールし、ターミナルでバージョンが表示されることを確認してから、再検索を押してください。", "ui.agent_chat_remove": "待機から削除", "ui.agent_chat_remove_file": "このメッセージから外す", "ui.agent_chat_remove_imported": "このメッセージから外します。パーツはデザインに残ります (元に戻すで削除できます)", + "ui.agent_chat_reply_cut_off": "応答が終わる前に長さの上限に達したため、不完全な可能性があります。続けるか、もっと短く答えるようエージェントに頼んでください。", + "ui.agent_chat_reply_declined": "モデルはこのメッセージへの回答を断りました。", "ui.agent_chat_retry": "再試行", "ui.agent_chat_right": "右", "ui.agent_chat_save": "保存", @@ -3832,7 +4565,7 @@ "ui.agent_chat_send_now_tip": "エージェントの現在のステップを止めて、これを次に送信します(Ctrl+Enter)", "ui.agent_chat_setup_body": "SolidCraft は、このコンピューターにインストールされたコーディングエージェントと連携します。「環境設定 › AI」で選択してください。", "ui.agent_chat_setup_title": "アシスタントを設定", - "ui.agent_chat_side": "エージェントチャットの位置", + "ui.agent_chat_side": "チャットをドッキング", "ui.agent_chat_signed_in": "サインイン済み", "ui.agent_chat_state_auth": "サインインが必要", "ui.agent_chat_state_busy": "作業中…", @@ -3851,7 +4584,7 @@ "ui.agent_chat_undone": "(元に戻しました)", "ui.agent_chat_view_attached": "ビューを添付済み", "ui.agent_chat_waiting": "確認待ち", - "ui.agent_cursor": "エージェントカーソル", + "ui.agent_cursor": "エージェントのポインター", "ui.agent_cursor_speed": "エージェントカーソル速度", "ui.agent_off_thread": "エージェントのコマンド実行中もウィンドウを操作可能にする", "ui.agent_off_thread_note": "エージェント(AI パネルまたは MCP クライアント)の時間のかかるコマンドをウィンドウとは別に計算します。実行中もビューの回転や確認ができ、ビュー内の表示から停止できます。オフ:各コマンドはウィンドウのスレッドで実行され、終わるまでウィンドウは待ちます。", @@ -3882,24 +4615,29 @@ "ui.ai_copy_suffix": "コピー", "ui.ai_custom_url": "カスタム URL", "ui.ai_default": "既定", + "ui.ai_edit": "編集", + "ui.ai_edit_agent_title": "エージェントを編集", + "ui.ai_edit_gone": "このエージェントは削除されたため、保存するものはありません。", + "ui.ai_edit_tip": "このエージェントの名前、コマンド、エンドポイントを変更します。保存済みのキーは表示されません。", "ui.ai_http_busy": "エンドポイントが混雑しているか上限に達しています。後で再試行してください", "ui.ai_http_key": "エンドポイントがキーを拒否しました。「環境設定 > AI」で確認してください", "ui.ai_http_not_found": "エンドポイントまたはモデルが見つかりません。ベース URL とモデル名を確認してください", "ui.ai_http_too_large": "会話がこのエンドポイントには大きすぎます。新しいチャットを始めてください", "ui.ai_key": "API キー", "ui.ai_key_hint": "任意。システムのキーチェーンに保存", + "ui.ai_key_keep_hint": "空のままにすると保存済みのキーを使い続けます", "ui.ai_key_needs_https": "キーは HTTPS 経由、またはこのコンピューター宛てにのみ送信されます。", "ui.ai_key_note": "システムのキーチェーンに保存され、SolidCraft の設定には保存されません。ローカルサーバーの場合は空欄のままにします。", "ui.ai_keychain_error": "システムのキーチェーンが拒否しました: {error}", "ui.ai_kind": "種類", - "ui.ai_mode_all": "すべて許可", + "ui.ai_mode_all": "すべて実行", "ui.ai_mode_all_note": "確認なしで実行します。クラッシュレポートは引き続き対象外で、フォルダー制限も有効です。", "ui.ai_mode_all_warning": "エージェントは確認なしでデザインの保存・上書き・エクスポート・置き換えができます。信頼できるエージェントで、保存済みのデザインに対してのみ使ってください。", - "ui.ai_mode_ask": "毎回確認", + "ui.ai_mode_ask": "先に確認", "ui.ai_mode_ask_note": "デザインへのすべての変更とファイル操作が、あなたの許可を待ちます。", - "ui.ai_mode_edits": "モデル編集を自動許可", + "ui.ai_mode_edits": "編集を許可", "ui.ai_mode_edits_note": "モデリングコマンドは確認なしで実行されます。保存・開く・エクスポートなどのファイル操作や破壊的な操作は引き続き確認します。", - "ui.ai_mode_global": "上の設定に従う", + "ui.ai_mode_global": "上の設定と同じ", "ui.ai_model": "モデル", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "これらの設定は SolidCraft のツールに適用されます。エージェント自身のツール(シェル、ファイル編集)は、エージェントにモードがある場合にチャットパネルのヘッダーで選ぶエージェント自身のモードに従います。", @@ -3914,14 +4652,18 @@ "ui.ai_permissions": "権限", "ui.ai_preset": "プリセット", "ui.ai_protocol": "プロトコル", + "ui.ai_reasoning_effort": "推論の強度", + "ui.ai_reasoning_effort_field_hint": "空 = プロバイダーの既定値", + "ui.ai_reasoning_effort_hint": "任意。エンドポイントに `reasoning_effort` として送信されます。許可される値はプロバイダーによって異なります(例: `low`、`high`、`max`)。ここで設定した値が SolidCraft に置き換えられることはありません。空のままなら何も送信されず、プロバイダーの既定値が使われます。", "ui.ai_remove": "削除", "ui.ai_request_timed_out": "モデルの応答に {seconds} 秒以上かかりました。このエンドポイントのリクエストのタイムアウトは、環境設定 › アシスタントで長くできます。", "ui.ai_request_timeout": "リクエストのタイムアウト", "ui.ai_request_timeout_hint": "このエンドポイントへのモデルリクエスト1回にかけられる時間です(30秒〜1時間)。遅いローカルモデルでは長くしてください。", "ui.ai_reset": "リセット", + "ui.ai_save": "保存", "ui.ai_settings": "AI 設定…", "ui.ai_show_features": "AI 機能を表示", - "ui.ai_show_features_note": "エージェントチャット: 普段使っているコーディングエージェント、または選んだモデルのエンドポイントが、開いているデザインを操作するパネルです。オフ: AI ボタン、ショートカット、メニュー項目、パネルは表示されず、検索も起動も行いません。", + "ui.ai_show_features_note": "オフにするとアシスタントをすべて非表示にし、何も起動しません。以下の項目はすべて無効表示になります。\n\nエージェントチャット: 普段使っているコーディングエージェント、または選んだモデルのエンドポイントが、開いているデザインを操作するパネルです。オフ: AI ボタン、ショートカット、メニュー項目、パネルは表示されず、検索も起動も行いません。", "ui.ai_switch_tip": "この会話のエージェントを切り替え", "ui.ai_test": "テスト", "ui.ai_test_acp_ok": "応答あり: {agent}", @@ -3955,7 +4697,7 @@ "ui.ai_tool_sum_then": "{first}、続いて {next}", "ui.ai_tool_unfold": "クリックして結果を表示", "ui.ai_tool_waiting": "待機中", - "ui.ai_toolbar_button": "アプリケーションバーにアシスタントボタンを表示", + "ui.ai_toolbar_button": "アプリケーションバーのアシスタントボタン", "ui.ai_toolbar_button_note": "アプリケーションバーのアシスタントボタン。Ctrl+Shift+A と表示メニューからもパネルを開けます。", "ui.ai_undo_tip": "このメッセージでエージェントが行った変更を、1回でまとめて元に戻します", "ui.ai_url_hint": "https://example.com/v1", @@ -4002,11 +4744,14 @@ "ui.centerline": "中心線", "ui.chain": "チェーン", "ui.chamfer": "面取り", + "ui.chamfer_angle": "面取り角度", + "ui.chamfer_depth": "面取り深さ", "ui.chamfer_type": "面取りタイプ", "ui.change_workspace": "ワークスペースの変更", "ui.circle": "円", "ui.circular_pattern": "円形パターン", "ui.clear": "クリア", + "ui.clear_print_face": "造形面を解除", "ui.clear_recent": "最近使った項目をクリア", "ui.clear_the_selection": "選択をクリア", "ui.click_selects_whole_bodies": "クリックでボディ全体を選択", @@ -4031,10 +4776,16 @@ "ui.colour_vision_sample": "サンプル", "ui.colour_vision_tritan": "3型色覚(T型)", "ui.colour_vision_tritan_tip": "青を感じにくい、または感じない場合に", + "ui.comb_length": "コームの長さ", + "ui.comb_length_tip": "歯の長さ: 自動の長さの倍率です。自動の長さでは、いちばん長い歯が表示中の曲線の大きさの 5 分の 1 になります。", + "ui.comb_teeth": "歯の数", + "ui.comb_teeth_tip": "各コームの歯の数です。曲線に沿って等間隔に並びます。歯を増やすと、曲率の変わり方がより細かく見えます。", "ui.combine": "結合", "ui.coming_later": "準備中", "ui.command_done": "{command} 完了", "ui.command_palette_hint": "コマンドを入力(例: {example})— または S キーで検索", + "ui.components_from_bodies_hint": "選択した各ボディと同じ名前のコンポーネントを、アクティブなコンポーネントの下に作成します。", + "ui.components_from_bodies_required": "ボディを1つ以上選択してください。", "ui.concentric": "同心", "ui.cone": "円錐", "ui.conic_curve": "円錐曲線", @@ -4047,15 +4798,30 @@ "ui.construction.contact_hint": "接線: 円/円弧または開いたスプライン/円錐曲線を選び、接点を選択 (自由曲線は端点のみ)", "ui.construction.external_hint": "接線: 円または円弧、外部点、必要な解の順に選択", "ui.construction.free_hint": "補助直線: 2点をクリック。右クリックで最初から", + "ui.construction.normal_needs_length": "無限直線は常に補助線です。通常の線を描くには長さを入力", "ui.construction.point_hint": "補助直線: 通過点をクリック", "ui.construction.reference_hint": "補助直線: 直線、点の順に選択。右クリックで参照を変更", "ui.construction.ribbon_label": "補助線", + "ui.construction.side_hint": "補助直線: 線を伸ばす側をクリック。右クリックで最初から", "ui.context_menu": "コンテキスト メニュー", + "ui.continuity_crease": "折れ", + "ui.continuity_curvature": "曲率", + "ui.continuity_curvature_change": "曲率変化", + "ui.continuity_curvature_change_tip": "曲率変化 (G3): 境目で曲率の変化もなめらかです。", + "ui.continuity_curvature_tip": "曲率連続 (G2): 映り込みが折れずに通ります。", "ui.continuity_g0": "G0 折れ", "ui.continuity_g1": "G1 接線", "ui.continuity_g2": "G2 曲率", "ui.continuity_gap": "隙間", + "ui.continuity_position": "位置", + "ui.continuity_position_tip": "位置 (G0): 面はつながりますが、境目に折れがあります。", + "ui.continuity_smooth_curvature_change": "なめらかな曲率変化", + "ui.continuity_smooth_curvature_change_tip": "なめらかな曲率変化 (G4): 境目で曲率の変わり方そのものもなめらかに続きます。", + "ui.continuity_tangent": "接線", + "ui.continuity_tangent_tip": "接線 (G1): 折れはありませんが、境目で曲率が飛びます。", "ui.copy": "コピー", + "ui.copy_details": "詳細をコピー", + "ui.copy_details_tip": "調べたり報告したりできるよう、メッセージ全文をコピーします。", "ui.corner": "コーナー", "ui.corners": "コーナー", "ui.cosmetic_thread_markings": "ねじの簡略表示", @@ -4077,6 +4843,8 @@ "ui.dark": "ダーク", "ui.default_modelling_orientation": "モデリングのデフォルト方向", "ui.delete": "削除", + "ui.delete_select_first": "先に削除するものを選択してください: フィーチャ、ボディ、コンポーネント、スケッチ ジオメトリ", + "ui.dependents_select_first": "先に、依存先を表示する対象を選択してください", "ui.depth": "深さ", "ui.design": "デザイン", "ui.design_properties.author": "作成者", @@ -4091,6 +4859,40 @@ "ui.design_properties.project": "プロジェクト", "ui.design_properties.revision": "リビジョン", "ui.design_saved": "{path} に保存しました", + "ui.details_access_caption": "選択した方向から工具が各面に届くかどうかを表示します。", + "ui.details_angle": "角度", + "ui.details_continuity_caption": "選択した継ぎ目を編集します。他の継ぎ目の設定は変更されません。", + "ui.details_continuity_stale": "以前の形状です。この継ぎ目を編集または画面にフィットするには、解析を再実行してください。", + "ui.details_copy_list": "リストをコピー", + "ui.details_curvature": "曲率許容差", + "ui.details_curvature_caption": "面は局所的な曲率半径に応じて色分けされます。", + "ui.details_direction": "工具方向", + "ui.details_draft_caption": "面は抜き方向に対する角度に応じて色分けされます。", + "ui.details_edit_seam": "継ぎ目を編集", + "ui.details_fixture": "UIコンポーネントの表示例 — サンプルデータのみ", + "ui.details_fixture_caption": "説明用の値を用いたUIコンポーネントの表示例です。モデルの解析結果ではありません。", + "ui.details_fixture_problem": "問題を示す検出結果の例", + "ui.details_fixture_readout": "測定値の例", + "ui.details_flip": "反転", + "ui.details_gap": "間隔", + "ui.details_hatch": "切断面をハッチング", + "ui.details_jump": "曲率の不連続", + "ui.details_key": "凡例", + "ui.details_offset": "オフセット", + "ui.details_plane": "平面", + "ui.details_pull": "抜き方向", + "ui.details_radius": "半径", + "ui.details_readout": "測定値", + "ui.details_samples": "サンプル数", + "ui.details_seam": "{body} · エッジ {edge}", + "ui.details_settings": "設定", + "ui.details_sharp_gap": "角が鋭い、または間隔あり", + "ui.details_show_all": "すべて表示({count} 件)", + "ui.details_smooth": "滑らか", + "ui.details_stripes": "縞模様", + "ui.details_target": "形状を画面にフィット", + "ui.details_worst_seams": "連続性の悪い継ぎ目", + "ui.details_zebra_caption": "反射した縞模様で、面のつながりの滑らかさを確認できます。", "ui.diameter": "直径", "ui.dimension": "寸法", "ui.direct_interaction": "ダイレクト操作", @@ -4135,39 +4937,78 @@ "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", "ui.edit_in_place_wait": "デザインで実行中の処理が終わるまでお待ちください", "ui.edit_section_analysis": "断面解析を編集", + "ui.edit_sketch_empty": "編集できるスケッチはありません", "ui.ellipse": "楕円", "ui.emboss_wrap_note": "サポートされる円柱に接する直交線のプロファイルは自動的に巻き付けられます。対象を選ぶには壁を選択してください。", + "ui.end": "終端", "ui.end_radius": "終了半径", "ui.end_scale": "終端スケール", + "ui.ends": "端部", "ui.entities": "エンティティ", "ui.equal": "等しい", "ui.equation_end": "終了", "ui.equation_explicit": "陽関数", "ui.equation_form": "形式", "ui.equation_note": "変数は単位のない数値です。sin(t) はラジアンとして扱います。単位のない結果はデザインの単位になります。", + "ui.equation_note_range": "変数は範囲と同じく長さです。長さのパラメータと組み合わせられます。sin() には長さで割って渡します。単位のない結果はデザインの単位になります。", "ui.equation_parametric": "パラメトリック", + "ui.equation_variable_unit": "変数に範囲の単位を持たせる", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "等価半径", "ui.expand": "展開", + "ui.explode_needs_two_components": "分解図はコンポーネント同士を引き離すため、デザインに 2 つ以上のコンポーネントが必要です(新規コンポーネント、デザインを挿入、またはボディからコンポーネントを作成)", "ui.exportDxf": "DXF をエクスポート…", "ui.export_ellipsis_keymap": "エクスポート…", "ui.export_keymap_tip": "ショートカット、Sボックスのお気に入り、ツールバー設定をファイルに保存", "ui.extend": "延長", + "ui.extent": "範囲", "ui.extent_type": "範囲タイプ", "ui.extract_component": "ファイルに抽出…", "ui.extract_design_changed": "ファイルの選択中にデザインが変更されました。ファイルへの抽出をやり直してください。", "ui.extract_done": "コンポーネントは独立したデザインになり、ここにリンクされました。", "ui.extrude": "押し出し", "ui.extrude_auto_to_object": "選択した対象まで押し出し", - "ui.extrude_auto_to_object_tip": "押し出しでプロファイルを選択した後、その平面外の面・頂点・平行な平面を選ぶと、範囲タイプが「オブジェクトまで」に切り替わります", + "ui.extrude_auto_to_object_tip": "面、頂点、平行な平面を選ぶと範囲が「オブジェクトまで」に切り替わります。", "ui.factor": "倍率", + "ui.fade": "切り上げ", + "ui.fade_length": "切り上げ長さ", "ui.feature_history": "フィーチャー履歴", "ui.feature_options": "フィーチャーオプション", "ui.features": "フィーチャー", "ui.file": "ファイル", "ui.fillet": "フィレット", + "ui.fillet_corner_ball": "ボール", + "ui.fillet_corner_ball_tip": "転がるボールの球面の一部で、各フィレットに接します (G1)。", + "ui.fillet_corner_curvature_tip": "曲率 (G2): なめらかなパッチ。コーナーを各エッジに沿ってセットバック分 (入力しなければ半径の {factor} 倍) 後退させてパッチで埋め、映り込みが折れずに通ります。", + "ui.fillet_corner_needs_constant": "スムーズパッチのコーナー (G2) には、一定の半径と厳密な半径フィットが必要です。", + "ui.fillet_corner_patch": "スムーズパッチ", + "ui.fillet_corner_patch_tip": "曲率連続 (G2): コーナーを各エッジに沿って後退させてパッチで埋め、映り込みが折れずに通ります。", + "ui.fillet_corner_tangent_tip": "接線 (G1): 転がるボールのコーナー。転がるボールの球面の一部で、各フィレットに接します。", + "ui.fillet_error_corner": "ここではなめらかなコーナーを作れませんでした。別のセットバックか、接線のコーナーを試してください。", + "ui.fillet_error_failed": "このフィレットをこれらのエッジに作れませんでした。別の半径を試すか、一度に丸めるエッジを減らしてください。", + "ui.fillet_error_setback_short": "このコーナーのパッチにはセットバックが短すぎます。{least} 以上で作れます。より長いセットバックを試してください。", + "ui.fillet_error_too_large": "これらのエッジの隣の面に対して半径が大きすぎます。小さい半径を試すか、「面の境界」を「最大半径」にしてください。", + "ui.fillet_fit": "面の境界", + "ui.fillet_fit_exact": "正確な半径", + "ui.fillet_fit_needs_constant": "半径フィットには一定の半径が必要です。", + "ui.fillet_fit_reduce": "最大半径", + "ui.fillet_fit_taper": "狭めた半径", + "ui.fillet_fit_tip": "半径がエッジの隣の面で収まる大きさを超えるとき。\n正確な半径: 指定どおりの半径。収まらなければ丸めずに理由を知らせます。\n最大半径: 各エッジを収まる最大の半径で丸めます。\n狭めた半径: 半径を保ち、面が足りない所だけフィレットを細くします。", + "ui.fillet_options_tip": "正接チェーン: 選んだエッジからなめらかに続くエッジも丸めます。\nプレビュー: 編集中に結果をビューに表示します。", + "ui.fillet_setback": "セットバック", + "ui.fillet_setback_hint": "{factor} × 半径", + "ui.fillet_setback_least": "{least} より大きく", + "ui.fillet_setback_tip": "なめらかなコーナーパッチが始まる位置: コーナーから各エッジに沿った距離。既定値は半径の {factor} 倍。最小セットバック (セットバックなしでラウンド同士が交わる位置。面どうしが直角なら半径) より大きくする必要があります。", + "ui.fillet_smooth_radius": "半径をなめらかに変化", + "ui.fillet_turn": "曲がり角", + "ui.fillet_turn_mitre": "留め継ぎ", + "ui.fillet_turn_swept": "回転", + "ui.fillet_turn_tip": "2 つのフィレットが間にある鋭いコーナーエッジを回り込む所(ボスの根元のフィレットが立ち上がりエッジを回る所など)。\n留め継ぎ: フィレットは延びて留め継ぎで出会います。\n回転: フィレットはコーナーエッジで止まり、その周りを回ります。コーナーは両方に接するトーラスです。同じ半径のフィレットが、まっすぐな凸のコーナーエッジを回る場合のみ。", + "ui.fillet_type_choices_tip": "一定の半径: エッジ全体で一つの半径。\n弦長: 面がどんな角度で交わっても、フィレットの幅が同じ。\n可変半径: 両端の半径と、追加すればエッジ沿いの半径。\n曲率連続: 平面と接する所で映り込みが折れない断面 (G2)。\nスプライン: エッジ沿いの半径が、設定した制御半径に従います。", + "ui.fillet_type_curvature": "曲率連続", + "ui.fillet_type_tip": "エッジを横切る断面。曲率連続: 平面の間の曲率連続 (G2) 断面で、映り込みが面からフィレットへ折れずにつながります。", "ui.filter_commands_or_keys": "コマンドまたはキーを検索", "ui.findInTimeline": "タイムラインで検索", "ui.findInWindow": "ウィンドウで検索", @@ -4277,13 +5118,15 @@ "ui.hideOrigin": "原点を非表示", "ui.hidePlanes": "平面を非表示", "ui.hideProfile": "プロファイルを非表示", - "ui.hide_origin_by_default": "原点を既定で非表示", + "ui.hide_component_history": "このコンポーネントの履歴を非表示", + "ui.hide_origin_by_default": "新規デザインで原点フォルダーを非表示", "ui.hide_origin_note": "新しいデザインは原点フォルダーを非表示にして始まります。原点の表示/非表示を切り替えたデザインは、その設定を保持します。", "ui.history_back": "1ステップ戻る", "ui.history_below_browser": "ブラウザーの下", "ui.history_edge_hint": "端をダブルクリック", "ui.history_first": "先頭に移動", "ui.history_forward": "1ステップ進む", + "ui.history_hide_hidden": "非表示のコンポーネントを隠す", "ui.history_hide_names": "名前を非表示", "ui.history_last": "末尾に移動", "ui.history_marker_tip": "履歴マーカー:ドラッグしてモデルをロールバックします。新しいフィーチャーはここに追加されます", @@ -4293,10 +5136,12 @@ "ui.history_play_button_show": "再生ボタンを表示", "ui.history_play_finish_action": "現在の操作を完了してから履歴を再生してください", "ui.history_play_roll_back": "再生する前に履歴マーカーを戻してください", + "ui.history_show_hidden": "非表示のコンポーネントを表示", "ui.history_show_names": "名前を表示", "ui.history_sketch_listed_under": "{feature} の下に表示", "ui.history_title": "履歴", "ui.history_toggle_names": "フィーチャー名を表示・非表示", + "ui.history_waits_for_editor": "元に戻す、やり直す、履歴は、フィーチャーエディターが開くまで待機します", "ui.hole": "穴", "ui.hole_tap_type": "ねじ穴タイプ", "ui.hole_type": "穴タイプ", @@ -4312,7 +5157,9 @@ "ui.insert_design.saved_file": "{name} に保存されていない変更があるため、保存済みのファイルを挿入しました。保存してから、リンクを更新で変更を取り込んでください。", "ui.insert_design.unsaved": "未保存の変更", "ui.inspect": "検査", + "ui.instances": "インスタンス", "ui.intersect": "交差", + "ui.iso_4753": "ISO 4753", "ui.isolate": "分離表示", "ui.join": "結合", "ui.joint_play": "▶ 再生", @@ -4320,12 +5167,14 @@ "ui.joints": "ジョイント", "ui.keyboard_shortcuts": "キーボードショートカット", "ui.language": "言語", + "ui.lasso_select": "投げ縄(フリーハンドで囲む:完全に内側にあるものを選択)", "ui.layout_compact": "コンパクト", "ui.layout_floating": "フローティング", "ui.length": "長さ", "ui.length_decimals": "長さの小数点以下の桁数", "ui.light": "ライト", "ui.line": "線分", + "ui.line_arc_hint": "接線円弧: 円弧の終点をクリックします。線に戻るには最後の点で再び止めます。右クリックまたは Esc で終了します", "ui.link_copies": "同一のコピーをリンク", "ui.link_copies_keep": "そのまま", "ui.link_copies_link": "リンク", @@ -4413,7 +5262,9 @@ "ui.part_size_needs_a_part": "サイズを変更する挿入済みの標準パーツ(ねじ、ナット、座金、ピン)を選択してください。ボディを拡大・縮小するには尺度を使います。", "ui.part_size_shared": "パーツを再構築し、追加したフィーチャを置き換えます。このコンポーネントのすべての配置が更新されます。", "ui.paste": "貼り付け", + "ui.patch_continuity_corner_tip": "パッチは各辺に沿って、周囲の面と選んだ連続性でつながります。周囲の面どうしが異なる曲率で接するコーナーでは、そこで接線 (G1) にとどまります。", "ui.path": "パス", + "ui.pattern_object_type_tip": "ボディ: ビューまたはブラウザで選ぶ立体形状。それぞれがまるごとコピーされます。\nフィーチャー: 押し出しや穴など履歴のステップ。履歴で、またはそれが作った面で選びます。そのステップが繰り返されます。\nスケッチはどちらでもありません: 曲線はスケッチ内のパターンかミラーで繰り返すか、先に押し出してください。", "ui.pattern_on_path": "パス上のパターン", "ui.perforate_margin_default": "直径と同じ", "ui.perforate_pitch": "ピッチ", @@ -4428,7 +5279,7 @@ "ui.pitch": "ピッチ", "ui.placement": "配置", "ui.placement_handles": "配置ハンドル", - "ui.placement_handles_tip": "レスト、ボス、スナップ フィットのプレビューに表示されるハンドル: マーカーをドラッグしてモデル上を移動し、リングで回転します", + "ui.placement_handles_tip": "モデル上でフィーチャーをドラッグするマーカーと、回転させるリング。", "ui.plane": "平面", "ui.plane_at_angle": "傾斜平面", "ui.plugins": "プラグイン", @@ -4440,12 +5291,17 @@ "ui.plugins_skipped": "{count} 個のフォルダを読めませんでした。", "ui.plugins_version": "{version}", "ui.point": "点", + "ui.point_cloud_add_filter": "フィルターを追加…", "ui.point_cloud_auto_range": "範囲を自動設定", "ui.point_cloud_color_by": "色の付け方", "ui.point_cloud_file_colors": "ファイルの色", + "ui.point_cloud_filter_by": "フィルター", "ui.point_cloud_height_high": "最高の高さ", "ui.point_cloud_height_low": "最低の高さ", + "ui.point_cloud_legend_filter": "上の凡例で表示・非表示を切り替え", "ui.point_cloud_no_file_colors": "ファイルに色情報がありません", + "ui.point_cloud_pause": "一時停止", + "ui.point_cloud_play": "再生", "ui.point_cloud_single_color": "単色", "ui.point_cloud_size": "点のサイズ", "ui.point_cloud_units": "ファイルの単位", @@ -4454,6 +5310,11 @@ "ui.polygon": "ポリゴン", "ui.preferences": "環境設定", "ui.press_a_key": "キーを押してください…", + "ui.print_face_body_not_sent": "この面のボディは送信されません。先にボディに追加してください", + "ui.print_face_cleared": "{body}: 造形面を解除しました", + "ui.print_face_input": "造形面", + "ui.print_face_pick": "ソリッドボディの平面を1つ選択すると造形面になります", + "ui.print_face_set": "{body}: 造形面を設定しました。スライサーへ送るとこの面を下にして置きます", "ui.profile": "プロファイル", "ui.profile_plane": "プロファイル平面", "ui.profiles": "プロファイル", @@ -4470,6 +5331,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "測定中…", + "ui.properties.measuring_bodies": "測定中… {total} 個中 {done} 個のボディ", "ui.properties.measuring_failed": "測定が完了する前に停止しました。", "ui.properties.principal_axis": "主軸 {number}", "ui.properties.principal_moments": "主慣性モーメント", @@ -4537,6 +5399,7 @@ "ui.selectOther": "その他を選択…", "ui.selectTangentChain": "接線チェーンを選択", "ui.select_all": "すべて選択", + "ui.select_components_by_face": "コンポーネントを選択(面をクリックするとそのコンポーネントが選択されます)", "ui.selection": "選択", "ui.selection_modifiers": "選択修飾キー", "ui.selection_shift_add_only": "Shift+クリックで追加のみ(解除なし)", @@ -4562,6 +5425,7 @@ "ui.showDimension": "寸法を表示", "ui.showOrigin": "原点を表示", "ui.showPlanes": "平面を表示", + "ui.show_component_history": "このコンポーネントの履歴を表示", "ui.show_constraints": "拘束", "ui.show_construction_geometries": "構築ジオメトリ", "ui.show_dimensions": "寸法", @@ -4576,8 +5440,15 @@ "ui.sketch_intersect_geometry": "ジオメトリ", "ui.sketch_intersect_projection_link": "投影リンク", "ui.sketch_intersect_selection_filter": "選択フィルター", + "ui.sketch_keys_only": "スケッチ中はモデルのキーを使わない", + "ui.sketch_keys_only_tip": "スケッチの編集中は、スケッチのキーとどこでも使えるキーだけが働きます。E や F などのモデルのキーは何もしないので、うっかり押したキーで重いスケッチが閉じることはありません。", "ui.sketch_modifiers": "スケッチ修飾キー", "ui.sketch_project_geometry": "ジオメトリ", + "ui.sketch_report.all_constrained": "すべて完全に拘束されています。", + "ui.sketch_report.dof": "自由度", + "ui.sketch_report.loose": "完全には拘束されていません", + "ui.sketch_report.status": "状態", + "ui.sketch_report.title": "スケッチ レポート", "ui.sketch_scale": "スケッチ尺度", "ui.sketches": "スケッチ", "ui.slice": "スライス", @@ -4588,7 +5459,7 @@ "ui.slicer_no_response": "{slicer} が時間内に応答しませんでした。ファイルは {path} に保存済みです。スライサーが起動したら、もう一度送ってください。", "ui.slicer_resend_hint": "もう一度送ると、スライサーで開いているファイルが置き換わります。", "ui.slicer_single_instance": "すでに起動しているスライサーでファイルを開く", - "ui.slicer_single_instance_tip": "PrusaSlicer、SuperSlicer、Cura は、別のウィンドウを起動せず、開いているウィンドウでファイルを読み込みます。ほかのスライサーはそのまま起動します。PrusaSlicer 3.0 は常にこの動作です。ランチャーはほかの方法ではファイルを受け取れません。", + "ui.slicer_single_instance_tip": "実行中のウィンドウにファイルを読み込むスライサー用。", "ui.slicer_starting": "{slicer} を起動しています…", "ui.slicer_still_starting": "まだ {slicer} の起動を待っています。ほかには何も送信していません。", "ui.slicer_stl_fallback": "3MF を書き込めなかったため、STL で送信しました。", @@ -4607,8 +5478,8 @@ "ui.start": "開始", "ui.start_over": "最初からやり直す", "ui.start_page": "スタートページ", - "ui.step_values": "矢印キーとホイールで数値を増減", - "ui.step_values_tip": "入力中の値フィールドでは、上下矢印キーとフィールド上のマウスホイールで数値を 1 ずつ増減します(Shift: 10、Alt: 0.1)。式はそのまま残ります。", + "ui.step_values": "矢印キーとホイールで値を変更", + "ui.step_values_tip": "値入力欄の上で上下矢印キーやホイールを使うと数値が変わります。", "ui.stitch_tolerance_hint": "厳密", "ui.stretch": "伸縮", "ui.supersampling": "スーパーサンプリング (SSAA)", @@ -4674,19 +5545,31 @@ "ui.view_angles": "ビュー角度", "ui.view_angles_convention": "上方向の軸まわりの角度(度)。ヨー 0° が正面ビュー、90° が左、−90° が右、180° が背面です。ピッチ 90° が上面ビューです。ロールが正のとき、モデルは画面上で時計回りに回ります。", "ui.view_angles_help": "方向ギズモの下に、ビューのピッチ、ヨー、ロール(度)と投影法を表示します。表示をクリックすると正確な角度を入力できます。", + "ui.view_angles_lock": "{axis}をロック", "ui.view_angles_ortho": "平行投影", "ui.view_angles_persp": "透視投影", "ui.view_angles_pitch": "ピッチ", "ui.view_angles_readout": "ピッチ {pitch} · ヨー {yaw} · ロール {roll}", "ui.view_angles_roll": "ロール", + "ui.view_angles_unlock": "{axis}のロックを解除", "ui.view_angles_yaw": "ヨー", + "ui.view_angles_zero": "{axis}を0°に設定", "ui.view_centre": "ビュー中心", "ui.viewport_status_clear": "{name}をオフにする", "ui.viewport_status_clear_hint": "{name}をオフにする · Esc", + "ui.viewport_status_edges": "{count} エッジ", + "ui.viewport_status_from": "方向 {direction}", "ui.viewport_status_key": "{name}の凡例を表示", "ui.viewport_status_minimum_radius": "最小半径", "ui.viewport_status_pairs": "{count} 組", + "ui.viewport_status_section_hatch": "{setting} · ハッチング", + "ui.viewport_status_section_plane": "現在の平面", + "ui.viewport_status_section_tilted": "傾斜 · {offset}", "ui.viewport_status_stripes": "縞 {count} 本", + "ui.viewport_status_summary_clear": "すべて解除", + "ui.viewport_status_summary_heading": "このビュー内", + "ui.viewport_status_summary_label": "{name} と他 {count} 項目", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "テーマに従う", "ui.visual_shaded_hidden_edges": "隠線付きシェーディング", "ui.visual_shaded_with_edges": "エッジ付きシェーディング", @@ -4722,11 +5605,13 @@ "update.available": "SolidCraft {version} が利用できます", "update.button": "アップデート", "update.button_version": "{version} にアップデート", - "update.check_automatically": "アップデートを自動的に確認", + "update.check_automatically": "起動時と1日1回確認", + "update.check_for_updates": "アップデートを確認", "update.check_now": "今すぐ確認", + "update.check_unavailable": "このインストールではアップデートを確認できません。", "update.checking": "確認中…", "update.copy": "コピー", - "update.dmg_opened": "ディスクイメージを検証して開きました: SolidCraft をアプリケーションフォルダにドラッグして古いものを置き換え、SolidCraft を再起動してください。", + "update.dmg_opened": "ディスクイメージを検証して開きました: SolidCraft を終了し、新しい SolidCraft をアプリケーションフォルダにドラッグして古いものを置き換えてから、SolidCraft をもう一度開いてください。", "update.download": "ダウンロード", "update.download_open": "ダウンロードして開く", "update.downloading": "ダウンロードと検証中… {done} / {total} MB", @@ -4770,6 +5655,7 @@ "web.open_link": "リンク先のデザインを開きますか?", "web.open_link_confirm": "保存していない変更があります。リンク先のデザインを新しいタブで開きますか?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選択 · Enter / Tab 補完 · Esc 閉じる", + "↑ ↓ choose · Enter applies this value": "↑ ↓ 選択 · Enter この値を適用", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 選択 · Enter 入力どおりに適用 · Esc 閉じる", "⌘Enter continues on GitHub.": "⌘EnterでGitHubに進みます。" } diff --git a/assets/locales/ka.json b/assets/locales/ka.json new file mode 100644 index 000000000..896abe6d8 --- /dev/null +++ b/assets/locales/ka.json @@ -0,0 +1,5448 @@ +{ + "(active rule)": "(აქტიური წესი)", + "0 turns it off": "0 გამორთავს", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. გახსენით GitHub-ის მონახაზი ქვემოთ, შემდეგ ჩასვით გაცვლის ბუფერში დაკოპირებული შეტყობინება.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. გახსენით GitHub-ის მონახაზი ქვემოთ. თქვენი სათაური და შეტყობინება ავტომატურად შეივსება.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. დაურთეთ ეკრანის ანაბეჭდი: დააკოპირეთ და ჩასვით, ან შეინახეთ და ატვირთეთ PNG.", + "2D": "2D", + "3. Click Submit new issue on GitHub to send your report.": "3. შეტყობინების გასაგზავნად GitHub-ზე დაწკაპეთ Submit new issue.", + "A Single hole snaps to the middle of its face and to the centres of its round edges": "ცალკეული ხვრელი ებმის თავისი წახნაგის შუაგულს და მისი მრგვალი წიბოების ცენტრებს", + "A new configuration, a copy of the active one": "ახალი კონფიგურაცია, აქტიურის ასლი", + "A placed Single hole has a handle to drag it, and picking its face again moves the hole there instead of taking it out": "განთავსებულ ცალკეულ ხვრელს გადასატანი სახელური აქვს, ხოლო მისი წახნაგის ხელახლა არჩევა ხვრელს იქ გადაიტანს და არ წაშლის", + "A short title for the problem (optional)": "პრობლემის მოკლე სათაური (არასავალდებულო)", + "ARRANGE": "დალაგება", + "About SolidCraft": "SolidCraft-ის შესახებ", + "Acceleration": "აჩქარება", + "Access": "მისაწვდომობა", + "Actions": "მოქმედებები", + "Active": "აქტიური", + "Active rule": "აქტიური წესი", + "Add": "დამატება", + "Add Column": "სვეტის დამატება", + "Add Key": "საკვანძო კადრის დამატება", + "Add Mid Radius": "შუალედური რადიუსის დამატება", + "Add Row": "სტრიქონის დამატება", + "Add a tool": "ხელსაწყოს დამატება", + "Add all bodies": "ყველა სხეულის დამატება", + "Add bend": "მოღუნვის დამატება", + "Add condition": "პირობის დამატება", + "Add or edit rule": "წესის დამატება ან რედაქტირება", + "Add to New Folder": "ახალ საქაღალდეში დამატება", + "Add visible bodies": "ხილული სხეულების დამატება", + "Advanced": "დამატებითი", + "Against": "რის მიმართ", + "Alignment": "სწორება", + "All Lines": "ყველა ხაზი", + "All Sketch Points": "ესკიზის ყველა წერტილი", + "All components": "ყველა კომპონენტი", + "All open designs": "ყველა გახსნილი პროექტი", + "Allowed expressions, separated by semicolons": "დაშვებული გამოსახულებები, წერტილ-მძიმით გამოყოფილი", + "Also deletes": "ასევე წაიშლება", + "Also place them from the origin (fully constrained)": "ასევე სათავიდან განთავსება (სრულად შეზღუდული)", + "Anchor": "მიბმის წერტილი", + "Angle 2": "კუთხე 2", + "Angle Display": "კუთხის ჩვენება", + "Animate": "ანიმაცია", + "Another bend on the far edge of the last flange": "კიდევ ერთი მოღუნვა ბოლო ფლანეცის შორეულ წიბოზე", + "App/system information and command settings are included. Review private details before sharing.": "თან ერთვის აპის/სისტემის ინფორმაცია და ბრძანებების პარამეტრები. გაზიარებამდე გადახედეთ პირად მონაცემებს.", + "Appearance name": "იერსახის სახელი", + "Applied Radius": "გამოყენებული რადიუსი", + "Apply To": "გამოყენების არე", + "Apply library appearance": "ბიბლიოთეკის იერსახის გამოყენება", + "Apply to selection": "მონიშნულზე გამოყენება", + "Apply your appearance first. Exports assigned appearances and materials created in this design.": "ჯერ გამოიყენეთ თქვენი იერსახე. ექსპორტდება მინიჭებული იერსახეები და ამ პროექტში შექმნილი მასალები.", + "Arc length": "რკალის სიგრძე", + "Area": "ფართობი", + "As Picked": "როგორც არჩეულია", + "As-Built": "არსებული მდებარეობით", + "Assign Rule": "წესის მინიჭება", + "Attachment": "მიმაგრება", + "BLEND SURFACE": "გადასვლის ზედაპირი", + "BOUNDARY SURFACE": "საზღვრით აგებული ზედაპირი", + "BROWSER": "მოდელის ხე", + "Back to the original order": "საწყის რიგზე დაბრუნება", + "Ball": "სფერული", + "Bar": "ზოლოვანა", + "Base Center": "ფუძის ცენტრი", + "Base Height": "ფუძის სიმაღლე", + "Bend": "მოღუნვა", + "Bend Edges": "მოღუნვის წიბოები", + "Bend Line": "მოღუნვის ხაზი", + "Bend Line Position": "მოღუნვის ხაზის პოზიცია", + "Bend Position": "მოღუნვის პოზიცია", + "Bend Radius": "მოღუნვის რადიუსი", + "Bend Table": "მოღუნვების ცხრილი", + "Bends": "მოღუნვები", + "Bodies": "სხეულები", + "Bodies (optional)": "სხეულები (არასავალდებულო)", + "Body": "სხეული", + "Body (last if none)": "სხეული (თუ არცერთი, ბოლო)", + "Body to split": "გასაყოფი სხეული", + "Body, or faces to take out": "სხეული, ან ამოსაღები წახნაგები", + "Both": "ორივე", + "Bottom Left": "ქვედა მარცხენა", + "Bottom Middle": "ქვედა შუა", + "Bottom Right": "ქვედა მარჯვენა", + "Boundary": "საზღვარი", + "Bounding box": "გაბარიტული ყუთი", + "CHECK": "შემოწმება", + "COMPONENTS": "კომპონენტები", + "CONFIGURATIONS": "კონფიგურაციები", + "CONSTRAIN": "შეზღუდვა", + "CONTACT": "კონტაქტი", + "CONVERT": "გარდაქმნა", + "CSV or JSON: updates existing parameters, adds new ones": "CSV ან JSON: არსებულ პარამეტრებს განაახლებს, ახლებს დაამატებს", + "Capture All Positions": "ყველა პოზიციის დაფიქსირება", + "Capture Pos.": "პოზ. დაფიქსირება", + "Catch Depth": "კაუჭის სიღრმე", + "Catch Direction": "კაუჭის მიმართულება", + "Catch Length": "კაუჭის სიგრძე", + "Cells": "უჯრედები", + "Center X": "ცენტრი X", + "Center Y": "ცენტრი Y", + "Center of mass": "მასის ცენტრი", + "Centre to centre": "ცენტრიდან ცენტრამდე", + "Centroid": "ცენტროიდი", + "Chamfer Type": "ფასკის ტიპი", + "Channel": "შველერი", + "Check collisions": "შეჯახებების შემოწმება", + "Checked": "შემოწმებული", + "Choose Variable radius or Spline in Type.": "ტიპში აირჩიეთ ცვლადი რადიუსი ან სპლაინი.", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "აირჩიეთ ახალი სიბრტყე. ესკიზის გეომეტრია და ზომები მის ორგანზომილებიან კოორდინატებში უცვლელი რჩება.", + "Choose…": "არჩევა…", + "Circle center": "წრის ცენტრი", + "Circle or sphere": "წრე ან სფერო", + "Circular": "წრიული", + "Circumference": "წრეწირის სიგრძე", + "Clockwise": "საათის ისრის მიმართულებით", + "Close draft": "მონახაზის დახურვა", + "Collapse": "ჩაკეცვა", + "Collisions": "შეჯახებები", + "Colour": "ფერი", + "Command": "ბრძანება", + "Comment": "კომენტარი", + "Component 1": "კომპონენტი 1", + "Component 2": "კომპონენტი 2", + "Component1": "კომპონენტი1", + "Components": "კომპონენტები", + "Config Table": "კონფიგურაციების ცხრილი", + "Configuration": "კონფიგურაცია", + "Configuration rules": "კონფიგურაციის წესები", + "Constant radius": "მუდმივი რადიუსი", + "Contact": "კონტაქტი", + "Contact Sets": "კონტაქტის ნაკრებები", + "Contact sets": "კონტაქტის ნაკრებები", + "Continue on GitHub": "GitHub-ზე გაგრძელება", + "Continuity": "უწყვეტობა", + "Control Radius": "საკონტროლო რადიუსი", + "Copies the definition only. Assign it from Physical Material when ready.": "კოპირდება მხოლოდ განსაზღვრება. როცა მზად იქნებით, მიანიჭეთ ის ფიზიკური მასალიდან.", + "Copy Error Message": "შეცდომის შეტყობინების კოპირება", + "Copy Warning Message": "გაფრთხილების შეტყობინების კოპირება", + "Copy all licences": "ყველა ლიცენზიის კოპირება", + "Copy diagnostic information": "დიაგნოსტიკური ინფორმაციის კოპირება", + "Copy report": "შეტყობინების კოპირება", + "Copy screenshot": "ეკრანის ანაბეჭდის კოპირება", + "Corner Relief": "კუთხის განტვირთვის ჭრილი", + "Corner Relief Shape": "კუთხის განტვირთვის ჭრილის ფორმა", + "Corner radius": "კუთხის რადიუსი", + "Counterbore depth": "ცილინდრული ჩაღრმავების სიღრმე", + "Counterbore Ø": "ცილინდრული ჩაღრმავების Ø", + "Countersink angle": "კონუსური ჩაღრმავების კუთხე", + "Countersink Ø": "კონუსური ჩაღრმავების Ø", + "Create Hole": "ხვრელის შექმნა", + "Create Issue — review draft": "შეტყობინების შექმნა — მონახაზის გადახედვა", + "Create Issue…": "შეტყობინების შექმნა…", + "Cross curves": "განივი მრუდები", + "Ctrl+Enter continues on GitHub.": "Ctrl+Enter-ით GitHub-ზე გააგრძელებთ.", + "Cube": "კუბი", + "Current orthographic view (1:1 mm)": "მიმდინარე ორთოგრაფიული ხედი (1:1 mm)", + "Current perspective view": "მიმდინარე პერსპექტიული ხედი", + "Current plane": "მიმდინარე სიბრტყე", + "Curv. Comb": "სიმრუდის სავარცხელი", + "Curvature (G2)": "სიმრუდე (G2)", + "Curvature change (G3)": "სიმრუდის ცვლილება (G3)", + "Custom": "მორგებული", + "Customize Toolbar": "ხელსაწყოთა ზოლის მორგება", + "Customize…": "მორგება…", + "Cylindrical": "ცილინდრული", + "Cylindrical face": "ცილინდრული წახნაგი", + "Deboss": "ჩაჭდევა", + "Delete": "წაშლა", + "Delete Folders and Features…": "საქაღალდეების და ოპერაციების წაშლა…", + "Delete Selected Features…": "მონიშნული ოპერაციების წაშლა…", + "Delete Selected Folders": "მონიშნული საქაღალდეების წაშლა", + "Delete all": "ყველას წაშლა", + "Delete rule": "წესის წაშლა", + "Delete the row": "სტრიქონის წაშლა", + "Delete the set": "ნაკრების წაშლა", + "Density": "სიმკვრივე", + "Dependents": "დამოკიდებულები", + "Describe the problem you saw": "აღწერეთ შენიშნული პრობლემა", + "Describe what happened before continuing.": "გაგრძელებამდე აღწერეთ, რა მოხდა.", + "Designs you open or save appear here.": "აქ გამოჩნდება თქვენ მიერ გახსნილი ან შენახული პროექტები.", + "Determined by To Object. Choose Angle to edit the angular extent.": "განისაზღვრება ვარიანტით „ობიექტამდე“. კუთხური მოცულობის შესაცვლელად აირჩიეთ „კუთხე“.", + "Diameter": "დიამეტრი", + "Did this assembly open the wrong way up?": "ეს აწყობა არასწორი ორიენტაციით გაიხსნა?", + "Did this part open the wrong way up?": "ეს დეტალი არასწორი ორიენტაციით გაიხსნა?", + "Dimension new shapes": "ახალი ფიგურებისთვის ზომების დატანა", + "Direction": "მიმართულება", + "Discard": "უარყოფა", + "Distance": "მანძილი", + "Distance 1": "მანძილი 1", + "Do not export hidden edges": "დამალული წიბოების გამოტოვება", + "Don't ask again": "აღარ მკითხო", + "Double-click to rename": "სახელის შესაცვლელად ორჯერ დაწკაპეთ", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "შუა ღილაკით ორმაგი დაწკაპება ხედში: საწყისი (საწყისი ხედი, ნაჩვენების ჩატევით), ჩატევა (ნაჩვენების ჩატევა ორიენტაციის შენარჩუნებით) ან არაფერი", + "Drag to move the boss across the model. It snaps to sketch points on the face.": "გადაათრიეთ დგარის მოდელზე გადასაადგილებლად. ის ებმის წახნაგზე არსებულ ესკიზის წერტილებს.", + "Drag to move the hole; click to remove it": "გადაათრიეთ ხვრელის გადასაადგილებლად; დაწკაპეთ მის მოსაშორებლად", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "გადაათრიეთ საყრდენის მოდელზე გადასაადგილებლად. ის ებმის წახნაგზე არსებულ ესკიზის წერტილებს.", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "გადაათრიეთ ჩამკეტის მოდელზე გადასაადგილებლად. ის ებმის წახნაგზე არსებულ ესკიზის წერტილებს.", + "Drag to point the catch in another direction.": "გადაათრიეთ კაუჭის სხვა მიმართულებით მოსაბრუნებლად.", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "გადაათრიეთ საყრდენის 5°-იანი ბიჯით მოსაბრუნებლად. თავისუფლად მოსაბრუნებლად დააჭირეთ Alt-ს ან Ctrl-ს.", + "Drive Joint": "შეერთების ამოძრავება", + "Duration": "ხანგრძლივობა", + "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "ყოველ ახალ ფიგურას ზომები ესკიზის სათავიდანაც დაედება, სანამ მისი არაფერი დარჩება თავისუფალი. ფიგურა, რომელიც უკვე მიბმულია სათავეს ან განთავსებულ გეომეტრიას, ზომებს არ იღებს.", + "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "თქვენ მიერ დახატული ყოველი ფიგურა იღებს ყველა თავის ზომას დახატული სიდიდეებით (აკრეფილ მნიშვნელობებს უპირატესობა აქვს). ზომა, რომელსაც ესკიზი უკვე განსაზღვრავს, გამოტოვებულია.", + "Edge": "წიბო", + "Edges": "წიბოები", + "Edit": "რედაქტირება", + "Edit Profile Sketch": "პროფილის ესკიზის რედაქტირება", + "Edit shortcuts": "მალსახმობების რედაქტირება", + "Enable rule": "წესის ჩართვა", + "Enabled": "ჩართულია", + "End Radius": "საბოლოო რადიუსი", + "End bulge": "საბოლოო ამობურცულობა", + "End continuity": "საბოლოო უწყვეტობა", + "Equal Distance": "თანაბარი მანძილი", + "Expand": "გაშლა", + "Expected result (optional)": "მოსალოდნელი შედეგი (არასავალდებულო)", + "Explode": "დაშლა", + "Explode Text": "ტექსტის დაშლა", + "Export Animation…": "ანიმაციის ექსპორტი…", + "Export Bend Table…": "მოღუნვების ცხრილის ექსპორტი…", + "Export CSV…": "CSV ექსპორტი…", + "Export Current View as DXF": "მიმდინარე ხედის ექსპორტი DXF-ად", + "Export Current View as DXF…": "მიმდინარე ხედის ექსპორტი DXF-ად…", + "Export DXF": "DXF ექსპორტი", + "Export DXF…": "DXF ექსპორტი…", + "Export JSON…": "JSON ექსპორტი…", + "Export design library...": "პროექტის ბიბლიოთეკის ექსპორტი...", + "Export hidden edges as dashed lines": "დამალული წიბოების ექსპორტი წყვეტილი ხაზებით", + "Exported by SolidWorks, which usually saves Y up": "ექსპორტირებულია SolidWorks-ით, რომელიც ჩვეულებრივ Y ღერძს ზემოთ ინახავს", + "Expression": "გამოსახულება", + "Extend to meet": "გაგრძელება შეხვედრამდე", + "Extents": "საზღვრები", + "FILES": "ფაილები", + "FLAT": "გაშლილი", + "Face": "წახნაგი", + "Face Appearance": "წახნაგის იერსახე", + "Face attachment lost": "წახნაგთან მიმაგრება დაიკარგა", + "Face center": "წახნაგის ცენტრი", + "Faces": "წახნაგები", + "Faces / edges / vertices": "წახნაგები / წიბოები / წვეროები", + "Faces to split": "გასაყოფი წახნაგები", + "Faces/Body": "წახნაგები/სხეული", + "Factor must be a positive number": "კოეფიციენტი დადებითი რიცხვი უნდა იყოს", + "Fastener": "სამაგრი ელემენტი", + "Favorites": "რჩეულები", + "Favourite": "რჩეული", + "Feature": "ოპერაცია", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "ბევრი CAD პროგრამის ფაილებში Y ზემოთაა მიმართული, ამიტომ აქ ისინი ზურგზე წამოწოლილი იხსნება (Z ზემოთ).", + "Filter": "ფილტრი", + "Filter…": "ფილტრი…", + "Find in Browser": "მოდელის ხეში ძებნა", + "Finish": "დასრულება", + "First edge": "პირველი წიბო", + "First plane": "პირველი სიბრტყე", + "First point": "პირველი წერტილი", + "Fit and G2 corners require Constant radius.": "მისადაგება და G2 კუთხეები მუდმივ რადიუსს მოითხოვს.", + "Fixed Face": "უძრავი წახნაგი", + "Flange Gap": "ფლანეცის ღრეჩო", + "Flange thickness": "ფლანეცის სისქე", + "Flanges": "ფლანეცები", + "Flat Pattern": "გაშლილი ფორმა", + "Flat size": "გაშლილი ფორმის ზომა", + "Flat size X": "გაშლილი ფორმის ზომა X", + "Flat size Y": "გაშლილი ფორმის ზომა Y", + "Follow camera (Look At sketches)": "კამერის მიდევნება (ესკიზებისკენ შებრუნება)", + "Follow the camera (Look At sketches)": "კამერის მიდევნება (ესკიზებისკენ შებრუნება)", + "Font": "შრიფტი", + "Free Move": "თავისუფალი გადაადგილება", + "From": "საიდან", + "From Bodies": "სხეულებიდან", + "From Snap": "მიბმის წერტილიდან", + "From edges": "წიბოებიდან", + "Full Length": "სრული სიგრძე", + "Full thread depth": "კუთხვილის სრული სიღრმე", + "Further Bends": "შემდგომი მოღუნვები", + "G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "G2 კუთხეები მოითხოვს მუდმივ რადიუსს და ზუსტ მისადაგებას. G2 კუთხის აგება ჯერ მხარდაჭერილი არ არის.", + "Gap": "ღრეჩო", + "Grid": "ბადე", + "HISTORY": "ქრონოლოგია", + "Halo under sketch curves": "შარავანდი ესკიზის მრუდების ქვეშ", + "Height": "სიმაღლე", + "Height From": "სიმაღლის ათვლა", + "Hem Gap": "წიბოს გადაკეცვის ღრეჩო", + "Hidden edges": "დამალული წიბოები", + "History layout": "ქრონოლოგიის განლაგება", + "History names": "სახელები ქრონოლოგიაში", + "Hole (optional)": "ხვრელი (არასავალდებულო)", + "Hole Depth": "ხვრელის სიღრმე", + "Hole Diameter": "ხვრელის დიამეტრი", + "Holes": "ხვრელები", + "Holes (edges on them)": "ხვრელები (მათი წიბოები)", + "Home view": "საწყისი ხედი", + "Horiz./Vert.": "ჰორიზ./ვერტ.", + "I-Beam": "ორტესებრი კოჭი", + "IMAGES": "გამოსახულებები", + "If you are offline or GitHub does not open, use Copy report and keep the text to submit later.": "თუ ინტერნეტთან კავშირი არ გაქვთ ან GitHub არ იხსნება, გამოიყენეთ „შეტყობინების კოპირება“ და შეინახეთ ტექსტი მოგვიანებით გასაგზავნად.", + "Import material into design": "მასალის იმპორტი პროექტში", + "Import…": "იმპორტი…", + "In This Design": "ამ პროექტში", + "In place (surfaces)": "ადგილზე (ზედაპირები)", + "In plane": "სიბრტყეში", + "Included": "შიგა", + "Inner Sharp": "შიგა წვეტი", + "Inside": "შიგნით", + "Instant": "მყისიერი", + "Interface font": "ინტერფეისის შრიფტი", + "Interferes": "იკვეთება", + "Invert": "ინვერსია", + "Isocurve": "იზომრუდი", + "Issue title": "შეტყობინების სათაური", + "Items": "ელემენტები", + "JOINTS": "შეერთებები", + "Joint 1": "შეერთება 1", + "Joint 2": "შეერთება 2", + "Joint Origin1": "შეერთების სათავე1", + "K Factor": "K-ფაქტორი", + "Keep (points on it)": "დასატოვებელი (მასზე მდებარე წერტილები)", + "Keep Tools": "ხელსაწყოების შენარჩუნება", + "Keep of the other surface": "სხვა ზედაპირიდან დასატოვებელი", + "Key a joint's value at this step": "შეერთების მნიშვნელობის საკვანძო კადრად ჩაწერა ამ ნაბიჯზე", + "Keys": "საკვანძო კადრები", + "Knife Edge": "ბასრი წიბო", + "L-Angle": "კუთხოვანა", + "LIBRARY": "ბიბლიოთეკა", + "LINKS": "ბმულები", + "Later": "მოგვიანებით", + "Leave it": "დატოვება ისე", + "Left Middle": "მარცხენა შუა", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "წახნაგთან მიმაგრების ძველი ტიპი. სერტიფიცირებულ წახნაგზე ხელახლა მიბმა ზუსტ მიმაგრებას ქმნის.", + "Length": "სიგრძე", + "Length units": "სიგრძის ერთეულები", + "Letter Spacing": "ასოებს შორის ინტერვალი", + "Library": "ბიბლიოთეკა", + "Library file": "ბიბლიოთეკის ფაილი", + "Library response is missing": "ბიბლიოთეკის პასუხი არ არის", + "Limits": "ზღვრები", + "Line Spacing": "სტრიქონთა დაშორება", + "Line Type": "ხაზის ტიპი", + "Line on plane": "ხაზი სიბრტყეზე", + "Lines": "ხაზები", + "Listing the installed fonts…": "დაინსტალირებული შრიფტების სიის შედგენა…", + "Load library": "ბიბლიოთეკის ჩატვირთვა", + "Local library": "ლოკალური ბიბლიოთეკა", + "Loop": "ციკლი", + "M5 or M5x0.5": "M5 ან M5x0.5", + "M5, M5x0.5, 1/4-20 UNC": "M5, M5x0.5, 1/4-20 UNC", + "MANAGE": "მართვა", + "MATERIALS": "მასალები", + "MODEL": "მოდელი", + "MOTION": "მოძრაობა", + "Margin": "მარაგი", + "Mass": "მასა", + "Mass Center": "მასის ცენტრი", + "Matched restrictions check the final values.": "შესრულებული პირობის მქონე შეზღუდვები საბოლოო მნიშვნელობებს ამოწმებს.", + "Material": "მასალა", + "Material Outside": "მასალა გარეთ", + "Material copied. Existing body assignments are unchanged.": "მასალა დაკოპირდა. სხეულებზე არსებული მინიჭებები არ შეცვლილა.", + "Max": "მაქსიმუმი", + "Max Thickness": "მაქს. სისქე", + "Maximum": "მაქსიმუმი", + "Mesh body": "პოლიგონური ბადის სხეული", + "Mid Radius": "შუალედური რადიუსი", + "Middle double-click": "შუა ღილაკით ორმაგი დაწკაპება", + "Min": "მინიმუმი", + "Min Draft": "მინ. დახრა", + "Min Thickness": "მინ. სისქე", + "Minimum": "მინიმუმი", + "Mirror Plane": "არეკვლის სიბრტყე", + "Mitre": "ირიბი ჭრა", + "Model Parameters": "მოდელის პარამეტრები", + "Modeled": "მოდელირებული", + "More toolbar panels": "ხელსაწყოთა ზოლის სხვა პანელები", + "Motion": "მოძრაობა", + "Mouse gestures": "მაუსის ჟესტები", + "Mouse gestures only work with the SolidWorks mouse mode (the wheel orbits, Ctrl + wheel pans).": "მაუსის ჟესტები მუშაობს მხოლოდ SolidWorks-ის მაუსის რეჟიმში (ბორბალი ხედს ატრიალებს, Ctrl + ბორბალი გადაადგილებს).", + "Move / Copy": "გადაადგილება / კოპირება", + "Move Type": "გადაადგილების ტიპი", + "Move down": "ჩამოწევა", + "Move earlier": "უფრო ადრე გადატანა", + "Move holes by clicking or dragging": "ხვრელების გადაადგილება დაწკაპებით ან გადათრევით", + "Move later": "უფრო გვიან გადატანა", + "Move up": "აწევა", + "Name": "სახელი", + "Name on import": "სახელი იმპორტისას", + "Nearest": "უახლოესი", + "Neutral plane": "ნეიტრალური სიბრტყე", + "New": "ახალი", + "New Comp.": "ახალი კომპ.", + "New Sketch": "ახალი ესკიზი", + "New rule…": "ახალი წესი…", + "New study": "ახალი კვლევა", + "No crash reports.": "ავარიული დასრულების ანგარიშები არ არის.", + "No matching appearance presets.": "შესაბამისი იერსახის პრესეტები არ არის.", + "No matching appearances": "შესაბამისი იერსახეები არ არის", + "No matching physical materials.": "შესაბამისი ფიზიკური მასალები არ არის.", + "No visible bodies or sketches to export.": "ექსპორტისთვის ხილული სხეულები ან ესკიზები არ არის.", + "Nominal Radius": "ნომინალური რადიუსი", + "Nominal diameter": "ნომინალური დიამეტრი", + "None": "არცერთი", + "Not available yet": "ჯერ ხელმისაწვდომი არ არის", + "Not saved yet": "ჯერ არ არის შენახული", + "Notch": "ჭრილი", + "OUTPUT": "გამოტანა", + "Of": "თავისუფლების ხარისხი", + "On your computer": "თქვენს კომპიუტერზე", + "Opacity": "გაუმჭვირვალობა", + "Open GitHub": "GitHub-ის გახსნა", + "Open GitHub draft": "GitHub-ის მონახაზის გახსნა", + "Open GitHub issue form": "GitHub-ის შეტყობინების ფორმის გახსნა", + "Open bodies (no volume)": "ღია სხეულები (მოცულობის გარეშე)", + "Open library...": "ბიბლიოთეკის გახსნა...", + "Open local libraries in the desktop app. You can export this design's library here.": "ლოკალური ბიბლიოთეკები გახსენით დესკტოპის აპში. აქ შეგიძლიათ ამ პროექტის ბიბლიოთეკის ექსპორტი.", + "Open surface — no volume": "ღია ზედაპირი — მოცულობის გარეშე", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "ღია კოდის პარამეტრული 3D CAD Rust-ზე. ლიცენზია: MIT OR Apache-2.0.", + "Opens your browser and copies the report text for you to paste into GitHub.": "ხსნის ბრაუზერს და აკოპირებს შეტყობინების ტექსტს, რომ GitHub-ში ჩასვათ.", + "Opens your browser and copies the report text. Review and submit your report on GitHub.": "ხსნის ბრაუზერს და აკოპირებს შეტყობინების ტექსტს. გადახედეთ და გაგზავნეთ შეტყობინება GitHub-ზე.", + "Opens your browser. Review and submit your report on GitHub.": "ხსნის ბრაუზერს. გადახედეთ და გაგზავნეთ შეტყობინება GitHub-ზე.", + "Operator": "ოპერატორი", + "Orbit (right drag)": "ორბიტა (მარჯვენა ღილაკით გადათრევა)", + "Other side": "მეორე მხარე", + "Other surface (mutual trim)": "სხვა ზედაპირი (ურთიერთმოკვეთა)", + "Other way": "საპირისპირო მიმართულებით", + "Outer Sharp": "გარე წვეტი", + "Outer radius": "გარე რადიუსი", + "Outside": "გარეთ", + "Overall length": "საერთო სიგრძე", + "Param. Graph": "პარამ. გრაფი", + "Parameter": "პარამეტრი", + "Part length must be greater than zero and at most 2000 mm": "დეტალის სიგრძე უნდა იყოს ნულზე მეტი და არაუმეტეს 2000 mm", + "Parts": "დეტალები", + "Pass through": "გასავლელი წერტილები", + "Path": "ტრაექტორია", + "Pattern": "მასივი", + "Per Edge": "თითოეული წიბოსთვის", + "Physical material definitions": "ფიზიკური მასალების განსაზღვრებები", + "Pick a part size": "აირჩიეთ დეტალის ზომა", + "Pick the tool bodies": "აირჩიეთ ხელსაწყო სხეულები", + "Picked": "არჩეული", + "Picked point": "არჩეული წერტილი", + "Pin-slot": "ღერძი-ღარი", + "Pitch": "ბიჯი", + "Pivot": "ბრუნვის ცენტრი", + "Place at the origin instead": "ამის ნაცვლად სათავეში განთავსება", + "Planar": "სიბრტყული", + "Plastic Rules": "პლასტმასის წესები", + "Play the joint's motion in the view": "შეერთების მოძრაობის დაკვრა ხედში", + "Playback": "დაკვრა", + "Plot": "გრაფიკი", + "Point on line": "წერტილი ხაზზე", + "Point on plane": "წერტილი სიბრტყეზე", + "Position": "პოზიცია", + "Position (0 to 1)": "პოზიცია (0-დან 1-მდე)", + "Position (G0)": "პოზიცია (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "პოზიცია წიბოს გასწვრივ, 0 — საწყის ბოლოზე, 1 — მეორეზე", + "Preferences › Design turns the offer back on": "შეთავაზების ხელახლა ჩართვა: პარამეტრები › პროექტი", + "Preview": "წინასწარი ნახვა", + "Preview Row": "სტრიქონის წინასწარი ნახვა", + "Preview leaves the current design unchanged.": "წინასწარი ნახვა მიმდინარე პროექტს არ ცვლის.", + "Profile / Edges": "პროფილი / წიბოები", + "Profiles or curves": "პროფილები ან მრუდები", + "Profiles/Curves": "პროფილები/მრუდები", + "Quantity": "რაოდენობა", + "Quantity must be at least 2": "რაოდენობა უნდა იყოს მინიმუმ 2", + "RECENT": "ბოლოდროინდელი", + "REFERENCE": "ორიენტირები", + "RULED SURFACE": "სწორხაზოვანი ზედაპირი", + "RULES": "წესები", + "Radius": "რადიუსი", + "Radius Fit": "რადიუსის მისადაგება", + "Ratio": "თანაფარდობა", + "Read-only list: shortcuts can't be changed here.": "მხოლოდ წასაკითხი სია: მალსახმობების შეცვლა აქ შეუძლებელია.", + "Reattach selected face": "მონიშნულ წახნაგზე ხელახლა მიმაგრება", + "Recover": "აღდგენა", + "Recover unsaved design?": "აღვადგინოთ შეუნახავი პროექტი?", + "Rectangular": "მართკუთხა", + "Rectangular Tube": "მართკუთხა მილი", + "Reference face": "ორიენტირი წახნაგი", + "Reference plane": "საორიენტაციო სიბრტყე", + "Relief Depth": "განტვირთვის ჭრილის სიღრმე", + "Relief Width": "განტვირთვის ჭრილის სიგანე", + "Remove Tools": "ხელსაწყოების მოშორება", + "Remove condition": "პირობის წაშლა", + "Remove from Folder": "საქაღალდიდან ამოღება", + "Remove from list": "სიიდან ამოშლა", + "Remove override": "გადაფარვის მოხსნა", + "Remove private design details or paths before sharing.": "გაზიარებამდე წაშალეთ პროექტის პირადი დეტალები ან ბილიკები.", + "Remove screenshot": "ეკრანის ანაბეჭდის წაშლა", + "Remove the column": "სვეტის წაშლა", + "Remove the track": "ტრეკის წაშლა", + "Remove this bend": "ამ მოღუნვის წაშლა", + "Remove this point": "ამ წერტილის წაშლა", + "Rename Feature": "ოპერაციის სახელის შეცვლა", + "Rename Folder": "საქაღალდის სახელის შეცვლა", + "Render Stage": "რენდერის სცენა", + "Reopen designs": "პროექტების ხელახლა გახსნა", + "Reopen the designs that were open when SolidCraft was last closed": "წინა ჯერზე გახსნილი პროექტების ხელახლა გახსნა", + "Repair Part": "დეტალის შეკეთება", + "Replace existing library file": "არსებული ბიბლიოთეკის ფაილის ჩანაცვლება", + "Report a bug — review a screenshot and open a GitHub draft": "ხარვეზის შეტყობინება — გადახედეთ ეკრანის ანაბეჭდს და გახსენით GitHub-ის მონახაზი", + "Report copied. Keep this text to submit on GitHub when you are online.": "შეტყობინება დაკოპირდა. შეინახეთ ეს ტექსტი, რომ ინტერნეტთან დაკავშირებისას GitHub-ზე გაგზავნოთ.", + "Report text copied. Paste it into GitHub and submit your report there.": "შეტყობინების ტექსტი დაკოპირდა. ჩასვით ის GitHub-ში და იქ გაგზავნეთ.", + "Reports are public. A GitHub account is required.": "შეტყობინებები საჯაროა. საჭიროა GitHub-ის ანგარიში.", + "Reset Toolbar": "ხელსაწყოთა ზოლის ჩამოყრა", + "Resize Part": "დეტალის ზომის შეცვლა", + "Restore View": "ხედის აღდგენა", + "Restore outer boundary": "გარე საზღვრის აღდგენა", + "Restore the inherited component or physical material appearance": "კომპონენტის ან ფიზიკური მასალის მემკვიდრეობით მიღებული იერსახის აღდგენა", + "Restore this studio's tools": "ამ სტუდიის ხელსაწყოების აღდგენა", + "Result": "შედეგი", + "Retake screenshot": "ეკრანის ანაბეჭდის ხელახლა გადაღება", + "Reveal Height": "საფეხურის სიმაღლე", + "Reverse": "შებრუნება", + "Reverse Direction": "მიმართულების შებრუნება", + "Revert": "დაბრუნება", + "Revert All Positions": "ყველა პოზიციის დაბრუნება", + "Revert Pos.": "პოზ. დაბრუნება", + "Revert Position": "პოზიციის დაბრუნება", + "Review the report and screenshot before opening GitHub.": "GitHub-ის გახსნამდე გადახედეთ შეტყობინებას და ეკრანის ანაბეჭდს.", + "Review your report on GitHub and click Submit new issue to publish it.": "გადახედეთ შეტყობინებას GitHub-ზე და გამოსაქვეყნებლად დაწკაპეთ Submit new issue.", + "Revolute": "მბრუნავი", + "Rib Length": "სიხისტის წიბოს სიგრძე", + "Rib Offset": "სიხისტის წიბოს წანაცვლება", + "Rib Thickness": "სიხისტის წიბოს სისქე", + "Ribs": "სიხისტის წიბოები", + "Right Middle": "მარჯვენა შუა", + "Rigid": "ხისტი", + "Rim Edge": "ქიმის წიბო", + "Rim face": "ქიმის წახნაგი", + "Ring of tools on the right button": "ხელსაწყოების რგოლი მარჯვენა ღილაკზე", + "Roll Back Here": "აქამდე უკან დაბრუნება", + "Roll History Marker Here": "ქრონოლოგიის მარკერის აქ გადატანა", + "Root radius": "ძირის რადიუსი", + "Round": "მომრგვალებული", + "Round Bar": "მრგვალი ღერო", + "Round Tube": "მრგვალი მილი", + "Rule": "წესი", + "Rule name": "წესის სახელი", + "Rules run from top to bottom. Matched drives change effective values.": "წესები სრულდება ზემოდან ქვემოთ. შესრულებული პირობის მქონე მმართველი წესები ცვლის მოქმედ მნიშვნელობებს.", + "SECTION": "კვეთი", + "SURFACE QUALITY": "ზედაპირის ხარისხი", + "Same way": "იმავე მიმართულებით", + "Save Rule": "წესის შენახვა", + "Save View": "ხედის შენახვა", + "Save screenshot…": "ეკრანის ანაბეჭდის შენახვა…", + "Save the study as an animated GIF, seen as the viewport shows it": "კვლევის შენახვა ანიმირებულ GIF-ად, ისე როგორც ხედვის არე აჩვენებს", + "Saved preview. Geometry is being checked before editing.": "შენახული წინასწარი ხედი. რედაქტირებამდე გეომეტრია მოწმდება.", + "Scale factor": "მასშტაბის კოეფიციენტი", + "Scene": "სცენა", + "Screenshot (optional)": "ეკრანის ანაბეჭდი (არასავალდებულო)", + "Search": "ძიება", + "Search commands": "ბრძანებების ძიება", + "Search this library": "ამ ბიბლიოთეკაში ძიება", + "Second edge": "მეორე წიბო", + "Second plane": "მეორე სიბრტყე", + "Second point": "მეორე წერტილი", + "Section": "კვეთი", + "Section (optional)": "კვეთი (არასავალდებულო)", + "Section position": "კვეთის პოზიცია", + "Sections": "კვეთები", + "Sections (one sketch each)": "კვეთები (თითოეულისთვის თითო ესკიზი)", + "Select Other": "სხვის არჩევა", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "სხვის არჩევა: კურსორის ქვეშ მყოფი ყველაფრის სიის სანახავად მოდელზე უძრავად დააჭირეთ მარცხენა ღილაკს (ან მარჯვენა დაწკაპება › სხვის არჩევა…); იმავე ადგილზე კვლავ დაწკაპებით აირჩევთ იქ მყოფ შემდეგ ობიექტს. საწყის ხედზე გადასასვლელად შუა ღილაკით ორჯერ დაწკაპეთ (პარამეტრები › ნავიგაცია).", + "Select Same Look": "იგივე ვიზუალური სტილის მქონეთა მონიშვნა", + "Select bodies (a face picks its body)": "აირჩიეთ სხეულები (წახნაგი თავის სხეულს ირჩევს)", + "Select bodies or faces instead": "ამის ნაცვლად სხეულების ან წახნაგების არჩევა", + "Select edges": "აირჩიეთ წიბოები", + "Select points of the sketch being edited": "აირჩიეთ რედაქტირებადი ესკიზის წერტილები", + "Select the centre the pattern turns around first": "ჯერ აირჩიეთ ცენტრი, რომლის გარშემოც მასივი ბრუნავს", + "Select the curves to offset first": "ჯერ აირჩიეთ წასანაცვლებელი მრუდები", + "Select the mirror line": "აირჩიეთ არეკვლის ხაზი", + "Select the sketch curves or points to mirror first": "ჯერ აირჩიეთ ასარეკლი ესკიზის მრუდები ან წერტილები", + "Select the sketch curves or points to move first": "ჯერ აირჩიეთ გადასაადგილებელი ესკიზის მრუდები ან წერტილები", + "Select the sketch curves or points to pattern first": "ჯერ აირჩიეთ მასივად გასამრავლებელი ესკიზის მრუდები ან წერტილები", + "Select the sketch curves or points to scale first": "ჯერ აირჩიეთ მასშტაბირებისთვის ესკიზის მრუდები ან წერტილები", + "Select the sketch curves or points to transform first": "ჯერ აირჩიეთ გარდასაქმნელი ესკიზის მრუდები ან წერტილები", + "Selection filter": "მონიშვნის ფილტრი", + "Semantic faces share their appearance across instances.": "სემანტიკური წახნაგები იერსახეს ყველა ეგზემპლარში იზიარებს.", + "Send your report on GitHub": "შეტყობინების გაგზავნა GitHub-ზე", + "Shaded": "დაჩრდილული", + "Shape": "ფორმა", + "Sheet Rules": "ფურცლოვანი ლითონის წესები", + "Show Agent Cursor": "აგენტის კურსორის ჩვენება", + "Show ghost": "ნახევრადგამჭვირვალე ასლის ჩვენება", + "Show in folder": "საქაღალდეში ჩვენება", + "Show the pointer an AI agent moves (#35)": "AI აგენტის მიერ მართული მაჩვენებლის ჩვენება (#35)", + "Show tool at cursor": "ხელსაწყოს ჩვენება კურსორთან", + "Signed axes": "ნიშნიანი ღერძები", + "Size": "ზომა", + "Sketch constraints": "ესკიზის შეზღუდვები", + "Sketch curves": "ესკიზის მრუდები", + "Sketch dimensions": "ესკიზის ზომები", + "Sketch geometry and profiles": "ესკიზის გეომეტრია და პროფილები", + "Sketch plane has no body-face attachment.": "ესკიზის სიბრტყე სხეულის წახნაგთან მიმაგრებული არ არის.", + "Sketch points": "ესკიზის წერტილები", + "Slider": "მცურავი", + "Slot width": "ღარის სიგანე", + "Snap to face and edge centres": "მიბმა წახნაგებისა და წიბოების ცენტრებზე", + "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft-ს შეტყობინებების პირდაპირ გაგზავნა არ შეუძლია. გაგზავნეთ GitHub-ზე; აპში ტოკენი საჭირო არ არის.", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft დაიხურა ამ პროექტების შენახვამდე. შესაძლებელია მათი ბოლო ავტოშენახვის გახსნა.", + "Sort A to Z": "სორტირება ა-დან ჰ-მდე", + "Sort Z to A": "სორტირება ჰ-დან ა-მდე", + "Spacing 2 must be a non-zero number": "ბიჯი 2 ნულისგან განსხვავებული რიცხვი უნდა იყოს", + "Spacing must be a non-zero number": "ბიჯი ნულისგან განსხვავებული რიცხვი უნდა იყოს", + "Specialise": "სპეციალიზება", + "Speed": "სიჩქარე", + "Splitting tool": "გამყოფი ხელსაწყო", + "Square": "კვადრატი", + "Stand it up": "წამოყენება", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "წამოყენება: მეოთხედი ბრუნი X ღერძის გარშემო, ერთი გადაადგილების ოპერაციით, რომლის გაუქმებაც შეგიძლიათ.", + "Stand this assembly up?": "წამოვაყენოთ ეს აწყობა?", + "Stand this part up?": "წამოვაყენოთ ეს დეტალი?", + "Start angle": "საწყისი კუთხე", + "Start bulge": "საწყისი ამობურცულობა", + "Start continuity": "საწყისი უწყვეტობა", + "Stationary Side": "უძრავი მხარე", + "Step": "ნაბიჯი", + "Steps": "ნაბიჯები", + "Steps to reproduce (optional)": "გამეორების ნაბიჯები (არასავალდებულო)", + "Stitch the kept pieces": "დატოვებული ნაწილების შეკერვა", + "Stitch to both bodies": "ორივე სხეულთან შეკერვა", + "Studio": "სტუდია", + "Study": "კვლევა", + "Style": "სტილი", + "Summary": "შეჯამება", + "Suppress": "ჩახშობა", + "Suppress Selected Folders": "მონიშნული საქაღალდეების ჩახშობა", + "Suppressed": "ჩახშობილი", + "Surface": "ზედაპირი", + "Surface, or faces to turn over": "ზედაპირი, ან შესაბრუნებელი წახნაგები", + "Surfaces": "ზედაპირები", + "Swap Ends": "ბოლოების გაცვლა", + "TRIM": "მოკვეთა", + "Tangent": "მხები", + "Tangent (G1)": "მხები (G1)", + "Tangent Chain": "მხებთა ჯაჭვი", + "Tangent chain": "მხებთა ჯაჭვი", + "Tangent to Edge": "წიბოს მხები", + "Tap drill diameter": "ხრახნის ბურღის დიამეტრი", + "Target": "სამიზნე", + "Target Body": "სამიზნე სხეული", + "Target Face (optional)": "სამიზნე წახნაგი (არასავალდებულო)", + "Tear": "გახევა", + "Technical details": "ტექნიკური დეტალები", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "წყვეტილი ესკიზი სიბრტყის შენახული ორიენტირია. მიმაგრების აღსადგენად აირჩიეთ ახალი წახნაგი.", + "The design changed. Reopen Change Part Size for the component.": "პროექტი შეიცვალა. კომპონენტისთვის ხელახლა გახსენით „დეტალის ზომის შეცვლა“.", + "The direction must be an axis or a straight sketch curve that lies in the sketch plane": "მიმართულება უნდა იყოს ღერძი ან ესკიზის სიბრტყეში მდებარე სწორი მრუდი", + "The mirror line cannot also be mirrored": "არეკვლის ხაზი თავად ვერ აირეკლება", + "The mirror line must be a straight curve of this sketch, not an origin axis": "არეკვლის ხაზი უნდა იყოს ამ ესკიზის სწორი მრუდი და არა სათავის ღერძი", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "შენახული საავტორო ეგზემპლარი აღარ არსებობს. ხელახლა მიბმამდე აირჩიეთ სწორი საავტორო განთავსება.", + "Then": "მაშინ", + "These features will be deleted:": "ეს ოპერაციები წაიშლება:", + "These features will fail:": "ეს ოპერაციები ვერ შესრულდება:", + "Thickness Outside": "სისქე გარეთ", + "Thickness Variation": "სისქის ცვალებადობა", + "Thin": "თხელი", + "Thin Extrude": "თხელკედლიანი ამოწევა", + "Third plane": "მესამე სიბრტყე", + "Third point": "მესამე წერტილი", + "This child is shared. Deleting it removes it from every copy of its parent.": "ეს შვილობილი ელემენტი გაზიარებულია. მისი წაშლა მას მშობლის ყველა ასლიდან მოაშორებს.", + "This child is shared. Position changes apply to every copy of its parent.": "ეს შვილობილი ელემენტი გაზიარებულია. პოზიციის ცვლილებები მშობლის ყველა ასლზე მოქმედებს.", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "ეს კომპონენტი ერთზე მეტჯერ განთავსებული ქვეაწყობის შიგნითაა: მისი სწორება მას ყველა განთავსებაში გადაადგილებს.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "ეს წახნაგი მდგრად მიმაგრებას ვერ უზრუნველყოფს. აირჩიეთ სხვა წახნაგი ან პირდაპირ გამოიყენეთ ფიქსირებული სიბრტყე.", + "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "ეს გამოსახულება GitHub-ზე ჯერ არ არის დართული. დააკოპირეთ ან შეინახეთ, შემდეგ დაურთეთ GitHub-ზე.", + "Thread depth": "კუთხვილის სიღრმე", + "Thread diameter": "კუთხვილის დიამეტრი", + "Through point": "გავლის წერტილი", + "To": "სადამდე", + "To Offset": "წანაცვლებამდე", + "To Snap": "მიბმის წერტილამდე", + "To edges": "წიბოებამდე", + "Toe radius": "თაროს ბოლოს რადიუსი", + "Tolerance": "დაშვება", + "Too close": "ზედმეტად ახლოსაა", + "Tool Bodies": "ხელსაწყო სხეულები", + "Tools": "ხელსაწყოები", + "Tools, clockwise from the top": "ხელსაწყოები, ზემოდან საათის ისრის მიმართულებით", + "Top Left": "ზედა მარცხენა", + "Top Middle": "ზედა შუა", + "Top Right": "ზედა მარჯვენა", + "Trimming tool (plane, face or curves)": "მომკვეთი ხელსაწყო (სიბრტყე, წახნაგი ან მრუდები)", + "Turn off section analysis before exporting the view.": "ხედის ექსპორტამდე გამორთეთ კვეთის ანალიზი.", + "Type": "ტიპი", + "Type a distance or an angle to move by": "აკრიფეთ გადაადგილების მანძილი ან კუთხე", + "UNTRIM": "მოკვეთის მოხსნა", + "Unit": "ერთეული", + "Unsuppress": "ჩახშობის მოხსნა", + "Unsuppress Selected Folders": "მონიშნული საქაღალდეების ჩახშობის მოხსნა", + "Updating the preview": "წინასწარი ხედი ახლდება", + "Use active author placement": "აქტიური საავტორო განთავსების გამოყენება", + "Use fixed plane": "ფიქსირებული სიბრტყის გამოყენება", + "Use saved fixed plane": "შენახული ფიქსირებული სიბრტყის გამოყენება", + "Use selected face as fixed plane": "მონიშნული წახნაგის ფიქსირებულ სიბრტყედ გამოყენება", + "Use the SolidWorks mouse mode": "SolidWorks-ის მაუსის რეჟიმის გამოყენება", + "User Parameters": "მომხმარებლის პარამეტრები", + "VIEW": "ხედი", + "VIEWS": "ხედები", + "Value": "მნიშვნელობა", + "Variable Radius": "ცვლადი რადიუსი", + "Velocity": "სიჩქარე", + "Vertices": "წვეროები", + "View navigator": "ხედის ნავიგატორი", + "Volume": "მოცულობა", + "Wall": "კედელი", + "Wall Location": "კედლის მდებარეობა", + "Wall Thickness": "კედლის სისქე", + "Web thickness": "შუა კედლის სისქე", + "What did you do just before the problem? A short list is enough": "რას აკეთებდით პრობლემის წინ? მოკლე ჩამონათვალიც საკმარისია", + "What did you expect to see?": "რის დანახვას ელოდით?", + "What happened?": "რა მოხდა?", + "When": "როცა", + "Width": "სიგანე", + "Will fail": "ვერ შესრულდება", + "With gestures on, the right button no longer orbits the view: hold it and move to open the ring, then touch a tool's zone. A plain right-click still opens the menu.": "ჟესტების ჩართვისას მარჯვენა ღილაკი ხედს აღარ ატრიალებს: რგოლის გასახსნელად დააჭირეთ და გაამოძრავეთ, შემდეგ შეეხეთ ხელსაწყოს ზონას. ჩვეულებრივი მარჯვენა დაწკაპება კვლავ ხსნის მენიუს.", + "X": "X", + "X Angle": "X კუთხე", + "X angle": "X კუთხე", + "X distance": "X მანძილი", + "Y": "Y", + "Y Angle": "Y კუთხე", + "Y angle": "Y კუთხე", + "Y distance": "Y მანძილი", + "Z": "Z", + "Z Angle": "Z კუთხე", + "Z Distance": "Z მანძილი", + "Z angle": "Z კუთხე", + "Z distance": "Z მანძილი", + "Zebra": "ზებრა", + "`joint` must be an id or a name": "`joint` უნდა იყოს id ან სახელი", + "`params` must be an object": "`params` უნდა იყოს ობიექტი", + "`values` must be a list": "`values` უნდა იყოს სია", + "a chamfer needs a corner of exactly two lines": "ფასკას სჭირდება კუთხე, რომელსაც ზუსტად ორი ხაზი ქმნის", + "a file operation is in progress": "მიმდინარეობს ფაილური ოპერაცია", + "a picked curve is no longer in a sketch": "არჩეული მრუდი აღარ არის ესკიზში", + "a picked curve's sketch has not been solved": "არჩეული მრუდის ესკიზი ამოხსნილი არ არის", + "a picked edge has no points": "არჩეულ წიბოს წერტილები არ აქვს", + "a picked edge is gone": "არჩეული წიბო აღარ არსებობს", + "a picked edge's body is gone": "არჩეული წიბოს სხეული აღარ არსებობს", + "add a key for a joint first": "ჯერ შეერთებისთვის საკვანძო კადრი დაამატეთ", + "ai.connected_toast": "SolidCraft ახლა ხელმისაწვდომია აქ: {clients}. გამოსაყენებლად გადატვირთეთ ისინი (პარამეტრები > ასისტენტი).", + "ai.prefs.allow_control": "AI აგენტების დაკავშირების ნებართვა (მართვის არხი / MCP)", + "ai.prefs.allow_control_note": "ხსნის მართვის არხს მხოლოდ ამ კომპიუტერზე (127.0.0.1, პორტი 27878 ან შემდეგი თავისუფალი). დამაკავშირებელმა პროგრამამ ასევე უნდა წარადგინოს საიდუმლო ტოკენი, რომლის წაკითხვაც მხოლოდ თქვენს მომხმარებლის ანგარიშს შეუძლია და რომელიც ყოველ გაშვებაზე ახლიდან იქმნება. ძალაში შედის SolidCraft-ის შემდეგი გაშვებისას. გამორთულისას: არაფერი უსმენს, თუ SolidCraft-ს --control-ით არ გაუშვებთ.", + "ai.prefs.availability": "ასისტენტის მართვა", + "ai.prefs.background_commands": "აგენტის ბრძანებების ფონურ რეჟიმში შესრულება", + "ai.prefs.connect_apps": "SolidCraft-ის ხელმისაწვდომობა ამ კომპიუტერის AI აპებისთვის", + "ai.prefs.connect_apps_note": "SolidCraft-ის გაშვებისას ამატებს მას MCP სერვერად ამ კომპიუტერზე ნაპოვნ AI აპებში (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), რომ აგენტმა ის ყოველგვარი დაყენების გარეშე გამოიყენოს. ემატება მხოლოდ solidcraft ჩანაწერი ან ახლდება მისი ბილიკი; თქვენ მიერ შეცვლილი ჩანაწერი ხელუხლებელი რჩება, ფაილის სარეზერვო ასლი კი წინასწარ იქმნება. გამორთულისას: მის მიერ დამატებული ჩანაწერები წაიშლება. იგივეს ხელით აკეთებს დახმარება > AI ასისტენტების დაკავშირება….", + "ai.prefs.connect_at_start": "ბოლოს გამოყენებული აგენტის დაკავშირება SolidCraft-ის გაშვებისას", + "ai.prefs.connect_at_start_note": "SolidCraft-ის ყოველი გაშვებისას ფონურ რეჟიმში უშვებს ბოლოს დაკავშირებულ (ან ნაგულისხმევ) აგენტს, რომ ის სასაუბროდ მზად იყოს. არა მაშინ, როცა SolidCraft --control-ით არის გაშვებული. თუ დაკავშირება ვერ მოხერხდა, ასისტენტი აჩვენებს „დაკავშირება ვერ მოხერხდა“ და ღილაკს „ხელახლა ცდა“.", + "ai.prefs.follow_camera": "კამერის ესკიზებისკენ შებრუნება", + "ai.prefs.follow_camera_off": "კამერის ავტომატური მიდევნება გამორთულია.", + "ai.prefs.follow_camera_on": "კამერა ბრუნდება აგენტის მიერ შექმნილი ესკიზებისკენ.", + "ai.prefs.intro": "აგენტები, ნებართვები და მათი მუშაობის ჩვენება.", + "ai.prefs.make_default": "ნაგულისხმევად გამოყენება", + "ai.prefs.no_agents": "აგენტები ჯერ არ არის. დაამატეთ აგენტი ან დაინსტალირებული აგენტების მოსაძებნად განაახლეთ.", + "ai.prefs.no_saved_approvals": "შენახული დასტურები არ არის.", + "ai.prefs.open_at_start": "ასისტენტის პანელის გახსნა SolidCraft-ის გაშვებისას", + "ai.prefs.open_at_start_note": "SolidCraft-ის ყოველი გაშვებისას აჩვენებს ასისტენტის პანელს (ან მის ცალკე ფანჯარას). არა მაშინ, როცა SolidCraft --control-ით არის გაშვებული.", + "ai.prefs.override_all_warning": "ამ აგენტს შეუძლია პროექტის შენახვა, გადაწერა, ექსპორტი ან ჩანაცვლება კითხვის გარეშე.", + "ai.prefs.permission_all": "ყველაფრის დაშვება", + "ai.prefs.permission_all_summary": "SolidCraft-ის ხელმისაწვდომი ხელსაწყოები კითხვის გარეშე სრულდება.", + "ai.prefs.permission_ask": "კითხვა ცვლილებებამდე", + "ai.prefs.permission_ask_summary": "დაადასტურეთ პროექტის ყოველი ცვლილება და ფაილური მოქმედება.", + "ai.prefs.permission_edits": "მოდელის ცვლილებების დაშვება", + "ai.prefs.permission_edits_summary": "მოდელის ცვლილებები სრულდება; ფაილური და დესტრუქციული მოქმედებები მაინც დასტურს ითხოვს.", + "ai.prefs.permission_scope": "მხოლოდ SolidCraft-ის ხელსაწყოებისთვის. აგენტის ტერმინალის ბრძანებები და ფაილების რედაქტირება მის საკუთარ ნებართვებს ექვემდებარება.", + "ai.prefs.pointer_preview_hidden": "მაჩვენებელი დამალულია", + "ai.prefs.pointer_preview_speed": "აგენტის მაჩვენებელი · {speed}", + "ai.prefs.pointer_speed": "მოძრაობის სიჩქარე", + "ai.prefs.privacy_note": "საუბარს იღებს მხოლოდ თქვენ მიერ არჩეული აგენტი ან საბოლოო წერტილი. საბოლოო წერტილების გასაღებები ინახება თქვენი სისტემის გასაღებების საცავში.", + "ai.prefs.show_pointer": "აგენტის მაჩვენებლის ჩვენება", + "ai.prefs.turn_limit_hint": "პროექტის შემცვლელი ხელსაწყოს გამოძახებების მაქსიმალური რაოდენობა, რომელიც ასისტენტს ერთ შეტყობინებაზე შეუძლია.", + "angle, height": "კუთხე, სიმაღლე", + "appearance.dielectric_ior": "დიელექტრიკის IOR", + "appearance.metallic": "მეტალიკური", + "appearance.only_available": "მხოლოდ ხელმისაწვდომი იერსახეები", + "appearance.pbr_help": "ეს ზედაპირი ნახეთ რენდერში ან პროდუქტის PNG-ში. სინათლის გარდატეხისა და გატარების გარეშე.", + "appearance.pbr_opaque": "გაუმჭვირვალე PBR", + "appearance.roughness": "უხეშობა", + "appearance.surface_response": "ზედაპირის რეაქცია", + "at the face": "წახნაგთან", + "bom.group_children": "ქვედეტალები თავიანთი დეტალის სტრიქონში", + "browser.body_name": "სხეული{number}", + "browser.calibrate_click_a": "A წერტილისთვის დაწკაპეთ გამოსახულებაზე, ან აკრიფეთ მისი კოორდინატები.", + "browser.calibrate_click_b": "B წერტილისთვის დაწკაპეთ გამოსახულებაზე, ან აკრიფეთ მისი კოორდინატები.", + "browser.calibrate_title": "კალიბრება: {name}", + "browser.capture_many": "გადაადგილებულია კომპონენტები, რომელთა პოზიციები დაფიქსირებული არ არის: {count}.", + "browser.capture_note": "დაფიქსირება ინარჩუნებს ახალ პოზიციას; დაბრუნება აბრუნებს ძველს.", + "browser.capture_one": "კომპონენტი გადაადგილდა, მაგრამ მისი პოზიცია დაფიქსირებული არ არის.", + "browser.component_name": "კომპონენტი{number}", + "browser.edit_canvas_title": "ტილოს რედაქტირება: {name}", + "browser.edit_point_cloud_title": "წერტილების ღრუბლის რედაქტირება: {name}", + "browser.move_title": "გადაადგილება: {name}", + "browser.needs_repair": "{name}: საჭიროებს შეკეთებას", + "browser.parameters": "პარამეტრები ({count})", + "browser.precision": "სიზუსტე: {precision}", + "browser.sketch_attachment_lost": "{name} (მიმაგრება დაიკარგა)", + "browser.sketch_editing": "{name} (რედაქტირდება)", + "browser.sketch_name": "ესკიზი{number}", + "browser.sketches_to_parts_already_in_part": "უკვე თავიანთ დეტალშია", + "browser.sketches_to_parts_design_body": "თავად პროექტის სხეულზეა", + "browser.sketches_to_parts_moved": "იმ დეტალში, რომელზეც მდებარეობს, გადავიდა ესკიზი: {moved}", + "browser.sketches_to_parts_no_exact_attachment": "წახნაგზეა ზუსტი მიმაგრების გარეშე", + "browser.sketches_to_parts_not_on_face": "დეტალის წახნაგზე არ არის", + "browser.sketches_to_parts_part_missing": "მათი დეტალი აღარ არსებობს", + "browser.sketches_to_parts_result": "იმ დეტალში, რომელზეც მდებარეობს, გადავიდა ესკიზი: {moved}; დარჩა: {stayed}, მიზეზი: {why}", + "browser.units": "ერთეულები: {units}", + "cam.flat": "ბრტყელი წახნაგი", + "cam.follower": "მიმყოლი", + "cam.knife": "ბასრი წიბო", + "cam.needs_joints": "საჭიროა ერთი მბრუნავი შეერთება და ერთი მცურავი ან მრხევი", + "cam.roller": "გორგოლაჭი", + "cam.roller_pick": "გორგოლაჭი (არასავალდებულო)", + "cam.tip_pick": "წვერი (არასავალდებულო)", + "camera.shot_pitch": "დახრილობა", + "camera.shot_roll": "გორება", + "camera.shot_yaw": "აზიმუტი", + "canvas.decal_place_hint": "სტიკერის განსათავსებლად დაწკაპეთ წახნაგზე", + "canvas.place_hint": "ტილოს განსათავსებლად დაწკაპეთ სიბრტყეზე ან წახნაგზე", + "choose a profile": "აირჩიეთ პროფილი", + "choose the cam's and the follower's joints": "აირჩიეთ მუშტისა და მიმყოლის შეერთებები", + "choose the joints to couple": "აირჩიეთ დასაწყვილებელი შეერთებები", + "click a plane or planar face": "დაწკაპეთ სიბრტყეზე ან ბრტყელ წახნაგზე", + "click sketch curves": "დაწკაპეთ ესკიზის მრუდებზე", + "cmd.appearance_assign": "იერსახე", + "cmd.appearance_chain": "იერსახეების ჯაჭვი", + "cmd.appearance_copy": "ვიზუალური სტილის კოპირება", + "cmd.appearance_favorite": "ვიზუალური სტილის რჩეულებში დამატება", + "cmd.appearance_library": "იერსახეების ბიბლიოთეკა", + "cmd.appearance_list": "იერსახეების სია", + "cmd.appearance_paint": "იერსახით შეღებვა", + "cmd.appearance_paste": "ვიზუალური სტილის ჩასმა", + "cmd.appearance_pick_up": "იერსახის აღება", + "cmd.appearance_replace": "იერსახის ჩანაცვლება", + "cmd.assembly_bom": "სპეციფიკაცია", + "cmd.assembly_mass_properties": "მასის მახასიათებლები", + "cmd.body.print_face": "ბეჭდვის წახნაგი", + "cmd.body_rename": "სხეულის სახელის შეცვლა", + "cmd.body_repair": "დეტალის შეკეთება", + "cmd.browser_collapse_all": "ყველას ჩაკეცვა", + "cmd.browser_expand_all": "ყველას გაშლა", + "cmd.browser_group": "ახალი ჯგუფი", + "cmd.browser_move": "მოდელის ხის ელემენტების გადატანა", + "cmd.browser_order": "მოდელის ხის ელემენტების დალაგება", + "cmd.browser_rename_group": "ჯგუფის სახელის შეცვლა", + "cmd.browser_reparent": "კომპონენტში გადატანა", + "cmd.browser_ungroup": "დაჯგუფების მოხსნა", + "cmd.browser_visibility": "ჩვენება/დამალვა", + "cmd.canvas_calibrate": "ტილოს კალიბრება", + "cmd.canvas_decal": "სტიკერი", + "cmd.canvas_delete": "ტილოს წაშლა", + "cmd.canvas_edit": "ტილოს რედაქტირება", + "cmd.canvas_insert": "ტილო", + "cmd.canvas_to_sketch": "ტილოს ესკიზად გარდაქმნა", + "cmd.component_activate": "კომპონენტის გააქტიურება", + "cmd.component_break_link": "ბმულის გაწყვეტა", + "cmd.component_capture_position": "პოზიციის დაფიქსირება", + "cmd.component_copies": "იდენტური ასლების ძებნა", + "cmd.component_copy_bodies": "სხეულების ჩასმა", + "cmd.component_create": "ახალი კომპონენტი", + "cmd.component_cycle_color": "კომპონენტის ფერის ციკლური შეცვლა", + "cmd.component_delete": "კომპონენტის წაშლა", + "cmd.component_edit_in_place": "ადგილზე რედაქტირება", + "cmd.component_extract": "ფაილში გატანა", + "cmd.component_finish_edit": "რედაქტირების დასრულება", + "cmd.component_from_bodies": "კომპონენტების შექმნა სხეულებიდან", + "cmd.component_hide_history": "კომპონენტის ქრონოლოგიის დამალვა", + "cmd.component_insert_design": "პროექტის ჩასმა", + "cmd.component_links": "ბმულების სია", + "cmd.component_list": "კომპონენტების სია", + "cmd.component_metadata": "დეტალის თვისებები", + "cmd.component_metadata_set": "დეტალის თვისებების შეცვლა", + "cmd.component_move_bodies": "სხეულების კომპონენტში გადატანა", + "cmd.component_move_features": "ოპერაციების კომპონენტში გადატანა", + "cmd.component_move_sketches": "ესკიზების კომპონენტში გადატანა", + "cmd.component_move_sketches_to_parts": "ესკიზების გადატანა თავიანთ დეტალებში", + "cmd.component_paste_from_design": "ჩასმა სხვა პროექტიდან", + "cmd.component_paste_new": "ახლის სახით ჩასმა", + "cmd.component_properties": "კომპონენტის ფიზიკური თვისებები", + "cmd.component_relink": "წყაროს ხელახლა მიბმა", + "cmd.component_rename": "კომპონენტის სახელის შეცვლა", + "cmd.component_replace_with_link": "ბმულით ჩანაცვლება", + "cmd.component_revert_position": "პოზიციის დაბრუნება", + "cmd.component_show_history": "კომპონენტის ქრონოლოგიის ჩვენება", + "cmd.component_unlock": "შიგთავსის განბლოკვა", + "cmd.component_update_links": "ბმულების განახლება", + "cmd.config_activate": "კონფიგურაციის გააქტიურება", + "cmd.config_column": "კონფიგურაციის სვეტი", + "cmd.config_configure": "კონფიგურაცია", + "cmd.config_preview": "კონფიგურაციის წინასწარი ნახვა", + "cmd.config_row": "კონფიგურაციის სტრიქონი", + "cmd.config_rule": "კონფიგურაციის წესი", + "cmd.config_rules": "კონფიგურაციის წესები", + "cmd.config_table": "კონფიგურაციების ცხრილის ჩვენება", + "cmd.construct.plane.axis_point": "სიბრტყე ღერძისა და წერტილის გავლით", + "cmd.construct_axis_edge": "ღერძი წიბოზე", + "cmd.construct_axis_normal_to_face": "ღერძი წახნაგის მართობულად", + "cmd.construct_axis_through_cylinder": "ღერძი ცილინდრის/კონუსის/ტორის გავლით", + "cmd.construct_axis_two_planes": "ღერძი ორი სიბრტყის გავლით", + "cmd.construct_axis_two_points": "ღერძი ორი წერტილის გავლით", + "cmd.construct_plane_along_path": "სიბრტყე ტრაექტორიის გასწვრივ", + "cmd.construct_plane_midplane": "შუა სიბრტყე", + "cmd.construct_plane_perpendicular": "მართობული სიბრტყე", + "cmd.construct_plane_tangent": "მხები სიბრტყე", + "cmd.construct_plane_three_points": "სიბრტყე სამი წერტილის გავლით", + "cmd.construct_plane_two_edges": "სიბრტყე ორი წიბოს გავლით", + "cmd.construct_point_along_path": "წერტილი ტრაექტორიის გასწვრივ", + "cmd.construct_point_center": "წერტილი წრის/სფეროს/ტორის ცენტრში", + "cmd.construct_point_edge_plane": "წერტილი წიბოსა და სიბრტყის გადაკვეთაზე", + "cmd.construct_point_three_planes": "წერტილი სამი სიბრტყის გადაკვეთაზე", + "cmd.construct_point_two_edges": "წერტილი ორი წიბოს გადაკვეთაზე", + "cmd.construct_point_vertex": "წერტილი წვეროზე", + "cmd.contact_check": "კონტაქტის შემოწმება", + "cmd.contact_create": "კონტაქტის ახალი ნაკრები", + "cmd.contact_disable_all": "კონტაქტის გამორთვა", + "cmd.contact_edit": "კონტაქტის ნაკრების რედაქტირება", + "cmd.contact_enable_all": "კონტაქტის ჩართვა ყველა დეტალისთვის", + "cmd.contact_enable_sets": "კონტაქტის ნაკრებების ჩართვა", + "cmd.contact_list": "კონტაქტის ნაკრებების სია", + "cmd.diagnostics_crash_report": "ავარიის ანგარიში", + "cmd.diagnostics_crash_reports": "ავარიის ანგარიშები", + "cmd.diagnostics_crash_reports_clear": "ავარიის ანგარიშების წაშლა", + "cmd.diagnostics_crash_test": "ავარიის ტესტი", + "cmd.diagnostics_profile": "პროფილირება", + "cmd.diagnostics_validation": "ვალიდაცია", + "cmd.doc_recover": "პროექტის აღდგენა", + "cmd.doc_recovery_discard": "აღდგენილი პროექტის უარყოფა", + "cmd.doc_recovery_list": "აღსადგენი პროექტები", + "cmd.document_inspect": "პროექტის შემოწმება", + "cmd.document_metadata": "პროექტის თვისებები", + "cmd.document_metadata_remove": "პროექტის თვისების წაშლა", + "cmd.document_metadata_set": "პროექტის თვისებების შეცვლა", + "cmd.document_revision": "პროექტის რევიზია", + "cmd.document_units": "პროექტის ერთეულების შეცვლა", + "cmd.edit_checkpoint": "საკონტროლო წერტილი", + "cmd.edit_repeat": "ბოლო ბრძანების გამეორება", + "cmd.edit_restore_checkpoint": "საკონტროლო წერტილის აღდგენა", + "cmd.engine_commands": "ბრძანებების სია", + "cmd.engine_describe": "ბრძანების აღწერა", + "cmd.explode_create": "დაშლილი ხედი", + "cmd.explode_delete": "დაშლილი ხედის წაშლა", + "cmd.explode_list": "დაშლილი ხედების სია", + "cmd.explode_show": "დაშლილი ხედის ჩვენება", + "cmd.expr_evaluate": "გამოსახულების გამოთვლა", + "cmd.face_delete": "წახნაგის წაშლა", + "cmd.file.export_3mf": "3MF ექსპორტი", + "cmd.file.export_obj": "OBJ ექსპორტი", + "cmd.file.export_step": "STEP ექსპორტი", + "cmd.file.export_stl": "STL ექსპორტი", + "cmd.file.export_urdf": "URDF ექსპორტი", + "cmd.file_export": "ექსპორტი", + "cmd.file_insert_mesh": "პოლიგონური ბადის ჩასმა", + "cmd.file_insert_step": "STEP-ის ჩასმა", + "cmd.file_open_in_easyprint": "EasyPrint-ით გახსნა", + "cmd.file_save_mesh": "შენახვა პოლიგონური ბადის სახით", + "cmd.file_send_to_slicer": "სლაისერში გაგზავნა", + "cmd.file_slicers": "დაინსტალირებული სლაისერები", + "cmd.frame_member": "ჩარჩოს ელემენტი", + "cmd.frame_profile_insert": "პროფილის ჩასმა", + "cmd.frame_profile_list": "პროფილების ბიბლიოთეკა", + "cmd.frame_profile_properties": "პროფილის თვისებები", + "cmd.inspect_accessibility": "მისაწვდომობის ანალიზი", + "cmd.inspect_analysis": "ანალიზის ნახვა", + "cmd.inspect_center_of_mass": "მასის ცენტრი", + "cmd.inspect_clearance": "ღრეჩო", + "cmd.inspect_colored_components": "კომპონენტების ფერების ჩართვა", + "cmd.inspect_colored_components_disable": "კომპონენტების ფერების გამორთვა", + "cmd.inspect_compare": "სხეულების შედარება", + "cmd.inspect_compare_picture": "სურათთან შედარება", + "cmd.inspect_continuity": "უწყვეტობის ანალიზი", + "cmd.inspect_curvature_comb": "სიმრუდის სავარცხლის ანალიზი", + "cmd.inspect_curvature_map": "სიმრუდის რუკის ანალიზი", + "cmd.inspect_draft": "დახრის ანალიზი", + "cmd.inspect_environment_map": "გარემოს რუკის ანალიზი", + "cmd.inspect_interference": "ურთიერთგადაკვეთა", + "cmd.inspect_isocurve": "იზოპარამეტრული მრუდების ანალიზი", + "cmd.inspect_minimum_radius": "მინიმალური რადიუსის ანალიზი", + "cmd.inspect_parameter_sweep": "პარამეტრის ვარიაცია", + "cmd.inspect_silhouette": "სილუეტი", + "cmd.inspect_zebra": "ზებრას ანალიზი", + "cmd.joint_as_built": "შეერთება არსებულ პოზიციაში", + "cmd.joint_cam": "კულაჩი", + "cmd.joint_create": "შეერთება", + "cmd.joint_delete": "შეერთების წაშლა", + "cmd.joint_drive": "შეერთებების ამოძრავება", + "cmd.joint_edit": "შეერთების რედაქტირება", + "cmd.joint_find_limits": "შეერთების ზღვრების პოვნა", + "cmd.joint_gear": "კბილანა", + "cmd.joint_inspect": "შეერთების შემოწმება", + "cmd.joint_limits": "შეერთების ზღვრები", + "cmd.joint_list": "შეერთებების სია", + "cmd.joint_motion_link": "მოძრაობის კავშირი", + "cmd.joint_origin": "შეერთების სათავე", + "cmd.joint_rack_pinion": "კბილა ლარტყა და კბილანა", + "cmd.joint_reach": "წერტილამდე მიწვდომა", + "cmd.joint_rigid_group": "ხისტი ჯგუფი", + "cmd.joint_screw": "ხრახნი", + "cmd.joint_solve": "შეერთებების ამოხსნა", + "cmd.joint_sweep": "შეერთების გავლა კონტაქტამდე", + "cmd.library_apply": "ლოკალური ბიბლიოთეკის ჩანაწერის გამოყენება", + "cmd.library_export": "პროექტის ბიბლიოთეკის ექსპორტი", + "cmd.library_inspect": "ლოკალური ბიბლიოთეკის შემოწმება", + "cmd.material_assign": "ფიზიკური მასალა", + "cmd.material_create": "ახალი ფიზიკური მასალა", + "cmd.material_delete": "ფიზიკური მასალის წაშლა", + "cmd.material_edit": "ფიზიკური მასალის რედაქტირება", + "cmd.material_inspect": "ფიზიკური მასალის შემოწმება", + "cmd.material_list": "მასალების სია", + "cmd.material_properties_directional": "მიმართულებითი დრეკადობის მოდული", + "cmd.material_properties_validate": "ფიზიკური მასალის მონაცემების შემოწმება", + "cmd.mesh_convert": "პოლიგონური ბადის გარდაქმნა", + "cmd.model_edges": "წიბოების სია", + "cmd.model_faces": "წახნაგების სია", + "cmd.model_threads": "კუთხვილების სია", + "cmd.motion_delete": "მოძრაობის კვლევის წაშლა", + "cmd.motion_export": "მოძრაობის კვლევის ექსპორტი", + "cmd.motion_export_animation": "მოძრაობის ანიმაციის ექსპორტი", + "cmd.motion_interference": "ურთიერთგადაკვეთა მოძრაობისას", + "cmd.motion_list": "მოძრაობის კვლევების სია", + "cmd.motion_play": "მოძრაობის კვლევის დაკვრა", + "cmd.motion_plot": "მოძრაობის კვლევის გრაფიკის აგება", + "cmd.motion_study": "მოძრაობის კვლევა", + "cmd.motion_trace": "მოძრაობის კვალი", + "cmd.motion_trace_edit": "მოძრაობის კვალის რედაქტირება", + "cmd.motion_trace_keep": "მოძრაობის კვალის შენარჩუნება", + "cmd.occurrence_align": "ეგზემპლარის სწორება", + "cmd.occurrence_copy": "ჩასმა (ეგზემპლარი)", + "cmd.occurrence_drag": "ეგზემპლარის გადათრევა", + "cmd.occurrence_ground": "უძრავად დამაგრება", + "cmd.occurrence_move": "ეგზემპლარის გადაადგილება", + "cmd.occurrence_properties": "ეგზემპლარის ფიზიკური თვისებები", + "cmd.occurrence_reparent": "კომპონენტში გადატანა", + "cmd.parameters_add": "მომხმარებლის პარამეტრის დამატება", + "cmd.parameters_change": "პარამეტრების შეცვლა", + "cmd.parameters_comment": "პარამეტრზე კომენტარის დართვა", + "cmd.parameters_complete": "გამოსახულების დასრულება", + "cmd.parameters_delete": "პარამეტრის წაშლა", + "cmd.parameters_export": "პარამეტრების ექსპორტი", + "cmd.parameters_favorite": "პარამეტრის რჩეულებში დამატება", + "cmd.parameters_graph": "პარამეტრების გრაფი", + "cmd.parameters_import": "პარამეტრების იმპორტი", + "cmd.parameters_list": "პარამეტრების სია", + "cmd.parameters_move": "პარამეტრის გადატანა", + "cmd.parameters_rename": "პარამეტრის სახელის შეცვლა", + "cmd.parameters_users": "სად გამოიყენება პარამეტრი", + "cmd.parts_fastener": "სამაგრი ელემენტის ჩასმა", + "cmd.parts_insert": "დეტალის ჩასმა", + "cmd.parts_library": "სტანდარტული დეტალები", + "cmd.parts_resize": "დეტალის ზომის შეცვლა", + "cmd.plastic_assign_rule": "პლასტმასის წესის მინიჭება", + "cmd.plastic_boss": "დგარი", + "cmd.plastic_lip": "ბორტი", + "cmd.plastic_manage_rules": "პლასტმასის წესების მართვა", + "cmd.plastic_rest": "საყრდენი", + "cmd.plastic_rules": "პლასტმასის წესების სია", + "cmd.plastic_snap_fit": "ჩამკეტი სამაგრი", + "cmd.pointcloud_delete": "წერტილების ღრუბლის წაშლა", + "cmd.pointcloud_edit": "წერტილების ღრუბლის რედაქტირება", + "cmd.pointcloud_insert": "წერტილების ღრუბლის ჩასმა", + "cmd.pointcloud_list": "წერტილების ღრუბლები", + "cmd.render.compare.divider": "რენდერების შედარების გამყოფის გადაადგილება", + "cmd.render.result.discard": "რენდერის შედეგის უარყოფა", + "cmd.render.result.select": "რენდერის შედეგის არჩევა", + "cmd.render_aging_describe": "ზედაპირის მრავალშრიანი დაძველება", + "cmd.render_backends": "რენდერის ძრავები", + "cmd.render_batch": "ყველა კადრის რენდერი", + "cmd.render_camera_fit": "რენდერის ობიექტის კადრში მოქცევა", + "cmd.render_camera_get": "რენდერის კამერის შემოწმება", + "cmd.render_cancel": "რენდერის გაუქმება", + "cmd.render_compare": "გამოსახულებების შედარება", + "cmd.render_effects_describe": "ლინზისა და შემოქმედებითი ეფექტები", + "cmd.render_export": "რენდერის გამოსახულების ექსპორტი", + "cmd.render_hdr_inspect": "HDR წყაროს შემოწმება", + "cmd.render_library_appearance_apply": "ბიბლიოთეკის გაუმჭვირვალე იერსახის გამოყენება", + "cmd.render_library_describe": "რენდერის ბიბლიოთეკის რესურსის შემოწმება", + "cmd.render_library_environment_apply": "ჩაშენებული HDR გარემოს გამოყენება", + "cmd.render_library_list": "რენდერის ბიბლიოთეკის დათვალიერება", + "cmd.render_library_physical_prepare": "ფიზიკური ეტალონის მომზადება", + "cmd.render_library_preview": "ზედაპირის საწყისი რუკის შემოწმება", + "cmd.render_library_studio_apply": "სტუდიის საავტორო განათების გამოყენება", + "cmd.render_library_studio_prepare": "სტუდიის საავტორო განათების მომზადება", + "cmd.render_library_surface_bind": "ზედაპირის მიბმის შენახვა", + "cmd.render_library_surface_prepare": "ზედაპირის საავტორო რუკების მომზადება", + "cmd.render_library_surface_unbind": "ზედაპირის მიბმის მოხსნა", + "cmd.render_library_targets": "რენდერის ბიბლიოთეკის სამიზნეების ძებნა", + "cmd.render_lights_add": "სინათლის დამატება", + "cmd.render_lights_duplicate": "რენდერის სინათლის დუბლირება", + "cmd.render_lights_list": "რენდერის სინათლეების სია", + "cmd.render_lights_mute": "სინათლის დადუმება", + "cmd.render_lights_remove": "რენდერის სინათლის წაშლა", + "cmd.render_lights_set": "რენდერის სინათლის დაყენება", + "cmd.render_lights_solo": "სინათლის სოლო", + "cmd.render_optics_bind": "ოპტიკური მიბმის შენახვა", + "cmd.render_optics_unbind": "ოპტიკური მიბმის მოხსნა", + "cmd.render_output_size": "რენდერის გამოტანის ზომის დაყენება", + "cmd.render_preflight": "რენდერის მოთხოვნის შემოწმება", + "cmd.render_preflight_copy": "რენდერის შემოწმების ანგარიშის კოპირება", + "cmd.render_preset_apply": "ჩაშენებული სტუდიის გამოყენება", + "cmd.render_preset_resolve": "ჩაშენებული სტუდიის გადახედვა", + "cmd.render_quality_prepare": "სემპლინგის ფიქსირებული ბიუჯეტის გადახედვა", + "cmd.render_result_close": "რენდერის გამოსახულების დახურვა", + "cmd.render_result_copy": "რენდერის გამოსახულების კოპირება", + "cmd.render_result_pin": "ნაჩვენები რენდერის შედეგის შენარჩუნება", + "cmd.render_result_regrade": "წრფივი მასტერის ხელახალი კორექცია", + "cmd.render_result_view": "რენდერის გამოსახულების ნახვა", + "cmd.render_scene": "რენდერის სცენის შემოწმება", + "cmd.render_settings_apply": "რენდერის კამერის გამოყენება", + "cmd.render_settings_capture_hdr": "რენდერის პარამეტრების შენახვა HDR-ით", + "cmd.render_settings_get": "რენდერის პარამეტრები", + "cmd.render_settings_set": "რენდერის პარამეტრების შენახვა", + "cmd.render_shot_duplicate": "რენდერის კადრის დუბლირება", + "cmd.render_shot_remove": "რენდერის კადრის წაშლა", + "cmd.render_shot_rename": "რენდერის კადრის სახელის შეცვლა", + "cmd.render_stage_backdrop": "რენდერის ფიზიკური ფონის შენახვა", + "cmd.render_stage_clear": "რენდერის დეკორაციის წაშლა", + "cmd.render_stage_ground": "რენდერის მიწის შენახვა", + "cmd.render_start": "გამოსახულების რენდერი", + "cmd.render_status": "რენდერის პროგრესი", + "cmd.select_clear": "მონიშვნის მოხსნა", + "cmd.settings_profile_apply": "პარამეტრების პროფილის გამოყენება", + "cmd.settings_profile_delete": "პარამეტრების პროფილის წაშლა", + "cmd.settings_profile_export": "პარამეტრების პროფილის ექსპორტი", + "cmd.settings_profile_import": "პარამეტრების პროფილის იმპორტი", + "cmd.settings_profile_list": "პარამეტრების პროფილები", + "cmd.settings_profile_rename": "პარამეტრების პროფილის სახელის შეცვლა", + "cmd.settings_profile_save": "პარამეტრების პროფილის შენახვა", + "cmd.sheet_convert": "ფურცლოვან ლითონად გარდაქმნა", + "cmd.sheet_export_bend_table": "მოღუნვის ცხრილის ექსპორტი", + "cmd.sheet_export_dxf": "გაშლილი ფორმის ექსპორტი DXF-ად", + "cmd.sheet_flange": "ფლანეცი", + "cmd.sheet_flat_pattern": "გაშლილი ფორმის შექმნა", + "cmd.sheet_fold": "მოკეცვა", + "cmd.sheet_hem": "წიბოს გადაკეცვა", + "cmd.sheet_manage_rules": "ფურცლოვანი ლითონის წესები", + "cmd.sheet_path_flange": "ფლანეცი ტრაექტორიის გასწვრივ", + "cmd.sheet_perforate": "პერფორირება", + "cmd.sheet_refold": "ხელახლა მოკეცვა", + "cmd.sheet_rules": "ფურცლოვანი ლითონის წესების სია", + "cmd.sheet_unfold": "გაშლა", + "cmd.sketch.construction_line": "დამხმარე ხაზი", + "cmd.sketch.construction_line.angle": "დამხმარე ხაზი კუთხით", + "cmd.sketch.construction_line.bisector": "კუთხის ბისექტრისა", + "cmd.sketch.construction_line.horizontal": "ჰორიზონტალური დამხმარე ხაზი", + "cmd.sketch.construction_line.parallel": "პარალელური დამხმარე ხაზი", + "cmd.sketch.construction_line.perpendicular": "მართობული დამხმარე ხაზი", + "cmd.sketch.construction_line.tangent_at": "მხები მრუდის წერტილში", + "cmd.sketch.construction_line.tangent_external": "მხები გარე წერტილის გავლით", + "cmd.sketch.construction_line.tangent_two": "საერთო მხები", + "cmd.sketch.construction_line.vertical": "ვერტიკალური დამხმარე ხაზი", + "cmd.sketch_arc3d": "3D რკალი", + "cmd.sketch_arc_center_point": "რკალი ცენტრით", + "cmd.sketch_arc_tangent": "მხები რკალი", + "cmd.sketch_arc_three_point": "რკალი 3 წერტილით", + "cmd.sketch_auto_constrain": "ავტოშეზღუდვა", + "cmd.sketch_auto_constrain_from_datum": "ავტოშეზღუდვა საბაზო წერტილიდან", + "cmd.sketch_auto_project": "წიბოების ავტოპროეცირება ორიენტირზე", + "cmd.sketch_blend_curve": "გადასვლის მრუდი", + "cmd.sketch_cancel": "ესკიზის გაუქმება", + "cmd.sketch_chain": "ჯაჭვი", + "cmd.sketch_chamfer_distance_angle": "ფასკა მანძილით და კუთხით", + "cmd.sketch_chamfer_equal_distance": "ფასკა ტოლი მანძილით", + "cmd.sketch_chamfer_two_distance": "ფასკა ორი მანძილით", + "cmd.sketch_circle_center": "წრე ცენტრით და დიამეტრით", + "cmd.sketch_circle_three_point": "წრე 3 წერტილით", + "cmd.sketch_circle_three_tangent": "წრე 3 მხებით", + "cmd.sketch_circle_two_point": "წრე 2 წერტილით", + "cmd.sketch_circle_two_tangent": "წრე 2 მხებით", + "cmd.sketch_constrainer": "ესკიზის შემზღუდველი", + "cmd.sketch_constraint_fix": "ფიქსაცია/ფიქსაციის მოხსნა", + "cmd.sketch_constraint_midpoint": "შუა წერტილი", + "cmd.sketch_construction": "ჩვეულებრივი/დამხმარე", + "cmd.sketch_copy": "ესკიზის ელემენტების კოპირება", + "cmd.sketch_cut": "ესკიზის ელემენტების ამოჭრა", + "cmd.sketch_delete": "ესკიზის ელემენტების წაშლა", + "cmd.sketch_dimension_text": "ზომის ტექსტის გადაადგილება", + "cmd.sketch_drag": "ესკიზის გეომეტრიის გადათრევა", + "cmd.sketch_drag_end": "ესკიზის გადათრევის დასრულება", + "cmd.sketch_draw_dimensioned": "ზომებიანი ესკიზის გეომეტრიის ხატვა", + "cmd.sketch_drawing_bounds": "ნახაზის ზომა", + "cmd.sketch_edit": "ესკიზის რედაქტირება", + "cmd.sketch_edit_text": "ტექსტის რედაქტირება", + "cmd.sketch_equation_curve": "განტოლებით მოცემული მრუდი", + "cmd.sketch_equation_curve_edit": "განტოლებით მოცემული მრუდის რედაქტირება", + "cmd.sketch_export_dxf": "შენახვა DXF-ად", + "cmd.sketch_finish_auto_constrain": "დასრულება ავტოშეზღუდვით", + "cmd.sketch_fit_curves_to_section": "მრუდების მისადაგება ბადის კვეთზე", + "cmd.sketch_glyphs": "შეზღუდვის ნიშნები", + "cmd.sketch_include_3d": "3D გეომეტრიის ჩართვა", + "cmd.sketch_infinite": "უსასრულო ხაზი", + "cmd.sketch_insert_dxf": "DXF-ის ჩასმა", + "cmd.sketch_insert_svg": "SVG-ის ჩასმა", + "cmd.sketch_inspect": "ესკიზის შემოწმება", + "cmd.sketch_intersection_curve": "გადაკვეთის მრუდი", + "cmd.sketch_isoparametric_curve": "იზოპარამეტრული მრუდი", + "cmd.sketch_line3d": "3D ხაზი", + "cmd.sketch_line_midpoint": "ხაზი შუა წერტილით", + "cmd.sketch_loose_ends": "თავისუფალი ბოლოები", + "cmd.sketch_loose_ends_tie": "თავისუფალი ბოლოების შეერთება", + "cmd.sketch_move": "ესკიზის ელემენტების გადაადგილება/კოპირება", + "cmd.sketch_move3d": "3D წერტილის გადაადგილება", + "cmd.sketch_move_point": "ესკიზის წერტილის გადათრევა", + "cmd.sketch_offset_break": "წანაცვლების კავშირის გაწყვეტა", + "cmd.sketch_options": "ესკიზის პალიტრის პარამეტრები", + "cmd.sketch_paste": "ესკიზის ელემენტების ჩასმა", + "cmd.sketch_point3d": "3D წერტილი", + "cmd.sketch_polygon_circumscribed": "შემოხაზული მრავალკუთხედი", + "cmd.sketch_polygon_edge": "მრავალკუთხედი გვერდით", + "cmd.sketch_polygon_inscribed": "ჩახაზული მრავალკუთხედი", + "cmd.sketch_project_to_surface": "ზედაპირზე პროეცირება", + "cmd.sketch_rectangle_center": "მართკუთხედი ცენტრით", + "cmd.sketch_rectangle_rounded": "მომრგვალებული მართკუთხედი", + "cmd.sketch_rectangle_three_point": "მართკუთხედი 3 წერტილით", + "cmd.sketch_rectangle_two_point": "მართკუთხედი 2 წერტილით", + "cmd.sketch_redefine": "ესკიზის სიბრტყის ხელახლა განსაზღვრა", + "cmd.sketch_slot_arc_center": "რკალისებრი ღარი ცენტრით", + "cmd.sketch_slot_arc_three_point": "რკალისებრი ღარი სამი წერტილით", + "cmd.sketch_slot_center_point": "ღარი ცენტრით", + "cmd.sketch_slot_center_to_center": "ღარი ცენტრიდან ცენტრამდე", + "cmd.sketch_slot_overall": "ღარი სრული სიგრძით", + "cmd.sketch_snap": "მიბმის ავტომატური დადგენა", + "cmd.sketch_solve": "ესკიზის ამოხსნა", + "cmd.sketch_spline3d": "3D სპლაინი", + "cmd.sketch_spline_control_point": "სპლაინი მართვის წერტილებით", + "cmd.sketch_spline_control_point_5": "სპლაინი მართვის წერტილებით (ხარისხი 5)", + "cmd.sketch_spline_fit_point": "სპლაინი მისადაგების წერტილებით", + "cmd.sketch_spline_insert_point": "სპლაინის წერტილის დამატება", + "cmd.sketch_spline_remove_point": "სპლაინის წერტილის წაშლა", + "cmd.sketch_spline_reverse": "სპლაინის მიმართულების შებრუნება", + "cmd.sketch_spun_profile": "ბრუნვის პროფილი", + "cmd.sketch_toggle_diameter": "რადიუსის / დიამეტრის გადართვა", + "cmd.sketch_toggle_driven": "დამოკიდებული ზომის გადართვა", + "cmd.sketch_transform": "გარდაქმნა", + "cmd.sketch_trim_path": "მოკვეთა ტრაექტორიის გასწვრივ", + "cmd.solid_align": "სწორება", + "cmd.solid_boundary_fill": "საზღვრებით შევსება", + "cmd.solid_bounding_solid": "შემომსაზღვრელი სხეული", + "cmd.solid_emboss": "რელიეფი", + "cmd.solid_move": "გადაადგილება/კოპირება", + "cmd.solid_offset_face": "წახნაგის წანაცვლება", + "cmd.solid_press_pull": "გაწევა-შეწევა", + "cmd.solid_remove": "წაშლა", + "cmd.solid_replace_face": "წახნაგის ჩანაცვლება", + "cmd.solid_rib": "სიხისტის წიბო", + "cmd.solid_split_face": "წახნაგის დაყოფა", + "cmd.solid_web": "სიხისტის კედლები", + "cmd.surface_blend": "გადასვლის ზედაპირი", + "cmd.surface_boundary": "საზღვრებით მოცემული ზედაპირი", + "cmd.surface_extrude": "ზედაპირის ამოწევა", + "cmd.surface_fair": "ზედაპირის დაგლუვება", + "cmd.surface_fillet": "ზედაპირის მომრგვალება", + "cmd.surface_loft": "ზედაპირის კვეთებით აგება", + "cmd.surface_match": "ზედაპირის მისადაგება", + "cmd.surface_offset": "ზედაპირის წანაცვლება", + "cmd.surface_patch": "საკერებელი", + "cmd.surface_reverse_normal": "ნორმალის შებრუნება", + "cmd.surface_revolve": "ზედაპირის ბრუნვით აგება", + "cmd.surface_ruled": "წრფივმსახველიანი ზედაპირი", + "cmd.surface_stitch": "შეკერვა", + "cmd.surface_sweep": "ზედაპირის ტრაექტორიით აგება", + "cmd.surface_thicken": "გასქელება", + "cmd.surface_unstitch": "შეკერვის მოხსნა", + "cmd.surface_untrim": "მოკვეთის მოხსნა", + "cmd.timeline_add": "ჩაწერილი ოპერაციის დამატება", + "cmd.timeline_compute_all": "ყველაფრის გამოთვლა", + "cmd.timeline_copy": "ოპერაციების კოპირება", + "cmd.timeline_dependents": "დამოკიდებული ოპერაციები", + "cmd.timeline_export_script": "ბრძანებების სკრიპტის ექსპორტი", + "cmd.timeline_inspect": "ოპერაციის შემოწმება", + "cmd.timeline_paste": "ოპერაციების ჩასმა", + "cmd.timeline_play": "ქრონოლოგიის დაკვრა", + "cmd.timeline_redefine": "ოპერაციის რედაქტირება", + "cmd.timeline_rename": "სახელის შეცვლა", + "cmd.timeline_reorder": "ოპერაციის გადალაგება", + "cmd.timeline_roll_to": "ქრონოლოგიის მარკერის გადაწევა", + "cmd.timeline_rollback": "ქრონოლოგიის მარკერის გადატანა", + "cmd.timeline_stop": "ქრონოლოგიის დაკვრის შეჩერება", + "cmd.timeline_suppress": "ოპერაციის ჩახშობა", + "cmd.ui.assistant": "ასისტენტის ჩართვა/გამორთვა", + "cmd.view.render_browser": "რენდერის ხე", + "cmd.view.render_dock": "რენდერის პანელის გადატანა", + "cmd.view.render_focus": "რენდერის ფოკუსირებული ხედი", + "cmd.view.status_details": "ხედვის არის სტატუსის დეტალები", + "cmd.view.status_items": "ხედვის არის სტატუსის ელემენტები", + "cmd.view_ambient_occlusion": "გარემოს დაჩრდილვა", + "cmd.view_angle_readout": "ხედის კუთხეები", + "cmd.view_apply": "დასახელებული ხედის აღდგენა", + "cmd.view_back": "უკანა ხედი", + "cmd.view_bottom": "ქვედა ხედი", + "cmd.view_delete": "დასახელებული ხედის წაშლა", + "cmd.view_fit": "ჩატევა", + "cmd.view_front": "წინა ხედი", + "cmd.view_graphics_preset": "გრაფიკის პრესეტი", + "cmd.view_grid": "ბადე", + "cmd.view_ground_shadow": "ჩრდილი იატაკზე", + "cmd.view_home": "საწყისი ხედი", + "cmd.view_isometric": "იზომეტრიული ხედი", + "cmd.view_left": "მარცხენა ხედი", + "cmd.view_list": "დასახელებული ხედების სია", + "cmd.view_navigate": "ხედის ნავიგაცია", + "cmd.view_navigation_bar": "ნავიგაციის ზოლი", + "cmd.view_next_tab": "შემდეგი ჩანართი", + "cmd.view_normal_to": "მონიშნულის მართობულად", + "cmd.view_previous_tab": "წინა ჩანართი", + "cmd.view_rename": "დასახელებული ხედის სახელის შეცვლა", + "cmd.view_render_frame": "რენდერის კადრის დამხმარე ხაზები", + "cmd.view_right": "მარჯვენა ხედი", + "cmd.view_save": "ახალი დასახელებული ხედი", + "cmd.view_shots_strip": "კადრების ზოლი", + "cmd.view_spin": "უწყვეტი ორბიტა", + "cmd.view_tool": "ნავიგაციის ხელსაწყო", + "cmd.view_top": "ზედა ხედი", + "cmd.view_visual_style": "ვიზუალური სტილი", + "color.blue": "ლურჯი", + "color.copy": "ფერის მნიშვნელობების დასაკოპირებლად დაწკაპეთ", + "color.edit": "ფერის შესაცვლელად დაწკაპეთ", + "color.gamma": "ფერის მნიშვნელობები ნაჩვენებია 0-255 გამა-სივრცეში", + "color.green": "მწვანე", + "color.hex": "Hex", + "color.hex_help": "შეიყვანეთ #rrggbb ან #rrggbbaa; ექვსნიშნა მნიშვნელობა გაუმჭვირვალობას უცვლელს ტოვებს", + "color.hex_hint": "#rrggbb", + "color.hue": "ფერის ტონი", + "color.linear": "ფერის მნიშვნელობები ნაჩვენებია 0-1 წრფივ სივრცეში", + "color.recent": "ბოლოდროინდელი ფერები", + "color.recent_help": "ნებისმიერ ფერის ველში არჩეული ფერები აქ ჩნდება", + "color.red": "წითელი", + "color.saturation": "გაჯერება (პროცენტი)", + "color.saturation_value": "გაჯერება და სიკაშკაშე", + "color.selected": "არჩეული ფერი", + "color.step_down": "ერთი ბიჯით შემცირება", + "color.step_up": "ერთი ბიჯით გაზრდა", + "color.value": "სიკაშკაშე (პროცენტი)", + "config.column_filter_empty": "შესაბამისი სვეტები არ არის", + "config.rule_parameter_columns": "ჩამოთვლილია მხოლოდ ის პარამეტრები, რომლებსაც ცხრილში სვეტი აქვს. აქ გამოსაყენებლად დაამატეთ სვეტი ღილაკით „სვეტის დამატება“ (+).", + "config.rule_suppression_columns": "ჩამოთვლილია მხოლოდ ის ოპერაციები, რომლებსაც ცხრილში ჩახშობის სვეტი აქვს. აქედან სამართავად დაამატეთ სვეტი ღილაკით „სვეტის დამატება“ (+).", + "contact.components_count": "კომპონენტი: {count}", + "contact.enabled_label": "ჩართულია", + "coupling.gear_1": "კბილანა 1", + "coupling.gear_1_pick": "კბილანა 1 (არასავალდებულო)", + "coupling.gear_2": "კბილანა 2", + "coupling.gear_2_pick": "კბილანა 2 (არასავალდებულო)", + "coupling.internal": "შიდა კბილანა", + "coupling.needs_turn_and_slide": "საჭიროა ერთი მბრუნავი და ერთი მოსრიალე შეერთება", + "coupling.needs_turns": "საჭიროა ორი მბრუნავი შეერთება", + "coupling.not_round": "მრგვალი წახნაგი არ არის", + "coupling.nut": "ქანჩი", + "coupling.picked": "არჩეულია", + "coupling.pinion": "კბილანა", + "coupling.pinion_pick": "კბილანა (არასავალდებულო)", + "coupling.pitch": "ბიჯი", + "coupling.rack": "კბილა ლარტყა", + "coupling.radius_1": "რადიუსი 1", + "coupling.radius_2": "რადიუსი 2", + "crash.announce": "წინა ჯერზე SolidCraft მოულოდნელად დაიხურა ან შიდა შეცდომა მოხდა. ავარიის ანგარიში შენახულია (დახმარება > ავარიის ანგარიშები…).", + "crash.copy_folder": "საქაღალდის მისამართის კოპირება", + "crash.copy_path": "მისამართის კოპირება", + "crash.deleted": "წაიშალა ანგარიში: {count}.", + "crash.detected_time": "აღმოჩენილია {time} UTC", + "crash.intro": "ავარიის ანგარიშები ამ კომპიუტერზე რჩება და არსად იგზავნება. „შეტყობინება…“ ხსნის მონახაზს, რომელსაც გაზიარებამდე გადახედავთ.", + "crash.kind_command": "შიდა შეცდომა ბრძანებაში", + "crash.kind_internal": "შიდა შეცდომა", + "crash.kind_kernel": "ბირთვის შეცდომა (აღდგენილი)", + "crash.kind_unclean": "მოულოდნელად დაიხურა", + "crash.previous_session": "SolidCraft-ის წინა სესია მოულოდნელად დასრულდა ან შიდა შეცდომა მოხდა. არაკორექტული დასრულების ანგარიშები გაშვებისას ვლინდება. დეტალებისთვის იხილეთ დახმარება > ავარიის ანგარიშები…", + "crash.replayable": "გამეორებადი", + "crash.report": "შეტყობინება…", + "crash.unclean_explanation": "აღმოჩენილია მომდევნო გაშვებისას; დასრულების ზუსტი დრო არ ჩაწერილა. არაკორექტული დასრულება შეიძლება სისტემის გამორთვამ ან იძულებითმა შეჩერებამაც გამოიწვიოს.", + "delete.and_more": "… და კიდევ {count}", + "diagnostic.empty_boolean_component": "კომპონენტში '{component}' მოსაჭრელი ან გადასაკვეთი სხეული არ არის; ხელსაწყო შესაძლოა გადაფარავდეს '{body}'-ს კომპონენტში '{other}' — გააქტიურეთ ის კომპონენტი ან აირჩიეთ სხეული სამიზნედ", + "diagnostic.reselect_reference": "{feature}: ორიენტირი `{reference}` აღარ არსებობს ისე, როგორც არჩეული იყო; აირჩიეთ ის ხელახლა", + "dialog.bodies_count": "სხეული: {count}", + "dialog.clearance_invalid": "ღრეჩო უნდა იყოს 0-ის ტოლი ან მეტი სიგრძე", + "dialog.compute": "გამოთვლა", + "dialog.compute_again": "ხელახლა გამოთვლა", + "dialog.computing": "გამოითვლება… {seconds} წმ", + "dialog.could_not_be_checked": "ვერ შემოწმდა", + "dialog.custom_axis": "↖ მორგებული ღერძი", + "dialog.dimension_insert_hint": "მისი სახელის ჩასასმელად დაწკაპეთ სხვა მმართველ ზომაზე", + "dialog.dimension_name": "ზომა: {name}", + "dialog.edit_title": "რედაქტირება: {title}", + "dialog.no_shown_body": "შესაცვლელი ხილული სხეული არ არის: გამოაჩინეთ ერთი ან აირჩიეთ „ახალი სხეული“", + "dialog.pattern_sketch_not_object": "აირჩიეთ სხეულები ან ოპერაციები: ესკიზი არც ერთია და არც მეორე. მისი მრუდები გაიმეორეთ თავად ესკიზის მასივით ან არეკვლით, ან ჯერ ამოწიეთ.", + "dialog.select": "↖ მონიშვნა", + "dialog.selected_count": "↖ მონიშნულია: {count}", + "dialog.selection_constraint": "შეზღუდვა {id}", + "dialog.selection_external_curve": "{sketch} · მრუდი {id}", + "dialog.selection_guidance": "შესაცვლელად აირჩიეთ შესატანი ველი. მონიშნულ ობიექტებზე დაწკაპებით ისინი მოიხსნება; Ctrl/Cmd-დაწკაპებაც გადართავს მათ. გადახედეთ წინასწარ ხედს, შემდეგ დააჭირეთ OK-ს.", + "dialog.selection_midpoint": "შუა წერტილი · {id}", + "dialog.selection_profile": "{sketch} · პროფილი {number}", + "dialog.selection_step": "{step} / {total}: მონიშნეთ {input}", + "dialog.step": "ბიჯი", + "document.changed_on_disk": "{name} დისკზე შეიცვალა", + "document.changed_on_disk_detail": "{name} სხვა პროგრამამ ან კომპიუტერმა შეცვალა მას შემდეგ, რაც ის გახსენით ან ბოლოს შეინახეთ. „გადაწერა“ იმ ცვლილებებს თქვენით ჩაანაცვლებს; „ასლის შენახვა“ ორივეს ინახავს.", + "document.copy_name": "{name} ასლი", + "document.open_anyway": "მაინც გახსნა", + "document.open_elsewhere": "{name} უკვე გახსნილია", + "document.open_elsewhere_detail": "{name} გახსნილია SolidCraft {app}-ში, {who}-ზე, გაიხსნა {when}. თუ ორივე შეინახავთ, ერთ-ერთი თქვენგანი ნამუშევარს დაკარგავს. გახსენით მხოლოდ წასაკითხად, რომ ნახოთ ზედ გადაწერის გარეშე.", + "document.open_read_only": "მხოლოდ წასაკითხად გახსნა", + "document.opened_read_only": "გახსნილია მხოლოდ წასაკითხად: შენახვისას ახალი ფაილი მოითხოვება", + "document.overwrite": "გადაწერა", + "document.read_only_save": "ეს პროექტი მხოლოდ წასაკითხად გაიხსნა: შეინახეთ ახალ ფაილად", + "document.save_changes": "შევინახოთ ცვლილებები {name}-ში?", + "document.save_copy": "ასლის შენახვა…", + "document.unsaved_changes": "{name}-ში შეუნახავი ცვლილებებია. თუ არ შეინახავთ, ისინი დაიკარგება.", + "drive.rigid": "{joint} ხისტი შეერთებაა: ის დეტალებს უძრავად აკავებს, ამიტომ ასამოძრავებელი არაფერი აქვს. მათი ამოძრავებისთვის შეცვალეთ მისი ტიპი „შეერთების რედაქტირებაში“: „მბრუნავი“ ბრუნვისთვის, „მოსრიალე“ სრიალისთვის, „ცილინდრული“ ორივესთვის.", + "drive.stopped_by_contact": "შეჩერდა {value}-ზე: {a} {b}-ში გაივლიდა", + "drive.stopped_by_loop": "შეჩერდა {value}-ზე: {joint}-ზე გამავალი კონტური უფრო მეტად ვეღარ შეიკვრება", + "drive.unconnected": "არაფერს ამოძრავებს: {part} არცერთ უძრავად დამაგრებულ ელემენტთან არ არის დაკავშირებული", + "dxf.cancel_wait": "ექსპორტის შეჩერების მოლოდინი…", + "dxf.cancelled": "DXF-ის ექსპორტი გაუქმდა", + "dxf.cancelling": "DXF-ის ექსპორტის გაუქმება", + "dxf.exporting": "DXF-ის ექსპორტი", + "dxf.invalid_tolerance": "მრუდის დაშვება უნდა იყოს 0.0001-დან 1 mm-მდე.", + "dxf.progress.index": "ზედაპირების მომზადება (2/5)", + "dxf.progress.meshes": "პოლიგონური ბადეების მომზადება (1/5)", + "dxf.progress.occlusion": "დამალული ხაზების დადგენა (4/5)", + "dxf.progress.projection": "გეომეტრიის პროეცირება (3/5)", + "dxf.progress.write": "DXF-ის ჩაწერა (5/5)", + "dxf.tolerance": "მრუდის დაშვება", + "dxf.tolerance_help": "მხოლოდ ხილული სხეულები და ნაჩვენები ესკიზები. მრუდები სწორი სეგმენტებით გადმოიცემა. მცირე დაშვება უფრო ზუსტ მრუდებს იძლევა და მეტ დროსა და მეხსიერებას იყენებს.", + "each rail's curves must be in one sketch": "თითოეული მიმმართველის მრუდები ერთ ესკიზში უნდა იყოს", + "feature computation ended without a result": "ოპერაციის გამოთვლა შედეგის გარეშე დასრულდა", + "file.open.drawing_filter": "პროექტები, CAD ფაილები, პოლიგონური ბადეები და ნახაზები", + "file_load.built": "ჯერჯერობით აგებულია ოპერაცია: {built} / {total}.", + "file_load.converting": "მყარი სხეულის გარდაქმნა: {done} / {total}", + "file_load.inserting": "გეომეტრიის ჩასმა", + "file_load.link_item": "{name} ({done} / {total})", + "file_load.opening": "პროექტის გახსნა", + "file_load.preparing_thumbnail": "მინიატურის მომზადება...", + "file_load.preparing_view": "ხედის მომზადება...", + "file_load.preview_note": "შენახული გადახედვა. რედაქტირებამდე გეომეტრია მოწმდება.", + "file_load.reading": "ფაილის წაკითხვა...", + "file_load.reading_percent": "ფაილის წაკითხვა... {percent}%", + "file_load.rebuilding": "ოპერაციის თავიდან აგება: {done} / {total}", + "file_load.recovering": "პროექტის აღდგენა", + "file_load.step_build": "მოდელის აგება", + "file_load.step_feature": "ოპერაცია: {done} / {total}", + "file_load.step_part": "დეტალი: {done} / {total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "ფაილის წაკითხვა", + "file_load.step_rebuild": "ოპერაციების თავიდან აგება", + "file_load.step_repair": "დეტალების შემოწმება და შეკეთება", + "file_load.step_show": "ხედის მომზადება", + "file_load.stopping": "წინა ოპერაციის შეჩერების მოლოდინი...", + "file_load.updating_links": "ბმულების განახლება", + "file_load.waiting": "ფაილური ოპერაციის მოლოდინი", + "fits the face, e.g. M8": "ერგება წახნაგს, მაგ. M8", + "from the profile": "პროფილიდან", + "from the rule": "წესიდან", + "help.apache": "Apache ლიცენზია 2.0", + "help.appearance.assign": "არჩეულ სხეულებს, წახნაგებს ან კომპონენტებს ანიჭებს ფერს ან მასალის იერსახეს, მათი წონის შეუცვლელად. გამოიყენეთ დეტალების ერთმანეთისგან გასარჩევად ან ზედაპირის დამუშავების წინასწარ სანახავად.", + "help.assembly.bom": "ჩამოთვლის პროექტის ან კომპონენტის დეტალებს მათი რაოდენობით, დეტალის ნომრების მიხედვით, და შეუძლია სიის შენახვა CSV ან JSON ფორმატში. გამოიყენეთ როგორც დეტალების სია შეკვეთისა და აწყობისთვის.", + "help.attributions": "ავტორობის მითითებები (ATTRIBUTION.md)", + "help.build": "ვერსია {version} · კომიტი {commit} · აგებულია {date}", + "help.canvas.decal": "მოდელის ბრტყელ წახნაგზე ათავსებს გამოსახულებას, სტიკერივით. გამოიყენეთ დეტალზე ეტიკეტის, ლოგოს ან დაბეჭდილი ნახატის საჩვენებლად.", + "help.canvas.edit": "ცვლის ტილოს: მის პოზიციას, ზომას, კუთხეს, გაუმჭვირვალობას, არეკვლას, ხილვადობას ან სახელს. გამოიყენეთ საორიენტაციო გამოსახულების იმ ესკიზთან შესათავსებლად, რომელსაც მასზე გადაიხაზავთ.", + "help.canvas.insert": "ათავსებს PNG ან JPEG გამოსახულებას სიბრტყეზე ან წახნაგზე გამჭვირვალე საორიენტაციო ფონად. გამოიყენეთ ფოტოს ან ნახაზის ესკიზში გადასახაზად, გამოსახულების ცნობილ ზომამდე მასშტაბირებით.", + "help.component.break_link": "მიბმულ კომპონენტს მისი პროექტის ფაილს აწყვეტს და მის სხეულებს უცვლელად ინარჩუნებს. გამოიყენეთ, როცა დეტალმა აღარ უნდა მიჰყვეს საწყისი ფაილის ცვლილებებს.", + "help.component.capture_position": "ინარჩუნებს ხელით გადაადგილებული დეტალების პოზიციებს, ასე რომ ისინი ამ დეტალების ახალ ადგილად იქცევა. გამოიყენეთ დეტალების ადგილზე გადათრევის შემდეგ, თუ მათ შეერთება არ აკავებს.", + "help.component.create": "პროექტს ამატებს ახალ, ცარიელ კომპონენტს, აქტიური კომპონენტის შიგნით, თუ სხვა მშობელს არ აირჩევთ. გამოიყენეთ, რომ აწყობის ახალ დეტალს სხეულებისა და ესკიზებისთვის საკუთარი ადგილი ჰქონდეს.", + "help.component.finish_edit": "ინახავს ადგილზე რედაქტირებად დეტალს, უბრუნდება მის აწყობას და მის მიხედვით აახლებს აწყობას. გამოიყენეთ, როცა მიბმულ დეტალში ცვლილებებს დაასრულებთ.", + "help.component.from_bodies": "თითოეულ არჩეულ სხეულს ცალკე კომპონენტად აქცევს, სხეულის სახელით. გამოიყენეთ, როცა ცალკეული სხეულებით აგებული პროექტი უნდა იქცეს აწყობად, რომლის დეტალების შეერთება და გადაადგილება შეიძლება.", + "help.component.insert_design": "სვამს სხვა შენახულ პროექტს კომპონენტად, რომელიც მის ფაილზეა მიბმული, მყარი სხეულები კი იქ არსებული განლაგებით თავსდება. გამოიყენეთ დეტალის აწყობაში ხელახლა გამოსაყენებლად და შემდგომი ცვლილებების „ბმულების განახლებით“ მისაღებად.", + "help.component.properties": "აჩვენებს კომპონენტის მოცულობას, მასას, მასის ცენტრსა და ინერციის მომენტებს, მისი სხეულების მასალების მიხედვით. გამოიყენეთ აწყობის წონისა და წონასწორობის შესამოწმებლად.", + "help.component.revert_position": "ხელით გადაადგილებულ დეტალებს წინა ადგილზე აბრუნებს და დაუფიქსირებელ გადაადგილებებს აუქმებს. გამოიყენეთ აწყობაში საცდელი გადაადგილებების გასაუქმებლად.", + "help.component.update_links": "ხელახლა კითხულობს მიბმული პროექტების ფაილებს და ანაცვლებს სხეულებს, სადაც ისინი შეიცვალა. გამოიყენეთ იმ დეტალის რედაქტირების შემდეგ, რომელსაც ეს აწყობა იყენებს.", + "help.config.configure": "ამატებს პარამეტრებს, ოპერაციებს, მასალებს ან იერსახეებს კონფიგურაციების ცხრილის სვეტებად. გამოიყენეთ ერთი პროექტის ვარიანტების ასაგებად, მაგალითად, დეტალის სხვადასხვა ზომისთვის.", + "help.config.preview": "ამოწმებს, აიგება თუ არა კონფიგურაციების ცხრილის სტრიქონი, პროექტისა და მისი ისტორიის შეუცვლელად. გამოიყენეთ იმ ვარიანტზე გადართვამდე, რომელშიც დარწმუნებული არ ხართ.", + "help.config.rules": "აჩვენებს კონფიგურაციების ცხრილის წესებს, მის სტრიქონებს და რომელი სტრიქონია აქტიური. გამოიყენეთ, რათა ნახოთ, როგორაა მოწყობილი პროექტის ვარიანტები.", + "help.config.table": "აჩვენებს კონფიგურაციების ცხრილს: თითო სტრიქონი თითო ვარიანტზე, თითო სვეტი თითო პარამეტრზე ან ოპერაციაზე, და შეესაბამება თუ არა პროექტი ისევ აქტიურ სტრიქონს. გამოიყენეთ პროექტის ვარიანტების გადასახედად.", + "help.connect_note": "SolidCraft-ის სერვერის ჩასატვირთად გადატვირთეთ თითოეული ასისტენტი. თითოეული ფაილის სარეზერვო ასლი შეცვლამდე შეინახა .bak სახით.", + "help.connect_title": "AI ასისტენტების დაკავშირება", + "help.construct.axis.edge": "ქმნის დამხმარე ღერძს სწორი წიბოს ან ესკიზის ხაზის გასწვრივ. გამოიყენეთ როგორც ღერძი ბრუნვით აგებისთვის, წრიული მასივისთვის ან შეერთებისთვის.", + "help.construct.axis.normal_to_face": "ქმნის დამხმარე ღერძს, რომელიც გადის წერტილზე წახნაგის მართობულად. გამოიყენეთ ღერძისთვის, რომელიც ზედაპირიდან პირდაპირ გარეთ არის მიმართული.", + "help.construct.axis.through_cylinder": "ქმნის დამხმარე ღერძს ცილინდრის, კონუსის ან ტორის წახნაგის ან წრიული წიბოს ცენტრზე გავლით. გამოიყენეთ მრგვალი დეტალის გარშემო ოპერაციების შემოსაბრუნებლად ან მასივად გასამრავლებლად.", + "help.construct.axis.two_planes": "ქმნის დამხმარე ღერძს იქ, სადაც ორი სიბრტყე ან ბრტყელი წახნაგი ხვდება ერთმანეთს. გამოიყენეთ, როცა საჭირო ღერძი ორი წახნაგის შეხვედრის ხაზია.", + "help.construct.axis.two_points": "ქმნის დამხმარე ღერძს, რომელიც გადის ორ წერტილზე, წვეროზე ან ესკიზის წერტილზე. გამოიყენეთ ღერძისთვის, რომელიც ორ ცნობილ პოზიციას შორის გადის.", + "help.construct.plane.along_path": "ქმნის დამხმარე სიბრტყეს წიბოს ან მრუდის მართობულად, მის გასწვრივ მოცემულ პოზიციაზე. გამოიყენეთ პროფილის ესკიზის შესაქმნელად ტრაექტორიით აგებისთვის ან ტრაექტორიის კვეთისთვის.", + "help.construct.plane.at_angle": "ქმნის დამხმარე სიბრტყეს, რომელიც სიბრტყიდან ან წახნაგიდან კუთხით არის შემობრუნებული ღერძის ან წიბოს გარშემო. გამოიყენეთ დახრილი ესკიზებისთვის, მაგალითად, კუთხოვანი კრონშტეინისთვის.", + "help.construct.plane.axis_point": "ქმნის დამხმარე სიბრტყეს, რომელიც შეიცავს ღერძს და ამ ღერძის გარეთ მდებარე წერტილს. აირჩიეთ სათავის ან დამხმარე ღერძი, სწორი წიბო ან ესკიზის ხაზი, შემდეგ წვერო, ესკიზის წერტილი ან დამხმარე წერტილი. ღერძზე მდებარე წერტილი ცალსახა სიბრტყეს ვერ განსაზღვრავს.", + "help.construct.plane.midplane": "ქმნის დამხმარე სიბრტყეს ორ სიბრტყეს ან ბრტყელ წახნაგს შუა, ან მათ ბისექტორს, თუ ისინი კუთხით ხვდებიან ერთმანეთს. გამოიყენეთ როგორც სიმეტრიის სიბრტყე არეკვლისთვის.", + "help.construct.plane.offset": "ქმნის დამხმარე სიბრტყეს სიბრტყის ან ბრტყელი წახნაგის პარალელურად, მოცემულ მანძილზე ან წერტილზე გავლით. გამოიყენეთ წახნაგიდან განსაზღვრულ სიმაღლეზე ესკიზის შესაქმნელად.", + "help.construct.plane.perpendicular": "ქმნის დამხმარე სიბრტყეს, რომელიც შეიცავს ხაზს ან წიბოს და სიბრტყის ან წახნაგის მართობულად დგას. გამოიყენეთ მოდელზე წიბოს გასწვრივ ვერტიკალური ესკიზის შესაქმნელად.", + "help.construct.plane.tangent": "ქმნის დამხმარე სიბრტყეს, რომელიც ცილინდრს, კონუსს, სფეროს ან ტორს წერტილში ეხება. გამოიყენეთ მრგვალი დეტალის გვერდზე ესკიზის შესაქმნელად.", + "help.construct.plane.three_points": "ქმნის დამხმარე სიბრტყეს სამ წერტილზე გავლით. გამოიყენეთ მოდელზე პოზიციებით განსაზღვრული სიბრტყისთვის, მაგალითად, სამი კუთხით.", + "help.construct.plane.two_edges": "ქმნის დამხმარე სიბრტყეს ორ სწორ წიბოზე ან ხაზზე გავლით, რომლებიც ერთ სიბრტყეში მდებარეობს. გამოიყენეთ დეტალის გამჭოლი სიბრტყისთვის, მაგალითად, ორ მოპირდაპირე წიბოზე გამავალისთვის.", + "help.construct.point.along_path": "ქმნის დამხმარე წერტილს წიბოს ან მრუდის გასწვრივ მოცემულ პოზიციაზე. გამოიყენეთ როგორც ორიენტირი ტრაექტორიის შუალედურ ადგილას.", + "help.construct.point.center": "ქმნის დამხმარე წერტილს წრიული წიბოს, ესკიზის წრის ან რკალის, სფეროს ან ტორის ცენტრში. გამოიყენეთ როგორც ორიენტირი ხვრელების, ღერძებისა და შეერთებებისთვის.", + "help.construct.point.edge_plane": "ქმნის დამხმარე წერტილს იქ, სადაც წიბო ან ხაზი სიბრტყეს ან ბრტყელ წახნაგს კვეთს. გამოიყენეთ იმ ადგილის მოსანიშნად, სადაც ტრაექტორია სიბრტყეს კვეთს.", + "help.construct.point.three_planes": "ქმნის დამხმარე წერტილს იქ, სადაც სამი სიბრტყე ან ბრტყელი წახნაგი ხვდება ერთმანეთს. გამოიყენეთ როგორც კუთხის ორიენტირი, მაშინაც კი, როცა მოდელს იქ წვერო არ აქვს.", + "help.construct.point.two_edges": "ქმნის დამხმარე წერტილს იქ, სადაც ორი წიბო ან ხაზი ხვდება ერთმანეთს ან ყველაზე ახლოსაა. გამოიყენეთ როგორც ორიენტირი წარმოსახვით კუთხეში.", + "help.construct.point.vertex": "ქმნის დამხმარე წერტილს წვეროზე ან ესკიზის წერტილზე. გამოიყენეთ როგორც ორიენტირი, რომელიც რჩება, როცა მის გარშემო ესკიზი ან სხეული დამალულია.", + "help.contact.check": "ჩამოთვლის კონტაქტის ნაკრებებში შემავალი დეტალების იმ წყვილებს, რომლებიც მიმდინარე პოზიციაში ერთმანეთში გადის. გამოიყენეთ შეჯახებების მოსაძებნად შეერთებების ამოძრავებამდე ან მოძრაობის კვლევის გაშვებამდე.", + "help.contact.create": "ორ ან მეტ დეტალს აჯგუფებს კონტაქტის ნაკრებად, რომლის სხეულებს შეერთებების მოძრაობისას ერთმანეთში გავლა არ შეუძლიათ. გამოიყენეთ დეტალებისთვის, რომლებიც შეხებისას უნდა გაჩერდეს, მაგალითად, ბერკეტი თავის საბჯენთან.", + "help.contact.disable_all": "გამორთავს კონტაქტს, ასე რომ ამოძრავებული შეერთებები და მოძრაობის კვლევები აღარ ჩერდება იქ, სადაც დეტალები ერთმანეთს ეხება. გამოიყენეთ დეტალების ისევ თავისუფლად გადასაადგილებლად ან დიდი აწყობის სწრაფი რეაგირების შესანარჩუნებლად.", + "help.contact.edit": "ცვლის კონტაქტის ნაკრებს: მასში შემავალ დეტალებს, მის სახელს ან ჩახშობილია თუ არა; შეუძლია ნაკრების წაშლაც. გამოიყენეთ იმის დასარეგულირებლად, რომელ დეტალებს არ შეუძლიათ ერთმანეთში გავლა.", + "help.contact.enable_all": "აწყობის ყველა დეტალს ერთ კონტაქტის ნაკრებში ათავსებს, ასე რომ შეერთებების მოძრაობისას ვერცერთი ორი დეტალი ერთმანეთში ვერ გაივლის. გამოიყენეთ მთელი მექანიზმის სწრაფი შემოწმებისთვის.", + "help.contact.enable_sets": "რთავს კონტაქტს თქვენ მიერ განსაზღვრული კონტაქტის ნაკრებებისთვის, ასე რომ ამოძრავებული შეერთებები და მოძრაობის კვლევები ჩერდება იქ, სადაც მათი დეტალები ერთმანეთში გაივლიდა. გამოიყენეთ კონტაქტის გამორთვის შემდეგ თქვენი ნაკრებების დასაბრუნებლად.", + "help.contact.list": "ჩამოთვლის პროექტის კონტაქტის ნაკრებებს, თითოეულში შემავალ დეტალებს და ჩართულია თუ არა კონტაქტი. გამოიყენეთ კონტაქტის პარამეტრების შესამოწმებლად აწყობის ამოძრავებამდე.", + "help.document.inspect": "აჩვენებს პროექტის მიმოხილვას: მის კომპონენტებს, სხეულებს, ესკიზებს, ოპერაციებსა და პარამეტრებს. გამოიყენეთ იმ პროექტში გასარკვევად, რომელიც თავად არ აგიგიათ.", + "help.document.units": "ცვლის ერთეულებს, რომლებშიც პროექტი სიგრძეებს აჩვენებს, მაგალითად, mm ან დუიმები. გეომეტრია ზომას ინარჩუნებს; იცვლება მხოლოდ ჩვენება და ერთეულის გარეშე შეყვანილი რიცხვები.", + "help.edit.checkpoint": "იმახსოვრებს პროექტს, აქტიურ ესკიზსა და ისტორიას მათი ამჟამინდელი სახით. გამოიყენეთ სარისკო ცდამდე, რომლიდანაც შეიძლება უკან დაბრუნება მოგინდეთ.", + "help.edit.restore_checkpoint": "უბრუნდება საკონტროლო წერტილს, ისტორიის ჩათვლით. გამოიყენეთ საკონტროლო წერტილის შემდეგ გაკეთებული ყველაფრის ერთი ნაბიჯით გასაუქმებლად.", + "help.explode.create": "ქმნის დაშლილ ხედს, რომელიც დეტალებს აწყობის ცენტრიდან აშორებს, ან თქვენ მიერ მითითებული გადაადგილებებით. გამოიყენეთ იმის საჩვენებლად, როგორ იწყობა აწყობა, ინსტრუქციებისა და პრეზენტაციებისთვის.", + "help.face.delete": "შლის არჩეულ წახნაგებს და მეზობელ წახნაგებს ღრეჩოს დახურვის საშუალებას აძლევს, ან ღრეჩოს ღიად ტოვებს ზედაპირის სახით. გამოიყენეთ ხელისშემშლელი მომრგვალებული წიბოს, ხვრელის ან დგარის მოსაშორებლად.", + "help.file.insert_mesh": "პროექტს ამატებს 3MF, STL, OBJ, PLY ან glTF ფაილს პოლიგონური ბადის სხეულებად ახალ კომპონენტში. გამოიყენეთ ჩამოტვირთული ან დასკანერებული მოდელის თქვენი პროექტის გვერდით საორიენტაციოდ მოსათავსებლად.", + "help.file.insert_step": "პროექტს ამატებს STEP, IGES, FreeCAD ან Rhino ფაილს მყარ სხეულებად ახალ კომპონენტში; აწყობის დეტალები ჩადგმულ კომპონენტებად იქცევა. გამოიყენეთ მომწოდებლებისგან ან სხვა CAD პროგრამებიდან მოდელების შემოსატანად.", + "help.file.save_mesh": "ინახავს სხეულებს STL, 3MF ან OBJ პოლიგონურ ბადედ, მრუდე წახნაგების თქვენ მიერ არჩეული სიგლუვით. გამოიყენეთ დეტალების 3D ბეჭდვისთვის ან პოლიგონური ბადეების წამკითხველი პროგრამებისთვის მოსამზადებლად.", + "help.file.send_to_slicer": "ინახავს არჩეულ სხეულებს 3MF ფაილად და ხსნის მას თქვენ მიერ არჩეულ სლაისერში. გამოიყენეთ მოდელიდან ბეჭდვაზე ერთი ნაბიჯით გადასასვლელად.", + "help.font_details": "ინტერფეისი იყენებს egui-ის ჩაშენებულ შრიფტებს (Ubuntu Light და Hack, Ubuntu Font Licence-ისა და MIT/Bitstream Vera ლიცენზიით; Noto Emoji და ემოჯის ხატულების შრიფტი, OFL-ისა და MIT-ის ლიცენზიით). ესკიზის ტექსტი იყენებს Liberation Sans-ს (SIL OFL 1.1). Crafting Apps-ის არასავალდებულო შრიფტების პაკეტი craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1) SolidCraft-ის ანაწყობებში არ შედის.", + "help.fonts": "შრიფტები", + "help.frame.member": "ათავსებს პროფილს, მაგალითად, მილს ან ალუმინის ექსტრუზიულ პროფილს, ჩარჩოს ესკიზის ხაზების გასწვრივ, თითო ელემენტს თითო ხაზზე. გამოიყენეთ ჩარჩოების, სტელაჟებისა და შედუღებული კონსტრუქციების ასაგებად.", + "help.inspect.accessibility": "აფერადებს წახნაგებს, რომლებსაც ხელსაწყო ერთი მიმართულებიდან მიწვდება, და იმათ, რომლებსაც ვერ. გამოიყენეთ იმის შესამოწმებლად, შეიძლება თუ არა დეტალის ამ მხრიდან მექანიკური დამუშავება ან ყალიბში ჩამოსხმა.", + "help.inspect.center_of_mass": "აჩვენებს სხეულების მასის ცენტრს, თითოეულისას ცალკე და ყველასას ერთად, ერთგვაროვანი სიმკვრივის დაშვებით. გამოიყენეთ წონასწორობის შესამოწმებლად და იმის გასარკვევად, საით გადაყირავდება დეტალი.", + "help.inspect.colored_components": "თითოეულ კომპონენტს საკუთარ დროებით ფერს ანიჭებს, იერსახეების შეუცვლელად. გამოიყენეთ აწყობის დეტალების ერთი შეხედვით გასარჩევად.", + "help.inspect.compare": "ადარებს ორ სხეულს და აჩვენებს, სად აქვს ერთს მასალა, რომელიც მეორეს არ აქვს, მოცულობითა და გადახრით. გამოიყენეთ შეცვლილი ან იმპორტირებული დეტალის ორიგინალთან შესადარებლად.", + "help.inspect.continuity": "ამოწმებს, რამდენად გლუვად ერთდება წახნაგები წიბოების გასწვრივ: ღრეჩოები, გადატეხვები ან სიმრუდის ნახტომები, და ნაკერებს ფერით გამოყოფს. გამოიყენეთ იმ ადგილების მოსაძებნად, სადაც ზედაპირები სუფთად არ ერთდება.", + "help.inspect.curvature_comb": "ხატავს სავარცხლებს მრუდების, წიბოების ან წახნაგების გასწვრივ, რომელთა კბილები აჩვენებს, რამდენად ძლიერად იღუნებიან ისინი. გამოიყენეთ ბრტყელი უბნების, გადატეხვებისა და არათანაბარი სიმრუდის აღმოსაჩენად.", + "help.inspect.curvature_map": "აფერადებს წახნაგებს სიმრუდის სიძლიერის მიხედვით, წითლად იქ, სადაც რადიუსი მცირეა. გამოიყენეთ მკვეთრი მოსახვევების მოსაძებნად და ზედაპირის სიგლუვის შესაფასებლად.", + "help.inspect.draft": "აფერადებს წახნაგებს მათი დახრის კუთხის მიხედვით ამოღების მიმართულების მიმართ და მონიშნავს იმათ, რომლებსაც ძალიან მცირე დახრა აქვს. გამოიყენეთ დეტალის შესამოწმებლად ყალიბში ჩამოსხმამდე ან ლითონის ჩამოსხმამდე.", + "help.inspect.environment_map": "აჩვენებს მოდელს ამრეკლი, სარკისებრი საფარით. გამოიყენეთ ზედაპირების დინების შესაფასებლად იმის მიხედვით, როგორ მიედინება მათზე ანარეკლები.", + "help.inspect.interference": "პოულობს ერთმანეთში შეჭრილ სხეულებს და აჩვენებს თითოეულ გადაფარვას მისი მოცულობით. გამოიყენეთ აწყობაში ერთმანეთთან შეჯახებული დეტალების აღმოსაჩენად.", + "help.inspect.isocurve": "ხატავს წახნაგების იზოპარამეტრულ მრუდებს, ბადეს, რომელზეც ზედაპირია აგებული. გამოიყენეთ, რათა ნახოთ, როგორ მიედინება ზედაპირი და სად არის იგი შეჯგუფებული.", + "help.inspect.measure": "ზომავს სიგრძეებს, მანძილებს, კუთხეებს, ფართობებსა და რადიუსებს არჩეულ ობიექტებს შორის, ან სხეულების მოცულობასა და მასას. გამოიყენეთ ზომებისა და ღრეჩოების შესამოწმებლად.", + "help.inspect.minimum_radius": "პოულობს მრუდების, წიბოების ან წახნაგების სიმრუდის უმცირეს რადიუსს და მის ადგილს. გამოიყენეთ იმის შესამოწმებლად, შეძლებს თუ არა ხელსაწყო ან საქშენი ფორმის გაყოლას.", + "help.inspect.section": "ჭრის ხედს სიბრტყის გასწვრივ და აშტრიხავს ჭრილის წახნაგებს, მოდელის შეუცვლელად. გამოიყენეთ დეტალებისა და აწყობების შიგნით შესახედად.", + "help.inspect.zebra": "აჩვენებს მოდელის წახნაგებზე არეკლილ შავ-თეთრ ზოლებს. გამოიყენეთ სიგლუვის შესაფასებლად: ზოლები, რომლებიც წიბოსთან წყდება ან ტყდება, ცუდ გადასვლაზე მიუთითებს.", + "help.joint.as_built": "აერთებს ორ დეტალს იქ, სადაც ისინი უკვე არიან, რომელიმეს გადაადგილების გარეშე, და ადგენს, როგორ შეუძლიათ კვლავ მოძრაობა. გამოიყენეთ დეტალებისთვის, რომლებიც უკვე საბოლოო პოზიციაზე მოათავსეთ.", + "help.joint.cam": "მბრუნავ კულაჩს აკავშირებს ბიძგასთან, ასე რომ ბიძგა სრიალებს ან ირხევა, როცა კულაჩის კონტური მის ქვეშ გადის. გამოიყენეთ კულაჩებისთვის, ექსცენტრიკებისა და სარქველის ამძრავებისთვის.", + "help.joint.create": "აერთებს ორ დეტალს თქვენ მიერ არჩეულ შეერთების სათავეებში და მეორე დეტალს ადგილზე გადააადგილებს; შეერთების ტიპი ადგენს, როგორ შეუძლიათ კვლავ მოძრაობა. გამოიყენეთ აწყობის ასაგებად, რომლის დეტალები ნამდვილი მექანიზმივით მოძრაობს.", + "help.joint.drive": "აყენებს შეერთების კუთხეს ან მანძილს და მასთან ერთად დეტალებს ამოძრავებს, მისი ზღვრების ფარგლებში; დაკავშირებული შეერთებები და შეკრული კონტურები მიჰყვება. გამოიყენეთ იმის შესამოწმებლად, მოძრაობს თუ არა მექანიზმი ჩაფიქრებისამებრ.", + "help.joint.gear": "აკავშირებს ორ მბრუნავ შეერთებას გადაცემის რიცხვით, ასე რომ ერთის ამოძრავება მეორეს აბრუნებს. გამოიყენეთ ცილინდრული და შიდა კბილანებისთვის, გადაცემის რიცხვით საწყისი წრეწირების რადიუსებიდან ან კბილების რაოდენობიდან.", + "help.joint.limits": "ადგენს, რამდენად შეუძლია შეერთებას მობრუნება ან გასრიალება, მინიმუმითა და მაქსიმუმით, ან აუქმებს ამ ზღვრებს. გამოიყენეთ ანჯამის, მოსრიალე ელემენტის ან ბერკეტის მისი რეალური სვლის ფარგლებში შესანარჩუნებლად.", + "help.joint.motion_link": "აწყვილებს ორ შეერთებას კოეფიციენტითა და წანაცვლებით, ასე რომ ერთის ამოძრავება მეორეს ამოძრავებს. გამოიყენეთ შეერთებებს შორის მუდმივი დამოკიდებულებისთვის, რომელსაც „კბილანა“, „კბილა ლარტყა და კბილანა“ ან „ხრახნი“ არ მოიცავს.", + "help.joint.origin": "დეტალზე ათავსებს დასახელებულ შეერთების სათავეს: წახნაგის ან მრგვალი ბოლოს ცენტრში, წიბოს შუაში, კუთხეში ან წერტილში. გამოიყენეთ შეერთებების მიმაგრების ადგილების მოსამზადებლად; წახნაგზე არჩეული სათავე მას მიჰყვება, როცა დეტალის ზომა იცვლება.", + "help.joint.rack_pinion": "მბრუნავ კბილანას აკავშირებს მოსრიალე კბილა ლარტყასთან, ასე რომ ლარტყა გადაადგილდება საწყისი წრეწირის იმ სიგრძით, რომელზეც კბილანა გადაგორდება. გამოიყენეთ კბილალარტყული ამძრავებისთვის, საჭის მექანიზმებისა და წრფივი პლატფორმებისთვის.", + "help.joint.reach": "დეტალზე არსებულ წერტილს სამიზნისკენ ამოძრავებს მისი ჯაჭვის შეერთებების შეცვლით, მათი ზღვრების ფარგლებში. გამოიყენეთ მექანიზმის პოზის დასაყენებლად იმის მიხედვით, სად უნდა იყოს მისი ბოლო, მაგალითად, რობოტის მკლავის წვერი.", + "help.joint.rigid_group": "არჩეულ დეტალებს ერთმანეთთან ამაგრებს ისე, როგორც არიან, ასე რომ ისინი ერთად მოძრაობს. გამოიყენეთ დეტალებისთვის, რომლებიც ერთმანეთს ეკუთვნის და მათ შორის მოძრაობა არ არის.", + "help.joint.screw": "ბრუნვასა და სრიალს აკავშირებს ბიჯით, ასე რომ ყოველი ბრუნი ამ მანძილით წინ წაწევს. გამოიყენეთ სასვლელი ხრახნებისთვის, ჭანჭიკებისა და კუთხვილიანი შპინდელებისთვის.", + "help.library.apply": "ანიჭებს სხეულებს, წახნაგებს ან კომპონენტებს მასალას ან იერსახეს ლოკალური ბიბლიოთეკის ფაილიდან. გამოიყენეთ სხვა პროექტიდან შენახული მასალების ხელახლა გამოსაყენებლად.", + "help.library.export": "ინახავს პროექტის მასალებსა და იერსახეებს ბიბლიოთეკის ფაილში. გამოიყენეთ მათ გასაზიარებლად ან სხვა პროექტებში ხელახლა გამოსაყენებლად.", + "help.library.inspect": "ამოწმებს ბიბლიოთეკის ფაილს და ჩამოთვლის მის მასალებსა და იერსახეებს, პროექტის შეუცვლელად. გამოიყენეთ, რათა მიანიჭებამდე ნახოთ, რას შეიცავს ბიბლიოთეკა.", + "help.licences": "ლიცენზიები", + "help.material.assign": "ადგენს, რისგან არის დამზადებული არჩეული სხეულები, მაგალითად, ფოლადი, ალუმინი ან ABS. გამოიყენეთ, რომ მასა და წონა ნამდვილ დეტალს შეესაბამებოდეს.", + "help.material.properties.validate": "ამოწმებს მასალის მონაცემთა ბარათს რიცხვების შეთანხმებულობასა და გამოტოვებულ მნიშვნელობებზე. გამოიყენეთ, სანამ ამ მონაცემებს მასის ან სიხისტის გამოსათვლელად დაეყრდნობით.", + "help.mesh.convert": "ბადის სხეულს, მაგალითად, STL-ს, გადააგებს რედაქტირებად მყარ სხეულად ბრტყელი და ცილინდრული წახნაგებით. გამოიყენეთ იმპორტირებული მექანიკური დეტალების მოდელირებული სხეულის მსგავსად შესაცვლელად.", + "help.mit": "MIT ლიცენზია", + "help.motion.study": "აყენებს შეერთებების მნიშვნელობებს დროის ღერძის ნაბიჯებზე და ანიმაციად უკრავს მათ. გამოიყენეთ მექანიზმის მოძრაობის თანმიმდევრობის სანახავად და გზადაგზა ღრეჩოების შესამოწმებლად.", + "help.motion.trace": "იწერს ტრაექტორიას, რომელსაც დეტალის წერტილი გადის მოძრაობის კვლევის დაკვრისას ან შეერთების ამოძრავებისას, და დადასტურებისას ინახავს მას 3D ესკიზის მრუდად. გამოიყენეთ იმის სანახავად, სადამდე აღწევს მექანიზმი, ან მის ტრაექტორიაზე ასაგებად.", + "help.notice": "NOTICE", + "help.occurrence.ground": "დეტალს ადგილზე ამაგრებს ან ისევ ათავისუფლებს, ასე რომ შეერთებები სხვა დეტალებს მის გარშემო ამოძრავებს. გამოიყენეთ ჩარჩოსთვის ან ფუძისთვის, რომელზეც დანარჩენი აწყობაა აგებული.", + "help.occurrence.move": "აწყობის დეტალს გადააადგილებს მხოლოდ მისი შეერთებებით დაშვებული თავისუფლების ხარისხებით. მონიშნეთ დეტალის წახნაგი, შემდეგ გადაათრიეთ ხელმისაწვდომი ისარი ან რკალი.", + "help.parameters.change": "ხსნის დასახელებული მნიშვნელობებისა და გამოსახულებების ცხრილს, რომლებიც პროექტის ზომებს მართავს. გამოიყენეთ ზომის ერთ ადგილას შესაცვლელად, რომ მის გამომყენებელ ყველა ოპერაციას ეს ცვლილება მიჰყვეს.", + "help.parameters.export": "ინახავს პროექტის პარამეტრებს CSV ან JSON ფორმატში. გამოიყენეთ მათ ელცხრილში დასარედაქტირებლად ან სხვა პროექტში გადასატანად.", + "help.parameters.graph": "აჩვენებს, რომელი პარამეტრები და ოპერაციები რომელ სხვებს იყენებს, და მათ შორის არსებულ ციკლებსა თუ შეცდომებს. გამოიყენეთ, რათა ნახოთ, რაზე იმოქმედებს პარამეტრის შეცვლა.", + "help.parameters.import": "კითხულობს პარამეტრებს CSV-დან ან JSON-დან პროექტში, ან ყველას ერთად, ან არცერთს. გამოიყენეთ ელცხრილიდან ან სხვა პროექტიდან მნიშვნელობების შემოსატანად.", + "help.parameters.move": "გადააადგილებს მომხმარებლის პარამეტრს სიაში სხვა პარამეტრის წინ ან შემდეგ. გამოიყენეთ დაკავშირებული პარამეტრების ერთად შესანარჩუნებლად.", + "help.parts.fastener": "ამატებს სტანდარტულ ხრახნს, ჭანჭიკს, ქანჩს, საყელურს, შტიფტს ან საკისარს თქვენ მიერ არჩეული ზომით. ხვრელზე მოთავსებისას ის ხვრელში შეერთებით ჯდება, ასე რომ სამაგრი ელემენტების მოდელირება თავად არ გიწევთ.", + "help.parts.insert": "სვამს სტანდარტულ დეტალს თქვენ მიერ არჩეული ოჯახით, ზომითა და სიგრძით. ხვრელის ნაპირზე ან კედელზე მოთავსებისას ის ხვრელზე ხისტი შეერთებით ჯდება.", + "help.parts.library": "ხსნის სტანდარტულ დეტალებს: ხრახნებს, ჭანჭიკებს, ქანჩებს, საყელურებს, საყრდენ ხრახნებს, ცილინდრულ შტიფტებსა და საკისრებს სტანდარტული ზომებით. გამოიყენეთ სტანდარტული დეტალის დასამატებლად, მისი თავად მოდელირების ნაცვლად.", + "help.parts.resize": "ცვლის ჩასმული სტანდარტული დეტალის ზომას ან სიგრძეს და თავიდან აგებს მას; მისი შეერთებები მას ადგილზე აკავებს. გამოიყენეთ, როცა ხრახნი ზედმეტად გრძელი აღმოჩნდება ან ხვრელს სხვა ზომა სჭირდება.", + "help.plastic.assign_rule": "ანიჭებს სხეულებს პლასტმასის წესს, რათა მათმა პლასტმასის ოპერაციებმა ნაგულისხმევად მისი დახრა და ღრეჩო აიღონ. გამოიყენეთ ყალიბში ჩამოსხმული დეტალის პარამეტრების ერთხელ, მისი ყველა ოპერაციისთვის დასაყენებლად.", + "help.plastic.boss": "ამატებს ხრახნის დგარს წახნაგზე: სვეტს არასავალდებულო ხვრელით, დახრით, ძირის მომრგვალებითა და სიხისტის წიბოებით. გამოიყენეთ ხრახნის სამაგრი წერტილებისთვის ყალიბში ჩამოსხმულ ან დაბეჭდილ კორპუსებში.", + "help.plastic.lip": "ამატებს შვერილს ან მის შესაბამის ღარს გარსად ქცეული სხეულის ნაპირის გასწვრივ. გამოიყენეთ, რათა კორპუსის ორი ნახევარი ერთმანეთზე სწორად დაჯდეს და მჭიდროდ დაიხუროს.", + "help.plastic.manage_rules": "ქმნის და არედაქტირებს პლასტმასის წესებს: მასალა, კედლის სისქე, რადიუსები, ღრეჩო და დახრა. გამოიყენეთ ისინი ყალიბში ჩამოსხმული დეტალის ოპერაციების ერთგვაროვნების შესანარჩუნებლად.", + "help.plastic.rest": "ამატებს საყრდენს წახნაგზე: მრგვალ ან მართკუთხა ბაქანს, მასიურს ან ღრუს, დახრით. გამოიყენეთ ბჯენად ან დისტანციურ დგარად ყალიბში ჩამოსხმულ კორპუსში.", + "help.plastic.snap_fit": "ამატებს ჩამკეტ კავს წახნაგზე, მისი სიგრძით, სისქითა და კბილით. გამოიყენეთ დეტალების ხრახნების გარეშე ერთმანეთზე დასამაგრებლად.", + "help.pointcloud.insert": "სვამს PLY, XYZ ან PTS სკანს წერტილების ღრუბლად მოდელის გვერდით. გამოიყენეთ საორიენტაციოდ, როცა მოდელს გაზომილი მონაცემებით აგებთ.", + "help.sheet.convert": "თანაბარი სისქის ფილას ან გარსად ქცეულ სხეულს ფურცლოვანი ლითონის სხეულად აქცევს, თქვენ მიერ არჩეულ წიბოებზე მოღუნვებით. გამოიყენეთ არსებული დეტალის გაშლადად საქცევად.", + "help.sheet.export_bend_table": "ინახავს ფურცლოვანი ლითონის სხეულის მოღუნვების ცხრილს CSV ან JSON ფორმატში: კუთხეები, რადიუსები და მოღუნვების პოზიციები გაშლილ მდგომარეობაში. გამოიყენეთ მოსაღუნი პრესისთვის ან სახელოსნოსთვის.", + "help.sheet.export_dxf": "ინახავს გაშლილ ფორმას DXF ფორმატში, კონტურებით, მოღუნვის ხაზებითა და არასავალდებულო მოღუნვის შენიშვნებით. გამოიყენეთ ლაზერული, პლაზმური ან წყლის ჭავლით ჭრისთვის.", + "help.sheet.flange": "ამატებს ფლანეცს: საბაზო ფილას ესკიზიდან, კედელს ესკიზის ღია კონტურის გასწვრივ ან მოღუნულ კედელს ფურცლის წიბოებზე. გამოიყენეთ ფურცლოვანი ლითონის დეტალების ასაგებად.", + "help.sheet.flat_pattern": "ქმნის ფურცლოვანი ლითონის სხეულის გაშლილ ფორმას, მისი ზომით, ამონაჭრებითა და მოღუნვის ხაზებით. გამოიყენეთ ნამზადის შესამოწმებლად მის გაჭრამდე.", + "help.sheet.fold": "ღუნავს ფურცელს ესკიზის ხაზის გასწვრივ მოცემული კუთხითა და რადიუსით. გამოიყენეთ ბრტყელი ფურცლის მოსაკეცად მასში ოპერაციების ამოჭრის შემდეგ.", + "help.sheet.hem": "გადაკეცავს ფურცლის წიბოს თავის თავზე. გამოიყენეთ უსაფრთხო, მყარი წიბოებისთვის ბასრი ხორკლების გარეშე.", + "help.sheet.manage_rules": "ქმნის და არედაქტირებს ფურცლოვანი ლითონის წესებს: სისქე, მოღუნვის რადიუსი, K-ფაქტორი, განტვირთვის ჭრილები და ღრეჩოები. გამოიყენეთ ისინი თქვენი სახელოსნოს მასალისა და ხელსაწყოების შესაბამისად.", + "help.sheet.path_flange": "ამატებს ფლანეცების ჯაჭვს ფურცლის წიბოს გასწვრივ, ესკიზის ხაზების ღია ჯაჭვის მიხედვით. გამოიყენეთ ისეთი პროფილებისთვის, როგორიცაა U ან Z ფორმა, ერთი ნაბიჯით.", + "help.sheet.perforate": "ამატებს ხვრელების ველს მთელ ბრტყელ ფურცელზე, ჭადრაკული ან კვადრატული განლაგებით. გამოიყენეთ სავენტილაციო ხვრელებისთვის, ცხაურებისა და მსუბუქი პანელებისთვის.", + "help.sheet.refold": "გაშლილ ფურცლოვანი ლითონის სხეულს ხელახლა კეცავს. გამოიყენეთ ბრტყელ ფურცელზე ოპერაციების დამატების შემდეგ.", + "help.sheet.unfold": "შლის ფურცლოვანი ლითონის სხეულის ყველა მოღუნვას. გამოიყენეთ ისეთი ხვრელების ან ჭრილების დასამატებლად, რომლებმაც მოღუნვა უნდა გადაკვეთონ, შემდეგ კი ხელახლა მოკეცეთ.", + "help.sketch.arc.center_point": "ხატავს წრიულ რკალს ცენტრის გარშემო, საწყისი წერტილიდან ბოლო წერტილამდე. გამოიყენეთ, როცა რკალის ცენტრი ცნობილია, მაგალითად, რადიუსი ხვრელის ან სახსრის გარშემო.", + "help.sketch.arc.tangent": "ხატავს რკალს, რომელიც ხაზის ან რკალის ბოლოდან იწყება და მის მხებად გრძელდება. გამოიყენეთ ჯაჭვის გლუვი მოხვევით გასაგრძელებლად, კუთხის ნაცვლად.", + "help.sketch.arc.three_point": "ხატავს რკალს საწყისი წერტილიდან ბოლო წერტილამდე მესამე წერტილის გავლით. გამოიყენეთ, როცა რკალმა მოცემულ წერტილებზე უნდა გაიაროს და არა ცნობილი ცენტრის გარშემო.", + "help.sketch.arc3d": "ხატავს ზუსტ წრიულ რკალს სივრცეში სამი წერტილის გავლით, როცა 3D ესკიზი ჩართულია. გამოიყენეთ ტრაექტორიებისა და მიმმართველების მოსახვევებისთვის, რომლებიც ესკიზის სიბრტყიდან გადიან.", + "help.sketch.auto_constrain": "ამატებს შეზღუდვებს, რომლებიც ესკიზს თითქმის უკვე აქვს, მაგალითად, ჰორიზონტალურობა, პარალელურობა ან დამთხვევა, შემდეგ კი ზომებს ადებს, სანამ სრულად განსაზღვრული არ გახდება. გამოიყენეთ უხეშად დახატული ესკიზის ერთი ნაბიჯით დასაფიქსირებლად.", + "help.sketch.auto_constrain_from_datum": "მუშაობს როგორც ავტოშეზღუდვა, ოღონდ პოზიციებს ზომავს თქვენ მიერ არჩეული საბაზო წერტილიდან და არა სათავიდან. გამოიყენეთ, როცა დეტალი ერთი საორიენტაციო წერტილიდან არის განლაგებული, მაგალითად, კუთხიდან ან ხვრელიდან.", + "help.sketch.blend_curve": "ორი მრუდის ბოლოებს აერთებს გლუვი სპლაინით, რომელიც ორივეს მხებია, ან სურვილისამებრ სიმრუდითაც უწყვეტი. გამოიყენეთ მრუდებს შორის ღრეჩოს გადასაბმელად გადატეხვის გარეშე.", + "help.sketch.break": "მრუდს ნაწილებად ყოფს იქ, სადაც მას სხვა მრუდები კვეთს, ან მასზე თქვენ მიერ დასმულ წერტილებში. გამოიყენეთ, როცა მრუდის ნაწილს საკუთარი შეზღუდვა სჭირდება ან ცალკე უნდა წაიშალოს.", + "help.sketch.cancel": "ტოვებს ესკიზს და აუქმებს ყველა ცვლილებას მისი შექმნის ან რედაქტირებისთვის გახსნის შემდეგ. „დაბრუნება“ ცვლილებებს აღადგენს.", + "help.sketch.centerline": "ხაზებს გადართავს ჩვეულებრივ ხაზებსა და ღერძულ ხაზებს შორის — ღერძებს, რომლებსაც პროფილები არ ითვალისწინებს. ღერძული ხაზი გამოიყენეთ ბრუნვით აგების, არეკვლის ან სიმეტრიის შეზღუდვის ღერძად.", + "help.sketch.chamfer.distance_angle": "ორ ხაზს შორის კუთხეს ფასკით ჭრის, რომელიც პირველი ხაზის გასწვრივ მანძილითა და კუთხით არის მოცემული. გამოიყენეთ, როცა ნახაზზე ფასკა სიგრძითა და კუთხით არის მითითებული, მაგალითად, 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "ორ ხაზს შორის კუთხეს ფასკით ჭრის ორივე ხაზის გასწვრივ ერთნაირი მანძილით. გამოიყენეთ კონტურზე ჩვეულებრივი 45° ფასკისთვის.", + "help.sketch.chamfer.two_distance": "ორ ხაზს შორის კუთხეს ფასკით ჭრის, რომელიც თითოეული ხაზის გასწვრივ ცალკე მანძილით არის მოცემული. გამოიყენეთ არა 45°-იანი ფასკებისთვის, რომლებიც ორი სიგრძით არის მოცემული.", + "help.sketch.circle.center": "ხატავს წრეს მისი ცენტრითა და დიამეტრით. გამოიყენეთ ხვრელებისთვის, დგარებისა და სხვა მრგვალი ელემენტებისთვის, რომელთა ცენტრი ცნობილია.", + "help.sketch.circle.three_point": "ხატავს წრეს სამი წერტილის გავლით. გამოიყენეთ, როცა წრემ მოცემულ წერტილებზე უნდა გაიაროს, მაგალითად, არსებული გეომეტრიის წერტილებზე.", + "help.sketch.circle.three_tangent": "ხატავს წრეს, რომელიც სამ ხაზს, წრეს ან რკალს ეხება. გამოიყენეთ სამ მრუდს შორის სივრცეში წრის ჩასატევად, მაგალითად, სამკუთხედში ჩახაზული წრისთვის.", + "help.sketch.circle.two_point": "ხატავს წრეს მისი დიამეტრის ორი ბოლოთი. გამოიყენეთ, როცა ცნობილია წრეწირის წერტილები და არა მისი ცენტრი.", + "help.sketch.circle.two_tangent": "ხატავს მოცემული ზომის წრეს, რომელიც ორ ხაზს, წრეს ან რკალს ეხება. გამოიყენეთ ორ მრუდს შორის ფიქსირებული რადიუსით მოსამრგვალებლად.", + "help.sketch.conic": "ხატავს კონიკურ მრუდს ორ ბოლო წერტილს შორის, რომლის ფორმას წვეროს წერტილი და rho მნიშვნელობა განსაზღვრავს. გამოიყენეთ გლუვი გადასვლებისთვის, რომელთა სისავსის რეგულირებაც გსურთ, ბრტყლიდან თითქმის მკვეთრ კუთხემდე.", + "help.sketch.constrainer": "იყენებს შეზღუდვას, რომელიც ერთ ან ორ არჩეულ მრუდს თითქმის უკვე აქვს, მაგალითად, ჰორიზონტალურობა, პარალელურობა, მხებობა ან ტოლობა. გამოიყენეთ ხელით დახატული ესკიზის თითო დამოკიდებულებით მოსაწესრიგებლად.", + "help.sketch.constraint.coincident": "წერტილს ათავსებს სხვა წერტილზე, მრუდზე ან ესკიზის ღერძზე. გამოიყენეთ პროფილში ღრეჩოების დასახურად ან წერტილის ხაზზე მოსათავსებლად.", + "help.sketch.constraint.collinear": "ორ ხაზს ერთ წრფეზე ათავსებს. გამოიყენეთ შეწყვეტილი წიბოების ერთ ხაზზე გასასწორებლად, მაგალითად, ჭრილის ორივე მხარისა.", + "help.sketch.constraint.concentric": "ორ წრეს ან რკალს საერთო ცენტრს აძლევს, ან წრის ან რკალის ცენტრს ესკიზის წერტილზე ათავსებს, სათავის ჩათვლით. აირჩიეთ ნებისმიერი წყვილი ნებისმიერი თანმიმდევრობით.", + "help.sketch.constraint.curvature": "ბოლო წერტილში შემხვედრ ორ მრუდს ერთნაირი სიმრუდით აგრძელებს (G2). გამოიყენეთ იქ, სადაც მხებით მიერთება საკმარისად გლუვი არ არის, მაგალითად, ხილულ ზედაპირებზე.", + "help.sketch.constraint.equal": "ხაზებს ერთნაირ სიგრძეს, ან წრეებსა და რკალებს ერთნაირ რადიუსს ანიჭებს. გამოიყენეთ, რომ ერთმა ზომამ რამდენიმე შესაბამისი ელემენტი მართოს.", + "help.sketch.constraint.fix": "წერტილებს ან მრუდებს ადგილზე აფიქსირებს ან ისევ ათავისუფლებს. გამოიყენეთ გეომეტრიისთვის, რომელიც არ უნდა გადაადგილდეს ესკიზის გადათრევისას ან ამოხსნისას.", + "help.sketch.constraint.horizontal_vertical": "ხაზს, ან ორ წერტილს შორის ხაზს, ჰორიზონტალურს ან ვერტიკალურს ხდის, იმის მიხედვით, რომელი უფრო ახლოსაა. გამოიყენეთ კონტურის ესკიზის ღერძებთან გასასწორებლად.", + "help.sketch.constraint.midpoint": "წერტილს ხაზის შუაში ათავსებს, ან ორი ხაზის შუა წერტილებს ამთხვევს. გამოიყენეთ გეომეტრიის წიბოზე ცენტრირებისთვის.", + "help.sketch.constraint.parallel": "ორ ხაზს პარალელურს ხდის. გამოიყენეთ გვერდებისთვის, რომლებიც პარალელური უნდა დარჩეს სხვა ზომების შეცვლისას.", + "help.sketch.constraint.perpendicular": "ორ ხაზს მართი კუთხით ახვედრებს ერთმანეთს. გამოიყენეთ მართი კუთხეებისთვის იმ ხაზებს შორის, რომლებიც ესკიზის ღერძებზე არ არის.", + "help.sketch.constraint.polygon": "ხაზების შეკრულ ჯაჭვს წესიერ მრავალკუთხედად აქცევს: ტოლი გვერდებით, ყველა კუთხით ერთ წრეწირზე. გამოიყენეთ ხელით დახატული მრავალკუთხედის წესიერად საქცევად და ასე შესანარჩუნებლად.", + "help.sketch.constraint.symmetry": "ორ წერტილს ან მრუდს ერთმანეთის სარკისებრს ხდის ხაზის ან წერტილის მიმართ. გამოიყენეთ პროფილის სიმეტრიულად შესანარჩუნებლად, როცა ერთ მხარეს ცვლით.", + "help.sketch.constraint.tangent": "ორ მრუდს მხებად ახვედრებს, მაგალითად, ხაზსა და რკალს. გამოიყენეთ გლუვი მიერთებებისთვის გადატეხვის გარეშე.", + "help.sketch.construction": "მრუდებს გადართავს ჩვეულებრივ და დამხმარე გეომეტრიას შორის, რომელსაც პროფილები არ ითვალისწინებს. დამხმარე მრუდები გამოიყენეთ განლაგების, ორიენტირებისა და ზომების დამხმარედ.", + "help.sketch.construction_line": "ქმნის უსასრულო დამხმარე ხაზს ორი წერტილის გავლით. გამოიყენეთ ესკიზის განლაგებისთვის პროფილების გაყოფის გარეშე.", + "help.sketch.construction_line.angle": "ქმნის უსასრულო დამხმარე ხაზს ესკიზის X-ის მიმართ კუთხით. აირჩიეთ წერტილი და აკრიფეთ კუთხე, ან აირჩიეთ მისი მიმართულება.", + "help.sketch.construction_line.bisector": "აირჩიეთ ესკიზის ორი გადამკვეთი სწორი ხაზი, შემდეგ აირჩიეთ კუთხის რომელიმე ბისექტრისა. შედეგი თავის საწყის ხაზებს მიჰყვება.", + "help.sketch.construction_line.horizontal": "ქმნის უსასრულო ჰორიზონტალურ დამხმარე ხაზს წერტილის გავლით. მისი ჰორიზონტალურობის შეზღუდვა შემდგომ ცვლილებებს მიჰყვება.", + "help.sketch.construction_line.parallel": "აირჩიეთ ესკიზის სწორი ხაზი, შემდეგ მოათავსეთ პარალელური უსასრულო დამხმარე ხაზი. სხვა ორიენტირის ასარჩევად დაწკაპეთ მარჯვენა ღილაკით.", + "help.sketch.construction_line.perpendicular": "აირჩიეთ ესკიზის სწორი ხაზი, შემდეგ მოათავსეთ მართობული უსასრულო დამხმარე ხაზი. სხვა ორიენტირის ასარჩევად დაწკაპეთ მარჯვენა ღილაკით.", + "help.sketch.construction_line.tangent_at": "ქმნის მხებს წრის ან წრიული რკალის წერტილში, ან ღია სპლაინის ან კონიკური მრუდის ბოლო წერტილში. აირჩიეთ მრუდი, შემდეგ მისი შეხების წერტილი.", + "help.sketch.construction_line.tangent_external": "აირჩიეთ წრე ან წრიული რკალი, შემდეგ გარე წერტილი და მხების ამონახსნი. წინასწარ ხედებში ჩანს მხოლოდ დახატულ რკალზე არსებული შეხების წერტილები.", + "help.sketch.construction_line.tangent_two": "აირჩიეთ ორი წრე ან წრიული რკალი, შემდეგ წინასწარ ხედში აირჩიეთ საერთო მხები. შეხების წერტილები დახატულ მრუდებზე უნდა იყოს.", + "help.sketch.construction_line.vertical": "ქმნის უსასრულო ვერტიკალურ დამხმარე ხაზს წერტილის გავლით. მისი ვერტიკალურობის შეზღუდვა შემდგომ ცვლილებებს მიჰყვება.", + "help.sketch.copy": "აკოპირებს ესკიზის არჩეულ მრუდებსა და წერტილებს, მათ შორის არსებულ შეზღუდვებთან და ზომებთან ერთად. ჩასვით ისინი ამ ან სხვა ესკიზში.", + "help.sketch.create": "იწყებს ახალ 2D ესკიზს სიბრტყეზე ან მოდელის ბრტყელ წახნაგზე. ყოველი ამოწევა, ბრუნვით აგება და ტრაექტორიით აგება ესკიზით იწყება.", + "help.sketch.cut": "აკოპირებს ესკიზის არჩეულ გეომეტრიას და შლის მას ესკიზიდან, ერთ დაბრუნების ნაბიჯად. ჩასვით ის ამ ესკიზის სხვა ადგილას ან სხვა ესკიზში.", + "help.sketch.dimension": "ამატებს მმართველ ზომას: სიგრძეს, მანძილს, კუთხეს, რადიუსს ან დიამეტრს, იმის მიხედვით, რას აირჩევთ. აკრიფეთ მნიშვნელობა ან პარამეტრის სახელი და ესკიზი მას მიჰყვება.", + "help.sketch.edit": "ხსნის არსებულ ესკიზს რედაქტირებისთვის. მასზე აგებული ოპერაციები ესკიზის დასრულებისას განახლდება.", + "help.sketch.ellipse": "ხატავს ელიფსს მისი ცენტრით, დიდი ღერძის ბოლოთი და მცირე ღერძის მხარეს არსებული წერტილით. გამოიყენეთ ოვალური ხვრელებისთვის, კულაჩებისა და სხვა წაგრძელებული მრგვალი ფორმებისთვის.", + "help.sketch.equation_curve": "ხატავს მრუდს ფორმულებით: x(t) და y(t), ან y = f(x), მოცემულ დიაპაზონზე. ფორმულებს შეუძლიათ პარამეტრების გამოყენება და მრუდი მათ მიჰყვება: გამოიყენეთ სინუსოიდისთვის, სპირალისთვის ან კბილანას კბილის ევოლვენტისთვის.", + "help.sketch.extend": "აგრძელებს ხაზს ან რკალს გზაზე არსებულ უახლოეს მრუდამდე, ან ორ მრუდს მათ შეხვედრამდე აგრძელებს. გამოიყენეთ პროფილში ღრეჩოების დასახურად მოკვეთის ან რედაქტირების შემდეგ.", + "help.sketch.fillet": "ამრგვალებს ორი ხაზის ან რკალის შეხვედრის კუთხეს მოცემული რადიუსის რკალით. ერთად მომრგვალებულ რამდენიმე კუთხეს საერთო რადიუსი აქვს.", + "help.sketch.finish": "ტოვებს ესკიზს და უბრუნდება მოდელს. ამის შემდეგ მისი შეკრული პროფილები მზადაა ამოწევისთვის, ბრუნვით აგებისა და სხვა ოპერაციებისთვის.", + "help.sketch.finish_auto_constrain": "ესკიზზე უშვებს ავტოშეზღუდვას, შემდეგ კი ასრულებს მას. გამოიყენეთ, რომ ესკიზი ერთი ნაბიჯით სრულად განსაზღვრული დატოვოთ.", + "help.sketch.fit_curves_to_section": "ჭრის პოლიგონურ ბადეს ან მყარ სხეულს ესკიზის სიბრტყით და კვეთს ხაზებსა და რკალებს უსადაგებს. გამოიყენეთ დასკანერებული ან იმპორტირებული დეტალის რედაქტირებად ესკიზად აღსადგენად.", + "help.sketch.include_3d": "მოდელის წიბოებს, წვეროებს და სხვა ესკიზების მრუდებს ამ ესკიზში მიბმულ ორიენტირებად შემოიტანს, მისი სიბრტყის გარეთ მყოფებს კი მასზე აბრტყელებს. გამოიყენეთ გეომეტრიაზე დასაყრდნობად, რომელიც ესკიზის სიბრტყეში არ დევს.", + "help.sketch.infinite": "ხაზებს გადართავს ჩვეულებრივ ხაზებსა და უსასრულო დამხმარე ხაზებს შორის, რომლებიც მთელ ხედს კვეთს. გამოიყენეთ ისინი განლაგების ორიენტირებად, რომლებიც არასოდეს აღმოჩნდება ზედმეტად მოკლე.", + "help.sketch.insert_dxf": "ესკიზში კითხულობს DXF ნახაზის მრუდებს, თქვენ მიერ მითითებული მასშტაბით, შემობრუნებითა და პოზიციით. გამოიყენეთ სხვა პროგრამის 2D ნახაზზე დასაყრდნობად, მაგალითად, ლაზერული ჭრის კონტურზე.", + "help.sketch.insert_svg": "ესკიზში კითხულობს SVG ნახაზის ტრაექტორიებს, თქვენ მიერ მითითებული მასშტაბით, შემობრუნებითა და პოზიციით. გამოიყენეთ ლოგოს ან ვექტორული კონტურის ამოსაწევ მრუდებად საქცევად.", + "help.sketch.inspect": "ხსნის ანგარიშს ღია ესკიზზე: რამდენი თავისუფლების ხარისხია დარჩენილი და სრულად შეზღუდულია თუ არა. გამოიყენეთ ესკიზის დასრულებამდე იმის გასარკვევად, რა მოძრაობს ჯერ კიდევ.", + "help.sketch.intersect": "ამატებს მრუდებს ან წერტილებს იქ, სადაც სხეულები, წახნაგები, წიბოები ან სხვა ესკიზები ესკიზის სიბრტყეს კვეთს. ისინი მიბმული რჩება და მოდელის შეცვლისას მას მიჰყვება.", + "help.sketch.intersection_curve": "ქმნის 3D მრუდებს ორი სხეულის ან წახნაგის შეხვედრის ადგილას, მათზე მიბმულს. გამოიყენეთ ისინი ტრაექტორიებად ან მიმმართველებად, რომლებიც მოდელს მიჰყვება.", + "help.sketch.isoparametric_curve": "ქმნის 3D მრუდს წახნაგის U ან V მიმართულებით თქვენ მიერ არჩეული წერტილის გავლით, წახნაგზე მიბმულს. გამოიყენეთ ტრაექტორიად ან გამყოფ ხაზად, რომელიც ზედაპირს მიჰყვება.", + "help.sketch.line": "ხატავს ერთმანეთთან დაკავშირებულ ხაზებს წერტილ-წერტილ, ღია ჯაჭვად ან შეკრულ კონტურად. ეს ძირითადი ხელსაწყოა პროფილების უმეტესობისთვის.", + "help.sketch.line.midpoint": "ხატავს ხაზს მისი შუა წერტილიდან ერთ ბოლომდე, მეორე ბოლო კი სარკისებრად აისახება. გამოიყენეთ წერტილზე ცენტრირებული ხაზებისთვის, მაგალითად, სიმეტრიული წიბოსთვის.", + "help.sketch.line3d": "ხატავს ერთმანეთთან დაკავშირებულ სწორ ხაზებს სივრცის წერტილებს შორის, როცა 3D ესკიზი ჩართულია. გამოიყენეთ ტრაექტორიებისა და ჩარჩოებისთვის, რომლებიც ესკიზის სიბრტყიდან გადიან.", + "help.sketch.mirror": "ირეკლავს ესკიზის მრუდებსა და წერტილებს ხაზის ან ღერძის მიმართ და ამატებს სიმეტრიის შეზღუდვებს. გამოიყენეთ სიმეტრიული პროფილის ნახევრის დასახატად და მის დასასრულებლად.", + "help.sketch.move": "გადააადგილებს ან აბრუნებს ესკიზის მრუდებსა და წერტილებს, ან მათ ასლს. გამოიყენეთ გეომეტრიის ახალ ადგილას გადასატანად მისი ფორმისა და შეზღუდვების შენარჩუნებით.", + "help.sketch.offset": "ქმნის მრუდების ჯაჭვის ასლს მოცემულ მანძილზე, ერთ ან ორივე მხარეს. გამოიყენეთ კედლების, კონტურებისა და ღრეჩოებისთვის; მანძილი რედაქტირებად ზომად რჩება.", + "help.sketch.paste": "აქტიურ ესკიზში სვამს თქვენ მიერ დაკოპირებულ ან ამოჭრილ ესკიზის გეომეტრიას. მოათავსეთ ის წერტილში ან გადაწიეთ წანაცვლებით.", + "help.sketch.pattern.circular": "აკოპირებს ესკიზის გეომეტრიას ცენტრის გარშემო, სრულ წრეზე ან მოცემულ კუთხეზე. გამოიყენეთ ჭანჭიკების წრიული განლაგებისთვის, სხივებისა და კბილებისთვის.", + "help.sketch.pattern.rectangular": "აკოპირებს ესკიზის გეომეტრიას მწკრივებად და სვეტებად მოცემული ბიჯით. გამოიყენეთ ხვრელების, ღარების ან სავენტილაციო ჭრილების ბადეებისთვის.", + "help.sketch.point": "ათავსებს ესკიზის წერტილს. გამოიყენეთ ზომების, შეზღუდვების, ხვრელების ცენტრების ან შემდგომი ოპერაციების ორიენტირად.", + "help.sketch.point3d": "ათავსებს წერტილს სივრცეში, როცა 3D ესკიზი ჩართულია. გამოიყენეთ 3D მრუდებისა და ტრაექტორიების ორიენტირად.", + "help.sketch.polygon.circumscribed": "ხატავს წრეზე შემოხაზულ წესიერ მრავალკუთხედს, ზომით ცენტრიდან გვერდის შუამდე. გამოიყენეთ, როცა ცნობილია ზომა წახნაგებს შორის, მაგალითად, ექვსწახნაგა ქანჩისთვის.", + "help.sketch.polygon.edge": "ხატავს წესიერ მრავალკუთხედს ერთი გვერდის ორი ბოლოთი. გამოიყენეთ, როცა ცნობილია გვერდის სიგრძე და პოზიცია.", + "help.sketch.polygon.inscribed": "ხატავს წრეში ჩახაზულ წესიერ მრავალკუთხედს, ზომით ცენტრიდან კუთხემდე. გამოიყენეთ, როცა ცნობილია ზომა კუთხეებს შორის.", + "help.sketch.project": "მოდელის წიბოებს, წახნაგებს, წვეროებს და სხვა ესკიზების მრუდებს ამ ესკიზში შემოიტანს, მის სიბრტყეზე დაპროეცირებულს. ისინი მიბმული რჩება და მოდელის შეცვლისას მას მიჰყვება.", + "help.sketch.project_to_surface": "აპროეცირებს სხვა ესკიზების მრუდებს ამ ესკიზის ნორმალის გასწვრივ წახნაგზე, მიბმულ 3D მრუდებად. გამოიყენეთ ლოგოს, გამყოფი ხაზის ან ტრაექტორიის მრუდ ზედაპირზე დასატანად.", + "help.sketch.rectangle.center": "ხატავს მართკუთხედს მისი ცენტრითა და ერთი კუთხით. გამოიყენეთ წერტილზე ცენტრირებული კონტურებისთვის, მაგალითად, სათავეზე.", + "help.sketch.rectangle.rounded": "ხატავს მართკუთხედს, რომლის ოთხივე კუთხე ერთი რადიუსით არის მომრგვალებული. გამოიყენეთ ფირფიტების, სახურავებისა და მომრგვალებულკუთხიანი ხვრელებისთვის.", + "help.sketch.rectangle.three_point": "ხატავს მართკუთხედს ერთი გვერდითა და მოპირდაპირე მხარეს არსებული წერტილით. გამოიყენეთ ესკიზის ღერძების მიმართ დახრილი მართკუთხედებისთვის.", + "help.sketch.rectangle.two_point": "ხატავს მართკუთხედს ორი მოპირდაპირე კუთხით. გამოიყენეთ ფირფიტების, ბლოკებისა და ჩაღრმავებების კონტურებისთვის.", + "help.sketch.scale": "მასშტაბირებს ესკიზის მრუდებსა და წერტილებს კოეფიციენტით საბაზო წერტილის მიმართ. გამოიყენეთ ესკიზის ნაწილის ზომის შესაცვლელად ხელახლა დახატვის გარეშე.", + "help.sketch.slot.arc_center": "ხატავს მოცემული სიგანის მრუდ ღარს რკალის გასწვრივ, რომელიც ცენტრით, დასაწყისითა და ბოლოთი არის მოცემული. გამოიყენეთ სარეგულირებელი ღარებისთვის სახსრის გარშემო.", + "help.sketch.slot.arc_three_point": "ხატავს მოცემული სიგანის მრუდ ღარს სამ წერტილზე გამავალი რკალის გასწვრივ. გამოიყენეთ, როცა ღარის ტრაექტორიამ მოცემულ წერტილებზე უნდა გაიაროს.", + "help.sketch.slot.center_point": "ხატავს მოცემული სიგანის სწორ ღარს მისი ცენტრიდან ერთი ბოლო რკალის ცენტრამდე. გამოიყენეთ წერტილზე ცენტრირებული ღარებისთვის.", + "help.sketch.slot.center_to_center": "ხატავს მოცემული სიგანის სწორ ღარს მისი ორი ბოლო რკალის ცენტრებს შორის. გამოიყენეთ ცენტრიდან ცენტრამდე ზომით მოცემული ღარებისთვის, მაგალითად, ხრახნების სარეგულირებელი ღარებისთვის.", + "help.sketch.slot.overall": "ხატავს მოცემული სიგანის სწორ ღარს ერთი გარე ბოლოდან მეორემდე. გამოიყენეთ, როცა მნიშვნელოვანია ღარის სრული სიგრძე.", + "help.sketch.spline.control_point": "ხატავს კუბურ სპლაინს, რომლის ფორმას მართვის წერტილები განსაზღვრავს და რომლებზეც ის არ გადის. გამოიყენეთ გლუვი, მდინარე მრუდებისთვის, რომელთა ფორმას წერტილების გადაადგილებით აძლევთ.", + "help.sketch.spline.control_point_5": "ხატავს მე-5 ხარისხის სპლაინს, რომლის ფორმას მართვის წერტილები განსაზღვრავს. გამოიყენეთ იქ, სადაც მრუდები უფრო გლუვი სიმრუდით უნდა შეუერთდეს ერთმანეთს, მაგალითად, ხილულ დიზაინერულ ზედაპირებზე.", + "help.sketch.spline.fit_point": "ხატავს გლუვ სპლაინს, რომელიც თქვენ მიერ დასმულ ყველა წერტილზე გადის, ღიას ან შეკრულს. გამოიყენეთ ცნობილ წერტილებზე გამავალი ფორმის გადასახაზად.", + "help.sketch.spline3d": "ხატავს გლუვ მრუდს სივრცეში წერტილების გავლით, როცა 3D ესკიზი ჩართულია. გამოიყენეთ ტრაექტორიით აგების ტრაექტორიებისა და კაბელების გაყვანისთვის, რომლებიც ესკიზის სიბრტყიდან გადიან.", + "help.sketch.spun_profile": "ესკიზის სიბრტყეში ქმნის კონტურს, რომელსაც სხეული ღერძის გარშემო ბრუნვისას შემოწერს. გამოიყენეთ ჩარხზე დამუშავებული დეტალის სილუეტის მისაღებად ბრუნვით აგებისთვის ან ნახაზისთვის.", + "help.sketch.text": "წერს ტექსტს ესკიზში არჩეული შრიფტით, სიმაღლითა და კუთხით; მისი სიტყვები შეიძლება პარამეტრებს მიჰყვებოდეს. ამოწიეთ ის ან რელიეფად აქციეთ ეტიკეტებისა და წარწერებისთვის.", + "help.sketch.transform": "ესკიზის გეომეტრიას ცენტრის მიმართ ერთი ნაბიჯით მასშტაბირებს, აბრუნებს და გადააადგილებს. გამოიყენეთ მონიშნულის ერთდროულად გადასაადგილებლად და ზომის შესაცვლელად.", + "help.sketch.trim": "შლის მრუდის იმ ნაწილს, რომელიც დაწკაპების ადგილის გარშემო უახლოეს გადაკვეთებს შორისაა. გამოიყენეთ ერთმანეთზე გადამფარავი ხაზების შეკრულ პროფილად გასასუფთავებლად.", + "help.solid.align": "არჩეულ სხეულებს ისე გადააადგილებს, რომ მათზე არსებული წერტილი, წახნაგი ან სიბრტყე სხვაგან არსებულ წერტილს, წახნაგს ან სიბრტყეს დაემთხვეს. გამოიყენეთ დეტალის მეორესთან მისადებად წანაცვლების გაზომვის გარეშე.", + "help.solid.boundary_fill": "ქმნის მყარ სხეულებს გადამფარავი ხელსაწყო-სხეულებით შემოსაზღვრული რეგიონებიდან და ავსებს მხოლოდ თქვენ მიერ არჩეულ რეგიონებს. გამოიყენეთ ფორმის ასაგებად იმ სივრციდან, რომელსაც რამდენიმე სხეული ერთად შემოსაზღვრავს.", + "help.solid.bounding_solid": "ქმნის პარალელეპიპედს, რომელიც არჩეულ სხეულებს მოიცავს, არასავალდებულო მარაგით. გამოიყენეთ დეტალის გაბარიტული ზომის სანახავად ან ნამზადად, რომლისგანაც ის მუშავდება.", + "help.solid.box": "ქმნის პარალელეპიპედს სიგრძით, სიგანითა და სიმაღლით, კუთხის წერტილიდან ან წერტილზე ცენტრირებულს. გამოიყენეთ სწრაფი ბლოკისთვის, დროებითი ჩანაცვლებისთვის ან სხეულისთვის, რომელშიც ოპერაციებს ამოჭრით.", + "help.solid.chamfer": "ჭრის არჩეულ წიბოებს მოცემული მანძილის ბრტყელი ფასკით. გამოიყენეთ ბასრი წიბოების მოსახსნელად ან შტიფტის ან ხრახნის შესვლის გასაადვილებლად.", + "help.solid.coil": "ქმნის სპირალურ სხეულს, მაგალითად, ზამბარას, დიამეტრით, ხვიებით, სიმაღლით ან ბიჯით და მრგვალი ან კვადრატული კვეთით. გამოიყენეთ ზამბარებისთვის, ხვიებისა და სპირალური ქიმებისთვის.", + "help.solid.combine": "აერთიანებს სხეულებს, ამოჭრის მათ სამიზნე სხეულიდან ან ინარჩუნებს მხოლოდ მათ საერთო მოცულობას, და შეუძლია ხელსაწყო-სხეულების შენარჩუნება. გამოიყენეთ დეტალების გასაერთიანებლად, ერთი ფორმის მეორით ამოსაჭრელად ან ორი სხეულის გადაფარვის ადგილის მოსაძებნად.", + "help.solid.cone": "ქმნის კონუსს ფუძის წრითა და სიმაღლით, ან წაკვეთილ კონუსს, როცა ზედა ნაწილსაც აქვს რადიუსი. გამოიყენეთ კონუსური ფორმების, ძაბრების, კონუსური ჩაღრმავებებისა და წვეტიანი ბოლოებისთვის.", + "help.solid.cylinder": "ქმნის ცილინდრს რადიუსით ან დიამეტრით და სიმაღლით, წერტილზე ღერძის გასწვრივ მდგომს. გამოიყენეთ ლილვებისთვის, შტიფტებისთვის, დგარებისა და მრგვალი ნამზადებისთვის.", + "help.solid.draft": "არჩეულ წახნაგებს მოცემული კუთხით ხრის, ნეიტრალური სიბრტყიდან გაზომილით. გამოიყენეთ ჩამოსხმულ დეტალებზე, რომ ისინი ყალიბიდან ამოსრიალდეს.", + "help.solid.emboss": "ესკიზის პროფილებს, მაგალითად, ტექსტს ან ლოგოს, წახნაგიდან ამოწევს ან მასში ჩაღრმავებს. გამოიყენეთ წარწერებისთვის, ეტიკეტებისა და მარკირებისთვის ბრტყელ ან მრგვალ წახნაგებზე.", + "help.solid.extrude": "ესკიზის პროფილს 3D-ში ამოწევს მოცემულ მანძილზე, მასალის დამატებით ან მოცილებით. გამოიყენეთ ბრტყელი კონტურის ბლოკად, დგარად ან ჩაღრმავებად საქცევად.", + "help.solid.fillet": "არჩეულ წიბოებს ამრგვალებს მოცემული რადიუსის გლუვი წრიული გადასვლით. გამოიყენეთ ბასრი წიბოების დასარბილებლად სიმტკიცის, მოხერხებულობის ან იერის გამო.", + "help.solid.hole": "ბურღავს მოცემული დიამეტრის მრგვალ ხვრელს წახნაგის არჩეულ წერტილში. გამოიყენეთ ხრახნის გამავალი ხვრელებისთვის, შტიფტებისა და სხვა მარტივი მრგვალი ხვრელებისთვის.", + "help.solid.loft": "ქმნის გლუვ მყარ სხეულს ორ ან მეტ ესკიზის პროფილს შორის, ან პროფილიდან წერტილამდე. გამოიყენეთ გადასვლებისთვის, ძაბრებისთვის, სახელურებისა და ნებისმიერი ფორმისთვის, რომლის კვეთაც სიგრძის გასწვრივ იცვლება.", + "help.solid.mirror": "ქმნის არჩეული სხეულების ან ოპერაციების სარკისებრ ასლს სიბრტყის მიმართ და შეუძლია მისი ორიგინალთან გაერთიანება. გამოიყენეთ სიმეტრიული დეტალებისთვის, რომ ერთი ნახევრის მოდელირებით ორივე მიიღოთ.", + "help.solid.move": "გადააადგილებს ან აბრუნებს არჩეულ სხეულებს, ან მათ ასლს, მოცემული მანძილითა და კუთხით. გამოიყენეთ სხეულის ახალ ადგილას გადასატანად ან მეორის სხვა ადგილას შესაქმნელად.", + "help.solid.offset_face": "არჩეულ წახნაგებს შიგნით ან გარეთ წევს მოცემული მანძილით, მათ გარშემო არსებული წახნაგები კი მიჰყვება. გამოიყენეთ კედლის გასასქელებლად, ჩაღრმავების გასაღრმავებლად ან დგარის ასამაღლებლად ესკიზის რედაქტირების გარეშე.", + "help.solid.pattern.circular": "არჩეულ ობიექტებს ღერძის გარშემო იმეორებს, მოცემული რაოდენობითა და სრული კუთხით. გამოიყენეთ ჭანჭიკების წრიული განლაგებისთვის, სხივებისთვის, ფრთებისა და კბილებისთვის.", + "help.solid.pattern.path": "აკოპირებს ოპერაციებს ან სხეულებს ესკიზის ტრაექტორიის გასწვრივ, რაოდენობითა და ბიჯით. გამოიყენეთ ხვრელებისთვის მრუდე წიბოს გასწვრივ ან დეტალებისთვის რელსის გასწვრივ.", + "help.solid.pattern.rectangular": "არჩეულ ობიექტებს ერთი ან ორი მიმართულებით იმეორებს მოცემული რაოდენობითა და ბიჯით. გამოიყენეთ ხვრელების, სიხისტის წიბოების, შტიფტების ან საყრდენი ფეხების მწკრივებისა და ბადეებისთვის.", + "help.solid.pipe": "ქმნის მრგვალ მილს ესკიზის მრუდების ტრაექტორიის გასწვრივ, მასიურს ან ღრუს მოცემული კედლის სისქით. გამოიყენეთ მილებისთვის, მავთულებისთვის, კაბელებისა და რელსებისთვის.", + "help.solid.press_pull": "ამატებს ან აშორებს მასალას წახნაგის გადათრევისას, ან ამრგვალებს წიბოებს მათი გადათრევისას. გამოიყენეთ სწრაფი ცვლილებებისთვის პირდაპირ მოდელზე.", + "help.solid.remove": "არჩეულ სხეულებს პროექტიდან იღებს ქრონოლოგიის ამ წერტილიდან მოყოლებული; ადრინდელ ნაბიჯებში ისინი რჩება. გამოიყენეთ დამხმარე სხეულის მოსაშორებლად, მაგალითად, საჭრელი ხელსაწყოსი, რომელიც აღარ გჭირდებათ.", + "help.solid.replace_face": "არჩეულ ბრტყელ წახნაგებს გადააადგილებს სიბრტყეზე ან პარალელურ წახნაგზე, სხეული კი მის მისაღწევად იზრდება ან მცირდება. გამოიყენეთ წახნაგის სხვა დეტალთან ან დამხმარე სიბრტყესთან ერთ დონეზე მოსაყვანად.", + "help.solid.revolve": "ესკიზის პროფილს ღერძის გარშემო აბრუნებს მრგვალი მყარი სხეულის მისაღებად. გამოიყენეთ ლილვებისთვის, სახელურებისთვის, თასებისა და ნებისმიერი დეტალისთვის, რომელიც ღერძული ხაზის მიმართ მრგვალია.", + "help.solid.rib": "ამატებს თხელ კედელს ესკიზის ღია მრუდის გასწვრივ, სხეულის უახლოეს წახნაგებამდე შევსებულს. გამოიყენეთ კედლებისა და კუთხეების გასამაგრებლად, მაგალითად, ჩამოსხმულ ან დაბეჭდილ დეტალებში.", + "help.solid.scale": "არჩეულ სხეულებს ადიდებს ან ამცირებს კოეფიციენტით, ყველა მიმართულებით ერთნაირად ან თითო ღერძზე ცალკე. გამოიყენეთ იმპორტირებული ფორმის ზომის შესაცვლელად ან ჯდენის გასათვალისწინებლად.", + "help.solid.shell": "მყარ სხეულს შიგნიდან ამოღრუებს და მოცემული სისქის კედლებს ტოვებს, ასევე შეუძლია თქვენ მიერ არჩეული წახნაგების გახსნა. გამოიყენეთ ყუთებისთვის, სახურავებისა და სხვა თხელკედლიანი დეტალებისთვის.", + "help.solid.sphere": "ქმნის სფეროს რადიუსით ან დიამეტრით ცენტრალური წერტილის გარშემო. გამოიყენეთ ბურთულებისთვის, სახელურებისა და მომრგვალებული ბოლოებისთვის.", + "help.solid.split_body": "ჭრის სხეულს ცალკეულ სხეულებად სიბრტყით, სხვა სხეულის წახნაგით ან ესკიზის ხაზით. გამოიყენეთ დეტალების შესაქმნელად, რომლებიც ცალ-ცალკე იბეჭდება, მუშავდება ან იღებება.", + "help.solid.split_face": "ყოფს არჩეულ წახნაგებს სიბრტყის, სხვა სხეულის წახნაგის ან ესკიზის მრუდების გასწვრივ, სხეულის გაჭრის გარეშე. გამოიყენეთ წახნაგის ნაწილისთვის საკუთარი დახრის, ფერის ან წანაცვლების მისაცემად.", + "help.solid.sweep": "ესკიზის პროფილს ტრაექტორიის გასწვრივ მიათრევს მყარი სხეულის შესაქმნელად. გამოიყენეთ მილებისთვის, რელსებისთვის, სახელურებისა და მუდმივი კვეთის ნებისმიერი დეტალისთვის, რომელიც მრუდს მიჰყვება.", + "help.solid.thread": "ცილინდრულ წახნაგს ამატებს ISO მეტრულ კუთხვილს, პირობით კუთხვილად ან სხეულში ამოჭრილად. გამოიყენეთ ჭანჭიკებისთვის, კუთხვილიანი ხვრელებისა და დაბეჭდილი ხრახნიანი დეტალებისთვის.", + "help.solid.torus": "ქმნის რგოლს ღერძის გარშემო დიდი რადიუსით და მისი მრგვალი კვეთის მცირე რადიუსით. გამოიყენეთ O-რგოლებისთვის, სახელურებისა და მრგვალი ქიმებისთვის.", + "help.solid.web": "ამატებს თხელ კედელს ესკიზის თითოეული ღია მრუდის გასწვრივ, თითოეულს სხეულის უახლოეს წახნაგებამდე შევსებულს. გამოიყენეთ კორპუსებსა და ლანგრებში საყრდენი კედლების ბადისთვის.", + "help.surface.blend": "ქმნის ზედაპირს, რომელიც ორი სხეულის წიბოებს აერთებს, ორივესთან მხები ან სიმრუდით უწყვეტი. გამოიყენეთ ორი ზედაპირის ღრეჩოს გავლით გლუვად შესაერთებლად.", + "help.surface.boundary": "ქმნის ზედაპირს, რომელიც ავსებს ორიდან ოთხამდე ესკიზის მრუდის შეკრულ კონტურს ან მრუდების ქსელს. გამოიყენეთ თავისუფალი ფორმის პანელებისთვის, რომლებიც თავიანთი წიბოებით არის განსაზღვრული.", + "help.surface.extend": "აგრძელებს ზედაპირს მისი წიბოების მიღმა, მოცემული მანძილით ან სიბრტყემდე ან წახნაგამდე. გამოიყენეთ, რათა ზედაპირებმა ერთმანეთი გადაფარონ, სანამ მათ მოკვეთთ ან შეკერავთ.", + "help.surface.extrude": "ესკიზის მრუდებს ან პროფილებს მოცემულ მანძილზე აწევს და ზედაპირად აქცევს, მხოლოდ კედლებით, ხუფების გარეშე. გამოიყენეთ თხელი კედლებისთვის და საჭრელი ან გამყოფი ინსტრუმენტებისთვის.", + "help.surface.fair": "აგლუვებს თავისუფალი ფორმის წახნაგების შიდა ნაწილს, ხოლო მათი წიბოები ადგილზე რჩება. გამოიყენეთ ზედაპირზე ბორცვებისა და ტალღოვანი ანარეკლების მოსასწორებლად.", + "help.surface.loft": "ქმნის ზედაპირს, რომელიც თანმიმდევრობით გადის ორ ან მეტ კვეთაზე, ხუფების გარეშე. გამოიყენეთ გარსებისა და სხვადასხვა ფორმებს შორის გადასვლებისთვის.", + "help.surface.match": "გადააგებს ზედაპირის წიბოს ისე, რომ ის სხვა სხეულის წიბოს დაემთხვეს, შესაბამისი მხებით ან სიმრუდით. გამოიყენეთ ორ ზედაპირს შორის ნაკერის გლუვად დასახურად.", + "help.surface.offset": "ქმნის წახნაგების ასლს მოცემულ მანძილზე მათი ნორმალების გასწვრივ, ახალ ზედაპირულ სხეულად. გამოიყენეთ საფარისთვის, ღრეჩოებისთვის ან კედლის მეორე მხარისთვის.", + "help.surface.patch": "ავსებს ესკიზის რეგიონს ან წიბოების შეკრულ კონტურს წახნაგით, ბრტყლით ან გლუვად მოხრილით. გამოიყენეთ ზედაპირულ სხეულში ხვრელების დასახურად.", + "help.surface.reverse_normal": "აბრუნებს ზედაპირული სხეულის წახნაგებს, რათა მათი გარე მხარე საპირისპიროდ იყოს მიმართული. გამოიყენეთ გასქელებამდე ან შეკერვამდე, როცა წახნაგები შიგნითაა მიმართული.", + "help.surface.revolve": "ესკიზის მრუდებს ან პროფილებს ღერძის გარშემო აბრუნებს და ზედაპირად აქცევს, ხუფების გარეშე. გამოიყენეთ მრგვალი გარსებისთვის, როგორიცაა აბაჟურები, თასები და საქშენები.", + "help.surface.ruled": "ქმნის სწორი ხაზების ზოლს წიბოების ჯაჭვიდან, წახნაგის ნორმალის ან მხების გასწვრივ ან კუთხით. გამოიყენეთ დახრილი კედლების, გაგრძელების ზედაპირებისა და ყალიბის გამყოფი ზედაპირებისთვის.", + "help.surface.stitch": "კერავს ზედაპირულ სხეულებს მათი საერთო წიბოების გასწვრივ, ხოლო თუ ისინი შეიკვრება, მყარ სხეულად. გამოიყენეთ ზედაპირების ნაკრების ერთ სხეულად საქცევად.", + "help.surface.sweep": "ესკიზის მრუდებს ან პროფილებს ტრაექტორიის გასწვრივ ამოძრავებს და ზედაპირად აქცევს, ხუფების გარეშე. გამოიყენეთ ღარებისთვის, მორთულობისთვის და სხვა თხელი ფორმებისთვის, რომლებიც ტრაექტორიას მიჰყვება.", + "help.surface.thicken": "ზედაპირულ სხეულს სისქეს აძლევს, რითაც მას მყარ სხეულად აქცევს. გამოიყენეთ ზედაპირებიდან დასაბეჭდი ან მექანიკურად დასამუშავებელი დეტალების შესაქმნელად.", + "help.surface.trim": "ჭრის ზედაპირს სიბრტყით, სხვა ზედაპირით ან ესკიზის მრუდებით და ტოვებს თქვენ მიერ არჩეულ მხარეს. გამოიყენეთ შეკერვამდე ზედაპირების ფორმაზე მოსაჭრელად.", + "help.surface.unstitch": "ყოფს სხეულის წახნაგებს ცალკეულ ზედაპირულ სხეულებად; მყარი სხეული ზედაპირებად იშლება. გამოიყენეთ სხეულის ცალკეული წახნაგების გადასაკეთებლად.", + "help.surface.untrim": "შლის წახნაგიდან ხვრელებს ან აღადგენს მის გარე საზღვარს ზედაპირის ბუნებრივ საზღვრებამდე. გამოიყენეთ მოკვეთის შემდეგ სრული ზედაპირის დასაბრუნებლად.", + "help.third_party": "მესამე მხარის ლიცენზიები", + "help.timeline.compute_all": "თავიდან აგებს ქრონოლოგიის ყველა ოპერაციას დასაწყისიდან. გამოიყენეთ მოდელის გასაახლებლად და იმის სანახავად, რომელი ოპერაციები ვერ სრულდება.", + "help.timeline.delete": "შლის არჩეულ ოპერაციებს ქრონოლოგიიდან; ესკიზის წაშლა მისგან აგებულ ოპერაციებსაც შლის. გამოიყენეთ აღარასაჭირო ნაბიჯის მოსაშორებლად.", + "help.timeline.dependents": "ჩამოთვლის ოპერაციებს, რომლებიც ოპერაციასთან ერთად წაიშლება, და იმათ, რომლებიც მის გარეშე ვერ აიგება. გამოიყენეთ ოპერაციის წაშლამდე ან შეცვლამდე.", + "help.timeline.play": "დარჩენილ ოპერაციებს სათითაოდ ხელახლა უკრავს, ყოველი აგების შემდეგ ნახევარწამიანი პაუზით. შესაჩერებლად ისევ გაუშვით ეს ბრძანება ან დააჭირეთ Escape-ს; „ბოლოში გადასვლა“ მაშინვე ბოლოში გადადის.", + "help.version": "ვერსია {version}", + "help.view.apply": "ხედს აყენებს სტანდარტულ მიმართულებაზე, როგორიცაა წინა, ზედა ან იზომეტრიული, ან შენახულ დასახელებულ ხედზე. გამოიყენეთ მოდელის ფიქსირებული კუთხიდან სანახავად.", + "help.view.delete": "შლის შენახულ დასახელებულ ხედს. მოდელი არ იცვლება.", + "help.view.fit": "ცვლის მასშტაბს და გადაადგილებს ხედს ისე, რომ მთელი მოდელი ან მონიშნული ობიექტები ხედს შეავსოს. გამოიყენეთ, როცა მოდელი ხედიდან გაქრა.", + "help.view.grid": "აჩვენებს ან მალავს ბადეს ხედვის არეში. გამოიყენეთ როგორც ზომისა და ორიენტაციის ორიენტირი მოდელირებისას.", + "help.view.ground_shadow": "აჩვენებს ან მალავს მოდელის ჩრდილს მიწაზე. გამოიყენეთ სიმაღლისა და პოზიციის უფრო მარტივად შესაფასებლად.", + "help.view.home": "ხედს საწყის მიმართულებაზე აბრუნებს და მოდელს ხედში ჩაატევს. გამოიყენეთ ცნობილ ხედზე სწრაფად დასაბრუნებლად.", + "help.view.list": "ჩამოთვლის პროექტში შენახულ დასახელებულ ხედებს. გამოიყენეთ ადრე შენახული ხედის მოსაძებნად.", + "help.view.navigate": "აბრუნებს, გადაადგილებს ან ცვლის ხედის მასშტაბს ნაბიჯ-ნაბიჯ, მაგალითად, მეოთხედი ბრუნით მარცხნივ. გამოიყენეთ კამერის ზუსტად გადასაადგილებლად გადათრევის ნაცვლად.", + "help.view.navigation_bar": "აჩვენებს ან მალავს ნავიგაციის ზოლს ხედვის არის ქვედა ნაწილში. დამალეთ მეტი ადგილისთვის, გამოაჩინეთ ხედის ხელსაწყოებთან მაუსით წვდომისთვის.", + "help.view.rename": "შენახულ დასახელებულ ხედს ახალ სახელს აძლევს. თავად ხედი არ იცვლება.", + "help.view.save": "ინახავს კამერის მიმდინარე პოზიციას დასახელებულ ხედად პროექტში. გამოიყენეთ მოგვიანებით იმავე კუთხეზე დასაბრუნებლად, მაგალითად, ეკრანის ანაბეჭდებისთვის.", + "help.view.spin": "უწყვეტად აბრუნებს ხედს მოდელის გარშემო შემდეგ დაწკაპებამდე ან კლავიშის დაჭერამდე. გამოიყენეთ მოდელის ყველა მხრიდან საჩვენებლად.", + "help.view.tool": "აფიქსირებს კამერის ხელსაწყოს, ორბიტას, პანორამას ან მასშტაბს, ისე, რომ მაუსის მარცხენა ღილაკით გადათრევა ხედს ამოძრავებს, სანამ ხელსაწყოს არ გამორთავთ. გამოიყენეთ სენსორულ პანელზე ან მაუსის შუა ღილაკის გარეშე.", + "help.view.visual_style": "ცვლის მოდელის ჩვენების სახეს: დაჩრდილული წიბოებით ან მათ გარეშე, კარკასი ან დამალული წიბოებით. გამოიყენეთ კარკასი შიგნით დასანახად, დაჩრდილული კი სუფთა იერისთვის.", + "history.sketch_under_constrained": "არასრულად შეზღუდული (თავისუფლების ხარისხი: {count})", + "history.sketch_under_constrained_one": "არასრულად შეზღუდული (თავისუფლების ხარისხი: {count})", + "hole_presets.confirm_delete": "წაშლის დადასტურება", + "hole_presets.delete": "წაშლა", + "hole_presets.delete_prompt": "წავშალოთ ეს პირადი პრესეტი? არსებული ხვრელები არ შეიცვლება.", + "hole_presets.full": "პირად ბიბლიოთეკაში უკვე 64 პრესეტია.", + "hole_presets.invalid_name": "შეიყვანეთ მოკლე სახელი სტრიქონის წყვეტებისა და მმართველი სიმბოლოების გარეშე.", + "hole_presets.invalid_parameters": "შეავსეთ ხვრელის პარამეტრები სწორი და გონივრული სიგრძის გამოსახულებებით.", + "hole_presets.missing": "არჩეული პრესეტი აღარ არის ხელმისაწვდომი.", + "hole_presets.name": "პრესეტის სახელი", + "hole_presets.name_exists": "ამ სახელით პრესეტი უკვე არსებობს. გამოიყენეთ სხვა სახელი.", + "hole_presets.name_hint": "უნიკალური სახელი", + "hole_presets.overwrite": "ცვლილებების შენახვა არჩეულ პრესეტში", + "hole_presets.preset": "პრესეტი", + "hole_presets.recall": "ჩატვირთვა", + "hole_presets.rename": "სახელის შეცვლა", + "hole_presets.save": "ახლის შენახვა", + "hole_presets.scope": "ინახება თქვენს პროფილში ყველა პროექტისთვის.", + "hole_presets.select": "აირჩიეთ პრესეტი", + "hole_presets.title": "პირადი პრესეტები", + "hole_presets.unsupported_options": "ეს პრესეტი კუთხვილის ისეთ პარამეტრებს იყენებს, რომლებსაც ეს ვერსია ვერ ჩატვირთავს.", + "hole_presets.unsupported_overwrite": "ეს პრესეტი შეიცავს პარამეტრებს, რომელთა უსაფრთხოდ გადაწერა შეუძლებელია.", + "home.back": "{name}-ში დაბრუნება", + "home.crashes": "ავარიის ანგარიშები", + "home.design_workspace": "დიზაინი", + "home.documentation": "დოკუმენტაცია", + "home.export": "ექსპორტი", + "home.export_hint": "აირჩიეთ ფორმატი მიმდინარე პროექტისთვის.", + "home.export_json_hint": "რედაქტირებადი პროექტი და ბრძანებების ისტორია", + "home.export_mesh_hint": "პოლიგონური ბადე ბეჭდვისთვის ან გაზიარებისთვის", + "home.export_step_hint": "ზუსტი მყარი გეომეტრია", + "home.import": "იმპორტი…", + "home.import_hint": "STEP, IGES ან პოლიგონური ბადე ახალ პროექტში", + "home.in_this_browser": "ამ ბრაუზერში", + "home.missing": "ვერ მოიძებნა", + "home.month_01": "იან", + "home.month_02": "თებ", + "home.month_03": "მარ", + "home.month_04": "აპრ", + "home.month_05": "მაი", + "home.month_06": "ივნ", + "home.month_07": "ივლ", + "home.month_08": "აგვ", + "home.month_09": "სექ", + "home.month_10": "ოქტ", + "home.month_11": "ნოე", + "home.month_12": "დეკ", + "home.new_inches": "ახალი პროექტი, დუიმები", + "home.new_inches_hint": "დუიმები · იხსნება დიზაინში", + "home.new_mm": "ახალი პროექტი", + "home.new_mm_hint": "მილიმეტრები · იხსნება დიზაინში", + "home.open": "გახსნა…", + "home.open_hint": ".sc პროექტი ({shortcut})", + "home.open_now": "ახლავე გახსნა", + "home.opened_days_ago": "{count} დღის წინ", + "home.opened_hours_ago": "{count} სთ-ის წინ", + "home.opened_just_now": "ახლახან", + "home.opened_minutes_ago": "{count} წთ-ის წინ", + "home.opening": "იხსნება…", + "home.properties": "პროექტის თვისებები", + "home.recent": "ბოლოდროინდელი", + "home.recent_empty": "აქ გამოჩნდება პროექტები, რომლებსაც გახსნით ან შეინახავთ.", + "home.recovery_count": "აღსადგენი პროექტები: {count}", + "home.recovery_empty": "აღსადგენი პროექტები არ არის.", + "home.recovery_hint": "SolidCraft დაიხურა, სანამ ეს პროექტები შეინახებოდა.", + "home.report_issue": "პრობლემის შეტყობინება", + "home.samples": "ნიმუშები", + "home.settings": "პარამეტრები", + "home.short_date": "{day} {month}", + "home.shortcuts": "კლავიატურის მალსახმობები", + "home.start_hint": "შექმენით პროექტი, გახსენით ბოლოდროინდელი ფაილი ან დაათვალიერეთ ნიმუში.", + "home.whats_new": "რა არის ახალი", + "home.yesterday": "გუშინ", + "import_report.details": "დეტალები:", + "import_report.file_one": "ფაილს კიდევ 1 პრობლემა ჰქონდა.", + "import_report.file_other": "ფაილს კიდევ {count} პრობლემა ჰქონდა.", + "import_report.hint": "ამ დეტალების ხელახალი ექსპორტი იმ პროგრამიდან, რომელმაც ისინი შექმნა, შესაძლოა პრობლემას გადაჭრის. დეტალები აქვს ბრძანებას „გაფრთხილების შეტყობინების კოპირება“.", + "import_report.left_out_one": "1 წახნაგის შეკეთება ვერ მოხერხდა და ის აკლია.", + "import_report.left_out_other": "{count} წახნაგის შეკეთება ვერ მოხერხდა და ისინი აკლია.", + "import_report.needs_repair_one": "1 დეტალს მასზე მოდელირებამდე შეკეთება სჭირდება.", + "import_report.needs_repair_other": "{count} დეტალს მათზე მოდელირებამდე შეკეთება სჭირდება.", + "import_report.not_imported_one": "1 დეტალის იმპორტი ვერ მოხერხდა.", + "import_report.not_imported_other": "{count} დეტალის იმპორტი ვერ მოხერხდა.", + "import_report.not_shown_one": "1 წახნაგის დახატვა ვერ მოხერხდა და ის დამალულია.", + "import_report.not_shown_other": "{count} წახნაგის დახატვა ვერ მოხერხდა და ისინი დამალულია.", + "import_report.open_one": "1 დეტალს წახნაგებს შორის ღრეჩოები აქვს და ღია სხეულად შემოვიდა.", + "import_report.open_other": "{count} დეტალს წახნაგებს შორის ღრეჩოები აქვს და ღია სხეულებად შემოვიდა.", + "import_report.refused_one": "1 დეტალის მყარ სხეულად გარდაქმნა ვერ მოხერხდა და მისი იმპორტი არ მომხდარა.", + "import_report.refused_other": "{count} დეტალის მყარ სხეულებად გარდაქმნა ვერ მოხერხდა და მათი იმპორტი არ მომხდარა.", + "import_report.repaired_one": "1 დეტალში მცირე დეფექტები შეკეთდა.", + "import_report.repaired_other": "{count} დეტალში მცირე დეფექტები შეკეთდა.", + "import_report.solids": "მყარ სხეულებად იმპორტირებულია {solids} დეტალი {parts}-დან.", + "import_report.surfaces_one": "1 დეტალის მყარ სხეულად გარდაქმნა ვერ მოხერხდა და ის ზედაპირებად შემოვიდა.", + "import_report.surfaces_other": "{count} დეტალის მყარ სხეულებად გარდაქმნა ვერ მოხერხდა და ისინი ზედაპირებად შემოვიდა.", + "install.button_tip": "დააინსტალირეთ SolidCraft აპად: ის საკუთარ ფანჯარაში იხსნება და ოფლაინ მუშაობს", + "install.dock_1": "აირჩიეთ File › Add to Dock.", + "install.dock_2": "დაწკაპეთ Add.", + "install.dock_after": "ამის შემდეგ SolidCraft Dock-იდან საკუთარ ფანჯარაში გაიხსნება და ოფლაინ იმუშავებს.", + "install.done": "მზადაა", + "install.home_screen_1": "შეეხეთ Share-ს (… მენიუში, თუ ის ხელსაწყოთა ზოლზე არ არის).", + "install.home_screen_2": "აირჩიეთ Add to Home Screen.", + "install.home_screen_3": "შეეხეთ Add-ს.", + "install.home_screen_after": "ამის შემდეგ SolidCraft საწყის ეკრანზე მისი ხატულიდან გაიხსნება, Safari-ის ზოლების გარეშე, და ოფლაინ იმუშავებს.", + "install.menu": "აპის ინსტალაცია…", + "install.steps_intro": "Safari ვებაპებს საკუთარი მენიუებიდან აინსტალირებს:", + "install.title": "SolidCraft-ის ინსტალაცია", + "issue.body_label": "ანგარიშის ტექსტი", + "issue.note_changed_while_waiting": "გადახედვის მოლოდინისას პარამეტრები ან მოდელი შეიცვალა. მიმდინარე ხედის ტექნიკური დეტალების განსაახლებლად ხელახლა გადაიღეთ ეკრანის ანაბეჭდი.", + "issue.note_details_kept": "ეკრანის ანაბეჭდი ლოკალურად გადაღებულია. თქვენ მიერ შესწორებული ტექნიკური დეტალები შენარჩუნდა: შეამოწმეთ, ისევ შეესაბამება თუ არა ისინი მიმდინარე ხედს.", + "issue.note_details_updated": "ტექნიკური დეტალები განახლდა მიმდინარე ხედის შესაბამისად. ეკრანის ანაბეჭდი ლოკალურად გადაღებულია. გადახედეთ მას GitHub-ზე დართვამდე.", + "issue.note_image_copied": "ჩასვით გამოსახულება GitHub-ის მონახაზში, ან შეინახეთ PNG, თუ გამოსახულების კოპირება მიუწვდომელია.", + "issue.note_opened": "გადახედეთ GitHub-ის მონახაზს და დაურთეთ ეკრანის ანაბეჭდი. მას GitHub-ის ღილაკი Submit new issue გამოაქვეყნებს.", + "issue.note_opened_copied": "ანგარიში დაკოპირდა. ჩასვით ის GitHub-ის მონახაზში, დაურთეთ ეკრანის ანაბეჭდი, შემდეგ GitHub-ზე დაწკაპეთ Submit new issue.", + "issue.note_removed": "ეკრანის ანაბეჭდი ამ მონახაზიდან წაიშალა.", + "issue.note_report_copied": "ანგარიში დაკოპირდა. საჭიროების შემთხვევაში ჩასვით ის GitHub-ის მონახაზში.", + "issue.note_save_failed": "ეკრანის ანაბეჭდის შენახვა ვერ მოხერხდა: {error}", + "issue.note_saved": "ეკრანის ანაბეჭდი შენახულია. დაურთეთ PNG ფაილი GitHub-ის მონახაზს.", + "issue.save_screenshot": "ეკრანის ანაბეჭდის შენახვა…", + "joint.find_limits": "ზღვრების პოვნა", + "joint.find_limits_failed": "ზღვრების ძებნა შეცდომით შეწყდა", + "joint.find_limits_hint": "ზღვრების შევსება იქიდან, სადაც ამ შეერთებით მოძრავი დეტალები პირველად ეხება სხვა დეტალს, როცა მიმდინარე მდებარეობიდან თითოეული მიმართულებით ბრუნავს ან სრიალებს. ძებნა ასლზე სრულდება: OK-მდე არაფერი იცვლება.", + "joint.find_limits_stale": "ამ ზღვრების პოვნის შემდეგ შეერთება ან პროექტი შეიცვალა: იპოვეთ ისინი ხელახლა", + "joint.finding_limits": "ზღვრების ძებნა…", + "joint.from_bodies_hint": "თითოეული არჩეული სხეული გადადის საკუთარ ახალ კომპონენტში და ადგილზე რჩება.", + "joint.limit_contact": "{side} {value}: {a} ეხება {b}-ს", + "joint.limit_limit": "{side} {value}: სხვა მნიშვნელობის ან შეერთების ზღვარი", + "joint.limit_loop": "{side} {value}: შეკრული კონტური მის მიღმა ვერ შეიკვრება", + "joint.limit_range": "{side}: {range}-ის ფარგლებში შეხება არ არის, დარჩა როგორც იყო", + "joint.limit_turn": "{side} {value}: ერთი სრული ბრუნის ფარგლებში შეხება არ არის", + "joint.limits_overlapping": "აქ უკვე ერთმანეთში შედის: {pairs}. ძებნას მხოლოდ მაშინ აჩერებს, თუ უფრო ღრმად შევა.", + "joint.one_body": "ორივე არჩეული ელემენტი {body}-ზეა. მეორე აირჩიეთ სხვა დეტალზე.", + "joint.one_component": "ეს დეტალები ერთი კომპონენტის სხეულებია: {bodies}. შეერთება ერთ კომპონენტს მეორის მიმართ ამოძრავებს, ამიტომ თითოეულ დეტალს საკუთარი კომპონენტი სჭირდება.", + "joint.rigid_group_one_component": "ყველა ეს სხეული ({count}) ერთ კომპონენტშია (ან თავად პროექტში): ჯერ გამოიყენეთ {command}.", + "joint.rigid_group_select_components": "მონიშნეთ ორი ან მეტი კომპონენტი.", + "joint_move.blocked_hint": "შეამოწმეთ შეერთების ტიპი (მაგალითად, ხისტი), ფიქსაცია, შეერთების ზღვრები და პარამეტრებით განსაზღვრული მნიშვნელობები.", + "joint_move.blocked_title": "ამ დეტალის გადაადგილება შეუძლებელია", + "joint_move.coarse": "ბრუნვის ბიჯი ღერძთან ახლოს (°)", + "joint_move.conflict": "ამ დეტალის ერთი შეერთება დანარჩენებს ეწინააღმდეგება: {joint}.", + "joint_move.conflict_hint": "შეცვალეთ, ჩაახშეთ ან წაშალეთ კონფლიქტური შეერთება, რომ დანარჩენმა შეერთებებმა დეტალი განათავსოს.", + "joint_move.distance": "მანძილი საწყისიდან", + "joint_move.done": "მზადაა", + "joint_move.fine": "ბრუნვის ბიჯი ღერძიდან მოშორებით (°)", + "joint_move.fixed": "ამ დეტალს შეერთების მოძრავი ღერძი არ აქვს.", + "joint_move.help": "გადაადგილება — გადაათრიეთ ისარი ან რგოლი. Esc მიმდინარე გადათრევას აუქმებს.", + "joint_move.legacy_hint": "გამორთეთ, რომ გამოიყენოთ გადაადგილების წინა პანელი.", + "joint_move.precision": "ზუსტი ბრუნვისთვის გაიტანეთ წყვეტილი დამხმარე ხაზის გარეთ.", + "joint_move.rotation": "ბრუნვა საწყისიდან", + "joint_move.select": "მონიშნეთ წახნაგი ან აწყობის ერთი დეტალი, შემდეგ აირჩიეთ „გადაადგილება“.", + "joint_move.settings": "აწყობის გადაადგილება", + "joint_move.step": "ბიჯი", + "joint_move.use_handles": "შეერთების მოძრაობის სახელურების გამოყენება აწყობის გადაადგილებისას", + "keymap.command_id": "ბრძანების ID", + "keymap.empty": "შესაბამისი ბრძანება ვერ მოიძებნა", + "keymap.use_anyway": "{key}-ის აქ მაინც გამოყენება", + "label.move_to_left_side": "მარცხენა მხარეს გადატანა", + "label.move_to_right_side": "მარჯვენა მხარეს გადატანა", + "manage.appearance_hint": "აირჩიეთ იერსახე მონიშნულისთვის, ან გადაათრიეთ ნიმუში სხეულზე ან წახნაგზე.", + "manage.assign_hint": "მონიშნეთ სხეულები და აირჩიეთ მათი პლასტმასის დიზაინის წესი.", + "manage.config_hint": "შეცვალეთ კონფიგურაციის სტრიქონები, სვეტები და წესები, შემდეგ გაააქტიურეთ ან წინასწარ ნახეთ სტრიქონი.", + "manage.empty": "შესაბამისი სტრიქონი ვერ მოიძებნა.", + "manage.material_hint": "მონიშნეთ სხეულები და აირჩიეთ მათი ფიზიკური მასალა.", + "manage.parameters_hint": "შეცვალეთ გამოსახულებები და ერთეულები. ცვლილებები გამოიყენება Enter-ზე ან ველიდან გასვლისას.", + "manage.rules_hint": "აირჩიეთ შესაცვლელი წესი ან შექმენით ახალი. შესანახად დაადასტურეთ.", + "material.editor.add_property": "თვისების დამატება", + "material.editor.add_source": "წყაროს დამატება", + "material.editor.assigned_density": "მინიჭებული სიმკვრივე", + "material.editor.axes": "მასალის ღერძები", + "material.editor.axes_numeric": "1 / 2 / 3", + "material.editor.axes_wood": "L / R / T", + "material.editor.copy_name": "{name}-ის ასლი", + "material.editor.density_range": "მინიჭებული სიმკვრივე უნდა იყოს 0-ზე მეტი და არაუმეტეს 1000 g/cm³.", + "material.editor.designation": "აღნიშვნა", + "material.editor.duplicate": "დუბლირება", + "material.editor.engineering_card": "საინჟინრო თვისებების ბარათი", + "material.editor.family": "მასალის ოჯახი", + "material.editor.glass": "მინა", + "material.editor.illustrative": "საილუსტრაციო", + "material.editor.invalid_property": "თვისების ტიპი მხარდაუჭერელია.", + "material.editor.isotropic": "იზოტროპული", + "material.editor.measurement": "გაზომვა", + "material.editor.metal": "ლითონი", + "material.editor.moisture": "ტენიანობა, მშრალ მასაზე", + "material.editor.name_required": "შეიყვანეთ სახელი 1–128 სიმბოლოთი.", + "material.editor.no_draft": "მასალის მონახაზი გახსნილი არ არის.", + "material.editor.number_required": "შეიყვანეთ სასრული რიცხვითი მნიშვნელობა.", + "material.editor.orthotropic": "ორთოტროპული", + "material.editor.other": "სხვა", + "material.editor.polymer": "პოლიმერი", + "material.editor.preserved_appearance": "შენარჩუნებული იერსახე", + "material.editor.public_reference": "საჯარო წყარო", + "material.editor.reference": "საცნობარო", + "material.editor.save_or_discard": "მასალის მინიჭებამდე შეინახეთ ან გააუქმეთ მასალის მონახაზი.", + "material.editor.saved": "მასალა შენახულია. სხეულებზე მინიჭებები არ შეცვლილა.", + "material.editor.scope": "შენახვა ამ მასალას ინახავს სხეულებზე მინიჭების გარეშე. ცარიელი თვისებები და პირობები უცნობად რჩება. ბარათის სიმკვრივე არ ცვლის მინიჭებულ სიმკვრივეს ან მასას.", + "material.editor.source_id": "წყაროს ID", + "material.editor.source_kind": "წყაროს ტიპი", + "material.editor.source_title": "წყაროს სათაური", + "material.editor.sources": "წყაროები", + "material.editor.stale": "მონახაზის გახსნის დროს ეს მასალა შეიცვალა. შენახვამდე გააუქმეთ და ხელახლა გახსენით.", + "material.editor.state": "მასალის მდგომარეობა", + "material.editor.strain_rate": "დეფორმაციის სიჩქარე", + "material.editor.symmetry": "დრეკადი სიმეტრია", + "material.editor.temperature": "ტემპერატურა", + "material.editor.unknown_card": "საინჟინრო თვისებები უცნობია. შენახვამ შეიძლება მხოლოდ მინიჭებული სიმკვრივე და არსებული იერსახე შეინარჩუნოს.", + "material.editor.user_supplied": "მომხმარებლის მიერ მოწოდებული", + "material.editor.wood": "ხე-ტყე", + "material.selection.choose": "აირჩიეთ მასალა", + "material.selection.mixed": "სხვადასხვა მასალა", + "measure.at": "მდებარეობა", + "measure.item": "ელემენტი {number}", + "measure.quick_copied": "გაზომვა დაკოპირდა", + "measure.quick_copy": "დაწკაპეთ გაზომვის დასაკოპირებლად", + "measure.quick_edges": "წიბო: {count}", + "measure.quick_faces": "წახნაგი: {count}", + "messages.ago_h": "{n} სთ-ის წინ", + "messages.ago_min": "{n} წთ-ის წინ", + "messages.ago_s": "{n} წმ-ის წინ", + "messages.chip_hint": "დაწკაპეთ ამ სესიის ყველა შეტყობინების სანახავად", + "messages.clear": "გასუფთავება", + "messages.copy_all": "ყველას კოპირება", + "messages.menu": "შეტყობინებები…", + "messages.none": "შეტყობინებები ჯერ არ არის.", + "messages.title": "შეტყობინებები", + "motion.checked_to": "შემოწმდა მხოლოდ {step}-ე ნაბიჯამდე: შემოწმებას სამუშაო ლიმიტი ამოეწურა", + "motion.collision": "{a} · {b}: ნაბიჯები {steps}", + "motion.delete_key": "საკვანძო კადრის წაშლა", + "motion.duration_hint": "წამი (ცარიელი: თითო ნაბიჯზე)", + "motion.key_here": "საკვანძო კადრი აქ", + "motion.key_here_hint": "ამ ნაბიჯზე საკვანძო კადრის დამატება შეერთების ამჟამინდელი მნიშვნელობით", + "motion.no_collisions": "მთელ კვლევაში შეჯახება არ არის", + "motion.plot_quantity": "სიდიდე", + "motion.step_back": "ნაბიჯით უკან", + "motion.step_forward": "ნაბიჯით წინ", + "motion.to_end": "ბოლოში", + "motion.to_start": "დასაწყისში", + "motion.track_name": "ტრეკი {number}", + "nav.alias.help": "Shift+Alt+მარცხენა ღილაკით გადათრევა: ორბიტა, Shift+Alt+შუა: პანორამა, Shift+Alt+მარჯვენა: მასშტაბი; შუა ღილაკით გადათრევაც პანორამაა, მარჯვენათი კი ორბიტა", + "nav.blender.help": "შუა ღილაკით გადათრევა: ორბიტა, Shift+შუა: პანორამა, Ctrl+შუა: მასშტაბი; მარჯვენა ღილაკით გადათრევა კამერას არ ეხება", + "nav.creo.help": "შუა ღილაკით გადათრევა: ორბიტა, Shift+შუა: პანორამა, Ctrl+შუა ვერტიკალური გადათრევით: მასშტაბი (ქვემოთ — გადიდება); ბორბლის დატრიალება: მასშტაბი", + "nav.creo.label": "Creo", + "nav.free_orbit.help": "მაუსი და 3D მაუსი ხედს ორივე პოლუსზე გადაატარებს და გორებას ინარჩუნებს. Shift-ით ღერძზე მიბმა გამორთულია.", + "nav.free_orbit.label": "თავისუფალი ორბიტა", + "nav.free_orbit.snap_help": "მაუსი და 3D მაუსი ხედს ორივე პოლუსზე გადაატარებს და გორებას ინარჩუნებს. ხედის მიმართულებისა და გორების მისაბმელად ორბიტით გადათრევისას დააჭირეთ Shift-ს.", + "nav.free_orbit_upright.help": "მაუსის გვერდით გადათრევა მოდელს სამყაროს ვერტიკალური ღერძის გარშემო აბრუნებს; ზემოთ და ქვემოთ გადათრევა მას ზედა მხარეს გადაღმა უსაზღვროდ ხრის.", + "nav.free_orbit_upright.label": "ვერტიკალური ღერძის გარშემო ბრუნვა", + "nav.fusion.help": "შუა ღილაკით გადათრევა: პანორამა, Shift+შუა: ორბიტა, მარჯვენა ღილაკით გადათრევა: ორბიტა", + "nav.hfss.help": "Alt+მარცხენა ღილაკით გადათრევა: პანორამა, Shift+Alt+მარცხენა: მასშტაბი, Ctrl+მარცხენა ღილაკით გადათრევა ცარიელ ადგილზე: ორბიტა", + "nav.inventor.help": "შუა ღილაკით გადათრევა: პანორამა, Shift+შუა: ორბიტა, Ctrl+შუა: მასშტაბი, მარჯვენა ღილაკით გადათრევა: ორბიტა", + "nav.maya.help": "Alt+მარცხენა ღილაკით გადათრევა: ორბიტა, Alt+შუა: პანორამა, Alt+მარჯვენა: მასშტაბი; შუა ღილაკით გადათრევაც პანორამაა", + "nav.nx.help": "შუა ღილაკით გადათრევა: ორბიტა, Shift+შუა: პანორამა (NX-ში შუა + მარჯვენა), Ctrl+შუა: მასშტაბი (NX-ში შუა + მარცხენა); მარჯვენა ღილაკით გადათრევა კამერას არ ეხება", + "nav.openscad.help": "მარცხენა ღილაკით გადათრევა ცარიელ ადგილზე: ორბიტა, Shift+მარცხენა: ჩარჩოთი მონიშვნა, ესკიზის გეომეტრიის გადათრევა მას ცვლის; მარჯვენა ან შუა ღილაკით გადათრევა: პანორამა, Shift+მარჯვენა ან Shift+შუა: მასშტაბი", + "nav.perspective.sketch": "ესკიზის რედაქტირება ორთოგრაფიულ ხედს იყენებს. პერსპექტივის გადასართავად ესკიზი დაასრულეთ.", + "nav.right_drag_orbits.help": "გამორთული: მარჯვენა ღილაკით გადათრევა კამერას არ ეხება და მარჯვენა ღილაკი მხოლოდ კონტექსტურ მენიუს ხსნის. SolidWorks-ის მაუსის სქემის არჩევა ამას გამორთავს.", + "nav.right_drag_orbits.label": "მარჯვენა ღილაკით გადათრევა: ორბიტა", + "nav.solidworks.help": "შუა ღილაკით გადათრევა: ორბიტა, Ctrl+შუა: პანორამა, Shift+შუა: მასშტაბი, მარჯვენა ღილაკით გადათრევა: ორბიტა", + "nav.tinkercad.help": "მარჯვენა ღილაკით გადათრევა: ორბიტა, შუა ან Shift+მარჯვენა ღილაკით გადათრევა: პანორამა", + "nav.touchpad.help": "პანორამისთვის დააჭირეთ Shift-ს და გადაადგილეთ მაჩვენებელი; ორბიტისთვის დააჭირეთ Alt/Option-ს და გადაადგილეთ. მაუსის ღილაკი საჭირო არ არის. ვერტიკალური გადახვევა მასშტაბს ცვლის.", + "nav.touchpad.label": "სენსორული პანელი", + "nav.touchpad.orbit": "ორბიტა (დააჭირეთ Alt/Option-ს და გადაადგილეთ; მაუსის ღილაკის გარეშე)", + "nav.touchpad.pan": "პანორამა (დააჭირეთ Shift-ს და გადაადგილეთ; მაუსის ღილაკის გარეშე)", + "nav.touchpad.scroll": "სენსორული პანელი მასშტაბისთვის ვერტიკალურ გადახვევას იყენებს. ორი თითით პანორამის თქვენი პარამეტრი სხვა პრესეტებისთვის შენარჩუნებულია.", + "nav.touchpad.zoom": "მასშტაბი (ვერტიკალური გადახვევა ან თითების მოჭერა)", + "navbar.agent_chat": "ასისტენტის ჩატის პანელი", + "navbar.agent_cursor": "აგენტის კურსორის ჩვენება", + "navbar.ambient_occlusion": "გარემოს დაჩრდილვა", + "navbar.assistant": "ასისტენტი", + "navbar.custom.add_slot": "{slot}-ის დამატება", + "navbar.custom.always": "ყოველთვის ჩანს", + "navbar.custom.available": "{available} · გადაათრიეთ ზოლზე ან დააჭირეთ „დამატებას“", + "navbar.custom.buttons": "ღილაკები", + "navbar.custom.compact": "კომპაქტური", + "navbar.custom.count": "სლოტი: {count} / 16", + "navbar.custom.customise": "ნავიგაციის ზოლის მორგება…", + "navbar.custom.design": "დიზაინი", + "navbar.custom.duplicate": "ეს სლოტი ზოლზე უკვე არის.", + "navbar.custom.edge": "კიდე", + "navbar.custom.edge_bottom": "ქვემოთ", + "navbar.custom.edge_top": "ზემოთ", + "navbar.custom.fade": "მილევა", + "navbar.custom.full": "სხვის დასამატებლად ერთი სლოტი წაშალეთ.", + "navbar.custom.hidden_design": "დამალულია დიზაინში", + "navbar.custom.hidden_render": "დამალულია რენდერში", + "navbar.custom.hide": "ნავიგაციის ზოლის დამალვა", + "navbar.custom.hide_idle": "დამალვა მაჩვენებლის მიტანამდე", + "navbar.custom.icon_only": "მხოლოდ ხატულა", + "navbar.custom.icon_value": "ხატულა და მნიშვნელობა", + "navbar.custom.icons": "ხატულები", + "navbar.custom.idle": "უმოქმედობისას", + "navbar.custom.intro": "აირჩიეთ, რომელი მართვის ელემენტები იყოს 3D ხედის ქვედა ზოლზე და რა რიგით. სლოტის გადასაადგილებლად გადაათრიეთ, წასაშლელად კი ზოლიდან გაიტანეთ.", + "navbar.custom.labels": "ხატულები და წარწერები", + "navbar.custom.left": "მარცხნივ გადატანა", + "navbar.custom.position": "პოზიცია", + "navbar.custom.position_centre": "ცენტრში", + "navbar.custom.position_left": "მარცხნივ", + "navbar.custom.position_right": "მარჯვნივ", + "navbar.custom.preview_as": "წინასწარი ნახვა როგორც", + "navbar.custom.regular": "ჩვეულებრივი", + "navbar.custom.remove": "წაშლა", + "navbar.custom.remove_bar": "ზოლიდან წაშლა", + "navbar.custom.render": "რენდერი", + "navbar.custom.reset": "ნავიგაციის ზოლის ჩამოყრა", + "navbar.custom.reset_default": "ნაგულისხმევზე ჩამოყრა", + "navbar.custom.right": "მარჯვნივ გადატანა", + "navbar.custom.select": "სლოტი მონიშნული არ არის. მონიშნეთ სლოტი ზოლზე მის გადასაადგილებლად, წასაშლელად ან იერსახის შესაცვლელად.", + "navbar.custom.separators_full": "ზოლს უკვე ოთხი გამყოფი აქვს.", + "navbar.custom.show": "ნავიგაციის ზოლის ჩვენება", + "navbar.custom.shows": "აჩვენებს", + "navbar.custom.size": "ზომა", + "navbar.custom.stale": "ზოლი შეიცვალა. სლოტი ხელახლა მონიშნეთ.", + "navbar.custom.title": "ნავიგაციის ზოლი", + "navbar.custom.unknown": "ეს სლოტი მიუწვდომელია.", + "navbar.description.ambient_occlusion": "სიღრმისთვის ამუქებს ნაკეცებსა და კუთხეებს.", + "navbar.description.display": "ხედის პარამეტრებს შეიცავს: გრაფიკის პრესეტი, ბადე, ჩრდილი იატაკზე, გარემოს დაჩრდილვა და პროექცია.", + "navbar.description.fit": "ჩარჩოში აქცევს მონიშნულს, ან მთელ მოდელს, თუ არაფერია მონიშნული.", + "navbar.description.grid": "აჩვენებს ან მალავს იატაკის ბადეს.", + "navbar.description.ground_shadow": "აჩვენებს ან მალავს მოდელის ქვეშ ჩრდილს.", + "navbar.description.home": "მთელი მოდელის იზომეტრიულ ხედს უბრუნდება.", + "navbar.description.look_at": "ხედს მონიშნული წახნაგის, სიბრტყის ან ღია ესკიზის პირისპირ აბრუნებს.", + "navbar.description.orbit": "ხედს მოდელის გარშემო აბრუნებს.", + "navbar.description.pan": "ხედს გვერდზე, ზემოთ ან ქვემოთ წაანაცვლებს.", + "navbar.description.projection": "ორთოგრაფიულ და პერსპექტიულ ხედებს შორის გადართავს.", + "navbar.description.separator": "წვრილი ხაზი, რომელიც მეზობელ სლოტებს აჯგუფებს.", + "navbar.description.spin": "ხედი ბრუნავს, სანამ არ დაწკაპებთ ან კლავიშს არ დააჭერთ.", + "navbar.description.visual_style": "ცვლის მოდელის ხატვის წესს: დაჩრდილული, კარკასული ან უხილავი წიბოებით.", + "navbar.description.zoom": "ხედს მოდელთან აახლოებს ან აშორებს.", + "navbar.display": "ეკრანი", + "navbar.fit": "ჩატევა", + "navbar.graphics": "გრაფიკა", + "navbar.grid": "ბადე", + "navbar.ground_shadow": "ჩრდილი იატაკზე", + "navbar.home": "საწყისი ხედი", + "navbar.later": "მოგვიანებით", + "navbar.look_at": "პირისპირ ხედი", + "navbar.more": "მეტი", + "navbar.orbit": "ორბიტა", + "navbar.orthographic": "ორთოგრაფიული", + "navbar.pan": "პანორამა", + "navbar.perspective": "პერსპექტიული", + "navbar.preset": "პრესეტი", + "navbar.projection": "პროექცია", + "navbar.projection_heading": "პროექცია", + "navbar.separator": "გამყოფი", + "navbar.show": "ჩვენება", + "navbar.spin": "ბრუნვა", + "navbar.style.shaded": "დაჩრდილული", + "navbar.style.shaded_with_edges": "დაჩრდილული, წიბოებით", + "navbar.style.shaded_with_hidden_edges": "დაჩრდილული, უხილავი წიბოებით", + "navbar.style.wireframe": "კარკასი", + "navbar.translucent": "ნახევრად გამჭვირვალე", + "navbar.value_tip": "{name} · {value}", + "navbar.visual_style": "ვიზუალური სტილი", + "navbar.zoom": "მასშტაბი", + "needs two joints": "საჭიროა ორი შეერთება", + "network.allow_once": "ერთხელ დაშვება", + "network.always_allow": "ამ სერვერის ყოველთვის დაშვება", + "network.prompt_detail": "ეს პროექტი მიმართავს ფაილს ქსელურ მდებარეობაზე {host}. მისი გახსნა ამ კომპიუტერს დაუკავშირდება და შეიძლება მას თქვენი Windows-ის შესვლის მონაცემები გაუგზავნოს. დაუშვით მხოლოდ სანდო სერვერები.", + "network.prompt_title": "ქსელური მდებარეობა", + "new configuration": "ახალი კონფიგურაცია", + "new parameter": "ახალი პარამეტრი", + "no hole": "ნახვრეტი არ არის", + "no interference": "ურთიერთგადაკვეთა არ არის", + "no joint that moves yet": "მოძრავი შეერთება ჯერ არ არის", + "no motion study yet": "მოძრაობის კვლევა ჯერ არ არის", + "no picture": "გამოსახულება არ არის", + "no such joint": "ასეთი შეერთება არ არსებობს", + "none": "არცერთი", + "not a move": "ეს გადაადგილება არ არის", + "not a number": "რიცხვი არ არის", + "open a sketch first": "ჯერ გახსენით ესკიზი", + "parameters.apply_live": "თითოეული ცვლილების გამოყენება მისი ველიდან გასვლისას", + "parameters.apply_live_tip": "გამორთული: ცვლილებები ელოდება „გამოყენებას“ ან OK-ს, შემდეგ პროექტი ყველასთვის ერთხელ გადაიგება. „გაუქმება“ ან Escape მათ უარყოფს.", + "parameters.held": "გამოყენებას ელოდება ცვლილება: {count}", + "parameters.held_hint": "შეცვალეთ გამოსახულებები და ერთეულები. ცვლილებები ელოდება „გამოყენებას“ ან OK-ს.", + "parameters.held_one": "გამოყენებას ელოდება 1 ცვლილება", + "parts.automatic_name": "ავტომატური", + "parts.dimension.across_flats": "ზომა წახნაგებს შორის", + "parts.dimension.bore": "ნახვრეტი", + "parts.dimension.d": "ნომინალური დიამეტრი", + "parts.dimension.head_diameter": "თავის დიამეტრი", + "parts.dimension.head_height": "თავის სიმაღლე", + "parts.dimension.height": "სიმაღლე", + "parts.dimension.inner": "შიდა დიამეტრი", + "parts.dimension.outer": "გარე დიამეტრი", + "parts.dimension.pitch": "ბიჯი", + "parts.dimension.socket": "ბუდის ზომა", + "parts.dimension.socket_depth": "ბუდის სიღრმე", + "parts.dimension.thickness": "სისქე", + "parts.dimension.width": "სიგანე", + "parts.family.bearing": "ღრმაღარიანი ბურთულებიანი საკისარი (გაბარიტი)", + "parts.family.button_head_cap_screw": "ნახევარსფერულთავიანი ხრახნი შიდა ექვსწახნაგით", + "parts.family.dowel_pin": "ცილინდრული შტიფტი", + "parts.family.hex_bolt": "ექვსწახნაგთავიანი ჭანჭიკი / ხრახნი", + "parts.family.hex_cap_screw_inch": "ექვსწახნაგთავიანი ხრახნი (დუიმური)", + "parts.family.hex_nut": "ექვსწახნაგა ქანჩი", + "parts.family.hex_nut_inch": "ექვსწახნაგა ქანჩი (დუიმური)", + "parts.family.set_screw": "საყრდენი ხრახნი შიდა ექვსწახნაგით, ბრტყელი ბოლოთი", + "parts.family.socket_head_cap_screw": "ცილინდრულთავიანი ხრახნი შიდა ექვსწახნაგით", + "parts.family.washer": "ბრტყელი საყელური", + "parts.family.washer_sae": "ბრტყელი საყელური, SAE (ვიწრო)", + "parts.family.washer_uss": "ბრტყელი საყელური, USS (განიერი)", + "parts.holes": "ნახვრეტები (არასავალდებულო)", + "parts.placement_hint": "აირჩიეთ ერთი ან მეტი ნახვრეტი, რომ თითოეულში დეტალი ჩაჯდეს, ან OK მას სათავეში განათავსებს", + "parts.system": "ერთეულების სისტემა", + "parts.system.inch": "დუიმური", + "parts.system.metric": "მეტრული", + "pattern.alignment_2": "სწორება 2", + "pattern.alignment_hint": "რაოდენობაში ორიგინალიც ითვლება. „ცენტრში“ ასლებს აბალანსებს; „შებრუნება“ ლუწი ჯამისას ზედმეტი ასლის მხარეს ირჩევს.", + "pattern.direction_1": "მიმართულება 1", + "pattern.direction_2": "მიმართულება 2", + "pattern.flip_direction": "მიმართულების შებრუნება", + "perf.click_for_details": "დაწკაპეთ დეტალებისთვის: კადრის დროის გრაფიკი, ჰისტოგრამა და რა დახატა GPU-მ", + "perf.draw_calls": "ხატვის გამოძახებები", + "perf.line_segments": "ხაზის სეგმენტები", + "perf.low_1": "ყველაზე დაბალი 1%", + "perf.renderer": "რენდერერი", + "perf.scene_build": "სცენის აგება", + "perf.triangles": "სამკუთხედები", + "perf.ui_time": "UI-ის დრო", + "perf.viewport": "ხედვის არე", + "perf.worst": "ყველაზე ცუდი", + "pick a body or some of its faces": "აირჩიეთ სხეული ან მისი რამდენიმე წახნაგი", + "pick a hole to seat it, or OK places it at the origin": "აირჩიეთ ნახვრეტი ჩასასმელად, ან OK მას სათავეში განათავსებს", + "pick a planar face": "აირჩიეთ ბრტყელი წახნაგი", + "pick a plane or a face as the tool": "აირჩიეთ სიბრტყე ან წახნაგი ხელსაწყოდ", + "pick a size": "აირჩიეთ ზომა", + "pick edges of a body": "აირჩიეთ სხეულის წიბოები", + "pick edges of one body": "აირჩიეთ ერთი სხეულის წიბოები", + "pick edges of the holes to remove": "აირჩიეთ მოსაშორებელი ნახვრეტების წიბოები", + "pick faces of one body": "აირჩიეთ ერთი სხეულის წახნაგები", + "pick faces to offset": "აირჩიეთ წასანაცვლებელი წახნაგები", + "pick lines of one sketch": "აირჩიეთ ერთი ესკიზის ხაზები", + "pick one or two vertices, edges or faces": "აირჩიეთ ერთი ან ორი წვერო, წიბო ან წახნაგი", + "pick one plane or face as the tool, or sketch curves": "აირჩიეთ ერთი სიბრტყე ან წახნაგი ხელსაწყოდ, ან ესკიზის მრუდები", + "pick sections in two or more sketches": "აირჩიეთ კვეთები ორ ან მეტ ესკიზში", + "pick sketch curves or edges": "აირჩიეთ ესკიზის მრუდები ან წიბოები", + "pick the face to untrim": "აირჩიეთ წახნაგი მოკვეთის მოსახსნელად", + "pick the path": "აირჩიეთ ტრაექტორია", + "pick what to keep": "აირჩიეთ, რა დარჩეს", + "pick what to keep of the other surface": "აირჩიეთ, რა დარჩეს მეორე ზედაპირიდან", + "prefs.add_item": "ელემენტის დამატება", + "prefs.alt_frees_manipulators": "Alt / Option მანიპულატორის ისრებსაც ათავისუფლებს", + "prefs.anti_aliasing_amd_dx12": "კიდეების მოგლუვება იყენებს 1×-ს, რადგან გაშვებისას შემოწმებამ მულტისემპლინგით ვერაფერი დახატა, 1×-ით კი გაიარა. ზემოთ შეგიძლიათ სხვა პარამეტრი აირჩიოთ; მის გამოსაყენებლად გადატვირთეთ, თუ შემოწმება გაივლის.", + "prefs.anti_aliasing_note": "აგლუვებს დაკბილულ კიდეებს.", + "prefs.appearance.colour_vision_help": "ცვლის ფერებს, რომლებსაც მნიშვნელობა აქვს: ესკიზის მდგომარეობებს, ღერძებს, მოღუნვებს, ანალიზებსა და ხატულებს.", + "prefs.appearance.desktop_only": "მხოლოდ დესკტოპზე", + "prefs.appearance.follow_help": "ხელახლა იტვირთება, როცა ფაილს სხვა ხელსაწყო გადაწერს.", + "prefs.appearance.interface_scale": "ინტერფეისის მასშტაბი", + "prefs.appearance.next_themes": "შემდეგი თემები", + "prefs.appearance.option_count": "ვარიანტი: {count}", + "prefs.appearance.option_count_one": "ვარიანტი: {count}", + "prefs.appearance.previous_themes": "წინა თემები", + "prefs.appearance.theme_count": "თემა: {count}", + "prefs.appearance.theme_own": "თემის საკუთარი", + "prefs.appearance.viewport_colours": "3D ხედის ფერები", + "prefs.appearance.viewport_logo": "ხედვის არე და ლოგო", + "prefs.applies_on_restart": "გამოიყენება გადატვირთვისას", + "prefs.assistant": "ასისტენტი", + "prefs.auto_operation": "ოპერაციის ავტომატური არჩევა", + "prefs.auto_operation_note": "ოპერაციის ფანჯრები ირჩევენ შეერთებას, ახალ სხეულს ან ამოჭრას იმის მიხედვით, რას ეხება ახალი მასალა, სანამ თავად არ აირჩევთ. გამორთული: ისინი ინარჩუნებენ ოპერაციას, რომლითაც იხსნება.", + "prefs.axes": "ღერძები", + "prefs.axis": "ღერძი", + "prefs.bodies_folders": "სხეულების საქაღალდეები", + "prefs.bodies_folders_always": "ყოველთვის", + "prefs.bodies_folders_never": "არასოდეს", + "prefs.bodies_folders_several": "მხოლოდ რამდენიმე სხეულისას", + "prefs.bottom": "ქვემოთ", + "prefs.bottom_centre": "ქვედა ცენტრი", + "prefs.bottom_right": "ქვედა მარჯვენა", + "prefs.browser": "მოდელის ხე", + "prefs.browser_components_open": "კომპონენტები თავიდანვე გაშლილია", + "prefs.browser_components_open_note": "მოდელის ხეში ყველა კომპონენტი თავიდანვე გაშლილია, როგორც ადრე, და არა აკეცილი, სანამ არ გაშლით.", + "prefs.browser_eye_left": "თვალი გაშლის ისრის გვერდით", + "prefs.browser_eye_left_note": "მოდელის ხის სტრიქონებში ჩვენება/დამალვის თვალი გაშლის ისრის გვერდით ჩანს, როგორც ადრე, და არა სტრიქონების მარჯვენა ბოლოს სვეტში.", + "prefs.browser_reveal_on_hover": "ჩვენება მაჩვენებლის მიტანისას", + "prefs.browser_show_note": "„ნაჩვენები“ მოდელის ხეს ეკრანზე ტოვებს. „ჩვენება მაჩვენებლის მიტანისას“ მას მალავს, სანამ მაჩვენებელი მის ადგილს ან მის მარცხენა კიდეზე არსებულ წვრილ ჩანართს არ მიუახლოვდება, და ღია რჩება, სანამ მაჩვენებელი მასშია ან მისი მენიუ ღიაა.", + "prefs.browser_shown": "ნაჩვენები", + "prefs.built_in": "ჩაშენებული", + "prefs.button_left": "მარცხენა ღილაკით გადათრევა", + "prefs.button_middle": "შუა ღილაკით გადათრევა", + "prefs.button_right": "მარჯვენა ღილაკით გადათრევა", + "prefs.carousel_next": "შემდეგი", + "prefs.carousel_previous": "წინა", + "prefs.choose_font": "შრიფტის ფაილის არჩევა…", + "prefs.click": "დაწკაპება", + "prefs.contact_shading": "რბილი საკონტაქტო დაჩრდილვა", + "prefs.contact_shading_note": "რბილი დაჩრდილვა იქ, სადაც დეტალები ერთმანეთს უახლოვდება.", + "prefs.context_menu": "კონტექსტური მენიუ", + "prefs.context_menu_ring": "კონტექსტური მენიუ · დააყოვნეთ რადიალური მენიუსთვის", + "prefs.cpu": "CPU (პროგრამული)", + "prefs.crash_reports": "ავარიის ანგარიშების გახსნა…", + "prefs.crash_reports_note": "ანგარიშები ამ კომპიუტერზე ინახება, პროექტთან და ბრძანებებთან ერთად, რომლებიც პრობლემას იმეორებს.", + "prefs.ctrl_cmd": "Ctrl / Cmd", + "prefs.curved_surfaces": "მრუდი ზედაპირები", + "prefs.curves": "მრუდი ზედაპირები", + "prefs.cut_preview_tint": "მოცილებული მასალის წითლად ჩვენება", + "prefs.cut_preview_tint_help": "წინასწარი ნახვა ოპერაციის მიერ მოცილებულ მასალას და მის მიერ ჩანაცვლებულ ფორმას წითელი გამჭვირვალე ლანდით ავსებს. გამორთვისას ეს შევსებები სრულად გამჭვირვალეა და მხოლოდ მათი კონტურები იხატება.", + "prefs.dark_parts_shading": "მუქი დეტალების ფორმის შენარჩუნება", + "prefs.dark_parts_shading_help": "ხედის დაჩრდილვა წრფივ განათებაში ცის რბილი შევსებით, რომ მუქ წახნაგებს გრადიენტი შერჩეს და არ გაშავდეს", + "prefs.dead_zone_note": "დაშტრიხული ზოლი მკვდარი ზონაა: მის შიგნით მოძრაობა იგნორირდება.", + "prefs.default": "ნაგულისხმევი", + "prefs.design": "პროექტის ნაგულისხმევი პარამეტრები", + "prefs.design_note": "რით იწყება ახალი პროექტები. ღია პროექტები საკუთარ პარამეტრებს ინარჩუნებს.", + "prefs.devices": "3D მაუსი", + "prefs.dialog_buttons": "დიალოგის ღილაკები", + "prefs.dialogs": "დიალოგები", + "prefs.dialogs_edge": "ხედის კიდეზე", + "prefs.dialogs_left_column": "მარცხენა სვეტში", + "prefs.dialogs_note": "სად იხსნება ბრძანებების დიალოგები: ხედის კიდეზე მიმაგრებული, ან მარცხენა სვეტში მოდელის ხისა და ქრონოლოგიის ადგილას, რომლებიც დიალოგის დახურვისას წინანდელ მდგომარეობას უბრუნდება.", + "prefs.display": "ეკრანი", + "prefs.edges": "წიბოები და დაჩრდილვა", + "prefs.extend": "გაფართოება", + "prefs.extra_navigation": "Ctrl+მარცხენა ღილაკით გადათრევა ცარიელ ადგილზე: ორბიტა; პანორამისთვის დააჭირეთ Space-ს.", + "prefs.extrude_view_isometric": "ამოწევის გახსნისას ხედის იზომეტრიულზე გადაყვანა", + "prefs.extrude_view_return": "ამოწევის დახურვისას წინა ხედზე დაბრუნება", + "prefs.follows_os": "ოპერაციული სისტემის მიხედვით", + "prefs.font": "შრიფტი", + "prefs.font_fallback": "გლიფები, რომლებიც არჩეულ შრიფტს არ აქვს, ჩაშენებული შრიფტით გამოჩნდება, ასე რომ არცერთ წარწერაში ცარიელი კვადრატი არ ჩანს.", + "prefs.font_sample": "სწრაფი ყავისფერი მელა · Ø12.50 mm · 45.0° · 0123456789", + "prefs.font_unreadable": "არჩეული შრიფტის წაკითხვა ვერ მოხერხდა.", + "prefs.general": "ზოგადი", + "prefs.general.active": "აქტიური", + "prefs.general.crash_reports": "ავარიის ანგარიშები", + "prefs.general.edited": "შეცვლილი", + "prefs.general.held": "პროფილში ინახება", + "prefs.general.import": "იმპორტი...", + "prefs.general.last_check": "ბოლო შემოწმება: {time}", + "prefs.general.minutes": "წუთი", + "prefs.general.name_setup": "დაარქვით ამ კონფიგურაციას სახელი", + "prefs.general.profile_name": "პროფილის სახელი", + "prefs.general.save_new": "ახლად შენახვა", + "prefs.general.step_import": "STEP და იმპორტი", + "prefs.general.this_computer": "ეს კომპიუტერი", + "prefs.general_note": "პროფილები, ენა, ფაილები და განახლებები.", + "prefs.gesture_orbit": "ორბიტა", + "prefs.gesture_pan": "პანორამა", + "prefs.gesture_zoom": "მასშტაბი", + "prefs.graphics": "გრაფიკა", + "prefs.graphics_card": "ვიდეობარათი", + "prefs.graphics_card_auto": "ავტომატური", + "prefs.graphics_card_missing": "შენახული ვიდეობარათი მიუწვდომელია; გამოიყენება „ავტომატური“.", + "prefs.graphics_card_restart": "ძალაში შედის SolidCraft-ის გადატვირთვის შემდეგ. WGPU_ADAPTER_NAME ამ არჩევანს აუქმებს.", + "prefs.graphics_card_unused": "ამ ფანჯრისთვის შენახული ვიდეობარათი არ იქნა გამოყენებული; გამოყენებული ბარათი ნაჩვენებია „დახმარება › შესახებ“-ში და სტატუსის სტრიქონში. სცადეთ „ავტომატური“, ან WGPU_ADAPTER_NAME-ს მიანიჭეთ ბარათის სახელის უნიკალური ნაწილი.", + "prefs.graphics_note": "სიჩქარე სიგლუვის სანაცვლოდ. თითოეული არჩევანი თავის ეფექტს ნიმუშზე აჩვენებს.", + "prefs.graphics_presets_note": "პრესეტები ქვემოთ მოცემულ არჩევანს ერთად აყენებს.", + "prefs.hide_constraint_glyphs_zoomed_out": "შეზღუდვის გლიფების დამალვა დაშორებისას", + "prefs.hide_constraint_glyphs_zoomed_out_note": "შეზღუდვის გლიფები ხედიდან ქრება, როცა ესკიზი იმდენად არის დაშორებული, რომ ხედს გადატვირთავდნენ. გამორთული: ისინი ყველა მასშტაბზე ეკრანის ფიქსირებულ ზომას ინარჩუნებს.", + "prefs.history": "ქრონოლოგია", + "prefs.history_origin_bodies": "სათავისა და სხეულების ზემოთ ჩვენება", + "prefs.history_origin_bodies_note": "მარცხნივ ან მოდელის ხის ქვეშ მდებარე ქრონოლოგია იწყება აქტიური კომპონენტის სხეულების საქაღალდითა და სათავით, მათი თვალებითა და მენიუებით, როგორც მოდელის ხეში. ქვემოთ მდებარე ქრონოლოგია არ იცვლება.", + "prefs.history_play_button": "ქრონოლოგიის დაკვრის ღილაკი ქრონოლოგიის მართვის ელემენტებში", + "prefs.history_play_button_note": "ქრონოლოგიის მართვის ელემენტებში „ქრონოლოგიის დაკვრას“ სვამს „ერთი ნაბიჯით უკან“ და „ერთი ნაბიჯით წინ“ შორის. მის საჩვენებლად ან დასამალად ასევე შეგიძლიათ მართვის ელემენტებზე მარჯვენა ღილაკით დაწკაპება.", + "prefs.history_sketches": "ესკიზები", + "prefs.history_sketches_in_order": "რიგის მიხედვით", + "prefs.history_sketches_note": "როცა „ესკიზები“ დაყენებულია „მათი ოპერაციის ქვეშ“, მარცხნივ მდებარე ქრონოლოგია თითოეულ ესკიზს ერთი დონით შიგნით აჩვენებს, პირველი ოპერაციის ქვეშ, რომელიც მისგან აიგო, თუ სახელებისთვის საკმარისად ფართოა. ქვემოთ მდებარე ქრონოლოგია ყოველთვის შექმნის რიგს ინარჩუნებს.", + "prefs.history_sketches_under_feature": "მათი ოპერაციის ქვეშ", + "prefs.hold_stop_snapping": "დააჭირეთ მიბმის შესაჩერებლად", + "prefs.home_fit_size": "საწყისი ხედისა და ჩატევის ზომა", + "prefs.home_fit_size_note": "ხედის რა ნაწილს ავსებს მოდელი, როცა მას საწყისი ხედი, ჩატევა, გახსნილი პროექტი ან ნავიგატორის ხედის შეცვლა კადრში აქცევს, ქვემოთ მოცემული პარამეტრის ჩართვის მიუხედავად. 100 %: ავსებს ხედს პანელებს, კომპასსა და ნავიგაციის ზოლს შორის.", + "prefs.icons_only": "მხოლოდ ხატულები", + "prefs.imported_file": "იმპორტირებული ფაილი", + "prefs.in_browser": "მოდელის ხეში", + "prefs.input": "შეყვანა", + "prefs.interface": "ინტერფეისი", + "prefs.interface_language": "ინტერფეისის ენა", + "prefs.interface_note": "როგორ გამოიყურება SolidCraft და სად არის მისი ნაწილები.", + "prefs.interval_minutes": "{n} წთ", + "prefs.invert_curved_roll_arrows": "გორების მრუდე ისრების შებრუნება", + "prefs.invert_curved_roll_arrows_note": "კუბის კუთხესთან მდებარე ორი მრუდე ისარი ხედს ეკრანის სიბრტყეში აგორებს. ჩართული: საათის ისრის მიმართულების ისარი საათის ისრის საწინააღმდეგოდ აგორებს, საწინააღმდეგო კი — საათის ისრის მიმართულებით. გამორთული: თითოეული ისარი ხედს თავისი მოხრის მიმართულებით აგორებს.", + "prefs.invert_navigator_arrows": "ხედის კუბის ბრუნვის ისრების შებრუნება", + "prefs.invert_navigator_arrows_note": "კუბის გარშემო ისრები კამერას ორბიტაზე იმ მიმართულებით ატრიალებს, საითაც მიუთითებს, როგორც Fusion-სა და Inventor-ში: მარცხენა ისარი მარჯვნივ მიუთითებს და კამერას მარჯვნივ აბრუნებს. გამორთული: ისარი კუბს იმ მხრისკენ აბრუნებს, რომელზეც მდებარეობს, ამიტომ მარცხენა ისარი კამერას მარცხნივ აბრუნებს. გორების მრუდე ისრებზე ეს არ მოქმედებს.", + "prefs.keep_work_on_tab_switch": "პროექტებს შორის გადართვისას დიალოგებისა და ხელსაწყოების ღიად დატოვება", + "prefs.keep_work_on_tab_switch_note": "პროექტის თითოეული ჩანართი ინარჩუნებს თავის ღია დიალოგს ან ხელსაწყოს, მასში არჩეულსა და აკრეფილს, და ხელსაწყოთა ზოლის ჩანართს. პროექტში დაბრუნებისას ისინი ისევ იქ დაგხვდებათ. გამორთული: პროექტების გადართვა მათ აუქმებს და „მოდელის“ ჩანართს აჩვენებს.", + "prefs.labels": "წარწერები", + "prefs.language_system": "სისტემური", + "prefs.layout": "განლაგება", + "prefs.layout_note": "„კომპაქტური“ პანელებს ფანჯრის კიდეებზე ამაგრებს. მოდელის ხის გამჭვირვალობა ხელმისაწვდომია „მცურავ“ რეჟიმში. ასისტენტის მხარე შეცვალეთ ასისტენტის გვერდზე.", + "prefs.left": "მარცხნივ", + "prefs.left_click": "მარცხენა დაწკაპება", + "prefs.line_drag_draws_one": "დაჭერა და გადათრევა ერთ ხაზს ხატავს", + "prefs.line_drag_draws_one_note": "ხაზის ხელსაწყოში დაჭერა, გადათრევა და აშვება ერთ ხაზს ხატავს დაჭერის წერტილიდან აშვების წერტილამდე და იქვე სრულდება. დაწკაპებები კვლავ ჯაჭვს ხატავს. გამორთული: გადათრევა წერტილს იქ სვამს, სადაც აუშვებთ, როგორც დაწკაპება.", + "prefs.line_hover_tangent_arc": "ხაზის ბოლო წერტილზე შეჩერებით მხებ რკალზე გადართვა", + "prefs.line_hover_tangent_arc_note": "ხაზის ხელსაწყოში, სეგმენტის დახატვის შემდეგ, მოაშორეთ მაჩვენებელი ჯაჭვის ბოლო წერტილს, დაბრუნდით და უძრავად გააჩერეთ მასზე: შემდეგი დაწკაპება მხებ რკალს დაასრულებს, იგივე ჟესტი კი ხაზებზე დააბრუნებს. გამორთული: იქ შეჩერება არაფერს აკეთებს.", + "prefs.linked_designs": "მიბმული პროექტები", + "prefs.live_input": "ცოცხალი შეყვანა", + "prefs.live_preview": "ცოცხალი წინასწარი ნახვა", + "prefs.logo": "ლოგო", + "prefs.logo_accent": "აქცენტის ფერი", + "prefs.logo_theme": "თემის ფერები", + "prefs.max_file_size": "გასახსნელი ფაილის მაქსიმალური ზომა", + "prefs.max_file_size_design": "გასახსნელი ფაილის მაქსიმალური ზომა: პროექტი", + "prefs.max_file_size_flag": "ეს სესია დაიწყო --max-file-size {size}-ით, რომელიც SolidCraft-ის დახურვამდე მოქმედებს. ეს პარამეტრები მოქმედებს, როცა ის მის გარეშე ეშვება.", + "prefs.max_file_size_note": "ნაგულისხმევი: 512 MB და 256 MB; მაქსიმუმ 16 GB. ფაილის გახსნას მეხსიერებაში მისი ზომის რამდენჯერმე მეტი სჭირდება. დიდი იმპორტის შემცველ პროექტს შენახვისა და ხელახლა გახსნისთვის შეიძლება პროექტის ფაილის უფრო მაღალი ლიმიტი დასჭირდეს.", + "prefs.max_file_size_step": "გასახსნელი ფაილის მაქსიმალური ზომა: STEP და იმპორტი", + "prefs.max_file_size_web": "ვებაპი ხსნის STEP და იმპორტის ფაილებს 512 MB-მდე და პროექტებს 256 MB-მდე: ბრაუზერის ჩანართი უფრო დიდ ფაილებს ვერ იტევს. დესკტოპის აპს ამ ლიმიტების გაზრდა შეუძლია.", + "prefs.megabytes": "MB", + "prefs.menu_grid": "დიდი ხატულები", + "prefs.menu_list": "სია", + "prefs.menus": "მენიუები", + "prefs.minutes": "წუთი", + "prefs.minutes_suffix": " წთ", + "prefs.mouse": "მაუსი და სენსორული პანელი", + "prefs.mouse_heading": "მაუსი", + "prefs.mouse_mapping": "მაუსის სქემა", + "prefs.navigation": "ნავიგაცია", + "prefs.navigation_note": "როგორ ამოძრავებს ხედს მაუსი, სენსორული პანელი და 3D მაუსი.", + "prefs.navigator_fit": "ნავიგატორით ხედის შეცვლის შემდეგ მოდელის ჩატევა", + "prefs.navigator_fit_note": "ხედის კუბის წახნაგი, კუთხე ან ისარი, ან მანიპულატორის ღერძი ასევე მოდელის შუაგულს უყურებს ერთი მანძილიდან, საიდანაც ის ყველა მხრიდან ეტევა (მისი შემომსაზღვრელი სფერო). სანამ ეს ჩართულია, საწყისი ხედი იმავე მასშტაბსა და ცენტრს იყენებს, ამიტომ მის შემდეგ არჩეული ხედები მხოლოდ ბრუნავს. გამორთული: ხედი ადგილზე ბრუნავს, სამიზნისა და მასშტაბის შენარჩუნებით.", + "prefs.network_host_remove": "წაშლა", + "prefs.network_locations": "პროექტებში ქსელური მდებარეობების დაშვება", + "prefs.network_locations_note": "ორგანიზაციებისთვის, რომლებიც პროექტებს ფაილურ სერვერებზე ინახავენ. გამორთული: მხოლოდ თქვენ მიერ დაშვებული სერვერები.", + "prefs.network_locations_section": "ქსელური მდებარეობები", + "prefs.not_on_gpu": "ამ GPU-ზე არა", + "prefs.on": "ჩართული", + "prefs.opaque": "გაუმჭვირვალე", + "prefs.orbit_snap": "ღერძზე მისაბმელად ორბიტისას დააჭირეთ Shift-ს.", + "prefs.orientation": "ორიენტაცია", + "prefs.origin_plane_names": "სათავის სიბრტყეების სახელები", + "prefs.origin_plane_names_note": "სახელები, რომლებიც მოდელის ხეში, დიალოგებსა და სიებში ჩანს. {top} არის XY, {front} — XZ და {right} — YZ, Z ზემოთ. ბრძანებები, სკრიპტები და შენახული პროექტები XY-ს, XZ-სა და YZ-ს ინარჩუნებს.", + "prefs.overall_speed": "საერთო სიჩქარე", + "prefs.parameter_list_rows": "პარამეტრების სიის სტრიქონები", + "prefs.parameter_list_rows_tip": "ცარიელ მნიშვნელობის ველში ქვემოთ ისარი პარამეტრებს ჩამოთვლის, ჯერ რჩეულებს, მაქსიმუმ ამდენს. ნაკლები რაოდენობა სიას დიდ პროექტში მსუბუქს ტოვებს.", + "prefs.persistent_ribbon_pressed": "ლენტის აქტიური ბრძანებების გამოკვეთა", + "prefs.persistent_ribbon_pressed_help": "ლენტის ბრძანებების გამოკვეთა, სანამ მათი ეფექტი ჩართულია. გამორთეთ წინა ნეიტრალური იერსახისა და ბრძანების დახმარების შესანარჩუნებლად.", + "prefs.perspective_fov": "ხედვის კუთხე", + "prefs.placement": "განთავსება", + "prefs.prefer_free_sketch_points": "გადაფარვისას ესკიზის მოძრავი წერტილების უპირატესობა", + "prefs.preview_choices": "თქვენი არჩევანის წინასწარი ნახვა", + "prefs.preview_tint_new_faces": "ახალი ზედაპირის შეფერვა წინასწარ ნახვაში", + "prefs.preview_tint_new_faces_help": "სხეულის შემცვლელი ოპერაციის წინასწარ ნახვას შეუძლია მის მიერ დამატებული ზედაპირი წინასწარი ნახვის ფერით დახატოს. გამორთვისას სხეული ისე იხატება, როგორიც არის.", + "prefs.print_face_highlight": "საბეჭდი წახნაგის გამოკვეთა", + "prefs.print_face_highlight_tip": "რამდენად ძლიერად იღებება და იკონტურება ხედში სხეულის საბეჭდი წახნაგი. 0 % გამოკვეთას არ აჩვენებს.", + "prefs.profile_active": "აქტიური პროფილი", + "prefs.profile_applied": "პროფილი გამოყენებულია.", + "prefs.profile_changed": "პარამეტრები შეიცვალა პროფილის შენახვის შემდეგ. „შენახვა“ მათ პროფილში შეინახავს.", + "prefs.profile_deleted": "პროფილი წაიშალა.", + "prefs.profile_export": "ექსპორტი", + "prefs.profile_exported": "პროფილის ექსპორტი შესრულდა.", + "prefs.profile_imported": "პროფილის იმპორტი შესრულდა.", + "prefs.profile_name_hint": "პროფილის სახელი, მაგ. ლეპტოპი", + "prefs.profile_operations": "ოპერაციების პროფილირება", + "prefs.profile_operations_note": "იწერს, რამდენ ხანს გრძელდება SMLib-ის გამოძახებები, ბირთვის ოპერაციები, მოდელირების ოპერაციები, ბრძანებები და იმპორტები. აგენტები ამას diagnostics.profile-ით კითხულობენ.", + "prefs.profile_rename": "სახელის შეცვლა", + "prefs.profile_renamed": "პროფილს სახელი შეეცვალა.", + "prefs.profile_save": "შენახვა", + "prefs.profile_saved": "მიმდინარე პარამეტრები პროფილში შეინახა.", + "prefs.profile_skipped": "პროფილი გამოყენებულია; პარამეტრმა ({n}) მიმდინარე მნიშვნელობა შეინარჩუნა (იხილეთ ჟურნალი).", + "prefs.profiles": "პარამეტრების პროფილები", + "prefs.profiles_note": "მალსახმობები, ხელსაწყოთა ზოლი, ნავიგაცია, რადიალური მენიუ და ინტერფეისის პარამეტრები, ერთად შენახული ერთი სახელით და ერთბაშად გადასართავი.", + "prefs.project_options_dialog": "დაგეგმილების პარამეტრების დიალოგი", + "prefs.project_options_dialog_note": "ჩართული: დაგეგმილებამდე აირჩიეთ „გეომეტრია“ ან „სხეულები“ და „დაგეგმილების კავშირი“. გამორთული: შეინარჩუნეთ წინა, პირდაპირი არჩევის სამუშაო პროცესი.", + "prefs.quality_default": "ნაგულისხმევი", + "prefs.quality_fastest": "უსწრაფესი", + "prefs.quality_slowest": "უნელესი", + "prefs.quality_smoother": "უფრო გლუვი", + "prefs.quick_measure": "სწრაფი გაზომვა ხედის კუთხეში", + "prefs.quick_measure_note": "მონიშნულის ზომა ხედის ქვედა მარჯვენა კუთხეში: წიბოს სიგრძე, ან Ø და R მრგვალისთვის, წახნაგის ფართობი, წერტილის პოზიცია, ორი ელემენტის მანძილი და კუთხე, რამდენიმე წიბოს ან წახნაგის ჯამი. დაწკაპება მას აკოპირებს.", + "prefs.render_previous_geometry_budget": "რენდერის წინასწარი ნახვის გეომეტრიის წინა ლიმიტის გამოყენება", + "prefs.render_previous_geometry_budget_help": "წინა ფიქსირებული გეომეტრიის ლიმიტის აღდგენა (512 MiB 64-ბიტიან დესკტოპზე, 128 MiB სხვაგან) მოწყობილობაზე დამოკიდებული ლიმიტის ნაცვლად.", + "prefs.reports_saved": "შენახულია: {n}", + "prefs.restore_page_defaults": "გვერდის ნაგულისხმევის აღდგენა", + "prefs.ribbon_click_ends_tool": "მიმდინარე ხელსაწყოს ღილაკზე დაწკაპება მას ასრულებს", + "prefs.ribbon_click_ends_tool_note": "გამოყენებული ესკიზის ხელსაწყოს ანთებულ ლენტის ღილაკზე დაწკაპება ხელსაწყოს ასრულებს, ასე რომ ხედში დაწკაპება ისევ მონიშნავს. გამორთული: დაწკაპება ხელსაწყოს თავიდან იწყებს.", + "prefs.ribbon_reveal": "ძიების შედეგების ჩვენება ლენტში", + "prefs.ribbon_reveal_note": "ბრძანებების ძიებაში შედეგზე მაჩვენებლის მიტანა აჩვენებს, სად არის ბრძანება ლენტში: მისი ჩანართი, ღილაკი ან სტრიქონი პანელის ჩამოსაშლელ სიაში. ძიებიდან გაშვებული ბრძანება იქ ციმციმებს, ხოლო ჩამოსაშლელი სიიდან გაშვებული მიმდინარე ბრძანება თავის პანელს აღნიშნავს.", + "prefs.right_click": "მარჯვენა დაწკაპება", + "prefs.saving": "გაშვება და შენახვა", + "prefs.scale_note": "ფანჯარაში ასევე Ctrl + / Ctrl −. ღილაკები 100%-ზე 28 px-ია.", + "prefs.scale_text": "მასშტაბი და ტექსტი", + "prefs.search": "პარამეტრების ძიება", + "prefs.search_empty": "შესაბამისი პარამეტრი ვერ მოიძებნა", + "prefs.section_hatch": "კვეთის დაშტრიხვა", + "prefs.section_hatch_by_part": "დეტალის მიხედვით", + "prefs.section_hatch_one": "ერთი სტილი", + "prefs.select": "მონიშვნა", + "prefs.select_one_item": "ერთი ელემენტის მონიშვნა", + "prefs.select_other_hidden": "დამალული გეომეტრიის მონიშვნა „სხვის მონიშვნით“", + "prefs.select_other_hidden_help": "ჩართული: მაჩვენებელთან ახლოს დამალული სხეულების, ესკიზებისა და დაფარული წიბოების ჩართვა. გამორთული: მაჩვენებლის ქვეშ ხილული გეომეტრიის საწყისი სიის გამოყენება.", + "prefs.selecting": "მონიშვნა", + "prefs.shift": "Shift", + "prefs.shift_add_ctrl_toggle": "Shift მხოლოდ ამატებს; Ctrl / Cmd გადართავს", + "prefs.shift_add_note": "ჩართული: Shift ამატებს, Ctrl / Cmd გადართავს. გამორთული (ნაგულისხმევი): ორივე გადართავს.", + "prefs.shortcuts": "მალსახმობები", + "prefs.single_surface_analysis": "ზედაპირის ერთი ანალიზის გამოყენება", + "prefs.single_surface_analysis_help": "გამორთულისას ზედაპირის დაჩრდილვა და უწყვეტობა შეიძლება ერთად იყოს ჩართული. ამის ჩართვა ბოლოს დაწყებულ ან შეცვლილ ანალიზს ტოვებს.", + "prefs.sketch_align_points": "ხატვისას ესკიზის სხვა წერტილებთან გასწორება", + "prefs.sketch_align_points_note": "ხატვისას წერტილი ერთდროულად ჰორიზონტალურად სწორდება ესკიზის ერთ წერტილთან და ვერტიკალურად მეორესთან, წერტილოვანი დამხმარე ხაზით, და დაწკაპება ორივე გასწორებას ინარჩუნებს. გამორთული: მხოლოდ წინა წერტილთან, თითო ღერძით.", + "prefs.sketch_conflict_colour": "კონფლიქტური გეომეტრია კონფლიქტის ფერით", + "prefs.sketch_conflict_colour_note": "სანამ ესკიზის შეზღუდვები ერთმანეთს ეწინააღმდეგება, წარუმატებელი შეზღუდვის მიერ დაკავებული მრუდები და წერტილებიც კონფლიქტის ფერით იხატება და არა მხოლოდ მისი გლიფი ან ზომა. გამორთული: ისინი ჩვეულ ფერებს ინარჩუნებს.", + "prefs.sketch_construction_lines": "დამხმარე ხაზების გაფართოებული ხელსაწყოები", + "prefs.sketch_exit_view": "ესკიზის დასრულებისას", + "prefs.sketch_exit_view.keep": "მიმდინარე ხედის შენარჩუნება", + "prefs.sketch_exit_view.previous": "წინა ხედზე დაბრუნება", + "prefs.sketch_exit_view.unless_rotated": "დაბრუნება, თუ არ შემობრუნებულა", + "prefs.sketch_exit_view_note": "სად გადადის ხედი „ესკიზის დასრულების“, „გაუქმების“ ან ორმაგი Esc-ის შემდეგ.", + "prefs.sketch_face_activates_part": "დეტალის წახნაგზე ესკიზის დაწყება ამ დეტალს აქტიურს ხდის", + "prefs.sketch_face_activates_part_note": "სხვა კომპონენტის სხეულის წახნაგზე დაწყებული ესკიზი ჯერ ამ კომპონენტს ააქტიურებს, ასე რომ ესკიზი მას ეკუთვნის და მოდელის ხეში ამ დეტალთან რჩება. დეტალი ამის შემდეგაც აქტიური რჩება. გამორთული: ესკიზი აქტიურ კომპონენტს ეკუთვნის.", + "prefs.sketch_open_look_at": "ესკიზის გახსნისას პირისპირ შემობრუნება", + "prefs.sketch_open_look_at_note": "გამორთული: ესკიზის შექმნა ან რედაქტირება ხედს ისე ტოვებს, როგორც არის. „პირისპირ ხედი“ ესკიზს მაშინ აბრუნებს, როცა გსურთ.", + "prefs.sketch_recent_snap": "ბოლო ცენტრებსა და შუა წერტილებზე ავტომატური მიბმა", + "prefs.sketch_recent_snap_note": "ხატვისას კურსორის მიბმა იქ, სადაც ორი ბოლო წრის ცენტრის ან სწორი წიბოს შუა წერტილის დამხმარე ხაზები იკვეთება. გამორთული: ეს დამხმარე ხაზები მხოლოდ ვიზუალურია და კურსორი არ მოძრაობს.", + "prefs.sketch_selection": "ესკიზი და მონიშვნა", + "prefs.sketch_selection_heading": "ესკიზი და მონიშვნა", + "prefs.sketch_selection_note": "როგორ ებმება ესკიზები და როგორ მონიშნავს დაწკაპებები.", + "prefs.sketch_state_icons": "ესკიზის ხატულები მათი მდგომარეობის ფერით", + "prefs.sketch_state_icons_note": "ქრონოლოგიასა და მოდელის ხეში ესკიზის ხატულა მისი მდგომარეობის ფერს იღებს (ნაკლებად შეზღუდული, სრულად შეზღუდული ან კონფლიქტური) და მისი მინიშნება მდგომარეობას ასახელებს. გამორთული: ყველა ესკიზს ერთნაირი ხატულა აქვს.", + "prefs.sketch_tab_always": "ესკიზის ჩანართის მუდმივი ჩვენება", + "prefs.sketch_tab_always_note": "ესკიზის ჩანართი ლენტში რჩება, „მოდელის“ შემდეგ, სანამ ესკიზი გახსნილი არ არის. მისი ხატვის ხელსაწყოები მაშინ ესკიზს მონიშნულ სიბრტყეზე ან წახნაგზე იწყებს, ან სიბრტყეზე, რომელსაც შემდეგ აირჩევთ, და ხელსაწყო მასში მზად არის.", + "prefs.sketch_tracking_guides": "ცენტრისა და შუა წერტილის გასწორების დამხმარე ხაზები", + "prefs.sketch_tracking_guides_note": "მიიტანეთ მაჩვენებელი წრის ცენტრზე ან სწორი წიბოს შუა წერტილზე, შემდეგ გადაადგილეთ ჰორიზონტალურად ან ვერტიკალურად დროებითი წერტილოვანი დამხმარე ხაზის საჩვენებლად.", + "prefs.sketch_tracking_points": "ხატვისას გასწორების დამხმარე ხაზები ბოლო წერტილებიდან და კუთხეებიდან", + "prefs.sketch_tracking_points_note": "სანამ ხატვის ხელსაწყო წერტილს ელოდება, ხაზის ან რკალის ბოლოზე, მართკუთხედის კუთხეზე ან თავისუფალ წერტილზე მაჩვენებლის მიტანა იმავე დროებით წერტილოვან დამხმარე ხაზს აჩვენებს, რასაც ცენტრი ან შუა წერტილი. გამორთული: მხოლოდ ცენტრები და შუა წერტილები.", + "prefs.sketching": "ესკიზის ხატვა", + "prefs.snap_drawing_note": "ესკიზის წერტილის ხატვის ან გადათრევისას.", + "prefs.source": "წყარო", + "prefs.speed": "სიჩქარე", + "prefs.stand_up_note": "როცა STEP ან IGES ფაილი Z ზემოთ იხსნება, X-ის გარშემო მეოთხედი ბრუნის შეთავაზება.", + "prefs.stand_up_unknown": "უცნობი პროგრამების ფაილებისთვის", + "prefs.stand_up_unknown.ask": "დიალოგში კითხვა", + "prefs.stand_up_unknown.note": "შენიშვნის ჩვენება", + "prefs.stand_up_unknown.off": "არ შემოთავაზება", + "prefs.stand_up_unknown_note": "როგორ ხდება შეთავაზება, როცა ფაილის თავსართი არ ასახელებს პროგრამას, რომელიც ცნობილია Y ზემოთ შენახვით. შენიშვნა მხოლოდ მაშინ ჩანს, როცა ფაილი, როგორც ჩანს, ზურგზე წევს; „დიალოგში კითხვა“ ყოველ ასეთ ფაილზე კითხულობს, როგორც ადრე.", + "prefs.status_bar": "სტატუსის ზოლი", + "prefs.status_bar_note": "ფანჯრის ქვედა კიდეზე წვრილი ზოლი აჩვენებს, რა რედაქტირდება, ღია ესკიზის მდგომარეობას მისი ფერით და პროექტის ერთეულებს; ერთეულებზე დაწკაპება მათ ცვლის. ესკიზის მდგომარეობა მაშინ ხედის კუთხეში აღარ ჩანს.", + "prefs.status_done": "მზადაა", + "prefs.status_error": "შეცდომა", + "prefs.status_selected": "მონიშნული", + "prefs.status_warning": "გაფრთხილება", + "prefs.structure.appearance": "იერსახე", + "prefs.structure.appearance_note": "ფერები, ტექსტი და მისაწვდომობა.", + "prefs.structure.in_profile": "პროფილშია", + "prefs.structure.layout": "განლაგება", + "prefs.structure.layout_note": "სად მდებარეობს ფანჯრის ნაწილები.", + "prefs.structure.look": "ვიზუალური სტილი", + "prefs.structure.measure_pointer": "გაზომვა და მაჩვენებელი", + "prefs.structure.mouse3d": "3D მაუსი", + "prefs.structure.mouse3d_note": "SpaceMouse და SpaceNavigator.", + "prefs.structure.navigation_note": "მაუსი და სენსორული პანელი. 3D მაუსს საკუთარი გვერდი აქვს.", + "prefs.structure.profile": "პროფილი", + "prefs.structure.profile_edited": "შენახვის შემდეგ შეიცვალა", + "prefs.structure.profile_hover": "ინახება პარამეტრების პროფილებში", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "ესკიზი", + "prefs.structure.tools": "ხელსაწყოები", + "prefs.structure.tools_note": "როგორ იქცევა მოდელირების ხელსაწყოები.", + "prefs.structure.work": "მუშაობა", + "prefs.supersampling_brief": "ხედს უფრო დიდ ზომაში ხატავს და ამცირებს: ძალიან მკვეთრი და უფრო მძიმე.", + "prefs.tab_accent_note": "აქცენტის ფერი აქტიურ ჩანართს მიჰყვება", + "prefs.theme_file": "თემის ფაილი", + "prefs.theme_file_or_paste": "ფაილი ან ჩასმა", + "prefs.theme_follow": "თემის ფაილის მიდევნება", + "prefs.theme_follow_error": "არ გამოყენებულა: {error}. ბოლო სწორი თემა რჩება.", + "prefs.theme_follow_launch": "მიდევნება მხოლოდ ამ სესიაში (--theme-file); ხელახლა იტვირთება, როცა მას სხვა ხელსაწყო გადაწერს.", + "prefs.theme_follow_note": "ხელახლა იტვირთება, როცა მას სხვა ხელსაწყო გადაწერს. თემის არჩევა მიდევნებას წყვეტს.", + "prefs.theme_follow_off": "გამორთული", + "prefs.theme_follow_stop": "მიდევნების შეწყვეტა", + "prefs.theme_import_hint": "დაწკაპეთ თემის ფაილის ასარჩევად, ჩააგდეთ ფაილი აქ, ან დააჭირეთ Ctrl+V-ს (Mac-ზე Cmd+V) დაკოპირებული თემით", + "prefs.theme_option_opacity": "გაუმჭვირვალობა", + "prefs.theme_option_opacity_help": "მცურავი პანელების გაუმჭვირვალობის მორგება. წაკითხვადობის ქვედა ზღვარი ტექსტს ხედვის არის ფერებზე იცავს.", + "prefs.theme_option_tab_colours": "ჩანართების ფერები", + "prefs.theme_option_tab_colours_help": "ლენტის თითოეული ჩანართისთვის ამ თემის პანელისა და ხედვის არის ფერების გამოყენება.", + "prefs.theme_option_tab_fade_ms": "ჩანართების გადასვლა", + "prefs.theme_option_tab_fade_ms_help": "პანელისა და ხედვის არის ფერების თანდათანობითი შეცვლა ჩანართების გადართვისას. ნულის შემთხვევაში გადართვა მყისიერია.", + "prefs.theme_options_badge": "პარამეტრები", + "prefs.theme_options_more": "მეტი · {count}", + "prefs.theme_options_reset": "ჩამოყრა", + "prefs.theme_options_unavailable": "ამ მოწყობილობაზე მიუწვდომელია", + "prefs.theme_paste": "თემის ჩასმა", + "prefs.theme_paste_none": "ბუფერში SolidCraft-ის თემა არ არის", + "prefs.timeline_half_hour": "−30 წთ", + "prefs.timeline_now": "ახლა", + "prefs.timeline_quarter_hour": "−15", + "prefs.toast_place": "შეტყობინებები", + "prefs.toggle_item": "ელემენტის დამატება ან ისევ ამოღება", + "prefs.toolbar": "ხელსაწყოთა ზოლი", + "prefs.toolbar_tabs": "ხელსაწყოთა ზოლის ჩანართები", + "prefs.top": "ზემოთ", + "prefs.trackpad_zoom_modifier": "მასშტაბი ორი თითით გადახვევით, როცა დაჭერილია", + "prefs.trackpad_zoom_modifier.alt": "⌥ / Alt", + "prefs.trackpad_zoom_modifier.cmd": "⌘", + "prefs.trackpad_zoom_modifier.ctrl": "Ctrl", + "prefs.trackpad_zoom_modifier.help": "მაჩვენებელთან ვერტიკალური გადახვევით მასშტაბისთვის დააჭირეთ მხოლოდ ამ კლავიშს. „გამორთული“ გადახვევის არსებულ ქცევას ინარჩუნებს.", + "prefs.trackpad_zoom_modifier.off": "გამორთული", + "prefs.translucent": "ნახევრად გამჭვირვალე", + "prefs.under_browser": "მოდელის ხის ქვეშ", + "prefs.under_cursor": "კურსორის ქვეშ", + "prefs.units_precision": "ერთეულები და სიზუსტე", + "prefs.updates": "განახლებები", + "prefs.validation": "სხეულის შემოწმება", + "prefs.validation.each_feature": "ერთხელ თითო ოპერაციაზე", + "prefs.validation.each_step": "ყოველი ნაბიჯის შემდეგ", + "prefs.validation.label": "ბირთვის სრული შემოწმება", + "prefs.validation.off": "გამორთული (ექსპერიმენტული)", + "prefs.validation_note": "ყოველი ნაბიჯის შემდეგ: მოწმდება ყოველი ტრაექტორიით აგება, ბულის ოპერაცია და მომრგვალება.\nერთხელ თითო ოპერაციაზე: თითოეული ოპერაციის შედეგი ერთხელ მოწმდება.\nგამორთული (ექსპერიმენტული): შემოწმება არ ხდება.", + "prefs.value_boxes_in_view": "მნიშვნელობების ჩვენება ხედში მათ სახელურებთან", + "prefs.value_boxes_in_view_tip": "ბრძანების მნიშვნელობა (მანძილი, რადიუსი…) ველში მისი სახელურის გვერდით, მოდელის თავზე. გამორთული: მას ბრძანების ფანჯარაში აკრეფთ, რომელიც არჩევის შემდეგ კლავიატურას იკავებს, და მოდელს არაფერი ფარავს.", + "prefs.view": "ხედის ქცევა", + "prefs.view_confirm_corner": "OK და გაუქმება ხედის კუთხეში", + "prefs.view_confirm_corner_note": "სანამ დიალოგი ან ესკიზი ღიაა, ხედის ზედა მარჯვენა კუთხეში თოლია და ჯვარი იმავეს აკეთებს, რასაც დიალოგის OK და „გაუქმება“, ან ასრულებს და აუქმებს ესკიზს. ხედის ნავიგატორი მათ ქვემოთ ჩადის.", + "prefs.viewport": "ხედვის არე", + "prefs.viewport_analysis_status": "ხედვის არეში ანალიზის სტატუსის ჩვენება", + "prefs.viewport_analysis_status_help": "აქტიური ანალიზების ჩვენება ხედვის არის ზემოთ, მათი ლეგენდების გახსნა თითოეული ელემენტიდან და Esc-ით უახლესი ანალიზის გამორთვა. გამორთეთ კუთხის ლეგენდებისა და Esc-ის წინა ქცევის აღსადგენად.", + "prefs.viewport_background": "ფონი", + "prefs.viewport_background_colour": "ფერი", + "prefs.viewport_background_theme": "თემის გრადიენტი", + "prefs.viewport_section_status": "ხედვის არეში ჭრილის სტატუსის ჩვენება", + "prefs.viewport_section_status_help": "ჭრილის პარამეტრის ჩვენება ხედვის არეში. Escape და ლენტის აქტიური ღილაკი მას გამორთავს. გამორთეთ ჭრილის წინა მართვის ელემენტების შესანარჩუნებლად.", + "prefs.viewport_status_details": "ხედვის არის ცოცხალი დეტალები", + "prefs.viewport_status_details_help": "აქტიური ანალიზისა და ჭრილის პარამეტრების რედაქტირება სტანდარტულ დეტალების ბარათებში. გამორთეთ ანალიზის მხოლოდ წასაკითხი ლეგენდებისა და ჭრილის დიალოგის აღსადგენად.", + "prefs.viewport_status_summary": "ხედვის არის სტატუსის ელემენტების დაკეცვა", + "prefs.viewport_status_summary_help": "ხედვის არის სამი ან მეტი სტატუსის ელემენტის ერთ შემაჯამებელ ნიშნაკში დაკეცვა. გამორთეთ ყველა ელემენტის სრულ რიგში შესანარჩუნებლად.", + "prefs.wheel": "ბორბალი", + "prefs.wheel_trackpad": "ბორბალი და სენსორული პანელი", + "prefs.workspace": "სამუშაო სივრცე", + "prefs.zoom_stop_at_model": "მასშტაბის შეჩერება მოდელთან", + "prefs.zoom_stop_at_model_tip": "3D მაუსი და მოწყობილობის აპი მასშტაბს ხედის შუაში მდებარე ზედაპირისკენ ცვლის; გადათრევით მასშტაბი ინარჩუნებს წერტილს, სადაც გადათრევა დაიწყო. გამორთული: მასშტაბს შეუძლია მოდელში გაიაროს. ბორბალი და თითების მოჭერა ცალკე იყენებს „მასშტაბს კურსორისკენ“", + "prefs.zoom_toward_cursor": "მასშტაბი, კურსორისკენ", + "properties.title": "თვისებები: {name}", + "recovery.days_ago": "{count} დღის წინ", + "recovery.detail": "{file} · ოპერაცია: {features} · ავტომატურად შენახულია {when}", + "recovery.discard_all": "ყველას გაუქმება", + "recovery.discard_all_detail": "ამის დაბრუნება შეუძლებელია.", + "recovery.discard_all_title": "გაუქმდეს ავტოშენახული ასლები: {count}?", + "recovery.discard_all_title_one": "გაუქმდეს 1 ავტოშენახული ასლი?", + "recovery.hours_ago": "{count} სთ-ის წინ", + "recovery.just_now": "ახლახან", + "recovery.min_ago": "{count} წთ-ის წინ", + "recovery.never_saved": "არასოდეს შენახულა", + "refused.change": "{body}-ის შეცვლა ვერ მოხერხდა.", + "refused.cut": "{body}-ის ამოჭრა ვერ მოხერხდა.", + "refused.face_curved": "მისი ერთ-ერთი მრუდე წახნაგი მოდელირებისთვის გამოუსადეგარია.", + "refused.face_flat": "მისი ერთ-ერთი ბრტყელი წახნაგი მოდელირებისთვის გამოუსადეგარია.", + "refused.face_freeform": "მისი ერთ-ერთი თავისუფალი ფორმის წახნაგი მოდელირებისთვის გამოუსადეგარია.", + "refused.face_rounded": "მისი ერთ-ერთი მომრგვალებული წახნაგი მოდელირებისთვის გამოუსადეგარია.", + "refused.faces_apart": "მისი წახნაგები მოდელირებისთვის საკმარისად მჭიდროდ არ ერთდება.", + "refused.intersect": "{body}-თან გადაკვეთა ვერ მოხერხდა.", + "refused.join": "{body}-თან შეერთება ვერ მოხერხდა.", + "refused.repair": "დეტალის შეკეთება", + "refused.show_face": "წახნაგის ჩვენება", + "render.adaptive_absolute": "RGB-ის აბსოლუტური ცდომილების ქვედა ზღვარი", + "render.adaptive_coverage": "დაფარვის ცდომილების მიზნობრივი მნიშვნელობა", + "render.adaptive_enable": "სემპლების განაწილება დამოუკიდებელი საცდელი სემპლებით", + "render.adaptive_help": "მხოლოდ GPU. დამოუკიდებელი საცდელი სემპლები უგულებელყოფილია, შემდეგ თითო პიქსელზე ნაწილდება 16 ან მეტი საბოლოო სემპლი „სემპლები პიქსელზე“ მნიშვნელობამდე. განაწილებას RGB-ისა და დაფარვის დისპერსია განსაზღვრავს; იშვიათი გზები შეიძლება გამოგრჩეს და ლიმიტამდე მისული პიქსელები შეიძლება ხმაურიანი დარჩეს. საბოლოო ანგარიში რეალურ სამუშაოს ითვლის. ხმაურის ან დროის სერტიფიცირებული გარანტია არ არის.", + "render.adaptive_minimum": "საბოლოო სემპლების მინიმუმი", + "render.adaptive_pending": "ხელმისაწვდომია GPU-ის ადაპტური განაწილება დამოუკიდებელი საცდელი სემპლებით და ფრენელის პირობითი სტრატები. სერტიფიცირებული კრებადობა, იშვიათი მოვლენების გარანტიები და CPU-ის ადაპტური ტრანსპორტი კვლავ მიუწვდომელია.", + "render.adaptive_pilots": "საცდელი სემპლები პიქსელზე", + "render.adaptive_relative": "RGB-ის ფარდობითი ცდომილების მიზნობრივი მნიშვნელობა", + "render.add_ground": "მორგებული იატაკის დამატება კომპოზიციაში", + "render.advanced_material_scope": "ხელმისაწვდომია ერთი სასრული ერთგვაროვანი GPU გარემო, მკაფიო შეზღუდვებით. სიმკვრივის ბადეები, მინისა და მოცულობის ჩადგმული კომბინაციები, ქვეზედაპირული ზედაპირები, ზედაპირის რელიეფური ცვლა, სპექტრული ტრანსპორტი და მიუბმელი გაფართოებული მასალის კონცეფციები კვლავ მიუწვდომელია.", + "render.aging_add": "დაძველების ფენის დამატება", + "render.aging_airborne": "ჰაერში შეწონილი მტვერი / მონაწილე გარემო", + "render.aging_airborne_help": "ჰაერში შეწონილი მტვერი ცალკე სასრული ერთგვაროვანი გამბნევი მოცულობაა. ის ცვლის ტრანსპორტს და დაუმუშავებელ EXR-ს და არა ზედაპირის დაძველების ფენებს. მოცულობის/მინის/ხმაურის მოცილების არსებული შეზღუდვები მკაფიოდ რჩება; ატმოსფერო ავტომატურად არ ემატება.", + "render.aging_all_bodies": "ყველა შესაბამისი გაუმჭვირვალე სხეული", + "render.aging_chips": "აქერცლილი საღებავი", + "render.aging_class_any": "გაუმჭვირვალე მასალის ყველა კლასი", + "render.aging_class_dielectric": "მხოლოდ არალითონური ზედაპირები", + "render.aging_class_metal": "მხოლოდ ლითონური ზედაპირები", + "render.aging_color": "ფენის ფერი · sRGB", + "render.aging_coverage": "დაფარვა", + "render.aging_dust": "დალექილი მტვერი", + "render.aging_empty": "დაძველების ფენები არ არის: საწყისი ზედაპირები უცვლელი რჩება.", + "render.aging_fading": "გახუნებული საფარი", + "render.aging_grime": "ჭუჭყი და ლაქები", + "render.aging_help": "გააერთიანეთ მაქსიმუმ რვა ოპტიკური ფენა, რიგის მიხედვით. ჟანგი და პატინა შექმნილი იერსახეებია და არა დაძველების/კოროზიის სიმულაცია. მასშტაბი სამყაროს მილიმეტრებშია. გეომეტრია, მასა და საინჟინრო თვისებები არ იცვლება; მინა და პასიური დეკორაციები გამორიცხულია.", + "render.aging_metallic": "ფენის მეტალურობის წილი", + "render.aging_origin": "ველის სათავე · სამყაროს mm", + "render.aging_patina": "სპილენძის მწვანე პატინა", + "render.aging_refresh_targets": "მიმდინარე სხეულების შემოწმება", + "render.aging_roughness": "ფენის უხეშობა", + "render.aging_rust": "დაჟანგული რკინა / ჟანგი", + "render.aging_scale": "პატერნის მასშტაბი", + "render.aging_scratches": "წვრილი ნაკაწრები", + "render.aging_target": "სამიზნე და კოორდინატები", + "render.aging_target_help": "დასახელებული სამიზნე კვლავ უნდა შეესაბამებოდეს თავის დაფიქსირებულ ინდექსსა და სახელს. გლობალური ნიღბები სამყაროსთან არის მიბმული; ისინი მოძრავ დეტალებს არ მიჰყვება. ეს არც ღრუების აღმოჩენაა და არც წიბოების ნამდვილი ცვეთა. დამატებით სხეულებამდე მისაღწევად სია გაფილტრეთ.", + "render.aging_target_search": "სხეულების სახელების ფილტრი", + "render.aging_upward": "ზემოთ მიმართულ ზედაპირებზე დალექვა", + "render.all_controls_help": "ყველა მიმდინარე მართვის ელემენტის მჭიდრო მიმოხილვა. განყოფილებების გვერდები ფოკუსირებულ რედაქტირებას იძლევა საბაზისო მოთხოვნის შეუცვლელად.", + "render.all_shots_label": "ყველა კადრი", + "render.appearance_editor.absorption": "შთანთქმა", + "render.appearance_editor.base_colour": "საბაზისო ფერი", + "render.appearance_editor.body_reason": "ოპტიკური მიბმები მთელ სხეულს ეხება. ამ მართვის ელემენტების შესაცვლელად აირჩიეთ „სხეული“.", + "render.appearance_editor.boundary": "საზღვარი", + "render.appearance_editor.box": "პარალელეპიპედი", + "render.appearance_editor.choose_image": "გამოსახულების არჩევა…", + "render.appearance_editor.closed": "დახურული მყარი სხეული", + "render.appearance_editor.coat": "გამჭვირვალე ლაქი", + "render.appearance_editor.cpu_reason": "საჭიროებს CPU-ით სხივების ტრასირებას.", + "render.appearance_editor.glass": "მინა და შთანთქმა", + "render.appearance_editor.glass_enable": "ამ სხეულზე ფიზიკური მინის გამოყენება", + "render.appearance_editor.glass_note": "დახურული მინა გეომეტრიულ მანძილს იყენებს. მას არ შეუძლია სხეულის გაზიარება გამჭვირვალე ლაქთან ან რუკებთან.", + "render.appearance_editor.gpu_reason": "საჭიროებს GPU-ით გზების ტრასირებას.", + "render.appearance_editor.ior": "IOR", + "render.appearance_editor.maps": "რუკები", + "render.appearance_editor.normal": "ნორმალი", + "render.appearance_editor.normal_strength": "ნორმალის სიძლიერე", + "render.appearance_editor.origin": "სათავე", + "render.appearance_editor.recipe": "რეცეპტი", + "render.appearance_editor.reflection_sampling": "სემპლირება ყველა ამრეკლი სხეულისთვის", + "render.appearance_editor.reflections": "ანარეკლები", + "render.appearance_editor.remove": "შენახულის წაშლა", + "render.appearance_editor.remove_note": "შენახული ოპტიკის წაშლა ამ კადრიდან. გეომეტრია და მინიჭებული იერსახეები შენარჩუნდება.", + "render.appearance_editor.remove_title": "წაიშალოს შენახული ოპტიკა?", + "render.appearance_editor.replace": "ამ სხეულის შენახული ოპტიკის ჩანაცვლება", + "render.appearance_editor.revalidate": "ამ სხეულის ხელახლა შემოწმება", + "render.appearance_editor.save": "ამ ოპტიკის შენახვა", + "render.appearance_editor.save_reason": "ამ ოპტიკის შენახვას მიმდინარე GPU სხეულზე ფიზიკური მინა სჭირდება. ლაქი და ლოკალური გამოსახულების რუკები დროებითი რჩება.", + "render.appearance_editor.saved": "შენახულია ამ კადრთან", + "render.appearance_editor.saved_state": "ეს ოპტიკა ამ კადრთან არის შენახული.", + "render.appearance_editor.scatter_reason": "შიდა გაბნევას დახურული მყარი სხეულის საზღვარი სჭირდება.", + "render.appearance_editor.temporary": "ეს ოპტიკა ამ ჩანართზე დროებითია. შეინახეთ, რომ კადრთან დარჩეს.", + "render.appearance_editor.thickness": "სისქე", + "render.appearance_editor.thickness_reason": "სისქე თხელ ფურცლებზე მოქმედებს; დახურული მინა გეომეტრიულ მანძილს იყენებს.", + "render.appearance_editor.thin": "თხელი ფურცელი", + "render.appearance_editor.u_repeat": "U გამეორება", + "render.appearance_editor.v_repeat": "V გამეორება", + "render.appearance_editor.v_up": "ტექსტურის V მიმართულია ზემოთ", + "render.appearance_editor.weight": "წილი", + "render.appearance_physics_separate": "ვიზუალური იერსახე არ ანიჭებს სიმკვრივეს, თერმულ მონაცემებს ან სხვა საინჟინრო თვისებებს.", + "render.appearances": "იერსახეები", + "render.assign_help": "დაწკაპეთ მონიშნულზე გამოსაყენებლად; გადაათრიეთ წინასწარი ნახვისთვის და ჩააგდეთ, ან დაწკაპეთ, როცა არაფერია მონიშნული, დასახატად.", + "render.availability_native": "ჩაშენებული კომპოზიცია; გამოყენებამდე გადახედეთ", + "render.availability_projection": "მხარდაჭერილი პროექცია; იხილეთ მოცულობა და გამოტოვებები", + "render.availability_reference": "საცნობარო მონაცემები; არა ავტომატური მინიჭება", + "render.backdrop_alpha_conflict": "აირჩიეთ ეს ფონი ან გამჭვირვალე PNG გამოტანა; რენდერერი არცერთ პარამეტრს ჩუმად არ უგულებელყოფს.", + "render.backdrop_enable": "მხოლოდ კამერის გრადიენტული ფონის გამოყენება", + "render.backdrop_first": "საწყისი / ცენტრის ფერი", + "render.backdrop_help": "ეკრანის სივრცის ეს ფონი არ ანათებს, ჩრდილს არ აგდებს, არ აირეკლება და რელიეფს არ წარმოადგენს. ის დაუმუშავებელ EXR-ში არ შედის. გეომეტრია, სინათლის წყაროები და HDR გარემო დამოუკიდებელი რჩება.", + "render.backdrop_horizontal": "ჰორიზონტალური გრადიენტი", + "render.backdrop_radial": "რადიალური გრადიენტი", + "render.backdrop_radius": "რადიუსი", + "render.backdrop_second": "საბოლოო / კიდის ფერი", + "render.backdrop_vertical": "ვერტიკალური გრადიენტი", + "render.backdrop_x": "ცენტრი X", + "render.backdrop_y": "ცენტრი Y", + "render.background": "სცენის ფონი", + "render.background_camera_section": "კამერის ფონი · PNG პრეზენტაცია", + "render.background_completed_frozen": "ნაჩვენები შედეგი გაყინული დასრულებული გამოსახულებაა. ფონის რედაქტირება ამ შედეგს ავტომატურად არ გადახატავს. მხოლოდ კამერის ცვლილებებისთვის გამოიყენეთ „ხელახალი კორექცია“, ახალი ფიზიკური დეკორაციისთვის კი „რენდერი“.", + "render.background_hdr_separate": "მიმდინარე HDR რესურსები ზედაპირებს ანათებს და მათზე აირეკლება; ისინი ობიექტის უკან პანორამად ავტომატურად არ ჩანს. გრადიენტის შეცვლა განათებას არ აბრუნებს და არ ცვლის მის ფერს.", + "render.background_lighting_section": "HDR განათება · კამერის ფონისგან დამოუკიდებლად", + "render.background_no_alpha_override": "კამერის ფონი გამჭვირვალე გამოტანას ჩუმად არ ემატება. დაუმუშავებელი მასტერის ხელახალი კორექცია დაფიქსირებულ დაფარვას იყენებს და ხმაურის მოცილებას ხელახლა არ ასრულებს; წყარო EXR უცვლელი რჩება.", + "render.background_not_light": "ფონის ფერი პრეზენტაციისთვისაა და არა დამატებითი სინათლის წყარო.", + "render.background_regrade": "შენახულ დაუმუშავებელ მასტერზე გამოყენება", + "render.background_stage_occlusion": "ეს კადრი ფიზიკური დეკორაციის გეომეტრიას შეიცავს. დიდმა იატაკმა ან კედელმა შეიძლება კადრი შეავსოს და მხოლოდ კამერის ფონი დამალოს. შეგნებულად გაასუფთავეთ ან შეცვალეთ დეკორაციის ზომა, ან შეცვალეთ მისი ფიზიკური არეკვლის უნარი. ხელახალი კორექცია დაფიქსირებულ გეომეტრიას ვერ წაშლის.", + "render.background_workflow": "აირჩიეთ სასურველი ფონი: მხოლოდ კამერის ფერი/გრადიენტი, ფიზიკური დეკორაცია, რომელიც სინათლეს იღებს, ან HDR განათება. ისინი დამოუკიდებელია. „ცოცხალი წინასწარი ნახვა“ მოდელირების ხედია; კამერის საბოლოო დამუშავების სანახავად დაარენდერეთ ახალი გამოსახულება ან ხელახლა გააკორექტირეთ შენახული მასტერი.", + "render.base_appearance": "სხეულის რედაქტირებადი იერსახე", + "render.base_apply": "სხეულის იერსახის გამოყენება", + "render.base_apply_help": "ერთი გაუქმებადი ვიზუალური მინიჭება გადახედულ კონკრეტულ სხეულზე. არსებული წახნაგების იერსახეები და საინჟინრო მასალები ცალკე რჩება.", + "render.base_color": "საბაზისო ფერი · sRGB", + "render.base_metallic": "მეტალურობის წილი", + "render.base_opaque_only": "ეს რედაქტორი სხეულის გაუმჭვირვალე სემანტიკას ინარჩუნებს. ოპტიკური გატარებისთვის გამოიყენეთ მინის მკაფიო მართვის ელემენტები.", + "render.batch_all_shots": "ყველა კადრი ({count})", + "render.batch_empty": "ყველა კადრის რენდერამდე შეინახეთ კადრი.", + "render.batch_limit": "ყველა კადრის რენდერი 32 კადრით შემოიფარგლება.", + "render.batch_status": "სრულდება: {running} · რიგში: {waiting}", + "render.bloom_enable": "ეკრანული ნათება", + "render.bloom_help": "შემოქმედებითი, მხოლოდ გამოტანის ნათება დადებითი წრფივი შუქებიდან, გაშლილი სამი ნორმალიზებული ყუთისებრი გავლით. რადიუსი გამოტანის პიქსელებშია. ემატება წრფივ ეკრანულ სინათლეში sRGB-მდე; ეს არ არის ლინზა, მოცულობითი ეფექტი ან კრებადობის გაუმჯობესება. დაუმუშავებელი EXR უცვლელია.", + "render.bloom_opaque": "ნათებას გაუმჭვირვალე გამოტანა სჭირდება. გამჭვირვალე PNG უარყოფილია და ჩუმად არ ბრტყელდება.", + "render.bloom_radius": "ნათების რადიუსი", + "render.bloom_strength": "ნათების სიძლიერე", + "render.bloom_threshold": "წრფივი შუქის ზღვარი", + "render.browse_capabilities": "შესაძლებლობების სრული კატალოგის დათვალიერება", + "render.browse_environments": "ორიგინალური HDR გარემოების დათვალიერება", + "render.browse_looks": "არჩევა…", + "render.browse_native_scenes": "ჩაშენებული სტუდიების დათვალიერება", + "render.browse_physical": "ფიზიკური ეტალონების დათვალიერება", + "render.browse_quality": "ხარისხის სპეციფიკაციების დათვალიერება", + "render.browse_rigs": "განათების სქემების დათვალიერება", + "render.browse_scene_specs": "სცენის გაფართოებული სპეციფიკაციების დათვალიერება", + "render.browse_surfaces": "შექმნილი ზედაპირების დათვალიერება", + "render.browser_library": "ბიბლიოთეკა", + "render.browser_model": "მოდელი", + "render.camera_distance": "მანძილი თვალიდან სამიზნემდე", + "render.camera_exact_help": "სამყაროს მილიმეტრები; კუთხეები ნაჩვენებია გრადუსებში და ინახება რადიანებში. ნავიგაცია იმავე კამერას იყენებს, რასაც ხედვის არე.", + "render.camera_fov": "ვერტიკალური ხედვის კუთხე", + "render.camera_pitch": "კამერის დახრილობა", + "render.camera_roll": "გორება", + "render.camera_set": "რენდერის კამერის დაყენება", + "render.camera_target": "სამიზნის პოზიცია · mm", + "render.camera_yaw": "აზიმუტი", + "render.category_metal": "ლითონი", + "render.category_paint": "საღებავი", + "render.category_plastic": "პლასტმასა", + "render.category_wood": "ხე-ტყე", + "render.check_opaque": "გამჭვირვალობა: მხოლოდ გაუმჭვირვალე ზედაპირები; ფონის ალფა მხარდაჭერილია.", + "render.check_sorted_alpha": "გამჭვირვალობა: დახარისხებული ალფას მიახლოება.", + "render.check_transmission": "გამჭვირვალობა: ფიზიკური გატარება.", + "render.children.absolute_floor": "აბსოლუტური ქვედა ზღვარი", + "render.children.adaptive": "ადაპტური", + "render.children.add_look_reason": "დაამატეთ სტილი, რომ შეცვალოთ მისი ჩართვა და სიძლიერე.", + "render.children.all_shots": "ყველა კადრი", + "render.children.bloom": "ნათება", + "render.children.check": "შემოწმება", + "render.children.check_now": "ახლავე შემოწმება", + "render.children.chromatic": "ქრომატული", + "render.children.compact": "კომპაქტური", + "render.children.contrast": "კონტრასტი", + "render.children.copy_image": "კოპირება", + "render.children.copy_job": "დავალების JSON-ის კოპირება", + "render.children.copy_request": "მოთხოვნის JSON-ის კოპირება", + "render.children.coverage_error": "დაფარვის ცდომილება", + "render.children.cpu": "CPU-ით სხივების ტრასირება", + "render.children.denoise": "დასრულებულ გამოსახულებაში ხმაურის შემცირება", + "render.children.depth": "გზის სიღრმე", + "render.children.distortion": "დეფორმაცია", + "render.children.edge_samples": "კიდის სემპლები", + "render.children.effects_banner": "ამ ეფექტებს GPU-ით გზების ტრასირება სჭირდება. ამის გახსნა მეთოდს არასოდეს ცვლის.", + "render.children.enable_adaptive": "ადაპტური ლიმიტების შესაცვლელად ჩართეთ დამოუკიდებელი საცდელი სემპლები.", + "render.children.enable_bloom": "სიძლიერის, ზღვრისა და რადიუსის შესაცვლელად ჩართეთ ნათება.", + "render.children.finishing": "საბოლოო დამუშავება", + "render.children.flare": "ანარეკლი", + "render.children.fresnel": "ფრენელის სტრატები", + "render.children.ghosts": "მოჩვენებითი რგოლები", + "render.children.glass": "მინაში გატარება", + "render.children.go_to": "გადასვლა: {editor}", + "render.children.grain": "მარცვლოვნება", + "render.children.halo": "შარავანდი", + "render.children.hdr": "HDR", + "render.children.keep_master": "დაუმუშავებელი წრფივი მასტერის შენარჩუნება", + "render.children.last_result": "ბოლო: {number} · {width} × {height} · {phase}", + "render.children.lens_effects": "ლინზის ეფექტები", + "render.children.look_summary": "{tone} · სტილი: {count}", + "render.children.looks": "შემოქმედებითი სტილები", + "render.children.memory": "მეხსიერება", + "render.children.method": "მეთოდი", + "render.children.minimum": "მინიმუმი", + "render.children.needs_cpu": "საჭიროებს CPU-ით სხივების ტრასირებას. ამის გახსნა მეთოდს არასოდეს ცვლის.", + "render.children.nested": "სერტიფიცირებული ჩადგმული დიელექტრიკები", + "render.children.not_checked": "არ შემოწმებულა", + "render.children.path": "გზების ტრასირება", + "render.children.pilots": "საცდელი სემპლები", + "render.children.preview": "წინასწარი ნახვის მონაცემები", + "render.children.progressive_reason": "სემპლების რაოდენობისა და საწყისი რიცხვის შესაცვლელად აირჩიეთ „პროგრესული“.", + "render.children.radius": "რადიუსი", + "render.children.reflect_depth": "არეკვლის სიღრმე", + "render.children.reflect_samples": "არეკვლის სემპლები", + "render.children.regrade": "ხელახალი კორექცია", + "render.children.relative_error": "ფარდობითი ცდომილება", + "render.children.render": "რენდერი", + "render.children.render_shot": "კადრის რენდერი", + "render.children.renderer": "რენდერერი", + "render.children.renderers": "რენდერერები", + "render.children.request": "ეს მოთხოვნა", + "render.children.reset_finishing": "საბოლოო დამუშავების ჩამოყრა", + "render.children.review_quality": "ხარისხის სპეციფიკაციის გადახედვა…", + "render.children.rgb_gain": "RGB გაძლიერება", + "render.children.samples": "სემპლები", + "render.children.sampling": "სემპლირება", + "render.children.saturation": "გაჯერება", + "render.children.scene_summary": "სხეული: {bodies} · სამკუთხედი: {triangles}", + "render.children.seed": "საწყისი რიცხვი", + "render.children.sharpening": "გამკვეთრება", + "render.children.single_image": "ერთი გამოსახულება", + "render.children.soft_focus": "რბილი ფოკუსი", + "render.children.streak": "სხივური ზოლი", + "render.children.strength": "სიძლიერე", + "render.children.studio": "სტუდია", + "render.children.threshold": "ზღვარი", + "render.children.tone": "ტონი", + "render.children.under_hood": "ტექნიკური დეტალები", + "render.children.vignette": "ვინიეტი", + "render.children.workstation": "სამუშაო სადგური", + "render.choose_look": "ჯერ აირჩიეთ იერსახე „იერსახეებში“", + "render.chromatic_offset": "კიდის ქრომატული წანაცვლება", + "render.clear_stage": "შენახული დეკორაციის წაშლა", + "render.compare_divider": "შედარების გამყოფი", + "render.compare_live": "ცოცხალი", + "render.compare_live_preview": "ცოცხალი წინასწარი ნახვა", + "render.compare_render": "რენდერი {number}", + "render.compare_side": "რენდერი {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} წმ · {renderer} · დაფიქსირდა რევიზიაზე {revision}", + "render.compare_swap": "გაცვლა", + "render.copy_request": "JSON-ის კოპირება", + "render.cpu_aa_help": "სივრცითი სემპლები: მეტი სემპლი აუმჯობესებს კიდეებს და ზრდის რენდერის დროს.", + "render.cpu_area_add": "მართკუთხა CPU სინათლის წყაროს დამატება", + "render.cpu_area_editor": "მართკუთხა CPU სინათლის წყაროები", + "render.cpu_area_editor_help": "გვერდების სრული ვექტორები მილიმეტრებში; U-ს ვექტორული ნამრავლი V-ზე მიმართულია გამომსხივებელი მხარისკენ. ეს განსხვავდება GPU-ის ნახევარგვერდის ვექტორებისგან.", + "render.cpu_area_full_u": "U გვერდი სრულად · mm", + "render.cpu_area_full_v": "V გვერდი სრულად · mm", + "render.cpu_area_samples": "ფართობული სინათლის სემპლები", + "render.cpu_binding_confirm": "ამ სხეულის დადასტურება", + "render.cpu_binding_stale": "სცენა შეიცვალა. რენდერამდე ეს არეკვლის სამიზნე ხელახლა დაადასტურეთ.", + "render.cpu_body_choose": "აირჩიეთ სხეული", + "render.cpu_body_filter": "სხეულების ფილტრი სახელით", + "render.cpu_body_filter_more": "მეტი სხეულის სანახავად დააზუსტეთ ფილტრი.", + "render.cpu_body_missing": "არეკვლის სამიზნე აკლია, დამალულია, ორაზროვანია ან მისი სახელი 128 ბაიტზე გრძელია. აირჩიეთ ხელახლა.", + "render.cpu_budget": "CPU-ის რესურსების პროფილი", + "render.cpu_budget_bodies": "სხეულების ზედა ზღვარი", + "render.cpu_budget_compact": "კომპაქტური (ძველი ლიმიტები)", + "render.cpu_budget_details": "რესურსების ლიმიტები", + "render.cpu_budget_help": "უფრო დიდი ლიმიტები აირჩიეთ ცალსახად. გარჩევადობა და სემპლები ავტომატურად არასოდეს მცირდება.", + "render.cpu_budget_memory": "ამოცანის მეხსიერების ზედა ზღვარი", + "render.cpu_budget_not_guarantee": "ეს დაშვების ზედა ზღვრებია და არა RAM-ის დაჯავშნა ან სიჩქარის გარანტია. გეომეტრია, ფირი და შენახული გადახედვები მეხსიერების საერთო ბიუჯეტს იყენებს; რენდერინგის გაუქმება ყოველთვის შეიძლება.", + "render.cpu_budget_resize": "მონახაზი აჭარბებს ამ CPU-პროფილს ან მისი კამერის სემპლების ბიუჯეტს. ცალსახად დაეთანხმეთ უფრო მცირე ზომებს ან აირჩიეთ უფრო დიდი პროფილი.", + "render.cpu_budget_studio": "სტუდია (დიდი გამოსახულებები)", + "render.cpu_budget_triangles": "სამკუთხედების ზედა ზღვარი", + "render.cpu_budget_workstation": "სამუშაო სადგური (მძიმე სცენები)", + "render.cpu_captured_hdr": "ამ გამოსახულებისთვის დაფიქსირებული HDR", + "render.cpu_check_capture_help": "„შემოწმება“ და „დაწყება“ ფაილის ერთსა და იმავე დაიჯესტს ამოწმებს ან ჩაშენებულ HDR-ს იყენებს. ყოველი გამოსახულება თავის დაფიქსირებულ წყაროს ინარჩუნებს.", + "render.cpu_check_changed": "ამ შემოწმების შემდეგ მართვის ელემენტები ან მოდელი შეიცვალა. რენდერინგამდე ხელახლა შეამოწმეთ.", + "render.cpu_constant_help": "მუდმივი ენერგეტიკული სიკაშკაშე ჩანს არეკლილი ან გამავალი სხივებისთვის. ის პირდაპირ დიფუზურ განათებას არ იძლევა.", + "render.cpu_custom_directions": "პრესეტის ჩანაცვლება მორგებული მიმართული სინათლეებით", + "render.cpu_direction": "მიმართულება სინათლისკენ (X, Y, Z)", + "render.cpu_directional": "მიმართული სინათლე", + "render.cpu_directional_add": "მიმართული სინათლის დამატება", + "render.cpu_environment": "CPU-ის გარემო", + "render.cpu_environment_background": "გამოსახულების ფონი გარემოს განათებისგან დამოუკიდებელი რჩება.", + "render.cpu_environment_bounds": "CPU-ის ინტენსივობა უნდა იყოს 0–64, HDR-ის შემობრუნება — სასრული, ±1,000,000 რადიანის ფარგლებში, ხოლო HDR-ის სემპლები — 1, 4, 16 ან 64.", + "render.cpu_environment_constant": "მუდმივი გარემო მეორადი სხივებისთვის", + "render.cpu_environment_none": "CPU-ის გარემოს გარეშე", + "render.cpu_environment_samples": "HDR-განათების სემპლები", + "render.cpu_exposure_help": "CPU-ის ექსპოზიცია უნდა იყოს −16-დან 16 EV-მდე. ამ დიაპაზონს გარეთ არსებული GPU-ის ექსპოზიცია შენარჩუნდება, სანამ არ შეცვლით.", + "render.cpu_fixed": "ერთი გამოსახულება", + "render.cpu_hdr_help": "Radiance .hdr, 2:1 პანორამა, 2048 × 1024-მდე და 16 MiB-მდე. CPU-ს სჭირდება ფაილში ცალსახად მითითებული sRGB/D65 ძირითადი ფერები; მიუთითებელი ძირითადი ფერები და EXR უარყოფილია.", + "render.cpu_hdr_reflection_help": "HDR-ის უხეში არეკვლები მოითხოვს სხეულისა და წახნაგის სრულად მეტალიკურ ზედაპირებს. შემოწმება მხარდაუჭერელ კომბინაციებს აჩვენებს.", + "render.cpu_key_rim": "მთავარი და კონტურული", + "render.cpu_last_check": "CPU-ის ბოლო შემოწმება", + "render.cpu_light_help": "რვამდე მიმართული სინათლე. ცარიელი მორგებული სია მათ გამორთავს; პრესეტის არჩევა მის სინათლეებს აღადგენს. ფერები წრფივ RGB-შია, ინტენსივობა კი ფარდობითია და არა ვატებში.", + "render.cpu_light_intensity": "ფარდობითი ინტენსივობა (0–64)", + "render.cpu_light_minimum": "შესუსტების მინიმალური მანძილი", + "render.cpu_light_position": "მსოფლიო პოზიცია (X, Y, Z)", + "render.cpu_light_reference": "ინტენსივობის საბაზო მანძილი", + "render.cpu_light_remove": "სინათლის წაშლა", + "render.cpu_lighting": "განათების პრესეტი", + "render.cpu_lights": "CPU-ის სინათლეები", + "render.cpu_linear_color": "წრფივი ფერი (R, G, B)", + "render.cpu_neutral": "ნეიტრალური", + "render.cpu_opaque_required": "CPU-ის სხივების მიდევნებას გაუმჭვირვალე ფონი სჭირდება. გასაგრძელებლად მოხსენით „გამჭვირვალე ფონი“.", + "render.cpu_options_pending": "ამ CPU-პანელს ჯერ არ შეუძლია გამოსხივების, ზედაპირის ეფექტების, მინის ან ანიზოტროპიის რედაქტირება. გამოყენებამდე გაასუფთავეთ API-ის ეს ოფციები.", + "render.cpu_point": "წერტილოვანი სინათლე", + "render.cpu_point_add": "წერტილოვანი სინათლის დამატება", + "render.cpu_point_help": "რვამდე წერტილოვანი სინათლე, რომლებიც არჩეულ მიმართულ განათებას ემატება. მანძილები mm-შია; მინიმალური არ უნდა აღემატებოდეს საბაზო მანძილს.", + "render.cpu_primary_samples": "კიდის სემპლები პიქსელზე", + "render.cpu_progressive": "CPU პროგრესული", + "render.cpu_progressive_help": "CPU-ის არსებული ინტეგრატორის დაგროვება გავლებით, თითო პირველადი სემპლით. არჩეულ არეკვლებს ერთი სემპლი სჭირდება; ფართობულ სინათლეებს, დიელექტრიკებსა და ანიზოტროპიას — „ერთი გამოსახულება“.", + "render.cpu_progressive_limits": "მაქსიმუმ 1,048,576 პიქსელი და 16,777,216 პიქსელი × სემპლის შეფასება. სემპლების შეცვლა გამოსახულების ზომას ავტომატურად არასოდეს ცვლის.", + "render.cpu_progressive_seed": "CPU-ის სემპლინგის საწყისი რიცხვი", + "render.cpu_progressive_spp": "სემპლი პიქსელზე", + "render.cpu_reflection_add": "უხეში არეკვლის დამატება", + "render.cpu_reflection_depth": "არეკვლის სიღრმე (1–8)", + "render.cpu_reflection_empty": "სხეულები არჩეული არ არის: სცენის არეკვლები გამორთულია.", + "render.cpu_reflection_help": "აირჩიეთ სხეულები და დააყენეთ „გამორთული“, „სარკისებრი“ ან „უხეში“. „უხეში“ მინიჭებული ზედაპირის უხეშობას იყენებს. მეტი სემპლი და ასხლეტა დროს ზრდის; ეს შეზღუდული სარკისებრი გადატანაა და არა გლობალური განათება.", + "render.cpu_reflection_limit": "მხარდაჭერილია 64-მდე ამრეკლი სხეული.", + "render.cpu_reflection_mirror": "სარკისებრი", + "render.cpu_reflection_off": "გამორთული", + "render.cpu_reflection_rough": "უხეში", + "render.cpu_reflection_samples": "არეკვლის სემპლები (1–64)", + "render.cpu_reflections": "CPU-ის არეკვლები", + "render.cpu_runtime_help": "სინათლისა და გარემოს რიცხვითი პარამეტრები კონფიგურაციასთან ერთად ინახება. სხეულების არეკვლები და HDR-ფაილები დროებითი რჩება. ფართობული სინათლისა და პროჟექტორის კონუსის არსებული მნიშვნელობები შენარჩუნდება.", + "render.cpu_sampling_mode": "CPU-ის სემპლინგის რეჟიმი", + "render.cpu_shadows": "ჩრდილების დაყრა", + "render.cpu_summary": "CPU-ის სხივების მიდევნება · არეკვლები · HDR · მიმართული და წერტილოვანი სინათლეები", + "render.cpu_warm_cool": "თბილი და ცივი", + "render.diag_bodies": "ხილული სხეულები", + "render.diag_job_details": "დაფიქსირებული ამოცანის დეტალები", + "render.diag_last_check": "ბოლო წინასწარი შემოწმება", + "render.diag_memory": "დაშვების ლოგიკური შეფასება", + "render.diag_not_implemented": "შესაძლებლობების ცალსახა საზღვრები", + "render.diag_preflight_details": "წინასწარი შემოწმების დეტალები", + "render.diag_request": "ზუსტი მიმდინარე მოთხოვნა", + "render.diag_triangles": "სამკუთხედები", + "render.discard_continue": "მონახაზის გაუქმება და გაგრძელება", + "render.draft_confirm_help": "რენდერის მიმდინარე მონახაზს გამოუყენებელი ცვლილებები აქვს. გადართვამდე შეინახეთ ისინი, ცალსახად გააუქმეთ ან განაგრძეთ რედაქტირება.", + "render.draft_confirm_title": "რენდერის შეცვლილი პარამეტრების შენარჩუნება", + "render.effects_gpu_only": "ამ ეფექტებს GPU-ის ტრაექტორიების მიდევნება სჭირდება. გვერდის შეცვლა რენდერერს ავტომატურად არასოდეს გადართავს.", + "render.effects_help": "მოწესრიგებული ფერის ვიზუალური სტილებისა და გამოსახულების სივრცის ობიექტივის ეფექტების კომბინირება. რენდერინგი და დაუმუშავებელი მასტერის ხელახალი ფერკორექცია ერთსა და იმავე შენახულ პარამეტრებს იყენებს. დაუმუშავებელი EXR უცვლელი რჩება. ეს ორიგინალური მხატვრული მართვის ელემენტებია და არა დაკალიბრებული ობიექტივის ან ბრენდირებული ფირის ემულაცია.", + "render.effects_reset_lens": "ობიექტივის ეფექტების ჩამოყრა", + "render.effects_seed": "ნიმუშის საწყისი რიცხვი", + "render.emitted_axis": "გამოსხივების ღერძი", + "render.env_advanced": "დამატებითი", + "render.env_backdrop": "ფონი", + "render.env_backdrop_pending": "გარემოს ხილვადობასა და ფონის გაბუნდოვნებას რენდერერი ჯერ არ უჭერს მხარს.", + "render.env_blur": "გაბუნდოვნება", + "render.env_change": "შეცვლა", + "render.env_choose_source": "განათების რედაქტირებამდე აირჩიეთ გარემო სტუდიებსა და გარემოებში.", + "render.env_clear": "გასუფთავება", + "render.env_colour": "ფერი", + "render.env_environments": "გარემოები", + "render.env_ground": "მიწა", + "render.env_ground_pending": "ფიზიკური მიწა ჩრდილებს სასრული დიფუზური ზედაპირის სახით იღებს. მხოლოდ ჩრდილების დაჭერა და მიწის არეკვლები ჯერ მხარდაჭერილი არ არის.", + "render.env_intensity": "ინტენსივობა", + "render.env_invalid_edit": "გარემოს არასწორი ცვლილება.", + "render.env_physical_ground": "ფიზიკური მიწა", + "render.env_preview_help": "საილუსტრაციო სფეროს ნიმუში; არჩეული გარემოს გადახედვა არ არის.", + "render.env_reflection": "არეკვლა", + "render.env_ring_help": "განათების შესაბრუნებლად გადაათრიეთ რგოლი. 15°-ზე მისაბმელად დააჭირეთ Shift-ს.", + "render.env_rotate": "შემობრუნება", + "render.env_set": "რენდერის გარემოს დაყენება", + "render.env_shadow_catcher": "ჩრდილის დამჭერი", + "render.env_show_environment": "გარემოს ჩვენება", + "render.env_source": "წყარო", + "render.env_stage_details": "მიწის ცვლილებებს სხივების მიდევნება და მიწის ერთი პანელი სჭირდება. დეკორაციის სხვა პანელების რედაქტირებისთვის გამოიყენეთ „სცენა“.", + "render.env_studios": "სტუდიები", + "render.environment.albedo": "ალბედო", + "render.environment.atmosphere": "ატმოსფერო", + "render.environment.backdrop_note": "ფონს მხოლოდ კამერა ხედავს. ის არასოდეს ანათებს, ჩრდილს არ აყრის, არ აირეკლება და გამჭვირვალე გამოტანისას უარყოფილია.", + "render.environment.blur_pending": "გაბუნდოვნება მიუწვდომელია: რენდერერს ფონის გაბუნდოვნების პარამეტრი არ აქვს.", + "render.environment.builtin": "ჩაშენებული HDR", + "render.environment.check": "ფაილის შემოწმება", + "render.environment.checked": "HDR-ფაილი შემოწმებულია. შენახვისას ეს ბაიტები ჩაიშენება.", + "render.environment.choose": "HDR-ის არჩევა…", + "render.environment.constant": "მუდმივი", + "render.environment.cyclorama": "ციკლორამა", + "render.environment.embedded": "შენახულია ამ პროექტში", + "render.environment.end": "ბოლო", + "render.environment.extinction": "ექსტინქცია", + "render.environment.file": "ფაილი", + "render.environment.fit": "მიწის მორგება და შენახვა", + "render.environment.floor_wall": "იატაკი და კედელი", + "render.environment.gap": "დაშორების ღრეჩო", + "render.environment.gradient": "გრადიენტი", + "render.environment.gradient_gpu": "გრადიენტულ ფონს GPU-ის ტრაექტორიების მიდევნება სჭირდება.", + "render.environment.ground": "მიწა და დეკორაცია", + "render.environment.hdr": "HDR", + "render.environment.hdr_file": "HDR-ფაილი", + "render.environment.horizon": "ჰორიზონტი", + "render.environment.horizontal": "ჰორიზონტალური", + "render.environment.keep": "შენარჩუნება", + "render.environment.lighting_samples": "განათების სემპლები", + "render.environment.margin": "საზღვრების მარაგი", + "render.environment.max": "მაქსიმალური საზღვრები", + "render.environment.medium": "მოცულობითი გარემო", + "render.environment.min": "მინიმალური საზღვრები", + "render.environment.mode": "რეჟიმი", + "render.environment.needs_gpu": "სჭირდება GPU-ის ტრაექტორიების მიდევნება.", + "render.environment.none": "არცერთი", + "render.environment.orientation": "ორიენტაცია და სიძლიერე", + "render.environment.phase": "ფაზა", + "render.environment.primaries": "მიუთითებელი ძირითადი ფერების წრფივ sRGB-ად მიჩნევა", + "render.environment.primaries_gpu": "მიუთითებელი ძირითადი ფერების ინტერპრეტაციას GPU-ის ტრაექტორიების მიდევნება სჭირდება.", + "render.environment.radial": "რადიალური", + "render.environment.radial_only": "ცენტრი და რადიუსი რადიალურ რეჟიმს ეხება.", + "render.environment.reflectance": "არეკვლის უნარი", + "render.environment.remove": "დეკორაციის წაშლა", + "render.environment.remove_confirm": "წაიშალოს შენახული დეკორაცია?", + "render.environment.remove_note": "ამ კადრიდან შლის პასიურ პანელებს (რაოდენობა: {count}). კამერის ფონი რჩება.", + "render.environment.replace": "არსებული დეკორაციის ჩანაცვლების დადასტურება", + "render.environment.rotation_hdr": "CPU-ის სხივების მიდევნებისას შემობრუნებას HDR-წყარო სჭირდება.", + "render.environment.samples_cpu": "განათების სემპლებს GPU-ის ტრაექტორიების მიდევნების ბიუჯეტი ადგენს; ამ პარამეტრს CPU-ის სხივების მიდევნება სჭირდება.", + "render.environment.saved_panels": "შენახული პანელები: {count}", + "render.environment.sky_ground": "მიწა", + "render.environment.sky_note": "ცის ორიგინალური გრადიენტი განათებისთვის; დაკალიბრებული ატმოსფერო არ არის.", + "render.environment.source_raytrace": "გარემოს წყაროებს CPU-ის ან GPU-ის სხივების მიდევნება სჭირდება.", + "render.environment.stage_raytrace": "ფიზიკურ დეკორაციებს CPU-ის ან GPU-ის სხივების მიდევნება სჭირდება.", + "render.environment.start": "დასაწყისი", + "render.environment.vertical": "ვერტიკალური", + "render.environment.world": "მსოფლიო", + "render.environment.world_pending": "მსოფლიოს ფონი მიუწვდომელია: გარემოს კამერისთვის ხილვადობას ჯერ შენახული პარამეტრი არ აქვს.", + "render.environment.zenith": "ზენიტი", + "render.environment_tiles_require_raytrace": "გარემოებს CPU-ის ან GPU-ის სხივების მიდევნება სჭირდება. აირჩიეთ ის გამოტანის რედაქტორში.", + "render.error_area_samples": "area_samples უნდა იყოს 1, 4, 16 ან 64", + "render.error_binding_allocation": "მასალის მიბმის დაჯავშნა ვერ მოხერხდა", + "render.error_body_bound": "პროდუქტის გადახედვა აჭარბებს დაფიქსირებული სხეულების ზღვარს", + "render.error_checkpoint_dimensions": "საკონტროლო წერტილის ზომები დაფიქსირებული მოთხოვნისგან განსხვავდება", + "render.error_decode_budget": "გამოსახულების დეკოდირების ბიუჯეტი გადაივსო", + "render.error_denoise_setting": "ხმაურის მოცილების ნატიური პარამეტრი არასწორია", + "render.error_display_dimensions": "გამოსახულების ჩვენების ზომები არასწორია", + "render.error_display_fit": "გამოსახულების ჩვენება ამ მოწყობილობაზე ვერ ეტევა", + "render.error_display_height": "ჩვენების სიმაღლე გადაივსო", + "render.error_display_width": "ჩვენების სიგანე გადაივსო", + "render.error_duplicate_face": "პროდუქტის წახნაგის იერსახე დუბლირებულია", + "render.error_export_document": "რენდერის ექსპორტის დოკუმენტი შეიცვალა დანიშნულების ადგილის არჩევისას", + "render.error_face_cap": "პროდუქტის გადახედვა აჭარბებს წახნაგების იერსახეების დაშვების ზღვარს", + "render.error_finish_gesture": "გადახედვამდე დაასრულეთ მოდელირების ჟესტი", + "render.error_finish_operation": "რენდერზე გადასვლამდე დაასრულეთ მოდელირების მიმდინარე ოპერაცია", + "render.error_fixed_preview": "სტუდიის ფიქსირებულ გადახედვას სჭირდება ექსპოზიცია 0, გარემოს შემობრუნება 0 და ინტენსივობა 1", + "render.error_geometry_size": "პროდუქტის გეომეტრიის ზომა გადაივსო", + "render.error_glass_recipe": "მინის უცნობი რეცეპტი", + "render.error_gpu_preview": "პროდუქტის GPU-გადახედვა ამ ჰოსტზე მიუწვდომელია. შენახული კონფიგურაციები ხელმისაწვდომი რჩება.", + "render.error_gpu_samples": "GPU-ის სემპლების მხარდაუჭერელი რაოდენობა", + "render.error_image_dimensions": "რენდერის გამოსახულების ზომები მის ამოცანას არ ემთხვევა", + "render.error_image_profile": "რენდერის გამოსახულება აჭარბებს დაფიქსირებულ რესურსების პროფილს", + "render.error_interactive_command": "რენდერის ინტერაქტიული ბრძანება მიბმული არ არის", + "render.error_job_action": "ეს გამოსახულების ამოცანის ინტერაქტიული მოქმედება არ არის", + "render.error_job_identity": "რენდერის ამოცანის არასწორი იდენტიფიკატორი: {error}", + "render.error_library_reply": "რენდერის ბიბლიოთეკის არასწორი პასუხი", + "render.error_material_binding": "მასალის მიბმა აკლია", + "render.error_no_completed_image": "რენდერს დასრულებული გამოსახულება არ აქვს", + "render.error_no_geometry": "პროდუქტის გეომეტრია არ არის", + "render.error_no_scene": "პროდუქტის სცენა არ არის", + "render.error_opacity": "პროდუქტის იერსახის არასწორი გაუმჭვირვალობა", + "render.error_pbr_opacity": "გაუმჭვირვალე PBR-ს სჭირდება გაუმჭვირვალობა 1", + "render.error_physical_glass": "არჩეული რეცეპტი ფიზიკური მინა არ არის", + "render.error_preview_device": "პროდუქტის გადახედვას სჭირდება დაყენებული მოწყობილობა სიღრმის ბუფერით", + "render.error_product_triangle": "პროდუქტის არასწორი სამკუთხედი", + "render.error_provisional_identity": "რენდერის დროებითი იდენტიფიკატორი ან სემპლების რაოდენობა არასწორია", + "render.error_quality_bounds": "ხარისხის პროექცია აჭარბებს ნატიურ საზღვრებს", + "render.error_quality_method": "ხარისხის პროექციას სჭირდება იგივე ცალსახა GPU-მეთოდი", + "render.error_quality_projection": "ხარისხის ნატიური პროექცია არასწორია", + "render.error_regrade_identity": "ხელახალი ფერკორექციის არასწორი იდენტიფიკატორი: {error}", + "render.error_scene_bodies": "რენდერის სცენის სხეულები აკლია", + "render.error_scene_body_limit": "რენდერის სცენა აჭარბებს სხეულების ლიმიტს", + "render.error_scene_identity": "რენდერის სცენის არასწორი იდენტიფიკატორი", + "render.error_setup_panicked": "GPU-ის ტრაექტორიების მიდევნების მომზადება ავარიულად შეწყდა", + "render.error_setup_stopped": "მომზადების პროცესი ჰოსტის დაბრუნების გარეშე შეჩერდა", + "render.error_setup_worker": "მომზადების პროცესის გაშვება ვერ მოხერხდა: {error}", + "render.error_source_preview": "წყაროს გადახედვა აჭარბებს ბაიტების ზღვარს", + "render.error_surface_normals": "PBR-ს სჭირდება ზედაპირის არანულოვანი ნორმალები", + "render.error_surface_reply": "ავტორის ზედაპირის არასწორი პასუხი", + "render.error_triangle_bound": "პროდუქტის გადახედვა აჭარბებს წყაროს რვამილიონსამკუთხედიან ზღვარს", + "render.error_triangle_count": "პროდუქტის სამკუთხედების რაოდენობა გადაივსო", + "render.error_upload_slot": "პროდუქტის გადახედვის ატვირთვის სლოტი მიუწვდომელია", + "render.error_vertex_allocation": "პროდუქტის გადახედვისთვის წვეროების გამოყოფა ვერ მოხერხდა", + "render.error_vertex_envelope": "პროდუქტის გადახედვა აჭარბებს წვეროების მონაცემების {limit} MiB-იან ზღვარს; გეომეტრია არ გამარტივებულა", + "render.error_vertex_packing": "პროდუქტის გადახედვის შეფუთვა დაშვებული წვეროების მონაცემებისგან განსხვავდება", + "render.error_visible_solid": "აქ გადასახედად დიზაინში შექმენით ხილული მყარი სხეული.", + "render.exit_focus": "ფოკუსიდან გამოსვლა", + "render.export_display": "ექსპორტი: საჩვენებელი PNG", + "render.export_image_label": "გამოსახულების ექსპორტი", + "render.export_linear": "ექსპორტი: დაუმუშავებელი წრფივი EXR", + "render.exr_pending": "GPU-ს შეუძლია დაუმუშავებელი წრფივი EXR-ის შენარჩუნება. შეკუმშვა, მრავალშრიანი გამოსახულებები და რენდერის დამხმარე გავლები ჯერ მიუწვდომელია.", + "render.film_grain": "ფოტოგრაფიული მარცვლოვნება", + "render.fit": "პროდუქტის ჩატევა", + "render.fixed_camera": "კამერა", + "render.fixed_world": "მსოფლიო", + "render.flare_ghosts": "ანარეკლის რგოლები ყოველ წყაროზე", + "render.flare_halo": "ანარეკლის შარავანდი", + "render.flare_streak": "ანამორფული ზოლი", + "render.flare_strength": "ნათელი ადგილების ანარეკლის სიძლიერე", + "render.flare_threshold": "ანარეკლის ზღვარი სცენის წრფივ სივრცეში", + "render.fold_browser": "მოდელის ხის აკეცვა", + "render.frame_aspect": "თანაფარდობა", + "render.frame_centre_mark": "ცენტრის ნიშანი", + "render.frame_copy_limit": "კადრის დუბლიკატისთვის თავისუფალი სახელი არ არის", + "render.frame_copy_name": "{name} ასლი {number}", + "render.frame_custom": "მორგებული", + "render.frame_distance_unit": " × ზომა", + "render.frame_duplicate": "დუბლირება", + "render.frame_exposure": "ექსპოზიცია", + "render.frame_fov": "ხედვის კუთხე", + "render.frame_guides": "დამხმარე ხაზები", + "render.frame_invalid_aspect": "თანაფარდობის არასწორი პრესეტი", + "render.frame_lens": "ხედვის კუთხე {fov}° · ≈ {mm} mm", + "render.frame_name": "სახელი", + "render.frame_output_size": "გამოტანის ზომა", + "render.frame_photo": "3:2 · ფოტო", + "render.frame_portrait": "4:5 · პორტრეტი", + "render.frame_presets": "კადრის პრესეტები", + "render.frame_presets_pending": "გამოჩნდება კადრის რედაქტორთან ერთად", + "render.frame_projection": "პროექცია", + "render.frame_render_shot": "ამ კადრის რენდერი", + "render.frame_rule_thirds": "მესამედების წესი", + "render.frame_safe_area": "უსაფრთხო არე", + "render.frame_shot_title": "კადრი · {name}", + "render.frame_square": "1:1 · კვადრატი", + "render.frame_tall": "9:16 · ვერტიკალური", + "render.frame_thirds": "მესამედები", + "render.frame_wide": "16:9 · ფართოეკრანიანი", + "render.gpu_depth": "ტრაექტორიის მაქსიმალური სიღრმე", + "render.gpu_options_help": "სემპლები, სიღრმე, საწყისი რიცხვი და ექსპოზიცია ამ კონფიგურაციასთან ერთად ინახება. ინახება მხოლოდ აქტიური გამოსახულების მეთოდი.", + "render.gpu_path_failed": "GPU-ის ტრაექტორიების მიდევნება მიუწვდომელია", + "render.gpu_path_first_setup": "ამ GPU-ზე პირველ მომზადებას რამდენიმე წუთი შეიძლება დასჭირდეს; ამასობაში SolidCraft-ით სარგებლობა შეგიძლიათ. შემდგომი გაშვებები კომპილირებულ შეიდერებს ხელახლა იყენებს, თუ დრაივერი მათ ინახავს.", + "render.gpu_path_preparing": "GPU-ის ტრაექტორიების მიდევნება: შეიდერების კომპილაცია…", + "render.gpu_seed": "შემთხვევითობის საწყისი რიცხვი", + "render.gpu_unavailable": "GPU-ის ტრაექტორიების მიდევნება ამ მოწყობილობაზე მზად არ არის.", + "render.ground_apply": "მიწის მორგება და შენახვა", + "render.ground_gap": "დაშორების ცალსახა ღრეჩო", + "render.ground_linear_rgb": "დიფუზური არეკვლის უნარი · წრფივი RGB", + "render.ground_margin": "მიწის საზღვრების მარაგი", + "render.hdr_details": "HDR-წყაროს დეტალები", + "render.hdr_embedded": "HDR შენახულია ამ პროექტში", + "render.hdr_embedded_help": "რენდერინგი პროექტში ჩართულ ბაიტებს იყენებს; საწყისი ფაილი აღარ არის საჭირო.", + "render.hdr_file_captured": "HDR-ფაილი შემოწმებულია. შენახვისას ეს ბაიტები ჩაიშენება; თუ ფაილი შეიცვლება, ცალსახად ხელახლა შეამოწმეთ.", + "render.hdr_inspect": "HDR-ფაილის შემოწმება", + "render.hdr_inspect_required": "შენახვამდე ან რენდერინგამდე აირჩიეთ და შეამოწმეთ HDR-ფაილი.", + "render.hdr_primaries_declared": "წყარო თავის ძირითად ფერებს მიუთითებს.", + "render.hdr_primaries_srgb": "ძირითადი ფერები: sRGB/D65", + "render.hdr_primaries_undeclared": "წყარო ძირითად ფერებს არ მიუთითებს; გადახედეთ რენდერერის ფერის მოთხოვნებს.", + "render.hdr_resource_missing": "ამ პროექტს შენახული HDR-რესურსი აკლია.", + "render.heading_batch": "პაკეტური დამუშავება", + "render.heading_frame": "ჩარჩო", + "render.heading_lens": "ობიექტივი", + "render.heading_results": "შედეგები", + "render.heading_shots": "კადრები", + "render.hide_shots_label": "კადრების ზოლის დამალვა", + "render.hover_look": "{object} · {look} · დაწკაპეთ ასარჩევად", + "render.image_advanced": "GPU-ის დამატებითი პარამეტრები", + "render.image_cancelled": "რენდერი გაუქმდა", + "render.image_cancelling": "უქმდება", + "render.image_completed": "გამოსახულება ექსპორტისთვის მზადაა", + "render.image_encoding": "PNG-ის კოდირება", + "render.image_export": "დასრულებული გამოსახულების ექსპორტი", + "render.image_exposure": "ექსპოზიცია", + "render.image_failed": "რენდერი ვერ შესრულდა", + "render.image_height": "სიმაღლე", + "render.image_help": "CPU-ის გადახედვის გამოსახულება · PNG · მიახლოებითი გამჭვირვალობა", + "render.image_host_missing": "გამოსახულების ჰოსტი დაყენებული არ არის.", + "render.image_method": "გამოსახულების მეთოდი", + "render.image_overwrite": "არსებული ფაილის ჩანაცვლება", + "render.image_preparing": "გამოსახულება მზადდება", + "render.image_progressive": "პროგრესული რენდერინგი", + "render.image_queued": "რენდერის მოლოდინში", + "render.image_reduce": "სცადეთ უფრო მცირე გამოსახულება ან უფრო მარტივი სცენა.", + "render.image_running": "გამოსახულების რენდერინგი", + "render.image_samples": "სემპლები პიქსელზე", + "render.image_scene_stale": "გამოსახულების შემოწმებამდე ან დაწყებამდე დაასრულეთ მოდელირების ჟესტი ან განაახლეთ სცენა.", + "render.image_stale": "ეს გამოსახულება შემდგომ ცვლილებებამდე დაფიქსირებულ სცენას იყენებს.", + "render.image_start": "რენდერის დაწყება", + "render.image_supported": "რენდერის მოთხოვნა მხარდაჭერილია; რიგი და მეხსიერების ფონდი დაწყებისას ხელახლა შემოწმდება.", + "render.image_title": "გამოსახულების რენდერი", + "render.image_too_large": "გამოსახულების ლიმიტი გადაჭარბებულია: თითო მხარეზე 4096 პიქსელი და სულ 4,194,304 პიქსელი.", + "render.image_transparent": "გამჭვირვალე ფონი", + "render.image_unknown": "რენდერის მდგომარეობა მიუწვდომელია", + "render.image_use_largest": "ამ თანაფარდობით უდიდესი ზომის გამოყენება:", + "render.image_width": "სიგანე", + "render.include_rig_cards": "პასიური ამრეკლებისა და ფარების ჩართვა", + "render.inner_half_angle": "შიდა ნახევარკუთხე", + "render.inspect_scene": "დაფიქსირებული სცენის შეჯამების განახლება", + "render.inspector": "ინსპექტორი", + "render.inspector_advanced": "დამატებითი", + "render.inspector_all_users": "ყველა ობიექტი ({count})", + "render.inspector_applies_to": "ეხება", + "render.inspector_both_users": "ორივე ობიექტი", + "render.inspector_chain": "საიდან მოდის ეს ვიზუალური სტილი", + "render.inspector_colour": "ფერი", + "render.inspector_edit": "რედაქტირება", + "render.inspector_finish": "ზედაპირის დამუშავება", + "render.inspector_from_material": "მასალიდან", + "render.inspector_gloss": "სიპრიალე", + "render.inspector_material": "მასალა", + "render.inspector_matte": "მატი", + "render.inspector_metal": "ლითონი", + "render.inspector_opacity": "გაუმჭვირვალობა", + "render.inspector_opaque_help": "ზედაპირის დამუშავებისა და ოპტიკის ველები გაუმჭვირვალე PBR-ს იყენებს (გაუმჭვირვალობა 1). უფრო დაბალი გაუმჭვირვალობა სკალარულ დაჩრდილვას იყენებს.", + "render.inspector_pick_target": "მისი იერსახის შესამოწმებლად აირჩიეთ ამ ტიპის სამიზნე.", + "render.inspector_remove": "გადაფარვის მოხსნა", + "render.inspector_replace": "ჩანაცვლება…", + "render.inspector_reset": "ჩამოყრა", + "render.inspector_satin": "ატლასი", + "render.inspector_save_library": "ბიბლიოთეკაში შენახვა…", + "render.inspector_set_all": "შერეული იერსახეები. რედაქტირება ვიზუალურ სტილს ყველა არჩეულ სამიზნეზე დააყენებს.", + "render.inspector_soon": "მალე", + "render.inspector_target_limit": "იერსახეების შესამოწმებლად აირჩიეთ არაუმეტეს 10000 სამიზნისა.", + "render.inspector_textures": "ტექსტურები", + "render.inspector_this_body": "ეს სხეული", + "render.inspector_this_component": "ეს კომპონენტი", + "render.inspector_this_face": "ეს წახნაგი", + "render.inspector_this_target": "ეს სამიზნე", + "render.inspector_used_by": "გამოიყენება: {count}", + "render.keep_editing": "რედაქტირების გაგრძელება", + "render.layer_down": "ჩამოწევა", + "render.layer_enabled": "შრე ჩართულია", + "render.layer_off_suffix": " (გამორთული)", + "render.layer_remove": "შრის წაშლა", + "render.layer_strength": "შრის სიძლიერე", + "render.layer_up": "აწევა", + "render.lens_effects_help": "ანარეკლი რეალურ წრფივ გამოსახულებაში ოთხამდე განცალკევებულ ნათელ წყაროს იყენებს. ანარეკლის რგოლები, შარავანდი, ზოლები, ქრომატული წანაცვლებები და რადიალური დამახინჯება გამოსახულების სივრცის მხატვრული მიახლოებებია. სივრცულ ეფექტებს გაუმჭვირვალე გამოტანა სჭირდება; გარეთა სემპლები გამოსახულების კიდეს აგრძელებს. მარცვლოვნება დეტერმინისტულია. ფიზიკა, EXR ან გეომეტრია არ იცვლება.", + "render.lens_effects_title": "ობიექტივით შთაგონებული და ფოტოგრაფიული", + "render.library_all": "კატალოგი", + "render.library_all_states": "ხელმისაწვდომობის ყველა მდგომარეობა", + "render.library_appearance_available": "ხელმისაწვდომი იერსახე", + "render.library_applicable": "გამოსაყენებელი რესურსები", + "render.library_applied": "რესურსის პროექცია გამოყენებულია. დაწყებამდე შეამოწმეთ რენდერის სრული მოთხოვნა.", + "render.library_apply_appearance": "იერსახის გამოყენება", + "render.library_apply_hdr": "შენახვა ამ HDR-გარემოთი", + "render.library_apply_hint": "დაწკაპეთ გამოსაყენებლად · გადაათრიეთ მოდელზე", + "render.library_apply_maps": "ავტორის GPU-ზედაპირის რუკების გამოყენება", + "render.library_apply_studio": "ავტორის სტუდიის პროექციის შენახვა", + "render.library_apply_uniform": "ერთგვაროვანი გაუმჭვირვალე იერსახის გამოყენება", + "render.library_authored_help": "ავტორის ორიგინალური რესურსები საილუსტრაციოა და არა გაზომილი საინჟინრო მონაცემები. ყოველი მოქმედება მხოლოდ მის მითითებულ პროექციას იყენებს.", + "render.library_blocked": "დაბლოკილია / საჭიროებს კალიბრაციას", + "render.library_capabilities": "შესაძლებლობების სპეციფიკაციები", + "render.library_center": "კომპლექტის ცენტრი", + "render.library_clear_search": "გასუფთავება", + "render.library_details": "სპეციფიკაცია და წარმომავლობა", + "render.library_emitters_only_ack": "მხოლოდ გამომსხივებლების გამოყენება; დოკუმენტირებული პასიური ამრეკლების გამოტოვება", + "render.library_empty": "შესაბამისი რესურსები არ არის. სცადეთ სხვა მოთხოვნა ან ხელმისაწვდომობის ფილტრი.", + "render.library_environment_concepts": "გარემოს კონცეფციები", + "render.library_extent": "ობიექტის განფენილობა", + "render.library_favorite": "რჩეულებში დამატება", + "render.library_favorites": "რჩეულები", + "render.library_filters": "კატალოგი და ხელმისაწვდომობა", + "render.library_grid": "ბადე", + "render.library_hdr": "ჩაშენებული HDR-გარემოები", + "render.library_hdr_help": "ორიგინალურ HDR-ს შენახულ კონფიგურაციაში ჩააშენებს. ავტორის გრძედის სათავე ცალსახად გარდაიქმნება; შენახვის შემდეგ გარე ფაილი საჭირო აღარ არის.", + "render.library_in_design": "პროექტში", + "render.library_inspect_only": "შესამოწმებლად აირჩიეთ; ავტომატურად არაფერი გამოიყენება. რჩეულები და ბოლოდროინდელი ისტორია ამ ღია დოკუმენტის სესიას ეკუთვნის.", + "render.library_ior": "IOR", + "render.library_light_concepts": "განათების კონცეფციები", + "render.library_list": "სია", + "render.library_maps_help": "ჩაშენებული რუკები შეიძლება შეინახოს მიმაგრებული წყაროებითა და ადგილობრივი ეგზემპლარების ასახვით. დროებითი ოპტიკური გადაფარვები ცალკე რეჟიმად რჩება.", + "render.library_material_concepts": "მასალის კონცეფციები", + "render.library_metallic": "მეტალიკური", + "render.library_native_scenes": "ნატიური სტუდიები", + "render.library_next": "შემდეგი გვერდი", + "render.library_omitted": "არ შედის", + "render.library_opacity": "გაუმჭვირვალობა", + "render.library_other": "სხვა იერსახეები", + "render.library_physical_profiles": "ფიზიკური საცნობარო პროფილები", + "render.library_previous": "წინა გვერდი", + "render.library_quality_concepts": "ხარისხის სპეციფიკაციები", + "render.library_recent": "ბოლოდროინდელი", + "render.library_replace_environment": "არსებული გარემოს ცალსახად ჩანაცვლება", + "render.library_replace_studio": "შენახული განათების, გარემოსა და დეკორაციის ჩანაცვლება", + "render.library_results": "შესაბამისი რესურსები", + "render.library_rig_help": "ერთხელ მოარგეთ ცალსახა ცენტრსა და ფიზიკურ განფენილობას. სრული კომპლექტები პასიურ ამრეკლებსაც შეიცავს; კალიბრაციის დამბლოკველები კვლავ უარს იწვევს. გამომსხივებლისა და ამრეკლის ღრეჩო შენახვამდე კონსერვატიულად მოწმდება.", + "render.library_rigs": "ავტორის განათების კომპლექტები", + "render.library_roughness": "უხეშობა", + "render.library_save_maps": "რუკების შენახვა ამ კონფიგურაციაში", + "render.library_scene_bounds": "სცენის დაფიქსირებული საზღვრების გამოყენება", + "render.library_scenes": "სცენის სპეციფიკაციები", + "render.library_search": "ბიბლიოთეკაში ძიება", + "render.library_select_hint": "მისი მხარდაჭერილი მოქმედებებისა და შეზღუდვების სანახავად აირჩიეთ რესურსი ბიბლიოთეკაში.", + "render.library_selene": "SELENE გაუმჭვირვალე იერსახეები", + "render.library_selene_shots": "SELENE კადრების სპეციფიკაციები", + "render.library_short_blocked": "მიუწვდომელია", + "render.library_short_native": "ნატიური კომპოზიცია", + "render.library_short_projection": "მხარდაჭერილი პროექცია", + "render.library_short_reference": "მხოლოდ საცნობაროდ", + "render.library_short_specification": "მხოლოდ სპეციფიკაცია", + "render.library_source_preview": "წყაროს რუკის გადახედვის ჩატვირთვა", + "render.library_source_preview_help": "ავტორის ძირითადი ფერის წყაროს რუკა. ეს არ არის მასალის რენდერირებული ან გაზომილი გადახედვა.", + "render.library_specification_only": "მხოლოდ სპეციფიკაცია: ეს არ არის სრული შესრულებადი პრესეტი. საჭირო ეფექტებს, რესურსებსა და ობიექტის როლებს ჯერ კიდევ სჭირდება ცალსახა რეალიზაცია და მიბმა.", + "render.library_specs": "მხოლოდ სპეციფიკაციები", + "render.library_status": "ხელმისაწვდომობა", + "render.library_surfaces": "ავტორის PBR-ზედაპირები", + "render.library_target": "სამიზნე სხეული", + "render.library_title": "რენდერის რესურსების ბიბლიოთეკა", + "render.library_unfavorite": "რჩეულებიდან წაშლა", + "render.library_uniform_ack": "ერთგვაროვანი მიახლოების გამოყენება სივრცული ან დამატებითი ეფექტების გარეშე", + "render.library_usable": "შესრულებადი პროექციები", + "render.library_users": "გამოყენება", + "render.light_aim": "დამიზნება", + "render.light_anchor_pending": "სინათლის კოორდინატთა სისტემის შეცვლა ჯერ მხარდაჭერილი არ არის.", + "render.light_azimuth": "აზიმუტი", + "render.light_backend_limit": "სინათლეების რედაქტირებისთვის აირჩიეთ CPU-ის სხივების მიდევნება ან ცალსახა GPU-სტუდია. ძველი GPU-სტუდიის სინათლეები მხოლოდ წასაკითხი რჩება.", + "render.light_behaviour": "ქცევა", + "render.light_default_fill": "შემავსებელი", + "render.light_default_key": "მთავარი", + "render.light_default_number": "სინათლე {number}", + "render.light_default_rim": "კონტურული", + "render.light_delete": "წაშლა", + "render.light_distance": "მანძილი", + "render.light_duplicate": "დუბლირება", + "render.light_elevation": "სიმაღლის კუთხე", + "render.light_gpu_punctual": "წერტილოვანი და პროჟექტორის სინათლეები CPU-ის სხივების მიდევნებით არის ხელმისაწვდომი.", + "render.light_hard_shadow": "ამ სინათლეს მკვეთრი ჩრდილები აქვს; გამომსხივებლის სირბილე მიუწვდომელია.", + "render.light_intensity": "ინტენსივობა", + "render.light_missing": "ეს სინათლე აღარ არსებობს. აირჩიეთ სინათლე მოდელის ხეში.", + "render.light_place_highlight": "განთავსება ნათელი ლაქის მიხედვით", + "render.light_place_pending": "ნათელი ლაქის მიხედვით განთავსებას ხედვის არეში სინათლის არჩევა სჭირდება და ჯერ მხარდაჭერილი არ არის.", + "render.light_position": "პოზიცია", + "render.light_preview_help": "ცოცხალი ხედი ჩრდილების გარეშეა; ფართობული სინათლეები ცენტრალური სემპლის მიახლოებას იყენებს. რენდერი სინათლის სრულ მოდელს იყენებს.", + "render.light_product_centre": "პროდუქტის ცენტრი", + "render.light_size": "ზომა", + "render.light_softness": "სირბილე", + "render.light_temperature": "ფერის ტემპერატურა", + "render.light_temperature_help": "აბსოლუტურად შავი სხეულის მიახლოებითი ელფერი; ინახება წრფივი RGB-ის სახით.", + "render.light_type": "ტიპი", + "render.light_type_area": "ფართობი", + "render.light_type_point": "წერტილი", + "render.light_type_spot": "პროჟექტორი", + "render.light_type_sun": "მზე", + "render.light_view_only": "სოლო და დადუმება ამ ხედსა და მის რენდერებზე მოქმედებს; პროექტში არასოდეს ინახება.", + "render.light_world_origin": "მსოფლიოს სათავე", + "render.lighting_aim_point": "დამიზნების წერტილი", + "render.lighting_apply": "პრესეტის გამოყენება", + "render.lighting_area_samples": "ფართობის სემპლები", + "render.lighting_budget": "ბიუჯეტი", + "render.lighting_budget_help": "რაოდენობები მხოლოდ წასაკითხია. მათ შესაცვლელად დაამატეთ, დუბლირეთ ან წაშალეთ სინათლეები; ლიმიტებს მეთოდი ადგენს.", + "render.lighting_colour": "ფერი", + "render.lighting_consent": "მიმართული სინათლეების ჩანაცვლება ამ პრესეტით", + "render.lighting_custom": "მორგებული სინათლეები", + "render.lighting_custom_help": "„მორგებულის“ არჩევა პრესეტს რედაქტირებად სინათლეებად აქცევს, თითოეულს — ცალკე სტრიქონად ხეში.", + "render.lighting_direction": "მიმართულება X Y Z", + "render.lighting_direction_help": "ან შეიყვანეთ მიმართულება სინათლისკენ (X Y Z).", + "render.lighting_distance_unit": " × ზომა", + "render.lighting_edge_u": "გვერდის U ვექტორი", + "render.lighting_edge_v": "გვერდის V ვექტორი", + "render.lighting_falloff": "მილევა", + "render.lighting_falloff_help": "ინტენსივობა საბაზო მანძილზეა მითითებული.", + "render.lighting_height": "სიმაღლე V", + "render.lighting_minimum": "მინიმუმი", + "render.lighting_mute": "ამ სინათლის დადუმება", + "render.lighting_point": "წერტილი", + "render.lighting_preset": "სტუდიის პრესეტი", + "render.lighting_preset_cpu": "სტუდიის მიმართულ პრესეტებს CPU-ის სხივების მიდევნება სჭირდება. GPU-განათება ცალსახა მზისა და ფართობულ სინათლეებს იყენებს.", + "render.lighting_preset_row": "პრესეტი", + "render.lighting_radiance": "ენერგეტიკული სიკაშკაშე", + "render.lighting_reference": "საბაზო", + "render.lighting_review_help": "ანაცვლებს მიმართული სინათლეების სიას. ინარჩუნებს წერტილოვან და ფართობულ სინათლეებს, გარემოს, ჩრდილებს, კამერას და კადრის ყველა სხვა პარამეტრს.", + "render.lighting_review_title": "განათების პრესეტის გადახედვა", + "render.lighting_samples_cpu": "ფართობული სინათლის სემპლები CPU-ის სხივების მიდევნებას ეხება.", + "render.lighting_samples_need_area": "ფართობის სემპლების დასაყენებლად დაამატეთ CPU-ის ფართობული სინათლე.", + "render.lighting_samples_reason": "ფართობის სემპლები უნდა იყოს 1, 4, 16 ან 64.", + "render.lighting_shadow_cpu": "ჩრდილების გადამრთველს CPU-ის სხივების მიდევნება სჭირდება. GPU-ის ტრაექტორიების მიდევნება ჩრდილებს ყოველთვის ყრის.", + "render.lighting_shadows": "ჩრდილების დაყრა", + "render.lighting_shadows_section": "ჩრდილები და სემპლინგი", + "render.lighting_shape": "ფორმა", + "render.lighting_solo": "ამ სინათლის სოლო", + "render.lighting_source": "წყარო", + "render.lighting_source_section": "სინათლის წყარო", + "render.lighting_spot_preserved": "ეს წერტილოვანი სინათლე შენახულ პროჟექტორის კონუსს ინარჩუნებს, სანამ მისი ტიპი არ შეიცვლება.", + "render.lighting_sun_distance": "მზის მიმართულება მანძილსა და დამიზნების წერტილზე არ არის დამოკიდებული.", + "render.lighting_unsupported": "მხარდაუჭერელი", + "render.lighting_used": "{used} / {limit}", + "render.lighting_width": "სიგანე U", + "render.lighting_world_position": "მსოფლიო X Y Z", + "render.lights_fixed_to": "სინათლეები მიმაგრებულია", + "render.linear_help": "ინარჩუნებს 32-ბიტიან მცურავმძიმიან RGBA-მასტერს ხმაურის მოცილებამდე, ექსპოზიციამდე, ტონალურ ასახვამდე, ფილტრებამდე და ფონამდე. წრფივი sRGB/D65; დაფარვით წინასწარ გამრავლებული. დამატებითი მეხსიერება ცალსახად ეთმობა. შეკუმშვისა და დამატებითი გავლების გარეშე.", + "render.linear_retain": "დაუმუშავებელი წრფივი EXR-ის შენარჩუნება", + "render.linear_unavailable": "არჩეულ დასრულებულ კადრს შენახული EXR არ აქვს. რენდერინგამდე ჩართეთ შენარჩუნება; ძველი PNG დაუმუშავებელ ენერგეტიკულ სიკაშკაშეს ვერ აღადგენს.", + "render.look_add": "ფერის ვიზუალური სტილის დამატება", + "render.look_applied": "გამოყენებულია: {name}", + "render.look_bleach": "გაუთეთრებელი დამუშავების სტილში", + "render.look_cool": "ცივი", + "render.look_cyanotype": "ციანოტიპიის სტილში", + "render.look_faded": "გახუნებული ანაბეჭდი", + "render.look_material": "მასალა", + "render.look_mono": "მონოქრომული", + "render.look_pasted": "ვიზუალური სტილი ჩასმულია", + "render.look_sepia": "სეპია", + "render.look_strength": "ვიზუალური სტილის სიძლიერე", + "render.look_teal_orange": "ზღვისფერი / ნარინჯისფერი", + "render.look_title": "ვიზუალური სტილების კრეატიული დასტა", + "render.look_warm": "თბილი", + "render.mapping_scale": "ფიზიკური გამეორების მამრავლი", + "render.material_absorption": "შთანთქმა R · G · B (mm-ზე)", + "render.material_add": "ამ სხეულის დამატება ან რედაქტირება", + "render.material_assignments": "სხეულების მინიჭებები", + "render.material_binding_enable": "ამ სხეულის გადაფარვის ჩართვა", + "render.material_box": "ღერძებზე გასწორებული პარალელეპიპედი", + "render.material_browse": "გამოსახულების არჩევა…", + "render.material_certification": "დახურული მინა გეომეტრიულ მანძილს იყენებს. ტოპოლოგია, ორიენტაცია, გადაფარვა და ოპტიკური საზღვრები GPU-ის მომზადებისას მოწმდება; შემოწმება მხოლოდ მოთხოვნას უშვებს.", + "render.material_choose_body": "სცენის სხეულის არჩევა", + "render.material_closed": "დახურული მყარი პოლიგონური ბადე", + "render.material_coat": "გამჭვირვალე ლაქი ძირითად მასალაზე", + "render.material_coat_enable": "გამჭვირვალე ლაქის ჩართვა", + "render.material_coat_help": "საილუსტრაციო დიელექტრიკული საფარი არსებულ გაუმჭვირვალე იერსახეზე. ნულოვანი წონა ძირითად მასალას უცვლელს ტოვებს.", + "render.material_color_map": "ძირითადი ფერის გამოსახულება (sRGB)", + "render.material_color_replace": "ძირითადი რუკა სხეულის ფერს ანაცვლებს", + "render.material_custom": "მორგებული საილუსტრაციო ოპტიკა", + "render.material_enable": "ამ GPU-მასალის გადაფარვების გამოყენება", + "render.material_filter": "სცენის სხეულების ფილტრი…", + "render.material_filter_help": "ნაჩვენებია 128-მდე შესაბამისი სხეული. დიდი სცენებისთვის დააზუსტეთ ფილტრი.", + "render.material_glass": "მინა და ოპტიკური შთანთქმა", + "render.material_glass_enable": "ამ სხეულზე ფიზიკური მინის გამოყენება", + "render.material_glass_exclusive": "ამ რენდერერში მინა ერთ სხეულზე ვერ იქნება გამჭვირვალე ლაქთან ან გაშვების დროის რუკებთან ერთად.", + "render.material_glass_help": "ორიგინალური საილუსტრაციო რეცეპტები. ნიმუშები გამტარობას აჩვენებს და არა რენდერირებულ გადახედვას. შთანთქმა არის −ln(წრფივი გამტარობა) / საბაზო მანძილი; ალფა უცვლელია.", + "render.material_gpu_required": "მასალის ამ აქტიურ გადაფარვებს GPU-ის ტრაექტორიების მიდევნება სჭირდება. „შემოწმებამდე“ ან „დაწყებამდე“ აირჩიეთ GPU ან გამორთეთ გადაფარვები.", + "render.material_ior": "გარდატეხის მაჩვენებელი (IOR)", + "render.material_limits": "მაქსიმუმ 128 სხეულის გადაფარვა, 32 არაგადამკვეთი მინის სხეული, 64 საფარი და 128 ტექსტურის მიბმა. იდენტური რუკები საცავს იზიარებს; მოწყობილობისა და მეხსიერების რეალური საერთო ლიმიტები მაინც მოქმედებს.", + "render.material_map_invalid": "რუკების ბილიკები უნდა იყოს შეზღუდული ადგილობრივი ბილიკები; ნორმალის სიძლიერე უნდა იყოს სასრული და 0-სა და 1-ს შორის.", + "render.material_map_required": "რუკების გამოყენებამდე აირჩიეთ ფერის ან ნორმალის გამოსახულება.", + "render.material_maps": "ფერისა და ნორმალის სიბრტყული რუკები", + "render.material_maps_enable": "რუკების ჩართვა ამ გაუმჭვირვალე სხეულისთვის", + "render.material_maps_help": "PNG/JPEG 1024×1024-მდე; სულ 16 MiB დაკოდირებული. U და V მსოფლიოს mm-ში გამოსახული ორთოგონალური გამეორების ვექტორებია (მაქსიმუმ 128 გამეორება). ფერი sRGB-შია; ნორმალის მონაცემები OpenGL +Y-ს იყენებს. ფაილები შემოწმების/დაწყებისას ფიქსირდება.", + "render.material_metallic_map": "მეტალიკურობის რუკა (წრფივი)", + "render.material_normal_map": "ნორმალის გამოსახულება (OpenGL, +Y)", + "render.material_normal_strength": "ნორმალის სიძლიერე (0–1)", + "render.material_origin": "ასახვის სათავე X · Y · Z (mm)", + "render.material_refresh": "სცენის სხეულების განახლება", + "render.material_refresh_needed": "სცენა შეიცვალა. სამიზნის დამატებამდე განაახლეთ სხეულების სია.", + "render.material_remove": "ამ მინიჭების წაშლა", + "render.material_repeat_u": "ერთი U გამეორება X · Y · Z (mm)", + "render.material_repeat_v": "ერთი V გამეორება X · Y · Z (mm)", + "render.material_revalidate": "ამ სხეულის ხელახალი შემოწმება", + "render.material_revalidate_needed": "ეს მინიჭება სცენის ადრინდელ რევიზიას ეკუთვნის. რენდერინგამდე ხელახლა შეამოწმეთ მისი სხეულის ზუსტი იდენტობა.", + "render.material_roughness": "საფარის უხეშობა (0.045–1)", + "render.material_roughness_map": "უხეშობის რუკა (წრფივი)", + "render.material_shadow": "ჩრდილის სწორი სხივების გატარება", + "render.material_target_missing": "სხეულის რიგითი ნომერი და სახელი აღარ ემთხვევა. წაშალეთ ეს მინიჭება და ცალსახად აირჩიეთ სასურველი სხეული ხელახლა.", + "render.material_thickness": "თხელი ფურცლის სისქე (mm)", + "render.material_thin": "თხელი ფურცელი", + "render.material_title": "GPU-გამოსახულების მასალები", + "render.material_transient": "დროებითი ოპტიკური გადაფარვები ამ დოკუმენტის ჩანართისთვის. ისინი არ ინახება პროექტში, რენდერის კონფიგურაციაში ან მასალების ბიბლიოთეკაში.", + "render.material_v_up": "ტექსტურის V გამოსახულებაში ზემოთ არის მიმართული", + "render.material_weight": "საფარის წონა (0–1)", + "render.method_cpu": "CPU-ის სხივების მიდევნება", + "render.method_gpu": "GPU-ის ტრაექტორიების მიდევნება", + "render.method_limit_raster": "რასტრი სტუდიის ფიქსირებულ გაუმჭვირვალე გადახედვას იყენებს. მხარდაჭერილი ოპტიკური პარამეტრებისთვის აირჩიეთ სხივების მიდევნების ცალსახა მეთოდი.", + "render.method_raster": "CPU-რასტრი", + "render.navigation_help": "კამერა ისევე მოძრაობს, როგორც დიზაინში (პარამეტრები › ნავიგაცია). „კონფიგურაციის შენახვა“ მიმდინარე კამერას იმახსოვრებს.", + "render.nested_enable": "სერტიფიცირებული ჩადგმული დიელექტრიკები", + "render.nested_help": "16-მდე შემცველი შრე; ყოველი მშობელი ამოზნექილი უნდა იყოს და ყოველი შვილი — მკაცრად მის შიგნით. გადაკვეთები, შეხებადი ზედაპირები, თხელი ფურცლები და ჩრდილის სწორი სხივების გატარება უარყოფილია. კამერის შიგნით ყოფნის მდგომარეობა სერტიფიცირებულ იერარქიას მიჰყვება. სითხის ზედაპირს არ ქმნის და CAD-ის შეხებად საზღვრებს არ აერთიანებს.", + "render.opaque_image_summary": "გადახედვის PNG · გაუმჭვირვალე PBR · შერეული გამჭვირვალობა", + "render.opaque_preview_help": "გაუმჭვირვალე PBR და მარტივი ფერები; შერეული გამჭვირვალობა. გარდატეხა, HDRI და საბოლოო რენდერინგი ჯერ მიუწვდომელია.", + "render.optics_remove": "შენახული ოპტიკის წაშლა", + "render.optics_replace": "ამ სამიზნის შენახული ოპტიკის ცალსახად ჩანაცვლება", + "render.optics_save": "ამ ოპტიკის შენახვა კონფიგურაციაში", + "render.optics_saved": "შენახული ოპტიკური სამიზნეები", + "render.optics_saved_help": "ზუსტი განსაზღვრების, ოპერაციისა და ეგზემპლარის იდენტობა ოფლაინ ხელახლა გახსნისას ნარჩუნდება. დაკარგული/ჩანაცვლებული/დამალული სამიზნეები უარყოფილია; საინჟინრო მასალები უცვლელია. შენახული სამიზნის წაშლამდე შეინახეთ ან გააუქმეთ რიცხვითი ცვლილებები.", + "render.outer_half_angle": "გარე ნახევარკუთხე", + "render.output_advanced": "დამატებითი", + "render.output_backend_ready": "მზადაა", + "render.output_check": "შემოწმება", + "render.output_check_failed": "შემოწმება · შეცდომა", + "render.output_check_help": "ამ მოთხოვნის გადასახედად რენდერის დაწყების გარეშე გაუშვით შემოწმება.", + "render.output_check_summary": "შემოწმება · შენიშვნები: {count}", + "render.output_copy": "კოპირება", + "render.output_copy_report": "ანგარიშის კოპირება", + "render.output_destination": "დანიშნულება", + "render.output_destination_help": "დასრულებული გამოსახულების ექსპორტისას აირჩიეთ დანიშნულების ფაილი.", + "render.output_dimensions": "ზომა", + "render.output_effects": "ეფექტები", + "render.output_export": "PNG-ის ექსპორტი…", + "render.output_exr_unavailable": "EXR-გამოტანის კონფიგურაცია აქ მიუწვდომელია. წრფივი EXR-ის ექსპორტს სჭირდება დასრულებული GPU-გამოსახულება შენახული წრფივი მასტერით.", + "render.output_fit": "ჩატევა", + "render.output_format": "ფორმატი", + "render.output_format_status": "PNG ზუსტად დასრულებული საჩვენებელი გამოსახულებაა. არასავალდებულო GPU EXR ინარჩუნებს სცენის დაუმუშავებელ წრფივ FLOAT32 ენერგეტიკულ სიკაშკაშეს ჩვენების ფილტრებამდე. ექსპორტი არასოდეს ანაცვლებს მას გადახედვის ქეშით ან სხვა ამოცანით.", + "render.output_grading": "ფერკორექცია", + "render.output_image": "გამოსახულება", + "render.output_largest": "მაქს. {width} × {height}", + "render.output_lock_ratio": "თანაფარდობის ჩაკეტვა", + "render.output_over_budget": "მოთხოვნილი გამოსახულება აჭარბებს არჩეული რესურსების ზღვარს. ცალსახად აირჩიეთ თავსებადი ზომა ან პროფილი; ავტომატური შემცირება არ ხდება.", + "render.output_presets_help": "ფორმატი, ხარისხი და შემოწმების სია გამოტანის რედაქტორშია.", + "render.output_quality": "ხარისხი", + "render.output_quality_waiting": "ხარისხის კონტრაქტის მოლოდინში", + "render.output_ratio_refused": "დაკავშირებული ზომა აჭარბებს ამ მეთოდის ზომის ლიმიტს. წინა ზომა შენარჩუნებულია; მოხსენით თანაფარდობის ჩაკეტვა ან აირჩიეთ უფრო მცირე მნიშვნელობა.", + "render.output_ready": "რენდერისთვის მზადაა", + "render.output_run_check": "შემოწმების გაშვება", + "render.output_size_limit": "{method}: თითო მხარეზე {dimension} px-მდე და {pixels} პიქსელამდე. უდიდესი ჩატეული ზომა: {width} × {height}.", + "render.output_size_method_profile": "{width} × {height}-ის რენდერისთვის აირჩიეთ {method} CPU-ის რესურსების პროფილით „{profile}“, ან უფრო მცირე ზომა.", + "render.output_size_ok": "ზომა სწორია · {width} × {height} px", + "render.output_size_profile": "{width} × {height}-ის რენდერისთვის აირჩიეთ CPU-ის რესურსების პროფილი „{profile}“, ან უფრო მცირე ზომა.", + "render.output_swap_orientation": "სიგანისა და სიმაღლის გაცვლა", + "render.output_tools_inspector": "ზომა და ფორმატი შეცვალეთ გამოტანის ინსპექტორში.", + "render.output_view_image": "გამოსახულების ნახვა", + "render.page_aging": "დაძველება და დაბინძურება", + "render.page_all": "ყველა პარამეტრი", + "render.page_appearance": "იერსახე", + "render.page_background": "ფონები", + "render.page_camera": "კამერა", + "render.page_diagnostics": "დიაგნოსტიკა", + "render.page_effects": "ობიექტივისა და დასრულების ეფექტები", + "render.page_environment": "გარემო", + "render.page_lighting": "განათება", + "render.page_output": "გამოტანა", + "render.page_scene": "სცენა", + "render.paint_label": "შეღებვა", + "render.painting_with": "შეღებვა: {name}", + "render.passive_stage": "მიწა და პასიური დეკორაცია", + "render.passive_stage_help": "სასრული პასიური პანელები მხოლოდ რენდერირებულ გამოსახულებებს ეკუთვნის. ისინი CAD-სხეულებს ან მასას არ ამატებს. გამოყენების შემდეგ განლაგება ფიქსირებულია; პროდუქტის საზღვრებთან გადაკვეთა უარყოფილია. CPU დიფუზურ ასხლეტილ განათებას არ იძლევა.", + "render.perspective": "პერსპექტიული კამერა", + "render.physical_acknowledge": "მესმის, რომ ამ ნაწილობრივ საცნობარო მონაცემს მარკის, მდგომარეობისა და წყაროს გადახედვა სჭირდება", + "render.physical_associations": "ფიზიკური კანდიდატები და როლები", + "render.physical_background_help": "რეალური პასიური იატაკი და კედელი, კამერის ფონისგან ცალკე. ციკლორამა 24 მრავალკუთხა ზოლს იყენებს; ის არც უსასრულოა და არც ანალიზურად გლუვი ზედაპირი. შენახულ დეკორაციას მხოლოდ თქვენი თანხმობით ანაცვლებს.", + "render.physical_copy_plan": "გეგმის კოპირება წყაროებითა და გამოტოვებებით", + "render.physical_cyclorama": "მრავალკუთხა ციკლორამის მორგება", + "render.physical_floor_wall": "ფიზიკური იატაკისა და კედლის მორგება", + "render.physical_material_name": "საცნობარო მასალის შემოთავაზებული სახელი", + "render.physical_omissions": "თვისებები, რომლებიც ნატიურ ბარათში ვერ აისახება", + "render.physical_plan_only": "მომზადდა მხოლოდ წასაკითხი გეგმა. მასალა არ შექმნილა და არ მინიჭებულა. ნატიური ბარათის გადახედვისას შეინარჩუნეთ მისი გაფართოებული პროფილი და გამოტოვებები.", + "render.physical_prepare_plan": "შექმნის გეგმის მომზადება (არ გამოიყენება)", + "render.physical_separate": "იერსახე მასალის იდენტიფიკაცია არ არის. ეს წყაროზე დაფუძნებული საცნობარო მონაცემებია და არა სერტიფიცირებული ეფექტური თვისებები. არსებული მასა, საინჟინრო მასალები და ოპტიკა უცვლელია.", + "render.physical_unknown": "რიცხვითი კანდიდატი დადგენილი არ არის. უნდა მიეთითოს მარკა, შედგენილობა ან კონსტრუქცია; უცნობი ნულს არ ნიშნავს.", + "render.pick_body": "სხეული", + "render.pick_component": "კომპონენტი", + "render.pick_face": "წახნაგი", + "render.pick_help": "აირჩიეთ სხეული, წახნაგი ან კომპონენტი. გასასუფთავებლად დაწკაპეთ ცარიელ ადგილზე; Shift ან Ctrl ამატებს ან გადართავს. მონიშვნები მხოლოდ პროდუქტის ცოცხალ ხედში ჩანს.", + "render.pick_label": "არჩევა", + "render.pick_up_label": "აღება", + "render.pick_up_prompt": "დაწკაპეთ ობიექტზე მისი ვიზუალური სტილის ასაღებად", + "render.pick_waiting": "პროდუქტზე არჩევა ჯერ მხარდაჭერილი არ არის.", + "render.post_contrast": "კონტრასტი", + "render.post_gain_b": "ლურჯის გაძლიერება", + "render.post_gain_g": "მწვანის გაძლიერება", + "render.post_gain_r": "წითლის გაძლიერება", + "render.post_help": "მხოლოდ კრეატიული წარდგენისთვის. RGB-გაძლიერება ტონალურ ასახვამდე სრულდება; კონტრასტი, გაჯერება და ვინიეტი შემდეგ, ჩვენების წრფივ სინათლეში. „რენდერის დაწყება“ გადატანის ახალ სემპლებს ქმნის. ხელახალი ფერკორექცია არჩეულ შენახულ დაუმუშავებელ მასტერს იყენებს ხმაურის მოცილებისა და ახალი სხივების გარეშე.", + "render.post_reset": "წარდგენის ფილტრების ჩამოყრა", + "render.post_saturation": "გაჯერება", + "render.post_title": "წარდგენის ფილტრები", + "render.post_vignette": "ვინიეტი", + "render.preview": "ინტეგრირებული გადახედვა", + "render.preview_help": "რასტრული დაჩრდილვა და შერეული გამჭვირვალობა. გარდატეხა, HDRI და საბოლოო რენდერინგი ჯერ მიუწვდომელია.", + "render.preview_image_settings_help": "ცოცხალი გადახედვა სტუდიის ფიქსირებულ განათებას ინარჩუნებს. ექსპოზიცია და გამოსახულების განათება გამოსახულების ამოცანას ეხება, როცა „შემოწმებას“ ან „დაწყებას“ დააჭერთ.", + "render.preview_lighting_help": "ცოცხალი გადახედვა მხოლოდ პირდაპირ სინათლეს აჩვენებს, ჩრდილების გარეშე.", + "render.preview_retry": "ცოცხალი გადახედვის ხელახლა ცდა", + "render.preview_unavailable_help": "ცოცხალი გადახედვა მიუწვდომელია. შენახული კონფიგურაციები და გამოსახულების ამოცანის პარამეტრები ხელმისაწვდომი რჩება. შეცვალეთ სცენა ან ცალსახად სცადეთ ხელახლა; უარყოფილი სცენა ყოველ კადრზე თავიდან არ აიგება.", + "render.preview_upload": "ცოცხალი გადახედვის წვეროების მონაცემები", + "render.preview_upload_help": "გადახედვის წვეროების ზუსტი ბაიტები და არა GPU-ის ან პროცესის მთლიანი მეხსიერება. გეომეტრია არ მარტივდება. გამოსახულების ამოცანები საკუთარ დაშვებასა და განათებას იყენებს.", + "render.progressive_image_summary": "გადახედვის PNG · PBR და მინა · პროგრესული სემპლები", + "render.property_conditions": "პირობები: {value}", + "render.property_fallback": "თვისება", + "render.property_qualifier": "დამაზუსტებელი: {value}", + "render.property_source": "წყარო: {id} - {locator}", + "render.property_uncertainty": "განუსაზღვრელობა: {value}", + "render.property_unknown": "უცნობი", + "render.quality_ack": "ფიქსირებული ბიუჯეტის პროექციისა და გამოტოვებების დადასტურება", + "render.quality_apply": "ამ ფიქსირებული სემპლინგის ბიუჯეტის გამოყენება", + "render.quality_balanced": "დაბალანსებული", + "render.quality_custom": "მორგებული", + "render.quality_draft": "მონახაზი", + "render.quality_high": "მაღალი", + "render.quality_projection_help": "Q-პრესეტები მომავალ მოთხოვნებსაც მოიცავს. ეს მოქმედება მხოლოდ მხარდაჭერილ, ფიქსირებულსემპლიან PNG-ბიუჯეტს აპროექციებს და ცალსახად გამოტოვებს ადაპტიურ შეჩერებას, დაუმუშავებელ წრფივ გამოტანას და გამტარობის დამოუკიდებელ ლიმიტებს.", + "render.quality_review": "სემპლინგის ბიუჯეტის გადახედვა", + "render.queue_pending": "ამ ინტერფეისში არ არის წარმოების ავტომატური რიგი ან ანიმაციის რენდერერი. დასრულებული სტატიკური გამოსახულებების ექსპორტი ცალ-ცალკე შეიძლება.", + "render.radial_assign": "იერსახის მინიჭება", + "render.radial_compare": "შედარება", + "render.radial_distortion": "რადიალური დამახინჯება", + "render.radial_fit": "პროდუქტის ჩატევა", + "render.radial_save": "კადრის შენახვა", + "render.recent_looks": "ბოლოდროინდელი ვიზუალური სტილები", + "render.regrade_action": "დაუმუშავებელი მასტერის ხელახალი ფერკორექცია (ხმაურის მოცილების გარეშე)", + "render.regrade_help": "არჩეული დასრულებული დაუმუშავებელი მასტერიდან ამ წარდგენის პარამეტრებით ცალკე PNG-ს ქმნის. სხივებს არ მიადევნებს, დაფიქსირებულ ზომას/კამერას/სინათლეებს არ ცვლის და EXR-ს არ გადაწერს. ხმაურის მოცილება ხელახლა არ გამოიყენება: დაუმუშავებელი მასტერები მის დამხმარე მონაცემებს არ ინახავს. წარმოებული გამოსახულების ექსპორტი იმავე ამოცანის პარამეტრებით შეიძლება.", + "render.regrade_label": "ხელახალი ფერკორექცია", + "render.reload_settings": "შენახული პარამეტრების ხელახლა ჩატვირთვა", + "render.remove_override": "გადაფარვის მოხსნა", + "render.replace_all": "ყველას ჩანაცვლება", + "render.replace_ground": "არსებული დეკორაციის ჩანაცვლების დადასტურება", + "render.replace_label": "ჩანაცვლება", + "render.replace_saved_surface": "ამ სამიზნის არსებული შენახული მიბმის ჩანაცვლება", + "render.replace_with": "ჩანაცვლება შემდეგით", + "render.restore_camera": "შენახული კამერის აღდგენა", + "render.result_actual": "100%", + "render.result_actual_help": "გამოსახულების ერთი პიქსელი ეკრანის ერთ პიქსელზე.", + "render.result_actual_size": "100%", + "render.result_capture": "დაფიქსირებული რევიზია", + "render.result_current": "მოდელის დაფიქსირებული რევიზია მიმდინარეა.", + "render.result_empty": "დასრულებული გამოსახულება ჯერ არ არის. შეამოწმეთ პარამეტრები, შემდეგ დაიწყეთ რენდერი.", + "render.result_fit": "გამოსახულების ჩატევა", + "render.result_job": "ამოცანა", + "render.result_navigation": "პანორამა და მასშტაბი ნავიგაციის პარამეტრებს იყენებს. Space + გადათრევა ხედს გადააადგილებს.", + "render.result_open": "დასრულებული გამოსახულების გახსნა მთავარ ტილოზე.", + "render.result_preview": "ცოცხალი გადახედვა", + "render.result_provisional": "დროებითი CPU-გამოსახულება", + "render.result_provisional_help": "ამ საკონტროლო წერტილის ექსპორტი შეუძლებელია. ექსპორტი ბოლო დასრულებულ შედეგს ინარჩუნებს; გაუქმება იმავე შედეგს უბრუნდება.", + "render.result_reduced_display": "საჩვენებელი გადახედვა შემცირებულია ხედვის არის მოწყობილობის/ქეშის ლიმიტამდე. შენახული PNG და ექსპორტი სრულ გარჩევადობას ინარჩუნებს; ამ შემცირებული ხედისთვის ნატიური 100%-იანი დათვალიერება მიუწვდომელია.", + "render.result_retained": "ნაჩვენებია ბოლო დასრულებული გამოსახულება; უფრო ახალ რენდერს ის ჯერ არ ჩაუნაცვლებია.", + "render.result_sequence": "საკონტროლო წერტილი", + "render.result_title": "რენდერის შედეგი", + "render.results_choose": "შენახული შედეგები", + "render.results_label": "რენდერი {number} · {shot} · {seconds} წმ", + "render.results_stale_label": "{result} [მოძველებული]", + "render.results_unnamed": "გამოსახულება", + "render.return_design": "დიზაინში დაბრუნება", + "render.review_stale": "ეს გადახედვა მოძველებულია. გამოყენებამდე გადაწყვიტეთ ან ხელახლა შეამოწმეთ.", + "render.ribbon_aging": "დაძველება", + "render.ribbon_backgrounds": "ფონები", + "render.ribbon_check": "შემოწმება", + "render.ribbon_check_help": "ზუსტად იმ მიმდინარე მონახაზის შემოწმება, რომელსაც რენდერი გაგზავნის. რენდერერის სარეზერვო ჩანაცვლების, ჩუმი ზომის შეცვლის ან რესურსის ჩანაცვლების გარეშე.", + "render.ribbon_edit_lights": "სინათლეების რედაქტირება", + "render.ribbon_effects": "ეფექტები", + "render.ribbon_environment_help": "HDR-განათება, მხოლოდ კამერისთვის ხილული ფონები და ფიზიკური დეკორაციის ზედაპირები ცალკე პარამეტრებია, ჩანაცვლებაზე ცალსახა თანხმობით.", + "render.ribbon_finish_dialog": "ჯერ დაასრულეთ მიმდინარე ფაილის ან დადასტურების დიალოგი.", + "render.ribbon_frame": "კადრირება", + "render.ribbon_hdr_library": "HDR-ბიბლიოთეკა", + "render.ribbon_job_active": "რენდერი უკვე მიმდინარეობს; ახლის დაწყებამდე ცალსახად გააუქმეთ ის.", + "render.ribbon_light_rigs": "განათების კომპლექტები", + "render.ribbon_lights_help": "შეამოწმეთ ავტორის კომპლექტები ან შეცვალეთ მხარდაჭერილი სინათლეები ისე, რომ მიმდინარე კონფიგურაცია არ ჩანაცვლდეს, სანამ ცვლილებას ცალსახად არ გამოიყენებთ.", + "render.ribbon_materials": "მასალები", + "render.ribbon_materials_help": "იერსახის საერთო ინსპექტორისა და ზედაპირების ორიგინალური ბიბლიოთეკის გახსნა. ოპტიკური ცვლილებები საინჟინრო თვისებებს ჩუმად არასოდეს ცვლის.", + "render.ribbon_no_active_job": "გასაუქმებელი აქტიური რენდერი არ არის.", + "render.ribbon_no_result": "მისი ზუსტი გამოსახულების ექსპორტამდე დაასრულეთ რენდერი.", + "render.ribbon_no_saved_camera": "კამერის აღდგენამდე შეინახეთ კადრი.", + "render.ribbon_saved_camera": "შენახული კამერა", + "render.ribbon_shots": "კადრები", + "render.ribbon_studios": "სტუდიები", + "render.ribbon_studios_help": "დაათვალიერეთ სტუდიის რეალიზებული კომპოზიციები და გამოყენებამდე გადახედეთ მათ ჩანაცვლებებს. მხოლოდ კონცეფციის სცენები მონიშნული რჩება.", + "render.ribbon_surface_maps": "ზედაპირის რუკები", + "render.sampling_title": "ადაპტიური და გამტარობის სემპლინგი", + "render.save_continue": "შენახვა და გაგრძელება", + "render.save_setup": "კონფიგურაციის შენახვა", + "render.save_shot": "კადრის შენახვა", + "render.saved_maps_runtime_conflict": "შენახული ზედაპირის მიბმები ვერ შეერევა დროებით ოპტიკურ გადაფარვებს ან შეუნახავ HDR-ს. შეინახეთ HDR ან ცალსახად წაშალეთ დროებითი შემავალი მონაცემები.", + "render.saved_surface_remove": "შენახული მიბმის წაშლა", + "render.saved_surfaces": "ზედაპირის შენახული მიბმები", + "render.saved_surfaces_help": "მიმაგრებული ჩაშენებული რუკები არჩეულ ეგზემპლარს ადგილობრივ მილიმეტრებში მიჰყვება. ჩანაცვლებული ან დაკარგული სამიზნე შეცდომაა და არასოდეს — ავტომატური ხელახალი მინიჭება.", + "render.scene_all_shots": "ყველა კადრი ({count})", + "render.scene_apply": "გადახედილი სტუდიის გამოყენება", + "render.scene_batch_reason": "„ყველა კადრს“ შენახული კადრების რენდერის რიგი სჭირდება, რომელიც ჯერ მიუწვდომელია.", + "render.scene_check_now": "ახლავე შემოწმება", + "render.scene_check_passed": "შემოწმება გავლილია · შენიშვნები: {notes}", + "render.scene_check_stale": "შემოწმება მოძველებულია · შეამოწმეთ ხელახლა", + "render.scene_check_unchecked": "ჯერ არ შემოწმებულა · შენიშვნები: 0", + "render.scene_consent": "განათების, გარემოს, ექსპოზიციისა და დეკორაციის ჩანაცვლების დადასტურება", + "render.scene_light_summary": "{environment} · სინათლეები: {lights}", + "render.scene_look_summary": "ვიზუალური სტილები: {looks} · გადაფარვები: {overrides}", + "render.scene_open_check": "შემოწმების გახსნა", + "render.scene_preserved_fields": "კამერა, სემპლინგი, ზომები, ოპტიკური მიბმები, CAD-გეომეტრია და საინჟინრო მასალები შენარჩუნებულია.", + "render.scene_preserves_design": "ხილული ობიექტისთვის განათებისა და პასიური დეკორაციის კომპოზიცია. გეომეტრია, საინჟინრო მასალები და კამერა ცალკე რჩება.", + "render.scene_ready": "რენდერისთვის მზადაა", + "render.scene_reminder": "სცენა პროექტს ინარჩუნებს. რენდერიდან გეომეტრია, საინჟინრო თვისებები და CAD არასოდეს იცვლება.", + "render.scene_reminders": "შეხსენებები", + "render.scene_renderer_ready": "{renderer} მზადაა", + "render.scene_replaces": "ანაცვლებს", + "render.scene_review": "გადაწყვეტა და გადახედვა", + "render.scene_review_help": "გამოყენებამდე გადახედეთ სრულ ნატიურ კომპოზიციას. მიუბმელი დამატებითი SCENE-სპეციფიკაციები არ ჩანაცვლდება.", + "render.scene_scope_details": "კომპოზიციის მოცულობა", + "render.scene_stages": "დეკორაციები", + "render.search_appearances": "ძიება იერსახეებში ({count})", + "render.setup_legacy_environment": "ეს ძველი კონფიგურაცია გარემოს შემობრუნების ან ინტენსივობის ძველ მნიშვნელობებს იყენებს. ეს მნიშვნელობები შენარჩუნებულია; სრული გამოსახულების ამოცანის შენახვამდე ცალსახად გარდაქმენით ისინი.", + "render.setup_name": "კონფიგურაციის სახელი", + "render.setup_numeric_help": "შენახვა იმახსოვრებს გამოსახულების აქტიურ მეთოდს და მის ყველა რიცხვით პარამეტრს. ხელახლა ჩატვირთვა ან სხვა კონფიგურაციის არჩევა ამ მონახაზს ანაცვლებს; კამერა ცალკე აღადგინეთ.", + "render.setup_offline_help": "ამ მეთოდის რედაქტირება და შენახვა მისი რენდერერის გარეშეც შეგიძლიათ. „შემოწმებასა“ და „დაწყებას“ ხელმისაწვდომი ჰოსტი სჭირდება.", + "render.setup_runtime_unsupported": "ამ სრული ამოცანის შენახვა ჯერ შეუძლებელია: ის რუკებს ან სცენის სხეულების მიბმებს შეიცავს. პორტატული კონფიგურაციის შენახვამდე წაშალეთ ეს დროებითი შემავალი მონაცემები.", + "render.setup_save_missing": "ბრძანების დასრულების შემდეგ რენდერის შენახული კონფიგურაცია ვერ მოიძებნა.", + "render.sharpening": "დეტალების გამკვეთრება", + "render.shell_tab_appearance": "რენდერის იერსახე", + "render.shell_tab_camera": "რენდერის კამერა", + "render.shell_tab_lighting": "განათება", + "render.shell_tab_scene": "რენდერის სცენა", + "render.shot_aperture": "დიაფრაგმა", + "render.shot_distance": "მანძილი", + "render.shot_dof": "ველის სიღრმე", + "render.shot_duplicate": "შენახული კადრის დუბლირება", + "render.shot_edit_output": "გამოტანაში რედაქტირება", + "render.shot_exposure_reason": "ექსპოზიციას სჭირდება CPU-ის სხივების მიდევნება ან GPU-ის ტრაექტორიების მიდევნება.", + "render.shot_exposure_section": "ექსპოზიცია", + "render.shot_focus_distance": "ფოკუსური მანძილი", + "render.shot_fov_reason": "ხედვის კუთხეს პერსპექტიული პროექცია სჭირდება.", + "render.shot_frame_subject": "ობიექტის კადრირება", + "render.shot_invalid_camera": "კამერის მნიშვნელობები სასრული და დიაპაზონში უნდა იყოს.", + "render.shot_lens": "ობიექტივი", + "render.shot_lens_enable_reason": "დიაფრაგმისა და ფოკუსური მანძილის რედაქტირებისთვის ჩართეთ ველის სიღრმე.", + "render.shot_lens_gpu_reason": "ველის სიღრმეს GPU-ის ტრაექტორიების მიდევნება სჭირდება.", + "render.shot_lens_perspective_reason": "ველის სიღრმეს პერსპექტიული პროექცია სჭირდება.", + "render.shot_look_selection": "მონიშნულზე მიმართვა", + "render.shot_manager": "შენახული კადრები", + "render.shot_new_name": "კადრის ახალი სახელი", + "render.shot_remove": "შენახული კადრის წაშლა", + "render.shot_remove_help": "წაიშლება მხოლოდ ეს შენახული კონფიგურაცია. საწყისი გეომეტრია და დასრულებული გამოსახულებები შენარჩუნდება; მოქმედების გაუქმება შესაძლებელია.", + "render.shot_remove_title": "წაიშალოს შენახული კადრი?", + "render.shot_rename": "შენახული კადრის სახელის შეცვლა", + "render.shot_saved_only": "ჯერ შეინახეთ მიმდინარე მონახაზი. დუბლირება და სახელის შეცვლა ზუსტ შენახულ ოფციებსა და რესურსების მიმართვებს ინარჩუნებს.", + "render.shot_selection_reason": "დასამიზნებლად აირჩიეთ სხეული ან წახნაგი.", + "render.shot_size": "ზომა", + "render.shot_target": "სამიზნე", + "render.shots_camera_changed": "ამ კადრის შენახვის შემდეგ კამერა შეიცვალა", + "render.shots_name_help": "შეიყვანეთ მიმდინარე კადრის უნიკალური სახელი.", + "render.shots_no_result": "რენდერი ჯერ არ არის", + "render.shots_result": "რენდერი {number} · {width} × {height}", + "render.shots_revert": "წინა ვერსიაზე დაბრუნება", + "render.shots_save": "კადრის შენახვა", + "render.shots_update": "კადრის განახლება", + "render.show_shots_label": "კადრების ზოლის ჩვენება", + "render.size_4k": "4K", + "render.size_4k_uhd": "4K UHD", + "render.size_custom": "მორგებული…", + "render.size_full_hd": "Full HD", + "render.size_hd": "HD", + "render.size_needs_profile": "{size} · საჭიროა {profile}", + "render.size_presets": "ზომის პრესეტები", + "render.size_presets_pending": "გამოჩნდება გამოტანის რედაქტორთან ერთად", + "render.size_preview": "წინასწარი ნახვა", + "render.size_square": "კვადრატი", + "render.sky_ground": "მიწა · წრფივი RGB", + "render.sky_horizon": "ჰორიზონტი · წრფივი RGB", + "render.sky_zenith": "ზენიტი · წრფივი RGB", + "render.soft_focus": "რბილი ფოკუსი", + "render.spot_cone": "პროჟექტორის კონუსი", + "render.stage_frame": "კადრირება", + "render.stage_layout.appearance_note": "დაწკაპეთ მონიშნულზე გამოსაყენებლად.", + "render.stage_layout.studio_note": "დაწკაპეთ, რომ გამოყენებამდე გადახედოთ.", + "render.stage_light": "განათება", + "render.stage_look": "ვიზუალური სტილი", + "render.stage_orthographic": "ორთოგრაფიული", + "render.stage_output": "გამოტანა", + "render.stage_panel_count": "შენახული პანელები", + "render.stage_panels.acknowledge": "ვადასტურებ ჩანაცვლებას და შეზღუდვებს", + "render.stage_panels.appearance_note": "დაწკაპეთ მონიშნულზე გამოსაყენებლად. გადაიტანეთ მოდელზე. როცა არაფერია მონიშნული, დაწკაპება შეღებვას ააქტიურებს.", + "render.stage_panels.apply": "გამოყენება", + "render.stage_panels.apply_studio": "სტუდიის გამოყენება", + "render.stage_panels.badge_blocked": "დაბლოკილი", + "render.stage_panels.badge_native": "საკუთარი", + "render.stage_panels.badge_projection": "პროექცია", + "render.stage_panels.badge_reference": "ეტალონი", + "render.stage_panels.badge_specification": "მხოლოდ სპეციფიკაცია", + "render.stage_panels.candidate_summary": "კანდიდატები: წყაროთი დადასტურებული მნიშვნელობა: {count}. ხარისხი და ზედაპირის დამუშავება გადასახედია.", + "render.stage_panels.captured_bounds": "სცენის დაფიქსირებული საზღვრების გამოყენება", + "render.stage_panels.centre": "ცენტრი", + "render.stage_panels.depth": "სიღრმე", + "render.stage_panels.environments": "გარემოები", + "render.stage_panels.extent": "გაბარიტი", + "render.stage_panels.fit_save": "მორგება და შენახვა", + "render.stage_panels.gpu_required": "საჭიროა GPU ბილიკების ტრასირება", + "render.stage_panels.keep": "დატოვება", + "render.stage_panels.kept": "შენარჩუნებულია", + "render.stage_panels.kept_fields": "კამერა, სემპლირება, ზომები, ოპტიკური მიბმები, CAD გეომეტრია და საინჟინრო თვისებები.", + "render.stage_panels.kept_quality": "მეთოდი, კამერა, განათება, გარემო, სცენა, ოპტიკა, ექსპოზიცია და ტონალური ასახვა.", + "render.stage_panels.mine": "ჩემი", + "render.stage_panels.mine_pending": "პირადი სტუდიების შენახვა ჯერ არ არის მხარდაჭერილი.", + "render.stage_panels.omits": "გამოტოვებულია", + "render.stage_panels.paint_pending": "შეღებვა და გადატანით მინიჭება ჯერ არ არის მხარდაჭერილი. ვიზუალური სტილის გამოსაყენებლად აირჩიეთ სამიზნე.", + "render.stage_panels.partial_reference": "კანდიდატები: მხოლოდ წყაროთი დადასტურებული მნიშვნელობები; გადახედეთ ხარისხს, მდგომარეობას და წყაროებს. უცნობი მნიშვნელობები უცნობად რჩება.", + "render.stage_panels.plane": "სიბრტყე", + "render.stage_panels.prepare_plan": "შექმნის გეგმის მომზადება", + "render.stage_panels.projects": "პროექცია", + "render.stage_panels.quality_ack": "ვადასტურებ ფიქსირებულ ბიუჯეტს და მის გამოტოვებებს", + "render.stage_panels.quality_omissions": "ადაპტური შეჩერება და ცდომილების მიზნები, გატარების ცალკე სიღრმე, „რუსული რულეტკის“ წესები, დაუმუშავებელი წრფივი გამოტანა, EXR მასტერი და კრებადობის სერტიფიცირება.", + "render.stage_panels.reference": "ეტალონი", + "render.stage_panels.references": "ეტალონები", + "render.stage_panels.remove_optics": "ოპტიკის მოცილება", + "render.stage_panels.remove_optics_help": "ამ კადრიდან შლის შენახულ ოპტიკას. საწყისი გეომეტრია რჩება.", + "render.stage_panels.remove_optics_title": "წაიშალოს შენახული ოპტიკა?", + "render.stage_panels.remove_shot": "კადრის წაშლა", + "render.stage_panels.remove_stage": "სცენის წაშლა", + "render.stage_panels.remove_stage_help": "ამ კადრიდან შლის შენახულ პასიურ პანელებს. კამერის ფონი რჩება.", + "render.stage_panels.remove_stage_title": "წაიშალოს შენახული სცენა?", + "render.stage_panels.repeat": "გამეორება", + "render.stage_panels.replaces": "ანაცვლებს", + "render.stage_panels.replaces_environment": "გარემო", + "render.stage_panels.replaces_maps": "დროებითი რუკები არჩეულ სხეულზე; შენახული ოპტიკა შეიძლება კონფლიქტში მოვიდეს.", + "render.stage_panels.replaces_physical": "არაფერს. ეს გეგმა მხოლოდ საკითხავია.", + "render.stage_panels.replaces_quality": "გამოსახულების ზომები, სემპლების ფიქსირებული რაოდენობა, ბილიკის სიღრმე, seed და ხმაურის მოცილება.", + "render.stage_panels.replaces_rig": "განათება, გარემო და სცენა", + "render.stage_panels.replaces_saved_maps": "შენახული ზედაპირის რუკები არჩეულ სხეულზე; დროებითი გადაფარვები შეიძლება კონფლიქტში მოვიდეს.", + "render.stage_panels.replaces_stage": "შენახული მიწა და სცენის პასიური პანელები", + "render.stage_panels.replaces_studio": "განათება, გარემო, ექსპოზიცია და სცენა", + "render.stage_panels.replaces_uniform": "გაუმჭვირვალე იერსახე არჩეულ სხეულზე. სივრცული რუკები ერთგვაროვანი მნიშვნელობებით მიახლოვდება.", + "render.stage_panels.review_environment": "გარემოს გადახედვა", + "render.stage_panels.review_maps": "GPU რუკების გადახედვა", + "render.stage_panels.review_physical": "ფიზიკური ეტალონის გეგმა", + "render.stage_panels.review_quality": "სემპლირების ფიქსირებული ბიუჯეტის გამოყენება", + "render.stage_panels.review_rig": "განათების სისტემის მორგება", + "render.stage_panels.review_saved_maps": "შენახული რუკების გადახედვა", + "render.stage_panels.review_stage": "მიწისა და სცენის გადახედვა", + "render.stage_panels.review_studio": "საკუთარი სტუდიის გადახედვა", + "render.stage_panels.review_uniform": "ერთგვაროვანი იერსახის გადახედვა", + "render.stage_panels.rig_summary": "საავტორო განათების სისტემა · გამომსხივებელი: {emitters}, ბარათი: {cards}", + "render.stage_panels.rigs": "განათების სისტემები", + "render.stage_panels.save_maps": "რუკების შენახვა ამ კადრში", + "render.stage_panels.scope": "მოქმედების არე", + "render.stage_panels.search_studios": "სტუდიების ძიება", + "render.stage_panels.search_surfaces": "ზედაპირებისა და ეტალონების ძიება", + "render.stage_panels.source_note": "საავტორო ძირითადი ფერის საწყისი რუკა. არ არის გაზომილი მასალა.", + "render.stage_panels.specifications": "სპეციფიკაციები · მხოლოდ საკითხავი", + "render.stage_panels.studio_ack": "დაადასტურეთ განათების, გარემოს, ექსპოზიციისა და სცენის ჩანაცვლება", + "render.stage_panels.studio_note": "დაწკაპეთ გადასახედად. გამოყენება განათებას, გარემოს და სცენას მხოლოდ თქვენი დადასტურების შემდეგ ანაცვლებს. სინათლის წყაროები რედაქტირებადი რჩება.", + "render.stage_panels.studios": "სტუდიები", + "render.stage_panels.subtitle_environment": "ორიგინალური HDR გარემო · მთელი სცენა", + "render.stage_panels.subtitle_maps": "საავტორო სივრცული რუკები · დროებითი წინასწარი ნახვა", + "render.stage_panels.subtitle_physical": "მხოლოდ საკითხავი გეგმა · მასალა არ იქმნება და არ ენიჭება", + "render.stage_panels.subtitle_quality": "ფიქსირებული GPU ბიუჯეტი · მომავალი მოთხოვნები გამოტოვებულია", + "render.stage_panels.subtitle_rig": "საავტორო განათების სისტემა · გამომსხივებლები და პასიური ბარათები", + "render.stage_panels.subtitle_saved_maps": "საავტორო რუკები · ინახება ამ კადრთან ერთად", + "render.stage_panels.subtitle_stage": "ფიზიკური მიწა და სცენა · მორგებული ნაკეთობაზე", + "render.stage_panels.subtitle_studio": "საკუთარი სტუდია · ვრცელდება მთელ სცენაზე", + "render.stage_panels.subtitle_uniform": "ერთგვაროვანი მიახლოება · არ არის გაზომილი მასალა", + "render.stage_panels.surfaces": "ზედაპირები", + "render.stage_panels.surfaces_references": "ზედაპირები და ეტალონები", + "render.stage_panels.target": "სამიზნე", + "render.stage_panels.use_budget": "ამ ბიუჯეტის გამოყენება", + "render.stage_panels.use_maps": "GPU რუკების გამოყენება", + "render.stage_panels.use_uniform": "ერთგვაროვანის გამოყენება", + "render.stage_preview_note": "ჩაშენებული წინასწარი ნახვა · პირდაპირი სინათლე", + "render.state_completed": "დასრულებული გამოსახულება", + "render.state_in_progress": "გამოსახულება მზადდება", + "render.state_model": "მოდელის წინასწარი ნახვა", + "render.strip_label": "ზოლი", + "render.studio_add_area": "ფართობული სინათლის დამატება", + "render.studio_ambient": "გარემოს მუდმივი გამოსხივება", + "render.studio_ambient_rgb": "გარემოს მუდმივი გამოსხივება (წრფივი RGB)", + "render.studio_aperture": "დიაფრაგმის რადიუსი", + "render.studio_area": "ფართობული სინათლე", + "render.studio_area_help": "ოთხამდე ცალმხრივი მართკუთხედი. ორთოგონალური ნახევარწიბოები U და V განსაზღვრავს ზომას; U × V განათებული მხრისკენაა მიმართული. კოორდინატები მსოფლიო სივრცის მილიმეტრებშია.", + "render.studio_center": "ცენტრი X, Y, Z (mm)", + "render.studio_denoise": "ხმაურის შემცირება დასრულებულ გამოსახულებაში", + "render.studio_denoise_help": "საბოლოო ფილტრი, რომელიც კიდეებს ითვალისწინებს; წვრილი დეტალები შეიძლება დარბილდეს. მინა და მკვეთრად სარკისებრი ზედაპირები ფილტრს გვერდს უვლის.", + "render.studio_direction": "მიმართულება მზისკენ (X, Y, Z)", + "render.studio_environment": "გარემო", + "render.studio_environment_bounds": "გარემოს შემობრუნება უნდა იყოს სასრული, ±1,000,000 რადიანის ფარგლებში, ხოლო ინტენსივობა — 0-დან 100-მდე.", + "render.studio_environment_none": "გარემოს რუკის გარეშე", + "render.studio_focus": "ღერძული ფოკუსური მანძილი", + "render.studio_half_u": "ნახევარწიბო U (mm)", + "render.studio_half_v": "ნახევარწიბო V (mm)", + "render.studio_hdr": "Radiance HDR ფაილი", + "render.studio_hdr_browse": "HDR-ის არჩევა…", + "render.studio_hdr_help": "Radiance .hdr, 2:1 პანორამა, 2048 × 1024-მდე. EXR მიუწვდომელია. ფერის დაშვება მხოლოდ მაშინ მოქმედებს, როცა პირველადი ფერები მითითებული არ არის.", + "render.studio_hdr_required": "აირჩიეთ ლოკალური .hdr ფაილი.", + "render.studio_hdr_srgb": "მიუთითებელი პირველადი ფერების წრფივ sRGB-დ ინტერპრეტაცია", + "render.studio_intensity": "გარემოს ინტენსივობა", + "render.studio_lens": "ველის სიღრმე", + "render.studio_lens_perspective": "ველის სიღრმეს პერსპექტიული კამერა სჭირდება.", + "render.studio_lighting": "სტუდიური განათება", + "render.studio_lighting_enable": "სტუდიის საკუთარი განათების გამოყენება", + "render.studio_needs_review": "გადახედეთ მეთოდს და პარამეტრებს", + "render.studio_radiance": "წრფივი RGB გამოსხივება", + "render.studio_ready": "მზადაა შესამოწმებლად", + "render.studio_remove_area": "ფართობული სინათლის წაშლა", + "render.studio_rotation": "გარემოს შემობრუნება", + "render.studio_runtime_help": "სტუდიის რიცხვითი პარამეტრები და შემოწმებული HDR წყაროები შეიძლება შეინახოს გამართვასთან ერთად. სხეულის ოპტიკური/მასალის გადაფარვები დროებითი რჩება და შენახულ იერსახეებს არ ცვლის.", + "render.studio_saved": "შენახული გამართვა / მიმდინარე კამერა", + "render.studio_sky": "მხატვრული ცა", + "render.studio_sky_help": "ცის ორიგინალური გრადიენტი განათებისთვის; არ არის კალიბრებული ატმოსფერული მოდელი.", + "render.studio_sun": "მზე", + "render.studio_sun_radius": "კუთხური რადიუსი", + "render.studio_tiles_require_gpu": "სტუდიებს GPU ბილიკების ტრასირება სჭირდება. აირჩიეთ GPU გამოტანის რედაქტორში.", + "render.studio_title": "რენდერის სტუდია", + "render.studio_tone_map": "ტონალური ასახვა", + "render.studios_environments": "სტუდიები და გარემოები", + "render.subsurface_enable": "შიდა გაბნევის შემთხვევითი ხეტიალი", + "render.subsurface_help": "მხოლოდ ჩაკეტილი დიელექტრიკი. გაბნევა და RGB შთანთქმა ცალკეული კოეფიციენტებია მილიმეტრზე. ბილიკები რეალური გეომეტრიის შიგნით იბნევა, შემდეგ საზღვარზე გარდატყდება ან აირეკლება. გამორთეთ ჩრდილის პირდაპირი გატარება, ზედაპირის ხმაურის მოცილება და გარე მოცულობა; გამოიყენეთ ფრენელის ერთი სტრატა. არ არის დიფუზიის შეიდერი, სიმკვრივის ბადე ან გაზომილი მასალა. მკვრივ გარემოს შეიძლება მეტი სემპლი და ბილიკის სიღრმე დასჭირდეს.", + "render.subsurface_rate": "გაბნევისას შეჯახების სიხშირე", + "render.tone_aces_fitted": "ACES fitted", + "render.tone_reinhard": "Reinhard", + "render.transmission_scope": "GPU მინა სერტიფიცირებულ, ერთმანეთისგან განცალკევებულ გარემოებს უჭერს მხარს. შეუზღუდავი ჩადგმული გარემოები და უხმაურო გატარების შემფასებელი არ არის.", + "render.transmission_strata": "ფრენელის პირობითი სტრატები", + "render.transmission_strata_help": "1 ორიგინალურ ნაკადს ინარჩუნებს. 2 ან 4 ქვებილიკი მინაში პირველ არეკვლა/გატარების არჩევანს სტრატიფიცირებს სნელისა და შთანთქმის უცვლელი კანონებით. მეტი ბილიკი მეტ სამუშაოს ნიშნავს; ეს არ არის ხმაურის მოცილება, ჩადგმული გარემოების მხარდაჭერა ან უფრო სწრაფი რენდერინგის დაპირება.", + "render.tree_add_light": "სინათლის წყაროს დამატება", + "render.tree_add_shot": "კადრის დამატება", + "render.tree_browser": "რენდერის ხე", + "render.tree_by_look": "ვიზუალური სტილის მიხედვით", + "render.tree_by_object": "ობიექტის მიხედვით", + "render.tree_constant": "მუდმივი გარემო", + "render.tree_default": "ნაგულისხმევი", + "render.tree_directional": "მიმართული", + "render.tree_environment": "გარემო", + "render.tree_environment_values": "{rotation}° · {intensity}×", + "render.tree_face_count": "წახნაგი: {count}", + "render.tree_face_one": "წახნაგი: {count}", + "render.tree_fixed_studio": "ფიქსირებული სტუდია", + "render.tree_hdr": "HDR", + "render.tree_lights": "სინათლის წყაროები", + "render.tree_lights_pending": "სახელდებული სინათლის წყაროების ბრძანებები ჯერ მიუწვდომელია.", + "render.tree_mixed": "შერეული", + "render.tree_more": "კიდევ {count}", + "render.tree_mute": "სინათლის წყაროს დადუმება", + "render.tree_no_environment": "გარემოს გარეშე", + "render.tree_objects": "ობიექტები", + "render.tree_output": "გამოტანა", + "render.tree_point": "წერტილოვანი", + "render.tree_rectangle": "მართკუთხა", + "render.tree_search": "ობიექტების ძიება", + "render.tree_selection": "რენდერის მონიშნული", + "render.tree_shots": "კადრები", + "render.tree_sky": "ცა", + "render.tree_solo": "სინათლის წყაროს სოლო", + "render.tree_spot": "პროჟექტორი", + "render.tree_sun": "მზე", + "render.tree_switch": "გადართვა", + "render.tree_user_one": "ობიექტი: {count}", + "render.tree_users": "ობიექტი: {count}", + "render.unavailable_preview": "ეს გამართვა მიუწვდომელ წინასწარი ნახვის პროფილს ითხოვს.", + "render.unsaved": "წინასწარი ნახვის შეუნახავი ცვლილებები", + "render.use_preview": "ჩაშენებული წინასწარი ნახვის გამოყენება", + "render.volume_albedo": "გაბნევის ალბედო · წრფივი RGB", + "render.volume_anisotropy": "ფაზის საშუალო კოსინუსი", + "render.volume_enable": "მონაწილე გარემოს ჩართვა", + "render.volume_extinction": "ჩაქრობის კოეფიციენტი", + "render.volume_help": "GPU გადატანა ერთ სასრულ ყუთში, ბირის მილევით და HG გაბნევით კამერისა და არაპირდაპირ ბილიკებზე. იყენებს აშკარა სტუდიურ/HDR/ცის განათებას, ჩრდილის მილევის ჩათვლით. ფაზის დადებითი კოსინუსი წინ გაბნევას იწვევს. მინის საზღვრები და ზედაპირის ხმაურის მოცილება ცალკე უნდა გამოირთოს. ნულოვანი ჩაქრობა გადატანას არ ცვლის. არ არის მთვარის ფიზიკური ატმოსფერო, სიმკვრივის ბადე, მოცულობითი გამოსხივება, სპექტრული გადატანა ან მასალის სერტიფიცირებული თვისება.", + "render.volume_max": "მაქსიმალური საზღვრები · მსოფლიო mm", + "render.volume_min": "მინიმალური საზღვრები · მსოფლიო mm", + "render.volume_title": "შემოსაზღვრული ერთგვაროვანი მოცულობა", + "render.wait_add_light": "ჯერ არ არის მხარდაჭერილი: სახელდებული სინათლის წყაროს შექმნა", + "render.wait_batch": "ჯერ არ არის მხარდაჭერილი: შენახული კადრების რენდერის რიგი", + "render.wait_compare": "ჯერ არ არის მხარდაჭერილი: შენახული გამოსახულებების შედარება", + "render.wait_paint": "ჯერ არ არის მხარდაჭერილი: ნაკეთობის არჩევა და იერსახით შეღებვა", + "render.wait_pick_up": "ჯერ არ არის მხარდაჭერილი: ნაკეთობის არჩევა და იერსახის აღება", + "render.wait_replace": "ჯერ არ არის მხარდაჭერილი: იერსახის ყველა გამოყენების ჩანაცვლება", + "render.wait_solo": "ჯერ არ არის მხარდაჭერილი: სინათლის წყაროს ხილვადობისა და სოლოს მართვა", + "render.wear_applies_to": "ვრცელდება", + "render.wear_layer_count": "შრე: {count}", + "render.wear_layer_one": "შრე: {count}", + "render.wear_layers": "შრეები", + "render.wear_no_layers": "შრეების გარეშე", + "render.wear_selected_layer": "მონიშნული შრე", + "render.wear_title": "ცვეთა", + "sample.bracket.about": "საბაზო ფლანეცი წიბოს ფლანეცებით და წიბოს გადაკეცვით, 2 mm-იან წესზე", + "sample.bracket.name": "ფურცლოვანი ლითონის კრონშტეინი", + "sample.enclosure.about": "გარსით დამუშავებული ყუთი ბორტით, ხრახნის დგარებით, საყრდენით და ჩამკეტი სამაგრით", + "sample.enclosure.name": "პლასტმასის კორპუსი", + "sample.flange.about": "მილისა და ფლანეცის კვანძი წრიული მასივით, რომელსაც პარამეტრი მართავს", + "sample.flange.name": "ჭანჭიკიანი ფლანეცი", + "sample.hinge.about": "ორი კომპონენტი და მბრუნავი შეერთება, 60°-მდე მობრუნებული", + "sample.hinge.name": "ანჯამის აწყობა", + "sample.plate.about": "პარამეტრული ფირფიტა მომრგვალებებით, ხვრელებით და გაბურღული დგარით", + "sample.plate.name": "ნიმუშის ფირფიტა", + "sample.vents.about": "ღრეჩოები მართკუთხა მასივში: მწკრივები, სვეტები და ბიჯი პარამეტრებია", + "sample.vents.name": "სავენტილაციო ფირფიტა", + "search.command_keys": "Enter გაშვება Shift+Enter გაშვება და ღიად დატოვება Esc დახურვა", + "search.commands": "ბრძანებები", + "search.design": "ამ პროექტში", + "search.feature": "ოპერაცია", + "search.invalid": "არავალიდური", + "search.keys": "↑ ↓ არჩევა Enter გაშვება Tab სახელის შევსება Esc დახურვა", + "search.no_match": "'{query}'-ს არცერთი ბრძანება არ ემთხვევა", + "search.parameter": "პარამეტრი", + "search.recent": "ბოლოდროინდელი", + "search.run": "ბრძანების გაშვება", + "search.suggest": "ხომ არ გულისხმობდით: {label}?", + "search.try": "აკრიფეთ ბრძანების სახელი, ამ პროექტის ოპერაცია ან პარამეტრი. ბრძანების მნიშვნელობებით გასაშვებად აკრიფეთ მისი id და JSON ობიექტი: {example}", + "search.valid": "ვალიდური", + "section.off_hint": "სიბრტყე არჩეული არ არის: OK კვეთს გამორთავს.", + "select a direction (an axis, a sketch line or a straight edge) first": "ჯერ აირჩიეთ მიმართულება (ღერძი, ესკიზის ხაზი ან სწორი წიბო)", + "select a direction (an axis, a sketch line or a straight edge) for the profile to follow": "აირჩიეთ მიმართულება (ღერძი, ესკიზის ხაზი ან სწორი წიბო), რომელსაც პროფილი გაჰყვება", + "select a point on a component": "აირჩიეთ წერტილი კომპონენტზე", + "select a profile, edges or sketch lines first": "ჯერ აირჩიეთ პროფილი, წიბოები ან ესკიზის ხაზები", + "select an axis": "აირჩიეთ ღერძი", + "select an axis, a straight or circular edge, or a cylinder, cone or torus face first": "ჯერ აირჩიეთ ღერძი, სწორი ან წრიული წიბო, ან ცილინდრის, კონუსის ან ტორის წახნაგი", + "select bodies first": "ჯერ აირჩიეთ სხეულები", + "select components first": "ჯერ აირჩიეთ კომპონენტები", + "select corner points, or the two lines of one corner": "აირჩიეთ კუთხის წერტილები ან ერთი კუთხის ორი ხაზი", + "select one corner point, or the two lines of one corner": "აირჩიეთ კუთხის ერთი წერტილი ან ერთი კუთხის ორი ხაზი", + "select sheet edges first": "ჯერ აირჩიეთ ფურცლის წიბოები", + "select the bend line (a sketch line) first": "ჯერ აირჩიეთ მოღუნვის ხაზი (ესკიზის ხაზი)", + "select the cam's profile (a sketch profile or the cam's edges)": "აირჩიეთ კულაჩის პროფილი (ესკიზის პროფილი ან კულაჩის წიბოები)", + "select the corner to cut first": "ჯერ აირჩიეთ ამოსაჭრელი კუთხე", + "select the corners to round first": "ჯერ აირჩიეთ მოსამრგვალებელი კუთხეები", + "select the fixed face first (a plate's large face)": "ჯერ აირჩიეთ ფიქსირებული წახნაგი (ფირფიტის დიდი წახნაგი)", + "select the frame sketch's lines first": "ჯერ აირჩიეთ ჩარჩოს ესკიზის ხაზები", + "select the path (sketch lines across the edge)": "აირჩიეთ ტრაექტორია (ესკიზის ხაზები წიბოს გასწვრივ)", + "select the rim face first": "ჯერ აირჩიეთ ბორტის წახნაგი", + "select the sheet edge first": "ჯერ აირჩიეთ ფურცლის წიბო", + "select two components": "აირჩიეთ ორი კომპონენტი", + "set by the sketch's lines": "განისაზღვრება ესკიზის ხაზებით", + "settings.display_quality_note": "მხოლოდ ეკრანზე ჩვენება. პროექტებსა და ექსპორტზე გავლენა არ აქვს.", + "settings.double_click_components": "ორმაგი დაწკაპებით კომპონენტის გააქტიურება ან დაკავშირებულის ადგილზე რედაქტირება", + "settings.frame_rate_details_note": "ამატებს ბოლო კადრების დროების გრაფიკს მასზე დახატული სამკუთხედებით, კადრის დროების ჰისტოგრამას და იმას, რაც GPU-მ დახატა. მათ საჩვენებლად ან დასამალად ხედში დაწკაპეთ კადრების სიხშირეზე.", + "settings.frame_rate_note": "ხედის ქვედა მარჯვენა კუთხეში აჩვენებს კადრების რაოდენობას წამში.", + "settings.insert_lists_open_designs": "პროექტის ჩასმა ჯერ სხვა ჩანართებში გახსნილ პროექტებს ჩამოთვლის", + "settings.measure_axis_distances": "X/Y/Z მანძილების ჩვენება", + "settings.measure_axis_distances_help": "გაზომვის გახსნისას საერთო მანძილთან ერთად მსოფლიო ღერძების გასწვრივ მდგენელების ჩვენება.", + "settings.msaa_applies_on_restart": "ანტიალიასინგი SolidCraft-ის შემდეგი გაშვებისას ამოქმედდება", + "settings.msaa_reset": "{setting}: {requested}× ამ გრაფიკულ მოწყობილობას არ აქვს მხარდაჭერილი; ახლა არის {reset}× (მხარდაჭერილი: {supported}).", + "settings.msaa_unsupported": "ამ გრაფიკულ მოწყობილობას არ აქვს მხარდაჭერილი", + "settings.reference_geometry_through_bodies": "ორიენტირების ჩვენება სხეულებში გამჭოლად", + "settings.reference_geometry_through_bodies_help": "არააქტიური ესკიზების კონტურებისა და საბაზო სიბრტყეების დახატვა დაჩრდილულ სხეულებზე ზემოდან", + "settings.reset_intro": "ეს პარამეტრები ამ კომპიუტერზე არ მუშაობს და SolidCraft-ს გაშვებას შეუშლიდა, ამიტომ შეიცვალა:", + "settings.reset_title": "პარამეტრები შეიცვალა", + "settings.supersampling_note": "ხედს უფრო მაღალი გარჩევადობით ხატავს და ფილტრით ამცირებს: უფრო გლუვი კიდეები, ხაზები და ბადე 4K-ზე დაბალ ეკრანებზე. ეს GPU-ს დროს მოითხოვს: დაახლოებით 2.25× პიქსელი 1.5×-ზე და 4× — 2×-ზე.", + "settings.update_changed_links": "დაკავშირებული შეცვლილი პროექტების განახლება ჩანართზე დაბრუნებისას", + "settings.window_system_details": "დეტალები", + "settings.window_system_note_now": "ამოქმედდება გადატვირთვის შემდეგ. ახლა: {now}.", + "settings.window_system_wayland_limited": "ზოგი ფუნქცია შეზღუდულია ნატიურ Wayland-ზე.", + "sheet.flange_type_base": "საბაზო", + "sheet.flange_type_contour": "კონტურული", + "sheet.flange_type_edge": "წიბოს", + "sheet.no_body": "ფურცლოვანი ლითონის სხეული არ არის: დაიწყეთ ბრძანებით ფლანეცი > საბაზო, ან ფირფიტა ფურცლოვან ლითონად გარდაქმენით ბრძანებით „ფურცლოვან ლითონად გარდაქმნა“ (აირჩიეთ მისი დიდი ბრტყელი წახნაგი)", + "sheet.personal_rules.confirm_delete": "წაშლის დადასტურება", + "sheet.personal_rules.delete": "წაშლა", + "sheet.personal_rules.delete_prompt": "წაიშალოს ეს პირადი წესი? პროექტებში უკვე არსებული წესები არ შეიცვლება.", + "sheet.personal_rules.full": "პირად ბიბლიოთეკაში უკვე 64 წესია.", + "sheet.personal_rules.invalid_name": "შეიყვანეთ მოკლე სახელი სტრიქონის წყვეტებისა და მმართველი სიმბოლოების გარეშე.", + "sheet.personal_rules.invalid_values": "შეავსეთ წესის მნიშვნელობები: თითოეული ამ პროექტში უნდა გამოითვლებოდეს, დადებითი სისქით და K-ფაქტორით 0-დან 1-მდე.", + "sheet.personal_rules.missing": "არჩეული პირადი წესი აღარ არის ხელმისაწვდომი.", + "sheet.personal_rules.name": "წესის სახელი", + "sheet.personal_rules.name_exists": "პირადი წესი ამ სახელით უკვე არსებობს. გამოიყენეთ სხვა სახელი.", + "sheet.personal_rules.name_hint": "უნიკალური სახელი", + "sheet.personal_rules.overwrite": "ცვლილებების შენახვა არჩეულ პირად წესში", + "sheet.personal_rules.rename": "სახელის შეცვლა", + "sheet.personal_rules.rule": "პირადი წესი", + "sheet.personal_rules.save": "ახლის შენახვა", + "sheet.personal_rules.scope": "ინახება თქვენს პროფილში ყველა პროექტისთვის.", + "sheet.personal_rules.select": "აირჩიეთ წესი", + "sheet.personal_rules.title": "პირადი წესები", + "sheet.personal_rules.unsupported": "ამ წესს აქვს მნიშვნელობები, რომლებსაც ეს ვერსია ვერ იყენებს.", + "shortcut.json_error": "პარამეტრები JSON-ში უნდა იყოს: {error}", + "shortcut.no_command": "ბრძანება `{id}` არ არსებობს; JSON-მდე ტექსტი ბრძანების id უნდა იყოს", + "shortcut.pin": "S ველის თავში მიმაგრება", + "shortcut.unpin": "მოხსნა", + "sketch is missing": "ესკიზი აკლია", + "sketch.degrees_of_freedom": "თავისუფლების ხარისხი: {count}", + "sketch.dimension_added_driven": "ესკიზი ამ ზომას უკვე განსაზღვრავს, ამიტომ ის დაემატა როგორც მართული (საცნობარო) ზომა", + "sketch.dimension_applied": "ზომა დადებულია", + "sketch.dimension_applied_defined": "ზომა დადებულია; განისაზღვრა პარამეტრი `{name}`", + "sketch.dimension_applied_renamed": "ზომა დადებულია; პარამეტრს ეწოდა `{name}`", + "sketch.dof_left": "დარჩენილი თავისუფლების ხარისხი: {count}", + "sketch.dof_left_one": "დარჩენილი თავისუფლების ხარისხი: {count}", + "sketch.draw_curves": "ხატვა როგორც {linetype}", + "sketch.make_selection": "მონიშნულის გარდაქმნა: {linetype}", + "sketch.open_ends": "ღია ბოლო: {count}", + "sketch.status_conflict": "შეზღუდვები ეწინააღმდეგება ერთმანეთს", + "sketch.status_fully_constrained": "სრულად შეზღუდული", + "sketch.untied_ends": "მიუბმელი: {count}", + "sketch_panel.attached": "მიმაგრებულია: {body} / {path}", + "sketch_panel.author": "საავტორო განლაგება: {path}", + "sketch_panel.dimension_hint": "შეიყვანეთ მნიშვნელობა ან გამოსახულება, შემდეგ დააჭირეთ OK-ს.", + "sketch_panel.move_hint": "შეიყვანეთ მანძილები და კუთხე, შემდეგ დააჭირეთ OK-ს.", + "sketch_panel.plane_angle": "{plane}, შემობრუნებული {angle}-ით", + "sketch_panel.plane_fixed": "ფიქსირებული სიბრტყე", + "sketch_panel.plane_flipped": "{plane}, მეორე მხრიდან", + "sketch_panel.plane_offset": "{plane}, წანაცვლებული {distance}-ით", + "sketch_panel.plane_origin": "სიბრტყე {plane}", + "sketch_panel.redefine_title": "{command}: {name}", + "sketch_panel.sheet_attachment": "მიმაგრებულია ფურცლოვანი ლითონის სხეულის ბრტყელ წახნაგზე; ფურცლის შეცვლისას იმ პანელს მიჰყვება.", + "sketch_panel.text_hint": "შეცვალეთ ტექსტი და მისი განლაგება, შემდეგ დააჭირეთ OK-ს.", + "sketch_panel.use_plane": "სიბრტყის {plane} გამოყენება", + "sketch_text.align_center": "ცენტრში", + "sketch_text.align_left": "მარცხნივ", + "sketch_text.align_right": "მარჯვნივ", + "sketch_text.bold": "მუქი", + "sketch_text.builtin_font": "{family} (ჩაშენებული)", + "sketch_text.formula": "დაიწყეთ = ნიშნით, რომ სიტყვები პარამეტრებისგან ააწყოთ: ='W' + number(Width)", + "sketch_text.italic": "დახრილი", + "sketch_text.loading_fonts": "დაინსტალირებული შრიფტების ძებნა…", + "sketch_text.no_bold": "ჩაშენებულ შრიფტს მუქი მოხაზულობა არ აქვს: აირჩიეთ დაინსტალირებული შრიფტი", + "sketch_text.on_path": "ტექსტი თავის ტრაექტორიას მიჰყვება: მის მდებარეობას მრუდი განსაზღვრავს", + "sketch_text.path_clear": "ტექსტის მოხსნა მრუდიდან", + "sketch_text.path_hint": "ესკიზის მრუდი, რომელსაც ტექსტი მიჰყვება: დაწკაპეთ აქ, შემდეგ მრუდზე", + "sketch_text.use_font_file": "შრიფტის ფაილის {path} გამოყენება", + "solid": "სხეული", + "status.editing": "რედაქტირდება {name}", + "status.navigation": "მაუსის მინიჭება: {mapping}", + "status.navigation_tip": "როგორ გადაადგილებს მაუსი ხედს. დაწკაპეთ სხვა მინიჭების ასარჩევად", + "status.under_constrained": "არასრულად შეზღუდული (თავისუფლების ხარისხი: {count})", + "status.under_constrained_one": "არასრულად შეზღუდული (თავისუფლების ხარისხი: {count})", + "status.units_tip": "პროექტის ერთეულები. დაწკაპეთ შესაცვლელად", + "the angle must be a number": "კუთხე რიცხვი უნდა იყოს", + "the curves must be in one sketch": "მრუდები ერთ ესკიზში უნდა იყოს", + "the direction must be an axis, a sketch line or a straight edge": "მიმართულება უნდა იყოს ღერძი, ესკიზის ხაზი ან სწორი წიბო", + "the duration must be a number of seconds, 0.001 or more": "ხანგრძლივობა წამების რიცხვი უნდა იყოს, 0.001 ან მეტი", + "the line's sketch is gone": "ხაზის ესკიზი აღარ არსებობს", + "the lines must be in one sketch": "ხაზები ერთ ესკიზში უნდა იყოს", + "the lines must be in one sketch, not the section's": "ხაზები ერთ ესკიზში უნდა იყოს და არა კვეთისაში", + "the parts library is empty": "დეტალების ბიბლიოთეკა ცარიელია", + "the parts library is not available": "დეტალების ბიბლიოთეკა მიუწვდომელია", + "the path curves must be in one other sketch": "ტრაექტორიის მრუდები ერთ სხვა ესკიზში უნდა იყოს", + "the path's sketch is gone": "ტრაექტორიის ესკიზი აღარ არსებობს", + "the position must be a number": "პოზიცია რიცხვი უნდა იყოს", + "the preview failed": "წინასწარი ნახვა ვერ მოხერხდა", + "the profiles and curves must be in one sketch": "პროფილები და მრუდები ერთ ესკიზში უნდა იყოს", + "the reference face must be on the edges' body": "ორიენტირად არჩეული წახნაგი წიბოების სხეულზე უნდა იყოს", + "the scale must be above 0": "მასშტაბი 0-ზე მეტი უნდა იყოს", + "the section's profiles must be in one sketch": "კვეთის პროფილები ერთ ესკიზში უნდა იყოს", + "the two origins are on the same component": "ორივე სათავე ერთსა და იმავე კომპონენტზეა", + "thread.automatic_size": "ავტომატური ზომა", + "thread.chamfer_depth_needed": "ამ ფორმისთვის სავალდებულოა", + "thread.designation": "აღნიშვნა", + "thread.drill_range": "ხრახნის მწარმოებლის ბურღი {drill} mm-ია. შიდა კუთხვილის სტანდარტული შიდა დიამეტრი {minor} mm-ია. მიიღება ბურღი {low}-დან {high} mm-მდე.", + "thread.drill_range_custom": "ბურღი არის გარე დიამეტრს გამოკლებული ბიჯი, {drill} mm. შიდა კუთხვილის სტანდარტული შიდა დიამეტრი {minor} mm-ია. მიიღება ბურღი {low}-დან {high} mm-მდე.", + "thread.drill_range_taper": "ხრახნის მწარმოებლის ბურღი {drill} mm-ია. სტანდარტის შიდა დიამეტრი კუთხვილის ბოლოში {minor} mm-ია. მიიღება ბურღი {low}-დან {high} mm-მდე.", + "thread.end_square": "სწორი", + "thread.fade_short": "1.25 P (ISO 3508)", + "thread.fade_standard": "2.5 P (ISO 3508)", + "thread.fits_the_face": "წახნაგს ერგება, მაგ. {example}", + "thread.form_bspp": "მილის G (ISO 228-1)", + "thread.form_bspt": "მილის კონუსური R, Rc (ISO 7-1)", + "thread.form_npt": "მილის კონუსური NPT (ASME B1.20.1)", + "thread.form_rp": "მილის Rp (ISO 7-1)", + "thread.iso_metric": "ISO მეტრული", + "thread.select_size": "აირჩიეთ ზომა", + "timeline.delete_after_marker_one": "ისტორიის მარკერის შემდეგ 1 ოპერაციის წაშლა", + "timeline.delete_after_marker_other": "ისტორიის მარკერის შემდეგ ოპერაციების წაშლა ({count})", + "timeline.delete_folders_tip": "მათი ოპერაციები და ჩადგმული საქაღალდეები ისტორიაში დარჩება", + "timeline.delete_folders_with_features_tip": "საქაღალდეების წაშლა მათში არსებული ყველა ოპერაციით და ჩადგმული საქაღალდეებით", + "timeline.delete_many": "მონიშნული ოპერაციების წაშლა ({count})", + "timeline.edited_rolled_back": "{name} შეიცვალა, მაგრამ ისტორიის მარკერის შემდეგაა, ამიტომ არ აიგება: შედეგის სანახავად მარკერი მის იქით გადაწიეთ", + "timeline.feature_error": "შეცდომა: {message}", + "timeline.feature_hint": "ორმაგი დაწკაპება — რედაქტირება · გადათრევა — გადალაგება · მარჯვენა დაწკაპება — მეტი", + "timeline.feature_rolled_back": "უკან გადაწეულია: ისტორიის მარკერის შემდეგაა, ამიტომ არ აიგება", + "timeline.feature_warning": "გაფრთხილება: {message}", + "timeline.group": "ოპერაციების ახალი საქაღალდე", + "timeline.move_many": "ქრონოლოგიის ელემენტების გადატანა", + "timeline.move_to_group": "ოპერაციების საქაღალდეში გადატანა", + "timeline.rename_group": "ოპერაციების საქაღალდის სახელის შეცვლა", + "timeline.reorder_many": "ოპერაციების გადალაგება", + "timeline.suppress_features": "ოპერაციების ჩახშობა", + "timeline.suppress_folders_tip": "საქაღალდეებსა და მათ ჩადგმულ საქაღალდეებში ყველა ოპერაციის ჩახშობა ან ჩახშობის მოხსნა", + "timeline.ungroup": "ოპერაციების საქაღალდეების მოშლა", + "timeline.unsuppress_features": "ოპერაციების ჩახშობის მოხსნა", + "to the face": "წახნაგამდე", + "to the next face": "შემდეგ წახნაგამდე", + "toolbar.customize_note": "ჩანართი {tab}. მონიშნეთ ბრძანება, რომ ხელსაწყოთა ზოლზე ღილაკი მიიღოს. შეგიძლიათ ასევე პანელის ჩამოსაშლელი სიის სტრიქონი ხელსაწყოთა ზოლზე გადაიტანოთ, ღილაკი ზოლიდან გადაათრიოთ მის მოსაცილებლად, ან ჩამოსაშლელი სიის სტრიქონზე სამაგრი გამოიყენოთ.", + "toolbar.image": "გამოსახულება", + "toolbar.render": "რენდერი", + "toolbar.render_appearance": "იერსახე", + "toolbar.render_camera": "კამერა", + "toolbar.render_environment": "გარემო", + "toolbar.render_lighting": "განათება", + "toolbar.render_lights": "სინათლის წყაროები", + "toolbar.render_result": "შედეგი", + "toolbar.render_scene": "სცენა", + "toolbar.render_stage": "სცენის ფონი", + "toolbar.render_studio": "სტუდია", + "trace.points": "ტრაექტორიის გასწვრივ წერტილი: {count}", + "trace.stopped_by_contact": "სრულდება სემპლზე {sample}: {a} {b}-ში გაივლიდა", + "trace.stopped_by_loop": "სრულდება სემპლზე {sample}: {joint}-ზე გამავალი კონტური უფრო მეტად ვეღარ შეიკვრება", + "trim by sketch curves, or by one plane or face": "მოკვეთა ესკიზის მრუდებით ან ერთი სიბრტყით ან წახნაგით", + "ui.1_degree_of_freedom": "თავისუფლების ხარისხი: 1", + "ui.3d_mouse_axes_reassigned": "ღერძები პარამეტრებშია გადანაწილებული და ეს ამ კალიბრაციის ზემოდანაც მოქმედებს.", + "ui.3d_mouse_button": "ღილაკი {number}", + "ui.3d_mouse_button_nothing": "არაფერი", + "ui.3d_mouse_button_settings": "3D მაუსის პარამეტრები", + "ui.3d_mouse_buttons": "ღილაკები", + "ui.3d_mouse_buttons_hint": "დააჭირეთ ღილაკს თქვენს 3D მაუსზე, რომ აქ იპოვოთ, შემდეგ აირჩიეთ, რას აკეთებს.", + "ui.3d_mouse_buttons_no_device": "მიაერთეთ 3D მაუსი, რომ მისი ღილაკების ფუნქციები დააყენოთ.", + "ui.3d_mouse_buttons_reset": "ნაგულისხმევი ღილაკების აღდგენა", + "ui.3d_mouse_calibrate": "კალიბრაცია…", + "ui.3d_mouse_calibrate_tip": "ამოძრავეთ თავსახური ისე, როგორც ფანჯარა გთხოვთ, რომ SolidCraft-მა გაიგოს, ამ 3D მაუსის თითოეული ღერძი რა მიმართულებით და რამდენად მოძრაობს. ინახება ამ 3D მაუსისთვის.", + "ui.3d_mouse_calibrate_title": "3D მაუსის კალიბრაცია", + "ui.3d_mouse_calibrate_wait": "ერთხელ ამოძრავეთ 3D მაუსი, რომ SolidCraft-მა დაინახოს.", + "ui.3d_mouse_calibrated": "კალიბრებულია", + "ui.3d_mouse_calibration": "კალიბრაცია", + "ui.3d_mouse_calibration_done": "მზადაა. შეინახეთ, რომ ეს 3D მაუსის მიერთებისას ყოველთვის გამოიყენოთ.", + "ui.3d_mouse_calibration_no_response": "ერთი ღერძი თითქმის არ განძრეულა, ამიტომ მისი კალიბრაცია შეუძლებელია. თავიდან დაიწყეთ და თავსახური ყოველ ჯერზე უფრო შორს გადაწიეთ.", + "ui.3d_mouse_circles_help": "წრეები აჩვენებს, რას აგზავნის მოწყობილობა კალიბრაციის შემდეგ. სატესტო მოდელი აჩვენებს, რას აკეთებს ამით ხედი ინვერსიის, სიჩქარისა და ღერძების მინიჭების შემდეგ.", + "ui.3d_mouse_dead_zone": "მკვდარი ზონა", + "ui.3d_mouse_dead_zone_tip": "რამდენად უნდა გადაიწიოს თავსახური, სანამ ხედი გადაადგილდება, მისი სრული სვლის წილად. გაზარდეთ, თუ ხედი მცოცავს, როცა თავსახური უძრავადაა.", + "ui.3d_mouse_denied": "SolidCraft ხედავს 3D მაუსს, მაგრამ მისი წაკითხვის უფლება არ აქვს. udev წესისთვის იხილეთ 3D მაუსის დაყენების შენიშვნები.", + "ui.3d_mouse_denied_short": "ნაპოვნია, მაგრამ არ იკითხება", + "ui.3d_mouse_driven_by": "მოწყობილობის რომელი კალიბრებული მოძრაობა მართავს ამ ღერძს. თუ აირჩევთ მოძრაობას, რომელსაც სხვა ღერძი უკვე იყენებს, ისინი ადგილებს გაცვლიან.", + "ui.3d_mouse_driven_by_label": "მართავს", + "ui.3d_mouse_driver": "დრაივერი", + "ui.3d_mouse_driver_auto": "ავტომატური", + "ui.3d_mouse_driver_direct": "პირდაპირი (hidraw)", + "ui.3d_mouse_driver_fallback": "ჯერჯერობით იკითხება spacenavd-ის გავლით: თავად მოწყობილობის გახსნა ვერ მოხერხდა.", + "ui.3d_mouse_driver_only_direct": "მოწყობილობა პირდაპირ იკითხება; spacenavd გაშვებული არ არის", + "ui.3d_mouse_driver_only_spacenavd": "იკითხება spacenavd-ის გავლით — ერთადერთი ხელმისაწვდომი გზით", + "ui.3d_mouse_forget": "კალიბრაციის დავიწყება", + "ui.3d_mouse_ghost_left_viewport": "ხედვის არის მარცხნივ", + "ui.3d_mouse_ghost_left_window": "ფანჯრის მარცხნივ", + "ui.3d_mouse_ghost_position": "პოზიცია", + "ui.3d_mouse_ghost_right_viewport": "ხედვის არის მარჯვნივ", + "ui.3d_mouse_hint": "ხედის ერთდროული გადაადგილება და შემობრუნება; ესკიზებში მხოლოდ პანორამა და მასშტაბი.", + "ui.3d_mouse_kind_cap": "ცენტრში დაბრუნებადი", + "ui.3d_mouse_kind_question": "რა ტიპის 3D მაუსია?", + "ui.3d_mouse_kind_trackball": "ტრეკბოლი", + "ui.3d_mouse_looks_like_cap": "ჩვენება უცვლელი რჩება, სანამ უჭერთ — ისე, როგორც ცენტრში დაბრუნებად მოწყობილობაზე.", + "ui.3d_mouse_looks_like_trackball": "ჩვენება უკან ბრუნდება, როგორც კი მოძრაობას შეწყვეტთ — ისე, როგორც ტრეკბოლზე.", + "ui.3d_mouse_motion_rotation_x": "შემობრუნება X", + "ui.3d_mouse_motion_rotation_y": "შემობრუნება Y", + "ui.3d_mouse_motion_rotation_z": "შემობრუნება Z", + "ui.3d_mouse_motion_translation_x": "გადაადგილება X", + "ui.3d_mouse_motion_translation_y": "გადაადგილება Y", + "ui.3d_mouse_motion_translation_z": "გადაადგილება Z", + "ui.3d_mouse_navigate": "ნავიგაცია 3D მაუსით", + "ui.3d_mouse_none": "3D მაუსი ვერ მოიძებნა", + "ui.3d_mouse_not_calibrated": "არ არის კალიბრებული", + "ui.3d_mouse_offer": "3D მაუსის კალიბრაცია ასწორებს გაცვლილ ან შებრუნებულ ღერძებს და აყენებს მის სიჩქარესა და შეგრძნებას.", + "ui.3d_mouse_offer_never": "აღარასოდეს ჩვენება", + "ui.3d_mouse_offer_swap": "Hidraw-ზე გადართვა (პირდაპირი დრაივერი)", + "ui.3d_mouse_orbit": "ორბიტა", + "ui.3d_mouse_orbit_classic": "კლასიკური", + "ui.3d_mouse_orbit_tip": "მიდევნებული: 3D მაუსი ხედს მოდელის იმ ნაწილის გარშემო აბრუნებს, რომელიც ბრუნვის დაწყებისას ხედის შუაშია და მკრთალი ბურთულით აღინიშნება. კლასიკური: ხედის ცენტრის გარშემო", + "ui.3d_mouse_orbit_traced": "მიდევნებული", + "ui.3d_mouse_reading": "ჩვენება", + "ui.3d_mouse_reset_axes": "ღერძების მინიჭების ჩამოყრა", + "ui.3d_mouse_reset_view": "ხედის ჩამოყრა", + "ui.3d_mouse_restore": "ნაგულისხმევის აღდგენა", + "ui.3d_mouse_restore_ask": "დაუბრუნდეს 3D მაუსის პარამეტრები ნაგულისხმევ მნიშვნელობებს? კალიბრაცია და ღილაკების მინიჭება შენარჩუნდება.", + "ui.3d_mouse_section": "3D მაუსი", + "ui.3d_mouse_show_in_view": "3D მაუსის ჩვენება 3D ხედში", + "ui.3d_mouse_show_in_view_tip": "თქვენი 3D მაუსის გამოსახულება ქვედა მარცხენა კუთხეში, რომელიც მოძრაობს, როცა მას ამოძრავებთ.", + "ui.3d_mouse_sketch_orbit": "ესკიზების შემობრუნება 3D მაუსით", + "ui.3d_mouse_sketch_orbit_tip": "3D მაუსი ხედს მაშინაც აბრუნებს, როცა ესკიზი ღიაა და პირდაპირ ჩანს, როგორც ეს მაუსს შეუძლია. გამორთული: ესკიზს მხოლოდ პანორამით და მასშტაბით გადაადგილებს, სანამ ხედს არ დახრით.", + "ui.3d_mouse_skip": "ჩემს მოწყობილობას ეს არ შეუძლია", + "ui.3d_mouse_skip_tip": "ამ მოძრაობას ორივე მიმართულებით გამოტოვებს და კალიბრაცია მას არ ითვალისწინებს.", + "ui.3d_mouse_speed": "3D მაუსის სიჩქარე", + "ui.3d_mouse_step_lift": "აწიეთ თავსახური, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_press": "ჩააჭირეთ თავსახური ქვემოთ, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_pull": "გამოსწიეთ თავსახური თქვენკენ, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_push": "გასწიეთ თავსახური თქვენგან, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_rest": "აიღეთ ხელი თავსახურიდან და დატოვეთ უძრავად.", + "ui.3d_mouse_step_rest_trackball": "აიღეთ ხელი ბურთიდან და დატოვეთ უძრავად.", + "ui.3d_mouse_step_ring_clockwise": "შეატრიალეთ გადახვევის რგოლი საათის ისრის მიმართულებით რამდენიმე დაწკაპებით.", + "ui.3d_mouse_step_ring_counterclockwise": "შეატრიალეთ გადახვევის რგოლი საათის ისრის საწინააღმდეგოდ რამდენიმე დაწკაპებით.", + "ui.3d_mouse_step_roll_away": "რამდენჯერმე გააგორეთ ბურთი თქვენგან, შემდეგ გააჩერეთ.", + "ui.3d_mouse_step_roll_left": "რამდენჯერმე გააგორეთ ბურთი მარცხნივ, შემდეგ გააჩერეთ.", + "ui.3d_mouse_step_roll_right": "რამდენჯერმე გააგორეთ ბურთი მარჯვნივ, შემდეგ გააჩერეთ.", + "ui.3d_mouse_step_roll_toward": "რამდენჯერმე გააგორეთ ბურთი თქვენკენ, შემდეგ გააჩერეთ.", + "ui.3d_mouse_step_slide_left": "გასწიეთ თავსახური მარცხნივ, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_slide_right": "გასწიეთ თავსახური მარჯვნივ, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_spin_clockwise": "რამდენჯერმე დაატრიალეთ ბურთი საათის ისრის მიმართულებით, შემდეგ გააჩერეთ.", + "ui.3d_mouse_step_spin_counterclockwise": "რამდენჯერმე დაატრიალეთ ბურთი საათის ისრის საწინააღმდეგოდ, შემდეგ გააჩერეთ.", + "ui.3d_mouse_step_tilt_away": "დახარეთ თავსახურის ზედა ნაწილი თქვენგან (თქვენთან უახლოესი კიდე მაღლა იწევს), დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_tilt_left": "დახარეთ თავსახური მარცხნივ (მარცხენა კიდე დაბლა), დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_tilt_right": "დახარეთ თავსახური მარჯვნივ (მარჯვენა კიდე დაბლა), დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_tilt_toward": "დახარეთ თავსახურის ზედა ნაწილი თქვენკენ (თქვენთან უახლოესი კიდე დაბლა იწევს), დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_touch": "დაადეთ ხელი თავსახურს ისე, რომ არ დააწვეთ.", + "ui.3d_mouse_step_twist_clockwise": "მოატრიალეთ თავსახური საათის ისრის მიმართულებით, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_step_twist_counterclockwise": "მოატრიალეთ თავსახური საათის ისრის საწინააღმდეგოდ, დააყოვნეთ, შემდეგ გაუშვით.", + "ui.3d_mouse_switch_cap": "კალიბრაცია როგორც ცენტრში დაბრუნებადის", + "ui.3d_mouse_switch_trackball": "კალიბრაცია როგორც ტრეკბოლის", + "ui.3d_mouse_use_direct": "პირდაპირი დრაივერის გამოყენება", + "ui.3d_mouse_use_direct_tip": "3D მაუსის პირდაპირ წაკითხვა (hidraw) spacenavd-ის ნაცვლად.", + "ui.3d_mouse_view_axis": "ხედის ღერძი", + "ui.3d_mouse_view_off": "გამორთული", + "ui.3d_mouse_view_off_tip": "3D მაუსის დრაივერის პროფილი ამ ღერძს თიშავს, ამიტომ მისი მოძრაობა ხედს არ ამოძრავებს. თუ აქ სხვა ღერძის მოძრაობას აირჩევთ, ისინი ადგილებს გაცვლიან და ის მოძრაობა ხედის ამოძრავებას შეწყვეტს.", + "ui.3d_mouse_view_orbit_sideways": "ორბიტა Y", + "ui.3d_mouse_view_orbit_up_down": "ორბიტა X", + "ui.3d_mouse_view_pan_sideways": "პანორამა X", + "ui.3d_mouse_view_pan_up_down": "პანორამა Y", + "ui.3d_mouse_view_roll": "გორება", + "ui.3d_mouse_view_unmapped": "ღერძი {n}", + "ui.3d_mouse_view_zoom": "მასშტაბი", + "ui.3d_mouse_waiting": "მოძრაობის მოლოდინი", + "ui.3d_mouse_wiggle": "თუ მიერთებული გაქვთ, შეარხიეთ.", + "ui.3d_sketch": "3D ესკიზი", + "ui.activate": "გააქტიურება", + "ui.active_component": "აქტიური კომპონენტი", + "ui.add_configuration": "კონფიგურაციის დამატება", + "ui.add_parameter": "პარამეტრის დამატება", + "ui.agent_chat": "აგენტის ჩატი", + "ui.agent_chat_add": "ფაილების მიმაგრება", + "ui.agent_chat_add_file": "ფაილის არჩევა…", + "ui.agent_chat_allow": "დაშვება", + "ui.agent_chat_allow_once": "ერთჯერ დაშვება", + "ui.agent_chat_allowed": "დაშვებულია", + "ui.agent_chat_answered": "პასუხი: {option}", + "ui.agent_chat_approval": "დავუშვათ, რომ აგენტმა ეს გააკეთოს?", + "ui.agent_chat_attach_selection": "მონიშნულის მიმაგრება", + "ui.agent_chat_attach_selection_tip": "შეტყობინებასთან ერთად მოდელში მონიშნულის (წახნაგების, წიბოების, ოპერაციების, სხეულების) გაგზავნა, რომ აგენტმა იცოდეს, რას გულისხმობთ", + "ui.agent_chat_attach_view": "ხედის მიმაგრება", + "ui.agent_chat_attach_view_tip": "შეტყობინებასთან ერთად მიმდინარე ხედის სურათის გაგზავნა", + "ui.agent_chat_attachable": "სურათები, PDF-ები, ტექსტი და CAD ფაილები", + "ui.agent_chat_auth_agent": "შესვლა {name}-ით", + "ui.agent_chat_auth_env": "დააყენეთ {vars} თქვენს გარემოში და გადატვირთეთ SolidCraft.", + "ui.agent_chat_auth_needed": "აგენტი გთხოვთ, შეხვიდეთ სისტემაში. შედიხართ თავად აგენტით; SolidCraft ვერასოდეს ხედავს თქვენს პაროლს ან გასაღებებს.", + "ui.agent_chat_auth_none": "აგენტი აქ შესვლის საშუალებას არ გთავაზობთ: შედით ისე, როგორც მისი დოკუმენტაცია აღწერს.", + "ui.agent_chat_auth_retry": "შევედი: ხელახლა დაკავშირება", + "ui.agent_chat_auth_terminal": "გაუშვით ეს ტერმინალში, შემდეგ დააჭირეთ „ხელახლა დაკავშირებას“:", + "ui.agent_chat_auth_title": "აგენტში შესვლა", + "ui.agent_chat_cancel": "გაუქმება", + "ui.agent_chat_cancel_timeout": "აგენტმა შეჩერებაზე არ უპასუხა და კავშირი გაწყდა. გასაგრძელებლად ხელახლა დაუკავშირდით.", + "ui.agent_chat_cannot_start": "დაინსტალირებულია, მაგრამ არ ეშვება: {error}", + "ui.agent_chat_changes": "ცვლილება: {n}, დაბრუნების ერთი ნაბიჯი", + "ui.agent_chat_changes_n": "ცვლილება: {n}", + "ui.agent_chat_changes_of": "ცვლილება: {n}/{limit}", + "ui.agent_chat_choose_model": "აირჩიეთ მოდელი", + "ui.agent_chat_close": "დახურვა", + "ui.agent_chat_command": "აგენტის ბრძანება", + "ui.agent_chat_connect": "დაკავშირება", + "ui.agent_chat_copy": "კოპირება", + "ui.agent_chat_copy_message": "შეტყობინების კოპირება", + "ui.agent_chat_ctx_bodies": "სხეულები", + "ui.agent_chat_ctx_elements": "ელემენტები", + "ui.agent_chat_ctx_features": "ოპერაციები", + "ui.agent_chat_ctx_more": "+{n} კიდევ", + "ui.agent_chat_ctx_other": "სხვა", + "ui.agent_chat_custom_heading": "საკუთარი მოდელი", + "ui.agent_chat_custom_hint": "ნებისმიერი პროგრამა, რომელიც stdin-სა და stdout-ზე Agent Client Protocol-ით საუბრობს. მას გარსი არ უშვებს.", + "ui.agent_chat_denied": "უარყოფილია", + "ui.agent_chat_deny": "უარყოფა", + "ui.agent_chat_desktop_only": "აგენტის ჩატს დესკტოპის აპი სჭირდება.", + "ui.agent_chat_detecting": "აგენტების ძებნა…", + "ui.agent_chat_dock": "გვერდით პანელში მიმაგრება", + "ui.agent_chat_dock_left": "მარცხნივ მიმაგრება", + "ui.agent_chat_dock_right": "მარჯვნივ მიმაგრება", + "ui.agent_chat_drop_hint": "ჩააგდეთ, რომ შემდეგ შეტყობინებას მიემაგროს", + "ui.agent_chat_edit": "რედაქტირება", + "ui.agent_chat_exited": "აგენტი შეჩერდა.", + "ui.agent_chat_failed_start": "აგენტი ვერ გაეშვა: {error}", + "ui.agent_chat_file_cad_not_read": "{name}: CAD ფაილი პროექტში იმპორტირდება და არა იკითხება", + "ui.agent_chat_file_empty_picture": "{name}: ცარიელი სურათი", + "ui.agent_chat_file_error": "{name}: {error}", + "ui.agent_chat_file_heic": "{name}: HEIC სურათები აქ ვერ იკითხება; ჯერ გაიტანეთ JPEG-ად ან PNG-ად", + "ui.agent_chat_file_importing": "პროექტში იმპორტი…", + "ui.agent_chat_file_kinds": "{name}: მიმაგრება შეიძლება სურათების (PNG, JPEG, GIF, WebP, BMP, TIFF), ტექსტური ფაილების (SVG-ის ჩათვლით) და CAD ფაილების (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF)", + "ui.agent_chat_file_loading": "ფაილი იკითხება…", + "ui.agent_chat_file_not_a_file": "{name}: ფაილი არ არის", + "ui.agent_chat_file_not_a_picture": "{name}: სურათი არ არის", + "ui.agent_chat_file_not_utf8": "{name}: UTF-8 ტექსტი არ არის", + "ui.agent_chat_file_picture_too_big": "{name}: სურათი მაქსიმუმ {max} MB შეიძლება იყოს", + "ui.agent_chat_file_text_too_big": "{name}: ტექსტური ფაილი მაქსიმუმ {max} KB შეიძლება იყოს", + "ui.agent_chat_file_too_large": "{name}: ზედმეტად დიდია", + "ui.agent_chat_file_too_large_to_send": "{name}: გასაგზავნად ზედმეტად დიდია, შემცირების შემდეგაც კი", + "ui.agent_chat_file_unreadable_picture": "{name}: ეს სურათი აქ ვერ იკითხება", + "ui.agent_chat_files": "ფაილები: {files}", + "ui.agent_chat_files_left_out": "ერთ შეტყობინებას მაქსიმუმ {max} ფაილი ერთვის; გამოტოვებულია: {files}", + "ui.agent_chat_files_loading": "ფაილების წაკითხვის მოლოდინი", + "ui.agent_chat_files_max": "ერთ შეტყობინებაზე მაქსიმუმ {max} ფაილი", + "ui.agent_chat_flatpak_none_found": "პროგრამირების აგენტი ვერ მოიძებნა. Flatpak-ის სენდბოქსი ვერ ხედავს თქვენს საწყის საქაღალდეში დაინსტალირებულ აგენტებს და ნაგულისხმევად ქსელზე წვდომა არ აქვს. nvm-ით ან ~/.local/bin-ში დაინსტალირებული Claude Code-ისა და მისი ACP ადაპტერის დასაშვებად ტერმინალში გაუშვით ეს ბრძანება, შემდეგ გადატვირთეთ SolidCraft. ის წვდომას იძლევა ჩამოთვლილ პროგრამასა და შესვლის ფაილებზე, ასევე ქსელზე:", + "ui.agent_chat_import_failed": "{name}: იმპორტი ვერ მოხერხდა: {error}", + "ui.agent_chat_intro": "ესაუბრეთ პროგრამირების აგენტს, რომელსაც უკვე იყენებთ, ან თქვენ მიერ არჩეულ მოდელის ენდპოინტს. ის ღია პროექტზე SolidCraft-ის ხელსაწყოებით მუშაობს: მისი ცვლილებები შეტანისთანავე ჩანს და თითო შეტყობინებაზე ერთი ნაბიჯით ბრუნდება. რისი გაკეთება შეუძლია უკითხავად, პარამეტრები > AI-ში დგინდება.", + "ui.agent_chat_key_in_env": "გასაღები დაყენებულია", + "ui.agent_chat_last_missing": "ბოლოს გამოყენებული აგენტი ({agent}) აღარ არის ხელმისაწვდომი. აირჩიეთ აგენტი, შემდეგ დააჭირეთ „ხელახლა ცდას“.", + "ui.agent_chat_left": "მარცხნივ", + "ui.agent_chat_limit": "აგენტმა ერთი შეტყობინებისთვის {limit} ცვლილების ზღვარს მიაღწია. გაგზავნეთ კიდევ ერთი შეტყობინება, რომ გააგრძელოს.", + "ui.agent_chat_login_found": "შესვლის მონაცემები ნაპოვნია", + "ui.agent_chat_minimize": "ზოლად ჩაკეცვა", + "ui.agent_chat_mode_all": "ყველა", + "ui.agent_chat_mode_ask": "კითხვით", + "ui.agent_chat_mode_edits": "ცვლილებები", + "ui.agent_chat_model_custom": "საკუთარის გამოყენება: {model}", + "ui.agent_chat_model_no_tools": "{model} ვერ იყენებს SolidCraft-ის ხელსაწყოებს, ამიტომ მხოლოდ საუბარი შეუძლია. აირჩიეთ ხელსაწყოების მხარდაჭერის მქონე მოდელი.", + "ui.agent_chat_model_rejected": "აგენტმა {model} არ მიიღო: {error}", + "ui.agent_chat_model_search": "მოდელების ძიება…", + "ui.agent_chat_model_tip": "მოდელი, რომელსაც აგენტი იყენებს. თქვენი არჩევანი ამ აგენტისთვის დაიმახსოვრება.", + "ui.agent_chat_models_failed": "მოდელების სიის მიღება ვერ მოხერხდა: {error}", + "ui.agent_chat_models_heading": "ხელმისაწვდომი მოდელები", + "ui.agent_chat_models_listing": "მოდელების სიის მიღება…", + "ui.agent_chat_models_none": "ენდპოინტი მოდელებს არ ჩამოთვლის", + "ui.agent_chat_models_not_a_list": "პასუხი მოდელების სია არ იყო", + "ui.agent_chat_new": "ახალი ჩატი", + "ui.agent_chat_new_confirm": "დავიწყოთ ახალი ჩატი? მიმდინარე გასუფთავდება.", + "ui.agent_chat_next_picture": "შემდეგი სურათი", + "ui.agent_chat_no_cli": "solidcraft-cli აპის გვერდით ვერ მოიძებნა, ამიტომ აგენტი პროექტს ვერ მისწვდება.", + "ui.agent_chat_no_control": "აგენტის ჩატის ენდპოინტი არ გაეშვა, ამიტომ აგენტი პროექტს ვერ მისწვდება.", + "ui.agent_chat_no_images": "ეს აგენტი სურათებს არ იღებს", + "ui.agent_chat_no_picture": "გაცვლის ბუფერში სურათი არ არის", + "ui.agent_chat_no_tool_call": "მოდელმა SolidCraft-ის ხელსაწყოები არ გამოიყენა, ამიტომ პროექტი არ შეცვლილა. აირჩიეთ მოდელი, რომელსაც ხელსაწყოების გამოძახება შეუძლია; იხილეთ „ლოკალური მოდელები“ აგენტის ჩატის სახელმძღვანელოში.", + "ui.agent_chat_node_too_old": "Node.js {version} ამ აგენტისთვის ძალიან ძველია. დააინსტალირეთ Node.js 20.10 ან უფრო ახალი, შემდეგ დააჭირეთ „განახლებას“.", + "ui.agent_chat_none_found": "პროგრამირების აგენტი ვერ მოიძებნა. დააინსტალირეთ ერთ-ერთი ამათგანი, შემდეგ დააჭირეთ „განახლებას“:", + "ui.agent_chat_none_found_short": "აგენტი ვერ მოიძებნა", + "ui.agent_chat_not_installed": "არ არის დაინსტალირებული", + "ui.agent_chat_not_signed_in": "შესული არ ხართ", + "ui.agent_chat_open_settings": "პარამეტრების გახსნა", + "ui.agent_chat_own_window": "ცალკე ფანჯარა", + "ui.agent_chat_paste_picture": "სურათის ჩასმა", + "ui.agent_chat_permission": "აგენტი ითხოვს გაშვებას: {title}", + "ui.agent_chat_pick": "აგენტი", + "ui.agent_chat_pick_context": "კონტექსტის არჩევა", + "ui.agent_chat_pick_context_tip": "აირჩიეთ მოდელში წახნაგები, წიბოები, ოპერაციები და სხეულები, რომ აგენტმა დაათვალიეროს, შემდეგ დააჭირეთ OK-ს", + "ui.agent_chat_placeholder": "სთხოვეთ აგენტს პროექტის შეცვლა…", + "ui.agent_chat_placeholder_busy": "შეტყობინების რიგში ჩაყენება, სანამ აგენტი მორჩება (Ctrl+Enter: ახლავე გაგზავნა)", + "ui.agent_chat_pop_out": "ცალკე ფანჯარაში გახსნა, რომლის სხვა ეკრანზე გადატანაც შეგიძლიათ", + "ui.agent_chat_previous_picture": "წინა სურათი", + "ui.agent_chat_privacy": "არაფერი იგზავნება არსად, გარდა თქვენ მიერ გაშვებული აგენტისა, თქვენივე ანგარიშით.", + "ui.agent_chat_privacy_note": "თავად ჩატი არსად არაფერს აგზავნის: თქვენ მიერ გაშვებული აგენტი საკუთარ სერვისს თქვენივე ანგარიშით უკავშირდება. SolidCraft ვერასოდეს ხედავს და არ ინახავს გასაღებს ან პაროლს.", + "ui.agent_chat_provider_models": "მოდელი: {count}", + "ui.agent_chat_provider_other": "სხვა", + "ui.agent_chat_provider_tip": "მომწოდებელი, რომლის მოდელებსაც შემდეგი სია აჩვენებს.", + "ui.agent_chat_queue": "რიგი", + "ui.agent_chat_queue_full": "ზედმეტად ბევრი შეტყობინება ელოდება: წაშალეთ ერთი ან დაელოდეთ აგენტს.", + "ui.agent_chat_queued": "რიგშია", + "ui.agent_chat_queued_stopped": "რიგშია (შეჩერებულია, არ გაიგზავნა)", + "ui.agent_chat_refresh": "განახლება", + "ui.agent_chat_refused": "აგენტისთვის დაუშვებელია: {reason}", + "ui.agent_chat_reinstall": "{agent} დაინსტალირებულია ({program}), მაგრამ SolidCraft-ის შემოწმებისას არ გაეშვა: {error}\nშესაძლოა, ინსტალაცია არასრულია ან სხვა ტიპის კომპიუტერისთვისაა. ხელახლა დააინსტალირეთ `{install}`-ით, შეამოწმეთ, რომ ტერმინალში თავის ვერსიას ბეჭდავს, შემდეგ დააჭირეთ „განახლებას“.", + "ui.agent_chat_remove": "რიგიდან ამოღება", + "ui.agent_chat_remove_file": "ამ შეტყობინებიდან მოხსნა", + "ui.agent_chat_remove_imported": "ამ შეტყობინებიდან მოხსნა; დეტალი პროექტში რჩება (დაბრუნება მას წაშლის)", + "ui.agent_chat_reply_cut_off": "პასუხმა დასრულებამდე სიგრძის ზღვარს მიაღწია, ამიტომ შეიძლება არასრული იყოს. სთხოვეთ აგენტს, გააგრძელოს, ან უფრო მოკლე პასუხი გასცეს.", + "ui.agent_chat_reply_declined": "მოდელმა ამ შეტყობინებაზე პასუხზე უარი თქვა.", + "ui.agent_chat_retry": "ხელახლა ცდა", + "ui.agent_chat_right": "მარჯვნივ", + "ui.agent_chat_save": "შენახვა", + "ui.agent_chat_send": "გაგზავნა", + "ui.agent_chat_send_now": "ახლავე გაგზავნა", + "ui.agent_chat_send_now_tip": "აგენტის მიმდინარე ნაბიჯის შეწყვეტა და ამის შემდეგ გაგზავნა (Ctrl+Enter)", + "ui.agent_chat_setup_body": "SolidCraft ამ კომპიუტერზე დაინსტალირებულ პროგრამირების აგენტს უკავშირდება. აირჩიეთ ის პარამეტრები › AI-ში.", + "ui.agent_chat_setup_title": "ასისტენტის დაყენება", + "ui.agent_chat_side": "აგენტის ჩატის მხარე", + "ui.agent_chat_signed_in": "შესული ხართ", + "ui.agent_chat_state_auth": "საჭიროა შესვლა", + "ui.agent_chat_state_busy": "მუშაობს…", + "ui.agent_chat_state_exited": "აგენტი შეჩერდა", + "ui.agent_chat_state_failed": "დაკავშირება ვერ მოხერხდა", + "ui.agent_chat_state_off": "არ არის დაკავშირებული", + "ui.agent_chat_state_ready": "მზადაა", + "ui.agent_chat_state_starting": "ეშვება…", + "ui.agent_chat_stop": "შეწყვეტა", + "ui.agent_chat_stop_tip": "აგენტისა და მის მიერ გაშვებული ყველაფრის შეწყვეტა", + "ui.agent_chat_stop_turn_tip": "აგენტის შეწყვეტა (Esc). რიგში მყოფი შეტყობინებები რიგში რჩება.", + "ui.agent_chat_turn_limit": "ცვლილებები ერთ შეტყობინებაზე", + "ui.agent_chat_turn_unlimited": "შეუზღუდავი", + "ui.agent_chat_undo_changes": "ამ ცვლილებების დაბრუნება", + "ui.agent_chat_undo_label": "აგენტის ჩატი: {message}", + "ui.agent_chat_undone": "(დაბრუნებულია)", + "ui.agent_chat_view_attached": "ხედი მიმაგრებულია", + "ui.agent_chat_waiting": "გელოდებათ", + "ui.agent_cursor": "აგენტის კურსორი", + "ui.agent_cursor_speed": "აგენტის კურსორის სიჩქარე", + "ui.agent_off_thread": "ფანჯრის რეაგირებადობის შენარჩუნება, სანამ აგენტები ბრძანებებს ასრულებენ", + "ui.agent_off_thread_note": "აგენტის ნელი ბრძანებები (AI პანელიდან ან MCP კლიენტიდან) ფანჯრის პარალელურად გამოითვლება: შეგიძლიათ ხედის ბრუნვა და დათვალიერება გააგრძელოთ და ბრძანება ხედში არსებული ჩიპიდან შეწყვიტოთ. გამორთული: თითოეული ფანჯრის ნაკადში სრულდება და ფანჯარა მას ელოდება.", + "ui.ai_add": "დამატება", + "ui.ai_add_agent": "აგენტის დამატება…", + "ui.ai_add_agent_title": "აგენტის დამატება", + "ui.ai_add_anthropic": "Anthropic-თან თავსებადი API", + "ui.ai_add_api": "OpenAI-თან თავსებადი API", + "ui.ai_add_custom": "საკუთარი ბრძანება", + "ui.ai_add_endpoint": "API ენდპოინტი", + "ui.ai_add_installed": "დაინსტალირებული აგენტი", + "ui.ai_add_installed_note": "თქვენი საკუთარი ჩანაწერი დაინსტალირებული აგენტისთვის, მაგალითად სხვა არგუმენტებით. დაინსტალირებული აგენტები სიაში თავისთავად ჩნდება.", + "ui.ai_added": "დამატებულია", + "ui.ai_agent_mode_tip": "აგენტის საკუთარი რეჟიმი: მის საკუთარ ხელსაწყოებზე (გარსი, ფაილების რედაქტირება) ის მოქმედებს. SolidCraft-ის ხელსაწყოებზე მოქმედებს ნებართვები პარამეტრები > AI-დან.", + "ui.ai_agents": "აგენტები", + "ui.ai_always_allow": "ყოველთვის დაშვება", + "ui.ai_always_allow_tip": "{tool}-ის დაშვება ამ აგენტისთვის ამიერიდან, უკითხავად", + "ui.ai_always_allowed": "ყოველთვის დაშვებული", + "ui.ai_always_allowed_none": "ჯერ არაფერია ყოველთვის დაშვებული. ჩატში გაცემული „ყოველთვის დაშვება“ პასუხები აქ ჩამოითვლება.", + "ui.ai_auto_allowed": "ავტომატურად დაშვებულია: {title} ({why})", + "ui.ai_auto_mode": "თქვენი ნებართვის პარამეტრი", + "ui.ai_auto_ours": "SolidCraft საკუთარ ხელსაწყოებს თავად ამოწმებს", + "ui.ai_auto_remembered": "აირჩიეთ „ყოველთვის დაშვება“", + "ui.ai_bad_url": "შეიყვანეთ URL, რომელიც http://-ით ან https://-ით იწყება", + "ui.ai_base_url": "საბაზო URL", + "ui.ai_button": "AI", + "ui.ai_command_hint": "my-agent --acp", + "ui.ai_copy_suffix": "ასლი", + "ui.ai_custom_url": "საკუთარი URL", + "ui.ai_default": "ნაგულისხმევი", + "ui.ai_edit": "რედაქტირება", + "ui.ai_edit_agent_title": "აგენტის რედაქტირება", + "ui.ai_edit_gone": "ეს აგენტი წაიშალა, ამიტომ შესანახი არაფერია.", + "ui.ai_edit_tip": "ამ აგენტის სახელის, ბრძანების ან ენდპოინტის შეცვლა. შენახული გასაღები დამალული რჩება.", + "ui.ai_http_busy": "ენდპოინტი დაკავებულია ან ლიმიტს გადააჭარბა; სცადეთ მოგვიანებით", + "ui.ai_http_key": "ენდპოინტმა გასაღები უარყო: შეამოწმეთ ის პარამეტრები > AI-ში", + "ui.ai_http_not_found": "ასეთი ენდპოინტი ან მოდელი არ არსებობს: შეამოწმეთ საბაზო URL და მოდელის სახელი", + "ui.ai_http_too_large": "საუბარი ზედმეტად დიდია ამ ენდპოინტისთვის; დაიწყეთ ახალი ჩატი", + "ui.ai_key": "API გასაღები", + "ui.ai_key_hint": "არასავალდებულო; ინახება სისტემის გასაღებების საცავში", + "ui.ai_key_keep_hint": "დატოვეთ ცარიელი, რომ შენახული გასაღები დარჩეს", + "ui.ai_key_needs_https": "გასაღები მხოლოდ HTTPS-ით ან ამ კომპიუტერზე იგზავნება.", + "ui.ai_key_note": "ინახება სისტემის გასაღებების საცავში და არასოდეს SolidCraft-ის პარამეტრებში. ლოკალური სერვერისთვის დატოვეთ ცარიელი.", + "ui.ai_keychain_error": "სისტემის გასაღებების საცავმა უარი თქვა: {error}", + "ui.ai_kind": "სახეობა", + "ui.ai_mode_all": "ყველაფრის დაშვება", + "ui.ai_mode_all_note": "არაფერი ითხოვს წინასწარ თანხმობას. ავარიის ანგარიშები მიუწვდომელი რჩება და საქაღალდეების შეზღუდვები კვლავ მოქმედებს.", + "ui.ai_mode_all_warning": "აგენტს შეუძლია უკითხავად შეინახოს, გადააწეროს, გაიტანოს და ჩაანაცვლოს თქვენი პროექტი. გამოიყენეთ მხოლოდ სანდო აგენტთან, შენახულ პროექტებზე.", + "ui.ai_mode_ask": "ყოველ ჯერზე კითხვა", + "ui.ai_mode_ask_note": "პროექტის ყოველი ცვლილება და ფაილზე ყოველი მოქმედება თქვენს „დაშვებას“ ელოდება.", + "ui.ai_mode_edits": "მოდელის ცვლილებების ავტომატური დაშვება", + "ui.ai_mode_edits_note": "მოდელირების ბრძანებები უკითხავად სრულდება; შენახვა, გახსნა, ექსპორტი და ფაილზე სხვა ან დესტრუქციული მოქმედებები კვლავ კითხვას საჭიროებს.", + "ui.ai_mode_global": "როგორც ზემოთაა დაყენებული", + "ui.ai_model": "მოდელი", + "ui.ai_model_hint": "qwen3:14b", + "ui.ai_modes_scope": "ეს პარამეტრები SolidCraft-ის ხელსაწყოებს ეხება. აგენტის საკუთარ ხელსაწყოებზე (მის გარსზე, ფაილების რედაქტირებაზე) აგენტის საკუთარი რეჟიმი მოქმედებს, რომელსაც ჩატის პანელის თავსართში ირჩევთ, როცა აგენტს რეჟიმები აქვს.", + "ui.ai_name": "სახელი", + "ui.ai_name_hint": "ჩემი აგენტი", + "ui.ai_need_command": "შეიყვანეთ ბრძანება, რომელიც აგენტს უშვებს", + "ui.ai_need_model": "შეიყვანეთ მოდელის სახელი", + "ui.ai_no_answer": "აგენტმა დროულად არ უპასუხა", + "ui.ai_no_http": "ეს ანაწყობი API ენდპოინტებს ვერ მისწვდება", + "ui.ai_no_keychain": "სისტემის გასაღებების საცავი მიუწვდომელია, ამიტომ გასაღების შენახვა შეუძლებელია. ლოკალური სერვერი გასაღების გარეშე მაინც მუშაობს.", + "ui.ai_panel": "პანელი", + "ui.ai_permissions": "ნებართვები", + "ui.ai_preset": "პრესეტი", + "ui.ai_protocol": "პროტოკოლი", + "ui.ai_reasoning_effort": "მსჯელობის ძალისხმევა", + "ui.ai_reasoning_effort_field_hint": "ცარიელი = მომწოდებლის ნაგულისხმევი", + "ui.ai_reasoning_effort_hint": "არასავალდებულო. ენდპოინტს ეგზავნება როგორც `reasoning_effort`; დასაშვები მნიშვნელობები მომწოდებლის მიხედვით განსხვავდება (მაგალითად, `low`, `high` ან `max`). აქ მითითებულ მნიშვნელობას SolidCraft არასოდეს ცვლის. დატოვეთ ცარიელი, რომ არაფერი გაიგზავნოს და მომწოდებლის ნაგულისხმევი დარჩეს.", + "ui.ai_remove": "წაშლა", + "ui.ai_request_timed_out": "მოდელს {seconds} წმ-ზე მეტი დასჭირდა. ამ ენდპოინტის მოთხოვნის ვადის გაზრდა შეგიძლიათ პარამეტრები › ასისტენტში.", + "ui.ai_request_timeout": "მოთხოვნის ვადა", + "ui.ai_request_timeout_hint": "რამდენ ხანს შეიძლება გაგრძელდეს მოდელის ერთი მოთხოვნა ამ ენდპოინტზე, 30 წმ-დან ერთ საათამდე. გაზარდეთ ნელი ლოკალური მოდელისთვის.", + "ui.ai_reset": "ჩამოყრა", + "ui.ai_save": "შენახვა", + "ui.ai_settings": "AI პარამეტრები…", + "ui.ai_show_features": "AI ფუნქციების ჩვენება", + "ui.ai_show_features_note": "აგენტის ჩატი: პანელი, სადაც პროგრამირების აგენტი, რომელსაც უკვე იყენებთ, ან თქვენ მიერ არჩეული მოდელის ენდპოინტი ღია პროექტზე მუშაობს. გამორთული: არ არის AI ღილაკი, მალსახმობი, მენიუს პუნქტი ან პანელი, და არაფერი იძებნება ან ეშვება.", + "ui.ai_switch_tip": "ამ საუბრისთვის აგენტის შეცვლა", + "ui.ai_test": "ტესტი", + "ui.ai_test_acp_ok": "პასუხობს: {agent}", + "ui.ai_test_acp_tip": "აგენტს მოკლედ უშვებს და სესიას სთხოვს; შემდეგ ისევ ასრულებს", + "ui.ai_test_answered": "დაკავშირება წარმატებულია: {model}-მა უპასუხა", + "ui.ai_test_anthropic_tip": "ენდპოინტს მოკლე შეტყობინებას უგზავნის", + "ui.ai_test_api_tip": "ენდპოინტს მისი მოდელების სიას სთხოვს", + "ui.ai_test_no_model": "დაკავშირება წარმატებულია: მოდელი: {count}, მაგრამ არა {model}", + "ui.ai_test_ok": "დაკავშირება წარმატებულია: მოდელი: {count}", + "ui.ai_testing": "მოწმდება…", + "ui.ai_tool_arguments": "არგუმენტები", + "ui.ai_tool_details": "დეტალები", + "ui.ai_tool_done": "შესრულდა", + "ui.ai_tool_failed": "ვერ მოხერხდა", + "ui.ai_tool_result": "შედეგი", + "ui.ai_tool_running": "სრულდება", + "ui.ai_tool_sum_bodies_one": "სხეული: {count}", + "ui.ai_tool_sum_bodies_other": "სხეული: {count}", + "ui.ai_tool_sum_by": "{value}-ით", + "ui.ai_tool_sum_edges_one": "წიბო: {count}", + "ui.ai_tool_sum_edges_other": "წიბო: {count}", + "ui.ai_tool_sum_faces_one": "წახნაგი: {count}", + "ui.ai_tool_sum_faces_other": "წახნაგი: {count}", + "ui.ai_tool_sum_features_one": "ოპერაცია: {count}", + "ui.ai_tool_sum_features_other": "ოპერაცია: {count}", + "ui.ai_tool_sum_measured": "გაიზომა {what}", + "ui.ai_tool_sum_more": "{steps} და კიდევ {count}", + "ui.ai_tool_sum_radius": "r {value}", + "ui.ai_tool_sum_saved": "შენახულია {file}", + "ui.ai_tool_sum_screenshot": "ეკრანის ანაბეჭდი", + "ui.ai_tool_sum_then": "{first}, შემდეგ {next}", + "ui.ai_tool_unfold": "დაწკაპეთ, რომ ნახოთ, რა დააბრუნა", + "ui.ai_tool_waiting": "ელოდება", + "ui.ai_toolbar_button": "ასისტენტის ღილაკის ჩვენება აპლიკაციის ზოლში", + "ui.ai_toolbar_button_note": "ასისტენტის ღილაკი აპლიკაციის ზოლში. Ctrl+Shift+A და მენიუ „ხედი“ პანელს მაინც ხსნის.", + "ui.ai_undo_tip": "ამ შეტყობინებისთვის აგენტის ყველა ცვლილების დაბრუნება ერთ ნაბიჯად", + "ui.ai_url_hint": "https://example.com/v1", + "ui.all": "ყველა", + "ui.ambient_occlusion": "გარემოს დაჩრდილვა", + "ui.ambient_occlusion_help": "რბილი დაჩრდილვა იქ, სადაც გაუმჭვირვალე ზედაპირები ერთმანეთს ხვდება. საჭიროებს GPU ხედვის არეს.", + "ui.analysis": "ანალიზი", + "ui.angle": "კუთხე", + "ui.angle_decimals": "კუთხის ათწილადი ნიშნები", + "ui.animateJoint": "შეერთების ანიმირება", + "ui.animate_view_changes": "ხედის ცვლილებების ანიმირება", + "ui.animation": "ანიმაცია", + "ui.animation_speed": "ანიმაციის სიჩქარე", + "ui.anti_aliasing": "ანტიალიასინგი", + "ui.apply": "გამოყენება", + "ui.arc": "რკალი", + "ui.assistant": "ასისტენტი", + "ui.assistant_waiting": "მოლოდინში მყოფი დასტური: {count}", + "ui.autosave_every": "ავტომატური შენახვა ყოველ", + "ui.axes": "ღერძები", + "ui.axis": "ღერძი", + "ui.back": "უკან", + "ui.base_point": "საბაზო წერტილი", + "ui.blocked": "დაბლოკილია", + "ui.bodies": "სხეულები", + "ui.bodies_all_if_none": "სხეულები (ყველა, თუ არცერთი)", + "ui.body_kind_mesh": "პოლიგონური ბადის სხეული", + "ui.body_kind_solid": "მყარი სხეული", + "ui.body_kind_surface": "ზედაპირული სხეული", + "ui.bottom": "ქვედა", + "ui.box": "პარალელეპიპედი", + "ui.break": "გაწყვეტა", + "ui.browser_bodies_one": "სხეული: {count}", + "ui.browser_bodies_other": "სხეული: {count}", + "ui.browser_collapse": "მოდელის ხის ჩაკეცვა", + "ui.browser_expand": "მოდელის ხის გაშლა", + "ui.browser_title": "მოდელის ხე", + "ui.calibrate": "კალიბრაცია", + "ui.cancel": "გაუქმება", + "ui.canvases": "ტილოები", + "ui.center": "ცენტრი", + "ui.center_arc_follows_cursor": "ცენტრით აგებული რკალი კურსორის მიმართულებას მიჰყვება", + "ui.center_arc_follows_cursor_tip": "ცენტრით აგებული რკალი საათის ისრის მიმართულებით ან საწინააღმდეგოდ მიდის, იმის მიხედვით, როგორ უვლის კურსორი მის ცენტრს. გამორთული: ყოველთვის საათის ისრის საწინააღმდეგოდ საწყისი წერტილიდან.", + "ui.centerline": "ღერძული ხაზი", + "ui.chain": "ჯაჭვი", + "ui.chamfer": "ფასკა", + "ui.chamfer_angle": "ფასკის კუთხე", + "ui.chamfer_depth": "ფასკის სიღრმე", + "ui.chamfer_type": "ფასკის ტიპი", + "ui.change_workspace": "სამუშაო სივრცის შეცვლა", + "ui.circle": "წრე", + "ui.circular_pattern": "წრიული მასივი", + "ui.clear": "გასუფთავება", + "ui.clear_print_face": "ბეჭდვის წახნაგის მოხსნა", + "ui.clear_recent": "ბოლოდროინდელის გასუფთავება", + "ui.clear_the_selection": "მონიშნულის გასუფთავება", + "ui.click_selects_whole_bodies": "დაწკაპებით მთელი სხეული მოინიშნება", + "ui.click_then_press_key": "დაწკაპეთ, შემდეგ დააჭირეთ ახალ კლავიშს", + "ui.close": "დახურვა", + "ui.coil": "ხვია", + "ui.coincident": "დამთხვევა", + "ui.collapse": "ჩაკეცვა", + "ui.collinear": "კოლინეარობა", + "ui.colour_vision": "ფერთა აღქმა", + "ui.colour_vision_deutan": "დეიტერანოპია", + "ui.colour_vision_deutan_tip": "მწვანე ფერის სუსტი ან არარსებული აღქმისთვის", + "ui.colour_vision_failed": "ვერ მოხერხდა", + "ui.colour_vision_fixed": "ფიქსირებული", + "ui.colour_vision_mode": "რეჟიმი", + "ui.colour_vision_note": "ცვლის ფერებს, რომლებსაც მნიშვნელობა აქვს: ესკიზის მდგომარეობები, ღერძები, მოღუნვები, ანალიზები და ხატულები. თუ Windows-ის ფერის ფილტრებს იყენებთ, ეს გამორთული დატოვეთ.", + "ui.colour_vision_off": "გამორთული", + "ui.colour_vision_off_tip": "თემის საკუთარი ფერები", + "ui.colour_vision_projected": "პროეცირებული", + "ui.colour_vision_protan": "პროტანოპია", + "ui.colour_vision_protan_tip": "წითელი ფერის სუსტი ან არარსებული აღქმისთვის", + "ui.colour_vision_sample": "ნიმუში", + "ui.colour_vision_tritan": "ტრიტანოპია", + "ui.colour_vision_tritan_tip": "ლურჯი ფერის სუსტი ან არარსებული აღქმისთვის", + "ui.comb_length": "სავარცხლის სიგრძე", + "ui.comb_length_tip": "რა სიგრძისაა კბილები: ავტომატური სიგრძის ჯერადი, რომლის დროსაც ყველაზე გრძელი კბილი ნაჩვენები მრუდების ზომის მეხუთედია.", + "ui.comb_teeth": "კბილები", + "ui.comb_teeth_tip": "რამდენი კბილი აქვს თითოეულ სავარცხელს, მრუდის გასწვრივ თანაბრად განაწილებული. მეტი კბილი უფრო დაწვრილებით აჩვენებს, როგორ იცვლება სიმრუდე.", + "ui.combine": "გაერთიანება", + "ui.coming_later": "მოგვიანებით დაემატება", + "ui.command_done": "{command} შესრულდა", + "ui.command_palette_hint": "აკრიფეთ ბრძანება, მაგ. {example} — ან ძიებისთვის დააჭირეთ S-ს", + "ui.components_from_bodies_hint": "აქტიური კომპონენტის ქვეშ თითოეული მონიშნული სხეულისთვის ერთი კომპონენტის შექმნა, ამ სხეულის სახელით.", + "ui.components_from_bodies_required": "მონიშნეთ ერთი სხეული მაინც.", + "ui.concentric": "კონცენტრულობა", + "ui.cone": "კონუსი", + "ui.conic_curve": "კონიკური მრუდი", + "ui.constant": "მუდმივა", + "ui.constraints_conflict": "შეზღუდვები ეწინააღმდეგება ერთმანეთს", + "ui.construction": "დამხმარე", + "ui.construction.angle_hint": "დამხმარე ხაზი: დაწკაპეთ წერტილზე, შემდეგ აკრიფეთ კუთხე ან აირჩიეთ მიმართულება", + "ui.construction.bisector_hint": "ბისექტრისა: აირჩიეთ ორი გადამკვეთი წრფე, შემდეგ სასურველი ამონახსნი", + "ui.construction.common_hint": "საერთო მხები: აირჩიეთ ორი წრე/რკალი, შემდეგ სასურველი ამონახსნი", + "ui.construction.contact_hint": "მხები: აირჩიეთ წრე/რკალი ან ღია სპლაინი/კონიკური მრუდი, შემდეგ შეხების წერტილი (თავისუფალი მრუდები: ბოლო წერტილები)", + "ui.construction.external_hint": "მხები: აირჩიეთ წრე ან რკალი, გარე წერტილი, შემდეგ სასურველი ამონახსნი", + "ui.construction.free_hint": "დამხმარე ხაზი: დაწკაპეთ ორ წერტილზე; თავიდან დასაწყებად დაწკაპეთ მარჯვენა ღილაკით", + "ui.construction.normal_needs_length": "უსასრულო ხაზი ყოველთვის დამხმარეა: ნორმალის ხაზის დასახატად აკრიფეთ სიგრძე", + "ui.construction.point_hint": "დამხმარე ხაზი: დაწკაპეთ წერტილზე, რომელზეც უნდა გაიაროს", + "ui.construction.reference_hint": "დამხმარე ხაზი: აირჩიეთ წრფე, შემდეგ წერტილი; ორიენტირის შესაცვლელად დაწკაპეთ მარჯვენა ღილაკით", + "ui.construction.ribbon_label": "დამხმარე ხაზები", + "ui.construction.side_hint": "დამხმარე ხაზი: დაწკაპეთ იმ მხარეს, საითკენაც ხაზი მიდის; თავიდან დასაწყებად დაწკაპეთ მარჯვენა ღილაკით", + "ui.context_menu": "კონტექსტური მენიუ", + "ui.continuity_crease": "ტეხი", + "ui.continuity_curvature": "სიმრუდე", + "ui.continuity_curvature_change": "სიმრუდის ცვლილება", + "ui.continuity_curvature_change_tip": "სიმრუდის ცვლილება (G3): ნაკერზე სიმრუდეც გლუვად იცვლება.", + "ui.continuity_curvature_tip": "სიმრუდის უწყვეტობა (G2): ანარეკლები გადატეხვის გარეშე გადადის.", + "ui.continuity_g0": "G0 ტეხი", + "ui.continuity_g1": "G1 მხები", + "ui.continuity_g2": "G2 სიმრუდე", + "ui.continuity_gap": "ღრეჩო", + "ui.continuity_position": "პოზიცია", + "ui.continuity_position_tip": "პოზიცია (G0): ზედაპირები ხვდება ერთმანეთს და შეხვედრის ადგილას ტეხი აქვს.", + "ui.continuity_smooth_curvature_change": "სიმრუდის გლუვი ცვლილება", + "ui.continuity_smooth_curvature_change_tip": "სიმრუდის გლუვი ცვლილება (G4): ნაკერზე გლუვად გრძელდება თვით სიმრუდის ცვლილების ხასიათიც.", + "ui.continuity_tangent": "მხები", + "ui.continuity_tangent_tip": "მხები (G1): ტეხი არ არის, თუმცა ნაკერზე სიმრუდე ნახტომით იცვლება.", + "ui.copy": "კოპირება", + "ui.copy_details": "დეტალების კოპირება", + "ui.copy_details_tip": "სრული შეტყობინების კოპირება, მოსაძებნად ან შესატყობინებლად.", + "ui.corner": "კუთხე", + "ui.corners": "კუთხეები", + "ui.cosmetic_thread_markings": "კუთხვილის პირობითი აღნიშვნები", + "ui.cosmetic_thread_markings_help": "კუთხვილიან ცილინდრულ კედლებზე სქემატური აღნიშვნების ჩვენება. ცვლის მხოლოდ ჩვენებას და არასოდეს — პროექტს ან ექსპორტს.", + "ui.counterbore": "ცილინდრული ჩაღრმავება", + "ui.countersink": "კონუსური ჩაღრმავება", + "ui.create": "შექმნა", + "ui.create_copy": "ასლის შექმნა", + "ui.create_sketch": "ესკიზის შექმნა", + "ui.current": "მიმდინარე", + "ui.curvature": "სიმრუდე", + "ui.curvature_g2": "სიმრუდე (G2)", + "ui.curves": "მრუდები", + "ui.custom_program": "სხვა…", + "ui.custom_program_tip": "აირჩიეთ სლაისერის პროგრამა სიაში დასამატებლად", + "ui.customizeToolbar": "ხელსაწყოთა ზოლის მორგება…", + "ui.cut": "ამოჭრა", + "ui.cylinder": "ცილინდრი", + "ui.dark": "ბნელი", + "ui.default_modelling_orientation": "მოდელირების ნაგულისხმევი ორიენტაცია", + "ui.delete": "წაშლა", + "ui.delete_select_first": "ჯერ მონიშნეთ, რა წაიშალოს: ოპერაციები, სხეულები, კომპონენტები ან ესკიზის გეომეტრია", + "ui.depth": "სიღრმე", + "ui.design": "დიზაინი", + "ui.design_properties.author": "ავტორი", + "ui.design_properties.description": "აღწერა", + "ui.design_properties.exports": "STEP, IGES და 3MF ექსპორტი ამ მონაცემებს შეიცავს, თუ ფორმატში მათთვის ადგილია.", + "ui.design_properties.license": "ლიცენზია", + "ui.design_properties.not_text": "შენახულია არა ტექსტის სახით; აქ აკრეფა მას ჩაანაცვლებს.", + "ui.design_properties.organization": "ორგანიზაცია", + "ui.design_properties.others": "სხვა ხელსაწყოების მონაცემები", + "ui.design_properties.others_note": "პროექტში ინახება უცვლელად და არასოდეს გადის ექსპორტში.", + "ui.design_properties.part_number": "დეტალის ნომერი", + "ui.design_properties.project": "პროექტი", + "ui.design_properties.revision": "რევიზია", + "ui.design_saved": "შენახულია: {path}", + "ui.details_access_caption": "წახნაგები აჩვენებს, მისწვდება თუ არა მათ ხელსაწყო არჩეული მიმართულებიდან.", + "ui.details_angle": "კუთხე", + "ui.details_continuity_caption": "არჩეული ნაკერის რედაქტირება. სხვა ნაკერები თავიანთ პარამეტრებს ინარჩუნებს.", + "ui.details_continuity_stale": "ძველი გეომეტრია: ამ ნაკერის რედაქტირებისთვის ან ხედში ჩასატევად ანალიზი ხელახლა გაუშვით.", + "ui.details_copy_list": "სიის კოპირება", + "ui.details_curvature": "სიმრუდის დაშვება", + "ui.details_curvature_caption": "წახნაგები შეფერილია სიმრუდის ლოკალური რადიუსის მიხედვით.", + "ui.details_direction": "ხელსაწყოს მიმართულება", + "ui.details_draft_caption": "წახნაგები შეფერილია ამოღების მიმართულებასთან კუთხის მიხედვით.", + "ui.details_edit_seam": "ნაკერის რედაქტირება", + "ui.details_fixture": "კომპონენტის ნიმუში — მხოლოდ სანიმუშო მონაცემები", + "ui.details_fixture_caption": "კომპონენტის ნიმუში საილუსტრაციო მნიშვნელობებით; ეს მოდელის შედეგი არ არის.", + "ui.details_fixture_problem": "პრობლემის მქონე სანიმუშო შედეგი", + "ui.details_fixture_readout": "სანიმუშო გაზომილი მნიშვნელობა", + "ui.details_flip": "შებრუნება", + "ui.details_gap": "ღრეჩო", + "ui.details_hatch": "ჭრილის წახნაგების დაშტრიხვა", + "ui.details_jump": "სიმრუდის ნახტომი", + "ui.details_key": "ლეგენდა", + "ui.details_offset": "წანაცვლება", + "ui.details_plane": "სიბრტყე", + "ui.details_pull": "ამოღების მიმართულება", + "ui.details_radius": "რადიუსი", + "ui.details_readout": "მაჩვენებლები", + "ui.details_samples": "შერჩევის წერტილები", + "ui.details_seam": "{body} · წიბო {edge}", + "ui.details_settings": "პარამეტრები", + "ui.details_sharp_gap": "ტეხი ან ღრეჩო", + "ui.details_show_all": "ყველას ჩვენება: {count}", + "ui.details_smooth": "გლუვი", + "ui.details_stripes": "ზოლები", + "ui.details_target": "გეომეტრიის ხედში ჩატევა", + "ui.details_worst_seams": "ყველაზე ცუდი ნაკერები", + "ui.details_zebra_caption": "არეკლილი ზოლები აჩვენებს, რამდენად გლუვად უერთდება წახნაგები ერთმანეთს.", + "ui.diameter": "დიამეტრი", + "ui.dimension": "ზომა", + "ui.direct_interaction": "პირდაპირი მოქმედება", + "ui.direct_interaction_note": "მოდელზე პირდაპირ ხედვის არეში იმუშავეთ. დააჭირეთ ბრტყელ წახნაგს ან პროფილს და გასწიეთ: ზემოთ — ამოწევა, ქვემოთ სხეულში — ამოჭრა, გვერდზე მოძრაობა კი ბიჯის ზომას ადგენს", + "ui.direction": "მიმართულება", + "ui.display_quality": "ჩვენების ხარისხი", + "ui.display_quality_coarse": "უხეში", + "ui.display_quality_fine": "დეტალური", + "ui.display_quality_normal": "ჩვეულებრივი", + "ui.display_quality_ultra": "ულტრა", + "ui.distance": "მანძილი", + "ui.distance_1": "მანძილი 1", + "ui.distance_2": "მანძილი 2", + "ui.document_settings": "დოკუმენტის პარამეტრები", + "ui.don_t_save": "არ შეინახო", + "ui.draft": "დახრა", + "ui.drawing": "ნახაზი", + "ui.drill_point": "ბურღის წვერი", + "ui.easyprint_consent": "EasyPrint არის Printables-ის სლაისერი ბრაუზერში. მოდელის იქ გასახსნელად SolidCraft მას Printables-ის სერვერებზე ატვირთავს. ბმულს 30 წუთში გასდის ვადა და Printables-ში შესული უნდა იყოთ. გავაგრძელოთ?", + "ui.easyprint_failed": "EasyPrint-ზე ატვირთვა ვერ მოხერხდა: {error}", + "ui.easyprint_opened": "გაიხსნა EasyPrint-ში", + "ui.easyprint_row": "EasyPrint (Printables, ბრაუზერში)", + "ui.easyprint_uploading": "იტვირთება Printables-ზე…", + "ui.edit": "რედაქტირება", + "ui.editJointLimits": "შეერთების ზღვრების რედაქტირება", + "ui.edit_in_place": "ადგილზე რედაქტირება", + "ui.edit_in_place_after_turn": "რედაქტირება დასრულდება, როცა აგენტის სვლა დამთავრდება", + "ui.edit_in_place_agent_busy": "აგენტი ჯერ კიდევ მუშაობს ამ პროექტში; სცადეთ ხელახლა, როცა მისი სვლა დასრულდება", + "ui.edit_in_place_already_queued": "ერთი რედაქტირება უკვე ელოდება აგენტის სვლის დასრულებას", + "ui.edit_in_place_assembly_closed": "{name} აღარ არის გახსნილი", + "ui.edit_in_place_banner": "რედაქტირება {name}-ში", + "ui.edit_in_place_busy": "ჯერ დაასრულეთ ან გააუქმეთ ის, რაც გახსნილია", + "ui.edit_in_place_none": "არცერთი მიბმული პროექტი არ რედაქტირდება ადგილზე", + "ui.edit_in_place_not_saved": "დეტალს შეუნახავი ცვლილებები აქვს; რედაქტირების დასასრულებლად შეინახეთ იგი", + "ui.edit_in_place_open_elsewhere": "{name} გახსნილია სხვა SolidCraft-ში", + "ui.edit_in_place_opens_after_turn": "დეტალი გაიხსნება, როცა აგენტის სვლა დასრულდება", + "ui.edit_in_place_refresh_dropped": "ბმულების განახლების დროს აწყობა შეიცვალა; გაუშვით ხელახლა", + "ui.edit_in_place_refresh_stopped": "ბმულების განახლება დასრულებამდე შეჩერდა", + "ui.edit_in_place_refreshing": "ბმულები ახლდება {name}-ში…", + "ui.edit_in_place_save_first": "ჯერ აწყობა შეინახეთ: მისი მიბმული პროექტები მისი ფაილით მოიძებნება", + "ui.edit_in_place_save_waits": "{name}-ში ბმულების განახლება მიმდინარეობს; შეინახეთ, როცა დასრულდება", + "ui.edit_in_place_saved_elsewhere": "დეტალი სხვა ფაილში შეინახა; აწყობა კვლავ {name}-ს უკავშირდება", + "ui.edit_in_place_wait": "დაელოდეთ, სანამ პროექტში გაშვებული პროცესი დასრულდება", + "ui.edit_section_analysis": "კვეთის ანალიზის რედაქტირება", + "ui.edit_sketch_empty": "რედაქტირებადი ესკიზები არ არის", + "ui.ellipse": "ელიფსი", + "ui.emboss_wrap_note": "ერთი მხარდაჭერილი ცილინდრის მხები ორთოგონალური ხაზოვანი პროფილები მას ავტომატურად შემოეხვევა. სამიზნის ასარჩევად აირჩიეთ კედელი.", + "ui.end": "ბოლო", + "ui.end_radius": "ბოლო რადიუსი", + "ui.end_scale": "ბოლო მასშტაბი", + "ui.ends": "ბოლოები", + "ui.entities": "ობიექტები", + "ui.equal": "ტოლობა", + "ui.equation_end": "დასასრული", + "ui.equation_explicit": "ცხადი", + "ui.equation_form": "ფორმა", + "ui.equation_note": "ცვლადი უბრალო რიცხვია: sin(t) მას რადიანებში იღებს. ერთეულის გარეშე შედეგი პროექტის ერთეულშია.", + "ui.equation_note_range": "ცვლადი სიგრძეა, ისევე როგორც მისი დიაპაზონი: შეურიეთ ის სიგრძის პარამეტრებს, sin()-ისთვის კი სიგრძეზე გაყავით. ერთეულის გარეშე შედეგი პროექტის ერთეულშია.", + "ui.equation_parametric": "პარამეტრული", + "ui.equation_variable_unit": "ცვლადს დიაპაზონის ერთეული აქვს", + "ui.equation_x_of_t": "x(t)", + "ui.equation_y_of_t": "y(t)", + "ui.equation_y_of_x": "y(x)", + "ui.equivalent_radius": "ეკვივალენტური რადიუსი", + "ui.expand": "გაშლა", + "ui.explode_needs_two_components": "დაშლილი ხედი კომპონენტებს ერთმანეთს აშორებს, ამიტომ პროექტს ორი ან მეტი კომპონენტი სჭირდება (ახალი კომპონენტი, პროექტის ჩასმა ან კომპონენტების შექმნა სხეულებიდან)", + "ui.exportDxf": "DXF ექსპორტი…", + "ui.export_ellipsis_keymap": "ექსპორტი…", + "ui.export_keymap_tip": "კლავიშები, S ველის რჩეულები და ხელსაწყოთა ზოლი, ფაილის სახით", + "ui.extend": "გაგრძელება", + "ui.extent": "ზღვარი", + "ui.extent_type": "ზღვრის ტიპი", + "ui.extract_component": "ფაილში გატანა…", + "ui.extract_design_changed": "ფაილის არჩევისას პროექტი შეიცვალა. ფაილში გატანა თავიდან დაიწყეთ.", + "ui.extract_done": "კომპონენტი ახლა ცალკე პროექტია და აქ არის მიბმული.", + "ui.extrude": "ამოწევა", + "ui.extrude_auto_to_object": "ამოწევა არჩეულ სამიზნემდე", + "ui.extrude_auto_to_object_tip": "ამოწევისას, როცა პროფილი არჩეულია, მისი სიბრტყის გარეთ წახნაგის, წვეროს ან პარალელური სიბრტყის არჩევა ზღვარს „ობიექტამდე“ რეჟიმზე გადართავს", + "ui.factor": "კოეფიციენტი", + "ui.fade": "მილევა", + "ui.fade_length": "მილევის სიგრძე", + "ui.feature_history": "ოპერაციების ქრონოლოგია", + "ui.feature_options": "ოპერაციის პარამეტრები", + "ui.features": "ოპერაციები", + "ui.file": "ფაილი", + "ui.fillet": "მომრგვალება", + "ui.fillet_corner_ball": "სფერო", + "ui.fillet_corner_ball_tip": "მგორავი სფეროს ნაწილი, თითოეული მომრგვალების მხები (G1).", + "ui.fillet_corner_curvature_tip": "სიმრუდე (G2): გლუვი საკერებელი. კუთხე თითოეული წიბოს გასწვრივ უკან იწევს დაშორების ოდენობით (რადიუსი × {factor}, თუ სხვას არ აკრეფთ) და ივსება საკერებლით, ასე რომ ანარეკლები მასში გადატეხვის გარეშე გადის.", + "ui.fillet_corner_needs_constant": "გლუვი საკერებლით კუთხეებს (G2) სჭირდება მუდმივი რადიუსი და ზუსტი მისადაგება.", + "ui.fillet_corner_patch": "გლუვი საკერებელი", + "ui.fillet_corner_patch_tip": "სიმრუდის უწყვეტობა (G2): კუთხე თითოეული წიბოს გასწვრივ უკან იწევს და ივსება საკერებლით, ასე რომ ანარეკლები მასში გადატეხვის გარეშე გადის.", + "ui.fillet_corner_tangent_tip": "მხები (G1): მგორავი სფეროს კუთხე, მგორავი სფეროს ნაწილი, თითოეული მომრგვალების მხები.", + "ui.fillet_error_corner": "გლუვი კუთხის აგება აქ ვერ მოხერხდა. სცადეთ სხვა დაშორება ან მხები კუთხეები.", + "ui.fillet_error_failed": "ამ წიბოებზე ეს მომრგვალება ვერ აიგო. სცადეთ სხვა რადიუსი ან ერთდროულად ნაკლები წიბოს მომრგვალება.", + "ui.fillet_error_setback_short": "დაშორება ამ კუთხის საკერებლისთვის ძალიან მოკლეა: ის {least}-დან აიგება. სცადეთ უფრო გრძელი დაშორება.", + "ui.fillet_error_too_large": "რადიუსი ძალიან დიდია ამ წიბოების მიმდებარე წახნაგებისთვის. სცადეთ უფრო მცირე რადიუსი, ან „წახნაგების ზღვრებში“ აირჩიეთ „უდიდესი რადიუსი“.", + "ui.fillet_fit": "წახნაგების ზღვრები", + "ui.fillet_fit_exact": "ზუსტი რადიუსი", + "ui.fillet_fit_needs_constant": "რადიუსის მისადაგებას მუდმივი რადიუსი სჭირდება.", + "ui.fillet_fit_reduce": "უდიდესი რადიუსი", + "ui.fillet_fit_taper": "შევიწროებული რადიუსი", + "ui.fillet_fit_tip": "როცა რადიუსი იმაზე დიდია, ვიდრე წიბოს მიმდებარე წახნაგები იძლევა.\nზუსტი რადიუსი: რადიუსი, როგორც მითითებულია, ან არაფერი მომრგვალდება და შეტყობინება ახსნის მიზეზს.\nუდიდესი რადიუსი: ყოველი წიბო მომრგვალდება უდიდესი რადიუსით, რომელიც ეტევა.\nშევიწროებული რადიუსი: რადიუსი შენარჩუნებულია, მომრგვალება მხოლოდ იქ ვიწროვდება, სადაც წახნაგები მთავრდება.", + "ui.fillet_options_tip": "მხებთა ჯაჭვი: ასევე მომრგვალდება წიბოები, რომლებიც არჩეულებს გლუვად აგრძელებს.\nწინასწარი ნახვა: შედეგის ჩვენება ხედში რედაქტირებისას.", + "ui.fillet_setback": "დაშორება", + "ui.fillet_setback_hint": "რადიუსი × {factor}", + "ui.fillet_setback_least": "{least}-ზე მეტი", + "ui.fillet_setback_tip": "სად იწყება კუთხის გლუვი საკერებელი: რა მანძილზე კუთხიდან თითოეული წიბოს გასწვრივ. ნაგულისხმევად ეს რადიუსი × {factor}-ია. ის უნდა აღემატებოდეს უმცირეს დაშორებას, რომლის დროსაც მომრგვალებები დაშორების გარეშე ხვდება ერთმანეთს: რადიუსს იქ, სადაც წახნაგები ერთმანეთის მართობულია.", + "ui.fillet_smooth_radius": "რადიუსის გლუვი ცვლილება", + "ui.fillet_type_choices_tip": "მუდმივი რადიუსი: ერთი რადიუსი წიბოს მთელ სიგრძეზე.\nქორდის სიგრძე: მომრგვალების სიგანე უცვლელია, რა კუთხითაც არ უნდა ხვდებოდეს წახნაგები ერთმანეთს.\nცვლადი რადიუსი: რადიუსი თითოეულ ბოლოში და მეტი წიბოს გასწვრივ, თუ დაამატებთ.\nსიმრუდის უწყვეტობით: კვეთი, რომელიც ბრტყელ წახნაგებთან შეხვედრისას ანარეკლებს არ ტეხს (G2).\nსპლაინი: რადიუსი წიბოს გასწვრივ თქვენ მიერ მითითებულ საკონტროლო რადიუსებს მიჰყვება.", + "ui.fillet_type_curvature": "სიმრუდის უწყვეტობით", + "ui.fillet_type_tip": "კვეთი წიბოს გარდიგარდმო. სიმრუდის უწყვეტობით: სიმრუდის მიხედვით უწყვეტი (G2) კვეთი ბრტყელ წახნაგებს შორის, ასე რომ ანარეკლები წახნაგებიდან მომრგვალებაში გადატეხვის გარეშე გადადის.", + "ui.filter_commands_or_keys": "ბრძანებების ან კლავიშების გაფილტვრა", + "ui.findInTimeline": "ქრონოლოგიაში ძებნა", + "ui.findInWindow": "ფანჯარაში ძებნა", + "ui.fine": "წვრილი", + "ui.finest": "უწვრილესი", + "ui.finish_sketch": "ესკიზის დასრულება", + "ui.fit": "ჩატევა", + "ui.fix_unfix": "ფიქსაცია/ფიქსაციის მოხსნა", + "ui.flat": "ბრტყელი", + "ui.flip": "შებრუნება", + "ui.format": "ფორმატი", + "ui.frame_rate": "კადრების სიხშირე", + "ui.frame_rate_details": "კადრების სიხშირის დეტალები", + "ui.front": "წინა", + "ui.fully_constrained": "სრულად შეზღუდული", + "ui.function": "ფუნქცია", + "ui.general": "ზოგადი", + "ui.gpu_memory_lowered": "ვიდეობარათს მეხსიერება ამოეწურა: ხედი დაბალი ხარისხით იხატება.", + "ui.graphics": "გრაფიკა", + "ui.graphics_custom": "მორგებული", + "ui.graphics_performance": "წარმადობა", + "ui.graphics_preset": "გრაფიკის პრესეტი", + "ui.graphics_preset_help": "ხარისხი: გარემოს დაჩრდილვა (ambient occlusion), ჩვენების ხარისხი „დეტალური“ და ადაპტური 2× სუპერსემპლინგი. წარმადობა: გარემოს დაჩრდილვის გარეშე, ჩვენების ხარისხი „ჩვეულებრივი“ და სუპერსემპლინგი გამორთული. ხელით ცვლილებისას ჩანს „მორგებული“. MSAA უცვლელი რჩება.", + "ui.graphics_quality": "ხარისხი", + "ui.grid_follows_view": "ბადე ხედს მიჰყვება", + "ui.grid_follows_view_hint": "გვერდით ხედებში ბადე ჩანს მათკენ მიმართულ ვერტიკალურ სიბრტყეზე და არა მიწაზე", + "ui.ground_shadow": "ჩრდილი მიწაზე", + "ui.groupSelected": "მონიშნულის დაჯგუფება", + "ui.hatch": "დაშტრიხვა", + "ui.heading_add_ins": "დანამატები", + "ui.heading_assemble": "აწყობა", + "ui.heading_box": "პარალელეპიპედი", + "ui.heading_chamfer": "ფასკა", + "ui.heading_circular_pattern": "წრიული მასივი", + "ui.heading_coil": "ხვია", + "ui.heading_combine": "გაერთიანება", + "ui.heading_cone": "კონუსი", + "ui.heading_configure": "კონფიგურაცია", + "ui.heading_constraints": "შეზღუდვები", + "ui.heading_construct": "დამხმარე გეომეტრია", + "ui.heading_create": "შექმნა", + "ui.heading_create_sketch": "ესკიზის შექმნა", + "ui.heading_cylinder": "ცილინდრი", + "ui.heading_design": "დიზაინი", + "ui.heading_draft": "დახრა", + "ui.heading_edit": "რედაქტირება", + "ui.heading_equation_curve": "მრუდი განტოლებით", + "ui.heading_extrude": "ამოწევა", + "ui.heading_fillet": "მომრგვალება", + "ui.heading_finish_editing": "რედაქტირების დასრულება", + "ui.heading_finish_sketch": "ესკიზის დასრულება", + "ui.heading_form": "ფორმა", + "ui.heading_front": "წინა", + "ui.heading_hole": "ხვრელი", + "ui.heading_home": "მთავარი", + "ui.heading_insert": "ჩასმა", + "ui.heading_inspect": "შემოწმება", + "ui.heading_interference": "გადაფარვა", + "ui.heading_loft": "კვეთებით აგება", + "ui.heading_make": "დამზადება", + "ui.heading_measure": "გაზომვა", + "ui.heading_mesh": "პოლიგონური ბადე", + "ui.heading_mirror": "არეკვლა", + "ui.heading_modify": "შეცვლა", + "ui.heading_move": "გადაადგილება", + "ui.heading_move_copy": "გადაადგილება/კოპირება", + "ui.heading_offset": "წანაცვლება", + "ui.heading_offset_plane": "წანაცვლებული სიბრტყე", + "ui.heading_ok": "OK", + "ui.heading_parameters": "პარამეტრები", + "ui.heading_pattern": "მასივი", + "ui.heading_pattern_on_path": "მასივი ტრაექტორიაზე", + "ui.heading_pipe": "მილი", + "ui.heading_plane_at_angle": "სიბრტყე კუთხით", + "ui.heading_plastic": "პლასტმასი", + "ui.heading_position": "პოზიცია", + "ui.heading_prepare": "მომზადება", + "ui.heading_rectangular_pattern": "მართკუთხა მასივი", + "ui.heading_revolve": "ბრუნვით აგება", + "ui.heading_right": "მარჯვენა", + "ui.heading_save_mesh": "პოლიგონურ ბადედ შენახვა", + "ui.heading_scale": "მასშტაბირება", + "ui.heading_section_analysis": "კვეთის ანალიზი", + "ui.heading_select": "მონიშვნა", + "ui.heading_setup": "მომართვა", + "ui.heading_sheet_metal": "ფურცლოვანი ლითონი", + "ui.heading_shell": "გარსი", + "ui.heading_sketch": "ესკიზი", + "ui.heading_sketch_scale": "ესკიზის მასშტაბირება", + "ui.heading_solid": "სხეული", + "ui.heading_sphere": "სფერო", + "ui.heading_split_body": "სხეულის გაყოფა", + "ui.heading_surface": "ზედაპირი", + "ui.heading_sweep": "ტრაექტორიით აგება", + "ui.heading_thread": "კუთხვილი", + "ui.heading_top": "ზედა", + "ui.heading_torus": "ტორი", + "ui.heading_utilities": "უტილიტები", + "ui.heading_utility": "უტილიტა", + "ui.heading_weldments": "შედუღებული კონსტრუქციები", + "ui.height": "სიმაღლე", + "ui.help": "დახმარება", + "ui.hide": "დამალვა", + "ui.hideAxes": "ღერძების დამალვა", + "ui.hideDimension": "ზომის დამალვა", + "ui.hideOrigin": "სათავის დამალვა", + "ui.hidePlanes": "სიბრტყეების დამალვა", + "ui.hideProfile": "პროფილის დამალვა", + "ui.hide_component_history": "მისი ქრონოლოგიის დამალვა", + "ui.hide_origin_by_default": "სათავე ნაგულისხმევად დამალულია", + "ui.hide_origin_note": "ახალი პროექტები სათავის საქაღალდით დამალულით იწყება. როცა სათავეს აჩვენებთ ან დამალავთ, პროექტი თავის პარამეტრს ინარჩუნებს.", + "ui.history_back": "ერთი ნაბიჯით უკან", + "ui.history_below_browser": "მოდელის ხის ქვემოთ", + "ui.history_edge_hint": "ორჯერ დაწკაპეთ კიდეზე", + "ui.history_first": "დასაწყისში გადასვლა", + "ui.history_forward": "ერთი ნაბიჯით წინ", + "ui.history_hide_hidden": "დამალული კომპონენტების დამალვა", + "ui.history_hide_names": "სახელების დამალვა", + "ui.history_last": "ბოლოში გადასვლა", + "ui.history_marker_tip": "ქრონოლოგიის მარკერი: მოდელის უკან დასაბრუნებლად გადაათრიეთ; ახალი ოპერაციები აქ ემატება", + "ui.history_names": "სახელები", + "ui.history_play": "ბოლომდე დაკვრა", + "ui.history_play_button_hide": "დაკვრის ღილაკის დამალვა", + "ui.history_play_button_show": "დაკვრის ღილაკის ჩვენება", + "ui.history_play_finish_action": "ქრონოლოგიის დაკვრამდე დაასრულეთ მიმდინარე მოქმედება", + "ui.history_play_roll_back": "დაკვრამდე ქრონოლოგიის მარკერი უკან გადაიტანეთ", + "ui.history_show_hidden": "დამალული კომპონენტების ჩვენება", + "ui.history_show_names": "სახელების ჩვენება", + "ui.history_sketch_listed_under": "ჩამოთვლილია ოპერაციის ქვეშ: {feature}", + "ui.history_title": "ქრონოლოგია", + "ui.history_toggle_names": "ოპერაციების სახელების ჩვენება ან დამალვა", + "ui.history_waits_for_editor": "დაბრუნება, ხელახლა შესრულება და ქრონოლოგია ელოდება, სანამ ოპერაციის რედაქტორი გაიხსნება", + "ui.hole": "ხვრელი", + "ui.hole_tap_type": "ხვრელის კუთხვილის ტიპი", + "ui.hole_type": "ხვრელის ტიპი", + "ui.home": "საწყისი ხედი", + "ui.homeView": "საწყისი ხედი", + "ui.horizontal_constraint": "ჰორიზონტალურობის შეზღუდვა", + "ui.horizontal_vertical": "ჰორიზონტალური/ვერტიკალური", + "ui.import_ellipsis": "იმპორტი…", + "ui.infinite": "უსასრულო", + "ui.insert": "ჩასმა", + "ui.insert_design.browse": "არჩევა…", + "ui.insert_design.open_designs": "გახსნილი პროექტები", + "ui.insert_design.saved_file": "{name}-ს შეუნახავი ცვლილებები აქვს, ამიტომ ჩაისვა მისი შენახული ფაილი. შეინახეთ იგი, შემდეგ ცვლილებების შემოსატანად გაუშვით ბმულების განახლება.", + "ui.insert_design.unsaved": "შეუნახავი ცვლილებები", + "ui.inspect": "შემოწმება", + "ui.instances": "ეგზემპლარები", + "ui.intersect": "გადაკვეთა", + "ui.iso_4753": "ISO 4753", + "ui.isolate": "იზოლირება", + "ui.join": "შეერთება", + "ui.joint_play": "▶ დაკვრა", + "ui.joint_stop": "■ შეჩერება", + "ui.joints": "შეერთებები", + "ui.keyboard_shortcuts": "კლავიატურის მალსახმობები", + "ui.language": "ენა", + "ui.lasso_select": "ლასო (შემოხაზეთ თავისუფალი მარყუჟი: მოინიშნება ის, რაც მთლიანად შიგნითაა)", + "ui.layout_compact": "კომპაქტური", + "ui.layout_floating": "მცურავი", + "ui.length": "სიგრძე", + "ui.length_decimals": "სიგრძის ათწილადი ნიშნები", + "ui.light": "ღია", + "ui.line": "ხაზი", + "ui.line_arc_hint": "მხები რკალი: დაწკაპეთ რკალის ბოლოზე. ხაზებზე დასაბრუნებლად კვლავ შეჩერდით ბოლო წერტილზე; დასასრულებლად დაწკაპეთ მარჯვენა ღილაკით ან დააჭირეთ Esc-ს", + "ui.link_copies": "იდენტური ასლების მიბმა", + "ui.link_copies_keep": "შენარჩუნება", + "ui.link_copies_link": "მიბმა", + "ui.link_copies_text": "ეს კომპონენტები იმავე სხეულებს აგებს, რასაც {name}. გადავაქციოთ ისინი მისი ბმულის განთავსებებად?", + "ui.lock": "ჩაკეტვა", + "ui.loft": "კვეთებით აგება", + "ui.look_at": "პირისპირ ხედი", + "ui.look_at_anim_desc": "ღერძული ხედი, პირისპირ ხედი, საწყისი ხედი და ჩატევა", + "ui.major_radius": "დიდი რადიუსი", + "ui.manipulator_free_alt": "მანიპულატორის თავისუფალი გადათრევა Alt/Option-ითაც", + "ui.manipulator_free_alt_tip": "ჩართული: Alt/Option ან Ctrl/Cmd ამოწევის / მანიპულატორის ისრებზე მნიშვნელობებზე მიბმას თიშავს. გამორთული: მხოლოდ Ctrl/Cmd.", + "ui.manufacture": "წარმოება", + "ui.material_review.axes": "მასალის ლოკალური ღერძები; სხეულის ორიენტაცია მინიჭებული არ არის.", + "ui.material_review.claims": "წყაროები და ლიცენზიები გადაუმოწმებელი განცხადებებია. გამოტოვებული მნიშვნელობები უცნობი რჩება.", + "ui.material_review.compressive_strength": "სიმტკიცე კუმშვაზე", + "ui.material_review.conditions": "მითითებული პირობები", + "ui.material_review.density": "სიმკვრივე", + "ui.material_review.derived": "მიღებული იზოტროპული მოდულები", + "ui.material_review.elasticity": "დრეკადობა", + "ui.material_review.input": "ჩასვით schema-1 მასალის ბარათი (JSON)", + "ui.material_review.limit": "ბარათი აჭარბებს შეყვანის 256 KiB ზღვარს.", + "ui.material_review.moisture_unit": "kg წყალი / kg მშრალი მასალა", + "ui.material_review.properties": "თვისებები", + "ui.material_review.review": "ბარათის განხილვა", + "ui.material_review.scope": "მხოლოდ კანდიდატი: არ არის მინიჭებული ან შენახული. რიცხვითი შემოწმება საინჟინრო სერტიფიცირება არ არის.", + "ui.material_review.shear_strength": "სიმტკიცე ძვრაზე", + "ui.material_review.source": "წყარო", + "ui.material_review.specific_heat": "კუთრი სითბოტევადობა", + "ui.material_review.tensile_strength": "სიმტკიცე გაჭიმვაზე", + "ui.material_review.thermal_conductivity": "თბოგამტარობა", + "ui.material_review.thermal_expansion": "თერმული გაფართოება", + "ui.material_review.title": "მასალის ფიზიკური მონაცემების განხილვა", + "ui.material_review.unknown": "უცნობი", + "ui.material_review.yield_strength": "დენადობის ზღვარი", + "ui.measure": "გაზომვა", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF წახნაგების ჭდეებით", + "ui.mesh_format_stl": "STL", + "ui.minor_radius": "მცირე რადიუსი", + "ui.mirror": "არეკვლა", + "ui.mirror_line": "არეკვლის ხაზი", + "ui.modifiers_either": "{first} ან {second}", + "ui.move": "გადაადგილება", + "ui.multiple": "რამდენიმე", + "ui.named_views": "დასახელებული ხედები", + "ui.nav_bridge": "ნავიგაცია ამ კომპიუტერზე მოწყობილობის აპით", + "ui.nav_bridge_connected": "დაკავშირებულია", + "ui.nav_bridge_port": "პორტი", + "ui.nav_bridge_tip": "3D შეყვანის მოწყობილობის საკუთარი პროგრამა (მაგალითად, ხელნაკეთი 3D მაუსის დრაივერი) ხედს ლოკალური კავშირით ამოძრავებს, ასე რომ მაუსის მაჩვენებელი თქვენს განკარგულებაში რჩება. SolidCraft მას ამ პორტზე უკავშირდება, მხოლოდ ამ კომპიუტერზე.", + "ui.nav_bridge_waiting": "მოწყობილობის აპის მოლოდინი", + "ui.navigation": "ნავიგაცია", + "ui.needs_design": "{command}: ჯერ გახსენით პროექტი", + "ui.newSketchGroup": "ესკიზების ახალი ჯგუფი", + "ui.new_body": "ახალი სხეული", + "ui.new_design": "ახალი პროექტი", + "ui.no_geometry_yet": "გეომეტრია ჯერ არ არის", + "ui.no_slicer_found": "სლაისერი ვერ მოიძებნა", + "ui.normal": "ჩვეულებრივი", + "ui.normalConstruction": "ჩვეულებრივი / დამხმარე", + "ui.not_a_program": "{path} არ არის გასაშვები პროგრამა", + "ui.object_type": "ობიექტის ტიპი", + "ui.objects": "ობიექტები", + "ui.offer_to_stand_up_y_up_files": "Y-ზემოთ ფაილების წამოყენების შეთავაზება", + "ui.offset": "წანაცვლება", + "ui.offset_plane": "წანაცვლებული სიბრტყე", + "ui.one_side": "ერთი მხარე", + "ui.open": "გახსნა", + "ui.open_ends_tip": "არაფერს ეხება", + "ui.open_linked_design": "მიბმული პროექტის გახსნა", + "ui.open_preferences": "პარამეტრების გახსნა", + "ui.open_recent": "ბოლოს გახსნილი ფაილების გახსნა", + "ui.operation": "ოპერაცია", + "ui.options": "პარამეტრები", + "ui.orbit": "ორბიტა", + "ui.orbit_around": "ორბიტის ცენტრი", + "ui.orientation": "ორიენტაცია", + "ui.origin": "სათავე", + "ui.palette_construction_mode": "დამხმარე რეჟიმი (X)", + "ui.palette_more": "მეტი", + "ui.palette_sketch_options": "ესკიზის პარამეტრები", + "ui.pan": "პანორამა", + "ui.pan_zoom_orbit": "პანორამა, მასშტაბი, ორბიტა", + "ui.parallel": "პარალელური", + "ui.parameters": "პარამეტრები", + "ui.part_size_needs_a_part": "ზომის შესაცვლელად მონიშნეთ ჩასმული სტანდარტული დეტალი (ხრახნი, ქანჩი, საყელური ან შტიფტი). სხეულის გასადიდებლად ან დასაპატარავებლად გამოიყენეთ მასშტაბირება.", + "ui.part_size_shared": "დეტალი თავიდან აიგება და ყველა დამატებული ოპერაცია ჩანაცვლდება. ამ კომპონენტის ყველა შემთხვევა განახლდება.", + "ui.paste": "ჩასმა", + "ui.patch_continuity_corner_tip": "საკერებელი მის გარშემო მდებარე წახნაგებს თითოეული მხრის გასწვრივ არჩეული უწყვეტობით ხვდება. კუთხეში, სადაც ეს წახნაგები ერთმანეთს სხვადასხვა სიმრუდით ხვდება, ის იქ მხებად (G1) რჩება.", + "ui.path": "ტრაექტორია", + "ui.pattern_object_type_tip": "სხეულები: მყარი ფორმები, არჩეული ხედში ან მოდელის ხეში; თითოეული მთლიანად კოპირდება.\nოპერაციები: ქრონოლოგიის ნაბიჯები, მაგალითად, ამოწევა ან ხვრელი, არჩეული ქრონოლოგიაში ან მათ მიერ შექმნილ წახნაგზე; ნაბიჯი მეორდება.\nესკიზი არც ერთია და არც მეორე: მისი მრუდები გაიმეორეთ თავად ესკიზის მასივით ან არეკვლით, ან ჯერ ამოწიეთ.", + "ui.pattern_on_path": "მასივი ტრაექტორიაზე", + "ui.perforate_margin_default": "დიამეტრიდან", + "ui.perforate_pitch": "ბიჯი", + "ui.perforate_square": "კვადრატული", + "ui.perforate_staggered": "ჭადრაკული (60°)", + "ui.perforate_title": "პერფორაცია", + "ui.perpendicular": "მართობული", + "ui.perspective_view": "პერსპექტიული ხედი", + "ui.pinToShortcuts": "მალსახმობებზე მიმაგრება", + "ui.pinToToolbar": "ხელსაწყოთა ზოლზე მიმაგრება", + "ui.pipe": "მილი", + "ui.pitch": "ბიჯი", + "ui.placement": "განთავსება", + "ui.placement_handles": "განთავსების სახელურები", + "ui.placement_handles_tip": "სახელურები საყრდენის, ბოსის ან ჩამკეტის გადახედვაზე: მარკერი გადაათრიეთ მოდელზე მის გადასაადგილებლად, ხოლო რგოლით შეაბრუნეთ", + "ui.plane": "სიბრტყე", + "ui.plane_at_angle": "სიბრტყე კუთხით", + "ui.plugins": "პლაგინები", + "ui.plugins_desktop": "პლაგინები ხელმისაწვდომია დესკტოპის აპში.", + "ui.plugins_empty": "პლაგინები დაინსტალირებული არ არის.", + "ui.plugins_none": "ამ ძიებას არცერთი პლაგინი არ შეესაბამება.", + "ui.plugins_note": "თითოეული პლაგინი არის საქაღალდე {path}-ში plugin.json ფაილით. SolidCraft ამ ფაილს კითხულობს და საქაღალდიდან არანაირ კოდს არ უშვებს. პლაგინის გამორთვისას ის დაინსტალირებული რჩება.", + "ui.plugins_search": "პლაგინების ძიება", + "ui.plugins_skipped": "საქაღალდე, რომლის წაკითხვაც ვერ მოხერხდა: {count}.", + "ui.plugins_version": "{version}", + "ui.point": "წერტილი", + "ui.point_cloud_add_filter": "ფილტრის დამატება…", + "ui.point_cloud_auto_range": "ავტომატური დიაპაზონი", + "ui.point_cloud_color_by": "შეფერვა", + "ui.point_cloud_file_colors": "ფაილის ფერები", + "ui.point_cloud_filter_by": "ფილტრი", + "ui.point_cloud_height_high": "უმაღლესი", + "ui.point_cloud_height_low": "უდაბლესი", + "ui.point_cloud_legend_filter": "ჩანს და იმალება ზემოთ მოცემული ლეგენდით", + "ui.point_cloud_no_file_colors": "ფაილს ფერები არ აქვს", + "ui.point_cloud_pause": "პაუზა", + "ui.point_cloud_play": "დაკვრა", + "ui.point_cloud_single_color": "ერთი ფერი", + "ui.point_cloud_size": "წერტილის ზომა", + "ui.point_cloud_units": "ფაილის ერთეულები", + "ui.point_under_the_cursor": "წერტილი კურსორის ქვეშ", + "ui.points": "წერტილები", + "ui.polygon": "მრავალკუთხედი", + "ui.preferences": "პარამეტრები", + "ui.press_a_key": "დააჭირეთ კლავიშს…", + "ui.print_face_body_not_sent": "ამ წახნაგის სხეული არ იგზავნება: ჯერ დაამატეთ ის სხეულებში", + "ui.print_face_cleared": "{body}: ბეჭდვის წახნაგი მოიხსნა", + "ui.print_face_input": "ბეჭდვის წახნაგი", + "ui.print_face_pick": "მყარი სხეულის ერთი ბრტყელი წახნაგი მონიშნეთ, რომ ბეჭდვის წახნაგად აქციოთ", + "ui.print_face_set": "{body}: ბეჭდვის წახნაგი დაყენდა; სლაისერში გაგზავნა სხეულს მასზე დადებს", + "ui.profile": "პროფილი", + "ui.profile_plane": "პროფილის სიბრტყე", + "ui.profiles": "პროფილები", + "ui.project": "პროეცირება", + "ui.project_face_edges_sketch": "წახნაგის წიბოების პროეცირება ახალ ესკიზებში", + "ui.properties": "თვისებები", + "ui.properties.copy_matrix": "მატრიცის კოპირება", + "ui.properties.first_moments": "სტატიკური მომენტები", + "ui.properties.inertia": "ინერციის მომენტი", + "ui.properties.inertia_note": "მასის ცენტრის მიმართ, მსოფლიო ღერძებში (g·{unit}²)", + "ui.properties.inertia_unavailable": "მიუწვდომელია: სხეულის პოლიგონური ბადე არ არის შეკრული.", + "ui.properties.inertia_x": "Ixx, Ixy, Ixz", + "ui.properties.inertia_y": "Iyx, Iyy, Iyz", + "ui.properties.inertia_z": "Izx, Izy, Izz", + "ui.properties.measuring": "იზომება…", + "ui.properties.measuring_bodies": "იზომება… სხეული: {done} / {total}", + "ui.properties.measuring_failed": "გაზომვა დასრულებამდე შეჩერდა.", + "ui.properties.principal_axis": "მთავარი ღერძი {number}", + "ui.properties.principal_moments": "მთავარი მომენტები", + "ui.pull_direction": "ამოღების მიმართულება", + "ui.quality": "ხარისხი", + "ui.quantity": "რაოდენობა", + "ui.quantity_2": "რაოდენობა 2", + "ui.quit": "გასვლა", + "ui.radial_context_menu": "რადიალური კონტექსტური მენიუ", + "ui.radius": "რადიუსი", + "ui.rail": "მიმმართველი", + "ui.rail_fit": "მიმმართველზე მორგება", + "ui.reachable": "მისაწვდომი", + "ui.rectangle": "მართკუთხედი", + "ui.rectangular_pattern": "მართკუთხა მასივი", + "ui.redo": "ხელახლა შესრულება", + "ui.reference_1": "ორიენტირი 1", + "ui.reference_2": "ორიენტირი 2", + "ui.reference_distance": "მანძილი ორიენტირამდე", + "ui.relink_design_changed": "წყაროს არჩევისას აწყობა შეიცვალა. წყაროს ხელახლა მიბმა თავიდან დაიწყეთ.", + "ui.relink_done": "წყარო ყველა ეგზემპლარისთვის ხელახლა მიება.", + "ui.relink_not_linked": "ეს კომპონენტი წყარო პროექტზე მიბმული არ არის.", + "ui.relink_select_one": "ჯერ მონიშნეთ ერთი მიბმული კომპონენტი ან მისი ერთ-ერთი ეგზემპლარი.", + "ui.relink_source_all": "წყაროს ხელახლა მიბმა (ყველა ეგზემპლარი)…", + "ui.removeFromToolbar": "ხელსაწყოთა ზოლიდან ამოღება", + "ui.removeSection": "კვეთის მოხსნა", + "ui.render": "რენდერი", + "ui.renderer": "რენდერერი", + "ui.repeat": "გამეორება", + "ui.repeat_nothing": "გასამეორებელი ჯერ არაფერია: ჯერ ხელსაწყო ან დიალოგი გაუშვით.", + "ui.replace_with_link_done": "ასლები ახლა მიბმული პროექტის განთავსებებია.", + "ui.report_a_bug": "შეცდომის შეტყობინება", + "ui.reset": "ჩამოყრა", + "ui.reset_all": "ყველაფრის ჩამოყრა", + "ui.reset_the_settings_on_this_page": "ამ გვერდის პარამეტრების ჩამოყრა", + "ui.restore": "აღდგენა", + "ui.restore_defaults": "ნაგულისხმევის აღდგენა", + "ui.reverse_horizontal_pan_direction": "ჰორიზონტალური პანორამირების მიმართულების შებრუნება", + "ui.reverse_horizontal_pan_tip": "ორი თითით ჰორიზონტალური გადახვევა და ცერის ბორბალი საპირისპირო მიმართულებით გადაადგილებს ხედს", + "ui.reverse_trackpad_orbit_direction": "ტრეკპადით ორბიტის მიმართულების შებრუნება", + "ui.reverse_trackpad_orbit_tip": "Shift ორი თითით გადახვევასთან ერთად ორბიტას საპირისპირო მიმართულებით აბრუნებს", + "ui.reverse_vertical_pan_direction": "ვერტიკალური პანორამირების მიმართულების შებრუნება", + "ui.reverse_vertical_pan_tip": "ორი თითით ვერტიკალური გადახვევა საპირისპირო მიმართულებით გადაადგილებს ხედს", + "ui.reverse_zoom_direction": "მასშტაბის მიმართულების შებრუნება", + "ui.revolutions": "ბრუნები", + "ui.revolve": "ბრუნვით აგება", + "ui.ribbon_exit": "გასვლა", + "ui.ribbon_labels": "ტექსტის ჩვენება ლენტის ხატულების ქვეშ", + "ui.ribbon_menus_skip_pinned": "მიმაგრებული ბრძანებები ჩამოსაშლელ მენიუებში არ ჩანდეს", + "ui.ribbon_pin_footer": "მიმაგრებული ბრძანებები ლენტზე ჩანს. მისამაგრებლად ან მოსახსნელად მიიტანეთ კურსორი სტრიქონზე.", + "ui.ribbon_workspace": "სამუშაო სივრცე", + "ui.right": "მარჯვენა", + "ui.save": "შენახვა", + "ui.save_as": "შენახვა როგორც", + "ui.save_mesh_no_slicer_open": "სლაისერი ვერ მოიძებნა: აირჩიეთ „სხვა…“ და მიუთითეთ თქვენი სლაისერის პროგრამა", + "ui.save_mesh_pick_bodies": "მონიშნეთ შესანახი სხეულები", + "ui.saved_to": "შენახულია: {path}", + "ui.sbox_pin": "S ველის თავში მიმაგრება", + "ui.sbox_unpin": "მოხსნა", + "ui.scale": "მასშტაბირება", + "ui.second_rail": "მეორე მიმმართველი", + "ui.section_analysis": "კვეთის ანალიზი", + "ui.section_size": "კვეთის ზომა", + "ui.select": "მონიშვნა", + "ui.selectOther": "სხვის მონიშვნა…", + "ui.selectTangentChain": "მხები ჯაჭვის მონიშვნა", + "ui.select_all": "ყველაფრის მონიშვნა", + "ui.select_components_by_face": "კომპონენტების მონიშვნა (წახნაგი თავის კომპონენტს ირჩევს)", + "ui.selection": "მონიშვნა", + "ui.selection_modifiers": "მონიშვნის მოდიფიკატორები", + "ui.selection_shift_add_only": "Shift+დაწკაპება ამატებს, არ აკლებს", + "ui.selection_shift_add_only_tip": "ჩართული: Shift ამატებს ელემენტებს, Ctrl/Cmd გადართავს. გამორთული (ნაგულისხმევი): Shift და Ctrl/Cmd ორივე გადართავს.", + "ui.send": "გაგზავნა", + "ui.send_to_slicer_unavailable": "სლაისერში გაგზავნას დესკტოპის აპი სჭირდება: ბრაუზერს პროგრამის გაშვება არ შეუძლია", + "ui.sent_to_slicer": "გაიგზავნა {slicer}-ში", + "ui.sent_to_slicer_copy": "გაიგზავნა {slicer}-ში ფაილად {file}, რადგან პირველი ფაილი იქ ჯერ კიდევ გახსნილია", + "ui.sheet_gap": "ღრეჩო", + "ui.shell": "გარსი", + "ui.shortcut_capture_add_key": "დაამატეთ ერთი ჩვეულებრივი კლავიში. Escape აუქმებს.", + "ui.shortcut_capture_hint": "დაწკაპეთ მინიჭებაზე, შემდეგ დააჭირეთ მოდიფიკატორებს და ერთ კლავიშს. მოდიფიკატორები ერთ წამში დაამატეთ; დასადასტურებლად ყველა კლავიში გაუშვით. Escape აუქმებს.", + "ui.shortcut_capture_press": "დააჭირეთ მოდიფიკატორებს და ერთ კლავიშს. Escape აუქმებს.", + "ui.shortcut_capture_release": "დასადასტურებლად ყველა კლავიში გაუშვით. Escape აუქმებს.", + "ui.shortcut_capture_settling": "მალსახმობი დასტურდება… Escape აუქმებს.", + "ui.shortcut_cycles_modes": "ხელსაწყოს მალსახმობზე ხელახლა დაჭერა მის რეჟიმს ცვლის", + "ui.shortcut_cycles_modes_tip": "პირველ წერტილამდე ესკიზის ხელსაწყოს მალსახმობზე ხელახლა დაჭერა მისი შექმნის რეჟიმებს რიგრიგობით გადართავს. გამორთული: ხელსაწყო თავიდან ეშვება.", + "ui.shortcut_multiple_keys": "გამოიყენეთ მოდიფიკატორები და მხოლოდ ერთი სხვა კლავიში. ხელახლა საცდელად დაწკაპეთ მინიჭებაზე.", + "ui.show": "ჩვენება", + "ui.showAll": "ყველაფრის ჩვენება", + "ui.showAllBodies": "ყველა სხეულის ჩვენება", + "ui.showAxes": "ღერძების ჩვენება", + "ui.showDimension": "ზომის ჩვენება", + "ui.showOrigin": "სათავის ჩვენება", + "ui.showPlanes": "სიბრტყეების ჩვენება", + "ui.show_component_history": "მისი ქრონოლოგიის ჩვენება", + "ui.show_constraints": "შეზღუდვები", + "ui.show_construction_geometries": "დამხმარე გეომეტრია", + "ui.show_dimensions": "ზომები", + "ui.show_profile": "პროფილის ჩვენება", + "ui.show_projected_geometries": "პროეცირებული გეომეტრია", + "ui.simple": "მარტივი", + "ui.simulation": "სიმულაცია", + "ui.single": "ერთმაგი", + "ui.sketch": "ესკიზი", + "ui.sketch_dimension": "ესკიზის ზომა", + "ui.sketch_grid": "ესკიზის ბადე", + "ui.sketch_intersect_geometry": "გეომეტრია", + "ui.sketch_intersect_projection_link": "პროეცირების კავშირი", + "ui.sketch_intersect_selection_filter": "მონიშვნის ფილტრი", + "ui.sketch_keys_only": "მოდელის კლავიშები ესკიზებში არ მუშაობს", + "ui.sketch_keys_only_tip": "ესკიზის რედაქტირებისას მუშაობს მხოლოდ ესკიზის კლავიშები და ყველგან მოქმედი კლავიშები; მოდელის კლავიში, მაგალითად E ან F, არაფერს აკეთებს, ასე რომ შემთხვევით დაჭერილი კლავიში მძიმე ესკიზს ვერ დახურავს.", + "ui.sketch_modifiers": "ესკიზის მოდიფიკატორები", + "ui.sketch_project_geometry": "გეომეტრია", + "ui.sketch_report.all_constrained": "ყველაფერი სრულად შეზღუდულია.", + "ui.sketch_report.dof": "თავისუფლების ხარისხები", + "ui.sketch_report.loose": "სრულად შეზღუდული არ არის", + "ui.sketch_report.status": "სტატუსი", + "ui.sketch_report.title": "ესკიზის ანგარიში", + "ui.sketch_scale": "ესკიზის მასშტაბირება", + "ui.sketches": "ესკიზები", + "ui.slice": "დაჭრა", + "ui.slicer": "სლაისერი", + "ui.slicer_delete_tip": "{program}\nსიიდან წასაშლელად დააჭირეთ Delete-ს", + "ui.slicer_lost": "{slicer} გაეშვა, მაგრამ ფაილის გასაგზავნად ვეღარ მოიძებნა. ფაილი შენახულია აქ: {path}; გახსენით იქიდან.", + "ui.slicer_no_file": "{slicer} მზადაა, მაგრამ გასაგზავნი ფაილი არ არის.", + "ui.slicer_no_response": "{slicer}-მა დროულად არ უპასუხა. ფაილი უკვე შენახულია აქ: {path}; სლაისერის გაშვების შემდეგ ხელახლა გაგზავნეთ.", + "ui.slicer_resend_hint": "ხელახლა გაგზავნა ჩაანაცვლებს ფაილს, რომელიც სლაისერშია გახსნილი.", + "ui.slicer_single_instance": "ფაილების გახსნა უკვე გაშვებულ სლაისერში", + "ui.slicer_single_instance_tip": "სლაისერებისთვის, რომლებიც ფაილს უკვე გაშვებულ ფანჯარაში ტვირთავს.", + "ui.slicer_starting": "{slicer} ეშვება…", + "ui.slicer_still_starting": "ჯერ კიდევ ველოდებით {slicer}-ის გაშვებას. სხვა არაფერი გაგზავნილა.", + "ui.slicer_stl_fallback": "3MF-ის ჩაწერა ვერ მოხერხდა, ამიტომ ეს STL-ია.", + "ui.slot": "ღარი", + "ui.smooth": "დაგლუვება", + "ui.smooth_wheel_zoom": "ბორბლით გლუვი მასშტაბირება", + "ui.smooth_wheel_zoom_tip": "გამორთეთ, რომ ბორბლის თითოეული მოძრაობა მყისიერად, გლუვი მილევის გარეშე შესრულდეს", + "ui.snap": "მიბმა", + "ui.spacing": "ბიჯი", + "ui.spacing_2": "ბიჯი 2", + "ui.sphere": "სფერო", + "ui.spline": "სპლაინი", + "ui.split_body": "სხეულის გაყოფა", + "ui.stand_up_tip": "STEP ან IGES ფაილის Z-ზემოთ გახსნის შემდეგ, X-ის გარშემო მეოთხედი ბრუნის შეთავაზება", + "ui.standard": "სტანდარტული", + "ui.start": "დასაწყისი", + "ui.start_over": "თავიდან დაწყება", + "ui.start_page": "საწყისი გვერდი", + "ui.step_values": "მნიშვნელობების ცვლა ისრიანი კლავიშებითა და ბორბლით", + "ui.step_values_tip": "მნიშვნელობის ველში აკრეფისას Up/Down უბრალო რიცხვს 1-ით ცვლის (Shift: 10, Alt: 0.1); იგივეს აკეთებს მაუსის ბორბალი ველზე. გამოსახულებები ისე რჩება, როგორც აკრიფეთ.", + "ui.stitch_tolerance_hint": "მჭიდრო", + "ui.stretch": "გაწელვა", + "ui.supersampling": "სუპერსემპლინგი (SSAA)", + "ui.supersampling_adaptive": "მხოლოდ როცა ხედი უძრავია", + "ui.supersampling_off": "გამორთული (1×)", + "ui.suppress": "ჩახშობა", + "ui.suppress_auto_snap": "ავტომიბმის ჩახშობა ხატვისას / გადათრევისას", + "ui.suppress_auto_snap_note": "ნაგულისხმევი: Ctrl/Cmd ან Alt/Option თითოეული ესკიზის მიბმას ჩაახშობს. შესაზღუდად აირჩიეთ ერთი კლავიში.", + "ui.sweep": "ტრაექტორიით აგება", + "ui.sweep_follow_direction": "მიმართულების მიდევნება", + "ui.sweep_keep_as_drawn": "დახატულის შენარჩუნება", + "ui.sweep_turn_with_path": "ტრაექტორიასთან ერთად შემობრუნება", + "ui.symmetric": "სიმეტრიული", + "ui.symmetry": "სიმეტრია", + "ui.system": "სისტემა", + "ui.tab_assemble": "აწყობა", + "ui.tab_manage": "მართვა", + "ui.tab_sheet_metal": "ფურცლოვანი ლითონი", + "ui.tab_view": "ხედი", + "ui.tab_weldments": "შედუღებული კონსტრუქციები", + "ui.tangent": "მხები", + "ui.taper_angle": "წაწვეტების კუთხე", + "ui.tapped": "კუთხვილიანი", + "ui.text": "ტექსტი", + "ui.theme": "თემა", + "ui.thickness": "სისქე", + "ui.thread": "კუთხვილი", + "ui.tie_ends": "მიბმა", + "ui.tie_ends_tip": "ყველა მიუბმელი ბოლოს შეზღუდვა", + "ui.timeline_bottom": "ქრონოლოგია ქვემოთ", + "ui.timeline_left_note": "ვერტიკალური ქრონოლოგია მოდელის ხის მარცხნივ მდებარეობს. ოპერაციების სახელები ზოლზე ჩართეთ ან გამორთეთ.", + "ui.timeline_left_sidebar": "მარცხენა გვერდითი პანელი", + "ui.tip_angle": "წვერის კუთხე", + "ui.to_object": "ობიექტამდე", + "ui.tool_direction": "ხელსაწყოს მიმართულება", + "ui.toolbar_tabs_hidden": "ხელსაწყოთა ზოლის ყველა ჩანართი დამალულია. ჩანართის საჩვენებლად დაწკაპეთ + ან აქ დაწკაპეთ მარჯვენა ღილაკით.", + "ui.top": "ზედა", + "ui.top_diameter": "ზედა დიამეტრი", + "ui.top_radius": "ზედა რადიუსი", + "ui.torus": "ტორი", + "ui.total_angle": "ჯამური კუთხე", + "ui.trackpad_pan_tip": "ორი თითით გადახვევა ხედს გადაადგილებს; Fusion-ის მსგავსად Shift + ორი თითი ორბიტაზე ატრიალებს. გამორთული: გადახვევა მასშტაბს ცვლის. მაუსის ბორბალი და თითების შეკუმშვა მასშტაბს ცვლის; ცერის ბორბალი გვერდზე გადაადგილებს.", + "ui.trim": "მოკვეთა", + "ui.turn_up_axis": "ზედა ღერძის შემობრუნება", + "ui.twist": "გრეხა", + "ui.two_finger_scroll_pans": "ორი თითით გადახვევა ხედს გადაადგილებს", + "ui.two_sides": "ორი მხარე", + "ui.ui_scale": "ინტერფეისის მასშტაბი", + "ui.undo": "დაბრუნება", + "ui.unground": "ფიქსაციის მოხსნა", + "ui.unisolate": "იზოლირების მოხსნა", + "ui.units": "ერთეულები", + "ui.units_of_new_designs": "ახალი პროექტების ერთეულები", + "ui.unlock": "განბლოკვა", + "ui.unsuppress": "ჩახშობის მოხსნა", + "ui.untied_ends_tip": "ეხება მხოლოდ პოზიციით", + "ui.untitled": "უსათაურო", + "ui.up_axis_note": "რომელი ღერძია მიმართული ზემოთ ხედებში (ღერძული ხედი, საწყისი ხედი, პირისპირ ხედი). პროექტები არ იცვლება.", + "ui.updateToCurrentView": "მიმდინარე ხედით განახლება", + "ui.upload": "ატვირთვა", + "ui.vertical_constraint": "ვერტიკალურობის შეზღუდვა", + "ui.view_angles": "ხედის კუთხეები", + "ui.view_angles_convention": "გრადუსები ზედა ღერძის გარშემო. მობრუნება 0° წინა ხედია, 90° — მარცხენა, −90° — მარჯვენა, 180° — უკანა; ქანობი 90° ზედა ხედია; დადებითი გორება მოდელს საათის ისრის მიმართულებით აბრუნებს.", + "ui.view_angles_help": "ორიენტაციის ინდიკატორის ქვეშ აჩვენებს ხედის ქანობს, მობრუნებას და გორებას გრადუსებში და მის პროექციას. ზუსტი კუთხეების ასაკრეფად დაწკაპეთ მაჩვენებელზე.", + "ui.view_angles_lock": "{axis}-ის ჩაკეტვა", + "ui.view_angles_ortho": "ორთო", + "ui.view_angles_persp": "პერსპ.", + "ui.view_angles_pitch": "ქანობი", + "ui.view_angles_readout": "ქანობი {pitch} · მობრუნება {yaw} · გორება {roll}", + "ui.view_angles_roll": "გორება", + "ui.view_angles_unlock": "{axis}-ის განბლოკვა", + "ui.view_angles_yaw": "მობრუნება", + "ui.view_angles_zero": "{axis}-ის 0°-ზე დაყენება", + "ui.view_centre": "ხედის ცენტრი", + "ui.viewport_status_clear": "{name}: გამორთვა", + "ui.viewport_status_clear_hint": "{name}: გამორთვა · Esc", + "ui.viewport_status_edges": "წიბო: {count}", + "ui.viewport_status_from": "მიმართულება: {direction}", + "ui.viewport_status_key": "{name}: ლეგენდის ჩვენება", + "ui.viewport_status_minimum_radius": "მინიმალური რადიუსი", + "ui.viewport_status_pairs": "წყვილი: {count}", + "ui.viewport_status_section_hatch": "{setting} · დაშტრიხვა", + "ui.viewport_status_section_plane": "მიმდინარე სიბრტყე", + "ui.viewport_status_section_tilted": "დახრილი · {offset}", + "ui.viewport_status_stripes": "ზოლი: {count}", + "ui.viewport_status_summary_clear": "ყველაფრის გამორთვა", + "ui.viewport_status_summary_heading": "ამ ხედში", + "ui.viewport_status_summary_label": "{name} და კიდევ {count}", + "ui.viewport_status_summary_more": "+{count}", + "ui.viewport_theme_follow": "თემის მიხედვით", + "ui.visual_shaded_hidden_edges": "დაჩრდილული, დამალული წიბოებით", + "ui.visual_shaded_with_edges": "დაჩრდილული, წიბოებით", + "ui.visual_style": "ვიზუალური სტილი", + "ui.visual_wireframe": "კარკასი", + "ui.wheel_zoom_speed": "მაუსის ბორბლით მასშტაბირების სიჩქარე", + "ui.width": "სიგანე", + "ui.window_system": "ფანჯრების სისტემა", + "ui.window_system_auto": "ავტომატური", + "ui.window_system_wayland": "Wayland", + "ui.window_system_x11": "X11", + "ui.workspace": "სამუშაო სივრცე", + "ui.workspace_animation_description": "დაშლილი ხედები, მოძრაობის კვლევები და სცენარის დაფები", + "ui.workspace_available": "ხელმისაწვდომი", + "ui.workspace_current": "მიმდინარე", + "ui.workspace_design_description": "ესკიზი, მოდელირება, აწყობა და შემოწმება", + "ui.workspace_design_tabs": "მოდელი · ზედაპირი · აწყობა · ჩასმა · შემოწმება · მართვა · ხედი", + "ui.workspace_drawing_description": "2D ნახაზები ხედებით, ზომებითა და ძირითადი წარწერებით", + "ui.workspace_footer": "ყველა სამუშაო სივრცე ერთსა და იმავე პროექტზე, ქრონოლოგიასა და მონიშვნაზე მუშაობს; იცვლება მხოლოდ ლენტის ჩანართები. სანამ ესკიზი ან ოპერაცია რედაქტირდება, გადამრთველი ჩაკეტილია.", + "ui.workspace_layout": "სამუშაო სივრცის განლაგება", + "ui.workspace_manufacture_description": "სლაისინგი, ხელსაწყოს ტრაექტორიები და მომართვა", + "ui.workspace_planned": "დაგეგმილი", + "ui.workspace_render_description": "ნაწარმის გადახედვა, სცენის პარამეტრები და რენდერირებული გამოსახულებები", + "ui.workspace_render_tabs": "სცენა · გამოსახულება", + "ui.workspace_simulation_description": "დატვირთვები, შეზღუდვები და შედეგები", + "ui.x_distance": "მანძილი X-ით", + "ui.y_distance": "მანძილი Y-ით", + "ui.y_up": "Y ზემოთ", + "ui.z_up": "Z ზემოთ", + "ui.zoom": "მასშტაბი", + "ui.zoom_to_cursor_tip": "ბორბალი მასშტაბს კურსორის ქვეშ მყოფი წერტილისკენ ცვლის (გამორთული: ხედის ცენტრისკენ)", + "ui.zoom_to_the_cursor": "მასშტაბირება კურსორისკენ", + "update.available": "ხელმისაწვდომია SolidCraft {version}", + "update.button": "განახლება", + "update.button_version": "განახლება {version}-მდე", + "update.check_automatically": "შემოწმება გაშვებისას და დღეში ერთხელ", + "update.check_for_updates": "განახლებების შემოწმება", + "update.check_now": "ახლავე შემოწმება", + "update.check_unavailable": "ამ ინსტალაციისთვის განახლებების შემოწმება მიუწვდომელია.", + "update.checking": "მოწმდება…", + "update.copy": "კოპირება", + "update.dmg_opened": "დისკის ასლი გახსნილი და შემოწმებულია: დახურეთ SolidCraft, გადაათრიეთ ახალი SolidCraft Applications-ში ძველი ასლის ჩანაცვლებით, შემდეგ SolidCraft ხელახლა გახსენით.", + "update.download": "ჩამოტვირთვა", + "update.download_open": "ჩამოტვირთვა და გახსნა", + "update.downloading": "ჩამოტვირთვა და შემოწმება… {done} / {total} MB", + "update.failed": "შემოწმება ვერ მოხერხდა: {error}", + "update.file": "ჩამოტვირთვით მიიღებთ: {file}.", + "update.install_failed": "განახლება ვერ დაინსტალირდა: {error}. არაფერი შეცვლილა; ჩამოტვირთვით ამის ნაცვლად პაკეტს მიიღებთ.", + "update.install_msi": "ინსტალაცია (SolidCraft დაიხურება)", + "update.installed": "SolidCraft {version} დაინსტალირებულია. გამოსაყენებლად გადატვირთეთ.", + "update.installer_started": "ინსტალერი გაეშვება, როცა SolidCraft დაიხურება.", + "update.later": "მოგვიანებით შემახსენე", + "update.managed": "ხელმისაწვდომია განახლება: განაახლეთ SolidCraft {manager}-ში", + "update.no_notes": "ამ გამოშვებას შენიშვნები არ აქვს.", + "update.package_hint": "ეს ასლი მიღებულია {kind}-დან. ჩამოტვირთეთ ახალი პაკეტი, შემდეგ დააინსტალირეთ ბრძანებით:", + "update.prefs_dev": "ეს დეველოპერული ბილდია ({version}): ის განახლებებს არ ამოწმებს.", + "update.prefs_flatpak": "ამ ასლს ({version}) Flatpak აახლებს: გაუშვით {command} ან გამოიყენეთ პროგრამების ცენტრი. SolidCraft არ ამოწმებს.", + "update.prefs_label": "განახლებები", + "update.prefs_managed": "ეს არის SolidCraft {version}, რომელსაც {manager} მართავს. შემოწმება GitHub-ს უახლეს გამოშვებას ეკითხება და სხვას არაფერს აგზავნის; განაახლეთ SolidCraft {manager}-ში.", + "update.prefs_note": "ეს არის SolidCraft {version} ({kind}). შემოწმება GitHub-ს უახლეს გამოშვებას ეკითხება და სხვას არაფერს აგზავნის.", + "update.prefs_web": "ვებაპის უახლესი ვერსიის მისაღებად გადატვირთეთ გვერდი. თუ ქსელი მიუწვდომელია ან განახლება დროულად ვერ ჩამოიტვირთება, გაიხსნება შენახული ვერსია; მიმდინარე ჩამოტვირთვა შემდეგი გადატვირთვისთვის გაგრძელდება.", + "update.refresh_checking": "უახლესი გამოშვების შემოწმება…", + "update.refresh_fallback": "უფრო ახალი გამოშვების შემოწმება ვერ მოხერხდა; ახლდება ადრე ნაპოვნ {version}-მდე.", + "update.refresh_selected": "ახლდება {version}-მდე.", + "update.release_page": "გამოშვების გვერდის გახსნა", + "update.restart": "ახლავე გადატვირთვა", + "update.restart_later": "მოგვიანებით", + "update.show": "{version}-მდე განახლების ჩვენება", + "update.skip": "ამ ვერსიის გამოტოვება", + "update.system_hint": "ეს ასლი არის {kind}. განაახლეთ ბრძანებით:", + "update.title": "ხელმისაწვდომია განახლება", + "update.up_to_date": "SolidCraft განახლებულია.", + "update.update_now": "ახლავე განახლება", + "update.you_have": "თქვენ გაქვთ {version}.", + "use a positive nominal diameter and a pitch smaller than it": "მიუთითეთ დადებითი ნომინალური დიამეტრი და მასზე ნაკლები ბიჯი", + "values must be finite numbers": "მნიშვნელობები სასრული რიცხვები უნდა იყოს", + "values must be numbers or expressions": "მნიშვნელობები რიცხვები ან გამოსახულებები უნდა იყოს", + "view.auto_ortho_faces": "ორბიტისას პერსპექტივა, წახნაგებზე ორთო", + "view.render_inspector": "რენდერის ინსპექტორი", + "web.files.insert_drawings_hint": "CAD ფაილები, პოლიგონური ბადეები, DXF ან SVG გახსნილ პროექტში", + "web.files.insert_stored_drawings_hint": "გახსნილ პროექტში (CAD ფაილები, პოლიგონური ბადეები, DXF, SVG)", + "web.open_full": "გახსნა SolidCraft-ში", + "web.open_link": "გავხსნათ მიბმული პროექტი?", + "web.open_link_confirm": "არის შეუნახავი ცვლილებები. გავხსნათ მიბმული პროექტი ახალ ჩანართში?", + "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ არჩევა · Enter / Tab დასრულება · Esc დახურვა", + "↑ ↓ choose · Enter applies this value": "↑ ↓ არჩევა · Enter ამ მნიშვნელობას იყენებს", + "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ არჩევა · Enter აკრეფილს იყენებს · Esc დახურვა", + "⌘Enter continues on GitHub.": "⌘Enter GitHub-ზე აგრძელებს." +} diff --git a/assets/locales/ko.json b/assets/locales/ko.json index c05cef543..4f8928bfe 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -325,6 +325,7 @@ "Move Type": "이동 유형", "Move down": "아래로 이동", "Move earlier": "앞으로 이동", + "Move holes by clicking or dragging": "클릭 또는 드래그로 이동", "Move later": "뒤로 이동", "Move up": "위로 이동", "Name": "Name", @@ -407,6 +408,7 @@ "Recover unsaved design?": "저장되지 않은 디자인을 복구할까요?", "Rectangular": "직사각형", "Reference face": "참조 면", + "Reference plane": "참조 평면", "Relief Depth": "릴리프 깊이", "Relief Width": "릴리프 너비", "Remove Tools": "공구 제거", @@ -422,6 +424,8 @@ "Rename Feature": "피처 이름 바꾸기", "Rename Folder": "폴더 이름 바꾸기", "Render Stage": "렌더링 단계", + "Reopen the designs that were open when SolidCraft was last closed": "지난번에 열려 있던 디자인 다시 열기", + "Repair Part": "부품 복구", "Replace existing library file": "기존 라이브러리 파일 바꾸기", "Report a bug — review a screenshot and open a GitHub draft": "버그 신고 — 스크린샷을 검토하고 GitHub 초안 열기", "Report text copied. Paste it into GitHub and submit your report there.": "보고서 텍스트를 복사했습니다. GitHub에 붙여넣고 그곳에서 보고서를 제출하세요.", @@ -476,6 +480,7 @@ "Second point": "두 번째 점", "Section": "단면", "Section position": "단면 위치", + "Sections": "단면", "Sections (one sketch each)": "단면 (각각 스케치 하나)", "Select Other": "다른 항목 선택", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "다른 항목 선택: 모델 위에서 왼쪽 버튼을 가만히 누르고 있거나(또는 오른쪽 클릭 › 다른 항목 선택…) 커서 아래의 모든 항목을 나열합니다. 같은 위치를 다시 클릭하면 다음 항목이 선택됩니다. 가운데 버튼을 더블 클릭하면 홈으로 이동합니다(환경설정 › 탐색).", @@ -501,7 +506,7 @@ "Show Agent Cursor": "에이전트 커서 표시", "Show in folder": "폴더에서 보기", "Show the pointer an AI agent moves (#35)": "AI 에이전트가 움직이는 포인터 표시 (#35)", - "Show tool at cursor": "커서 옆에 도구 표시", + "Show tool at cursor": "커서에 도구 표시", "Signed axes": "부호 있는 축", "Size": "크기", "Sketch constraints": "스케치 구속 조건", @@ -512,6 +517,7 @@ "Sketch points": "스케치 점", "Slider": "슬라이더", "Slot width": "슬롯 폭", + "Snap to face and edge centres": "중심에 스냅", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "이 디자인들이 저장되기 전에 SolidCraft가 종료되었습니다. 마지막 자동 저장본을 열 수 있습니다.", "Spacing 2 must be a non-zero number": "간격 2는 0이 아닌 숫자여야 합니다", "Spacing must be a non-zero number": "간격은 0이 아닌 숫자여야 합니다", @@ -637,26 +643,32 @@ "a picked edge is gone": "선택한 모서리가 더 이상 없습니다", "a picked edge's body is gone": "선택한 모서리의 바디가 더 이상 없습니다", "add a key for a joint first": "먼저 관절의 키를 추가하세요", - "ai.prefs.availability": "어시스턴트 제어", - "ai.prefs.background_commands": "에이전트 명령을 백그라운드에서 실행", - "ai.prefs.follow_camera": "카메라를 스케치로 돌리기", + "ai.prefs.allow_control": "AI 에이전트 연결 허용", + "ai.prefs.allow_control_note": "로컬 채널(MCP)입니다. 이 컴퓨터 밖으로 아무것도 나가지 않습니다.\n\n이 컴퓨터에서만 제어 채널을 엽니다(127.0.0.1, 포트 27878 또는 다음 빈 포트). 연결하는 프로그램은 시작할 때마다 새로 생성되며 현재 사용자 계정만 읽을 수 있는 비밀 토큰을 제시해야 합니다. SolidCraft를 다음에 시작할 때 적용됩니다. 끄면 --control로 실행하지 않는 한 아무것도 수신하지 않습니다.", + "ai.prefs.availability": "사용 설정", + "ai.prefs.background_commands": "느린 명령을 백그라운드에서 실행", + "ai.prefs.connect_apps": "AI 앱에 SolidCraft 추가", + "ai.prefs.connect_apps_note": "끄면 추가한 항목이 다시 제거됩니다.\n\nSolidCraft 시작 시 이 컴퓨터에서 찾은 AI 앱(OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code)에 MCP 서버로 추가합니다. solidcraft 항목만 추가하거나 경로를 갱신하며, 사용자가 변경한 항목은 그대로 두고 파일을 먼저 백업합니다. 끄면 추가했던 항목을 제거합니다. 도움말 > AI 어시스턴트 연결…에서 수동으로 실행할 수도 있습니다.", + "ai.prefs.connect_at_start": "시작할 때 마지막 에이전트 연결", + "ai.prefs.follow_camera": "카메라 따라가기", "ai.prefs.follow_camera_off": "카메라 자동 따라가기가 꺼져 있습니다.", "ai.prefs.follow_camera_on": "에이전트가 만드는 스케치를 향해 카메라가 회전합니다.", - "ai.prefs.intro": "에이전트, 권한, 그리고 작업이 표시되는 방식.", - "ai.prefs.make_default": "기본값으로 사용", + "ai.prefs.intro": "SolidCraft의 AI 에이전트.", + "ai.prefs.make_default": "기본값으로 설정", "ai.prefs.no_agents": "아직 에이전트가 없습니다. 에이전트를 추가하거나 새로 고쳐서 설치된 에이전트를 찾으세요.", "ai.prefs.no_saved_approvals": "저장된 승인이 없습니다.", + "ai.prefs.open_at_start": "시작할 때 채팅 열기", "ai.prefs.override_all_warning": "이 에이전트는 묻지 않고 설계를 저장, 덮어쓰기, 내보내기 또는 교체할 수 있습니다.", - "ai.prefs.permission_all": "모두 허용", - "ai.prefs.permission_all_summary": "사용 가능한 SolidCraft 도구가 묻지 않고 실행됩니다.", - "ai.prefs.permission_ask": "변경 전에 묻기", - "ai.prefs.permission_ask_summary": "모든 설계 변경과 파일 작업을 승인합니다.", - "ai.prefs.permission_edits": "모델 편집 허용", - "ai.prefs.permission_edits_summary": "모델 편집은 실행되고, 파일 및 파괴적인 작업은 계속 묻습니다.", + "ai.prefs.permission_all": "모두 실행", + "ai.prefs.permission_all_summary": "묻지 않음", + "ai.prefs.permission_ask": "먼저 묻기", + "ai.prefs.permission_ask_summary": "모든 변경 전에 확인", + "ai.prefs.permission_edits": "편집 허용", + "ai.prefs.permission_edits_summary": "자유롭게 편집하고 나머지는 확인", "ai.prefs.permission_scope": "SolidCraft 도구에만 적용됩니다. 에이전트의 셸과 파일 편집은 자체 권한을 사용합니다.", "ai.prefs.pointer_preview_hidden": "포인터 숨김", "ai.prefs.pointer_preview_speed": "에이전트 포인터 · {speed}", - "ai.prefs.pointer_speed": "동작 속도", + "ai.prefs.pointer_speed": "속도", "ai.prefs.privacy_note": "선택한 에이전트 또는 엔드포인트만 대화를 받습니다. 엔드포인트 키는 시스템 키체인에 저장됩니다.", "ai.prefs.show_pointer": "에이전트 포인터 표시", "ai.prefs.turn_limit_hint": "메시지 하나에 어시스턴트가 수행할 수 있는 설계 변경 도구 호출의 최대 횟수입니다.", @@ -679,6 +691,7 @@ "browser.edit_canvas_title": "캔버스 편집: {name}", "browser.edit_point_cloud_title": "포인트 클라우드 편집: {name}", "browser.move_title": "이동: {name}", + "browser.needs_repair": "{name}: 복구 필요", "browser.parameters": "매개변수 ({count})", "browser.precision": "정밀도: {precision}", "browser.sketch_attachment_lost": "{name} (부착 해제됨)", @@ -713,7 +726,10 @@ "cmd.assembly_bom": "자재 명세서", "cmd.assembly_bom_item_set": "항목 번호 변경", "cmd.assembly_bom_renumber": "항목 번호 다시 매기기", + "cmd.assembly_mass_properties": "질량 특성", + "cmd.body.print_face": "출력 바닥면", "cmd.body_rename": "바디 이름 변경", + "cmd.body_repair": "부품 복구", "cmd.browser_group": "새 그룹", "cmd.browser_move": "브라우저 항목 이동", "cmd.browser_order": "브라우저 항목 정렬", @@ -758,6 +774,7 @@ "cmd.config_rule": "구성 규칙", "cmd.config_rules": "구성 규칙", "cmd.config_table": "구성 표시", + "cmd.construct.plane.axis_point": "축과 점을 지나는 평면", "cmd.construct_axis_edge": "모서리를 통과하는 축", "cmd.construct_axis_normal_to_face": "면에 수직인 축", "cmd.construct_axis_through_cylinder": "원기둥/원뿔/토러스를 통과하는 축", @@ -786,6 +803,8 @@ "cmd.diagnostics_crash_reports": "충돌 보고서", "cmd.diagnostics_crash_reports_clear": "충돌 보고서 삭제", "cmd.diagnostics_crash_test": "충돌 테스트", + "cmd.diagnostics_profile": "프로파일", + "cmd.diagnostics_validation": "검증", "cmd.doc_recover": "설계 복구", "cmd.doc_recovery_discard": "복구된 설계 폐기", "cmd.doc_recovery_list": "복구 가능한 설계", @@ -847,6 +866,11 @@ "cmd.joint_screw": "나사", "cmd.joint_solve": "관절 해석", "cmd.joint_sweep": "관절 스윕", + "cmd.layout.apply": "레이아웃 적용", + "cmd.layout.get": "레이아웃 확인", + "cmd.layout.reset": "레이아웃 초기화", + "cmd.layout.save": "레이아웃 저장", + "cmd.layout.workspace.select": "레이아웃 작업 공간 선택", "cmd.library_apply": "로컬 라이브러리 항목 적용", "cmd.library_export": "설계 라이브러리 내보내기", "cmd.library_inspect": "로컬 라이브러리 확인", @@ -877,6 +901,21 @@ "cmd.occurrence_ground": "고정", "cmd.occurrence_move": "인스턴스 이동", "cmd.occurrence_properties": "인스턴스 물리 속성", + "cmd.panel.activate": "패널 탭 활성화", + "cmd.panel.close": "패널 닫기", + "cmd.panel.collapse": "패널 구역 접기", + "cmd.panel.dismiss": "패널 임시 보기 닫기", + "cmd.panel.float": "패널 띄우기", + "cmd.panel.focus": "패널에 초점 맞추기", + "cmd.panel.list": "패널 목록", + "cmd.panel.move": "패널 이동", + "cmd.panel.native_close": "별도 창의 패널 구역 다시 도킹", + "cmd.panel.open": "패널 열기", + "cmd.panel.peek": "접힌 패널 임시 보기", + "cmd.panel.popout": "패널을 별도 창으로 이동", + "cmd.panel.reset_pair": "패널 구분선 초기화", + "cmd.panel.resize": "패널 구역 크기 조정", + "cmd.panel.resize_pair": "패널 구분선 이동", "cmd.parameters_add": "사용자 매개 변수 추가", "cmd.parameters_change": "매개 변수 변경", "cmd.parameters_comment": "매개 변수에 설명 추가", @@ -905,6 +944,9 @@ "cmd.pointcloud_edit": "포인트 클라우드 편집", "cmd.pointcloud_insert": "포인트 클라우드 삽입", "cmd.pointcloud_list": "포인트 클라우드", + "cmd.render.compare.divider": "렌더 비교 구분선 이동", + "cmd.render.result.discard": "렌더 결과 버리기", + "cmd.render.result.select": "렌더 결과 선택", "cmd.render_backends": "렌더링 백엔드", "cmd.render_batch": "모든 샷 렌더링", "cmd.render_camera_fit": "렌더 대상 화면 맞춤", @@ -1093,9 +1135,11 @@ "cmd.timeline_rollback": "타임라인 마커 이동", "cmd.timeline_stop": "기록 재생 중지", "cmd.timeline_suppress": "특성 비활성화", + "cmd.ui.assistant": "도우미 표시 전환", "cmd.view.render_browser": "렌더 브라우저", "cmd.view.render_dock": "렌더 도크 이동", "cmd.view.render_focus": "렌더 집중 보기", + "cmd.view.status_details": "뷰포트 상태 상세 정보", "cmd.view.status_items": "뷰포트 상태 항목", "cmd.view_ambient_occlusion": "앰비언트 오클루전", "cmd.view_angle_readout": "뷰 각도", @@ -1109,14 +1153,17 @@ "cmd.view_render_frame": "렌더 프레임 가이드", "cmd.view_save": "새 이름 있는 보기", "cmd.view_shots_strip": "샷 스트립", + "color.blue": "파랑", "color.copy": "클릭하여 색상 값 복사", "color.edit": "클릭하여 색상 편집", "color.gamma": "색상 값을 0-255 감마 공간으로 표시 중", + "color.green": "초록", "color.hex": "Hex", "color.hex_help": "#rrggbb 또는 #rrggbbaa 입력. 6자리 값은 불투명도 유지", "color.hex_hint": "#rrggbb", "color.hue": "색조", "color.linear": "색상 값을 0-1 선형 공간으로 표시 중", + "color.red": "빨강", "color.saturation_value": "채도 및 명도", "color.selected": "선택한 색상", "config.column_filter_empty": "일치하는 열이 없습니다", @@ -1153,6 +1200,7 @@ "crash.report": "보고…", "crash.unclean_explanation": "이후 실행 시 감지되었으며 정확한 종료 시각은 기록되지 않았습니다. 시스템 종료나 강제 중지로도 비정상 종료가 발생할 수 있습니다.", "delete.and_more": "… 외 {count}개", + "diagnostic.reselect_reference": "{feature}: 참조 `{reference}`이(가) 선택했을 때의 모습으로 더 이상 존재하지 않습니다. 다시 선택하세요", "dialog.bodies_count": "바디 {count}개", "dialog.clearance_invalid": "간격은 0 이상의 길이여야 합니다", "dialog.compute": "계산", @@ -1162,10 +1210,18 @@ "dialog.custom_axis": "↖ 사용자 정의 축", "dialog.dimension_insert_hint": "다른 구동 치수를 두 번 클릭하여 이름 삽입", "dialog.dimension_name": "치수: {name}", + "dialog.dimension_step_down": "{step} 줄이기", + "dialog.dimension_step_expression": "숫자만 증감할 수 있으며 수식은 입력한 그대로 유지됩니다", + "dialog.dimension_step_up": "{step} 늘리기", "dialog.edit_title": "{title} 편집", + "dialog.pattern_sketch_not_object": "바디나 피처를 선택하세요. 스케치는 둘 다 아닙니다. 곡선은 스케치 안의 패턴이나 대칭 복사로 반복하거나, 먼저 돌출하세요.", "dialog.select": "↖ 선택", "dialog.selected_count": "↖ {count}개 선택됨", + "dialog.selection_constraint": "구속 조건 {id}", + "dialog.selection_external_curve": "{sketch} · 곡선 {id}", "dialog.selection_guidance": "변경할 입력을 선택하세요. 선택한 객체를 클릭하면 선택이 해제되며, Ctrl/Cmd를 누른 채 클릭해도 전환됩니다. 미리 보기를 확인한 다음 확인을 누르세요.", + "dialog.selection_midpoint": "중점 · {id}", + "dialog.selection_profile": "{sketch} · 프로파일 {number}", "dialog.selection_step": "{step}/{total} 단계: {input} 선택", "dialog.step": "단계", "document.save_changes": "{name}의 변경 사항을 저장하시겠습니까?", @@ -1198,6 +1254,14 @@ "file_load.reading_percent": "파일 읽는 중... {percent}%", "file_load.rebuilding": "피처 다시 빌드 중 {done}/{total}", "file_load.recovering": "디자인 복구 중", + "file_load.step_build": "모델 만드는 중", + "file_load.step_feature": "피처 {done}/{total}", + "file_load.step_part": "부품 {done}/{total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "파일 읽는 중", + "file_load.step_rebuild": "피처 다시 빌드 중", + "file_load.step_repair": "부품 확인 및 복구 중", + "file_load.step_show": "뷰 준비 중", "file_load.stopping": "이전 작업이 중지되기를 기다리는 중...", "file_load.waiting": "파일 작업 대기 중", "fits the face, e.g. M8": "면에 맞음, 예: M8", @@ -1206,11 +1270,32 @@ "help.attributions": "저작자 표시 (ATTRIBUTION.md)", "help.build": "버전 {version} · 커밋 {commit} · 빌드 날짜 {date}", "help.component.finish_edit": "제자리에서 편집 중인 부품을 저장하고 어셈블리로 돌아가 그 부품으로 어셈블리를 업데이트합니다. 연결된 부품의 변경을 마쳤을 때 사용하세요.", + "help.construct.plane.axis_point": "축과 축 위에 있지 않은 점을 포함하는 구성 평면을 만듭니다. 원점 축, 구성 축, 직선 모서리 또는 스케치 직선을 선택한 다음 꼭짓점, 스케치 점 또는 구성점을 선택합니다. 축 위의 점으로는 평면을 하나로 결정할 수 없습니다.", "help.font_details": "인터페이스는 egui의 내장 글꼴을 사용합니다(Ubuntu Font Licence 및 MIT/Bitstream Vera 라이선스의 Ubuntu Light와 Hack, OFL 및 MIT의 Noto Emoji와 이모지 아이콘 글꼴). 스케치 텍스트는 Liberation Sans(SIL OFL 1.1)를 사용합니다. The Crafting Apps의 선택적 글꼴 팩 craft-fonts(BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1)는 SolidCraft 빌드에 포함되지 않습니다.", "help.fonts": "글꼴", + "help.layout.apply": "저장된 레이아웃을 현재 작업 공간에 적용합니다. 유지 중인 편집기의 초안은 보존됩니다.", + "help.layout.get": "확정된 레이아웃과 등록된 작업 공간을 확인합니다.", + "help.layout.reset": "현재 작업 공간에 등록된 기본 레이아웃을 복원합니다. 사용자 사전 설정은 유지됩니다.", + "help.layout.save": "전체 레이아웃에 이름을 지정해 저장합니다. 사용자 사전 설정을 바꾸려면 명시적인 덮어쓰기 허용이 필요합니다.", + "help.layout.workspace.select": "등록된 레이아웃 작업 공간을 선택하고 이전 레이아웃을 기억합니다.", "help.licences": "라이선스", "help.mit": "MIT 라이선스", "help.notice": "NOTICE", + "help.panel.activate": "키보드 초점을 요청하지 않고 열린 패널 탭을 선택합니다.", + "help.panel.close": "콘텐츠 수명 주기 검사를 거쳐 패널을 닫습니다. 배치는 기억됩니다.", + "help.panel.collapse": "요청한 치수를 유지하면서 패널 구역을 접거나 펼칩니다.", + "help.panel.dismiss": "접힌 패널의 임시 보기를 닫습니다.", + "help.panel.float": "패널을 위치가 명시된 부동 구역으로 이동합니다.", + "help.panel.focus": "패널에 초점을 맞춥니다. 필요하면 유지된 상태를 다시 열고 구역을 펼칩니다.", + "help.panel.list": "등록된 패널 종류, 확정된 인스턴스, 활성 탭, 사용 가능 여부와 호스트 기능을 확인합니다.", + "help.panel.move": "패널을 새 구역으로 이동하거나 기존 탭 그룹에 추가합니다.", + "help.panel.native_close": "콘텐츠를 취소하지 않고 별도 창의 패널 구역을 기억된 도킹 위치로 되돌립니다.", + "help.panel.open": "패널 종류와 명시적인 인스턴스 식별자로 패널을 엽니다. 새 인스턴스에는 배치가 필요합니다.", + "help.panel.peek": "저장된 크기나 접힘 상태를 바꾸지 않고 접힌 패널을 임시로 표시합니다.", + "help.panel.popout": "지원되는 경우 패널을 별도 창으로 이동합니다. 브라우저에서는 부동 구역을 사용합니다.", + "help.panel.reset_pair": "인접한 도킹 구역 쌍을 공통 제약 안에서 기본 크기 비율로 복원합니다.", + "help.panel.resize": "모든 탭의 제약 안에서 패널 구역의 바깥 너비와 높이를 설정합니다.", + "help.panel.resize_pair": "공유하는 전체 길이를 유지하면서 인접한 도킹 구역의 크기를 함께 조정합니다.", "help.pointcloud.insert": "PLY, XYZ 또는 PTS 스캔을 모델 옆에 포인트 클라우드로 삽입합니다. 측정 데이터를 참고하여 모델링할 때 사용합니다.", "help.sketch.construction_line": "두 점을 지나는 무한 보조 직선을 만듭니다. 스케치 프로파일을 나누지 않고 작도할 수 있습니다.", "help.sketch.construction_line.angle": "스케치 X축을 기준으로 지정한 각도의 무한 보조 직선을 만듭니다. 점을 선택한 뒤 각도를 입력하거나 방향을 선택합니다.", @@ -1284,6 +1369,27 @@ "home.start_hint": "설계를 만들거나, 최근 파일을 열거나, 예제를 살펴보세요.", "home.whats_new": "새로운 기능", "home.yesterday": "어제", + "import_report.details": "세부 정보:", + "import_report.file_one": "파일에 다른 문제가 1개 있었습니다.", + "import_report.file_other": "파일에 다른 문제가 {count}개 있었습니다.", + "import_report.hint": "이 부품을 만든 프로그램에서 다시 내보내면 해결될 수 있습니다. 세부 정보는 경고 메시지 복사에 있습니다.", + "import_report.left_out_one": "면 1개를 복구하지 못해 빠져 있습니다.", + "import_report.left_out_other": "면 {count}개를 복구하지 못해 빠져 있습니다.", + "import_report.needs_repair_one": "부품 1개는 모델링하기 전에 복구해야 합니다.", + "import_report.needs_repair_other": "부품 {count}개는 모델링하기 전에 복구해야 합니다.", + "import_report.not_imported_one": "부품 1개를 가져오지 못했습니다.", + "import_report.not_imported_other": "부품 {count}개를 가져오지 못했습니다.", + "import_report.not_shown_one": "면 1개를 그리지 못해 숨겨져 있습니다.", + "import_report.not_shown_other": "면 {count}개를 그리지 못해 숨겨져 있습니다.", + "import_report.open_one": "부품 1개는 면 사이에 틈이 있어 열린 바디로 들어왔습니다.", + "import_report.open_other": "부품 {count}개는 면 사이에 틈이 있어 열린 바디로 들어왔습니다.", + "import_report.refused_one": "부품 1개를 솔리드로 만들지 못해 가져오지 않았습니다.", + "import_report.refused_other": "부품 {count}개를 솔리드로 만들지 못해 가져오지 않았습니다.", + "import_report.repaired_one": "부품 1개의 작은 결함을 복구했습니다.", + "import_report.repaired_other": "부품 {count}개의 작은 결함을 복구했습니다.", + "import_report.solids": "부품 {parts}개 중 {solids}개를 솔리드로 가져왔습니다.", + "import_report.surfaces_one": "부품 1개를 솔리드로 만들지 못해 서피스로 들어왔습니다.", + "import_report.surfaces_other": "부품 {count}개를 솔리드로 만들지 못해 서피스로 들어왔습니다.", "install.button_tip": "SolidCraft를 앱으로 설치합니다. 별도 창에서 열리며 오프라인에서도 작동합니다", "install.dock_1": "파일 › Dock에 추가를 선택합니다.", "install.dock_2": "추가를 클릭합니다.", @@ -1308,6 +1414,13 @@ "joint.from_bodies_hint": "선택한 각 바디가 제자리에 그대로 있으면서 자체의 새 구성 요소로 옮겨집니다.", "joint.one_body": "두 선택이 모두 {body}에 있습니다. 두 번째는 다른 부품에서 선택하세요.", "joint.one_component": "이 부품들은 한 구성 요소의 바디입니다: {bodies}. 관절은 한 구성 요소를 다른 구성 요소에 대해 움직이므로 부품마다 자체 구성 요소가 필요합니다.", + "joint_move.coarse": "축 근처 단계", + "joint_move.conflict": "이 부품의 조인트가 다른 조인트와 충돌합니다: {joint}.", + "joint_move.conflict_hint": "충돌하는 조인트를 편집, 비활성화 또는 삭제하여 다른 조인트가 부품을 배치할 수 있게 하세요.", + "joint_move.fine": "축에서 먼 단계", + "joint_move.legacy_hint": "끄면 이전 이동 패널을 사용합니다.", + "joint_move.precision": "미세 단계를 사용하려면 점선 가이드 바깥으로 당기세요.", + "joint_move.use_handles": "이동에 조인트 모션 핸들 사용", "keymap.command_id": "명령 ID", "keymap.empty": "일치하는 명령이 없습니다", "keymap.use_anyway": "그래도 여기서 {key} 사용", @@ -1324,6 +1437,7 @@ "material.selection.mixed": "서로 다른 재질", "measure.at": "위치", "measure.item": "항목 {number}", + "measure.line_to_centre": "선에서 중심까지", "messages.ago_h": "{n}시간 전", "messages.ago_min": "{n}분 전", "messages.ago_s": "{n}초 전", @@ -1348,6 +1462,8 @@ "motion.track_name": "트랙 {number}", "nav.alias.help": "Shift+Alt+왼쪽 드래그는 회전, Shift+Alt+가운데 드래그는 이동, Shift+Alt+오른쪽 드래그는 확대/축소입니다. 가운데 드래그로도 이동하고 오른쪽 드래그로도 회전합니다", "nav.blender.help": "가운데 드래그는 회전, Shift+가운데 드래그는 이동, Ctrl+가운데 드래그는 확대/축소입니다. 오른쪽 드래그는 카메라에 영향을 주지 않습니다", + "nav.creo.help": "가운데 버튼을 끌면 회전, Shift+가운데 버튼은 이동, Ctrl+가운데 버튼을 위아래로 끌면 확대/축소합니다(아래로 끌면 확대). 휠을 굴려도 확대/축소합니다", + "nav.creo.label": "Creo", "nav.free_orbit.help": "마우스와 3D 마우스로 롤을 유지하며 양 극점을 넘어 회전합니다. Shift 축 스냅은 비활성화됩니다.", "nav.free_orbit.label": "자유 회전", "nav.free_orbit.snap_help": "마우스와 3D 마우스로 양쪽 극점을 지나 회전할 수 있으며 롤 각도가 유지됩니다. 궤도 회전 드래그 중 Shift를 누르면 보기 방향과 롤 각도가 스냅됩니다.", @@ -1375,6 +1491,12 @@ "navbar.assistant": "어시스턴트", "navbar.custom.add_slot": "{slot} 추가", "navbar.custom.always": "항상 표시", + "navbar.custom.anchor.bottom_centre": "하단 가운데", + "navbar.custom.anchor.bottom_left": "왼쪽 아래", + "navbar.custom.anchor.bottom_right": "오른쪽 아래", + "navbar.custom.anchor.top_centre": "상단 가운데", + "navbar.custom.anchor.top_left": "왼쪽 위", + "navbar.custom.anchor.top_right": "오른쪽 위", "navbar.custom.available": "{available} · 막대로 끌어 놓거나 추가를 누르세요", "navbar.custom.buttons": "버튼", "navbar.custom.compact": "컴팩트", @@ -1408,6 +1530,7 @@ "navbar.custom.reset_default": "기본값으로 재설정", "navbar.custom.right": "오른쪽으로 이동", "navbar.custom.select": "선택한 칸이 없습니다. 막대에서 칸을 선택하면 이동하거나 제거하거나 모양을 바꿀 수 있습니다.", + "navbar.custom.separator_hint": "버튼 그룹 사이의 구분선입니다. 막대로 끌거나 추가를 누르세요. 원하는 만큼 사용할 수 있습니다.", "navbar.custom.separators_full": "막대에 구분선이 이미 네 개 있습니다.", "navbar.custom.show": "탐색 막대 표시", "navbar.custom.shows": "표시 내용", @@ -1516,22 +1639,57 @@ "prefs.add_item": "항목 추가", "prefs.alt_frees_manipulators": "Alt / Option 키로 조작 화살표도 자유롭게 움직입니다", "prefs.anti_aliasing_note": "울퉁불퉁한 모서리를 부드럽게 합니다.", + "prefs.appearance.colour_vision_help": "의미를 전달하는 색상을 변경합니다: 스케치 상태, 축, 굽힘, 분석 및 아이콘.", + "prefs.appearance.desktop_only": "데스크톱 전용", + "prefs.appearance.follow_help": "다른 도구가 파일을 다시 쓰면 다시 불러옵니다.", + "prefs.appearance.interface_scale": "인터페이스 배율", + "prefs.appearance.next_themes": "다음 테마", + "prefs.appearance.option_count": "옵션 {count}개", + "prefs.appearance.option_count_one": "옵션 {count}개", + "prefs.appearance.previous_themes": "이전 테마", + "prefs.appearance.theme_count": "테마 {count}개", + "prefs.appearance.theme_own": "테마 자체", + "prefs.appearance.viewport_colours": "3D 보기 색상", + "prefs.appearance.viewport_logo": "뷰포트 및 로고", "prefs.applies_on_restart": "다시 시작하면 적용됩니다", "prefs.assistant": "어시스턴트", + "prefs.assistant_connecting": "연결", + "prefs.assistant_follow_help": "스케치의 Look At 동작이 포인터와 함께 보기를 이동합니다.", + "prefs.assistant_limit": "제한", + "prefs.assistant_limited": "제한됨", + "prefs.assistant_pointer_speed": "포인터 속도", + "prefs.assistant_seconds": "초", + "prefs.assistant_seconds_aria": "초", + "prefs.assistant_use_care": "주의해서 사용", + "prefs.auto_operation_note": "재료가 닿는 대상에 따라 결합, 새 바디 또는 자르기를 선택합니다.", "prefs.axes": "축", "prefs.axis": "축", + "prefs.blur_cost": "상대적인 렌더링 비용입니다. 막대가 많을수록 일반적으로 더 많은 작업이 필요합니다.", + "prefs.blur_device": "이 그래픽 장치 또는 렌더링 경로에서는 사용할 수 없습니다", + "prefs.blur_guard": "화면의 원활한 응답을 위해 흐림 품질을 낮췄습니다. 반경은 변경되지 않습니다.", + "prefs.blur_off": "끄기", + "prefs.blur_reduce_transparency": "시스템의 투명도 줄이기 설정에 의해 비활성화됨", + "prefs.blur_software": "소프트웨어 그래픽에서는 사용할 수 없습니다 (gpu-software)", + "prefs.blur_source": "이 작업 공간 보기에서는 사용할 수 없습니다", + "prefs.blur_web": "이 웹 렌더링 경로에서는 사용할 수 없습니다", "prefs.bodies_folders": "바디 폴더", "prefs.bodies_folders_always": "항상 표시", "prefs.bodies_folders_never": "표시 안 함", - "prefs.bodies_folders_several": "바디가 여러 개일 때만", + "prefs.bodies_folders_several": "여러 개", "prefs.bottom": "아래쪽", "prefs.bottom_centre": "하단 가운데", "prefs.bottom_right": "오른쪽 아래", "prefs.browser": "브라우저", + "prefs.browser_components_open": "구성요소를 펼친 상태로 시작", + "prefs.browser_components_open_note": "브라우저의 모든 구성요소가 이전처럼 펼쳐진 상태로 시작합니다. 끄면 직접 펼칠 때까지 접혀 있습니다.", + "prefs.browser_eye_left": "접기 화살표 옆의 눈 아이콘", + "prefs.browser_eye_left_note": "브라우저 행의 표시 아이콘을 행 오른쪽 끝의 열이 아니라 이전처럼 접기 화살표 옆에 표시합니다.", "prefs.built_in": "기본 제공", "prefs.button_left": "왼쪽 드래그", "prefs.button_middle": "가운데 드래그", "prefs.button_right": "오른쪽 드래그", + "prefs.carousel_next": "다음", + "prefs.carousel_previous": "이전", "prefs.choose_font": "글꼴 파일 선택…", "prefs.click": "클릭", "prefs.contact_shading": "부드러운 접촉 음영", @@ -1544,16 +1702,38 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "곡면", "prefs.curves": "곡면", + "prefs.cut_preview_tint": "제거되는 재료를 빨간색으로 표시", + "prefs.cut_preview_tint_help": "미리 보기는 피처가 제거하는 재료와 대체되는 형상을 빨간색 반투명 고스트로 채웁니다. 끄면 이 채움이 완전히 투명해지고 윤곽선만 그려집니다.", + "prefs.dark_parts_shading": "어두운 부품의 형태 유지", + "prefs.dark_parts_shading_help": "선형 조명과 부드러운 하늘광으로 뷰를 음영 처리하여 어두운 면이 검게 뭉개지지 않고 그라데이션을 유지합니다", "prefs.dead_zone_note": "빗금 친 영역이 데드존입니다. 그 안의 움직임은 무시됩니다.", "prefs.default": "기본값", - "prefs.design": "설계 기본값", - "prefs.design_note": "새 설계가 시작할 때의 설정입니다. 열려 있는 설계는 자체 설정을 유지합니다.", + "prefs.design": "디자인", + "prefs.design_note": "새 디자인의 시작 설정입니다.", + "prefs.design_tools.ask": "묻기", + "prefs.design_tools.degrees": "도", + "prefs.design_tools.double_click_help": "연결된 구성요소를 제자리에서 편집할 수도 있습니다.", + "prefs.design_tools.ghost": "이동한 부품의 이전 위치를 고스트로 표시", + "prefs.design_tools.hole_moves_help": "면을 다시 선택하면 구멍을 제거하지 않고 이동합니다.", + "prefs.design_tools.hole_snaps_help": "면의 가운데와 원형 모서리의 중심입니다.", + "prefs.design_tools.imported_files": "가져온 파일", + "prefs.design_tools.note": "알림", + "prefs.design_tools.off": "끄기", + "prefs.design_tools.placement_group": "레스트, 보스, 스냅 핏", + "prefs.design_tools.rows": "행", "prefs.devices": "3D 마우스", "prefs.dialog_buttons": "대화 상자 버튼", "prefs.dialogs": "대화 상자", "prefs.dialogs_edge": "뷰 가장자리", "prefs.dialogs_left_column": "왼쪽 열", "prefs.dialogs_note": "명령 대화 상자가 열리는 위치: 뷰 가장자리에 고정하거나, 왼쪽 열에서 브라우저와 이력 대신 표시합니다. 대화 상자를 닫으면 브라우저와 이력이 그대로 돌아옵니다.", + "prefs.dimension_step_angle": "창의 화살표, 위/아래 키와 휠이 각도에 더하는 값", + "prefs.dimension_step_length": "창의 화살표, 위/아래 키와 휠이 길이에 더하는 값", + "prefs.dimension_steps": "창의 증감 단위", + "prefs.dimension_values": "치수 값", + "prefs.dimension_values_note": "치수 값을 입력하는 위치입니다. 창에는 값을 증감하는 화살표가 있으며, 치수 도구는 텍스트를 먼저 배치합니다.", + "prefs.dimension_values_view": "뷰에서", + "prefs.dimension_values_window": "창에서", "prefs.display": "표시", "prefs.drawings": "도면", "prefs.edges": "모서리 및 음영", @@ -1565,19 +1745,53 @@ "prefs.font_sample": "The quick brown fox · Ø12.50 mm · 45.0° · 0123456789", "prefs.font_unreadable": "선택한 글꼴을 읽을 수 없습니다.", "prefs.general": "일반", - "prefs.general_note": "언어, 저장 및 업데이트.", + "prefs.general.active": "사용 중", + "prefs.general.crash_reports": "충돌 보고서", + "prefs.general.edited": "수정됨", + "prefs.general.held": "포함 항목", + "prefs.general.import": "가져오기...", + "prefs.general.last_check": "마지막 확인: {time}", + "prefs.general.minutes": "분", + "prefs.general.name_setup": "이 설정의 이름", + "prefs.general.profile_name": "프로필 이름", + "prefs.general.save_new": "새로 저장", + "prefs.general.step_import": "STEP 및 가져오기", + "prefs.general.this_computer": "이 컴퓨터", + "prefs.general_note": "프로필, 언어, 파일 및 업데이트.", "prefs.gesture_orbit": "회전", "prefs.gesture_pan": "이동", "prefs.gesture_zoom": "확대/축소", "prefs.graphics": "그래픽", "prefs.graphics_note": "속도와 부드러움 중에서 선택합니다. 각 선택의 효과가 샘플에 표시됩니다.", + "prefs.graphics_page.current_view": "현재 뷰", + "prefs.graphics_page.fastest": "가장 빠르게", + "prefs.graphics_page.fold_items": "항목 접기", + "prefs.graphics_page.in_view": "뷰 내부", + "prefs.graphics_page.live_details": "실시간 세부 정보", + "prefs.graphics_page.own_mix": "사용자 조합", + "prefs.graphics_page.quick_measure": "빠른 측정", + "prefs.graphics_page.reference_geometry_through_bodies": "바디를 통한 참조 형상", + "prefs.graphics_page.restart": "다시 시작 필요", + "prefs.graphics_page.sharpest": "가장 선명하게", + "prefs.graphics_page.single_surface_analysis": "단일 표면 분석", + "prefs.graphics_page.status_chips": "상태 칩", + "prefs.graphics_page.subtitle": "속도와 부드러움의 균형을 조절합니다.", + "prefs.graphics_page.supersampling": "슈퍼샘플링", + "prefs.graphics_page.supersampling_adaptive": "뷰가 멈춰 있는 동안만", + "prefs.graphics_page.surfaces_edges": "곡면과 모서리", + "prefs.graphics_page.view_bar": "뷰 표시줄에서도 사용", "prefs.graphics_presets_note": "프리셋은 아래의 선택 항목을 한 번에 설정합니다.", + "prefs.hide_constraint_glyphs_zoomed_out": "축소 시 구속 조건 기호 숨기기", + "prefs.hide_constraint_glyphs_zoomed_out_note": "스케치를 충분히 축소하면 구속 조건 기호가 가려지지 않도록 숨깁니다. 끄기: 확대/축소와 관계없이 고정된 화면 크기를 유지합니다.", "prefs.history": "이력", "prefs.history_origin_bodies": "원점과 바디를 맨 위에 표시", "prefs.history_origin_bodies_note": "왼쪽 또는 브라우저 아래의 히스토리가 활성 구성 요소의 바디 폴더와 원점으로 시작하며, 브라우저처럼 표시 아이콘과 메뉴가 있습니다. 아래쪽 히스토리는 바뀌지 않습니다.", "prefs.history_play_button": "기록 컨트롤에 기록 재생 버튼 표시", "prefs.history_play_button_note": "기록 컨트롤의 한 단계 뒤로와 한 단계 앞으로 사이에 기록 재생을 추가합니다. 컨트롤을 마우스 오른쪽 버튼으로 클릭해 표시하거나 숨길 수도 있습니다.", + "prefs.history_sketches": "히스토리의 스케치", "prefs.hold_stop_snapping": "누르고 있으면 스냅 중지", + "prefs.home_fit_size": "홈·맞춤 크기", + "prefs.home_fit_size_note": "홈, 맞춤, 연 디자인 또는 뷰 탐색기의 뷰 변경으로 모델을 화면에 맞출 때 모델이 뷰에서 차지하는 비율. 아래 설정과 관계없이 적용됩니다. 100 %: 패널, 나침반, 내비게이션 바 사이의 뷰를 가득 채웁니다.", "prefs.icons_only": "아이콘만", "prefs.imported_file": "가져온 파일", "prefs.input": "입력", @@ -1586,19 +1800,38 @@ "prefs.interface_note": "SolidCraft의 모양과 각 부분의 위치입니다.", "prefs.interval_minutes": "{n}분", "prefs.labels": "레이블", + "prefs.language_system": "시스템", "prefs.layout": "레이아웃", "prefs.layout_note": "컴팩트는 패널을 창 가장자리에 고정합니다. 브라우저 반투명은 플로팅에서 사용할 수 있습니다. 어시스턴트 위치는 어시스턴트 페이지에서 바꿀 수 있습니다.", + "prefs.layout_page.active_commands": "활성 명령 강조", + "prefs.layout_page.always": "항상", + "prefs.layout_page.card": "카드", + "prefs.layout_page.column": "열", + "prefs.layout_page.hover": "마우스를 올릴 때", + "prefs.layout_page.icons_labels": "아이콘 + 레이블", + "prefs.layout_page.ok_cancel": "확인과 취소", + "prefs.layout_page.on_hover": "마우스를 올릴 때", + "prefs.layout_page.open": "열기", + "prefs.layout_page.origin_bodies": "원점과 바디를 위에 표시", + "prefs.layout_page.panels": "패널", + "prefs.layout_page.pinned_menus": "고정 명령을 메뉴에서 제외", + "prefs.layout_page.play_history": "히스토리 재생 버튼", + "prefs.layout_page.slot_count": "슬롯 {count} / {max}개", + "prefs.layout_page.view_corner": "뷰 모서리에도 표시", + "prefs.layout_page.window": "창", "prefs.left": "왼쪽", "prefs.left_click": "왼쪽 클릭", "prefs.line_drag_draws_one": "누른 채 드래그하면 선 하나 그리기", "prefs.line_drag_draws_one_note": "선 도구에서 누르고 드래그한 뒤 놓으면 누른 곳에서 놓은 곳까지 선 하나를 그리고 거기서 끝납니다. 클릭하면 이전처럼 이어지는 선을 그립니다. 끄면: 드래그는 클릭처럼 놓은 곳에 점을 둡니다.", + "prefs.line_hover_tangent_arc": "선의 마지막 점에 머무르면 접선 호로 전환", + "prefs.line_hover_tangent_arc_note": "선 도구에서 선분을 그린 뒤 체인의 마지막 점에서 벗어났다가 돌아와 포인터를 그 위에 멈추면, 다음 클릭으로 접선 호의 끝점을 지정합니다. 같은 동작으로 선으로 돌아갑니다. 끔: 머물러도 아무 일도 일어나지 않습니다.", "prefs.live_input": "실시간 입력", "prefs.live_preview": "실시간 미리보기", "prefs.max_file_size": "열 수 있는 최대 파일 크기", - "prefs.max_file_size_design": "디자인 파일", + "prefs.max_file_size_design": "열 파일의 최대 크기: 디자인", "prefs.max_file_size_flag": "이번 실행은 --max-file-size {size}로 시작했으며 SolidCraft를 닫을 때까지 적용됩니다. 이 설정은 해당 옵션 없이 시작할 때 적용됩니다.", "prefs.max_file_size_note": "기본값: 512 MB 및 256 MB, 최대 16 GB. 파일을 열려면 파일 크기의 몇 배에 달하는 메모리가 필요합니다. 큰 가져오기 데이터를 보관하는 디자인은 저장하고 다시 열기 위해 디자인 파일 한도를 높여야 할 수 있습니다.", - "prefs.max_file_size_step": "STEP 및 가져오기 파일", + "prefs.max_file_size_step": "열 파일의 최대 크기: STEP 및 가져오기", "prefs.max_file_size_web": "웹 앱은 STEP 및 가져오기 파일을 512 MB까지, 디자인을 256 MB까지 엽니다. 브라우저 탭은 더 큰 파일을 담을 수 없습니다. 데스크톱 앱에서는 이 한도를 높일 수 있습니다.", "prefs.megabytes": "MB", "prefs.minutes": "분", @@ -1607,7 +1840,17 @@ "prefs.mouse_heading": "마우스", "prefs.mouse_mapping": "마우스 매핑", "prefs.navigation": "탐색", + "prefs.navigation.axes_signed": "축", + "prefs.navigation.cube_compact": "큐브", + "prefs.navigation.device": "장치", + "prefs.navigation.free": "자유", + "prefs.navigation.orbit_style": "회전 방식", + "prefs.navigation.radial_help": "오른쪽 버튼을 길게 누르거나 튕겨 도구 링을 표시합니다.", + "prefs.navigation.turntable": "턴테이블", "prefs.navigation_note": "마우스, 트랙패드, 3D 마우스로 뷰를 움직이는 방식입니다.", + "prefs.navigator_fit": "뷰 탐색기로 뷰를 바꾼 뒤 모델 맞춤", + "prefs.navigator_fit_note": "큐브의 면, 모서리, 화살표나 기즈모의 축을 클릭하면 어느 방향에서든 전체가 들어가는 한 거리(경계 구)에서 모델의 중심을 바라봅니다. 켜져 있는 동안 홈 뷰도 같은 확대/축소와 중심을 쓰므로 그 뒤에 고른 뷰는 방향만 바뀝니다. 끄면 뷰가 제자리에서 회전하며 대상과 확대/축소를 유지합니다.", + "prefs.network_locations_note": "파일 서버에 디자인을 보관하는 조직용입니다. 끄면 허용한 서버만 사용합니다.", "prefs.not_on_gpu": "이 GPU에서는 사용할 수 없음", "prefs.on": "켜짐", "prefs.opaque": "불투명", @@ -1616,10 +1859,23 @@ "prefs.origin_plane_names": "원점 평면 이름", "prefs.origin_plane_names_note": "브라우저, 대화 상자, 목록에 표시되는 이름입니다. {top}은 XY, {front}는 XZ, {right}는 YZ이며 Z가 위쪽입니다. 명령, 스크립트, 저장된 디자인은 XY, XZ, YZ를 유지합니다.", "prefs.overall_speed": "전체 속도", + "prefs.parameter_list_rows_tip": "빈 수식 상자에서 아래쪽 화살표로 표시할 매개변수의 최대 개수입니다.", "prefs.persistent_ribbon_pressed": "활성 리본 명령 강조 표시", "prefs.persistent_ribbon_pressed_help": "효과가 켜져 있는 동안 리본 명령을 강조 표시합니다. 끄면 이전의 중립적인 모양과 명령 도움말을 유지합니다.", "prefs.perspective_fov": "시야각", + "prefs.plugins_enabled": "사용", + "prefs.plugins_installed": "설치됨", + "prefs.plugins_intro": "샌드박스 추가 기능.", + "prefs.plugins_show_folder": "플러그인 폴더 표시", "prefs.preview_choices": "선택 항목 미리보기", + "prefs.preview_tint_new_faces": "미리 보기에서 새 면에 색 입히기", + "prefs.preview_tint_new_faces_help": "바디를 변경하는 피처의 미리 보기에서 추가되는 면을 미리 보기 색으로 그릴 수 있습니다. 끄면 바디가 원래 색으로 그려집니다.", + "prefs.print_face_highlight": "출력 바닥면 강조", + "prefs.print_face_highlight_tip": "뷰에서 바디의 출력 바닥면을 색칠하고 윤곽을 그리는 강도입니다. 0 %이면 강조하지 않습니다.", + "prefs.profile_export": "내보내기", + "prefs.profile_imported": "프로필을 가져왔습니다.", + "prefs.profile_operations": "작업 프로파일링", + "prefs.profile_operations_note": "SMLib 호출, 커널 작업, 피처, 명령, 가져오기에 걸리는 시간을 기록합니다. 에이전트는 diagnostics.profile로 읽습니다.", "prefs.project_options_dialog": "Project 옵션 대화상자", "prefs.project_options_dialog_note": "켜기: 투영 전에 지오메트리 또는 바디와 투영 링크를 선택합니다. 끄기: 기존 직접 선택 작업 흐름을 유지합니다.", "prefs.quality_default": "기본값", @@ -1627,21 +1883,61 @@ "prefs.quality_slowest": "가장 느림", "prefs.quality_smoother": "더 부드럽게", "prefs.reports_saved": "{n}개 저장됨", + "prefs.restore_page_defaults": "페이지 기본값 복원", + "prefs.ribbon_click_ends_tool": "실행 중인 도구의 버튼을 클릭하면 도구 종료", + "prefs.ribbon_click_ends_tool_note": "사용 중인 스케치 도구의 강조된 리본 버튼을 클릭하면 도구가 종료되어 뷰에서 클릭하면 다시 선택됩니다. 끄기: 클릭하면 도구가 다시 시작됩니다.", "prefs.right_click": "오른쪽 클릭", - "prefs.saving": "자동 저장 및 복구", + "prefs.saving": "시작 및 저장", "prefs.scale_note": "창에서 Ctrl + / Ctrl −로도 조절합니다. 버튼은 100%에서 28 px입니다.", "prefs.scale_text": "배율 및 텍스트", "prefs.search": "설정 검색", "prefs.search_empty": "일치하는 설정이 없습니다", "prefs.select": "선택", "prefs.select_one_item": "항목 하나 선택", + "prefs.select_other_hidden": "다른 항목 선택으로 숨겨진 형상 선택", + "prefs.select_other_hidden_help": "켜짐: 포인터 근처의 숨겨진 바디, 스케치 및 가려진 모서리를 포함합니다. 꺼짐: 포인터 바로 아래에 보이는 형상만 포함하는 기존 목록을 사용합니다.", "prefs.selecting": "선택", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift는 추가만, Ctrl / Cmd는 토글", "prefs.shift_add_note": "켬: Shift는 추가, Ctrl / Cmd는 토글. 끔(기본값): 둘 다 토글.", "prefs.shortcuts": "단축키", + "prefs.shortcuts_import": "가져오기", + "prefs.shortcuts_intro": "각 명령의 키.", + "prefs.shortcuts_not_assigned": "할당되지 않음", + "prefs.shortcuts_press": "키를 누르세요...", "prefs.single_surface_analysis": "표면 분석 하나만 사용", "prefs.single_surface_analysis_help": "끄면 표면 음영 분석과 연속성 분석을 함께 유지할 수 있습니다. 켜면 마지막으로 시작하거나 변경한 분석만 유지됩니다.", + "prefs.sketch.align_points": "다른 스케치 점에 정렬", + "prefs.sketch.align_points_note": "그리는 선을 두 축의 점에 동시에 정렬합니다.", + "prefs.sketch.auto_dimensions": "새 도형에 모든 치수 지정", + "prefs.sketch.auto_dimensions_note": "입력한 값과 도형을 고정하는 모든 치수.", + "prefs.sketch.auto_locate": "스케치 원점에서 배치", + "prefs.sketch.auto_locate_note": "모든 치수 지정 시 적용.", + "prefs.sketch.center_arc": "중심점 호가 커서를 따라감", + "prefs.sketch.click_selects": "클릭으로 선택", + "prefs.sketch.conflict_colour": "충돌 색상", + "prefs.sketch.drawing": "그리기", + "prefs.sketch.exit_keep": "유지", + "prefs.sketch.exit_previous": "이전 뷰로 돌아가기", + "prefs.sketch.exit_unless_rotated": "회전하지 않았다면", + "prefs.sketch.faces_edges": "면과 모서리", + "prefs.sketch.hide_glyphs": "축소 시 기호 숨기기", + "prefs.sketch.marks": "스케치의 표시", + "prefs.sketch.note": "그리기, 스냅 및 선택.", + "prefs.sketch.opening_closing": "열기 및 닫기", + "prefs.sketch.prefer_free_points": "겹치는 곳에서는 이동 가능한 점 우선", + "prefs.sketch.project_options": "투영 옵션을 먼저 묻기", + "prefs.sketch.recent_snap": "두 안내선의 교차점에 스냅", + "prefs.sketch.select_other_hidden": "다른 항목 선택에 숨겨진 형상 포함", + "prefs.sketch.shortcut_cycles_modes": "단축키를 다시 누르면 모드 전환", + "prefs.sketch.shortcut_cycles_modes_tip": "끄면 도구를 다시 시작합니다.", + "prefs.sketch.snapping_guides": "스냅 및 안내선", + "prefs.sketch.state_icons": "상태 아이콘", + "prefs.sketch.tracking_guides": "중심 및 중점 안내선", + "prefs.sketch.tracking_guides_note": "마우스를 올린 중심과 모서리 중점에서 임시 가로 및 세로 안내선을 표시합니다.", + "prefs.sketch.tracking_points": "스케치 점에서도 안내선 표시", + "prefs.sketch.unless_turned_note": "회전하지 않았으면 복귀", + "prefs.sketch.whole_bodies": "전체 바디", "prefs.sketch_align_points": "그리는 동안 다른 스케치 점에 맞추기", "prefs.sketch_align_points_note": "그리는 동안 점이 한 스케치 점과 수평으로, 다른 점과 수직으로 동시에 맞춰지고 점선 안내선이 표시됩니다. 클릭하면 두 정렬이 모두 유지됩니다. 끄기: 이전 점에만, 한 번에 한 축씩 맞춥니다.", "prefs.sketch_conflict_colour": "충돌하는 기하를 충돌 색상으로 표시", @@ -1660,17 +1956,39 @@ "prefs.sketch_tab_always_note": "스케치가 열려 있지 않을 때도 스케치 탭이 리본에서 모델 바로 다음에 남아 있습니다. 그 그리기 도구는 선택한 평면이나 면, 또는 다음에 고르는 평면에서 스케치를 시작하고 그 안에서 도구를 바로 쓸 수 있게 합니다.", "prefs.sketch_tracking_guides": "중심 및 중점 정렬 안내선", "prefs.sketch_tracking_guides_note": "원 중심이나 직선 모서리의 중점에 마우스를 올린 다음 수평 또는 수직으로 이동하면 임시 점선 안내선이 표시됩니다.", + "prefs.sketch_tracking_points": "그리는 동안 끝점과 모서리에서도 정렬 안내선", + "prefs.sketch_tracking_points_note": "그리기 도구가 점을 기다리는 동안 선이나 호의 끝점, 직사각형 모서리, 자유 점에 마우스를 올리면 중심이나 중점과 같은 임시 점선 안내선이 표시됩니다. 끄면: 중심과 중점만.", "prefs.sketching": "스케치", "prefs.snap_drawing_note": "스케치 점을 그리거나 드래그하는 동안.", "prefs.source": "소스", "prefs.speed": "속도", "prefs.stand_up_note": "STEP 또는 IGES 파일이 Z가 위쪽인 상태로 열린 후 X축 기준 90도 회전을 제안합니다.", + "prefs.stand_up_unknown": "알 수 없는 프로그램의 파일", + "prefs.stand_up_unknown_note": "파일에 알려진 프로그램 이름이 없을 때 제안하는 방법입니다.", "prefs.status_bar": "상태 표시줄", "prefs.status_bar_note": "창 아래쪽 가장자리의 얇은 표시줄에 편집 중인 항목, 열려 있는 스케치의 상태(해당 색상으로), 설계 단위가 표시됩니다. 단위를 클릭하면 변경할 수 있습니다. 스케치 상태는 더 이상 뷰 모서리에 표시되지 않습니다.", "prefs.status_done": "완료", "prefs.status_error": "오류", "prefs.status_selected": "선택됨", "prefs.status_warning": "경고", + "prefs.structure.appearance": "모양", + "prefs.structure.appearance_note": "색상, 텍스트 및 접근성.", + "prefs.structure.in_profile": "프로필에 포함", + "prefs.structure.layout": "레이아웃", + "prefs.structure.layout_note": "창 구성 요소의 위치.", + "prefs.structure.look": "보기", + "prefs.structure.measure_pointer": "측정 및 포인터", + "prefs.structure.mouse3d": "3D 마우스", + "prefs.structure.mouse3d_note": "SpaceMouse 및 SpaceNavigator.", + "prefs.structure.navigation_note": "마우스와 트랙패드. 3D 마우스는 별도 페이지에 있습니다.", + "prefs.structure.profile": "프로필", + "prefs.structure.profile_edited": "저장 후 변경됨", + "prefs.structure.profile_hover": "설정 프로필에 저장됨", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "스케치", + "prefs.structure.tools": "도구", + "prefs.structure.tools_note": "모델링 도구의 동작.", + "prefs.structure.work": "작업", "prefs.supersampling_brief": "뷰를 더 크게 그린 뒤 줄여서 필터링합니다. 매우 선명하지만 더 무겁습니다.", "prefs.tab_accent_note": "강조 색상이 활성 탭을 따라갑니다", "prefs.theme_file": "테마 파일", @@ -1680,6 +1998,21 @@ "prefs.theme_follow_note": "다른 도구가 파일을 다시 쓸 때마다 다시 불러옵니다. 테마를 선택하면 따르기를 중지합니다.", "prefs.theme_follow_off": "끄기", "prefs.theme_follow_stop": "따르기 중지", + "prefs.theme_notice_dismiss": "닫기", + "prefs.theme_option_blur": "패널 뒤 흐림", + "prefs.theme_option_blur_help": "반투명 패널 뒤의 흐림을 물리적 픽셀 단위로 설정합니다. 0이면 꺼집니다.", + "prefs.theme_option_invalid": "{option}의 저장된 값이 유효하지 않아 테마 기본값을 사용합니다. 저장된 값은 유지됩니다.", + "prefs.theme_option_opacity": "불투명도", + "prefs.theme_option_opacity_help": "플로팅 패널의 불투명도를 조정합니다. 뷰포트 색상 위에서도 텍스트를 읽을 수 있도록 최솟값이 적용됩니다.", + "prefs.theme_option_tab_colours": "탭 색상", + "prefs.theme_option_tab_colours_help": "각 리본 탭에 이 테마의 패널 및 뷰포트 색상을 사용합니다.", + "prefs.theme_option_tab_fade_ms": "탭 전환", + "prefs.theme_option_tab_fade_ms_help": "탭을 전환할 때 패널 및 뷰포트 색상을 서서히 변경합니다. 0이면 즉시 전환합니다.", + "prefs.theme_options_badge": "옵션", + "prefs.theme_options_more": "더 보기 · {count}", + "prefs.theme_options_newer": "이 테마에는 더 최신 버전의 SolidCraft가 필요합니다. 업그레이드 후 원본 테마를 다시 가져와 옵션 정의를 복구하세요.", + "prefs.theme_options_reset": "초기화", + "prefs.theme_options_unavailable": "이 기기에서는 사용할 수 없음", "prefs.timeline_half_hour": "−30분", "prefs.timeline_now": "지금", "prefs.timeline_quarter_hour": "−15", @@ -1699,10 +2032,26 @@ "prefs.under_cursor": "커서 아래", "prefs.units_precision": "단위 및 정밀도", "prefs.updates": "업데이트", + "prefs.validation": "바디 검사", + "prefs.validation.each_feature": "피처마다 한 번", + "prefs.validation.each_step": "모든 단계 후", + "prefs.validation.label": "커널 전체 검사", + "prefs.validation.off": "끄기 (실험적)", + "prefs.validation_note": "모든 단계 후: 스윕, 불리언, 블렌드마다 검사합니다.\n피처마다 한 번: 각 피처의 결과를 한 번 검사합니다.\n끄기 (실험적): 검사하지 않습니다.", + "prefs.value_boxes_in_view": "핸들 옆에 값 표시", + "prefs.value_boxes_in_view_tip": "돌출의 거리, 필렛의 반지름 등을 뷰 안의 상자로 표시합니다.", "prefs.view": "뷰 동작", "prefs.view_confirm_corner": "뷰 모서리에 확인 및 취소", "prefs.view_confirm_corner_note": "대화 상자나 스케치가 열려 있는 동안 뷰 오른쪽 위의 체크와 X 표시가 대화 상자의 확인과 취소와 같은 동작을 하거나 스케치를 마치고 취소합니다. 뷰 탐색기는 그 아래로 내려갑니다.", "prefs.viewport": "뷰포트", + "prefs.viewport_analysis_status": "뷰포트 해석 상태 표시", + "prefs.viewport_analysis_status_help": "활성 해석을 뷰포트 위에 표시하고 각 항목에서 범례를 엽니다. Esc로 최신 해석을 끕니다. 끄면 모서리 범례와 이전 Esc 동작으로 돌아갑니다.", + "prefs.viewport_section_status": "뷰포트 단면 상태 표시", + "prefs.viewport_section_status_help": "뷰포트에 단면 설정을 표시합니다. Escape 키와 활성 리본 버튼으로 단면을 끕니다. 비활성화하면 이전 단면 조작을 유지합니다.", + "prefs.viewport_status_details": "뷰포트 실시간 상세 정보", + "prefs.viewport_status_details_help": "표준 상세 카드에서 활성 분석 및 단면 설정을 편집합니다. 끄면 읽기 전용 분석 범례와 단면 대화상자로 돌아갑니다.", + "prefs.viewport_status_summary": "뷰포트 상태 항목 요약", + "prefs.viewport_status_summary_help": "상태 항목이 3개 이상이면 하나의 요약 배지로 표시합니다. 비활성화하면 모든 항목을 기존 행에 표시합니다.", "prefs.wheel": "휠", "prefs.wheel_trackpad": "휠 및 트랙패드", "prefs.workspace": "작업 공간", @@ -1720,6 +2069,17 @@ "recovery.just_now": "방금", "recovery.min_ago": "{count}분 전", "recovery.never_saved": "저장된 적 없음", + "refused.change": "{body}을(를) 변경하지 못했습니다.", + "refused.cut": "{body}을(를) 자르지 못했습니다.", + "refused.face_curved": "곡면 중 하나를 모델링에 사용할 수 없습니다.", + "refused.face_flat": "평면 중 하나를 모델링에 사용할 수 없습니다.", + "refused.face_freeform": "자유 곡면 중 하나를 모델링에 사용할 수 없습니다.", + "refused.face_rounded": "둥근 면 중 하나를 모델링에 사용할 수 없습니다.", + "refused.faces_apart": "면들이 충분히 맞물리지 않아 모델링에 사용할 수 없습니다.", + "refused.intersect": "{body}과(와) 교차하지 못했습니다.", + "refused.join": "{body}에 결합하지 못했습니다.", + "refused.repair": "부품 복구", + "refused.show_face": "면 보기", "render.add_ground": "Add fitted ground to setup", "render.all_shots_label": "모든 샷", "render.appearance_editor.absorption": "흡수", @@ -1764,6 +2124,10 @@ "render.appearances": "외관", "render.assign_help": "클릭하여 선택 항목에 적용하거나 드래그하여 미리 보고 놓으세요. 선택이 없으면 칠하기를 시작합니다.", "render.background": "장면 배경", + "render.batch_all_shots": "모든 샷 ({count})", + "render.batch_empty": "모든 샷을 렌더링하기 전에 샷을 저장하세요.", + "render.batch_limit": "한 번에 최대 32개의 샷을 렌더링할 수 있습니다.", + "render.batch_status": "{running}개 실행 중 · {waiting}개 대기 중", "render.bloom_enable": "표시 블룸", "render.bloom_help": "양의 선형 하이라이트를 세 번의 정규화 필터로 확산하는 출력 전용 효과입니다. 반경은 출력 픽셀 단위이며 sRGB 전에 더합니다. 렌즈·볼륨·수렴 개선이 아니며 원본 EXR은 변하지 않습니다.", "render.bloom_opaque": "블룸에는 불투명 출력이 필요합니다. 투명 PNG를 몰래 합성하지 않고 거부합니다.", @@ -1855,6 +2219,13 @@ "render.children.workstation": "워크스테이션", "render.choose_look": "먼저 외관 라이브러리에서 외관을 선택하세요", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "비교 구분선", + "render.compare_live": "라이브", + "render.compare_live_preview": "라이브 미리보기", + "render.compare_render": "렌더 {number}", + "render.compare_side": "렌더 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds}초 · {renderer} · 리비전 {revision}에서 캡처", + "render.compare_swap": "맞바꾸기", "render.cpu_budget": "CPU 리소스 프로필", "render.cpu_budget_bodies": "바디 수 상한", "render.cpu_budget_compact": "컴팩트 (기존 제한)", @@ -2267,7 +2638,9 @@ "render.output_ready": "렌더링 준비 완료", "render.output_run_check": "검사 실행", "render.output_size_limit": "{method}: 한 변 최대 {dimension} px, 총 {pixels} 픽셀. 가능한 최대 크기: {width} × {height}.", + "render.output_size_method_profile": "{width} × {height}을(를) 렌더링하려면 {method}와(과) {profile} CPU 리소스 프로필을 선택하거나 더 작은 크기를 선택하세요.", "render.output_size_ok": "크기 정상 · {width} × {height} px", + "render.output_size_profile": "{width} × {height}을(를) 렌더링하려면 {profile} CPU 리소스 프로필이나 더 작은 크기를 선택하세요.", "render.output_tools_inspector": "출력 검사기에서 크기와 형식을 편집하세요.", "render.output_view_image": "이미지 보기", "render.paint_label": "칠하기", @@ -2321,6 +2694,10 @@ "render.result_actual": "100%", "render.result_actual_size": "100%", "render.result_reduced_display": "표시 미리보기를 뷰포트 장치 또는 캐시 제한에 맞춰 축소했습니다. 보관된 PNG와 내보내기는 전체 해상도를 유지합니다. 이 축소 보기에서는 원본 100% 검사가 불가능합니다.", + "render.results_choose": "보관된 결과", + "render.results_label": "렌더 {number} · {shot} · {seconds}초", + "render.results_stale_label": "{result} [이전 버전]", + "render.results_unnamed": "이미지", "render.return_design": "설계로 돌아가기", "render.ribbon_backgrounds": "배경", "render.ribbon_check": "검사", @@ -2399,6 +2776,7 @@ "render.size_custom": "사용자 지정…", "render.size_full_hd": "풀 HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · {profile} 필요", "render.size_presets": "크기 프리셋", "render.size_presets_pending": "출력 편집기와 함께 제공 예정", "render.size_preview": "미리보기", @@ -2604,10 +2982,10 @@ "select the sheet edge first": "판금 모서리를 먼저 선택하세요", "select two components": "구성요소 두 개를 선택하세요", "settings.display_quality_note": "세밀할수록 곡면과 모서리가 더 매끄럽게 표시되지만 메시 생성 시간이 늘어납니다. 뷰포트만 바뀌며 설계나 내보내기는 바뀌지 않습니다.", - "settings.double_click_components": "구성 요소를 두 번 클릭하여 활성화하거나 연결된 구성 요소를 제자리에서 편집", + "settings.double_click_components": "구성요소를 두 번 클릭하여 활성화", "settings.frame_rate_note": "뷰의 오른쪽 아래에 초당 프레임 수를 표시합니다.", - "settings.insert_lists_open_designs": "설계 삽입에서 다른 탭에 열린 설계를 먼저 표시", - "settings.measure_axis_distances": "X/Y/Z 거리 표시", + "settings.insert_lists_open_designs": "디자인 삽입에서 열린 디자인을 먼저 표시", + "settings.measure_axis_distances": "측정에서 축 거리 표시", "settings.measure_axis_distances_help": "측정 대화상자가 열려 있는 동안 전체 거리와 함께 월드 축 방향 치수와 거리를 표시합니다.", "settings.msaa_applies_on_restart": "안티앨리어싱은 다음에 SolidCraft를 시작할 때 적용됩니다", "settings.msaa_reset": "{setting}: {requested}×는 이 그래픽 장치에서 지원되지 않아 {reset}×로 변경했습니다(지원: {supported}).", @@ -2617,9 +2995,28 @@ "settings.reset_intro": "다음 설정은 이 컴퓨터에서 작동하지 않아 SolidCraft를 시작할 수 없게 하므로 변경되었습니다:", "settings.reset_title": "설정이 변경되었습니다", "settings.supersampling_note": "뷰를 더 높은 해상도로 그린 뒤 축소합니다. 4K 미만 화면에서 모서리, 선, 그리드가 더 매끄러워집니다. GPU 시간이 듭니다: 1.5×에서 약 2.25배, 2×에서 4배의 픽셀.", + "settings.update_changed_links": "탭으로 돌아올 때 변경된 링크 업데이트", "sheet.flange_type_base": "베이스", "sheet.flange_type_contour": "윤곽", "sheet.flange_type_edge": "모서리", + "sheet.personal_rules.confirm_delete": "삭제 확인", + "sheet.personal_rules.delete": "삭제", + "sheet.personal_rules.delete_prompt": "이 개인 규칙을 삭제할까요? 설계에 이미 있는 규칙은 바뀌지 않습니다.", + "sheet.personal_rules.full": "개인 라이브러리에 이미 규칙이 64개 있습니다.", + "sheet.personal_rules.invalid_name": "줄 바꿈이나 제어 문자가 없는 짧은 이름을 입력하세요.", + "sheet.personal_rules.invalid_values": "규칙 값을 모두 입력하세요. 각 값은 이 설계에서 계산할 수 있어야 하며, 두께는 양수, K 계수는 0에서 1 사이여야 합니다.", + "sheet.personal_rules.missing": "선택한 개인 규칙을 더 이상 사용할 수 없습니다.", + "sheet.personal_rules.name": "규칙 이름", + "sheet.personal_rules.name_exists": "같은 이름의 개인 규칙이 이미 있습니다. 다른 이름을 사용하세요.", + "sheet.personal_rules.name_hint": "고유한 이름", + "sheet.personal_rules.overwrite": "선택한 개인 규칙에 변경 사항 저장", + "sheet.personal_rules.rename": "이름 바꾸기", + "sheet.personal_rules.rule": "개인 규칙", + "sheet.personal_rules.save": "새로 저장", + "sheet.personal_rules.scope": "모든 설계에서 쓸 수 있도록 프로필에 저장됩니다.", + "sheet.personal_rules.select": "규칙 선택", + "sheet.personal_rules.title": "개인 규칙", + "sheet.personal_rules.unsupported": "이 규칙에는 이 버전에서 사용할 수 없는 값이 있습니다.", "shortcut.json_error": "매개변수는 JSON 형식이어야 합니다: {error}", "shortcut.no_command": "`{id}` 명령이 없습니다. JSON 앞의 텍스트는 명령 ID여야 합니다", "shortcut.pin": "S 상자 맨 위에 고정", @@ -2681,7 +3078,18 @@ "the section's profiles must be in one sketch": "단면의 프로파일은 하나의 스케치 안에 있어야 합니다", "the two origins are on the same component": "두 원점이 같은 구성요소에 있습니다", "thread.automatic_size": "자동 크기", + "thread.chamfer_depth_needed": "이 형상에 필요", "thread.designation": "호칭", + "thread.drill_range": "탭 제조사의 드릴은 {drill} mm입니다. 암나사의 규격 골지름은 {minor} mm입니다. {low}~{high} mm 드릴을 사용할 수 있습니다.", + "thread.drill_range_custom": "드릴은 바깥지름에서 피치를 뺀 {drill} mm입니다. 암나사의 규격 골지름은 {minor} mm입니다. {low}~{high} mm 드릴을 사용할 수 있습니다.", + "thread.drill_range_taper": "탭 제조사의 드릴은 {drill} mm입니다. 나사 끝에서의 규격 골지름은 {minor} mm입니다. {low}~{high} mm 드릴을 사용할 수 있습니다.", + "thread.end_square": "직각", + "thread.fade_short": "1.25 P (ISO 3508)", + "thread.fade_standard": "2.5 P (ISO 3508)", + "thread.form_bspp": "관용 평행나사 G (ISO 228-1)", + "thread.form_bspt": "관용 테이퍼나사 R, Rc (ISO 7-1)", + "thread.form_npt": "관용 테이퍼나사 NPT (ASME B1.20.1)", + "thread.form_rp": "관용 평행 암나사 Rp (ISO 7-1)", "thread.iso_metric": "ISO 미터", "thread.select_size": "크기 선택", "timeline.feature_hint": "두 번 클릭하여 편집 · 드래그하여 순서 변경 · 마우스 오른쪽 버튼을 클릭하여 더 보기", @@ -2776,6 +3184,7 @@ "ui.3d_mouse_section": "3D 마우스", "ui.3d_mouse_show_in_view": "3D 뷰에 3D 마우스 표시", "ui.3d_mouse_show_in_view_tip": "왼쪽 아래에 3D 마우스 그림을 띄워 움직임을 따라 보여 줍니다.", + "ui.3d_mouse_sketch_orbit": "스케치 편집 중 뷰 회전", "ui.3d_mouse_skip": "내 장치는 이 동작을 못 해요", "ui.3d_mouse_skip_tip": "이 동작을 양방향 모두 건너뛰고 보정에서 뺍니다.", "ui.3d_mouse_speed": "3D 마우스 속도", @@ -2804,6 +3213,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "캡을 시계 반대 방향으로 돌려 유지한 다음 놓으세요.", "ui.3d_mouse_switch_cap": "중앙 복귀형으로 보정", "ui.3d_mouse_switch_trackball": "트랙볼로 보정", + "ui.3d_mouse_use_direct": "직접 드라이버 사용", + "ui.3d_mouse_use_direct_tip": "spacenavd를 거치지 않고 3D 마우스를 직접(hidraw) 읽습니다.", "ui.3d_mouse_view_axis": "뷰 축", "ui.3d_mouse_view_off": "끔", "ui.3d_mouse_view_off_tip": "3D 마우스 드라이버 프로필이 이 축을 끄므로, 이 축의 동작으로는 뷰가 움직이지 않습니다. 여기서 다른 축의 동작을 고르면 둘이 바뀌고, 그 동작은 더 이상 뷰를 움직이지 않습니다.", @@ -2840,12 +3251,15 @@ "ui.agent_chat_auth_terminal": "터미널에서 이것을 실행한 뒤 다시 연결을 누르세요:", "ui.agent_chat_auth_title": "에이전트에 로그인", "ui.agent_chat_cancel": "취소", + "ui.agent_chat_cancel_timeout": "에이전트가 중지 요청에 응답하지 않아 연결이 끊어졌습니다. 계속하려면 다시 연결하세요.", + "ui.agent_chat_cannot_start": "설치되어 있지만 시작되지 않습니다: {error}", "ui.agent_chat_changes": "변경 {n}개, 실행 취소 한 번", "ui.agent_chat_changes_of": "변경 {n}/{limit}", "ui.agent_chat_close": "닫기", "ui.agent_chat_command": "에이전트 명령", "ui.agent_chat_connect": "연결", "ui.agent_chat_copy": "복사", + "ui.agent_chat_custom_heading": "사용자 지정 모델", "ui.agent_chat_custom_hint": "표준 입출력으로 Agent Client Protocol을 사용하는 모든 프로그램. 셸 없이 실행됩니다.", "ui.agent_chat_denied": "거부함", "ui.agent_chat_deny": "거부", @@ -2887,7 +3301,15 @@ "ui.agent_chat_mode_all": "모두", "ui.agent_chat_mode_ask": "확인", "ui.agent_chat_mode_edits": "편집", + "ui.agent_chat_model_custom": "직접 입력 사용: {model}", + "ui.agent_chat_model_rejected": "에이전트가 {model}을(를) 받아들이지 않았습니다: {error}", + "ui.agent_chat_model_search": "모델 검색…", "ui.agent_chat_model_tip": "에이전트가 사용하는 모델입니다. 선택은 이 에이전트에 기억됩니다.", + "ui.agent_chat_models_failed": "모델 목록을 가져올 수 없습니다: {error}", + "ui.agent_chat_models_heading": "사용 가능한 모델", + "ui.agent_chat_models_listing": "모델 목록을 가져오는 중…", + "ui.agent_chat_models_none": "엔드포인트에 나열된 모델이 없습니다", + "ui.agent_chat_models_not_a_list": "응답이 모델 목록이 아닙니다", "ui.agent_chat_new": "새 채팅", "ui.agent_chat_new_confirm": "새 채팅을 시작할까요? 현재 채팅은 지워집니다.", "ui.agent_chat_next_picture": "다음 이미지", @@ -2895,6 +3317,7 @@ "ui.agent_chat_no_control": "에이전트 채팅 엔드포인트가 시작되지 않아 에이전트가 디자인에 접근할 수 없습니다.", "ui.agent_chat_no_images": "이 에이전트는 이미지를 받지 않습니다", "ui.agent_chat_no_picture": "클립보드에 이미지가 없습니다", + "ui.agent_chat_node_too_old": "Node.js {version}은 이 에이전트에 사용하기에는 너무 오래된 버전입니다. Node.js 20.10 이상을 설치한 후 새로 고침을 누르세요.", "ui.agent_chat_none_found": "코딩 에이전트를 찾지 못했습니다. 다음 중 하나를 설치한 뒤 새로 고침을 누르세요:", "ui.agent_chat_none_found_short": "에이전트를 찾지 못함", "ui.agent_chat_not_installed": "설치되지 않음", @@ -2916,9 +3339,12 @@ "ui.agent_chat_queued_stopped": "대기 중 (중지됨, 보내지 않음)", "ui.agent_chat_refresh": "새로 고침", "ui.agent_chat_refused": "에이전트에게 허용되지 않음: {reason}", + "ui.agent_chat_reinstall": "{agent}이(가) 설치되어 있지만({program}) SolidCraft가 확인할 때 시작되지 않았습니다: {error}\n설치가 완료되지 않았거나 다른 종류의 컴퓨터용일 수 있습니다. `{install}`(으)로 다시 설치하고, 터미널에서 버전이 출력되는지 확인한 뒤 새로 고침을 누르세요.", "ui.agent_chat_remove": "대기열에서 제거", "ui.agent_chat_remove_file": "이 메시지에서 빼기", "ui.agent_chat_remove_imported": "이 메시지에서 빼기. 부품은 디자인에 남습니다 (실행 취소하면 제거됨)", + "ui.agent_chat_reply_cut_off": "응답이 끝나기 전에 길이 한도에 도달해 불완전할 수 있습니다. 에이전트에게 계속하거나 더 짧게 답하라고 요청하세요.", + "ui.agent_chat_reply_declined": "모델이 이 메시지에 대한 답변을 거절했습니다.", "ui.agent_chat_right": "오른쪽", "ui.agent_chat_save": "저장", "ui.agent_chat_send": "보내기", @@ -2926,7 +3352,7 @@ "ui.agent_chat_send_now_tip": "에이전트의 현재 단계를 중지하고 이것을 다음으로 보냅니다 (Ctrl+Enter)", "ui.agent_chat_setup_body": "SolidCraft는 이 컴퓨터에 설치된 코딩 에이전트와 통신합니다. 환경 설정 › AI에서 에이전트를 선택하세요.", "ui.agent_chat_setup_title": "어시스턴트 설정", - "ui.agent_chat_side": "에이전트 채팅 위치", + "ui.agent_chat_side": "채팅 도킹", "ui.agent_chat_signed_in": "로그인됨", "ui.agent_chat_state_auth": "로그인 필요", "ui.agent_chat_state_busy": "작업 중…", @@ -2943,7 +3369,7 @@ "ui.agent_chat_undone": "(취소됨)", "ui.agent_chat_view_attached": "뷰 첨부됨", "ui.agent_chat_waiting": "확인 대기 중", - "ui.agent_cursor": "에이전트 커서", + "ui.agent_cursor": "에이전트 포인터", "ui.agent_cursor_speed": "에이전트 커서 속도", "ui.agent_off_thread": "에이전트가 명령을 실행하는 동안 창 반응성 유지", "ui.agent_off_thread_note": "에이전트의 느린 명령(AI 패널 또는 MCP 클라이언트에서 실행)은 창과 별도로 계산됩니다. 뷰를 계속 회전하며 살펴볼 수 있고, 뷰의 칩에서 하나씩 중지할 수 있습니다. 끄면 각 명령이 창의 스레드에서 실행되며, 창은 명령이 끝날 때까지 기다립니다.", @@ -2972,23 +3398,28 @@ "ui.ai_copy_suffix": "복사본", "ui.ai_custom_url": "사용자 지정 URL", "ui.ai_default": "기본값", + "ui.ai_edit": "편집", + "ui.ai_edit_agent_title": "에이전트 편집", + "ui.ai_edit_gone": "이 에이전트는 제거되었으므로 저장할 내용이 없습니다.", + "ui.ai_edit_tip": "이 에이전트의 이름, 명령 또는 엔드포인트를 변경합니다. 저장된 키는 표시되지 않습니다.", "ui.ai_http_busy": "엔드포인트가 바쁘거나 한도에 도달했습니다. 나중에 다시 시도하세요", "ui.ai_http_key": "엔드포인트가 키를 거부했습니다. 환경 설정 > AI에서 확인하세요", "ui.ai_http_not_found": "엔드포인트나 모델을 찾을 수 없습니다. 기본 URL과 모델 이름을 확인하세요", "ui.ai_http_too_large": "대화가 이 엔드포인트에 비해 너무 큽니다. 새 채팅을 시작하세요", "ui.ai_key": "API 키", "ui.ai_key_hint": "선택 사항, 시스템 키체인에 저장", + "ui.ai_key_keep_hint": "저장된 키를 유지하려면 비워 두세요", "ui.ai_key_needs_https": "키는 HTTPS를 통해서만, 또는 이 컴퓨터로만 전송됩니다.", "ui.ai_key_note": "SolidCraft 설정이 아닌 시스템 키체인에 저장됩니다. 로컬 서버라면 비워 두세요.", "ui.ai_keychain_error": "시스템 키체인이 거부했습니다: {error}", - "ui.ai_mode_all": "모두 허용", + "ui.ai_mode_all": "모두 실행", "ui.ai_mode_all_note": "묻지 않고 실행합니다. 충돌 보고서는 계속 제외되고 폴더 제한도 그대로 적용됩니다.", "ui.ai_mode_all_warning": "에이전트가 묻지 않고 디자인을 저장, 덮어쓰기, 내보내기, 교체할 수 있습니다. 신뢰하는 에이전트와 저장된 디자인에서만 사용하세요.", - "ui.ai_mode_ask": "매번 묻기", + "ui.ai_mode_ask": "먼저 묻기", "ui.ai_mode_ask_note": "디자인의 모든 변경과 파일 작업이 사용자의 허용을 기다립니다.", - "ui.ai_mode_edits": "모델 편집 자동 허용", + "ui.ai_mode_edits": "편집 허용", "ui.ai_mode_edits_note": "모델링 명령은 묻지 않고 실행되며, 저장·열기·내보내기 등 파일 작업이나 파괴적인 작업은 계속 묻습니다.", - "ui.ai_mode_global": "위 설정 따름", + "ui.ai_mode_global": "위와 동일", "ui.ai_model": "모델", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "이 설정은 SolidCraft 도구에 적용됩니다. 에이전트 자체 도구(셸, 파일 편집)는 에이전트에 모드가 있을 때 채팅 패널 머리글에서 고르는 에이전트 자체 모드를 따릅니다.", @@ -3004,9 +3435,10 @@ "ui.ai_preset": "프리셋", "ui.ai_remove": "제거", "ui.ai_reset": "재설정", + "ui.ai_save": "저장", "ui.ai_settings": "AI 설정…", "ui.ai_show_features": "AI 기능 표시", - "ui.ai_show_features_note": "에이전트 채팅: 이미 사용 중인 코딩 에이전트나 선택한 모델 엔드포인트가 열린 디자인을 다루는 패널입니다. 끄면 AI 버튼, 단축키, 메뉴 항목, 패널이 없고 아무것도 찾거나 시작하지 않습니다.", + "ui.ai_show_features_note": "끄면 모든 곳에서 어시스턴트를 숨기고 아무것도 시작하지 않습니다. 아래 항목이 모두 흐려집니다.\n\n에이전트 채팅: 이미 사용 중인 코딩 에이전트나 선택한 모델 엔드포인트가 열린 디자인을 다루는 패널입니다. 끄면 AI 버튼, 단축키, 메뉴 항목, 패널이 없고 아무것도 찾거나 시작하지 않습니다.", "ui.ai_switch_tip": "이 대화의 에이전트 변경", "ui.ai_test": "테스트", "ui.ai_test_acp_ok": "응답: {agent}", @@ -3020,7 +3452,7 @@ "ui.ai_tool_running": "실행 중", "ui.ai_tool_unfold": "클릭하면 결과를 표시", "ui.ai_tool_waiting": "대기 중", - "ui.ai_toolbar_button": "도구 모음에 버튼 표시", + "ui.ai_toolbar_button": "애플리케이션 바의 어시스턴트 버튼", "ui.ai_toolbar_button_note": "도구 모음 오른쪽 끝의 AI 버튼. Ctrl+Shift+A와 보기 메뉴로도 패널을 열 수 있습니다.", "ui.ai_undo_tip": "이 메시지에서 에이전트가 바꾼 모든 것을 한 번에 실행 취소", "ui.ai_url_hint": "https://example.com/v1", @@ -3067,6 +3499,7 @@ "ui.circle": "원", "ui.circular_pattern": "원형 패턴", "ui.clear": "지우기", + "ui.clear_print_face": "출력 바닥면 해제", "ui.clear_recent": "최근 항목 지우기", "ui.clear_the_selection": "선택 해제", "ui.click_selects_whole_bodies": "클릭하면 바디 전체 선택", @@ -3091,10 +3524,16 @@ "ui.colour_vision_sample": "예시", "ui.colour_vision_tritan": "청색각이상 (Tritan)", "ui.colour_vision_tritan_tip": "파란색 감각이 약하거나 없는 경우", + "ui.comb_length": "빗 길이", + "ui.comb_length_tip": "빗살의 길이: 자동 길이의 배수입니다. 자동 길이에서는 가장 긴 빗살이 표시된 곡선 크기의 5분의 1이 됩니다.", + "ui.comb_teeth": "빗살 수", + "ui.comb_teeth_tip": "각 빗의 빗살 수이며, 곡선을 따라 같은 간격으로 놓입니다. 빗살이 많을수록 곡률이 어떻게 바뀌는지 더 자세히 보입니다.", "ui.combine": "결합", "ui.coming_later": "추후 지원 예정", "ui.command_done": "{command} 완료", "ui.command_palette_hint": "명령 입력(예: {example}) — 또는 S 키를 눌러 검색", + "ui.components_from_bodies_hint": "활성 구성요소 아래에 선택한 각 바디와 같은 이름의 구성요소를 만듭니다.", + "ui.components_from_bodies_required": "바디를 하나 이상 선택하세요.", "ui.concentric": "동심", "ui.cone": "원뿔", "ui.conic_curve": "원뿔 곡선", @@ -3107,15 +3546,30 @@ "ui.construction.contact_hint": "접선: 원/원호 또는 열린 스플라인/원뿔 곡선 선택 후 접점 선택 (자유 곡선은 끝점만)", "ui.construction.external_hint": "접선: 원 또는 원호, 외부 점, 원하는 해를 차례로 선택", "ui.construction.free_hint": "보조 직선: 두 점 클릭; 마우스 오른쪽 버튼으로 다시 시작", + "ui.construction.normal_needs_length": "무한 직선은 항상 보조선입니다. 일반 선을 그리려면 길이를 입력하세요", "ui.construction.point_hint": "보조 직선: 통과할 점 클릭", "ui.construction.reference_hint": "보조 직선: 직선 선택 후 점 선택; 마우스 오른쪽 버튼으로 참조 변경", "ui.construction.ribbon_label": "보조선", + "ui.construction.side_hint": "보조 직선: 선이 뻗어 나갈 쪽 클릭; 마우스 오른쪽 버튼으로 다시 시작", "ui.context_menu": "컨텍스트 메뉴", + "ui.continuity_crease": "꺾임", + "ui.continuity_curvature": "곡률", + "ui.continuity_curvature_change": "곡률 변화", + "ui.continuity_curvature_change_tip": "곡률 변화(G3): 이음매에서 곡률의 변화도 부드럽습니다.", + "ui.continuity_curvature_tip": "곡률 연속(G2): 반사가 꺾임 없이 이어집니다.", "ui.continuity_g0": "G0 꺾임", "ui.continuity_g1": "G1 접선", "ui.continuity_g2": "G2 곡률", "ui.continuity_gap": "틈", + "ui.continuity_position": "위치", + "ui.continuity_position_tip": "위치(G0): 면이 만나지만, 만나는 곳에 꺾임이 있습니다.", + "ui.continuity_smooth_curvature_change": "부드러운 곡률 변화", + "ui.continuity_smooth_curvature_change_tip": "부드러운 곡률 변화(G4): 이음매에서 곡률이 변하는 방식까지 부드럽게 이어집니다.", + "ui.continuity_tangent": "접선", + "ui.continuity_tangent_tip": "접선(G1): 꺾임은 없지만, 이음매에서 곡률이 급변합니다.", "ui.copy": "복사", + "ui.copy_details": "세부 정보 복사", + "ui.copy_details_tip": "찾아보거나 보고할 수 있도록 전체 메시지를 복사합니다.", "ui.corner": "코너", "ui.corners": "코너", "ui.counterbore": "카운터보어", @@ -3135,6 +3589,8 @@ "ui.dark": "어둡게", "ui.default_modelling_orientation": "기본 모델링 방향", "ui.delete": "삭제", + "ui.delete_select_first": "먼저 삭제할 항목을 선택하세요: 피처, 바디, 컴포넌트 또는 스케치 형상", + "ui.dependents_select_first": "먼저 종속 항목을 표시할 대상을 선택하세요", "ui.depth": "깊이", "ui.design": "디자인", "ui.design_properties.author": "작성자", @@ -3148,6 +3604,40 @@ "ui.design_properties.part_number": "부품 번호", "ui.design_properties.project": "프로젝트", "ui.design_properties.revision": "리비전", + "ui.details_access_caption": "선택한 방향에서 공구가 각 면에 도달할 수 있는지 표시합니다.", + "ui.details_angle": "각도", + "ui.details_continuity_caption": "선택한 이음부를 편집합니다. 다른 이음부는 각자의 설정을 유지합니다.", + "ui.details_continuity_stale": "이전 형상입니다. 이 이음부를 편집하거나 화면에 맞추려면 분석을 다시 실행하세요.", + "ui.details_copy_list": "목록 복사", + "ui.details_curvature": "곡률 공차", + "ui.details_curvature_caption": "각 면의 국소 곡률 반지름에 따라 색상이 표시됩니다.", + "ui.details_direction": "공구 방향", + "ui.details_draft_caption": "금형 분리 방향에 대한 각 면의 각도에 따라 색상이 표시됩니다.", + "ui.details_edit_seam": "이음부 편집", + "ui.details_fixture": "UI 구성 요소 예시 — 샘플 데이터만 표시", + "ui.details_fixture_caption": "설명용 값을 사용하는 UI 구성 요소 예시입니다. 모델의 분석 결과가 아닙니다.", + "ui.details_fixture_problem": "문제가 있는 결과 예시", + "ui.details_fixture_readout": "측정값 예시", + "ui.details_flip": "뒤집기", + "ui.details_gap": "간격", + "ui.details_hatch": "절단면 해칭", + "ui.details_jump": "곡률 불연속", + "ui.details_key": "범례", + "ui.details_offset": "오프셋", + "ui.details_plane": "평면", + "ui.details_pull": "금형 분리 방향", + "ui.details_radius": "반지름", + "ui.details_readout": "측정값", + "ui.details_samples": "샘플 수", + "ui.details_seam": "{body} · 모서리 {edge}", + "ui.details_settings": "설정", + "ui.details_sharp_gap": "날카로운 이음 또는 간격", + "ui.details_show_all": "전체 {count}개 표시", + "ui.details_smooth": "매끄러움", + "ui.details_stripes": "줄무늬", + "ui.details_target": "형상에 맞게 보기 조정", + "ui.details_worst_seams": "연속성이 가장 나쁜 이음부", + "ui.details_zebra_caption": "반사된 줄무늬는 면이 얼마나 매끄럽게 이어지는지 보여 줍니다.", "ui.diameter": "지름", "ui.dimension": "치수", "ui.direct_interaction": "직접 조작", @@ -3192,8 +3682,10 @@ "ui.edit_in_place_saved_elsewhere": "부품이 다른 파일에 저장되었습니다. 어셈블리는 여전히 {name}에 연결되어 있습니다", "ui.edit_in_place_wait": "디자인에서 실행 중인 작업이 끝날 때까지 기다리세요", "ui.edit_section_analysis": "단면 분석 편집", + "ui.edit_sketch_empty": "편집할 스케치가 없습니다", "ui.ellipse": "타원", "ui.emboss_wrap_note": "지원되는 원통에 접하는 직교 선 프로파일은 자동으로 감깁니다. 대상을 고르려면 벽을 선택하세요.", + "ui.end": "끝", "ui.end_radius": "끝 반지름", "ui.end_scale": "끝 배율", "ui.entities": "요소", @@ -3202,24 +3694,60 @@ "ui.equation_explicit": "명시적", "ui.equation_form": "형식", "ui.equation_note": "변수는 단위가 없는 수입니다. sin(t)는 라디안으로 읽습니다. 단위가 없는 결과는 디자인 단위입니다.", + "ui.equation_note_range": "변수는 범위와 같이 길이입니다. 길이 매개변수와 함께 쓸 수 있으며, sin()에는 길이로 나누어 넣습니다. 단위가 없는 결과는 디자인 단위로 읽습니다.", "ui.equation_parametric": "매개변수식", + "ui.equation_variable_unit": "변수에 범위의 단위 사용", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "등가 반지름", "ui.expand": "펼치기", + "ui.explode_needs_two_components": "분해 보기는 구성 요소를 서로 떼어 놓으므로 설계에 구성 요소가 두 개 이상 있어야 합니다(새 구성 요소, 설계 삽입 또는 바디로 구성 요소 만들기)", "ui.exportDxf": "DXF 내보내기…", "ui.export_ellipsis_keymap": "내보내기…", "ui.export_keymap_tip": "키, S 상자 즐겨찾기, 도구 모음을 파일로 내보내기", "ui.extend": "연장", "ui.extent_type": "범위 유형", "ui.extrude": "돌출", + "ui.extrude_auto_to_object_tip": "면, 꼭짓점 또는 평행 평면을 선택하면 범위가 객체까지로 전환됩니다.", "ui.factor": "배율", + "ui.fade": "페이드", + "ui.fade_length": "페이드 길이", "ui.feature_history": "피처 기록", "ui.feature_options": "피처 옵션", "ui.features": "피처", "ui.file": "파일", "ui.fillet": "필렛", + "ui.fillet_corner_ball": "볼", + "ui.fillet_corner_ball_tip": "굴러가는 볼의 구면 일부로, 각 라운드에 접합니다(G1).", + "ui.fillet_corner_curvature_tip": "곡률(G2): 부드러운 패치. 코너를 각 모서리를 따라 셋백만큼(입력하지 않으면 반지름의 {factor}배) 물려 패치로 채우므로, 반사가 꺾임 없이 지나갑니다.", + "ui.fillet_corner_needs_constant": "부드러운 패치 코너(G2)에는 일정한 반지름과 정확한 반지름 맞춤이 필요합니다.", + "ui.fillet_corner_patch": "부드러운 패치", + "ui.fillet_corner_patch_tip": "곡률 연속(G2): 코너를 각 모서리를 따라 물려 패치로 채우므로, 반사가 꺾임 없이 지나갑니다.", + "ui.fillet_corner_tangent_tip": "접선(G1): 굴러가는 볼 코너. 굴러가는 볼의 구면 일부로, 각 라운드에 접합니다.", + "ui.fillet_error_corner": "여기에서는 부드러운 코너를 만들 수 없었습니다. 다른 셋백이나 접선 코너를 시도해 보세요.", + "ui.fillet_error_failed": "이 모서리들에 이 필렛을 만들 수 없었습니다. 다른 반지름을 시도하거나 한 번에 둥글게 하는 모서리 수를 줄여 보세요.", + "ui.fillet_error_setback_short": "이 코너의 패치에 비해 셋백이 너무 짧습니다. {least}부터 만들 수 있습니다. 더 긴 셋백을 시도해 보세요.", + "ui.fillet_error_too_large": "이 모서리 옆의 면에 비해 반지름이 너무 큽니다. 더 작은 반지름을 시도하거나 '면 경계'를 '최대 반지름'으로 설정하세요.", + "ui.fillet_fit": "면 경계", + "ui.fillet_fit_exact": "정확한 반지름", + "ui.fillet_fit_needs_constant": "반지름 맞춤에는 일정한 반지름이 필요합니다.", + "ui.fillet_fit_reduce": "최대 반지름", + "ui.fillet_fit_taper": "좁힌 반지름", + "ui.fillet_fit_tip": "반지름이 모서리 옆 면이 허용하는 것보다 클 때.\n정확한 반지름: 지정한 반지름 그대로, 또는 둥글게 하지 않고 이유를 알리는 메시지.\n최대 반지름: 모든 모서리를 들어가는 가장 큰 반지름으로 둥글게 합니다.\n좁힌 반지름: 반지름을 유지하고 면이 모자란 곳에서만 라운드를 좁힙니다.", + "ui.fillet_options_tip": "접선 체인: 선택한 모서리에서 부드럽게 이어지는 모서리도 둥글게 합니다.\n미리 보기: 편집하는 동안 결과를 뷰에 표시합니다.", + "ui.fillet_setback": "셋백", + "ui.fillet_setback_hint": "{factor} × 반지름", + "ui.fillet_setback_least": "{least}보다 크게", + "ui.fillet_setback_tip": "부드러운 코너 패치가 시작되는 위치: 코너에서 각 모서리를 따른 거리. 기본값은 반지름의 {factor}배. 최소 셋백(셋백 없이 라운드가 만나는 곳, 면이 서로 직각이면 반지름)보다 커야 합니다.", + "ui.fillet_smooth_radius": "반지름 부드럽게 변화", + "ui.fillet_turn": "꺾임", + "ui.fillet_turn_mitre": "마이터", + "ui.fillet_turn_swept": "회전", + "ui.fillet_turn_tip": "두 라운드가 사이의 날카로운 코너 모서리를 돌아가는 곳(보스 밑동의 라운드가 세로 모서리를 도는 곳 등).\n마이터: 라운드가 계속 이어져 마이터로 만납니다.\n회전: 라운드가 코너 모서리에서 멈추고 그 둘레를 돕니다. 코너는 둘 모두에 접하는 토러스입니다. 반지름이 같은 라운드가 곧고 볼록한 코너 모서리를 돌 때만.", + "ui.fillet_type_choices_tip": "일정한 반지름: 모서리 전체에 하나의 반지름.\n현 길이: 면이 어떤 각도로 만나든 라운드의 폭이 같습니다.\n가변 반지름: 양 끝의 반지름과, 추가하면 모서리를 따라 더.\n곡률 연속: 평면과 만나는 곳에서 반사가 꺾이지 않는 단면(G2).\n스플라인: 모서리를 따라 반지름이 설정한 제어 반지름을 따릅니다.", + "ui.fillet_type_curvature": "곡률 연속", + "ui.fillet_type_tip": "모서리를 가로지르는 단면. 곡률 연속: 평면 사이의 곡률 연속(G2) 단면으로, 반사가 면에서 라운드로 꺾임 없이 이어집니다.", "ui.filter_commands_or_keys": "명령 또는 키 필터", "ui.findInTimeline": "타임라인에서 찾기", "ui.findInWindow": "창에서 찾기", @@ -3327,6 +3855,7 @@ "ui.hideOrigin": "원점 숨기기", "ui.hidePlanes": "평면 숨기기", "ui.hideProfile": "윤곽 숨기기", + "ui.hide_origin_by_default": "새 디자인에서 원점 폴더 숨기기", "ui.history_back": "한 단계 뒤로", "ui.history_below_browser": "브라우저 아래", "ui.history_edge_hint": "가장자리를 더블클릭", @@ -3358,6 +3887,7 @@ "ui.insert_design.saved_file": "{name}에 저장되지 않은 변경 사항이 있어 저장된 파일을 삽입했습니다. 저장한 다음 링크 업데이트로 변경 사항을 가져오세요.", "ui.insert_design.unsaved": "저장되지 않은 변경 사항", "ui.inspect": "검사", + "ui.instances": "인스턴스", "ui.intersect": "교차", "ui.isolate": "분리 표시", "ui.join": "접합", @@ -3366,12 +3896,14 @@ "ui.joints": "조인트", "ui.keyboard_shortcuts": "키보드 단축키", "ui.language": "언어", + "ui.lasso_select": "올가미(자유롭게 둘러 그리기: 완전히 안쪽에 있는 것을 선택)", "ui.layout_compact": "컴팩트", "ui.layout_floating": "플로팅", "ui.length": "길이", "ui.length_decimals": "길이 소수점 자릿수", "ui.light": "밝게", "ui.line": "선", + "ui.line_arc_hint": "접선 호: 호의 끝점을 클릭합니다. 선으로 돌아가려면 마지막 점에 다시 머무르고, 끝내려면 오른쪽 클릭 또는 Esc를 누릅니다", "ui.lock": "잠금", "ui.loft": "로프트", "ui.look_at": "바라보기", @@ -3413,6 +3945,7 @@ "ui.move": "이동", "ui.multiple": "다중", "ui.named_views": "명명된 뷰", + "ui.nav_bridge_tip": "장치의 내비게이션 브리지에 연결합니다. 요청하기 전에는 꺼져 있습니다. 3D 입력 장치 자체 프로그램(예: 직접 만든 3D 마우스 드라이버)이 뷰를 움직이며 마우스 포인터는 그대로 사용할 수 있습니다. 연결은 이 컴퓨터의 이 포트만 사용합니다.", "ui.navigation": "탐색", "ui.needs_design": "{command}: 먼저 디자인을 열어 주세요", "ui.newSketchGroup": "새 스케치 그룹", @@ -3450,7 +3983,9 @@ "ui.part_size_needs_a_part": "크기를 바꿀 삽입된 표준 부품(나사, 너트, 와셔 또는 핀)을 선택하십시오. 바디를 키우거나 줄이려면 축척을 사용하십시오.", "ui.part_size_shared": "부품을 다시 빌드하며 추가된 피처는 모두 대체됩니다. 이 구성요소의 모든 인스턴스가 업데이트됩니다.", "ui.paste": "붙여넣기", + "ui.patch_continuity_corner_tip": "패치는 각 변을 따라 주변 면과 선택한 연속성으로 이어집니다. 주변 면끼리 서로 다른 곡률로 만나는 모서리에서는 그곳에서 접선(G1)으로 유지됩니다.", "ui.path": "경로", + "ui.pattern_object_type_tip": "바디: 뷰나 브라우저에서 선택하는 솔리드 형상이며, 각각 통째로 복사됩니다.\n피처: 돌출이나 구멍 같은 기록의 단계이며, 기록에서 또는 그 단계가 만든 면에서 선택합니다. 그 단계가 반복됩니다.\n스케치는 둘 다 아닙니다. 곡선은 스케치 안의 패턴이나 대칭 복사로 반복하거나, 먼저 돌출하세요.", "ui.pattern_on_path": "경로 패턴", "ui.perpendicular": "수직", "ui.perspective_view": "원근 투영 뷰", @@ -3459,6 +3994,7 @@ "ui.pipe": "파이프", "ui.pitch": "피치", "ui.placement": "배치", + "ui.placement_handles_tip": "모델 위로 피처를 드래그하는 마커와 회전하는 링입니다.", "ui.plane": "평면", "ui.plane_at_angle": "각도 평면", "ui.plugins": "플러그인", @@ -3482,6 +4018,11 @@ "ui.polygon": "다각형", "ui.preferences": "환경 설정", "ui.press_a_key": "키를 누르세요…", + "ui.print_face_body_not_sent": "이 면의 바디는 보내지지 않습니다. 먼저 바디에 추가하십시오", + "ui.print_face_cleared": "{body}: 출력 바닥면을 해제했습니다", + "ui.print_face_input": "출력 바닥면", + "ui.print_face_pick": "솔리드 바디의 평면 하나를 선택하면 출력 바닥면이 됩니다", + "ui.print_face_set": "{body}: 출력 바닥면을 설정했습니다. 슬라이서로 보내면 이 면이 아래로 놓입니다", "ui.profile": "프로파일", "ui.profile_plane": "프로파일 평면", "ui.profiles": "프로파일", @@ -3498,6 +4039,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "측정 중…", + "ui.properties.measuring_bodies": "측정 중… 바디 {total}개 중 {done}개", "ui.properties.measuring_failed": "측정이 끝나기 전에 중단되었습니다.", "ui.properties.principal_axis": "주축 {number}", "ui.properties.principal_moments": "주관성 모멘트", @@ -3559,6 +4101,7 @@ "ui.selectOther": "기타 선택…", "ui.selectTangentChain": "접선 체인 선택", "ui.select_all": "모두 선택", + "ui.select_components_by_face": "구성요소 선택(면을 클릭하면 해당 구성요소 선택)", "ui.selection": "선택", "ui.selection_modifiers": "선택 보조 키", "ui.selection_shift_add_only": "Shift+클릭은 추가만 함", @@ -3601,6 +4144,7 @@ "ui.slice": "슬라이스", "ui.slicer": "슬라이서", "ui.slicer_delete_tip": "{program}\nDelete 키로 목록에서 제거", + "ui.slicer_single_instance_tip": "실행 중인 창에 파일을 불러오는 슬라이서용입니다.", "ui.slot": "슬롯", "ui.smooth": "부드럽게", "ui.smooth_wheel_zoom": "부드러운 휠 확대/축소", @@ -3616,6 +4160,8 @@ "ui.start": "시작", "ui.start_over": "처음부터 다시", "ui.start_page": "시작 페이지", + "ui.step_values": "화살표와 휠로 값 변경", + "ui.step_values_tip": "값 필드에서 위/아래 화살표와 휠로 숫자를 변경합니다.", "ui.stitch_tolerance_hint": "엄격", "ui.stretch": "늘이기", "ui.supersampling": "슈퍼샘플링 (SSAA)", @@ -3688,10 +4234,19 @@ "ui.view_centre": "뷰 중심", "ui.viewport_status_clear": "{name} 끄기", "ui.viewport_status_clear_hint": "{name} 끄기 · Esc", + "ui.viewport_status_edges": "모서리 {count}개", + "ui.viewport_status_from": "{direction} 방향에서", "ui.viewport_status_key": "{name} 범례 표시", "ui.viewport_status_minimum_radius": "최소 반지름", "ui.viewport_status_pairs": "{count}쌍", + "ui.viewport_status_section_hatch": "{setting} · 해칭", + "ui.viewport_status_section_plane": "현재 평면", + "ui.viewport_status_section_tilted": "기울어짐 · {offset}", "ui.viewport_status_stripes": "줄무늬 {count}개", + "ui.viewport_status_summary_clear": "모두 끄기", + "ui.viewport_status_summary_heading": "이 뷰에서", + "ui.viewport_status_summary_label": "{name} 외 {count}개 항목", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "테마 따르기", "ui.visual_shaded_hidden_edges": "음영 처리 및 숨겨진 모서리", "ui.visual_shaded_with_edges": "음영 처리 및 모서리", @@ -3722,11 +4277,13 @@ "update.available": "SolidCraft {version} 사용 가능", "update.button": "업데이트", "update.button_version": "{version}(으)로 업데이트", - "update.check_automatically": "업데이트 자동 확인", + "update.check_automatically": "시작 시 및 하루에 한 번 확인", + "update.check_for_updates": "업데이트 확인", "update.check_now": "지금 확인", + "update.check_unavailable": "이 설치에서는 업데이트를 확인할 수 없습니다.", "update.checking": "확인 중…", "update.copy": "복사", - "update.dmg_opened": "디스크 이미지를 확인하고 열었습니다: SolidCraft를 응용 프로그램 폴더로 끌어 기존 버전을 바꾼 뒤 SolidCraft를 다시 시작하세요.", + "update.dmg_opened": "디스크 이미지를 확인하고 열었습니다: SolidCraft를 종료하고, 새 SolidCraft를 응용 프로그램 폴더로 끌어 기존 버전을 바꾼 뒤 SolidCraft를 다시 여세요.", "update.download": "다운로드", "update.download_open": "다운로드 후 열기", "update.downloading": "다운로드 및 확인 중… {done} / {total} MB", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index 775cea4f4..9f63b34f1 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "PERMUKAAN GAUNAN", "BOUNDARY SURFACE": "PERMUKAAN SEMPADAN", "BROWSER": "PELAYAR", + "Back to the original order": "Kembali ke susunan asal", "Ball": "Bebola", "Bar": "Bar", "Base Center": "Pusat Tapak", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Reka bentuk dibuka atau disimpan ada di sini.", "Determined by To Object. Choose Angle to edit the angular extent.": "Ditentukan oleh tetapan Ke Objek. Pilih Sudut untuk mengubah julat sudut.", "Diameter": "Diameter", + "Did this assembly open the wrong way up?": "Adakah pemasangan ini dibuka dengan orientasi yang salah?", + "Did this part open the wrong way up?": "Adakah bahagian ini dibuka dengan orientasi yang salah?", "Dimension new shapes": "Dimensikan bentuk baharu", "Direction": "Arah", "Discard": "Buang", @@ -474,6 +477,7 @@ "Rectangular": "Segi empat tepat", "Rectangular Tube": "Tiub Segi Empat Tepat", "Reference face": "Muka rujukan", + "Reference plane": "Satah rujukan", "Relief Depth": "Kedalaman Pelepasan", "Relief Width": "Lebar Pelepasan", "Remove Tools": "Buang Alat", @@ -553,6 +557,7 @@ "Section": "Keratan", "Section (optional)": "Keratan (pilihan)", "Section position": "Kedudukan keratan", + "Sections": "Keratan", "Sections (one sketch each)": "Keratan (satu lakaran setiap satu)", "Select Other": "Pilih Yang Lain", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Pilih Lain: tahan butang kiri pada model tanpa bergerak (atau klik kanan › Pilih Lain…) untuk senarai objek di bawah kursor. Klik tempat sama untuk objek seterusnya. Klik dua kali butang tengah untuk ke Utama (Tetapan › Navigasi).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Lekap pada pusat muka dan tepi", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft tidak dapat menghantar laporan secara terus. Hantar di GitHub; tiada token diperlukan dalam aplikasi.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft ditutup sebelum reka bentuk disimpan. Buka simpanan automatik terakhirnya.", + "Sort A to Z": "Isih A hingga Z", + "Sort Z to A": "Isih Z hingga A", "Spacing 2 must be a non-zero number": "Selang 2 mestilah nombor bukan sifar", "Spacing must be a non-zero number": "Selang mestilah nombor bukan sifar", "Specialise": "Khususkan", @@ -601,6 +608,7 @@ "Square": "Segi empat sama", "Stand it up": "Tegakkan", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Tegakkan: suku putaran pada X, satu ciri Alih yang boleh dibatalkan.", + "Stand this assembly up?": "Tegakkan pemasangan ini?", "Stand this part up?": "Tegakkan bahagian ini?", "Start angle": "Sudut mula", "Start bulge": "Bonjolan permulaan", @@ -772,6 +780,8 @@ "at the face": "pada muka", "bom.group_children": "Sub-bahagian dalam baris bahagiannya", "browser.body_name": "Jasad{number}", + "browser.calibrate_click_a": "Klik imej untuk Titik A, atau taip koordinatnya.", + "browser.calibrate_click_b": "Klik imej untuk Titik B, atau taip koordinatnya.", "browser.calibrate_title": "Tentukur: {name}", "browser.capture_many": "{count} komponen telah dialihkan tetapi kedudukannya belum dirakam.", "browser.capture_note": "Rakam mengekalkan kedudukan baharu; Kembalikan memulihkannya.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (pautan hilang)", "browser.sketch_editing": "{name} (sedang disunting)", "browser.sketch_name": "Lakaran{number}", + "browser.sketches_to_parts_already_in_part": "sudah berada dalam bahagiannya", + "browser.sketches_to_parts_design_body": "pada jasad reka bentuk itu sendiri", + "browser.sketches_to_parts_moved": "{moved} lakaran dialihkan ke bahagian tempat lakaran itu berada", + "browser.sketches_to_parts_no_exact_attachment": "pada muka tanpa pautan yang tepat", + "browser.sketches_to_parts_not_on_face": "bukan pada muka sesuatu bahagian", + "browser.sketches_to_parts_part_missing": "bahagiannya sudah tiada", + "browser.sketches_to_parts_result": "{moved} lakaran dialihkan ke bahagian tempat lakaran itu berada; {stayed} kekal di tempatnya: {why}", "browser.units": "Unit: {units}", "cam.flat": "Muka rata", "cam.follower": "Pengikut", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Ambil Penampilan", "cmd.appearance_replace": "Gantikan Penampilan", "cmd.assembly_bom": "Senarai Bahan", + "cmd.assembly_mass_properties": "Sifat jisim", + "cmd.body.print_face": "Muka cetakan", "cmd.body_rename": "Tukar Nama Jasad", "cmd.browser_collapse_all": "Ringkaskan Semua", "cmd.browser_expand_all": "Kembangkan Semua", @@ -842,6 +861,7 @@ "cmd.component_extract": "Ekstrak ke Fail", "cmd.component_finish_edit": "Selesai Sunting", "cmd.component_from_bodies": "Cipta Komponen daripada Jasad", + "cmd.component_hide_history": "Sembunyikan Sejarah Komponen", "cmd.component_insert_design": "Sisip Reka Bentuk", "cmd.component_links": "Senarai Pautan", "cmd.component_list": "Senarai Komponen", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Alih Jasad ke Komponen", "cmd.component_move_features": "Alih Ciri ke Komponen", "cmd.component_move_sketches": "Alih Lakaran ke Komponen", + "cmd.component_move_sketches_to_parts": "Alihkan Lakaran ke Bahagian Masing-masing", "cmd.component_paste_from_design": "Tampal daripada Reka Bentuk Lain", "cmd.component_paste_new": "Tampal Baharu", "cmd.component_properties": "Sifat Fizikal Komponen", @@ -857,6 +878,7 @@ "cmd.component_rename": "Tukar Nama Komponen", "cmd.component_replace_with_link": "Gantikan dengan Pautan", "cmd.component_revert_position": "Kembalikan Kedudukan", + "cmd.component_show_history": "Papar Sejarah Komponen", "cmd.component_unlock": "Buka Kunci Kandungan", "cmd.component_update_links": "Kemas Kini Pautan", "cmd.config_activate": "Aktifkan Konfigurasi", @@ -867,6 +889,7 @@ "cmd.config_rule": "Peraturan Konfigurasi", "cmd.config_rules": "Peraturan Konfigurasi", "cmd.config_table": "Paparkan Jadual Konfigurasi", + "cmd.construct.plane.axis_point": "Satah Melalui Paksi dan Titik", "cmd.construct_axis_edge": "Paksi Melalui Tepi", "cmd.construct_axis_normal_to_face": "Paksi Serenjang dengan Muka", "cmd.construct_axis_through_cylinder": "Paksi Melalui Silinder/Kon/Torus", @@ -915,6 +938,11 @@ "cmd.explode_show": "Papar Pandangan Terlerai", "cmd.expr_evaluate": "Nilaikan Ungkapan", "cmd.face_delete": "Padam Muka", + "cmd.file.export_3mf": "Eksport 3MF", + "cmd.file.export_obj": "Eksport OBJ", + "cmd.file.export_step": "Eksport STEP", + "cmd.file.export_stl": "Eksport STL", + "cmd.file.export_urdf": "Eksport URDF", "cmd.file_export": "Eksport", "cmd.file_insert_mesh": "Sisip Mesh", "cmd.file_insert_step": "Sisip STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Aktifkan Warna Komponen", "cmd.inspect_colored_components_disable": "Nyahaktifkan Warna Komponen", "cmd.inspect_compare": "Bandingkan Jasad", + "cmd.inspect_compare_picture": "Banding dengan Imej", "cmd.inspect_continuity": "Analisis Keselanjaran", "cmd.inspect_curvature_comb": "Analisis Sisir Kelengkungan", "cmd.inspect_curvature_map": "Analisis Peta Kelengkungan", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Sunting Awan Titik", "cmd.pointcloud_insert": "Sisip Awan Titik", "cmd.pointcloud_list": "Awan Titik", + "cmd.render.compare.divider": "Alih Pembahagi Perbandingan Render", + "cmd.render.result.discard": "Buang Hasil Render", + "cmd.render.result.select": "Pilih Hasil Render", "cmd.render_aging_describe": "Penuaan Permukaan Berlapis", "cmd.render_backends": "Enjin Render", "cmd.render_batch": "Render Semua Syot", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Splin Titik Kawalan (Darjah 5)", "cmd.sketch_spline_fit_point": "Splin Titik Padanan", "cmd.sketch_spline_insert_point": "Tambah Titik Splin", + "cmd.sketch_spline_remove_point": "Buang Titik Splin", "cmd.sketch_spline_reverse": "Songsangkan Arah Splin", "cmd.sketch_spun_profile": "Profil Putaran", "cmd.sketch_toggle_diameter": "Togol Jejari / Diameter", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Alih Penanda Garis Masa", "cmd.timeline_stop": "Hentikan Main Sejarah", "cmd.timeline_suppress": "Nyahaktifkan Ciri", + "cmd.ui.assistant": "Togol Pembantu", "cmd.view.render_browser": "Pelayar Render", "cmd.view.render_dock": "Alih Dok Render", "cmd.view.render_focus": "Pandangan Fokus Render", + "cmd.view.status_details": "Butiran Status Tetingkap Pandangan", "cmd.view.status_items": "Item Status Tetingkap Pandangan", "cmd.view_ambient_occlusion": "Oklusi Ambien", "cmd.view_angle_readout": "Sudut Pandangan", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Alat navigasi", "cmd.view_top": "Pandangan Atas", "cmd.view_visual_style": "Gaya visual", + "color.blue": "Biru", "color.copy": "Klik untuk menyalin nilai warna", "color.edit": "Klik untuk menyunting warna", "color.gamma": "Memaparkan nilai warna dalam ruang gamma 0-255", + "color.green": "Hijau", "color.hex": "Heks", "color.hex_help": "Masukkan #rrggbb atau #rrggbbaa; enam digit mengekalkan kelegapan", "color.hex_hint": "#rrggbb", "color.hue": "Rona", "color.linear": "Memaparkan nilai warna dalam ruang linear 0-1", + "color.recent": "Warna terkini", + "color.recent_help": "Warna yang anda pilih dalam mana-mana medan warna dipaparkan di sini", + "color.red": "Merah", + "color.saturation": "Ketepuan (peratus)", "color.saturation_value": "Ketepuan dan nilai", "color.selected": "Warna dipilih", + "color.step_down": "Turunkan", + "color.step_up": "Naikkan", + "color.value": "Nilai, iaitu kecerahan (peratus)", "config.column_filter_empty": "Tiada lajur yang sepadan", + "config.rule_parameter_columns": "Hanya parameter yang mempunyai lajur dalam jadual disenaraikan. Tambah satu dengan Tambah Lajur (+) untuk menggunakannya di sini.", + "config.rule_suppression_columns": "Hanya ciri yang mempunyai lajur Nyahaktifkan dalam jadual disenaraikan. Tambah satu dengan Tambah Lajur (+) untuk mengawalnya di sini.", "contact.components_count": "{count} komponen", "contact.enabled_label": "diaktifkan", "coupling.gear_1": "Gear 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Klik dimensi pemacu lain untuk menyisip namanya", "dialog.dimension_name": "Dimensi: {name}", "dialog.edit_title": "SUNTING {title}", + "dialog.no_shown_body": "Tiada jasad dipaparkan untuk diubah: paparkan satu, atau pilih Jasad Baharu", + "dialog.pattern_sketch_not_object": "Pilih jasad atau ciri: lakaran bukan kedua-duanya. Ulang lengkungnya dengan Corak atau Cermin milik lakaran itu sendiri, atau semperit dahulu.", "dialog.select": "↖ Pilih", "dialog.selected_count": "↖ {count} dipilih", + "dialog.selection_constraint": "Kekangan {id}", + "dialog.selection_external_curve": "{sketch} · lengkung {id}", "dialog.selection_guidance": "Pilih input untuk diubah. Klik objek dipilih untuk nyahpilih; Ctrl/Cmd+klik juga menogol pilihan. Semak pratonton, kemudian tekan OK.", + "dialog.selection_midpoint": "Titik tengah · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} daripada {total}: Pilih {input}", "dialog.step": "Langkah", "document.changed_on_disk": "{name} berubah pada cakera", @@ -1380,26 +1432,244 @@ "from the rule": "daripada peraturan", "help.apache": "Lesen Apache 2.0", "help.appearance.assign": "Memberikan warna atau rupa bahan kepada jasad, muka atau komponen yang dipilih, tanpa mengubah beratnya. Gunakan untuk membezakan bahagian atau melihat pratonton kemasan.", + "help.assembly.bom": "Menyenaraikan bahagian reka bentuk atau komponen beserta kuantitinya, mengikut nombor bahagian, dan boleh menyimpan senarai itu sebagai CSV atau JSON. Gunakan sebagai senarai bahagian untuk pesanan dan pemasangan.", "help.attributions": "Atribusi (ATTRIBUTION.md)", "help.build": "Versi {version} · commit {commit} · dibina {date}", + "help.canvas.decal": "Meletakkan imej pada muka rata model, seperti pelekat. Gunakan untuk memaparkan label, logo atau corak bercetak pada sesuatu bahagian.", + "help.canvas.edit": "Mengubah kanvas: kedudukan, saiz, sudut, kelegapan, pencerminan, keterlihatan atau namanya. Gunakan untuk menjajarkan imej rujukan dengan lakaran yang anda surih.", + "help.canvas.insert": "Meletakkan imej PNG atau JPEG pada satah atau muka sebagai rujukan lut sinar. Gunakan untuk menyurih foto atau lukisan dalam lakaran, dengan imej berskala pada saiz yang diketahui.", + "help.component.break_link": "Memutuskan komponen terpaut daripada fail reka bentuknya dan mengekalkan jasadnya seperti sedia ada. Gunakan apabila bahagian itu tidak lagi perlu mengikut perubahan pada fail asal.", + "help.component.capture_position": "Menyimpan kedudukan bahagian yang anda alihkan dengan tangan, supaya kedudukan itu menjadi tempat bahagian tersebut. Gunakan selepas menyeret bahagian ke tempatnya yang tidak dipegang oleh sendi.", + "help.component.create": "Menambah komponen baharu yang kosong ke dalam reka bentuk, di dalam komponen aktif melainkan anda memilih induk lain. Gunakan untuk memberi bahagian baharu pemasangan tempatnya sendiri bagi jasad dan lakaran.", "help.component.finish_edit": "Menyimpan bahagian yang sedang anda sunting di tempat, kembali ke pemasangannya dan mengemas kini pemasangan daripadanya. Gunakannya apabila perubahan anda pada bahagian terpaut sudah selesai.", + "help.component.from_bodies": "Menjadikan setiap jasad yang dipilih sebagai komponen tersendiri, dinamakan sempena jasad itu. Gunakan apabila reka bentuk yang dibina daripada jasad berasingan patut menjadi pemasangan yang bahagiannya boleh disambung dan digerakkan.", + "help.component.insert_design": "Menyisip reka bentuk tersimpan lain sebagai komponen yang dipautkan ke failnya, dengan jasad pepejalnya diletakkan seperti dalam fail itu. Gunakan untuk menggunakan semula bahagian dalam pemasangan dan menerima perubahan kemudian dengan Kemas Kini Pautan.", + "help.component.properties": "Memaparkan isi padu, jisim, pusat jisim dan momen inersia sesebuah komponen, menggunakan bahan jasadnya. Gunakan untuk menyemak berat dan keseimbangan pemasangan.", + "help.component.revert_position": "Mengembalikan bahagian yang anda alihkan dengan tangan ke tempat asalnya, dengan membuang pergerakan yang tidak dirakam. Gunakan untuk membuat asal pergerakan percubaan dalam pemasangan.", + "help.component.update_links": "Membaca semula fail reka bentuk terpaut dan menggantikan jasad yang telah berubah. Gunakan selepas menyunting bahagian yang digunakan oleh pemasangan ini.", + "help.config.configure": "Menambah parameter, ciri, bahan atau penampilan sebagai lajur jadual konfigurasi. Gunakan untuk membina varian satu reka bentuk, seperti pelbagai saiz sesuatu bahagian.", + "help.config.preview": "Menyemak bahawa satu baris jadual konfigurasi dapat dibina semula, tanpa mengubah reka bentuk atau sejarahnya. Gunakan sebelum bertukar kepada varian yang anda tidak pasti.", + "help.config.rules": "Memaparkan peraturan jadual konfigurasi, barisnya dan baris yang aktif. Gunakan untuk melihat cara varian sesuatu reka bentuk disediakan.", + "help.config.table": "Memaparkan jadual konfigurasi: satu baris bagi setiap varian, satu lajur bagi setiap parameter atau ciri, dan sama ada reka bentuk masih sepadan dengan baris aktif. Gunakan untuk menyemak varian sesuatu reka bentuk.", "help.connect_note": "Mulakan semula setiap pembantu untuk memuatkan pelayan SolidCraft. Setiap fail telah disandarkan sebagai .bak sebelum diubah.", "help.connect_title": "Sambungkan pembantu AI", + "help.construct.axis.edge": "Mencipta paksi binaan sepanjang tepi lurus atau garis lakaran. Gunakan sebagai paksi untuk Putar, corak membulat atau sendi.", + "help.construct.axis.normal_to_face": "Mencipta paksi binaan melalui satu titik, serenjang dengan muka. Gunakan sebagai paksi yang tegak keluar dari permukaan.", + "help.construct.axis.through_cylinder": "Mencipta paksi binaan melalui pusat muka silinder, kon atau torus, atau tepi bulat. Gunakan untuk memutar atau mencorak ciri di sekeliling bahagian bulat.", + "help.construct.axis.two_planes": "Mencipta paksi binaan di tempat dua satah atau muka rata bertemu. Gunakan apabila paksi yang diperlukan ialah garis antara dua muka.", + "help.construct.axis.two_points": "Mencipta paksi binaan melalui dua titik, bucu atau titik lakaran. Gunakan untuk paksi yang menghubungkan dua kedudukan yang diketahui.", + "help.construct.plane.along_path": "Mencipta satah binaan yang serenjang dengan tepi atau lengkung, pada satu kedudukan sepanjangnya. Gunakan untuk melakar profil bagi Sapu atau keratan sesuatu laluan.", + "help.construct.plane.at_angle": "Mencipta satah binaan yang dipusingkan pada satu sudut daripada satah atau muka, pada paksi atau tepi. Gunakan untuk lakaran condong, seperti braket bersudut.", + "help.construct.plane.axis_point": "Mencipta satah binaan yang mengandungi satu paksi dan satu titik di luar paksi itu. Pilih titik asal atau paksi binaan, tepi lurus atau garis lakaran, kemudian bucu, titik lakaran atau titik binaan. Titik pada paksi tidak dapat menentukan satu satah yang unik.", + "help.construct.plane.midplane": "Mencipta satah binaan di tengah-tengah antara dua satah atau muka rata, atau yang membahagi dua kedua-duanya di tempat ia bertemu pada satu sudut. Gunakan sebagai satah simetri untuk pencerminan.", + "help.construct.plane.offset": "Mencipta satah binaan yang selari dengan satah atau muka rata, pada satu jarak atau melalui satu titik. Gunakan untuk melakar pada ketinggian tertentu di atas sesuatu muka.", + "help.construct.plane.perpendicular": "Mencipta satah binaan yang memuatkan garis atau tepi dan berdiri serenjang dengan satah atau muka. Gunakan untuk melakar secara tegak pada model sepanjang tepi.", + "help.construct.plane.tangent": "Mencipta satah binaan yang menyentuh silinder, kon, sfera atau torus pada satu titik. Gunakan untuk melakar pada sisi bahagian bulat.", + "help.construct.plane.three_points": "Mencipta satah binaan melalui tiga titik. Gunakan untuk satah yang ditentukan oleh kedudukan pada model, seperti tiga bucu.", + "help.construct.plane.two_edges": "Mencipta satah binaan melalui dua tepi atau garis lurus yang terletak pada satu satah. Gunakan untuk satah merentasi sesuatu bahagian, seperti melalui dua tepi yang bertentangan.", + "help.construct.point.along_path": "Mencipta titik binaan pada satu kedudukan sepanjang tepi atau lengkung. Gunakan sebagai rujukan di pertengahan laluan.", + "help.construct.point.center": "Mencipta titik binaan di pusat tepi bulat, bulatan atau lengkok lakaran, sfera atau torus. Gunakan sebagai rujukan untuk lubang, paksi dan sendi.", + "help.construct.point.edge_plane": "Mencipta titik binaan di tempat tepi atau garis melalui satah atau muka rata. Gunakan untuk menandakan tempat laluan merentasi satah.", + "help.construct.point.three_planes": "Mencipta titik binaan di tempat tiga satah atau muka rata bertemu. Gunakan sebagai rujukan sudut, walaupun model tiada bucu di situ.", + "help.construct.point.two_edges": "Mencipta titik binaan di tempat dua tepi atau garis bertemu, atau paling hampir antara satu sama lain. Gunakan sebagai rujukan pada sudut maya.", + "help.construct.point.vertex": "Mencipta titik binaan pada bucu atau titik lakaran. Gunakan sebagai rujukan yang kekal apabila lakaran atau jasad di sekelilingnya disembunyikan.", + "help.contact.check": "Menyenaraikan pasangan bahagian dalam set sentuhan yang menembusi satu sama lain pada kedudukan semasa. Gunakan untuk mencari perlanggaran sebelum anda menggerakkan sendi atau menjalankan kajian gerakan.", + "help.contact.create": "Mengumpulkan dua atau lebih bahagian ke dalam satu set sentuhan, yang jasadnya dihalang daripada menembusi satu sama lain semasa sendi bergerak. Gunakan untuk bahagian yang patut berhenti apabila bersentuhan, seperti tuil terhadap penahannya.", + "help.contact.disable_all": "Mematikan sentuhan, supaya sendi yang digerakkan dan kajian gerakan tidak lagi berhenti di tempat bahagian bersentuhan. Gunakan untuk menggerakkan bahagian dengan bebas semula, atau untuk memastikan pemasangan besar kekal responsif.", + "help.contact.edit": "Mengubah set sentuhan: bahagian yang dipegangnya, namanya, atau sama ada ia dinyahaktifkan; ia juga boleh memadam set itu. Gunakan untuk melaraskan bahagian mana yang dihalang daripada menembusi satu sama lain.", + "help.contact.enable_all": "Memasukkan setiap bahagian pemasangan ke dalam satu set sentuhan, supaya tiada dua bahagian dapat menembusi satu sama lain semasa sendi bergerak. Gunakan untuk semakan pantas seluruh mekanisme.", + "help.contact.enable_sets": "Mengaktifkan sentuhan bagi set sentuhan yang anda takrifkan, supaya sendi yang digerakkan dan kajian gerakan berhenti di tempat bahagiannya akan menembusi satu sama lain. Gunakan untuk memulihkan set anda selepas mematikan sentuhan.", + "help.contact.list": "Menyenaraikan set sentuhan dalam reka bentuk, bahagian dalam setiap satu dan sama ada sentuhan diaktifkan. Gunakan untuk menyemak cara sentuhan disediakan sebelum anda menggerakkan pemasangan.", + "help.document.inspect": "Memaparkan gambaran keseluruhan reka bentuk: komponen, jasad, lakaran, ciri dan parameternya. Gunakan untuk memahami reka bentuk yang bukan anda bina sendiri.", + "help.document.units": "Menukar unit yang digunakan reka bentuk untuk memaparkan panjang, seperti mm atau inci. Geometri kekal bersaiz sama; hanya paparan dan nombor biasa yang mengikutinya.", + "help.edit.checkpoint": "Mengingati reka bentuk, lakaran aktif dan sejarah Buat Asal seperti keadaan sekarang. Gunakan sebelum mencuba sesuatu yang berisiko dan mungkin hendak anda kembali daripadanya.", + "help.edit.restore_checkpoint": "Kembali ke titik semak, termasuk sejarah Buat Asal. Gunakan untuk membuang semua yang dilakukan sejak titik semak dalam satu langkah.", + "help.explode.create": "Mencipta pandangan terlerai yang menolak bahagian menjauhi pusat pemasangan, atau mengikut pergerakan yang anda tetapkan. Gunakan untuk menunjukkan cara pemasangan disatukan, bagi arahan atau pembentangan.", "help.face.delete": "Membuang muka yang dipilih dan membiarkan muka bersebelahan menutup ruang kosong itu, atau membiarkannya terbuka sebagai permukaan. Gunakan untuk menanggalkan tepi bulat, lubang atau bonggol yang menghalang.", + "help.file.insert_mesh": "Menambah fail 3MF, STL, OBJ, PLY atau glTF ke dalam reka bentuk sebagai jasad mesh dalam komponen baharu. Gunakan untuk meletakkan model yang dimuat turun atau diimbas di sebelah reka bentuk anda sebagai rujukan.", + "help.file.insert_step": "Menambah fail STEP, IGES, FreeCAD atau Rhino ke dalam reka bentuk sebagai jasad pepejal dalam komponen baharu; bahagian pemasangan menjadi komponen bersarang. Gunakan untuk membawa masuk model daripada pembekal atau program CAD lain.", + "help.file.save_mesh": "Menyimpan jasad sebagai mesh STL, 3MF atau OBJ, dengan kehalusan muka melengkung yang anda pilih. Gunakan untuk menyediakan bahagian bagi pencetakan 3D atau program yang membaca mesh.", + "help.file.send_to_slicer": "Menyimpan jasad yang dipilih sebagai fail 3MF dan membukanya dalam penghiris yang anda pilih. Gunakan untuk beralih daripada model kepada pencetakan dalam satu langkah.", "help.font_details": "Antara muka menggunakan fon terbina dalam egui (Ubuntu Light dan Hack, di bawah Lesen Fon Ubuntu dan lesen MIT/Bitstream Vera; Noto Emoji dan fon ikon emoji, di bawah OFL dan MIT). Teks lakaran menggunakan Liberation Sans (SIL OFL 1.1). Pek fon pilihan Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), tidak disertakan dalam binaan SolidCraft.", "help.fonts": "Fon", + "help.frame.member": "Meletakkan profil, seperti tiub atau aluminium tersemperit, sepanjang garis lakaran rangka, satu anggota bagi setiap garis. Gunakan untuk membina rangka, rak dan struktur kimpalan.", + "help.inspect.accessibility": "Mewarnakan muka yang dapat dicapai oleh alat dari satu arah, dan yang tidak dapat dicapai. Gunakan untuk menyemak bahagian bagi pemesinan atau pengacuanan dari sisi itu.", + "help.inspect.center_of_mass": "Memaparkan pusat jisim jasad, setiap satu secara berasingan dan semuanya bersama, pada ketumpatan seragam. Gunakan untuk menyemak keseimbangan dan tempat bahagian akan terbalik.", + "help.inspect.colored_components": "Memberi setiap komponen warna sementaranya sendiri, tanpa mengubah penampilan. Gunakan untuk membezakan bahagian pemasangan dengan sekilas pandang.", + "help.inspect.compare": "Membandingkan dua jasad dan menunjukkan di mana satu mempunyai bahan yang tiada pada yang lain, dengan isi padu dan sisihan. Gunakan untuk menyemak bahagian yang diubah atau diimport dengan yang asal.", + "help.inspect.continuity": "Menyemak kehalusan pertemuan muka di sepanjang tepinya: sela, patahan atau lonjakan kelengkungan, dan mewarnakan sambungannya. Gunakan untuk mencari tempat permukaan tidak bercantum dengan kemas.", + "help.inspect.curvature_comb": "Melukis sisir di sepanjang lengkung, tepi atau muka yang giginya menunjukkan sekuat mana ia melengkung. Gunakan untuk mengesan tempat rata, patahan dan kelengkungan yang tidak sekata.", + "help.inspect.curvature_map": "Mewarnakan muka mengikut sekuat mana ia melengkung, merah di tempat jejari kecil. Gunakan untuk mencari tempat yang sempit dan menilai kehalusan sesuatu permukaan.", + "help.inspect.draft": "Mewarnakan muka mengikut sudut draf terhadap arah tarikan, dan menandakan yang sudutnya terlalu kecil. Gunakan untuk menyemak bahagian sebelum pengacuanan atau penuangan.", + "help.inspect.environment_map": "Memaparkan model dengan kemasan memantul seperti cermin. Gunakan untuk menilai aliran permukaan melalui cara pantulan melintasinya.", + "help.inspect.interference": "Mencari jasad yang bertindih dan menunjukkan setiap pertindihan dengan isi padunya. Gunakan untuk menyemak pemasangan bagi bahagian yang berlanggar.", + "help.inspect.isocurve": "Melukis lengkung isoparametrik pada muka, iaitu grid tempat permukaan dibina. Gunakan untuk melihat aliran permukaan dan tempat ia terkumpul.", + "help.inspect.measure": "Mengukur panjang, jarak, sudut, luas dan jejari antara apa yang anda pilih, atau isi padu dan jisim jasad. Gunakan untuk menyemak saiz dan kelegaan.", + "help.inspect.minimum_radius": "Mencari jejari kelengkungan terkecil bagi lengkung, tepi atau muka, dan tempatnya. Gunakan untuk menyemak bahawa alat atau muncung dapat mengikuti bentuk itu.", + "help.inspect.section": "Membelah pandangan di sepanjang satah dan melorek muka yang dipotong, tanpa mengubah model. Gunakan untuk melihat ke dalam bahagian dan pemasangan.", + "help.inspect.zebra": "Memaparkan jalur hitam dan putih yang memantul pada muka model. Gunakan untuk menilai kehalusan: jalur yang putus atau patah di tepi menunjukkan peralihan yang kurang baik.", + "help.joint.as_built": "Menyambung dua bahagian di tempat ia berada, tanpa menggerakkan mana-mana satu, dan menetapkan cara ia masih boleh bergerak. Gunakan untuk bahagian yang sudah anda letakkan pada kedudukan akhirnya.", + "help.joint.cam": "Memaut sesondol yang berputar kepada pengikut, supaya pengikut menggelongsor atau berayun apabila garis luar sesondol melaluinya. Gunakan untuk sesondol, eksentrik dan pemacu injap.", + "help.joint.create": "Menyambung dua bahagian pada titik asal sendi yang anda pilih dan menggerakkan bahagian kedua ke tempatnya; jenis sendi menentukan cara ia masih boleh bergerak. Gunakan untuk membina pemasangan yang bahagiannya bergerak seperti mekanisme sebenar.", + "help.joint.drive": "Menetapkan sudut atau jarak sesebuah sendi dan menggerakkan bahagian bersamanya, dalam had sendi itu; sendi terpaut dan gelung tertutup turut mengikut. Gunakan untuk menyemak bahawa mekanisme bergerak seperti yang dimaksudkan.", + "help.joint.gear": "Memaut dua sendi berputar dengan nisbah gear, supaya menggerakkan satu akan memutar yang lain. Gunakan untuk gear taji dan gear dalaman, dengan nisbah daripada jejari pic atau bilangan gigi.", + "help.joint.limits": "Menetapkan sejauh mana sendi boleh berputar atau menggelongsor, sebagai minimum dan maksimum, atau mengosongkan had itu. Gunakan untuk memastikan engsel, gelangsar atau tuil kekal dalam julat pergerakan sebenarnya.", + "help.joint.motion_link": "Memaut dua sendi dengan nisbah dan ofset, supaya menggerakkan satu akan menggerakkan yang lain. Gunakan untuk hubungan tetap antara sendi yang tidak diliputi oleh Gear, Rak dan Pinan atau Skru.", + "help.joint.origin": "Meletakkan titik asal sendi bernama pada sesuatu bahagian: di pusat muka atau hujung bulat, tengah tepi, sudut atau satu titik. Gunakan untuk menyediakan tempat sendi melekat; titik asal yang dipilih pada muka mengikutinya apabila saiz bahagian berubah.", + "help.joint.rack_pinion": "Memaut pinan berputar kepada rak menggelongsor, supaya rak bergerak sepanjang bulatan pic yang digelek oleh pinan. Gunakan untuk pemacu rak, stereng dan pentas linear.", + "help.joint.reach": "Menggerakkan satu titik pada bahagian ke arah sasaran dengan mengubah sendi pada rantaiannya, dalam had sendi itu. Gunakan untuk melaraskan mekanisme mengikut kedudukan hujungnya, seperti hujung lengan robot.", + "help.joint.rigid_group": "Mengunci bahagian yang dipilih bersama seperti sedia ada, supaya ia bergerak sebagai satu. Gunakan untuk bahagian yang bersatu dan tiada gerakan antara satu sama lain.", + "help.joint.screw": "Memaut putaran dan gelongsoran melalui pic, supaya setiap pusingan menggerakkan jarak itu. Gunakan untuk skru pemacu, bolt dan gelendong berbebenang.", + "help.library.apply": "Menggunakan bahan atau penampilan daripada fail koleksi setempat pada jasad, muka atau komponen. Gunakan untuk menggunakan semula bahan yang anda simpan daripada reka bentuk lain.", + "help.library.export": "Menyimpan bahan dan penampilan reka bentuk ke fail koleksi. Gunakan untuk berkongsinya atau menggunakannya semula dalam reka bentuk lain.", + "help.library.inspect": "Menyemak fail koleksi dan menyenaraikan bahan dan penampilannya, tanpa mengubah reka bentuk. Gunakan untuk melihat kandungan koleksi sebelum menggunakannya.", "help.licences": "Lesen", "help.material.assign": "Menetapkan bahan jasad yang dipilih, seperti keluli, aluminium atau ABS. Gunakan supaya jisim dan berat sepadan dengan bahagian sebenar.", + "help.material.properties.validate": "Menyemak kad data bahan untuk nombor yang konsisten dan nilai yang hilang. Gunakan sebelum bergantung pada data itu untuk jisim atau kekakuan.", + "help.mesh.convert": "Membina semula jasad mesh, seperti STL, sebagai pepejal boleh sunting dengan muka rata dan silinder. Gunakan untuk mengubah suai bahagian mekanikal yang diimport seperti jasad yang dimodelkan.", "help.mit": "Lesen MIT", + "help.motion.study": "Menetapkan nilai sendi pada beberapa langkah sepanjang garis masa dan memainkannya semula sebagai animasi. Gunakan untuk menonton mekanisme bergerak melalui satu urutan dan menyemak kelegaan sepanjangnya.", + "help.motion.trace": "Menjejak laluan yang diikuti satu titik pada bahagian semasa kajian gerakan dimainkan atau sendi digerakkan, dan menyimpannya sebagai lengkung lakaran 3D apabila anda mengesahkan. Gunakan untuk melihat sejauh mana mekanisme mencapai, atau untuk membina berdasarkan laluannya.", "help.notice": "NOTIS", + "help.occurrence.ground": "Menetapkan bahagian pada tempatnya, atau membebaskannya semula, supaya sendi menggerakkan bahagian lain di sekelilingnya. Gunakan untuk rangka atau tapak yang menjadi asas seluruh pemasangan.", "help.occurrence.move": "Mengalihkan bahagian pemasangan hanya mengikut kebebasan yang dibenarkan oleh sendinya. Pilih muka bahagian, kemudian seret anak panah atau lengkok yang tersedia.", "help.parameters.change": "Membuka jadual nilai dan ungkapan bernama yang memacu dimensi reka bentuk. Gunakan untuk menukar saiz di satu tempat dan membiarkan setiap ciri yang menggunakannya mengikut.", + "help.parameters.export": "Menyimpan parameter reka bentuk sebagai CSV atau JSON. Gunakan untuk menyuntingnya dalam hamparan atau memindahkannya ke reka bentuk lain.", + "help.parameters.graph": "Menunjukkan parameter dan ciri mana yang menggunakan yang mana, dan sebarang gelung atau ralat di antaranya. Gunakan untuk melihat apa yang akan terjejas oleh perubahan pada sesuatu parameter.", + "help.parameters.import": "Membaca parameter daripada CSV atau JSON ke dalam reka bentuk, semuanya atau tiada satu pun. Gunakan untuk membawa masuk nilai daripada hamparan atau reka bentuk lain.", + "help.parameters.move": "Mengalihkan parameter pengguna sebelum atau selepas parameter lain dalam senarai. Gunakan untuk memastikan parameter yang berkaitan berada bersama.", + "help.parts.fastener": "Menambah skru, bolt, nat, sesendal, pin atau galas piawai dalam saiz yang anda pilih. Apabila diletakkan pada lubang, ia duduk dalam lubang itu dengan sendi, jadi anda tidak perlu memodelkan pengikat sendiri.", + "help.parts.insert": "Menyisip bahagian piawai dalam keluarga, saiz dan panjang yang anda pilih. Apabila diletakkan pada pinggir atau dinding lubang, ia duduk pada lubang itu dengan sendi tegar.", + "help.parts.library": "Membuka bahagian piawai: skru, bolt, nat, sesendal, skru penetap, pin dowel dan galas dalam saiz piawai. Gunakan untuk menambah bahagian piawai dan bukannya memodelkannya sendiri.", + "help.parts.resize": "Mengubah saiz atau panjang bahagian piawai yang disisipkan dan membinanya semula; sendinya mengekalkannya pada tempat. Gunakan apabila skru ternyata terlalu panjang atau lubang memerlukan saiz lain.", + "help.plastic.assign_rule": "Menetapkan peraturan plastik pada jasad, supaya ciri plastiknya menggunakan sudut draf dan kelegaan peraturan itu sebagai lalai. Gunakan untuk menyediakan bahagian teracu sekali sahaja bagi semua cirinya.", + "help.plastic.boss": "Menambah bonggol skru pada muka: tiang dengan lubang pilihan, sudut draf, jejari sudut pada akar dan rusuk penyokong. Gunakan untuk titik skru dalam perumah teracu atau bercetak.", + "help.plastic.lip": "Menambah bibir atau alur sepadan di sepanjang pinggir jasad yang diberi ronggak. Gunakan supaya dua separuh perumah duduk pada satu sama lain dan tertutup rapat.", + "help.plastic.manage_rules": "Mencipta dan menyunting peraturan plastik: bahan, ketebalan dinding, jejari, kelegaan dan sudut draf. Gunakan untuk memastikan ciri bahagian teracu konsisten.", + "help.plastic.rest": "Menambah penyokong pada muka: pad bulat atau segi empat tepat, pepejal atau berongga, dengan sudut draf. Gunakan sebagai sokongan atau tiang pengasing dalam perumah teracu.", + "help.plastic.snap_fit": "Menambah cangkuk sambungan sentap pada muka, dengan panjang, ketebalan dan penahannya. Gunakan untuk mengklip bahagian bersama tanpa skru.", "help.pointcloud.insert": "Sisipkan imbasan PLY, XYZ atau PTS sebagai awan titik di samping model. Gunakannya sebagai rujukan semasa membina model daripada data yang diukur.", + "help.sheet.convert": "Menukar plat atau jasad beronggak yang berketebalan sekata kepada jasad logam kepingan, dengan lenturan pada tepi yang anda pilih. Gunakan untuk menjadikan bahagian sedia ada boleh dibuka lipatan.", + "help.sheet.export_bend_table": "Menyimpan jadual lenturan jasad logam kepingan sebagai CSV atau JSON: sudut, jejari dan kedudukan lenturan dalam bentangan rata. Gunakan untuk brek tekan atau bengkel.", + "help.sheet.export_dxf": "Menyimpan bentangan rata sebagai DXF, dengan garis luar, garis lenturan dan nota lenturan pilihan. Gunakan untuk pemotongan laser, plasma atau jet air.", + "help.sheet.flange": "Menambah bebibir: plat tapak daripada lakaran, dinding di sepanjang kontur lakaran terbuka, atau dinding berlentur pada tepi kepingan. Gunakan untuk membina bahagian logam kepingan.", + "help.sheet.flat_pattern": "Mencipta bentangan rata jasad logam kepingan, dengan saiz, potongan dan garis lenturannya. Gunakan untuk menyemak kepingan mentah sebelum anda memotongnya.", + "help.sheet.fold": "Melipat kepingan di sepanjang garis lakaran mengikut sudut dan jejari. Gunakan untuk melipat kepingan rata selepas memotong ciri padanya.", + "help.sheet.hem": "Melipat tepi kepingan kembali ke atas dirinya. Gunakan untuk tepi yang selamat dan kukuh tanpa duri tajam.", + "help.sheet.manage_rules": "Mencipta dan menyunting peraturan logam kepingan: ketebalan, jejari lenturan, faktor K, pelega dan sela. Gunakan untuk menyesuaikan dengan bahan dan alat bengkel anda.", + "help.sheet.path_flange": "Menambah rantaian bebibir di sepanjang tepi kepingan, mengikut rantaian terbuka garis lakaran. Gunakan untuk profil seperti bentuk U atau Z dalam satu langkah.", + "help.sheet.perforate": "Menambah medan lubang di seluruh kepingan rata, dalam corak berselang-seli atau segi empat sama. Gunakan untuk lubang angin, gril dan panel yang lebih ringan.", + "help.sheet.refold": "Melipat semula jasad logam kepingan yang telah dibuka lipatan. Gunakan selepas menambah ciri pada kepingan rata.", + "help.sheet.unfold": "Membuka lipatan semua lenturan jasad logam kepingan. Gunakan untuk menambah lubang atau potongan yang perlu melintasi lenturan, kemudian lipat semula.", + "help.sketch.arc.center_point": "Melukis lengkok bulat di sekeliling titik pusat, daripada titik mula ke titik akhir. Gunakan apabila pusat lengkok diketahui, seperti jejari di sekeliling lubang atau pangsi.", + "help.sketch.arc.tangent": "Melukis lengkok yang bermula di hujung garis atau lengkok dan bersambung secara tangen dengannya. Gunakan untuk meneruskan rantaian dengan lenturan licin dan bukannya sudut.", + "help.sketch.arc.three_point": "Melukis lengkok daripada titik mula ke titik akhir melalui titik ketiga. Gunakan apabila lengkok perlu melalui titik yang diberi dan bukannya mengelilingi pusat yang diketahui.", + "help.sketch.arc3d": "Melukis lengkok bulat tepat dalam ruang melalui tiga titik, dengan Lakaran 3D aktif. Gunakan untuk lenturan pada laluan dan rel pemandu yang keluar daripada satah lakaran.", + "help.sketch.auto_constrain": "Menambah kekangan yang hampir dimiliki lakaran, seperti mendatar, selari atau bertindih tepat, kemudian mendimensikannya sehingga tertakrif sepenuhnya. Gunakan untuk mengunci lakaran yang dilukis secara kasar dalam satu langkah.", + "help.sketch.auto_constrain_from_datum": "Berfungsi seperti Kekangan Automatik, tetapi mengukur kedudukan daripada titik datum yang anda pilih dan bukannya titik asal. Gunakan apabila bahagian disusun daripada satu titik rujukan, seperti sudut atau lubang.", + "help.sketch.blend_curve": "Menyambung hujung dua lengkung dengan splin licin yang tangen kepada kedua-duanya, atau juga selanjar kelengkungan jika anda pilih. Gunakan untuk merapatkan jurang antara lengkung tanpa patahan.", + "help.sketch.break": "Memutuskan lengkung kepada beberapa keping di tempat lengkung lain melintasinya, atau pada titik yang anda letakkan padanya. Gunakan apabila sebahagian lengkung memerlukan kekangannya sendiri atau patut dipadam secara berasingan.", + "help.sketch.cancel": "Meninggalkan lakaran dan membuang semua yang diubah sejak ia dicipta atau dibuka untuk disunting. Buat Asal mengembalikan perubahan itu.", + "help.sketch.centerline": "Menukar garis antara garis biasa dan garis tengah, paksi yang diabaikan oleh profil. Gunakan garis tengah sebagai paksi untuk Putar, Cermin atau kekangan simetri.", + "help.sketch.chamfer.distance_angle": "Menyerongkan sudut antara dua garis, ditetapkan oleh jarak sepanjang garis pertama dan satu sudut. Gunakan apabila lukisan memberikan serong sebagai panjang dan sudut, seperti 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Menyerongkan sudut antara dua garis dengan jarak yang sama ke belakang sepanjang kedua-duanya. Gunakan untuk serong 45° yang biasa pada garis luar.", + "help.sketch.chamfer.two_distance": "Menyerongkan sudut antara dua garis, ditetapkan oleh jarak berasingan sepanjang setiap garis. Gunakan untuk serong yang bukan 45°, diberikan sebagai dua panjang.", + "help.sketch.circle.center": "Melukis bulatan daripada pusat dan diameternya. Gunakan untuk lubang, bonggol dan ciri bulat lain yang pusatnya diketahui.", + "help.sketch.circle.three_point": "Melukis bulatan melalui tiga titik. Gunakan apabila bulatan perlu melalui titik yang diberi, contohnya pada geometri sedia ada.", + "help.sketch.circle.three_tangent": "Melukis bulatan yang menyentuh tiga garis, bulatan atau lengkok. Gunakan untuk memuatkan bulatan dalam ruang antara tiga lengkung, seperti bulatan terterap dalam segi tiga.", + "help.sketch.circle.two_point": "Melukis bulatan daripada dua hujung diameternya. Gunakan apabila titik tepi bulatan diketahui dan bukannya pusatnya.", + "help.sketch.circle.two_tangent": "Melukis bulatan bersaiz tertentu yang menyentuh dua garis, bulatan atau lengkok. Gunakan untuk pembulatan berjejari tetap antara dua lengkung.", + "help.sketch.conic": "Melukis lengkung kon antara dua titik hujung, dibentuk oleh titik puncak dan nilai rho. Gunakan untuk peralihan licin yang kepenuhannya hendak anda laraskan, daripada rata hingga hampir sudut tajam.", + "help.sketch.constrainer": "Menggunakan kekangan yang hampir dimiliki satu atau dua lengkung yang dipilih, seperti mendatar, selari, tangen atau sama. Gunakan untuk mengemaskan lakaran lukisan tangan satu hubungan demi satu hubungan.", + "help.sketch.constraint.coincident": "Menjadikan satu titik bertindih tepat dengan titik lain, lengkung atau paksi lakaran. Gunakan untuk menutup jurang dalam profil atau untuk meletakkan titik pada garis.", + "help.sketch.constraint.collinear": "Menjadikan dua garis terletak pada satu garis lurus. Gunakan untuk menjajarkan tepi yang terputus, seperti kedua-dua sisi takuk.", + "help.sketch.constraint.concentric": "Memberi dua bulatan atau lengkok pusat yang sama. Gunakan untuk gelang, lubang benam rata dan aci bertingkat.", + "help.sketch.constraint.curvature": "Menjadikan dua lengkung yang bertemu di titik hujung bersambung dengan kelengkungan yang sama (G2). Gunakan apabila sambungan tangen tidak cukup licin, contohnya pada permukaan yang kelihatan.", + "help.sketch.constraint.equal": "Menjadikan garis sama panjang, atau bulatan dan lengkok sama jejari. Gunakan supaya satu dimensi memacu beberapa ciri yang sepadan.", + "help.sketch.constraint.fix": "Menetapkan titik atau lengkung di tempatnya, atau melepaskannya semula. Gunakan untuk geometri yang tidak boleh bergerak apabila anda menyeret atau menyelesaikan lakaran.", + "help.sketch.constraint.horizontal_vertical": "Menjadikan garis, atau garis antara dua titik, mendatar atau menegak, mana-mana yang lebih hampir. Gunakan untuk meluruskan garis luar mengikut paksi lakaran.", + "help.sketch.constraint.midpoint": "Meletakkan titik di tengah garis, atau menjadikan titik tengah dua garis bertemu. Gunakan untuk memusatkan geometri pada tepi.", + "help.sketch.constraint.parallel": "Menjadikan dua garis selari. Gunakan untuk sisi yang mesti kekal selari apabila dimensi lain berubah.", + "help.sketch.constraint.perpendicular": "Menjadikan dua garis bertemu pada sudut tegak. Gunakan untuk sudut segi empat antara garis yang tidak berada pada paksi lakaran.", + "help.sketch.constraint.polygon": "Menjadikan rantaian garis tertutup sebagai poligon sekata: sisi sama panjang, dengan setiap sudut pada satu bulatan. Gunakan untuk menjadikan poligon lukisan tangan sekata dan mengekalkannya begitu.", + "help.sketch.constraint.symmetry": "Menjadikan dua titik atau lengkung saling bercermin merentasi garis atau mengelilingi titik. Gunakan untuk memastikan profil kekal simetri apabila anda mengubah satu sisi.", + "help.sketch.constraint.tangent": "Menjadikan dua lengkung bersentuhan secara tangen, seperti garis dan lengkok. Gunakan untuk sambungan licin tanpa patahan.", + "help.sketch.construction": "Menukar lengkung antara geometri biasa dan geometri binaan, yang diabaikan oleh profil. Gunakan lengkung binaan sebagai pembantu untuk susun atur, rujukan dan dimensi.", + "help.sketch.construction_line": "Cipta garis binaan tak terhingga melalui dua titik. Gunakannya untuk menyusun lakaran tanpa memisahkan profil.", + "help.sketch.construction_line.angle": "Cipta garis binaan tak terhingga pada sudut daripada paksi X lakaran. Pilih titik dan taip sudutnya, atau pilih arahnya.", + "help.sketch.construction_line.bisector": "Pilih dua garis lakaran lurus yang bersilang, kemudian pilih salah satu pembahagi dua sudut. Hasilnya mengikut garis sumbernya.", + "help.sketch.construction_line.horizontal": "Cipta garis binaan mendatar tak terhingga melalui satu titik. Kekangan mendatarnya kekal apabila disunting kemudian.", + "help.sketch.construction_line.parallel": "Pilih garis lakaran lurus, kemudian letakkan garis binaan tak terhingga yang selari. Klik kanan untuk memilih rujukan lain.", + "help.sketch.construction_line.perpendicular": "Pilih garis lakaran lurus, kemudian letakkan garis binaan tak terhingga yang serenjang. Klik kanan untuk memilih rujukan lain.", + "help.sketch.construction_line.tangent_at": "Cipta tangen pada satu titik pada bulatan atau lengkok bulat, atau pada titik hujung splin atau lengkung kon yang terbuka. Pilih lengkung itu, kemudian titik sentuhnya.", + "help.sketch.construction_line.tangent_external": "Pilih bulatan atau lengkok bulat, kemudian satu titik luar dan satu penyelesaian tangen. Pratonton hanya menunjukkan titik sentuh pada lengkok yang dilukis.", + "help.sketch.construction_line.tangent_two": "Pilih dua bulatan atau lengkok bulat, kemudian pilih tangen sepunya dalam pratonton. Titik sentuh mesti terletak pada lengkung yang dilukis.", + "help.sketch.construction_line.vertical": "Cipta garis binaan menegak tak terhingga melalui satu titik. Kekangan menegaknya kekal apabila disunting kemudian.", + "help.sketch.copy": "Menyalin lengkung dan titik lakaran yang dipilih, bersama kekangan dan dimensi di antaranya. Tampalkannya ke dalam lakaran ini atau lakaran lain.", + "help.sketch.create": "Memulakan lakaran 2D baharu pada satah atau muka rata model. Setiap Semperit, Putar dan Sapu bermula dengan lakaran.", + "help.sketch.cut": "Menyalin geometri lakaran yang dipilih dan memadamnya daripada lakaran, dalam satu langkah Buat Asal. Tampalkannya di tempat lain dalam lakaran ini atau ke dalam lakaran lain.", + "help.sketch.dimension": "Menambah dimensi pemacu: panjang, jarak, sudut, jejari atau diameter, bergantung pada apa yang anda pilih. Taip nilai atau nama parameter, dan lakaran mengikutinya.", + "help.sketch.edit": "Membuka lakaran sedia ada untuk disunting. Ciri yang dibina padanya dikemas kini apabila anda menamatkan lakaran.", + "help.sketch.ellipse": "Melukis elips daripada pusatnya, hujung paksi utama dan satu titik pada sisi minornya. Gunakan untuk bukaan bujur, sesondol dan bentuk bulat memanjang yang lain.", "help.sketch.equation_curve": "Melukis lengkung daripada formula: x(t) dan y(t), atau y = f(x), dalam satu julat. Formula boleh menggunakan parameter dan lengkung akan mengikutinya: gunakannya untuk gelombang sinus, lingkaran atau involut gigi gear.", + "help.sketch.extend": "Memanjangkan garis atau lengkok sehingga lengkung terdekat yang menghalang, atau memanjangkan dua lengkung sehingga bertemu. Gunakan untuk menutup jurang dalam profil selepas memangkas atau menyunting.", + "help.sketch.fillet": "Membulatkan sudut tempat dua garis atau lengkok bertemu dengan lengkok berjejari tertentu. Beberapa sudut yang dibulatkan bersama berkongsi satu jejari.", + "help.sketch.finish": "Meninggalkan lakaran dan kembali ke model. Profilnya yang tertutup kemudian sedia untuk Semperit, Putar dan ciri lain.", + "help.sketch.finish_auto_constrain": "Menjalankan Kekangan Automatik pada lakaran, kemudian menamatkannya. Gunakan untuk meninggalkan lakaran yang tertakrif sepenuhnya dalam satu langkah.", + "help.sketch.fit_curves_to_section": "Memotong jasad mesh atau pepejal dengan satah lakaran dan memadankan garis dan lengkok pada keratan itu. Gunakan untuk membina semula bahagian yang diimbas atau diimport sebagai lakaran boleh sunting.", + "help.sketch.include_3d": "Membawa tepi model, bucu dan lengkung lakaran lain ke dalam lakaran ini sebagai rujukan terpaut, dan meratakan yang tidak berada pada satahnya ke atasnya. Gunakan untuk membina berdasarkan geometri yang tidak terletak pada satah lakaran.", + "help.sketch.infinite": "Menukar garis antara garis biasa dan garis binaan tak terhingga yang melintasi seluruh pandangan. Gunakan sebagai rujukan susun atur yang tidak pernah terlalu pendek.", + "help.sketch.insert_dxf": "Membaca lengkung lukisan DXF ke dalam lakaran, diskalakan, diputar dan diletakkan mengikut tetapan anda. Gunakan untuk membina berdasarkan lukisan 2D daripada program lain, seperti garis luar potongan laser.", + "help.sketch.insert_svg": "Membaca laluan lukisan SVG ke dalam lakaran, diskalakan, diputar dan diletakkan mengikut tetapan anda. Gunakan untuk menukar logo atau garis luar vektor kepada lengkung yang boleh disemperit.", + "help.sketch.inspect": "Membuka laporan tentang lakaran yang terbuka: berapa banyak darjah kebebasan yang tinggal dan sama ada ia terkekang sepenuhnya. Gunakan untuk mengetahui apa yang masih bergerak sebelum anda menamatkan lakaran.", + "help.sketch.intersect": "Menambah lengkung atau titik tempat jasad, muka, tepi atau lakaran lain melintasi satah lakaran. Ia kekal terpaut dan mengikut model apabila model berubah.", + "help.sketch.intersection_curve": "Mencipta lengkung 3D tempat dua jasad atau muka bertemu, terpaut kepadanya. Gunakan sebagai laluan atau rel pemandu yang mengikut model.", + "help.sketch.isoparametric_curve": "Mencipta lengkung 3D di sepanjang arah U atau V muka melalui titik yang anda pilih, terpaut kepada muka itu. Gunakan sebagai laluan atau garis belahan yang mengikut permukaan.", + "help.sketch.line": "Melukis garis bersambung titik demi titik, sebagai rantaian terbuka atau garis luar tertutup. Ia ialah alat asas bagi kebanyakan profil.", + "help.sketch.line.midpoint": "Melukis garis daripada titik tengahnya ke satu hujung, dengan hujung satu lagi dicerminkan. Gunakan untuk garis yang berpusat pada satu titik, seperti tepi simetri.", + "help.sketch.line3d": "Melukis garis lurus bersambung antara titik dalam ruang, dengan Lakaran 3D aktif. Gunakan untuk laluan dan rangka yang keluar daripada satah lakaran.", + "help.sketch.mirror": "Mencerminkan lengkung dan titik lakaran merentasi garis atau paksi dan menambah kekangan simetri. Gunakan untuk melukis separuh profil simetri dan melengkapkannya.", + "help.sketch.move": "Mengalihkan atau memutar lengkung dan titik lakaran, atau salinannya. Gunakan untuk meletakkan semula geometri sambil mengekalkan bentuk dan kekangannya.", + "help.sketch.offset": "Mencipta salinan rantaian lengkung pada jarak tertentu, di satu sisi atau kedua-duanya. Gunakan untuk dinding, garis luar dan kelegaan; jarak kekal sebagai dimensi yang boleh disunting.", + "help.sketch.paste": "Menampal geometri lakaran yang anda salin atau potong ke dalam lakaran aktif. Letakkan pada satu titik atau anjakkan dengan ofset.", + "help.sketch.pattern.circular": "Menyalin geometri lakaran mengelilingi titik pusat, sepanjang bulatan penuh atau sudut tertentu. Gunakan untuk bulatan bolt, ruji dan gigi.", + "help.sketch.pattern.rectangular": "Menyalin geometri lakaran dalam baris dan lajur pada jarak tertentu. Gunakan untuk grid lubang, slot atau lubang angin.", + "help.sketch.point": "Meletakkan titik lakaran. Gunakan sebagai rujukan untuk dimensi, kekangan, pusat lubang atau ciri kemudian.", + "help.sketch.point3d": "Meletakkan titik dalam ruang, dengan Lakaran 3D aktif. Gunakan sebagai rujukan untuk lengkung dan laluan 3D.", + "help.sketch.polygon.circumscribed": "Melukis poligon sekata di sekeliling bulatan, bersaiz daripada pusatnya ke tengah satu sisi. Gunakan apabila lebar merentasi sisi rata diketahui, seperti pada nat heks.", + "help.sketch.polygon.edge": "Melukis poligon sekata daripada dua hujung satu sisi. Gunakan apabila panjang dan kedudukan satu sisi diketahui.", + "help.sketch.polygon.inscribed": "Melukis poligon sekata di dalam bulatan, bersaiz daripada pusatnya ke satu sudut. Gunakan apabila saiz merentasi sudut diketahui.", + "help.sketch.project": "Membawa tepi model, muka, bucu dan lengkung lakaran lain ke dalam lakaran ini, diunjurkan ke satahnya. Ia kekal terpaut dan mengikut model apabila model berubah.", + "help.sketch.project_to_surface": "Mengunjurkan lengkung lakaran lain di sepanjang normal lakaran ini ke atas muka, sebagai lengkung 3D terpaut. Gunakan untuk meletakkan logo, garis belahan atau laluan pada permukaan melengkung.", + "help.sketch.rectangle.center": "Melukis segi empat tepat daripada pusatnya dan satu sudut. Gunakan untuk garis luar yang berpusat pada satu titik, seperti titik asal.", + "help.sketch.rectangle.rounded": "Melukis segi empat tepat dengan keempat-empat sudut dibulatkan pada satu jejari. Gunakan untuk plat, penutup dan bukaan bersudut bulat.", + "help.sketch.rectangle.three_point": "Melukis segi empat tepat daripada satu tepi dan satu titik pada sisi bertentangan. Gunakan untuk segi empat tepat yang condong terhadap paksi lakaran.", + "help.sketch.rectangle.two_point": "Melukis segi empat tepat daripada dua sudut bertentangan. Gunakan untuk garis luar plat, blok dan poket.", + "help.sketch.scale": "Menskalakan lengkung dan titik lakaran dengan satu faktor mengikut titik asas. Gunakan untuk mengubah saiz sebahagian lakaran tanpa melukisnya semula.", + "help.sketch.slot.arc_center": "Melukis slot melengkung dengan lebar tertentu di sepanjang lengkok yang ditetapkan oleh pusat, permulaan dan penghujungnya. Gunakan untuk slot pelarasan di sekeliling pangsi.", + "help.sketch.slot.arc_three_point": "Melukis slot melengkung dengan lebar tertentu di sepanjang lengkok melalui tiga titik. Gunakan apabila laluan slot perlu melalui titik yang diberi.", + "help.sketch.slot.center_point": "Melukis slot lurus dengan lebar tertentu daripada pusatnya ke pusat satu lengkok hujung. Gunakan untuk slot yang berpusat pada satu titik.", + "help.sketch.slot.center_to_center": "Melukis slot lurus dengan lebar tertentu antara pusat kedua-dua lengkok hujungnya. Gunakan untuk slot yang didimensikan dari pusat ke pusat, seperti slot pelarasan untuk skru.", + "help.sketch.slot.overall": "Melukis slot lurus dengan lebar tertentu dari satu hujung luar ke hujung yang lain. Gunakan apabila panjang keseluruhan slot yang penting.", + "help.sketch.spline.control_point": "Melukis splin kubik yang dibentuk oleh titik kawalan yang tidak dilaluinya. Gunakan untuk lengkung licin dan mengalir yang anda bentuk dengan menggerakkan titik.", + "help.sketch.spline.control_point_5": "Melukis splin darjah 5 yang dibentuk oleh titik kawalan. Gunakan apabila lengkung perlu bersambung dengan kelengkungan yang lebih licin, contohnya pada permukaan bergaya yang kelihatan.", + "help.sketch.spline.fit_point": "Melukis splin licin yang melalui setiap titik yang anda letakkan, terbuka atau tertutup. Gunakan untuk menyurih bentuk melalui titik yang diketahui.", + "help.sketch.spline3d": "Melukis lengkung licin dalam ruang melalui titik, dengan Lakaran 3D aktif. Gunakan untuk laluan sapuan dan laluan kabel yang keluar daripada satah lakaran.", + "help.sketch.spun_profile": "Mencipta dalam satah lakaran garis luar yang dilalui oleh jasad apabila ia berputar pada paksi. Gunakan untuk mendapatkan siluet bahagian bubutan bagi Putar atau lukisan.", + "help.sketch.text": "Menulis teks dalam lakaran dengan fon, ketinggian dan sudut yang dipilih; perkataannya boleh mengikut parameter. Semperit atau timbulkan untuk label dan tulisan.", + "help.sketch.transform": "Menskalakan, memutar dan mengalihkan geometri lakaran mengelilingi titik pusat dalam satu langkah. Gunakan untuk meletakkan semula dan mengubah saiz pilihan sekali gus.", + "help.sketch.trim": "Membuang bahagian lengkung antara persilangan terdekat di sekeliling tempat anda mengklik. Gunakan untuk mengemaskan garis bertindih menjadi profil tertutup.", "help.solid.align": "Mengalihkan jasad yang dipilih supaya satu titik, muka atau satah padanya bertemu satu titik, muka atau satah di tempat lain. Gunakan untuk meletakkan satu bahagian pada bahagian lain tanpa mengukur ofset.", + "help.solid.boundary_fill": "Membuat pepejal daripada kawasan yang dikelilingi jasad alat yang bertindih, mengisi hanya kawasan yang anda pilih. Gunakan untuk membina bentuk daripada ruang yang disempadani bersama oleh beberapa jasad.", + "help.solid.bounding_solid": "Mencipta kotak yang mengurung jasad yang dipilih, dengan margin pilihan. Gunakan untuk melihat saiz keseluruhan bahagian, atau sebagai stok bahan yang daripadanya ia dimesin.", + "help.solid.box": "Mencipta kotak daripada panjang, lebar dan tinggi, daripada titik sudut atau berpusat pada satu titik. Gunakan untuk blok pantas, pemegang tempat atau jasad untuk dipotong ciri padanya.", "help.solid.chamfer": "Memotong tepi yang dipilih dengan potongan serong rata sejauh jarak yang anda tetapkan. Gunakan untuk menumpulkan tepi tajam atau memudahkan kemasukan pin atau skru.", + "help.solid.coil": "Mencipta jasad heliks, seperti pegas, daripada diameter, bilangan lilitan, ketinggian atau pic dan keratan bulat atau segi empat sama. Gunakan untuk pegas, gegelung dan rabung heliks.", "help.solid.combine": "Mencantum jasad, memotongnya daripada jasad sasaran, atau hanya mengekalkan isi padu yang dikongsi, dan boleh mengekalkan jasad alat. Gunakan untuk menggabungkan bahagian, memotong satu bentuk dengan bentuk lain atau mencari tempat dua jasad bertindih.", + "help.solid.cone": "Mencipta kon daripada bulatan tapak dan ketinggian, atau kon terpenggal apabila bahagian atas juga berjejari. Gunakan untuk tirus, corong, lubang benam tirus dan hujung tajam.", + "help.solid.cylinder": "Mencipta silinder daripada jejari atau diameter dan ketinggian, berdiri pada satu titik di sepanjang paksi. Gunakan untuk aci, pin, bonggol dan bakal bulat.", "help.solid.draft": "Mencondongkan muka yang dipilih mengikut sudut yang anda tetapkan, diukur dari satah neutral. Gunakan pada bahagian yang diacu atau dituang supaya boleh dikeluarkan dari acuan.", + "help.solid.emboss": "Menimbulkan profil lakaran, seperti teks atau logo, keluar daripada muka, atau membenamkannya ke dalamnya. Gunakan untuk tulisan, label dan tanda pada muka rata atau bulat.", "help.solid.extrude": "Menyemperit profil lakaran menjadi 3D sepanjang jarak yang ditetapkan, menambah atau membuang bahan. Gunakan untuk menukar garis bentuk rata menjadi blok, bonggol atau poket.", "help.solid.fillet": "Membulatkan tepi yang dipilih dengan peralihan bulat licin berjejari yang anda tetapkan. Gunakan untuk melembutkan tepi tajam demi kekuatan, keselesaan atau rupa.", "help.solid.hole": "Menggerudi lubang bulat berdiameter yang anda tetapkan pada titik terpilih pada muka. Gunakan untuk ruang skru, pin dan bukaan bulat ringkas yang lain.", @@ -1408,20 +1678,62 @@ "help.solid.move": "Mengalih atau memutar jasad yang dipilih, atau salinannya, mengikut jarak dan sudut yang ditetapkan. Gunakan untuk menempatkan semula jasad atau membuat satu lagi di tempat lain.", "help.solid.offset_face": "Menolak muka yang dipilih ke dalam atau ke luar mengikut jarak yang ditetapkan, dan muka di sekelilingnya turut mengikut. Gunakan untuk menebalkan dinding, mendalamkan poket atau meninggikan bonggol tanpa menyunting lakaran.", "help.solid.pattern.circular": "Mengulang objek yang dipilih mengelilingi paksi, mengikut bilangan dan jumlah sudut yang ditetapkan. Gunakan untuk bulatan bolt, jejari roda, sirip dan gigi.", + "help.solid.pattern.path": "Menyalin ciri atau jasad di sepanjang laluan lakaran, mengikut bilangan dan jarak. Gunakan untuk lubang di sepanjang tepi melengkung atau bahagian di sepanjang rel.", "help.solid.pattern.rectangular": "Mengulang objek yang dipilih dalam satu atau dua arah mengikut bilangan dan selang yang ditetapkan. Gunakan untuk baris dan grid lubang, rusuk, pin atau kaki.", + "help.solid.pipe": "Mencipta tiub bulat di sepanjang laluan lengkung lakaran, pepejal atau berongga dengan ketebalan dinding. Gunakan untuk tiub, wayar, kabel dan rel.", "help.solid.press_pull": "Menambah atau membuang bahan semasa anda menyeret muka, atau membulatkan tepi semasa anda menyeretnya. Gunakan untuk perubahan pantas terus pada model.", "help.solid.remove": "Mengeluarkan jasad yang dipilih daripada reka bentuk mulai titik ini dalam garis masa; langkah terdahulu masih mengekalkannya. Gunakan untuk menggugurkan jasad bantu, seperti alat pemotong yang tidak diperlukan lagi.", "help.solid.replace_face": "Mengalihkan muka rata yang dipilih ke satah atau ke muka selari, dan jasad membesar atau mengecil untuk bertemu dengannya. Gunakan untuk menyamakan aras muka dengan bahagian lain atau satah binaan.", "help.solid.revolve": "Memutar profil lakaran mengelilingi paksi untuk menghasilkan pepejal bulat. Gunakan untuk aci, tombol, mangkuk dan mana-mana bahagian yang bulat di sekeliling garis tengah.", + "help.solid.rib": "Menambah dinding nipis di sepanjang lengkung lakaran terbuka, diisi sehingga muka seterusnya pada jasad. Gunakan untuk mengukuhkan dinding dan sudut, contohnya pada bahagian teracu atau bercetak.", "help.solid.scale": "Membesarkan atau mengecilkan jasad yang dipilih mengikut faktor, sama ke semua arah atau satu bagi setiap paksi. Gunakan untuk mengubah saiz bentuk yang diimport atau untuk mengambil kira pengecutan.", "help.solid.shell": "Mengosongkan bahagian dalam pepejal, meninggalkan dinding setebal yang ditetapkan, dan boleh membuka muka yang anda pilih. Gunakan untuk kotak, penutup dan bahagian berdinding nipis yang lain.", + "help.solid.sphere": "Mencipta sfera daripada jejari atau diameter mengelilingi titik pusat. Gunakan untuk bebola, tombol dan hujung bulat.", "help.solid.split_body": "Memotong jasad kepada beberapa jasad berasingan menggunakan satah, muka jasad lain atau garis lakaran. Gunakan untuk menghasilkan bahagian yang dicetak, dimesin atau diwarnakan secara berasingan.", "help.solid.split_face": "Membahagikan muka yang dipilih di sepanjang satah, muka jasad lain atau lengkung lakaran, tanpa memotong jasad. Gunakan untuk memberikan sebahagian muka sudut draf, warna atau ofset tersendiri.", "help.solid.sweep": "Menyeret profil lakaran di sepanjang laluan untuk menghasilkan pepejal. Gunakan untuk paip, rel, pemegang dan mana-mana bahagian berkeratan malar yang mengikut lengkung.", + "help.solid.thread": "Menambah bebenang metrik ISO pada muka silinder, sama ada sebagai bebenang kosmetik atau dipotong ke dalam jasad. Gunakan untuk bolt, lubang berbebenang dan bahagian skru bercetak.", + "help.solid.torus": "Mencipta gelang daripada jejari utama mengelilingi paksinya dan jejari minor untuk keratan bulatnya. Gunakan untuk gelang-O, pemegang dan manik bulat.", + "help.solid.web": "Menambah dinding nipis di sepanjang setiap lengkung lakaran terbuka, masing-masing diisi sehingga muka seterusnya pada jasad. Gunakan untuk grid dinding penyokong di dalam perumah dan dulang.", + "help.surface.blend": "Mencipta permukaan yang menyambung tepi dua jasad, tangen atau selanjar kelengkungan kepada kedua-duanya. Gunakan untuk menyambung dua permukaan dengan licin merentasi jurang.", + "help.surface.boundary": "Mencipta permukaan yang mengisi gelung dua hingga empat lengkung lakaran, atau rangkaian lengkung. Gunakan untuk panel bentuk bebas yang ditakrifkan oleh tepinya.", + "help.surface.extend": "Memanjangkan permukaan melepasi tepinya, mengikut jarak atau sehingga satah atau muka. Gunakan supaya permukaan bertindih sebelum anda memangkas atau mencantumnya.", + "help.surface.extrude": "Menolak lengkung atau profil lakaran sepanjang satu jarak menjadi permukaan, dinding sahaja, tanpa penutup. Gunakan untuk dinding nipis dan untuk alat pemotong atau pembelah.", + "help.surface.fair": "Melicinkan bahagian dalam muka bentuk bebas sementara tepinya kekal. Gunakan untuk meratakan bonjolan dan pantulan beralun pada permukaan.", + "help.surface.loft": "Mencipta permukaan yang melalui dua atau lebih keratan mengikut urutan, tanpa penutup. Gunakan untuk cangkerang dan peralihan antara bentuk yang berbeza.", + "help.surface.match": "Membina semula tepi permukaan supaya bertemu dengan tepi jasad lain, dengan tangen atau kelengkungan yang sepadan. Gunakan untuk menutup sambungan dengan licin antara dua permukaan.", + "help.surface.offset": "Mencipta salinan muka pada satu jarak di sepanjang normalnya, sebagai jasad permukaan baharu. Gunakan untuk kulit, kelegaan atau sisi lain sesuatu dinding.", + "help.surface.patch": "Mengisi kawasan lakaran atau gelung tertutup tepi dengan muka, rata atau melengkung licin. Gunakan untuk menutup lubang pada jasad permukaan.", + "help.surface.reverse_normal": "Membalikkan muka jasad permukaan, supaya bahagian luarnya menghadap arah lain. Gunakan sebelum menebalkan atau mencantum apabila muka menghala ke dalam.", + "help.surface.revolve": "Memutar lengkung atau profil lakaran pada paksi menjadi permukaan, tanpa penutup. Gunakan untuk cangkerang bulat seperti teduhan lampu, mangkuk dan muncung.", + "help.surface.ruled": "Mencipta jalur garis lurus keluar daripada rantaian tepi, sepanjang normal muka, tangen atau pada satu sudut. Gunakan untuk dinding draf, kawasan lari-keluar dan permukaan perpisahan.", + "help.surface.stitch": "Mencantum jasad permukaan bersama di sepanjang tepi yang dikongsi, menjadi pepejal apabila ia tertutup. Gunakan untuk menjadikan sekumpulan permukaan satu jasad.", + "help.surface.sweep": "Menggerakkan lengkung atau profil lakaran di sepanjang laluan menjadi permukaan, tanpa penutup. Gunakan untuk alur air, perapi dan bentuk nipis lain yang mengikut laluan.", + "help.surface.thicken": "Memberi ketebalan kepada jasad permukaan, menjadikannya pepejal. Gunakan untuk membuat bahagian yang boleh dicetak atau dimesin daripada permukaan.", + "help.surface.trim": "Memotong permukaan dengan satah, permukaan lain atau lengkung lakaran, dan mengekalkan sisi yang anda pilih. Gunakan untuk memotong permukaan mengikut bentuk sebelum dicantum.", + "help.surface.unstitch": "Melerai muka jasad menjadi jasad permukaan tersendiri; pepejal terlerai menjadi permukaan. Gunakan untuk mengolah semula muka tunggal pada jasad.", + "help.surface.untrim": "Membuang lubang daripada muka, atau memulihkan sempadan luarnya kepada had semula jadi permukaan. Gunakan untuk mendapatkan semula permukaan penuh selepas dipangkas.", "help.third_party": "Lesen pihak ketiga", "help.timeline.compute_all": "Membina semula setiap ciri dalam garis masa dari awal. Gunakan untuk menyegarkan model dan melihat ciri yang gagal.", "help.timeline.delete": "Memadam ciri yang dipilih daripada garis masa; memadam lakaran turut memadam ciri yang dibina daripadanya. Gunakan untuk membuang langkah yang tidak lagi diperlukan.", + "help.timeline.dependents": "Menyenaraikan ciri yang akan dipadam bersama sesuatu ciri, dan yang akan gagal tanpanya. Gunakan sebelum memadam atau mengubah ciri.", "help.timeline.play": "Main semula ciri yang tinggal satu demi satu, dengan jeda setengah saat selepas setiap pembinaan semula. Jalankan perintah ini sekali lagi atau tekan Escape untuk berhenti; Pergi ke penghujung melompat serta-merta.", + "help.view.apply": "Memutar pandangan ke arah piawai seperti hadapan, atas atau iso, atau ke pandangan bernama yang disimpan. Gunakan untuk melihat model dari sudut tetap.", + "help.view.delete": "Memadam pandangan bernama yang disimpan. Model tidak berubah.", + "help.view.fit": "Menzum dan menyorot supaya seluruh model, atau pilihan, memenuhi pandangan. Gunakan apabila model telah hilang daripada pandangan.", + "help.view.grid": "Memaparkan atau menyembunyikan grid dalam tetingkap pandangan. Gunakan sebagai panduan saiz dan orientasi semasa memodelkan.", + "help.view.ground_shadow": "Memaparkan atau menyembunyikan bayang model pada lantai. Gunakan untuk menilai ketinggian dan kedudukan dengan lebih mudah.", + "help.view.home": "Memutar pandangan kembali ke arah utama dan memuatkan model. Gunakan untuk kembali ke pandangan yang diketahui dengan cepat.", + "help.view.list": "Menyenaraikan pandangan bernama yang disimpan dalam reka bentuk. Gunakan untuk mencari pandangan yang anda simpan sebelum ini.", + "help.view.navigate": "Memutar, menyorot atau menzum pandangan mengikut langkah, seperti suku pusingan ke kiri. Gunakan untuk menggerakkan kamera dengan tepat dan bukannya menyeret.", + "help.view.navigation_bar": "Memaparkan atau menyembunyikan bar navigasi di bahagian bawah tetingkap pandangan. Sembunyikan untuk ruang lebih luas, paparkan untuk mencapai alat pandangan dengan tetikus.", + "help.view.rename": "Memberi nama baharu kepada pandangan bernama yang disimpan. Pandangan itu sendiri kekal sama.", + "help.view.save": "Menyimpan kedudukan kamera semasa sebagai pandangan bernama dalam reka bentuk. Gunakan untuk kembali ke sudut yang sama kemudian, contohnya untuk tangkapan skrin.", + "help.view.spin": "Mengorbit pandangan mengelilingi model secara berterusan sehingga klik atau kekunci seterusnya. Gunakan untuk mempersembahkan model dari semua sisi.", + "help.view.tool": "Mengunci alat kamera, orbit, sorot atau zum, supaya menyeret dengan butang kiri tetikus menggerakkan pandangan sehingga anda mematikannya. Gunakan pada pad jejak atau tanpa butang tengah tetikus.", + "help.view.visual_style": "Menukar cara model dilukis: berlorek dengan atau tanpa tepi, rangka dawai, atau dengan tepi tersembunyi. Gunakan rangka dawai untuk melihat ke dalam, berlorek untuk rupa yang bersih.", + "history.sketch_under_constrained": "Kurang terkekang ({count} darjah kebebasan)", + "history.sketch_under_constrained_one": "Kurang terkekang ({count} darjah kebebasan)", "hole_presets.confirm_delete": "Sahkan pemadaman", "hole_presets.delete": "Padam", "hole_presets.delete_prompt": "Padam pratetap peribadi ini? Lubang sedia ada tidak berubah.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Semak jenis sendi (seperti Tegar), status tetap, had sendi dan nilai yang dipacu parameter.", "joint_move.blocked_title": "Tidak dapat mengalihkan bahagian ini", "joint_move.coarse": "Langkah putaran dekat paksi (°)", + "joint_move.conflict": "Satu sendi bagi bahagian ini bercanggah dengan yang lain: {joint}.", + "joint_move.conflict_hint": "Sunting, nyahaktifkan atau padam sendi yang bercanggah supaya sendi lain dapat meletakkan bahagian itu.", "joint_move.distance": "Jarak dari mula", "joint_move.done": "Selesai", "joint_move.fine": "Langkah putaran jauh dari paksi (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Bahan berbeza", "measure.at": "Pada", "measure.item": "Item {number}", + "measure.quick_copied": "Ukuran disalin", + "measure.quick_copy": "Klik untuk menyalin ukuran", + "measure.quick_edges": "{count} tepi", + "measure.quick_faces": "{count} muka", "messages.ago_h": "{n} j lalu", "messages.ago_min": "{n} min lalu", "messages.ago_s": "{n} s lalu", @@ -1620,6 +1938,8 @@ "motion.track_name": "Trek {number}", "nav.alias.help": "Shift+Alt+seret kiri mengorbit, Shift+Alt+seret tengah menyorot, Shift+Alt+seret kanan menzum; seret tengah juga menyorot dan seret kanan mengorbit", "nav.blender.help": "Seret tengah mengorbit, Shift+tengah menyorot, Ctrl+tengah menzum; seret kanan tidak menggerakkan kamera", + "nav.creo.help": "Seret tengah mengorbit, Shift+tengah menyorot, Ctrl+seret tengah secara menegak menzum (ke bawah untuk zum masuk); tatal roda untuk zum", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Tetikus dan tetikus 3D berputar melalui kedua-dua kutub dan mengekalkan gelek. Pelekapan paksi dengan Shift dilumpuhkan.", "nav.free_orbit.label": "Orbit bebas", "nav.free_orbit.snap_help": "Tetikus dan tetikus 3D berputar melalui kedua-dua kutub dan mengekalkan gelek. Tahan Shift semasa menyeret orbit untuk melekapkan arah pandangan dan gelek.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+seret kiri menyorot, Shift+Alt+seret kiri menzum, Ctrl+seret kiri pada ruang kosong mengorbit", "nav.inventor.help": "Seret tengah menyorot, Shift+tengah mengorbit, Ctrl+tengah menzum, seret kanan mengorbit", "nav.maya.help": "Alt+seret kiri mengorbit, Alt+seret tengah menyorot, Alt+seret kanan menzum; seret tengah juga menyorot", + "nav.nx.help": "Seret tengah mengorbit, Shift+tengah menyorot (tengah + kanan dalam NX), Ctrl+tengah menzum (tengah + kiri dalam NX); seret kanan tidak menggerakkan kamera", "nav.openscad.help": "Seret kiri pada ruang kosong mengorbit, Shift+seret kiri memilih dengan kotak, seretan geometri lakaran menyunting; seret kanan atau tengah menyorot, Shift+seret kanan atau Shift+seret tengah menzum", "nav.perspective.sketch": "Penyuntingan lakaran menggunakan pandangan ortografik. Siapkan lakaran untuk bertukar ke perspektif.", "nav.right_drag_orbits.help": "Mati: seret kanan tidak menggerakkan kamera dan butang kanan hanya membuka menu konteks. Memilih pemetaan tetikus SolidWorks akan mematikannya.", @@ -1748,6 +2069,11 @@ "not a move": "bukan gerakan", "not a number": "bukan nombor", "open a sketch first": "buka lakaran dahulu", + "parameters.apply_live": "Gunakan setiap perubahan apabila anda meninggalkan medannya", + "parameters.apply_live_tip": "Mati: perubahan menunggu sehingga Gunakan atau OK, kemudian reka bentuk dibina semula sekali untuk semuanya. Batal atau Escape membuangnya.", + "parameters.held": "{count} perubahan menunggu Gunakan", + "parameters.held_hint": "Sunting ungkapan dan unit. Perubahan menunggu Gunakan atau OK.", + "parameters.held_one": "1 perubahan menunggu Gunakan", "parts.automatic_name": "automatik", "parts.dimension.across_flats": "Merentasi rata", "parts.dimension.bore": "Diameter lubang", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Skru kepala butang", "parts.family.dowel_pin": "Pin selari (dowel)", "parts.family.hex_bolt": "Bolt / skru kepala heks", + "parts.family.hex_cap_screw_inch": "Skru kepala heks (cap screw, inci)", "parts.family.hex_nut": "Nat heks", + "parts.family.hex_nut_inch": "Nat heks (inci)", "parts.family.set_screw": "Skru penetap soket heks, hujung rata", "parts.family.socket_head_cap_screw": "Skru kepala soket", "parts.family.washer": "Sesendal biasa", + "parts.family.washer_sae": "Sesendal biasa, SAE (sempit)", + "parts.family.washer_uss": "Sesendal biasa, USS (lebar)", + "parts.holes": "Lubang (pilihan)", + "parts.placement_hint": "pilih satu atau lebih lubang untuk meletakkan bahagian pada setiap satu, atau tekan OK untuk meletakkannya di titik asal", + "parts.system": "Sistem unit", + "parts.system.inch": "Inci", + "parts.system.metric": "Metrik", "pattern.alignment_2": "Penjajaran 2", "pattern.alignment_hint": "Bilangan termasuk asal. Tengah seimbangkan salinan; Balik pilih sisi lebih untuk bilangan genap.", "pattern.direction_1": "Arah 1", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Melicinkan tepi bergerigi.", "prefs.applies_on_restart": "Berkuat kuasa selepas dimulakan semula", "prefs.assistant": "Pembantu", + "prefs.auto_operation": "Pilih operasi secara automatik", + "prefs.auto_operation_note": "Tetingkap ciri memilih Cantum, Jasad Baharu atau Potong berdasarkan apa yang disentuh oleh bahan baharu, sehingga anda memilih satu. Mati: ia mengekalkan operasi yang dibukanya.", "prefs.axes": "Paksi", "prefs.axis": "Paksi", "prefs.bodies_folders": "Folder jasad", @@ -1820,6 +2157,8 @@ "prefs.bottom_centre": "Bawah tengah", "prefs.bottom_right": "Bawah kanan", "prefs.browser": "Pelayar", + "prefs.browser_eye_left": "Ikon mata di sebelah anak panah kembang/ringkas", + "prefs.browser_eye_left_note": "Baris pelayar memaparkan ikon mata papar/sembunyi di sebelah anak panah kembang/ringkas, seperti sebelum ini, bukannya dalam lajur di hujung kanan baris.", "prefs.browser_reveal_on_hover": "Muncul apabila dilalui kursor", "prefs.browser_show_note": "Dipaparkan mengekalkan pelayar pada skrin. Muncul apabila dilalui kursor menyembunyikannya sehingga penuding berada di atas tempatnya atau tab nipis di tepi kirinya, dan ia kekal terbuka selagi penuding berada di dalamnya atau menu daripadanya terbuka.", "prefs.browser_shown": "Dipaparkan", @@ -1827,6 +2166,8 @@ "prefs.button_left": "Seret kiri", "prefs.button_middle": "Seret tengah", "prefs.button_right": "Seret kanan", + "prefs.carousel_next": "Seterusnya", + "prefs.carousel_previous": "Sebelumnya", "prefs.choose_font": "Pilih fail fon…", "prefs.click": "Klik", "prefs.contact_shading": "Lorekan sentuhan lembut", @@ -1839,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Permukaan melengkung", "prefs.curves": "Permukaan melengkung", + "prefs.cut_preview_tint": "Papar bahan yang dibuang dalam warna merah", + "prefs.cut_preview_tint_help": "Pratonton mengisi bahan yang dibuang oleh sesuatu ciri, dan bentuk yang digantikannya, dengan bayang merah lut sinar. Apabila dimatikan, isian itu telus sepenuhnya dan hanya garis luarnya dilukis.", + "prefs.dark_parts_shading": "Kekalkan bentuk bahagian yang gelap", + "prefs.dark_parts_shading_help": "Lorekkan pandangan dalam cahaya linear dengan cahaya isian langit yang lembut, supaya muka yang gelap mengekalkan kecerunan dan tidak menjadi hitam", "prefs.dead_zone_note": "Jalur berlorek ialah zon mati: gerakan di dalamnya diabaikan.", "prefs.default": "lalai", "prefs.design": "Lalai reka bentuk", @@ -1853,6 +2198,8 @@ "prefs.edges": "Tepi dan teduhan", "prefs.extend": "Panjangkan", "prefs.extra_navigation": "Seret kiri dengan Ctrl pada ruang kosong untuk mengorbit; tahan Space untuk menyorot.", + "prefs.extrude_view_isometric": "Putar pandangan ke isometrik apabila Semperit dibuka", + "prefs.extrude_view_return": "Kembali ke pandangan terdahulu apabila Semperit ditutup", "prefs.follows_os": "Ikut OS", "prefs.font": "Fon", "prefs.font_fallback": "Glif yang tiada dalam fon pilihan akan beralih kepada fon terbina dalam, jadi tiada label yang memaparkan kotak kosong.", @@ -1868,8 +2215,11 @@ "prefs.graphics_card_auto": "Automatik", "prefs.graphics_card_missing": "Kad grafik yang disimpan tidak tersedia; Automatik digunakan.", "prefs.graphics_card_restart": "Berkuat kuasa selepas SolidCraft dimulakan semula. WGPU_ADAPTER_NAME mengatasi pilihan ini.", + "prefs.graphics_card_unused": "Kad grafik yang disimpan tidak digunakan untuk tetingkap ini; kad yang sedang digunakan dipaparkan dalam Bantuan › Tentang dan dalam bar status. Cuba Automatik, atau tetapkan WGPU_ADAPTER_NAME kepada bahagian unik pada nama kad itu.", "prefs.graphics_note": "Tukar kelajuan dengan kelicinan. Setiap pilihan menunjukkan kesannya pada contoh.", "prefs.graphics_presets_note": "Pratetap menetapkan pilihan di bawah sekali gus.", + "prefs.hide_constraint_glyphs_zoomed_out": "Sembunyikan glif kekangan apabila dizum keluar", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Glif kekangan hilang daripada pandangan apabila lakaran dizum keluar sehingga glif itu menyesakkan paparan. Mati: ia kekal pada saiz skrin tetap pada setiap tahap zum.", "prefs.history": "Sejarah", "prefs.history_origin_bodies": "Papar titik asal dan jasad di bahagian atas", "prefs.history_origin_bodies_note": "Sejarah di sebelah kiri atau di bawah pelayar bermula dengan folder Jasad bagi komponen aktif dan Titik Asal, lengkap dengan ikon mata dan menunya seperti dalam pelayar. Sejarah di bahagian bawah tidak berubah.", @@ -1880,6 +2230,8 @@ "prefs.history_sketches_note": "Apabila Lakaran ditetapkan kepada Di bawah cirinya, Sejarah di sebelah kiri menyenaraikan setiap lakaran satu tahap ke dalam, di bawah ciri pertama yang dibina daripadanya, apabila ruangnya cukup lebar untuk nama. Garis masa di bahagian bawah sentiasa mengekalkan urutan penciptaan.", "prefs.history_sketches_under_feature": "Di bawah cirinya", "prefs.hold_stop_snapping": "Tahan untuk menghentikan pelekapan", + "prefs.home_fit_size": "Saiz Utama dan Muatkan", + "prefs.home_fit_size_note": "Seberapa banyak pandangan yang diisi oleh model apabila Utama, Muatkan, reka bentuk yang baru dibuka atau perubahan pandangan melalui kawalan pandangan membingkainya, sama ada tetapan di bawah dihidupkan atau tidak. 100 %: memenuhi pandangan di antara panel, kompas dan bar navigasi.", "prefs.icons_only": "Ikon sahaja", "prefs.imported_file": "Fail yang diimport", "prefs.in_browser": "Dalam pelayar", @@ -1888,13 +2240,22 @@ "prefs.interface_language": "Bahasa antara muka", "prefs.interface_note": "Rupa SolidCraft dan kedudukan bahagiannya.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Songsangkan anak panah gelek melengkung", + "prefs.invert_curved_roll_arrows_note": "Dua anak panah melengkung di sudut kubus menggelek pandangan dalam satah skrin. Hidup: anak panah ikut arah jam menggelek lawan arah jam dan anak panah lawan arah jam menggelek ikut arah jam. Mati: setiap anak panah menggelek pandangan mengikut arah lengkungannya.", + "prefs.invert_navigator_arrows": "Songsangkan anak panah putaran kubus pandangan", + "prefs.invert_navigator_arrows_note": "Anak panah di sekeliling kubus mengorbit kamera mengikut arah yang ditunjuknya, seperti dalam Fusion dan Inventor: anak panah di kiri menunjuk ke kanan dan mengayunkan kamera ke kanan. Mati: anak panah memutarkan kubus ke arah sisi tempat ia berada, jadi anak panah kiri mengayunkan kamera ke kiri. Anak panah gelek yang melengkung tidak terjejas.", + "prefs.keep_work_on_tab_switch": "Kekalkan dialog dan alat terbuka apabila menukar reka bentuk", + "prefs.keep_work_on_tab_switch_note": "Setiap tab reka bentuk mengekalkan dialog atau alat yang dibukanya, bersama apa yang anda pilih dan taip di dalamnya, serta tab bar alatnya. Semuanya ada semula apabila anda kembali ke reka bentuk itu. Mati: menukar reka bentuk membatalkannya dan menunjukkan tab Model.", "prefs.labels": "Label", + "prefs.language_system": "Sistem", "prefs.layout": "Susun atur", "prefs.layout_note": "Padat melabuhkan panel pada tepi tetingkap. Kelutsinaran pelayar tersedia dalam Terapung. Tukar sisi Pembantu pada halaman Pembantu.", "prefs.left": "Kiri", "prefs.left_click": "Klik kiri", "prefs.line_drag_draws_one": "Tekan dan seret melukis satu garis", "prefs.line_drag_draws_one_note": "Dalam alat Garis, menekan, menyeret dan melepaskan melukis satu garis dari titik tekan hingga titik lepas, dan ia tamat di situ. Klik masih melukis rantaian. Mati: seretan meletakkan titik di tempat ia dilepaskan, seperti klik.", + "prefs.line_hover_tangent_arc": "Berhenti pada titik terakhir garis untuk bertukar kepada lengkok tangen", + "prefs.line_hover_tangent_arc_note": "Dalam alat Garis, selepas satu segmen dilukis, alihkan penuding menjauhi titik terakhir rantaian, kembali dan tahan penuding diam di situ: klik seterusnya menentukan hujung lengkok tangen, dan gerak isyarat yang sama kembali kepada garis. Mati: berhenti di situ tidak berbuat apa-apa.", "prefs.linked_designs": "Reka bentuk terpaut", "prefs.live_input": "Input langsung", "prefs.live_preview": "Pratonton langsung", @@ -1908,6 +2269,9 @@ "prefs.max_file_size_step": "Fail STEP dan import", "prefs.max_file_size_web": "Aplikasi web membuka fail STEP dan import sehingga 512 MB serta reka bentuk sehingga 256 MB: tab pelayar tidak dapat memuatkan fail lebih besar. Aplikasi desktop boleh menaikkan had ini.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Ikon besar", + "prefs.menu_list": "Senarai", + "prefs.menus": "Menu", "prefs.minutes": "minit", "prefs.minutes_suffix": " min", "prefs.mouse": "Tetikus dan pad jejak", @@ -1915,6 +2279,8 @@ "prefs.mouse_mapping": "Pemetaan tetikus", "prefs.navigation": "Navigasi", "prefs.navigation_note": "Cara tetikus, pad jejak dan tetikus 3D menggerakkan pandangan.", + "prefs.navigator_fit": "Muatkan model selepas perubahan pandangan navigator", + "prefs.navigator_fit_note": "Muka, sudut atau anak panah pada kubus pandangan, atau paksi pada gizmo, turut menghadap ke tengah model dari satu jarak yang memuatkannya dari semua sisi (sfera pembatasnya). Utama menggunakan zum dan pusat yang sama selagi ini dihidupkan, jadi pandangan yang dipilih selepasnya hanya berputar. Mati: pandangan berputar di tempat, dengan sasaran dan zumnya kekal.", "prefs.network_host_remove": "Buang", "prefs.network_locations": "Benarkan lokasi rangkaian dalam reka bentuk", "prefs.network_locations_note": "Dimatikan: fail terpaut bagi reka bentuk pada komputer lain (\\\\server\\share) hanya dibuka daripada pelayan yang disenaraikan di sini, atau selepas anda membenarkannya apabila ditanya.", @@ -1927,10 +2293,18 @@ "prefs.origin_plane_names": "Nama satah asal", "prefs.origin_plane_names_note": "Nama yang dipaparkan dalam pelayar, dialog dan senarai. {top} ialah XY, {front} ialah XZ dan {right} ialah YZ, dengan Z ke atas. Arahan, skrip dan reka bentuk yang disimpan kekal menggunakan XY, XZ dan YZ.", "prefs.overall_speed": "Kelajuan keseluruhan", + "prefs.parameter_list_rows": "Baris senarai parameter", + "prefs.parameter_list_rows_tip": "Anak panah ke bawah dalam medan nilai kosong menyenaraikan parameter, kegemaran dahulu, sehingga bilangan ini. Bilangan yang lebih kecil memastikan senarai ringan dalam reka bentuk besar.", + "prefs.persistent_ribbon_pressed": "Serlahkan arahan reben yang aktif", + "prefs.persistent_ribbon_pressed_help": "Serlahkan arahan reben selagi kesannya dihidupkan. Matikan untuk mengekalkan rupa neutral dan bantuan arahan yang terdahulu.", "prefs.perspective_fov": "Medan pandangan", "prefs.placement": "Penempatan", "prefs.prefer_free_sketch_points": "Utamakan titik lakaran yang boleh digerakkan apabila titik bertindih", "prefs.preview_choices": "Pratonton pilihan anda", + "prefs.preview_tint_new_faces": "Warnakan permukaan baharu dalam pratonton", + "prefs.preview_tint_new_faces_help": "Pratonton ciri yang mengubah sesuatu jasad boleh melukis permukaan yang ditambahnya dalam warna pratonton. Apabila dimatikan, jasad dilukis seperti biasa.", + "prefs.print_face_highlight": "Serlahan muka cetakan", + "prefs.print_face_highlight_tip": "Sejauh mana muka cetakan sesuatu jasad diwarnakan dan digaris dalam paparan. 0 % tidak menunjukkan serlahan.", "prefs.profile_active": "Profil aktif", "prefs.profile_applied": "Profil digunakan.", "prefs.profile_changed": "Tetapan telah berubah sejak profil disimpan. Simpan mengekalkannya dalam profil.", @@ -1952,9 +2326,13 @@ "prefs.quality_fastest": "terpantas", "prefs.quality_slowest": "terperlahan", "prefs.quality_smoother": "lebih licin", + "prefs.quick_measure": "Ukuran pantas di sudut pandangan", + "prefs.quick_measure_note": "Saiz pilihan di sudut kanan bawah pandangan: panjang tepi, atau Ø dan R bagi tepi bulat, luas muka, kedudukan titik, jarak dan sudut dua item, jumlah beberapa tepi atau muka. Satu klik menyalinnya.", "prefs.render_previous_geometry_budget": "Gunakan bajet geometri pratonton Render sebelumnya", "prefs.render_previous_geometry_budget_help": "Pulihkan had geometri tetap sebelumnya (512 MiB pada desktop 64-bit, 128 MiB di tempat lain) dan bukannya bajet berdasarkan peranti.", "prefs.reports_saved": "{n} disimpan", + "prefs.ribbon_click_ends_tool": "Mengklik butang alat yang sedang berjalan menamatkannya", + "prefs.ribbon_click_ends_tool_note": "Satu klik pada butang reben yang menyala bagi alat lakaran yang sedang digunakan menamatkan alat itu, jadi klik dalam pandangan memilih semula. Mati: klik memulakan alat itu semula.", "prefs.ribbon_reveal": "Tunjukkan hasil carian dalam reben", "prefs.ribbon_reveal_note": "Melalukan kursor pada hasil dalam Cari arahan menunjukkan kedudukan arahan itu dalam reben: tabnya, butangnya atau barisnya dalam senarai juntai sesuatu panel. Arahan yang dimulakan daripada carian berkelip di situ, dan arahan yang sedang berjalan daripada senarai juntai menandakan panelnya.", "prefs.right_click": "Klik kanan", @@ -1965,6 +2343,8 @@ "prefs.search_empty": "Tiada tetapan yang sepadan", "prefs.select": "Pilih", "prefs.select_one_item": "Pilih satu item", + "prefs.select_other_hidden": "Pilih geometri tersembunyi dengan Pilih Lain", + "prefs.select_other_hidden_help": "Hidup: sertakan jasad, lakaran dan tepi terlindung yang tersembunyi berhampiran penuding. Mati: guna senarai asal geometri kelihatan di bawah penuding.", "prefs.selecting": "Pemilihan", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift hanya menambah; Ctrl / Cmd menogol", @@ -1976,31 +2356,63 @@ "prefs.sketch_align_points_note": "Semasa melukis, titik diselaraskan secara mendatar dengan satu titik lakaran dan secara menegak dengan titik lain pada masa yang sama, dengan panduan bertitik, dan klik mengekalkan kedua-dua penjajaran. Mati: hanya dengan titik sebelumnya, satu paksi pada satu masa.", "prefs.sketch_conflict_colour": "Geometri bercanggah dalam warna percanggahan", "prefs.sketch_conflict_colour_note": "Apabila kekangan lakaran bercanggah, lengkung dan titik yang dipegang oleh kekangan yang gagal turut dilukis dalam warna percanggahan, bukan sahaja glifnya atau dimensinya. Mati: ia mengekalkan warna biasa.", + "prefs.sketch_construction_lines": "Alat garis binaan lanjutan", "prefs.sketch_exit_view": "Apabila lakaran tamat", "prefs.sketch_exit_view.keep": "Kekalkan pandangan semasa", "prefs.sketch_exit_view.previous": "Kembali ke pandangan sebelumnya", "prefs.sketch_exit_view.unless_rotated": "Kembali melainkan diputar", "prefs.sketch_exit_view_note": "Ke mana pandangan beralih selepas Siap Lakaran, Batal atau Esc dua kali.", + "prefs.sketch_face_activates_part": "Melakar pada muka sesuatu bahagian menjadikan bahagian itu aktif", + "prefs.sketch_face_activates_part_note": "Lakaran yang dimulakan pada muka jasad milik komponen lain mengaktifkan komponen itu terlebih dahulu, jadi lakaran itu menjadi milik komponen tersebut dan kekal bersama bahagian itu dalam pelayar. Bahagian itu kekal aktif selepas itu. Mati: lakaran menjadi milik komponen aktif.", + "prefs.sketch_open_look_at": "Putar menghadap lakaran apabila dibuka", + "prefs.sketch_open_look_at_note": "Mati: mencipta atau menyunting lakaran membiarkan pandangan seperti sedia ada. Pandang Tepat menghadapkan pandangan ke lakaran apabila anda mahu.", "prefs.sketch_recent_snap": "Lekap auto pada pusat dan titik tengah terkini", "prefs.sketch_recent_snap_note": "Semasa melukis, kursor melekap pada titik persilangan panduan daripada dua pusat bulatan atau titik tengah tepi lurus yang terkini. Mati: panduan itu hanya untuk paparan dan kursor tidak bergerak.", "prefs.sketch_selection": "Lakaran & pilihan", "prefs.sketch_selection_heading": "Lakaran dan pilihan", "prefs.sketch_selection_note": "Cara lakaran melekap dan cara klik memilih.", + "prefs.sketch_state_icons": "Ikon lakaran dalam warna keadaannya", + "prefs.sketch_state_icons_note": "Dalam Sejarah dan pelayar, ikon lakaran mengambil warna keadaannya (kurang terkekang, terkekang sepenuhnya atau bercanggah) dan petua alatnya menamakan keadaan itu. Mati: setiap lakaran mempunyai ikon yang sama.", "prefs.sketch_tab_always": "Kekalkan tab Lakaran dipaparkan", "prefs.sketch_tab_always_note": "Tab Lakaran kekal dalam reben, sejurus selepas Model, selagi tiada lakaran dibuka. Alat lukisannya kemudian memulakan lakaran pada satah atau muka yang dipilih, atau pada satah yang anda pilih seterusnya, dengan alat itu sedia di dalamnya.", "prefs.sketch_tracking_guides": "Panduan penjajaran pusat dan titik tengah", "prefs.sketch_tracking_guides_note": "Halakan kursor pada pusat bulatan atau titik tengah tepi lurus, kemudian gerakkan secara mendatar atau menegak untuk memaparkan panduan bertitik sementara.", + "prefs.sketch_tracking_points": "Panduan penjajaran daripada titik hujung dan sudut semasa melukis", + "prefs.sketch_tracking_points_note": "Semasa alat lukisan menunggu satu titik, meletakkan penuding pada hujung garis atau lengkok, sudut segi empat tepat atau titik bebas memaparkan panduan bertitik sementara yang sama seperti bagi pusat atau titik tengah. Mati: hanya pusat dan titik tengah.", "prefs.sketching": "Melakar", "prefs.snap_drawing_note": "Semasa melukis atau menyeret titik lakaran.", "prefs.source": "Sumber", "prefs.speed": "Kelajuan", "prefs.stand_up_note": "Selepas fail STEP atau IGES dibuka dengan Z ke atas, tawarkan putaran suku pusingan pada paksi X.", + "prefs.stand_up_unknown": "Untuk fail daripada program yang tidak dikenali", + "prefs.stand_up_unknown.ask": "Tanya dalam dialog", + "prefs.stand_up_unknown.note": "Papar nota", + "prefs.stand_up_unknown.off": "Jangan tawarkan", + "prefs.stand_up_unknown_note": "Cara tawaran dibuat apabila pengepala fail tidak menamakan program yang diketahui menyimpan dengan Y ke atas. Nota dipaparkan hanya apabila fail kelihatan terbaring; Tanya dalam dialog bertanya tentang setiap fail sedemikian, seperti sebelum ini.", "prefs.status_bar": "Bar status", "prefs.status_bar_note": "Bar nipis di sepanjang tepi bawah tetingkap memaparkan apa yang sedang disunting, keadaan lakaran yang dibuka dalam warnanya dan unit reka bentuk; klik pada unit untuk menukarnya. Keadaan lakaran kemudian tidak lagi dipaparkan di sudut paparan.", "prefs.status_done": "Selesai", "prefs.status_error": "Ralat", "prefs.status_selected": "Dipilih", "prefs.status_warning": "Amaran", + "prefs.structure.appearance": "Penampilan", + "prefs.structure.appearance_note": "Warna, teks dan kebolehcapaian.", + "prefs.structure.in_profile": "Dalam profil", + "prefs.structure.layout": "Susun atur", + "prefs.structure.layout_note": "Kedudukan bahagian-bahagian tetingkap.", + "prefs.structure.look": "Gaya", + "prefs.structure.measure_pointer": "Ukur dan penuding", + "prefs.structure.mouse3d": "Tetikus 3D", + "prefs.structure.mouse3d_note": "SpaceMouse dan SpaceNavigator.", + "prefs.structure.navigation_note": "Tetikus dan pad jejak. Tetikus 3D mempunyai halamannya sendiri.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Berubah sejak disimpan", + "prefs.structure.profile_hover": "Disimpan dalam profil tetapan", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Lakaran", + "prefs.structure.tools": "Alat", + "prefs.structure.tools_note": "Cara alat pemodelan berfungsi.", + "prefs.structure.work": "Kerja", "prefs.supersampling_brief": "Melukis pandangan pada saiz lebih besar lalu menapisnya ke bawah: sangat tajam, tetapi lebih berat.", "prefs.tab_accent_note": "Aksen mengikut tab aktif", "prefs.theme_file": "fail tema", @@ -2012,6 +2424,16 @@ "prefs.theme_follow_off": "Mati", "prefs.theme_follow_stop": "Berhenti mengikuti", "prefs.theme_import_hint": "Klik untuk memilih fail tema, seret satu ke sini, atau tekan Ctrl+V (Cmd+V pada Mac) dengan tema yang telah disalin", + "prefs.theme_option_opacity": "Kelegapan", + "prefs.theme_option_opacity_help": "Laraskan kelegapan panel terapung. Paras kebolehbacaan minimum melindungi teks di atas warna tetingkap pandangan.", + "prefs.theme_option_tab_colours": "Warna tab", + "prefs.theme_option_tab_colours_help": "Gunakan warna panel dan tetingkap pandangan tema ini bagi setiap tab reben.", + "prefs.theme_option_tab_fade_ms": "Peralihan tab", + "prefs.theme_option_tab_fade_ms_help": "Pudarkan warna panel dan tetingkap pandangan apabila bertukar tab. Sifar bertukar serta-merta.", + "prefs.theme_options_badge": "Pilihan", + "prefs.theme_options_more": "Lagi · {count}", + "prefs.theme_options_reset": "Set Semula", + "prefs.theme_options_unavailable": "Tidak tersedia pada peranti ini", "prefs.theme_paste": "Tampal tema", "prefs.theme_paste_none": "Papan keratan tidak mengandungi tema SolidCraft", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2455,23 @@ "prefs.under_cursor": "Di bawah kursor", "prefs.units_precision": "Unit dan ketepatan", "prefs.updates": "Kemas kini", + "prefs.value_boxes_in_view": "Papar nilai di sebelah pemegangnya dalam pandangan", + "prefs.value_boxes_in_view_tip": "Nilai sesuatu arahan (Jarak, Jejari…) dalam kotak di sebelah pemegangnya, di atas model. Mati: anda menaipnya dalam tetingkap arahan, yang mengambil papan kekunci selepas satu pilihan, dan tiada apa-apa menutupi model.", "prefs.view": "Kelakuan pandangan", "prefs.view_confirm_corner": "OK dan Batal di sudut pandangan", "prefs.view_confirm_corner_note": "Semasa dialog atau lakaran dibuka, tanda semak dan tanda silang di bahagian kanan atas pandangan melakukan apa yang dilakukan OK dan Batal dialog, atau menyiapkan dan membatalkan lakaran. Navigator pandangan bergerak ke bawah di bawahnya.", "prefs.viewport": "Tetingkap pandangan", + "prefs.viewport_analysis_status": "Papar status analisis tetingkap pandangan", + "prefs.viewport_analysis_status_help": "Papar analisis aktif di atas tetingkap pandangan, buka petunjuknya daripada setiap item, dan gunakan Esc untuk mematikan analisis terbaharu. Matikan untuk memulihkan petunjuk sudut dan tingkah laku Esc yang terdahulu.", "prefs.viewport_background": "Latar belakang", "prefs.viewport_background_colour": "Warna", "prefs.viewport_background_theme": "Kecerunan tema", + "prefs.viewport_section_status": "Papar status keratan tetingkap pandangan", + "prefs.viewport_section_status_help": "Papar tetapan keratan dalam tetingkap pandangan. Escape dan butang reben yang aktif mematikannya. Matikan untuk mengekalkan kawalan keratan sebelumnya.", + "prefs.viewport_status_details": "Butiran tetingkap pandangan langsung", + "prefs.viewport_status_details_help": "Sunting tetapan analisis dan keratan yang aktif dalam kad butiran piawai. Matikan untuk memulihkan kekunci analisis baca sahaja dan dialog Keratan.", + "prefs.viewport_status_summary": "Ringkaskan item status tetingkap pandangan", + "prefs.viewport_status_summary_help": "Ringkaskan tiga atau lebih item status tetingkap pandangan ke dalam satu lencana ringkasan. Matikan untuk mengekalkan setiap item dalam baris penuh.", "prefs.wheel": "Roda", "prefs.wheel_trackpad": "Roda dan pad jejak", "prefs.workspace": "Ruang kerja", @@ -2049,6 +2481,10 @@ "properties.title": "Sifat: {name}", "recovery.days_ago": "{count} hari lalu", "recovery.detail": "{file} · {features} ciri · disimpan automatik {when}", + "recovery.discard_all": "Buang semua", + "recovery.discard_all_detail": "Tindakan ini tidak boleh dibuat asal.", + "recovery.discard_all_title": "Buang {count} simpanan automatik?", + "recovery.discard_all_title_one": "Buang 1 simpanan automatik?", "recovery.hours_ago": "{count} j lalu", "recovery.just_now": "sebentar tadi", "recovery.min_ago": "{count} min lalu", @@ -2164,6 +2600,10 @@ "render.base_color": "Warna asas · sRGB", "render.base_metallic": "Pecahan logam", "render.base_opaque_only": "Penyunting ini mengekalkan semantik jasad legap. Gunakan kawalan kaca yang khusus untuk transmisi optik.", + "render.batch_all_shots": "Semua syot ({count})", + "render.batch_empty": "Simpan satu syot sebelum merender semua syot.", + "render.batch_limit": "Render Semua Syot dihadkan kepada 32 syot.", + "render.batch_status": "{running} sedang berjalan · {waiting} menunggu", "render.bloom_enable": "Papar bloom", "render.bloom_help": "Pendaran kreatif untuk keluaran sahaja daripada serlahan linear positif, disebarkan dengan tiga laluan kotak ternormal. Jejari dalam piksel keluaran. Ditambah dalam cahaya paparan linear sebelum sRGB; bukan kesan kanta, kesan volumetrik atau peningkatan penumpuan. EXR mentah tidak berubah.", "render.bloom_opaque": "Bloom memerlukan keluaran legap. PNG telus ditolak, bukan diratakan secara senyap.", @@ -2274,6 +2714,13 @@ "render.choose_look": "Pilih gaya dalam Penampilan dahulu", "render.chromatic_offset": "Ofset tepi kromatik", "render.clear_stage": "Buang pentas yang disimpan", + "render.compare_divider": "Pembahagi perbandingan", + "render.compare_live": "Langsung", + "render.compare_live_preview": "Pratonton langsung", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · dirakam pada semakan {revision}", + "render.compare_swap": "Tukar", "render.copy_request": "Salin JSON", "render.cpu_aa_help": "Sampel ruang: lebih banyak sampel menambah baik tepi dan menambah masa render.", "render.cpu_area_add": "Tambah lampu segi empat tepat CPU", @@ -2914,7 +3361,9 @@ "render.output_ready": "Sedia untuk merender", "render.output_run_check": "Jalankan semakan", "render.output_size_limit": "{method}: sehingga {dimension} px setiap sisi dan {pixels} piksel. Saiz terbesar yang muat: {width} × {height}.", + "render.output_size_method_profile": "Untuk merender {width} × {height}, pilih {method} dengan profil sumber CPU {profile}, atau saiz yang lebih kecil.", "render.output_size_ok": "Saiz OK · {width} × {height} px", + "render.output_size_profile": "Untuk merender {width} × {height}, pilih profil sumber CPU {profile}, atau saiz yang lebih kecil.", "render.output_swap_orientation": "Tukar lebar dan ketinggian", "render.output_tools_inspector": "Sunting saiz dan format dalam pemeriksa Keluaran.", "render.output_view_image": "Lihat imej", @@ -3021,6 +3470,10 @@ "render.result_retained": "Memaparkan imej siap yang terakhir; render yang lebih baharu belum menggantikannya.", "render.result_sequence": "Titik Semak", "render.result_title": "Hasil Render", + "render.results_choose": "Hasil yang dikekalkan", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [lapuk]", + "render.results_unnamed": "Imej", "render.return_design": "Kembali ke Reka Bentuk", "render.review_stale": "Tinjauan ini sudah lapuk. Selesaikan atau semak semula sebelum menggunakan.", "render.ribbon_aging": "Penuaan", @@ -3127,6 +3580,7 @@ "render.size_custom": "Tersuai…", "render.size_full_hd": "HD Penuh", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · memerlukan {profile}", "render.size_presets": "Pratetap saiz", "render.size_presets_pending": "Akan hadir bersama penyunting Keluaran", "render.size_preview": "Pratonton", @@ -3414,6 +3868,24 @@ "sheet.flange_type_contour": "Kontur", "sheet.flange_type_edge": "Tepi", "sheet.no_body": "tiada jasad logam kepingan: mulakan satu dengan Bebibir > Asas, atau tukarkan plat kepada logam kepingan dengan Tukar kepada Logam Kepingan (pilih muka rata yang besar)", + "sheet.personal_rules.confirm_delete": "Sahkan pemadaman", + "sheet.personal_rules.delete": "Padam", + "sheet.personal_rules.delete_prompt": "Padam peraturan peribadi ini? Peraturan yang sudah ada dalam reka bentuk tidak berubah.", + "sheet.personal_rules.full": "Koleksi peribadi sudah mengandungi 64 peraturan.", + "sheet.personal_rules.invalid_name": "Masukkan nama pendek tanpa pemisah baris atau aksara kawalan.", + "sheet.personal_rules.invalid_values": "Lengkapkan nilai peraturan: setiap satu mesti dapat dikira dalam reka bentuk ini, dengan ketebalan positif dan faktor K dari 0 hingga 1.", + "sheet.personal_rules.missing": "Peraturan peribadi yang dipilih tidak lagi tersedia.", + "sheet.personal_rules.name": "Nama peraturan", + "sheet.personal_rules.name_exists": "Peraturan peribadi dengan nama ini sudah wujud. Gunakan nama lain.", + "sheet.personal_rules.name_hint": "Nama yang unik", + "sheet.personal_rules.overwrite": "Simpan perubahan pada peraturan peribadi yang dipilih", + "sheet.personal_rules.rename": "Tukar nama", + "sheet.personal_rules.rule": "Peraturan peribadi", + "sheet.personal_rules.save": "Simpan baharu", + "sheet.personal_rules.scope": "Disimpan dalam profil anda untuk semua reka bentuk.", + "sheet.personal_rules.select": "Pilih peraturan", + "sheet.personal_rules.title": "Peraturan peribadi", + "sheet.personal_rules.unsupported": "Peraturan ini mempunyai nilai yang tidak dapat digunakan oleh versi ini.", "shortcut.json_error": "parameter mestilah JSON: {error}", "shortcut.no_command": "tiada arahan `{id}`; teks sebelum JSON mestilah ID arahan", "shortcut.pin": "Semat di atas kotak S", @@ -3450,8 +3922,10 @@ "sketch_text.align_right": "Kanan", "sketch_text.bold": "Tebal", "sketch_text.builtin_font": "{family} (terbina dalam)", + "sketch_text.formula": "Mulakan dengan = untuk membina perkataan daripada parameter: ='W' + number(Width)", "sketch_text.italic": "Condong", "sketch_text.loading_fonts": "Mencari fon yang dipasang…", + "sketch_text.no_bold": "Fon terbina dalam tiada versi tebal: pilih fon yang dipasang", "sketch_text.on_path": "Teks mengikut laluan lengkung, yang menentukan kedudukannya", "sketch_text.path_clear": "Pisahkan teks daripada lengkung", "sketch_text.path_hint": "Lengkung lakaran yang akan diikuti teks: klik di sini, kemudian klik lengkung", @@ -3483,10 +3957,7 @@ "the two origins are on the same component": "kedua-dua titik asal berada pada komponen yang sama", "thread.automatic_size": "Saiz automatik", "thread.designation": "Penamaan", - "thread.direction": "Arah bebenang", "thread.iso_metric": "Metrik ISO", - "thread.left_hand": "Tangan kiri", - "thread.right_hand": "Tangan kanan", "thread.select_size": "Pilih saiz", "timeline.delete_after_marker_one": "Padam 1 Ciri Selepas Penanda Sejarah", "timeline.delete_after_marker_other": "Padam {count} Ciri Selepas Penanda Sejarah", @@ -3503,8 +3974,10 @@ "timeline.move_to_group": "Alih Ciri ke Folder", "timeline.rename_group": "Tukar Nama Folder Ciri", "timeline.reorder_many": "Susun Semula Ciri", + "timeline.suppress_features": "Nyahaktifkan Ciri", "timeline.suppress_folders_tip": "Nyahaktifkan atau aktifkan semula setiap ciri dalam folder dan folder bersarangnya", "timeline.ungroup": "Buang Folder Ciri", + "timeline.unsuppress_features": "Aktifkan Semula Ciri", "to the face": "ke muka", "to the next face": "ke muka seterusnya", "toolbar.customize_note": "Tab {tab}. Tandakan arahan untuk memberinya butang bar alat. Anda juga boleh menyeret baris menu lungsur panel ke bar alat, menyeret butang keluar dari bar alat untuk membuangnya, atau guna semat pada baris menu lungsur.", @@ -3588,6 +4061,8 @@ "ui.3d_mouse_section": "Tetikus 3D", "ui.3d_mouse_show_in_view": "Tunjukkan tetikus 3D dalam paparan 3D", "ui.3d_mouse_show_in_view_tip": "Gambar tetikus 3D anda di sudut kiri bawah, yang bergerak apabila anda menggerakkannya.", + "ui.3d_mouse_sketch_orbit": "Putar lakaran dengan tetikus 3D", + "ui.3d_mouse_sketch_orbit_tip": "Tetikus 3D juga memutar pandangan semasa lakaran dibuka dan dilihat tepat dari hadapan, sama seperti yang boleh dilakukan tetikus. Mati: ia menyorot dan menzum lakaran sehingga anda mencondongkan pandangan.", "ui.3d_mouse_skip": "Peranti saya tidak boleh buat ini", "ui.3d_mouse_skip_tip": "Langkau gerakan ini kedua-dua arah; penentukuran tidak menggunakannya.", "ui.3d_mouse_speed": "Kelajuan tetikus 3D", @@ -3616,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Pusing penutup lawan arah jam, tahan, kemudian lepaskan.", "ui.3d_mouse_switch_cap": "Tentukur sebagai kembali ke tengah", "ui.3d_mouse_switch_trackball": "Tentukur sebagai bola jejak", + "ui.3d_mouse_use_direct": "Guna pemacu terus", + "ui.3d_mouse_use_direct_tip": "Baca tetikus 3D secara terus (hidraw) dan bukan melalui spacenavd.", "ui.3d_mouse_view_axis": "Paksi paparan", "ui.3d_mouse_view_off": "Mati", "ui.3d_mouse_view_off_tip": "Profil pemacu tetikus 3D mematikan paksi ini, jadi gerakannya tidak menggerakkan paparan. Memilih gerakan paksi lain di sini menukar kedua-duanya, dan gerakan itu tidak lagi menggerakkan paparan.", @@ -3654,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Jalankan arahan ini dalam terminal, kemudian tekan Sambung semula:", "ui.agent_chat_auth_title": "Log masuk ke ejen", "ui.agent_chat_cancel": "Batal", + "ui.agent_chat_cancel_timeout": "Ejen tidak bertindak balas kepada Hentikan dan telah diputuskan sambungannya. Sambung semula untuk meneruskan.", + "ui.agent_chat_cannot_start": "Terpasang, tetapi tidak bermula: {error}", "ui.agent_chat_changes": "{n} perubahan, satu Buat Asal", "ui.agent_chat_changes_n": "{n} perubahan", "ui.agent_chat_changes_of": "{n}/{limit} perubahan", @@ -3662,11 +4141,13 @@ "ui.agent_chat_command": "Arahan ejen", "ui.agent_chat_connect": "Sambung", "ui.agent_chat_copy": "Salin", + "ui.agent_chat_copy_message": "Salin mesej", "ui.agent_chat_ctx_bodies": "Jasad", "ui.agent_chat_ctx_elements": "Elemen", "ui.agent_chat_ctx_features": "Ciri", "ui.agent_chat_ctx_more": "+{n} lagi", "ui.agent_chat_ctx_other": "Lain-lain", + "ui.agent_chat_custom_heading": "Model tersuai", "ui.agent_chat_custom_hint": "Program yang guna Agent Client Protocol melalui stdin dan stdout. Dijalankan tanpa shell.", "ui.agent_chat_denied": "Ditolak", "ui.agent_chat_deny": "Tolak", @@ -3710,8 +4191,16 @@ "ui.agent_chat_mode_all": "Semua", "ui.agent_chat_mode_ask": "Tanya", "ui.agent_chat_mode_edits": "Suntingan", + "ui.agent_chat_model_custom": "Guna tersuai: {model}", "ui.agent_chat_model_no_tools": "{model} tidak dapat menggunakan alat SolidCraft, jadi hanya boleh berbual. Pilih model yang menyokong alat.", + "ui.agent_chat_model_rejected": "Ejen tidak menerima {model}: {error}", + "ui.agent_chat_model_search": "Cari model…", "ui.agent_chat_model_tip": "Model yang digunakan oleh ejen. Pilihan anda disimpan untuk ejen ini.", + "ui.agent_chat_models_failed": "Tidak dapat menyenaraikan model: {error}", + "ui.agent_chat_models_heading": "Model yang tersedia", + "ui.agent_chat_models_listing": "Menyenaraikan model…", + "ui.agent_chat_models_none": "Titik akhir tidak menyenaraikan sebarang model", + "ui.agent_chat_models_not_a_list": "Jawapan itu bukan senarai model", "ui.agent_chat_new": "Sembang baharu", "ui.agent_chat_new_confirm": "Mulakan sembang baharu? Sembang semasa akan dikosongkan.", "ui.agent_chat_next_picture": "Gambar seterusnya", @@ -3746,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "Menunggu (dihentikan, belum dihantar)", "ui.agent_chat_refresh": "Muat Semula", "ui.agent_chat_refused": "Tindakan ejen tidak dibenarkan: {reason}", + "ui.agent_chat_reinstall": "{agent} terpasang ({program}), tetapi tidak bermula apabila SolidCraft memeriksanya: {error}\nPemasangannya mungkin tidak lengkap, atau dibuat untuk jenis komputer lain. Pasang semula dengan `{install}`, semak bahawa ia mencetak versinya dalam terminal, kemudian tekan Muat Semula.", "ui.agent_chat_remove": "Buang daripada baris gilir", "ui.agent_chat_remove_file": "Buang daripada mesej ini", "ui.agent_chat_remove_imported": "Buang daripada mesej ini; bahagian kekal dalam reka bentuk (Buat Asal membuangnya)", + "ui.agent_chat_reply_cut_off": "Balasan mencapai had panjangnya sebelum selesai, jadi mungkin tidak lengkap. Minta ejen meneruskan, atau memberi jawapan yang lebih pendek.", + "ui.agent_chat_reply_declined": "Model enggan menjawab mesej ini.", "ui.agent_chat_retry": "Cuba semula", "ui.agent_chat_right": "Kanan", "ui.agent_chat_save": "Simpan", @@ -3807,12 +4299,17 @@ "ui.ai_copy_suffix": "salinan", "ui.ai_custom_url": "URL tersuai", "ui.ai_default": "Lalai", + "ui.ai_edit": "Sunting", + "ui.ai_edit_agent_title": "Sunting ejen", + "ui.ai_edit_gone": "Ejen ini telah dibuang, jadi tiada apa-apa untuk disimpan.", + "ui.ai_edit_tip": "Tukar nama, arahan atau titik akhir ejen ini. Kunci yang disimpan kekal tersembunyi.", "ui.ai_http_busy": "titik akhir sibuk atau telah melebihi had; cuba lagi kemudian", "ui.ai_http_key": "kunci ditolak oleh titik akhir: semak dalam Tetapan > AI", "ui.ai_http_not_found": "titik akhir atau model tidak ditemui: semak URL asas dan nama model", "ui.ai_http_too_large": "perbualan terlalu besar untuk titik akhir ini; mulakan sembang baharu", "ui.ai_key": "Kunci API", "ui.ai_key_hint": "tidak wajib; disimpan dalam rantai kunci sistem", + "ui.ai_key_keep_hint": "biarkan kosong untuk mengekalkan kunci yang disimpan", "ui.ai_key_needs_https": "Kunci hanya dihantar melalui HTTPS, atau ke komputer ini.", "ui.ai_key_note": "Disimpan dalam rantai kunci sistem, bukan dalam tetapan SolidCraft. Biarkan kosong untuk pelayan setempat.", "ui.ai_keychain_error": "Rantai kunci sistem menolak: {error}", @@ -3839,11 +4336,15 @@ "ui.ai_permissions": "Kebenaran", "ui.ai_preset": "Pratetap", "ui.ai_protocol": "Protokol", + "ui.ai_reasoning_effort": "Usaha penaakulan", + "ui.ai_reasoning_effort_field_hint": "kosong = lalai pembekal", + "ui.ai_reasoning_effort_hint": "Pilihan. Dihantar kepada titik akhir sebagai `reasoning_effort`; nilai yang diterima berbeza bagi setiap pembekal (contohnya `low`, `high` atau `max`). Nilai yang anda tetapkan di sini tidak sekali-kali diganti oleh SolidCraft. Biarkan kosong untuk tidak menghantar apa-apa dan mengekalkan lalai pembekal.", "ui.ai_remove": "Buang", "ui.ai_request_timed_out": "Model mengambil masa lebih daripada {seconds} s. Anda boleh menaikkan had masa permintaan untuk titik akhir ini dalam Tetapan › Pembantu.", "ui.ai_request_timeout": "Had masa permintaan", "ui.ai_request_timeout_hint": "Berapa lama satu permintaan model ke titik akhir ini boleh mengambil masa, daripada 30 s hingga sejam. Naikkan untuk model setempat yang perlahan.", "ui.ai_reset": "Set Semula", + "ui.ai_save": "Simpan", "ui.ai_settings": "Tetapan AI…", "ui.ai_show_features": "Papar ciri AI", "ui.ai_show_features_note": "Panel sembang untuk ejen pengekodan atau titik akhir model pilihan mengubah reka bentuk terbuka. Jika dimatikan: tiada butang AI, pintasan, menu atau panel; tiada ejen dicari atau dimulakan.", @@ -3922,6 +4423,8 @@ "ui.cancel": "Batal", "ui.canvases": "Kanvas", "ui.center": "Tengah", + "ui.center_arc_follows_cursor": "Lengkok titik pusat mengikut arah kursor", + "ui.center_arc_follows_cursor_tip": "Lengkok titik pusat berjalan ikut arah jam atau lawan arah jam mengikut cara kursor mengelilingi pusatnya. Mati: sentiasa lawan arah jam dari permulaan.", "ui.centerline": "Garis tengah", "ui.chain": "Rantaian", "ui.chamfer": "Serong", @@ -3930,6 +4433,7 @@ "ui.circle": "Bulatan", "ui.circular_pattern": "Corak Membulat", "ui.clear": "Kosongkan", + "ui.clear_print_face": "Kosongkan muka cetakan", "ui.clear_recent": "Kosongkan Terkini", "ui.clear_the_selection": "Kosongkan pilihan", "ui.click_selects_whole_bodies": "Klik untuk memilih keseluruhan jasad", @@ -3964,12 +4468,27 @@ "ui.constant": "Malar", "ui.constraints_conflict": "Kekangan bercanggah", "ui.construction": "Binaan", + "ui.construction.angle_hint": "Garis binaan: klik satu titik, kemudian taip sudut atau pilih arah", + "ui.construction.bisector_hint": "Pembahagi dua sudut: pilih dua garis lurus yang bersilang, kemudian penyelesaian yang dikehendaki", + "ui.construction.common_hint": "Tangen sepunya: pilih dua bulatan/lengkok, kemudian penyelesaian yang dikehendaki", + "ui.construction.contact_hint": "Tangen: pilih bulatan/lengkok atau splin/lengkung kon terbuka, kemudian titik sentuh (lengkung bentuk bebas: titik hujung)", + "ui.construction.external_hint": "Tangen: pilih bulatan atau lengkok, satu titik luar, kemudian penyelesaian yang dikehendaki", + "ui.construction.free_hint": "Garis binaan: klik dua titik; klik kanan untuk mula semula", + "ui.construction.normal_needs_length": "Garis tak terhingga sentiasa garis binaan: taip panjang untuk melukis garis biasa", + "ui.construction.point_hint": "Garis binaan: klik titik yang akan dilalui", + "ui.construction.reference_hint": "Garis binaan: pilih garis lurus, kemudian satu titik; klik kanan untuk menukar rujukan", "ui.construction.ribbon_label": "Garis bantu", + "ui.construction.side_hint": "Garis binaan: klik sisi yang dituju garis; klik kanan untuk mula semula", "ui.context_menu": "Menu konteks", + "ui.continuity_crease": "Lipatan", + "ui.continuity_curvature": "Kelengkungan", + "ui.continuity_curvature_change": "Perubahan kelengkungan", "ui.continuity_g0": "Lipatan G0", "ui.continuity_g1": "Tangen G1", "ui.continuity_g2": "Kelengkungan G2", "ui.continuity_gap": "Sela", + "ui.continuity_position": "Kedudukan", + "ui.continuity_tangent": "Tangen", "ui.copy": "Salin", "ui.corner": "Sudut", "ui.corners": "Sudut", @@ -3992,6 +4511,7 @@ "ui.dark": "Gelap", "ui.default_modelling_orientation": "Orientasi pemodelan lalai", "ui.delete": "Padam", + "ui.delete_select_first": "Pilih dahulu apa yang hendak dipadam: ciri, jasad, komponen atau geometri lakaran", "ui.depth": "Kedalaman", "ui.design": "Reka", "ui.design_properties.author": "Pengarang", @@ -4006,6 +4526,40 @@ "ui.design_properties.project": "Projek", "ui.design_properties.revision": "Semakan", "ui.design_saved": "Disimpan ke {path}", + "ui.details_access_caption": "Muka menunjukkan sama ada alat dapat mencapainya dari arah yang dipilih.", + "ui.details_angle": "Sudut", + "ui.details_continuity_caption": "Sunting sambungan yang dipilih. Sambungan lain mengekalkan tetapannya sendiri.", + "ui.details_continuity_stale": "Geometri terdahulu: jalankan semula analisis untuk menyunting atau membingkaikan sambungan ini.", + "ui.details_copy_list": "Salin senarai", + "ui.details_curvature": "Toleransi kelengkungan", + "ui.details_curvature_caption": "Muka diwarnakan mengikut jejari kelengkungan setempatnya.", + "ui.details_direction": "Arah alat", + "ui.details_draft_caption": "Muka diwarnakan mengikut sudutnya terhadap arah tarikan.", + "ui.details_edit_seam": "Sunting sambungan", + "ui.details_fixture": "Spesimen komponen — data sampel sahaja", + "ui.details_fixture_caption": "Spesimen komponen dengan nilai ilustrasi; ini bukan hasil model.", + "ui.details_fixture_problem": "Contoh penemuan dengan masalah", + "ui.details_fixture_readout": "Contoh nilai yang diukur", + "ui.details_flip": "Balik", + "ui.details_gap": "Sela", + "ui.details_hatch": "Lorek muka yang dipotong", + "ui.details_jump": "Lonjakan kelengkungan", + "ui.details_key": "Petunjuk", + "ui.details_offset": "Ofset", + "ui.details_plane": "Satah", + "ui.details_pull": "Arah tarikan", + "ui.details_radius": "Jejari", + "ui.details_readout": "Bacaan", + "ui.details_samples": "Sampel", + "ui.details_seam": "{body} · Tepi {edge}", + "ui.details_settings": "Tetapan", + "ui.details_sharp_gap": "Tajam atau sela", + "ui.details_show_all": "Papar semua {count}", + "ui.details_smooth": "Licin", + "ui.details_stripes": "Jalur", + "ui.details_target": "Bingkaikan geometri", + "ui.details_worst_seams": "Sambungan terburuk", + "ui.details_zebra_caption": "Jalur yang dipantulkan menunjukkan kehalusan pertemuan muka.", "ui.diameter": "Diameter", "ui.dimension": "Dimensi", "ui.direct_interaction": "Interaksi langsung", @@ -4050,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "Bahagian ini disimpan ke fail lain; pemasangan masih memaut {name}", "ui.edit_in_place_wait": "Tunggu sehingga apa yang sedang berjalan dalam reka bentuk selesai", "ui.edit_section_analysis": "Sunting Analisis Keratan", + "ui.edit_sketch_empty": "Tiada lakaran untuk disunting", "ui.ellipse": "Elips", "ui.emboss_wrap_note": "Profil garis ortogon yang tangen pada satu silinder yang disokong dibalut secara automatik. Pilih dinding untuk memilih sasaran.", "ui.end_radius": "Jejari Akhir", @@ -4060,12 +4615,15 @@ "ui.equation_explicit": "Eksplisit", "ui.equation_form": "Bentuk", "ui.equation_note": "Pemboleh ubah ialah nombor biasa: sin(t) mengambilnya dalam radian. Hasil tanpa unit adalah dalam unit reka bentuk.", + "ui.equation_note_range": "Pemboleh ubah ialah panjang, begitu juga julatnya: campurkannya dengan parameter panjang, dan bahagikannya dengan satu panjang untuk sin(). Hasil tanpa unit adalah dalam unit reka bentuk.", "ui.equation_parametric": "Parametrik", + "ui.equation_variable_unit": "Pemboleh ubah menggunakan unit julat", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Jejari Setara", "ui.expand": "Kembangkan", + "ui.explode_needs_two_components": "Pandangan Terlerai menarik komponen berjauhan, jadi reka bentuk memerlukan dua atau lebih komponen (Komponen Baharu, Sisip Reka Bentuk atau Cipta Komponen daripada Jasad)", "ui.exportDxf": "Eksport DXF…", "ui.export_ellipsis_keymap": "Eksport…", "ui.export_keymap_tip": "Simpan kekunci, kegemaran kotak S dan bar alat ke fail", @@ -4191,6 +4749,7 @@ "ui.hideOrigin": "Sembunyi Titik Asal", "ui.hidePlanes": "Sembunyi Satah", "ui.hideProfile": "Sembunyi Profil", + "ui.hide_component_history": "Sembunyikan Sejarahnya", "ui.hide_origin_by_default": "Sembunyi titik asal secara lalai", "ui.hide_origin_note": "Reka bentuk baharu bermula dengan folder Titik Asal disembunyikan. Sesuatu reka bentuk mengekalkan tetapan Titik Asalnya sendiri sebaik sahaja anda memaparkan atau menyembunyikannya.", "ui.history_back": "Undur satu langkah", @@ -4198,6 +4757,7 @@ "ui.history_edge_hint": "klik dua kali pada tepi", "ui.history_first": "Pergi ke permulaan", "ui.history_forward": "Maju satu langkah", + "ui.history_hide_hidden": "Sembunyikan Komponen Tersembunyi", "ui.history_hide_names": "Sembunyi nama", "ui.history_last": "Pergi ke penghujung", "ui.history_marker_tip": "Penanda sejarah: seret untuk mengundurkan model; ciri baharu diletakkan di sini", @@ -4207,10 +4767,12 @@ "ui.history_play_button_show": "Papar Butang Main", "ui.history_play_finish_action": "Selesaikan tindakan semasa sebelum memainkan Sejarah", "ui.history_play_roll_back": "Alih penanda Sejarah ke belakang sebelum memainkan", + "ui.history_show_hidden": "Papar Komponen Tersembunyi", "ui.history_show_names": "Papar nama", "ui.history_sketch_listed_under": "Disenaraikan di bawah {feature}", "ui.history_title": "Sejarah", "ui.history_toggle_names": "Papar atau sembunyikan nama ciri", + "ui.history_waits_for_editor": "Buat Asal, Buat Semula dan Sejarah menunggu sehingga penyunting ciri dibuka", "ui.hole": "Lubang", "ui.hole_tap_type": "Jenis Bebenang Lubang", "ui.hole_type": "Jenis Lubang", @@ -4226,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} mempunyai perubahan yang belum disimpan, jadi fail tersimpannya disisipkan. Simpan reka bentuk itu, kemudian gunakan Kemas Kini Pautan untuk membawa masuk perubahan.", "ui.insert_design.unsaved": "Perubahan belum disimpan", "ui.inspect": "Periksa", + "ui.instances": "Salinan", "ui.intersect": "Silang", "ui.isolate": "Asingkan", "ui.join": "Cantum", @@ -4234,12 +4797,14 @@ "ui.joints": "Sendi", "ui.keyboard_shortcuts": "Pintasan Kekunci", "ui.language": "Bahasa", + "ui.lasso_select": "Lasso (seret gelung bebas: memilih yang sepenuhnya berada di dalam)", "ui.layout_compact": "Padat", "ui.layout_floating": "Terapung", "ui.length": "Panjang", "ui.length_decimals": "Perpuluhan panjang", "ui.light": "Cerah", "ui.line": "Garis", + "ui.line_arc_hint": "Lengkok tangen: klik hujung lengkok. Berhenti lagi pada titik terakhir untuk garis; klik kanan atau Esc untuk selesai", "ui.link_copies": "Pautkan Salinan Serupa", "ui.link_copies_keep": "Kekalkan", "ui.link_copies_link": "Pautkan", @@ -4328,6 +4893,7 @@ "ui.part_size_shared": "Membina semula bahagian, menggantikan sebarang ciri yang ditambah. Semua kejadian komponen ini dikemas kini.", "ui.paste": "Tampal", "ui.path": "Laluan", + "ui.pattern_object_type_tip": "Jasad: bentuk pepejal, dipilih dalam pandangan atau Pelayar; setiap satu disalin keseluruhannya.\nCiri: langkah Sejarah, seperti semperit atau lubang, dipilih dalam Sejarah atau pada muka yang dihasilkannya; langkah itu diulang.\nLakaran bukan kedua-duanya: ulang lengkungnya dengan Corak atau Cermin milik lakaran itu sendiri, atau semperit dahulu.", "ui.pattern_on_path": "Corak Sepanjang Laluan", "ui.perforate_margin_default": "daripada diameter", "ui.perforate_pitch": "Pic", @@ -4354,12 +4920,17 @@ "ui.plugins_skipped": "{count} folder tidak dapat dibaca.", "ui.plugins_version": "{version}", "ui.point": "Titik", + "ui.point_cloud_add_filter": "Tambah penapis…", "ui.point_cloud_auto_range": "Julat Automatik", "ui.point_cloud_color_by": "Warna Mengikut", "ui.point_cloud_file_colors": "Warna Fail", + "ui.point_cloud_filter_by": "Tapis mengikut", "ui.point_cloud_height_high": "Tertinggi", "ui.point_cloud_height_low": "Terendah", + "ui.point_cloud_legend_filter": "Dipaparkan dan disembunyikan dalam petunjuk di atas", "ui.point_cloud_no_file_colors": "Fail tiada warna", + "ui.point_cloud_pause": "Jeda", + "ui.point_cloud_play": "Main", "ui.point_cloud_single_color": "Warna Tunggal", "ui.point_cloud_size": "Saiz Titik", "ui.point_cloud_units": "Unit Fail", @@ -4368,6 +4939,11 @@ "ui.polygon": "Poligon", "ui.preferences": "Tetapan", "ui.press_a_key": "tekan kekunci…", + "ui.print_face_body_not_sent": "Jasad muka itu tidak dihantar: tambahkannya pada Jasad dahulu", + "ui.print_face_cleared": "{body}: muka cetakan dikosongkan", + "ui.print_face_input": "Muka cetakan", + "ui.print_face_pick": "Pilih satu muka rata pada jasad pepejal untuk menjadikannya muka cetakan", + "ui.print_face_set": "{body}: muka cetakan ditetapkan; Hantar ke penghiris meletakkan jasad di atasnya", "ui.profile": "Profil", "ui.profile_plane": "Satah Profil", "ui.profiles": "Profil", @@ -4383,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Mengukur…", + "ui.properties.measuring_bodies": "Mengukur… {done} daripada {total} jasad", "ui.properties.measuring_failed": "Pengukuran berhenti sebelum selesai.", "ui.properties.principal_axis": "Paksi utama {number}", "ui.properties.principal_moments": "Momen utama", @@ -4431,6 +5008,7 @@ "ui.revolve": "Putar", "ui.ribbon_exit": "Keluar", "ui.ribbon_labels": "Tunjukkan teks di bawah ikon reben", + "ui.ribbon_menus_skip_pinned": "Kecualikan arahan tersemat daripada menu lungsur", "ui.ribbon_pin_footer": "Arahan tersemat dipaparkan pada reben. Lalukan tetikus pada baris untuk menyemat atau menyahsemat.", "ui.ribbon_workspace": "Ruang kerja", "ui.right": "Kanan", @@ -4449,6 +5027,7 @@ "ui.selectOther": "Pilih Lain…", "ui.selectTangentChain": "Pilih Rantaian Tangen", "ui.select_all": "Pilih Semua", + "ui.select_components_by_face": "Pilih komponen (satu muka memilih komponennya)", "ui.selection": "Pilihan", "ui.selection_modifiers": "Pengubah suai pilihan", "ui.selection_shift_add_only": "Shift+klik menambah tanpa membuang", @@ -4474,6 +5053,7 @@ "ui.showDimension": "Papar Dimensi", "ui.showOrigin": "Papar Titik Asal", "ui.showPlanes": "Papar Satah", + "ui.show_component_history": "Papar Sejarahnya", "ui.show_constraints": "Kekangan", "ui.show_construction_geometries": "Geometri Binaan", "ui.show_dimensions": "Dimensi", @@ -4490,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Penapis Pilihan", "ui.sketch_modifiers": "Pengubah suai lakaran", "ui.sketch_project_geometry": "Geometri", + "ui.sketch_report.all_constrained": "Semuanya terkekang sepenuhnya.", + "ui.sketch_report.dof": "Darjah kebebasan", + "ui.sketch_report.loose": "Tidak terkekang sepenuhnya", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Laporan Lakaran", "ui.sketch_scale": "Skala Lakaran", "ui.sketches": "Lakaran", "ui.slice": "Hiris", @@ -4585,19 +5170,31 @@ "ui.view_angles": "Sudut pandangan", "ui.view_angles_convention": "Darjah pada paksi ke atas. Yaw 0° ialah pandangan Hadapan, 90° Kiri, −90° Kanan, 180° Belakang; pic 90° ialah pandangan Atas; gelek positif memutar model mengikut arah jam.", "ui.view_angles_help": "Memaparkan pic, yaw dan gelek pandangan dalam darjah serta unjurannya di bawah gizmo orientasi. Klik bacaan untuk menaip sudut yang tepat.", + "ui.view_angles_lock": "Kunci {axis}", "ui.view_angles_ortho": "Orto", "ui.view_angles_persp": "Persp", "ui.view_angles_pitch": "Pic", "ui.view_angles_readout": "Pic {pitch} · Yaw {yaw} · Gelek {roll}", "ui.view_angles_roll": "Gelek", + "ui.view_angles_unlock": "Buka kunci {axis}", "ui.view_angles_yaw": "Yaw", + "ui.view_angles_zero": "Tetapkan {axis} kepada 0°", "ui.view_centre": "Pusat pandangan", "ui.viewport_status_clear": "Matikan {name}", "ui.viewport_status_clear_hint": "Matikan {name} · Esc", + "ui.viewport_status_edges": "{count} tepi", + "ui.viewport_status_from": "dari {direction}", "ui.viewport_status_key": "Papar petunjuk untuk {name}", "ui.viewport_status_minimum_radius": "Jejari minimum", "ui.viewport_status_pairs": "{count} pasangan", + "ui.viewport_status_section_hatch": "{setting} · lorek", + "ui.viewport_status_section_plane": "Satah semasa", + "ui.viewport_status_section_tilted": "condong · {offset}", "ui.viewport_status_stripes": "{count} jalur", + "ui.viewport_status_summary_clear": "Matikan semuanya", + "ui.viewport_status_summary_heading": "Dalam pandangan ini", + "ui.viewport_status_summary_label": "{name} dan {count} item lagi", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Ikut tema", "ui.visual_shaded_hidden_edges": "Berlorek dengan tepi tersembunyi", "ui.visual_shaded_with_edges": "Berlorek dengan tepi", @@ -4634,10 +5231,12 @@ "update.button": "Kemas kini", "update.button_version": "Kemas kini ke {version}", "update.check_automatically": "Semak kemas kini secara automatik", + "update.check_for_updates": "Semak kemas kini", "update.check_now": "Semak sekarang", + "update.check_unavailable": "Semakan kemas kini tidak tersedia untuk pemasangan ini.", "update.checking": "Menyemak…", "update.copy": "Salin", - "update.dmg_opened": "Imej cakera telah dibuka dan disahkan: seret SolidCraft ke Applications untuk menggantikan salinan lama, kemudian mulakan semula SolidCraft.", + "update.dmg_opened": "Imej cakera telah dibuka dan disahkan: keluar dari SolidCraft, seret SolidCraft yang baharu ke Applications untuk menggantikan salinan lama, kemudian buka SolidCraft semula.", "update.download": "Muat turun", "update.download_open": "Muat turun dan buka", "update.downloading": "Memuat turun dan mengesahkan… {done} daripada {total} MB", @@ -4648,11 +5247,13 @@ "update.installed": "SolidCraft {version} telah dipasang. Mulakan semula untuk menggunakannya.", "update.installer_started": "Pemasang bermula apabila SolidCraft ditutup.", "update.later": "Ingatkan saya kemudian", + "update.managed": "Kemas kini tersedia: kemas kini SolidCraft dalam {manager}", "update.no_notes": "Tiada nota untuk keluaran ini.", "update.package_hint": "Salinan ini dipasang melalui {kind}. Muat turun pakej baharu, kemudian pasang dengan:", "update.prefs_dev": "Ini ialah binaan pembangunan ({version}). Semakan kemas kini tidak dilakukan.", "update.prefs_flatpak": "Flatpak mengemas kini {version}: jalankan {command} atau guna pusat perisian. SolidCraft tidak menyemak.", "update.prefs_label": "Kemas kini", + "update.prefs_managed": "Ini ialah SolidCraft {version}, diurus oleh {manager}. Semakan hanya meminta keluaran terkini daripada GitHub dan tidak menghantar apa-apa lagi; kemas kini SolidCraft dalam {manager}.", "update.prefs_note": "SolidCraft {version} ({kind}). Semakan hanya meminta keluaran terkini dari GitHub, tanpa data lain dihantar.", "update.prefs_web": "Muat semula halaman untuk mendapatkan aplikasi web terkini. Jika rangkaian tidak tersedia atau kemas kini tidak dapat selesai dimuat turun tepat pada masanya, versi yang disimpan dibuka sebaliknya; muat turun yang sedang berjalan diteruskan untuk muat semula seterusnya.", "update.refresh_checking": "Menyemak keluaran terbaharu…", @@ -4679,6 +5280,7 @@ "web.open_link": "Buka reka bentuk yang dipautkan?", "web.open_link_confirm": "Terdapat perubahan yang belum disimpan. Buka reka bentuk yang dipautkan dalam tab baharu?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ pilih · Enter / Tab lengkapkan · Esc tutup", + "↑ ↓ choose · Enter applies this value": "↑ ↓ pilih · Enter menggunakan nilai ini", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ pilih · Enter menggunakan apa yang anda taip · Esc tutup", "⌘Enter continues on GitHub.": "⌘Enter diteruskan di GitHub." } diff --git a/assets/locales/nb.json b/assets/locales/nb.json index 6a3e2c70d..997a1bf7a 100644 --- a/assets/locales/nb.json +++ b/assets/locales/nb.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "OVERGANGSFLATE", "BOUNDARY SURFACE": "GRENSEFLATE", "BROWSER": "MODELLTRE", + "Back to the original order": "Tilbake til opprinnelig rekkefølge", "Ball": "Kule", "Bar": "Stang", "Base Center": "Basesenter", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Design du åpner eller lagrer, vises her.", "Determined by To Object. Choose Angle to edit the angular extent.": "Bestemmes av Til objekt. Velg Vinkel for å endre vinkelutstrekningen.", "Diameter": "Diameter", + "Did this assembly open the wrong way up?": "Ble denne sammenstillingen åpnet feil vei opp?", + "Did this part open the wrong way up?": "Ble denne delen åpnet feil vei opp?", "Dimension new shapes": "Sett mål på nye figurer", "Direction": "Retning", "Discard": "Forkast", @@ -474,6 +477,7 @@ "Rectangular": "Rektangulær", "Rectangular Tube": "Rektangulært rør", "Reference face": "Referanseflate", + "Reference plane": "Referanseplan", "Relief Depth": "Avlastningsdybde", "Relief Width": "Avlastningsbredde", "Remove Tools": "Fjern verktøy", @@ -553,6 +557,7 @@ "Section": "Snitt", "Section (optional)": "Tverrsnitt (valgfritt)", "Section position": "Snittposisjon", + "Sections": "Tverrsnitt", "Sections (one sketch each)": "Tverrsnitt (én skisse hver)", "Select Other": "Velg annet", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Velg annet: Hold venstre museknapp inne uten å flytte pekeren på modellen (eller høyreklikk › Velg annet…) for å vise alt under markøren. Klikk på samme sted igjen for å velge neste objekt. Dobbeltklikk med midtknappen for å gå til hjemvisningen (Innstillinger › Navigasjon).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Fang til flate- og kantsentre", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft kan ikke sende inn rapporter direkte. Send inn på GitHub; ingen token trengs i appen.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft ble lukket før disse designene ble lagret. Du kan åpne den siste automatisk lagrede versjonen av hvert design.", + "Sort A to Z": "Sorter A til Å", + "Sort Z to A": "Sorter Å til A", "Spacing 2 must be a non-zero number": "Avstand 2 må være et tall forskjellig fra null", "Spacing must be a non-zero number": "Avstand må være et tall forskjellig fra null", "Specialise": "Spesialiser", @@ -601,6 +608,7 @@ "Square": "Kvadrat", "Stand it up": "Reis den opp", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Reis den opp: en kvart omdreining om X, som én Flytt-funksjon du kan angre.", + "Stand this assembly up?": "Reise denne sammenstillingen opp?", "Stand this part up?": "Reise denne delen opp?", "Start angle": "Startvinkel", "Start bulge": "Utbuling ved starten", @@ -772,6 +780,8 @@ "at the face": "ved flaten", "bom.group_children": "Underdeler i raden til overordnet del", "browser.body_name": "Kropp{number}", + "browser.calibrate_click_a": "Klikk på bildet for punkt A, eller skriv inn koordinatene.", + "browser.calibrate_click_b": "Klikk på bildet for punkt B, eller skriv inn koordinatene.", "browser.calibrate_title": "Kalibrer: {name}", "browser.capture_many": "{count} komponenter er flyttet, men de nye posisjonene er ikke registrert.", "browser.capture_note": "Registrer posisjon beholder den nye posisjonen. Tilbakestill gjenoppretter den forrige.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (tilknytning mistet)", "browser.sketch_editing": "{name} (redigeres)", "browser.sketch_name": "Skisse{number}", + "browser.sketches_to_parts_already_in_part": "allerede i delen sin", + "browser.sketches_to_parts_design_body": "på en kropp i selve designet", + "browser.sketches_to_parts_moved": "Flyttet {moved} skisser til delen de ligger på", + "browser.sketches_to_parts_no_exact_attachment": "på en flate uten nøyaktig tilknytning", + "browser.sketches_to_parts_not_on_face": "ikke på flaten til en del", + "browser.sketches_to_parts_part_missing": "delen finnes ikke lenger", + "browser.sketches_to_parts_result": "Flyttet {moved} skisser til delen de ligger på; {stayed} ble liggende: {why}", "browser.units": "Enheter: {units}", "cam.flat": "Plan flate", "cam.follower": "Følger", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Plukk opp utseende", "cmd.appearance_replace": "Erstatt utseende", "cmd.assembly_bom": "Stykkliste", + "cmd.assembly_mass_properties": "Masseegenskaper", + "cmd.body.print_face": "Utskriftsflate", "cmd.body_rename": "Gi nytt navn til kropp", "cmd.browser_collapse_all": "Skjul alle", "cmd.browser_expand_all": "Utvid alle", @@ -842,6 +861,7 @@ "cmd.component_extract": "Trekk ut til fil", "cmd.component_finish_edit": "Fullfør redigering", "cmd.component_from_bodies": "Opprett komponenter fra kropper", + "cmd.component_hide_history": "Skjul komponentens tidslinje", "cmd.component_insert_design": "Sett inn design", "cmd.component_links": "Vis koblinger", "cmd.component_list": "Vis komponenter", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Flytt kropper til komponent", "cmd.component_move_features": "Flytt funksjoner til komponent", "cmd.component_move_sketches": "Flytt skisser til komponent", + "cmd.component_move_sketches_to_parts": "Flytt skisser til delene deres", "cmd.component_paste_from_design": "Lim inn fra et annet design", "cmd.component_paste_new": "Lim inn ny", "cmd.component_properties": "Fysiske egenskaper for komponent", @@ -857,6 +878,7 @@ "cmd.component_rename": "Gi nytt navn til komponent", "cmd.component_replace_with_link": "Erstatt med lenke", "cmd.component_revert_position": "Tilbakestill posisjon", + "cmd.component_show_history": "Vis komponentens tidslinje", "cmd.component_unlock": "Lås opp innhold", "cmd.component_update_links": "Oppdater koblinger", "cmd.config_activate": "Aktiver konfigurasjon", @@ -867,6 +889,7 @@ "cmd.config_rule": "Konfigurasjonsregel", "cmd.config_rules": "Konfigurasjonsregler", "cmd.config_table": "Vis konfigurasjonstabell", + "cmd.construct.plane.axis_point": "Plan gjennom akse og punkt", "cmd.construct_axis_edge": "Akse gjennom kant", "cmd.construct_axis_normal_to_face": "Akse vinkelrett på flate", "cmd.construct_axis_through_cylinder": "Akse gjennom sylinder/kjegle/torus", @@ -915,6 +938,11 @@ "cmd.explode_show": "Vis eksplodert visning", "cmd.expr_evaluate": "Evaluer uttrykk", "cmd.face_delete": "Slett flate", + "cmd.file.export_3mf": "Eksporter 3MF", + "cmd.file.export_obj": "Eksporter OBJ", + "cmd.file.export_step": "Eksporter STEP", + "cmd.file.export_stl": "Eksporter STL", + "cmd.file.export_urdf": "Eksporter URDF", "cmd.file_export": "Eksporter", "cmd.file_insert_mesh": "Sett inn mesh", "cmd.file_insert_step": "Sett inn STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Aktiver komponentfarger", "cmd.inspect_colored_components_disable": "Deaktiver komponentfarger", "cmd.inspect_compare": "Sammenlign kropper", + "cmd.inspect_compare_picture": "Sammenlign bilde", "cmd.inspect_continuity": "Kontinuitetsanalyse", "cmd.inspect_curvature_comb": "Analyse med krumningskam", "cmd.inspect_curvature_map": "Analyse med krumningskart", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Rediger punktsky", "cmd.pointcloud_insert": "Sett inn punktsky", "cmd.pointcloud_list": "Punktskyer", + "cmd.render.compare.divider": "Flytt skillelinjen i rendringssammenligningen", + "cmd.render.result.discard": "Forkast rendringsresultat", + "cmd.render.result.select": "Velg rendringsresultat", "cmd.render_aging_describe": "Lagdelt overflatealdring", "cmd.render_backends": "Rendringsmotorer", "cmd.render_batch": "Rendre alle opptak", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline med kontrollpunkter (grad 5)", "cmd.sketch_spline_fit_point": "Spline gjennom punkter", "cmd.sketch_spline_insert_point": "Legg til splinepunkt", + "cmd.sketch_spline_remove_point": "Fjern splinepunkt", "cmd.sketch_spline_reverse": "Reverser splineretning", "cmd.sketch_spun_profile": "Dreid profil", "cmd.sketch_toggle_diameter": "Veksle mellom radius / diameter", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Flytt tidslinjemarkør", "cmd.timeline_stop": "Stopp avspilling av tidslinje", "cmd.timeline_suppress": "Undertrykk funksjon", + "cmd.ui.assistant": "Vis/skjul assistent", "cmd.view.render_browser": "Rendringsutforsker", "cmd.view.render_dock": "Flytt rendringspanel", "cmd.view.render_focus": "Rendringsfokusvisning", + "cmd.view.status_details": "Statusdetaljer i visningsområdet", "cmd.view.status_items": "Statuselementer i visningsområdet", "cmd.view_ambient_occlusion": "Ambient occlusion", "cmd.view_angle_readout": "Visningsvinkler", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Navigasjonsverktøy", "cmd.view_top": "Toppvisning", "cmd.view_visual_style": "Visuell stil", + "color.blue": "Blå", "color.copy": "Klikk for å kopiere fargeverdier", "color.edit": "Klikk for å redigere farge", "color.gamma": "Viser gammakorrigerte fargeverdier i området 0–255", + "color.green": "Grønn", "color.hex": "Hex", "color.hex_help": "Skriv inn #rrggbb eller #rrggbbaa; seks sifre beholder opasiteten", "color.hex_hint": "#rrggbb", "color.hue": "Kulør", "color.linear": "Viser lineære fargeverdier i området 0–1", + "color.recent": "Nylige farger", + "color.recent_help": "Fargene du velger i et fargefelt, vises her", + "color.red": "Rød", + "color.saturation": "Metning (prosent)", "color.saturation_value": "Metning og lysverdi", "color.selected": "Valgt farge", + "color.step_down": "Ett trinn ned", + "color.step_up": "Ett trinn opp", + "color.value": "Lysverdi, lysstyrken (prosent)", "config.column_filter_empty": "Ingen samsvarende kolonner", + "config.rule_parameter_columns": "Bare parametere som har en kolonne i tabellen, er med i listen. Legg til en kolonne med Legg til kolonne (+) for å bruke parameteren her.", + "config.rule_suppression_columns": "Bare funksjoner som har en Undertrykk-kolonne i tabellen, er med i listen. Legg til en kolonne med Legg til kolonne (+) for å styre undertrykkingen her.", "contact.components_count": "{count} komponenter", "contact.enabled_label": "aktivert", "coupling.gear_1": "Tannhjul 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Klikk på et annet styrende mål for å sette inn navnet", "dialog.dimension_name": "Mål: {name}", "dialog.edit_title": "REDIGER {title}", + "dialog.no_shown_body": "Ingen synlig kropp å endre: vis en, eller velg Ny kropp", + "dialog.pattern_sketch_not_object": "Velg kropper eller funksjoner: en skisse er ingen av delene. Gjenta kurvene med skissens eget Mønster eller Speil, eller ekstruder den først.", "dialog.select": "↖ Velg", "dialog.selected_count": "↖ {count} valgt", + "dialog.selection_constraint": "Binding {id}", + "dialog.selection_external_curve": "{sketch} · kurve {id}", "dialog.selection_guidance": "Velg et felt for å endre det. Klikk på valgte objekter for å fjerne dem fra utvalget; Ctrl/Cmd+klikk veksler også mellom valgt og ikke valgt. Se over forhåndsvisningen, og trykk deretter OK.", + "dialog.selection_midpoint": "Midtpunkt · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} av {total}: Velg {input}", "dialog.step": "Trinn", "document.changed_on_disk": "{name} er endret på disken", @@ -1380,26 +1432,244 @@ "from the rule": "fra regelen", "help.apache": "Apache-lisens 2.0", "help.appearance.assign": "Gir de valgte kroppene, flatene eller komponentene en farge eller et materialutseende, uten å endre vekten deres. Bruk det til å skille deler fra hverandre eller til å forhåndsvise en overflatebehandling.", + "help.assembly.bom": "Lister opp delene i designet eller en komponent med antall, gruppert etter delenummer, og kan lagre listen som CSV eller JSON. Bruk det som stykkliste ved bestilling og montering.", "help.attributions": "Opphav og lisenser (ATTRIBUTION.md)", "help.build": "Versjon {version} · commit {commit} · bygget {date}", + "help.canvas.decal": "Plasserer et bilde på en plan flate av modellen, som et klistremerke. Bruk det til å vise en etikett, en logo eller et trykt mønster på en del.", + "help.canvas.edit": "Endrer et lerret: posisjon, størrelse, vinkel, opasitet, speiling, synlighet eller navn. Bruk det til å justere et referansebilde mot skissen du tegner over det.", + "help.canvas.insert": "Plasserer et PNG- eller JPEG-bilde på et plan eller en flate som en gjennomsiktig referanse. Bruk det til å tegne av et foto eller en tegning i en skisse, med bildet skalert til en kjent størrelse.", + "help.component.break_link": "Løsner en koblet komponent fra designfilen sin og beholder kroppene som de er. Bruk det når delen ikke lenger skal følge endringer i originalfilen.", + "help.component.capture_position": "Beholder posisjonene til delene du har flyttet for hånd, slik at de blir der delene står. Bruk det etter at du har dratt deler på plass som ikke holdes av noe ledd.", + "help.component.create": "Legger til en ny, tom komponent i designet, inni den aktive komponenten med mindre du velger en annen overordnet komponent. Bruk det til å gi en ny del av en sammenstilling sin egen plass for kropper og skisser.", "help.component.finish_edit": "Lagrer delen du redigerer på stedet, går tilbake til sammenstillingen og oppdaterer sammenstillingen fra den. Bruk den når endringene dine i den koblede delen er ferdige.", + "help.component.from_bodies": "Gjør hver valgte kropp til en egen komponent, oppkalt etter kroppen. Bruk det når et design bygget av løse kropper skal bli en sammenstilling der delene kan kobles sammen med ledd og flyttes.", + "help.component.insert_design": "Setter inn et annet lagret design som en komponent koblet til filen sin, med volumkroppene plassert som de står der. Bruk det til å gjenbruke en del i en sammenstilling og få med senere endringer med Oppdater koblinger.", + "help.component.properties": "Viser volum, masse, massesenter og treghetsmomenter for en komponent, ut fra materialene til kroppene. Bruk det til å sjekke vekt og balanse i en sammenstilling.", + "help.component.revert_position": "Setter delene du har flyttet for hånd tilbake dit de var, og forkaster flyttinger som ikke ble registrert. Bruk det til å angre prøveflyttinger i en sammenstilling.", + "help.component.update_links": "Leser de koblede designfilene på nytt og erstatter kropper som er endret. Bruk det etter at du har redigert en del som denne sammenstillingen bruker.", + "help.config.configure": "Legger til parametere, funksjoner, materialer eller utseender som kolonner i konfigurasjonstabellen. Bruk det til å bygge varianter av ett design, for eksempel størrelser av en del.", + "help.config.preview": "Sjekker at en rad i konfigurasjonstabellen kan bygges på nytt, uten å endre designet eller historikken. Bruk det før du bytter til en variant du er usikker på.", + "help.config.rules": "Viser reglene i konfigurasjonstabellen, radene og hvilken rad som er aktiv. Bruk det til å se hvordan variantene av et design er satt opp.", + "help.config.table": "Viser konfigurasjonstabellen: én rad per variant, én kolonne per parameter eller funksjon, og om designet fortsatt samsvarer med den aktive raden. Bruk det til å gå gjennom variantene av et design.", "help.connect_note": "Start hver assistent på nytt for å laste inn SolidCraft-serveren. Hver fil ble sikkerhetskopiert som .bak før den ble endret.", "help.connect_title": "Koble til AI-assistenter", + "help.construct.axis.edge": "Oppretter en hjelpeakse langs en rett kant eller skisselinje. Bruk den som akse for en omdreining, et sirkulært mønster eller et ledd.", + "help.construct.axis.normal_to_face": "Oppretter en hjelpeakse gjennom et punkt, vinkelrett på en flate. Bruk den som en akse som står rett ut fra en overflate.", + "help.construct.axis.through_cylinder": "Oppretter en hjelpeakse gjennom senteret av en sylinder-, kjegle- eller torusflate, eller en sirkulær kant. Bruk den til å dreie funksjoner eller lage mønster av dem rundt en rund del.", + "help.construct.axis.two_planes": "Oppretter en hjelpeakse der to plan eller plane flater møtes. Bruk den når aksen du trenger er linjen mellom to flater.", + "help.construct.axis.two_points": "Oppretter en hjelpeakse gjennom to punkter, hjørner eller skissepunkter. Bruk den til en akse mellom to kjente posisjoner.", + "help.construct.plane.along_path": "Oppretter et hjelpeplan vinkelrett på en kant eller kurve, på en posisjon langs den. Bruk det til å skisse en profil for en sweep eller et snitt av en bane.", + "help.construct.plane.at_angle": "Oppretter et hjelpeplan vridd med en vinkel fra et plan eller en flate, om en akse eller kant. Bruk det til skråstilte skisser, for eksempel en vinklet brakett.", + "help.construct.plane.axis_point": "Oppretter et hjelpeplan som inneholder en akse og et punkt utenfor aksen. Velg en origoakse eller hjelpeakse, en rett kant eller skisselinje, og deretter et hjørne, skissepunkt eller hjelpepunkt. Et punkt på aksen kan ikke definere et entydig plan.", + "help.construct.plane.midplane": "Oppretter et hjelpeplan midt mellom to plan eller plane flater, eller som halverer dem der de møtes i en vinkel. Bruk det som symmetriplan for speiling.", + "help.construct.plane.offset": "Oppretter et hjelpeplan parallelt med et plan eller en plan flate, i en avstand eller gjennom et punkt. Bruk det til å skisse i en bestemt høyde over en flate.", + "help.construct.plane.perpendicular": "Oppretter et hjelpeplan som inneholder en linje eller kant og står vinkelrett på et plan eller en flate. Bruk det til å skisse oppreist på en modell langs en kant.", + "help.construct.plane.tangent": "Oppretter et hjelpeplan som berører en sylinder, kjegle, kule eller torus i et punkt. Bruk det til å skisse på siden av en rund del.", + "help.construct.plane.three_points": "Oppretter et hjelpeplan gjennom tre punkter. Bruk det til et plan som bestemmes av posisjoner på modellen, for eksempel tre hjørner.", + "help.construct.plane.two_edges": "Oppretter et hjelpeplan gjennom to rette kanter eller linjer som ligger i ett plan. Bruk det til et plan på tvers av en del, for eksempel gjennom to motstående kanter.", + "help.construct.point.along_path": "Oppretter et hjelpepunkt på en posisjon langs en kant eller kurve. Bruk det som referanse et stykke ut langs en bane.", + "help.construct.point.center": "Oppretter et hjelpepunkt i senteret av en sirkulær kant, skissesirkel eller bue, kule eller torus. Bruk det som referanse for hull, akser og ledd.", + "help.construct.point.edge_plane": "Oppretter et hjelpepunkt der en kant eller linje går gjennom et plan eller en plan flate. Bruk det til å markere hvor en bane krysser et plan.", + "help.construct.point.three_planes": "Oppretter et hjelpepunkt der tre plan eller plane flater møtes. Bruk det som hjørnereferanse, selv der modellen ikke har noe hjørne.", + "help.construct.point.two_edges": "Oppretter et hjelpepunkt der to kanter eller linjer møtes, eller kommer nærmest hverandre. Bruk det som referanse i et virtuelt hjørne.", + "help.construct.point.vertex": "Oppretter et hjelpepunkt på et hjørne eller skissepunkt. Bruk det som en referanse som blir stående når skissen eller kroppen rundt er skjult.", + "help.contact.check": "Lister opp parene av deler i kontaktsett som går gjennom hverandre i gjeldende posisjon. Bruk det til å finne kollisjoner før du driver ledd eller kjører en bevegelsesanalyse.", + "help.contact.create": "Grupperer to eller flere deler i et kontaktsett, der kroppene hindres i å gå gjennom hverandre mens leddene beveger seg. Bruk det til deler som skal stoppe når de berører hverandre, for eksempel en spak mot stoppen sin.", + "help.contact.disable_all": "Slår av kontakt, slik at drevne ledd og bevegelsesanalyser ikke lenger stopper der delene berører hverandre. Bruk det til å flytte delene fritt igjen, eller til å holde en stor sammenstilling responsiv.", + "help.contact.edit": "Endrer et kontaktsett: delene det inneholder, navnet eller om det er undertrykt; det kan også slette settet. Bruk det til å justere hvilke deler som hindres i å gå gjennom hverandre.", + "help.contact.enable_all": "Legger alle delene i sammenstillingen i ett kontaktsett, slik at ingen to deler kan gå gjennom hverandre mens leddene beveger seg. Bruk det til en rask kontroll av en hel mekanisme.", + "help.contact.enable_sets": "Slår på kontakt for kontaktsettene du har definert, slik at drevne ledd og bevegelsesanalyser stopper der delene deres ville gått gjennom hverandre. Bruk det til å få tilbake settene dine etter at du har slått av kontakt.", + "help.contact.list": "Lister opp kontaktsettene i designet, delene i hvert av dem og om kontakt er slått på. Bruk det til å sjekke hvordan kontakt er satt opp før du driver sammenstillingen.", + "help.document.inspect": "Viser en oversikt over designet: komponenter, kropper, skisser, funksjoner og parametere. Bruk det til å få oversikt i et design du ikke har bygget selv.", + "help.document.units": "Endrer enhetene designet viser lengder i, for eksempel mm eller tommer. Geometrien beholder størrelsen sin; bare visningen og vanlige tall følger med.", + "help.edit.checkpoint": "Husker designet, den aktive skissen og angrehistorikken slik de er nå. Bruk det før du prøver noe risikabelt som du kanskje vil gå tilbake fra.", + "help.edit.restore_checkpoint": "Går tilbake til et sjekkpunkt, inkludert angrehistorikken. Bruk det til å forkaste alt som er gjort siden sjekkpunktet, i ett trinn.", + "help.explode.create": "Oppretter en eksplodert visning som skyver delene bort fra sentrum av sammenstillingen, eller etter flyttingene du angir. Bruk det til å vise hvordan en sammenstilling settes sammen, i veiledninger eller presentasjoner.", "help.face.delete": "Fjerner de valgte flatene og lar naboflatene lukke åpningen, eller lar åpningen stå igjen som en flate. Bruk det til å fjerne en avrundet kant, et hull eller en forhøyning som er i veien.", + "help.file.insert_mesh": "Legger en 3MF-, STL-, OBJ-, PLY- eller glTF-fil til i designet som nettkropper i en ny komponent. Bruk det til å plassere en nedlastet eller skannet modell ved siden av designet ditt som referanse.", + "help.file.insert_step": "Legger en STEP-, IGES-, FreeCAD- eller Rhino-fil til i designet som volumkropper i en ny komponent; delene i en sammenstilling blir nestede komponenter. Bruk det til å hente inn modeller fra leverandører eller andre CAD-programmer.", + "help.file.save_mesh": "Lagrer kropper som et STL-, 3MF- eller OBJ-mesh, med den jevnheten på krumme flater du velger. Bruk det til å forberede deler for 3D-printing eller for programmer som leser mesher.", + "help.file.send_to_slicer": "Lagrer de valgte kroppene som en 3MF-fil og åpner den i slicer-programmet du velger. Bruk det til å gå fra modell til utskrift i ett trinn.", "help.font_details": "Grensesnittet bruker de innebygde skriftene i egui (Ubuntu Light og Hack, under Ubuntu Font Licence og MIT/Bitstream Vera-lisensen; Noto Emoji og skriften med emoji-ikoner, under OFL og MIT). Skissetekst bruker Liberation Sans (SIL OFL 1.1). Crafting Apps sin valgfrie skriftpakke, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), følger ikke med i SolidCraft.", "help.fonts": "Skrifter", + "help.frame.member": "Plasserer en profil, for eksempel et rør eller en aluminiumsprofil, langs linjene i en rammeskisse, ett element per linje. Bruk det til å bygge rammer, stativer og sveisede konstruksjoner.", + "help.inspect.accessibility": "Fargelegger flatene et verktøy kan nå fra én retning, og de det ikke kan nå. Bruk det til å sjekke en del for maskinering eller støping fra den siden.", + "help.inspect.center_of_mass": "Viser massesenteret til kropper, hver for seg og alle samlet, ved jevn tetthet. Bruk det til å sjekke balansen og hvor en del vil velte.", + "help.inspect.colored_components": "Gir hver komponent sin egen midlertidige farge, uten å endre utseender. Bruk det til å se forskjell på delene i en sammenstilling med et blikk.", + "help.inspect.compare": "Sammenligner to kropper og viser hvor den ene har materiale som den andre ikke har, med volum og avvik. Bruk det til å sjekke en endret eller importert del mot originalen.", + "help.inspect.continuity": "Sjekker hvor jevnt flater møtes langs kantene sine: mellomrom, knekk eller krumningssprang, og fargelegger skjøtene. Bruk det til å finne hvor flater ikke går rent sammen.", + "help.inspect.curvature_comb": "Tegner kammer langs kurver, kanter eller flater, der tennene viser hvor sterkt de bøyer. Bruk det til å oppdage flate partier, knekk og ujevn krumning.", + "help.inspect.curvature_map": "Fargelegger flater etter hvor sterkt de krummer, rødt der radiusen er liten. Bruk det til å finne trange partier og vurdere hvor jevn en flate er.", + "help.inspect.draft": "Fargelegger flater etter slippvinkelen til en trekkretning og markerer de som har for liten. Bruk det til å sjekke en del før støping.", + "help.inspect.environment_map": "Viser modellen med en reflekterende, speillignende finish. Bruk det til å vurdere hvordan flatene flyter, ut fra hvordan refleksjonene løper over dem.", + "help.inspect.interference": "Finner kropper som overlapper og viser hver overlapping med volum. Bruk det til å sjekke en sammenstilling for deler som kolliderer.", + "help.inspect.isocurve": "Tegner de isoparametriske kurvene på flater, rutenettet flaten er bygget på. Bruk det til å se hvordan en flate flyter og hvor kurvene samler seg tett.", + "help.inspect.measure": "Måler lengder, avstander, vinkler, areal og radier mellom det du velger, eller volumet og massen til kropper. Bruk det til å sjekke størrelser og klaringer.", + "help.inspect.minimum_radius": "Finner den minste krumningsradiusen til kurver, kanter eller flater, og hvor den er. Bruk det til å sjekke at et verktøy eller en dyse kan følge formen.", + "help.inspect.section": "Skjærer visningen åpen langs et plan og skraverer snittflatene, uten å endre modellen. Bruk det til å se inn i deler og sammenstillinger.", + "help.inspect.zebra": "Viser svarte og hvite striper reflektert på flatene til modellen. Bruk det til å vurdere jevnheten: striper som brytes eller knekker ved en kant, viser en dårlig overgang.", + "help.joint.as_built": "Forbinder to deler der de allerede står, uten å flytte noen av dem, og angir hvordan de fortsatt kan bevege seg. Bruk det til deler du allerede har plassert i sluttposisjonen.", + "help.joint.cam": "Kobler en dreiende kam til en følger, slik at følgeren glir eller svinger når kamprofilen passerer under den. Bruk det til kammer, eksentre og ventildrifter.", + "help.joint.create": "Forbinder to deler ved leddorigoene du velger og flytter den andre delen på plass; leddtypen bestemmer hvordan de fortsatt kan bevege seg. Bruk det til å bygge en sammenstilling der delene beveger seg som den virkelige mekanismen.", + "help.joint.drive": "Setter vinkelen eller avstanden til et ledd og flytter delene med det, innenfor grensene; koblede ledd og lukkede sløyfer følger med. Bruk det til å sjekke at en mekanisme beveger seg som tenkt.", + "help.joint.gear": "Kobler to dreiende ledd med et utvekslingsforhold, slik at drift av det ene dreier det andre. Bruk det til rette tannhjul og ringhjul, med forholdet fra delesirkelradier eller tannantall.", + "help.joint.limits": "Setter hvor langt et ledd kan dreie eller gli, som minimum og maksimum, eller fjerner grensene. Bruk det til å holde et hengsel, et glidende ledd eller en spak innenfor det virkelige bevegelsesområdet.", + "help.joint.motion_link": "Kobler to ledd med et forhold og en forskyvning, slik at drift av det ene flytter det andre. Bruk det til en fast sammenheng mellom ledd som Tannhjul, Tannstang og drev eller Skrue ikke dekker.", + "help.joint.origin": "Plasserer en navngitt leddorigo på en del: i senteret av en flate eller rund ende, midt på en kant, i et hjørne eller i et punkt. Bruk det til å forberede hvor ledd festes; en valgt på en flate følger flaten når delen endrer størrelse.", + "help.joint.rack_pinion": "Kobler et dreiende drev til en glidende tannstang, slik at stangen flytter seg like langt som delesirkelen drevet ruller gjennom. Bruk det til tannstangdrifter, styring og lineære akser.", + "help.joint.reach": "Flytter et punkt på en del mot et mål ved å endre leddene i kjeden, innenfor grensene deres. Bruk det til å stille en mekanisme etter hvor enden skal være, for eksempel spissen på en robotarm.", + "help.joint.rigid_group": "Låser de valgte delene sammen slik de er, så de beveger seg som én. Bruk det til deler som hører sammen og ikke skal bevege seg i forhold til hverandre.", + "help.joint.screw": "Kobler dreining og glidning med en stigning, slik at hver omdreining flytter like langt som stigningen. Bruk det til ledeskruer, bolter og gjengede spindler.", + "help.library.apply": "Bruker et materiale eller utseende fra en lokal bibliotekfil på kropper, flater eller komponenter. Bruk det til å gjenbruke materialer du har lagret fra et annet design.", + "help.library.export": "Lagrer materialene og utseendene i designet til en bibliotekfil. Bruk det til å dele dem eller gjenbruke dem i andre design.", + "help.library.inspect": "Sjekker en bibliotekfil og lister opp materialene og utseendene i den, uten å endre designet. Bruk det til å se hva et bibliotek inneholder før du bruker det.", "help.licences": "Lisenser", "help.material.assign": "Angir hva de valgte kroppene er laget av, for eksempel stål, aluminium eller ABS. Bruk det slik at masse og vekt stemmer med den virkelige delen.", + "help.material.properties.validate": "Sjekker et materialdatakort for konsistente tall og manglende verdier. Bruk det før du stoler på dataene for masse eller stivhet.", + "help.mesh.convert": "Bygger en nettkropp, for eksempel en STL, om til en redigerbar volumkropp med plane og sylindriske flater. Bruk det til å endre importerte mekaniske deler som en modellert kropp.", "help.mit": "MIT-lisens", + "help.motion.study": "Setter leddverdier ved trinn langs en tidslinje og spiller dem av som en animasjon. Bruk det til å se en mekanisme bevege seg gjennom en sekvens og sjekke klaringer underveis.", + "help.motion.trace": "Sporer banen et punkt på en del følger mens en bevegelsesanalyse spilles av eller et ledd drives, og beholder den som en kurve i en 3D-skisse når du bekrefter. Bruk det til å se hvor en mekanisme når, eller til å bygge videre på banen.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fester en del på plass, eller frigjør den igjen, slik at ledd flytter de andre delene rundt den. Bruk det til rammen eller basen resten av sammenstillingen bygges på.", "help.occurrence.move": "Flytter en del i en sammenstilling bare langs frihetsgradene som leddene tillater. Velg en flate på delen, og dra deretter en tilgjengelig pil eller bue.", "help.parameters.change": "Åpner tabellen over navngitte verdier og uttrykk som styrer målene i designet. Bruk den til å endre en størrelse ett sted og la alle funksjoner som bruker den følge med.", + "help.parameters.export": "Lagrer parameterne i designet som CSV eller JSON. Bruk det til å redigere dem i et regneark eller flytte dem til et annet design.", + "help.parameters.graph": "Viser hvilke parametere og funksjoner som bruker hvilke andre, og eventuelle sløyfer eller feil blant dem. Bruk det til å se hva en endring av en parameter vil påvirke.", + "help.parameters.import": "Leser parametere fra CSV eller JSON inn i designet, alle eller ingen. Bruk det til å hente inn verdier fra et regneark eller et annet design.", + "help.parameters.move": "Flytter en brukerparameter før eller etter en annen i listen. Bruk det til å holde relaterte parametere sammen.", + "help.parts.fastener": "Legger til en standard skrue, bolt, mutter, skive, stift eller et lager i størrelsen du velger. Plassert på et hull sitter det i hullet med et ledd, så du slipper å modellere festemidler selv.", + "help.parts.insert": "Setter inn en standarddel i familien, størrelsen og lengden du velger. Plassert på kanten eller veggen av et hull sitter den på hullet med et stivt ledd.", + "help.parts.library": "Åpner standarddelene: skruer, bolter, muttere, skiver, settskruer, passtifter og lagre i standardstørrelser. Bruk det til å legge til en standarddel i stedet for å modellere den selv.", + "help.parts.resize": "Endrer størrelsen eller lengden på en innsatt standarddel og bygger den på nytt; leddene holder den på plass. Bruk det når en skrue viser seg å være for lang eller et hull trenger en annen størrelse.", + "help.plastic.assign_rule": "Tildeler en plastregel til kropper, slik at plastfunksjonene deres bruker slippvinkelen og klaringen fra den som standard. Bruk det til å sette opp en støpt del én gang for alle funksjonene.", + "help.plastic.boss": "Legger til et skruefeste på en flate: en stolpe med valgfritt hull, slippvinkel, avrunding i foten og støttende ribber. Bruk det til skruepunkter i støpte eller utskrevne hus.", + "help.plastic.lip": "Legger til en leppekant eller et tilsvarende spor langs kanten av en uthulet kropp. Bruk det slik at to husdeler plasserer seg mot hverandre og lukker tett.", + "help.plastic.manage_rules": "Oppretter og redigerer plastregler: materiale, veggtykkelse, radier, klaring og slippvinkel. Bruk dem til å holde funksjonene i en støpt del konsistente.", + "help.plastic.rest": "Legger til et anlegg på en flate: en rund eller rektangulær pute, massiv eller hul, med slippvinkel. Bruk det som støtte eller avstandsstykke i et støpt hus.", + "help.plastic.snap_fit": "Legger til en snap-fit-krok på en flate, med lengde, tykkelse og hake. Bruk det til å klikke deler sammen uten skruer.", "help.pointcloud.insert": "Sett inn en PLY-, XYZ- eller PTS-skanning som en punktsky ved siden av modellen. Bruk den som referanse når du bygger en modell fra måledata.", + "help.sheet.convert": "Gjør en plate eller en uthulet kropp med jevn tykkelse om til en platekropp, med bøyninger ved kantene du velger. Bruk det til å gjøre en eksisterende del utbrettbar.", + "help.sheet.export_bend_table": "Lagrer bøyetabellen til en platekropp som CSV eller JSON: vinkler, radier og bøyeposisjoner i utbrettingen. Bruk det til kantpressen eller verkstedet.", + "help.sheet.export_dxf": "Lagrer utbrettingen som en DXF, med konturer, bøyelinjer og valgfrie bøyenotater. Bruk det til laser-, plasma- eller vannskjæring.", + "help.sheet.flange": "Legger til en flens: en grunnplate fra en skisse, en vegg langs en åpen skissekontur eller en bøyd vegg på platekanter. Bruk det til å bygge opp platedeler.", + "help.sheet.flat_pattern": "Oppretter utbrettingen av en platekropp, med størrelse, utsparinger og bøyelinjer. Bruk det til å sjekke emnet før du skjærer det ut.", + "help.sheet.fold": "Bøyer en plate langs en skisselinje med en vinkel og en radius. Bruk det til å brette en flat plate etter at du har lagt utskjæringer i den.", + "help.sheet.hem": "Bretter en platekant tilbake over seg selv. Bruk det til trygge, stive kanter uten skarpe grater.", + "help.sheet.manage_rules": "Oppretter og redigerer plateregler: tykkelse, bøyeradius, K-faktor, avlastninger og mellomrom. Bruk dem til å tilpasse materialet og verktøyene i verkstedet ditt.", + "help.sheet.path_flange": "Legger til en kjede av flenser langs en platekant, etter en åpen kjede av skisselinjer. Bruk det til profiler som en U- eller Z-form i ett trinn.", + "help.sheet.perforate": "Legger til et felt av hull over hele den flate platen, i et forskjøvet eller kvadratisk mønster. Bruk det til ventilasjon, gitter og lettere paneler.", + "help.sheet.refold": "Bretter en utbrettet platekropp sammen igjen. Bruk det etter at du har lagt funksjoner til den flate platen.", + "help.sheet.unfold": "Bretter ut alle bøyninger i en platekropp. Bruk det til å legge til hull eller skjæringer som må krysse en bøyning, og brett deretter sammen igjen.", + "help.sketch.arc.center_point": "Tegner en sirkelbue rundt et senterpunkt, fra et startpunkt til et sluttpunkt. Bruk det når buens senter er kjent, for eksempel en radius rundt et hull eller en dreietapp.", + "help.sketch.arc.tangent": "Tegner en bue som starter ved enden av en linje eller bue og fortsetter tangentielt. Bruk det til å føre en kjede videre med en jevn bøy i stedet for et hjørne.", + "help.sketch.arc.three_point": "Tegner en bue fra et startpunkt til et sluttpunkt gjennom et tredje punkt. Bruk det når buen må gå gjennom gitte punkter i stedet for rundt et kjent senter.", + "help.sketch.arc3d": "Tegner en eksakt sirkelbue i rommet gjennom tre punkter, med 3D-skisse slått på. Bruk det til svinger i baner og føringskurver som forlater skisseplanet.", + "help.sketch.auto_constrain": "Legger til bindingene skissen nesten har fra før, som vannrett, parallell eller sammenfallende, og setter deretter mål på den til den er fullt bestemt. Bruk det til å låse en grovt tegnet skisse i ett trinn.", + "help.sketch.auto_constrain_from_datum": "Fungerer som Automatiske bindinger, men måler posisjonene fra et referansepunkt du velger i stedet for origo. Bruk det når delen er lagt ut fra ett referansepunkt, for eksempel et hjørne eller et hull.", + "help.sketch.blend_curve": "Forbinder endene på to kurver med en jevn spline som er tangent til begge, eller også krumningskontinuerlig hvis du velger det. Bruk det til å bygge bro over et mellomrom mellom kurver uten knekk.", + "help.sketch.break": "Deler en kurve i biter der andre kurver krysser den, eller ved punkter du plasserer på den. Bruk det når en del av en kurve trenger sin egen binding eller skal slettes for seg.", + "help.sketch.cancel": "Forlater skissen og forkaster alt som er endret siden den ble opprettet eller åpnet for redigering. Angre henter endringene tilbake.", + "help.sketch.centerline": "Bytter linjer mellom vanlige linjer og senterlinjer, akser som profiler utelater. Bruk en senterlinje som akse for en omdreining, en speiling eller en symmetribinding.", + "help.sketch.chamfer.distance_angle": "Lager en fas på hjørnet mellom to linjer, bestemt av en avstand langs den første linjen og en vinkel. Bruk det når en tegning oppgir fasen som en lengde og en vinkel, for eksempel 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Lager en fas på hjørnet mellom to linjer, like langt tilbake langs begge. Bruk det til den vanlige 45°-fasen på en kontur.", + "help.sketch.chamfer.two_distance": "Lager en fas på hjørnet mellom to linjer, bestemt av en egen avstand langs hver linje. Bruk det til faser som ikke er 45°, oppgitt som to lengder.", + "help.sketch.circle.center": "Tegner en sirkel fra senteret og diameteren. Bruk det til hull, skruefester og andre runde former med kjent senter.", + "help.sketch.circle.three_point": "Tegner en sirkel gjennom tre punkter. Bruk det når sirkelen må gå gjennom gitte punkter, for eksempel på eksisterende geometri.", + "help.sketch.circle.three_tangent": "Tegner en sirkel som berører tre linjer, sirkler eller buer. Bruk det til å passe en sirkel inn i rommet mellom tre kurver, for eksempel den innskrevne sirkelen i en trekant.", + "help.sketch.circle.two_point": "Tegner en sirkel fra de to endene av diameteren. Bruk det når kantpunktene på sirkelen er kjent i stedet for senteret.", + "help.sketch.circle.two_tangent": "Tegner en sirkel i en gitt størrelse som berører to linjer, sirkler eller buer. Bruk det til en avrunding med fast radius mellom to kurver.", + "help.sketch.conic": "Tegner en kjeglesnittkurve mellom to endepunkter, formet av et toppunkt og en rho-verdi. Bruk det til jevne overganger der du vil justere fyldigheten, fra flat til nesten et skarpt hjørne.", + "help.sketch.constrainer": "Bruker bindingen som en eller to valgte kurver nesten har fra før, som vannrett, parallell, tangent eller lik. Bruk det til å rydde opp i en håndtegnet skisse én relasjon om gangen.", + "help.sketch.constraint.coincident": "Får et punkt til å ligge på et annet punkt, en kurve eller en skisseakse. Bruk det til å lukke mellomrom i en profil eller til å legge et punkt på en linje.", + "help.sketch.constraint.collinear": "Får to linjer til å ligge på én rett linje. Bruk det til å rette opp avbrutte kanter, for eksempel begge sidene av en utsparing.", + "help.sketch.constraint.concentric": "Gir to sirkler eller buer samme senter. Bruk det til ringer, sylindriske forsenkninger og aksler med skuldre.", + "help.sketch.constraint.curvature": "Får to kurver som møtes i et endepunkt til å fortsette med samme krumning (G2). Bruk det der en tangentforbindelse ikke er jevn nok, for eksempel på synlige flater.", + "help.sketch.constraint.equal": "Gjør linjer like lange, eller sirkler og buer like store i radius. Bruk det slik at ett mål styrer flere tilsvarende former.", + "help.sketch.constraint.fix": "Fikserer punkter eller kurver der de er, eller frigjør dem igjen. Bruk det til geometri som ikke må flytte seg når du drar i eller løser skissen.", + "help.sketch.constraint.horizontal_vertical": "Gjør en linje, eller linjen mellom to punkter, vannrett eller loddrett, avhengig av hva som er nærmest. Bruk det til å rette opp en kontur mot skisseaksene.", + "help.sketch.constraint.midpoint": "Legger et punkt midt på en linje, eller får midtpunktene til to linjer til å møtes. Bruk det til å sentrere geometri på en kant.", + "help.sketch.constraint.parallel": "Gjør to linjer parallelle. Bruk det til sider som må forbli parallelle når andre mål endres.", + "help.sketch.constraint.perpendicular": "Får to linjer til å møtes i rett vinkel. Bruk det til rette hjørner mellom linjer som ikke ligger på skisseaksene.", + "help.sketch.constraint.polygon": "Gjør en lukket kjede av linjer til en regulær mangekant: like sider, med hvert hjørne på én sirkel. Bruk det til å gjøre en håndtegnet mangekant regulær og holde den slik.", + "help.sketch.constraint.symmetry": "Får to punkter eller kurver til å speile hverandre om en linje eller et punkt. Bruk det til å holde en profil symmetrisk når du endrer den ene siden.", + "help.sketch.constraint.tangent": "Får to kurver til å berøre hverandre tangentielt, for eksempel en linje og en bue. Bruk det til jevne forbindelser uten knekk.", + "help.sketch.construction": "Bytter kurver mellom vanlig geometri og konstruksjonsgeometri, som profiler utelater. Bruk konstruksjonskurver som hjelp til utlegg, referanser og mål.", + "help.sketch.construction_line": "Opprett en uendelig hjelpelinje gjennom to punkter. Bruk den til å legge opp en skisse uten å dele opp profilene.", + "help.sketch.construction_line.angle": "Opprett en uendelig hjelpelinje i en vinkel fra skissens X-akse. Velg punktet og skriv inn vinkelen, eller velg retningen.", + "help.sketch.construction_line.bisector": "Velg to rette skisselinjer som krysser hverandre, og velg deretter en av vinkelhalveringslinjene. Resultatet følger kildelinjene sine.", + "help.sketch.construction_line.horizontal": "Opprett en uendelig vannrett hjelpelinje gjennom et punkt. Den vannrette bindingen følger med ved senere endringer.", + "help.sketch.construction_line.parallel": "Velg en rett skisselinje, og plasser deretter en parallell uendelig hjelpelinje. Høyreklikk for å velge en annen referanse.", + "help.sketch.construction_line.perpendicular": "Velg en rett skisselinje, og plasser deretter en vinkelrett uendelig hjelpelinje. Høyreklikk for å velge en annen referanse.", + "help.sketch.construction_line.tangent_at": "Opprett en tangent i et punkt på en sirkel eller sirkelbue, eller i endepunktet på en åpen spline eller kjeglesnittkurve. Velg kurven, og deretter berøringspunktet.", + "help.sketch.construction_line.tangent_external": "Velg en sirkel eller sirkelbue, deretter et eksternt punkt og en tangentløsning. Forhåndsvisningene viser bare berøringspunkter på den tegnede buen.", + "help.sketch.construction_line.tangent_two": "Velg to sirkler eller sirkelbuer, og velg deretter en felles tangent i forhåndsvisningen. Berøringspunktene må ligge på de tegnede kurvene.", + "help.sketch.construction_line.vertical": "Opprett en uendelig loddrett hjelpelinje gjennom et punkt. Den loddrette bindingen følger med ved senere endringer.", + "help.sketch.copy": "Kopierer de valgte skissekurvene og punktene, sammen med bindingene og målene mellom dem. Lim dem inn i denne skissen eller en annen.", + "help.sketch.create": "Starter en ny 2D-skisse på et plan eller på en plan flate av modellen. Hver ekstrudering, omdreining og sweep begynner med en skisse.", + "help.sketch.cut": "Kopierer den valgte skissegeometrien og sletter den fra skissen, i ett angretrinn. Lim den inn et annet sted i denne skissen eller i en annen.", + "help.sketch.dimension": "Legger til et styrende mål: en lengde, avstand, vinkel, radius eller diameter, avhengig av hva du velger. Skriv inn en verdi eller et parameternavn, så følger skissen det.", + "help.sketch.edit": "Åpner en eksisterende skisse for redigering. Funksjonene som er bygget på den, oppdateres når du fullfører skissen.", + "help.sketch.ellipse": "Tegner en ellipse fra senteret, enden av storaksen og et punkt på den korte siden. Bruk det til ovale åpninger, kammer og andre avlange runde former.", "help.sketch.equation_curve": "Tegner en kurve ut fra formler: x(t) og y(t), eller y = f(x), over et intervall. Formlene kan bruke parametere, og kurven følger dem: bruk den til en sinusbølge, en spiral eller evolventen til en tannhjulstann.", + "help.sketch.extend": "Forlenger en linje eller bue til nærmeste kurve i veien, eller lar to kurver vokse til de møtes. Bruk det til å lukke mellomrom i en profil etter trimming eller redigering.", + "help.sketch.fillet": "Runder av hjørnet der to linjer eller buer møtes, med en bue med gitt radius. Flere hjørner som avrundes sammen, deler én radius.", + "help.sketch.finish": "Forlater skissen og går tilbake til modellen. De lukkede profilene er da klare for Ekstrudering, Omdreining og andre funksjoner.", + "help.sketch.finish_auto_constrain": "Kjører Automatiske bindinger på skissen og fullfører den deretter. Bruk det til å la en skisse være fullt bestemt i ett trinn.", + "help.sketch.fit_curves_to_section": "Skjærer en nettkropp eller volumkropp med skisseplanet og tilpasser linjer og buer til snittet. Bruk det til å gjenoppbygge en skannet eller importert del som en redigerbar skisse.", + "help.sketch.include_3d": "Henter modellkanter, hjørner og kurver fra andre skisser inn i denne skissen som koblede referanser, og flater ut de som ligger utenfor planet på det. Bruk det til å bygge på geometri som ikke ligger i skisseplanet.", + "help.sketch.infinite": "Bytter linjer mellom vanlige linjer og uendelige hjelpelinjer som går over hele visningen. Bruk dem som utleggsreferanser som aldri ender for kort.", + "help.sketch.insert_dxf": "Leser kurvene fra en DXF-tegning inn i en skisse, skalert, dreid og plassert slik du angir. Bruk det til å bygge på en 2D-tegning fra et annet program, for eksempel en kontur for laserskjæring.", + "help.sketch.insert_svg": "Leser banene fra en SVG-tegning inn i en skisse, skalert, dreid og plassert slik du angir. Bruk det til å gjøre en logo eller vektorkontur om til kurver du kan ekstrudere.", + "help.sketch.inspect": "Åpner en rapport om den åpne skissen: hvor mange frihetsgrader som gjenstår og om den er fullstendig bundet. Bruk det til å finne ut hva som fortsatt beveger seg før du fullfører skissen.", + "help.sketch.intersect": "Legger til kurvene eller punktene der kropper, flater, kanter eller andre skisser krysser skisseplanet. De forblir koblet og følger modellen når den endres.", + "help.sketch.intersection_curve": "Oppretter 3D-kurver der to kropper eller flater møtes, koblet til dem. Bruk dem som baner eller føringskurver som følger modellen.", + "help.sketch.isoparametric_curve": "Oppretter en 3D-kurve langs U- eller V-retningen til en flate gjennom et punkt du velger, koblet til flaten. Bruk den som en bane eller delelinje som følger flaten.", + "help.sketch.line": "Tegner sammenhengende linjer punkt for punkt, som en åpen kjede eller en lukket kontur. Det er det grunnleggende verktøyet for de fleste profiler.", + "help.sketch.line.midpoint": "Tegner en linje fra midtpunktet og ut til den ene enden, med den andre enden speilet. Bruk det til linjer sentrert på et punkt, for eksempel en symmetrisk kant.", + "help.sketch.line3d": "Tegner sammenhengende rette linjer mellom punkter i rommet, med 3D-skisse slått på. Bruk det til baner og rammer som forlater skisseplanet.", + "help.sketch.mirror": "Speiler skissekurver og punkter om en linje eller akse og legger til symmetribindinger. Bruk det til å tegne halvparten av en symmetrisk profil og fullføre den.", + "help.sketch.move": "Flytter eller roterer skissekurver og punkter, eller en kopi av dem. Bruk det til å plassere geometri på nytt og beholde formen og bindingene.", + "help.sketch.offset": "Lager en kopi av en kjede av kurver i en gitt avstand, på den ene siden eller begge. Bruk det til vegger, konturer og klaringer; avstanden forblir et redigerbart mål.", + "help.sketch.paste": "Limer inn skissegeometri du har kopiert eller klippet ut i den aktive skissen. Plasser den i et punkt eller forskyv den med en offset.", + "help.sketch.pattern.circular": "Kopierer skissegeometri rundt et senterpunkt, over en full sirkel eller en gitt vinkel. Bruk det til hullsirkler, eiker og tenner.", + "help.sketch.pattern.rectangular": "Kopierer skissegeometri i rader og kolonner med gitte avstander. Bruk det til rutenett av hull, spor eller ventilasjonsåpninger.", + "help.sketch.point": "Plasserer et skissepunkt. Bruk det som referanse for mål, bindinger, hullsentre eller senere funksjoner.", + "help.sketch.point3d": "Plasserer et punkt i rommet, med 3D-skisse slått på. Bruk det som referanse for 3D-kurver og baner.", + "help.sketch.polygon.circumscribed": "Tegner en regulær mangekant rundt en sirkel, dimensjonert fra senteret til midten av en side. Bruk det når bredden over flatene er kjent, som for en sekskantmutter.", + "help.sketch.polygon.edge": "Tegner en regulær mangekant fra de to endene av én side. Bruk det når lengden og posisjonen til en side er kjent.", + "help.sketch.polygon.inscribed": "Tegner en regulær mangekant inni en sirkel, dimensjonert fra senteret til et hjørne. Bruk det når målet over hjørnene er kjent.", + "help.sketch.project": "Henter modellkanter, flater, hjørner og kurver fra andre skisser inn i denne skissen, projisert på planet. De forblir koblet og følger modellen når den endres.", + "help.sketch.project_to_surface": "Projiserer kurver fra andre skisser langs normalen til denne skissen på en flate, som koblede 3D-kurver. Bruk det til å legge en logo, delelinje eller bane på en kurvet flate.", + "help.sketch.rectangle.center": "Tegner et rektangel fra senteret og ett hjørne. Bruk det til konturer sentrert på et punkt, for eksempel origo.", + "help.sketch.rectangle.rounded": "Tegner et rektangel med alle fire hjørnene avrundet til én radius. Bruk det til plater, lokk og åpninger med avrundede hjørner.", + "help.sketch.rectangle.three_point": "Tegner et rektangel fra én kant og et punkt på motsatt side. Bruk det til rektangler i vinkel mot skisseaksene.", + "help.sketch.rectangle.two_point": "Tegner et rektangel fra to motstående hjørner. Bruk det til konturene av plater, blokker og lommer.", + "help.sketch.scale": "Skalerer skissekurver og punkter med en faktor om et basepunkt. Bruk det til å endre størrelsen på en del av en skisse uten å tegne den på nytt.", + "help.sketch.slot.arc_center": "Tegner et buet spor med gitt bredde langs en bue bestemt av senteret, starten og slutten. Bruk det til justeringsspor rundt en dreietapp.", + "help.sketch.slot.arc_three_point": "Tegner et buet spor med gitt bredde langs en bue gjennom tre punkter. Bruk det når sporets bane må gå gjennom gitte punkter.", + "help.sketch.slot.center_point": "Tegner et rett spor med gitt bredde fra senteret til senteret av den ene endebuen. Bruk det til spor sentrert på et punkt.", + "help.sketch.slot.center_to_center": "Tegner et rett spor med gitt bredde mellom sentrene til de to endebuene. Bruk det til spor målsatt senter til senter, for eksempel justeringsspor for skruer.", + "help.sketch.slot.overall": "Tegner et rett spor med gitt bredde fra den ene ytterenden til den andre. Bruk det når sporets totale lengde er det som teller.", + "help.sketch.spline.control_point": "Tegner en kubisk spline formet av kontrollpunkter som den ikke går gjennom. Bruk det til jevne, flytende kurver som du former ved å flytte punktene.", + "help.sketch.spline.control_point_5": "Tegner en spline av grad 5 formet av kontrollpunkter. Bruk det der kurver må henge sammen med jevnere krumning, for eksempel på synlige designflater.", + "help.sketch.spline.fit_point": "Tegner en jevn spline som går gjennom hvert punkt du plasserer, åpen eller lukket. Bruk det til å tegne en form gjennom kjente punkter.", + "help.sketch.spline3d": "Tegner en jevn kurve i rommet gjennom punkter, med 3D-skisse slått på. Bruk det til sweep-baner og kabelføringer som forlater skisseplanet.", + "help.sketch.spun_profile": "Oppretter i skisseplanet omrisset en kropp tegner ut når den dreier om en akse. Bruk det til å få silhuetten av en dreiedel for en omdreining eller en tegning.", + "help.sketch.text": "Skriver tekst i skissen i en valgt skrift, høyde og vinkel; ordene kan følge parametere. Ekstruder eller preg den for etiketter og skrift.", + "help.sketch.transform": "Skalerer, dreier og flytter skissegeometri om et senterpunkt i ett trinn. Bruk det til å plassere og endre størrelsen på et utvalg samtidig.", + "help.sketch.trim": "Fjerner delen av en kurve mellom de nærmeste kryssingene rundt stedet du klikker. Bruk det til å rydde overlappende linjer til en lukket profil.", "help.solid.align": "Flytter de valgte kroppene slik at et punkt, en flate eller et plan på dem møter et punkt, en flate eller et plan et annet sted. Bruk det til å plassere en del mot en annen uten å måle forskyvningen.", + "help.solid.boundary_fill": "Lager volumkropper av områdene som omsluttes av overlappende verktøykropper, og fyller bare områdene du velger. Bruk det til å bygge en form av rommet flere kropper avgrenser sammen.", + "help.solid.bounding_solid": "Oppretter en boks som omslutter de valgte kroppene, med en valgfri margin. Bruk det til å se den samlede størrelsen på en del, eller som råemnet den freses ut av.", + "help.solid.box": "Oppretter en boks fra lengde, bredde og høyde, fra et hjørnepunkt eller sentrert på et punkt. Bruk det til en rask blokk, en plassholder eller en kropp å skjære funksjoner inn i.", "help.solid.chamfer": "Lager en plan fas langs de valgte kantene med avstanden du angir. Bruk verktøyet til å fjerne skarpe kanter eller gjøre det lettere å føre inn en pinne eller skrue.", + "help.solid.coil": "Oppretter en spiralformet kropp, for eksempel en fjær, fra en diameter, vindinger, høyde eller stigning og et rundt eller kvadratisk tverrsnitt. Bruk det til fjærer, spoler og spiralformede rygger.", "help.solid.combine": "Slår sammen kropper, trekker dem fra en målkropp eller beholder bare volumet de har felles, og kan beholde verktøykroppene. Bruk det til å slå sammen deler, til å skjære en form med en annen eller til å finne hvor to kropper overlapper.", + "help.solid.cone": "Oppretter en kjegle fra en grunnsirkel og en høyde, eller en avkortet kjegle når toppen også har en radius. Bruk det til tilspissinger, traktere, koniske forsenkninger og spisser.", + "help.solid.cylinder": "Oppretter en sylinder fra en radius eller diameter og en høyde, stående på et punkt langs en akse. Bruk det til aksler, stifter, skruefester og runde emner.", "help.solid.draft": "Tilter de valgte flatene med vinkelen du angir, målt fra et nøytralt plan. Bruk det på støpte eller formsprøytede deler slik at de glir ut av formen.", + "help.solid.emboss": "Hever skisseprofiler, for eksempel tekst eller en logo, ut fra en flate, eller senker dem ned i den. Bruk det til skrift, etiketter og merking på plane eller runde flater.", "help.solid.extrude": "Trekker en skisseprofil ut i 3D over en angitt avstand og legger til eller fjerner materiale. Bruk verktøyet til å gjøre et flatt omriss til en blokk, en knast eller en lomme.", "help.solid.fillet": "Runder av de valgte kantene med en jevn, sirkulær overgang med radiusen du angir. Bruk verktøyet til å avrunde skarpe kanter av hensyn til styrke, komfort eller utseende.", "help.solid.hole": "Lager et rundt hull med diameteren du angir, ved et valgt punkt på en flate. Bruk verktøyet til klaringshull for skruer, hull for pinner og andre enkle, runde åpninger.", @@ -1408,20 +1678,62 @@ "help.solid.move": "Flytter eller roterer de valgte kroppene, eller en kopi av dem, med avstanden og vinkelen du angir. Bruk det til å flytte en kropp eller lage en til på et annet sted.", "help.solid.offset_face": "Skyver de valgte flatene inn eller ut med avstanden du angir, og flatene rundt følger med. Bruk det til å gjøre en vegg tykkere, en lomme dypere eller en forhøyning høyere uten å redigere skissen.", "help.solid.pattern.circular": "Gjentar de valgte objektene rundt en akse, med antallet og totalvinkelen du angir. Bruk det til boltesirkler, eiker, finner og tenner.", + "help.solid.pattern.path": "Kopierer funksjoner eller kropper langs en skissebane, etter antall og avstand. Bruk det til hull langs en kurvet kant eller deler langs en skinne.", "help.solid.pattern.rectangular": "Gjentar de valgte objektene i én eller to retninger med antallet og avstanden du angir. Bruk det til rader og rutenett av hull, ribber, pinner eller føtter.", + "help.solid.pipe": "Oppretter et rundt rør langs en bane av skissekurver, massivt eller hult med en veggtykkelse. Bruk det til rør, ledninger, kabler og skinner.", "help.solid.press_pull": "Legger til eller fjerner materiale når du drar i en flate, eller avrunder kanter når du drar i dem. Bruk det til raske endringer rett på modellen.", "help.solid.remove": "Tar de valgte kroppene ut av designet fra dette punktet i tidslinjen og utover; tidligere trinn beholder dem. Bruk det til å fjerne en hjelpekropp, for eksempel et skjæreverktøy du ikke trenger lenger.", "help.solid.replace_face": "Flytter de valgte plane flatene til et plan eller en parallell flate, og kroppen vokser eller krymper for å møte det. Bruk det til å få en flate på linje med en annen del eller et konstruksjonsplan.", "help.solid.revolve": "Dreier en skisseprofil rundt en akse for å lage en rotasjonssymmetrisk volumkropp. Bruk verktøyet til aksler, knotter, skåler og andre deler som er runde rundt en senterlinje.", + "help.solid.rib": "Legger til en tynn vegg langs en åpen skissekurve, fylt ut til de neste flatene på kroppen. Bruk det til å avstive vegger og hjørner, for eksempel i støpte eller utskrevne deler.", "help.solid.scale": "Gjør de valgte kroppene større eller mindre med en faktor, lik i alle retninger eller én per akse. Bruk det til å endre størrelsen på en importert form eller til å ta hensyn til krymping.", "help.solid.shell": "Huler ut en volumkropp og lager vegger med tykkelsen du angir. Flatene du velger, fjernes for å lage åpninger. Bruk verktøyet til bokser, deksler og andre tynnveggede deler.", + "help.solid.sphere": "Oppretter en kule fra en radius eller diameter rundt et senterpunkt. Bruk det til kuler, knotter og avrundede ender.", "help.solid.split_body": "Deler en kropp i separate kropper med et plan, flaten til en annen kropp eller en skisselinje. Bruk det til å lage deler som skal skrives ut, maskineres eller farges hver for seg.", "help.solid.split_face": "Deler de valgte flatene langs et plan, flaten til en annen kropp eller skisserte kurver, uten å dele kroppen. Bruk det til å gi en del av en flate sin egen slippvinkel, farge eller forskyvning.", "help.solid.sweep": "Drar en skisseprofil langs en bane for å lage en volumkropp. Bruk det til rør, skinner, håndtak og alle deler med konstant tverrsnitt som følger en kurve.", + "help.solid.thread": "Legger til en ISO-metrisk gjenge på en sylindrisk flate, enten som en kosmetisk gjenge eller skåret inn i kroppen. Bruk det til bolter, gjengede hull og utskrevne skrudeler.", + "help.solid.torus": "Oppretter en ring fra en storradius rundt aksen og en lilleradius for det runde tverrsnittet. Bruk det til O-ringer, håndtak og runde perler.", + "help.solid.web": "Legger til en tynn vegg langs hver åpne skissekurve, hver fylt ut til de neste flatene på kroppen. Bruk det til et rutenett av støttevegger inni hus og brett.", + "help.surface.blend": "Oppretter en flate som bygger bro mellom kantene på to kropper, tangent- eller krumningskontinuerlig mot begge. Bruk det til å forbinde to flater jevnt over et mellomrom.", + "help.surface.boundary": "Oppretter en flate som fyller en sløyfe av to til fire skissekurver, eller et nett av kurver. Bruk det til frie paneler definert av kantene sine.", + "help.surface.extend": "Forlenger en flate forbi kantene, med en avstand eller opp til et plan eller en flate. Bruk det slik at flater overlapper før du trimmer eller syr dem sammen.", + "help.surface.extrude": "Skyver skissekurver eller profiler en avstand ut til en flate, bare vegger, uten lokk. Bruk det til tynne vegger og til skjære- eller delingsverktøy.", + "help.surface.fair": "Jevner ut innsiden av frie flater mens kantene blir stående. Bruk det til å jevne ut bulker og bølgete refleksjoner i en flate.", + "help.surface.loft": "Oppretter en flate som går gjennom to eller flere profiler i rekkefølge, uten lokk. Bruk det til skall og overganger mellom ulike former.", + "help.surface.match": "Bygger kanten av en flate på nytt slik at den møter kanten til en annen kropp, med samsvarende tangent eller krumning. Bruk det til å lukke en skjøt jevnt mellom to flater.", + "help.surface.offset": "Lager en kopi av flater i en avstand langs normalene deres, som en ny flatekropp. Bruk det til hud, klaringer eller den andre siden av en vegg.", + "help.surface.patch": "Fyller et skisseområde eller en lukket sløyfe av kanter med en flate, plan eller jevnt krum. Bruk det til å lukke hull i en flatekropp.", + "help.surface.reverse_normal": "Snur flatene i en flatekropp, slik at utsiden vender den andre veien. Bruk det før fortykning eller sammensying når flatene peker innover.", + "help.surface.revolve": "Dreier skissekurver eller profiler om en akse til en flate, uten lokk. Bruk det til runde skall som lampeskjermer, boller og dyser.", + "help.surface.ruled": "Oppretter en stripe av rette linjer ut fra en kjede av kanter, langs flatens normal, tangent eller i en vinkel. Bruk det til slippvegger, utløp og delingsflater.", + "help.surface.stitch": "Syr flatekropper sammen langs de felles kantene, til en volumkropp når de lukker seg. Bruk det til å gjøre et sett flater om til én kropp.", + "help.surface.sweep": "Fører skissekurver eller profiler langs en bane til en flate, uten lokk. Bruk det til renner, lister og andre tynne former som følger en bane.", + "help.surface.thicken": "Gir en flatekropp en tykkelse og gjør den til en volumkropp. Bruk det til å lage utskrivbare eller maskinerbare deler av flater.", + "help.surface.trim": "Skjærer en flate med et plan, en annen flate eller skissekurver, og beholder siden du velger. Bruk det til å skjære flater til form før sammensying.", + "help.surface.unstitch": "Skiller flatene til en kropp ut i egne flatekropper; en volumkropp faller fra hverandre til flater. Bruk det til å bearbeide enkeltflater på en kropp.", + "help.surface.untrim": "Fjerner hull fra en flate, eller gjenoppretter ytterkanten til flatens naturlige grenser. Bruk det til å få tilbake hele flaten etter en trimming.", "help.third_party": "Tredjepartslisenser", "help.timeline.compute_all": "Bygger alle funksjoner i tidslinjen på nytt fra begynnelsen. Bruk det til å oppdatere modellen og se hvilke funksjoner som feiler.", "help.timeline.delete": "Sletter de valgte funksjonene fra tidslinjen; sletting av en skisse sletter også funksjonene som er bygget på den. Bruk det til å fjerne et trinn som ikke lenger er ønsket.", + "help.timeline.dependents": "Lister opp funksjonene som ville blitt slettet sammen med en funksjon, og de som ville feilet uten den. Bruk det før du sletter eller endrer en funksjon.", "help.timeline.play": "Spill av de gjenstående funksjonene én om gangen, med en halv sekunds pause etter hver gjenoppbygging. Kjør denne kommandoen igjen eller trykk Escape for å stoppe; Gå til slutten hopper umiddelbart.", + "help.view.apply": "Dreier visningen til en standardretning som front, topp eller iso, eller til en lagret navngitt visning. Bruk det til å se på modellen fra en fast vinkel.", + "help.view.delete": "Sletter en lagret navngitt visning. Modellen endres ikke.", + "help.view.fit": "Zoomer og panorerer slik at hele modellen, eller utvalget, fyller visningen. Bruk det når modellen har kommet ut av syne.", + "help.view.grid": "Viser eller skjuler rutenettet i visningsområdet. Bruk det som en størrelses- og orienteringshjelp under modellering.", + "help.view.ground_shadow": "Viser eller skjuler skyggen til modellen på bakken. Bruk det til å vurdere høyde og posisjon lettere.", + "help.view.home": "Dreier visningen tilbake til hjemretningen og tilpasser modellen. Bruk det til raskt å komme tilbake til en kjent visning.", + "help.view.list": "Lister opp de navngitte visningene som er lagret i designet. Bruk det til å finne en visning du lagret tidligere.", + "help.view.navigate": "Dreier, panorerer eller zoomer visningen i trinn, for eksempel en kvart omdreining til venstre. Bruk det til å flytte kameraet presist i stedet for å dra.", + "help.view.navigation_bar": "Viser eller skjuler navigasjonslinjen nederst i visningsområdet. Skjul den for mer plass, vis den for å nå visningsverktøyene med musen.", + "help.view.rename": "Gir en lagret navngitt visning et nytt navn. Selve visningen forblir den samme.", + "help.view.save": "Lagrer gjeldende kameraposisjon som en navngitt visning i designet. Bruk det til å komme tilbake til samme vinkel senere, for eksempel for skjermbilder.", + "help.view.spin": "Roterer visningen rundt modellen kontinuerlig til neste klikk eller tast. Bruk det til å presentere en modell fra alle sider.", + "help.view.tool": "Låser et kameraverktøy, rotering, panorering eller zoom, slik at det å dra med venstre museknapp flytter visningen til du slår det av. Bruk det på en styreflate eller uten midtre museknapp.", + "help.view.visual_style": "Bytter hvordan modellen tegnes: skyggelagt med eller uten kanter, trådmodell eller med skjulte kanter. Bruk trådmodell for å se inn i modellen, skyggelagt for et rent utseende.", + "history.sketch_under_constrained": "Underbestemt ({count} frihetsgrader)", + "history.sketch_under_constrained_one": "Underbestemt ({count} frihetsgrad)", "hole_presets.confirm_delete": "Bekreft sletting", "hole_presets.delete": "Slett", "hole_presets.delete_prompt": "Slette denne personlige forhåndsinnstillingen? Eksisterende hull endres ikke.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Kontroller leddtypen (for eksempel Stiv), om posisjonen er festet, leddgrenser og parameterstyrte verdier.", "joint_move.blocked_title": "Kan ikke flytte denne delen", "joint_move.coarse": "Rotasjonstrinn nær aksen (°)", + "joint_move.conflict": "Et ledd på denne delen er i konflikt med de andre: {joint}.", + "joint_move.conflict_hint": "Rediger, undertrykk eller slett det konfliktende leddet, slik at de andre leddene kan plassere delen.", "joint_move.distance": "Avstand fra start", "joint_move.done": "Ferdig", "joint_move.fine": "Rotasjonstrinn langt fra aksen (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Ulike materialer", "measure.at": "Ved", "measure.item": "Element {number}", + "measure.quick_copied": "Målet er kopiert", + "measure.quick_copy": "Klikk for å kopiere målet", + "measure.quick_edges": "{count} kanter", + "measure.quick_faces": "{count} flater", "messages.ago_h": "for {n} t siden", "messages.ago_min": "for {n} min siden", "messages.ago_s": "for {n} s siden", @@ -1620,6 +1938,8 @@ "motion.track_name": "Spor {number}", "nav.alias.help": "Shift+Alt+venstredrag roterer, Shift+Alt+midtdrag panorerer, Shift+Alt+høyredrag zoomer; midtdrag panorerer og høyredrag roterer også", "nav.blender.help": "Midtdrag roterer, Shift+midtdrag panorerer, Ctrl+midtdrag zoomer; høyredrag lar kameraet stå i ro", + "nav.creo.help": "Midtdrag roterer, Shift+midtdrag panorerer, Ctrl+midtdrag vertikalt zoomer (ned for å zoome inn); rulling med hjulet zoomer", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Mus og 3D-mus roterer gjennom begge polene og bevarer rulling. Aksefangst med Shift er deaktivert.", "nav.free_orbit.label": "Fri rotasjon", "nav.free_orbit.snap_help": "Mus og 3D-mus roterer gjennom begge polene og bevarer rull. Hold Shift mens du drar for å rotere, så låses visningsretningen og rullen til faste trinn.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+venstredrag panorerer, Shift+Alt+venstredrag zoomer, Ctrl+venstredrag fra tomt område roterer", "nav.inventor.help": "Midtdrag panorerer, Shift+midtdrag roterer, Ctrl+midtdrag zoomer, høyredrag roterer", "nav.maya.help": "Alt+venstredrag roterer, Alt+midtdrag panorerer, Alt+høyredrag zoomer; midtdrag panorerer også", + "nav.nx.help": "Midtdrag roterer, Shift+midtdrag panorerer (i NX: midt + høyre), Ctrl+midtdrag zoomer (i NX: midt + venstre); høyredrag lar kameraet stå i ro", "nav.openscad.help": "Venstredrag i tomt område roterer, Shift+venstredrag velger med ramme, dra i skissegeometri for å redigere; høyre- eller midtdrag panorerer, Shift+høyredrag eller Shift+midtdrag zoomer", "nav.perspective.sketch": "Skisseredigering bruker ortografisk visning. Fullfør skissen for å bytte til perspektiv.", "nav.right_drag_orbits.help": "Av: et høyredrag lar kameraet stå i ro, og høyre museknapp åpner bare kontekstmenyen. Når du velger SolidWorks-museoppsettet, slås dette av.", @@ -1748,6 +2069,11 @@ "not a move": "ikke en flytting", "not a number": "ikke et tall", "open a sketch first": "åpne en skisse først", + "parameters.apply_live": "Bruk hver endring når du forlater feltet", + "parameters.apply_live_tip": "Av: endringene venter til Bruk eller OK, og så bygges designet på nytt én gang for alle. Avbryt eller Escape forkaster dem.", + "parameters.held": "{count} endringer venter på Bruk", + "parameters.held_hint": "Rediger uttrykk og enheter. Endringer venter på Bruk eller OK.", + "parameters.held_one": "1 endring venter på Bruk", "parts.automatic_name": "automatisk", "parts.dimension.across_flats": "Nøkkelvidde", "parts.dimension.bore": "Boring", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Linsehodeskrue med innvendig sekskant", "parts.family.dowel_pin": "Parallellstift (passtift)", "parts.family.hex_bolt": "Sekskantbolt / sekskantskrue", + "parts.family.hex_cap_screw_inch": "Sekskantskrue (tommer)", "parts.family.hex_nut": "Sekskantmutter", + "parts.family.hex_nut_inch": "Sekskantmutter (tommer)", "parts.family.set_screw": "Settskrue med innvendig sekskant, flat ende", "parts.family.socket_head_cap_screw": "Sylinderskrue med innvendig sekskant", "parts.family.washer": "Underlagsskive", + "parts.family.washer_sae": "Underlagsskive, SAE (smal)", + "parts.family.washer_uss": "Underlagsskive, USS (bred)", + "parts.holes": "Hull (valgfritt)", + "parts.placement_hint": "velg ett eller flere hull for å sette inn en del i hvert av dem, eller OK plasserer den ved origo", + "parts.system": "Enhetssystem", + "parts.system.inch": "Tommer", + "parts.system.metric": "Metrisk", "pattern.alignment_2": "Justering 2", "pattern.alignment_hint": "Antallet inkluderer originalen. Senter fordeler kopiene rundt originalen. Speil velger hvilken side som får en ekstra kopi når antallet er et partall.", "pattern.direction_1": "Retning 1", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Jevner ut taggete kanter.", "prefs.applies_on_restart": "Tas i bruk ved omstart", "prefs.assistant": "Assistent", + "prefs.auto_operation": "Velg operasjon automatisk", + "prefs.auto_operation_note": "Funksjonsdialoger velger Slå sammen, Ny kropp eller Klipp ut ut fra hva det nye materialet berører, helt til du velger selv. Av: de beholder operasjonen de åpnes med.", "prefs.axes": "Akser", "prefs.axis": "Akse", "prefs.bodies_folders": "Kroppsmapper", @@ -1820,6 +2157,8 @@ "prefs.bottom_centre": "Nederst i midten", "prefs.bottom_right": "Nederst til høyre", "prefs.browser": "Modelltre", + "prefs.browser_eye_left": "Øyet ved siden av foldepilen", + "prefs.browser_eye_left_note": "Radene i modelltreet viser vis/skjul-øyet ved siden av foldepilen, som før, i stedet for i en kolonne ytterst til høyre i radene.", "prefs.browser_reveal_on_hover": "Vis når pekeren er over", "prefs.browser_show_note": "Vist holder modelltreet på skjermen. Vis når pekeren er over holder det skjult til pekeren kommer over plassen det har, eller over den tynne fanen ved venstre kant, og det forblir åpent mens pekeren er inne i det eller en meny fra det er åpen.", "prefs.browser_shown": "Vist", @@ -1827,6 +2166,8 @@ "prefs.button_left": "Dra med venstre museknapp", "prefs.button_middle": "Dra med midtre museknapp", "prefs.button_right": "Dra med høyre museknapp", + "prefs.carousel_next": "Neste", + "prefs.carousel_previous": "Forrige", "prefs.choose_font": "Velg skriftfil…", "prefs.click": "Klikk", "prefs.contact_shading": "Myk kontaktskyggelegging", @@ -1839,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Buede flater", "prefs.curves": "Buede flater", + "prefs.cut_preview_tint": "Vis fjernet materiale i rødt", + "prefs.cut_preview_tint_help": "En forhåndsvisning fyller materialet en funksjon fjerner, og formen den erstatter, med et rødt, gjennomsiktig spøkelse. Når dette er av, er fyllene helt gjennomsiktige, og bare konturene tegnes.", + "prefs.dark_parts_shading": "Bevar formen på mørke deler", + "prefs.dark_parts_shading_help": "Skygger visningen i lineært lys med en myk himmelfylling, slik at mørke flater beholder en gradient i stedet for å bli svarte", "prefs.dead_zone_note": "Det skraverte feltet er dødsonen: bevegelser innenfor den ignoreres.", "prefs.default": "standard", "prefs.design": "Standarder for design", @@ -1853,6 +2198,8 @@ "prefs.edges": "Kanter og skyggelegging", "prefs.extend": "Utvid", "prefs.extra_navigation": "Ctrl+venstredrag i tomt område roterer; hold mellomromstasten inne for å panorere.", + "prefs.extrude_view_isometric": "Drei visningen til isometrisk når Ekstrudering åpnes", + "prefs.extrude_view_return": "Gå tilbake til forrige visning når Ekstrudering lukkes", "prefs.follows_os": "Følger operativsystemet", "prefs.font": "Skrift", "prefs.font_fallback": "Tegn som mangler i valgt skrift, hentes fra den innebygde skriften, slik at ingen etiketter viser tomme ruter.", @@ -1868,8 +2215,11 @@ "prefs.graphics_card_auto": "Automatisk", "prefs.graphics_card_missing": "Det lagrede grafikkortet er utilgjengelig. Automatisk brukes i stedet.", "prefs.graphics_card_restart": "Trer i kraft etter at SolidCraft er startet på nytt. WGPU_ADAPTER_NAME overstyrer dette valget.", + "prefs.graphics_card_unused": "Det lagrede grafikkortet ble ikke brukt for dette vinduet. Kortet som er i bruk, vises i Hjelp › Om og i statuslinjen. Prøv Automatisk, eller sett WGPU_ADAPTER_NAME til en unik del av kortets navn.", "prefs.graphics_note": "Velg mellom hastighet og jevnhet. Hvert valg viser effekten på et eksempel.", "prefs.graphics_presets_note": "Forhåndsinnstillinger angir valgene nedenfor samlet.", + "prefs.hide_constraint_glyphs_zoomed_out": "Skjul bindingssymboler når det er zoomet ut", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Bindingssymbolene forsvinner fra visningen når skissen er zoomet ut så langt at de ville rotet til den. Av: de beholder en fast størrelse på skjermen ved alle zoomnivåer.", "prefs.history": "Historikk", "prefs.history_origin_bodies": "Vis origo og kropper øverst", "prefs.history_origin_bodies_note": "Tidslinjen til venstre eller under modelltreet starter med Kropper-mappen til den aktive komponenten og Origo, med øyne og menyer som i modelltreet. Tidslinjen nederst er uendret.", @@ -1880,6 +2230,8 @@ "prefs.history_sketches_note": "Når Skisser er satt til Under funksjonen sin, viser tidslinjen til venstre hver skisse ett nivå inn, under den første funksjonen som er bygget fra den, så lenge den er bred nok til å vise navn. Tidslinjen nederst beholder alltid opprettelsesrekkefølgen.", "prefs.history_sketches_under_feature": "Under funksjonen sin", "prefs.hold_stop_snapping": "Hold inne for å slå av punktfangst", + "prefs.home_fit_size": "Størrelse for Hjem og Tilpass", + "prefs.home_fit_size_note": "Hvor mye av visningen modellen fyller når Hjem, Tilpass, et åpnet design eller en visningsendring fra navigatoren rammer den inn, enten innstillingen under er på eller ikke. 100 %: fyller visningen mellom panelene, kompasset og navigasjonslinjen.", "prefs.icons_only": "Bare ikoner", "prefs.imported_file": "Importert fil", "prefs.in_browser": "I modelltreet", @@ -1888,13 +2240,22 @@ "prefs.interface_language": "Grensesnittspråk", "prefs.interface_note": "Hvordan SolidCraft ser ut, og hvor delene er plassert.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Inverter de krumme rullepilene", + "prefs.invert_curved_roll_arrows_note": "De to krumme pilene i hjørnet av kuben ruller visningen i skjermplanet. På: pilen med klokken ruller mot klokken, og pilen mot klokken ruller med klokken. Av: hver pil ruller visningen i den retningen den krummer seg.", + "prefs.invert_navigator_arrows": "Inverter rotasjonspilene på visningskuben", + "prefs.invert_navigator_arrows_note": "Pilene rundt kuben roterer kameraet i den retningen de peker, som i Fusion og Inventor: pilen til venstre peker mot høyre og svinger kameraet mot høyre. Av: en pil roterer kuben mot siden den står på, så venstre pil svinger kameraet mot venstre. De krumme rullepilene påvirkes ikke.", + "prefs.keep_work_on_tab_switch": "Behold dialoger og verktøy åpne når du bytter design", + "prefs.keep_work_on_tab_switch_note": "Hver designfane beholder sin åpne dialog eller sitt åpne verktøy, med det du har valgt og skrevet i den, og sin fane på båndet. De er der igjen når du kommer tilbake til designet. Av: å bytte design avbryter dem og viser fanen Modell.", "prefs.labels": "Etiketter", + "prefs.language_system": "System", "prefs.layout": "Oppsett", "prefs.layout_note": "Kompakt fester panelene til vinduskantene. Gjennomsiktig modelltre er tilgjengelig i Flytende. Endre siden for assistenten på assistentsiden.", "prefs.left": "Venstre", "prefs.left_click": "Venstreklikk", "prefs.line_drag_draws_one": "Trykk og dra tegner én linje", "prefs.line_drag_draws_one_note": "I Linje-verktøyet tegner trykk, dra og slipp én linje fra der du trykket til der du slapp, og linjen avsluttes der. Klikk tegner fortsatt en kjede. Av: et drag plasserer et punkt der det slippes, slik et klikk gjør.", + "prefs.line_hover_tangent_arc": "Hvil på det siste punktet på en linje for å bytte til en tangentbue", + "prefs.line_hover_tangent_arc_note": "I Linje-verktøyet: når et segment er tegnet, beveg pekeren bort fra det siste punktet i kjeden, kom tilbake og hold pekeren i ro på det: neste klikk avslutter en tangentbue, og samme bevegelse går tilbake til linjer. Av: å hvile der gjør ingenting.", "prefs.linked_designs": "Koblede design", "prefs.live_input": "Direkte inndata", "prefs.live_preview": "Direkte forhåndsvisning", @@ -1908,6 +2269,9 @@ "prefs.max_file_size_step": "STEP- og importfiler", "prefs.max_file_size_web": "Nettappen åpner STEP- og importfiler opptil 512 MB og design opptil 256 MB: en nettleserfane kan ikke romme større filer. Grensene kan økes i skrivebordsappen.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Store ikoner", + "prefs.menu_list": "Liste", + "prefs.menus": "Menyer", "prefs.minutes": "minutter", "prefs.minutes_suffix": " min", "prefs.mouse": "Mus og styreflate", @@ -1915,6 +2279,8 @@ "prefs.mouse_mapping": "Museoppsett", "prefs.navigation": "Navigasjon", "prefs.navigation_note": "Hvordan mus, styreflate og 3D-mus beveger visningen.", + "prefs.navigator_fit": "Tilpass modellen etter en visningsendring fra navigatoren", + "prefs.navigator_fit_note": "En flate, et hjørne eller en pil på visningskuben, eller en akse på orienteringsindikatoren, ser også mot midten av modellen fra den ene avstanden som får den til å passe fra alle sider (den omsluttende kulen). Hjem bruker samme zoom og senter mens dette er på, så visninger som velges etterpå bare dreier. Av: visningen dreier på stedet og beholder målpunktet og zoomen sin.", "prefs.network_host_remove": "Fjern", "prefs.network_locations": "Tillat nettverksplasseringer i design", "prefs.network_locations_note": "Av: lenkede filer i et design på en annen datamaskin (\\\\server\\share) åpnes bare fra serverne som er oppført her, eller etter at du har tillatt en når du blir spurt.", @@ -1927,10 +2293,18 @@ "prefs.origin_plane_names": "Navn på origoplan", "prefs.origin_plane_names_note": "Navn som vises i modelltreet, dialoger og lister. {top} er XY, {front} er XZ og {right} er YZ, med Z opp. Kommandoer, skript og lagrede design beholder XY, XZ og YZ.", "prefs.overall_speed": "Samlet hastighet", + "prefs.parameter_list_rows": "Rader i parameterlisten", + "prefs.parameter_list_rows_tip": "Pil ned i et tomt verdifelt viser parameterne, favorittene først, opp til dette antallet. Færre holder listen lett i et stort design.", + "prefs.persistent_ribbon_pressed": "Fremhev aktive kommandoer på båndet", + "prefs.persistent_ribbon_pressed_help": "Fremhev kommandoer på båndet mens effektene deres er slått på. Slå av for å beholde det forrige nøytrale utseendet og den forrige kommandohjelpen.", "prefs.perspective_fov": "Synsfelt", "prefs.placement": "Plassering", "prefs.prefer_free_sketch_points": "Foretrekk flyttbare skissepunkter når punkter overlapper", "prefs.preview_choices": "Forhåndsvisning av valgene dine", + "prefs.preview_tint_new_faces": "Fargelegg ny overflate i en forhåndsvisning", + "prefs.preview_tint_new_faces_help": "En forhåndsvisning av en funksjon som endrer en kropp, kan tegne overflaten den legger til i forhåndsvisningsfargen. Når dette er av, tegnes kroppen som seg selv.", + "prefs.print_face_highlight": "Utheving av utskriftsflate", + "prefs.print_face_highlight_tip": "Hvor sterkt et legemes utskriftsflate fargelegges og omrisses i visningen. 0 % viser ingen utheving.", "prefs.profile_active": "Aktiv profil", "prefs.profile_applied": "Profilen er brukt.", "prefs.profile_changed": "Innstillingene er endret siden profilen ble lagret. Lagre beholder dem i profilen.", @@ -1952,9 +2326,13 @@ "prefs.quality_fastest": "raskest", "prefs.quality_slowest": "langsomst", "prefs.quality_smoother": "jevnere", + "prefs.quick_measure": "Hurtigmåling i hjørnet av visningen", + "prefs.quick_measure_note": "Størrelsen på utvalget nederst til høyre i visningen: lengden til en kant, eller Ø og R for en rund kant, arealet til en flate, posisjonen til et punkt, avstanden og vinkelen mellom to elementer, summen for flere kanter eller flater. Et klikk kopierer den.", "prefs.render_previous_geometry_budget": "Bruk forrige geometribudsjett for rendringsforhåndsvisning", "prefs.render_previous_geometry_budget_help": "Gjenopprett den forrige faste geometrigrensen (512 MiB på 64-biters skrivebordsmaskiner, 128 MiB ellers) i stedet for budsjettet som er basert på enheten.", "prefs.reports_saved": "{n} lagret", + "prefs.ribbon_click_ends_tool": "Å klikke på knappen til verktøyet som kjører, avslutter det", + "prefs.ribbon_click_ends_tool_note": "Et klikk på den lysende båndknappen til skisseverktøyet som er i bruk, avslutter verktøyet, så klikk i visningen velger igjen. Av: klikket starter verktøyet på nytt.", "prefs.ribbon_reveal": "Vis søkeresultater på båndet", "prefs.ribbon_reveal_note": "Når pekeren holdes over et resultat i Søk i kommandoer, vises hvor kommandoen ligger på båndet: fanen, knappen eller raden i et panels nedtrekksmeny. En kommando som startes fra søket, blinker der, og en kjørende kommando fra en nedtrekksmeny markerer panelet sitt.", "prefs.right_click": "Høyreklikk", @@ -1965,6 +2343,8 @@ "prefs.search_empty": "Ingen samsvarende innstillinger", "prefs.select": "Velg", "prefs.select_one_item": "Velg ett element", + "prefs.select_other_hidden": "Velg skjult geometri med Velg annet", + "prefs.select_other_hidden_help": "På: ta med skjulte kropper, skisser og tildekte kanter nær pekeren. Av: bruk den opprinnelige listen over synlig geometri under pekeren.", "prefs.selecting": "Valg", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift legger bare til; Ctrl / Cmd veksler", @@ -1976,31 +2356,63 @@ "prefs.sketch_align_points_note": "Under tegning justeres et punkt vannrett etter ett skissepunkt og loddrett etter et annet samtidig, med en prikket hjelpelinje, og klikket beholder begge justeringene. Av: bare etter forrige punkt, én akse om gangen.", "prefs.sketch_conflict_colour": "Motstridende geometri i konfliktfargen", "prefs.sketch_conflict_colour_note": "Mens bindingene i en skisse er i konflikt, tegnes også kurvene og punktene som en feilende binding holder i konfliktfargen, ikke bare symbolet eller målet. Av: de beholder sine vanlige farger.", + "prefs.sketch_construction_lines": "Utvidede hjelpelinjeverktøy", "prefs.sketch_exit_view": "Når en skisse avsluttes", "prefs.sketch_exit_view.keep": "Behold gjeldende visning", "prefs.sketch_exit_view.previous": "Gå tilbake til forrige visning", "prefs.sketch_exit_view.unless_rotated": "Gå tilbake med mindre visningen er rotert", "prefs.sketch_exit_view_note": "Hvor visningen går etter Fullfør skisse, Avbryt eller dobbelt Esc.", + "prefs.sketch_face_activates_part": "Skissering på flaten til en del gjør delen aktiv", + "prefs.sketch_face_activates_part_note": "En skisse som startes på en flate av kroppen til en annen komponent, aktiverer først den komponenten, så skissen tilhører den og blir hos den delen i modelltreet. Delen forblir aktiv etterpå. Av: skissen tilhører den aktive komponenten.", + "prefs.sketch_open_look_at": "Orienter mot skissen når den åpnes", + "prefs.sketch_open_look_at_note": "Av: å opprette eller redigere en skisse lar visningen stå som den er. Orienter mot vender visningen mot skissen når du vil.", "prefs.sketch_recent_snap": "Fang automatisk til nylige sentre og midtpunkter", "prefs.sketch_recent_snap_note": "Under tegning fanges markøren der hjelpelinjene fra de to siste sirkelsentrene eller midtpunktene på rette kanter krysser hverandre. Av: hjelpelinjene vises bare, og markøren flytter seg ikke.", "prefs.sketch_selection": "Skisse og valg", "prefs.sketch_selection_heading": "Skisse og valg", "prefs.sketch_selection_note": "Hvordan skisser bruker punktfangst, og hvordan klikk velger.", + "prefs.sketch_state_icons": "Skisseikoner i fargen til tilstanden deres", + "prefs.sketch_state_icons_note": "I tidslinjen og modelltreet får skisseikonet fargen til skissens tilstand (underbestemt, fullt bundet eller i konflikt), og verktøytipset oppgir tilstanden. Av: alle skisser har samme ikon.", "prefs.sketch_tab_always": "Behold Skisse-fanen synlig", "prefs.sketch_tab_always_note": "Skisse-fanen blir stående på båndet, rett etter Modell, også når ingen skisse er åpen. Tegneverktøyene starter da en skisse på det valgte planet eller den valgte flaten, eller på planet du velger deretter, med verktøyet klart i skissen.", "prefs.sketch_tracking_guides": "Hjelpelinjer for senter og midtpunkt", "prefs.sketch_tracking_guides_note": "Hold over en sirkels senter eller midtpunktet på en rett kant, og flytt deretter vannrett eller loddrett for å vise en midlertidig prikket hjelpelinje.", + "prefs.sketch_tracking_points": "Hjelpelinjer fra endepunkter og hjørner under tegning", + "prefs.sketch_tracking_points_note": "Mens et tegneverktøy venter på et punkt, viser det å holde pekeren over enden av en linje eller bue, hjørnet av et rektangel eller et fritt punkt den samme midlertidige stiplede hjelpelinjen som for et senter eller midtpunkt. Av: bare sentre og midtpunkter.", "prefs.sketching": "Skissetegning", "prefs.snap_drawing_note": "Mens du tegner eller drar et skissepunkt.", "prefs.source": "Kilde", "prefs.speed": "Hastighet", "prefs.stand_up_note": "Når en STEP- eller IGES-fil åpnes med Z opp, tilby en kvart omdreining rundt X.", + "prefs.stand_up_unknown": "For filer fra ukjente programmer", + "prefs.stand_up_unknown.ask": "Spør i en dialog", + "prefs.stand_up_unknown.note": "Vis en melding", + "prefs.stand_up_unknown.off": "Ikke tilby", + "prefs.stand_up_unknown_note": "Hvordan tilbudet gis når filhodet ikke nevner noe program som er kjent for å lagre med Y opp. En melding vises bare når filen ser ut til å ligge på ryggen. Spør i en dialog spør om hver slik fil, som før.", "prefs.status_bar": "Statuslinje", "prefs.status_bar_note": "En tynn linje langs vinduets nedre kant viser hva som redigeres, tilstanden til den åpne skissen i dens farge og designets enheter; et klikk på enhetene endrer dem. Skissens tilstand vises da ikke lenger i hjørnet av visningen.", "prefs.status_done": "Ferdig", "prefs.status_error": "Feil", "prefs.status_selected": "Valgt", "prefs.status_warning": "Advarsel", + "prefs.structure.appearance": "Utseende", + "prefs.structure.appearance_note": "Farger, tekst og tilgjengelighet.", + "prefs.structure.in_profile": "I profilen", + "prefs.structure.layout": "Oppsett", + "prefs.structure.layout_note": "Hvor delene av vinduet plasseres.", + "prefs.structure.look": "Stil", + "prefs.structure.measure_pointer": "Mål og peker", + "prefs.structure.mouse3d": "3D-mus", + "prefs.structure.mouse3d_note": "SpaceMouse og SpaceNavigator.", + "prefs.structure.navigation_note": "Mus og styreflate. 3D-musen har sin egen side.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Endret siden den ble lagret", + "prefs.structure.profile_hover": "Lagret i innstillingsprofiler", + "prefs.structure.scale_percent": "{percent} %", + "prefs.structure.sketch": "Skisse", + "prefs.structure.tools": "Verktøy", + "prefs.structure.tools_note": "Hvordan modelleringsverktøyene oppfører seg.", + "prefs.structure.work": "Arbeid", "prefs.supersampling_brief": "Tegner visningen større og skalerer den ned: svært skarpt, og mer krevende.", "prefs.tab_accent_note": "Aksentfargen følger den aktive fanen", "prefs.theme_file": "temafil", @@ -2012,6 +2424,16 @@ "prefs.theme_follow_off": "Av", "prefs.theme_follow_stop": "Slutt å følge", "prefs.theme_import_hint": "Klikk for å velge en temafil, slipp en her, eller trykk Ctrl+V (Cmd+V på Mac) med et kopiert tema", + "prefs.theme_option_opacity": "Opasitet", + "prefs.theme_option_opacity_help": "Juster opasiteten til flytende paneler. En lesbarhetsgrense beskytter tekst over visningsfarger.", + "prefs.theme_option_tab_colours": "Fanefarger", + "prefs.theme_option_tab_colours_help": "Bruk dette temaets panel- og visningsfarger for hver båndfane.", + "prefs.theme_option_tab_fade_ms": "Faneovergang", + "prefs.theme_option_tab_fade_ms_help": "Toner panel- og visningsfarger når du bytter fane. Null bytter umiddelbart.", + "prefs.theme_options_badge": "Alternativer", + "prefs.theme_options_more": "Flere · {count}", + "prefs.theme_options_reset": "Tilbakestill", + "prefs.theme_options_unavailable": "Ikke tilgjengelig på denne enheten", "prefs.theme_paste": "Lim inn tema", "prefs.theme_paste_none": "Utklippstavlen inneholder ikke noe SolidCraft-tema", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2455,23 @@ "prefs.under_cursor": "Under pekeren", "prefs.units_precision": "Enheter og presisjon", "prefs.updates": "Oppdateringer", + "prefs.value_boxes_in_view": "Vis verdier ved siden av håndtakene i visningen", + "prefs.value_boxes_in_view_tip": "Verdien til en kommando (Avstand, Radius …) i en boks ved siden av håndtaket, over modellen. Av: du skriver den inn i kommandovinduet, som tar over tastaturet etter et valg, og ingenting dekker modellen.", "prefs.view": "Visningsatferd", "prefs.view_confirm_corner": "OK og Avbryt i hjørnet av visningen", "prefs.view_confirm_corner_note": "Mens en dialog eller en skisse er åpen, gjør et hakemerke og et kryss øverst til høyre i visningen det samme som OK og Avbryt i dialogen, eller fullfører og avbryter skissen. Visningsnavigatoren flyttes ned under dem.", "prefs.viewport": "Visningsområde", + "prefs.viewport_analysis_status": "Vis analysestatus i visningsområdet", + "prefs.viewport_analysis_status_help": "Vis aktive analyser over visningsområdet, åpne tegnforklaringene deres fra hvert element, og bruk Esc for å slå av den nyeste analysen. Slå av for å gjenopprette tegnforklaringer i hjørnene og den tidligere Esc-oppførselen.", "prefs.viewport_background": "Bakgrunn", "prefs.viewport_background_colour": "Farge", "prefs.viewport_background_theme": "Temaets gradient", + "prefs.viewport_section_status": "Vis snittstatus i visningsområdet", + "prefs.viewport_section_status_help": "Vis snittinnstillingen i visningsområdet. Escape og den aktive båndknappen slår den av. Slå av for å beholde de tidligere snittkontrollene.", + "prefs.viewport_status_details": "Live detaljer i visningsområdet", + "prefs.viewport_status_details_help": "Rediger aktive analyse- og snittinnstillinger i vanlige detaljkort. Slå av for å gjenopprette skrivebeskyttede tegnforklaringer for analyse og Snitt-dialogen.", + "prefs.viewport_status_summary": "Slå sammen statuselementer i visningsområdet", + "prefs.viewport_status_summary_help": "Slå sammen tre eller flere statuselementer i visningsområdet til ett oppsummeringsmerke. Slå av for å beholde hvert element i hele raden.", "prefs.wheel": "Musehjul", "prefs.wheel_trackpad": "Musehjul og styreflate", "prefs.workspace": "Arbeidsområde", @@ -2049,6 +2481,10 @@ "properties.title": "Egenskaper: {name}", "recovery.days_ago": "for {count} dager siden", "recovery.detail": "{file} · {features} funksjoner · automatisk lagret {when}", + "recovery.discard_all": "Forkast alle", + "recovery.discard_all_detail": "Dette kan ikke angres.", + "recovery.discard_all_title": "Forkast {count} automatiske lagringer?", + "recovery.discard_all_title_one": "Forkast 1 automatisk lagring?", "recovery.hours_ago": "for {count} t siden", "recovery.just_now": "nettopp", "recovery.min_ago": "for {count} min siden", @@ -2164,6 +2600,10 @@ "render.base_color": "Grunnfarge · sRGB", "render.base_metallic": "Metallfraksjon", "render.base_opaque_only": "Denne redigeringen bevarer semantikken for ugjennomsiktige kropper. Bruk de eksplisitte glasskontrollene for optisk transmisjon.", + "render.batch_all_shots": "Alle opptak ({count})", + "render.batch_empty": "Lagre et opptak før alle opptak rendres.", + "render.batch_limit": "Å rendre alle opptak er begrenset til 32 opptak.", + "render.batch_status": "{running} pågår · {waiting} venter", "render.bloom_enable": "Vis bloom", "render.bloom_help": "Kreativ glød kun i utdata, fra positive lineære høylys, spredt med tre normaliserte boksfilterpasseringer. Radius er i utdatapiksler. Legges til i lineært visningslys før sRGB; ikke en linse- eller volumeffekt eller en forbedring av konvergens. Rå EXR er uendret.", "render.bloom_opaque": "Bloom krever ugjennomsiktig utdata. Gjennomsiktig PNG avvises og flates ikke ut i det stille.", @@ -2274,6 +2714,13 @@ "render.choose_look": "Velg en stil i Utseender først", "render.chromatic_offset": "Kromatisk kantforskyvning", "render.clear_stage": "Fjern lagret rendringsdekor", + "render.compare_divider": "Skillelinje i sammenligningen", + "render.compare_live": "Live", + "render.compare_live_preview": "Live-forhåndsvisning", + "render.compare_render": "Rendring {number}", + "render.compare_side": "Rendring {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · registrert ved revisjon {revision}", + "render.compare_swap": "Bytt plass", "render.copy_request": "Kopier JSON", "render.cpu_aa_help": "Romlige prøver: flere prøver forbedrer kanter og øker rendringstiden.", "render.cpu_area_add": "Legg til rektangulært CPU-lys", @@ -2914,7 +3361,9 @@ "render.output_ready": "Klar til rendring", "render.output_run_check": "Kjør sjekk", "render.output_size_limit": "{method}: opptil {dimension} px per side og {pixels} piksler. Største størrelse som passer: {width} × {height}.", + "render.output_size_method_profile": "For å rendre {width} × {height}, velg {method} med CPU-ressursprofilen {profile}, eller en mindre størrelse.", "render.output_size_ok": "Størrelse OK · {width} × {height} px", + "render.output_size_profile": "For å rendre {width} × {height}, velg CPU-ressursprofilen {profile}, eller en mindre størrelse.", "render.output_swap_orientation": "Bytt bredde og høyde", "render.output_tools_inspector": "Rediger størrelse og format i utdatainspektøren.", "render.output_view_image": "Vis bilde", @@ -3021,6 +3470,10 @@ "render.result_retained": "Viser det siste ferdige bildet; en nyere rendring har ikke erstattet det.", "render.result_sequence": "Sjekkpunkt", "render.result_title": "Rendringsresultat", + "render.results_choose": "Beholdte resultater", + "render.results_label": "Rendring {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [utdatert]", + "render.results_unnamed": "Bilde", "render.return_design": "Tilbake til design", "render.review_stale": "Denne gjennomgangen er utdatert. Avklar eller sjekk på nytt før du bruker den.", "render.ribbon_aging": "Aldring", @@ -3127,6 +3580,7 @@ "render.size_custom": "Egendefinert…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · trenger {profile}", "render.size_presets": "Forhåndsinnstillinger for størrelse", "render.size_presets_pending": "Kommer med utdataeditoren", "render.size_preview": "Forhåndsvisning", @@ -3414,6 +3868,24 @@ "sheet.flange_type_contour": "Kontur", "sheet.flange_type_edge": "Kant", "sheet.no_body": "det finnes ingen platemetallkropp: start en med Flens > Basis, eller gjør en plate om til platemetall med Konverter til platemetall (velg den store, flate siden)", + "sheet.personal_rules.confirm_delete": "Bekreft sletting", + "sheet.personal_rules.delete": "Slett", + "sheet.personal_rules.delete_prompt": "Slette denne personlige regelen? Regler som allerede ligger i design, endres ikke.", + "sheet.personal_rules.full": "Det personlige biblioteket inneholder allerede 64 regler.", + "sheet.personal_rules.invalid_name": "Skriv inn et kort navn uten linjeskift eller kontrolltegn.", + "sheet.personal_rules.invalid_values": "Fullfør verdiene i regelen: hver må kunne beregnes i dette designet, med positiv tykkelse og en K-faktor fra 0 til 1.", + "sheet.personal_rules.missing": "Den valgte personlige regelen er ikke lenger tilgjengelig.", + "sheet.personal_rules.name": "Regelnavn", + "sheet.personal_rules.name_exists": "Det finnes allerede en personlig regel med dette navnet. Bruk et annet navn.", + "sheet.personal_rules.name_hint": "Et unikt navn", + "sheet.personal_rules.overwrite": "Lagre endringer i valgt personlig regel", + "sheet.personal_rules.rename": "Gi nytt navn", + "sheet.personal_rules.rule": "Personlig regel", + "sheet.personal_rules.save": "Lagre som ny", + "sheet.personal_rules.scope": "Lagres i profilen din for alle design.", + "sheet.personal_rules.select": "Velg en regel", + "sheet.personal_rules.title": "Personlige regler", + "sheet.personal_rules.unsupported": "Denne regelen har verdier som denne versjonen ikke kan bruke.", "shortcut.json_error": "parametere må være JSON: {error}", "shortcut.no_command": "ingen kommando `{id}`; teksten før JSON må være en kommando-id", "shortcut.pin": "Fest øverst i S-boksen", @@ -3450,8 +3922,10 @@ "sketch_text.align_right": "Høyre", "sketch_text.bold": "Fet", "sketch_text.builtin_font": "{family} (innebygd)", + "sketch_text.formula": "Start med = for å bygge ordene fra parametere: ='W' + number(Width)", "sketch_text.italic": "Kursiv", "sketch_text.loading_fonts": "Ser etter installerte skrifter…", + "sketch_text.no_bold": "Den innebygde skriften har ingen fet utgave: velg en installert skrift", "sketch_text.on_path": "Teksten følger banen og plasseres langs kurven", "sketch_text.path_clear": "Ta teksten av kurven", "sketch_text.path_hint": "Velg en kurve i skissen som teksten skal følge: klikk her og deretter på kurven", @@ -3483,10 +3957,7 @@ "the two origins are on the same component": "de to origoene ligger på samme komponent", "thread.automatic_size": "Automatisk størrelse", "thread.designation": "Betegnelse", - "thread.direction": "Gjengeretning", "thread.iso_metric": "ISO-metrisk", - "thread.left_hand": "Venstregjenget", - "thread.right_hand": "Høyregjenget", "thread.select_size": "Velg størrelse", "timeline.delete_after_marker_one": "Slett 1 funksjon etter historikkmarkøren", "timeline.delete_after_marker_other": "Slett {count} funksjoner etter historikkmarkøren", @@ -3503,8 +3974,10 @@ "timeline.move_to_group": "Flytt funksjoner til gruppe", "timeline.rename_group": "Gi nytt navn til funksjonsgruppe", "timeline.reorder_many": "Omorganiser funksjoner", + "timeline.suppress_features": "Undertrykk funksjoner", "timeline.suppress_folders_tip": "Undertrykk eller opphev undertrykking av alle funksjoner i mappene og de nestede mappene deres", "timeline.ungroup": "Opphev funksjonsgruppering", + "timeline.unsuppress_features": "Opphev undertrykking av funksjoner", "to the face": "til flaten", "to the next face": "til neste flate", "toolbar.customize_note": "Fanen {tab}. Kryss av for en kommando for å legge til en knapp på verktøylinjen. Du kan også dra en rad fra panelets nedtrekksmeny til verktøylinjen, dra en knapp ut av verktøylinjen for å fjerne den, eller feste en kommando fra nedtrekksmenyen.", @@ -3588,6 +4061,8 @@ "ui.3d_mouse_section": "3D-mus", "ui.3d_mouse_show_in_view": "Vis 3D-musen i 3D-visningen", "ui.3d_mouse_show_in_view_tip": "Et bilde av 3D-musen din i nedre venstre hjørne som beveger seg når du beveger den.", + "ui.3d_mouse_sketch_orbit": "Roter skisser med 3D-musen", + "ui.3d_mouse_sketch_orbit_tip": "3D-musen roterer også visningen mens en skisse er åpen og sett rett forfra, slik musen kan. Av: den panorerer og zoomer skissen til du heller visningen.", "ui.3d_mouse_skip": "Enheten min kan ikke gjøre dette", "ui.3d_mouse_skip_tip": "Hopper over denne bevegelsen i begge retninger, og kalibreringen utelater den.", "ui.3d_mouse_speed": "3D-musehastighet", @@ -3616,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Vri knotten mot klokken, hold den, og slipp.", "ui.3d_mouse_switch_cap": "Kalibrer som Tilbake til midten", "ui.3d_mouse_switch_trackball": "Kalibrer som trackball", + "ui.3d_mouse_use_direct": "Bruk direkte driver", + "ui.3d_mouse_use_direct_tip": "Les 3D-musen direkte (hidraw) i stedet for gjennom spacenavd.", "ui.3d_mouse_view_axis": "Visningsakse", "ui.3d_mouse_view_off": "Av", "ui.3d_mouse_view_off_tip": "Profilen til 3D-musdriveren slår av denne aksen, så bevegelsen flytter ikke visningen. Hvis du velger en annen akses bevegelse her, bytter de to plass, og den bevegelsen slutter å flytte visningen.", @@ -3654,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Kjør dette i en terminal, og trykk deretter Koble til igjen:", "ui.agent_chat_auth_title": "Logg inn på agenten", "ui.agent_chat_cancel": "Avbryt", + "ui.agent_chat_cancel_timeout": "Agenten svarte ikke på Stopp og ble koblet fra. Koble til igjen for å fortsette.", + "ui.agent_chat_cannot_start": "Installert, men starter ikke: {error}", "ui.agent_chat_changes": "Endringer: {n}, ett angretrinn", "ui.agent_chat_changes_n": "{n} endringer", "ui.agent_chat_changes_of": "{n}/{limit} endringer", @@ -3662,11 +4141,13 @@ "ui.agent_chat_command": "Agentkommando", "ui.agent_chat_connect": "Koble til", "ui.agent_chat_copy": "Kopier", + "ui.agent_chat_copy_message": "Kopier melding", "ui.agent_chat_ctx_bodies": "Kropper", "ui.agent_chat_ctx_elements": "Elementer", "ui.agent_chat_ctx_features": "Funksjoner", "ui.agent_chat_ctx_more": "+{n} til", "ui.agent_chat_ctx_other": "Annet", + "ui.agent_chat_custom_heading": "Egendefinert modell", "ui.agent_chat_custom_hint": "Et program som bruker Agent Client Protocol via stdin og stdout. Programmet startes uten et kommandoskall.", "ui.agent_chat_denied": "Avvist", "ui.agent_chat_deny": "Avvis", @@ -3710,8 +4191,16 @@ "ui.agent_chat_mode_all": "Alle", "ui.agent_chat_mode_ask": "Spør", "ui.agent_chat_mode_edits": "Endringer", + "ui.agent_chat_model_custom": "Bruk egendefinert modell: {model}", "ui.agent_chat_model_no_tools": "{model} kan ikke bruke verktøyene i SolidCraft, så den kan bare chatte. Velg en modell med verktøystøtte.", + "ui.agent_chat_model_rejected": "Agenten godtok ikke {model}: {error}", + "ui.agent_chat_model_search": "Søk etter modeller…", "ui.agent_chat_model_tip": "Modellen agenten bruker. Valget ditt huskes for denne agenten.", + "ui.agent_chat_models_failed": "Kunne ikke liste opp modellene: {error}", + "ui.agent_chat_models_heading": "Tilgjengelige modeller", + "ui.agent_chat_models_listing": "Henter modeller…", + "ui.agent_chat_models_none": "Endepunktet viser ingen modeller", + "ui.agent_chat_models_not_a_list": "Svaret var ikke en modellliste", "ui.agent_chat_new": "Ny chat", "ui.agent_chat_new_confirm": "Starte en ny chat? Den nåværende tømmes.", "ui.agent_chat_next_picture": "Neste bilde", @@ -3746,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "I kø (stoppet, ikke sendt)", "ui.agent_chat_refresh": "Oppdater", "ui.agent_chat_refused": "Ikke tillatt for agenten: {reason}", + "ui.agent_chat_reinstall": "{agent} er installert ({program}), men startet ikke da SolidCraft sjekket den: {error}\nInstallasjonen kan være ufullstendig, eller laget for en annen type datamaskin. Installer den på nytt med `{install}`, kontroller at den skriver ut versjonen sin i en terminal, og trykk deretter Oppdater.", "ui.agent_chat_remove": "Fjern fra køen", "ui.agent_chat_remove_file": "Fjern vedlegget fra denne meldingen", "ui.agent_chat_remove_imported": "Fjern vedlegget fra denne meldingen. Delen blir i designet (Angre fjerner den).", + "ui.agent_chat_reply_cut_off": "Svaret nådde lengdegrensen før det var ferdig, så det kan være ufullstendig. Be agenten fortsette, eller om et kortere svar.", + "ui.agent_chat_reply_declined": "Modellen avslo å svare på denne meldingen.", "ui.agent_chat_retry": "Prøv igjen", "ui.agent_chat_right": "Høyre", "ui.agent_chat_save": "Lagre", @@ -3807,12 +4299,17 @@ "ui.ai_copy_suffix": "kopi", "ui.ai_custom_url": "Egendefinert URL", "ui.ai_default": "Standard", + "ui.ai_edit": "Rediger", + "ui.ai_edit_agent_title": "Rediger agent", + "ui.ai_edit_gone": "Denne agenten ble fjernet, så det er ingenting å lagre.", + "ui.ai_edit_tip": "Endre navn, kommando eller endepunkt for denne agenten. En lagret nøkkel forblir skjult.", "ui.ai_http_busy": "endepunktet er opptatt eller over grensen; prøv igjen senere", "ui.ai_http_key": "endepunktet avviste nøkkelen: sjekk den i Innstillinger > AI", "ui.ai_http_not_found": "endepunktet eller modellen finnes ikke; kontroller base-URL og modellnavn", "ui.ai_http_too_large": "samtalen er for stor for dette endepunktet; start en ny chat", "ui.ai_key": "API-nøkkel", "ui.ai_key_hint": "valgfritt; lagres i systemets nøkkelring", + "ui.ai_key_keep_hint": "la stå tom for å beholde den lagrede nøkkelen", "ui.ai_key_needs_https": "En nøkkel sendes bare over HTTPS, eller til denne datamaskinen.", "ui.ai_key_note": "Lagres i systemets nøkkelring, aldri i SolidCrafts innstillinger. La den stå tom for en lokal server.", "ui.ai_keychain_error": "Systemets nøkkelring avviste forespørselen: {error}", @@ -3839,11 +4336,15 @@ "ui.ai_permissions": "Tillatelser", "ui.ai_preset": "Forhåndsinnstilling", "ui.ai_protocol": "Protokoll", + "ui.ai_reasoning_effort": "Resonneringsinnsats", + "ui.ai_reasoning_effort_field_hint": "tom = standard fra leverandøren", + "ui.ai_reasoning_effort_hint": "Valgfritt. Sendes til endepunktet som `reasoning_effort`; godkjente verdier varierer fra leverandør til leverandør (for eksempel `low`, `high` eller `max`). En verdi du angir her, blir aldri erstattet av SolidCraft. La feltet stå tomt for å ikke sende noe og beholde leverandørens standard.", "ui.ai_remove": "Fjern", "ui.ai_request_timed_out": "Modellen brukte lenger tid enn {seconds} s. Du kan øke tidsavbruddet for forespørsler til dette endepunktet i Innstillinger › Assistent.", "ui.ai_request_timeout": "Tidsavbrudd for forespørsel", "ui.ai_request_timeout_hint": "Hvor lang tid én modellforespørsel til dette endepunktet kan ta, fra 30 s til en time. Øk verdien for en treg lokal modell.", "ui.ai_reset": "Tilbakestill", + "ui.ai_save": "Lagre", "ui.ai_settings": "AI-innstillinger…", "ui.ai_show_features": "Vis AI-funksjoner", "ui.ai_show_features_note": "Agentchat er et panel der en kodeagent du allerede bruker, eller et modellendepunkt du velger, arbeider på det åpne designet. Når dette er av, vises ingen AI-knapp, snarvei, menypunkt eller panel, og ingen agenter søkes etter eller startes.", @@ -3922,6 +4423,8 @@ "ui.cancel": "Avbryt", "ui.canvases": "Lerreter", "ui.center": "Senter", + "ui.center_arc_follows_cursor": "Senterpunktbue følger markørens retning", + "ui.center_arc_follows_cursor_tip": "En senterpunktbue går med eller mot klokken, etter hvordan markøren beveger seg rundt senteret. Av: alltid mot klokken fra start.", "ui.centerline": "Senterlinje", "ui.chain": "Kjede", "ui.chamfer": "Fas", @@ -3930,6 +4433,7 @@ "ui.circle": "Sirkel", "ui.circular_pattern": "Sirkulært mønster", "ui.clear": "Tøm", + "ui.clear_print_face": "Fjern utskriftsflate", "ui.clear_recent": "Tøm listen over nylige design", "ui.clear_the_selection": "Tøm utvalget", "ui.click_selects_whole_bodies": "Klikk velger hele kropper", @@ -3964,12 +4468,27 @@ "ui.constant": "Konstant", "ui.constraints_conflict": "Bindinger i konflikt", "ui.construction": "Konstruksjon", + "ui.construction.angle_hint": "Hjelpelinje: klikk på et punkt, og skriv deretter inn en vinkel eller velg en retning", + "ui.construction.bisector_hint": "Vinkelhalveringslinje: velg to rette linjer som krysser hverandre, og deretter ønsket løsning", + "ui.construction.common_hint": "Felles tangent: velg to sirkler/buer, og deretter ønsket løsning", + "ui.construction.contact_hint": "Tangent: velg en sirkel/bue eller åpen spline/kjeglesnittkurve, og deretter berøringspunktet (frie kurver: endepunkter)", + "ui.construction.external_hint": "Tangent: velg en sirkel eller bue, et eksternt punkt, og deretter ønsket løsning", + "ui.construction.free_hint": "Hjelpelinje: klikk på to punkter; høyreklikk for å starte på nytt", + "ui.construction.normal_needs_length": "En uendelig linje er alltid en hjelpelinje: skriv inn en lengde for å tegne en normal linje", + "ui.construction.point_hint": "Hjelpelinje: klikk på punktet linjen skal gå gjennom", + "ui.construction.reference_hint": "Hjelpelinje: velg en rett linje, og deretter et punkt; høyreklikk for å bytte referanse", "ui.construction.ribbon_label": "Hjelpelinjer", + "ui.construction.side_hint": "Hjelpelinje: klikk på siden linjen går mot; høyreklikk for å starte på nytt", "ui.context_menu": "Kontekstmeny", + "ui.continuity_crease": "Knekk", + "ui.continuity_curvature": "Krumning", + "ui.continuity_curvature_change": "Krumningsendring", "ui.continuity_g0": "G0-knekk", "ui.continuity_g1": "G1-tangent", "ui.continuity_g2": "G2-krumning", "ui.continuity_gap": "Gap", + "ui.continuity_position": "Posisjon", + "ui.continuity_tangent": "Tangent", "ui.copy": "Kopier", "ui.corner": "Hjørne", "ui.corners": "Hjørner", @@ -3992,6 +4511,7 @@ "ui.dark": "Mørk", "ui.default_modelling_orientation": "Standard modelleringsorientering", "ui.delete": "Slett", + "ui.delete_select_first": "Velg først hva som skal slettes: funksjoner, kropper, komponenter eller skissegeometri", "ui.depth": "Dybde", "ui.design": "Design", "ui.design_properties.author": "Forfatter", @@ -4006,6 +4526,40 @@ "ui.design_properties.project": "Prosjekt", "ui.design_properties.revision": "Revisjon", "ui.design_saved": "Lagret i {path}", + "ui.details_access_caption": "Flatene viser om et verktøy kan nå dem fra den valgte retningen.", + "ui.details_angle": "Vinkel", + "ui.details_continuity_caption": "Rediger den valgte skjøten. Andre skjøter beholder sine egne innstillinger.", + "ui.details_continuity_stale": "Tidligere geometri: kjør analysen på nytt for å redigere eller innramme denne skjøten.", + "ui.details_copy_list": "Kopier listen", + "ui.details_curvature": "Krumningstoleranse", + "ui.details_curvature_caption": "Flatene fargelegges etter lokal krumningsradius.", + "ui.details_direction": "Verktøyretning", + "ui.details_draft_caption": "Flatene fargelegges etter vinkelen til trekkretningen.", + "ui.details_edit_seam": "Rediger skjøt", + "ui.details_fixture": "Komponenteksempel — bare eksempeldata", + "ui.details_fixture_caption": "Komponenteksempel med illustrerende verdier; dette er ikke et modellresultat.", + "ui.details_fixture_problem": "Eksempelfunn med et problem", + "ui.details_fixture_readout": "Eksempel på målt verdi", + "ui.details_flip": "Snu", + "ui.details_gap": "Mellomrom", + "ui.details_hatch": "Skraver snittflatene", + "ui.details_jump": "Krumningssprang", + "ui.details_key": "Tegnforklaring", + "ui.details_offset": "Offset", + "ui.details_plane": "Plan", + "ui.details_pull": "Trekkretning", + "ui.details_radius": "Radius", + "ui.details_readout": "Avlesning", + "ui.details_samples": "Prøver", + "ui.details_seam": "{body} · Kant {edge}", + "ui.details_settings": "Innstillinger", + "ui.details_sharp_gap": "Skarp eller mellomrom", + "ui.details_show_all": "Vis alle {count}", + "ui.details_smooth": "Jevn", + "ui.details_stripes": "Striper", + "ui.details_target": "Innram geometrien", + "ui.details_worst_seams": "Dårligste skjøter", + "ui.details_zebra_caption": "Reflekterte striper viser hvor jevnt flatene går sammen.", "ui.diameter": "Diameter", "ui.dimension": "Mål", "ui.direct_interaction": "Direkte interaksjon", @@ -4050,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "Delen ble lagret i en annen fil; sammenstillingen er fortsatt koblet til {name}", "ui.edit_in_place_wait": "Vent til det som kjører i designet er ferdig", "ui.edit_section_analysis": "Rediger snittanalyse", + "ui.edit_sketch_empty": "Ingen skisser å redigere", "ui.ellipse": "Ellipse", "ui.emboss_wrap_note": "Ortogonale linjeprofiler som tangerer én støttet sylinder, legges automatisk rundt den. Velg en vegg for å velge et mål.", "ui.end_radius": "Sluttradius", @@ -4060,12 +4615,15 @@ "ui.equation_explicit": "Eksplisitt", "ui.equation_form": "Form", "ui.equation_note": "Variabelen er et rent tall: sin(t) tolker det i radianer. Et resultat uten enhet er i designets enhet.", + "ui.equation_note_range": "Variabelen er en lengde, slik intervallet er: kombiner den med lengdeparametere, og del den på en lengde for sin(). Et resultat uten enhet er i designets enhet.", "ui.equation_parametric": "Parametrisk", + "ui.equation_variable_unit": "Variabelen har intervallets enhet", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Ekvivalent radius", "ui.expand": "Utvid", + "ui.explode_needs_two_components": "Eksplodert visning trekker komponenter fra hverandre, så designet må ha to eller flere av dem (Ny komponent, Sett inn design eller Opprett komponenter fra kropper)", "ui.exportDxf": "Eksporter DXF…", "ui.export_ellipsis_keymap": "Eksporter…", "ui.export_keymap_tip": "Taster, S-boks-favoritter og verktøylinjen, som en fil", @@ -4191,6 +4749,7 @@ "ui.hideOrigin": "Skjul origo", "ui.hidePlanes": "Skjul plan", "ui.hideProfile": "Skjul profil", + "ui.hide_component_history": "Skjul dens tidslinje", "ui.hide_origin_by_default": "Skjul origo som standard", "ui.hide_origin_note": "Nye design starter med Origo-mappen skjult. Et design beholder sin egen Origo-innstilling når du har vist eller skjult den.", "ui.history_back": "Gå ett trinn tilbake", @@ -4198,6 +4757,7 @@ "ui.history_edge_hint": "dobbeltklikk kanten", "ui.history_first": "Gå til starten", "ui.history_forward": "Gå ett trinn frem", + "ui.history_hide_hidden": "Skjul skjulte komponenter", "ui.history_hide_names": "Skjul navn", "ui.history_last": "Gå til slutten", "ui.history_marker_tip": "Tidslinjemarkør: dra for å vise en tidligere tilstand av modellen. Nye funksjoner legges til her.", @@ -4207,10 +4767,12 @@ "ui.history_play_button_show": "Vis avspillingsknapp", "ui.history_play_finish_action": "Fullfør gjeldende handling før du spiller av tidslinjen", "ui.history_play_roll_back": "Flytt tidslinjemarkøren tilbake før avspilling", + "ui.history_show_hidden": "Vis skjulte komponenter", "ui.history_show_names": "Vis navn", "ui.history_sketch_listed_under": "Oppført under {feature}", "ui.history_title": "Tidslinje", "ui.history_toggle_names": "Vis eller skjul funksjonsnavn", + "ui.history_waits_for_editor": "Angre, Gjør om og Tidslinje venter til funksjonsredigeringen er åpnet", "ui.hole": "Hull", "ui.hole_tap_type": "Type gjenging", "ui.hole_type": "Hulltype", @@ -4226,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} har ulagrede endringer, så den lagrede filen ble satt inn. Lagre den, og bruk deretter Oppdater koblinger for å hente inn endringene.", "ui.insert_design.unsaved": "Ulagrede endringer", "ui.inspect": "Inspiser", + "ui.instances": "Forekomster", "ui.intersect": "Snitt", "ui.isolate": "Isoler", "ui.join": "Slå sammen", @@ -4234,12 +4797,14 @@ "ui.joints": "Ledd", "ui.keyboard_shortcuts": "Tastatursnarveier", "ui.language": "Språk", + "ui.lasso_select": "Lasso (dra en frihåndssløyfe: velger alt som ligger helt innenfor)", "ui.layout_compact": "Kompakt", "ui.layout_floating": "Flytende", "ui.length": "Lengde", "ui.length_decimals": "Lengdedesimaler", "ui.light": "Lys", "ui.line": "Linje", + "ui.line_arc_hint": "Tangentbue: klikk på enden av buen. Hvil på det siste punktet igjen for linjer; høyreklikk eller Esc for å avslutte", "ui.link_copies": "Lenk identiske kopier", "ui.link_copies_keep": "Behold", "ui.link_copies_link": "Lenk", @@ -4328,6 +4893,7 @@ "ui.part_size_shared": "Bygger delen på nytt og erstatter eventuelle funksjoner som er lagt til. Alle forekomster av denne komponenten oppdateres.", "ui.paste": "Lim inn", "ui.path": "Bane", + "ui.pattern_object_type_tip": "Kropper: volumformer, valgt i visningen eller modelltreet; hver kopieres hel.\nFunksjoner: trinn i tidslinjen, som en ekstrudering eller et hull, valgt i tidslinjen eller på en flate de har laget; trinnet gjentas.\nEn skisse er ingen av delene: gjenta kurvene med skissens eget Mønster eller Speil, eller ekstruder den først.", "ui.pattern_on_path": "Mønster på bane", "ui.perforate_margin_default": "fra diameteren", "ui.perforate_pitch": "Senteravstand", @@ -4354,12 +4920,17 @@ "ui.plugins_skipped": "{count} mappe(r) kunne ikke leses.", "ui.plugins_version": "{version}", "ui.point": "Punkt", + "ui.point_cloud_add_filter": "Legg til filter…", "ui.point_cloud_auto_range": "Automatisk område", "ui.point_cloud_color_by": "Farge etter", "ui.point_cloud_file_colors": "Filfarger", + "ui.point_cloud_filter_by": "Filtrer etter", "ui.point_cloud_height_high": "Høyeste", "ui.point_cloud_height_low": "Laveste", + "ui.point_cloud_legend_filter": "Vises og skjules i tegnforklaringen ovenfor", "ui.point_cloud_no_file_colors": "Filen har ingen farger", + "ui.point_cloud_pause": "Pause", + "ui.point_cloud_play": "Spill av", "ui.point_cloud_single_color": "Én farge", "ui.point_cloud_size": "Punktstørrelse", "ui.point_cloud_units": "Filenheter", @@ -4368,6 +4939,11 @@ "ui.polygon": "Mangekant", "ui.preferences": "Innstillinger", "ui.press_a_key": "trykk på en tast…", + "ui.print_face_body_not_sent": "Legemet til den flaten sendes ikke: legg det til i Kropper først", + "ui.print_face_cleared": "{body}: utskriftsflate fjernet", + "ui.print_face_input": "Utskriftsflate", + "ui.print_face_pick": "Velg en plan flate på et massivt legeme for å gjøre den til utskriftsflaten", + "ui.print_face_set": "{body}: utskriftsflate satt; Send til slicer legger legemet på den", "ui.profile": "Profil", "ui.profile_plane": "Profilplan", "ui.profiles": "Profiler", @@ -4383,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Måler…", + "ui.properties.measuring_bodies": "Måler… {done} av {total} legemer", "ui.properties.measuring_failed": "Målingen stoppet før den var ferdig.", "ui.properties.principal_axis": "Hovedakse {number}", "ui.properties.principal_moments": "Hovedtreghetsmomenter", @@ -4431,6 +5008,7 @@ "ui.revolve": "Omdreining", "ui.ribbon_exit": "Avslutt", "ui.ribbon_labels": "Vis tekst under båndikonene", + "ui.ribbon_menus_skip_pinned": "Utelat festede kommandoer fra nedtrekksmenyene", "ui.ribbon_pin_footer": "Festede kommandoer vises på båndet. Hold pekeren over en rad for å feste eller løsne kommandoen.", "ui.ribbon_workspace": "Arbeidsområde", "ui.right": "Høyre", @@ -4449,6 +5027,7 @@ "ui.selectOther": "Velg annet…", "ui.selectTangentChain": "Velg tangentkjede", "ui.select_all": "Velg alle", + "ui.select_components_by_face": "Velg komponenter (en flate velger komponenten sin)", "ui.selection": "Utvalg", "ui.selection_modifiers": "Utvalgsmodifikatorer", "ui.selection_shift_add_only": "Shift+klikk legger til uten å fjerne", @@ -4474,6 +5053,7 @@ "ui.showDimension": "Vis mål", "ui.showOrigin": "Vis origo", "ui.showPlanes": "Vis plan", + "ui.show_component_history": "Vis dens tidslinje", "ui.show_constraints": "Bindinger", "ui.show_construction_geometries": "Konstruksjonsgeometri", "ui.show_dimensions": "Mål", @@ -4490,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Utvalgsfilter", "ui.sketch_modifiers": "Skissemodifikatorer", "ui.sketch_project_geometry": "Geometri", + "ui.sketch_report.all_constrained": "Alt er fullstendig bundet.", + "ui.sketch_report.dof": "Frihetsgrader", + "ui.sketch_report.loose": "Ikke fullstendig bundet", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Skisserapport", "ui.sketch_scale": "Skisseskala", "ui.sketches": "Skisser", "ui.slice": "Snittvisning", @@ -4585,19 +5170,31 @@ "ui.view_angles": "Visningsvinkler", "ui.view_angles_convention": "Grader om oppaksen. Giring 0° er frontvisningen, 90° venstre, −90° høyre, 180° bak; helning 90° er toppvisningen; positiv rull dreier modellen med klokken.", "ui.view_angles_help": "Viser visningens helning, giring og rull i grader og projeksjonen under orienteringsindikatoren. Klikk på avlesningen for å skrive inn nøyaktige vinkler.", + "ui.view_angles_lock": "Lås {axis}", "ui.view_angles_ortho": "Orto", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Helning", "ui.view_angles_readout": "Helning {pitch} · Giring {yaw} · Rull {roll}", "ui.view_angles_roll": "Rull", + "ui.view_angles_unlock": "Lås opp {axis}", "ui.view_angles_yaw": "Giring", + "ui.view_angles_zero": "Sett {axis} til 0°", "ui.view_centre": "Visningssenter", "ui.viewport_status_clear": "Slå av {name}", "ui.viewport_status_clear_hint": "Slå av {name} · Esc", + "ui.viewport_status_edges": "{count} kanter", + "ui.viewport_status_from": "fra {direction}", "ui.viewport_status_key": "Vis tegnforklaring for {name}", "ui.viewport_status_minimum_radius": "Minimumsradius", "ui.viewport_status_pairs": "{count} par", + "ui.viewport_status_section_hatch": "{setting} · skravur", + "ui.viewport_status_section_plane": "Gjeldende plan", + "ui.viewport_status_section_tilted": "skråstilt · {offset}", "ui.viewport_status_stripes": "{count} striper", + "ui.viewport_status_summary_clear": "Slå av alt", + "ui.viewport_status_summary_heading": "I denne visningen", + "ui.viewport_status_summary_label": "{name} og {count} elementer til", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Følg tema", "ui.visual_shaded_hidden_edges": "Skyggelagt med skjulte kanter", "ui.visual_shaded_with_edges": "Skyggelagt med kanter", @@ -4634,10 +5231,12 @@ "update.button": "Oppdater", "update.button_version": "Oppdater til {version}", "update.check_automatically": "Se etter oppdateringer automatisk", + "update.check_for_updates": "Se etter oppdateringer", "update.check_now": "Sjekk nå", + "update.check_unavailable": "Søk etter oppdateringer er ikke tilgjengelig for denne installasjonen.", "update.checking": "Sjekker…", "update.copy": "Kopier", - "update.dmg_opened": "Diskbildet er åpent og verifisert: dra SolidCraft til Applications, erstatt den gamle kopien, og start deretter SolidCraft på nytt.", + "update.dmg_opened": "Diskbildet er åpent og verifisert: avslutt SolidCraft, dra det nye SolidCraft til Applications, erstatt den gamle kopien, og åpne deretter SolidCraft igjen.", "update.download": "Last ned", "update.download_open": "Last ned og åpne", "update.downloading": "Laster ned og verifiserer… {done} av {total} MB", @@ -4648,11 +5247,13 @@ "update.installed": "SolidCraft {version} er installert. Start på nytt for å bruke den.", "update.installer_started": "Installasjonsprogrammet starter når SolidCraft lukkes.", "update.later": "Minn meg på senere", + "update.managed": "Oppdatering tilgjengelig: oppdater SolidCraft i {manager}", "update.no_notes": "Denne utgivelsen har ingen merknader.", "update.package_hint": "Denne kopien kom fra en {kind}. Last ned den nye pakken, og installer den med:", "update.prefs_dev": "Dette er et utviklingsbygg ({version}): det ser ikke etter oppdateringer.", "update.prefs_flatpak": "Flatpak oppdaterer denne kopien ({version}): kjør {command} eller bruk programvaresenteret. SolidCraft sjekker ikke.", "update.prefs_label": "Oppdateringer", + "update.prefs_managed": "Dette er SolidCraft {version}, administrert av {manager}. Ved en oppdateringssjekk spør programmet GitHub om den nyeste utgivelsen, og ingen andre opplysninger sendes. Oppdater SolidCraft i {manager}.", "update.prefs_note": "Dette er SolidCraft {version} ({kind}). Ved en oppdateringssjekk spør programmet GitHub om den nyeste utgivelsen. Ingen andre opplysninger sendes.", "update.prefs_web": "Last inn siden på nytt for å få den nyeste nettappen. Hvis nettverket ikke er tilgjengelig, eller oppdateringen ikke rekker å lastes ned i tide, åpnes den lagrede versjonen i stedet; en nedlasting som pågår, fortsetter til neste gang siden lastes inn på nytt.", "update.refresh_checking": "Ser etter den nyeste utgivelsen…", @@ -4679,6 +5280,7 @@ "web.open_link": "Åpne lenket design?", "web.open_link_confirm": "Det finnes ulagrede endringer. Åpne det lenkede designet i en ny fane?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ velg · Enter / Tab fullfør · Esc lukk", + "↑ ↓ choose · Enter applies this value": "↑ ↓ velg · Enter bruker denne verdien", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ velg · Enter bruker det du skrev · Esc lukk", "⌘Enter continues on GitHub.": "⌘Enter fortsetter på GitHub." } diff --git a/assets/locales/nl.json b/assets/locales/nl.json index 2638e00cc..6a53a3e10 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "SAMENVOEGOPPERVLAK", "BOUNDARY SURFACE": "BEGRENZINGSOPPERVLAK", "BROWSER": "BROWSER", + "Back to the original order": "Terug naar de oorspronkelijke volgorde", "Ball": "Kogel", "Bar": "Staaf", "Base Center": "Basismiddelpunt", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Ontwerpen die u opent of opslaat, verschijnen hier.", "Determined by To Object. Choose Angle to edit the angular extent.": "Bepaald door Tot object. Kies Hoek om de hoekomvang te bewerken.", "Diameter": "Diameter", + "Did this assembly open the wrong way up?": "Is deze samenstelling verkeerd om geopend?", + "Did this part open the wrong way up?": "Is dit onderdeel verkeerd om geopend?", "Dimension new shapes": "Nieuwe vormen maatvoeren", "Direction": "Richting", "Discard": "Verwerpen", @@ -474,6 +477,7 @@ "Rectangular": "Rechthoekig", "Rectangular Tube": "Rechthoekige buis", "Reference face": "Referentievlak", + "Reference plane": "Referentievlak", "Relief Depth": "Vrijsnijdiepte", "Relief Width": "Vrijsnijbreedte", "Remove Tools": "Gereedschappen verwijderen", @@ -553,6 +557,7 @@ "Section": "Doorsnede", "Section (optional)": "Doorsnede (optioneel)", "Section position": "Positie van de doorsnede", + "Sections": "Doorsneden", "Sections (one sketch each)": "Doorsneden (één schets per doorsnede)", "Select Other": "Overige selecteren", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Overige selecteren: houd de linkermuisknop stil op het model (of klik met rechts › Overige selecteren…) om alles onder de cursor weer te geven; klik opnieuw op dezelfde plek om het volgende item daar te selecteren. Dubbelklik met de middelste knop om naar Home te gaan (Voorkeuren › Navigatie).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Snappen op middelpunten van vlakken en randen", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft kan rapporten niet rechtstreeks indienen. Dien ze in op GitHub; in de app is geen token nodig.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft is gesloten voordat deze ontwerpen zijn opgeslagen. Hun laatste automatische opslag kan worden geopend.", + "Sort A to Z": "Sorteren van A tot Z", + "Sort Z to A": "Sorteren van Z tot A", "Spacing 2 must be a non-zero number": "Tussenruimte 2 moet een getal ongelijk aan nul zijn", "Spacing must be a non-zero number": "De tussenruimte moet een getal ongelijk aan nul zijn", "Specialise": "Specialiseren", @@ -601,6 +608,7 @@ "Square": "Vierkant", "Stand it up": "Rechtop zetten", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Rechtop zetten: een kwartslag om X, als één Verplaatsen-kenmerk dat u ongedaan kunt maken.", + "Stand this assembly up?": "Deze samenstelling rechtop zetten?", "Stand this part up?": "Dit onderdeel rechtop zetten?", "Start angle": "Beginhoek", "Start bulge": "Beginbolling", @@ -772,6 +780,8 @@ "at the face": "op het vlak", "bom.group_children": "Subonderdelen in de rij van hun onderdeel", "browser.body_name": "Lichaam{number}", + "browser.calibrate_click_a": "Klik op de afbeelding voor Punt A of typ de coördinaten ervan.", + "browser.calibrate_click_b": "Klik op de afbeelding voor Punt B of typ de coördinaten ervan.", "browser.calibrate_title": "Kalibreren: {name}", "browser.capture_many": "{count} componenten zijn verplaatst, maar hun posities zijn niet vastgelegd.", "browser.capture_note": "Vastleggen behoudt de nieuwe positie; Terugzetten zet deze terug.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (bevestiging kwijt)", "browser.sketch_editing": "{name} (wordt bewerkt)", "browser.sketch_name": "Schets{number}", + "browser.sketches_to_parts_already_in_part": "al in hun onderdeel", + "browser.sketches_to_parts_design_body": "op een lichaam van het ontwerp zelf", + "browser.sketches_to_parts_moved": "{moved} schetsen verplaatst naar het onderdeel waarop ze staan", + "browser.sketches_to_parts_no_exact_attachment": "op een vlak zonder exacte bevestiging", + "browser.sketches_to_parts_not_on_face": "niet op het vlak van een onderdeel", + "browser.sketches_to_parts_part_missing": "hun onderdeel bestaat niet meer", + "browser.sketches_to_parts_result": "{moved} schetsen verplaatst naar het onderdeel waarop ze staan; {stayed} bleven staan: {why}", "browser.units": "Eenheden: {units}", "cam.flat": "Plat vlak", "cam.follower": "Volger", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Uiterlijk oppakken", "cmd.appearance_replace": "Uiterlijk vervangen", "cmd.assembly_bom": "Stuklijst", + "cmd.assembly_mass_properties": "Massa-eigenschappen", + "cmd.body.print_face": "Printvlak", "cmd.body_rename": "Lichaam hernoemen", "cmd.browser_collapse_all": "Alles samenvouwen", "cmd.browser_expand_all": "Alles uitvouwen", @@ -842,6 +861,7 @@ "cmd.component_extract": "Naar bestand extraheren", "cmd.component_finish_edit": "Bewerken voltooien", "cmd.component_from_bodies": "Componenten maken van lichamen", + "cmd.component_hide_history": "Componentgeschiedenis verbergen", "cmd.component_insert_design": "Ontwerp invoegen", "cmd.component_links": "Koppelingen weergeven", "cmd.component_list": "Componenten weergeven", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Lichamen naar component verplaatsen", "cmd.component_move_features": "Kenmerken naar component verplaatsen", "cmd.component_move_sketches": "Schetsen naar component verplaatsen", + "cmd.component_move_sketches_to_parts": "Schetsen naar hun onderdeel verplaatsen", "cmd.component_paste_from_design": "Plakken uit een ander ontwerp", "cmd.component_paste_new": "Nieuw plakken", "cmd.component_properties": "Fysieke eigenschappen component", @@ -857,6 +878,7 @@ "cmd.component_rename": "Component hernoemen", "cmd.component_replace_with_link": "Vervangen door koppeling", "cmd.component_revert_position": "Positie terugzetten", + "cmd.component_show_history": "Componentgeschiedenis tonen", "cmd.component_unlock": "Inhoud ontgrendelen", "cmd.component_update_links": "Koppelingen bijwerken", "cmd.config_activate": "Configuratie activeren", @@ -867,6 +889,7 @@ "cmd.config_rule": "Configuratieregel", "cmd.config_rules": "Configuratieregels", "cmd.config_table": "Configuratietabel tonen", + "cmd.construct.plane.axis_point": "Vlak door as en punt", "cmd.construct_axis_edge": "As door rand", "cmd.construct_axis_normal_to_face": "As loodrecht op vlak", "cmd.construct_axis_through_cylinder": "As door cilinder/kegel/torus", @@ -915,6 +938,11 @@ "cmd.explode_show": "Explosieweergave tonen", "cmd.expr_evaluate": "Expressie evalueren", "cmd.face_delete": "Vlak verwijderen", + "cmd.file.export_3mf": "3MF exporteren", + "cmd.file.export_obj": "OBJ exporteren", + "cmd.file.export_step": "STEP exporteren", + "cmd.file.export_stl": "STL exporteren", + "cmd.file.export_urdf": "URDF exporteren", "cmd.file_export": "Exporteren", "cmd.file_insert_mesh": "Mesh invoegen", "cmd.file_insert_step": "STEP invoegen", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Componentkleuren inschakelen", "cmd.inspect_colored_components_disable": "Componentkleuren uitschakelen", "cmd.inspect_compare": "Lichamen vergelijken", + "cmd.inspect_compare_picture": "Afbeelding vergelijken", "cmd.inspect_continuity": "Continuïteitsanalyse", "cmd.inspect_curvature_comb": "Krommingskamanalyse", "cmd.inspect_curvature_map": "Krommingskaartanalyse", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Puntenwolk bewerken", "cmd.pointcloud_insert": "Puntenwolk invoegen", "cmd.pointcloud_list": "Puntenwolken", + "cmd.render.compare.divider": "Scheidingslijn van de rendervergelijking verplaatsen", + "cmd.render.result.discard": "Renderresultaat verwerpen", + "cmd.render.result.select": "Renderresultaat selecteren", "cmd.render_aging_describe": "Gelaagde oppervlakveroudering", "cmd.render_backends": "Render-backends", "cmd.render_batch": "Alle renderopnamen renderen", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline met controlepunten (graad 5)", "cmd.sketch_spline_fit_point": "Spline door punten", "cmd.sketch_spline_insert_point": "Splinepunt toevoegen", + "cmd.sketch_spline_remove_point": "Splinepunt verwijderen", "cmd.sketch_spline_reverse": "Splinerichting omkeren", "cmd.sketch_spun_profile": "Gedraaid profiel", "cmd.sketch_toggle_diameter": "Straal/diameter omschakelen", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Tijdlijnmarkering verplaatsen", "cmd.timeline_stop": "Geschiedenis stoppen", "cmd.timeline_suppress": "Kenmerk onderdrukken", + "cmd.ui.assistant": "Assistent tonen/verbergen", "cmd.view.render_browser": "Renderbrowser", "cmd.view.render_dock": "Renderdock verplaatsen", "cmd.view.render_focus": "Renderfocusweergave", + "cmd.view.status_details": "Statusdetails in de viewport", "cmd.view.status_items": "Statusitems in de viewport", "cmd.view_ambient_occlusion": "Ambient occlusion", "cmd.view_angle_readout": "Weergavehoeken", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Navigatiegereedschap", "cmd.view_top": "Bovenaanzicht", "cmd.view_visual_style": "Visuele stijl", + "color.blue": "Blauw", "color.copy": "Klik om kleurwaarden te kopiëren", "color.edit": "Klik om kleur te bewerken", "color.gamma": "Kleurwaarden worden getoond in gammaruimte 0-255", + "color.green": "Groen", "color.hex": "Hex", "color.hex_help": "Voer #rrggbb of #rrggbbaa in; met zes cijfers blijft de dekking behouden", "color.hex_hint": "#rrggbb", "color.hue": "Tint", "color.linear": "Kleurwaarden worden getoond in lineaire ruimte 0-1", + "color.recent": "Recente kleuren", + "color.recent_help": "Kleuren die je in een kleurveld kiest, verschijnen hier", + "color.red": "Rood", + "color.saturation": "Verzadiging (procent)", "color.saturation_value": "Verzadiging en waarde", "color.selected": "Geselecteerde kleur", + "color.step_down": "Stap omlaag", + "color.step_up": "Stap omhoog", + "color.value": "Waarde, de helderheid (procent)", "config.column_filter_empty": "Geen overeenkomende kolommen", + "config.rule_parameter_columns": "Alleen parameters met een kolom in de tabel worden weergegeven. Voeg een kolom toe met Kolom toevoegen (+) om de parameter hier te gebruiken.", + "config.rule_suppression_columns": "Alleen kenmerken met een kolom Onderdrukken in de tabel worden weergegeven. Voeg een kolom toe met Kolom toevoegen (+) om de onderdrukking hier aan te sturen.", "contact.components_count": "{count} componenten", "contact.enabled_label": "ingeschakeld", "coupling.gear_1": "Tandwiel 1", @@ -1322,10 +1368,19 @@ "dialog.custom_axis": "↖ Aangepaste as", "dialog.dimension_insert_hint": "Klik op een andere aandrijvende maat om de naam ervan in te voegen", "dialog.dimension_name": "Maat: {name}", + "dialog.dimension_step_down": "{step} omlaag", + "dialog.dimension_step_expression": "Alleen een getal verspringt; een uitdrukking blijft zoals ingevoerd", + "dialog.dimension_step_up": "{step} omhoog", "dialog.edit_title": "{title} BEWERKEN", + "dialog.no_shown_body": "Geen zichtbaar lichaam om te wijzigen: toon er een of kies Nieuw lichaam", + "dialog.pattern_sketch_not_object": "Kies lichamen of kenmerken: een schets is geen van beide. Herhaal de curven ervan met het eigen Patroon of Spiegelen van de schets, of extrudeer de schets eerst.", "dialog.select": "↖ Selecteren", "dialog.selected_count": "↖ {count} geselecteerd", + "dialog.selection_constraint": "Beperking {id}", + "dialog.selection_external_curve": "{sketch} · curve {id}", "dialog.selection_guidance": "Selecteer een invoer om deze te wijzigen. Klik op geselecteerde objecten om ze te verwijderen; Ctrl/Cmd-klik schakelt ze ook om. Controleer het voorbeeld en druk daarna op OK.", + "dialog.selection_midpoint": "Middelpunt · {id}", + "dialog.selection_profile": "{sketch} · profiel {number}", "dialog.selection_step": "{step} van {total}: {input} selecteren", "dialog.step": "Stap", "document.changed_on_disk": "{name} is op schijf gewijzigd", @@ -1340,6 +1395,7 @@ "document.read_only_save": "Dit ontwerp is alleen-lezen geopend: sla het op als nieuw bestand", "document.save_changes": "Wijzigingen in {name} opslaan?", "document.save_copy": "Kopie opslaan…", + "document.tab_unsaved_changes": "Niet-opgeslagen wijzigingen", "document.unsaved_changes": "{name} heeft niet-opgeslagen wijzigingen. Als u niet opslaat, gaan ze verloren.", "drive.rigid": "{joint} is een starre verbinding: die houdt zijn onderdelen vast en heeft dus niets om aan te sturen. Wijzig het type in Verbinding bewerken om ze te laten bewegen: Draaiend om te draaien, Schuivend om te schuiven, Cilindrisch voor beide.", "drive.stopped_by_contact": "Gestopt bij {value}: {a} zou door {b} heen gaan", @@ -1380,26 +1436,244 @@ "from the rule": "uit de regel", "help.apache": "Apache-licentie 2.0", "help.appearance.assign": "Geeft de geselecteerde lichamen, vlakken of componenten een kleur of materiaaluiterlijk, zonder hun gewicht te wijzigen. Gebruik dit om onderdelen van elkaar te onderscheiden of een afwerking in voorbeeld te bekijken.", + "help.assembly.bom": "Toont de onderdelen van het ontwerp of van een component met hun aantallen, per onderdeelnummer, en kan de lijst opslaan als CSV of JSON. Gebruik dit als onderdelenlijst voor bestellen en monteren.", "help.attributions": "Naamsvermeldingen (ATTRIBUTION.md)", "help.build": "Versie {version} · commit {commit} · gebouwd {date}", + "help.canvas.decal": "Plaatst een afbeelding op een vlak van het model, als een sticker. Gebruik dit om een label, logo of opgedrukt patroon op een onderdeel te tonen.", + "help.canvas.edit": "Wijzigt een canvas: de positie, grootte, hoek, dekking, spiegeling, zichtbaarheid of naam. Gebruik dit om een referentieafbeelding uit te lijnen met de schets die je erover overtrekt.", + "help.canvas.insert": "Plaatst een PNG- of JPEG-afbeelding als doorzichtige referentie op een vlak. Gebruik dit om een foto of tekening in een schets over te trekken, met de afbeelding op een bekende maat geschaald.", + "help.component.break_link": "Maakt een gekoppeld component los van zijn ontwerpbestand en laat de lichamen ongewijzigd. Gebruik dit wanneer het onderdeel niet langer wijzigingen in het oorspronkelijke bestand hoeft te volgen.", + "help.component.capture_position": "Legt de posities vast van onderdelen die je met de hand hebt verplaatst, zodat die posities hun plaats worden. Gebruik dit nadat je onderdelen op hun plaats hebt gesleept die door geen enkele verbinding worden vastgehouden.", + "help.component.create": "Voegt een nieuw, leeg component toe aan het ontwerp, binnen het actieve component tenzij je een andere bovenliggende kiest. Gebruik dit om een nieuw onderdeel van een samenstelling een eigen plek te geven voor lichamen en schetsen.", "help.component.finish_edit": "Slaat het ter plaatse bewerkte onderdeel op, keert terug naar de bijbehorende samenstelling en werkt de samenstelling ermee bij. Gebruik dit zodra de wijzigingen aan het gekoppelde onderdeel klaar zijn.", + "help.component.from_bodies": "Maakt van elk geselecteerd lichaam een eigen component, genoemd naar het lichaam. Gebruik dit wanneer een ontwerp van losse lichamen een samenstelling moet worden waarvan de onderdelen verbonden en verplaatst kunnen worden.", + "help.component.insert_design": "Voegt een ander opgeslagen ontwerp in als component, gekoppeld aan zijn bestand, met de massieve lichamen geplaatst zoals ze daar staan. Gebruik dit om een onderdeel in een samenstelling te hergebruiken en latere wijzigingen over te nemen met Koppelingen bijwerken.", + "help.component.properties": "Toont het volume, de massa, het zwaartepunt en de traagheidsmomenten van een component, op basis van de materialen van de lichamen. Gebruik dit om gewicht en balans van een samenstelling te controleren.", + "help.component.revert_position": "Zet onderdelen die je met de hand hebt verplaatst terug waar ze waren en laat verplaatsingen vervallen die niet zijn vastgelegd. Gebruik dit om proefverplaatsingen in een samenstelling ongedaan te maken.", + "help.component.update_links": "Leest de gekoppelde ontwerpbestanden opnieuw in en vervangt lichamen die zijn gewijzigd. Gebruik dit nadat je een onderdeel hebt bewerkt dat deze samenstelling gebruikt.", + "help.config.configure": "Voegt parameters, kenmerken, materialen of uiterlijken toe als kolommen van de configuratietabel. Gebruik dit om varianten van één ontwerp te maken, zoals maten van een onderdeel.", + "help.config.preview": "Controleert of een rij van de configuratietabel opnieuw opgebouwd kan worden, zonder het ontwerp of de geschiedenis te wijzigen. Gebruik dit voordat je overschakelt naar een variant waarvan je niet zeker bent.", + "help.config.rules": "Toont de regels van de configuratietabel, de rijen en welke rij actief is. Gebruik dit om te zien hoe de varianten van een ontwerp zijn ingesteld.", + "help.config.table": "Toont de configuratietabel: één rij per variant, één kolom per parameter of kenmerk, en of het ontwerp nog overeenkomt met de actieve rij. Gebruik dit om de varianten van een ontwerp door te nemen.", "help.connect_note": "Start elke assistent opnieuw om de SolidCraft-server te laden. Van elk bestand is vóór de wijziging een back-up gemaakt met de extensie .bak.", "help.connect_title": "AI-assistenten verbinden", + "help.construct.axis.edge": "Maakt een constructieas langs een rechte rand of schetslijn. Gebruik dit als as voor een revolve, een cirkelvormig patroon of een verbinding.", + "help.construct.axis.normal_to_face": "Maakt een constructieas door een punt, loodrecht op een vlak. Gebruik dit als as die recht uit een oppervlak steekt.", + "help.construct.axis.through_cylinder": "Maakt een constructieas door het midden van een cilinder-, kegel- of torusvlak, of van een cirkelvormige rand. Gebruik dit om kenmerken rond een rond onderdeel te draaien of te herhalen.", + "help.construct.axis.two_planes": "Maakt een constructieas waar twee vlakken samenkomen. Gebruik dit wanneer de benodigde as de lijn tussen twee vlakken is.", + "help.construct.axis.two_points": "Maakt een constructieas door twee punten, hoekpunten of schetspunten. Gebruik dit voor een as die tussen twee bekende posities loopt.", + "help.construct.plane.along_path": "Maakt een constructievlak loodrecht op een rand of curve, op een positie erlangs. Gebruik dit om een profiel voor een sweep of een doorsnede van een pad te schetsen.", + "help.construct.plane.at_angle": "Maakt een constructievlak dat onder een hoek is gedraaid ten opzichte van een vlak, om een as of rand. Gebruik dit voor schuine schetsen, zoals een hoekbeugel.", + "help.construct.plane.axis_point": "Maakt een constructievlak dat een as en een punt buiten die as bevat. Kies een as van de oorsprong of een constructieas, een rechte rand of schetslijn, en daarna een hoekpunt, schetspunt of constructiepunt. Een punt op de as kan geen eenduidig vlak bepalen.", + "help.construct.plane.midplane": "Maakt een constructievlak halverwege twee vlakken, of dat de hoek tussen twee vlakken halveert waar ze onder een hoek samenkomen. Gebruik dit als symmetrievlak om te spiegelen.", + "help.construct.plane.offset": "Maakt een constructievlak evenwijdig aan een vlak, op een afstand of door een punt. Gebruik dit om op een vaste hoogte boven een vlak te schetsen.", + "help.construct.plane.perpendicular": "Maakt een constructievlak dat een lijn of rand bevat en loodrecht op een vlak staat. Gebruik dit om rechtop op een model te schetsen, langs een rand.", + "help.construct.plane.tangent": "Maakt een constructievlak dat een cilinder, kegel, bol of torus in een punt raakt. Gebruik dit om op de zijkant van een rond onderdeel te schetsen.", + "help.construct.plane.three_points": "Maakt een constructievlak door drie punten. Gebruik dit voor een vlak dat door posities op het model wordt bepaald, zoals drie hoeken.", + "help.construct.plane.two_edges": "Maakt een constructievlak door twee rechte randen of lijnen die in één vlak liggen. Gebruik dit voor een vlak door een onderdeel, bijvoorbeeld door twee tegenover elkaar liggende randen.", + "help.construct.point.along_path": "Maakt een constructiepunt op een positie langs een rand of curve. Gebruik dit als referentie ergens op een pad.", + "help.construct.point.center": "Maakt een constructiepunt in het midden van een cirkelvormige rand, een schetscirkel of boog, een bol of een torus. Gebruik dit als referentie voor gaten, assen en verbindingen.", + "help.construct.point.edge_plane": "Maakt een constructiepunt waar een rand of lijn door een vlak gaat. Gebruik dit om te markeren waar een pad een vlak kruist.", + "help.construct.point.three_planes": "Maakt een constructiepunt waar drie vlakken samenkomen. Gebruik dit als hoekreferentie, ook waar het model geen hoekpunt heeft.", + "help.construct.point.two_edges": "Maakt een constructiepunt waar twee randen of lijnen elkaar ontmoeten of het dichtst bij elkaar komen. Gebruik dit als referentie op een virtuele hoek.", + "help.construct.point.vertex": "Maakt een constructiepunt op een hoekpunt of schetspunt. Gebruik dit als referentie die blijft bestaan wanneer de schets of het lichaam eromheen verborgen is.", + "help.contact.check": "Toont de paren onderdelen in contactsets die in hun huidige positie door elkaar heen gaan. Gebruik dit om botsingen te vinden voordat je verbindingen aanstuurt of een bewegingsstudie uitvoert.", + "help.contact.create": "Groepeert twee of meer onderdelen in een contactset, waarvan de lichamen niet door elkaar heen kunnen gaan terwijl verbindingen bewegen. Gebruik dit voor onderdelen die moeten stoppen wanneer ze elkaar raken, zoals een hendel tegen zijn aanslag.", + "help.contact.disable_all": "Schakelt contact uit, zodat aangestuurde verbindingen en bewegingsstudies niet meer stoppen waar onderdelen elkaar raken. Gebruik dit om onderdelen weer vrij te verplaatsen, of om een grote samenstelling responsief te houden.", + "help.contact.edit": "Wijzigt een contactset: de onderdelen erin, de naam of de onderdrukking; de set kan ook worden verwijderd. Gebruik dit om aan te passen welke onderdelen niet door elkaar heen kunnen gaan.", + "help.contact.enable_all": "Zet elk onderdeel van de samenstelling in één contactset, zodat geen twee onderdelen door elkaar heen kunnen gaan terwijl verbindingen bewegen. Gebruik dit voor een snelle controle van een heel mechanisme.", + "help.contact.enable_sets": "Schakelt contact in voor de contactsets die je hebt gedefinieerd, zodat aangestuurde verbindingen en bewegingsstudies stoppen waar hun onderdelen door elkaar heen zouden gaan. Gebruik dit om je sets terug te halen nadat je contact hebt uitgeschakeld.", + "help.contact.list": "Toont de contactsets van het ontwerp, de onderdelen in elke set en of contact aan staat. Gebruik dit om te controleren hoe contact is ingesteld voordat je de samenstelling aanstuurt.", + "help.document.inspect": "Toont een overzicht van het ontwerp: de componenten, lichamen, schetsen, kenmerken en parameters. Gebruik dit om houvast te krijgen in een ontwerp dat je niet zelf hebt gebouwd.", + "help.document.units": "Wijzigt de eenheden waarin het ontwerp lengtes toont, zoals mm of inch. De geometrie behoudt zijn grootte; alleen de weergave en gewone getallen volgen.", + "help.edit.checkpoint": "Onthoudt het ontwerp, de actieve schets en de geschiedenis voor ongedaan maken zoals ze nu zijn. Gebruik dit voordat je iets riskants probeert waarvan je mogelijk wilt terugkeren.", + "help.edit.restore_checkpoint": "Keert terug naar een controlepunt, inclusief de geschiedenis voor ongedaan maken. Gebruik dit om alles wat sinds het controlepunt is gedaan in één stap te laten vervallen.", + "help.explode.create": "Maakt een explosieweergave die de onderdelen van het midden van de samenstelling af duwt, of volgens de verplaatsingen die je instelt. Gebruik dit om te laten zien hoe een samenstelling in elkaar zit, voor handleidingen of presentaties.", "help.face.delete": "Verwijdert de geselecteerde vlakken en laat de aangrenzende vlakken de opening sluiten, of laat de opening open als oppervlak. Gebruik dit om een afgeronde rand, een gat of een nok die in de weg zit te verwijderen.", + "help.file.insert_mesh": "Voegt een 3MF-, STL-, OBJ-, PLY- of glTF-bestand als meshlichamen toe aan het ontwerp in een nieuw component. Gebruik dit om een gedownload of gescand model als referentie naast je ontwerp te plaatsen.", + "help.file.insert_step": "Voegt een STEP-, IGES-, FreeCAD- of Rhino-bestand als massieve lichamen toe aan het ontwerp in een nieuw component; de onderdelen van een samenstelling worden geneste componenten. Gebruik dit om modellen van leveranciers of andere CAD-programma's te importeren.", + "help.file.save_mesh": "Slaat lichamen op als STL-, 3MF- of OBJ-mesh, met de gladheid van gebogen vlakken die je kiest. Gebruik dit om onderdelen voor te bereiden voor 3D-printen of voor programma's die meshes lezen.", + "help.file.send_to_slicer": "Slaat de geselecteerde lichamen op als 3MF-bestand en opent het in de slicer die je kiest. Gebruik dit om in één stap van model naar printen te gaan.", "help.font_details": "De interface gebruikt de ingebouwde lettertypen van egui (Ubuntu Light en Hack, onder de Ubuntu Font Licence en de MIT/Bitstream Vera-licentie; Noto Emoji en het emoji-pictogramlettertype, onder de OFL en MIT). Schetstekst gebruikt Liberation Sans (SIL OFL 1.1). Het optionele lettertypepakket van The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), wordt niet meegeleverd in SolidCraft-builds.", "help.fonts": "Lettertypen", + "help.frame.member": "Plaatst een profiel, zoals een buis of een aluminium extrusieprofiel, langs de lijnen van een kaderschets, één constructiedeel per lijn. Gebruik dit om kaders, rekken en gelaste constructies te bouwen.", + "help.inspect.accessibility": "Kleurt de vlakken die een gereedschap vanuit één richting kan bereiken, en die het niet kan bereiken. Gebruik dit om een onderdeel te controleren op bewerking of gieten vanaf die kant.", + "help.inspect.center_of_mass": "Toont het zwaartepunt van lichamen, elk afzonderlijk en allemaal samen, bij uniforme dichtheid. Gebruik dit om balans te controleren en te zien waar een onderdeel kantelt.", + "help.inspect.colored_components": "Geeft elk component een eigen tijdelijke kleur, zonder uiterlijken te wijzigen. Gebruik dit om de onderdelen van een samenstelling in één oogopslag te onderscheiden.", + "help.inspect.compare": "Vergelijkt twee lichamen en toont waar het ene materiaal heeft dat het andere niet heeft, met volume en afwijking. Gebruik dit om een gewijzigd of geïmporteerd onderdeel met het origineel te vergelijken.", + "help.inspect.continuity": "Controleert hoe vloeiend vlakken langs hun randen aansluiten: gaten, knikken of krommingssprongen, en kleurt de naden. Gebruik dit om te vinden waar oppervlakken niet netjes op elkaar aansluiten.", + "help.inspect.curvature_comb": "Tekent kammen langs curven, randen of vlakken waarvan de tanden tonen hoe sterk ze buigen. Gebruik dit om vlakke plekken, knikken en ongelijkmatige kromming op te sporen.", + "help.inspect.curvature_map": "Kleurt vlakken naar hoe sterk ze krommen, rood waar de straal klein is. Gebruik dit om krappe plekken te vinden en te beoordelen hoe glad een oppervlak is.", + "help.inspect.draft": "Kleurt vlakken naar hun hellingshoek ten opzichte van een trekrichting en markeert die met te weinig helling. Gebruik dit om een onderdeel te controleren vóór het spuitgieten of gieten.", + "help.inspect.environment_map": "Toont het model met een spiegelende, glanzende afwerking. Gebruik dit om het verloop van oppervlakken te beoordelen aan de hand van de weerspiegelingen die erover lopen.", + "help.inspect.interference": "Vindt lichamen die elkaar overlappen en toont elke overlap met zijn volume. Gebruik dit om een samenstelling te controleren op onderdelen die botsen.", + "help.inspect.isocurve": "Tekent de isoparametrische curven van vlakken, het raster waarop het oppervlak is opgebouwd. Gebruik dit om te zien hoe een oppervlak verloopt en waar het samenklontert.", + "help.inspect.measure": "Meet lengtes, afstanden, hoeken, oppervlakten en stralen tussen wat je kiest, of het volume en de massa van lichamen. Gebruik dit om maten en speling te controleren.", + "help.inspect.minimum_radius": "Zoekt de kleinste krommingsstraal van curven, randen of vlakken en waar die zit. Gebruik dit om te controleren of een gereedschap of spuitmond de vorm kan volgen.", + "help.inspect.section": "Snijdt de weergave open langs een vlak en arceert de snijvlakken, zonder het model te wijzigen. Gebruik dit om in onderdelen en samenstellingen te kijken.", + "help.inspect.zebra": "Toont zwart-witte strepen die op de vlakken van het model weerspiegelen. Gebruik dit om gladheid te beoordelen: strepen die bij een rand breken of knikken wijzen op een slechte overgang.", + "help.joint.as_built": "Verbindt twee onderdelen waar ze al staan, zonder er een te verplaatsen, en stelt in hoe ze nog mogen bewegen. Gebruik dit voor onderdelen die je al op hun definitieve plek hebt geplaatst.", + "help.joint.cam": "Koppelt een draaiende nok aan een volger, zodat de volger schuift of zwenkt terwijl de omtrek van de nok eronder doorgaat. Gebruik dit voor nokken, excenters en klepaandrijvingen.", + "help.joint.create": "Verbindt twee onderdelen op de verbindingsoorsprongen die je kiest en verplaatst het tweede onderdeel op zijn plaats; het verbindingstype bepaalt hoe ze nog mogen bewegen. Gebruik dit om een samenstelling te bouwen waarvan de onderdelen bewegen als het echte mechanisme.", + "help.joint.drive": "Stelt de hoek of afstand van een verbinding in en beweegt de onderdelen mee, binnen de limieten; gekoppelde verbindingen en gesloten lussen volgen. Gebruik dit om te controleren of een mechanisme beweegt zoals bedoeld.", + "help.joint.gear": "Koppelt twee draaiende verbindingen met een overbrengingsverhouding, zodat het aansturen van de ene de andere laat draaien. Gebruik dit voor recht vertande en inwendig vertande tandwielen, met de verhouding uit steekcirkelstralen of tandenaantallen.", + "help.joint.limits": "Stelt in hoever een verbinding mag draaien of schuiven, als minimum en maximum, of wist die limieten. Gebruik dit om een scharnier, schuifverbinding of hendel binnen zijn echte bewegingsbereik te houden.", + "help.joint.motion_link": "Koppelt twee verbindingen met een verhouding en een offset, zodat het aansturen van de ene de andere beweegt. Gebruik dit voor een vaste relatie tussen verbindingen die Tandwiel, Tandheugel en rondsel of Schroef niet dekken.", + "help.joint.origin": "Plaatst een benoemde verbindingsoorsprong op een onderdeel: in het midden van een vlak of rond uiteinde, het midden van een rand, een hoek of een punt. Gebruik dit om voor te bereiden waar verbindingen vastzitten; een oorsprong op een vlak volgt dat vlak wanneer het onderdeel van grootte verandert.", + "help.joint.rack_pinion": "Koppelt een draaiend rondsel aan een schuivende tandheugel, zodat de tandheugel verschuift over de lengte van de steekcirkel die het rondsel afrolt. Gebruik dit voor tandheugelaandrijvingen, besturingen en lineaire tafels.", + "help.joint.reach": "Beweegt een punt op een onderdeel naar een doel door de verbindingen in de keten ervan te wijzigen, binnen hun limieten. Gebruik dit om een mechanisme te positioneren aan de hand van waar het uiteinde moet komen, zoals de punt van een robotarm.", + "help.joint.rigid_group": "Vergrendelt de geselecteerde onderdelen zoals ze zijn, zodat ze als één geheel bewegen. Gebruik dit voor onderdelen die bij elkaar horen en waartussen geen beweging is.", + "help.joint.screw": "Koppelt draaien en schuiven via een spoed, zodat elke omwenteling over die afstand opschuift. Gebruik dit voor aandrijfspindels, bouten en schroefspindels.", + "help.library.apply": "Past een materiaal of uiterlijk uit een lokaal bibliotheekbestand toe op lichamen, vlakken of componenten. Gebruik dit om materialen die je uit een ander ontwerp hebt opgeslagen opnieuw te gebruiken.", + "help.library.export": "Slaat de materialen en uiterlijken van het ontwerp op in een bibliotheekbestand. Gebruik dit om ze te delen of in andere ontwerpen te hergebruiken.", + "help.library.inspect": "Controleert een bibliotheekbestand en toont de materialen en uiterlijken erin, zonder het ontwerp te wijzigen. Gebruik dit om te zien wat een bibliotheek bevat voordat je die toepast.", "help.licences": "Licenties", "help.material.assign": "Stelt in waarvan de geselecteerde lichamen gemaakt zijn, zoals staal, aluminium of ABS. Gebruik dit zodat massa en gewicht overeenkomen met het echte onderdeel.", + "help.material.properties.validate": "Controleert een materiaalgegevenskaart op consistente getallen en ontbrekende waarden. Gebruik dit voordat je op de gegevens vertrouwt voor massa of stijfheid.", + "help.mesh.convert": "Bouwt een meshlichaam, zoals een STL, opnieuw op als bewerkbaar massief lichaam met platte en cilindrische vlakken. Gebruik dit om geïmporteerde mechanische onderdelen te wijzigen als een gemodelleerd lichaam.", "help.mit": "MIT-licentie", + "help.motion.study": "Stelt verbindingswaarden in op stappen langs een tijdlijn en speelt ze af als animatie. Gebruik dit om een mechanisme door een reeks bewegingen te zien gaan en onderweg de speling te controleren.", + "help.motion.trace": "Volgt het pad dat een punt op een onderdeel aflegt terwijl een bewegingsstudie wordt afgespeeld of een verbinding wordt aangestuurd, en bewaart het als 3D-schetscurve wanneer je bevestigt. Gebruik dit om te zien waar een mechanisme reikt, of om op het pad voort te bouwen.", "help.notice": "NOTICE", + "help.occurrence.ground": "Zet een onderdeel vast, of maakt het weer vrij, zodat verbindingen de andere onderdelen eromheen bewegen. Gebruik dit voor het frame of de basis waarop de rest van de samenstelling is gebouwd.", "help.occurrence.move": "Verplaatst een onderdeel van een samenstelling alleen langs de vrijheidsgraden die zijn verbindingen toestaan. Selecteer een vlak van het onderdeel en sleep dan een beschikbare pijl of boog.", "help.parameters.change": "Opent de tabel met benoemde waarden en expressies die de maten van het ontwerp aansturen. Gebruik dit om een maat op één plek te wijzigen, zodat elk kenmerk dat die maat gebruikt vanzelf meegaat.", + "help.parameters.export": "Slaat de parameters van het ontwerp op als CSV of JSON. Gebruik dit om ze in een spreadsheet te bewerken of naar een ander ontwerp over te brengen.", + "help.parameters.graph": "Toont welke parameters en kenmerken welke andere gebruiken, en eventuele lussen of fouten daartussen. Gebruik dit om te zien wat een wijziging van een parameter beïnvloedt.", + "help.parameters.import": "Leest parameters uit CSV of JSON in het ontwerp, alle of geen. Gebruik dit om waarden uit een spreadsheet of een ander ontwerp over te nemen.", + "help.parameters.move": "Verplaatst een gebruikersparameter vóór of na een andere in de lijst. Gebruik dit om samenhangende parameters bij elkaar te houden.", + "help.parts.fastener": "Voegt een standaard schroef, bout, moer, ring, pen of lager toe in de maat die je kiest. Op een gat geplaatst, komt het met een verbinding in het gat te zitten, zodat je bevestigingsmiddelen niet zelf hoeft te modelleren.", + "help.parts.insert": "Voegt een standaardonderdeel in met de familie, maat en lengte die je kiest. Op de rand of wand van een gat geplaatst, komt het met een starre verbinding op het gat te zitten.", + "help.parts.library": "Opent de standaardonderdelen: schroeven, bouten, moeren, ringen, stelschroeven, paspennen en lagers in standaardmaten. Gebruik dit om een standaardonderdeel toe te voegen in plaats van het zelf te modelleren.", + "help.parts.resize": "Wijzigt de maat of lengte van een ingevoegd standaardonderdeel en bouwt het opnieuw op; de verbindingen houden het op zijn plaats. Gebruik dit wanneer een schroef te lang blijkt of een gat een andere maat nodig heeft.", + "help.plastic.assign_rule": "Wijst een kunststofregel toe aan lichamen, zodat hun kunststofkenmerken de aanzet en speling ervan als standaard overnemen. Gebruik dit om een spuitgegoten onderdeel één keer in te stellen voor al zijn kenmerken.", + "help.plastic.boss": "Voegt een schroefnok toe op een vlak: een pilaar met optioneel een gat, aanzet, wortelafronding en ondersteunende ribben. Gebruik dit voor schroefpunten in spuitgegoten of geprinte behuizingen.", + "help.plastic.lip": "Voegt een lip of een bijpassende groef toe langs de rand van een geschaald lichaam. Gebruik dit zodat twee behuizingshelften op elkaar passen en strak sluiten.", + "help.plastic.manage_rules": "Maakt en bewerkt kunststofregels: materiaal, wanddikte, stralen, speling en aanzet. Gebruik ze om de kenmerken van een spuitgegoten onderdeel consistent te houden.", + "help.plastic.rest": "Voegt een rustvlak toe op een vlak: een ronde of rechthoekige verhoging, massief of hol, met aanzet. Gebruik dit als steun of afstandhouder in een spuitgegoten behuizing.", + "help.plastic.snap_fit": "Voegt een snaphaak toe op een vlak, met lengte, dikte en klikrand. Gebruik dit om onderdelen zonder schroeven aan elkaar te klikken.", "help.pointcloud.insert": "Voeg een PLY-, XYZ- of PTS-scan in als puntenwolk naast het model. Gebruik deze als referentie bij het bouwen van een model op basis van gemeten gegevens.", + "help.sheet.convert": "Maakt van een plaat of geschaald lichaam van gelijkmatige dikte een plaatwerklichaam, met buigingen op de randen die je kiest. Gebruik dit om een bestaand onderdeel ontvouwbaar te maken.", + "help.sheet.export_bend_table": "Slaat de buigtabel van een plaatwerklichaam op als CSV of JSON: hoeken, stralen en buigposities in de uitslag. Gebruik dit voor de kantbank of de werkplaats.", + "help.sheet.export_dxf": "Slaat de uitslag op als DXF, met contouren, buiglijnen en optionele buigopmerkingen. Gebruik dit voor laser-, plasma- of waterstraalsnijden.", + "help.sheet.flange": "Voegt een flens toe: een basisplaat uit een schets, een wand langs een open schetscontour, of een gebogen wand op plaatranden. Gebruik dit om plaatwerkonderdelen op te bouwen.", + "help.sheet.flat_pattern": "Maakt de uitslag van een plaatwerklichaam, met zijn afmetingen, uitsnijdingen en buiglijnen. Gebruik dit om de plano te controleren voordat je hem snijdt.", + "help.sheet.fold": "Vouwt een plaat langs een schetslijn onder een hoek en met een straal. Gebruik dit om een vlakke plaat te vouwen nadat je er kenmerken in hebt gesneden.", + "help.sheet.hem": "Vouwt een plaatrand terug op zichzelf. Gebruik dit voor veilige, stijve randen zonder scherpe bramen.", + "help.sheet.manage_rules": "Maakt en bewerkt plaatwerkregels: dikte, buigstraal, K-factor, vrijsnijdingen en spleten. Gebruik ze om af te stemmen op het materiaal en het gereedschap van je werkplaats.", + "help.sheet.path_flange": "Voegt een reeks flenzen toe langs een plaatrand, volgens een open keten van schetslijnen. Gebruik dit voor profielen zoals een U- of Z-vorm in één stap.", + "help.sheet.perforate": "Voegt een veld van gaten toe over de hele vlakke plaat, in een verspringend of vierkant patroon. Gebruik dit voor ventilatieopeningen, roosters en lichtere panelen.", + "help.sheet.refold": "Vouwt een ontvouwen plaatwerklichaam weer op. Gebruik dit nadat je kenmerken aan de vlakke plaat hebt toegevoegd.", + "help.sheet.unfold": "Ontvouwt alle buigingen van een plaatwerklichaam. Gebruik dit om gaten of sneden toe te voegen die over een buiging heen moeten lopen, en vouw daarna opnieuw.", + "help.sketch.arc.center_point": "Tekent een cirkelboog rond een middelpunt, van een beginpunt naar een eindpunt. Gebruik dit wanneer het middelpunt van de boog bekend is, zoals een straal rond een gat of een draaipunt.", + "help.sketch.arc.tangent": "Tekent een boog die begint op het uiteinde van een lijn of boog en er tangentieel op aansluit. Gebruik dit om een keten voort te zetten met een vloeiende bocht in plaats van een hoek.", + "help.sketch.arc.three_point": "Tekent een boog van een beginpunt naar een eindpunt door een derde punt. Gebruik dit wanneer de boog door gegeven punten moet gaan in plaats van rond een bekend middelpunt.", + "help.sketch.arc3d": "Tekent een exacte cirkelboog in de ruimte door drie punten, met 3D-schets aan. Gebruik dit voor bochten in paden en geleiders die het schetsvlak verlaten.", + "help.sketch.auto_constrain": "Voegt de beperkingen toe die de schets al bijna heeft, zoals horizontaal, evenwijdig of samenvallend, en voorziet hem daarna van maten tot hij volledig bepaald is. Gebruik dit om een ruw getekende schets in één stap vast te leggen.", + "help.sketch.auto_constrain_from_datum": "Werkt zoals Autom. beperken, maar meet de posities vanaf een referentiepunt dat je kiest in plaats van vanaf de oorsprong. Gebruik dit wanneer het onderdeel vanuit één referentiepunt is opgezet, zoals een hoek of een gat.", + "help.sketch.blend_curve": "Verbindt de uiteinden van twee curven met een vloeiende spline die tangentieel aansluit op beide, of ook krommingscontinu als je dat kiest. Gebruik dit om een opening tussen curven zonder knik te overbruggen.", + "help.sketch.break": "Splitst een curve in stukken waar andere curven hem kruisen, of op punten die je erop plaatst. Gebruik dit wanneer een deel van een curve een eigen beperking nodig heeft of apart moet worden verwijderd.", + "help.sketch.cancel": "Verlaat de schets en verwerpt alles wat is gewijzigd sinds hij is gemaakt of geopend voor bewerking. Met Ongedaan maken komen de wijzigingen terug.", + "help.sketch.centerline": "Schakelt lijnen om tussen gewone lijnen en hartlijnen, assen die profielen weglaten. Gebruik een hartlijn als as voor een revolve, een spiegeling of een symmetriebeperking.", + "help.sketch.chamfer.distance_angle": "Schuint de hoek tussen twee lijnen af, ingesteld met een afstand langs de eerste lijn en een hoek. Gebruik dit wanneer een tekening de afschuining opgeeft als lengte en hoek, zoals 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Schuint de hoek tussen twee lijnen af met dezelfde afstand terug langs beide. Gebruik dit voor de gebruikelijke afschuining van 45° op een contour.", + "help.sketch.chamfer.two_distance": "Schuint de hoek tussen twee lijnen af, ingesteld met een aparte afstand langs elke lijn. Gebruik dit voor afschuiningen die niet 45° zijn, opgegeven als twee lengtes.", + "help.sketch.circle.center": "Tekent een cirkel vanuit zijn middelpunt en diameter. Gebruik dit voor gaten, nokken en andere ronde kenmerken waarvan het middelpunt bekend is.", + "help.sketch.circle.three_point": "Tekent een cirkel door drie punten. Gebruik dit wanneer de cirkel door gegeven punten moet gaan, bijvoorbeeld van bestaande geometrie.", + "help.sketch.circle.three_tangent": "Tekent een cirkel die drie lijnen, cirkels of bogen raakt. Gebruik dit om een cirkel in de ruimte tussen drie curven te passen, zoals de ingeschreven cirkel van een driehoek.", + "help.sketch.circle.two_point": "Tekent een cirkel vanuit de twee uiteinden van zijn diameter. Gebruik dit wanneer de randpunten van de cirkel bekend zijn in plaats van het middelpunt.", + "help.sketch.circle.two_tangent": "Tekent een cirkel van een opgegeven grootte die twee lijnen, cirkels of bogen raakt. Gebruik dit voor een afronding met vaste straal tussen twee curven.", + "help.sketch.conic": "Tekent een kegelsnede tussen twee eindpunten, gevormd door een toppunt en een rho-waarde. Gebruik dit voor vloeiende overgangen waarvan je de volheid wilt afstellen, van vlak tot bijna een scherpe hoek.", + "help.sketch.constrainer": "Past de beperking toe die een of twee gekozen curven al bijna hebben, zoals horizontaal, evenwijdig, tangentieel of gelijk. Gebruik dit om een met de hand getekende schets relatie voor relatie op te ruimen.", + "help.sketch.constraint.coincident": "Laat een punt samenvallen met een ander punt, een curve of een schetsas. Gebruik dit om openingen in een profiel te sluiten of een punt op een lijn te zetten.", + "help.sketch.constraint.collinear": "Laat twee lijnen op één rechte lijn liggen. Gebruik dit om onderbroken randen uit te lijnen, zoals beide zijden van een inkeping.", + "help.sketch.constraint.concentric": "Geeft twee cirkels of bogen hetzelfde middelpunt. Gebruik dit voor ringen, verzinkingen en assen met schouders.", + "help.sketch.constraint.curvature": "Laat twee curven die in een eindpunt samenkomen met dezelfde kromming (G2) doorlopen. Gebruik dit waar een tangentiële aansluiting niet vloeiend genoeg is, bijvoorbeeld op zichtbare oppervlakken.", + "help.sketch.constraint.equal": "Maakt lijnen even lang, of cirkels en bogen even groot van straal. Gebruik dit zodat één maat meerdere overeenkomende kenmerken aanstuurt.", + "help.sketch.constraint.fix": "Zet punten of curven vast waar ze zijn, of maakt ze weer los. Gebruik dit voor geometrie die niet mag bewegen wanneer je de schets sleept of oplost.", + "help.sketch.constraint.horizontal_vertical": "Maakt een lijn, of de lijn tussen twee punten, horizontaal of verticaal, afhankelijk van wat het dichtst bij ligt. Gebruik dit om een contour recht op de schetsassen te zetten.", + "help.sketch.constraint.midpoint": "Zet een punt op het midden van een lijn, of laat de middelpunten van twee lijnen samenvallen. Gebruik dit om geometrie op een rand te centreren.", + "help.sketch.constraint.parallel": "Maakt twee lijnen evenwijdig. Gebruik dit voor zijden die evenwijdig moeten blijven wanneer andere maten veranderen.", + "help.sketch.constraint.perpendicular": "Laat twee lijnen een rechte hoek maken. Gebruik dit voor rechte hoeken tussen lijnen die niet op de schetsassen liggen.", + "help.sketch.constraint.polygon": "Maakt van een gesloten keten van lijnen een regelmatige veelhoek: gelijke zijden, met elke hoek op één cirkel. Gebruik dit om een met de hand getekende veelhoek regelmatig te maken en te houden.", + "help.sketch.constraint.symmetry": "Laat twee punten of curven elkaars spiegelbeeld zijn ten opzichte van een lijn of rond een punt. Gebruik dit om een profiel symmetrisch te houden wanneer je één zijde wijzigt.", + "help.sketch.constraint.tangent": "Laat twee curven elkaar tangentieel raken, zoals een lijn en een boog. Gebruik dit voor vloeiende aansluitingen zonder knik.", + "help.sketch.construction": "Schakelt curven om tussen normale geometrie en constructiegeometrie, die profielen weglaten. Gebruik constructiecurven als hulp voor indeling, referenties en maten.", + "help.sketch.construction_line": "Maak een oneindige constructielijn door twee punten. Gebruik deze om een schets op te zetten zonder profielen te splitsen.", + "help.sketch.construction_line.angle": "Maak een oneindige constructielijn onder een hoek ten opzichte van de X-as van de schets. Kies het punt en typ de hoek, of kies de richting ervan.", + "help.sketch.construction_line.bisector": "Kies twee elkaar snijdende rechte schetslijnen en kies dan een van beide bissectrices. Het resultaat volgt zijn bronlijnen.", + "help.sketch.construction_line.horizontal": "Maak een oneindige horizontale constructielijn door een punt. De horizontale beperking blijft gelden bij latere bewerkingen.", + "help.sketch.construction_line.parallel": "Kies een rechte schetslijn en plaats dan een parallelle, oneindige constructielijn. Klik met rechts om een andere referentie te kiezen.", + "help.sketch.construction_line.perpendicular": "Kies een rechte schetslijn en plaats dan een loodrechte, oneindige constructielijn. Klik met rechts om een andere referentie te kiezen.", + "help.sketch.construction_line.tangent_at": "Maak een raaklijn in een punt van een cirkel of cirkelboog, of in een eindpunt van een open spline of kegelsnede. Kies de kromme en dan het raakpunt.", + "help.sketch.construction_line.tangent_external": "Kies een cirkel of cirkelboog en dan een extern punt en een oplossing voor de raaklijn. De voorbeelden tonen alleen raakpunten op de getekende boog.", + "help.sketch.construction_line.tangent_two": "Kies twee cirkels of cirkelbogen en kies dan een gemeenschappelijke raaklijn in het voorbeeld. De raakpunten moeten op de getekende krommen liggen.", + "help.sketch.construction_line.vertical": "Maak een oneindige verticale constructielijn door een punt. De verticale beperking blijft gelden bij latere bewerkingen.", + "help.sketch.copy": "Kopieert de geselecteerde schetscurven en -punten, samen met de beperkingen en maten daartussen. Plak ze in deze schets of in een andere.", + "help.sketch.create": "Start een nieuwe 2D-schets op een vlak of op een plat vlak van het model. Elke extrusie, revolve en sweep begint met een schets.", + "help.sketch.cut": "Kopieert de geselecteerde schetsgeometrie en verwijdert die uit de schets, in één stap om ongedaan te maken. Plak haar elders in deze schets of in een andere.", + "help.sketch.dimension": "Voegt een aandrijvende maat toe: een lengte, afstand, hoek, straal of diameter, afhankelijk van wat je kiest. Typ een waarde of een parameternaam en de schets volgt die.", + "help.sketch.edit": "Opent een bestaande schets voor bewerking. De kenmerken die erop zijn gebouwd worden bijgewerkt wanneer je de schets voltooit.", + "help.sketch.ellipse": "Tekent een ellips vanuit zijn middelpunt, het uiteinde van zijn lange as en een punt aan de korte zijde. Gebruik dit voor ovale openingen, nokken en andere langgerekte ronde vormen.", "help.sketch.equation_curve": "Tekent een curve uit formules: x(t) en y(t), of y = f(x), over een bereik. De formules kunnen parameters gebruiken en de curve volgt ze: gebruik dit voor een sinusgolf, een spiraal of de evolvente van een tandwieltand.", + "help.sketch.extend": "Verlengt een lijn of boog tot de dichtstbijzijnde curve in de weg, of laat twee curven aangroeien tot ze elkaar ontmoeten. Gebruik dit om openingen in een profiel te sluiten na het trimmen of bewerken.", + "help.sketch.fillet": "Rondt de hoek waar twee lijnen of bogen samenkomen af met een boog met een opgegeven straal. Meerdere hoeken die samen worden afgerond delen één straal.", + "help.sketch.finish": "Verlaat de schets en keert terug naar het model. De gesloten profielen zijn dan klaar voor Extruderen, Revolve en andere kenmerken.", + "help.sketch.finish_auto_constrain": "Voert Autom. beperken uit op de schets en voltooit hem daarna. Gebruik dit om een schets in één stap volledig bepaald achter te laten.", + "help.sketch.fit_curves_to_section": "Snijdt een mesh- of massief lichaam met het schetsvlak en past lijnen en bogen aan op de doorsnede. Gebruik dit om een gescand of geïmporteerd onderdeel opnieuw op te bouwen als bewerkbare schets.", + "help.sketch.include_3d": "Brengt modelranden, hoekpunten en curven van andere schetsen als gekoppelde referenties in deze schets, waarbij wat buiten het schetsvlak ligt op dat vlak wordt afgeplat. Gebruik dit om voort te bouwen op geometrie die niet in het schetsvlak ligt.", + "help.sketch.infinite": "Schakelt lijnen om tussen normale lijnen en oneindige constructielijnen die door de hele weergave lopen. Gebruik ze als indelingsreferenties die nooit te kort zijn.", + "help.sketch.insert_dxf": "Leest de curven van een DXF-tekening in een schets, geschaald, gedraaid en geplaatst waar je instelt. Gebruik dit om voort te bouwen op een 2D-tekening uit een ander programma, zoals een lasersnijcontour.", + "help.sketch.insert_svg": "Leest de paden van een SVG-tekening in een schets, geschaald, gedraaid en geplaatst waar je instelt. Gebruik dit om een logo of vectorcontour om te zetten in curven die je kunt extruderen.", + "help.sketch.inspect": "Opent een rapport over de geopende schets: hoeveel vrijheidsgraden er nog over zijn en of hij volledig beperkt is. Gebruik dit om te zien wat nog beweegt voordat je de schets voltooit.", + "help.sketch.intersect": "Voegt de curven of punten toe waar lichamen, vlakken, randen of andere schetsen het schetsvlak kruisen. Ze blijven gekoppeld en volgen het model wanneer dat verandert.", + "help.sketch.intersection_curve": "Maakt 3D-curven waar twee lichamen of vlakken samenkomen, eraan gekoppeld. Gebruik ze als paden of geleiders die het model volgen.", + "help.sketch.isoparametric_curve": "Maakt een 3D-curve langs de U- of V-richting van een vlak door een punt dat je kiest, gekoppeld aan het vlak. Gebruik dit als pad of splitslijn die het oppervlak volgt.", + "help.sketch.line": "Tekent verbonden lijnen punt voor punt, als open keten of gesloten contour. Het is het basisgereedschap voor de meeste profielen.", + "help.sketch.line.midpoint": "Tekent een lijn vanuit zijn middelpunt naar één uiteinde, waarbij het andere uiteinde wordt gespiegeld. Gebruik dit voor lijnen die op een punt zijn gecentreerd, zoals een symmetrische rand.", + "help.sketch.line3d": "Tekent verbonden rechte lijnen tussen punten in de ruimte, met 3D-schets aan. Gebruik dit voor paden en kaders die het schetsvlak verlaten.", + "help.sketch.mirror": "Spiegelt schetscurven en -punten over een lijn of as en voegt symmetriebeperkingen toe. Gebruik dit om de helft van een symmetrisch profiel te tekenen en het aan te vullen.", + "help.sketch.move": "Verplaatst of draait schetscurven en -punten, of een kopie ervan. Gebruik dit om geometrie op een andere plek te zetten met behoud van vorm en beperkingen.", + "help.sketch.offset": "Maakt een kopie van een keten van curven op een opgegeven afstand, aan één kant of aan beide. Gebruik dit voor wanden, contouren en spelingen; de afstand blijft een bewerkbare maat.", + "help.sketch.paste": "Plakt schetsgeometrie die je hebt gekopieerd of geknipt in de actieve schets. Plaats haar op een punt of verschuif haar met een offset.", + "help.sketch.pattern.circular": "Kopieert schetsgeometrie rond een middelpunt, over een volledige cirkel of een opgegeven hoek. Gebruik dit voor steekcirkels van bouten, spaken en tanden.", + "help.sketch.pattern.rectangular": "Kopieert schetsgeometrie in rijen en kolommen met opgegeven tussenafstanden. Gebruik dit voor roosters van gaten, sleuven of ventilatieopeningen.", + "help.sketch.point": "Plaatst een schetspunt. Gebruik dit als referentie voor maten, beperkingen, gatmiddelpunten of latere kenmerken.", + "help.sketch.point3d": "Plaatst een punt in de ruimte, met 3D-schets aan. Gebruik dit als referentie voor 3D-curven en paden.", + "help.sketch.polygon.circumscribed": "Tekent een regelmatige veelhoek rond een cirkel, bepaald door de afstand van het midden tot het midden van een zijde. Gebruik dit wanneer de sleutelwijdte bekend is, zoals bij een zeskantmoer.", + "help.sketch.polygon.edge": "Tekent een regelmatige veelhoek vanuit de twee uiteinden van één zijde. Gebruik dit wanneer de lengte en positie van een zijde bekend zijn.", + "help.sketch.polygon.inscribed": "Tekent een regelmatige veelhoek binnen een cirkel, bepaald door de afstand van het midden tot een hoek. Gebruik dit wanneer de maat over de hoeken bekend is.", + "help.sketch.project": "Brengt modelranden, vlakken, hoekpunten en curven van andere schetsen in deze schets, geprojecteerd op het vlak ervan. Ze blijven gekoppeld en volgen het model wanneer dat verandert.", + "help.sketch.project_to_surface": "Projecteert curven van andere schetsen langs de normaal van deze schets op een vlak, als gekoppelde 3D-curven. Gebruik dit om een logo, splitslijn of pad op een gebogen oppervlak te zetten.", + "help.sketch.rectangle.center": "Tekent een rechthoek vanuit zijn middelpunt en één hoek. Gebruik dit voor contouren die op een punt zijn gecentreerd, zoals de oorsprong.", + "help.sketch.rectangle.rounded": "Tekent een rechthoek waarvan alle vier de hoeken met één straal zijn afgerond. Gebruik dit voor platen, deksels en openingen met afgeronde hoeken.", + "help.sketch.rectangle.three_point": "Tekent een rechthoek vanuit één rand en een punt aan de overliggende zijde. Gebruik dit voor rechthoeken onder een hoek met de schetsassen.", + "help.sketch.rectangle.two_point": "Tekent een rechthoek vanuit twee overliggende hoeken. Gebruik dit voor de contouren van platen, blokken en uitsparingen.", + "help.sketch.scale": "Schaalt schetscurven en -punten met een factor rond een basispunt. Gebruik dit om een deel van een schets van grootte te veranderen zonder het opnieuw te tekenen.", + "help.sketch.slot.arc_center": "Tekent een gebogen sleuf met een opgegeven breedte langs een boog die is bepaald door middelpunt, begin en einde. Gebruik dit voor stelsleuven rond een draaipunt.", + "help.sketch.slot.arc_three_point": "Tekent een gebogen sleuf met een opgegeven breedte langs een boog door drie punten. Gebruik dit wanneer het pad van de sleuf door gegeven punten moet gaan.", + "help.sketch.slot.center_point": "Tekent een rechte sleuf met een opgegeven breedte vanuit zijn midden tot het middelpunt van één eindboog. Gebruik dit voor sleuven die op een punt zijn gecentreerd.", + "help.sketch.slot.center_to_center": "Tekent een rechte sleuf met een opgegeven breedte tussen de middelpunten van zijn twee eindbogen. Gebruik dit voor sleuven met maatvoering hart-op-hart, zoals stelsleuven voor schroeven.", + "help.sketch.slot.overall": "Tekent een rechte sleuf met een opgegeven breedte van het ene buitenste uiteinde tot het andere. Gebruik dit wanneer de totale lengte van de sleuf telt.", + "help.sketch.spline.control_point": "Tekent een kubische spline die wordt gevormd door controlepunten waar hij niet doorheen gaat. Gebruik dit voor vloeiende, soepele curven die je vormgeeft door de punten te verplaatsen.", + "help.sketch.spline.control_point_5": "Tekent een spline van graad 5, gevormd door controlepunten. Gebruik dit waar curven met vloeiendere kromming moeten aansluiten, bijvoorbeeld op zichtbare vormgevingsoppervlakken.", + "help.sketch.spline.fit_point": "Tekent een vloeiende spline die door elk punt gaat dat je plaatst, open of gesloten. Gebruik dit om een vorm door bekende punten na te trekken.", + "help.sketch.spline3d": "Tekent een vloeiende curve in de ruimte door punten, met 3D-schets aan. Gebruik dit voor sweeppaden en kabeltrajecten die het schetsvlak verlaten.", + "help.sketch.spun_profile": "Maakt in het schetsvlak de contour die een lichaam doorloopt wanneer het om een as draait. Gebruik dit om het silhouet van een gedraaid onderdeel te krijgen voor een revolve of een tekening.", + "help.sketch.text": "Schrijft tekst in de schets in een gekozen lettertype, hoogte en hoek; de woorden kunnen parameters volgen. Gebruik Extruderen of Embossen voor labels en belettering.", + "help.sketch.transform": "Schaalt, draait en verplaatst schetsgeometrie rond een middelpunt in één stap. Gebruik dit om een selectie in één keer te verplaatsen en van grootte te veranderen.", + "help.sketch.trim": "Verwijdert het stuk van een curve tussen de dichtstbijzijnde snijpunten rond waar je klikt. Gebruik dit om overlappende lijnen op te ruimen tot een gesloten profiel.", "help.solid.align": "Verplaatst de geselecteerde lichamen zodat een punt, vlak of werkvlak erop samenvalt met een punt, vlak of werkvlak elders. Gebruik dit om een onderdeel tegen een ander te plaatsen zonder de afstand te meten.", + "help.solid.boundary_fill": "Maakt massieve lichamen uit de gebieden die worden ingesloten door elkaar overlappende gereedschapslichamen, en vult alleen de gebieden die je kiest. Gebruik dit om een vorm op te bouwen uit de ruimte die meerdere lichamen samen begrenzen.", + "help.solid.bounding_solid": "Maakt een kubus die de geselecteerde lichamen omsluit, met een optionele marge. Gebruik dit om de totale afmetingen van een onderdeel te zien, of als het ruwe materiaal waaruit het wordt bewerkt.", + "help.solid.box": "Maakt een kubus uit een lengte, breedte en hoogte, vanaf een hoekpunt of gecentreerd op een punt. Gebruik dit voor een snel blok, een plaatshouder of een lichaam om kenmerken in te snijden.", "help.solid.chamfer": "Snijdt de geselecteerde randen af met een vlakke afschuining van de ingestelde afstand. Gebruik dit om scherpe randen te breken of het inbrengen van een pen of schroef te vergemakkelijken.", + "help.solid.coil": "Maakt een schroeflijnvormig lichaam, zoals een veer, uit een diameter, windingen, hoogte of spoed en een ronde of vierkante doorsnede. Gebruik dit voor veren, spoelen en schroeflijnvormige ribbels.", "help.solid.combine": "Voegt lichamen samen, snijdt ze uit een doellichaam of behoudt alleen het gedeelde volume, en kan de gereedschapslichamen behouden. Gebruik dit om onderdelen samen te voegen, een vorm met een andere uit te snijden of te vinden waar twee lichamen overlappen.", + "help.solid.cone": "Maakt een kegel uit een grondcirkel en een hoogte, of een afgeknotte kegel wanneer de top ook een straal heeft. Gebruik dit voor taps toelopende delen, trechters, verzinkingen en punten.", + "help.solid.cylinder": "Maakt een cilinder uit een straal of diameter en een hoogte, staand op een punt langs een as. Gebruik dit voor assen, pennen, nokken en ronde stukken ruw materiaal.", "help.solid.draft": "Kantelt de geselecteerde vlakken met de ingestelde hoek, gemeten vanaf een neutraal vlak. Gebruik dit bij gegoten of gevormde onderdelen zodat ze uit de mal loskomen.", + "help.solid.emboss": "Verheft schetsprofielen, zoals tekst of een logo, uit een vlak, of verzinkt ze erin. Gebruik dit voor belettering, labels en markeringen op platte of ronde vlakken.", "help.solid.extrude": "Duwt een schetsprofiel over een afstand de 3D in en voegt materiaal toe of verwijdert het. Gebruik dit om een vlakke contour om te zetten in een blok, een nok of een uitsparing.", "help.solid.fillet": "Rondt de geselecteerde randen af met een vloeiende cirkelvormige overgang met de ingestelde straal. Gebruik dit om scherpe randen te verzachten voor sterkte, comfort of uiterlijk.", "help.solid.hole": "Boort een rond gat met de ingestelde diameter op een gekozen punt van een vlak. Gebruik dit voor doorvoergaten voor schroeven, pennen en andere eenvoudige ronde openingen.", @@ -1408,20 +1682,60 @@ "help.solid.move": "Verplaatst of draait de geselecteerde lichamen, of een kopie ervan, over de ingestelde afstand en hoek. Gebruik dit om een lichaam een nieuwe positie te geven of om een tweede lichaam op een andere plek te maken.", "help.solid.offset_face": "Duwt de geselecteerde vlakken naar binnen of buiten over de ingestelde afstand, waarbij de omliggende vlakken meegaan. Gebruik dit om een wand dikker, een uitsparing dieper of een nok hoger te maken zonder de schets te bewerken.", "help.solid.pattern.circular": "Herhaalt de geselecteerde objecten rond een as, met het ingestelde aantal en de ingestelde totaalhoek. Gebruik dit voor boutcirkels, spaken, koelribben en tanden.", + "help.solid.pattern.path": "Kopieert kenmerken of lichamen langs een schetspad, op aantal en tussenafstand. Gebruik dit voor gaten langs een gebogen rand of onderdelen langs een rail.", "help.solid.pattern.rectangular": "Herhaalt de geselecteerde objecten in één of twee richtingen met het ingestelde aantal en de ingestelde afstand. Gebruik dit voor rijen en rasters van gaten, ribben, pennen of voeten.", + "help.solid.pipe": "Maakt een ronde buis langs een pad van schetscurven, massief of hol met een wanddikte. Gebruik dit voor buizen, draden, kabels en rails.", "help.solid.press_pull": "Voegt materiaal toe of verwijdert het terwijl een vlak wordt gesleept, of rondt randen af terwijl ze worden gesleept. Gebruik dit voor snelle wijzigingen rechtstreeks op het model.", "help.solid.remove": "Haalt de geselecteerde lichamen vanaf dit punt in de tijdlijn uit het ontwerp; eerdere stappen behouden ze. Gebruik dit om een hulplichaam te verwijderen, zoals een snijgereedschap dat niet meer nodig is.", "help.solid.replace_face": "Verplaatst de geselecteerde platte vlakken naar een werkvlak of een evenwijdig vlak, waarbij het lichaam groeit of krimpt om aan te sluiten. Gebruik dit om een vlak gelijk te trekken met een ander onderdeel of een constructievlak.", "help.solid.revolve": "Draait een schetsprofiel rond een as tot een rond solid. Gebruik dit voor assen, knoppen, kommen en elk onderdeel dat draaisymmetrisch is rond een hartlijn.", + "help.solid.rib": "Voegt een dunne wand toe langs een open schetscurve, uitgevuld tot de eerstvolgende vlakken van het lichaam. Gebruik dit om wanden en hoeken te verstijven, bijvoorbeeld in spuitgegoten of geprinte onderdelen.", "help.solid.scale": "Maakt de geselecteerde lichamen groter of kleiner met een factor, in elke richting gelijk of per as een eigen factor. Gebruik dit om een geïmporteerde vorm te schalen of krimp te compenseren.", "help.solid.shell": "Holt een solid uit, waarbij wanden van de ingestelde dikte overblijven, en kan de gekozen vlakken openen. Gebruik dit voor dozen, deksels en andere dunwandige onderdelen.", + "help.solid.sphere": "Maakt een bol uit een straal of diameter rond een middelpunt. Gebruik dit voor ballen, knoppen en afgeronde uiteinden.", "help.solid.split_body": "Snijdt een lichaam met een vlak, het vlak van een ander lichaam of een schetslijn in afzonderlijke lichamen. Gebruik dit voor onderdelen die afzonderlijk worden geprint, bewerkt of gekleurd.", "help.solid.split_face": "Verdeelt de geselecteerde vlakken langs een vlak, het vlak van een ander lichaam of schetscurven, zonder het lichaam te snijden. Gebruik dit om een deel van een vlak een eigen helling, kleur of offset te geven.", "help.solid.sweep": "Sleept een schetsprofiel langs een pad tot een solid. Gebruik dit voor buizen, rails, handgrepen en elk onderdeel met een constante doorsnede dat een curve volgt.", + "help.solid.thread": "Voegt een ISO-metrische schroefdraad toe aan een cilindrisch vlak, als cosmetische schroefdraad of in het lichaam gesneden. Gebruik dit voor bouten, tapgaten en geprinte schroefonderdelen.", + "help.solid.torus": "Maakt een ring uit een grote straal rond zijn as en een kleine straal voor zijn ronde doorsnede. Gebruik dit voor O-ringen, handvatten en ronde kralen.", + "help.solid.web": "Voegt een dunne wand toe langs elke open schetscurve, elk uitgevuld tot de eerstvolgende vlakken van het lichaam. Gebruik dit voor een raster van ondersteunende wanden in behuizingen en bakken.", + "help.surface.blend": "Maakt een oppervlak dat de randen van twee lichamen overbrugt, tangentieel of krommingscontinu aan beide. Gebruik dit om twee oppervlakken vloeiend over een opening heen te verbinden.", + "help.surface.boundary": "Maakt een oppervlak dat een lus van twee tot vier schetscurven of een netwerk van curven vult. Gebruik dit voor vrije vormpanelen die door hun randen zijn bepaald.", + "help.surface.extend": "Verlengt een oppervlak voorbij zijn randen, met een afstand of tot een vlak. Gebruik dit zodat oppervlakken overlappen voordat je ze trimt of naait.", + "help.surface.extrude": "Duwt schetscurven of profielen over een afstand uit tot een oppervlak, alleen wanden, zonder afsluitvlakken. Gebruik dit voor dunne wanden en voor snij- of splitsgereedschap.", + "help.surface.fair": "Egaliseert de binnenkant van vrije vormvlakken terwijl hun randen op hun plaats blijven. Gebruik dit om bobbels en golvende reflecties in een oppervlak glad te strijken.", + "help.surface.loft": "Maakt een oppervlak dat in volgorde door twee of meer doorsneden gaat, zonder afsluitvlakken. Gebruik dit voor schalen en overgangen tussen verschillende vormen.", + "help.surface.match": "Bouwt de rand van een oppervlak opnieuw op zodat hij aansluit op de rand van een ander lichaam, met overeenkomende tangent of kromming. Gebruik dit om een naad tussen twee oppervlakken vloeiend te sluiten.", + "help.surface.offset": "Maakt een kopie van vlakken op een afstand langs hun normalen, als nieuw oppervlaklichaam. Gebruik dit voor huiden, spelingen of de andere kant van een wand.", + "help.surface.patch": "Vult een schetsgebied of een gesloten lus van randen met een vlak, plat of vloeiend gebogen. Gebruik dit om gaten in een oppervlaklichaam te dichten.", + "help.surface.reverse_normal": "Keert vlakken van een oppervlaklichaam om, zodat hun buitenkant de andere kant op wijst. Gebruik dit vóór het verdikken of naaien wanneer de vlakken naar binnen wijzen.", + "help.surface.revolve": "Draait schetscurven of profielen om een as tot een oppervlak, zonder afsluitvlakken. Gebruik dit voor ronde schalen zoals lampenkappen, kommen en mondstukken.", + "help.surface.ruled": "Maakt een strook van rechte lijnen vanuit een keten van randen, langs de normaal of tangent van het vlak of onder een hoek. Gebruik dit voor aanzetwanden, uitlopen en scheidingsvlakken.", + "help.surface.stitch": "Naait oppervlaklichamen aan elkaar langs hun gedeelde randen, tot een massief lichaam wanneer ze sluiten. Gebruik dit om een reeks oppervlakken tot één lichaam te maken.", + "help.surface.sweep": "Beweegt schetscurven of profielen langs een pad tot een oppervlak, zonder afsluitvlakken. Gebruik dit voor goten, lijsten en andere dunne vormen die een pad volgen.", + "help.surface.thicken": "Geeft een oppervlaklichaam een dikte, waardoor het een massief lichaam wordt. Gebruik dit om printbare of bewerkbare onderdelen uit oppervlakken te maken.", + "help.surface.trim": "Snijdt een oppervlak met een vlak, een ander oppervlak of schetscurven en behoudt de zijde die je kiest. Gebruik dit om oppervlakken op vorm te snijden voordat je ze naait.", + "help.surface.unstitch": "Scheidt vlakken van een lichaam in eigen oppervlaklichamen; een massief lichaam valt uiteen in oppervlakken. Gebruik dit om afzonderlijke vlakken van een lichaam te herwerken.", + "help.surface.untrim": "Verwijdert gaten uit een vlak, of herstelt de buitengrens ervan tot de natuurlijke grenzen van het oppervlak. Gebruik dit om na een trim het volledige oppervlak terug te krijgen.", "help.third_party": "Licenties van derden", "help.timeline.compute_all": "Bouwt elk kenmerk in de tijdlijn opnieuw op vanaf het begin. Gebruik dit om het model te vernieuwen en te zien welke kenmerken mislukken.", "help.timeline.delete": "Verwijdert de geselecteerde kenmerken uit de tijdlijn; als een schets wordt verwijderd, gaan ook de kenmerken eruit die erop zijn gebouwd. Gebruik dit om een stap te verwijderen die niet meer gewenst is.", + "help.timeline.dependents": "Toont de kenmerken die met een kenmerk zouden worden verwijderd, en die zonder dat kenmerk zouden mislukken. Gebruik dit voordat je een kenmerk verwijdert of wijzigt.", "help.timeline.play": "Speel de resterende kenmerken één voor één opnieuw af, met een pauze van een halve seconde na elke herberekening. Voer deze opdracht opnieuw uit of druk op Escape om te stoppen; Naar het einde springt direct.", + "help.view.apply": "Draait de weergave naar een standaardrichting zoals voor, boven of iso, of naar een opgeslagen benoemde weergave. Gebruik dit om het model vanuit een vaste hoek te bekijken.", + "help.view.delete": "Verwijdert een opgeslagen benoemde weergave. Het model wordt niet gewijzigd.", + "help.view.fit": "Zoomt en pant zodat het hele model, of de selectie, de weergave vult. Gebruik dit wanneer het model uit beeld is geraakt.", + "help.view.grid": "Toont of verbergt het raster in de viewport. Gebruik dit als hulp voor maat en oriëntatie tijdens het modelleren.", + "help.view.ground_shadow": "Toont of verbergt de schaduw van het model op de grond. Gebruik dit om hoogte en positie gemakkelijker te beoordelen.", + "help.view.home": "Draait de weergave terug naar de beginweergave en past het model in beeld. Gebruik dit om snel terug te keren naar een bekende weergave.", + "help.view.list": "Toont de benoemde weergaven die in het ontwerp zijn opgeslagen. Gebruik dit om een eerder opgeslagen weergave te vinden.", + "help.view.navigate": "Draait, pant of zoomt de weergave in stappen, zoals een kwartslag naar links. Gebruik dit om de camera nauwkeurig te bewegen in plaats van te slepen.", + "help.view.navigation_bar": "Toont of verbergt de navigatiebalk onderaan de viewport. Verberg hem voor meer ruimte, toon hem om de weergavegereedschappen met de muis te bereiken.", + "help.view.rename": "Geeft een opgeslagen benoemde weergave een nieuwe naam. De weergave zelf blijft hetzelfde.", + "help.view.save": "Slaat de huidige camerapositie op als benoemde weergave in het ontwerp. Gebruik dit om later naar dezelfde hoek terug te keren, bijvoorbeeld voor schermafbeeldingen.", + "help.view.spin": "Laat de weergave continu om het model draaien tot de volgende klik of toets. Gebruik dit om een model van alle kanten te presenteren.", + "help.view.tool": "Vergrendelt een cameragereedschap, roteren, pannen of zoomen, zodat slepen met de linkermuisknop de weergave beweegt tot je het uitschakelt. Gebruik dit op een trackpad of zonder middelste muisknop.", + "help.view.visual_style": "Wijzigt hoe het model wordt getekend: gearceerd met of zonder randen, draadmodel, of met verborgen randen. Gebruik draadmodel om naar binnen te kijken en gearceerd voor een nette weergave.", "history.sketch_under_constrained": "Onderbeperkt ({count} vrijheidsgraden)", "history.sketch_under_constrained_one": "Onderbeperkt ({count} vrijheidsgraad)", "hole_presets.confirm_delete": "Verwijderen bevestigen", @@ -1527,6 +1841,8 @@ "joint_move.blocked_hint": "Controleer het verbindingstype (zoals Star), het vastzetten, de verbindingslimieten en door parameters aangestuurde waarden.", "joint_move.blocked_title": "Dit onderdeel kan niet worden verplaatst", "joint_move.coarse": "Rotatiestap dicht bij de as (°)", + "joint_move.conflict": "Een verbinding van dit onderdeel conflicteert met de andere: {joint}.", + "joint_move.conflict_hint": "Bewerk, onderdruk of verwijder de conflicterende verbinding zodat de andere verbindingen het onderdeel kunnen plaatsen.", "joint_move.distance": "Afstand vanaf het begin", "joint_move.done": "Gereed", "joint_move.fine": "Rotatiestap ver van de as (°)", @@ -1598,6 +1914,10 @@ "material.selection.mixed": "Verschillende materialen", "measure.at": "Bij", "measure.item": "Item {number}", + "measure.quick_copied": "Meting gekopieerd", + "measure.quick_copy": "Klik om de meting te kopiëren", + "measure.quick_edges": "{count} randen", + "measure.quick_faces": "{count} vlakken", "messages.ago_h": "{n} u geleden", "messages.ago_min": "{n} min geleden", "messages.ago_s": "{n} s geleden", @@ -1622,6 +1942,8 @@ "motion.track_name": "Spoor {number}", "nav.alias.help": "Shift+Alt+linkerknop slepen draait, Shift+Alt+middenknop slepen pant, Shift+Alt+rechterknop slepen zoomt; middenknop slepen pant ook en rechterknop slepen draait", "nav.blender.help": "Middenknop slepen draait, Shift+middenknop pant, Ctrl+middenknop zoomt; rechterknop slepen heeft geen invloed op de camera", + "nav.creo.help": "Middenknop slepen draait, Shift+middenknop pant, Ctrl+middenknop verticaal slepen zoomt (omlaag om in te zoomen); scrollen met het wiel zoomt", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Muis en 3D-muis draaien door beide polen heen en behouden de rolhoek. Het snappen op assen met Shift is uitgeschakeld.", "nav.free_orbit.label": "Vrij draaien", "nav.free_orbit.snap_help": "Muis en 3D-muis draaien door beide polen heen en behouden de rolhoek. Houd Shift ingedrukt tijdens het slepen om de kijkrichting en de rolhoek te snappen.", @@ -1631,6 +1953,7 @@ "nav.hfss.help": "Alt+linkerknop slepen pant, Shift+Alt+linkerknop zoomt, Ctrl+linkerknop slepen op lege ruimte draait", "nav.inventor.help": "Middenknop slepen pant, Shift+middenknop draait, Ctrl+middenknop zoomt, rechterknop slepen draait", "nav.maya.help": "Alt+linkerknop slepen draait, Alt+middenknop pant, Alt+rechterknop zoomt; middenknop slepen pant ook", + "nav.nx.help": "Middenknop slepen draait, Shift+middenknop pant (middelste + rechterknop in NX), Ctrl+middenknop zoomt (middelste + linkerknop in NX); rechterknop slepen heeft geen invloed op de camera", "nav.openscad.help": "Linkerknop slepen op lege ruimte draait, Shift+linkerknop slepen selecteert met een kader, schetsgeometrie slepen bewerkt die; rechter- of middenknop slepen pant, Shift+rechter- of Shift+middenknop slepen zoomt", "nav.perspective.sketch": "Schetsbewerking gebruikt een orthografische weergave. Rond de schets af om naar perspectief te schakelen.", "nav.right_drag_orbits.help": "Uit: rechts slepen laat de camera met rust en de rechtermuisknop opent alleen het contextmenu. Het kiezen van de SolidWorks-muistoewijzing schakelt dit uit.", @@ -1750,6 +2073,11 @@ "not a move": "geen verplaatsing", "not a number": "geen getal", "open a sketch first": "open eerst een schets", + "parameters.apply_live": "Elke wijziging toepassen zodra je het veld verlaat", + "parameters.apply_live_tip": "Uit: wijzigingen wachten tot Toepassen of OK, daarna wordt het ontwerp één keer voor alle wijzigingen opnieuw opgebouwd. Annuleren of Escape verwerpt ze.", + "parameters.held": "{count} wijzigingen wachten op Toepassen", + "parameters.held_hint": "Bewerk expressies en eenheden. Wijzigingen wachten op Toepassen of OK.", + "parameters.held_one": "1 wijziging wacht op Toepassen", "parts.automatic_name": "automatisch", "parts.dimension.across_flats": "Sleutelwijdte", "parts.dimension.bore": "Boring", @@ -1768,10 +2096,19 @@ "parts.family.button_head_cap_screw": "Bolkopschroef met inbus", "parts.family.dowel_pin": "Parallelpen (paspen)", "parts.family.hex_bolt": "Zeskantbout / zeskantschroef", + "parts.family.hex_cap_screw_inch": "Zeskantschroef (inch)", "parts.family.hex_nut": "Zeskantmoer", + "parts.family.hex_nut_inch": "Zeskantmoer (inch)", "parts.family.set_screw": "Stelschroef met inbus, vlakke punt", "parts.family.socket_head_cap_screw": "Cilinderkopschroef met inbus", "parts.family.washer": "Vlakke onderlegring", + "parts.family.washer_sae": "Vlakke onderlegring, SAE (smal)", + "parts.family.washer_uss": "Vlakke onderlegring, USS (breed)", + "parts.holes": "Gaten (optioneel)", + "parts.placement_hint": "kies een of meer gaten om in elk een onderdeel te plaatsen, of OK plaatst het in de oorsprong", + "parts.system": "Eenhedensysteem", + "parts.system.inch": "Inch", + "parts.system.metric": "Metrisch", "pattern.alignment_2": "Uitlijning 2", "pattern.alignment_hint": "Aantallen omvatten het origineel. Gecentreerd verdeelt kopieën gelijkmatig; Omkeren kiest de extra zijde bij even totalen.", "pattern.direction_1": "Richting 1", @@ -1812,6 +2149,8 @@ "prefs.anti_aliasing_note": "Maakt kartelige randen glad.", "prefs.applies_on_restart": "Wordt toegepast na herstart", "prefs.assistant": "Assistent", + "prefs.auto_operation": "De bewerking automatisch kiezen", + "prefs.auto_operation_note": "De dialoogvensters van kenmerken kiezen Samenvoegen, Nieuw lichaam of Knippen op basis van wat het nieuwe materiaal raakt, totdat je er zelf een kiest. Uit: ze houden de bewerking aan waarmee ze openen.", "prefs.axes": "Assen", "prefs.axis": "As", "prefs.bodies_folders": "Lichamenmappen", @@ -1822,6 +2161,8 @@ "prefs.bottom_centre": "Midden onder", "prefs.bottom_right": "Rechtsonder", "prefs.browser": "Browser", + "prefs.browser_eye_left": "Oog naast de uitklappijl", + "prefs.browser_eye_left_note": "Rijen in de browser tonen hun oog om te tonen of te verbergen naast de uitklappijl, zoals voorheen, in plaats van in een kolom aan het rechteruiteinde van de rijen.", "prefs.browser_reveal_on_hover": "Tonen bij aanwijzen", "prefs.browser_show_note": "Getoond houdt de browser op het scherm. Tonen bij aanwijzen houdt hem uit beeld totdat de aanwijzer over zijn plek of over het smalle lipje aan zijn linkerrand komt, en hij blijft open zolang de aanwijzer erin staat of een menu ervan open is.", "prefs.browser_shown": "Getoond", @@ -1829,6 +2170,8 @@ "prefs.button_left": "Linkerknop slepen", "prefs.button_middle": "Middenknop slepen", "prefs.button_right": "Rechterknop slepen", + "prefs.carousel_next": "Volgende", + "prefs.carousel_previous": "Vorige", "prefs.choose_font": "Lettertypebestand kiezen…", "prefs.click": "Klik", "prefs.contact_shading": "Zachte contactschaduw", @@ -1841,6 +2184,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Gebogen oppervlakken", "prefs.curves": "Gebogen oppervlakken", + "prefs.cut_preview_tint": "Verwijderd materiaal rood tonen", + "prefs.cut_preview_tint_help": "Een voorbeeld vult het materiaal dat een kenmerk verwijdert, en de vorm die het vervangt, met een rood doorschijnend spookbeeld. Als dit uit staat, zijn die vullingen volledig transparant en worden alleen hun contouren getekend.", + "prefs.dark_parts_shading": "Vorm van donkere onderdelen behouden", + "prefs.dark_parts_shading_help": "Schaduw de weergave in lineair licht met een zachte hemelvulling, zodat donkere vlakken een verloop houden in plaats van zwart te worden", "prefs.dead_zone_note": "De gearceerde band is de dode zone: beweging daarbinnen wordt genegeerd.", "prefs.default": "standaard", "prefs.design": "Standaardwaarden voor ontwerpen", @@ -1851,10 +2198,19 @@ "prefs.dialogs_edge": "Aan de rand van de weergave", "prefs.dialogs_left_column": "In de linkerkolom", "prefs.dialogs_note": "Waar opdrachtdialogen openen: vastgezet aan de rand van de weergave, of in de linkerkolom in plaats van de browser en de geschiedenis, die terugkomen zoals ze waren wanneer de dialoog sluit.", + "prefs.dimension_step_angle": "Wat de pijlen van het venster, Omhoog/Omlaag en het wieltje bij een hoek optellen", + "prefs.dimension_step_length": "Wat de pijlen van het venster, Omhoog/Omlaag en het wieltje bij een lengte optellen", + "prefs.dimension_steps": "Stappen in het venster", + "prefs.dimension_values": "Maatwaarden", + "prefs.dimension_values_note": "Waar de waarde van een maat wordt ingevoerd. Een venster heeft pijlen die de waarde laten verspringen; het maatgereedschap plaatst eerst de tekst.", + "prefs.dimension_values_view": "In de weergave", + "prefs.dimension_values_window": "In een venster", "prefs.display": "Weergave", "prefs.edges": "Randen en schaduwing", "prefs.extend": "Verlengen", "prefs.extra_navigation": "Ctrl+linkerknop slepen op lege ruimte roteert; houd Space ingedrukt om te pannen.", + "prefs.extrude_view_isometric": "De weergave isometrisch draaien wanneer Extruderen opent", + "prefs.extrude_view_return": "Terug naar de eerdere weergave wanneer Extruderen sluit", "prefs.follows_os": "Volgt het besturingssysteem", "prefs.font": "Lettertype", "prefs.font_fallback": "Tekens die het gekozen lettertype mist, vallen terug op het ingebouwde lettertype, zodat geen enkel label een leeg vakje toont.", @@ -1870,8 +2226,11 @@ "prefs.graphics_card_auto": "Automatisch", "prefs.graphics_card_missing": "De opgeslagen grafische kaart is niet beschikbaar; Automatisch wordt gebruikt.", "prefs.graphics_card_restart": "Wordt van kracht na het opnieuw starten van SolidCraft. WGPU_ADAPTER_NAME heeft voorrang op deze keuze.", + "prefs.graphics_card_unused": "De opgeslagen grafische kaart is niet gebruikt voor dit venster; de kaart die wel in gebruik is, staat in Help › Over SolidCraft en in de statusbalk. Probeer Automatisch, of stel WGPU_ADAPTER_NAME in op een uniek deel van de kaartnaam.", "prefs.graphics_note": "Wissel snelheid in voor een gladder beeld. Elke keuze toont het effect op een voorbeeld.", "prefs.graphics_presets_note": "Voorinstellingen stellen de onderstaande keuzes samen in.", + "prefs.hide_constraint_glyphs_zoomed_out": "Beperkingssymbolen verbergen bij uitzoomen", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Beperkingssymbolen verdwijnen uit beeld als er zo ver op de schets is uitgezoomd dat ze het beeld zouden overladen. Uit: ze behouden bij elk zoomniveau een vaste grootte op het scherm.", "prefs.history": "Geschiedenis", "prefs.history_origin_bodies": "Oorsprong en lichamen bovenaan tonen", "prefs.history_origin_bodies_note": "De geschiedenis links of onder de browser begint met de map Lichamen van het actieve component en de Oorsprong, met hun oogpictogrammen en menu's zoals in de browser. De geschiedenis onderaan blijft ongewijzigd.", @@ -1882,6 +2241,8 @@ "prefs.history_sketches_note": "Als Schetsen op Onder hun kenmerk staat, toont de geschiedenis links elke schets een niveau ingesprongen, onder het eerste kenmerk dat erop is gebouwd, zodra die breed genoeg is voor namen. De tijdlijn onderaan houdt altijd de aanmaakvolgorde aan.", "prefs.history_sketches_under_feature": "Onder hun kenmerk", "prefs.hold_stop_snapping": "Ingedrukt houden om snappen te stoppen", + "prefs.home_fit_size": "Grootte bij Beginweergave en Passend", + "prefs.home_fit_size_note": "Hoeveel van de weergave het model vult wanneer Beginweergave, Passend, een geopend ontwerp of een wijziging van de navigatorweergave het model in beeld brengt, ongeacht of de instelling hieronder aan staat. 100 %: vult de weergave tussen de panelen, het kompas en de navigatiebalk.", "prefs.icons_only": "Alleen pictogrammen", "prefs.imported_file": "Geïmporteerd bestand", "prefs.in_browser": "In de browser", @@ -1890,13 +2251,22 @@ "prefs.interface_language": "Interfacetaal", "prefs.interface_note": "Hoe SolidCraft eruitziet en waar de onderdelen staan.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "De gebogen rolpijlen omkeren", + "prefs.invert_curved_roll_arrows_note": "De twee gebogen pijlen op de hoek van de kubus laten de weergave in het schermvlak rollen. Aan: de pijl met de klok mee rolt tegen de klok in en de pijl tegen de klok in rolt met de klok mee. Uit: elke pijl rolt de weergave in de richting waarin hij krult.", + "prefs.invert_navigator_arrows": "De rotatiepijlen van de weergavekubus omkeren", + "prefs.invert_navigator_arrows_note": "De pijlen rond de kubus laten de camera roteren in de richting waarin ze wijzen, zoals in Fusion en Inventor: de pijl links wijst naar rechts en zwaait de camera naar rechts. Uit: een pijl draait de kubus naar de kant waar hij staat, dus de linkerpijl zwaait de camera naar links. De gebogen rolpijlen worden hierdoor niet beïnvloed.", + "prefs.keep_work_on_tab_switch": "Dialoogvensters en gereedschappen open houden bij het wisselen van ontwerp", + "prefs.keep_work_on_tab_switch_note": "Elk ontwerptabblad behoudt zijn geopende dialoogvenster of gereedschap, met wat je erin hebt gekozen en getypt, en zijn lint-tabblad. Ze zijn er weer als je terugkeert naar het ontwerp. Uit: wisselen van ontwerp breekt ze af en toont het tabblad Model.", "prefs.labels": "Labels", + "prefs.language_system": "Systeem", "prefs.layout": "Indeling", "prefs.layout_note": "Compact plaatst panelen vast aan de vensterranden. Doorschijnendheid van de browser is beschikbaar in Zwevend. Wijzig de kant van de Assistent op de pagina Assistent.", "prefs.left": "Links", "prefs.left_click": "Linksklik", "prefs.line_drag_draws_one": "Indrukken en slepen tekent één lijn", "prefs.line_drag_draws_one_note": "In het lijngereedschap tekent indrukken, slepen en loslaten één lijn van het indrukpunt tot het loslaatpunt, en daar eindigt de lijn. Klikken tekent nog steeds een keten. Uit: slepen zet, net als een klik, een punt waar losgelaten wordt.", + "prefs.line_hover_tangent_arc": "Op het laatste punt van een lijn stilstaan om naar een tangentiële boog te wisselen", + "prefs.line_hover_tangent_arc_note": "Als je in het lijngereedschap een segment hebt getekend, beweeg je weg van het laatste punt van de keten, kom je terug en houd je de aanwijzer er stil: de volgende klik beëindigt een tangentiële boog, en hetzelfde gebaar schakelt terug naar lijnen. Uit: daar stilstaan doet niets.", "prefs.linked_designs": "Gekoppelde ontwerpen", "prefs.live_input": "Live invoer", "prefs.live_preview": "Live voorbeeld", @@ -1910,6 +2280,9 @@ "prefs.max_file_size_step": "STEP- en importbestanden", "prefs.max_file_size_web": "De webapp opent STEP- en importbestanden tot 512 MB en ontwerpen tot 256 MB: een browsertabblad kan geen grotere bestanden bevatten. In de desktopapp kunnen deze limieten worden verhoogd.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Grote pictogrammen", + "prefs.menu_list": "Lijst", + "prefs.menus": "Menu's", "prefs.minutes": "minuten", "prefs.minutes_suffix": " min", "prefs.mouse": "Muis en trackpad", @@ -1917,6 +2290,8 @@ "prefs.mouse_mapping": "Muistoewijzing", "prefs.navigation": "Navigatie", "prefs.navigation_note": "Hoe de muis, het trackpad en de 3D-muis de weergave verplaatsen.", + "prefs.navigator_fit": "Het model passend in beeld brengen na een wijziging van de navigatorweergave", + "prefs.navigator_fit_note": "Een vlak, hoek of pijl van de weergavekubus, of een as van de gizmo, kijkt ook naar het midden van het model, vanaf de ene afstand waarop het van alle kanten in beeld past (de omsluitende bol). Beginweergave gebruikt dezelfde zoom en hetzelfde middelpunt zolang dit aan staat, zodat weergaven die je daarna kiest alleen draaien. Uit: de weergave draait ter plaatse en behoudt het richtpunt en de zoom.", "prefs.network_host_remove": "Verwijderen", "prefs.network_locations": "Netwerklocaties in ontwerpen toestaan", "prefs.network_locations_note": "Uit: gekoppelde bestanden van een ontwerp op een andere computer (\\\\server\\share) worden alleen geopend vanaf de servers in deze lijst, of nadat je er een toestaat wanneer erom wordt gevraagd.", @@ -1929,10 +2304,18 @@ "prefs.origin_plane_names": "Namen van oorsprongsvlakken", "prefs.origin_plane_names_note": "Namen die worden getoond in de browser, dialoogvensters en lijsten. {top} is XY, {front} is XZ en {right} is YZ, met Z omhoog. Opdrachten, scripts en opgeslagen ontwerpen blijven XY, XZ en YZ gebruiken.", "prefs.overall_speed": "Totale snelheid", + "prefs.parameter_list_rows": "Rijen in de parameterlijst", + "prefs.parameter_list_rows_tip": "De pijl-omlaag in een leeg waardeveld toont de parameters, favorieten eerst, tot dit aantal. Minder houdt de lijst licht in een groot ontwerp.", + "prefs.persistent_ribbon_pressed": "Actieve lintopdrachten markeren", + "prefs.persistent_ribbon_pressed_help": "Lintopdrachten markeren zolang hun effect actief is. Zet dit uit om het vorige neutrale uiterlijk en de vorige opdrachthulp te behouden.", "prefs.perspective_fov": "Gezichtsveld", "prefs.placement": "Plaatsing", "prefs.prefer_free_sketch_points": "Verplaatsbare schetspunten voorrang geven als punten overlappen", "prefs.preview_choices": "Voorbeeld van je keuzes", + "prefs.preview_tint_new_faces": "Nieuw oppervlak in een voorbeeld inkleuren", + "prefs.preview_tint_new_faces_help": "Een voorbeeld van een kenmerk dat een lichaam wijzigt, kan het oppervlak dat het toevoegt in de voorbeeldkleur tekenen. Als dit uit staat, wordt het lichaam als zichzelf getekend.", + "prefs.print_face_highlight": "Markering van het printvlak", + "prefs.print_face_highlight_tip": "Hoe sterk het printvlak van een lichaam in de weergave wordt gekleurd en omlijnd. 0 % toont geen markering.", "prefs.profile_active": "Actief profiel", "prefs.profile_applied": "Profiel toegepast.", "prefs.profile_changed": "De instellingen zijn gewijzigd sinds het profiel is opgeslagen. Opslaan bewaart ze erin.", @@ -1954,9 +2337,13 @@ "prefs.quality_fastest": "snelste", "prefs.quality_slowest": "langzaamste", "prefs.quality_smoother": "gladder", + "prefs.quick_measure": "Snelle meting in de hoek van de weergave", + "prefs.quick_measure_note": "De grootte van de selectie rechtsonder in de weergave: de lengte van een rand, of Ø en R van een ronde rand, de oppervlakte van een vlak, de positie van een punt, de afstand en hoek van twee items, het totaal van meerdere randen of vlakken. Een klik kopieert hem.", "prefs.render_previous_geometry_budget": "Vorig geometriebudget voor het rendervoorbeeld gebruiken", "prefs.render_previous_geometry_budget_help": "De vorige vaste geometrielimiet herstellen (512 MiB op 64-bits desktops, elders 128 MiB) in plaats van het budget op basis van het apparaat.", "prefs.reports_saved": "{n} opgeslagen", + "prefs.ribbon_click_ends_tool": "Klikken op de knop van het actieve gereedschap beëindigt het", + "prefs.ribbon_click_ends_tool_note": "Een klik op de verlichte lintknop van het schetsgereedschap dat in gebruik is, beëindigt het gereedschap, zodat klikken in de weergave weer selecteert. Uit: de klik start het gereedschap opnieuw.", "prefs.ribbon_reveal": "Zoekresultaten in het lint tonen", "prefs.ribbon_reveal_note": "Als je de aanwijzer op een resultaat in Opdrachten zoeken houdt, zie je waar de opdracht in het lint staat: het tabblad, de knop of de rij in de vervolgkeuzelijst van een paneel. Een opdracht die vanuit de zoekfunctie is gestart, knippert daar, en een actieve opdracht uit een vervolgkeuzelijst markeert het paneel.", "prefs.right_click": "Rechtsklik", @@ -1967,6 +2354,8 @@ "prefs.search_empty": "Geen overeenkomende instellingen", "prefs.select": "Selecteren", "prefs.select_one_item": "Eén item selecteren", + "prefs.select_other_hidden": "Verborgen geometrie selecteren met Overige selecteren", + "prefs.select_other_hidden_help": "Aan: ook verborgen lichamen, schetsen en afgedekte randen bij de aanwijzer meenemen. Uit: de oorspronkelijke lijst met zichtbare geometrie onder de aanwijzer gebruiken.", "prefs.selecting": "Selecteren", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift voegt alleen toe; Ctrl / Cmd schakelt om", @@ -1978,11 +2367,16 @@ "prefs.sketch_align_points_note": "Tijdens het tekenen lijnt een punt tegelijk horizontaal uit met het ene schetspunt en verticaal met een ander, met een gestippelde hulplijn, en de klik behoudt beide uitlijningen. Uit: alleen met het vorige punt, één as tegelijk.", "prefs.sketch_conflict_colour": "Conflicterende geometrie in de conflictkleur", "prefs.sketch_conflict_colour_note": "Zolang de beperkingen van een schets conflicteren, worden ook de curven en punten die een niet-vervulde beperking vasthoudt in de conflictkleur getekend, niet alleen het symbool of de maat ervan. Uit: ze houden hun gewone kleuren.", + "prefs.sketch_construction_lines": "Uitgebreide tools voor constructielijnen", "prefs.sketch_exit_view": "Wanneer een schets eindigt", "prefs.sketch_exit_view.keep": "De huidige weergave behouden", "prefs.sketch_exit_view.previous": "Terug naar de vorige weergave", "prefs.sketch_exit_view.unless_rotated": "Terug, tenzij geroteerd", "prefs.sketch_exit_view_note": "Waar de weergave naartoe gaat na Schets afronden, Annuleren of een dubbele Esc.", + "prefs.sketch_face_activates_part": "Schetsen op het vlak van een onderdeel maakt dat onderdeel actief", + "prefs.sketch_face_activates_part_note": "Een schets die op een vlak van het lichaam van een andere component wordt gestart, activeert eerst die component, zodat de schets erbij hoort en in de browser bij dat onderdeel blijft. Het onderdeel blijft daarna actief. Uit: de schets hoort bij de actieve component.", + "prefs.sketch_open_look_at": "Naar een schets toe draaien wanneer die wordt geopend", + "prefs.sketch_open_look_at_note": "Uit: een schets maken of bewerken laat de weergave zoals die is. Kijken naar richt de weergave op de schets wanneer je dat wilt.", "prefs.sketch_recent_snap": "Automatisch snappen op recente cirkelmiddens en middelpunten", "prefs.sketch_recent_snap_note": "Tijdens het tekenen snapt de cursor op het punt waar de hulplijnen van de twee meest recente cirkelmiddens of middelpunten van rechte randen elkaar kruisen. Uit: die hulplijnen worden alleen getoond en de cursor beweegt niet.", "prefs.sketch_selection": "Schets en selectie", @@ -1994,17 +2388,42 @@ "prefs.sketch_tab_always_note": "De Schets-tab blijft in het lint staan, direct na Model, ook als er geen schets open is. Zijn tekentools beginnen dan een schets op het geselecteerde vlak, of op het vlak dat je daarna kiest, met de tool daarin klaar voor gebruik.", "prefs.sketch_tracking_guides": "Uitlijnhulplijnen voor midden en middelpunt", "prefs.sketch_tracking_guides_note": "Wijs naar het midden van een cirkel of het middelpunt van een rechte rand en beweeg dan horizontaal of verticaal om een tijdelijke gestippelde hulplijn te tonen.", + "prefs.sketch_tracking_points": "Uitlijnhulplijnen vanaf eindpunten en hoeken tijdens het tekenen", + "prefs.sketch_tracking_points_note": "Wanneer een tekengereedschap op een punt wacht, toont het aanwijzen van het uiteinde van een lijn of boog, een hoek van een rechthoek of een los punt dezelfde tijdelijke stippellijn als bij een middelpunt of midden. Uit: alleen middelpunten en middens.", "prefs.sketching": "Schetsen", "prefs.snap_drawing_note": "Tijdens het tekenen of slepen van een schetspunt.", "prefs.source": "Bron", "prefs.speed": "Snelheid", "prefs.stand_up_note": "Nadat een STEP- of IGES-bestand met Z omhoog is geopend, een kwartslag om X aanbieden.", + "prefs.stand_up_unknown": "Voor bestanden uit onbekende programma's", + "prefs.stand_up_unknown.ask": "Vragen in een dialoogvenster", + "prefs.stand_up_unknown.note": "Een melding tonen", + "prefs.stand_up_unknown.off": "Niet aanbieden", + "prefs.stand_up_unknown_note": "Hoe het aanbod wordt gedaan als de header van het bestand geen programma noemt waarvan bekend is dat het met Y omhoog opslaat. Een melding wordt alleen getoond als het bestand op zijn rug lijkt te liggen; Vragen in een dialoogvenster vraagt dat voor elk bestand van dat soort, zoals voorheen.", "prefs.status_bar": "Statusbalk", "prefs.status_bar_note": "Een smalle balk langs de onderrand van het venster toont wat er wordt bewerkt, de staat van de open schets in zijn kleur en de eenheden van het ontwerp; een klik op de eenheden wijzigt ze. De staat van de schets staat dan niet meer in de hoek van de weergave.", "prefs.status_done": "Gereed", "prefs.status_error": "Fout", "prefs.status_selected": "Geselecteerd", "prefs.status_warning": "Waarschuwing", + "prefs.structure.appearance": "Uiterlijk", + "prefs.structure.appearance_note": "Kleuren, tekst en toegankelijkheid.", + "prefs.structure.in_profile": "In profiel", + "prefs.structure.layout": "Indeling", + "prefs.structure.layout_note": "Waar de onderdelen van het venster staan.", + "prefs.structure.look": "Vormgeving", + "prefs.structure.measure_pointer": "Meten en aanwijzer", + "prefs.structure.mouse3d": "3D-muis", + "prefs.structure.mouse3d_note": "SpaceMouse en SpaceNavigator.", + "prefs.structure.navigation_note": "Muis en trackpad. De 3D-muis heeft een eigen pagina.", + "prefs.structure.profile": "Profiel", + "prefs.structure.profile_edited": "Gewijzigd sinds opslaan", + "prefs.structure.profile_hover": "Opgeslagen in instellingenprofielen", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Schets", + "prefs.structure.tools": "Gereedschappen", + "prefs.structure.tools_note": "Hoe modelleergereedschappen zich gedragen.", + "prefs.structure.work": "Werk", "prefs.supersampling_brief": "Tekent de weergave groter en filtert die omlaag: zeer scherp, maar zwaarder.", "prefs.tab_accent_note": "De accentkleur volgt het actieve tabblad", "prefs.theme_file": "themabestand", @@ -2016,6 +2435,16 @@ "prefs.theme_follow_off": "Uit", "prefs.theme_follow_stop": "Volgen stoppen", "prefs.theme_import_hint": "Klik om een themabestand te kiezen, sleep er een hierheen of druk op Ctrl+V (Cmd+V op een Mac) met een gekopieerd thema", + "prefs.theme_option_opacity": "Dekking", + "prefs.theme_option_opacity_help": "Pas de dekking van zwevende panelen aan. Een minimum voor leesbaarheid beschermt tekst boven de kleuren van de viewport.", + "prefs.theme_option_tab_colours": "Tabbladkleuren", + "prefs.theme_option_tab_colours_help": "Gebruik de paneel- en viewportkleuren van dit thema voor elk tabblad van het lint.", + "prefs.theme_option_tab_fade_ms": "Tabbladovergang", + "prefs.theme_option_tab_fade_ms_help": "Laat paneel- en viewportkleuren vervagen bij het wisselen van tabblad. Nul schakelt direct om.", + "prefs.theme_options_badge": "Opties", + "prefs.theme_options_more": "Meer · {count}", + "prefs.theme_options_reset": "Herstellen", + "prefs.theme_options_unavailable": "Niet beschikbaar op dit apparaat", "prefs.theme_paste": "Thema plakken", "prefs.theme_paste_none": "Het klembord bevat geen SolidCraft-thema", "prefs.timeline_half_hour": "−30 min", @@ -2037,13 +2466,23 @@ "prefs.under_cursor": "Onder de cursor", "prefs.units_precision": "Eenheden en precisie", "prefs.updates": "Updates", + "prefs.value_boxes_in_view": "Waarden naast hun grepen in de weergave tonen", + "prefs.value_boxes_in_view_tip": "De waarde van een opdracht (Afstand, Straal…) in een vak naast de greep, boven het model. Uit: je typt de waarde in het opdrachtvenster, dat na een keuze het toetsenbord overneemt, en niets bedekt het model.", "prefs.view": "Weergavegedrag", "prefs.view_confirm_corner": "OK en Annuleren in de hoek van de weergave", "prefs.view_confirm_corner_note": "Zolang een dialoogvenster of een schets open is, doen een vinkje en een kruisje rechtsboven in de weergave hetzelfde als OK en Annuleren van het dialoogvenster, of ze ronden de schets af of annuleren die. De weergavenavigator schuift daaronder naar beneden.", "prefs.viewport": "Weergavevenster", + "prefs.viewport_analysis_status": "Analysestatus van de viewport tonen", + "prefs.viewport_analysis_status_help": "Toon actieve analyses boven de viewport, open hun legenda's vanuit elk item en gebruik Esc om de nieuwste analyse uit te schakelen. Schakel uit om de legenda's in de hoeken en het vorige Esc-gedrag te herstellen.", "prefs.viewport_background": "Achtergrond", "prefs.viewport_background_colour": "Kleur", "prefs.viewport_background_theme": "Verloop van het thema", + "prefs.viewport_section_status": "Doorsnedestatus van de viewport tonen", + "prefs.viewport_section_status_help": "Toon de doorsnede-instelling in de viewport. Escape en de actieve lintknop schakelen hem uit. Schakel uit om de vorige doorsnedebediening te behouden.", + "prefs.viewport_status_details": "Live details van de viewport", + "prefs.viewport_status_details_help": "Bewerk actieve analyse- en doorsnede-instellingen in standaarddetailkaarten. Schakel uit om de alleen-lezen analysetoetsen en het dialoogvenster Doorsnede te herstellen.", + "prefs.viewport_status_summary": "Statusitems van de viewport samenvouwen", + "prefs.viewport_status_summary_help": "Vouw drie of meer statusitems van de viewport samen tot één overzichtsbadge. Schakel uit om elk item in de volledige rij te houden.", "prefs.wheel": "Wiel", "prefs.wheel_trackpad": "Wiel en trackpad", "prefs.workspace": "Werkruimte", @@ -2053,6 +2492,10 @@ "properties.title": "Eigenschappen: {name}", "recovery.days_ago": "{count} dagen geleden", "recovery.detail": "{file} · {features} kenmerken · automatisch opgeslagen {when}", + "recovery.discard_all": "Alles verwerpen", + "recovery.discard_all_detail": "Dit kan niet ongedaan worden gemaakt.", + "recovery.discard_all_title": "{count} automatische opslagen verwerpen?", + "recovery.discard_all_title_one": "1 automatische opslag verwerpen?", "recovery.hours_ago": "{count} u geleden", "recovery.just_now": "zojuist", "recovery.min_ago": "{count} min geleden", @@ -2168,6 +2611,10 @@ "render.base_color": "Basiskleur · sRGB", "render.base_metallic": "Metaalfractie", "render.base_opaque_only": "Deze editor behoudt de semantiek van ondoorzichtige lichamen. Gebruik de expliciete glasbesturing voor optische transmissie.", + "render.batch_all_shots": "Alle opnamen ({count})", + "render.batch_empty": "Sla een opname op voordat alle opnamen worden gerenderd.", + "render.batch_limit": "Alle opnamen renderen is beperkt tot 32 opnamen.", + "render.batch_status": "{running} bezig · {waiting} wachten", "render.bloom_enable": "Bloom tonen", "render.bloom_help": "Creatieve gloed, alleen in de uitvoer, afkomstig van positieve lineaire highlights en verspreid met drie genormaliseerde boxpassen. De straal is in uitvoerpixels. Toegevoegd in lineair weergavelicht vóór sRGB; geen lens- of volumetrisch effect en geen verbetering van de convergentie. De ruwe EXR blijft ongewijzigd.", "render.bloom_opaque": "Bloom vereist ondoorzichtige uitvoer. Transparante PNG wordt geweigerd, niet stilzwijgend afgevlakt.", @@ -2278,6 +2725,13 @@ "render.choose_look": "Kies eerst een uiterlijk in Uiterlijken", "render.chromatic_offset": "Chromatische randverschuiving", "render.clear_stage": "Opgeslagen decor verwijderen", + "render.compare_divider": "Scheidingslijn vergelijking", + "render.compare_live": "Live", + "render.compare_live_preview": "Live voorbeeld", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · vastgelegd bij revisie {revision}", + "render.compare_swap": "Omwisselen", "render.copy_request": "JSON kopiëren", "render.cpu_aa_help": "Ruimtelijke samples: meer samples verbeteren randen en verlengen de rendertijd.", "render.cpu_area_add": "Rechthoekig CPU-licht toevoegen", @@ -2918,7 +3372,9 @@ "render.output_ready": "Gereed om te renderen", "render.output_run_check": "Controle uitvoeren", "render.output_size_limit": "{method}: tot {dimension} px per zijde en {pixels} pixels. Grootste passende formaat: {width} × {height}.", + "render.output_size_method_profile": "Kies voor het renderen van {width} × {height} de methode {method} met het CPU-resourceprofiel {profile}, of een kleiner formaat.", "render.output_size_ok": "Grootte OK · {width} × {height} px", + "render.output_size_profile": "Kies voor het renderen van {width} × {height} het CPU-resourceprofiel {profile}, of een kleiner formaat.", "render.output_swap_orientation": "Breedte en hoogte omwisselen", "render.output_tools_inspector": "Bewerk grootte en bestandsindeling in de inspecteur Uitvoer.", "render.output_view_image": "Afbeelding bekijken", @@ -3025,6 +3481,10 @@ "render.result_retained": "De laatste voltooide afbeelding wordt getoond; een nieuwere render heeft die nog niet vervangen.", "render.result_sequence": "Controlepunt", "render.result_title": "Renderresultaat", + "render.results_choose": "Bewaarde resultaten", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [verouderd]", + "render.results_unnamed": "Afbeelding", "render.return_design": "Terug naar Ontwerp", "render.review_stale": "Deze beoordeling is verouderd. Los het op of controleer opnieuw voordat je toepast.", "render.ribbon_aging": "Veroudering", @@ -3131,6 +3591,7 @@ "render.size_custom": "Aangepast…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · vereist {profile}", "render.size_presets": "Groottevoorinstellingen", "render.size_presets_pending": "Komt met de Uitvoer-editor", "render.size_preview": "Voorbeeld", @@ -3418,6 +3879,24 @@ "sheet.flange_type_contour": "Contour", "sheet.flange_type_edge": "Rand", "sheet.no_body": "er is geen plaatwerklichaam: begin er een met Flens > Basis, of zet een plaat om in plaatwerk met Converteren naar plaatwerk (kies het grote platte vlak ervan)", + "sheet.personal_rules.confirm_delete": "Verwijderen bevestigen", + "sheet.personal_rules.delete": "Verwijderen", + "sheet.personal_rules.delete_prompt": "Deze persoonlijke regel verwijderen? Regels die al in ontwerpen staan, blijven ongewijzigd.", + "sheet.personal_rules.full": "De persoonlijke bibliotheek bevat al 64 regels.", + "sheet.personal_rules.invalid_name": "Voer een korte naam in zonder regeleinden of stuurtekens.", + "sheet.personal_rules.invalid_values": "Vul de waarden van de regel aan: elke waarde moet in dit ontwerp uitwerkbaar zijn, met een positieve dikte en een K-factor van 0 tot 1.", + "sheet.personal_rules.missing": "De geselecteerde persoonlijke regel is niet meer beschikbaar.", + "sheet.personal_rules.name": "Regelnaam", + "sheet.personal_rules.name_exists": "Er bestaat al een persoonlijke regel met deze naam. Gebruik een andere naam.", + "sheet.personal_rules.name_hint": "Een unieke naam", + "sheet.personal_rules.overwrite": "Wijzigingen in geselecteerde persoonlijke regel opslaan", + "sheet.personal_rules.rename": "Hernoemen", + "sheet.personal_rules.rule": "Persoonlijke regel", + "sheet.personal_rules.save": "Als nieuw opslaan", + "sheet.personal_rules.scope": "Opgeslagen in je profiel voor alle ontwerpen.", + "sheet.personal_rules.select": "Selecteer een regel", + "sheet.personal_rules.title": "Persoonlijke regels", + "sheet.personal_rules.unsupported": "Deze regel bevat waarden die deze versie niet kan gebruiken.", "shortcut.json_error": "parameters moeten JSON zijn: {error}", "shortcut.no_command": "geen opdracht `{id}`; de tekst vóór de JSON moet een opdracht-id zijn", "shortcut.pin": "Bovenaan het S-vak vastpinnen", @@ -3454,8 +3933,10 @@ "sketch_text.align_right": "Rechts", "sketch_text.bold": "Vet", "sketch_text.builtin_font": "{family} (ingebouwd)", + "sketch_text.formula": "Begin met = om de woorden uit parameters op te bouwen: ='W' + number(Width)", "sketch_text.italic": "Cursief", "sketch_text.loading_fonts": "Geïnstalleerde lettertypen zoeken…", + "sketch_text.no_bold": "Het ingebouwde lettertype heeft geen vette variant: kies een geïnstalleerd lettertype", "sketch_text.on_path": "De tekst volgt zijn pad: de curve plaatst hem", "sketch_text.path_clear": "De tekst van zijn curve halen", "sketch_text.path_hint": "Een curve van de schets die de tekst volgt: klik hier en daarna op de curve", @@ -3487,10 +3968,7 @@ "the two origins are on the same component": "de twee oorsprongen liggen op hetzelfde component", "thread.automatic_size": "Automatische grootte", "thread.designation": "Aanduiding", - "thread.direction": "Richting van schroefdraad", "thread.iso_metric": "ISO metrisch", - "thread.left_hand": "Linksdraaiend", - "thread.right_hand": "Rechtsdraaiend", "thread.select_size": "Grootte selecteren", "timeline.delete_after_marker_one": "1 kenmerk na geschiedenismarkering verwijderen", "timeline.delete_after_marker_other": "{count} kenmerken na geschiedenismarkering verwijderen", @@ -3507,8 +3985,10 @@ "timeline.move_to_group": "Kenmerken naar map verplaatsen", "timeline.rename_group": "Kenmerkmap hernoemen", "timeline.reorder_many": "Kenmerken herordenen", + "timeline.suppress_features": "Kenmerken onderdrukken", "timeline.suppress_folders_tip": "Alle kenmerken in de mappen en hun geneste mappen onderdrukken of de onderdrukking ervan opheffen", "timeline.ungroup": "Kenmerkmappen verwijderen", + "timeline.unsuppress_features": "Onderdrukking van kenmerken opheffen", "to the face": "tot het vlak", "to the next face": "tot het volgende vlak", "toolbar.customize_note": "Tabblad {tab}. Vink een opdracht aan om er een werkbalkknop voor te maken. U kunt ook een rij uit de vervolgkeuzelijst van een paneel naar de werkbalk slepen, een knop van de werkbalk af slepen om hem te verwijderen, of de pin op een rij van de vervolgkeuzelijst gebruiken.", @@ -3592,6 +4072,8 @@ "ui.3d_mouse_section": "3D-muis", "ui.3d_mouse_show_in_view": "De 3D-muis tonen in de 3D-weergave", "ui.3d_mouse_show_in_view_tip": "Een afbeelding van je 3D-muis in de linkerbenedenhoek, die meebeweegt als jij de muis beweegt.", + "ui.3d_mouse_sketch_orbit": "Schetsen roteren met de 3D-muis", + "ui.3d_mouse_sketch_orbit_tip": "De 3D-muis roteert de weergave ook terwijl een schets open is en recht van voren wordt bekeken, zoals de muis dat kan. Uit: hij pant en zoomt de schets totdat je de weergave kantelt.", "ui.3d_mouse_skip": "Mijn apparaat kan dit niet", "ui.3d_mouse_skip_tip": "Slaat deze beweging in beide richtingen over, en de kalibratie laat haar weg.", "ui.3d_mouse_speed": "Snelheid van 3D-muis", @@ -3620,6 +4102,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Draai de dop tegen de klok in, houd vast en laat dan los.", "ui.3d_mouse_switch_cap": "Kalibreren als Return to Center", "ui.3d_mouse_switch_trackball": "Kalibreren als trackball", + "ui.3d_mouse_use_direct": "Direct stuurprogramma gebruiken", + "ui.3d_mouse_use_direct_tip": "De 3D-muis direct uitlezen (hidraw) in plaats van via spacenavd.", "ui.3d_mouse_view_axis": "Weergave-as", "ui.3d_mouse_view_off": "Uit", "ui.3d_mouse_view_off_tip": "Het profiel van het 3D-muisstuurprogramma schakelt deze as uit, dus de beweging ervan verplaatst de weergave niet. Kies je hier de beweging van een andere as, dan wisselen de twee van plaats en verplaatst die beweging de weergave niet meer.", @@ -3658,6 +4142,8 @@ "ui.agent_chat_auth_terminal": "Voer dit uit in een terminal en druk daarna opnieuw op Verbinden:", "ui.agent_chat_auth_title": "Aanmelden bij de agent", "ui.agent_chat_cancel": "Annuleren", + "ui.agent_chat_cancel_timeout": "De agent reageerde niet op Stoppen en is losgekoppeld. Verbind opnieuw om door te gaan.", + "ui.agent_chat_cannot_start": "Geïnstalleerd, maar start niet: {error}", "ui.agent_chat_changes": "Wijzigingen: {n}, één stap ongedaan maken", "ui.agent_chat_changes_n": "{n} wijzigingen", "ui.agent_chat_changes_of": "{n}/{limit} wijzigingen", @@ -3666,11 +4152,13 @@ "ui.agent_chat_command": "Agentopdracht", "ui.agent_chat_connect": "Verbinden", "ui.agent_chat_copy": "Kopiëren", + "ui.agent_chat_copy_message": "Bericht kopiëren", "ui.agent_chat_ctx_bodies": "Lichamen", "ui.agent_chat_ctx_elements": "Elementen", "ui.agent_chat_ctx_features": "Kenmerken", "ui.agent_chat_ctx_more": "+{n} meer", "ui.agent_chat_ctx_other": "Overig", + "ui.agent_chat_custom_heading": "Eigen model", "ui.agent_chat_custom_hint": "Elk programma dat het Agent Client Protocol spreekt via stdin en stdout. Er wordt geen shell gebruikt.", "ui.agent_chat_denied": "Geweigerd", "ui.agent_chat_deny": "Weigeren", @@ -3714,8 +4202,16 @@ "ui.agent_chat_mode_all": "Alles", "ui.agent_chat_mode_ask": "Vragen", "ui.agent_chat_mode_edits": "Bewerken", + "ui.agent_chat_model_custom": "Eigen model gebruiken: {model}", "ui.agent_chat_model_no_tools": "{model} kan de gereedschappen van SolidCraft niet gebruiken en kan dus alleen chatten. Kies een model met ondersteuning voor gereedschappen.", + "ui.agent_chat_model_rejected": "De agent accepteerde {model} niet: {error}", + "ui.agent_chat_model_search": "Modellen zoeken…", "ui.agent_chat_model_tip": "Het model dat de agent gebruikt. Uw keuze wordt voor deze agent onthouden.", + "ui.agent_chat_models_failed": "Modellen konden niet worden opgehaald: {error}", + "ui.agent_chat_models_heading": "Beschikbare modellen", + "ui.agent_chat_models_listing": "Modellen ophalen…", + "ui.agent_chat_models_none": "Het eindpunt geeft geen modellen weer", + "ui.agent_chat_models_not_a_list": "Het antwoord was geen lijst met modellen", "ui.agent_chat_new": "Nieuwe chat", "ui.agent_chat_new_confirm": "Een nieuwe chat starten? De huidige wordt gewist.", "ui.agent_chat_next_picture": "Volgende afbeelding", @@ -3750,9 +4246,12 @@ "ui.agent_chat_queued_stopped": "In wachtrij (gestopt, niet verzonden)", "ui.agent_chat_refresh": "Vernieuwen", "ui.agent_chat_refused": "Niet toegestaan voor de agent: {reason}", + "ui.agent_chat_reinstall": "{agent} is geïnstalleerd ({program}), maar is niet gestart toen SolidCraft het controleerde: {error}\nDe installatie is mogelijk onvolledig, of gemaakt voor een ander type computer. Installeer opnieuw met `{install}`, controleer in een terminal of de versie wordt afgedrukt en druk dan op Vernieuwen.", "ui.agent_chat_remove": "Uit de wachtrij verwijderen", "ui.agent_chat_remove_file": "Van dit bericht verwijderen", "ui.agent_chat_remove_imported": "Van dit bericht verwijderen; het onderdeel blijft in het ontwerp (Ongedaan maken verwijdert het)", + "ui.agent_chat_reply_cut_off": "Het antwoord bereikte zijn lengtelimiet voordat het klaar was en is mogelijk onvolledig. Vraag de agent om door te gaan, of om een korter antwoord.", + "ui.agent_chat_reply_declined": "Het model weigerde dit bericht te beantwoorden.", "ui.agent_chat_retry": "Opnieuw proberen", "ui.agent_chat_right": "Rechts", "ui.agent_chat_save": "Opslaan", @@ -3811,12 +4310,17 @@ "ui.ai_copy_suffix": "kopie", "ui.ai_custom_url": "Aangepaste URL", "ui.ai_default": "Standaard", + "ui.ai_edit": "Bewerken", + "ui.ai_edit_agent_title": "Agent bewerken", + "ui.ai_edit_gone": "Deze agent is verwijderd, dus er valt niets op te slaan.", + "ui.ai_edit_tip": "Wijzig de naam, opdracht of het eindpunt van deze agent. Een opgeslagen sleutel blijft verborgen.", "ui.ai_http_busy": "het eindpunt is bezet of boven zijn limiet; probeer het later opnieuw", "ui.ai_http_key": "het eindpunt weigerde de sleutel: controleer deze in Voorkeuren > AI", "ui.ai_http_not_found": "geen eindpunt of model gevonden: controleer de basis-URL en de modelnaam", "ui.ai_http_too_large": "het gesprek is te groot voor dit endpoint; begin een nieuwe chat", "ui.ai_key": "API-sleutel", "ui.ai_key_hint": "optioneel; bewaard in de sleutelhanger van het systeem", + "ui.ai_key_keep_hint": "laat leeg om de opgeslagen sleutel te behouden", "ui.ai_key_needs_https": "Een sleutel wordt alleen via HTTPS of naar deze computer verzonden.", "ui.ai_key_note": "Bewaard in de sleutelhanger van het systeem, nooit in de instellingen van SolidCraft. Laat leeg voor een lokale server.", "ui.ai_keychain_error": "De sleutelhanger van het systeem weigerde: {error}", @@ -3843,11 +4347,15 @@ "ui.ai_permissions": "Machtigingen", "ui.ai_preset": "Voorinstelling", "ui.ai_protocol": "Protocol", + "ui.ai_reasoning_effort": "Redeneerinspanning", + "ui.ai_reasoning_effort_field_hint": "leeg = standaard van de provider", + "ui.ai_reasoning_effort_hint": "Optioneel. Wordt als `reasoning_effort` naar het eindpunt gestuurd; toegestane waarden verschillen per provider (bijvoorbeeld `low`, `high` of `max`). Een waarde die je hier instelt, wordt nooit door SolidCraft vervangen. Laat het veld leeg om niets te sturen en de standaard van de provider te behouden.", "ui.ai_remove": "Verwijderen", "ui.ai_request_timed_out": "Het model deed er langer dan {seconds} s over. Je kunt de time-out voor aanvragen van dit eindpunt verhogen in Voorkeuren › Assistent.", "ui.ai_request_timeout": "Time-out voor aanvragen", "ui.ai_request_timeout_hint": "Hoelang één modelaanvraag aan dit eindpunt mag duren, van 30 s tot een uur. Verhoog dit voor een traag lokaal model.", "ui.ai_reset": "Herstellen", + "ui.ai_save": "Opslaan", "ui.ai_settings": "AI-instellingen…", "ui.ai_show_features": "AI-functies tonen", "ui.ai_show_features_note": "De agentchat: een paneel waarin een codeeragent die u al gebruikt, of een modeleindpunt naar keuze, aan het geopende ontwerp werkt. Uit: geen AI-knop, sneltoets, menu-item of paneel, en er wordt niets gezocht of gestart.", @@ -3926,6 +4434,8 @@ "ui.cancel": "Annuleren", "ui.canvases": "Canvassen", "ui.center": "Midden", + "ui.center_arc_follows_cursor": "Boog met middelpunt volgt de richting van de cursor", + "ui.center_arc_follows_cursor_tip": "Een boog met middelpunt loopt met de klok mee of ertegen in, afhankelijk van hoe de cursor om het middelpunt heen beweegt. Uit: altijd tegen de klok in vanaf het begin.", "ui.centerline": "Hartlijn", "ui.chain": "Keten", "ui.chamfer": "Afschuining", @@ -3934,6 +4444,7 @@ "ui.circle": "Cirkel", "ui.circular_pattern": "Cirkelvormig patroon", "ui.clear": "Wissen", + "ui.clear_print_face": "Printvlak wissen", "ui.clear_recent": "Recent wissen", "ui.clear_the_selection": "De selectie wissen", "ui.click_selects_whole_bodies": "Klik selecteert volledige lichamen", @@ -3968,12 +4479,27 @@ "ui.constant": "Constant", "ui.constraints_conflict": "Beperkingen conflicteren", "ui.construction": "Constructie", + "ui.construction.angle_hint": "Constructielijn: klik op een punt en typ dan een hoek of kies een richting", + "ui.construction.bisector_hint": "Bissectrice: kies twee elkaar snijdende rechte lijnen en dan de gewenste oplossing", + "ui.construction.common_hint": "Gemeenschappelijke raaklijn: kies twee cirkels/bogen en dan de gewenste oplossing", + "ui.construction.contact_hint": "Raaklijn: kies een cirkel/boog of open spline/kegelsnede en dan het raakpunt (vrije krommen: eindpunten)", + "ui.construction.external_hint": "Raaklijn: kies een cirkel of boog, een extern punt en dan de gewenste oplossing", + "ui.construction.free_hint": "Constructielijn: klik op twee punten; klik met rechts om opnieuw te beginnen", + "ui.construction.normal_needs_length": "Een oneindige lijn is altijd een constructielijn: typ een lengte om een normale lijn te tekenen", + "ui.construction.point_hint": "Constructielijn: klik op het punt waar de lijn doorheen moet", + "ui.construction.reference_hint": "Constructielijn: kies een rechte lijn en dan een punt; klik met rechts om de referentie te wijzigen", "ui.construction.ribbon_label": "Hulplijnen", + "ui.construction.side_hint": "Constructielijn: klik op de zijde waarheen de lijn loopt; klik met rechts om opnieuw te beginnen", "ui.context_menu": "Contextmenu", + "ui.continuity_crease": "Knik", + "ui.continuity_curvature": "Kromming", + "ui.continuity_curvature_change": "Krommingsverandering", "ui.continuity_g0": "G0-knik", "ui.continuity_g1": "G1-tangentieel", "ui.continuity_g2": "G2-kromming", "ui.continuity_gap": "Opening", + "ui.continuity_position": "Positie", + "ui.continuity_tangent": "Tangentieel", "ui.copy": "Kopiëren", "ui.corner": "Hoek", "ui.corners": "Hoeken", @@ -3996,6 +4522,7 @@ "ui.dark": "Donker", "ui.default_modelling_orientation": "Standaard modelleeroriëntatie", "ui.delete": "Verwijderen", + "ui.delete_select_first": "Selecteer eerst wat je wilt verwijderen: kenmerken, lichamen, componenten of schetsgeometrie", "ui.depth": "Diepte", "ui.design": "Ontwerp", "ui.design_properties.author": "Auteur", @@ -4010,6 +4537,40 @@ "ui.design_properties.project": "Project", "ui.design_properties.revision": "Revisie", "ui.design_saved": "Opgeslagen in {path}", + "ui.details_access_caption": "Vlakken tonen of een gereedschap ze vanuit de gekozen richting kan bereiken.", + "ui.details_angle": "Hoek", + "ui.details_continuity_caption": "Bewerk de geselecteerde naad. Andere naden behouden hun eigen instellingen.", + "ui.details_continuity_stale": "Eerdere geometrie: voer de analyse opnieuw uit om deze naad te bewerken of in beeld te brengen.", + "ui.details_copy_list": "Lijst kopiëren", + "ui.details_curvature": "Krommingstolerantie", + "ui.details_curvature_caption": "Vlakken worden gekleurd op hun lokale krommingsstraal.", + "ui.details_direction": "Gereedschapsrichting", + "ui.details_draft_caption": "Vlakken worden gekleurd op hun hoek ten opzichte van de trekrichting.", + "ui.details_edit_seam": "Naad bewerken", + "ui.details_fixture": "Voorbeeldcomponent — alleen voorbeeldgegevens", + "ui.details_fixture_caption": "Voorbeeldcomponent met illustratieve waarden; dit is geen modelresultaat.", + "ui.details_fixture_problem": "Voorbeeldbevinding met een probleem", + "ui.details_fixture_readout": "Voorbeeld van een gemeten waarde", + "ui.details_flip": "Omdraaien", + "ui.details_gap": "Opening", + "ui.details_hatch": "Snijvlakken arceren", + "ui.details_jump": "Krommingssprong", + "ui.details_key": "Legenda", + "ui.details_offset": "Offset", + "ui.details_plane": "Vlak", + "ui.details_pull": "Trekrichting", + "ui.details_radius": "Straal", + "ui.details_readout": "Uitlezing", + "ui.details_samples": "Samples", + "ui.details_seam": "{body} · Rand {edge}", + "ui.details_settings": "Instellingen", + "ui.details_sharp_gap": "Scherp of opening", + "ui.details_show_all": "Alle {count} tonen", + "ui.details_smooth": "Glad", + "ui.details_stripes": "Strepen", + "ui.details_target": "Geometrie in beeld brengen", + "ui.details_worst_seams": "Slechtste naden", + "ui.details_zebra_caption": "Weerspiegelde strepen tonen hoe vloeiend vlakken op elkaar aansluiten.", "ui.diameter": "Diameter", "ui.dimension": "Maat", "ui.direct_interaction": "Directe interactie", @@ -4054,6 +4615,7 @@ "ui.edit_in_place_saved_elsewhere": "Het onderdeel is in een ander bestand opgeslagen; de samenstelling is nog steeds gekoppeld aan {name}", "ui.edit_in_place_wait": "Wacht tot wat in het ontwerp wordt uitgevoerd klaar is", "ui.edit_section_analysis": "Doorsnedeanalyse bewerken", + "ui.edit_sketch_empty": "Geen schetsen om te bewerken", "ui.ellipse": "Ellips", "ui.emboss_wrap_note": "Orthogonale lijnprofielen die raken aan één ondersteunde cilinder worden automatisch omwikkeld. Kies een wand om een doel te kiezen.", "ui.end_radius": "Eindstraal", @@ -4064,12 +4626,15 @@ "ui.equation_explicit": "Expliciet", "ui.equation_form": "Vorm", "ui.equation_note": "De variabele is een gewoon getal: sin(t) neemt het in radialen. Een resultaat zonder eenheid is in de eenheid van het ontwerp.", + "ui.equation_note_range": "De variabele is een lengte, net als haar bereik: combineer haar met lengteparameters en deel haar voor sin() door een lengte. Een resultaat zonder eenheid is in de eenheid van het ontwerp.", "ui.equation_parametric": "Parametrisch", + "ui.equation_variable_unit": "Variabele heeft de eenheid van het bereik", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Equivalente straal", "ui.expand": "Uitvouwen", + "ui.explode_needs_two_components": "Explosieweergave trekt componenten uit elkaar, dus het ontwerp heeft er twee of meer nodig (Nieuw component, Ontwerp invoegen of Componenten maken van lichamen)", "ui.exportDxf": "DXF exporteren…", "ui.export_ellipsis_keymap": "Exporteren…", "ui.export_keymap_tip": "Sneltoetsen, favorieten van het S-vak en de werkbalk, als bestand", @@ -4195,6 +4760,7 @@ "ui.hideOrigin": "Oorsprong verbergen", "ui.hidePlanes": "Vlakken verbergen", "ui.hideProfile": "Profiel verbergen", + "ui.hide_component_history": "Geschiedenis ervan verbergen", "ui.hide_origin_by_default": "Oorsprong standaard verbergen", "ui.hide_origin_note": "Nieuwe ontwerpen beginnen met de map Oorsprong verborgen. Een ontwerp behoudt zijn eigen instelling voor Oorsprong zodra je die toont of verbergt.", "ui.history_back": "Eén stap terug", @@ -4202,6 +4768,7 @@ "ui.history_edge_hint": "dubbelklik op de rand", "ui.history_first": "Naar het begin", "ui.history_forward": "Eén stap vooruit", + "ui.history_hide_hidden": "Verborgen componenten verbergen", "ui.history_hide_names": "Namen verbergen", "ui.history_last": "Naar het einde", "ui.history_marker_tip": "Geschiedenismarkering: sleep om het model terug te draaien; nieuwe kenmerken komen hier", @@ -4211,10 +4778,12 @@ "ui.history_play_button_show": "Afspeelknop tonen", "ui.history_play_finish_action": "Voltooi de huidige actie voordat u de geschiedenis afspeelt", "ui.history_play_roll_back": "Verplaats de geschiedenismarkering naar achteren voordat u afspeelt", + "ui.history_show_hidden": "Verborgen componenten tonen", "ui.history_show_names": "Namen tonen", "ui.history_sketch_listed_under": "Vermeld onder {feature}", "ui.history_title": "Geschiedenis", "ui.history_toggle_names": "Kenmerknamen tonen of verbergen", + "ui.history_waits_for_editor": "Ongedaan maken, Opnieuw en Geschiedenis wachten tot de kenmerkeditor is geopend", "ui.hole": "Gat", "ui.hole_tap_type": "Type tapgat", "ui.hole_type": "Gattype", @@ -4230,6 +4799,7 @@ "ui.insert_design.saved_file": "{name} heeft niet-opgeslagen wijzigingen, dus is het opgeslagen bestand ingevoegd. Sla het op en gebruik daarna Koppelingen bijwerken om de wijzigingen over te nemen.", "ui.insert_design.unsaved": "Niet-opgeslagen wijzigingen", "ui.inspect": "Inspecteren", + "ui.instances": "Instanties", "ui.intersect": "Snijden", "ui.isolate": "Isoleren", "ui.join": "Samenvoegen", @@ -4238,12 +4808,14 @@ "ui.joints": "Verbindingen", "ui.keyboard_shortcuts": "Sneltoetsen", "ui.language": "Taal", + "ui.lasso_select": "Lasso (sleep een lus uit de vrije hand: neemt alles wat er helemaal binnen valt)", "ui.layout_compact": "Compact", "ui.layout_floating": "Zwevend", "ui.length": "Lengte", "ui.length_decimals": "Lengtedecimalen", "ui.light": "Licht", "ui.line": "Lijn", + "ui.line_arc_hint": "Tangentiële boog: klik op het eindpunt van de boog. Blijf opnieuw stilstaan op het laatste punt voor lijnen; klik met rechts of druk op Esc om te voltooien", "ui.link_copies": "Identieke kopieën koppelen", "ui.link_copies_keep": "Behouden", "ui.link_copies_link": "Koppelen", @@ -4332,6 +4904,7 @@ "ui.part_size_shared": "Bouwt het onderdeel opnieuw op en vervangt alle toegevoegde kenmerken. Alle voorkomens van dit component worden bijgewerkt.", "ui.paste": "Plakken", "ui.path": "Pad", + "ui.pattern_object_type_tip": "Lichamen: massieve vormen, gekozen in de weergave of de Browser; elk wordt in zijn geheel gekopieerd.\nKenmerken: stappen van de Geschiedenis, zoals een extrusie of een gat, gekozen in de Geschiedenis of op een vlak dat ze hebben gemaakt; de stap wordt herhaald.\nEen schets is geen van beide: herhaal de curven ervan met het eigen Patroon of Spiegelen van de schets, of extrudeer de schets eerst.", "ui.pattern_on_path": "Patroon op pad", "ui.perforate_margin_default": "vanaf de diameter", "ui.perforate_pitch": "Steek", @@ -4358,12 +4931,17 @@ "ui.plugins_skipped": "{count} map(pen) kon(den) niet worden gelezen.", "ui.plugins_version": "{version}", "ui.point": "Punt", + "ui.point_cloud_add_filter": "Filter toevoegen…", "ui.point_cloud_auto_range": "Automatisch bereik", "ui.point_cloud_color_by": "Kleuren op basis van", "ui.point_cloud_file_colors": "Bestandskleuren", + "ui.point_cloud_filter_by": "Filteren op", "ui.point_cloud_height_high": "Hoogste", "ui.point_cloud_height_low": "Laagste", + "ui.point_cloud_legend_filter": "Getoond en verborgen in de legenda hierboven", "ui.point_cloud_no_file_colors": "Het bestand bevat geen kleuren", + "ui.point_cloud_pause": "Pauzeren", + "ui.point_cloud_play": "Afspelen", "ui.point_cloud_single_color": "Eén kleur", "ui.point_cloud_size": "Puntgrootte", "ui.point_cloud_units": "Bestandseenheden", @@ -4372,6 +4950,11 @@ "ui.polygon": "Veelhoek", "ui.preferences": "Voorkeuren", "ui.press_a_key": "druk op een toets…", + "ui.print_face_body_not_sent": "Het lichaam van dat vlak wordt niet verstuurd: voeg het eerst toe aan Lichamen", + "ui.print_face_cleared": "{body}: printvlak gewist", + "ui.print_face_input": "Printvlak", + "ui.print_face_pick": "Selecteer één vlak van een massief lichaam om het het printvlak te maken", + "ui.print_face_set": "{body}: printvlak ingesteld; Naar slicer sturen legt het lichaam erop", "ui.profile": "Profiel", "ui.profile_plane": "Profielvlak", "ui.profiles": "Profielen", @@ -4387,6 +4970,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Meten…", + "ui.properties.measuring_bodies": "Meten… {done} van {total} lichamen", "ui.properties.measuring_failed": "Het meten is gestopt voordat het klaar was.", "ui.properties.principal_axis": "Hoofdas {number}", "ui.properties.principal_moments": "Hoofdtraagheidsmomenten", @@ -4435,6 +5019,7 @@ "ui.revolve": "Revolve", "ui.ribbon_exit": "Afsluiten", "ui.ribbon_labels": "Tekst onder lintpictogrammen tonen", + "ui.ribbon_menus_skip_pinned": "Vastgepinde opdrachten weglaten uit de vervolgkeuzelijsten", "ui.ribbon_pin_footer": "Vastgepinde opdrachten verschijnen in het lint. Beweeg over een rij om vast te pinnen of los te maken.", "ui.ribbon_workspace": "Werkruimte", "ui.right": "Rechts", @@ -4453,6 +5038,7 @@ "ui.selectOther": "Overige selecteren…", "ui.selectTangentChain": "Tangentiële keten selecteren", "ui.select_all": "Alles selecteren", + "ui.select_components_by_face": "Componenten selecteren (een vlak kiest zijn component)", "ui.selection": "Selectie", "ui.selection_modifiers": "Selectiemodificatoren", "ui.selection_shift_add_only": "Shift+klik voegt toe zonder te verwijderen", @@ -4478,6 +5064,7 @@ "ui.showDimension": "Maat tonen", "ui.showOrigin": "Oorsprong tonen", "ui.showPlanes": "Vlakken tonen", + "ui.show_component_history": "Geschiedenis ervan tonen", "ui.show_constraints": "Beperkingen", "ui.show_construction_geometries": "Constructiegeometrieën", "ui.show_dimensions": "Maatvoering", @@ -4494,6 +5081,11 @@ "ui.sketch_intersect_selection_filter": "Selectiefilter", "ui.sketch_modifiers": "Schetsmodificatoren", "ui.sketch_project_geometry": "Geometrie", + "ui.sketch_report.all_constrained": "Alles is volledig beperkt.", + "ui.sketch_report.dof": "Vrijheidsgraden", + "ui.sketch_report.loose": "Niet volledig beperkt", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Schetsrapport", "ui.sketch_scale": "Schetsschaal", "ui.sketches": "Schetsen", "ui.slice": "Slicen", @@ -4589,19 +5181,31 @@ "ui.view_angles": "Weergavehoeken", "ui.view_angles_convention": "Graden rond de verticale as. Gieren 0° is het vooraanzicht, 90° het linkeraanzicht, −90° het rechteraanzicht, 180° het achteraanzicht; kanteling 90° is het bovenaanzicht; een positieve rol draait het model met de klok mee.", "ui.view_angles_help": "Toont de stamp-, gier- en rolhoek van de weergave in graden en de projectie ervan onder de oriëntatiegizmo. Klik op de uitlezing om exacte hoeken in te typen.", + "ui.view_angles_lock": "{axis} vergrendelen", "ui.view_angles_ortho": "Ortho", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Kanteling", "ui.view_angles_readout": "Kanteling {pitch} · Gieren {yaw} · Rollen {roll}", "ui.view_angles_roll": "Rollen", + "ui.view_angles_unlock": "{axis} ontgrendelen", "ui.view_angles_yaw": "Gieren", + "ui.view_angles_zero": "{axis} instellen op 0°", "ui.view_centre": "Weergavemidden", "ui.viewport_status_clear": "{name} uitschakelen", "ui.viewport_status_clear_hint": "{name} uitschakelen · Esc", + "ui.viewport_status_edges": "{count} randen", + "ui.viewport_status_from": "vanaf {direction}", "ui.viewport_status_key": "Legenda tonen voor {name}", "ui.viewport_status_minimum_radius": "Minimale straal", "ui.viewport_status_pairs": "{count} paren", + "ui.viewport_status_section_hatch": "{setting} · arcering", + "ui.viewport_status_section_plane": "Huidig vlak", + "ui.viewport_status_section_tilted": "gekanteld · {offset}", "ui.viewport_status_stripes": "{count} strepen", + "ui.viewport_status_summary_clear": "Alles uitschakelen", + "ui.viewport_status_summary_heading": "In deze weergave", + "ui.viewport_status_summary_label": "{name} en {count} andere items", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Thema volgen", "ui.visual_shaded_hidden_edges": "Gearceerd met verborgen randen", "ui.visual_shaded_with_edges": "Gearceerd met randen", @@ -4638,10 +5242,12 @@ "update.button": "Bijwerken", "update.button_version": "Bijwerken naar {version}", "update.check_automatically": "Automatisch controleren op updates", + "update.check_for_updates": "Controleren op updates", "update.check_now": "Nu controleren", + "update.check_unavailable": "Controleren op updates is niet beschikbaar voor deze installatie.", "update.checking": "Controleren…", "update.copy": "Kopiëren", - "update.dmg_opened": "Het schijfkopie is geopend en geverifieerd: sleep SolidCraft naar Programma's, vervang de oude kopie en start SolidCraft daarna opnieuw.", + "update.dmg_opened": "Het schijfkopie is geopend en geverifieerd: stop SolidCraft, sleep de nieuwe SolidCraft naar Programma's, vervang de oude kopie en open SolidCraft daarna opnieuw.", "update.download": "Downloaden", "update.download_open": "Downloaden en openen", "update.downloading": "Downloaden en verifiëren… {done} van {total} MB", @@ -4652,11 +5258,13 @@ "update.installed": "SolidCraft {version} is geïnstalleerd. Start opnieuw om het te gebruiken.", "update.installer_started": "Het installatieprogramma start wanneer SolidCraft wordt gesloten.", "update.later": "Herinner me later", + "update.managed": "Update beschikbaar: werk SolidCraft bij in {manager}", "update.no_notes": "Deze release heeft geen notities.", "update.package_hint": "Deze kopie kwam van een {kind}. Download het nieuwe pakket en installeer het daarna met:", "update.prefs_dev": "Dit is een ontwikkelbuild ({version}): er wordt niet op updates gecontroleerd.", "update.prefs_flatpak": "Flatpak werkt deze kopie ({version}) bij: voer {command} uit of gebruik uw softwarecentrum. SolidCraft controleert niet.", "update.prefs_label": "Updates", + "update.prefs_managed": "Dit is SolidCraft {version}, beheerd door {manager}. Een controle vraagt GitHub om de nieuwste release en verzendt verder niets; werk SolidCraft bij in {manager}.", "update.prefs_note": "Dit is SolidCraft {version} ({kind}). Een controle vraagt GitHub om de nieuwste release en verzendt verder niets.", "update.prefs_web": "Laad de pagina opnieuw om de nieuwste web-app te krijgen. Als het netwerk niet beschikbaar is of de update niet op tijd kan worden gedownload, wordt de opgeslagen versie geopend; een download die bezig is, gaat door voor de volgende keer opnieuw laden.", "update.refresh_checking": "Zoeken naar de nieuwste release…", @@ -4683,6 +5291,7 @@ "web.open_link": "Gekoppeld ontwerp openen?", "web.open_link_confirm": "Er zijn niet-opgeslagen wijzigingen. Het gekoppelde ontwerp in een nieuw tabblad openen?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ kiezen · Enter / Tab aanvullen · Esc sluiten", + "↑ ↓ choose · Enter applies this value": "↑ ↓ kiezen · Enter past deze waarde toe", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ kiezen · Enter past toe wat je typte · Esc sluiten", "⌘Enter continues on GitHub.": "⌘Enter gaat verder op GitHub." } diff --git a/assets/locales/pending/viewport-analysis-status.json b/assets/locales/pending/viewport-analysis-status.json deleted file mode 100644 index 2625833df..000000000 --- a/assets/locales/pending/viewport-analysis-status.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "en": { - "prefs.viewport_analysis_status": "Show viewport analysis status", - "prefs.viewport_analysis_status_help": "Show active analyses above the viewport, open their legends from each item, and use Esc to turn off the newest analysis. Turn off to restore corner legends and the previous Esc behaviour.", - "ui.viewport_status_edges": "{count} edges", - "ui.viewport_status_from": "from {direction}" - }, - "ar": { - "prefs.viewport_analysis_status": "إظهار حالة التحليل في منفذ العرض", - "prefs.viewport_analysis_status_help": "عرض التحليلات النشطة أعلى منفذ العرض وفتح مفتاح كل تحليل من عنصره. ينهي Esc أحدث تحليل. أوقف الخيار لاستعادة المفاتيح في الزاوية وسلوك Esc السابق.", - "ui.viewport_status_edges": "{count} حواف", - "ui.viewport_status_from": "من {direction}" - }, - "de": { - "prefs.viewport_analysis_status": "Analysestatus im Ansichtsfenster anzeigen", - "prefs.viewport_analysis_status_help": "Zeigt aktive Analysen über dem Ansichtsfenster und ihre Legenden am jeweiligen Eintrag. Esc beendet die neueste Analyse. Ausschalten stellt Ecklegenden und das bisherige Esc-Verhalten wieder her.", - "ui.viewport_status_edges": "{count} Kanten", - "ui.viewport_status_from": "aus {direction}" - }, - "he": { - "prefs.viewport_analysis_status": "הצגת מצב ניתוח בחלון התצוגה", - "prefs.viewport_analysis_status_help": "הצגת ניתוחים פעילים מעל חלון התצוגה ופתיחת המקרא מכל פריט. Esc מכבה את הניתוח האחרון. כיבוי האפשרות משחזר את המקרא בפינה ואת פעולת Esc הקודמת.", - "ui.viewport_status_edges": "{count} קצוות", - "ui.viewport_status_from": "מכיוון {direction}" - }, - "ja": { - "prefs.viewport_analysis_status": "ビューポートの解析状態を表示", - "prefs.viewport_analysis_status_help": "有効な解析をビューポートの上部に表示し、各項目から凡例を開きます。Esc で最新の解析を解除します。無効にすると隅の凡例と従来の Esc 動作に戻ります。", - "ui.viewport_status_edges": "{count} エッジ", - "ui.viewport_status_from": "方向 {direction}" - }, - "ko": { - "prefs.viewport_analysis_status": "뷰포트 해석 상태 표시", - "prefs.viewport_analysis_status_help": "활성 해석을 뷰포트 위에 표시하고 각 항목에서 범례를 엽니다. Esc로 최신 해석을 끕니다. 끄면 모서리 범례와 이전 Esc 동작으로 돌아갑니다.", - "ui.viewport_status_edges": "모서리 {count}개", - "ui.viewport_status_from": "{direction} 방향에서" - }, - "vi": { - "prefs.viewport_analysis_status": "Hiện trạng thái phân tích trong khung nhìn", - "prefs.viewport_analysis_status_help": "Hiện các phân tích đang bật phía trên khung nhìn và mở chú giải từ từng mục. Esc tắt phân tích mới nhất. Tắt tùy chọn để khôi phục chú giải ở góc và hành vi Esc trước đây.", - "ui.viewport_status_edges": "{count} cạnh", - "ui.viewport_status_from": "từ {direction}" - }, - "zh": { - "prefs.viewport_analysis_status": "显示视口分析状态", - "prefs.viewport_analysis_status_help": "在视口上方显示启用的分析,从各项目打开图例,并按 Esc 关闭最近启用的分析。关闭此选项可恢复角落图例和原来的 Esc 行为。", - "ui.viewport_status_edges": "{count} 条边", - "ui.viewport_status_from": "从 {direction}" - } -} diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 61dead712..ff7a57e5d 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -1,11 +1,15 @@ { + "(active rule)": "(aktywna reguła)", "0 turns it off": "0 wyłącza", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Otwórz poniżej szkic zgłoszenia na GitHubie, a następnie wklej raport skopiowany do schowka.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Otwórz poniżej szkic zgłoszenia na GitHubie. Tytuł i raport zostaną wypełnione.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Dołącz zrzut ekranu: skopiuj go i wklej albo zapisz i prześlij plik PNG.", "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Kliknij Submit new issue na GitHubie, aby wysłać raport.", + "A Single hole snaps to the middle of its face and to the centres of its round edges": "Pojedynczy otwór przyciąga się do środka swojej ściany i do środków jej okrągłych krawędzi", "A new configuration, a copy of the active one": "Nowa konfiguracja, kopia aktywnej", + "A placed Single hole has a handle to drag it, and picking its face again moves the hole there instead of taking it out": "Umieszczony pojedynczy otwór ma uchwyt do przeciągania, a ponowne wybranie jego ściany przenosi tam otwór, zamiast go usuwać", + "A short title for the problem (optional)": "Krótki tytuł problemu (opcjonalnie)", "ARRANGE": "UKŁADANIE", "About SolidCraft": "O programie SolidCraft", "Acceleration": "Przyspieszenie", @@ -14,42 +18,70 @@ "Active": "Aktywne", "Active rule": "Aktywna reguła", "Add": "Dodaj", + "Add Column": "Dodaj kolumnę", "Add Key": "Dodaj klucz", "Add Mid Radius": "Dodaj promień środkowy", "Add Row": "Dodaj wiersz", + "Add a tool": "Dodaj narzędzie", + "Add all bodies": "Dodaj wszystkie bryły", + "Add bend": "Dodaj gięcie", "Add condition": "Dodaj warunek", "Add or edit rule": "Dodaj lub edytuj regułę", + "Add to New Folder": "Dodaj do nowego folderu", + "Add visible bodies": "Dodaj widoczne bryły", + "Advanced": "Zaawansowane", "Against": "Względem", "Alignment": "Wyrównanie", + "All Lines": "Wszystkie linie", "All Sketch Points": "Wszystkie punkty szkicu", "All components": "Wszystkie komponenty", "All open designs": "Wszystkie otwarte projekty", "Allowed expressions, separated by semicolons": "Dozwolone wyrażenia, rozdzielone średnikami", "Also deletes": "Usuwa również", "Also place them from the origin (fully constrained)": "Umieść je też względem początku (w pełni związane)", + "Anchor": "Kotwica", "Angle 2": "Kąt 2", + "Angle Display": "Wyświetlanie kąta", "Animate": "Animuj", + "Another bend on the far edge of the last flange": "Kolejne gięcie na dalszej krawędzi ostatniego kołnierza", "App/system information and command settings are included. Review private details before sharing.": "Dołączone są informacje o aplikacji i systemie oraz ustawienia poleceń. Przed udostępnieniem sprawdź, czy nie ma tam prywatnych danych.", "Appearance name": "Nazwa wyglądu", "Applied Radius": "Zastosowany promień", "Apply To": "Zastosuj do", + "Apply library appearance": "Zastosuj wygląd z biblioteki", "Apply to selection": "Zastosuj do zaznaczenia", "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Najpierw zastosuj wygląd. Eksportuje przypisane wyglądy i materiały utworzone w tym projekcie.", "Arc length": "Długość łuku", "Area": "Pole powierzchni", + "As Picked": "Jak wybrano", "As-Built": "W stanie zastanym", "Assign Rule": "Przypisz regułę", "Attachment": "Zaczepienie", "BLEND SURFACE": "POWIERZCHNIA PRZEJŚCIOWA", "BOUNDARY SURFACE": "POWIERZCHNIA Z KONTURU", "BROWSER": "PRZEGLĄDARKA", + "Ball": "Kuliste", + "Bar": "Pręt", + "Base Center": "Środek podstawy", + "Base Height": "Wysokość podstawy", + "Bend": "Gięcie", + "Bend Edges": "Krawędzie gięcia", + "Bend Line": "Linia gięcia", "Bend Line Position": "Położenie linii gięcia", "Bend Position": "Położenie gięcia", "Bend Radius": "Promień gięcia", "Bend Table": "Tabela gięć", "Bends": "Gięcia", "Bodies": "Bryły", + "Bodies (optional)": "Bryły (opcjonalnie)", "Body": "Bryła", + "Body (last if none)": "Bryła (ostatnia, jeśli nie wybrano)", + "Body to split": "Bryła do podziału", + "Body, or faces to take out": "Bryła lub ściany do usunięcia", + "Both": "Obie", + "Bottom Left": "Dół z lewej", + "Bottom Middle": "Dół pośrodku", + "Bottom Right": "Dół z prawej", "Boundary": "Kontur", "Bounding box": "Prostopadłościan otaczający", "CHECK": "SPRAWDZANIE", @@ -61,33 +93,48 @@ "CSV or JSON: updates existing parameters, adds new ones": "CSV lub JSON: aktualizuje istniejące parametry, dodaje nowe", "Capture All Positions": "Zapamiętaj wszystkie położenia", "Capture Pos.": "Zapamiętaj poł.", + "Catch Depth": "Głębokość zaczepu", "Catch Direction": "Kierunek zaczepu", + "Catch Length": "Długość zaczepu", "Cells": "Komórki", "Center X": "Środek X", "Center Y": "Środek Y", "Center of mass": "Środek masy", "Centre to centre": "Od środka do środka", + "Centroid": "Środek ciężkości", "Chamfer Type": "Typ fazy", + "Channel": "Ceownik", "Check collisions": "Sprawdzaj kolizje", "Checked": "Sprawdzono", + "Choose Variable radius or Spline in Type.": "Wybierz w polu Typ opcję Zmienny promień lub Splajn.", "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Wybierz nową płaszczyznę. Geometria i wymiary szkicu pozostają niezmienione w jego dwuwymiarowych współrzędnych.", "Choose…": "Wybierz…", + "Circle center": "Środek okręgu", + "Circle or sphere": "Okrąg lub sfera", "Circular": "Kołowy", "Circumference": "Obwód", "Clockwise": "Zgodnie z ruchem wskazówek zegara", "Close draft": "Zamknij szkic zgłoszenia", + "Collapse": "Zwiń", "Collisions": "Kolizje", "Colour": "Kolor", + "Command": "Polecenie", "Comment": "Komentarz", + "Component 1": "Komponent 1", + "Component 2": "Komponent 2", "Component1": "Komponent1", + "Components": "Komponenty", "Config Table": "Tabela konfiguracji", "Configuration": "Konfiguracja", "Configuration rules": "Reguły konfiguracji", + "Constant radius": "Stały promień", "Contact": "Kontakt", "Contact Sets": "Zestawy kontaktów", "Contact sets": "Zestawy kontaktów", "Continue on GitHub": "Kontynuuj na GitHubie", "Continuity": "Ciągłość", + "Control Radius": "Promień kontrolny", + "Copies the definition only. Assign it from Physical Material when ready.": "Kopiuje tylko definicję. Gdy będzie gotowa, przypisz ją przez Materiał fizyczny.", "Copy Error Message": "Kopiuj komunikat błędu", "Copy Warning Message": "Kopiuj komunikat ostrzeżenia", "Copy all licences": "Kopiuj wszystkie licencje", @@ -96,19 +143,33 @@ "Copy screenshot": "Kopiuj zrzut ekranu", "Corner Relief": "Odciążenie naroża", "Corner Relief Shape": "Kształt odciążenia naroża", + "Corner radius": "Promień naroża", "Counterbore depth": "Głębokość pogłębienia walcowego", + "Counterbore Ø": "Ø pogłębienia walcowego", "Countersink angle": "Kąt pogłębienia stożkowego", + "Countersink Ø": "Ø pogłębienia stożkowego", + "Create Hole": "Utwórz otwór", "Create Issue — review draft": "Utwórz zgłoszenie — sprawdź szkic", + "Create Issue…": "Utwórz zgłoszenie…", "Cross curves": "Krzywe poprzeczne", + "Ctrl+Enter continues on GitHub.": "Ctrl+Enter przechodzi dalej na GitHubie.", "Cube": "Sześcian", "Current orthographic view (1:1 mm)": "Bieżący widok ortogonalny (1:1 mm)", "Current perspective view": "Bieżący widok perspektywiczny", + "Current plane": "Bieżąca płaszczyzna", "Curv. Comb": "Grzebień krzyw.", "Curvature (G2)": "Krzywizna (G2)", "Curvature change (G3)": "Zmiana krzywizny (G3)", "Custom": "Niestandardowy", "Customize Toolbar": "Dostosuj pasek narzędzi", + "Customize…": "Dostosuj…", + "Cylindrical": "Walcowe", + "Cylindrical face": "Ściana walcowa", + "Deboss": "Wgłębienie", "Delete": "Usuń", + "Delete Folders and Features…": "Usuń foldery i funkcje…", + "Delete Selected Features…": "Usuń zaznaczone funkcje…", + "Delete Selected Folders": "Usuń zaznaczone foldery", "Delete all": "Usuń wszystko", "Delete rule": "Usuń regułę", "Delete the row": "Usuń wiersz", @@ -119,14 +180,20 @@ "Describe what happened before continuing.": "Zanim przejdziesz dalej, opisz, co się stało.", "Designs you open or save appear here.": "Tutaj pojawiają się otwierane lub zapisywane projekty.", "Determined by To Object. Choose Angle to edit the angular extent.": "Wynika z opcji Do obiektu. Wybierz Kąt, aby edytować zakres kątowy.", + "Diameter": "Średnica", + "Did this assembly open the wrong way up?": "Czy to złożenie otworzyło się odwrócone?", + "Did this part open the wrong way up?": "Czy ta część otworzyła się odwrócona?", "Dimension new shapes": "Wymiaruj nowe kształty", "Direction": "Kierunek", "Discard": "Odrzuć", + "Distance": "Odległość", + "Distance 1": "Odległość 1", "Do not export hidden edges": "Nie eksportuj krawędzi niewidocznych", "Don't ask again": "Nie pytaj ponownie", "Double-click to rename": "Kliknij dwukrotnie, aby zmienić nazwę", "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Dwukrotne kliknięcie środkowym przyciskiem w widoku: Widok główny (kadruje to, co widoczne), Dopasuj (kadruje to, co widoczne, zachowując orientację) lub nic", "Drag to move the boss across the model. It snaps to sketch points on the face.": "Przeciągnij, aby przesunąć występ po modelu. Przyciąga się do punktów szkicu na ścianie.", + "Drag to move the hole; click to remove it": "Przeciągnij, aby przesunąć otwór; kliknij, aby go usunąć", "Drag to move the rest across the model. It snaps to sketch points on the face.": "Przeciągnij, aby przesunąć podparcie po modelu. Przyciąga się do punktów szkicu na ścianie.", "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "Przeciągnij, aby przesunąć zatrzask po modelu. Przyciąga się do punktów szkicu na ścianie.", "Drag to point the catch in another direction.": "Przeciągnij, aby skierować zaczep w inną stronę.", @@ -135,87 +202,149 @@ "Duration": "Czas trwania", "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Każdy nowy kształt otrzymuje też wymiary od początku szkicu, aż nic nie pozostanie swobodne. Kształt już połączony z początkiem lub z umieszczoną geometrią nie otrzymuje żadnych.", "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Każdy narysowany kształt otrzymuje wszystkie swoje wymiary w narysowanych rozmiarach (wpisane wartości mają pierwszeństwo). Rozmiar, który szkic już określa, jest pomijany.", + "Edge": "Krawędź", "Edges": "Krawędzie", "Edit": "Edytuj", "Edit Profile Sketch": "Edytuj szkic profilu", + "Edit shortcuts": "Edytuj skróty", "Enable rule": "Włącz regułę", "Enabled": "Włączone", + "End Radius": "Promień końcowy", "End bulge": "Wybrzuszenie końca", "End continuity": "Ciągłość końca", + "Equal Distance": "Równa odległość", + "Expand": "Rozwiń", "Expected result (optional)": "Oczekiwany wynik (opcjonalnie)", "Explode": "Rozstrzel", "Explode Text": "Rozbij tekst", "Export Animation…": "Eksportuj animację…", + "Export Bend Table…": "Eksportuj tabelę gięć…", "Export CSV…": "Eksportuj CSV…", "Export Current View as DXF": "Eksportuj bieżący widok jako DXF", "Export Current View as DXF…": "Eksportuj bieżący widok jako DXF…", "Export DXF": "Eksportuj DXF", "Export DXF…": "Eksportuj DXF…", "Export JSON…": "Eksportuj JSON…", + "Export design library...": "Eksportuj bibliotekę projektu...", "Export hidden edges as dashed lines": "Eksportuj krawędzie niewidoczne jako linie kreskowe", + "Exported by SolidWorks, which usually saves Y up": "Wyeksportowano z SolidWorks, który zwykle zapisuje z osią Y w górę", "Expression": "Wyrażenie", "Extend to meet": "Wydłuż do spotkania", "Extents": "Zakres", "FILES": "PLIKI", "FLAT": "ROZWINIĘCIE", "Face": "Ściana", + "Face Appearance": "Wygląd ściany", "Face attachment lost": "Utracono zaczepienie do ściany", + "Face center": "Środek ściany", "Faces": "Ściany", "Faces / edges / vertices": "Ściany / krawędzie / wierzchołki", + "Faces to split": "Ściany do podziału", + "Faces/Body": "Ściany/bryła", + "Factor must be a positive number": "Współczynnik musi być liczbą dodatnią", "Fastener": "Element złączny", "Favorites": "Ulubione", "Favourite": "Ulubione", "Feature": "Funkcja", "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Pliki z wielu programów CAD mają oś Y skierowaną w górę, więc otwierają się tutaj leżąc na plecach (oś Z w górę).", "Filter": "Filtr", + "Filter…": "Filtr…", "Find in Browser": "Znajdź w przeglądarce", "Finish": "Wykończenie", + "First edge": "Pierwsza krawędź", + "First plane": "Pierwsza płaszczyzna", + "First point": "Pierwszy punkt", + "Fit and G2 corners require Constant radius.": "Dopasowanie i naroża G2 wymagają stałego promienia.", + "Fixed Face": "Ściana stała", + "Flange Gap": "Szczelina kołnierza", + "Flange thickness": "Grubość półki", + "Flanges": "Kołnierze", "Flat Pattern": "Rozwinięcie", "Flat size": "Wymiary rozwinięcia", + "Flat size X": "Wymiar rozwinięcia X", + "Flat size Y": "Wymiar rozwinięcia Y", "Follow camera (Look At sketches)": "Podążaj za kamerą (Patrz na szkice)", "Follow the camera (Look At sketches)": "Podążaj za kamerą (Patrz na szkice)", "Font": "Czcionka", + "Free Move": "Swobodne przesuwanie", + "From": "Od", "From Bodies": "Z brył", + "From Snap": "Od punktu przyciągania", "From edges": "Z krawędzi", "Full Length": "Pełna długość", + "Full thread depth": "Głębokość pełnego gwintu", + "Further Bends": "Kolejne gięcia", + "G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "Naroża G2 wymagają stałego promienia i dopasowania Dokładne. Tworzenie naroży G2 nie jest jeszcze obsługiwane.", "Gap": "Szczelina", "Grid": "Siatka", "HISTORY": "HISTORIA", + "Halo under sketch curves": "Obwódka pod krzywymi szkicu", "Height": "Wysokość", + "Height From": "Wysokość od", + "Hem Gap": "Szczelina zawinięcia", "Hidden edges": "Krawędzie niewidoczne", "History layout": "Układ historii", "History names": "Nazwy w historii", + "Hole (optional)": "Otwór (opcjonalnie)", + "Hole Depth": "Głębokość otworu", + "Hole Diameter": "Średnica otworu", "Holes": "Otwory", "Holes (edges on them)": "Otwory (krawędzie na nich)", "Home view": "Widok główny", "Horiz./Vert.": "Poz./Pion.", + "I-Beam": "Dwuteownik", "IMAGES": "OBRAZY", + "If you are offline or GitHub does not open, use Copy report and keep the text to submit later.": "Jeśli jesteś offline lub GitHub się nie otwiera, użyj Kopiuj raport i zachowaj tekst, aby wysłać go później.", + "Import material into design": "Importuj materiał do projektu", "Import…": "Importuj…", "In This Design": "W tym projekcie", "In place (surfaces)": "W miejscu (powierzchnie)", "In plane": "W płaszczyźnie", + "Included": "Uwzględnione", + "Inner Sharp": "Ostre wewnętrzne", "Inside": "Wewnątrz", + "Instant": "Natychmiast", + "Interface font": "Czcionka interfejsu", "Interferes": "Koliduje", + "Invert": "Odwróć", "Isocurve": "Izokrzywa", "Issue title": "Tytuł zgłoszenia", + "Items": "Elementy", "JOINTS": "ZŁĄCZA", + "Joint 1": "Złącze 1", + "Joint 2": "Złącze 2", "Joint Origin1": "Początek złącza1", + "K Factor": "Współczynnik K", "Keep (points on it)": "Zachowaj (punkty na niej)", "Keep Tools": "Zachowaj narzędzia", "Keep of the other surface": "Zachowaj z drugiej powierzchni", + "Key a joint's value at this step": "Zapisz klucz wartości złącza w tym kroku", + "Keys": "Klucze", + "Knife Edge": "Ostrze", + "L-Angle": "Kątownik", "LIBRARY": "BIBLIOTEKA", "LINKS": "ŁĄCZA", "Later": "Później", "Leave it": "Zostaw", + "Left Middle": "Lewo pośrodku", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Starsze zaczepienie do ściany. Ponowne powiązanie z certyfikowaną ścianą tworzy dokładne zaczepienie.", "Length": "Długość", "Length units": "Jednostki długości", "Letter Spacing": "Odstęp między literami", "Library": "Biblioteka", "Library file": "Plik biblioteki", + "Library response is missing": "Brak odpowiedzi biblioteki", + "Limits": "Limity", "Line Spacing": "Odstęp między wierszami", + "Line Type": "Rodzaj linii", + "Line on plane": "Linia na płaszczyźnie", + "Lines": "Linie", + "Listing the installed fonts…": "Wyszukiwanie zainstalowanych czcionek…", + "Load library": "Wczytaj bibliotekę", "Local library": "Biblioteka lokalna", "Loop": "Pętla", + "M5 or M5x0.5": "M5 lub M5x0.5", + "M5, M5x0.5, 1/4-20 UNC": "M5, M5x0.5, 1/4-20 UNC", "MANAGE": "ZARZĄDZANIE", "MATERIALS": "MATERIAŁY", "MODEL": "MODEL", @@ -225,23 +354,37 @@ "Mass Center": "Środek masy", "Matched restrictions check the final values.": "Ograniczenia, których warunki są spełnione, sprawdzają wartości końcowe.", "Material": "Materiał", + "Material Outside": "Materiał na zewnątrz", + "Material copied. Existing body assignments are unchanged.": "Skopiowano materiał. Istniejące przypisania do brył pozostają bez zmian.", "Max": "Maks.", + "Max Thickness": "Maks. grubość", + "Maximum": "Maksimum", + "Mesh body": "Bryła siatkowa", "Mid Radius": "Promień środkowy", "Middle double-click": "Dwukrotne kliknięcie środkowym", "Min": "Min.", + "Min Draft": "Min. pochylenie", + "Min Thickness": "Min. grubość", + "Minimum": "Minimum", + "Mirror Plane": "Płaszczyzna odbicia", "Mitre": "Ukos", "Model Parameters": "Parametry modelu", "Modeled": "Wymodelowane", "More toolbar panels": "Więcej paneli paska narzędzi", "Motion": "Ruch", + "Mouse gestures": "Gesty myszy", + "Mouse gestures only work with the SolidWorks mouse mode (the wheel orbits, Ctrl + wheel pans).": "Gesty myszy działają tylko w trybie myszy SolidWorks (kółko obraca widok, Ctrl + kółko przesuwa).", "Move / Copy": "Przesuń / Kopiuj", "Move Type": "Typ przesunięcia", "Move down": "Przenieś w dół", "Move earlier": "Przesuń wcześniej", + "Move holes by clicking or dragging": "Przesuwaj otwory kliknięciem lub przeciąganiem", "Move later": "Przesuń później", "Move up": "Przenieś w górę", "Name": "Nazwa", + "Name on import": "Nazwa przy imporcie", "Nearest": "Najbliższy", + "Neutral plane": "Płaszczyzna neutralna", "New": "Nowy", "New Comp.": "Nowy komp.", "New Sketch": "Nowy szkic", @@ -250,68 +393,110 @@ "No crash reports.": "Brak raportów o awariach.", "No matching appearance presets.": "Brak pasujących ustawień wyglądu.", "No matching appearances": "Brak pasujących wyglądów", + "No matching physical materials.": "Brak pasujących materiałów fizycznych.", "No visible bodies or sketches to export.": "Brak widocznych brył lub szkiców do wyeksportowania.", + "Nominal Radius": "Promień nominalny", "Nominal diameter": "Średnica nominalna", "None": "Brak", "Not available yet": "Jeszcze niedostępne", + "Not saved yet": "Jeszcze nie zapisano", "Notch": "Wycięcie", "OUTPUT": "WYJŚCIE", + "Of": "Obiekt", + "On your computer": "Na tym komputerze", "Opacity": "Nieprzezroczystość", + "Open GitHub": "Otwórz GitHub", "Open GitHub draft": "Otwórz szkic zgłoszenia na GitHubie", + "Open GitHub issue form": "Otwórz formularz zgłoszenia na GitHubie", + "Open bodies (no volume)": "Bryły otwarte (bez objętości)", + "Open library...": "Otwórz bibliotekę...", "Open local libraries in the desktop app. You can export this design's library here.": "Otwórz biblioteki lokalne w aplikacji komputerowej. Tutaj możesz wyeksportować bibliotekę tego projektu.", + "Open surface — no volume": "Powierzchnia otwarta — bez objętości", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Otwartoźródłowy parametryczny CAD 3D w języku Rust. Licencja MIT OR Apache-2.0.", "Opens your browser and copies the report text for you to paste into GitHub.": "Otwiera przeglądarkę internetową i kopiuje treść raportu, którą wkleisz na GitHubie.", + "Opens your browser and copies the report text. Review and submit your report on GitHub.": "Otwiera przeglądarkę internetową i kopiuje treść raportu. Sprawdź raport i wyślij go na GitHubie.", "Opens your browser. Review and submit your report on GitHub.": "Otwiera przeglądarkę internetową. Sprawdź raport i wyślij go na GitHubie.", "Operator": "Operator", "Orbit (right drag)": "Obracanie widoku (przeciąganie prawym przyciskiem)", "Other side": "Druga strona", "Other surface (mutual trim)": "Druga powierzchnia (wzajemne przycięcie)", + "Other way": "W drugą stronę", + "Outer Sharp": "Ostre zewnętrzne", + "Outer radius": "Promień zewnętrzny", "Outside": "Na zewnątrz", "Overall length": "Długość całkowita", "Param. Graph": "Wykres param.", "Parameter": "Parametr", + "Part length must be greater than zero and at most 2000 mm": "Długość części musi być większa od zera i nie większa niż 2000 mm", "Parts": "Części", "Pass through": "Przechodzi przez", "Path": "Ścieżka", "Pattern": "Szyk", "Per Edge": "Dla każdej krawędzi", + "Physical material definitions": "Definicje materiałów fizycznych", + "Pick a part size": "Wybierz rozmiar części", "Pick the tool bodies": "Wybierz bryły narzędziowe", "Picked": "Wybrane", "Picked point": "Wybrany punkt", + "Pin-slot": "Sworzeń w rowku", "Pitch": "Skok", + "Pivot": "Punkt obrotu", "Place at the origin instead": "Zamiast tego umieść w początku układu", + "Planar": "Płaskie", "Plastic Rules": "Reguły tworzyw", + "Play the joint's motion in the view": "Odtwórz ruch złącza w widoku", "Playback": "Odtwarzanie", "Plot": "Wykres", + "Point on line": "Punkt na linii", + "Point on plane": "Punkt na płaszczyźnie", "Position": "Położenie", "Position (0 to 1)": "Położenie (od 0 do 1)", "Position (G0)": "Położenie (G0)", "Position along the edge, 0 at the start end, 1 at the other": "Położenie wzdłuż krawędzi: 0 na jej początku, 1 na drugim końcu", "Preferences › Design turns the offer back on": "Preferencje › Projekt ponownie włącza tę propozycję", + "Preview": "Podgląd", "Preview Row": "Podgląd wiersza", "Preview leaves the current design unchanged.": "Podgląd nie zmienia bieżącego projektu.", + "Profile / Edges": "Profil / krawędzie", + "Profiles or curves": "Profile lub krzywe", "Profiles/Curves": "Profile/krzywe", "Quantity": "Liczba", + "Quantity must be at least 2": "Liczba musi wynosić co najmniej 2", "RECENT": "OSTATNIE", "REFERENCE": "ODNIESIENIE", "RULED SURFACE": "POWIERZCHNIA PROSTOKREŚLNA", "RULES": "REGUŁY", + "Radius": "Promień", "Radius Fit": "Dopasowanie promienia", "Ratio": "Stosunek", + "Read-only list: shortcuts can't be changed here.": "Lista tylko do odczytu: tutaj nie można zmieniać skrótów.", "Reattach selected face": "Ponownie zaczep wybraną ścianę", "Recover": "Odzyskaj", "Recover unsaved design?": "Odzyskać niezapisany projekt?", "Rectangular": "Prostokątny", + "Rectangular Tube": "Profil prostokątny zamknięty", "Reference face": "Ściana odniesienia", + "Relief Depth": "Głębokość odciążenia", + "Relief Width": "Szerokość odciążenia", "Remove Tools": "Usuń narzędzia", + "Remove condition": "Usuń warunek", + "Remove from Folder": "Usuń z folderu", "Remove from list": "Usuń z listy", "Remove override": "Usuń nadpisanie", "Remove private design details or paths before sharing.": "Przed udostępnieniem usuń prywatne szczegóły projektu i ścieżki.", "Remove screenshot": "Usuń zrzut ekranu", "Remove the column": "Usuń kolumnę", "Remove the track": "Usuń ścieżkę", + "Remove this bend": "Usuń to gięcie", "Remove this point": "Usuń ten punkt", + "Rename Feature": "Zmień nazwę funkcji", + "Rename Folder": "Zmień nazwę folderu", + "Render Stage": "Scenografia renderowania", + "Reopen designs": "Otwieraj ponownie projekty", + "Reopen the designs that were open when SolidCraft was last closed": "Otwieraj ponownie projekty, które były otwarte przy ostatnim zamknięciu SolidCraft", + "Replace existing library file": "Zastąp istniejący plik biblioteki", "Report a bug — review a screenshot and open a GitHub draft": "Zgłoś błąd — sprawdź zrzut ekranu i otwórz szkic zgłoszenia na GitHubie", + "Report copied. Keep this text to submit on GitHub when you are online.": "Skopiowano raport. Zachowaj ten tekst, aby wysłać go na GitHubie, gdy będziesz online.", "Report text copied. Paste it into GitHub and submit your report there.": "Skopiowano treść raportu. Wklej ją na GitHubie i tam wyślij raport.", "Reports are public. A GitHub account is required.": "Raporty są publiczne. Wymagane jest konto GitHub.", "Reset Toolbar": "Przywróć pasek narzędzi", @@ -319,8 +504,10 @@ "Restore View": "Przywróć widok", "Restore outer boundary": "Przywróć kontur zewnętrzny", "Restore the inherited component or physical material appearance": "Przywróć wygląd odziedziczony z komponentu lub materiału fizycznego", + "Restore this studio's tools": "Przywróć narzędzia tego studia", "Result": "Wynik", "Retake screenshot": "Ponów zrzut ekranu", + "Reveal Height": "Wysokość odsłonięcia", "Reverse": "Odwróć", "Reverse Direction": "Odwróć kierunek", "Revert": "Przywróć", @@ -329,14 +516,28 @@ "Revert Position": "Przywróć położenie", "Review the report and screenshot before opening GitHub.": "Przed otwarciem GitHuba sprawdź raport i zrzut ekranu.", "Review your report on GitHub and click Submit new issue to publish it.": "Sprawdź raport na GitHubie i kliknij Submit new issue, aby go opublikować.", + "Revolute": "Obrotowe", + "Rib Length": "Długość żebra", + "Rib Offset": "Odsunięcie żebra", + "Rib Thickness": "Grubość żebra", + "Ribs": "Żebra", + "Right Middle": "Prawo pośrodku", + "Rigid": "Sztywne", "Rim Edge": "Krawędź obrzeża", + "Rim face": "Ściana obrzeża", + "Ring of tools on the right button": "Pierścień narzędzi pod prawym przyciskiem", + "Roll Back Here": "Cofnij tutaj", "Roll History Marker Here": "Przesuń tutaj znacznik historii", + "Root radius": "Promień u nasady", "Round": "Okrągłe", + "Round Bar": "Pręt okrągły", + "Round Tube": "Rura okrągła", "Rule": "Reguła", "Rule name": "Nazwa reguły", "Rules run from top to bottom. Matched drives change effective values.": "Reguły są wykonywane od góry do dołu. Reguły sterujące, których warunki są spełnione, zmieniają wartości efektywne.", "SECTION": "PRZEKRÓJ", "SURFACE QUALITY": "JAKOŚĆ POWIERZCHNI", + "Same way": "W tę samą stronę", "Save Rule": "Zapisz regułę", "Save View": "Zapisz widok", "Save screenshot…": "Zapisz zrzut ekranu…", @@ -348,17 +549,36 @@ "Search": "Szukaj", "Search commands": "Szukaj poleceń", "Search this library": "Przeszukaj tę bibliotekę", + "Second edge": "Druga krawędź", + "Second plane": "Druga płaszczyzna", + "Second point": "Drugi punkt", "Section": "Przekrój", + "Section (optional)": "Przekrój (opcjonalnie)", "Section position": "Położenie przekroju", + "Sections (one sketch each)": "Przekroje (każdy w osobnym szkicu)", + "Select Other": "Wybierz inny", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Wybierz inny: przytrzymaj nieruchomo lewy przycisk na modelu (lub prawy przycisk › Wybierz inny…), aby wyświetlić wszystko pod kursorem; kliknij ponownie w tym samym miejscu, aby zaznaczyć kolejny obiekt. Dwukrotne kliknięcie środkowym przyciskiem przechodzi do widoku głównego (Preferencje › Nawigacja).", + "Select Same Look": "Zaznacz o tym samym wyglądzie", "Select bodies (a face picks its body)": "Zaznacz bryły (ściana wybiera swoją bryłę)", "Select bodies or faces instead": "Zamiast tego zaznacz bryły lub ściany", + "Select edges": "Zaznacz krawędzie", + "Select points of the sketch being edited": "Zaznacz punkty edytowanego szkicu", + "Select the centre the pattern turns around first": "Najpierw zaznacz środek, wokół którego obraca się szyk", + "Select the curves to offset first": "Najpierw zaznacz krzywe do odsunięcia", + "Select the mirror line": "Zaznacz linię odbicia", + "Select the sketch curves or points to mirror first": "Najpierw zaznacz krzywe lub punkty szkicu do odbicia", + "Select the sketch curves or points to move first": "Najpierw zaznacz krzywe lub punkty szkicu do przesunięcia", + "Select the sketch curves or points to pattern first": "Najpierw zaznacz krzywe lub punkty szkicu do szyku", + "Select the sketch curves or points to scale first": "Najpierw zaznacz krzywe lub punkty szkicu do skalowania", + "Select the sketch curves or points to transform first": "Najpierw zaznacz krzywe lub punkty szkicu do przekształcenia", "Selection filter": "Filtr zaznaczania", "Semantic faces share their appearance across instances.": "Ściany semantyczne współdzielą wygląd między wystąpieniami.", "Send your report on GitHub": "Wyślij raport na GitHubie", + "Shaded": "Cieniowany", "Shape": "Kształt", "Sheet Rules": "Reguły blach", "Show Agent Cursor": "Pokaż kursor agenta", + "Show ghost": "Pokaż widmo", "Show in folder": "Pokaż w folderze", "Show the pointer an AI agent moves (#35)": "Pokaż wskaźnik poruszany przez agenta AI (#35)", "Show tool at cursor": "Pokaż narzędzie przy kursorze", @@ -370,64 +590,108 @@ "Sketch geometry and profiles": "Geometria i profile szkicu", "Sketch plane has no body-face attachment.": "Płaszczyzna szkicu nie ma zaczepienia do ściany bryły.", "Sketch points": "Punkty szkicu", + "Slider": "Przesuwne", "Slot width": "Szerokość rowka", + "Snap to face and edge centres": "Przyciągaj do środków ścian i krawędzi", + "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft nie może wysyłać raportów bezpośrednio. Wyślij je na GitHubie; aplikacja nie potrzebuje do tego tokenu.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft zamknął się, zanim te projekty zostały zapisane. Można otworzyć ich ostatni autozapis.", + "Spacing 2 must be a non-zero number": "Odstęp 2 musi być liczbą różną od zera", + "Spacing must be a non-zero number": "Odstęp musi być liczbą różną od zera", "Specialise": "Uszczegółów", "Speed": "Prędkość", + "Splitting tool": "Narzędzie podziału", "Square": "Kwadrat", "Stand it up": "Postaw", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Postaw: obrót o ćwierć obrotu wokół osi X, jako jedna funkcja Przesuń, którą można cofnąć.", + "Stand this assembly up?": "Postawić to złożenie?", "Stand this part up?": "Postawić tę część?", "Start angle": "Kąt początkowy", "Start bulge": "Wybrzuszenie początku", "Start continuity": "Ciągłość początku", + "Stationary Side": "Strona nieruchoma", "Step": "Krok", "Steps": "Kroki", "Steps to reproduce (optional)": "Kroki do odtworzenia (opcjonalnie)", "Stitch the kept pieces": "Zszyj zachowane części", "Stitch to both bodies": "Zszyj z obiema bryłami", + "Studio": "Studio", "Study": "Badanie", "Style": "Styl", "Summary": "Podsumowanie", + "Suppress": "Wygaś", + "Suppress Selected Folders": "Wygaś zaznaczone foldery", "Suppressed": "Wygaszone", "Surface": "Powierzchnia", + "Surface, or faces to turn over": "Powierzchnia lub ściany do odwrócenia", + "Surfaces": "Powierzchnie", "Swap Ends": "Zamień końce", "TRIM": "PRZYCINANIE", + "Tangent": "Styczność", "Tangent (G1)": "Styczność (G1)", "Tangent Chain": "Łańcuch styczny", + "Tangent chain": "Łańcuch styczny", + "Tangent to Edge": "Styczna do krawędzi", "Tap drill diameter": "Średnica wiertła pod gwint", + "Target": "Cel", + "Target Body": "Bryła docelowa", + "Target Face (optional)": "Ściana docelowa (opcjonalnie)", "Tear": "Rozdarcie", "Technical details": "Szczegóły techniczne", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Przerywany szkic to zapisana płaszczyzna pomocnicza. Wybierz nową ścianę, aby naprawić zaczepienie.", + "The design changed. Reopen Change Part Size for the component.": "Projekt się zmienił. Otwórz ponownie Zmień rozmiar części dla tego komponentu.", + "The direction must be an axis or a straight sketch curve that lies in the sketch plane": "Kierunek musi być osią lub prostą krzywą szkicu leżącą w płaszczyźnie szkicu", + "The mirror line cannot also be mirrored": "Linia odbicia nie może być jednocześnie odbijana", + "The mirror line must be a straight curve of this sketch, not an origin axis": "Linia odbicia musi być prostą krzywą tego szkicu, a nie osią początku układu", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Brak zapisanego wystąpienia autora. Przed ponownym powiązaniem wybierz prawidłowe położenie autora.", "Then": "Wtedy", "These features will be deleted:": "Te funkcje zostaną usunięte:", "These features will fail:": "Te funkcje się nie powiodą:", "Thickness Outside": "Grubość na zewnątrz", + "Thickness Variation": "Zmienność grubości", "Thin": "Cienkościenne", "Thin Extrude": "Wyciągnięcie cienkościenne", + "Third plane": "Trzecia płaszczyzna", + "Third point": "Trzeci punkt", "This child is shared. Deleting it removes it from every copy of its parent.": "Ten element podrzędny jest współdzielony. Usunięcie go usuwa go z każdej kopii elementu nadrzędnego.", "This child is shared. Position changes apply to every copy of its parent.": "Ten element podrzędny jest współdzielony. Zmiany położenia dotyczą każdej kopii elementu nadrzędnego.", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "Ten komponent jest w podzłożeniu umieszczonym więcej niż raz: wyrównanie przesuwa go w każdym umiejscowieniu.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Ta ściana nie zapewnia trwałego zaczepienia. Wybierz inną ścianę lub jawnie użyj stałej płaszczyzny.", "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "Ten obraz nie jest jeszcze dołączony na GitHubie. Skopiuj go lub zapisz, a potem dołącz na GitHubie.", + "Thread depth": "Głębokość gwintu", + "Thread diameter": "Średnica gwintu", + "Through point": "Przez punkt", + "To": "Do", "To Offset": "Do odsunięcia", + "To Snap": "Do punktu przyciągania", "To edges": "Do krawędzi", + "Toe radius": "Promień na końcu półki", "Tolerance": "Tolerancja", "Too close": "Zbyt blisko", + "Tool Bodies": "Bryły narzędziowe", + "Tools": "Narzędzia", + "Tools, clockwise from the top": "Narzędzia, zgodnie z ruchem wskazówek zegara od góry", + "Top Left": "Góra z lewej", + "Top Middle": "Góra pośrodku", + "Top Right": "Góra z prawej", "Trimming tool (plane, face or curves)": "Narzędzie przycinające (płaszczyzna, ściana lub krzywe)", "Turn off section analysis before exporting the view.": "Przed eksportem widoku wyłącz analizę przekroju.", "Type": "Typ", + "Type a distance or an angle to move by": "Wpisz odległość lub kąt przesunięcia", "UNTRIM": "COFNIJ PRZYCIĘCIE", "Unit": "Jednostka", + "Unsuppress": "Przywróć wygaszone", + "Unsuppress Selected Folders": "Przywróć wygaszone zaznaczone foldery", "Updating the preview": "Aktualizowanie podglądu", "Use active author placement": "Użyj aktywnego położenia autora", "Use fixed plane": "Użyj stałej płaszczyzny", "Use saved fixed plane": "Użyj zapisanej stałej płaszczyzny", "Use selected face as fixed plane": "Użyj wybranej ściany jako stałej płaszczyzny", + "Use the SolidWorks mouse mode": "Użyj trybu myszy SolidWorks", "User Parameters": "Parametry użytkownika", "VIEW": "WIDOK", "VIEWS": "WIDOKI", "Value": "Wartość", + "Variable Radius": "Zmienny promień", "Velocity": "Prędkość", "Vertices": "Wierzchołki", "View navigator": "Nawigator widoku", @@ -435,21 +699,48 @@ "Wall": "Ścianka", "Wall Location": "Położenie ścianki", "Wall Thickness": "Grubość ścianki", + "Web thickness": "Grubość środnika", "What did you do just before the problem? A short list is enough": "Co robiłeś tuż przed wystąpieniem problemu? Wystarczy krótka lista", "What did you expect to see?": "Czego się spodziewałeś?", "What happened?": "Co się stało?", "When": "Gdy", "Width": "Szerokość", "Will fail": "Nie powiedzie się", + "With gestures on, the right button no longer orbits the view: hold it and move to open the ring, then touch a tool's zone. A plain right-click still opens the menu.": "Gdy gesty są włączone, prawy przycisk nie obraca już widoku: przytrzymaj go i porusz myszą, aby otworzyć pierścień, a potem najedź na strefę narzędzia. Zwykłe kliknięcie prawym nadal otwiera menu.", + "X": "X", + "X Angle": "Kąt X", "X angle": "Kąt X", "X distance": "Odległość X", + "Y": "Y", + "Y Angle": "Kąt Y", "Y angle": "Kąt Y", "Y distance": "Odległość Y", + "Z": "Z", + "Z Angle": "Kąt Z", + "Z Distance": "Odległość Z", "Z angle": "Kąt Z", "Z distance": "Odległość Z", "Zebra": "Zebra", + "`joint` must be an id or a name": "`joint` musi być identyfikatorem lub nazwą", + "`params` must be an object": "`params` musi być obiektem", + "`values` must be a list": "`values` musi być listą", + "a chamfer needs a corner of exactly two lines": "faza wymaga naroża z dokładnie dwóch linii", + "a file operation is in progress": "trwa operacja na pliku", + "a picked curve is no longer in a sketch": "wybrana krzywa nie należy już do szkicu", + "a picked curve's sketch has not been solved": "szkic wybranej krzywej nie został rozwiązany", + "a picked edge has no points": "wybrana krawędź nie ma punktów", + "a picked edge is gone": "wybrana krawędź już nie istnieje", + "a picked edge's body is gone": "bryła wybranej krawędzi już nie istnieje", + "add a key for a joint first": "najpierw dodaj klucz dla złącza", + "ai.connected_toast": "SolidCraft jest teraz dostępny w: {clients}. Uruchom je ponownie, aby go używać (Preferencje > Asystent).", + "ai.prefs.allow_control": "Pozwól agentom AI się łączyć (kanał sterowania / MCP)", + "ai.prefs.allow_control_note": "Otwiera kanał sterowania tylko na tym komputerze (127.0.0.1, port 27878 lub następny wolny). Łączący się program musi też podać tajny token, który może odczytać tylko Twoje konto użytkownika, tworzony na nowo przy każdym uruchomieniu. Działa od następnego uruchomienia SolidCraft. Wyłączone: nic nie nasłuchuje, chyba że uruchomisz SolidCraft z --control.", "ai.prefs.availability": "Sterowanie asystentem", "ai.prefs.background_commands": "Uruchamiaj polecenia agenta w tle", + "ai.prefs.connect_apps": "Udostępnij SolidCraft aplikacjom AI na tym komputerze", + "ai.prefs.connect_apps_note": "Przy uruchomieniu SolidCraft dodaje go jako serwer MCP do aplikacji AI znalezionych na tym komputerze (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), aby agent mógł go używać bez konfiguracji. Dodawany jest tylko wpis solidcraft lub odświeżana jego ścieżka; zmieniony przez Ciebie wpis pozostaje nietknięty, a plik jest najpierw kopiowany. Wyłączone: dodane wpisy są usuwane. Pomoc > Połącz asystentów AI… robi to ręcznie.", + "ai.prefs.connect_at_start": "Łącz ostatnio używanego agenta przy uruchomieniu SolidCraft", + "ai.prefs.connect_at_start_note": "Przy każdym uruchomieniu SolidCraft uruchamia w tle ostatnio połączonego agenta (lub domyślnego), aby był gotowy do rozmowy. Nie działa, gdy SolidCraft jest uruchomiony z --control. Jeśli nie uda się połączyć, Asystent pokaże Połączenie nieudane i przycisk Ponów.", "ai.prefs.follow_camera": "Obracaj kamerę do szkiców", "ai.prefs.follow_camera_off": "Automatyczne podążanie kamery jest wyłączone.", "ai.prefs.follow_camera_on": "Kamera obraca się przodem do szkiców tworzonych przez agenta.", @@ -457,6 +748,8 @@ "ai.prefs.make_default": "Używaj domyślnie", "ai.prefs.no_agents": "Brak agentów. Dodaj agenta lub odśwież, aby wyszukać zainstalowane agenty.", "ai.prefs.no_saved_approvals": "Brak zapisanych zgód.", + "ai.prefs.open_at_start": "Otwieraj panel Asystenta przy uruchomieniu SolidCraft", + "ai.prefs.open_at_start_note": "Pokazuje panel Asystenta (lub jego osobne okno) przy każdym uruchomieniu SolidCraft. Nie działa, gdy SolidCraft jest uruchomiony z --control.", "ai.prefs.override_all_warning": "Ten agent może zapisywać, nadpisywać, eksportować i zastępować projekt bez pytania.", "ai.prefs.permission_all": "Zezwalaj na wszystko", "ai.prefs.permission_all_summary": "Dostępne narzędzia SolidCraft działają bez pytania.", @@ -480,6 +773,7 @@ "appearance.roughness": "Chropowatość", "appearance.surface_response": "Reakcja powierzchni", "at the face": "przy ścianie", + "bom.group_children": "Podczęści w wierszu ich części", "browser.body_name": "Bryła{number}", "browser.calibrate_title": "Kalibruj: {name}", "browser.capture_many": "Przesunięto komponenty ({count}), ale ich położenia nie zostały zapamiętane.", @@ -487,9 +781,12 @@ "browser.capture_one": "Przesunięto komponent, ale jego położenie nie zostało zapamiętane.", "browser.component_name": "Komponent{number}", "browser.edit_canvas_title": "Edytuj kanwę: {name}", + "browser.edit_point_cloud_title": "Edytuj chmurę punktów: {name}", "browser.move_title": "Przesuń: {name}", "browser.parameters": "Parametry ({count})", "browser.precision": "Dokładność: {precision}", + "browser.sketch_attachment_lost": "{name} (utracono zaczepienie)", + "browser.sketch_editing": "{name} (edytowany)", "browser.sketch_name": "Szkic{number}", "browser.units": "Jednostki: {units}", "cam.flat": "Płaska ściana", @@ -499,15 +796,37 @@ "cam.roller": "Rolka", "cam.roller_pick": "Rolka (opcjonalnie)", "cam.tip_pick": "Końcówka (opcjonalnie)", + "camera.shot_pitch": "Pochylenie", + "camera.shot_roll": "Przechylenie", + "camera.shot_yaw": "Odchylenie", + "canvas.decal_place_hint": "Kliknij ścianę, aby umieścić naklejkę", + "canvas.place_hint": "Kliknij płaszczyznę lub ścianę, aby umieścić płótno", + "choose a profile": "wybierz profil", + "choose the cam's and the follower's joints": "wybierz złącza krzywki i popychacza", + "choose the joints to couple": "wybierz złącza do sprzężenia", + "click a plane or planar face": "kliknij płaszczyznę lub płaską ścianę", + "click sketch curves": "kliknij krzywe szkicu", "cmd.appearance_assign": "Wygląd", + "cmd.appearance_chain": "Łańcuch wyglądów", + "cmd.appearance_copy": "Kopiuj wygląd", + "cmd.appearance_favorite": "Ulubiony wygląd", "cmd.appearance_library": "Biblioteka wyglądów", "cmd.appearance_list": "Lista wyglądów", + "cmd.appearance_paint": "Maluj wyglądem", + "cmd.appearance_paste": "Wklej wygląd", + "cmd.appearance_pick_up": "Pobierz wygląd", + "cmd.appearance_replace": "Zastąp wygląd", "cmd.assembly_bom": "Zestawienie materiałowe", + "cmd.assembly_mass_properties": "Właściwości masowe", + "cmd.body.print_face": "Powierzchnia druku", "cmd.body_rename": "Zmień nazwę bryły", + "cmd.browser_collapse_all": "Zwiń wszystko", + "cmd.browser_expand_all": "Rozwiń wszystko", "cmd.browser_group": "Nowa grupa", "cmd.browser_move": "Przenieś elementy przeglądarki", "cmd.browser_order": "Uporządkuj elementy przeglądarki", "cmd.browser_rename_group": "Zmień nazwę grupy", + "cmd.browser_reparent": "Przenieś do komponentu", "cmd.browser_ungroup": "Rozgrupuj", "cmd.browser_visibility": "Pokaż/ukryj", "cmd.canvas_calibrate": "Kalibruj płótno", @@ -519,8 +838,14 @@ "cmd.component_activate": "Aktywuj komponent", "cmd.component_break_link": "Zerwij łącze", "cmd.component_capture_position": "Zapamiętaj położenie", + "cmd.component_copies": "Znajdź identyczne kopie", + "cmd.component_copy_bodies": "Wklej bryły", "cmd.component_create": "Nowy komponent", + "cmd.component_cycle_color": "Zmień kolor komponentu", "cmd.component_delete": "Usuń komponent", + "cmd.component_edit_in_place": "Edytuj w miejscu", + "cmd.component_extract": "Wyodrębnij do pliku", + "cmd.component_finish_edit": "Zakończ edycję", "cmd.component_from_bodies": "Utwórz komponenty z brył", "cmd.component_insert_design": "Wstaw projekt", "cmd.component_links": "Lista łączy", @@ -528,11 +853,14 @@ "cmd.component_metadata": "Właściwości części", "cmd.component_metadata_set": "Zmień właściwości części", "cmd.component_move_bodies": "Przenieś bryły do komponentu", + "cmd.component_move_features": "Przenieś funkcje do komponentu", "cmd.component_move_sketches": "Przenieś szkice do komponentu", + "cmd.component_paste_from_design": "Wklej z innego projektu", "cmd.component_paste_new": "Wklej jako nowy", "cmd.component_properties": "Właściwości fizyczne komponentu", "cmd.component_relink": "Połącz ponownie ze źródłem", "cmd.component_rename": "Zmień nazwę komponentu", + "cmd.component_replace_with_link": "Zastąp łączem", "cmd.component_revert_position": "Przywróć położenie", "cmd.component_unlock": "Odblokuj zawartość", "cmd.component_update_links": "Aktualizuj łącza", @@ -582,6 +910,7 @@ "cmd.document_revision": "Wersja projektu", "cmd.document_units": "Zmień jednostki projektu", "cmd.edit_checkpoint": "Punkt kontrolny", + "cmd.edit_repeat": "Powtórz ostatnie polecenie", "cmd.edit_restore_checkpoint": "Przywróć punkt kontrolny", "cmd.engine_commands": "Lista poleceń", "cmd.engine_describe": "Opisz polecenie", @@ -596,6 +925,7 @@ "cmd.file_insert_step": "Wstaw STEP", "cmd.file_open_in_easyprint": "Otwórz w EasyPrint", "cmd.file_save_mesh": "Zapisz jako siatkę", + "cmd.file_send_to_slicer": "Wyślij do slicera", "cmd.file_slicers": "Zainstalowane slicery", "cmd.frame_member": "Element ramy", "cmd.frame_profile_insert": "Wstaw profil", @@ -604,6 +934,8 @@ "cmd.inspect_accessibility": "Analiza dostępności", "cmd.inspect_center_of_mass": "Środek masy", "cmd.inspect_clearance": "Prześwit", + "cmd.inspect_colored_components": "Włącz kolory komponentów", + "cmd.inspect_colored_components_disable": "Wyłącz kolory komponentów", "cmd.inspect_compare": "Porównaj bryły", "cmd.inspect_continuity": "Analiza ciągłości", "cmd.inspect_curvature_comb": "Analiza grzebienia krzywizny", @@ -613,6 +945,7 @@ "cmd.inspect_interference": "Kolizja", "cmd.inspect_isocurve": "Analiza izokrzywych", "cmd.inspect_minimum_radius": "Analiza promienia minimalnego", + "cmd.inspect_parameter_sweep": "Przegląd wartości parametru", "cmd.inspect_silhouette": "Sylwetka", "cmd.inspect_zebra": "Analiza zebry", "cmd.joint_as_built": "Złącze w stanie zastanym", @@ -657,11 +990,15 @@ "cmd.motion_plot": "Wykres badania ruchu", "cmd.motion_study": "Badanie ruchu", "cmd.motion_trace": "Ślad ruchu", + "cmd.motion_trace_edit": "Edytuj ślad ruchu", "cmd.motion_trace_keep": "Zachowaj ślad ruchu", + "cmd.occurrence_align": "Wyrównaj wystąpienie", "cmd.occurrence_copy": "Wklej (wystąpienie)", + "cmd.occurrence_drag": "Przeciągnij wystąpienie", "cmd.occurrence_ground": "Unieruchom", "cmd.occurrence_move": "Przesuń wystąpienie", "cmd.occurrence_properties": "Właściwości fizyczne wystąpienia", + "cmd.occurrence_reparent": "Przenieś do komponentu", "cmd.parameters_add": "Dodaj parametr użytkownika", "cmd.parameters_change": "Zmień parametry", "cmd.parameters_comment": "Komentarz parametru", @@ -686,17 +1023,73 @@ "cmd.plastic_rest": "Podparcie", "cmd.plastic_rules": "Lista reguł tworzyw", "cmd.plastic_snap_fit": "Zatrzask", + "cmd.pointcloud_delete": "Usuń chmurę punktów", + "cmd.pointcloud_edit": "Edytuj chmurę punktów", + "cmd.pointcloud_insert": "Wstaw chmurę punktów", + "cmd.pointcloud_list": "Chmury punktów", + "cmd.render_aging_describe": "Warstwowe starzenie powierzchni", "cmd.render_backends": "Silniki renderowania", + "cmd.render_batch": "Renderuj wszystkie ujęcia", + "cmd.render_camera_fit": "Kadruj obiekt renderowania", + "cmd.render_camera_get": "Sprawdź kamerę renderowania", "cmd.render_cancel": "Anuluj renderowanie", + "cmd.render_compare": "Porównaj obrazy", + "cmd.render_effects_describe": "Efekty obiektywu i kreatywne", "cmd.render_export": "Eksportuj obraz renderowania", + "cmd.render_hdr_inspect": "Sprawdź źródło HDR", + "cmd.render_library_appearance_apply": "Zastosuj nieprzezroczysty wygląd z biblioteki", + "cmd.render_library_describe": "Sprawdź zasób biblioteki renderowania", + "cmd.render_library_environment_apply": "Zastosuj wbudowane otoczenie HDR", + "cmd.render_library_list": "Przeglądaj bibliotekę renderowania", + "cmd.render_library_physical_prepare": "Przygotuj odniesienie fizyczne", + "cmd.render_library_preview": "Sprawdź oryginalną mapę powierzchni", + "cmd.render_library_studio_apply": "Zastosuj autorskie oświetlenie studyjne", + "cmd.render_library_studio_prepare": "Przygotuj autorskie oświetlenie studyjne", + "cmd.render_library_surface_bind": "Zapisz powiązanie powierzchni", + "cmd.render_library_surface_prepare": "Przygotuj autorskie mapy powierzchni", + "cmd.render_library_surface_unbind": "Usuń powiązanie powierzchni", + "cmd.render_library_targets": "Znajdź cele biblioteki renderowania", + "cmd.render_lights_add": "Dodaj światło", + "cmd.render_lights_duplicate": "Powiel światło renderowania", + "cmd.render_lights_list": "Lista świateł renderowania", + "cmd.render_lights_mute": "Wycisz światło", + "cmd.render_lights_remove": "Usuń światło renderowania", + "cmd.render_lights_set": "Ustaw światło renderowania", + "cmd.render_lights_solo": "Tylko to światło", + "cmd.render_optics_bind": "Zapisz powiązanie optyczne", + "cmd.render_optics_unbind": "Usuń powiązanie optyczne", + "cmd.render_output_size": "Ustaw rozmiar obrazu renderowania", "cmd.render_preflight": "Sprawdź zlecenie renderowania", + "cmd.render_preflight_copy": "Kopiuj raport kontroli renderowania", + "cmd.render_preset_apply": "Zastosuj natywne studio", + "cmd.render_preset_resolve": "Przejrzyj natywne studio", + "cmd.render_quality_prepare": "Przejrzyj stały budżet próbkowania", + "cmd.render_result_close": "Zamknij obraz renderowania", + "cmd.render_result_copy": "Kopiuj obraz renderowania", + "cmd.render_result_pin": "Zachowaj wyświetlany wynik renderowania", + "cmd.render_result_regrade": "Ponownie skoryguj kolory oryginału liniowego", + "cmd.render_result_view": "Pokaż obraz renderowania", "cmd.render_scene": "Sprawdź scenę renderowania", "cmd.render_settings_apply": "Zastosuj kamerę renderowania", + "cmd.render_settings_capture_hdr": "Zapisz ustawienia renderowania z HDR", "cmd.render_settings_get": "Ustawienia renderowania", "cmd.render_settings_set": "Zapisz ustawienia renderowania", + "cmd.render_shot_duplicate": "Powiel ujęcie renderowania", + "cmd.render_shot_remove": "Usuń ujęcie renderowania", + "cmd.render_shot_rename": "Zmień nazwę ujęcia renderowania", + "cmd.render_stage_backdrop": "Zapisz fizyczne tło renderowania", + "cmd.render_stage_clear": "Usuń scenografię renderowania", + "cmd.render_stage_ground": "Zapisz podłoże renderowania", "cmd.render_start": "Renderuj obraz", "cmd.render_status": "Postęp renderowania", "cmd.select_clear": "Wyczyść zaznaczenie", + "cmd.settings_profile_apply": "Zastosuj profil ustawień", + "cmd.settings_profile_delete": "Usuń profil ustawień", + "cmd.settings_profile_export": "Eksportuj profil ustawień", + "cmd.settings_profile_import": "Importuj profil ustawień", + "cmd.settings_profile_list": "Profile ustawień", + "cmd.settings_profile_rename": "Zmień nazwę profilu ustawień", + "cmd.settings_profile_save": "Zapisz profil ustawień", "cmd.sheet_convert": "Konwertuj na blachę", "cmd.sheet_export_bend_table": "Eksportuj tabelę gięć", "cmd.sheet_export_dxf": "Eksportuj rozwinięcie jako DXF", @@ -705,6 +1098,7 @@ "cmd.sheet_fold": "Zagięcie", "cmd.sheet_hem": "Zawinięcie", "cmd.sheet_manage_rules": "Reguły blach", + "cmd.sheet_path_flange": "Kołnierz wzdłuż ścieżki", "cmd.sheet_perforate": "Perforacja", "cmd.sheet_refold": "Zegnij ponownie", "cmd.sheet_rules": "Lista reguł blach", @@ -719,6 +1113,7 @@ "cmd.sketch.construction_line.tangent_external": "Styczna przez punkt zewnętrzny", "cmd.sketch.construction_line.tangent_two": "Wspólna styczna", "cmd.sketch.construction_line.vertical": "Pionowa prosta konstrukcyjna", + "cmd.sketch_arc3d": "Łuk 3D", "cmd.sketch_arc_center_point": "Łuk ze środka", "cmd.sketch_arc_tangent": "Łuk styczny", "cmd.sketch_arc_three_point": "Łuk przez 3 punkty", @@ -726,6 +1121,7 @@ "cmd.sketch_auto_constrain_from_datum": "Wiązania automatyczne od bazy", "cmd.sketch_auto_project": "Automatyczne rzutowanie krawędzi odniesienia", "cmd.sketch_blend_curve": "Krzywa przejściowa", + "cmd.sketch_cancel": "Anuluj szkic", "cmd.sketch_chain": "Łańcuch", "cmd.sketch_chamfer_distance_angle": "Faza odległość i kąt", "cmd.sketch_chamfer_equal_distance": "Faza równa odległość", @@ -746,8 +1142,11 @@ "cmd.sketch_drag": "Przeciągnij geometrię szkicu", "cmd.sketch_drag_end": "Zakończ przeciąganie szkicu", "cmd.sketch_draw_dimensioned": "Rysuj zwymiarowaną geometrię szkicu", + "cmd.sketch_drawing_bounds": "Rozmiar rysunku", "cmd.sketch_edit": "Edytuj szkic", "cmd.sketch_edit_text": "Edytuj tekst", + "cmd.sketch_equation_curve": "Krzywa z równania", + "cmd.sketch_equation_curve_edit": "Edytuj krzywą z równania", "cmd.sketch_export_dxf": "Zapisz jako DXF", "cmd.sketch_finish_auto_constrain": "Zakończ z wiązaniami automatycznymi", "cmd.sketch_fit_curves_to_section": "Dopasuj krzywe do przekroju siatki", @@ -790,9 +1189,13 @@ "cmd.sketch_spline_control_point": "Splajn z punktów kontrolnych", "cmd.sketch_spline_control_point_5": "Splajn z punktów kontrolnych (stopień 5)", "cmd.sketch_spline_fit_point": "Splajn przez punkty", + "cmd.sketch_spline_insert_point": "Dodaj punkt splajnu", + "cmd.sketch_spline_remove_point": "Usuń punkt splajnu", "cmd.sketch_spline_reverse": "Odwróć kierunek splajnu", "cmd.sketch_spun_profile": "Profil obrotowy", + "cmd.sketch_toggle_diameter": "Przełącz promień / średnicę", "cmd.sketch_toggle_driven": "Przełącz wymiar sterowany", + "cmd.sketch_transform": "Przekształć", "cmd.sketch_trim_path": "Przytnij wzdłuż ścieżki", "cmd.solid_align": "Wyrównaj", "cmd.solid_boundary_fill": "Wypełnienie konturem", @@ -830,28 +1233,58 @@ "cmd.timeline_export_script": "Eksportuj skrypt poleceń", "cmd.timeline_inspect": "Sprawdź funkcję", "cmd.timeline_paste": "Wklej funkcje", + "cmd.timeline_play": "Odtwórz historię", "cmd.timeline_redefine": "Edytuj funkcję", "cmd.timeline_rename": "Zmień nazwę", "cmd.timeline_reorder": "Zmień kolejność funkcji", "cmd.timeline_roll_to": "Przesuń znacznik historii", "cmd.timeline_rollback": "Przesuń znacznik osi czasu", + "cmd.timeline_stop": "Zatrzymaj historię", "cmd.timeline_suppress": "Wygaś funkcję", + "cmd.view.render_browser": "Przeglądarka renderowania", + "cmd.view.render_dock": "Przenieś dok renderowania", + "cmd.view.render_focus": "Widok skupienia na renderowaniu", + "cmd.view.status_items": "Elementy stanu widoku", "cmd.view_ambient_occlusion": "Okluzja otoczenia", + "cmd.view_angle_readout": "Kąty widoku", "cmd.view_apply": "Przywróć widok nazwany", + "cmd.view_back": "Widok z tyłu", + "cmd.view_bottom": "Widok z dołu", "cmd.view_delete": "Usuń widok nazwany", + "cmd.view_fit": "Dopasuj", + "cmd.view_front": "Widok z przodu", "cmd.view_graphics_preset": "Ustawienie graficzne", + "cmd.view_grid": "Siatka", + "cmd.view_ground_shadow": "Cień na podłożu", + "cmd.view_home": "Widok główny", + "cmd.view_isometric": "Widok izometryczny", + "cmd.view_left": "Widok z lewej", "cmd.view_list": "Lista widoków nazwanych", "cmd.view_navigate": "Nawiguj widokiem", + "cmd.view_navigation_bar": "Pasek nawigacji", + "cmd.view_next_tab": "Następna karta", "cmd.view_normal_to": "Prostopadle do zaznaczenia", + "cmd.view_previous_tab": "Poprzednia karta", "cmd.view_rename": "Zmień nazwę widoku nazwanego", + "cmd.view_render_frame": "Linie kadru renderowania", + "cmd.view_right": "Widok z prawej", "cmd.view_save": "Nowy widok nazwany", + "cmd.view_shots_strip": "Pasek ujęć", + "cmd.view_spin": "Ciągłe obracanie", + "cmd.view_tool": "Narzędzie nawigacji", + "cmd.view_top": "Widok z góry", + "cmd.view_visual_style": "Styl wizualny", "color.copy": "Kliknij, aby skopiować wartości koloru", "color.edit": "Kliknij, aby edytować kolor", "color.gamma": "Wartości koloru w przestrzeni gamma 0-255", + "color.hex": "Hex", + "color.hex_help": "Wpisz #rrggbb lub #rrggbbaa; sześć cyfr zachowuje nieprzezroczystość", + "color.hex_hint": "#rrggbb", "color.hue": "Odcień", "color.linear": "Wartości koloru w przestrzeni liniowej 0-1", "color.saturation_value": "Nasycenie i wartość", "color.selected": "Wybrany kolor", + "config.column_filter_empty": "Brak pasujących kolumn", "contact.components_count": "Liczba komponentów: {count}", "contact.enabled_label": "włączone", "coupling.gear_1": "Koło zębate 1", @@ -885,6 +1318,7 @@ "crash.report": "Zgłoś…", "crash.unclean_explanation": "Wykryto przy późniejszym uruchomieniu; dokładny czas zamknięcia nie został zapisany. Nieprawidłowe zamknięcie może też wynikać z wyłączenia systemu lub wymuszonego zatrzymania.", "delete.and_more": "… i jeszcze {count}", + "diagnostic.empty_boolean_component": "w komponencie '{component}' nie ma bryły do wycięcia lub przycięcia; narzędzie może nachodzić na '{body}' w komponencie '{other}' — aktywuj ten komponent lub wybierz tę bryłę jako cel", "dialog.bodies_count": "Bryły: {count}", "dialog.clearance_invalid": "luz musi być długością równą 0 lub większą", "dialog.compute": "Oblicz", @@ -895,13 +1329,27 @@ "dialog.dimension_insert_hint": "Kliknij dwukrotnie inny wymiar sterujący, aby wstawić jego nazwę", "dialog.dimension_name": "Wymiar: {name}", "dialog.edit_title": "EDYCJA: {title}", + "dialog.no_shown_body": "Brak widocznej bryły do zmiany: pokaż jakąś lub wybierz Nowa bryła", "dialog.select": "↖ Zaznacz", "dialog.selected_count": "↖ Zaznaczono: {count}", "dialog.selection_guidance": "Wybierz pole, aby je zmienić. Kliknij zaznaczone obiekty, aby je usunąć; Ctrl/Cmd+kliknięcie również je przełącza. Sprawdź podgląd i naciśnij OK.", "dialog.selection_step": "{step} z {total}: zaznacz {input}", "dialog.step": "Krok", + "document.changed_on_disk": "{name} zmienił się na dysku", + "document.changed_on_disk_detail": "{name} został zmieniony przez inny program lub komputer od chwili otwarcia lub ostatniego zapisu. Nadpisz zastępuje te zmiany Twoimi; Zapisz kopię zachowuje obie wersje.", + "document.copy_name": "{name} — kopia", + "document.open_anyway": "Otwórz mimo to", + "document.open_elsewhere": "{name} jest już otwarty", + "document.open_elsewhere_detail": "{name} jest otwarty w SolidCraft {app} na {who}, otwarty {when}. Jeśli oboje zapiszecie, ktoś straci swoją pracę. Otwórz go tylko do odczytu, aby go obejrzeć bez nadpisywania.", + "document.open_read_only": "Otwórz tylko do odczytu", + "document.opened_read_only": "Otwarto tylko do odczytu: Zapisz poprosi o nowy plik", + "document.overwrite": "Nadpisz", + "document.read_only_save": "Ten projekt otwarto tylko do odczytu: zapisz go jako nowy plik", "document.save_changes": "Zapisać zmiany w {name}?", + "document.save_copy": "Zapisz kopię…", + "document.tab_unsaved_changes": "Niezapisane zmiany", "document.unsaved_changes": "{name} ma niezapisane zmiany. Jeśli ich nie zapiszesz, zostaną utracone.", + "drive.rigid": "{joint} to złącze sztywne: utrzymuje swoje części nieruchomo, więc nie ma czym sterować. Aby mogły się poruszać, zmień jego typ w Edytuj złącze: Obrotowe do obrotu, Przesuwne do przesuwu, Walcowe do obu.", "drive.stopped_by_contact": "Zatrzymano przy {value}: {a} przeszedłby przez {b}", "drive.stopped_by_loop": "Zatrzymano przy {value}: pętla przez {joint} nie może się bardziej zamknąć", "drive.unconnected": "Nic się nie porusza: {part} nie jest połączony z niczym unieruchomionym", @@ -917,9 +1365,13 @@ "dxf.progress.write": "Zapisywanie DXF (5/5)", "dxf.tolerance": "Tolerancja krzywych", "dxf.tolerance_help": "Tylko widoczne bryły i pokazane szkice. Krzywe są przybliżane odcinkami. Mniejsza tolerancja daje dokładniejsze krzywe, ale zajmuje więcej czasu i pamięci.", + "each rail's curves must be in one sketch": "krzywe każdej prowadnicy muszą leżeć w jednym szkicu", + "feature computation ended without a result": "obliczanie funkcji zakończyło się bez wyniku", + "file.open.drawing_filter": "Projekty, pliki CAD, siatki i rysunki", "file_load.built": "Dotąd zbudowano: {built} z {total} elementów.", "file_load.converting": "Konwertowanie bryły {done} z {total}", "file_load.inserting": "Wstawianie geometrii", + "file_load.link_item": "{name} ({done} z {total})", "file_load.opening": "Otwieranie projektu", "file_load.preparing_thumbnail": "Przygotowywanie miniatury...", "file_load.preparing_view": "Przygotowywanie widoku...", @@ -929,24 +1381,77 @@ "file_load.rebuilding": "Przebudowa elementu {done} z {total}", "file_load.recovering": "Odzyskiwanie projektu", "file_load.stopping": "Oczekiwanie na zatrzymanie poprzedniej operacji...", + "file_load.updating_links": "Aktualizowanie łączy", "file_load.waiting": "Oczekiwanie na operację na pliku", "fits the face, e.g. M8": "pasuje do ściany, np. M8", + "from the profile": "z profilu", "from the rule": "z reguły", "help.apache": "Licencja Apache 2.0", + "help.appearance.assign": "Nadaje zaznaczonym bryłom, ścianom lub komponentom kolor albo wygląd materiału, bez zmiany ich masy. Służy do odróżniania części lub podglądu wykończenia.", "help.attributions": "Uznanie autorstwa (ATTRIBUTION.md)", "help.build": "Wersja {version} · commit {commit} · zbudowano {date}", + "help.component.finish_edit": "Zapisuje część edytowaną w miejscu, wraca do jej złożenia i aktualizuje je. Użyj, gdy skończysz zmieniać połączoną część.", + "help.connect_note": "Uruchom ponownie każdego asystenta, aby wczytał serwer SolidCraft. Przed zmianą każdy plik zapisano jako kopię .bak.", + "help.connect_title": "Połącz asystentów AI", + "help.face.delete": "Usuwa zaznaczone ściany i pozwala sąsiednim ścianom zamknąć lukę albo pozostawia ją otwartą jako powierzchnię. Służy do usunięcia przeszkadzającego zaokrąglenia, otworu lub występu.", "help.font_details": "Interfejs używa wbudowanych czcionek egui (Ubuntu Light i Hack na licencjach Ubuntu Font Licence oraz MIT/Bitstream Vera; Noto Emoji i czcionka ikon emoji na licencjach OFL i MIT). Tekst szkicu używa Liberation Sans (SIL OFL 1.1). Opcjonalny pakiet czcionek The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), nie jest dołączany do kompilacji SolidCraft.", "help.fonts": "Czcionki", "help.licences": "Licencje", + "help.material.assign": "Ustala, z czego są wykonane zaznaczone bryły, np. ze stali, aluminium lub ABS. Dzięki temu masa i ciężar odpowiadają rzeczywistej części.", "help.mit": "Licencja MIT", "help.notice": "NOTICE", + "help.occurrence.move": "Przesuwa część złożenia tylko w zakresie swobody dozwolonym przez jej złącza. Zaznacz ścianę części, a potem przeciągnij dostępną strzałkę lub łuk.", + "help.parameters.change": "Otwiera tabelę nazwanych wartości i wyrażeń sterujących wymiarami projektu. Służy do zmiany rozmiaru w jednym miejscu, za którą podąża każda funkcja, która go używa.", + "help.pointcloud.insert": "Wstawia skan PLY, XYZ lub PTS jako chmurę punktów obok modelu. Służy jako odniesienie przy budowaniu modelu z danych pomiarowych.", + "help.sketch.equation_curve": "Rysuje krzywą ze wzorów: x(t) i y(t) albo y = f(x), w zadanym zakresie. Wzory mogą używać parametrów, a krzywa za nimi podąża: służy do sinusoidy, spirali lub ewolwenty zęba koła.", + "help.solid.align": "Przesuwa zaznaczone bryły tak, aby punkt, ściana lub płaszczyzna na nich spotkały punkt, ścianę lub płaszczyznę w innym miejscu. Służy do dosunięcia części do innej bez mierzenia odsunięcia.", "help.solid.chamfer": "Ścina zaznaczone krawędzie płaską fazą o zadanej odległości. Służy do łamania ostrych krawędzi lub ułatwienia wprowadzenia kołka czy śruby.", + "help.solid.combine": "Łączy bryły, wycina je z bryły docelowej lub zachowuje tylko ich wspólną objętość, i może zachować bryły narzędziowe. Służy do scalania części, wycinania jednego kształtu drugim lub znajdowania miejsca, gdzie dwie bryły nachodzą na siebie.", + "help.solid.draft": "Pochyla zaznaczone ściany o zadany kąt mierzony od płaszczyzny neutralnej. Służy do części formowanych lub odlewanych, aby dały się wyjąć z formy.", "help.solid.extrude": "Wyciąga profil szkicu w 3D na zadaną odległość, dodając lub usuwając materiał. Służy do zamiany płaskiego obrysu w blok, występ lub kieszeń.", "help.solid.fillet": "Zaokrągla zaznaczone krawędzie gładkim łukiem o zadanym promieniu. Służy do złagodzenia ostrych krawędzi dla wytrzymałości, wygody lub wyglądu.", "help.solid.hole": "Wierci okrągły otwór o zadanej średnicy w wybranym punkcie ściany. Służy do otworów przelotowych pod śruby, kołki i innych prostych okrągłych otworów.", + "help.solid.loft": "Tworzy gładką bryłę przechodzącą przez dwa lub więcej profili szkicu albo od profilu do punktu. Służy do przejść, lejków, uchwytów i każdego kształtu, którego przekrój zmienia się na długości.", + "help.solid.mirror": "Tworzy lustrzaną kopię zaznaczonych brył lub funkcji względem płaszczyzny i może połączyć ją z oryginałem. Służy do części symetrycznych: modelujesz połowę, a dostajesz całość.", + "help.solid.move": "Przesuwa lub obraca zaznaczone bryły albo ich kopię o zadaną odległość i kąt. Służy do zmiany położenia bryły lub utworzenia drugiej w innym miejscu.", + "help.solid.offset_face": "Przesuwa zaznaczone ściany do wewnątrz lub na zewnątrz o zadaną odległość, a otaczające ściany za nimi podążają. Służy do pogrubienia ścianki, pogłębienia kieszeni lub podwyższenia występu bez edycji szkicu.", + "help.solid.pattern.circular": "Powtarza zaznaczone obiekty wokół osi z zadaną liczbą i kątem całkowitym. Służy do okręgów otworów pod śruby, szprych, żeberek i zębów.", + "help.solid.pattern.rectangular": "Powtarza zaznaczone obiekty w jednym lub dwóch kierunkach z zadaną liczbą i odstępem. Służy do rzędów i siatek otworów, żeber, kołków lub nóżek.", + "help.solid.press_pull": "Dodaje lub usuwa materiał, gdy przeciągasz ścianę, albo zaokrągla krawędzie, gdy je przeciągasz. Służy do szybkich zmian bezpośrednio na modelu.", + "help.solid.remove": "Usuwa zaznaczone bryły z projektu od tego miejsca na osi czasu; wcześniejsze kroki je zachowują. Służy do pozbycia się bryły pomocniczej, np. niepotrzebnego już narzędzia tnącego.", + "help.solid.replace_face": "Przenosi zaznaczone płaskie ściany na płaszczyznę lub równoległą ścianę, a bryła rośnie lub maleje, aby do niej dojść. Służy do zrównania ściany z inną częścią lub płaszczyzną konstrukcyjną.", "help.solid.revolve": "Obraca profil szkicu wokół osi, tworząc okrągłą bryłę. Służy do wałków, gałek, misek i wszystkich części okrągłych względem osi.", + "help.solid.scale": "Powiększa lub zmniejsza zaznaczone bryły o współczynnik, jednakowo we wszystkich kierunkach albo osobno dla każdej osi. Służy do zmiany rozmiaru zaimportowanego kształtu lub uwzględnienia skurczu.", "help.solid.shell": "Wydrąża bryłę, pozostawiając ścianki o zadanej grubości, i może otworzyć wybrane ściany. Służy do pudełek, pokryw i innych części cienkościennych.", + "help.solid.split_body": "Dzieli bryłę na osobne bryły płaszczyzną, ścianą innej bryły lub linią szkicu. Służy do tworzenia części drukowanych, obrabianych lub barwionych osobno.", + "help.solid.split_face": "Dzieli zaznaczone ściany wzdłuż płaszczyzny, ściany innej bryły lub krzywych szkicu, bez cięcia bryły. Służy do nadania części ściany własnego pochylenia, koloru lub odsunięcia.", + "help.solid.sweep": "Przeciąga profil szkicu wzdłuż ścieżki, tworząc bryłę. Służy do rur, prowadnic, uchwytów i każdej części o stałym przekroju biegnącej wzdłuż krzywej.", "help.third_party": "Licencje stron trzecich", + "help.timeline.compute_all": "Przelicza od początku każdą funkcję na osi czasu. Służy do odświeżenia modelu i sprawdzenia, które funkcje się nie powiodły.", + "help.timeline.delete": "Usuwa zaznaczone funkcje z osi czasu; usunięcie szkicu usuwa też funkcje na nim zbudowane. Służy do usunięcia niepotrzebnego już kroku.", + "help.timeline.play": "Odtwarza pozostałe funkcje jedna po drugiej, z półsekundową przerwą po każdym przeliczeniu. Uruchom to polecenie ponownie lub naciśnij Escape, aby zatrzymać; Przejdź do końca przeskakuje od razu.", + "history.sketch_under_constrained": "Niedostatecznie związany (stopnie swobody: {count})", + "history.sketch_under_constrained_one": "Niedostatecznie związany (stopnie swobody: {count})", + "hole_presets.confirm_delete": "Potwierdź usunięcie", + "hole_presets.delete": "Usuń", + "hole_presets.delete_prompt": "Usunąć ten własny szablon? Istniejące otwory pozostaną bez zmian.", + "hole_presets.full": "Biblioteka własnych szablonów zawiera już 64 szablony.", + "hole_presets.invalid_name": "Wpisz krótką nazwę bez podziałów wierszy i znaków sterujących.", + "hole_presets.invalid_parameters": "Uzupełnij parametry otworu poprawnymi wyrażeniami rozsądnej długości.", + "hole_presets.missing": "Wybrany szablon nie jest już dostępny.", + "hole_presets.name": "Nazwa szablonu", + "hole_presets.name_exists": "Szablon o tej nazwie już istnieje. Użyj innej nazwy.", + "hole_presets.name_hint": "Unikalna nazwa", + "hole_presets.overwrite": "Zapisz zmiany w wybranym szablonie", + "hole_presets.preset": "Szablon", + "hole_presets.recall": "Wczytaj", + "hole_presets.rename": "Zmień nazwę", + "hole_presets.save": "Zapisz nowy", + "hole_presets.scope": "Zapisywany w Twoim profilu dla wszystkich projektów.", + "hole_presets.select": "Wybierz szablon", + "hole_presets.title": "Własne szablony", + "hole_presets.unsupported_options": "Ten szablon używa opcji gwintu, których ta wersja nie potrafi wczytać.", + "hole_presets.unsupported_overwrite": "Ten szablon zawiera opcje, których nie można bezpiecznie nadpisać.", "home.back": "Wróć do {name}", "home.crashes": "Raporty awarii", "home.design_workspace": "Projektowanie", @@ -1011,6 +1516,9 @@ "install.steps_intro": "Safari instaluje aplikacje internetowe z własnych menu:", "install.title": "Zainstaluj SolidCraft", "issue.body_label": "Treść zgłoszenia", + "issue.note_changed_while_waiting": "Ustawienia lub model zmieniły się w trakcie oczekiwania na podgląd. Zrób ponownie zrzut ekranu, aby zaktualizować szczegóły techniczne dla bieżącego widoku.", + "issue.note_details_kept": "Zrzut ekranu zrobiono lokalnie. Zachowano edytowane przez Ciebie szczegóły techniczne: sprawdź, czy nadal pasują do bieżącego widoku.", + "issue.note_details_updated": "Zaktualizowano szczegóły techniczne do bieżącego widoku. Zrzut ekranu zrobiono lokalnie. Sprawdź go przed dołączeniem na GitHubie.", "issue.note_image_copied": "Wklej obraz do szkicu na GitHubie lub zapisz plik PNG, jeśli kopiowanie obrazu jest niedostępne.", "issue.note_opened": "Przejrzyj szkic na GitHubie i dołącz zrzut ekranu. Przycisk Submit new issue na GitHubie publikuje zgłoszenie.", "issue.note_opened_copied": "Skopiowano raport. Wklej go do szkicu na GitHubie, dołącz zrzut ekranu, a następnie kliknij Submit new issue na GitHubie.", @@ -1022,9 +1530,28 @@ "joint.from_bodies_hint": "Każda wybrana bryła trafia do nowego, własnego komponentu i pozostaje na swoim miejscu.", "joint.one_body": "Oba wybory leżą na {body}. Drugi wybierz na innej części.", "joint.one_component": "Te części są bryłami jednego komponentu: {bodies}. Złącze porusza jeden komponent względem drugiego, więc każda część potrzebuje własnego komponentu.", + "joint.rigid_group_one_component": "Te bryły ({count}) są w jednym komponencie (lub w samym projekcie): najpierw użyj {command}.", + "joint.rigid_group_select_components": "Zaznacz dwa lub więcej komponentów.", + "joint_move.blocked_hint": "Sprawdź typ złącza (np. Sztywne), unieruchomienie, limity złącza i wartości sterowane parametrami.", + "joint_move.blocked_title": "Nie można przesunąć tej części", + "joint_move.coarse": "Krok obrotu przy osi (°)", + "joint_move.distance": "Odległość od początku", + "joint_move.done": "Gotowe", + "joint_move.fine": "Krok obrotu z dala od osi (°)", + "joint_move.fixed": "Ta część nie ma ruchomej osi złącza.", + "joint_move.help": "Przesuń — przeciągnij strzałkę lub pierścień. Esc anuluje bieżące przeciąganie.", + "joint_move.legacy_hint": "Wyłącz, aby używać poprzedniego panelu Przesuń.", + "joint_move.precision": "Wyciągnij poza przerywaną linię, aby obracać precyzyjnie.", + "joint_move.rotation": "Obrót od początku", + "joint_move.select": "Zaznacz ścianę lub jedną część złożenia, a potem wybierz Przesuń.", + "joint_move.settings": "Przesuwanie w złożeniu", + "joint_move.step": "Krok", + "joint_move.use_handles": "Używaj uchwytów ruchu złączy do przesuwania w złożeniu", "keymap.command_id": "ID polecenia", "keymap.empty": "Brak pasujących poleceń", "keymap.use_anyway": "Mimo to użyj tutaj {key}", + "label.move_to_left_side": "Przenieś na lewą stronę", + "label.move_to_right_side": "Przenieś na prawą stronę", "manage.appearance_hint": "Wybierz wygląd dla zaznaczenia lub przeciągnij próbkę na bryłę albo ścianę.", "manage.assign_hint": "Wybierz bryły i ich regułę projektowania części z tworzyw sztucznych.", "manage.config_hint": "Edytuj wiersze, kolumny i reguły konfiguracji, a następnie aktywuj wiersz lub wyświetl jego podgląd.", @@ -1032,6 +1559,51 @@ "manage.material_hint": "Wybierz bryły i ich materiał fizyczny.", "manage.parameters_hint": "Edytuj wyrażenia i jednostki. Zmiany są stosowane po naciśnięciu Enter lub opuszczeniu pola.", "manage.rules_hint": "Wybierz regułę do edycji lub utwórz nową. Potwierdź, aby zapisać regułę.", + "material.editor.add_property": "Dodaj właściwość", + "material.editor.add_source": "Dodaj źródło", + "material.editor.assigned_density": "Przypisana gęstość", + "material.editor.axes": "Osie materiału", + "material.editor.axes_numeric": "1 / 2 / 3", + "material.editor.axes_wood": "L / R / T", + "material.editor.copy_name": "Kopia {name}", + "material.editor.density_range": "Przypisana gęstość musi być większa od 0 i nie większa niż 1000 g/cm³.", + "material.editor.designation": "Oznaczenie", + "material.editor.duplicate": "Powiel", + "material.editor.engineering_card": "Karta właściwości inżynierskich", + "material.editor.family": "Rodzina materiałów", + "material.editor.glass": "Szkło", + "material.editor.illustrative": "Poglądowe", + "material.editor.invalid_property": "Nieobsługiwany typ właściwości.", + "material.editor.isotropic": "Izotropowy", + "material.editor.measurement": "Pomiar", + "material.editor.metal": "Metal", + "material.editor.moisture": "Wilgotność, w przeliczeniu na suchą masę", + "material.editor.name_required": "Wpisz nazwę o długości od 1 do 128 znaków.", + "material.editor.no_draft": "Nie otwarto żadnego szkicu materiału.", + "material.editor.number_required": "Wpisz skończoną wartość liczbową.", + "material.editor.orthotropic": "Ortotropowy", + "material.editor.other": "Inne", + "material.editor.polymer": "Polimer", + "material.editor.preserved_appearance": "Zachowany wygląd", + "material.editor.public_reference": "Publiczne źródło", + "material.editor.reference": "Źródło", + "material.editor.save_or_discard": "Zapisz lub odrzuć szkic materiału przed przypisaniem materiału.", + "material.editor.saved": "Zapisano materiał. Przypisania do brył pozostają bez zmian.", + "material.editor.scope": "Zapisz przechowuje ten materiał bez przypisywania go do brył. Puste właściwości i warunki pozostają nieznane. Gęstość z karty nie zmienia przypisanej gęstości ani masy.", + "material.editor.source_id": "Identyfikator źródła", + "material.editor.source_kind": "Typ źródła", + "material.editor.source_title": "Tytuł źródła", + "material.editor.sources": "Źródła", + "material.editor.stale": "Ten materiał zmienił się, gdy szkic był otwarty. Odrzuć go i otwórz ponownie przed zapisaniem.", + "material.editor.state": "Stan materiału", + "material.editor.strain_rate": "Prędkość odkształcenia", + "material.editor.symmetry": "Symetria sprężystości", + "material.editor.temperature": "Temperatura", + "material.editor.unknown_card": "Właściwości inżynierskie są nieznane. Zapisanie może zachować tylko przypisaną gęstość i istniejący wygląd.", + "material.editor.user_supplied": "Podane przez użytkownika", + "material.editor.wood": "Drewno", + "material.selection.choose": "Wybierz materiał", + "material.selection.mixed": "Różne materiały", "measure.at": "W punkcie", "measure.item": "Element {number}", "messages.ago_h": "{n} godz. temu", @@ -1056,44 +1628,213 @@ "motion.to_end": "Na koniec", "motion.to_start": "Na początek", "motion.track_name": "Ścieżka {number}", + "nav.alias.help": "Shift+Alt+przeciąganie lewym obraca widok, Shift+Alt+środkowym przesuwa, Shift+Alt+prawym powiększa; przeciąganie środkowym także przesuwa, a prawym obraca", + "nav.blender.help": "Przeciąganie środkowym obraca widok, Shift+środkowy przesuwa, Ctrl+środkowy powiększa; przeciąganie prawym nie rusza kamery", "nav.free_orbit.help": "Mysz i mysz 3D obracają widok przez oba bieguny i zachowują przechylenie. Przyciąganie do osi z Shift jest wyłączone.", "nav.free_orbit.label": "Swobodne obracanie", + "nav.free_orbit.snap_help": "Mysz i mysz 3D obracają widok przez oba bieguny i zachowują przechylenie. Przytrzymaj Shift podczas obracania, aby przyciągnąć kierunek widoku i przechylenie.", + "nav.free_orbit_upright.help": "Przeciąganie myszą w bok obraca model wokół pionowej osi świata; przeciąganie w górę i w dół przechyla go nad wierzchołkiem bez ograniczeń.", + "nav.free_orbit_upright.label": "Obracaj wokół osi pionowej", + "nav.fusion.help": "Przeciąganie środkowym przesuwa, Shift+środkowy obraca widok, przeciąganie prawym obraca widok", + "nav.hfss.help": "Alt+przeciąganie lewym przesuwa, Shift+Alt+lewy powiększa, Ctrl+przeciąganie lewym na pustym miejscu obraca widok", + "nav.inventor.help": "Przeciąganie środkowym przesuwa, Shift+środkowy obraca widok, Ctrl+środkowy powiększa, przeciąganie prawym obraca widok", + "nav.maya.help": "Alt+przeciąganie lewym obraca widok, Alt+środkowy przesuwa, Alt+prawy powiększa; przeciąganie środkowym także przesuwa", + "nav.openscad.help": "Przeciąganie lewym na pustym miejscu obraca widok, Shift+przeciąganie lewym zaznacza prostokątem, przeciąganie geometrii szkicu ją edytuje; przeciąganie prawym lub środkowym przesuwa, Shift+prawy lub Shift+środkowy powiększa", + "nav.perspective.sketch": "Edycja szkicu używa widoku ortogonalnego. Zakończ szkic, aby przełączyć na perspektywę.", + "nav.right_drag_orbits.help": "Wyłączone: przeciąganie prawym nie rusza kamery, a prawy przycisk tylko otwiera menu kontekstowe. Wybranie przypisania myszy SolidWorks wyłącza tę opcję.", + "nav.right_drag_orbits.label": "Przeciąganie prawym obraca widok", + "nav.solidworks.help": "Przeciąganie środkowym obraca widok, Ctrl+środkowy przesuwa, Shift+środkowy powiększa, przeciąganie prawym obraca widok", + "nav.tinkercad.help": "Przeciąganie prawym obraca widok, przeciąganie środkowym lub Shift+prawym przesuwa", "nav.touchpad.help": "Przytrzymaj Shift i poruszaj wskaźnikiem, aby przesuwać; przytrzymaj Alt/Option i poruszaj nim, aby obracać widok. Przycisk myszy nie jest potrzebny. Przewijanie w pionie powiększa.", "nav.touchpad.label": "Touchpad", "nav.touchpad.orbit": "Obracanie widoku (przytrzymaj Alt/Option i poruszaj; bez przycisku myszy)", "nav.touchpad.pan": "Przesuwanie (przytrzymaj Shift i poruszaj; bez przycisku myszy)", "nav.touchpad.scroll": "Touchpad powiększa przewijaniem w pionie. Ustawienie przesuwania dwoma palcami jest zachowane dla innych ustawień wstępnych.", "nav.touchpad.zoom": "Powiększanie (przewijanie w pionie lub szczypanie)", + "navbar.agent_chat": "Panel czatu Asystenta", + "navbar.agent_cursor": "Pokaż kursor agenta", + "navbar.ambient_occlusion": "Okluzja otoczenia", + "navbar.assistant": "Asystent", + "navbar.custom.add_slot": "Dodaj {slot}", + "navbar.custom.always": "Zawsze widoczny", + "navbar.custom.available": "{available} · przeciągnij na pasek lub naciśnij Dodaj", + "navbar.custom.buttons": "Przyciski", + "navbar.custom.compact": "Kompaktowy", + "navbar.custom.count": "{count} z 16 miejsc", + "navbar.custom.customise": "Dostosuj pasek nawigacji…", + "navbar.custom.design": "Projekt", + "navbar.custom.duplicate": "To miejsce jest już na pasku.", + "navbar.custom.edge": "Krawędź", + "navbar.custom.edge_bottom": "Dół", + "navbar.custom.edge_top": "Góra", + "navbar.custom.fade": "Wygaszaj", + "navbar.custom.full": "Usuń jedno miejsce, aby dodać kolejne.", + "navbar.custom.hidden_design": "Ukryty w środowisku Projekt", + "navbar.custom.hidden_render": "Ukryty w środowisku Renderowanie", + "navbar.custom.hide": "Ukryj pasek nawigacji", + "navbar.custom.hide_idle": "Ukryj do najechania kursorem", + "navbar.custom.icon_only": "Tylko ikona", + "navbar.custom.icon_value": "Ikona i wartość", + "navbar.custom.icons": "Ikony", + "navbar.custom.idle": "W bezczynności", + "navbar.custom.intro": "Wybierz elementy sterujące na pasku u dołu widoku 3D i ich kolejność. Przeciągnij miejsce, aby je przesunąć, lub przeciągnij je poza pasek, aby je usunąć.", + "navbar.custom.labels": "Ikony i etykiety", + "navbar.custom.left": "Przesuń w lewo", + "navbar.custom.position": "Położenie", + "navbar.custom.position_centre": "Środek", + "navbar.custom.position_left": "Lewo", + "navbar.custom.position_right": "Prawo", + "navbar.custom.preview_as": "Podgląd jako", + "navbar.custom.regular": "Zwykły", + "navbar.custom.remove": "Usuń", + "navbar.custom.remove_bar": "Usuń z paska", + "navbar.custom.render": "Renderowanie", + "navbar.custom.reset": "Resetuj pasek nawigacji", + "navbar.custom.reset_default": "Przywróć domyślne", + "navbar.custom.right": "Przesuń w prawo", + "navbar.custom.select": "Nie wybrano miejsca. Zaznacz miejsce na pasku, aby je przesunąć, usunąć lub zmienić jego wygląd.", + "navbar.custom.separators_full": "Pasek ma już cztery separatory.", + "navbar.custom.show": "Pokaż pasek nawigacji", + "navbar.custom.shows": "Pokazuje", + "navbar.custom.size": "Rozmiar", + "navbar.custom.stale": "Pasek się zmienił. Zaznacz miejsce ponownie.", + "navbar.custom.title": "Pasek nawigacji", + "navbar.custom.unknown": "To miejsce jest niedostępne.", + "navbar.description.ambient_occlusion": "Przyciemnia zagłębienia i narożniki, dodając głębi.", + "navbar.description.display": "Zawiera ustawienia widoku: ustawienie wstępne grafiki, siatkę, cień na podłożu, okluzję otoczenia i rzutowanie.", + "navbar.description.fit": "Kadruje zaznaczenie lub cały model, jeśli nic nie jest zaznaczone.", + "navbar.description.grid": "Pokazuje lub ukrywa siatkę podłoża.", + "navbar.description.ground_shadow": "Pokazuje lub ukrywa cień pod modelem.", + "navbar.description.home": "Wraca do widoku izometrycznego całego modelu.", + "navbar.description.look_at": "Obraca widok przodem do zaznaczonej ściany, płaszczyzny lub otwartego szkicu.", + "navbar.description.orbit": "Obraca widok wokół modelu.", + "navbar.description.pan": "Przesuwa widok w bok, w górę lub w dół.", + "navbar.description.projection": "Przełącza między widokiem ortogonalnym a perspektywicznym.", + "navbar.description.separator": "Cienka linia grupująca sąsiednie miejsca.", + "navbar.description.spin": "Obraca widok bez przerwy, aż klikniesz lub naciśniesz klawisz.", + "navbar.description.visual_style": "Przełącza sposób rysowania modelu: cieniowany, krawędziowy lub z krawędziami niewidocznymi.", + "navbar.description.zoom": "Przybliża lub oddala widok od modelu.", + "navbar.display": "Wyświetlanie", + "navbar.fit": "Dopasuj", + "navbar.graphics": "Grafika", + "navbar.grid": "Siatka", + "navbar.ground_shadow": "Cień na podłożu", + "navbar.home": "Widok główny", + "navbar.later": "Później", + "navbar.look_at": "Patrz na", + "navbar.more": "Więcej", + "navbar.orbit": "Obracanie widoku", + "navbar.orthographic": "Ortogonalny", + "navbar.pan": "Przesuwanie", + "navbar.perspective": "Perspektywiczny", + "navbar.preset": "Ustawienie wstępne", + "navbar.projection": "Rzutowanie", + "navbar.projection_heading": "Rzutowanie", + "navbar.separator": "Separator", + "navbar.show": "Pokaż", + "navbar.spin": "Ciągłe obracanie", + "navbar.style.shaded": "Cieniowany", + "navbar.style.shaded_with_edges": "Cieniowany z krawędziami", + "navbar.style.shaded_with_hidden_edges": "Cieniowany z krawędziami niewidocznymi", + "navbar.style.wireframe": "Model krawędziowy", + "navbar.translucent": "Półprzezroczysty", + "navbar.value_tip": "{name} · {value}", + "navbar.visual_style": "Styl wizualny", + "navbar.zoom": "Powiększenie", "needs two joints": "wymaga dwóch złączy", + "network.allow_once": "Zezwól jednorazowo", + "network.always_allow": "Zawsze zezwalaj temu serwerowi", + "network.prompt_detail": "Ten projekt ma łącze do pliku w lokalizacji sieciowej {host}. Otwarcie go łączy się z tym komputerem i może wysłać do niego Twoje dane logowania systemu Windows. Zezwalaj tylko zaufanym serwerom.", + "network.prompt_title": "Lokalizacja sieciowa", "new configuration": "nowa konfiguracja", "new parameter": "nowy parametr", "no hole": "bez otworu", "no interference": "brak kolizji", "no joint that moves yet": "brak jeszcze ruchomego złącza", + "no motion study yet": "brak jeszcze badania ruchu", "no picture": "brak obrazu", + "no such joint": "nie ma takiego złącza", "none": "brak", + "not a move": "to nie jest przesunięcie", + "not a number": "to nie jest liczba", + "open a sketch first": "najpierw otwórz szkic", "parts.automatic_name": "automatycznie", + "parts.dimension.across_flats": "Rozwartość klucza", + "parts.dimension.bore": "Otwór", "parts.dimension.d": "Średnica nominalna", + "parts.dimension.head_diameter": "Średnica łba", + "parts.dimension.head_height": "Wysokość łba", "parts.dimension.height": "Wysokość", + "parts.dimension.inner": "Średnica wewnętrzna", + "parts.dimension.outer": "Średnica zewnętrzna", "parts.dimension.pitch": "Skok", + "parts.dimension.socket": "Rozmiar gniazda", + "parts.dimension.socket_depth": "Głębokość gniazda", "parts.dimension.thickness": "Grubość", "parts.dimension.width": "Szerokość", + "parts.family.bearing": "Łożysko kulkowe zwykłe (obrys)", + "parts.family.button_head_cap_screw": "Śruba z łbem półokrągłym z gniazdem sześciokątnym", + "parts.family.dowel_pin": "Kołek walcowy", + "parts.family.hex_bolt": "Śruba z łbem sześciokątnym", + "parts.family.hex_nut": "Nakrętka sześciokątna", + "parts.family.set_screw": "Wkręt dociskowy z gniazdem sześciokątnym, płaski", + "parts.family.socket_head_cap_screw": "Śruba z łbem walcowym z gniazdem sześciokątnym", + "parts.family.washer": "Podkładka zwykła", "pattern.alignment_2": "Wyrównanie 2", "pattern.alignment_hint": "Liczba obejmuje oryginał. Wyśrodkuj rozkłada kopie po obu stronach; Odwróć wybiera stronę z dodatkową kopią przy parzystej liczbie.", "pattern.direction_1": "Kierunek 1", "pattern.direction_2": "Kierunek 2", "pattern.flip_direction": "Odwróć kierunek", + "perf.click_for_details": "Kliknij, aby zobaczyć szczegóły: wykres czasu klatek, histogram i to, co narysował GPU", + "perf.draw_calls": "Wywołania rysowania", + "perf.line_segments": "Odcinki linii", + "perf.low_1": "1% najniższych", + "perf.renderer": "Renderer", + "perf.scene_build": "Budowanie sceny", + "perf.triangles": "Trójkąty", + "perf.ui_time": "Czas interfejsu", + "perf.viewport": "Widok", + "perf.worst": "najgorszy", + "pick a body or some of its faces": "wybierz bryłę lub niektóre jej ściany", "pick a hole to seat it, or OK places it at the origin": "wybierz otwór, aby go osadzić, lub OK umieszcza go w początku układu", + "pick a planar face": "wybierz płaską ścianę", + "pick a plane or a face as the tool": "wybierz płaszczyznę lub ścianę jako narzędzie", + "pick a size": "wybierz rozmiar", + "pick edges of a body": "wybierz krawędzie bryły", + "pick edges of one body": "wybierz krawędzie jednej bryły", + "pick edges of the holes to remove": "wybierz krawędzie otworów do usunięcia", + "pick faces of one body": "wybierz ściany jednej bryły", + "pick faces to offset": "wybierz ściany do odsunięcia", + "pick lines of one sketch": "wybierz linie jednego szkicu", "pick one or two vertices, edges or faces": "wybierz jeden lub dwa wierzchołki, krawędzie lub ściany", + "pick one plane or face as the tool, or sketch curves": "wybierz jedną płaszczyznę lub ścianę jako narzędzie albo krzywe szkicu", + "pick sections in two or more sketches": "wybierz przekroje w dwóch lub więcej szkicach", + "pick sketch curves or edges": "wybierz krzywe szkicu lub krawędzie", + "pick the face to untrim": "wybierz ścianę do cofnięcia przycięcia", + "pick the path": "wybierz ścieżkę", + "pick what to keep": "wybierz, co zachować", + "pick what to keep of the other surface": "wybierz, co zachować z drugiej powierzchni", "prefs.add_item": "Dodaj element", "prefs.alt_frees_manipulators": "Alt / Option zwalnia również strzałki manipulatora", + "prefs.anti_aliasing_amd_dx12": "Wygładzanie krawędzi używa 1×, ponieważ test przy uruchomieniu nic nie narysował z wielopróbkowaniem i przeszedł przy 1×. Możesz wybrać inne ustawienie powyżej; uruchom ponownie, aby je zastosować, jeśli test przejdzie.", "prefs.anti_aliasing_note": "Wygładza poszarpane krawędzie.", "prefs.applies_on_restart": "Działa po ponownym uruchomieniu", "prefs.assistant": "Asystent", + "prefs.auto_operation": "Wybieraj operację automatycznie", + "prefs.auto_operation_note": "Okna funkcji wybierają Połącz, Nowa bryła lub Wytnij na podstawie tego, czego dotyka nowy materiał, dopóki nie wybierzesz sam. Wyłączone: zachowują operację, z którą się otwierają.", "prefs.axes": "Osie", "prefs.axis": "Oś", + "prefs.bodies_folders": "Foldery brył", + "prefs.bodies_folders_always": "Zawsze", + "prefs.bodies_folders_never": "Nigdy", + "prefs.bodies_folders_several": "Tylko przy kilku bryłach", "prefs.bottom": "Dół", + "prefs.bottom_centre": "Dół pośrodku", + "prefs.bottom_right": "Dół z prawej", "prefs.browser": "Przeglądarka", + "prefs.browser_reveal_on_hover": "Pokazuj po najechaniu", + "prefs.browser_show_note": "Widoczna utrzymuje przeglądarkę na ekranie. Pokazuj po najechaniu ukrywa ją, dopóki wskaźnik nie znajdzie się w jej miejscu lub na cienkiej karcie przy jej lewej krawędzi; pozostaje otwarta, gdy wskaźnik jest w niej lub otwarte jest jej menu.", + "prefs.browser_shown": "Widoczna", "prefs.built_in": "Wbudowana", "prefs.button_left": "Przeciąganie lewym", "prefs.button_middle": "Przeciąganie środkowym", @@ -1115,6 +1856,11 @@ "prefs.design": "Ustawienia domyślne projektu", "prefs.design_note": "Ustawienia, z którymi startują nowe projekty. Otwarte projekty zachowują własne.", "prefs.devices": "Mysz 3D", + "prefs.dialog_buttons": "Przyciski okien dialogowych", + "prefs.dialogs": "Okna dialogowe", + "prefs.dialogs_edge": "Przy krawędzi widoku", + "prefs.dialogs_left_column": "W lewej kolumnie", + "prefs.dialogs_note": "Gdzie otwierają się okna poleceń: zadokowane przy krawędzi widoku albo w lewej kolumnie w miejscu przeglądarki i Historii, które wracają na swoje miejsce po zamknięciu okna.", "prefs.display": "Wyświetlanie", "prefs.edges": "Krawędzie i cieniowanie", "prefs.extend": "Rozszerz", @@ -1130,12 +1876,25 @@ "prefs.gesture_pan": "Przesuwanie", "prefs.gesture_zoom": "Powiększanie", "prefs.graphics": "Grafika", + "prefs.graphics_card": "Karta graficzna", + "prefs.graphics_card_auto": "Automatycznie", + "prefs.graphics_card_missing": "Zapisana karta graficzna jest niedostępna; używane jest ustawienie Automatycznie.", + "prefs.graphics_card_restart": "Działa po ponownym uruchomieniu SolidCraft. WGPU_ADAPTER_NAME ma pierwszeństwo przed tym wyborem.", "prefs.graphics_note": "Wybierz między szybkością a gładkością. Każda opcja pokazuje swój efekt na przykładzie.", "prefs.graphics_presets_note": "Ustawienia wstępne zmieniają razem poniższe opcje.", "prefs.history": "Historia", + "prefs.history_origin_bodies": "Pokazuj początek układu i bryły na górze", + "prefs.history_origin_bodies_note": "Historia po lewej lub pod przeglądarką zaczyna się od folderu Bryły aktywnego komponentu i Początku układu, z ikonami oka i menu jak w przeglądarce. Historia na dole pozostaje bez zmian.", + "prefs.history_play_button": "Przycisk Odtwórz historię w elementach sterujących Historii", + "prefs.history_play_button_note": "Umieszcza Odtwórz historię między Cofnij o jeden krok a Przejdź o jeden krok do przodu w elementach sterujących Historii. Możesz też kliknąć je prawym przyciskiem, aby go pokazać lub ukryć.", + "prefs.history_sketches": "Szkice", + "prefs.history_sketches_in_order": "W kolejności", + "prefs.history_sketches_note": "Gdy Szkice są ustawione na Pod swoją funkcją, Historia po lewej pokazuje każdy szkic o poziom głębiej, pod pierwszą zbudowaną z niego funkcją, o ile jest dość szeroka na nazwy. Oś czasu na dole zawsze zachowuje kolejność tworzenia.", + "prefs.history_sketches_under_feature": "Pod swoją funkcją", "prefs.hold_stop_snapping": "Przytrzymaj, aby wyłączyć przyciąganie", "prefs.icons_only": "Tylko ikony", "prefs.imported_file": "Zaimportowany plik", + "prefs.in_browser": "W przeglądarce", "prefs.input": "Wprowadzanie", "prefs.interface": "Interfejs", "prefs.interface_language": "Język interfejsu", @@ -1146,8 +1905,14 @@ "prefs.layout_note": "Kompaktowy dokuje panele do krawędzi okna. Przezroczystość przeglądarki jest dostępna w układzie Pływający. Stronę asystenta zmienisz na stronie Asystent.", "prefs.left": "Lewo", "prefs.left_click": "Kliknięcie lewym", + "prefs.line_drag_draws_one": "Naciśnięcie i przeciągnięcie rysuje jedną linię", + "prefs.line_drag_draws_one_note": "W narzędziu Linia naciśnięcie, przeciągnięcie i puszczenie rysuje jedną linię od miejsca naciśnięcia do puszczenia i na tym się kończy. Kliknięcia nadal rysują łańcuch. Wyłączone: przeciągnięcie stawia punkt w miejscu puszczenia, tak jak kliknięcie.", + "prefs.linked_designs": "Projekty połączone", "prefs.live_input": "Bieżące wejście", "prefs.live_preview": "Podgląd na żywo", + "prefs.logo": "Logo", + "prefs.logo_accent": "Akcent", + "prefs.logo_theme": "Kolory motywu", "prefs.max_file_size": "Maksymalny rozmiar otwieranego pliku", "prefs.max_file_size_design": "Pliki projektów", "prefs.max_file_size_flag": "To uruchomienie używa --max-file-size {size} aż do zamknięcia SolidCraft. Te ustawienia obowiązują przy uruchomieniu bez tej opcji.", @@ -1162,23 +1927,56 @@ "prefs.mouse_mapping": "Przypisanie przycisków myszy", "prefs.navigation": "Nawigacja", "prefs.navigation_note": "Jak mysz, gładzik i mysz 3D poruszają widokiem.", + "prefs.network_host_remove": "Usuń", + "prefs.network_locations": "Zezwalaj na lokalizacje sieciowe w projektach", + "prefs.network_locations_note": "Wyłączone: połączone pliki projektu na innym komputerze (\\\\serwer\\udział) są otwierane tylko z serwerów wymienionych tutaj albo po zezwoleniu, gdy pojawi się pytanie.", + "prefs.network_locations_section": "Lokalizacje sieciowe", "prefs.not_on_gpu": "niedostępne na tym GPU", "prefs.on": "Włączone", "prefs.opaque": "Nieprzezroczysta", "prefs.orbit_snap": "Przytrzymaj Shift podczas obracania widoku, aby przyciągnąć do osi.", "prefs.orientation": "Orientacja", + "prefs.origin_plane_names": "Nazwy płaszczyzn początku układu", + "prefs.origin_plane_names_note": "Nazwy pokazywane w przeglądarce, oknach dialogowych i listach. {top} to XY, {front} to XZ, a {right} to YZ, przy osi Z w górę. Polecenia, skrypty i zapisane projekty zachowują XY, XZ i YZ.", "prefs.overall_speed": "Szybkość ogólna", + "prefs.perspective_fov": "Pole widzenia", "prefs.placement": "Umieszczanie", + "prefs.prefer_free_sketch_points": "Przy nakładających się punktach preferuj ruchome punkty szkicu", "prefs.preview_choices": "Podgląd wybranych opcji", + "prefs.print_face_highlight": "Wyróżnienie powierzchni druku", + "prefs.print_face_highlight_tip": "Jak mocno powierzchnia druku bryły jest barwiona i obrysowywana w widoku. 0 % nie pokazuje wyróżnienia.", + "prefs.profile_active": "Aktywny profil", + "prefs.profile_applied": "Zastosowano profil.", + "prefs.profile_changed": "Ustawienia zmieniły się od zapisania profilu. Zapisz zachowa je w nim.", + "prefs.profile_deleted": "Usunięto profil.", + "prefs.profile_export": "Eksportuj…", + "prefs.profile_exported": "Wyeksportowano profil.", + "prefs.profile_imported": "Zaimportowano profil. Wybierz go w polu Aktywny profil, aby się na niego przełączyć.", + "prefs.profile_name_hint": "Nazwa profilu, np. Laptop", + "prefs.profile_rename": "Zmień nazwę", + "prefs.profile_renamed": "Zmieniono nazwę profilu.", + "prefs.profile_save": "Zapisz", + "prefs.profile_saved": "Zapisano bieżące ustawienia w profilu.", + "prefs.profile_skipped": "Zastosowano profil; ustawienia, które zachowały bieżącą wartość: {n} (zobacz dziennik).", + "prefs.profiles": "Profile ustawień", + "prefs.profiles_note": "Skróty, pasek narzędzi, nawigacja, menu promieniste i ustawienia interfejsu, zebrane pod jedną nazwą i przełączane naraz.", + "prefs.project_options_dialog": "Okno opcji rzutowania", + "prefs.project_options_dialog_note": "Włączone: przed rzutowaniem wybierz Geometria lub Bryły oraz Powiązanie rzutu. Wyłączone: zachowaj poprzedni sposób bezpośredniego wybierania.", "prefs.quality_default": "domyślnie", "prefs.quality_fastest": "najszybciej", "prefs.quality_slowest": "najwolniej", "prefs.quality_smoother": "gładziej", + "prefs.render_previous_geometry_budget": "Używaj poprzedniego budżetu geometrii podglądu renderowania", + "prefs.render_previous_geometry_budget_help": "Przywraca poprzedni stały limit geometrii (512 MiB na 64-bitowym komputerze stacjonarnym, 128 MiB w innych przypadkach) zamiast budżetu zależnego od urządzenia.", "prefs.reports_saved": "Zapisane: {n}", + "prefs.ribbon_reveal": "Pokazuj wyniki wyszukiwania na wstążce", + "prefs.ribbon_reveal_note": "Najechanie na wynik w Szukaj poleceń pokazuje, gdzie polecenie znajduje się na wstążce: jego kartę, przycisk lub wiersz w rozwijanej liście panelu. Polecenie uruchomione z wyszukiwania miga w tym miejscu, a działające polecenie z rozwijanej listy oznacza swój panel.", "prefs.right_click": "Kliknięcie prawym", "prefs.saving": "Autozapis i odzyskiwanie", "prefs.scale_note": "Także Ctrl + / Ctrl − w oknie. Przyciski mają 28 px przy 100%.", "prefs.scale_text": "Skala i tekst", + "prefs.search": "Szukaj w preferencjach", + "prefs.search_empty": "Brak pasujących preferencji", "prefs.select": "Zaznacz", "prefs.select_one_item": "Zaznacz jeden element", "prefs.selecting": "Zaznaczanie", @@ -1186,14 +1984,38 @@ "prefs.shift_add_ctrl_toggle": "Shift tylko dodaje; Ctrl / Cmd przełącza", "prefs.shift_add_note": "Włączone: Shift dodaje, Ctrl / Cmd przełącza. Wyłączone (domyślnie): oba przełączają.", "prefs.shortcuts": "Skróty", + "prefs.single_surface_analysis": "Używaj jednej analizy powierzchni", + "prefs.single_surface_analysis_help": "Gdy wyłączone, cieniowanie powierzchni i Ciągłość mogą być włączone jednocześnie. Włączenie zachowuje ostatnio uruchomioną lub zmienioną analizę.", + "prefs.sketch_align_points": "Wyrównuj do innych punktów szkicu podczas rysowania", + "prefs.sketch_align_points_note": "Podczas rysowania punkt wyrównuje się jednocześnie poziomo z jednym punktem szkicu i pionowo z innym, z kropkowaną linią pomocniczą, a kliknięcie zachowuje oba wyrównania. Wyłączone: tylko z poprzednim punktem, po jednej osi.", + "prefs.sketch_conflict_colour": "Geometria w konflikcie w kolorze konfliktu", + "prefs.sketch_conflict_colour_note": "Gdy wiązania szkicu są w konflikcie, krzywe i punkty trzymane przez niespełnione wiązanie też są rysowane w kolorze konfliktu, a nie tylko jego symbol lub wymiar. Wyłączone: zachowują zwykłe kolory.", + "prefs.sketch_exit_view": "Po zakończeniu szkicu", + "prefs.sketch_exit_view.keep": "Zachowaj bieżący widok", + "prefs.sketch_exit_view.previous": "Wróć do poprzedniego widoku", + "prefs.sketch_exit_view.unless_rotated": "Wróć, chyba że obrócono widok", + "prefs.sketch_exit_view_note": "Dokąd przechodzi widok po Zakończ szkic, Anuluj lub podwójnym Esc.", "prefs.sketch_selection": "Szkic i zaznaczanie", "prefs.sketch_selection_heading": "Szkic i zaznaczanie", "prefs.sketch_selection_note": "Jak działa przyciąganie w szkicach i jak kliknięcia zaznaczają.", + "prefs.sketch_state_icons": "Ikony szkiców w kolorze ich stanu", + "prefs.sketch_state_icons_note": "W Historii i przeglądarce ikona szkicu przyjmuje kolor jego stanu (niedostatecznie związany, w pełni związany lub w konflikcie), a podpowiedź podaje ten stan. Wyłączone: każdy szkic ma tę samą ikonę.", + "prefs.sketch_tab_always": "Zawsze pokazuj kartę Szkic", + "prefs.sketch_tab_always_note": "Karta Szkic pozostaje na wstążce, zaraz po Model, nawet gdy żaden szkic nie jest otwarty. Jej narzędzia rysunkowe zaczynają wtedy szkic na zaznaczonej płaszczyźnie lub ścianie albo na następnej wybranej płaszczyźnie, z gotowym narzędziem.", + "prefs.sketch_tracking_guides": "Linie pomocnicze wyrównania do środków i punktów środkowych", + "prefs.sketch_tracking_guides_note": "Najedź na środek okręgu lub punkt środkowy prostej krawędzi, a potem przesuń w poziomie lub pionie, aby pokazać tymczasową kropkowaną linię pomocniczą.", "prefs.sketching": "Szkicowanie", "prefs.snap_drawing_note": "Podczas rysowania lub przeciągania punktu szkicu.", "prefs.source": "Źródło", "prefs.speed": "Szybkość", "prefs.stand_up_note": "Gdy plik STEP lub IGES otworzy się z osią Z w górę, proponuj obrót o ćwierć obrotu wokół osi X.", + "prefs.stand_up_unknown": "Dla plików z nieznanych programów", + "prefs.stand_up_unknown.ask": "Pytaj w oknie dialogowym", + "prefs.stand_up_unknown.note": "Pokaż uwagę", + "prefs.stand_up_unknown.off": "Nie proponuj", + "prefs.stand_up_unknown_note": "Jak składana jest propozycja, gdy nagłówek pliku nie wskazuje programu, o którym wiadomo, że zapisuje z osią Y w górę. Uwaga pojawia się tylko, gdy plik wydaje się leżeć na plecach; Pytaj w oknie dialogowym pyta o każdy taki plik, jak dotąd.", + "prefs.status_bar": "Pasek stanu", + "prefs.status_bar_note": "Cienki pasek wzdłuż dolnej krawędzi okna pokazuje, co jest edytowane, stan otwartego szkicu w jego kolorze i jednostki projektu; kliknięcie jednostek je zmienia. Stan szkicu nie jest wtedy pokazywany w rogu widoku.", "prefs.status_done": "Gotowe", "prefs.status_error": "Błąd", "prefs.status_selected": "Zaznaczone", @@ -1201,27 +2023,47 @@ "prefs.supersampling_brief": "Rysuje widok w większym rozmiarze i go zmniejsza: bardzo ostro, ale bardziej obciąża.", "prefs.tab_accent_note": "Kolor akcentu podąża za aktywną kartą", "prefs.theme_file": "plik motywu", + "prefs.theme_file_or_paste": "plik lub wklejenie", "prefs.theme_follow": "Śledź plik motywu", "prefs.theme_follow_error": "Nie zastosowano: {error}. Ostatni poprawny motyw pozostaje aktywny.", "prefs.theme_follow_launch": "Śledzenie tylko w tej sesji (--theme-file); plik jest wczytywany ponownie po każdym nadpisaniu przez inne narzędzie.", "prefs.theme_follow_note": "Plik jest wczytywany ponownie po każdym nadpisaniu przez inne narzędzie. Wybór motywu kończy śledzenie.", "prefs.theme_follow_off": "Wyłączone", "prefs.theme_follow_stop": "Zakończ śledzenie", + "prefs.theme_import_hint": "Kliknij, aby wybrać plik motywu, upuść go tutaj albo naciśnij Ctrl+V (Cmd+V na Macu), mając skopiowany motyw", + "prefs.theme_paste": "Wklej motyw", + "prefs.theme_paste_none": "Schowek nie zawiera motywu SolidCraft", "prefs.timeline_half_hour": "−30 min", "prefs.timeline_now": "teraz", "prefs.timeline_quarter_hour": "−15", + "prefs.toast_place": "Powiadomienia", "prefs.toggle_item": "Dodaj element lub usuń go ponownie", "prefs.toolbar": "Pasek narzędzi", + "prefs.toolbar_tabs": "Karty paska narzędzi", + "prefs.top": "Góra", + "prefs.trackpad_zoom_modifier": "Powiększaj przewijaniem dwoma palcami, trzymając", + "prefs.trackpad_zoom_modifier.alt": "⌥ / Alt", + "prefs.trackpad_zoom_modifier.cmd": "⌘", + "prefs.trackpad_zoom_modifier.ctrl": "Ctrl", + "prefs.trackpad_zoom_modifier.help": "Przytrzymaj tylko ten klawisz, aby powiększać w miejscu wskaźnika przewijaniem w pionie. Wyłączone zachowuje dotychczasowe przewijanie.", + "prefs.trackpad_zoom_modifier.off": "Wyłączone", "prefs.translucent": "Półprzezroczysta", "prefs.under_browser": "Pod przeglądarką", "prefs.under_cursor": "Pod kursorem", "prefs.units_precision": "Jednostki i dokładność", "prefs.updates": "Aktualizacje", "prefs.view": "Zachowanie widoku", + "prefs.view_confirm_corner": "OK i Anuluj w rogu widoku", + "prefs.view_confirm_corner_note": "Gdy otwarte jest okno dialogowe lub szkic, znaczek i krzyżyk w prawym górnym rogu widoku działają jak OK i Anuluj w oknie albo kończą i anulują szkic. Nawigator widoku przesuwa się pod nie.", "prefs.viewport": "Widok", + "prefs.viewport_background": "Tło", + "prefs.viewport_background_colour": "Kolor", + "prefs.viewport_background_theme": "Gradient motywu", "prefs.wheel": "Kółko", "prefs.wheel_trackpad": "Kółko i gładzik", "prefs.workspace": "Środowisko pracy", + "prefs.zoom_stop_at_model": "Zatrzymuj powiększanie na modelu", + "prefs.zoom_stop_at_model_tip": "Mysz 3D i aplikacja urządzenia powiększają w stronę powierzchni na środku widoku; powiększanie przeciąganiem trzyma punkt, w którym zaczęło się przeciąganie. Wyłączone: powiększanie może przejść przez model. Kółko i szczypanie osobno używają Powiększaj w stronę kursora", "prefs.zoom_toward_cursor": "Powiększanie w stronę kursora", "properties.title": "Właściwości: {name}", "recovery.days_ago": "{count} dni temu", @@ -1293,8 +2135,34 @@ "search.suggest": "Czy chodziło o {label}?", "search.try": "Wpisz nazwę polecenia, element tego projektu lub parametr. Aby uruchomić polecenie z wartościami, wpisz jego identyfikator i obiekt JSON: {example}", "search.valid": "Prawidłowe", + "section.off_hint": "Nie wybrano płaszczyzny: OK wyłącza przekrój.", + "select a direction (an axis, a sketch line or a straight edge) first": "najpierw zaznacz kierunek (oś, linię szkicu lub prostą krawędź)", + "select a direction (an axis, a sketch line or a straight edge) for the profile to follow": "zaznacz kierunek (oś, linię szkicu lub prostą krawędź), za którym ma podążać profil", + "select a point on a component": "zaznacz punkt na komponencie", + "select a profile, edges or sketch lines first": "najpierw zaznacz profil, krawędzie lub linie szkicu", + "select an axis": "zaznacz oś", + "select an axis, a straight or circular edge, or a cylinder, cone or torus face first": "najpierw zaznacz oś, prostą lub okrągłą krawędź albo ścianę walca, stożka lub torusa", + "select bodies first": "najpierw zaznacz bryły", + "select components first": "najpierw zaznacz komponenty", + "select corner points, or the two lines of one corner": "zaznacz punkty naroży lub dwie linie jednego naroża", + "select one corner point, or the two lines of one corner": "zaznacz jeden punkt naroża lub dwie linie jednego naroża", + "select sheet edges first": "najpierw zaznacz krawędzie blachy", + "select the bend line (a sketch line) first": "najpierw zaznacz linię gięcia (linię szkicu)", + "select the cam's profile (a sketch profile or the cam's edges)": "zaznacz profil krzywki (profil szkicu lub krawędzie krzywki)", + "select the corner to cut first": "najpierw zaznacz naroże do ścięcia", + "select the corners to round first": "najpierw zaznacz naroża do zaokrąglenia", + "select the fixed face first (a plate's large face)": "najpierw zaznacz ścianę stałą (dużą ścianę płyty)", + "select the frame sketch's lines first": "najpierw zaznacz linie szkicu ramy", + "select the path (sketch lines across the edge)": "zaznacz ścieżkę (linie szkicu w poprzek krawędzi)", + "select the rim face first": "najpierw zaznacz ścianę obrzeża", + "select the sheet edge first": "najpierw zaznacz krawędź blachy", + "select two components": "zaznacz dwa komponenty", + "set by the sketch's lines": "wyznaczone przez linie szkicu", "settings.display_quality_note": "Wyższe poziomy rysują zakrzywione ściany i krawędzie gładziej, ale siatka powstaje dłużej. Zmienia się tylko widok, nigdy projekt ani eksport.", + "settings.double_click_components": "Kliknij dwukrotnie komponent, aby go aktywować lub edytować połączony komponent w miejscu", + "settings.frame_rate_details_note": "Dodaje wykres czasów ostatnich klatek z nałożoną liczbą rysowanych trójkątów, histogram czasów klatek i to, co narysował GPU. Kliknij liczbę klatek w widoku, aby je pokazać lub ukryć.", "settings.frame_rate_note": "Pokazuje liczbę klatek na sekundę w prawym dolnym rogu widoku.", + "settings.insert_lists_open_designs": "Wstaw projekt pokazuje najpierw projekty otwarte w innych kartach", "settings.measure_axis_distances": "Pokaż odległości X/Y/Z", "settings.measure_axis_distances_help": "Gdy pomiar jest otwarty, pokazuj składowe wzdłuż osi globalnych obok odległości całkowitej.", "settings.msaa_applies_on_restart": "Wygładzanie krawędzi zadziała po ponownym uruchomieniu SolidCraft", @@ -1305,10 +2173,19 @@ "settings.reset_intro": "Te ustawienia nie działają na tym komputerze i uniemożliwiłyby uruchomienie SolidCraft, więc zostały zmienione:", "settings.reset_title": "Zmieniono ustawienia", "settings.supersampling_note": "Rysuje widok w wyższej rozdzielczości i go zmniejsza: gładsze krawędzie, linie i siatka na ekranach poniżej 4K. Kosztuje czas GPU: ok. 2,25× więcej pikseli przy 1,5× i 4× przy 2×.", + "settings.update_changed_links": "Aktualizuj zmienione połączone projekty po powrocie do karty", + "settings.window_system_details": "Szczegóły", + "settings.window_system_note_now": "Działa po ponownym uruchomieniu. Teraz: {now}.", + "settings.window_system_wayland_limited": "Niektóre funkcje są ograniczone w natywnym Wayland.", + "sheet.flange_type_base": "Bazowy", + "sheet.flange_type_contour": "Konturowy", + "sheet.flange_type_edge": "Krawędziowy", + "sheet.no_body": "nie ma bryły blaszanej: zacznij ją przez Kołnierz > Bazowy albo zamień płytę w blachę przez Konwertuj na blachę (wybierz jej dużą płaską ścianę)", "shortcut.json_error": "parametry muszą być w formacie JSON: {error}", "shortcut.no_command": "nie ma polecenia `{id}`; tekst przed JSON musi być identyfikatorem polecenia", "shortcut.pin": "Przypnij na górze pola S", "shortcut.unpin": "Odepnij", + "sketch is missing": "brak szkicu", "sketch.degrees_of_freedom": "Stopnie swobody: {count}", "sketch.dimension_added_driven": "Szkic już określa ten wymiar, więc dodano go jako wymiar sterowany (referencyjny)", "sketch.dimension_applied": "Wymiar zastosowany", @@ -1319,11 +2196,18 @@ "sketch.draw_curves": "Rysuj jako {linetype}", "sketch.make_selection": "Zamień zaznaczenie na {linetype}", "sketch.open_ends": "Otwarte: {count}", + "sketch.status_conflict": "wiązania w konflikcie", + "sketch.status_fully_constrained": "w pełni związany", "sketch.untied_ends": "Niezwiązane: {count}", "sketch_panel.attached": "Dołączony do {body} / {path}", "sketch_panel.author": "Pierwotne położenie: {path}", "sketch_panel.dimension_hint": "Wprowadź wartość lub wyrażenie, a następnie naciśnij OK.", "sketch_panel.move_hint": "Wprowadź odległości i kąt, a następnie naciśnij OK.", + "sketch_panel.plane_angle": "{plane}, obrócona o {angle}", + "sketch_panel.plane_fixed": "Stała płaszczyzna", + "sketch_panel.plane_flipped": "{plane}, od drugiej strony", + "sketch_panel.plane_offset": "{plane}, odsunięta o {distance}", + "sketch_panel.plane_origin": "Płaszczyzna {plane}", "sketch_panel.redefine_title": "{command}: {name}", "sketch_panel.sheet_attachment": "Dołączony do płaskiej ściany bryły blaszanej; podąża za tym panelem przy zmianach blachy.", "sketch_panel.text_hint": "Edytuj tekst i jego położenie, a następnie naciśnij OK.", @@ -1340,29 +2224,71 @@ "sketch_text.path_hint": "Krzywa szkicu, wzdłuż której biegnie tekst: kliknij tutaj, a potem krzywą", "sketch_text.use_font_file": "Użyj pliku czcionki {path}", "solid": "bryła", + "status.editing": "Edycja: {name}", + "status.navigation": "Przypisanie myszy: {mapping}", + "status.navigation_tip": "Jak mysz porusza widokiem. Kliknij, aby wybrać inne przypisanie", + "status.under_constrained": "Niedostatecznie związany (stopnie swobody: {count})", + "status.under_constrained_one": "Niedostatecznie związany (stopnie swobody: {count})", + "status.units_tip": "Jednostki projektu. Kliknij, aby je zmienić", + "the angle must be a number": "kąt musi być liczbą", + "the curves must be in one sketch": "krzywe muszą leżeć w jednym szkicu", + "the direction must be an axis, a sketch line or a straight edge": "kierunek musi być osią, linią szkicu lub prostą krawędzią", + "the duration must be a number of seconds, 0.001 or more": "czas trwania musi być liczbą sekund, co najmniej 0,001", + "the line's sketch is gone": "szkic linii już nie istnieje", + "the lines must be in one sketch": "linie muszą leżeć w jednym szkicu", + "the lines must be in one sketch, not the section's": "linie muszą leżeć w jednym szkicu, innym niż szkic przekroju", + "the parts library is empty": "biblioteka części jest pusta", "the parts library is not available": "biblioteka części jest niedostępna", + "the path curves must be in one other sketch": "krzywe ścieżki muszą leżeć w jednym, innym szkicu", + "the path's sketch is gone": "szkic ścieżki już nie istnieje", + "the position must be a number": "położenie musi być liczbą", + "the preview failed": "podgląd się nie powiódł", + "the profiles and curves must be in one sketch": "profile i krzywe muszą leżeć w jednym szkicu", + "the reference face must be on the edges' body": "ściana odniesienia musi leżeć na bryle tych krawędzi", + "the scale must be above 0": "skala musi być większa od 0", + "the section's profiles must be in one sketch": "profile przekroju muszą leżeć w jednym szkicu", + "the two origins are on the same component": "oba początki leżą na tym samym komponencie", "thread.automatic_size": "Rozmiar automatyczny", "thread.designation": "Oznaczenie", "thread.iso_metric": "Metryczny ISO", "thread.select_size": "Wybierz rozmiar", "timeline.delete_after_marker_one": "Usuń 1 funkcję za znacznikiem historii", "timeline.delete_after_marker_other": "Usuń funkcje za znacznikiem historii: {count}", + "timeline.delete_folders_tip": "Zachowaj ich funkcje i zagnieżdżone foldery w historii", + "timeline.delete_folders_with_features_tip": "Usuń foldery razem ze wszystkimi funkcjami w nich i zagnieżdżonymi folderami", "timeline.delete_many": "Usuń zaznaczone funkcje: {count}", + "timeline.edited_rolled_back": "{name} się zmieniła, ale leży za znacznikiem historii, więc nie jest budowana: przesuń znacznik za nią, aby zobaczyć wynik", + "timeline.feature_error": "Błąd: {message}", + "timeline.feature_hint": "Kliknij dwukrotnie, aby edytować · przeciągnij, aby zmienić kolejność · prawy przycisk, aby zobaczyć więcej", + "timeline.feature_rolled_back": "Cofnięta: leży za znacznikiem historii, więc nie jest budowana", + "timeline.feature_warning": "Ostrzeżenie: {message}", "timeline.group": "Nowy folder funkcji", "timeline.move_many": "Przenieś elementy osi czasu", "timeline.move_to_group": "Przenieś funkcje do folderu", "timeline.rename_group": "Zmień nazwę folderu funkcji", "timeline.reorder_many": "Zmień kolejność funkcji", + "timeline.suppress_features": "Wygaś funkcje", + "timeline.suppress_folders_tip": "Wygaś lub przywróć każdą funkcję w folderach i ich zagnieżdżonych folderach", "timeline.ungroup": "Usuń foldery funkcji", + "timeline.unsuppress_features": "Przywróć wygaszone funkcje", "to the face": "do ściany", "to the next face": "do następnej ściany", "toolbar.customize_note": "Karta {tab}. Zaznacz polecenie, aby dodać jego przycisk do paska narzędzi. Możesz też przeciągnąć wiersz z listy rozwijanej panelu na pasek narzędzi, przeciągnąć przycisk poza pasek, aby go usunąć, lub użyć pinezki w wierszu listy rozwijanej.", "toolbar.image": "OBRAZ", "toolbar.render": "RENDEROWANIE", + "toolbar.render_appearance": "WYGLĄD", + "toolbar.render_camera": "KAMERA", + "toolbar.render_environment": "OTOCZENIE", + "toolbar.render_lighting": "OŚWIETLENIE", + "toolbar.render_lights": "ŚWIATŁA", + "toolbar.render_result": "WYNIK", "toolbar.render_scene": "SCENA", + "toolbar.render_stage": "SCENOGRAFIA", + "toolbar.render_studio": "STUDIO", "trace.points": "Punkty wzdłuż ścieżki: {count}", "trace.stopped_by_contact": "Kończy się na próbce {sample}: {a} przeszedłby przez {b}", "trace.stopped_by_loop": "Kończy się na próbce {sample}: pętla przez {joint} nie może się bardziej zamknąć", + "trim by sketch curves, or by one plane or face": "przytnij krzywymi szkicu albo jedną płaszczyzną lub ścianą", "ui.1_degree_of_freedom": "1 stopień swobody", "ui.3d_mouse_axes_reassigned": "Osie są przypisane na nowo w Ustawieniach i to nadal obowiązuje razem z tą kalibracją.", "ui.3d_mouse_button": "Przycisk {number}", @@ -1416,6 +2342,10 @@ "ui.3d_mouse_offer": "Kalibracja myszy 3D naprawia zamienione lub odwrócone osie oraz ustawia jej szybkość i odczucie.", "ui.3d_mouse_offer_never": "Nie pokazuj więcej", "ui.3d_mouse_offer_swap": "Przełącz na Hidraw (sterownik bezpośredni)", + "ui.3d_mouse_orbit": "Obracanie widoku", + "ui.3d_mouse_orbit_classic": "Klasyczne", + "ui.3d_mouse_orbit_tip": "Śledzone: mysz 3D obraca widok wokół części modelu, która jest na środku widoku w chwili rozpoczęcia obrotu, oznaczonej bladą kulą. Klasyczne: wokół środka widoku", + "ui.3d_mouse_orbit_traced": "Śledzone", "ui.3d_mouse_reading": "Odczyt", "ui.3d_mouse_reset_axes": "Przywróć przypisanie osi", "ui.3d_mouse_reset_view": "Resetuj widok", @@ -1452,6 +2382,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Obróć nakładkę przeciwnie do ruchu wskazówek zegara, przytrzymaj, a następnie puść.", "ui.3d_mouse_switch_cap": "Kalibruj jako powrót do środka", "ui.3d_mouse_switch_trackball": "Kalibruj jako trackball", + "ui.3d_mouse_use_direct": "Użyj sterownika bezpośredniego", + "ui.3d_mouse_use_direct_tip": "Odczytuj mysz 3D bezpośrednio (hidraw) zamiast przez spacenavd.", "ui.3d_mouse_view_axis": "Oś widoku", "ui.3d_mouse_view_off": "Wyłączona", "ui.3d_mouse_view_off_tip": "Profil sterownika myszy 3D wyłącza tę oś, więc jej ruch nie porusza widokiem. Wybranie tu ruchu innej osi zamienia je miejscami, a ten ruch przestaje poruszać widokiem.", @@ -1477,6 +2409,8 @@ "ui.agent_chat_allowed": "Zezwolono", "ui.agent_chat_answered": "Odpowiedź: {option}", "ui.agent_chat_approval": "Zezwolić agentowi na to działanie?", + "ui.agent_chat_attach_selection": "Dołącz zaznaczenie", + "ui.agent_chat_attach_selection_tip": "Wyślij z wiadomością to, co zaznaczono w modelu (ściany, krawędzie, funkcje, bryły), aby agent wiedział, o co chodzi", "ui.agent_chat_attach_view": "Dołącz widok", "ui.agent_chat_attach_view_tip": "Wyślij z wiadomością obraz bieżącego widoku", "ui.agent_chat_attachable": "Obrazy, pliki PDF, tekstowe i CAD", @@ -1489,11 +2423,18 @@ "ui.agent_chat_auth_title": "Zaloguj się do agenta", "ui.agent_chat_cancel": "Anuluj", "ui.agent_chat_changes": "Zmiany: {n}, jeden krok cofania", + "ui.agent_chat_changes_n": "Zmiany: {n}", "ui.agent_chat_changes_of": "Zmiany: {n}/{limit}", + "ui.agent_chat_choose_model": "Wybierz model", "ui.agent_chat_close": "Zamknij", "ui.agent_chat_command": "Polecenie agenta", "ui.agent_chat_connect": "Połącz", "ui.agent_chat_copy": "Kopiuj", + "ui.agent_chat_ctx_bodies": "Bryły", + "ui.agent_chat_ctx_elements": "Elementy", + "ui.agent_chat_ctx_features": "Funkcje", + "ui.agent_chat_ctx_more": "+{n} więcej", + "ui.agent_chat_ctx_other": "Inne", "ui.agent_chat_custom_hint": "Dowolny program, który obsługuje Agent Client Protocol przez stdin i stdout. Nie jest uruchamiany przez powłokę.", "ui.agent_chat_denied": "Odmówiono", "ui.agent_chat_deny": "Odmów", @@ -1529,12 +2470,15 @@ "ui.agent_chat_import_failed": "{name}: import się nie powiódł: {error}", "ui.agent_chat_intro": "Rozmawiaj z agentem programistycznym, którego już używasz, lub z wybranym punktem końcowym modelu. Pracuje on na otwartym projekcie za pomocą narzędzi SolidCraft: jego zmiany są widoczne na bieżąco, a cofa się je jednym krokiem na wiadomość. To, co może robić bez pytania, ustawisz w Preferencje > AI.", "ui.agent_chat_key_in_env": "klucz ustawiony", + "ui.agent_chat_last_missing": "Ostatnio używany agent ({agent}) nie jest już dostępny. Wybierz agenta, a potem naciśnij Ponów.", "ui.agent_chat_left": "Lewa", "ui.agent_chat_limit": "Agent osiągnął limit {limit} zmian na jedną wiadomość. Wyślij kolejną wiadomość, aby mógł kontynuować.", + "ui.agent_chat_login_found": "znaleziono logowanie", "ui.agent_chat_minimize": "Zminimalizuj do paska", "ui.agent_chat_mode_all": "Wszystko", "ui.agent_chat_mode_ask": "Pytaj", "ui.agent_chat_mode_edits": "Edycje", + "ui.agent_chat_model_no_tools": "{model} nie może używać narzędzi SolidCraft, więc może tylko rozmawiać. Wybierz model obsługujący narzędzia.", "ui.agent_chat_model_tip": "Model używany przez agenta. Twój wybór jest zapamiętywany dla tego agenta.", "ui.agent_chat_new": "Nowy czat", "ui.agent_chat_new_confirm": "Rozpocząć nowy czat? Bieżący zostanie wyczyszczony.", @@ -1543,6 +2487,7 @@ "ui.agent_chat_no_control": "Punkt końcowy czatu z agentem się nie uruchomił, więc agent nie ma dostępu do projektu.", "ui.agent_chat_no_images": "Ten agent nie przyjmuje obrazów", "ui.agent_chat_no_picture": "W schowku nie ma obrazu", + "ui.agent_chat_no_tool_call": "Model nie użył narzędzi SolidCraft, więc projekt nie został zmieniony. Wybierz model obsługujący wywoływanie narzędzi; zobacz Modele lokalne w przewodniku czatu z agentem.", "ui.agent_chat_none_found": "Nie znaleziono agenta programistycznego. Zainstaluj jeden z poniższych, a potem naciśnij Odśwież:", "ui.agent_chat_none_found_short": "Nie znaleziono agenta", "ui.agent_chat_not_installed": "Nie zainstalowano", @@ -1552,12 +2497,17 @@ "ui.agent_chat_paste_picture": "Wklej obraz", "ui.agent_chat_permission": "Agent prosi o uruchomienie: {title}", "ui.agent_chat_pick": "Agent", + "ui.agent_chat_pick_context": "Wybierz kontekst", + "ui.agent_chat_pick_context_tip": "Wybierz w modelu ściany, krawędzie, funkcje i bryły, którym agent ma się przyjrzeć, a potem naciśnij OK", "ui.agent_chat_placeholder": "Poproś agenta o zmianę projektu…", "ui.agent_chat_placeholder_busy": "Zakolejkuj wiadomość na czas, gdy agent skończy (Ctrl+Enter: wyślij teraz)", "ui.agent_chat_pop_out": "Otwórz w osobnym oknie, które możesz przenieść na inny ekran", "ui.agent_chat_previous_picture": "Poprzedni obraz", "ui.agent_chat_privacy": "Nic nie trafia nigdzie poza uruchomionym przez Ciebie agentem, na Twoim własnym koncie.", "ui.agent_chat_privacy_note": "Czat sam z siebie nigdzie niczego nie wysyła: uruchomiony przez Ciebie agent łączy się z własną usługą na Twoim koncie. SolidCraft nigdy nie widzi ani nie przechowuje klucza ani hasła.", + "ui.agent_chat_provider_models": "Modele: {count}", + "ui.agent_chat_provider_other": "Inny", + "ui.agent_chat_provider_tip": "Dostawca, którego modele pokazuje następna lista.", "ui.agent_chat_queue": "Kolejka", "ui.agent_chat_queue_full": "Za dużo wiadomości czeka: usuń jedną lub poczekaj na agenta.", "ui.agent_chat_queued": "W kolejce", @@ -1567,6 +2517,7 @@ "ui.agent_chat_remove": "Usuń z kolejki", "ui.agent_chat_remove_file": "Usuń z tej wiadomości", "ui.agent_chat_remove_imported": "Usuń z tej wiadomości; część pozostaje w projekcie (Cofnij ją usuwa)", + "ui.agent_chat_retry": "Ponów", "ui.agent_chat_right": "Prawa", "ui.agent_chat_save": "Zapisz", "ui.agent_chat_send": "Wyślij", @@ -1579,6 +2530,7 @@ "ui.agent_chat_state_auth": "Wymagane logowanie", "ui.agent_chat_state_busy": "Pracuje…", "ui.agent_chat_state_exited": "Agent zatrzymany", + "ui.agent_chat_state_failed": "Połączenie nieudane", "ui.agent_chat_state_off": "Brak połączenia", "ui.agent_chat_state_ready": "Gotowy", "ui.agent_chat_state_starting": "Uruchamianie…", @@ -1586,6 +2538,7 @@ "ui.agent_chat_stop_tip": "Zatrzymaj agenta i wszystko, co uruchomił", "ui.agent_chat_stop_turn_tip": "Zatrzymaj agenta (Esc). Wiadomości w kolejce pozostają w kolejce.", "ui.agent_chat_turn_limit": "Zmiany na wiadomość", + "ui.agent_chat_turn_unlimited": "Bez limitu", "ui.agent_chat_undo_changes": "Cofnij te zmiany", "ui.agent_chat_undo_label": "Czat z agentem: {message}", "ui.agent_chat_undone": "(cofnięto)", @@ -1598,8 +2551,10 @@ "ui.ai_add": "Dodaj", "ui.ai_add_agent": "Dodaj agenta…", "ui.ai_add_agent_title": "Dodaj agenta", + "ui.ai_add_anthropic": "API zgodne z Anthropic", "ui.ai_add_api": "API zgodne z OpenAI", "ui.ai_add_custom": "Polecenie niestandardowe", + "ui.ai_add_endpoint": "Punkt końcowy API", "ui.ai_add_installed": "Zainstalowany agent", "ui.ai_add_installed_note": "Własny wpis dla zainstalowanego agenta, na przykład z innymi argumentami. Zainstalowane agenty są wyświetlane automatycznie.", "ui.ai_added": "dodano", @@ -1629,6 +2584,7 @@ "ui.ai_key_needs_https": "Klucz jest wysyłany tylko przez HTTPS albo do tego komputera.", "ui.ai_key_note": "Przechowywany w systemowym pęku kluczy, nigdy w ustawieniach SolidCraft. Dla serwera lokalnego zostaw puste.", "ui.ai_keychain_error": "Systemowy pęk kluczy odmówił: {error}", + "ui.ai_kind": "Rodzaj", "ui.ai_mode_all": "Zezwalaj na wszystko", "ui.ai_mode_all_note": "Nic nie pyta wcześniej. Raporty o awariach pozostają niedostępne, a ograniczenia folderów nadal obowiązują.", "ui.ai_mode_all_warning": "Agent może zapisywać, nadpisywać, eksportować i zastępować projekt bez pytania. Używaj tego tylko z zaufanym agentem i na zapisanych projektach.", @@ -1650,7 +2606,11 @@ "ui.ai_panel": "Panel", "ui.ai_permissions": "Uprawnienia", "ui.ai_preset": "Ustawienie wstępne", + "ui.ai_protocol": "Protokół", "ui.ai_remove": "Usuń", + "ui.ai_request_timed_out": "Model odpowiadał dłużej niż {seconds} s. Limit czasu żądania dla tego punktu końcowego możesz zwiększyć w Preferencje › Asystent.", + "ui.ai_request_timeout": "Limit czasu żądania", + "ui.ai_request_timeout_hint": "Jak długo może trwać jedno żądanie do modelu w tym punkcie końcowym, od 30 s do godziny. Zwiększ dla wolnego modelu lokalnego.", "ui.ai_reset": "Resetuj", "ui.ai_settings": "Ustawienia AI…", "ui.ai_show_features": "Pokaż funkcje AI", @@ -1659,13 +2619,33 @@ "ui.ai_test": "Testuj", "ui.ai_test_acp_ok": "Odpowiada: {agent}", "ui.ai_test_acp_tip": "Uruchamia na chwilę agenta, prosi go o sesję i ponownie ją kończy", + "ui.ai_test_answered": "Połączono: {model} odpowiedział", + "ui.ai_test_anthropic_tip": "Wysyła krótką wiadomość do punktu końcowego", "ui.ai_test_api_tip": "Prosi punkt końcowy o listę modeli", "ui.ai_test_no_model": "Połączono: modele: {count}, ale brak {model}", "ui.ai_test_ok": "Połączono: modele: {count}", "ui.ai_testing": "Testowanie…", + "ui.ai_tool_arguments": "Argumenty", + "ui.ai_tool_details": "Szczegóły", "ui.ai_tool_done": "gotowe", "ui.ai_tool_failed": "niepowodzenie", + "ui.ai_tool_result": "Wynik", "ui.ai_tool_running": "w toku", + "ui.ai_tool_sum_bodies_one": "Bryły: {count}", + "ui.ai_tool_sum_bodies_other": "Bryły: {count}", + "ui.ai_tool_sum_by": "o {value}", + "ui.ai_tool_sum_edges_one": "Krawędzie: {count}", + "ui.ai_tool_sum_edges_other": "Krawędzie: {count}", + "ui.ai_tool_sum_faces_one": "Ściany: {count}", + "ui.ai_tool_sum_faces_other": "Ściany: {count}", + "ui.ai_tool_sum_features_one": "Funkcje: {count}", + "ui.ai_tool_sum_features_other": "Funkcje: {count}", + "ui.ai_tool_sum_measured": "Zmierzono: {what}", + "ui.ai_tool_sum_more": "{steps} i {count} więcej", + "ui.ai_tool_sum_radius": "r {value}", + "ui.ai_tool_sum_saved": "Zapisano {file}", + "ui.ai_tool_sum_screenshot": "Zrzut ekranu", + "ui.ai_tool_sum_then": "{first}, potem {next}", "ui.ai_tool_unfold": "Kliknij, aby zobaczyć, co zwróciło", "ui.ai_tool_waiting": "oczekuje", "ui.ai_toolbar_button": "Pokaż przycisk na pasku narzędzi", @@ -1695,6 +2675,9 @@ "ui.blocked": "Zablokowane", "ui.bodies": "Bryły", "ui.bodies_all_if_none": "Bryły (wszystkie, jeśli brak)", + "ui.body_kind_mesh": "Bryła siatkowa", + "ui.body_kind_solid": "Bryła pełna", + "ui.body_kind_surface": "Bryła powierzchniowa", "ui.bottom": "Dół", "ui.box": "Prostopadłościan", "ui.break": "Podziel", @@ -1707,6 +2690,8 @@ "ui.cancel": "Anuluj", "ui.canvases": "Płótna", "ui.center": "Środek", + "ui.center_arc_follows_cursor": "Łuk ze środka podąża za kierunkiem kursora", + "ui.center_arc_follows_cursor_tip": "Łuk ze środka biegnie zgodnie lub przeciwnie do ruchu wskazówek zegara, tak jak kursor okrąża jego środek. Wyłączone: zawsze przeciwnie do ruchu wskazówek zegara od początku.", "ui.centerline": "Linia osiowa", "ui.chain": "Łańcuch", "ui.chamfer": "Faza", @@ -1715,6 +2700,7 @@ "ui.circle": "Okrąg", "ui.circular_pattern": "Szyk kołowy", "ui.clear": "Wyczyść", + "ui.clear_print_face": "Usuń powierzchnię druku", "ui.clear_recent": "Wyczyść ostatnie", "ui.clear_the_selection": "Wyczyść zaznaczenie", "ui.click_selects_whole_bodies": "Kliknięcie zaznacza całe bryły", @@ -1751,13 +2737,20 @@ "ui.construction": "Konstrukcyjne", "ui.construction.ribbon_label": "Linie pom.", "ui.context_menu": "Menu kontekstowe", + "ui.continuity_crease": "Załamanie", + "ui.continuity_curvature": "Krzywizna", + "ui.continuity_curvature_change": "Zmiana krzywizny", "ui.continuity_g0": "G0 załamanie", "ui.continuity_g1": "G1 styczność", "ui.continuity_g2": "G2 krzywizna", "ui.continuity_gap": "Szczelina", + "ui.continuity_position": "Położenie", + "ui.continuity_tangent": "Styczność", "ui.copy": "Kopiuj", "ui.corner": "Naroże", "ui.corners": "Naroża", + "ui.cosmetic_thread_markings": "Kosmetyczne oznaczenia gwintu", + "ui.cosmetic_thread_markings_help": "Pokazuje schematyczne oznaczenia na gwintowanych ściankach walcowych. Zmienia tylko wyświetlanie, nigdy projekt ani eksport.", "ui.counterbore": "Pogłębienie walcowe", "ui.countersink": "Pogłębienie stożkowe", "ui.create": "Utwórz", @@ -1788,8 +2781,11 @@ "ui.design_properties.part_number": "Numer części", "ui.design_properties.project": "Projekt", "ui.design_properties.revision": "Wersja", + "ui.design_saved": "Zapisano {path}", "ui.diameter": "Średnica", "ui.dimension": "Wymiar", + "ui.direct_interaction": "Bezpośrednia praca na modelu", + "ui.direct_interaction_note": "Pracuj na modelu bezpośrednio w widoku. Naciśnij płaską ścianę lub profil i pociągnij: w górę wyciąga, w dół w bryłę wycina, a ruch w bok ustawia wielkość kroku", "ui.direction": "Kierunek", "ui.display_quality": "Jakość wyświetlania", "ui.display_quality_coarse": "Zgrubna", @@ -1811,12 +2807,39 @@ "ui.easyprint_uploading": "Wysyłanie do Printables…", "ui.edit": "Edytuj", "ui.editJointLimits": "Edytuj limity złącza", + "ui.edit_in_place": "Edytuj w miejscu", + "ui.edit_in_place_after_turn": "Edycja zakończy się, gdy agent skończy swoją turę", + "ui.edit_in_place_agent_busy": "Agent wciąż pracuje w tym projekcie; spróbuj ponownie, gdy skończy swoją turę", + "ui.edit_in_place_already_queued": "Jedna edycja już czeka na koniec tury agenta", + "ui.edit_in_place_assembly_closed": "{name} nie jest już otwarty", + "ui.edit_in_place_banner": "Edycja w {name}", + "ui.edit_in_place_busy": "Najpierw zakończ lub anuluj to, co jest otwarte", + "ui.edit_in_place_none": "Żaden połączony projekt nie jest edytowany w miejscu", + "ui.edit_in_place_not_saved": "Część ma niezapisane zmiany; zapisz ją, aby zakończyć edycję", + "ui.edit_in_place_open_elsewhere": "{name} jest otwarty w innym SolidCraft", + "ui.edit_in_place_opens_after_turn": "Część otworzy się, gdy agent skończy swoją turę", + "ui.edit_in_place_refresh_dropped": "Złożenie zmieniło się w trakcie Aktualizuj łącza; uruchom je ponownie", + "ui.edit_in_place_refresh_stopped": "Aktualizuj łącza zatrzymało się przed zakończeniem", + "ui.edit_in_place_refreshing": "Aktualizowanie łączy w {name}…", + "ui.edit_in_place_save_first": "Najpierw zapisz złożenie: jego połączone projekty są wyszukiwane na podstawie jego pliku", + "ui.edit_in_place_save_waits": "W {name} trwa Aktualizuj łącza; zapisz go, gdy się zakończy", + "ui.edit_in_place_saved_elsewhere": "Część zapisano do innego pliku; złożenie nadal ma łącze do {name}", + "ui.edit_in_place_wait": "Poczekaj, aż zakończy się to, co działa w projekcie", "ui.edit_section_analysis": "Edytuj analizę przekroju", "ui.ellipse": "Elipsa", + "ui.emboss_wrap_note": "Ortogonalne profile liniowe styczne do jednego obsługiwanego walca owijają się automatycznie. Wybierz ściankę, aby wskazać cel.", "ui.end_radius": "Promień końcowy", "ui.end_scale": "Skala końcowa", "ui.entities": "Elementy", "ui.equal": "Równość", + "ui.equation_end": "Koniec", + "ui.equation_explicit": "Jawna", + "ui.equation_form": "Postać", + "ui.equation_note": "Zmienna jest zwykłą liczbą: sin(t) przyjmuje ją w radianach. Wynik bez jednostki jest w jednostce projektu.", + "ui.equation_parametric": "Parametryczna", + "ui.equation_x_of_t": "x(t)", + "ui.equation_y_of_t": "y(t)", + "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Promień zastępczy", "ui.expand": "Rozwiń", "ui.exportDxf": "Eksportuj DXF…", @@ -1824,7 +2847,12 @@ "ui.export_keymap_tip": "Klawisze, ulubione z okna S i pasek narzędzi, jako plik", "ui.extend": "Wydłuż", "ui.extent_type": "Typ zakresu", + "ui.extract_component": "Wyodrębnij do pliku…", + "ui.extract_design_changed": "Projekt zmienił się podczas wybierania pliku. Uruchom Wyodrębnij do pliku ponownie.", + "ui.extract_done": "Komponent jest teraz osobnym projektem, połączonym tutaj.", "ui.extrude": "Wyciągnięcie", + "ui.extrude_auto_to_object": "Wyciągaj do wybranego celu", + "ui.extrude_auto_to_object_tip": "W Wyciągnięciu, gdy profil jest wybrany, wybranie ściany, wierzchołka lub równoległej płaszczyzny poza jego płaszczyzną przełącza zakres na Do obiektu", "ui.factor": "Współczynnik", "ui.feature_history": "Historia funkcji", "ui.feature_options": "Opcje funkcji", @@ -1843,10 +2871,12 @@ "ui.flip": "Odwróć", "ui.format": "Format", "ui.frame_rate": "Liczba klatek", + "ui.frame_rate_details": "Szczegóły liczby klatek", "ui.front": "Przód", "ui.fully_constrained": "W pełni związany", "ui.function": "Funkcja", "ui.general": "Ogólne", + "ui.gpu_memory_lowered": "Karcie graficznej zabrakło pamięci: widok jest rysowany w niższej jakości.", "ui.graphics": "Grafika", "ui.graphics_custom": "Własne", "ui.graphics_performance": "Wydajność", @@ -1875,9 +2905,12 @@ "ui.heading_design": "PROJEKT", "ui.heading_draft": "POCHYLENIE", "ui.heading_edit": "EDYCJA", + "ui.heading_equation_curve": "KRZYWA Z RÓWNANIA", "ui.heading_extrude": "WYCIĄGNIĘCIE", "ui.heading_fillet": "ZAOKRĄGLENIE", + "ui.heading_finish_editing": "ZAKOŃCZ EDYCJĘ", "ui.heading_finish_sketch": "ZAKOŃCZ SZKIC", + "ui.heading_form": "FORMA", "ui.heading_front": "PRZÓD", "ui.heading_hole": "OTWÓR", "ui.heading_home": "WIDOK GŁÓWNY", @@ -1934,6 +2967,8 @@ "ui.hideOrigin": "Ukryj początek układu", "ui.hidePlanes": "Ukryj płaszczyzny", "ui.hideProfile": "Ukryj profil", + "ui.hide_origin_by_default": "Domyślnie ukrywaj początek układu", + "ui.hide_origin_note": "Nowe projekty zaczynają z ukrytym folderem Początek układu. Projekt zachowuje własne ustawienie, gdy go pokażesz lub ukryjesz.", "ui.history_back": "Cofnij o jeden krok", "ui.history_below_browser": "Pod przeglądarką", "ui.history_edge_hint": "kliknij dwukrotnie krawędź", @@ -1944,7 +2979,12 @@ "ui.history_marker_tip": "Znacznik historii: przeciągnij, aby cofnąć model; nowe funkcje trafiają tutaj", "ui.history_names": "Nazwy", "ui.history_play": "Odtwórz do końca", + "ui.history_play_button_hide": "Ukryj przycisk Odtwórz", + "ui.history_play_button_show": "Pokaż przycisk Odtwórz", + "ui.history_play_finish_action": "Zakończ bieżące działanie przed odtworzeniem Historii", + "ui.history_play_roll_back": "Przed odtworzeniem przesuń znacznik Historii wstecz", "ui.history_show_names": "Pokaż nazwy", + "ui.history_sketch_listed_under": "Pokazany pod {feature}", "ui.history_title": "Historia", "ui.history_toggle_names": "Pokaż lub ukryj nazwy funkcji", "ui.hole": "Otwór", @@ -1952,14 +2992,22 @@ "ui.hole_type": "Typ otworu", "ui.home": "Widok główny", "ui.homeView": "Widok główny", + "ui.horizontal_constraint": "Wiązanie poziome", "ui.horizontal_vertical": "Poziomo/pionowo", "ui.import_ellipsis": "Importuj…", "ui.infinite": "Nieskończona", "ui.insert": "Wstaw", + "ui.insert_design.browse": "Przeglądaj…", + "ui.insert_design.open_designs": "Otwarte projekty", + "ui.insert_design.saved_file": "{name} ma niezapisane zmiany, więc wstawiono jego zapisany plik. Zapisz go, a potem użyj Aktualizuj łącza, aby wprowadzić zmiany.", + "ui.insert_design.unsaved": "Niezapisane zmiany", "ui.inspect": "Sprawdź", + "ui.instances": "Wystąpienia", "ui.intersect": "Przytnij", "ui.isolate": "Izoluj", "ui.join": "Połącz", + "ui.joint_play": "▶ Odtwórz", + "ui.joint_stop": "■ Zatrzymaj", "ui.joints": "Złącza", "ui.keyboard_shortcuts": "Skróty klawiszowe", "ui.language": "Język", @@ -1969,10 +3017,15 @@ "ui.length_decimals": "Miejsca dziesiętne długości", "ui.light": "Jasny", "ui.line": "Linia", + "ui.link_copies": "Połącz identyczne kopie", + "ui.link_copies_keep": "Zachowaj", + "ui.link_copies_link": "Połącz", + "ui.link_copies_text": "Te komponenty tworzą te same bryły co {name}. Zamienić je w umiejscowienia jego łącza?", "ui.lock": "Zablokuj", "ui.loft": "Wyciągnięcie złożone", "ui.look_at": "Patrz na", "ui.look_at_anim_desc": "Widok osi, Patrz na, Widok główny i Dopasuj", + "ui.major_radius": "Promień główny", "ui.manipulator_free_alt": "Swobodne przeciąganie manipulatora także z Alt/Option", "ui.manipulator_free_alt_tip": "Wł.: Alt/Option lub Ctrl/Cmd na strzałkach wyciągnięcia / uchwytu wyłącza przyciąganie wartości. Wył.: tylko Ctrl/Cmd.", "ui.manufacture": "Wytwarzanie", @@ -2002,8 +3055,10 @@ "ui.mesh_format_3mf": "3MF", "ui.mesh_format_3mf_tagged": "3MF ze znacznikami ścian", "ui.mesh_format_stl": "STL", + "ui.minor_radius": "Promień mniejszy", "ui.mirror": "Lustro", "ui.mirror_line": "Linia odbicia", + "ui.modifiers_either": "{first} lub {second}", "ui.move": "Przesuń", "ui.multiple": "Wiele", "ui.named_views": "Widoki nazwane", @@ -2030,6 +3085,7 @@ "ui.one_side": "Jedna strona", "ui.open": "Otwórz", "ui.open_ends_tip": "Niczego nie dotyka", + "ui.open_linked_design": "Otwórz połączony projekt", "ui.open_preferences": "Otwórz preferencje", "ui.open_recent": "Otwórz ostatnie", "ui.operation": "Operacja", @@ -2050,6 +3106,11 @@ "ui.paste": "Wklej", "ui.path": "Ścieżka", "ui.pattern_on_path": "Szyk wzdłuż ścieżki", + "ui.perforate_margin_default": "od średnicy", + "ui.perforate_pitch": "Rozstaw", + "ui.perforate_square": "Kwadratowy", + "ui.perforate_staggered": "Przestawny (60°)", + "ui.perforate_title": "PERFORACJA", "ui.perpendicular": "Prostopadłość", "ui.perspective_view": "Widok perspektywiczny", "ui.pinToShortcuts": "Przypnij do skrótów", @@ -2064,21 +3125,49 @@ "ui.plugins": "Wtyczki", "ui.plugins_desktop": "Wtyczki są dostępne w aplikacji desktopowej.", "ui.plugins_empty": "Brak zainstalowanych wtyczek.", + "ui.plugins_none": "Żadna wtyczka nie pasuje do wyszukiwania.", "ui.plugins_note": "Każda wtyczka to folder w {path} z plikiem plugin.json. SolidCraft odczytuje ten plik i nie uruchamia żadnego kodu z folderu. Wyłączenie wtyczki nie odinstalowuje jej.", + "ui.plugins_search": "Szukaj wtyczek", "ui.plugins_skipped": "Nie udało się odczytać folderów: {count}.", "ui.plugins_version": "{version}", "ui.point": "Punkt", + "ui.point_cloud_auto_range": "Zakres automatyczny", + "ui.point_cloud_color_by": "Koloruj według", + "ui.point_cloud_file_colors": "Kolory z pliku", + "ui.point_cloud_height_high": "Najwyżej", + "ui.point_cloud_height_low": "Najniżej", + "ui.point_cloud_no_file_colors": "Plik nie zawiera kolorów", + "ui.point_cloud_single_color": "Jeden kolor", + "ui.point_cloud_size": "Rozmiar punktu", + "ui.point_cloud_units": "Jednostki pliku", "ui.point_under_the_cursor": "Punkt pod kursorem", "ui.points": "Punkty", "ui.polygon": "Wielokąt", "ui.preferences": "Preferencje", "ui.press_a_key": "naciśnij klawisz…", + "ui.print_face_body_not_sent": "Bryła tej powierzchni nie jest wysyłana: najpierw dodaj ją do Bryły", + "ui.print_face_cleared": "{body}: usunięto powierzchnię druku", + "ui.print_face_input": "Powierzchnia druku", + "ui.print_face_pick": "Wybierz płaską powierzchnię bryły, aby ustawić ją jako powierzchnię druku", + "ui.print_face_set": "{body}: ustawiono powierzchnię druku; Wyślij do slicera kładzie bryłę na niej", "ui.profile": "Profil", "ui.profile_plane": "Płaszczyzna profilu", "ui.profiles": "Profile", "ui.project": "Rzutuj", "ui.project_face_edges_sketch": "Rzutuj krawędzie ściany do nowych szkiców", "ui.properties": "Właściwości", + "ui.properties.copy_matrix": "Kopiuj macierz", + "ui.properties.first_moments": "Momenty statyczne", + "ui.properties.inertia": "Moment bezwładności", + "ui.properties.inertia_note": "Względem środka masy, w osiach globalnych (g·{unit}²)", + "ui.properties.inertia_unavailable": "Niedostępne: siatka bryły nie jest zamknięta.", + "ui.properties.inertia_x": "Ixx, Ixy, Ixz", + "ui.properties.inertia_y": "Iyx, Iyy, Iyz", + "ui.properties.inertia_z": "Izx, Izy, Izz", + "ui.properties.measuring": "Pomiar…", + "ui.properties.measuring_failed": "Pomiar zatrzymał się przed zakończeniem.", + "ui.properties.principal_axis": "Oś główna {number}", + "ui.properties.principal_moments": "Główne momenty bezwładności", "ui.pull_direction": "Kierunek wyjmowania", "ui.quality": "Jakość", "ui.quantity": "Liczba", @@ -2092,6 +3181,9 @@ "ui.rectangle": "Prostokąt", "ui.rectangular_pattern": "Szyk prostokątny", "ui.redo": "Ponów", + "ui.reference_1": "Odniesienie 1", + "ui.reference_2": "Odniesienie 2", + "ui.reference_distance": "Odległość odniesienia", "ui.relink_design_changed": "Zespół zmienił się podczas wyboru źródła. Uruchom ponownie Połącz ponownie ze źródłem.", "ui.relink_done": "Ponownie połączono źródło dla wszystkich wystąpień.", "ui.relink_not_linked": "Ten komponent nie jest połączony z projektem źródłowym.", @@ -2102,6 +3194,8 @@ "ui.render": "Renderowanie", "ui.renderer": "Renderer", "ui.repeat": "Powtórz", + "ui.repeat_nothing": "Nie ma jeszcze czego powtórzyć: najpierw uruchom narzędzie lub okno.", + "ui.replace_with_link_done": "Kopie są teraz umiejscowieniami połączonego projektu.", "ui.report_a_bug": "Zgłoś błąd", "ui.reset": "Resetuj", "ui.reset_all": "Resetuj wszystko", @@ -2110,7 +3204,12 @@ "ui.restore_defaults": "Przywróć domyślne", "ui.reverse_horizontal_pan_direction": "Odwróć kierunek przesuwania w poziomie", "ui.reverse_horizontal_pan_tip": "Przewijanie w poziomie dwoma palcami i kółko kciukowe przesuwają w przeciwną stronę", + "ui.reverse_trackpad_orbit_direction": "Odwróć kierunek obracania gładzikiem", + "ui.reverse_trackpad_orbit_tip": "Shift z przewijaniem dwoma palcami obraca widok w przeciwną stronę", + "ui.reverse_vertical_pan_direction": "Odwróć kierunek przesuwania w pionie", + "ui.reverse_vertical_pan_tip": "Przewijanie w pionie dwoma palcami przesuwa w przeciwną stronę", "ui.reverse_zoom_direction": "Odwróć kierunek powiększania", + "ui.revolutions": "Obroty", "ui.revolve": "Obrót", "ui.ribbon_exit": "Wyjdź", "ui.ribbon_labels": "Pokazuj tekst pod ikonami wstążki", @@ -2119,6 +3218,7 @@ "ui.right": "Prawy", "ui.save": "Zapisz", "ui.save_as": "Zapisz jako", + "ui.save_mesh_no_slicer_open": "Nie znaleziono slicera: wybierz Niestandardowy… i wskaż program slicera", "ui.save_mesh_pick_bodies": "Zaznacz bryły do zapisania", "ui.saved_to": "Zapisano {path}", "ui.sbox_pin": "Przypnij na górze okna S", @@ -2126,6 +3226,7 @@ "ui.scale": "Skala", "ui.second_rail": "Druga prowadnica", "ui.section_analysis": "Analiza przekroju", + "ui.section_size": "Rozmiar przekroju", "ui.select": "Zaznacz", "ui.selectOther": "Wybierz inny…", "ui.selectTangentChain": "Zaznacz łańcuch styczny", @@ -2135,9 +3236,19 @@ "ui.selection_shift_add_only": "Shift+kliknięcie tylko dodaje", "ui.selection_shift_add_only_tip": "Wł.: Shift dodaje elementy, Ctrl/Cmd przełącza. Wył. (domyślnie): Shift i Ctrl/Cmd przełączają.", "ui.send": "Wyślij", + "ui.send_to_slicer_unavailable": "Wyślij do slicera wymaga aplikacji desktopowej: przeglądarka nie może uruchomić programu", "ui.sent_to_slicer": "Wysłano do {slicer}", + "ui.sent_to_slicer_copy": "Wysłano do {slicer} jako {file}, ponieważ pierwszy plik jest tam nadal otwarty", "ui.sheet_gap": "Szczelina", "ui.shell": "Skorupa", + "ui.shortcut_capture_add_key": "Dodaj jeden zwykły klawisz. Escape anuluje.", + "ui.shortcut_capture_hint": "Kliknij przypisanie, a potem naciśnij modyfikatory i jeden klawisz. Modyfikatory dodaj w ciągu sekundy; puść wszystkie klawisze, aby potwierdzić. Escape anuluje.", + "ui.shortcut_capture_press": "Naciśnij modyfikatory i jeden klawisz. Escape anuluje.", + "ui.shortcut_capture_release": "Puść wszystkie klawisze, aby potwierdzić. Escape anuluje.", + "ui.shortcut_capture_settling": "Potwierdzanie skrótu… Escape anuluje.", + "ui.shortcut_cycles_modes": "Ponowne naciśnięcie skrótu narzędzia przełącza jego tryb", + "ui.shortcut_cycles_modes_tip": "Przed pierwszym punktem ponowne naciśnięcie skrótu narzędzia szkicu przełącza kolejno jego tryby tworzenia. Wyłączone: uruchamia narzędzie od nowa.", + "ui.shortcut_multiple_keys": "Użyj modyfikatorów i tylko jednego innego klawisza. Kliknij przypisanie, aby spróbować ponownie.", "ui.show": "Pokaż", "ui.showAll": "Pokaż wszystko", "ui.showAllBodies": "Pokaż wszystkie bryły", @@ -2156,12 +3267,25 @@ "ui.sketch": "Szkic", "ui.sketch_dimension": "Wymiar szkicu", "ui.sketch_grid": "Siatka szkicu", + "ui.sketch_intersect_geometry": "Geometria", + "ui.sketch_intersect_projection_link": "Powiązanie rzutu", + "ui.sketch_intersect_selection_filter": "Filtr zaznaczania", "ui.sketch_modifiers": "Modyfikatory szkicu", + "ui.sketch_project_geometry": "Geometria", "ui.sketch_scale": "Skala szkicu", "ui.sketches": "Szkice", "ui.slice": "Przetnij", "ui.slicer": "Slicer", "ui.slicer_delete_tip": "{program}\nNaciśnij Delete, aby usunąć go z listy", + "ui.slicer_lost": "{slicer} został uruchomiony, ale nie można go ponownie znaleźć, aby wysłać plik. Plik jest zapisany w {path}: otwórz go stamtąd.", + "ui.slicer_no_file": "{slicer} jest gotowy, ale nie ma pliku do wysłania.", + "ui.slicer_no_response": "{slicer} nie odpowiedział na czas. Plik jest już zapisany w {path}: wyślij go ponownie, gdy slicer się uruchomi.", + "ui.slicer_resend_hint": "Ponowne wysłanie zastępuje plik otwarty w slicerze.", + "ui.slicer_single_instance": "Otwieraj pliki w już uruchomionym slicerze", + "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer i Cura wczytują plik w otwartym oknie, zamiast uruchamiać kolejne. Inne slicery są uruchamiane normalnie. PrusaSlicer 3.0 zawsze tak robi: jego program uruchamiający nie przyjmuje pliku w inny sposób.", + "ui.slicer_starting": "Uruchamianie {slicer}…", + "ui.slicer_still_starting": "Nadal czekam na uruchomienie {slicer}. Nic więcej nie wysłano.", + "ui.slicer_stl_fallback": "Nie udało się zapisać 3MF, więc to jest STL.", "ui.slot": "Rowek", "ui.smooth": "Gładkie", "ui.smooth_wheel_zoom": "Płynne powiększanie kółkiem", @@ -2177,6 +3301,9 @@ "ui.start": "Start", "ui.start_over": "Zacznij od nowa", "ui.start_page": "Strona startowa", + "ui.step_values": "Zmieniaj wartości klawiszami strzałek i kółkiem", + "ui.step_values_tip": "W polu wartości, w którym piszesz, strzałki w górę i w dół zmieniają zwykłą liczbę o 1 (Shift: 10, Alt: 0,1), podobnie kółko myszy nad polem. Wyrażenia pozostają tak, jak je wpisano.", + "ui.stitch_tolerance_hint": "ciasna", "ui.stretch": "Rozciągnij", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Tylko gdy widok jest nieruchomy", @@ -2195,6 +3322,7 @@ "ui.tab_manage": "Zarządzanie", "ui.tab_sheet_metal": "Blacha", "ui.tab_view": "Widok", + "ui.tab_weldments": "Konstrukcje spawane", "ui.tangent": "Styczność", "ui.taper_angle": "Kąt pochylenia", "ui.tapped": "Gwintowany", @@ -2210,11 +3338,15 @@ "ui.tip_angle": "Kąt wierzchołkowy", "ui.to_object": "Do obiektu", "ui.tool_direction": "Kierunek narzędzia", + "ui.toolbar_tabs_hidden": "Wszystkie karty paska narzędzi są ukryte. Kliknij + lub kliknij tutaj prawym przyciskiem, aby pokazać jedną.", "ui.top": "Góra", + "ui.top_diameter": "Średnica górna", + "ui.top_radius": "Promień górny", "ui.torus": "Torus", "ui.total_angle": "Kąt całkowity", "ui.trackpad_pan_tip": "Gesty na gładziku przesuwają (wyłączone: powiększają jak kółko); kółko myszy powiększa, kółko kciukowe przesuwa w bok, szczypanie zawsze powiększa", "ui.trim": "Przytnij", + "ui.turn_up_axis": "Obróć oś pionową", "ui.twist": "Skręcenie", "ui.two_finger_scroll_pans": "Przewijanie dwoma palcami przesuwa", "ui.two_sides": "Dwie strony", @@ -2231,12 +3363,34 @@ "ui.up_axis_note": "Która oś wskazuje górę w widokach (widok osi, Widok główny, Patrz na). Projekty pozostają bez zmian.", "ui.updateToCurrentView": "Aktualizuj do bieżącego widoku", "ui.upload": "Wyślij", + "ui.vertical_constraint": "Wiązanie pionowe", + "ui.view_angles": "Kąty widoku", + "ui.view_angles_convention": "Stopnie wokół osi pionowej. Odchylenie 0° to widok z przodu, 90° z lewej, −90° z prawej, 180° z tyłu; pochylenie 90° to widok z góry; dodatnie przechylenie obraca model zgodnie z ruchem wskazówek zegara.", + "ui.view_angles_help": "Pokazuje pochylenie, odchylenie i przechylenie widoku w stopniach oraz jego rzutowanie pod wskaźnikiem orientacji. Kliknij odczyt, aby wpisać dokładne kąty.", + "ui.view_angles_ortho": "Orto", + "ui.view_angles_persp": "Persp", + "ui.view_angles_pitch": "Pochylenie", + "ui.view_angles_readout": "Pochylenie {pitch} · Odchylenie {yaw} · Przechylenie {roll}", + "ui.view_angles_roll": "Przechylenie", + "ui.view_angles_yaw": "Odchylenie", "ui.view_centre": "Środek widoku", + "ui.viewport_status_clear": "Wyłącz {name}", + "ui.viewport_status_clear_hint": "Wyłącz {name} · Esc", + "ui.viewport_status_key": "Pokaż legendę dla {name}", + "ui.viewport_status_minimum_radius": "Promień minimalny", + "ui.viewport_status_pairs": "Pary: {count}", + "ui.viewport_status_stripes": "Pasy: {count}", + "ui.viewport_theme_follow": "Zgodnie z motywem", "ui.visual_shaded_hidden_edges": "Cieniowany z krawędziami niewidocznymi", "ui.visual_shaded_with_edges": "Cieniowany z krawędziami", "ui.visual_style": "Styl wizualny", "ui.visual_wireframe": "Model krawędziowy", + "ui.wheel_zoom_speed": "Szybkość powiększania kółkiem myszy", "ui.width": "Szerokość", + "ui.window_system": "System okien", + "ui.window_system_auto": "Automatycznie", + "ui.window_system_wayland": "Wayland", + "ui.window_system_x11": "X11", "ui.workspace": "środowisko pracy", "ui.workspace_animation_description": "Widoki rozstrzelone, badania ruchu i scenorysy", "ui.workspace_available": "Dostępne", @@ -2262,10 +3416,12 @@ "update.button": "Aktualizuj", "update.button_version": "Aktualizuj do {version}", "update.check_automatically": "Automatycznie sprawdzaj aktualizacje", + "update.check_for_updates": "Sprawdź aktualizacje", "update.check_now": "Sprawdź teraz", + "update.check_unavailable": "Sprawdzanie aktualizacji nie jest dostępne dla tej instalacji.", "update.checking": "Sprawdzanie…", "update.copy": "Kopiuj", - "update.dmg_opened": "Obraz dysku jest otwarty i zweryfikowany: przeciągnij SolidCraft do folderu Aplikacje, zastępując starą kopię, a następnie uruchom SolidCraft ponownie.", + "update.dmg_opened": "Obraz dysku jest otwarty i zweryfikowany: zakończ SolidCraft, przeciągnij nowy SolidCraft do folderu Aplikacje, zastępując starą kopię, a następnie ponownie otwórz SolidCraft.", "update.download": "Pobierz", "update.download_open": "Pobierz i otwórz", "update.downloading": "Pobieranie i weryfikacja… {done} z {total} MB", @@ -2276,12 +3432,18 @@ "update.installed": "SolidCraft {version} jest zainstalowany. Uruchom ponownie, aby go używać.", "update.installer_started": "Instalator uruchomi się po zamknięciu SolidCraft.", "update.later": "Przypomnij później", + "update.managed": "Dostępna aktualizacja: zaktualizuj SolidCraft w {manager}", "update.no_notes": "To wydanie nie ma opisu zmian.", "update.package_hint": "Ta kopia pochodzi z {kind}. Pobierz nowy pakiet, a następnie zainstaluj go poleceniem:", "update.prefs_dev": "To jest wersja deweloperska ({version}): nie sprawdza aktualizacji.", "update.prefs_flatpak": "Flatpak aktualizuje tę kopię ({version}): uruchom {command} lub użyj centrum oprogramowania. SolidCraft nie sprawdza aktualizacji.", "update.prefs_label": "Aktualizacje", + "update.prefs_managed": "To jest SolidCraft {version}, zarządzany przez {manager}. Sprawdzanie pyta GitHuba o najnowsze wydanie i nie wysyła nic więcej; zaktualizuj SolidCraft w {manager}.", "update.prefs_note": "To jest SolidCraft {version} ({kind}). Sprawdzanie pyta GitHuba o najnowsze wydanie i nie wysyła nic więcej.", + "update.prefs_web": "Odśwież stronę, aby pobrać najnowszą aplikację internetową. Jeśli sieć jest niedostępna lub aktualizacja nie zdąży się pobrać, otworzy się zapisana wersja; trwające pobieranie będzie kontynuowane przy następnym odświeżeniu.", + "update.refresh_checking": "Sprawdzanie najnowszego wydania…", + "update.refresh_fallback": "Nie udało się sprawdzić nowszego wydania; aktualizacja do wcześniej znalezionej wersji {version}.", + "update.refresh_selected": "Aktualizacja do wersji {version}.", "update.release_page": "Otwórz stronę wydania", "update.restart": "Uruchom ponownie teraz", "update.restart_later": "Później", @@ -2292,5 +3454,17 @@ "update.up_to_date": "SolidCraft jest aktualny.", "update.update_now": "Aktualizuj teraz", "update.you_have": "Masz wersję {version}.", - "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ wybierz · Enter / Tab uzupełnij · Esc zamknij" + "use a positive nominal diameter and a pitch smaller than it": "użyj dodatniej średnicy nominalnej i mniejszego od niej skoku", + "values must be finite numbers": "wartości muszą być skończonymi liczbami", + "values must be numbers or expressions": "wartości muszą być liczbami lub wyrażeniami", + "view.auto_ortho_faces": "Perspektywa podczas obracania, widok ortogonalny na ścianach", + "view.render_inspector": "Inspektor renderowania", + "web.files.insert_drawings_hint": "Pliki CAD, siatki, DXF lub SVG do otwartego projektu", + "web.files.insert_stored_drawings_hint": "Do otwartego projektu (pliki CAD, siatki, DXF, SVG)", + "web.open_full": "Otwórz w SolidCraft", + "web.open_link": "Otworzyć połączony projekt?", + "web.open_link_confirm": "Są niezapisane zmiany. Otworzyć połączony projekt w nowej karcie?", + "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ wybierz · Enter / Tab uzupełnij · Esc zamknij", + "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ wybierz · Enter stosuje to, co wpisano · Esc zamyka", + "⌘Enter continues on GitHub.": "⌘Enter przechodzi dalej na GitHubie." } diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index d0bea463d..a183538e4 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -606,6 +606,8 @@ "cmd.appearance_library": "Biblioteca de aparências", "cmd.appearance_list": "Listar aparências", "cmd.assembly_bom": "Lista de materiais", + "cmd.assembly_mass_properties": "Propriedades de massa", + "cmd.body.print_face": "Face de impressão", "cmd.body_rename": "Renomear corpo", "cmd.browser_group": "Novo grupo", "cmd.browser_move": "Mover itens do navegador", @@ -1217,6 +1219,8 @@ "prefs.axis": "Eixo", "prefs.bottom": "Embaixo", "prefs.browser": "Navegador", + "prefs.browser_components_open": "Componentes começam abertos", + "prefs.browser_components_open_note": "Cada componente no navegador começa aberto, como antes, em vez de fechado até que você o abra.", "prefs.built_in": "Integrado", "prefs.button_left": "Arrastar com o esquerdo", "prefs.button_middle": "Arrastar com o meio", @@ -1292,6 +1296,8 @@ "prefs.orientation": "Orientação", "prefs.overall_speed": "Velocidade geral", "prefs.preview_choices": "Prévia das suas escolhas", + "prefs.print_face_highlight": "Destaque da face de impressão", + "prefs.print_face_highlight_tip": "Intensidade da cor e do contorno da face de impressão de um corpo na vista. 0 % não mostra destaque.", "prefs.quality_default": "padrão", "prefs.quality_fastest": "mais rápido", "prefs.quality_slowest": "mais lento", @@ -1571,6 +1577,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Gire a tampa no sentido anti-horário, segure e solte.", "ui.3d_mouse_switch_cap": "Calibrar como retorno ao centro", "ui.3d_mouse_switch_trackball": "Calibrar como trackball", + "ui.3d_mouse_use_direct": "Usar driver direto", + "ui.3d_mouse_use_direct_tip": "Ler o mouse 3D diretamente (hidraw) em vez de pelo spacenavd.", "ui.3d_mouse_view_axis": "Eixo da vista", "ui.3d_mouse_view_off": "Desligado", "ui.3d_mouse_view_off_tip": "O perfil do driver do mouse 3D desliga este eixo, então o movimento dele não move a vista. Escolher aqui o movimento de outro eixo troca os dois, e esse movimento deixa de mover a vista.", @@ -1840,6 +1848,7 @@ "ui.circle": "Círculo", "ui.circular_pattern": "Padrão circular", "ui.clear": "Limpar", + "ui.clear_print_face": "Limpar face de impressão", "ui.clear_recent": "Limpar recentes", "ui.clear_the_selection": "Limpar a seleção", "ui.click_selects_whole_bodies": "O clique seleciona corpos inteiros", @@ -1876,10 +1885,15 @@ "ui.construction": "Construção", "ui.construction.ribbon_label": "Linhas aux.", "ui.context_menu": "Menu de contexto", + "ui.continuity_crease": "Vinco", + "ui.continuity_curvature": "Curvatura", + "ui.continuity_curvature_change": "Variação de curvatura", "ui.continuity_g0": "G0 vinco", "ui.continuity_g1": "G1 tangente", "ui.continuity_g2": "G2 curvatura", "ui.continuity_gap": "Folga", + "ui.continuity_position": "Posição", + "ui.continuity_tangent": "Tangente", "ui.copy": "Copiar", "ui.corner": "Canto", "ui.corners": "Cantos", @@ -2085,6 +2099,7 @@ "ui.infinite": "Infinita", "ui.insert": "Inserir", "ui.inspect": "Inspecionar", + "ui.instances": "Instâncias", "ui.intersect": "Interseção", "ui.isolate": "Isolar", "ui.join": "Unir", @@ -2198,6 +2213,11 @@ "ui.polygon": "Polígono", "ui.preferences": "Preferências", "ui.press_a_key": "pressione uma tecla…", + "ui.print_face_body_not_sent": "O corpo dessa face não está sendo enviado: adicione-o primeiro a Corpos", + "ui.print_face_cleared": "{body}: face de impressão removida", + "ui.print_face_input": "Face de impressão", + "ui.print_face_pick": "Selecione uma face plana de um corpo sólido para torná-la a face de impressão", + "ui.print_face_set": "{body}: face de impressão definida; Enviar ao fatiador apoia o corpo sobre ela", "ui.profile": "Perfil", "ui.profile_plane": "Plano do perfil", "ui.profiles": "Perfis", @@ -2388,10 +2408,12 @@ "update.button": "Atualizar", "update.button_version": "Atualizar para {version}", "update.check_automatically": "Verificar atualizações automaticamente", + "update.check_for_updates": "Verificar atualizações", "update.check_now": "Verificar agora", + "update.check_unavailable": "A verificação de atualizações não está disponível para esta instalação.", "update.checking": "Verificando…", "update.copy": "Copiar", - "update.dmg_opened": "A imagem de disco está aberta e verificada: arraste o SolidCraft para Aplicativos, substituindo a cópia antiga, e reinicie o SolidCraft.", + "update.dmg_opened": "A imagem de disco está aberta e verificada: encerre o SolidCraft, arraste o novo SolidCraft para Aplicativos, substituindo a cópia antiga, e abra o SolidCraft novamente.", "update.download": "Baixar", "update.download_open": "Baixar e abrir", "update.downloading": "Baixando e verificando… {done} de {total} MB", diff --git a/assets/locales/ro.json b/assets/locales/ro.json index f1aef5744..61c2342e9 100644 --- a/assets/locales/ro.json +++ b/assets/locales/ro.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "SUPRAFAȚĂ DE RACORDARE", "BOUNDARY SURFACE": "SUPRAFAȚĂ LIMITĂ", "BROWSER": "NAVIGATOR", + "Back to the original order": "Înapoi la ordinea inițială", "Ball": "Sferică", "Bar": "Bară", "Base Center": "Centrul bazei", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Proiectele deschise sau salvate apar aici.", "Determined by To Object. Choose Angle to edit the angular extent.": "Determinat de Până la obiect. Alegeți Unghi pentru a edita întinderea unghiulară.", "Diameter": "Diametru", + "Did this assembly open the wrong way up?": "Acest ansamblu s-a deschis cu orientarea greșită?", + "Did this part open the wrong way up?": "Această piesă s-a deschis cu orientarea greșită?", "Dimension new shapes": "Cotează formele noi", "Direction": "Direcție", "Discard": "Renunță", @@ -474,6 +477,7 @@ "Rectangular": "Dreptunghiular", "Rectangular Tube": "Tub dreptunghiular", "Reference face": "Față de referință", + "Reference plane": "Plan de referință", "Relief Depth": "Adâncime relief", "Relief Width": "Lățime relief", "Remove Tools": "Elimină sculele", @@ -553,6 +557,7 @@ "Section": "Secțiune", "Section (optional)": "Secțiune (opțional)", "Section position": "Poziția secțiunii", + "Sections": "Secțiuni", "Sections (one sketch each)": "Secțiuni (câte o schiță)", "Select Other": "Selectează altul", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Selectează altul: țineți apăsat butonul stâng nemișcat pe model (sau clic dreapta › Selectează altul…) pentru a lista tot ce se află sub cursor; faceți clic din nou în același loc pentru a selecta următorul element. Dublu clic pe butonul din mijloc pentru a merge Acasă (Preferințe › Navigare).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Agățare la centrele fețelor și muchiilor", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft nu poate trimite rapoarte direct. Trimiteți raportul pe GitHub; nu este necesar niciun token în aplicație.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft s-a închis înainte ca aceste proiecte să fie salvate. Ultima lor salvare automată poate fi deschisă.", + "Sort A to Z": "Sortează de la A la Z", + "Sort Z to A": "Sortează de la Z la A", "Spacing 2 must be a non-zero number": "Spațierea 2 trebuie să fie un număr nenul", "Spacing must be a non-zero number": "Spațierea trebuie să fie un număr nenul", "Specialise": "Specializează", @@ -601,6 +608,7 @@ "Square": "Pătrat", "Stand it up": "Ridică-l în picioare", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Ridică-l în picioare: un sfert de rotație în jurul lui X, ca o singură operație de mutare ce poate fi anulată.", + "Stand this assembly up?": "Ridicați acest ansamblu în picioare?", "Stand this part up?": "Ridicați această piesă în picioare?", "Start angle": "Unghi de început", "Start bulge": "Bombare inițială", @@ -772,6 +780,8 @@ "at the face": "la față", "bom.group_children": "Subpiesele în rândul piesei lor", "browser.body_name": "Corp{number}", + "browser.calibrate_click_a": "Faceți clic pe imagine pentru Punctul A sau tastați coordonatele acestuia.", + "browser.calibrate_click_b": "Faceți clic pe imagine pentru Punctul B sau tastați coordonatele acestuia.", "browser.calibrate_title": "Calibrare: {name}", "browser.capture_many": "{count} componente au fost mutate, dar pozițiile lor nu sunt capturate.", "browser.capture_note": "Captura păstrează noua poziție; Revenire o readuce.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (atașare pierdută)", "browser.sketch_editing": "{name} (în editare)", "browser.sketch_name": "Schița{number}", + "browser.sketches_to_parts_already_in_part": "deja în piesa lor", + "browser.sketches_to_parts_design_body": "pe un corp al proiectului însuși", + "browser.sketches_to_parts_moved": "Au fost mutate {moved} schițe în piesa pe care se află", + "browser.sketches_to_parts_no_exact_attachment": "pe o față fără atașare exactă", + "browser.sketches_to_parts_not_on_face": "nu pe fața unei piese", + "browser.sketches_to_parts_part_missing": "piesa lor nu mai există", + "browser.sketches_to_parts_result": "Au fost mutate {moved} schițe în piesa pe care se află; {stayed} au rămas pe loc: {why}", "browser.units": "Unități: {units}", "cam.flat": "Față plană", "cam.follower": "Tachet", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Preia aspectul", "cmd.appearance_replace": "Înlocuiește aspectul", "cmd.assembly_bom": "Listă de materiale", + "cmd.assembly_mass_properties": "Proprietăți de masă", + "cmd.body.print_face": "Față de imprimare", "cmd.body_rename": "Redenumește corpul", "cmd.browser_collapse_all": "Restrânge tot", "cmd.browser_expand_all": "Extinde tot", @@ -842,6 +861,7 @@ "cmd.component_extract": "Extrage în fișier", "cmd.component_finish_edit": "Finalizează editarea", "cmd.component_from_bodies": "Creează componente din corpuri", + "cmd.component_hide_history": "Ascunde istoricul componentei", "cmd.component_insert_design": "Inserează proiect", "cmd.component_links": "Listează legăturile", "cmd.component_list": "Listează componentele", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Mută corpurile în componentă", "cmd.component_move_features": "Mută operațiile în componentă", "cmd.component_move_sketches": "Mută schițele în componentă", + "cmd.component_move_sketches_to_parts": "Mută schițele în piesele lor", "cmd.component_paste_from_design": "Lipește din alt proiect", "cmd.component_paste_new": "Lipește ca nou", "cmd.component_properties": "Proprietățile fizice ale componentei", @@ -857,6 +878,7 @@ "cmd.component_rename": "Redenumește componenta", "cmd.component_replace_with_link": "Înlocuiește cu legătură", "cmd.component_revert_position": "Revino la poziție", + "cmd.component_show_history": "Afișează istoricul componentei", "cmd.component_unlock": "Deblochează conținutul", "cmd.component_update_links": "Actualizează legăturile", "cmd.config_activate": "Activează configurația", @@ -867,6 +889,7 @@ "cmd.config_rule": "Regulă de configurație", "cmd.config_rules": "Reguli de configurație", "cmd.config_table": "Afișează tabelul de configurații", + "cmd.construct.plane.axis_point": "Plan printr-o axă și un punct", "cmd.construct_axis_edge": "Axă prin muchie", "cmd.construct_axis_normal_to_face": "Axă perpendiculară pe față", "cmd.construct_axis_through_cylinder": "Axă prin cilindru/con/tor", @@ -915,6 +938,11 @@ "cmd.explode_show": "Afișează vederea explodată", "cmd.expr_evaluate": "Evaluează expresia", "cmd.face_delete": "Șterge fața", + "cmd.file.export_3mf": "Exportă 3MF", + "cmd.file.export_obj": "Exportă OBJ", + "cmd.file.export_step": "Exportă STEP", + "cmd.file.export_stl": "Exportă STL", + "cmd.file.export_urdf": "Exportă URDF", "cmd.file_export": "Exportă", "cmd.file_insert_mesh": "Inserează plasă", "cmd.file_insert_step": "Inserează STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Activează culorile componentelor", "cmd.inspect_colored_components_disable": "Dezactivează culorile componentelor", "cmd.inspect_compare": "Compară corpurile", + "cmd.inspect_compare_picture": "Compară imaginea", "cmd.inspect_continuity": "Analiza continuității", "cmd.inspect_curvature_comb": "Analiza pieptenelui de curbură", "cmd.inspect_curvature_map": "Analiza hărții de curbură", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Editează norul de puncte", "cmd.pointcloud_insert": "Inserează nor de puncte", "cmd.pointcloud_list": "Nori de puncte", + "cmd.render.compare.divider": "Mută separatorul comparației de randare", + "cmd.render.result.discard": "Renunță la rezultatul de randare", + "cmd.render.result.select": "Alege rezultatul de randare", "cmd.render_aging_describe": "Îmbătrânirea stratificată a suprafeței", "cmd.render_backends": "Motoare de randare", "cmd.render_batch": "Randează toate cadrele", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline cu puncte de control (grad 5)", "cmd.sketch_spline_fit_point": "Spline cu puncte de potrivire", "cmd.sketch_spline_insert_point": "Adaugă punct la spline", + "cmd.sketch_spline_remove_point": "Elimină punct din spline", "cmd.sketch_spline_reverse": "Inversează direcția spline-ului", "cmd.sketch_spun_profile": "Profil rotit", "cmd.sketch_toggle_diameter": "Comută rază / diametru", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Mută marcajul cronologiei", "cmd.timeline_stop": "Oprește istoricul", "cmd.timeline_suppress": "Suprimă operația", + "cmd.ui.assistant": "Afișează/Ascunde asistentul", "cmd.view.render_browser": "Navigator de randare", "cmd.view.render_dock": "Mută panoul de randare", "cmd.view.render_focus": "Vizualizare de randare concentrată", + "cmd.view.status_details": "Detalii de stare ale ferestrei de vizualizare", "cmd.view.status_items": "Elemente de stare ale ferestrei de vizualizare", "cmd.view_ambient_occlusion": "Ocluzie ambientală", "cmd.view_angle_readout": "Unghiuri de vizualizare", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Instrument de navigare", "cmd.view_top": "Vizualizare de sus", "cmd.view_visual_style": "Stil vizual", + "color.blue": "Albastru", "color.copy": "Clic pentru a copia valorile culorii", "color.edit": "Clic pentru a edita culoarea", "color.gamma": "Se afișează valorile culorii în spațiul gamma 0-255", + "color.green": "Verde", "color.hex": "Hex", "color.hex_help": "Introduceți #rrggbb sau #rrggbbaa; cu șase cifre se păstrează opacitatea", "color.hex_hint": "#rrggbb", "color.hue": "Nuanță", "color.linear": "Se afișează valorile culorii în spațiul liniar 0-1", + "color.recent": "Culori recente", + "color.recent_help": "Culorile pe care le alegeți în orice câmp de culoare apar aici", + "color.red": "Roșu", + "color.saturation": "Saturație (procente)", "color.saturation_value": "Saturație și valoare", "color.selected": "Culoare selectată", + "color.step_down": "Scade cu un pas", + "color.step_up": "Crește cu un pas", + "color.value": "Valoare, luminozitatea (procente)", "config.column_filter_empty": "Nicio coloană potrivită", + "config.rule_parameter_columns": "Sunt listați doar parametrii care au o coloană în tabel. Adăugați una cu Adaugă coloană (+) ca să o folosiți aici.", + "config.rule_suppression_columns": "Sunt listate doar operațiile care au o coloană Suprimă în tabel. Adăugați una cu Adaugă coloană (+) ca să le controlați de aici.", "contact.components_count": "{count} componente", "contact.enabled_label": "activat", "coupling.gear_1": "Roată dințată 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Faceți clic pe altă cotă de comandă pentru a-i insera numele", "dialog.dimension_name": "Cotă: {name}", "dialog.edit_title": "EDITARE {title}", + "dialog.no_shown_body": "Niciun corp afișat de modificat: afișați unul sau alegeți Corp nou", + "dialog.pattern_sketch_not_object": "Alegeți corpuri sau operații: o schiță nu este niciuna dintre ele. Repetați curbele ei cu Matrice sau Oglindire din schiță, ori extrudați-o mai întâi.", "dialog.select": "↖ Selectează", "dialog.selected_count": "↖ {count} selectate", + "dialog.selection_constraint": "Constrângerea {id}", + "dialog.selection_external_curve": "{sketch} · curba {id}", "dialog.selection_guidance": "Selectați o intrare pentru a o modifica. Faceți clic pe obiectele selectate pentru a le elimina; Ctrl/Cmd-clic le comută de asemenea. Verificați previzualizarea, apoi apăsați OK.", + "dialog.selection_midpoint": "Punct de mijloc · {id}", + "dialog.selection_profile": "{sketch} · profilul {number}", "dialog.selection_step": "{step} din {total}: Selectați {input}", "dialog.step": "Pas", "document.changed_on_disk": "{name} a fost modificat pe disc", @@ -1380,26 +1432,244 @@ "from the rule": "din regulă", "help.apache": "Licența Apache 2.0", "help.appearance.assign": "Dă corpurilor, fețelor sau componentelor selectate o culoare sau un aspect de material, fără a le modifica greutatea. Folosiți-l pentru a deosebi piesele sau pentru a previzualiza un finisaj.", + "help.assembly.bom": "Listează piesele proiectului sau ale unei componente, cu cantitățile lor, pe numere de piesă, și poate salva lista ca CSV sau JSON. Folosiți-o ca listă de piese pentru comandă și asamblare.", "help.attributions": "Atribuiri (ATTRIBUTION.md)", "help.build": "Versiunea {version} · commit {commit} · construit {date}", + "help.canvas.decal": "Plasează o imagine pe o față plană a modelului, ca un autocolant. Folosiți-l pentru a arăta o etichetă, un logo sau un model imprimat pe o piesă.", + "help.canvas.edit": "Modifică o pânză: poziția, dimensiunea, unghiul, opacitatea, oglindirea, vizibilitatea sau numele. Folosiți-o pentru a alinia o imagine de referință cu schița trasată peste ea.", + "help.canvas.insert": "Plasează o imagine PNG sau JPEG pe un plan sau pe o față, ca referință transparentă. Folosiți-o pentru a copia o fotografie sau un desen într-o schiță, cu imaginea scalată la o dimensiune cunoscută.", + "help.component.break_link": "Desprinde o componentă legată de fișierul ei de proiect, păstrându-i corpurile așa cum sunt. Folosiți-o când piesa nu mai trebuie să urmeze modificările fișierului original.", + "help.component.capture_position": "Păstrează pozițiile pieselor mutate manual, astfel încât acestea să devină noile lor poziții. Folosiți-o după ce ați tras în loc piese pe care nu le ține nicio îmbinare.", + "help.component.create": "Adaugă în proiect o componentă nouă, goală, în componenta activă, dacă nu alegeți un alt părinte. Folosiți-o pentru a da unei piese noi a unui ansamblu propriul loc pentru corpuri și schițe.", "help.component.finish_edit": "Salvează piesa pe care o editați pe loc, revine la ansamblul ei și actualizează ansamblul pe baza piesei. Folosiți-o când modificările piesei legate sunt gata.", + "help.component.from_bodies": "Transformă fiecare corp selectat într-o componentă proprie, cu numele corpului. Folosiți-o când un proiect construit din corpuri separate trebuie să devină un ansamblu ale cărui piese pot fi îmbinate și mutate.", + "help.component.insert_design": "Inserează un alt proiect salvat ca o componentă legată de fișierul său, cu corpurile solide plasate ca acolo. Folosiți-o pentru a reutiliza o piesă într-un ansamblu și a prelua modificările ulterioare cu Actualizează legăturile.", + "help.component.properties": "Arată volumul, masa, centrul de masă și momentele de inerție ale unei componente, pe baza materialelor corpurilor sale. Folosiți-o pentru a verifica greutatea și echilibrul unui ansamblu.", + "help.component.revert_position": "Readuce piesele mutate manual unde erau, renunțând la mutările necapturate. Folosiți-o pentru a anula mutările de probă dintr-un ansamblu.", + "help.component.update_links": "Citește din nou fișierele de proiect legate și înlocuiește corpurile care s-au modificat. Folosiți-o după editarea unei piese folosite de acest ansamblu.", + "help.config.configure": "Adaugă parametri, operații, materiale sau aspecte ca coloane ale tabelului de configurații. Folosiți-o pentru a crea variante ale unui proiect, de exemplu dimensiuni ale unei piese.", + "help.config.preview": "Verifică dacă un rând al tabelului de configurații se reconstruiește, fără a modifica proiectul sau istoricul lui. Folosiți-o înainte de a trece la o variantă de care nu sunteți sigur.", + "help.config.rules": "Arată regulile tabelului de configurații, rândurile lui și care rând este activ. Folosiți-o pentru a vedea cum sunt definite variantele unui proiect.", + "help.config.table": "Arată tabelul de configurații: un rând pentru fiecare variantă, o coloană pentru fiecare parametru sau operație și dacă proiectul se potrivește încă cu rândul activ. Folosiți-o pentru a revizui variantele unui proiect.", "help.connect_note": "Reporniți fiecare asistent pentru a încărca serverul SolidCraft. Din fiecare fișier s-a făcut o copie de rezervă .bak înainte de modificare.", "help.connect_title": "Conectare asistenți AI", + "help.construct.axis.edge": "Creează o axă de construcție de-a lungul unei muchii drepte sau a unei linii de schiță. Folosiți-o ca axă pentru o revoluție, o matrice circulară sau o îmbinare.", + "help.construct.axis.normal_to_face": "Creează o axă de construcție printr-un punct, perpendiculară pe o față. Folosiți-o ca axă care iese drept dintr-o suprafață.", + "help.construct.axis.through_cylinder": "Creează o axă de construcție prin centrul unei fețe cilindrice, conice sau toroidale ori al unei muchii circulare. Folosiți-o pentru a roti sau a multiplica operații în jurul unei piese rotunde.", + "help.construct.axis.two_planes": "Creează o axă de construcție acolo unde se întâlnesc două plane sau fețe plane. Folosiți-o când axa de care aveți nevoie este linia în care se întâlnesc două fețe.", + "help.construct.axis.two_points": "Creează o axă de construcție prin două puncte, vârfuri sau puncte de schiță. Folosiți-o pentru o axă care trece între două poziții cunoscute.", + "help.construct.plane.along_path": "Creează un plan de construcție perpendicular pe o muchie sau o curbă, într-o poziție de-a lungul ei. Folosiți-l pentru a schița un profil de baleiere sau o secțiune prin traseu.", + "help.construct.plane.at_angle": "Creează un plan de construcție rotit cu un unghi față de un plan sau o față, în jurul unei axe sau muchii. Folosiți-l pentru schițe înclinate, de exemplu un suport în unghi.", + "help.construct.plane.axis_point": "Creează un plan de construcție care conține o axă și un punct din afara axei. Alegeți o origine sau o axă de construcție, o muchie dreaptă sau o linie de schiță, apoi un vârf, un punct de schiță sau un punct de construcție. Un punct situat pe axă nu poate defini un plan unic.", + "help.construct.plane.midplane": "Creează un plan de construcție la jumătatea distanței dintre două plane sau fețe plane ori care le bisectează acolo unde se întâlnesc sub un unghi. Folosiți-l ca plan de simetrie pentru oglindire.", + "help.construct.plane.offset": "Creează un plan de construcție paralel cu un plan sau o față plană, la o distanță sau printr-un punct. Folosiți-l pentru a schița la o înălțime stabilită deasupra unei fețe.", + "help.construct.plane.perpendicular": "Creează un plan de construcție care conține o linie sau o muchie și este perpendicular pe un plan sau o față. Folosiți-l pentru a schița vertical pe un model, de-a lungul unei muchii.", + "help.construct.plane.tangent": "Creează un plan de construcție care atinge un cilindru, un con, o sferă sau un tor într-un punct. Folosiți-l pentru a schița pe latura unei piese rotunde.", + "help.construct.plane.three_points": "Creează un plan de construcție prin trei puncte. Folosiți-l pentru un plan stabilit de poziții de pe model, de exemplu trei colțuri.", + "help.construct.plane.two_edges": "Creează un plan de construcție prin două muchii drepte sau linii care se află în același plan. Folosiți-l pentru un plan prin mijlocul unei piese, de exemplu prin două muchii opuse.", + "help.construct.point.along_path": "Creează un punct de construcție într-o poziție de-a lungul unei muchii sau curbe. Folosiți-l ca referință la o anumită distanță pe un traseu.", + "help.construct.point.center": "Creează un punct de construcție în centrul unei muchii circulare, al unui cerc sau arc de schiță, al unei sfere sau al unui tor. Folosiți-l ca referință pentru găuri, axe și îmbinări.", + "help.construct.point.edge_plane": "Creează un punct de construcție acolo unde o muchie sau o linie trece printr-un plan sau o față plană. Folosiți-l pentru a marca locul unde un traseu traversează un plan.", + "help.construct.point.three_planes": "Creează un punct de construcție acolo unde se întâlnesc trei plane sau fețe plane. Folosiți-l ca referință de colț, chiar și acolo unde modelul nu are vârf.", + "help.construct.point.two_edges": "Creează un punct de construcție acolo unde două muchii sau linii se întâlnesc sau se apropie cel mai mult. Folosiți-l ca referință la un colț virtual.", + "help.construct.point.vertex": "Creează un punct de construcție pe un vârf sau pe un punct de schiță. Folosiți-l ca referință care rămâne când schița sau corpul din jurul lui sunt ascunse.", + "help.contact.check": "Listează perechile de piese din seturile de contact care se întrepătrund în poziția lor curentă. Folosiți-o pentru a găsi coliziuni înainte de a acționa îmbinările sau de a rula un studiu de mișcare.", + "help.contact.create": "Grupează două sau mai multe piese într-un set de contact, ale cărui corpuri nu se pot întrepătrunde cât timp se mișcă îmbinările. Folosiți-o pentru piese care trebuie să se oprească la atingere, de exemplu o pârghie lângă opritorul ei.", + "help.contact.disable_all": "Dezactivează contactul, astfel încât îmbinările acționate și studiile de mișcare să nu se mai oprească acolo unde piesele se ating. Folosiți-o pentru a mișca din nou piesele liber sau pentru a menține receptiv un ansamblu mare.", + "help.contact.edit": "Modifică un set de contact: piesele pe care le conține, numele lui sau dacă este suprimat; poate și șterge setul. Folosiți-o pentru a ajusta ce piese nu se pot întrepătrunde.", + "help.contact.enable_all": "Pune toate piesele ansamblului într-un singur set de contact, astfel încât două piese să nu se poată întrepătrunde cât timp se mișcă îmbinările. Folosiți-o pentru o verificare rapidă a unui mecanism întreg.", + "help.contact.enable_sets": "Activează contactul pentru seturile de contact pe care le-ați definit, astfel încât îmbinările acționate și studiile de mișcare să se oprească acolo unde piesele lor s-ar întrepătrunde. Folosiți-o pentru a readuce seturile după dezactivarea contactului.", + "help.contact.list": "Listează seturile de contact ale proiectului, piesele din fiecare și dacă contactul este activ. Folosiți-o pentru a verifica cum este configurat contactul înainte de a acționa ansamblul.", + "help.document.inspect": "Arată o privire de ansamblu asupra proiectului: componentele, corpurile, schițele, operațiile și parametrii lui. Folosiți-o pentru a vă orienta într-un proiect pe care nu l-ați construit dumneavoastră.", + "help.document.units": "Schimbă unitățile în care proiectul afișează lungimile, de exemplu mm sau inchi. Geometria își păstrează dimensiunea; doar afișarea și numerele simple urmează unitatea.", + "help.edit.checkpoint": "Reține proiectul, schița activă și istoricul de anulare așa cum sunt acum. Folosiți-l înainte de a încerca ceva riscant, de la care s-ar putea să vreți să vă întoarceți.", + "help.edit.restore_checkpoint": "Revine la un punct de control, inclusiv la istoricul de anulare. Folosiți-o pentru a renunța dintr-un singur pas la tot ce s-a făcut de la punctul de control.", + "help.explode.create": "Creează o vedere explodată care îndepărtează piesele de centrul ansamblului sau după mutările stabilite de dumneavoastră. Folosiți-o pentru a arăta cum se asamblează un ansamblu, pentru instrucțiuni sau prezentări.", "help.face.delete": "Elimină fețele selectate și lasă fețele vecine să închidă golul sau lasă golul deschis ca suprafață. Folosiți-l pentru a îndepărta o muchie rotunjită, o gaură sau un bosaj care incomodează.", + "help.file.insert_mesh": "Adaugă un fișier 3MF, STL, OBJ, PLY sau glTF în proiect ca corpuri plasă într-o componentă nouă. Folosiți-o pentru a plasa lângă proiectul dumneavoastră, ca referință, un model descărcat sau scanat.", + "help.file.insert_step": "Adaugă un fișier STEP, IGES, FreeCAD sau Rhino în proiect ca corpuri solide într-o componentă nouă; piesele unui ansamblu devin componente imbricate. Folosiți-o pentru a aduce modele de la furnizori sau din alte programe CAD.", + "help.file.save_mesh": "Salvează corpurile ca plasă STL, 3MF sau OBJ, cu netezimea fețelor curbe pe care o alegeți. Folosiți-o pentru a pregăti piese pentru imprimarea 3D sau pentru programe care citesc plase.", + "help.file.send_to_slicer": "Salvează corpurile selectate ca fișier 3MF și îl deschide în slicerul pe care îl alegeți. Folosiți-o pentru a trece de la model la imprimare într-un singur pas.", "help.font_details": "Interfața folosește fonturile încorporate ale egui (Ubuntu Light și Hack, sub Ubuntu Font Licence și licența MIT/Bitstream Vera; Noto Emoji și fontul de pictograme emoji, sub OFL și MIT). Textul din schiță folosește Liberation Sans (SIL OFL 1.1). Pachetul opțional de fonturi al Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), nu este inclus în versiunile SolidCraft.", "help.fonts": "Fonturi", + "help.frame.member": "Plasează un profil, de exemplu o țeavă sau un profil extrudat din aluminiu, de-a lungul liniilor unei schițe de cadru, câte un element pe linie. Folosiți-o pentru a construi cadre, rafturi și structuri sudate.", + "help.inspect.accessibility": "Colorează fețele pe care o sculă le poate atinge dintr-o direcție și pe cele pe care nu le poate atinge. Folosiți-o pentru a verifica o piesă pentru prelucrare sau matrițare din acea parte.", + "help.inspect.center_of_mass": "Arată centrul de masă al corpurilor, fiecare separat și toate împreună, la densitate uniformă. Folosiți-o pentru a verifica echilibrul și locul unde se răstoarnă o piesă.", + "help.inspect.colored_components": "Dă fiecărei componente propria culoare temporară, fără a modifica aspectele. Folosiți-o pentru a deosebi dintr-o privire piesele unui ansamblu.", + "help.inspect.compare": "Compară două corpuri și arată unde unul are material pe care celălalt nu îl are, cu volumul și abaterea. Folosiți-o pentru a verifica o piesă modificată sau importată față de original.", + "help.inspect.continuity": "Verifică cât de neted se întâlnesc fețele de-a lungul muchiilor: spații, frângeri sau salturi de curbură, și colorează cusăturile. Folosiți-o pentru a găsi unde suprafețele nu se îmbină curat.", + "help.inspect.curvature_comb": "Desenează piepteni de-a lungul curbelor, muchiilor sau fețelor, ai căror dinți arată cât de tare se curbează acestea. Folosiți-o pentru a depista porțiuni plate, frângeri și curbură neuniformă.", + "help.inspect.curvature_map": "Colorează fețele după cât de tare se curbează, cu roșu unde raza este mică. Folosiți-o pentru a găsi locurile strânse și a aprecia cât de netedă este o suprafață.", + "help.inspect.draft": "Colorează fețele după unghiul lor de înclinare față de o direcție de extragere, marcându-le pe cele cu prea puțină înclinare. Folosiți-o pentru a verifica o piesă înainte de matrițare sau turnare.", + "help.inspect.environment_map": "Arată modelul cu un finisaj reflectant, ca de oglindă. Folosiți-o pentru a aprecia curgerea suprafețelor după felul în care se desfășoară reflexiile pe ele.", + "help.inspect.interference": "Găsește corpurile care se suprapun și arată fiecare suprapunere cu volumul ei. Folosiți-o pentru a verifica dacă un ansamblu are piese care se ciocnesc.", + "help.inspect.isocurve": "Desenează curbele izoparametrice ale fețelor, adică grila pe care este construită suprafața. Folosiți-o pentru a vedea cum curge o suprafață și unde se îngrămădește.", + "help.inspect.measure": "Măsoară lungimi, distanțe, unghiuri, arii și raze între elementele alese sau volumul și masa corpurilor. Folosiți-o pentru a verifica dimensiuni și jocuri.", + "help.inspect.minimum_radius": "Găsește cea mai mică rază de curbură a curbelor, muchiilor sau fețelor și locul unde apare. Folosiți-o pentru a verifica dacă o sculă sau o duză poate urmări forma.", + "help.inspect.section": "Taie vizualizarea de-a lungul unui plan și hașurează fețele tăiate, fără a modifica modelul. Folosiți-o pentru a privi în interiorul pieselor și ansamblurilor.", + "help.inspect.zebra": "Arată dungi albe și negre reflectate pe fețele modelului. Folosiți-o pentru a aprecia netezimea: dungile care se rup sau se frâng la o muchie arată o tranziție slabă.", + "help.joint.as_built": "Îmbină două piese acolo unde se află deja, fără a muta niciuna, și stabilește cum se mai pot mișca. Folosiți-o pentru piese pe care le-ați plasat deja în poziția finală.", + "help.joint.cam": "Leagă o camă rotitoare de un tachet, astfel încât tachetul să alunece sau să oscileze pe măsură ce conturul camei trece pe sub el. Folosiți-o pentru came, excentrice și mecanisme de acționare a supapelor.", + "help.joint.create": "Îmbină două piese la originile îmbinării alese și mută a doua piesă la locul ei; tipul îmbinării stabilește cum se mai pot mișca. Folosiți-o pentru a construi un ansamblu ale cărui piese se mișcă precum mecanismul real.", + "help.joint.drive": "Stabilește unghiul sau distanța unei îmbinări și mută piesele odată cu ea, în limitele ei; îmbinările legate și buclele închise o urmează. Folosiți-o pentru a verifica dacă un mecanism se mișcă așa cum trebuie.", + "help.joint.gear": "Leagă două îmbinări rotitoare printr-un raport de transmisie, astfel încât acționarea uneia o rotește pe cealaltă. Folosiți-l pentru roți dințate cilindrice și interioare, cu raportul dat de razele cercurilor de divizare sau de numărul de dinți.", + "help.joint.limits": "Stabilește cât se poate roti sau aluneca o îmbinare, ca minim și maxim, sau șterge aceste limite. Folosiți-o pentru a ține o balama, un cursor sau o pârghie în cursa ei reală.", + "help.joint.motion_link": "Cuplează două îmbinări cu un raport și un decalaj, astfel încât acționarea uneia o mișcă pe cealaltă. Folosiți-o pentru o relație fixă între îmbinări pe care Angrenaj, Cremalieră și pinion sau Șurub nu o acoperă.", + "help.joint.origin": "Plasează pe o piesă o origine de îmbinare denumită: în centrul unei fețe sau al unui capăt rotund, la mijlocul unei muchii, într-un colț sau într-un punct. Folosiți-o pentru a pregăti locurile unde se prind îmbinările; una aleasă pe o față o urmează când piesa își schimbă dimensiunea.", + "help.joint.rack_pinion": "Leagă un pinion rotitor de o cremalieră glisantă, astfel încât cremaliera se mișcă pe lungimea cercului de divizare pe care se rostogolește pinionul. Folosiți-o pentru acționări cu cremalieră, mecanisme de direcție și module liniare.", + "help.joint.reach": "Mută un punct de pe o piesă spre o țintă schimbând îmbinările lanțului său, în limitele lor. Folosiți-o pentru a poziționa un mecanism după locul unde trebuie să ajungă capătul lui, de exemplu vârful unui braț de robot.", + "help.joint.rigid_group": "Blochează împreună piesele selectate așa cum sunt, astfel încât să se miște ca una singură. Folosiți-l pentru piese care aparțin laolaltă și între care nu există mișcare.", + "help.joint.screw": "Leagă rotirea și alunecarea printr-un pas, astfel încât fiecare rotație avansează cu acea distanță. Folosiți-o pentru șuruburi conducătoare, șuruburi și axe filetate.", + "help.library.apply": "Aplică un material sau un aspect dintr-un fișier de bibliotecă locală corpurilor, fețelor sau componentelor. Folosiți-o pentru a reutiliza materiale salvate dintr-un alt proiect.", + "help.library.export": "Salvează materialele și aspectele proiectului într-un fișier de bibliotecă. Folosiți-o pentru a le partaja sau a le reutiliza în alte proiecte.", + "help.library.inspect": "Verifică un fișier de bibliotecă și îi listează materialele și aspectele, fără a modifica proiectul. Folosiți-o pentru a vedea ce conține o bibliotecă înainte de a o aplica.", "help.licences": "Licențe", "help.material.assign": "Stabilește din ce sunt făcute corpurile selectate, de exemplu oțel, aluminiu sau ABS. Folosiți-l pentru ca masa și greutatea să corespundă piesei reale.", + "help.material.properties.validate": "Verifică dacă fișa de date a unui material are numere coerente și dacă îi lipsesc valori. Folosiți-o înainte de a vă baza pe date pentru masă sau rigiditate.", + "help.mesh.convert": "Reconstruiește un corp plasă, de exemplu un STL, ca solid editabil cu fețe plane și cilindrice. Folosiți-o pentru a modifica piese mecanice importate ca pe un corp modelat.", "help.mit": "Licența MIT", + "help.motion.study": "Stabilește valorile îmbinărilor la pași pe o cronologie și le redă ca animație. Folosiți-l pentru a urmări un mecanism parcurgând o secvență și a verifica jocurile pe parcurs.", + "help.motion.trace": "Urmărește drumul parcurs de un punct al unei piese în timp ce rulează un studiu de mișcare sau se acționează o îmbinare și îl păstrează ca o curbă de schiță 3D când confirmați. Folosiți-o pentru a vedea unde ajunge un mecanism sau pentru a construi pe traseul lui.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fixează o piesă pe loc sau o eliberează din nou, astfel încât îmbinările să miște celelalte piese în jurul ei. Folosiți-o pentru cadrul sau baza pe care este construit restul ansamblului.", "help.occurrence.move": "Mută o piesă din ansamblu doar pe direcțiile de mișcare permise de îmbinările sale. Selectați o față a piesei, apoi trageți o săgeată sau un arc disponibil.", "help.parameters.change": "Deschide tabelul cu valori denumite și expresii care controlează cotele proiectului. Folosiți-l pentru a schimba o dimensiune într-un singur loc și a lăsa toate operațiile care o folosesc să o urmeze.", + "help.parameters.export": "Salvează parametrii proiectului ca CSV sau JSON. Folosiți-o pentru a-i edita într-o foaie de calcul sau a-i muta într-un alt proiect.", + "help.parameters.graph": "Arată ce parametri și ce operații le folosesc pe celelalte, precum și eventualele bucle sau erori dintre ele. Folosiți-l pentru a vedea ce va afecta modificarea unui parametru.", + "help.parameters.import": "Citește parametri din CSV sau JSON în proiect, pe toți sau deloc. Folosiți-o pentru a aduce valori dintr-o foaie de calcul sau dintr-un alt proiect.", + "help.parameters.move": "Mută un parametru utilizator înaintea sau după altul în listă. Folosiți-o pentru a ține împreună parametrii înrudiți.", + "help.parts.fastener": "Adaugă un șurub, un bolț, o piuliță, o șaibă, un știft sau un rulment standard, în dimensiunea aleasă. Plasat pe o gaură, se așază în gaură printr-o îmbinare, așa că nu trebuie să modelați singur elementele de fixare.", + "help.parts.insert": "Inserează o piesă standard din familia, dimensiunea și lungimea alese. Plasată pe marginea sau peretele unei găuri, se așază în gaură printr-o îmbinare rigidă.", + "help.parts.library": "Deschide piesele standard: șuruburi, bolțuri, piulițe, șaibe, șuruburi de fixare, știfturi de centrare și rulmenți, în dimensiuni standard. Folosiți-o pentru a adăuga o piesă standard în loc să o modelați singur.", + "help.parts.resize": "Schimbă dimensiunea sau lungimea unei piese standard inserate și o reconstruiește; îmbinările ei o păstrează așezată. Folosiți-o când un șurub se dovedește prea lung sau o gaură cere altă dimensiune.", + "help.plastic.assign_rule": "Atribuie o regulă pentru plastic unor corpuri, astfel încât operațiile lor pentru plastic să preia înclinarea și jocul ei ca valori implicite. Folosiți-o pentru a configura o singură dată o piesă matrițată pentru toate operațiile ei.", + "help.plastic.boss": "Adaugă pe o față un bosaj pentru șurub: un stâlp cu gaură opțională, înclinare, racordare la bază și nervuri de susținere. Folosiți-l pentru punctele de șurub din carcase matrițate sau imprimate.", + "help.plastic.lip": "Adaugă o buză sau o canelură potrivită pe marginea unui corp scobit. Folosiți-o pentru ca două jumătăți de carcasă să se centreze una pe alta și să se închidă strâns.", + "help.plastic.manage_rules": "Creează și editează reguli pentru plastic: materialul, grosimea peretelui, razele, jocul și înclinarea. Folosiți-le pentru a menține coerente operațiile unei piese matrițate.", + "help.plastic.rest": "Adaugă un reazem pe o față: o platformă rotundă sau dreptunghiulară, plină sau goală, cu înclinare. Folosiți-l ca sprijin sau distanțier într-o carcasă matrițată.", + "help.plastic.snap_fit": "Adaugă pe o față un cârlig de prindere cu clichet, cu lungimea, grosimea și zăvorul lui. Folosiți-o pentru a prinde piesele între ele fără șuruburi.", "help.pointcloud.insert": "Inserați o scanare PLY, XYZ sau PTS ca nor de puncte alături de model. Folosiți-o ca referință la construirea unui model pe baza datelor măsurate.", + "help.sheet.convert": "Transformă o placă sau un corp scobit de grosime uniformă într-un corp din tablă, cu îndoiri la muchiile alese. Folosiți-o pentru a face desfășurabilă o piesă existentă.", + "help.sheet.export_bend_table": "Salvează tabelul de îndoire al unui corp din tablă ca CSV sau JSON: unghiuri, raze și poziții ale îndoirilor în desfășurată. Folosiți-o pentru presa de îndoit sau pentru atelier.", + "help.sheet.export_dxf": "Salvează desfășurata ca DXF, cu contururi, linii de îndoire și note de îndoire opționale. Folosiți-o pentru tăierea cu laser, cu plasmă sau cu jet de apă.", + "help.sheet.flange": "Adaugă o flanșă: o placă de bază dintr-o schiță, un perete de-a lungul unui contur deschis de schiță sau un perete îndoit pe muchii de tablă. Folosiți-o pentru a construi piese din tablă.", + "help.sheet.flat_pattern": "Creează desfășurata plană a unui corp din tablă, cu dimensiunea, decupările și liniile de îndoire. Folosiți-o pentru a verifica semifabricatul înainte de tăiere.", + "help.sheet.fold": "Îndoaie o tablă de-a lungul unei linii de schiță cu un unghi și o rază. Folosiți-o pentru a îndoi o tablă plană după ce ați adăugat în ea decupări.", + "help.sheet.hem": "Îndoaie o muchie de tablă peste ea însăși. Folosiți-o pentru muchii sigure și rigide, fără bavuri ascuțite.", + "help.sheet.manage_rules": "Creează și editează reguli pentru tablă: grosime, rază de îndoire, factor K, degajări și spații. Folosiți-le pentru a vă adapta la materialul și sculele atelierului dumneavoastră.", + "help.sheet.path_flange": "Adaugă un lanț de flanșe de-a lungul unei muchii de tablă, urmând un lanț deschis de linii de schiță. Folosiți-o pentru profile precum forma U sau Z dintr-un singur pas.", + "help.sheet.perforate": "Adaugă un câmp de găuri pe toată tabla desfășurată, într-un model decalat sau pătrat. Folosiți-o pentru ventilații, grilaje și panouri mai ușoare.", + "help.sheet.refold": "Îndoaie la loc un corp din tablă desfășurat. Folosiți-o după ce ați adăugat operații pe tabla plană.", + "help.sheet.unfold": "Desfășoară toate îndoirile unui corp din tablă. Folosiți-o pentru a adăuga găuri sau decupări care trebuie să traverseze o îndoire, apoi reîndoiți.", + "help.sketch.arc.center_point": "Desenează un arc de cerc în jurul unui punct central, de la un punct de început la unul de sfârșit. Folosiți-l când centrul arcului este cunoscut, de exemplu o rază în jurul unei găuri sau al unui pivot.", + "help.sketch.arc.tangent": "Desenează un arc care pornește de la capătul unei linii sau al unui arc și continuă tangent la acesta. Folosiți-l pentru a continua un lanț cu o curbă lină în loc de un colț.", + "help.sketch.arc.three_point": "Desenează un arc de la un punct de început la unul de sfârșit, printr-un al treilea punct. Folosiți-l când arcul trebuie să treacă prin puncte date, nu în jurul unui centru cunoscut.", + "help.sketch.arc3d": "Desenează un arc de cerc exact în spațiu prin trei puncte, cu Schiță 3D activată. Folosiți-l pentru curbe în traseele și ghidajele care ies din planul schiței.", + "help.sketch.auto_constrain": "Adaugă constrângerile pe care schița le are aproape deja, de exemplu orizontală, paralelă sau coincidentă, apoi o cotează până este complet definită. Folosiți-o pentru a bloca dintr-un singur pas o schiță desenată aproximativ.", + "help.sketch.auto_constrain_from_datum": "Funcționează ca Constrângere automată, dar măsoară pozițiile față de un reper ales de dumneavoastră, nu față de origine. Folosiți-o când piesa este trasată dintr-un singur punct de referință, de exemplu un colț sau o gaură.", + "help.sketch.blend_curve": "Unește capetele a două curbe cu un spline lin, tangent la amândouă sau, la alegere, și cu curbură continuă. Folosiți-o pentru a acoperi un spațiu dintre curbe fără frângere.", + "help.sketch.break": "Împarte o curbă în bucăți acolo unde o taie alte curbe sau în punctele pe care le plasați pe ea. Folosiți-o când o parte a unei curbe are nevoie de propria constrângere sau trebuie ștearsă separat.", + "help.sketch.cancel": "Părăsește schița și renunță la tot ce s-a schimbat de când a fost creată sau deschisă pentru editare. Anularea ultimei acțiuni readuce modificările.", + "help.sketch.centerline": "Comută liniile între linii normale și linii de axă, adică axe pe care profilurile le omit. Folosiți o linie de axă ca axă pentru o revoluție, o oglindire sau o constrângere de simetrie.", + "help.sketch.chamfer.distance_angle": "Teșește colțul dintre două linii, stabilit printr-o distanță pe prima linie și un unghi. Folosiți-o când un desen dă teșitura ca lungime și unghi, de exemplu 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Teșește colțul dintre două linii cu aceeași distanță pe ambele. Folosiți-o pentru teșitura obișnuită de 45° pe un contur.", + "help.sketch.chamfer.two_distance": "Teșește colțul dintre două linii, stabilit printr-o distanță separată pe fiecare linie. Folosiți-o pentru teșituri care nu sunt de 45°, date ca două lungimi.", + "help.sketch.circle.center": "Desenează un cerc după centrul și diametrul lui. Folosiți-l pentru găuri, bosaje și alte elemente rotunde al căror centru este cunoscut.", + "help.sketch.circle.three_point": "Desenează un cerc prin trei puncte. Folosiți-l când cercul trebuie să treacă prin puncte date, de exemplu ale geometriei existente.", + "help.sketch.circle.three_tangent": "Desenează un cerc care atinge trei linii, cercuri sau arce. Folosiți-l pentru a potrivi un cerc în spațiul dintre trei curbe, de exemplu cercul înscris al unui triunghi.", + "help.sketch.circle.two_point": "Desenează un cerc din cele două capete ale diametrului său. Folosiți-l când sunt cunoscute punctele de pe marginea cercului, nu centrul.", + "help.sketch.circle.two_tangent": "Desenează un cerc de o dimensiune dată care atinge două linii, cercuri sau arce. Folosiți-l pentru o rotunjire de rază fixă între două curbe.", + "help.sketch.conic": "Desenează o curbă conică între două puncte finale, modelată de un punct de vârf și o valoare rho. Folosiți-o pentru tranziții line a căror plinătate o reglați, de la plată până aproape de un colț ascuțit.", + "help.sketch.constrainer": "Aplică constrângerea pe care una sau două curbe alese o au aproape deja, de exemplu orizontală, paralelă, tangentă sau egală. Folosiți-o pentru a pune în ordine o schiță desenată de mână, câte o relație pe rând.", + "help.sketch.constraint.coincident": "Face ca un punct să se afle pe alt punct, pe o curbă sau pe o axă a schiței. Folosiți-o pentru a închide spațiile dintr-un profil sau a pune un punct pe o linie.", + "help.sketch.constraint.collinear": "Face ca două linii să se afle pe aceeași dreaptă. Folosiți-o pentru a alinia muchii întrerupte, de exemplu ambele laturi ale unei crestături.", + "help.sketch.constraint.concentric": "Dă la două cercuri sau arce același centru. Folosiți-o pentru inele, lamaje și arbori cu umeri.", + "help.sketch.constraint.curvature": "Face ca două curbe care se întâlnesc într-un punct final să continue cu aceeași curbură (G2). Folosiți-o acolo unde un racord tangent nu este destul de neted, de exemplu pe suprafețe vizibile.", + "help.sketch.constraint.equal": "Face liniile de aceeași lungime sau cercurile și arcele de aceeași rază. Folosiți-o pentru ca o singură cotă să conducă mai multe elemente identice.", + "help.sketch.constraint.fix": "Fixează puncte sau curbe unde se află sau le eliberează din nou. Folosiți-o pentru geometria care nu trebuie să se miște când trageți sau rezolvați schița.", + "help.sketch.constraint.horizontal_vertical": "Face o linie, sau linia dintre două puncte, orizontală sau verticală, după care este mai apropiată. Folosiți-o pentru a aduce un contur în unghi drept pe axele schiței.", + "help.sketch.constraint.midpoint": "Pune un punct la mijlocul unei linii sau face ca mijloacele a două linii să coincidă. Folosiți-o pentru a centra geometria pe o muchie.", + "help.sketch.constraint.parallel": "Face două linii paralele. Folosiți-o pentru laturi care trebuie să rămână paralele când se schimbă alte cote.", + "help.sketch.constraint.perpendicular": "Face două linii să se întâlnească în unghi drept. Folosiți-o pentru colțuri drepte între linii care nu se află pe axele schiței.", + "help.sketch.constraint.polygon": "Face dintr-un lanț închis de linii un poligon regulat: laturi egale, cu fiecare colț pe același cerc. Folosiți-o pentru a face regulat un poligon desenat de mână și a-l menține așa.", + "help.sketch.constraint.symmetry": "Face două puncte sau curbe să fie în oglindă față de o linie sau în jurul unui punct. Folosiți-o pentru a menține un profil simetric când schimbați o parte.", + "help.sketch.constraint.tangent": "Face două curbe să se atingă tangent, de exemplu o linie și un arc. Folosiți-o pentru racorduri line, fără frângere.", + "help.sketch.construction": "Comută curbele între geometrie normală și geometrie de construcție, pe care profilurile o omit. Folosiți curbele de construcție ca ajutoare pentru trasare, referințe și cote.", + "help.sketch.construction_line": "Creați o dreaptă de construcție infinită prin două puncte. Folosiți-o pentru a structura o schiță fără a diviza profilurile.", + "help.sketch.construction_line.angle": "Creați o dreaptă de construcție infinită sub un unghi față de axa X a schiței. Alegeți punctul și tastați unghiul sau alegeți direcția acestuia.", + "help.sketch.construction_line.bisector": "Alegeți două linii drepte ale schiței care se intersectează, apoi una dintre cele două bisectoare. Rezultatul urmărește liniile sursă.", + "help.sketch.construction_line.horizontal": "Creați o dreaptă de construcție orizontală infinită printr-un punct. Constrângerea orizontală rămâne valabilă la editările ulterioare.", + "help.sketch.construction_line.parallel": "Alegeți o linie dreaptă a schiței, apoi plasați o dreaptă de construcție paralelă infinită. Clic dreapta pentru a alege o altă referință.", + "help.sketch.construction_line.perpendicular": "Alegeți o linie dreaptă a schiței, apoi plasați o dreaptă de construcție perpendiculară infinită. Clic dreapta pentru a alege o altă referință.", + "help.sketch.construction_line.tangent_at": "Creați o tangentă într-un punct al unui cerc sau arc de cerc ori în capătul unui spline sau al unei curbe conice deschise. Alegeți curba, apoi punctul de tangență.", + "help.sketch.construction_line.tangent_external": "Alegeți un cerc sau un arc de cerc, apoi un punct exterior și o soluție de tangentă. Previzualizările arată doar punctele de tangență de pe arcul desenat.", + "help.sketch.construction_line.tangent_two": "Alegeți două cercuri sau arce de cerc, apoi o tangentă comună în previzualizare. Punctele de tangență trebuie să se afle pe curbele desenate.", + "help.sketch.construction_line.vertical": "Creați o dreaptă de construcție verticală infinită printr-un punct. Constrângerea verticală rămâne valabilă la editările ulterioare.", + "help.sketch.copy": "Copiază curbele și punctele de schiță selectate, împreună cu constrângerile și cotele dintre ele. Lipiți-le în această schiță sau în alta.", + "help.sketch.create": "Începe o schiță 2D nouă pe un plan sau pe o față plană a modelului. Orice extrudare, revoluție și baleiere începe cu o schiță.", + "help.sketch.cut": "Copiază geometria de schiță selectată și o șterge din schiță, într-un singur pas de anulare. Lipiți-o în altă parte din această schiță sau într-o alta.", + "help.sketch.dimension": "Adaugă o cotă conducătoare: o lungime, o distanță, un unghi, o rază sau un diametru, după ce alegeți. Tastați o valoare sau un nume de parametru, iar schița o urmează.", + "help.sketch.edit": "Deschide o schiță existentă pentru editare. Operațiile construite pe ea se actualizează când finalizați schița.", + "help.sketch.ellipse": "Desenează o elipsă după centrul ei, capătul axei mari și un punct pe latura mică. Folosiți-o pentru deschideri ovale, came și alte forme rotunde alungite.", "help.sketch.equation_curve": "Desenează o curbă din formule: x(t) și y(t) sau y = f(x), pe un interval. Formulele pot folosi parametri, iar curba îi urmează: folosiți-o pentru o sinusoidă, o spirală sau evolventa unui dinte de roată dințată.", + "help.sketch.extend": "Prelungește o linie sau un arc până la cea mai apropiată curbă din calea lui sau extinde două curbe până se întâlnesc. Folosiți-o pentru a închide spațiile dintr-un profil după tăiere sau editare.", + "help.sketch.fillet": "Racordează colțul în care se întâlnesc două linii sau arce cu un arc de rază dată. Mai multe colțuri racordate împreună au aceeași rază.", + "help.sketch.finish": "Părăsește schița și revine la model. Profilurile ei închise sunt apoi gata pentru Extrudare, Revoluție și alte operații.", + "help.sketch.finish_auto_constrain": "Rulează Constrângere automată pe schiță, apoi o finalizează. Folosiți-o pentru a lăsa o schiță complet definită dintr-un singur pas.", + "help.sketch.fit_curves_to_section": "Taie un corp plasă sau solid cu planul schiței și potrivește linii și arce pe secțiune. Folosiți-o pentru a reconstrui o piesă scanată sau importată ca schiță editabilă.", + "help.sketch.include_3d": "Aduce în această schiță muchii ale modelului, vârfuri și curbe ale altor schițe, ca referințe legate, aplatizându-le pe plan pe cele aflate în afara lui. Folosiți-o pentru a construi pe geometrie care nu se află în planul schiței.", + "help.sketch.infinite": "Comută liniile între linii normale și linii infinite de construcție, care traversează toată vizualizarea. Folosiți-le ca referințe de trasare care nu se termină niciodată prea devreme.", + "help.sketch.insert_dxf": "Citește curbele unui desen DXF într-o schiță, scalate, rotite și plasate așa cum stabiliți. Folosiți-o pentru a construi pe un desen 2D din alt program, de exemplu un contur pentru tăiere cu laser.", + "help.sketch.insert_svg": "Citește traseele unui desen SVG într-o schiță, scalate, rotite și plasate așa cum stabiliți. Folosiți-o pentru a transforma un logo sau un contur vectorial în curbe pe care le puteți extruda.", + "help.sketch.inspect": "Deschide un raport despre schița deschisă: câte grade de libertate au rămas și dacă este complet constrânsă. Folosiți-l pentru a afla ce se mai mișcă înainte de a finaliza schița.", + "help.sketch.intersect": "Adaugă curbele sau punctele în care corpuri, fețe, muchii sau alte schițe taie planul schiței. Rămân legate și urmează modelul când acesta se schimbă.", + "help.sketch.intersection_curve": "Creează curbe 3D acolo unde se întâlnesc două corpuri sau fețe, legate de ele. Folosiți-le ca trasee sau ghidaje care urmează modelul.", + "help.sketch.isoparametric_curve": "Creează o curbă 3D pe direcția U sau V a unei fețe, printr-un punct ales de dumneavoastră, legată de față. Folosiți-o ca traseu sau linie de separare care urmează suprafața.", + "help.sketch.line": "Desenează linii conectate punct cu punct, ca lanț deschis sau contur închis. Este instrumentul de bază pentru majoritatea profilurilor.", + "help.sketch.line.midpoint": "Desenează o linie de la mijlocul ei spre un capăt, celălalt capăt fiind în oglindă. Folosiți-o pentru linii centrate pe un punct, de exemplu o muchie simetrică.", + "help.sketch.line3d": "Desenează linii drepte conectate între puncte din spațiu, cu Schiță 3D activată. Folosiți-o pentru traseele și cadrele care ies din planul schiței.", + "help.sketch.mirror": "Oglindește curbele și punctele de schiță față de o linie sau o axă și adaugă constrângeri de simetrie. Folosiți-o pentru a desena jumătate dintr-un profil simetric și a-l completa.", + "help.sketch.move": "Mută sau rotește curbe și puncte de schiță, ori o copie a lor. Folosiți-o pentru a repoziționa geometria, păstrându-i forma și constrângerile.", + "help.sketch.offset": "Creează o copie decalată a unui lanț de curbe, la o distanță dată, pe o parte sau pe ambele. Folosiți-o pentru pereți, contururi și jocuri; distanța rămâne o cotă editabilă.", + "help.sketch.paste": "Lipește în schița activă geometria de schiță pe care ați copiat-o sau decupat-o. Plasați-o într-un punct sau deplasați-o cu un decalaj.", + "help.sketch.pattern.circular": "Copiază geometria schiței în jurul unui punct central, pe un cerc complet sau pe un unghi dat. Folosiți-o pentru cercuri de șuruburi, spițe și dinți.", + "help.sketch.pattern.rectangular": "Copiază geometria schiței în rânduri și coloane, la distanțe stabilite. Folosiți-o pentru grile de găuri, canale sau ventilații.", + "help.sketch.point": "Plasează un punct de schiță. Folosiți-l ca referință pentru cote, constrângeri, centre de găuri sau operații ulterioare.", + "help.sketch.point3d": "Plasează un punct în spațiu, cu Schiță 3D activată. Folosiți-l ca referință pentru curbe și trasee 3D.", + "help.sketch.polygon.circumscribed": "Desenează un poligon regulat în jurul unui cerc, dimensionat de la centru până la mijlocul unei laturi. Folosiți-l când este cunoscută deschiderea cheii, ca la o piuliță hexagonală.", + "help.sketch.polygon.edge": "Desenează un poligon regulat din cele două capete ale unei laturi. Folosiți-l când sunt cunoscute lungimea și poziția unei laturi.", + "help.sketch.polygon.inscribed": "Desenează un poligon regulat în interiorul unui cerc, dimensionat de la centru până la un colț. Folosiți-l când este cunoscută dimensiunea între colțuri.", + "help.sketch.project": "Aduce în această schiță muchii ale modelului, fețe, vârfuri și curbe ale altor schițe, proiectate pe planul ei. Rămân legate și urmează modelul când acesta se schimbă.", + "help.sketch.project_to_surface": "Proiectează curbe ale altor schițe de-a lungul normalei acestei schițe pe o față, ca curbe 3D legate. Folosiți-o pentru a pune un logo, o linie de separare sau un traseu pe o suprafață curbă.", + "help.sketch.rectangle.center": "Desenează un dreptunghi după centrul și un colț al lui. Folosiți-l pentru contururi centrate pe un punct, de exemplu originea.", + "help.sketch.rectangle.rounded": "Desenează un dreptunghi cu toate cele patru colțuri rotunjite la aceeași rază. Folosiți-l pentru plăci, capace și deschideri cu colțuri rotunjite.", + "help.sketch.rectangle.three_point": "Desenează un dreptunghi dintr-o muchie și un punct de pe latura opusă. Folosiți-l pentru dreptunghiuri înclinate față de axele schiței.", + "help.sketch.rectangle.two_point": "Desenează un dreptunghi din două colțuri opuse. Folosiți-l pentru contururile plăcilor, blocurilor și buzunarelor.", + "help.sketch.scale": "Scalează curbe și puncte de schiță cu un factor față de un punct de bază. Folosiți-o pentru a redimensiona o parte a unei schițe fără a o desena din nou.", + "help.sketch.slot.arc_center": "Desenează un canal curbat, de lățime dată, de-a lungul unui arc stabilit prin centru, început și sfârșit. Folosiți-l pentru canale de reglaj în jurul unui pivot.", + "help.sketch.slot.arc_three_point": "Desenează un canal curbat, de lățime dată, de-a lungul unui arc prin trei puncte. Folosiți-l când traseul canalului trebuie să treacă prin puncte date.", + "help.sketch.slot.center_point": "Desenează un canal drept, de lățime dată, de la centrul lui până la centrul unui arc de capăt. Folosiți-l pentru canale centrate pe un punct.", + "help.sketch.slot.center_to_center": "Desenează un canal drept, de lățime dată, între centrele celor două arce de capăt. Folosiți-l pentru canale cotate de la centru la centru, de exemplu canale de reglaj pentru șuruburi.", + "help.sketch.slot.overall": "Desenează un canal drept, de lățime dată, de la un capăt exterior la celălalt. Folosiți-l când contează lungimea totală a canalului.", + "help.sketch.spline.control_point": "Desenează un spline cubic modelat de puncte de control prin care nu trece. Folosiți-l pentru curbe line și fluide pe care le modelați mutând punctele.", + "help.sketch.spline.control_point_5": "Desenează un spline de gradul 5 modelat de puncte de control. Folosiți-l unde curbele trebuie să se racordeze cu o curbură mai netedă, de exemplu pe suprafețe stilizate vizibile.", + "help.sketch.spline.fit_point": "Desenează un spline neted care trece prin fiecare punct plasat de dumneavoastră, deschis sau închis. Folosiți-l pentru a urmări o formă prin puncte cunoscute.", + "help.sketch.spline3d": "Desenează o curbă netedă în spațiu prin puncte, cu Schiță 3D activată. Folosiți-l pentru trasee de baleiere și trasee de cabluri care ies din planul schiței.", + "help.sketch.spun_profile": "Creează în planul schiței conturul pe care îl descrie un corp când se rotește în jurul unei axe. Folosiți-l pentru a obține silueta unei piese strunjite pentru o revoluție sau un desen.", + "help.sketch.text": "Scrie text în schiță, cu un font, o înălțime și un unghi alese; cuvintele pot urma parametri. Extrudați-l sau reliefați-l pentru etichete și inscripții.", + "help.sketch.transform": "Scalează, rotește și mută geometria schiței în jurul unui punct central, dintr-un singur pas. Folosiți-o pentru a repoziționa și redimensiona deodată o selecție.", + "help.sketch.trim": "Elimină bucata unei curbe dintre cele mai apropiate intersecții din jurul locului unde faceți clic. Folosiți-o pentru a curăța liniile suprapuse până obțineți un profil închis.", "help.solid.align": "Mută corpurile selectate astfel încât un punct, o față sau un plan de pe ele să se întâlnească cu un punct, o față sau un plan din altă parte. Folosiți-l pentru a așeza o piesă lângă alta fără a măsura decalajul.", + "help.solid.boundary_fill": "Creează solide din regiunile închise de corpuri-sculă suprapuse, umplând doar regiunile pe care le alegeți. Folosiți-o pentru a construi o formă din spațiul delimitat împreună de mai multe corpuri.", + "help.solid.bounding_solid": "Creează o cutie care cuprinde corpurile selectate, cu o marjă opțională. Folosiți-l pentru a vedea dimensiunea generală a unei piese sau ca semifabricat din care se prelucrează.", + "help.solid.box": "Creează o cutie după lungime, lățime și înălțime, dintr-un punct de colț sau centrată pe un punct. Folosiți-o pentru un bloc rapid, un înlocuitor provizoriu sau un corp în care să tăiați operații.", "help.solid.chamfer": "Teșește muchiile selectate cu o înclinare plană la distanța stabilită. Folosiți-l pentru a îndepărta muchiile ascuțite sau pentru a ușura introducerea unui pin sau a unui șurub.", + "help.solid.coil": "Creează un corp elicoidal, de exemplu un arc, după diametru, spire, înălțime sau pas și o secțiune rotundă sau pătrată. Folosiți-o pentru arcuri, bobine și nervuri elicoidale.", "help.solid.combine": "Unește corpurile, le decupează dintr-un corp țintă sau păstrează doar volumul pe care îl au în comun și poate păstra corpurile-sculă. Folosiți-l pentru a îmbina piese, pentru a decupa o formă cu alta sau pentru a găsi unde se suprapun două corpuri.", + "help.solid.cone": "Creează un con după un cerc de bază și o înălțime sau un trunchi de con când și vârful are o rază. Folosiți-l pentru conicități, pâlnii, înfundări conice și vârfuri.", + "help.solid.cylinder": "Creează un cilindru după rază sau diametru și înălțime, așezat pe un punct de-a lungul unei axe. Folosiți-l pentru arbori, știfturi, bosaje și semifabricate rotunde.", "help.solid.draft": "Înclină fețele selectate cu unghiul stabilit, măsurat de la un plan neutru. Folosiți-l la piese turnate sau matrițate pentru ca ele să iasă din matriță.", + "help.solid.emboss": "Ridică profile de schiță, de exemplu text sau un logo, dintr-o față sau le adâncește în ea. Folosiți-o pentru inscripții, etichete și marcaje pe fețe plane sau rotunde.", "help.solid.extrude": "Împinge un profil de schiță în 3D pe o distanță, adăugând sau eliminând material. Folosiți-l pentru a transforma un contur plat într-un bloc, un bosaj sau un buzunar.", "help.solid.fillet": "Racordează muchiile selectate cu un arc de cerc neted, de raza stabilită. Folosiți-l pentru a rotunji muchiile ascuțite din motive de rezistență, confort sau aspect.", "help.solid.hole": "Execută o gaură rotundă de diametrul stabilit într-un punct ales al unei fețe. Folosiți-l pentru degajările șuruburilor, pentru pini și alte deschideri rotunde simple.", @@ -1408,20 +1678,62 @@ "help.solid.move": "Mută sau rotește corpurile selectate, ori o copie a lor, cu distanța și unghiul stabilite. Se folosește pentru a repoziționa un corp sau pentru a crea un al doilea corp în alt loc.", "help.solid.offset_face": "Împinge fețele selectate spre interior sau spre exterior cu distanța stabilită, iar fețele din jur le urmează. Se folosește pentru a îngroșa un perete, a adânci un buzunar sau a înălța un bosaj fără a edita schița.", "help.solid.pattern.circular": "Repetă obiectele selectate în jurul unei axe, pentru numărul și unghiul total stabilite. Se folosește pentru cercuri de șuruburi, spițe, aripioare și dinți.", + "help.solid.pattern.path": "Copiază operații sau corpuri de-a lungul unui traseu de schiță, după număr și distanță. Folosiți-o pentru găuri de-a lungul unei muchii curbe sau piese de-a lungul unei șine.", "help.solid.pattern.rectangular": "Repetă obiectele selectate pe una sau două direcții, cu numărul și spațierea stabilite. Se folosește pentru rânduri și grile de găuri, nervuri, știfturi sau picioare.", + "help.solid.pipe": "Creează un tub rotund de-a lungul unui traseu de curbe de schiță, plin sau gol, cu o grosime de perete. Folosiți-o pentru tuburi, fire, cabluri și șine.", "help.solid.press_pull": "Adaugă sau elimină material pe măsură ce trageți o față sau racordează muchiile pe măsură ce le trageți. Se folosește pentru modificări rapide direct pe model.", "help.solid.remove": "Elimină corpurile selectate din proiect începând de la acest punct al cronologiei; pașii anteriori le păstrează. Se folosește pentru a renunța la un corp auxiliar, de exemplu o sculă de tăiere de care nu mai aveți nevoie.", "help.solid.replace_face": "Mută fețele plane selectate pe un plan sau pe o față paralelă, iar corpul crește sau se micșorează pentru a ajunge la ea. Se folosește pentru a aduce o față la același nivel cu o altă piesă sau cu un plan de construcție.", "help.solid.revolve": "Rotește un profil de schiță în jurul unei axe pentru a crea un solid de revoluție. Se folosește pentru arbori, butoane, boluri și orice piesă rotundă în jurul unei linii de axă.", + "help.solid.rib": "Adaugă un perete subțire de-a lungul unei curbe de schiță deschise, extins până la fețele următoare ale corpului. Folosiți-o pentru a rigidiza pereți și colțuri, de exemplu în piese matrițate sau imprimate.", "help.solid.scale": "Mărește sau micșorează corpurile selectate cu un factor, la fel în toate direcțiile sau câte unul pentru fiecare axă. Se folosește pentru a redimensiona o formă importată sau pentru a compensa contracția.", "help.solid.shell": "Scobește un solid, lăsând pereți de grosimea stabilită, și poate deschide fețele alese. Se folosește pentru cutii, capace și alte piese cu pereți subțiri.", + "help.solid.sphere": "Creează o sferă după rază sau diametru în jurul unui punct central. Folosiți-o pentru bile, butoane și capete rotunjite.", "help.solid.split_body": "Taie un corp în corpuri separate cu un plan, cu fața altui corp sau cu o linie de schiță. Se folosește pentru piese care sunt imprimate, prelucrate sau colorate separat.", "help.solid.split_face": "Împarte fețele selectate de-a lungul unui plan, al feței altui corp sau al unor curbe de schiță, fără a tăia corpul. Se folosește pentru a da unei părți dintr-o față propria înclinare, culoare sau propriul decalaj.", "help.solid.sweep": "Trage un profil de schiță de-a lungul unui traseu pentru a crea un solid. Se folosește pentru conducte, ghidaje, mânere și orice piesă cu secțiune constantă care urmează o curbă.", + "help.solid.thread": "Adaugă un filet metric ISO pe o față cilindrică, fie ca filet cosmetic, fie tăiat în corp. Folosiți-l pentru șuruburi, găuri filetate și piese imprimate cu filet.", + "help.solid.torus": "Creează un inel după o rază mare în jurul axei lui și o rază mică pentru secțiunea lui rotundă. Folosiți-l pentru garnituri O-ring, mânere și mărgele rotunde.", + "help.solid.web": "Adaugă un perete subțire de-a lungul fiecărei curbe de schiță deschise, fiecare extins până la fețele următoare ale corpului. Folosiți-o pentru o grilă de pereți de susținere în carcase și tăvi.", + "help.surface.blend": "Creează o suprafață care leagă muchiile a două corpuri, tangentă sau cu curbură continuă la ambele. Folosiți-o pentru a uni lin două suprafețe peste un spațiu.", + "help.surface.boundary": "Creează o suprafață care umple o buclă de două până la patru curbe de schiță sau o rețea de curbe. Folosiți-o pentru panouri cu formă liberă definite de muchiile lor.", + "help.surface.extend": "Prelungește o suprafață dincolo de muchiile ei, cu o distanță sau până la un plan ori o față. Folosiți-o pentru ca suprafețele să se suprapună înainte de a le tăia sau coase.", + "help.surface.extrude": "Împinge curbe sau profile de schiță pe o distanță într-o suprafață, doar pereți, fără capace. Folosiți-o pentru pereți subțiri și pentru scule de tăiere sau de împărțire.", + "help.surface.fair": "Netezește interiorul fețelor cu formă liberă, în timp ce muchiile lor rămân pe loc. Folosiți-o pentru a uniformiza denivelările și reflexiile ondulate dintr-o suprafață.", + "help.surface.loft": "Creează o suprafață care trece prin două sau mai multe secțiuni, în ordine, fără capace. Folosiți-l pentru carcase și tranziții între forme diferite.", + "help.surface.match": "Reconstruiește muchia unei suprafețe astfel încât să se întâlnească cu muchia altui corp, cu tangență sau curbură potrivită. Folosiți-o pentru a închide lin o cusătură între două suprafețe.", + "help.surface.offset": "Creează o copie a fețelor la o distanță, de-a lungul normalelor lor, ca nou corp suprafață. Folosiți-o pentru învelișuri, jocuri sau cealaltă parte a unui perete.", + "help.surface.patch": "Umple o regiune de schiță sau o buclă închisă de muchii cu o față, plană sau curbată lin. Folosiți-l pentru a închide găuri într-un corp suprafață.", + "help.surface.reverse_normal": "Întoarce fețele unui corp suprafață, astfel încât exteriorul lor să privească în cealaltă direcție. Folosiți-o înainte de îngroșare sau de coasere, când fețele sunt orientate spre interior.", + "help.surface.revolve": "Rotește curbe sau profile de schiță în jurul unei axe într-o suprafață, fără capace. Folosiți-o pentru carcase rotunde, cum sunt abajururile, vasele și duzele.", + "help.surface.ruled": "Creează o fâșie de linii drepte pornind dintr-un lanț de muchii, pe direcția normalei sau a tangentei fețelor ori sub un unghi. Folosiți-o pentru pereți înclinați, zone de ieșire și suprafețe de separare.", + "help.surface.stitch": "Coase corpurile suprafață între ele de-a lungul muchiilor comune, într-un solid când se închid. Folosiți-o pentru a transforma un set de suprafețe într-un singur corp.", + "help.surface.sweep": "Mută curbe sau profile de schiță de-a lungul unui traseu într-o suprafață, fără capace. Folosiți-o pentru jgheaburi, ornamente și alte forme subțiri care urmează un traseu.", + "help.surface.thicken": "Dă unui corp suprafață o grosime, transformându-l într-un solid. Folosiți-o pentru a face piese imprimabile sau prelucrabile din suprafețe.", + "help.surface.trim": "Taie o suprafață cu un plan, o altă suprafață sau curbe de schiță și păstrează partea pe care o alegeți. Folosiți-o pentru a tăia suprafețele la formă înainte de coasere.", + "help.surface.unstitch": "Separă fețele unui corp în corpuri suprafață proprii; un solid se desface în suprafețe. Folosiți-o pentru a reface fețe individuale ale unui corp.", + "help.surface.untrim": "Elimină găurile dintr-o față sau readuce conturul ei exterior la limitele naturale ale suprafeței. Folosiți-o pentru a recupera suprafața întreagă după o tăiere.", "help.third_party": "Licențe terțe", "help.timeline.compute_all": "Reconstruiește toate operațiile din cronologie, de la început. Se folosește pentru a reîmprospăta modelul și a vedea ce operații eșuează.", "help.timeline.delete": "Șterge operațiile selectate din cronologie; ștergerea unei schițe șterge și operațiile construite din ea. Se folosește pentru a elimina un pas care nu mai este dorit.", + "help.timeline.dependents": "Listează operațiile care ar fi șterse odată cu o operație și pe cele care ar eșua fără ea. Folosiți-o înainte de a șterge sau a modifica o operație.", "help.timeline.play": "Redă operațiile rămase pe rând, cu o pauză de o jumătate de secundă după fiecare reconstrucție. Rulați din nou această comandă sau apăsați Escape pentru a opri; Mergi la sfârșit sare imediat.", + "help.view.apply": "Rotește vizualizarea într-o direcție standard, de exemplu față, sus sau izometrică, sau într-o vizualizare numită salvată. Folosiți-o pentru a privi modelul dintr-un unghi fix.", + "help.view.delete": "Șterge o vizualizare numită salvată. Modelul nu este modificat.", + "help.view.fit": "Mărește și panoramează astfel încât tot modelul sau selecția să umple vizualizarea. Folosiți-o când modelul a ieșit din câmpul vizual.", + "help.view.grid": "Afișează sau ascunde grila din fereastra de vizualizare. Folosiți-o ca ghid de dimensiune și orientare în timpul modelării.", + "help.view.ground_shadow": "Afișează sau ascunde umbra modelului pe sol. Folosiți-o pentru a aprecia mai ușor înălțimea și poziția.", + "help.view.home": "Readuce vizualizarea la direcția de start și încadrează modelul. Folosiți-o pentru a reveni rapid la o vizualizare cunoscută.", + "help.view.list": "Listează vizualizările numite salvate în proiect. Folosiți-o pentru a găsi o vizualizare salvată mai devreme.", + "help.view.navigate": "Rotește, panoramează sau mărește vizualizarea în pași, de exemplu un sfert de rotație la stânga. Folosiți-o pentru a mișca precis camera în loc să trageți.", + "help.view.navigation_bar": "Afișează sau ascunde bara de navigare din partea de jos a ferestrei de vizualizare. Ascundeți-o pentru mai mult spațiu, afișați-o pentru a ajunge cu mouse-ul la instrumentele de vizualizare.", + "help.view.rename": "Dă un nume nou unei vizualizări numite salvate. Vizualizarea în sine rămâne neschimbată.", + "help.view.save": "Salvează poziția curentă a camerei ca vizualizare numită în proiect. Folosiți-o pentru a reveni mai târziu la același unghi, de exemplu pentru capturi de ecran.", + "help.view.spin": "Orbitează continuu vizualizarea în jurul modelului până la următorul clic sau la următoarea tastă. Folosiți-o pentru a prezenta un model din toate părțile.", + "help.view.tool": "Fixează un instrument de cameră, orbitare, panoramare sau zoom, astfel încât tragerea cu butonul stâng al mouse-ului să miște vizualizarea până îl dezactivați. Folosiți-l pe un trackpad sau fără buton de mijloc la mouse.", + "help.view.visual_style": "Schimbă modul în care este desenat modelul: umbrit cu sau fără muchii, cadru de sârmă sau cu muchii ascunse. Folosiți cadrul de sârmă pentru a vedea înăuntru, umbrirea pentru un aspect curat.", + "history.sketch_under_constrained": "Constrângeri insuficiente ({count} grade de libertate)", + "history.sketch_under_constrained_one": "Constrângeri insuficiente ({count} grad de libertate)", "hole_presets.confirm_delete": "Confirmă ștergerea", "hole_presets.delete": "Șterge", "hole_presets.delete_prompt": "Ștergeți această presetare personală? Găurile existente rămân neschimbate.", @@ -1525,6 +1837,8 @@ "joint_move.blocked_hint": "Verificați tipul îmbinării (de exemplu Rigidă), fixarea, limitele îmbinării și valorile conduse de parametri.", "joint_move.blocked_title": "Această piesă nu poate fi mutată", "joint_move.coarse": "Pas de rotire lângă axă (°)", + "joint_move.conflict": "O îmbinare a acestei piese este în conflict cu celelalte: {joint}.", + "joint_move.conflict_hint": "Editați, suprimați sau ștergeți îmbinarea în conflict, ca celelalte îmbinări să poată poziționa piesa.", "joint_move.distance": "Distanță față de start", "joint_move.done": "Gata", "joint_move.fine": "Pas de rotire departe de axă (°)", @@ -1596,6 +1910,10 @@ "material.selection.mixed": "Materiale diferite", "measure.at": "La", "measure.item": "Element {number}", + "measure.quick_copied": "Măsurătoare copiată", + "measure.quick_copy": "Clic pentru a copia măsurătoarea", + "measure.quick_edges": "{count} muchii", + "measure.quick_faces": "{count} fețe", "messages.ago_h": "acum {n} h", "messages.ago_min": "acum {n} min", "messages.ago_s": "acum {n} s", @@ -1620,6 +1938,8 @@ "motion.track_name": "Pista {number}", "nav.alias.help": "Shift+Alt+tragere cu stânga orbitează, Shift+Alt+tragere cu mijlocul panoramează, Shift+Alt+tragere cu dreapta face zoom; tragerea cu mijlocul panoramează și ea, iar tragerea cu dreapta orbitează", "nav.blender.help": "Tragerea cu mijlocul orbitează, Shift+mijloc panoramează, Ctrl+mijloc face zoom; tragerea cu dreapta nu mișcă camera", + "nav.creo.help": "Tragerea cu mijlocul orbitează, Shift+mijloc panoramează, tragerea verticală cu Ctrl+mijloc face zoom (în jos pentru apropiere); rotița mouse-ului face zoom", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Mouse-ul și mouse-ul 3D rotesc vizualizarea prin ambii poli și păstrează ruliul. Agățarea pe axe cu Shift este dezactivată.", "nav.free_orbit.label": "Orbitare liberă", "nav.free_orbit.snap_help": "Mouse-ul și mouse-ul 3D rotesc vizualizarea prin ambii poli și păstrează ruliul. Țineți apăsat Shift în timpul tragerii de orbitare pentru a agăța direcția de privire și ruliul.", @@ -1629,6 +1949,7 @@ "nav.hfss.help": "Alt+tragere cu butonul stâng: panoramare, Shift+Alt+tragere cu butonul stâng: zoom, Ctrl+tragere cu butonul stâng pe spațiu gol: orbitare", "nav.inventor.help": "Tragerea cu mijlocul panoramează, Shift+mijloc orbitează, Ctrl+mijloc face zoom, tragerea cu dreapta orbitează", "nav.maya.help": "Alt+tragere cu butonul stâng: orbitare, Alt+butonul din mijloc: panoramare, Alt+butonul drept: zoom; tragerea cu butonul din mijloc face de asemenea panoramare", + "nav.nx.help": "Tragerea cu mijlocul orbitează, Shift+mijloc panoramează (mijloc + dreapta în NX), Ctrl+mijloc face zoom (mijloc + stânga în NX); tragerea cu dreapta nu mișcă camera", "nav.openscad.help": "Tragerea cu stânga pe spațiu gol orbitează, Shift+tragere cu stânga selectează cu casetă, tragerea geometriei schiței o editează; tragerea cu dreapta sau cu mijlocul panoramează, Shift+tragere cu dreapta sau Shift+tragere cu mijlocul face zoom", "nav.perspective.sketch": "Editarea schiței folosește vizualizarea ortografică. Finalizați schița pentru a comuta la perspectivă.", "nav.right_drag_orbits.help": "Dezactivat: tragerea cu dreapta nu mișcă camera, iar butonul drept doar deschide meniul contextual. Alegerea mapării de mouse SolidWorks dezactivează această opțiune.", @@ -1748,6 +2069,11 @@ "not a move": "nu este o mutare", "not a number": "nu este un număr", "open a sketch first": "deschideți mai întâi o schiță", + "parameters.apply_live": "Aplică fiecare modificare la ieșirea din câmpul ei", + "parameters.apply_live_tip": "Dezactivat: modificările așteaptă până la Aplică sau OK, apoi proiectul se reconstruiește o singură dată pentru toate. Anulează sau Escape le abandonează.", + "parameters.held": "{count} modificări în așteptare până la Aplică", + "parameters.held_hint": "Editați expresii și unități. Modificările așteaptă până la Aplică sau OK.", + "parameters.held_one": "1 modificare în așteptare până la Aplică", "parts.automatic_name": "automat", "parts.dimension.across_flats": "Deschidere cheie", "parts.dimension.bore": "Alezaj", @@ -1766,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Șurub cu cap bombat și locaș hexagonal", "parts.family.dowel_pin": "Știft cilindric (de centrare)", "parts.family.hex_bolt": "Șurub / bolț cu cap hexagonal", + "parts.family.hex_cap_screw_inch": "Șurub cu cap hexagonal (inci)", "parts.family.hex_nut": "Piuliță hexagonală", + "parts.family.hex_nut_inch": "Piuliță hexagonală (inci)", "parts.family.set_screw": "Șurub de fixare cu locaș hexagonal, vârf plat", "parts.family.socket_head_cap_screw": "Șurub cu cap cilindric și locaș hexagonal", "parts.family.washer": "Șaibă plată", + "parts.family.washer_sae": "Șaibă plată, SAE (îngustă)", + "parts.family.washer_uss": "Șaibă plată, USS (lată)", + "parts.holes": "Găuri (opțional)", + "parts.placement_hint": "alegeți una sau mai multe găuri pentru a așeza câte o piesă în fiecare, sau OK plasează piesa în origine", + "parts.system": "Sistem de unități", + "parts.system.inch": "Inci", + "parts.system.metric": "Metric", "pattern.alignment_2": "Aliniere 2", "pattern.alignment_hint": "Numărul include originalul. Centrat echilibrează copiile; Inversare alege partea suplimentară pentru totaluri pare.", "pattern.direction_1": "Direcția 1", @@ -1810,6 +2145,8 @@ "prefs.anti_aliasing_note": "Netezește muchiile zimțate.", "prefs.applies_on_restart": "Se aplică la repornire", "prefs.assistant": "Asistent", + "prefs.auto_operation": "Alege automat operația", + "prefs.auto_operation_note": "Ferestrele operațiilor aleg Unire, Corp nou sau Decupează în funcție de ce atinge materialul nou, până când alegeți una. Dezactivat: păstrează operația cu care se deschid.", "prefs.axes": "Axe", "prefs.axis": "Axă", "prefs.bodies_folders": "Foldere pentru corpuri", @@ -1820,6 +2157,8 @@ "prefs.bottom_centre": "Centru jos", "prefs.bottom_right": "Dreapta jos", "prefs.browser": "Navigator", + "prefs.browser_eye_left": "Ochiul lângă săgeata de restrângere", + "prefs.browser_eye_left_note": "Rândurile din navigator își afișează ochiul de afișare/ascundere lângă săgeata de restrângere, ca înainte, în loc de o coloană la capătul din dreapta al rândurilor.", "prefs.browser_reveal_on_hover": "Afișează la survol", "prefs.browser_show_note": "Afișat ține navigatorul pe ecran. Afișează la survol îl ține ascuns până când indicatorul ajunge pe locul lui sau pe fila subțire de la marginea lui stângă, iar navigatorul rămâne deschis cât timp indicatorul este în interiorul lui sau cât timp un meniu al lui este deschis.", "prefs.browser_shown": "Afișat", @@ -1827,6 +2166,8 @@ "prefs.button_left": "Tragere cu butonul stâng", "prefs.button_middle": "Tragere cu butonul din mijloc", "prefs.button_right": "Tragere cu butonul drept", + "prefs.carousel_next": "Următorul", + "prefs.carousel_previous": "Anteriorul", "prefs.choose_font": "Alegeți fișierul de font…", "prefs.click": "Clic", "prefs.contact_shading": "Umbrire de contact moale", @@ -1839,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Suprafețe curbe", "prefs.curves": "Suprafețe curbe", + "prefs.cut_preview_tint": "Afișează materialul îndepărtat în roșu", + "prefs.cut_preview_tint_help": "O previzualizare umple materialul pe care îl îndepărtează o operație, și forma pe care o înlocuiește, cu o fantomă roșie transparentă. Dezactivat, aceste umpleri sunt complet transparente și se desenează doar contururile lor.", + "prefs.dark_parts_shading": "Păstrează forma pieselor întunecate", + "prefs.dark_parts_shading_help": "Umbrește vizualizarea în lumină liniară, cu o lumină de umplere moale de la cer, astfel încât fețele întunecate să păstreze un gradient în loc să devină negre", "prefs.dead_zone_note": "Banda hașurată este zona moartă: mișcarea din interiorul ei este ignorată.", "prefs.default": "implicit", "prefs.design": "Valori implicite ale proiectului", @@ -1853,6 +2198,8 @@ "prefs.edges": "Muchii și umbrire", "prefs.extend": "Prelungește", "prefs.extra_navigation": "Ctrl+tragere cu butonul stâng pe un spațiu gol orbitează; țineți apăsat Space pentru panoramare.", + "prefs.extrude_view_isometric": "Treci la vizualizarea izometrică la deschiderea Extrudării", + "prefs.extrude_view_return": "Revino la vizualizarea anterioară la închiderea Extrudării", "prefs.follows_os": "Urmează sistemul de operare", "prefs.font": "Font", "prefs.font_fallback": "Glifele care lipsesc din fontul ales trec la fontul încorporat, astfel încât nicio etichetă să nu afișeze un pătrat gol.", @@ -1868,8 +2215,11 @@ "prefs.graphics_card_auto": "Automat", "prefs.graphics_card_missing": "Placa video salvată nu este disponibilă; se folosește Automat.", "prefs.graphics_card_restart": "Intră în vigoare după repornirea SolidCraft. WGPU_ADAPTER_NAME suprascrie această alegere.", + "prefs.graphics_card_unused": "Placa video salvată nu a fost folosită pentru această fereastră; placa în uz este afișată în Ajutor › Despre și în bara de stare. Încercați Automat sau setați WGPU_ADAPTER_NAME la o parte unică din numele plăcii.", "prefs.graphics_note": "Alegeți între viteză și netezime. Fiecare opțiune își arată efectul pe un eșantion.", "prefs.graphics_presets_note": "Presetările stabilesc împreună opțiunile de mai jos.", + "prefs.hide_constraint_glyphs_zoomed_out": "Ascunde simbolurile de constrângere la micșorare", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Simbolurile de constrângere dispar din vizualizare când schița este micșorată atât de mult încât ar aglomera-o. Dezactivat: rămân la o dimensiune fixă pe ecran la orice nivel de zoom.", "prefs.history": "Istoric", "prefs.history_origin_bodies": "Afișează originea și corpurile în partea de sus", "prefs.history_origin_bodies_note": "Istoricul din stânga sau de sub navigator începe cu dosarul Corpuri al componentei active și cu Originea, cu ochii și meniurile lor ca în navigator. Istoricul din partea de jos rămâne neschimbat.", @@ -1880,6 +2230,8 @@ "prefs.history_sketches_note": "Cu Schițe setat la Sub operația lor, Istoricul din stânga listează fiecare schiță cu un nivel mai în interior, sub prima operație construită din ea, ori de câte ori este suficient de lat pentru nume. Cronologia din partea de jos păstrează întotdeauna ordinea creării.", "prefs.history_sketches_under_feature": "Sub operația lor", "prefs.hold_stop_snapping": "Țineți apăsat pentru a opri agățarea", + "prefs.home_fit_size": "Dimensiunea pentru Acasă și Potrivire", + "prefs.home_fit_size_note": "Cât din vizualizare umple modelul când Acasă, Potrivire, un proiect deschis sau o schimbare de vizualizare din navigatorul de vizualizare îi stabilește încadrarea, indiferent dacă setarea de mai jos este activată sau nu. 100 %: umple vizualizarea dintre panouri, busolă și bara de navigare.", "prefs.icons_only": "Doar pictograme", "prefs.imported_file": "Fișier importat", "prefs.in_browser": "În navigator", @@ -1888,13 +2240,22 @@ "prefs.interface_language": "Limba interfeței", "prefs.interface_note": "Cum arată SolidCraft și unde sunt așezate elementele sale.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Inversează săgețile curbe de ruliu", + "prefs.invert_curved_roll_arrows_note": "Cele două săgeți curbe din colțul cubului rotesc vizualizarea în planul ecranului. Activat: săgeata în sens orar rotește în sens antiorar, iar săgeata în sens antiorar rotește în sens orar. Dezactivat: fiecare săgeată rotește vizualizarea în direcția în care se curbează.", + "prefs.invert_navigator_arrows": "Inversează săgețile de rotație ale cubului de vizualizare", + "prefs.invert_navigator_arrows_note": "Săgețile din jurul cubului rotesc camera în jurul modelului în direcția în care indică, ca în Fusion și Inventor: săgeata din stânga indică spre dreapta și rotește camera spre dreapta. Dezactivat: o săgeată rotește cubul spre partea pe care se află, deci săgeata din stânga rotește camera spre stânga. Săgețile curbe de ruliu nu sunt afectate.", + "prefs.keep_work_on_tab_switch": "Păstrează deschise dialogurile și instrumentele la schimbarea proiectului", + "prefs.keep_work_on_tab_switch_note": "Fiecare filă de proiect își păstrează dialogul sau instrumentul deschis, cu ce ați ales și ați tastat în el, și fila ei din bara de instrumente. Le regăsiți când reveniți la proiect. Dezactivat: schimbarea proiectului le anulează și afișează fila Model.", "prefs.labels": "Etichete", + "prefs.language_system": "Sistem", "prefs.layout": "Dispunere", "prefs.layout_note": "Compact fixează panourile la marginile ferestrei. Transparența navigatorului este disponibilă în modul Plutitor. Schimbați partea Asistentului în pagina Asistent.", "prefs.left": "Stânga", "prefs.left_click": "Clic stânga", "prefs.line_drag_draws_one": "Apăsarea și tragerea desenează o singură linie", "prefs.line_drag_draws_one_note": "În instrumentul Linie, apăsarea, tragerea și eliberarea desenează o singură linie de la punctul apăsării la cel al eliberării, iar linia se termină acolo. Clicurile desenează în continuare un lanț. Dezactivat: o tragere plasează un punct acolo unde este eliberată, la fel ca un clic.", + "prefs.line_hover_tangent_arc": "Oprește indicatorul pe ultimul punct al unei linii pentru a trece la un arc tangent", + "prefs.line_hover_tangent_arc_note": "În instrumentul Linie, după ce a fost desenat un segment, îndepărtați-vă de ultimul punct al lanțului, reveniți și țineți indicatorul nemișcat pe el: următorul clic încheie un arc tangent, iar același gest revine la linii. Dezactivat: oprirea acolo nu face nimic.", "prefs.linked_designs": "Proiecte legate", "prefs.live_input": "Intrare în timp real", "prefs.live_preview": "Previzualizare în timp real", @@ -1908,6 +2269,9 @@ "prefs.max_file_size_step": "Fișiere STEP și de import", "prefs.max_file_size_web": "Aplicația web deschide fișiere STEP și de import de până la 512 MB și proiecte de până la 256 MB: o filă de browser nu poate conține fișiere mai mari. Aplicația desktop permite creșterea acestor limite.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Pictograme mari", + "prefs.menu_list": "Listă", + "prefs.menus": "Meniuri", "prefs.minutes": "minute", "prefs.minutes_suffix": " min", "prefs.mouse": "Mouse și trackpad", @@ -1915,6 +2279,8 @@ "prefs.mouse_mapping": "Mapare mouse", "prefs.navigation": "Navigare", "prefs.navigation_note": "Cum mută vizualizarea mouse-ul, trackpadul și mouse-ul 3D.", + "prefs.navigator_fit": "Potrivește modelul după o schimbare de vizualizare din navigator", + "prefs.navigator_fit_note": "O față, un colț sau o săgeată a cubului de vizualizare ori o axă a reperului de orientare privește și spre mijlocul modelului, de la singura distanță care îl cuprinde din toate părțile (sfera lui de încadrare). Acasă folosește același zoom și același centru cât timp opțiunea este activată, așa că vizualizările alese după aceea doar se rotesc. Dezactivat: vizualizarea se rotește pe loc, păstrându-și ținta și zoomul.", "prefs.network_host_remove": "Elimină", "prefs.network_locations": "Permite locațiile de rețea în proiecte", "prefs.network_locations_note": "Dezactivat: fișierele legate ale unui proiect aflate pe alt computer (\\\\server\\share) se deschid doar de pe serverele listate aici sau după ce permiteți unul, când vi se cere.", @@ -1927,10 +2293,18 @@ "prefs.origin_plane_names": "Numele planelor de origine", "prefs.origin_plane_names_note": "Nume afișate în navigator, în dialoguri și în liste. {top} este XY, {front} este XZ și {right} este YZ, cu Z în sus. Comenzile, scripturile și proiectele salvate păstrează XY, XZ și YZ.", "prefs.overall_speed": "Viteză generală", + "prefs.parameter_list_rows": "Rânduri în lista de parametri", + "prefs.parameter_list_rows_tip": "Săgeata în jos dintr-un câmp de valoare gol listează parametrii, favoriții primii, până la acest număr. Un număr mai mic menține lista ușoară într-un proiect mare.", + "prefs.persistent_ribbon_pressed": "Evidențiază comenzile active din panglică", + "prefs.persistent_ribbon_pressed_help": "Evidențiază comenzile din panglică cât timp efectele lor sunt active. Dezactivați pentru a păstra aspectul neutru anterior și ajutorul pentru comenzi.", "prefs.perspective_fov": "Câmp vizual", "prefs.placement": "Plasare", "prefs.prefer_free_sketch_points": "Preferă punctele de schiță mobile când punctele se suprapun", "prefs.preview_choices": "Previzualizarea opțiunilor alese", + "prefs.preview_tint_new_faces": "Colorează suprafața nouă într-o previzualizare", + "prefs.preview_tint_new_faces_help": "Previzualizarea unei operații care modifică un corp poate desena suprafața adăugată în culoarea previzualizării. Dezactivat, corpul este desenat ca atare.", + "prefs.print_face_highlight": "Evidențierea feței de imprimare", + "prefs.print_face_highlight_tip": "Cât de puternic este colorată și conturată fața de imprimare a unui corp în vizualizare. 0 % nu afișează evidențiere.", "prefs.profile_active": "Profil activ", "prefs.profile_applied": "Profil aplicat.", "prefs.profile_changed": "Setările s-au modificat de la salvarea profilului. Salvează le păstrează în el.", @@ -1952,9 +2326,13 @@ "prefs.quality_fastest": "cel mai rapid", "prefs.quality_slowest": "cel mai lent", "prefs.quality_smoother": "mai neted", + "prefs.quick_measure": "Măsurătoare rapidă în colțul vizualizării", + "prefs.quick_measure_note": "Dimensiunea selecției în colțul din dreapta jos al vizualizării: lungimea unei muchii sau Ø și R pentru una rotundă, aria unei fețe, poziția unui punct, distanța și unghiul dintre două elemente, totalul mai multor muchii sau fețe. Un clic o copiază.", "prefs.render_previous_geometry_budget": "Folosește bugetul anterior de geometrie pentru previzualizarea din Randare", "prefs.render_previous_geometry_budget_help": "Restabilește limita fixă anterioară de geometrie (512 MiB pe desktop pe 64 de biți, 128 MiB în rest) în locul bugetului bazat pe dispozitiv.", "prefs.reports_saved": "{n} salvate", + "prefs.ribbon_click_ends_tool": "Un clic pe butonul instrumentului în uz îl încheie", + "prefs.ribbon_click_ends_tool_note": "Un clic pe butonul evidențiat din panglică al instrumentului de schiță în uz încheie instrumentul, astfel încât clicurile din vizualizare selectează din nou. Dezactivat: clicul pornește din nou instrumentul.", "prefs.ribbon_reveal": "Afișează rezultatele căutării în panglică", "prefs.ribbon_reveal_note": "Trecerea cursorului peste un rezultat din Caută comenzi arată unde se află comanda în panglică: fila, butonul sau rândul ei din lista derulantă a unui panou. O comandă pornită din căutare clipește acolo, iar o comandă în curs pornită dintr-o listă derulantă îi marchează panoul.", "prefs.right_click": "Clic dreapta", @@ -1965,6 +2343,8 @@ "prefs.search_empty": "Nicio setare corespunzătoare", "prefs.select": "Selectează", "prefs.select_one_item": "Selectați un element", + "prefs.select_other_hidden": "Selectează geometria ascunsă cu Selectează altul", + "prefs.select_other_hidden_help": "Activat: include corpurile ascunse, schițele ascunse și muchiile acoperite din apropierea indicatorului. Dezactivat: folosește lista inițială de geometrie vizibilă de sub indicator.", "prefs.selecting": "Selectare", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift doar adaugă; Ctrl / Cmd comută", @@ -1976,31 +2356,63 @@ "prefs.sketch_align_points_note": "În timpul desenării, un punct se aliniază simultan pe orizontală cu un punct de schiță și pe verticală cu altul, cu un ghid punctat, iar clicul păstrează ambele alinieri. Dezactivat: doar cu punctul anterior, pe o singură axă odată.", "prefs.sketch_conflict_colour": "Geometrie în conflict, în culoarea de conflict", "prefs.sketch_conflict_colour_note": "Cât timp constrângerile unei schițe sunt în conflict, curbele și punctele pe care le leagă o constrângere eșuată sunt desenate și ele în culoarea de conflict, nu doar simbolul sau cota ei. Dezactivat: își păstrează culorile obișnuite.", + "prefs.sketch_construction_lines": "Scule extinse pentru dreptele de construcție", "prefs.sketch_exit_view": "Când se încheie o schiță", "prefs.sketch_exit_view.keep": "Păstrează vizualizarea curentă", "prefs.sketch_exit_view.previous": "Revino la vizualizarea anterioară", "prefs.sketch_exit_view.unless_rotated": "Revino, dacă nu a fost rotită", "prefs.sketch_exit_view_note": "Unde ajunge vizualizarea după Finalizează schița, Anulează sau un dublu Esc.", + "prefs.sketch_face_activates_part": "Schițarea pe fața unei piese activează acea piesă", + "prefs.sketch_face_activates_part_note": "O schiță începută pe fața unui corp al altei componente activează mai întâi acea componentă, astfel încât schița îi aparține și rămâne cu acea piesă în Navigator. Piesa rămâne activă după aceea. Dezactivat: schița aparține componentei active.", + "prefs.sketch_open_look_at": "Rotește vizualizarea spre schiță la deschiderea ei", + "prefs.sketch_open_look_at_note": "Dezactivat: crearea sau editarea unei schițe lasă vizualizarea neschimbată. Comanda Privește spre orientează vizualizarea spre schiță atunci când doriți.", "prefs.sketch_recent_snap": "Agățare automată la centrele și punctele de mijloc recente", "prefs.sketch_recent_snap_note": "În timpul desenării, cursorul se agață acolo unde se intersectează ghidurile ultimelor două centre de cerc sau puncte de mijloc ale liniilor drepte. Dezactivat: aceste ghiduri rămân doar vizuale, iar cursorul nu se mișcă.", "prefs.sketch_selection": "Schiță și selecție", "prefs.sketch_selection_heading": "Schiță și selecție", "prefs.sketch_selection_note": "Cum se agață schițele și cum selectează clicurile.", + "prefs.sketch_state_icons": "Pictogramele schițelor în culoarea stării lor", + "prefs.sketch_state_icons_note": "În Istoric și în navigator, pictograma unei schițe preia culoarea stării ei (constrângeri insuficiente, complet constrânsă sau în conflict), iar sugestia ei indică starea. Dezactivat: toate schițele au aceeași pictogramă.", "prefs.sketch_tab_always": "Păstrează fila Schiță afișată", "prefs.sketch_tab_always_note": "Fila Schiță rămâne în panglică, imediat după Model, cât timp nu este deschisă nicio schiță. Sculele ei de desenare pornesc atunci o schiță pe planul sau fața selectată ori pe planul pe care îl alegeți în continuare, cu scula deja activă în ea.", "prefs.sketch_tracking_guides": "Ghiduri de aliniere pentru centru și punct de mijloc", "prefs.sketch_tracking_guides_note": "Treceți cu cursorul peste centrul unui cerc sau peste mijlocul unei linii drepte, apoi deplasați-vă orizontal sau vertical pentru a afișa un ghid punctat temporar.", + "prefs.sketch_tracking_points": "Ghiduri de aliniere de la capete și colțuri în timpul desenării", + "prefs.sketch_tracking_points_note": "Cât timp un instrument de desen așteaptă un punct, trecerea cursorului peste capătul unei linii sau al unui arc, peste un colț de dreptunghi sau peste un punct liber arată același ghid punctat temporar ca la un centru sau un punct de mijloc. Dezactivat: doar centrele și punctele de mijloc.", "prefs.sketching": "Schițare", "prefs.snap_drawing_note": "În timp ce desenați sau trageți un punct de schiță.", "prefs.source": "Sursă", "prefs.speed": "Viteză", "prefs.stand_up_note": "După ce un fișier STEP sau IGES se deschide cu Z în sus, oferă o rotire cu un sfert de tură în jurul lui X.", + "prefs.stand_up_unknown": "Pentru fișiere din programe necunoscute", + "prefs.stand_up_unknown.ask": "Întreabă într-un dialog", + "prefs.stand_up_unknown.note": "Afișează o notă", + "prefs.stand_up_unknown.off": "Nu oferi", + "prefs.stand_up_unknown_note": "Cum se face oferta atunci când antetul fișierului nu indică niciun program cunoscut că salvează cu Y în sus. O notă apare doar când fișierul pare să zacă pe spate; Întreabă într-un dialog întreabă pentru fiecare astfel de fișier, ca înainte.", "prefs.status_bar": "Bară de stare", "prefs.status_bar_note": "O bară subțire de-a lungul marginii de jos a ferestrei arată ce se editează, starea schiței deschise prin culoarea ei și unitățile proiectului; un clic pe unități le schimbă. Starea schiței nu mai apare atunci în colțul vizualizării.", "prefs.status_done": "Gata", "prefs.status_error": "Eroare", "prefs.status_selected": "Selectat", "prefs.status_warning": "Avertisment", + "prefs.structure.appearance": "Aspect", + "prefs.structure.appearance_note": "Culori, text și accesibilitate.", + "prefs.structure.in_profile": "În profil", + "prefs.structure.layout": "Dispunere", + "prefs.structure.layout_note": "Unde se află părțile ferestrei.", + "prefs.structure.look": "Stil", + "prefs.structure.measure_pointer": "Măsurare și indicator", + "prefs.structure.mouse3d": "Mouse 3D", + "prefs.structure.mouse3d_note": "SpaceMouse și SpaceNavigator.", + "prefs.structure.navigation_note": "Mouse și trackpad. Mouse-ul 3D are propria pagină.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Modificat de la salvare", + "prefs.structure.profile_hover": "Salvat în profilurile de setări", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Schiță", + "prefs.structure.tools": "Instrumente", + "prefs.structure.tools_note": "Cum se comportă instrumentele de modelare.", + "prefs.structure.work": "Lucru", "prefs.supersampling_brief": "Desenează vizualizarea mai mare și o filtrează la dimensiunea finală: foarte clar, dar mai solicitant.", "prefs.tab_accent_note": "Accentul urmează fila activă", "prefs.theme_file": "fișier de temă", @@ -2012,6 +2424,16 @@ "prefs.theme_follow_off": "Dezactivat", "prefs.theme_follow_stop": "Oprește urmărirea", "prefs.theme_import_hint": "Faceți clic pentru a alege un fișier de temă, trageți unul aici sau apăsați Ctrl+V (Cmd+V pe Mac) cu o temă copiată", + "prefs.theme_option_opacity": "Opacitate", + "prefs.theme_option_opacity_help": "Reglați opacitatea panourilor flotante. Un prag de lizibilitate protejează textul de deasupra culorilor ferestrei de vizualizare.", + "prefs.theme_option_tab_colours": "Culorile filelor", + "prefs.theme_option_tab_colours_help": "Folosește culorile panourilor și ale ferestrei de vizualizare ale acestei teme pentru fiecare filă din panglică.", + "prefs.theme_option_tab_fade_ms": "Tranziția filelor", + "prefs.theme_option_tab_fade_ms_help": "Estompează culorile panourilor și ale ferestrei de vizualizare la schimbarea filelor. Zero comută instantaneu.", + "prefs.theme_options_badge": "Opțiuni", + "prefs.theme_options_more": "Mai multe · {count}", + "prefs.theme_options_reset": "Resetează", + "prefs.theme_options_unavailable": "Indisponibil pe acest dispozitiv", "prefs.theme_paste": "Lipește tema", "prefs.theme_paste_none": "Clipboardul nu conține nicio temă SolidCraft", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2455,23 @@ "prefs.under_cursor": "Sub cursor", "prefs.units_precision": "Unități și precizie", "prefs.updates": "Actualizări", + "prefs.value_boxes_in_view": "Arată valorile lângă mânerele lor în vizualizare", + "prefs.value_boxes_in_view_tip": "Valoarea unei comenzi (Distanță, Rază…) într-o casetă lângă mânerul ei, deasupra modelului. Dezactivat: o tastați în fereastra comenzii, care preia tastatura după o alegere, și nimic nu acoperă modelul.", "prefs.view": "Comportamentul vizualizării", "prefs.view_confirm_corner": "OK și Anulează în colțul vizualizării", "prefs.view_confirm_corner_note": "Cât timp este deschis un dialog sau o schiță, o bifă și o cruce în dreapta sus a vizualizării fac ce fac OK și Anulează din dialog, sau finalizează și anulează schița. Controlul de navigare al vizualizării se mută mai jos, sub ele.", "prefs.viewport": "Fereastră de vizualizare", + "prefs.viewport_analysis_status": "Afișează starea analizelor deasupra ferestrei de vizualizare", + "prefs.viewport_analysis_status_help": "Afișează analizele active deasupra ferestrei de vizualizare, deschide legenda fiecăreia din elementul ei și folosește Esc pentru a dezactiva cea mai recentă analiză. Dezactivați pentru a reveni la legendele din colțuri și la comportamentul anterior al tastei Esc.", "prefs.viewport_background": "Fundal", "prefs.viewport_background_colour": "Culoare", "prefs.viewport_background_theme": "Gradientul temei", + "prefs.viewport_section_status": "Afișează starea secțiunii în fereastra de vizualizare", + "prefs.viewport_section_status_help": "Afișează setarea secțiunii în fereastra de vizualizare. Escape și butonul activ din panglică o dezactivează. Dezactivați pentru a păstra comenzile anterioare ale secțiunii.", + "prefs.viewport_status_details": "Detalii live ale ferestrei de vizualizare", + "prefs.viewport_status_details_help": "Editați setările active de analiză și de secțiune în carduri standard de detalii. Dezactivați pentru a restabili legendele de analiză doar în citire și dialogul Secțiune.", + "prefs.viewport_status_summary": "Restrânge elementele de stare ale ferestrei de vizualizare", + "prefs.viewport_status_summary_help": "Restrânge trei sau mai multe elemente de stare ale ferestrei de vizualizare într-o singură etichetă rezumat. Dezactivați pentru a păstra toate elementele în rândul complet.", "prefs.wheel": "Rotiță", "prefs.wheel_trackpad": "Rotiță și trackpad", "prefs.workspace": "Spațiu de lucru", @@ -2049,6 +2481,10 @@ "properties.title": "Proprietăți: {name}", "recovery.days_ago": "acum {count} zile", "recovery.detail": "{file} · {features} operații · salvat automat {when}", + "recovery.discard_all": "Renunță la toate", + "recovery.discard_all_detail": "Această acțiune nu poate fi anulată.", + "recovery.discard_all_title": "Renunțați la salvările automate ({count})?", + "recovery.discard_all_title_one": "Renunțați la 1 salvare automată?", "recovery.hours_ago": "acum {count} h", "recovery.just_now": "chiar acum", "recovery.min_ago": "acum {count} min", @@ -2164,6 +2600,10 @@ "render.base_color": "Culoare de bază · sRGB", "render.base_metallic": "Fracție metalică", "render.base_opaque_only": "Acest editor păstrează semantica corpurilor opace. Pentru transmisia optică folosiți controalele explicite pentru sticlă.", + "render.batch_all_shots": "Toate cadrele ({count})", + "render.batch_empty": "Salvați un cadru înainte de a randa toate cadrele.", + "render.batch_limit": "Randarea tuturor cadrelor este limitată la 32 de cadre.", + "render.batch_status": "{running} în desfășurare · {waiting} în așteptare", "render.bloom_enable": "Afișează bloom", "render.bloom_help": "Strălucire creativă, doar la ieșire, provenită din zonele luminoase liniare pozitive și răspândită prin trei treceri box normalizate. Raza este în pixeli de ieșire. Se adaugă în lumina de afișare liniară, înainte de sRGB; nu este un efect de lentilă, un efect volumetric sau o îmbunătățire a convergenței. EXR-ul brut rămâne neschimbat.", "render.bloom_opaque": "Bloom necesită ieșire opacă. PNG-ul transparent este refuzat, nu aplatizat în tăcere.", @@ -2274,6 +2714,13 @@ "render.choose_look": "Alegeți mai întâi un stil în Aspecte", "render.chromatic_offset": "Decalaj cromatic al marginilor", "render.clear_stage": "Elimină decorul salvat", + "render.compare_divider": "Separator de comparație", + "render.compare_live": "Live", + "render.compare_live_preview": "Previzualizare în timp real", + "render.compare_render": "Randarea {number}", + "render.compare_side": "Randarea {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · capturat la revizia {revision}", + "render.compare_swap": "Schimbă", "render.copy_request": "Copiază JSON", "render.cpu_aa_help": "Eșantioane spațiale: mai multe eșantioane îmbunătățesc marginile și măresc timpul de randare.", "render.cpu_area_add": "Adaugă lumină dreptunghiulară CPU", @@ -2914,7 +3361,9 @@ "render.output_ready": "Gata de randare", "render.output_run_check": "Rulează verificarea", "render.output_size_limit": "{method}: până la {dimension} px pe latură și {pixels} pixeli. Cea mai mare dimensiune care încape: {width} × {height}.", + "render.output_size_method_profile": "Pentru a randa {width} × {height}, alegeți {method} cu profilul de resurse CPU {profile} sau o dimensiune mai mică.", "render.output_size_ok": "Dimensiune OK · {width} × {height} px", + "render.output_size_profile": "Pentru a randa {width} × {height}, alegeți profilul de resurse CPU {profile} sau o dimensiune mai mică.", "render.output_swap_orientation": "Interschimbă lățimea și înălțimea", "render.output_tools_inspector": "Editați dimensiunea și formatul în inspectorul Ieșire.", "render.output_view_image": "Vizualizează imaginea", @@ -3021,6 +3470,10 @@ "render.result_retained": "Se afișează ultima imagine finalizată; o randare mai nouă nu a înlocuit-o.", "render.result_sequence": "Punct de control", "render.result_title": "Rezultatul randării", + "render.results_choose": "Rezultate păstrate", + "render.results_label": "Randarea {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [învechit]", + "render.results_unnamed": "Imagine", "render.return_design": "Înapoi la proiectare", "render.review_stale": "Această revizuire este depășită. Rezolvați sau verificați din nou înainte de aplicare.", "render.ribbon_aging": "Îmbătrânire", @@ -3127,6 +3580,7 @@ "render.size_custom": "Personalizat…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · necesită {profile}", "render.size_presets": "Presetări de dimensiune", "render.size_presets_pending": "Apare odată cu editorul de ieșire", "render.size_preview": "Previzualizare", @@ -3414,6 +3868,24 @@ "sheet.flange_type_contour": "Contur", "sheet.flange_type_edge": "Muchie", "sheet.no_body": "nu există un corp din tablă: începeți unul cu Flanșă > Bază sau transformați o placă în tablă cu Convertește în tablă (alegeți fața ei mare și plată)", + "sheet.personal_rules.confirm_delete": "Confirmă ștergerea", + "sheet.personal_rules.delete": "Șterge", + "sheet.personal_rules.delete_prompt": "Ștergeți această regulă personală? Regulile deja existente în proiecte rămân neschimbate.", + "sheet.personal_rules.full": "Biblioteca personală conține deja 64 de reguli.", + "sheet.personal_rules.invalid_name": "Introduceți un nume scurt, fără întreruperi de rând sau caractere de control.", + "sheet.personal_rules.invalid_values": "Completați valorile regulii: fiecare trebuie să poată fi calculată în acest proiect, cu o grosime pozitivă și un factor K între 0 și 1.", + "sheet.personal_rules.missing": "Regula personală selectată nu mai este disponibilă.", + "sheet.personal_rules.name": "Numele regulii", + "sheet.personal_rules.name_exists": "Există deja o regulă personală cu acest nume. Folosiți alt nume.", + "sheet.personal_rules.name_hint": "Un nume unic", + "sheet.personal_rules.overwrite": "Salvează modificările în regula personală selectată", + "sheet.personal_rules.rename": "Redenumește", + "sheet.personal_rules.rule": "Regulă personală", + "sheet.personal_rules.save": "Salvează ca nouă", + "sheet.personal_rules.scope": "Salvată în profil, pentru toate proiectele.", + "sheet.personal_rules.select": "Alegeți o regulă", + "sheet.personal_rules.title": "Reguli personale", + "sheet.personal_rules.unsupported": "Această regulă are valori pe care această versiune nu le poate folosi.", "shortcut.json_error": "parametrii trebuie să fie JSON: {error}", "shortcut.no_command": "nu există comanda `{id}`; textul dinaintea JSON trebuie să fie un id de comandă", "shortcut.pin": "Fixează în partea de sus a casetei S", @@ -3450,8 +3922,10 @@ "sketch_text.align_right": "Dreapta", "sketch_text.bold": "Aldin", "sketch_text.builtin_font": "{family} (încorporat)", + "sketch_text.formula": "Începeți cu = pentru a construi cuvintele din parametri: ='W' + number(Width)", "sketch_text.italic": "Cursiv", "sketch_text.loading_fonts": "Se caută fonturile instalate…", + "sketch_text.no_bold": "Fontul încorporat nu are variantă aldină: alegeți un font instalat", "sketch_text.on_path": "Textul urmează traseul său: curba îl poziționează", "sketch_text.path_clear": "Scoate textul de pe curbă", "sketch_text.path_hint": "O curbă a schiței pe care o urmează textul: faceți clic aici, apoi pe curbă", @@ -3483,10 +3957,7 @@ "the two origins are on the same component": "cele două origini sunt pe aceeași componentă", "thread.automatic_size": "Dimensiune automată", "thread.designation": "Denumire", - "thread.direction": "Sensul filetului", "thread.iso_metric": "ISO metric", - "thread.left_hand": "Pe stânga", - "thread.right_hand": "Pe dreapta", "thread.select_size": "Selectați dimensiunea", "timeline.delete_after_marker_one": "Șterge 1 operație după marcajul de istoric", "timeline.delete_after_marker_other": "Șterge {count} operații după marcajul de istoric", @@ -3503,8 +3974,10 @@ "timeline.move_to_group": "Mută operațiile în dosar", "timeline.rename_group": "Redenumește dosarul de operații", "timeline.reorder_many": "Reordonează operațiile", + "timeline.suppress_features": "Suprimă operațiile", "timeline.suppress_folders_tip": "Suprimă sau anulează suprimarea tuturor operațiilor din dosare și din dosarele lor imbricate", "timeline.ungroup": "Elimină dosarele de operații", + "timeline.unsuppress_features": "Anulează suprimarea operațiilor", "to the face": "până la față", "to the next face": "până la fața următoare", "toolbar.customize_note": "Fila {tab}. Bifați o comandă pentru a-i da un buton în bara de instrumente. Puteți și să trageți un rând din lista derulantă a unui panou pe bara de instrumente, să trageți un buton în afara barei pentru a-l elimina sau să folosiți pionezul de pe un rând din lista derulantă.", @@ -3588,6 +4061,8 @@ "ui.3d_mouse_section": "Mouse 3D", "ui.3d_mouse_show_in_view": "Afișează mouse-ul 3D în vizualizarea 3D", "ui.3d_mouse_show_in_view_tip": "O imagine a mouse-ului 3D în colțul din stânga jos, care se mișcă odată cu el.", + "ui.3d_mouse_sketch_orbit": "Rotește schițele cu mouse-ul 3D", + "ui.3d_mouse_sketch_orbit_tip": "Mouse-ul 3D rotește vizualizarea și când o schiță este deschisă și privită frontal, așa cum poate face mouse-ul. Dezactivat: panoramează și mărește schița până când înclinați vizualizarea.", "ui.3d_mouse_skip": "Dispozitivul meu nu poate face asta", "ui.3d_mouse_skip_tip": "Omite această mișcare în ambele sensuri, iar calibrarea o lasă deoparte.", "ui.3d_mouse_speed": "Viteza mouse-ului 3D", @@ -3616,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Răsuciți capacul în sens invers acelor de ceasornic, țineți-l, apoi eliberați-l.", "ui.3d_mouse_switch_cap": "Calibrează ca dispozitiv cu revenire la centru", "ui.3d_mouse_switch_trackball": "Calibrează ca trackball", + "ui.3d_mouse_use_direct": "Folosește driverul direct", + "ui.3d_mouse_use_direct_tip": "Citește mouse-ul 3D direct (hidraw) în loc de prin spacenavd.", "ui.3d_mouse_view_axis": "Axa vizualizării", "ui.3d_mouse_view_off": "Dezactivat", "ui.3d_mouse_view_off_tip": "Profilul driverului mouse-ului 3D dezactivează această axă, deci mișcarea ei nu mișcă vizualizarea. Alegerea aici a mișcării altei axe le interschimbă pe cele două, iar acea mișcare nu mai mișcă vizualizarea.", @@ -3654,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Rulați aceasta într-un terminal, apoi apăsați din nou Conectare:", "ui.agent_chat_auth_title": "Autentificare la agent", "ui.agent_chat_cancel": "Anulează", + "ui.agent_chat_cancel_timeout": "Agentul nu a răspuns la Oprește și a fost deconectat. Reconectați-vă pentru a continua.", + "ui.agent_chat_cannot_start": "Instalat, dar nu pornește: {error}", "ui.agent_chat_changes": "Modificări: {n}, un singur pas de anulare", "ui.agent_chat_changes_n": "{n} modificări", "ui.agent_chat_changes_of": "{n}/{limit} modificări", @@ -3662,11 +4141,13 @@ "ui.agent_chat_command": "Comanda agentului", "ui.agent_chat_connect": "Conectare", "ui.agent_chat_copy": "Copiază", + "ui.agent_chat_copy_message": "Copiază mesajul", "ui.agent_chat_ctx_bodies": "Corpuri", "ui.agent_chat_ctx_elements": "Elemente", "ui.agent_chat_ctx_features": "Operații", "ui.agent_chat_ctx_more": "+{n} în plus", "ui.agent_chat_ctx_other": "Altele", + "ui.agent_chat_custom_heading": "Model personalizat", "ui.agent_chat_custom_hint": "Orice program care vorbește Agent Client Protocol pe stdin și stdout. Nu este rulat de niciun shell.", "ui.agent_chat_denied": "Refuzat", "ui.agent_chat_deny": "Refuză", @@ -3710,8 +4191,16 @@ "ui.agent_chat_mode_all": "Tot", "ui.agent_chat_mode_ask": "Întreabă", "ui.agent_chat_mode_edits": "Modificări", + "ui.agent_chat_model_custom": "Folosește modelul personalizat: {model}", "ui.agent_chat_model_no_tools": "{model} nu poate folosi instrumentele SolidCraft, deci poate doar să converseze. Alegeți un model cu suport pentru instrumente.", + "ui.agent_chat_model_rejected": "Agentul nu a acceptat {model}: {error}", + "ui.agent_chat_model_search": "Caută modele…", "ui.agent_chat_model_tip": "Modelul folosit de agent. Alegerea dumneavoastră este reținută pentru acest agent.", + "ui.agent_chat_models_failed": "Nu s-au putut lista modelele: {error}", + "ui.agent_chat_models_heading": "Modele disponibile", + "ui.agent_chat_models_listing": "Se listează modelele…", + "ui.agent_chat_models_none": "Endpoint-ul nu listează niciun model", + "ui.agent_chat_models_not_a_list": "Răspunsul nu a fost o listă de modele", "ui.agent_chat_new": "Chat nou", "ui.agent_chat_new_confirm": "Începeți un chat nou? Cel curent este șters.", "ui.agent_chat_next_picture": "Imaginea următoare", @@ -3746,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "În coadă (oprit, netrimis)", "ui.agent_chat_refresh": "Reîmprospătare", "ui.agent_chat_refused": "Nepermis pentru agent: {reason}", + "ui.agent_chat_reinstall": "{agent} este instalat ({program}), dar nu a pornit când SolidCraft l-a verificat: {error}\nInstalarea lui poate fi incompletă sau făcută pentru alt tip de calculator. Instalați-l din nou cu `{install}`, verificați într-un terminal că afișează versiunea, apoi apăsați Reîmprospătare.", "ui.agent_chat_remove": "Elimină din coadă", "ui.agent_chat_remove_file": "Scoate-l din acest mesaj", "ui.agent_chat_remove_imported": "Scoate-l din acest mesaj; piesa rămâne în proiect (Anulare o elimină)", + "ui.agent_chat_reply_cut_off": "Răspunsul a atins limita de lungime înainte de a se termina, deci poate fi incomplet. Cereți agentului să continue sau să dea un răspuns mai scurt.", + "ui.agent_chat_reply_declined": "Modelul a refuzat să răspundă la acest mesaj.", "ui.agent_chat_retry": "Reîncearcă", "ui.agent_chat_right": "Dreapta", "ui.agent_chat_save": "Salvează", @@ -3807,12 +4299,17 @@ "ui.ai_copy_suffix": "copie", "ui.ai_custom_url": "URL personalizat", "ui.ai_default": "Implicit", + "ui.ai_edit": "Editează", + "ui.ai_edit_agent_title": "Editează agentul", + "ui.ai_edit_gone": "Acest agent a fost eliminat, deci nu este nimic de salvat.", + "ui.ai_edit_tip": "Schimbă numele, comanda sau endpointul acestui agent. O cheie salvată rămâne ascunsă.", "ui.ai_http_busy": "endpointul este ocupat sau și-a depășit limita; încercați mai târziu", "ui.ai_http_key": "endpointul a refuzat cheia: verificați-o în Preferințe > AI", "ui.ai_http_not_found": "nu există un astfel de endpoint sau model: verificați URL-ul de bază și numele modelului", "ui.ai_http_too_large": "conversația este prea mare pentru acest endpoint; începeți un chat nou", "ui.ai_key": "Cheie API", "ui.ai_key_hint": "opțional; păstrată în depozitul de chei al sistemului", + "ui.ai_key_keep_hint": "lăsați gol pentru a păstra cheia salvată", "ui.ai_key_needs_https": "O cheie se trimite doar prin HTTPS sau către acest calculator.", "ui.ai_key_note": "Stocată în depozitul de chei al sistemului, niciodată în setările SolidCraft. Lăsați gol pentru un server local.", "ui.ai_keychain_error": "Depozitul de chei al sistemului a refuzat: {error}", @@ -3839,11 +4336,15 @@ "ui.ai_permissions": "Permisiuni", "ui.ai_preset": "Presetare", "ui.ai_protocol": "Protocol", + "ui.ai_reasoning_effort": "Efort de raționament", + "ui.ai_reasoning_effort_field_hint": "gol = valoarea implicită a furnizorului", + "ui.ai_reasoning_effort_hint": "Opțional. Trimis către endpoint ca `reasoning_effort`; valorile acceptate diferă în funcție de furnizor (de exemplu `low`, `high` sau `max`). O valoare setată aici nu este niciodată înlocuită de SolidCraft. Lăsați gol pentru a nu trimite nimic și a păstra valoarea implicită a furnizorului.", "ui.ai_remove": "Elimină", "ui.ai_request_timed_out": "Modelul a durat mai mult de {seconds} s. Puteți mări timpul de expirare pentru acest endpoint în Preferințe › Asistent.", "ui.ai_request_timeout": "Timp de expirare a cererii", "ui.ai_request_timeout_hint": "Cât timp poate dura o cerere către model la acest endpoint, de la 30 s la o oră. Măriți-l pentru un model local lent.", "ui.ai_reset": "Resetează", + "ui.ai_save": "Salvează", "ui.ai_settings": "Setări AI…", "ui.ai_show_features": "Afișează funcțiile AI", "ui.ai_show_features_note": "Chatul cu agentul: un panou în care un agent de programare pe care îl folosiți deja sau un endpoint de model ales de dumneavoastră lucrează la proiectul deschis. Dezactivat: fără buton AI, scurtătură, intrare de meniu sau panou, și nu se caută și nu se pornește nimic.", @@ -3922,6 +4423,8 @@ "ui.cancel": "Anulează", "ui.canvases": "Pânze", "ui.center": "Centru", + "ui.center_arc_follows_cursor": "Arcul după centru urmează direcția cursorului", + "ui.center_arc_follows_cursor_tip": "Un arc după centru merge în sens orar sau antiorar, după cum cursorul se rotește în jurul centrului său. Dezactivat: întotdeauna în sens antiorar de la început.", "ui.centerline": "Linie de axă", "ui.chain": "Lanț", "ui.chamfer": "Teșire", @@ -3930,6 +4433,7 @@ "ui.circle": "Cerc", "ui.circular_pattern": "Matrice circulară", "ui.clear": "Șterge", + "ui.clear_print_face": "Șterge fața de imprimare", "ui.clear_recent": "Golește recentele", "ui.clear_the_selection": "Șterge selecția", "ui.click_selects_whole_bodies": "Clicul selectează corpuri întregi", @@ -3964,12 +4468,27 @@ "ui.constant": "Constant", "ui.constraints_conflict": "Conflict de constrângeri", "ui.construction": "Construcție", + "ui.construction.angle_hint": "Dreaptă de construcție: clic pe un punct, apoi tastați un unghi sau alegeți o direcție", + "ui.construction.bisector_hint": "Bisectoare: alegeți două linii drepte care se intersectează, apoi soluția dorită", + "ui.construction.common_hint": "Tangentă comună: alegeți două cercuri/arce, apoi soluția dorită", + "ui.construction.contact_hint": "Tangentă: alegeți un cerc/arc sau un spline/o curbă conică deschisă, apoi punctul de tangență (curbe de formă liberă: capetele)", + "ui.construction.external_hint": "Tangentă: alegeți un cerc sau un arc, un punct exterior, apoi soluția dorită", + "ui.construction.free_hint": "Dreaptă de construcție: clic pe două puncte; clic dreapta pentru a relua", + "ui.construction.normal_needs_length": "O dreaptă infinită este întotdeauna de construcție: introduceți o lungime pentru a desena o linie normală", + "ui.construction.point_hint": "Dreaptă de construcție: clic pe punctul prin care trece", + "ui.construction.reference_hint": "Dreaptă de construcție: alegeți o linie dreaptă, apoi un punct; clic dreapta pentru a schimba referința", "ui.construction.ribbon_label": "Linii aux.", + "ui.construction.side_hint": "Dreaptă de construcție: faceți clic pe partea spre care merge linia; clic dreapta pentru a relua", "ui.context_menu": "Meniu contextual", + "ui.continuity_crease": "Muchie", + "ui.continuity_curvature": "Curbură", + "ui.continuity_curvature_change": "Variația curburii", "ui.continuity_g0": "Muchie G0", "ui.continuity_g1": "Tangent G1", "ui.continuity_g2": "Curbură G2", "ui.continuity_gap": "Spațiu", + "ui.continuity_position": "Poziție", + "ui.continuity_tangent": "Tangent", "ui.copy": "Copiază", "ui.corner": "Colț", "ui.corners": "Colțuri", @@ -3992,6 +4511,7 @@ "ui.dark": "Întunecat", "ui.default_modelling_orientation": "Orientarea implicită de modelare", "ui.delete": "Șterge", + "ui.delete_select_first": "Selectați mai întâi ce doriți să ștergeți: operații, corpuri, componente sau geometrie de schiță", "ui.depth": "Adâncime", "ui.design": "Proiect", "ui.design_properties.author": "Autor", @@ -4006,6 +4526,40 @@ "ui.design_properties.project": "Proiect", "ui.design_properties.revision": "Revizie", "ui.design_saved": "Salvat în {path}", + "ui.details_access_caption": "Fețele arată dacă o sculă le poate atinge din direcția aleasă.", + "ui.details_angle": "Unghi", + "ui.details_continuity_caption": "Editați cusătura selectată. Celelalte cusături își păstrează propriile setări.", + "ui.details_continuity_stale": "Geometrie mai veche: rulați din nou analiza pentru a edita sau a încadra această cusătură.", + "ui.details_copy_list": "Copiază lista", + "ui.details_curvature": "Toleranța curburii", + "ui.details_curvature_caption": "Fețele sunt colorate după raza lor locală de curbură.", + "ui.details_direction": "Direcția sculei", + "ui.details_draft_caption": "Fețele sunt colorate după unghiul lor față de direcția de extragere.", + "ui.details_edit_seam": "Editează cusătura", + "ui.details_fixture": "Exemplar de componentă — doar date de exemplu", + "ui.details_fixture_caption": "Exemplar de componentă cu valori ilustrative; nu este un rezultat al modelului.", + "ui.details_fixture_problem": "Exemplu de constatare cu o problemă", + "ui.details_fixture_readout": "Exemplu de valoare măsurată", + "ui.details_flip": "Răstoarnă", + "ui.details_gap": "Spațiu", + "ui.details_hatch": "Hașurează fețele tăiate", + "ui.details_jump": "Salt de curbură", + "ui.details_key": "Legendă", + "ui.details_offset": "Decalaj", + "ui.details_plane": "Plan", + "ui.details_pull": "Direcția de extragere", + "ui.details_radius": "Rază", + "ui.details_readout": "Citire", + "ui.details_samples": "Eșantioane", + "ui.details_seam": "{body} · Muchia {edge}", + "ui.details_settings": "Setări", + "ui.details_sharp_gap": "Frângere sau spațiu", + "ui.details_show_all": "Afișează toate {count}", + "ui.details_smooth": "Neted", + "ui.details_stripes": "Dungi", + "ui.details_target": "Încadrează geometria", + "ui.details_worst_seams": "Cele mai slabe cusături", + "ui.details_zebra_caption": "Dungile reflectate arată cât de neted se îmbină fețele.", "ui.diameter": "Diametru", "ui.dimension": "Cotă", "ui.direct_interaction": "Interacțiune directă", @@ -4050,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "Piesa a fost salvată într-un alt fișier; ansamblul rămâne legat de {name}", "ui.edit_in_place_wait": "Așteptați până se termină ce rulează în proiect", "ui.edit_section_analysis": "Editează analiza secțiunii", + "ui.edit_sketch_empty": "Nicio schiță de editat", "ui.ellipse": "Elipsă", "ui.emboss_wrap_note": "Profilurile din linii ortogonale, tangente la un cilindru acceptat, se înfășoară automat. Alegeți un perete pentru a alege o țintă.", "ui.end_radius": "Rază finală", @@ -4060,12 +4615,15 @@ "ui.equation_explicit": "Explicită", "ui.equation_form": "Formă", "ui.equation_note": "Variabila este un număr simplu: sin(t) o primește în radiani. Un rezultat fără unitate este în unitatea proiectului.", + "ui.equation_note_range": "Variabila este o lungime, la fel ca intervalul ei: combinați-o cu parametri de lungime și împărțiți-o la o lungime pentru sin(). Un rezultat fără unitate este în unitatea proiectului.", "ui.equation_parametric": "Parametrică", + "ui.equation_variable_unit": "Variabila are unitatea intervalului", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Rază echivalentă", "ui.expand": "Extinde", + "ui.explode_needs_two_components": "Vedere explodată îndepărtează componentele una de alta, deci proiectul trebuie să aibă două sau mai multe (Componentă nouă, Inserează proiect sau Creează componente din corpuri)", "ui.exportDxf": "Exportă DXF…", "ui.export_ellipsis_keymap": "Exportă…", "ui.export_keymap_tip": "Tastele, favoritele casetei S și bara de instrumente, ca fișier", @@ -4191,6 +4749,7 @@ "ui.hideOrigin": "Ascunde originea", "ui.hidePlanes": "Ascunde planele", "ui.hideProfile": "Ascunde profilul", + "ui.hide_component_history": "Ascunde istoricul ei", "ui.hide_origin_by_default": "Ascunde originea implicit", "ui.hide_origin_note": "Proiectele noi încep cu dosarul Origine ascuns. Un proiect își păstrează propria setare Origine după ce îl afișați sau îl ascundeți.", "ui.history_back": "Un pas înapoi", @@ -4198,6 +4757,7 @@ "ui.history_edge_hint": "faceți dublu clic pe muchie", "ui.history_first": "Mergi la început", "ui.history_forward": "Un pas înainte", + "ui.history_hide_hidden": "Ascunde componentele ascunse", "ui.history_hide_names": "Ascunde numele", "ui.history_last": "Mergi la sfârșit", "ui.history_marker_tip": "Marcaj de istoric: trageți-l pentru a derula modelul înapoi; operațiile noi se adaugă aici", @@ -4207,10 +4767,12 @@ "ui.history_play_button_show": "Afișează butonul Redare", "ui.history_play_finish_action": "Finalizați acțiunea curentă înainte de a reda istoricul", "ui.history_play_roll_back": "Mutați marcajul istoricului înapoi înainte de redare", + "ui.history_show_hidden": "Afișează componentele ascunse", "ui.history_show_names": "Afișează numele", "ui.history_sketch_listed_under": "Listată sub {feature}", "ui.history_title": "Istoric", "ui.history_toggle_names": "Afișează sau ascunde numele operațiilor", + "ui.history_waits_for_editor": "Anulează, Refă și Istoric așteaptă până se deschide editorul operației", "ui.hole": "Gaură", "ui.hole_tap_type": "Tip de filetare gaură", "ui.hole_type": "Tip de gaură", @@ -4226,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} are modificări nesalvate, așa că a fost inserat fișierul său salvat. Salvați-l, apoi folosiți Actualizează legăturile pentru a aduce modificările.", "ui.insert_design.unsaved": "Modificări nesalvate", "ui.inspect": "Inspectează", + "ui.instances": "Instanțe", "ui.intersect": "Intersecție", "ui.isolate": "Izolează", "ui.join": "Unire", @@ -4234,12 +4797,14 @@ "ui.joints": "Îmbinări", "ui.keyboard_shortcuts": "Scurtături de tastatură", "ui.language": "Limbă", + "ui.lasso_select": "Lasou (trageți o buclă liberă: preia tot ce se află în întregime înăuntru)", "ui.layout_compact": "Compact", "ui.layout_floating": "Plutitor", "ui.length": "Lungime", "ui.length_decimals": "Zecimale lungime", "ui.light": "Luminos", "ui.line": "Linie", + "ui.line_arc_hint": "Arc tangent: faceți clic pe capătul arcului. Opriți-vă din nou pe ultimul punct pentru linii; clic dreapta sau Esc pentru a finaliza", "ui.link_copies": "Leagă copiile identice", "ui.link_copies_keep": "Păstrează", "ui.link_copies_link": "Leagă", @@ -4328,6 +4893,7 @@ "ui.part_size_shared": "Reconstruiește piesa, înlocuind orice operații adăugate. Toate aparițiile acestei componente se actualizează.", "ui.paste": "Lipește", "ui.path": "Traseu", + "ui.pattern_object_type_tip": "Corpuri: forme solide, alese în vizualizare sau în Navigator; fiecare este copiat întreg.\nOperații: pași ai Istoricului, de exemplu o extrudare sau o gaură, alese în Istoric sau pe o față creată de ei; pasul este repetat.\nO schiță nu este niciuna dintre ele: repetați curbele ei cu Matrice sau Oglindire din schiță, ori extrudați-o mai întâi.", "ui.pattern_on_path": "Matrice pe traseu", "ui.perforate_margin_default": "din diametru", "ui.perforate_pitch": "Pas", @@ -4354,12 +4920,17 @@ "ui.plugins_skipped": "{count} dosar(e) nu au putut fi citite.", "ui.plugins_version": "{version}", "ui.point": "Punct", + "ui.point_cloud_add_filter": "Adaugă filtru…", "ui.point_cloud_auto_range": "Interval automat", "ui.point_cloud_color_by": "Colorează după", "ui.point_cloud_file_colors": "Culorile fișierului", + "ui.point_cloud_filter_by": "Filtrează după", "ui.point_cloud_height_high": "Cel mai înalt", "ui.point_cloud_height_low": "Cel mai de jos", + "ui.point_cloud_legend_filter": "Afișate și ascunse în legenda de mai sus", "ui.point_cloud_no_file_colors": "Fișierul nu are culori", + "ui.point_cloud_pause": "Pauză", + "ui.point_cloud_play": "Redă", "ui.point_cloud_single_color": "Culoare unică", "ui.point_cloud_size": "Dimensiunea punctelor", "ui.point_cloud_units": "Unitățile fișierului", @@ -4368,6 +4939,11 @@ "ui.polygon": "Poligon", "ui.preferences": "Preferințe", "ui.press_a_key": "apăsați o tastă…", + "ui.print_face_body_not_sent": "Corpul acelei fețe nu este trimis: adăugați-l mai întâi la Corpuri", + "ui.print_face_cleared": "{body}: fața de imprimare a fost ștearsă", + "ui.print_face_input": "Față de imprimare", + "ui.print_face_pick": "Selectați o față plană a unui corp solid pentru a o face fața de imprimare", + "ui.print_face_set": "{body}: fața de imprimare a fost setată; Trimite la slicer așază corpul pe ea", "ui.profile": "Profil", "ui.profile_plane": "Planul profilului", "ui.profiles": "Profiluri", @@ -4383,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Se măsoară…", + "ui.properties.measuring_bodies": "Se măsoară… {done} din {total} corpuri", "ui.properties.measuring_failed": "Măsurarea s-a oprit înainte de a se termina.", "ui.properties.principal_axis": "Axa principală {number}", "ui.properties.principal_moments": "Momente principale", @@ -4431,6 +5008,7 @@ "ui.revolve": "Revoluție", "ui.ribbon_exit": "Ieșire", "ui.ribbon_labels": "Afișează text sub pictogramele panglicii", + "ui.ribbon_menus_skip_pinned": "Lasă comenzile fixate în afara listelor derulante", "ui.ribbon_pin_footer": "Comenzile fixate apar pe bandă. Treceți cursorul peste un rând pentru a-l fixa sau defixa.", "ui.ribbon_workspace": "Spațiu de lucru", "ui.right": "Dreapta", @@ -4449,6 +5027,7 @@ "ui.selectOther": "Selectează altul…", "ui.selectTangentChain": "Selectează lanțul tangent", "ui.select_all": "Selectează tot", + "ui.select_components_by_face": "Selectați componente (o față alege componenta ei)", "ui.selection": "Selecție", "ui.selection_modifiers": "Modificatori de selecție", "ui.selection_shift_add_only": "Shift+clic adaugă fără a elimina", @@ -4474,6 +5053,7 @@ "ui.showDimension": "Afișează cota", "ui.showOrigin": "Afișează originea", "ui.showPlanes": "Afișează planele", + "ui.show_component_history": "Afișează istoricul ei", "ui.show_constraints": "Constrângeri", "ui.show_construction_geometries": "Geometrii de construcție", "ui.show_dimensions": "Cote", @@ -4490,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Filtru de selecție", "ui.sketch_modifiers": "Modificatori de schiță", "ui.sketch_project_geometry": "Geometrie", + "ui.sketch_report.all_constrained": "Totul este complet constrâns.", + "ui.sketch_report.dof": "Grade de libertate", + "ui.sketch_report.loose": "Nu sunt complet constrânse", + "ui.sketch_report.status": "Stare", + "ui.sketch_report.title": "Raportul schiței", "ui.sketch_scale": "Scara schiței", "ui.sketches": "Schițe", "ui.slice": "Felie", @@ -4585,19 +5170,31 @@ "ui.view_angles": "Unghiuri de vizualizare", "ui.view_angles_convention": "Grade în jurul axei verticale. Girația 0° este vizualizarea din față, 90° din stânga, −90° din dreapta, 180° din spate; înclinarea 90° este vizualizarea de sus; un ruliu pozitiv rotește modelul în sens orar.", "ui.view_angles_help": "Afișează înclinarea, girația și ruliul vizualizării în grade, plus proiecția ei, sub reperul de orientare. Faceți clic pe valori pentru a introduce unghiuri exacte.", + "ui.view_angles_lock": "Blochează {axis}", "ui.view_angles_ortho": "Ortog.", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Înclinare", "ui.view_angles_readout": "Înclinare {pitch} · Girație {yaw} · Ruliu {roll}", "ui.view_angles_roll": "Ruliu", + "ui.view_angles_unlock": "Deblochează {axis}", "ui.view_angles_yaw": "Girație", + "ui.view_angles_zero": "Setează {axis} la 0°", "ui.view_centre": "Centrul vizualizării", "ui.viewport_status_clear": "Dezactivează {name}", "ui.viewport_status_clear_hint": "Dezactivează {name} · Esc", + "ui.viewport_status_edges": "{count} muchii", + "ui.viewport_status_from": "din {direction}", "ui.viewport_status_key": "Afișează legenda pentru {name}", "ui.viewport_status_minimum_radius": "Rază minimă", "ui.viewport_status_pairs": "{count} perechi", + "ui.viewport_status_section_hatch": "{setting} · hașură", + "ui.viewport_status_section_plane": "Planul curent", + "ui.viewport_status_section_tilted": "înclinat · {offset}", "ui.viewport_status_stripes": "{count} dungi", + "ui.viewport_status_summary_clear": "Dezactivează tot", + "ui.viewport_status_summary_heading": "În această vizualizare", + "ui.viewport_status_summary_label": "{name} și încă {count} elemente", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Urmează tema", "ui.visual_shaded_hidden_edges": "Umbrit cu muchii ascunse", "ui.visual_shaded_with_edges": "Umbrit cu muchii", @@ -4634,10 +5231,12 @@ "update.button": "Actualizează", "update.button_version": "Actualizează la {version}", "update.check_automatically": "Verifică automat actualizările", + "update.check_for_updates": "Caută actualizări", "update.check_now": "Verifică acum", + "update.check_unavailable": "Căutarea actualizărilor nu este disponibilă pentru această instalare.", "update.checking": "Se verifică…", "update.copy": "Copiază", - "update.dmg_opened": "Imaginea de disc este deschisă și verificată: trageți SolidCraft în Applications, înlocuind copia veche, apoi reporniți SolidCraft.", + "update.dmg_opened": "Imaginea de disc este deschisă și verificată: ieșiți din SolidCraft, trageți noul SolidCraft în Applications, înlocuind copia veche, apoi deschideți din nou SolidCraft.", "update.download": "Descarcă", "update.download_open": "Descarcă și deschide", "update.downloading": "Se descarcă și se verifică… {done} din {total} MB", @@ -4648,11 +5247,13 @@ "update.installed": "SolidCraft {version} este instalat. Reporniți pentru a-l folosi.", "update.installer_started": "Programul de instalare pornește când SolidCraft se închide.", "update.later": "Amintește-mi mai târziu", + "update.managed": "Actualizare disponibilă: actualizați SolidCraft în {manager}", "update.no_notes": "Această versiune nu are note.", "update.package_hint": "Această copie provine dintr-un {kind}. Descărcați noul pachet, apoi instalați-l cu:", "update.prefs_dev": "Aceasta este o versiune de dezvoltare ({version}): nu verifică actualizările.", "update.prefs_flatpak": "Flatpak actualizează această copie ({version}): rulați {command} sau folosiți centrul de software. SolidCraft nu verifică.", "update.prefs_label": "Actualizări", + "update.prefs_managed": "Aceasta este SolidCraft {version}, gestionat de {manager}. O verificare cere GitHub ultima versiune și nu trimite nimic altceva; actualizați SolidCraft în {manager}.", "update.prefs_note": "Aceasta este SolidCraft {version} ({kind}). O verificare cere GitHub ultima versiune și nu trimite nimic altceva.", "update.prefs_web": "Reîncărcați pagina pentru a obține cea mai recentă aplicație web. Dacă rețeaua nu este disponibilă sau actualizarea nu poate termina descărcarea la timp, se deschide versiunea salvată; o descărcare în curs continuă pentru următoarea reîncărcare.", "update.refresh_checking": "Se caută cea mai nouă versiune…", @@ -4679,6 +5280,7 @@ "web.open_link": "Deschideți proiectul legat?", "web.open_link_confirm": "Există modificări nesalvate. Deschideți proiectul legat într-o filă nouă?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ alege · Enter / Tab completează · Esc închide", + "↑ ↓ choose · Enter applies this value": "↑ ↓ alegeți · Enter aplică această valoare", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ alegeți · Enter aplică ce ați tastat · Esc închide", "⌘Enter continues on GitHub.": "⌘Enter continuă pe GitHub." } diff --git a/assets/locales/ru.json b/assets/locales/ru.json index e0f913fc7..20485b0c4 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "СОПРЯГАЮЩАЯ ПОВЕРХНОСТЬ", "BOUNDARY SURFACE": "ГРАНИЧНАЯ ПОВЕРХНОСТЬ", "BROWSER": "БРАУЗЕР", + "Back to the original order": "Вернуть исходный порядок", "Ball": "Шаровое", "Bar": "Полоса", "Base Center": "Центр основания", @@ -114,7 +115,7 @@ "Circular": "Круговой", "Circumference": "Окружность", "Clockwise": "По часовой стрелке", - "Close draft": "Закрыть анализ уклонов", + "Close draft": "Закрыть черновик", "Collapse": "Свернуть", "Collisions": "Столкновения", "Colour": "Цвет", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Здесь появляются открытые и сохранённые дизайны.", "Determined by To Object. Choose Angle to edit the angular extent.": "Определяется параметром «До объекта». Выберите «Угол», чтобы задать угловой предел.", "Diameter": "Диаметр", + "Did this assembly open the wrong way up?": "Эта сборка открылась не той стороной вверх?", + "Did this part open the wrong way up?": "Эта деталь открылась не той стороной вверх?", "Dimension new shapes": "Проставлять размеры новых фигур", "Direction": "Направление", "Discard": "Отменить", @@ -474,6 +477,7 @@ "Rectangular": "Прямоугольная", "Rectangular Tube": "Прямоугольная труба", "Reference face": "Базовая грань", + "Reference plane": "Базовая плоскость", "Relief Depth": "Глубина разгрузки", "Relief Width": "Ширина разгрузки", "Remove Tools": "Убрать инструменты", @@ -553,6 +557,7 @@ "Section": "Сечение", "Section (optional)": "Сечение (необязательно)", "Section position": "Положение сечения", + "Sections": "Сечения", "Sections (one sketch each)": "Сечения (по одному эскизу)", "Select Other": "Выбрать другое", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Выбрать другое: удерживайте левую кнопку на модели (или правый щелчок › Выбрать другое…), чтобы увидеть всё под курсором; повторный щелчок в том же месте выбирает следующий объект. Двойной щелчок средней кнопкой — «Главная» (Настройки › Навигация).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Привязка к центрам граней и рёбер", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft не может отправлять отчёты напрямую. Отправьте отчёт на GitHub; токен в приложении не нужен.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft закрылся до сохранения этих дизайнов. Можно открыть последнюю автосохранённую версию.", + "Sort A to Z": "Сортировать от А до Я", + "Sort Z to A": "Сортировать от Я до А", "Spacing 2 must be a non-zero number": "Интервал 2 должен быть ненулевым числом", "Spacing must be a non-zero number": "Интервал должен быть ненулевым числом", "Specialise": "Специализировать", @@ -601,6 +608,7 @@ "Square": "Квадрат", "Stand it up": "Поставить вертикально", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Поставить вертикально: четверть оборота вокруг X одной операцией «Переместить», которую можно отменить.", + "Stand this assembly up?": "Поставить эту сборку вертикально?", "Stand this part up?": "Поставить эту деталь вертикально?", "Start angle": "Начальный угол", "Start bulge": "Выпуклость в начале", @@ -772,6 +780,8 @@ "at the face": "у грани", "bom.group_children": "Вложенные детали в строке своей детали", "browser.body_name": "Тело{number}", + "browser.calibrate_click_a": "Щёлкните по изображению, чтобы задать точку A, или введите её координаты.", + "browser.calibrate_click_b": "Щёлкните по изображению, чтобы задать точку B, или введите её координаты.", "browser.calibrate_title": "Калибровка: {name}", "browser.capture_many": "Компоненты ({count}) перемещены, но их положения не зафиксированы.", "browser.capture_note": "«Зафиксировать положение» сохраняет новое положение; «Вернуть положение» восстанавливает прежнее.", @@ -784,6 +794,13 @@ "browser.sketch_attachment_lost": "{name} (привязка потеряна)", "browser.sketch_editing": "{name} (редактируется)", "browser.sketch_name": "Эскиз{number}", + "browser.sketches_to_parts_already_in_part": "уже в своей детали", + "browser.sketches_to_parts_design_body": "на теле самого дизайна", + "browser.sketches_to_parts_moved": "Перемещено эскизов в деталь, на которой они лежат: {moved}", + "browser.sketches_to_parts_no_exact_attachment": "на грани без точной привязки", + "browser.sketches_to_parts_not_on_face": "не на грани детали", + "browser.sketches_to_parts_part_missing": "их детали больше нет", + "browser.sketches_to_parts_result": "Перемещено эскизов в деталь, на которой они лежат: {moved}; остались на месте: {stayed} — {why}", "browser.units": "Единицы: {units}", "cam.flat": "Плоский", "cam.follower": "Толкатель", @@ -813,6 +830,8 @@ "cmd.appearance_pick_up": "Взять внешний вид", "cmd.appearance_replace": "Заменить внешний вид", "cmd.assembly_bom": "Спецификация", + "cmd.assembly_mass_properties": "Массовые характеристики", + "cmd.body.print_face": "Грань печати", "cmd.body_rename": "Переименовать тело", "cmd.browser_collapse_all": "Свернуть всё", "cmd.browser_expand_all": "Развернуть всё", @@ -841,6 +860,7 @@ "cmd.component_extract": "Извлечь в файл", "cmd.component_finish_edit": "Завершить изменение", "cmd.component_from_bodies": "Создать компоненты из тел", + "cmd.component_hide_history": "Скрыть историю компонента", "cmd.component_insert_design": "Вставить дизайн", "cmd.component_links": "Список связей", "cmd.component_list": "Список компонентов", @@ -849,6 +869,7 @@ "cmd.component_move_bodies": "Переместить тела в компонент", "cmd.component_move_features": "Переместить операции в компонент", "cmd.component_move_sketches": "Переместить эскизы в компонент", + "cmd.component_move_sketches_to_parts": "Переместить эскизы в их детали", "cmd.component_paste_from_design": "Вставить из другого дизайна", "cmd.component_paste_new": "Вставить как новый", "cmd.component_properties": "Физические свойства компонента", @@ -856,6 +877,7 @@ "cmd.component_rename": "Переименовать компонент", "cmd.component_replace_with_link": "Заменить ссылкой", "cmd.component_revert_position": "Вернуть положение", + "cmd.component_show_history": "Показать историю компонента", "cmd.component_unlock": "Разблокировать содержимое", "cmd.component_update_links": "Обновить связи", "cmd.config_activate": "Активировать конфигурацию", @@ -866,6 +888,7 @@ "cmd.config_rule": "Правило конфигурации", "cmd.config_rules": "Правила конфигурации", "cmd.config_table": "Показать таблицу конфигурации", + "cmd.construct.plane.axis_point": "Плоскость через ось и точку", "cmd.construct_axis_edge": "Ось через ребро", "cmd.construct_axis_normal_to_face": "Ось перпендикулярно грани", "cmd.construct_axis_through_cylinder": "Ось через цилиндр/конус/тор", @@ -914,6 +937,11 @@ "cmd.explode_show": "Показать разобранный вид", "cmd.expr_evaluate": "Вычислить выражение", "cmd.face_delete": "Удалить грань", + "cmd.file.export_3mf": "Экспортировать 3MF", + "cmd.file.export_obj": "Экспортировать OBJ", + "cmd.file.export_step": "Экспортировать STEP", + "cmd.file.export_stl": "Экспортировать STL", + "cmd.file.export_urdf": "Экспортировать URDF", "cmd.file_export": "Экспорт", "cmd.file_insert_mesh": "Вставить меш", "cmd.file_insert_step": "Вставить STEP", @@ -931,6 +959,7 @@ "cmd.inspect_colored_components": "Включить цвета компонентов", "cmd.inspect_colored_components_disable": "Отключить цвета компонентов", "cmd.inspect_compare": "Сравнить тела", + "cmd.inspect_compare_picture": "Сравнить с изображением", "cmd.inspect_continuity": "Анализ непрерывности", "cmd.inspect_curvature_comb": "Анализ кривизны (гребёнка)", "cmd.inspect_curvature_map": "Карта кривизны", @@ -1017,6 +1046,9 @@ "cmd.plastic_rest": "Опора", "cmd.plastic_rules": "Список правил пластика", "cmd.plastic_snap_fit": "Защёлка", + "cmd.render.compare.divider": "Переместить разделитель сравнения рендеров", + "cmd.render.result.discard": "Отбросить результат рендера", + "cmd.render.result.select": "Выбрать результат рендера", "cmd.render_aging_describe": "Многослойное старение поверхности", "cmd.render_backends": "Рендер-бэкенды", "cmd.render_batch": "Рендер всех кадров", @@ -1175,6 +1207,7 @@ "cmd.sketch_spline_control_point_5": "Сплайн по контрольным точкам (степень 5)", "cmd.sketch_spline_fit_point": "Сплайн по точкам сглаживания", "cmd.sketch_spline_insert_point": "Добавить точку сплайна", + "cmd.sketch_spline_remove_point": "Удалить точку сплайна", "cmd.sketch_spline_reverse": "Обратить направление сплайна", "cmd.sketch_spun_profile": "Профиль вращения", "cmd.sketch_toggle_diameter": "Переключить радиус / диаметр", @@ -1225,9 +1258,11 @@ "cmd.timeline_rollback": "Сдвинуть маркер шкалы", "cmd.timeline_stop": "Остановить воспроизведение истории", "cmd.timeline_suppress": "Подавить операцию", + "cmd.ui.assistant": "Показать/скрыть ассистента", "cmd.view.render_browser": "Браузер рендера", "cmd.view.render_dock": "Переместить панель рендера", "cmd.view.render_focus": "Режим фокуса рендера", + "cmd.view.status_details": "Подробности состояния видового экрана", "cmd.view.status_items": "Элементы состояния видового экрана", "cmd.view_ambient_occlusion": "Окружающее затенение", "cmd.view_angle_readout": "Углы вида", @@ -1258,17 +1293,28 @@ "cmd.view_tool": "Инструмент навигации", "cmd.view_top": "Вид сверху", "cmd.view_visual_style": "Визуальный стиль", + "color.blue": "Синий", "color.copy": "Щёлкните, чтобы скопировать значения цвета", "color.edit": "Щёлкните, чтобы изменить цвет", "color.gamma": "Значения цвета показаны в гамма-пространстве 0–255", + "color.green": "Зелёный", "color.hex": "Hex", "color.hex_help": "Введите #rrggbb или #rrggbbaa; при вводе шести цифр непрозрачность сохраняется", "color.hex_hint": "#rrggbb", "color.hue": "Оттенок", "color.linear": "Значения цвета показаны в линейном пространстве 0–1", + "color.recent": "Недавние цвета", + "color.recent_help": "Цвета, выбранные в любом поле цвета, появляются здесь", + "color.red": "Красный", + "color.saturation": "Насыщенность (в процентах)", "color.saturation_value": "Насыщенность и яркость", "color.selected": "Выбранный цвет", + "color.step_down": "Уменьшить на шаг", + "color.step_up": "Увеличить на шаг", + "color.value": "Значение, то есть яркость (в процентах)", "config.column_filter_empty": "Нет подходящих столбцов", + "config.rule_parameter_columns": "Показаны только параметры, у которых есть столбец в таблице. Добавьте столбец кнопкой «Добавить столбец» (+), чтобы использовать параметр здесь.", + "config.rule_suppression_columns": "Показаны только операции, у которых в таблице есть столбец «Подавить». Добавьте столбец кнопкой «Добавить столбец» (+), чтобы управлять операцией здесь.", "contact.components_count": "Компонентов: {count}", "contact.enabled_label": "включено", "coupling.gear_1": "Шестерня 1", @@ -1313,9 +1359,15 @@ "dialog.dimension_insert_hint": "Дважды щёлкните другой управляющий размер, чтобы вставить его имя", "dialog.dimension_name": "Размер: {name}", "dialog.edit_title": "ИЗМЕНИТЬ: {title}", + "dialog.no_shown_body": "Нет отображаемого тела для изменения: покажите тело или выберите «Новое тело»", + "dialog.pattern_sketch_not_object": "Выберите тела или операции: эскиз — ни то, ни другое. Повторите его кривые собственным инструментом «Массив» или «Зеркало» в эскизе либо сначала выдавите его.", "dialog.select": "↖ Выбрать", "dialog.selected_count": "↖ Выбрано: {count}", + "dialog.selection_constraint": "Ограничение {id}", + "dialog.selection_external_curve": "{sketch} · кривая {id}", "dialog.selection_guidance": "Щёлкните поле ввода, чтобы изменить его. Щелчок по выделенному объекту убирает его; Ctrl/Cmd+щелчок тоже переключает. Проверьте предпросмотр и нажмите OK.", + "dialog.selection_midpoint": "Середина · {id}", + "dialog.selection_profile": "{sketch} · профиль {number}", "dialog.selection_step": "{step} из {total}: Выберите {input}", "dialog.step": "Шаг", "document.changed_on_disk": "Файл {name} изменён на диске", @@ -1370,25 +1422,243 @@ "from the rule": "из правила", "help.apache": "Лицензия Apache 2.0", "help.appearance.assign": "Задаёт выбранным телам, граням или компонентам цвет или вид материала, не меняя их вес. Используйте, чтобы различать детали или заранее увидеть отделку.", + "help.assembly.bom": "Перечисляет детали дизайна или компонента с их количеством по номерам деталей и может сохранить список в CSV или JSON. Используйте как список деталей для заказа и сборки.", "help.attributions": "Сведения об авторстве (ATTRIBUTION.md)", "help.build": "Версия {version} · коммит {commit} · сборка от {date}", + "help.canvas.decal": "Помещает изображение на плоскую грань модели, как наклейку. Используйте, чтобы показать на детали надпись, логотип или печатный рисунок.", + "help.canvas.edit": "Меняет подложку: её положение, размер, угол, непрозрачность, отражение, видимость или имя. Используйте, чтобы совместить образец с эскизом, который вы по нему обводите.", + "help.canvas.insert": "Помещает изображение PNG или JPEG на плоскость или грань как полупрозрачный образец. Используйте, чтобы обвести в эскизе фотографию или чертёж, масштабировав изображение до известного размера.", + "help.component.break_link": "Отсоединяет связанный компонент от файла дизайна, оставляя его тела как есть. Используйте, когда деталь больше не должна следовать изменениям исходного файла.", + "help.component.capture_position": "Сохраняет положения деталей, которые вы передвинули вручную, как их новые места. Используйте после перетаскивания деталей на место, если их не удерживает ни одно сопряжение.", + "help.component.create": "Добавляет в дизайн новый пустой компонент: внутрь активного, если вы не выберете другого родителя. Используйте, чтобы дать новой детали сборки собственное место для тел и эскизов.", "help.component.finish_edit": "Сохраняет деталь, которую вы изменяете на месте, возвращается в её сборку и обновляет сборку по ней. Используйте, когда изменения связанной детали готовы.", + "help.component.from_bodies": "Превращает каждое выбранное тело в отдельный компонент с именем этого тела. Используйте, когда дизайн из разрозненных тел должен стать сборкой, детали которой можно соединять и перемещать.", + "help.component.insert_design": "Вставляет другой сохранённый дизайн как компонент, связанный со своим файлом; его твёрдые тела размещаются так же, как в оригинале. Используйте, чтобы повторно применить деталь в сборке и подхватывать последующие изменения командой «Обновить связи».", + "help.component.properties": "Показывает объём, массу, центр масс и моменты инерции компонента по материалам его тел. Используйте, чтобы проверить вес и баланс сборки.", + "help.component.revert_position": "Возвращает вручную перемещённые детали на прежние места, отбрасывая незафиксированные перемещения. Используйте, чтобы отменить пробные перемещения в сборке.", + "help.component.update_links": "Заново читает связанные файлы дизайнов и заменяет изменившиеся тела. Используйте после правки детали, которую применяет эта сборка.", + "help.config.configure": "Добавляет параметры, операции, материалы или внешние виды как столбцы таблицы конфигурации. Используйте, чтобы создавать варианты одного дизайна, например размеры детали.", + "help.config.preview": "Проверяет, что строка таблицы конфигурации пересобирается, не меняя дизайн и его историю. Используйте перед переключением на вариант, в котором вы не уверены.", + "help.config.rules": "Показывает правила таблицы конфигурации, её строки и активную строку. Используйте, чтобы увидеть, как настроены варианты дизайна.", + "help.config.table": "Показывает таблицу конфигурации: строка на вариант, столбец на параметр или операцию, и совпадает ли дизайн с активной строкой. Используйте, чтобы просмотреть варианты дизайна.", "help.connect_note": "Перезапустите каждого ассистента, чтобы загрузить сервер SolidCraft. Перед изменением каждого файла создана резервная копия с расширением .bak.", "help.connect_title": "Подключение ИИ-ассистентов", + "help.construct.axis.edge": "Создаёт вспомогательную ось вдоль прямого ребра или линии эскиза. Используйте как ось для вращения, кругового массива или сопряжения.", + "help.construct.axis.normal_to_face": "Создаёт вспомогательную ось через точку перпендикулярно грани. Используйте как ось, прямо выходящую из поверхности.", + "help.construct.axis.through_cylinder": "Создаёт вспомогательную ось через центр цилиндрической, конической или тороидальной грани либо круглого ребра. Используйте, чтобы вращать элементы или делать массив вокруг круглой детали.", + "help.construct.axis.two_planes": "Создаёт вспомогательную ось в месте пересечения двух плоскостей или плоских граней. Используйте, когда нужная ось — линия между двумя гранями.", + "help.construct.axis.two_points": "Создаёт вспомогательную ось через две точки, вершины или точки эскиза. Используйте для оси, идущей между двумя известными положениями.", + "help.construct.plane.along_path": "Создаёт вспомогательную плоскость, перпендикулярную ребру или кривой, в выбранном месте вдоль неё. Используйте, чтобы нарисовать профиль для операции «Сдвиг» или сечение траектории.", + "help.construct.plane.at_angle": "Создаёт вспомогательную плоскость, повёрнутую на угол от плоскости или грани вокруг оси или ребра. Используйте для наклонных эскизов, например для кронштейна под углом.", + "help.construct.plane.axis_point": "Создаёт вспомогательную плоскость, содержащую ось и точку вне этой оси. Выберите ось начала координат или вспомогательную ось, прямое ребро или линию эскиза, затем вершину, точку эскиза или вспомогательную точку. Точка на оси не задаёт единственную плоскость.", + "help.construct.plane.midplane": "Создаёт вспомогательную плоскость посередине между двумя плоскостями или плоскими гранями либо делящую пополам угол между ними. Используйте как плоскость симметрии для зеркального отражения.", + "help.construct.plane.offset": "Создаёт вспомогательную плоскость, параллельную плоскости или плоской грани, на заданном расстоянии или через точку. Используйте, чтобы рисовать на заданной высоте над гранью.", + "help.construct.plane.perpendicular": "Создаёт вспомогательную плоскость, содержащую линию или ребро и перпендикулярную плоскости или грани. Используйте, чтобы рисовать на модели вертикально вдоль ребра.", + "help.construct.plane.tangent": "Создаёт вспомогательную плоскость, касающуюся цилиндра, конуса, сферы или тора в точке. Используйте, чтобы рисовать на боковой стороне круглой детали.", + "help.construct.plane.three_points": "Создаёт вспомогательную плоскость через три точки. Используйте для плоскости, заданной положениями на модели, например тремя углами.", + "help.construct.plane.two_edges": "Создаёт вспомогательную плоскость через два прямых ребра или линии, лежащие в одной плоскости. Используйте для плоскости сквозь деталь, например через два противоположных ребра.", + "help.construct.point.along_path": "Создаёт вспомогательную точку в выбранном месте вдоль ребра или кривой. Используйте как ориентир на полпути вдоль траектории.", + "help.construct.point.center": "Создаёт вспомогательную точку в центре круглого ребра, окружности или дуги эскиза, сферы или тора. Используйте как ориентир для отверстий, осей и сопряжений.", + "help.construct.point.edge_plane": "Создаёт вспомогательную точку там, где ребро или линия пересекает плоскость или плоскую грань. Используйте, чтобы отметить, где траектория пересекает плоскость.", + "help.construct.point.three_planes": "Создаёт вспомогательную точку там, где сходятся три плоскости или плоские грани. Используйте как угловой ориентир, даже если у модели нет вершины.", + "help.construct.point.two_edges": "Создаёт вспомогательную точку там, где два ребра или линии пересекаются или подходят ближе всего друг к другу. Используйте как ориентир в воображаемом углу.", + "help.construct.point.vertex": "Создаёт вспомогательную точку в вершине или точке эскиза. Используйте как ориентир, который остаётся, когда окружающий эскиз или тело скрыты.", + "help.contact.check": "Перечисляет пары деталей в наборах контактов, которые в текущем положении проходят друг сквозь друга. Используйте, чтобы найти столкновения до привода сопряжений или исследования движения.", + "help.contact.create": "Объединяет две или более детали в набор контактов: их тела не проходят друг сквозь друга, пока двигаются сопряжения. Используйте для деталей, которые должны останавливаться при касании, например рычага у упора.", + "help.contact.disable_all": "Отключает контакт, так что приводимые сопряжения и исследования движения больше не останавливаются там, где детали соприкасаются. Используйте, чтобы снова свободно двигать детали или чтобы большая сборка отзывалась быстрее.", + "help.contact.edit": "Меняет набор контактов: входящие в него детали, имя или подавление; набор можно и удалить. Используйте, чтобы изменить, какие детали не должны проходить друг сквозь друга.", + "help.contact.enable_all": "Помещает все детали сборки в один набор контактов, так что никакие две детали не проходят друг сквозь друга, пока двигаются сопряжения. Используйте для быстрой проверки всего механизма.", + "help.contact.enable_sets": "Включает контакт для заданных вами наборов контактов, так что приводимые сопряжения и исследования движения останавливаются там, где их детали прошли бы друг сквозь друга. Используйте, чтобы вернуть свои наборы после отключения контакта.", + "help.contact.list": "Перечисляет наборы контактов дизайна, детали в каждом из них и включён ли контакт. Используйте, чтобы проверить настройку контактов перед приводом сборки.", + "help.document.inspect": "Показывает обзор дизайна: его компоненты, тела, эскизы, операции и параметры. Используйте, чтобы сориентироваться в дизайне, который вы создавали не сами.", + "help.document.units": "Меняет единицы, в которых дизайн показывает длины, например мм или дюймы. Размер геометрии не меняется; подстраиваются только отображение и числа без единиц.", + "help.edit.checkpoint": "Запоминает дизайн, активный эскиз и историю отмен в их текущем состоянии. Используйте перед рискованной попыткой, от которой, возможно, захочется вернуться.", + "help.edit.restore_checkpoint": "Возвращается к контрольной точке вместе с историей отмен. Используйте, чтобы одним шагом отбросить всё сделанное после контрольной точки.", + "help.explode.create": "Создаёт разобранный вид: детали отодвигаются от центра сборки или на заданные вами смещения. Используйте, чтобы показать, как собирается сборка, для инструкций или презентаций.", "help.face.delete": "Удаляет выбранные грани, и соседние грани закрывают промежуток, либо промежуток остаётся открытым как поверхность. Используйте, чтобы убрать скруглённое ребро, отверстие или выступ, которые мешают.", + "help.file.insert_mesh": "Добавляет файл 3MF, STL, OBJ, PLY или glTF в дизайн как тела-меши в новом компоненте. Используйте, чтобы разместить рядом с дизайном скачанную или отсканированную модель как образец.", + "help.file.insert_step": "Добавляет файл STEP, IGES, FreeCAD или Rhino в дизайн как твёрдые тела в новом компоненте; детали сборки становятся вложенными компонентами. Используйте, чтобы подключать модели от поставщиков или из других CAD-программ.", + "help.file.save_mesh": "Сохраняет тела как меш STL, 3MF или OBJ с выбранной гладкостью криволинейных граней. Используйте для подготовки деталей к 3D-печати или для программ, читающих меши.", + "help.file.send_to_slicer": "Сохраняет выбранные тела как файл 3MF и открывает его в выбранном слайсере. Используйте, чтобы перейти от модели к печати одним шагом.", "help.font_details": "Интерфейс использует встроенные шрифты egui (Ubuntu Light и Hack под лицензиями Ubuntu Font Licence и MIT/Bitstream Vera; Noto Emoji и шрифт значков эмодзи под лицензиями OFL и MIT). Для текста эскизов используется Liberation Sans (SIL OFL 1.1). Необязательный пакет шрифтов The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), не входит в сборки SolidCraft.", "help.fonts": "Шрифты", + "help.frame.member": "Размещает профиль, например трубу или алюминиевый экструзионный профиль, вдоль линий эскиза рамы, по одному элементу на линию. Используйте для рам, стеллажей и сварных конструкций.", + "help.inspect.accessibility": "Раскрашивает грани, до которых инструмент может дотянуться с одного направления, и те, до которых не может. Используйте, чтобы проверить деталь на обработку или формование с этой стороны.", + "help.inspect.center_of_mass": "Показывает центр масс тел, каждого по отдельности и всех вместе, при равномерной плотности. Используйте, чтобы проверить баланс и понять, куда деталь опрокинется.", + "help.inspect.colored_components": "Задаёт каждому компоненту свой временный цвет, не меняя внешний вид. Используйте, чтобы с первого взгляда различать детали сборки.", + "help.inspect.compare": "Сравнивает два тела и показывает, где у одного есть материал, которого нет у другого, с объёмом и отклонением. Используйте, чтобы сверить изменённую или импортированную деталь с оригиналом.", + "help.inspect.continuity": "Проверяет, насколько плавно грани стыкуются по рёбрам (зазоры, изломы или скачки кривизны), и закрашивает швы. Используйте, чтобы найти места, где поверхности стыкуются неаккуратно.", + "help.inspect.curvature_comb": "Рисует гребёнки вдоль кривых, рёбер или граней: их зубья показывают, насколько сильно они изгибаются. Используйте, чтобы заметить плоские участки, изломы и неравномерную кривизну.", + "help.inspect.curvature_map": "Раскрашивает грани по силе кривизны, красным там, где радиус мал. Используйте, чтобы находить тесные места и оценивать гладкость поверхности.", + "help.inspect.draft": "Раскрашивает грани по углу уклона относительно направления вытягивания и отмечает те, где он слишком мал. Используйте, чтобы проверить деталь перед формованием или литьём.", + "help.inspect.environment_map": "Показывает модель с отражающей, зеркальной отделкой. Используйте, чтобы оценить плавность поверхностей по тому, как по ним бегут отражения.", + "help.inspect.interference": "Находит перекрывающиеся тела и показывает каждое перекрытие с его объёмом. Используйте, чтобы проверить сборку на сталкивающиеся детали.", + "help.inspect.isocurve": "Рисует изопараметрические кривые граней: сетку, на которой построена поверхность. Используйте, чтобы увидеть, как течёт поверхность и где она сгущается.", + "help.inspect.measure": "Измеряет длины, расстояния, углы, площади и радиусы между выбранными элементами либо объём и массу тел. Используйте, чтобы проверить размеры и зазоры.", + "help.inspect.minimum_radius": "Находит наименьший радиус кривизны кривых, рёбер или граней и показывает, где он. Используйте, чтобы убедиться, что инструмент или сопло смогут пройти по форме.", + "help.inspect.section": "Разрезает вид по плоскости и штрихует срезанные грани, не меняя модель. Используйте, чтобы заглянуть внутрь деталей и сборок.", + "help.inspect.zebra": "Показывает чёрно-белые полосы, отражённые на гранях модели. Используйте для оценки гладкости: полосы, которые обрываются или ломаются на ребре, указывают на плохой переход.", + "help.joint.as_built": "Соединяет две детали там, где они уже стоят, не двигая ни одну, и задаёт, как они ещё могут двигаться. Используйте для деталей, которые вы уже поставили в окончательное положение.", + "help.joint.cam": "Связывает вращающийся кулачок с толкателем, так что толкатель скользит или качается, пока под ним проходит контур кулачка. Используйте для кулачков, эксцентриков и приводов клапанов.", + "help.joint.create": "Соединяет две детали в выбранных точках сопряжения и ставит вторую деталь на место; тип сопряжения задаёт, как они ещё могут двигаться. Используйте, чтобы собрать сборку, детали которой движутся как настоящий механизм.", + "help.joint.drive": "Задаёт угол или расстояние сопряжения и двигает вместе с ним детали в пределах ограничений; связанные сопряжения и замкнутые контуры следуют за ним. Используйте, чтобы проверить, что механизм движется как задумано.", + "help.joint.gear": "Связывает два вращающихся сопряжения передаточным отношением, так что поворот одного вращает другое. Используйте для цилиндрических и внутренних зубчатых колёс, задавая отношение по радиусам делительных окружностей или числам зубьев.", + "help.joint.limits": "Задаёт, насколько сопряжение может повернуться или сдвинуться, минимумом и максимумом, либо снимает эти пределы. Используйте, чтобы удерживать шарнир, ползун или рычаг в реальном диапазоне хода.", + "help.joint.motion_link": "Связывает два сопряжения отношением и смещением, так что приведение одного двигает другое. Используйте для фиксированной связи между сопряжениями, которую не охватывают «Зубчатая передача», «Реечная передача» и «Винт».", + "help.joint.origin": "Размещает именованную точку сопряжения на детали: в центре грани или круглого торца, в середине ребра, в углу или в точке. Используйте, чтобы подготовить места крепления сопряжений; точка, выбранная на грани, следует за ней при изменении размера детали.", + "help.joint.rack_pinion": "Связывает вращающуюся шестерню с движущейся рейкой, так что рейка смещается на длину делительной окружности, которую прокатывает шестерня. Используйте для реечных приводов, рулевых механизмов и линейных столов.", + "help.joint.reach": "Перемещает точку детали к цели, меняя сопряжения её цепи в пределах ограничений. Используйте, чтобы ставить механизм в позу по тому, где должен оказаться его конец, например кончик руки робота.", + "help.joint.rigid_group": "Жёстко скрепляет выбранные детали друг с другом как есть, так что они движутся как одно целое. Используйте для деталей, которые составляют единое целое и не должны двигаться друг относительно друга.", + "help.joint.screw": "Связывает вращение и скольжение шагом, так что каждый оборот смещает на это расстояние. Используйте для ходовых винтов, болтов и резьбовых шпинделей.", + "help.library.apply": "Применяет материал или внешний вид из файла локальной библиотеки к телам, граням или компонентам. Используйте, чтобы повторно применять материалы, сохранённые в другом дизайне.", + "help.library.export": "Сохраняет материалы и внешние виды дизайна в файл библиотеки. Используйте, чтобы поделиться ими или применять их в других дизайнах.", + "help.library.inspect": "Проверяет файл библиотеки и перечисляет её материалы и внешние виды, не меняя дизайн. Используйте, чтобы узнать, что содержит библиотека, перед применением.", "help.licences": "Лицензии", "help.material.assign": "Задаёт, из чего сделаны выбранные тела, например сталь, алюминий или ABS. Используйте, чтобы масса и вес соответствовали реальной детали.", + "help.material.properties.validate": "Проверяет карточку данных материала на согласованность чисел и пропущенные значения. Используйте перед тем, как полагаться на эти данные при расчёте массы или жёсткости.", + "help.mesh.convert": "Перестраивает тело-меш, например STL, в редактируемое твёрдое тело с плоскими и цилиндрическими гранями. Используйте, чтобы менять импортированные механические детали как смоделированное тело.", "help.mit": "Лицензия MIT", + "help.motion.study": "Задаёт значения сопряжений по шагам вдоль временной шкалы и воспроизводит их как анимацию. Используйте, чтобы наблюдать движение механизма по последовательности и проверять зазоры по ходу.", + "help.motion.trace": "Прослеживает путь точки детали во время воспроизведения исследования движения или привода сопряжения и после подтверждения сохраняет его как кривую 3D-эскиза. Используйте, чтобы увидеть, куда достаёт механизм, или строить по его траектории.", "help.notice": "NOTICE", + "help.occurrence.ground": "Закрепляет деталь на месте или снова освобождает её, так что сопряжения двигают остальные детали вокруг неё. Используйте для рамы или основания, на которых построена остальная сборка.", "help.occurrence.move": "Перемещает деталь сборки только по степеням свободы, разрешённым её сопряжениями. Выберите грань детали, затем перетащите доступную стрелку или дугу.", "help.parameters.change": "Открывает таблицу именованных значений и выражений, управляющих размерами дизайна. Используйте, чтобы изменить размер в одном месте, а все операции, которые его используют, обновились следом.", + "help.parameters.export": "Сохраняет параметры дизайна как CSV или JSON. Используйте, чтобы править их в электронной таблице или переносить в другой дизайн.", + "help.parameters.graph": "Показывает, какие параметры и операции используют какие другие, а также циклы и ошибки среди них. Используйте, чтобы увидеть, на что повлияет изменение параметра.", + "help.parameters.import": "Читает параметры из CSV или JSON в дизайн: все или ни одного. Используйте, чтобы подтянуть значения из электронной таблицы или другого дизайна.", + "help.parameters.move": "Перемещает пользовательский параметр в списке перед другим параметром или после него. Используйте, чтобы держать связанные параметры рядом.", + "help.parts.fastener": "Добавляет стандартный винт, болт, гайку, шайбу, штифт или подшипник выбранного размера. Поставленный на отверстие, он садится в него через сопряжение, так что крепёж не нужно моделировать самому.", + "help.parts.insert": "Вставляет стандартную деталь выбранного семейства, размера и длины. Поставленная на кромку или стенку отверстия, она садится на это отверстие через жёсткое сопряжение.", + "help.parts.library": "Открывает стандартные детали: винты, болты, гайки, шайбы, установочные винты, цилиндрические штифты и подшипники стандартных размеров. Используйте, чтобы добавить стандартную деталь, а не моделировать её самому.", + "help.parts.resize": "Меняет размер или длину вставленной стандартной детали и перестраивает её; сопряжения удерживают её на месте. Используйте, если винт оказался слишком длинным или отверстию нужен другой размер.", + "help.plastic.assign_rule": "Назначает правило пластика телам, так что их пластиковые операции берут из него уклон и зазор по умолчанию. Используйте, чтобы один раз настроить формованную деталь для всех её операций.", + "help.plastic.boss": "Добавляет бобышку под винт на грани: стойку с необязательным отверстием, уклоном, скруглением у основания и поддерживающими рёбрами жёсткости. Используйте для точек крепления винтов в формованных или печатных корпусах.", + "help.plastic.lip": "Добавляет выступ или ответный паз вдоль кромки тонкостенного тела. Используйте, чтобы две половины корпуса фиксировались друг на друге и плотно закрывались.", + "help.plastic.manage_rules": "Создаёт и изменяет правила пластика: материал, толщину стенки, радиусы, зазор и уклон. Используйте, чтобы операции формованной детали были согласованы.", + "help.plastic.rest": "Добавляет опору на грани: круглую или прямоугольную площадку, сплошную или полую, с уклоном. Используйте как опору или стойку в формованном корпусе.", + "help.plastic.snap_fit": "Добавляет защёлку-крючок на грани с заданными длиной, толщиной и зацепом. Используйте, чтобы скреплять детали без винтов.", + "help.sheet.convert": "Превращает пластину или оболочку одинаковой толщины в тело из листового металла с гибами на выбранных рёбрах. Используйте, чтобы сделать существующую деталь разворачиваемой.", + "help.sheet.export_bend_table": "Сохраняет таблицу гибов тела из листового металла как CSV или JSON: углы, радиусы и положения гибов на развёртке. Используйте для листогибочного пресса или мастерской.", + "help.sheet.export_dxf": "Сохраняет развёртку как DXF с контурами, линиями гибов и необязательными примечаниями о гибах. Используйте для лазерной, плазменной или гидроабразивной резки.", + "help.sheet.flange": "Добавляет фланец: пластину-основание из эскиза, стенку вдоль открытого контура эскиза или отогнутую стенку на рёбрах листа. Используйте для построения деталей из листового металла.", + "help.sheet.flat_pattern": "Создаёт развёртку тела из листового металла с её размером, вырезами и линиями гибов. Используйте, чтобы проверить заготовку перед резкой.", + "help.sheet.fold": "Сгибает лист вдоль линии эскиза на заданный угол с заданным радиусом. Используйте, чтобы согнуть плоский лист после того, как в нём вырезаны элементы.", + "help.sheet.hem": "Загибает кромку листа назад на себя. Используйте для безопасных жёстких кромок без острых заусенцев.", + "help.sheet.manage_rules": "Создаёт и изменяет правила листового металла: толщину, радиус гиба, коэффициент K, разгрузки и зазоры. Используйте, чтобы подогнать их под материал и инструменты вашей мастерской.", + "help.sheet.path_flange": "Добавляет цепочку фланцев вдоль кромки листа по открытой цепочке линий эскиза. Используйте для профилей вроде U- или Z-образного за один шаг.", + "help.sheet.perforate": "Добавляет поле отверстий по всему плоскому листу в шахматном или квадратном порядке. Используйте для вентиляционных отверстий, решёток и облегчённых панелей.", + "help.sheet.refold": "Снова сгибает разогнутое тело из листового металла. Используйте после добавления элементов на плоский лист.", + "help.sheet.unfold": "Разгибает все гибы тела из листового металла. Используйте, чтобы добавить отверстия или вырезы, которые должны пересекать гиб, а затем согните снова.", + "help.sketch.arc.center_point": "Рисует дугу окружности вокруг центральной точки от начальной точки до конечной. Используйте, когда центр дуги известен, например для радиуса вокруг отверстия или оси.", + "help.sketch.arc.tangent": "Рисует дугу, которая начинается в конце линии или дуги и продолжается по касательной к ней. Используйте, чтобы продолжить цепочку плавным изгибом вместо угла.", + "help.sketch.arc.three_point": "Рисует дугу от начальной точки до конечной через третью точку. Используйте, когда дуга должна проходить через заданные точки, а не вокруг известного центра.", + "help.sketch.arc3d": "Рисует точную дугу окружности в пространстве через три точки при включённом 3D-эскизе. Используйте для изгибов траекторий и направляющих, выходящих из плоскости эскиза.", + "help.sketch.auto_constrain": "Добавляет ограничения, которым эскиз уже почти соответствует (горизонтальность, параллельность, совпадение), а затем проставляет размеры, пока он не станет полностью определён. Используйте, чтобы зафиксировать грубо нарисованный эскиз за один шаг.", + "help.sketch.auto_constrain_from_datum": "Работает как «Автоограничения», но отсчитывает положения от выбранной базовой точки, а не от начала координат. Используйте, когда деталь размечена от одной опорной точки, например угла или отверстия.", + "help.sketch.blend_curve": "Соединяет концы двух кривых плавным сплайном, касательным к обеим, а при желании и с непрерывной кривизной. Используйте, чтобы перекрыть зазор между кривыми без излома.", + "help.sketch.break": "Разделяет кривую на части там, где её пересекают другие кривые, или в точках, которые вы на ней поставите. Используйте, когда часть кривой должна получить собственное ограничение или быть удалена отдельно.", + "help.sketch.cancel": "Выходит из эскиза и отбрасывает всё, что изменено с момента его создания или открытия для правки. Отмена последнего действия вернёт изменения.", + "help.sketch.centerline": "Переключает линии между обычными и осевыми: осями, которые профили не учитывают. Используйте осевую линию как ось для «Вращения», зеркала или ограничения симметрии.", + "help.sketch.chamfer.distance_angle": "Снимает фаску на углу между двумя линиями по расстоянию вдоль первой линии и углу. Используйте, когда на чертеже фаска задана длиной и углом, например 2 мм × 30°.", + "help.sketch.chamfer.equal_distance": "Снимает фаску на углу между двумя линиями на одинаковое расстояние по обеим. Используйте для обычной фаски 45° на контуре.", + "help.sketch.chamfer.two_distance": "Снимает фаску на углу между двумя линиями с отдельным расстоянием вдоль каждой линии. Используйте для фасок не под 45°, заданных двумя длинами.", + "help.sketch.circle.center": "Рисует окружность по центру и диаметру. Используйте для отверстий, бобышек и других круглых элементов с известным центром.", + "help.sketch.circle.three_point": "Рисует окружность через три точки. Используйте, когда окружность должна пройти через заданные точки, например существующей геометрии.", + "help.sketch.circle.three_tangent": "Рисует окружность, касающуюся трёх линий, окружностей или дуг. Используйте, чтобы вписать окружность в пространство между тремя кривыми, например вписанную окружность треугольника.", + "help.sketch.circle.two_point": "Рисует окружность по двум концам её диаметра. Используйте, когда известны точки на краю окружности, а не её центр.", + "help.sketch.circle.two_tangent": "Рисует окружность заданного размера, касающуюся двух линий, окружностей или дуг. Используйте для скругления фиксированного радиуса между двумя кривыми.", + "help.sketch.conic": "Рисует коническую кривую между двумя конечными точками; её форму задают вершина и значение rho. Используйте для плавных переходов, наполненность которых нужно подстроить: от плоской до почти острого угла.", + "help.sketch.constrainer": "Применяет ограничение, которому одна или две выбранные кривые уже почти соответствуют (горизонтальность, параллельность, касание или равенство). Используйте, чтобы привести в порядок нарисованный от руки эскиз по одному ограничению за раз.", + "help.sketch.constraint.coincident": "Помещает точку на другую точку, кривую или ось эскиза. Используйте, чтобы закрыть зазоры в профиле или поставить точку на линию.", + "help.sketch.constraint.collinear": "Располагает две линии на одной прямой. Используйте, чтобы выровнять прерванные рёбра, например обе стороны выемки.", + "help.sketch.constraint.concentric": "Задаёт двум окружностям или дугам общий центр. Используйте для колец, цековок и валов с уступами.", + "help.sketch.constraint.curvature": "Заставляет две кривые, встречающиеся в конечной точке, продолжаться с одинаковой кривизной (G2). Используйте там, где касательного стыка недостаточно для плавности, например на видимых поверхностях.", + "help.sketch.constraint.equal": "Делает линии одинаковой длины, а окружности и дуги — одинакового радиуса. Используйте, чтобы один размер управлял несколькими одинаковыми элементами.", + "help.sketch.constraint.fix": "Фиксирует точки или кривые на месте или снова освобождает их. Используйте для геометрии, которая не должна двигаться при перетаскивании или решении эскиза.", + "help.sketch.constraint.horizontal_vertical": "Делает линию, или линию между двумя точками, горизонтальной или вертикальной, в зависимости от того, что ближе. Используйте, чтобы выровнять контур по осям эскиза.", + "help.sketch.constraint.midpoint": "Ставит точку на середину линии или совмещает середины двух линий. Используйте, чтобы центрировать геометрию на ребре.", + "help.sketch.constraint.parallel": "Делает две линии параллельными. Используйте для сторон, которые должны оставаться параллельными при изменении других размеров.", + "help.sketch.constraint.perpendicular": "Делает так, чтобы две линии встречались под прямым углом. Используйте для прямых углов между линиями, не лежащими на осях эскиза.", + "help.sketch.constraint.polygon": "Превращает замкнутую цепочку линий в правильный многоугольник: равные стороны, все углы на одной окружности. Используйте, чтобы сделать нарисованный от руки многоугольник правильным и сохранить это.", + "help.sketch.constraint.symmetry": "Делает две точки или кривые зеркальными друг для друга относительно линии или центральной точки. Используйте, чтобы профиль оставался симметричным при изменении одной стороны.", + "help.sketch.constraint.tangent": "Заставляет две кривые касаться, например линию и дугу. Используйте для плавных стыков без излома.", + "help.sketch.construction": "Переключает кривые между обычной и вспомогательной геометрией, которую профили не учитывают. Используйте вспомогательные кривые как помощники для разметки, ориентиры и размеры.", + "help.sketch.construction_line": "Создайте бесконечную вспомогательную прямую через две точки. С её помощью можно разметить эскиз, не разделяя профили.", + "help.sketch.construction_line.angle": "Создайте бесконечную вспомогательную прямую под углом к оси X эскиза. Укажите точку и введите угол либо задайте направление.", + "help.sketch.construction_line.bisector": "Выберите две пересекающиеся прямые эскиза, затем одну из двух биссектрис. Результат изменяется вместе с исходными прямыми.", + "help.sketch.construction_line.horizontal": "Создайте бесконечную горизонтальную вспомогательную прямую через точку. Её горизонтальное ограничение сохраняется при последующих изменениях.", + "help.sketch.construction_line.parallel": "Выберите прямую эскиза, затем разместите параллельную бесконечную вспомогательную прямую. Щелчок правой кнопкой — выбрать другую исходную прямую.", + "help.sketch.construction_line.perpendicular": "Выберите прямую эскиза, затем разместите перпендикулярную бесконечную вспомогательную прямую. Щелчок правой кнопкой — выбрать другую исходную прямую.", + "help.sketch.construction_line.tangent_at": "Создайте касательную в точке окружности или дуги окружности либо в конечной точке открытого сплайна или коники. Выберите кривую, затем точку касания.", + "help.sketch.construction_line.tangent_external": "Выберите окружность или дугу, затем внешнюю точку и решение для касательной. В предпросмотре показаны только точки касания на нарисованной дуге.", + "help.sketch.construction_line.tangent_two": "Выберите две окружности или дуги, затем в предпросмотре выберите общую касательную. Точки касания должны лежать на нарисованных кривых.", + "help.sketch.construction_line.vertical": "Создайте бесконечную вертикальную вспомогательную прямую через точку. Её вертикальное ограничение сохраняется при последующих изменениях.", + "help.sketch.copy": "Копирует выбранные кривые и точки эскиза вместе с ограничениями и размерами между ними. Вставьте их в этот эскиз или в другой.", + "help.sketch.create": "Начинает новый 2D-эскиз на плоскости или плоской грани модели. Каждое «Выдавливание», «Вращение» и «Сдвиг» начинается с эскиза.", + "help.sketch.cut": "Копирует выбранную геометрию эскиза и удаляет её из эскиза одним шагом отмены. Вставьте её в другое место этого эскиза или в другой эскиз.", + "help.sketch.dimension": "Добавляет управляющий размер: длину, расстояние, угол, радиус или диаметр, в зависимости от выбранного. Введите значение или имя параметра, и эскиз последует за ним.", + "help.sketch.edit": "Открывает существующий эскиз для правки. Операции, построенные на нём, обновятся, когда вы завершите эскиз.", + "help.sketch.ellipse": "Рисует эллипс по центру, концу большой оси и точке на малой стороне. Используйте для овальных проёмов, кулачков и других вытянутых круглых форм.", "help.sketch.equation_curve": "Рисует кривую по формулам: x(t) и y(t) либо y = f(x) на заданном интервале. В формулах можно использовать параметры, и кривая следует за ними. Используйте для синусоиды, спирали или эвольвенты зуба шестерни.", + "help.sketch.extend": "Удлиняет линию или дугу до ближайшей кривой на её пути либо наращивает две кривые, пока они не встретятся. Используйте, чтобы закрыть зазоры в профиле после обрезки или правки.", + "help.sketch.fillet": "Скругляет угол, где встречаются две линии или дуги, дугой заданного радиуса. Несколько углов, скруглённых вместе, получают один радиус.", + "help.sketch.finish": "Выходит из эскиза и возвращается к модели. Его замкнутые профили становятся готовы для «Выдавливания», «Вращения» и других операций.", + "help.sketch.finish_auto_constrain": "Запускает «Автоограничения» для эскиза, затем завершает его. Используйте, чтобы выйти из эскиза полностью определённым за один шаг.", + "help.sketch.fit_curves_to_section": "Разрезает меш или твёрдое тело плоскостью эскиза и подбирает линии и дуги по сечению. Используйте, чтобы воссоздать отсканированную или импортированную деталь как редактируемый эскиз.", + "help.sketch.include_3d": "Переносит рёбра модели, вершины и кривые других эскизов в этот эскиз как связанные ссылки, проецируя на его плоскость те, что лежат вне её. Используйте, чтобы строить по геометрии, не лежащей в плоскости эскиза.", + "help.sketch.infinite": "Переключает линии между обычными и бесконечными вспомогательными, идущими через весь вид. Используйте их как ориентиры разметки, которые никогда не оказываются слишком короткими.", + "help.sketch.insert_dxf": "Читает кривые чертежа DXF в эскиз, масштабируя, поворачивая и размещая их так, как вы зададите. Используйте, чтобы строить по 2D-чертежу из другой программы, например по контуру для лазерной резки.", + "help.sketch.insert_svg": "Читает контуры рисунка SVG в эскиз, масштабируя, поворачивая и размещая их так, как вы зададите. Используйте, чтобы превратить логотип или векторный контур в кривые, которые можно выдавить.", + "help.sketch.inspect": "Открывает отчёт об открытом эскизе: сколько осталось степеней свободы и определён ли он полностью. Используйте, чтобы выяснить, что ещё двигается, прежде чем завершить эскиз.", + "help.sketch.intersect": "Добавляет кривые или точки, где тела, грани, рёбра или другие эскизы пересекают плоскость эскиза. Они остаются связанными и следуют за моделью при её изменении.", + "help.sketch.intersection_curve": "Создаёт 3D-кривые там, где встречаются два тела или две грани, связанные с ними. Используйте как траектории или направляющие, следующие за моделью.", + "help.sketch.isoparametric_curve": "Создаёт 3D-кривую вдоль направления U или V грани через выбранную точку, связанную с гранью. Используйте как траекторию или линию разделения, следующую за поверхностью.", + "help.sketch.line": "Рисует соединённые линии точка за точкой, как открытую цепочку или замкнутый контур. Это основной инструмент для большинства профилей.", + "help.sketch.line.midpoint": "Рисует линию от её середины до одного конца, второй конец отражается зеркально. Используйте для линий с центром в точке, например симметричного ребра.", + "help.sketch.line3d": "Рисует соединённые прямые линии между точками в пространстве при включённом 3D-эскизе. Используйте для траекторий и рам, выходящих из плоскости эскиза.", + "help.sketch.mirror": "Отражает кривые и точки эскиза относительно линии или оси и добавляет ограничения симметрии. Используйте, чтобы нарисовать половину симметричного профиля и достроить его.", + "help.sketch.move": "Перемещает или поворачивает кривые и точки эскиза либо их копию. Используйте, чтобы переставить геометрию, сохранив её форму и ограничения.", + "help.sketch.offset": "Создаёт копию цепочки кривых на заданном расстоянии с одной или с обеих сторон. Используйте для стенок, контуров и зазоров; расстояние остаётся редактируемым размером.", + "help.sketch.paste": "Вставляет скопированную или вырезанную геометрию эскиза в активный эскиз. Поместите её в точку или сместите на заданную величину.", + "help.sketch.pattern.circular": "Копирует геометрию эскиза вокруг центральной точки на полный круг или заданный угол. Используйте для окружностей болтов, спиц и зубьев.", + "help.sketch.pattern.rectangular": "Копирует геометрию эскиза рядами и столбцами с заданным шагом. Используйте для сеток отверстий, пазов или вентиляционных прорезей.", + "help.sketch.point": "Ставит точку эскиза. Используйте как ориентир для размеров, ограничений, центров отверстий или последующих операций.", + "help.sketch.point3d": "Ставит точку в пространстве при включённом 3D-эскизе. Используйте как ориентир для 3D-кривых и траекторий.", + "help.sketch.polygon.circumscribed": "Рисует правильный многоугольник вокруг окружности; размер задаётся от центра до середины стороны. Используйте, когда известен размер под ключ, например у шестигранной гайки.", + "help.sketch.polygon.edge": "Рисует правильный многоугольник по двум концам одной стороны. Используйте, когда известны длина и положение стороны.", + "help.sketch.polygon.inscribed": "Рисует правильный многоугольник внутри окружности; размер задаётся от центра до угла. Используйте, когда известен размер между углами.", + "help.sketch.project": "Переносит рёбра, грани, вершины модели и кривые других эскизов в этот эскиз, проецируя их на его плоскость. Они остаются связанными и следуют за моделью при её изменении.", + "help.sketch.project_to_surface": "Проецирует кривые других эскизов по нормали этого эскиза на грань как связанные 3D-кривые. Используйте, чтобы нанести логотип, линию разделения или траекторию на изогнутую поверхность.", + "help.sketch.rectangle.center": "Рисует прямоугольник по центру и одному углу. Используйте для контуров с центром в точке, например в начале координат.", + "help.sketch.rectangle.rounded": "Рисует прямоугольник со всеми четырьмя углами, скруглёнными одним радиусом. Используйте для пластин, крышек и проёмов со скруглёнными углами.", + "help.sketch.rectangle.three_point": "Рисует прямоугольник по одной стороне и точке на противоположной. Используйте для прямоугольников под углом к осям эскиза.", + "help.sketch.rectangle.two_point": "Рисует прямоугольник по двум противоположным углам. Используйте для контуров пластин, блоков и карманов.", + "help.sketch.scale": "Масштабирует кривые и точки эскиза на коэффициент относительно базовой точки. Используйте, чтобы изменить размер части эскиза, не рисуя её заново.", + "help.sketch.slot.arc_center": "Рисует изогнутый паз заданной ширины вдоль дуги, заданной центром, началом и концом. Используйте для регулировочных пазов вокруг оси.", + "help.sketch.slot.arc_three_point": "Рисует изогнутый паз заданной ширины вдоль дуги через три точки. Используйте, когда траектория паза должна пройти через заданные точки.", + "help.sketch.slot.center_point": "Рисует прямой паз заданной ширины от его центра до центра одной торцевой дуги. Используйте для пазов с центром в точке.", + "help.sketch.slot.center_to_center": "Рисует прямой паз заданной ширины между центрами двух торцевых дуг. Используйте для пазов, размеры которых заданы от центра до центра, например регулировочных пазов под винты.", + "help.sketch.slot.overall": "Рисует прямой паз заданной ширины от одного внешнего конца до другого. Используйте, когда важна полная длина паза.", + "help.sketch.spline.control_point": "Рисует кубический сплайн по контрольным точкам, через которые он не проходит. Используйте для плавных текучих кривых, форму которых вы задаёте перемещением точек.", + "help.sketch.spline.control_point_5": "Рисует сплайн степени 5 по контрольным точкам. Используйте там, где кривые должны стыковаться с более плавной кривизной, например на видимых стилизованных поверхностях.", + "help.sketch.spline.fit_point": "Рисует плавный сплайн, проходящий через каждую поставленную вами точку, открытый или замкнутый. Используйте, чтобы обвести форму по известным точкам.", + "help.sketch.spline3d": "Рисует плавную кривую в пространстве через точки при включённом 3D-эскизе. Используйте для траекторий сдвига и трасс кабелей, выходящих из плоскости эскиза.", + "help.sketch.spun_profile": "Создаёт в плоскости эскиза контур, который тело заметает, вращаясь вокруг оси. Используйте, чтобы получить силуэт точёной детали для «Вращения» или чертежа.", + "help.sketch.text": "Пишет в эскизе текст выбранным шрифтом, высотой и под выбранным углом; слова могут следовать за параметрами. Выдавите его или нанесите «Тиснением» для надписей и маркировки.", + "help.sketch.transform": "Масштабирует, поворачивает и перемещает геометрию эскиза относительно центральной точки за один шаг. Используйте, чтобы сразу переставить и изменить размер выбранного.", + "help.sketch.trim": "Удаляет участок кривой между ближайшими пересечениями вокруг места щелчка. Используйте, чтобы превратить перекрывающиеся линии в замкнутый профиль.", "help.solid.align": "Перемещает выбранные тела так, чтобы точка, грань или плоскость на них совпала с точкой, гранью или плоскостью в другом месте. Используйте, чтобы приставить деталь к другой, не измеряя смещение.", + "help.solid.boundary_fill": "Создаёт тела из областей, ограниченных перекрывающимися телами-инструментами, заполняя только выбранные области. Используйте, чтобы построить форму из пространства, которое совместно ограничивают несколько тел.", + "help.solid.bounding_solid": "Создаёт бокс, охватывающий выбранные тела, с необязательным запасом. Используйте, чтобы увидеть габариты детали или как заготовку, из которой её обрабатывают.", + "help.solid.box": "Создаёт бокс по длине, ширине и высоте от угловой точки или с центром в точке. Используйте для быстрого блока, заглушки или тела, в котором вырезают элементы.", "help.solid.chamfer": "Срезает выбранные рёбра плоской фаской на заданное расстояние. Используйте, чтобы притупить острые кромки или облегчить вход штифта или винта.", + "help.solid.coil": "Создаёт винтовое тело, например пружину, по диаметру, числу витков, высоте или шагу и круглому либо квадратному сечению. Используйте для пружин, спиралей и винтовых гребней.", "help.solid.combine": "Объединяет тела, вырезает их из целевого тела или оставляет только общий для них объём; тела-инструменты можно сохранить. Используйте, чтобы слить детали, вырезать одной формой другую или найти, где два тела пересекаются.", + "help.solid.cone": "Создаёт конус по окружности основания и высоте или усечённый конус, если у верхней части тоже есть радиус. Используйте для сужений, воронок, зенковок и острий.", + "help.solid.cylinder": "Создаёт цилиндр по радиусу или диаметру и высоте, стоящий на точке вдоль оси. Используйте для валов, штифтов, бобышек и круглых заготовок.", "help.solid.draft": "Наклоняет выбранные грани на заданный угол, отсчитываемый от нейтральной плоскости. Используйте для литых и формованных деталей, чтобы они свободно извлекались из формы.", + "help.solid.emboss": "Выпячивает профили эскиза, например текст или логотип, из грани или вдавливает их в неё. Используйте для надписей, табличек и маркировки на плоских и круглых гранях.", "help.solid.extrude": "Выдавливает профиль эскиза в 3D на заданное расстояние, добавляя или удаляя материал. Используйте, чтобы превратить плоский контур в брусок, выступ или карман.", "help.solid.fillet": "Скругляет выбранные рёбра плавным круговым переходом заданного радиуса. Используйте, чтобы смягчить острые рёбра ради прочности, удобства или внешнего вида.", "help.solid.hole": "Сверлит круглое отверстие заданного диаметра в выбранной точке грани. Используйте для отверстий под винты и штифты и других простых круглых проёмов.", @@ -1397,20 +1667,62 @@ "help.solid.move": "Перемещает или поворачивает выбранные тела либо их копию на заданное расстояние и угол. Используйте, чтобы переставить тело или создать второе в другом месте.", "help.solid.offset_face": "Смещает выбранные грани внутрь или наружу на заданное расстояние, а окружающие грани следуют за ними. Используйте, чтобы сделать стенку толще, карман глубже или выступ выше, не редактируя эскиз.", "help.solid.pattern.circular": "Повторяет выбранные объекты вокруг оси с заданным количеством и общим углом. Используйте для болтов по окружности, спиц, рёбер и зубьев.", + "help.solid.pattern.path": "Копирует операции или тела вдоль траектории эскиза по числу и шагу. Используйте для отверстий вдоль изогнутого ребра или деталей вдоль направляющей.", "help.solid.pattern.rectangular": "Повторяет выбранные объекты в одном или двух направлениях с заданным количеством и шагом. Используйте для рядов и сеток отверстий, рёбер жёсткости, штифтов или ножек.", + "help.solid.pipe": "Создаёт круглую трубу вдоль траектории из кривых эскиза, сплошную или полую с заданной толщиной стенки. Используйте для труб, проводов, кабелей и направляющих.", "help.solid.press_pull": "Добавляет или удаляет материал при перетаскивании грани либо скругляет рёбра при их перетаскивании. Используйте для быстрых изменений прямо на модели.", "help.solid.remove": "Убирает выбранные тела из дизайна начиная с этого места в истории; предыдущие шаги их сохраняют. Используйте, чтобы убрать вспомогательное тело, например режущий инструмент, который больше не нужен.", "help.solid.replace_face": "Переносит выбранные плоские грани на плоскость или на параллельную грань, и тело растёт или уменьшается, чтобы достичь её. Используйте, чтобы совместить грань вровень с другой деталью или вспомогательной плоскостью.", "help.solid.revolve": "Вращает профиль эскиза вокруг оси, создавая тело вращения. Используйте для валов, ручек, чаш и любых деталей, круглых относительно осевой линии.", + "help.solid.rib": "Добавляет ребро жёсткости: тонкую стенку вдоль открытой кривой эскиза, доведённую до ближайших граней тела. Используйте, чтобы усилить стенки и углы, например в формованных или печатных деталях.", "help.solid.scale": "Увеличивает или уменьшает выбранные тела на коэффициент, одинаковый по всем направлениям или свой для каждой оси. Используйте, чтобы изменить размер импортированной формы или учесть усадку.", "help.solid.shell": "Делает тело полым, оставляя стенки заданной толщины, и может открывать выбранные грани. Используйте для коробок, крышек и других тонкостенных деталей.", + "help.solid.sphere": "Создаёт сферу по радиусу или диаметру вокруг центральной точки. Используйте для шаров, ручек и скруглённых концов.", "help.solid.split_body": "Разрезает тело на отдельные тела плоскостью, гранью другого тела или линией эскиза. Используйте, чтобы получить детали, которые печатаются, обрабатываются или окрашиваются отдельно.", "help.solid.split_face": "Делит выбранные грани по плоскости, грани другого тела или кривым эскиза, не разрезая тело. Используйте, чтобы задать части грани собственный уклон, цвет или смещение.", "help.solid.sweep": "Протягивает профиль эскиза вдоль траектории, создавая тело. Используйте для труб, направляющих, ручек и любых деталей постоянного сечения, следующих по кривой.", + "help.solid.thread": "Добавляет метрическую резьбу ISO на цилиндрическую грань: условную или вырезанную в теле. Используйте для болтов, резьбовых отверстий и печатных винтовых деталей.", + "help.solid.torus": "Создаёт кольцо по большому радиусу вокруг его оси и малому радиусу круглого сечения. Используйте для уплотнительных колец, ручек и круглых бусин.", + "help.solid.web": "Добавляет тонкую перегородку вдоль каждой открытой кривой эскиза, каждую доведённую до ближайших граней тела. Используйте для сетки поддерживающих перегородок внутри корпусов и лотков.", + "help.surface.blend": "Создаёт поверхность, соединяющую рёбра двух тел, касательную или с непрерывной кривизной к обоим. Используйте, чтобы плавно соединить две поверхности через зазор.", + "help.surface.boundary": "Создаёт поверхность, заполняющую контур из двух–четырёх кривых эскиза, или сеть кривых. Используйте для свободных панелей, заданных своими краями.", + "help.surface.extend": "Удлиняет поверхность за её кромки на расстояние или до плоскости или грани. Используйте, чтобы поверхности перекрывались перед обрезкой или сшиванием.", + "help.surface.extrude": "Выдавливает кривые или профили эскиза на расстояние в поверхность: только стенки, без торцов. Используйте для тонких стенок и режущих или разделяющих инструментов.", + "help.surface.fair": "Сглаживает внутреннюю часть свободных граней, пока их кромки остаются на месте. Используйте, чтобы выровнять бугры и волнистые отражения на поверхности.", + "help.surface.loft": "Создаёт поверхность, проходящую по порядку через два или более сечений, без торцов. Используйте для оболочек и переходов между разными формами.", + "help.surface.match": "Перестраивает кромку поверхности так, чтобы она стыковалась с кромкой другого тела, с согласованными касательными или кривизной. Используйте, чтобы плавно закрыть шов между двумя поверхностями.", + "help.surface.offset": "Создаёт копию граней на расстоянии по их нормалям как новое тело-поверхность. Используйте для оболочек, зазоров или другой стороны стенки.", + "help.surface.patch": "Заполняет область эскиза или замкнутый контур рёбер гранью, плоской или плавно изогнутой. Используйте, чтобы закрывать отверстия в теле-поверхности.", + "help.surface.reverse_normal": "Переворачивает грани тела-поверхности, так что их внешняя сторона смотрит в другую сторону. Используйте перед утолщением или сшиванием, если грани направлены внутрь.", + "help.surface.revolve": "Вращает кривые или профили эскиза вокруг оси в поверхность, без торцов. Используйте для круглых оболочек, таких как абажуры, чаши и сопла.", + "help.surface.ruled": "Создаёт полосу из прямых линий от цепочки рёбер вдоль нормали грани, по касательной или под углом. Используйте для стенок с уклоном, переходных участков и поверхностей разъёма.", + "help.surface.stitch": "Сшивает тела-поверхности по общим рёбрам, а если они замыкаются, получается твёрдое тело. Используйте, чтобы превратить набор поверхностей в одно тело.", + "help.surface.sweep": "Протягивает кривые или профили эскиза вдоль траектории в поверхность, без торцов. Используйте для желобов, накладок и других тонких форм, следующих за траекторией.", + "help.surface.thicken": "Придаёт телу-поверхности толщину, превращая его в твёрдое тело. Используйте, чтобы получать из поверхностей детали для печати или обработки.", + "help.surface.trim": "Обрезает поверхность плоскостью, другой поверхностью или кривыми эскиза и оставляет выбранную сторону. Используйте, чтобы подрезать поверхности по форме перед сшиванием.", + "help.surface.unstitch": "Разделяет грани тела на отдельные тела-поверхности; твёрдое тело распадается на поверхности. Используйте, чтобы переработать отдельные грани тела.", + "help.surface.untrim": "Удаляет отверстия из грани или возвращает её внешнюю границу к естественным границам поверхности. Используйте, чтобы вернуть полную поверхность после обрезки.", "help.third_party": "Лицензии сторонних компонентов", "help.timeline.compute_all": "Перестраивает все операции в истории с самого начала. Используйте, чтобы обновить модель и увидеть, какие операции завершаются с ошибкой.", "help.timeline.delete": "Удаляет выбранные операции из истории; при удалении эскиза также удаляются операции, построенные на нём. Используйте, чтобы убрать шаг, который больше не нужен.", + "help.timeline.dependents": "Перечисляет операции, которые будут удалены вместе с выбранной, и те, что перестанут работать без неё. Используйте перед удалением или изменением операции.", "help.timeline.play": "Воспроизводит оставшиеся операции по одной с паузой в полсекунды после каждой перестройки. Чтобы остановить, запустите эту команду снова или нажмите Esc; «Перейти в конец» переходит мгновенно.", + "help.view.apply": "Поворачивает вид к стандартному направлению, например спереди, сверху или изометрии, либо к сохранённому именованному виду. Используйте, чтобы смотреть на модель под фиксированным углом.", + "help.view.delete": "Удаляет сохранённый именованный вид. Модель не меняется.", + "help.view.fit": "Масштабирует и сдвигает вид так, чтобы вся модель или выделенное заполнили его. Используйте, когда модель ушла из поля зрения.", + "help.view.grid": "Показывает или скрывает сетку на видовом экране. Используйте как ориентир размера и направления при моделировании.", + "help.view.ground_shadow": "Показывает или скрывает тень модели на земле. Используйте, чтобы легче оценивать высоту и положение.", + "help.view.home": "Возвращает вид в главное направление и вписывает модель. Используйте, чтобы быстро вернуться к известному виду.", + "help.view.list": "Перечисляет именованные виды, сохранённые в дизайне. Используйте, чтобы найти вид, сохранённый ранее.", + "help.view.navigate": "Поворачивает, сдвигает или масштабирует вид шагами, например четверть оборота влево. Используйте, чтобы точно двигать камеру вместо перетаскивания.", + "help.view.navigation_bar": "Показывает или скрывает панель навигации внизу видового экрана. Скройте её, чтобы освободить место, и покажите, чтобы пользоваться инструментами вида мышью.", + "help.view.rename": "Даёт сохранённому именованному виду новое имя. Сам вид не меняется.", + "help.view.save": "Сохраняет текущее положение камеры как именованный вид в дизайне. Используйте, чтобы позже вернуться к тому же ракурсу, например для снимков экрана.", + "help.view.spin": "Непрерывно вращает вид вокруг модели до следующего щелчка или нажатия клавиши. Используйте, чтобы показать модель со всех сторон.", + "help.view.tool": "Закрепляет инструмент камеры (орбиту, панорамирование или масштаб), так что перетаскивание левой кнопкой мыши двигает вид, пока вы его не отключите. Используйте на трекпаде или без средней кнопки мыши.", + "help.view.visual_style": "Переключает способ отрисовки модели: тонированная с рёбрами или без них, каркас или со скрытыми рёбрами. Используйте каркас, чтобы заглянуть внутрь, а тонированный вид — для чистого вида.", + "history.sketch_under_constrained": "Недоопределён (степеней свободы: {count})", + "history.sketch_under_constrained_one": "Недоопределён (степеней свободы: {count})", "hole_presets.confirm_delete": "Подтвердить удаление", "hole_presets.delete": "Удалить", "hole_presets.delete_prompt": "Удалить этот личный пресет? Существующие отверстия не изменятся.", @@ -1514,6 +1826,8 @@ "joint_move.blocked_hint": "Проверьте тип сопряжения (например, «Жёсткое»), закрепление, ограничения сопряжения и значения, заданные параметрами.", "joint_move.blocked_title": "Эту деталь нельзя переместить", "joint_move.coarse": "Шаг поворота вблизи оси (°)", + "joint_move.conflict": "Одно из сопряжений этой детали конфликтует с остальными: {joint}.", + "joint_move.conflict_hint": "Измените, подавите или удалите конфликтующее сопряжение, чтобы остальные сопряжения могли расположить деталь.", "joint_move.distance": "Расстояние от начала", "joint_move.done": "Готово", "joint_move.fine": "Шаг поворота вдали от оси (°)", @@ -1585,6 +1899,10 @@ "material.selection.mixed": "Разные материалы", "measure.at": "В точке", "measure.item": "Элемент {number}", + "measure.quick_copied": "Измерение скопировано", + "measure.quick_copy": "Щёлкните, чтобы скопировать измерение", + "measure.quick_edges": "Рёбер: {count}", + "measure.quick_faces": "Граней: {count}", "messages.ago_h": "{n} ч назад", "messages.ago_min": "{n} мин назад", "messages.ago_s": "{n} с назад", @@ -1609,6 +1927,8 @@ "motion.track_name": "Дорожка {number}", "nav.alias.help": "Shift+Alt+перетаскивание левой кнопкой вращает, Shift+Alt+средней панорамирует, Shift+Alt+правой меняет масштаб; перетаскивание средней кнопкой тоже панорамирует, правой — вращает", "nav.blender.help": "Перетаскивание средней кнопкой вращает, Shift+средняя панорамирует, Ctrl+средняя меняет масштаб; перетаскивание правой кнопкой камеру не двигает", + "nav.creo.help": "Перетаскивание средней кнопкой вращает, Shift+средняя панорамирует, Ctrl+перетаскивание средней кнопкой по вертикали меняет масштаб (вниз — приблизить); колесо прокрутки тоже меняет масштаб", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Мышь и 3D-мышь вращают вид через оба полюса и сохраняют крен. Привязка к осям по Shift отключена.", "nav.free_orbit.label": "Свободная орбита", "nav.free_orbit.snap_help": "Мышь и 3D-мышь вращают вид через оба полюса и сохраняют крен. Удерживайте Shift при вращении, чтобы привязать направление вида и крен к осям.", @@ -1618,6 +1938,7 @@ "nav.hfss.help": "Alt+перетаскивание левой кнопкой панорамирует, Shift+Alt+левая кнопка меняет масштаб, Ctrl+перетаскивание левой кнопкой по пустому месту вращает", "nav.inventor.help": "Перетаскивание средней кнопкой панорамирует, Shift+средняя вращает, Ctrl+средняя меняет масштаб, перетаскивание правой кнопкой вращает", "nav.maya.help": "Alt+перетаскивание левой кнопкой вращает, Alt+средняя кнопка панорамирует, Alt+правая кнопка меняет масштаб; перетаскивание средней кнопкой тоже панорамирует", + "nav.nx.help": "Перетаскивание средней кнопкой вращает, Shift+средняя панорамирует (в NX — средняя + правая), Ctrl+средняя меняет масштаб (в NX — средняя + левая); перетаскивание правой кнопкой камеру не двигает", "nav.openscad.help": "Перетаскивание левой кнопкой по пустому месту вращает, Shift+левая выделяет рамкой, перетаскивание геометрии эскиза изменяет её; правая или средняя кнопка панорамирует, Shift+правая или Shift+средняя меняет масштаб", "nav.perspective.sketch": "При редактировании эскиза используется ортогональный вид. Завершите эскиз, чтобы включить перспективу.", "nav.right_drag_orbits.help": "Выкл.: перетаскивание правой кнопкой не двигает камеру, а правая кнопка только открывает контекстное меню. Выбор назначения кнопок мыши SolidWorks отключает этот параметр.", @@ -1737,6 +2058,11 @@ "not a move": "это не перемещение", "not a number": "не число", "open a sketch first": "сначала откройте эскиз", + "parameters.apply_live": "Применять каждое изменение при выходе из поля", + "parameters.apply_live_tip": "Выкл.: изменения ждут «Применить» или OK, после чего дизайн один раз пересобирается для всех сразу. «Отмена» или Esc отбрасывает их.", + "parameters.held": "Изменений в ожидании применения: {count}", + "parameters.held_hint": "Правьте выражения и единицы. Изменения ждут «Применить» или OK.", + "parameters.held_one": "1 изменение ждёт применения", "parts.automatic_name": "автоматически", "parts.dimension.across_flats": "Размер под ключ", "parts.dimension.bore": "Диаметр отверстия", @@ -1755,10 +2081,19 @@ "parts.family.button_head_cap_screw": "Винт с полукруглой головкой и внутренним шестигранником", "parts.family.dowel_pin": "Цилиндрический штифт", "parts.family.hex_bolt": "Болт / винт с шестигранной головкой", + "parts.family.hex_cap_screw_inch": "Винт с шестигранной головкой (дюймовый)", "parts.family.hex_nut": "Шестигранная гайка", + "parts.family.hex_nut_inch": "Шестигранная гайка (дюймовая)", "parts.family.set_screw": "Установочный винт с внутренним шестигранником и плоским концом", "parts.family.socket_head_cap_screw": "Винт с цилиндрической головкой и внутренним шестигранником", "parts.family.washer": "Плоская шайба", + "parts.family.washer_sae": "Плоская шайба, SAE (узкая)", + "parts.family.washer_uss": "Плоская шайба, USS (широкая)", + "parts.holes": "Отверстия (необязательно)", + "parts.placement_hint": "выберите одно или несколько отверстий, чтобы посадить деталь в каждое, или OK поместит её в начало координат", + "parts.system": "Система единиц", + "parts.system.inch": "Дюймовая", + "parts.system.metric": "Метрическая", "pattern.alignment_2": "Выравнивание 2", "pattern.alignment_hint": "Количество включает оригинал. Центрирование распределяет копии по обе стороны; при чётном количестве смена направления выбирает сторону с дополнительной копией.", "pattern.direction_1": "Направление 1", @@ -1799,6 +2134,8 @@ "prefs.anti_aliasing_note": "Сглаживает неровные края.", "prefs.applies_on_restart": "Применяется после перезапуска", "prefs.assistant": "Ассистент", + "prefs.auto_operation": "Выбирать операцию автоматически", + "prefs.auto_operation_note": "Окна операций сами выбирают «Объединить», «Новое тело» или «Вырезать» в зависимости от того, чего касается новый материал, пока вы не выберете операцию вручную. Выкл.: окна сохраняют ту операцию, с которой открылись.", "prefs.axes": "Оси", "prefs.axis": "Ось", "prefs.bodies_folders": "Папки тел", @@ -1807,6 +2144,10 @@ "prefs.bodies_folders_several": "Только если тел несколько", "prefs.bottom": "Снизу", "prefs.browser": "Браузер", + "prefs.browser_components_open": "Компоненты развёрнуты с начала", + "prefs.browser_components_open_note": "Каждый компонент в браузере сразу развёрнут, как раньше, а не свёрнут, пока вы его не развернёте.", + "prefs.browser_eye_left": "Глаз рядом со стрелкой свёртывания", + "prefs.browser_eye_left_note": "Строки браузера показывают глаз показа/скрытия рядом со стрелкой свёртывания, как раньше, а не в столбце на правом конце строк.", "prefs.browser_reveal_on_hover": "Появляется при наведении", "prefs.browser_show_note": "«Показан» оставляет браузер на экране. «Появляется при наведении» прячет его, пока указатель не окажется на его месте или на тонкой вкладке у его левого края; он остаётся открытым, пока указатель находится внутри него или открыто его меню.", "prefs.browser_shown": "Показан", @@ -1814,6 +2155,8 @@ "prefs.button_left": "Перетаскивание левой кнопкой", "prefs.button_middle": "Перетаскивание средней кнопкой", "prefs.button_right": "Перетаскивание правой кнопкой", + "prefs.carousel_next": "Далее", + "prefs.carousel_previous": "Назад", "prefs.choose_font": "Выбрать файл шрифта…", "prefs.click": "Щелчок", "prefs.contact_shading": "Мягкое контактное затенение", @@ -1826,6 +2169,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Криволинейные поверхности", "prefs.curves": "Криволинейные поверхности", + "prefs.cut_preview_tint": "Показывать удаляемый материал красным", + "prefs.cut_preview_tint_help": "В предпросмотре материал, который удаляет операция, и форма, которую она заменяет, закрашиваются красным полупрозрачным призраком. Если выключено, эти заливки полностью прозрачны и рисуются только их контуры.", + "prefs.dark_parts_shading": "Сохранять форму тёмных деталей", + "prefs.dark_parts_shading_help": "Затенять вид в линейном свете с мягкой заполняющей подсветкой неба, чтобы тёмные грани сохраняли градиент, а не становились чёрными", "prefs.dead_zone_note": "Заштрихованная полоса — мёртвая зона: движение внутри неё игнорируется.", "prefs.default": "по умолчанию", "prefs.design": "Параметры дизайна по умолчанию", @@ -1840,6 +2187,8 @@ "prefs.edges": "Рёбра и затенение", "prefs.extend": "Удлинить", "prefs.extra_navigation": "Ctrl+перетаскивание левой кнопкой по пустому месту вращает вид; удерживайте Space для панорамирования.", + "prefs.extrude_view_isometric": "Поворачивать вид в изометрию при открытии «Выдавливания»", + "prefs.extrude_view_return": "Возвращать прежний вид при закрытии «Выдавливания»", "prefs.follows_os": "Как в системе", "prefs.font": "Шрифт", "prefs.font_fallback": "Символы, которых нет в выбранном шрифте, берутся из встроенного шрифта, поэтому ни одна подпись не показывает пустой квадрат.", @@ -1855,8 +2204,11 @@ "prefs.graphics_card_auto": "Автоматически", "prefs.graphics_card_missing": "Сохранённая видеокарта недоступна; используется «Автоматически».", "prefs.graphics_card_restart": "Вступит в силу после перезапуска SolidCraft. WGPU_ADAPTER_NAME переопределяет этот выбор.", + "prefs.graphics_card_unused": "Сохранённая видеокарта для этого окна не использовалась; используемая видеокарта показана в меню Справка › О SolidCraft и в строке состояния. Попробуйте «Автоматически» или задайте для WGPU_ADAPTER_NAME уникальную часть названия видеокарты.", "prefs.graphics_note": "Выбирайте между скоростью и плавностью изображения. Каждый вариант показывает свой эффект на образце.", "prefs.graphics_presets_note": "Пресеты задают сразу все настройки ниже.", + "prefs.hide_constraint_glyphs_zoomed_out": "Скрывать знаки ограничений при уменьшении масштаба", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Знаки ограничений исчезают из вида, когда эскиз уменьшен настолько, что они загромождали бы его. Выкл.: при любом масштабе они сохраняют фиксированный размер на экране.", "prefs.history": "История", "prefs.history_origin_bodies": "Показывать начало координат и тела сверху", "prefs.history_origin_bodies_note": "История слева или под браузером начинается с папки «Тела» активного компонента и начала координат, с их глазками и меню, как в браузере. История внизу не меняется.", @@ -1867,6 +2219,8 @@ "prefs.history_sketches_note": "Если для эскизов выбрано «Под своей операцией», История слева показывает каждый эскиз на один уровень глубже, под первой операцией, построенной по нему, когда она достаточно широкая для названий. Шкала внизу всегда сохраняет порядок создания.", "prefs.history_sketches_under_feature": "Под своей операцией", "prefs.hold_stop_snapping": "Удерживайте, чтобы отключить привязку", + "prefs.home_fit_size": "Размер для «Главная» и «Вписать»", + "prefs.home_fit_size_note": "Какую часть вида занимает модель, когда её кадрируют «Главная», «Вписать», открытый дизайн или смена вида в навигаторе, независимо от того, включён ли параметр ниже. 100 %: заполняет вид между панелями, компасом и панелью навигации.", "prefs.icons_only": "Только значки", "prefs.imported_file": "Импортированный файл", "prefs.input": "Ввод", @@ -1874,13 +2228,22 @@ "prefs.interface_language": "Язык интерфейса", "prefs.interface_note": "Как выглядит SolidCraft и где расположены его части.", "prefs.interval_minutes": "{n} мин", + "prefs.invert_curved_roll_arrows": "Инвертировать изогнутые стрелки крена", + "prefs.invert_curved_roll_arrows_note": "Две изогнутые стрелки в углу куба поворачивают вид в плоскости экрана. Вкл.: стрелка по часовой стрелке поворачивает вид против часовой, а стрелка против часовой — по часовой. Выкл.: каждая стрелка поворачивает вид в ту сторону, куда она изогнута.", + "prefs.invert_navigator_arrows": "Инвертировать стрелки вращения куба видов", + "prefs.invert_navigator_arrows_note": "Стрелки вокруг куба вращают камеру в ту сторону, куда указывают, как в Fusion и Inventor: стрелка слева указывает вправо и поворачивает камеру вправо. Выкл.: стрелка поворачивает куб в сторону, где она расположена, поэтому левая стрелка поворачивает камеру влево. Изогнутые стрелки крена не затрагиваются.", + "prefs.keep_work_on_tab_switch": "Сохранять открытые диалоги и инструменты при переключении между дизайнами", + "prefs.keep_work_on_tab_switch_note": "Каждая вкладка дизайна сохраняет свой открытый диалог или инструмент вместе с тем, что вы в нём выбрали и ввели, а также свою вкладку панели инструментов. Они снова на месте, когда вы возвращаетесь к дизайну. Выкл.: при переключении дизайнов они отменяются, и показывается вкладка «Модель».", "prefs.labels": "Подписи", + "prefs.language_system": "Системный", "prefs.layout": "Расположение", "prefs.layout_note": "«Компактная» прикрепляет панели к краям окна. Прозрачность браузера доступна в режиме «Плавающая». Сторону ассистента можно изменить на странице «Ассистент».", "prefs.left": "Слева", "prefs.left_click": "Щелчок левой кнопкой", "prefs.line_drag_draws_one": "Нажатие и перетаскивание рисует одну линию", "prefs.line_drag_draws_one_note": "В инструменте «Линия» нажатие, перетаскивание и отпускание рисуют одну линию от места нажатия до места отпускания, и на этом она заканчивается. Щелчки по-прежнему рисуют цепочку. Выкл.: перетаскивание ставит точку там, где его отпустили, как и щелчок.", + "prefs.line_hover_tangent_arc": "Задержаться на последней точке линии, чтобы перейти к касательной дуге", + "prefs.line_hover_tangent_arc_note": "В инструменте «Линия» после того, как сегмент нарисован, отведите указатель от последней точки цепочки, вернитесь и удерживайте его на ней неподвижно: следующий щелчок завершит касательную дугу, а тот же жест вернёт к линиям. Выкл.: задержка там ничего не делает.", "prefs.linked_designs": "Связанные дизайны", "prefs.live_input": "Ввод в реальном времени", "prefs.live_preview": "Предпросмотр в реальном времени", @@ -1894,6 +2257,9 @@ "prefs.max_file_size_step": "Файлы STEP и импорта", "prefs.max_file_size_web": "Веб-приложение открывает файлы STEP и импорта до 512 МБ и дизайны до 256 МБ: вкладка браузера не вмещает более крупные файлы. В настольном приложении эти пределы можно увеличить.", "prefs.megabytes": "МБ", + "prefs.menu_grid": "Крупные значки", + "prefs.menu_list": "Список", + "prefs.menus": "Меню", "prefs.minutes": "мин.", "prefs.minutes_suffix": " min", "prefs.mouse": "Мышь и тачпад", @@ -1901,6 +2267,8 @@ "prefs.mouse_mapping": "Назначение кнопок мыши", "prefs.navigation": "Навигация", "prefs.navigation_note": "Как мышь, тачпад и 3D-мышь двигают вид.", + "prefs.navigator_fit": "Вписывать модель после смены вида в навигаторе", + "prefs.navigator_fit_note": "Грань, угол или стрелка куба видов либо ось гизмо также направляет взгляд на середину модели с единственного расстояния, с которого она целиком видна со всех сторон (её габаритная сфера). «Главная» при включённом параметре использует тот же масштаб и центр, поэтому выбранные после неё виды только поворачиваются. Выкл.: вид поворачивается на месте, сохраняя свою цель и масштаб.", "prefs.network_host_remove": "Убрать", "prefs.network_locations": "Разрешить сетевые расположения в дизайнах", "prefs.network_locations_note": "Выкл.: связанные файлы дизайна на другом компьютере (\\\\server\\share) открываются только с перечисленных здесь серверов или после того, как вы разрешите сервер по запросу.", @@ -1913,10 +2281,18 @@ "prefs.origin_plane_names": "Имена плоскостей начала координат", "prefs.origin_plane_names_note": "Имена в браузере, диалогах и списках. {top} — это XY, {front} — XZ, {right} — YZ, ось Z направлена вверх. Команды, скрипты и сохранённые дизайны по-прежнему используют XY, XZ и YZ.", "prefs.overall_speed": "Общая скорость", + "prefs.parameter_list_rows": "Строк в списке параметров", + "prefs.parameter_list_rows_tip": "Стрелка вниз в пустом поле значения открывает список параметров, сначала избранные, не больше этого числа. Меньшее число делает список лёгким в большом дизайне.", + "prefs.persistent_ribbon_pressed": "Подсвечивать активные команды на ленте", + "prefs.persistent_ribbon_pressed_help": "Подсвечивает команды на ленте, пока их действие включено. Отключите, чтобы сохранить прежний нейтральный вид и справку по командам.", "prefs.perspective_fov": "Угол обзора", "prefs.placement": "Размещение", "prefs.prefer_free_sketch_points": "Предпочитать подвижные точки эскиза, когда точки перекрываются", "prefs.preview_choices": "Предпросмотр вашего выбора", + "prefs.preview_tint_new_faces": "Подкрашивать новую поверхность в предпросмотре", + "prefs.preview_tint_new_faces_help": "Предпросмотр операции, изменяющей тело, может рисовать добавляемую ею поверхность цветом предпросмотра. Если выключено, тело рисуется как есть.", + "prefs.print_face_highlight": "Подсветка грани печати", + "prefs.print_face_highlight_tip": "Насколько сильно грань печати тела окрашивается и обводится в виде. 0 % — без подсветки.", "prefs.profile_active": "Активный профиль", "prefs.profile_applied": "Профиль применён.", "prefs.profile_changed": "Настройки изменились после сохранения профиля. «Сохранить» запоминает их в профиле.", @@ -1938,9 +2314,13 @@ "prefs.quality_fastest": "быстрее всего", "prefs.quality_slowest": "медленнее всего", "prefs.quality_smoother": "глаже", + "prefs.quick_measure": "Быстрое измерение в углу вида", + "prefs.quick_measure_note": "Размер выделенного в правом нижнем углу вида: длина ребра, Ø и R для круглого, площадь грани, положение точки, расстояние и угол между двумя элементами, общее значение для нескольких рёбер или граней. Щелчок копирует его.", "prefs.render_previous_geometry_budget": "Использовать прежний бюджет геометрии предпросмотра рендера", "prefs.render_previous_geometry_budget_help": "Вернуть прежний фиксированный предел геометрии (512 МиБ на 64-разрядном настольном компьютере, 128 МиБ на остальных устройствах) вместо бюджета, зависящего от устройства.", "prefs.reports_saved": "Сохранено: {n}", + "prefs.ribbon_click_ends_tool": "Щелчок по кнопке работающего инструмента завершает его", + "prefs.ribbon_click_ends_tool_note": "Щелчок по подсвеченной кнопке используемого инструмента эскиза на ленте завершает инструмент, и щелчки в виде снова выделяют объекты. Выкл.: щелчок снова запускает инструмент.", "prefs.ribbon_reveal": "Показывать результаты поиска на ленте", "prefs.ribbon_reveal_note": "Наведение на результат в «Поиске команд» показывает, где команда находится на ленте: её вкладку, кнопку или строку в раскрывающемся списке панели. Команда, запущенная из поиска, мигает там, а выполняемая команда из раскрывающегося списка отмечает свою панель.", "prefs.right_click": "Правый щелчок", @@ -1951,6 +2331,8 @@ "prefs.search_empty": "Нет подходящих настроек", "prefs.select": "Выделить", "prefs.select_one_item": "Выбрать один элемент", + "prefs.select_other_hidden": "Выбирать скрытую геометрию командой «Выбрать другое»", + "prefs.select_other_hidden_help": "Вкл.: учитывать скрытые тела, эскизы и перекрытые рёбра рядом с указателем. Выкл.: использовать исходный список видимой геометрии под указателем.", "prefs.selecting": "Выделение", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift только добавляет; Ctrl / Cmd переключает", @@ -1966,26 +2348,57 @@ "prefs.sketch_exit_view.previous": "Вернуться к прежнему виду", "prefs.sketch_exit_view.unless_rotated": "Вернуться, если вид не повёрнут", "prefs.sketch_exit_view_note": "Куда переходит вид после «Завершить эскиз», «Отмена» или двойного Esc.", + "prefs.sketch_face_activates_part": "Эскиз на грани детали делает эту деталь активной", + "prefs.sketch_face_activates_part_note": "Эскиз, начатый на грани тела другого компонента, сначала активирует этот компонент, поэтому эскиз принадлежит ему и в браузере остаётся с этой деталью. После этого деталь остаётся активной. Выкл.: эскиз принадлежит активному компоненту.", + "prefs.sketch_open_look_at": "Поворачивать камеру к эскизу при его открытии", + "prefs.sketch_open_look_at_note": "Выкл.: при создании или редактировании эскиза вид не меняется. «Взгляд на» поворачивает вид к эскизу, когда это нужно.", "prefs.sketch_recent_snap": "Автопривязка к недавним центрам и серединам", "prefs.sketch_recent_snap_note": "При рисовании курсор привязывается к месту пересечения направляющих двух последних центров окружностей или середин прямых отрезков. Выкл.: эти направляющие остаются только визуальными, а курсор не смещается.", "prefs.sketch_selection": "Эскиз и выделение", "prefs.sketch_selection_heading": "Эскиз и выделение", "prefs.sketch_selection_note": "Как работает привязка в эскизах и как щелчки выделяют объекты.", + "prefs.sketch_state_icons": "Значки эскизов в цвете их состояния", + "prefs.sketch_state_icons_note": "В истории и браузере значок эскиза принимает цвет его состояния (недоопределён, полностью определён или с конфликтом), а подсказка называет это состояние. Выкл.: у всех эскизов одинаковый значок.", "prefs.sketch_tab_always": "Всегда показывать вкладку «Эскиз»", "prefs.sketch_tab_always_note": "Вкладка «Эскиз» остаётся на ленте сразу после «Модель», пока не открыт ни один эскиз. Её инструменты рисования создают эскиз на выбранной плоскости или грани либо на плоскости, которую вы выберете следом, и сразу включают нужный инструмент.", "prefs.sketch_tracking_guides": "Направляющие выравнивания по центру и середине", "prefs.sketch_tracking_guides_note": "Наведите курсор на центр окружности или середину прямого отрезка, затем двигайтесь по горизонтали или вертикали, чтобы показать временную пунктирную направляющую.", + "prefs.sketch_tracking_points": "Направляющие выравнивания от концов и углов при рисовании", + "prefs.sketch_tracking_points_note": "Пока инструмент рисования ждёт точку, наведение на конец линии или дуги, угол прямоугольника или свободную точку показывает ту же временную пунктирную направляющую, что и для центра или середины. Выкл.: только центры и середины.", "prefs.sketching": "Эскизирование", "prefs.snap_drawing_note": "При рисовании или перетаскивании точки эскиза.", "prefs.source": "Источник", "prefs.speed": "Скорость", "prefs.stand_up_note": "После открытия файла STEP или IGES с осью Z вверх предлагать повернуть его на четверть оборота вокруг X.", + "prefs.stand_up_unknown": "Для файлов из неизвестных программ", + "prefs.stand_up_unknown.ask": "Спрашивать в диалоговом окне", + "prefs.stand_up_unknown.note": "Показывать уведомление", + "prefs.stand_up_unknown.off": "Не предлагать", + "prefs.stand_up_unknown_note": "Как делается предложение, когда в заголовке файла не указана программа, о которой известно, что она сохраняет с осью Y вверх. Уведомление показывается, только если файл, судя по всему, лежит на спине; «Спрашивать в диалоговом окне» спрашивает о каждом таком файле, как раньше.", "prefs.status_bar": "Строка состояния", "prefs.status_bar_note": "Тонкая полоса вдоль нижнего края окна показывает, что изменяется, состояние открытого эскиза его цветом и единицы дизайна; щелчок по единицам изменяет их. Состояние эскиза при этом больше не показывается в углу вида.", "prefs.status_done": "Готово", "prefs.status_error": "Ошибка", "prefs.status_selected": "Выбрано", "prefs.status_warning": "Предупреждение", + "prefs.structure.appearance": "Внешний вид", + "prefs.structure.appearance_note": "Цвета, текст и специальные возможности.", + "prefs.structure.in_profile": "В профиле", + "prefs.structure.layout": "Расположение", + "prefs.structure.layout_note": "Где находятся части окна.", + "prefs.structure.look": "Оформление", + "prefs.structure.measure_pointer": "Измерение и указатель", + "prefs.structure.mouse3d": "3D-мышь", + "prefs.structure.mouse3d_note": "SpaceMouse и SpaceNavigator.", + "prefs.structure.navigation_note": "Мышь и тачпад. У 3D-мыши есть своя страница.", + "prefs.structure.profile": "Профиль", + "prefs.structure.profile_edited": "Изменено после сохранения", + "prefs.structure.profile_hover": "Сохранено в профилях настроек", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Эскиз", + "prefs.structure.tools": "Инструменты", + "prefs.structure.tools_note": "Как ведут себя инструменты моделирования.", + "prefs.structure.work": "Работа", "prefs.supersampling_brief": "Рисует вид в большем размере и уменьшает его: очень чётко, но тяжелее.", "prefs.tab_accent_note": "Акцентный цвет следует за активной вкладкой", "prefs.theme_file": "файл темы", @@ -1997,6 +2410,16 @@ "prefs.theme_follow_off": "Выкл.", "prefs.theme_follow_stop": "Прекратить отслеживание", "prefs.theme_import_hint": "Щёлкните, чтобы выбрать файл темы, перетащите его сюда или нажмите Ctrl+V (Cmd+V на Mac) при скопированной теме", + "prefs.theme_option_opacity": "Непрозрачность", + "prefs.theme_option_opacity_help": "Настройте непрозрачность плавающих панелей. Нижний порог читаемости защищает текст поверх цветов видового экрана.", + "prefs.theme_option_tab_colours": "Цвета вкладок", + "prefs.theme_option_tab_colours_help": "Использовать цвета панелей и видового экрана этой темы для каждой вкладки ленты.", + "prefs.theme_option_tab_fade_ms": "Переход между вкладками", + "prefs.theme_option_tab_fade_ms_help": "Плавно менять цвета панелей и видового экрана при переключении вкладок. Ноль переключает мгновенно.", + "prefs.theme_options_badge": "Параметры", + "prefs.theme_options_more": "Ещё · {count}", + "prefs.theme_options_reset": "Сбросить", + "prefs.theme_options_unavailable": "Недоступно на этом устройстве", "prefs.theme_paste": "Вставить тему", "prefs.theme_paste_none": "В буфере обмена нет темы SolidCraft", "prefs.timeline_half_hour": "−30 мин", @@ -2017,13 +2440,23 @@ "prefs.under_cursor": "Под курсором", "prefs.units_precision": "Единицы и точность", "prefs.updates": "Обновления", + "prefs.value_boxes_in_view": "Показывать значения рядом с манипуляторами на виде", + "prefs.value_boxes_in_view_tip": "Значение команды (Расстояние, Радиус…) в рамке рядом с её манипулятором, поверх модели. Выкл.: вы вводите его в окне команды, которое получает клавиатуру после выбора, и ничто не закрывает модель.", "prefs.view": "Поведение вида", "prefs.view_confirm_corner": "OK и Отмена в углу вида", "prefs.view_confirm_corner_note": "Пока открыт диалог или эскиз, галочка и крестик в правом верхнем углу вида делают то же, что OK и Отмена в диалоге, либо завершают и отменяют эскиз. Навигатор видов сдвигается вниз под ними.", "prefs.viewport": "Видовой экран", + "prefs.viewport_analysis_status": "Показывать состояние анализа над видовым экраном", + "prefs.viewport_analysis_status_help": "Показывает активные анализы над видовым экраном, открывает их легенды из каждого элемента, а клавиша Esc выключает самый новый анализ. Выключите, чтобы вернуть легенды в углах и прежнее поведение Esc.", "prefs.viewport_background": "Фон", "prefs.viewport_background_colour": "Цвет", "prefs.viewport_background_theme": "Градиент темы", + "prefs.viewport_section_status": "Показывать состояние сечения на видовом экране", + "prefs.viewport_section_status_help": "Показывает настройку сечения на видовом экране. Esc и активная кнопка ленты отключают её. Выключите, чтобы сохранить прежние элементы управления сечением.", + "prefs.viewport_status_details": "Интерактивные сведения о видовом экране", + "prefs.viewport_status_details_help": "Редактируйте настройки активных анализов и сечения в стандартных карточках сведений. Выключите, чтобы вернуть клавиши анализа только для чтения и диалог «Сечение».", + "prefs.viewport_status_summary": "Сворачивать элементы состояния видового экрана", + "prefs.viewport_status_summary_help": "Сворачивать три и более элемента состояния видового экрана в один сводный значок. Выключите, чтобы показывать все элементы в полной строке.", "prefs.wheel": "Колесо", "prefs.wheel_trackpad": "Колесо и тачпад", "prefs.workspace": "Рабочее пространство", @@ -2033,6 +2466,10 @@ "properties.title": "Свойства: {name}", "recovery.days_ago": "{count} дн. назад", "recovery.detail": "{file} · операций: {features} · автосохранение {when}", + "recovery.discard_all": "Отбросить все", + "recovery.discard_all_detail": "Это действие нельзя отменить.", + "recovery.discard_all_title": "Отбросить автосохранения ({count})?", + "recovery.discard_all_title_one": "Отбросить 1 автосохранение?", "recovery.hours_ago": "{count} ч назад", "recovery.just_now": "только что", "recovery.min_ago": "{count} мин назад", @@ -2148,6 +2585,10 @@ "render.base_color": "Базовый цвет · sRGB", "render.base_metallic": "Металличность", "render.base_opaque_only": "Этот редактор сохраняет семантику непрозрачного тела. Для оптического пропускания света используйте отдельные элементы управления стеклом.", + "render.batch_all_shots": "Все кадры ({count})", + "render.batch_empty": "Сохраните кадр, прежде чем рендерить все кадры.", + "render.batch_limit": "Рендер всех кадров ограничен 32 кадрами.", + "render.batch_status": "Выполняется: {running} · ожидает: {waiting}", "render.bloom_enable": "Показывать свечение", "render.bloom_help": "Творческое свечение только на выводе от положительных линейных ярких участков, размытое тремя нормированными блочными проходами. Радиус задан в пикселях вывода. Добавляется в линейном свете дисплея до sRGB; это не эффект объектива, не объёмный эффект и не улучшение сходимости. Необработанный EXR не меняется.", "render.bloom_opaque": "Свечение требует непрозрачного вывода. Прозрачный PNG отклоняется, а не молча сводится к непрозрачному изображению.", @@ -2255,6 +2696,13 @@ "render.choose_look": "Сначала выберите внешний вид в разделе «Внешние виды»", "render.chromatic_offset": "Хроматическое смещение краёв", "render.clear_stage": "Удалить сохранённую площадку", + "render.compare_divider": "Разделитель сравнения", + "render.compare_live": "Интерактивный", + "render.compare_live_preview": "Интерактивный просмотр", + "render.compare_render": "Рендер {number}", + "render.compare_side": "Рендер {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} с · {renderer} · зафиксировано в редакции {revision}", + "render.compare_swap": "Поменять местами", "render.copy_request": "Копировать JSON", "render.cpu_aa_help": "Пространственные сэмплы: чем их больше, тем лучше края и тем дольше рендер.", "render.cpu_area_add": "Добавить прямоугольный источник света CPU", @@ -2875,6 +3323,8 @@ "render.output_ratio_refused": "Связанный размер превышает предел для этого метода. Прежний размер сохранён; разблокируйте соотношение или укажите меньшее значение.", "render.output_run_check": "Выполнить проверку", "render.output_size_limit": "{method}: до {dimension} px по стороне и {pixels} пикселей. Наибольший подходящий размер: {width} × {height}.", + "render.output_size_method_profile": "Чтобы отрендерить {width} × {height}, выберите {method} с профилем ресурсов CPU {profile} или меньший размер.", + "render.output_size_profile": "Чтобы отрендерить {width} × {height}, выберите профиль ресурсов CPU {profile} или меньший размер.", "render.output_swap_orientation": "Поменять местами ширину и высоту", "render.output_tools_inspector": "Измените размер и формат в инспекторе «Вывод».", "render.page_aging": "Старение и загрязнение", @@ -2971,6 +3421,10 @@ "render.result_retained": "Показано последнее готовое изображение; новый рендер его пока не заменил.", "render.result_sequence": "Контрольная точка", "render.result_title": "Результат рендера", + "render.results_choose": "Сохранённые результаты", + "render.results_label": "Рендер {number} · {shot} · {seconds} с", + "render.results_stale_label": "{result} [устарел]", + "render.results_unnamed": "Изображение", "render.return_design": "Вернуться к проектированию", "render.review_stale": "Этот обзор устарел. Повторите определение и проверку перед применением.", "render.ribbon_aging": "Старение", @@ -3075,6 +3529,7 @@ "render.size_4k_uhd": "4K UHD", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · требуется {profile}", "render.size_presets": "Пресеты размера", "render.size_presets_pending": "Появится в редакторе «Вывод»", "render.sky_ground": "Земля · линейный RGB", @@ -3356,6 +3811,24 @@ "sheet.flange_type_contour": "Контурный", "sheet.flange_type_edge": "Краевой", "sheet.no_body": "нет тела листового металла: создайте его командой Фланец > Базовый или преобразуйте пластину в листовой металл командой «Преобразовать в листовой металл» (выберите её большую плоскую грань)", + "sheet.personal_rules.confirm_delete": "Подтвердить удаление", + "sheet.personal_rules.delete": "Удалить", + "sheet.personal_rules.delete_prompt": "Удалить это личное правило? Правила, уже применённые в дизайнах, не меняются.", + "sheet.personal_rules.full": "В личной библиотеке уже 64 правила.", + "sheet.personal_rules.invalid_name": "Введите короткое имя без переводов строк и управляющих символов.", + "sheet.personal_rules.invalid_values": "Заполните значения правила: каждое должно вычисляться в этом дизайне, толщина должна быть положительной, а коэффициент K — от 0 до 1.", + "sheet.personal_rules.missing": "Выбранное личное правило больше недоступно.", + "sheet.personal_rules.name": "Имя правила", + "sheet.personal_rules.name_exists": "Личное правило с таким именем уже существует. Используйте другое имя.", + "sheet.personal_rules.name_hint": "Уникальное имя", + "sheet.personal_rules.overwrite": "Сохранить изменения в выбранном личном правиле", + "sheet.personal_rules.rename": "Переименовать", + "sheet.personal_rules.rule": "Личное правило", + "sheet.personal_rules.save": "Сохранить как новое", + "sheet.personal_rules.scope": "Сохраняется в вашем профиле для всех дизайнов.", + "sheet.personal_rules.select": "Выберите правило", + "sheet.personal_rules.title": "Личные правила", + "sheet.personal_rules.unsupported": "В этом правиле есть значения, которые эта версия не может использовать.", "shortcut.json_error": "параметры должны быть в формате JSON: {error}", "shortcut.no_command": "команда `{id}` не найдена; текст перед JSON должен быть ID команды", "shortcut.pin": "Закрепить вверху поля S", @@ -3392,8 +3865,10 @@ "sketch_text.align_right": "По правому краю", "sketch_text.bold": "Полужирный", "sketch_text.builtin_font": "{family} (встроенный)", + "sketch_text.formula": "Начните с =, чтобы составить слова из параметров: ='W' + number(Width)", "sketch_text.italic": "Курсив", "sketch_text.loading_fonts": "Поиск установленных шрифтов…", + "sketch_text.no_bold": "У встроенного шрифта нет полужирного начертания: выберите установленный шрифт", "sketch_text.on_path": "Текст следует по траектории: кривая задаёт его положение", "sketch_text.path_clear": "Снять текст с кривой", "sketch_text.path_hint": "Кривая эскиза, вдоль которой идёт текст: щёлкните здесь, затем по кривой", @@ -3425,10 +3900,7 @@ "the two origins are on the same component": "обе точки сопряжения находятся на одном компоненте", "thread.automatic_size": "Автоматический размер", "thread.designation": "Обозначение", - "thread.direction": "Направление резьбы", "thread.iso_metric": "Метрическая ISO", - "thread.left_hand": "Левая", - "thread.right_hand": "Правая", "thread.select_size": "Выберите размер", "timeline.delete_after_marker_one": "Удалить 1 операцию после маркера истории", "timeline.delete_after_marker_other": "Удалить операции после маркера истории: {count}", @@ -3445,8 +3917,10 @@ "timeline.move_to_group": "Переместить операции в папку", "timeline.rename_group": "Переименовать папку операций", "timeline.reorder_many": "Изменить порядок операций", + "timeline.suppress_features": "Подавить операции", "timeline.suppress_folders_tip": "Подавить или снять подавление со всех операций в папках и вложенных папках", "timeline.ungroup": "Убрать папки операций", + "timeline.unsuppress_features": "Снять подавление с операций", "to the face": "до грани", "to the next face": "до следующей грани", "toolbar.customize_note": "Вкладка {tab}. Отметьте команду, чтобы добавить её кнопку на панель инструментов. Можно также перетащить строку из выпадающего меню панели на панель инструментов, перетащить кнопку за пределы панели для удаления или использовать значок закрепления в строке выпадающего меню.", @@ -3530,6 +4004,8 @@ "ui.3d_mouse_section": "3D-мышь", "ui.3d_mouse_show_in_view": "Показывать 3D-мышь в 3D-виде", "ui.3d_mouse_show_in_view_tip": "Изображение вашей 3D-мыши в левом нижнем углу, которое двигается вместе с ней.", + "ui.3d_mouse_sketch_orbit": "Вращать эскизы 3D-мышью", + "ui.3d_mouse_sketch_orbit_tip": "3D-мышь вращает вид и при открытом эскизе, если смотреть на него прямо, как это умеет обычная мышь. Выкл.: она панорамирует и масштабирует эскиз, пока вы не наклоните вид.", "ui.3d_mouse_skip": "Моё устройство так не умеет", "ui.3d_mouse_skip_tip": "Пропускает это движение в обе стороны; калибровка его не учитывает.", "ui.3d_mouse_speed": "Скорость 3D-мыши", @@ -3558,6 +4034,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Поверните колпачок против часовой стрелки, удержите и отпустите.", "ui.3d_mouse_switch_cap": "Калибровать как возврат в центр", "ui.3d_mouse_switch_trackball": "Калибровать как трекбол", + "ui.3d_mouse_use_direct": "Использовать прямой драйвер", + "ui.3d_mouse_use_direct_tip": "Читать 3D-мышь напрямую (hidraw), а не через spacenavd.", "ui.3d_mouse_view_axis": "Ось вида", "ui.3d_mouse_view_off": "Выкл.", "ui.3d_mouse_view_off_tip": "Профиль драйвера 3D-мыши отключает эту ось, поэтому её движение не двигает вид. Если выбрать здесь движение другой оси, они поменяются местами, и это движение перестанет двигать вид.", @@ -3596,6 +4074,8 @@ "ui.agent_chat_auth_terminal": "Выполните это в терминале, затем снова нажмите «Подключить»:", "ui.agent_chat_auth_title": "Вход в агент", "ui.agent_chat_cancel": "Отмена", + "ui.agent_chat_cancel_timeout": "Агент не ответил на «Остановить» и был отключён. Подключитесь снова, чтобы продолжить.", + "ui.agent_chat_cannot_start": "Установлен, но не запускается: {error}", "ui.agent_chat_changes": "Изменений: {n}, один шаг отмены", "ui.agent_chat_changes_n": "Изменений: {n}", "ui.agent_chat_changes_of": "Изменений: {n}/{limit}", @@ -3604,11 +4084,13 @@ "ui.agent_chat_command": "Команда агента", "ui.agent_chat_connect": "Подключить", "ui.agent_chat_copy": "Копировать", + "ui.agent_chat_copy_message": "Копировать сообщение", "ui.agent_chat_ctx_bodies": "Тела", "ui.agent_chat_ctx_elements": "Элементы", "ui.agent_chat_ctx_features": "Операции", "ui.agent_chat_ctx_more": "+ещё {n}", "ui.agent_chat_ctx_other": "Другое", + "ui.agent_chat_custom_heading": "Своя модель", "ui.agent_chat_custom_hint": "Любая программа, поддерживающая Agent Client Protocol через stdin и stdout. Оболочка для запуска не используется.", "ui.agent_chat_denied": "Отклонено", "ui.agent_chat_deny": "Отклонить", @@ -3652,8 +4134,16 @@ "ui.agent_chat_mode_all": "Всё", "ui.agent_chat_mode_ask": "Спросить", "ui.agent_chat_mode_edits": "Правки", + "ui.agent_chat_model_custom": "Использовать свою модель: {model}", "ui.agent_chat_model_no_tools": "{model} не может использовать инструменты SolidCraft, поэтому может только вести чат. Выберите модель с поддержкой инструментов.", + "ui.agent_chat_model_rejected": "Агент не принял {model}: {error}", + "ui.agent_chat_model_search": "Поиск моделей…", "ui.agent_chat_model_tip": "Модель, которую использует агент. Ваш выбор запоминается для этого агента.", + "ui.agent_chat_models_failed": "Не удалось получить список моделей: {error}", + "ui.agent_chat_models_heading": "Доступные модели", + "ui.agent_chat_models_listing": "Получение списка моделей…", + "ui.agent_chat_models_none": "Конечная точка не вернула ни одной модели", + "ui.agent_chat_models_not_a_list": "В ответе нет списка моделей", "ui.agent_chat_new": "Новый чат", "ui.agent_chat_new_confirm": "Начать новый чат? Текущий будет очищен.", "ui.agent_chat_next_picture": "Следующее изображение", @@ -3688,9 +4178,12 @@ "ui.agent_chat_queued_stopped": "В очереди (остановлено, не отправлено)", "ui.agent_chat_refresh": "Обновить", "ui.agent_chat_refused": "Агенту не разрешено: {reason}", + "ui.agent_chat_reinstall": "{agent} установлен ({program}), но не запустился, когда SolidCraft его проверил: {error}\nВозможно, установка неполная или сделана для другого типа компьютера. Установите его заново командой `{install}`, убедитесь, что в терминале он выводит свою версию, затем нажмите «Обновить».", "ui.agent_chat_remove": "Убрать из очереди", "ui.agent_chat_remove_file": "Убрать из этого сообщения", "ui.agent_chat_remove_imported": "Убрать из этого сообщения; деталь останется в дизайне (Отмена удалит её)", + "ui.agent_chat_reply_cut_off": "Ответ достиг предела длины, не закончившись, поэтому может быть неполным. Попросите агента продолжить или дать более короткий ответ.", + "ui.agent_chat_reply_declined": "Модель отказалась отвечать на это сообщение.", "ui.agent_chat_retry": "Повторить", "ui.agent_chat_right": "Справа", "ui.agent_chat_save": "Сохранить", @@ -3749,12 +4242,17 @@ "ui.ai_copy_suffix": "копия", "ui.ai_custom_url": "Свой URL", "ui.ai_default": "По умолчанию", + "ui.ai_edit": "Изменить", + "ui.ai_edit_agent_title": "Изменить агент", + "ui.ai_edit_gone": "Этот агент удалён, сохранять нечего.", + "ui.ai_edit_tip": "Измените имя, команду или конечную точку этого агента. Сохранённый ключ остаётся скрытым.", "ui.ai_http_busy": "конечная точка занята или превысила лимит; повторите позже", "ui.ai_http_key": "конечная точка отклонила ключ: проверьте его в Настройки > ИИ", "ui.ai_http_not_found": "нет такой конечной точки или модели: проверьте базовый URL и имя модели", "ui.ai_http_too_large": "разговор слишком велик для этой конечной точки; начните новый чат", "ui.ai_key": "Ключ API", "ui.ai_key_hint": "необязательно; хранится в системной связке ключей", + "ui.ai_key_keep_hint": "оставьте пустым, чтобы сохранить имеющийся ключ", "ui.ai_key_needs_https": "Ключ отправляется только по HTTPS или на этот компьютер.", "ui.ai_key_note": "Хранится в системной связке ключей, а не в настройках SolidCraft. Для локального сервера оставьте пустым.", "ui.ai_keychain_error": "Системная связка ключей отказала: {error}", @@ -3781,11 +4279,15 @@ "ui.ai_permissions": "Разрешения", "ui.ai_preset": "Пресет", "ui.ai_protocol": "Протокол", + "ui.ai_reasoning_effort": "Уровень рассуждений", + "ui.ai_reasoning_effort_field_hint": "пусто = значение поставщика по умолчанию", + "ui.ai_reasoning_effort_hint": "Необязательно. Отправляется на конечную точку как `reasoning_effort`; допустимые значения зависят от поставщика (например, `low`, `high` или `max`). Заданное здесь значение SolidCraft никогда не заменяет. Оставьте поле пустым, чтобы ничего не отправлять и сохранить значение поставщика по умолчанию.", "ui.ai_remove": "Удалить", "ui.ai_request_timed_out": "Модель отвечала дольше {seconds} с. Тайм-аут запроса для этой конечной точки можно увеличить в Настройки › Ассистент.", "ui.ai_request_timeout": "Тайм-аут запроса", "ui.ai_request_timeout_hint": "Сколько может длиться один запрос к модели на этой конечной точке: от 30 с до часа. Увеличьте для медленной локальной модели.", "ui.ai_reset": "Сбросить", + "ui.ai_save": "Сохранить", "ui.ai_settings": "Настройки ИИ…", "ui.ai_show_features": "Показывать функции ИИ", "ui.ai_show_features_note": "Чат с агентом: панель, в которой уже используемый вами кодирующий агент или выбранная конечная точка модели работает с открытым дизайном. Выключено: нет кнопки ИИ, сочетания клавиш, пункта меню и панели, ничего не ищется и не запускается.", @@ -3864,6 +4366,8 @@ "ui.cancel": "Отмена", "ui.canvases": "Подложки", "ui.center": "Центр", + "ui.center_arc_follows_cursor": "Дуга из центра следует направлению курсора", + "ui.center_arc_follows_cursor_tip": "Дуга из центра идёт по часовой стрелке или против неё — в ту сторону, в которую курсор обходит её центр. Выкл.: всегда против часовой стрелки от начальной точки.", "ui.centerline": "Осевая линия", "ui.chain": "Цепочка", "ui.chamfer": "Фаска", @@ -3872,6 +4376,7 @@ "ui.circle": "Окружность", "ui.circular_pattern": "Круговой массив", "ui.clear": "Очистить", + "ui.clear_print_face": "Сбросить грань печати", "ui.clear_recent": "Очистить недавние", "ui.clear_the_selection": "Снять выделение", "ui.click_selects_whole_bodies": "Щелчок выделяет тела целиком", @@ -3912,14 +4417,21 @@ "ui.construction.contact_hint": "Касательная: выберите окружность/дугу или открытый сплайн/конику, затем точку касания (для сплайна/коники — конец)", "ui.construction.external_hint": "Касательная: выберите окружность или дугу, внешнюю точку, затем нужное решение", "ui.construction.free_hint": "Вспомогательная прямая: укажите две точки; правая кнопка — начать заново", + "ui.construction.normal_needs_length": "Бесконечная прямая всегда вспомогательная: введите длину, чтобы нарисовать обычную линию", "ui.construction.point_hint": "Вспомогательная прямая: укажите точку прохождения", "ui.construction.reference_hint": "Выберите прямую, затем точку; правая кнопка — сменить исходную прямую", "ui.construction.ribbon_label": "Всп. линии", + "ui.construction.side_hint": "Вспомогательная прямая: укажите сторону, в которую идёт прямая; правая кнопка — начать заново", "ui.context_menu": "Контекстное меню", + "ui.continuity_crease": "Излом", + "ui.continuity_curvature": "Кривизна", + "ui.continuity_curvature_change": "Изменение кривизны", "ui.continuity_g0": "G0, излом", "ui.continuity_g1": "G1, касательная", "ui.continuity_g2": "G2, кривизна", "ui.continuity_gap": "Зазор", + "ui.continuity_position": "Положение", + "ui.continuity_tangent": "Касание", "ui.copy": "Копировать", "ui.corner": "Угол", "ui.corners": "Углы", @@ -3942,6 +4454,7 @@ "ui.dark": "Тёмная", "ui.default_modelling_orientation": "Ориентация моделирования по умолчанию", "ui.delete": "Удалить", + "ui.delete_select_first": "Сначала выберите, что удалить: операции, тела, компоненты или геометрию эскиза", "ui.depth": "Глубина", "ui.design": "Дизайн", "ui.design_properties.author": "Автор", @@ -3956,6 +4469,40 @@ "ui.design_properties.project": "Проект", "ui.design_properties.revision": "Редакция", "ui.design_saved": "Сохранено: {path}", + "ui.details_access_caption": "Грани показывают, может ли инструмент достать до них с выбранного направления.", + "ui.details_angle": "Угол", + "ui.details_continuity_caption": "Правка выбранного шва. Остальные швы сохраняют свои настройки.", + "ui.details_continuity_stale": "Прежняя геометрия: повторите анализ, чтобы править или кадрировать этот шов.", + "ui.details_copy_list": "Копировать список", + "ui.details_curvature": "Допуск кривизны", + "ui.details_curvature_caption": "Грани окрашены по локальному радиусу кривизны.", + "ui.details_direction": "Направление инструмента", + "ui.details_draft_caption": "Грани окрашены по углу к направлению вытягивания.", + "ui.details_edit_seam": "Править шов", + "ui.details_fixture": "Образец компонента — только пример данных", + "ui.details_fixture_caption": "Образец компонента с иллюстративными значениями; это не результат по модели.", + "ui.details_fixture_problem": "Пример находки с проблемой", + "ui.details_fixture_readout": "Пример измеренного значения", + "ui.details_flip": "Перевернуть", + "ui.details_gap": "Зазор", + "ui.details_hatch": "Штриховать срезанные грани", + "ui.details_jump": "Скачок кривизны", + "ui.details_key": "Легенда", + "ui.details_offset": "Смещение", + "ui.details_plane": "Плоскость", + "ui.details_pull": "Направление вытягивания", + "ui.details_radius": "Радиус", + "ui.details_readout": "Показание", + "ui.details_samples": "Точки выборки", + "ui.details_seam": "{body} · Ребро {edge}", + "ui.details_settings": "Настройки", + "ui.details_sharp_gap": "Излом или зазор", + "ui.details_show_all": "Показать все {count}", + "ui.details_smooth": "Гладко", + "ui.details_stripes": "Полосы", + "ui.details_target": "Кадрировать геометрию", + "ui.details_worst_seams": "Худшие швы", + "ui.details_zebra_caption": "Отражённые полосы показывают, насколько плавно стыкуются грани.", "ui.diameter": "Диаметр", "ui.dimension": "Размер", "ui.direct_interaction": "Прямое взаимодействие", @@ -4000,6 +4547,7 @@ "ui.edit_in_place_saved_elsewhere": "Деталь сохранена в другой файл; сборка по-прежнему связана с {name}", "ui.edit_in_place_wait": "Дождитесь завершения того, что выполняется в дизайне", "ui.edit_section_analysis": "Изменить анализ сечения", + "ui.edit_sketch_empty": "Нет эскизов для редактирования", "ui.ellipse": "Эллипс", "ui.emboss_wrap_note": "Профили из ортогональных линий, касательные к одному поддерживаемому цилиндру, оборачиваются автоматически. Выберите стенку, чтобы задать цель.", "ui.end_radius": "Конечный радиус", @@ -4010,12 +4558,15 @@ "ui.equation_explicit": "Явная", "ui.equation_form": "Форма", "ui.equation_note": "Переменная — обычное число: sin(t) принимает её в радианах. Результат без единицы измерения задаётся в единицах дизайна.", + "ui.equation_note_range": "Переменная — длина, как и её диапазон: сочетайте её с параметрами длины, а для sin() делите её на длину. Результат без единицы измерения задаётся в единицах дизайна.", "ui.equation_parametric": "Параметрическая", + "ui.equation_variable_unit": "Переменная имеет единицу измерения диапазона", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Эквивалентный радиус", "ui.expand": "Развернуть", + "ui.explode_needs_two_components": "«Разобранный вид» раздвигает компоненты, поэтому в дизайне их должно быть два или больше («Новый компонент», «Вставить дизайн» или «Создать компоненты из тел»)", "ui.exportDxf": "Экспорт DXF…", "ui.export_ellipsis_keymap": "Экспорт…", "ui.export_keymap_tip": "Сочетания клавиш, избранное панели S и панель инструментов — в файл", @@ -4141,6 +4692,7 @@ "ui.hideOrigin": "Скрыть начало координат", "ui.hidePlanes": "Скрыть плоскости", "ui.hideProfile": "Скрыть профиль", + "ui.hide_component_history": "Скрыть его историю", "ui.hide_origin_by_default": "Скрывать начало координат по умолчанию", "ui.hide_origin_note": "Новые дизайны создаются со скрытой папкой «Начало координат». Как только вы покажете или скроете её, дизайн запоминает собственную настройку.", "ui.history_back": "На один шаг назад", @@ -4148,6 +4700,7 @@ "ui.history_edge_hint": "двойной щелчок по границе", "ui.history_first": "Перейти в начало", "ui.history_forward": "На один шаг вперёд", + "ui.history_hide_hidden": "Скрыть скрытые компоненты", "ui.history_hide_names": "Скрыть имена", "ui.history_last": "Перейти в конец", "ui.history_marker_tip": "Маркер истории: перетащите, чтобы откатить модель; новые операции добавляются сюда", @@ -4157,10 +4710,12 @@ "ui.history_play_button_show": "Показать кнопку воспроизведения", "ui.history_play_finish_action": "Завершите текущее действие перед воспроизведением истории", "ui.history_play_roll_back": "Переместите маркер истории назад перед воспроизведением", + "ui.history_show_hidden": "Показать скрытые компоненты", "ui.history_show_names": "Показать имена", "ui.history_sketch_listed_under": "Показан под операцией {feature}", "ui.history_title": "История", "ui.history_toggle_names": "Показать или скрыть имена операций", + "ui.history_waits_for_editor": "«Отменить», «Повторить» и «История» ждут, пока откроется редактор операции", "ui.hole": "Отверстие", "ui.hole_tap_type": "Тип резьбы отверстия", "ui.hole_type": "Тип отверстия", @@ -4176,6 +4731,7 @@ "ui.insert_design.saved_file": "В {name} есть несохранённые изменения, поэтому вставлен его сохранённый файл. Сохраните его, затем выполните «Обновить связи», чтобы подтянуть изменения.", "ui.insert_design.unsaved": "Несохранённые изменения", "ui.inspect": "Инспекция", + "ui.instances": "Экземпляры", "ui.intersect": "Пересечение", "ui.isolate": "Изолировать", "ui.join": "Объединить", @@ -4184,12 +4740,14 @@ "ui.joints": "Сопряжения", "ui.keyboard_shortcuts": "Сочетания клавиш", "ui.language": "Язык", + "ui.lasso_select": "Лассо (перетащите произвольный контур: выделяет всё, что целиком внутри)", "ui.layout_compact": "Компактная", "ui.layout_floating": "Плавающая", "ui.length": "Длина", "ui.length_decimals": "Знаков после запятой (длины)", "ui.light": "Светлая", "ui.line": "Линия", + "ui.line_arc_hint": "Касательная дуга: щёлкните в конце дуги. Снова задержитесь на последней точке, чтобы вернуться к линиям; щёлкните правой кнопкой или нажмите Esc, чтобы завершить", "ui.link_copies": "Связать одинаковые копии", "ui.link_copies_keep": "Оставить", "ui.link_copies_link": "Связать", @@ -4278,6 +4836,7 @@ "ui.part_size_shared": "Перестраивает деталь, заменяя все добавленные операции. Обновляются все вхождения этого компонента.", "ui.paste": "Вставить", "ui.path": "Траектория", + "ui.pattern_object_type_tip": "Тела: твёрдые формы, выбираемые в виде или в браузере; каждое копируется целиком.\nОперации: шаги Истории, например выдавливание или отверстие, выбираемые в Истории или на созданной ими грани; шаг повторяется.\nЭскиз — ни то, ни другое: повторите его кривые собственным инструментом «Массив» или «Зеркало» в эскизе либо сначала выдавите его.", "ui.pattern_on_path": "Массив по траектории", "ui.perforate_margin_default": "от диаметра", "ui.perforate_pitch": "Шаг", @@ -4304,11 +4863,21 @@ "ui.plugins_skipped": "Не удалось прочитать папок: {count}.", "ui.plugins_version": "{version}", "ui.point": "Точка", + "ui.point_cloud_add_filter": "Добавить фильтр…", + "ui.point_cloud_filter_by": "Фильтровать по", + "ui.point_cloud_legend_filter": "Показано и скрыто в легенде выше", + "ui.point_cloud_pause": "Пауза", + "ui.point_cloud_play": "Воспроизвести", "ui.point_under_the_cursor": "Точка под курсором", "ui.points": "Точки", "ui.polygon": "Многоугольник", "ui.preferences": "Настройки", "ui.press_a_key": "нажмите клавишу…", + "ui.print_face_body_not_sent": "Тело этой грани не отправляется: сначала добавьте его в Тела", + "ui.print_face_cleared": "{body}: грань печати сброшена", + "ui.print_face_input": "Грань печати", + "ui.print_face_pick": "Выберите плоскую грань твёрдого тела, чтобы сделать её гранью печати", + "ui.print_face_set": "{body}: грань печати задана; «Отправить в слайсер» кладёт тело на неё", "ui.profile": "Профиль", "ui.profile_plane": "Плоскость профиля", "ui.profiles": "Профили", @@ -4324,6 +4893,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Измерение…", + "ui.properties.measuring_bodies": "Измерение… {done} из {total} тел", "ui.properties.measuring_failed": "Измерение остановлено, не закончив работу.", "ui.properties.principal_axis": "Главная ось {number}", "ui.properties.principal_moments": "Главные моменты", @@ -4370,6 +4940,7 @@ "ui.revolve": "Вращение", "ui.ribbon_exit": "Выход", "ui.ribbon_labels": "Показывать текст под значками ленты", + "ui.ribbon_menus_skip_pinned": "Не включать закреплённые команды в выпадающие меню", "ui.ribbon_pin_footer": "Закреплённые команды отображаются на ленте. Наведите курсор на строку, чтобы закрепить или открепить её.", "ui.ribbon_workspace": "Рабочая область", "ui.right": "Справа", @@ -4388,6 +4959,7 @@ "ui.selectOther": "Выбрать другое…", "ui.selectTangentChain": "Выбрать касательную цепочку", "ui.select_all": "Выделить всё", + "ui.select_components_by_face": "Выбор компонентов (грань выбирает свой компонент)", "ui.selection": "Выделение", "ui.selection_modifiers": "Модификаторы выбора", "ui.selection_shift_add_only": "Shift+щелчок добавляет без удаления", @@ -4413,6 +4985,7 @@ "ui.showDimension": "Показать размер", "ui.showOrigin": "Показать начало координат", "ui.showPlanes": "Показать плоскости", + "ui.show_component_history": "Показать его историю", "ui.show_constraints": "Ограничения", "ui.show_construction_geometries": "Вспомогательная геометрия", "ui.show_dimensions": "Размеры", @@ -4429,6 +5002,11 @@ "ui.sketch_intersect_selection_filter": "Фильтр выделения", "ui.sketch_modifiers": "Модификаторы эскиза", "ui.sketch_project_geometry": "Геометрия", + "ui.sketch_report.all_constrained": "Всё полностью определено.", + "ui.sketch_report.dof": "Степени свободы", + "ui.sketch_report.loose": "Определён не полностью", + "ui.sketch_report.status": "Состояние", + "ui.sketch_report.title": "Отчёт об эскизе", "ui.sketch_scale": "Масштаб эскиза", "ui.sketches": "Эскизы", "ui.slice": "Срез", @@ -4524,19 +5102,31 @@ "ui.view_angles": "Углы вида", "ui.view_angles_convention": "Градусы вокруг вертикальной оси. Рыскание 0° — вид спереди, 90° — слева, −90° — справа, 180° — сзади; тангаж 90° — вид сверху; положительный крен поворачивает модель по часовой стрелке.", "ui.view_angles_help": "Показывает тангаж, рыскание и крен вида в градусах, а также его проекцию под гизмо ориентации. Щёлкните по показанию, чтобы ввести точные углы.", + "ui.view_angles_lock": "Заблокировать {axis}", "ui.view_angles_ortho": "Орто", "ui.view_angles_persp": "Персп.", "ui.view_angles_pitch": "Тангаж", "ui.view_angles_readout": "Тангаж {pitch} · Рыскание {yaw} · Крен {roll}", "ui.view_angles_roll": "Крен", + "ui.view_angles_unlock": "Разблокировать {axis}", "ui.view_angles_yaw": "Рыскание", + "ui.view_angles_zero": "Установить {axis} в 0°", "ui.view_centre": "Центр вида", "ui.viewport_status_clear": "Выключить {name}", "ui.viewport_status_clear_hint": "Выключить {name} · Esc", + "ui.viewport_status_edges": "Рёбер: {count}", + "ui.viewport_status_from": "со стороны {direction}", "ui.viewport_status_key": "Показать легенду для {name}", "ui.viewport_status_minimum_radius": "Минимальный радиус", "ui.viewport_status_pairs": "Пар: {count}", + "ui.viewport_status_section_hatch": "{setting} · штриховка", + "ui.viewport_status_section_plane": "Текущая плоскость", + "ui.viewport_status_section_tilted": "наклонено · {offset}", "ui.viewport_status_stripes": "Полос: {count}", + "ui.viewport_status_summary_clear": "Выключить всё", + "ui.viewport_status_summary_heading": "На этом виде", + "ui.viewport_status_summary_label": "{name} и ещё элементов: {count}", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Следовать теме", "ui.visual_shaded_hidden_edges": "Заполненный с невидимыми рёбрами", "ui.visual_shaded_with_edges": "Заполненный с рёбрами", @@ -4573,10 +5163,12 @@ "update.button": "Обновить", "update.button_version": "Обновить до {version}", "update.check_automatically": "Проверять обновления автоматически", + "update.check_for_updates": "Проверить обновления", "update.check_now": "Проверить сейчас", + "update.check_unavailable": "Проверка обновлений недоступна для этой установки.", "update.checking": "Проверка…", "update.copy": "Копировать", - "update.dmg_opened": "Образ диска открыт и проверен: перетащите SolidCraft в «Программы», заменив старую копию, затем перезапустите SolidCraft.", + "update.dmg_opened": "Образ диска открыт и проверен: завершите SolidCraft, перетащите новый SolidCraft в «Программы», заменив старую копию, затем снова откройте SolidCraft.", "update.download": "Скачать", "update.download_open": "Скачать и открыть", "update.downloading": "Загрузка и проверка… {done} из {total} МБ", @@ -4587,11 +5179,13 @@ "update.installed": "SolidCraft {version} установлен. Перезапустите, чтобы использовать его.", "update.installer_started": "Установщик запустится после закрытия SolidCraft.", "update.later": "Напомнить позже", + "update.managed": "Доступно обновление: обновите SolidCraft в {manager}", "update.no_notes": "У этого выпуска нет примечаний.", "update.package_hint": "Эта копия установлена из {kind}. Скачайте новый пакет, затем установите его командой:", "update.prefs_dev": "Это сборка для разработки ({version}): она не проверяет обновления.", "update.prefs_flatpak": "Эту копию ({version}) обновляет Flatpak: выполните {command} или воспользуйтесь центром приложений. SolidCraft не проверяет обновления.", "update.prefs_label": "Обновления", + "update.prefs_managed": "Это SolidCraft {version}, которым управляет {manager}. Проверка запрашивает у GitHub последний релиз и больше ничего не отправляет; обновляйте SolidCraft в {manager}.", "update.prefs_note": "Это SolidCraft {version} ({kind}). При проверке у GitHub запрашивается последний выпуск, больше ничего не отправляется.", "update.prefs_web": "Перезагрузите страницу, чтобы получить последнюю версию веб-приложения. Если сеть недоступна или обновление не успевает загрузиться, открывается сохранённая версия; незавершённая загрузка продолжится до следующей перезагрузки.", "update.refresh_checking": "Проверка наличия новейшего выпуска…", @@ -4618,6 +5212,7 @@ "web.open_link": "Открыть связанный дизайн?", "web.open_link_confirm": "Есть несохранённые изменения. Открыть связанный дизайн в новой вкладке?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ выбрать · Enter / Tab дополнить · Esc закрыть", + "↑ ↓ choose · Enter applies this value": "↑ ↓ выбрать · Enter — применить это значение", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ выбрать · Enter применяет введённое · Esc закрыть", "⌘Enter continues on GitHub.": "⌘Enter продолжит на GitHub." } diff --git a/assets/locales/sr.json b/assets/locales/sr.json index eaca5f9d9..fde184562 100644 --- a/assets/locales/sr.json +++ b/assets/locales/sr.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "ПРЕЛАЗНА ПОВРШ", "BOUNDARY SURFACE": "ГРАНИЧНА ПОВРШ", "BROWSER": "СТАБЛО МОДЕЛА", + "Back to the original order": "Врати на првобитни редослед", "Ball": "Кугласто", "Bar": "Шипка", "Base Center": "Центар основе", @@ -476,6 +477,7 @@ "Rectangular": "Правоугаони", "Rectangular Tube": "Правоугаона цев", "Reference face": "Референтно лице", + "Reference plane": "Референтна раван", "Relief Depth": "Дубина растерећења", "Relief Width": "Ширина растерећења", "Remove Tools": "Уклони алате", @@ -555,6 +557,7 @@ "Section": "Пресек", "Section (optional)": "Пресек (необавезно)", "Section position": "Положај пресека", + "Sections": "Пресеци", "Sections (one sketch each)": "Пресеци (по једна скица)", "Select Other": "Изабери друго", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Изабери друго: држите лево дугме мирно на моделу (или десни клик › Изабери друго…) да прикажете све испод показивача; поново кликните на исто место да изаберете следећи елемент. Двапут кликните средњим дугметом за Почетни приказ (Подешавања › Навигација).", @@ -595,6 +598,8 @@ "Snap to face and edge centres": "Привлачи на центре лица и ивица", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft не може директно да шаље извештаје. Пошаљите на GitHub; у апликацији није потребан токен.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft се затворио пре него што су ови дизајни сачувани. Може се отворити њихово последње аутоматско чување.", + "Sort A to Z": "Поређај од А до Ш", + "Sort Z to A": "Поређај од Ш до А", "Spacing 2 must be a non-zero number": "Размак 2 мора бити број различит од нуле", "Spacing must be a non-zero number": "Размак мора бити број различит од нуле", "Specialise": "Специјализуј", @@ -775,6 +780,8 @@ "at the face": "на лицу", "bom.group_children": "Подделови у реду свог дела", "browser.body_name": "Тело{number}", + "browser.calibrate_click_a": "Кликните слику да зададете тачку A или упишите њене координате.", + "browser.calibrate_click_b": "Кликните слику да зададете тачку B или упишите њене координате.", "browser.calibrate_title": "Калибриши: {name}", "browser.capture_many": "Померене компоненте без забележеног положаја: {count}.", "browser.capture_note": "Забележи задржава нови положај; Врати га враћа назад.", @@ -788,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (причвршћење изгубљено)", "browser.sketch_editing": "{name} (у измени)", "browser.sketch_name": "Скица{number}", + "browser.sketches_to_parts_already_in_part": "већ у свом делу", + "browser.sketches_to_parts_design_body": "на телу самог дизајна", + "browser.sketches_to_parts_moved": "Скице премештене у део на којем се налазе: {moved}", + "browser.sketches_to_parts_no_exact_attachment": "на лицу без тачног причвршћења", + "browser.sketches_to_parts_not_on_face": "не на лицу дела", + "browser.sketches_to_parts_part_missing": "њихов део више не постоји", + "browser.sketches_to_parts_result": "Скице премештене у део на којем се налазе: {moved}; остале на месту: {stayed} ({why})", "browser.units": "Јединице: {units}", "cam.flat": "Равно лице", "cam.follower": "Пратилац", @@ -817,6 +831,8 @@ "cmd.appearance_pick_up": "Преузми изглед", "cmd.appearance_replace": "Замени изглед", "cmd.assembly_bom": "Саставница", + "cmd.assembly_mass_properties": "Својства масе", + "cmd.body.print_face": "Површина за штампу", "cmd.body_rename": "Преименуј тело", "cmd.browser_collapse_all": "Скупи све", "cmd.browser_expand_all": "Прошири све", @@ -845,6 +861,7 @@ "cmd.component_extract": "Издвоји у датотеку", "cmd.component_finish_edit": "Заврши измену", "cmd.component_from_bodies": "Направи компоненте из тела", + "cmd.component_hide_history": "Сакриј временску траку компоненте", "cmd.component_insert_design": "Уметни дизајн", "cmd.component_links": "Списак веза", "cmd.component_list": "Списак компоненти", @@ -853,6 +870,7 @@ "cmd.component_move_bodies": "Премести тела у компоненту", "cmd.component_move_features": "Премести операције у компоненту", "cmd.component_move_sketches": "Премести скице у компоненту", + "cmd.component_move_sketches_to_parts": "Премести скице у њихове делове", "cmd.component_paste_from_design": "Налепи из другог дизајна", "cmd.component_paste_new": "Налепи као ново", "cmd.component_properties": "Физичка својства компоненте", @@ -860,6 +878,7 @@ "cmd.component_rename": "Преименуј компоненту", "cmd.component_replace_with_link": "Замени везом", "cmd.component_revert_position": "Врати положај", + "cmd.component_show_history": "Прикажи временску траку компоненте", "cmd.component_unlock": "Откључај садржај", "cmd.component_update_links": "Ажурирај везе", "cmd.config_activate": "Активирај конфигурацију", @@ -870,6 +889,7 @@ "cmd.config_rule": "Правило конфигурације", "cmd.config_rules": "Правила конфигурације", "cmd.config_table": "Прикажи табелу конфигурација", + "cmd.construct.plane.axis_point": "Раван кроз осу и тачку", "cmd.construct_axis_edge": "Оса кроз ивицу", "cmd.construct_axis_normal_to_face": "Оса окомита на лице", "cmd.construct_axis_through_cylinder": "Оса кроз цилиндар/конус/торус", @@ -918,6 +938,11 @@ "cmd.explode_show": "Прикажи растављени приказ", "cmd.expr_evaluate": "Израчунај израз", "cmd.face_delete": "Избриши лице", + "cmd.file.export_3mf": "Извези 3MF", + "cmd.file.export_obj": "Извези OBJ", + "cmd.file.export_step": "Извези STEP", + "cmd.file.export_stl": "Извези STL", + "cmd.file.export_urdf": "Извези URDF", "cmd.file_export": "Извоз", "cmd.file_insert_mesh": "Уметни мрежу", "cmd.file_insert_step": "Уметни STEP", @@ -935,6 +960,7 @@ "cmd.inspect_colored_components": "Омогући боје компоненти", "cmd.inspect_colored_components_disable": "Онемогући боје компоненти", "cmd.inspect_compare": "Упореди тела", + "cmd.inspect_compare_picture": "Упореди слику", "cmd.inspect_continuity": "Анализа континуитета", "cmd.inspect_curvature_comb": "Анализа чешља закривљености", "cmd.inspect_curvature_map": "Анализа мапе закривљености", @@ -1025,6 +1051,9 @@ "cmd.pointcloud_edit": "Измени облак тачака", "cmd.pointcloud_insert": "Уметни облак тачака", "cmd.pointcloud_list": "Облаци тачака", + "cmd.render.compare.divider": "Помери разделник поређења рендеровања", + "cmd.render.result.discard": "Одбаци резултат рендеровања", + "cmd.render.result.select": "Изабери резултат рендеровања", "cmd.render_aging_describe": "Слојевито старење површине", "cmd.render_backends": "Позадински системи рендеровања", "cmd.render_batch": "Рендеруј све кадрове", @@ -1188,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Сплајн контролних тачака (степен 5)", "cmd.sketch_spline_fit_point": "Сплајн кроз тачке", "cmd.sketch_spline_insert_point": "Додај тачку сплајна", + "cmd.sketch_spline_remove_point": "Уклони тачку сплајна", "cmd.sketch_spline_reverse": "Обрни смер сплајна", "cmd.sketch_spun_profile": "Ротирани профил", "cmd.sketch_toggle_diameter": "Пребаци полупречник / пречник", @@ -1238,9 +1268,11 @@ "cmd.timeline_rollback": "Помери ознаку враћања", "cmd.timeline_stop": "Заустави временску траку", "cmd.timeline_suppress": "Потисни операцију", + "cmd.ui.assistant": "Прикажи или сакриј Асистента", "cmd.view.render_browser": "Стабло рендеровања", "cmd.view.render_dock": "Премести панел рендеровања", "cmd.view.render_focus": "Фокусни приказ рендеровања", + "cmd.view.status_details": "Детаљи статуса у прозору приказа", "cmd.view.status_items": "Ставке статуса у прозору приказа", "cmd.view_ambient_occlusion": "Амбијентална оклузија", "cmd.view_angle_readout": "Углови приказа", @@ -1271,17 +1303,28 @@ "cmd.view_tool": "Алат за навигацију", "cmd.view_top": "Поглед одозго", "cmd.view_visual_style": "Визуелни стил", + "color.blue": "Плава", "color.copy": "Кликните да копирате вредности боје", "color.edit": "Кликните да измените боју", "color.gamma": "Приказ вредности боје у гама простору 0-255", + "color.green": "Зелена", "color.hex": "Hex", "color.hex_help": "Унесите #rrggbb или #rrggbbaa; шест цифара чува непрозирност", "color.hex_hint": "#rrggbb", "color.hue": "Нијанса", "color.linear": "Приказ вредности боје у линеарном простору 0-1", + "color.recent": "Недавне боје", + "color.recent_help": "Овде се појављују боје које изаберете у било ком пољу боје", + "color.red": "Црвена", + "color.saturation": "Засићеност (проценат)", "color.saturation_value": "Засићеност и вредност", "color.selected": "Изабрана боја", + "color.step_down": "Смањи за корак", + "color.step_up": "Повећај за корак", + "color.value": "Вредност, светлина (проценат)", "config.column_filter_empty": "Нема одговарајућих колона", + "config.rule_parameter_columns": "Приказани су само параметри који имају колону у табели. Додајте колону помоћу Додај колону (+) да бисте параметар користили овде.", + "config.rule_suppression_columns": "Приказане су само операције које имају колону Потисни у табели. Додајте колону помоћу Додај колону (+) да бисте овде могли да управљате операцијом.", "contact.components_count": "Компоненте: {count}", "contact.enabled_label": "омогућено", "coupling.gear_1": "Зупчаник 1", @@ -1327,9 +1370,14 @@ "dialog.dimension_name": "Кота: {name}", "dialog.edit_title": "ИЗМЕНИ {title}", "dialog.no_shown_body": "Нема приказаног тела за измену: прикажите једно или изаберите Ново тело", + "dialog.pattern_sketch_not_object": "Изаберите тела или операције: скица није ни једно ни друго. Поновите њене криве помоћу алата Низ или Пресликај у самој скици или је прво екструдирајте.", "dialog.select": "↖ Изабери", "dialog.selected_count": "↖ Изабрано: {count}", + "dialog.selection_constraint": "Ограничење {id}", + "dialog.selection_external_curve": "{sketch} · крива {id}", "dialog.selection_guidance": "Изаберите улаз да га промените. Кликните изабране објекте да их уклоните; Ctrl/Cmd-клик их такође укључује и искључује. Погледајте преглед, а затим притисните У реду.", + "dialog.selection_midpoint": "Средишња тачка · {id}", + "dialog.selection_profile": "{sketch} · профил {number}", "dialog.selection_step": "{step} од {total}: Изаберите {input}", "dialog.step": "Корак", "document.changed_on_disk": "{name} је промењен на диску", @@ -1384,26 +1432,244 @@ "from the rule": "из правила", "help.apache": "Apache лиценца 2.0", "help.appearance.assign": "Даје изабраним телима, лицима или компонентама боју или изглед материјала, без промене њихове тежине. Користите га да разликујете делове или прегледате завршну обраду.", + "help.assembly.bom": "Наводи делове дизајна или компоненте са њиховим бројем комада, по броју дела, и може да сачува списак као CSV или JSON. Користите је као списак делова за наручивање и монтажу.", "help.attributions": "Атрибуције (ATTRIBUTION.md)", "help.build": "Верзија {version} · commit {commit} · изграђено {date}", + "help.canvas.decal": "Поставља слику на раван лице модела, као налепницу. Користите је да на делу прикажете ознаку, логотип или одштампан узорак.", + "help.canvas.edit": "Мења платно: његов положај, величину, угао, непрозирност, пресликавање, видљивост или назив. Користите га да референтну слику поравнате са скицом коју цртате преко ње.", + "help.canvas.insert": "Поставља PNG или JPEG слику на раван или лице као провидну референцу. Користите га да у скици прецртате фотографију или цртеж, са сликом скалираном на познату величину.", + "help.component.break_link": "Одваја повезану компоненту од њене датотеке дизајна, а њена тела остају каква јесу. Користите је када део више не треба да прати измене изворне датотеке.", + "help.component.capture_position": "Задржава положаје делова које сте ручно померили, па они постају нови положаји тих делова. Користите га након превлачења делова на место које ниједан спој не држи.", + "help.component.create": "Додаје нову, празну компоненту дизајну, унутар активне компоненте осим ако изаберете другу надређену компоненту. Користите је да нови део склопа добије своје место за тела и скице.", "help.component.finish_edit": "Чува део који мењате на месту, враћа се у његов склоп и ажурира склоп према њему. Користите када завршите измене повезаног дела.", + "help.component.from_bodies": "Претвара свако изабрано тело у засебну компоненту, названу по телу. Користите га када дизајн направљен од појединачних тела треба да постане склоп чији се делови могу спајати и померати.", + "help.component.insert_design": "Умеће други сачувани дизајн као компоненту повезану са његовом датотеком, а његова пуна тела се постављају онако како су у њему. Користите га да поново употребите део у склопу и да касније измене преузмете командом Ажурирај везе.", + "help.component.properties": "Приказује запремину, масу, центар масе и моменте инерције компоненте, према материјалима њених тела. Користите га да проверите тежину и равнотежу склопа.", + "help.component.revert_position": "Враћа делове које сте ручно померили на њихова претходна места и одбацује померања која нису забележена. Користите га да поништите пробна померања у склопу.", + "help.component.update_links": "Поново чита повезане датотеке дизајна и замењује тела која су се променила. Користите га након измене дела који овај склоп користи.", + "help.config.configure": "Додаје параметре, операције, материјале или изгледе као колоне табеле конфигурација. Користите га да направите варијанте једног дизајна, на пример величине једног дела.", + "help.config.preview": "Проверава да ли се ред табеле конфигурација успешно поново гради, без промене дизајна или његове историје. Користите га пре преласка на варијанту у коју нисте сигурни.", + "help.config.rules": "Приказује правила табеле конфигурација, њене редове и који ред је активан. Користите га да видите како су подешене варијанте дизајна.", + "help.config.table": "Приказује табелу конфигурација: један ред по варијанти, једну колону по параметру или операцији и да ли дизајн још одговара активном реду. Користите је да прегледате варијанте дизајна.", "help.connect_note": "Поново покрените сваки асистент да учита SolidCraft сервер. Свака датотека је безбедносно копирана као .bak пре промене.", "help.connect_title": "Повежи AI асистенте", + "help.construct.axis.edge": "Прави помоћну осу дуж праве ивице или линије скице. Користите је као осу за ротацију, кружни низ или спој.", + "help.construct.axis.normal_to_face": "Прави помоћну осу кроз тачку, окомиту на лице. Користите је као осу која излази право из површине.", + "help.construct.axis.through_cylinder": "Прави помоћну осу кроз центар цилиндричног, конусног или торусног лица, или кружне ивице. Користите је да операције окрећете или распоређујете у низ око округлог дела.", + "help.construct.axis.two_planes": "Прави помоћну осу тамо где се састају две равни или равна лица. Користите је када је оса која вам треба линија између два лица.", + "help.construct.axis.two_points": "Прави помоћну осу кроз две тачке, врхове или тачке скице. Користите је за осу која пролази кроз два позната положаја.", + "help.construct.plane.along_path": "Прави помоћну раван окомиту на ивицу или криву, на положају дуж ње. Користите је да скицирате профил за повлачење или попречни пресек путање.", + "help.construct.plane.at_angle": "Прави помоћну раван заокренуту под углом у односу на раван или лице, око осе или ивице. Користите је за нагнуте скице, на пример за угаони носач.", + "help.construct.plane.axis_point": "Прави помоћну раван која садржи осу и тачку изван те осе. Изаберите осу исходишта или помоћну осу, праву ивицу или линију скице, па врх, тачку скице или помоћну тачку. Тачка на оси не може да одреди јединствену раван.", + "help.construct.plane.midplane": "Прави помоћну раван на половини између две равни или равна лица, или раван која полови угао под којим се састају. Користите је као раван симетрије за пресликавање.", + "help.construct.plane.offset": "Прави помоћну раван паралелну равни или равном лицу, на задатом растојању или кроз тачку. Користите је да скицирате на одређеној висини изнад лица.", + "help.construct.plane.perpendicular": "Прави помоћну раван која садржи линију или ивицу и стоји окомито на раван или лице. Користите је да скицирате усправно на моделу дуж ивице.", + "help.construct.plane.tangent": "Прави помоћну раван која у једној тачки додирује цилиндар, конус, сферу или торус. Користите је да скицирате на боку округлог дела.", + "help.construct.plane.three_points": "Прави помоћну раван кроз три тачке. Користите је за раван одређену положајима на моделу, на пример за три угла.", + "help.construct.plane.two_edges": "Прави помоћну раван кроз две праве ивице или линије које леже у једној равни. Користите је за раван кроз део, на пример кроз две наспрамне ивице.", + "help.construct.point.along_path": "Прави помоћну тачку на положају дуж ивице или криве. Користите је као референцу негде на путањи.", + "help.construct.point.center": "Прави помоћну тачку у центру кружне ивице, круга или лука скице, сфере или торуса. Користите је као референцу за рупе, осе и спојеве.", + "help.construct.point.edge_plane": "Прави помоћну тачку где ивица или линија пролази кроз раван или равно лице. Користите је да означите где путања сече раван.", + "help.construct.point.three_planes": "Прави помоћну тачку где се састају три равни или равна лица. Користите је као референцу за угао, чак и тамо где модел нема врх.", + "help.construct.point.two_edges": "Прави помоћну тачку где се две ивице или линије састају или су најближе једна другој. Користите је као референцу у виртуелном углу.", + "help.construct.point.vertex": "Прави помоћну тачку на врху или тачки скице. Користите је као референцу која остаје и када су скица или тело око ње сакривени.", + "help.contact.check": "Наводи парове делова у скуповима контаката који у свом тренутном положају пролазе један кроз други. Користите га да пронађете сударе пре него што покренете спојеве или студију кретања.", + "help.contact.create": "Групише два или више делова у скуп контаката чија тела не могу да прођу један кроз други док се спојеви крећу. Користите га за делове који треба да стану када се додирну, као што је полуга уз свој граничник.", + "help.contact.disable_all": "Искључује контакт, па покренути спојеви и студије кретања више не стају тамо где се делови додирују. Користите га да поново слободно померате делове или да велики склоп остане брз.", + "help.contact.edit": "Мења скуп контаката: делове које садржи, његов назив или да ли је потиснут; може и да избрише скуп. Користите га да подесите који делови не могу да прођу један кроз други.", + "help.contact.enable_all": "Ставља сваки део склопа у један скуп контаката, па никоја два дела не могу да прођу један кроз други док се спојеви крећу. Користите га за брзу проверу целог механизма.", + "help.contact.enable_sets": "Укључује контакт за скупове контаката које сте дефинисали, па покренути спојеви и студије кретања стају тамо где би њихови делови прошли један кроз други. Користите га да вратите своје скупове након искључивања контакта.", + "help.contact.list": "Наводи скупове контаката дизајна, делове у сваком од њих и да ли је контакт укључен. Користите га да проверите како је контакт подешен пре него што покренете склоп.", + "help.document.inspect": "Приказује преглед дизајна: његове компоненте, тела, скице, операције и параметре. Користите га да се снађете у дизајну који нисте сами направили.", + "help.document.units": "Мења јединице у којима дизајн приказује дужине, на пример mm или инчи. Геометрија задржава своју величину; мењају се само приказ и обични бројеви.", + "help.edit.checkpoint": "Памти дизајн, активну скицу и историју поништавања онакве какви су сада. Користите је пре него што испробате нешто ризично од чега ћете се можда хтети вратити.", + "help.edit.restore_checkpoint": "Враћа се на контролну тачку, укључујући историју поништавања. Користите га да једним кораком одбаците све што је урађено од контролне тачке.", + "help.explode.create": "Прави растављени приказ који делове одгура од центра склопа, или за померања која зададете. Користите га да прикажете како се склоп саставља, за упутства или презентације.", "help.face.delete": "Уклања изабрана лица и пушта да суседна лица затворе отвор, или оставља отвор отвореним као површ. Користите га да уклоните заобљену ивицу, рупу или испупчење које смета.", + "help.file.insert_mesh": "Додаје 3MF, STL, OBJ, PLY или glTF датотеку дизајну као мрежна тела у новој компоненти. Користите га да преузети или скенирани модел поставите поред свог дизајна као референцу.", + "help.file.insert_step": "Додаје STEP, IGES, FreeCAD или Rhino датотеку дизајну као пуна тела у новој компоненти; делови склопа постају угнежђене компоненте. Користите га да унесете моделе од добављача или из других CAD програма.", + "help.file.save_mesh": "Чува тела као STL, 3MF или OBJ мрежу, са глаткоћом закривљених лица коју изаберете. Користите је да припремите делове за 3D штампу или за програме који читају мреже.", + "help.file.send_to_slicer": "Чува изабрана тела као 3MF датотеку и отвара је у слајсеру који изаберете. Користите га да једним кораком пређете од модела до штампе.", "help.font_details": "Интерфејс користи уграђене фонтове библиотеке egui (Ubuntu Light и Hack, под лиценцама Ubuntu Font Licence и MIT/Bitstream Vera; Noto Emoji и фонт емоџи икона, под лиценцама OFL и MIT). Текст скице користи Liberation Sans (SIL OFL 1.1). Необавезни пакет фонтова Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), није укључен у издања SolidCraft-а.", "help.fonts": "Фонтови", + "help.frame.member": "Поставља профил, на пример цев или алуминијумски екструдирани профил, дуж линија скице оквира, по један елемент по линији. Користите га да направите оквире, регале и заварене конструкције.", + "help.inspect.accessibility": "Боји лица до којих алат може да допре из једног смера и она до којих не може. Користите је да проверите део за обраду или израду у калупу са те стране.", + "help.inspect.center_of_mass": "Приказује центар масе тела, сваког посебно и свих заједно, при уједначеној густини. Користите га да проверите равнотежу и где ће се део преврнути.", + "help.inspect.colored_components": "Даје свакој компоненти сопствену привремену боју, без промене изгледа. Користите га да на први поглед разликујете делове склопа.", + "help.inspect.compare": "Упоређује два тела и показује где једно има материјал којег друго нема, са запремином и одступањем. Користите га да проверите измењен или увезен део у односу на оригинал.", + "help.inspect.continuity": "Проверава колико глатко се лица спајају дуж својих ивица: размаке, прегибе или скокове закривљености, и осенчава шавове. Користите је да пронађете где се површи не спајају уредно.", + "help.inspect.curvature_comb": "Црта чешљеве дуж кривих, ивица или лица чији зуби показују колико су јако закривљени. Користите је да уочите равна места, прегибе и неуједначену закривљеност.", + "help.inspect.curvature_map": "Боји лица према јачини закривљености, црвено где је полупречник мали. Користите је да пронађете оштре кривине и да процените колико је површ глатка.", + "help.inspect.draft": "Боји лица према углу нагиба у односу на смер вађења из калупа и означава она са премало нагиба. Користите је да проверите део пре израде у калупу или ливења.", + "help.inspect.environment_map": "Приказује модел са рефлектујућом завршном обрадом налик огледалу. Користите је да процените ток површи по начину на који се одблесци простиру преко њих.", + "help.inspect.interference": "Проналази тела која се преклапају и приказује свако преклапање са његовом запремином. Користите га да проверите да ли у склопу има делова који се сударају.", + "help.inspect.isocurve": "Црта изопараметарске криве лица, мрежу на којој је површ изграђена. Користите је да видите како површ тече и где се згушњава.", + "help.inspect.measure": "Мери дужине, растојања, углове, површине и полупречнике између онога што изаберете, или запремину и масу тела. Користите га да проверите мере и зазоре.", + "help.inspect.minimum_radius": "Проналази најмањи полупречник закривљености кривих, ивица или лица и где се налази. Користите је да проверите да ли алат или млазница може да прати облик.", + "help.inspect.section": "Расеца приказ дуж равни и шрафира пресечена лица, без промене модела. Користите га да погледате унутрашњост делова и склопова.", + "help.inspect.zebra": "Приказује црне и беле пруге одбијене на лицима модела. Користите је да процените глаткоћу: пруге које се прекидају или ломе на ивици показују лош прелаз.", + "help.joint.as_built": "Спаја два дела тамо где већ јесу, не померајући ниједан, и одређује како се још могу кретати. Користите га за делове које сте већ поставили у њихов коначни положај.", + "help.joint.cam": "Повезује брег који се окреће са пратиоцем, па пратилац клизи или се њише док обрис брега пролази испод њега. Користите га за брегове, ексцентре и погоне вентила.", + "help.joint.create": "Спаја два дела у исходиштима споја која изаберете и помера други део на место; врста споја одређује како се још могу кретати. Користите га да направите склоп чији се делови крећу као прави механизам.", + "help.joint.drive": "Задаје угао или растојање споја и са њим помера делове, у оквиру његових граница; повезани спојеви и затворене петље га прате. Користите га да проверите да ли се механизам креће како је замишљено.", + "help.joint.gear": "Повезује два окретна споја преносним односом, па покретање једног окреће други. Користите га за чеоне и унутрашње зупчанике, са односом из полупречника подеоних кругова или броја зуба.", + "help.joint.limits": "Одређује докле спој сме да се окреће или клизи, као минимум и максимум, или брише те границе. Користите га да шарку, клизач или полугу задржите у њиховом стварном опсегу кретања.", + "help.joint.motion_link": "Спреже два споја односом и помаком, па покретање једног помера други. Користите је за сталну везу између спојева коју Зупчаник, Зупчаста летва и зупчаник или Завртањ не покривају.", + "help.joint.origin": "Поставља именовано исходиште споја на део: у центар лица или округлог краја, средину ивице, угао или тачку. Користите га да припремите места на која се спојеви причвршћују; исходиште изабрано на лицу прати лице када део промени величину.", + "help.joint.rack_pinion": "Повезује мали зупчаник који се окреће са зупчастом летвом која клизи, па се летва помера за дужину подеоног круга коју зупчаник пређе котрљањем. Користите га за погоне са зупчастом летвом, управљање и линеарне столове.", + "help.joint.reach": "Помера тачку на делу ка циљу променом спојева на њеном ланцу, у оквиру њихових граница. Користите га да механизам поставите према томе где би његов крај требало да буде, на пример врх руке робота.", + "help.joint.rigid_group": "Закључава изабране делове један за други онакве какви јесу, па се крећу као једно. Користите је за делове који припадају заједно и међу којима нема кретања.", + "help.joint.screw": "Повезује окретање и клизање кораком, па сваки окретај помера за то растојање. Користите га за навојна вретена, завртње и навојне осовине.", + "help.library.apply": "Примењује материјал или изглед из датотеке локалне библиотеке на тела, лица или компоненте. Користите га да поново употребите материјале које сте сачували из другог дизајна.", + "help.library.export": "Чува материјале и изгледе дизајна у датотеку библиотеке. Користите га да их делите или поново користите у другим дизајнима.", + "help.library.inspect": "Проверава датотеку библиотеке и наводи њене материјале и изгледе, без промене дизајна. Користите га да видите шта библиотека садржи пре него што је примените.", "help.licences": "Лиценце", "help.material.assign": "Одређује од чега су изабрана тела направљена, нпр. челик, алуминијум или ABS. Користите га да маса и тежина одговарају стварном делу.", + "help.material.properties.validate": "Проверава да ли су бројеви на картици података о материјалу међусобно усклађени и да ли недостају вредности. Користите га пре него што се ослоните на податке за масу или крутост.", + "help.mesh.convert": "Поново гради мрежно тело, на пример STL, као тело које се може мењати, са равним и цилиндричним лицима. Користите га да мењате увезене механичке делове као моделована тела.", "help.mit": "MIT лиценца", + "help.motion.study": "Задаје вредности спојева у корацима дуж временске осе и репродукује их као анимацију. Користите је да гледате како се механизам креће кроз низ положаја и успут проверите зазоре.", + "help.motion.trace": "Прати путању којом иде тачка на делу док се студија кретања репродукује или спој покреће и, када потврдите, чува је као 3D криву скице. Користите га да видите докле механизам досеже или да на његовој путањи градите даље.", "help.notice": "NOTICE", + "help.occurrence.ground": "Учвршћује део на месту или га поново ослобађа, тако да спојеви померају остале делове око њега. Користите га за оквир или основу на којој је изграђен остатак склопа.", "help.occurrence.move": "Помера део склопа само дуж слобода које дозвољавају његови спојеви. Изаберите лице дела, а затим превуците доступну стрелицу или лук.", "help.parameters.change": "Отвара табелу именованих вредности и израза који управљају котама дизајна. Користите је да промените меру на једном месту, а све операције које је користе је прате.", + "help.parameters.export": "Чува параметре дизајна као CSV или JSON. Користите га да их уређујете у табели или пренесете у други дизајн.", + "help.parameters.graph": "Показује који параметри и операције користе које друге, као и евентуалне петље или грешке међу њима. Користите га да видите на шта ће утицати промена параметра.", + "help.parameters.import": "Учитава параметре из CSV или JSON у дизајн, и то све или ниједан. Користите га да унесете вредности из табеле или другог дизајна.", + "help.parameters.move": "Помера кориснички параметар испред или иза другог на списку. Користите га да сродни параметри остану заједно.", + "help.parts.fastener": "Додаје стандардни завртањ, вијак, навртку, подлошку, клин или лежај у величини коју изаберете. Постављен на рупу, належе у рупу помоћу споја, па не морате сами да моделујете спојне елементе.", + "help.parts.insert": "Умеће стандардни део у породици, величини и дужини које изаберете. Постављен на обод или зид рупе, належе на рупу крутим спојем.", + "help.parts.library": "Отвара стандардне делове: завртње, вијке, навртке, подлошке, завртње без главе, паралелне клинове (колчиће) и лежајеве у стандардним величинама. Користите га да додате стандардни део уместо да га сами моделујете.", + "help.parts.resize": "Мења величину или дужину уметнутог стандардног дела и поново га гради; његови спојеви га држе на месту. Користите га када се покаже да је завртањ предугачак или када рупа захтева другу величину.", + "help.plastic.assign_rule": "Додељује правило за пластику телима, па њихове пластичне операције преузимају његов нагиб и зазор као подразумеване вредности. Користите га да једном подесите део израђен у калупу за све његове операције.", + "help.plastic.boss": "Додаје испуст за завртањ на лицу: стуб са необавезном рупом, нагибом, заобљењем у корену и потпорним ребрима. Користите га за места за завртње у кућиштима израђеним у калупу или штампаним.", + "help.plastic.lip": "Додаје усну или одговарајући жлеб дуж обода издубљеног тела. Користите је да се две половине кућишта позиционирају једна на другу и чврсто затворе.", + "help.plastic.manage_rules": "Прави и мења правила за пластику: материјал, дебљину зида, полупречнике, зазор и нагиб. Користите их да операције дела израђеног у калупу буду усклађене.", + "help.plastic.rest": "Додаје ослонац на лицу: округло или правоугаоно постоље, пуно или шупље, са нагибом. Користите га као подлогу или дистанцер у кућишту израђеном у калупу.", + "help.plastic.snap_fit": "Додаје куку шкљоцајућег споја на лицу, са њеном дужином, дебљином и зупцем. Користите га да делове спојите шкљоцањем, без завртања.", "help.pointcloud.insert": "Уметните PLY, XYZ или PTS скенирање као облак тачака поред модела. Користите га као референцу при изради модела на основу измерених података.", + "help.sheet.convert": "Претвара плочу или издубљено тело једнаке дебљине у тело од лима, са савијањима на ивицама које изаберете. Користите га да постојећи део буде могуће развити.", + "help.sheet.export_bend_table": "Чува табелу савијања тела од лима као CSV или JSON: углове, полупречнике и положаје савијања у развијеном облику. Користите је за пресу за савијање или радионицу.", + "help.sheet.export_dxf": "Чува развијени облик као DXF, са обрисима, линијама савијања и необавезним белешкама о савијању. Користите га за ласерско, плазма или водено сечење.", + "help.sheet.flange": "Додаје прирубницу: основну плочу из скице, зид дуж отворене контуре скице или савијени зид на ивицама лима. Користите је да изградите делове од лима.", + "help.sheet.flat_pattern": "Прави развијени облик тела од лима, са његовом величином, изрезима и линијама савијања. Користите га да проверите заготовак пре сечења.", + "help.sheet.fold": "Савија лим дуж линије скице за задати угао и полупречник. Користите га да пресавијете раван лим након што сте у њега исекли изрезе.", + "help.sheet.hem": "Пресавија ивицу лима натраг на саму себе. Користите га за безбедне, круте ивице без оштрог грата.", + "help.sheet.manage_rules": "Прави и мења правила за лим: дебљину, полупречник савијања, K-фактор, растерећења и размаке. Користите их да ускладите материјал и алате своје радионице.", + "help.sheet.path_flange": "Додаје низ прирубница дуж ивице лима, пратећи отворени ланац линија скице. Користите је за профиле као што су U или Z облик у једном кораку.", + "help.sheet.perforate": "Додаје поље рупа преко целог равног лима, у помереном или квадратном распореду. Користите га за отворе за проветравање, решетке и лакше панеле.", + "help.sheet.refold": "Поново савија развијено тело од лима. Користите га након додавања операција на раван лим.", + "help.sheet.unfold": "Развија сва савијања тела од лима. Користите га да додате рупе или изрезе који морају да пређу преко савијања, а затим поново пресавијте.", + "help.sketch.arc.center_point": "Црта кружни лук око центра, од почетне до крајње тачке. Користите га када је центар лука познат, на пример за полупречник око рупе или осовине.", + "help.sketch.arc.tangent": "Црта лук који почиње на крају линије или лука и наставља тангентно на њега. Користите га да ланац наставите глатком кривином уместо углом.", + "help.sketch.arc.three_point": "Црта лук од почетне до крајње тачке кроз трећу тачку. Користите га када лук мора да прође кроз задате тачке, а не око познатог центра.", + "help.sketch.arc3d": "Црта тачан кружни лук у простору кроз три тачке, са укљученом 3D скицом. Користите га за кривине путања и водилица које напуштају раван скице.", + "help.sketch.auto_constrain": "Додаје ограничења која скица скоро већ има, као што су хоризонталност, паралелност или подударност, а затим је котира док није потпуно дефинисана. Користите ову команду да једним кораком учврстите грубо нацртану скицу.", + "help.sketch.auto_constrain_from_datum": "Ради као команда Аутоматска ограничења, али положаје мери од референтне тачке коју изаберете уместо од исходишта. Користите је када је део распоређен од једне референтне тачке, на пример угла или рупе.", + "help.sketch.blend_curve": "Спаја крајеве две криве глатким сплајном који је тангентан на обе, или и непрекидан по закривљености ако тако изаберете. Користите је да премостите размак између кривих без прегиба.", + "help.sketch.break": "Дели криву на делове тамо где је секу друге криве или у тачкама које поставите на њу. Користите га када део криве треба да има своје ограничење или да се сам избрише.", + "help.sketch.cancel": "Напушта скицу и одбацује све што је измењено откако је направљена или отворена за измену. Поништи враћа измене.", + "help.sketch.centerline": "Пребацује линије између обичних линија и средишњих линија, оса које профили изостављају. Користите средишњу линију као осу за ротацију, пресликавање или ограничење симетрије.", + "help.sketch.chamfer.distance_angle": "Скошава угао између две линије; задаје се растојањем дуж прве линије и углом. Користите га када цртеж даје скошење као дужину и угао, на пример 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Скошава угао између две линије за исто растојање уназад дуж обе. Користите га за уобичајено скошење од 45° на обрису.", + "help.sketch.chamfer.two_distance": "Скошава угао између две линије; задаје се засебним растојањем дуж сваке линије. Користите га за скошења која нису од 45°, задата као две дужине.", + "help.sketch.circle.center": "Црта круг из његовог центра и пречника. Користите га за рупе, испусте и друге округле облике чији је центар познат.", + "help.sketch.circle.three_point": "Црта круг кроз три тачке. Користите га када круг мора да прође кроз задате тачке, на пример кроз тачке постојеће геометрије.", + "help.sketch.circle.three_tangent": "Црта круг који додирује три елемента: линије, кругове или лукове. Користите га да уклопите круг у простор између три криве, на пример као уписани круг троугла.", + "help.sketch.circle.two_point": "Црта круг из две крајње тачке његовог пречника. Користите га када су познате тачке на ивици круга, а не његов центар.", + "help.sketch.circle.two_tangent": "Црта круг задате величине који додирује два елемента: линије, кругове или лукове. Користите га за заобљење сталног полупречника између две криве.", + "help.sketch.conic": "Црта конику између две крајње тачке, обликовану теменом и параметром ρ. Користите је за глатке прелазе чију пуноћу желите да подесите, од равног до скоро оштрог угла.", + "help.sketch.constrainer": "Примењује ограничење које једна или две изабране криве већ скоро имају, као што су хоризонтално, паралелно, тангентно или једнако. Користите га да ручно нацртану скицу сређујете ограничење по ограничење.", + "help.sketch.constraint.coincident": "Поставља тачку на другу тачку, криву или осу скице. Користите је да затворите размаке у профилу или да поставите тачку на линију.", + "help.sketch.constraint.collinear": "Поставља две линије на једну праву. Користите је да поравнате прекинуте ивице, на пример обе стране зареза.", + "help.sketch.constraint.concentric": "Поставља два круга или лука на исти центар. Користите је за прстенове, цилиндрична упуштења и вратила са степеницама.", + "help.sketch.constraint.curvature": "Чини да две криве које се сусрећу у крајњој тачки настављају са истом закривљеношћу (G2). Користите је тамо где тангентни спој није довољно глатак, на пример на видљивим површинама.", + "help.sketch.constraint.equal": "Чини линије исте дужине, а кругове и лукове истог полупречника. Користите је да једна кота одређује неколико одговарајућих облика.", + "help.sketch.constraint.fix": "Фиксира тачке или криве где јесу или их поново ослобађа. Користите га за геометрију која се не сме померати када превлачите или решавате скицу.", + "help.sketch.constraint.horizontal_vertical": "Чини линију, или линију између две тачке, хоризонталном или вертикалном, зависно од тога која је ближа. Користите га да обрис поравнате са осама скице.", + "help.sketch.constraint.midpoint": "Поставља тачку на средину линије или чини да се средишње тачке две линије поклопе. Користите га да геометрију центрирате на ивици.", + "help.sketch.constraint.parallel": "Чини да две линије буду паралелне. Користите је за странице које морају остати паралелне када се друге коте промене.", + "help.sketch.constraint.perpendicular": "Чини да се две линије састају под правим углом. Користите је за праве углове између линија које нису на осама скице.", + "help.sketch.constraint.polygon": "Чини затворени ланац линија правилним полигоном: једнаких страница, са сваким теменом на једном кругу. Користите га да ручно нацртани полигон учините правилним и да такав остане.", + "help.sketch.constraint.symmetry": "Чини да две тачке или криве буду једна другој одраз преко линије или око тачке. Користите је да профил остане симетричан када мењате једну страну.", + "help.sketch.constraint.tangent": "Чини да се две криве додирују тангентно, на пример линија и лук. Користите га за глатке спојеве без прегиба.", + "help.sketch.construction": "Пребацује криве између обичне и помоћне геометрије, коју профили изостављају. Користите помоћне криве као помагала за распоред, референце и коте.", + "help.sketch.construction_line": "Направите бесконачну помоћну праву кроз две тачке. Користите је да распоредите скицу без раздвајања профила.", + "help.sketch.construction_line.angle": "Направите бесконачну помоћну праву под углом од осе X скице. Изаберите тачку и упишите угао или изаберите смер.", + "help.sketch.construction_line.bisector": "Изаберите две праве линије скице које се секу, па једну од две симетрале угла. Резултат прати изворне линије.", + "help.sketch.construction_line.horizontal": "Направите бесконачну хоризонталну помоћну праву кроз тачку. Њено ограничење хоризонталности остаје на снази при каснијим изменама.", + "help.sketch.construction_line.parallel": "Изаберите праву линију скице, па поставите паралелну бесконачну помоћну праву. Десним кликом изаберите другу референцу.", + "help.sketch.construction_line.perpendicular": "Изаберите праву линију скице, па поставите нормалну бесконачну помоћну праву. Десним кликом изаберите другу референцу.", + "help.sketch.construction_line.tangent_at": "Направите тангенту у тачки на кругу или кружном луку, или у крајњој тачки отвореног сплајна или конике. Изаберите криву, па тачку додира.", + "help.sketch.construction_line.tangent_external": "Изаберите круг или кружни лук, па спољашњу тачку и решење тангенте. Прегледи приказују само тачке додира на нацртаном луку.", + "help.sketch.construction_line.tangent_two": "Изаберите два круга или кружна лука, па у прегледу изаберите заједничку тангенту. Тачке додира морају лежати на нацртаним кривама.", + "help.sketch.construction_line.vertical": "Направите бесконачну вертикалну помоћну праву кроз тачку. Њено ограничење вертикалности остаје на снази при каснијим изменама.", + "help.sketch.copy": "Копира изабране криве и тачке скице, заједно са ограничењима и котама међу њима. Налепите их у ову или у другу скицу.", + "help.sketch.create": "Започиње нову 2D скицу на равни или на равном лицу модела. Свака екструзија, ротација и повлачење почиње скицом.", + "help.sketch.cut": "Копира изабрану геометрију скице и брише је из скице, у једном кораку поништавања. Налепите је на другом месту у овој скици или у другу.", + "help.sketch.dimension": "Додаје погонску коту: дужину, растојање, угао, полупречник или пречник, зависно од тога шта изаберете. Упишите вредност или назив параметра, а скица га прати.", + "help.sketch.edit": "Отвара постојећу скицу за измену. Операције изграђене на њој ажурирају се када завршите скицу.", + "help.sketch.ellipse": "Црта елипсу из њеног центра, краја велике осе и тачке на њеној малој оси. Користите је за овалне отворе, брегове и друге издужене округле облике.", "help.sketch.equation_curve": "Црта криву из формула: x(t) и y(t), или y = f(x), у задатом опсегу. Формуле могу да користе параметре и крива их прати: користите је за синусоиду, спиралу или евольвенту зупца зупчаника.", + "help.sketch.extend": "Продужава линију или лук до најближе криве на свом путу или продужава две криве док се не сретну. Користите га да затворите размаке у профилу након одсецања или измене.", + "help.sketch.fillet": "Заобљује угао у којем се састају линије или лукови, луком задатог полупречника. Више углова заобљених заједно деле један полупречник.", + "help.sketch.finish": "Напушта скицу и враћа се на модел. Њени затворени профили су тада спремни за Екструдирај, Ротирај и друге операције.", + "help.sketch.finish_auto_constrain": "Покреће команду Аутоматска ограничења на скици, а затим је завршава. Користите га да једним кораком оставите потпуно дефинисану скицу.", + "help.sketch.fit_curves_to_section": "Пресеца мрежно или пуно тело равни скице и уклапа линије и лукове у пресек. Користите га да скенирани или увезени део поново направите као скицу која се може мењати.", + "help.sketch.include_3d": "Уноси ивице модела, врхове и криве других скица у ову скицу као повезане референце, а оне ван њене равни спљоштава на њу. Користите га да градите на геометрији која не лежи у равни скице.", + "help.sketch.infinite": "Пребацује линије између обичних линија и бесконачних помоћних линија које се пружају преко целог приказа. Користите је за референце распореда које никад не завршавају прерано.", + "help.sketch.insert_dxf": "Учитава криве DXF цртежа у скицу, скалиране, окренуте и постављене како зададете. Користите га да градите на 2D цртежу из другог програма, на пример на обрису за ласерско сечење.", + "help.sketch.insert_svg": "Учитава путање SVG цртежа у скицу, скалиране, окренуте и постављене како зададете. Користите га да логотип или векторски обрис претворите у криве које можете екструдирати.", + "help.sketch.inspect": "Отвара извештај о отвореној скици: колико је степени слободе остало и да ли је потпуно ограничена. Користите га да сазнате шта се још помера пре него што завршите скицу.", + "help.sketch.intersect": "Додаје криве или тачке у којима тела, лица, ивице или друге скице секу раван скице. Оне остају повезане и прате модел када се он промени.", + "help.sketch.intersection_curve": "Прави 3D криве тамо где се два тела или лица састају, повезане са њима. Користите их као путање или водилице које прате модел.", + "help.sketch.isoparametric_curve": "Прави 3D криву дуж U или V смера лица кроз тачку коју изаберете, повезану са лицем. Користите је као путању или линију поделе која прати површ.", + "help.sketch.line": "Црта повезане линије тачку по тачку, као отворени ланац или затворени обрис. То је основни алат за већину профила.", + "help.sketch.line.midpoint": "Црта линију од њене средишње тачке до једног краја, а други крај се пресликава. Користите је за линије центриране на тачки, на пример за симетричну ивицу.", + "help.sketch.line3d": "Црта повезане праве линије између тачака у простору, са укљученом 3D скицом. Користите је за путање и оквире који напуштају раван скице.", + "help.sketch.mirror": "Пресликава криве и тачке скице преко линије или осе и додаје ограничења симетрије. Користите га да нацртате половину симетричног профила и допуните га.", + "help.sketch.move": "Помера или ротира криве и тачке скице, или њихову копију. Користите га да промените положај геометрије уз задржавање њеног облика и ограничења.", + "help.sketch.offset": "Прави копију ланца кривих на задатом растојању, на једној или обе стране. Користите га за зидове, обрисе и зазоре; растојање остаје кота која се може мењати.", + "help.sketch.paste": "Налепљује геометрију скице коју сте копирали или исекли у активну скицу. Поставите је на тачку или је померите за задати помак.", + "help.sketch.pattern.circular": "Копира геометрију скице око централне тачке, преко пуног круга или задатог угла. Користите га за кружне распореде рупа за завртње, паоке и зубе.", + "help.sketch.pattern.rectangular": "Копира геометрију скице у редове и колоне на задатим размацима. Користите га за мреже рупа, жлебова или отвора за проветравање.", + "help.sketch.point": "Поставља тачку скице. Користите је као референцу за коте, ограничења, центре рупа или касније операције.", + "help.sketch.point3d": "Поставља тачку у простору, са укљученом 3D скицом. Користите је као референцу за 3D криве и путање.", + "help.sketch.polygon.circumscribed": "Црта правилан полигон око круга, чија се величина задаје од центра до средине странице. Користите га када је познат отвор кључа, као код шестоугаоне навртке.", + "help.sketch.polygon.edge": "Црта правилан полигон из два краја једне странице. Користите га када су познате дужина и положај странице.", + "help.sketch.polygon.inscribed": "Црта правилан полигон унутар круга, чија се величина задаје од центра до темена. Користите га када је позната мера преко темена.", + "help.sketch.project": "Уноси ивице, лица и врхове модела и криве других скица у ову скицу, пројектоване на њену раван. Оне остају повезане и прате модел када се он промени.", + "help.sketch.project_to_surface": "Пројектује криве других скица дуж нормале ове скице на лице, као повезане 3D криве. Користите га да логотип, линију поделе или путању ставите на закривљену површину.", + "help.sketch.rectangle.center": "Црта правоугаоник из његовог центра и једног угла. Користите га за обрисе центриране на тачки, на пример на исходишту.", + "help.sketch.rectangle.rounded": "Црта правоугаоник са сва четири угла заобљена истим полупречником. Користите га за плоче, поклопце и отворе са заобљеним угловима.", + "help.sketch.rectangle.three_point": "Црта правоугаоник из једне ивице и тачке на супротној страни. Користите га за правоугаонике под углом у односу на осе скице.", + "help.sketch.rectangle.two_point": "Црта правоугаоник из два супротна угла. Користите га за обрисе плоча, блокова и џепова.", + "help.sketch.scale": "Скалира криве и тачке скице задатим фактором око базне тачке. Користите га да промените величину дела скице без поновног цртања.", + "help.sketch.slot.arc_center": "Црта закривљени жлеб задате ширине дуж лука одређеног центром, почетком и крајем. Користите га за жлебове за подешавање око осовине.", + "help.sketch.slot.arc_three_point": "Црта закривљени жлеб задате ширине дуж лука кроз три тачке. Користите га када путања жлеба мора да прође кроз задате тачке.", + "help.sketch.slot.center_point": "Црта прави жлеб задате ширине од његовог центра до центра једног крајњег лука. Користите га за жлебове центриране на тачки.", + "help.sketch.slot.center_to_center": "Црта прави жлеб задате ширине између центара његова два крајња лука. Користите га за жлебове котиране од центра до центра, на пример за жлебове за подешавање завртња.", + "help.sketch.slot.overall": "Црта прави жлеб задате ширине од једног спољног краја до другог. Користите га када је важна укупна дужина жлеба.", + "help.sketch.spline.control_point": "Црта кубни сплајн обликован контролним тачкама кроз које не пролази. Користите га за глатке, течне криве које обликујете померањем тачака.", + "help.sketch.spline.control_point_5": "Црта сплајн степена 5 обликован контролним тачкама. Користите га тамо где се криве морају спојити са глаткијом закривљеношћу, на пример на видљивим дизајнерским површинама.", + "help.sketch.spline.fit_point": "Црта глатки сплајн који пролази кроз сваку тачку коју поставите, отворен или затворен. Користите га да пратите облик кроз познате тачке.", + "help.sketch.spline3d": "Црта глатку криву у простору кроз тачке, са укљученом 3D скицом. Користите га за путање повлачења и трасе каблова који напуштају раван скице.", + "help.sketch.spun_profile": "Прави у равни скице обрис који тело опише када се окреће око осе. Користите га да добијете силуету струганог дела за ротацију или цртеж.", + "help.sketch.text": "Уписује текст у скицу изабраним фонтом, висином и углом; његове речи могу да прате параметре. Екструдирајте га или направите рељеф за ознаке и натписе.", + "help.sketch.transform": "Скалира, окреће и помера геометрију скице око централне тачке у једном кораку. Користите га да истовремено промените положај и величину избора.", + "help.sketch.trim": "Уклања део криве између најближих пресека око места где кликнете. Користите га да преклапајуће линије средите у затворен профил.", "help.solid.align": "Помера изабрана тела тако да се тачка, лице или раван на њима поклопи са тачком, лицем или равни негде другде. Користите га да поставите део уз други без мерења одмака.", + "help.solid.boundary_fill": "Прави тела од области затворених преклапајућим алатним телима, попуњавајући само области које изаберете. Користите је да направите облик од простора који заједно ограничава неколико тела.", + "help.solid.bounding_solid": "Прави кутију која обухвата изабрана тела, са необавезним додатком. Користите га да видите укупну величину дела или као комад материјала од којег се обрађује.", + "help.solid.box": "Прави кутију из дужине, ширине и висине, из угаоне тачке или центрирану на тачки. Користите је за брз блок, привремену замену или тело у које се секу облици.", "help.solid.chamfer": "Одсеца изабране ивице равним скошењем задатог растојања. Користите га да ублажите оштре ивице или олакшате увођење чивије или завртња.", + "help.solid.coil": "Прави завојно тело, на пример опругу, из пречника, броја окретаја, висине или корака и округлог или квадратног пресека. Користите је за опруге, завојнице и завојне гребене.", "help.solid.combine": "Спаја тела, одузима их од циљног тела или задржава само заједничку запремину, а може да задржи и алатна тела. Користите га да спојите делове, да једним обликом одсечете други или да пронађете где се два тела преклапају.", + "help.solid.cone": "Прави конус из основног круга и висине, или зарубљени конус када и врх има полупречник. Користите га за сужења, левкове, упуштања и шиљке.", + "help.solid.cylinder": "Прави цилиндар из полупречника или пречника и висине, постављен на тачку дуж осе. Користите га за вратила, клинове, испусте и округле заготовке.", "help.solid.draft": "Нагиње изабрана лица за угао који задате, мерено од неутралне равни. Користите га на ливеним или бризганим деловима како би изашли из калупа.", + "help.solid.emboss": "Издиже профиле скице, на пример текст или логотип, из лица или их утискује у њега. Користите га за натписе, ознаке и обележја на равним или округлим лицима.", "help.solid.extrude": "Извлачи профил скице у 3D дуж задатог растојања, додајући или уклањајући материјал. Користите га да раван обрис претворите у блок, испуст или џеп.", "help.solid.fillet": "Заобљује изабране ивице глатким кружним прелазом задатог полупречника. Користите га да омекшате оштре ивице ради чврстоће, удобности или изгледа.", "help.solid.hole": "Буши округлу рупу задатог пречника на изабраној тачки лица. Користите је за пролазе завртања, чивије и друге једноставне округле отворе.", @@ -1412,20 +1678,60 @@ "help.solid.move": "Помера или ротира изабрана тела, или њихову копију, за растојање и угао које задате. Користите га да преместите тело или направите друго на другом месту.", "help.solid.offset_face": "Гура изабрана лица унутра или напоље за растојање које задате, а околна лица их прате. Користите га да подебљате зид, продубите џеп или повисите испупчење без мењања скице.", "help.solid.pattern.circular": "Понавља изабране објекте око осе, за задати број и укупни угао. Користите га за кругове завртања, жбице, ребра хладњака и зупце.", + "help.solid.pattern.path": "Копира операције или тела дуж путање скице, према броју и размаку. Користите га за рупе дуж закривљене ивице или делове дуж шине.", "help.solid.pattern.rectangular": "Понавља изабране објекте у једном или два смера са задатим бројем и размаком. Користите га за редове и мреже рупа, ребара, чивија или ножица.", + "help.solid.pipe": "Прави округлу цев дуж путање кривих скице, пуну или шупљу са задатом дебљином зида. Користите је за цеви, жице, каблове и шине.", "help.solid.press_pull": "Додаје или уклања материјал док превлачите лице, или заобљава ивице док их превлачите. Користите га за брзе измене директно на моделу.", "help.solid.remove": "Уклања изабрана тела из дизајна од ове тачке временске траке надаље; ранији кораци их задржавају. Користите га да одбаците помоћно тело, нпр. алат за сечење који вам више не треба.", "help.solid.replace_face": "Премешта изабрана равна лица на раван или на паралелно лице, а тело расте или се смањује да га досегне. Користите га да поравнате лице са другим делом или помоћном равни.", "help.solid.revolve": "Окреће профил скице око осе и прави округло тело. Користите га за вратила, дугмад, посуде и сваки део који је округао око средишње линије.", + "help.solid.rib": "Додаје танак зид дуж отворене криве скице, испуњен до наредних лица тела. Користите га да ојачате зидове и углове, на пример код делова израђених у калупу или штампаних.", "help.solid.scale": "Повећава или смањује изабрана тела за фактор, једнако у свим смеровима или посебно по оси. Користите га да промените величину увезеног облика или урачунате скупљање.", "help.solid.shell": "Издубљује тело и оставља зидове задате дебљине, а може да отвори лица која изаберете. Користите га за кутије, поклопце и друге танкозидне делове.", + "help.solid.sphere": "Прави сферу из полупречника или пречника око централне тачке. Користите је за кугле, дугмад и заобљене крајеве.", "help.solid.split_body": "Сече тело на засебна тела равни, лицем другог тела или линијом скице. Користите га за делове који се засебно штампају, обрађују или боје.", "help.solid.split_face": "Дели изабрана лица по равни, лицу другог тела или кривама скице, без сечења тела. Користите га да делу лица дате сопствени нагиб, боју или одмак.", "help.solid.sweep": "Повлачи профил скице дуж путање и прави тело. Користите га за цеви, шине, ручке и сваки део константног пресека који прати криву.", + "help.solid.thread": "Додаје ISO метрички навој на цилиндрично лице, као козметички навој или урезан у тело. Користите га за завртње, навојне рупе и штампане делове са навојем.", + "help.solid.torus": "Прави прстен из великог полупречника око његове осе и малог полупречника његовог округлог пресека. Користите га за О-прстенове, ручке и округле перле.", + "help.solid.web": "Додаје танак зид дуж сваке отворене криве скице, сваки испуњен до наредних лица тела. Користите је за мрежу потпорних зидова унутар кућишта и тацни.", + "help.surface.blend": "Прави површ која премошћује ивице два тела, тангентно или непрекидно по закривљености са оба. Користите је да глатко спојите две површи преко размака.", + "help.surface.boundary": "Прави површ која испуњава петљу од две до четири криве скице или мрежу кривих. Користите је за слободне панеле дефинисане њиховим ивицама.", + "help.surface.extend": "Продужава површ преко њених ивица, за растојање или до равни или лица. Користите га да се површи преклопе пре него што их одсечете или сашијете.", + "help.surface.extrude": "Извлачи криве или профиле скице дуж растојања у површ, само зидове, без поклопаца. Користите је за танке зидове и за алате за сечење или поделу.", + "help.surface.fair": "Углађује унутрашњост слободних лица док њихове ивице остају на месту. Користите га да изравнате избочине и таласасте одблеске на површи.", + "help.surface.loft": "Прави површ која редом пролази кроз два или више профила, без поклопаца. Користите је за љуске и прелазе између различитих облика.", + "help.surface.match": "Поново гради ивицу површи тако да се поклопи са ивицом другог тела, уз одговарајућу тангентност или закривљеност. Користите га да глатко затворите шав између две површи.", + "help.surface.offset": "Прави копију лица на растојању дуж њихових нормала, као ново површинско тело. Користите је за опне, зазоре или другу страну зида.", + "help.surface.patch": "Испуњава област скице или затворену петљу ивица лицем, равним или глатко закривљеним. Користите је да затворите рупе у површинском телу.", + "help.surface.reverse_normal": "Преврће лица површинског тела, тако да њихова спољна страна гледа на другу страну. Користите га пре подебљавања или сашивања када лица гледају ка унутра.", + "help.surface.revolve": "Окреће криве или профиле скице око осе у површ, без поклопаца. Користите је за округле љуске као што су абажури, посуде и млазнице.", + "help.surface.ruled": "Прави траку од правих линија из ланца ивица, дуж нормале лица, тангенте или под углом. Користите је за зидове са нагибом, прелазе и површи раздвајања.", + "help.surface.stitch": "Шије површинска тела заједно дуж њихових заједничких ивица, у тело када се затворе. Користите га да скуп површи претворите у једно тело.", + "help.surface.sweep": "Помера криве или профиле скице дуж путање у површ, без поклопаца. Користите је за олуке, лајсне и друге танке облике који прате путању.", + "help.surface.thicken": "Даје површинском телу дебљину и претвара га у пуно тело. Користите га да од површи направите делове погодне за штампу или обраду.", + "help.surface.trim": "Сече површ помоћу равни, друге површи или кривих скице и задржава страну коју изаберете. Користите га да површи обликујете сечењем пре сашивања.", + "help.surface.unstitch": "Раздваја лица тела у засебна површинска тела; пуно тело се распада на површи. Користите га да прерадите појединачна лица тела.", + "help.surface.untrim": "Уклања рупе са лица или враћа његову спољну границу на природне границе површи. Користите га да вратите целу површ након одсецања.", "help.third_party": "Лиценце трећих страна", "help.timeline.compute_all": "Поново гради сваку операцију на временској траци од почетка. Користите га да освежите модел и видите које операције не успевају.", "help.timeline.delete": "Брише изабране операције са временске траке; брисање скице брише и операције направљене из ње. Користите га да уклоните корак који више не желите.", + "help.timeline.dependents": "Наводи операције које би биле избрисане заједно са једном операцијом и оне које не би успеле без ње. Користите га пре брисања или промене операције.", "help.timeline.play": "Поново репродукује преостале операције једну по једну, са паузом од пола секунде након сваке обнове. Покрените ову команду поново или притисните Escape да зауставите; Иди на крај одмах скаче на крај.", + "help.view.apply": "Окреће приказ у стандардни смер, као што су предњи, горњи или изометријски, или на сачувани именовани приказ. Користите га да модел гледате из одређеног угла.", + "help.view.delete": "Брише сачувани именовани приказ. Модел се не мења.", + "help.view.fit": "Зумира и помера приказ тако да цео модел, или избор, испуни приказ. Користите га када је модел ван видног поља.", + "help.view.grid": "Приказује или сакрива мрежу у прозору приказа. Користите је као водич за величину и оријентацију током моделовања.", + "help.view.ground_shadow": "Приказује или сакрива сенку модела на подлози. Користите је да лакше процените висину и положај.", + "help.view.home": "Враћа приказ на почетни смер и уклапа модел. Користите га да се брзо вратите на познати приказ.", + "help.view.list": "Наводи именоване приказе сачуване у дизајну. Користите га да пронађете приказ који сте раније сачували.", + "help.view.navigate": "Окреће, помера или зумира приказ по корацима, на пример четвртином окрета улево. Користите га да прецизно померате камеру уместо превлачења.", + "help.view.navigation_bar": "Приказује или сакрива навигациону траку на дну прозора приказа. Сакријте је за више простора, а прикажите је да алатима приказа приступате мишем.", + "help.view.rename": "Даје сачуваном именованом приказу нови назив. Сам приказ остаје исти.", + "help.view.save": "Чува тренутни положај камере као именовани приказ у дизајну. Користите га да се касније вратите на исти угао, на пример за снимке екрана.", + "help.view.spin": "Непрекидно орбитира приказ око модела до следећег клика или тастера. Користите га да представите модел са свих страна.", + "help.view.tool": "Закључава алат камере, орбитирање, померање или зумирање, па превлачење левим дугметом миша помера приказ док га не искључите. Користите га на додирној табли или без средњег дугмета миша.", + "help.view.visual_style": "Мења начин на који се модел исцртава: осенчено са ивицама или без њих, жичани модел или са скривеним ивицама. Користите жичани модел да видите унутра, а осенчено за чист изглед.", "history.sketch_under_constrained": "Недовољно ограничено ({count} степени слободе)", "history.sketch_under_constrained_one": "Недовољно ограничено ({count} степен слободе)", "hole_presets.confirm_delete": "Потврди брисање", @@ -1531,6 +1837,8 @@ "joint_move.blocked_hint": "Проверите врсту споја (на пример Круто), учвршћивање, границе споја и вредности које покрећу параметри.", "joint_move.blocked_title": "Овај део се не може померити", "joint_move.coarse": "Корак ротације близу осе (°)", + "joint_move.conflict": "Један спој овог дела је у сукобу са осталима: {joint}.", + "joint_move.conflict_hint": "Измените, потисните или избришите спој који је у сукобу да би остали спојеви могли да поставе део.", "joint_move.distance": "Растојање од почетка", "joint_move.done": "Готово", "joint_move.fine": "Корак ротације далеко од осе (°)", @@ -1602,6 +1910,10 @@ "material.selection.mixed": "Различити материјали", "measure.at": "На", "measure.item": "Ставка {number}", + "measure.quick_copied": "Мерење је копирано", + "measure.quick_copy": "Кликните да копирате мерење", + "measure.quick_edges": "Ивица: {count}", + "measure.quick_faces": "Лица: {count}", "messages.ago_h": "пре {n} h", "messages.ago_min": "пре {n} min", "messages.ago_s": "пре {n} s", @@ -1626,6 +1938,8 @@ "motion.track_name": "Стаза {number}", "nav.alias.help": "Shift+Alt+превлачење левим дугметом орбитира, Shift+Alt+средњим помера, Shift+Alt+десним зумира; превлачење средњим дугметом такође помера, а десним орбитира", "nav.blender.help": "Превлачење средњим дугметом орбитира, Shift+средње помера, Ctrl+средње зумира; превлачење десним дугметом не дира камеру", + "nav.creo.help": "Превлачење средњим дугметом орбитира, Shift+средње помера, Ctrl+средње уз вертикално превлачење зумира (надоле за приближавање); точкић такође зумира", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Миш и 3D миш ротирају кроз оба пола и чувају нагиб. Привлачење оса тастером Shift је искључено.", "nav.free_orbit.label": "Слободно орбитирање", "nav.free_orbit.snap_help": "Миш и 3D миш ротирају кроз оба пола и чувају нагиб. Држите Shift током превлачења за орбитирање да привучете смер погледа и нагиб.", @@ -1635,6 +1949,7 @@ "nav.hfss.help": "Alt+превлачење левим тастером помера, Shift+Alt+леви зумира, Ctrl+превлачење левим на празном простору орбитира", "nav.inventor.help": "Превлачење средњим дугметом помера, Shift+средње орбитира, Ctrl+средње зумира, превлачење десним орбитира", "nav.maya.help": "Alt+превлачење левим орбитира, Alt+средњи помера, Alt+десни зумира; превлачење средњим такође помера", + "nav.nx.help": "Превлачење средњим дугметом орбитира, Shift+средње помера (у NX-у средње + десно), Ctrl+средње зумира (у NX-у средње + лево); превлачење десним дугметом не дира камеру", "nav.openscad.help": "Превлачење левим дугметом по празном простору орбитира, Shift+превлачење левим бира оквиром, превлачење геометрије скице је мења; превлачење десним или средњим дугметом помера, Shift+десно или Shift+средње зумира", "nav.perspective.sketch": "Измена скице користи ортографски приказ. Завршите скицу да пребаците на перспективу.", "nav.right_drag_orbits.help": "Искључено: превлачење десним дугметом не дира камеру, а десно дугме само отвара контекстни мени. Избор SolidWorks мапирања миша га искључује.", @@ -1754,6 +2069,11 @@ "not a move": "није померање", "not a number": "није број", "open a sketch first": "прво отворите скицу", + "parameters.apply_live": "Примени сваку измену чим напустите њено поље", + "parameters.apply_live_tip": "Искључено: измене чекају на Примени или У реду, а затим се дизајн једном поново гради за све њих. Откажи или Esc их одбацује.", + "parameters.held": "Измена на чекању за Примени: {count}", + "parameters.held_hint": "Мењајте изразе и јединице. Измене чекају на Примени или У реду.", + "parameters.held_one": "1 измена на чекању за Примени", "parts.automatic_name": "аутоматски", "parts.dimension.across_flats": "Отвор кључа", "parts.dimension.bore": "Отвор", @@ -1772,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Завртањ са полуоблом главом и унутрашњим шестоугаоником", "parts.family.dowel_pin": "Паралелни клин (колчић)", "parts.family.hex_bolt": "Завртањ са шестоугаоном главом", + "parts.family.hex_cap_screw_inch": "Завртањ са шестоугаоном главом (инч)", "parts.family.hex_nut": "Шестоугаона навртка", + "parts.family.hex_nut_inch": "Шестоугаона навртка (инч)", "parts.family.set_screw": "Завртањ без главе са унутрашњим шестоугаоником, равног врха", "parts.family.socket_head_cap_screw": "Завртањ са цилиндричном главом и унутрашњим шестоугаоником", "parts.family.washer": "Обична подлошка", + "parts.family.washer_sae": "Обична подлошка, SAE (уска)", + "parts.family.washer_uss": "Обична подлошка, USS (широка)", + "parts.holes": "Рупе (необавезно)", + "parts.placement_hint": "изаберите једну или више рупа да у сваку поставите део, или У реду поставља део у исходиште", + "parts.system": "Систем јединица", + "parts.system.inch": "Инчни", + "parts.system.metric": "Метрички", "pattern.alignment_2": "Поравнање 2", "pattern.alignment_hint": "Број укључује оригинал. Центар равномерно распоређује копије; Обрни бира додатну страну за парне укупне бројеве.", "pattern.direction_1": "Смер 1", @@ -1828,6 +2157,8 @@ "prefs.bottom_centre": "Доле у средини", "prefs.bottom_right": "Доле десно", "prefs.browser": "Стабло модела", + "prefs.browser_eye_left": "Око поред стрелице за скупљање", + "prefs.browser_eye_left_note": "Редови стабла модела приказују око за приказивање/скривање поред стрелице за скупљање, као раније, уместо у колони на десном крају редова.", "prefs.browser_reveal_on_hover": "Прикажи при преласку мишем", "prefs.browser_show_note": "Приказано држи стабло модела на екрану. Прикажи при преласку мишем га скрива док показивач не дође на његово место или на танак језичак на његовој левој ивици, а остаје отворено док је показивач у њему или док је отворен мени из њега.", "prefs.browser_shown": "Приказано", @@ -1835,6 +2166,8 @@ "prefs.button_left": "Превлачење левим дугметом", "prefs.button_middle": "Превлачење средњим дугметом", "prefs.button_right": "Превлачење десним дугметом", + "prefs.carousel_next": "Следеће", + "prefs.carousel_previous": "Претходно", "prefs.choose_font": "Изабери датотеку фонта…", "prefs.click": "Клик", "prefs.contact_shading": "Меко сенчење додира", @@ -1847,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Закривљене површи", "prefs.curves": "Закривљене површи", + "prefs.cut_preview_tint": "Прикажи уклоњени материјал у црвеној боји", + "prefs.cut_preview_tint_help": "Преглед испуњава материјал који операција уклања и облик који замењује црвеном провидном сенком. Када је искључено, те испуне су потпуно провидне и цртају се само њихови обриси.", + "prefs.dark_parts_shading": "Задржи облик тамних делова", + "prefs.dark_parts_shading_help": "Сенчи приказ у линеарном светлу уз меко допунско светло неба, тако да тамна лица задрже градијент уместо да поцрне", "prefs.dead_zone_note": "Шрафирана трака је мртва зона: кретање унутар ње се занемарује.", "prefs.default": "подразумевано", "prefs.design": "Подразумевана подешавања дизајна", @@ -1861,6 +2198,8 @@ "prefs.edges": "Ивице и сенчење", "prefs.extend": "Продужи", "prefs.extra_navigation": "Ctrl + превлачење левим дугметом по празном простору орбитира; држите размакницу за померање.", + "prefs.extrude_view_isometric": "Окрени приказ у изометријски када се отвори Екструдирај", + "prefs.extrude_view_return": "Врати се на претходни приказ када се Екструдирај затвори", "prefs.follows_os": "Прати оперативни систем", "prefs.font": "Фонт", "prefs.font_fallback": "Знакови који недостају изабраном фонту приказују се уграђеним фонтом, тако да ниједна ознака не приказује празан квадрат.", @@ -1876,8 +2215,11 @@ "prefs.graphics_card_auto": "Аутоматски", "prefs.graphics_card_missing": "Сачувана графичка картица није доступна; користи се Аутоматски.", "prefs.graphics_card_restart": "Ступа на снагу након поновног покретања SolidCraft-а. WGPU_ADAPTER_NAME има предност над овим избором.", + "prefs.graphics_card_unused": "Сачувана графичка картица није коришћена за овај прозор; картица која се користи приказана је у Помоћ › О програму и у статусној траци. Покушајте са опцијом Аутоматски или поставите WGPU_ADAPTER_NAME на јединствени део назива картице.", "prefs.graphics_note": "Жртвујте брзину за глаткоћу. Сваки избор показује свој учинак на примеру.", "prefs.graphics_presets_note": "Унапред подешене вредности подешавају све изборе испод одједном.", + "prefs.hide_constraint_glyphs_zoomed_out": "Сакриј симболе ограничења када је приказ умањен", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Симболи ограничења нестају из приказа када је скица толико умањена да би је затрпали. Искључено: остају фиксне величине на екрану при сваком зумирању.", "prefs.history": "Временска трака", "prefs.history_origin_bodies": "Прикажи исходиште и тела на врху", "prefs.history_origin_bodies_note": "Временска трака лево или испод стабла модела почиње фасциклом Тела активне компоненте и Исходиштем, са њиховим оком и менијима као у стаблу модела. Временска трака на дну остаје непромењена.", @@ -1888,6 +2230,8 @@ "prefs.history_sketches_note": "Када је Скице подешено на Испод своје операције, временска трака лево приказује сваку скицу један ниво увучено, испод прве операције направљене из ње, кад год је довољно широка за називе. Временска трака на дну увек задржава редослед настанка.", "prefs.history_sketches_under_feature": "Испод своје операције", "prefs.hold_stop_snapping": "Држите да искључите привлачење", + "prefs.home_fit_size": "Величина за Почетни приказ и Уклопи", + "prefs.home_fit_size_note": "Колики део приказа модел испуњава када га уоквири Почетни приказ, Уклопи, отварање дизајна или промена приказа у навигатору, без обзира на то да ли је подешавање испод укључено. 100 %: испуњава приказ између панела, компаса и навигационе траке.", "prefs.icons_only": "Само иконе", "prefs.imported_file": "Увезена датотека", "prefs.in_browser": "У стаблу модела", @@ -1896,13 +2240,22 @@ "prefs.interface_language": "Језик интерфејса", "prefs.interface_note": "Како SolidCraft изгледа и где су његови делови.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Обрни закривљене стрелице за ваљање", + "prefs.invert_curved_roll_arrows_note": "Две закривљене стрелице у углу коцке ваљају приказ унутар равни екрана. Укључено: стрелица у смеру казаљке на сату ваља приказ супротно од смера казаљке на сату, а стрелица супротно од смера казаљке на сату ваља га у смеру казаљке на сату. Искључено: свака стрелица ваља приказ онако како је закривљена.", + "prefs.invert_navigator_arrows": "Обрни стрелице за ротацију коцке приказа", + "prefs.invert_navigator_arrows_note": "Стрелице око коцке орбитирају камеру у смеру у којем показују, као у програмима Fusion и Inventor: стрелица са леве стране показује удесно и закреће камеру удесно. Искључено: стрелица окреће коцку ка страни на којој се налази, па лева стрелица закреће камеру улево. Подешавање не утиче на закривљене стрелице за ваљање.", + "prefs.keep_work_on_tab_switch": "Задржи дијалоге и алате отвореним при пребацивању између дизајна", + "prefs.keep_work_on_tab_switch_note": "Свака картица дизајна задржава свој отворени дијалог или алат, са оним што сте у њему изабрали и уписали, те своју картицу траке са алатима. Када се вратите на дизајн, поново су ту. Искључено: пребацивање између дизајна отказује их и приказује картицу Модел.", "prefs.labels": "Ознаке", + "prefs.language_system": "Систем", "prefs.layout": "Распоред", "prefs.layout_note": "Компактно причвршћује панеле уз ивице прозора. Провидност стабла модела доступна је у опцији Плутајуће. Страну Асистента промените на страници Асистент.", "prefs.left": "Лево", "prefs.left_click": "Леви клик", "prefs.line_drag_draws_one": "Притисак и превлачење цртају једну линију", "prefs.line_drag_draws_one_note": "У алату Линија, притисак, превлачење и пуштање цртају једну линију од места притиска до места пуштања и ту се завршава. Кликови и даље цртају ланац. Искључено: превлачење поставља тачку где се пусти, као и клик.", + "prefs.line_hover_tangent_arc": "Задржите показивач на последњој тачки линије да пређете на тангентни лук", + "prefs.line_hover_tangent_arc_note": "У алату Линија, након што је нацртан сегмент, одмакните показивач од последње тачке ланца, вратите га на њу и држите га мирно: следећи клик завршава тангентни лук, а исти покрет враћа на линије. Искључено: задржавање на тој тачки не ради ништа.", "prefs.linked_designs": "Повезани дизајни", "prefs.live_input": "Улаз уживо", "prefs.live_preview": "Преглед уживо", @@ -1916,6 +2269,9 @@ "prefs.max_file_size_step": "STEP и датотеке за увоз", "prefs.max_file_size_web": "Веб апликација отвара STEP и датотеке за увоз до 512 MB и дизајне до 256 MB: картица прегледача не може да садржи веће датотеке. Десктоп апликација може да повећа ова ограничења.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Велике иконе", + "prefs.menu_list": "Списак", + "prefs.menus": "Менији", "prefs.minutes": "минута", "prefs.minutes_suffix": " min", "prefs.mouse": "Миш и додирна табла", @@ -1923,6 +2279,8 @@ "prefs.mouse_mapping": "Мапирање миша", "prefs.navigation": "Навигација", "prefs.navigation_note": "Како миш, додирна табла и 3D миш померају приказ.", + "prefs.navigator_fit": "Уклопи модел након промене приказа у навигатору", + "prefs.navigator_fit_note": "Лице, угао или стрелица коцке приказа, односно оса гизма оријентације, такође усмерава поглед на средину модела са једног растојања на којем се уклапа из сваког смера (његова гранична сфера). Почетни приказ користи исти зум и центар док је ова опција укључена, па се прикази које изаберете после њега само окрећу. Искључено: приказ се окреће на месту и задржава свој циљ и зум.", "prefs.network_host_remove": "Уклони", "prefs.network_locations": "Дозволи мрежне локације у дизајнима", "prefs.network_locations_note": "Искључено: повезане датотеке дизајна на другом рачунару (\\\\server\\share) отварају се само са сервера наведених овде или након што га дозволите када се то затражи.", @@ -1935,10 +2293,18 @@ "prefs.origin_plane_names": "Називи равни исходишта", "prefs.origin_plane_names_note": "Називи приказани у стаблу модела, дијалозима и листама. {top} је XY, {front} је XZ, а {right} је YZ, са Z нагоре. Команде, скрипте и сачувани дизајни задржавају XY, XZ и YZ.", "prefs.overall_speed": "Укупна брзина", + "prefs.parameter_list_rows": "Редови на списку параметара", + "prefs.parameter_list_rows_tip": "Стрелица надоле у празном пољу вредности наводи параметре, прво омиљене, до овог броја. Мањи број држи списак лаким у великом дизајну.", + "prefs.persistent_ribbon_pressed": "Истакни активне команде на траци", + "prefs.persistent_ribbon_pressed_help": "Истиче команде на траци док су њихови ефекти укључени. Искључите да бисте задржали претходни неутрални изглед и помоћ за команде.", "prefs.perspective_fov": "Видно поље", "prefs.placement": "Постављање", "prefs.prefer_free_sketch_points": "Дај предност покретним тачкама скице када се тачке преклапају", "prefs.preview_choices": "Преглед ваших избора", + "prefs.preview_tint_new_faces": "Обоји нову површ у прегледу", + "prefs.preview_tint_new_faces_help": "Преглед операције која мења тело може да нацрта површ коју додаје у боји прегледа. Када је искључено, тело се црта какво јесте.", + "prefs.print_face_highlight": "Истицање површине за штампу", + "prefs.print_face_highlight_tip": "Колико се јако површина за штампу тела боји и обрубљује у приказу. 0 % не приказује истицање.", "prefs.profile_active": "Активни профил", "prefs.profile_applied": "Профил је примењен.", "prefs.profile_changed": "Подешавања су промењена откако је профил сачуван. Притисните Сачувај да их задржите у њему.", @@ -1960,9 +2326,13 @@ "prefs.quality_fastest": "најбрже", "prefs.quality_slowest": "најспорије", "prefs.quality_smoother": "глађе", + "prefs.quick_measure": "Брзо мерење у углу приказа", + "prefs.quick_measure_note": "Величина избора у доњем десном углу приказа: дужина ивице, или Ø и R за округлу, површина лица, положај тачке, растојање и угао две ставке, збир неколико ивица или лица. Клик га копира.", "prefs.render_previous_geometry_budget": "Користи претходни буџет геометрије за преглед у Рендеровању", "prefs.render_previous_geometry_budget_help": "Враћа претходно фиксно ограничење геометрије (512 MiB на 64-битним десктоп рачунарима, 128 MiB другде) уместо буџета према уређају.", "prefs.reports_saved": "Сачувано: {n}", + "prefs.ribbon_click_ends_tool": "Клик на дугме активног алата завршава га", + "prefs.ribbon_click_ends_tool_note": "Клик на истакнуто дугме на траци алата за скицирање који је у употреби завршава тај алат, па кликови у приказу поново служе за избор. Искључено: клик поново покреће алат.", "prefs.ribbon_reveal": "Прикажи резултате претраге на траци", "prefs.ribbon_reveal_note": "Задржавање показивача изнад резултата у Претражи команде показује где се команда налази на траци: њену картицу, њено дугме или њен ред у падајућем менију панела. Команда покренута из претраге тамо трепери, а покренута команда из падајућег менија означава свој панел.", "prefs.right_click": "Десни клик", @@ -1973,6 +2343,8 @@ "prefs.search_empty": "Нема одговарајућих подешавања", "prefs.select": "Избор", "prefs.select_one_item": "Изабери једну ставку", + "prefs.select_other_hidden": "Изабери скривену геометрију помоћу Изабери друго", + "prefs.select_other_hidden_help": "Укључено: обухвата скривена тела, скице и заклоњене ивице у близини показивача. Искључено: користи се изворни списак видљиве геометрије испод показивача.", "prefs.selecting": "Бирање", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift само додаје; Ctrl / Cmd укључује и искључује", @@ -1984,11 +2356,16 @@ "prefs.sketch_align_points_note": "Током цртања тачка се истовремено поравнава хоризонтално са једном тачком скице и вертикално са другом, уз тачкасти водич, а клик задржава оба поравнања. Искључено: само са претходном тачком, по једна оса.", "prefs.sketch_conflict_colour": "Геометрија у сукобу у боји сукоба", "prefs.sketch_conflict_colour_note": "Док су ограничења скице у сукобу, криве и тачке које држи ограничење које не успева исцртавају се такође у боји сукоба, а не само његов симбол или кота. Искључено: задржавају уобичајене боје.", + "prefs.sketch_construction_lines": "Проширени алати за помоћне праве", "prefs.sketch_exit_view": "Када се скица заврши", "prefs.sketch_exit_view.keep": "Задржи тренутни приказ", "prefs.sketch_exit_view.previous": "Врати се на претходни приказ", "prefs.sketch_exit_view.unless_rotated": "Врати се осим ако је ротирано", "prefs.sketch_exit_view_note": "Куда приказ иде након Заврши скицу, Откажи или двоструког Esc.", + "prefs.sketch_face_activates_part": "Скицирање на лицу дела чини тај део активним", + "prefs.sketch_face_activates_part_note": "Скица започета на лицу тела друге компоненте прво активира ту компоненту, па скица припада њој и у стаблу модела остаје уз тај део. Тај део након тога остаје активан. Искључено: скица припада активној компоненти.", + "prefs.sketch_open_look_at": "Окрени камеру према скици када се отвори", + "prefs.sketch_open_look_at_note": "Искључено: када направите или измените скицу, приказ остаје онакав какав јесте. Погледај окреће приказ према скици када то желите.", "prefs.sketch_recent_snap": "Аутоматски привлачи на недавне центре и средишње тачке", "prefs.sketch_recent_snap_note": "Током цртања показивач се привлачи тамо где се секу водичи двају последњих центара кругова или средишњих тачака правих ивица. Искључено: ти водичи служе само за приказ и показивач се не помера.", "prefs.sketch_selection": "Скица и избор", @@ -2000,6 +2377,8 @@ "prefs.sketch_tab_always_note": "Картица Скица остаје на траци, одмах после картице Модел, док ниједна скица није отворена. Њени алати за цртање тада започињу скицу на изабраној равни или лицу, или на равни коју следећу изаберете, са спремним алатом у њој.", "prefs.sketch_tracking_guides": "Водичи за поравнање центра и средишње тачке", "prefs.sketch_tracking_guides_note": "Задржите показивач изнад центра круга или средишта праве ивице, па се померите хоризонтално или вертикално да би се приказао привремени тачкасти водич.", + "prefs.sketch_tracking_points": "Водичи за поравнање од крајњих тачака и углова током цртања", + "prefs.sketch_tracking_points_note": "Док алат за цртање чека на тачку, задржавање показивача изнад краја линије или лука, угла правоугаоника или слободне тачке приказује исти привремени тачкасти водич као код центра или средишње тачке. Искључено: само центри и средишње тачке.", "prefs.sketching": "Скицирање", "prefs.snap_drawing_note": "Током цртања или превлачења тачке скице.", "prefs.source": "Извор", @@ -2016,6 +2395,24 @@ "prefs.status_error": "Грешка", "prefs.status_selected": "Изабрано", "prefs.status_warning": "Упозорење", + "prefs.structure.appearance": "Изглед", + "prefs.structure.appearance_note": "Боје, текст и приступачност.", + "prefs.structure.in_profile": "У профилу", + "prefs.structure.layout": "Распоред", + "prefs.structure.layout_note": "Где се налазе делови прозора.", + "prefs.structure.look": "Визуелно", + "prefs.structure.measure_pointer": "Мерење и показивач", + "prefs.structure.mouse3d": "3D миш", + "prefs.structure.mouse3d_note": "SpaceMouse и SpaceNavigator.", + "prefs.structure.navigation_note": "Миш и додирна табла. 3D миш има сопствену страницу.", + "prefs.structure.profile": "Профил", + "prefs.structure.profile_edited": "Промењено откако је сачувано", + "prefs.structure.profile_hover": "Сачувано у профилима подешавања", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Скица", + "prefs.structure.tools": "Алати", + "prefs.structure.tools_note": "Како се понашају алати за моделовање.", + "prefs.structure.work": "Рад", "prefs.supersampling_brief": "Исцртава приказ већим и смањује га филтрирањем: веома оштро и захтевније.", "prefs.tab_accent_note": "Нагласна боја прати активну картицу", "prefs.theme_file": "датотека теме", @@ -2027,6 +2424,16 @@ "prefs.theme_follow_off": "Искључено", "prefs.theme_follow_stop": "Престани да пратиш", "prefs.theme_import_hint": "Кликните да изаберете датотеку теме, превуците је овде или притисните Ctrl+V (Cmd+V на Mac рачунару) када је тема копирана", + "prefs.theme_option_opacity": "Непрозирност", + "prefs.theme_option_opacity_help": "Подесите непрозирност плутајућих панела. Доња граница читљивости штити текст преко боја прозора приказа.", + "prefs.theme_option_tab_colours": "Боје картица", + "prefs.theme_option_tab_colours_help": "Користи боје панела и прозора приказа ове теме за сваку картицу на траци.", + "prefs.theme_option_tab_fade_ms": "Прелаз између картица", + "prefs.theme_option_tab_fade_ms_help": "Постепено мења боје панела и прозора приказа при промени картице. Нула прелази одмах.", + "prefs.theme_options_badge": "Опције", + "prefs.theme_options_more": "Више · {count}", + "prefs.theme_options_reset": "Ресетуј", + "prefs.theme_options_unavailable": "Није доступно на овом уређају", "prefs.theme_paste": "Налепи тему", "prefs.theme_paste_none": "Клипборд не садржи SolidCraft тему", "prefs.timeline_half_hour": "−30 min", @@ -2048,13 +2455,23 @@ "prefs.under_cursor": "Испод показивача", "prefs.units_precision": "Јединице и прецизност", "prefs.updates": "Ажурирања", + "prefs.value_boxes_in_view": "Прикажи вредности поред њихових ручица у приказу", + "prefs.value_boxes_in_view_tip": "Вредност команде (Растојање, Полупречник…) у пољу поред њене ручице, преко модела. Искључено: уносите је у прозору команде, који преузима тастатуру након избора, а ништа не прекрива модел.", "prefs.view": "Понашање приказа", "prefs.view_confirm_corner": "У реду и Откажи у углу приказа", "prefs.view_confirm_corner_note": "Док је отворен дијалог или скица, квачица и крстић горе десно у приказу раде исто што и дугмад У реду и Откажи у дијалогу, односно завршавају и отказују скицу. Навигатор приказа помера се испод њих.", "prefs.viewport": "Прозор приказа", + "prefs.viewport_analysis_status": "Прикажи статус анализе у прозору приказа", + "prefs.viewport_analysis_status_help": "Приказује активне анализе изнад прозора приказа, отвара њихове легенде из сваке ставке, а тастер Esc искључује најновију анализу. Искључите да бисте вратили легенде у угловима и претходно понашање тастера Esc.", "prefs.viewport_background": "Позадина", "prefs.viewport_background_colour": "Боја", "prefs.viewport_background_theme": "Градијент теме", + "prefs.viewport_section_status": "Прикажи статус пресека у прозору приказа", + "prefs.viewport_section_status_help": "Приказује подешавање пресека у прозору приказа. Esc и активно дугме на траци га искључују. Искључите да задржите претходне контроле пресека.", + "prefs.viewport_status_details": "Детаљи прозора приказа уживо", + "prefs.viewport_status_details_help": "Мењајте подешавања активне анализе и пресека у стандардним картицама са детаљима. Искључите да вратите легенде анализе само за читање и дијалог Пресек.", + "prefs.viewport_status_summary": "Сажми ставке статуса у прозору приказа", + "prefs.viewport_status_summary_help": "Сажима три или више ставки статуса у прозору приказа у једну збирну значку. Искључите да свака ставка остане у пуном реду.", "prefs.wheel": "Точкић", "prefs.wheel_trackpad": "Точкић и додирна табла", "prefs.workspace": "Радни простор", @@ -2064,6 +2481,10 @@ "properties.title": "Својства: {name}", "recovery.days_ago": "пре {count} дана", "recovery.detail": "{file} · операција: {features} · аутоматски сачувано {when}", + "recovery.discard_all": "Одбаци све", + "recovery.discard_all_detail": "Ово се не може поништити.", + "recovery.discard_all_title": "Одбацити аутоматска чувања ({count})?", + "recovery.discard_all_title_one": "Одбацити 1 аутоматско чување?", "recovery.hours_ago": "пре {count} h", "recovery.just_now": "управо сада", "recovery.min_ago": "пре {count} min", @@ -2179,6 +2600,10 @@ "render.base_color": "Основна боја · sRGB", "render.base_metallic": "Метални удео", "render.base_opaque_only": "Овај уређивач чува семантику непрозирних тела. За оптичко пропуштање користите изричите контроле стакла.", + "render.batch_all_shots": "Сви кадрови ({count})", + "render.batch_empty": "Сачувајте кадар пре рендеровања свих кадрова.", + "render.batch_limit": "Рендеровање свих кадрова ограничено је на 32 кадра.", + "render.batch_status": "У току: {running} · На чекању: {waiting}", "render.bloom_enable": "Сјај приказа", "render.bloom_help": "Креативни сјај само на излазу из позитивних линеарних светлих делова, раширен кроз три нормализована пролаза кутијастог филтера. Полупречник је у пикселима излаза. Додаје се у линеарној светлости приказа пре sRGB-а; није објектив, волуметријски ефекат нити побољшање конвергенције. Сирови EXR остаје непромењен.", "render.bloom_opaque": "Сјај захтева непрозирни излаз. Провидни PNG се одбија, а не спљоштава тихо.", @@ -2289,6 +2714,13 @@ "render.choose_look": "Прво изаберите изглед у Изгледима", "render.chromatic_offset": "Хроматски помак ивица", "render.clear_stage": "Уклони сачувану сцену", + "render.compare_divider": "Разделник поређења", + "render.compare_live": "Уживо", + "render.compare_live_preview": "Преглед уживо", + "render.compare_render": "Рендер {number}", + "render.compare_side": "Рендер {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · забележено у ревизији {revision}", + "render.compare_swap": "Замени стране", "render.copy_request": "Копирај JSON", "render.cpu_aa_help": "Просторни узорци: више узорака побољшава ивице и продужава рендеровање.", "render.cpu_area_add": "Додај правоугаоно CPU светло", @@ -2929,7 +3361,9 @@ "render.output_ready": "Спремно за рендеровање", "render.output_run_check": "Покрени проверу", "render.output_size_limit": "{method}: до {dimension} px по страни и {pixels} пиксела. Највећа величина која стаје: {width} × {height}.", + "render.output_size_method_profile": "Да бисте рендеровали {width} × {height}, изаберите {method} са CPU профилом ресурса {profile}, или мању величину.", "render.output_size_ok": "Величина је у реду · {width} × {height} px", + "render.output_size_profile": "Да бисте рендеровали {width} × {height}, изаберите CPU профил ресурса {profile}, или мању величину.", "render.output_swap_orientation": "Замени ширину и висину", "render.output_tools_inspector": "Величину и формат измените у инспектору Излаз.", "render.output_view_image": "Прикажи слику", @@ -3036,6 +3470,10 @@ "render.result_retained": "Приказује се последња завршена слика; новије рендеровање је још није заменило.", "render.result_sequence": "Контролна тачка", "render.result_title": "Резултат рендеровања", + "render.results_choose": "Задржани резултати", + "render.results_label": "Рендер {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [застарео]", + "render.results_unnamed": "Слика", "render.return_design": "Назад на Дизајн", "render.review_stale": "Овај преглед је застарео. Решите га или поново проверите пре примене.", "render.ribbon_aging": "Старење", @@ -3142,6 +3580,7 @@ "render.size_custom": "Прилагођено…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · захтева {profile}", "render.size_presets": "Унапред подешене величине", "render.size_presets_pending": "Стиже са уређивачем излаза", "render.size_preview": "Преглед", @@ -3429,6 +3868,24 @@ "sheet.flange_type_contour": "Контура", "sheet.flange_type_edge": "Ивица", "sheet.no_body": "нема лименог тела: направите га помоћу Прирубница > Основа или претворите плочу у лим помоћу Претвори у лим (изаберите њено велико равно лице)", + "sheet.personal_rules.confirm_delete": "Потврди брисање", + "sheet.personal_rules.delete": "Избриши", + "sheet.personal_rules.delete_prompt": "Избрисати ово лично правило? Правила која су већ у дизајнима остају непромењена.", + "sheet.personal_rules.full": "Лична библиотека већ садржи 64 правила.", + "sheet.personal_rules.invalid_name": "Унесите кратак назив без прелома реда или контролних знакова.", + "sheet.personal_rules.invalid_values": "Допуните вредности правила: свака мора да се израчуна у овом дизајну, са позитивном дебљином и K-фактором од 0 до 1.", + "sheet.personal_rules.missing": "Изабрано лично правило више није доступно.", + "sheet.personal_rules.name": "Назив правила", + "sheet.personal_rules.name_exists": "Лично правило са овим називом већ постоји. Користите други назив.", + "sheet.personal_rules.name_hint": "Јединствен назив", + "sheet.personal_rules.overwrite": "Сачувај промене у изабраном личном правилу", + "sheet.personal_rules.rename": "Преименуј", + "sheet.personal_rules.rule": "Лично правило", + "sheet.personal_rules.save": "Сачувај ново", + "sheet.personal_rules.scope": "Сачувано у вашем профилу за све дизајне.", + "sheet.personal_rules.select": "Изаберите правило", + "sheet.personal_rules.title": "Лична правила", + "sheet.personal_rules.unsupported": "Ово правило има вредности које ова верзија не може да користи.", "shortcut.json_error": "параметри морају бити JSON: {error}", "shortcut.no_command": "нема команде `{id}`; текст пре JSON-а мора бити id команде", "shortcut.pin": "Прикачи на врх S оквира", @@ -3465,8 +3922,10 @@ "sketch_text.align_right": "Десно", "sketch_text.bold": "Подебљано", "sketch_text.builtin_font": "{family} (уграђено)", + "sketch_text.formula": "Почните са = да речи саставите од параметара: ='W' + number(Width)", "sketch_text.italic": "Курзив", "sketch_text.loading_fonts": "Тражење инсталираних фонтова…", + "sketch_text.no_bold": "Уграђени фонт нема подебљану варијанту: изаберите инсталирани фонт", "sketch_text.on_path": "Текст прати своју путању: крива га поставља", "sketch_text.path_clear": "Скини текст са његове криве", "sketch_text.path_hint": "Крива скице коју текст прати: кликните овде, а затим криву", @@ -3498,10 +3957,7 @@ "the two origins are on the same component": "оба исходишта су на истој компоненти", "thread.automatic_size": "Аутоматска величина", "thread.designation": "Ознака", - "thread.direction": "Смер навоја", "thread.iso_metric": "ISO метрички", - "thread.left_hand": "Леви", - "thread.right_hand": "Десни", "thread.select_size": "Изаберите величину", "timeline.delete_after_marker_one": "Избриши 1 операцију након ознаке враћања", "timeline.delete_after_marker_other": "Избриши операције након ознаке враћања: {count}", @@ -3605,6 +4061,8 @@ "ui.3d_mouse_section": "3D миш", "ui.3d_mouse_show_in_view": "Прикажи 3D миш у 3D приказу", "ui.3d_mouse_show_in_view_tip": "Слика вашег 3D миша у доњем левом углу, која се креће док га померате.", + "ui.3d_mouse_sketch_orbit": "Окрећи скице 3D мишем", + "ui.3d_mouse_sketch_orbit_tip": "3D миш окреће приказ и док је скица отворена и гледана под правим углом, као што то може и миш. Искључено: помера и зумира скицу док не нагнете приказ.", "ui.3d_mouse_skip": "Мој уређај ово не може", "ui.3d_mouse_skip_tip": "Прескаче ово кретање у оба смера, а калибрација га изоставља.", "ui.3d_mouse_speed": "Брзина 3D миша", @@ -3633,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Закрените капицу супротно од казаљке на сату, држите је, а затим пустите.", "ui.3d_mouse_switch_cap": "Калибриши као Повратак у центар", "ui.3d_mouse_switch_trackball": "Калибриши као трекбол", + "ui.3d_mouse_use_direct": "Користи директни драјвер", + "ui.3d_mouse_use_direct_tip": "Читај 3D миш директно (hidraw) уместо преко spacenavd.", "ui.3d_mouse_view_axis": "Оса приказа", "ui.3d_mouse_view_off": "Искључено", "ui.3d_mouse_view_off_tip": "Профил драјвера 3D миша искључује ову осу, па њено кретање не помера приказ. Избор кретања друге осе овде их замењује, а то кретање престаје да помера приказ.", @@ -3671,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Покрените ово у терминалу, а затим притисните Повежи поново:", "ui.agent_chat_auth_title": "Пријави се код агента", "ui.agent_chat_cancel": "Откажи", + "ui.agent_chat_cancel_timeout": "Агент није одговорио на Заустави па је веза са њим прекинута. Поново се повежите да бисте наставили.", + "ui.agent_chat_cannot_start": "Инсталиран, али се не покреће: {error}", "ui.agent_chat_changes": "Промене: {n}, један корак поништавања", "ui.agent_chat_changes_n": "Промене: {n}", "ui.agent_chat_changes_of": "Промене: {n}/{limit}", @@ -3679,11 +4141,13 @@ "ui.agent_chat_command": "Команда агента", "ui.agent_chat_connect": "Повежи", "ui.agent_chat_copy": "Копирај", + "ui.agent_chat_copy_message": "Копирај поруку", "ui.agent_chat_ctx_bodies": "Тела", "ui.agent_chat_ctx_elements": "Елементи", "ui.agent_chat_ctx_features": "Операције", "ui.agent_chat_ctx_more": "+још {n}", "ui.agent_chat_ctx_other": "Остало", + "ui.agent_chat_custom_heading": "Прилагођени модел", "ui.agent_chat_custom_hint": "Било који програм који говори Agent Client Protocol на stdin и stdout. Не покреће га никаква љуска.", "ui.agent_chat_denied": "Одбијено", "ui.agent_chat_deny": "Одбиј", @@ -3727,8 +4191,16 @@ "ui.agent_chat_mode_all": "Све", "ui.agent_chat_mode_ask": "Питај", "ui.agent_chat_mode_edits": "Измене", + "ui.agent_chat_model_custom": "Користи прилагођени: {model}", "ui.agent_chat_model_no_tools": "{model} не може да користи SolidCraft алате, па може само да разговара. Изаберите модел са подршком за алате.", + "ui.agent_chat_model_rejected": "Агент није прихватио модел {model}: {error}", + "ui.agent_chat_model_search": "Претражи моделе…", "ui.agent_chat_model_tip": "Модел који агент користи. Ваш избор се памти за овог агента.", + "ui.agent_chat_models_failed": "Списак модела није могуће учитати: {error}", + "ui.agent_chat_models_heading": "Доступни модели", + "ui.agent_chat_models_listing": "Учитавање списка модела…", + "ui.agent_chat_models_none": "Крајња тачка не наводи ниједан модел", + "ui.agent_chat_models_not_a_list": "Одговор није списак модела", "ui.agent_chat_new": "Нови разговор", "ui.agent_chat_new_confirm": "Започети нови разговор? Тренутни ће бити обрисан.", "ui.agent_chat_next_picture": "Следећа слика", @@ -3763,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "У реду чекања (заустављено, није послато)", "ui.agent_chat_refresh": "Освежи", "ui.agent_chat_refused": "Није дозвољено агенту: {reason}", + "ui.agent_chat_reinstall": "{agent} је инсталиран ({program}), али се није покренуо када га је SolidCraft проверио: {error}\nЊегова инсталација је можда непотпуна или направљена за другу врсту рачунара. Инсталирајте га поново помоћу `{install}`, проверите да у терминалу исписује своју верзију, а затим притисните Освежи.", "ui.agent_chat_remove": "Уклони из реда", "ui.agent_chat_remove_file": "Скини са ове поруке", "ui.agent_chat_remove_imported": "Скини са ове поруке; део остаје у дизајну (Поништи га уклања)", + "ui.agent_chat_reply_cut_off": "Одговор је достигао ограничење дужине пре него што је завршен, па је можда непотпун. Затражите од агента да настави или да одговори сажетије.", + "ui.agent_chat_reply_declined": "Модел је одбио да одговори на ову поруку.", "ui.agent_chat_retry": "Покушај поново", "ui.agent_chat_right": "Десно", "ui.agent_chat_save": "Сачувај", @@ -3824,12 +4299,17 @@ "ui.ai_copy_suffix": "копирај", "ui.ai_custom_url": "Прилагођени URL", "ui.ai_default": "Подразумевано", + "ui.ai_edit": "Измени", + "ui.ai_edit_agent_title": "Измени агента", + "ui.ai_edit_gone": "Овај агент је уклоњен, па нема шта да се сачува.", + "ui.ai_edit_tip": "Промените назив, команду или крајњу тачку овог агента. Сачувани кључ остаје скривен.", "ui.ai_http_busy": "крајња тачка је заузета или је преко ограничења; покушајте поново касније", "ui.ai_http_key": "крајња тачка је одбила кључ: проверите га у Подешавања > AI", "ui.ai_http_not_found": "нема такве крајње тачке или модела: проверите основни URL и назив модела", "ui.ai_http_too_large": "разговор је превелик за ову крајњу тачку; започните нови разговор", "ui.ai_key": "API кључ", "ui.ai_key_hint": "необавезно; чува се у системском привеску кључева", + "ui.ai_key_keep_hint": "оставите празно да задржите сачувани кључ", "ui.ai_key_needs_https": "Кључ се шаље само преко HTTPS-а или на овај рачунар.", "ui.ai_key_note": "Чува се у системском привеску кључева, никад у подешавањима SolidCraft-а. За локални сервер оставите празно.", "ui.ai_keychain_error": "Системски привесак кључева је одбио: {error}", @@ -3856,11 +4336,15 @@ "ui.ai_permissions": "Дозволе", "ui.ai_preset": "Унапред подешено", "ui.ai_protocol": "Протокол", + "ui.ai_reasoning_effort": "Ниво закључивања", + "ui.ai_reasoning_effort_field_hint": "празно = подразумевана вредност пружаоца", + "ui.ai_reasoning_effort_hint": "Необавезно. Шаље се крајњој тачки као `reasoning_effort`; прихваћене вредности се разликују од пружаоца до пружаоца (на пример `low`, `high` или `max`). SolidCraft никад не мења вредност коју овде поставите. Оставите празно да се ништа не шаље и да се задржи подразумевана вредност пружаоца.", "ui.ai_remove": "Уклони", "ui.ai_request_timed_out": "Модел је трајао дуже од {seconds} s. Временско ограничење захтева за ову крајњу тачку можете повећати у Подешавања › Асистент.", "ui.ai_request_timeout": "Временско ограничење захтева", "ui.ai_request_timeout_hint": "Колико дуго један захтев моделу на овој крајњој тачки сме да траје, од 30 s до једног сата. Повећајте за спори локални модел.", "ui.ai_reset": "Ресетуј", + "ui.ai_save": "Сачувај", "ui.ai_settings": "AI подешавања…", "ui.ai_show_features": "Прикажи AI функције", "ui.ai_show_features_note": "Разговор са агентом: панел у ком агент за кодирање који већ користите или крајња тачка модела коју изаберете ради на отвореном дизајну. Искључено: нема AI дугмета, пречице, ставке менија ни панела, и ништа се не тражи нити покреће.", @@ -3949,6 +4433,7 @@ "ui.circle": "Круг", "ui.circular_pattern": "Кружни низ", "ui.clear": "Очисти", + "ui.clear_print_face": "Уклони површину за штампу", "ui.clear_recent": "Очисти недавно", "ui.clear_the_selection": "Поништи избор", "ui.click_selects_whole_bodies": "Клик бира цела тела", @@ -3983,7 +4468,17 @@ "ui.constant": "Константно", "ui.constraints_conflict": "Ограничења су у сукобу", "ui.construction": "Помоћна", + "ui.construction.angle_hint": "Помоћна права: кликните тачку, па упишите угао или изаберите смер", + "ui.construction.bisector_hint": "Симетрала: изаберите две праве линије које се секу, па жељено решење", + "ui.construction.common_hint": "Заједничка тангента: изаберите два круга или лука, па жељено решење", + "ui.construction.contact_hint": "Тангента: изаберите круг/лук или отворени сплајн/конику, па тачку додира (криве слободног облика: крајње тачке)", + "ui.construction.external_hint": "Тангента: изаберите круг или лук, спољашњу тачку, па жељено решење", + "ui.construction.free_hint": "Помоћна права: кликните две тачке; десним кликом почните испочетка", + "ui.construction.normal_needs_length": "Бесконачна линија је увек помоћна: упишите дужину да бисте нацртали обичну линију", + "ui.construction.point_hint": "Помоћна права: кликните тачку кроз коју пролази", + "ui.construction.reference_hint": "Помоћна права: изаберите праву линију, па тачку; десним кликом промените референцу", "ui.construction.ribbon_label": "Пом. праве", + "ui.construction.side_hint": "Помоћна права: кликните страну ка којој линија иде; десним кликом почните испочетка", "ui.context_menu": "Контекстни мени", "ui.continuity_g0": "G0 прегиб", "ui.continuity_g1": "G1 тангентно", @@ -4011,6 +4506,7 @@ "ui.dark": "Тамна", "ui.default_modelling_orientation": "Подразумевана оријентација моделовања", "ui.delete": "Избриши", + "ui.delete_select_first": "Прво изаберите шта желите да избришете: операције, тела, компоненте или геометрију скице", "ui.depth": "Дубина", "ui.design": "Дизајн", "ui.design_properties.author": "Аутор", @@ -4025,6 +4521,40 @@ "ui.design_properties.project": "Пројекат", "ui.design_properties.revision": "Ревизија", "ui.design_saved": "Сачувано: {path}", + "ui.details_access_caption": "Лица показују да ли алат може да допре до њих из изабраног смера.", + "ui.details_angle": "Угао", + "ui.details_continuity_caption": "Измените изабрани шав. Остали шавови задржавају своја подешавања.", + "ui.details_continuity_stale": "Старија геометрија: поново покрените анализу да бисте изменили овај шав или га уклопили у приказ.", + "ui.details_copy_list": "Копирај списак", + "ui.details_curvature": "Толеранција закривљености", + "ui.details_curvature_caption": "Лица су обојена према локалном полупречнику закривљености.", + "ui.details_direction": "Смер алата", + "ui.details_draft_caption": "Лица су обојена према углу у односу на смер вађења из калупа.", + "ui.details_edit_seam": "Измени шав", + "ui.details_fixture": "Узорак компоненте — само пробни подаци", + "ui.details_fixture_caption": "Узорак компоненте са илустративним вредностима; ово није резултат модела.", + "ui.details_fixture_problem": "Пример налаза са проблемом", + "ui.details_fixture_readout": "Пример измерене вредности", + "ui.details_flip": "Обрни", + "ui.details_gap": "Размак", + "ui.details_hatch": "Шрафирај пресечена лица", + "ui.details_jump": "Скок закривљености", + "ui.details_key": "Легенда", + "ui.details_offset": "Одмак", + "ui.details_plane": "Раван", + "ui.details_pull": "Смер вађења из калупа", + "ui.details_radius": "Полупречник", + "ui.details_readout": "Очитавање", + "ui.details_samples": "Узорци", + "ui.details_seam": "{body} · Ивица {edge}", + "ui.details_settings": "Подешавања", + "ui.details_sharp_gap": "Оштро или са размаком", + "ui.details_show_all": "Прикажи свих {count}", + "ui.details_smooth": "Глатко", + "ui.details_stripes": "Пруге", + "ui.details_target": "Уклопи геометрију", + "ui.details_worst_seams": "Најгори шавови", + "ui.details_zebra_caption": "Одбијене пруге показују колико се глатко лица спајају.", "ui.diameter": "Пречник", "ui.dimension": "Кота", "ui.direct_interaction": "Директна интеракција", @@ -4069,6 +4599,7 @@ "ui.edit_in_place_saved_elsewhere": "Део је сачуван у другу датотеку; склоп и даље повезује {name}", "ui.edit_in_place_wait": "Сачекајте док се оно што ради у дизајну не заврши", "ui.edit_section_analysis": "Измени анализу пресека", + "ui.edit_sketch_empty": "Нема скица за измену", "ui.ellipse": "Елипса", "ui.emboss_wrap_note": "Профили од ортогоналних линија тангентни на један подржани цилиндар омотавају се аутоматски. Изаберите зид да бисте изабрали циљ.", "ui.end_radius": "Крајњи полупречник", @@ -4079,12 +4610,15 @@ "ui.equation_explicit": "Експлицитни", "ui.equation_form": "Облик", "ui.equation_note": "Променљива је обичан број: sin(t) је узима у радијанима. Резултат без јединице је у јединици дизајна.", + "ui.equation_note_range": "Променљива је дужина, као и њен опсег: комбинујте је са параметрима дужине, а за sin() је поделите дужином. Резултат без јединице је у јединици дизајна.", "ui.equation_parametric": "Параметарски", + "ui.equation_variable_unit": "Променљива има јединицу опсега", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Еквивалентни полупречник", "ui.expand": "Прошири", + "ui.explode_needs_two_components": "Растављени приказ раздваја компоненте, па дизајн мора имати две или више њих (Нова компонента, Уметни дизајн или Направи компоненте из тела)", "ui.exportDxf": "Извези DXF…", "ui.export_ellipsis_keymap": "Извези…", "ui.export_keymap_tip": "Тастери, омиљено из оквира S и трака са алатима, као датотека", @@ -4210,6 +4744,7 @@ "ui.hideOrigin": "Сакриј исходиште", "ui.hidePlanes": "Сакриј равни", "ui.hideProfile": "Сакриј профил", + "ui.hide_component_history": "Сакриј њену временску траку", "ui.hide_origin_by_default": "Подразумевано сакриј исходиште", "ui.hide_origin_note": "Нови дизајни почињу са скривеном фасциклом Исходиште. Дизајн задржава сопствено подешавање Исходишта када га прикажете или сакријете.", "ui.history_back": "Иди корак назад", @@ -4217,6 +4752,7 @@ "ui.history_edge_hint": "двапут кликните ивицу", "ui.history_first": "Иди на почетак", "ui.history_forward": "Иди корак напред", + "ui.history_hide_hidden": "Сакриј скривене компоненте", "ui.history_hide_names": "Сакриј називе", "ui.history_last": "Иди на крај", "ui.history_marker_tip": "Ознака враћања: превуците да вратите модел уназад; нове операције долазе овде", @@ -4226,10 +4762,12 @@ "ui.history_play_button_show": "Прикажи дугме за репродукцију", "ui.history_play_finish_action": "Завршите тренутну радњу пре репродукције временске траке", "ui.history_play_roll_back": "Померите маркер временске траке уназад пре репродукције", + "ui.history_show_hidden": "Прикажи скривене компоненте", "ui.history_show_names": "Прикажи називе", "ui.history_sketch_listed_under": "Наведено испод {feature}", "ui.history_title": "Временска трака", "ui.history_toggle_names": "Прикажи или сакриј називе операција", + "ui.history_waits_for_editor": "Поништи, Понови и временска трака чекају док се не отвори уређивач операције", "ui.hole": "Рупа", "ui.hole_tap_type": "Врста навоја рупе", "ui.hole_type": "Врста рупе", @@ -4245,6 +4783,7 @@ "ui.insert_design.saved_file": "Дизајн {name} има несачуване промене, па је уметнута његова сачувана датотека. Сачувајте га, а затим покрените Ажурирај везе да бисте унели промене.", "ui.insert_design.unsaved": "Несачуване промене", "ui.inspect": "Прегледај", + "ui.instances": "Инстанце", "ui.intersect": "Пресек", "ui.isolate": "Изолуј", "ui.join": "Споји", @@ -4253,12 +4792,14 @@ "ui.joints": "Спојеви", "ui.keyboard_shortcuts": "Пречице на тастатури", "ui.language": "Језик", + "ui.lasso_select": "Ласо (превуците петљу слободном руком: узима све што је у целини унутра)", "ui.layout_compact": "Компактно", "ui.layout_floating": "Плутајуће", "ui.length": "Дужина", "ui.length_decimals": "Децимале дужине", "ui.light": "Светла", "ui.line": "Линија", + "ui.line_arc_hint": "Тангентни лук: кликните крај лука. Поново се задржите на последњој тачки за линије; десни клик или Esc за завршетак", "ui.link_copies": "Повежи идентичне копије", "ui.link_copies_keep": "Задржи", "ui.link_copies_link": "Повежи", @@ -4347,6 +4888,7 @@ "ui.part_size_shared": "Поново гради део, замењујући све додате операције. Сви примерци ове компоненте се ажурирају.", "ui.paste": "Налепи", "ui.path": "Путања", + "ui.pattern_object_type_tip": "Тела: пуни облици, бирају се у приказу или у стаблу модела; свако се копира у целини.\nОперације: кораци временске траке, као што су екструзија или рупа, бирају се на временској траци или на лицу које су направили; корак се понавља.\nСкица није ни једно ни друго: поновите њене криве помоћу алата Низ или Пресликај у самој скици или је прво екструдирајте.", "ui.pattern_on_path": "Низ дуж путање", "ui.perforate_margin_default": "из пречника", "ui.perforate_pitch": "Корак", @@ -4373,12 +4915,17 @@ "ui.plugins_skipped": "Фасцикле није било могуће прочитати: {count}.", "ui.plugins_version": "{version}", "ui.point": "Тачка", + "ui.point_cloud_add_filter": "Додај филтер…", "ui.point_cloud_auto_range": "Аутоматски опсег", "ui.point_cloud_color_by": "Боја према", "ui.point_cloud_file_colors": "Боје из датотеке", + "ui.point_cloud_filter_by": "Филтрирај према", "ui.point_cloud_height_high": "Највише", "ui.point_cloud_height_low": "Најниже", + "ui.point_cloud_legend_filter": "Приказује се и сакрива у легенди изнад", "ui.point_cloud_no_file_colors": "Датотека нема боје", + "ui.point_cloud_pause": "Паузирај", + "ui.point_cloud_play": "Репродукуј", "ui.point_cloud_single_color": "Једна боја", "ui.point_cloud_size": "Величина тачке", "ui.point_cloud_units": "Јединице датотеке", @@ -4387,6 +4934,11 @@ "ui.polygon": "Полигон", "ui.preferences": "Подешавања", "ui.press_a_key": "притисните тастер…", + "ui.print_face_body_not_sent": "Тело те површине се не шаље: прво га додајте у Тела", + "ui.print_face_cleared": "{body}: површина за штампу уклоњена", + "ui.print_face_input": "Површина за штампу", + "ui.print_face_pick": "Изаберите равну површину пуног тела да постане површина за штампу", + "ui.print_face_set": "{body}: површина за штампу постављена; Пошаљи у слајсер полаже тело на њу", "ui.profile": "Профил", "ui.profile_plane": "Раван профила", "ui.profiles": "Профили", @@ -4402,6 +4954,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Мерење…", + "ui.properties.measuring_bodies": "Мерење… {done} од {total} тела", "ui.properties.measuring_failed": "Мерење је заустављено пре завршетка.", "ui.properties.principal_axis": "Главна оса {number}", "ui.properties.principal_moments": "Главни моменти", @@ -4450,6 +5003,7 @@ "ui.revolve": "Ротирај", "ui.ribbon_exit": "Изађи", "ui.ribbon_labels": "Прикажи текст испод икона на траци", + "ui.ribbon_menus_skip_pinned": "Изостави прикачене команде из падајућих менија", "ui.ribbon_pin_footer": "Прикачене команде приказују се на траци. Задржите показивач изнад реда да га прикачите или откачите.", "ui.ribbon_workspace": "Радни простор", "ui.right": "Десно", @@ -4468,6 +5022,7 @@ "ui.selectOther": "Изабери друго…", "ui.selectTangentChain": "Изабери тангентни ланац", "ui.select_all": "Изабери све", + "ui.select_components_by_face": "Изабери компоненте (лице бира своју компоненту)", "ui.selection": "Избор", "ui.selection_modifiers": "Модификатори избора", "ui.selection_shift_add_only": "Shift+клик додаје без уклањања", @@ -4493,6 +5048,7 @@ "ui.showDimension": "Прикажи коту", "ui.showOrigin": "Прикажи исходиште", "ui.showPlanes": "Прикажи равни", + "ui.show_component_history": "Прикажи њену временску траку", "ui.show_constraints": "Ограничења", "ui.show_construction_geometries": "Помоћна геометрија", "ui.show_dimensions": "Коте", @@ -4509,6 +5065,11 @@ "ui.sketch_intersect_selection_filter": "Филтер избора", "ui.sketch_modifiers": "Модификатори скице", "ui.sketch_project_geometry": "Геометрија", + "ui.sketch_report.all_constrained": "Све је потпуно ограничено.", + "ui.sketch_report.dof": "Степени слободе", + "ui.sketch_report.loose": "Није потпуно ограничено", + "ui.sketch_report.status": "Статус", + "ui.sketch_report.title": "Извештај о скици", "ui.sketch_scale": "Скалирање скице", "ui.sketches": "Скице", "ui.slice": "Пресеци", @@ -4604,19 +5165,31 @@ "ui.view_angles": "Углови приказа", "ui.view_angles_convention": "Степени око осе нагоре. Скретање 0° је Поглед спреда, 90° слева, −90° здесна, 180° отпозади; корак 90° је Поглед одозго; позитивно ваљање окреће модел у смеру казаљке на сату.", "ui.view_angles_help": "Приказује корак, скретање и ваљање приказа у степенима и његову пројекцију испод гизма оријентације. Кликните на очитање да унесете тачне углове.", + "ui.view_angles_lock": "Закључај {axis}", "ui.view_angles_ortho": "Орто", "ui.view_angles_persp": "Перс.", "ui.view_angles_pitch": "Нагиб", "ui.view_angles_readout": "Нагиб {pitch} · Скретање {yaw} · Ваљање {roll}", "ui.view_angles_roll": "Ваљање", + "ui.view_angles_unlock": "Откључај {axis}", "ui.view_angles_yaw": "Скретање", + "ui.view_angles_zero": "Постави {axis} на 0°", "ui.view_centre": "Центар приказа", "ui.viewport_status_clear": "Искључи {name}", "ui.viewport_status_clear_hint": "Искључи {name} · Esc", + "ui.viewport_status_edges": "Ивица: {count}", + "ui.viewport_status_from": "из смера {direction}", "ui.viewport_status_key": "Прикажи легенду за {name}", "ui.viewport_status_minimum_radius": "Минимални полупречник", "ui.viewport_status_pairs": "Парова: {count}", + "ui.viewport_status_section_hatch": "{setting} · шрафура", + "ui.viewport_status_section_plane": "Тренутна раван", + "ui.viewport_status_section_tilted": "нагнуто · {offset}", "ui.viewport_status_stripes": "Пруга: {count}", + "ui.viewport_status_summary_clear": "Искључи све", + "ui.viewport_status_summary_heading": "У овом приказу", + "ui.viewport_status_summary_label": "{name} и још ставки: {count}", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Прати тему", "ui.visual_shaded_hidden_edges": "Осенчено са скривеним ивицама", "ui.visual_shaded_with_edges": "Осенчено са ивицама", @@ -4653,7 +5226,9 @@ "update.button": "Ажурирај", "update.button_version": "Ажурирај на {version}", "update.check_automatically": "Аутоматски проверавај ажурирања", + "update.check_for_updates": "Провери ажурирања", "update.check_now": "Провери сада", + "update.check_unavailable": "Провера ажурирања није доступна за ову инсталацију.", "update.checking": "Провера…", "update.copy": "Копирај", "update.dmg_opened": "Слика диска је отворена и проверена: превуците SolidCraft у Applications, замените стару копију, а затим поново покрените SolidCraft.", @@ -4700,6 +5275,7 @@ "web.open_link": "Отворити повезани дизајн?", "web.open_link_confirm": "Постоје несачуване промене. Отворити повезани дизајн у новој картици?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ изабери · Enter / Tab доврши · Esc одбаци", + "↑ ↓ choose · Enter applies this value": "↑ ↓ избор · Enter примењује ову вредност", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ изабери · Enter примењује оно што сте уписали · Esc одбаци", "⌘Enter continues on GitHub.": "⌘Enter наставља на GitHub-у." } diff --git a/assets/locales/sv.json b/assets/locales/sv.json index 283b3d1d8..cc68dca25 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "BLANDYTA", "BOUNDARY SURFACE": "GRÄNSYTA", "BROWSER": "WEBBLÄSARE", + "Back to the original order": "Tillbaka till ursprunglig ordning", "Ball": "Kul", "Bar": "Stång", "Base Center": "Bascentrum", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Konstruktioner du öppnar eller sparar visas här.", "Determined by To Object. Choose Angle to edit the angular extent.": "Bestäms av Till objekt. Välj Vinkel för att redigera vinkelutsträckningen.", "Diameter": "Diameter", + "Did this assembly open the wrong way up?": "Öppnades den här sammanställningen med fel sida upp?", + "Did this part open the wrong way up?": "Öppnades den här delen med fel sida upp?", "Dimension new shapes": "Måttsätt nya former", "Direction": "Riktning", "Discard": "Förkasta", @@ -474,6 +477,7 @@ "Rectangular": "Rektangulär", "Rectangular Tube": "Rektangulärt rör", "Reference face": "Referensyta", + "Reference plane": "Referensplan", "Relief Depth": "Avlastningsdjup", "Relief Width": "Avlastningsbredd", "Remove Tools": "Ta bort verktyg", @@ -553,6 +557,7 @@ "Section": "Sektion", "Section (optional)": "Sektion (valfritt)", "Section position": "Profilens läge", + "Sections": "Tvärsnitt", "Sections (one sketch each)": "Sektioner (en skiss per sektion)", "Select Other": "Markera annan", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Markera annan: håll vänsterknappen stilla på modellen (eller högerklicka › Markera annan…) för att lista allt under markören; klicka igen på samma plats för att markera nästa objekt där. Dubbelklicka med mittenknappen för att gå till Hem (Inställningar › Navigering).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Snappa till ytors och kanters centrum", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft kan inte skicka in rapporter direkt. Skicka in dem på GitHub; ingen token behövs i appen.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft stängdes innan dessa konstruktioner sparades. Deras senaste autospar kan öppnas.", + "Sort A to Z": "Sortera A till Ö", + "Sort Z to A": "Sortera Ö till A", "Spacing 2 must be a non-zero number": "Avstånd 2 måste vara ett tal skilt från noll", "Spacing must be a non-zero number": "Avståndet måste vara ett tal skilt från noll", "Specialise": "Specialisera", @@ -601,6 +608,7 @@ "Square": "Kvadrat", "Stand it up": "Res upp den", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Res upp den: ett kvartsvarv runt X, som en enda Flytta-funktion som du kan ångra.", + "Stand this assembly up?": "Resa upp denna sammanställning?", "Stand this part up?": "Resa upp denna del?", "Start angle": "Startvinkel", "Start bulge": "Startbukt", @@ -772,6 +780,8 @@ "at the face": "vid ytan", "bom.group_children": "Underdelar i sin dels rad", "browser.body_name": "Kropp{number}", + "browser.calibrate_click_a": "Klicka på bilden för punkt A eller skriv dess koordinater.", + "browser.calibrate_click_b": "Klicka på bilden för punkt B eller skriv dess koordinater.", "browser.calibrate_title": "Kalibrera: {name}", "browser.capture_many": "{count} komponenter flyttades men deras lägen har inte fångats.", "browser.capture_note": "Fånga behåller det nya läget; Återställ sätter tillbaka det.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (fäste förlorat)", "browser.sketch_editing": "{name} (redigeras)", "browser.sketch_name": "Skiss{number}", + "browser.sketches_to_parts_already_in_part": "redan i sin del", + "browser.sketches_to_parts_design_body": "på en kropp i själva konstruktionen", + "browser.sketches_to_parts_moved": "Flyttade {moved} skisser till den del de ligger på", + "browser.sketches_to_parts_no_exact_attachment": "på en yta utan exakt fäste", + "browser.sketches_to_parts_not_on_face": "inte på en dels yta", + "browser.sketches_to_parts_part_missing": "deras del finns inte längre", + "browser.sketches_to_parts_result": "Flyttade {moved} skisser till den del de ligger på; {stayed} låg kvar: {why}", "browser.units": "Enheter: {units}", "cam.flat": "Plan yta", "cam.follower": "Följare", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Plocka upp utseende", "cmd.appearance_replace": "Ersätt utseende", "cmd.assembly_bom": "Stycklista", + "cmd.assembly_mass_properties": "Massegenskaper", + "cmd.body.print_face": "Utskriftsyta", "cmd.body_rename": "Byt namn på kropp", "cmd.browser_collapse_all": "Fäll ihop alla", "cmd.browser_expand_all": "Expandera alla", @@ -842,6 +861,7 @@ "cmd.component_extract": "Extrahera till fil", "cmd.component_finish_edit": "Slutför redigering", "cmd.component_from_bodies": "Skapa komponenter från kroppar", + "cmd.component_hide_history": "Dölj komponenthistorik", "cmd.component_insert_design": "Infoga konstruktion", "cmd.component_links": "Lista länkar", "cmd.component_list": "Lista komponenter", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Flytta kroppar till komponent", "cmd.component_move_features": "Flytta funktioner till komponent", "cmd.component_move_sketches": "Flytta skisser till komponent", + "cmd.component_move_sketches_to_parts": "Flytta skisser till deras delar", "cmd.component_paste_from_design": "Klistra in från en annan konstruktion", "cmd.component_paste_new": "Klistra in ny", "cmd.component_properties": "Komponentens fysiska egenskaper", @@ -857,6 +878,7 @@ "cmd.component_rename": "Byt namn på komponent", "cmd.component_replace_with_link": "Ersätt med länk", "cmd.component_revert_position": "Återställ läge", + "cmd.component_show_history": "Visa komponenthistorik", "cmd.component_unlock": "Lås upp innehåll", "cmd.component_update_links": "Uppdatera länkar", "cmd.config_activate": "Aktivera konfiguration", @@ -867,6 +889,7 @@ "cmd.config_rule": "Konfigurationsregel", "cmd.config_rules": "Konfigurationsregler", "cmd.config_table": "Visa konfigurationstabell", + "cmd.construct.plane.axis_point": "Plan genom axel och punkt", "cmd.construct_axis_edge": "Axel genom kant", "cmd.construct_axis_normal_to_face": "Axel vinkelrät mot yta", "cmd.construct_axis_through_cylinder": "Axel genom cylinder/kon/torus", @@ -915,6 +938,11 @@ "cmd.explode_show": "Visa sprängvy", "cmd.expr_evaluate": "Utvärdera uttryck", "cmd.face_delete": "Ta bort yta", + "cmd.file.export_3mf": "Exportera 3MF", + "cmd.file.export_obj": "Exportera OBJ", + "cmd.file.export_step": "Exportera STEP", + "cmd.file.export_stl": "Exportera STL", + "cmd.file.export_urdf": "Exportera URDF", "cmd.file_export": "Exportera", "cmd.file_insert_mesh": "Infoga mesh", "cmd.file_insert_step": "Infoga STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Aktivera komponentfärger", "cmd.inspect_colored_components_disable": "Inaktivera komponentfärger", "cmd.inspect_compare": "Jämför kroppar", + "cmd.inspect_compare_picture": "Jämför bild", "cmd.inspect_continuity": "Kontinuitetsanalys", "cmd.inspect_curvature_comb": "Krökningskamsanalys", "cmd.inspect_curvature_map": "Krökningskartanalys", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Redigera punktmoln", "cmd.pointcloud_insert": "Infoga punktmoln", "cmd.pointcloud_list": "Punktmoln", + "cmd.render.compare.divider": "Flytta avdelaren i renderingsjämförelsen", + "cmd.render.result.discard": "Förkasta renderingsresultat", + "cmd.render.result.select": "Markera renderingsresultat", "cmd.render_aging_describe": "Skiktad ytåldring", "cmd.render_backends": "Renderingsbackends", "cmd.render_batch": "Rendera alla tagningar", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Spline med kontrollpunkter (grad 5)", "cmd.sketch_spline_fit_point": "Spline med passpunkter", "cmd.sketch_spline_insert_point": "Lägg till splinepunkt", + "cmd.sketch_spline_remove_point": "Ta bort splinepunkt", "cmd.sketch_spline_reverse": "Vänd splinens riktning", "cmd.sketch_spun_profile": "Roterad profil", "cmd.sketch_toggle_diameter": "Växla radie / diameter", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Flytta tidslinjemarkör", "cmd.timeline_stop": "Stoppa historikuppspelning", "cmd.timeline_suppress": "Undertryck funktion", + "cmd.ui.assistant": "Visa/dölj assistent", "cmd.view.render_browser": "Renderingswebbläsare", "cmd.view.render_dock": "Flytta renderingspanel", "cmd.view.render_focus": "Fokusvy för rendering", + "cmd.view.status_details": "Statusdetaljer i vyfönstret", "cmd.view.status_items": "Statusobjekt i vyfönstret", "cmd.view_ambient_occlusion": "Omgivningsocklusion", "cmd.view_angle_readout": "Vyvinklar", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Navigeringsverktyg", "cmd.view_top": "Vy ovanifrån", "cmd.view_visual_style": "Visuell stil", + "color.blue": "Blå", "color.copy": "Klicka för att kopiera färgvärden", "color.edit": "Klicka för att redigera färg", "color.gamma": "Visar färgvärden i gammarymd 0–255", + "color.green": "Grön", "color.hex": "Hex", "color.hex_help": "Ange #rrggbb eller #rrggbbaa; sex siffror behåller opaciteten", "color.hex_hint": "#rrggbb", "color.hue": "Nyans", "color.linear": "Visar färgvärden i linjär rymd 0–1", + "color.recent": "Senaste färger", + "color.recent_help": "Färger som du väljer i ett färgfält visas här", + "color.red": "Röd", + "color.saturation": "Mättnad (procent)", "color.saturation_value": "Mättnad och värde", "color.selected": "Vald färg", + "color.step_down": "Ett steg ned", + "color.step_up": "Ett steg upp", + "color.value": "Värde, ljusstyrkan (procent)", "config.column_filter_empty": "Inga matchande kolumner", + "config.rule_parameter_columns": "Endast parametrar med en kolumn i tabellen listas. Lägg till en kolumn med Lägg till kolumn (+) för att använda parametern här.", + "config.rule_suppression_columns": "Endast funktioner med en kolumn Undertryck i tabellen listas. Lägg till en kolumn med Lägg till kolumn (+) för att styra undertryckningen här.", "contact.components_count": "{count} komponenter", "contact.enabled_label": "aktiverad", "coupling.gear_1": "Kugghjul 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "Klicka på ett annat styrande mått för att infoga dess namn", "dialog.dimension_name": "Mått: {name}", "dialog.edit_title": "REDIGERA {title}", + "dialog.no_shown_body": "Ingen synlig kropp att ändra: visa en, eller välj Ny kropp", + "dialog.pattern_sketch_not_object": "Välj kroppar eller funktioner: en skiss är ingetdera. Upprepa dess kurvor med skissens egna Mönster eller Spegla, eller extrudera den först.", "dialog.select": "↖ Markera", "dialog.selected_count": "↖ {count} markerade", + "dialog.selection_constraint": "Villkor {id}", + "dialog.selection_external_curve": "{sketch} · kurva {id}", "dialog.selection_guidance": "Markera en indata för att ändra den. Klicka på markerade objekt för att ta bort dem; Ctrl/Cmd-klick växlar dem också. Granska förhandsvisningen och tryck sedan på OK.", + "dialog.selection_midpoint": "Mittpunkt · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step} av {total}: Markera {input}", "dialog.step": "Steg", "document.changed_on_disk": "{name} har ändrats på disken", @@ -1340,6 +1392,7 @@ "document.read_only_save": "Den här konstruktionen öppnades skrivskyddad: spara den som en ny fil", "document.save_changes": "Spara ändringar i {name}?", "document.save_copy": "Spara en kopia…", + "document.tab_unsaved_changes": "Osparade ändringar", "document.unsaved_changes": "{name} har osparade ändringar. Om du inte sparar går de förlorade.", "drive.rigid": "{joint} är ett stelt led: det håller sina delar stilla och har därför inget att driva. Om delarna ska kunna röra sig, ändra ledets typ i Redigera led: Roterande för att rotera, Glidande för att glida, Cylindrisk för båda.", "drive.stopped_by_contact": "Stoppade vid {value}: {a} skulle gå igenom {b}", @@ -1380,26 +1433,244 @@ "from the rule": "från regeln", "help.apache": "Apache-licens 2.0", "help.appearance.assign": "Ger de markerade kropparna, ytorna eller komponenterna en färg eller ett materialutseende, utan att ändra deras vikt. Använd det för att skilja delar åt eller förhandsgranska en ytfinish.", + "help.assembly.bom": "Listar delarna i konstruktionen eller i en komponent med deras antal, per artikelnummer, och kan spara listan som CSV eller JSON. Använd den som stycklista för beställning och montering.", "help.attributions": "Erkännanden (ATTRIBUTION.md)", "help.build": "Version {version} · commit {commit} · byggd {date}", + "help.canvas.decal": "Placerar en bild på en plan yta på modellen, som ett klistermärke. Använd det för att visa en etikett, en logotyp eller ett tryckt mönster på en del.", + "help.canvas.edit": "Ändrar en duk: dess läge, storlek, vinkel, opacitet, spegling, synlighet eller namn. Använd det för att passa in en referensbild mot skissen som du ritar av den i.", + "help.canvas.insert": "Placerar en PNG- eller JPEG-bild på ett plan eller en yta som en genomskinlig referens. Använd det för att rita av ett foto eller en ritning i en skiss, med bilden skalad till en känd storlek.", + "help.component.break_link": "Kopplar loss en länkad komponent från sin konstruktionsfil och behåller dess kroppar som de är. Använd det när delen inte längre ska följa ändringar i originalfilen.", + "help.component.capture_position": "Behåller lägena för delar som du flyttat för hand, så att de blir delarnas nya utgångsläge. Använd det efter att du dragit delar på plats som ingen led håller fast.", + "help.component.create": "Lägger till en ny, tom komponent i konstruktionen, i den aktiva komponenten om du inte väljer en annan överordnad komponent. Använd det för att ge en ny del av en sammanställning en egen plats för kroppar och skisser.", "help.component.finish_edit": "Sparar delen du redigerar på plats, återgår till dess sammanställning och uppdaterar sammanställningen utifrån den. Använd det när dina ändringar i den länkade delen är klara.", + "help.component.from_bodies": "Gör varje markerad kropp till en egen komponent, uppkallad efter kroppen. Använd det när en konstruktion byggd av lösa kroppar ska bli en sammanställning vars delar kan fogas samman med leder och flyttas.", + "help.component.insert_design": "Infogar en annan sparad konstruktion som en komponent länkad till sin fil, med dess solida kroppar placerade som de är där. Använd det för att återanvända en del i en sammanställning och få med senare ändringar via Uppdatera länkar.", + "help.component.properties": "Visar volym, massa, masscentrum och tröghetsmoment för en komponent, utifrån kropparnas material. Använd det för att kontrollera vikt och balans hos en sammanställning.", + "help.component.revert_position": "Sätter tillbaka delar som du flyttat för hand där de var och förkastar flyttningar som inte fångats. Använd det för att ångra provflyttningar i en sammanställning.", + "help.component.update_links": "Läser de länkade konstruktionsfilerna igen och ersätter kroppar som har ändrats. Använd det efter att du redigerat en del som den här sammanställningen använder.", + "help.config.configure": "Lägger till parametrar, funktioner, material eller utseenden som kolumner i konfigurationstabellen. Använd det för att bygga varianter av en konstruktion, till exempel storlekar på en del.", + "help.config.preview": "Kontrollerar att en rad i konfigurationstabellen går att bygga om, utan att ändra konstruktionen eller dess historik. Använd det innan du byter till en variant som du är osäker på.", + "help.config.rules": "Visar konfigurationstabellens regler och rader och vilken rad som är aktiv. Använd det för att se hur en konstruktions varianter är uppsatta.", + "help.config.table": "Visar konfigurationstabellen: en rad per variant, en kolumn per parameter eller funktion, och om konstruktionen fortfarande stämmer med den aktiva raden. Använd det för att granska en konstruktions varianter.", "help.connect_note": "Starta om varje assistent för att läsa in SolidCraft-servern. Varje fil säkerhetskopierades som .bak innan den ändrades.", "help.connect_title": "Anslut AI-assistenter", + "help.construct.axis.edge": "Skapar en konstruktionsaxel längs en rak kant eller skisslinje. Använd den som axel för en rotation, ett cirkulärt mönster eller en led.", + "help.construct.axis.normal_to_face": "Skapar en konstruktionsaxel genom en punkt, vinkelrät mot en yta. Använd den som en axel som står rakt ut från en yta.", + "help.construct.axis.through_cylinder": "Skapar en konstruktionsaxel genom centrum av en cylinder-, kon- eller torusyta, eller en cirkulär kant. Använd den för att rotera eller mönstra funktioner runt en rund del.", + "help.construct.axis.two_planes": "Skapar en konstruktionsaxel där två plan eller plana ytor möts. Använd den när den axel du behöver är linjen mellan två ytor.", + "help.construct.axis.two_points": "Skapar en konstruktionsaxel genom två punkter, hörn eller skisspunkter. Använd den för en axel som löper mellan två kända lägen.", + "help.construct.plane.along_path": "Skapar ett konstruktionsplan vinkelrätt mot en kant eller kurva, på en position längs den. Använd det för att skissa en profil för en svepning eller ett tvärsnitt av en bana.", + "help.construct.plane.at_angle": "Skapar ett konstruktionsplan som är vridet i en vinkel från ett plan eller en yta, runt en axel eller kant. Använd det för lutande skisser, till exempel ett vinklat fäste.", + "help.construct.plane.axis_point": "Skapar ett konstruktionsplan som innehåller en axel och en punkt utanför den axeln. Välj en origoaxel eller konstruktionsaxel, en rak kant eller skisslinje och sedan ett hörn, en skisspunkt eller en konstruktionspunkt. En punkt på axeln kan inte definiera ett entydigt plan.", + "help.construct.plane.midplane": "Skapar ett konstruktionsplan mitt emellan två plan eller plana ytor, eller som delar vinkeln där de möts i en vinkel. Använd det som symmetriplan vid spegling.", + "help.construct.plane.offset": "Skapar ett konstruktionsplan parallellt med ett plan eller en plan yta, på ett avstånd eller genom en punkt. Använd det för att skissa på en bestämd höjd över en yta.", + "help.construct.plane.perpendicular": "Skapar ett konstruktionsplan som innehåller en linje eller kant och står vinkelrätt mot ett plan eller en yta. Använd det för att skissa upprätt på en modell längs en kant.", + "help.construct.plane.tangent": "Skapar ett konstruktionsplan som tangerar en cylinder, kon, sfär eller torus i en punkt. Använd det för att skissa på sidan av en rund del.", + "help.construct.plane.three_points": "Skapar ett konstruktionsplan genom tre punkter. Använd det för ett plan som bestäms av lägen på modellen, till exempel tre hörn.", + "help.construct.plane.two_edges": "Skapar ett konstruktionsplan genom två raka kanter eller linjer som ligger i samma plan. Använd det för ett plan tvärs genom en del, till exempel genom två motstående kanter.", + "help.construct.point.along_path": "Skapar en konstruktionspunkt på en position längs en kant eller kurva. Använd den som referens en bit längs en bana.", + "help.construct.point.center": "Skapar en konstruktionspunkt i centrum av en cirkulär kant, en skisscirkel eller skissbåge, en sfär eller en torus. Använd den som referens för hål, axlar och leder.", + "help.construct.point.edge_plane": "Skapar en konstruktionspunkt där en kant eller linje går genom ett plan eller en plan yta. Använd den för att markera var en bana korsar ett plan.", + "help.construct.point.three_planes": "Skapar en konstruktionspunkt där tre plan eller plana ytor möts. Använd den som hörnreferens, även där modellen saknar hörn.", + "help.construct.point.two_edges": "Skapar en konstruktionspunkt där två kanter eller linjer möts eller kommer närmast varandra. Använd den som referens i ett virtuellt hörn.", + "help.construct.point.vertex": "Skapar en konstruktionspunkt på ett hörn eller en skisspunkt. Använd den som en referens som finns kvar när skissen eller kroppen runt den är dold.", + "help.contact.check": "Listar de par av delar i kontaktuppsättningar som går igenom varandra i sitt nuvarande läge. Använd det för att hitta kollisioner innan du driver leder eller kör en rörelsestudie.", + "help.contact.create": "Grupperar två eller fler delar i en kontaktuppsättning vars kroppar hindras från att gå igenom varandra medan lederna rör sig. Använd det för delar som ska stanna när de rör vid varandra, till exempel en spak mot sitt stopp.", + "help.contact.disable_all": "Stänger av kontakt, så att drivna leder och rörelsestudier inte längre stannar där delar rör vid varandra. Använd det för att kunna flytta delar fritt igen, eller för att hålla en stor sammanställning responsiv.", + "help.contact.edit": "Ändrar en kontaktuppsättning: vilka delar den innehåller, dess namn eller om den är undertryckt; den kan också ta bort uppsättningen. Använd det för att justera vilka delar som hindras från att gå igenom varandra.", + "help.contact.enable_all": "Lägger alla delar i sammanställningen i en enda kontaktuppsättning, så att inga två delar kan gå igenom varandra medan lederna rör sig. Använd det för en snabb kontroll av en hel mekanism.", + "help.contact.enable_sets": "Slår på kontakt för de kontaktuppsättningar du har definierat, så att drivna leder och rörelsestudier stannar där deras delar skulle gå igenom varandra. Använd det för att få tillbaka dina uppsättningar efter att du stängt av kontakt.", + "help.contact.list": "Listar konstruktionens kontaktuppsättningar, delarna i var och en och om kontakt är på. Använd det för att kontrollera hur kontakt är inställd innan du driver sammanställningen.", + "help.document.inspect": "Visar en översikt över konstruktionen: dess komponenter, kroppar, skisser, funktioner och parametrar. Använd det för att orientera dig i en konstruktion som du inte byggt själv.", + "help.document.units": "Ändrar enheterna som konstruktionen visar längder i, till exempel mm eller tum. Geometrin behåller sin storlek; bara visningen och tal utan enhet följer med.", + "help.edit.checkpoint": "Kommer ihåg konstruktionen, den aktiva skissen och ångrahistoriken som de är nu. Använd det innan du provar något riskabelt som du kanske vill gå tillbaka från.", + "help.edit.restore_checkpoint": "Går tillbaka till en kontrollpunkt, inklusive ångrahistoriken. Använd det för att förkasta allt som gjorts sedan kontrollpunkten i ett enda steg.", + "help.explode.create": "Skapar en sprängvy som skjuter delarna bort från sammanställningens centrum, eller enligt de förflyttningar du anger. Använd det för att visa hur en sammanställning sätts ihop, för instruktioner eller presentationer.", "help.face.delete": "Tar bort de markerade ytorna och låter angränsande ytor sluta hålet, eller lämnar hålet öppet som en yta. Använd det för att ta bort en avrundad kant, ett hål eller ett nav som är i vägen.", + "help.file.insert_mesh": "Lägger till en 3MF-, STL-, OBJ-, PLY- eller glTF-fil i konstruktionen som meshkroppar i en ny komponent. Använd det för att placera en nedladdad eller skannad modell bredvid din konstruktion som referens.", + "help.file.insert_step": "Lägger till en STEP-, IGES-, FreeCAD- eller Rhino-fil i konstruktionen som solida kroppar i en ny komponent; en sammanställnings delar blir nästlade komponenter. Använd det för att hämta in modeller från leverantörer eller andra CAD-program.", + "help.file.save_mesh": "Sparar kroppar som mesh i formatet STL, 3MF eller OBJ, med den jämnhet för krökta ytor som du väljer. Använd det för att förbereda delar för 3D-utskrift eller för program som läser mesh.", + "help.file.send_to_slicer": "Sparar de markerade kropparna som en 3MF-fil och öppnar den i den slicer du väljer. Använd det för att gå från modell till utskrift i ett enda steg.", "help.font_details": "Gränssnittet använder egui:s inbyggda teckensnitt (Ubuntu Light och Hack, under Ubuntu Font Licence och MIT/Bitstream Vera-licensen; Noto Emoji och emoji-ikonteckensnittet, under OFL och MIT). Skisstext använder Liberation Sans (SIL OFL 1.1). Crafting Apps valfria teckensnittspaket, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), ingår inte i SolidCraft-byggen.", "help.fonts": "Teckensnitt", + "help.frame.member": "Placerar en profil, till exempel ett rör eller en aluminiumprofil, längs linjerna i en ramskiss, en ramdel per linje. Använd det för att bygga ramar, ställ och svetsade konstruktioner.", + "help.inspect.accessibility": "Färgar de ytor som ett verktyg kan nå från en riktning, och de som det inte kan nå. Använd det för att kontrollera en del för bearbetning eller formsprutning från den sidan.", + "help.inspect.center_of_mass": "Visar masscentrum för kroppar, var för sig och alla tillsammans, vid jämn densitet. Använd det för att kontrollera balans och var en del tippar.", + "help.inspect.colored_components": "Ger varje komponent en egen tillfällig färg, utan att ändra utseenden. Använd det för att snabbt skilja delarna i en sammanställning åt.", + "help.inspect.compare": "Jämför två kroppar och visar var den ena har material som den andra saknar, med volym och avvikelse. Använd det för att kontrollera en ändrad eller importerad del mot originalet.", + "help.inspect.continuity": "Kontrollerar hur jämnt ytor möts längs sina kanter: spalter, knäckar eller krökningshopp, och färgar skarvarna. Använd det för att hitta var ytor inte fogas rent.", + "help.inspect.curvature_comb": "Ritar kammar längs kurvor, kanter eller ytor vars tänder visar hur kraftigt de kröker sig. Använd det för att hitta plana ställen, knäckar och ojämn krökning.", + "help.inspect.curvature_map": "Färgar ytor efter hur kraftigt de kröker sig, rött där radien är liten. Använd det för att hitta snäva ställen och bedöma hur jämn en yta är.", + "help.inspect.draft": "Färgar ytor efter deras släppvinkel mot en dragriktning och markerar de som har för lite. Använd det för att kontrollera en del före formsprutning eller gjutning.", + "help.inspect.environment_map": "Visar modellen med en reflekterande, spegelliknande yta. Använd det för att bedöma ytornas förlopp utifrån hur reflektionerna löper över dem.", + "help.inspect.interference": "Hittar kroppar som överlappar varandra och visar varje överlapp med dess volym. Använd det för att kontrollera om delar i en sammanställning kolliderar.", + "help.inspect.isocurve": "Ritar ytors isoparametriska kurvor, det rutnät som ytan är byggd på. Använd det för att se hur en yta flyter och var den packas ihop.", + "help.inspect.measure": "Mäter längder, avstånd, vinklar, areor och radier mellan det du väljer, eller volym och massa hos kroppar. Använd det för att kontrollera storlekar och frigångar.", + "help.inspect.minimum_radius": "Hittar den minsta krökningsradien hos kurvor, kanter eller ytor och var den finns. Använd det för att kontrollera att ett verktyg eller ett munstycke kan följa formen.", + "help.inspect.section": "Skär upp vyn längs ett plan och skrafferar snittytorna, utan att ändra modellen. Använd det för att titta in i delar och sammanställningar.", + "help.inspect.zebra": "Visar svarta och vita ränder som speglas i modellens ytor. Använd det för att bedöma jämnhet: ränder som bryts eller knäcks vid en kant visar en dålig övergång.", + "help.joint.as_built": "Förbinder två delar där de redan är, utan att flytta någon av dem, och anger hur de fortfarande får röra sig. Använd det för delar som du redan har placerat i sitt slutliga läge.", + "help.joint.cam": "Länkar en roterande kam till en följare, så att följaren glider eller svänger när kamens kontur passerar under den. Använd det för kammar, excentrar och ventilmekanismer.", + "help.joint.create": "Förbinder två delar vid de ledursprung du väljer och flyttar den andra delen på plats; ledtypen anger hur de fortfarande får röra sig. Använd det för att bygga en sammanställning vars delar rör sig som den verkliga mekanismen.", + "help.joint.drive": "Anger en leds vinkel eller avstånd och flyttar delarna med den, inom dess gränser; länkade leder och slutna slingor följer med. Använd det för att kontrollera att en mekanism rör sig som avsett.", + "help.joint.gear": "Länkar två roterande leder med ett utväxlingsförhållande, så att den andra vrids när du driver den ena. Använd det för raka kugghjul och kuggkransar, med förhållandet från delningsradier eller kuggantal.", + "help.joint.limits": "Anger hur långt en led får vridas eller glida, som ett minimum och ett maximum, eller tar bort dessa gränser. Använd det för att hålla ett gångjärn, en glidande led eller en spak inom sitt verkliga rörelseomfång.", + "help.joint.motion_link": "Kopplar ihop två leder med ett förhållande och en förskjutning, så att den andra rör sig när du driver den ena. Använd det för ett fast samband mellan leder som Kugghjul, Kuggstång och drev eller Skruv inte täcker.", + "help.joint.origin": "Placerar ett namngivet ledursprung på en del: i centrum av en yta eller en rund ände, mitt på en kant, i ett hörn eller i en punkt. Använd det för att förbereda var leder fäster; ett som väljs på en yta följer den när delen ändrar storlek.", + "help.joint.rack_pinion": "Länkar ett roterande drev till en glidande kuggstång, så att kuggstången rör sig lika långt som den del av delningscirkeln som drevet rullar över. Använd det för kuggstångsdrifter, styrning och linjärstyrningar.", + "help.joint.reach": "Flyttar en punkt på en del mot ett mål genom att ändra lederna i dess kedja, inom deras gränser. Använd det för att ställa in en mekanism utifrån var dess ände ska vara, till exempel spetsen på en robotarm.", + "help.joint.rigid_group": "Låser de markerade delarna ihop som de är, så att de rör sig som en enhet. Använd det för delar som hör ihop och inte har någon rörelse mellan sig.", + "help.joint.screw": "Länkar vridning och glidning med en stigning, så att varje varv förflyttar delen det avståndet. Använd det för ledskruvar, bultar och gängade spindlar.", + "help.library.apply": "Tillämpar ett material eller utseende från en lokal biblioteksfil på kroppar, ytor eller komponenter. Använd det för att återanvända material som du sparat från en annan konstruktion.", + "help.library.export": "Sparar konstruktionens material och utseenden i en biblioteksfil. Använd det för att dela dem eller återanvända dem i andra konstruktioner.", + "help.library.inspect": "Kontrollerar en biblioteksfil och listar dess material och utseenden, utan att ändra konstruktionen. Använd det för att se vad ett bibliotek innehåller innan du tillämpar det.", "help.licences": "Licenser", "help.material.assign": "Anger vad de markerade kropparna är gjorda av, till exempel stål, aluminium eller ABS. Använd det så att massa och vikt stämmer med den verkliga delen.", + "help.material.properties.validate": "Kontrollerar att ett materialkort har konsekventa tal och inga saknade värden. Använd det innan du förlitar dig på data för massa eller styvhet.", + "help.mesh.convert": "Bygger om en meshkropp, till exempel en STL, till en redigerbar solid med plana och cylindriska ytor. Använd det för att ändra importerade mekaniska delar som om de vore en modellerad kropp.", "help.mit": "MIT-licens", + "help.motion.study": "Anger ledvärden vid steg längs en tidslinje och spelar upp dem som en animation. Använd det för att se en mekanism röra sig genom en sekvens och kontrollera frigångar längs vägen.", + "help.motion.trace": "Spårar den bana som en punkt på en del följer medan en rörelsestudie spelas upp eller en led drivs, och behåller den som en 3D-skisskurva när du bekräftar. Använd det för att se var en mekanism når, eller för att bygga vidare på dess bana.", "help.notice": "NOTICE", + "help.occurrence.ground": "Fixerar en del på plats, eller frigör den igen, så att leder flyttar de andra delarna runt den. Använd det för ramen eller basen som resten av sammanställningen byggs på.", "help.occurrence.move": "Flyttar en del i sammanställningen endast längs de frihetsgrader som dess leder tillåter. Markera en yta på delen och dra sedan en tillgänglig pil eller båge.", "help.parameters.change": "Öppnar tabellen med namngivna värden och uttryck som styr konstruktionens mått. Använd den för att ändra en storlek på ett ställe och låta varje funktion som använder den följa med.", + "help.parameters.export": "Sparar konstruktionens parametrar som CSV eller JSON. Använd det för att redigera dem i ett kalkylblad eller flytta dem till en annan konstruktion.", + "help.parameters.graph": "Visar vilka parametrar och funktioner som använder vilka andra, och eventuella cirkulära beroenden eller fel bland dem. Använd det för att se vad en ändring av en parameter påverkar.", + "help.parameters.import": "Läser in parametrar från CSV eller JSON i konstruktionen, antingen alla eller inga. Använd det för att hämta in värden från ett kalkylblad eller en annan konstruktion.", + "help.parameters.move": "Flyttar en användarparameter före eller efter en annan i listan. Använd det för att hålla relaterade parametrar samlade.", + "help.parts.fastener": "Lägger till en standardiserad skruv, bult, mutter, bricka, stift eller ett lager i den storlek du väljer. Placeras den på ett hål sätts den fast i hålet med en led, så att du inte behöver modellera fästelement själv.", + "help.parts.insert": "Infogar en standarddel i den familj, storlek och längd du väljer. Placeras den på kanten eller väggen av ett hål sätts den fast mot hålet med en stel led.", + "help.parts.library": "Öppnar standarddelarna: skruvar, bultar, muttrar, brickor, stoppskruvar, passtift och lager i standardstorlekar. Använd det för att lägga till en standarddel i stället för att modellera den själv.", + "help.parts.resize": "Ändrar storleken eller längden på en infogad standarddel och bygger om den; dess leder håller den på plats. Använd det när en skruv visar sig vara för lång eller ett hål behöver en annan storlek.", + "help.plastic.assign_rule": "Tilldelar en plastregel till kroppar, så att deras plastfunktioner tar dess släppvinkel och frigång som standardvärden. Använd det för att ställa in en formsprutad del en gång för alla dess funktioner.", + "help.plastic.boss": "Lägger till ett skruvnav på en yta: en pelare med valfritt hål, släppvinkel, rotavrundning och stödjande revben. Använd det för skruvpunkter i formsprutade eller utskrivna höljen.", + "help.plastic.lip": "Lägger till en läpp eller ett matchande spår längs kanten på en urholkad kropp. Använd det så att två höljeshalvor centreras mot varandra och sluter tätt.", + "help.plastic.manage_rules": "Skapar och redigerar plastregler: material, väggtjocklek, radier, frigång och släppvinkel. Använd dem för att hålla funktionerna i en formsprutad del enhetliga.", + "help.plastic.rest": "Lägger till ett stöd på en yta: en rund eller rektangulär platta, massiv eller ihålig, med släppvinkel. Använd det som stöd eller distans i ett formsprutat hölje.", + "help.plastic.snap_fit": "Lägger till en snäppkrok på en yta, med angiven längd, tjocklek och hake. Använd det för att snäppa ihop delar utan skruvar.", "help.pointcloud.insert": "Infoga en skanning i formatet PLY, XYZ eller PTS som ett punktmoln vid sidan av modellen. Använd den som referens när du bygger en modell från uppmätta data.", + "help.sheet.convert": "Gör en platta eller urholkad kropp med jämn tjocklek till en plåtkropp, med böjar vid de kanter du väljer. Använd det för att göra en befintlig del utvikbar.", + "help.sheet.export_bend_table": "Sparar böjtabellen för en plåtkropp som CSV eller JSON: vinklar, radier och böjlägen i det plana mönstret. Använd det för kantpressen eller verkstaden.", + "help.sheet.export_dxf": "Sparar det plana mönstret som en DXF, med konturer, böjlinjer och valfria böjanteckningar. Använd det för laser-, plasma- eller vattenskärning.", + "help.sheet.flange": "Lägger till en fläns: en grundplåt utifrån en skiss, en vägg längs en öppen skisskontur eller en böjd vägg på plåtkanter. Använd det för att bygga upp plåtdelar.", + "help.sheet.flat_pattern": "Skapar det plana mönstret för en plåtkropp, med dess storlek, utskärningar och böjlinjer. Använd det för att kontrollera plåtämnet innan du skär ut det.", + "help.sheet.fold": "Böjer en plåt längs en skisslinje med en vinkel och en radie. Använd det för att vika en plan plåt efter att du skurit ut funktioner i den.", + "help.sheet.hem": "Viker en plåtkant tillbaka mot sig själv. Använd det för säkra, styva kanter utan vassa grader.", + "help.sheet.manage_rules": "Skapar och redigerar plåtregler: tjocklek, böjradie, K-faktor, avlastningar och spalter. Använd dem för att anpassa efter materialet och verktygen i din verkstad.", + "help.sheet.path_flange": "Lägger till en kedja av flänsar längs en plåtkant, efter en öppen kedja av skisslinjer. Använd det för profiler som en U- eller Z-form i ett enda steg.", + "help.sheet.perforate": "Lägger till ett hålfält över hela den plana plåten, i ett förskjutet eller kvadratiskt mönster. Använd det för ventilation, galler och lättare paneler.", + "help.sheet.refold": "Viker ihop en utvikt plåtkropp igen. Använd det efter att du lagt till funktioner i den plana plåten.", + "help.sheet.unfold": "Viker ut alla böjar på en plåtkropp. Använd det för att lägga till hål eller skärningar som måste korsa en böj, och vik sedan ihop den igen.", + "help.sketch.arc.center_point": "Ritar en cirkelbåge runt en centrumpunkt, från en startpunkt till en slutpunkt. Använd det när bågens centrum är känt, till exempel en radie runt ett hål eller en vridpunkt.", + "help.sketch.arc.tangent": "Ritar en båge som börjar i änden av en linje eller båge och fortsätter tangentiellt mot den. Använd det för att fortsätta en kedja med en mjuk böj i stället för ett hörn.", + "help.sketch.arc.three_point": "Ritar en båge från en startpunkt till en slutpunkt genom en tredje punkt. Använd det när bågen ska gå genom givna punkter i stället för runt ett känt centrum.", + "help.sketch.arc3d": "Ritar en exakt cirkelbåge i rymden genom tre punkter, med 3D-skiss på. Använd det för böjar i banor och styrkurvor som lämnar skissplanet.", + "help.sketch.auto_constrain": "Lägger till de villkor som skissen nästan redan har, till exempel horisontell, parallell eller sammanfallande, och sätter sedan mått på den tills den är fullt definierad. Använd det för att låsa en grovt ritad skiss i ett enda steg.", + "help.sketch.auto_constrain_from_datum": "Fungerar som Autovillkor, men mäter lägena från en datumpunkt som du väljer i stället för origo. Använd det när delen läggs ut från en enda referenspunkt, till exempel ett hörn eller ett hål.", + "help.sketch.blend_curve": "Förbinder ändarna på två kurvor med en mjuk spline som tangerar båda, eller som även är krökningskontinuerlig om du väljer det. Använd det för att överbrygga ett glapp mellan kurvor utan knäck.", + "help.sketch.break": "Delar en kurva i bitar där andra kurvor korsar den, eller vid punkter som du placerar på den. Använd det när en del av en kurva behöver ett eget villkor eller ska tas bort för sig.", + "help.sketch.cancel": "Lämnar skissen och förkastar allt som ändrats sedan den skapades eller öppnades för redigering. Ångra tar tillbaka ändringarna.", + "help.sketch.centerline": "Växlar linjer mellan vanliga linjer och centrumlinjer, axlar som profiler utelämnar. Använd en centrumlinje som axel för en rotation, en spegling eller ett symmetrivillkor.", + "help.sketch.chamfer.distance_angle": "Fasar hörnet mellan två linjer, bestämt av ett avstånd längs den första linjen och en vinkel. Använd det när en ritning anger fasningen som en längd och en vinkel, till exempel 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Fasar hörnet mellan två linjer lika långt bakåt längs båda. Använd det för den vanliga 45°-fasningen på en kontur.", + "help.sketch.chamfer.two_distance": "Fasar hörnet mellan två linjer, bestämt av ett separat avstånd längs varje linje. Använd det för fasningar som inte är 45°, angivna som två längder.", + "help.sketch.circle.center": "Ritar en cirkel utifrån dess centrum och diameter. Använd det för hål, nav och andra runda former vars centrum är känt.", + "help.sketch.circle.three_point": "Ritar en cirkel genom tre punkter. Använd det när cirkeln ska gå genom givna punkter, till exempel på befintlig geometri.", + "help.sketch.circle.three_tangent": "Ritar en cirkel som tangerar tre linjer, cirklar eller bågar. Använd det för att passa in en cirkel i utrymmet mellan tre kurvor, till exempel en triangels inskrivna cirkel.", + "help.sketch.circle.two_point": "Ritar en cirkel utifrån diameterns två ändpunkter. Använd det när cirkelns kantpunkter är kända i stället för dess centrum.", + "help.sketch.circle.two_tangent": "Ritar en cirkel med en given storlek som tangerar två linjer, cirklar eller bågar. Använd det för en avrundning med fast radie mellan två kurvor.", + "help.sketch.conic": "Ritar en konisk kurva mellan två ändpunkter, formad av en toppunkt och ett rho-värde. Använd det för mjuka övergångar vars fyllighet du vill finjustera, från platt till nästan ett skarpt hörn.", + "help.sketch.constrainer": "Tillämpar det villkor som en eller två valda kurvor nästan redan har, till exempel horisontell, parallell, tangent eller lika. Använd det för att städa upp en frihandsritad skiss ett samband i taget.", + "help.sketch.constraint.coincident": "Gör att en punkt ligger på en annan punkt, en kurva eller en skissaxel. Använd det för att täppa till glapp i en profil eller för att lägga en punkt på en linje.", + "help.sketch.constraint.collinear": "Gör att två linjer ligger på samma räta linje. Använd det för att rikta in avbrutna kanter, till exempel båda sidor av ett urtag.", + "help.sketch.constraint.concentric": "Ger två cirklar eller bågar samma centrum. Använd det för ringar, försänkningar och axlar med skuldror.", + "help.sketch.constraint.curvature": "Låter två kurvor som möts i en ändpunkt fortsätta med samma krökning (G2). Använd det där en tangentiell övergång inte är tillräckligt jämn, till exempel på synliga ytor.", + "help.sketch.constraint.equal": "Gör linjer lika långa, eller cirklar och bågar med samma radie. Använd det så att ett mått styr flera motsvarande former.", + "help.sketch.constraint.fix": "Fäster punkter eller kurvor där de är, eller lossar dem igen. Använd det för geometri som inte får flytta sig när du drar i eller löser skissen.", + "help.sketch.constraint.horizontal_vertical": "Gör en linje, eller linjen mellan två punkter, horisontell eller vertikal, beroende på vilket som ligger närmast. Använd det för att räta upp en kontur mot skissaxlarna.", + "help.sketch.constraint.midpoint": "Placerar en punkt på mitten av en linje, eller låter två linjers mittpunkter sammanfalla. Använd det för att centrera geometri på en kant.", + "help.sketch.constraint.parallel": "Gör två linjer parallella. Använd det för sidor som ska förbli parallella när andra mått ändras.", + "help.sketch.constraint.perpendicular": "Låter två linjer mötas i rät vinkel. Använd det för räta hörn mellan linjer som inte ligger längs skissaxlarna.", + "help.sketch.constraint.polygon": "Gör en sluten kedja av linjer till en regelbunden polygon: lika långa sidor, med varje hörn på samma cirkel. Använd det för att göra en frihandsritad polygon regelbunden och hålla den så.", + "help.sketch.constraint.symmetry": "Låter två punkter eller kurvor spegla varandra över en linje eller kring en punkt. Använd det för att hålla en profil symmetrisk när du ändrar ena sidan.", + "help.sketch.constraint.tangent": "Låter två kurvor tangera varandra, till exempel en linje och en båge. Använd det för mjuka övergångar utan knäck.", + "help.sketch.construction": "Växlar kurvor mellan normal geometri och konstruktionsgeometri, som profiler utelämnar. Använd konstruktionskurvor som hjälpmedel för layout, referenser och mått.", + "help.sketch.construction_line": "Skapa en oändlig konstruktionslinje genom två punkter. Använd den för att lägga upp en skiss utan att dela profilerna.", + "help.sketch.construction_line.angle": "Skapa en oändlig konstruktionslinje i en vinkel mot skissens X-axel. Välj punkten och skriv vinkeln, eller välj dess riktning.", + "help.sketch.construction_line.bisector": "Välj två skärande raka skisslinjer och välj sedan någon av vinkelbisektriserna. Resultatet följer sina källlinjer.", + "help.sketch.construction_line.horizontal": "Skapa en oändlig horisontell konstruktionslinje genom en punkt. Det horisontella villkoret gäller även efter senare ändringar.", + "help.sketch.construction_line.parallel": "Välj en rak skisslinje och placera sedan en parallell, oändlig konstruktionslinje. Högerklicka för att välja en annan referens.", + "help.sketch.construction_line.perpendicular": "Välj en rak skisslinje och placera sedan en vinkelrät, oändlig konstruktionslinje. Högerklicka för att välja en annan referens.", + "help.sketch.construction_line.tangent_at": "Skapa en tangent i en punkt på en cirkel eller cirkelbåge, eller i en ändpunkt på en öppen spline eller konisk kurva. Välj kurvan och sedan beröringspunkten.", + "help.sketch.construction_line.tangent_external": "Välj en cirkel eller cirkelbåge, sedan en yttre punkt och en tangentlösning. Förhandsvisningarna visar bara beröringspunkter på den ritade bågen.", + "help.sketch.construction_line.tangent_two": "Välj två cirklar eller cirkelbågar och välj sedan en gemensam tangent i förhandsvisningen. Beröringspunkterna måste ligga på de ritade kurvorna.", + "help.sketch.construction_line.vertical": "Skapa en oändlig vertikal konstruktionslinje genom en punkt. Det vertikala villkoret gäller även efter senare ändringar.", + "help.sketch.copy": "Kopierar de markerade skisskurvorna och skisspunkterna, tillsammans med villkoren och måtten mellan dem. Klistra in dem i den här skissen eller i en annan.", + "help.sketch.create": "Startar en ny 2D-skiss på ett plan eller på en plan yta på modellen. Varje extrudering, rotation och svepning börjar med en skiss.", + "help.sketch.cut": "Kopierar den markerade skissgeometrin och tar bort den från skissen, i ett enda ångrasteg. Klistra in den någon annanstans i den här skissen eller i en annan.", + "help.sketch.dimension": "Lägger till ett styrande mått: en längd, ett avstånd, en vinkel, en radie eller en diameter, beroende på vad du väljer. Skriv ett värde eller ett parameternamn så följer skissen det.", + "help.sketch.edit": "Öppnar en befintlig skiss för redigering. Funktionerna som bygger på den uppdateras när du avslutar skissen.", + "help.sketch.ellipse": "Ritar en ellips utifrån dess centrum, änden av dess huvudaxel och en punkt på dess korta sida. Använd det för ovala öppningar, kammar och andra avlånga runda former.", "help.sketch.equation_curve": "Ritar en kurva utifrån formler: x(t) och y(t), eller y = f(x), över ett intervall. Formlerna kan använda parametrar och kurvan följer dem: använd den för en sinusvåg, en spiral eller evolventen på en kugge.", + "help.sketch.extend": "Förlänger en linje eller båge till närmaste kurva i dess väg, eller förlänger två kurvor tills de möts. Använd det för att täppa till glapp i en profil efter trimning eller redigering.", + "help.sketch.fillet": "Rundar av hörnet där två linjer eller bågar möts med en båge med en given radie. Flera hörn som rundas av tillsammans delar samma radie.", + "help.sketch.finish": "Lämnar skissen och återgår till modellen. Dess slutna profiler är då redo för Extrudera, Rotation och andra funktioner.", + "help.sketch.finish_auto_constrain": "Kör Autovillkor på skissen och avslutar den sedan. Använd det för att lämna en skiss fullt definierad i ett enda steg.", + "help.sketch.fit_curves_to_section": "Skär en mesh- eller solidkropp med skissplanet och anpassar linjer och bågar till snittet. Använd det för att bygga om en skannad eller importerad del som en redigerbar skiss.", + "help.sketch.include_3d": "Tar in modellkanter, hörn och kurvor från andra skisser i den här skissen som länkade referenser och plattar ut sådana som ligger utanför dess plan på det. Använd det för att bygga vidare på geometri som inte ligger i skissplanet.", + "help.sketch.infinite": "Växlar linjer mellan vanliga linjer och oändliga konstruktionslinjer som löper över hela vyn. Använd dem som layoutreferenser som aldrig tar slut för tidigt.", + "help.sketch.insert_dxf": "Läser in kurvorna från en DXF-ritning i en skiss, skalade, vridna och placerade där du anger. Använd det för att bygga vidare på en 2D-ritning från ett annat program, till exempel en kontur för laserskärning.", + "help.sketch.insert_svg": "Läser in banorna från en SVG-ritning i en skiss, skalade, vridna och placerade där du anger. Använd det för att göra en logotyp eller en vektorkontur till kurvor som du kan extrudera.", + "help.sketch.inspect": "Öppnar en rapport om den öppna skissen: hur många frihetsgrader som återstår och om den är fullt definierad. Använd det för att ta reda på vad som fortfarande rör sig innan du avslutar skissen.", + "help.sketch.intersect": "Lägger till de kurvor eller punkter där kroppar, ytor, kanter eller andra skisser korsar skissplanet. De förblir länkade och följer modellen när den ändras.", + "help.sketch.intersection_curve": "Skapar 3D-kurvor där två kroppar eller ytor möts, länkade till dem. Använd dem som banor eller styrkurvor som följer modellen.", + "help.sketch.isoparametric_curve": "Skapar en 3D-kurva längs en ytas U- eller V-riktning genom en punkt som du väljer, länkad till ytan. Använd den som en bana eller delningslinje som följer ytan.", + "help.sketch.line": "Ritar sammanhängande linjer punkt för punkt, som en öppen kedja eller en sluten kontur. Det är det grundläggande verktyget för de flesta profiler.", + "help.sketch.line.midpoint": "Ritar en linje från dess mittpunkt ut till ena änden, med den andra änden speglad. Använd det för linjer centrerade på en punkt, till exempel en symmetrisk kant.", + "help.sketch.line3d": "Ritar sammanhängande raka linjer mellan punkter i rymden, med 3D-skiss på. Använd det för banor och ramar som lämnar skissplanet.", + "help.sketch.mirror": "Speglar skisskurvor och skisspunkter över en linje eller axel och lägger till symmetrivillkor. Använd det för att rita ena halvan av en symmetrisk profil och komplettera den.", + "help.sketch.move": "Flyttar eller roterar skisskurvor och skisspunkter, eller en kopia av dem. Använd det för att flytta om geometri och samtidigt behålla dess form och villkor.", + "help.sketch.offset": "Skapar en kopia av en kedja av kurvor på ett bestämt avstånd, på ena sidan eller båda. Använd det för väggar, konturer och frigångar; avståndet förblir ett redigerbart mått.", + "help.sketch.paste": "Klistrar in kopierad eller utklippt skissgeometri i den aktiva skissen. Placera den vid en punkt eller flytta den ett visst avstånd.", + "help.sketch.pattern.circular": "Kopierar skissgeometri runt en centrumpunkt, över ett helt varv eller en bestämd vinkel. Använd det för hålcirklar, ekrar och tänder.", + "help.sketch.pattern.rectangular": "Kopierar skissgeometri i rader och kolumner med bestämda avstånd. Använd det för rutnät av hål, spår eller ventilationsöppningar.", + "help.sketch.point": "Placerar en skisspunkt. Använd den som referens för mått, villkor, hålcentrum eller senare funktioner.", + "help.sketch.point3d": "Placerar en punkt i rymden, med 3D-skiss på. Använd den som referens för 3D-kurvor och banor.", + "help.sketch.polygon.circumscribed": "Ritar en regelbunden polygon runt en cirkel, med storleken bestämd från dess centrum till mitten av en sida. Använd det när nyckelvidden är känd, som för en sexkantsmutter.", + "help.sketch.polygon.edge": "Ritar en regelbunden polygon utifrån en sidas två ändpunkter. Använd det när längden och läget på en sida är kända.", + "help.sketch.polygon.inscribed": "Ritar en regelbunden polygon inuti en cirkel, med storleken bestämd från dess centrum till ett hörn. Använd det när måttet över hörnen är känt.", + "help.sketch.project": "Tar in modellkanter, ytor, hörn och kurvor från andra skisser i den här skissen, projicerade på dess plan. De förblir länkade och följer modellen när den ändras.", + "help.sketch.project_to_surface": "Projicerar kurvor från andra skisser längs den här skissens normal på en yta, som länkade 3D-kurvor. Använd det för att lägga en logotyp, delningslinje eller bana på en böjd yta.", + "help.sketch.rectangle.center": "Ritar en rektangel utifrån dess centrum och ett hörn. Använd det för konturer centrerade på en punkt, till exempel origo.", + "help.sketch.rectangle.rounded": "Ritar en rektangel med alla fyra hörn avrundade med samma radie. Använd det för plattor, lock och öppningar med rundade hörn.", + "help.sketch.rectangle.three_point": "Ritar en rektangel utifrån en kant och en punkt på motsatt sida. Använd det för rektanglar som ligger i vinkel mot skissaxlarna.", + "help.sketch.rectangle.two_point": "Ritar en rektangel utifrån två motstående hörn. Använd det för konturer av plattor, block och fickor.", + "help.sketch.scale": "Skalar skisskurvor och skisspunkter med en faktor kring en baspunkt. Använd det för att ändra storlek på en del av en skiss utan att rita om den.", + "help.sketch.slot.arc_center": "Ritar ett böjt spår med en given bredd längs en båge som bestäms av dess centrum, start och slut. Använd det för justerspår runt en vridpunkt.", + "help.sketch.slot.arc_three_point": "Ritar ett böjt spår med en given bredd längs en båge genom tre punkter. Använd det när spårets bana ska gå genom givna punkter.", + "help.sketch.slot.center_point": "Ritar ett rakt spår med en given bredd från dess centrum till centrum av ena ändbågen. Använd det för spår centrerade på en punkt.", + "help.sketch.slot.center_to_center": "Ritar ett rakt spår med en given bredd mellan centrum för dess två ändbågar. Använd det för spår som mäts centrum till centrum, till exempel justerspår för skruvar.", + "help.sketch.slot.overall": "Ritar ett rakt spår med en given bredd från ena yttre änden till den andra. Använd det när spårets totala längd är det som räknas.", + "help.sketch.spline.control_point": "Ritar en kubisk spline som formas av kontrollpunkter som den inte går genom. Använd det för mjuka, flytande kurvor som du formar genom att flytta punkterna.", + "help.sketch.spline.control_point_5": "Ritar en spline av grad 5 som formas av kontrollpunkter. Använd det där kurvor ska mötas med jämnare krökning, till exempel på synliga designytor.", + "help.sketch.spline.fit_point": "Ritar en mjuk spline som går genom varje punkt du placerar, öppen eller sluten. Använd det för att följa en form genom kända punkter.", + "help.sketch.spline3d": "Ritar en mjuk kurva i rymden genom punkter, med 3D-skiss på. Använd det för svepbanor och kabeldragningar som lämnar skissplanet.", + "help.sketch.spun_profile": "Skapar i skissplanet den kontur som en kropp sveper över när den vrids kring en axel. Använd det för att få silhuetten av en svarvad del till en rotation eller en ritning.", + "help.sketch.text": "Skriver text i skissen med valt teckensnitt, vald höjd och vinkel; orden kan följa parametrar. Extrudera eller prägla den för etiketter och märkning.", + "help.sketch.transform": "Skalar, vrider och flyttar skissgeometri kring en centrumpunkt i ett enda steg. Använd det för att flytta om och ändra storlek på en markering samtidigt.", + "help.sketch.trim": "Tar bort den bit av en kurva som ligger mellan de närmaste skärningarna runt den punkt du klickar på. Använd det för att städa upp överlappande linjer till en sluten profil.", "help.solid.align": "Flyttar de markerade kropparna så att en punkt, yta eller ett plan på dem möter en punkt, yta eller ett plan någon annanstans. Använd det för att placera en del mot en annan utan att mäta förskjutningen.", + "help.solid.boundary_fill": "Skapar solider av de områden som omsluts av överlappande verktygskroppar, och fyller bara de områden du väljer. Använd det för att bygga en form av det utrymme som flera kroppar tillsammans avgränsar.", + "help.solid.bounding_solid": "Skapar ett block som omsluter de markerade kropparna, med valfri marginal. Använd det för att se en dels totala storlek, eller som det ämne den bearbetas ur.", + "help.solid.box": "Skapar ett block utifrån längd, bredd och höjd, från en hörnpunkt eller centrerat på en punkt. Använd det för ett snabbt block, en platshållare eller en kropp att skära funktioner i.", "help.solid.chamfer": "Fasar de markerade kanterna med en plan fas på det avstånd du anger. Använd det för att bryta skarpa kanter eller underlätta införandet av ett stift eller en skruv.", + "help.solid.coil": "Skapar en spiralformad kropp, till exempel en fjäder, utifrån diameter, antal varv, höjd eller stigning och ett runt eller kvadratiskt tvärsnitt. Använd det för fjädrar, spolar och spiralformade åsar.", "help.solid.combine": "Sammanfogar kroppar, skär bort dem från en målkropp eller behåller bara den volym de delar, och kan behålla verktygskropparna. Använd det för att slå ihop delar, skära en form med en annan eller hitta var två kroppar överlappar.", + "help.solid.cone": "Skapar en kon utifrån en bascirkel och en höjd, eller en stympad kon när toppen också har en radie. Använd det för avsmalningar, trattar, kägelsänkningar och spetsar.", + "help.solid.cylinder": "Skapar en cylinder utifrån en radie eller diameter och en höjd, stående på en punkt längs en axel. Använd det för axlar, stift, nav och runda ämnen.", "help.solid.draft": "Lutar de markerade ytorna med den vinkel du anger, mätt från ett neutralt plan. Använd det på gjutna eller formsprutade delar så att de släpper ur formen.", + "help.solid.emboss": "Höjer skissprofiler, till exempel text eller en logotyp, upp ur en yta, eller sänker ned dem i den. Använd det för text, etiketter och markeringar på plana eller runda ytor.", "help.solid.extrude": "Trycker en skissprofil ut i 3D över ett avstånd och lägger till eller tar bort material. Använd det för att göra en plan kontur till ett block, ett nav eller en ficka.", "help.solid.fillet": "Avrundar de markerade kanterna med en jämn cirkulär övergång med den radie du anger. Använd det för att mjuka upp skarpa kanter för hållfasthet, bekvämlighet eller utseende.", "help.solid.hole": "Borrar ett runt hål med den diameter du anger vid en vald punkt på en yta. Använd det för frigångshål till skruvar, stift och andra enkla runda öppningar.", @@ -1408,20 +1679,62 @@ "help.solid.move": "Flyttar eller roterar de markerade kropparna, eller en kopia av dem, med det avstånd och den vinkel du anger. Använd den för att flytta om en kropp eller skapa en till på ett annat ställe.", "help.solid.offset_face": "Skjuter de markerade ytorna inåt eller utåt med det avstånd du anger, och ytorna runt omkring följer med. Använd den för att göra en vägg tjockare, en ficka djupare eller ett nav högre utan att redigera skissen.", "help.solid.pattern.circular": "Upprepar de markerade objekten runt en axel, med det antal och den totala vinkel du anger. Använd den för hålcirklar, ekrar, kylflänsar och tänder.", + "help.solid.pattern.path": "Kopierar funktioner eller kroppar längs en skissbana, med antal och avstånd. Använd det för hål längs en böjd kant eller delar längs en skena.", "help.solid.pattern.rectangular": "Upprepar de markerade objekten i en eller två riktningar med det antal och det avstånd du anger. Använd den för rader och rutnät av hål, revben, stift eller fötter.", + "help.solid.pipe": "Skapar ett runt rör längs en bana av skisskurvor, massivt eller ihåligt med en väggtjocklek. Använd det för rör, trådar, kablar och skenor.", "help.solid.press_pull": "Lägger till eller tar bort material när du drar i en yta, eller rundar av kanter när du drar i dem. Använd den för snabba ändringar direkt på modellen.", "help.solid.remove": "Tar bort de markerade kropparna från konstruktionen från och med den här punkten i tidslinjen; tidigare steg behåller dem. Använd den för att bli av med en hjälpkropp, till exempel ett skärverktyg som du inte längre behöver.", "help.solid.replace_face": "Flyttar de markerade plana ytorna till ett plan eller till en parallell yta, och kroppen växer eller krymper så att den når fram. Använd den för att få en yta i nivå med en annan del eller ett konstruktionsplan.", "help.solid.revolve": "Roterar en skissprofil runt en axel och skapar en rund kropp. Använd den för axlar, vred, skålar och alla delar som är runda kring en mittlinje.", + "help.solid.rib": "Lägger till en tunn vägg längs en öppen skisskurva, som fylls ut till kroppens närmaste ytor. Använd det för att stärka väggar och hörn, till exempel i formsprutade eller utskrivna delar.", "help.solid.scale": "Gör de markerade kropparna större eller mindre med en faktor, lika i alla riktningar eller en per axel. Använd den för att ändra storlek på en importerad form eller för att ta hänsyn till krympning.", "help.solid.shell": "Urholkar en kropp så att väggar med den tjocklek du anger blir kvar, och kan öppna de ytor du väljer. Använd den för lådor, lock och andra tunnväggiga delar.", + "help.solid.sphere": "Skapar en sfär utifrån en radie eller diameter kring en centrumpunkt. Använd det för kulor, knoppar och rundade ändar.", "help.solid.split_body": "Delar en kropp i separata kroppar med ett plan, ytan på en annan kropp eller en skisslinje. Använd den för att skapa delar som skrivs ut, bearbetas eller färgas var för sig.", "help.solid.split_face": "Delar de markerade ytorna längs ett plan, ytan på en annan kropp eller skisskurvor, utan att skära i kroppen. Använd den för att ge en del av en yta egen släppvinkel, färg eller förskjutning.", "help.solid.sweep": "Drar en skissprofil längs en bana och skapar en kropp. Använd den för rör, skenor, handtag och alla delar med konstant tvärsnitt som följer en kurva.", + "help.solid.thread": "Lägger till en ISO-metrisk gänga på en cylindrisk yta, antingen som en kosmetisk gänga eller skuren in i kroppen. Använd det för bultar, gängade hål och utskrivna skruvdelar.", + "help.solid.torus": "Skapar en ring utifrån en stor radie kring dess axel och en liten radie för dess runda tvärsnitt. Använd det för O-ringar, handtag och runda pärlor.", + "help.solid.web": "Lägger till en tunn vägg längs varje öppen skisskurva, var och en utfylld till kroppens närmaste ytor. Använd det för ett rutnät av stödväggar inuti höljen och brickor.", + "help.surface.blend": "Skapar en yta som överbryggar kanterna på två kroppar, tangent- eller krökningskontinuerlig mot båda. Använd det för att foga samman två ytor mjukt över ett glapp.", + "help.surface.boundary": "Skapar en yta som fyller en slinga av två till fyra skisskurvor, eller ett nät av kurvor. Använd det för friformade paneler som bestäms av sina kanter.", + "help.surface.extend": "Förlänger en yta förbi dess kanter, med ett avstånd eller upp till ett plan eller en yta. Använd det så att ytor överlappar innan du trimmar eller syr ihop dem.", + "help.surface.extrude": "Trycker skisskurvor eller profiler ett visst avstånd till en yta, bara väggar, utan lock. Använd det för tunna väggar och för skär- eller delningsverktyg.", + "help.surface.fair": "Jämnar ut det inre av friformade ytor medan deras kanter ligger kvar. Använd det för att jämna ut bulor och vågiga reflektioner i en yta.", + "help.surface.loft": "Skapar en yta som går genom två eller flera tvärsnitt i ordning, utan lock. Använd det för skal och övergångar mellan olika former.", + "help.surface.match": "Bygger om kanten på en yta så att den möter en annan kropps kant, med matchande tangent eller krökning. Använd det för att sluta en skarv mjukt mellan två ytor.", + "help.surface.offset": "Skapar en kopia av ytor på ett avstånd längs deras normaler, som en ny ytkropp. Använd det för ytskikt, frigångar eller andra sidan av en vägg.", + "help.surface.patch": "Fyller ett skissområde eller en sluten slinga av kanter med en yta, plan eller mjukt böjd. Använd det för att täppa till hål i en ytkropp.", + "help.surface.reverse_normal": "Vänder ytor på en ytkropp, så att deras utsida vetter åt andra hållet. Använd det före förtjockning eller ihopsyning när ytorna pekar inåt.", + "help.surface.revolve": "Vrider skisskurvor eller profiler kring en axel till en yta, utan lock. Använd det för runda skal som lampskärmar, skålar och munstycken.", + "help.surface.ruled": "Skapar ett band av raka linjer ut från en kedja av kanter, längs ytans normal, tangent eller i en vinkel. Använd det för väggar med släppvinkel, utlopp och delningsytor.", + "help.surface.stitch": "Syr ihop ytkroppar längs sina gemensamma kanter, till en solid när de sluter sig. Använd det för att göra en uppsättning ytor till en enda kropp.", + "help.surface.sweep": "Drar skisskurvor eller profiler längs en bana till en yta, utan lock. Använd det för hängrännor, lister och andra tunna former som följer en bana.", + "help.surface.thicken": "Ger en ytkropp en tjocklek och gör den till en solid. Använd det för att göra utskrivbara eller bearbetningsbara delar av ytor.", + "help.surface.trim": "Skär en yta med ett plan, en annan yta eller skisskurvor och behåller den sida du väljer. Använd det för att skära ytor till form före ihopsyning.", + "help.surface.unstitch": "Separerar ytorna på en kropp till egna ytkroppar; en solid faller isär i ytor. Använd det för att arbeta om enskilda ytor på en kropp.", + "help.surface.untrim": "Tar bort hål från en yta, eller återställer dess yttre gräns till ytans naturliga gränser. Använd det för att få tillbaka hela ytan efter en trimning.", "help.third_party": "Licenser från tredje part", "help.timeline.compute_all": "Bygger om alla funktioner i tidslinjen från början. Använd den för att uppdatera modellen och se vilka funktioner som misslyckas.", "help.timeline.delete": "Tar bort de markerade funktionerna från tidslinjen; om du tar bort en skiss tas även funktionerna som bygger på den bort. Använd den för att ta bort ett steg som inte längre behövs.", + "help.timeline.dependents": "Listar de funktioner som skulle tas bort tillsammans med en funktion, och de som skulle misslyckas utan den. Använd det innan du tar bort eller ändrar en funktion.", "help.timeline.play": "Spela upp de återstående funktionerna en i taget, med en halv sekunds paus efter varje ombyggnad. Kör kommandot igen eller tryck på Escape för att stoppa; Gå till slutet hoppar direkt.", + "help.view.apply": "Vrider vyn till en standardriktning som framifrån, ovanifrån eller iso, eller till en sparad namngiven vy. Använd det för att titta på modellen från en fast vinkel.", + "help.view.delete": "Tar bort en sparad namngiven vy. Modellen ändras inte.", + "help.view.fit": "Zoomar och panorerar så att hela modellen, eller markeringen, fyller vyn. Använd det när modellen har hamnat utom synhåll.", + "help.view.grid": "Visar eller döljer rutnätet i vyfönstret. Använd det som hjälp för storlek och orientering under modellering.", + "help.view.ground_shadow": "Visar eller döljer modellens skugga på marken. Använd det för att lättare bedöma höjd och läge.", + "help.view.home": "Vrider tillbaka vyn till hemvyn och anpassar den efter modellen. Använd det för att snabbt komma tillbaka till en känd vy.", + "help.view.list": "Listar de namngivna vyer som sparats i konstruktionen. Använd det för att hitta en vy som du sparat tidigare.", + "help.view.navigate": "Vrider, panorerar eller zoomar vyn i steg, till exempel ett kvarts varv åt vänster. Använd det för att flytta kameran exakt i stället för att dra.", + "help.view.navigation_bar": "Visar eller döljer navigeringsfältet längst ned i vyfönstret. Dölj det för mer utrymme, visa det för att nå vyverktygen med musen.", + "help.view.rename": "Ger en sparad namngiven vy ett nytt namn. Själva vyn förblir densamma.", + "help.view.save": "Sparar den aktuella kameraplaceringen som en namngiven vy i konstruktionen. Använd det för att komma tillbaka till samma vinkel senare, till exempel för skärmbilder.", + "help.view.spin": "Orbiterar vyn kring modellen kontinuerligt till nästa klick eller tangenttryckning. Använd det för att visa en modell från alla sidor.", + "help.view.tool": "Låser ett kameraverktyg, orbitera, panorera eller zooma, så att dragning med vänster musknapp flyttar vyn tills du stänger av det. Använd det på en styrplatta eller utan mittenmusknapp.", + "help.view.visual_style": "Växlar hur modellen ritas: skuggad med eller utan kanter, trådram, eller med dolda kanter. Använd trådram för att se in i modellen, skuggad för ett rent utseende.", + "history.sketch_under_constrained": "Underbestämd ({count} frihetsgrader)", + "history.sketch_under_constrained_one": "Underbestämd ({count} frihetsgrad)", "hole_presets.confirm_delete": "Bekräfta borttagning", "hole_presets.delete": "Ta bort", "hole_presets.delete_prompt": "Ta bort den här personliga förinställningen? Befintliga hål påverkas inte.", @@ -1525,6 +1838,8 @@ "joint_move.blocked_hint": "Kontrollera ledtypen (till exempel Styv), fixering, ledgränser och parameterstyrda värden.", "joint_move.blocked_title": "Det går inte att flytta den här delen", "joint_move.coarse": "Rotationssteg nära axeln (°)", + "joint_move.conflict": "En led på den här delen står i konflikt med de andra: {joint}.", + "joint_move.conflict_hint": "Redigera, undertryck eller ta bort den konflikterande leden så att de andra lederna kan placera delen.", "joint_move.distance": "Avstånd från start", "joint_move.done": "Klar", "joint_move.fine": "Rotationssteg långt från axeln (°)", @@ -1596,6 +1911,10 @@ "material.selection.mixed": "Olika material", "measure.at": "Vid", "measure.item": "Objekt {number}", + "measure.quick_copied": "Mätningen kopierad", + "measure.quick_copy": "Klicka för att kopiera mätningen", + "measure.quick_edges": "{count} kanter", + "measure.quick_faces": "{count} ytor", "messages.ago_h": "för {n} h sedan", "messages.ago_min": "för {n} min sedan", "messages.ago_s": "för {n} s sedan", @@ -1620,6 +1939,8 @@ "motion.track_name": "Spår {number}", "nav.alias.help": "Shift+Alt+vänsterdrag orbiterar, Shift+Alt+mittdrag panorerar, Shift+Alt+högerdrag zoomar; mittdrag panorerar också och högerdrag orbiterar", "nav.blender.help": "Mittdrag orbiterar, Shift+mittdrag panorerar, Ctrl+mittdrag zoomar; högerdrag påverkar inte kameran", + "nav.creo.help": "Mittdrag orbiterar, Shift+mittdrag panorerar, Ctrl+mittdrag i lodrät led zoomar (neråt för att zooma in); rullning med hjulet zoomar", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Mus och 3D-mus roterar genom båda polerna och bevarar rollvinkeln. Axelsnappning med Shift är inaktiverad.", "nav.free_orbit.label": "Fri orbit", "nav.free_orbit.snap_help": "Mus och 3D-mus roterar genom båda polerna och bevarar rollvinkeln. Håll ned Shift under ett orbitdrag för att snappa vyriktningen och rollvinkeln.", @@ -1629,6 +1950,7 @@ "nav.hfss.help": "Alt+vänsterdrag panorerar, Shift+Alt+vänster zoomar, Ctrl+vänsterdrag på tom yta orbiterar", "nav.inventor.help": "Mittdrag panorerar, Shift+mittdrag orbiterar, Ctrl+mittdrag zoomar, högerdrag orbiterar", "nav.maya.help": "Alt+vänsterdrag orbiterar, Alt+mittknapp panorerar, Alt+högerknapp zoomar; mittknappsdrag panorerar också", + "nav.nx.help": "Mittdrag orbiterar, Shift+mittdrag panorerar (i NX: mitten + höger), Ctrl+mittdrag zoomar (i NX: mitten + vänster); högerdrag påverkar inte kameran", "nav.openscad.help": "Vänsterdrag på tomt utrymme orbiterar, Shift+vänsterdrag markerar med ruta, drag på skissgeometri redigerar; höger- eller mittdrag panorerar, Shift+höger- eller Shift+mittdrag zoomar", "nav.perspective.sketch": "Skissredigering använder ortografisk vy. Slutför skissen för att växla till perspektiv.", "nav.right_drag_orbits.help": "Av: ett högerdrag påverkar inte kameran och högerknappen öppnar bara snabbmenyn. Om du väljer musmappningen SolidWorks stängs det av.", @@ -1748,6 +2070,11 @@ "not a move": "inte en förflyttning", "not a number": "inte ett tal", "open a sketch first": "öppna en skiss först", + "parameters.apply_live": "Tillämpa varje ändring när du lämnar dess fält", + "parameters.apply_live_tip": "Av: ändringar väntar tills du trycker på Tillämpa eller OK, och sedan byggs konstruktionen om en gång för alla. Avbryt eller Escape förkastar dem.", + "parameters.held": "{count} ändringar väntar på Tillämpa", + "parameters.held_hint": "Redigera uttryck och enheter. Ändringar väntar på Tillämpa eller OK.", + "parameters.held_one": "1 ändring väntar på Tillämpa", "parts.automatic_name": "automatisk", "parts.dimension.across_flats": "Nyckelvidd", "parts.dimension.bore": "Håldiameter", @@ -1766,10 +2093,19 @@ "parts.family.button_head_cap_screw": "Kullrig insexskruv", "parts.family.dowel_pin": "Cylindriskt stift (passtift)", "parts.family.hex_bolt": "Sexkantsbult / sexkantsskruv", + "parts.family.hex_cap_screw_inch": "Sexkantsskruv (tum)", "parts.family.hex_nut": "Sexkantsmutter", + "parts.family.hex_nut_inch": "Sexkantsmutter (tum)", "parts.family.set_screw": "Stoppskruv med insex, plan ände", "parts.family.socket_head_cap_screw": "Cylinderskruv med insex", "parts.family.washer": "Plan bricka", + "parts.family.washer_sae": "Plan bricka, SAE (smal)", + "parts.family.washer_uss": "Plan bricka, USS (bred)", + "parts.holes": "Hål (valfritt)", + "parts.placement_hint": "välj ett eller flera hål för att sätta en del i varje, eller OK placerar den i origo", + "parts.system": "Enhetssystem", + "parts.system.inch": "Tum", + "parts.system.metric": "Metriskt", "pattern.alignment_2": "Justering 2", "pattern.alignment_hint": "Antalet inkluderar originalet. Centrera balanserar kopiorna; Vänd väljer den extra sidan för jämna totaler.", "pattern.direction_1": "Riktning 1", @@ -1810,6 +2146,8 @@ "prefs.anti_aliasing_note": "Jämnar ut hackiga kanter.", "prefs.applies_on_restart": "Tillämpas vid omstart", "prefs.assistant": "Assistent", + "prefs.auto_operation": "Välj operation automatiskt", + "prefs.auto_operation_note": "Funktionsdialoger väljer Sammanfoga, Ny kropp eller Klipp ut utifrån vad det nya materialet rör vid, tills du väljer själv. Av: de behåller den operation de öppnas med.", "prefs.axes": "Axlar", "prefs.axis": "Axel", "prefs.bodies_folders": "Kroppsmappar", @@ -1820,6 +2158,8 @@ "prefs.bottom_centre": "Nere i mitten", "prefs.bottom_right": "Nere till höger", "prefs.browser": "Webbläsare", + "prefs.browser_eye_left": "Ögat bredvid expanderingspilen", + "prefs.browser_eye_left_note": "Raderna i webbläsaren visar sitt visa/dölj-öga bredvid expanderingspilen, som tidigare, i stället för i en kolumn längst till höger i raderna.", "prefs.browser_reveal_on_hover": "Visa vid hovring", "prefs.browser_show_note": "Visas håller webbläsaren på skärmen. Visa vid hovring håller den dold tills pekaren kommer över dess plats eller den smala fliken vid dess vänstra kant, och den förblir öppen medan pekaren är inuti den eller en meny från den är öppen.", "prefs.browser_shown": "Visas", @@ -1827,6 +2167,8 @@ "prefs.button_left": "Dra med vänsterknapp", "prefs.button_middle": "Dra med mittknapp", "prefs.button_right": "Dra med högerknapp", + "prefs.carousel_next": "Nästa", + "prefs.carousel_previous": "Föregående", "prefs.choose_font": "Välj teckensnittsfil…", "prefs.click": "Klick", "prefs.contact_shading": "Mjuk kontaktskuggning", @@ -1839,6 +2181,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Krökta ytor", "prefs.curves": "Krökta ytor", + "prefs.cut_preview_tint": "Visa borttaget material i rött", + "prefs.cut_preview_tint_help": "En förhandsvisning fyller det material som en funktion tar bort, och den form den ersätter, med ett rött genomskinligt spöke. När det är av är fyllningarna helt genomskinliga och bara deras konturer ritas.", + "prefs.dark_parts_shading": "Behåll formen på mörka delar", + "prefs.dark_parts_shading_help": "Skuggar vyn i linjärt ljus med en mjuk himmelsfyllnad, så att mörka ytor behåller en gradient i stället för att bli svarta", "prefs.dead_zone_note": "Det skrafferade bandet är dödzonen: rörelse inom det ignoreras.", "prefs.default": "standard", "prefs.design": "Standardvärden för konstruktioner", @@ -1853,6 +2199,8 @@ "prefs.edges": "Kanter och skuggning", "prefs.extend": "Förläng", "prefs.extra_navigation": "Ctrl+vänsterdrag på ett tomt område orbiterar; håll Blanksteg för att panorera.", + "prefs.extrude_view_isometric": "Vrid vyn till isometrisk när Extrudera öppnas", + "prefs.extrude_view_return": "Gå tillbaka till den tidigare vyn när Extrudera stängs", "prefs.follows_os": "Följer operativsystemet", "prefs.font": "Teckensnitt", "prefs.font_fallback": "Tecken som det valda teckensnittet saknar ersätts av det inbyggda teckensnittet, så ingen etikett visar en tom ruta.", @@ -1868,8 +2216,11 @@ "prefs.graphics_card_auto": "Automatisk", "prefs.graphics_card_missing": "Det sparade grafikkortet är inte tillgängligt; Automatisk används.", "prefs.graphics_card_restart": "Träder i kraft efter att SolidCraft startats om. WGPU_ADAPTER_NAME åsidosätter detta val.", + "prefs.graphics_card_unused": "Det sparade grafikkortet användes inte för det här fönstret. Kortet som används visas i Hjälp › Om och i statusfältet. Prova Automatisk, eller ange WGPU_ADAPTER_NAME som en unik del av kortets namn.", "prefs.graphics_note": "Avväg hastighet mot jämnhet. Varje val visar sin effekt på ett exempel.", "prefs.graphics_presets_note": "Förinställningar anger valen nedan tillsammans.", + "prefs.hide_constraint_glyphs_zoomed_out": "Dölj villkorssymboler vid utzoomning", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Villkorssymbolerna försvinner från vyn när skissen zoomas ut så långt att de skulle skräpa ned den. Av: de behåller en fast storlek på skärmen vid varje zoomnivå.", "prefs.history": "Historik", "prefs.history_origin_bodies": "Visa origo och kroppar överst", "prefs.history_origin_bodies_note": "Historiken till vänster eller under webbläsaren börjar med den aktiva komponentens mapp Kroppar och Origo, med sina ögon och menyer som i webbläsaren. Historiken längst ned är oförändrad.", @@ -1880,6 +2231,8 @@ "prefs.history_sketches_note": "Med Skisser inställt på Under sin funktion listar historiken till vänster varje skiss en nivå in, under den första funktionen som byggts från den, så snart den är bred nog för namn. Tidslinjen längst ned behåller alltid skapandeordningen.", "prefs.history_sketches_under_feature": "Under sin funktion", "prefs.hold_stop_snapping": "Håll nedtryckt för att stoppa snappning", + "prefs.home_fit_size": "Storlek för Hem och Anpassa", + "prefs.home_fit_size_note": "Hur mycket av vyn modellen fyller när Hem, Anpassa, en öppnad konstruktion eller en vyändring i navigatorn ramar in den, oavsett om inställningen nedan är på eller inte. 100 %: fyller vyn mellan panelerna, kompassen och navigeringsfältet.", "prefs.icons_only": "Endast ikoner", "prefs.imported_file": "Importerad fil", "prefs.in_browser": "I webbläsaren", @@ -1888,13 +2241,22 @@ "prefs.interface_language": "Gränssnittsspråk", "prefs.interface_note": "Hur SolidCraft ser ut och var dess delar placeras.", "prefs.interval_minutes": "{n} min", + "prefs.invert_curved_roll_arrows": "Invertera de böjda rullningspilarna", + "prefs.invert_curved_roll_arrows_note": "De två böjda pilarna vid kubens hörn rullar vyn i skärmplanet. På: medurspilen rullar moturs och moturspilen rullar medurs. Av: varje pil rullar vyn åt det håll den kröker sig.", + "prefs.invert_navigator_arrows": "Invertera rotationspilarna på vykuben", + "prefs.invert_navigator_arrows_note": "Pilarna runt kuben orbiterar kameran åt det håll de pekar, som i Fusion och Inventor: pilen till vänster pekar åt höger och svänger kameran åt höger. Av: en pil roterar kuben mot den sida den sitter på, så den vänstra pilen svänger kameran åt vänster. De böjda rullningspilarna påverkas inte.", + "prefs.keep_work_on_tab_switch": "Behåll dialoger och verktyg öppna när du byter konstruktion", + "prefs.keep_work_on_tab_switch_note": "Varje konstruktionsflik behåller sin öppna dialog eller sitt öppna verktyg, med det du har valt och skrivit i den, och sin flik i menyfliksområdet. De finns kvar när du kommer tillbaka till konstruktionen. Av: att byta konstruktion avbryter dem och visar fliken Modell.", "prefs.labels": "Etiketter", + "prefs.language_system": "System", "prefs.layout": "Layout", "prefs.layout_note": "Kompakt dockar paneler mot fönsterkanterna. Genomskinlig webbläsare finns i Flytande. Ändra assistentens sida på sidan Assistent.", "prefs.left": "Vänster", "prefs.left_click": "Vänsterklick", "prefs.line_drag_draws_one": "Tryck och dra ritar en linje", "prefs.line_drag_draws_one_note": "I verktyget Linje ritar ett tryck, ett drag och ett släpp en linje från där du tryckte till där du släppte, och där slutar den. Klick ritar fortfarande en kedja. Av: ett drag placerar en punkt där det släpps, som ett klick gör.", + "prefs.line_hover_tangent_arc": "Vila på en linjes sista punkt för att växla till en tangentbåge", + "prefs.line_hover_tangent_arc_note": "I verktyget Linje: när ett segment har ritats, flytta pekaren bort från kedjans sista punkt, kom tillbaka och håll pekaren stilla på den: nästa klick avslutar en tangentbåge, och samma gest går tillbaka till linjer. Av: att vila där gör ingenting.", "prefs.linked_designs": "Länkade konstruktioner", "prefs.live_input": "Liveinmatning", "prefs.live_preview": "Liveförhandsvisning", @@ -1908,6 +2270,9 @@ "prefs.max_file_size_step": "STEP- och importfiler", "prefs.max_file_size_web": "Webbappen öppnar STEP- och importfiler upp till 512 MB och konstruktioner upp till 256 MB: en webbläsarflik kan inte rymma större filer. Gränserna kan höjas i skrivbordsappen.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Stora ikoner", + "prefs.menu_list": "Lista", + "prefs.menus": "Menyer", "prefs.minutes": "minuter", "prefs.minutes_suffix": " min", "prefs.mouse": "Mus och styrplatta", @@ -1915,6 +2280,8 @@ "prefs.mouse_mapping": "Musmappning", "prefs.navigation": "Navigering", "prefs.navigation_note": "Hur musen, styrplattan och 3D-musen flyttar vyn.", + "prefs.navigator_fit": "Anpassa modellen efter en vyändring i navigatorn", + "prefs.navigator_fit_note": "En yta, ett hörn eller en pil på vykuben, eller en axel på orienteringsgizmot, tittar också mot modellens mitt från det enda avstånd som får den att rymmas från alla sidor (dess begränsningssfär). Hem använder samma zoom och centrum medan detta är på, så vyer som väljs efteråt bara vrids. Av: vyn vrids på stället och behåller sitt mål och sin zoom.", "prefs.network_host_remove": "Ta bort", "prefs.network_locations": "Tillåt nätverksplatser i konstruktioner", "prefs.network_locations_note": "Av: en konstruktions länkade filer på en annan dator (\\\\server\\share) öppnas bara från de servrar som listas här, eller efter att du tillåtit en när du tillfrågas.", @@ -1927,10 +2294,18 @@ "prefs.origin_plane_names": "Namn på origoplan", "prefs.origin_plane_names_note": "Namn som visas i webbläsaren, dialoger och listor. {top} är XY, {front} är XZ och {right} är YZ, med Z uppåt. Kommandon, skript och sparade konstruktioner behåller XY, XZ och YZ.", "prefs.overall_speed": "Total hastighet", + "prefs.parameter_list_rows": "Rader i parameterlistan", + "prefs.parameter_list_rows_tip": "Nedåtpil i ett tomt värdefält listar parametrarna, favoriter först, upp till så här många. Färre håller listan lätt i en stor konstruktion.", + "prefs.persistent_ribbon_pressed": "Framhäv aktiva kommandon i menyfliksområdet", + "prefs.persistent_ribbon_pressed_help": "Framhäv kommandon i menyfliksområdet medan deras effekter är aktiva. Stäng av för att behålla det tidigare neutrala utseendet och kommandohjälpen.", "prefs.perspective_fov": "Synfält", "prefs.placement": "Placering", "prefs.prefer_free_sketch_points": "Föredra flyttbara skisspunkter när punkter överlappar", "prefs.preview_choices": "Förhandsvisning av dina val", + "prefs.preview_tint_new_faces": "Färglägg ny yta i en förhandsvisning", + "prefs.preview_tint_new_faces_help": "En förhandsvisning av en funktion som ändrar en kropp kan rita den yta den lägger till i förhandsvisningsfärgen. När det är av ritas kroppen som sig själv.", + "prefs.print_face_highlight": "Markering av utskriftsyta", + "prefs.print_face_highlight_tip": "Hur starkt en kropps utskriftsyta färgas och konturmarkeras i vyn. 0 % visar ingen markering.", "prefs.profile_active": "Aktiv profil", "prefs.profile_applied": "Profilen tillämpades.", "prefs.profile_changed": "Inställningarna har ändrats sedan profilen sparades. Spara behåller dem i den.", @@ -1952,9 +2327,13 @@ "prefs.quality_fastest": "snabbast", "prefs.quality_slowest": "långsammast", "prefs.quality_smoother": "jämnare", + "prefs.quick_measure": "Snabbmätning i vyns hörn", + "prefs.quick_measure_note": "Markeringens storlek i vyns nedre högra hörn: en kants längd, eller Ø och R för en rund kant, en ytas area, en punkts läge, avstånd och vinkel mellan två objekt, summan för flera kanter eller ytor. Ett klick kopierar värdet.", "prefs.render_previous_geometry_budget": "Använd tidigare geometribudget för renderingsförhandsvisning", "prefs.render_previous_geometry_budget_help": "Återställ den tidigare fasta geometrigränsen (512 MiB på 64-bitars dator, 128 MiB i övrigt) i stället för den enhetsbaserade budgeten.", "prefs.reports_saved": "{n} sparade", + "prefs.ribbon_click_ends_tool": "Ett klick på knappen för det pågående verktyget avslutar det", + "prefs.ribbon_click_ends_tool_note": "Ett klick på den tända knappen i menyfliksområdet för skissverktyget som används avslutar verktyget, så att klick i vyn markerar igen. Av: klicket startar verktyget igen.", "prefs.ribbon_reveal": "Visa sökresultat i menyfliksområdet", "prefs.ribbon_reveal_note": "När du håller pekaren över ett resultat i Sök kommandon visas var kommandot finns i menyfliksområdet: dess flik, dess knapp eller dess rad i en panels rullgardinsmeny. Ett kommando som startas från sökningen blinkar där, och ett pågående kommando från en rullgardinsmeny markerar sin panel.", "prefs.right_click": "Högerklick", @@ -1965,6 +2344,8 @@ "prefs.search_empty": "Inga matchande inställningar", "prefs.select": "Markera", "prefs.select_one_item": "Markera ett objekt", + "prefs.select_other_hidden": "Markera dold geometri med Markera annan", + "prefs.select_other_hidden_help": "På: ta med dolda kroppar, skisser och skymda kanter nära pekaren. Av: använd den ursprungliga listan över synlig geometri under pekaren.", "prefs.selecting": "Markering", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift lägger bara till; Ctrl / Cmd växlar", @@ -1976,31 +2357,63 @@ "prefs.sketch_align_points_note": "Vid ritning riktas en punkt in vågrätt mot en skisspunkt och lodrätt mot en annan samtidigt, med en prickad hjälplinje, och klicket behåller båda inriktningarna. Av: endast mot föregående punkt, en axel i taget.", "prefs.sketch_conflict_colour": "Motstridig geometri i konfliktfärgen", "prefs.sketch_conflict_colour_note": "Medan villkoren i en skiss står i konflikt ritas de kurvor och punkter som ett misslyckat villkor binder i konfliktfärgen också, inte bara dess symbol eller mått. Av: de behåller sina vanliga färger.", + "prefs.sketch_construction_lines": "Utökade verktyg för konstruktionslinjer", "prefs.sketch_exit_view": "När en skiss avslutas", "prefs.sketch_exit_view.keep": "Behåll den aktuella vyn", "prefs.sketch_exit_view.previous": "Återgå till föregående vy", "prefs.sketch_exit_view.unless_rotated": "Återgå om inte roterad", "prefs.sketch_exit_view_note": "Dit vyn går efter Slutför skiss, Avbryt eller en dubbel Esc-tryckning.", + "prefs.sketch_face_activates_part": "Att skissa på en dels yta gör delen aktiv", + "prefs.sketch_face_activates_part_note": "En skiss som påbörjas på en yta på en annan komponents kropp aktiverar först den komponenten, så att skissen tillhör den och stannar hos den delen i webbläsaren. Delen förblir aktiv efteråt. Av: skissen tillhör den aktiva komponenten.", + "prefs.sketch_open_look_at": "Vrid vyn mot en skiss när den öppnas", + "prefs.sketch_open_look_at_note": "Av: att skapa eller redigera en skiss lämnar vyn som den är. Titta på riktar vyn mot skissen när du vill.", "prefs.sketch_recent_snap": "Snappa automatiskt till senaste centrum och mittpunkter", "prefs.sketch_recent_snap_note": "Vid ritning snappar markören dit där hjälplinjerna från de två senaste cirkelcentrumen eller mittpunkterna på raka kanter korsar varandra. Av: hjälplinjerna visas bara och markören flyttas inte.", "prefs.sketch_selection": "Skiss och markering", "prefs.sketch_selection_heading": "Skiss och markering", "prefs.sketch_selection_note": "Hur skisser snappar och hur klick markerar.", + "prefs.sketch_state_icons": "Skissikoner i färgen för sitt tillstånd", + "prefs.sketch_state_icons_note": "I Historiken och webbläsaren tar skissikonen färgen för skissens tillstånd (underbestämd, fullt definierad eller i konflikt), och dess verktygstips anger tillståndet. Av: alla skisser har samma ikon.", "prefs.sketch_tab_always": "Visa alltid fliken Skiss", "prefs.sketch_tab_always_note": "Fliken Skiss ligger kvar i menyfliksområdet, direkt efter Modell, medan ingen skiss är öppen. Dess ritverktyg startar då en skiss på det markerade planet eller den markerade ytan, eller på det plan du väljer härnäst, med verktyget redo i den.", "prefs.sketch_tracking_guides": "Hjälplinjer för justering mot centrum och mittpunkt", "prefs.sketch_tracking_guides_note": "Håll muspekaren över en cirkels centrum eller en rak kants mittpunkt och flytta sedan vågrätt eller lodrätt för att visa en tillfällig prickad hjälplinje.", + "prefs.sketch_tracking_points": "Hjälplinjer för justering från ändpunkter och hörn under ritning", + "prefs.sketch_tracking_points_note": "När ett ritverktyg väntar på en punkt och du pekar på änden av en linje eller båge, ett rektangelhörn eller en fri punkt visas samma tillfälliga prickade hjälplinje som för ett centrum eller en mittpunkt. Av: bara centrum och mittpunkter.", "prefs.sketching": "Skissning", "prefs.snap_drawing_note": "När du ritar eller drar en skisspunkt.", "prefs.source": "Källa", "prefs.speed": "Hastighet", "prefs.stand_up_note": "Erbjud en kvartsvridning kring X efter att en STEP- eller IGES-fil öppnats med Z uppåt.", + "prefs.stand_up_unknown": "För filer från okända program", + "prefs.stand_up_unknown.ask": "Fråga i en dialog", + "prefs.stand_up_unknown.note": "Visa ett meddelande", + "prefs.stand_up_unknown.off": "Erbjud inte", + "prefs.stand_up_unknown_note": "Hur erbjudandet görs när filens huvud inte anger något program som är känt för att spara med Y uppåt. Ett meddelande visas bara när filen verkar ligga på rygg; Fråga i en dialog frågar om varje sådan fil, som tidigare.", "prefs.status_bar": "Statusfält", "prefs.status_bar_note": "Ett smalt fält längs fönstrets nederkant visar vad som redigeras, den öppna skissens tillstånd i dess färg och konstruktionens enheter; ett klick på enheterna ändrar dem. Skissens tillstånd visas då inte längre i vyns hörn.", "prefs.status_done": "Klar", "prefs.status_error": "Fel", "prefs.status_selected": "Markerad", "prefs.status_warning": "Varning", + "prefs.structure.appearance": "Utseende", + "prefs.structure.appearance_note": "Färger, text och tillgänglighet.", + "prefs.structure.in_profile": "I profilen", + "prefs.structure.layout": "Layout", + "prefs.structure.layout_note": "Var fönstrets delar sitter.", + "prefs.structure.look": "Stil", + "prefs.structure.measure_pointer": "Mätning och pekare", + "prefs.structure.mouse3d": "3D-mus", + "prefs.structure.mouse3d_note": "SpaceMouse och SpaceNavigator.", + "prefs.structure.navigation_note": "Mus och styrplatta. 3D-musen har en egen sida.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Ändrad sedan den sparades", + "prefs.structure.profile_hover": "Sparad i inställningsprofiler", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Skiss", + "prefs.structure.tools": "Verktyg", + "prefs.structure.tools_note": "Hur modelleringsverktygen beter sig.", + "prefs.structure.work": "Arbete", "prefs.supersampling_brief": "Ritar vyn större och filtrerar ned den: mycket skarp, och tyngre.", "prefs.tab_accent_note": "Accentfärgen följer den aktiva fliken", "prefs.theme_file": "temafil", @@ -2012,6 +2425,16 @@ "prefs.theme_follow_off": "Av", "prefs.theme_follow_stop": "Sluta följa", "prefs.theme_import_hint": "Klicka för att välja en temafil, släpp en här eller tryck Ctrl+V (Cmd+V på Mac) med ett tema kopierat", + "prefs.theme_option_opacity": "Opacitet", + "prefs.theme_option_opacity_help": "Justera opaciteten för flytande paneler. En lägstanivå för läsbarhet skyddar text över färgerna i vyfönstret.", + "prefs.theme_option_tab_colours": "Flikfärger", + "prefs.theme_option_tab_colours_help": "Använd det här temats panel- och vyfönsterfärger för varje flik i menyfliksområdet.", + "prefs.theme_option_tab_fade_ms": "Flikövergång", + "prefs.theme_option_tab_fade_ms_help": "Tona över panel- och vyfönsterfärger när du byter flik. Noll byter direkt.", + "prefs.theme_options_badge": "Alternativ", + "prefs.theme_options_more": "Fler · {count}", + "prefs.theme_options_reset": "Återställ", + "prefs.theme_options_unavailable": "Inte tillgängligt på den här enheten", "prefs.theme_paste": "Klistra in tema", "prefs.theme_paste_none": "Urklippet innehåller inget SolidCraft-tema", "prefs.timeline_half_hour": "−30 min", @@ -2033,13 +2456,23 @@ "prefs.under_cursor": "Under markören", "prefs.units_precision": "Enheter och precision", "prefs.updates": "Uppdateringar", + "prefs.value_boxes_in_view": "Visa värden bredvid sina handtag i vyn", + "prefs.value_boxes_in_view_tip": "Ett kommandos värde (Avstånd, Radie…) i en ruta bredvid dess handtag, över modellen. Av: du skriver det i kommandofönstret, som tar över tangentbordet efter ett val, och ingenting täcker modellen.", "prefs.view": "Vybeteende", "prefs.view_confirm_corner": "OK och Avbryt i vyns hörn", "prefs.view_confirm_corner_note": "Medan en dialog eller en skiss är öppen gör en bock och ett kryss uppe till höger i vyn samma sak som dialogens OK och Avbryt, eller slutför och avbryter skissen. Vynavigatorn flyttas ned under dem.", "prefs.viewport": "Vyfönster", + "prefs.viewport_analysis_status": "Visa analysstatus i vyfönstret", + "prefs.viewport_analysis_status_help": "Visa aktiva analyser ovanför vyfönstret, öppna deras teckenförklaringar från varje objekt och använd Esc för att stänga av den senaste analysen. Stäng av för att återställa teckenförklaringar i hörnen och det tidigare Esc-beteendet.", "prefs.viewport_background": "Bakgrund", "prefs.viewport_background_colour": "Färg", "prefs.viewport_background_theme": "Temats gradient", + "prefs.viewport_section_status": "Visa sektionsstatus i vyfönstret", + "prefs.viewport_section_status_help": "Visa sektionsinställningen i vyfönstret. Escape och den aktiva knappen i menyfliksområdet stänger av den. Inaktivera för att behålla de tidigare sektionskontrollerna.", + "prefs.viewport_status_details": "Direkta detaljer i vyfönstret", + "prefs.viewport_status_details_help": "Redigera aktiva analys- och sektionsinställningar i vanliga detaljkort. Inaktivera för att återställa skrivskyddade teckenförklaringar för analys och dialogrutan Sektion.", + "prefs.viewport_status_summary": "Vik ihop statusobjekt i vyfönstret", + "prefs.viewport_status_summary_help": "Vik ihop tre eller fler statusobjekt i vyfönstret till en enda sammanfattningsbricka. Inaktivera för att behålla varje objekt i hela raden.", "prefs.wheel": "Hjul", "prefs.wheel_trackpad": "Hjul och styrplatta", "prefs.workspace": "Arbetsyta", @@ -2049,6 +2482,10 @@ "properties.title": "Egenskaper: {name}", "recovery.days_ago": "för {count} dagar sedan", "recovery.detail": "{file} · {features} funktioner · autosparad {when}", + "recovery.discard_all": "Förkasta alla", + "recovery.discard_all_detail": "Det går inte att ångra.", + "recovery.discard_all_title": "Förkasta {count} autospar?", + "recovery.discard_all_title_one": "Förkasta 1 autospar?", "recovery.hours_ago": "för {count} h sedan", "recovery.just_now": "nyss", "recovery.min_ago": "för {count} min sedan", @@ -2164,6 +2601,10 @@ "render.base_color": "Basfärg · sRGB", "render.base_metallic": "Metallandel", "render.base_opaque_only": "Den här redigeraren bevarar semantiken för ogenomskinliga kroppar. Använd de särskilda glasreglagen för optisk transmission.", + "render.batch_all_shots": "Alla tagningar ({count})", + "render.batch_empty": "Spara en tagning innan alla tagningar renderas.", + "render.batch_limit": "Rendera alla tagningar är begränsat till 32 tagningar.", + "render.batch_status": "{running} pågår · {waiting} väntar", "render.bloom_enable": "Visa bloom", "render.bloom_help": "Kreativ glöd, bara i utdata, från positiva linjära högdagrar och utspridd med tre normaliserade boxpass. Radien anges i utdatapixlar. Läggs till i linjärt visningsljus före sRGB; ingen lins- eller volymeffekt och ingen förbättring av konvergensen. Rå EXR förblir oförändrad.", "render.bloom_opaque": "Bloom kräver ogenomskinlig utdata. Transparent PNG avvisas i stället för att i det tysta plattas ut.", @@ -2274,6 +2715,13 @@ "render.choose_look": "Välj först en stil i Utseenden", "render.chromatic_offset": "Kromatisk kantförskjutning", "render.clear_stage": "Ta bort sparad dekor", + "render.compare_divider": "Jämförelsens avdelare", + "render.compare_live": "Live", + "render.compare_live_preview": "Liveförhandsvisning", + "render.compare_render": "Rendering {number}", + "render.compare_side": "Rendering {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · fångad vid revision {revision}", + "render.compare_swap": "Byt plats", "render.copy_request": "Kopiera JSON", "render.cpu_aa_help": "Rumsliga prov: fler prov förbättrar kanterna och ökar renderingstiden.", "render.cpu_area_add": "Lägg till rektangulärt CPU-ljus", @@ -2914,7 +3362,9 @@ "render.output_ready": "Redo att rendera", "render.output_run_check": "Kör kontroll", "render.output_size_limit": "{method}: upp till {dimension} px per sida och {pixels} pixlar. Största storlek som får plats: {width} × {height}.", + "render.output_size_method_profile": "För att rendera {width} × {height}, välj {method} med CPU-resursprofilen {profile}, eller en mindre storlek.", "render.output_size_ok": "Storleken är OK · {width} × {height} px", + "render.output_size_profile": "För att rendera {width} × {height}, välj CPU-resursprofilen {profile}, eller en mindre storlek.", "render.output_swap_orientation": "Byt bredd och höjd", "render.output_tools_inspector": "Redigera storlek och format i inspektören Utdata.", "render.output_view_image": "Visa bild", @@ -3021,6 +3471,10 @@ "render.result_retained": "Visar den senast färdiga bilden; en nyare rendering har inte ersatt den.", "render.result_sequence": "Kontrollpunkt", "render.result_title": "Renderingsresultat", + "render.results_choose": "Behållna resultat", + "render.results_label": "Rendering {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [inaktuell]", + "render.results_unnamed": "Bild", "render.return_design": "Tillbaka till Konstruktion", "render.review_stale": "Den här granskningen är föråldrad. Åtgärda eller kontrollera igen innan du tillämpar.", "render.ribbon_aging": "Åldring", @@ -3127,6 +3581,7 @@ "render.size_custom": "Egen…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · kräver {profile}", "render.size_presets": "Storleksförinställningar", "render.size_presets_pending": "Kommer med utdataredigeraren", "render.size_preview": "Förhandsvisning", @@ -3414,6 +3869,24 @@ "sheet.flange_type_contour": "Kontur", "sheet.flange_type_edge": "Kant", "sheet.no_body": "det finns ingen plåtkropp: starta en med Fläns > Bas, eller gör om en platta till plåt med Konvertera till plåt (markera dess stora plana yta)", + "sheet.personal_rules.confirm_delete": "Bekräfta borttagning", + "sheet.personal_rules.delete": "Ta bort", + "sheet.personal_rules.delete_prompt": "Ta bort den här personliga regeln? Regler som redan finns i konstruktioner ändras inte.", + "sheet.personal_rules.full": "Det personliga biblioteket innehåller redan 64 regler.", + "sheet.personal_rules.invalid_name": "Ange ett kort namn utan radbrytningar eller styrtecken.", + "sheet.personal_rules.invalid_values": "Fyll i regelns värden: varje värde måste gå att räkna ut i den här konstruktionen, med en positiv tjocklek och en K-faktor från 0 till 1.", + "sheet.personal_rules.missing": "Den valda personliga regeln finns inte längre.", + "sheet.personal_rules.name": "Regelnamn", + "sheet.personal_rules.name_exists": "Det finns redan en personlig regel med det här namnet. Använd ett annat namn.", + "sheet.personal_rules.name_hint": "Ett unikt namn", + "sheet.personal_rules.overwrite": "Spara ändringar i vald personlig regel", + "sheet.personal_rules.rename": "Byt namn", + "sheet.personal_rules.rule": "Personlig regel", + "sheet.personal_rules.save": "Spara som ny", + "sheet.personal_rules.scope": "Sparas i din profil för alla konstruktioner.", + "sheet.personal_rules.select": "Välj en regel", + "sheet.personal_rules.title": "Personliga regler", + "sheet.personal_rules.unsupported": "Den här regeln har värden som den här versionen inte kan använda.", "shortcut.json_error": "parametrar måste vara JSON: {error}", "shortcut.no_command": "inget kommando `{id}`; texten före JSON måste vara ett kommando-id", "shortcut.pin": "Fäst överst i S-rutan", @@ -3450,8 +3923,10 @@ "sketch_text.align_right": "Höger", "sketch_text.bold": "Fet", "sketch_text.builtin_font": "{family} (inbyggd)", + "sketch_text.formula": "Börja med = för att bygga orden av parametrar: ='W' + number(Width)", "sketch_text.italic": "Kursiv", "sketch_text.loading_fonts": "Söker efter installerade teckensnitt…", + "sketch_text.no_bold": "Det inbyggda teckensnittet har ingen fet variant: välj ett installerat teckensnitt", "sketch_text.on_path": "Texten följer sin bana: kurvan placerar den", "sketch_text.path_clear": "Ta bort texten från dess kurva", "sketch_text.path_hint": "En kurva i skissen som texten följer: klicka här och sedan på kurvan", @@ -3483,10 +3958,7 @@ "the two origins are on the same component": "de två origona ligger på samma komponent", "thread.automatic_size": "Automatisk storlek", "thread.designation": "Beteckning", - "thread.direction": "Gängriktning", "thread.iso_metric": "ISO-metrisk", - "thread.left_hand": "Vänstergängad", - "thread.right_hand": "Högergängad", "thread.select_size": "Välj storlek", "timeline.delete_after_marker_one": "Ta bort 1 funktion efter historikmarkören", "timeline.delete_after_marker_other": "Ta bort {count} funktioner efter historikmarkören", @@ -3503,8 +3975,10 @@ "timeline.move_to_group": "Flytta funktioner till mapp", "timeline.rename_group": "Byt namn på funktionsmapp", "timeline.reorder_many": "Ändra funktionsordning", + "timeline.suppress_features": "Undertryck funktioner", "timeline.suppress_folders_tip": "Undertryck eller häv undertryckning av alla funktioner i mapparna och deras kapslade mappar", "timeline.ungroup": "Ta bort funktionsmappar", + "timeline.unsuppress_features": "Häv undertryckning av funktioner", "to the face": "till ytan", "to the next face": "till nästa yta", "toolbar.customize_note": "Fliken {tab}. Bocka för ett kommando för att ge det en verktygsfältsknapp. Du kan också dra en rad i en panels rullgardinsmeny till verktygsfältet, dra en knapp från verktygsfältet för att ta bort den, eller använda nålen på en rad i rullgardinsmenyn.", @@ -3588,6 +4062,8 @@ "ui.3d_mouse_section": "3D-mus", "ui.3d_mouse_show_in_view": "Visa 3D-musen i 3D-vyn", "ui.3d_mouse_show_in_view_tip": "En bild av din 3D-mus i nedre vänstra hörnet som rör sig när du rör den.", + "ui.3d_mouse_sketch_orbit": "Vrid skisser med 3D-musen", + "ui.3d_mouse_sketch_orbit_tip": "3D-musen vrider också vyn medan en skiss är öppen och ses rakt framifrån, så som musen kan. Av: den panorerar och zoomar skissen tills du lutar vyn.", "ui.3d_mouse_skip": "Min enhet kan inte göra det här", "ui.3d_mouse_skip_tip": "Hoppar över den här rörelsen i båda riktningarna, och kalibreringen utelämnar den.", "ui.3d_mouse_speed": "3D-musens hastighet", @@ -3616,6 +4092,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Vrid knappen moturs, håll den och släpp sedan.", "ui.3d_mouse_switch_cap": "Kalibrera som återgång till centrum", "ui.3d_mouse_switch_trackball": "Kalibrera som styrkula", + "ui.3d_mouse_use_direct": "Använd direkt drivrutin", + "ui.3d_mouse_use_direct_tip": "Läs 3D-musen direkt (hidraw) i stället för via spacenavd.", "ui.3d_mouse_view_axis": "Vyaxel", "ui.3d_mouse_view_off": "Av", "ui.3d_mouse_view_off_tip": "3D-musdrivrutinens profil stänger av den här axeln, så dess rörelse flyttar inte vyn. Om du väljer en annan axels rörelse här byter de två plats, och den rörelsen slutar flytta vyn.", @@ -3654,6 +4132,8 @@ "ui.agent_chat_auth_terminal": "Kör detta i en terminal och tryck sedan på Anslut igen:", "ui.agent_chat_auth_title": "Logga in hos agenten", "ui.agent_chat_cancel": "Avbryt", + "ui.agent_chat_cancel_timeout": "Agenten svarade inte på Stoppa och kopplades bort. Anslut igen för att fortsätta.", + "ui.agent_chat_cannot_start": "Installerad, men den startar inte: {error}", "ui.agent_chat_changes": "Ändringar: {n}, ett ångrasteg", "ui.agent_chat_changes_n": "{n} ändringar", "ui.agent_chat_changes_of": "{n}/{limit} ändringar", @@ -3662,11 +4142,13 @@ "ui.agent_chat_command": "Agentkommando", "ui.agent_chat_connect": "Anslut", "ui.agent_chat_copy": "Kopiera", + "ui.agent_chat_copy_message": "Kopiera meddelande", "ui.agent_chat_ctx_bodies": "Kroppar", "ui.agent_chat_ctx_elements": "Element", "ui.agent_chat_ctx_features": "Funktioner", "ui.agent_chat_ctx_more": "+{n} till", "ui.agent_chat_ctx_other": "Övrigt", + "ui.agent_chat_custom_heading": "Egen modell", "ui.agent_chat_custom_hint": "Valfritt program som talar Agent Client Protocol via stdin och stdout. Inget skal kör det.", "ui.agent_chat_denied": "Nekad", "ui.agent_chat_deny": "Neka", @@ -3710,8 +4192,16 @@ "ui.agent_chat_mode_all": "Allt", "ui.agent_chat_mode_ask": "Fråga", "ui.agent_chat_mode_edits": "Ändringar", + "ui.agent_chat_model_custom": "Använd egen modell: {model}", "ui.agent_chat_model_no_tools": "{model} kan inte använda SolidCrafts verktyg, så den kan bara chatta. Välj en modell med stöd för verktyg.", + "ui.agent_chat_model_rejected": "Agenten godtog inte {model}: {error}", + "ui.agent_chat_model_search": "Sök modeller…", "ui.agent_chat_model_tip": "Modellen som agenten använder. Ditt val kommer ihåg för den här agenten.", + "ui.agent_chat_models_failed": "Det gick inte att lista modellerna: {error}", + "ui.agent_chat_models_heading": "Tillgängliga modeller", + "ui.agent_chat_models_listing": "Listar modeller…", + "ui.agent_chat_models_none": "Slutpunkten listar inga modeller", + "ui.agent_chat_models_not_a_list": "Svaret var ingen modelllista", "ui.agent_chat_new": "Ny chatt", "ui.agent_chat_new_confirm": "Starta en ny chatt? Den nuvarande rensas.", "ui.agent_chat_next_picture": "Nästa bild", @@ -3746,9 +4236,12 @@ "ui.agent_chat_queued_stopped": "Köad (stoppad, ej skickad)", "ui.agent_chat_refresh": "Uppdatera", "ui.agent_chat_refused": "Inte tillåtet för agenten: {reason}", + "ui.agent_chat_reinstall": "{agent} är installerad ({program}), men startade inte när SolidCraft kontrollerade den: {error}\nInstallationen kan vara ofullständig, eller gjord för en annan typ av dator. Installera den igen med `{install}`, kontrollera att den skriver ut sin version i en terminal och tryck sedan på Uppdatera.", "ui.agent_chat_remove": "Ta bort från kön", "ui.agent_chat_remove_file": "Ta bort det från det här meddelandet", "ui.agent_chat_remove_imported": "Ta bort det från det här meddelandet; delen finns kvar i konstruktionen (Ångra tar bort den)", + "ui.agent_chat_reply_cut_off": "Svaret nådde sin längdgräns innan det var klart och kan därför vara ofullständigt. Be agenten fortsätta, eller be om ett kortare svar.", + "ui.agent_chat_reply_declined": "Modellen avböjde att svara på det här meddelandet.", "ui.agent_chat_retry": "Försök igen", "ui.agent_chat_right": "Höger", "ui.agent_chat_save": "Spara", @@ -3807,12 +4300,17 @@ "ui.ai_copy_suffix": "kopia", "ui.ai_custom_url": "Egen URL", "ui.ai_default": "Standard", + "ui.ai_edit": "Redigera", + "ui.ai_edit_agent_title": "Redigera agent", + "ui.ai_edit_gone": "Den här agenten togs bort, så det finns inget att spara.", + "ui.ai_edit_tip": "Ändra den här agentens namn, kommando eller slutpunkt. En sparad nyckel förblir dold.", "ui.ai_http_busy": "slutpunkten är upptagen eller över sin gräns; försök igen senare", "ui.ai_http_key": "slutpunkten nekade nyckeln: kontrollera den under Inställningar > AI", "ui.ai_http_not_found": "ingen sådan slutpunkt eller modell: kontrollera bas-URL:en och modellnamnet", "ui.ai_http_too_large": "konversationen är för stor för den här slutpunkten; starta en ny chatt", "ui.ai_key": "API-nyckel", "ui.ai_key_hint": "valfritt; lagras i systemets nyckelring", + "ui.ai_key_keep_hint": "lämna tomt för att behålla den sparade nyckeln", "ui.ai_key_needs_https": "En nyckel skickas endast via HTTPS, eller till den här datorn.", "ui.ai_key_note": "Lagras i systemets nyckelring, aldrig i SolidCrafts inställningar. Lämna tomt för en lokal server.", "ui.ai_keychain_error": "Systemets nyckelring nekade: {error}", @@ -3839,11 +4337,15 @@ "ui.ai_permissions": "Behörigheter", "ui.ai_preset": "Förinställning", "ui.ai_protocol": "Protokoll", + "ui.ai_reasoning_effort": "Resonemangsnivå", + "ui.ai_reasoning_effort_field_hint": "tomt = leverantörens standard", + "ui.ai_reasoning_effort_hint": "Valfritt. Skickas till slutpunkten som `reasoning_effort`; vilka värden som accepteras skiljer sig mellan leverantörer (till exempel `low`, `high` eller `max`). Ett värde som du anger här ersätts aldrig av SolidCraft. Lämna fältet tomt för att inte skicka något och behålla leverantörens standard.", "ui.ai_remove": "Ta bort", "ui.ai_request_timed_out": "Modellen tog längre tid än {seconds} s. Du kan öka tidsgränsen för begäran för den här slutpunkten i Inställningar › Assistent.", "ui.ai_request_timeout": "Tidsgräns för begäran", "ui.ai_request_timeout_hint": "Hur lång tid en modellbegäran till den här slutpunkten får ta, från 30 s till en timme. Öka den för en långsam lokal modell.", "ui.ai_reset": "Återställ", + "ui.ai_save": "Spara", "ui.ai_settings": "AI-inställningar…", "ui.ai_show_features": "Visa AI-funktioner", "ui.ai_show_features_note": "Agentchatten: en panel där en kodningsagent du redan använder, eller en modellslutpunkt du väljer, arbetar med den öppna konstruktionen. Av: ingen AI-knapp, genväg, menypost eller panel, och inget söks eller startas.", @@ -3922,6 +4424,8 @@ "ui.cancel": "Avbryt", "ui.canvases": "Dukar", "ui.center": "Centrum", + "ui.center_arc_follows_cursor": "Båge med centrumpunkt följer markörens riktning", + "ui.center_arc_follows_cursor_tip": "En båge med centrumpunkt går medurs eller moturs beroende på hur markören rör sig runt dess centrum. Av: alltid moturs från start.", "ui.centerline": "Centrumlinje", "ui.chain": "Kedja", "ui.chamfer": "Fasning", @@ -3930,6 +4434,7 @@ "ui.circle": "Cirkel", "ui.circular_pattern": "Cirkulärt mönster", "ui.clear": "Rensa", + "ui.clear_print_face": "Rensa utskriftsyta", "ui.clear_recent": "Rensa senaste", "ui.clear_the_selection": "Rensa markeringen", "ui.click_selects_whole_bodies": "Klick markerar hela kroppar", @@ -3964,12 +4469,27 @@ "ui.constant": "Konstant", "ui.constraints_conflict": "Villkor i konflikt", "ui.construction": "Konstruktion", + "ui.construction.angle_hint": "Konstruktionslinje: klicka på en punkt och skriv sedan en vinkel eller välj en riktning", + "ui.construction.bisector_hint": "Vinkelbisektris: välj två skärande raka linjer och sedan önskad lösning", + "ui.construction.common_hint": "Gemensam tangent: välj två cirklar/bågar och sedan önskad lösning", + "ui.construction.contact_hint": "Tangent: välj en cirkel/båge eller öppen spline/konisk kurva och sedan beröringspunkten (friformskurvor: ändpunkter)", + "ui.construction.external_hint": "Tangent: välj en cirkel eller båge, en yttre punkt och sedan önskad lösning", + "ui.construction.free_hint": "Konstruktionslinje: klicka på två punkter; högerklicka för att börja om", + "ui.construction.normal_needs_length": "En oändlig linje är alltid en konstruktionslinje: skriv en längd för att rita en normal linje", + "ui.construction.point_hint": "Konstruktionslinje: klicka på punkten som linjen ska gå genom", + "ui.construction.reference_hint": "Konstruktionslinje: välj en rak linje och sedan en punkt; högerklicka för att byta referens", "ui.construction.ribbon_label": "Hjälplinjer", + "ui.construction.side_hint": "Konstruktionslinje: klicka på den sida som linjen går mot; högerklicka för att börja om", "ui.context_menu": "Snabbmeny", + "ui.continuity_crease": "Veck", + "ui.continuity_curvature": "Krökning", + "ui.continuity_curvature_change": "Krökningsändring", "ui.continuity_g0": "G0-veck", "ui.continuity_g1": "G1-tangent", "ui.continuity_g2": "G2-krökning", "ui.continuity_gap": "Spalt", + "ui.continuity_position": "Läge", + "ui.continuity_tangent": "Tangent", "ui.copy": "Kopiera", "ui.corner": "Hörn", "ui.corners": "Hörn", @@ -3992,6 +4512,7 @@ "ui.dark": "Mörkt", "ui.default_modelling_orientation": "Standardorientering för modellering", "ui.delete": "Ta bort", + "ui.delete_select_first": "Markera först vad som ska tas bort: funktioner, kroppar, komponenter eller skissgeometri", "ui.depth": "Djup", "ui.design": "Konstruktion", "ui.design_properties.author": "Upphovsperson", @@ -4006,6 +4527,40 @@ "ui.design_properties.project": "Projekt", "ui.design_properties.revision": "Revision", "ui.design_saved": "Sparad i {path}", + "ui.details_access_caption": "Ytorna visar om ett verktyg kan nå dem från den valda riktningen.", + "ui.details_angle": "Vinkel", + "ui.details_continuity_caption": "Redigera den markerade skarven. Andra skarvar behåller sina egna inställningar.", + "ui.details_continuity_stale": "Tidigare geometri: kör analysen igen för att redigera eller rama in den här skarven.", + "ui.details_copy_list": "Kopiera lista", + "ui.details_curvature": "Krökningstolerans", + "ui.details_curvature_caption": "Ytorna färgas efter sin lokala krökningsradie.", + "ui.details_direction": "Verktygsriktning", + "ui.details_draft_caption": "Ytorna färgas efter sin vinkel mot dragriktningen.", + "ui.details_edit_seam": "Redigera skarv", + "ui.details_fixture": "Komponentexemplar — endast exempeldata", + "ui.details_fixture_caption": "Komponentexemplar med illustrativa värden; det här är inte ett modellresultat.", + "ui.details_fixture_problem": "Exempelresultat med ett problem", + "ui.details_fixture_readout": "Exempel på mätvärde", + "ui.details_flip": "Vänd", + "ui.details_gap": "Spalt", + "ui.details_hatch": "Skraffera snittytor", + "ui.details_jump": "Krökningshopp", + "ui.details_key": "Teckenförklaring", + "ui.details_offset": "Förskjutning", + "ui.details_plane": "Plan", + "ui.details_pull": "Dragriktning", + "ui.details_radius": "Radie", + "ui.details_readout": "Avläsning", + "ui.details_samples": "Provpunkter", + "ui.details_seam": "{body} · Kant {edge}", + "ui.details_settings": "Inställningar", + "ui.details_sharp_gap": "Skarp eller spalt", + "ui.details_show_all": "Visa alla {count}", + "ui.details_smooth": "Jämn", + "ui.details_stripes": "Ränder", + "ui.details_target": "Rama in geometrin", + "ui.details_worst_seams": "Sämsta skarvarna", + "ui.details_zebra_caption": "Speglade ränder visar hur jämnt ytorna möts.", "ui.diameter": "Diameter", "ui.dimension": "Mått", "ui.direct_interaction": "Direktinteraktion", @@ -4050,6 +4605,7 @@ "ui.edit_in_place_saved_elsewhere": "Delen sparades i en annan fil; sammanställningen länkar fortfarande till {name}", "ui.edit_in_place_wait": "Vänta tills det som körs i konstruktionen är klart", "ui.edit_section_analysis": "Redigera sektionsanalys", + "ui.edit_sketch_empty": "Inga skisser att redigera", "ui.ellipse": "Ellips", "ui.emboss_wrap_note": "Ortogonala linjeprofiler som tangerar en stödd cylinder lindas automatiskt runt den. Välj en vägg för att välja ett mål.", "ui.end_radius": "Slutradie", @@ -4060,12 +4616,15 @@ "ui.equation_explicit": "Explicit", "ui.equation_form": "Form", "ui.equation_note": "Variabeln är ett vanligt tal: sin(t) tolkar den i radianer. Ett resultat utan enhet anges i konstruktionens enhet.", + "ui.equation_note_range": "Variabeln är en längd, liksom dess intervall: blanda den med längdparametrar och dividera den med en längd för sin(). Ett resultat utan enhet anges i konstruktionens enhet.", "ui.equation_parametric": "Parametrisk", + "ui.equation_variable_unit": "Variabeln har intervallets enhet", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Ekvivalent radie", "ui.expand": "Expandera", + "ui.explode_needs_two_components": "Sprängvy drar isär komponenter, så konstruktionen behöver två eller fler (Ny komponent, Infoga konstruktion eller Skapa komponenter från kroppar)", "ui.exportDxf": "Exportera DXF…", "ui.export_ellipsis_keymap": "Exportera…", "ui.export_keymap_tip": "Tangenter, S-rutans favoriter och verktygsfältet, som en fil", @@ -4191,6 +4750,7 @@ "ui.hideOrigin": "Dölj origo", "ui.hidePlanes": "Dölj plan", "ui.hideProfile": "Dölj profil", + "ui.hide_component_history": "Dölj dess historik", "ui.hide_origin_by_default": "Dölj origo som standard", "ui.hide_origin_note": "Nya konstruktioner startar med mappen Origo dold. En konstruktion behåller sin egen Origo-inställning när du har visat eller dolt den.", "ui.history_back": "Gå ett steg bakåt", @@ -4198,6 +4758,7 @@ "ui.history_edge_hint": "dubbelklicka på kanten", "ui.history_first": "Gå till början", "ui.history_forward": "Gå ett steg framåt", + "ui.history_hide_hidden": "Dölj dolda komponenter", "ui.history_hide_names": "Dölj namn", "ui.history_last": "Gå till slutet", "ui.history_marker_tip": "Historikmarkör: dra för att rulla tillbaka modellen; nya funktioner hamnar här", @@ -4207,10 +4768,12 @@ "ui.history_play_button_show": "Visa uppspelningsknappen", "ui.history_play_finish_action": "Slutför den pågående åtgärden innan du spelar upp historiken", "ui.history_play_roll_back": "Flytta historikmarkören bakåt innan uppspelning", + "ui.history_show_hidden": "Visa dolda komponenter", "ui.history_show_names": "Visa namn", "ui.history_sketch_listed_under": "Listad under {feature}", "ui.history_title": "Historik", "ui.history_toggle_names": "Visa eller dölj funktionsnamn", + "ui.history_waits_for_editor": "Ångra, Gör om och Historik väntar tills funktionsredigeraren har öppnats", "ui.hole": "Hål", "ui.hole_tap_type": "Typ av gängning för hål", "ui.hole_type": "Hålets typ", @@ -4226,6 +4789,7 @@ "ui.insert_design.saved_file": "{name} har osparade ändringar, så dess sparade fil infogades. Spara den och kör sedan Uppdatera länkar för att hämta in ändringarna.", "ui.insert_design.unsaved": "Osparade ändringar", "ui.inspect": "Granska", + "ui.instances": "Instanser", "ui.intersect": "Skärning", "ui.isolate": "Isolera", "ui.join": "Sammanfoga", @@ -4234,12 +4798,14 @@ "ui.joints": "Leder", "ui.keyboard_shortcuts": "Kortkommandon", "ui.language": "Språk", + "ui.lasso_select": "Lasso (dra en frihandsslinga: markerar allt som ligger helt innanför)", "ui.layout_compact": "Kompakt", "ui.layout_floating": "Flytande", "ui.length": "Längd", "ui.length_decimals": "Längddecimaler", "ui.light": "Ljust", "ui.line": "Linje", + "ui.line_arc_hint": "Tangentbåge: klicka på bågens slut. Vila på den sista punkten igen för linjer; högerklicka eller Esc för att avsluta", "ui.link_copies": "Länka identiska kopior", "ui.link_copies_keep": "Behåll", "ui.link_copies_link": "Länka", @@ -4328,6 +4894,7 @@ "ui.part_size_shared": "Återbygger delen och ersätter eventuella tillagda funktioner. Alla förekomster av denna komponent uppdateras.", "ui.paste": "Klistra in", "ui.path": "Bana", + "ui.pattern_object_type_tip": "Kroppar: solida former som väljs i vyn eller webbläsaren; var och en kopieras hel.\nFunktioner: steg i historiken, till exempel en extrudering eller ett hål, som väljs i historiken eller på en yta som de har skapat; steget upprepas.\nEn skiss är ingetdera: upprepa dess kurvor med skissens egna Mönster eller Spegla, eller extrudera den först.", "ui.pattern_on_path": "Mönster på bana", "ui.perforate_margin_default": "från diametern", "ui.perforate_pitch": "Stigning", @@ -4354,12 +4921,17 @@ "ui.plugins_skipped": "{count} mapp(ar) kunde inte läsas.", "ui.plugins_version": "{version}", "ui.point": "Punkt", + "ui.point_cloud_add_filter": "Lägg till filter…", "ui.point_cloud_auto_range": "Automatiskt intervall", "ui.point_cloud_color_by": "Färglägg efter", "ui.point_cloud_file_colors": "Filens färger", + "ui.point_cloud_filter_by": "Filtrera efter", "ui.point_cloud_height_high": "Högst", "ui.point_cloud_height_low": "Lägst", + "ui.point_cloud_legend_filter": "Visas och döljs i teckenförklaringen ovan", "ui.point_cloud_no_file_colors": "Filen har inga färger", + "ui.point_cloud_pause": "Pausa", + "ui.point_cloud_play": "Spela upp", "ui.point_cloud_single_color": "En färg", "ui.point_cloud_size": "Punktstorlek", "ui.point_cloud_units": "Filens enheter", @@ -4368,6 +4940,11 @@ "ui.polygon": "Polygon", "ui.preferences": "Inställningar", "ui.press_a_key": "tryck på en tangent…", + "ui.print_face_body_not_sent": "Den ytans kropp skickas inte: lägg först till den i Kroppar", + "ui.print_face_cleared": "{body}: utskriftsyta rensad", + "ui.print_face_input": "Utskriftsyta", + "ui.print_face_pick": "Välj en plan yta på en solid kropp för att göra den till utskriftsytan", + "ui.print_face_set": "{body}: utskriftsyta angiven; Skicka till slicer lägger kroppen på den", "ui.profile": "Profil", "ui.profile_plane": "Profilplan", "ui.profiles": "Profiler", @@ -4383,6 +4960,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Mäter…", + "ui.properties.measuring_bodies": "Mäter… {done} av {total} kroppar", "ui.properties.measuring_failed": "Mätningen avbröts innan den var klar.", "ui.properties.principal_axis": "Huvudaxel {number}", "ui.properties.principal_moments": "Huvudtröghetsmoment", @@ -4431,6 +5009,7 @@ "ui.revolve": "Rotation", "ui.ribbon_exit": "Avsluta", "ui.ribbon_labels": "Visa text under menyfliksikoner", + "ui.ribbon_menus_skip_pinned": "Utelämna fästa kommandon från rullgardinsmenyerna", "ui.ribbon_pin_footer": "Fästa kommandon visas i menyfliken. Håll muspekaren över en rad för att fästa eller lossa den.", "ui.ribbon_workspace": "Arbetsyta", "ui.right": "Höger", @@ -4449,6 +5028,7 @@ "ui.selectOther": "Markera annan…", "ui.selectTangentChain": "Markera tangentkedja", "ui.select_all": "Markera alla", + "ui.select_components_by_face": "Markera komponenter (en yta väljer sin komponent)", "ui.selection": "Markering", "ui.selection_modifiers": "Markeringsmodifierare", "ui.selection_shift_add_only": "Shift+klick lägger till utan att ta bort", @@ -4474,6 +5054,7 @@ "ui.showDimension": "Visa mått", "ui.showOrigin": "Visa origo", "ui.showPlanes": "Visa plan", + "ui.show_component_history": "Visa dess historik", "ui.show_constraints": "Villkor", "ui.show_construction_geometries": "Konstruktionsgeometrier", "ui.show_dimensions": "Mått", @@ -4490,6 +5071,11 @@ "ui.sketch_intersect_selection_filter": "Markeringsfilter", "ui.sketch_modifiers": "Skissmodifierare", "ui.sketch_project_geometry": "Geometri", + "ui.sketch_report.all_constrained": "Allt är fullt definierat.", + "ui.sketch_report.dof": "Frihetsgrader", + "ui.sketch_report.loose": "Inte fullt definierade", + "ui.sketch_report.status": "Status", + "ui.sketch_report.title": "Skissrapport", "ui.sketch_scale": "Skissskala", "ui.sketches": "Skisser", "ui.slice": "Skiva", @@ -4585,19 +5171,31 @@ "ui.view_angles": "Vyvinklar", "ui.view_angles_convention": "Grader runt uppaxeln. Girning 0° är vyn framifrån, 90° från vänster, −90° från höger, 180° bakifrån; lutning 90° är vyn ovanifrån; en positiv rullning vrider modellen medurs.", "ui.view_angles_help": "Visar vyns lutning, girning och rullning i grader samt dess projektion under orienteringsgizmot. Klicka på avläsningen för att skriva in exakta vinklar.", + "ui.view_angles_lock": "Lås {axis}", "ui.view_angles_ortho": "Ortog.", "ui.view_angles_persp": "Persp.", "ui.view_angles_pitch": "Lutning", "ui.view_angles_readout": "Lutning {pitch} · Girning {yaw} · Rullning {roll}", "ui.view_angles_roll": "Rullning", + "ui.view_angles_unlock": "Lås upp {axis}", "ui.view_angles_yaw": "Girning", + "ui.view_angles_zero": "Sätt {axis} till 0°", "ui.view_centre": "Vycentrum", "ui.viewport_status_clear": "Stäng av {name}", "ui.viewport_status_clear_hint": "Stäng av {name} · Esc", + "ui.viewport_status_edges": "{count} kanter", + "ui.viewport_status_from": "från {direction}", "ui.viewport_status_key": "Visa teckenförklaring för {name}", "ui.viewport_status_minimum_radius": "Minsta radie", "ui.viewport_status_pairs": "{count} par", + "ui.viewport_status_section_hatch": "{setting} · skraffering", + "ui.viewport_status_section_plane": "Aktuellt plan", + "ui.viewport_status_section_tilted": "lutad · {offset}", "ui.viewport_status_stripes": "{count} ränder", + "ui.viewport_status_summary_clear": "Stäng av allt", + "ui.viewport_status_summary_heading": "I den här vyn", + "ui.viewport_status_summary_label": "{name} och {count} objekt till", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Följ tema", "ui.visual_shaded_hidden_edges": "Skuggad med dolda kanter", "ui.visual_shaded_with_edges": "Skuggad med kanter", @@ -4634,10 +5232,12 @@ "update.button": "Uppdatera", "update.button_version": "Uppdatera till {version}", "update.check_automatically": "Sök efter uppdateringar automatiskt", + "update.check_for_updates": "Sök efter uppdateringar", "update.check_now": "Sök nu", + "update.check_unavailable": "Sökning efter uppdateringar är inte tillgänglig för den här installationen.", "update.checking": "Söker…", "update.copy": "Kopiera", - "update.dmg_opened": "Diskavbilden är öppen och verifierad: dra SolidCraft till Program och ersätt den gamla kopian, starta sedan om SolidCraft.", + "update.dmg_opened": "Diskavbilden är öppen och verifierad: avsluta SolidCraft, dra det nya SolidCraft till Program och ersätt den gamla kopian, öppna sedan SolidCraft igen.", "update.download": "Ladda ned", "update.download_open": "Ladda ned och öppna", "update.downloading": "Laddar ned och verifierar… {done} av {total} MB", @@ -4648,11 +5248,13 @@ "update.installed": "SolidCraft {version} är installerad. Starta om för att använda den.", "update.installer_started": "Installationsprogrammet startar när SolidCraft stängs.", "update.later": "Påminn mig senare", + "update.managed": "Uppdatering tillgänglig: uppdatera SolidCraft i {manager}", "update.no_notes": "Den här utgåvan har inga anteckningar.", "update.package_hint": "Den här kopian kom från ett {kind}. Ladda ned det nya paketet och installera det sedan med:", "update.prefs_dev": "Detta är ett utvecklingsbygge ({version}): det söker inte efter uppdateringar.", "update.prefs_flatpak": "Flatpak uppdaterar den här kopian ({version}): kör {command} eller använd din programhanterare. SolidCraft söker inte själv.", "update.prefs_label": "Uppdateringar", + "update.prefs_managed": "Detta är SolidCraft {version}, hanterat av {manager}. En sökning frågar GitHub efter den senaste utgåvan och skickar inget annat; uppdatera SolidCraft i {manager}.", "update.prefs_note": "Detta är SolidCraft {version} ({kind}). En sökning frågar GitHub efter den senaste utgåvan och skickar inget annat.", "update.prefs_web": "Läs in sidan igen för att få den senaste webbappen. Om nätverket inte är tillgängligt eller om uppdateringen inte hinner laddas ned i tid öppnas den sparade versionen i stället; en nedladdning som pågår fortsätter till nästa omläsning.", "update.refresh_checking": "Söker efter den senaste utgåvan…", @@ -4679,6 +5281,7 @@ "web.open_link": "Öppna länkad konstruktion?", "web.open_link_confirm": "Det finns osparade ändringar. Öppna den länkade konstruktionen i en ny flik?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ välj · Enter / Tab komplettera · Esc stäng", + "↑ ↓ choose · Enter applies this value": "↑ ↓ välj · Enter tillämpar det här värdet", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ välj · Enter tillämpar det du skrev · Esc stäng", "⌘Enter continues on GitHub.": "⌘Enter fortsätter på GitHub." } diff --git a/assets/locales/tr.json b/assets/locales/tr.json index a51d4adea..c1b1d4302 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "GEÇİŞ YÜZEYİ", "BOUNDARY SURFACE": "SINIR YÜZEYİ", "BROWSER": "TARAYICI", + "Back to the original order": "Orijinal sıraya dön", "Ball": "Küresel", "Bar": "Çubuk", "Base Center": "Taban Merkezi", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "Açtığınız veya kaydettiğiniz tasarımlar burada görünür.", "Determined by To Object. Choose Angle to edit the angular extent.": "Nesneye kadar seçeneğiyle belirlenir. Açısal kapsamı düzenlemek için Açı seçeneğini seçin.", "Diameter": "Çap", + "Did this assembly open the wrong way up?": "Bu montaj yanlış yönde mi açıldı?", + "Did this part open the wrong way up?": "Bu parça yanlış yönde mi açıldı?", "Dimension new shapes": "Yeni şekillere ölçü ver", "Direction": "Yön", "Discard": "At", @@ -474,6 +477,7 @@ "Rectangular": "Dikdörtgen", "Rectangular Tube": "Dikdörtgen boru", "Reference face": "Referans yüzü", + "Reference plane": "Referans düzlem", "Relief Depth": "Boşaltma derinliği", "Relief Width": "Boşaltma genişliği", "Remove Tools": "Araçları kaldır", @@ -553,6 +557,7 @@ "Section": "Kesit", "Section (optional)": "Kesit (isteğe bağlı)", "Section position": "Kesit konumu", + "Sections": "Kesitler", "Sections (one sketch each)": "Kesitler (her biri bir eskiz)", "Select Other": "Başka Seç", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Diğerini seç: İmlecin altındaki her şeyi listelemek için sol tuşu model üzerinde hareket ettirmeden basılı tutun (veya sağ tık › Diğerini seç…); oradaki bir sonraki öğeyi seçmek için aynı noktaya tekrar tıklayın. Başlangıç görünümüne dönmek için orta tuşla çift tıklayın (Ayarlar › Gezinme).", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "Yüz ve kenar merkezlerine yapış", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft raporları doğrudan gönderemez. GitHub'da gönderin; uygulamada belirteç gerekmez.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft bu tasarımlar kaydedilmeden önce kapandı. Son otomatik kayıtları açılabilir.", + "Sort A to Z": "A'dan Z'ye sırala", + "Sort Z to A": "Z'den A'ya sırala", "Spacing 2 must be a non-zero number": "Aralık 2 sıfırdan farklı bir sayı olmalıdır", "Spacing must be a non-zero number": "Aralık sıfırdan farklı bir sayı olmalıdır", "Specialise": "Özelleştir", @@ -601,6 +608,7 @@ "Square": "Kare", "Stand it up": "Dik çevir", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Dik çevir: X etrafında çeyrek tur; geri alınabilen tek bir Taşı özelliği olarak eklenir.", + "Stand this assembly up?": "Bu montaj dik çevrilsin mi?", "Stand this part up?": "Bu parça dik çevrilsin mi?", "Start angle": "Başlangıç açısı", "Start bulge": "Başlangıç şişkinliği", @@ -772,6 +780,8 @@ "at the face": "yüzde", "bom.group_children": "Alt parçalar kendi parçalarının satırında", "browser.body_name": "Gövde {number}", + "browser.calibrate_click_a": "A Noktası için görüntüye tıklayın veya koordinatlarını yazın.", + "browser.calibrate_click_b": "B Noktası için görüntüye tıklayın veya koordinatlarını yazın.", "browser.calibrate_title": "Kalibre et: {name}", "browser.capture_many": "{count} bileşen taşındı ancak konumları yakalanmadı.", "browser.capture_note": "Konumu yakala yeni konumu korur; Konumu geri al önceki konuma döndürür.", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (bağlama kayboldu)", "browser.sketch_editing": "{name} (düzenleniyor)", "browser.sketch_name": "Eskiz {number}", + "browser.sketches_to_parts_already_in_part": "zaten kendi parçalarında", + "browser.sketches_to_parts_design_body": "tasarımın kendi bir gövdesinde", + "browser.sketches_to_parts_moved": "{moved} eskiz, üzerinde oldukları parçaya taşındı", + "browser.sketches_to_parts_no_exact_attachment": "tam bağlaması olmayan bir yüzde", + "browser.sketches_to_parts_not_on_face": "bir parçanın yüzünde değil", + "browser.sketches_to_parts_part_missing": "parçaları artık yok", + "browser.sketches_to_parts_result": "{moved} eskiz, üzerinde oldukları parçaya taşındı; {stayed} yerinde kaldı: {why}", "browser.units": "Birimler: {units}", "cam.flat": "Düz yüz", "cam.follower": "İzleyici", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "Görünümü Al", "cmd.appearance_replace": "Görünümü Değiştir", "cmd.assembly_bom": "Malzeme listesi", + "cmd.assembly_mass_properties": "Kütle özellikleri", + "cmd.body.print_face": "Baskı yüzeyi", "cmd.body_rename": "Gövdeyi yeniden adlandır", "cmd.browser_collapse_all": "Tümünü Daralt", "cmd.browser_expand_all": "Tümünü Genişlet", @@ -842,6 +861,7 @@ "cmd.component_extract": "Dosyaya Çıkar", "cmd.component_finish_edit": "Düzenlemeyi bitir", "cmd.component_from_bodies": "Gövdelerden bileşen oluştur", + "cmd.component_hide_history": "Bileşen geçmişini gizle", "cmd.component_insert_design": "Tasarım ekle", "cmd.component_links": "Bağları listele", "cmd.component_list": "Bileşenleri listele", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "Gövdeleri bileşene taşı", "cmd.component_move_features": "Özellikleri bileşene taşı", "cmd.component_move_sketches": "Eskizleri bileşene taşı", + "cmd.component_move_sketches_to_parts": "Eskizleri kendi parçalarına taşı", "cmd.component_paste_from_design": "Başka Bir Tasarımdan Yapıştır", "cmd.component_paste_new": "Yeni olarak yapıştır", "cmd.component_properties": "Bileşenin fiziksel özellikleri", @@ -857,6 +878,7 @@ "cmd.component_rename": "Bileşeni yeniden adlandır", "cmd.component_replace_with_link": "Bağlantıyla Değiştir", "cmd.component_revert_position": "Konumu geri al", + "cmd.component_show_history": "Bileşen geçmişini göster", "cmd.component_unlock": "İçeriğin kilidini aç", "cmd.component_update_links": "Bağları güncelle", "cmd.config_activate": "Konfigürasyonu etkinleştir", @@ -867,6 +889,7 @@ "cmd.config_rule": "Konfigürasyon kuralı", "cmd.config_rules": "Konfigürasyon kuralları", "cmd.config_table": "Konfigürasyon tablosunu göster", + "cmd.construct.plane.axis_point": "Eksen ve noktadan geçen düzlem", "cmd.construct_axis_edge": "Kenardan geçen eksen", "cmd.construct_axis_normal_to_face": "Yüze dik eksen", "cmd.construct_axis_through_cylinder": "Silindir/koni/torus içinden geçen eksen", @@ -915,6 +938,11 @@ "cmd.explode_show": "Patlatılmış görünümü göster", "cmd.expr_evaluate": "İfadeyi değerlendir", "cmd.face_delete": "Yüzü sil", + "cmd.file.export_3mf": "3MF olarak dışa aktar", + "cmd.file.export_obj": "OBJ olarak dışa aktar", + "cmd.file.export_step": "STEP olarak dışa aktar", + "cmd.file.export_stl": "STL olarak dışa aktar", + "cmd.file.export_urdf": "URDF olarak dışa aktar", "cmd.file_export": "Dışa aktar", "cmd.file_insert_mesh": "Ağ ekle", "cmd.file_insert_step": "STEP ekle", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "Bileşen Renklerini Etkinleştir", "cmd.inspect_colored_components_disable": "Bileşen Renklerini Devre Dışı Bırak", "cmd.inspect_compare": "Gövdeleri karşılaştır", + "cmd.inspect_compare_picture": "Görüntüyle karşılaştır", "cmd.inspect_continuity": "Süreklilik kontrolü", "cmd.inspect_curvature_comb": "Eğrilik tarağı analizi", "cmd.inspect_curvature_map": "Eğrilik haritası analizi", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "Nokta Bulutunu Düzenle", "cmd.pointcloud_insert": "Nokta Bulutu Ekle", "cmd.pointcloud_list": "Nokta Bulutları", + "cmd.render.compare.divider": "Render Karşılaştırma Ayırıcısını Taşı", + "cmd.render.result.discard": "Render Sonucunu At", + "cmd.render.result.select": "Render Sonucunu Seç", "cmd.render_aging_describe": "Katmanlı Yüzey Yaşlanması", "cmd.render_backends": "Render arka uçları", "cmd.render_batch": "Tüm Çekimleri Render Et", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Kontrol noktalı spline (derece 5)", "cmd.sketch_spline_fit_point": "Uydurma noktalı spline", "cmd.sketch_spline_insert_point": "Spline Noktası Ekle", + "cmd.sketch_spline_remove_point": "Spline Noktasını Kaldır", "cmd.sketch_spline_reverse": "Spline yönünü ters çevir", "cmd.sketch_spun_profile": "Döndürülmüş profil", "cmd.sketch_toggle_diameter": "Yarıçap / Çap Arasında Geçiş Yap", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "Zaman çizelgesi işaretçisini taşı", "cmd.timeline_stop": "Geçmişi Durdur", "cmd.timeline_suppress": "Özelliği bastır", + "cmd.ui.assistant": "Asistanı aç/kapat", "cmd.view.render_browser": "Render tarayıcısı", "cmd.view.render_dock": "Render panelini taşı", "cmd.view.render_focus": "Render odak görünümü", + "cmd.view.status_details": "Görünüm Alanı Durum Ayrıntıları", "cmd.view.status_items": "Görünüm Alanı Durum Öğeleri", "cmd.view_ambient_occlusion": "Ortam tıkanması", "cmd.view_angle_readout": "Görünüm açıları", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "Gezinme aracı", "cmd.view_top": "Üst Görünüm", "cmd.view_visual_style": "Görsel stil", + "color.blue": "Mavi", "color.copy": "Renk değerlerini kopyalamak için tıklayın", "color.edit": "Rengi düzenlemek için tıklayın", "color.gamma": "Renk değerleri 0-255 gama uzayında gösteriliyor", + "color.green": "Yeşil", "color.hex": "Hex", "color.hex_help": "#rrggbb veya #rrggbbaa girin; altı hane opaklığı korur", "color.hex_hint": "#rrggbb", "color.hue": "Ton", "color.linear": "Renk değerleri 0-1 doğrusal uzayda gösteriliyor", + "color.recent": "Son kullanılan renkler", + "color.recent_help": "Herhangi bir renk alanında seçtiğiniz renkler burada görünür", + "color.red": "Kırmızı", + "color.saturation": "Doygunluk (yüzde)", "color.saturation_value": "Doygunluk ve değer", "color.selected": "Seçili renk", + "color.step_down": "Bir adım aşağı", + "color.step_up": "Bir adım yukarı", + "color.value": "Değer, yani parlaklık (yüzde)", "config.column_filter_empty": "Eşleşen sütun yok", + "config.rule_parameter_columns": "Yalnızca tabloda sütunu olan parametreler listelenir. Burada kullanmak için Sütun Ekle (+) ile bir sütun ekleyin.", + "config.rule_suppression_columns": "Yalnızca tabloda Bastır sütunu olan özellikler listelenir. Burada denetlemek için Sütun Ekle (+) ile bir sütun ekleyin.", "contact.components_count": "{count} bileşen", "contact.enabled_label": "etkin", "coupling.gear_1": "Dişli 1", @@ -1324,9 +1370,14 @@ "dialog.dimension_name": "Ölçü: {name}", "dialog.edit_title": "{title} düzenleniyor", "dialog.no_shown_body": "Değiştirilecek görünür gövde yok: bir gövdeyi gösterin ya da Yeni gövde seçin", + "dialog.pattern_sketch_not_object": "Gövdeleri veya özellikleri seçin: eskiz bunlardan hiçbiri değildir. Eğrilerini eskizin kendi Dizi veya Aynala komutuyla tekrarlayın ya da önce ekstrüzyon yapın.", "dialog.select": "↖ Seç", "dialog.selected_count": "↖ {count} seçildi", + "dialog.selection_constraint": "Kısıtlama {id}", + "dialog.selection_external_curve": "{sketch} · eğri {id}", "dialog.selection_guidance": "Değiştirmek için bir girdi seçin. Kaldırmak için seçili nesnelere tıklayın; Ctrl/Cmd+tıklama ile de seçime ekleyip çıkarabilirsiniz. Önizlemeyi kontrol edin ve ardından OK'e basın.", + "dialog.selection_midpoint": "Orta nokta · {id}", + "dialog.selection_profile": "{sketch} · profil {number}", "dialog.selection_step": "{step}/{total}: {input} seçin", "dialog.step": "Adım", "document.changed_on_disk": "{name} diskte değişti", @@ -1381,26 +1432,244 @@ "from the rule": "kuraldan", "help.apache": "Apache lisansı 2.0", "help.appearance.assign": "Seçili gövdelere, yüzlere veya bileşenlere ağırlıklarını değiştirmeden bir renk veya malzeme görünümü verir. Parçaları ayırt etmek veya bir kaplamayı önizlemek için kullanın.", + "help.assembly.bom": "Tasarımın veya bir bileşenin parçalarını parça numarasına göre adetleriyle listeler ve listeyi CSV ya da JSON olarak kaydedebilir. Sipariş ve montaj için parça listesi olarak kullanın.", "help.attributions": "Atıflar (ATTRIBUTION.md)", "help.build": "Sürüm {version} · commit {commit} · derleme tarihi {date}", + "help.canvas.decal": "Bir görseli modelin düz bir yüzüne çıkartma gibi yerleştirir. Bir parça üzerinde etiket, logo veya baskılı desen göstermek için kullanın.", + "help.canvas.edit": "Bir tuvali değiştirir: konumunu, boyutunu, açısını, opaklığını, aynalamasını, görünürlüğünü veya adını. Referans görseli, üzerinden çizdiğiniz eskizle hizalamak için kullanın.", + "help.canvas.insert": "Bir PNG veya JPEG görseli, saydam bir referans olarak bir düzleme ya da yüze yerleştirir. Görsel bilinen bir ölçüye getirilmiş hâlde, bir fotoğrafın veya çizimin üzerinden eskiz çizmek için kullanın.", + "help.component.break_link": "Bağlı bir bileşeni tasarım dosyasından ayırır, gövdelerini olduğu gibi korur. Parça artık özgün dosyadaki değişiklikleri izlememeliyse kullanın.", + "help.component.capture_position": "Elle taşıdığınız parçaların bulunduğu konumları kalıcı olarak saklar. Hiçbir bağlantının tutmadığı parçaları sürükleyerek yerlerine getirdikten sonra kullanın.", + "help.component.create": "Tasarıma yeni, boş bir bileşen ekler; başka bir üst öğe seçmediğiniz sürece etkin bileşenin içine. Bir montajın yeni parçasına gövdeleri ve eskizleri için ayrı bir yer açmak amacıyla kullanın.", "help.component.finish_edit": "Yerinde düzenlediğiniz parçayı kaydeder, montajına döner ve montajı bu parçadan günceller. Bağlı parçadaki değişiklikleriniz bittiğinde kullanın.", + "help.component.from_bodies": "Seçili her gövdeyi, gövdenin adını taşıyan kendi bileşenine dönüştürür. Ayrı gövdelerden kurulmuş bir tasarım, parçaları birbirine bağlanıp taşınabilen bir montaja dönüşecekse kullanın.", + "help.component.insert_design": "Kaydedilmiş başka bir tasarımı, dosyasına bağlı bir bileşen olarak ekler; katı gövdeleri oradaki gibi yerleştirilir. Bir parçayı montajda yeniden kullanmak ve sonraki değişiklikleri Bağları güncelle ile almak için kullanın.", + "help.component.properties": "Bir bileşenin hacmini, kütlesini, kütle merkezini ve eylemsizlik momentlerini gövdelerinin malzemelerine göre gösterir. Bir montajın ağırlığını ve dengesini kontrol etmek için kullanın.", + "help.component.revert_position": "Elle taşıdığınız parçaları eski yerlerine geri koyar; yakalanmamış taşımaları atar. Bir montajdaki deneme taşımalarını geri almak için kullanın.", + "help.component.update_links": "Bağlı tasarım dosyalarını yeniden okur ve değişen yerlerdeki gövdeleri değiştirir. Bu montajın kullandığı bir parçayı düzenledikten sonra kullanın.", + "help.config.configure": "Parametreleri, özellikleri, malzemeleri veya görünümleri konfigürasyon tablosuna sütun olarak ekler. Bir tasarımın, örneğin bir parçanın farklı boyutları gibi varyantlarını oluşturmak için kullanın.", + "help.config.preview": "Konfigürasyon tablosundaki bir satırın yeniden oluşturulabildiğini, tasarımı veya geçmişini değiştirmeden kontrol eder. Emin olmadığınız bir varyanta geçmeden önce kullanın.", + "help.config.rules": "Konfigürasyon tablosunun kurallarını, satırlarını ve hangi satırın etkin olduğunu gösterir. Bir tasarımın varyantlarının nasıl kurulduğunu görmek için kullanın.", + "help.config.table": "Konfigürasyon tablosunu gösterir: varyant başına bir satır, parametre veya özellik başına bir sütun ve tasarımın etkin satırla hâlâ uyuşup uyuşmadığı. Bir tasarımın varyantlarını gözden geçirmek için kullanın.", "help.connect_note": "SolidCraft sunucusunu yüklemek için her asistanı yeniden başlatın. Değişmeden önce her dosya .bak olarak yedeklendi.", "help.connect_title": "AI asistanlarını bağla", + "help.construct.axis.edge": "Düz bir kenar veya eskiz çizgisi boyunca bir yapı ekseni oluşturur. Döndürme, dairesel desen veya bağlantı için eksen olarak kullanın.", + "help.construct.axis.normal_to_face": "Bir noktadan geçen ve bir yüze dik duran bir yapı ekseni oluşturur. Bir yüzeyden dosdoğru çıkan bir eksen olarak kullanın.", + "help.construct.axis.through_cylinder": "Bir silindir, koni veya torus yüzünün ya da dairesel bir kenarın merkezinden geçen bir yapı ekseni oluşturur. Özellikleri yuvarlak bir parçanın etrafında döndürmek veya çoğaltmak için kullanın.", + "help.construct.axis.two_planes": "İki düzlemin veya düz yüzün buluştuğu yerde bir yapı ekseni oluşturur. İhtiyacınız olan eksen iki yüz arasındaki çizgiyse kullanın.", + "help.construct.axis.two_points": "İki noktadan, köşe noktasından veya eskiz noktasından geçen bir yapı ekseni oluşturur. Bilinen iki konum arasında uzanan bir eksen için kullanın.", + "help.construct.plane.along_path": "Bir kenara veya eğriye dik, onun boyunca bir konumda yapı düzlemi oluşturur. Süpürme için bir profili ya da bir yolun kesitini eskizlemek için kullanın.", + "help.construct.plane.at_angle": "Bir düzlemden veya yüzden, bir eksen ya da kenar etrafında belirli bir açıyla döndürülmüş yapı düzlemi oluşturur. Açılı bir köşebent gibi eğimli eskizler için kullanın.", + "help.construct.plane.axis_point": "Bir eksen ile bu eksenin dışında kalan bir noktayı içeren yapı düzlemi oluşturur. Bir orijini ya da yapı eksenini, bir düz kenarı veya eskiz çizgisini, ardından bir köşe noktasını, eskiz noktasını ya da yapı noktasını seçin. Eksen üzerindeki bir nokta tek bir düzlem belirleyemez.", + "help.construct.plane.midplane": "İki düzlemin veya düz yüzün tam ortasında, bir açıyla buluşuyorlarsa onları ikiye bölen yapı düzlemi oluşturur. Aynalama için simetri düzlemi olarak kullanın.", + "help.construct.plane.offset": "Bir düzleme veya düz yüze paralel, belirli bir mesafede ya da bir noktadan geçen yapı düzlemi oluşturur. Bir yüzün belirli bir yükseklik üstünde eskiz çizmek için kullanın.", + "help.construct.plane.perpendicular": "Bir çizgiyi veya kenarı içeren ve bir düzleme ya da yüze dik duran yapı düzlemi oluşturur. Bir modelde kenar boyunca dik duran eskizler çizmek için kullanın.", + "help.construct.plane.tangent": "Bir silindire, koniye, küreye veya torusa bir noktada değen yapı düzlemi oluşturur. Yuvarlak bir parçanın yan tarafına eskiz çizmek için kullanın.", + "help.construct.plane.three_points": "Üç noktadan geçen bir yapı düzlemi oluşturur. Modeldeki konumlarla, örneğin üç köşeyle belirlenen bir düzlem için kullanın.", + "help.construct.plane.two_edges": "Aynı düzlemde bulunan iki düz kenardan veya çizgiden geçen yapı düzlemi oluşturur. Bir parçayı boydan boya kesen, örneğin iki karşılıklı kenardan geçen bir düzlem için kullanın.", + "help.construct.point.along_path": "Bir kenar veya eğri boyunca bir konumda yapı noktası oluşturur. Bir yolun ara bir yerinde referans olarak kullanın.", + "help.construct.point.center": "Dairesel bir kenarın, eskiz dairesinin veya yayının, kürenin ya da torusun merkezinde yapı noktası oluşturur. Delikler, eksenler ve bağlantılar için referans olarak kullanın.", + "help.construct.point.edge_plane": "Bir kenarın veya çizginin bir düzlemden ya da düz yüzden geçtiği yerde yapı noktası oluşturur. Bir yolun düzlemi nerede kestiğini işaretlemek için kullanın.", + "help.construct.point.three_planes": "Üç düzlemin veya düz yüzün buluştuğu yerde yapı noktası oluşturur. Modelde köşe noktası olmasa bile köşe referansı olarak kullanın.", + "help.construct.point.two_edges": "İki kenarın veya çizginin buluştuğu ya da birbirine en çok yaklaştığı yerde yapı noktası oluşturur. Sanal bir köşede referans olarak kullanın.", + "help.construct.point.vertex": "Bir köşe noktası veya eskiz noktası üzerinde yapı noktası oluşturur. Çevresindeki eskiz ya da gövde gizlense bile kalan bir referans olarak kullanın.", + "help.contact.check": "Temas kümelerindeki parçalardan, mevcut konumlarında birbirinin içinden geçen çiftleri listeler. Bağlantıları tahrik etmeden veya hareket etüdü çalıştırmadan önce çarpışmaları bulmak için kullanın.", + "help.contact.create": "İki veya daha fazla parçayı, bağlantılar hareket ederken gövdelerinin birbirinin içinden geçmesi engellenen bir temas kümesinde toplar. Dokunduklarında durması gereken parçalar için kullanın, örneğin dayanağına dayanan bir kol.", + "help.contact.disable_all": "Teması kapatır; böylece tahrik edilen bağlantılar ve hareket etütleri parçaların dokunduğu yerde artık durmaz. Parçaları yeniden serbestçe hareket ettirmek veya büyük bir montajı akıcı tutmak için kullanın.", + "help.contact.edit": "Bir temas kümesini değiştirir: içerdiği parçaları, adını veya bastırılıp bastırılmadığını; kümeyi silebilir de. Hangi parçaların birbirinin içinden geçmesinin engelleneceğini ayarlamak için kullanın.", + "help.contact.enable_all": "Montajın her parçasını tek bir temas kümesine koyar; böylece bağlantılar hareket ederken hiçbir iki parça birbirinin içinden geçemez. Bütün bir mekanizmayı hızlıca denetlemek için kullanın.", + "help.contact.enable_sets": "Tanımladığınız temas kümeleri için teması açar; böylece tahrik edilen bağlantılar ve hareket etütleri, parçaların birbirinin içinden geçeceği yerde durur. Temas kapatıldıktan sonra kümelerinizi geri getirmek için kullanın.", + "help.contact.list": "Tasarımın temas kümelerini, her birindeki parçaları ve temasın açık olup olmadığını listeler. Montajı tahrik etmeden önce temasın nasıl kurulduğunu kontrol etmek için kullanın.", + "help.document.inspect": "Tasarıma genel bir bakış gösterir: bileşenlerini, gövdelerini, eskizlerini, özelliklerini ve parametrelerini. Kendinizin kurmadığı bir tasarımda yolunuzu bulmak için kullanın.", + "help.document.units": "Tasarımın uzunlukları hangi birimde göstereceğini değiştirir, örneğin mm veya inç. Geometri boyutunu korur; yalnızca görünüm ve düz sayılar buna uyar.", + "help.edit.checkpoint": "Tasarımı, etkin eskizi ve geri alma geçmişini şu anki hâliyle hatırlar. Geri dönmek isteyebileceğiniz riskli bir şey denemeden önce kullanın.", + "help.edit.restore_checkpoint": "Geri alma geçmişi dahil, bir kontrol noktasına geri döner. Kontrol noktasından beri yapılan her şeyi tek adımda atmak için kullanın.", + "help.explode.create": "Parçaları montajın merkezinden uzağa iten ya da belirlediğiniz taşımalarla ayıran bir patlatılmış görünüm oluşturur. Bir montajın nasıl birleştiğini talimatlarda veya sunumlarda göstermek için kullanın.", "help.face.delete": "Seçili yüzleri kaldırır ve komşu yüzlerin boşluğu kapatmasını sağlar ya da boşluğu yüzey olarak açık bırakır. Yuvarlatılmış bir kenarı, bir deliği veya yolda duran bir çıkıntıyı gidermek için kullanın.", + "help.file.insert_mesh": "Bir 3MF, STL, OBJ, PLY veya glTF dosyasını tasarıma, yeni bir bileşende ağ gövdeleri olarak ekler. İndirilmiş veya taranmış bir modeli referans olarak tasarımınızın yanına koymak için kullanın.", + "help.file.insert_step": "Bir STEP, IGES, FreeCAD veya Rhino dosyasını tasarıma, yeni bir bileşende katı gövdeler olarak ekler; bir montajın parçaları iç içe bileşenler olur. Tedarikçilerden veya diğer CAD programlarından modeller getirmek için kullanın.", + "help.file.save_mesh": "Gövdeleri, eğri yüzlerin pürüzsüzlüğünü seçerek STL, 3MF veya OBJ ağı olarak kaydeder. Parçaları 3B baskıya ya da ağ okuyan programlara hazırlamak için kullanın.", + "help.file.send_to_slicer": "Seçili gövdeleri 3MF dosyası olarak kaydeder ve seçtiğiniz dilimleyicide açar. Modelden baskıya tek adımda geçmek için kullanın.", "help.font_details": "Arayüz, egui'nin yerleşik yazı tiplerini kullanır (Ubuntu Font Licence ve MIT/Bitstream Vera lisansları altında Ubuntu Light ve Hack; OFL ve MIT altında Noto Emoji ve emoji simge yazı tipi). Eskiz metni Liberation Sans (SIL OFL 1.1) kullanır. The Crafting Apps'in isteğe bağlı yazı tipi paketi craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), SolidCraft derlemelerine dahil değildir.", "help.fonts": "Yazı tipleri", + "help.frame.member": "Bir profili, örneğin bir boruyu veya alüminyum ekstrüzyon profilini, bir çerçeve eskizinin çizgileri boyunca, çizgi başına bir eleman olacak şekilde yerleştirir. Çerçeveler, raflar ve kaynaklı yapılar kurmak için kullanın.", + "help.inspect.accessibility": "Bir aletin tek bir yönden ulaşabildiği yüzleri ve ulaşamadıklarını renklendirir. Bir parçayı o taraftan işleme veya kalıplama açısından kontrol etmek için kullanın.", + "help.inspect.center_of_mass": "Gövdelerin kütle merkezini, tek tek ve hepsi birlikte, düzgün yoğunlukla gösterir. Dengeyi ve bir parçanın nereye devrileceğini kontrol etmek için kullanın.", + "help.inspect.colored_components": "Her bileşene, görünümleri değiştirmeden geçici kendi rengini verir. Bir montajın parçalarını bir bakışta ayırt etmek için kullanın.", + "help.inspect.compare": "İki gövdeyi karşılaştırır ve birinde olup diğerinde olmayan malzemenin nerede olduğunu hacim ve sapmayla gösterir. Değiştirilmiş veya içe aktarılmış bir parçayı orijinaliyle karşılaştırıp kontrol etmek için kullanın.", + "help.inspect.continuity": "Yüzlerin kenarları boyunca ne kadar düzgün buluştuğunu denetler: boşlukları, kırıkları veya eğrilik sıçramalarını; birleşim yerlerini renklendirir. Yüzeylerin nerede temiz birleşmediğini bulmak için kullanın.", + "help.inspect.curvature_comb": "Eğriler, kenarlar veya yüzler boyunca, dişleri ne kadar güçlü eğildiklerini gösteren taraklar çizer. Düzleşmiş yerleri, kırıkları ve düzensiz eğriliği fark etmek için kullanın.", + "help.inspect.curvature_map": "Yüzleri ne kadar güçlü eğrildiklerine göre renklendirir; yarıçapın küçük olduğu yerler kırmızıdır. Dar noktaları bulmak ve bir yüzeyin ne kadar pürüzsüz olduğunu değerlendirmek için kullanın.", + "help.inspect.draft": "Yüzleri, kalıptan çıkarma yönüne göre koniklik açılarına göre renklendirir ve yetersiz olanları işaretler. Bir parçayı kalıplamadan veya dökmeden önce kontrol etmek için kullanın.", + "help.inspect.environment_map": "Modeli yansıtıcı, ayna gibi bir yüzeyle gösterir. Yüzeylerin akışını, yansımaların üzerlerinden nasıl geçtiğine bakarak değerlendirmek için kullanın.", + "help.inspect.interference": "Örtüşen gövdeleri bulur ve her örtüşmeyi hacmiyle gösterir. Bir montajda çarpışan parçalar olup olmadığını kontrol etmek için kullanın.", + "help.inspect.isocurve": "Yüzlerin izoparametrik eğrilerini, yani yüzeyin üzerine kurulduğu ızgarayı çizer. Bir yüzeyin nasıl aktığını ve nerede sıkıştığını görmek için kullanın.", + "help.inspect.measure": "Seçtiğiniz öğeler arasındaki uzunlukları, mesafeleri, açıları, alanları ve yarıçapları ya da gövdelerin hacmini ve kütlesini ölçer. Boyutları ve boşlukları kontrol etmek için kullanın.", + "help.inspect.minimum_radius": "Eğrilerin, kenarların veya yüzlerin en küçük eğrilik yarıçapını ve nerede olduğunu bulur. Bir aletin veya nozulun şekli izleyip izleyemeyeceğini kontrol etmek için kullanın.", + "help.inspect.section": "Görünümü bir düzlem boyunca keserek açar ve kesilen yüzleri tarar; modeli değiştirmez. Parçaların ve montajların içine bakmak için kullanın.", + "help.inspect.zebra": "Modelin yüzlerinde yansıyan siyah beyaz şeritleri gösterir. Pürüzsüzlüğü değerlendirmek için kullanın: bir kenarda kopan veya kırılan şeritler zayıf bir geçişe işaret eder.", + "help.joint.as_built": "İki parçayı, ikisini de oynatmadan bulundukları yerde birbirine bağlar ve hâlâ nasıl hareket edebileceklerini belirler. Son konumlarına zaten yerleştirdiğiniz parçalar için kullanın.", + "help.joint.cam": "Dönen bir kamı bir izleyiciye bağlar; kamın dış hattı altından geçerken izleyici kayar veya salınır. Kamlar, eksantrikler ve supap tahrikleri için kullanın.", + "help.joint.create": "İki parçayı seçtiğiniz bağlantı orijinlerinde birleştirir ve ikinci parçayı yerine taşır; bağlantı türü, hâlâ nasıl hareket edebileceklerini belirler. Parçaları gerçek mekanizma gibi hareket eden bir montaj kurmak için kullanın.", + "help.joint.drive": "Bir bağlantının açısını veya mesafesini ayarlar ve parçaları sınırları içinde onunla birlikte hareket ettirir; bağlı bağlantılar ve kapalı döngüler de buna uyar. Bir mekanizmanın istendiği gibi hareket ettiğini kontrol etmek için kullanın.", + "help.joint.gear": "Dönen iki bağlantıyı bir dişli oranıyla bağlar; birini sürmek diğerini döndürür. Düz ve iç dişliler için kullanın; oran, adım yarıçaplarından veya diş sayılarından alınır.", + "help.joint.limits": "Bir bağlantının ne kadar dönebileceğini veya kayabileceğini en az ve en çok olarak belirler ya da bu sınırları temizler. Bir menteşeyi, kayar bağlantıyı veya kolu gerçek hareket aralığında tutmak için kullanın.", + "help.joint.motion_link": "İki bağlantıyı bir oran ve bir ofsetle eşler; birini sürmek diğerini hareket ettirir. Dişli, Kremayer ve pinyon veya Vida'nın kapsamadığı, bağlantılar arasındaki sabit bir ilişki için kullanın.", + "help.joint.origin": "Bir parça üzerine adlandırılmış bir bağlantı orijini yerleştirir: bir yüzün veya yuvarlak bir ucun merkezine, bir kenarın ortasına, bir köşeye ya da bir noktaya. Bağlantıların nereye tutunacağını hazırlamak için kullanın; bir yüzde seçilen orijin, parça boyut değiştirdiğinde yüzü izler.", + "help.joint.rack_pinion": "Dönen bir pinyonu kayan bir kremayere bağlar; kremayer, pinyonun üzerinde yuvarlandığı adım dairesi uzunluğu kadar hareket eder. Kremayer tahrikleri, direksiyon ve doğrusal tablalar için kullanın.", + "help.joint.reach": "Bir parça üzerindeki bir noktayı, zincirindeki bağlantıları sınırları içinde değiştirerek bir hedefe doğru taşır. Bir mekanizmayı, ucunun olması gereken yere göre konumlandırmak için kullanın, örneğin bir robot kolunun ucu.", + "help.joint.rigid_group": "Seçili parçaları olduğu gibi birbirine kilitler; böylece tek parça olarak hareket ederler. Birbirine ait olan ve aralarında hareket bulunmayan parçalar için kullanın.", + "help.joint.screw": "Dönmeyi ve kaymayı bir adımla bağlar; her tur o mesafe kadar ilerler. Hareket vidaları, cıvatalar ve dişli miller için kullanın.", + "help.library.apply": "Yerel bir kitaplık dosyasındaki bir malzemeyi veya görünümü gövdelere, yüzlere ya da bileşenlere uygular. Başka bir tasarımdan kaydettiğiniz malzemeleri tekrar uygulamak için kullanın.", + "help.library.export": "Tasarımın malzemelerini ve görünümlerini bir kitaplık dosyasına kaydeder. Bunları paylaşmanız ya da başka tasarımlarda yeniden kullanmanız gerekiyorsa kullanın.", + "help.library.inspect": "Bir kitaplık dosyasını denetler ve içindeki malzemeleri ile görünümleri, tasarımı değiştirmeden listeler. Uygulamadan önce kitaplığın neler içerdiğini görmek için kullanın.", "help.licences": "Lisanslar", "help.material.assign": "Seçili gövdelerin neyden yapıldığını belirler: çelik, alüminyum veya ABS gibi. Kütle ve ağırlığın gerçek parçayla uyuşması için kullanın.", + "help.material.properties.validate": "Bir malzeme veri kartını tutarlı sayılar ve eksik değerler açısından kontrol eder. Verilere kütle veya rijitlik için güvenmeden önce kullanın.", + "help.mesh.convert": "STL gibi bir ağ gövdesini, düz ve silindirik yüzlerden oluşan düzenlenebilir bir katı olarak yeniden kurar. İçe aktarılmış mekanik parçaları modellenmiş bir gövde gibi değiştirmek için kullanın.", "help.mit": "MIT lisansı", + "help.motion.study": "Bağlantı değerlerini bir zaman çizelgesi boyunca adımlarda ayarlar ve animasyon olarak oynatır. Bir mekanizmanın bir dizi boyunca hareketini izlemek ve yol boyunca açıklıkları kontrol etmek için kullanın.", + "help.motion.trace": "Bir hareket etüdü oynatılırken veya bir bağlantı sürülürken bir parça üzerindeki bir noktanın izlediği yolu çizer ve onayladığınızda 3B eskiz eğrisi olarak saklar. Bir mekanizmanın nereye eriştiğini görmek veya yolu üzerine bir şey kurmak için kullanın.", "help.notice": "NOTICE", + "help.occurrence.ground": "Bir parçayı yerine sabitler ya da yeniden serbest bırakır; böylece bağlantılar diğer parçaları onun etrafında hareket ettirir. Montajın geri kalanının üzerine kurulduğu çerçeve veya taban için kullanın.", "help.occurrence.move": "Montaj parçasını yalnızca eklemlerinin izin verdiği serbestliklerde taşır. Bir parça yüzü seçtikten sonra kullanılabilir oku veya yayı sürükleyin.", "help.parameters.change": "Tasarımın ölçülerini yöneten adlandırılmış değerlerin ve ifadelerin tablosunu açar. Bir ölçüyü tek yerden değiştirip onu kullanan her özelliğin buna uymasını sağlamak için kullanın.", + "help.parameters.export": "Tasarımın parametrelerini CSV veya JSON olarak kaydeder. Bunları bir elektronik tabloda düzenlemek veya başka bir tasarıma taşımak için kullanın.", + "help.parameters.graph": "Hangi parametrelerin ve özelliklerin hangilerini kullandığını, aralarındaki döngüleri veya hataları gösterir. Bir parametreyi değiştirmenin neleri etkileyeceğini görmek için kullanın.", + "help.parameters.import": "Parametreleri CSV veya JSON dosyasından tasarıma okur; ya hepsini ya hiçbirini. Değerleri bir elektronik tablodan veya başka bir tasarımdan getirmek için kullanın.", + "help.parameters.move": "Bir kullanıcı parametresini listede başka birinin önüne veya arkasına taşır. İlgili parametreleri bir arada tutmak için kullanın.", + "help.parts.fastener": "Seçtiğiniz boyutta standart bir vida, cıvata, somun, rondela, pim veya rulman ekler. Bir deliğe yerleştirildiğinde bir bağlantıyla deliğe oturur; böylece bağlantı elemanlarını kendiniz modellemeniz gerekmez.", + "help.parts.insert": "Seçtiğiniz ailede, boyutta ve uzunlukta standart bir parça ekler. Bir deliğin kenarına veya çeperine yerleştirildiğinde, rijit bir bağlantıyla deliğe oturur.", + "help.parts.library": "Standart parçaları açar: standart boyutlarda vidalar, cıvatalar, somunlar, rondelalar, tespit vidaları, silindirik pimler ve rulmanlar. Bir standart parçayı kendiniz modellemek yerine eklemek için kullanın.", + "help.parts.resize": "Eklenmiş bir standart parçanın boyutunu veya uzunluğunu değiştirir ve yeniden oluşturur; bağlantıları onu yerinde tutar. Bir vida çok uzun çıkarsa veya bir delik başka bir boyut gerektiriyorsa kullanın.", + "help.plastic.assign_rule": "Gövdelere bir plastik kuralı atar; böylece plastik özellikleri koniklik ve açıklık değerlerini varsayılan olarak ondan alır. Kalıplanmış bir parçayı tüm özellikleri için bir kez kurmak amacıyla kullanın.", + "help.plastic.boss": "Bir yüze vida göbeği ekler: isteğe bağlı delik, koniklik, kök yuvarlatması ve destek nervürleri olan bir direk. Kalıplanmış veya basılmış kasalardaki vida noktaları için kullanın.", + "help.plastic.lip": "İçi boşaltılmış bir gövdenin kenarı boyunca bir dudak veya buna uyan bir oluk ekler. İki kasa yarısının birbirine oturması ve sıkıca kapanması için kullanın.", + "help.plastic.manage_rules": "Plastik kurallarını oluşturur ve düzenler: malzeme, et kalınlığı, yarıçaplar, açıklık ve koniklik. Kalıplanmış bir parçanın özelliklerini tutarlı tutmak için kullanın.", + "help.plastic.rest": "Bir yüze dayanak ekler: yuvarlak veya dikdörtgen, dolu veya içi boş, konikliği olan bir ayak. Kalıplanmış bir kasada destek veya mesafe parçası olarak kullanın.", + "help.plastic.snap_fit": "Bir yüze, uzunluğu, kalınlığı ve tırnağıyla bir geçmeli bağlantı kancası ekler. Parçaları vidasız birbirine geçirmek için kullanın.", "help.pointcloud.insert": "PLY, XYZ veya PTS taramasını modelin yanına nokta bulutu olarak ekler. Ölçülmüş verilerden model oluştururken referans olarak kullanın.", + "help.sheet.convert": "Eşit kalınlıkta bir plakayı veya içi boşaltılmış bir gövdeyi, seçtiğiniz kenarlarda bükümlerle sac metal gövdeye dönüştürür. Mevcut bir parçayı açılabilir hâle getirmek için kullanın.", + "help.sheet.export_bend_table": "Bir sac metal gövdenin büküm tablosunu CSV veya JSON olarak kaydeder: açılar, yarıçaplar ve açınımdaki büküm konumları. Abkant pres veya atölye için kullanın.", + "help.sheet.export_dxf": "Açınımı DXF olarak kaydeder; dış hatlar, büküm çizgileri ve isteğe bağlı büküm notlarıyla. Lazer, plazma veya su jeti ile kesim için kullanın.", + "help.sheet.flange": "Bir flanş ekler: bir eskizden taban plakası, açık bir eskiz konturu boyunca bir cidar ya da sac kenarlarında bükülmüş bir cidar. Sac metal parçaları oluşturmak için kullanın.", + "help.sheet.flat_pattern": "Bir sac metal gövdenin açınımını boyutu, kesik alanları ve büküm çizgileriyle oluşturur. Kesmeden önce ham parçayı kontrol etmek için kullanın.", + "help.sheet.fold": "Bir sacı, bir eskiz çizgisi boyunca belirli bir açı ve yarıçapla büker. İçine kesme özellikleri ekledikten sonra düz bir sacı katlamak için kullanın.", + "help.sheet.hem": "Bir sac kenarını kendi üzerine geri katlar. Keskin çapaklar içermeyen, güvenli ve sağlam kenarlar için kullanın.", + "help.sheet.manage_rules": "Sac metal kurallarını oluşturur ve düzenler: kalınlık, büküm yarıçapı, K faktörü, boşaltmalar ve boşluklar. Atölyenizin malzemesine ve takımlarına uyum sağlamak için kullanın.", + "help.sheet.path_flange": "Açık bir eskiz çizgisi zincirini izleyerek bir sac kenarı boyunca bir flanş zinciri ekler. U veya Z biçimi gibi profilleri tek adımda oluşturmak için kullanın.", + "help.sheet.perforate": "Tüm düz sac üzerine, kaydırmalı veya kare desende bir delik alanı ekler. Havalandırmalar, ızgaralar ve daha hafif paneller için kullanın.", + "help.sheet.refold": "Açılmış bir sac metal gövdeyi yeniden katlar. Düz sace özellikler ekledikten sonra kullanın.", + "help.sheet.unfold": "Bir sac metal gövdenin tüm bükümlerini açar. Bir bükümü kesmesi gereken delikler veya kesimler eklemek için kullanın, ardından yeniden katlayın.", + "help.sketch.arc.center_point": "Bir merkez noktası etrafında, bir başlangıç noktasından bir bitiş noktasına dairesel bir yay çizer. Yayın merkezi biliniyorsa kullanın; örneğin bir deliğin ya da bir dönme noktasının etrafındaki yarıçap.", + "help.sketch.arc.tangent": "Bir çizginin veya yayın ucunda başlayan ve ona teğet olarak devam eden bir yay çizer. Zinciri köşe yerine yumuşak bir dönüşle sürdürmek için kullanın.", + "help.sketch.arc.three_point": "Bir başlangıç noktasından bir bitiş noktasına, üçüncü bir noktadan geçen bir yay çizer. Yay, bilinen bir merkez etrafında değil de verilen noktalardan geçmek zorundaysa kullanın.", + "help.sketch.arc3d": "3B eskiz açıkken, uzayda üç noktadan geçen tam bir dairesel yay çizer. Eskiz düzleminden çıkan yolların ve kılavuz raylarının kıvrımları için kullanın.", + "help.sketch.auto_constrain": "Eskizin neredeyse zaten sahip olduğu kısıtlamaları, örneğin yatay, paralel veya çakışık gibi olanları ekler, ardından tam tanımlanana kadar ölçülendirir. Kabaca çizilmiş bir eskizi tek adımda kilitlemek için kullanın.", + "help.sketch.auto_constrain_from_datum": "Otomatik kısıtlama gibi çalışır, ancak konumları orijin yerine seçtiğiniz bir referans noktasından ölçer. Parça tek bir referans noktasından, örneğin bir köşeden veya bir delikten yerleştirilmişse kullanın.", + "help.sketch.blend_curve": "İki eğrinin uçlarını, ikisine de teğet, istenirse eğrilik sürekli de olan pürüzsüz bir spline ile birleştirir. Eğriler arasındaki boşluğu kırıksız kapatmak için kullanın.", + "help.sketch.break": "Bir eğriyi, başka eğrilerin onu kestiği yerlerde veya üzerine koyduğunuz noktalarda parçalara böler. Eğrinin bir bölümü kendi kısıtlamasına ihtiyaç duyuyorsa ya da tek başına silinecekse kullanın.", + "help.sketch.cancel": "Eskizden çıkar ve oluşturulduğundan ya da düzenleme için açıldığından beri yapılan her değişikliği atar. Geri al değişiklikleri geri getirir.", + "help.sketch.centerline": "Çizgileri normal çizgi ile merkez çizgisi, yani profillerin dışında bıraktığı bir eksen, arasında değiştirir. Merkez çizgisini döndürme, ayna veya simetri kısıtlaması için eksen olarak kullanın.", + "help.sketch.chamfer.distance_angle": "İki çizgi arasındaki köşeyi, ilk çizgi boyunca bir mesafe ve bir açıyla belirlenen şekilde pahlar. Bir çizim pahı uzunluk ve açı olarak veriyorsa, örneğin 2 mm × 30°, kullanın.", + "help.sketch.chamfer.equal_distance": "İki çizgi arasındaki köşeyi, her iki çizgi boyunca aynı mesafe geriden pahlar. Bir dış hatta uygulanan olağan 45° pah için kullanın.", + "help.sketch.chamfer.two_distance": "İki çizgi arasındaki köşeyi, her çizgi boyunca ayrı bir mesafeyle belirlenen şekilde pahlar. İki uzunluk olarak verilen, 45° olmayan pahlar için kullanın.", + "help.sketch.circle.center": "Bir daireyi merkezinden ve çapından çizer. Merkezi bilinen delikler, kabarıklıklar ve diğer yuvarlak özellikler için kullanın.", + "help.sketch.circle.three_point": "Üç noktadan geçen bir daire çizer. Dairenin verilen noktalardan, örneğin mevcut geometrinin noktalarından geçmesi gerekiyorsa kullanın.", + "help.sketch.circle.three_tangent": "Üç çizgiye, daireye veya yaya değen bir daire çizer. Bir daireyi üç eğri arasındaki boşluğa oturtmak için kullanın; örneğin bir üçgenin iç teğet çemberi.", + "help.sketch.circle.two_point": "Bir daireyi çapının iki ucundan çizer. Merkezi değil de dairenin kenar noktaları biliniyorsa kullanın.", + "help.sketch.circle.two_tangent": "İki çizgiye, daireye veya yaya değen, verilen boyutta bir daire çizer. İki eğri arasında sabit yarıçaplı bir yuvarlatma için kullanın.", + "help.sketch.conic": "İki uç nokta arasında, bir tepe noktası ve bir rho değeriyle biçimlenen konik bir eğri çizer. Doluluğunu düz bir hattan neredeyse keskin bir köşeye kadar ayarlamak istediğiniz yumuşak geçişler için kullanın.", + "help.sketch.constrainer": "Seçilen bir veya iki eğrinin neredeyse zaten sahip olduğu kısıtlamayı, örneğin yatay, paralel, teğet veya eşit gibi olanı uygular. Elle çizilmiş bir eskizi her seferinde bir ilişkiyle düzene sokmak için kullanın.", + "help.sketch.constraint.coincident": "Bir noktayı başka bir noktanın, bir eğrinin veya bir eskiz ekseninin üzerine oturtur. Bir profildeki boşlukları kapatmak veya bir noktayı çizgi üzerine koymak için kullanın.", + "help.sketch.constraint.collinear": "İki çizgiyi aynı doğru üzerine getirir. Kesintiye uğramış kenarları, örneğin bir çentiğin iki yanını hizalamak için kullanın.", + "help.sketch.constraint.concentric": "İki daireye veya yaya aynı merkezi verir. Halkalar, düz havşalar ve omuzlu miller için kullanın.", + "help.sketch.constraint.curvature": "Bir uç noktada buluşan iki eğrinin aynı eğrilikle devam etmesini sağlar (G2). Teğet bir birleşimin yeterince pürüzsüz olmadığı yerlerde, örneğin görünen yüzeylerde kullanın.", + "help.sketch.constraint.equal": "Çizgileri aynı uzunlukta, daireleri ve yayları aynı yarıçapta yapar. Tek bir ölçünün birbirine uyan birkaç özelliği yönetmesi için kullanın.", + "help.sketch.constraint.fix": "Noktaları veya eğrileri bulundukları yere sabitler ya da yeniden serbest bırakır. Eskizi sürüklediğinizde veya çözdüğünüzde hareket etmemesi gereken geometri için kullanın.", + "help.sketch.constraint.horizontal_vertical": "Bir çizgiyi ya da iki nokta arasındaki çizgiyi, hangisine daha yakınsa yatay veya dikey yapar. Bir dış hattı eskiz eksenlerine hizalamak için kullanın.", + "help.sketch.constraint.midpoint": "Bir noktayı bir çizginin ortasına yerleştirir ya da iki çizginin orta noktalarını çakıştırır. Geometriyi bir kenar üzerinde ortalamak için kullanın.", + "help.sketch.constraint.parallel": "İki çizgiyi paralel yapar. Diğer ölçüler değiştiğinde paralel kalması gereken kenarlar için kullanın.", + "help.sketch.constraint.perpendicular": "İki çizgiyi dik açıyla buluşturur. Eskiz eksenleri üzerinde olmayan çizgiler arasındaki dik köşeler için kullanın.", + "help.sketch.constraint.polygon": "Kapalı bir çizgi zincirini düzgün bir çokgen yapar: eşit kenarlar ve her köşe tek bir daire üzerinde. Elle çizilmiş bir çokgeni düzgün hâle getirmek ve öyle tutmak için kullanın.", + "help.sketch.constraint.symmetry": "İki noktanın veya eğrinin bir çizgiye göre ya da bir noktaya göre birbirinin aynası olmasını sağlar. Bir tarafı değiştirdiğinizde profilin simetrik kalması için kullanın.", + "help.sketch.constraint.tangent": "İki eğriyi, örneğin bir çizgiyi ve bir yayı, teğet olarak değdirir. Kırıksız, pürüzsüz birleşimler için kullanın.", + "help.sketch.construction": "Eğrileri normal geometri ile profillerin dışında bıraktığı yapı geometrisi arasında değiştirir. Yapı eğrilerini yerleşim, referans ve ölçüler için yardımcı olarak kullanın.", + "help.sketch.construction_line": "İki noktadan geçen sonsuz bir yardımcı doğru oluşturun. Profilleri bölmeden bir eskizi kurgulamak için kullanın.", + "help.sketch.construction_line.angle": "Eskizin X ekseninden belirli bir açıyla sonsuz bir yardımcı doğru oluşturun. Noktayı seçip açıyı yazın veya yönünü seçin.", + "help.sketch.construction_line.bisector": "Kesişen iki düz eskiz çizgisini seçin, ardından iki açıortaydan birini seçin. Sonuç, kaynak çizgilerini izler.", + "help.sketch.construction_line.horizontal": "Bir noktadan geçen sonsuz yatay bir yardımcı doğru oluşturun. Yatay kısıtlaması sonraki düzenlemelerde de korunur.", + "help.sketch.construction_line.parallel": "Düz bir eskiz çizgisi seçin, ardından paralel bir sonsuz yardımcı doğru yerleştirin. Başka bir referans seçmek için sağ tıklayın.", + "help.sketch.construction_line.perpendicular": "Düz bir eskiz çizgisi seçin, ardından dik bir sonsuz yardımcı doğru yerleştirin. Başka bir referans seçmek için sağ tıklayın.", + "help.sketch.construction_line.tangent_at": "Bir daire veya dairesel yay üzerindeki bir noktada ya da açık bir spline veya konik eğrinin uç noktasında teğet oluşturun. Önce eğriyi, sonra değme noktasını seçin.", + "help.sketch.construction_line.tangent_external": "Bir daire veya dairesel yay seçin, ardından bir dış nokta ve bir teğet çözümü seçin. Önizlemeler yalnızca çizilen yay üzerindeki değme noktalarını gösterir.", + "help.sketch.construction_line.tangent_two": "İki daire veya dairesel yay seçin, ardından önizlemede ortak bir teğet seçin. Değme noktaları çizilen eğriler üzerinde olmalıdır.", + "help.sketch.construction_line.vertical": "Bir noktadan geçen sonsuz dikey bir yardımcı doğru oluşturun. Dikey kısıtlaması sonraki düzenlemelerde de korunur.", + "help.sketch.copy": "Seçili eskiz eğrilerini ve noktalarını, aralarındaki kısıtlamalar ve ölçülerle birlikte kopyalar. Bunları bu eskize veya başka bir eskize yapıştırın.", + "help.sketch.create": "Bir düzlemde veya modelin düz bir yüzünde yeni bir 2B eskiz başlatır. Her ekstrüzyon, döndürme ve süpürme bir eskizle başlar.", + "help.sketch.cut": "Seçili eskiz geometrisini kopyalar ve tek bir geri alma adımında eskizden siler. Bu eskizin başka bir yerine veya başka bir eskize yapıştırın.", + "help.sketch.dimension": "Sürücü bir ölçü ekler: seçtiğinize göre bir uzunluk, mesafe, açı, yarıçap veya çap. Bir değer ya da parametre adı yazın, eskiz onu izler.", + "help.sketch.edit": "Mevcut bir eskizi düzenlemek için açar. Üzerine kurulan özellikler, eskizi bitirdiğinizde güncellenir.", + "help.sketch.ellipse": "Bir elipsi merkezinden, büyük ekseninin ucundan ve küçük kenarındaki bir noktadan çizer. Oval açıklıklar, kamlar ve diğer uzamış yuvarlak biçimler için kullanın.", "help.sketch.equation_curve": "Formüllerden bir eğri çizer: bir aralık boyunca x(t) ve y(t) ya da y = f(x). Formüller parametre kullanabilir ve eğri onları izler: sinüs dalgası, spiral veya bir dişli dişinin evolventi için kullanın.", + "help.sketch.extend": "Bir çizgiyi veya yayı yolundaki en yakın eğriye kadar uzatır ya da iki eğriyi buluşana kadar büyütür. Kırpma veya düzenlemeden sonra bir profildeki boşlukları kapatmak için kullanın.", + "help.sketch.fillet": "İki çizginin veya yayın buluştuğu köşeyi verilen yarıçaplı bir yayla yuvarlar. Birlikte yuvarlatılan birkaç köşe aynı yarıçapı paylaşır.", + "help.sketch.finish": "Eskizden çıkar ve modele döner. Kapalı profilleri artık Ekstrüzyon, Döndür ve diğer özellikler için hazırdır.", + "help.sketch.finish_auto_constrain": "Eskize Otomatik kısıtlama uygular, ardından eskizi bitirir. Bir eskizi tek adımda tam tanımlı bırakmak için kullanın.", + "help.sketch.fit_curves_to_section": "Bir ağ veya katı gövdeyi eskiz düzlemiyle keser ve kesite çizgiler ile yaylar uydurur. Taranmış veya içe aktarılmış bir parçayı düzenlenebilir bir eskiz olarak yeniden kurmak için kullanın.", + "help.sketch.include_3d": "Model kenarlarını, köşe noktalarını ve diğer eskizlerin eğrilerini bu eskize bağlı referanslar olarak getirir; düzleminin dışında kalanları ona düzleştirir. Eskiz düzleminde bulunmayan geometri üzerine kurmak için kullanın.", + "help.sketch.infinite": "Çizgileri normal çizgi ile tüm görünüm boyunca uzanan sonsuz yardımcı doğrular arasında değiştirir. Hiçbir zaman kısa kalmayan yerleşim referansları olarak kullanın.", + "help.sketch.insert_dxf": "Bir DXF çiziminin eğrilerini, belirlediğiniz ölçekte, açıda ve konumda bir eskize okur. Başka bir programdan gelen 2B çizim üzerine, örneğin lazerle kesilecek bir dış hat üzerine kurmak için kullanın.", + "help.sketch.insert_svg": "Bir SVG çiziminin yollarını, belirlediğiniz ölçekte, açıda ve konumda bir eskize okur. Bir logoyu veya vektör dış hattını ekstrüzyon yapabileceğiniz eğrilere dönüştürmek için kullanın.", + "help.sketch.inspect": "Açık eskiz için bir rapor açar: kaç serbestlik derecesi kaldığını ve tam kısıtlı olup olmadığını. Eskizi bitirmeden önce nelerin hâlâ hareket ettiğini öğrenmek için kullanın.", + "help.sketch.intersect": "Gövdelerin, yüzlerin, kenarların veya diğer eskizlerin eskiz düzlemini kestiği eğrileri ya da noktaları ekler. Bağlı kalır ve model değiştiğinde onu izler.", + "help.sketch.intersection_curve": "İki gövdenin veya yüzün buluştuğu yerde, onlara bağlı 3B eğriler oluşturur. Bunları modeli izleyen yollar veya kılavuz raylar olarak kullanın.", + "help.sketch.isoparametric_curve": "Bir yüzün U veya V yönü boyunca, seçtiğiniz bir noktadan geçen ve yüze bağlı bir 3B eğri oluşturur. Yüzeyi izleyen bir yol veya bölme çizgisi olarak kullanın.", + "help.sketch.line": "Bağlantılı çizgileri nokta nokta, açık bir zincir veya kapalı bir dış hat olarak çizer. Çoğu profil için temel araçtır.", + "help.sketch.line.midpoint": "Bir çizgiyi orta noktasından bir uca doğru çizer; diğer uç yansıtılır. Bir nokta etrafında ortalanmış çizgiler, örneğin simetrik bir kenar için kullanın.", + "help.sketch.line3d": "3B eskiz açıkken, uzaydaki noktalar arasında bağlantılı düz çizgiler çizer. Eskiz düzleminden çıkan yollar ve çerçeveler için kullanın.", + "help.sketch.mirror": "Eskiz eğrilerini ve noktalarını bir çizgi veya eksen boyunca aynalar ve simetri kısıtlamaları ekler. Simetrik bir profilin yarısını çizip tamamlamak için kullanın.", + "help.sketch.move": "Eskiz eğrilerini ve noktalarını ya da kopyalarını taşır veya döndürür. Geometrinin şeklini ve kısıtlamalarını koruyarak yerini değiştirmek için kullanın.", + "help.sketch.offset": "Bir eğri zincirinin kopyasını, bir tarafta ya da her iki tarafta belirli bir mesafede oluşturur. Cidarlar, dış hatlar ve açıklıklar için kullanın; mesafe düzenlenebilir bir ölçü olarak kalır.", + "help.sketch.paste": "Kopyaladığınız veya kestiğiniz eskiz geometrisini etkin eskize yapıştırır. Bir noktaya yerleştirin ya da bir ofsetle kaydırın.", + "help.sketch.pattern.circular": "Eskiz geometrisini bir merkez noktası etrafında, tam bir daire veya belirli bir açı boyunca kopyalar. Cıvata daireleri, kollar ve dişler için kullanın.", + "help.sketch.pattern.rectangular": "Eskiz geometrisini belirli aralıklarla satırlar ve sütunlar halinde kopyalar. Delik, yuva veya havalandırma ızgaraları için kullanın.", + "help.sketch.point": "Bir eskiz noktası yerleştirir. Ölçüler, kısıtlamalar, delik merkezleri veya sonraki özellikler için referans olarak kullanın.", + "help.sketch.point3d": "3B eskiz açıkken uzayda bir nokta yerleştirir. 3B eğriler ve yollar için referans olarak kullanın.", + "help.sketch.polygon.circumscribed": "Bir dairenin etrafına, merkezinden bir kenarın ortasına kadar olan mesafeye göre boyutlandırılmış düzgün bir çokgen çizer. Anahtar ağzı genişliği biliniyorsa, örneğin altıgen bir somun için kullanın.", + "help.sketch.polygon.edge": "Düzgün bir çokgeni bir kenarının iki ucundan çizer. Bir kenarın uzunluğu ve konumu biliniyorsa kullanın.", + "help.sketch.polygon.inscribed": "Bir dairenin içine, merkezinden bir köşeye kadar olan mesafeye göre boyutlandırılmış düzgün bir çokgen çizer. Köşeler arası ölçü biliniyorsa kullanın.", + "help.sketch.project": "Model kenarlarını, yüzlerini, köşe noktalarını ve diğer eskizlerin eğrilerini bu eskizin düzlemine yansıtarak getirir. Bağlı kalır ve model değiştiğinde onu izler.", + "help.sketch.project_to_surface": "Diğer eskizlerin eğrilerini bu eskizin normali boyunca bir yüze, bağlı 3B eğriler olarak yansıtır. Bir logoyu, bölme çizgisini veya yolu eğri bir yüzeye koymak için kullanın.", + "help.sketch.rectangle.center": "Bir dikdörtgeni merkezinden ve bir köşesinden çizer. Bir nokta, örneğin orijin, etrafında ortalanmış dış hatlar için kullanın.", + "help.sketch.rectangle.rounded": "Dört köşesi de tek bir yarıçapla yuvarlatılmış bir dikdörtgen çizer. Yuvarlatılmış köşeli plakalar, kapaklar ve açıklıklar için kullanın.", + "help.sketch.rectangle.three_point": "Bir dikdörtgeni bir kenarından ve karşı taraftaki bir noktadan çizer. Eskiz eksenlerine açılı duran dikdörtgenler için kullanın.", + "help.sketch.rectangle.two_point": "Bir dikdörtgeni iki karşılıklı köşesinden çizer. Plakaların, blokların ve ceplerin dış hatları için kullanın.", + "help.sketch.scale": "Eskiz eğrilerini ve noktalarını bir taban noktası etrafında bir çarpanla ölçekler. Bir eskizin bir bölümünü yeniden çizmeden boyutlandırmak için kullanın.", + "help.sketch.slot.arc_center": "Merkezi, başlangıcı ve bitişiyle belirlenen bir yay boyunca, verilen genişlikte eğri bir yuva çizer. Bir dönme noktası etrafındaki ayar yuvaları için kullanın.", + "help.sketch.slot.arc_three_point": "Üç noktadan geçen bir yay boyunca, verilen genişlikte eğri bir yuva çizer. Yuvanın yolunun verilen noktalardan geçmesi gerekiyorsa kullanın.", + "help.sketch.slot.center_point": "Verilen genişlikte düz bir yuvayı, merkezinden bir uç yayının merkezine kadar çizer. Bir nokta etrafında ortalanmış yuvalar için kullanın.", + "help.sketch.slot.center_to_center": "Verilen genişlikte düz bir yuvayı, iki uç yayının merkezleri arasında çizer. Merkezden merkeze ölçülendirilen yuvalar, örneğin vida ayar yuvaları için kullanın.", + "help.sketch.slot.overall": "Verilen genişlikte düz bir yuvayı, bir dış ucundan diğerine kadar çizer. Yuvanın toplam uzunluğu önemliyse kullanın.", + "help.sketch.spline.control_point": "Üzerinden geçmediği kontrol noktalarıyla biçimlenen kübik bir spline çizer. Noktaları oynatarak şekillendirdiğiniz pürüzsüz, akıcı eğriler için kullanın.", + "help.sketch.spline.control_point_5": "Kontrol noktalarıyla biçimlenen 5. dereceden bir spline çizer. Eğrilerin daha pürüzsüz bir eğrilikle birleşmesi gereken yerlerde, örneğin görünen stil yüzeylerinde kullanın.", + "help.sketch.spline.fit_point": "Yerleştirdiğiniz her noktadan geçen, açık veya kapalı pürüzsüz bir spline çizer. Bir şekli bilinen noktalardan geçirerek izlemek için kullanın.", + "help.sketch.spline3d": "3B eskiz açıkken, uzayda noktalardan geçen pürüzsüz bir eğri çizer. Eskiz düzleminden çıkan süpürme yolları ve kablo güzergâhları için kullanın.", + "help.sketch.spun_profile": "Bir gövde bir eksen etrafında dönerken taradığı dış hattı eskiz düzleminde oluşturur. Tornalanmış bir parçanın siluetini döndürme veya çizim için elde etmek amacıyla kullanın.", + "help.sketch.text": "Eskize seçilen yazı tipi, yükseklik ve açıyla metin yazar; kelimeleri parametreleri izleyebilir. Etiketler ve yazılar için ekstrüzyon yapın veya kabartın.", + "help.sketch.transform": "Eskiz geometrisini bir merkez noktası etrafında tek adımda ölçekler, döndürür ve taşır. Bir seçimin yerini ve boyutunu aynı anda değiştirmek için kullanın.", + "help.sketch.trim": "Bir eğrinin, tıkladığınız yerin çevresindeki en yakın kesişimler arasında kalan parçasını kaldırır. Üst üste binen çizgileri temizleyip kapalı bir profil elde etmek için kullanın.", "help.solid.align": "Seçili gövdeleri, üzerlerindeki bir nokta, yüz veya düzlem başka bir yerdeki nokta, yüz veya düzlemle buluşacak şekilde taşır. Ofseti ölçmeden bir parçayı diğerinin yanına yerleştirmek için kullanın.", + "help.solid.boundary_fill": "Üst üste binen araç gövdelerinin çevrelediği bölgelerden katılar oluşturur; yalnızca seçtiğiniz bölgeleri doldurur. Bir şekli, birkaç gövdenin birlikte sınırladığı boşluktan oluşturmak için kullanın.", + "help.solid.bounding_solid": "Seçili gövdeleri çevreleyen, isteğe bağlı paylı bir kutu oluşturur. Bir parçanın toplam boyutunu görmek ya da işleneceği ham malzeme olarak ele almak için kullanın.", + "help.solid.box": "Uzunluk, genişlik ve yükseklikten, bir köşe noktasından veya bir noktaya ortalanmış bir kutu oluşturur. Hızlı bir blok, yer tutucu ya da içine özellikler kesilecek bir gövde için kullanın.", "help.solid.chamfer": "Seçili kenarları, belirlediğiniz mesafede düz bir pahla keser. Keskin kenarları kırmak veya bir pim ya da vidanın girişini kolaylaştırmak için kullanın.", + "help.solid.coil": "Çap, tur sayısı, yükseklik veya adım ile yuvarlak ya da kare bir kesitten, yay gibi helezon bir gövde oluşturur. Yaylar, helezonlar ve helezon kabartmalar için kullanın.", "help.solid.combine": "Gövdeleri birleştirir, bir hedef gövdeden çıkarır veya yalnızca paylaştıkları hacmi tutar ve araç gövdelerini tutabilir. Parçaları kaynaştırmak, bir şekli diğeriyle kesmek veya iki gövdenin örtüştüğü yeri bulmak için kullanın.", + "help.solid.cone": "Bir taban dairesi ve bir yükseklikten koni oluşturur; üstün de yarıçapı varsa kesik koni olur. Konik geçişler, huniler, havşalar ve sivri uçlar için kullanın.", + "help.solid.cylinder": "Yarıçap veya çap ile yükseklikten, bir eksen boyunca bir noktanın üzerinde duran bir silindir oluşturur. Miller, pimler, göbekler ve yuvarlak ham parçalar için kullanın.", "help.solid.draft": "Seçili yüzleri, nötr bir düzlemden ölçülen belirlediğiniz açı kadar eğerek koniklik verir. Kalıplanan veya dökülen parçaların kalıptan kolayca çıkması için kullanın.", + "help.solid.emboss": "Metin veya logo gibi eskiz profillerini bir yüzden yukarı kaldırır ya da içine gömer. Düz veya yuvarlak yüzlerdeki yazılar, etiketler ve işaretler için kullanın.", "help.solid.extrude": "Bir eskiz profilini, malzeme ekleyerek veya kaldırarak bir mesafe boyunca 3B'ye taşır. Düz bir konturu blok, kabarıklık veya cep haline getirmek için kullanın.", "help.solid.fillet": "Seçili kenarları, belirlediğiniz yarıçapta pürüzsüz dairesel bir uyumla yuvarlatır. Keskin kenarları sağlamlık, konfor veya görünüm için yumuşatmak amacıyla kullanın.", "help.solid.hole": "Bir yüzeyde seçtiğiniz noktada, belirlediğiniz çapta yuvarlak bir delik deler. Vida boşlukları, pimleri ve diğer basit yuvarlak açıklıklar için kullanın.", @@ -1409,20 +1678,62 @@ "help.solid.move": "Seçili gövdeleri ya da kopyalarını, belirlediğiniz mesafe ve açıyla taşır veya döndürür. Bir gövdenin yerini değiştirmek ya da başka bir yerde ikincisini oluşturmak için kullanın.", "help.solid.offset_face": "Seçili yüzleri belirlediğiniz mesafe kadar içeri veya dışarı iter, çevrelerindeki yüzler de buna uyar. Eskizi düzenlemeden bir duvarı kalınlaştırmak, bir cebi derinleştirmek veya bir çıkıntıyı yükseltmek için kullanın.", "help.solid.pattern.circular": "Seçili nesneleri, belirlediğiniz adet ve toplam açı boyunca bir eksen etrafında yineler. Cıvata daireleri, jant kolları, kanatçıklar ve dişler için kullanın.", + "help.solid.pattern.path": "Özellikleri veya gövdeleri bir eskiz yolu boyunca adet ve aralıkla kopyalar. Eğri bir kenar boyunca delikler veya bir ray boyunca parçalar için kullanın.", "help.solid.pattern.rectangular": "Seçili nesneleri, belirlediğiniz adet ve aralıkla bir veya iki yönde yineler. Delik, nervür, pim veya ayak dizileri ve ızgaraları için kullanın.", + "help.solid.pipe": "Eskiz eğrilerinden oluşan bir yol boyunca, dolu veya et kalınlıklı içi boş yuvarlak bir boru oluşturur. Borular, teller, kablolar ve raylar için kullanın.", "help.solid.press_pull": "Bir yüzü sürüklerken malzeme ekler veya kaldırır, kenarları sürüklerken yuvarlatır. Doğrudan model üzerinde hızlı değişiklikler için kullanın.", "help.solid.remove": "Seçili gövdeleri tasarımdan, zaman çizelgesindeki bu noktadan itibaren çıkarır; önceki adımlar onları korur. Artık gerekmeyen bir kesici araç gibi yardımcı bir gövdeyi atmak için kullanın.", "help.solid.replace_face": "Seçili düz yüzleri bir düzleme veya paralel bir yüze taşır, gövde de onunla buluşmak için büyür veya küçülür. Bir yüzü başka bir parçayla ya da bir yapı düzlemiyle aynı hizaya getirmek için kullanın.", "help.solid.revolve": "Bir eskiz profilini bir eksen etrafında döndürerek yuvarlak bir katı oluşturur. Miller, topuzlar, kaseler ve bir merkez çizgisi etrafında yuvarlak olan parçalar için kullanın.", + "help.solid.rib": "Açık bir eskiz eğrisi boyunca, gövdenin bir sonraki yüzlerine kadar uzanan ince bir cidar ekler. Cidarları ve köşeleri sağlamlaştırmak için, örneğin kalıplanmış veya basılmış parçalarda kullanın.", "help.solid.scale": "Seçili gövdeleri bir çarpanla büyütür veya küçültür; her yönde aynı ya da eksen başına ayrı olabilir. İçe aktarılan bir şekli yeniden boyutlandırmak veya büzülme payı bırakmak için kullanın.", "help.solid.shell": "Bir katıyı içini oyarak boşaltır, belirlediğiniz kalınlıkta duvarlar bırakır ve seçtiğiniz yüzleri açabilir. Kutular, kapaklar ve diğer ince cidarlı parçalar için kullanın.", + "help.solid.sphere": "Bir merkez noktası etrafında, yarıçap veya çaptan bir küre oluşturur. Toplar, topuzlar ve yuvarlatılmış uçlar için kullanın.", "help.solid.split_body": "Bir gövdeyi bir düzlemle, başka bir gövdenin yüzüyle veya bir eskiz çizgisiyle ayrı gövdelere keser. Ayrı ayrı basılan, işlenen veya renklendirilen parçalar elde etmek için kullanın.", "help.solid.split_face": "Seçili yüzleri, gövdeyi kesmeden bir düzlem, başka bir gövdenin yüzü veya eskiz eğrileri boyunca böler. Bir yüzün bir kısmına kendi koniklik, renk veya ofsetini vermek için kullanın.", "help.solid.sweep": "Bir eskiz profilini bir yol boyunca sürükleyerek katı oluşturur. Borular, raylar, saplar ve bir eğriyi izleyen sabit kesitli parçalar için kullanın.", + "help.solid.thread": "Silindirik bir yüze, kozmetik diş olarak ya da gövdeye kesilmiş olarak bir ISO metrik diş ekler. Cıvatalar, dişli delikler ve basılmış vida parçaları için kullanın.", + "help.solid.torus": "Ekseni etrafındaki bir büyük yarıçap ve yuvarlak kesiti için bir küçük yarıçaptan halka oluşturur. O-ringler, saplar ve yuvarlak boncuklar için kullanın.", + "help.solid.web": "Her açık eskiz eğrisi boyunca, her biri gövdenin bir sonraki yüzlerine kadar uzanan ince bir cidar ekler. Kasaların ve tepsilerin içindeki destek cidarlarından oluşan bir ızgara için kullanın.", + "help.surface.blend": "İki gövdenin kenarları arasında köprü kuran, ikisine de teğet veya eğrilik sürekli bir yüzey oluşturur. İki yüzeyi bir boşluk boyunca pürüzsüzce birleştirmek için kullanın.", + "help.surface.boundary": "İki ila dört eskiz eğrisinden oluşan bir döngüyü veya bir eğri ağını dolduran bir yüzey oluşturur. Kenarlarıyla tanımlanan serbest biçimli paneller için kullanın.", + "help.surface.extend": "Bir yüzeyi kenarlarının ötesine, bir mesafe kadar ya da bir düzleme veya yüze kadar uzatır. Yüzeyleri kırpmadan veya dikmeden önce üst üste bindirmek için kullanın.", + "help.surface.extrude": "Eskiz eğrilerini veya profillerini bir mesafe boyunca iterek kapaksız, yalnızca cidarlardan oluşan bir yüzey elde eder. İnce cidarlar ile kesme veya bölme araçları için kullanın.", + "help.surface.fair": "Serbest biçimli yüzlerin içini düzgünleştirir; kenarları yerinde kalır. Bir yüzeydeki çıkıntıları ve dalgalı yansımaları gidermek için kullanın.", + "help.surface.loft": "İki veya daha fazla kesitten sırayla geçen, kapaksız bir yüzey oluşturur. Kabuklar ve farklı şekiller arasındaki geçişler için kullanın.", + "help.surface.match": "Bir yüzeyin kenarını, başka bir gövdenin kenarıyla teğet veya eğrilik uyumuyla buluşacak şekilde yeniden kurar. İki yüzey arasındaki bir birleşim yerini pürüzsüzce kapatmak için kullanın.", + "help.surface.offset": "Yüzlerin kopyasını, normalleri boyunca bir mesafede yeni bir yüzey gövdesi olarak oluşturur. Kaplamalar, açıklıklar veya bir cidarın öbür yüzü için kullanın.", + "help.surface.patch": "Bir eskiz bölgesini veya kapalı bir kenar döngüsünü, düz ya da pürüzsüzce eğri bir yüzle doldurur. Bir yüzey gövdesindeki delikleri kapatmak için kullanın.", + "help.surface.reverse_normal": "Bir yüzey gövdesinin yüzlerini ters çevirir; böylece dış tarafları diğer yöne bakar. Yüzler içe bakıyorsa kalınlaştırmadan veya dikmeden önce kullanın.", + "help.surface.revolve": "Eskiz eğrilerini veya profillerini bir eksen etrafında döndürerek kapaksız bir yüzey elde eder. Abajurlar, kaseler ve nozullar gibi yuvarlak kabuklar için kullanın.", + "help.surface.ruled": "Bir kenar zincirinden, yüzün normali veya teğeti boyunca ya da bir açıyla çıkan düz çizgilerden oluşan bir şerit oluşturur. Koniklikli cidarlar, taşma yüzeyleri ve ayrım yüzeyleri için kullanın.", + "help.surface.stitch": "Yüzey gövdelerini ortak kenarları boyunca birbirine diker; kapandıklarında katı olur. Bir yüzey kümesini tek bir gövdeye dönüştürmek için kullanın.", + "help.surface.sweep": "Eskiz eğrilerini veya profillerini bir yol boyunca hareket ettirerek kapaksız bir yüzey oluşturur. Oluklar, çıtalar ve bir yolu izleyen diğer ince şekiller için kullanın.", + "help.surface.thicken": "Bir yüzey gövdesine kalınlık vererek onu katıya dönüştürür. Yüzeylerden basılabilir veya işlenebilir parçalar elde etmek için kullanın.", + "help.surface.trim": "Bir yüzeyi bir düzlemle, başka bir yüzeyle veya eskiz eğrileriyle keser ve seçtiğiniz tarafı tutar. Yüzeyleri dikmeden önce şekle kesmek için kullanın.", + "help.surface.unstitch": "Bir gövdenin yüzlerini kendi yüzey gövdelerine ayırır; bir katı yüzeylere dağılır. Bir gövdenin tek tek yüzlerini yeniden işlemek için kullanın.", + "help.surface.untrim": "Bir yüzdeki delikleri kaldırır ya da dış sınırını yüzeyin doğal sınırlarına geri getirir. Kırpmadan sonra yüzeyin tamamını geri almak için kullanın.", "help.third_party": "Üçüncü taraf lisansları", "help.timeline.compute_all": "Zaman çizelgesindeki her özelliği baştan yeniden oluşturur. Modeli tazelemek ve hangi özelliklerin başarısız olduğunu görmek için kullanın.", "help.timeline.delete": "Seçili özellikleri zaman çizelgesinden siler; bir eskizi silmek ondan oluşturulan özellikleri de siler. Artık istenmeyen bir adımı kaldırmak için kullanın.", + "help.timeline.dependents": "Bir özellikle birlikte silinecek özellikleri ve onsuz başarısız olacak özellikleri listeler. Bir özelliği silmeden veya değiştirmeden önce kullanın.", "help.timeline.play": "Kalan özellikleri, her yeniden hesaplamadan sonra yarım saniye bekleyerek tek tek yeniden oynatır. Durdurmak için bu komutu yeniden çalıştırın veya Esc tuşuna basın; Sona git hemen atlar.", + "help.view.apply": "Görünümü ön, üst veya izometrik gibi standart bir yöne ya da kayıtlı adlandırılmış bir görünüme çevirir. Modele sabit bir açıdan bakmak için kullanın.", + "help.view.delete": "Kayıtlı bir adlandırılmış görünümü siler. Model değişmez.", + "help.view.fit": "Tüm modelin veya seçimin görünümü doldurması için yakınlaştırır ve kaydırır. Model görüş alanından çıktığında kullanın.", + "help.view.grid": "Görünüm alanındaki ızgarayı gösterir veya gizler. Modelleme sırasında boyut ve yön kılavuzu olarak kullanın.", + "help.view.ground_shadow": "Modelin zemindeki gölgesini gösterir veya gizler. Yüksekliği ve konumu daha kolay değerlendirmek için kullanın.", + "help.view.home": "Görünümü ana yöne geri çevirir ve modeli sığdırır. Bilinen bir görünüme hızla dönmek için kullanın.", + "help.view.list": "Tasarımda kayıtlı adlandırılmış görünümleri listeler. Daha önce kaydettiğiniz bir görünümü bulmak için kullanın.", + "help.view.navigate": "Görünümü adımlarla, örneğin sola çeyrek tur, döndürür, kaydırır veya yakınlaştırır. Kamerayı sürüklemek yerine hassas biçimde hareket ettirmek için kullanın.", + "help.view.navigation_bar": "Görünüm alanının altındaki gezinme çubuğunu gösterir veya gizler. Daha fazla yer için gizleyin, görünüm araçlarına fareyle ulaşmak için gösterin.", + "help.view.rename": "Kayıtlı bir adlandırılmış görünüme yeni bir ad verir. Görünümün kendisi aynı kalır.", + "help.view.save": "Geçerli kamera konumunu tasarımda adlandırılmış bir görünüm olarak kaydeder. Daha sonra aynı açıya, örneğin ekran görüntüleri için, dönmek amacıyla kullanın.", + "help.view.spin": "Görünümü, bir sonraki tıklamaya veya tuşa kadar modelin etrafında sürekli döndürür. Bir modeli her yönden sunmak için kullanın.", + "help.view.tool": "Döndürme, kaydırma veya yakınlaştırma gibi bir kamera aracını sabitler; böylece siz kapatana kadar sol fare tuşuyla sürüklemek görünümü hareket ettirir. Trackpad'de veya orta fare tuşu olmadan kullanın.", + "help.view.visual_style": "Modelin nasıl çizileceğini değiştirir: kenarlı ya da kenarsız gölgeli, tel kafes veya gizli kenarlı. İçini görmek için tel kafes, temiz bir görünüm için gölgeli kullanın.", + "history.sketch_under_constrained": "Eksik kısıtlanmış ({count} serbestlik derecesi)", + "history.sketch_under_constrained_one": "Eksik kısıtlanmış ({count} serbestlik derecesi)", "hole_presets.confirm_delete": "Silmeyi onayla", "hole_presets.delete": "Sil", "hole_presets.delete_prompt": "Bu kişisel ön ayar silinsin mi? Mevcut delikler değişmez.", @@ -1526,6 +1837,8 @@ "joint_move.blocked_hint": "Eklem türünü (ör. Sabit), parçanın sabitlenme durumunu, eklem sınırlarını ve parametreyle belirlenen değerleri kontrol edin.", "joint_move.blocked_title": "Bu parça taşınamıyor", "joint_move.coarse": "Eksene yakın dönüş adımı (°)", + "joint_move.conflict": "Bu parçanın bir bağlantısı diğerleriyle çakışıyor: {joint}.", + "joint_move.conflict_hint": "Diğer bağlantılar parçayı yerleştirebilsin diye çakışan bağlantıyı düzenleyin, bastırın veya silin.", "joint_move.distance": "Başlangıçtan itibaren mesafe", "joint_move.done": "Tamam", "joint_move.fine": "Eksenden uzak dönüş adımı (°)", @@ -1597,6 +1910,10 @@ "material.selection.mixed": "Farklı malzemeler", "measure.at": "Konum", "measure.item": "Öğe {number}", + "measure.quick_copied": "Ölçüm kopyalandı", + "measure.quick_copy": "Ölçümü kopyalamak için tıklayın", + "measure.quick_edges": "{count} kenar", + "measure.quick_faces": "{count} yüz", "messages.ago_h": "{n} sa. önce", "messages.ago_min": "{n} dk. önce", "messages.ago_s": "{n} sn. önce", @@ -1621,6 +1938,8 @@ "motion.track_name": "İz {number}", "nav.alias.help": "Shift+Alt+sol sürükleme döndürür, Shift+Alt+orta kaydırır, Shift+Alt+sağ yakınlaştırır; orta sürükleme ayrıca kaydırır, sağ sürükleme döndürür", "nav.blender.help": "Orta sürükleme döndürür, Shift+orta kaydırır, Ctrl+orta yakınlaştırır; sağ sürükleme kameraya dokunmaz", + "nav.creo.help": "Orta sürükleme döndürür, Shift+orta kaydırır, Ctrl+orta dikey sürükleme yakınlaştırır (yakınlaştırmak için aşağı); tekerleği kaydırarak da yakınlaştırabilirsiniz", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Fare ve 3B fare, her iki kutuptan geçerek döndürür ve yuvarlanmayı korur. Shift eksen hizalama devre dışı.", "nav.free_orbit.label": "Serbest döndürme", "nav.free_orbit.snap_help": "Fare ve 3B fare, her iki kutuptan geçerek döndürür ve yuvarlanmayı korur. Görünüm yönünü ve yuvarlanmayı hizalamak için döndürme sürüklemesi sırasında Shift tuşunu basılı tutun.", @@ -1630,6 +1949,7 @@ "nav.hfss.help": "Alt+sol sürükleme kaydırır, Shift+Alt+sol yakınlaştırır, boş alanda Ctrl+sol sürükleme döndürür", "nav.inventor.help": "Orta sürükleme kaydırır, Shift+orta döndürür, Ctrl+orta yakınlaştırır, sağ sürükleme döndürür", "nav.maya.help": "Alt+sol sürükleme döndürür, Alt+orta kaydırır, Alt+sağ yakınlaştırır; orta sürükleme ayrıca kaydırır", + "nav.nx.help": "Orta sürükleme döndürür, Shift+orta kaydırır (NX'te orta + sağ), Ctrl+orta yakınlaştırır (NX'te orta + sol); sağ sürükleme kameraya dokunmaz", "nav.openscad.help": "Boşlukta sol sürükleme döndürür, Shift+sol sürükleme kutu seçimi yapar, eskiz geometrisi sürükleyerek düzenlenir; sağ veya orta sürükleme kaydırır, Shift+sağ veya Shift+orta sürükleme yakınlaştırır", "nav.perspective.sketch": "Eskiz düzenleme dik görünüm kullanır. Perspektife geçmek için eskizi bitirin.", "nav.right_drag_orbits.help": "Kapalı: sağ sürükleme kameraya dokunmaz ve sağ tuş yalnızca bağlam menüsünü açar. SolidWorks fare eşlemesini seçmek bunu kapatır.", @@ -1749,6 +2069,11 @@ "not a move": "bir taşıma değil", "not a number": "bir sayı değil", "open a sketch first": "önce bir eskiz açın", + "parameters.apply_live": "Her değişikliği alanından çıkarken uygula", + "parameters.apply_live_tip": "Kapalıyken: değişiklikler Uygula veya Tamam'a kadar bekler, ardından tasarım hepsi için bir kez yeniden oluşturulur. İptal veya Esc onları atar.", + "parameters.held": "Uygula'yı bekleyen {count} değişiklik", + "parameters.held_hint": "İfadeleri ve birimleri düzenleyin. Değişiklikler Uygula veya Tamam'a kadar bekler.", + "parameters.held_one": "Uygula'yı bekleyen 1 değişiklik", "parts.automatic_name": "otomatik", "parts.dimension.across_flats": "Anahtar ağzı", "parts.dimension.bore": "Delik çapı", @@ -1767,10 +2092,19 @@ "parts.family.button_head_cap_screw": "Mercimek başlı alyan cıvata", "parts.family.dowel_pin": "Silindirik pim (paralel)", "parts.family.hex_bolt": "Altıgen başlı cıvata / vida", + "parts.family.hex_cap_screw_inch": "Altıgen başlı cıvata (inç)", "parts.family.hex_nut": "Altıgen somun", + "parts.family.hex_nut_inch": "Altıgen somun (inç)", "parts.family.set_screw": "Alyan tespit vidası, düz uçlu", "parts.family.socket_head_cap_screw": "Alyan başlı cıvata", "parts.family.washer": "Düz rondela", + "parts.family.washer_sae": "Düz rondela, SAE (dar)", + "parts.family.washer_uss": "Düz rondela, USS (geniş)", + "parts.holes": "Delikler (isteğe bağlı)", + "parts.placement_hint": "her birine bir parça yerleştirmek için bir veya daha fazla delik seçin ya da OK ile orijine yerleştirin", + "parts.system": "Birim sistemi", + "parts.system.inch": "İnç", + "parts.system.metric": "Metrik", "pattern.alignment_2": "Hizalama 2", "pattern.alignment_hint": "Adet, orijinali içerir. Ortala, kopyaları iki yana dağıtır; çift adetlerde yönü ters çevirme, fazladan kopyanın hangi tarafta olacağını belirler.", "pattern.direction_1": "Yön 1", @@ -1823,6 +2157,8 @@ "prefs.bottom_centre": "Alt orta", "prefs.bottom_right": "Sağ alt", "prefs.browser": "Tarayıcı", + "prefs.browser_eye_left": "Göz, daraltma okunun yanında", + "prefs.browser_eye_left_note": "Tarayıcı satırları göster/gizle gözünü, satırların sağ ucundaki bir sütun yerine eskiden olduğu gibi daraltma okunun yanında gösterir.", "prefs.browser_reveal_on_hover": "Üzerine gelince göster", "prefs.browser_show_note": "Görünür, tarayıcıyı ekranda tutar. Üzerine gelince göster, imleç onun yerine veya sol kenarındaki ince sekmeye gelene kadar onu gizli tutar; imleç içindeyken veya ondan açılan bir menü açıkken açık kalır.", "prefs.browser_shown": "Görünür", @@ -1830,6 +2166,8 @@ "prefs.button_left": "Sol sürükleme", "prefs.button_middle": "Orta sürükleme", "prefs.button_right": "Sağ sürükleme", + "prefs.carousel_next": "Sonraki", + "prefs.carousel_previous": "Önceki", "prefs.choose_font": "Yazı tipi dosyası seçin…", "prefs.click": "Tıklama", "prefs.contact_shading": "Yumuşak temas gölgelemesi", @@ -1842,6 +2180,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Eğri yüzeyler", "prefs.curves": "Eğri yüzeyler", + "prefs.cut_preview_tint": "Kaldırılan malzemeyi kırmızı göster", + "prefs.cut_preview_tint_help": "Önizleme, bir özelliğin kaldırdığı malzemeyi ve yerine geçtiği şekli kırmızı, yarı saydam bir hayaletle doldurur. Kapalıyken bu dolgular tamamen saydamdır ve yalnızca dış hatları çizilir.", + "prefs.dark_parts_shading": "Koyu parçaların biçimini koru", + "prefs.dark_parts_shading_help": "Görünümü doğrusal ışıkta, yumuşak bir gökyüzü dolgusuyla gölgele; böylece koyu yüzler siyaha dönmek yerine degradelerini korur", "prefs.dead_zone_note": "Taramalı bant ölü bölgedir: içindeki hareket yok sayılır.", "prefs.default": "varsayılan", "prefs.design": "Tasarım varsayılanları", @@ -1856,6 +2198,8 @@ "prefs.edges": "Kenarlar ve gölgeleme", "prefs.extend": "Uzat", "prefs.extra_navigation": "Boşlukta Ctrl+sol sürükleme döndürür; kaydırmak için Space tuşunu basılı tutun.", + "prefs.extrude_view_isometric": "Ekstrüzyon açıldığında görünümü izometriğe çevir", + "prefs.extrude_view_return": "Ekstrüzyon kapandığında önceki görünüme dön", "prefs.follows_os": "İşletim sistemini izler", "prefs.font": "Yazı tipi", "prefs.font_fallback": "Seçilen yazı tipinde bulunmayan glifler yerleşik yazı tipine düşer, böylece hiçbir etiket boş kutu göstermez.", @@ -1871,8 +2215,11 @@ "prefs.graphics_card_auto": "Otomatik", "prefs.graphics_card_missing": "Kaydedilen ekran kartı kullanılamıyor; Otomatik kullanılıyor.", "prefs.graphics_card_restart": "SolidCraft'ı yeniden başlattıktan sonra etkili olur. WGPU_ADAPTER_NAME bu seçimi geçersiz kılar.", + "prefs.graphics_card_unused": "Kaydedilen ekran kartı bu pencere için kullanılmadı; kullanılan kart Yardım › SolidCraft hakkında içinde ve durum çubuğunda gösterilir. Otomatik seçeneğini deneyin veya WGPU_ADAPTER_NAME değerini kart adının benzersiz bir bölümüne ayarlayın.", "prefs.graphics_note": "Hızdan ödün verip pürüzsüzlük kazanın. Her seçenek, etkisini bir örnek üzerinde gösterir.", "prefs.graphics_presets_note": "Ön ayarlar aşağıdaki seçimleri birlikte belirler.", + "prefs.hide_constraint_glyphs_zoomed_out": "Uzaklaşıldığında kısıtlama simgelerini gizle", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Eskiz, kalabalık yaratacak kadar uzaklaştırıldığında kısıtlama simgeleri görünümden çıkar. Kapalıyken: her yakınlaştırma düzeyinde sabit ekran boyutunda kalırlar.", "prefs.history": "Geçmiş", "prefs.history_origin_bodies": "Başlangıç ve gövdeleri üstte göster", "prefs.history_origin_bodies_note": "Soldaki veya tarayıcının altındaki Geçmiş, etkin bileşenin Gövdeler klasörü ve Başlangıç ile başlar; gözleri ve menüleri tarayıcıdaki gibidir. Alttaki Geçmiş değişmez.", @@ -1883,6 +2230,8 @@ "prefs.history_sketches_note": "Eskizler, Özelliklerinin altında ayarlıyken, soldaki Geçmiş, adlar için yeterince geniş olduğunda her eskizi, kendisinden oluşturulan ilk özelliğin altında bir seviye içeride listeler. Alttaki zaman çizelgesi her zaman oluşturma sırasını korur.", "prefs.history_sketches_under_feature": "Özelliklerinin altında", "prefs.hold_stop_snapping": "Yapışmayı durdurmak için basılı tutun", + "prefs.home_fit_size": "Ana görünüm ve Sığdır boyutu", + "prefs.home_fit_size_note": "Ana görünüm, Sığdır, açılan bir tasarım veya bir gezgin görünümü değişikliği modeli çerçevelediğinde modelin görünümün ne kadarını doldurduğu; aşağıdaki ayar açık olsa da olmasa da geçerlidir. %100: paneller, pusula ve gezinme çubuğu arasındaki görünümü doldurur.", "prefs.icons_only": "Yalnızca simgeler", "prefs.imported_file": "İçe aktarılan dosya", "prefs.in_browser": "Tarayıcının içinde", @@ -1891,13 +2240,22 @@ "prefs.interface_language": "Arayüz dili", "prefs.interface_note": "SolidCraft'ın nasıl göründüğü ve parçalarının nerede durduğu.", "prefs.interval_minutes": "{n} dk", + "prefs.invert_curved_roll_arrows": "Eğri yuvarlanma oklarını ters çevir", + "prefs.invert_curved_roll_arrows_note": "Küpün köşesindeki iki eğri ok, görünümü ekran düzlemi içinde yuvarlar. Açık: saat yönündeki ok saat yönünün tersine, saat yönünün tersindeki ok saat yönünde yuvarlar. Kapalı: her ok görünümü kıvrıldığı yöne yuvarlar.", + "prefs.invert_navigator_arrows": "Görünüm küpünün döndürme oklarını ters çevir", + "prefs.invert_navigator_arrows_note": "Küpün çevresindeki oklar kamerayı gösterdikleri yönde döndürür, tıpkı Fusion ve Inventor'daki gibi: soldaki ok sağı gösterir ve kamerayı sağa savurur. Kapalı: bir ok küpü bulunduğu tarafa doğru döndürür, yani sol ok kamerayı sola savurur. Kıvrık yuvarlanma okları bundan etkilenmez.", + "prefs.keep_work_on_tab_switch": "Tasarımlar arasında geçerken diyalogları ve araçları açık tut", + "prefs.keep_work_on_tab_switch_note": "Her tasarım sekmesi, açık diyaloğunu veya aracını, içinde seçtiklerinizi ve yazdıklarınızı ve şerit sekmesini korur. Tasarıma döndüğünüzde yeniden oradadırlar. Kapalı: tasarımlar arasında geçmek bunları iptal eder ve Model sekmesini gösterir.", "prefs.labels": "Etiketler", + "prefs.language_system": "Sistem", "prefs.layout": "Düzen", "prefs.layout_note": "Sıkışık, panelleri pencere kenarlarına yerleştirir. Tarayıcı yarı saydamlığı Yüzen düzende kullanılabilir. Asistan tarafını Asistan sayfasından değiştirin.", "prefs.left": "Sol", "prefs.left_click": "Sol tıklama", "prefs.line_drag_draws_one": "Basıp sürüklemek tek çizgi çizer", "prefs.line_drag_draws_one_note": "Çizgi aracında basmak, sürüklemek ve bırakmak, basılan yerden bırakılan yere tek bir çizgi çizer ve çizim orada biter. Tıklamalar yine bir zincir çizer. Kapalı: sürükleme, tıklama gibi, bırakıldığı yere bir nokta koyar.", + "prefs.line_hover_tangent_arc": "Teğet yaya geçmek için bir çizginin son noktasında bekle", + "prefs.line_hover_tangent_arc_note": "Çizgi aracında bir çizgi parçası çizildikten sonra zincirin son noktasından uzaklaşın, geri gelin ve imleci üzerinde sabit tutun: sonraki tıklama bir teğet yayı bitirir, aynı hareket çizgilere geri döner. Kapalı: orada beklemek hiçbir şey yapmaz.", "prefs.linked_designs": "Bağlı tasarımlar", "prefs.live_input": "Canlı girdi", "prefs.live_preview": "Canlı önizleme", @@ -1911,6 +2269,9 @@ "prefs.max_file_size_step": "STEP ve içe aktarma dosyaları", "prefs.max_file_size_web": "Web uygulaması 512 MB’a kadar STEP ve içe aktarma dosyalarını, 256 MB’a kadar tasarımları açar: tarayıcı sekmesi daha büyük dosyaları barındıramaz. Masaüstü uygulamasında bu sınırlar artırılabilir.", "prefs.megabytes": "MB", + "prefs.menu_grid": "Büyük simgeler", + "prefs.menu_list": "Liste", + "prefs.menus": "Menüler", "prefs.minutes": "dakika", "prefs.minutes_suffix": " min", "prefs.mouse": "Fare ve trackpad", @@ -1918,6 +2279,8 @@ "prefs.mouse_mapping": "Fare eşlemesi", "prefs.navigation": "Gezinme", "prefs.navigation_note": "Farenin, trackpad'in ve 3B farenin görünümü nasıl hareket ettirdiği.", + "prefs.navigator_fit": "Gezgin görünümü değiştikten sonra modeli sığdır", + "prefs.navigator_fit_note": "Görünüm küpünün bir yüzü, köşesi veya oku ya da gizmonun bir ekseni, modelin ortasına da modeli her yönden sığdıran tek bir uzaklıktan (sınırlayıcı küresi) bakar. Bu açıkken Ana görünüm aynı yakınlaştırmayı ve merkezi kullanır; böylece sonrasında seçilen görünümler yalnızca döner. Kapalı: görünüm hedefini ve yakınlaştırmasını koruyarak yerinde döner.", "prefs.network_host_remove": "Kaldır", "prefs.network_locations": "Tasarımlarda ağ konumlarına izin ver", "prefs.network_locations_note": "Kapalı: bir tasarımın başka bir bilgisayardaki bağlı dosyaları (\\\\server\\paylaşım) yalnızca burada listelenen sunuculardan veya sorulduğunda izin verdiklerinizden açılır.", @@ -1930,10 +2293,18 @@ "prefs.origin_plane_names": "Orijin düzlemi adları", "prefs.origin_plane_names_note": "Tarayıcıda, diyaloglarda ve listelerde gösterilen adlar. Z yukarı olmak üzere {top} XY, {front} XZ ve {right} YZ'dir. Komutlar, betikler ve kayıtlı tasarımlar XY, XZ ve YZ adlarını korur.", "prefs.overall_speed": "Genel hız", + "prefs.parameter_list_rows": "Parametre listesi satırları", + "prefs.parameter_list_rows_tip": "Boş bir değer alanında Aşağı ok, parametreleri sık kullanılanlar önce olacak şekilde en fazla bu kadar satır listeler. Daha azı, büyük bir tasarımda listeyi hafif tutar.", + "prefs.persistent_ribbon_pressed": "Etkin şerit komutlarını vurgula", + "prefs.persistent_ribbon_pressed_help": "Şerit komutlarını, etkileri açık olduğu sürece vurgula. Önceki nötr görünümü ve komut yardımını korumak için kapatın.", "prefs.perspective_fov": "Görüş alanı", "prefs.placement": "Yerleşim", "prefs.prefer_free_sketch_points": "Noktalar örtüştüğünde hareketli eskiz noktalarını tercih et", "prefs.preview_choices": "Seçimlerinizin önizlemesi", + "prefs.preview_tint_new_faces": "Önizlemede yeni yüzeyi renklendir", + "prefs.preview_tint_new_faces_help": "Bir gövdeyi değiştiren özelliğin önizlemesi, eklediği yüzeyi önizleme renginde çizebilir. Kapalıyken gövde olduğu gibi çizilir.", + "prefs.print_face_highlight": "Baskı yüzeyi vurgusu", + "prefs.print_face_highlight_tip": "Bir gövdenin baskı yüzeyinin görünümde ne kadar güçlü renklendirilip çerçeveleneceği. %0 vurgu göstermez.", "prefs.profile_active": "Etkin profil", "prefs.profile_applied": "Profil uygulandı.", "prefs.profile_changed": "Profil kaydedildikten sonra ayarlar değişti. Kaydet, onları profilde saklar.", @@ -1955,9 +2326,13 @@ "prefs.quality_fastest": "en hızlı", "prefs.quality_slowest": "en yavaş", "prefs.quality_smoother": "daha pürüzsüz", + "prefs.quick_measure": "Görünümün köşesinde hızlı ölçüm", + "prefs.quick_measure_note": "Seçimin boyutu, görünümün sağ alt köşesinde: bir kenarın uzunluğu (yuvarlaksa Ø ve R), bir yüzün alanı, bir noktanın konumu, iki öğenin mesafesi ve açısı, birkaç kenarın veya yüzün toplamı. Tıklamak onu kopyalar.", "prefs.render_previous_geometry_budget": "Önceki Render önizleme geometri bütçesini kullan", "prefs.render_previous_geometry_budget_help": "Cihaza dayalı bütçe yerine önceki sabit geometri sınırını (64 bit masaüstünde 512 MiB, diğer yerlerde 128 MiB) geri getirir.", "prefs.reports_saved": "{n} kayıtlı", + "prefs.ribbon_click_ends_tool": "Çalışan aracın düğmesine tıklamak onu bitirir", + "prefs.ribbon_click_ends_tool_note": "Kullanımdaki eskiz aracının yanan şerit düğmesine tıklamak aracı bitirir; böylece görünümdeki tıklamalar yeniden seçim yapar. Kapalı: tıklama aracı yeniden başlatır.", "prefs.ribbon_reveal": "Arama sonuçlarını şeritte göster", "prefs.ribbon_reveal_note": "Komutlarda ara içindeki bir sonucun üzerine gelmek, komutun şeritte nerede olduğunu gösterir: sekmesini, düğmesini veya bir panelin açılır menüsündeki satırını. Aramadan başlatılan bir komut orada yanıp söner ve bir açılır menüden çalışan bir komut panelini işaretler.", "prefs.right_click": "Sağ tıklama", @@ -1968,6 +2343,8 @@ "prefs.search_empty": "Eşleşen ayar yok", "prefs.select": "Seçim", "prefs.select_one_item": "Bir öğe seçin", + "prefs.select_other_hidden": "Gizli geometriyi Diğerini seç ile seç", + "prefs.select_other_hidden_help": "Açıkken: imlecin yakınındaki gizli gövdeleri, eskizleri ve örtülü kenarları da dahil eder. Kapalıyken: imlecin altındaki görünür geometrinin özgün listesini kullanır.", "prefs.selecting": "Seçme", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift yalnızca ekler; Ctrl / Cmd değiştirir", @@ -1979,31 +2356,63 @@ "prefs.sketch_align_points_note": "Çizim sırasında bir nokta, noktalı bir kılavuzla aynı anda bir eskiz noktasıyla yatay, bir diğeriyle dikey olarak hizalanır ve tıklama her iki hizalamayı da korur. Kapalı: yalnızca önceki noktayla, her seferinde tek eksende.", "prefs.sketch_conflict_colour": "Çakışan geometri çakışma renginde", "prefs.sketch_conflict_colour_note": "Bir eskizin kısıtlamaları çakışırken, başarısız olan kısıtlamanın tuttuğu eğriler ve noktalar yalnızca simgesi veya ölçüsü değil, çakışma renginde de çizilir. Kapalıyken olağan renklerini korurlar.", + "prefs.sketch_construction_lines": "Genişletilmiş yardımcı doğru araçları", "prefs.sketch_exit_view": "Bir eskiz bittiğinde", "prefs.sketch_exit_view.keep": "Geçerli görünümü koru", "prefs.sketch_exit_view.previous": "Önceki görünüme dön", "prefs.sketch_exit_view.unless_rotated": "Döndürülmediyse dön", "prefs.sketch_exit_view_note": "Eskizi Bitir, İptal veya çift Esc sonrası görünümün nereye gittiği.", + "prefs.sketch_face_activates_part": "Bir parçanın yüzüne eskiz çizmek o parçayı etkin yapar", + "prefs.sketch_face_activates_part_note": "Başka bir bileşenin gövdesinin yüzünde başlatılan eskiz, önce o bileşeni etkinleştirir; böylece eskiz ona ait olur ve tarayıcıda o parçayla birlikte kalır. Parça sonrasında da etkin kalır. Kapalı: eskiz etkin bileşene ait olur.", + "prefs.sketch_open_look_at": "Eskiz açıldığında görünümü ona doğru döndür", + "prefs.sketch_open_look_at_note": "Kapalı: eskiz oluşturmak veya düzenlemek görünümü olduğu gibi bırakır. Bak komutu, istediğinizde görünümü eskize çevirir.", "prefs.sketch_recent_snap": "Son merkezlere ve orta noktalara otomatik yapış", "prefs.sketch_recent_snap_note": "Çizim sırasında imleç, son iki daire merkezi veya düz kenar orta noktasından gelen kılavuzların kesiştiği yere yapışır. Kapalıyken bu kılavuzlar yalnızca görsel kalır ve imleç hareket etmez.", "prefs.sketch_selection": "Eskiz ve seçim", "prefs.sketch_selection_heading": "Eskiz ve seçim", "prefs.sketch_selection_note": "Eskizlerin nasıl yapıştığı ve tıklamaların nasıl seçtiği.", + "prefs.sketch_state_icons": "Eskiz simgeleri durumlarının renginde", + "prefs.sketch_state_icons_note": "Geçmiş'te ve tarayıcıda bir eskizin simgesi durumunun rengini alır (eksik kısıtlanmış, tam kısıtlı veya çakışan) ve araç ipucu durumu belirtir. Kapalıyken: her eskizin simgesi aynıdır.", "prefs.sketch_tab_always": "Eskiz sekmesini hep göster", "prefs.sketch_tab_always_note": "Hiçbir eskiz açık değilken Eskiz sekmesi şeritte, Model’den hemen sonra kalır. Çizim araçları bu durumda seçili düzlemde veya yüzde ya da bir sonra seçtiğiniz düzlemde, araç hazır olarak bir eskiz başlatır.", "prefs.sketch_tracking_guides": "Merkez ve orta nokta hizalama kılavuzları", "prefs.sketch_tracking_guides_note": "Bir dairenin merkezinin veya düz bir kenarın orta noktasının üzerine gelin, ardından geçici noktalı bir kılavuz görmek için yatay veya dikey hareket ettirin.", + "prefs.sketch_tracking_points": "Çizim sırasında uç noktalardan ve köşelerden hizalama kılavuzları", + "prefs.sketch_tracking_points_note": "Bir çizim aracı bir nokta beklerken, bir çizgi veya yay ucunun, bir dikdörtgen köşesinin ya da serbest bir noktanın üzerine gelmek, bir merkez veya orta noktadaki gibi geçici noktalı kılavuzu gösterir. Kapalıyken: yalnızca merkezler ve orta noktalar.", "prefs.sketching": "Eskiz", "prefs.snap_drawing_note": "Bir eskiz noktası çizerken veya sürüklerken.", "prefs.source": "Kaynak", "prefs.speed": "Hız", "prefs.stand_up_note": "Bir STEP veya IGES dosyası Z yukarı açıldığında, X etrafında çeyrek tur öner.", + "prefs.stand_up_unknown": "Bilinmeyen programlardan gelen dosyalar için", + "prefs.stand_up_unknown.ask": "Diyalogda sor", + "prefs.stand_up_unknown.note": "Not göster", + "prefs.stand_up_unknown.off": "Önerme", + "prefs.stand_up_unknown_note": "Dosyanın başlığı, Y yukarı olarak kaydettiği bilinen bir program belirtmediğinde önerinin nasıl sunulacağı. Not yalnızca dosya sırtüstü yatıyor gibi göründüğünde gösterilir; Diyalogda sor, daha önce olduğu gibi böyle her dosya için sorar.", "prefs.status_bar": "Durum çubuğu", "prefs.status_bar_note": "Pencerenin alt kenarındaki ince bir çubuk, nelerin düzenlendiğini, açık eskizin durumunu rengiyle ve tasarımın birimlerini gösterir; birimlere tıklamak onları değiştirir. Bu durumda eskizin durumu artık görünümün köşesinde gösterilmez.", "prefs.status_done": "Tamam", "prefs.status_error": "Hata", "prefs.status_selected": "Seçildi", "prefs.status_warning": "Uyarı", + "prefs.structure.appearance": "Görünüm", + "prefs.structure.appearance_note": "Renkler, metin ve erişilebilirlik.", + "prefs.structure.in_profile": "Profilde", + "prefs.structure.layout": "Düzen", + "prefs.structure.layout_note": "Pencerenin parçalarının yeri.", + "prefs.structure.look": "Görünüş", + "prefs.structure.measure_pointer": "Ölçüm ve imleç", + "prefs.structure.mouse3d": "3B fare", + "prefs.structure.mouse3d_note": "SpaceMouse ve SpaceNavigator.", + "prefs.structure.navigation_note": "Fare ve trackpad. 3B farenin kendi sayfası var.", + "prefs.structure.profile": "Profil", + "prefs.structure.profile_edited": "Kaydedildikten sonra değiştirildi", + "prefs.structure.profile_hover": "Ayar profillerinde kaydedildi", + "prefs.structure.scale_percent": "%{percent}", + "prefs.structure.sketch": "Eskiz", + "prefs.structure.tools": "Araçlar", + "prefs.structure.tools_note": "Modelleme araçlarının nasıl davrandığı.", + "prefs.structure.work": "Çalışma", "prefs.supersampling_brief": "Görünümü daha büyük çizip aşağı süzer: çok net, ama daha ağır.", "prefs.tab_accent_note": "Vurgu rengi etkin sekmeyi izler", "prefs.theme_file": "tema dosyası", @@ -2015,6 +2424,16 @@ "prefs.theme_follow_off": "Kapalı", "prefs.theme_follow_stop": "Takibi durdur", "prefs.theme_import_hint": "Bir tema dosyası seçmek için tıklayın, buraya bırakın veya bir tema kopyalıyken Ctrl+V (Mac'te Cmd+V) tuşlarına basın", + "prefs.theme_option_opacity": "Opaklık", + "prefs.theme_option_opacity_help": "Kayan panellerin opaklığını ayarlayın. Bir okunabilirlik alt sınırı, görünüm alanı renkleri üzerindeki metni korur.", + "prefs.theme_option_tab_colours": "Sekme renkleri", + "prefs.theme_option_tab_colours_help": "Her şerit sekmesi için bu temanın panel ve görünüm alanı renklerini kullanın.", + "prefs.theme_option_tab_fade_ms": "Sekme geçişi", + "prefs.theme_option_tab_fade_ms_help": "Sekme değiştirirken panel ve görünüm alanı renkleri arasında yumuşak geçiş yapın. Sıfır, anında değiştirir.", + "prefs.theme_options_badge": "Seçenekler", + "prefs.theme_options_more": "Daha fazla · {count}", + "prefs.theme_options_reset": "Sıfırla", + "prefs.theme_options_unavailable": "Bu cihazda kullanılamıyor", "prefs.theme_paste": "Temayı yapıştır", "prefs.theme_paste_none": "Panoda SolidCraft teması yok", "prefs.timeline_half_hour": "−30 dk", @@ -2036,13 +2455,23 @@ "prefs.under_cursor": "İmlecin altında", "prefs.units_precision": "Birimler ve hassasiyet", "prefs.updates": "Güncellemeler", + "prefs.value_boxes_in_view": "Değerleri görünümde tutamaçlarının yanında göster", + "prefs.value_boxes_in_view_tip": "Bir komutun değeri (Mesafe, Yarıçap…), modelin üzerinde tutamacının yanındaki bir kutuda gösterilir. Kapalıyken: değeri, bir seçimden sonra klavyeyi alan komut penceresine yazarsınız ve hiçbir şey modeli örtmez.", "prefs.view": "Görünüm davranışı", "prefs.view_confirm_corner": "Görünümün köşesinde Tamam ve İptal", "prefs.view_confirm_corner_note": "Bir diyalog veya eskiz açıkken, görünümün sağ üstündeki bir onay işareti ve çarpı işareti, diyalogun Tamam ve İptal düğmelerinin ya da eskizi bitirip iptal etmenin işini yapar. Görünüm yönlendiricileri bunların altına iner.", "prefs.viewport": "Görünüm alanı", + "prefs.viewport_analysis_status": "Görünüm alanı analiz durumunu göster", + "prefs.viewport_analysis_status_help": "Etkin analizleri görünüm alanının üstünde gösterir, her öğeden göstergesini açar ve en yeni analizi kapatmak için Esc tuşunu kullanır. Köşe göstergelerini ve Esc'in önceki davranışını geri yüklemek için kapatın.", "prefs.viewport_background": "Arka plan", "prefs.viewport_background_colour": "Renk", "prefs.viewport_background_theme": "Temanın degradesi", + "prefs.viewport_section_status": "Görünüm alanı kesit durumunu göster", + "prefs.viewport_section_status_help": "Kesit ayarını görünüm alanında gösterin. Esc ve etkin şerit düğmesi onu kapatır. Önceki kesit denetimlerini korumak için devre dışı bırakın.", + "prefs.viewport_status_details": "Canlı görünüm alanı ayrıntıları", + "prefs.viewport_status_details_help": "Etkin analiz ve kesit ayarlarını standart ayrıntı kartlarında düzenleyin. Salt okunur analiz göstergelerini ve Kesit diyaloğunu geri getirmek için devre dışı bırakın.", + "prefs.viewport_status_summary": "Görünüm alanı durum öğelerini daralt", + "prefs.viewport_status_summary_help": "Üç veya daha fazla görünüm alanı durum öğesini tek bir özet rozetinde toplayın. Her öğeyi tam satırda tutmak için devre dışı bırakın.", "prefs.wheel": "Tekerlek", "prefs.wheel_trackpad": "Tekerlek ve trackpad", "prefs.workspace": "Çalışma alanı", @@ -2052,6 +2481,10 @@ "properties.title": "Özellikler: {name}", "recovery.days_ago": "{count} gün önce", "recovery.detail": "{file} · {features} özellik · otomatik kaydedilen: {when}", + "recovery.discard_all": "Tümünü at", + "recovery.discard_all_detail": "Bu işlem geri alınamaz.", + "recovery.discard_all_title": "{count} otomatik kayıt atılsın mı?", + "recovery.discard_all_title_one": "1 otomatik kayıt atılsın mı?", "recovery.hours_ago": "{count} sa. önce", "recovery.just_now": "az önce", "recovery.min_ago": "{count} dk. önce", @@ -2167,6 +2600,10 @@ "render.base_color": "Temel renk · sRGB", "render.base_metallic": "Metalik oranı", "render.base_opaque_only": "Bu düzenleyici opak gövde anlamlarını korur. Optik geçiş için açık cam kontrollerini kullanın.", + "render.batch_all_shots": "Tüm çekimler ({count})", + "render.batch_empty": "Tüm çekimleri render etmeden önce bir çekim kaydedin.", + "render.batch_limit": "Tüm Çekimleri Render Et en fazla 32 çekimle sınırlıdır.", + "render.batch_status": "{running} çalışıyor · {waiting} bekliyor", "render.bloom_enable": "Ekran bloom'u", "render.bloom_help": "Üç normalize kutu geçişiyle yayılan, pozitif doğrusal vurgulardan çıkan yalnızca çıktıya özel parlama. Yarıçap çıktı pikselidir. sRGB öncesi doğrusal görüntü ışığına eklenir; mercek, hacimsel efekt veya yakınsama iyileştirmesi değildir. Ham EXR değişmez.", "render.bloom_opaque": "Bloom opak çıktı gerektirir. Saydam PNG reddedilir, sessizce düzleştirilmez.", @@ -2277,6 +2714,13 @@ "render.choose_look": "Önce Görünümler'de bir görünüm seçin", "render.chromatic_offset": "Kromatik kenar kayması", "render.clear_stage": "Kaydedilmiş sahneyi kaldır", + "render.compare_divider": "Karşılaştırma ayırıcısı", + "render.compare_live": "Canlı", + "render.compare_live_preview": "Canlı önizleme", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} sn · {renderer} · {revision}. revizyonda yakalandı", + "render.compare_swap": "Yer değiştir", "render.copy_request": "JSON kopyala", "render.cpu_aa_help": "Uzamsal örnekler: daha fazla örnek kenarları iyileştirir ve render süresini artırır.", "render.cpu_area_add": "Dikdörtgen CPU ışığı ekle", @@ -2917,7 +3361,9 @@ "render.output_ready": "Render için hazır", "render.output_run_check": "Kontrolü çalıştır", "render.output_size_limit": "{method}: kenar başına en fazla {dimension} px ve {pixels} piksel. Sığan en büyük boyut: {width} × {height}.", + "render.output_size_method_profile": "{width} × {height} boyutunu render etmek için {profile} CPU kaynak profiliyle {method} yöntemini seçin ya da daha küçük bir boyut kullanın.", "render.output_size_ok": "Boyut uygun · {width} × {height} px", + "render.output_size_profile": "{width} × {height} boyutunu render etmek için {profile} CPU kaynak profilini seçin ya da daha küçük bir boyut kullanın.", "render.output_swap_orientation": "Genişlik ve yüksekliği değiştir", "render.output_tools_inspector": "Boyutu ve biçimi Çıktı denetçisinde düzenleyin.", "render.output_view_image": "Görüntüyü göster", @@ -3024,6 +3470,10 @@ "render.result_retained": "En son tamamlanan görüntü gösteriliyor; daha yeni bir render onu değiştirmedi.", "render.result_sequence": "Kontrol noktası", "render.result_title": "Render Sonucu", + "render.results_choose": "Saklanan sonuçlar", + "render.results_label": "Render {number} · {shot} · {seconds} sn", + "render.results_stale_label": "{result} [güncel değil]", + "render.results_unnamed": "Görüntü", "render.return_design": "Tasarıma dön", "render.review_stale": "Bu inceleme bayat. Uygulamadan önce çözün veya yeniden kontrol edin.", "render.ribbon_aging": "Yaşlanma", @@ -3130,6 +3580,7 @@ "render.size_custom": "Özel…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · {profile} gerekir", "render.size_presets": "Boyut ön ayarları", "render.size_presets_pending": "Çıktı düzenleyicisiyle gelecek", "render.size_preview": "Önizleme", @@ -3417,6 +3868,24 @@ "sheet.flange_type_contour": "Kontur", "sheet.flange_type_edge": "Kenar", "sheet.no_body": "sac metal gövde yok: Flanş > Taban ile bir tane başlatın veya bir plakayı Sac Metale Dönüştür ile sac metale çevirin (büyük düz yüzünü seçin)", + "sheet.personal_rules.confirm_delete": "Silmeyi onayla", + "sheet.personal_rules.delete": "Sil", + "sheet.personal_rules.delete_prompt": "Bu kişisel kural silinsin mi? Tasarımlardaki mevcut kurallar değişmez.", + "sheet.personal_rules.full": "Kişisel kitaplık zaten 64 kural içeriyor.", + "sheet.personal_rules.invalid_name": "Satır sonu veya kontrol karakteri içermeyen kısa bir ad girin.", + "sheet.personal_rules.invalid_values": "Kuralın değerlerini tamamlayın: her biri bu tasarımda geçerli bir değere çıkmalı; kalınlık pozitif, K faktörü 0 ile 1 arasında olmalıdır.", + "sheet.personal_rules.missing": "Seçilen kişisel kural artık kullanılamıyor.", + "sheet.personal_rules.name": "Kural adı", + "sheet.personal_rules.name_exists": "Bu adda bir kişisel kural zaten var. Farklı bir ad kullanın.", + "sheet.personal_rules.name_hint": "Benzersiz bir ad", + "sheet.personal_rules.overwrite": "Değişiklikleri seçili kişisel kurala kaydet", + "sheet.personal_rules.rename": "Yeniden adlandır", + "sheet.personal_rules.rule": "Kişisel kural", + "sheet.personal_rules.save": "Yeni kaydet", + "sheet.personal_rules.scope": "Tüm tasarımlar için profilinize kaydedilir.", + "sheet.personal_rules.select": "Bir kural seçin", + "sheet.personal_rules.title": "Kişisel kurallar", + "sheet.personal_rules.unsupported": "Bu kural, bu sürümün kullanamadığı değerler içeriyor.", "shortcut.json_error": "parametreler JSON biçiminde olmalıdır: {error}", "shortcut.no_command": "`{id}` komutu yok; JSON'dan önceki metin bir komut kimliği olmalıdır", "shortcut.pin": "S kutusunun üstüne sabitle", @@ -3453,8 +3922,10 @@ "sketch_text.align_right": "Sağ", "sketch_text.bold": "Kalın", "sketch_text.builtin_font": "{family} (yerleşik)", + "sketch_text.formula": "Kelimeleri parametrelerden oluşturmak için = ile başlayın: ='W' + number(Width)", "sketch_text.italic": "İtalik", "sketch_text.loading_fonts": "Yüklü yazı tipleri aranıyor…", + "sketch_text.no_bold": "Yerleşik yazı tipinin kalın biçimi yok: yüklü bir yazı tipi seçin", "sketch_text.on_path": "Metin eğrisini izler: konumunu eğri belirler", "sketch_text.path_clear": "Metni eğriden ayır", "sketch_text.path_hint": "Metnin izleyeceği eskiz eğrisi: önce buraya, ardından eğriye tıklayın", @@ -3486,10 +3957,7 @@ "the two origins are on the same component": "iki orijin aynı bileşende", "thread.automatic_size": "Otomatik boyut", "thread.designation": "Tanım", - "thread.direction": "Diş yönü", "thread.iso_metric": "ISO metrik", - "thread.left_hand": "Sol el", - "thread.right_hand": "Sağ el", "thread.select_size": "Boyut seç", "timeline.delete_after_marker_one": "Geçmiş İşaretçisinden Sonra 1 Özelliği Sil", "timeline.delete_after_marker_other": "Geçmiş İşaretçisinden Sonra {count} Özelliği Sil", @@ -3506,8 +3974,10 @@ "timeline.move_to_group": "Özellikleri klasöre taşı", "timeline.rename_group": "Özellik klasörünü yeniden adlandır", "timeline.reorder_many": "Özellikleri yeniden sırala", + "timeline.suppress_features": "Özellikleri bastır", "timeline.suppress_folders_tip": "Klasörlerdeki ve iç içe klasörlerindeki her özelliği bastır veya bastırmayı kaldır", "timeline.ungroup": "Özellik klasörünü kaldır", + "timeline.unsuppress_features": "Özelliklerin bastırmasını kaldır", "to the face": "yüze kadar", "to the next face": "sonraki yüze kadar", "toolbar.customize_note": "{tab} sekmesi. Bir komuta araç çubuğu düğmesi eklemek için komutu işaretleyin. Ayrıca panelin açılır menüsündeki bir satırı araç çubuğuna sürükleyebilir, bir düğmeyi kaldırmak için araç çubuğunun dışına sürükleyebilir veya açılır menü satırındaki raptiyeyi kullanabilirsiniz.", @@ -3591,6 +4061,8 @@ "ui.3d_mouse_section": "3D fare", "ui.3d_mouse_show_in_view": "3B fareyi 3B görünümde göster", "ui.3d_mouse_show_in_view_tip": "Sol alt köşede, siz hareket ettirdikçe hareket eden bir 3B fare resmi.", + "ui.3d_mouse_sketch_orbit": "Eskizleri 3B fareyle döndür", + "ui.3d_mouse_sketch_orbit_tip": "Bir eskiz açıkken ve dik bakılırken 3B fare de, fare gibi, görünümü döndürür. Kapalıyken: görünümü eğene kadar eskizi kaydırır ve yakınlaştırır.", "ui.3d_mouse_skip": "Cihazım bunu yapamıyor", "ui.3d_mouse_skip_tip": "Bu hareketi iki yönde de atlar; kalibrasyon onu dışarıda bırakır.", "ui.3d_mouse_speed": "3D fare hızı", @@ -3619,6 +4091,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Başlığı saat yönünün tersine çevirin, tutun, sonra bırakın.", "ui.3d_mouse_switch_cap": "Merkeze dönüş olarak kalibre et", "ui.3d_mouse_switch_trackball": "İztopu olarak kalibre et", + "ui.3d_mouse_use_direct": "Doğrudan sürücüyü kullan", + "ui.3d_mouse_use_direct_tip": "3D fareyi spacenavd yerine doğrudan (hidraw) oku.", "ui.3d_mouse_view_axis": "Görünüm ekseni", "ui.3d_mouse_view_off": "Kapalı", "ui.3d_mouse_view_off_tip": "3D fare sürücüsünün profili bu ekseni kapatıyor, bu yüzden hareketi görünümü oynatmaz. Burada başka bir eksenin hareketini seçerseniz ikisi yer değiştirir ve o hareket görünümü oynatmayı bırakır.", @@ -3657,6 +4131,8 @@ "ui.agent_chat_auth_terminal": "Bunu bir terminalde çalıştırın ve ardından tekrar Bağlan'a tıklayın:", "ui.agent_chat_auth_title": "Ajan için oturum aç", "ui.agent_chat_cancel": "İptal", + "ui.agent_chat_cancel_timeout": "Ajan Durdur komutuna yanıt vermedi ve bağlantısı kesildi. Devam etmek için yeniden bağlanın.", + "ui.agent_chat_cannot_start": "Yüklü ama başlamıyor: {error}", "ui.agent_chat_changes": "{n} değişiklik, tek geri alma adımı", "ui.agent_chat_changes_n": "{n} değişiklik", "ui.agent_chat_changes_of": "{n}/{limit} değişiklik", @@ -3665,11 +4141,13 @@ "ui.agent_chat_command": "Ajan komutu", "ui.agent_chat_connect": "Bağlan", "ui.agent_chat_copy": "Kopyala", + "ui.agent_chat_copy_message": "İletiyi kopyala", "ui.agent_chat_ctx_bodies": "Gövdeler", "ui.agent_chat_ctx_elements": "Öğeler", "ui.agent_chat_ctx_features": "Özellikler", "ui.agent_chat_ctx_more": "+{n} daha", "ui.agent_chat_ctx_other": "Diğer", + "ui.agent_chat_custom_heading": "Özel model", "ui.agent_chat_custom_hint": "stdin ve stdout üzerinden Agent Client Protocol'ü kullanan herhangi bir program. Kabuk (shell) olmadan çalıştırılır.", "ui.agent_chat_denied": "Reddedildi", "ui.agent_chat_deny": "Reddet", @@ -3713,8 +4191,16 @@ "ui.agent_chat_mode_all": "Tümü", "ui.agent_chat_mode_ask": "Sor", "ui.agent_chat_mode_edits": "Düzenle", + "ui.agent_chat_model_custom": "Özel olanı kullan: {model}", "ui.agent_chat_model_no_tools": "{model}, SolidCraft'ın araçlarını kullanamaz, bu yüzden yalnızca sohbet edebilir. Araç destekli bir model seçin.", + "ui.agent_chat_model_rejected": "Ajan {model} modelini kabul etmedi: {error}", + "ui.agent_chat_model_search": "Model ara…", "ui.agent_chat_model_tip": "Ajanın kullandığı model. Seçiminiz bu ajan için hatırlanır.", + "ui.agent_chat_models_failed": "Modeller listelenemedi: {error}", + "ui.agent_chat_models_heading": "Kullanılabilir modeller", + "ui.agent_chat_models_listing": "Modeller listeleniyor…", + "ui.agent_chat_models_none": "Uç nokta hiç model listelemiyor", + "ui.agent_chat_models_not_a_list": "Yanıt bir model listesi değildi", "ui.agent_chat_new": "Yeni sohbet", "ui.agent_chat_new_confirm": "Yeni bir sohbet başlatılsın mı? Geçerli sohbet temizlenir.", "ui.agent_chat_next_picture": "Sonraki resim", @@ -3749,9 +4235,12 @@ "ui.agent_chat_queued_stopped": "Sırada (durduruldu, gönderilmedi)", "ui.agent_chat_refresh": "Yenile", "ui.agent_chat_refused": "Ajan için izin verilmiyor: {reason}", + "ui.agent_chat_reinstall": "{agent} yüklü ({program}), ancak SolidCraft denetlediğinde başlamadı: {error}\nKurulumu eksik olabilir veya başka türde bir bilgisayar için yapılmış olabilir. `{install}` ile yeniden yükleyin, bir terminalde sürümünü yazdırdığını doğrulayın, ardından Yenile'ye tıklayın.", "ui.agent_chat_remove": "Sıradan kaldır", "ui.agent_chat_remove_file": "Bu iletiden çıkar", "ui.agent_chat_remove_imported": "Bu iletiden çıkar; parça tasarımda kalır (Geri al onu kaldırır)", + "ui.agent_chat_reply_cut_off": "Yanıt bitmeden uzunluk sınırına ulaştı, bu yüzden eksik olabilir. Ajandan devam etmesini veya daha kısa bir yanıt vermesini isteyin.", + "ui.agent_chat_reply_declined": "Model bu iletiyi yanıtlamayı reddetti.", "ui.agent_chat_retry": "Yeniden dene", "ui.agent_chat_right": "Sağ", "ui.agent_chat_save": "Kaydet", @@ -3810,12 +4299,17 @@ "ui.ai_copy_suffix": "Kopya", "ui.ai_custom_url": "Özel URL", "ui.ai_default": "Varsayılan", + "ui.ai_edit": "Düzenle", + "ui.ai_edit_agent_title": "Ajanı düzenle", + "ui.ai_edit_gone": "Bu ajan kaldırıldı, bu yüzden kaydedilecek bir şey yok.", + "ui.ai_edit_tip": "Bu ajanın adını, komutunu veya uç noktasını değiştirin. Kayıtlı bir anahtar gizli kalır.", "ui.ai_http_busy": "uç nokta meşgul veya sınırda; daha sonra tekrar deneyin", "ui.ai_http_key": "uç nokta anahtarı reddetti: Ayarlar > AI altında kontrol edin", "ui.ai_http_not_found": "Uç nokta veya model bulunamadı: temel URL'yi ve model adını kontrol edin", "ui.ai_http_too_large": "konuşma bu uç nokta için çok büyük; yeni bir sohbet başlatın", "ui.ai_key": "API anahtarı", "ui.ai_key_hint": "isteğe bağlı; sistem anahtar zincirinde saklanır", + "ui.ai_key_keep_hint": "kayıtlı anahtarı korumak için boş bırakın", "ui.ai_key_needs_https": "Anahtar yalnızca HTTPS üzerinden veya bu bilgisayara gönderilir.", "ui.ai_key_note": "SolidCraft ayarlarında değil, sistem anahtar zincirinde saklanır. Yerel bir sunucu için boş bırakın.", "ui.ai_keychain_error": "Sistem anahtar zinciri reddetti: {error}", @@ -3842,11 +4336,15 @@ "ui.ai_permissions": "İzinler", "ui.ai_preset": "Şablon", "ui.ai_protocol": "Protokol", + "ui.ai_reasoning_effort": "Akıl yürütme çabası", + "ui.ai_reasoning_effort_field_hint": "boş = sağlayıcının varsayılanı", + "ui.ai_reasoning_effort_hint": "İsteğe bağlı. Uç noktaya `reasoning_effort` olarak gönderilir; kabul edilen değerler sağlayıcıya göre değişir (örneğin `low`, `high` veya `max`). Burada belirlediğiniz değerin yerine SolidCraft hiçbir zaman başka bir değer koymaz. Hiçbir şey göndermemek ve sağlayıcının varsayılanını korumak için boş bırakın.", "ui.ai_remove": "Kaldır", "ui.ai_request_timed_out": "Model {seconds} sn'den uzun sürdü. Bu uç nokta için istek zaman aşımını Tercihler › Asistan altında yükseltebilirsiniz.", "ui.ai_request_timeout": "İstek zaman aşımı", "ui.ai_request_timeout_hint": "Bu uç noktaya tek bir model isteğinin 30 sn ile bir saat arasında ne kadar sürebileceği. Yavaş bir yerel model için yükseltin.", "ui.ai_reset": "Sıfırla", + "ui.ai_save": "Kaydet", "ui.ai_settings": "AI ayarları…", "ui.ai_show_features": "AI özelliklerini göster", "ui.ai_show_features_note": "Ajan sohbeti: zaten kullandığınız bir kodlama ajanının veya seçtiğiniz bir model uç noktasının açık tasarım üzerinde çalıştığı bir panel. Kapalı: AI düğmesi yok, kısayol yok, menü girişi yok, panel yok ve hiçbir şey aranmaz veya başlatılmaz.", @@ -3925,6 +4423,8 @@ "ui.cancel": "İptal", "ui.canvases": "Tuvaller", "ui.center": "Merkez", + "ui.center_arc_follows_cursor": "Merkez noktalı yay imlecin yönünü izler", + "ui.center_arc_follows_cursor_tip": "Merkez noktalı yay, imlecin merkezinin etrafında dönüş yönüne göre saat yönünde veya saat yönünün tersine ilerler. Kapalıyken: başlangıçtan itibaren her zaman saat yönünün tersine.", "ui.centerline": "Merkez çizgisi", "ui.chain": "Zincir", "ui.chamfer": "Pah", @@ -3933,6 +4433,7 @@ "ui.circle": "Daire", "ui.circular_pattern": "Dairesel desen", "ui.clear": "Temizle", + "ui.clear_print_face": "Baskı yüzeyini temizle", "ui.clear_recent": "Son kullanılanları temizle", "ui.clear_the_selection": "Seçimi temizle", "ui.click_selects_whole_bodies": "Tıklama tüm gövdeyi seçer", @@ -3967,12 +4468,27 @@ "ui.constant": "Sabit", "ui.constraints_conflict": "Kısıtlamalar çakışıyor", "ui.construction": "Yapı çizgisi", + "ui.construction.angle_hint": "Yardımcı doğru: bir noktaya tıklayın, ardından bir açı yazın veya bir yön seçin", + "ui.construction.bisector_hint": "Açıortay: kesişen iki düz çizgiyi, ardından istenen çözümü seçin", + "ui.construction.common_hint": "Ortak teğet: iki daire/yay, ardından istenen çözümü seçin", + "ui.construction.contact_hint": "Teğet: bir daire/yay veya açık spline/konik eğri, ardından değme noktasını seçin (serbest biçimli eğriler: uç noktalar)", + "ui.construction.external_hint": "Teğet: bir daire veya yay, bir dış nokta, ardından istenen çözümü seçin", + "ui.construction.free_hint": "Yardımcı doğru: iki noktaya tıklayın; yeniden başlamak için sağ tıklayın", + "ui.construction.normal_needs_length": "Sonsuz çizgi her zaman yardımcı doğrudur: normal bir çizgi çizmek için bir uzunluk yazın", + "ui.construction.point_hint": "Yardımcı doğru: geçeceği noktaya tıklayın", + "ui.construction.reference_hint": "Yardımcı doğru: düz bir çizgi, ardından bir nokta seçin; referansı değiştirmek için sağ tıklayın", "ui.construction.ribbon_label": "Yardımcılar", + "ui.construction.side_hint": "Yardımcı doğru: doğrunun ilerleyeceği tarafa tıklayın; yeniden başlamak için sağ tıklayın", "ui.context_menu": "Bağlam menüsü", + "ui.continuity_crease": "Kırık", + "ui.continuity_curvature": "Eğrilik", + "ui.continuity_curvature_change": "Eğrilik değişimi", "ui.continuity_g0": "G0 kırık", "ui.continuity_g1": "G1 teğet", "ui.continuity_g2": "G2 eğrilik", "ui.continuity_gap": "Boşluk", + "ui.continuity_position": "Konum", + "ui.continuity_tangent": "Teğet", "ui.copy": "Kopyala", "ui.corner": "Köşe", "ui.corners": "Köşeler", @@ -3995,6 +4511,7 @@ "ui.dark": "Koyu", "ui.default_modelling_orientation": "Varsayılan modelleme yönü", "ui.delete": "Sil", + "ui.delete_select_first": "Önce silinecekleri seçin: özellikler, gövdeler, bileşenler veya eskiz geometrisi", "ui.depth": "Derinlik", "ui.design": "Tasarım", "ui.design_properties.author": "Yazar", @@ -4009,6 +4526,40 @@ "ui.design_properties.project": "Proje", "ui.design_properties.revision": "Revizyon", "ui.design_saved": "{path} konumuna kaydedildi", + "ui.details_access_caption": "Yüzler, bir aletin onlara seçilen yönden ulaşıp ulaşamayacağını gösterir.", + "ui.details_angle": "Açı", + "ui.details_continuity_caption": "Seçili birleşim yerini düzenleyin. Diğer birleşim yerleri kendi ayarlarını korur.", + "ui.details_continuity_stale": "Önceki geometri: bu birleşim yerini düzenlemek veya çerçevelemek için analizi yeniden çalıştırın.", + "ui.details_copy_list": "Listeyi kopyala", + "ui.details_curvature": "Eğrilik toleransı", + "ui.details_curvature_caption": "Yüzler, yerel eğrilik yarıçaplarına göre renklendirilir.", + "ui.details_direction": "Alet yönü", + "ui.details_draft_caption": "Yüzler, kalıptan çıkarma yönüne olan açılarına göre renklendirilir.", + "ui.details_edit_seam": "Birleşim yerini düzenle", + "ui.details_fixture": "Arayüz bileşeni örneği — yalnızca örnek veri", + "ui.details_fixture_caption": "Açıklayıcı değerler içeren arayüz bileşeni örneği; bu bir model sonucu değildir.", + "ui.details_fixture_problem": "Sorunlu örnek bulgu", + "ui.details_fixture_readout": "Örnek ölçülen değer", + "ui.details_flip": "Ters çevir", + "ui.details_gap": "Boşluk", + "ui.details_hatch": "Kesilen yüzleri tara", + "ui.details_jump": "Eğrilik sıçraması", + "ui.details_key": "Gösterge", + "ui.details_offset": "Ofset", + "ui.details_plane": "Düzlem", + "ui.details_pull": "Kalıptan çıkarma yönü", + "ui.details_radius": "Yarıçap", + "ui.details_readout": "Okunan değer", + "ui.details_samples": "Örnekler", + "ui.details_seam": "{body} · Kenar {edge}", + "ui.details_settings": "Ayarlar", + "ui.details_sharp_gap": "Keskin veya boşluk", + "ui.details_show_all": "Tüm {count} öğeyi göster", + "ui.details_smooth": "Pürüzsüz", + "ui.details_stripes": "Şeritler", + "ui.details_target": "Geometriyi çerçevele", + "ui.details_worst_seams": "En kötü birleşim yerleri", + "ui.details_zebra_caption": "Yansıyan şeritler, yüzlerin ne kadar pürüzsüz birleştiğini gösterir.", "ui.diameter": "Çap", "ui.dimension": "Ölçü", "ui.direct_interaction": "Doğrudan etkileşim", @@ -4053,6 +4604,7 @@ "ui.edit_in_place_saved_elsewhere": "Parça başka bir dosyaya kaydedildi; montaj hâlâ {name} dosyasına bağlı", "ui.edit_in_place_wait": "Tasarımda çalışan işlem bitene kadar bekleyin", "ui.edit_section_analysis": "Kesit analizini düzenle", + "ui.edit_sketch_empty": "Düzenlenecek eskiz yok", "ui.ellipse": "Elips", "ui.emboss_wrap_note": "Desteklenen tek bir silindire teğet olan dik çizgi profilleri otomatik olarak sarılır. Hedef seçmek için bir cidar seçin.", "ui.end_radius": "Bitiş yarıçapı", @@ -4063,12 +4615,15 @@ "ui.equation_explicit": "Açık fonksiyon", "ui.equation_form": "Biçim", "ui.equation_note": "Değişken düz bir sayıdır: sin(t) onu radyan olarak alır. Birimi olmayan bir sonuç tasarımın birimindedir.", + "ui.equation_note_range": "Değişken, aralığı gibi bir uzunluktur: uzunluk parametreleriyle birleştirin ve sin() için bir uzunluğa bölün. Birimi olmayan bir sonuç tasarımın birimindedir.", "ui.equation_parametric": "Parametrik", + "ui.equation_variable_unit": "Değişken, aralığın birimine sahiptir", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Eşdeğer yarıçap", "ui.expand": "Genişlet", + "ui.explode_needs_two_components": "Patlatılmış görünüm bileşenleri birbirinden ayırır, bu yüzden tasarımda iki veya daha fazla bileşen olmalıdır (Yeni bileşen, Tasarım ekle veya Gövdelerden bileşen oluştur)", "ui.exportDxf": "DXF olarak dışa aktar…", "ui.export_ellipsis_keymap": "Dışa aktar…", "ui.export_keymap_tip": "Tuşları, S kutusu favorilerini ve araç çubuğunu dosya olarak dışa aktarır", @@ -4194,6 +4749,7 @@ "ui.hideOrigin": "Orijini gizle", "ui.hidePlanes": "Düzlemleri gizle", "ui.hideProfile": "Profili gizle", + "ui.hide_component_history": "Geçmişini gizle", "ui.hide_origin_by_default": "Başlangıcı varsayılan olarak gizle", "ui.hide_origin_note": "Yeni tasarımlar Başlangıç klasörü gizli başlar. Bir tasarım, gösterip gizledikten sonra kendi Başlangıç ayarını korur.", "ui.history_back": "Bir adım geri git", @@ -4201,6 +4757,7 @@ "ui.history_edge_hint": "kenara çift tıklayın", "ui.history_first": "Başlangıca git", "ui.history_forward": "Bir adım ileri git", + "ui.history_hide_hidden": "Gizli Bileşenleri Gizle", "ui.history_hide_names": "Adları gizle", "ui.history_last": "Sona git", "ui.history_marker_tip": "Geçmiş işaretçisi: modeli geri sarmak için sürükleyin; yeni özellikler buraya eklenir", @@ -4210,10 +4767,12 @@ "ui.history_play_button_show": "Oynat Düğmesini Göster", "ui.history_play_finish_action": "Geçmişi oynatmadan önce geçerli eylemi bitirin", "ui.history_play_roll_back": "Oynatmadan önce Geçmiş işaretçisini geri taşıyın", + "ui.history_show_hidden": "Gizli Bileşenleri Göster", "ui.history_show_names": "Adları göster", "ui.history_sketch_listed_under": "{feature} altında listelenir", "ui.history_title": "Geçmiş", "ui.history_toggle_names": "Özellik adlarını göster veya gizle", + "ui.history_waits_for_editor": "Geri al, Yinele ve Geçmiş, özellik düzenleyicisi açılana kadar bekler", "ui.hole": "Delik", "ui.hole_tap_type": "Diş türü", "ui.hole_type": "Delik türü", @@ -4229,6 +4788,7 @@ "ui.insert_design.saved_file": "{name} kaydedilmemiş değişiklikler içeriyor, bu yüzden kaydedilmiş dosyası eklendi. Değişiklikleri almak için onu kaydedin, ardından Bağları güncelle'yi çalıştırın.", "ui.insert_design.unsaved": "Kaydedilmemiş değişiklikler", "ui.inspect": "İncele", + "ui.instances": "Örnekler", "ui.intersect": "Kesişim", "ui.isolate": "Yalıt", "ui.join": "Birleştir", @@ -4237,12 +4797,14 @@ "ui.joints": "Bağlantılar", "ui.keyboard_shortcuts": "Klavye kısayolları", "ui.language": "Dil", + "ui.lasso_select": "Kement (serbest bir halka sürükleyin: tamamen içinde kalanları alır)", "ui.layout_compact": "Kompakt", "ui.layout_floating": "Kayan", "ui.length": "Uzunluk", "ui.length_decimals": "Uzunluk ondalık basamakları", "ui.light": "Açık", "ui.line": "Çizgi", + "ui.line_arc_hint": "Teğet yay: yayın ucuna tıklayın. Çizgilere dönmek için son noktada yeniden bekleyin; bitirmek için sağ tıklayın veya Esc tuşuna basın", "ui.link_copies": "Aynı Kopyaları Bağla", "ui.link_copies_keep": "Tut", "ui.link_copies_link": "Bağla", @@ -4331,6 +4893,7 @@ "ui.part_size_shared": "Parçayı yeniden oluşturur ve eklenen tüm özelliklerin yerine geçer. Bu bileşenin tüm örnekleri güncellenir.", "ui.paste": "Yapıştır", "ui.path": "Yol", + "ui.pattern_object_type_tip": "Gövdeler: katı biçimler, görünümde veya Tarayıcı'da seçilir; her biri bütün olarak kopyalanır.\nÖzellikler: Geçmiş'in adımları, örneğin bir ekstrüzyon veya delik; Geçmiş'te ya da oluşturdukları bir yüzde seçilir; adım tekrarlanır.\nEskiz bunlardan hiçbiri değildir: eğrilerini eskizin kendi Dizi veya Aynala komutuyla tekrarlayın ya da önce ekstrüzyon yapın.", "ui.pattern_on_path": "Yol üzerinde desen", "ui.perforate_margin_default": "çaptan", "ui.perforate_pitch": "Adım", @@ -4357,12 +4920,17 @@ "ui.plugins_skipped": "{count} klasör okunamadı.", "ui.plugins_version": "{version}", "ui.point": "Nokta", + "ui.point_cloud_add_filter": "Filtre ekle…", "ui.point_cloud_auto_range": "Otomatik aralık", "ui.point_cloud_color_by": "Renklendirme ölçütü", "ui.point_cloud_file_colors": "Dosya renkleri", + "ui.point_cloud_filter_by": "Filtreleme ölçütü", "ui.point_cloud_height_high": "En yüksek", "ui.point_cloud_height_low": "En düşük", + "ui.point_cloud_legend_filter": "Yukarıdaki göstergede gösterilir ve gizlenir", "ui.point_cloud_no_file_colors": "Dosyada renk yok", + "ui.point_cloud_pause": "Duraklat", + "ui.point_cloud_play": "Oynat", "ui.point_cloud_single_color": "Tek renk", "ui.point_cloud_size": "Nokta boyutu", "ui.point_cloud_units": "Dosya birimleri", @@ -4371,6 +4939,11 @@ "ui.polygon": "Çokgen", "ui.preferences": "Ayarlar", "ui.press_a_key": "bir tuşa basın…", + "ui.print_face_body_not_sent": "Bu yüzeyin gövdesi gönderilmiyor: önce onu Gövdeler'e ekleyin", + "ui.print_face_cleared": "{body}: baskı yüzeyi temizlendi", + "ui.print_face_input": "Baskı yüzeyi", + "ui.print_face_pick": "Baskı yüzeyi yapmak için katı bir gövdenin düz bir yüzeyini seçin", + "ui.print_face_set": "{body}: baskı yüzeyi ayarlandı; Dilimleyiciye gönder gövdeyi bu yüzeyin üzerine koyar", "ui.profile": "Profil", "ui.profile_plane": "Profil düzlemi", "ui.profiles": "Profiller", @@ -4386,6 +4959,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Ölçülüyor…", + "ui.properties.measuring_bodies": "Ölçülüyor… {total} gövdeden {done} tanesi", "ui.properties.measuring_failed": "Ölçüm tamamlanmadan durdu.", "ui.properties.principal_axis": "Asal eksen {number}", "ui.properties.principal_moments": "Asal momentler", @@ -4434,6 +5008,7 @@ "ui.revolve": "Döndür", "ui.ribbon_exit": "Çıkış", "ui.ribbon_labels": "Şerit simgelerinin altında metin göster", + "ui.ribbon_menus_skip_pinned": "Sabitlenen komutları açılır menülerin dışında bırak", "ui.ribbon_pin_footer": "Sabitlenen komutlar şeritte görünür. Sabitlemek veya kaldırmak için bir satırın üzerine gelin.", "ui.ribbon_workspace": "Çalışma alanı", "ui.right": "Sağ", @@ -4452,6 +5027,7 @@ "ui.selectOther": "Diğerini seç…", "ui.selectTangentChain": "Teğet zinciri seç", "ui.select_all": "Tümünü seç", + "ui.select_components_by_face": "Bileşenleri seçin (bir yüz kendi bileşenini seçer)", "ui.selection": "Seçim", "ui.selection_modifiers": "Seçim değiştiricileri", "ui.selection_shift_add_only": "Shift+tıklama kaldırmadan ekler", @@ -4477,6 +5053,7 @@ "ui.showDimension": "Ölçüyü göster", "ui.showOrigin": "Orijini göster", "ui.showPlanes": "Düzlemleri göster", + "ui.show_component_history": "Geçmişini göster", "ui.show_constraints": "Kısıtlamalar", "ui.show_construction_geometries": "Yapı geometrileri", "ui.show_dimensions": "Ölçüler", @@ -4493,6 +5070,11 @@ "ui.sketch_intersect_selection_filter": "Seçim filtresi", "ui.sketch_modifiers": "Eskiz değiştiricileri", "ui.sketch_project_geometry": "Geometri", + "ui.sketch_report.all_constrained": "Her şey tam kısıtlı.", + "ui.sketch_report.dof": "Serbestlik dereceleri", + "ui.sketch_report.loose": "Tam kısıtlı değil", + "ui.sketch_report.status": "Durum", + "ui.sketch_report.title": "Eskiz raporu", "ui.sketch_scale": "Eskiz ölçeği", "ui.sketches": "Eskizler", "ui.slice": "Dilim", @@ -4588,19 +5170,31 @@ "ui.view_angles": "Görünüm açıları", "ui.view_angles_convention": "Yukarı eksen etrafında derece cinsinden. Sapma 0° Ön görünümdür, 90° Sol, −90° Sağ, 180° Arka; yatıklık 90° Üst görünümdür; pozitif yuvarlanma modeli saat yönünde döndürür.", "ui.view_angles_help": "Görünümün yatıklık, sapma ve yuvarlanma açılarını derece cinsinden ve izdüşüm türünü yönlendirme gizmosunun altında gösterir. Tam açıları yazmak için göstergeye tıklayın.", + "ui.view_angles_lock": "{axis} değerini kilitle", "ui.view_angles_ortho": "Ortografik", "ui.view_angles_persp": "Perspektif", "ui.view_angles_pitch": "Yatıklık", "ui.view_angles_readout": "Yatıklık {pitch} · Sapma {yaw} · Yuvarlanma {roll}", "ui.view_angles_roll": "Yuvarlanma", + "ui.view_angles_unlock": "{axis} değerinin kilidini aç", "ui.view_angles_yaw": "Sapma", + "ui.view_angles_zero": "{axis} değerini 0° yap", "ui.view_centre": "Görünüm merkezi", "ui.viewport_status_clear": "Kapat: {name}", "ui.viewport_status_clear_hint": "Kapat: {name} · Esc", + "ui.viewport_status_edges": "{count} kenar", + "ui.viewport_status_from": "{direction} yönünden", "ui.viewport_status_key": "Göstergeyi göster: {name}", "ui.viewport_status_minimum_radius": "Minimum yarıçap", "ui.viewport_status_pairs": "{count} çift", + "ui.viewport_status_section_hatch": "{setting} · tarama", + "ui.viewport_status_section_plane": "Geçerli düzlem", + "ui.viewport_status_section_tilted": "eğik · {offset}", "ui.viewport_status_stripes": "{count} şerit", + "ui.viewport_status_summary_clear": "Hepsini kapat", + "ui.viewport_status_summary_heading": "Bu görünümde", + "ui.viewport_status_summary_label": "{name} ve {count} öğe daha", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Temayı izle", "ui.visual_shaded_hidden_edges": "Gizli kenarlarla gölgeli", "ui.visual_shaded_with_edges": "Kenarlarla gölgeli", @@ -4637,10 +5231,12 @@ "update.button": "Güncelle", "update.button_version": "{version} sürümüne güncelle", "update.check_automatically": "Güncellemeleri otomatik denetle", + "update.check_for_updates": "Güncellemeleri denetle", "update.check_now": "Şimdi denetle", + "update.check_unavailable": "Bu kurulum için güncelleme denetimi kullanılamıyor.", "update.checking": "Denetleniyor…", "update.copy": "Kopyala", - "update.dmg_opened": "Disk görüntüsü açıldı ve doğrulandı: SolidCraft'ı “Uygulamalar” klasörüne sürükleyin, eski sürümü değiştirin ve SolidCraft'ı yeniden başlatın.", + "update.dmg_opened": "Disk görüntüsü açıldı ve doğrulandı: SolidCraft'tan çıkın, yeni SolidCraft'ı “Uygulamalar” klasörüne sürükleyin, eski sürümü değiştirin ve SolidCraft'ı yeniden açın.", "update.download": "İndir", "update.download_open": "İndir ve aç", "update.downloading": "İndiriliyor ve doğrulanıyor… {done} / {total} MB", @@ -4651,11 +5247,13 @@ "update.installed": "SolidCraft {version} yüklendi. Kullanmak için yeniden başlatın.", "update.installer_started": "Yükleme programı, SolidCraft kapatıldığında başlar.", "update.later": "Daha sonra hatırlat", + "update.managed": "Güncelleme mevcut: SolidCraft'ı {manager} üzerinden güncelleyin", "update.no_notes": "Bu sürüm için not bulunmuyor.", "update.package_hint": "Bu kurulum bir {kind} kaynağından geliyor. Yeni paketi indirip şu komutla yükleyin:", "update.prefs_dev": "Bu bir geliştirme derlemesi ({version}): güncelleme aramaz.", "update.prefs_flatpak": "Bu kurulum ({version}) Flatpak tarafından güncellenir: {command} komutunu çalıştırın veya yazılım yöneticisini kullanın. SolidCraft kendisi denetlemez.", "update.prefs_label": "Güncellemeler", + "update.prefs_managed": "Bu, {manager} tarafından yönetilen SolidCraft {version}. Denetim, GitHub'a en yeni sürümü sorar ve başka hiçbir şey göndermez; SolidCraft'ı {manager} üzerinden güncelleyin.", "update.prefs_note": "Bu, SolidCraft {version} ({kind}). Denetim, GitHub'a en yeni sürümü sorar ve başka hiçbir şey göndermez.", "update.prefs_web": "En yeni web uygulamasını almak için sayfayı yeniden yükleyin. Ağ kullanılamazsa veya güncelleme indirmesi zamanında bitiremezse bunun yerine kaydedilmiş sürüm açılır; süren bir indirme bir sonraki yeniden yükleme için devam eder.", "update.refresh_checking": "En yeni sürüm denetleniyor…", @@ -4682,6 +5280,7 @@ "web.open_link": "Bağlı tasarım açılsın mı?", "web.open_link_confirm": "Kaydedilmemiş değişiklikler var. Bağlı tasarım yeni bir sekmede açılsın mı?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ seç · Enter / Tab tamamla · Esc kapat", + "↑ ↓ choose · Enter applies this value": "↑ ↓ seç · Enter bu değeri uygular", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ seçin · Enter yazdığınızı uygular · Esc kapatır", "⌘Enter continues on GitHub.": "⌘Enter ile GitHub'da devam edilir." } diff --git a/assets/locales/uk.json b/assets/locales/uk.json index ff79e2fcd..f40fb82a0 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "ПОВЕРХНЯ ПЕРЕХОДУ", "BOUNDARY SURFACE": "ПОВЕРХНЯ ЗА МЕЖАМИ", "BROWSER": "БРАУЗЕР", + "Back to the original order": "Повернути початковий порядок", "Ball": "Кульове", "Bar": "Смуга", "Base Center": "Центр основи", @@ -595,6 +596,8 @@ "Snap to face and edge centres": "Прив'язка до центрів граней і ребер", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft не може надсилати звіти напряму. Надішліть їх на GitHub; токен у застосунку не потрібен.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft закрився до того, як ці проєкти було збережено. Можна відкрити їхнє останнє автозбереження.", + "Sort A to Z": "Сортувати від А до Я", + "Sort Z to A": "Сортувати від Я до А", "Spacing 2 must be a non-zero number": "Крок 2 має бути ненульовим числом", "Spacing must be a non-zero number": "Крок має бути ненульовим числом", "Specialise": "Спеціалізувати", @@ -775,6 +778,8 @@ "at the face": "біля грані", "bom.group_children": "Піддеталі в рядку їхньої деталі", "browser.body_name": "Тіло{number}", + "browser.calibrate_click_a": "Клацніть зображення для точки A або введіть її координати.", + "browser.calibrate_click_b": "Клацніть зображення для точки B або введіть її координати.", "browser.calibrate_title": "Калібрувати: {name}", "browser.capture_many": "Компоненти ({count}) переміщено, але їхні положення не зафіксовано.", "browser.capture_note": "«Зафіксувати положення» зберігає нове положення; «Відновити положення» повертає попереднє.", @@ -788,6 +793,13 @@ "browser.sketch_attachment_lost": "{name} (прив'язку втрачено)", "browser.sketch_editing": "{name} (редагується)", "browser.sketch_name": "Ескіз{number}", + "browser.sketches_to_parts_already_in_part": "уже в своїй деталі", + "browser.sketches_to_parts_design_body": "на тілі самого проєкту", + "browser.sketches_to_parts_moved": "Переміщено ескізів у деталь, на якій вони лежать: {moved}", + "browser.sketches_to_parts_no_exact_attachment": "на грані без точної прив'язки", + "browser.sketches_to_parts_not_on_face": "не на грані деталі", + "browser.sketches_to_parts_part_missing": "їхньої деталі більше немає", + "browser.sketches_to_parts_result": "Переміщено ескізів у деталь, на якій вони лежать: {moved}; на місці залишилося: {stayed} — {why}", "browser.units": "Одиниці: {units}", "cam.flat": "Плоский", "cam.follower": "Штовхач", @@ -817,6 +829,8 @@ "cmd.appearance_pick_up": "Взяти вигляд", "cmd.appearance_replace": "Замінити вигляд", "cmd.assembly_bom": "Специфікація матеріалів", + "cmd.assembly_mass_properties": "Масові характеристики", + "cmd.body.print_face": "Грань друку", "cmd.body_rename": "Перейменувати тіло", "cmd.browser_collapse_all": "Згорнути все", "cmd.browser_expand_all": "Розгорнути все", @@ -824,6 +838,7 @@ "cmd.browser_move": "Перемістити елементи браузера", "cmd.browser_order": "Упорядкувати елементи браузера", "cmd.browser_rename_group": "Перейменувати групу", + "cmd.browser_reparent": "Перемістити до компонента", "cmd.browser_ungroup": "Розгрупувати", "cmd.browser_visibility": "Показати/приховати", "cmd.canvas_calibrate": "Калібрувати полотно", @@ -850,7 +865,9 @@ "cmd.component_metadata": "Властивості деталі", "cmd.component_metadata_set": "Змінити властивості деталі", "cmd.component_move_bodies": "Перемістити тіла до компонента", + "cmd.component_move_features": "Перемістити операції до компонента", "cmd.component_move_sketches": "Перемістити ескізи до компонента", + "cmd.component_move_sketches_to_parts": "Перемістити ескізи до їхніх деталей", "cmd.component_paste_from_design": "Вставити з іншого проєкту як компонент", "cmd.component_paste_new": "Вставити як новий", "cmd.component_properties": "Фізичні властивості компонента", @@ -1079,6 +1096,13 @@ "cmd.render_start": "Рендеринг зображення", "cmd.render_status": "Перебіг рендерингу", "cmd.select_clear": "Зняти виділення", + "cmd.settings_profile_apply": "Застосувати профіль налаштувань", + "cmd.settings_profile_delete": "Видалити профіль налаштувань", + "cmd.settings_profile_export": "Експортувати профіль налаштувань", + "cmd.settings_profile_import": "Імпортувати профіль налаштувань", + "cmd.settings_profile_list": "Профілі налаштувань", + "cmd.settings_profile_rename": "Перейменувати профіль налаштувань", + "cmd.settings_profile_save": "Зберегти профіль налаштувань", "cmd.sheet_convert": "Перетворити на листовий метал", "cmd.sheet_export_bend_table": "Експортувати таблицю згинів", "cmd.sheet_export_dxf": "Експортувати розгортку як DXF", @@ -1179,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Сплайн за контрольними точками (5-й степінь)", "cmd.sketch_spline_fit_point": "Сплайн за точками проходження", "cmd.sketch_spline_insert_point": "Додати точку сплайна", + "cmd.sketch_spline_remove_point": "Видалити точку сплайна", "cmd.sketch_spline_reverse": "Обернути напрямок сплайна", "cmd.sketch_spun_profile": "Профіль обертання", "cmd.sketch_toggle_diameter": "Перемкнути радіус / діаметр", @@ -1232,6 +1257,7 @@ "cmd.view.render_browser": "Браузер рендерингу", "cmd.view.render_dock": "Перемістити док рендерингу", "cmd.view.render_focus": "Вид фокусу рендерингу", + "cmd.view.status_details": "Подробиці рядка стану", "cmd.view.status_items": "Елементи рядка стану", "cmd.view_ambient_occlusion": "Окружне затінення", "cmd.view_angle_readout": "Кути виду", @@ -1270,8 +1296,14 @@ "color.hex_hint": "#rrggbb або #rrggbbaa", "color.hue": "Відтінок", "color.linear": "Значення кольору в лінійному просторі 0-1", + "color.recent": "Недавні кольори", + "color.recent_help": "Кольори, які ви вибираєте в будь-якому полі кольору, з'являються тут", + "color.saturation": "Насиченість (у відсотках)", "color.saturation_value": "Насиченість і яскравість", "color.selected": "Вибраний колір", + "color.step_down": "Зменшити на крок", + "color.step_up": "Збільшити на крок", + "color.value": "Значення, тобто яскравість (у відсотках)", "config.column_filter_empty": "Немає збігів", "contact.components_count": "Компонентів: {count}", "contact.enabled_label": "увімкнено", @@ -1318,6 +1350,7 @@ "dialog.dimension_name": "Розмір: {name}", "dialog.edit_title": "РЕДАГУВАННЯ {title}", "dialog.no_shown_body": "Немає видимих тіл для виконання операції", + "dialog.pattern_sketch_not_object": "Виберіть тіла або операції: ескіз не є ні тим, ні іншим. Повторіть його криві власним інструментом «Масив» чи «Дзеркало» в ескізі або спершу видавіть його.", "dialog.select": "↖ Вибрати", "dialog.selected_count": "↖ Вибрано: {count}", "dialog.selection_guidance": "Виберіть вхідні дані, щоб змінити їх. Клацніть вибрані об'єкти, щоб прибрати їх; натискання з Ctrl/Cmd також перемикає їх. Перегляньте попередній перегляд, а потім натисніть OK.", @@ -1375,26 +1408,243 @@ "from the rule": "з правила", "help.apache": "Ліцензія Apache 2.0", "help.appearance.assign": "Надає вибраним тілам, граням або компонентам колір чи вигляд матеріалу, не змінюючи їхньої ваги. Використовуйте, щоб розрізнити деталі або переглянути оздоблення.", + "help.assembly.bom": "Перелічує деталі проєкту або компонента з їхньою кількістю за номером деталі й може зберегти перелік як CSV або JSON. Використовуйте як список деталей для замовлення та складання.", "help.attributions": "Відомості про авторство (ATTRIBUTION.md)", "help.build": "Версія {version} · коміт {commit} · зібрано {date}", + "help.canvas.decal": "Розміщує зображення на плоскій грані моделі, наче наклейку. Використовуйте, щоб показати етикетку, логотип чи надрукований візерунок на деталі.", + "help.canvas.edit": "Змінює полотно: його положення, розмір, кут, непрозорість, віддзеркалення, видимість або назву. Використовуйте, щоб сумістити опорне зображення з ескізом, який ви обводите по ньому.", + "help.canvas.insert": "Розміщує зображення PNG або JPEG на площині чи грані як прозорий орієнтир. Використовуйте, щоб обвести фото чи креслення в ескізі, задавши зображенню відомий розмір.", + "help.component.break_link": "Відокремлює пов'язаний компонент від файлу його проєкту, залишаючи його тіла без змін. Використовуйте, коли деталь більше не має слідувати за змінами в початковому файлі.", + "help.component.capture_position": "Фіксує положення деталей, які ви пересунули вручну, і вони стають їхнім новим положенням. Використовуйте після перетягування на місце деталей, яких не утримує жодне з'єднання.", + "help.component.create": "Додає до проєкту новий порожній компонент усередині активного компонента, якщо ви не вибрали іншого батьківського. Використовуйте, щоб дати новій частині збірки власне місце для тіл і ескізів.", "help.component.finish_edit": "Зберігає деталь, яку ви редагуєте на місці, повертається до її збірки й оновлює збірку за цією деталлю. Використовуйте, коли зміни в пов'язаній деталі завершено.", + "help.component.from_bodies": "Перетворює кожне вибране тіло на окремий компонент із назвою цього тіла. Використовуйте, коли проєкт, збудований із окремих тіл, має стати збіркою, деталі якої можна з'єднувати й переміщувати.", + "help.component.insert_design": "Вставляє інший збережений проєкт як компонент, пов'язаний зі своїм файлом, із суцільними тілами в тому вигляді, як вони є там. Використовуйте, щоб повторно застосувати деталь у збірці й підхопити пізніші зміни через «Оновити зв'язки».", + "help.component.properties": "Показує об'єм, масу, центр мас і моменти інерції компонента за матеріалами його тіл. Використовуйте, щоб перевірити вагу й баланс збірки.", + "help.component.revert_position": "Повертає деталі, які ви пересунули вручну, на попередні місця, відкидаючи переміщення, що не були зафіксовані. Використовуйте, щоб скасувати пробні переміщення в збірці.", + "help.component.update_links": "Знову зчитує пов'язані файли проєктів і замінює тіла там, де вони змінилися. Використовуйте після редагування деталі, яку використовує ця збірка.", + "help.config.configure": "Додає параметри, операції, матеріали чи вигляди як стовпці таблиці конфігурацій. Використовуйте, щоб створити варіанти одного проєкту, наприклад розміри деталі.", + "help.config.preview": "Перевіряє, чи перебудовується рядок таблиці конфігурацій, не змінюючи проєкт чи його історію. Використовуйте перед перемиканням на варіант, у якому ви не впевнені.", + "help.config.rules": "Показує правила таблиці конфігурацій, її рядки та активний рядок. Використовуйте, щоб побачити, як налаштовано варіанти проєкту.", + "help.config.table": "Показує таблицю конфігурацій: по одному рядку на варіант, по одному стовпцю на параметр чи операцію, а також чи проєкт досі відповідає активному рядку. Використовуйте, щоб переглянути варіанти проєкту.", "help.connect_note": "Перезапустіть кожного асистента, щоб завантажити сервер SolidCraft. Перед зміною кожен файл збережено як резервну копію .bak.", "help.connect_title": "Підключення ШІ-асистентів", + "help.construct.axis.edge": "Створює допоміжну вісь уздовж прямого ребра або прямої ескізу. Використовуйте як вісь для обертання, кругового масиву чи з'єднання.", + "help.construct.axis.normal_to_face": "Створює допоміжну вісь через точку, перпендикулярну до грані. Використовуйте як вісь, що виходить прямо з поверхні.", + "help.construct.axis.through_cylinder": "Створює допоміжну вісь через центр грані циліндра, конуса чи тора або кругового ребра. Використовуйте, щоб обертати чи розмножувати операції навколо круглої деталі.", + "help.construct.axis.two_planes": "Створює допоміжну вісь там, де сходяться дві площини або плоскі грані. Використовуйте, коли потрібна вісь — лінія між двома гранями.", + "help.construct.axis.two_points": "Створює допоміжну вісь через дві точки, вершини або точки ескізу. Використовуйте для осі, що проходить між двома відомими положеннями.", + "help.construct.plane.along_path": "Створює допоміжну площину, перпендикулярну до ребра чи кривої, у вибраному місці вздовж неї. Використовуйте, щоб накреслити профіль для протягування або переріз траєкторії.", + "help.construct.plane.at_angle": "Створює допоміжну площину, повернуту на кут від площини чи грані навколо осі або ребра. Використовуйте для похилих ескізів, наприклад косого кронштейна.", + "help.construct.plane.midplane": "Створює допоміжну площину посередині між двома площинами чи плоскими гранями або таку, що ділить навпіл кут між ними. Використовуйте як площину симетрії для дзеркального відображення.", + "help.construct.plane.offset": "Створює допоміжну площину, паралельну площині чи плоскій грані, на відстані або через точку. Використовуйте, щоб креслити на заданій висоті над гранню.", + "help.construct.plane.perpendicular": "Створює допоміжну площину, що містить пряму чи ребро й стоїть перпендикулярно до площини або грані. Використовуйте, щоб креслити на моделі вздовж ребра в прямовисній площині.", + "help.construct.plane.tangent": "Створює допоміжну площину, що дотикається до циліндра, конуса, кулі чи тора в точці. Використовуйте, щоб креслити на боці круглої деталі.", + "help.construct.plane.three_points": "Створює допоміжну площину через три точки. Використовуйте для площини, заданої положеннями на моделі, наприклад трьома кутами.", + "help.construct.plane.two_edges": "Створює допоміжну площину через два прямі ребра чи прямі, що лежать в одній площині. Використовуйте для площини через деталь, наприклад через два протилежні ребра.", + "help.construct.point.along_path": "Створює допоміжну точку в певному місці вздовж ребра чи кривої. Використовуйте як орієнтир на півшляху вздовж траєкторії.", + "help.construct.point.center": "Створює допоміжну точку в центрі кругового ребра, кола чи дуги ескізу, кулі або тора. Використовуйте як орієнтир для отворів, осей і з'єднань.", + "help.construct.point.edge_plane": "Створює допоміжну точку там, де ребро чи пряма проходить крізь площину або плоску грань. Використовуйте, щоб позначити, де траєкторія перетинає площину.", + "help.construct.point.three_planes": "Створює допоміжну точку там, де сходяться три площини чи плоскі грані. Використовуйте як орієнтир кута, навіть якщо в моделі немає вершини.", + "help.construct.point.two_edges": "Створює допоміжну точку там, де два ребра чи прямі сходяться або підходять найближче одне до одного. Використовуйте як орієнтир у віртуальному куті.", + "help.construct.point.vertex": "Створює допоміжну точку на вершині або точці ескізу. Використовуйте як орієнтир, що залишається, коли навколишній ескіз чи тіло приховано.", + "help.contact.check": "Перелічує пари деталей у наборах контактів, що проходять одна крізь одну в поточному положенні. Використовуйте, щоб знайти зіткнення перед керуванням з'єднаннями чи запуском дослідження руху.", + "help.contact.create": "Об'єднує дві чи більше деталей у набір контактів, тіла якого не можуть проходити одне крізь одне, поки рухаються з'єднання. Використовуйте для деталей, що мають зупинятися при дотику, наприклад важеля біля свого упору.", + "help.contact.disable_all": "Вимикає контакт, тож керовані з'єднання та дослідження руху більше не зупиняються там, де деталі торкаються. Використовуйте, щоб знову вільно рухати деталі або щоб велика збірка швидко реагувала.", + "help.contact.edit": "Змінює набір контактів: деталі в ньому, його назву або те, чи його придушено; також може видалити набір. Використовуйте, щоб налаштувати, які деталі не можуть проходити одна крізь одну.", + "help.contact.enable_all": "Поміщає кожну деталь збірки в один набір контактів, тож жодні дві деталі не можуть проходити одна крізь одну, поки рухаються з'єднання. Використовуйте для швидкої перевірки всього механізму.", + "help.contact.enable_sets": "Вмикає контакт для заданих вами наборів контактів, тож керовані з'єднання та дослідження руху зупиняються там, де їхні деталі проходили б одна крізь одну. Використовуйте, щоб повернути ваші набори після вимкнення контакту.", + "help.contact.list": "Перелічує набори контактів проєкту, деталі в кожному з них і чи ввімкнено контакт. Використовуйте, щоб перевірити налаштування контакту перед керуванням збіркою.", + "help.document.inspect": "Показує огляд проєкту: його компоненти, тіла, ескізи, операції та параметри. Використовуйте, щоб зорієнтуватися в проєкті, який ви створювали не самі.", + "help.document.units": "Змінює одиниці, в яких проєкт показує довжини, наприклад mm або дюйми. Геометрія зберігає розмір; змінюються лише відображення й прості числа.", + "help.edit.checkpoint": "Запам'ятовує проєкт, активний ескіз і історію скасувань у поточному стані. Використовуйте перед ризикованою спробою, від якої, можливо, захочете повернутися.", + "help.edit.restore_checkpoint": "Повертається до контрольної точки разом з історією скасувань. Використовуйте, щоб відкинути все зроблене після контрольної точки одним кроком.", + "help.explode.create": "Створює рознесений вид, що розсовує деталі від центра збірки або на задані вами переміщення. Використовуйте, щоб показати, як збірку складають, для інструкцій чи презентацій.", "help.face.delete": "Видаляє вибрані грані, а сусідні грані закривають проміжок, або залишає його відкритим як поверхню. Використовуйте, щоб прибрати заокруглене ребро, отвір чи бобишку, що заважають.", + "help.file.insert_mesh": "Додає файл 3MF, STL, OBJ, PLY або glTF до проєкту як тіла сітки в новому компоненті. Використовуйте, щоб розмістити завантажену чи відскановану модель поруч із проєктом як орієнтир.", + "help.file.insert_step": "Додає файл STEP, IGES, FreeCAD або Rhino до проєкту як суцільні тіла в новому компоненті; деталі збірки стають вкладеними компонентами. Використовуйте, щоб імпортувати моделі від постачальників чи з інших CAD-програм.", + "help.file.save_mesh": "Зберігає тіла як сітку STL, 3MF або OBJ із вибраною вами гладкістю криволінійних граней. Використовуйте, щоб підготувати деталі до 3D-друку або для програм, які читають сітки.", + "help.file.send_to_slicer": "Зберігає вибрані тіла як файл 3MF і відкриває його у вибраному вами слайсері. Використовуйте, щоб перейти від моделі до друку одним кроком.", "help.font_details": "Інтерфейс використовує вбудовані шрифти egui (Ubuntu Light і Hack під ліцензіями Ubuntu Font Licence та MIT/Bitstream Vera; Noto Emoji та шрифт піктограм емодзі під ліцензіями OFL і MIT). Для тексту ескізів використовується Liberation Sans (SIL OFL 1.1). Необов’язковий пакет шрифтів The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), не входить до збірок SolidCraft.", "help.fonts": "Шрифти", + "help.frame.member": "Розміщує профіль, наприклад трубу чи алюмінієвий профіль, уздовж прямих ескізу рами, по одному елементу на пряму. Використовуйте, щоб будувати рами, стелажі та зварні конструкції.", + "help.inspect.accessibility": "Фарбує грані, до яких інструмент може дістатися з одного напрямку, і ті, до яких не може. Використовуйте, щоб перевірити деталь на можливість обробки чи формування з цього боку.", + "help.inspect.center_of_mass": "Показує центр мас тіл — кожного окремо й усіх разом — за однорідної густини. Використовуйте, щоб перевірити баланс і те, куди деталь перекинеться.", + "help.inspect.colored_components": "Надає кожному компоненту власний тимчасовий колір, не змінюючи вигляди. Використовуйте, щоб одразу розрізняти деталі збірки.", + "help.inspect.compare": "Порівнює два тіла й показує, де в одного є матеріал, якого немає в іншого, з об'ємом і відхиленням. Використовуйте, щоб порівняти змінену чи імпортовану деталь з оригіналом.", + "help.inspect.continuity": "Перевіряє, наскільки гладко грані сходяться вздовж ребер: проміжки, злами чи стрибки кривизни, і розфарбовує шви. Використовуйте, щоб знайти місця, де поверхні сполучаються нечисто.", + "help.inspect.curvature_comb": "Малює гребені вздовж кривих, ребер чи граней, зубці яких показують, наскільки сильно вони згинаються. Використовуйте, щоб помітити плоскі ділянки, злами та нерівномірну кривизну.", + "help.inspect.curvature_map": "Розфарбовує грані за силою їхньої кривизни: червоним там, де радіус малий. Використовуйте, щоб знайти тісні місця й оцінити, наскільки гладка поверхня.", + "help.inspect.draft": "Розфарбовує грані за кутом ухилу відносно напрямку витягування, позначаючи ті, де його замало. Використовуйте, щоб перевірити деталь перед формуванням чи литтям.", + "help.inspect.environment_map": "Показує модель із відбивним, дзеркальним оздобленням. Використовуйте, щоб оцінити перебіг поверхонь за тим, як по них біжать відбиття.", + "help.inspect.interference": "Знаходить тіла, що перетинаються, і показує кожен перетин з його об'ємом. Використовуйте, щоб перевірити збірку на деталі, які зіштовхуються.", + "help.inspect.isocurve": "Малює ізопараметричні криві граней — сітку, на якій побудована поверхня. Використовуйте, щоб побачити, як тече поверхня і де вона згущується.", + "help.inspect.measure": "Вимірює довжини, відстані, кути, площі та радіуси між вибраними об'єктами або об'єм і масу тіл. Використовуйте, щоб перевірити розміри й зазори.", + "help.inspect.minimum_radius": "Знаходить найменший радіус кривизни кривих, ребер чи граней і те, де він розташований. Використовуйте, щоб перевірити, чи може інструмент або сопло пройти за формою.", + "help.inspect.section": "Розрізає вид уздовж площини та штрихує перерізані грані, не змінюючи модель. Використовуйте, щоб зазирнути всередину деталей і збірок.", + "help.inspect.zebra": "Показує чорно-білі смуги, що відбиваються на гранях моделі. Використовуйте, щоб оцінити гладкість: смуги, які обриваються чи ламаються на ребрі, вказують на поганий перехід.", + "help.joint.as_built": "З'єднує дві деталі там, де вони вже є, не переміщуючи жодну з них, і задає, як вони ще можуть рухатися. Використовуйте для деталей, які ви вже поставили в остаточне положення.", + "help.joint.cam": "Зв'язує кулачок, що обертається, зі штовхачем, тож штовхач ковзає чи гойдається, коли контур кулачка проходить під ним. Використовуйте для кулачків, ексцентриків і приводів клапанів.", + "help.joint.create": "З'єднує дві деталі у вибраних початках з'єднання й переміщує другу деталь на місце; тип з'єднання задає, як вони ще можуть рухатися. Використовуйте, щоб створити збірку, деталі якої рухаються як справжній механізм.", + "help.joint.drive": "Задає кут чи відстань з'єднання й переміщує разом з ним деталі в межах його обмежень; пов'язані з'єднання та замкнені контури слідують за ним. Використовуйте, щоб перевірити, що механізм рухається як задумано.", + "help.joint.gear": "Зв'язує два обертові з'єднання передавальним числом, тож рух одного обертає інше. Використовуйте для прямозубих коліс і зубчастих вінців, із передавальним числом за радіусами ділильних кіл або кількістю зубів.", + "help.joint.limits": "Задає, наскільки далеко з'єднання може повернутися чи зсунутися, мінімумом і максимумом, або скасовує ці межі. Використовуйте, щоб утримати шарнір, повзун чи важіль у межах його справжнього ходу.", + "help.joint.motion_link": "Пов'язує два з'єднання співвідношенням і зсувом, тож рух одного рухає інше. Використовуйте для сталого зв'язку між з'єднаннями, якого не охоплюють «Зубчаста передача», «Рейкова передача» чи «Гвинт».", + "help.joint.origin": "Розміщує іменований початок з'єднання на деталі: у центрі грані чи круглого торця, на середині ребра, у куті або в точці. Використовуйте, щоб підготувати місця кріплення з'єднань; початок, вибраний на грані, слідує за нею, коли деталь змінює розмір.", + "help.joint.rack_pinion": "Зв'язує шестірню, що обертається, з рейкою, що ковзає, тож рейка переміщується на довжину ділильного кола, яку прокочує шестірня. Використовуйте для рейкових приводів, рульового керування й лінійних столиків.", + "help.joint.reach": "Переміщує точку на деталі до цілі, змінюючи з'єднання на її ланцюзі в межах їхніх обмежень. Використовуйте, щоб поставити механізм у позу за тим, де має бути його кінець, наприклад кінчик руки робота.", + "help.joint.rigid_group": "Скріплює вибрані деталі як є, тож вони рухаються як одне ціле. Використовуйте для деталей, що належать одна до одної й не мають руху між собою.", + "help.joint.screw": "Зв'язує обертання й ковзання кроком, тож кожен оберт зсуває на цю відстань. Використовуйте для ходових гвинтів, болтів і різьбових шпинделів.", + "help.library.apply": "Застосовує матеріал чи вигляд із файлу локальної бібліотеки до тіл, граней або компонентів. Використовуйте, щоб повторно застосувати матеріали, збережені з іншого проєкту.", + "help.library.export": "Зберігає матеріали та вигляди проєкту у файл бібліотеки. Використовуйте, щоб ділитися ними або повторно застосовувати в інших проєктах.", + "help.library.inspect": "Перевіряє файл бібліотеки та перелічує його матеріали й вигляди, не змінюючи проєкт. Використовуйте, щоб побачити, що містить бібліотека, перш ніж її застосовувати.", "help.licences": "Ліцензії", "help.material.assign": "Задає, з чого зроблено вибрані тіла, наприклад зі сталі, алюмінію чи ABS. Використовуйте, щоб маса й вага відповідали справжній деталі.", + "help.material.properties.validate": "Перевіряє картку даних матеріалу на узгодженість чисел і пропущені значення. Використовуйте перед тим, як покладатися на ці дані для маси чи жорсткості.", + "help.mesh.convert": "Перебудовує тіло сітки, наприклад STL, у суцільне тіло з плоскими й циліндричними гранями, яке можна редагувати. Використовуйте, щоб змінювати імпортовані механічні деталі як змодельоване тіло.", "help.mit": "Ліцензія MIT", + "help.motion.study": "Задає значення з'єднань на кроках уздовж часової шкали й відтворює їх як анімацію. Використовуйте, щоб спостерігати рух механізму за послідовністю й перевіряти зазори по дорозі.", + "help.motion.trace": "Відстежує траєкторію, якою рухається точка деталі під час дослідження руху чи керування з'єднанням, і після підтвердження зберігає її як криву 3D-ескізу. Використовуйте, щоб побачити, куди сягає механізм, або щоб будувати на його траєкторії.", "help.notice": "NOTICE", + "help.occurrence.ground": "Закріплює деталь на місці або знову звільняє її, тож з'єднання переміщують інші деталі навколо неї. Використовуйте для рами чи основи, на якій будується решта збірки.", "help.occurrence.move": "Переміщує екземпляр компонента в збірці", "help.parameters.change": "Відкриває таблицю іменованих значень і виразів, що керують розмірами проєкту. Використовуйте, щоб змінити розмір в одному місці, а всі операції, які його використовують, підлаштувалися.", + "help.parameters.export": "Зберігає параметри проєкту як CSV або JSON. Використовуйте, щоб редагувати їх у таблиці або перенести до іншого проєкту.", + "help.parameters.graph": "Показує, які параметри й операції використовують які інші, а також цикли чи помилки між ними. Використовуйте, щоб побачити, на що вплине зміна параметра.", + "help.parameters.import": "Зчитує параметри з CSV або JSON у проєкт: усі або жодного. Використовуйте, щоб імпортувати значення з таблиці чи іншого проєкту.", + "help.parameters.move": "Переміщує параметр користувача перед іншим або після нього в списку. Використовуйте, щоб тримати пов'язані параметри разом.", + "help.parts.fastener": "Додає стандартний гвинт, болт, гайку, шайбу, штифт чи підшипник вибраного розміру. Розміщений на отворі, він сідає в отвір із з'єднанням, тож вам не потрібно моделювати кріплення самостійно.", + "help.parts.insert": "Вставляє стандартну деталь вибраного сімейства, розміру й довжини. Розміщена на краю чи стінці отвору, вона сідає на отвір із жорстким з'єднанням.", + "help.parts.library": "Відкриває стандартні деталі: гвинти, болти, гайки, шайби, установчі гвинти, штифти та підшипники стандартних розмірів. Використовуйте, щоб додати стандартну деталь замість того, щоб моделювати її самостійно.", + "help.parts.resize": "Змінює розмір чи довжину вставленої стандартної деталі та перебудовує її; її з'єднання тримають її на місці. Використовуйте, коли гвинт виявився задовгим або отвору потрібен інший розмір.", + "help.plastic.assign_rule": "Призначає тілам правило пластику, тож їхні пластикові операції беруть з нього ухил і зазор за замовчуванням. Використовуйте, щоб один раз налаштувати формовану деталь для всіх її операцій.", + "help.plastic.boss": "Додає бобишку під гвинт на грані: стовпчик із необов'язковими отвором, ухилом, заокругленням біля основи та ребрами жорсткості. Використовуйте для точок кріплення гвинтів у формованих чи надрукованих корпусах.", + "help.plastic.lip": "Додає губку або відповідний паз уздовж краю порожнистого тіла. Використовуйте, щоб дві половини корпусу центрувалися одна на одній і щільно закривалися.", + "help.plastic.manage_rules": "Створює й редагує правила пластику: матеріал, товщину стінки, радіуси, зазор і ухил. Використовуйте їх, щоб операції формованої деталі були узгодженими.", + "help.plastic.rest": "Додає упор на грані: круглий чи прямокутний майданчик, суцільний або порожнистий, з ухилом. Використовуйте як опору чи стійку у формованому корпусі.", + "help.plastic.snap_fit": "Додає клацковий гачок на грані із заданими довжиною, товщиною та зачепом. Використовуйте, щоб скріпити деталі защіпкою без гвинтів.", "help.pointcloud.insert": "Вставте скан у форматі PLY, XYZ або PTS як хмару точок поряд із моделлю. Використовуйте її як довідку під час побудови моделі за виміряними даними.", + "help.sheet.convert": "Перетворює пластину або порожнисте тіло рівномірної товщини на тіло листового металу зі згинами на вибраних ребрах. Використовуйте, щоб зробити наявну деталь придатною до розгортання.", + "help.sheet.export_bend_table": "Зберігає таблицю згинів тіла листового металу як CSV або JSON: кути, радіуси та положення згинів на розгортці. Використовуйте для листогибочного преса або цеху.", + "help.sheet.export_dxf": "Зберігає розгортку як DXF із контурами, лініями згинів і за бажанням примітками до згинів. Використовуйте для лазерного, плазмового чи гідроабразивного різання.", + "help.sheet.flange": "Додає фланець: основну пластину з ескізу, стінку вздовж розімкненого контуру ескізу або зігнуту стінку на краях листа. Використовуйте, щоб будувати деталі з листового металу.", + "help.sheet.flat_pattern": "Створює розгортку тіла листового металу з її розміром, вирізами та лініями згинів. Використовуйте, щоб перевірити заготовку перед різанням.", + "help.sheet.fold": "Згинає лист уздовж прямої ескізу на заданий кут і радіус. Використовуйте, щоб зігнути плоский лист після вирізання в ньому елементів.", + "help.sheet.hem": "Загинає край листа назад на себе. Використовуйте для безпечних, жорстких країв без гострих задирок.", + "help.sheet.manage_rules": "Створює й редагує правила листового металу: товщину, радіус згину, коефіцієнт K, полегшення та проміжки. Використовуйте їх, щоб узгодити матеріал та інструменти вашої майстерні.", + "help.sheet.path_flange": "Додає ланцюг фланців уздовж краю листа за розімкненим ланцюгом прямих ескізу. Використовуйте для профілів, таких як U- чи Z-подібний, одним кроком.", + "help.sheet.perforate": "Додає поле отворів по всьому плоскому листу в шаховому чи квадратному розташуванні. Використовуйте для вентиляційних отворів, решіток і полегшених панелей.", + "help.sheet.refold": "Знову згинає розгорнуте тіло листового металу. Використовуйте після додавання елементів до плоского листа.", + "help.sheet.unfold": "Розгортає всі згини тіла листового металу. Використовуйте, щоб додати отвори чи вирізи, які мають перетинати згин, а потім знову зігнути.", + "help.sketch.arc.center_point": "Малює кругову дугу навколо центральної точки від початкової до кінцевої точки. Використовуйте, коли відомий центр дуги, наприклад радіус навколо отвору чи осі повороту.", + "help.sketch.arc.tangent": "Малює дугу, що починається в кінці прямої чи дуги й продовжує її по дотичній. Використовуйте, щоб продовжити ланцюг плавним згином замість кута.", + "help.sketch.arc.three_point": "Малює дугу від початкової до кінцевої точки через третю точку. Використовуйте, коли дуга має проходити через задані точки, а не навколо відомого центра.", + "help.sketch.arc3d": "Малює точну кругову дугу в просторі через три точки за ввімкненого 3D-ескізу. Використовуйте для згинів траєкторій і напрямних, що виходять із площини ескізу.", + "help.sketch.auto_constrain": "Додає обмеження, які ескіз майже вже має, як-от горизонтальність, паралельність чи співпадання, а потім проставляє розміри, доки він не стане повністю визначеним. Використовуйте, щоб зафіксувати приблизно накреслений ескіз одним кроком.", + "help.sketch.auto_constrain_from_datum": "Працює як «Автообмеження», але вимірює положення від вибраної вами базової точки замість початку координат. Використовуйте, коли деталь розмічено від однієї опорної точки, наприклад кута чи отвору.", + "help.sketch.blend_curve": "З'єднує кінці двох кривих плавним сплайном, дотичним до обох, або також неперервним за кривизною, якщо ви так виберете. Використовуйте, щоб перекрити проміжок між кривими без зламу.", + "help.sketch.break": "Розбиває криву на частини там, де її перетинають інші криві, або в точках, які ви на ній розмістите. Використовуйте, коли частина кривої потребує власного обмеження або її слід видалити окремо.", + "help.sketch.cancel": "Виходить з ескізу й відкидає все, що змінено відтоді, як його створено чи відкрито для редагування. Скасування дії повертає зміни.", + "help.sketch.centerline": "Перемикає прямі між звичайними та осьовими лініями — осями, які профілі не враховують. Використовуйте осьову лінію як вісь для обертання, дзеркала чи обмеження симетрії.", + "help.sketch.chamfer.distance_angle": "Скошує кут між двома прямими, заданий відстанню вздовж першої прямої та кутом. Використовуйте, коли на кресленні фаску задано довжиною й кутом, наприклад 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Скошує кут між двома прямими на однакову відстань уздовж обох. Використовуйте для звичайної фаски 45° на контурі.", + "help.sketch.chamfer.two_distance": "Скошує кут між двома прямими, заданий окремою відстанню вздовж кожної прямої. Використовуйте для фасок, що не є 45°, заданих двома довжинами.", + "help.sketch.circle.center": "Малює коло за центром і діаметром. Використовуйте для отворів, бобишок та інших круглих елементів, центр яких відомий.", + "help.sketch.circle.three_point": "Малює коло через три точки. Використовуйте, коли коло має проходити через задані точки, наприклад наявної геометрії.", + "help.sketch.circle.three_tangent": "Малює коло, що дотикається до трьох прямих, кіл або дуг. Використовуйте, щоб вписати коло в простір між трьома кривими, наприклад вписане коло трикутника.", + "help.sketch.circle.two_point": "Малює коло за двома кінцями його діаметра. Використовуйте, коли відомі точки на краю кола, а не його центр.", + "help.sketch.circle.two_tangent": "Малює коло заданого розміру, що дотикається до двох прямих, кіл або дуг. Використовуйте для заокруглення сталого радіуса між двома кривими.", + "help.sketch.conic": "Малює конічну криву між двома кінцевими точками, форма якої задається вершинною точкою та значенням rho. Використовуйте для плавних переходів, повноту яких потрібно налаштувати, — від плоскої до майже гострого кута.", + "help.sketch.constrainer": "Застосовує обмеження, яке вибрані одна чи дві криві майже вже мають, як-от горизонтальність, паралельність, дотичність чи рівність. Використовуйте, щоб упорядкувати накреслений від руки ескіз по одному зв'язку за раз.", + "help.sketch.constraint.coincident": "Розміщує точку на іншій точці, кривій чи осі ескізу. Використовуйте, щоб закрити проміжки в профілі або розмістити точку на прямій.", + "help.sketch.constraint.collinear": "Розміщує дві прямі на одній прямій. Використовуйте, щоб вирівняти перервані краї, наприклад обидві сторони виїмки.", + "help.sketch.constraint.concentric": "Надає двом колам чи дугам спільний центр. Використовуйте для кілець, цековок і валів з уступами.", + "help.sketch.constraint.curvature": "Змушує дві криві, що сходяться в кінцевій точці, продовжуватися з однаковою кривизною (G2). Використовуйте там, де дотичного сполучення замало для плавності, наприклад на видимих поверхнях.", + "help.sketch.constraint.equal": "Робить прямі однакової довжини, а кола й дуги — однакового радіуса. Використовуйте, щоб один розмір керував кількома однаковими елементами.", + "help.sketch.constraint.fix": "Закріплює точки чи криві там, де вони є, або знову звільняє їх. Використовуйте для геометрії, що не повинна зміщуватися під час перетягування чи розв'язування ескізу.", + "help.sketch.constraint.horizontal_vertical": "Робить пряму або лінію між двома точками горизонтальною чи вертикальною — залежно від того, що ближче. Використовуйте, щоб вирівняти контур за осями ескізу.", + "help.sketch.constraint.midpoint": "Ставить точку на середину прямої або поєднує середини двох прямих. Використовуйте, щоб відцентрувати геометрію відносно ребра.", + "help.sketch.constraint.parallel": "Робить дві прямі паралельними. Використовуйте для сторін, які мають залишатися паралельними, коли змінюються інші розміри.", + "help.sketch.constraint.perpendicular": "Змушує дві прямі сходитися під прямим кутом. Використовуйте для прямих кутів між прямими, що не лежать на осях ескізу.", + "help.sketch.constraint.polygon": "Робить замкнений ланцюг прямих правильним багатокутником: рівні сторони, а кожен кут лежить на одному колі. Використовуйте, щоб зробити накреслений від руки багатокутник правильним і зберегти це.", + "help.sketch.constraint.symmetry": "Робить дві точки чи криві дзеркальним відображенням одна одної відносно прямої або точки. Використовуйте, щоб профіль залишався симетричним, коли ви змінюєте одну зі сторін.", + "help.sketch.constraint.tangent": "Змушує дві криві дотикатися по дотичній, наприклад пряму й дугу. Використовуйте для плавних сполучень без зламу.", + "help.sketch.construction": "Перемикає криві між звичайною та конструкційною геометрією, яку профілі не враховують. Використовуйте конструкційні криві як допоміжні для розмітки, орієнтирів і розмірів.", + "help.sketch.construction_line": "Створює нескінченну допоміжну пряму через дві точки. Використовуйте її для розмітки ескізу без розбиття профілів.", + "help.sketch.construction_line.angle": "Створює нескінченну допоміжну пряму під кутом до осі X ескізу. Виберіть точку й введіть кут або виберіть її напрямок.", + "help.sketch.construction_line.bisector": "Виберіть дві прямі ескізу, що перетинаються, а потім одну з двох бісектрис. Результат змінюється разом із вихідними прямими.", + "help.sketch.construction_line.horizontal": "Створює нескінченну горизонтальну допоміжну пряму через точку. Її горизонтальне обмеження зберігається під час подальших змін.", + "help.sketch.construction_line.parallel": "Виберіть пряму ескізу, потім розмістіть паралельну нескінченну допоміжну пряму. Клацніть правою кнопкою, щоб вибрати інший опорний об'єкт.", + "help.sketch.construction_line.perpendicular": "Виберіть пряму ескізу, потім розмістіть перпендикулярну нескінченну допоміжну пряму. Клацніть правою кнопкою, щоб вибрати інший опорний об'єкт.", + "help.sketch.construction_line.tangent_at": "Створює дотичну в точці кола чи кругової дуги або в кінцевій точці відкритого сплайна чи конічної кривої. Виберіть криву, потім точку дотику.", + "help.sketch.construction_line.tangent_external": "Виберіть коло або кругову дугу, потім зовнішню точку й варіант дотичної. У попередніх переглядах показано лише точки дотику на намальованій дузі.", + "help.sketch.construction_line.tangent_two": "Виберіть два кола або кругові дуги, потім виберіть спільну дотичну в попередньому перегляді. Точки дотику мають лежати на намальованих кривих.", + "help.sketch.construction_line.vertical": "Створює нескінченну вертикальну допоміжну пряму через точку. Її вертикальне обмеження зберігається під час подальших змін.", + "help.sketch.copy": "Копіює вибрані криві й точки ескізу разом з обмеженнями та розмірами між ними. Вставте їх у цей ескіз або в інший.", + "help.sketch.create": "Починає новий 2D-ескіз на площині або на плоскій грані моделі. Кожне видавлювання, обертання й протягування починається з ескізу.", + "help.sketch.cut": "Копіює вибрану геометрію ескізу й видаляє її з ескізу одним кроком скасування. Вставте її в іншому місці цього ескізу або в інший.", + "help.sketch.dimension": "Додає керівний розмір: довжину, відстань, кут, радіус чи діаметр залежно від вибраного. Введіть значення або назву параметра, і ескіз підлаштується.", + "help.sketch.edit": "Відкриває наявний ескіз для редагування. Операції, побудовані на ньому, оновлюються, коли ви завершуєте ескіз.", + "help.sketch.ellipse": "Малює еліпс за його центром, кінцем великої осі та точкою на малій стороні. Використовуйте для овальних отворів, кулачків та інших видовжених округлих форм.", "help.sketch.equation_curve": "Створює криву за параметричними рівняннями X(t), Y(t) у площині ескізу.", + "help.sketch.extend": "Подовжує пряму чи дугу до найближчої кривої на її шляху або нарощує дві криві, доки вони не зустрінуться. Використовуйте, щоб закрити проміжки в профілі після обрізання чи редагування.", + "help.sketch.fillet": "Заокруглює кут, де сходяться дві прямі чи дуги, дугою заданого радіуса. Кілька кутів, заокруглених разом, мають один радіус.", + "help.sketch.finish": "Виходить з ескізу й повертається до моделі. Його замкнені профілі стають готовими до «Видавлювання», «Обертання» й інших операцій.", + "help.sketch.finish_auto_constrain": "Виконує «Автообмеження» для ескізу, а потім завершує його. Використовуйте, щоб залишити ескіз повністю визначеним одним кроком.", + "help.sketch.fit_curves_to_section": "Розрізає тіло сітки чи суцільне тіло площиною ескізу й підганяє прямі та дуги до перерізу. Використовуйте, щоб відновити відскановану чи імпортовану деталь як ескіз, який можна редагувати.", + "help.sketch.include_3d": "Переносить ребра, вершини моделі й криві інших ескізів до цього ескізу як пов'язані посилання, сплющуючи ті, що поза його площиною, на неї. Використовуйте, щоб будувати на геометрії, яка не лежить у площині ескізу.", + "help.sketch.infinite": "Перемикає прямі між звичайними та нескінченними допоміжними прямими, що проходять через увесь вид. Використовуйте їх як орієнтири розмітки, які ніколи не виявляться закороткими.", + "help.sketch.insert_dxf": "Зчитує криві креслення DXF в ескіз, масштабовані, повернуті й розміщені так, як ви задасте. Використовуйте, щоб будувати на 2D-кресленні з іншої програми, наприклад на контурі для лазерного різання.", + "help.sketch.insert_svg": "Зчитує контури малюнка SVG в ескіз, масштабовані, повернуті й розміщені так, як ви задасте. Використовуйте, щоб перетворити логотип або векторний контур на криві, які можна видавити.", + "help.sketch.inspect": "Відкриває звіт про відкритий ескіз: скільки ступенів вільності залишилося і чи він повністю обмежений. Використовуйте його, щоб дізнатися, що ще рухається, перш ніж завершити ескіз.", + "help.sketch.intersect": "Додає криві чи точки, де тіла, грані, ребра або інші ескізи перетинають площину ескізу. Вони залишаються пов'язаними й слідують за моделлю, коли вона змінюється.", + "help.sketch.intersection_curve": "Створює 3D-криві там, де сходяться два тіла чи грані, пов'язані з ними. Використовуйте їх як траєкторії або напрямні, що слідують за моделлю.", + "help.sketch.isoparametric_curve": "Створює 3D-криву, пов'язану з гранню, вздовж напрямку U або V грані через вибрану вами точку. Використовуйте як траєкторію або лінію розділення, що слідує за поверхнею.", + "help.sketch.line": "Малює з'єднані прямі точка за точкою — як розімкнений ланцюг або замкнений контур. Це основний інструмент для більшості профілів.", + "help.sketch.line.midpoint": "Малює пряму від її середини до одного кінця, а другий кінець відображається дзеркально. Використовуйте для прямих, центрованих на точці, наприклад симетричного краю.", + "help.sketch.line3d": "Малює з'єднані прямі між точками в просторі за ввімкненого 3D-ескізу. Використовуйте для траєкторій і рам, що виходять із площини ескізу.", + "help.sketch.mirror": "Віддзеркалює криві й точки ескізу відносно прямої або осі та додає обмеження симетрії. Використовуйте, щоб накреслити половину симетричного профілю й доповнити його.", + "help.sketch.move": "Переміщує або повертає криві й точки ескізу чи їхню копію. Використовуйте, щоб змінити положення геометрії, зберігши її форму й обмеження.", + "help.sketch.offset": "Створює копію ланцюга кривих на заданій відстані з одного чи обох боків. Використовуйте для стінок, контурів і зазорів; відстань залишається розміром, який можна редагувати.", + "help.sketch.paste": "Вставляє в активний ескіз геометрію ескізу, яку ви скопіювали чи вирізали. Розмістіть її в точці або зсуньте на відстань.", + "help.sketch.pattern.circular": "Копіює геометрію ескізу навколо центральної точки по повному колу або на заданий кут. Використовуйте для кіл розташування болтів, спиць і зубів.", + "help.sketch.pattern.rectangular": "Копіює геометрію ескізу рядками й стовпцями із заданими проміжками. Використовуйте для сіток отворів, пазів чи вентиляційних прорізів.", + "help.sketch.point": "Ставить точку ескізу. Використовуйте як орієнтир для розмірів, обмежень, центрів отворів або пізніших операцій.", + "help.sketch.point3d": "Ставить точку в просторі за ввімкненого 3D-ескізу. Використовуйте як орієнтир для 3D-кривих і траєкторій.", + "help.sketch.polygon.circumscribed": "Малює правильний багатокутник навколо кола, розмір якого задано від центра до середини сторони. Використовуйте, коли відомий розмір під ключ, як для шестигранної гайки.", + "help.sketch.polygon.edge": "Малює правильний багатокутник за двома кінцями однієї сторони. Використовуйте, коли відомі довжина й положення сторони.", + "help.sketch.polygon.inscribed": "Малює правильний багатокутник усередині кола, розмір якого задано від центра до кута. Використовуйте, коли відомий розмір між протилежними кутами.", + "help.sketch.project": "Переносить ребра, грані, вершини моделі та криві інших ескізів до цього ескізу, спроєктовані на його площину. Вони залишаються пов'язаними й слідують за моделлю, коли вона змінюється.", + "help.sketch.project_to_surface": "Проєктує криві інших ескізів уздовж нормалі цього ескізу на грань як пов'язані 3D-криві. Використовуйте, щоб нанести логотип, лінію розділення чи траєкторію на криву поверхню.", + "help.sketch.rectangle.center": "Малює прямокутник за центром і одним кутом. Використовуйте для контурів, центрованих на точці, наприклад на початку координат.", + "help.sketch.rectangle.rounded": "Малює прямокутник із чотирма кутами, заокругленими одним радіусом. Використовуйте для пластин, кришок і отворів із заокругленими кутами.", + "help.sketch.rectangle.three_point": "Малює прямокутник за одним краєм і точкою на протилежній стороні. Використовуйте для прямокутників, повернутих під кутом до осей ескізу.", + "help.sketch.rectangle.two_point": "Малює прямокутник за двома протилежними кутами. Використовуйте для контурів пластин, блоків і кишень.", + "help.sketch.scale": "Масштабує криві й точки ескізу на коефіцієнт відносно базової точки. Використовуйте, щоб змінити розмір частини ескізу, не креслячи її знову.", + "help.sketch.slot.arc_center": "Малює дуговий паз заданої ширини вздовж дуги, заданої центром, початком і кінцем. Використовуйте для регулювальних пазів навколо осі повороту.", + "help.sketch.slot.arc_three_point": "Малює дуговий паз заданої ширини вздовж дуги через три точки. Використовуйте, коли траєкторія паза має проходити через задані точки.", + "help.sketch.slot.center_point": "Малює прямий паз заданої ширини від його центра до центра однієї кінцевої дуги. Використовуйте для пазів, центрованих на точці.", + "help.sketch.slot.center_to_center": "Малює прямий паз заданої ширини між центрами двох його кінцевих дуг. Використовуйте для пазів, розмір яких задано від центру до центру, наприклад регулювальних пазів для гвинтів.", + "help.sketch.slot.overall": "Малює прямий паз заданої ширини від одного зовнішнього кінця до іншого. Використовуйте, коли важлива загальна довжина паза.", + "help.sketch.spline.control_point": "Малює кубічний сплайн, форма якого задається контрольними точками, крізь які він не проходить. Використовуйте для плавних, текучих кривих, які ви формуєте переміщенням точок.", + "help.sketch.spline.control_point_5": "Малює сплайн 5-го степеня, форма якого задається контрольними точками. Використовуйте там, де криві мають сполучатися з плавнішою кривизною, наприклад на видимих дизайнерських поверхнях.", + "help.sketch.spline.fit_point": "Малює плавний сплайн, що проходить через кожну розміщену вами точку, розімкнений чи замкнений. Використовуйте, щоб обвести форму через відомі точки.", + "help.sketch.spline3d": "Малює плавну криву в просторі через точки за ввімкненого 3D-ескізу. Використовуйте для траєкторій протягування та прокладання кабелів, що виходять із площини ескізу.", + "help.sketch.spun_profile": "Створює в площині ескізу контур, який тіло описує, обертаючись навколо осі. Використовуйте, щоб отримати силует точеної деталі для обертання чи креслення.", + "help.sketch.text": "Пише текст в ескізі вибраним шрифтом, висотою та під вибраним кутом; його слова можуть залежати від параметрів. Видавіть його або витисніть для написів і підписів.", + "help.sketch.transform": "Масштабує, повертає й переміщує геометрію ескізу відносно центральної точки одним кроком. Використовуйте, щоб одразу змінити положення й розмір виділеного.", + "help.sketch.trim": "Видаляє частину кривої між найближчими перетинами навколо місця, де ви клацнули. Використовуйте, щоб очистити лінії, що накладаються, до замкненого профілю.", "help.solid.align": "Переміщує вибрані тіла так, щоб точка, грань чи площина на них зійшлася з точкою, гранню чи площиною деінде. Використовуйте, щоб притиснути деталь до іншої, не вимірюючи зсуву.", + "help.solid.boundary_fill": "Створює суцільні тіла з областей, обмежених тілами-інструментами, що перекриваються, заповнюючи лише вибрані області. Використовуйте, щоб побудувати форму з простору, який разом обмежують кілька тіл.", + "help.solid.bounding_solid": "Створює прямокутний паралелепіпед, що охоплює вибрані тіла, за потреби із запасом. Використовуйте, щоб побачити габарити деталі або як заготовку, з якої її обробляють.", + "help.solid.box": "Створює куб (паралелепіпед) за довжиною, шириною й висотою від кутової точки або з центром у точці. Використовуйте для швидкого блока, заготовки-заповнювача чи тіла, у якому вирізають елементи.", "help.solid.chamfer": "Зрізає вибрані ребра плоским скосом на заданій відстані. Використовуйте, щоб притупити гострі ребра або полегшити вставляння штифта чи гвинта.", + "help.solid.coil": "Створює гвинтове тіло, наприклад пружину, за діаметром, кількістю витків, висотою чи кроком і круглим або квадратним перерізом. Використовуйте для пружин, спіралей і гвинтових гребенів.", "help.solid.combine": "Об'єднує тіла, вирізає їх із цільового тіла або залишає лише спільний для них об'єм, і може зберегти тіла-інструменти. Використовуйте, щоб з'єднати деталі, вирізати одну форму іншою або знайти, де два тіла перекриваються.", + "help.solid.cone": "Створює конус за колом основи та висотою або усічений конус, коли верх теж має радіус. Використовуйте для конічних звужень, лійок, зенківок і вістер.", + "help.solid.cylinder": "Створює циліндр за радіусом чи діаметром і висотою, що стоїть на точці вздовж осі. Використовуйте для валів, штифтів, бобишок і круглих заготовок.", "help.solid.draft": "Нахиляє вибрані грані на заданий кут відносно нейтральної площини. Використовуйте для литих чи формованих деталей, щоб вони виймалися з форми.", + "help.solid.emboss": "Піднімає профілі ескізу, наприклад текст чи логотип, над гранню або заглиблює їх у неї. Використовуйте для написів, етикеток і маркування на плоских чи округлих гранях.", "help.solid.extrude": "Витягує профіль ескізу в 3D на задану відстань, додаючи або видаляючи матеріал. Використовуйте, щоб перетворити плоский контур на брусок, бобишку або кишеню.", "help.solid.fillet": "Закруглює вибрані ребра плавним круговим переходом заданого радіуса. Використовуйте, щоб пом'якшити гострі ребра для міцності, зручності чи вигляду.", "help.solid.hole": "Просвердлює круглий отвір заданого діаметра в обраній точці на грані. Використовуйте для отворів під гвинти, штифтів та інших простих круглих отворів.", @@ -1403,20 +1653,60 @@ "help.solid.move": "Переміщує або обертає вибрані тіла (чи їхню копію) на задану відстань і кут. Використовуйте, щоб змінити положення тіла або створити друге в іншому місці.", "help.solid.offset_face": "Виштовхує або втягує вибрані грані на задану відстань, а навколишні грані слідують за ними. Використовуйте, щоб зробити стінку товщою, кишеню глибшою, а бобишку вищою без редагування ескізу.", "help.solid.pattern.circular": "Повторює вибрані об'єкти навколо осі задану кількість разів на заданий повний кут. Використовуйте для кіл розташування болтів, спиць, оребрення та зубців.", + "help.solid.pattern.path": "Копіює операції чи тіла вздовж траєкторії ескізу за кількістю та кроком. Використовуйте для отворів уздовж криволінійного ребра чи деталей уздовж напрямної.", "help.solid.pattern.rectangular": "Повторює вибрані об'єкти в одному або двох напрямках із заданими кількістю та кроком. Використовуйте для рядів і сіток отворів, ребер жорсткості, штифтів або ніжок.", + "help.solid.pipe": "Створює круглу трубу вздовж траєкторії з кривих ескізу, суцільну чи порожнисту із заданою товщиною стінки. Використовуйте для труб, дротів, кабелів і напрямних.", "help.solid.press_pull": "Додає або видаляє матеріал, коли ви тягнете грань, або заокруглює ребра, коли тягнете їх. Використовуйте для швидких змін просто на моделі.", "help.solid.remove": "Забирає вибрані тіла з проєкту, починаючи з цієї точки часового ланцюжка; попередні кроки їх зберігають. Використовуйте, щоб відкинути допоміжне тіло, наприклад інструмент різання, який уже не потрібен.", "help.solid.replace_face": "Переносить вибрані плоскі грані на площину або на паралельну грань, і тіло зростає чи зменшується до неї. Використовуйте, щоб вирівняти грань урівень з іншою деталлю або допоміжною площиною.", "help.solid.revolve": "Обертає профіль ескізу навколо осі, утворюючи кругле тіло. Використовуйте для валів, ручок, чаш та будь-яких деталей, круглих навколо осьової лінії.", + "help.solid.rib": "Додає тонку стінку вздовж розімкненої кривої ескізу, що сягає до найближчих граней тіла. Використовуйте, щоб зміцнити стінки й кути, наприклад у формованих чи надрукованих деталях.", "help.solid.scale": "Збільшує або зменшує вибрані тіла на коефіцієнт: однаковий у всіх напрямках або окремий для кожної осі. Використовуйте, щоб змінити розмір імпортованої форми або врахувати усадку.", "help.solid.shell": "Робить тіло порожнистим, залишаючи стінки заданої товщини, і може відкривати вибрані грані. Використовуйте для коробок, кришок та інших тонкостінних деталей.", + "help.solid.sphere": "Створює кулю за радіусом чи діаметром навколо центральної точки. Використовуйте для куль, ручок і заокруглених кінців.", "help.solid.split_body": "Розрізає тіло на окремі тіла площиною, гранню іншого тіла або лінією ескізу. Використовуйте, щоб отримати деталі, які друкуються, обробляються чи фарбуються окремо.", "help.solid.split_face": "Ділить вибрані грані за площиною, гранню іншого тіла або кривими ескізу, не розрізаючи тіла. Використовуйте, щоб надати частині грані власний ухил, колір чи зсув.", "help.solid.sweep": "Протягує профіль ескізу вздовж траєкторії, утворюючи суцільне тіло. Використовуйте для труб, напрямних, ручок і будь-якої деталі зі сталим перерізом, що йде за кривою.", + "help.solid.thread": "Додає метричну різьбу ISO на циліндричну грань — або косметичну, або вирізану в тілі. Використовуйте для болтів, різьбових отворів і надрукованих гвинтових деталей.", + "help.solid.torus": "Створює кільце за великим радіусом навколо його осі та малим радіусом його круглого перерізу. Використовуйте для O-подібних кілець, ручок і круглих намистин.", + "help.solid.web": "Додає тонку стінку вздовж кожної розімкненої кривої ескізу, кожна з яких сягає до найближчих граней тіла. Використовуйте для сітки опорних стінок усередині корпусів і лотків.", + "help.surface.blend": "Створює поверхню, що з'єднує ребра двох тіл, дотичну або неперервну за кривизною до обох. Використовуйте, щоб плавно з'єднати дві поверхні через проміжок.", + "help.surface.boundary": "Створює поверхню, що заповнює контур із двох-чотирьох кривих ескізу або сітку кривих. Використовуйте для вільних панелей, заданих своїми краями.", + "help.surface.extend": "Подовжує поверхню за її краї на відстань або до площини чи грані. Використовуйте, щоб поверхні перекривалися перед обрізанням чи зшиванням.", + "help.surface.extrude": "Видавлює криві чи профілі ескізу на відстань у поверхню — лише стінки, без торців. Використовуйте для тонких стінок і для інструментів різання чи розділення.", + "help.surface.fair": "Згладжує внутрішню частину вільних граней, залишаючи їхні краї на місці. Використовуйте, щоб вирівняти горби й хвилясті відбиття на поверхні.", + "help.surface.loft": "Створює поверхню, що послідовно проходить через два чи більше перерізів, без торців. Використовуйте для оболонок і переходів між різними формами.", + "help.surface.match": "Перебудовує край поверхні так, щоб він сходився з краєм іншого тіла з відповідною дотичністю чи кривизною. Використовуйте, щоб плавно закрити шов між двома поверхнями.", + "help.surface.offset": "Створює копію граней на відстані вздовж їхніх нормалей як нове поверхневе тіло. Використовуйте для оболонок-шкірок, зазорів або іншого боку стінки.", + "help.surface.patch": "Заповнює область ескізу чи замкнений контур ребер гранню, плоскою або плавно вигнутою. Використовуйте, щоб закрити отвори в поверхневому тілі.", + "help.surface.reverse_normal": "Перевертає грані поверхневого тіла, тож їхній зовнішній бік дивиться в інший бік. Використовуйте перед потовщенням чи зшиванням, коли грані спрямовані всередину.", + "help.surface.revolve": "Обертає криві чи профілі ескізу навколо осі в поверхню, без торців. Використовуйте для круглих оболонок, як-от абажури, чаші й сопла.", + "help.surface.ruled": "Створює смугу з прямих ліній від ланцюга ребер уздовж нормалі грані, дотичної або під кутом. Використовуйте для стінок з ухилом, виходів і поверхонь рознімання.", + "help.surface.stitch": "Зшиває поверхневі тіла разом уздовж спільних ребер, утворюючи суцільне тіло, коли вони замикаються. Використовуйте, щоб перетворити набір поверхонь на одне тіло.", + "help.surface.sweep": "Переміщує криві чи профілі ескізу вздовж траєкторії в поверхню, без торців. Використовуйте для ринв, обкладок та інших тонких форм, що йдуть уздовж траєкторії.", + "help.surface.thicken": "Надає поверхневому тілу товщину, перетворюючи його на суцільне. Використовуйте, щоб створювати з поверхонь деталі для друку чи механічної обробки.", + "help.surface.trim": "Розрізає поверхню площиною, іншою поверхнею чи кривими ескізу й залишає вибраний бік. Використовуйте, щоб надати поверхням форми перед зшиванням.", + "help.surface.unstitch": "Розділяє грані тіла на окремі поверхневі тіла; суцільне тіло розпадається на поверхні. Використовуйте, щоб переробляти окремі грані тіла.", + "help.surface.untrim": "Прибирає отвори з грані або повертає її зовнішню межу до природних меж поверхні. Використовуйте, щоб повернути повну поверхню після обрізання.", "help.third_party": "Ліцензії сторонніх компонентів", "help.timeline.compute_all": "Перебудовує кожну операцію часового ланцюжка з початку. Використовуйте, щоб оновити модель і побачити, які операції завершуються помилкою.", "help.timeline.delete": "Видаляє вибрані операції з часового ланцюжка; видалення ескізу видаляє й операції, побудовані на ньому. Використовуйте, щоб прибрати крок, який більше не потрібен.", + "help.timeline.dependents": "Перелічує операції, які буде видалено разом з операцією, і ті, що перестануть працювати без неї. Використовуйте перед видаленням чи зміною операції.", "help.timeline.play": "Відтворює решту операцій по одній, із паузою в півсекунди після кожного перебудування. Виконайте цю команду ще раз або натисніть Esc, щоб зупинити; «Перейти в кінець» переходить одразу.", + "help.view.apply": "Повертає вид до стандартного напрямку, як-от спереду, зверху чи ізометрія, або до збереженого іменованого виду. Використовуйте, щоб дивитися на модель із фіксованого кута.", + "help.view.delete": "Видаляє збережений іменований вид. Модель не змінюється.", + "help.view.fit": "Масштабує й зсуває вид так, щоб уся модель або виділене заповнювала його. Використовуйте, коли модель зникла з поля зору.", + "help.view.grid": "Показує чи ховає сітку у вікні перегляду. Використовуйте як орієнтир розмірів і напрямків під час моделювання.", + "help.view.ground_shadow": "Показує чи ховає тінь моделі на землі. Використовуйте, щоб легше оцінювати висоту й положення.", + "help.view.home": "Повертає вид до головного напрямку й вміщує модель. Використовуйте, щоб швидко повернутися до відомого виду.", + "help.view.list": "Перелічує іменовані види, збережені в проєкті. Використовуйте, щоб знайти вид, який ви зберегли раніше.", + "help.view.navigate": "Повертає, панорамує чи масштабує вид кроками, наприклад на чверть оберту ліворуч. Використовуйте, щоб точно переміщувати камеру замість перетягування.", + "help.view.navigation_bar": "Показує чи ховає панель навігації внизу вікна перегляду. Сховайте її, щоб звільнити місце, або покажіть, щоб мати доступ до інструментів виду мишею.", + "help.view.rename": "Дає збереженому іменованому виду нову назву. Сам вид не змінюється.", + "help.view.save": "Зберігає поточне положення камери як іменований вид у проєкті. Використовуйте, щоб пізніше повернутися до того самого кута, наприклад для знімків екрана.", + "help.view.spin": "Безперервно обертає вид навколо моделі до наступного клацання чи натискання клавіші. Використовуйте, щоб показати модель з усіх боків.", + "help.view.tool": "Фіксує інструмент камери — обертання, панорамування чи масштаб, — тож перетягування лівою кнопкою миші рухає вид, доки ви його не вимкнете. Використовуйте на трекпаді або без середньої кнопки миші.", + "help.view.visual_style": "Перемикає спосіб відображення моделі: затінена з ребрами чи без них, каркас або з прихованими ребрами. Використовуйте каркас, щоб зазирнути всередину, а затінення — для чистого вигляду.", "history.sketch_under_constrained": "Ескіз має {count} ступенів вільності", "history.sketch_under_constrained_one": "Ескіз має {count} ступінь вільності", "hole_presets.confirm_delete": "Підтвердити видалення", @@ -1593,6 +1883,10 @@ "material.selection.mixed": "Різні матеріали", "measure.at": "У точці", "measure.item": "Елемент {number}", + "measure.quick_copied": "Вимірювання скопійовано", + "measure.quick_copy": "Клацніть, щоб скопіювати вимірювання", + "measure.quick_edges": "Ребер: {count}", + "measure.quick_faces": "Граней: {count}", "messages.ago_h": "{n} год тому", "messages.ago_min": "{n} хв тому", "messages.ago_s": "{n} с тому", @@ -1626,6 +1920,7 @@ "nav.hfss.help": "Alt+ліва панорамує, Shift+Alt+ліва масштабує, Ctrl+ліва з порожнього місця обертає", "nav.inventor.help": "Середня панорамує, Shift+середня обертає, Ctrl+середня масштабує, права обертає", "nav.maya.help": "Alt+ліва обертає, Alt+середня панорамує, Alt+права масштабує; середня також панорамує", + "nav.nx.help": "Середня обертає, Shift+середня панорамує (у NX — середня + права), Ctrl+середня масштабує (у NX — середня + ліва); права не рухає камеру", "nav.openscad.help": "Ліва обертає по порожньому місцю, Shift+ліва виділяє рамкою, геометрію ескізу перетягують для редагування; права або середня панорамує, Shift+права або Shift+середня масштабує", "nav.perspective.sketch": "Редагування ескізу використовує ортографічний вид. Завершіть ескіз, щоб увімкнути перспективу.", "nav.right_drag_orbits.help": "Перетягування правою кнопкою миші обертає вид", @@ -1745,6 +2040,11 @@ "not a move": "це не переміщення", "not a number": "не число", "open a sketch first": "спершу відкрийте ескіз", + "parameters.apply_live": "Застосовувати кожну зміну, коли ви залишаєте її поле", + "parameters.apply_live_tip": "Вимкнено: зміни чекають на «Застосувати» або OK, після чого проєкт один раз перебудовується для всіх. «Скасувати» чи Esc відкидає їх.", + "parameters.held": "Змін, що чекають на «Застосувати»: {count}", + "parameters.held_hint": "Змінюйте вирази та одиниці. Зміни чекають на «Застосувати» або OK.", + "parameters.held_one": "1 зміна чекає на «Застосувати»", "parts.automatic_name": "автоматично", "parts.dimension.across_flats": "Розмір під ключ", "parts.dimension.bore": "Діаметр отвору", @@ -1767,6 +2067,8 @@ "parts.family.set_screw": "Установчий гвинт із шестигранним гніздом, плоский кінець", "parts.family.socket_head_cap_screw": "Гвинт із циліндричною головкою та шестигранним гніздом", "parts.family.washer": "Плоска шайба", + "parts.holes": "Отвори (необов'язково)", + "parts.placement_hint": "виберіть один чи кілька отворів, щоб посадити деталь у кожен, або OK розмістить її на початку координат", "pattern.alignment_2": "Вирівнювання 2", "pattern.alignment_hint": "Кількість включає оригінал. Центрування розподіляє копії з обох боків; за парної кількості зміна напрямку визначає бік із додатковою копією.", "pattern.direction_1": "Напрямок 1", @@ -1819,6 +2121,10 @@ "prefs.bottom_centre": "Внизу по центру", "prefs.bottom_right": "Внизу праворуч", "prefs.browser": "Браузер", + "prefs.browser_components_open": "Компоненти розгорнуті з початку", + "prefs.browser_components_open_note": "Кожен компонент у браузері одразу розгорнутий, як раніше, а не згорнутий, доки ви його не розгорнете.", + "prefs.browser_eye_left": "Око поруч зі стрілкою згортання", + "prefs.browser_eye_left_note": "Рядки браузера показують око «показати/приховати» поруч зі стрілкою згортання, як і раніше, а не в стовпці на правому краї рядків.", "prefs.browser_reveal_on_hover": "Показувати в браузері при наведенні", "prefs.browser_show_note": "Налаштування відображення браузера проєкту", "prefs.browser_shown": "Показувати браузер", @@ -1838,6 +2144,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Криві поверхні", "prefs.curves": "Криві поверхні", + "prefs.dark_parts_shading": "Зберігати форму темних деталей", + "prefs.dark_parts_shading_help": "Затінювати вид у лінійному світлі з м'яким заповнювальним світлом неба, щоб темні грані зберігали градієнт, а не ставали чорними", "prefs.dead_zone_note": "Заштрихована смуга — це мертва зона: рух у її межах ігнорується.", "prefs.default": "типово", "prefs.design": "Типові параметри проєкту", @@ -1852,6 +2160,8 @@ "prefs.edges": "Ребра та затінення", "prefs.extend": "Розширення", "prefs.extra_navigation": "Ctrl+перетягування лівою на порожньому місці обертає; утримуйте Space, щоб панорамувати.", + "prefs.extrude_view_isometric": "Повертати вид до ізометрії під час відкриття «Видавлювання»", + "prefs.extrude_view_return": "Повертати попередній вид під час закриття «Видавлювання»", "prefs.follows_os": "Як у системі", "prefs.font": "Шрифт", "prefs.font_fallback": "Символи, яких немає у вибраному шрифті, беруться з вбудованого, тож жоден напис не показує порожній квадрат.", @@ -1867,8 +2177,11 @@ "prefs.graphics_card_auto": "Автоматично", "prefs.graphics_card_missing": "Збережена відеокарта недоступна; використовується режим «Автоматично».", "prefs.graphics_card_restart": "Набуває чинності після перезапуску SolidCraft. Змінна WGPU_ADAPTER_NAME перевизначає цей вибір.", + "prefs.graphics_card_unused": "Збережену відеокарту для цього вікна не використано; використану відеокарту показано в меню Довідка › Про SolidCraft і в рядку стану. Спробуйте «Автоматично» або вкажіть для WGPU_ADAPTER_NAME унікальну частину назви відеокарти.", "prefs.graphics_note": "Обміняйте швидкість на плавність. Кожен варіант показує свій ефект на зразку.", "prefs.graphics_presets_note": "Набори задають наведені нижче параметри разом.", + "prefs.hide_constraint_glyphs_zoomed_out": "Ховати позначки обмежень на віддаленому виді", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Позначки обмежень зникають, коли ескіз віддалено настільки, що вони б захаращували вид. Вимкнено: вони зберігають сталий розмір на екрані за будь-якого масштабу.", "prefs.history": "Історія", "prefs.history_origin_bodies": "Показувати початок координат і тіла вгорі", "prefs.history_origin_bodies_note": "Історія ліворуч або під браузером починається з теки «Тіла» активного компонента та початку координат, з їхніми значками ока й меню, як у браузері. Історія внизу не змінюється.", @@ -1879,6 +2192,8 @@ "prefs.history_sketches_note": "Якщо для «Ескізи» вибрано «Під своєю операцією», Історія ліворуч показує кожен ескіз на один рівень глибше, під першою операцією, побудованою з нього, коли панель достатньо широка для назв. Часовий ланцюжок знизу завжди зберігає порядок створення.", "prefs.history_sketches_under_feature": "Під своєю операцією", "prefs.hold_stop_snapping": "Утримуйте, щоб вимкнути прив'язування", + "prefs.home_fit_size": "Розмір для «Головний вид» і «Вмістити»", + "prefs.home_fit_size_note": "Яку частину виду займає модель, коли її кадрують «Головний вид», «Вмістити», відкритий проєкт або зміна виду в навігаторі, незалежно від того, чи ввімкнено параметр нижче. 100 %: заповнює вид між панелями, компасом і панеллю навігації.", "prefs.icons_only": "Лише піктограми", "prefs.imported_file": "Імпортований файл", "prefs.in_browser": "У браузері", @@ -1887,13 +2202,20 @@ "prefs.interface_language": "Мова інтерфейсу", "prefs.interface_note": "Як виглядає SolidCraft і де розташовані його частини.", "prefs.interval_minutes": "{n} хв", + "prefs.invert_navigator_arrows": "Інвертувати стрілки обертання куба виду", + "prefs.invert_navigator_arrows_note": "Стрілки навколо куба обертають камеру в той бік, куди вказують, як у Fusion та Inventor: стрілка ліворуч вказує праворуч і повертає камеру праворуч. Вимк.: стрілка обертає куб у той бік, де вона розташована, тож ліва стрілка повертає камеру ліворуч. Вигнуті стрілки крену не змінюються.", + "prefs.keep_work_on_tab_switch": "Зберігати відкриті діалоги та інструменти під час перемикання між проєктами", + "prefs.keep_work_on_tab_switch_note": "Кожна вкладка проєкту зберігає свій відкритий діалог чи інструмент разом із тим, що ви в ньому вибрали й ввели, а також свою вкладку панелі інструментів. Вони знову на місці, коли ви повертаєтеся до проєкту. Вимк.: перемикання проєктів скасовує їх і показує вкладку «Модель».", "prefs.labels": "Підписи", + "prefs.language_system": "Системна", "prefs.layout": "Компонування", "prefs.layout_note": "«Компактне» прикріплює панелі до країв вікна. Прозорість браузера доступна в режимі «Плаваюче». Сторону Асистента можна змінити на сторінці «Асистент».", "prefs.left": "Ліворуч", "prefs.left_click": "Клацання лівою", "prefs.line_drag_draws_one": "Перетягування відрізка малює один елемент", "prefs.line_drag_draws_one_note": "Замість безперервного малювання при перетягуванні", + "prefs.line_hover_tangent_arc": "Затриматися на останній точці прямої, щоб перейти до дотичної дуги", + "prefs.line_hover_tangent_arc_note": "В інструменті «Пряма» після того, як сегмент накреслено, відведіть вказівник від останньої точки ланцюжка, поверніться й утримуйте його на ній нерухомо: наступне клацання завершить дотичну дугу, а той самий жест поверне до прямих. Вимк.: затримка там нічого не робить.", "prefs.linked_designs": "Пов'язані проєкти", "prefs.live_input": "Поточне введення", "prefs.live_preview": "Попередній перегляд у реальному часі", @@ -1907,6 +2229,9 @@ "prefs.max_file_size_step": "Файли STEP та імпорту", "prefs.max_file_size_web": "Вебзастосунок відкриває файли STEP та імпорту до 512 МБ і проєкти до 256 МБ: вкладка браузера не вміщує більші файли. У настільному застосунку ці межі можна збільшити.", "prefs.megabytes": "МБ", + "prefs.menu_grid": "Великі піктограми", + "prefs.menu_list": "Список", + "prefs.menus": "Меню", "prefs.minutes": "хв", "prefs.minutes_suffix": " хв", "prefs.mouse": "Миша й трекпад", @@ -1914,6 +2239,8 @@ "prefs.mouse_mapping": "Призначення кнопок миші", "prefs.navigation": "Навігація", "prefs.navigation_note": "Як миша, трекпад і 3D-миша рухають вид.", + "prefs.navigator_fit": "Вміщувати модель після зміни виду в навігаторі", + "prefs.navigator_fit_note": "Грань, кут або стрілка куба виду чи вісь гізмо також дивляться на середину моделі з єдиної відстані, з якої її видно цілком з усіх боків (її обмежувальна сфера). «Головний вид» за ввімкненого параметра використовує той самий масштаб і центр, тож види, вибрані після нього, лише повертаються. Вимк.: вид повертається на місці, зберігаючи свою ціль і масштаб.", "prefs.network_host_remove": "Вилучити", "prefs.network_locations": "Дозволяти мережеві розташування в проєктах", "prefs.network_locations_note": "Вимкнено: пов'язані файли проєкту на іншому комп'ютері (\\\\server\\share) відкриваються лише з перелічених тут серверів або після того, як ви дозволите один, коли запитають.", @@ -1926,19 +2253,46 @@ "prefs.origin_plane_names": "Назви площин початку координат", "prefs.origin_plane_names_note": "Назви, що показуються в браузері, діалогах і списках. {top} — це XY, {front} — XZ, {right} — YZ, а Z спрямована вгору. Команди, скрипти й збережені проєкти зберігають XY, XZ і YZ.", "prefs.overall_speed": "Загальна швидкість", + "prefs.parameter_list_rows": "Рядків у списку параметрів", + "prefs.parameter_list_rows_tip": "Стрілка вниз у порожньому полі значення показує список параметрів, спершу обрані, до цієї кількості. Менше число робить список легшим у великому проєкті.", + "prefs.persistent_ribbon_pressed": "Підсвічувати активні команди стрічки", + "prefs.persistent_ribbon_pressed_help": "Підсвічувати команди стрічки, поки їхні ефекти ввімкнені. Вимкніть, щоб зберегти попередній нейтральний вигляд і довідку команд.", "prefs.perspective_fov": "Кут огляду перспективи", "prefs.placement": "Розміщення", "prefs.prefer_free_sketch_points": "Надавати перевагу рухомим точкам ескізу, коли точки перекриваються", "prefs.preview_choices": "Перегляд ваших виборів", + "prefs.print_face_highlight": "Підсвічування грані друку", + "prefs.print_face_highlight_tip": "Наскільки сильно грань друку тіла зафарбовується й обводиться у вигляді. 0 % — без підсвічування.", + "prefs.profile_active": "Активний профіль", + "prefs.profile_applied": "Профіль застосовано.", + "prefs.profile_changed": "Налаштування змінено після збереження профілю. «Зберегти» додасть їх до профілю.", + "prefs.profile_deleted": "Профіль видалено.", + "prefs.profile_export": "Експортувати…", + "prefs.profile_exported": "Профіль експортовано.", + "prefs.profile_imported": "Профіль імпортовано. Виберіть його в полі «Активний профіль», щоб перейти на нього.", + "prefs.profile_name_hint": "Назва профілю, напр. Ноутбук", + "prefs.profile_rename": "Перейменувати", + "prefs.profile_renamed": "Профіль перейменовано.", + "prefs.profile_save": "Зберегти", + "prefs.profile_saved": "Поточні налаштування збережено в профілі.", + "prefs.profile_skipped": "Профіль застосовано; налаштувань, що зберегли поточне значення: {n} (див. журнал).", + "prefs.profiles": "Профілі налаштувань", + "prefs.profiles_note": "Комбінації клавіш, панель інструментів, навігація, кругове меню та налаштування інтерфейсу, що зберігаються разом під однією назвою й перемикаються одночасно.", "prefs.project_options_dialog": "Діалог параметрів проєкту", "prefs.project_options_dialog_note": "Відкривати діалог параметрів проєкту замість бічної панелі", "prefs.quality_default": "типово", "prefs.quality_fastest": "найшвидше", "prefs.quality_slowest": "найповільніше", "prefs.quality_smoother": "плавніше", + "prefs.quick_measure": "Швидке вимірювання в куті виду", + "prefs.quick_measure_note": "Розмір виділеного в нижньому правому куті виду: довжина ребра або Ø і R для круглого, площа грані, положення точки, відстань і кут між двома елементами, сума для кількох ребер чи граней. Клацання копіює його.", "prefs.render_previous_geometry_budget": "Бюджет попередньої геометрії для візуалізації", "prefs.render_previous_geometry_budget_help": "Максимальний обсяг пам'яті для кешу геометрії попереднього стану", "prefs.reports_saved": "Збережено: {n}", + "prefs.ribbon_click_ends_tool": "Клацання кнопки запущеного інструмента завершує його", + "prefs.ribbon_click_ends_tool_note": "Клацання підсвіченої кнопки використовуваного інструмента ескізу на стрічці завершує інструмент, тож клацання на виді знову виділяють об'єкти. Вимк.: клацання знову запускає інструмент.", + "prefs.ribbon_reveal": "Показувати результати пошуку на стрічці", + "prefs.ribbon_reveal_note": "Наведення курсора на результат у «Пошуку команд» показує, де команда розташована на стрічці: її вкладку, кнопку або рядок у випадному меню панелі. Команда, запущена з пошуку, блимає там, а запущена команда з випадного меню позначає свою панель.", "prefs.right_click": "Клацання правою", "prefs.saving": "Автозбереження й відновлення", "prefs.scale_note": "Також Ctrl + / Ctrl − у вікні. Кнопки мають 28 px за 100%.", @@ -1947,6 +2301,8 @@ "prefs.search_empty": "Немає відповідних налаштувань", "prefs.select": "Вибрати", "prefs.select_one_item": "Вибрати один елемент", + "prefs.select_other_hidden": "Вибирати приховану геометрію через «Вибрати інше»", + "prefs.select_other_hidden_help": "Увімкнено: до списку входять приховані тіла, ескізи та затулені ребра поблизу вказівника. Вимкнено: використовується початковий список видимої геометрії під вказівником.", "prefs.selecting": "Вибір", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift лише додає; Ctrl / Cmd перемикає", @@ -1958,11 +2314,18 @@ "prefs.sketch_align_points_note": "Автоматично вирівнювати точки при наближенні", "prefs.sketch_conflict_colour": "Конфліктна геометрія кольором конфлікту", "prefs.sketch_conflict_colour_note": "Поки обмеження ескізу суперечать одне одному, криві та точки, які утримує проблемне обмеження, також малюються кольором конфлікту, а не лише його піктограма чи розмір. Вимкнено: вони зберігають свої звичайні кольори.", + "prefs.sketch_construction_lines": "Розширені інструменти допоміжних прямих", "prefs.sketch_exit_view": "Коли ескіз завершується", "prefs.sketch_exit_view.keep": "Зберегти поточний вид", "prefs.sketch_exit_view.previous": "Повернутися до попереднього виду", "prefs.sketch_exit_view.unless_rotated": "Повернутися, якщо вид не оберталося", "prefs.sketch_exit_view_note": "Куди переходить вид після «Завершити ескіз», «Скасувати» або подвійного Esc.", + "prefs.sketch_face_activates_part": "Ескіз на грані деталі робить цю деталь активною", + "prefs.sketch_face_activates_part_note": "Ескіз, розпочатий на грані тіла іншого компонента, спершу активує цей компонент, тож ескіз належить йому й у браузері залишається з цією деталлю. Після цього деталь залишається активною. Вимк.: ескіз належить активному компоненту.", + "prefs.sketch_open_look_at": "Повертати вид до ескізу під час його відкриття", + "prefs.sketch_open_look_at_note": "Вимкнено: створення чи редагування ескізу не змінює вид. «Наведення» повертає вид до ескізу, коли ви цього захочете.", + "prefs.sketch_recent_snap": "Автоприв'язка до нещодавніх центрів і середніх точок", + "prefs.sketch_recent_snap_note": "Під час креслення курсор прив'язується до місця, де перетинаються допоміжні лінії двох останніх центрів кіл або середніх точок прямих відрізків. Вимкнено: ці лінії лише показуються, а курсор не зсувається.", "prefs.sketch_selection": "Ескіз і вибір", "prefs.sketch_selection_heading": "Ескіз і вибір", "prefs.sketch_selection_note": "Як ескізи прив'язуються й як клацання вибирають.", @@ -1972,6 +2335,8 @@ "prefs.sketch_tab_always_note": "Вкладка «Ескіз» залишається на стрічці одразу після вкладки «Модель», поки жоден ескіз не відкрито. Її інструменти креслення тоді запускають ескіз на вибраній площині чи грані або на площині, яку ви виберете далі, з уже готовим інструментом.", "prefs.sketch_tracking_guides": "Допоміжні лінії вирівнювання за центром і середньою точкою", "prefs.sketch_tracking_guides_note": "Наведіть курсор на центр кола або середню точку прямого відрізка, потім рухайте курсор горизонтально чи вертикально, щоб показати тимчасову пунктирну допоміжну лінію.", + "prefs.sketch_tracking_points": "Допоміжні лінії вирівнювання від кінцевих точок і кутів під час креслення", + "prefs.sketch_tracking_points_note": "Поки інструмент креслення очікує точку, наведення курсора на кінець прямої чи дуги, кут прямокутника або вільну точку показує таку саму тимчасову пунктирну допоміжну лінію, як і для центра чи середньої точки. Вимкнено: лише центри та середні точки.", "prefs.sketching": "Ескізування", "prefs.snap_drawing_note": "Під час малювання або перетягування точки ескізу.", "prefs.source": "Джерело", @@ -1988,6 +2353,24 @@ "prefs.status_error": "Помилка", "prefs.status_selected": "Вибрано", "prefs.status_warning": "Попередження", + "prefs.structure.appearance": "Вигляд", + "prefs.structure.appearance_note": "Кольори, текст і спеціальні можливості.", + "prefs.structure.in_profile": "У профілі", + "prefs.structure.layout": "Компонування", + "prefs.structure.layout_note": "Де розташовані частини вікна.", + "prefs.structure.look": "Оформлення", + "prefs.structure.measure_pointer": "Вимірювання та вказівник", + "prefs.structure.mouse3d": "3D-миша", + "prefs.structure.mouse3d_note": "SpaceMouse і SpaceNavigator.", + "prefs.structure.navigation_note": "Миша й трекпад. У 3D-миші є власна сторінка.", + "prefs.structure.profile": "Профіль", + "prefs.structure.profile_edited": "Змінено після збереження", + "prefs.structure.profile_hover": "Збережено в профілях налаштувань", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Ескіз", + "prefs.structure.tools": "Інструменти", + "prefs.structure.tools_note": "Як поводяться інструменти моделювання.", + "prefs.structure.work": "Робота", "prefs.supersampling_brief": "Малює вид у більшому розмірі й зменшує його: дуже чітко, але потребує більше ресурсів.", "prefs.tab_accent_note": "Акцентний колір відповідає активній вкладці", "prefs.theme_file": "файл теми", @@ -1999,6 +2382,16 @@ "prefs.theme_follow_off": "Вимк.", "prefs.theme_follow_stop": "Припинити відстеження", "prefs.theme_import_hint": "Клацніть, щоб вибрати файл теми, перетягніть його сюди або натисніть Ctrl+V (Cmd+V на Mac) зі скопійованою темою", + "prefs.theme_option_opacity": "Непрозорість", + "prefs.theme_option_opacity_help": "Налаштуйте непрозорість плаваючих панелей. Нижня межа читабельності захищає текст на кольорах вікна перегляду.", + "prefs.theme_option_tab_colours": "Кольори вкладок", + "prefs.theme_option_tab_colours_help": "Використовувати кольори панелей і вікна перегляду цієї теми для кожної вкладки стрічки.", + "prefs.theme_option_tab_fade_ms": "Перехід між вкладками", + "prefs.theme_option_tab_fade_ms_help": "Плавно змінювати кольори панелей і вікна перегляду під час перемикання вкладок. Нуль перемикає миттєво.", + "prefs.theme_options_badge": "Параметри", + "prefs.theme_options_more": "Ще · {count}", + "prefs.theme_options_reset": "Скинути", + "prefs.theme_options_unavailable": "Недоступно на цьому пристрої", "prefs.theme_paste": "Вставити тему", "prefs.theme_paste_none": "У буфері обміну немає теми SolidCraft", "prefs.timeline_half_hour": "−30 хв", @@ -2020,13 +2413,23 @@ "prefs.under_cursor": "Під курсором", "prefs.units_precision": "Одиниці й точність", "prefs.updates": "Оновлення", + "prefs.value_boxes_in_view": "Показувати значення біля їхніх маркерів на виді", + "prefs.value_boxes_in_view_tip": "Значення команди (Відстань, Радіус…) у полі біля її маркера, поверх моделі. Вимкнено: ви вводите його у вікні команди, яке після вибору отримує клавіатуру, і ніщо не закриває модель.", "prefs.view": "Поведінка виду", "prefs.view_confirm_corner": "OK і Скасувати в куті виду", "prefs.view_confirm_corner_note": "Поки відкрито діалог або ескіз, галочка й хрестик у правому верхньому куті виду роблять те саме, що OK і Скасувати в діалозі, або завершують і скасовують ескіз. Навігатор виду зсувається нижче.", "prefs.viewport": "Вікно перегляду", + "prefs.viewport_analysis_status": "Показувати стан аналізу у вікні перегляду", + "prefs.viewport_analysis_status_help": "Показувати активні аналізи над вікном перегляду, відкривати їхні легенди з кожного елемента, а Esc вимикає найновіший аналіз. Вимкніть, щоб повернути легенди в кутах і попередню поведінку Esc.", "prefs.viewport_background": "Фон вікна перегляду", "prefs.viewport_background_colour": "Колір", "prefs.viewport_background_theme": "Градієнт теми", + "prefs.viewport_section_status": "Показувати стан перерізу у вікні перегляду", + "prefs.viewport_section_status_help": "Показувати налаштування перерізу у вікні перегляду. Escape і активна кнопка стрічки вимикають його. Вимкніть, щоб зберегти попередні елементи керування перерізом.", + "prefs.viewport_status_details": "Інтерактивні подробиці вікна перегляду", + "prefs.viewport_status_details_help": "Редагуйте налаштування активного аналізу та перерізу в стандартних картках подробиць. Вимкніть, щоб повернути легенди аналізу лише для читання та діалог «Переріз».", + "prefs.viewport_status_summary": "Згортати елементи рядка стану", + "prefs.viewport_status_summary_help": "Згортати три й більше елементів рядка стану в один зведений значок. Вимкніть, щоб залишити всі елементи в повному рядку.", "prefs.wheel": "Колесо", "prefs.wheel_trackpad": "Колесо й трекпад", "prefs.workspace": "Робоча область", @@ -2036,6 +2439,10 @@ "properties.title": "Властивості: {name}", "recovery.days_ago": "{count} дн. тому", "recovery.detail": "{file} · елементів: {features} · автозбережено {when}", + "recovery.discard_all": "Відхилити все", + "recovery.discard_all_detail": "Цю дію не можна скасувати.", + "recovery.discard_all_title": "Відхилити автозбережень: {count}?", + "recovery.discard_all_title_one": "Відхилити 1 автозбереження?", "recovery.hours_ago": "{count} год тому", "recovery.just_now": "щойно", "recovery.min_ago": "{count} хв тому", @@ -2901,7 +3308,9 @@ "render.output_ready": "Готово до рендерингу", "render.output_run_check": "Запустити перевірку", "render.output_size_limit": "{method}: до {dimension} px на сторону та {pixels} пікселів. Найбільший придатний розмір: {width} × {height}.", + "render.output_size_method_profile": "Щоб візуалізувати {width} × {height}, виберіть {method} із профілем ресурсів CPU {profile} або менший розмір.", "render.output_size_ok": "Розмір допустимий · {width} × {height} px", + "render.output_size_profile": "Щоб візуалізувати {width} × {height}, виберіть профіль ресурсів CPU {profile} або менший розмір.", "render.output_swap_orientation": "Поміняти місцями ширину та висоту", "render.output_tools_inspector": "Змініть розмір і формат в інспекторі «Вивід».", "render.output_view_image": "Переглянути зображення", @@ -3114,6 +3523,7 @@ "render.size_custom": "Власний…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · потрібен {profile}", "render.size_presets": "Набори розмірів", "render.size_presets_pending": "З'явиться разом із редактором виведення", "render.size_preview": "Попередній перегляд", @@ -3401,6 +3811,24 @@ "sheet.flange_type_contour": "Контур", "sheet.flange_type_edge": "Ребро", "sheet.no_body": "немає листового тіла: створіть його через Фланець > Основа або перетворіть пластину на листовий метал командою «Перетворити на листовий метал» (виберіть її велику плоску грань)", + "sheet.personal_rules.confirm_delete": "Підтвердити видалення", + "sheet.personal_rules.delete": "Видалити", + "sheet.personal_rules.delete_prompt": "Видалити це особисте правило? Правила, що вже є в проєктах, не зміняться.", + "sheet.personal_rules.full": "Особиста бібліотека вже містить 64 правила.", + "sheet.personal_rules.invalid_name": "Введіть коротку назву без розривів рядка та керівних символів.", + "sheet.personal_rules.invalid_values": "Заповніть значення правила: кожне має обчислюватися в цьому проєкті, з додатною товщиною та коефіцієнтом K від 0 до 1.", + "sheet.personal_rules.missing": "Вибране особисте правило більше недоступне.", + "sheet.personal_rules.name": "Назва правила", + "sheet.personal_rules.name_exists": "Особисте правило з такою назвою вже існує. Використайте іншу назву.", + "sheet.personal_rules.name_hint": "Унікальна назва", + "sheet.personal_rules.overwrite": "Зберегти зміни у вибраному особистому правилі", + "sheet.personal_rules.rename": "Перейменувати", + "sheet.personal_rules.rule": "Особисте правило", + "sheet.personal_rules.save": "Зберегти як нове", + "sheet.personal_rules.scope": "Зберігається у вашому профілі для всіх проєктів.", + "sheet.personal_rules.select": "Виберіть правило", + "sheet.personal_rules.title": "Особисті правила", + "sheet.personal_rules.unsupported": "Це правило має значення, які ця версія не може використати.", "shortcut.json_error": "параметри мають бути у форматі JSON: {error}", "shortcut.no_command": "команду `{id}` не знайдено; текст перед JSON має бути ID команди", "shortcut.pin": "Закріпити вгорі поля S", @@ -3437,8 +3865,10 @@ "sketch_text.align_right": "Праворуч", "sketch_text.bold": "Жирний", "sketch_text.builtin_font": "{family} (вбудований)", + "sketch_text.formula": "Почніть із =, щоб скласти слова з параметрів: ='W' + number(Width)", "sketch_text.italic": "Курсив", "sketch_text.loading_fonts": "Пошук встановлених шрифтів…", + "sketch_text.no_bold": "Вбудований шрифт не має напівжирного накреслення: виберіть встановлений шрифт", "sketch_text.on_path": "Текст дотримується своєї траєкторії: крива його розміщує", "sketch_text.path_clear": "Зняти текст з його кривої", "sketch_text.path_hint": "Крива ескізу, якої дотримується текст: клацніть тут, а потім на кривій", @@ -3470,10 +3900,7 @@ "the two origins are on the same component": "обидва початки координат належать одному компоненту", "thread.automatic_size": "Автоматичний розмір", "thread.designation": "Позначення", - "thread.direction": "Напрямок різьби", "thread.iso_metric": "Метрична ISO", - "thread.left_hand": "Ліва", - "thread.right_hand": "Права", "thread.select_size": "Вибрати розмір", "timeline.delete_after_marker_one": "Видалити 1 операцію після маркера історії", "timeline.delete_after_marker_other": "Видалити операції після маркера історії: {count}", @@ -3577,6 +4004,8 @@ "ui.3d_mouse_section": "3D-миша", "ui.3d_mouse_show_in_view": "Показувати 3D-мишу в 3D-вигляді", "ui.3d_mouse_show_in_view_tip": "Зображення вашої 3D-миші в лівому нижньому куті, що рухається разом із нею.", + "ui.3d_mouse_sketch_orbit": "Повертати ескізи 3D-мишею", + "ui.3d_mouse_sketch_orbit_tip": "3D-миша також повертає вид, поки ескіз відкрито й ви дивитеся на нього прямо, так само, як і звичайна миша. Вимкнено: вона панорамує та масштабує ескіз, доки ви не нахилите вид.", "ui.3d_mouse_skip": "Мій пристрій так не вміє", "ui.3d_mouse_skip_tip": "Пропускає цей рух в обидва боки; калібрування його не враховує.", "ui.3d_mouse_speed": "Швидкість 3D-миші", @@ -3605,6 +4034,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Поверніть ковпачок проти годинникової стрілки, утримайте й відпустіть.", "ui.3d_mouse_switch_cap": "Калібрувати як повернення до центру", "ui.3d_mouse_switch_trackball": "Калібрувати як трекбол", + "ui.3d_mouse_use_direct": "Використати прямий драйвер", + "ui.3d_mouse_use_direct_tip": "Читати 3D-мишу напряму (hidraw), а не через spacenavd.", "ui.3d_mouse_view_axis": "Вісь вигляду", "ui.3d_mouse_view_off": "Вимк.", "ui.3d_mouse_view_off_tip": "Профіль драйвера 3D-миші вимикає цю вісь, тож її рух не рухає вигляд. Якщо вибрати тут рух іншої осі, вони поміняються місцями, і цей рух перестане рухати вигляд.", @@ -3643,6 +4074,7 @@ "ui.agent_chat_auth_terminal": "Виконайте це в терміналі, а потім знову натисніть «Під'єднатися»:", "ui.agent_chat_auth_title": "Вхід до агента", "ui.agent_chat_cancel": "Скасувати", + "ui.agent_chat_cannot_start": "Встановлено, але не запускається: {error}", "ui.agent_chat_changes": "Зміни: {n}, один крок скасування", "ui.agent_chat_changes_n": "Змін: {n}", "ui.agent_chat_changes_of": "{n}/{limit} змін", @@ -3735,9 +4167,12 @@ "ui.agent_chat_queued_stopped": "У черзі (зупинено, не надіслано)", "ui.agent_chat_refresh": "Оновити", "ui.agent_chat_refused": "Не дозволено для агента: {reason}", + "ui.agent_chat_reinstall": "{agent} встановлено ({program}), але він не запустився, коли SolidCraft його перевіряв: {error}\nЙого встановлення могло бути неповним або зробленим для іншого типу комп'ютера. Встановіть його знову командою `{install}`, перевірте в терміналі, що він виводить свою версію, а потім натисніть «Оновити».", "ui.agent_chat_remove": "Прибрати з черги", "ui.agent_chat_remove_file": "Прибрати з цього повідомлення", "ui.agent_chat_remove_imported": "Прибрати з цього повідомлення; деталь залишається в проєкті (скасування її прибирає)", + "ui.agent_chat_reply_cut_off": "Відповідь досягла обмеження довжини, не закінчившись, тож вона може бути неповною. Попросіть агента продовжити або дати коротшу відповідь.", + "ui.agent_chat_reply_declined": "Модель відмовилася відповідати на це повідомлення.", "ui.agent_chat_retry": "Повторити", "ui.agent_chat_right": "Праворуч", "ui.agent_chat_save": "Зберегти", @@ -3796,12 +4231,17 @@ "ui.ai_copy_suffix": "копія", "ui.ai_custom_url": "Власна URL-адреса", "ui.ai_default": "Типовий", + "ui.ai_edit": "Редагувати", + "ui.ai_edit_agent_title": "Редагувати агента", + "ui.ai_edit_gone": "Цього агента видалено, тож зберігати нічого.", + "ui.ai_edit_tip": "Змініть назву, команду або кінцеву точку цього агента. Збережений ключ залишається прихованим.", "ui.ai_http_busy": "кінцева точка зайнята або перевищила ліміт; спробуйте пізніше", "ui.ai_http_key": "кінцева точка відхилила ключ: перевірте його в Налаштування > ШІ", "ui.ai_http_not_found": "немає такої кінцевої точки чи моделі: перевірте базову URL-адресу й назву моделі", "ui.ai_http_too_large": "розмова завелика для цієї кінцевої точки; почніть новий чат", "ui.ai_key": "Ключ API", "ui.ai_key_hint": "необов'язково; зберігається в системному сховищі ключів", + "ui.ai_key_keep_hint": "залиште порожнім, щоб зберегти наявний ключ", "ui.ai_key_needs_https": "Ключ надсилається лише через HTTPS або на цей комп'ютер.", "ui.ai_key_note": "Зберігається в системному сховищі ключів, ніколи в налаштуваннях SolidCraft. Залиште порожнім для локального сервера.", "ui.ai_keychain_error": "Системне сховище ключів відмовило: {error}", @@ -3828,11 +4268,15 @@ "ui.ai_permissions": "Дозволи", "ui.ai_preset": "Набір", "ui.ai_protocol": "Протокол", + "ui.ai_reasoning_effort": "Рівень міркувань", + "ui.ai_reasoning_effort_field_hint": "порожньо = типове значення постачальника", + "ui.ai_reasoning_effort_hint": "Необов'язково. Надсилається на кінцеву точку як `reasoning_effort`; допустимі значення залежать від постачальника (наприклад, `low`, `high` або `max`). Значення, яке ви тут задали, SolidCraft ніколи не замінює. Залиште поле порожнім, щоб нічого не надсилати й зберегти типове значення постачальника.", "ui.ai_remove": "Видалити", "ui.ai_request_timed_out": "Модель відповідала довше за {seconds} с. Тайм-аут запиту для цієї кінцевої точки можна збільшити в Налаштування › Асистент.", "ui.ai_request_timeout": "Тайм-аут запиту", "ui.ai_request_timeout_hint": "Скільки може тривати один запит до моделі через цю кінцеву точку: від 30 с до години. Збільште для повільної локальної моделі.", "ui.ai_reset": "Скинути", + "ui.ai_save": "Зберегти", "ui.ai_settings": "Налаштування ШІ…", "ui.ai_show_features": "Показувати функції ШІ", "ui.ai_show_features_note": "Чат з агентом: панель, де агент для програмування, яким ви вже користуєтеся, або обрана вами модельна кінцева точка працює з відкритим проєктом. Вимкнено: немає кнопки ШІ, комбінації клавіш, пункту меню чи панелі, і нічого не шукається та не запускається.", @@ -3921,6 +4365,7 @@ "ui.circle": "Коло", "ui.circular_pattern": "Круговий масив", "ui.clear": "Очистити", + "ui.clear_print_face": "Скинути грань друку", "ui.clear_recent": "Очистити недавні", "ui.clear_the_selection": "Зняти виділення", "ui.click_selects_whole_bodies": "Клацання виділяє тіла цілком", @@ -3955,12 +4400,25 @@ "ui.constant": "Стала", "ui.constraints_conflict": "Конфлікт обмежень", "ui.construction": "Конструкційна", + "ui.construction.angle_hint": "Допоміжна пряма: клацніть точку, потім введіть кут або виберіть напрямок", + "ui.construction.bisector_hint": "Бісектриса: виберіть дві прямі, що перетинаються, потім потрібний варіант", + "ui.construction.common_hint": "Спільна дотична: виберіть два кола/дуги, потім потрібний варіант", + "ui.construction.contact_hint": "Дотична: виберіть коло/дугу або відкритий сплайн/конічну криву, потім точку дотику (криві довільної форми: кінцеві точки)", + "ui.construction.external_hint": "Дотична: виберіть коло або дугу, зовнішню точку, потім потрібний варіант", + "ui.construction.free_hint": "Допоміжна пряма: клацніть дві точки; клацніть правою кнопкою, щоб почати знову", + "ui.construction.point_hint": "Допоміжна пряма: клацніть точку, через яку вона проходить", + "ui.construction.reference_hint": "Допоміжна пряма: виберіть пряму, потім точку; клацніть правою кнопкою, щоб змінити опорний об'єкт", "ui.construction.ribbon_label": "Доп. лінії", "ui.context_menu": "Контекстне меню", + "ui.continuity_crease": "Злам", + "ui.continuity_curvature": "Кривизна", + "ui.continuity_curvature_change": "Зміна кривини", "ui.continuity_g0": "G0 злам", "ui.continuity_g1": "G1 дотичність", "ui.continuity_g2": "G2 кривина", "ui.continuity_gap": "Проміжок", + "ui.continuity_position": "Положення", + "ui.continuity_tangent": "Дотична", "ui.copy": "Копіювати", "ui.corner": "Кут", "ui.corners": "Кути", @@ -3983,6 +4441,7 @@ "ui.dark": "Темна", "ui.default_modelling_orientation": "Типова орієнтація моделювання", "ui.delete": "Видалити", + "ui.delete_select_first": "Спершу виберіть, що видалити: операції, тіла, компоненти або геометрію ескізу", "ui.depth": "Глибина", "ui.design": "Проєкт", "ui.design_properties.author": "Автор", @@ -3997,6 +4456,40 @@ "ui.design_properties.project": "Проєкт", "ui.design_properties.revision": "Редакція", "ui.design_saved": "Збережено в {path}", + "ui.details_access_caption": "Грані показують, чи може інструмент дістатися до них із вибраного напрямку.", + "ui.details_angle": "Кут", + "ui.details_continuity_caption": "Редагуйте вибраний шов. Інші шви зберігають власні налаштування.", + "ui.details_continuity_stale": "Попередня геометрія: повторіть аналіз, щоб редагувати цей шов або показати його в кадрі.", + "ui.details_copy_list": "Копіювати список", + "ui.details_curvature": "Допуск кривизни", + "ui.details_curvature_caption": "Грані розфарбовано за їхнім локальним радіусом кривизни.", + "ui.details_direction": "Напрямок інструмента", + "ui.details_draft_caption": "Грані розфарбовано за їхнім кутом до напрямку витягування.", + "ui.details_edit_seam": "Редагувати шов", + "ui.details_fixture": "Зразок компонента — лише приклад даних", + "ui.details_fixture_caption": "Зразок компонента з ілюстративними значеннями; це не результат для моделі.", + "ui.details_fixture_problem": "Приклад результату з проблемою", + "ui.details_fixture_readout": "Приклад виміряного значення", + "ui.details_flip": "Перевернути", + "ui.details_gap": "Проміжок", + "ui.details_hatch": "Штрихувати перерізані грані", + "ui.details_jump": "Стрибок кривизни", + "ui.details_key": "Легенда", + "ui.details_offset": "Зсув", + "ui.details_plane": "Площина", + "ui.details_pull": "Напрямок витягування", + "ui.details_radius": "Радіус", + "ui.details_readout": "Показання", + "ui.details_samples": "Вибірки", + "ui.details_seam": "{body} · Ребро {edge}", + "ui.details_settings": "Налаштування", + "ui.details_sharp_gap": "Злам або проміжок", + "ui.details_show_all": "Показати всі: {count}", + "ui.details_smooth": "Плавний", + "ui.details_stripes": "Смуги", + "ui.details_target": "Вмістити геометрію", + "ui.details_worst_seams": "Найгірші шви", + "ui.details_zebra_caption": "Відбиті смуги показують, наскільки гладко сполучаються грані.", "ui.diameter": "Діаметр", "ui.dimension": "Розмір", "ui.direct_interaction": "Пряма взаємодія", @@ -4041,6 +4534,7 @@ "ui.edit_in_place_saved_elsewhere": "Деталь збережено в інший файл; збірка досі пов'язана з {name}", "ui.edit_in_place_wait": "Зачекайте, поки завершиться те, що виконується в проєкті", "ui.edit_section_analysis": "Редагувати аналіз перерізу", + "ui.edit_sketch_empty": "Немає ескізів для редагування", "ui.ellipse": "Еліпс", "ui.emboss_wrap_note": "Ортогональні профілі з ліній, дотичні до одного підтримуваного циліндра, обгортаються автоматично. Виберіть стінку, щоб задати ціль.", "ui.end_radius": "Кінцевий радіус", @@ -4051,12 +4545,15 @@ "ui.equation_explicit": "Явна", "ui.equation_form": "Форма", "ui.equation_note": "Змінна — звичайне число: sin(t) сприймає радіани. Результат без одиниць виміру береться в одиницях проєкту.", + "ui.equation_note_range": "Змінна — довжина, як і її діапазон: поєднуйте її з параметрами довжини, а для sin() діліть її на довжину. Результат без одиниць виміру береться в одиницях проєкту.", "ui.equation_parametric": "Параметрична", + "ui.equation_variable_unit": "Змінна має одиниці виміру діапазону", "ui.equation_x_of_t": "X(t)", "ui.equation_y_of_t": "Y(t)", "ui.equation_y_of_x": "Y(x)", "ui.equivalent_radius": "Еквівалентний радіус", "ui.expand": "Розгорнути", + "ui.explode_needs_two_components": "«Рознесений вид» розсовує компоненти, тож у проєкті має бути два чи більше з них («Новий компонент», «Вставити проєкт» або «Створити компоненти з тіл»)", "ui.exportDxf": "Експорт DXF…", "ui.export_ellipsis_keymap": "Експорт…", "ui.export_keymap_tip": "Клавіші, обрані в полі S і панель інструментів як файл", @@ -4217,6 +4714,7 @@ "ui.insert_design.saved_file": "{name} має незбережені зміни, тому вставлено його збережений файл. Збережіть його, потім оновіть зв'язки, щоб перенести зміни.", "ui.insert_design.unsaved": "Незбережені зміни", "ui.inspect": "Перевірити", + "ui.instances": "Екземпляри", "ui.intersect": "Перетин", "ui.isolate": "Ізолювати", "ui.join": "З'єднати", @@ -4225,12 +4723,14 @@ "ui.joints": "З'єднання", "ui.keyboard_shortcuts": "Комбінації клавіш", "ui.language": "Мова", + "ui.lasso_select": "Ласо (перетягніть довільний контур: виділяє все, що повністю всередині)", "ui.layout_compact": "Компактне", "ui.layout_floating": "Плаваюче", "ui.length": "Довжина", "ui.length_decimals": "Знаки після коми для довжин", "ui.light": "Світла", "ui.line": "Пряма", + "ui.line_arc_hint": "Дотична дуга: клацніть у кінці дуги. Знову затримайтеся на останній точці, щоб повернутися до прямих; клацніть правою кнопкою або натисніть Esc, щоб завершити", "ui.link_copies": "Пов'язати однакові копії", "ui.link_copies_keep": "Залишити", "ui.link_copies_link": "Пов'язати", @@ -4319,6 +4819,7 @@ "ui.part_size_shared": "Перебудовує деталь, замінюючи всі додані елементи. Усі входження цього компонента оновлюються.", "ui.paste": "Вставити", "ui.path": "Траєкторія", + "ui.pattern_object_type_tip": "Тіла: суцільні форми, які вибирають на виді або в браузері; кожне копіюється цілком.\nОперації: кроки Історії, як-от видавлювання чи отвір, які вибирають в Історії або на грані, створеній ними; крок повторюється.\nЕскіз не є ні тим, ні іншим: повторіть його криві власним інструментом «Масив» чи «Дзеркало» в ескізі або спершу видавіть його.", "ui.pattern_on_path": "Масив на траєкторії", "ui.perforate_margin_default": "від діаметра", "ui.perforate_pitch": "Крок", @@ -4345,12 +4846,17 @@ "ui.plugins_skipped": "Не вдалося прочитати папок: {count}.", "ui.plugins_version": "{version}", "ui.point": "Точка", + "ui.point_cloud_add_filter": "Додати фільтр…", "ui.point_cloud_auto_range": "Автоматичний діапазон", "ui.point_cloud_color_by": "Колір за", "ui.point_cloud_file_colors": "Кольори з файлу", + "ui.point_cloud_filter_by": "Фільтр за", "ui.point_cloud_height_high": "Найвище", "ui.point_cloud_height_low": "Найнижче", + "ui.point_cloud_legend_filter": "Показане й приховане в легенді вище", "ui.point_cloud_no_file_colors": "У файлі немає кольорів", + "ui.point_cloud_pause": "Пауза", + "ui.point_cloud_play": "Відтворити", "ui.point_cloud_single_color": "Один колір", "ui.point_cloud_size": "Розмір точки", "ui.point_cloud_units": "Одиниці файлу", @@ -4359,6 +4865,11 @@ "ui.polygon": "Багатокутник", "ui.preferences": "Налаштування", "ui.press_a_key": "натисніть клавішу…", + "ui.print_face_body_not_sent": "Тіло цієї грані не надсилається: спершу додайте його до Тіла", + "ui.print_face_cleared": "{body}: грань друку скинуто", + "ui.print_face_input": "Грань друку", + "ui.print_face_pick": "Виберіть плоску грань твердого тіла, щоб зробити її гранню друку", + "ui.print_face_set": "{body}: грань друку задано; «Надіслати в слайсер» кладе тіло на неї", "ui.profile": "Профіль", "ui.profile_plane": "Площина профілю", "ui.profiles": "Профілі", @@ -4374,6 +4885,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Вимірювання…", + "ui.properties.measuring_bodies": "Вимірювання… {done} з {total} тіл", "ui.properties.measuring_failed": "Вимірювання перервано до завершення.", "ui.properties.principal_axis": "Головна вісь {number}", "ui.properties.principal_moments": "Головні моменти", @@ -4422,6 +4934,7 @@ "ui.revolve": "Обертання", "ui.ribbon_exit": "Вихід", "ui.ribbon_labels": "Показувати текст під піктограмами стрічки", + "ui.ribbon_menus_skip_pinned": "Не показувати закріплені команди у випадних меню", "ui.ribbon_pin_footer": "Закріплені команди відображаються на стрічці. Наведіть курсор на рядок, щоб закріпити або відкріпити його.", "ui.ribbon_workspace": "Робоча область", "ui.right": "Справа", @@ -4440,6 +4953,7 @@ "ui.selectOther": "Вибрати інше…", "ui.selectTangentChain": "Вибрати дотичний ланцюг", "ui.select_all": "Виділити все", + "ui.select_components_by_face": "Вибрати компоненти (грань вибирає свій компонент)", "ui.selection": "Виділення", "ui.selection_modifiers": "Модифікатори вибору", "ui.selection_shift_add_only": "Shift+клацання додає без вилучення", @@ -4481,6 +4995,11 @@ "ui.sketch_intersect_selection_filter": "Фільтр вибору", "ui.sketch_modifiers": "Модифікатори ескізу", "ui.sketch_project_geometry": "Геометрія", + "ui.sketch_report.all_constrained": "Усе повністю обмежено.", + "ui.sketch_report.dof": "Ступені вільності", + "ui.sketch_report.loose": "Не повністю обмежено", + "ui.sketch_report.status": "Стан", + "ui.sketch_report.title": "Звіт про ескіз", "ui.sketch_scale": "Масштаб ескізу", "ui.sketches": "Ескізи", "ui.slice": "Розріз", @@ -4576,19 +5095,31 @@ "ui.view_angles": "Кути виду", "ui.view_angles_convention": "Градуси навколо вертикальної осі. Рискання 0° — вид спереду, 90° — зліва, −90° — справа, 180° — ззаду; тангаж 90° — вид зверху; додатний крен повертає модель за годинниковою стрілкою.", "ui.view_angles_help": "Показує тангаж, рискання та крен виду в градусах, а також його проєкцію під елементом орієнтації. Клацніть показник, щоб ввести точні кути.", + "ui.view_angles_lock": "Заблокувати {axis}", "ui.view_angles_ortho": "Орто", "ui.view_angles_persp": "Персп.", "ui.view_angles_pitch": "Тангаж", "ui.view_angles_readout": "Тангаж {pitch} · Рискання {yaw} · Крен {roll}", "ui.view_angles_roll": "Крен", + "ui.view_angles_unlock": "Розблокувати {axis}", "ui.view_angles_yaw": "Рискання", + "ui.view_angles_zero": "Встановити {axis} на 0°", "ui.view_centre": "Центр виду", "ui.viewport_status_clear": "Вимкнути {name}", "ui.viewport_status_clear_hint": "Вимкнути {name} · Esc", + "ui.viewport_status_edges": "Ребер: {count}", + "ui.viewport_status_from": "з напрямку: {direction}", "ui.viewport_status_key": "Показати легенду для {name}", "ui.viewport_status_minimum_radius": "Мінімальний радіус", "ui.viewport_status_pairs": "Пар: {count}", + "ui.viewport_status_section_hatch": "{setting} · штрихування", + "ui.viewport_status_section_plane": "Поточна площина", + "ui.viewport_status_section_tilted": "нахилена · {offset}", "ui.viewport_status_stripes": "Смуг: {count}", + "ui.viewport_status_summary_clear": "Вимкнути все", + "ui.viewport_status_summary_heading": "На цьому виді", + "ui.viewport_status_summary_label": "{name} і ще елементів: {count}", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "За темою", "ui.visual_shaded_hidden_edges": "Затінений із прихованими ребрами", "ui.visual_shaded_with_edges": "Затінений із ребрами", @@ -4625,10 +5156,12 @@ "update.button": "Оновити", "update.button_version": "Оновити до {version}", "update.check_automatically": "Автоматично перевіряти оновлення", + "update.check_for_updates": "Перевірити оновлення", "update.check_now": "Перевірити зараз", + "update.check_unavailable": "Перевірка оновлень недоступна для цього встановлення.", "update.checking": "Перевірка…", "update.copy": "Копіювати", - "update.dmg_opened": "Образ диска відкрито й перевірено: перетягніть SolidCraft до Applications, замінивши стару копію, а потім перезапустіть SolidCraft.", + "update.dmg_opened": "Образ диска відкрито й перевірено: завершіть SolidCraft, перетягніть новий SolidCraft до Applications, замінивши стару копію, а потім знову відкрийте SolidCraft.", "update.download": "Завантажити", "update.download_open": "Завантажити й відкрити", "update.downloading": "Завантаження та перевірка… {done} з {total} МБ", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index eb1aced33..50e390f7f 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "MẶT NỐI MƯỢT", "BOUNDARY SURFACE": "BỀ MẶT BIÊN DẠNG", "BROWSER": "CÂY ĐỐI TƯỢNG", + "Back to the original order": "Trở về thứ tự ban đầu", "Ball": "Cầu", "Bar": "Thép thanh", "Base Center": "Tâm đáy", @@ -378,7 +379,7 @@ "Move Type": "Kiểu di chuyển", "Move down": "Chuyển xuống", "Move earlier": "Di chuyển lên trước", - "Move holes by clicking or dragging": "Di chuyển lỗ bằng cách bấm hoặc kéo rê", + "Move holes by clicking or dragging": "Di chuyển bằng nhấp hoặc kéo", "Move later": "Di chuyển xuống sau", "Move up": "Chuyển lên", "Name": "Tên", @@ -476,6 +477,7 @@ "Rectangular": "Hình chữ nhật", "Rectangular Tube": "Thép hộp chữ nhật", "Reference face": "Bề mặt tham chiếu", + "Reference plane": "Mặt phẳng tham chiếu", "Relief Depth": "Độ sâu rãnh thoát", "Relief Width": "Chiều rộng rãnh thoát", "Remove Tools": "Loại bỏ công cụ cắt", @@ -493,7 +495,8 @@ "Rename Folder": "Đổi tên thư mục", "Render Stage": "Giai đoạn kết xuất", "Reopen designs": "Mở lại thiết kế", - "Reopen the designs that were open when SolidCraft was last closed": "Mở lại các thiết kế đã mở khi đóng SolidCraft lần trước", + "Reopen the designs that were open when SolidCraft was last closed": "Mở lại các thiết kế đã mở lần trước", + "Repair Part": "Sửa chi tiết", "Replace existing library file": "Thay thế tệp thư viện hiện có", "Report a bug — review a screenshot and open a GitHub draft": "Báo cáo sự cố — xem lại ảnh chụp màn hình và mở bản nháp trên GitHub", "Report copied. Keep this text to submit on GitHub when you are online.": "Đã sao chép báo cáo. Hãy giữ lại nội dung này để gửi lên GitHub khi có kết nối mạng.", @@ -555,6 +558,7 @@ "Section": "Mặt cắt", "Section (optional)": "Mặt cắt (tùy chọn)", "Section position": "Vị trí mặt cắt", + "Sections": "Các mặt cắt", "Sections (one sketch each)": "Các mặt cắt (mỗi mặt cắt một phác thảo)", "Select Other": "Chọn đối tượng khác", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Chọn đối tượng khác: giữ nút chuột trái đứng yên trên mô hình (hoặc nhấp chuột phải › Chọn đối tượng khác…) để liệt kê mọi đối tượng dưới con trỏ; nhấp lại vào cùng vị trí đó để chọn đối tượng kế tiếp. Nhấp đúp chuột giữa để về Góc nhìn chuẩn (Tùy chọn cài đặt › Điều hướng).", @@ -581,7 +585,7 @@ "Show ghost": "Hiển thị bóng mờ", "Show in folder": "Hiển thị trong thư mục", "Show the pointer an AI agent moves (#35)": "Hiển thị con trỏ do AI Agent điều khiển (#35)", - "Show tool at cursor": "Hiển thị công cụ cạnh con trỏ", + "Show tool at cursor": "Công cụ tại con trỏ", "Signed axes": "Các trục có dấu (+/-)", "Size": "Kích thước", "Sketch constraints": "Ràng buộc phác thảo", @@ -592,9 +596,11 @@ "Sketch points": "Điểm phác thảo", "Slider": "Trượt", "Slot width": "Bề rộng rãnh then", - "Snap to face and edge centres": "Bắt vào tâm mặt và tâm cạnh", + "Snap to face and edge centres": "Bắt dính vào tâm", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft không thể gửi báo cáo trực tiếp. Hãy gửi trên GitHub; ứng dụng không cần mã truy cập.", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft đã đóng trước khi các thiết kế này được lưu. Bạn có thể mở bản tự động lưu gần nhất của chúng.", + "Sort A to Z": "Sắp xếp từ A đến Z", + "Sort Z to A": "Sắp xếp từ Z đến A", "Spacing 2 must be a non-zero number": "Khoảng cách 2 phải là một số khác 0", "Spacing must be a non-zero number": "Khoảng cách phải là một số khác 0", "Specialise": "Chuyên biệt hóa", @@ -733,36 +739,36 @@ "a picked edge's body is gone": "thân của một cạnh đã chọn không còn nữa", "add a key for a joint first": "hãy thêm một khóa cho khớp trước", "ai.connected_toast": "SolidCraft hiện đã sẵn sàng trong {clients}. Khởi động lại ứng dụng để sử dụng (Cài đặt > Trợ lý ảo).", - "ai.prefs.allow_control": "Cho phép AI agent kết nối (kênh điều khiển / MCP)", - "ai.prefs.allow_control_note": "Mở kênh điều khiển chỉ trên máy tính này (127.0.0.1, cổng 27878 hoặc cổng trống tiếp theo). Chương trình kết nối phải xuất trình mã token bảo mật chỉ tài khoản người dùng của bạn đọc được, được tạo mới mỗi lần khởi động. Có hiệu lực vào lần khởi động tiếp theo của SolidCraft. Khi tắt: không lắng nghe trừ khi bạn bật.", - "ai.prefs.availability": "Điều khiển trợ lý", - "ai.prefs.background_commands": "Chạy các lệnh của agent dưới nền", - "ai.prefs.connect_apps": "Cho phép các ứng dụng AI trên máy tính này kết nối với SolidCraft", - "ai.prefs.connect_apps_note": "Khi SolidCraft khởi động, tự động thêm phần mềm dưới dạng MCP server vào các ứng dụng AI tìm thấy trên máy tính này (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code) để AI agent có thể sử dụng ngay mà không cần cấu hình thủ công. Chỉ mục cấu hình solidcraft sẽ được thêm mới hoặc làm mới đường dẫn; các mục bạn tự tùy chỉnh sẽ được giữ nguyên và file được sao lưu .bak trước khi sửa. Tắt: các mục đã thêm sẽ được gỡ bỏ. Trợ giúp > Kết nối trợ lý ảo AI… để thực hiện thủ công.", - "ai.prefs.connect_at_start": "Kết nối tác tử dùng gần nhất khi SolidCraft khởi động", + "ai.prefs.allow_control": "Cho phép tác nhân AI kết nối", + "ai.prefs.allow_control_note": "Kênh cục bộ (MCP). Không có gì rời khỏi máy tính này.\n\nMở kênh điều khiển chỉ trên máy tính này (127.0.0.1, cổng 27878 hoặc cổng trống tiếp theo). Chương trình kết nối phải xuất trình mã token bảo mật chỉ tài khoản người dùng của bạn đọc được, được tạo mới mỗi lần khởi động. Có hiệu lực vào lần khởi động tiếp theo của SolidCraft. Khi tắt: không lắng nghe trừ khi bạn bật.", + "ai.prefs.availability": "Khả dụng", + "ai.prefs.background_commands": "Chạy lệnh chậm trong nền", + "ai.prefs.connect_apps": "Thêm SolidCraft vào ứng dụng AI", + "ai.prefs.connect_apps_note": "Tắt sẽ xóa các mục đã thêm.\n\nKhi SolidCraft khởi động, tự động thêm phần mềm dưới dạng MCP server vào các ứng dụng AI tìm thấy trên máy tính này (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code) để AI agent có thể sử dụng ngay mà không cần cấu hình thủ công. Chỉ mục cấu hình solidcraft sẽ được thêm mới hoặc làm mới đường dẫn; các mục bạn tự tùy chỉnh sẽ được giữ nguyên và file được sao lưu .bak trước khi sửa. Tắt: các mục đã thêm sẽ được gỡ bỏ. Trợ giúp > Kết nối trợ lý ảo AI… để thực hiện thủ công.", + "ai.prefs.connect_at_start": "Kết nối tác nhân gần nhất khi khởi động", "ai.prefs.connect_at_start_note": "Mỗi lần SolidCraft khởi động, chạy ngầm tác tử bạn kết nối gần nhất (hoặc tác tử mặc định) để sẵn sàng trò chuyện. Không áp dụng khi SolidCraft được khởi động với --control. Nếu không kết nối được, Trợ lý hiển thị “Kết nối thất bại” và nút “Thử lại”.", - "ai.prefs.follow_camera": "Xoay camera theo phác thảo", + "ai.prefs.follow_camera": "Theo camera", "ai.prefs.follow_camera_off": "Tự động xoay camera theo phác thảo đang tắt.", "ai.prefs.follow_camera_on": "Camera sẽ tự động xoay vuông góc với phác thảo do agent tạo.", - "ai.prefs.intro": "Thiết lập agent, quyền hạn và cách hiển thị kết quả.", + "ai.prefs.intro": "Tác nhân AI trong SolidCraft.", "ai.prefs.make_default": "Đặt làm mặc định", "ai.prefs.no_agents": "Chưa có agent nào. Thêm một agent hoặc làm mới để tìm các agent đã cài đặt.", "ai.prefs.no_saved_approvals": "Chưa có phê duyệt nào được lưu.", - "ai.prefs.open_at_start": "Mở bảng Trợ lý khi SolidCraft khởi động", + "ai.prefs.open_at_start": "Mở trò chuyện khi khởi động", "ai.prefs.open_at_start_note": "Hiển thị bảng Trợ lý (hoặc cửa sổ riêng của nó) mỗi lần SolidCraft khởi động. Không áp dụng khi SolidCraft được khởi động với --control.", "ai.prefs.override_all_warning": "Agent này có thể lưu, ghi đè, xuất hoặc thay thế thiết kế mà không cần hỏi trước.", - "ai.prefs.permission_all": "Cho phép tất cả", - "ai.prefs.permission_all_summary": "Các công cụ SolidCraft khả dụng sẽ chạy mà không cần hỏi trước.", - "ai.prefs.permission_ask": "Hỏi trước khi thay đổi", - "ai.prefs.permission_ask_summary": "Phê duyệt từng thay đổi thiết kế và thao tác với tệp.", - "ai.prefs.permission_edits": "Cho phép chỉnh sửa mô hình", - "ai.prefs.permission_edits_summary": "Các thao tác chỉnh sửa mô hình tự động chạy; thao tác với tệp và tác vụ phá hủy vẫn cần hỏi.", + "ai.prefs.permission_all": "Làm mọi việc", + "ai.prefs.permission_all_summary": "Không bao giờ hỏi", + "ai.prefs.permission_ask": "Hỏi trước", + "ai.prefs.permission_ask_summary": "Hỏi trước mọi thay đổi", + "ai.prefs.permission_edits": "Cho phép chỉnh sửa", + "ai.prefs.permission_edits_summary": "Tự do chỉnh sửa, hỏi về việc còn lại", "ai.prefs.permission_scope": "Chỉ áp dụng cho các công cụ SolidCraft. Thao tác dòng lệnh và tệp của agent sử dụng quyền riêng của nó.", "ai.prefs.pointer_preview_hidden": "Con trỏ đang ẩn", "ai.prefs.pointer_preview_speed": "Con trỏ agent • {speed}", - "ai.prefs.pointer_speed": "Tốc độ di chuyển", + "ai.prefs.pointer_speed": "Tốc độ", "ai.prefs.privacy_note": "Chỉ agent hoặc endpoint bạn đã chọn mới nhận được nội dung trò chuyện. Khóa API endpoint được lưu trong chuỗi khóa (keychain) hệ thống.", - "ai.prefs.show_pointer": "Hiển thị con trỏ agent", + "ai.prefs.show_pointer": "Hiện con trỏ của tác nhân", "ai.prefs.turn_limit_hint": "Số lượt gọi công cụ thay đổi thiết kế tối đa mà Trợ lý có thể thực hiện cho một tin nhắn.", "angle, height": "góc, chiều cao", "appearance.dielectric_ior": "Chỉ số khúc xạ điện môi (IOR)", @@ -785,11 +791,19 @@ "browser.edit_canvas_title": "Sửa ảnh nền Canvas: {name}", "browser.edit_point_cloud_title": "Chỉnh sửa đám mây điểm: {name}", "browser.move_title": "Di chuyển: {name}", + "browser.needs_repair": "{name}: cần sửa", "browser.parameters": "Bảng tham số ({count})", "browser.precision": "Độ chính xác: {precision}", "browser.sketch_attachment_lost": "{name} (mất liên kết)", "browser.sketch_editing": "{name} (đang sửa)", "browser.sketch_name": "Phác thảo{number}", + "browser.sketches_to_parts_already_in_part": "đã ở trong chi tiết của chúng", + "browser.sketches_to_parts_design_body": "nằm trên một khối của chính thiết kế", + "browser.sketches_to_parts_moved": "Đã chuyển {moved} bản phác thảo vào chi tiết chứa chúng", + "browser.sketches_to_parts_no_exact_attachment": "nằm trên mặt không có liên kết chính xác", + "browser.sketches_to_parts_not_on_face": "không nằm trên mặt của một chi tiết", + "browser.sketches_to_parts_part_missing": "chi tiết của chúng không còn", + "browser.sketches_to_parts_result": "Đã chuyển {moved} bản phác thảo vào chi tiết chứa chúng; {stayed} giữ nguyên: {why}", "browser.units": "Đơn vị: {units}", "cam.flat": "Bề mặt phẳng", "cam.follower": "Con đội cam", @@ -819,7 +833,10 @@ "cmd.appearance_pick_up": "Lấy diện mạo", "cmd.appearance_replace": "Thay diện mạo", "cmd.assembly_bom": "Bảng kê vật tư (BOM)", + "cmd.assembly_mass_properties": "Thuộc tính khối lượng", + "cmd.body.print_face": "Mặt in", "cmd.body_rename": "Đổi tên thân khối", + "cmd.body_repair": "Sửa chi tiết", "cmd.browser_collapse_all": "Thu gọn tất cả", "cmd.browser_expand_all": "Mở rộng tất cả", "cmd.browser_group": "Tạo nhóm mới", @@ -847,6 +864,7 @@ "cmd.component_extract": "Trích xuất ra tệp riêng", "cmd.component_finish_edit": "Hoàn tất chỉnh sửa", "cmd.component_from_bodies": "Tạo cụm chi tiết từ các thân khối", + "cmd.component_hide_history": "Ẩn lịch sử thành phần", "cmd.component_insert_design": "Chèn thiết kế vào cụm", "cmd.component_links": "Danh sách liên kết", "cmd.component_list": "Danh sách cụm chi tiết", @@ -855,6 +873,7 @@ "cmd.component_move_bodies": "Di chuyển các thân khối vào cụm chi tiết", "cmd.component_move_features": "Di chuyển các tính năng vào cụm chi tiết", "cmd.component_move_sketches": "Di chuyển các phác thảo vào cụm chi tiết", + "cmd.component_move_sketches_to_parts": "Chuyển bản phác thảo vào chi tiết của chúng", "cmd.component_paste_from_design": "Dán từ thiết kế khác", "cmd.component_paste_new": "Dán Tạo mới", "cmd.component_properties": "Thuộc tính cơ lý của cụm chi tiết", @@ -862,6 +881,7 @@ "cmd.component_rename": "Đổi tên cụm chi tiết", "cmd.component_replace_with_link": "Thay thế bằng liên kết", "cmd.component_revert_position": "Hoàn nguyên vị trí cụm", + "cmd.component_show_history": "Hiện lịch sử thành phần", "cmd.component_unlock": "Mở khóa nội dung cụm", "cmd.component_update_links": "Cập nhật liên kết", "cmd.config_activate": "Kích hoạt cấu hình", @@ -872,6 +892,7 @@ "cmd.config_rule": "Quy tắc cấu hình", "cmd.config_rules": "Danh sách quy tắc cấu hình", "cmd.config_table": "Hiển thị bảng cấu hình", + "cmd.construct.plane.axis_point": "Mặt phẳng qua trục và điểm", "cmd.construct_axis_edge": "Trục đi qua cạnh", "cmd.construct_axis_normal_to_face": "Trục vuông góc với bề mặt", "cmd.construct_axis_through_cylinder": "Trục qua hình trụ/nón/xuyến", @@ -900,6 +921,8 @@ "cmd.diagnostics_crash_reports": "Danh sách báo cáo sự cố", "cmd.diagnostics_crash_reports_clear": "Xóa báo cáo sự cố ứng dụng", "cmd.diagnostics_crash_test": "Kiểm tra cơ chế sập ứng dụng", + "cmd.diagnostics_profile": "Hồ sơ đo", + "cmd.diagnostics_validation": "Kiểm tra", "cmd.doc_recover": "Khôi phục thiết kế", "cmd.doc_recovery_discard": "Hủy thiết kế khôi phục", "cmd.doc_recovery_list": "Danh sách thiết kế có thể khôi phục", @@ -920,6 +943,11 @@ "cmd.explode_show": "Hiển thị chế độ xem phân rã", "cmd.expr_evaluate": "Tính giá trị biểu thức", "cmd.face_delete": "Xóa mặt", + "cmd.file.export_3mf": "Xuất tệp 3MF", + "cmd.file.export_obj": "Xuất tệp OBJ", + "cmd.file.export_step": "Xuất tệp STEP", + "cmd.file.export_stl": "Xuất tệp STL", + "cmd.file.export_urdf": "Xuất tệp URDF", "cmd.file_export": "Xuất tệp", "cmd.file_insert_mesh": "Chèn lưới đa giác (Mesh)", "cmd.file_insert_step": "Chèn tệp STEP", @@ -932,11 +960,13 @@ "cmd.frame_profile_list": "Thư viện tiết diện", "cmd.frame_profile_properties": "Thuộc tính tiết diện", "cmd.inspect_accessibility": "Phân tích khả năng gia công tiếp cận", + "cmd.inspect_analysis": "Phân tích khung nhìn", "cmd.inspect_center_of_mass": "Trọng tâm", "cmd.inspect_clearance": "Khoảng cách an toàn", "cmd.inspect_colored_components": "Bật màu cụm chi tiết", "cmd.inspect_colored_components_disable": "Tắt màu cụm chi tiết", "cmd.inspect_compare": "So sánh các thân khối", + "cmd.inspect_compare_picture": "So sánh với ảnh tham chiếu", "cmd.inspect_continuity": "Phân tích độ liên tục mặt", "cmd.inspect_curvature_comb": "Phân tích lược độ cong (Curvature Comb)", "cmd.inspect_curvature_map": "Phân tích bản đồ độ cong (Curvature Map)", @@ -954,6 +984,7 @@ "cmd.joint_delete": "Xóa Khớp nối cơ khí", "cmd.joint_drive": "Dẫn động các khớp nối", "cmd.joint_edit": "Chỉnh sửa khớp nối", + "cmd.joint_find_limits": "Tìm giới hạn khớp nối", "cmd.joint_gear": "Khớp bánh răng", "cmd.joint_inspect": "Kiểm tra khớp nối", "cmd.joint_limits": "Giới hạn chuyển động khớp nối", @@ -966,6 +997,11 @@ "cmd.joint_screw": "Khớp trục vít", "cmd.joint_solve": "Giải hệ thống khớp nối", "cmd.joint_sweep": "Quét khớp nối", + "cmd.layout.apply": "Áp dụng bố cục", + "cmd.layout.get": "Kiểm tra bố cục", + "cmd.layout.reset": "Đặt lại bố cục", + "cmd.layout.save": "Lưu bố cục", + "cmd.layout.workspace.select": "Chọn không gian làm việc của bố cục", "cmd.library_apply": "Áp dụng mục thư viện cục bộ", "cmd.library_export": "Xuất thư viện thiết kế", "cmd.library_inspect": "Kiểm tra thư viện cục bộ", @@ -999,6 +1035,21 @@ "cmd.occurrence_move": "Di chuyển đối tượng", "cmd.occurrence_properties": "Thuộc tính cơ lý của bản thể (Occurrence)", "cmd.occurrence_reparent": "Chuyển sang Cụm chi tiết", + "cmd.panel.activate": "Kích hoạt thẻ bảng", + "cmd.panel.close": "Đóng bảng", + "cmd.panel.collapse": "Thu gọn vùng bảng", + "cmd.panel.dismiss": "Đóng chế độ xem tạm của bảng", + "cmd.panel.float": "Thả nổi bảng", + "cmd.panel.focus": "Đặt tiêu điểm vào bảng", + "cmd.panel.list": "Liệt kê các bảng", + "cmd.panel.move": "Di chuyển bảng", + "cmd.panel.native_close": "Gắn lại vùng bảng từ cửa sổ riêng", + "cmd.panel.open": "Mở bảng", + "cmd.panel.peek": "Xem tạm bảng đã thu gọn", + "cmd.panel.popout": "Chuyển bảng sang cửa sổ riêng", + "cmd.panel.reset_pair": "Đặt lại thanh chia bảng", + "cmd.panel.resize": "Đổi kích thước vùng bảng", + "cmd.panel.resize_pair": "Di chuyển thanh chia bảng", "cmd.parameters_add": "Thêm tham số người dùng", "cmd.parameters_change": "Thay đổi tham số", "cmd.parameters_comment": "Thêm chú thích tham số", @@ -1027,6 +1078,9 @@ "cmd.pointcloud_edit": "Chỉnh sửa đám mây điểm", "cmd.pointcloud_insert": "Chèn đám mây điểm", "cmd.pointcloud_list": "Đám mây điểm", + "cmd.render.compare.divider": "Di chuyển vạch so sánh kết xuất", + "cmd.render.result.discard": "Bỏ kết quả kết xuất", + "cmd.render.result.select": "Chọn kết quả kết xuất", "cmd.render_aging_describe": "Lão hóa bề mặt phân lớp", "cmd.render_backends": "Kết xuất hình ảnh Sauends", "cmd.render_batch": "Kết xuất mọi cảnh chụp", @@ -1190,6 +1244,7 @@ "cmd.sketch_spline_control_point_5": "Đường cong Spline qua điểm điều khiển (Bậc 5)", "cmd.sketch_spline_fit_point": "Đường cong Spline qua các điểm", "cmd.sketch_spline_insert_point": "Thêm điểm vào đường cong Spline", + "cmd.sketch_spline_remove_point": "Xóa điểm khỏi đường cong Spline", "cmd.sketch_spline_reverse": "Đảo ngược hướng đường cong Spline", "cmd.sketch_spun_profile": "Biên dạng xoay tròn (Spun Profile)", "cmd.sketch_toggle_diameter": "Chuyển đổi bán kính / đường kính", @@ -1240,9 +1295,11 @@ "cmd.timeline_rollback": "Di chuyển con trỏ lịch sử thiết kế", "cmd.timeline_stop": "Dừng lịch sử", "cmd.timeline_suppress": "Tạm nén tính năng", + "cmd.ui.assistant": "Bật/tắt trợ lý", "cmd.view.render_browser": "Trình duyệt kết xuất", "cmd.view.render_dock": "Di chuyển neo kết xuất", "cmd.view.render_focus": "Chế độ xem tập trung kết xuất", + "cmd.view.status_details": "Chi tiết trạng thái khung nhìn", "cmd.view.status_items": "Các mục trạng thái khung nhìn", "cmd.view_ambient_occlusion": "Đổ bóng che khuất môi trường (AO)", "cmd.view_angle_readout": "Góc hướng nhìn", @@ -1273,17 +1330,28 @@ "cmd.view_tool": "Công cụ điều hướng", "cmd.view_top": "Góc nhìn từ trên", "cmd.view_visual_style": "Kiểu hiển thị trực quan", + "color.blue": "Xanh dương", "color.copy": "Nhấp để sao chép giá trị màu", "color.edit": "Nhấp để sửa màu", "color.gamma": "Đang hiển thị giá trị màu trong không gian gamma 0-255", + "color.green": "Xanh lá", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", "color.hue": "Sắc độ", "color.linear": "Đang hiển thị giá trị màu trong không gian tuyến tính 0-1", + "color.recent": "Màu gần đây", + "color.recent_help": "Các màu bạn chọn ở bất kỳ ô màu nào sẽ hiện ở đây", + "color.red": "Đỏ", + "color.saturation": "Độ bão hòa (phần trăm)", "color.saturation_value": "Độ bão hòa và giá trị", "color.selected": "Màu đã chọn", + "color.step_down": "Giảm một bước", + "color.step_up": "Tăng một bước", + "color.value": "Giá trị, độ sáng (phần trăm)", "config.column_filter_empty": "Không có cột phù hợp", + "config.rule_parameter_columns": "Chỉ những tham số có cột trong bảng mới được liệt kê. Thêm cột bằng “Thêm cột” (+) để dùng tham số đó ở đây.", + "config.rule_suppression_columns": "Chỉ những tính năng có cột “Bỏ kích hoạt (Suppress)” trong bảng mới được liệt kê. Thêm cột bằng “Thêm cột” (+) để điều khiển tính năng đó ở đây.", "contact.components_count": "{count} chi tiết", "contact.enabled_label": "đã bật", "coupling.gear_1": "Bánh răng 1", @@ -1318,6 +1386,7 @@ "crash.unclean_explanation": "Được phát hiện ở lần khởi chạy sau; thời điểm thoát chính xác không được ghi lại. Việc tắt máy hoặc buộc dừng cũng có thể gây ra thoát bất thường.", "delete.and_more": "… và {count} mục khác", "diagnostic.empty_boolean_component": "không có thân khối nào để cắt hoặc giao trong cụm chi tiết '{component}'; công cụ có thể giao nhau với '{body}' trong cụm chi tiết '{other}' — hãy kích hoạt cụm chi tiết đó hoặc chọn thân khối làm đối tượng đích", + "diagnostic.reselect_reference": "{feature}: tham chiếu `{reference}` không còn tồn tại như khi được chọn; hãy chọn lại", "dialog.bodies_count": "{count} thân khối", "dialog.clearance_invalid": "khoảng cách an toàn phải có chiều dài từ 0 trở lên", "dialog.compute": "Tính toán", @@ -1327,11 +1396,20 @@ "dialog.custom_axis": "↖ Trục tùy chỉnh", "dialog.dimension_insert_hint": "Nhấp vào một kích thước điều khiển khác để chèn tên của nó", "dialog.dimension_name": "Kích thước: {name}", + "dialog.dimension_step_down": "Giảm {step}", + "dialog.dimension_step_expression": "Chỉ số mới thay đổi theo bước; biểu thức giữ nguyên như đã nhập", + "dialog.dimension_step_up": "Tăng {step}", "dialog.edit_title": "CHỈNH SỬA {title}", "dialog.no_shown_body": "Không có thân khối đang hiển thị để thay đổi: hãy hiển thị một thân khối, hoặc chọn “Tạo mới Thân khối”", + "dialog.pattern_sketch_not_object": "Hãy chọn thân khối hoặc tính năng: bản phác thảo không phải là cả hai. Lặp lại các đường cong của nó bằng Mảng hoặc Lấy đối xứng trong chính bản phác thảo, hoặc đùn khối nó trước.", "dialog.select": "↖ Chọn", "dialog.selected_count": "↖ {count} đã chọn", + "dialog.selection_constraint": "Ràng buộc {id}", + "dialog.selection_external_curve": "{sketch} · đường cong {id}", + "dialog.selection_external_point": "{point} · {sketch}", "dialog.selection_guidance": "Chọn một mục đầu vào để thay đổi. Nhấp vào đối tượng đã chọn để bỏ chọn; Ctrl/Cmd-nhấp để bật/tắt chọn. Xem trước kết quả, sau đó nhấn OK.", + "dialog.selection_midpoint": "Trung điểm · {id}", + "dialog.selection_profile": "{sketch} · biên dạng {number}", "dialog.selection_step": "{step} / {total}: Chọn {input}", "dialog.step": "Bước", "document.changed_on_disk": "{name} đã thay đổi trên đĩa", @@ -1346,6 +1424,7 @@ "document.read_only_save": "Thiết kế này được mở ở chế độ chỉ đọc: hãy lưu thành tệp mới", "document.save_changes": "Lưu các thay đổi đối với {name}?", "document.save_copy": "Lưu bản sao…", + "document.tab_unsaved_changes": "Thay đổi chưa lưu", "document.unsaved_changes": "{name} có các thay đổi chưa lưu. Nếu không lưu, các thay đổi sẽ bị mất.", "drive.rigid": "{joint} là khớp nối cứng: nó giữ cố định các chi tiết, nên không có gì để dẫn động. Để các chi tiết chuyển động, hãy đổi loại khớp nối trong “Chỉnh sửa khớp nối”: Revolute để xoay, Slider để trượt, Cylindrical cho cả hai.", "drive.stopped_by_contact": "Đã dừng tại {value}: {a} sẽ xuyên qua {b}", @@ -1378,6 +1457,14 @@ "file_load.reading_percent": "Đang đọc tệp... {percent}%", "file_load.rebuilding": "Đang dựng lại tính năng {done} trên {total}", "file_load.recovering": "Đang khôi phục thiết kế", + "file_load.step_build": "Đang dựng mô hình", + "file_load.step_feature": "Đặc trưng {done} trong {total}", + "file_load.step_part": "Chi tiết {done} trong {total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "Đang đọc tệp", + "file_load.step_rebuild": "Đang dựng lại các đặc trưng", + "file_load.step_repair": "Đang kiểm tra và sửa các chi tiết", + "file_load.step_show": "Đang chuẩn bị khung nhìn", "file_load.stopping": "Đang chờ thao tác trước đó dừng lại...", "file_load.updating_links": "Đang cập nhật liên kết", "file_load.waiting": "Đang chờ thao tác tệp", @@ -1386,21 +1473,189 @@ "from the rule": "từ quy tắc", "help.apache": "Giấy phép Apache 2.0", "help.appearance.assign": "Gán màu hoặc vẻ ngoài vật liệu cho các khối, mặt hoặc thành phần đã chọn mà không thay đổi khối lượng. Dùng để phân biệt các chi tiết hoặc xem trước lớp hoàn thiện.", + "help.assembly.bom": "Liệt kê các chi tiết của thiết kế hoặc cụm chi tiết kèm số lượng theo mã chi tiết, và có thể lưu danh sách dạng CSV hoặc JSON. Dùng làm bảng kê vật tư để đặt hàng và lắp ráp.", "help.attributions": "Ghi công (ATTRIBUTION.md)", "help.build": "Phiên bản {version} · commit {commit} · dựng ngày {date}", + "help.canvas.decal": "Đặt hình ảnh lên một mặt phẳng của mô hình như một đề can. Dùng để thể hiện nhãn, logo hoặc hoa văn in trên chi tiết.", + "help.canvas.edit": "Thay đổi hình ảnh Canvas: vị trí, kích thước, góc, độ mờ đục, phản chiếu, hiển thị hoặc tên. Dùng để căn hình ảnh tham chiếu với bản phác thảo mà bạn vẽ đè lên ảnh.", + "help.canvas.insert": "Đặt hình ảnh PNG hoặc JPEG lên mặt phẳng hoặc bề mặt làm tham chiếu bán trong suốt. Dùng để đồ lại ảnh chụp hoặc bản vẽ trong phác thảo, với ảnh được chỉnh về kích thước đã biết.", + "help.component.break_link": "Ngắt liên kết cụm chi tiết với tệp thiết kế của nó, giữ nguyên các thân khối. Dùng khi chi tiết không còn cần cập nhật theo thay đổi trong tệp gốc.", + "help.component.capture_position": "Lưu vị trí các chi tiết đã di chuyển bằng tay làm vị trí chính thức của chúng. Dùng sau khi kéo các chi tiết vào vị trí mà không có khớp nối nào giữ chúng.", + "help.component.create": "Thêm một cụm chi tiết mới, rỗng vào thiết kế, bên trong cụm đang hoạt động trừ khi bạn chọn cụm cha khác. Dùng để dành không gian riêng cho các thân khối và phác thảo của một chi tiết mới trong cụm lắp ráp.", "help.component.finish_edit": "Lưu chi tiết đang được chỉnh sửa tại chỗ, quay lại cụm lắp ráp của nó và cập nhật cụm lắp ráp từ chi tiết đó. Dùng khi bạn đã hoàn tất các thay đổi cho chi tiết liên kết.", + "help.component.from_bodies": "Biến mỗi thân khối được chọn thành một cụm chi tiết riêng, lấy tên theo thân khối. Dùng khi cần chuyển thiết kế gồm các thân khối rời thành cụm lắp ráp có các chi tiết nối và di chuyển được.", + "help.component.insert_design": "Chèn một thiết kế đã lưu khác thành cụm chi tiết liên kết với tệp của nó, giữ vị trí các thân khối đặc như trong tệp đó. Dùng để tái sử dụng chi tiết trong cụm lắp ráp và nhận các thay đổi sau này bằng Cập nhật liên kết.", + "help.component.properties": "Hiển thị thể tích, khối lượng, trọng tâm và mô men quán tính của một cụm chi tiết, dựa trên vật liệu của các thân khối trong đó. Dùng để kiểm tra khối lượng và độ cân bằng của cụm lắp ráp.", + "help.component.revert_position": "Đưa các chi tiết đã di chuyển bằng tay về vị trí cũ, bỏ những lần di chuyển chưa lưu vị trí. Dùng để hoàn tác các lần di chuyển thử trong cụm lắp ráp.", + "help.component.update_links": "Đọc lại các tệp thiết kế được liên kết và thay thế những thân khối đã thay đổi. Dùng sau khi chỉnh sửa một chi tiết mà cụm lắp ráp này sử dụng.", + "help.config.configure": "Thêm tham số, tính năng, vật liệu hoặc ngoại quan làm cột của bảng cấu hình. Dùng để tạo các biến thể của một thiết kế, chẳng hạn các kích cỡ của một chi tiết.", + "help.config.preview": "Kiểm tra xem một hàng của bảng cấu hình có dựng lại được không, mà không thay đổi thiết kế hay lịch sử của nó. Dùng trước khi chuyển sang một biến thể bạn chưa chắc chắn.", + "help.config.rules": "Hiển thị các quy tắc của bảng cấu hình, các hàng và hàng đang kích hoạt. Dùng để xem các biến thể của thiết kế được thiết lập thế nào.", + "help.config.table": "Hiển thị bảng cấu hình: mỗi biến thể một hàng, mỗi tham số hoặc tính năng một cột, và cho biết thiết kế còn khớp với hàng đang kích hoạt hay không. Dùng để rà soát các biến thể của thiết kế.", "help.connect_note": "Khởi động lại từng trợ lý ảo để nạp SolidCraft server. Mỗi tập tin cấu hình đều đã được sao lưu thành .bak trước khi thay đổi.", "help.connect_title": "Kết nối trợ lý ảo AI", + "help.construct.axis.edge": "Tạo trục dựng hình dọc theo một cạnh thẳng hoặc đường phác thảo. Dùng làm trục cho Xoay tròn tạo khối, mảng tròn hoặc khớp nối.", + "help.construct.axis.normal_to_face": "Tạo trục dựng hình đi qua một điểm và vuông góc với một mặt. Dùng làm trục nhô thẳng ra khỏi bề mặt.", + "help.construct.axis.through_cylinder": "Tạo trục dựng hình đi qua tâm của mặt hình trụ, nón hoặc xuyến, hoặc của một cạnh tròn. Dùng để xoay hoặc tạo mảng các tính năng quanh một chi tiết tròn.", + "help.construct.axis.two_planes": "Tạo trục dựng hình tại nơi hai mặt phẳng giao nhau. Dùng khi trục cần có chính là đường giao giữa hai mặt.", + "help.construct.axis.two_points": "Tạo trục dựng hình đi qua hai điểm, đỉnh hoặc điểm phác thảo. Dùng cho trục chạy giữa hai vị trí đã biết.", + "help.construct.plane.along_path": "Tạo mặt phẳng dựng hình vuông góc với một cạnh hoặc đường cong, tại một vị trí dọc theo nó. Dùng để phác thảo biên dạng cho Quét theo đường dẫn hoặc mặt cắt của đường dẫn.", + "help.construct.plane.at_angle": "Tạo mặt phẳng dựng hình xoay một góc so với mặt phẳng hoặc mặt, quanh một trục hoặc cạnh. Dùng cho phác thảo nghiêng, chẳng hạn giá đỡ vát góc.", + "help.construct.plane.axis_point": "Tạo mặt phẳng dựng chứa một trục và một điểm nằm ngoài trục đó. Chọn trục gốc, trục dựng, cạnh thẳng hoặc đường thẳng phác thảo, rồi chọn đỉnh, điểm phác thảo hoặc điểm dựng. Điểm nằm trên trục không xác định được một mặt phẳng duy nhất.", + "help.construct.plane.midplane": "Tạo mặt phẳng dựng hình nằm giữa hai mặt phẳng, hoặc phân giác của chúng nơi chúng giao nhau theo một góc. Dùng làm mặt phẳng đối xứng khi Lấy đối xứng.", + "help.construct.plane.offset": "Tạo mặt phẳng dựng hình song song với một mặt phẳng, cách một khoảng hoặc đi qua một điểm. Dùng để phác thảo ở độ cao xác định phía trên một mặt.", + "help.construct.plane.perpendicular": "Tạo mặt phẳng dựng hình chứa một đường hoặc cạnh và vuông góc với một mặt phẳng hoặc mặt. Dùng để phác thảo thẳng đứng trên mô hình dọc theo một cạnh.", + "help.construct.plane.tangent": "Tạo mặt phẳng dựng hình tiếp xúc với hình trụ, nón, cầu hoặc xuyến tại một điểm. Dùng để phác thảo trên mặt bên của một chi tiết tròn.", + "help.construct.plane.three_points": "Tạo mặt phẳng dựng hình đi qua ba điểm. Dùng cho mặt phẳng xác định bởi các vị trí trên mô hình, chẳng hạn ba góc.", + "help.construct.plane.two_edges": "Tạo mặt phẳng dựng hình đi qua hai cạnh thẳng hoặc hai đường nằm trong cùng một mặt phẳng. Dùng cho mặt phẳng cắt ngang chi tiết, chẳng hạn qua hai cạnh đối diện.", + "help.construct.point.along_path": "Tạo điểm dựng hình tại một vị trí dọc theo cạnh hoặc đường cong. Dùng làm điểm tham chiếu ở giữa đường dẫn.", + "help.construct.point.center": "Tạo điểm dựng hình tại tâm của cạnh tròn, đường tròn hoặc cung phác thảo, hình cầu hoặc hình xuyến. Dùng làm điểm tham chiếu cho lỗ, trục và khớp nối.", + "help.construct.point.edge_plane": "Tạo điểm dựng hình tại nơi một cạnh hoặc đường xuyên qua một mặt phẳng. Dùng để đánh dấu chỗ đường dẫn cắt qua mặt phẳng.", + "help.construct.point.three_planes": "Tạo điểm dựng hình tại nơi ba mặt phẳng giao nhau. Dùng làm điểm tham chiếu cho góc, kể cả khi mô hình không có đỉnh ở đó.", + "help.construct.point.two_edges": "Tạo điểm dựng hình tại nơi hai cạnh hoặc hai đường gặp nhau, hoặc gần nhau nhất. Dùng làm điểm tham chiếu tại một góc ảo.", + "help.construct.point.vertex": "Tạo điểm dựng hình trên một đỉnh hoặc điểm phác thảo. Dùng làm điểm tham chiếu vẫn còn khi phác thảo hay thân khối xung quanh bị ẩn.", + "help.contact.check": "Liệt kê các cặp chi tiết trong tập hợp tiếp xúc đang xuyên qua nhau ở vị trí hiện tại. Dùng để tìm va chạm trước khi dẫn động khớp nối hoặc chạy nghiên cứu chuyển động.", + "help.contact.create": "Gom hai hay nhiều chi tiết thành tập hợp tiếp xúc, ngăn các thân khối xuyên qua nhau khi khớp nối chuyển động. Dùng cho các chi tiết cần dừng khi chạm nhau, như đòn bẩy chạm cữ chặn.", + "help.contact.disable_all": "Tắt tiếp xúc để khớp nối được dẫn động và nghiên cứu chuyển động không còn dừng khi các chi tiết chạm nhau. Dùng để di chuyển chi tiết tự do trở lại hoặc giữ cho cụm lắp ráp lớn phản hồi nhanh.", + "help.contact.edit": "Thay đổi tập hợp tiếp xúc: các chi tiết, tên hoặc trạng thái tạm nén, đồng thời có thể xóa tập hợp. Dùng để điều chỉnh những chi tiết không được xuyên qua nhau.", + "help.contact.enable_all": "Đưa mọi chi tiết của cụm lắp ráp vào một tập hợp tiếp xúc để không có hai chi tiết nào xuyên qua nhau khi khớp nối chuyển động. Dùng để kiểm tra nhanh toàn bộ cơ cấu.", + "help.contact.enable_sets": "Bật tiếp xúc cho các tập hợp tiếp xúc đã định nghĩa để khớp nối được dẫn động và nghiên cứu chuyển động dừng tại nơi các chi tiết sắp xuyên qua nhau. Dùng để bật lại các tập hợp sau khi tắt tiếp xúc.", + "help.contact.list": "Liệt kê các tập hợp tiếp xúc của thiết kế, các chi tiết trong mỗi tập hợp và trạng thái bật tiếp xúc. Dùng để kiểm tra thiết lập tiếp xúc trước khi dẫn động cụm lắp ráp.", + "help.document.inspect": "Hiển thị tổng quan về thiết kế: các cụm chi tiết, thân khối, phác thảo, tính năng và tham số. Dùng để nắm nhanh một thiết kế do người khác tạo.", + "help.document.units": "Thay đổi đơn vị hiển thị chiều dài của thiết kế, chẳng hạn mm hoặc inch. Hình học giữ nguyên kích thước; chỉ phần hiển thị và các số thuần túy thay đổi theo.", + "help.edit.checkpoint": "Ghi nhớ thiết kế, phác thảo đang hoạt động và lịch sử hoàn tác ở trạng thái hiện tại. Dùng trước khi thử điều gì rủi ro mà bạn có thể muốn quay lại.", + "help.edit.restore_checkpoint": "Quay về một điểm kiểm tra, kể cả lịch sử hoàn tác. Dùng để bỏ mọi thao tác đã làm kể từ điểm kiểm tra chỉ trong một bước.", + "help.explode.create": "Tạo chế độ xem phân rã, đẩy các chi tiết ra xa tâm cụm lắp ráp hoặc theo các dịch chuyển bạn thiết lập. Dùng để thể hiện cách lắp các chi tiết trong hướng dẫn hoặc bài trình bày.", "help.face.delete": "Xóa các mặt đã chọn và để các mặt lân cận khép kín chỗ trống, hoặc giữ lỗ hở dưới dạng bề mặt. Dùng để bỏ một cạnh bo tròn, một lỗ hoặc một phần lồi đang vướng.", + "help.file.insert_mesh": "Thêm tệp 3MF, STL, OBJ, PLY hoặc glTF vào thiết kế dưới dạng các thân khối lưới trong cụm chi tiết mới. Dùng để đặt mô hình tải về hoặc quét bên cạnh thiết kế làm tham chiếu.", + "help.file.insert_step": "Thêm tệp STEP, IGES, FreeCAD hoặc Rhino vào thiết kế dưới dạng các thân khối đặc trong cụm chi tiết mới; các chi tiết của cụm lắp ráp trở thành cụm chi tiết lồng nhau. Dùng để nhập mô hình từ nhà cung cấp hoặc chương trình CAD khác.", + "help.file.save_mesh": "Lưu các thân khối thành lưới đa giác STL, 3MF hoặc OBJ, với độ mịn của các mặt cong do bạn chọn. Dùng để chuẩn bị chi tiết cho in 3D hoặc cho các chương trình đọc lưới đa giác.", + "help.file.send_to_slicer": "Lưu các thân khối đã chọn thành tệp 3MF và mở trong phần mềm cắt lớp bạn chọn. Dùng để chuyển từ mô hình sang in chỉ trong một bước.", "help.font_details": "Giao diện sử dụng các phông chữ tích hợp của egui (Ubuntu Light và Hack, theo Ubuntu Font Licence và giấy phép MIT/Bitstream Vera; Noto Emoji và phông biểu tượng emoji, theo OFL và MIT). Văn bản phác thảo dùng Liberation Sans (SIL OFL 1.1). Gói phông chữ tùy chọn của Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), không được đóng gói kèm trong các bản dựng SolidCraft.", "help.fonts": "Phông chữ", + "help.frame.member": "Đặt một biên dạng, chẳng hạn ống hoặc nhôm định hình, dọc theo các đường của phác thảo khung, mỗi đường một phần tử. Dùng để dựng khung, giá đỡ và kết cấu hàn.", + "help.inspect.accessibility": "Tô màu các mặt mà dụng cụ có thể tiếp cận từ một hướng và các mặt không tiếp cận được. Dùng để kiểm tra chi tiết có gia công hoặc ép khuôn được từ phía đó không.", + "help.inspect.center_of_mass": "Hiển thị trọng tâm của các thân khối, từng thân riêng và tất cả cùng nhau, với giả định mật độ đồng đều. Dùng để kiểm tra cân bằng và chỗ chi tiết sẽ bị lật.", + "help.inspect.colored_components": "Gán cho mỗi cụm chi tiết một màu tạm thời riêng, không thay đổi ngoại quan. Dùng để phân biệt các chi tiết của cụm lắp ráp chỉ trong một cái nhìn.", + "help.inspect.compare": "So sánh hai thân khối và chỉ ra chỗ nào một thân có vật liệu mà thân kia không có, kèm thể tích và độ lệch. Dùng để đối chiếu chi tiết đã chỉnh sửa hoặc nhập vào với bản gốc.", + "help.inspect.continuity": "Kiểm tra các mặt gặp nhau mượt đến đâu dọc theo cạnh: khe hở, gãy góc hoặc nhảy độ cong, và tô bóng các đường nối. Dùng để tìm chỗ các bề mặt nối chưa sạch.", + "help.inspect.curvature_comb": "Vẽ các lược dọc theo đường cong, cạnh hoặc mặt, với răng lược cho thấy mức độ uốn cong. Dùng để phát hiện chỗ phẳng, chỗ gãy và độ cong không đều.", + "help.inspect.curvature_map": "Tô màu các mặt theo độ cong, màu đỏ ở nơi bán kính nhỏ. Dùng để tìm chỗ gấp gắt và đánh giá độ mượt của bề mặt.", + "help.inspect.draft": "Tô màu các mặt theo góc thoát khuôn so với hướng tháo khuôn, đánh dấu những mặt có góc quá nhỏ. Dùng để kiểm tra chi tiết trước khi ép khuôn hoặc đúc.", + "help.inspect.environment_map": "Hiển thị mô hình với lớp hoàn thiện phản chiếu như gương. Dùng để đánh giá độ uôn lượn của bề mặt qua cách các hình phản chiếu chạy trên đó.", + "help.inspect.interference": "Tìm các thân khối chồng lấn nhau và hiển thị từng vùng chồng lấn kèm thể tích. Dùng để kiểm tra cụm lắp ráp xem có chi tiết nào va chạm không.", + "help.inspect.isocurve": "Vẽ các đường đẳng trị của mặt, tức lưới mà bề mặt được xây dựng trên đó. Dùng để xem bề mặt chạy ra sao và chỗ nào các đường dồn lại.", + "help.inspect.measure": "Đo chiều dài, khoảng cách, góc, diện tích và bán kính giữa các đối tượng bạn chọn, hoặc thể tích và khối lượng của thân khối. Dùng để kiểm tra kích thước và khe hở.", + "help.inspect.minimum_radius": "Tìm bán kính cong nhỏ nhất của đường cong, cạnh hoặc mặt và vị trí của nó. Dùng để kiểm tra dụng cụ hoặc đầu phun có đi theo được hình dạng này không.", + "help.inspect.section": "Cắt mở khung nhìn theo một mặt phẳng và tô gạch các mặt bị cắt, không thay đổi mô hình. Dùng để nhìn vào bên trong chi tiết và cụm lắp ráp.", + "help.inspect.zebra": "Hiển thị các sọc đen trắng phản chiếu trên các mặt của mô hình. Dùng để đánh giá độ mượt: sọc bị đứt hoặc gãy tại một cạnh cho thấy chỗ chuyển tiếp kém.", + "help.joint.as_built": "Nối hai chi tiết tại vị trí hiện có mà không di chuyển chi tiết nào, đồng thời đặt cách chúng còn có thể chuyển động. Dùng cho các chi tiết đã được đặt ở vị trí cuối cùng.", + "help.joint.cam": "Liên kết cam quay với con đội để con đội trượt hoặc lắc khi biên dạng cam đi qua bên dưới. Dùng cho cam, cơ cấu lệch tâm và bộ dẫn động van.", + "help.joint.create": "Nối hai chi tiết tại các gốc tọa độ khớp nối bạn chọn và đưa chi tiết thứ hai vào vị trí; loại khớp nối quyết định cách chúng còn có thể chuyển động. Dùng để dựng cụm lắp ráp có các chi tiết chuyển động như cơ cấu thực.", + "help.joint.drive": "Đặt góc hoặc khoảng cách của khớp nối và di chuyển các chi tiết theo nó trong giới hạn cho phép; các khớp liên kết và vòng kín chuyển động theo. Dùng để kiểm tra cơ cấu có chuyển động đúng dự kiến hay không.", + "help.joint.gear": "Liên kết hai khớp quay theo tỉ số truyền bánh răng để dẫn động khớp này làm khớp kia quay. Dùng cho bánh răng trụ răng thẳng và bánh răng vành, với tỉ số từ bán kính vòng chia hoặc số răng.", + "help.joint.limits": "Đặt giới hạn nhỏ nhất và lớn nhất cho góc quay hoặc hành trình trượt của khớp nối, hoặc xóa các giới hạn đó. Dùng để giữ bản lề, con trượt hoặc đòn bẩy trong phạm vi chuyển động thực tế.", + "help.joint.motion_link": "Ghép hai khớp nối theo tỉ số và độ lệch để dẫn động khớp này làm khớp kia chuyển động. Dùng cho quan hệ cố định giữa các khớp mà Khớp bánh răng, Khớp thanh răng - bánh răng hoặc Khớp trục vít không đáp ứng.", + "help.joint.origin": "Đặt gốc tọa độ khớp nối có tên trên chi tiết: tại tâm mặt hoặc đầu tròn, trung điểm cạnh, góc hoặc một điểm. Dùng để chuẩn bị vị trí gắn khớp nối; gốc chọn trên mặt sẽ đi theo mặt khi chi tiết đổi kích thước.", + "help.joint.rack_pinion": "Liên kết bánh răng quay với thanh răng trượt để thanh răng di chuyển bằng độ dài cung vòng chia mà bánh răng lăn qua. Dùng cho bộ truyền thanh răng, cơ cấu lái và bàn trượt tuyến tính.", + "help.joint.reach": "Di chuyển một điểm trên chi tiết về phía đích bằng cách thay đổi các khớp trong chuỗi của nó, trong giới hạn cho phép. Dùng để đặt tư thế cơ cấu theo vị trí mong muốn của đầu mút, như đầu cánh tay rô bốt.", + "help.joint.rigid_group": "Khóa các chi tiết đã chọn với nhau ở vị trí hiện tại để chúng chuyển động như một khối. Dùng cho các chi tiết thuộc cùng một nhóm và không chuyển động tương đối với nhau.", + "help.joint.screw": "Liên kết chuyển động quay và trượt theo bước vít để mỗi vòng quay tiến được khoảng cách đó. Dùng cho vít me, bu lông và trục có ren.", + "help.layout.apply": "Áp dụng bố cục đã lưu cho không gian làm việc hiện tại. Các trình chỉnh sửa được giữ lại vẫn giữ bản nháp.", + "help.layout.get": "Đọc bố cục đã xác nhận và xem các không gian làm việc đã đăng ký.", + "help.layout.reset": "Khôi phục bố cục mặc định đã đăng ký của không gian làm việc hiện tại. Các thiết lập sẵn của người dùng vẫn được giữ lại.", + "help.layout.save": "Lưu toàn bộ bố cục với một tên. Việc thay thế thiết lập sẵn của người dùng cần được cho phép ghi đè rõ ràng.", + "help.layout.workspace.select": "Chọn không gian làm việc của bố cục đã đăng ký và ghi nhớ bố cục trước đó.", + "help.library.apply": "Áp dụng vật liệu hoặc ngoại quan từ tệp thư viện cục bộ lên thân khối, mặt hoặc cụm chi tiết. Dùng để tái sử dụng vật liệu đã lưu từ thiết kế khác.", + "help.library.export": "Lưu vật liệu và ngoại quan của thiết kế vào tệp thư viện. Dùng để chia sẻ hoặc tái sử dụng trong các thiết kế khác.", + "help.library.inspect": "Kiểm tra một tệp thư viện và liệt kê các vật liệu, ngoại quan trong đó, không thay đổi thiết kế. Dùng để xem thư viện có gì trước khi áp dụng.", "help.licences": "Giấy phép", "help.material.assign": "Đặt vật liệu cho các khối đã chọn, chẳng hạn thép, nhôm hoặc ABS. Dùng để khối lượng và trọng lượng khớp với chi tiết thật.", + "help.material.properties.validate": "Kiểm tra thẻ dữ liệu vật liệu xem các số liệu có nhất quán và có thiếu giá trị nào không. Dùng trước khi dựa vào dữ liệu này để tính khối lượng hay độ cứng.", + "help.mesh.convert": "Dựng lại thân khối dạng lưới, chẳng hạn tệp STL, thành khối đặc có thể chỉnh sửa với các mặt phẳng và mặt trụ. Dùng để sửa các chi tiết cơ khí nhập vào như một thân khối tự dựng.", "help.mit": "Giấy phép MIT", + "help.motion.study": "Đặt giá trị khớp nối tại các bước trên dòng thời gian và phát lại dưới dạng hoạt ảnh. Dùng để quan sát cơ cấu chuyển động theo chuỗi và kiểm tra khe hở trên đường đi.", + "help.motion.trace": "Theo dõi quỹ đạo của một điểm trên chi tiết khi phát nghiên cứu chuyển động hoặc dẫn động khớp nối, rồi giữ lại dưới dạng đường cong phác thảo 3D khi xác nhận. Dùng để xem tầm vươn của cơ cấu hoặc dựng hình dựa trên quỹ đạo đó.", "help.notice": "NOTICE", + "help.occurrence.ground": "Cố định chi tiết tại chỗ hoặc giải phóng nó trở lại để các khớp nối di chuyển những chi tiết khác quanh nó. Dùng cho khung hoặc đế làm nền cho phần còn lại của cụm lắp ráp.", "help.occurrence.move": "Chỉ di chuyển chi tiết lắp ráp theo các bậc tự do mà khớp nối cho phép. Chọn một mặt của chi tiết, rồi kéo mũi tên hoặc cung tròn có thể sử dụng.", + "help.panel.activate": "Chọn một thẻ bảng đang mở mà không yêu cầu tiêu điểm bàn phím.", + "help.panel.close": "Đóng bảng sau khi kiểm tra vòng đời nội dung. Vị trí của bảng được ghi nhớ.", + "help.panel.collapse": "Thu gọn hoặc mở rộng vùng bảng trong khi giữ nguyên các kích thước đã yêu cầu.", + "help.panel.dismiss": "Đóng chế độ xem tạm thời của bảng đã thu gọn.", + "help.panel.float": "Di chuyển bảng vào một vùng thả nổi có vị trí được chỉ định rõ ràng.", + "help.panel.focus": "Đặt tiêu điểm vào bảng, mở lại trạng thái được giữ và mở rộng vùng của bảng khi cần.", + "help.panel.list": "Đọc các loại bảng đã đăng ký, các phiên bản đã xác nhận, thẻ đang hoạt động, tính khả dụng và khả năng của môi trường chứa.", + "help.panel.move": "Di chuyển bảng vào vùng mới hoặc thêm vào nhóm thẻ hiện có.", + "help.panel.native_close": "Đưa vùng bảng từ cửa sổ riêng về vị trí gắn đã ghi nhớ mà không hủy nội dung.", + "help.panel.open": "Mở một loại bảng với mã phiên bản rõ ràng. Phiên bản mới cần được chỉ định vị trí.", + "help.panel.peek": "Tạm hiển thị bảng đã thu gọn mà không thay đổi kích thước đã lưu hoặc trạng thái thu gọn.", + "help.panel.popout": "Di chuyển bảng sang cửa sổ riêng khi được hỗ trợ. Trình duyệt sử dụng vùng thả nổi.", + "help.panel.reset_pair": "Khôi phục tỷ lệ kích thước mặc định của hai vùng gắn liền kề trong giới hạn chung.", + "help.panel.resize": "Đặt chiều rộng và chiều cao bên ngoài của vùng bảng trong giới hạn của mọi thẻ.", + "help.panel.resize_pair": "Đổi kích thước các vùng gắn liền kề cùng nhau trong khi giữ nguyên tổng chiều dài chung.", "help.parameters.change": "Mở bảng các giá trị có tên và biểu thức điều khiển kích thước của thiết kế. Dùng để sửa một kích thước ở một chỗ và mọi tính năng dùng nó sẽ cập nhật theo.", + "help.parameters.export": "Lưu các tham số của thiết kế dạng CSV hoặc JSON. Dùng để chỉnh sửa trong bảng tính hoặc chuyển sang thiết kế khác.", + "help.parameters.graph": "Hiển thị tham số và tính năng nào dùng tham số, tính năng nào khác, cùng các vòng lặp hoặc lỗi giữa chúng. Dùng để biết thay đổi một tham số sẽ ảnh hưởng đến những gì.", + "help.parameters.import": "Đọc tham số từ CSV hoặc JSON vào thiết kế, hoặc nhập tất cả hoặc không nhập gì. Dùng để đưa giá trị từ bảng tính hoặc thiết kế khác vào.", + "help.parameters.move": "Di chuyển một tham số người dùng lên trước hoặc xuống sau tham số khác trong danh sách. Dùng để giữ các tham số liên quan gần nhau.", + "help.parts.fastener": "Thêm vít, bu lông, đai ốc, vòng đệm, chốt hoặc ổ lăn tiêu chuẩn theo kích thước bạn chọn. Dùng tại lỗ để chi tiết liên kết tự lắp vào bằng khớp nối, giúp bạn không phải tự dựng hình chi tiết liên kết.", + "help.parts.insert": "Chèn chi tiết tiêu chuẩn theo họ, kích thước và chiều dài bạn chọn. Dùng tại vành hoặc thành lỗ để chi tiết lắp vào lỗ bằng khớp ngàm cứng.", + "help.parts.library": "Mở thư viện chi tiết tiêu chuẩn: vít, bu lông, đai ốc, vòng đệm, vít hãm, chốt định vị và ổ lăn theo kích thước tiêu chuẩn. Dùng để thêm chi tiết tiêu chuẩn thay vì tự dựng hình.", + "help.parts.resize": "Thay đổi kích thước hoặc chiều dài của chi tiết tiêu chuẩn đã chèn và dựng lại nó; các khớp nối giữ chi tiết đúng vị trí lắp. Dùng khi vít quá dài hoặc lỗ cần kích thước khác.", + "help.plastic.assign_rule": "Gán một quy tắc nhựa kỹ thuật cho các thân khối, để các tính năng nhựa của chúng lấy góc thoát khuôn và khe hở từ đó làm mặc định. Dùng để thiết lập chi tiết ép khuôn một lần cho mọi tính năng.", + "help.plastic.boss": "Thêm vấu bắt ốc vỏ nhựa lên một mặt: một trụ có thể kèm lỗ, góc thoát khuôn, Bo tròn mép ở chân và các gân tăng cứng. Dùng cho điểm bắt vít trong vỏ ép khuôn hoặc in 3D.", + "help.plastic.lip": "Thêm gờ khớp mí hoặc rãnh tương ứng dọc theo mép của thân khối đã khoét rỗng. Dùng để hai nửa vỏ định vị vào nhau và đóng khít.", + "help.plastic.manage_rules": "Tạo và chỉnh sửa quy tắc nhựa kỹ thuật: vật liệu, độ dày thành, bán kính, khe hở và góc thoát khuôn. Dùng để các tính năng của chi tiết ép khuôn luôn nhất quán.", + "help.plastic.rest": "Thêm vấu đỡ nhựa lên một mặt: đệm tròn hoặc chữ nhật, đặc hoặc rỗng, có góc thoát khuôn. Dùng làm chân đỡ hoặc trụ kê trong vỏ ép khuôn.", + "help.plastic.snap_fit": "Thêm móc khớp gài bấm lên một mặt, với chiều dài, độ dày và chốt hãm. Dùng để gài các chi tiết vào nhau mà không cần vít.", "help.pointcloud.insert": "Chèn bản quét PLY, XYZ hoặc PTS dưới dạng đám mây điểm bên cạnh mô hình. Dùng làm tham chiếu khi dựng mô hình từ dữ liệu đo.", + "help.sheet.convert": "Biến một tấm hoặc thân khối khoét rỗng có độ dày đều thành thân kim loại tấm, với các chỗ uốn tại cạnh bạn chọn. Dùng để làm cho chi tiết có sẵn trải phẳng được.", + "help.sheet.export_bend_table": "Lưu bảng chấn uốn của thân kim loại tấm dạng CSV hoặc JSON: góc, bán kính và vị trí chấn trên bản trải phẳng. Dùng cho máy chấn hoặc xưởng gia công.", + "help.sheet.export_dxf": "Lưu bản trải phẳng dạng DXF, gồm đường viền, đường chấn và ghi chú chấn tùy chọn. Dùng cho cắt laser, plasma hoặc tia nước.", + "help.sheet.flange": "Thêm chấn gập mép tôn: tấm đế từ phác thảo, thành dọc theo đường viền phác thảo hở, hoặc thành uốn trên cạnh tấm. Dùng để dựng các chi tiết kim loại tấm.", + "help.sheet.flat_pattern": "Tạo bản trải phẳng của thân kim loại tấm, gồm kích thước, các lỗ cắt và đường chấn. Dùng để kiểm tra phôi trước khi cắt.", + "help.sheet.fold": "Uốn tấm kim loại dọc theo một đường phác thảo với góc và bán kính cho trước. Dùng để gập tấm phẳng sau khi đã tạo các chi tiết cắt trên đó.", + "help.sheet.hem": "Gấp mép tấm kim loại ngược lại lên chính nó. Dùng để có mép an toàn, cứng cáp và không còn ba via sắc.", + "help.sheet.manage_rules": "Tạo và chỉnh sửa quy tắc kim loại tấm: độ dày, bán kính uốn, K-factor, rãnh giảm ứng suất và khe hở. Dùng để khớp với vật liệu và dụng cụ của xưởng bạn.", + "help.sheet.path_flange": "Thêm một chuỗi chấn gập mép tôn dọc theo cạnh tấm, theo một chuỗi đường phác thảo hở. Dùng cho các biên dạng như chữ U hoặc Z chỉ trong một bước.", + "help.sheet.perforate": "Thêm một vùng lỗ phủ toàn bộ tấm phẳng, theo kiểu so le hoặc vuông. Dùng cho lỗ thông gió, lưới chắn và tấm nhẹ hơn.", + "help.sheet.refold": "Gập lại thân kim loại tấm đã được trải phẳng. Dùng sau khi thêm tính năng lên tấm phẳng.", + "help.sheet.unfold": "Trải phẳng mọi chỗ uốn của thân kim loại tấm. Dùng để thêm lỗ hoặc đường cắt phải băng qua chỗ uốn, rồi Gập lại tấm kim loại.", + "help.sketch.arc.center_point": "Vẽ cung tròn quanh một tâm, từ điểm đầu đến điểm cuối. Dùng khi đã biết tâm cung, chẳng hạn bán kính quanh lỗ hoặc trục xoay.", + "help.sketch.arc.tangent": "Vẽ cung tròn bắt đầu từ đầu mút của đường thẳng hoặc cung và tiếp tuyến với nó. Dùng để nối tiếp chuỗi bằng chỗ uốn mượt thay vì góc nhọn.", + "help.sketch.arc.three_point": "Vẽ cung tròn từ điểm đầu đến điểm cuối đi qua điểm thứ ba. Dùng khi cung phải đi qua các điểm cho trước chứ không quanh một tâm đã biết.", + "help.sketch.arc3d": "Vẽ cung tròn chính xác trong không gian qua ba điểm, khi bật 3D Phác thảo. Dùng cho các chỗ uốn của đường dẫn và ray dẫn hướng nằm ngoài mặt phẳng phác thảo.", + "help.sketch.auto_constrain": "Thêm các ràng buộc mà phác thảo gần như đã thỏa, như nằm ngang, song song hay trùng khớp, rồi thêm kích thước cho đến khi xác định hoàn toàn. Dùng để khóa một phác thảo vẽ tay chỉ trong một bước.", + "help.sketch.auto_constrain_from_datum": "Hoạt động như Tự động gán ràng buộc, nhưng đo vị trí từ điểm chuẩn bạn chọn thay vì gốc tọa độ. Dùng khi chi tiết được bố trí từ một điểm tham chiếu, như góc hoặc lỗ.", + "help.sketch.blend_curve": "Nối đầu mút của hai đường cong bằng một spline mượt tiếp tuyến với cả hai, hoặc liên tục cả độ cong nếu bạn chọn. Dùng để lấp khoảng hở giữa các đường cong mà không bị gãy.", + "help.sketch.break": "Tách đường cong thành các đoạn tại chỗ các đường cong khác cắt qua, hoặc tại các điểm bạn đặt lên nó. Dùng khi một đoạn cần ràng buộc riêng hoặc cần xóa riêng.", + "help.sketch.cancel": "Thoát phác thảo và bỏ mọi thay đổi kể từ khi tạo hoặc mở ra để chỉnh sửa. Hoàn tác sẽ khôi phục lại các thay đổi.", + "help.sketch.centerline": "Chuyển đường thẳng giữa đường thường và đường tâm, tức trục mà biên dạng bỏ qua. Dùng đường tâm làm trục cho Xoay tròn tạo khối, đối xứng gương hoặc ràng buộc đối xứng.", + "help.sketch.chamfer.distance_angle": "Vát mép góc giữa hai đường thẳng theo khoảng cách dọc đường thứ nhất và một góc. Dùng khi bản vẽ cho kích thước vát mép bằng chiều dài và góc, như 2 mm × 30°.", + "help.sketch.chamfer.equal_distance": "Vát mép góc giữa hai đường thẳng với cùng khoảng cách dọc theo cả hai. Dùng cho kiểu vát mép 45° thông thường trên đường bao.", + "help.sketch.chamfer.two_distance": "Vát mép góc giữa hai đường thẳng với khoảng cách riêng dọc theo từng đường. Dùng cho vát mép không phải 45°, cho bằng hai chiều dài.", + "help.sketch.circle.center": "Vẽ đường tròn từ tâm và đường kính. Dùng cho lỗ, vấu và các chi tiết tròn khác đã biết tâm.", + "help.sketch.circle.three_point": "Vẽ đường tròn đi qua ba điểm. Dùng khi đường tròn phải đi qua các điểm cho trước, chẳng hạn của hình học có sẵn.", + "help.sketch.circle.three_tangent": "Vẽ đường tròn tiếp xúc với ba đường thẳng, đường tròn hoặc cung. Dùng để đặt đường tròn vào khoảng giữa ba đường cong, như đường tròn nội tiếp của tam giác.", + "help.sketch.circle.two_point": "Vẽ đường tròn từ hai đầu mút của đường kính. Dùng khi biết các điểm trên mép đường tròn chứ chưa biết tâm.", + "help.sketch.circle.two_tangent": "Vẽ đường tròn có kích thước cho trước tiếp xúc với hai đường thẳng, đường tròn hoặc cung. Dùng để bo tròn với bán kính cố định giữa hai đường cong.", + "help.sketch.conic": "Vẽ đường conic giữa hai đầu mút, định hình bằng một điểm đỉnh và giá trị rho. Dùng cho các chỗ chuyển tiếp mượt mà bạn muốn chỉnh độ phồng, từ phẳng đến gần như góc nhọn.", + "help.sketch.constrainer": "Áp dụng ràng buộc mà một hoặc hai đường cong đã chọn gần như đã thỏa, như nằm ngang, song song, tiếp tuyến hay bằng nhau. Dùng để chỉnh lại phác thảo vẽ tay từng quan hệ một.", + "help.sketch.constraint.coincident": "Làm một điểm trùng với điểm khác, nằm trên một đường cong hoặc trục phác thảo. Dùng để đóng khe hở trong biên dạng hoặc đặt điểm lên đường thẳng.", + "help.sketch.constraint.collinear": "Làm hai đường thẳng nằm trên cùng một đường thẳng. Dùng để căn thẳng hàng các cạnh bị ngắt quãng, như hai bên của một khe khuyết.", + "help.sketch.constraint.concentric": "Cho hai đường tròn hoặc cung cùng một tâm, hoặc đặt tâm của đường tròn hay cung tại một điểm phác thảo, kể cả gốc tọa độ. Chọn cặp đối tượng theo thứ tự bất kỳ.", + "help.sketch.constraint.curvature": "Làm hai đường cong gặp nhau tại đầu mút tiếp tục với cùng độ cong (G2). Dùng khi nối tiếp tuyến chưa đủ mượt, chẳng hạn trên các bề mặt nhìn thấy.", + "help.sketch.constraint.equal": "Làm các đường thẳng bằng chiều dài, hoặc các đường tròn và cung bằng bán kính. Dùng để một kích thước điều khiển nhiều chi tiết giống nhau.", + "help.sketch.constraint.fix": "Cố định điểm hoặc đường cong tại chỗ, hoặc bỏ cố định chúng. Dùng cho hình học không được di chuyển khi bạn kéo hoặc giải phác thảo.", + "help.sketch.constraint.horizontal_vertical": "Làm một đường thẳng, hoặc đường nối hai điểm, nằm ngang hoặc thẳng đứng, tùy hướng nào gần hơn. Dùng để căn đường bao thẳng theo các trục phác thảo.", + "help.sketch.constraint.midpoint": "Đặt một điểm vào trung điểm của đường thẳng, hoặc làm trung điểm của hai đường thẳng trùng nhau. Dùng để căn giữa hình học trên một cạnh.", + "help.sketch.constraint.parallel": "Làm hai đường thẳng song song. Dùng cho các cạnh phải luôn song song khi các kích thước khác thay đổi.", + "help.sketch.constraint.perpendicular": "Làm hai đường thẳng gặp nhau ở góc vuông. Dùng cho các góc vuông giữa những đường không nằm trên trục phác thảo.", + "help.sketch.constraint.polygon": "Biến chuỗi đường thẳng khép kín thành đa giác đều: các cạnh bằng nhau, mọi đỉnh nằm trên một đường tròn. Dùng để làm đa giác vẽ tay thành đa giác đều và giữ nguyên như vậy.", + "help.sketch.constraint.symmetry": "Làm hai điểm hoặc đường cong đối xứng nhau qua một đường thẳng hoặc quanh một điểm. Dùng để giữ biên dạng đối xứng khi bạn sửa một bên.", + "help.sketch.constraint.tangent": "Làm hai đường cong tiếp xúc tiếp tuyến, như đường thẳng và cung. Dùng cho các chỗ nối mượt, không bị gãy góc.", + "help.sketch.construction": "Chuyển đường cong giữa hình học thường và hình học dựng hình, thứ mà biên dạng bỏ qua. Dùng đường dựng hình làm công cụ hỗ trợ bố trí, tham chiếu và ghi kích thước.", "help.sketch.construction_line": "Tạo đường thẳng dựng hình vô hạn qua hai điểm để bố trí phác thảo mà không chia tách biên dạng.", "help.sketch.construction_line.angle": "Tạo đường dựng hình vô hạn theo góc so với trục X của phác thảo. Chọn điểm rồi nhập góc hoặc chọn hướng.", "help.sketch.construction_line.bisector": "Chọn hai đường thẳng giao nhau trong phác thảo rồi chọn một trong hai đường phân giác. Kết quả thay đổi theo các đường gốc.", @@ -1411,11 +1666,71 @@ "help.sketch.construction_line.tangent_external": "Chọn đường tròn hoặc cung tròn, một điểm ngoài rồi chọn nghiệm tiếp tuyến. Bản xem trước chỉ hiển thị tiếp điểm trên cung đã vẽ.", "help.sketch.construction_line.tangent_two": "Chọn hai đường tròn hoặc cung tròn rồi chọn tiếp tuyến chung trong bản xem trước. Tiếp điểm phải nằm trên các đường cong đã vẽ.", "help.sketch.construction_line.vertical": "Tạo đường dựng hình thẳng đứng vô hạn qua một điểm. Ràng buộc đứng được giữ khi chỉnh sửa sau này.", + "help.sketch.copy": "Sao chép các đường cong và điểm phác thảo đã chọn, cùng các ràng buộc và kích thước giữa chúng. Dán vào phác thảo này hoặc phác thảo khác.", + "help.sketch.create": "Bắt đầu một phác thảo 2D mới trên mặt phẳng chuẩn hoặc mặt phẳng của khối. Mọi lệnh Đùn khối, Xoay tròn tạo khối và Quét theo đường dẫn đều bắt đầu từ một phác thảo.", + "help.sketch.cut": "Sao chép hình học phác thảo đã chọn rồi xóa khỏi phác thảo, trong một bước hoàn tác. Dán sang chỗ khác trong phác thảo này hoặc phác thảo khác.", + "help.sketch.dimension": "Thêm kích thước điều khiển: chiều dài, khoảng cách, góc, bán kính hoặc đường kính, tùy thứ bạn chọn. Nhập giá trị hoặc tên tham số, phác thảo sẽ thay đổi theo.", + "help.sketch.edit": "Mở một phác thảo có sẵn để chỉnh sửa. Các tính năng dựng trên nó sẽ cập nhật khi bạn hoàn tất phác thảo.", + "help.sketch.ellipse": "Vẽ hình elip từ tâm, đầu mút trục lớn và một điểm ở phía trục nhỏ. Dùng cho lỗ mở hình bầu dục, cam và các hình tròn dài khác.", "help.sketch.equation_curve": "Vẽ một đường cong từ công thức trên một khoảng: x(t) và y(t), hoặc y = f(x). Công thức có thể dùng tham số và đường cong thay đổi theo: dùng cho sóng sin, đường xoắn ốc hay đường thân khai của răng bánh răng.", + "help.sketch.extend": "Kéo dài đường thẳng hoặc cung đến đường cong gần nhất cản đường, hoặc kéo hai đường cong cho đến khi gặp nhau. Dùng để đóng khe hở trong biên dạng sau khi cắt tỉa hoặc chỉnh sửa.", + "help.sketch.fillet": "Bo tròn góc nơi hai đường thẳng hoặc cung gặp nhau bằng một cung có bán kính cho trước. Nhiều góc bo cùng lúc dùng chung một bán kính.", + "help.sketch.finish": "Thoát phác thảo và quay lại mô hình. Các biên dạng khép kín của nó khi đó sẵn sàng cho Đùn khối, Xoay tròn tạo khối và các tính năng khác.", + "help.sketch.finish_auto_constrain": "Chạy Tự động gán ràng buộc cho phác thảo rồi hoàn tất. Dùng để để lại phác thảo xác định hoàn toàn chỉ trong một bước.", + "help.sketch.fit_curves_to_section": "Cắt một lưới hoặc khối đặc bằng mặt phẳng phác thảo rồi khớp các đường thẳng và cung vào mặt cắt. Dùng để dựng lại chi tiết quét hoặc nhập vào thành phác thảo có thể chỉnh sửa.", + "help.sketch.include_3d": "Đưa cạnh, đỉnh của mô hình và đường cong của các phác thảo khác vào phác thảo này dưới dạng tham chiếu liên kết, làm phẳng phần nằm ngoài mặt phẳng của nó. Dùng để dựng tiếp trên hình học không nằm trong mặt phẳng phác thảo.", + "help.sketch.infinite": "Chuyển đường thẳng giữa đường thường và đường dựng hình vô hạn chạy suốt khung nhìn. Dùng làm tham chiếu bố trí không bao giờ bị ngắn.", + "help.sketch.insert_dxf": "Đọc các đường cong của bản vẽ DXF vào phác thảo, theo tỉ lệ, góc xoay và vị trí bạn đặt. Dùng để dựng tiếp từ bản vẽ 2D của chương trình khác, như biên dạng cắt laser.", + "help.sketch.insert_svg": "Đọc các đường dẫn của bản vẽ SVG vào phác thảo, theo tỉ lệ, góc xoay và vị trí bạn đặt. Dùng để biến logo hoặc đường bao véc tơ thành đường cong có thể đùn.", + "help.sketch.inspect": "Mở báo cáo về bản phác thảo đang mở: còn bao nhiêu bậc tự do và đã ràng buộc hoàn toàn chưa. Dùng nó để biết phần nào vẫn còn di chuyển được trước khi hoàn tất bản phác thảo.", + "help.sketch.intersect": "Thêm các đường cong hoặc điểm nơi khối, mặt, cạnh hoặc phác thảo khác cắt qua mặt phẳng phác thảo. Chúng vẫn được liên kết và thay đổi theo mô hình.", + "help.sketch.intersection_curve": "Tạo đường cong 3D tại nơi hai khối hoặc hai mặt gặp nhau, liên kết với chúng. Dùng làm đường dẫn hoặc ray dẫn hướng thay đổi theo mô hình.", + "help.sketch.isoparametric_curve": "Tạo đường cong 3D theo hướng U hoặc V của một mặt qua điểm bạn chọn, liên kết với mặt đó. Dùng làm đường dẫn hoặc đường tách thay đổi theo bề mặt.", + "help.sketch.line": "Vẽ các đường thẳng nối liền từng điểm một, thành chuỗi hở hoặc đường bao khép kín. Đây là công cụ cơ bản cho hầu hết biên dạng.", + "help.sketch.line.midpoint": "Vẽ đường thẳng từ trung điểm ra một đầu, đầu kia đối xứng qua trung điểm. Dùng cho đường thẳng có tâm tại một điểm, như cạnh đối xứng.", + "help.sketch.line3d": "Vẽ các đường thẳng nối giữa các điểm trong không gian, khi bật 3D Phác thảo. Dùng cho đường dẫn và khung nằm ngoài mặt phẳng phác thảo.", + "help.sketch.mirror": "Lấy đối xứng gương các đường cong và điểm phác thảo qua một đường thẳng hoặc trục, đồng thời thêm ràng buộc đối xứng. Dùng để vẽ nửa biên dạng đối xứng rồi hoàn thiện nó.", + "help.sketch.move": "Di chuyển hoặc xoay các đường cong và điểm phác thảo, hoặc một bản sao của chúng. Dùng để đổi vị trí hình học mà vẫn giữ nguyên hình dạng và ràng buộc.", + "help.sketch.offset": "Tạo bản sao của một chuỗi đường cong ở khoảng cách cho trước, về một phía hoặc cả hai. Dùng cho thành, đường bao và khe hở; khoảng cách vẫn là kích thước có thể chỉnh sửa.", + "help.sketch.paste": "Dán hình học phác thảo đã sao chép hoặc cắt vào phác thảo đang hoạt động. Đặt tại một điểm hoặc dời theo một khoảng.", + "help.sketch.pattern.circular": "Sao chép hình học phác thảo quanh một tâm, trên cả vòng tròn hoặc một góc cho trước. Dùng cho vòng lỗ bu lông, nan hoa và răng.", + "help.sketch.pattern.rectangular": "Sao chép hình học phác thảo theo hàng và cột với khoảng cách cho trước. Dùng cho lưới lỗ, rãnh then hoặc khe thông gió.", + "help.sketch.point": "Đặt một điểm phác thảo. Dùng làm tham chiếu cho kích thước, ràng buộc, tâm lỗ hoặc các tính năng sau này.", + "help.sketch.point3d": "Đặt một điểm trong không gian, khi bật 3D Phác thảo. Dùng làm tham chiếu cho đường cong và đường dẫn 3D.", + "help.sketch.polygon.circumscribed": "Vẽ đa giác đều bao quanh một đường tròn, kích thước tính từ tâm đến trung điểm một cạnh. Dùng khi biết khoảng cách giữa hai cạnh đối diện, như với đai ốc lục giác.", + "help.sketch.polygon.edge": "Vẽ đa giác đều từ hai đầu mút của một cạnh. Dùng khi biết chiều dài và vị trí của cạnh.", + "help.sketch.polygon.inscribed": "Vẽ đa giác đều nội tiếp trong một đường tròn, kích thước tính từ tâm đến một đỉnh. Dùng khi biết kích thước giữa hai đỉnh đối diện.", + "help.sketch.project": "Đưa cạnh, mặt, đỉnh của mô hình và đường cong của các phác thảo khác vào phác thảo này, chiếu lên mặt phẳng của nó. Chúng vẫn được liên kết và thay đổi theo mô hình.", + "help.sketch.project_to_surface": "Chiếu đường cong của các phác thảo khác theo pháp tuyến của phác thảo này lên một mặt, thành đường cong 3D liên kết. Dùng để đặt logo, đường tách hoặc đường dẫn lên bề mặt cong.", + "help.sketch.rectangle.center": "Vẽ hình chữ nhật từ tâm và một góc. Dùng cho đường bao có tâm tại một điểm, như gốc tọa độ.", + "help.sketch.rectangle.rounded": "Vẽ hình chữ nhật có cả bốn góc bo tròn cùng một bán kính. Dùng cho tấm, nắp và lỗ mở có góc bo tròn.", + "help.sketch.rectangle.three_point": "Vẽ hình chữ nhật từ một cạnh và một điểm ở phía đối diện. Dùng cho hình chữ nhật nghiêng so với trục phác thảo.", + "help.sketch.rectangle.two_point": "Vẽ hình chữ nhật từ hai góc đối diện. Dùng cho đường bao của tấm, khối và hốc.", + "help.sketch.scale": "Thay đổi tỉ lệ các đường cong và điểm phác thảo theo một hệ số quanh điểm gốc. Dùng để đổi kích thước một phần phác thảo mà không phải vẽ lại.", + "help.sketch.slot.arc_center": "Vẽ rãnh then cong có độ rộng cho trước dọc theo một cung xác định bởi tâm, điểm đầu và điểm cuối. Dùng cho rãnh điều chỉnh quanh trục xoay.", + "help.sketch.slot.arc_three_point": "Vẽ rãnh then cong có độ rộng cho trước dọc theo một cung đi qua ba điểm. Dùng khi đường đi của rãnh phải qua các điểm cho trước.", + "help.sketch.slot.center_point": "Vẽ rãnh then thẳng có độ rộng cho trước từ tâm của nó đến tâm cung ở một đầu. Dùng cho rãnh có tâm tại một điểm.", + "help.sketch.slot.center_to_center": "Vẽ rãnh then thẳng có độ rộng cho trước giữa tâm của hai cung ở hai đầu. Dùng cho rãnh ghi kích thước tâm đến tâm, như rãnh điều chỉnh vít.", + "help.sketch.slot.overall": "Vẽ rãnh then thẳng có độ rộng cho trước từ mép ngoài này đến mép ngoài kia. Dùng khi chiều dài toàn phần của rãnh là điều quan trọng.", + "help.sketch.spline.control_point": "Vẽ spline bậc ba được định hình bởi các điểm điều khiển mà nó không đi qua. Dùng cho đường cong mượt, uyển chuyển mà bạn chỉnh bằng cách di chuyển các điểm.", + "help.sketch.spline.control_point_5": "Vẽ spline bậc 5 được định hình bởi các điểm điều khiển. Dùng khi các đường cong cần nối với độ cong mượt hơn, chẳng hạn trên bề mặt tạo dáng nhìn thấy.", + "help.sketch.spline.fit_point": "Vẽ spline mượt đi qua mọi điểm bạn đặt, hở hoặc khép kín. Dùng để vẽ theo một hình dạng qua các điểm đã biết.", + "help.sketch.spline3d": "Vẽ đường cong mượt trong không gian qua các điểm, khi bật 3D Phác thảo. Dùng cho đường dẫn của lệnh Quét theo đường dẫn và đường đi dây cáp nằm ngoài mặt phẳng phác thảo.", + "help.sketch.spun_profile": "Tạo trong mặt phẳng phác thảo đường bao mà một khối quét qua khi quay quanh một trục. Dùng để lấy hình bóng của chi tiết tiện cho lệnh Xoay tròn tạo khối hoặc bản vẽ.", + "help.sketch.text": "Viết văn bản trong phác thảo với phông chữ, chiều cao và góc tùy chọn; nội dung có thể thay đổi theo tham số. Dùng Đùn khối hoặc Dập nổi để làm nhãn và chữ.", + "help.sketch.transform": "Đổi tỉ lệ, xoay và di chuyển hình học phác thảo quanh một tâm chỉ trong một bước. Dùng để đổi vị trí và kích thước của vùng chọn cùng lúc.", + "help.sketch.trim": "Xóa đoạn đường cong nằm giữa các giao điểm gần nhất quanh chỗ bạn nhấp. Dùng để dọn các đường chồng lên nhau thành biên dạng khép kín.", "help.solid.align": "Di chuyển các khối đã chọn để một điểm, mặt hoặc mặt phẳng trên chúng gặp một điểm, mặt hoặc mặt phẳng ở nơi khác. Dùng để đặt chi tiết áp vào chi tiết khác mà không cần đo khoảng cách.", + "help.solid.boundary_fill": "Tạo khối đặc từ các vùng được bao kín bởi các thân khối công cụ chồng lấn, chỉ điền đầy những vùng bạn chọn. Dùng để dựng hình từ không gian được nhiều thân khối cùng bao lại.", + "help.solid.bounding_solid": "Tạo khối hộp bao ngoài các thân khối đã chọn, có thể thêm khoảng dư. Dùng để xem kích thước tổng thể của chi tiết hoặc làm phôi để gia công chi tiết đó.", + "help.solid.box": "Tạo khối hộp theo chiều dài, chiều rộng và chiều cao, từ điểm góc hoặc có tâm tại một điểm. Dùng để tạo nhanh khối, hình giữ chỗ hoặc thân khối để cắt tạo các tính năng.", "help.solid.chamfer": "Vát các cạnh đã chọn theo khoảng cách bạn thiết lập. Dùng để triệt tiêu cạnh sắc hoặc giúp lắp chốt, bu lông dễ dàng hơn.", + "help.solid.coil": "Tạo thân khối xoắn ốc, như lò xo, từ đường kính, số vòng, chiều cao hoặc bước xoắn và tiết diện tròn hoặc vuông. Dùng cho lò xo, cuộn xoắn và gờ xoắn ốc.", "help.solid.combine": "Hợp nhất các khối, cắt trừ khỏi khối đích, hoặc chỉ giữ lại phần thể tích giao nhau, đồng thời có thể giữ lại các khối công cụ. Dùng để gộp chi tiết, dùng hình này cắt hình kia hoặc tìm vị trí hai khối giao nhau.", + "help.solid.cone": "Tạo khối nón từ đường tròn đáy và chiều cao, hoặc nón cụt khi đỉnh cũng có bán kính. Dùng cho phần thuôn, phễu, lỗ loe côn và đầu nhọn.", + "help.solid.cylinder": "Tạo khối trụ theo bán kính hoặc đường kính và chiều cao, dựng tại một điểm dọc theo một trục. Dùng cho trục, chốt, vấu trụ và phôi tròn.", "help.solid.draft": "Làm nghiêng các mặt đã chọn theo góc thiết lập, đo từ một mặt phẳng trung hòa. Dùng cho chi tiết đúc hoặc ép phun để chúng tháo ra khỏi khuôn được.", + "help.solid.emboss": "Dập nổi các biên dạng phác thảo, như chữ hoặc logo, lên khỏi mặt hoặc dập chìm vào mặt. Dùng cho chữ, nhãn và dấu trên mặt phẳng hoặc mặt tròn.", "help.solid.extrude": "Đùn biên dạng phác thảo thành khối 3D theo khoảng cách, thêm hoặc bớt vật liệu. Dùng để biến phác thảo phẳng thành khối, vấu nổi hoặc hốc lõm.", "help.solid.fillet": "Bo tròn các cạnh đã chọn bằng cung cong mượt mà theo bán kính thiết lập. Dùng để làm mềm cạnh sắc nhằm tăng độ bền, an toàn khi chạm hoặc tăng thẩm mỹ.", "help.solid.hole": "Khoan lỗ tròn theo đường kính thiết lập tại vị trí chọn trên mặt. Dùng cho lỗ xỏ bu lông, chốt định vị và các lỗ tròn đơn giản.", @@ -1424,20 +1739,61 @@ "help.solid.move": "Di chuyển hoặc xoay các khối đã chọn, hoặc một bản sao của chúng, theo khoảng cách và góc thiết lập. Dùng để đổi vị trí một khối hoặc tạo thêm một khối ở chỗ khác.", "help.solid.offset_face": "Đẩy các mặt đã chọn vào trong hoặc ra ngoài theo khoảng cách thiết lập, các mặt xung quanh tự điều chỉnh theo. Dùng để làm thành dày hơn, hốc sâu hơn hoặc phần lồi cao hơn mà không sửa bản phác thảo.", "help.solid.pattern.circular": "Lặp lại các đối tượng được chọn quanh một trục theo số lượng và tổng góc thiết lập. Dùng cho bố trí vòng bu lông, nan hoa, cánh tản nhiệt và răng bánh răng.", + "help.solid.pattern.path": "Sao chép tính năng hoặc thân khối dọc theo đường phác thảo, theo số lượng và khoảng cách. Dùng cho các lỗ dọc theo cạnh cong hoặc chi tiết dọc theo thanh ray.", "help.solid.pattern.rectangular": "Lặp lại các đối tượng được chọn theo một hoặc hai hướng với số lượng và khoảng cách thiết lập. Dùng cho dãy hoặc mảng lỗ, gân tăng cứng, chốt định vị hoặc chân đế.", + "help.solid.pipe": "Tạo ống tròn dọc theo đường dẫn gồm các đường cong phác thảo, đặc hoặc rỗng với độ dày thành. Dùng cho ống, dây điện, cáp và thanh ray.", "help.solid.press_pull": "Thêm hoặc bớt vật liệu khi kéo một mặt, hoặc bo tròn các cạnh khi kéo chúng. Dùng để sửa nhanh trực tiếp trên mô hình.", "help.solid.remove": "Loại các khối đã chọn khỏi thiết kế từ điểm này trong lịch sử trở đi; các bước trước vẫn giữ chúng. Dùng để bỏ một khối phụ trợ, như một công cụ cắt không còn cần.", "help.solid.replace_face": "Đưa các mặt phẳng đã chọn tới một mặt phẳng hoặc một mặt song song, khối sẽ dài ra hoặc ngắn lại để chạm tới đó. Dùng để làm một mặt phẳng hàng với chi tiết khác hoặc với mặt phẳng dựng hình.", "help.solid.revolve": "Quay biên dạng phác thảo quanh một trục để tạo khối tròn xoay. Dùng cho trục, núm xoay, chén bát và bất kỳ chi tiết nào tròn xoay quanh tâm.", + "help.solid.rib": "Thêm gân tăng cứng mỏng dọc theo đường cong phác thảo hở, kéo đầy tới các mặt kế tiếp của thân khối. Dùng để tăng cứng thành và góc, chẳng hạn trong chi tiết đúc hoặc in.", "help.solid.scale": "Phóng to hoặc thu nhỏ các khối đã chọn theo một hệ số, như nhau theo mọi hướng hoặc riêng cho từng trục. Dùng để đổi kích thước hình nhập vào hoặc bù độ co ngót.", "help.solid.shell": "Khoét rỗng khối đặc, để lại thành mỏng theo độ dày thiết lập, và có thể mở các mặt bạn chọn. Dùng cho hộp, nắp che và các chi tiết thành mỏng.", + "help.solid.sphere": "Tạo khối cầu theo bán kính hoặc đường kính quanh một điểm tâm. Dùng cho bi, núm và đầu bo tròn.", "help.solid.split_body": "Tách một khối thành các khối riêng bằng một mặt phẳng, mặt của khối khác hoặc một đường thẳng trong bản phác thảo. Dùng để tạo các chi tiết được in, gia công hoặc tô màu riêng.", "help.solid.split_face": "Chia các mặt đã chọn theo một mặt phẳng, mặt của khối khác hoặc các đường cong phác thảo, mà không tách khối. Dùng để cho một phần của mặt có độ nghiêng, màu hoặc độ dịch riêng.", "help.solid.sweep": "Quét một biên dạng phác thảo dọc theo đường dẫn để tạo khối đặc. Dùng cho đường ống, thanh ray, tay vịn và bất kỳ chi tiết nào có tiết diện không đổi chạy dọc theo đường cong.", + "help.solid.thread": "Thêm ren hệ mét ISO lên mặt trụ, dưới dạng ren biểu diễn hoặc cắt vào thân khối. Dùng cho bu lông, lỗ ren và các chi tiết ren được in.", + "help.solid.torus": "Tạo khối vòng từ bán kính lớn quanh trục và bán kính nhỏ của tiết diện tròn. Dùng cho vòng đệm kín, tay cầm và gờ tròn dạng vòng.", + "help.solid.web": "Thêm thành mỏng dọc theo mỗi đường cong phác thảo hở, mỗi thành kéo đầy tới các mặt kế tiếp của thân khối. Dùng để tạo mạng lưới gân đỡ bên trong vỏ hộp và khay.", + "help.surface.blend": "Tạo mặt cong nối các cạnh của hai thân khối, tiếp tuyến hoặc liên tục độ cong với cả hai. Dùng để nối hai mặt cong mượt qua một khoảng hở.", + "help.surface.boundary": "Tạo mặt cong lấp đầy một vòng gồm hai đến bốn đường cong phác thảo, hoặc một mạng đường cong. Dùng cho các tấm tự do được xác định bởi các cạnh của chúng.", + "help.surface.extend": "Kéo dài mặt cong ra ngoài cạnh của nó, theo khoảng cách hoặc đến một mặt phẳng hoặc mặt. Dùng để các mặt cong chồng lên nhau trước khi Cắt tỉa hoặc Khâu mặt cong (Stitch).", + "help.surface.extrude": "Đùn các đường cong hoặc biên dạng phác thảo theo một khoảng cách thành mặt cong, chỉ có thành, không có nắp. Dùng cho thành mỏng và làm dụng cụ cắt hoặc tách.", + "help.surface.fair": "Làm mượt phần bên trong của các mặt tự do trong khi cạnh của chúng giữ nguyên. Dùng để san phẳng các chỗ lồi lõm và phản chiếu gợn sóng trên bề mặt.", + "help.surface.loft": "Tạo mặt cong đi qua hai hoặc nhiều tiết diện theo thứ tự, không có nắp. Dùng cho vỏ mỏng và chuyển tiếp giữa các hình dạng khác nhau.", + "help.surface.match": "Dựng lại cạnh của một mặt cong để gặp cạnh của thân khối khác, khớp tiếp tuyến hoặc độ cong. Dùng để khép kín đường nối mượt giữa hai mặt cong.", + "help.surface.offset": "Tạo bản sao của các mặt cách một khoảng theo pháp tuyến, thành một thân mặt cong mới. Dùng để tạo lớp vỏ, khe hở hoặc mặt bên kia của một thành.", + "help.surface.patch": "Lấp một vùng phác thảo hoặc vòng cạnh kín bằng một mặt, phẳng hoặc cong mượt. Dùng để bít các lỗ trên thân mặt cong.", + "help.surface.reverse_normal": "Lật các mặt của thân mặt cong để phía ngoài của chúng quay sang hướng ngược lại. Dùng trước khi Tạo độ dày cho mặt cong hoặc Khâu mặt cong (Stitch) khi các mặt đang hướng vào trong.", + "help.surface.revolve": "Xoay các đường cong hoặc biên dạng phác thảo quanh một trục thành mặt cong, không có nắp. Dùng cho vỏ tròn như chụp đèn, bát và vòi phun.", + "help.surface.ruled": "Tạo một dải đường thẳng xuất phát từ chuỗi cạnh, theo pháp tuyến, tiếp tuyến của mặt hoặc theo một góc. Dùng cho thành thoát khuôn, vùng thoát và mặt phân khuôn.", + "help.surface.stitch": "Khâu các thân mặt cong lại với nhau dọc theo cạnh chung, thành khối đặc nếu chúng khép kín. Dùng để biến một tập hợp mặt cong thành một thân khối.", + "help.surface.sweep": "Di chuyển các đường cong hoặc biên dạng phác thảo dọc theo đường dẫn để tạo mặt cong, không có nắp. Dùng cho máng xối, nẹp viền và các hình mỏng khác chạy theo đường dẫn.", + "help.surface.thicken": "Cho thân mặt cong một độ dày, biến nó thành khối đặc. Dùng để tạo chi tiết in được hoặc gia công được từ các mặt cong.", + "help.surface.trim": "Cắt một mặt cong bằng mặt phẳng, mặt cong khác hoặc đường cong phác thảo, và giữ lại phía bạn chọn. Dùng để cắt tỉa các mặt cong theo hình trước khi Khâu mặt cong (Stitch).", + "help.surface.unstitch": "Tách các mặt của một thân khối thành những thân mặt cong riêng; khối đặc sẽ rã ra thành các mặt cong. Dùng để chỉnh lại từng mặt riêng của một thân khối.", + "help.surface.untrim": "Loại bỏ các lỗ khỏi một mặt, hoặc khôi phục biên ngoài của nó về giới hạn tự nhiên của mặt cong. Dùng để lấy lại toàn bộ mặt cong sau khi Cắt tỉa.", "help.third_party": "Giấy phép của bên thứ ba", "help.timeline.compute_all": "Dựng lại mọi tính năng trong lịch sử từ đầu. Dùng để làm mới mô hình và xem tính năng nào bị lỗi.", "help.timeline.delete": "Xóa các tính năng đã chọn khỏi lịch sử; xóa một bản phác thảo cũng xóa các tính năng dựng từ nó. Dùng để bỏ một bước không còn cần.", + "help.timeline.dependents": "Liệt kê các tính năng sẽ bị xóa cùng một tính năng, và những tính năng sẽ lỗi nếu thiếu nó. Dùng trước khi xóa hoặc thay đổi một tính năng.", "help.timeline.play": "Phát lại lần lượt các tính năng còn lại, tạm dừng nửa giây sau mỗi lần dựng lại. Chạy lại lệnh này hoặc nhấn Escape để dừng; Đến cuối sẽ chuyển ngay đến cuối lịch sử.", + "help.version": "Phiên bản {version}", + "help.view.apply": "Xoay khung nhìn về hướng chuẩn như trước, trên hoặc iso, hoặc về một góc nhìn đã lưu. Dùng để xem mô hình từ một góc cố định.", + "help.view.delete": "Xóa một góc nhìn đã lưu. Mô hình không bị thay đổi.", + "help.view.fit": "Phóng to và dịch khung nhìn để toàn bộ mô hình, hoặc phần đang chọn, lấp đầy khung nhìn. Dùng khi mô hình đã trôi ra khỏi tầm mắt.", + "help.view.grid": "Hiện hoặc ẩn lưới trong khung nhìn. Dùng làm thước tham chiếu kích thước và hướng khi dựng mô hình.", + "help.view.ground_shadow": "Hiện hoặc ẩn bóng của mô hình trên mặt sàn. Dùng để đánh giá độ cao và vị trí dễ hơn.", + "help.view.home": "Đưa khung nhìn về hướng mặc định và vừa khít mô hình. Dùng để quay lại nhanh một góc nhìn quen thuộc.", + "help.view.list": "Liệt kê các góc nhìn đã lưu trong thiết kế. Dùng để tìm góc nhìn bạn đã lưu trước đó.", + "help.view.navigate": "Xoay, dịch hoặc thu phóng khung nhìn theo từng bước, chẳng hạn xoay một phần tư vòng sang trái. Dùng để điều khiển camera chính xác thay vì kéo chuột.", + "help.view.navigation_bar": "Hiện hoặc ẩn thanh điều hướng ở cuối khung nhìn. Ẩn đi để có thêm chỗ, hiện ra để dùng các công cụ xem bằng chuột.", + "help.view.rename": "Đặt tên mới cho một góc nhìn đã lưu. Bản thân góc nhìn không đổi.", + "help.view.save": "Lưu vị trí camera hiện tại thành một góc nhìn có tên trong thiết kế. Dùng để quay lại đúng góc đó sau này, chẳng hạn khi chụp ảnh màn hình.", + "help.view.spin": "Quay khung nhìn quanh mô hình liên tục cho đến cú nhấp hoặc phím tiếp theo. Dùng để trình bày mô hình từ mọi phía.", + "help.view.tool": "Giữ cố định một công cụ camera (xoay quanh, dịch hoặc thu phóng) để kéo bằng nút chuột trái sẽ di chuyển khung nhìn cho đến khi bạn tắt nó. Dùng trên bàn di chuột hoặc khi không có nút chuột giữa.", + "help.view.visual_style": "Đổi cách vẽ mô hình: tô bóng có hoặc không có cạnh, khung dây, hoặc hiện cạnh khuất. Dùng khung dây để nhìn vào bên trong, tô bóng để có hình ảnh gọn gàng.", "history.sketch_under_constrained": "Thiếu ràng buộc ({count} bậc tự do)", "history.sketch_under_constrained_one": "Thiếu ràng buộc ({count} bậc tự do)", "hole_presets.confirm_delete": "Xác nhận xóa", @@ -1511,6 +1867,27 @@ "home.start_hint": "Tạo thiết kế, mở tệp gần đây hoặc khám phá mẫu.", "home.whats_new": "Có gì mới", "home.yesterday": "Hôm qua", + "import_report.details": "Chi tiết:", + "import_report.file_one": "Có 1 vấn đề khác với tệp.", + "import_report.file_other": "Có {count} vấn đề khác với tệp.", + "import_report.hint": "Xuất lại các chi tiết này từ chương trình đã tạo ra chúng có thể khắc phục được. Sao chép thông báo cảnh báo có đầy đủ chi tiết.", + "import_report.left_out_one": "1 mặt không thể sửa và bị thiếu.", + "import_report.left_out_other": "{count} mặt không thể sửa và bị thiếu.", + "import_report.needs_repair_one": "1 chi tiết cần sửa trước khi có thể mô hình hóa tiếp.", + "import_report.needs_repair_other": "{count} chi tiết cần sửa trước khi có thể mô hình hóa tiếp.", + "import_report.not_imported_one": "1 chi tiết không thể nhập.", + "import_report.not_imported_other": "{count} chi tiết không thể nhập.", + "import_report.not_shown_one": "1 mặt không thể vẽ và bị ẩn.", + "import_report.not_shown_other": "{count} mặt không thể vẽ và bị ẩn.", + "import_report.open_one": "1 chi tiết có khe hở giữa các mặt và được nhập thành thân hở.", + "import_report.open_other": "{count} chi tiết có khe hở giữa các mặt và được nhập thành thân hở.", + "import_report.refused_one": "1 chi tiết không thể tạo thành khối đặc và không được nhập.", + "import_report.refused_other": "{count} chi tiết không thể tạo thành khối đặc và không được nhập.", + "import_report.repaired_one": "Đã sửa các lỗi nhỏ trong 1 chi tiết.", + "import_report.repaired_other": "Đã sửa các lỗi nhỏ trong {count} chi tiết.", + "import_report.solids": "Đã nhập {solids} trong {parts} chi tiết thành khối đặc.", + "import_report.surfaces_one": "1 chi tiết không thể tạo thành khối đặc và được nhập thành bề mặt.", + "import_report.surfaces_other": "{count} chi tiết không thể tạo thành khối đặc và được nhập thành bề mặt.", "install.button_tip": "Cài đặt SolidCraft dưới dạng ứng dụng: mở trong cửa sổ riêng và hoạt động ngoại tuyến", "install.dock_1": "Chọn Tệp › Thêm vào Dock.", "install.dock_2": "Nhấp vào Thêm.", @@ -1535,26 +1912,39 @@ "issue.note_save_failed": "Không thể lưu ảnh chụp màn hình: {error}", "issue.note_saved": "Đã lưu ảnh chụp màn hình. Hãy đính kèm tệp PNG vào bản nháp GitHub.", "issue.save_screenshot": "Lưu ảnh chụp màn hình…", + "joint.find_limits": "Tìm giới hạn", + "joint.find_limits_failed": "Việc tìm giới hạn đã dừng do lỗi", + "joint.find_limits_hint": "Điền giới hạn từ vị trí mà các chi tiết do khớp nối này di chuyển lần đầu chạm vào một chi tiết khác, khi xoay hoặc trượt theo cả hai hướng từ vị trí hiện tại. Thực hiện trên một bản sao: không có gì thay đổi cho đến khi bấm OK.", + "joint.find_limits_stale": "Khớp nối hoặc thiết kế đã thay đổi kể từ khi tìm thấy các giới hạn này: hãy tìm lại", + "joint.finding_limits": "Đang tìm giới hạn…", "joint.from_bodies_hint": "Mỗi thân khối được chọn sẽ được chuyển thành một cụm chi tiết mới riêng biệt và giữ nguyên vị trí hiện tại.", + "joint.limit_contact": "{side} {value}: {a} chạm vào {b}", + "joint.limit_limit": "{side} {value}: giới hạn của một giá trị hoặc khớp nối khác", + "joint.limit_loop": "{side} {value}: vòng kín không thể khép lại quá điểm này", + "joint.limit_range": "{side}: không có tiếp xúc trong phạm vi {range}, giữ nguyên", + "joint.limit_turn": "{side} {value}: không có tiếp xúc trong một vòng quay", + "joint.limits_overlapping": "Đã lồng vào nhau tại đây: {pairs}. Chúng chỉ dừng việc tìm kiếm nếu lồng sâu hơn.", "joint.one_body": "Cả hai điểm chọn đều nằm trên {body}. Vui lòng chọn điểm thứ hai trên chi tiết khác.", "joint.one_component": "Các chi tiết này thuộc cùng một cụm chi tiết: {bodies}. Khớp nối điều khiển một cụm chi tiết so với cụm chi tiết khác, vì vậy mỗi chi tiết cần một cụm chi tiết riêng.", "joint.rigid_group_one_component": "Tất cả {count} thân khối này đều nằm trong cùng một cụm chi tiết (hoặc trong chính thiết kế): hãy dùng lệnh {command} trước.", "joint.rigid_group_select_components": "Chọn từ hai cụm chi tiết trở lên.", "joint_move.blocked_hint": "Kiểm tra loại khớp nối (chẳng hạn khớp nối cố định), trạng thái cố định của chi tiết, giới hạn khớp nối và các giá trị do tham số điều khiển.", "joint_move.blocked_title": "Không thể di chuyển chi tiết này", - "joint_move.coarse": "Bước xoay khi ở gần trục (°)", + "joint_move.coarse": "Bước gần trục", + "joint_move.conflict": "Một khớp nối của chi tiết này xung đột với các khớp nối khác: {joint}.", + "joint_move.conflict_hint": "Chỉnh sửa, tạm nén hoặc xóa khớp nối xung đột để các khớp nối khác có thể định vị chi tiết.", "joint_move.distance": "Quãng đường từ vị trí bắt đầu", "joint_move.done": "Xong", - "joint_move.fine": "Bước xoay khi ở xa trục (°)", + "joint_move.fine": "Bước xa trục", "joint_move.fixed": "Chi tiết này không có trục khớp nối nào có thể di chuyển.", "joint_move.help": "Di chuyển — kéo mũi tên hoặc cung tròn. Nhấn Esc để hủy thao tác kéo hiện tại.", - "joint_move.legacy_hint": "Tắt để sử dụng bảng Di chuyển trước đây.", - "joint_move.precision": "Kéo ra ngoài đường dẫn nét đứt để tinh chỉnh góc xoay.", + "joint_move.legacy_hint": "Tắt: bảng Di chuyển trước đây.", + "joint_move.precision": "Kéo ra ngoài đường dẫn nét đứt để dùng bước nhỏ.", "joint_move.rotation": "Góc xoay từ vị trí bắt đầu", "joint_move.select": "Chọn một mặt hoặc một chi tiết trong cụm lắp ráp, rồi chọn Di chuyển.", "joint_move.settings": "Di chuyển trong cụm lắp ráp", "joint_move.step": "Bước", - "joint_move.use_handles": "Dùng tay nắm chuyển động khớp nối khi di chuyển trong cụm lắp ráp", + "joint_move.use_handles": "Dùng tay nắm chuyển động khớp cho Di chuyển", "keymap.command_id": "Mã lệnh", "keymap.empty": "Không có lệnh phù hợp", "keymap.use_anyway": "Vẫn dùng {key} tại đây", @@ -1614,6 +2004,11 @@ "material.selection.mixed": "Các vật liệu khác nhau", "measure.at": "Tại", "measure.item": "Mục {number}", + "measure.line_to_centre": "Từ đường đến tâm", + "measure.quick_copied": "Đã sao chép số đo", + "measure.quick_copy": "Nhấp để sao chép số đo", + "measure.quick_edges": "{count} cạnh", + "measure.quick_faces": "{count} mặt", "messages.ago_h": "{n} giờ trước", "messages.ago_min": "{n} phút trước", "messages.ago_s": "{n} giây trước", @@ -1638,6 +2033,8 @@ "motion.track_name": "Rãnh {number}", "nav.alias.help": "Shift+Alt+kéo chuột trái để xoay, Shift+Alt+chuột giữa để trượt, Shift+Alt+chuột phải để thu phóng; kéo chuột giữa cũng trượt và kéo chuột phải xoay", "nav.blender.help": "Kéo chuột giữa để xoay, Shift+chuột giữa để trượt, Ctrl+chuột giữa để thu phóng; kéo chuột phải giữ nguyên camera", + "nav.creo.help": "Kéo nút giữa để xoay, Shift+nút giữa để di chuyển, Ctrl+kéo nút giữa theo chiều dọc để thu phóng (kéo xuống để phóng to); lăn con lăn để thu phóng", + "nav.creo.label": "Creo", "nav.free_orbit.help": "Chuột và chuột 3D xoay tự do qua cả hai cực và giữ nguyên độ lăn nghiêng (Roll). Bắt dính trục bằng phím Shift sẽ bị tắt.", "nav.free_orbit.label": "Xoay góc nhìn tự do", "nav.free_orbit.snap_help": "Chuột và chuột 3D xoay qua cả hai cực và giữ nguyên góc nghiêng cuộn. Giữ Shift trong khi kéo xoay quỹ đạo để bắt dính hướng nhìn và góc nghiêng cuộn.", @@ -1647,6 +2044,7 @@ "nav.hfss.help": "Alt+kéo chuột trái để trượt, Shift+Alt+chuột trái để thu phóng, Ctrl+kéo chuột trái từ vùng trống để xoay", "nav.inventor.help": "Kéo chuột giữa để trượt, Shift + chuột giữa để xoay, Ctrl + chuột giữa để thu phóng, kéo chuột phải để xoay", "nav.maya.help": "Alt+kéo chuột trái để xoay, Alt+chuột giữa để trượt, Alt+chuột phải để thu phóng; kéo chuột giữa cũng trượt", + "nav.nx.help": "Kéo chuột giữa để xoay, Shift+chuột giữa để kéo ngang (NX: giữa + phải), Ctrl+chuột giữa để thu phóng (NX: giữa + trái); kéo chuột phải không di chuyển camera", "nav.openscad.help": "Kéo chuột trái trên vùng trống để xoay, Shift + chuột trái để quét chọn vùng, kéo hình học phác thảo để chỉnh sửa; kéo chuột phải hoặc chuột giữa để trượt, Shift + kéo chuột phải hoặc chuột giữa để thu phóng", "nav.perspective.sketch": "Chế độ chỉnh sửa phác thảo sử dụng góc nhìn trực giao. Hãy hoàn tất phác thảo để chuyển sang góc nhìn phối cảnh.", "nav.right_drag_orbits.help": "Tắt: kéo chuột phải không di chuyển camera, và nút phải chỉ mở menu ngữ cảnh. Chọn kiểu chuột SolidWorks sẽ tắt tùy chọn này.", @@ -1665,6 +2063,12 @@ "navbar.assistant": "Trợ lý", "navbar.custom.add_slot": "Thêm {slot}", "navbar.custom.always": "Luôn hiện", + "navbar.custom.anchor.bottom_centre": "Dưới giữa", + "navbar.custom.anchor.bottom_left": "Dưới trái", + "navbar.custom.anchor.bottom_right": "Dưới phải", + "navbar.custom.anchor.top_centre": "Trên giữa", + "navbar.custom.anchor.top_left": "Trên trái", + "navbar.custom.anchor.top_right": "Trên phải", "navbar.custom.available": "{available} · kéo vào thanh hoặc nhấn Thêm", "navbar.custom.buttons": "Nút", "navbar.custom.compact": "Gọn", @@ -1701,6 +2105,7 @@ "navbar.custom.reset_default": "Đặt lại mặc định", "navbar.custom.right": "Chuyển sang phải", "navbar.custom.select": "Chưa chọn ô nào. Hãy chọn một ô trên thanh để di chuyển, xóa hoặc đổi cách hiển thị.", + "navbar.custom.separator_hint": "Đường phân cách giữa các nhóm nút. Kéo vào thanh hoặc nhấn Thêm; bạn có thể dùng bao nhiêu đường phân cách tùy ý.", "navbar.custom.separators_full": "Thanh đã có bốn dải phân cách.", "navbar.custom.show": "Hiện thanh điều hướng", "navbar.custom.shows": "Hiển thị", @@ -1766,6 +2171,11 @@ "not a move": "không phải một phép di chuyển", "not a number": "không phải là số", "open a sketch first": "hãy mở một phác thảo trước", + "parameters.apply_live": "Áp dụng mỗi thay đổi khi rời khỏi ô của nó", + "parameters.apply_live_tip": "Tắt: các thay đổi chờ đến khi nhấn Áp dụng hoặc OK, rồi thiết kế được dựng lại một lần cho tất cả. Hủy hoặc Escape sẽ bỏ chúng.", + "parameters.held": "{count} thay đổi đang chờ Áp dụng", + "parameters.held_hint": "Sửa biểu thức và đơn vị. Thay đổi chờ đến khi nhấn Áp dụng hoặc OK.", + "parameters.held_one": "1 thay đổi đang chờ Áp dụng", "parts.automatic_name": "tự động", "parts.dimension.across_flats": "Cỡ cờ lê", "parts.dimension.bore": "Đường kính lỗ", @@ -1784,10 +2194,19 @@ "parts.family.button_head_cap_screw": "Vít đầu tròn lục giác chìm", "parts.family.dowel_pin": "Chốt trụ", "parts.family.hex_bolt": "Bu lông đầu lục giác", + "parts.family.hex_cap_screw_inch": "Bu lông đầu lục giác (inch)", "parts.family.hex_nut": "Đai ốc lục giác", + "parts.family.hex_nut_inch": "Đai ốc lục giác (inch)", "parts.family.set_screw": "Vít trí lục giác chìm, đầu bằng", "parts.family.socket_head_cap_screw": "Bu lông lục giác chìm đầu trụ", "parts.family.washer": "Vòng đệm phẳng", + "parts.family.washer_sae": "Vòng đệm phẳng, SAE (hẹp)", + "parts.family.washer_uss": "Vòng đệm phẳng, USS (rộng)", + "parts.holes": "Lỗ (tùy chọn)", + "parts.placement_hint": "chọn một hoặc nhiều lỗ để lắp một chi tiết vào mỗi lỗ, hoặc nhấn OK để đặt tại gốc tọa độ", + "parts.system": "Hệ đơn vị", + "parts.system.inch": "Inch", + "parts.system.metric": "Hệ mét", "pattern.alignment_2": "Căn chỉnh 2", "pattern.alignment_hint": "Số lượng bao gồm cả bản gốc. Căn giữa sẽ cân bằng các bản sao; Đổi hướng sẽ chọn phía bổ sung cho tổng số chẵn.", "pattern.direction_1": "Hướng 1", @@ -1826,20 +2245,52 @@ "prefs.alt_frees_manipulators": "Phím Alt / Option cũng giải phóng mũi tên thao tác", "prefs.anti_aliasing_amd_dx12": "Khử răng cưa sử dụng mức 1× vì kiểm tra khởi động không vẽ được hình ảnh với đa lấy mẫu và đã vượt qua ở mức 1×. Bạn có thể chọn cài đặt khác ở trên; hãy khởi động lại để áp dụng nếu kiểm tra vượt qua.", "prefs.anti_aliasing_note": "Làm mịn các cạnh răng cưa.", + "prefs.appearance.colour_vision_help": "Thay đổi các màu mang ý nghĩa: trạng thái phác thảo, trục, đường uốn, phân tích và biểu tượng.", + "prefs.appearance.desktop_only": "Chỉ máy tính", + "prefs.appearance.follow_help": "Tải lại khi công cụ khác ghi lại tệp.", + "prefs.appearance.interface_scale": "Tỷ lệ giao diện", + "prefs.appearance.next_themes": "Giao diện tiếp theo", + "prefs.appearance.option_count": "{count} tùy chọn", + "prefs.appearance.option_count_one": "{count} tùy chọn", + "prefs.appearance.previous_themes": "Giao diện trước", + "prefs.appearance.theme_count": "{count} giao diện", + "prefs.appearance.theme_own": "Theo giao diện", + "prefs.appearance.viewport_colours": "Màu khung nhìn 3D", + "prefs.appearance.viewport_logo": "Khung nhìn và logo", "prefs.applies_on_restart": "Áp dụng sau khi khởi động lại", "prefs.assistant": "Trợ lý", + "prefs.assistant_connecting": "Kết nối", + "prefs.assistant_follow_help": "Thao tác Look At trên bản phác di chuyển góc nhìn theo con trỏ.", + "prefs.assistant_limit": "Giới hạn", + "prefs.assistant_limited": "Có giới hạn", + "prefs.assistant_pointer_speed": "Tốc độ con trỏ", + "prefs.assistant_seconds": "giây", + "prefs.assistant_seconds_aria": "Giây", + "prefs.assistant_use_care": "Sử dụng thận trọng", "prefs.auto_operation": "Tự động chọn thao tác", - "prefs.auto_operation_note": "Cửa sổ tính năng chọn “Nối liền”, “Tạo mới Thân khối” hoặc “Cắt” theo những gì vật liệu mới chạm vào, cho đến khi bạn tự chọn. Tắt: cửa sổ giữ nguyên thao tác lúc mở.", + "prefs.auto_operation_note": "Nối, Vật thể mới hoặc Cắt, tùy vào phần vật liệu tiếp xúc.", "prefs.axes": "Các trục tọa độ", "prefs.axis": "Trục tọa độ", + "prefs.blur_cost": "Chi phí kết xuất tương đối. Nhiều thanh hơn thường có nghĩa là cần xử lý nhiều hơn.", + "prefs.blur_device": "Không khả dụng trên thiết bị đồ họa hoặc đường kết xuất này", + "prefs.blur_guard": "Chất lượng làm mờ đã giảm để duy trì độ phản hồi của khung hình. Bán kính không thay đổi.", + "prefs.blur_off": "Tắt", + "prefs.blur_reduce_transparency": "Bị tắt bởi cài đặt Giảm độ trong suốt của hệ thống", + "prefs.blur_software": "Không khả dụng với đồ họa phần mềm (gpu-software)", + "prefs.blur_source": "Không khả dụng trong chế độ xem không gian làm việc này", + "prefs.blur_web": "Không khả dụng trên đường kết xuất web này", "prefs.bodies_folders": "Thư mục thân khối", "prefs.bodies_folders_always": "Luôn luôn", "prefs.bodies_folders_never": "Không bao giờ", - "prefs.bodies_folders_several": "Chỉ khi có nhiều thân khối", + "prefs.bodies_folders_several": "Nhiều", "prefs.bottom": "Dưới cùng", "prefs.bottom_centre": "Giữa phía dưới", "prefs.bottom_right": "Góc dưới bên phải", "prefs.browser": "Cây thư mục", + "prefs.browser_components_open": "Thành phần mở sẵn", + "prefs.browser_components_open_note": "Mọi thành phần trong trình duyệt đều mở sẵn như trước, thay vì đóng cho đến khi bạn mở.", + "prefs.browser_eye_left": "Biểu tượng mắt cạnh mũi tên thu gọn", + "prefs.browser_eye_left_note": "Các hàng trong cây thư mục hiển thị biểu tượng mắt bật/tắt cạnh mũi tên thu gọn như trước đây, thay vì trong một cột ở đầu bên phải của các hàng.", "prefs.browser_reveal_on_hover": "Hiện khi di chuột", "prefs.browser_show_note": "Hiển thị giữ trình duyệt trên màn hình. Hiện khi di chuột ẩn nó cho đến khi con trỏ đến vị trí của nó hoặc thẻ mảnh ở cạnh trái, và nó vẫn mở khi con trỏ ở bên trong hoặc một menu của nó đang mở.", "prefs.browser_shown": "Hiển thị", @@ -1847,6 +2298,8 @@ "prefs.button_left": "Kéo chuột trái", "prefs.button_middle": "Kéo chuột giữa", "prefs.button_right": "Kéo chuột phải", + "prefs.carousel_next": "Tiếp", + "prefs.carousel_previous": "Trước", "prefs.choose_font": "Chọn tệp phông chữ…", "prefs.click": "Nhấp chuột", "prefs.contact_shading": "Đổ bóng tiếp xúc mềm", @@ -1859,27 +2312,63 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Các mặt cong", "prefs.curves": "Các đường cong", + "prefs.cut_preview_tint": "Hiển thị vật liệu bị loại bỏ bằng màu đỏ", + "prefs.cut_preview_tint_help": "Bản xem trước tô vật liệu mà đặc trưng loại bỏ, và hình dạng mà nó thay thế, bằng một bóng mờ màu đỏ. Khi tắt, các phần tô này hoàn toàn trong suốt và chỉ vẽ đường viền của chúng.", + "prefs.dark_parts_shading": "Giữ hình dạng của chi tiết tối", + "prefs.dark_parts_shading_help": "Tô bóng khung nhìn bằng ánh sáng tuyến tính với ánh sáng bầu trời dịu, để các mặt tối giữ được dải chuyển màu thay vì thành màu đen", "prefs.dead_zone_note": "Dải sọc chéo là vùng chết: các chuyển động bên trong vùng này sẽ bị bỏ qua.", "prefs.default": "mặc định", - "prefs.design": "Mặc định thiết kế", - "prefs.design_note": "Cài đặt khởi đầu cho các tệp thiết kế mới. Các thiết kế đang mở giữ nguyên cài đặt riêng của chúng.", + "prefs.design": "Thiết kế", + "prefs.design_note": "Thiết lập ban đầu cho thiết kế mới.", + "prefs.design_tools.ask": "Hỏi", + "prefs.design_tools.degrees": "Độ", + "prefs.design_tools.double_click_help": "Hoặc để chỉnh sửa thành phần được liên kết tại chỗ.", + "prefs.design_tools.ghost": "Hiện vị trí cũ của chi tiết đã di chuyển dưới dạng bóng mờ", + "prefs.design_tools.hole_moves_help": "Chọn lại mặt sẽ di chuyển lỗ thay vì xóa lỗ.", + "prefs.design_tools.hole_snaps_help": "Điểm giữa của mặt và tâm các cạnh tròn của mặt đó.", + "prefs.design_tools.imported_files": "Tệp đã nhập", + "prefs.design_tools.note": "Thông báo", + "prefs.design_tools.off": "Tắt", + "prefs.design_tools.placement_group": "Gối đỡ, Trụ, Khớp gài", + "prefs.design_tools.rows": "Hàng", "prefs.devices": "Chuột 3D", "prefs.dialog_buttons": "Nút hộp thoại", "prefs.dialogs": "Hộp thoại", "prefs.dialogs_edge": "Ở cạnh khung nhìn", "prefs.dialogs_left_column": "Trong cột bên trái", "prefs.dialogs_note": "Nơi hộp thoại lệnh mở ra: gắn ở cạnh khung nhìn, hoặc trong cột bên trái thay cho trình duyệt và Lịch sử, hai phần này trở lại như cũ khi hộp thoại đóng.", + "prefs.dimension_step_angle": "Lượng mà mũi tên của cửa sổ, Lên/Xuống và con lăn cộng vào một góc", + "prefs.dimension_step_length": "Lượng mà mũi tên của cửa sổ, Lên/Xuống và con lăn cộng vào một độ dài", + "prefs.dimension_steps": "Bước của cửa sổ", + "prefs.dimension_values": "Giá trị kích thước", + "prefs.dimension_values_note": "Nơi bạn nhập giá trị kích thước. Cửa sổ có mũi tên để thay đổi theo bước; công cụ Kích thước đặt văn bản trước.", + "prefs.dimension_values_view": "Trong khung nhìn", + "prefs.dimension_values_window": "Trong một cửa sổ", "prefs.display": "Hiển thị", "prefs.edges": "Cạnh và đổ bóng", "prefs.extend": "Kéo dài", "prefs.extra_navigation": "Ctrl + kéo chuột trái trên vùng trống để xoay; giữ phím Cách (Space) để trượt góc nhìn.", + "prefs.extrude_view_isometric": "Xoay sang góc nhìn trục đo khi mở Đùn khối", + "prefs.extrude_view_return": "Trở lại góc nhìn trước khi đóng Đùn khối", "prefs.follows_os": "Theo hệ điều hành", "prefs.font": "Phông chữ", "prefs.font_fallback": "Các ký tự mà phông chữ đã chọn thiếu sẽ tự động dùng phông mặc định tích hợp, tránh tình trạng hiển thị ô vuông lỗi.", "prefs.font_sample": "Kiểm tra phông chữ · Ø12.50 mm · 45.0° · 0123456789", "prefs.font_unreadable": "Không thể đọc tệp phông chữ đã chọn.", "prefs.general": "Cài đặt chung", - "prefs.general_note": "Ngôn ngữ, lưu tệp và cập nhật.", + "prefs.general.active": "Đang dùng", + "prefs.general.crash_reports": "Báo cáo sự cố", + "prefs.general.edited": "Đã sửa", + "prefs.general.held": "Được lưu", + "prefs.general.import": "Nhập...", + "prefs.general.last_check": "Kiểm tra lần cuối: {time}", + "prefs.general.minutes": "Phút", + "prefs.general.name_setup": "Đặt tên cấu hình này", + "prefs.general.profile_name": "Tên hồ sơ", + "prefs.general.save_new": "Lưu thành mới", + "prefs.general.step_import": "STEP và nhập", + "prefs.general.this_computer": "Máy tính này", + "prefs.general_note": "Hồ sơ, ngôn ngữ, tệp và cập nhật.", "prefs.gesture_orbit": "Xoay góc nhìn", "prefs.gesture_pan": "Trượt góc nhìn", "prefs.gesture_zoom": "Thu phóng", @@ -1888,18 +2377,40 @@ "prefs.graphics_card_auto": "Tự động", "prefs.graphics_card_missing": "Card đồ họa đã lưu không khả dụng; chế độ Tự động đang được sử dụng.", "prefs.graphics_card_restart": "Có hiệu lực sau khi khởi động lại SolidCraft. Biến môi trường WGPU_ADAPTER_NAME sẽ ghi đè lựa chọn này.", + "prefs.graphics_card_unused": "Card đồ họa đã lưu không được dùng cho cửa sổ này; card đang dùng hiện trong Trợ giúp › Giới thiệu và trên dòng trạng thái. Thử Tự động, hoặc đặt WGPU_ADAPTER_NAME thành phần tên card mang tính duy nhất.", "prefs.graphics_note": "Cân đối giữa tốc độ và độ mượt mà. Mỗi tùy chọn đều hiển thị hiệu ứng trực quan trên mẫu thử.", + "prefs.graphics_page.current_view": "Khung nhìn hiện tại", + "prefs.graphics_page.fastest": "Nhanh nhất", + "prefs.graphics_page.fold_items": "Thu gọn mục", + "prefs.graphics_page.in_view": "Trong khung nhìn", + "prefs.graphics_page.live_details": "Chi tiết trực tiếp", + "prefs.graphics_page.own_mix": "Tùy chỉnh riêng", + "prefs.graphics_page.quick_measure": "Đo nhanh", + "prefs.graphics_page.reference_geometry_through_bodies": "Hình học tham chiếu xuyên qua các khối", + "prefs.graphics_page.restart": "Cần khởi động lại", + "prefs.graphics_page.sharpest": "Sắc nét nhất", + "prefs.graphics_page.single_surface_analysis": "Phân tích bề mặt duy nhất", + "prefs.graphics_page.status_chips": "Nút trạng thái", + "prefs.graphics_page.subtitle": "Cân bằng tốc độ và độ mượt.", + "prefs.graphics_page.supersampling": "Siêu lấy mẫu", + "prefs.graphics_page.supersampling_adaptive": "Chỉ trong khi góc nhìn đứng yên", + "prefs.graphics_page.surfaces_edges": "Bề mặt và cạnh", + "prefs.graphics_page.view_bar": "Cũng có trên thanh khung nhìn", "prefs.graphics_presets_note": "Các cấu hình định sẵn sẽ thiết lập đồng thời các tùy chọn bên dưới.", + "prefs.hide_constraint_glyphs_zoomed_out": "Ẩn biểu tượng ràng buộc khi thu nhỏ", + "prefs.hide_constraint_glyphs_zoomed_out_note": "Biểu tượng ràng buộc biến mất khi bản phác được thu nhỏ đủ xa để không làm rối khung nhìn. Tắt: chúng giữ kích thước màn hình cố định ở mọi mức thu phóng.", "prefs.history": "Lịch sử", "prefs.history_origin_bodies": "Hiển thị gốc tọa độ và thân khối ở trên cùng", "prefs.history_origin_bodies_note": "Cây Lịch sử ở bên trái hoặc dưới cây thư mục sẽ bắt đầu với thư mục Thân khối và Gốc tọa độ của cụm chi tiết đang kích hoạt, cùng biểu tượng mắt bật/tắt và trình đơn tương tự như trong cây thư mục. Dòng Lịch sử ở cạnh dưới không thay đổi.", "prefs.history_play_button": "Nút Phát lịch sử trong các điều khiển Lịch sử", "prefs.history_play_button_note": "Thêm Phát lịch sử vào giữa Lùi một bước và Tiến một bước trong các điều khiển Lịch sử. Bạn cũng có thể nhấp chuột phải vào các điều khiển để hiện hoặc ẩn nút này.", - "prefs.history_sketches": "Phác thảo", + "prefs.history_sketches": "Các bản phác trong Lịch sử", "prefs.history_sketches_in_order": "Theo thứ tự tạo", "prefs.history_sketches_note": "Khi tùy chọn Phác thảo được đặt thành Dưới tính năng tương ứng, cây Lịch sử ở bên trái sẽ liệt kê mỗi phác thảo thụt vào một cấp dưới tính năng đầu tiên được tạo từ nó (khi khung đủ rộng để hiển thị tên). Dòng thời gian ở cạnh dưới luôn giữ nguyên thứ tự tạo.", "prefs.history_sketches_under_feature": "Dưới tính năng tương ứng", "prefs.hold_stop_snapping": "Giữ để tạm dừng bắt dính", + "prefs.home_fit_size": "Cỡ Home và Khớp", + "prefs.home_fit_size_note": "Mô hình chiếm bao nhiêu phần khung nhìn khi Home, Khớp, một thiết kế vừa mở hoặc đổi góc nhìn bằng khối điều hướng đưa nó vào khung hình, dù tùy chọn bên dưới bật hay tắt. 100 %: lấp đầy khung nhìn giữa các bảng, la bàn và thanh điều hướng.", "prefs.icons_only": "Chỉ hiện biểu tượng", "prefs.imported_file": "Tệp đã nhập", "prefs.in_browser": "Trong cây thư mục", @@ -1908,13 +2419,38 @@ "prefs.interface_language": "Ngôn ngữ giao diện", "prefs.interface_note": "Diện mạo của SolidCraft và cách bố trí các bảng điều khiển.", "prefs.interval_minutes": "{n} phút", + "prefs.invert_curved_roll_arrows": "Đảo ngược mũi tên cuộn cong", + "prefs.invert_curved_roll_arrows_note": "Hai mũi tên cong ở góc khối cuộn khung nhìn trong mặt phẳng màn hình. Khi bật: mũi tên theo chiều kim đồng hồ cuộn ngược chiều kim đồng hồ và ngược lại. Khi tắt: mỗi mũi tên cuộn khung nhìn theo chiều cong của nó.", + "prefs.invert_navigator_arrows": "Đảo ngược mũi tên xoay của khối điều hướng", + "prefs.invert_navigator_arrows_note": "Các mũi tên quanh khối xoay camera theo hướng mũi tên chỉ, như trong Fusion và Inventor: mũi tên bên trái chỉ sang phải và đưa camera sang phải. Khi tắt: mũi tên xoay khối về phía cạnh chứa nó, nên mũi tên bên trái đưa camera sang trái. Hai mũi tên cuộn cong không bị ảnh hưởng.", + "prefs.keep_work_on_tab_switch": "Giữ hộp thoại và công cụ mở khi chuyển giữa các thiết kế", + "prefs.keep_work_on_tab_switch_note": "Mỗi thẻ thiết kế giữ hộp thoại hoặc công cụ đang mở, cùng những gì bạn đã chọn và nhập trong đó, và thẻ thanh công cụ của nó. Chúng vẫn còn đó khi bạn quay lại thiết kế. Tắt: chuyển thiết kế sẽ hủy chúng và hiển thị thẻ Mô hình.", "prefs.labels": "Nhãn chữ", + "prefs.language_system": "Hệ thống", "prefs.layout": "Bố cục", "prefs.layout_note": "Chế độ Gọn (Compact) gắn các bảng vào mép cửa sổ. Độ trong suốt của Cây thư mục chỉ khả dụng ở chế độ Nổi (Floating). Thay đổi vị trí của Trợ lý trong trang Trợ lý.", + "prefs.layout_page.active_commands": "Tô sáng lệnh đang bật", + "prefs.layout_page.always": "Luôn luôn", + "prefs.layout_page.card": "Thẻ", + "prefs.layout_page.column": "Cột", + "prefs.layout_page.hover": "Rê chuột", + "prefs.layout_page.icons_labels": "Biểu tượng + nhãn", + "prefs.layout_page.ok_cancel": "Đồng ý và Hủy bỏ", + "prefs.layout_page.on_hover": "Khi rê chuột", + "prefs.layout_page.open": "Mở", + "prefs.layout_page.origin_bodies": "Gốc tọa độ và thân khối ở trên cùng", + "prefs.layout_page.panels": "Bảng điều khiển", + "prefs.layout_page.pinned_menus": "Loại lệnh đã ghim khỏi menu", + "prefs.layout_page.play_history": "Nút Phát lịch sử", + "prefs.layout_page.slot_count": "{count}/{max} ô", + "prefs.layout_page.view_corner": "Cũng ở góc khung nhìn", + "prefs.layout_page.window": "Cửa sổ", "prefs.left": "Bên trái", "prefs.left_click": "Nhấp chuột trái", "prefs.line_drag_draws_one": "Nhấn và kéo vẽ một đường", "prefs.line_drag_draws_one_note": "Trong công cụ Đường, nhấn, kéo rồi thả sẽ vẽ một đường từ điểm nhấn đến điểm thả, và kết thúc ở đó. Nhấp vẫn vẽ một chuỗi. Tắt: kéo đặt một điểm tại nơi thả, như một lần nhấp.", + "prefs.line_hover_tangent_arc": "Dừng trên điểm cuối của đường để chuyển sang cung tiếp tuyến", + "prefs.line_hover_tangent_arc_note": "Trong công cụ Đường, sau khi vẽ một đoạn, hãy rời điểm cuối của chuỗi, quay lại và giữ yên con trỏ trên đó: lần nhấp tiếp theo sẽ kết thúc một cung tiếp tuyến, và cùng thao tác đó sẽ quay lại đường thẳng. Tắt: dừng ở đó không có tác dụng.", "prefs.linked_designs": "Thiết kế liên kết", "prefs.live_input": "Nhập liệu trực tiếp", "prefs.live_preview": "Xem trước trực tiếp", @@ -1922,10 +2458,10 @@ "prefs.logo_accent": "Màu nhấn", "prefs.logo_theme": "Màu của chủ đề", "prefs.max_file_size": "Kích thước tệp tối đa để mở", - "prefs.max_file_size_design": "Tệp thiết kế", + "prefs.max_file_size_design": "Tệp lớn nhất có thể mở: Thiết kế", "prefs.max_file_size_flag": "Lần chạy này bắt đầu với --max-file-size {size}, có hiệu lực đến khi đóng SolidCraft. Các cài đặt này áp dụng khi khởi động không có tùy chọn đó.", "prefs.max_file_size_note": "Mặc định: 512 MB và 256 MB; tối đa 16 GB. Mở tệp cần lượng bộ nhớ gấp nhiều lần kích thước tệp. Thiết kế giữ dữ liệu nhập lớn có thể cần giới hạn tệp thiết kế cao hơn để lưu và mở lại.", - "prefs.max_file_size_step": "Tệp STEP và tệp nhập", + "prefs.max_file_size_step": "Tệp lớn nhất có thể mở: STEP và nhập", "prefs.max_file_size_web": "Ứng dụng web mở tệp STEP và tệp nhập tối đa 512 MB, thiết kế tối đa 256 MB: thẻ trình duyệt không chứa được tệp lớn hơn. Ứng dụng máy tính cho phép tăng các giới hạn này.", "prefs.megabytes": "MB", "prefs.menu_grid": "Biểu tượng lớn", @@ -1937,10 +2473,19 @@ "prefs.mouse_heading": "Chuột", "prefs.mouse_mapping": "Gán chức năng chuột", "prefs.navigation": "Điều hướng góc nhìn", + "prefs.navigation.axes_signed": "Trục", + "prefs.navigation.cube_compact": "Khối lập phương", + "prefs.navigation.device": "Thiết bị", + "prefs.navigation.free": "Tự do", + "prefs.navigation.orbit_style": "Kiểu xoay", + "prefs.navigation.radial_help": "Giữ hoặc hất nút phải để mở vòng công cụ.", + "prefs.navigation.turntable": "Bàn xoay", "prefs.navigation_note": "Cách chuột, bàn di cảm ứng và chuột 3D di chuyển góc nhìn.", + "prefs.navigator_fit": "Khớp mô hình sau khi đổi góc nhìn bằng khối điều hướng", + "prefs.navigator_fit_note": "Nhấp vào một mặt, góc hoặc mũi tên của khối lập phương, hoặc một trục của gizmo, cũng nhìn vào tâm mô hình từ một khoảng cách duy nhất chứa trọn nó từ mọi phía (khối cầu bao). Khi bật, góc nhìn chuẩn (Home) dùng cùng mức thu phóng và tâm đó, nên các góc nhìn chọn sau chỉ xoay. Tắt: góc nhìn xoay tại chỗ, giữ nguyên điểm nhìn và mức thu phóng.", "prefs.network_host_remove": "Xóa", "prefs.network_locations": "Cho phép các vị trí mạng trong thiết kế", - "prefs.network_locations_note": "Khi tắt: các tệp liên kết của thiết kế trên máy tính khác (\\\\server\\share) chỉ được mở từ các máy chủ được liệt kê tại đây, hoặc sau khi bạn đồng ý khi được hỏi.", + "prefs.network_locations_note": "Dành cho tổ chức lưu thiết kế trên máy chủ tệp. Khi tắt: chỉ các máy chủ bạn cho phép.", "prefs.network_locations_section": "Vị trí mạng", "prefs.not_on_gpu": "GPU này không hỗ trợ", "prefs.on": "Bật", @@ -1950,20 +2495,32 @@ "prefs.origin_plane_names": "Tên các mặt phẳng gốc", "prefs.origin_plane_names_note": "Tên hiển thị trong trình duyệt, hộp thoại và danh sách. {top} là XY, {front} là XZ và {right} là YZ, với Z hướng lên. Lệnh, script và thiết kế đã lưu vẫn dùng XY, XZ và YZ.", "prefs.overall_speed": "Tốc độ tổng thể", + "prefs.parameter_list_rows": "Số dòng danh sách tham số", + "prefs.parameter_list_rows_tip": "Số tham số tối đa được liệt kê khi nhấn mũi tên xuống trong ô biểu thức trống.", "prefs.persistent_ribbon_pressed": "Tô sáng lệnh đang bật trên dải băng", "prefs.persistent_ribbon_pressed_help": "Tô sáng các lệnh trên dải băng khi hiệu ứng của chúng đang bật. Tắt tùy chọn này để giữ giao diện trung tính và trợ giúp lệnh như trước.", "prefs.perspective_fov": "Trường nhìn", "prefs.placement": "Vị trí đặt", + "prefs.plugins_enabled": "Đã bật", + "prefs.plugins_installed": "Đã cài đặt", + "prefs.plugins_intro": "Tiện ích bổ sung trong vùng cách ly.", + "prefs.plugins_show_folder": "Hiện thư mục plugin", "prefs.prefer_free_sketch_points": "Ưu tiên điểm phác thảo có thể di chuyển khi các điểm chồng lên nhau", "prefs.preview_choices": "Xem trước các lựa chọn của bạn", + "prefs.preview_tint_new_faces": "Tô màu bề mặt mới trong bản xem trước", + "prefs.preview_tint_new_faces_help": "Bản xem trước của một đặc trưng làm thay đổi một khối có thể vẽ bề mặt được thêm vào bằng màu xem trước. Khi tắt, khối được vẽ bằng màu của chính nó.", + "prefs.print_face_highlight": "Tô sáng mặt in", + "prefs.print_face_highlight_tip": "Mức tô màu và viền mặt in của thân trong khung nhìn. 0 % không tô sáng.", "prefs.profile_active": "Hồ sơ đang dùng", "prefs.profile_applied": "Đã áp dụng hồ sơ.", "prefs.profile_changed": "Cài đặt đã thay đổi kể từ khi lưu hồ sơ. “Lưu” sẽ ghi chúng vào hồ sơ.", "prefs.profile_deleted": "Đã xóa hồ sơ.", - "prefs.profile_export": "Xuất tệp…", + "prefs.profile_export": "Xuất", "prefs.profile_exported": "Đã xuất hồ sơ.", - "prefs.profile_imported": "Đã nhập hồ sơ. Chọn hồ sơ trong “Hồ sơ đang dùng” để chuyển sang.", + "prefs.profile_imported": "Đã nhập hồ sơ.", "prefs.profile_name_hint": "Tên hồ sơ, ví dụ Laptop", + "prefs.profile_operations": "Đo thời gian thao tác", + "prefs.profile_operations_note": "Ghi lại thời gian các lệnh gọi SMLib, thao tác kernel, đặc trưng, lệnh và lần nhập. Tác tử đọc bằng diagnostics.profile.", "prefs.profile_rename": "Đổi tên", "prefs.profile_renamed": "Đã đổi tên hồ sơ.", "prefs.profile_save": "Lưu", @@ -1977,26 +2534,71 @@ "prefs.quality_fastest": "nhanh nhất", "prefs.quality_slowest": "chậm nhất (chất lượng cao nhất)", "prefs.quality_smoother": "mượt mà hơn", + "prefs.quick_measure": "Đo nhanh ở góc khung nhìn", + "prefs.quick_measure_note": "Hiển thị kích thước của đối tượng được chọn ở góc dưới bên phải khung nhìn, phía trên Lịch sử: chiều dài của cạnh (hoặc Ø và R với cạnh tròn), diện tích của mặt, vị trí của điểm, khoảng cách và góc giữa hai đối tượng, tổng của nhiều cạnh hoặc mặt. Nhấp để sao chép.", "prefs.render_previous_geometry_budget": "Dùng ngân sách hình học trước đây cho bản xem trước kết xuất", "prefs.render_previous_geometry_budget_help": "Khôi phục giới hạn hình học cố định trước đây (512 MiB trên máy tính 64 bit, 128 MiB trên các nền tảng khác) thay cho ngân sách dựa trên thiết bị.", "prefs.reports_saved": "Đã lưu {n}", + "prefs.restore_page_defaults": "Khôi phục mặc định của trang", + "prefs.ribbon_click_ends_tool": "Nhấp vào nút của công cụ đang chạy sẽ kết thúc nó", + "prefs.ribbon_click_ends_tool_note": "Nhấp vào nút ruy-băng đang sáng của công cụ phác thảo đang dùng sẽ kết thúc công cụ, để các cú nhấp trong khung nhìn lại chọn đối tượng. Tắt: cú nhấp khởi động lại công cụ.", "prefs.ribbon_reveal": "Hiện kết quả tìm kiếm trên ribbon", "prefs.ribbon_reveal_note": "Khi rê chuột lên một kết quả trong Tìm lệnh, ribbon cho biết lệnh nằm ở đâu: tab, nút hoặc dòng của nó trong menu thả xuống của một bảng. Lệnh bắt đầu từ tìm kiếm sẽ nhấp nháy ở đó, và lệnh đang chạy từ menu thả xuống sẽ đánh dấu bảng của nó.", "prefs.right_click": "Nhấp chuột phải", - "prefs.saving": "Tự động lưu và khôi phục", + "prefs.saving": "Khởi động và lưu", "prefs.scale_note": "Cũng có thể dùng Ctrl + / Ctrl − trong cửa sổ. Các nút có kích thước 28 px ở mức 100%.", "prefs.scale_text": "Tỉ lệ và văn bản", "prefs.search": "Tìm kiếm cài đặt", "prefs.search_empty": "Không có cài đặt nào khớp", + "prefs.section_hatch": "Gạch mặt cắt", + "prefs.section_hatch_by_part": "Theo chi tiết", + "prefs.section_hatch_one": "Một kiểu", "prefs.select": "Chọn", "prefs.select_one_item": "Chọn một mục", + "prefs.select_other_hidden": "Chọn hình học ẩn bằng Chọn đối tượng khác", + "prefs.select_other_hidden_help": "Bật: bao gồm các khối, bản phác thảo ẩn và cạnh bị che gần con trỏ. Tắt: dùng danh sách ban đầu chỉ gồm hình học đang hiển thị ngay dưới con trỏ.", "prefs.selecting": "Đang chọn", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift chỉ thêm; Ctrl / Cmd đảo trạng thái chọn", "prefs.shift_add_note": "Bật: Shift để thêm vào vùng chọn, Ctrl / Cmd để đảo chọn. Tắt (mặc định): cả hai đều đảo trạng thái chọn.", "prefs.shortcuts": "Phím tắt", + "prefs.shortcuts_import": "Nhập", + "prefs.shortcuts_intro": "Phím cho từng lệnh.", + "prefs.shortcuts_not_assigned": "Chưa gán", + "prefs.shortcuts_press": "Nhấn một phím...", "prefs.single_surface_analysis": "Chỉ dùng một phân tích bề mặt", "prefs.single_surface_analysis_help": "Khi tắt, phân tích tô bóng bề mặt và phân tích tính liên tục có thể cùng hoạt động. Khi bật, chỉ giữ phân tích được bắt đầu hoặc thay đổi gần nhất.", + "prefs.sketch.align_points": "Căn theo các điểm phác thảo khác", + "prefs.sketch.align_points_note": "Đường đang vẽ căn theo các điểm trên cả hai trục cùng lúc.", + "prefs.sketch.auto_dimensions": "Ghi đầy đủ kích thước cho hình mới", + "prefs.sketch.auto_dimensions_note": "Giá trị đã nhập cùng mọi kích thước xác định hình dạng.", + "prefs.sketch.auto_locate": "Định vị từ gốc phác thảo", + "prefs.sketch.auto_locate_note": "Khi ghi đầy đủ kích thước.", + "prefs.sketch.center_arc": "Cung theo tâm đi theo con trỏ", + "prefs.sketch.click_selects": "Nhấp để chọn", + "prefs.sketch.conflict_colour": "Màu xung đột", + "prefs.sketch.drawing": "Vẽ", + "prefs.sketch.exit_keep": "Giữ nguyên", + "prefs.sketch.exit_previous": "Trở về góc nhìn trước đó", + "prefs.sketch.exit_unless_rotated": "Trừ khi đã xoay", + "prefs.sketch.faces_edges": "Mặt và cạnh", + "prefs.sketch.hide_glyphs": "Ẩn ký hiệu khi thu nhỏ", + "prefs.sketch.marks": "Dấu trong phác thảo", + "prefs.sketch.note": "Vẽ, bắt điểm và chọn.", + "prefs.sketch.opening_closing": "Mở và đóng", + "prefs.sketch.prefer_free_points": "Ưu tiên điểm di chuyển được khi chồng nhau", + "prefs.sketch.project_options": "Hỏi tùy chọn Chiếu trước", + "prefs.sketch.recent_snap": "Bắt vào giao điểm của hai đường dẫn", + "prefs.sketch.select_other_hidden": "Chọn đối tượng khác bao gồm hình học bị ẩn", + "prefs.sketch.shortcut_cycles_modes": "Nhấn lại phím tắt để đổi chế độ", + "prefs.sketch.shortcut_cycles_modes_tip": "Tắt: khởi động lại công cụ.", + "prefs.sketch.snapping_guides": "Bắt điểm và đường dẫn", + "prefs.sketch.state_icons": "Biểu tượng trạng thái", + "prefs.sketch.tracking_guides": "Đường dẫn qua tâm và trung điểm", + "prefs.sketch.tracking_guides_note": "Đường dẫn ngang và dọc tạm thời từ tâm và trung điểm cạnh khi rê chuột qua.", + "prefs.sketch.tracking_points": "Đường dẫn từ cả các điểm phác thảo", + "prefs.sketch.unless_turned_note": "trở về nếu chưa xoay", + "prefs.sketch.whole_bodies": "Toàn bộ khối", "prefs.sketch_align_points": "Căn theo các điểm phác thảo khác khi vẽ", "prefs.sketch_align_points_note": "Khi vẽ, một điểm được căn ngang theo một điểm phác thảo và căn dọc theo điểm khác cùng lúc, kèm đường dẫn chấm; cú nhấp giữ cả hai ràng buộc căn. Tắt: chỉ căn theo điểm trước, mỗi lần một trục.", "prefs.sketch_conflict_colour": "Hình học xung đột theo màu xung đột", @@ -2007,6 +2609,8 @@ "prefs.sketch_exit_view.previous": "Trở về góc nhìn trước đó", "prefs.sketch_exit_view.unless_rotated": "Trở về góc nhìn trước trừ khi đã xoay", "prefs.sketch_exit_view_note": "Góc nhìn sẽ chuyển đến đâu sau khi bấm Hoàn tất phác thảo, Hủy bỏ hoặc bấm phím Esc hai lần.", + "prefs.sketch_face_activates_part": "Phác thảo trên mặt của một chi tiết sẽ kích hoạt chi tiết đó", + "prefs.sketch_face_activates_part_note": "Bản phác thảo bắt đầu trên mặt của một khối thuộc thành phần khác sẽ kích hoạt thành phần đó trước, nên bản phác thảo thuộc về nó và nằm cùng chi tiết đó trong trình duyệt. Chi tiết vẫn được kích hoạt sau đó. Tắt: bản phác thảo thuộc thành phần đang hoạt động.", "prefs.sketch_open_look_at": "Xoay góc nhìn trực diện phác thảo khi mở", "prefs.sketch_open_look_at_note": "Tắt: tạo hoặc chỉnh sửa phác thảo sẽ giữ nguyên góc nhìn. Dùng Nhìn trực diện để nhìn thẳng vào phác thảo khi cần.", "prefs.sketch_recent_snap": "Tự động bắt điểm vào tâm và trung điểm gần đây", @@ -2020,22 +2624,42 @@ "prefs.sketch_tab_always_note": "Thẻ Bản phác vẫn nằm trên thanh công cụ, ngay sau Mô hình, khi không có bản phác nào đang mở. Khi đó các công cụ vẽ của nó bắt đầu một bản phác trên mặt phẳng hoặc mặt đã chọn, hoặc trên mặt phẳng bạn chọn tiếp theo, với công cụ sẵn sàng trong đó.", "prefs.sketch_tracking_guides": "Đường căn chỉnh tâm và trung điểm", "prefs.sketch_tracking_guides_note": "Di con trỏ lên tâm đường tròn hoặc trung điểm của cạnh thẳng, rồi di chuyển theo phương ngang hoặc dọc để hiển thị đường căn chỉnh nét đứt tạm thời.", + "prefs.sketch_tracking_points": "Đường căn chỉnh từ điểm đầu mút và góc khi vẽ", + "prefs.sketch_tracking_points_note": "Khi một công cụ vẽ đang chờ một điểm, di con trỏ lên đầu mút của đường thẳng hoặc cung, góc của hình chữ nhật hoặc một điểm tự do sẽ hiển thị đường căn chỉnh nét đứt tạm thời giống như ở tâm hoặc trung điểm. Tắt: chỉ tâm và trung điểm.", "prefs.sketching": "Vẽ phác thảo", "prefs.snap_drawing_note": "Khi đang vẽ hoặc kéo một điểm phác thảo.", "prefs.source": "Nguồn", "prefs.speed": "Tốc độ", "prefs.stand_up_note": "Sau khi mở tệp STEP hoặc IGES với trục Z hướng lên, hỏi xem có muốn xoay một phần tư vòng quanh trục X không.", - "prefs.stand_up_unknown": "Với tệp từ chương trình không xác định", + "prefs.stand_up_unknown": "Tệp từ chương trình không xác định", "prefs.stand_up_unknown.ask": "Hỏi trong hộp thoại", "prefs.stand_up_unknown.note": "Hiện ghi chú", "prefs.stand_up_unknown.off": "Không gợi ý", - "prefs.stand_up_unknown_note": "Cách gợi ý khi phần đầu tệp không nêu chương trình nào được biết là lưu với trục Y hướng lên. Ghi chú chỉ hiện khi tệp có vẻ đang nằm ngửa; “Hỏi trong hộp thoại” sẽ hỏi với mọi tệp như vậy, như trước đây.", + "prefs.stand_up_unknown_note": "Cách đưa ra đề nghị khi tệp không ghi tên chương trình đã biết.", "prefs.status_bar": "Thanh trạng thái", "prefs.status_bar_note": "Một thanh mảnh dọc cạnh dưới cửa sổ hiển thị thứ đang được chỉnh sửa, trạng thái của bản phác đang mở theo màu của nó và đơn vị của thiết kế; nhấp vào đơn vị để đổi. Khi đó trạng thái bản phác không còn hiện ở góc khung nhìn.", "prefs.status_done": "Hoàn thành", "prefs.status_error": "Lỗi", "prefs.status_selected": "Đã chọn", "prefs.status_warning": "Cảnh báo", + "prefs.structure.appearance": "Giao diện", + "prefs.structure.appearance_note": "Màu sắc, văn bản và khả năng tiếp cận.", + "prefs.structure.in_profile": "Trong hồ sơ", + "prefs.structure.layout": "Bố cục", + "prefs.structure.layout_note": "Vị trí các phần của cửa sổ.", + "prefs.structure.look": "Hiển thị", + "prefs.structure.measure_pointer": "Đo lường và con trỏ", + "prefs.structure.mouse3d": "Chuột 3D", + "prefs.structure.mouse3d_note": "SpaceMouse và SpaceNavigator.", + "prefs.structure.navigation_note": "Chuột và bàn di chuột. Chuột 3D có trang riêng.", + "prefs.structure.profile": "Hồ sơ", + "prefs.structure.profile_edited": "Đã thay đổi kể từ lần lưu", + "prefs.structure.profile_hover": "Được lưu trong hồ sơ cài đặt", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "Phác thảo", + "prefs.structure.tools": "Công cụ", + "prefs.structure.tools_note": "Cách các công cụ dựng mô hình hoạt động.", + "prefs.structure.work": "Công việc", "prefs.supersampling_brief": "Vẽ khung nhìn ở độ phân giải lớn hơn rồi lọc giảm tỷ lệ: rất sắc nét, nhưng tốn tài nguyên hơn.", "prefs.tab_accent_note": "Màu nhấn theo tab đang kích hoạt", "prefs.theme_file": "tệp chủ đề", @@ -2047,6 +2671,21 @@ "prefs.theme_follow_off": "Tắt", "prefs.theme_follow_stop": "Dừng theo dõi", "prefs.theme_import_hint": "Nhấp để chọn tệp giao diện, thả tệp vào đây, hoặc nhấn Ctrl+V (Cmd+V trên Mac) khi đã sao chép một giao diện", + "prefs.theme_notice_dismiss": "Ẩn", + "prefs.theme_option_blur": "Làm mờ phía sau bảng", + "prefs.theme_option_blur_help": "Làm mờ phía sau các bảng bán trong suốt, tính bằng pixel vật lý. Giá trị 0 là tắt.", + "prefs.theme_option_invalid": "Giá trị đã lưu cho {option} không hợp lệ; đang dùng giá trị mặc định của giao diện. Giá trị đã lưu vẫn được giữ lại.", + "prefs.theme_option_opacity": "Độ đục", + "prefs.theme_option_opacity_help": "Điều chỉnh độ đục của các bảng nổi. Giới hạn độ đục tối thiểu giúp văn bản luôn dễ đọc trên nền màu của khung nhìn.", + "prefs.theme_option_tab_colours": "Màu thẻ", + "prefs.theme_option_tab_colours_help": "Sử dụng màu bảng điều khiển và khung nhìn của chủ đề này cho từng thẻ trên dải băng.", + "prefs.theme_option_tab_fade_ms": "Chuyển đổi thẻ", + "prefs.theme_option_tab_fade_ms_help": "Chuyển dần màu của bảng điều khiển và khung nhìn khi đổi thẻ. Đặt thành 0 để chuyển ngay lập tức.", + "prefs.theme_options_badge": "Tùy chọn", + "prefs.theme_options_more": "Thêm · {count}", + "prefs.theme_options_newer": "Giao diện này yêu cầu phiên bản SolidCraft mới hơn. Sau khi nâng cấp, hãy nhập lại giao diện gốc để khôi phục các định nghĩa tùy chọn.", + "prefs.theme_options_reset": "Đặt lại", + "prefs.theme_options_unavailable": "Không khả dụng trên thiết bị này", "prefs.theme_paste": "Dán giao diện", "prefs.theme_paste_none": "Bộ nhớ tạm không chứa giao diện SolidCraft nào", "prefs.timeline_half_hour": "−30 phút", @@ -2068,13 +2707,29 @@ "prefs.under_cursor": "Dưới con trỏ chuột", "prefs.units_precision": "Đơn vị và độ chính xác", "prefs.updates": "Cập nhật ứng dụng", + "prefs.validation": "Kiểm tra thân", + "prefs.validation.each_feature": "Một lần mỗi đặc trưng", + "prefs.validation.each_step": "Sau mỗi bước", + "prefs.validation.label": "Kiểm tra kernel đầy đủ", + "prefs.validation.off": "Tắt (thử nghiệm)", + "prefs.validation_note": "Sau mỗi bước: kiểm tra từng lần quét, phép boolean và đường bo.\nMột lần mỗi đặc trưng: kiểm tra kết quả của từng đặc trưng một lần.\nTắt (thử nghiệm): không kiểm tra.", + "prefs.value_boxes_in_view": "Hiện giá trị bên cạnh tay nắm", + "prefs.value_boxes_in_view_tip": "Khoảng cách Đùn, Bán kính Bo góc... dưới dạng ô trong khung nhìn.", "prefs.view": "Hành vi góc nhìn", "prefs.view_confirm_corner": "Nút Đồng ý và Hủy bỏ ở góc khung nhìn", "prefs.view_confirm_corner_note": "Khi hộp thoại hoặc môi trường phác thảo đang mở, dấu tích và dấu chéo ở góc trên bên phải khung nhìn có chức năng tương tự nút Đồng ý và Hủy bỏ của hộp thoại, hoặc để hoàn tất và hủy phác thảo. Khối điều hướng góc nhìn sẽ dời xuống bên dưới chúng.", "prefs.viewport": "Khung nhìn 3D", + "prefs.viewport_analysis_status": "Hiện trạng thái phân tích trong khung nhìn", + "prefs.viewport_analysis_status_help": "Hiện các phân tích đang bật phía trên khung nhìn và mở chú giải từ từng mục. Esc tắt phân tích mới nhất. Tắt tùy chọn để khôi phục chú giải ở góc và hành vi Esc trước đây.", "prefs.viewport_background": "Nền", "prefs.viewport_background_colour": "Màu", "prefs.viewport_background_theme": "Dải màu của chủ đề", + "prefs.viewport_section_status": "Hiện trạng thái mặt cắt trong khung nhìn", + "prefs.viewport_section_status_help": "Hiện thiết lập mặt cắt trong khung nhìn. Escape và nút dải công cụ đang bật sẽ tắt mặt cắt. Tắt tùy chọn để giữ cách điều khiển mặt cắt trước đây.", + "prefs.viewport_status_details": "Chi tiết trực tiếp trong khung nhìn", + "prefs.viewport_status_details_help": "Chỉnh sửa thiết lập phân tích và mặt cắt đang hoạt động trong các thẻ chi tiết chuẩn. Tắt để khôi phục chú giải phân tích chỉ đọc và hộp thoại Mặt cắt.", + "prefs.viewport_status_summary": "Tóm tắt các mục trạng thái khung nhìn", + "prefs.viewport_status_summary_help": "Gộp từ ba mục trạng thái khung nhìn trở lên thành một huy hiệu tóm tắt. Tắt để giữ mọi mục trong hàng đầy đủ.", "prefs.wheel": "Con lăn chuột", "prefs.wheel_trackpad": "Con lăn chuột và bàn di cảm ứng", "prefs.workspace": "Không gian làm việc", @@ -2092,6 +2747,17 @@ "recovery.just_now": "vừa xong", "recovery.min_ago": "{count} phút trước", "recovery.never_saved": "chưa từng lưu", + "refused.change": "Không thể thay đổi {body}.", + "refused.cut": "Không thể cắt {body}.", + "refused.face_curved": "Một trong các mặt cong của nó không dùng được để mô hình hóa.", + "refused.face_flat": "Một trong các mặt phẳng của nó không dùng được để mô hình hóa.", + "refused.face_freeform": "Một trong các mặt tự do của nó không dùng được để mô hình hóa.", + "refused.face_rounded": "Một trong các mặt bo tròn của nó không dùng được để mô hình hóa.", + "refused.faces_apart": "Các mặt của nó không gặp nhau đủ khít để dùng cho mô hình hóa.", + "refused.intersect": "Không thể giao với {body}.", + "refused.join": "Không thể nối vào {body}.", + "refused.repair": "Sửa chi tiết", + "refused.show_face": "Hiện mặt", "render.adaptive_absolute": "Ngưỡng lỗi RGB tuyệt đối", "render.adaptive_coverage": "Mục tiêu lỗi độ phủ (Coverage error)", "render.adaptive_enable": "Phân bổ mẫu bằng các mẫu thử độc lập", @@ -2203,6 +2869,10 @@ "render.base_color": "Màu cơ sở · sRGB", "render.base_metallic": "Tỷ lệ kim loại", "render.base_opaque_only": "Trình chỉnh sửa này giữ nguyên ngữ nghĩa khối đục. Dùng các điều khiển thủy tinh riêng biệt để chỉnh độ truyền quang học.", + "render.batch_all_shots": "Mọi cảnh chụp ({count})", + "render.batch_empty": "Hãy lưu một cảnh chụp trước khi kết xuất mọi cảnh chụp.", + "render.batch_limit": "Kết xuất mọi cảnh chụp giới hạn ở 32 cảnh chụp.", + "render.batch_status": "{running} đang chạy · {waiting} đang chờ", "render.bloom_enable": "Hiển thị lóe sáng (Bloom)", "render.bloom_help": "Hiệu ứng phát sáng sáng tạo cho đầu ra từ các điểm nhấn tuyến tính dương, được khuếch tán qua ba lượt lọc chuẩn hóa. Bán kính tính theo pixel đầu ra. Được cộng vào ánh sáng tuyến tính hiển thị trước sRGB; không phải ống kính thực tế, hiệu ứng thể tích hay cải thiện hội tụ. Tệp EXR thô không đổi.", "render.bloom_opaque": "Hiệu ứng lóe sáng yêu cầu đầu ra đục. PNG trong suốt sẽ bị từ chối chứ không âm thầm làm phẳng nền.", @@ -2313,6 +2983,13 @@ "render.choose_look": "Hãy chọn một diện mạo trong Diện mạo trước", "render.chromatic_offset": "Độ lệch sắc sai viền", "render.clear_stage": "Xóa sân khấu đã lưu", + "render.compare_divider": "Vạch so sánh", + "render.compare_live": "Trực tiếp", + "render.compare_live_preview": "Xem trước trực tiếp", + "render.compare_render": "Kết xuất {number}", + "render.compare_side": "Kết xuất {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} giây · {renderer} · ghi tại bản sửa {revision}", + "render.compare_swap": "Hoán đổi", "render.copy_request": "Sao chép JSON", "render.cpu_aa_help": "Số mẫu không gian: tăng số mẫu giúp cạnh mượt hơn nhưng tăng thời gian kết xuất.", "render.cpu_area_add": "Thêm nguồn sáng vùng chữ nhật CPU", @@ -2953,7 +3630,9 @@ "render.output_ready": "Sẵn sàng kết xuất", "render.output_run_check": "Chạy kiểm tra", "render.output_size_limit": "{method}: tối đa {dimension} px mỗi cạnh và {pixels} điểm ảnh. Kích thước lớn nhất vừa khít: {width} × {height}.", + "render.output_size_method_profile": "Để kết xuất {width} × {height}, hãy chọn {method} với cấu hình tài nguyên CPU {profile} hoặc một kích thước nhỏ hơn.", "render.output_size_ok": "Kích thước ổn · {width} × {height} px", + "render.output_size_profile": "Để kết xuất {width} × {height}, hãy chọn cấu hình tài nguyên CPU {profile} hoặc một kích thước nhỏ hơn.", "render.output_swap_orientation": "Hoán đổi chiều rộng và chiều cao", "render.output_tools_inspector": "Chỉnh kích thước và định dạng trong bảng thuộc tính Đầu ra.", "render.output_view_image": "Xem ảnh", @@ -3060,6 +3739,10 @@ "render.result_retained": "Đang hiển thị hình ảnh hoàn thành gần nhất; kết xuất mới hơn chưa thay thế nó.", "render.result_sequence": "Điểm kiểm tra trung gian", "render.result_title": "Kết quả kết xuất", + "render.results_choose": "Kết quả được giữ lại", + "render.results_label": "Kết xuất {number} · {shot} · {seconds} giây", + "render.results_stale_label": "{result} [cũ]", + "render.results_unnamed": "Ảnh", "render.return_design": "Quay lại thiết kế", "render.review_stale": "Kết quả xem xét này đã cũ. Hãy xử lý hoặc kiểm tra lại trước khi áp dụng.", "render.ribbon_aging": "Lão hóa", @@ -3166,6 +3849,7 @@ "render.size_custom": "Tùy chỉnh…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · cần {profile}", "render.size_presets": "Cỡ đặt sẵn", "render.size_presets_pending": "Sẽ có cùng trình chỉnh Đầu ra", "render.size_preview": "Xem trước", @@ -3431,11 +4115,11 @@ "select two components": "chọn hai thành phần", "set by the sketch's lines": "xác định bởi các đường của phác thảo", "settings.display_quality_note": "Mức độ chi tiết cao hơn giúp hiển thị các mặt cong và cạnh mượt mà hơn nhưng tốn nhiều thời gian tạo lưới hơn. Thiết lập này chỉ thay đổi vùng nhìn, không ảnh hưởng đến thiết kế hay dữ liệu xuất tệp.", - "settings.double_click_components": "Nhấp đúp vào một thành phần để kích hoạt nó, hoặc chỉnh sửa tại chỗ một thành phần liên kết", + "settings.double_click_components": "Nhấp đúp vào thành phần để kích hoạt", "settings.frame_rate_details_note": "Bổ sung biểu đồ thời gian các khung hình gần nhất xếp chồng số tam giác đã vẽ, biểu đồ phân bố thời gian khung hình và nội dung GPU đã vẽ. Bấm vào tốc độ khung hình trên khung nhìn để ẩn/hiện.", "settings.frame_rate_note": "Hiển thị số khung hình trên giây (FPS) ở góc dưới bên phải khung nhìn.", - "settings.insert_lists_open_designs": "Chèn thiết kế vào cụm liệt kê trước các thiết kế đang mở ở các thẻ khác", - "settings.measure_axis_distances": "Hiển thị khoảng cách theo trục X/Y/Z", + "settings.insert_lists_open_designs": "Chèn thiết kế liệt kê thiết kế đang mở trước", + "settings.measure_axis_distances": "Khoảng cách theo trục trong Đo", "settings.measure_axis_distances_help": "Hiển thị kích thước thành phần theo các trục tọa độ cùng với khoảng cách tổng thể khi mở công cụ Đo lường.", "settings.msaa_applies_on_restart": "Khử răng cưa sẽ áp dụng vào lần khởi động tiếp theo của SolidCraft", "settings.msaa_reset": "{setting}: Mức {requested}× không được hỗ trợ bởi thiết bị đồ họa này; đã đặt về {reset}× (hỗ trợ: {supported}).", @@ -3445,7 +4129,7 @@ "settings.reset_intro": "Các cài đặt sau không hoạt động trên máy tính này và có thể khiến SolidCraft không thể khởi động, vì vậy chúng đã được tự động điều chỉnh:", "settings.reset_title": "Cài đặt đã được thay đổi", "settings.supersampling_note": "Vẽ khung nhìn ở độ phân giải cao hơn rồi nén lại: giúp các cạnh, đường nét và lưới mượt mà hơn trên màn hình dưới 4K. Tính năng này tiêu tốn tài nguyên GPU: gấp khoảng 2,25 lần số điểm ảnh ở mức 1,5× và 4 lần ở mức 2×.", - "settings.update_changed_links": "Cập nhật các thiết kế liên kết đã thay đổi khi quay lại một thẻ", + "settings.update_changed_links": "Cập nhật liên kết đã thay đổi khi quay lại thẻ", "settings.window_system_details": "Chi tiết", "settings.window_system_note_now": "Áp dụng sau khi khởi động lại. Hiện tại: {now}.", "settings.window_system_wayland_limited": "Một số tính năng bị giới hạn trên Wayland gốc.", @@ -3453,6 +4137,24 @@ "sheet.flange_type_contour": "Đường viền", "sheet.flange_type_edge": "Cạnh", "sheet.no_body": "chưa có khối tấm kim loại: hãy bắt đầu bằng Cánh gập > Cơ sở (Base), hoặc chuyển một tấm phẳng thành tấm kim loại bằng lệnh 'Chuyển thành tấm kim loại' (chọn mặt phẳng lớn của nó)", + "sheet.personal_rules.confirm_delete": "Xác nhận xóa", + "sheet.personal_rules.delete": "Xóa", + "sheet.personal_rules.delete_prompt": "Xóa quy tắc cá nhân này? Các quy tắc đã có trong thiết kế sẽ không thay đổi.", + "sheet.personal_rules.full": "Thư viện cá nhân đã chứa tối đa 64 quy tắc.", + "sheet.personal_rules.invalid_name": "Nhập một tên ngắn gọn, không chứa ký tự xuống dòng hoặc ký tự điều khiển.", + "sheet.personal_rules.invalid_values": "Hãy điền đủ các giá trị của quy tắc: mỗi giá trị phải tính được trong thiết kế này, với độ dày dương và hệ số K từ 0 đến 1.", + "sheet.personal_rules.missing": "Quy tắc cá nhân đã chọn không còn khả dụng.", + "sheet.personal_rules.name": "Tên quy tắc", + "sheet.personal_rules.name_exists": "Quy tắc cá nhân với tên này đã tồn tại. Vui lòng sử dụng tên khác.", + "sheet.personal_rules.name_hint": "Tên duy nhất", + "sheet.personal_rules.overwrite": "Lưu các thay đổi vào quy tắc cá nhân đã chọn", + "sheet.personal_rules.rename": "Đổi tên", + "sheet.personal_rules.rule": "Quy tắc cá nhân", + "sheet.personal_rules.save": "Lưu mới", + "sheet.personal_rules.scope": "Được lưu trong hồ sơ cá nhân của bạn cho tất cả thiết kế.", + "sheet.personal_rules.select": "Chọn một quy tắc", + "sheet.personal_rules.title": "Quy tắc cá nhân", + "sheet.personal_rules.unsupported": "Quy tắc này có các giá trị mà phiên bản hiện tại không thể sử dụng.", "shortcut.json_error": "tham số phải là JSON: {error}", "shortcut.no_command": "không có lệnh `{id}`; văn bản trước JSON phải là mã lệnh", "shortcut.pin": "Ghim lên đầu hộp S", @@ -3489,8 +4191,10 @@ "sketch_text.align_right": "Phải", "sketch_text.bold": "In đậm", "sketch_text.builtin_font": "{family} (tích hợp sẵn)", + "sketch_text.formula": "Bắt đầu bằng = để tạo chữ từ các tham số: ='W' + number(Width)", "sketch_text.italic": "In nghiêng", "sketch_text.loading_fonts": "Đang tìm kiếm các phông chữ đã cài đặt…", + "sketch_text.no_bold": "Phông chữ tích hợp không có kiểu in đậm: chọn một phông chữ đã cài đặt", "sketch_text.on_path": "Văn bản đi theo đường dẫn: đường cong định vị văn bản", "sketch_text.path_clear": "Gỡ văn bản khỏi đường cong dẫn", "sketch_text.path_hint": "Đường cong phác thảo mà văn bản chạy theo: nhấp vào đây, sau đó chọn đường cong", @@ -3521,11 +4225,20 @@ "the section's profiles must be in one sketch": "các biên dạng của mặt cắt phải nằm trong cùng một phác thảo", "the two origins are on the same component": "hai gốc tọa độ nằm trên cùng một thành phần", "thread.automatic_size": "Kích thước tự động", + "thread.chamfer_depth_needed": "bắt buộc với dạng này", "thread.designation": "Ký hiệu ren", - "thread.direction": "Chiều ren", + "thread.drill_range": "Mũi khoan của nhà sản xuất taro là {drill} mm. Đường kính trong tiêu chuẩn của ren trong là {minor} mm. Chấp nhận mũi khoan từ {low} đến {high} mm.", + "thread.drill_range_custom": "Mũi khoan bằng đường kính ngoài trừ bước ren, {drill} mm. Đường kính trong tiêu chuẩn của ren trong là {minor} mm. Chấp nhận mũi khoan từ {low} đến {high} mm.", + "thread.drill_range_taper": "Mũi khoan của nhà sản xuất taro là {drill} mm. Đường kính trong theo tiêu chuẩn tại nơi ren kết thúc là {minor} mm. Chấp nhận mũi khoan từ {low} đến {high} mm.", + "thread.end_square": "Vuông", + "thread.fade_short": "1,25 P (ISO 3508)", + "thread.fade_standard": "2,5 P (ISO 3508)", + "thread.fits_the_face": "vừa với mặt, ví dụ {example}", + "thread.form_bspp": "Ống G (ISO 228-1)", + "thread.form_bspt": "Ống côn R, Rc (ISO 7-1)", + "thread.form_npt": "Ống côn NPT (ASME B1.20.1)", + "thread.form_rp": "Ống Rp (ISO 7-1)", "thread.iso_metric": "Hệ mét ISO", - "thread.left_hand": "Ren trái", - "thread.right_hand": "Ren phải", "thread.select_size": "Chọn kích thước", "timeline.delete_after_marker_one": "Xóa 1 tính năng sau điểm đánh dấu lịch sử", "timeline.delete_after_marker_other": "Xóa {count} tính năng sau điểm đánh dấu lịch sử", @@ -3629,6 +4342,8 @@ "ui.3d_mouse_section": "Chuột 3D", "ui.3d_mouse_show_in_view": "Hiện chuột 3D trong khung nhìn 3D", "ui.3d_mouse_show_in_view_tip": "Hình chuột 3D của bạn ở góc dưới bên trái, chuyển động theo bạn.", + "ui.3d_mouse_sketch_orbit": "Xoay bản phác thảo bằng chuột 3D", + "ui.3d_mouse_sketch_orbit_tip": "Chuột 3D cũng xoay khung nhìn khi bản phác thảo đang mở và được nhìn thẳng, như chuột thường. Tắt: chỉ di chuyển và thu phóng bản phác thảo cho đến khi bạn nghiêng khung nhìn.", "ui.3d_mouse_skip": "Thiết bị của tôi không làm được điều này", "ui.3d_mouse_skip_tip": "Bỏ qua chuyển động này theo cả hai chiều; việc hiệu chuẩn sẽ không dùng nó.", "ui.3d_mouse_speed": "Tốc độ chuột 3D", @@ -3657,6 +4372,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "Xoay núm điều khiển ngược chiều kim đồng hồ, giữ nguyên, rồi thả ra.", "ui.3d_mouse_switch_cap": "Hiệu chuẩn theo kiểu trở về giữa", "ui.3d_mouse_switch_trackball": "Hiệu chuẩn như bi xoay", + "ui.3d_mouse_use_direct": "Dùng trình điều khiển trực tiếp", + "ui.3d_mouse_use_direct_tip": "Đọc chuột 3D trực tiếp (hidraw) thay vì qua spacenavd.", "ui.3d_mouse_view_axis": "Trục khung nhìn", "ui.3d_mouse_view_off": "Tắt", "ui.3d_mouse_view_off_tip": "Hồ sơ của trình điều khiển chuột 3D tắt trục này, nên chuyển động của nó không làm khung nhìn di chuyển. Chọn chuyển động của trục khác ở đây sẽ hoán đổi hai trục, và chuyển động đó không còn di chuyển khung nhìn.", @@ -3695,6 +4412,8 @@ "ui.agent_chat_auth_terminal": "Chạy lệnh này trong cửa sổ dòng lệnh, sau đó nhấp Kết nối lại:", "ui.agent_chat_auth_title": "Đăng nhập vào AI Agent", "ui.agent_chat_cancel": "Hủy bỏ", + "ui.agent_chat_cancel_timeout": "Tác nhân không phản hồi yêu cầu Dừng nên đã bị ngắt kết nối. Hãy kết nối lại để tiếp tục.", + "ui.agent_chat_cannot_start": "Đã cài đặt nhưng không khởi động được: {error}", "ui.agent_chat_changes": "Thay đổi: {n}, trong 1 bước hoàn tác", "ui.agent_chat_changes_n": "{n} thay đổi", "ui.agent_chat_changes_of": "{n}/{limit} thay đổi", @@ -3703,11 +4422,13 @@ "ui.agent_chat_command": "Lệnh của AI Agent", "ui.agent_chat_connect": "Kết nối", "ui.agent_chat_copy": "Sao chép", + "ui.agent_chat_copy_message": "Sao chép tin nhắn", "ui.agent_chat_ctx_bodies": "Khối", "ui.agent_chat_ctx_elements": "Phần tử", "ui.agent_chat_ctx_features": "Tính năng", "ui.agent_chat_ctx_more": "+{n} mục khác", "ui.agent_chat_ctx_other": "Khác", + "ui.agent_chat_custom_heading": "Mô hình tùy chỉnh", "ui.agent_chat_custom_hint": "Bất kỳ chương trình nào hỗ trợ giao thức Agent Client Protocol qua stdin và stdout. Không chạy qua shell hệ thống.", "ui.agent_chat_denied": "Đã từ chối", "ui.agent_chat_deny": "Từ chối", @@ -3751,8 +4472,16 @@ "ui.agent_chat_mode_all": "Tất cả", "ui.agent_chat_mode_ask": "Hỏi", "ui.agent_chat_mode_edits": "Chỉnh sửa", + "ui.agent_chat_model_custom": "Dùng tùy chỉnh: {model}", "ui.agent_chat_model_no_tools": "{model} không thể sử dụng các công cụ của SolidCraft nên chỉ có thể trò chuyện. Hãy chọn mô hình có hỗ trợ công cụ.", + "ui.agent_chat_model_rejected": "Tác tử không chấp nhận {model}: {error}", + "ui.agent_chat_model_search": "Tìm mô hình…", "ui.agent_chat_model_tip": "Mô hình AI đang sử dụng. Lựa chọn của bạn sẽ được ghi nhớ cho Agent này.", + "ui.agent_chat_models_failed": "Không thể lấy danh sách mô hình: {error}", + "ui.agent_chat_models_heading": "Các mô hình có sẵn", + "ui.agent_chat_models_listing": "Đang lấy danh sách mô hình…", + "ui.agent_chat_models_none": "Điểm cuối không liệt kê mô hình nào", + "ui.agent_chat_models_not_a_list": "Phản hồi không phải là danh sách mô hình", "ui.agent_chat_new": "Cuộc trò chuyện mới", "ui.agent_chat_new_confirm": "Bắt đầu cuộc trò chuyện mới? Cuộc trò chuyện hiện tại sẽ bị xóa.", "ui.agent_chat_next_picture": "Ảnh kế tiếp", @@ -3761,6 +4490,7 @@ "ui.agent_chat_no_images": "AI Agent này không hỗ trợ tiếp nhận hình ảnh", "ui.agent_chat_no_picture": "Không có hình ảnh trong bộ nhớ tạm", "ui.agent_chat_no_tool_call": "Mô hình không sử dụng các công cụ của SolidCraft nên thiết kế không thay đổi. Hãy chọn mô hình hỗ trợ gọi công cụ; xem mục Mô hình cục bộ trong hướng dẫn trò chuyện AI.", + "ui.agent_chat_node_too_old": "Node.js {version} quá cũ đối với tác nhân này. Hãy cài đặt Node.js 20.10 trở lên, rồi nhấn Làm mới.", "ui.agent_chat_none_found": "Không tìm thấy tác tử lập trình nào. Hãy cài đặt một trong các tác tử sau, rồi nhấn Làm mới:", "ui.agent_chat_none_found_short": "Không tìm thấy tác tử nào", "ui.agent_chat_not_installed": "Chưa cài đặt", @@ -3787,9 +4517,12 @@ "ui.agent_chat_queued_stopped": "Đã xếp hàng (đã dừng, chưa gửi)", "ui.agent_chat_refresh": "Làm mới", "ui.agent_chat_refused": "Không được phép đối với tác tử: {reason}", + "ui.agent_chat_reinstall": "{agent} đã được cài đặt ({program}) nhưng không khởi động khi SolidCraft kiểm tra: {error}\nBản cài đặt có thể chưa hoàn tất, hoặc dành cho loại máy tính khác. Hãy cài lại bằng `{install}`, kiểm tra rằng nó in ra phiên bản trong terminal, rồi nhấn Làm mới.", "ui.agent_chat_remove": "Xóa khỏi hàng đợi", "ui.agent_chat_remove_file": "Bỏ tệp này khỏi tin nhắn", "ui.agent_chat_remove_imported": "Gỡ khỏi tin nhắn này; chi tiết vẫn nằm trong thiết kế (sử dụng Hoàn tác để xóa)", + "ui.agent_chat_reply_cut_off": "Câu trả lời đã chạm giới hạn độ dài trước khi xong nên có thể chưa đầy đủ. Hãy yêu cầu AI Agent tiếp tục, hoặc trả lời ngắn hơn.", + "ui.agent_chat_reply_declined": "Mô hình đã từ chối trả lời tin nhắn này.", "ui.agent_chat_retry": "Thử lại", "ui.agent_chat_right": "Phải (Hình chiếu cạnh)", "ui.agent_chat_save": "Lưu", @@ -3798,7 +4531,7 @@ "ui.agent_chat_send_now_tip": "Dừng bước hiện tại của tác tử và gửi tin nhắn này ngay (Ctrl+Enter)", "ui.agent_chat_setup_body": "SolidCraft giao tiếp với một tác nhân lập trình được cài đặt trên máy tính này. Chọn một tác nhân trong Tùy chọn cài đặt › AI.", "ui.agent_chat_setup_title": "Thiết lập trợ lý", - "ui.agent_chat_side": "Vị trí bảng trò chuyện AI", + "ui.agent_chat_side": "Gắn khung trò chuyện", "ui.agent_chat_signed_in": "đã đăng nhập", "ui.agent_chat_state_auth": "Cần đăng nhập", "ui.agent_chat_state_busy": "Đang xử lý…", @@ -3817,7 +4550,7 @@ "ui.agent_chat_undone": "(hoàn tácne)", "ui.agent_chat_view_attached": "Đã đính kèm góc nhìn", "ui.agent_chat_waiting": "Đang chờ bạn", - "ui.agent_cursor": "Con trỏ AI", + "ui.agent_cursor": "Con trỏ tác nhân", "ui.agent_cursor_speed": "Tốc độ con trỏ AI", "ui.agent_off_thread": "Giữ giao diện phản hồi mượt mà khi agent AI thực thi lệnh", "ui.agent_off_thread_note": "Các lệnh tốn thời gian của agent (từ bảng AI hoặc MCP client) được tính toán song song ngoài luồng cửa sổ: bạn vẫn có thể xoay và kiểm tra vùng nhìn, và có thể dừng lệnh bất cứ lúc nào từ thẻ trạng thái trong khung nhìn. Khi tắt: mỗi lệnh sẽ chạy trên luồng cửa sổ và cửa sổ sẽ phải chờ cho đến khi hoàn thành.", @@ -3848,24 +4581,29 @@ "ui.ai_copy_suffix": "sao chép", "ui.ai_custom_url": "URL tùy chỉnh", "ui.ai_default": "Mặc định", + "ui.ai_edit": "Sửa", + "ui.ai_edit_agent_title": "Sửa AI Agent", + "ui.ai_edit_gone": "AI Agent này đã bị xóa nên không có gì để lưu.", + "ui.ai_edit_tip": "Đổi tên, lệnh hoặc endpoint của AI Agent này. Khóa đã lưu vẫn được ẩn.", "ui.ai_http_busy": "điểm cuối đang bận hoặc vượt quá giới hạn; vui lòng thử lại sau", "ui.ai_http_key": "điểm cuối từ chối khóa API: hãy kiểm tra trong Tùy chọn cài đặt > AI", "ui.ai_http_not_found": "không tìm thấy điểm cuối hoặc mô hình: hãy kiểm tra URL cơ sở và tên mô hình", "ui.ai_http_too_large": "cuộc trò chuyện quá lớn đối với điểm cuối này; hãy bắt đầu cuộc trò chuyện mới", "ui.ai_key": "Khóa API", "ui.ai_key_hint": "tùy chọn; lưu trữ bảo mật trong chuỗi khóa hệ thống", + "ui.ai_key_keep_hint": "để trống để giữ khóa đã lưu", "ui.ai_key_needs_https": "Khóa chỉ được gửi qua HTTPS, hoặc trực tiếp trên máy tính này.", "ui.ai_key_note": "Được lưu an toàn trong Keychain hệ thống, không lưu trong cài đặt của SolidCraft. Để trống nếu dùng máy chủ cục bộ.", "ui.ai_keychain_error": "Chuỗi khóa hệ thống từ chối: {error}", "ui.ai_kind": "Loại", - "ui.ai_mode_all": "Cho phép tất cả", + "ui.ai_mode_all": "Làm mọi việc", "ui.ai_mode_all_note": "Không yêu cầu xác nhận trước. Báo cáo sự cố và các thư mục giới hạn vẫn được bảo vệ.", "ui.ai_mode_all_warning": "Tác tử có thể lưu, ghi đè, xuất tệp và thay thế thiết kế của bạn mà không cần hỏi. Chỉ sử dụng chế độ này với tác tử bạn tin tưởng và trên các thiết kế đã được lưu.", - "ui.ai_mode_ask": "Hỏi mỗi lần", + "ui.ai_mode_ask": "Hỏi trước", "ui.ai_mode_ask_note": "Mọi thay đổi đối với thiết kế và mọi thao tác tệp đều cần bạn xác nhận Cho phép.", - "ui.ai_mode_edits": "Tự động cho phép chỉnh sửa mô hình", + "ui.ai_mode_edits": "Cho phép chỉnh sửa", "ui.ai_mode_edits_note": "Các lệnh tạo mô hình sẽ chạy mà không cần hỏi; các hành động lưu, mở, xuất và các thao tác tệp hoặc hủy hoại khác vẫn sẽ hỏi ý kiến bạn.", - "ui.ai_mode_global": "Theo cài đặt bên trên", + "ui.ai_mode_global": "Giống bên trên", "ui.ai_model": "Mô hình AI", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "Các cài đặt này áp dụng cho các công cụ của SolidCraft. Công cụ riêng của tác tử (shell hệ thống, chỉnh sửa tệp) tuân theo chế độ riêng của tác tử, được chọn trên thanh tiêu đề bảng điều khiển trò chuyện.", @@ -3880,14 +4618,18 @@ "ui.ai_permissions": "Quyền hạn", "ui.ai_preset": "Mẫu cấu hình sẵn", "ui.ai_protocol": "Giao thức", + "ui.ai_reasoning_effort": "Mức độ suy luận", + "ui.ai_reasoning_effort_field_hint": "trống = mặc định của nhà cung cấp", + "ui.ai_reasoning_effort_hint": "Tùy chọn. Được gửi tới điểm cuối dưới dạng `reasoning_effort`; các giá trị được chấp nhận khác nhau tùy nhà cung cấp (ví dụ: `low`, `high` hoặc `max`). Giá trị bạn đặt ở đây không bao giờ bị SolidCraft thay thế. Để trống để không gửi gì và giữ mặc định của nhà cung cấp.", "ui.ai_remove": "Xóa", "ui.ai_request_timed_out": "Mô hình phản hồi lâu hơn {seconds} giây. Bạn có thể tăng thời gian chờ yêu cầu cho điểm cuối này trong Tùy chọn › Trợ lý.", "ui.ai_request_timeout": "Thời gian chờ yêu cầu", "ui.ai_request_timeout_hint": "Thời gian tối đa cho một yêu cầu tới điểm cuối này, từ 30 giây đến 1 giờ. Hãy tăng giá trị này đối với mô hình cục bộ xử lý chậm.", "ui.ai_reset": "Đặt lại", + "ui.ai_save": "Lưu", "ui.ai_settings": "AI cài đặt…", "ui.ai_show_features": "Hiển thị các tính năng AI", - "ui.ai_show_features_note": "Trò chuyện với tác tử: bảng điều khiển nơi tác tử lập trình hoặc điểm cuối mô hình thao tác trên thiết kế đang mở. Tắt: ẩn nút AI, phím tắt, menu và bảng điều khiển, không tìm kiếm hay khởi chạy tác tử.", + "ui.ai_show_features_note": "Tắt sẽ ẩn Trợ lý ở mọi nơi và không khởi chạy gì. Mọi mục bên dưới đều mờ đi.\n\nTrò chuyện với tác tử: bảng điều khiển nơi tác tử lập trình hoặc điểm cuối mô hình thao tác trên thiết kế đang mở. Tắt: ẩn nút AI, phím tắt, menu và bảng điều khiển, không tìm kiếm hay khởi chạy tác tử.", "ui.ai_switch_tip": "Chuyển đổi AI Agent cho cuộc hội thoại này", "ui.ai_test": "Kiểm tra", "ui.ai_test_acp_ok": "Phản hồi: {agent}", @@ -3921,7 +4663,7 @@ "ui.ai_tool_sum_then": "{first}, sau đó {next}", "ui.ai_tool_unfold": "Nhấp để xem nội dung trả về", "ui.ai_tool_waiting": "đang chờ", - "ui.ai_toolbar_button": "Hiển thị nút trên thanh công cụ", + "ui.ai_toolbar_button": "Nút Trợ lý trên thanh ứng dụng", "ui.ai_toolbar_button_note": "Nút AI ở góc phải thanh công cụ. Phím tắt Ctrl+Shift+A và menu Khung nhìn vẫn có thể mở bảng điều khiển.", "ui.ai_undo_tip": "Hoàn tác mọi thay đổi do tác tử thực hiện cho tin nhắn này, như một bước duy nhất", "ui.ai_url_hint": "https://example.com/v1", @@ -3968,11 +4710,14 @@ "ui.centerline": "Đường tâm", "ui.chain": "Chuỗi", "ui.chamfer": "Vát mép", + "ui.chamfer_angle": "Góc vát", + "ui.chamfer_depth": "Chiều sâu vát", "ui.chamfer_type": "Kiểu vát mép", "ui.change_workspace": "Đổi không gian làm việc", "ui.circle": "Hình tròn", "ui.circular_pattern": "Mảng tròn quanh trục", "ui.clear": "Xóa", + "ui.clear_print_face": "Xóa mặt in", "ui.clear_recent": "Xóa danh sách gần đây", "ui.clear_the_selection": "Hủy chọn", "ui.click_selects_whole_bodies": "Nhấp chuột chọn toàn bộ thân khối", @@ -3997,10 +4742,16 @@ "ui.colour_vision_sample": "Mẫu thử", "ui.colour_vision_tritan": "Mù màu xanh dương (Tritan)", "ui.colour_vision_tritan_tip": "Dành cho người cảm nhận màu xanh dương yếu hoặc mất hẳn", + "ui.comb_length": "Độ dài lược", + "ui.comb_length_tip": "Độ dài của các răng: bội số của độ dài tự động, độ dài này làm răng dài nhất bằng một phần năm kích thước các đường cong được hiển thị.", + "ui.comb_teeth": "Răng", + "ui.comb_teeth_tip": "Số răng của mỗi lược, cách đều dọc theo đường cong. Càng nhiều răng càng thấy rõ độ cong thay đổi thế nào.", "ui.combine": "Hợp nhất / Cắt khối", "ui.coming_later": "sắp ra mắt", "ui.command_done": "Hoàn tất lệnh {command}", "ui.command_palette_hint": "Nhập một lệnh, ví dụ: {example} — hoặc nhấn S để tìm kiếm", + "ui.components_from_bodies_hint": "Tạo một thành phần cho mỗi vật thể đã chọn, đặt tên theo vật thể đó, bên dưới thành phần đang hoạt động.", + "ui.components_from_bodies_required": "Chọn ít nhất một vật thể.", "ui.concentric": "Đồng tâm", "ui.cone": "Hình nón", "ui.conic_curve": "Đường cong Conic", @@ -4013,15 +4764,30 @@ "ui.construction.contact_hint": "Tiếp tuyến: chọn đường tròn/cung hoặc spline/conic hở rồi chọn tiếp điểm (đường cong tự do: chỉ đầu mút)", "ui.construction.external_hint": "Tiếp tuyến: chọn đường tròn hoặc cung, điểm ngoài rồi chọn nghiệm mong muốn", "ui.construction.free_hint": "Đường dựng hình: nhấp hai điểm; nhấp chuột phải để bắt đầu lại", + "ui.construction.normal_needs_length": "Đường vô hạn luôn là đường dựng hình: nhập chiều dài để vẽ đường thường", "ui.construction.point_hint": "Đường dựng hình: nhấp điểm đi qua", "ui.construction.reference_hint": "Đường dựng hình: chọn đường thẳng rồi chọn điểm; nhấp chuột phải để đổi tham chiếu", "ui.construction.ribbon_label": "Đường phụ", + "ui.construction.side_hint": "Đường dựng hình: nhấp phía mà đường kéo dài tới; nhấp chuột phải để bắt đầu lại", "ui.context_menu": "Menu ngữ cảnh", + "ui.continuity_crease": "Nếp gập", + "ui.continuity_curvature": "Độ cong", + "ui.continuity_curvature_change": "Thay đổi độ cong", + "ui.continuity_curvature_change_tip": "Thay đổi độ cong (G3): độ cong cũng thay đổi trơn qua đường nối.", + "ui.continuity_curvature_tip": "Liên tục độ cong (G2): phản chiếu đi qua mà không bị gãy.", "ui.continuity_g0": "Nếp gập G0", "ui.continuity_g1": "G1 tiếp tuyến", "ui.continuity_g2": "G2 độ cong", "ui.continuity_gap": "Khe hở", + "ui.continuity_position": "Vị trí liên tục", + "ui.continuity_position_tip": "Vị trí (G0): các bề mặt gặp nhau, tạo nếp gấp tại nơi đó.", + "ui.continuity_smooth_curvature_change": "Thay đổi độ cong trơn", + "ui.continuity_smooth_curvature_change_tip": "Thay đổi độ cong trơn (G4): ngay cả cách độ cong thay đổi cũng liền mạch qua đường nối.", + "ui.continuity_tangent": "Tiếp tuyến", + "ui.continuity_tangent_tip": "Tiếp tuyến (G1): không có nếp gấp, nhưng độ cong nhảy qua đường nối.", "ui.copy": "Sao chép", + "ui.copy_details": "Sao chép chi tiết", + "ui.copy_details_tip": "Sao chép toàn bộ thông báo để tra cứu hoặc báo cáo.", "ui.corner": "Góc", "ui.corners": "Các góc", "ui.cosmetic_thread_markings": "Ký hiệu ren quy ước", @@ -4043,6 +4809,8 @@ "ui.dark": "Tối", "ui.default_modelling_orientation": "Hướng mô hình hóa mặc định", "ui.delete": "Xóa", + "ui.delete_select_first": "Hãy chọn trước những gì cần xóa: tính năng, khối, thành phần hoặc hình học phác thảo", + "ui.dependents_select_first": "Hãy chọn trước đối tượng để liệt kê các phần phụ thuộc của nó", "ui.depth": "Độ sâu", "ui.design": "Thiết kế", "ui.design_properties.author": "Tác giả", @@ -4057,6 +4825,40 @@ "ui.design_properties.project": "Dự án", "ui.design_properties.revision": "Lần sửa đổi (Revision)", "ui.design_saved": "Đã lưu vào {path}", + "ui.details_access_caption": "Các bề mặt cho biết dụng cụ có thể tiếp cận chúng từ hướng đã chọn hay không.", + "ui.details_angle": "Góc", + "ui.details_continuity_caption": "Chỉnh sửa đường nối đã chọn. Các đường nối khác giữ nguyên thiết lập riêng.", + "ui.details_continuity_stale": "Hình học trước đó: chạy lại phân tích để chỉnh sửa đường nối này hoặc điều chỉnh khung nhìn vừa với nó.", + "ui.details_copy_list": "Sao chép danh sách", + "ui.details_curvature": "Dung sai độ cong", + "ui.details_curvature_caption": "Các bề mặt được tô màu theo bán kính cong cục bộ.", + "ui.details_direction": "Hướng dụng cụ", + "ui.details_draft_caption": "Các bề mặt được tô màu theo góc so với hướng tháo khuôn.", + "ui.details_edit_seam": "Chỉnh sửa đường nối", + "ui.details_fixture": "Mẫu thành phần giao diện — chỉ dùng dữ liệu minh họa", + "ui.details_fixture_caption": "Mẫu thành phần giao diện với các giá trị minh họa; đây không phải là kết quả của mô hình.", + "ui.details_fixture_problem": "Ví dụ kết quả có vấn đề", + "ui.details_fixture_readout": "Ví dụ giá trị đo", + "ui.details_flip": "Đảo hướng", + "ui.details_gap": "Khe hở", + "ui.details_hatch": "Gạch các mặt cắt", + "ui.details_jump": "Gián đoạn độ cong", + "ui.details_key": "Chú giải", + "ui.details_offset": "Độ lệch", + "ui.details_plane": "Mặt phẳng", + "ui.details_pull": "Hướng tháo khuôn", + "ui.details_radius": "Bán kính", + "ui.details_readout": "Giá trị đo", + "ui.details_samples": "Số mẫu", + "ui.details_seam": "{body} · Cạnh {edge}", + "ui.details_settings": "Thiết lập", + "ui.details_sharp_gap": "Sắc cạnh hoặc có khe hở", + "ui.details_show_all": "Hiển thị tất cả {count}", + "ui.details_smooth": "Trơn mượt", + "ui.details_stripes": "Sọc", + "ui.details_target": "Điều chỉnh khung nhìn vừa với hình học", + "ui.details_worst_seams": "Các đường nối kém nhất", + "ui.details_zebra_caption": "Các sọc phản chiếu cho thấy mức độ trơn mượt khi các bề mặt nối với nhau.", "ui.diameter": "Đường kính", "ui.dimension": "Kích thước", "ui.direct_interaction": "Tương tác trực tiếp", @@ -4101,39 +4903,78 @@ "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", "ui.edit_in_place_wait": "Hãy chờ những gì đang chạy trong thiết kế hoàn tất", "ui.edit_section_analysis": "Chỉnh sửa phân tích mặt cắt", + "ui.edit_sketch_empty": "Không có phác thảo để chỉnh sửa", "ui.ellipse": "Hình elip", "ui.emboss_wrap_note": "Các biên dạng đường trực giao tiếp xúc với một hình trụ được hỗ trợ sẽ tự động quấn. Chọn một thành để chọn mục tiêu.", + "ui.end": "Đầu", "ui.end_radius": "Bán kính kết thúc", "ui.end_scale": "Tỷ lệ đầu cuối", + "ui.ends": "Các đầu", "ui.entities": "Các thực thể", "ui.equal": "Bằng nhau", "ui.equation_end": "Kết thúc", "ui.equation_explicit": "Tường minh", "ui.equation_form": "Dạng", "ui.equation_note": "Biến là một số không có đơn vị: sin(t) hiểu nó theo radian. Kết quả không có đơn vị dùng đơn vị của thiết kế.", + "ui.equation_note_range": "Biến là một độ dài, giống như khoảng của nó: có thể kết hợp với tham số độ dài, và chia cho một độ dài khi dùng sin(). Kết quả không có đơn vị sẽ theo đơn vị của thiết kế.", "ui.equation_parametric": "Tham số", + "ui.equation_variable_unit": "Biến có đơn vị của khoảng", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "Bán kính tương đương", "ui.expand": "Mở rộng", + "ui.explode_needs_two_components": "Chế độ xem phân rã tách các cụm chi tiết ra xa nhau, nên thiết kế cần có từ hai cụm chi tiết trở lên (Tạo mới Cụm chi tiết, Chèn thiết kế vào cụm hoặc Tạo cụm chi tiết từ các thân khối)", "ui.exportDxf": "Xuất tệp DXF…", "ui.export_ellipsis_keymap": "Xuất tệp…", "ui.export_keymap_tip": "Xuất phím tắt, danh sách S box yêu thích và thanh công cụ ra tệp", "ui.extend": "Kéo dài đường", + "ui.extent": "Phạm vi", "ui.extent_type": "Kiểu giới hạn kéo dài", "ui.extract_component": "Trích xuất ra tệp riêng…", "ui.extract_design_changed": "Thiết kế đã thay đổi trong khi đang chọn tệp. Vui lòng thực hiện lại lệnh Trích xuất ra tệp.", "ui.extract_done": "Thành phần này hiện đã là một thiết kế độc lập, được liên kết tại đây.", "ui.extrude": "Đùn khối", "ui.extrude_auto_to_object": "Đùn khối đến đối tượng được chọn", - "ui.extrude_auto_to_object_tip": "Trong lệnh Đùn, khi đã chọn biên dạng, nhấp chọn một mặt, đỉnh hoặc mặt phẳng song song ngoài mặt phẳng của nó sẽ tự động chuyển phạm vi đùn thành 'Đến đối tượng' (To Object)", + "ui.extrude_auto_to_object_tip": "Một mặt, đỉnh hoặc mặt phẳng song song chuyển phạm vi sang Đến đối tượng.", "ui.factor": "Hệ số", + "ui.fade": "Thoát ren", + "ui.fade_length": "Chiều dài thoát ren", "ui.feature_history": "Lịch sử tính năng", "ui.feature_options": "Tùy chọn tính năng", "ui.features": "Các tính năng", "ui.file": "Tệp", "ui.fillet": "Bo tròn mép", + "ui.fillet_corner_ball": "Bi lăn", + "ui.fillet_corner_ball_tip": "Một phần mặt cầu của bi lăn, tiếp tuyến (G1) với từng đường bo.", + "ui.fillet_corner_curvature_tip": "Độ cong (G2): một mảng trơn. Góc được lùi dọc theo mỗi cạnh một khoảng Lùi ({factor} × bán kính nếu bạn không nhập) rồi được lấp bằng một mảng, nên phản chiếu đi qua mà không bị gãy.", + "ui.fillet_corner_needs_constant": "Góc mảng trơn (G2) cần Bán kính không đổi và Khớp chính xác.", + "ui.fillet_corner_patch": "Mảng trơn", + "ui.fillet_corner_patch_tip": "Liên tục độ cong (G2): góc được lùi dọc theo mỗi cạnh và được lấp bằng một mảng, nên phản chiếu đi qua mà không bị gãy.", + "ui.fillet_corner_tangent_tip": "Tiếp tuyến (G1): góc bi lăn, một phần mặt cầu của bi lăn tiếp tuyến với từng đường bo.", + "ui.fillet_error_corner": "Không thể tạo góc trơn tại đây. Hãy thử khoảng Lùi khác hoặc góc Tiếp tuyến.", + "ui.fillet_error_failed": "Không thể tạo đường bo này trên các cạnh này. Hãy thử bán kính khác hoặc bo ít cạnh hơn một lần.", + "ui.fillet_error_setback_short": "Khoảng lùi quá ngắn cho mảng ở góc này: góc dựng được từ {least} trở lên. Hãy thử một khoảng Lùi dài hơn.", + "ui.fillet_error_too_large": "Bán kính quá lớn so với các mặt bên cạnh những cạnh này. Hãy thử bán kính nhỏ hơn hoặc đặt Giới hạn mặt thành Bán kính lớn nhất.", + "ui.fillet_fit": "Giới hạn mặt", + "ui.fillet_fit_exact": "Bán kính chính xác", + "ui.fillet_fit_needs_constant": "Khớp bán kính cần Bán kính không đổi.", + "ui.fillet_fit_reduce": "Bán kính lớn nhất", + "ui.fillet_fit_taper": "Bán kính thu hẹp", + "ui.fillet_fit_tip": "Khi bán kính lớn hơn mức các mặt bên cạnh một cạnh cho phép.\nBán kính chính xác: đúng bán kính đã nhập, hoặc không bo gì và có thông báo lý do.\nBán kính lớn nhất: mọi cạnh được bo với bán kính lớn nhất vừa khớp.\nBán kính thu hẹp: giữ bán kính, đường bo chỉ thu hẹp ở nơi các mặt hết chỗ.", + "ui.fillet_options_tip": "Chuỗi tiếp tuyến: bo cả các cạnh nối tiếp trơn từ những cạnh đã chọn.\nXem trước: hiển thị kết quả trong khung nhìn khi bạn chỉnh sửa.", + "ui.fillet_setback": "Lùi", + "ui.fillet_setback_hint": "{factor} × bán kính", + "ui.fillet_setback_least": "Lớn hơn {least}", + "ui.fillet_setback_tip": "Nơi mảng góc trơn bắt đầu: khoảng cách dọc theo mỗi cạnh tính từ góc. Mặc định là {factor} × bán kính. Giá trị phải lớn hơn khoảng lùi nhỏ nhất, tại đó các đường bo gặp nhau mà không cần lùi: bằng bán kính khi các mặt vuông góc với nhau.", + "ui.fillet_smooth_radius": "Thay đổi bán kính trơn", + "ui.fillet_turn": "Chỗ rẽ", + "ui.fillet_turn_mitre": "Vát góc", + "ui.fillet_turn_swept": "Quét vòng", + "ui.fillet_turn_tip": "Nơi hai góc lượn rẽ quanh một cạnh góc sắc nằm giữa chúng, ví dụ các góc lượn ở chân một khối lồi tại các cạnh đứng của nó.\nVát góc: các góc lượn kéo dài cho đến khi gặp nhau theo đường vát.\nQuét vòng: các góc lượn dừng ở cạnh góc và quay quanh nó, góc là một mặt xuyến tiếp xúc với cả hai. Chỉ cho các góc lượn cùng bán kính quanh một cạnh góc thẳng và lồi.", + "ui.fillet_type_choices_tip": "Bán kính không đổi: một bán kính dọc suốt cạnh.\nĐộ dài dây cung: độ rộng ngang đường bo giữ nguyên, bất kể góc gặp nhau của các mặt.\nBán kính thay đổi: một bán kính ở mỗi đầu, và thêm dọc cạnh nếu bạn thêm vào.\nLiên tục độ cong: mặt cắt không làm gãy phản chiếu tại nơi gặp các mặt phẳng (G2).\nSpline: bán kính dọc cạnh theo các bán kính điều khiển bạn đặt.", + "ui.fillet_type_curvature": "Liên tục độ cong", + "ui.fillet_type_tip": "Mặt cắt ngang qua cạnh. Liên tục độ cong: mặt cắt liên tục độ cong (G2) giữa các mặt phẳng, nên phản chiếu đi từ các mặt vào đường bo mà không bị gãy.", "ui.filter_commands_or_keys": "Lọc lệnh hoặc phím tắt", "ui.findInTimeline": "Tìm trong lịch sử thiết kế", "ui.findInWindow": "Tìm trong cửa sổ", @@ -4242,13 +5083,15 @@ "ui.hideOrigin": "Ẩn Gốc tọa độ", "ui.hidePlanes": "Ẩn các mặt phẳng", "ui.hideProfile": "Ẩn biên dạng", - "ui.hide_origin_by_default": "Mặc định ẩn gốc tọa độ", + "ui.hide_component_history": "Ẩn lịch sử của nó", + "ui.hide_origin_by_default": "Ẩn thư mục Gốc tọa độ trong thiết kế mới", "ui.hide_origin_note": "Bản vẽ mới bắt đầu với thư mục Gốc tọa độ được ẩn. Thiết kế sẽ giữ lại cài đặt Gốc tọa độ riêng sau khi bạn ẩn hoặc hiện nó.", "ui.history_back": "Lùi một bước", "ui.history_below_browser": "Bên dưới trình duyệt", "ui.history_edge_hint": "nhấp đúp vào cạnh", "ui.history_first": "Về đầu", "ui.history_forward": "Tiến một bước", + "ui.history_hide_hidden": "Ẩn các thành phần bị ẩn", "ui.history_hide_names": "Ẩn tên", "ui.history_last": "Đến cuối", "ui.history_marker_tip": "Điểm đánh dấu lịch sử: kéo để lùi mô hình về bước trước; các tính năng mới sẽ được thêm vào đây", @@ -4258,10 +5101,12 @@ "ui.history_play_button_show": "Hiện nút Phát", "ui.history_play_finish_action": "Hoàn tất thao tác hiện tại trước khi phát lịch sử", "ui.history_play_roll_back": "Đưa điểm đánh dấu lịch sử lùi lại trước khi phát", + "ui.history_show_hidden": "Hiện các thành phần bị ẩn", "ui.history_show_names": "Hiện tên", "ui.history_sketch_listed_under": "Được liệt kê dưới {feature}", "ui.history_title": "Lịch sử", "ui.history_toggle_names": "Hiện hoặc ẩn tên tính năng", + "ui.history_waits_for_editor": "Hoàn tác, Làm lại và Lịch sử sẽ chờ cho đến khi trình chỉnh sửa tính năng mở xong", "ui.hole": "Tạo lỗ", "ui.hole_tap_type": "Kiểu ta-rô ren lỗ", "ui.hole_type": "Loại lỗ", @@ -4277,7 +5122,9 @@ "ui.insert_design.saved_file": "{name} có thay đổi chưa lưu, nên tệp đã lưu của nó đã được chèn. Hãy lưu nó, rồi dùng Cập nhật liên kết để đưa các thay đổi vào.", "ui.insert_design.unsaved": "Thay đổi chưa lưu", "ui.inspect": "Kiểm tra", + "ui.instances": "Số bản", "ui.intersect": "Giao nhau", + "ui.iso_4753": "ISO 4753", "ui.isolate": "Cô lập đối tượng", "ui.join": "Nối liền", "ui.joint_play": "▶ Phát", @@ -4285,12 +5132,14 @@ "ui.joints": "Các khớp nối", "ui.keyboard_shortcuts": "Phím tắt bàn phím", "ui.language": "Ngôn ngữ (Language)", + "ui.lasso_select": "Lasso (kéo một vòng tự do: chọn những gì nằm hoàn toàn bên trong)", "ui.layout_compact": "Gọn", "ui.layout_floating": "Nổi", "ui.length": "Chiều dài", "ui.length_decimals": "Số chữ số thập phân cho chiều dài", "ui.light": "Sáng", "ui.line": "Đoạn thẳng", + "ui.line_arc_hint": "Cung tiếp tuyến: nhấp vào điểm cuối của cung. Dừng lại trên điểm cuối cùng để quay lại đường thẳng; nhấp chuột phải hoặc Esc để kết thúc", "ui.link_copies": "Liên kết các bản sao đồng nhất", "ui.link_copies_keep": "Giữ nguyên", "ui.link_copies_link": "Tạo liên kết", @@ -4378,7 +5227,9 @@ "ui.part_size_needs_a_part": "Hãy chọn một chi tiết tiêu chuẩn đã chèn (vít, đai ốc, vòng đệm hoặc chốt) để đổi kích thước. Để phóng to hoặc thu nhỏ một thân khối, hãy dùng Thay đổi tỷ lệ.", "ui.part_size_shared": "Dựng lại chi tiết, thay thế mọi tính năng đã thêm. Tất cả các lần xuất hiện của chi tiết này đều được cập nhật.", "ui.paste": "Dán", + "ui.patch_continuity_corner_tip": "Mảng gặp các mặt xung quanh với độ liên tục đã chọn dọc theo mỗi cạnh. Tại góc nơi các mặt đó gặp nhau với độ cong khác nhau, mảng giữ tiếp tuyến (G1) ở đó.", "ui.path": "Đường dẫn", + "ui.pattern_object_type_tip": "Thân khối: các hình đặc, chọn trong khung nhìn hoặc Trình duyệt; mỗi thân được sao chép nguyên vẹn.\nTính năng: các bước trong Lịch sử, như một lần đùn khối hay một lỗ, chọn trong Lịch sử hoặc trên một mặt do chúng tạo ra; bước đó được lặp lại.\nBản phác thảo không phải là cả hai: lặp lại các đường cong của nó bằng Mảng hoặc Lấy đối xứng trong chính bản phác thảo, hoặc đùn khối nó trước.", "ui.pattern_on_path": "Mảng dọc theo đường dẫn", "ui.perforate_margin_default": "theo đường kính", "ui.perforate_pitch": "Bước lỗ", @@ -4393,7 +5244,7 @@ "ui.pitch": "Bước xoắn", "ui.placement": "Vị trí đặt", "ui.placement_handles": "Tay nắm định vị", - "ui.placement_handles_tip": "Tay nắm trên hình xem trước của Gờ đỡ, Vấu lồi hoặc Khớp cài: kéo điểm đánh dấu để di chuyển trên mô hình, xoay bằng vòng xoay", + "ui.placement_handles_tip": "Dấu để kéo đặc trưng trên mô hình và vòng để xoay.", "ui.plane": "Mặt phẳng", "ui.plane_at_angle": "Mặt phẳng theo góc", "ui.plugins": "Plugin", @@ -4405,12 +5256,17 @@ "ui.plugins_skipped": "Không thể đọc {count} thư mục.", "ui.plugins_version": "{version}", "ui.point": "Điểm", + "ui.point_cloud_add_filter": "Thêm bộ lọc…", "ui.point_cloud_auto_range": "Phạm vi tự động", "ui.point_cloud_color_by": "Tô màu theo", "ui.point_cloud_file_colors": "Màu trong tệp", + "ui.point_cloud_filter_by": "Lọc theo", "ui.point_cloud_height_high": "Cao nhất", "ui.point_cloud_height_low": "Thấp nhất", + "ui.point_cloud_legend_filter": "Hiện và ẩn trong chú giải ở trên", "ui.point_cloud_no_file_colors": "Tệp không có màu", + "ui.point_cloud_pause": "Tạm dừng", + "ui.point_cloud_play": "Phát", "ui.point_cloud_single_color": "Một màu", "ui.point_cloud_size": "Kích thước điểm", "ui.point_cloud_units": "Đơn vị của tệp", @@ -4419,6 +5275,11 @@ "ui.polygon": "Đa giác", "ui.preferences": "Tùy chọn cài đặt", "ui.press_a_key": "nhấn một phím…", + "ui.print_face_body_not_sent": "Thân của mặt này không được gửi: hãy thêm nó vào Thân khối trước", + "ui.print_face_cleared": "{body}: đã xóa mặt in", + "ui.print_face_input": "Mặt in", + "ui.print_face_pick": "Chọn một mặt phẳng của thân đặc để đặt làm mặt in", + "ui.print_face_set": "{body}: đã đặt mặt in; Gửi đến Slicer sẽ đặt thân lên mặt này", "ui.profile": "Biên dạng", "ui.profile_plane": "Mặt phẳng biên dạng", "ui.profiles": "Các biên dạng", @@ -4434,6 +5295,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "Đang đo…", + "ui.properties.measuring_bodies": "Đang đo… {done} trên {total} thân khối", "ui.properties.measuring_failed": "Phép đo đã dừng trước khi hoàn tất.", "ui.properties.principal_axis": "Trục chính {number}", "ui.properties.principal_moments": "Mômen quán tính chính", @@ -4501,6 +5363,7 @@ "ui.selectOther": "Chọn đối tượng khác…", "ui.selectTangentChain": "Chọn chuỗi tiếp tuyến", "ui.select_all": "Chọn tất cả", + "ui.select_components_by_face": "Chọn thành phần (chọn một mặt sẽ chọn thành phần chứa mặt đó)", "ui.selection": "Vùng chọn", "ui.selection_modifiers": "Phím bổ trợ chọn", "ui.selection_shift_add_only": "Shift+nhấp chỉ thêm, không bỏ chọn", @@ -4526,6 +5389,7 @@ "ui.showDimension": "Hiển thị Kích thước", "ui.showOrigin": "Hiển thị Gốc tọa độ", "ui.showPlanes": "Hiển thị các mặt phẳng", + "ui.show_component_history": "Hiện lịch sử của nó", "ui.show_constraints": "Các ràng buộc", "ui.show_construction_geometries": "Đối tượng dựng hình (nét đứt)", "ui.show_dimensions": "Các kích thước", @@ -4540,8 +5404,15 @@ "ui.sketch_intersect_geometry": "Hình học", "ui.sketch_intersect_projection_link": "Liên kết chiếu", "ui.sketch_intersect_selection_filter": "Bộ lọc lựa chọn", + "ui.sketch_keys_only": "Không dùng phím mô hình trong bản phác thảo", + "ui.sketch_keys_only_tip": "Khi đang chỉnh sửa bản phác thảo, chỉ các phím phác thảo và các phím dùng được ở mọi nơi mới hoạt động; phím mô hình như E hoặc F không làm gì, nên một phím bấm nhầm không thể đóng một bản phác thảo nặng.", "ui.sketch_modifiers": "Phím bổ trợ phác thảo", "ui.sketch_project_geometry": "Hình học", + "ui.sketch_report.all_constrained": "Mọi thứ đã được ràng buộc hoàn toàn.", + "ui.sketch_report.dof": "Bậc tự do", + "ui.sketch_report.loose": "Chưa ràng buộc hoàn toàn", + "ui.sketch_report.status": "Trạng thái", + "ui.sketch_report.title": "Báo cáo phác thảo", "ui.sketch_scale": "Tỷ lệ phác thảo", "ui.sketches": "Các phác thảo", "ui.slice": "Cắt lát", @@ -4552,7 +5423,7 @@ "ui.slicer_no_response": "{slicer} không phản hồi kịp thời. Tệp đã được lưu tại {path}: hãy gửi lại sau khi phần mềm cắt lớp khởi động xong.", "ui.slicer_resend_hint": "Gửi lại sẽ thay thế tệp đang mở trong phần mềm cắt lớp.", "ui.slicer_single_instance": "Mở tệp trong phần mềm cắt lớp đang chạy sẵn", - "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer và Cura sẽ tải tệp vào cửa sổ đang mở thay vì khởi động cửa sổ mới. Các phần mềm cắt lớp khác được khởi động như bình thường. PrusaSlicer 3.0 luôn hoạt động theo cách này: trình khởi chạy của nó không thể nhận tệp theo cách nào khác.", + "ui.slicer_single_instance_tip": "Dành cho phần mềm cắt lớp tải tệp vào cửa sổ đang chạy.", "ui.slicer_starting": "Đang khởi động {slicer}…", "ui.slicer_still_starting": "Vẫn đang chờ {slicer} khởi động. Chưa có dữ liệu nào khác được gửi.", "ui.slicer_stl_fallback": "Không thể ghi tệp 3MF nên định dạng xuất là STL.", @@ -4571,8 +5442,8 @@ "ui.start": "Bắt đầu", "ui.start_over": "Bắt đầu lại", "ui.start_page": "Trang bắt đầu", - "ui.step_values": "Tăng giảm giá trị bằng phím mũi tên và con lăn chuột", - "ui.step_values_tip": "Trong ô nhập giá trị đang gõ, phím Lên/Xuống và con lăn chuột trên ô sẽ tăng giảm số thuần túy 1 đơn vị (Shift: 10, Alt: 0.1). Biểu thức toán học được giữ nguyên như đã nhập.", + "ui.step_values": "Thay đổi giá trị bằng mũi tên và con lăn", + "ui.step_values_tip": "Phím lên/xuống và con lăn trên trường giá trị sẽ thay đổi số trong đó.", "ui.stitch_tolerance_hint": "chặt", "ui.stretch": "Kéo giãn", "ui.supersampling": "Khử răng cưa SSAA", @@ -4637,19 +5508,31 @@ "ui.view_angles": "Góc hướng nhìn", "ui.view_angles_convention": "Độ quanh trục hướng lên. Lệch 0° là góc nhìn phía trước, 90° bên trái, −90° bên phải, 180° phía sau; chúc 90° là góc nhìn từ trên; nghiêng dương xoay mô hình trên màn hình theo chiều kim đồng hồ.", "ui.view_angles_help": "Hiển thị góc chúc, góc lệch và góc nghiêng của góc nhìn theo độ cùng kiểu chiếu, bên dưới gizmo định hướng. Bấm vào phần hiển thị để nhập góc chính xác.", + "ui.view_angles_lock": "Khóa {axis}", "ui.view_angles_ortho": "Trực giao", "ui.view_angles_persp": "Phối cảnh", "ui.view_angles_pitch": "Chúc", "ui.view_angles_readout": "Chúc {pitch} · Lệch {yaw} · Nghiêng {roll}", "ui.view_angles_roll": "Nghiêng", + "ui.view_angles_unlock": "Mở khóa {axis}", "ui.view_angles_yaw": "Lệch", + "ui.view_angles_zero": "Đặt {axis} về 0°", "ui.view_centre": "Tâm góc nhìn", "ui.viewport_status_clear": "Tắt {name}", "ui.viewport_status_clear_hint": "Tắt {name} · Esc", + "ui.viewport_status_edges": "{count} cạnh", + "ui.viewport_status_from": "từ {direction}", "ui.viewport_status_key": "Hiển thị chú giải cho {name}", "ui.viewport_status_minimum_radius": "Bán kính nhỏ nhất", "ui.viewport_status_pairs": "{count} cặp", + "ui.viewport_status_section_hatch": "{setting} · gạch mặt cắt", + "ui.viewport_status_section_plane": "Mặt phẳng hiện tại", + "ui.viewport_status_section_tilted": "nghiêng · {offset}", "ui.viewport_status_stripes": "{count} sọc", + "ui.viewport_status_summary_clear": "Tắt tất cả", + "ui.viewport_status_summary_heading": "Trong khung nhìn này", + "ui.viewport_status_summary_label": "{name} và {count} mục khác", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "Theo chủ đề giao diện", "ui.visual_shaded_hidden_edges": "Tô bóng kèm nét khuất", "ui.visual_shaded_with_edges": "Tô bóng kèm hiển thị cạnh", @@ -4685,11 +5568,13 @@ "update.available": "Đã có phiên bản SolidCraft {version}", "update.button": "Cập nhật", "update.button_version": "Cập nhật lên {version}", - "update.check_automatically": "Tự động kiểm tra bản cập nhật", + "update.check_automatically": "Kiểm tra khi khởi động và mỗi ngày một lần", + "update.check_for_updates": "Kiểm tra bản cập nhật", "update.check_now": "Kiểm tra ngay", + "update.check_unavailable": "Không thể kiểm tra bản cập nhật cho bản cài đặt này.", "update.checking": "Đang kiểm tra…", "update.copy": "Sao chép", - "update.dmg_opened": "Ảnh đĩa đã mở và được xác thực: kéo SolidCraft vào thư mục Applications để thay thế bản cũ, sau đó khởi động lại SolidCraft.", + "update.dmg_opened": "Ảnh đĩa đã mở và được xác thực: thoát SolidCraft, kéo SolidCraft mới vào thư mục Applications để thay thế bản cũ, sau đó mở lại SolidCraft.", "update.download": "Tải về", "update.download_open": "Tải về và mở", "update.downloading": "Đang tải về và xác thực… {done} trên {total} MB", @@ -4733,6 +5618,7 @@ "web.open_link": "Mở thiết kế liên kết?", "web.open_link_confirm": "Có những thay đổi chưa lưu. Mở thiết kế liên kết trong tab mới?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ chọn · Enter / Tab hoàn tất · Esc bỏ qua", + "↑ ↓ choose · Enter applies this value": "↑ ↓ để chọn · Enter để áp dụng giá trị này", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ để chọn · Enter để áp dụng nội dung đã nhập · Esc để đóng", "⌘Enter continues on GitHub.": "Nhấn ⌘Enter để tiếp tục trên GitHub." } diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index c536529b4..24104b2fe 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "混合曲面", "BOUNDARY SURFACE": "邊界曲面", "BROWSER": "瀏覽器", + "Back to the original order": "還原原始順序", "Ball": "球", "Bar": "扁鋼", "Base Center": "底面中心", @@ -181,6 +182,8 @@ "Designs you open or save appear here.": "您開啟或儲存的設計會顯示在此處。", "Determined by To Object. Choose Angle to edit the angular extent.": "由「到物件」確定。選擇「角度」可編輯角度範圍。", "Diameter": "直徑", + "Did this assembly open the wrong way up?": "此組合件開啟時的朝向是否不對?", + "Did this part open the wrong way up?": "此零件開啟時的朝向是否不對?", "Dimension new shapes": "為新圖形標註尺寸", "Direction": "方向", "Discard": "捨棄", @@ -474,6 +477,7 @@ "Rectangular": "矩形", "Rectangular Tube": "矩形管", "Reference face": "參考面", + "Reference plane": "參考平面", "Relief Depth": "止裂槽深度", "Relief Width": "止裂槽寬度", "Remove Tools": "移除工具", @@ -553,6 +557,7 @@ "Section": "剖面", "Section (optional)": "剖面(可選)", "Section position": "截面位置", + "Sections": "剖面", "Sections (one sketch each)": "剖面(每個一張草圖)", "Select Other": "選取其他", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "「選擇其他」:在模型上按住左鍵(或右鍵點擊 › 選擇其他…)列出游標下的所有物件;在同一位置再次點擊可選擇該處的下一個物件。雙擊中鍵轉到主檢視(偏好設定 › 導覽)。", @@ -593,6 +598,8 @@ "Snap to face and edge centres": "吸附到面和邊的中心", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft 無法直接提交報告。請在 GitHub 上提交;應用程式內不需要權杖。", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft 在這些設計儲存前已關閉。可以開啟它們的上次自動儲存。", + "Sort A to Z": "A 到 Z 排序", + "Sort Z to A": "Z 到 A 排序", "Spacing 2 must be a non-zero number": "間距 2 必須是非零數字", "Spacing must be a non-zero number": "間距必須是非零數字", "Specialise": "專用操作", @@ -601,6 +608,7 @@ "Square": "正方形", "Stand it up": "將其立起", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "將其立起:繞 X 軸旋轉四分之一週,作為一個可復原的移動特徵。", + "Stand this assembly up?": "立起此組合件?", "Stand this part up?": "立起此零件?", "Start angle": "起始角度", "Start bulge": "起始鼓度", @@ -772,6 +780,8 @@ "at the face": "在面上", "bom.group_children": "子零件併入所屬零件的列", "browser.body_name": "實體{number}", + "browser.calibrate_click_a": "按一下影像以指定點 A,或輸入其座標。", + "browser.calibrate_click_b": "按一下影像以指定點 B,或輸入其座標。", "browser.calibrate_title": "校準:{name}", "browser.capture_many": "{count} 個元件已移動,但尚未擷取其位置。", "browser.capture_note": "「擷取位置」保留新位置;「還原位置」還原原先的位置。", @@ -785,6 +795,13 @@ "browser.sketch_attachment_lost": "{name} (附著遺失)", "browser.sketch_editing": "{name} (編輯中)", "browser.sketch_name": "草圖{number}", + "browser.sketches_to_parts_already_in_part": "已在所屬零件中", + "browser.sketches_to_parts_design_body": "位於設計本身的實體上", + "browser.sketches_to_parts_moved": "已將 {moved} 個草圖移至其所在的零件", + "browser.sketches_to_parts_no_exact_attachment": "位於沒有精確附著的面上", + "browser.sketches_to_parts_not_on_face": "不在零件的面上", + "browser.sketches_to_parts_part_missing": "所屬零件已不存在", + "browser.sketches_to_parts_result": "已將 {moved} 個草圖移至其所在的零件;{stayed} 個未移動:{why}", "browser.units": "單位: {units}", "cam.flat": "平底", "cam.follower": "從動件", @@ -814,6 +831,8 @@ "cmd.appearance_pick_up": "吸取外觀", "cmd.appearance_replace": "取代外觀", "cmd.assembly_bom": "物料清單", + "cmd.assembly_mass_properties": "質量屬性", + "cmd.body.print_face": "列印底面", "cmd.body_rename": "重新命名實體", "cmd.browser_collapse_all": "全部摺疊", "cmd.browser_expand_all": "全部展開", @@ -842,6 +861,7 @@ "cmd.component_extract": "提取到檔案", "cmd.component_finish_edit": "完成編輯", "cmd.component_from_bodies": "由實體建立元件", + "cmd.component_hide_history": "隱藏元件歷程記錄", "cmd.component_insert_design": "插入設計", "cmd.component_links": "列出連結", "cmd.component_list": "列出元件", @@ -850,6 +870,7 @@ "cmd.component_move_bodies": "將實體移至元件", "cmd.component_move_features": "將特徵移至元件", "cmd.component_move_sketches": "將草圖移至元件", + "cmd.component_move_sketches_to_parts": "將草圖移至所屬零件", "cmd.component_paste_from_design": "從其他設計貼上", "cmd.component_paste_new": "貼上為新物件", "cmd.component_properties": "元件物理屬性", @@ -857,6 +878,7 @@ "cmd.component_rename": "重新命名元件", "cmd.component_replace_with_link": "取代為連結", "cmd.component_revert_position": "還原位置", + "cmd.component_show_history": "顯示元件歷程記錄", "cmd.component_unlock": "解鎖內容", "cmd.component_update_links": "更新連結", "cmd.config_activate": "啟用組態", @@ -867,6 +889,7 @@ "cmd.config_rule": "組態規則", "cmd.config_rules": "組態規則", "cmd.config_table": "顯示組態表", + "cmd.construct.plane.axis_point": "過軸與點的平面", "cmd.construct_axis_edge": "過邊的軸", "cmd.construct_axis_normal_to_face": "垂直於面的軸", "cmd.construct_axis_through_cylinder": "過圓柱/圓錐/圓環的軸", @@ -915,6 +938,11 @@ "cmd.explode_show": "顯示爆炸圖", "cmd.expr_evaluate": "計算運算式", "cmd.face_delete": "刪除面", + "cmd.file.export_3mf": "匯出 3MF", + "cmd.file.export_obj": "匯出 OBJ", + "cmd.file.export_step": "匯出 STEP", + "cmd.file.export_stl": "匯出 STL", + "cmd.file.export_urdf": "匯出 URDF", "cmd.file_export": "匯出", "cmd.file_insert_mesh": "插入網格", "cmd.file_insert_step": "插入 STEP", @@ -932,6 +960,7 @@ "cmd.inspect_colored_components": "啟用元件顏色", "cmd.inspect_colored_components_disable": "停用元件顏色", "cmd.inspect_compare": "比較實體", + "cmd.inspect_compare_picture": "與圖片比較", "cmd.inspect_continuity": "連續性分析", "cmd.inspect_curvature_comb": "曲率梳分析", "cmd.inspect_curvature_map": "曲率圖分析", @@ -1022,6 +1051,9 @@ "cmd.pointcloud_edit": "編輯點雲", "cmd.pointcloud_insert": "插入點雲", "cmd.pointcloud_list": "點雲", + "cmd.render.compare.divider": "移動彩現比較分隔線", + "cmd.render.result.discard": "捨棄彩現結果", + "cmd.render.result.select": "選取彩現結果", "cmd.render_aging_describe": "分層表面老化", "cmd.render_backends": "彩現後端", "cmd.render_batch": "彩現所有鏡頭", @@ -1185,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "控制點雲形線(5 次)", "cmd.sketch_spline_fit_point": "擬合點雲形線", "cmd.sketch_spline_insert_point": "新增雲形線點", + "cmd.sketch_spline_remove_point": "刪除雲形線點", "cmd.sketch_spline_reverse": "反向雲形線方向", "cmd.sketch_spun_profile": "旋轉輪廓", "cmd.sketch_toggle_diameter": "切換半徑 / 直徑", @@ -1235,9 +1268,11 @@ "cmd.timeline_rollback": "移動時間軸標記", "cmd.timeline_stop": "停止播放歷程記錄", "cmd.timeline_suppress": "抑制特徵", + "cmd.ui.assistant": "切換助理", "cmd.view.render_browser": "彩現瀏覽器", "cmd.view.render_dock": "移動彩現停靠面板", "cmd.view.render_focus": "彩現聚焦檢視", + "cmd.view.status_details": "視埠狀態詳細資料", "cmd.view.status_items": "視埠狀態項目", "cmd.view_ambient_occlusion": "環境光遮蔽", "cmd.view_angle_readout": "檢視角度", @@ -1268,17 +1303,28 @@ "cmd.view_tool": "導覽工具", "cmd.view_top": "俯視圖", "cmd.view_visual_style": "視覺樣式", + "color.blue": "藍色", "color.copy": "點擊複製顏色值", "color.edit": "點擊編輯顏色", "color.gamma": "以 0–255 伽馬空間顯示顏色值", + "color.green": "綠色", "color.hex": "十六進位", "color.hex_help": "輸入 #rrggbb 或 #rrggbbaa;六位數會保留不透明度", "color.hex_hint": "#rrggbb", "color.hue": "色相", "color.linear": "以 0–1 線性空間顯示顏色值", + "color.recent": "最近使用的顏色", + "color.recent_help": "您在任何顏色欄位中選擇的顏色會顯示於此", + "color.red": "紅色", + "color.saturation": "飽和度(百分比)", "color.saturation_value": "飽和度和明度", "color.selected": "所選顏色", + "color.step_down": "減少", + "color.step_up": "增加", + "color.value": "明度,即亮度(百分比)", "config.column_filter_empty": "沒有符合的欄", + "config.rule_parameter_columns": "只會列出表格中有對應欄的參數。以「新增欄」(+) 加入一欄,即可在此使用。", + "config.rule_suppression_columns": "只會列出表格中有「抑制」欄的特徵。以「新增欄」(+) 加入一欄,即可在此控制。", "contact.components_count": "{count} 個元件", "contact.enabled_label": "已啟用", "coupling.gear_1": "齒輪 1", @@ -1323,9 +1369,15 @@ "dialog.dimension_insert_hint": "點擊其他驅動尺寸以插入其名稱", "dialog.dimension_name": "尺寸:{name}", "dialog.edit_title": "編輯 {title}", + "dialog.no_shown_body": "沒有可變更的已顯示實體:請顯示一個,或選擇「新建實體」", + "dialog.pattern_sketch_not_object": "請選取實體或特徵:草圖兩者皆非。請用草圖自己的「陣列」或「鏡射」重複其曲線,或先將它擠出。", "dialog.select": "↖ 選擇", "dialog.selected_count": "↖ 已選擇 {count} 個", + "dialog.selection_constraint": "拘束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲線 {id}", "dialog.selection_guidance": "選擇輸入項進行修改。點擊已選物件可取消選擇;按住 Ctrl/Cmd 點擊也可切換選擇。檢查預覽後,再按「確定」。", + "dialog.selection_midpoint": "中點 · {id}", + "dialog.selection_profile": "{sketch} · 輪廓 {number}", "dialog.selection_step": "第 {step} 步,共 {total} 步:選擇{input}", "dialog.step": "步驟", "document.changed_on_disk": "{name} 已在磁碟上變更", @@ -1380,26 +1432,244 @@ "from the rule": "來自規則", "help.apache": "Apache 授權 2.0", "help.appearance.assign": "為所選的實體、面或元件設定顏色或材質外觀,不改變其重量。用於區分零件或預覽表面處理效果。", + "help.assembly.bom": "依零件編號列出設計或元件的零件及其數量,也可將清單儲存為 CSV 或 JSON。用作訂購與組裝的零件清單。", "help.attributions": "署名資訊 (ATTRIBUTION.md)", "help.build": "版本 {version} · 提交 {commit} · 建置日期 {date}", + "help.canvas.decal": "將圖片像貼紙一樣貼在模型的平坦面上。用於在零件上顯示標籤、標誌或印刷圖案。", + "help.canvas.edit": "變更畫布的位置、大小、角度、不透明度、鏡射、可見性或名稱。用於讓參考圖片對齊要描摹的草圖。", + "help.canvas.insert": "將 PNG 或 JPEG 圖片作為半透明參考放置在平面或面上。用於在草圖中描摹照片或圖紙,圖片可縮放至已知尺寸。", + "help.component.break_link": "將已連結的元件從其設計檔案斷開,並保持其實體原樣。用於零件不再需要跟隨原始檔案的變更時。", + "help.component.capture_position": "擷取手動移動後的零件位置,使其成為這些零件的所在位置。用於將零件拖曳到定位,且沒有接頭固定它們之後。", + "help.component.create": "在設計中新增一個空元件,預設位於作用中元件內,也可選擇其他父元件。用於為組合件的新零件提供存放實體與草圖的專屬位置。", "help.component.finish_edit": "儲存就地編輯的零件,返回其組合件,並以該零件更新組合件。連結零件的變更完成後使用。", + "help.component.from_bodies": "將每個所選實體轉成各自獨立的元件,並以該實體命名。用於將以零散實體建成的設計改為可接合、移動零件的組合件。", + "help.component.insert_design": "將另一個已儲存的設計作為連結到其檔案的元件插入,其實體維持原有的位置。用於在組合件中重複使用零件,並透過「更新連結」取得後續變更。", + "help.component.properties": "依元件實體的材質,顯示元件的體積、質量、質心與慣性矩。用於檢查組合件的重量與平衡。", + "help.component.revert_position": "將手動移動的零件放回原位,並捨棄尚未擷取的移動。用於還原組合件中的試移動。", + "help.component.update_links": "重新讀取已連結的設計檔案,並取代已變更的實體。用於編輯過此組合件所用的零件之後。", + "help.config.configure": "將參數、特徵、材質或外觀作為欄新增到組態表。用於建立同一設計的各種變體,例如零件的不同尺寸。", + "help.config.preview": "檢查組態表的某一列是否能重建,不更改設計或其歷程記錄。用於切換到沒有把握的變體之前。", + "help.config.rules": "顯示組態表的規則、各列,以及哪一列為作用中。用於了解設計的變體如何設定。", + "help.config.table": "顯示組態表:每個變體一列,每個參數或特徵一欄,並顯示設計是否仍與作用中的列相符。用於檢視設計的各個變體。", "help.connect_note": "請重新啟動各個助理以載入 SolidCraft 伺服器。每個檔案在變更前都已備份為 .bak。", "help.connect_title": "連接 AI 助理", + "help.construct.axis.edge": "沿直邊或草圖直線建立建構軸。用作旋轉、環形陣列或接頭的軸。", + "help.construct.axis.normal_to_face": "通過一點、垂直於面建立建構軸。用作從表面垂直伸出的軸。", + "help.construct.axis.through_cylinder": "通過圓柱面、圓錐面或圓環面的中心,或圓形邊,建立建構軸。用於讓特徵繞圓形零件旋轉或陣列。", + "help.construct.axis.two_planes": "在兩個平面或平坦的面相交處建立建構軸。用於所需的軸正是兩個面之間的交線時。", + "help.construct.axis.two_points": "通過兩點、頂點或草圖點建立建構軸。用於穿過兩個已知位置的軸。", + "help.construct.plane.along_path": "在邊或曲線上沿其某個位置,建立垂直於它的建構平面。用於為掃掠繪製輪廓草圖,或繪製路徑的剖面。", + "help.construct.plane.at_angle": "以某個軸或邊為基準,將平面或面旋轉一個角度,建立建構平面。用於傾斜的草圖,例如斜角支架。", + "help.construct.plane.axis_point": "建立包含一條軸與軸外一點的建構平面。依序選取原點或建構軸、直邊或草圖直線,再選取頂點、草圖點或建構點。軸上的點無法決定唯一的平面。", + "help.construct.plane.midplane": "在兩個平面或平坦的面正中間建立建構平面;若兩者以一個角度相交,則平分該夾角。用作鏡射的對稱平面。", + "help.construct.plane.offset": "建立與平面或平坦的面平行的建構平面,可指定距離或通過一點。用於在面上方的指定高度繪製草圖。", + "help.construct.plane.perpendicular": "建立包含一條直線或邊、並垂直於某平面或面的建構平面。用於沿邊在模型上繪製直立的草圖。", + "help.construct.plane.tangent": "建立在某一點與圓柱、圓錐、球或圓環相切的建構平面。用於在圓形零件的側面繪製草圖。", + "help.construct.plane.three_points": "通過三點建立建構平面。用於由模型上的位置決定的平面,例如三個角。", + "help.construct.plane.two_edges": "通過位於同一平面內的兩條直邊或直線建立建構平面。用於橫跨零件的平面,例如通過兩條對邊。", + "help.construct.point.along_path": "在邊或曲線上沿其某個位置建立建構點。用作路徑中途的參考。", + "help.construct.point.center": "在圓形邊、草圖圓或圓弧、球或圓環的中心建立建構點。用作孔、軸和接頭的參考。", + "help.construct.point.edge_plane": "在邊或直線穿過平面或平坦的面之處建立建構點。用於標出路徑與平面相交的位置。", + "help.construct.point.three_planes": "在三個平面或平坦的面相交處建立建構點。用作角的參考,即使模型在該處沒有頂點。", + "help.construct.point.two_edges": "在兩條邊或直線相交或最接近之處建立建構點。用作虛擬角的參考。", + "help.construct.point.vertex": "在頂點或草圖點上建立建構點。用作參考,即使周圍的草圖或實體被隱藏,它也會保留。", + "help.contact.check": "列出接觸集中,在目前位置互相穿過的零件對。用於在驅動接頭或執行運動研究之前找出碰撞。", + "help.contact.create": "將兩個或多個零件組成一個接觸集,接頭移動時,其實體不會互相穿過。用於碰到就該停住的零件,例如槓桿與其擋塊。", + "help.contact.disable_all": "關閉接觸,使受驅動的接頭和運動研究不再於零件接觸處停止。用於讓零件重新自由移動,或讓大型組合件保持流暢。", + "help.contact.edit": "變更接觸集:其包含的零件、名稱,或是否抑制;也可以刪除該接觸集。用於調整哪些零件不可互相穿過。", + "help.contact.enable_all": "將組合件的所有零件放入同一個接觸集,使接頭移動時任何兩個零件都不會互相穿過。用於快速檢查整個機構。", + "help.contact.enable_sets": "為您定義的接觸集開啟接觸,使受驅動的接頭和運動研究在其零件即將互相穿過之處停止。用於關閉接觸後恢復您的接觸集。", + "help.contact.list": "列出設計的接觸集、各接觸集中的零件,以及接觸是否開啟。用於在驅動組合件之前確認接觸的設定。", + "help.document.inspect": "顯示設計的概覽:其元件、實體、草圖、特徵與參數。用於熟悉不是自己建立的設計。", + "help.document.units": "變更設計顯示長度所用的單位,例如 mm 或英吋。幾何尺寸不變,只有顯示的數值和未標單位的數字會跟著變。", + "help.edit.checkpoint": "記住設計、作用中的草圖與復原歷程目前的狀態。用於嘗試有風險、之後可能想退回的操作之前。", + "help.edit.restore_checkpoint": "回到某個檢查點,包括復原歷程。用於一步捨棄檢查點之後所做的一切。", + "help.explode.create": "建立爆炸圖,將零件從組合件中心向外推開,或依您設定的移動量推開。用於展示組合件如何組裝,供說明書或簡報使用。", "help.face.delete": "刪除所選的面,並由相鄰的面封閉留下的缺口,也可以讓缺口保持開放、成為曲面。用於移除礙事的圓角、孔或凸座。", + "help.file.insert_mesh": "將 3MF、STL、OBJ、PLY 或 glTF 檔案作為網格實體加入設計的新元件中。用於把下載或掃描的模型放在設計旁作為參考。", + "help.file.insert_step": "將 STEP、IGES、FreeCAD 或 Rhino 檔案作為實體加入設計的新元件中;組合件的零件會成為巢狀元件。用於匯入供應商或其他 CAD 程式的模型。", + "help.file.save_mesh": "將實體儲存為 STL、3MF 或 OBJ 網格,弧形面的平滑度可自行選擇。用於準備 3D 列印的零件,或供讀取網格的程式使用。", + "help.file.send_to_slicer": "將所選實體儲存為 3MF 檔案,並在您選擇的切片軟體中開啟。用於一步從模型進入列印。", "help.font_details": "介面使用 egui 的內建字型(Ubuntu Light 和 Hack,採用 Ubuntu Font Licence 和 MIT/Bitstream Vera 授權;Noto Emoji 和表情圖示字型,採用 OFL 和 MIT 授權)。草圖文字使用 Liberation Sans(SIL OFL 1.1)。The Crafting Apps 的可選字型包 craft-fonts(BIZ UDPGothic、Shippori Mincho、BIZ UDMincho、Noto Sans CJK SC、Noto Sans Arabic;SIL OFL 1.1)未隨 SolidCraft 建置版本隨附提供。", "help.fonts": "字型", + "help.frame.member": "沿框架草圖的直線放置輪廓(例如管材或鋁擠型材),每條直線一個構件。用於建立框架、機架和焊接結構。", + "help.inspect.accessibility": "為刀具能從某一方向到達的面和無法到達的面上色。用於檢查零件能否從該側進行加工或成型。", + "help.inspect.center_of_mass": "在均勻密度下,顯示各實體各自及全部合計的質心。用於檢查平衡以及零件會在哪裡傾倒。", + "help.inspect.colored_components": "為每個元件指定各自的暫時顏色,不改變外觀。用於一眼分辨組合件的各個零件。", + "help.inspect.compare": "比較兩個實體,並顯示其中一個有而另一個沒有材料之處,附帶體積與偏差。用於對照已變更或匯入的零件與原件。", + "help.inspect.continuity": "檢查面沿其邊相接的平滑程度:間隙、折角或曲率跳變,並為接縫著色。用於找出曲面接合不順之處。", + "help.inspect.curvature_comb": "沿曲線、邊或面繪製曲率梳,其梳齒顯示彎曲的程度。用於發現平坦處、折角和曲率不均。", + "help.inspect.curvature_map": "依彎曲程度為面上色,半徑小處為紅色。用於找出緊縮處並評估曲面的平滑度。", + "help.inspect.draft": "依面與拔模方向的拔模角為面上色,並標出角度不足者。用於成型或鑄造之前檢查零件。", + "help.inspect.environment_map": "以反光、鏡面般的表面顯示模型。用於從反射掠過的方式判斷曲面的走勢。", + "help.inspect.interference": "找出重疊的實體,並顯示每處重疊及其體積。用於檢查組合件中是否有零件互相碰撞。", + "help.inspect.isocurve": "繪製面的等參線,即曲面所依據的網格。用於觀察曲面如何走向,以及哪裡變得密集。", + "help.inspect.measure": "測量所選項目之間的長度、距離、角度、面積和半徑,或實體的體積和質量。用於檢查尺寸和間隙。", + "help.inspect.minimum_radius": "找出曲線、邊或面的最小曲率半徑及其位置。用於檢查刀具或噴嘴是否能跟隨該形狀。", + "help.inspect.section": "沿平面將檢視剖開並為切面畫上剖面線,不更改模型。用於查看零件和組合件的內部。", + "help.inspect.zebra": "在模型的面上顯示反射的黑白條紋。用於判斷平滑度:條紋在邊處斷開或折彎,表示過渡不佳。", + "help.joint.as_built": "在兩個零件現有的位置接合它們,不移動其中任何一個,並設定它們仍可如何移動。用於已放置在最終位置的零件。", + "help.joint.cam": "將旋轉的凸輪與從動件連結,使從動件隨凸輪輪廓經過其下方而滑動或擺動。用於凸輪、偏心輪和氣門驅動。", + "help.joint.create": "在您選取的接頭原點接合兩個零件,並將第二個零件移到定位;接頭類型決定它們仍可如何移動。用於建立零件像真實機構一樣運動的組合件。", + "help.joint.drive": "設定接頭的角度或距離,並在其限制內帶動零件移動;連動的接頭和封閉迴路會跟著動。用於檢查機構是否如預期運動。", + "help.joint.gear": "以齒輪比連結兩個旋轉接頭,驅動其中一個會帶動另一個。用於正齒輪和內齒輪,齒輪比取自節圓半徑或齒數。", + "help.joint.limits": "以最小值和最大值設定接頭可旋轉或滑動的範圍,或清除這些限制。用於讓鉸鏈、滑塊或槓桿保持在實際的行程範圍內。", + "help.joint.motion_link": "以比率和偏移量耦合兩個接頭,使驅動其一時另一個也隨之移動。用於「齒輪」、「齒輪齒條」或「螺旋」未涵蓋的接頭間固定關係。", + "help.joint.origin": "在零件上放置具名的接頭原點:位於面或圓端的中心、邊的中點、角或某一點。用於預先決定接頭的附著位置;在面上選取的原點會在零件改變大小時跟隨該面。", + "help.joint.rack_pinion": "將旋轉的小齒輪與滑動的齒條連結,使齒條移動的長度等於小齒輪滾過的節圓長度。用於齒條傳動、轉向機構和線性平台。", + "help.joint.reach": "透過在限制範圍內改變其鏈上的接頭,將零件上的一點移向目標。用於依末端應到達的位置擺放機構,例如機械手臂的尖端。", + "help.joint.rigid_group": "將所選零件按現狀鎖在一起,使它們一起移動。用於屬於同一組、彼此之間沒有運動的零件。", + "help.joint.screw": "以螺距連結旋轉與滑動,每轉一圈前進該距離。用於導螺桿、螺栓和螺紋軸。", + "help.library.apply": "將本機零件庫檔案中的材質或外觀套用到實體、面或元件。用於重複使用在其他設計中儲存的材質。", + "help.library.export": "將設計的材質和外觀儲存到零件庫檔案。用於分享,或在其他設計中重複使用。", + "help.library.inspect": "檢查零件庫檔案並列出其中的材質和外觀,不更改設計。用於套用之前查看零件庫包含什麼。", "help.licences": "授權", "help.material.assign": "設定所選實體的材質,例如鋼、鋁或 ABS。用於讓質量和重量與實際零件一致。", + "help.material.properties.validate": "檢查材質資料卡的數值是否一致、有無缺漏。用於在依賴這些資料計算質量或剛度之前。", + "help.mesh.convert": "將 STL 等網格實體重建為具有平面和圓柱面的可編輯實體。用於像修改建模的實體一樣修改匯入的機械零件。", "help.mit": "MIT 授權", + "help.motion.study": "在時間軸的各步驟設定接頭值,並以動畫播放。用於觀看機構依序運動,並沿途檢查間隙。", + "help.motion.trace": "描繪零件上某一點在運動研究播放或接頭被驅動時所走的路徑,確認後保留為 3D 草圖曲線。用於查看機構能到達哪裡,或以其路徑為基礎繼續建模。", "help.notice": "NOTICE", + "help.occurrence.ground": "將零件固定在原位,或再次釋放,讓接頭帶動其周圍的其他零件。用於作為組合件其餘部分基礎的框架或底座。", "help.occurrence.move": "僅沿接頭允許的自由度移動組合件零件。請選取零件的面,然後拖曳可用的箭頭或圓弧。", "help.parameters.change": "開啟用於驅動設計尺寸的具名數值與運算式表。用於在同一處修改尺寸,讓所有使用該尺寸的特徵隨之更新。", + "help.parameters.export": "將設計的參數儲存為 CSV 或 JSON。用於在試算表中編輯,或移到其他設計。", + "help.parameters.graph": "顯示哪些參數和特徵使用了哪些其他項目,以及其中的迴圈或錯誤。用於了解變更某個參數會影響什麼。", + "help.parameters.import": "將 CSV 或 JSON 中的參數讀入設計,全部匯入或全不匯入。用於從試算表或其他設計帶入數值。", + "help.parameters.move": "將使用者參數移到清單中另一個參數之前或之後。用於讓相關參數放在一起。", + "help.parts.fastener": "依您選擇的尺寸新增標準螺絲、螺栓、螺帽、墊圈、銷或軸承。放在孔上時,會以接頭落入孔中,因此無需自行建模扣件。", + "help.parts.insert": "依您選擇的系列、尺寸和長度插入標準零件。放在孔的邊緣或孔壁上時,會以剛性接頭落在孔上。", + "help.parts.library": "開啟標準零件:標準尺寸的螺絲、螺栓、螺帽、墊圈、止付螺絲、圓柱銷和軸承。用於新增標準零件,而無需自行建模。", + "help.parts.resize": "變更已插入標準零件的尺寸或長度並重建;其接頭使它保持就位。用於螺絲太長或孔需要另一種尺寸時。", + "help.plastic.assign_rule": "將塑膠規則指定給實體,使其塑膠特徵以該規則的拔模和間隙為預設值。用於一次為成型件的所有特徵完成設定。", + "help.plastic.boss": "在面上新增螺絲凸座:一根柱,可選孔、拔模、根部圓角和支撐肋。用於射出成型或列印外殼中的螺絲固定點。", + "help.plastic.lip": "沿薄殼實體的邊緣新增唇緣或對應的凹槽。用於讓外殼的兩半互相定位並緊密閉合。", + "help.plastic.manage_rules": "建立和編輯塑膠規則:材質、壁厚、半徑、間隙和拔模。用於讓成型件的各特徵保持一致。", + "help.plastic.rest": "在面上新增墊塊:圓形或矩形的墊,實心或空心,帶拔模。用作成型外殼中的支撐或間隔柱。", + "help.plastic.snap_fit": "在面上新增卡扣鉤,可設定長度、厚度和卡榫。用於不用螺絲就能把零件夾在一起。", "help.pointcloud.insert": "將 PLY、XYZ 或 PTS 掃描資料作為點雲插入模型旁。以實測資料建立模型時,可作為參考。", + "help.sheet.convert": "將厚度均勻的板或薄殼實體轉為鈑金實體,在您選取的邊處加入折彎。用於讓現有零件可以展開。", + "help.sheet.export_bend_table": "將鈑金實體的折彎表儲存為 CSV 或 JSON:展開狀態下的角度、半徑和折彎位置。用於折彎機或工廠。", + "help.sheet.export_dxf": "將展開圖儲存為 DXF,含輪廓、折彎線,以及可選的折彎註記。用於雷射、電漿或水刀切割。", + "help.sheet.flange": "新增凸緣:由草圖建立的底板、沿開放草圖輪廓的壁,或鈑金邊上的折彎壁。用於建立鈑金零件。", + "help.sheet.flat_pattern": "建立鈑金實體的展開圖,含其尺寸、切口和折彎線。用於切割之前檢查下料尺寸。", + "help.sheet.fold": "沿草圖直線以指定角度和半徑折彎鈑金。用於在平板上切出特徵後再將其摺疊。", + "help.sheet.hem": "將鈑金邊緣向內折回自身。用於得到安全、堅挺且沒有尖銳毛邊的邊緣。", + "help.sheet.manage_rules": "建立和編輯鈑金規則:厚度、折彎半徑、K 因子、止裂槽和間隙。用於配合您工廠的材料和工具。", + "help.sheet.path_flange": "沿鈑金邊新增一串凸緣,依循一串開放的草圖直線。用於一步做出 U 形或 Z 形等輪廓。", + "help.sheet.perforate": "在整片展開的鈑金上新增一片孔陣,採交錯或方形排列。用於通風口、格柵和減重面板。", + "help.sheet.refold": "將已展開的鈑金實體重新折起。用於在平板上加入特徵之後。", + "help.sheet.unfold": "展開鈑金實體的所有折彎。用於加入必須穿過折彎的孔或切口,之後再重新折彎。", + "help.sketch.arc.center_point": "繞圓心畫圓弧,從起點到終點。用於已知圓弧圓心時,例如繞孔或樞軸的半徑。", + "help.sketch.arc.tangent": "畫一段從直線或圓弧末端開始、並與其相切延續的圓弧。用於以平滑的彎曲而非轉角延續一串線條。", + "help.sketch.arc.three_point": "畫一段從起點經過第三點到終點的圓弧。用於圓弧必須通過給定的點,而非繞已知圓心時。", + "help.sketch.arc3d": "開啟「3D 草圖」時,通過三點在空間中畫出精確的圓弧。用於路徑和導軌中離開草圖平面的彎曲。", + "help.sketch.auto_constrain": "加入草圖幾乎已具備的拘束,例如水平、平行或重合,然後標註尺寸,直到完全定義。用於一步鎖定粗略畫出的草圖。", + "help.sketch.auto_constrain_from_datum": "與「自動拘束」相同,但從您選取的基準點而非原點量測位置。用於零件以某個參考點佈局時,例如角或孔。", + "help.sketch.blend_curve": "以與兩者相切的平滑雲形線連接兩條曲線的端點,若選擇,也可曲率連續。用於在曲線之間的缺口架橋而不產生折角。", + "help.sketch.break": "在其他曲線穿過處,或在您放置的點處,將曲線分割成多段。用於曲線的一部分需要自己的拘束,或需要單獨刪除時。", + "help.sketch.cancel": "離開草圖,並捨棄自建立或開啟編輯以來的所有變更。「復原」可找回這些變更。", + "help.sketch.centerline": "在一般直線與中心線之間切換,中心線是輪廓會略過的軸。可將中心線用作旋轉、鏡射或對稱拘束的軸。", + "help.sketch.chamfer.distance_angle": "為兩條直線之間的轉角倒斜角,由沿第一條線的距離和一個角度決定。用於圖紙以長度和角度給出倒角時,例如 2 mm × 30°。", + "help.sketch.chamfer.equal_distance": "沿兩條直線往回相同的距離,為兩條線之間的轉角倒斜角。用於輪廓上常見的 45° 倒角。", + "help.sketch.chamfer.two_distance": "為兩條直線之間的轉角倒斜角,沿每條線各有獨立的距離。用於非 45° 的倒角,以兩個長度給出。", + "help.sketch.circle.center": "以圓心和直徑畫圓。用於圓心已知的孔、凸座和其他圓形特徵。", + "help.sketch.circle.three_point": "通過三點畫圓。用於圓必須通過給定的點時,例如現有幾何上的點。", + "help.sketch.circle.three_tangent": "畫一個與三條直線、圓或圓弧相切的圓。用於讓圓落在三條曲線之間的空間內,例如三角形的內切圓。", + "help.sketch.circle.two_point": "以直徑的兩個端點畫圓。用於已知圓的邊緣點而非圓心時。", + "help.sketch.circle.two_tangent": "畫一個指定大小、與兩條直線、圓或圓弧相切的圓。用於兩條曲線之間固定半徑的圓角。", + "help.sketch.conic": "在兩個端點之間畫圓錐曲線,形狀由頂點和 rho 值決定。用於需要調整飽滿程度的平滑過渡,從平緩到近乎尖角。", + "help.sketch.constrainer": "為一條或兩條選取的曲線套用它們幾乎已具備的拘束,例如水平、平行、相切或相等。用於逐一整理手繪草圖的關係。", + "help.sketch.constraint.coincident": "使點落在另一個點、曲線或草圖軸上。用於封閉輪廓中的缺口,或將點放在直線上。", + "help.sketch.constraint.collinear": "使兩條直線位於同一條直線上。用於對齊中斷的邊,例如缺口的兩側。", + "help.sketch.constraint.concentric": "使兩個圓或圓弧具有相同的圓心。用於圓環、沉孔和階梯軸。", + "help.sketch.constraint.curvature": "使在端點相接的兩條曲線以相同的曲率(G2)延續。用於相切接合不夠平滑之處,例如在可見的曲面上。", + "help.sketch.constraint.equal": "使直線長度相同,或使圓與圓弧半徑相同。用於讓一個尺寸驅動多個相同的特徵。", + "help.sketch.constraint.fix": "將點或曲線固定在原位,或再次釋放。用於拖曳或求解草圖時不可移動的幾何。", + "help.sketch.constraint.horizontal_vertical": "使一條直線,或兩點之間的連線,成為水平或垂直,取較接近者。用於讓輪廓與草圖軸對齊。", + "help.sketch.constraint.midpoint": "將點放在直線的中間,或使兩條直線的中點重合。用於讓幾何居中於一條邊。", + "help.sketch.constraint.parallel": "使兩條直線平行。用於其他尺寸改變時必須保持平行的邊。", + "help.sketch.constraint.perpendicular": "使兩條直線以直角相交。用於不在草圖軸上的直線之間的方角。", + "help.sketch.constraint.polygon": "使一串封閉的直線成為正多邊形:各邊等長,每個角都在同一個圓上。用於讓手繪的多邊形變成正多邊形並保持如此。", + "help.sketch.constraint.symmetry": "使兩個點或曲線以一條直線為軸,或繞一點,互為鏡像。用於變更一側時保持輪廓對稱。", + "help.sketch.constraint.tangent": "使兩條曲線相切接觸,例如直線與圓弧。用於沒有折角的平滑接合。", + "help.sketch.construction": "在一般幾何與建構幾何之間切換曲線,輪廓會略過建構幾何。將建構曲線用作佈局、參考和尺寸的輔助。", + "help.sketch.construction_line": "建立通過兩點的無限長建構直線。可用來規劃草圖佈局,而不會分割輪廓。", + "help.sketch.construction_line.angle": "建立與草圖 X 軸夾指定角度的無限長建構直線。請選取點並輸入角度,或選取其方向。", + "help.sketch.construction_line.bisector": "選取兩條相交的草圖直線,再選擇其中一條角平分線。結果會跟隨其來源直線。", + "help.sketch.construction_line.horizontal": "建立通過某一點的水平無限長建構直線。其水平拘束會在後續編輯中持續維持。", + "help.sketch.construction_line.parallel": "選取一條草圖直線,再放置與其平行的無限長建構直線。按右鍵可選擇其他參考。", + "help.sketch.construction_line.perpendicular": "選取一條草圖直線,再放置與其垂直的無限長建構直線。按右鍵可選擇其他參考。", + "help.sketch.construction_line.tangent_at": "在圓或圓弧上的某一點,或在開放雲形線或圓錐曲線的端點建立切線。請先選取曲線,再選取其切點。", + "help.sketch.construction_line.tangent_external": "選取圓或圓弧,再選取外部點與一個切線解。預覽只會顯示位於所繪圓弧上的切點。", + "help.sketch.construction_line.tangent_two": "選取兩個圓或圓弧,再於預覽中選擇一條公切線。切點必須位於所繪曲線上。", + "help.sketch.construction_line.vertical": "建立通過某一點的鉛直無限長建構直線。其鉛直拘束會在後續編輯中持續維持。", + "help.sketch.copy": "複製所選的草圖曲線和點,連同它們之間的拘束與尺寸。可貼上到此草圖或另一個草圖。", + "help.sketch.create": "在平面或模型的平坦面上開始新的 2D 草圖。每個擠出、旋轉和掃掠都從草圖開始。", + "help.sketch.cut": "複製所選的草圖幾何並將其從草圖中刪除,作為一個復原步驟。可貼到此草圖的其他位置或另一個草圖。", + "help.sketch.dimension": "新增驅動尺寸:依所選項目為長度、距離、角度、半徑或直徑。輸入數值或參數名稱,草圖就會跟隨。", + "help.sketch.edit": "開啟現有的草圖進行編輯。完成草圖時,建立在其上的特徵會隨之更新。", + "help.sketch.ellipse": "由圓心、長軸末端和短軸側的一點畫橢圓。用於橢圓形開口、凸輪和其他細長的圓形形狀。", "help.sketch.equation_curve": "依公式繪製曲線:在指定範圍內使用 x(t) 和 y(t),或 y = f(x)。公式可以使用參數,曲線會隨之更新:可用於正弦波、螺旋線或齒輪齒形的漸開線。", + "help.sketch.extend": "將直線或圓弧延長到擋在前方的最近曲線,或讓兩條曲線生長直到相遇。用於修剪或編輯後封閉輪廓中的缺口。", + "help.sketch.fillet": "以指定半徑的圓弧,將兩條直線或圓弧相接的轉角倒圓。同時倒圓的多個轉角共用一個半徑。", + "help.sketch.finish": "離開草圖並回到模型。其封閉輪廓隨即可用於擠出、旋轉和其他特徵。", + "help.sketch.finish_auto_constrain": "對草圖執行「自動拘束」,然後完成草圖。用於一步讓草圖在完全定義的狀態下離開。", + "help.sketch.fit_curves_to_section": "以草圖平面剖切網格或實體,並將直線和圓弧擬合到剖面上。用於把掃描或匯入的零件重建為可編輯的草圖。", + "help.sketch.include_3d": "將模型的邊、頂點和其他草圖的曲線作為連結的參考帶入此草圖,並把不在其平面上的壓平到平面上。用於以不位於草圖平面內的幾何為基礎建構。", + "help.sketch.infinite": "在一般直線與橫貫整個檢視的無限長建構直線之間切換。用作永遠不會過短的佈局參考。", + "help.sketch.insert_dxf": "將 DXF 圖紙的曲線讀入草圖,並依您的設定縮放、旋轉和放置。用於以其他程式的 2D 圖紙為基礎建構,例如雷射切割的輪廓。", + "help.sketch.insert_svg": "將 SVG 圖形的路徑讀入草圖,並依您的設定縮放、旋轉和放置。用於把標誌或向量輪廓轉成可擠出的曲線。", + "help.sketch.inspect": "開啟目前草圖的報告:還剩多少個自由度,以及是否已完全拘束。用於在完成草圖之前找出哪些部分仍會移動。", + "help.sketch.intersect": "加入實體、面、邊或其他草圖與草圖平面相交的曲線或點。它們保持連結,並在模型變更時跟隨。", + "help.sketch.intersection_curve": "在兩個實體或面相接處建立 3D 曲線,並與它們連結。用作跟隨模型的路徑或導軌。", + "help.sketch.isoparametric_curve": "通過您選取的點,沿面的 U 或 V 方向建立 3D 曲線,並與該面連結。用作跟隨曲面的路徑或分割線。", + "help.sketch.line": "逐點畫出相連的直線,可為開放的鏈或封閉的輪廓。這是大多數輪廓的基本工具。", + "help.sketch.line.midpoint": "從中點向一端畫直線,另一端對稱映射。用於以一點為中心的直線,例如對稱的邊。", + "help.sketch.line3d": "開啟「3D 草圖」時,在空間中的點之間畫相連的直線。用於離開草圖平面的路徑和框架。", + "help.sketch.mirror": "以直線或軸為對稱軸鏡射草圖曲線和點,並加入對稱拘束。用於畫出對稱輪廓的一半後將其補全。", + "help.sketch.move": "移動或旋轉草圖曲線和點,或它們的副本。用於重新定位幾何,同時保持其形狀和拘束。", + "help.sketch.offset": "以指定距離建立一串曲線的副本,可在一側或兩側。用於壁、輪廓和間隙;距離保持為可編輯的尺寸。", + "help.sketch.paste": "將複製或剪下的草圖幾何貼到作用中的草圖。可放在某一點,或以偏移量移位。", + "help.sketch.pattern.circular": "繞圓心複製草圖幾何,可為整圈或指定角度。用於螺栓圓、輪輻和齒。", + "help.sketch.pattern.rectangular": "以指定間距按行和列複製草圖幾何。用於孔、槽或通風口的網格。", + "help.sketch.point": "放置草圖點。用作尺寸、拘束、孔中心或後續特徵的參考。", + "help.sketch.point3d": "開啟「3D 草圖」時,在空間中放置點。用作 3D 曲線和路徑的參考。", + "help.sketch.polygon.circumscribed": "在圓外畫正多邊形,大小由中心到邊中點的距離決定。用於已知對邊寬度時,例如六角螺帽。", + "help.sketch.polygon.edge": "由一條邊的兩個端點畫正多邊形。用於已知邊的長度和位置時。", + "help.sketch.polygon.inscribed": "在圓內畫正多邊形,大小由中心到角的距離決定。用於已知對角寬度時。", + "help.sketch.project": "將模型的邊、面、頂點和其他草圖的曲線投影到此草圖的平面上並帶入。它們保持連結,並在模型變更時跟隨。", + "help.sketch.project_to_surface": "沿此草圖的法向將其他草圖的曲線投影到面上,成為連結的 3D 曲線。用於把標誌、分割線或路徑放到曲面上。", + "help.sketch.rectangle.center": "由中心和一個角畫矩形。用於以一點為中心的輪廓,例如原點。", + "help.sketch.rectangle.rounded": "畫四個角都以同一半徑倒圓的矩形。用於帶圓角的板、蓋和開口。", + "help.sketch.rectangle.three_point": "由一條邊和對側的一點畫矩形。用於與草圖軸成一角度的矩形。", + "help.sketch.rectangle.two_point": "由兩個對角畫矩形。用於板、方塊和凹槽的輪廓。", + "help.sketch.scale": "以基點為中心按倍數縮放草圖曲線和點。用於調整草圖一部分的大小,而無需重畫。", + "help.sketch.slot.arc_center": "沿由圓心、起點和終點決定的圓弧,畫指定寬度的弧形槽。用於繞樞軸的調整槽。", + "help.sketch.slot.arc_three_point": "沿通過三點的圓弧畫指定寬度的弧形槽。用於槽的路徑必須通過給定的點時。", + "help.sketch.slot.center_point": "從中心到一端圓弧的中心,畫指定寬度的直槽。用於以一點為中心的槽。", + "help.sketch.slot.center_to_center": "在兩端圓弧的中心之間畫指定寬度的直槽。用於以中心距標註尺寸的槽,例如螺絲的調整槽。", + "help.sketch.slot.overall": "從一個外端到另一個外端畫指定寬度的直槽。用於槽的總長最重要時。", + "help.sketch.spline.control_point": "畫由控制點塑形的三次雲形線,曲線不會通過控制點。用於透過移動控制點來塑形的平滑流暢曲線。", + "help.sketch.spline.control_point_5": "畫由控制點塑形的 5 次雲形線。用於曲線須以更平滑的曲率接合之處,例如可見的造型曲面。", + "help.sketch.spline.fit_point": "畫通過您放置的每一點的平滑雲形線,可為開放或封閉。用於通過已知點描摹形狀。", + "help.sketch.spline3d": "開啟「3D 草圖」時,通過空間中的點畫平滑曲線。用於離開草圖平面的掃掠路徑和線纜路線。", + "help.sketch.spun_profile": "在草圖平面中建立實體繞軸旋轉時掃出的輪廓。用於取得車削零件的外形,供旋轉或圖紙使用。", + "help.sketch.text": "以選定的字型、高度和角度在草圖中寫入文字;文字內容可跟隨參數。可擠出或浮雕,用於標籤和字樣。", + "help.sketch.transform": "一步以中心點為基準縮放、旋轉和移動草圖幾何。用於一次重新定位並調整所選項目的大小。", + "help.sketch.trim": "移除曲線上您按一下之處兩側最近交點之間的一段。用於把重疊的線條清理成封閉的輪廓。", "help.solid.align": "移動所選實體,使其上的點、面或平面與別處的點、面或平面對齊。用於將一個零件貼靠到另一個零件上,而無需測量偏移量。", + "help.solid.boundary_fill": "由重疊的工具實體所圍成的區域建立實體,只填充您選取的區域。用於由多個實體共同圍出的空間建構形狀。", + "help.solid.bounding_solid": "建立包圍所選實體的長方體,可附邊距。用於查看零件的整體尺寸,或作為加工它的毛料。", + "help.solid.box": "由長、寬、高建立長方體,從一個角點開始或以一點為中心。用於快速建立方塊、佔位件,或作為要在其中切出特徵的實體。", "help.solid.chamfer": "以指定的距離在所選邊上切出平直的斜面。用於去除銳邊,或使銷釘、螺絲更容易插入。", + "help.solid.coil": "由直徑、圈數、高度或螺距,以及圓形或方形斷面,建立螺旋狀實體,例如彈簧。用於彈簧、線圈和螺旋脊。", "help.solid.combine": "結合多個實體、從目標實體中切除,或只保留它們共有的體積,還可以保留工具實體。用於合併零件、用一個形體切割另一個形體,或找出兩個實體重疊的位置。", + "help.solid.cone": "由底圓和高度建立圓錐體;若頂部也有半徑,則建立截頭圓錐。用於錐形、漏斗、錐孔和尖頭。", + "help.solid.cylinder": "由半徑或直徑和高度,沿軸立在一點上建立圓柱體。用於軸、銷、凸座和圓形毛料。", "help.solid.draft": "將所選的面依指定角度傾斜,角度從中性面量起。用於射出成型件或鑄件,使零件能夠順利脫模。", + "help.solid.emboss": "將草圖輪廓(例如文字或標誌)從面上凸起,或壓入面內。用於平面或圓面上的字樣、標籤和標記。", "help.solid.extrude": "將草圖輪廓依指定距離擠出為三維形體,可增加或移除材料。用於將平面輪廓變成方塊、凸座或凹槽。", "help.solid.fillet": "以指定半徑的平滑圓弧將所選的邊倒圓。用於為了強度、手感或外觀而柔化銳邊。", "help.solid.hole": "在面上的指定位置鑽出指定直徑的圓孔。用於螺絲過孔、銷孔及其他簡單的圓形開口。", @@ -1408,20 +1678,63 @@ "help.solid.move": "依指定的距離和角度移動或旋轉所選實體,或其副本。用於調整實體位置,或在別處再建立一個。", "help.solid.offset_face": "將所選的面依指定距離向內或向外推移,周圍的面隨之調整。用於在不編輯草圖的情況下加厚壁、加深凹槽或加高凸座。", "help.solid.pattern.circular": "將所選物件依指定的數量和總角度繞軸重複排列。用於螺栓圓周分布、輻條、散熱片和輪齒。", + "help.solid.pattern.path": "沿草圖路徑依數量和間距複製特徵或實體。用於沿曲邊排列的孔,或沿導軌排列的零件。", "help.solid.pattern.rectangular": "將所選物件依指定的數量和間距沿一個或兩個方向重複排列。用於成排或成網格的孔、肋、銷釘或支腳。", + "help.solid.pipe": "沿草圖曲線構成的路徑建立圓管,實心或帶壁厚的空心。用於管、線、纜和軌。", "help.solid.press_pull": "拖曳面以增加或移除材料,或拖曳邊將其倒圓。用於直接在模型上快速修改。", "help.solid.remove": "從時間軸的這個位置起,將所選實體從設計中移除;之前的步驟仍保留它們。用於移除輔助實體,例如不再需要的切割工具。", "help.solid.replace_face": "將所選的平面移到某個平面或平行的面上,實體會隨之伸長或縮短以對接。用於讓某個面與另一個零件或建構平面齊平。", "help.solid.revolve": "將草圖輪廓繞軸旋轉,生成圓形的實體。用於軸、旋鈕、碗,以及任何繞中心線呈圓形的零件。", + "help.solid.rib": "沿開放的草圖曲線新增薄壁,延伸填滿至實體的下一個面。用於加強壁和轉角,例如在成型或列印的零件中。", "help.solid.scale": "依比例放大或縮小所選實體,可各方向相同,也可依軸分別設定。用於調整匯入形體的大小,或預留收縮量。", "help.solid.shell": "將實體掏空,留下指定厚度的壁,還可以開啟所選的面。用於盒子、蓋子及其他薄壁零件。", + "help.solid.sphere": "由半徑或直徑繞中心點建立球體。用於球、旋鈕和圓端。", "help.solid.split_body": "以平面、另一個實體的面或草圖直線,將實體切分為多個獨立的實體。用於製作分別列印、加工或上色的零件。", "help.solid.split_face": "沿平面、另一個實體的面或草圖曲線分割所選的面,而不切開實體。用於為面的一部分單獨設定拔模、顏色或偏移。", "help.solid.sweep": "沿路徑拖曳草圖輪廓以生成實體。用於管道、導軌、把手,以及任何截面恆定且沿曲線延伸的零件。", + "help.solid.thread": "在圓柱面上新增 ISO 公制螺紋,可為裝飾螺紋或切入實體。用於螺栓、螺紋孔和列印的螺絲零件。", + "help.solid.torus": "由繞其軸的大半徑和圓形斷面的小半徑建立圓環體。用於 O 形環、把手和圓珠。", + "help.solid.web": "沿每條開放的草圖曲線新增薄壁,各自延伸填滿至實體的下一個面。用於外殼和托盤內部的支撐壁格柵。", + "help.surface.blend": "建立橋接兩個實體邊的曲面,與兩者相切或曲率連續。用於在間隙兩側平滑接合兩個曲面。", + "help.surface.boundary": "建立填滿由二至四條草圖曲線構成的迴圈或曲線網格的曲面。用於由邊界定義的自由形狀面板。", + "help.surface.extend": "將曲面延長超出其邊,可指定距離或延伸到平面或面。用於在修剪或縫合前讓曲面互相重疊。", + "help.surface.extrude": "將草圖曲線或輪廓沿一段距離推成曲面,只有壁,沒有封口。用於薄壁,以及切割或分割工具。", + "help.surface.fair": "在邊保持不動的情況下,平滑自由形狀面的內部。用於撫平曲面上的凸起和起伏的反射。", + "help.surface.loft": "建立依序通過兩個或多個斷面的曲面,沒有封口。用於殼體以及不同形狀之間的過渡。", + "help.surface.match": "重建曲面的邊,使其與另一個實體的邊相接,並相切或曲率相符。用於在兩個曲面之間平滑地封閉接縫。", + "help.surface.offset": "沿法線方向距離一定處建立面的副本,成為新的曲面實體。用於外皮、間隙,或壁的另一側。", + "help.surface.patch": "以平坦或平滑彎曲的面填滿草圖區域或封閉的邊迴圈。用於封閉曲面實體上的孔。", + "help.surface.reverse_normal": "翻轉曲面實體的面,使其外側朝向另一邊。用於面朝內時,在加厚或縫合之前。", + "help.surface.revolve": "將草圖曲線或輪廓繞軸旋轉成曲面,沒有封口。用於燈罩、碗和噴嘴等圓形殼體。", + "help.surface.ruled": "從一串邊沿面的法向、切線方向或以某個角度,建立由直線構成的條帶。用於拔模壁、延伸面和分模面。", + "help.surface.stitch": "沿共用的邊縫合曲面實體;若閉合則成為實體。用於將一組曲面變成一個實體。", + "help.surface.sweep": "將草圖曲線或輪廓沿路徑移動成曲面,沒有封口。用於沿路徑的排水槽、飾條和其他薄形狀。", + "help.surface.thicken": "賦予曲面實體厚度,將其變成實體。用於由曲面製作可列印或可加工的零件。", + "help.surface.trim": "以平面、另一個曲面或草圖曲線切割曲面,並保留您選取的一側。用於縫合前把曲面切成形狀。", + "help.surface.unstitch": "將實體的面分離為各自獨立的曲面實體;實體會散開成曲面。用於重做實體的單個面。", + "help.surface.untrim": "移除面上的孔,或將其外邊界還原為曲面的自然邊界。用於修剪後取回完整的曲面。", "help.third_party": "第三方授權", "help.timeline.compute_all": "從頭重新計算時間軸中的所有特徵。用於重新整理模型,並查看哪些特徵失敗。", "help.timeline.delete": "從時間軸中刪除所選特徵;刪除草圖時,由它建立的特徵也會一併刪除。用於移除不再需要的步驟。", + "help.timeline.dependents": "列出會隨某個特徵一起被刪除的特徵,以及沒有它就會失敗的特徵。用於刪除或變更特徵之前。", "help.timeline.play": "逐一重播其餘特徵,每次重建後暫停半秒。再次執行此命令或按 Escape 可停止;「移至結尾」會立即跳到結尾。", + "help.version": "版本 {version}", + "help.view.apply": "將檢視轉到標準方向(例如前、上或等角),或轉到已儲存的命名檢視。用於從固定角度觀看模型。", + "help.view.delete": "刪除已儲存的命名檢視。不會更改模型。", + "help.view.fit": "縮放並平移,使整個模型或所選項目填滿檢視。用於模型跑出視野之外時。", + "help.view.grid": "顯示或隱藏視埠中的網格。用作建模時的尺寸與方向參考。", + "help.view.ground_shadow": "顯示或隱藏模型在地面上的陰影。用於更容易判斷高度和位置。", + "help.view.home": "將檢視轉回主方向,並使模型符合視圖。用於快速回到已知的檢視。", + "help.view.list": "列出設計中儲存的命名檢視。用於找出先前儲存的檢視。", + "help.view.navigate": "以步進方式旋轉、平移或縮放檢視,例如向左四分之一圈。用於精確移動相機,而不必拖曳。", + "help.view.navigation_bar": "顯示或隱藏視埠底部的導覽列。隱藏可獲得更多空間,顯示則可用滑鼠使用檢視工具。", + "help.view.rename": "為已儲存的命名檢視取新名稱。檢視本身保持不變。", + "help.view.save": "將目前的相機位置儲存為設計中的命名檢視。用於之後回到同一角度,例如截圖。", + "help.view.spin": "持續環繞模型轉動檢視,直到下一次按一下或按鍵。用於從各個方向展示模型。", + "help.view.tool": "鎖定相機工具(環繞、平移或縮放),讓以滑鼠左鍵拖曳時移動檢視,直到您將其關閉。用於觸控板或沒有滑鼠中鍵時。", + "help.view.visual_style": "切換模型的繪製方式:著色(含或不含邊線)、線框,或含隱藏線。用線框查看內部,用著色得到乾淨的外觀。", + "history.sketch_under_constrained": "拘束不足({count} 個自由度)", + "history.sketch_under_constrained_one": "拘束不足({count} 個自由度)", "hole_presets.confirm_delete": "確認刪除", "hole_presets.delete": "刪除", "hole_presets.delete_prompt": "刪除此個人預設?現有的孔不會改變。", @@ -1525,6 +1838,8 @@ "joint_move.blocked_hint": "請檢查接頭類型(例如剛性)、固定狀態、接頭限制,以及由參數驅動的值。", "joint_move.blocked_title": "無法移動此零件", "joint_move.coarse": "靠近軸心時的旋轉步距(°)", + "joint_move.conflict": "此零件的一個接頭與其他接頭衝突:{joint}。", + "joint_move.conflict_hint": "請編輯、抑制或刪除衝突的接頭,讓其他接頭可以放置此零件。", "joint_move.distance": "與起點的距離", "joint_move.done": "完成", "joint_move.fine": "遠離軸心時的旋轉步距(°)", @@ -1596,6 +1911,10 @@ "material.selection.mixed": "不同材質", "measure.at": "位置", "measure.item": "項目 {number}", + "measure.quick_copied": "已複製測量值", + "measure.quick_copy": "按一下以複製測量值", + "measure.quick_edges": "{count} 條邊", + "measure.quick_faces": "{count} 個面", "messages.ago_h": "{n} 小時前", "messages.ago_min": "{n} 分鐘前", "messages.ago_s": "{n} 秒前", @@ -1620,6 +1939,8 @@ "motion.track_name": "軌道 {number}", "nav.alias.help": "Shift+Alt+左鍵拖曳可環繞,Shift+Alt+中鍵拖曳可平移,Shift+Alt+右鍵拖曳可縮放;中鍵拖曳也可平移,右鍵拖曳也可環繞", "nav.blender.help": "中鍵拖曳可環繞,Shift+中鍵可平移,Ctrl+中鍵可縮放;右鍵拖曳不會移動相機", + "nav.creo.help": "中鍵拖曳可環繞,Shift+中鍵可平移,Ctrl+中鍵垂直拖曳可縮放(向下為放大);捲動滾輪也可縮放", + "nav.creo.label": "Creo", "nav.free_orbit.help": "滑鼠與 3D 滑鼠可越過兩個極點旋轉並保留滾轉。Shift 軸向吸附已停用。", "nav.free_orbit.label": "自由環繞", "nav.free_orbit.snap_help": "滑鼠與 3D 滑鼠可越過兩個極點旋轉並保留滾轉。環繞拖曳時按住 Shift,可吸附檢視方向與滾轉。", @@ -1629,6 +1950,7 @@ "nav.hfss.help": "Alt+左鍵拖曳可平移,Shift+Alt+左鍵可縮放,在空白處按 Ctrl+左鍵拖曳可環轉", "nav.inventor.help": "中鍵拖曳可平移,Shift+中鍵可環繞,Ctrl+中鍵可縮放,右鍵拖曳可環繞", "nav.maya.help": "Alt+左鍵拖曳可環轉,Alt+中鍵可平移,Alt+右鍵可縮放;中鍵拖曳同樣可平移", + "nav.nx.help": "中鍵拖曳可環繞,Shift+中鍵可平移(NX 的中鍵 + 右鍵),Ctrl+中鍵可縮放(NX 的中鍵 + 左鍵);右鍵拖曳不會移動相機", "nav.openscad.help": "在空白處以左鍵拖曳可環繞,Shift+左鍵拖曳可框選,拖曳草圖幾何可編輯;右鍵或中鍵拖曳可平移,Shift+右鍵或 Shift+中鍵拖曳可縮放", "nav.perspective.sketch": "編輯草圖時會使用正交檢視。完成草圖後才能切換為透視。", "nav.right_drag_orbits.help": "關閉:右鍵拖曳不會移動相機,右鍵只會開啟右鍵選單。選擇 SolidWorks 滑鼠對應會將其關閉。", @@ -1748,6 +2070,11 @@ "not a move": "不是移動", "not a number": "不是數字", "open a sketch first": "請先開啟一個草圖", + "parameters.apply_live": "離開欄位時即套用每項變更", + "parameters.apply_live_tip": "關閉:變更會等到按下「套用」或「確定」,然後設計一次性為所有變更重建。「取消」或 Esc 會捨棄這些變更。", + "parameters.held": "{count} 項變更等待套用", + "parameters.held_hint": "編輯運算式和單位。變更會等到按下「套用」或「確定」。", + "parameters.held_one": "1 項變更等待套用", "parts.automatic_name": "自動", "parts.dimension.across_flats": "對邊寬度", "parts.dimension.bore": "內徑", @@ -1766,10 +2093,19 @@ "parts.family.button_head_cap_screw": "內六角半圓頭螺絲", "parts.family.dowel_pin": "圓柱銷", "parts.family.hex_bolt": "六角頭螺栓", + "parts.family.hex_cap_screw_inch": "外六角螺絲(英吋)", "parts.family.hex_nut": "六角螺帽", + "parts.family.hex_nut_inch": "六角螺帽(英吋)", "parts.family.set_screw": "內六角平端止付螺絲", "parts.family.socket_head_cap_screw": "內六角圓柱頭螺絲", "parts.family.washer": "平墊圈", + "parts.family.washer_sae": "平墊圈,SAE(窄型)", + "parts.family.washer_uss": "平墊圈,USS(寬型)", + "parts.holes": "孔(可選)", + "parts.placement_hint": "選取一個或多個孔,將零件放入每個孔中,或按「確定」將其放在原點", + "parts.system": "單位系統", + "parts.system.inch": "英吋", + "parts.system.metric": "公制", "pattern.alignment_2": "對齊 2", "pattern.alignment_hint": "數量包含原始物件。置中時副本分佈在兩側;數量為偶數時,反轉可切換多一個副本的一側。", "pattern.direction_1": "方向 1", @@ -1810,6 +2146,8 @@ "prefs.anti_aliasing_note": "平滑鋸齒狀邊緣。", "prefs.applies_on_restart": "重新啟動後生效", "prefs.assistant": "助理", + "prefs.auto_operation": "自動選擇操作", + "prefs.auto_operation_note": "特徵視窗會依新材料接觸到的內容,自動選擇「接合」、「新建實體」或「剪下」,直到您自行選擇為止。關閉時:維持開啟時的操作。", "prefs.axes": "軸", "prefs.axis": "軸", "prefs.bodies_folders": "實體資料夾", @@ -1820,6 +2158,10 @@ "prefs.bottom_centre": "下方置中", "prefs.bottom_right": "右下方", "prefs.browser": "瀏覽器", + "prefs.browser_components_open": "元件初始展開", + "prefs.browser_components_open_note": "瀏覽器中的每個元件都像以前一樣初始展開,而不是在您展開前保持摺疊。", + "prefs.browser_eye_left": "眼睛圖示置於摺疊箭頭旁", + "prefs.browser_eye_left_note": "瀏覽器各列會照舊把顯示/隱藏的眼睛圖示放在摺疊箭頭旁,而不是放在各列右端的一欄中。", "prefs.browser_reveal_on_hover": "游標移上時顯示", "prefs.browser_show_note": "「顯示」會讓瀏覽器保持在畫面上。「游標移上時顯示」會將它隱藏,直到指標移到它的位置或其左緣的細長標籤上;當指標位於其中或從它開啟的選單仍開著時,它會保持開啟。", "prefs.browser_shown": "顯示", @@ -1827,6 +2169,8 @@ "prefs.button_left": "左鍵拖曳", "prefs.button_middle": "中鍵拖曳", "prefs.button_right": "右鍵拖曳", + "prefs.carousel_next": "下一個", + "prefs.carousel_previous": "上一個", "prefs.choose_font": "選擇字型檔案…", "prefs.click": "點擊", "prefs.contact_shading": "柔和接觸陰影", @@ -1839,6 +2183,10 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "曲面", "prefs.curves": "曲面", + "prefs.cut_preview_tint": "以紅色顯示移除的材料", + "prefs.cut_preview_tint_help": "預覽會以紅色半透明的虛影填滿特徵所移除的材料,以及被它取代的形狀。關閉時,這些填色完全透明,只繪製輪廓線。", + "prefs.dark_parts_shading": "保留深色零件的形狀", + "prefs.dark_parts_shading_help": "以線性光搭配柔和的天空補光對檢視進行著色,讓深色的面保有漸層,而不會變成全黑", "prefs.dead_zone_note": "斜線區域為死區:此範圍內的移動會被忽略。", "prefs.default": "預設", "prefs.design": "設計預設值", @@ -1853,6 +2201,8 @@ "prefs.edges": "邊與著色", "prefs.extend": "延伸", "prefs.extra_navigation": "在空白處按住 Ctrl 並以左鍵拖曳可環轉;按住空白鍵可平移。", + "prefs.extrude_view_isometric": "開啟「擠出」時將檢視轉為等角視圖", + "prefs.extrude_view_return": "關閉「擠出」時回到先前的檢視", "prefs.follows_os": "跟隨作業系統", "prefs.font": "字型", "prefs.font_fallback": "所選字型缺少的字元會改用內建字型,因此標籤不會出現空白方框。", @@ -1868,8 +2218,11 @@ "prefs.graphics_card_auto": "自動", "prefs.graphics_card_missing": "已儲存的顯示卡無法使用;將改用自動選擇。", "prefs.graphics_card_restart": "重新啟動 SolidCraft 後生效。WGPU_ADAPTER_NAME 會覆蓋此選擇。", + "prefs.graphics_card_unused": "已儲存的顯示卡未用於此視窗;實際使用的顯示卡顯示在「說明 › 關於」和狀態列中。請嘗試「自動」,或將 WGPU_ADAPTER_NAME 設為顯示卡名稱中的唯一部分。", "prefs.graphics_note": "在速度與平滑度之間取捨。每個選項都會在範例上顯示其效果。", "prefs.graphics_presets_note": "預設集會一併設定下列選項。", + "prefs.hide_constraint_glyphs_zoomed_out": "縮小檢視時隱藏拘束符號", + "prefs.hide_constraint_glyphs_zoomed_out_note": "草圖縮小到拘束符號會使畫面雜亂的程度時,拘束符號會從檢視中消失。關閉時:無論縮放多少,它們都維持固定的螢幕大小。", "prefs.history": "歷程記錄", "prefs.history_origin_bodies": "在頂部顯示原點與實體", "prefs.history_origin_bodies_note": "左側或瀏覽器下方的歷程記錄,會以作用中元件的「實體」資料夾和「原點」開頭,其顯示切換(眼睛圖示)和選單與瀏覽器中相同。底部的歷程記錄維持不變。", @@ -1880,6 +2233,8 @@ "prefs.history_sketches_note": "「草圖」設為「位於其特徵下」時,左側的歷程記錄在寬度足以顯示名稱時,會把每個草圖縮排一層,列在由它建立的第一個特徵之下。底部的時間軸一律保持建立順序。", "prefs.history_sketches_under_feature": "位於其特徵下", "prefs.hold_stop_snapping": "按住以停用鎖點", + "prefs.home_fit_size": "主檢視與符合檢視的大小", + "prefs.home_fit_size_note": "在主檢視、符合檢視、開啟設計或檢視導覽器切換檢視而為模型取景時,模型佔滿檢視的程度,不論下方的設定是否開啟。100 %:填滿面板、羅盤與導覽列之間的檢視區域。", "prefs.icons_only": "僅圖示", "prefs.imported_file": "已匯入的檔案", "prefs.in_browser": "瀏覽器內", @@ -1888,13 +2243,22 @@ "prefs.interface_language": "介面語言", "prefs.interface_note": "SolidCraft 的外觀與各面板的位置。", "prefs.interval_minutes": "{n} 分鐘", + "prefs.invert_curved_roll_arrows": "反轉彎曲的滾轉箭頭", + "prefs.invert_curved_roll_arrows_note": "立方體角落的兩個彎曲箭頭會在螢幕平面內滾轉檢視。開啟時:順時針箭頭會逆時針滾轉,逆時針箭頭會順時針滾轉。關閉時:每個箭頭依其彎曲的方向滾轉檢視。", + "prefs.invert_navigator_arrows": "反轉檢視立方體的旋轉箭頭", + "prefs.invert_navigator_arrows_note": "立方體周圍的箭頭會依其所指方向環繞相機,與 Fusion 和 Inventor 相同:左側箭頭指向右方,並將相機向右擺動。關閉時:箭頭會將立方體轉向它所在的一側,因此左側箭頭會將相機向左擺動。彎曲的滾轉箭頭不受影響。", + "prefs.keep_work_on_tab_switch": "切換設計時保持對話方塊與工具開啟", + "prefs.keep_work_on_tab_switch_note": "每個設計分頁都會保留其開啟的對話方塊或工具、您在其中選取與輸入的內容,以及其工具列索引標籤。回到該設計時,它們會恢復原狀。關閉時:切換設計會取消它們,並顯示「模型」索引標籤。", "prefs.labels": "標籤", + "prefs.language_system": "系統", "prefs.layout": "配置", "prefs.layout_note": "精簡模式會將面板停靠在視窗邊緣。瀏覽器半透明僅適用於浮動模式。助理的位置請在「助理」頁面中變更。", "prefs.left": "左側", "prefs.left_click": "左鍵點擊", "prefs.line_drag_draws_one": "按下並拖曳繪製一條直線", "prefs.line_drag_draws_one_note": "在「直線」工具中,按下、拖曳再放開,會從按下處到放開處繪製一條直線,並在該處結束。按一下仍會繪製連續線段。關閉:拖曳會在放開處放置一個點,與按一下相同。", + "prefs.line_hover_tangent_arc": "停在直線的最後一點上即可切換為相切圓弧", + "prefs.line_hover_tangent_arc_note": "在「直線」工具中繪製一段後,移離連續線段的最後一點,再回來並將指標停在該點上:下一次點擊會決定相切圓弧的終點,同樣的動作則會切回直線。關閉時:停在該處不會有任何作用。", "prefs.linked_designs": "連結設計", "prefs.live_input": "即時輸入", "prefs.live_preview": "即時預覽", @@ -1908,6 +2272,9 @@ "prefs.max_file_size_step": "STEP 和匯入檔案", "prefs.max_file_size_web": "網頁版可開啟最大 512 MB 的 STEP 和匯入檔案,以及最大 256 MB 的設計:瀏覽器分頁無法容納更大的檔案。桌面版可提高這些上限。", "prefs.megabytes": "MB", + "prefs.menu_grid": "大圖示", + "prefs.menu_list": "清單", + "prefs.menus": "選單", "prefs.minutes": "分鐘", "prefs.minutes_suffix": " min", "prefs.mouse": "滑鼠與觸控板", @@ -1915,6 +2282,8 @@ "prefs.mouse_mapping": "滑鼠對應", "prefs.navigation": "導覽", "prefs.navigation_note": "滑鼠、觸控板和 3D 滑鼠移動檢視的方式。", + "prefs.navigator_fit": "變更導覽器檢視後使模型符合視圖", + "prefs.navigator_fit_note": "檢視立方體的面、角或箭頭,或方向控制器的某個軸,也會從能容納整個模型各側的單一距離(其邊界球)看向模型中心。啟用時,「主檢視」使用相同的縮放與中心,因此之後選擇的檢視只會旋轉。關閉時:檢視原地旋轉,保留其目標與縮放。", "prefs.network_host_remove": "移除", "prefs.network_locations": "允許設計中的網路位置", "prefs.network_locations_note": "關閉:設計中位於其他電腦 (\\\\server\\share) 上的連結檔案,只會從此處列出的伺服器開啟,或在詢問時由您允許某個伺服器後才開啟。", @@ -1927,10 +2296,18 @@ "prefs.origin_plane_names": "原點平面名稱", "prefs.origin_plane_names_note": "顯示於瀏覽器、對話方塊和清單中的名稱。{top} 為 XY,{front} 為 XZ,{right} 為 YZ,Z 軸朝上。命令、指令碼和已儲存的設計仍使用 XY、XZ 和 YZ。", "prefs.overall_speed": "整體速度", + "prefs.parameter_list_rows": "參數清單列數", + "prefs.parameter_list_rows_tip": "在空的數值欄位按向下鍵會列出參數,收藏的排在前面,最多列出這麼多列。列數較少可讓大型設計中的清單保持輕巧。", + "prefs.persistent_ribbon_pressed": "醒目顯示作用中的功能區命令", + "prefs.persistent_ribbon_pressed_help": "在功能區命令的效果開啟期間醒目顯示這些命令。關閉可維持先前的中性外觀與命令說明。", "prefs.perspective_fov": "視角", "prefs.placement": "放置", "prefs.prefer_free_sketch_points": "點重疊時優先選取可移動的草圖點", "prefs.preview_choices": "所選設定的預覽", + "prefs.preview_tint_new_faces": "在預覽中為新增的表面著色", + "prefs.preview_tint_new_faces_help": "會改變實體的特徵預覽,可用預覽色繪製其新增的表面。關閉時,實體依本身的樣子繪製。", + "prefs.print_face_highlight": "列印底面醒目提示", + "prefs.print_face_highlight_tip": "在檢視中為實體的列印底面著色及描邊的強度。0 % 不顯示醒目提示。", "prefs.profile_active": "作用中的設定檔", "prefs.profile_applied": "已套用設定檔。", "prefs.profile_changed": "儲存設定檔後設定已有變更。按「儲存」可將變更保存到設定檔中。", @@ -1952,9 +2329,13 @@ "prefs.quality_fastest": "最快", "prefs.quality_slowest": "最慢", "prefs.quality_smoother": "更平滑", + "prefs.quick_measure": "檢視角落的快速測量", + "prefs.quick_measure_note": "在檢視右下角顯示所選項目的大小:邊的長度(圓形邊則為 Ø 和 R)、面的面積、點的位置、兩個項目的距離和角度,或多條邊、多個面的總計。按一下即可複製。", "prefs.render_previous_geometry_budget": "使用先前的彩現預覽幾何預算", "prefs.render_previous_geometry_budget_help": "還原先前固定的幾何上限(64 位元桌面版為 512 MiB,其他平台為 128 MiB),而非依裝置決定的預算。", "prefs.reports_saved": "已儲存 {n} 份", + "prefs.ribbon_click_ends_tool": "按一下執行中工具的按鈕即可結束該工具", + "prefs.ribbon_click_ends_tool_note": "按一下使用中草圖工具亮起的功能區按鈕會結束該工具,讓在檢視中的點擊恢復為選取。關閉時:點擊會重新啟動該工具。", "prefs.ribbon_reveal": "在功能區中顯示搜尋結果", "prefs.ribbon_reveal_note": "在「搜尋命令」中將指標停留在結果上,會顯示該命令在功能區中的位置:其索引標籤、按鈕,或面板下拉選單中的列。從搜尋啟動的命令會在該處閃爍,而從下拉選單執行中的命令會標示其所在面板。", "prefs.right_click": "右鍵點擊", @@ -1965,6 +2346,8 @@ "prefs.search_empty": "沒有符合的設定", "prefs.select": "選擇", "prefs.select_one_item": "選擇一個項目", + "prefs.select_other_hidden": "以「選擇其他」選取隱藏的幾何", + "prefs.select_other_hidden_help": "開啟:納入指標附近隱藏的實體、草圖與被遮住的邊。關閉:沿用原本指標下可見幾何的清單。", "prefs.selecting": "選擇", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift 僅新增;Ctrl / Cmd 切換選擇", @@ -1976,31 +2359,63 @@ "prefs.sketch_align_points_note": "繪製時,點可同時與一個草圖點水平對齊、並與另一個草圖點垂直對齊,並顯示點線輔助線,按一下會保留兩個對齊。關閉:只與前一個點對齊,一次一個軸向。", "prefs.sketch_conflict_colour": "衝突幾何以衝突顏色顯示", "prefs.sketch_conflict_colour_note": "草圖的拘束發生衝突時,失敗拘束所涉及的曲線與點也會以衝突顏色繪製,而不只是其符號或尺寸。關閉時:維持原本的顏色。", + "prefs.sketch_construction_lines": "延伸建構直線工具", "prefs.sketch_exit_view": "草圖結束時", "prefs.sketch_exit_view.keep": "保持目前檢視", "prefs.sketch_exit_view.previous": "返回先前的檢視", "prefs.sketch_exit_view.unless_rotated": "未旋轉時返回", "prefs.sketch_exit_view_note": "「完成草圖」、取消或連按兩次 Esc 後檢視的去向。", + "prefs.sketch_face_activates_part": "在零件的面上繪製草圖會使該零件成為作用中", + "prefs.sketch_face_activates_part_note": "在其他元件之實體的面上開始的草圖,會先啟用該元件,因此草圖屬於該元件,並在瀏覽器中與該零件放在一起。之後該零件仍保持作用中。關閉時:草圖屬於目前作用中的元件。", + "prefs.sketch_open_look_at": "開啟草圖時轉向正對草圖", + "prefs.sketch_open_look_at_note": "關閉:建立或編輯草圖時維持目前的檢視。需要時可用「注視」正對草圖。", "prefs.sketch_recent_snap": "自動鎖點至最近使用的圓心與中點", "prefs.sketch_recent_snap_note": "繪製時,游標會鎖點至最近使用的兩個圓心或直線邊中點的輔助線交會處。關閉時:這些輔助線僅供顯示,游標不會移動。", "prefs.sketch_selection": "草圖與選取", "prefs.sketch_selection_heading": "草圖與選取", "prefs.sketch_selection_note": "草圖如何貼齊,以及點擊如何選取。", + "prefs.sketch_state_icons": "草圖圖示以其狀態的顏色顯示", + "prefs.sketch_state_icons_note": "在歷程記錄與瀏覽器中,草圖圖示會採用其狀態的顏色(拘束不足、完全拘束或衝突),其工具提示也會註明該狀態。關閉時:所有草圖使用相同圖示。", "prefs.sketch_tab_always": "保持顯示「草圖」索引標籤", "prefs.sketch_tab_always_note": "沒有開啟草圖時,「草圖」索引標籤仍保留在功能區中,位於「模型」之後。使用其繪圖工具時,會在所選的平面或面上、或在你接著選取的平面上開始草圖,並直接啟用該工具。", "prefs.sketch_tracking_guides": "圓心與中點對齊輔助線", "prefs.sketch_tracking_guides_note": "游標停在圓心或直線邊的中點上,再水平或垂直移動,即可顯示暫時的點線輔助線。", + "prefs.sketch_tracking_points": "繪製時顯示來自端點和角的對齊輔助線", + "prefs.sketch_tracking_points_note": "繪圖工具等待指定點時,將游標停在直線或圓弧的端點、矩形的角或自由點上,會顯示與圓心或中點相同的暫時點線輔助線。關閉:僅限圓心和中點。", "prefs.sketching": "草圖", "prefs.snap_drawing_note": "繪製或拖曳草圖點時使用。", "prefs.source": "來源", "prefs.speed": "速度", "prefs.stand_up_note": "以 Z 軸向上開啟 STEP 或 IGES 檔案後,詢問是否繞 X 軸旋轉 90°。", + "prefs.stand_up_unknown": "來自未知程式的檔案", + "prefs.stand_up_unknown.ask": "在對話方塊中詢問", + "prefs.stand_up_unknown.note": "顯示提示", + "prefs.stand_up_unknown.off": "不提供", + "prefs.stand_up_unknown_note": "當檔案標頭沒有指出任何已知以 Y 軸向上儲存的程式時,要如何提出詢問。「顯示提示」只會在檔案看起來平躺時顯示;「在對話方塊中詢問」則和以往一樣,對每一個這類檔案都會詢問。", "prefs.status_bar": "狀態列", "prefs.status_bar_note": "視窗底部的細長列會顯示正在編輯的內容、以顏色表示的開啟中草圖狀態,以及設計的單位;按一下單位即可變更。草圖狀態就不會再顯示在檢視的角落。", "prefs.status_done": "完成", "prefs.status_error": "錯誤", "prefs.status_selected": "已選取", "prefs.status_warning": "警告", + "prefs.structure.appearance": "外觀", + "prefs.structure.appearance_note": "顏色、文字與無障礙功能。", + "prefs.structure.in_profile": "在設定檔中", + "prefs.structure.layout": "配置", + "prefs.structure.layout_note": "視窗各部分的位置。", + "prefs.structure.look": "風格", + "prefs.structure.measure_pointer": "測量與指標", + "prefs.structure.mouse3d": "3D 滑鼠", + "prefs.structure.mouse3d_note": "SpaceMouse 與 SpaceNavigator。", + "prefs.structure.navigation_note": "滑鼠與觸控板。3D 滑鼠有專屬頁面。", + "prefs.structure.profile": "設定檔", + "prefs.structure.profile_edited": "儲存後已變更", + "prefs.structure.profile_hover": "儲存於設定檔中", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "草圖", + "prefs.structure.tools": "工具", + "prefs.structure.tools_note": "建模工具的行為方式。", + "prefs.structure.work": "工作", "prefs.supersampling_brief": "以更高解析度繪製檢視再縮小:非常清晰,但負載較高。", "prefs.tab_accent_note": "強調色跟隨目前的分頁", "prefs.theme_file": "主題檔案", @@ -2012,6 +2427,16 @@ "prefs.theme_follow_off": "關閉", "prefs.theme_follow_stop": "停止跟隨", "prefs.theme_import_hint": "按一下以選擇主題檔案、將檔案拖放到此處,或在已複製主題的情況下按 Ctrl+V(Mac 為 Cmd+V)", + "prefs.theme_option_opacity": "不透明度", + "prefs.theme_option_opacity_help": "調整浮動面板的不透明度。可讀性下限會保護視埠顏色上的文字。", + "prefs.theme_option_tab_colours": "索引標籤顏色", + "prefs.theme_option_tab_colours_help": "每個功能區索引標籤都使用此主題的面板和視埠顏色。", + "prefs.theme_option_tab_fade_ms": "索引標籤轉場", + "prefs.theme_option_tab_fade_ms_help": "切換索引標籤時,面板和視埠顏色會淡入淡出。設為零則立即切換。", + "prefs.theme_options_badge": "選項", + "prefs.theme_options_more": "更多 · {count}", + "prefs.theme_options_reset": "重設", + "prefs.theme_options_unavailable": "此裝置上無法使用", "prefs.theme_paste": "貼上主題", "prefs.theme_paste_none": "剪貼簿中沒有 SolidCraft 主題", "prefs.timeline_half_hour": "−30 分鐘", @@ -2033,13 +2458,23 @@ "prefs.under_cursor": "游標下方", "prefs.units_precision": "單位與精度", "prefs.updates": "更新", + "prefs.value_boxes_in_view": "在檢視中於控點旁顯示數值", + "prefs.value_boxes_in_view_tip": "命令的數值(距離、半徑…)會顯示在模型上方、控點旁的方框中。關閉:在命令視窗中輸入,選取後命令視窗會接手鍵盤,也不會有東西遮住模型。", "prefs.view": "檢視行為", "prefs.view_confirm_corner": "在檢視角落顯示「確定」與「取消」", "prefs.view_confirm_corner_note": "開啟對話框或草圖時,檢視右上角的勾號與叉號,作用等同於對話框的「確定」與「取消」,或完成與取消草圖。檢視導覽器會下移到它們下方。", "prefs.viewport": "視埠", + "prefs.viewport_analysis_status": "顯示視埠分析狀態", + "prefs.viewport_analysis_status_help": "在視埠上方顯示作用中的分析,可從各項目開啟其圖例,並以 Esc 關閉最新的分析。關閉可還原角落圖例與先前的 Esc 行為。", "prefs.viewport_background": "背景", "prefs.viewport_background_colour": "顏色", "prefs.viewport_background_theme": "主題漸層", + "prefs.viewport_section_status": "顯示視埠剖面狀態", + "prefs.viewport_section_status_help": "在視埠中顯示剖面設定。按 Esc 或作用中的功能區按鈕可將其關閉。停用可保留先前的剖面控制項。", + "prefs.viewport_status_details": "即時視埠詳細資料", + "prefs.viewport_status_details_help": "在標準詳細資料卡中編輯作用中的分析和剖面設定。停用可還原唯讀的分析圖例和「剖面」對話方塊。", + "prefs.viewport_status_summary": "摺疊視埠狀態項目", + "prefs.viewport_status_summary_help": "將三個或更多視埠狀態項目摺疊成一個摘要徽章。停用可讓每個項目都留在完整的列中。", "prefs.wheel": "滾輪", "prefs.wheel_trackpad": "滾輪與觸控板", "prefs.workspace": "工作區", @@ -2049,6 +2484,10 @@ "properties.title": "屬性:{name}", "recovery.days_ago": "{count} 天前", "recovery.detail": "{file} · {features} 個特徵 · 自動儲存於 {when}", + "recovery.discard_all": "全部捨棄", + "recovery.discard_all_detail": "此操作無法復原。", + "recovery.discard_all_title": "捨棄 {count} 個自動儲存檔?", + "recovery.discard_all_title_one": "捨棄 1 個自動儲存檔?", "recovery.hours_ago": "{count} 小時前", "recovery.just_now": "剛剛", "recovery.min_ago": "{count} 分鐘前", @@ -2164,6 +2603,10 @@ "render.base_color": "基底顏色 · sRGB", "render.base_metallic": "金屬比例", "render.base_opaque_only": "此編輯器保留不透明實體的語意。光學穿透請使用專屬的玻璃控制項。", + "render.batch_all_shots": "所有鏡頭({count})", + "render.batch_empty": "彩現所有鏡頭前,請先儲存一個鏡頭。", + "render.batch_limit": "「彩現所有鏡頭」最多只能處理 32 個鏡頭。", + "render.batch_status": "{running} 個執行中 · {waiting} 個等待中", "render.bloom_enable": "顯示泛光", "render.bloom_help": "僅用於輸出的創意輝光,由線性正值高光經三次正規化方框模糊擴散而成。半徑以輸出像素為單位。在轉換為 sRGB 之前,於線性顯示光中疊加;並非鏡頭效果、體積效果,也無法改善收斂。原始 EXR 保持不變。", "render.bloom_opaque": "泛光需要不透明輸出。透明 PNG 會被拒絕,而不會默默壓平。", @@ -2274,6 +2717,13 @@ "render.choose_look": "請先在「外觀」中選擇風格", "render.chromatic_offset": "邊緣色差偏移", "render.clear_stage": "移除已儲存的佈景", + "render.compare_divider": "比較分隔線", + "render.compare_live": "即時", + "render.compare_live_preview": "即時預覽", + "render.compare_render": "彩現 {number}", + "render.compare_side": "彩現 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · 擷取於修訂版本 {revision}", + "render.compare_swap": "對調", "render.copy_request": "複製 JSON", "render.cpu_aa_help": "空間取樣:取樣越多,邊緣越平滑,但彩現時間也越長。", "render.cpu_area_add": "新增矩形 CPU 燈光", @@ -2914,7 +3364,9 @@ "render.output_ready": "可開始彩現", "render.output_run_check": "執行檢查", "render.output_size_limit": "{method}:每邊最多 {dimension} px,總計 {pixels} 像素。可容納的最大尺寸:{width} × {height}。", + "render.output_size_method_profile": "若要彩現 {width} × {height},請選擇搭配 {profile} CPU 資源設定檔的 {method},或選擇較小的尺寸。", "render.output_size_ok": "大小正常 · {width} × {height} px", + "render.output_size_profile": "若要彩現 {width} × {height},請選擇 {profile} CPU 資源設定檔,或選擇較小的尺寸。", "render.output_swap_orientation": "交換寬度與高度", "render.output_tools_inspector": "請在「輸出」檢查器中編輯尺寸與格式。", "render.output_view_image": "檢視影像", @@ -3021,6 +3473,10 @@ "render.result_retained": "顯示上一張已完成的影像;較新的彩現尚未取代它。", "render.result_sequence": "檢查點", "render.result_title": "彩現結果", + "render.results_choose": "保留的結果", + "render.results_label": "彩現 {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [已過期]", + "render.results_unnamed": "影像", "render.return_design": "返回設計", "render.review_stale": "此檢閱已過期。請先解決或重新檢查,再套用。", "render.ribbon_aging": "老化", @@ -3127,6 +3583,7 @@ "render.size_custom": "自訂…", "render.size_full_hd": "Full HD", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · 需要 {profile}", "render.size_presets": "尺寸預設", "render.size_presets_pending": "將隨「輸出」編輯器推出", "render.size_preview": "預覽", @@ -3414,6 +3871,24 @@ "sheet.flange_type_contour": "輪廓", "sheet.flange_type_edge": "邊線", "sheet.no_body": "沒有鈑金實體:請用「凸緣 > Base」建立,或用「轉換為鈑金」將板材轉為鈑金(選取其較大的平面)", + "sheet.personal_rules.confirm_delete": "確認刪除", + "sheet.personal_rules.delete": "刪除", + "sheet.personal_rules.delete_prompt": "要刪除此個人規則嗎?已在設計中的規則不受影響。", + "sheet.personal_rules.full": "個人規則庫已包含 64 條規則。", + "sheet.personal_rules.invalid_name": "請輸入不含換行或控制字元的簡短名稱。", + "sheet.personal_rules.invalid_values": "請補全規則的數值:每個值都必須能在此設計中成立,厚度須為正,K 因子須介於 0 到 1。", + "sheet.personal_rules.missing": "所選的個人規則已無法使用。", + "sheet.personal_rules.name": "規則名稱", + "sheet.personal_rules.name_exists": "已有同名的個人規則。請使用其他名稱。", + "sheet.personal_rules.name_hint": "唯一的名稱", + "sheet.personal_rules.overwrite": "將變更儲存到所選的個人規則", + "sheet.personal_rules.rename": "重新命名", + "sheet.personal_rules.rule": "個人規則", + "sheet.personal_rules.save": "另存為新規則", + "sheet.personal_rules.scope": "儲存在您的設定檔中,適用於所有設計。", + "sheet.personal_rules.select": "選擇規則", + "sheet.personal_rules.title": "個人規則", + "sheet.personal_rules.unsupported": "此規則含有此版本無法使用的值。", "shortcut.json_error": "參數必須採用 JSON 格式:{error}", "shortcut.no_command": "沒有命令 `{id}`;JSON 前的文字必須是命令 ID", "shortcut.pin": "固定到 S 框頂部", @@ -3450,8 +3925,10 @@ "sketch_text.align_right": "靠右對齊", "sketch_text.bold": "粗體", "sketch_text.builtin_font": "{family}(內建)", + "sketch_text.formula": "以 = 開頭,可由參數組出文字:='W' + number(Width)", "sketch_text.italic": "斜體", "sketch_text.loading_fonts": "正在查詢已安裝字型…", + "sketch_text.no_bold": "內建字型沒有粗體:請選擇已安裝的字型", "sketch_text.on_path": "文字沿路徑排列:由曲線放置", "sketch_text.path_clear": "將文字移離其曲線", "sketch_text.path_hint": "文字所跟隨的草圖曲線:先點擊此處,再選擇曲線", @@ -3483,10 +3960,7 @@ "the two origins are on the same component": "這兩個原點位於同一個元件上", "thread.automatic_size": "自動尺寸", "thread.designation": "螺紋標示", - "thread.direction": "螺紋方向", "thread.iso_metric": "ISO 公制", - "thread.left_hand": "左旋", - "thread.right_hand": "右旋", "thread.select_size": "選擇尺寸", "timeline.delete_after_marker_one": "刪除歷程標記之後的 1 個特徵", "timeline.delete_after_marker_other": "刪除歷程標記之後的 {count} 個特徵", @@ -3503,8 +3977,10 @@ "timeline.move_to_group": "將特徵移至資料夾", "timeline.rename_group": "重新命名特徵資料夾", "timeline.reorder_many": "特徵重新排序", + "timeline.suppress_features": "抑制特徵", "timeline.suppress_folders_tip": "抑制或取消抑制資料夾及其巢狀資料夾中的所有特徵", "timeline.ungroup": "移除特徵資料夾", + "timeline.unsuppress_features": "取消抑制特徵", "to the face": "到面", "to the next face": "到下一個面", "toolbar.customize_note": "{tab} 索引標籤。勾選命令可將其按鈕新增到工具列。您也可以將面板下拉選單中的某一行拖到工具列,將按鈕拖出工具列以移除,或使用下拉選單行中的固定圖示。", @@ -3588,6 +4064,8 @@ "ui.3d_mouse_section": "3D 滑鼠", "ui.3d_mouse_show_in_view": "在 3D 檢視中顯示 3D 滑鼠", "ui.3d_mouse_show_in_view_tip": "在左下角顯示 3D 滑鼠的圖示,隨您的操作而移動。", + "ui.3d_mouse_sketch_orbit": "使用 3D 滑鼠旋轉草圖", + "ui.3d_mouse_sketch_orbit_tip": "開啟草圖且正對觀看時,3D 滑鼠也能像滑鼠一樣旋轉檢視。關閉:在您傾斜檢視之前,它只會平移和縮放草圖。", "ui.3d_mouse_skip": "我的裝置做不到", "ui.3d_mouse_skip_tip": "兩個方向都跳過此動作,校準時不包含它。", "ui.3d_mouse_speed": "3D 滑鼠速度", @@ -3616,6 +4094,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "逆時針扭轉搖桿帽,保持住,然後鬆開。", "ui.3d_mouse_switch_cap": "改以回中型校準", "ui.3d_mouse_switch_trackball": "改以軌跡球校準", + "ui.3d_mouse_use_direct": "使用直接驅動", + "ui.3d_mouse_use_direct_tip": "直接讀取 3D 滑鼠(hidraw),不經過 spacenavd。", "ui.3d_mouse_view_axis": "檢視軸", "ui.3d_mouse_view_off": "關閉", "ui.3d_mouse_view_off_tip": "3D 滑鼠驅動程式的設定檔關閉了此軸,因此它的動作不會移動檢視。在此選擇另一個軸的動作會將兩者互換,該動作將不再移動檢視。", @@ -3654,6 +4134,8 @@ "ui.agent_chat_auth_terminal": "在終端中執行以下命令,然後再次點擊連線:", "ui.agent_chat_auth_title": "登入代理", "ui.agent_chat_cancel": "取消", + "ui.agent_chat_cancel_timeout": "代理未回應「停止」,已中斷連線。請重新連線以繼續。", + "ui.agent_chat_cannot_start": "已安裝,但無法啟動:{error}", "ui.agent_chat_changes": "{n} 項變更,一步復原", "ui.agent_chat_changes_n": "{n} 項變更", "ui.agent_chat_changes_of": "變更 {n}/{limit}", @@ -3662,11 +4144,13 @@ "ui.agent_chat_command": "代理命令", "ui.agent_chat_connect": "連線", "ui.agent_chat_copy": "複製", + "ui.agent_chat_copy_message": "複製訊息", "ui.agent_chat_ctx_bodies": "實體", "ui.agent_chat_ctx_elements": "元素", "ui.agent_chat_ctx_features": "特徵", "ui.agent_chat_ctx_more": "另有 {n} 項", "ui.agent_chat_ctx_other": "其他", + "ui.agent_chat_custom_heading": "自訂模型", "ui.agent_chat_custom_hint": "任何透過標準輸入輸出使用 Agent Client Protocol 的程式。不經過 shell 執行。", "ui.agent_chat_denied": "已拒絕", "ui.agent_chat_deny": "拒絕", @@ -3710,8 +4194,16 @@ "ui.agent_chat_mode_all": "全部", "ui.agent_chat_mode_ask": "詢問", "ui.agent_chat_mode_edits": "編輯", + "ui.agent_chat_model_custom": "使用自訂:{model}", "ui.agent_chat_model_no_tools": "{model} 無法使用 SolidCraft 的工具,只能聊天。請選擇支援工具的模型。", + "ui.agent_chat_model_rejected": "代理未接受 {model}:{error}", + "ui.agent_chat_model_search": "搜尋模型…", "ui.agent_chat_model_tip": "代理使用的模型。您的選擇會為此代理記住。", + "ui.agent_chat_models_failed": "無法列出模型:{error}", + "ui.agent_chat_models_heading": "可用的模型", + "ui.agent_chat_models_listing": "正在列出模型…", + "ui.agent_chat_models_none": "端點未列出任何模型", + "ui.agent_chat_models_not_a_list": "回應不是模型清單", "ui.agent_chat_new": "新對話", "ui.agent_chat_new_confirm": "開始新對話?目前對話將被清除。", "ui.agent_chat_next_picture": "下一張圖片", @@ -3746,9 +4238,12 @@ "ui.agent_chat_queued_stopped": "已加入佇列(已停止,未傳送)", "ui.agent_chat_refresh": "重新整理", "ui.agent_chat_refused": "不允許代理執行:{reason}", + "ui.agent_chat_reinstall": "{agent} 已安裝({program}),但 SolidCraft 檢查時它沒有啟動:{error}\n其安裝可能不完整,或是為另一種電腦製作的。請用 `{install}` 重新安裝,在終端機中確認它會印出版本,然後按「重新整理」。", "ui.agent_chat_remove": "從佇列中移除", "ui.agent_chat_remove_file": "從這條訊息中移除", "ui.agent_chat_remove_imported": "從這條訊息中移除;零件仍保留在設計中(復原可將其刪除)", + "ui.agent_chat_reply_cut_off": "回覆在完成前就達到長度上限,因此可能不完整。請要求代理繼續,或給出較短的答案。", + "ui.agent_chat_reply_declined": "模型拒絕回答此訊息。", "ui.agent_chat_retry": "重試", "ui.agent_chat_right": "右側", "ui.agent_chat_save": "儲存", @@ -3807,12 +4302,17 @@ "ui.ai_copy_suffix": "副本", "ui.ai_custom_url": "自訂 URL", "ui.ai_default": "預設", + "ui.ai_edit": "編輯", + "ui.ai_edit_agent_title": "編輯代理", + "ui.ai_edit_gone": "此代理已被移除,因此沒有可儲存的內容。", + "ui.ai_edit_tip": "變更此代理的名稱、命令或端點。已儲存的金鑰會保持隱藏。", "ui.ai_http_busy": "端點繁忙或已達上限,請稍後再試", "ui.ai_http_key": "端點拒絕了金鑰:請在「偏好設定 > AI」中檢查", "ui.ai_http_not_found": "找不到該端點或模型:請檢查基礎 URL 和模型名稱", "ui.ai_http_too_large": "對話對此端點來說過大;請開始新的聊天", "ui.ai_key": "API 金鑰", "ui.ai_key_hint": "可選;儲存在系統鑰匙圈中", + "ui.ai_key_keep_hint": "留空以保留已儲存的金鑰", "ui.ai_key_needs_https": "金鑰只會透過 HTTPS 傳送,或傳送到本機。", "ui.ai_key_note": "儲存在系統鑰匙圈中,絕不儲存在 SolidCraft 的設定裡。本機伺服器可留空。", "ui.ai_keychain_error": "系統鑰匙圈拒絕:{error}", @@ -3839,11 +4339,15 @@ "ui.ai_permissions": "權限", "ui.ai_preset": "預設", "ui.ai_protocol": "通訊協定", + "ui.ai_reasoning_effort": "推理強度", + "ui.ai_reasoning_effort_field_hint": "留空 = 供應商預設值", + "ui.ai_reasoning_effort_hint": "可選。會以 `reasoning_effort` 傳送給端點;可接受的值因供應商而異(例如 `low`、`high` 或 `max`)。您在此設定的值絕不會被 SolidCraft 取代。留空則不傳送任何內容,並沿用供應商的預設值。", "ui.ai_remove": "移除", "ui.ai_request_timed_out": "模型耗時超過 {seconds} s。您可以在「偏好設定 › 助理」中調高此端點的請求逾時。", "ui.ai_request_timeout": "請求逾時", "ui.ai_request_timeout_hint": "對此端點的單次模型請求最多可花費的時間,從 30 s 到 1 小時。本機模型較慢時請調高。", "ui.ai_reset": "重設", + "ui.ai_save": "儲存", "ui.ai_settings": "AI 設定…", "ui.ai_show_features": "顯示 AI 功能", "ui.ai_show_features_note": "代理聊天:一個面板,由您已在使用的程式設計代理或您選擇的模型端點處理開啟的設計。關閉後:沒有 AI 按鈕、快捷鍵、選單項或面板,也不會查詢或啟動任何程式。", @@ -3922,6 +4426,8 @@ "ui.cancel": "取消", "ui.canvases": "畫布", "ui.center": "中心", + "ui.center_arc_follows_cursor": "中心點圓弧跟隨游標的方向", + "ui.center_arc_follows_cursor_tip": "中心點圓弧會依游標繞其圓心的方向,順時針或逆時針繪製。關閉時:一律從起點起逆時針繪製。", "ui.centerline": "中心線", "ui.chain": "鏈", "ui.chamfer": "倒角", @@ -3930,6 +4436,7 @@ "ui.circle": "圓", "ui.circular_pattern": "環形陣列", "ui.clear": "清除", + "ui.clear_print_face": "清除列印底面", "ui.clear_recent": "清除最近", "ui.clear_the_selection": "清除選擇", "ui.click_selects_whole_bodies": "點擊選擇整個實體", @@ -3964,12 +4471,27 @@ "ui.constant": "恆定", "ui.constraints_conflict": "拘束條件衝突", "ui.construction": "建構", + "ui.construction.angle_hint": "建構直線:按一下一點,再輸入角度或選取方向", + "ui.construction.bisector_hint": "角平分線:選取兩條相交的直線,再選取所需的解", + "ui.construction.common_hint": "公切線:選取兩個圓/圓弧,再選取所需的解", + "ui.construction.contact_hint": "切線:選取圓/圓弧或開放雲形線/圓錐曲線,再選取切點(自由曲線:端點)", + "ui.construction.external_hint": "切線:選取圓或圓弧、一個外部點,再選取所需的解", + "ui.construction.free_hint": "建構直線:按一下兩點;按右鍵可重新開始", + "ui.construction.normal_needs_length": "無限長直線一律是建構直線:輸入長度即可繪製一般直線", + "ui.construction.point_hint": "建構直線:按一下要通過的點", + "ui.construction.reference_hint": "建構直線:選取一條直線,再選取一點;按右鍵可變更參考", "ui.construction.ribbon_label": "輔助線", + "ui.construction.side_hint": "建構直線:按一下直線要延伸的那一側;按右鍵可重新開始", "ui.context_menu": "右鍵選單", + "ui.continuity_crease": "摺痕", + "ui.continuity_curvature": "曲率", + "ui.continuity_curvature_change": "曲率變化", "ui.continuity_g0": "G0 摺痕", "ui.continuity_g1": "G1 相切", "ui.continuity_g2": "G2 曲率", "ui.continuity_gap": "間隙", + "ui.continuity_position": "位置", + "ui.continuity_tangent": "相切", "ui.copy": "複製", "ui.corner": "轉角", "ui.corners": "角點", @@ -3992,6 +4514,7 @@ "ui.dark": "深色", "ui.default_modelling_orientation": "預設建模方向", "ui.delete": "刪除", + "ui.delete_select_first": "請先選取要刪除的項目:特徵、實體、元件或草圖幾何", "ui.depth": "深度", "ui.design": "設計", "ui.design_properties.author": "作者", @@ -4006,6 +4529,40 @@ "ui.design_properties.project": "專案", "ui.design_properties.revision": "修訂版本", "ui.design_saved": "已儲存至 {path}", + "ui.details_access_caption": "面會顯示刀具能否從所選方向到達。", + "ui.details_angle": "角度", + "ui.details_continuity_caption": "編輯所選的接縫。其他接縫保留各自的設定。", + "ui.details_continuity_stale": "較早的幾何:請重新執行分析,才能編輯此接縫或縮放至該處。", + "ui.details_copy_list": "複製清單", + "ui.details_curvature": "曲率公差", + "ui.details_curvature_caption": "面依其局部曲率半徑上色。", + "ui.details_direction": "刀具方向", + "ui.details_draft_caption": "面依其與拔模方向的夾角上色。", + "ui.details_edit_seam": "編輯接縫", + "ui.details_fixture": "元件樣本——僅為範例資料", + "ui.details_fixture_caption": "帶有示意數值的元件樣本;這不是模型的結果。", + "ui.details_fixture_problem": "有問題的範例發現", + "ui.details_fixture_readout": "範例測量值", + "ui.details_flip": "翻轉", + "ui.details_gap": "間隙", + "ui.details_hatch": "為切面畫上剖面線", + "ui.details_jump": "曲率跳變", + "ui.details_key": "圖例", + "ui.details_offset": "偏移", + "ui.details_plane": "平面", + "ui.details_pull": "拔模方向", + "ui.details_radius": "半徑", + "ui.details_readout": "讀值", + "ui.details_samples": "取樣數", + "ui.details_seam": "{body} · 邊 {edge}", + "ui.details_settings": "設定", + "ui.details_sharp_gap": "尖銳或間隙", + "ui.details_show_all": "顯示全部 {count} 項", + "ui.details_smooth": "平滑", + "ui.details_stripes": "條紋", + "ui.details_target": "縮放至幾何", + "ui.details_worst_seams": "最差的接縫", + "ui.details_zebra_caption": "反射的條紋顯示面接合得有多平滑。", "ui.diameter": "直徑", "ui.dimension": "尺寸", "ui.direct_interaction": "直接互動", @@ -4050,6 +4607,7 @@ "ui.edit_in_place_saved_elsewhere": "零件已儲存到另一個檔案;組合件仍連結 {name}", "ui.edit_in_place_wait": "請等待設計中正在執行的作業完成", "ui.edit_section_analysis": "編輯截面分析", + "ui.edit_sketch_empty": "沒有可編輯的草圖", "ui.ellipse": "橢圓", "ui.emboss_wrap_note": "與受支援圓柱相切的正交線輪廓會自動纏繞。選取一個壁以指定目標。", "ui.end_radius": "終點半徑", @@ -4060,12 +4618,15 @@ "ui.equation_explicit": "顯式", "ui.equation_form": "形式", "ui.equation_note": "變數為純數字:sin(t) 以弧度計算。沒有單位的結果會使用設計的單位。", + "ui.equation_note_range": "變數為長度,其範圍亦同:可與長度參數混合運算,用於 sin() 時請除以一個長度。沒有單位的結果會使用設計的單位。", "ui.equation_parametric": "參數式", + "ui.equation_variable_unit": "變數使用範圍的單位", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "等效半徑", "ui.expand": "展開", + "ui.explode_needs_two_components": "「爆炸圖」會將元件拉開,因此設計需要有兩個或更多元件(新建元件、插入設計或由實體建立元件)", "ui.exportDxf": "匯出 DXF…", "ui.export_ellipsis_keymap": "匯出…", "ui.export_keymap_tip": "將按鍵、S 框收藏和工具列匯出為檔案", @@ -4191,6 +4752,7 @@ "ui.hideOrigin": "隱藏原點", "ui.hidePlanes": "隱藏平面", "ui.hideProfile": "隱藏輪廓", + "ui.hide_component_history": "隱藏其歷程記錄", "ui.hide_origin_by_default": "預設隱藏原點", "ui.hide_origin_note": "新設計開啟時會隱藏「原點」資料夾。設計一旦顯示或隱藏過原點,就會保留自己的原點設定。", "ui.history_back": "後退一步", @@ -4198,6 +4760,7 @@ "ui.history_edge_hint": "雙擊邊", "ui.history_first": "移至開頭", "ui.history_forward": "前進一步", + "ui.history_hide_hidden": "隱藏已隱藏的元件", "ui.history_hide_names": "隱藏名稱", "ui.history_last": "移至結尾", "ui.history_marker_tip": "歷程標記:拖曳可回溯模型;新特徵會加在此處", @@ -4207,10 +4770,12 @@ "ui.history_play_button_show": "顯示播放按鈕", "ui.history_play_finish_action": "播放歷程記錄前,請先完成目前的操作", "ui.history_play_roll_back": "播放前,請先將歷程記錄標記往回移", + "ui.history_show_hidden": "顯示已隱藏的元件", "ui.history_show_names": "顯示名稱", "ui.history_sketch_listed_under": "列在 {feature} 之下", "ui.history_title": "歷程記錄", "ui.history_toggle_names": "顯示或隱藏特徵名稱", + "ui.history_waits_for_editor": "復原、重做與歷程記錄會等到特徵編輯器開啟後才可使用", "ui.hole": "孔", "ui.hole_tap_type": "攻牙類型", "ui.hole_type": "孔類型", @@ -4226,6 +4791,7 @@ "ui.insert_design.saved_file": "{name} 有未儲存的變更,因此插入的是其已儲存的檔案。請儲存後執行「更新連結」以帶入變更。", "ui.insert_design.unsaved": "未儲存的變更", "ui.inspect": "檢查", + "ui.instances": "實例數", "ui.intersect": "相交", "ui.isolate": "隔離", "ui.join": "接合", @@ -4234,12 +4800,14 @@ "ui.joints": "接頭", "ui.keyboard_shortcuts": "鍵盤快捷鍵", "ui.language": "語言", + "ui.lasso_select": "套索(拖曳出手繪的封閉圈:選取完全位於圈內的項目)", "ui.layout_compact": "精簡", "ui.layout_floating": "浮動", "ui.length": "長度", "ui.length_decimals": "長度小數位數", "ui.light": "淺色", "ui.line": "直線", + "ui.line_arc_hint": "相切圓弧:點擊圓弧的終點。再次停在最後一點上可回到直線;按一下右鍵或按 Esc 結束", "ui.link_copies": "連結相同的副本", "ui.link_copies_keep": "保留", "ui.link_copies_link": "連結", @@ -4328,6 +4896,7 @@ "ui.part_size_shared": "重建零件並取代額外新增的特徵。此元件的所有實例都會更新。", "ui.paste": "貼上", "ui.path": "路徑", + "ui.pattern_object_type_tip": "實體:實心形狀,在檢視或瀏覽器中選取;每個都會整個複製。\n特徵:歷程記錄中的步驟,例如擠出或孔,在歷程記錄中或其所建立的面上選取;該步驟會被重複。\n草圖兩者皆非:請用草圖自己的「陣列」或「鏡射」重複其曲線,或先將它擠出。", "ui.pattern_on_path": "路徑陣列", "ui.perforate_margin_default": "依直徑決定", "ui.perforate_pitch": "間距", @@ -4354,12 +4923,17 @@ "ui.plugins_skipped": "有 {count} 個資料夾無法讀取。", "ui.plugins_version": "{version}", "ui.point": "點", + "ui.point_cloud_add_filter": "新增篩選…", "ui.point_cloud_auto_range": "自動範圍", "ui.point_cloud_color_by": "顏色依據", "ui.point_cloud_file_colors": "檔案顏色", + "ui.point_cloud_filter_by": "篩選依據", "ui.point_cloud_height_high": "最高", "ui.point_cloud_height_low": "最低", + "ui.point_cloud_legend_filter": "在上方圖例中顯示與隱藏", "ui.point_cloud_no_file_colors": "檔案沒有顏色", + "ui.point_cloud_pause": "暫停", + "ui.point_cloud_play": "播放", "ui.point_cloud_single_color": "單一顏色", "ui.point_cloud_size": "點大小", "ui.point_cloud_units": "檔案單位", @@ -4368,6 +4942,11 @@ "ui.polygon": "多邊形", "ui.preferences": "偏好設定", "ui.press_a_key": "按一個鍵…", + "ui.print_face_body_not_sent": "此面的實體不會傳送:請先將其加入實體", + "ui.print_face_cleared": "{body}:已清除列印底面", + "ui.print_face_input": "列印底面", + "ui.print_face_pick": "選取實體的一個平面,將其設為列印底面", + "ui.print_face_set": "{body}:已設定列印底面;傳送到切片軟體時實體會放在此面上", "ui.profile": "輪廓", "ui.profile_plane": "輪廓平面", "ui.profiles": "輪廓", @@ -4383,6 +4962,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "正在測量…", + "ui.properties.measuring_bodies": "正在測量… 第 {done} 個,共 {total} 個實體", "ui.properties.measuring_failed": "測量在完成前已停止。", "ui.properties.principal_axis": "主軸 {number}", "ui.properties.principal_moments": "主慣性矩", @@ -4431,6 +5011,7 @@ "ui.revolve": "旋轉", "ui.ribbon_exit": "結束", "ui.ribbon_labels": "顯示功能區圖示下的文字", + "ui.ribbon_menus_skip_pinned": "下拉選單中不列出已固定的命令", "ui.ribbon_pin_footer": "固定的命令會顯示在功能區中。將指標停留在某列上即可固定或取消固定。", "ui.ribbon_workspace": "工作區", "ui.right": "右視", @@ -4449,6 +5030,7 @@ "ui.selectOther": "選擇其他…", "ui.selectTangentChain": "選擇相切鏈", "ui.select_all": "全選", + "ui.select_components_by_face": "選擇元件(點選面即選取其元件)", "ui.selection": "選擇", "ui.selection_modifiers": "選擇修飾鍵", "ui.selection_shift_add_only": "Shift+點擊僅新增、不取消選擇", @@ -4474,6 +5056,7 @@ "ui.showDimension": "顯示尺寸", "ui.showOrigin": "顯示原點", "ui.showPlanes": "顯示平面", + "ui.show_component_history": "顯示其歷程記錄", "ui.show_constraints": "拘束條件", "ui.show_construction_geometries": "建構幾何", "ui.show_dimensions": "尺寸", @@ -4490,6 +5073,11 @@ "ui.sketch_intersect_selection_filter": "選擇篩選", "ui.sketch_modifiers": "草圖修飾鍵", "ui.sketch_project_geometry": "幾何", + "ui.sketch_report.all_constrained": "全部都已完全拘束。", + "ui.sketch_report.dof": "自由度", + "ui.sketch_report.loose": "尚未完全拘束", + "ui.sketch_report.status": "狀態", + "ui.sketch_report.title": "草圖報告", "ui.sketch_scale": "草圖比例", "ui.sketches": "草圖", "ui.slice": "切片", @@ -4585,19 +5173,31 @@ "ui.view_angles": "檢視角度", "ui.view_angles_convention": "以向上軸為準的角度(單位為度)。偏航 0° 為前視圖,90° 為左視圖,−90° 為右視圖,180° 為後視圖;俯仰 90° 為俯視圖;滾轉為正值時,模型順時針轉動。", "ui.view_angles_help": "在方向控制器下方顯示檢視的俯仰、偏航與滾轉角度(單位為度)及其投影方式。按一下讀值即可輸入精確角度。", + "ui.view_angles_lock": "鎖定 {axis}", "ui.view_angles_ortho": "正交", "ui.view_angles_persp": "透視", "ui.view_angles_pitch": "俯仰", "ui.view_angles_readout": "俯仰 {pitch} · 偏航 {yaw} · 滾轉 {roll}", "ui.view_angles_roll": "滾轉", + "ui.view_angles_unlock": "解鎖 {axis}", "ui.view_angles_yaw": "偏航", + "ui.view_angles_zero": "將 {axis} 設為 0°", "ui.view_centre": "檢視中心", "ui.viewport_status_clear": "關閉 {name}", "ui.viewport_status_clear_hint": "關閉 {name} · Esc", + "ui.viewport_status_edges": "{count} 條邊", + "ui.viewport_status_from": "從 {direction}", "ui.viewport_status_key": "顯示 {name} 的圖例", "ui.viewport_status_minimum_radius": "最小半徑", "ui.viewport_status_pairs": "{count} 對", + "ui.viewport_status_section_hatch": "{setting} · 剖面線", + "ui.viewport_status_section_plane": "目前平面", + "ui.viewport_status_section_tilted": "傾斜 · {offset}", "ui.viewport_status_stripes": "{count} 道條紋", + "ui.viewport_status_summary_clear": "全部關閉", + "ui.viewport_status_summary_heading": "此檢視中", + "ui.viewport_status_summary_label": "{name} 及另外 {count} 項", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "跟隨主題", "ui.visual_shaded_hidden_edges": "含隱藏邊的著色", "ui.visual_shaded_with_edges": "含邊線的著色", @@ -4634,10 +5234,12 @@ "update.button": "更新", "update.button_version": "更新到 {version}", "update.check_automatically": "自動檢查更新", + "update.check_for_updates": "檢查更新", "update.check_now": "立即檢查", + "update.check_unavailable": "此安裝版本無法檢查更新。", "update.checking": "正在檢查…", "update.copy": "複製", - "update.dmg_opened": "磁碟映像已驗證並開啟:將 SolidCraft 拖到「應用程式」取代舊版本,然後重新啟動 SolidCraft。", + "update.dmg_opened": "磁碟映像已驗證並開啟:結束 SolidCraft,將新的 SolidCraft 拖到「應用程式」取代舊版本,然後再次開啟 SolidCraft。", "update.download": "下載", "update.download_open": "下載並開啟", "update.downloading": "正在下載並驗證… {done} / {total} MB", @@ -4648,11 +5250,13 @@ "update.installed": "SolidCraft {version} 已安裝。重新啟動後生效。", "update.installer_started": "SolidCraft 關閉後將啟動安裝程式。", "update.later": "稍後提醒", + "update.managed": "有可用更新:請在 {manager} 中更新 SolidCraft", "update.no_notes": "此版本沒有發佈說明。", "update.package_hint": "此副本來自 {kind}。下載新套件後用以下命令安裝:", "update.prefs_dev": "這是開發版本({version}),不檢查更新。", "update.prefs_flatpak": "此副本({version})由 Flatpak 更新:執行 {command} 或使用軟體中心。SolidCraft 不會自行檢查。", "update.prefs_label": "更新", + "update.prefs_managed": "目前為 SolidCraft {version},由 {manager} 管理。檢查時只向 GitHub 查詢最新版本,不傳送其他任何資料;請在 {manager} 中更新 SolidCraft。", "update.prefs_note": "目前為 SolidCraft {version}({kind})。檢查時只向 GitHub 查詢最新版本,不傳送其他任何資料。", "update.prefs_web": "重新載入頁面以取得最新的網頁應用程式。如果網路無法使用,或更新無法及時下載完成,則會改為開啟已儲存的版本;進行中的下載會繼續,供下次重新載入時使用。", "update.refresh_checking": "正在檢查最新版本…", @@ -4679,6 +5283,7 @@ "web.open_link": "開啟連結的設計?", "web.open_link_confirm": "有未儲存的變更。要在新分頁中開啟連結的設計嗎?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選擇 · Enter / Tab 自動完成 · Esc 關閉", + "↑ ↓ choose · Enter applies this value": "↑ ↓ 選擇 · Enter 套用此值", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 選擇 · Enter 照原樣套用 · Esc 關閉", "⌘Enter continues on GitHub.": "按 ⌘Enter 在 GitHub 上繼續。" } diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 0cb8afc26..e6f8a08c7 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -60,6 +60,7 @@ "BLEND SURFACE": "混合曲面", "BOUNDARY SURFACE": "边界曲面", "BROWSER": "浏览器", + "Back to the original order": "恢复原始顺序", "Ball": "球", "Bar": "扁钢", "Base Center": "底面中心", @@ -378,7 +379,7 @@ "Move Type": "移动类型", "Move down": "下移", "Move earlier": "向前移动", - "Move holes by clicking or dragging": "通过单击或拖动移动孔", + "Move holes by clicking or dragging": "通过单击或拖动移动", "Move later": "向后移动", "Move up": "上移", "Name": "名称", @@ -476,6 +477,7 @@ "Rectangular": "矩形", "Rectangular Tube": "矩形管", "Reference face": "参考面", + "Reference plane": "参考平面", "Relief Depth": "止裂槽深度", "Relief Width": "止裂槽宽度", "Remove Tools": "移除工具", @@ -493,7 +495,8 @@ "Rename Folder": "重命名文件夹", "Render Stage": "渲染阶段", "Reopen designs": "重新打开设计", - "Reopen the designs that were open when SolidCraft was last closed": "重新打开上次关闭 SolidCraft 时打开的设计", + "Reopen the designs that were open when SolidCraft was last closed": "重新打开上次打开的设计", + "Repair Part": "修复零件", "Replace existing library file": "替换现有库文件", "Report a bug — review a screenshot and open a GitHub draft": "报告缺陷 — 复核截图并开启 GitHub 草稿", "Report copied. Keep this text to submit on GitHub when you are online.": "报告已复制。请保留此文本,联网后在 GitHub 上提交。", @@ -555,6 +558,7 @@ "Section": "剖面", "Section (optional)": "截面(可选)", "Section position": "截面位置", + "Sections": "截面", "Sections (one sketch each)": "截面(每个一个草图)", "Select Other": "选择其他", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。", @@ -581,7 +585,7 @@ "Show ghost": "显示虚影", "Show in folder": "在文件夹中显示", "Show the pointer an AI agent moves (#35)": "显示 AI 代理移动的指针(#35)", - "Show tool at cursor": "在光标旁显示工具", + "Show tool at cursor": "光标处显示工具", "Signed axes": "带符号轴", "Size": "大小", "Sketch constraints": "草图约束", @@ -592,9 +596,11 @@ "Sketch points": "草图点", "Slider": "滑块", "Slot width": "槽宽", - "Snap to face and edge centres": "捕捉到面和边的中心", + "Snap to face and edge centres": "捕捉到中心", "SolidCraft cannot submit reports directly. Submit on GitHub; no token is needed in the app.": "SolidCraft 无法直接提交报告。请在 GitHub 上提交;应用中不需要令牌。", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft 在这些设计保存前已关闭。可以打开它们的上次自动保存。", + "Sort A to Z": "升序排序", + "Sort Z to A": "降序排序", "Spacing 2 must be a non-zero number": "间距 2 必须是非零数字", "Spacing must be a non-zero number": "间距必须是非零数字", "Specialise": "专用操作", @@ -733,34 +739,34 @@ "a picked edge's body is gone": "所选边所属的实体已不存在", "add a key for a joint first": "请先为接头添加关键帧", "ai.connected_toast": "SolidCraft 现已可在 {clients} 中使用。请重启它们(设置 > 助手)。", - "ai.prefs.allow_control": "允许 AI 代理连接(控制通道 / MCP)", - "ai.prefs.allow_control_note": "仅在本机开放控制通道(127.0.0.1,端口 27878 或下一个空闲端口)。连接的程序还必须出示一个每次启动时新生成、只有你的用户账户能读取的秘密令牌。下次启动 SolidCraft 时生效。关闭:除非用 --control 启动,否则不监听任何端口。", - "ai.prefs.availability": "助手控制", - "ai.prefs.background_commands": "在后台执行代理命令", - "ai.prefs.connect_apps": "让此电脑上的 AI 应用可以使用 SolidCraft", - "ai.prefs.connect_apps_note": "SolidCraft 启动时,会把自己作为 MCP 服务器添加到此电脑上找到的 AI 应用(OpenCode、Claude Desktop、Claude Code、Cursor、Codex、Gemini CLI、Copilot CLI、Windsurf、Zed、VS Code)。只添加或更新 solidcraft 条目;你修改过的条目不会被改动,文件会先备份。关闭后,会删除它添加的条目。", - "ai.prefs.connect_at_start": "SolidCraft 启动时连接上次使用的智能体", + "ai.prefs.allow_control": "允许AI代理连接", + "ai.prefs.allow_control_note": "本地通道(MCP)。任何内容都不会离开此计算机。\n\n仅在本机开放控制通道(127.0.0.1,端口 27878 或下一个空闲端口)。连接的程序还必须出示一个每次启动时新生成、只有你的用户账户能读取的秘密令牌。下次启动 SolidCraft 时生效。关闭:除非用 --control 启动,否则不监听任何端口。", + "ai.prefs.availability": "可用性", + "ai.prefs.background_commands": "在后台运行耗时命令", + "ai.prefs.connect_apps": "将SolidCraft添加到AI应用", + "ai.prefs.connect_apps_note": "关闭后会移除已添加的条目。\n\nSolidCraft 启动时,会把自己作为 MCP 服务器添加到此电脑上找到的 AI 应用(OpenCode、Claude Desktop、Claude Code、Cursor、Codex、Gemini CLI、Copilot CLI、Windsurf、Zed、VS Code)。只添加或更新 solidcraft 条目;你修改过的条目不会被改动,文件会先备份。关闭后,会删除它添加的条目。", + "ai.prefs.connect_at_start": "启动时连接上次使用的代理", "ai.prefs.connect_at_start_note": "每次启动 SolidCraft 时,在后台启动上次连接的智能体(或默认智能体),以便随时开始聊天。使用 --control 启动 SolidCraft 时不会这样做。如果无法连接,助手会显示“连接失败”和“重试”按钮。", - "ai.prefs.follow_camera": "将相机转向草图", + "ai.prefs.follow_camera": "跟随相机", "ai.prefs.follow_camera_off": "相机自动跟随已关闭。", "ai.prefs.follow_camera_on": "相机将转向代理创建的草图。", - "ai.prefs.intro": "设置代理、权限及其工作方式。", + "ai.prefs.intro": "SolidCraft中的AI代理。", "ai.prefs.make_default": "设为默认", "ai.prefs.no_agents": "尚无代理。添加代理或刷新以查找已安装的代理。", "ai.prefs.no_saved_approvals": "没有已保存的批准。", - "ai.prefs.open_at_start": "SolidCraft 启动时打开助手面板", + "ai.prefs.open_at_start": "启动时打开聊天", "ai.prefs.open_at_start_note": "每次启动 SolidCraft 时显示助手面板(或其独立窗口)。使用 --control 启动 SolidCraft 时不会这样做。", "ai.prefs.override_all_warning": "此代理可在不询问的情况下保存、覆盖、导出或替换设计。", - "ai.prefs.permission_all": "全部允许", - "ai.prefs.permission_all_summary": "可用的 SolidCraft 工具无需询问即可运行。", - "ai.prefs.permission_ask": "更改前询问", - "ai.prefs.permission_ask_summary": "每次设计更改和文件操作均需批准。", - "ai.prefs.permission_edits": "允许模型编辑", - "ai.prefs.permission_edits_summary": "模型编辑自动执行;文件及破坏性操作仍需询问。", + "ai.prefs.permission_all": "执行所有操作", + "ai.prefs.permission_all_summary": "从不询问", + "ai.prefs.permission_ask": "先询问", + "ai.prefs.permission_ask_summary": "每次更改前询问", + "ai.prefs.permission_edits": "允许编辑", + "ai.prefs.permission_edits_summary": "自由编辑,其余操作先询问", "ai.prefs.permission_scope": "仅适用于 SolidCraft 工具。代理的终端和文件编辑使用其自身权限。", "ai.prefs.pointer_preview_hidden": "指针已隐藏", "ai.prefs.pointer_preview_speed": "代理指针 · {speed}", - "ai.prefs.pointer_speed": "移动速度", + "ai.prefs.pointer_speed": "速度", "ai.prefs.privacy_note": "对话仅发送给所选代理或端点。端点密钥保存在系统钥匙串中。", "ai.prefs.show_pointer": "显示代理指针", "ai.prefs.turn_limit_hint": "助手针对一条消息可调用的设计更改工具次数上限。", @@ -785,11 +791,19 @@ "browser.edit_canvas_title": "编辑画布:{name}", "browser.edit_point_cloud_title": "编辑点云: {name}", "browser.move_title": "移动:{name}", + "browser.needs_repair": "{name}:需要修复", "browser.parameters": "参数 ({count})", "browser.precision": "精度: {precision}", "browser.sketch_attachment_lost": "{name} (附着丢失)", "browser.sketch_editing": "{name} (编辑中)", "browser.sketch_name": "草图{number}", + "browser.sketches_to_parts_already_in_part": "已在其零件中", + "browser.sketches_to_parts_design_body": "位于设计本身的实体上", + "browser.sketches_to_parts_moved": "已将 {moved} 个草图移到其所在的零件", + "browser.sketches_to_parts_no_exact_attachment": "位于没有精确附着的面上", + "browser.sketches_to_parts_not_on_face": "不在零件的面上", + "browser.sketches_to_parts_part_missing": "其零件已不存在", + "browser.sketches_to_parts_result": "已将 {moved} 个草图移到其所在的零件;{stayed} 个保留原处:{why}", "browser.units": "单位: {units}", "cam.flat": "平底", "cam.follower": "从动件", @@ -821,7 +835,10 @@ "cmd.assembly_bom": "物料清单", "cmd.assembly_bom_item_set": "更改项目编号", "cmd.assembly_bom_renumber": "重新编号项目", + "cmd.assembly_mass_properties": "质量属性", + "cmd.body.print_face": "打印底面", "cmd.body_rename": "重命名实体", + "cmd.body_repair": "修复零件", "cmd.browser_collapse_all": "全部折叠", "cmd.browser_expand_all": "全部展开", "cmd.browser_group": "新建组", @@ -849,6 +866,7 @@ "cmd.component_extract": "提取到文件", "cmd.component_finish_edit": "完成编辑", "cmd.component_from_bodies": "由实体创建组件", + "cmd.component_hide_history": "隐藏组件历史记录", "cmd.component_insert_design": "插入设计", "cmd.component_links": "列出链接", "cmd.component_list": "列出组件", @@ -857,6 +875,7 @@ "cmd.component_move_bodies": "将实体移至组件", "cmd.component_move_features": "将特征移至组件", "cmd.component_move_sketches": "将草图移至组件", + "cmd.component_move_sketches_to_parts": "将草图移到各自的零件", "cmd.component_paste_from_design": "从其他设计粘贴", "cmd.component_paste_new": "粘贴为新对象", "cmd.component_properties": "组件物理属性", @@ -864,6 +883,7 @@ "cmd.component_rename": "重命名组件", "cmd.component_replace_with_link": "替换为链接", "cmd.component_revert_position": "恢复位置", + "cmd.component_show_history": "显示组件历史记录", "cmd.component_unlock": "解锁内容", "cmd.component_update_links": "更新链接", "cmd.config_activate": "激活配置", @@ -874,6 +894,7 @@ "cmd.config_rule": "配置规则", "cmd.config_rules": "配置规则", "cmd.config_table": "显示配置表", + "cmd.construct.plane.axis_point": "通过轴和点的平面", "cmd.construct_axis_edge": "过边的轴", "cmd.construct_axis_normal_to_face": "垂直于面的轴", "cmd.construct_axis_through_cylinder": "过圆柱/圆锥/圆环的轴", @@ -902,6 +923,8 @@ "cmd.diagnostics_crash_reports": "崩溃报告", "cmd.diagnostics_crash_reports_clear": "删除崩溃报告", "cmd.diagnostics_crash_test": "崩溃测试", + "cmd.diagnostics_profile": "性能分析", + "cmd.diagnostics_validation": "验证", "cmd.doc_recover": "恢复设计", "cmd.doc_recovery_discard": "丢弃已恢复的设计", "cmd.doc_recovery_list": "可恢复的设计", @@ -952,6 +975,11 @@ "cmd.explode_show": "显示爆炸图", "cmd.expr_evaluate": "计算表达式", "cmd.face_delete": "删除面", + "cmd.file.export_3mf": "导出 3MF", + "cmd.file.export_obj": "导出 OBJ", + "cmd.file.export_step": "导出 STEP", + "cmd.file.export_stl": "导出 STL", + "cmd.file.export_urdf": "导出 URDF", "cmd.file_export": "导出", "cmd.file_insert_mesh": "插入网格", "cmd.file_insert_step": "插入 STEP", @@ -964,11 +992,13 @@ "cmd.frame_profile_list": "型材库", "cmd.frame_profile_properties": "型材属性", "cmd.inspect_accessibility": "可达性分析", + "cmd.inspect_analysis": "视图分析", "cmd.inspect_center_of_mass": "质心", "cmd.inspect_clearance": "间隙", "cmd.inspect_colored_components": "启用组件颜色", "cmd.inspect_colored_components_disable": "禁用组件颜色", "cmd.inspect_compare": "比较实体", + "cmd.inspect_compare_picture": "比较参考图", "cmd.inspect_continuity": "连续性分析", "cmd.inspect_curvature_comb": "曲率梳分析", "cmd.inspect_curvature_map": "曲率图分析", @@ -986,6 +1016,7 @@ "cmd.joint_delete": "删除接头", "cmd.joint_drive": "驱动接头", "cmd.joint_edit": "编辑接头", + "cmd.joint_find_limits": "查找接头限制", "cmd.joint_gear": "齿轮", "cmd.joint_inspect": "检查接头", "cmd.joint_limits": "接头限制", @@ -998,6 +1029,11 @@ "cmd.joint_screw": "螺旋", "cmd.joint_solve": "解算接头", "cmd.joint_sweep": "扫掠接头", + "cmd.layout.apply": "应用布局", + "cmd.layout.get": "检查布局", + "cmd.layout.reset": "重置布局", + "cmd.layout.save": "保存布局", + "cmd.layout.workspace.select": "选择布局工作区", "cmd.library_apply": "应用本地库条目", "cmd.library_export": "导出设计库", "cmd.library_inspect": "检查本地库", @@ -1032,6 +1068,21 @@ "cmd.occurrence_move": "移动实例", "cmd.occurrence_properties": "实例物理属性", "cmd.occurrence_reparent": "移动到组件", + "cmd.panel.activate": "激活面板选项卡", + "cmd.panel.close": "关闭面板", + "cmd.panel.collapse": "折叠面板分区", + "cmd.panel.dismiss": "关闭面板临时预览", + "cmd.panel.float": "浮动面板", + "cmd.panel.focus": "聚焦面板", + "cmd.panel.list": "列出面板", + "cmd.panel.move": "移动面板", + "cmd.panel.native_close": "重新停靠独立窗口中的面板分区", + "cmd.panel.open": "打开面板", + "cmd.panel.peek": "临时预览折叠面板", + "cmd.panel.popout": "将面板移至独立窗口", + "cmd.panel.reset_pair": "重置面板分隔条", + "cmd.panel.resize": "调整面板分区大小", + "cmd.panel.resize_pair": "移动面板分隔条", "cmd.parameters_add": "添加用户参数", "cmd.parameters_change": "更改参数", "cmd.parameters_comment": "注释参数", @@ -1060,6 +1111,9 @@ "cmd.pointcloud_edit": "编辑点云", "cmd.pointcloud_insert": "插入点云", "cmd.pointcloud_list": "点云", + "cmd.render.compare.divider": "移动渲染比较分隔线", + "cmd.render.result.discard": "丢弃渲染结果", + "cmd.render.result.select": "选择渲染结果", "cmd.render_aging_describe": "分层表面老化", "cmd.render_backends": "渲染后端", "cmd.render_batch": "渲染所有镜头", @@ -1223,6 +1277,7 @@ "cmd.sketch_spline_control_point_5": "控制点样条曲线(5 次)", "cmd.sketch_spline_fit_point": "拟合点样条曲线", "cmd.sketch_spline_insert_point": "添加样条曲线点", + "cmd.sketch_spline_remove_point": "删除样条曲线点", "cmd.sketch_spline_reverse": "反向样条曲线方向", "cmd.sketch_spun_profile": "旋转轮廓", "cmd.sketch_toggle_diameter": "切换半径 / 直径", @@ -1273,9 +1328,11 @@ "cmd.timeline_rollback": "移动时间线标记", "cmd.timeline_stop": "停止历史播放", "cmd.timeline_suppress": "抑制特征", + "cmd.ui.assistant": "切换助手显示", "cmd.view.render_browser": "渲染浏览器", "cmd.view.render_dock": "移动渲染停靠面板", "cmd.view.render_focus": "渲染专注视图", + "cmd.view.status_details": "视口状态详情", "cmd.view.status_items": "视口状态项", "cmd.view_ambient_occlusion": "环境光遮蔽", "cmd.view_angle_readout": "视图角度", @@ -1306,17 +1363,28 @@ "cmd.view_tool": "导航工具", "cmd.view_top": "俯视图", "cmd.view_visual_style": "视觉样式", + "color.blue": "蓝色", "color.copy": "单击复制颜色值", "color.edit": "单击编辑颜色", "color.gamma": "以 0–255 伽马空间显示颜色值", + "color.green": "绿色", "color.hex": "Hex", "color.hex_help": "输入 #rrggbb 或 #rrggbbaa;六位数保留不透明度", "color.hex_hint": "#rrggbb", "color.hue": "色相", "color.linear": "以 0–1 线性空间显示颜色值", + "color.recent": "最近使用的颜色", + "color.recent_help": "在任意颜色字段中选择的颜色会显示在这里", + "color.red": "红色", + "color.saturation": "饱和度(百分比)", "color.saturation_value": "饱和度和明度", "color.selected": "所选颜色", + "color.step_down": "减少一步", + "color.step_up": "增加一步", + "color.value": "明度(百分比)", "config.column_filter_empty": "没有匹配的列", + "config.rule_parameter_columns": "此处仅列出在表中有列的参数。使用“添加列”(+) 添加一列,即可在此使用该参数。", + "config.rule_suppression_columns": "此处仅列出在表中有“抑制”列的特征。使用“添加列”(+) 添加一列,即可在此控制该特征。", "contact.components_count": "{count} 个组件", "contact.enabled_label": "已启用", "coupling.gear_1": "齿轮 1", @@ -1351,6 +1419,7 @@ "crash.unclean_explanation": "在后续启动时检测到;未记录确切的退出时间。系统关机或强制停止也可能导致会话未正常结束。", "delete.and_more": "…以及另外 {count} 项", "diagnostic.empty_boolean_component": "组件 '{component}' 中没有可供切除或求交的实体;工具可能与组件 '{other}' 中的 '{body}' 重叠 — 请激活该组件或选择该实体作为目标", + "diagnostic.reselect_reference": "{feature}:引用 `{reference}` 已不再是选择时的样子;请重新选择", "dialog.bodies_count": "{count} 个实体", "dialog.clearance_invalid": "间隙必须是 0 或更大的长度", "dialog.compute": "计算", @@ -1360,11 +1429,20 @@ "dialog.custom_axis": "↖ 自定义轴", "dialog.dimension_insert_hint": "单击其他驱动尺寸以插入其名称", "dialog.dimension_name": "尺寸:{name}", + "dialog.dimension_step_down": "减少 {step}", + "dialog.dimension_step_expression": "只有数字可以增减;表达式保持不变", + "dialog.dimension_step_up": "增加 {step}", "dialog.edit_title": "编辑 {title}", "dialog.no_shown_body": "没有可更改的显示实体:请显示一个实体,或选择新建实体", + "dialog.pattern_sketch_not_object": "请选择实体或特征:草图两者都不是。请用草图自身的阵列或镜像重复其曲线,或先将其拉伸。", "dialog.select": "↖ 选择", "dialog.selected_count": "↖ 已选择 {count} 个", + "dialog.selection_constraint": "约束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲线 {id}", + "dialog.selection_external_point": "{point} · {sketch}", "dialog.selection_guidance": "选择输入项进行修改。点击已选对象可取消选择;按住 Ctrl/Cmd 点击也可切换选择。检查预览后,再按“确定”。", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · 轮廓 {number}", "dialog.selection_step": "第 {step} 步,共 {total} 步:选择{input}", "dialog.step": "步骤", "document.changed_on_disk": "{name} 已在磁盘上更改", @@ -1379,6 +1457,7 @@ "document.read_only_save": "此设计以只读方式打开:请另存为新文件", "document.save_changes": "保存对 {name} 的更改?", "document.save_copy": "保存副本…", + "document.tab_unsaved_changes": "未保存的更改", "document.unsaved_changes": "{name} 有未保存的更改。如果不保存,将丢失这些更改。", "drive.rigid": "{joint} 是刚性接头:它把零件固定在原位,因此没有可驱动的运动。要让零件运动,请在“编辑接头”中更改其类型:旋转用 Revolute,滑动用 Slider,两者兼有用 Cylindrical。", "drive.stopped_by_contact": "停在 {value}:{a} 会穿过 {b}", @@ -1411,6 +1490,14 @@ "file_load.reading_percent": "正在读取文件... {percent}%", "file_load.rebuilding": "正在重建特征 {done}/{total}", "file_load.recovering": "正在恢复设计", + "file_load.step_build": "正在构建模型", + "file_load.step_feature": "特征 {done}/{total}", + "file_load.step_part": "零件 {done}/{total}", + "file_load.step_percent": "{percent}%", + "file_load.step_read": "正在读取文件", + "file_load.step_rebuild": "正在重建特征", + "file_load.step_repair": "正在检查和修复零件", + "file_load.step_show": "正在准备视图", "file_load.stopping": "正在等待上一次操作停止...", "file_load.updating_links": "正在更新链接", "file_load.waiting": "正在等待文件操作", @@ -1419,21 +1506,189 @@ "from the rule": "来自规则", "help.apache": "Apache 许可证 2.0", "help.appearance.assign": "为所选的实体、面或组件设置颜色或材质外观,不改变其重量。用于区分零件或预览表面效果。", + "help.assembly.bom": "按零件号列出设计或组件的零件及其数量,并可将清单保存为 CSV 或 JSON。用作采购和装配的物料清单。", "help.attributions": "署名信息 (ATTRIBUTION.md)", "help.build": "版本 {version} · 提交 {commit} · 构建日期 {date}", + "help.canvas.decal": "像贴纸一样将图像放到模型的平面上。用于在零件上显示标签、标志或印刷图案。", + "help.canvas.edit": "修改画布:位置、大小、角度、不透明度、镜像、可见性或名称。用于将参考图像与在其上描绘的草图对齐。", + "help.canvas.insert": "将 PNG 或 JPEG 图像作为半透明参考放在平面或面上。用于按已知尺寸缩放图像后,在草图中描绘照片或图纸。", + "help.component.break_link": "断开链接组件与其设计文件的关联,保留其实体不变。用于零件不再需要跟随原文件修改时。", + "help.component.capture_position": "将手动移动过的零件的位置确定为其新位置。用于拖动未被接头约束的零件到位之后。", + "help.component.create": "向设计添加一个新的空组件,除非另选父级,否则放在当前激活的组件中。用于为装配中的新零件提供存放实体和草图的位置。", "help.component.finish_edit": "保存正在原位编辑的零件,返回其装配体,并用该零件更新装配体。对链接零件的更改完成后使用。", + "help.component.from_bodies": "将每个选中的实体变成一个独立的组件,并以实体名称命名。用于把由零散实体构成的设计变成可用接头连接和移动零件的装配。", + "help.component.insert_design": "将另一个已保存的设计作为链接到其文件的组件插入,其实体保持在原设计中的位置。用于在装配中复用零件,并通过“更新链接”获取之后的修改。", + "help.component.properties": "根据各实体的材料,显示组件的体积、质量、质心和转动惯量。用于检查装配体的重量和平衡。", + "help.component.revert_position": "将手动移动过的零件放回原位,放弃尚未捕获的移动。用于撤销装配中的试移动。", + "help.component.update_links": "重新读取链接的设计文件,并替换已更改的实体。用于编辑了此装配所使用的零件之后。", + "help.config.configure": "将参数、特征、材料或外观添加为配置表的列。用于创建同一设计的变体,例如零件的不同尺寸。", + "help.config.preview": "检查配置表的某一行能否重新生成,不改变设计及其历史。用于切换到没有把握的变体之前。", + "help.config.rules": "显示配置表的规则、各行以及当前生效的行。用于了解设计的变体是如何设置的。", + "help.config.table": "显示配置表:每个变体一行,每个参数或特征一列,并指出设计是否仍与当前生效的行一致。用于检查设计的各个变体。", "help.connect_note": "请重启各个助手以加载 SolidCraft 服务器。每个被修改的文件都已备份为 .bak。", "help.connect_title": "连接 AI 助手", + "help.construct.axis.edge": "沿直边或草图线创建构造轴。用作旋转、圆周阵列或接头的轴。", + "help.construct.axis.normal_to_face": "创建一条过某点、垂直于面的构造轴。用作从表面笔直伸出的轴。", + "help.construct.axis.through_cylinder": "通过圆柱、圆锥或圆环面的中心,或圆形边的中心创建构造轴。用于绕圆形零件旋转或阵列特征。", + "help.construct.axis.two_planes": "在两个平面或平整面相交处创建构造轴。用于所需的轴正是两个面之间的交线时。", + "help.construct.axis.two_points": "通过两个点、顶点或草图点创建构造轴。用于连接两个已知位置的轴。", + "help.construct.plane.along_path": "在边或曲线上的指定位置创建垂直于它的构造平面。用于为扫掠绘制轮廓,或绘制路径的截面。", + "help.construct.plane.at_angle": "创建一个由平面或面绕轴或边旋转一定角度而成的构造平面。用于倾斜的草图,例如斜支架。", + "help.construct.plane.axis_point": "创建包含一条轴和一个轴外点的构造平面。先选择原点轴、构造轴、直边或草图直线,再选择顶点、草图点或构造点。轴上的点无法确定唯一的平面。", + "help.construct.plane.midplane": "在两个平面或平整面的正中间创建构造平面;若二者成角相交,则取其角平分面。用作镜像的对称面。", + "help.construct.plane.offset": "创建与平面或平整面平行的构造平面,按距离或过某点确定。用于在面上方指定高度处绘制草图。", + "help.construct.plane.perpendicular": "创建一个包含某直线或边、并垂直于某平面或面的构造平面。用于沿边在模型上垂直地绘制草图。", + "help.construct.plane.tangent": "创建在某点与圆柱、圆锥、球或圆环相切的构造平面。用于在圆形零件的侧面绘制草图。", + "help.construct.plane.three_points": "通过三个点创建构造平面。用于由模型上的位置(如三个角)确定的平面。", + "help.construct.plane.two_edges": "通过位于同一平面内的两条直边或直线创建构造平面。用于穿过零件的平面,例如通过两条相对的边。", + "help.construct.point.along_path": "在边或曲线上的指定位置创建构造点。用作路径中途的参考。", + "help.construct.point.center": "在圆形边、草图圆或圆弧、球或圆环的中心创建构造点。用作孔、轴和接头的参考。", + "help.construct.point.edge_plane": "在边或直线穿过平面或平整面处创建构造点。用于标出路径与平面相交的位置。", + "help.construct.point.three_planes": "在三个平面或平整面相交处创建构造点。即使模型上没有顶点,也可用作角点参考。", + "help.construct.point.two_edges": "在两条边或直线相交处(或相距最近处)创建构造点。用作虚拟角点处的参考。", + "help.construct.point.vertex": "在顶点或草图点上创建构造点。用作参考,即使周围的草图或实体被隐藏也会保留。", + "help.contact.check": "列出接触集中在当前位置相互穿透的零件对。用于在驱动接头或运行运动研究之前查找碰撞。", + "help.contact.create": "将两个或更多零件组成一个接触集,在接头运动时其实体不会相互穿透。用于接触时应停止的零件,例如抵住限位块的杠杆。", + "help.contact.disable_all": "关闭接触,驱动接头和运动研究在零件接触处不再停止。用于重新自由移动零件,或让大型装配保持流畅。", + "help.contact.edit": "修改接触集:其包含的零件、名称或是否抑制;也可以删除该接触集。用于调整哪些零件不得相互穿透。", + "help.contact.enable_all": "将装配中的所有零件放入同一个接触集,使接头运动时任何两个零件都不会相互穿透。用于快速检查整个机构。", + "help.contact.enable_sets": "为已定义的接触集开启接触,驱动接头和运动研究会在其零件即将相互穿透处停止。用于在关闭接触后恢复这些接触集。", + "help.contact.list": "列出设计中的接触集、每个接触集包含的零件以及接触是否开启。用于在驱动装配之前检查接触设置。", + "help.document.inspect": "显示设计的概览:组件、实体、草图、特征和参数。用于了解不是自己创建的设计。", + "help.document.units": "更改设计显示长度所用的单位,如 mm 或英寸。几何大小不变,只有显示和纯数字随之改变。", + "help.edit.checkpoint": "记住设计、当前草图和撤销历史的现状。用于尝试有风险的操作之前,以便日后可以回退。", + "help.edit.restore_checkpoint": "回到某个检查点,撤销历史一并还原。用于一步丢弃检查点之后的所有操作。", + "help.explode.create": "创建爆炸图,将零件从装配中心向外推开,或按设定的位移移动。用于在说明书或演示中展示装配的组装方式。", "help.face.delete": "删除所选的面,并由相邻的面封闭留下的缺口,也可以让缺口保持开放、成为曲面。用于去掉碍事的圆角、孔或凸台。", + "help.file.insert_mesh": "将 3MF、STL、OBJ、PLY 或 glTF 文件作为新组件中的网格实体添加到设计中。用于把下载或扫描得到的模型作为参考放在设计旁边。", + "help.file.insert_step": "将 STEP、IGES、FreeCAD 或 Rhino 文件作为新组件中的实体添加到设计中;装配中的零件会成为嵌套组件。用于导入供应商或其他 CAD 程序的模型。", + "help.file.save_mesh": "将实体保存为 STL、3MF 或 OBJ 网格,曲面的平滑程度可选。用于为 3D 打印或读取网格的程序准备零件。", + "help.file.send_to_slicer": "将选中的实体保存为 3MF 文件,并在所选的切片软件中打开。用于一步从模型进入打印。", "help.font_details": "界面使用 egui 的内置字体(Ubuntu Light 和 Hack,采用 Ubuntu Font Licence 和 MIT/Bitstream Vera 许可证;Noto Emoji 和表情图标字体,采用 OFL 和 MIT 许可证)。草图文本使用 Liberation Sans(SIL OFL 1.1)。The Crafting Apps 的可选字体包 craft-fonts(BIZ UDPGothic、Shippori Mincho、BIZ UDMincho、Noto Sans CJK SC、Noto Sans Arabic;SIL OFL 1.1)未随 SolidCraft 构建版本捆绑提供。", "help.fonts": "字体", + "help.frame.member": "沿框架草图的线放置型材(如管材或铝型材),每条线一根构件。用于构建框架、货架和焊接结构。", + "help.inspect.accessibility": "给刀具从某一方向能够到达和无法到达的面着色。用于检查零件从该方向加工或成型是否可行。", + "help.inspect.center_of_mass": "在均匀密度下显示各实体单独以及整体的质心。用于检查平衡和零件的倾倒位置。", + "help.inspect.colored_components": "给每个组件一种临时颜色,不改变外观。用于一眼分辨装配体的各个零件。", + "help.inspect.compare": "比较两个实体,显示其中一个有而另一个没有材料的位置,并给出体积和偏差。用于对照原件检查修改过或导入的零件。", + "help.inspect.continuity": "检查各面沿边相接的平滑程度:间隙、折角或曲率跳变,并给接缝着色。用于找出曲面衔接不干净的地方。", + "help.inspect.curvature_comb": "沿曲线、边或面绘制梳状线,梳齿显示弯曲的强弱。用于发现平坦处、折角和曲率不均。", + "help.inspect.curvature_map": "按弯曲程度给面着色,半径小的地方为红色。用于找出急弯处并判断曲面是否光滑。", + "help.inspect.draft": "按各面相对拔模方向的拔模角着色,标出角度不足的面。用于注塑或铸造前检查零件。", + "help.inspect.environment_map": "以反光的镜面效果显示模型。用于根据反射的走向判断曲面的流畅程度。", + "help.inspect.interference": "找出相互重叠的实体,并显示每处重叠及其体积。用于检查装配体中是否有零件发生碰撞。", + "help.inspect.isocurve": "绘制面的等参线,即曲面所依据的网格。用于查看曲面的走向以及线条密集之处。", + "help.inspect.measure": "测量所选对象之间的长度、距离、角度、面积和半径,或实体的体积和质量。用于检查尺寸和间隙。", + "help.inspect.minimum_radius": "找出曲线、边或面的最小曲率半径及其位置。用于检查刀具或喷嘴能否沿形状走刀。", + "help.inspect.section": "沿平面剖开视图并为截面填充剖面线,不改变模型。用于查看零件和装配体的内部。", + "help.inspect.zebra": "在模型的面上显示反射的黑白条纹。用于判断光顺程度:条纹在边处断开或折弯,说明过渡不好。", + "help.joint.as_built": "在两个零件当前所在位置将其连接,不移动任何一个,并设定它们仍可如何运动。用于已放置在最终位置的零件。", + "help.joint.cam": "将旋转的凸轮与从动件关联,使从动件随凸轮轮廓滑动或摆动。用于凸轮、偏心机构和气门传动。", + "help.joint.create": "在所选的接头原点处连接两个零件,并把第二个零件移到位;接头类型决定它们仍可如何运动。用于构建零件像真实机构一样运动的装配。", + "help.joint.drive": "在限制范围内设定接头的角度或距离,并带动零件移动;关联的接头和闭环随之运动。用于检查机构是否按预期运动。", + "help.joint.gear": "以齿轮传动比关联两个旋转接头,驱动其中一个时另一个随之转动。用于直齿轮和内齿轮,传动比由节圆半径或齿数确定。", + "help.joint.limits": "以最小值和最大值设定接头可转动或滑动的范围,或清除这些限制。用于使铰链、滑块或杠杆保持在其实际行程内。", + "help.joint.motion_link": "以比例和偏移关联两个接头,驱动其中一个时另一个随之运动。用于“齿轮”“齿轮齿条”或“螺旋”无法表达的接头运动关系。", + "help.joint.origin": "在零件上放置一个命名的接头原点:位于面或圆形端部的中心、边的中点、角点或某一点。用于预先确定接头的连接位置;在面上选取的原点会在零件尺寸改变时跟随该面。", + "help.joint.rack_pinion": "将旋转的小齿轮与滑动的齿条关联,齿条移动的距离等于小齿轮节圆滚过的弧长。用于齿轮齿条传动、转向机构和直线平台。", + "help.joint.reach": "通过在限制范围内改变链上的接头,将零件上的某一点移向目标。用于按末端应到达的位置摆放机构,例如机械臂的末端。", + "help.joint.rigid_group": "将选中的零件按当前位置锁定在一起,使其作为一个整体运动。用于彼此之间没有相对运动的成组零件。", + "help.joint.screw": "以螺距关联转动与滑动,每转一圈前进相应距离。用于丝杠、螺栓和螺纹轴。", + "help.layout.apply": "将保存的布局应用到当前工作区。保留的编辑器会继续保留其草稿。", + "help.layout.get": "读取已提交的布局并查看已注册的工作区。", + "help.layout.reset": "恢复当前工作区注册的默认布局。用户预设仍会保留。", + "help.layout.save": "为完整布局命名并保存。替换用户预设需要明确允许覆盖。", + "help.layout.workspace.select": "选择已注册的布局工作区,并记住离开前的布局。", + "help.library.apply": "将本地库文件中的材料或外观应用到实体、面或组件。用于重复使用在其他设计中保存的材料。", + "help.library.export": "将设计的材料和外观保存到库文件。用于共享,或在其他设计中重复使用。", + "help.library.inspect": "检查库文件并列出其中的材料和外观,不改变设计。用于在应用之前查看库里有什么。", "help.licences": "许可证", "help.material.assign": "设置所选实体的材料,例如钢、铝或 ABS。用于让质量和重量与实际零件一致。", + "help.material.properties.validate": "检查材料数据卡的数值是否一致、有无缺失。用于在依赖这些数据计算质量或刚度之前。", + "help.mesh.convert": "将网格实体(如 STL)重建为带平面和圆柱面的可编辑实体。用于像修改建模实体那样修改导入的机械零件。", "help.mit": "MIT 许可证", + "help.motion.study": "在时间轴的各个步骤设定接头值,并以动画方式回放。用于观察机构完成一系列动作,并检查过程中的间隙。", + "help.motion.trace": "求出运动研究播放或驱动接头时零件上某一点经过的轨迹,确认后保留为三维草图曲线。用于查看机构的可达范围,或在该轨迹基础上建模。", "help.notice": "NOTICE", + "help.occurrence.ground": "将零件固定在原位,或重新解除固定,接头会围绕它移动其他零件。用于装配中其余零件所依托的框架或底座。", "help.occurrence.move": "仅沿关节允许的自由度移动装配零部件。选中零部件的面后,拖动可用的箭头或圆弧。", + "help.panel.activate": "选择已打开的面板选项卡,而不请求键盘焦点。", + "help.panel.close": "通过内容生命周期检查后关闭面板。其位置会被记住。", + "help.panel.collapse": "折叠或展开面板分区,同时保留所需尺寸。", + "help.panel.dismiss": "关闭折叠面板的临时视图。", + "help.panel.float": "将面板移至位置明确指定的浮动分区。", + "help.panel.focus": "聚焦面板,必要时重新打开其保留状态并展开分区。", + "help.panel.list": "读取已注册的面板种类、已提交的实例、活动选项卡、可用状态和宿主能力。", + "help.panel.move": "将面板移至新分区,或加入现有的选项卡组。", + "help.panel.native_close": "将独立窗口中的面板分区返回记住的停靠位置,而不取消其内容。", + "help.panel.open": "使用明确的实例标识打开指定种类的面板。新实例需要指定位置。", + "help.panel.peek": "临时显示折叠的面板,而不更改保存的尺寸或折叠状态。", + "help.panel.popout": "支持时将面板移至独立窗口。浏览器宿主会使用浮动分区。", + "help.panel.reset_pair": "在共同约束内恢复相邻停靠分区对的默认尺寸比例。", + "help.panel.resize": "在所有选项卡的约束内设置面板分区的外部宽度和高度。", + "help.panel.resize_pair": "同时调整相邻停靠分区的尺寸,并保持其共同总长度。", "help.parameters.change": "打开驱动设计尺寸的命名数值和表达式表。用于在一处修改尺寸,让所有引用它的特征随之更新。", + "help.parameters.export": "将设计的参数保存为 CSV 或 JSON。用于在电子表格中编辑,或转移到其他设计。", + "help.parameters.graph": "显示哪些参数和特征使用了哪些其他参数和特征,以及其中的循环或错误。用于了解改动某个参数会影响什么。", + "help.parameters.import": "将 CSV 或 JSON 中的参数读入设计,要么全部读入,要么一个也不读。用于从电子表格或其他设计带入数值。", + "help.parameters.move": "将某个用户参数移到列表中另一个参数之前或之后。用于把相关参数放在一起。", + "help.parts.fastener": "按所选尺寸添加标准螺钉、螺栓、螺母、垫圈、销或轴承。放在孔上时会通过接头安装在孔中,无需自己建模紧固件。", + "help.parts.insert": "按所选类别、尺寸和长度插入标准零件。放在孔的边缘或孔壁上时,会通过刚性接头安装在孔上。", + "help.parts.library": "打开标准零件:标准尺寸的螺钉、螺栓、螺母、垫圈、紧定螺钉、定位销和轴承。用于直接添加标准件,而无需自己建模。", + "help.parts.resize": "修改已插入标准零件的尺寸或长度并重建;其接头保持安装位置不变。用于螺钉过长或孔需要其他尺寸时。", + "help.plastic.assign_rule": "将塑料规则指定给实体,使其塑料特征默认采用该规则的拔模和间隙。用于一次设置好注塑件的所有特征。", + "help.plastic.boss": "在面上添加螺钉凸台:带可选孔、拔模、根部圆角和加强筋的立柱。用于注塑或打印外壳中的螺钉位。", + "help.plastic.lip": "沿抽壳实体的边缘添加凸缘或与之配合的凹槽。用于让外壳的两半相互定位并紧密闭合。", + "help.plastic.manage_rules": "创建和编辑塑料规则:材料、壁厚、半径、间隙和拔模。用于保持注塑件各特征一致。", + "help.plastic.rest": "在面上添加垫块:圆形或矩形的凸垫,可实心或空心,带拔模。用作注塑外壳中的支撑或定位柱。", + "help.plastic.snap_fit": "在面上添加卡扣钩,可设置其长度、厚度和卡爪。用于不用螺钉将零件卡在一起。", "help.pointcloud.insert": "将 PLY、XYZ 或 PTS 扫描作为点云插入到模型旁。根据测量数据建模时,可将其用作参考。", + "help.sheet.convert": "将厚度均匀的板或抽壳实体转换为钣金实体,在所选的边处折弯。用于让现有零件可以展开。", + "help.sheet.export_bend_table": "将钣金实体的折弯表保存为 CSV 或 JSON:角度、半径以及展开图中的折弯位置。用于折弯机或车间。", + "help.sheet.export_dxf": "将展开图保存为 DXF,包含轮廓、折弯线和可选的折弯注释。用于激光、等离子或水刀切割。", + "help.sheet.flange": "添加法兰:由草图生成的基板、沿开放草图轮廓的壁,或在钣金边上折弯的壁。用于构建钣金零件。", + "help.sheet.flat_pattern": "创建钣金实体的展开图,含尺寸、切口和折弯线。用于在切割前检查坯料。", + "help.sheet.fold": "沿草图线按指定角度和半径折弯钣金。用于在平板上切好特征之后将其折叠。", + "help.sheet.hem": "将钣金边缘折回贴合自身。用于获得安全、坚固且没有锐利毛刺的边缘。", + "help.sheet.manage_rules": "创建和编辑钣金规则:厚度、折弯半径、K 因子、释放槽和间隙。用于匹配车间的材料和工具。", + "help.sheet.path_flange": "沿钣金边按开放的草图线链添加一串法兰。用于一步生成 U 形或 Z 形等型材。", + "help.sheet.perforate": "在整块展开的钣金上添加孔阵,排列为交错或方格。用于通风口、格栅和减重面板。", + "help.sheet.refold": "将展开的钣金实体重新折回。用于在展开的钣金上添加特征之后。", + "help.sheet.unfold": "展开钣金实体的所有折弯。用于添加需要跨越折弯的孔或切口,之后再重新折弯。", + "help.sketch.arc.center_point": "在圆心周围绘制一段圆弧,从起点到终点。适用于圆心已知的情况,例如孔周围或转轴周围的半径。", + "help.sketch.arc.tangent": "从直线或圆弧的端点出发,绘制与其相切的圆弧。用于以平滑的弯曲而不是尖角延续链条。", + "help.sketch.arc.three_point": "绘制从起点经过第三个点到终点的圆弧。适用于圆弧必须经过给定的点、而不是围绕已知圆心的情况。", + "help.sketch.arc3d": "开启3D 草图后,通过三点在空间中绘制精确的圆弧。用于离开草图平面的路径和导轨中的弯曲。", + "help.sketch.auto_constrain": "添加草图已近乎满足的约束,例如水平、平行或重合,然后标注尺寸直到完全定义。用于一步锁定画得比较随意的草图。", + "help.sketch.auto_constrain_from_datum": "与自动约束类似,但位置是从你选取的基准点而不是原点开始测量。适用于以某个参考点(如角点或孔)布置零件的情况。", + "help.sketch.blend_curve": "用与两条曲线都相切的平滑样条曲线连接两者的端点,也可选择曲率连续。用于无折痕地桥接曲线之间的间隙。", + "help.sketch.break": "在其他曲线与其相交处,或在你放置的点处,把曲线拆分成若干段。适用于曲线的某一段需要单独约束或单独删除的情况。", + "help.sketch.cancel": "离开草图,并放弃自创建或开始编辑以来的所有更改。撤销可恢复这些更改。", + "help.sketch.centerline": "在普通直线与中心线之间切换,中心线是轮廓中不包含的轴线。把中心线用作旋转、镜像或对称约束的轴。", + "help.sketch.chamfer.distance_angle": "按沿第一条直线的距离和一个角度,对两条直线之间的拐角倒角。适用于图纸以长度加角度给出倒角的情况,例如 2 mm × 30°。", + "help.sketch.chamfer.equal_distance": "沿两条直线向后退相同距离,对它们之间的拐角倒角。用于轮廓上常见的 45° 倒角。", + "help.sketch.chamfer.two_distance": "按沿每条直线各自的距离,对两条直线之间的拐角倒角。用于以两个长度给出的非 45° 倒角。", + "help.sketch.circle.center": "根据圆心和直径绘制圆。用于圆心已知的孔、凸台和其他圆形特征。", + "help.sketch.circle.three_point": "绘制经过三个点的圆。适用于圆必须经过给定点的情况,例如已有几何体上的点。", + "help.sketch.circle.three_tangent": "绘制与三条直线、圆或圆弧都相切的圆。用于在三条曲线之间放入一个圆,例如三角形的内切圆。", + "help.sketch.circle.two_point": "根据直径的两个端点绘制圆。适用于已知圆周上的点而非圆心的情况。", + "help.sketch.circle.two_tangent": "绘制指定大小、与两条直线、圆或圆弧相切的圆。用于在两条曲线之间做固定半径的圆角过渡。", + "help.sketch.conic": "在两个端点之间绘制圆锥曲线,形状由顶点和 rho 值决定。用于需要调节饱满度的平滑过渡,从平缓到接近尖角都可以。", + "help.sketch.constrainer": "应用所选的一两条曲线已近乎满足的约束,例如水平、平行、相切或相等。用于逐个关系地整理手绘草图。", + "help.sketch.constraint.coincident": "使一个点位于另一个点、曲线或草图轴上。用于闭合轮廓中的间隙,或把点放到直线上。", + "help.sketch.constraint.collinear": "使两条直线位于同一条直线上。用于对齐被打断的边,例如缺口的两侧。", + "help.sketch.constraint.concentric": "使两个圆或圆弧具有相同的圆心,也可将圆或圆弧的圆心约束到草图点(包括原点)。两者的选择顺序不限。", + "help.sketch.constraint.curvature": "使在端点相接的两条曲线以相同的曲率延续 (G2)。用于相切连接不够平滑的地方,例如可见曲面。", + "help.sketch.constraint.equal": "使直线长度相等,或使圆和圆弧半径相等。用于让一个尺寸同时驱动多个相同的特征。", + "help.sketch.constraint.fix": "把点或曲线固定在当前位置,或再次解除固定。用于拖动或解算草图时不得移动的几何体。", + "help.sketch.constraint.horizontal_vertical": "使一条直线或两点之间的连线水平或竖直,取更接近的方向。用于让轮廓与草图坐标轴对齐。", + "help.sketch.constraint.midpoint": "把点放在直线的中间,或使两条直线的中点重合。用于使几何体相对于某条边居中。", + "help.sketch.constraint.parallel": "使两条直线平行。用于其他尺寸变化时必须保持平行的边。", + "help.sketch.constraint.perpendicular": "使两条直线以直角相交。用于不在草图坐标轴上的直线之间的直角拐角。", + "help.sketch.constraint.polygon": "把封闭的直线链变成正多边形:各边相等,所有顶点位于同一个圆上。用于让手绘的多边形变成正多边形并保持如此。", + "help.sketch.constraint.symmetry": "使两个点或曲线关于一条直线或一个点互为镜像。用于修改一侧时保持轮廓对称。", + "help.sketch.constraint.tangent": "使两条曲线相切,例如直线与圆弧。用于无折痕的平滑连接。", + "help.sketch.construction": "在普通几何与构造几何之间切换,构造几何不参与轮廓。把构造曲线用作布局、参照和尺寸标注的辅助。", "help.sketch.construction_line": "创建经过两点的无限构造直线,用于辅助绘制草图而不分割轮廓。", "help.sketch.construction_line.angle": "创建与草图X轴成指定角度的无限构造直线。选择一点后输入角度或选择方向。", "help.sketch.construction_line.bisector": "选择两条相交的草图直线,再选择所需的角平分线。结果随原直线的编辑而变化。", @@ -1444,11 +1699,71 @@ "help.sketch.construction_line.tangent_external": "依次选择圆或圆弧、外部点和所需切线。预览仅显示接点位于已绘圆弧上的解。", "help.sketch.construction_line.tangent_two": "选择两个圆或圆弧,再从预览中选择公切线。接点必须位于已绘曲线上。", "help.sketch.construction_line.vertical": "创建经过指定点的无限竖直构造直线。后续编辑时保持竖直约束。", + "help.sketch.copy": "复制所选的草图曲线和点,以及它们之间的约束和尺寸。可粘贴到本草图或另一个草图中。", + "help.sketch.create": "在平面或模型的平面上开始新的二维草图。每个拉伸、旋转和扫掠都从草图开始。", + "help.sketch.cut": "复制所选的草图几何并将其从草图中删除,只需一步撤销。可粘贴到本草图的其他位置或另一个草图中。", + "help.sketch.dimension": "添加驱动尺寸:根据所选对象为长度、距离、角度、半径或直径。输入数值或参数名,草图随之变化。", + "help.sketch.edit": "打开已有的草图进行编辑。完成草图后,基于它创建的特征会随之更新。", + "help.sketch.ellipse": "根据圆心、长轴端点和短轴一侧的一个点绘制椭圆。用于椭圆形开口、凸轮和其他细长的圆形形状。", "help.sketch.equation_curve": "在一个范围内按公式绘制曲线:x(t) 和 y(t),或 y = f(x)。公式可以使用参数,曲线随参数变化。适用于正弦波、螺旋线或齿轮的渐开线。", + "help.sketch.extend": "把直线或圆弧延长到途中最近的曲线,或把两条曲线延伸到相交。用于在修剪或编辑后闭合轮廓中的间隙。", + "help.sketch.fillet": "用指定半径的圆弧把两条直线或圆弧相交的拐角倒圆。同时倒圆的多个拐角共用同一个半径。", + "help.sketch.finish": "离开草图并返回模型。其封闭轮廓随即可用于拉伸、旋转和其他特征。", + "help.sketch.finish_auto_constrain": "对草图运行自动约束,然后完成草图。用于一步得到完全定义的草图。", + "help.sketch.fit_curves_to_section": "用草图平面剖切网格或实体,并用直线和圆弧拟合截面。用于把扫描或导入的零件重建为可编辑的草图。", + "help.sketch.include_3d": "把模型的边、顶点和其他草图的曲线作为关联参照引入本草图,并把不在其平面上的几何压平到平面上。用于基于不在草图平面内的几何继续作图。", + "help.sketch.infinite": "在普通直线与贯穿整个视图的无限构造直线之间切换。用作永远不会过短的布局参照。", + "help.sketch.insert_dxf": "将 DXF 图纸中的曲线读入草图,并按设定进行缩放、旋转和放置。用于在其他程序制作的二维图纸(例如激光切割轮廓)基础上建模。", + "help.sketch.insert_svg": "将 SVG 图形中的路径读入草图,并按设定进行缩放、旋转和放置。用于把标志或矢量轮廓变成可拉伸的曲线。", + "help.sketch.inspect": "打开当前草图的报告:显示剩余的自由度以及是否已完全约束。在完成草图之前,用它找出仍然可以移动的部分。", + "help.sketch.intersect": "添加实体、面、边或其他草图与草图平面相交处的曲线或点。它们保持关联,并随模型变化。", + "help.sketch.intersection_curve": "在两个实体或面相交处创建与它们关联的三维曲线。用作跟随模型的路径或导轨。", + "help.sketch.isoparametric_curve": "通过你选取的点,沿面的 U 或 V 方向创建与该面关联的三维曲线。用作跟随曲面的路径或分割线。", + "help.sketch.line": "逐点绘制相连的直线,可以是开放链或封闭轮廓。这是绘制大多数轮廓的基本工具。", + "help.sketch.line.midpoint": "从中点向一端绘制直线,另一端随之对称生成。用于以某点为中心的直线,例如对称的边。", + "help.sketch.line3d": "开启3D 草图后,在空间中的点之间绘制相连的直线。用于离开草图平面的路径和框架。", + "help.sketch.mirror": "把草图曲线和点关于直线或轴镜像,并添加对称约束。用于只画对称轮廓的一半,再将其补全。", + "help.sketch.move": "移动或旋转草图曲线和点,或它们的副本。用于在保持形状和约束的同时调整几何的位置。", + "help.sketch.offset": "按设定的距离在一侧或两侧创建曲线链的副本。用于壁、轮廓和间隙;距离仍是可编辑的尺寸。", + "help.sketch.paste": "把复制或剪切的草图几何粘贴到当前草图。可放置在某一点,或按偏移量移动。", + "help.sketch.pattern.circular": "绕中心点复制草图几何,可绕整圆或按设定角度。用于螺栓圆、辐条和齿。", + "help.sketch.pattern.rectangular": "按设定间距以行和列复制草图几何。用于孔、槽或通风口的阵列。", + "help.sketch.point": "放置一个草图点。用作尺寸、约束、孔心或后续特征的参照。", + "help.sketch.point3d": "开启3D 草图后,在空间中放置一个点。用作三维曲线和路径的参照。", + "help.sketch.polygon.circumscribed": "在圆外绘制正多边形,大小由中心到边中点的距离决定。适用于已知对边距的情况,例如六角螺母。", + "help.sketch.polygon.edge": "根据一条边的两个端点绘制正多边形。适用于已知边的长度和位置的情况。", + "help.sketch.polygon.inscribed": "在圆内绘制正多边形,大小由中心到顶点的距离决定。适用于已知对角距的情况。", + "help.sketch.project": "把模型的边、面、顶点和其他草图的曲线投影到本草图的平面上并引入。它们保持关联,并随模型变化。", + "help.sketch.project_to_surface": "把其他草图的曲线沿本草图的法线方向投影到面上,生成关联的三维曲线。用于把标志、分割线或路径放到曲面上。", + "help.sketch.rectangle.center": "根据中心和一个角点绘制矩形。用于以某点(如原点)为中心的轮廓。", + "help.sketch.rectangle.rounded": "绘制四个角都倒成同一半径圆角的矩形。用于带圆角的板、盖和开口。", + "help.sketch.rectangle.three_point": "根据一条边和对侧的一个点绘制矩形。用于与草图坐标轴成角度的矩形。", + "help.sketch.rectangle.two_point": "根据两个对角点绘制矩形。用于板、块体和凹槽的轮廓。", + "help.sketch.scale": "以基点为中心按比例缩放草图曲线和点。用于无需重画就调整草图某一部分的大小。", + "help.sketch.slot.arc_center": "沿由圆心、起点和终点确定的圆弧,绘制指定宽度的弧形槽。用于绕转轴的调节槽。", + "help.sketch.slot.arc_three_point": "沿经过三点的圆弧,绘制指定宽度的弧形槽。适用于槽的路径必须经过给定点的情况。", + "help.sketch.slot.center_point": "从中心到一端圆弧的圆心,绘制指定宽度的直槽。用于以某点为中心的槽。", + "help.sketch.slot.center_to_center": "在两端圆弧的圆心之间,绘制指定宽度的直槽。用于按中心距标注的槽,例如螺钉调节槽。", + "help.sketch.slot.overall": "从一个外端到另一个外端,绘制指定宽度的直槽。适用于槽的总长最重要的情况。", + "help.sketch.spline.control_point": "绘制由控制点决定形状的三次样条曲线,曲线不经过这些点。用于通过移动控制点来塑形的平滑流畅曲线。", + "help.sketch.spline.control_point_5": "绘制由控制点决定形状的 5 次样条曲线。用于曲线需要以更平滑的曲率连接的地方,例如可见的造型曲面。", + "help.sketch.spline.fit_point": "绘制经过你放置的每个点的平滑样条曲线,可开放或封闭。用于通过已知点描出形状。", + "help.sketch.spline3d": "开启3D 草图后,在空间中通过各点绘制平滑曲线。用于离开草图平面的扫掠路径和线缆走线。", + "help.sketch.spun_profile": "在草图平面中创建实体绕轴旋转时扫出的轮廓。用于获得车削零件的剪影,以便旋转或出图。", + "help.sketch.text": "用选定的字体、高度和角度在草图中写文字;文字内容可以跟随参数。拉伸或压印后可做标签和字样。", + "help.sketch.transform": "以中心点为基准,一步完成草图几何的缩放、旋转和移动。用于同时调整所选对象的位置和大小。", + "help.sketch.trim": "删除你点击位置周围、最近两个交点之间的那段曲线。用于把重叠的线整理成封闭轮廓。", "help.solid.align": "移动所选实体,使其上的点、面或平面与别处的点、面或平面对齐。用于把一个零件贴靠到另一个零件上,而无需测量距离。", + "help.solid.boundary_fill": "由相互重叠的工具实体所围成的区域生成实体,只填充所选区域。用于利用多个实体共同围成的空间构建形状。", + "help.solid.bounding_solid": "创建包围选中实体的长方体,可设置余量。用于查看零件的总体尺寸,或作为加工所用的毛坯。", + "help.solid.box": "根据长、宽、高创建长方体,可从角点或以某点为中心放置。用于快速创建块体、占位体或用于切出特征的实体。", "help.solid.chamfer": "用指定的距离在所选边上切出一个平直的斜面。用于去除锐边,或使销钉、螺钉更容易插入。", + "help.solid.coil": "根据直径、圈数、高度或螺距以及圆形或方形截面创建螺旋形实体,例如弹簧。用于弹簧、线圈和螺旋凸筋。", "help.solid.combine": "将多个实体合并、从目标实体中切除,或只保留它们共有的体积,还可以保留工具实体。用于合并零件、用一个形体切割另一个形体,或找出两个实体重叠的位置。", + "help.solid.cone": "根据底圆和高度创建圆锥体;若顶面也有半径,则为圆台。用于锥度、漏斗、沉头孔和尖端。", + "help.solid.cylinder": "根据半径或直径和高度创建圆柱体,立于某点并沿某轴延伸。用于轴、销、凸台和圆形毛坯。", "help.solid.draft": "将所选的面按指定角度倾斜,角度从中性面量起。用于注塑件或铸件,使零件能够脱模。", + "help.solid.emboss": "将文字或标志等草图轮廓从面上凸起或凹入。用于平面或圆柱面上的文字、标签和标记。", "help.solid.extrude": "将草图轮廓按指定距离拉伸为三维形体,可以增加或去除材料。用于把平面轮廓变成方块、凸台或凹槽。", "help.solid.fillet": "用指定半径的平滑圆弧将所选的边倒圆。用于出于强度、手感或外观的考虑而柔化锐边。", "help.solid.hole": "在面上的指定位置钻出指定直径的圆孔。用于螺钉过孔、销孔等简单的圆形开口。", @@ -1457,20 +1772,61 @@ "help.solid.move": "按指定的距离和角度移动或旋转所选实体,或其副本。用于调整实体位置,或在别处再生成一个。", "help.solid.offset_face": "将所选的面按指定距离向内或向外推移,周围的面随之调整。用于在不编辑草图的情况下加厚壁、加深凹槽或加高凸台。", "help.solid.pattern.circular": "将所选对象按指定的数量和总角度绕轴重复排列。用于螺栓圆周分布、辐条、散热片和轮齿。", + "help.solid.pattern.path": "沿草图路径按数量和间距复制特征或实体。用于沿曲线边的孔,或沿导轨的零件。", "help.solid.pattern.rectangular": "将所选对象按指定的数量和间距沿一个或两个方向重复排列。用于成排或成网格的孔、加强筋、销钉或支脚。", + "help.solid.pipe": "沿草图曲线路径创建圆管,可为实心或带壁厚的空心。用于管道、线材、电缆和栏杆。", "help.solid.press_pull": "拖动面来增加或去除材料,或拖动边将其倒圆。用于直接在模型上快速修改。", "help.solid.remove": "从时间线的这一位置起,将所选实体从设计中移除;之前的步骤仍保留它们。用于去掉辅助实体,例如不再需要的切割工具。", "help.solid.replace_face": "将所选的平面移到一个平面或平行的面上,实体随之伸长或缩短。用于让一个面与另一个零件或构造平面齐平。", "help.solid.revolve": "将草图轮廓绕一条轴旋转,生成圆形的实体。用于轴、旋钮、碗等围绕中心线呈圆形的零件。", + "help.solid.rib": "沿开放的草图曲线添加一道薄壁,延伸到实体的下一个面。用于加强壁和角,例如注塑件或打印件。", "help.solid.scale": "按比例放大或缩小所选实体,可在各方向相同,也可按轴分别设置。用于调整导入形体的大小,或预留收缩量。", "help.solid.shell": "将实体掏空,留下指定厚度的壁,还可以打开所选的面。用于盒子、盖子等薄壁零件。", + "help.solid.sphere": "根据半径或直径,以指定点为球心创建球体。用于球、旋钮和圆头端部。", "help.solid.split_body": "用平面、另一实体的面或草图直线,将实体切分为多个独立的实体。用于制作分别打印、加工或上色的零件。", "help.solid.split_face": "沿平面、另一实体的面或草图曲线分割所选的面,而不切开实体。用于给面的一部分单独设置拔模、颜色或偏移。", "help.solid.sweep": "沿路径拖动草图轮廓生成实体。用于管道、导轨、手柄等截面恒定且沿曲线延伸的零件。", + "help.solid.thread": "在圆柱面上添加 ISO 公制螺纹,可作为装饰螺纹或切入实体。用于螺栓、螺纹孔和打印的螺纹零件。", + "help.solid.torus": "根据绕轴的大半径和圆形截面的小半径创建圆环。用于 O 形圈、把手和环形凸筋。", + "help.solid.web": "沿每条开放的草图曲线各添加一道薄壁,均延伸到实体的下一个面。用于外壳和托盘内部的网格支撑壁。", + "help.surface.blend": "创建桥接两个实体边的曲面,与两侧相切连续或曲率连续。用于在间隙上将两个曲面平滑连接。", + "help.surface.boundary": "创建填充由二至四条草图曲线构成的环或曲线网络的曲面。用于由边界定义的自由曲面面板。", + "help.surface.extend": "将曲面延伸出其边缘,按距离或直至某个平面或面。用于在修剪或缝合之前让曲面相互重叠。", + "help.surface.extrude": "将草图曲线或轮廓按一段距离拉伸为曲面,只有壁,没有端盖。用于薄壁,以及切割或分割工具。", + "help.surface.fair": "在保持边不动的前提下,使自由曲面的内部变得光顺。用于抚平曲面上的凸起和波浪状反射。", + "help.surface.loft": "创建按顺序穿过两个或更多截面的曲面,无端盖。用于外壳以及不同形状之间的过渡。", + "help.surface.match": "重建曲面的边,使其与另一实体的边衔接,并匹配相切或曲率。用于平滑地闭合两个曲面之间的接缝。", + "help.surface.offset": "将面沿法向按一定距离复制为新的曲面实体。用于蒙皮、间隙,或壁的另一侧。", + "help.surface.patch": "用平面或平滑弯曲的面填充草图区域或边的闭合环。用于封闭曲面实体上的孔。", + "help.surface.reverse_normal": "翻转曲面实体的面,使其外侧朝向反方向。用于面朝内时,在加厚或缝合之前。", + "help.surface.revolve": "将草图曲线或轮廓绕轴旋转为曲面,无端盖。用于灯罩、碗、喷嘴等圆形壳体。", + "help.surface.ruled": "从一串边出发,沿面的法向、切向或按某一角度生成由直线构成的带状面。用于拔模壁、过渡面和分型面。", + "help.surface.stitch": "沿共用的边将曲面实体缝合在一起,闭合时成为实体。用于将一组曲面变成一个实体。", + "help.surface.sweep": "沿路径移动草图曲线或轮廓生成曲面,无端盖。用于排水槽、饰条等沿路径延伸的薄形状。", + "help.surface.thicken": "为曲面实体赋予厚度,使其成为实体。用于由曲面制作可打印或可加工的零件。", + "help.surface.trim": "用平面、另一个曲面或草图曲线切割曲面,并保留所选的一侧。用于在缝合前将曲面切成所需形状。", + "help.surface.unstitch": "将实体的面分离为各自独立的曲面实体;实体会拆成曲面。用于重新处理实体中的单个面。", + "help.surface.untrim": "去掉面上的孔,或将其外边界恢复为曲面的自然边界。用于在修剪之后找回完整的曲面。", "help.third_party": "第三方许可证", "help.timeline.compute_all": "从头重新计算时间线中的所有特征。用于刷新模型,并查看哪些特征失败。", "help.timeline.delete": "从时间线中删除所选特征;删除草图时,由它生成的特征也会一起删除。用于去掉不再需要的步骤。", + "help.timeline.dependents": "列出会随某个特征一同被删除的特征,以及缺少它就会失败的特征。用于在删除或更改特征之前。", "help.timeline.play": "逐个播放剩余特征,每次重建后暂停半秒。再次运行此命令或按Escape停止;转到末尾会立即跳转。", + "help.version": "版本 {version}", + "help.view.apply": "将视图转到前视、俯视、等轴测等标准方向,或转到已保存的命名视图。用于从固定角度观察模型。", + "help.view.delete": "删除已保存的命名视图。模型不会改变。", + "help.view.fit": "缩放并平移,使整个模型或所选对象充满视图。用于模型跑出视野时。", + "help.view.grid": "显示或隐藏视口中的网格。用作建模时的尺寸和方向参考。", + "help.view.ground_shadow": "显示或隐藏模型在地面上的阴影。用于更容易判断高度和位置。", + "help.view.home": "将视图转回主视图方向并适合模型。用于快速回到已知的视图。", + "help.view.list": "列出设计中保存的命名视图。用于找到之前保存的视图。", + "help.view.navigate": "按步骤旋转、平移或缩放视图,例如向左转四分之一圈。用于精确移动相机,而不是靠拖动。", + "help.view.navigation_bar": "显示或隐藏视口底部的导航栏。隐藏可腾出空间,显示便于用鼠标使用视图工具。", + "help.view.rename": "为已保存的命名视图改名。视图本身保持不变。", + "help.view.save": "将当前相机位置作为命名视图保存到设计中。用于以后回到同一角度,例如截图。", + "help.view.spin": "让视图持续绕模型环绕,直到下一次点击或按键。用于从各个方向展示模型。", + "help.view.tool": "锁定一个相机工具(环绕、平移或缩放),之后用鼠标左键拖动即可移动视图,直到关闭。用于触控板或没有鼠标中键时。", + "help.view.visual_style": "切换模型的绘制方式:带边或不带边的着色、线框,或带隐藏边。用线框看内部,用着色得到干净的外观。", "history.sketch_under_constrained": "欠约束({count} 个自由度)", "history.sketch_under_constrained_one": "欠约束({count} 个自由度)", "hole_presets.confirm_delete": "确认删除", @@ -1544,6 +1900,27 @@ "home.start_hint": "创建设计、打开最近的文件或浏览示例。", "home.whats_new": "新功能", "home.yesterday": "昨天", + "import_report.details": "详细信息:", + "import_report.file_one": "文件还有 1 个其他问题。", + "import_report.file_other": "文件还有 {count} 个其他问题。", + "import_report.hint": "从创建这些零件的程序重新导出可能会解决此问题。“复制警告消息”中有详细信息。", + "import_report.left_out_one": "1 个面无法修复,已缺失。", + "import_report.left_out_other": "{count} 个面无法修复,已缺失。", + "import_report.needs_repair_one": "1 个零件需要修复后才能建模。", + "import_report.needs_repair_other": "{count} 个零件需要修复后才能建模。", + "import_report.not_imported_one": "1 个零件无法导入。", + "import_report.not_imported_other": "{count} 个零件无法导入。", + "import_report.not_shown_one": "1 个面无法绘制,已隐藏。", + "import_report.not_shown_other": "{count} 个面无法绘制,已隐藏。", + "import_report.open_one": "1 个零件的面之间有缝隙,作为开放实体导入。", + "import_report.open_other": "{count} 个零件的面之间有缝隙,作为开放实体导入。", + "import_report.refused_one": "1 个零件无法生成实体,未导入。", + "import_report.refused_other": "{count} 个零件无法生成实体,未导入。", + "import_report.repaired_one": "已修复 1 个零件中的小缺陷。", + "import_report.repaired_other": "已修复 {count} 个零件中的小缺陷。", + "import_report.solids": "{parts} 个零件中有 {solids} 个作为实体导入。", + "import_report.surfaces_one": "1 个零件无法生成实体,作为曲面导入。", + "import_report.surfaces_other": "{count} 个零件无法生成实体,作为曲面导入。", "install.button_tip": "将 SolidCraft 安装为应用:在独立窗口中打开,离线也能使用", "install.dock_1": "选择“文件”›“添加到程序坞”。", "install.dock_2": "点按“添加”。", @@ -1568,26 +1945,39 @@ "issue.note_save_failed": "无法保存截图:{error}", "issue.note_saved": "截图已保存。请在 GitHub 草稿中附上 PNG。", "issue.save_screenshot": "保存截图…", + "joint.find_limits": "查找限制", + "joint.find_limits_failed": "查找限制时出错停止", + "joint.find_limits_hint": "根据此接头移动的零件首次接触其他零件的位置填写限制,从当前位置向两个方向旋转或滑动。在副本上进行:按“确定”前不会更改任何内容。", + "joint.find_limits_stale": "找到这些限制后接头或设计已更改:请重新查找", + "joint.finding_limits": "正在查找限制…", "joint.from_bodies_hint": "每个所选实体移入各自的新组件,位置保持不变。", + "joint.limit_contact": "{side} {value}:{a} 接触 {b}", + "joint.limit_limit": "{side} {value}:另一个值或接头的限制", + "joint.limit_loop": "{side} {value}:超过此处闭环无法闭合", + "joint.limit_range": "{side}:{range} 内无接触,保持不变", + "joint.limit_turn": "{side} {value}:一圈内无接触", + "joint.limits_overlapping": "此处已相互重叠:{pairs}。只有更深入时才会停止查找。", "joint.one_body": "两次选择都在 {body} 上。请在另一个零件上选择第二个。", "joint.one_component": "这些零件是同一组件的实体:{bodies}。接头使一个组件相对另一个组件运动,因此每个零件都需要自己的组件。", "joint.rigid_group_one_component": "这 {count} 个实体都位于同一组件中(或直接位于设计中):请先使用“{command}”。", "joint.rigid_group_select_components": "请选择两个或更多组件。", "joint_move.blocked_hint": "请检查关节类型(例如 Rigid)、固定状态、关节限位和参数驱动值。", "joint_move.blocked_title": "无法移动此零部件", - "joint_move.coarse": "靠近轴线时的旋转步长(°)", + "joint_move.coarse": "近轴步长", + "joint_move.conflict": "此零部件的一个关节与其他关节冲突:{joint}。", + "joint_move.conflict_hint": "请编辑、抑制或删除冲突的关节,以便其他关节可以放置该零部件。", "joint_move.distance": "相对起点的移动距离", "joint_move.done": "完成", - "joint_move.fine": "远离轴线时的旋转步长(°)", + "joint_move.fine": "远轴步长", "joint_move.fixed": "此零部件没有可操作的关节自由度。", "joint_move.help": "移动 — 拖动箭头或圆弧。按 Esc 取消当前拖动。", - "joint_move.legacy_hint": "关闭后使用原有的移动面板。", - "joint_move.precision": "将光标移到虚线引导圈外侧可微调旋转。", + "joint_move.legacy_hint": "关闭:使用原来的移动面板。", + "joint_move.precision": "拉到虚线引导线外可使用精细步长。", "joint_move.rotation": "相对起点的旋转角度", "joint_move.select": "请选择一个面或一个装配零部件,然后执行移动。", "joint_move.settings": "装配移动", "joint_move.step": "步长", - "joint_move.use_handles": "装配移动使用关节运动手柄", + "joint_move.use_handles": "移动时使用关节运动控制柄", "keymap.command_id": "命令 ID", "keymap.empty": "没有匹配的命令", "keymap.use_anyway": "仍在此处使用 {key}", @@ -1647,6 +2037,11 @@ "material.selection.mixed": "不同材料", "measure.at": "位置", "measure.item": "项目 {number}", + "measure.line_to_centre": "线到圆心", + "measure.quick_copied": "已复制测量值", + "measure.quick_copy": "点击复制测量值", + "measure.quick_edges": "{count} 条边", + "measure.quick_faces": "{count} 个面", "messages.ago_h": "{n} 小时前", "messages.ago_min": "{n} 分钟前", "messages.ago_s": "{n} 秒前", @@ -1671,6 +2066,8 @@ "motion.track_name": "轨道 {number}", "nav.alias.help": "Shift+Alt+左键拖动旋转,Shift+Alt+中键拖动平移,Shift+Alt+右键拖动缩放;中键拖动也可平移,右键拖动旋转", "nav.blender.help": "中键拖动旋转,Shift+中键拖动平移,Ctrl+中键拖动缩放;右键拖动不会移动相机", + "nav.creo.help": "中键拖动旋转,Shift+中键平移,Ctrl+中键上下拖动缩放(向下放大);滚动滚轮也可缩放", + "nav.creo.label": "Creo", "nav.free_orbit.help": "鼠标和3D鼠标可保持滚转并越过两个极点旋转。Shift轴吸附将被禁用。", "nav.free_orbit.label": "自由旋转", "nav.free_orbit.snap_help": "鼠标和3D鼠标可越过两极旋转,并保留画面旋转角度。在拖动环绕时按住Shift,可吸附视图方向和画面旋转角度。", @@ -1680,6 +2077,7 @@ "nav.hfss.help": "Alt+左键拖动平移,Shift+Alt+左键拖动缩放,在空白处 Ctrl+左键拖动旋转", "nav.inventor.help": "中键拖动平移,Shift+中键拖动旋转,Ctrl+中键拖动缩放,右键拖动旋转", "nav.maya.help": "Alt+左键拖动旋转,Alt+中键拖动平移,Alt+右键拖动缩放;中键拖动也可平移", + "nav.nx.help": "中键拖动旋转,Shift+中键平移(对应 NX 的中键+右键),Ctrl+中键缩放(对应 NX 的中键+左键);右键拖动不旋转视图", "nav.openscad.help": "在空白处左键拖动旋转,Shift+左键拖动框选,拖动草图几何可编辑;右键或中键拖动平移,Shift+右键或 Shift+中键拖动缩放", "nav.perspective.sketch": "编辑草图时使用正交视图。完成草图后才能切换透视。", "nav.right_drag_orbits.help": "关闭:右键拖动不会移动相机,右键只打开上下文菜单。选择 SolidWorks 鼠标映射时会关闭此项。", @@ -1698,6 +2096,12 @@ "navbar.assistant": "助手", "navbar.custom.add_slot": "添加{slot}", "navbar.custom.always": "始终显示", + "navbar.custom.anchor.bottom_centre": "底部居中", + "navbar.custom.anchor.bottom_left": "左下角", + "navbar.custom.anchor.bottom_right": "右下角", + "navbar.custom.anchor.top_centre": "顶部居中", + "navbar.custom.anchor.top_left": "左上角", + "navbar.custom.anchor.top_right": "右上角", "navbar.custom.available": "{available} · 拖到栏上,或点击添加", "navbar.custom.buttons": "按钮", "navbar.custom.compact": "紧凑", @@ -1734,6 +2138,7 @@ "navbar.custom.reset_default": "恢复默认", "navbar.custom.right": "右移", "navbar.custom.select": "未选择槽位。选择栏上的槽位即可移动、移除或更改其外观。", + "navbar.custom.separator_hint": "按钮组之间的分隔线。将其拖到栏上,或按“添加”;可以按需使用任意数量。", "navbar.custom.separators_full": "导航栏已有4个分隔线。", "navbar.custom.show": "显示导航栏", "navbar.custom.shows": "显示内容", @@ -1799,6 +2204,11 @@ "not a move": "不是移动", "not a number": "不是数字", "open a sketch first": "请先打开一个草图", + "parameters.apply_live": "离开字段时立即应用每项更改", + "parameters.apply_live_tip": "关闭时:更改会等到“应用”或“确定”,然后设计只为所有更改重建一次。“取消”或 Esc 会放弃这些更改。", + "parameters.held": "{count} 项更改等待应用", + "parameters.held_hint": "编辑表达式和单位。更改将等到“应用”或“确定”时生效。", + "parameters.held_one": "1 项更改等待应用", "parts.automatic_name": "自动", "parts.dimension.across_flats": "对边宽度", "parts.dimension.bore": "内径", @@ -1817,10 +2227,19 @@ "parts.family.button_head_cap_screw": "圆头内六角螺钉", "parts.family.dowel_pin": "圆柱销", "parts.family.hex_bolt": "六角头螺栓", + "parts.family.hex_cap_screw_inch": "六角头螺栓(英制)", "parts.family.hex_nut": "六角螺母", + "parts.family.hex_nut_inch": "六角螺母(英制)", "parts.family.set_screw": "内六角平端紧定螺钉", "parts.family.socket_head_cap_screw": "内六角圆柱头螺钉", "parts.family.washer": "平垫圈", + "parts.family.washer_sae": "平垫圈,SAE(窄型)", + "parts.family.washer_uss": "平垫圈,USS(宽型)", + "parts.holes": "孔(可选)", + "parts.placement_hint": "选择一个或多个孔,在每个孔中各装一个零件;或按确定将其放在原点", + "parts.system": "单位制", + "parts.system.inch": "英制", + "parts.system.metric": "公制", "pattern.alignment_2": "对齐 2", "pattern.alignment_hint": "数量包含原始图形。居中时副本分布在两侧;数量为偶数时,反转可切换多一个副本的一侧。", "pattern.direction_1": "方向 1", @@ -1859,20 +2278,52 @@ "prefs.alt_frees_manipulators": "Alt / Option 也可自由拖动操纵器箭头", "prefs.anti_aliasing_amd_dx12": "由于启动检查在启用多重采样时未绘制任何内容,而在1×时通过了检查,抗锯齿已设为1×。您可以在上方选择其他设置;重启后若检查通过,该设置将生效。", "prefs.anti_aliasing_note": "平滑锯齿边缘。", + "prefs.appearance.colour_vision_help": "更改具有含义的颜色:草图状态、坐标轴、折弯、分析和图标。", + "prefs.appearance.desktop_only": "仅限桌面", + "prefs.appearance.follow_help": "其他工具重写文件时重新加载。", + "prefs.appearance.interface_scale": "界面缩放", + "prefs.appearance.next_themes": "下一个主题", + "prefs.appearance.option_count": "{count} 个选项", + "prefs.appearance.option_count_one": "{count} 个选项", + "prefs.appearance.previous_themes": "上一个主题", + "prefs.appearance.theme_count": "{count} 个主题", + "prefs.appearance.theme_own": "主题自身", + "prefs.appearance.viewport_colours": "3D 视图颜色", + "prefs.appearance.viewport_logo": "视口和徽标", "prefs.applies_on_restart": "重启后生效", "prefs.assistant": "助手", + "prefs.assistant_connecting": "连接", + "prefs.assistant_follow_help": "草图的Look At操作会使视图随指针移动。", + "prefs.assistant_limit": "上限", + "prefs.assistant_limited": "有限制", + "prefs.assistant_pointer_speed": "指针速度", + "prefs.assistant_seconds": "秒", + "prefs.assistant_seconds_aria": "秒", + "prefs.assistant_use_care": "谨慎使用", "prefs.auto_operation": "自动选择操作", - "prefs.auto_operation_note": "特征窗口根据新材料接触的对象选择连接、新建实体或剪切,直到您手动选择。关闭:保持窗口打开时的操作。", + "prefs.auto_operation_note": "根据材料接触的对象选择合并、新建实体或切割。", "prefs.axes": "坐标轴", "prefs.axis": "轴", + "prefs.blur_cost": "相对渲染开销。条形越多,通常意味着处理工作越多。", + "prefs.blur_device": "此图形设备或渲染路径不支持此功能", + "prefs.blur_guard": "已降低模糊质量,以保持画面响应。模糊半径未改变。", + "prefs.blur_off": "关闭", + "prefs.blur_reduce_transparency": "已被系统的降低透明度设置禁用", + "prefs.blur_software": "软件图形渲染不支持此功能 (gpu-software)", + "prefs.blur_source": "此工作区视图不支持此功能", + "prefs.blur_web": "此网页渲染路径不支持此功能", "prefs.bodies_folders": "实体文件夹", "prefs.bodies_folders_always": "始终显示", "prefs.bodies_folders_never": "不显示", - "prefs.bodies_folders_several": "仅限多个实体", + "prefs.bodies_folders_several": "多个", "prefs.bottom": "底部", "prefs.bottom_centre": "底部居中", "prefs.bottom_right": "右下角", "prefs.browser": "浏览器", + "prefs.browser_components_open": "组件初始展开", + "prefs.browser_components_open_note": "浏览器中的每个组件都像以前一样初始展开,而不是在您展开前保持折叠。", + "prefs.browser_eye_left": "折叠箭头旁的眼睛图标", + "prefs.browser_eye_left_note": "浏览器各行的显示切换像以前一样位于折叠箭头旁,而不是在行右端的一列中。", "prefs.browser_reveal_on_hover": "悬停时显示", "prefs.browser_show_note": "“显示”让浏览器始终留在屏幕上。“悬停时显示”会将其隐藏,直到指针移到它的位置或其左边缘的细标签上;指针在其中或其菜单打开时,它保持打开。", "prefs.browser_shown": "显示", @@ -1880,6 +2331,8 @@ "prefs.button_left": "左键拖动", "prefs.button_middle": "中键拖动", "prefs.button_right": "右键拖动", + "prefs.carousel_next": "下一个", + "prefs.carousel_previous": "上一个", "prefs.choose_font": "选择字体文件…", "prefs.click": "单击", "prefs.contact_shading": "柔和接触阴影", @@ -1892,28 +2345,64 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "曲面", "prefs.curves": "曲面", + "prefs.cut_preview_tint": "以红色显示被移除的材料", + "prefs.cut_preview_tint_help": "预览会用红色半透明幻影填充特征所移除的材料以及被替换的形状。关闭时,这些填充完全透明,仅绘制其轮廓。", + "prefs.dark_parts_shading": "保持深色零件的形状", + "prefs.dark_parts_shading_help": "以线性光照和柔和的天空补光着色视图,使深色面保留渐变而不变成一片黑色", "prefs.dead_zone_note": "斜线区域为死区:此范围内的移动将被忽略。", "prefs.default": "默认", - "prefs.design": "设计默认值", - "prefs.design_note": "新建设计的初始设置。已打开的设计保留各自的设置。", + "prefs.design": "设计", + "prefs.design_note": "新设计的初始设置。", + "prefs.design_tools.ask": "询问", + "prefs.design_tools.degrees": "度", + "prefs.design_tools.double_click_help": "或就地编辑链接的组件。", + "prefs.design_tools.ghost": "以虚影显示已移动零件的原位置", + "prefs.design_tools.hole_moves_help": "再次选择该面会移动孔而非移除孔。", + "prefs.design_tools.hole_snaps_help": "面的中点及其圆形边的圆心。", + "prefs.design_tools.imported_files": "导入的文件", + "prefs.design_tools.note": "提示", + "prefs.design_tools.off": "关闭", + "prefs.design_tools.placement_group": "支座、凸台、卡扣", + "prefs.design_tools.rows": "行数", "prefs.devices": "3D 鼠标", "prefs.dialog_buttons": "对话框按钮", "prefs.dialogs": "对话框", "prefs.dialogs_edge": "视图边缘", "prefs.dialogs_left_column": "左侧栏", "prefs.dialogs_note": "命令对话框的打开位置:停靠在视图边缘,或在左侧栏中替代浏览器和历史;关闭对话框后,浏览器和历史恢复原样。", + "prefs.dimension_step_angle": "窗口的箭头、上下方向键和滚轮给角度增减的量", + "prefs.dimension_step_length": "窗口的箭头、上下方向键和滚轮给长度增减的量", + "prefs.dimension_steps": "窗口步长", + "prefs.dimension_values": "尺寸值", + "prefs.dimension_values_note": "输入尺寸值的位置。窗口带有可增减数值的箭头;尺寸工具会先放置文字。", + "prefs.dimension_values_view": "在视图中", + "prefs.dimension_values_window": "在窗口中", "prefs.display": "显示", "prefs.drawings": "绘图", "prefs.edges": "边缘与着色", "prefs.extend": "扩展", "prefs.extra_navigation": "在空白处按住Ctrl并用鼠标左键拖动可旋转;按住空格键可平移。", + "prefs.extrude_view_isometric": "打开拉伸时转到等轴测视图", + "prefs.extrude_view_return": "关闭拉伸时回到之前的视图", "prefs.follows_os": "跟随操作系统", "prefs.font": "字体", "prefs.font_fallback": "所选字体缺少的字符会使用内置字体,避免标签显示为空方框。", "prefs.font_sample": "字体示例 · Ø12.50 mm · 45.0° · 0123456789", "prefs.font_unreadable": "无法读取所选字体。", "prefs.general": "常规", - "prefs.general_note": "语言、保存和更新。", + "prefs.general.active": "当前", + "prefs.general.crash_reports": "崩溃报告", + "prefs.general.edited": "已修改", + "prefs.general.held": "包含", + "prefs.general.import": "导入...", + "prefs.general.last_check": "上次检查:{time}", + "prefs.general.minutes": "分钟", + "prefs.general.name_setup": "为此配置命名", + "prefs.general.profile_name": "配置文件名称", + "prefs.general.save_new": "另存为新配置", + "prefs.general.step_import": "STEP 和导入", + "prefs.general.this_computer": "此计算机", + "prefs.general_note": "配置文件、语言、文件和更新。", "prefs.gesture_orbit": "环绕", "prefs.gesture_pan": "平移", "prefs.gesture_zoom": "缩放", @@ -1922,18 +2411,40 @@ "prefs.graphics_card_auto": "自动", "prefs.graphics_card_missing": "已保存的显卡不可用;将使用自动选择。", "prefs.graphics_card_restart": "重启 SolidCraft 后生效。WGPU_ADAPTER_NAME 优先于此选择。", + "prefs.graphics_card_unused": "已保存的显卡未用于此窗口;实际使用的显卡显示在“帮助 › 关于”和状态栏中。请尝试“自动”,或将 WGPU_ADAPTER_NAME 设为显卡名称中的唯一部分。", "prefs.graphics_note": "在速度与平滑度之间取舍。每个选项均以示例展示效果。", + "prefs.graphics_page.current_view": "当前视图", + "prefs.graphics_page.fastest": "最快", + "prefs.graphics_page.fold_items": "折叠项目", + "prefs.graphics_page.in_view": "视图内", + "prefs.graphics_page.live_details": "实时详情", + "prefs.graphics_page.own_mix": "自定义组合", + "prefs.graphics_page.quick_measure": "快速测量", + "prefs.graphics_page.reference_geometry_through_bodies": "透过实体的参考几何体", + "prefs.graphics_page.restart": "需要重启", + "prefs.graphics_page.sharpest": "最清晰", + "prefs.graphics_page.single_surface_analysis": "单一曲面分析", + "prefs.graphics_page.status_chips": "状态标签", + "prefs.graphics_page.subtitle": "在速度与平滑度之间权衡。", + "prefs.graphics_page.supersampling": "超级采样", + "prefs.graphics_page.supersampling_adaptive": "仅在视图保持静止时", + "prefs.graphics_page.surfaces_edges": "曲面与边", + "prefs.graphics_page.view_bar": "也可在视图栏中设置", "prefs.graphics_presets_note": "预设会同时设置以下选项。", + "prefs.hide_constraint_glyphs_zoomed_out": "缩小时隐藏约束符号", + "prefs.hide_constraint_glyphs_zoomed_out_note": "草图缩小到一定程度时隐藏约束符号,以免遮挡草图。关闭:任意缩放比例下符号仍保持固定屏幕大小。", "prefs.history": "历史", "prefs.history_origin_bodies": "在顶部显示原点和实体", "prefs.history_origin_bodies_note": "左侧或浏览器下方的历史以活动组件的实体文件夹和原点开头,并带有与浏览器相同的显示切换和菜单。底部的历史保持不变。", "prefs.history_play_button": "在历史控件中显示“播放历史”按钮", "prefs.history_play_button_note": "在历史控件的“后退一步”和“前进一步”之间添加“播放历史”。也可以右键单击这些控件来显示或隐藏它。", - "prefs.history_sketches": "草图", + "prefs.history_sketches": "历史中的草图", "prefs.history_sketches_in_order": "按创建顺序", "prefs.history_sketches_note": "草图:选择“位于其特征下”后,左侧历史在宽度足以显示名称时,会将草图缩进一级,列在由其创建的第一个特征下。底部时间轴始终保持创建顺序。", "prefs.history_sketches_under_feature": "位于其特征下", "prefs.hold_stop_snapping": "按住以停用吸附", + "prefs.home_fit_size": "主视图与适配大小", + "prefs.home_fit_size_note": "主视图、适配、打开的设计或视图导航器切换视图框住模型时,模型占视图的比例,与下方设置是否开启无关。100 %:填满面板、罗盘和导航栏之间的视图。", "prefs.icons_only": "仅图标", "prefs.imported_file": "已导入文件", "prefs.in_browser": "在浏览器中", @@ -1942,13 +2453,38 @@ "prefs.interface_language": "界面语言", "prefs.interface_note": "SolidCraft 的外观和面板布局。", "prefs.interval_minutes": "{n} 分钟", + "prefs.invert_curved_roll_arrows": "反转弯曲的翻滚箭头", + "prefs.invert_curved_roll_arrows_note": "立方体角落的两个弯曲箭头在屏幕平面内翻滚视图。开启:顺时针箭头逆时针翻滚,逆时针箭头顺时针翻滚。关闭:每个箭头按其弯曲方向翻滚视图。", + "prefs.invert_navigator_arrows": "反转视图立方体的旋转箭头", + "prefs.invert_navigator_arrows_note": "立方体周围的箭头按箭头所指的方向转动相机,与 Fusion 和 Inventor 相同:左侧箭头指向右,相机向右转动。关闭:箭头把立方体转向它所在的那一面,因此左侧箭头使相机向左转动。弯曲的翻滚箭头不受影响。", + "prefs.keep_work_on_tab_switch": "切换设计时保持对话框和工具打开", + "prefs.keep_work_on_tab_switch_note": "每个设计标签页保留其打开的对话框或工具(包括其中已选择和输入的内容)以及工具栏选项卡。回到该设计时它们仍在原处。关闭时:切换设计会取消它们并显示“模型”选项卡。", "prefs.labels": "标签", + "prefs.language_system": "系统", "prefs.layout": "布局", "prefs.layout_note": "紧凑模式将面板停靠在窗口边缘。浏览器半透明仅适用于浮动模式。助手面板的位置在助手页面中设置。", + "prefs.layout_page.active_commands": "突出显示活动命令", + "prefs.layout_page.always": "始终", + "prefs.layout_page.card": "卡片", + "prefs.layout_page.column": "列", + "prefs.layout_page.hover": "悬停", + "prefs.layout_page.icons_labels": "图标+标签", + "prefs.layout_page.ok_cancel": "确定和取消", + "prefs.layout_page.on_hover": "悬停时", + "prefs.layout_page.open": "打开位置", + "prefs.layout_page.origin_bodies": "原点和实体置顶", + "prefs.layout_page.panels": "面板", + "prefs.layout_page.pinned_menus": "从菜单中排除固定命令", + "prefs.layout_page.play_history": "播放历史按钮", + "prefs.layout_page.slot_count": "{count} / {max} 个槽位", + "prefs.layout_page.view_corner": "同时在视图角落显示", + "prefs.layout_page.window": "窗口", "prefs.left": "左侧", "prefs.left_click": "左键单击", "prefs.line_drag_draws_one": "按下并拖动绘制一条直线", "prefs.line_drag_draws_one_note": "在直线工具中,按下、拖动再松开,会从按下处到松开处绘制一条直线并在此结束。单击仍会绘制连续的直线。关闭时:拖动与单击一样,在松开处放置一个点。", + "prefs.line_hover_tangent_arc": "停留在直线的最后一点上以切换到相切圆弧", + "prefs.line_hover_tangent_arc_note": "在直线工具中,画好一段后,先离开连续线的最后一点,再回到该点并让指针保持不动:下一次单击将确定相切圆弧的终点,同样的操作可切回直线。关闭:停留在该点不起作用。", "prefs.linked_designs": "链接设计", "prefs.live_input": "实时输入", "prefs.live_preview": "实时预览", @@ -1956,10 +2492,10 @@ "prefs.logo_accent": "强调色", "prefs.logo_theme": "主题颜色", "prefs.max_file_size": "可打开的最大文件", - "prefs.max_file_size_design": "设计文件", + "prefs.max_file_size_design": "可打开的最大文件:设计", "prefs.max_file_size_flag": "本次启动指定了 --max-file-size {size},该值在关闭 SolidCraft 前有效。不带此选项启动时才会应用这些设置。", "prefs.max_file_size_note": "默认值:512 MB 和 256 MB;上限为 16 GB。打开文件需要数倍于文件大小的内存。保留大型导入数据的设计可能需要提高设计文件上限,才能保存并重新打开。", - "prefs.max_file_size_step": "STEP 和导入文件", + "prefs.max_file_size_step": "可打开的最大文件:STEP 和导入", "prefs.max_file_size_web": "网页版可打开最大 512 MB 的 STEP 和导入文件,以及最大 256 MB 的设计:浏览器标签页无法容纳更大的文件。桌面版可提高这些上限。", "prefs.megabytes": "MB", "prefs.menu_grid": "大图标", @@ -1971,10 +2507,19 @@ "prefs.mouse_heading": "鼠标", "prefs.mouse_mapping": "鼠标映射", "prefs.navigation": "导航", + "prefs.navigation.axes_signed": "坐标轴", + "prefs.navigation.cube_compact": "立方体", + "prefs.navigation.device": "设备", + "prefs.navigation.free": "自由", + "prefs.navigation.orbit_style": "旋转方式", + "prefs.navigation.radial_help": "按住或轻甩右键以显示工具环。", + "prefs.navigation.turntable": "转台", "prefs.navigation_note": "鼠标、触控板和3D鼠标如何移动视图。", + "prefs.navigator_fit": "视图导航器切换视图后适配模型", + "prefs.navigator_fit_note": "点击立方体的面、角或箭头,或坐标轴指示器的轴时,也会从各个方向都能容纳模型的同一距离(其包围球)注视模型中心。开启期间主视图使用相同的缩放和中心,因此之后选择的视图只改变方向。关闭:视图原地旋转,保持目标点和缩放。", "prefs.network_host_remove": "删除", "prefs.network_locations": "允许设计中的网络位置", - "prefs.network_locations_note": "关闭:设计中位于其他计算机 (\\\\server\\share) 上的链接文件,只会从此处列出的服务器打开,或在询问时你允许的服务器打开。", + "prefs.network_locations_note": "适用于将设计存放在文件服务器上的组织。关闭时:仅允许您授权的服务器。", "prefs.network_locations_section": "网络位置", "prefs.not_on_gpu": "此 GPU 不支持", "prefs.on": "开启", @@ -1984,20 +2529,32 @@ "prefs.origin_plane_names": "原点平面名称", "prefs.origin_plane_names_note": "浏览器、对话框和列表中显示的名称。{top} 即 XY,{front} 即 XZ,{right} 即 YZ(Z 轴朝上)。命令、脚本和已保存的设计仍使用 XY、XZ 和 YZ。", "prefs.overall_speed": "整体速度", + "prefs.parameter_list_rows": "参数列表行数", + "prefs.parameter_list_rows_tip": "在空表达式框中按向下箭头时列出的参数上限。", "prefs.persistent_ribbon_pressed": "突出显示已启用的功能区命令", "prefs.persistent_ribbon_pressed_help": "在效果启用时突出显示相应的功能区命令。关闭此选项可保留原来的中性外观和命令帮助。", "prefs.perspective_fov": "视场角", "prefs.placement": "放置", + "prefs.plugins_enabled": "已启用", + "prefs.plugins_installed": "已安装", + "prefs.plugins_intro": "沙箱化扩展。", + "prefs.plugins_show_folder": "显示插件文件夹", "prefs.prefer_free_sketch_points": "草图点重合时优先选择可移动的点", "prefs.preview_choices": "所选设置预览", + "prefs.preview_tint_new_faces": "在预览中为新表面着色", + "prefs.preview_tint_new_faces_help": "更改实体的特征,其预览可以用预览颜色绘制新增的表面。关闭时,实体按自身颜色绘制。", + "prefs.print_face_highlight": "打印底面高亮", + "prefs.print_face_highlight_tip": "视图中实体打印底面的着色和轮廓强度。0 % 不显示高亮。", "prefs.profile_active": "当前配置文件", "prefs.profile_applied": "已应用配置文件。", "prefs.profile_changed": "保存配置文件后设置已更改。“保存”会将其写入配置文件。", "prefs.profile_deleted": "已删除配置文件。", - "prefs.profile_export": "导出…", + "prefs.profile_export": "导出", "prefs.profile_exported": "已导出配置文件。", - "prefs.profile_imported": "已导入配置文件。在“当前配置文件”中选择它即可切换。", + "prefs.profile_imported": "已导入配置文件。", "prefs.profile_name_hint": "配置文件名称,例如 笔记本", + "prefs.profile_operations": "分析操作耗时", + "prefs.profile_operations_note": "记录 SMLib 调用、内核操作、特征、命令和导入所用的时间。智能体通过 diagnostics.profile 读取。", "prefs.profile_rename": "重命名", "prefs.profile_renamed": "已重命名配置文件。", "prefs.profile_save": "保存", @@ -2011,26 +2568,71 @@ "prefs.quality_fastest": "最快", "prefs.quality_slowest": "最慢", "prefs.quality_smoother": "更平滑", + "prefs.quick_measure": "在视图角落显示快速测量", + "prefs.quick_measure_note": "在视图右下角、历史记录上方显示所选对象的尺寸:边的长度(圆形边显示 Ø 和 R)、面的面积、点的位置、两个对象之间的距离和角度、多条边或多个面的总和。点击即可复制。", "prefs.render_previous_geometry_budget": "使用先前的渲染预览几何内存预算", "prefs.render_previous_geometry_budget_help": "恢复先前的固定几何内存上限(64位桌面为512 MiB,其他平台为128 MiB),替代基于设备的预算。", "prefs.reports_saved": "已保存 {n} 份", + "prefs.restore_page_defaults": "恢复本页默认值", + "prefs.ribbon_click_ends_tool": "单击正在运行的工具的按钮将结束该工具", + "prefs.ribbon_click_ends_tool_note": "单击正在使用的草图工具的高亮功能区按钮会结束该工具,在视图中单击即可再次选择。关闭:单击会重新启动该工具。", "prefs.ribbon_reveal": "在功能区中显示搜索结果", "prefs.ribbon_reveal_note": "将指针悬停在“搜索命令”的结果上时,会显示该命令在功能区中的位置:其选项卡、按钮或面板下拉菜单中的行。从搜索启动的命令会在那里闪烁,从下拉菜单运行的命令会标记其面板。", "prefs.right_click": "右键单击", - "prefs.saving": "自动保存和恢复", + "prefs.saving": "启动和保存", "prefs.scale_note": "也可在窗口中使用 Ctrl + / Ctrl −。100% 时按钮高度为 28 像素。", "prefs.scale_text": "缩放与文字", "prefs.search": "搜索设置", "prefs.search_empty": "没有匹配的设置", + "prefs.section_hatch": "剖面线", + "prefs.section_hatch_by_part": "按零件", + "prefs.section_hatch_one": "单一样式", "prefs.select": "选择", "prefs.select_one_item": "选择一个项目", + "prefs.select_other_hidden": "使用“选择其他”选择隐藏几何体", + "prefs.select_other_hidden_help": "开启:包括指针附近的隐藏实体、草图和被遮挡的边。关闭:恢复原来的列表,仅包含指针正下方的可见几何体。", "prefs.selecting": "选择", "prefs.shift": "Shift", "prefs.shift_add_ctrl_toggle": "Shift 仅添加;Ctrl / Cmd 切换选择", "prefs.shift_add_note": "开启:Shift 添加,Ctrl / Cmd 切换选择。关闭(默认):两者均切换选择。", "prefs.shortcuts": "快捷键", + "prefs.shortcuts_import": "导入", + "prefs.shortcuts_intro": "每个命令的按键。", + "prefs.shortcuts_not_assigned": "未分配", + "prefs.shortcuts_press": "请按键...", "prefs.single_surface_analysis": "仅使用一个曲面分析", "prefs.single_surface_analysis_help": "关闭时,曲面着色分析和连续性分析可以同时保持启用。开启时,仅保留最后启动或修改的分析。", + "prefs.sketch.align_points": "与其他草图点对齐", + "prefs.sketch.align_points_note": "绘制的线同时与两个轴上的点对齐。", + "prefs.sketch.auto_dimensions": "为新形状标注全部尺寸", + "prefs.sketch.auto_dimensions_note": "输入的数值以及确定形状所需的所有尺寸。", + "prefs.sketch.auto_locate": "相对草图原点定位", + "prefs.sketch.auto_locate_note": "启用全部尺寸标注时。", + "prefs.sketch.center_arc": "圆心圆弧跟随光标", + "prefs.sketch.click_selects": "单击选择", + "prefs.sketch.conflict_colour": "冲突颜色", + "prefs.sketch.drawing": "绘制", + "prefs.sketch.exit_keep": "保持", + "prefs.sketch.exit_previous": "返回之前的视图", + "prefs.sketch.exit_unless_rotated": "除非已旋转", + "prefs.sketch.faces_edges": "面和边", + "prefs.sketch.hide_glyphs": "缩小时隐藏符号", + "prefs.sketch.marks": "草图中的标记", + "prefs.sketch.note": "绘制、捕捉和选择。", + "prefs.sketch.opening_closing": "打开和关闭", + "prefs.sketch.prefer_free_points": "重叠时优先选择可移动点", + "prefs.sketch.project_options": "先询问投影选项", + "prefs.sketch.recent_snap": "捕捉两条辅助线的交点", + "prefs.sketch.select_other_hidden": "选择其他对象可选中隐藏几何体", + "prefs.sketch.shortcut_cycles_modes": "再次按快捷键切换模式", + "prefs.sketch.shortcut_cycles_modes_tip": "关闭时:重新启动工具。", + "prefs.sketch.snapping_guides": "捕捉和辅助线", + "prefs.sketch.state_icons": "状态图标", + "prefs.sketch.tracking_guides": "圆心和中点辅助线", + "prefs.sketch.tracking_guides_note": "从悬停的圆心和边中点显示临时水平和垂直辅助线。", + "prefs.sketch.tracking_points": "也从草图点显示辅助线", + "prefs.sketch.unless_turned_note": "未旋转时返回", + "prefs.sketch.whole_bodies": "整个实体", "prefs.sketch_align_points": "绘制时与其他草图点对齐", "prefs.sketch_align_points_note": "绘制时,点可同时与一个草图点水平对齐、与另一个草图点竖直对齐,并显示虚线参考线;单击后保留两个对齐约束。关闭:仅与上一点对齐,每次一个方向。", "prefs.sketch_conflict_colour": "以冲突颜色显示冲突的几何图形", @@ -2041,6 +2643,8 @@ "prefs.sketch_exit_view.previous": "返回之前的视图", "prefs.sketch_exit_view.unless_rotated": "未旋转时返回", "prefs.sketch_exit_view_note": "“完成草图”、取消或连按两次 Esc 后视图的去向。", + "prefs.sketch_face_activates_part": "在零件的面上绘制草图时激活该零件", + "prefs.sketch_face_activates_part_note": "在另一个组件的实体面上开始的草图会先激活该组件,因此草图属于它,并在浏览器中留在该零件下。之后该零件保持激活。关闭时:草图属于当前激活的组件。", "prefs.sketch_open_look_at": "打开草图时转向正对草图", "prefs.sketch_open_look_at_note": "关闭:创建或编辑草图时视图保持不变。需要时用“朝向”正对草图。", "prefs.sketch_recent_snap": "自动吸附到最近的圆心和中点", @@ -2054,6 +2658,8 @@ "prefs.sketch_tab_always_note": "未打开草图时,草图选项卡也保留在功能区中紧随模型之后。其中的绘图工具会先在所选平面或面上(否则在接下来选取的平面上)创建草图,并在其中准备好该工具。", "prefs.sketch_tracking_guides": "圆心和中点对齐辅助线", "prefs.sketch_tracking_guides_note": "将光标悬停在圆心或直线边的中点,然后水平或垂直移动以显示临时虚线辅助线。", + "prefs.sketch_tracking_points": "绘制时也从端点和角点显示对齐辅助线", + "prefs.sketch_tracking_points_note": "绘图工具等待点时,将光标悬停在直线或圆弧的端点、矩形的角点或独立点上,会显示与圆心或中点相同的临时虚线辅助线。关闭:仅圆心和中点。", "prefs.sketching": "草图", "prefs.snap_drawing_note": "在绘制或拖动草图点时使用。", "prefs.source": "来源", @@ -2063,13 +2669,31 @@ "prefs.stand_up_unknown.ask": "在对话框中询问", "prefs.stand_up_unknown.note": "显示提示", "prefs.stand_up_unknown.off": "不提供", - "prefs.stand_up_unknown_note": "当文件头未注明已知以 Y 轴向上保存的程序时,如何提供立起选项。仅当文件看起来平躺时才显示提示;“在对话框中询问”会像以前一样对每个此类文件进行询问。", + "prefs.stand_up_unknown_note": "文件未注明已知程序时如何提出建议。", "prefs.status_bar": "状态栏", "prefs.status_bar_note": "窗口底边的一条细栏显示正在编辑的对象、打开的草图的状态(以其颜色显示)以及设计的单位;单击单位即可更改。草图的状态随后不再显示在视图的角落。", "prefs.status_done": "完成", "prefs.status_error": "错误", "prefs.status_selected": "已选择", "prefs.status_warning": "警告", + "prefs.structure.appearance": "外观", + "prefs.structure.appearance_note": "颜色、文字和无障碍。", + "prefs.structure.in_profile": "包含在配置中", + "prefs.structure.layout": "布局", + "prefs.structure.layout_note": "窗口各部分的位置。", + "prefs.structure.look": "外观", + "prefs.structure.measure_pointer": "测量和指针", + "prefs.structure.mouse3d": "3D 鼠标", + "prefs.structure.mouse3d_note": "SpaceMouse 和 SpaceNavigator。", + "prefs.structure.navigation_note": "鼠标和触控板。3D 鼠标有单独的页面。", + "prefs.structure.profile": "配置", + "prefs.structure.profile_edited": "保存后已更改", + "prefs.structure.profile_hover": "保存在设置配置中", + "prefs.structure.scale_percent": "{percent}%", + "prefs.structure.sketch": "草图", + "prefs.structure.tools": "工具", + "prefs.structure.tools_note": "建模工具的行为。", + "prefs.structure.work": "工作", "prefs.supersampling_brief": "以更高分辨率绘制后滤波缩小:更清晰,但负载更高。", "prefs.tab_accent_note": "强调色跟随当前选项卡", "prefs.theme_file": "主题文件", @@ -2081,6 +2705,21 @@ "prefs.theme_follow_off": "关闭", "prefs.theme_follow_stop": "停止跟随", "prefs.theme_import_hint": "单击选择主题文件,拖放到此处,或复制主题后按 Ctrl+V(Mac 上为 Cmd+V)", + "prefs.theme_notice_dismiss": "忽略", + "prefs.theme_option_blur": "面板背后模糊", + "prefs.theme_option_blur_help": "半透明面板背后的模糊程度,以物理像素为单位。0 表示关闭。", + "prefs.theme_option_invalid": "{option} 的已保存值无效;正在使用主题默认值。已保存值将予以保留。", + "prefs.theme_option_opacity": "不透明度", + "prefs.theme_option_opacity_help": "调整浮动面板的不透明度。最低不透明度限制可确保文字在视口颜色上清晰可读。", + "prefs.theme_option_tab_colours": "选项卡颜色", + "prefs.theme_option_tab_colours_help": "为每个功能区选项卡使用主题的面板和视口颜色。", + "prefs.theme_option_tab_fade_ms": "选项卡过渡", + "prefs.theme_option_tab_fade_ms_help": "切换选项卡时渐变面板和视口颜色。设为零可立即切换。", + "prefs.theme_options_badge": "选项", + "prefs.theme_options_more": "更多 · {count}", + "prefs.theme_options_newer": "此主题需要更新版本的 SolidCraft。升级后,请重新导入原始主题以恢复其选项定义。", + "prefs.theme_options_reset": "重置", + "prefs.theme_options_unavailable": "此设备不支持", "prefs.theme_paste": "粘贴主题", "prefs.theme_paste_none": "剪贴板中没有 SolidCraft 主题", "prefs.timeline_half_hour": "−30 分钟", @@ -2102,13 +2741,29 @@ "prefs.under_cursor": "光标下方", "prefs.units_precision": "单位与精度", "prefs.updates": "更新", + "prefs.validation": "实体检查", + "prefs.validation.each_feature": "每个特征一次", + "prefs.validation.each_step": "每一步之后", + "prefs.validation.label": "内核完整检查", + "prefs.validation.off": "关闭(实验性)", + "prefs.validation_note": "每一步之后:检查每次扫掠、布尔运算和倒圆。\n每个特征一次:每个特征的结果检查一次。\n关闭(实验性):不检查。", + "prefs.value_boxes_in_view": "在控制柄旁显示数值", + "prefs.value_boxes_in_view_tip": "将拉伸距离、圆角半径等显示为视图中的输入框。", "prefs.view": "视图行为", "prefs.view_confirm_corner": "在视图角落显示确定和取消", "prefs.view_confirm_corner_note": "打开对话框或草图时,视图右上角的勾号和叉号与对话框的确定和取消作用相同,或完成和取消草图。视图导航器会下移到它们下方。", "prefs.viewport": "视口", + "prefs.viewport_analysis_status": "显示视口分析状态", + "prefs.viewport_analysis_status_help": "在视口上方显示启用的分析,从各项目打开图例,并按 Esc 关闭最近启用的分析。关闭此选项可恢复角落图例和原来的 Esc 行为。", "prefs.viewport_background": "背景", "prefs.viewport_background_colour": "颜色", "prefs.viewport_background_theme": "主题渐变", + "prefs.viewport_section_status": "显示视口剖面状态", + "prefs.viewport_section_status_help": "在视口中显示剖面设置。按 Escape 或单击活动的功能区按钮可关闭剖面。禁用以保留原有剖面控件。", + "prefs.viewport_status_details": "视口实时详情", + "prefs.viewport_status_details_help": "在标准详情卡片中编辑当前分析和剖面设置。禁用后恢复只读分析图例和剖面对话框。", + "prefs.viewport_status_summary": "汇总视口状态项", + "prefs.viewport_status_summary_help": "将三个或更多视口状态项折叠为一个汇总徽章。禁用后,所有项目仍显示在完整的一行中。", "prefs.wheel": "滚轮", "prefs.wheel_trackpad": "滚轮与触控板", "prefs.workspace": "工作区", @@ -2126,6 +2781,17 @@ "recovery.just_now": "刚刚", "recovery.min_ago": "{count} 分钟前", "recovery.never_saved": "从未保存", + "refused.change": "无法更改 {body}。", + "refused.cut": "无法切割 {body}。", + "refused.face_curved": "它的一个曲面无法用于建模。", + "refused.face_flat": "它的一个平面无法用于建模。", + "refused.face_freeform": "它的一个自由曲面无法用于建模。", + "refused.face_rounded": "它的一个圆角面无法用于建模。", + "refused.faces_apart": "它的面贴合得不够紧密,无法用于建模。", + "refused.intersect": "无法与 {body} 求交。", + "refused.join": "无法合并到 {body}。", + "refused.repair": "修复零件", + "refused.show_face": "显示面", "render.adaptive_absolute": "RGB 绝对误差下限", "render.adaptive_coverage": "覆盖率误差目标", "render.adaptive_enable": "使用独立预采样分配样本", @@ -2237,6 +2903,10 @@ "render.base_color": "基础颜色 · sRGB", "render.base_metallic": "金属比例", "render.base_opaque_only": "此编辑器保留不透明实体语义;光学透射请使用明确的玻璃控件。", + "render.batch_all_shots": "所有镜头 ({count})", + "render.batch_empty": "渲染所有镜头前请先保存镜头。", + "render.batch_limit": "一次最多渲染32个镜头。", + "render.batch_status": "{running} 个运行中 · {waiting} 个等待中", "render.bloom_enable": "显示泛光", "render.bloom_help": "仅用于输出的创意辉光,将正线性高光经过三次归一化滤波扩散。半径以输出像素计,在 sRGB 前叠加;不模拟镜头或体积,也不改善收敛。原始 EXR 不变。", "render.bloom_opaque": "泛光需要不透明输出;会拒绝透明 PNG,而非暗中合成背景。", @@ -2347,6 +3017,13 @@ "render.choose_look": "请先在外观库中选择外观", "render.chromatic_offset": "边缘色差偏移", "render.clear_stage": "移除已保存的舞台", + "render.compare_divider": "比较分隔线", + "render.compare_live": "实时", + "render.compare_live_preview": "实时预览", + "render.compare_render": "渲染 {number}", + "render.compare_side": "渲染 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · 捕获于修订版 {revision}", + "render.compare_swap": "交换", "render.copy_request": "复制 JSON", "render.cpu_aa_help": "增加空间采样可改善边缘,但会增加渲染时间。", "render.cpu_area_add": "添加 CPU 矩形光源", @@ -2987,7 +3664,9 @@ "render.output_ready": "已就绪,可渲染", "render.output_run_check": "运行检查", "render.output_size_limit": "{method}:每边最多 {dimension} px,总计 {pixels} 像素。可用的最大尺寸:{width} × {height}。", + "render.output_size_method_profile": "要渲染 {width} × {height},请选择 {method} 和“{profile}”CPU 资源配置,或选择更小的尺寸。", "render.output_size_ok": "尺寸正常 · {width} × {height} px", + "render.output_size_profile": "要渲染 {width} × {height},请选择“{profile}”CPU 资源配置,或选择更小的尺寸。", "render.output_swap_orientation": "交换宽度和高度", "render.output_tools_inspector": "请在输出检查器中编辑尺寸和格式。", "render.output_view_image": "查看图像", @@ -3094,6 +3773,10 @@ "render.result_retained": "正在显示最后完成的图像;较新的渲染尚未替换它。", "render.result_sequence": "中间结果", "render.result_title": "渲染结果", + "render.results_choose": "保留的结果", + "render.results_label": "渲染 {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [已过期]", + "render.results_unnamed": "图像", "render.return_design": "返回设计", "render.review_stale": "此审阅结果已过期;应用前请重新解析或检查。", "render.ribbon_aging": "老化", @@ -3200,6 +3883,7 @@ "render.size_custom": "自定义…", "render.size_full_hd": "全高清", "render.size_hd": "HD", + "render.size_needs_profile": "{size} · 需要“{profile}”", "render.size_presets": "尺寸预设", "render.size_presets_pending": "随输出编辑器推出", "render.size_preview": "预览", @@ -3465,11 +4149,11 @@ "select two components": "请选择两个组件", "set by the sketch's lines": "由草图的线条决定", "settings.display_quality_note": "仅影响显示,不影响设计和导出。", - "settings.double_click_components": "双击组件以激活它,或在原位编辑链接组件", + "settings.double_click_components": "双击组件以激活", "settings.frame_rate_details_note": "添加最近各帧耗时的图表(叠加绘制的三角形数)、帧耗时直方图以及 GPU 绘制的内容。点击视图中的帧率可显示或隐藏。", "settings.frame_rate_note": "在视图右下角显示每秒帧数。", - "settings.insert_lists_open_designs": "插入设计时先列出其他标签页中打开的设计", - "settings.measure_axis_distances": "显示 X/Y/Z 距离", + "settings.insert_lists_open_designs": "插入设计时优先列出已打开的设计", + "settings.measure_axis_distances": "测量中的轴向距离", "settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。", "settings.msaa_applies_on_restart": "抗锯齿将在下次启动 SolidCraft 时生效", "settings.msaa_reset": "{setting}: {requested}× 不受此图形设备支持;已重置为 {reset}× (支持: {supported})。", @@ -3479,7 +4163,7 @@ "settings.reset_intro": "这些设置在此计算机上无法正常工作,会导致 SolidCraft 无法启动,因此已更改:", "settings.reset_title": "设置已更改", "settings.supersampling_note": "以更高分辨率绘制视图再缩小:在低于 4K 的屏幕上边、线和网格更平滑。会消耗 GPU 时间:1.5× 时约 2.25 倍像素,2× 时 4 倍。", - "settings.update_changed_links": "返回标签页时更新已更改的链接设计", + "settings.update_changed_links": "返回选项卡时更新已更改的链接", "settings.window_system_details": "详情", "settings.window_system_note_now": "重启后生效。当前:{now}。", "settings.window_system_wayland_limited": "在原生 Wayland 下部分功能受限。", @@ -3487,6 +4171,24 @@ "sheet.flange_type_contour": "轮廓", "sheet.flange_type_edge": "边线", "sheet.no_body": "没有钣金实体:请使用法兰 > Base 创建,或使用转换为钣金将板材转换为钣金(选择其较大的平面)。", + "sheet.personal_rules.confirm_delete": "确认删除", + "sheet.personal_rules.delete": "删除", + "sheet.personal_rules.delete_prompt": "删除此个人规则?设计中已有的规则不会改变。", + "sheet.personal_rules.full": "个人库中已有64条规则。", + "sheet.personal_rules.invalid_name": "请输入不含换行符或控制字符的简短名称。", + "sheet.personal_rules.invalid_values": "请填写完整的规则值:每个值都必须能在此设计中计算,厚度为正,K 因子在 0 到 1 之间。", + "sheet.personal_rules.missing": "所选个人规则已不可用。", + "sheet.personal_rules.name": "规则名称", + "sheet.personal_rules.name_exists": "同名个人规则已存在,请使用其他名称。", + "sheet.personal_rules.name_hint": "唯一名称", + "sheet.personal_rules.overwrite": "保存对所选个人规则的修改", + "sheet.personal_rules.rename": "重命名", + "sheet.personal_rules.rule": "个人规则", + "sheet.personal_rules.save": "另存为新规则", + "sheet.personal_rules.scope": "保存在您的配置中,适用于所有设计。", + "sheet.personal_rules.select": "选择规则", + "sheet.personal_rules.title": "个人规则", + "sheet.personal_rules.unsupported": "此规则包含当前版本无法使用的值。", "shortcut.json_error": "参数必须采用 JSON 格式:{error}", "shortcut.no_command": "没有命令 `{id}`;JSON 前的文本必须是命令 ID", "shortcut.pin": "固定到 S 框顶部", @@ -3523,8 +4225,10 @@ "sketch_text.align_right": "右对齐", "sketch_text.bold": "粗体", "sketch_text.builtin_font": "{family}(内置)", + "sketch_text.formula": "以 = 开头即可用参数组成文字:='W' + number(Width)", "sketch_text.italic": "斜体", "sketch_text.loading_fonts": "正在查找已安装字体…", + "sketch_text.no_bold": "内置字体没有粗体字形:请选择已安装的字体", "sketch_text.on_path": "文字沿路径排列:由曲线放置", "sketch_text.path_clear": "将文字移离其曲线", "sketch_text.path_hint": "文字所跟随的草图曲线:先单击此处,再选择曲线", @@ -3555,11 +4259,20 @@ "the section's profiles must be in one sketch": "截面的轮廓必须位于同一个草图中", "the two origins are on the same component": "这两个原点位于同一个组件上", "thread.automatic_size": "自动尺寸", + "thread.chamfer_depth_needed": "此牙型必填", "thread.designation": "螺纹标记", - "thread.direction": "螺纹方向", + "thread.drill_range": "丝锥制造商的钻头为 {drill} mm。内螺纹的标准小径为 {minor} mm。可使用 {low} 至 {high} mm 的钻头。", + "thread.drill_range_custom": "钻头为大径减螺距,{drill} mm。内螺纹的标准小径为 {minor} mm。可使用 {low} 至 {high} mm 的钻头。", + "thread.drill_range_taper": "丝锥制造商的钻头为 {drill} mm。螺纹终端处的标准小径为 {minor} mm。可使用 {low} 至 {high} mm 的钻头。", + "thread.end_square": "直角", + "thread.fade_short": "1.25 P(ISO 3508)", + "thread.fade_standard": "2.5 P(ISO 3508)", + "thread.fits_the_face": "适合该面,例如 {example}", + "thread.form_bspp": "管螺纹 G(ISO 228-1)", + "thread.form_bspt": "圆锥管螺纹 R、Rc(ISO 7-1)", + "thread.form_npt": "圆锥管螺纹 NPT(ASME B1.20.1)", + "thread.form_rp": "圆柱内管螺纹 Rp(ISO 7-1)", "thread.iso_metric": "ISO 公制", - "thread.left_hand": "左旋", - "thread.right_hand": "右旋", "thread.select_size": "选择尺寸", "timeline.delete_after_marker_one": "删除历史标记之后的 1 个特征", "timeline.delete_after_marker_other": "删除历史标记之后的 {count} 个特征", @@ -3663,6 +4376,8 @@ "ui.3d_mouse_section": "3D 鼠标", "ui.3d_mouse_show_in_view": "在 3D 视图中显示 3D 鼠标", "ui.3d_mouse_show_in_view_tip": "在左下角显示你的 3D 鼠标图示,随你的操作而动。", + "ui.3d_mouse_sketch_orbit": "用 3D 鼠标旋转草图", + "ui.3d_mouse_sketch_orbit_tip": "草图打开并正对视图时,3D 鼠标也能旋转视图,与鼠标一样。关闭:在你倾斜视图之前,只平移和缩放草图。", "ui.3d_mouse_skip": "我的设备做不到", "ui.3d_mouse_skip_tip": "在两个方向上都跳过这个动作,校准时不包含它。", "ui.3d_mouse_speed": "3D 鼠标速度", @@ -3691,6 +4406,8 @@ "ui.3d_mouse_step_twist_counterclockwise": "逆时针扭转摇杆帽,保持住,然后松开。", "ui.3d_mouse_switch_cap": "按回中类型校准", "ui.3d_mouse_switch_trackball": "按轨迹球校准", + "ui.3d_mouse_use_direct": "使用直接驱动", + "ui.3d_mouse_use_direct_tip": "直接读取 3D 鼠标(hidraw),不经过 spacenavd。", "ui.3d_mouse_view_axis": "视图轴", "ui.3d_mouse_view_off": "关闭", "ui.3d_mouse_view_off_tip": "3D 鼠标驱动程序的配置文件关闭了此轴,因此它的动作不会移动视图。在此选择另一个轴的动作会将两者互换,该动作将不再移动视图。", @@ -3729,6 +4446,8 @@ "ui.agent_chat_auth_terminal": "在终端中运行以下命令,然后再次点击连接:", "ui.agent_chat_auth_title": "登录智能体", "ui.agent_chat_cancel": "取消", + "ui.agent_chat_cancel_timeout": "代理未响应停止请求,已断开连接。请重新连接以继续。", + "ui.agent_chat_cannot_start": "已安装,但无法启动:{error}", "ui.agent_chat_changes": "{n} 项更改,一步撤销", "ui.agent_chat_changes_n": "{n} 项更改", "ui.agent_chat_changes_of": "更改 {n}/{limit}", @@ -3737,11 +4456,13 @@ "ui.agent_chat_command": "智能体命令", "ui.agent_chat_connect": "连接", "ui.agent_chat_copy": "复制", + "ui.agent_chat_copy_message": "复制消息", "ui.agent_chat_ctx_bodies": "实体", "ui.agent_chat_ctx_elements": "元素", "ui.agent_chat_ctx_features": "特征", "ui.agent_chat_ctx_more": "另有 {n} 项", "ui.agent_chat_ctx_other": "其他", + "ui.agent_chat_custom_heading": "自定义模型", "ui.agent_chat_custom_hint": "任何通过标准输入输出使用 Agent Client Protocol 的程序。不经过 shell 运行。", "ui.agent_chat_denied": "已拒绝", "ui.agent_chat_deny": "拒绝", @@ -3785,8 +4506,16 @@ "ui.agent_chat_mode_all": "全部", "ui.agent_chat_mode_ask": "询问", "ui.agent_chat_mode_edits": "编辑", + "ui.agent_chat_model_custom": "使用自定义:{model}", "ui.agent_chat_model_no_tools": "{model} 无法使用 SolidCraft 的工具,只能聊天。请选择支持工具的模型。", + "ui.agent_chat_model_rejected": "智能体未接受 {model}:{error}", + "ui.agent_chat_model_search": "搜索模型…", "ui.agent_chat_model_tip": "智能体使用的模型。你的选择会为此智能体记住。", + "ui.agent_chat_models_failed": "无法列出模型:{error}", + "ui.agent_chat_models_heading": "可用模型", + "ui.agent_chat_models_listing": "正在列出模型…", + "ui.agent_chat_models_none": "该端点未列出任何模型", + "ui.agent_chat_models_not_a_list": "响应不是模型列表", "ui.agent_chat_new": "新对话", "ui.agent_chat_new_confirm": "开始新对话?当前对话将被清除。", "ui.agent_chat_next_picture": "下一张图片", @@ -3795,6 +4524,7 @@ "ui.agent_chat_no_images": "该智能体不接收图片", "ui.agent_chat_no_picture": "剪贴板上没有图片", "ui.agent_chat_no_tool_call": "模型没有使用 SolidCraft 的工具,因此设计没有更改。请选择支持工具调用的模型;参见智能体聊天指南中的“本地模型”。", + "ui.agent_chat_node_too_old": "Node.js {version} 版本过旧,无法运行此代理。请安装 Node.js 20.10 或更新版本,然后点击刷新。", "ui.agent_chat_none_found": "未找到编程智能体。请安装以下之一,然后点击刷新:", "ui.agent_chat_none_found_short": "未找到智能体", "ui.agent_chat_not_installed": "未安装", @@ -3821,9 +4551,12 @@ "ui.agent_chat_queued_stopped": "已排队(已停止,未发送)", "ui.agent_chat_refresh": "刷新", "ui.agent_chat_refused": "不允许智能体执行:{reason}", + "ui.agent_chat_reinstall": "{agent} 已安装({program}),但 SolidCraft 检查时它没有启动:{error}\n它的安装可能不完整,或是为另一种计算机准备的。请用 `{install}` 重新安装,确认它能在终端中显示版本号,然后点击刷新。", "ui.agent_chat_remove": "从队列中移除", "ui.agent_chat_remove_file": "从这条消息中移除", "ui.agent_chat_remove_imported": "从这条消息中移除;零件仍保留在设计中(撤销可将其删除)", + "ui.agent_chat_reply_cut_off": "回复在完成前达到了长度上限,可能不完整。请让智能体继续,或请它回答得更简短。", + "ui.agent_chat_reply_declined": "模型拒绝回答这条消息。", "ui.agent_chat_retry": "重试", "ui.agent_chat_right": "右侧", "ui.agent_chat_save": "保存", @@ -3832,7 +4565,7 @@ "ui.agent_chat_send_now_tip": "停止智能体当前的步骤,并接着发送这条消息(Ctrl+Enter)", "ui.agent_chat_setup_body": "SolidCraft 会与安装在此计算机上的编程代理通信。请在“首选项 › AI”中选择一个。", "ui.agent_chat_setup_title": "设置助手", - "ui.agent_chat_side": "智能体聊天位置", + "ui.agent_chat_side": "停靠聊天", "ui.agent_chat_signed_in": "已登录", "ui.agent_chat_state_auth": "需要登录", "ui.agent_chat_state_busy": "工作中…", @@ -3851,7 +4584,7 @@ "ui.agent_chat_undone": "(已撤销)", "ui.agent_chat_view_attached": "已附加视图", "ui.agent_chat_waiting": "等待您的回复", - "ui.agent_cursor": "代理光标", + "ui.agent_cursor": "代理指针", "ui.agent_cursor_speed": "代理光标速度", "ui.agent_off_thread": "代理运行命令时保持窗口响应", "ui.agent_off_thread_note": "代理(来自 AI 面板或 MCP 客户端)的耗时命令在窗口之外计算:运行时仍可旋转和查看视图,并可在视图中的提示上停止它。关闭:每条命令在窗口线程上运行,窗口会等待其完成。", @@ -3882,24 +4615,29 @@ "ui.ai_copy_suffix": "副本", "ui.ai_custom_url": "自定义 URL", "ui.ai_default": "默认", + "ui.ai_edit": "编辑", + "ui.ai_edit_agent_title": "编辑智能体", + "ui.ai_edit_gone": "此智能体已被移除,没有可保存的内容。", + "ui.ai_edit_tip": "更改此智能体的名称、命令或端点。已保存的密钥保持隐藏。", "ui.ai_http_busy": "端点繁忙或已达上限,请稍后再试", "ui.ai_http_key": "端点拒绝了密钥:请在“首选项 > AI”中检查", "ui.ai_http_not_found": "找不到该端点或模型:请检查基础 URL 和模型名称", "ui.ai_http_too_large": "对话对此端点来说过大,请开始新的聊天", "ui.ai_key": "API 密钥", "ui.ai_key_hint": "可选;保存在系统钥匙串中", + "ui.ai_key_keep_hint": "留空以保留已保存的密钥", "ui.ai_key_needs_https": "密钥只会通过 HTTPS 发送,或发送到本机。", "ui.ai_key_note": "保存在系统钥匙串中,绝不保存在 SolidCraft 的设置里。本地服务器可留空。", "ui.ai_keychain_error": "系统钥匙串拒绝:{error}", "ui.ai_kind": "类型", - "ui.ai_mode_all": "全部允许", + "ui.ai_mode_all": "执行所有操作", "ui.ai_mode_all_note": "不再询问。崩溃报告仍不可访问,文件夹限制仍然有效。", "ui.ai_mode_all_warning": "智能体可以不经询问保存、覆盖、导出和替换你的设计。只在你信任的智能体和已保存的设计上使用。", - "ui.ai_mode_ask": "每次询问", + "ui.ai_mode_ask": "先询问", "ui.ai_mode_ask_note": "对设计的每项更改和每个文件操作都要等待你的允许。", - "ui.ai_mode_edits": "自动允许模型编辑", + "ui.ai_mode_edits": "允许编辑", "ui.ai_mode_edits_note": "建模命令无需询问即可运行;保存、打开、导出等文件操作或破坏性操作仍会询问。", - "ui.ai_mode_global": "按上方设置", + "ui.ai_mode_global": "与上方相同", "ui.ai_model": "模型", "ui.ai_model_hint": "qwen3:14b", "ui.ai_modes_scope": "这些设置适用于 SolidCraft 的工具。智能体自己的工具(它的 shell、文件编辑)遵循智能体自己的模式;如果智能体提供模式,可在聊天面板标题栏中选择。", @@ -3914,14 +4652,18 @@ "ui.ai_permissions": "权限", "ui.ai_preset": "预设", "ui.ai_protocol": "协议", + "ui.ai_reasoning_effort": "推理强度", + "ui.ai_reasoning_effort_field_hint": "留空 = 服务商默认", + "ui.ai_reasoning_effort_hint": "可选。将作为 `reasoning_effort` 发送给端点;各服务商接受的值不同(例如 `low`、`high` 或 `max`)。您在此设置的值绝不会被 SolidCraft 替换。留空则不发送任何内容,沿用服务商默认值。", "ui.ai_remove": "移除", "ui.ai_request_timed_out": "模型用时超过 {seconds} 秒。可在“首选项 › 助手”中调高此端点的请求超时。", "ui.ai_request_timeout": "请求超时", "ui.ai_request_timeout_hint": "对此端点的一次模型请求最多可用的时间,30 秒到 1 小时。本地模型较慢时请调高。", "ui.ai_reset": "重置", + "ui.ai_save": "保存", "ui.ai_settings": "AI 设置…", "ui.ai_show_features": "显示 AI 功能", - "ui.ai_show_features_note": "智能体聊天:一个面板,由你已在使用的编程智能体或你选择的模型端点处理打开的设计。关闭后:没有 AI 按钮、快捷键、菜单项或面板,也不会查找或启动任何程序。", + "ui.ai_show_features_note": "关闭后将隐藏所有助手功能,且不会启动任何内容。下方所有选项都会变灰。\n\n智能体聊天:一个面板,由你已在使用的编程智能体或你选择的模型端点处理打开的设计。关闭后:没有 AI 按钮、快捷键、菜单项或面板,也不会查找或启动任何程序。", "ui.ai_switch_tip": "更改此对话的智能体", "ui.ai_test": "测试", "ui.ai_test_acp_ok": "已响应:{agent}", @@ -3955,7 +4697,7 @@ "ui.ai_tool_sum_then": "{first},然后 {next}", "ui.ai_tool_unfold": "点击显示返回内容", "ui.ai_tool_waiting": "等待中", - "ui.ai_toolbar_button": "在工具栏显示按钮", + "ui.ai_toolbar_button": "应用栏中的助手按钮", "ui.ai_toolbar_button_note": "工具栏右端的 AI 按钮。Ctrl+Shift+A 和视图菜单仍可打开面板。", "ui.ai_undo_tip": "将智能体为此消息所做的全部更改一步撤销", "ui.ai_url_hint": "https://example.com/v1", @@ -4002,11 +4744,14 @@ "ui.centerline": "中心线", "ui.chain": "链", "ui.chamfer": "倒角", + "ui.chamfer_angle": "倒角角度", + "ui.chamfer_depth": "倒角深度", "ui.chamfer_type": "倒角类型", "ui.change_workspace": "更改工作区", "ui.circle": "圆", "ui.circular_pattern": "圆形阵列", "ui.clear": "清除", + "ui.clear_print_face": "清除打印底面", "ui.clear_recent": "清除最近", "ui.clear_the_selection": "清除选择", "ui.click_selects_whole_bodies": "单击选择整个实体", @@ -4031,10 +4776,16 @@ "ui.colour_vision_sample": "示例", "ui.colour_vision_tritan": "蓝色觉异常(Tritan)", "ui.colour_vision_tritan_tip": "蓝色感知较弱或缺失时使用", + "ui.comb_length": "梳长", + "ui.comb_length_tip": "梳齿的长度:自动长度的倍数。自动长度使最长的梳齿为所示曲线尺寸的五分之一。", + "ui.comb_teeth": "梳齿数", + "ui.comb_teeth_tip": "每个梳的梳齿数,沿曲线均匀分布。梳齿越多,越能看清曲率如何变化。", "ui.combine": "组合", "ui.coming_later": "即将推出", "ui.command_done": "{command} 完成", "ui.command_palette_hint": "输入命令,例如 {example} — 或按 S 搜索", + "ui.components_from_bodies_hint": "在活动组件下,为每个选定实体创建一个以该实体命名的组件。", + "ui.components_from_bodies_required": "请至少选择一个实体。", "ui.concentric": "同心", "ui.cone": "圆锥体", "ui.conic_curve": "圆锥曲线", @@ -4047,15 +4798,30 @@ "ui.construction.contact_hint": "切线:先选圆/圆弧或开放样条曲线/圆锥曲线,再选接点(自由曲线仅支持端点)", "ui.construction.external_hint": "切线:依次选择圆或圆弧、外部点和所需解", "ui.construction.free_hint": "构造直线:单击两点;右键单击重新开始", + "ui.construction.normal_needs_length": "无限直线始终是构造线:输入长度以绘制普通直线", "ui.construction.point_hint": "构造直线:单击要经过的点", "ui.construction.reference_hint": "构造直线:先选直线,再选一点;右键单击更换参照", "ui.construction.ribbon_label": "辅助线", + "ui.construction.side_hint": "构造直线:单击直线延伸的一侧;右键单击重新开始", "ui.context_menu": "上下文菜单", + "ui.continuity_crease": "折痕", + "ui.continuity_curvature": "曲率", + "ui.continuity_curvature_change": "曲率变化", + "ui.continuity_curvature_change_tip": "曲率变化 (G3):曲率在接缝处的变化也是平滑的。", + "ui.continuity_curvature_tip": "曲率连续 (G2):反射平滑穿过,没有折痕。", "ui.continuity_g0": "G0 折痕", "ui.continuity_g1": "G1 相切", "ui.continuity_g2": "G2 曲率", "ui.continuity_gap": "缝隙", + "ui.continuity_position": "位置", + "ui.continuity_position_tip": "位置 (G0):曲面相接,但接缝处有折痕。", + "ui.continuity_smooth_curvature_change": "平滑曲率变化", + "ui.continuity_smooth_curvature_change_tip": "平滑曲率变化 (G4):连曲率的变化方式在接缝处也平滑延续。", + "ui.continuity_tangent": "相切", + "ui.continuity_tangent_tip": "相切 (G1):没有折痕,但曲率在接缝处突变。", "ui.copy": "复制", + "ui.copy_details": "复制详细信息", + "ui.copy_details_tip": "复制完整消息,以便查找或报告。", "ui.corner": "角", "ui.corners": "角点", "ui.cosmetic_thread_markings": "装饰螺纹标记", @@ -4077,6 +4843,8 @@ "ui.dark": "深色", "ui.default_modelling_orientation": "默认建模方向", "ui.delete": "删除", + "ui.delete_select_first": "请先选择要删除的内容:特征、实体、组件或草图几何", + "ui.dependents_select_first": "请先选择要列出其依赖项的对象", "ui.depth": "深度", "ui.design": "设计", "ui.design_properties.author": "作者", @@ -4091,6 +4859,40 @@ "ui.design_properties.project": "项目", "ui.design_properties.revision": "版本", "ui.design_saved": "已保存到 {path}", + "ui.details_access_caption": "面显示刀具能否从所选方向到达它们。", + "ui.details_angle": "角度", + "ui.details_continuity_caption": "编辑所选接缝。其他接缝保留各自的设置。", + "ui.details_continuity_stale": "先前的几何体:请重新运行分析,以编辑此接缝或使其适合视图。", + "ui.details_copy_list": "复制列表", + "ui.details_curvature": "曲率容差", + "ui.details_curvature_caption": "面按其局部曲率半径着色。", + "ui.details_direction": "刀具方向", + "ui.details_draft_caption": "面按其与脱模方向的夹角着色。", + "ui.details_edit_seam": "编辑接缝", + "ui.details_fixture": "界面组件示例 — 仅含示例数据", + "ui.details_fixture_caption": "使用说明性数值的界面组件示例;这不是模型的分析结果。", + "ui.details_fixture_problem": "含问题的检查结果示例", + "ui.details_fixture_readout": "测量值示例", + "ui.details_flip": "翻转", + "ui.details_gap": "间隙", + "ui.details_hatch": "为切割面添加剖面线", + "ui.details_jump": "曲率突变", + "ui.details_key": "图例", + "ui.details_offset": "偏移", + "ui.details_plane": "平面", + "ui.details_pull": "脱模方向", + "ui.details_radius": "半径", + "ui.details_readout": "读数", + "ui.details_samples": "采样数", + "ui.details_seam": "{body} · 边 {edge}", + "ui.details_settings": "设置", + "ui.details_sharp_gap": "尖锐或有间隙", + "ui.details_show_all": "显示全部 {count} 项", + "ui.details_smooth": "光顺", + "ui.details_stripes": "条纹", + "ui.details_target": "使几何体适合视图", + "ui.details_worst_seams": "连续性最差的接缝", + "ui.details_zebra_caption": "反射条纹显示面之间连接的光顺程度。", "ui.diameter": "直径", "ui.dimension": "尺寸", "ui.direct_interaction": "直接交互", @@ -4135,39 +4937,78 @@ "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", "ui.edit_in_place_wait": "请等待设计中正在运行的操作完成", "ui.edit_section_analysis": "编辑截面分析", + "ui.edit_sketch_empty": "没有可编辑的草图", "ui.ellipse": "椭圆", "ui.emboss_wrap_note": "与受支持圆柱相切的正交线轮廓会自动缠绕。选择一个壁以指定目标。", + "ui.end": "末端", "ui.end_radius": "结束半径", "ui.end_scale": "末端缩放", + "ui.ends": "端部", "ui.entities": "实体", "ui.equal": "相等", "ui.equation_end": "结束", "ui.equation_explicit": "显式", "ui.equation_form": "形式", "ui.equation_note": "变量是不带单位的数:sin(t) 按弧度计算。不带单位的结果采用设计的单位。", + "ui.equation_note_range": "变量与其范围一样是长度:可与长度参数混用,用于 sin() 时需除以一个长度。没有单位的结果采用设计的单位。", "ui.equation_parametric": "参数式", + "ui.equation_variable_unit": "变量使用范围的单位", "ui.equation_x_of_t": "x(t)", "ui.equation_y_of_t": "y(t)", "ui.equation_y_of_x": "y(x)", "ui.equivalent_radius": "等效半径", "ui.expand": "展开", + "ui.explode_needs_two_components": "爆炸图会将组件彼此分开,因此设计中需要两个或更多组件(新建组件、插入设计或由实体创建组件)", "ui.exportDxf": "导出 DXF…", "ui.export_ellipsis_keymap": "导出…", "ui.export_keymap_tip": "将按键、S 框收藏和工具栏导出为文件", "ui.extend": "延伸", + "ui.extent": "范围", "ui.extent_type": "延伸类型", "ui.extract_component": "提取到文件…", "ui.extract_design_changed": "选择文件时设计已更改。请重新开始提取到文件。", "ui.extract_done": "该组件现在是独立的设计,并已在此处链接。", "ui.extrude": "拉伸", "ui.extrude_auto_to_object": "拉伸到所选目标", - "ui.extrude_auto_to_object_tip": "在拉伸中选择轮廓后,选取其平面外的面、顶点或平行平面会将延伸类型切换为“到对象”", + "ui.extrude_auto_to_object_tip": "选择面、顶点或平行平面会将范围切换为到对象。", "ui.factor": "系数", + "ui.fade": "收尾", + "ui.fade_length": "收尾长度", "ui.feature_history": "特征历史", "ui.feature_options": "特征选项", "ui.features": "特征", "ui.file": "文件", "ui.fillet": "圆角", + "ui.fillet_corner_ball": "球面", + "ui.fillet_corner_ball_tip": "滚球球面的一部分,与每个圆角相切 (G1)。", + "ui.fillet_corner_curvature_tip": "曲率 (G2):平滑曲面片。角点沿每条边后退一个后退距离(未输入时为半径的 {factor} 倍),并用曲面片填充,反射穿过时没有折痕。", + "ui.fillet_corner_needs_constant": "平滑曲面片角点 (G2) 需要恒定半径和精确的半径拟合。", + "ui.fillet_corner_patch": "平滑曲面片", + "ui.fillet_corner_patch_tip": "曲率连续 (G2):角点沿每条边后退,并用曲面片填充,反射穿过时没有折痕。", + "ui.fillet_corner_tangent_tip": "相切 (G1):滚球角,滚球球面的一部分,与每个圆角相切。", + "ui.fillet_error_corner": "无法在此处构建平滑角点。请尝试其他后退距离,或相切角点。", + "ui.fillet_error_failed": "无法在这些边上构建此圆角。请尝试其他半径,或一次少倒几条边。", + "ui.fillet_error_setback_short": "对于此角点的面片,后退距离太短:从 {least} 起可以构建。请尝试更长的后退距离。", + "ui.fillet_error_too_large": "半径对这些边旁边的面来说太大。请尝试更小的半径,或将“面边界”设为“最大半径”。", + "ui.fillet_fit": "面边界", + "ui.fillet_fit_exact": "精确半径", + "ui.fillet_fit_needs_constant": "半径拟合需要恒定半径。", + "ui.fillet_fit_reduce": "最大半径", + "ui.fillet_fit_taper": "收窄半径", + "ui.fillet_fit_tip": "当半径大于边旁边的面所允许的大小时。\n精确半径:按给定的半径倒圆,否则不倒圆并说明原因。\n最大半径:用能容纳的最大半径倒每条边。\n收窄半径:保持半径,只在面不够的地方收窄圆角。", + "ui.fillet_options_tip": "相切链:同时倒圆与所选边平滑相连的边。\n预览:编辑时在视图中显示结果。", + "ui.fillet_setback": "后退距离", + "ui.fillet_setback_hint": "{factor} × 半径", + "ui.fillet_setback_least": "须大于 {least}", + "ui.fillet_setback_tip": "平滑角点曲面片开始的位置:从角点沿每条边的距离。默认值为半径的 {factor} 倍。必须大于最小后退距离(不后退时圆角相交之处;面相互垂直时即半径)。", + "ui.fillet_smooth_radius": "半径平滑变化", + "ui.fillet_turn": "转角", + "ui.fillet_turn_mitre": "斜接", + "ui.fillet_turn_swept": "旋转", + "ui.fillet_turn_tip": "两个圆角绕过它们之间尖锐的角边处,例如凸台根部的圆角绕过其竖直边。\n斜接:圆角继续延伸,直到以斜接相遇。\n旋转:圆角止于角边并绕它旋转,转角是与两者相切的圆环面。仅用于同一半径的圆角绕过笔直的凸角边时。", + "ui.fillet_type_choices_tip": "恒定半径:整条边一个半径。\n弦长:无论面以什么角度相交,圆角宽度都相同。\n可变半径:两端各一个半径,添加后沿边还有更多。\n曲率连续:与平面相接处反射没有折痕的截面 (G2)。\n样条:沿边的半径跟随您设置的控制半径。", + "ui.fillet_type_curvature": "曲率连续", + "ui.fillet_type_tip": "横跨边的截面。曲率连续:平面之间的曲率连续 (G2) 截面,反射从面平滑过渡到圆角,没有折痕。", "ui.filter_commands_or_keys": "筛选命令或按键", "ui.findInTimeline": "在时间线中查找", "ui.findInWindow": "在窗口中查找", @@ -4277,13 +5118,15 @@ "ui.hideOrigin": "隐藏原点", "ui.hidePlanes": "隐藏平面", "ui.hideProfile": "隐藏轮廓", - "ui.hide_origin_by_default": "默认隐藏原点", + "ui.hide_component_history": "隐藏其历史记录", + "ui.hide_origin_by_default": "在新设计中隐藏原点文件夹", "ui.hide_origin_note": "新设计开始时原点文件夹处于隐藏状态。显示或隐藏过原点的设计会保留自己的原点设置。", "ui.history_back": "后退一步", "ui.history_below_browser": "浏览器下方", "ui.history_edge_hint": "双击边缘", "ui.history_first": "转到开头", "ui.history_forward": "前进一步", + "ui.history_hide_hidden": "隐藏已隐藏的组件", "ui.history_hide_names": "隐藏名称", "ui.history_last": "转到末尾", "ui.history_marker_tip": "历史标记:拖动以回退模型;新特征将在此处添加", @@ -4293,10 +5136,12 @@ "ui.history_play_button_show": "显示播放按钮", "ui.history_play_finish_action": "请先完成当前操作,再播放历史", "ui.history_play_roll_back": "播放前请将历史标记向后移动", + "ui.history_show_hidden": "显示隐藏的组件", "ui.history_show_names": "显示名称", "ui.history_sketch_listed_under": "列在 {feature} 下", "ui.history_title": "历史", "ui.history_toggle_names": "显示或隐藏特征名称", + "ui.history_waits_for_editor": "撤销、重做和历史将等待特征编辑器打开", "ui.hole": "孔", "ui.hole_tap_type": "孔攻丝类型", "ui.hole_type": "孔类型", @@ -4312,7 +5157,9 @@ "ui.insert_design.saved_file": "{name} 有未保存的更改,因此插入的是其已保存的文件。请先保存,再使用“更新链接”导入这些更改。", "ui.insert_design.unsaved": "未保存的更改", "ui.inspect": "检查", + "ui.instances": "实例数", "ui.intersect": "相交", + "ui.iso_4753": "ISO 4753", "ui.isolate": "隔离", "ui.join": "连接", "ui.joint_play": "▶ 播放", @@ -4320,12 +5167,14 @@ "ui.joints": "关节", "ui.keyboard_shortcuts": "键盘快捷键", "ui.language": "语言", + "ui.lasso_select": "套索(徒手圈选:选择完全在圈内的对象)", "ui.layout_compact": "紧凑", "ui.layout_floating": "浮动", "ui.length": "长度", "ui.length_decimals": "长度小数位", "ui.light": "浅色", "ui.line": "直线", + "ui.line_arc_hint": "相切圆弧:单击圆弧的终点。再次停留在最后一点可切回直线;右键单击或按 Esc 结束", "ui.link_copies": "链接相同副本", "ui.link_copies_keep": "保留", "ui.link_copies_link": "链接", @@ -4413,7 +5262,9 @@ "ui.part_size_needs_a_part": "请选择已插入的标准零件(螺钉、螺母、垫圈或销)以更改其尺寸。要放大或缩小实体,请使用缩放。", "ui.part_size_shared": "重新生成零件并替换额外添加的特征。此零部件的所有实例都会更新。", "ui.paste": "粘贴", + "ui.patch_continuity_corner_tip": "补面沿每条边以所选的连续性与周围的面相接。在周围的面彼此以不同曲率相接的角上,补面在该处保持相切 (G1)。", "ui.path": "路径", + "ui.pattern_object_type_tip": "实体:在视图或浏览器中选取的实心形状,每个都会被整体复制。\n特征:历史中的步骤,例如拉伸或孔,在历史中或在其生成的面上选取;该步骤会被重复。\n草图两者都不是:请用草图自身的阵列或镜像重复其曲线,或先将其拉伸。", "ui.pattern_on_path": "路径阵列", "ui.perforate_margin_default": "与直径相同", "ui.perforate_pitch": "孔距", @@ -4428,7 +5279,7 @@ "ui.pitch": "螺距", "ui.placement": "放置", "ui.placement_handles": "放置手柄", - "ui.placement_handles_tip": "垫块、凸台或卡扣预览上的手柄:拖动标记在模型上移动,用转环旋转", + "ui.placement_handles_tip": "用于在模型上拖动特征的标记和用于旋转的圆环。", "ui.plane": "平面", "ui.plane_at_angle": "角度平面", "ui.plugins": "插件", @@ -4440,12 +5291,17 @@ "ui.plugins_skipped": "有 {count} 个文件夹无法读取。", "ui.plugins_version": "{version}", "ui.point": "点", + "ui.point_cloud_add_filter": "添加筛选…", "ui.point_cloud_auto_range": "自动范围", "ui.point_cloud_color_by": "着色方式", "ui.point_cloud_file_colors": "文件颜色", + "ui.point_cloud_filter_by": "筛选依据", "ui.point_cloud_height_high": "最高高度", "ui.point_cloud_height_low": "最低高度", + "ui.point_cloud_legend_filter": "在上方图例中显示或隐藏", "ui.point_cloud_no_file_colors": "文件中没有颜色", + "ui.point_cloud_pause": "暂停", + "ui.point_cloud_play": "播放", "ui.point_cloud_single_color": "单色", "ui.point_cloud_size": "点大小", "ui.point_cloud_units": "文件单位", @@ -4454,6 +5310,11 @@ "ui.polygon": "多边形", "ui.preferences": "首选项", "ui.press_a_key": "按一个键…", + "ui.print_face_body_not_sent": "此面所属的实体不会发送:请先将其添加到实体", + "ui.print_face_cleared": "{body}:已清除打印底面", + "ui.print_face_input": "打印底面", + "ui.print_face_pick": "选择实体的一个平面,将其设为打印底面", + "ui.print_face_set": "{body}:已设置打印底面;发送到切片软件时实体将放在此面上", "ui.profile": "轮廓", "ui.profile_plane": "轮廓平面", "ui.profiles": "轮廓", @@ -4470,6 +5331,7 @@ "ui.properties.inertia_y": "Iyx, Iyy, Iyz", "ui.properties.inertia_z": "Izx, Izy, Izz", "ui.properties.measuring": "正在测量…", + "ui.properties.measuring_bodies": "正在测量… 第 {done} 个,共 {total} 个实体", "ui.properties.measuring_failed": "测量在完成前已停止。", "ui.properties.principal_axis": "主轴 {number}", "ui.properties.principal_moments": "主惯性矩", @@ -4537,6 +5399,7 @@ "ui.selectOther": "选择其他…", "ui.selectTangentChain": "选择相切链", "ui.select_all": "全选", + "ui.select_components_by_face": "选择组件(单击面即选择其所属组件)", "ui.selection": "选择", "ui.selection_modifiers": "选择修饰键", "ui.selection_shift_add_only": "Shift+点击仅添加、不取消选择", @@ -4562,6 +5425,7 @@ "ui.showDimension": "显示尺寸", "ui.showOrigin": "显示原点", "ui.showPlanes": "显示平面", + "ui.show_component_history": "显示其历史记录", "ui.show_constraints": "约束", "ui.show_construction_geometries": "构造几何图元", "ui.show_dimensions": "尺寸", @@ -4576,8 +5440,15 @@ "ui.sketch_intersect_geometry": "几何体", "ui.sketch_intersect_projection_link": "投影链接", "ui.sketch_intersect_selection_filter": "选择过滤器", + "ui.sketch_keys_only": "草图中不使用模型快捷键", + "ui.sketch_keys_only_tip": "编辑草图时,只有草图快捷键和在任何地方都可用的快捷键会生效;E 或 F 等模型快捷键不起作用,因此误按的按键不会关闭复杂的草图。", "ui.sketch_modifiers": "草图修饰键", "ui.sketch_project_geometry": "几何体", + "ui.sketch_report.all_constrained": "全部已完全约束。", + "ui.sketch_report.dof": "自由度", + "ui.sketch_report.loose": "未完全约束", + "ui.sketch_report.status": "状态", + "ui.sketch_report.title": "草图报告", "ui.sketch_scale": "草图比例", "ui.sketches": "草图", "ui.slice": "切片", @@ -4588,7 +5459,7 @@ "ui.slicer_no_response": "{slicer} 未在规定时间内响应。文件已保存到 {path}:切片软件启动后请再次发送。", "ui.slicer_resend_hint": "再次发送会替换切片软件中已打开的文件。", "ui.slicer_single_instance": "在已运行的切片软件中打开文件", - "ui.slicer_single_instance_tip": "PrusaSlicer、SuperSlicer 和 Cura 会在已打开的窗口中加载文件,而不是再启动一个。其他切片软件按原样启动。PrusaSlicer 3.0 始终如此:其启动器无法以其他方式接收文件。", + "ui.slicer_single_instance_tip": "适用于将文件加载到正在运行的窗口中的切片软件。", "ui.slicer_starting": "正在启动 {slicer}…", "ui.slicer_still_starting": "仍在等待 {slicer} 启动。没有发送其他内容。", "ui.slicer_stl_fallback": "无法写入 3MF,因此发送的是 STL。", @@ -4607,8 +5478,8 @@ "ui.start": "开始", "ui.start_over": "重新开始", "ui.start_page": "起始页", - "ui.step_values": "使用方向键和滚轮调整数值", - "ui.step_values_tip": "在正在输入的数值框中,上下方向键和框上的鼠标滚轮可将数字增减 1(Shift:10,Alt:0.1)。表达式保持不变。", + "ui.step_values": "使用箭头和滚轮调整数值", + "ui.step_values_tip": "在数值字段上使用上/下箭头或滚轮可更改数值。", "ui.stitch_tolerance_hint": "严格", "ui.stretch": "伸展", "ui.supersampling": "超级采样 (SSAA)", @@ -4674,19 +5545,31 @@ "ui.view_angles": "视图角度", "ui.view_angles_convention": "绕向上轴的角度(度)。偏航 0° 为前视图,90° 为左视图,−90° 为右视图,180° 为后视图;俯仰 90° 为俯视图;滚转为正时,模型在屏幕上顺时针旋转。", "ui.view_angles_help": "在方向小部件下方显示视图的俯仰、偏航和滚转角(度)以及投影方式。单击读数可输入精确角度。", + "ui.view_angles_lock": "锁定{axis}", "ui.view_angles_ortho": "正交", "ui.view_angles_persp": "透视", "ui.view_angles_pitch": "俯仰", "ui.view_angles_readout": "俯仰 {pitch} · 偏航 {yaw} · 滚转 {roll}", "ui.view_angles_roll": "滚转", + "ui.view_angles_unlock": "解锁{axis}", "ui.view_angles_yaw": "偏航", + "ui.view_angles_zero": "将{axis}设为 0°", "ui.view_centre": "视图中心", "ui.viewport_status_clear": "关闭{name}", "ui.viewport_status_clear_hint": "关闭{name} · Esc", + "ui.viewport_status_edges": "{count} 条边", + "ui.viewport_status_from": "从 {direction}", "ui.viewport_status_key": "显示{name}的图例", "ui.viewport_status_minimum_radius": "最小半径", "ui.viewport_status_pairs": "{count} 对", + "ui.viewport_status_section_hatch": "{setting} · 填充线", + "ui.viewport_status_section_plane": "当前平面", + "ui.viewport_status_section_tilted": "倾斜 · {offset}", "ui.viewport_status_stripes": "{count} 条条纹", + "ui.viewport_status_summary_clear": "全部关闭", + "ui.viewport_status_summary_heading": "此视图中", + "ui.viewport_status_summary_label": "{name} 和其他 {count} 项", + "ui.viewport_status_summary_more": "+{count}", "ui.viewport_theme_follow": "跟随主题", "ui.visual_shaded_hidden_edges": "带隐藏边的着色", "ui.visual_shaded_with_edges": "带边着色", @@ -4722,11 +5605,13 @@ "update.available": "SolidCraft {version} 已发布", "update.button": "更新", "update.button_version": "更新到 {version}", - "update.check_automatically": "自动检查更新", + "update.check_automatically": "启动时及每天检查一次", + "update.check_for_updates": "检查更新", "update.check_now": "立即检查", + "update.check_unavailable": "此安装版本无法检查更新。", "update.checking": "正在检查…", "update.copy": "复制", - "update.dmg_opened": "磁盘映像已校验并打开:将 SolidCraft 拖到“应用程序”替换旧版本,然后重启 SolidCraft。", + "update.dmg_opened": "磁盘映像已校验并打开:退出 SolidCraft,将新的 SolidCraft 拖到“应用程序”替换旧版本,然后重新打开 SolidCraft。", "update.download": "下载", "update.download_open": "下载并打开", "update.downloading": "正在下载并校验… {done} / {total} MB", @@ -4770,6 +5655,7 @@ "web.open_link": "打开链接的设计?", "web.open_link_confirm": "有未保存的更改。要在新标签页中打开链接的设计吗?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 选择 · Enter / Tab 补全 · Esc 关闭", + "↑ ↓ choose · Enter applies this value": "↑ ↓ 选择 · Enter 应用此值", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 选择 · Enter 按原样应用 · Esc 关闭", "⌘Enter continues on GitHub.": "按⌘Enter在GitHub中继续。" } diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 3e323724e..fd7ca921a 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -18,8 +18,11 @@ struct U { depth: vec4, // x = 1: reversed depth (1 near, 0 far); y, z: the faces' push (`FACE_BIAS`) tint: vec4, // xyz added to a whole hovered body's colour before lighting sel: vec4, // xyz a whole selected body's colour before lighting + // the section hatch colours by part (`solidcraft_render::hatch`), the first the cap's own + hatch: array, 3>, product_lights_meta: vec4, // explicit preview flag and bounded count product_lights: array,84>, // position/kind, radiance, axis/cone, attenuation + sky: vec4, // xyz = world up; w = 1: shade in linear light with a sky fill (#7974) }; fn reversed() -> bool { @@ -34,21 +37,31 @@ fn near_z(c: vec4) -> f32 { @group(1) @binding(2) var acc_t: texture_2d; @group(2) @binding(0) var ao_depth: texture_2d; +@group(2) @binding(1) var ao_map: texture_2d; fn clipped(p: vec3) -> bool { return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w; } @group(0) @binding(0) var u: U; -// The scene's colours, 2048 entries to a row: an R32Uint texture rather than a storage buffer, -// so the viewport draws on WebGL2 (which has no storage buffers) as well. +// The scene's colours, 2048 entries to a row: an Rg32Uint texture rather than a storage buffer, +// so the viewport draws on WebGL2 (which has no storage buffers) as well. Each entry is the +// colour's bytes, then 1 + the section hatch of the body it colours (0: the cap's own). @group(0) @binding(1) var pal: texture_2d; -/// The colour at palette entry `i`, as byte/255 (the old Unorm8x4 conversion, bit for bit). -fn palette(i: u32) -> vec4 { - let v = textureLoad(pal, vec2(i32(i & 2047u), i32(i >> 11u)), 0).x; +fn palette_entry(i: u32) -> vec2 { + return textureLoad(pal, vec2(i32(i & 2047u), i32(i >> 11u)), 0).xy; +} + +/// A palette entry's colour bytes as byte/255 (the old Unorm8x4 conversion, bit for bit). +fn unpack_color(v: u32) -> vec4 { return vec4(f32(v & 255u), f32((v >> 8u) & 255u), f32((v >> 16u) & 255u), f32((v >> 24u) & 255u)) / 255.0; } +/// The colour at palette entry `i`. +fn palette(i: u32) -> vec4 { + return unpack_color(palette_entry(i).x); +} + fn to_linear(c: vec3) -> vec3 { return select(c, pow((c + vec3(0.055)) / vec3(1.055), vec3(2.4)), c > vec3(0.04045)); } @@ -61,10 +74,12 @@ fn out_color(c: vec4) -> vec4 { } struct TOut { - @builtin(position) pos: vec4, + @invariant @builtin(position) pos: vec4, @location(0) n: vec3, @location(1) c: vec4, @location(2) wp: vec3, + // 1 + the section hatch of the body (0: the cap's own), from the palette. + @location(3) @interpolate(flat) h: u32, }; @vertex @@ -72,7 +87,9 @@ fn vs_tri(@location(0) p: vec3, @location(1) n: vec3, @location(2) c: var o: TOut; o.pos = u.vp * vec4(p, 1.0); o.n = n; - o.c = palette(c); + let e = palette_entry(c); + o.c = unpack_color(e.x); + o.h = e.y; o.wp = p; return o; } @@ -94,7 +111,9 @@ fn vs_tri_inst( var o: TOut; o.pos = u.vp * vec4(wp, 1.0); o.n = vec3(dot(r0.xyz, n), dot(r1.xyz, n), dot(r2.xyz, n)); - o.c = palette(c); + let e = palette_entry(c); + o.c = unpack_color(e.x); + o.h = e.y; o.wp = wp; return o; } @@ -106,9 +125,10 @@ fn vs_tri_inst( /// stores every vertex's outputs: more of them cost more than the triangles' shared vertices /// save). struct FOut { - @builtin(position) pos: vec4, + @invariant @builtin(position) pos: vec4, @location(0) rp: vec3, @location(1) c: vec4, + @location(2) @interpolate(flat) h: u32, }; @vertex @@ -124,7 +144,9 @@ fn vs_tri_inst_flat( var o: FOut; o.pos = u.vp * vec4(wp, 1.0); o.rp = wp - u.eye.xyz; - o.c = palette(c); + let e = palette_entry(c); + o.c = unpack_color(e.x); + o.h = e.y; return o; } @@ -140,6 +162,7 @@ fn flat_fragment(i: FOut, front: bool) -> TOut { o.pos = i.pos; o.n = n; o.c = i.c; + o.h = i.h; o.wp = i.rp + u.eye.xyz; return o; } @@ -208,6 +231,12 @@ fn fs_ao_depth_flat(i: FOut, @builtin(front_facing) front: bool) -> AoDepth { return opaque_depth(t, front); } +@fragment +fn fs_ao_term_flat(i: FOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { + let t = flat_fragment(i, front); + return ao_term(t, front); +} + /// Opaque model surfaces: cut by the section plane/// Opaque model surfaces: cut by the section plane, the inside shows as a flat cap colour. @fragment fn fs_solid(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { @@ -215,13 +244,43 @@ fn fs_solid(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4 @location(0) vec4 { + if (clipped(i.wp)) { discard; } + return vec4(0.0); +} + +@fragment +fn fs_clip_flat(i: FOut) -> @location(0) vec4 { + if (clipped(i.rp + u.eye.xyz)) { discard; } + return vec4(0.0); +} + +/// Faces where the section plane is outside every closed body (`Cut::rest`): a back face seen +/// there is the inside of an open body (a surface body, a solid with faces left out), lit as it +/// is without a section rather than hatched, since there is no cut face to show. +@fragment +fn fs_solid_open(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { + let c = solid(i, true); + return c; +} + +@fragment +fn fs_solid_open_flat(i: FOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { + let t = flat_fragment(i, front); + let c = solid(t, true); + return c; +} + struct CutOut { @location(0) c: vec4, @builtin(frag_depth) depth: f32, }; -/// The section cap (the inside seen through the cut, drawn on the far walls' back faces where -/// they are the visible surface) again, at the depth of the section plane rather than of the +/// The section cap (where the section plane lies inside a body, drawn on the far walls' back +/// faces) again, at the depth of the section plane rather than of the /// far wall, so the cut face hides what lies inside the body instead of showing it like a /// pane of glass. @fragment @@ -266,11 +325,19 @@ fn solid(i: TOut, front: bool) -> vec4 { if (clipped(i.wp)) { discard; } if (!front && length(u.clip.xyz) > 0.5) { // The cut face in its body's colour ("from component" colouring), tinted toward the - // cap colour so it reads as a cut, hatched at 45 degrees on screen; with the hatch off + // cap colour so it reads as a cut, hatched at 45 degrees on screen; by part, toward the + // body's own hatch colour and at its angle (45 or 135 degrees). With the hatch off // (`u.cap.a` 0), plain in the body's own colour. if (u.cap.a < 0.5) { return out_color(vec4(i.c.rgb, 1.0)); } - let base = mix(i.c.rgb, u.cap.rgb, 0.35); - let h = fract((i.pos.x + i.pos.y) / 9.0); + var tint = u.cap.rgb; + var turn = 1.0; + if (i.h > 0u) { + let k = i.h - 1u; + tint = u.hatch[min(k >> 1u, 2u)].rgb; + turn = select(1.0, -1.0, (k & 1u) == 1u); + } + let base = mix(i.c.rgb, tint, 0.35); + let h = fract((i.pos.x + turn * i.pos.y) / 9.0); return out_color(vec4(select(base, base * 0.6, h < 0.22), 1.0)); } if (u.ana.x > 0.5 && length(i.n) > 0.5) { @@ -307,11 +374,89 @@ fn opaque_depth(i: TOut, front: bool) -> AoDepth { return AoDepth(depth, bitcast(depth)); } +/// The term for an opaque surface's fragment, on the prepass's depth. A section's cut face has none. +fn ao_term(i: TOut, front: bool) -> vec4 { + if (clipped(i.wp) || length(i.n) < 0.5) { discard; } + if (!front && length(u.clip.xyz) > 0.5) { return vec4(1.0); } + return vec4(occlusion_term(i)); +} + +@fragment +fn fs_ao_term(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { + return ao_term(i, front); +} + +@vertex +fn vs_ao_blur(@builtin(vertex_index) v: u32) -> @builtin(position) vec4 { + let p = vec2(f32((v << 1u) & 2u), f32(v & 2u)); + return vec4(p * 2.0 - 1.0, 0.0, 1.0); +} + +/// The depth map at `p`, reading 0 near and 1 far whichever way the buffer runs. +fn map_depth(p: vec2) -> f32 { + let at = clamp(p, vec2(0), vec2(textureDimensions(ao_depth)) - vec2(1)); + let d = bitcast(textureLoad(ao_depth, at, 0).x); + return select(d, 1.0 - d, reversed()); +} + +/// The raw term (`ao_map` in this pass) averaged over a 4 x 4 window, which holds every turn of +/// [`ao_turn`]'s pattern once. A neighbour counts when it lies on this pixel's plane, the slope +/// taken from the nearer side across each axis, so no surface's shade crosses an edge. +@fragment +fn fs_ao_blur(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = vec2(pos.xy); + let d = map_depth(c); + if (d >= 1.0) { return vec4(1.0); } + let left = d - map_depth(c + vec2(-1, 0)); + let right = map_depth(c + vec2(1, 0)) - d; + let above = d - map_depth(c + vec2(0, -1)); + let below = map_depth(c + vec2(0, 1)) - d; + let dx = select(right, left, abs(left) < abs(right)); + let dy = select(below, above, abs(above) < abs(below)); + let tolerance = 1.5 * (abs(dx) + abs(dy)) + 1e-6; + let last = vec2(textureDimensions(ao_map)) - vec2(1); + var sum = 0.0; + var weight = 0.0; + for (var y = -2; y < 2; y = y + 1) { + for (var x = -2; x < 2; x = x + 1) { + let p = c + vec2(x, y); + let s = map_depth(p); + if (s < 1.0 && abs(s - (d + dx * f32(x) + dy * f32(y))) <= tolerance) { + sum = sum + textureLoad(ao_map, clamp(p, vec2(0), last), 0).x; + weight = weight + 1.0; + } + } + } + return vec4(sum / max(weight, 1.0)); +} + +/// A pixel's turn of the sample pattern: every 4 x 4 window holds each of 16 turns once. +fn ao_turn(pos: vec2) -> f32 { + let x = u32(pos.x) & 3u; + let y = u32(pos.y) & 3u; + // WGSL won't mix shifts and `|` without parentheses; naga takes it, browsers refuse it (#11080). + let v = (((x ^ y) & 1u) << 3u) | ((y & 1u) << 2u) | (((x ^ y) >> 1u) << 1u) | (y >> 1u); + return (f32(v) + 0.5) / 16.0; +} + +/// The lit pass's occlusion: the blurred term where this point falls in the map, whatever the +/// window's viewport offset and supersampling. +fn occlusion(i: TOut) -> f32 { + let size = vec2(textureDimensions(ao_map)); + // The maps are 1 × 1 stand-ins until a frame draws into them (the product preview draws no + // prepass, and AO off releases them): they tell nothing, so leave the surface unoccluded. + if (u.ao.x <= 0.0 || length(i.n) < 0.5 || size.x < 2 || size.y < 2) { return 1.0; } + let q = u.vp * vec4(i.wp, 1.0); + if (q.w <= 0.0) { return 1.0; } + let uv = vec2(q.x / q.w * 0.5 + 0.5, 0.5 - q.y / q.w * 0.5); + return textureLoad(ao_map, clamp(vec2(uv * vec2(size)), vec2(0), size - vec2(1)), 0).x; +} + // Cosine-weighted hemisphere samples, the pattern turned by a different angle at each pixel. // Projecting the sample and a point one radius toward the eye supplies a depth range in both // orthographic and perspective views; distant foreground geometry cannot cast a dark halo onto // a background surface. -fn occlusion(i: TOut) -> f32 { +fn occlusion_term(i: TOut) -> f32 { let radius = u.ao.x; if (radius <= 0.0 || length(i.n) < 0.5) { return 1.0; } var n = normalize(i.n); @@ -325,10 +470,9 @@ fn occlusion(i: TOut) -> f32 { if (size.x < 2 || size.y < 2) { return 1.0; } // The same offsets at every pixel made each sample darken its own shifted copy of a nearby // part's outline: faint ghosts of the part where the radius is large on screen (#4167), - // stepped bands along contacts where it is small (#3407). Turned by interleaved gradient - // noise (Jimenez 2014), neighbouring pixels sample different points and the copies break up - // into an even grain. - let turn = fract(52.9829189 * fract(dot(i.pos.xy, vec2(0.06711056, 0.00583715)))); + // stepped bands along contacts where it is small (#3407). Turned, neighbouring pixels sample + // different points, the copies break up into grain, and the blur takes the grain out (#9327). + let turn = ao_turn(i.pos.xy); let t = tangent * cos(turn * 6.28318531) + bitangent * sin(turn * 6.28318531); let b = cross(n, t); // One comparison for both depth directions: depths read as 0 near / 1 far (mirrored when @@ -385,8 +529,13 @@ fn analysis(i: TOut, k: f32) -> vec4 { let r = reflect(-v, n); var side = cross(v, vec3(0.0, 0.0, 1.0)); if (length(side) < 1e-3) { side = vec3(1.0, 0.0, 0.0); } - let s = sin(dot(r, normalize(side)) * u.ana.y * 3.14159265); - let c = select(0.08, 0.95, s > 0.0); + let x = dot(r, normalize(side)); + let s = sin(x * u.ana.y * 3.14159265); + // A face whose normal lies in the upright plane through the view (every horizontal + // face) reflects straight ahead: its sideways part is zero, on the edge between a black + // and a white stripe, and rounding picked one or the other from frame to frame while + // the view turned (#2153). Straight ahead is white. + let c = select(0.08, 0.95, s > 0.0 || abs(x) < 1e-4); return out_color(vec4(vec3(c), 1.0)); } if (u.ana.x > 4.5) { @@ -507,6 +656,31 @@ fn lit(i: TOut, visibility: f32) -> vec4 { return lit_color(i, visibility, i.c); } +/// sRGB to linear light, exact (the straight segment too, which `to_linear` leaves out). +fn srgb_decode(c: vec3) -> vec3 { + return select(c / 12.92, pow((c + vec3(0.055)) / vec3(1.055), vec3(2.4)), c > vec3(0.04045)); +} + +fn srgb_encode(c: vec3) -> vec3 { + let l = clamp(c, vec3(0.0), vec3(1.0)); + return select(l * 12.92, 1.055 * pow(l, vec3(1.0 / 2.4)) - vec3(0.055), l > vec3(0.0031308)); +} + +/// The studio light summed in linear light, encoded once (#7974): the key and the eye fill as in +/// [`lit_color`], over a sky fill that grows as the face turns up, and the 4% every dielectric +/// reflects of that sky (a little more toward grazing), so a near-black face keeps a gradient. The sky +/// and the fill are what ambient occlusion (`visibility`) takes away. sRGB out. +fn sky_lit(base: vec3, n: vec3, diff: f32, fill: f32, visibility: f32) -> vec3 { + let up = dot(n, normalize(u.sky.xyz)) * 0.5 + 0.5; + let sky = mix(0.18, 0.42, up); + // Schlick's rise toward grazing, tempered so mid-tones only gain a soft rim. + let fresnel = 0.04 + 0.2 * pow(1.0 - fill, 5.0); + let albedo = srgb_decode(base); + // Scaled so light and mid-grey faces land near where the sRGB shading puts them. + let light = albedo * (0.41 * diff + (0.66 * sky + 0.2 * fill) * visibility) + vec3(fresnel * sky * visibility); + return srgb_encode(light); +} + /// [`lit`] in a colour of its own: a whole highlighted body is lit in its colour lifted by the /// hover amount, or in the selection colour, from the model's own plan triangles. fn lit_color(i: TOut, visibility: f32, base: vec4) -> vec4 { @@ -533,6 +707,9 @@ fn lit_color(i: TOut, visibility: f32, base: vec4) -> vec4 { let fill = max(dot(n, v), 0.0); let h = normalize(key + v); let spec = pow(max(dot(n, h), 0.0), 40.0) * 0.25; + if u.sky.w > 0.5 { + return out_color(vec4(min(sky_lit(base.rgb, n, diff, fill, visibility) + vec3(spec), vec3(1.0)), base.a)); + } let k = 0.42 + 0.38 * diff + 0.25 * fill - (0.42 + 0.25 * fill) * (1.0 - visibility); return out_color(vec4(min(base.rgb * k + vec3(spec), vec3(1.0)), base.a)); } @@ -625,7 +802,9 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3, @location( let sb = cb.xy / max(cb.w, 1e-6) * half; var dir = sb - sa; let len = length(dir); - if (len < 1e-6) { dir = vec2(1.0, 0.0); } else { dir = dir / len; } + // Intel OpenGL can miscompile vector/scalar division here (#8053). Scalar + // quotients keep the same direction and the fallback for a point. + if (len < 1e-6) { dir = vec2(1.0, 0.0); } else { dir = vec2(dir.x / len, dir.y / len); } let nrm = vec2(-dir.y, dir.x); // Two triangles: corners (t, side). var ts = array(0.0, 1.0, 1.0, 0.0, 1.0, 0.0); @@ -697,38 +876,96 @@ fn fs_line_all(i: LOut) -> @location(0) vec4 { return out_color(i.c); } -// Point clouds: each point is a round dot a few pixels across, facing the screen, depth-tested -// and written like the model's faces, so the model hides the points behind it and they hide it. -// The colour's alpha carries the dot's size (eighths of a pixel). +// Point clouds (`view/clouds.rs`): each point is a round dot a few pixels across, facing the +// screen, depth-tested and written like the model's faces, so the model hides the points behind +// it and they hide it. The cloud's style colours them by their own colour, a ramp or a palette, +// and shows only those whose filtered values lie in its ranges or sets. -struct POut { +struct Cloud { + style: vec4, // x: colour (0 own, 1 ramp, 2 palette), y: dot size (px), z, w: ramp range + filters: array, 4>, // x: kind (0 off, 1 range y…z, 2 whole values y + i for the bits i of w) +}; +@group(1) @binding(3) var cloud: Cloud; + +struct CIn { + @location(0) p: vec3, + @location(1) v: f32, + @location(2) f: vec4, + @location(3) rgb: vec4, +}; + +struct COut { @builtin(position) pos: vec4, - @location(0) c: vec4, - @location(1) wp: vec3, - @location(2) at: vec2, + @location(0) wp: vec3, + @location(1) v: f32, + @location(2) f: vec4, + @location(3) rgb: vec3, + @location(4) at: vec2, // the place on its disc + @location(5) @interpolate(flat) has: u32, }; @vertex -fn vs_point(@builtin(vertex_index) vi: u32, @location(0) p: vec3, @location(1) c: vec4) -> POut { +fn vs_cloud_dot(@builtin(vertex_index) vi: u32, i: CIn) -> COut { var xs = array(-1.0, 1.0, 1.0, -1.0, 1.0, -1.0); var ys = array(-1.0, -1.0, 1.0, -1.0, 1.0, 1.0); let at = vec2(xs[vi], ys[vi]); - let size = max(c.a * 255.0 / 8.0, 1.0); - let centre = u.vp * vec4(p, 1.0); - let half = u.screen.xy * 0.5; - var o: POut; - o.pos = vec4(centre.xy + at * size * 0.5 / half * centre.w, centre.z, centre.w); + let size = max(cloud.style.y, 1.0); + let centre = u.vp * vec4(i.p, 1.0); + var o: COut; + o.pos = vec4(centre.xy + at * size / u.screen.xy * centre.w, centre.z, centre.w); // Behind the eye: nothing. if (near_z(centre) < 0.0) { o.pos = vec4(0.0, 0.0, 0.0, -1.0); } - o.c = vec4(c.rgb, 1.0); - o.wp = p; + o.wp = i.p; + o.v = i.v; + o.f = i.f; + o.rgb = i.rgb.rgb; + o.has = u32(round(i.rgb.a * 255.0)); // Dots under two pixels are squares: a disc that small loses its centre pixel. o.at = at * select(1.0, 0.0, size < 2.0); return o; } +/// Whether filter `f` keeps the value `v`. +fn cloud_keeps(f: vec4, v: f32) -> bool { + if (f.x < 0.5) { return true; } + if (f.x < 1.5) { return v >= f.y && v <= f.z; } + let k = i32(round(v)) - i32(round(f.y)); + return k >= 0 && k < 32 && ((bitcast(f.w) >> u32(k)) & 1u) != 0u; +} + +fn cloud_ramp(t: f32) -> vec3 { + var stops = array, 5>( + vec3(40.0, 70.0, 200.0), vec3(30.0, 170.0, 230.0), vec3(60.0, 200.0, 90.0), + vec3(240.0, 220.0, 60.0), vec3(230.0, 70.0, 50.0)); + let k = clamp(t, 0.0, 1.0) * 4.0; + let j = min(u32(k), 3u); + return mix(stops[j], stops[j + 1u], k - f32(j)) / 255.0; +} + +fn cloud_palette(v: f32) -> vec3 { + var colours = array, 10>( + vec3(240.0, 140.0, 40.0), vec3(245.0, 205.0, 65.0), vec3(230.0, 65.0, 65.0), + vec3(165.0, 75.0, 190.0), vec3(65.0, 190.0, 115.0), vec3(75.0, 150.0, 220.0), + vec3(240.0, 120.0, 180.0), vec3(140.0, 105.0, 75.0), vec3(120.0, 215.0, 215.0), + vec3(190.0, 190.0, 80.0)); + if (v < -0.5) { return vec3(150.0, 160.0, 176.0) / 255.0; } + return colours[u32(round(v)) % 10u] / 255.0; +} + + @fragment -fn fs_point(i: POut) -> @location(0) vec4 { - if (clipped(i.wp) || dot(i.at, i.at) > 1.0) { discard; } - return out_color(i.c); +fn fs_cloud(o: COut) -> @location(0) vec4 { + var out = clipped(o.wp) || dot(o.at, o.at) > 1.0; + for (var k = 0u; k < 4u; k++) { + out = out || (((o.has >> k) & 1u) != 0u && !cloud_keeps(cloud.filters[k], o.f[k])); + } + if (out) { discard; } + var c = o.rgb; + let mode = cloud.style.x; + if ((o.has & 16u) != 0u && mode > 1.5) { + c = cloud_palette(o.v); + } else if ((o.has & 16u) != 0u && mode > 0.5) { + c = cloud_ramp((o.v - cloud.style.z) / max(cloud.style.w - cloud.style.z, 1e-12)); + } + return out_color(vec4(c, 1.0)); } diff --git a/assets/styles/ui/palettes.rs b/assets/styles/ui/palettes.rs index 201c45da7..e5bf23465 100644 --- a/assets/styles/ui/palettes.rs +++ b/assets/styles/ui/palettes.rs @@ -75,6 +75,7 @@ impl Tokens { font_compass: 13.5, font_subtitle: 15.0, font_intro: 16.0, + font_page_heading: 20.0, font_article_heading: 17.0, font_title: 22.0, font_display: 26.0, @@ -203,6 +204,11 @@ impl Tokens { dimension_driven: Color32::from_rgb(160, 90, 120), sketch_point_free: Color32::from_rgb(30, 90, 200), section_cap: Color32::from_rgb(214, 128, 72), + // A steel and a sage that tint a body about as strongly as the cap does and to within + // a few points of its lightness, so the cut stays calm, while staying apart from the + // cap, each other and the body in every colour vision mode (dark keeps them, as the + // cap). + section_hatch: [Color32::from_rgb(84, 138, 168), Color32::from_rgb(108, 180, 126)], dialog_bg: Color32::from_rgb(250, 251, 252), dialog_border: Color32::from_rgb(213, 219, 227), chip: Color32::from_rgb(38, 120, 218), @@ -226,6 +232,31 @@ impl Tokens { dialog_label: Color32::from_rgb(58, 70, 86), selected_ink: Color32::from_rgb(26, 80, 127), selected_bg: Color32::from_rgb(232, 241, 250), + figure_ground: Color32::from_rgb(247, 248, 250), + figure_line: Color32::from_rgb(111, 124, 143), + figure_highlight: Color32::WHITE, + figure_shadow: Color32::BLACK, + figure_face_top: Color32::from_rgb(255, 255, 255), + figure_face_left: Color32::from_rgb(228, 233, 240), + figure_face_right: Color32::from_rgb(201, 210, 222), + figure_card: Color32::from_rgb(255, 255, 255), + figure_white: Color32::WHITE, + figure_black: Color32::BLACK, + figure_accent: Color32::from_rgb(35, 110, 173), + figure_reference: Color32::from_rgb(138, 83, 0), + figure_axis_x: Color32::from_rgb(214, 69, 69), + figure_axis_y: Color32::from_rgb(46, 158, 91), + figure_axis_z: Color32::from_rgb(47, 111, 208), + figure_ok: Color32::from_rgb(47, 125, 91), + figure_warn: Color32::from_rgb(201, 138, 0), + figure_conflict: Color32::from_rgb(184, 74, 0), + pref_well: Color32::from_rgb(238, 241, 245), + pref_note: Color32::from_rgb(183, 74, 0), + pref_note_fill: Color32::from_rgb(251, 235, 221), + pref_on_accent: Color32::from_rgb(255, 255, 255), + pref_ok: Color32::from_rgb(39, 107, 44), + pref_ok_fill: Color32::from_rgb(229, 242, 230), + pref_disabled: Color32::from_rgb(138, 148, 163), timeline_item: Color32::WHITE, timeline_item_error: Color32::from_rgb(250, 220, 220), timeline_marker: Color32::from_rgb(70, 76, 88), @@ -241,6 +272,8 @@ impl Tokens { bend_up: Color32::from_rgb(30, 140, 50), bend_down: Color32::from_rgb(200, 90, 20), interference: Color32::from_rgb(235, 45, 40), + comb_envelope: Color32::from_rgb(130, 40, 175), + comb_teeth: Color32::from_rgb(215, 105, 0), continuity: [ Color32::from_rgb(0, 158, 115), Color32::from_rgb(0, 114, 178), @@ -345,6 +378,27 @@ impl Tokens { t.dialog_label = t.text; t.selected_ink = Color32::from_rgb(156, 199, 245); t.selected_bg = Color32::from_rgb(42, 70, 110); + t.figure_ground = Color32::from_rgb(28, 31, 38); + t.figure_line = Color32::from_rgb(163, 174, 194); + t.figure_face_top = Color32::from_rgb(107, 119, 144); + t.figure_face_left = Color32::from_rgb(81, 91, 114); + t.figure_face_right = Color32::from_rgb(57, 66, 86); + t.figure_card = Color32::from_rgb(47, 52, 62); + t.figure_accent = Color32::from_rgb(140, 190, 245); + t.figure_reference = Color32::from_rgb(232, 194, 74); + t.figure_axis_x = Color32::from_rgb(242, 122, 122); + t.figure_axis_y = Color32::from_rgb(98, 212, 142); + t.figure_axis_z = Color32::from_rgb(108, 168, 247); + t.figure_ok = Color32::from_rgb(127, 209, 174); + t.figure_warn = Color32::from_rgb(232, 194, 74); + t.figure_conflict = Color32::from_rgb(240, 162, 122); + t.pref_well = Color32::from_rgb(47, 52, 62); + t.pref_note = Color32::from_rgb(240, 162, 122); + t.pref_note_fill = Color32::from_rgb(74, 51, 38); + t.pref_on_accent = Color32::from_rgb(15, 22, 32); + t.pref_ok = Color32::from_rgb(127, 209, 174); + t.pref_ok_fill = Color32::from_rgb(31, 58, 49); + t.pref_disabled = Color32::from_rgb(138, 148, 163); t.construction_geom = icon_primary(crate::icon_svg::CONSTRUCTION_PRIMARY[1]); t.error = Color32::from_rgb(240, 100, 96); t.sketch_conflict = t.error; @@ -387,6 +441,8 @@ impl Tokens { t.box_crossing = Color32::from_rgb(80, 200, 120); t.bend_up = Color32::from_rgb(110, 200, 120); t.bend_down = Color32::from_rgb(240, 150, 80); + t.comb_envelope = Color32::from_rgb(195, 130, 255); + t.comb_teeth = Color32::from_rgb(255, 160, 60); t.form_ink = t.text; t.form_dim = Color32::from_rgb(180, 187, 200); t.form_primary = t.accent; diff --git a/assets/styles/ui/themes/1-bit-dark.json b/assets/styles/ui/themes/1-bit-dark.json index b4d0af051..a78bb1f0e 100644 --- a/assets/styles/ui/themes/1-bit-dark.json +++ b/assets/styles/ui/themes/1-bit-dark.json @@ -29,6 +29,8 @@ "chip": "#ffffff", "construction_geom": "#ffffff", "construction_plane": "#000000", + "comb_envelope": "#ffffff", + "comb_teeth": "#ffffff", "continuity": [ "#ffffff", "#ffffff", @@ -132,6 +134,10 @@ "render_soft": "#000000", "rubber_band": "#ffffff", "section_cap": "#ffffff", + "section_hatch": [ + "#ffffff", + "#ffffff" + ], "sel_edge": "#000000", "sel_edge_rim": "#000000", "sel_face": "#ffffff", diff --git a/assets/styles/ui/themes/1-bit.json b/assets/styles/ui/themes/1-bit.json index c5769ff0a..8db76c367 100644 --- a/assets/styles/ui/themes/1-bit.json +++ b/assets/styles/ui/themes/1-bit.json @@ -29,6 +29,8 @@ "chip": "#000000", "construction_geom": "#000000", "construction_plane": "#ffffff", + "comb_envelope": "#000000", + "comb_teeth": "#000000", "continuity": [ "#000000", "#000000", @@ -132,6 +134,10 @@ "render_soft": "#ffffff", "rubber_band": "#000000", "section_cap": "#000000", + "section_hatch": [ + "#000000", + "#000000" + ], "sel_edge": "#ffffff", "sel_edge_rim": "#ffffff", "sel_face": "#000000", diff --git a/assets/styles/ui/themes/cga.json b/assets/styles/ui/themes/cga.json index 6395933bd..add35c79f 100644 --- a/assets/styles/ui/themes/cga.json +++ b/assets/styles/ui/themes/cga.json @@ -29,6 +29,8 @@ "chip": "#aa00aa", "construction_geom": "#aaaaaa", "construction_plane": "#ffff5522", + "comb_envelope": "#ff55ff", + "comb_teeth": "#55ffff", "continuity": [ "#55ff55", "#5555ff", @@ -132,6 +134,10 @@ "render_soft": "#000000", "rubber_band": "#55ffff", "section_cap": "#ffff55", + "section_hatch": [ + "#555555", + "#aaaaaa" + ], "sel_edge": "#ffff55", "sel_edge_rim": "#000000", "sel_face": "#ffff55", diff --git a/assets/styles/ui/themes/gruvbox-dark-hard.json b/assets/styles/ui/themes/gruvbox-dark-hard.json deleted file mode 100644 index d1f9b019a..000000000 --- a/assets/styles/ui/themes/gruvbox-dark-hard.json +++ /dev/null @@ -1,171 +0,0 @@ -{ - "order": 20, - "provenance": "Original SolidCraft mapping of Gruvbox (MIT palette)", - "format": "solidcraft-theme/1", - "name": "Gruvbox Dark Hard", - "base": "dark", - "colors": { - "app_bar": "#141617", - "toolbar": "#1d2021", - "panel": "#1d2021", - "panel_header": "#3c3836", - "border": "#504945", - "text": "#ebdbb2", - "text_dim": "#a89984", - "accent": "#83a598", - "accent_soft": "#414f4b", - "sketch_accent": "#a1a322", - "error": "#fb4934", - "warning": "#fabd2f", - "icon": "#d5c4a1", - "timeline": "#141617", - "hover": "#46403e", - "sel_face": "#458588", - "sel_edge": "#83a598", - "sel_edge_rim": "#aec4bc", - "sel_profile": "#076678", - "sel_profile_edge": "#458588", - "hover_profile": "#83a59830", - "hover_profile_edge": "#83a598", - "sel_vertex": "#83a598", - "origin_plane": "#fe801950", - "origin_plane_edge": "#d65d0ec8", - "origin_plane_hover": "#83a59896", - "origin_point": "#d5c4a1", - "axis_x": "#fb4934", - "axis_y": "#b8bb26", - "axis_z": "#83a598", - "construction_plane": "#fe801940", - "construction_geom": "#e97926", - "body": "#a89984", - "body_edge": "#141617", - "manipulator": "#83a598", - "preview_add": "#83a598", - "preview_new": "#fabd2f", - "preview_sketch": "#b8bb26", - "preview_cut": "#fb49346e", - "cube_face": "#ebdbb2", - "cube_border": "#665c54", - "cube_text": "#282828", - "cube_hover": "#83a598", - "viewport_top": "#2c2c2c", - "viewport_bottom": "#2c2c2c", - "grid": "#443f3c", - "grid_major": "#504945", - "body_selected": "#83a598", - "sketch": "#83a598", - "sketch_fixed": "#ebdbb2", - "sketch_halo": "#141617", - "sketch_locked": "#b8bb26", - "dimension": "#fabd2f", - "dimension_driven": "#b57614", - "sketch_point": "#ebdbb2", - "sketch_point_free": "#83a598", - "dialog_bg": "#3c3836", - "dialog_border": "#504945", - "chip": "#458588", - "section_cap": "#d65d0e", - "profile_fill": "#83a59828", - "glyph_bg": "#2c2c2c", - "glyph_edge": "#fe614c", - "glyph_text": "#fe614c", - "overlay": "#1d2021f0", - "rubber_band": "#83a598", - "app_bar_text": "#ebdbb2", - "app_bar_hover": "#ebdbb21c", - "timeline_item": "#3c3836", - "timeline_item_error": "#63221f", - "timeline_marker": "#bdae93", - "field": "#141617", - "box_window": "#83a598", - "box_crossing": "#b8bb26", - "sketch_projected": "#d3869b", - "sketch_lost": "#fb4934", - "sketch_construction": "#fe8019", - "sketch_centerline": "#d65d0e", - "bend_up": "#b8bb26", - "bend_down": "#fe8019", - "interference": "#fb4934", - "icons.agent": "#d3869b", - "surface_fill": "#fe9755", - "surface_soft": "#382c20", - "surface_ink": "#fe8019", - "surface_accent": "#e97926", - "mesh_fill": "#e1ab32", - "mesh_soft": "#383323", - "mesh_ink": "#fabd2f", - "mesh_accent": "#c39429", - "form_fill": "#ea9bb0", - "form_soft": "#332c30", - "form_tab_ink": "#d3869b", - "form_accent": "#cf8297", - "sheet_fill": "#93c681", - "sheet_soft": "#2b332c", - "sheet_ink": "#8ec07c", - "render_fill": "#fc9483", - "render_soft": "#382523", - "render_ink": "#fb5d4a", - "render_accent": "#fe614c", - "sketch_soft": "#303322", - "sketch_ink": "#b8bb26", - "form_ink": "#ebdbb2", - "form_dim": "#bdae93", - "form_primary": "#83a598", - "form_error": "#fb4934", - "form_error_fill": "#63221f", - "form_success": "#b8bb26", - "form_success_fill": "#343a28", - "dialog_body": "#1d2021", - "dialog_footer": "#3c3836", - "dialog_rule": "#504945", - "control_fill": "#141617", - "control_border": "#7c6f64", - "dialog_label": "#ebdbb2", - "selected_ink": "#ebdbb2", - "selected_bg": "#414f4b", - "on_accent": "#1d2021" - }, - "icon_palette": { - "ink": "#141617", - "line": "#d5c4a1", - "passive-1": "#c5c0b8", - "passive-2": "#9a948d", - "passive-3": "#706b64", - "guide": "#a89984", - "solid": [ - "#b8dbcd", - "#9bbeb1", - "#83a598" - ], - "surface": [ - "#fcc4a3", - "#fe9755", - "#e97926" - ], - "mesh": [ - "#fbca67", - "#e1ab32", - "#c39429" - ], - "form": [ - "#fbbfce", - "#ea9bb0", - "#cf8297" - ], - "sketch": [ - "#d7db50", - "#babd2a", - "#a1a322" - ], - "constraint": [ - "#fcc2b7", - "#fc9483", - "#fe614c" - ], - "construction": [ - "#fcc4a3", - "#fe9755", - "#e97926" - ] - } -} diff --git a/assets/styles/ui/themes/gruvbox-dark-soft.json b/assets/styles/ui/themes/gruvbox-dark-soft.json deleted file mode 100644 index 847b57a03..000000000 --- a/assets/styles/ui/themes/gruvbox-dark-soft.json +++ /dev/null @@ -1,172 +0,0 @@ -{ - "order": 30, - "provenance": "Original SolidCraft mapping of Gruvbox (MIT palette)", - "format": "solidcraft-theme/1", - "name": "Gruvbox Dark Soft", - "base": "dark", - "colors": { - "app_bar": "#1d2021", - "toolbar": "#32302f", - "panel": "#32302f", - "panel_header": "#3c3836", - "border": "#504945", - "text": "#ebdbb2", - "text_dim": "#a89984", - "accent": "#83a598", - "accent_soft": "#4e5954", - "selected_ink": "#ebdbb2", - "sketch_accent": "#a1a322", - "error": "#fb4934", - "warning": "#fabd2f", - "icon": "#d5c4a1", - "timeline": "#1d2021", - "hover": "#46403e", - "sel_face": "#458588", - "sel_edge": "#83a598", - "sel_edge_rim": "#aec4bc", - "sel_profile": "#076678", - "sel_profile_edge": "#458588", - "hover_profile": "#83a59830", - "hover_profile_edge": "#83a598", - "sel_vertex": "#83a598", - "origin_plane": "#fe801950", - "origin_plane_edge": "#d65d0ec8", - "origin_plane_hover": "#83a59896", - "origin_point": "#d5c4a1", - "axis_x": "#fb4934", - "axis_y": "#b8bb26", - "axis_z": "#83a598", - "construction_plane": "#fe801940", - "construction_geom": "#e97926", - "body": "#a89984", - "body_edge": "#1d2021", - "manipulator": "#83a598", - "preview_add": "#83a598", - "preview_new": "#fabd2f", - "preview_sketch": "#b8bb26", - "preview_cut": "#fb49346e", - "cube_face": "#ebdbb2", - "cube_border": "#665c54", - "cube_text": "#282828", - "cube_hover": "#83a598", - "viewport_top": "#373432", - "viewport_bottom": "#373432", - "grid": "#443f3c", - "grid_major": "#504945", - "body_selected": "#83a598", - "sketch": "#83a598", - "sketch_fixed": "#ebdbb2", - "sketch_halo": "#1d2021", - "sketch_locked": "#b8bb26", - "dimension": "#fabd2f", - "dimension_driven": "#b57614", - "sketch_point": "#ebdbb2", - "sketch_point_free": "#83a598", - "dialog_bg": "#3c3836", - "dialog_border": "#504945", - "chip": "#458588", - "section_cap": "#d65d0e", - "profile_fill": "#83a59828", - "glyph_bg": "#373432", - "glyph_edge": "#fe614c", - "glyph_text": "#fe614c", - "overlay": "#32302ff0", - "rubber_band": "#83a598", - "app_bar_text": "#ebdbb2", - "app_bar_hover": "#ebdbb21c", - "timeline_item": "#3c3836", - "timeline_item_error": "#702b28", - "timeline_marker": "#bdae93", - "field": "#1d2021", - "box_window": "#83a598", - "box_crossing": "#b8bb26", - "sketch_projected": "#d3869b", - "sketch_lost": "#fb4934", - "sketch_construction": "#fe8019", - "sketch_centerline": "#d65d0e", - "bend_up": "#b8bb26", - "bend_down": "#fe8019", - "interference": "#fb4934", - "icons.agent": "#d3869b", - "surface_fill": "#fe9755", - "surface_soft": "#4a3a2c", - "surface_ink": "#fe8b2e", - "surface_accent": "#e97926", - "mesh_fill": "#e1ab32", - "mesh_soft": "#4a412f", - "mesh_ink": "#fabd2f", - "mesh_accent": "#c39429", - "form_fill": "#ea9bb0", - "form_soft": "#453a3c", - "form_tab_ink": "#d996a8", - "form_accent": "#cf8297", - "sheet_fill": "#93c681", - "sheet_soft": "#3d4138", - "sheet_ink": "#8ec07c", - "render_fill": "#fc9483", - "render_soft": "#4a3330", - "render_ink": "#fc7e6f", - "render_accent": "#fe614c", - "sketch_soft": "#42412e", - "sketch_ink": "#b8bb26", - "form_ink": "#ebdbb2", - "form_dim": "#bdae93", - "form_primary": "#83a598", - "form_error": "#fb4934", - "form_error_fill": "#702b28", - "form_success": "#b8bb26", - "form_success_fill": "#343a28", - "dialog_body": "#32302f", - "dialog_footer": "#3c3836", - "dialog_rule": "#504945", - "control_fill": "#1d2021", - "control_border": "#7c6f64", - "dialog_label": "#ebdbb2", - "selected_ink": "#ebdbb2", - "selected_bg": "#4e5954", - "on_accent": "#1d2021" - }, - "icon_palette": { - "ink": "#1d2021", - "line": "#d5c4a1", - "passive-1": "#c5c0b8", - "passive-2": "#9a948d", - "passive-3": "#706b64", - "guide": "#a89984", - "solid": [ - "#b8dbcd", - "#9bbeb1", - "#83a598" - ], - "surface": [ - "#fcc4a3", - "#fe9755", - "#e97926" - ], - "mesh": [ - "#fbca67", - "#e1ab32", - "#c39429" - ], - "form": [ - "#fbbfce", - "#ea9bb0", - "#cf8297" - ], - "sketch": [ - "#d7db50", - "#babd2a", - "#a1a322" - ], - "constraint": [ - "#fcc2b7", - "#fc9483", - "#fe614c" - ], - "construction": [ - "#fcc4a3", - "#fe9755", - "#e97926" - ] - } -} diff --git a/assets/styles/ui/themes/gruvbox-dark.json b/assets/styles/ui/themes/gruvbox-dark.json index 9c73534e0..11ab4c6f8 100644 --- a/assets/styles/ui/themes/gruvbox-dark.json +++ b/assets/styles/ui/themes/gruvbox-dark.json @@ -122,7 +122,6 @@ "control_fill": "#1d2021", "control_border": "#7c6f64", "dialog_label": "#ebdbb2", - "selected_ink": "#ebdbb2", "selected_bg": "#48544f", "on_accent": "#1d2021" }, @@ -168,5 +167,124 @@ "#fe9755", "#e97926" ] - } + }, + "options": [ + { + "id": "contrast", + "type": "choice", + "default": "standard", + "label": { + "de": "Kontrast", + "en": "Contrast", + "ja": "コントラスト", + "ko": "대비", + "zh": "对比度" + }, + "help": { + "de": "Wähle die weiche, normale oder harte Gruvbox-Palette.", + "en": "Choose the soft, standard or hard Gruvbox palette.", + "ja": "Gruvboxのソフト・標準・ハードのパレットを選びます。", + "ko": "Gruvbox의 부드러운, 표준 또는 강한 팔레트를 선택합니다.", + "zh": "选择柔和、标准或强对比的 Gruvbox 配色。" + }, + "values": [ + { + "id": "soft", + "label": { + "de": "Weich", + "en": "Soft", + "ja": "ソフト", + "ko": "부드럽게", + "zh": "柔和" + } + }, + { + "id": "standard", + "label": { + "de": "Standard", + "en": "Standard", + "ja": "標準", + "ko": "표준", + "zh": "标准" + } + }, + { + "id": "hard", + "label": { + "de": "Hart", + "en": "Hard", + "ja": "ハード", + "ko": "강하게", + "zh": "强对比" + } + } + ] + } + ], + "overlays": [ + { + "when": { + "opt": "contrast", + "eq": "soft" + }, + "colors": { + "toolbar": "#32302f", + "panel": "#32302f", + "accent_soft": "#4e5954", + "viewport_top": "#373432", + "viewport_bottom": "#373432", + "glyph_bg": "#373432", + "overlay": "#32302ff0", + "timeline_item_error": "#702b28", + "surface_soft": "#4a3a2c", + "surface_ink": "#fe8b2e", + "mesh_soft": "#4a412f", + "form_soft": "#453a3c", + "form_tab_ink": "#d996a8", + "sheet_soft": "#3d4138", + "render_soft": "#4a3330", + "render_ink": "#fc7e6f", + "sketch_soft": "#42412e", + "form_error_fill": "#702b28", + "dialog_body": "#32302f", + "selected_bg": "#4e5954" + } + }, + { + "when": { + "opt": "contrast", + "eq": "hard" + }, + "colors": { + "app_bar": "#141617", + "toolbar": "#1d2021", + "panel": "#1d2021", + "accent_soft": "#414f4b", + "timeline": "#141617", + "body_edge": "#141617", + "viewport_top": "#2c2c2c", + "viewport_bottom": "#2c2c2c", + "sketch_halo": "#141617", + "glyph_bg": "#2c2c2c", + "overlay": "#1d2021f0", + "timeline_item_error": "#63221f", + "field": "#141617", + "surface_soft": "#382c20", + "mesh_soft": "#383323", + "form_soft": "#332c30", + "form_tab_ink": "#d3869b", + "sheet_soft": "#2b332c", + "render_soft": "#382523", + "render_ink": "#fb5d4a", + "sketch_soft": "#303322", + "form_error_fill": "#63221f", + "dialog_body": "#1d2021", + "control_fill": "#141617", + "selected_bg": "#414f4b" + }, + "icon_palette": { + "ink": "#141617" + } + } + ] } diff --git a/assets/styles/ui/themes/gruvbox-light-hard.json b/assets/styles/ui/themes/gruvbox-light-hard.json deleted file mode 100644 index 75e669b51..000000000 --- a/assets/styles/ui/themes/gruvbox-light-hard.json +++ /dev/null @@ -1,171 +0,0 @@ -{ - "order": 50, - "provenance": "Original SolidCraft mapping of Gruvbox (MIT palette)", - "format": "solidcraft-theme/1", - "name": "Gruvbox Light Hard", - "base": "light", - "colors": { - "app_bar": "#3c3836", - "toolbar": "#f9f5d7", - "panel": "#f9f5d7", - "panel_header": "#ebdbb2", - "border": "#d5c4a1", - "text": "#3c3836", - "text_dim": "#7c6f64", - "accent": "#076678", - "accent_soft": "#c9d8c4", - "sketch_accent": "#625e15", - "error": "#9d0006", - "warning": "#b57614", - "icon": "#504945", - "timeline": "#ebdbb2", - "hover": "#f1e5c1", - "sel_face": "#458588", - "sel_edge": "#076678", - "sel_edge_rim": "#83a598", - "sel_profile": "#076678", - "sel_profile_edge": "#458588", - "hover_profile": "#45858830", - "hover_profile_edge": "#458588", - "sel_vertex": "#076678", - "origin_plane": "#fe80195e", - "origin_plane_edge": "#d65d0ec8", - "origin_plane_hover": "#45858896", - "origin_point": "#d5c4a1", - "axis_x": "#cc241d", - "axis_y": "#98971a", - "axis_z": "#458588", - "construction_plane": "#fe801946", - "construction_geom": "#9b3407", - "body": "#bdae93", - "body_edge": "#3c3836", - "manipulator": "#076678", - "preview_add": "#458588", - "preview_new": "#d79921", - "preview_sketch": "#98971a", - "preview_cut": "#cc241d6e", - "cube_face": "#fbf1c7", - "cube_border": "#7c6f64", - "cube_text": "#3c3836", - "cube_hover": "#83a598", - "viewport_top": "#fbf8e3", - "viewport_bottom": "#ebdbb2", - "grid": "#d5c4a1", - "grid_major": "#bdae93", - "body_selected": "#83a598", - "sketch": "#076678", - "sketch_fixed": "#282828", - "sketch_halo": "#fbf8e3", - "sketch_locked": "#79740e", - "dimension": "#1f5c40", - "dimension_driven": "#4f7d64", - "sketch_point": "#282828", - "sketch_point_free": "#076678", - "dialog_bg": "#f9f5d7", - "dialog_border": "#d5c4a1", - "chip": "#458588", - "section_cap": "#d65d0e", - "profile_fill": "#fabd2f46", - "glyph_bg": "#fcfaeb", - "glyph_edge": "#a91714", - "glyph_text": "#a91714", - "overlay": "#f9f5d7eb", - "rubber_band": "#076678", - "app_bar_text": "#fbf1c7", - "app_bar_hover": "#fbf1c71c", - "timeline_item": "#f9f5d7", - "timeline_item_error": "#f0cbb2", - "timeline_marker": "#504945", - "field": "#fcfaeb", - "box_window": "#076678", - "box_crossing": "#79740e", - "sketch_projected": "#8f3f71", - "sketch_lost": "#9d0006", - "sketch_construction": "#af3a03", - "sketch_centerline": "#d65d0e", - "bend_up": "#79740e", - "bend_down": "#af3a03", - "interference": "#cc241d", - "icons.agent": "#8f3f71", - "surface_fill": "#df663c", - "surface_soft": "#f3e6c6", - "surface_ink": "#af3a03", - "surface_accent": "#9b3407", - "mesh_fill": "#c08024", - "mesh_soft": "#f4ebc7", - "mesh_ink": "#915e10", - "mesh_accent": "#7b5112", - "form_fill": "#c46fa2", - "form_soft": "#f1e6cf", - "form_tab_ink": "#8f3f71", - "form_accent": "#893a6c", - "sheet_fill": "#659f7a", - "sheet_soft": "#eaebcd", - "sheet_ink": "#3d7252", - "render_fill": "#e85a4d", - "render_soft": "#f2e1c6", - "render_ink": "#9d0006", - "render_accent": "#a91714", - "sketch_soft": "#efebc7", - "sketch_ink": "#6e6a0d", - "form_ink": "#3c3836", - "form_dim": "#665c54", - "form_primary": "#076678", - "form_error": "#9d0006", - "form_error_fill": "#f0cbb2", - "form_success": "#427b58", - "form_success_fill": "#dae3b6", - "dialog_body": "#f9f5d7", - "dialog_footer": "#ebdbb2", - "dialog_rule": "#d5c4a1", - "control_fill": "#fcfaeb", - "control_border": "#a89984", - "dialog_label": "#3c3836", - "selected_ink": "#3c3836", - "selected_bg": "#c9d8c4", - "on_accent": "#fbf1c7" - }, - "icon_palette": { - "ink": "#3c3836", - "line": "#504945", - "passive-1": "#e9e3df", - "passive-2": "#b8b3af", - "passive-3": "#8a8581", - "guide": "#7c6f64", - "solid": [ - "#87d5e9", - "#4e9caf", - "#076678" - ], - "surface": [ - "#feb299", - "#df663c", - "#9b3407" - ], - "mesh": [ - "#fcb864", - "#c08024", - "#7b5112" - ], - "form": [ - "#fbaad9", - "#c46fa2", - "#893a6c" - ], - "sketch": [ - "#d0cc73", - "#989439", - "#625e15" - ], - "constraint": [ - "#fab3a8", - "#e85a4d", - "#a91714" - ], - "construction": [ - "#feb299", - "#df663c", - "#9b3407" - ] - } -} diff --git a/assets/styles/ui/themes/gruvbox-light-soft.json b/assets/styles/ui/themes/gruvbox-light-soft.json deleted file mode 100644 index 24c372901..000000000 --- a/assets/styles/ui/themes/gruvbox-light-soft.json +++ /dev/null @@ -1,171 +0,0 @@ -{ - "order": 60, - "provenance": "Original SolidCraft mapping of Gruvbox (MIT palette)", - "format": "solidcraft-theme/1", - "name": "Gruvbox Light Soft", - "base": "light", - "colors": { - "app_bar": "#3c3836", - "toolbar": "#f2e5bc", - "panel": "#f2e5bc", - "panel_header": "#ebdbb2", - "border": "#d5c4a1", - "text": "#3c3836", - "text_dim": "#7c6f64", - "accent": "#076678", - "accent_soft": "#c3ccae", - "sketch_accent": "#625e15", - "error": "#9d0006", - "warning": "#b57614", - "icon": "#504945", - "timeline": "#ebdbb2", - "hover": "#eedfb6", - "sel_face": "#458588", - "sel_edge": "#076678", - "sel_edge_rim": "#83a598", - "sel_profile": "#076678", - "sel_profile_edge": "#458588", - "hover_profile": "#45858830", - "hover_profile_edge": "#458588", - "sel_vertex": "#076678", - "origin_plane": "#fe80195e", - "origin_plane_edge": "#d65d0ec8", - "origin_plane_hover": "#45858896", - "origin_point": "#d5c4a1", - "axis_x": "#cc241d", - "axis_y": "#98971a", - "axis_z": "#458588", - "construction_plane": "#fe801946", - "construction_geom": "#9b3407", - "body": "#bdae93", - "body_edge": "#3c3836", - "manipulator": "#076678", - "preview_add": "#458588", - "preview_new": "#d79921", - "preview_sketch": "#98971a", - "preview_cut": "#cc241d6e", - "cube_face": "#fbf1c7", - "cube_border": "#7c6f64", - "cube_text": "#3c3836", - "cube_hover": "#83a598", - "viewport_top": "#f6edd0", - "viewport_bottom": "#ebdbb2", - "grid": "#d5c4a1", - "grid_major": "#bdae93", - "body_selected": "#83a598", - "sketch": "#076678", - "sketch_fixed": "#282828", - "sketch_halo": "#f6edd0", - "sketch_locked": "#79740e", - "dimension": "#1f5c40", - "dimension_driven": "#4f7d64", - "sketch_point": "#282828", - "sketch_point_free": "#076678", - "dialog_bg": "#f2e5bc", - "dialog_border": "#d5c4a1", - "chip": "#458588", - "section_cap": "#d65d0e", - "profile_fill": "#fabd2f46", - "glyph_bg": "#f8f2de", - "glyph_edge": "#a91714", - "glyph_text": "#a91714", - "overlay": "#f2e5bceb", - "rubber_band": "#076678", - "app_bar_text": "#fbf1c7", - "app_bar_hover": "#fbf1c71c", - "timeline_item": "#f2e5bc", - "timeline_item_error": "#eabe9c", - "timeline_marker": "#504945", - "field": "#f8f2de", - "box_window": "#076678", - "box_crossing": "#79740e", - "sketch_projected": "#8f3f71", - "sketch_lost": "#9d0006", - "sketch_construction": "#af3a03", - "sketch_centerline": "#d65d0e", - "bend_up": "#79740e", - "bend_down": "#af3a03", - "interference": "#cc241d", - "icons.agent": "#8f3f71", - "surface_fill": "#df663c", - "surface_soft": "#edd7ad", - "surface_ink": "#a83803", - "surface_accent": "#9b3407", - "mesh_fill": "#c08024", - "mesh_soft": "#eddcaf", - "mesh_ink": "#84560f", - "mesh_accent": "#7b5112", - "form_fill": "#c46fa2", - "form_soft": "#ead8b6", - "form_tab_ink": "#8f3f71", - "form_accent": "#893a6c", - "sheet_fill": "#659f7a", - "sheet_soft": "#e4ddb4", - "sheet_ink": "#38694b", - "render_fill": "#e85a4d", - "render_soft": "#ebd3ad", - "render_ink": "#9d0006", - "render_accent": "#a91714", - "sketch_soft": "#e8dcae", - "sketch_ink": "#66610c", - "form_ink": "#3c3836", - "form_dim": "#665c54", - "form_primary": "#076678", - "form_error": "#9d0006", - "form_error_fill": "#eabe9c", - "form_success": "#427b58", - "form_success_fill": "#dae3b6", - "dialog_body": "#f2e5bc", - "dialog_footer": "#ebdbb2", - "dialog_rule": "#d5c4a1", - "control_fill": "#f8f2de", - "control_border": "#a89984", - "dialog_label": "#3c3836", - "selected_ink": "#3c3836", - "selected_bg": "#c3ccae", - "on_accent": "#fbf1c7" - }, - "icon_palette": { - "ink": "#3c3836", - "line": "#504945", - "passive-1": "#e9e3df", - "passive-2": "#b8b3af", - "passive-3": "#8a8581", - "guide": "#7c6f64", - "solid": [ - "#87d5e9", - "#4e9caf", - "#076678" - ], - "surface": [ - "#feb299", - "#df663c", - "#9b3407" - ], - "mesh": [ - "#fcb864", - "#c08024", - "#7b5112" - ], - "form": [ - "#fbaad9", - "#c46fa2", - "#893a6c" - ], - "sketch": [ - "#d0cc73", - "#989439", - "#625e15" - ], - "constraint": [ - "#fab3a8", - "#e85a4d", - "#a91714" - ], - "construction": [ - "#feb299", - "#df663c", - "#9b3407" - ] - } -} diff --git a/assets/styles/ui/themes/gruvbox-light.json b/assets/styles/ui/themes/gruvbox-light.json index b61a4cd27..97d8056a8 100644 --- a/assets/styles/ui/themes/gruvbox-light.json +++ b/assets/styles/ui/themes/gruvbox-light.json @@ -167,5 +167,127 @@ "#df663c", "#9b3407" ] - } + }, + "options": [ + { + "id": "contrast", + "type": "choice", + "default": "standard", + "label": { + "de": "Kontrast", + "en": "Contrast", + "ja": "コントラスト", + "ko": "대비", + "zh": "对比度" + }, + "help": { + "de": "Wähle die weiche, normale oder harte Gruvbox-Palette.", + "en": "Choose the soft, standard or hard Gruvbox palette.", + "ja": "Gruvboxのソフト・標準・ハードのパレットを選びます。", + "ko": "Gruvbox의 부드러운, 표준 또는 강한 팔레트를 선택합니다.", + "zh": "选择柔和、标准或强对比的 Gruvbox 配色。" + }, + "values": [ + { + "id": "soft", + "label": { + "de": "Weich", + "en": "Soft", + "ja": "ソフト", + "ko": "부드럽게", + "zh": "柔和" + } + }, + { + "id": "standard", + "label": { + "de": "Standard", + "en": "Standard", + "ja": "標準", + "ko": "표준", + "zh": "标准" + } + }, + { + "id": "hard", + "label": { + "de": "Hart", + "en": "Hard", + "ja": "ハード", + "ko": "강하게", + "zh": "强对比" + } + } + ] + } + ], + "overlays": [ + { + "when": { + "opt": "contrast", + "eq": "soft" + }, + "colors": { + "toolbar": "#f2e5bc", + "panel": "#f2e5bc", + "accent_soft": "#c3ccae", + "hover": "#eedfb6", + "viewport_top": "#f6edd0", + "sketch_halo": "#f6edd0", + "dialog_bg": "#f2e5bc", + "glyph_bg": "#f8f2de", + "overlay": "#f2e5bceb", + "timeline_item": "#f2e5bc", + "timeline_item_error": "#eabe9c", + "field": "#f8f2de", + "surface_soft": "#edd7ad", + "surface_ink": "#a83803", + "mesh_soft": "#eddcaf", + "mesh_ink": "#84560f", + "form_soft": "#ead8b6", + "sheet_soft": "#e4ddb4", + "sheet_ink": "#38694b", + "render_soft": "#ebd3ad", + "sketch_soft": "#e8dcae", + "sketch_ink": "#66610c", + "form_error_fill": "#eabe9c", + "dialog_body": "#f2e5bc", + "control_fill": "#f8f2de", + "selected_bg": "#c3ccae" + } + }, + { + "when": { + "opt": "contrast", + "eq": "hard" + }, + "colors": { + "toolbar": "#f9f5d7", + "panel": "#f9f5d7", + "accent_soft": "#c9d8c4", + "hover": "#f1e5c1", + "viewport_top": "#fbf8e3", + "sketch_halo": "#fbf8e3", + "dialog_bg": "#f9f5d7", + "glyph_bg": "#fcfaeb", + "overlay": "#f9f5d7eb", + "timeline_item": "#f9f5d7", + "timeline_item_error": "#f0cbb2", + "field": "#fcfaeb", + "surface_soft": "#f3e6c6", + "mesh_soft": "#f4ebc7", + "mesh_ink": "#915e10", + "form_soft": "#f1e6cf", + "sheet_soft": "#eaebcd", + "sheet_ink": "#3d7252", + "render_soft": "#f2e1c6", + "sketch_soft": "#efebc7", + "sketch_ink": "#6e6a0d", + "form_error_fill": "#f0cbb2", + "dialog_body": "#f9f5d7", + "control_fill": "#fcfaeb", + "selected_bg": "#c9d8c4" + } + } + ] } diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 8960e0be1..4af383d32 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -9,9 +9,11 @@ license.workspace = true workspace = true [dependencies] +solidcore-record = { workspace = true } solidcraft-geom = { workspace = true } solidcraft-sketch = { workspace = true } solidcraft-kernel = { workspace = true } +solidcraft-profile = { workspace = true } solidcraft-render = { workspace = true } solidcraft-derive = { workspace = true } serde = { workspace = true } diff --git a/crates/doc/src/anchor_frame.rs b/crates/doc/src/anchor_frame.rs index 9dd56cd1e..091cec098 100644 --- a/crates/doc/src/anchor_frame.rs +++ b/crates/doc/src/anchor_frame.rs @@ -6,7 +6,7 @@ pub fn state_in_face_anchor_frame<'a>(doc: &Document, state: &'a ModelState, anc let frame = anchor.author_frame(doc, author)?; let raw = state.body(&anchor.target.body).ok_or_else(|| DocError::Unknown(format!("anchored body `{}`", anchor.target.body)))?; let relative = anchor.source_to_author(doc, author, raw)?; - let mut output = crate::state_in_frame_at(doc, state, author, frame).into_owned(); + let mut output = crate::state_in_frame_at(doc, state, author, frame)?.into_owned(); // In place, the body is the model's own, display mesh included: a sketch projecting the // face's edges meshes it once for the features after it too, rather than a copy. let body = state.body_in_frame(raw, &relative)?; diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 574b4200a..69f9f9467 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -3,10 +3,11 @@ //! a component's over the physical material's look; a body with none of these keeps the colour //! it was imported with. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Document; diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index 591aa5236..f9cfda649 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -9,7 +9,8 @@ //! and the engine maps a new feature's geometry into the active component's frame. use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Plane, Vec3}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::prelude::*; use crate::{DocError, Document, FeatureKind, PlaneRef, Result}; @@ -101,6 +102,23 @@ pub fn mat_inverse(m: &Mat) -> Option { Some(out) } +/// Whether `m` is a placement an occurrence may have: finite, a rotation (orthonormal axes, not +/// mirrored) and a translation within 1e9 mm, its last column `0, 0, 0, 1`. Every placement is +/// checked against this where it enters the document (a design file, a command, an import). +pub fn is_placement(m: &Mat) -> bool { + let axis = |i: usize| Vec3::new(m[i][0], m[i][1], m[i][2]); + let (x, y, z) = (axis(0), axis(1), axis(2)); + m.iter().flatten().all(|v| v.is_finite()) + && m[3][..3].iter().all(|v| v.abs() <= 1e9) + && [x, y, z].iter().all(|v| (v.dot(*v) - 1.0).abs() < 1e-6) + && x.dot(y).abs() < 1e-6 + && x.dot(z).abs() < 1e-6 + && y.dot(z).abs() < 1e-6 + && x.cross(y).dot(z) > 0.0 + && [m[0][3], m[1][3], m[2][3]].iter().all(|v| v.abs() < 1e-9) + && (m[3][3] - 1.0).abs() < 1e-9 +} + /// A rigid transform: rotation by `angle` about `axis` through `origin`, then a translation. pub fn rigid(translate: Vec3, origin: Vec3, axis: Vec3, angle: f64) -> Mat { let k = axis.normalized().unwrap_or(Vec3::Z); @@ -219,12 +237,16 @@ fn map_plane_ref(m: &Mat, p: &mut PlaneRef) { } // Named origin planes and construction planes are the component's own. PlaneRef::Origin { .. } | PlaneRef::Construction { .. } => {} - PlaneRef::Tangent { face, at } => { + PlaneRef::Tangent { face, at, reference, .. } => { *at = apply_point(m, *at); map_geo_ref(m, face); + if let Some(r) = reference { + map_geo_ref(m, r); + } } PlaneRef::Midplane { .. } | PlaneRef::TwoEdges { .. } + | PlaneRef::AxisPoint { .. } | PlaneRef::ThreePoints { .. } | PlaneRef::AlongPath { .. } | PlaneRef::Perpendicular { .. } => { @@ -505,6 +527,19 @@ impl Document { held } + /// Is `c` (or one of its ancestors) marked out of the History bar (#10393)? The root (0) + /// never is: its own features always show. + pub fn component_history_hidden(&self, mut c: u64) -> bool { + for _ in 0..1000 { + match self.components.iter().find(|x| x.id == c) { + Some(x) if x.history_hidden => return true, + Some(x) if x.parent != 0 => c = x.parent, + _ => return false, + } + } + false + } + /// Would putting a placement of `component` into `parent` put it inside itself: is `parent` /// the component, or inside it, created in it or placed in it at any depth? Placements can sit /// apart from where their component was created ([`Self::component_within`] follows only @@ -529,7 +564,8 @@ impl Document { false } - /// Add an occurrence of an existing component into `parent`. + /// Add an occurrence of an existing component into `parent`, placed by `transform` (which + /// must pass [`is_placement`]). pub fn add_occurrence(&mut self, component: u64, parent: u64, transform: Mat) -> Result { if component == 0 || !self.components.iter().any(|c| c.id == component) { return Err(DocError::Unknown(format!("component {component}"))); @@ -540,10 +576,20 @@ impl Document { if self.occurrences.len() >= 100_000 { return Err(DocError::Invalid("too many occurrences".into())); } + if !is_placement(&transform) { + return Err(DocError::Invalid("an occurrence's placement must be a rigid motion (no scaling or mirroring) within 1e9 mm".into())); + } let id = self.next_id.max(1); self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let cname = self.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default(); - let k = self.occurrences.iter().filter(|o| o.component == component).count() + 1; + // The next number, or, when an occurrence already has that name (one before it was + // deleted, or of another component of that name), the first number none has (#9738). + let next = self.occurrences.iter().filter(|o| o.component == component).count() + 1; + let free = |k: &usize| { + let name = format!("{cname}:{k}"); + !self.occurrences.iter().any(|o| o.name == name) + }; + let k = std::iter::once(next).chain(1..).find(free).unwrap_or(next); self.occurrences.push(crate::Occurrence { id, component, parent, name: format!("{cname}:{k}"), transform, grounded: false, bom_type: None }); Ok(id) } diff --git a/crates/doc/src/body_transfer.rs b/crates/doc/src/body_transfer.rs index 1eca9bbe6..1226ea1d0 100644 --- a/crates/doc/src/body_transfer.rs +++ b/crates/doc/src/body_transfer.rs @@ -1,20 +1,9 @@ //! Recorded ownership changes are evaluated at their timeline position. use crate::{DocError, Document, Mat, ModelBody, ModelState, Result}; -use solidcraft_geom::Vec3; use std::collections::BTreeSet; pub fn valid_transfer_matrix(m: &Mat) -> bool { - let axis = |i: usize| Vec3::new(m[i][0], m[i][1], m[i][2]); - let (x, y, z) = (axis(0), axis(1), axis(2)); - m.iter().flatten().all(|v| v.is_finite()) - && m[3][..3].iter().all(|v| v.abs() <= 1e9) - && [x, y, z].iter().all(|v| (v.dot(*v) - 1.0).abs() < 1e-6) - && x.dot(y).abs() < 1e-6 - && x.dot(z).abs() < 1e-6 - && y.dot(z).abs() < 1e-6 - && x.cross(y).dot(z) > 0.0 - && [m[0][3], m[1][3], m[2][3]].iter().all(|v| v.abs() < 1e-9) - && (m[3][3] - 1.0).abs() < 1e-9 + crate::is_placement(m) } /// Validate the stored boundary before allocation, loading, or evaluation. diff --git a/crates/doc/src/body_transfer_sheet.rs b/crates/doc/src/body_transfer_sheet.rs index 5a0784781..82c274c66 100644 --- a/crates/doc/src/body_transfer_sheet.rs +++ b/crates/doc/src/body_transfer_sheet.rs @@ -1,5 +1,6 @@ //! World-frame metadata at a timeline body ownership boundary. -use solidcraft_geom::Plane; +use solidcore_record::Plane; +use solidcraft_geom::prelude::*; use crate::{DocError, Mat, ModelState, Result, apply_point, apply_vector}; diff --git a/crates/doc/src/bom.rs b/crates/doc/src/bom.rs index 000fd1024..aca4d4321 100644 --- a/crates/doc/src/bom.rs +++ b/crates/doc/src/bom.rs @@ -731,7 +731,8 @@ struct Step { /// contents under it when asked); an inseparable part is one row, and in parts only its purchased /// parts are listed beside it; a normal part is a row in the structured views, in all levels with /// what it holds under it, and in parts only a subassembly is listed through its parts unless it -/// has bodies of its own. A folded part is one row holding all it holds. +/// has bodies of its own. A folded part is one row holding all it holds, what it holds listed under +/// it (of an inseparable one, its purchased parts). fn classify(view: View, walk: Walk, bom_type: BomType, shape: Shape) -> Step { let nothing = Step { row: false, inside: None, kit: false, holds: Holds::All }; let row = |holds| Step { row: true, holds, ..nothing }; @@ -745,6 +746,7 @@ fn classify(view: View, walk: Walk, bom_type: BomType, shape: Shape) -> Step { } (BomType::Purchased, _) => row(Holds::All), (_, Walk::PurchasedOnly) => Step { inside: contents(Walk::PurchasedOnly), ..nothing }, + (BomType::Inseparable, Walk::Listed) if shape.folded => Step { inside: contents(Walk::PurchasedOnly), kit: true, ..row(Holds::All) }, (BomType::Inseparable, Walk::Listed) => match view { View::PartsOnly => Step { inside: contents(Walk::PurchasedOnly), ..row(Holds::AllButPurchased) }, View::FirstLevel | View::AllLevels => row(Holds::All), diff --git a/crates/doc/src/browser_tree.rs b/crates/doc/src/browser_tree.rs new file mode 100644 index 000000000..5d10a4b39 --- /dev/null +++ b/crates/doc/src/browser_tree.rs @@ -0,0 +1,182 @@ +//! The browser's groups as a tree: how deep a group sits, who holds whom, and pruning what a +//! saved design says about the browser down to what still exists. +use crate::document::{BROWSER_FOLDERS, BrowserEntry, BrowserGroup, Document, MAX_GROUP_NESTING}; +use std::collections::{BTreeMap, BTreeSet}; + +impl Document { + pub fn browser_group(&self, id: u64) -> Option<&BrowserGroup> { + self.browser_groups.iter().find(|g| g.id == id) + } + + /// The level of a group: 1 for a top-level group, 2 for a child of one, and so on. A chain + /// that loops or runs past the limit counts as one level too deep. + pub fn group_level(&self, id: u64) -> usize { + let mut level = 0; + let mut at = Some(id); + while let Some(g) = at { + level += 1; + if level > MAX_GROUP_NESTING { + return level; + } + at = self.browser_group(g).and_then(|g| g.parent); + } + level + } + + /// Whether `ancestor` is `id` or holds it, at any depth. + pub fn group_within(&self, id: u64, ancestor: u64) -> bool { + let mut at = Some(id); + for _ in 0..=MAX_GROUP_NESTING { + match at { + Some(g) if g == ancestor => return true, + Some(g) => at = self.browser_group(g).and_then(|g| g.parent), + None => return false, + } + } + false + } + + /// How many levels the group and the groups under it take: 1 for a group with no child group. + pub fn group_height(&self, id: u64) -> usize { + fn height(d: &Document, id: u64, left: usize) -> usize { + if left == 0 { + return 1; + } + 1 + d.browser_groups.iter().filter(|g| g.parent == Some(id)).map(|g| height(d, g.id, left - 1)).max().unwrap_or(0) + } + height(self, id, MAX_GROUP_NESTING + 1) + } + + /// The entries of a holder's list in display order: a group's contents, or the folder's top + /// level when `holder` is `None`. Groups the list names come where it names them. The child + /// groups it does not name (in creation order) go just after the last group it names, or + /// first when it names none, so they sit above the items as they always have. Entries for + /// groups that are not the holder's children are dropped. + pub fn ordered_entries(&self, component: u64, folder: &str, holder: Option) -> Vec { + let listed: &[BrowserEntry] = match holder { + Some(g) => self.browser_group(g).map_or(&[], |g| &g.items), + None => self.browser_order.get(&format!("{component}/{folder}")).map_or(&[], Vec::as_slice), + }; + let mine: Vec = + self.browser_groups.iter().filter(|g| g.component == component && g.folder == folder && g.parent == holder).map(|g| g.id).collect(); + let mut out: Vec = Vec::with_capacity(listed.len() + mine.len()); + for e in listed { + match e { + BrowserEntry::Group(id) if !mine.contains(id) || out.contains(e) => {} + _ => out.push(e.clone()), + } + } + let at = out.iter().rposition(|e| matches!(e, BrowserEntry::Group(_))).map_or(0, |i| i + 1); + let unlisted: Vec = mine.iter().map(|id| BrowserEntry::Group(*id)).filter(|e| !out.contains(e)).collect(); + out.splice(at..at, unlisted); + out + } + + /// The items in a group and in the groups inside it. + pub fn group_item_keys(&self, id: u64) -> Vec { + let inside = self.browser_groups.iter().filter(|g| self.group_within(g.id, id)); + inside.flat_map(|g| g.item_keys().map(str::to_string)).collect() + } + + /// The group holding the item directly, in a component's folder. + pub fn group_of_item(&self, component: u64, folder: &str, key: &str) -> Option<&BrowserGroup> { + self.browser_groups.iter().find(|g| g.component == component && g.folder == folder && g.has_item(key)) + } + + /// Only the browser's groups and order changed (a group made, nested, moved into, ordered): + /// nothing is evaluated and no placement moves. The same whole-Document proof as + /// [`Document::differs_only_in_render`]; `next_id` may differ, as a new group takes an id. + pub fn differs_only_in_browser(&self, previous: &Document) -> bool { + if self.browser_groups == previous.browser_groups && self.browser_order == previous.browser_order { + return false; + } + let mut normalized = previous.clone(); + normalized.browser_groups.clone_from(&self.browser_groups); + normalized.browser_order.clone_from(&self.browser_order); + normalized.next_id = self.next_id; + *self == normalized + } + + /// What [`Document::browser_pruned`] depends on, cheaply: it can only find something to drop + /// after a feature, placement, component or group was added or removed. Ids are never + /// reused, so a removal followed by an addition still moves `next_id`. + pub fn browser_stamp(&self) -> [u64; 6] { + let n = |len: usize| u64::try_from(len).unwrap_or(u64::MAX); + [ + self.next_id, + n(self.features.len()), + n(self.occurrences.len()), + n(self.components.len()), + n(self.browser_groups.len()), + n(self.browser_order.len()), + ] + } + + /// The groups and order lists with what they name that is gone dropped, or `None` when + /// nothing is: groups of a missing component or folder, a parent that is missing, elsewhere + /// or loops, entries for groups and sketches, construction items and placements that no + /// longer exist, repeats, and order lists of missing components. Body names are left alone: + /// only an evaluated model knows them. + pub fn browser_pruned(&self) -> Option<(Vec, BTreeMap>)> { + if self.browser_groups.is_empty() && self.browser_order.is_empty() { + return None; + } + let components: BTreeSet = self.components.iter().map(|c| c.id).collect(); + let features: BTreeSet = self.features.iter().map(|f| f.id).collect(); + let placed_in: BTreeMap = self.occurrences.iter().map(|o| (o.id, o.parent)).collect(); + let component_exists = |c: u64| c == 0 || components.contains(&c); + let placed = |component: u64, key: &str| key.parse::().ok().and_then(|o| placed_in.get(&o)) == Some(&component); + // Body names cannot be checked here; the other folders hold feature ids. + let item_exists = |folder: &str, component: u64, key: &str| match folder { + "bodies" => true, + "components" => placed(component, key), + _ => key.parse::().is_ok_and(|id| features.contains(&id)), + }; + let mut groups = self.browser_groups.clone(); + let mut order = self.browser_order.clone(); + groups.retain(|g| component_exists(g.component) && BROWSER_FOLDERS.contains(&g.folder.as_str())); + let known: BTreeMap = groups.iter().map(|g| (g.id, (g.component, g.folder.clone()))).collect(); + let parents: BTreeMap> = groups + .iter() + .map(|g| (g.id, g.parent.filter(|p| *p != g.id && known.get(p).is_some_and(|(c, f)| *c == g.component && *f == g.folder)))) + .collect(); + // A loop, or a chain too deep, is cut at the group that makes it. + let too_deep = |id: u64| std::iter::successors(Some(id), |g| parents.get(g).copied().flatten()).nth(MAX_GROUP_NESTING).is_some(); + let kept: BTreeMap> = parents.iter().map(|(id, p)| (*id, if too_deep(*id) { None } else { *p })).collect(); + for g in &mut groups { + g.parent = kept[&g.id]; + } + let mut taken: BTreeSet<(u64, String, String)> = BTreeSet::new(); + for g in &mut groups { + let (component, folder, id) = (g.component, g.folder.clone(), g.id); + let mut seen = BTreeSet::new(); + g.items.retain(|e| match e { + BrowserEntry::Group(c) => kept.get(c) == Some(&Some(id)) && seen.insert(*c), + BrowserEntry::Item(k) => item_exists(&folder, component, k) && taken.insert((component, folder.clone(), k.clone())), + }); + } + let top = |c: u64, folder: &str, id: u64| kept.get(&id) == Some(&None) && known.get(&id).is_some_and(|(kc, kf)| *kc == c && kf == folder); + order.retain(|key, list| { + let Some((c, folder)) = key.split_once('/') else { return false }; + let Some(c) = c.parse::().ok().filter(|c| component_exists(*c)) else { return false }; + if !BROWSER_FOLDERS.contains(&folder) { + return false; + } + let mut seen = BTreeSet::new(); + list.retain(|e| match e { + BrowserEntry::Group(id) => top(c, folder, *id) && seen.insert(e.clone()), + BrowserEntry::Item(k) => item_exists(folder, c, k) && seen.insert(e.clone()), + }); + !list.is_empty() + }); + (groups != self.browser_groups || order != self.browser_order).then_some((groups, order)) + } + + /// Put placements of one component in the order the browser shows them: the saved + /// `components` order, then the rest as they were. + pub fn sort_placements(&self, parent: u64, ids: &mut [u64]) { + let Some(order) = self.browser_order.get(&format!("{parent}/components")) else { return }; + let rank: BTreeMap<&str, usize> = order.iter().enumerate().filter_map(|(i, e)| Some((e.as_item()?, i))).collect(); + ids.sort_by_cached_key(|id| rank.get(id.to_string().as_str()).copied().unwrap_or(usize::MAX)); + } +} diff --git a/crates/doc/src/canvas.rs b/crates/doc/src/canvas.rs index e3f3de5bb..dd52be031 100644 --- a/crates/doc/src/canvas.rs +++ b/crates/doc/src/canvas.rs @@ -2,7 +2,8 @@ //! The image bytes travel inside the design file (base64), so it reopens without the original. use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Plane, Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use crate::PlaneRef; @@ -15,8 +16,10 @@ pub struct Canvas { pub name: String, /// `png` or `jpeg`. pub format: String, - /// The image file, base64. - pub data: String, + /// The image file, base64. Shared rather than owned: every edit clones the document (the undo + /// history keeps the old one), and an image of up to 16 MiB copied into each of the 200 undo + /// states would hold gigabytes. Serialized as the same JSON string as before. + pub data: std::sync::Arc, /// Pixel size of the image. pub pixels: [u32; 2], pub plane: PlaneRef, diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index 83cb3b733..f2f1e7526 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -176,6 +176,8 @@ pub(crate) fn remap_link( remap_link(b, ids, names, bodies, depth + 1); } LinkSource::Plane { name } => mapped_name(name, names), + // A construction axis, by name (#9324); the origin axes are no feature's. + LinkSource::Axis { name } if !matches!(name.as_str(), "X" | "Y" | "Z") => mapped_name(name, names), _ => {} } } @@ -205,6 +207,7 @@ impl crate::Feature { K::Draft { neutral, .. } => checked_plane(neutral, 0)?, K::ReplaceFace { target, .. } => checked_plane(target, 0)?, K::SurfaceExtend { up_to: Some(crate::ExtendTo::Plane(plane)), .. } => checked_plane(plane, 0)?, + K::Thread { up_to: Some(crate::ThreadLimit::Plane(plane)), .. } => checked_plane(plane, 0)?, K::ConstructionAxis { def } => { for r in def.refs() { checked_geo(r, 0)?; @@ -274,6 +277,7 @@ impl crate::Feature { K::Draft { neutral, .. } => remap_plane(neutral, ids, bodies, 0)?, K::ReplaceFace { target, .. } => remap_plane(target, ids, bodies, 0)?, K::SurfaceExtend { up_to: Some(crate::ExtendTo::Plane(plane)), .. } => remap_plane(plane, ids, bodies, 0)?, + K::Thread { up_to: Some(crate::ThreadLimit::Plane(plane)), .. } => remap_plane(plane, ids, bodies, 0)?, K::ConstructionAxis { def } => { for r in def.refs_mut() { remap_geo(r, ids, bodies, 0)?; @@ -287,6 +291,17 @@ impl crate::Feature { K::Revolve { axis: crate::AxisRef::Model { geo }, .. } | K::SurfaceRevolve { axis: crate::AxisRef::Model { geo }, .. } | K::Pattern { pattern: crate::PatternKind::Circular { axis_ref: Some(geo), .. }, .. } => remap_geo(geo, ids, bodies, 0)?, + // An Align frame's joint origin finds its faces and edges by name, as the feature's + // own face names are found. + K::Align { from_frame, to_frame, .. } => { + for fr in [from_frame, to_frame].into_iter().flatten() { + if let crate::AlignFrame::Origin { origin } = fr { + for n in origin.snap.face_names_mut() { + *n = remap_topology(n, ids, bodies); + } + } + } + } _ => {} } Ok(()) @@ -314,7 +329,7 @@ fn checked_plane(p: &PlaneRef, depth: usize) -> crate::Result<()> { checked_geo(g, depth + 1)?; } } - PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } => { + PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } | PlaneRef::AxisPoint { axis: a, point: b } => { checked_geo(a, depth + 1)?; checked_geo(b, depth + 1)?; } @@ -331,7 +346,12 @@ fn checked_plane(p: &PlaneRef, depth: usize) -> crate::Result<()> { checked_geo(b, depth + 1)?; checked_geo(c, depth + 1)?; } - PlaneRef::Tangent { face, .. } => checked_geo(face, depth + 1)?, + PlaneRef::Tangent { face, reference, .. } => { + checked_geo(face, depth + 1)?; + if let Some(r) = reference { + checked_geo(r, depth + 1)?; + } + } PlaneRef::AlongPath { path, .. } => checked_geo(path, depth + 1)?, _ => {} } diff --git a/crates/doc/src/config_certificates.rs b/crates/doc/src/config_certificates.rs index f2080b01f..d2424d718 100644 --- a/crates/doc/src/config_certificates.rs +++ b/crates/doc/src/config_certificates.rs @@ -1,7 +1,8 @@ //! Certificates are producer identities, never a nearest-surface selection. use crate::{DocError, Document, FeatureKind, ModelBody, Result, SolvedSketch}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Seg2; +use solidcore_record::Seg2; +use solidcraft_geom::prelude::*; fn valid_signature(outer: &[String], holes: &[Vec]) -> bool { let valid = |ids: &[String]| { @@ -68,11 +69,11 @@ pub(crate) fn cap_key(outer: &[String], holes: &[Vec]) -> String { } format!("{:x}", hash.finalize()) } -fn exact_region_signature(curves: &ExactSketchCurves, region: &solidcraft_geom::Region2) -> Option { +fn exact_region_signature(curves: &ExactSketchCurves, region: &solidcore_record::Region2) -> Option { if region.outer.segs.len() + region.holes.iter().map(|hole| hole.segs.len()).sum::() > 4096 || region.holes.len() > 128 { return None; } - let signature = |outline: &solidcraft_geom::Loop2| { + let signature = |outline: &solidcore_record::Loop2| { let mut ids = outline.segs.iter().map(|segment| curves.find(segment)).collect::>>()?; ids.sort(); ids.dedup(); @@ -116,7 +117,7 @@ pub(crate) fn extrude_cap_bindings(sketch: &SolvedSketch, bodies: &[solidcraft_k let mut counts = std::collections::BTreeMap::new(); let mut bindings = Vec::with_capacity(bodies.len()); for body in bodies { - let mut cached: Option<(&solidcraft_geom::Region2, Option)> = None; + let mut cached: Option<(&solidcore_record::Region2, Option)> = None; let mut values = Vec::new(); for source in body.face_sources().into_iter().flatten() { let signature = if let Some(FaceSource::ExtrudeCap { region, high, .. }) = source { @@ -392,6 +393,8 @@ pub(crate) struct ExactSketchCurves<'a> { /// Each analytic curve's id, whether it is projected (linked) reference geometry, and its /// segments. segments: Vec<(&'a str, bool, Vec)>, + /// Each free-form curve's id (ellipses, conics, splines) and its exact segments. + free_form: Vec<(&'a str, Vec)>, } impl<'a> ExactSketchCurves<'a> { @@ -399,10 +402,17 @@ impl<'a> ExactSketchCurves<'a> { /// and segment allocation must not be repeated for every generated face. pub(crate) fn new(sketch: &'a SolvedSketch) -> Self { let mut segments = Vec::new(); + let mut free_form = Vec::new(); if sketch.sketch.curves.len() > 2000 { - return Self { segments }; + return Self { segments, free_form }; } for (index, curve) in sketch.sketch.curves.iter().enumerate() { + if !curve.construction + && let Some(exact) = sketch.sketch.exact_segs(index) + { + free_form.push((curve.id.as_str(), exact)); + continue; + } if curve.construction || !matches!( curve.kind, @@ -424,7 +434,21 @@ impl<'a> ExactSketchCurves<'a> { }; segments.push((curve.id.as_str(), curve.link.is_some(), originals)); } - Self { segments } + Self { segments, free_form } + } + + /// The one free-form sketch curve (an ellipse, conic or spline) a generated segment is a + /// whole piece of, either way round: one of the exact segments the curve is made of. A + /// segment two curves share stays ambiguous. + pub(crate) fn find_free_form(&self, generated: &Seg2) -> Option { + let reversed = generated.reversed(); + let mut found: Option> = None; + for (id, originals) in &self.free_form { + if originals.iter().any(|original| *original == *generated || *original == reversed) { + found = Some(if found.is_some() { None } else { Some(*id) }); + } + } + found.flatten().map(str::to_owned) } /// The one sketch curve a generated segment lies on. A curve drawn over projected @@ -614,7 +638,7 @@ fn exact_segment_contains(original: &Seg2, generated: &Seg2) -> bool { (Seg2::Line { a, b }, Seg2::Line { a: c, b: d }) => { let direction = *b - *a; let scale = direction.len().max((*d - *c).len()).max(1.); - let interval = |point: solidcraft_geom::Vec2| { + let interval = |point: solidcore_record::Vec2| { let t = (point - *a).dot(direction) / direction.len2(); (-1e-10..=1. + 1e-10).contains(&t) }; @@ -650,7 +674,12 @@ fn exact_segment_contains(original: &Seg2, generated: &Seg2) -> bool { } impl Document { - pub fn configuration_face_target(&self, body: &ModelBody, index: usize, point: solidcraft_geom::Vec3) -> Result { + pub fn configuration_face_target( + &self, + body: &ModelBody, + index: usize, + point: solidcore_record::Vec3, + ) -> Result { let names = crate::naming::face_names(body); let mut name = names .get(index) @@ -719,7 +748,7 @@ impl Document { certificate.validate()?; Ok(Some(certificate)) } - pub fn strong_face_target(&self, body: &ModelBody, index: usize, point: solidcraft_geom::Vec3) -> Result { + pub fn strong_face_target(&self, body: &ModelBody, index: usize, point: solidcore_record::Vec3) -> Result { let mut target = self.configuration_face_target(body, index, point)?; match body.body.face_sources().and_then(|sources| sources.get(index)).and_then(Option::as_ref) { Some(solidcraft_kernel::FaceSource::Box { producer: Some(producer), axis, high, .. }) => { @@ -752,27 +781,27 @@ impl Document { /// is), projected onto it. A face that moves along its normal keeps the frame where it was; /// one that moves within its plane (a Move feature) keeps it too, as a sketch on a face does /// in the definition's coordinates. -pub fn lineage_frame(body: &ModelBody, plane: &solidcraft_geom::Plane) -> Option { - use solidcraft_geom::Vec3; +pub fn lineage_frame(body: &ModelBody, plane: &solidcore_record::Plane) -> Option { + use solidcore_record::Vec3; let n = plane.normal(); let m = &body.source_transform; let origin = crate::apply_point(m, Vec3::ZERO); let axis = [Vec3::X, Vec3::Y, Vec3::Z].into_iter().filter_map(|a| crate::apply_vector(m, a).normalized()).find(|a| a.dot(n).abs() < 0.6)?; let x = axis - n * axis.dot(n); let origin = origin - n * (origin - plane.origin).dot(n); - solidcraft_geom::Plane::new(origin, x, n.cross(x)) + solidcore_record::Plane::new(origin, x, n.cross(x)) } /// Whether Split Face split `body`'s faces on `plane` (a split line lies on it). -fn split_on_purpose(body: &ModelBody, plane: &solidcraft_geom::Plane) -> bool { +fn split_on_purpose(body: &ModelBody, plane: &solidcore_record::Plane) -> bool { let tolerance = 1e-6 * (1. + body.body.size()); let on_plane = - |line: &Vec| !line.is_empty() && line.iter().all(|p| (*p - plane.origin).dot(plane.normal()).abs() <= tolerance); + |line: &Vec| !line.is_empty() && line.iter().all(|p| (*p - plane.origin).dot(plane.normal()).abs() <= tolerance); body.body.split_lines().is_some_and(|lines| lines.iter().any(on_plane)) } /// Whether two exact planes are one oriented plane (pieces of one face). -fn same_oriented_plane(a: &solidcraft_geom::Plane, b: &solidcraft_geom::Plane, scale: f64) -> bool { +fn same_oriented_plane(a: &solidcore_record::Plane, b: &solidcore_record::Plane, scale: f64) -> bool { a.normal().dot(b.normal()) >= 1. - 1e-8 && (b.origin - a.origin).dot(a.normal()).abs() <= 1e-7 * (1. + scale) } @@ -780,7 +809,7 @@ impl Document { /// The exact plane an anchor on face `index` of `body` is measured in: the construction /// certificate's plane, or for a [`FaceCertificate::Lineage`] face its current exact plane in /// the [`lineage_frame`]. - pub fn anchor_face_plane(&self, body: &ModelBody, index: usize, certificate: Option<&FaceCertificate>) -> Option { + pub fn anchor_face_plane(&self, body: &ModelBody, index: usize, certificate: Option<&FaceCertificate>) -> Option { match certificate { Some(FaceCertificate::Lineage) => body.body.planar_face(index).and_then(|plane| lineage_frame(body, &plane)), _ => body.body.face_plane(index), @@ -796,7 +825,7 @@ impl Document { &self, body: &ModelBody, index: usize, - point: solidcraft_geom::Vec3, + point: solidcore_record::Vec3, ) -> Option { let names = crate::naming::names(body); if !names.verified(index) { @@ -842,8 +871,13 @@ impl Document { }; let mut indices: Vec = names.faces.iter().enumerate().filter(|(_, face)| piece_of(face)).map(|(index, _)| index).collect(); if indices.is_empty() { - indices = - names.info.iter().enumerate().filter(|(_, info)| info.aliases.iter().any(|alias| alias == name)).map(|(index, _)| index).collect(); + indices = names + .info + .iter() + .enumerate() + .filter(|(_, info)| info.synonyms.iter().chain(&info.aliases).any(|other| other == name)) + .map(|(index, _)| index) + .collect(); } if indices.is_empty() { return Err(DocError::Unknown(format!("face `{name}` on `{}` no longer exists", body.name))); @@ -950,7 +984,7 @@ mod tests { SolvedSketch { feature: 1, name: "sources".into(), - plane: solidcraft_geom::Plane::XY, + plane: solidcore_record::Plane::XY, sketch, report, profiles: Vec::new(), @@ -985,7 +1019,7 @@ mod tests { #[test] fn prepared_sources_keep_exact_identity_and_reject_ambiguity() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; let mut sketch = solidcraft_sketch::Sketch::new(); sketch.add_line(Vec2::ZERO, Vec2::new(10., 0.), None, None, Some("line")).unwrap(); sketch.add_circle(Vec2::new(20., 0.), 2., None, Some("circle")).unwrap(); @@ -1010,7 +1044,7 @@ mod tests { #[test] fn a_curve_drawn_over_a_projected_boundary_is_the_source() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; // A face sketch's live boundary, with a profile edge traced over it (issue #489). let mut sketch = solidcraft_sketch::Sketch::new(); let projected = sketch.add_line(Vec2::ZERO, Vec2::new(10., 0.), None, None, Some("edge")).unwrap(); @@ -1034,7 +1068,7 @@ mod tests { #[test] #[ignore = "manual optimized certification microbenchmark; no timing assertion"] fn benchmark_prepared_extrude_sources() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; let mut sketch = solidcraft_sketch::Sketch::new(); for i in 0..1000 { let y = i as f64; @@ -1087,7 +1121,7 @@ mod tests { #[test] fn analytic_arc_interval_refuses_unsampled_gaps_and_accepts_wrap_reversal() { let radians = |degrees: f64| degrees.to_radians(); - let arc = |start, sweep| Seg2::Arc { center: solidcraft_geom::Vec2::default(), radius: 10., start: radians(start), sweep: radians(sweep) }; + let arc = |start, sweep| Seg2::Arc { center: solidcore_record::Vec2::default(), radius: 10., start: radians(start), sweep: radians(sweep) }; assert!(!exact_segment_contains(&arc(10., 350.), &arc(20., 360.)), "five point probes missed the missing ten-degree gap"); assert!(!exact_segment_contains(&arc(10., 350.), &arc(20., -360.))); assert!(exact_segment_contains(&arc(350., 40.), &arc(355., 20.))); diff --git a/crates/doc/src/config_clone.rs b/crates/doc/src/config_clone.rs index c85eed89e..0860271d6 100644 --- a/crates/doc/src/config_clone.rs +++ b/crates/doc/src/config_clone.rs @@ -142,7 +142,7 @@ mod tests { body: "Old".into(), origin_feature: 3, name: "F3:+z".into(), - point: solidcraft_geom::Vec3::new(1., 1., 2.), + point: solidcore_record::Vec3::new(1., 1., 2.), certificate: None, }), ], @@ -199,7 +199,7 @@ mod tests { body: "Foreign".into(), origin_feature: 3, name: "F3:+z".into(), - point: solidcraft_geom::Vec3::ZERO, + point: solidcore_record::Vec3::ZERO, certificate: None, }), ], diff --git a/crates/doc/src/config_shell_tests.rs b/crates/doc/src/config_shell_tests.rs index ad33c690a..5333ac9b1 100644 --- a/crates/doc/src/config_shell_tests.rs +++ b/crates/doc/src/config_shell_tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::{FeatureKind, Model, PlaneRef}; use serde_json::json; -use solidcraft_geom::{Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; fn shell_document() -> (Document, u64, u64) { let mut doc = Document::new("certified shell"); @@ -43,15 +43,15 @@ fn face_index(body: &ModelBody, inner: bool) -> usize { #[test] fn shell_planar_raw_bounds_flat_identity_and_clone_remap() { - let plane = solidcraft_geom::Plane::XY; - let same = |planes: &[Option]| super::super::styles::shell_plane_family(planes.iter().copied()); + let plane = solidcore_record::Plane::XY; + let same = |planes: &[Option]| super::super::styles::shell_plane_family(planes.iter().copied()); assert!(same(&[Some(plane), Some(plane)])); assert!(!same(&[])); assert!(!same(&[Some(plane), None])); for different in [ - solidcraft_geom::Plane { origin: Vec3::X, ..plane }, - solidcraft_geom::Plane { x: -plane.x, y: -plane.y, ..plane }, - solidcraft_geom::Plane { y: -plane.y, ..plane }, + solidcore_record::Plane { origin: Vec3::X, ..plane }, + solidcore_record::Plane { x: -plane.x, y: -plane.y, ..plane }, + solidcore_record::Plane { y: -plane.y, ..plane }, ] { assert!(!same(&[Some(plane), Some(different)])); } @@ -221,7 +221,7 @@ fn regularized_shell_keeps_legacy_and_explicit_single_face_projections_closed() let mut sketch = solidcraft_sketch::Sketch::new(); let link = sketch.add_link(solidcraft_sketch::LinkKind::Project, source, &legacy.geom).unwrap(); sketch.links[0].face_name = Some(crate::naming::face_names(body)[index].clone()); - let warnings = crate::project::refresh_links(&doc, &values, &state, &plane, &mut sketch); + let warnings = crate::project::refresh_links(&doc, &values, &state, &plane, &mut sketch).unwrap(); assert!(warnings.is_empty(), "{warnings:?}"); assert!(!sketch.links[0].lost); assert!(!sketch.update_link(&link, &explicit.geom).unwrap()); @@ -230,8 +230,8 @@ fn regularized_shell_keeps_legacy_and_explicit_single_face_projections_closed() } #[test] -fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material() { - let (mut doc, _, shell) = shell_document(); +fn saved_former_strip_projection_asks_for_its_face_again_without_expanding_healthy_material() { + let (mut doc, _, _) = shell_document(); let mut model = Model::new(); model.evaluate(&doc); let state = model.state(); @@ -240,27 +240,10 @@ fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material let plane = body.body.face_plane(index).unwrap(); let stem = crate::naming::face_names(body)[index].clone(); assert_eq!(crate::naming::strip_piece(&stem), stem); - // Reconstruct the original raw shell before certificate stamping/regularization, - // and run the unchanged historical naming/capture path on its actual strip. - let before = model.state_before(shell); - // Legacy Shell did not propagate construction certificates. Omit transient - // metadata here; operand paint also disables new wall-run coalescence so - // this control retains the actual historical raw pieces. - let raw_source = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(20., 12., 10.)).unwrap().with_paint(Some(solidcraft_kernel::Paint { - opacity: 1., - faces: vec![solidcraft_kernel::FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }], - })); - let raw = solidcraft_kernel::shell(&raw_source, &[Vec3::new(5., 6., 10.)], 2.).unwrap(); - let mut old_body = ModelBody::new("Case".into(), raw, shell); - old_body.names = crate::naming::NameCell::new(Some(std::sync::Arc::new(crate::naming::NamingOrigin { - feature: doc.feature(shell).unwrap().clone(), - before, - depth: 1, - mats: vec![], - sheets: vec![], - }))); - let captured = crate::naming::face_name_at_body(&old_body, Vec3::new(20., 6., 1.)).unwrap(); - assert_eq!(crate::naming::parent_piece(&captured), Some(stem.as_str()), "actual strip capture records a piece name"); + // The builds before format 14 split this wall into strips along the opening and saved a + // projection of one of them by its number. The kernel's shell leaves the wall one face now, + // so the strip exists only as that saved name and geometry. + assert_eq!(crate::naming::face_name_at_body(body, Vec3::new(20., 6., 1.)).as_deref(), Some(stem.as_str()), "the shelled wall is one face"); // What the builds before format 14 saved for that piece: its number by centroid order. let former = format!("{stem}#1"); let mut sketch = solidcraft_sketch::Sketch::new(); @@ -274,10 +257,9 @@ fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material ) .unwrap(); sketch.links[0].face_name = Some(former.clone()); - let original = sketch.clone(); let sk = doc .add_feature( - FeatureKind::Sketch { plane: PlaneRef::Face { plane, at: Vec3::new(20., 6., 1.), name: Some(former), anchor: None }, sketch }, + FeatureKind::Sketch { plane: PlaneRef::Face { plane, at: Vec3::new(20., 6., 1.), name: Some(former.clone()), anchor: None }, sketch }, Some("Saved strip sketch"), ) .unwrap(); @@ -305,28 +287,19 @@ fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material let mut cold = Model::new(); cold.evaluate(&loaded); for current in [&model, &cold] { - let warning = current.results.iter().find(|r| r.id == sk).unwrap().warning.as_deref().unwrap(); - assert!(warning.contains("no longer exists; last geometry retained"), "{warning}"); - let state = current.state(); - let solved = state.sketch(sk).unwrap(); - assert!(solved.sketch.links[0].lost); - assert_eq!(solved.sketch.curves, original.curves); - assert_eq!(solved.sketch.points, original.points); - let material = state.bodies.iter().find(|body| body.feature == boss).unwrap(); - assert!( - (solidcraft_kernel::measure(&material.body).unwrap().volume - 24.).abs() < 1e-8, - "old24mm3 profile must not silently become120mm3 wall profile" - ); - let bounds = material.mesh().bounds(); - assert!((bounds.min.x - width).abs() < 1e-8 && (bounds.max.x - width - 1.).abs() < 1e-8); - assert!((bounds.max.y - 12.).abs() < 1e-8 && (bounds.max.z - 2.).abs() < 1e-8); + // The name was saved before format 14 (marked): it finds no face, so the sketch on it + // fails, asking for its face again, and so does the material made from it. + let result = current.results.iter().find(|r| r.id == sk).unwrap(); + let reference = format!("{}{former}", crate::naming::LEGACY_MARK); + assert_eq!(result.error.as_deref().and_then(crate::reselect_parts), Some(("Saved strip sketch", reference.as_str())), "{result:?}"); + assert!(current.results.iter().find(|r| r.id == boss).unwrap().error.is_some()); + assert!(current.state().bodies.iter().all(|body| body.feature != boss), "old 24 mm3 profile must not silently become the 120 mm3 wall"); } } } #[test] -fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { - use solidcraft_kernel::{FacePaint, Paint}; +fn saved_curved_strip_projection_asks_for_its_face_again_after_exact_wall_coalescence() { use solidcraft_sketch::{LinkKind, LinkSource, Sketch}; let mut doc = Document::new("saved curved strip"); doc.set_param("width", "80", Some("mm"), None).unwrap(); @@ -344,92 +317,45 @@ fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { Some("Corners"), ) .unwrap(); - let shell = doc - .add_feature( - FeatureKind::Shell { - faces: vec![crate::FacePick(Vec3::new(0., 0., 30.))], - thickness: "wall".into(), - body: Some("Case".into()), - direction: "inside".into(), - tangent_chain: false, - }, - Some("Shell"), - ) - .unwrap(); + doc.add_feature( + FeatureKind::Shell { + faces: vec![crate::FacePick(Vec3::new(0., 0., 30.))], + thickness: "wall".into(), + body: Some("Case".into()), + direction: "inside".into(), + tangent_chain: false, + }, + Some("Shell"), + ) + .unwrap(); let mut model = Model::new(); model.evaluate(&doc); assert!(model.results.iter().all(|r| r.error.is_none()), "{:?}", model.results); - let before = model.state_before(shell); - // Per-face paint disables the construction optimization: this control keeps - // the real pre-repair slab faces without forging a name or source witness. - let old_source = before - .body("Case") - .unwrap() - .body - .clone() - .with_paint(Some(Paint { opacity: 1., faces: vec![FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }] })); - let cavity_box = solidcraft_kernel::box_solid(Vec3::new(-38., -28., 2.), Vec3::new(38., 28., 35.)).unwrap(); - let cavity = solidcraft_kernel::fillet( - &cavity_box, - &[Vec3::new(38., 28., 15.), Vec3::new(-38., 28., 15.), Vec3::new(-38., -28., 15.), Vec3::new(38., -28., 15.)], - 4., - ) - .unwrap(); - let raw = solidcraft_kernel::boolean(&old_source, &cavity, solidcraft_kernel::BoolOp::Cut).unwrap().unwrap(); - let mut old_body = ModelBody::new("Case".into(), raw, shell); - old_body.names = crate::naming::NameCell::new(Some(std::sync::Arc::new(crate::naming::NamingOrigin { - feature: doc.feature(shell).unwrap().clone(), - before, - depth: 1, - mats: vec![], - sheets: vec![], - }))); + // A point low on the outer round of the +x+y corner (radius 6 about (34, 24)), below the + // cavity's floor at z = 2. let t = std::f64::consts::FRAC_1_SQRT_2; let at = Vec3::new(34. + 6. * t, 24. + 6. * t, 1.); - let former = crate::naming::face_name_at_body(&old_body, at).unwrap(); - let stem = crate::naming::strip_piece(&former).to_string(); - assert_ne!(former, stem, "actual old cylindrical strip must have a piece suffix"); let state = model.state(); let current = state.body("Case").unwrap(); let names = crate::naming::face_names(current); + let stem = crate::naming::face_name_at_body(current, at).unwrap(); + assert_eq!(crate::naming::strip_piece(&stem), stem, "the shelled wall's round is one exact face, floor to rim"); let index = names.iter().position(|name| name == &stem).unwrap(); - assert!(current.body.face_was_coalesced(index)); assert!(current.body.face_plane(index).is_none(), "witness grants no planar attachment authority"); - assert!(old_body.body.face_sources().is_none_or(|sources| sources.iter().enumerate().all(|(index, _)| !old_body.body.face_was_coalesced(index)))); - let mut old_state = (*model.state()).clone(); - old_state.bodies = vec![old_body]; + // What a build that sewed the cut slab by slab saved: the round in two pieces split at the + // cavity's floor, the projection made on the lower one, `#1` (pieces numbered up their + // longest spread), from z = 0 to 2. Projected on YZ, the quarter round from (40, 24) to + // (34, 30) is the rectangle y 24..30, z 0..2: its two arcs and its two straight sides. + let former = format!("{stem}#1"); + let reference = former.clone(); let source = LinkSource::Face { body: "Case".into(), at }; - // Recover the saved projection from the old face's complete raw topology. - // Display seam suppression must not discard a historical strip boundary. - let old_body = old_state.body("Case").unwrap(); - let old_index = crate::naming::face_on_body(old_body, &former, at).unwrap().0; - let mesh = old_body.mesh(); - let mut geometry = Vec::new(); - for (index, faces) in mesh.edge_faces.iter().enumerate() { - if !faces.contains(&(old_index as u32)) { - continue; - } - let points = &mesh.edges[index]; - let a = solidcraft_geom::Plane::YZ.to_local(*points.first().unwrap()); - let b = solidcraft_geom::Plane::YZ.to_local(*points.last().unwrap()); - let (a, b) = (Vec2::new(a.x, a.y), Vec2::new(b.x, b.y)); - assert!(a.dist(b) > 1e-6); - for point in points { - let q = solidcraft_geom::Plane::YZ.to_local(*point); - let q = Vec2::new(q.x, q.y); - let direction = b - a; - let t = ((q - a).dot(direction) / direction.dot(direction)).clamp(0., 1.); - assert!(q.dist(a + direction * t) < 1e-7, "exact cylindrical quadrant projects to a straight support"); - } - geometry.push(solidcraft_sketch::LinkGeom::Line(a, b)); - } - assert_eq!(geometry.len(), 4, "historical curved strip has a complete four-edge rectangular projection"); + let (a, b, c, d) = (Vec2::new(24., 0.), Vec2::new(30., 0.), Vec2::new(30., 2.), Vec2::new(24., 2.)); + let geometry: Vec<_> = [(a, b), (b, c), (c, d), (d, a)].into_iter().map(|(p, q)| solidcraft_sketch::LinkGeom::Line(p, q)).collect(); let mut sketch = Sketch::new(); sketch.add_link(LinkKind::Project, source, &geometry).unwrap(); sketch.links[0].face_name = Some(former); - let original = sketch.clone(); let sk = doc - .add_feature(FeatureKind::Sketch { plane: PlaneRef::Custom { plane: solidcraft_geom::Plane::YZ }, sketch }, Some("Saved corner strip")) + .add_feature(FeatureKind::Sketch { plane: PlaneRef::Custom { plane: solidcore_record::Plane::YZ }, sketch }, Some("Saved corner strip")) .unwrap(); let boss = doc .add_feature( @@ -452,26 +378,21 @@ fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { let mut cold = Model::new(); cold.evaluate(&loaded); for current in [&model, &cold] { + // No face is the piece any more, and the whole wall is not it: the sketch fails, + // asking for its face again, and so does the material made from it. The case builds. let result = current.results.iter().find(|r| r.id == sk).unwrap(); - assert!(result.error.is_none()); - assert!(result.warning.as_deref().unwrap().contains("no longer exists; last geometry retained")); + assert_eq!(result.error.as_deref().and_then(crate::reselect_parts), Some(("Saved corner strip", reference.as_str())), "{result:?}"); + assert!(current.results.iter().find(|r| r.id == boss).unwrap().error.is_some()); + assert!(current.results.iter().filter(|r| r.id != sk && r.id != boss).all(|r| r.error.is_none()), "{:?}", current.results); let state = current.state(); - let solved = state.sketch(sk).unwrap(); - assert!(solved.sketch.links[0].lost); - assert_eq!(solved.sketch.points, original.points); - assert_eq!(solved.sketch.curves, original.curves); - let material = state.bodies.iter().find(|body| body.feature == boss).unwrap(); - assert!( - (solidcraft_kernel::measure(&material.body).unwrap().volume - 12.).abs() < 1e-7, - "two-mm strip cannot expand to a full thirty-mm wall" - ); + assert!(state.body("Case").is_some()); + assert!(state.bodies.iter().all(|body| body.feature != boss), "two-mm strip cannot expand to a full thirty-mm wall"); } } } #[test] -fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { - use solidcraft_kernel::{BoolOp, FacePaint, Paint}; +fn saved_stepped_tab_cut_piece_projection_asks_for_its_face_again_without_expanding_material() { use solidcraft_sketch::{LinkKind, LinkSource, Sketch}; let mut doc = Document::new("public stepped tab case"); doc.set_param("length", "40", Some("mm"), None).unwrap(); @@ -498,46 +419,26 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { ) .unwrap(); doc.feature_mut(tool).unwrap().body_names = vec!["Pocket tool".into()]; - let cut = doc - .add_feature( - FeatureKind::Combine { target: "Case".into(), tools: vec!["Pocket tool".into()], operation: crate::Operation::Cut, keep_tools: false }, - Some("Pocket"), - ) - .unwrap(); + doc.add_feature( + FeatureKind::Combine { target: "Case".into(), tools: vec!["Pocket tool".into()], operation: crate::Operation::Cut, keep_tools: false }, + Some("Pocket"), + ) + .unwrap(); let mut model = Model::new(); model.evaluate(&doc); assert!(model.results.iter().all(|r| r.error.is_none()), "{:?}", model.results); - let before = model.state_before(cut); - // A real per-face paint control preserves the former slab construction; - // no historical names or geometry are fabricated. - let old_stock = before - .body("Case") - .unwrap() - .body - .clone() - .with_paint(Some(Paint { opacity: 1., faces: vec![FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }] })); - let old_cut = solidcraft_kernel::boolean(&old_stock, &before.body("Pocket tool").unwrap().body, BoolOp::Cut).unwrap().unwrap(); - let mut old_body = ModelBody::new("Case".into(), old_cut, cut); - old_body.names = crate::naming::NameCell::new(Some(std::sync::Arc::new(crate::naming::NamingOrigin { - feature: doc.feature(cut).unwrap().clone(), - before, - depth: 1, - mats: vec![], - sheets: vec![], - }))); + // Older builds left Case's -x wall split by the Join and the Cut and saved a projection of + // the patch y 10..20, z 0..20 by its piece name. The kernel leaves the wall one face now: the + // patch is only that saved name and its rectangle on YZ. let at = Vec3::new(0., 15., 1.); - let former = crate::naming::face_name_at_body(&old_body, at).unwrap(); - assert_ne!(former, crate::naming::strip_piece(&former), "actual former bounded wall patch has a full piece name"); - let index = crate::naming::face_on_body(&old_body, &former, at).unwrap().0; - let mut old_state = crate::ModelState::default(); - old_state.bodies.push(old_body); - let plane = solidcraft_geom::Plane::YZ; - let resolved = crate::project::resolve_face_indices(&old_state, &plane, LinkKind::Project, "Case", &[index]).unwrap(); + let plane = solidcore_record::Plane::YZ; let current_state = model.state(); let current = current_state.body("Case").unwrap(); - let stem = crate::naming::strip_piece(&former); + let stem = crate::naming::face_name_at_body(current, at).unwrap(); + assert_eq!(crate::naming::strip_piece(&stem), stem, "the -x wall is one face"); + let former = format!("{stem}#1"); let current_names = crate::naming::face_names(current); - let merged = current_names.iter().position(|name| name == stem).unwrap(); + let merged = current_names.iter().position(|name| name == &stem).unwrap(); // The Join leaves Case's -x wall on its own support, so the wall keeps its exact box // identity through the Join and the Cut: one face again, no longer the saved piece. assert!( @@ -548,11 +449,12 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { "the merged wall carries its exact construction identity" ); assert!(!current_names.contains(&former)); + let corners = [Vec2::new(10., 0.), Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(10., 20.)]; + let geometry: Vec<_> = (0..4).map(|i| solidcraft_sketch::LinkGeom::Line(corners[i], corners[(i + 1) % 4])).collect(); let mut sketch = Sketch::new(); - sketch.add_link(LinkKind::Project, LinkSource::Face { body: "Case".into(), at }, &resolved.geom).unwrap(); - sketch.links[0].face_name = Some(former); - let original = sketch.clone(); - let captured = original.points.iter().filter(|p| p.link.is_some()).map(|p| p.pos).collect::>(); + sketch.add_link(LinkKind::Project, LinkSource::Face { body: "Case".into(), at }, &geometry).unwrap(); + sketch.links[0].face_name = Some(former.clone()); + let captured = sketch.points.iter().filter(|p| p.link.is_some()).map(|p| p.pos).collect::>(); assert_eq!(captured.len(), 4); assert!(captured.iter().all(|p| (p.x == 10. || p.x == 20.) && (p.y == 0. || p.y == 20.))); let sk = doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Custom { plane }, sketch }, Some("Saved wall patch")).unwrap(); @@ -577,22 +479,13 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { let mut cold = Model::new(); cold.evaluate(&reopened); for current in [&model, &cold] { + // No face is the patch any more, and the whole wall is not it: the sketch fails, + // asking for its face again, and so does the stock made from it. let result = current.results.iter().find(|r| r.id == sk).unwrap(); - assert!(result.error.is_none(), "{result:?}"); - assert!(result.warning.as_deref().is_some_and(|w| w.contains("no longer exists; last geometry retained")), "{result:?}"); + assert_eq!(result.error.as_deref().and_then(crate::reselect_parts), Some(("Saved wall patch", former.as_str())), "{result:?}"); + assert!(current.results.iter().find(|r| r.id == material).unwrap().error.is_some()); let state = current.state(); - let saved = state.sketch(sk).unwrap(); - assert!(saved.sketch.links[0].lost); - assert_eq!(saved.sketch.points, original.points); - assert_eq!(saved.sketch.curves, original.curves); - let stock = state.bodies.iter().find(|b| b.feature == material).unwrap(); - assert!( - (solidcraft_kernel::measure(&stock.body).unwrap().volume - 200.).abs() < 1e-7, - "saved10x20 patch must not become30x20 wall; actualvolume={}, bounds={:?}, originalpoints={:?}", - solidcraft_kernel::measure(&stock.body).unwrap().volume, - stock.mesh().bounds(), - original.points - ); + assert!(state.bodies.iter().all(|b| b.feature != material), "saved 10 x 20 patch must not become the 30 x 20 wall"); let case = state.body("Case").unwrap(); let expected = length * 30. * 20. + 8. * 10. * 8. - (length - 2. * wall) * (30. - 2. * wall) * (20. - wall); assert!((solidcraft_kernel::measure(&case.body).unwrap().volume - expected).abs() < 1e-6); diff --git a/crates/doc/src/config_styles.rs b/crates/doc/src/config_styles.rs index 7c148530b..a2d93f800 100644 --- a/crates/doc/src/config_styles.rs +++ b/crates/doc/src/config_styles.rs @@ -3,9 +3,10 @@ use super::Column; use crate::{DocError, Document, FeatureKind, ModelState, Result}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; -pub(crate) fn shell_plane_family(planes: impl IntoIterator>) -> bool { +pub(crate) fn shell_plane_family(planes: impl IntoIterator>) -> bool { let mut planes = planes.into_iter(); let Some(Some(first)) = planes.next() else { return false }; first.origin.is_finite() && first.x.is_finite() && first.y.is_finite() && planes.all(|plane| plane == Some(first)) @@ -282,13 +283,13 @@ impl Document { let count = body.body.face_sources().map_or(0, |sources| sources.len()); let mut indices: Vec<_> = (0..count).filter(|index| side(*index, true)).collect(); // A side drawn in collinear pieces is one face over all of them (#1788): a certificate - // made when the pieces were faces of their own finds it by the piece's name, which - // the joined face answers to. + // made when the pieces were faces of their own finds it by the piece's name, which is + // a name of the joined face too (one of its synonyms). if indices.is_empty() { let names = crate::naming::names(body); indices = (0..count) .filter(|index| { - side(*index, false) && crate::history_names::matches(&names, *index, &target.name) == Some(crate::history_names::Match::Alias) + side(*index, false) && crate::history_names::matches(&names, *index, &target.name) == Some(crate::history_names::Match::Exact) }) .collect(); } diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index cfa6935dc..9730864d1 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -6,10 +6,11 @@ //! vertex the names of the edges that meet there, so they follow the model when earlier features //! change; the picked point is the fallback. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Plane, Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; use solidcraft_kernel::{self as kernel, FaceSurface}; use crate::eval::{ModelBody, ModelState}; @@ -116,6 +117,11 @@ pub struct Construct { pub feature: u64, pub name: String, pub geom: ConstructGeom, + /// The bodies it was built from, when every pick it reads lies on a body + /// ([`source_bodies`]): a later Move of all of them carries it along (#10127). Empty when + /// it also reads something fixed (a point, a plane, a sketch), which keeps it in place. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub bodies: Vec, } /// Everything a reference needs to be resolved. @@ -141,16 +147,16 @@ fn construct<'a>(st: &'a ModelState, name: &str) -> Result<&'a ConstructGeom> { st.construct.iter().find(|c| c.name == name).map(|c| &c.geom).ok_or_else(|| DocError::Unknown(format!("construction `{name}`"))) } -/// The face picked: (body, face index, point on it). +/// The face picked: (body, face index, point on it). A face picked with a name is the face the +/// name finds, or the reference fails, asking for it to be picked again. fn face_of<'a>(st: &'a ModelState, at: Vec3, name: &Option) -> Result<(&'a ModelBody, usize, Vec3)> { // The named face itself: its nearest point to the old pick can lie on an edge it shares // (a corner round that a parameter moved away from the pick), where picking again by the // point finds the flat face beside it (#1255). - if let Some(hit) = name.as_deref().and_then(|n| crate::name_lookup::locate_face(st, n, at)) - && let Some(b) = st.bodies.get(hit.body).filter(|b| !b.body.is_mesh()) - && hit.face < b.body.face_count() - { - return Ok((b, hit.face, hit.point)); + if let Some(n) = name.as_deref() { + return crate::name_lookup::locate_face(st, n, at) + .and_then(|hit| st.bodies.get(hit.body).filter(|b| !b.body.is_mesh() && hit.face < b.body.face_count()).map(|b| (b, hit.face, hit.point))) + .ok_or_else(|| DocError::reselect(n)); } for b in bodies(st) { if let Some(fi) = crate::appearance::face_index_at(b, at) { @@ -165,16 +171,13 @@ fn edge_points(st: &ModelState, at: Vec3, name: &Option) -> Result(st: &'a ModelState, at: Vec3, name: &Option) -> Result<(&'a ModelBody, usize, Vec)> { let mut at = at; if let Some(n) = name { - for b in bodies(st) { - if let Ok((q, _)) = crate::naming::find_edge(b, n, at) { - at = q; - break; - } - } + at = bodies(st).find_map(|b| crate::naming::find_edge(b, n, at).ok()).ok_or_else(|| DocError::reselect(n.as_str()))?; } let mut best: Option<(f64, &ModelBody, usize, Vec)> = None; for b in bodies(st) { @@ -452,31 +455,66 @@ fn centre(ctx: &Ctx, g: &GeoRef) -> Result { } } -/// Point and unit tangent at fraction `t` along a polyline. -fn along(pts: &[Vec3], t: f64) -> Option<(Vec3, Vec3)> { - let total: f64 = pts.windows(2).map(|w| (w[1] - w[0]).len()).sum(); - if !(total > 0.0) { - return None; - } - let mut left = t.clamp(0.0, 1.0) * total; - for w in pts.windows(2) { - let l = (w[1] - w[0]).len(); - if l <= 0.0 { - continue; - } - if left <= l { - return Some((w[0] + (w[1] - w[0]) * (left / l), (w[1] - w[0]) * (1.0 / l))); - } - left -= l; - } - let (a, b) = (pts.get(pts.len() - 2)?, pts.last()?); - Some((*b, (*b - *a).normalized()?)) +/// The point a fraction `t` (0…1) of the way along a picked edge or sketch curve by arc length, +/// and the unit direction of travel there ([`kernel::along_path`]): exact on the curve itself. +fn along(ctx: &Ctx, g: &GeoRef, t: f64) -> Result<(Vec3, Vec3)> { + Ok(kernel::along_path(&path_segs(ctx, g)?, t)?) } -fn path_points(ctx: &Ctx, g: &GeoRef) -> Result> { +/// A picked edge or sketch curve as the path segments that are its curve exactly, from the end +/// the drawn curve starts at: a body edge's record curve ([`kernel::edge_path`]), a planar sketch +/// curve's exact pieces, a 3D sketch curve's arc, spline, line or linked exact curves. Only a +/// curve that exists as points alone runs along them: an intersection edge (its record holds no +/// exact curve, only the surfaces and a leader near it), a 3D curve known only as its points +/// (projected onto a face, iso curves), a spline above the exact pieces' degree. +fn path_segs(ctx: &Ctx, g: &GeoRef) -> Result> { + let lines = |pts: &[Vec3]| -> Vec { + pts.windows(2).filter(|w| w[0].dist(w[1]) > 0.0).map(|w| kernel::PathSeg::Line { a: w[0], b: w[1] }).collect() + }; match g { - GeoRef::Edge { at, name } => edge_points(ctx.st, *at, name), - GeoRef::SketchCurve { sketch, curve } => sketch_curve_points(ctx, *sketch, curve), + GeoRef::Edge { at, name } => { + let (b, i, pts) = edge_pick(ctx.st, *at, name)?; + let procedural = + b.body.record().edges.get(i).is_some_and(|e| matches!(e.parameters(), solidcore_record::brep::Curve::SurfaceIntersection { .. })); + if procedural { + return Ok(lines(&pts)); + } + let segs = kernel::edge_path(&b.body, i)?; + // The drawn edge sets which way t runs, as the picked edge's polyline has it. + let (Some(first), Some(start)) = (pts.first(), segs.first().map(kernel::PathSeg::start)) else { return Ok(segs) }; + let end = segs.last().map(kernel::PathSeg::end).unwrap_or(start); + Ok(if end.dist(*first) < start.dist(*first) { segs.iter().rev().map(kernel::PathSeg::reversed).collect() } else { segs }) + } + GeoRef::SketchCurve { sketch, curve } => { + let ss = ctx.st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?; + // Evaluation has already mapped wires into this component's frame: their coordinates + // are independent of the sketch plane. + if let Some(wire) = ss.sketch.wires.iter().find(|wire| wire.id == *curve) { + if let Some(arc) = &wire.arc { + let angle = solidcraft_sketch::arc_sweep(arc); + return Ok(vec![kernel::PathSeg::Arc { a: arc.start, center: arc.center, axis: arc.normal, angle }]); + } + if wire.fit.len() >= 3 { + let spline = kernel::PathPiece::Spline { fit: wire.fit.clone(), reversed: false }; + if let Some(spans) = spline.spans()? { + return Ok(spans); + } + } + if let [a, b] = wire.fit.as_slice() { + return Ok(vec![kernel::PathSeg::Line { a: *a, b: *b }]); + } + if !wire.exact.is_empty() { + let mut segs = Vec::new(); + for c in &wire.exact { + segs.extend(kernel::curve_path(&c.curve, c.interval)?); + } + return Ok(segs); + } + return Ok(lines(&wire.pts)); + } + let ci = ss.sketch.curve_index(curve).ok_or_else(|| DocError::Unknown(format!("curve `{curve}`")))?; + Ok(ss.sketch.exact_pieces(ci).iter().map(|s| kernel::PathSeg::of_sketch(&ss.plane, s)).collect()) + } _ => Err(bad("pick an edge or sketch curve as the path")), } } @@ -512,6 +550,48 @@ fn surface_normal(s: FaceSurface, p: Vec3) -> Option<(Vec3, Vec3)> { } } +/// A point over `s` where the face turns towards `towards` (a reference plane's normal): around +/// the axis of a cylinder, cone or torus, turned `angle` about it; straight at it on a sphere. Of +/// the two sides, the one `at` is on (#8822). +fn facing(s: FaceSurface, at: Vec3, towards: Vec3, angle: f64) -> Result { + let side = |d: Vec3, w: Vec3| if d.dot(w) < 0.0 { d * -1.0 } else { d }; + let around = |axis: Vec3, w: Vec3| -> Result<(Vec3, f64)> { + let d = (towards - axis * towards.dot(axis)) + .normalized() + .ok_or_else(|| bad("the reference is square to the face's axis: every plane tangent to the face meets it at a right angle"))?; + let d = d * angle.cos() + axis.cross(d) * angle.sin(); + let r = w - axis * w.dot(axis); + Ok((side(d, r), r.len())) + }; + if !angle.is_finite() { + return Err(bad("the angle is not a number")); + } + Ok(match s { + FaceSurface::Plane { .. } => at, + FaceSurface::Cylinder { origin, axis, radius } => { + let w = at - origin; + let (d, _) = around(axis.into(), w)?; + origin + axis * w.dot(axis) + d * radius + } + FaceSurface::Cone { apex, axis, .. } => { + let w = at - apex; + let (d, r) = around(axis.into(), w)?; + apex + axis * w.dot(axis) + d * r.max(1e-6) + } + // On the outer equator, where the tube faces away from the axis. + FaceSurface::Torus { center, axis, major, minor } => { + let (d, _) = around(axis.into(), at - center)?; + center + d * (major + minor) + } + FaceSurface::Sphere { center, radius } => { + if angle.abs() > 1e-12 { + return Err(bad("a sphere has no axis to turn the plane about: leave the angle out")); + } + center + side(towards, at - center) * radius + } + }) +} + fn face_surface_at(ctx: &Ctx, g: &GeoRef) -> Result<(FaceSurface, Vec3)> { match g { GeoRef::Face { at, name } => { @@ -553,6 +633,46 @@ fn line_line(a: (Vec3, Vec3), b: (Vec3, Vec3)) -> Option { Some(((p + u * s) + (q + v * t)) * 0.5) } +/// The bodies a construction built from `refs` lies on: each face, edge and vertex pick's body, +/// and the bodies of the constructions it is built from. Empty when any pick is not on a body +/// (a fixed point, the origin, a plane, a world axis, a sketch) or is not found: such a +/// construction is held by something a move of the bodies leaves where it is, so it stays. +pub(crate) fn source_bodies(ctx: &Ctx, refs: &[&GeoRef]) -> Vec { + let mut out: Vec = Vec::new(); + for g in refs { + let found: Vec = match g { + GeoRef::Face { at, name } => face_of(ctx.st, *at, name).map(|(b, ..)| vec![b.definition_name().to_string()]).unwrap_or_default(), + GeoRef::Edge { at, name } => edge_pick(ctx.st, *at, name).map(|(b, ..)| vec![b.definition_name().to_string()]).unwrap_or_default(), + GeoRef::Vertex { .. } => { + point(ctx, g).ok().and_then(|p| vertex_body(ctx.st, p)).map(|b| vec![b.definition_name().to_string()]).unwrap_or_default() + } + GeoRef::Axis { name } | GeoRef::ConstructPoint { name } => { + ctx.st.construct.iter().find(|c| c.name.as_str() == AsRef::::as_ref(name)).map(|c| c.bodies.clone()).unwrap_or_default() + } + _ => Vec::new(), + }; + if found.is_empty() { + return Vec::new(); + } + for b in found { + if !out.contains(&b) { + out.push(b); + } + } + } + out +} + +/// The body with a vertex (an end of one of its edges) at `p`. +fn vertex_body(st: &ModelState, p: Vec3) -> Option<&ModelBody> { + bodies(st).find(|b| { + let tol = (b.body.size() * 1e-3).max(1e-3); + b.body + .edges(tol) + .is_ok_and(|edges| edges.iter().flat_map(|e| [e.points.first(), e.points.last()]).flatten().any(|v| v.dist(p) <= 1e-6 * (1.0 + p.len()))) + }) +} + pub(crate) fn resolve_axis(ctx: &Ctx, d: &AxisDef) -> Result<(Vec3, Vec3)> { match d { AxisDef::ThroughFace { face } => line(ctx, face), @@ -595,7 +715,7 @@ pub(crate) fn resolve_point(ctx: &Ctx, d: &PointDef) -> Result { } PointDef::AlongPath { path, t } => { let t = Document::eval_in(ctx.vals, t, Kind::Unitless)?; - along(&path_points(ctx, path)?, t).map(|(p, _)| p).ok_or_else(|| bad("the path has no length")) + along(ctx, path, t).map(|(p, _)| p) } } } @@ -635,6 +755,16 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { }; Plane::new(o1, d1, n.cross(d1)).ok_or_else(degenerate) } + PlaneRef::AxisPoint { axis, point: at } => { + let (origin, dir) = line(ctx, axis)?; + let dir = dir.normalized().ok_or_else(|| bad("the axis has no direction"))?; + let delta = point(ctx, at)? - origin; + let across = delta - dir * delta.dot(dir); + if !across.len().is_finite() || across.len() < 1e-9 { + return Err(bad("the point is on the axis: pick a point off the axis to define a unique plane")); + } + Plane::new(origin, dir, across).ok_or_else(degenerate) + } PlaneRef::ThreePoints { a, b, c } => { let (pa, pb, pc) = (point(ctx, a)?, point(ctx, b)?, point(ctx, c)?); if (pb - pa).cross(pc - pa).len() < 1e-9 { @@ -642,9 +772,17 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { } Plane::new(pa, pb - pa, pc - pa).ok_or_else(degenerate) } - PlaneRef::Tangent { face, at } => { + PlaneRef::Tangent { face, at, reference, angle } => { let (s, _) = face_surface_at(ctx, face)?; - let (on, n) = surface_normal(s, *at).ok_or_else(|| bad("the point is on the face's axis"))?; + let at = match reference { + Some(r) => { + let towards = plane(ctx, r)?.normal().normalized().ok_or_else(degenerate)?; + let angle = angle.as_ref().map(|a| Document::eval_in(ctx.vals, a, Kind::Angle)).transpose()?.unwrap_or(0.0); + facing(s, *at, towards, angle)? + } + None => *at, + }; + let (on, n) = surface_normal(s, at).ok_or_else(|| bad("the point is on the face's axis"))?; Plane::from_normal(on, n).ok_or_else(degenerate) } PlaneRef::Perpendicular { plane: base, line: l } => { @@ -658,7 +796,7 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { } PlaneRef::AlongPath { path, t } => { let t = Document::eval_in(ctx.vals, t, Kind::Unitless)?; - let (p, tan) = along(&path_points(ctx, path)?, t).ok_or_else(|| bad("the path has no length"))?; + let (p, tan) = along(ctx, path, t)?; Plane::from_normal(p, tan).ok_or_else(degenerate) } PlaneRef::ThroughPoint { base, point: at } => { @@ -672,12 +810,15 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { impl GeoRef { /// Where a picked edge or face is now, found the way evaluation finds it (by its persistent - /// name, else at the picked point): a point on it. `None` for other references and for an + /// name when it has one, else at the picked point): a point on it. `None` for other references and for an /// edge or face that is gone. pub fn picked_point(&self, st: &ModelState) -> Option { match self { GeoRef::Edge { at, name } => { - let on = name.as_deref().and_then(|n| bodies(st).find_map(|b| crate::naming::find_edge(b, n, *at).ok())).map_or(*at, |(q, _)| q); + let on = match name.as_deref() { + Some(n) => bodies(st).find_map(|b| crate::naming::find_edge(b, n, *at).ok())?, + None => *at, + }; edge_pick(st, on, &None).ok().map(|_| on) } GeoRef::Face { at, name } => face_of(st, *at, name).ok().map(|(_, _, p)| p), @@ -783,10 +924,14 @@ impl PlaneRef { /// The references of a plane built from model geometry. pub fn refs_mut(&mut self) -> Vec<&mut GeoRef> { match self { - PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } => vec![a.as_mut(), b.as_mut()], + PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } | PlaneRef::AxisPoint { axis: a, point: b } => vec![a.as_mut(), b.as_mut()], PlaneRef::Perpendicular { plane, line } => vec![plane.as_mut(), line.as_mut()], PlaneRef::ThreePoints { a, b, c } => vec![a.as_mut(), b.as_mut(), c.as_mut()], - PlaneRef::Tangent { face, .. } => vec![face.as_mut()], + PlaneRef::Tangent { face, reference, .. } => { + let mut v = vec![face.as_mut()]; + v.extend(reference.as_deref_mut()); + v + } PlaneRef::AlongPath { path, .. } => vec![path.as_mut()], PlaneRef::ThroughPoint { base, point } => { let mut refs = base.refs_mut(); diff --git a/crates/doc/src/display_quality.rs b/crates/doc/src/display_quality.rs index 041c3497b..911cd8637 100644 --- a/crates/doc/src/display_quality.rs +++ b/crates/doc/src/display_quality.rs @@ -164,7 +164,7 @@ mod tests { /// closer to the surface, and the reference mesh the model reads never changes. #[test] fn each_level_has_its_own_plan_and_the_reference_mesh_stays() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let body = solidcraft_kernel::cylinder(Vec3::ZERO, Vec3::Z, 20.0, 50.0).unwrap(); let mb = crate::ModelBody::new("Body1".into(), body, 1); let reference = mb.mesh(); @@ -187,7 +187,13 @@ mod tests { } assert!(std::sync::Arc::ptr_eq(&reference, &mb.mesh())); assert_eq!(mb.display_plan_at(DisplayQuality::Normal).unwrap().vertex_count(), { - let plan = mb.body.display_plan_angular((mb.body.size() * 1e-3).max(1e-3), solidcraft_kernel::DISPLAY_ANGLE).unwrap(); + let plan = mb + .body + .mesh_plan(&solidcraft_kernel::MeshTolerance { + chord: (mb.body.size() * 1e-3).max(1e-3), + angle: Some(solidcraft_kernel::DISPLAY_ANGLE), + }) + .unwrap(); plan.vertex_count() }); } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 0ac5b7a72..7a1698fd2 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1,5 +1,6 @@ use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Plane, Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use solidcraft_kernel::Continuity; use solidcraft_sketch::Sketch; @@ -15,21 +16,6 @@ pub const MAX_PARAMS: usize = 10_000; /// numbers, and far from overflowing the next id. pub const MAX_FEATURE_ID: u64 = 1 << 52; -/// Screw direction independent of the cylinder's placement and the picked end. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, solidcraft_derive::Walk)] -#[serde(rename_all = "lowercase")] -pub enum ThreadHandedness { - #[default] - Right, - Left, -} - -impl ThreadHandedness { - pub fn is_right(&self) -> bool { - *self == Self::Right - } -} - /// A named parameter. User parameters are created by the user; model parameters (`d1`, `d2`…) /// are created by dimensions and features. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -97,10 +83,21 @@ pub enum PlaneRef { Midplane { a: Box, b: Box }, /// Through two straight edges (lines) that lie in one plane. TwoEdges { a: Box, b: Box }, + /// Through a line (axis) and a point not on that line. + AxisPoint { axis: Box, point: Box }, /// Through three points. ThreePoints { a: Box, b: Box, c: Box }, - /// Tangent to a face (cylinder, cone, sphere, torus) where the point `at` lies over it. - Tangent { face: Box, at: Vec3 }, + /// Tangent to a face (cylinder, cone, sphere, torus) where the point `at` lies over it. With + /// a `reference` (a plane or planar face), it touches where the face turns towards the + /// reference instead, turned by `angle` about the face's axis, on the side of `at` (#8822). + Tangent { + face: Box, + at: Vec3, + #[serde(default, skip_serializing_if = "Option::is_none")] + reference: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + angle: Option, + }, /// Square to an edge or sketch curve, a fraction `t` (expression, 0…1) of the way along it. AlongPath { path: Box, t: Expr }, /// Through a straight edge (or line, axis) and square to a plane (or planar face). @@ -196,6 +193,33 @@ impl Operation { } } +/// What a join makes of pieces that share no face: they share no volume and no area, so nothing +/// fuses them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Touching { + /// A piece that touches another only along an edge or at a point cannot be one solid with it + /// and becomes a body of its own; pieces that touch nothing stay one body of several pieces. + #[default] + Separate, + /// Every piece stays in one body, also those that touch along an edge or at a point. + OneBody, +} + +impl Touching { + pub fn parse(s: &str) -> Option { + Some(match s.to_ascii_lowercase().replace([' ', '-'], "_").as_str() { + "separate" => Touching::Separate, + "one_body" => Touching::OneBody, + _ => return None, + }) + } + + fn is_separate(&self) -> bool { + *self == Touching::Separate + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Direction { @@ -301,6 +325,13 @@ pub struct Extent { #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Taper angle")] pub taper: Option, + /// How a taper closes the profile's sharp corners, when the user chose + /// ([`solidcraft_kernel::draft_corners`] says what each rule gives at each corner). Without + /// it each profile takes preserve curvature where the kernel can build it exactly and the + /// tangent rule where a curve that is neither a line nor an arc has a corner, and the + /// feature's warning says so. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub corner: Option, /// To Object: end at the face (or vertex/point) at this point, instead of `distance`. #[serde(default, skip_serializing_if = "Option::is_none")] pub to: Option, @@ -312,6 +343,11 @@ pub struct Extent { /// `start_offset`). #[serde(default, skip_serializing_if = "Option::is_none")] pub from: Option, + /// A Join To Object leaves the body it runs to as its own body, joining only its targets. + /// Designs saved before a Join also took that body (format 39 and older, #8151) open with + /// it set, so they keep the bodies they were built with. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub to_body_apart: bool, } /// Thin Extrude: a wall of constant thickness along sketch curves instead of the profiles. @@ -569,6 +605,51 @@ impl<'de> Deserialize<'de> for FlangeEdge { } } +/// One side of an Align by frames (#6257): an origin and a z direction, found again from the +/// geometry each time the design is evaluated, so the bodies follow it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum AlignFrame { + /// A joint origin on the model (its component's coordinates): its origin and z. + Origin { origin: Box }, + /// A sketch point; z along the sketch's normal. + SketchPoint { sketch: SketchId, point: String }, + /// The centre of a sketch circle, arc or ellipse; z along the sketch's normal. + SketchCurve { sketch: SketchId, curve: String }, +} + +impl AlignFrame { + /// The frame's origin and unit z in the model state `st` (its component's coordinates). + pub fn resolve(&self, doc: &Document, st: &crate::ModelState) -> Result<(Vec3, Vec3)> { + let sketch = |id: &SketchId| st.sketch(id.0).ok_or_else(|| DocError::Unknown(format!("sketch {id}"))); + let (o, z) = match self { + AlignFrame::Origin { origin } => { + let m = crate::joints::resolve_origin(doc, st, origin)?; + (Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(m[2][0], m[2][1], m[2][2])) + } + AlignFrame::SketchPoint { sketch: id, point } => { + let ss = sketch(id)?; + let q = ss.sketch.point_index(point).and_then(|i| ss.sketch.point(i)); + (ss.plane.to_world(q.ok_or_else(|| DocError::Unknown(format!("sketch point `{point}`")))?), ss.plane.normal()) + } + AlignFrame::SketchCurve { sketch: id, curve } => { + use solidcraft_sketch::CurveKind; + let ss = sketch(id)?; + let kind = ss.sketch.curve_index(curve).and_then(|i| ss.sketch.curves.get(i)).map(|c| &c.kind); + let centre = match kind.ok_or_else(|| DocError::Unknown(format!("sketch curve `{curve}`")))? { + CurveKind::Circle { c, .. } | CurveKind::Arc { c, .. } | CurveKind::Ellipse { c, .. } => ss.sketch.point(*c), + _ => return Err(DocError::Invalid(format!("sketch curve `{curve}` is not a circle, arc or ellipse"))), + }; + (ss.plane.to_world(centre.ok_or_else(|| DocError::Invalid(format!("sketch curve `{curve}` has no centre")))?), ss.plane.normal()) + } + }; + match z.normalized() { + Some(z) if o.is_finite() => Ok((o, z)), + _ => Err(DocError::Invalid("the frame has no finite origin and direction".into())), + } + } +} + /// Feature definitions. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] #[serde(tag = "type", rename_all = "snake_case")] @@ -644,6 +725,18 @@ pub enum FeatureKind { /// (default) or a G2 patch repeating each blend up to the second order. #[serde(default, skip_serializing_if = "FilletCorner::is_rolling")] corner: FilletCorner, + /// Corners set back: each corner's patch starts its distance along every edge there + /// from the vertex instead of where the rounds meet (a constant-radius fillet only). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + setbacks: Vec, + /// How two rounds turn where they meet at a sharp side edge: in a mitre (the default) or + /// swept round it (a constant-radius, exact, rolling-corner fillet without setbacks only). + #[serde(default, skip_serializing_if = "FilletTurn::is_mitre")] + turn: FilletTurn, + /// Round each picked edge's tangent chain with it (the default: edges continuing it + /// smoothly at its ends, as far as they go), or only the picked edges. + #[serde(default = "yes", skip_serializing_if = "is_yes")] + tangent_chain: bool, }, Chamfer { edges: Vec, @@ -662,6 +755,9 @@ pub enum FeatureKind { flip: bool, #[serde(default, skip_serializing_if = "Option::is_none")] body: Option, + /// Cut each picked edge's tangent chain with it (the default), or only the picked edges. + #[serde(default = "yes", skip_serializing_if = "is_yes")] + tangent_chain: bool, }, Box { #[serde(with = "point_expr")] @@ -798,9 +894,17 @@ pub enum FeatureKind { #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Thread depth")] thread_depth: Option, - /// Screw direction of the cosmetic thread; older holes are right-handed. - #[serde(default, skip_serializing_if = "ThreadHandedness::is_right")] - handedness: ThreadHandedness, + /// The tapped thread's hand: right (the default) or left; never both. + #[serde(default, skip_serializing_if = "crate::thread_forms::is_default")] + hand: crate::thread_forms::ThreadHand, + /// The tapped thread cut into the wall (the groove between its teeth, as a modelled + /// `solid.thread` cuts it) instead of only listed. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + modeled: bool, + /// A modelled tapped thread's inner end, towards the bottom: it fades out over this + /// length (ISO 3508's runout); none: it stops square, or clear of a blind hole's bottom. + #[serde(default, skip_serializing_if = "Option::is_none")] + ease_out: Option, /// To Object: drill down to the face (or point) here instead of `depth`. #[serde(default, skip_serializing_if = "Option::is_none")] to: Option, @@ -817,14 +921,47 @@ pub enum FeatureKind { face: FacePick, #[serde(default, skip_serializing_if = "Option::is_none")] designation: Option, - /// Thread length from the face's end nearest `face`; `None` = full length. + /// Thread length from the end it starts at; `None` = full length (or `up_to`). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Length")] length: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] modeled: bool, - #[serde(default, skip_serializing_if = "ThreadHandedness::is_right")] - handedness: ThreadHandedness, + /// A point near the end of the face the thread starts at; `None`: the face's only free + /// end (no material past it), or the end the pick at `face` lies near. + #[serde(default, skip_serializing_if = "Option::is_none")] + from: Option, + /// Where the thread runs up to from the end it starts at, instead of a length. + #[serde(default, skip_serializing_if = "Option::is_none")] + up_to: Option, + /// The thread's form; `designation`'s prefix names it when this is the default. + #[serde(default, skip_serializing_if = "crate::thread_forms::is_default")] + form: crate::thread_forms::ThreadForm, + #[serde(default, skip_serializing_if = "crate::thread_forms::is_default")] + hand: crate::thread_forms::ThreadHand, + /// Starts (1 to 8): the lead is starts × pitch (unless `designation` gives the lead). + #[serde(default = "crate::thread_forms::one_start", skip_serializing_if = "crate::thread_forms::is_one_start")] + starts: u32, + /// The runout at the thread's inner end, the one away from where it starts (a groove + /// that fades out); none: the groove stops square there. + #[serde(default, skip_serializing_if = "Option::is_none")] + ease_out: Option, + /// The chamfered tip at the thread's free end (ISO 4753). + #[serde(default, skip_serializing_if = "crate::thread_forms::is_default")] + tip: crate::thread_forms::ThreadTip, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(angle = "Chamfer angle")] + chamfer_angle: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(length = "Chamfer depth")] + chamfer_depth: Option, + /// Buttress forms: which way the steep flank of the screw's teeth faces. + #[serde(default, skip_serializing_if = "crate::thread_forms::is_default")] + steep_flank: crate::thread_forms::SteepFlank, + /// Set on threads saved before holes were sized by their nominal diameter, whose size + /// was left to the tap drill: a 12 mm hole stays M14 there. New threads leave it off. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + old_auto_size: bool, }, /// Ruled loft through profiles of several sketches, in order. Loft { @@ -1078,6 +1215,24 @@ pub enum FeatureKind { /// bodies follow. Replaces `to`. #[serde(default, skip_serializing_if = "Option::is_none")] to_plane: Option, + /// Point-to-point alignment: the directions the offset moves along (the chosen world + /// X/Y/Z axes in the frame of the bodies being moved). `None`: all three axes, the + /// offset in full. + #[serde(default, skip_serializing_if = "Option::is_none")] + axes: Option>, + /// A frame on the bodies (#6257), found again on every evaluation: its origin and z are + /// the `from` point and normal. Replaces `from`, `from_normal` and `from_plane`. + #[serde(default, skip_serializing_if = "Option::is_none")] + from_frame: Option, + /// A frame the bodies move onto, found again on every evaluation, so they follow it when + /// it moves. Replaces `to`, `to_normal` and `to_plane`. + #[serde(default, skip_serializing_if = "Option::is_none")] + to_frame: Option, + /// A turn about the target's direction (its frame's z, face normal or plane normal), + /// through where `from` lands, after the move. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(angle = "Angle")] + angle: Option, }, /// A helical coil: a circular or square section swept `turns` times about `axis`, rising /// `pitch` per turn, on a helix of `diameter` (the section's centre, or its inside or outside). @@ -1196,9 +1351,10 @@ pub enum FeatureKind { body: Option, }, /// A perforation field (#732): round holes of `diameter` on a staggered (60°) or square grid of `pitch` over the - /// whole flat sheet, kept `margin` (default: the diameter) clear of its edges, cut-outs and bend zones. Stored like - /// a cosmetic thread: the holes go to the flat pattern, the DXF and the measured volume, not into the B-rep, so a - /// panel can carry tens of thousands of them. + /// whole flat sheet, or inside the closed profiles of `sketch` when it is given, kept `margin` (default: the + /// diameter) clear of its edges, cut-outs, bend zones and the outline. Stored like a cosmetic thread: the holes go + /// to the flat pattern, the DXF and the measured volume, not into the B-rep, so a panel can carry tens of thousands + /// of them. SheetPerforate { #[walk(length = "Diameter")] diameter: Expr, @@ -1211,6 +1367,13 @@ pub enum FeatureKind { pattern: Option, #[serde(default, skip_serializing_if = "Option::is_none")] body: Option, + /// The field's outline: a sketch on a face of the sheet. None: the whole sheet. + #[serde(default, skip_serializing_if = "Option::is_none")] + sketch: Option, + /// Which of the outline sketch's profiles bound the field. None: all of them. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(profiles_of = sketch)] + profiles: Option, }, /// Fold a sheet along a line on its base face: a sketch line (followed when the sketch /// changes), else the points `a`, `b`. @@ -1568,7 +1731,9 @@ pub enum FeatureKind { /// A strip of ruled surface `distance` wide hanging off the chain of `body`'s edges through /// `edges`, as a new surface body: along `mode` (`angle` from `direction`, or from the /// face's normal; along `direction`), from the face at `face` where it borders the chain; - /// `flip` puts it on the other side; sharp corners as `corners` says. + /// `flip` puts it on the other side; sharp corners as `corners` says. `far`: per chain edge, + /// the interior control points of a free strip's far curve (moved handles); `None` or + /// missing, the kernel's default curve. SurfaceRuled { body: BodyName, edges: Vec, @@ -1587,6 +1752,8 @@ pub enum FeatureKind { corners: RuledCorners, #[serde(default, skip_serializing_if = "Option::is_none")] face: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + far: Vec>>, }, /// A surface body's boundary edges through `edges` extended outward: by `distance`, or up /// to `up_to`; the surface continued (`mode` natural) or a run-off face along each edge @@ -1762,6 +1929,26 @@ pub enum FeatureKind { file: String, meshes: Vec, }, + /// Repair Part (#8371): faces SMLib refuses rebuilt on their own surfaces, free edges that + /// pair up within `gap` sewn, and, when `patch_holes`, the loops of free edges left patched + /// and sewn in (`kernel::repair`). + Repair { + body: BodyName, + #[walk(length = "Gap")] + gap: Expr, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + patch_holes: bool, + }, +} + +/// A fillet corner set back: the vertex at `vertex`, where every edge is rounded, has its corner +/// patch start `distance` along each of its edges from the vertex, the rounds running whole up to +/// their sections there. One distance for all of a corner's edges. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +pub struct CornerSetback { + pub vertex: Position, + #[walk(length = "Setback")] + pub distance: Expr, } /// What fills the corner where three blended edges meet. @@ -1771,7 +1958,9 @@ pub enum FilletCorner { /// A piece of the rolling ball's sphere: tangent (G1) to each blend. #[default] Rolling, - /// A G2 patch repeating each blend's surface up to the second order (see `corner_g2`). + /// The corner set back (its distance from the fillet's `setbacks`, else 1.5 × the radius) + /// and filled with a patch meeting the rounds and the faces round it to the second order + /// (`solidcraft_kernel::fillet_g2_corners`). G2, } @@ -1781,6 +1970,38 @@ impl FilletCorner { } } +/// How two constant rounds of one radius turn round a sharp, straight, convex side edge square to +/// both on a plane, such as the rounds along a boss's base at its upright edges. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FilletTurn { + /// The rounds run on to where they cross and meet in a mitre. + #[default] + Mitre, + /// The rounds end at the side edge and the corner is their section revolved about it, a + /// torus tangent to both (`solidcraft_kernel::FilletTurn::Swept`). + Swept, +} + +/// Why a swept turn is refused with a fillet's other options: the kernel sweeps the turn of two +/// constant rounds of one radius, at its own corners only. +pub const SWEPT_TAKES: &str = "a swept corner turns two constant rounds of one radius: `turn: swept` takes `type: constant`, \ +`corner: rolling`, no `setbacks` and `fit: exact` or `reduce`"; + +impl FilletTurn { + pub fn is_mitre(&self) -> bool { + *self == FilletTurn::Mitre + } + + /// The kernel's turn. + pub fn kernel(self) -> solidcraft_kernel::FilletTurn { + match self { + FilletTurn::Mitre => solidcraft_kernel::FilletTurn::Mitre, + FilletTurn::Swept => solidcraft_kernel::FilletTurn::Swept, + } + } +} + /// How Extend continues a surface past its edges. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -1800,6 +2021,29 @@ impl ExtendMode { } } +/// Where a thread runs up to instead of a length. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +#[serde(rename_all = "snake_case")] +pub enum ThreadLimit { + /// Where this point lies along the thread's axis (a point on a face, such as a shoulder). + Face(FacePick), + /// Where this plane crosses the thread's axis. + Plane(PlaneRef), +} + +/// A thread's runout length at one end: a length, or ISO 3508's standard (2.5 P) or short +/// (1.25 P) runout. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +#[serde(rename_all = "snake_case")] +pub enum ThreadRunout { + Standard, + Short, + Length { + #[walk(length = "Runout")] + length: Expr, + }, +} + /// What Extend extends up to instead of a distance. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] #[serde(rename_all = "snake_case")] @@ -2009,7 +2253,7 @@ fn fair_keep_edges() -> bool { /// Triangles of one imported mesh body (millimetres). The arrays are shared by clones: every /// edit keeps the design as it was for undo, and a scanned part's triangles (hundreds of /// megabytes) are not copied for that. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct MeshData { pub name: String, /// x, y, z per vertex. @@ -2020,6 +2264,20 @@ pub struct MeshData { pub color: Option<[f32; 3]>, } +/// The same mesh: shared arrays are the same without reading them, so the dirty check and +/// autosave after an edit elsewhere do not walk a scan's millions of coordinates. Arrays that +/// are not shared compare value by value, as before. Coordinates are finite (a design that +/// holds others does not load), so the shortcut only skips work. +impl PartialEq for MeshData { + fn eq(&self, other: &Self) -> bool { + use std::sync::Arc; + self.name == other.name + && self.color == other.color + && (Arc::ptr_eq(&self.triangles, &other.triangles) || self.triangles == other.triangles) + && (Arc::ptr_eq(&self.positions, &other.positions) || self.positions == other.positions) + } +} + /// Points of a sketch, by id. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct SketchPoints { @@ -2057,6 +2315,11 @@ pub struct Component { /// Free text properties of the definition (material grade, finish, supplier…), by name. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub properties: std::collections::BTreeMap, + /// Keeps this component's features (and its children's) out of the History bar (#10393). + /// The features still rebuild and the component still shows in the Browser; imported copies + /// whose features only exist to rebuild the copy can carry this flag. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub history_hidden: bool, } /// One loft section: profiles of a sketch. @@ -2192,7 +2455,11 @@ pub enum PatternKind { reversed2: bool, }, Circular { - origin: Position, + /// A point on the axis the copies turn about: numbers, or length expressions it follows + /// as the parameters change (#10852). + #[serde(with = "point_expr")] + #[walk(placement)] + origin: PointExpr, axis: Dir, #[walk(unitless = "Quantity")] count: Expr, @@ -2400,8 +2667,172 @@ impl FeatureKind { FeatureKind::Import { .. } => "BaseFeature", FeatureKind::MeshImport { .. } => "MeshFeature", FeatureKind::MeshConvert { .. } => "MeshConvertFeature", + FeatureKind::Repair { .. } => "RepairFeature", } } + + /// Design-file variant key (e.g. `"extrude"`, `"box"`, `"sheet_flange"`). + pub fn kind_key(&self) -> &'static str { + match self { + FeatureKind::BodyTransfer { .. } => "body_transfer", + FeatureKind::Sketch { .. } => "sketch", + FeatureKind::Extrude { .. } => "extrude", + FeatureKind::Revolve { .. } => "revolve", + FeatureKind::Fillet { .. } => "fillet", + FeatureKind::Chamfer { .. } => "chamfer", + FeatureKind::Box { .. } => "box", + FeatureKind::Cylinder { .. } => "cylinder", + FeatureKind::Sphere { .. } => "sphere", + FeatureKind::Torus { .. } => "torus", + FeatureKind::Cone { .. } => "cone", + FeatureKind::Combine { .. } => "combine", + FeatureKind::Pattern { .. } => "pattern", + FeatureKind::Mirror { .. } => "mirror", + FeatureKind::Hole { .. } => "hole", + FeatureKind::Thread { .. } => "thread", + FeatureKind::Loft { .. } => "loft", + FeatureKind::Sweep { .. } => "sweep", + FeatureKind::Shell { .. } => "shell", + FeatureKind::Draft { .. } => "draft", + FeatureKind::ConstructionPlane { .. } => "construction_plane", + FeatureKind::Split { .. } => "split", + FeatureKind::ConstructionAxis { .. } => "construction_axis", + FeatureKind::ConstructionPoint { .. } => "construction_point", + FeatureKind::SplitFace { .. } => "split_face", + FeatureKind::Scale { .. } => "scale", + FeatureKind::OffsetFace { .. } => "offset_face", + FeatureKind::DeleteFace { .. } => "delete_face", + FeatureKind::BoundingSolid { .. } => "bounding_solid", + FeatureKind::Pipe { .. } => "pipe", + FeatureKind::FrameMember { .. } => "frame_member", + FeatureKind::Emboss { .. } => "emboss", + FeatureKind::Rib { .. } => "rib", + FeatureKind::ReplaceFace { .. } => "replace_face", + FeatureKind::Align { .. } => "align", + FeatureKind::Coil { .. } => "coil", + FeatureKind::SheetBase { .. } => "sheet_base", + FeatureKind::SheetContour { .. } => "sheet_contour", + FeatureKind::SheetFlange { .. } => "sheet_flange", + FeatureKind::SheetHem { .. } => "sheet_hem", + FeatureKind::SheetPerforate { .. } => "sheet_perforate", + FeatureKind::SheetFold { .. } => "sheet_fold", + FeatureKind::SheetPath { .. } => "sheet_path", + FeatureKind::SheetUnfold { .. } => "sheet_unfold", + FeatureKind::SheetConvert { .. } => "sheet_convert", + FeatureKind::Boss { .. } => "boss", + FeatureKind::Lip { .. } => "lip", + FeatureKind::SnapFit { .. } => "snap_fit", + FeatureKind::Rest { .. } => "rest", + FeatureKind::BoundaryFill { .. } => "boundary_fill", + FeatureKind::Remove { .. } => "remove", + FeatureKind::Patch { .. } => "patch", + FeatureKind::Stitch { .. } => "stitch", + FeatureKind::Thicken { .. } => "thicken", + FeatureKind::SurfaceExtrude { .. } => "surface_extrude", + FeatureKind::Unstitch { .. } => "unstitch", + FeatureKind::ReverseNormal { .. } => "reverse_normal", + FeatureKind::SurfaceUntrim { .. } => "surface_untrim", + FeatureKind::SurfaceRevolve { .. } => "surface_revolve", + FeatureKind::SurfaceSweep { .. } => "surface_sweep", + FeatureKind::SurfaceLoft { .. } => "surface_loft", + FeatureKind::SurfaceOffset { .. } => "surface_offset", + FeatureKind::SurfaceRuled { .. } => "surface_ruled", + FeatureKind::SurfaceExtend { .. } => "surface_extend", + FeatureKind::SurfaceBlend { .. } => "surface_blend", + FeatureKind::SurfaceBoundary { .. } => "surface_boundary", + FeatureKind::SurfaceNetwork { .. } => "surface_network", + FeatureKind::SurfaceMatch { .. } => "surface_match", + FeatureKind::SurfaceFair { .. } => "surface_fair", + FeatureKind::SurfaceTrim { .. } => "surface_trim", + FeatureKind::Move { .. } => "move", + FeatureKind::Import { .. } => "import", + FeatureKind::MeshConvert { .. } => "mesh_convert", + FeatureKind::MeshImport { .. } => "mesh_import", + FeatureKind::Repair { .. } => "repair", + } + } + + /// Map a display or Rust type name (e.g. `"HoleFeature"`, `"EdgeFlangeFeature"`) + /// to the canonical design-file variant key (`"hole"`, `"sheet_flange"`). + pub fn type_name_to_kind_key(name: &str) -> Option<&'static str> { + Some(match name { + "BodyTransferFeature" => "body_transfer", + "Sketch" => "sketch", + "ExtrudeFeature" => "extrude", + "RevolveFeature" => "revolve", + "FilletFeature" => "fillet", + "ChamferFeature" => "chamfer", + "BoxFeature" => "box", + "CylinderFeature" => "cylinder", + "SphereFeature" => "sphere", + "TorusFeature" => "torus", + "ConeFeature" => "cone", + "CombineFeature" => "combine", + "RectangularPatternFeature" | "PathPatternFeature" | "CircularPatternFeature" => "pattern", + "MirrorFeature" => "mirror", + "ConstructionPlane" => "construction_plane", + "HoleFeature" => "hole", + "ThreadFeature" => "thread", + "LoftFeature" => "loft", + "SweepFeature" => "sweep", + "ShellFeature" => "shell", + "DraftFeature" => "draft", + "SplitBodyFeature" => "split", + "SplitFaceFeature" => "split_face", + "ConstructionAxis" => "construction_axis", + "ConstructionPoint" => "construction_point", + "MoveFeature" => "move", + "ScaleFeature" => "scale", + "OffsetFacesFeature" => "offset_face", + "DeleteFaceFeature" => "delete_face", + "OffsetSurfaceFeature" => "surface_offset", + "BoundingSolidFeature" => "bounding_solid", + "PipeFeature" => "pipe", + "FrameMemberFeature" => "frame_member", + "EmbossFeature" => "emboss", + "BossFeature" => "boss", + "LipFeature" | "GrooveFeature" => "lip", + "SnapFitFeature" => "snap_fit", + "RestFeature" => "rest", + "BoundaryFillFeature" => "boundary_fill", + "BaseFlangeFeature" => "sheet_base", + "ContourFlangeFeature" => "sheet_contour", + "EdgeFlangeFeature" => "sheet_flange", + "HemFeature" => "sheet_hem", + "PerforateFeature" => "sheet_perforate", + "FoldFeature" => "sheet_fold", + "PathFlangeFeature" => "sheet_path", + "UnfoldFeature" | "RefoldFeature" => "sheet_unfold", + "ConvertToSheetMetalFeature" => "sheet_convert", + "CoilFeature" => "coil", + "RibFeature" | "WebFeature" => "rib", + "ReplaceFaceFeature" => "replace_face", + "AlignFeature" => "align", + "RemoveFeature" => "remove", + "PatchFeature" => "patch", + "SurfaceExtrudeFeature" => "surface_extrude", + "SurfaceRevolveFeature" => "surface_revolve", + "SurfaceSweepFeature" => "surface_sweep", + "SurfaceLoftFeature" => "surface_loft", + "BlendFeature" => "surface_blend", + "BoundaryFeature" => "surface_boundary", + "MatchFeature" => "surface_match", + "FairFeature" => "surface_fair", + "StitchFeature" => "stitch", + "ThickenFeature" => "thicken", + "TrimFeature" => "surface_trim", + "ExtendFeature" => "surface_extend", + "RuledSurfaceFeature" => "surface_ruled", + "UnstitchFeature" => "unstitch", + "ReverseNormalFeature" => "reverse_normal", + "UntrimFeature" => "surface_untrim", + "BaseFeature" => "import", + "MeshFeature" => "mesh_import", + "MeshConvertFeature" => "mesh_convert", + "RepairFeature" => "repair", + _ => return None, + }) + } /// Default name prefix (`Extrude` → `Extrude1`). pub fn base_name(&self) -> &'static str { match self { @@ -2483,6 +2914,7 @@ impl FeatureKind { FeatureKind::Import { .. } => "Import", FeatureKind::MeshImport { .. } => "Mesh", FeatureKind::MeshConvert { .. } => "ConvertMesh", + FeatureKind::Repair { .. } => "Repair", } } } @@ -2541,6 +2973,11 @@ pub struct Feature { /// its faces are named after them and references follow them through Update Links (#3330). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub link_faces: Vec>, + /// What a join of this feature makes of pieces that share no face: those that touch along an + /// edge or at a point become separate bodies and those that touch nothing stay one body (the + /// default), or every piece stays one body. + #[serde(default, skip_serializing_if = "Touching::is_separate")] + pub touching: Touching, #[serde(flatten)] pub kind: FeatureKind, } @@ -2623,6 +3060,19 @@ pub struct DesignLink { /// local overrides and survive a source update. Older links start with no baseline. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub inherited: Vec, + /// SHA-256 of the design file's bytes as this design last read them ([`Self::file_digest`]): + /// opened again, this design tells which linked files changed meanwhile (#9739). Links made + /// before it was kept have none and are taken as up to date. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file_sha256: Option, +} + +impl DesignLink { + /// What [`Self::file_sha256`] keeps for a design file's `bytes`. + pub fn file_digest(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + format!("{:x}", Sha256::digest(bytes)) + } } /// The values last inherited by a linked body, not another editable material library. @@ -2731,6 +3181,9 @@ pub struct Document { /// Physical material per body (by body name); others use the default. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub materials: std::collections::BTreeMap, + /// The flat face per body (by body name) that a slicer export lays on the print bed. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub print_faces: std::collections::BTreeMap, /// Physical materials defined in this design (`material.create`), next to the built-in ones. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub user_materials: Vec, @@ -2751,9 +3204,11 @@ pub struct Document { /// order; feature ids remain the source of truth when features are renamed or reordered. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub timeline_groups: Vec, - /// Browser item order per component folder (`"/"` → item keys). + /// Browser order per component folder (`"/"` → groups and item keys). + /// The `components` folder orders a component's sub-components (by placement id); it is not + /// drawn as a folder. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] - pub browser_order: std::collections::BTreeMap>, + pub browser_order: std::collections::BTreeMap>, /// Named views: saved cameras. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub named_views: Vec, @@ -2831,7 +3286,7 @@ impl Visibility { pub struct NamedView { #[serde(default)] pub name: String, - pub target: solidcraft_geom::Vec3, + pub target: solidcore_record::Vec3, pub yaw: f64, pub pitch: f64, pub distance: f64, @@ -2848,8 +3303,69 @@ pub struct BrowserGroup { #[serde(default)] pub component: u64, pub folder: String, + /// The group that holds this one; `None` is the top level of its folder. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, + /// The group's items and child groups in display order. A child group missing here still + /// belongs to it (its `parent` says so) and is listed after the ones that are here. #[serde(default)] - pub items: Vec, + pub items: Vec, +} + +/// One line of a browser order list: a group (a number in a saved design) or an item (a string: +/// an item key or body name, so a body named `"1"` never clashes with group 1). +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(untagged)] +pub enum BrowserEntry { + Group(u64), + Item(String), +} + +impl From<&str> for BrowserEntry { + fn from(key: &str) -> Self { + BrowserEntry::Item(key.to_string()) + } +} + +impl From for BrowserEntry { + fn from(key: String) -> Self { + BrowserEntry::Item(key) + } +} + +impl BrowserEntry { + pub fn item(key: &str) -> Self { + BrowserEntry::Item(key.to_string()) + } + + pub fn as_item(&self) -> Option<&str> { + match self { + BrowserEntry::Item(k) => Some(k), + BrowserEntry::Group(_) => None, + } + } + + pub fn is_item(&self, key: &str) -> bool { + self.as_item() == Some(key) + } +} + +/// How many groups may sit inside one another (a top-level group is level 1). +pub const MAX_GROUP_NESTING: usize = 8; + +/// The folders a browser group or order list can be for. `components` only orders sub-components. +pub const BROWSER_FOLDERS: [&str; 4] = ["bodies", "sketches", "construction", "components"]; + +impl BrowserGroup { + /// The keys of the items directly in this group, in order. + pub fn item_keys(&self) -> impl Iterator { + self.items.iter().filter_map(BrowserEntry::as_item) + } + + /// Whether this group holds the item directly. + pub fn has_item(&self, key: &str) -> bool { + self.items.iter().any(|e| e.is_item(key)) + } } /// A saved history folder. Folders may nest; each feature or joint belongs to at most one folder. @@ -2983,6 +3499,7 @@ impl Document { body_components: Default::default(), body_offsets: Default::default(), materials: Default::default(), + print_faces: Default::default(), user_materials: Vec::new(), appearances: Default::default(), favorites: Default::default(), @@ -2999,7 +3516,7 @@ impl Document { } /// Rename body `old` to `new` where the design keeps things by body name outside its - /// features: materials, appearances, plastic rules, configuration columns, offsets, components and the + /// features: materials, print faces, appearances, plastic rules, configuration columns, offsets, components and the /// browser's groups and order. (The features are the rename command's to change.) /// /// A name the design numbered (`Body1`) is not used again after the rename: the design's @@ -3015,6 +3532,10 @@ impl Document { if let Some(m) = self.materials.remove(old) { self.materials.insert(new.to_string(), m); } + if let Some(mut face) = self.print_faces.remove(old) { + face.body = new.to_string(); + self.print_faces.insert(new.to_string(), face); + } if let Some(rule) = self.plastic.assigned.remove(old) { self.plastic.assigned.insert(new.to_string(), rule); } @@ -3041,22 +3562,23 @@ impl Document { if let Some(c) = self.body_components.remove(old) { self.body_components.insert(new.to_string(), c); } - for g in self.browser_groups.iter_mut().filter(|g| g.folder == "bodies") { - for k in g.items.iter_mut().filter(|k| *k == old) { - *k = new.to_string(); + let rename = |e: &mut BrowserEntry| { + if e.is_item(old) { + *e = BrowserEntry::item(new); } + }; + for g in self.browser_groups.iter_mut().filter(|g| g.folder == "bodies") { + g.items.iter_mut().for_each(rename); } for (_, v) in self.browser_order.iter_mut().filter(|(k, _)| k.ends_with("/bodies")) { - for k in v.iter_mut().filter(|k| *k == old) { - *k = new.to_string(); - } + v.iter_mut().for_each(rename); } } /// The single body rename (old name, new name) that turns `previous` into this design, /// when that is all that changed: the features' stored body names (`made` gives the names - /// each feature's bodies have now, by feature id) and what [`Document::rename_body_keys`] - /// renames. `None` for any other change. + /// each feature's bodies have now, by feature id), typed body references, participants and + /// what [`Document::rename_body_keys`] renames. `None` for any other change. pub fn body_rename_from(&self, previous: &Document, made: impl Fn(u64) -> Vec) -> Option<(String, String)> { if self.features.len() != previous.features.len() { return None; @@ -3087,8 +3609,16 @@ impl Document { } let (old, new) = rename?; let mut expected = previous.clone(); + let bodies = std::collections::BTreeMap::from([(old.clone(), new.clone())]); for (f, g) in expected.features.iter_mut().zip(&self.features) { f.body_names.clone_from(&g.body_names); + // Updating references to the renamed body changes no feature input other than its + // name (#6287). Keep the full comparison below: geometry, expressions, sketch links + // and face anchors must still agree before the model may reuse its geometry. + f.kind.remap_bodies(&bodies); + for body in f.participants.iter_mut().filter(|body| **body == old) { + body.clone_from(&new); + } } expected.rename_body_keys(&old, &new); (expected == *self).then_some((old, new)) @@ -3420,10 +3950,14 @@ impl Document { /// Read a design file's JSON (any format this build knows; older ones are upgraded). pub fn from_json(s: &str) -> Result { crate::render_resources::check_json_budget(s)?; - let d = crate::format::read(s)?; + let mut d = crate::format::read(s)?; if d.features.len() > MAX_FEATURES || d.params.len() > MAX_PARAMS { return Err(DocError::Invalid("document too large".into())); } + // A design from elsewhere may nest groups too deep, loop, or name things that are gone. + if let Some((groups, order)) = d.browser_pruned() { + (d.browser_groups, d.browser_order) = (groups, order); + } Ok(d) } pub fn to_json(&self) -> String { @@ -3431,6 +3965,8 @@ impl Document { } pub fn feature(&self, id: u64) -> Option<&Feature> { + #[cfg(test)] + crate::eval::cost_tests::count_feature_search(); self.features.iter().find(|f| f.id == id) } pub fn feature_mut(&mut self, id: u64) -> Option<&mut Feature> { @@ -3449,15 +3985,35 @@ impl Document { self.features.iter().find(|f| f.name.eq_ignore_ascii_case(r)) } + /// Resolve a textual timeline reference. An exact name wins even when it looks like an id. + /// Older scripts also pass ids as strings or use a different case for a unique name. + pub fn resolve_feature_name(&self, name: &str) -> Result<&Feature> { + if let Some(feature) = self.features.iter().find(|f| f.name == name) { + return Ok(feature); + } + if let Ok(id) = name.parse::() + && let Some(feature) = self.feature(id) + { + return Ok(feature); + } + let mut matches = self.features.iter().filter(|f| f.name.eq_ignore_ascii_case(name)); + let feature = matches.next().ok_or_else(|| DocError::Invalid(format!("no feature `{name}`")))?; + if matches.next().is_some() { + return Err(DocError::Invalid(format!("ambiguous feature `{name}`. Use its exact name or numeric id"))); + } + Ok(feature) + } + /// The feature a pattern or mirror seed names, resolved the way `replay()` resolved seed /// names before seeds were keyed by id (#1134): an exact name match on a feature that is /// not a sketch or a construction plane wins — a sketch and its extrude often share a - /// name, and the feature that makes geometry is the one to copy — else [`find_feature`]. + /// name, and the feature that makes geometry is the one to copy. Other references use + /// the timeline lookup. pub fn seed_feature(&self, name: &str) -> Option<&Feature> { self.features .iter() .find(|x| x.name == name && !matches!(x.kind, FeatureKind::Sketch { .. } | FeatureKind::ConstructionPlane { .. })) - .or_else(|| self.find_feature(name)) + .or_else(|| self.resolve_feature_name(name).ok()) } fn unique_name(&self, base: &str) -> String { @@ -3513,12 +4069,18 @@ impl Document { } else { 0 }; - let id = self.next_id.max(1); - self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let name = match name { Some(n) if !n.trim().is_empty() => n.trim().to_string(), _ => self.unique_name(kind.base_name()), }; + // Plane references share the feature namespace. A duplicate would silently select + // the first feature. Other shared names (a sketch and its extrude) remain supported. + let is_plane = matches!(kind, FeatureKind::ConstructionPlane { .. }); + if self.features.iter().any(|f| f.name == name && (is_plane || matches!(f.kind, FeatureKind::ConstructionPlane { .. }))) { + return Err(DocError::Invalid(format!("another feature is called `{name}`"))); + } + let id = self.next_id.max(1); + self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let f = Feature { id, name, @@ -3534,6 +4096,7 @@ impl Document { kernel_piece_order: false, inserted: false, link_faces: Vec::new(), + touching: Touching::Separate, kind, }; self.place_feature(f); @@ -3916,6 +4479,7 @@ impl Document { } PlaneRef::Midplane { .. } | PlaneRef::TwoEdges { .. } + | PlaneRef::AxisPoint { .. } | PlaneRef::ThreePoints { .. } | PlaneRef::Tangent { .. } | PlaneRef::AlongPath { .. } @@ -4068,7 +4632,7 @@ impl Document { return Err(DocError::Invalid("a text's height must be positive".into())); } if let Some(e) = &exprs.text { - let words = self.eval_words(e).map_err(|error| DocError::Expr(format!("text: {error}")))?; + let words = self.eval_words(e, vals).map_err(|error| DocError::Expr(format!("text: {error}")))?; if words.trim().is_empty() || words.chars().count() > solidcraft_sketch::MAX_TEXT_CHARS { return Err(DocError::Invalid(format!("text: `{e}` gives no words, or too many"))); } @@ -4113,6 +4677,11 @@ impl Document { analysis: solidcraft_sketch::Analysis, ) -> Result { self.apply_dimension_values(vals, sk)?; + // A text built anew since it was stored (an expression gave it other words) has other + // outline entities: the stored sketch is taken with this sketch's, so the points still + // pair up for the side checks and the walk below. + let paired = moved_from.and_then(|from| sk.stored_with_rebuilt_texts(from)); + let moved_from = paired.as_ref().or(moved_from); let was = |sk: &Sketch| moved_from.and_then(|from| sk.positions_in(from)); let offsets = !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty(); // Offsets always require another solve after refresh. Only that last report is @@ -4151,6 +4720,14 @@ impl Document { } else { solidcraft_sketch::solve_after_edit_with_analysis(sk, stored, was(sk).as_deref(), analysis) }; + // An attachment to the old offset can prevent the source from moving at all. + // Retry from a source-only seed, adopting it only if every constraint still holds. + if !report.ok() + && report.oversized.is_none() + && let Some(retried) = sk.solve_after_offset_edit(stored, was(sk).as_deref(), analysis) + { + report = retried; + } } Ok(report) } diff --git a/crates/doc/src/drawing.rs b/crates/doc/src/drawing.rs index 5a8b89e09..0ac8b72a1 100644 --- a/crates/doc/src/drawing.rs +++ b/crates/doc/src/drawing.rs @@ -52,11 +52,12 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::Value; +use solidcore_record::Vec2; +use solidcraft_geom::Aabb2; use solidcraft_geom::cell::Projection; use solidcraft_geom::drawing_sheet::{self, DrawingBorderProfile}; use solidcraft_geom::revision::RevisionRecord; use solidcraft_geom::title_block::TitleBlock; -use solidcraft_geom::{Aabb2, Vec2}; use crate::format::DRAWING; use crate::ids::{self, IdSource}; diff --git a/crates/doc/src/drawing/balloon.rs b/crates/doc/src/drawing/balloon.rs index 478dff802..6deeb0046 100644 --- a/crates/doc/src/drawing/balloon.rs +++ b/crates/doc/src/drawing/balloon.rs @@ -19,7 +19,7 @@ //! ([`super::dimension::Status`]): by name, strictly, and what it can't decide it says. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_geom::drawing_view::is_paper_coordinate; use solidcraft_geom::paper::MAX_SIDE_MM; diff --git a/crates/doc/src/drawing/dimension.rs b/crates/doc/src/drawing/dimension.rs index bf22b2544..6aa5f1df1 100644 --- a/crates/doc/src/drawing/dimension.rs +++ b/crates/doc/src/drawing/dimension.rs @@ -56,10 +56,11 @@ use std::f64::consts::PI; use std::sync::Arc; use serde::{Deserialize, Serialize}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; use solidcraft_geom::drawing_measure::{self, AngleFrom, Cylinder, LinearDirection, Measured, Reading, SilhouetteSide}; use solidcraft_geom::drawing_view::{Invalid, is_paper_coordinate}; use solidcraft_geom::paper::MAX_SIDE_MM; -use solidcraft_geom::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use super::{Drawing, Units, add_by_id, in_id_order, require}; use crate::config::MAX_REFERENCE_NAME_BYTES; @@ -826,9 +827,17 @@ impl<'a> Lookup<'a> { let through = Plane { origin: *line.first().ok_or_else(face_on)?, ..*basis }; let local = mat_inverse(&found.frame).and_then(|back| map_plane(&back, &through)).ok_or_else(face_on)?; let body = self.state.bodies.get(found.body).ok_or_else(|| Status::Lost("its body no longer exists".into()))?; - let segs = body.body.planar_edges(&local, &[*index]).pop().flatten().ok_or_else(face_on)?; + let pieces = body.body.planar_edges(&local, &[*index]).pop().flatten().ok_or_else(face_on)?; let not_round = || Status::Unmeasurable(format!("edge `{}` isn't a circle or an arc", edge.name)); - let (radius, points) = one_arc(&segs).ok_or_else(not_round)?; + // A spline piece is no arc: only the pieces the kernel gives as segments can be one. + let segs: Option> = pieces + .into_iter() + .map(|piece| match piece { + crate::kernel::PlanarPiece::Seg(seg) => Some(seg), + crate::kernel::PlanarPiece::Spline(_) => None, + }) + .collect(); + let (radius, points) = segs.as_deref().and_then(one_arc).ok_or_else(not_round)?; Ok((radius, points.map(|p| apply_point(&found.frame, local.to_world(p))))) } diff --git a/crates/doc/src/drawing/dimension_tests.rs b/crates/doc/src/drawing/dimension_tests.rs index 2f4804f63..cf594494a 100644 --- a/crates/doc/src/drawing/dimension_tests.rs +++ b/crates/doc/src/drawing/dimension_tests.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_geom::drawing_sheet::{self, Orientation, PaperSize}; use solidcraft_geom::drawing_view::NamedView; diff --git a/crates/doc/src/drawing/view.rs b/crates/doc/src/drawing/view.rs index 521e40d59..86798ca57 100644 --- a/crates/doc/src/drawing/view.rs +++ b/crates/doc/src/drawing/view.rs @@ -18,9 +18,9 @@ use std::collections::BTreeSet; use std::sync::Arc; use serde::{Deserialize, Serialize}; +use solidcore_record::{Plane, Vec2}; use solidcraft_geom::drawing_view::{ProjectedSide, Scale, is_paper_coordinate, projected_basis}; use solidcraft_geom::paper::MAX_SIDE_MM; -use solidcraft_geom::{Plane, Vec2}; use solidcraft_render::VisualStyle; use super::{Drawing, add_by_id, in_id_order, require}; diff --git a/crates/doc/src/drawing/view_tests.rs b/crates/doc/src/drawing/view_tests.rs index f913df9dc..1b477478c 100644 --- a/crates/doc/src/drawing/view_tests.rs +++ b/crates/doc/src/drawing/view_tests.rs @@ -1,8 +1,9 @@ +use solidcraft_geom::prelude::*; use std::collections::BTreeSet; use std::sync::Arc; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_geom::cell::Projection; use solidcraft_geom::drawing_sheet::{self, Orientation, PaperSize}; use solidcraft_geom::drawing_view::NamedView; diff --git a/crates/doc/src/drawing_view.rs b/crates/doc/src/drawing_view.rs index b45e7ca29..044efe531 100644 --- a/crates/doc/src/drawing_view.rs +++ b/crates/doc/src/drawing_view.rs @@ -3,7 +3,7 @@ //! optional so that a projected view can follow its parent. use serde::{Deserialize, Deserializer, Serialize}; -use solidcraft_geom::Plane; +use solidcore_record::Plane; use solidcraft_geom::drawing_view::{Invalid, NamedView, Scale, basis_looking}; use solidcraft_render::VisualStyle; diff --git a/crates/doc/src/drawing_view_tests.rs b/crates/doc/src/drawing_view_tests.rs index e1b632150..be42aeb21 100644 --- a/crates/doc/src/drawing_view_tests.rs +++ b/crates/doc/src/drawing_view_tests.rs @@ -1,5 +1,5 @@ use serde_json::json; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use super::*; diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index fd50a1233..441a2d3ce 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -5,13 +5,16 @@ mod placed_mesh; #[path = "placement_reuse.rs"] mod placement_reuse; +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; use std::sync::{Arc, OnceLock}; use serde::{Deserialize, Serialize}; +use solidcore_record::brep::part::Contact; +use solidcore_record::{Plane, Region2, Vec2, Vec3}; use solidcraft_geom::tess::TessPlan; -use solidcraft_geom::{Mesh, Plane, Region2, UnitVec3, Vec2, Vec3, regions_apart}; +use solidcraft_geom::{Mesh, UnitVec3, regions_apart}; use solidcraft_kernel::{self as kernel, Body, BoolOp}; use solidcraft_sketch::{CurveKind, Profile, SolveReport, find_profiles}; @@ -21,6 +24,10 @@ use crate::{AxisRef, DocError, Document, Feature, FeatureId, FeatureKind, HoleKi type JointFaces = (Body, kernel::Result>); +/// A body's isoparametric curves worked out so far ([`ModelBody::iso_lines`]), with the body they +/// were worked out on: by face, count each way and display quality. +type IsoLines = (Option, std::collections::HashMap<(usize, usize, usize), Arc<[kernel::IsoLine]>>); + /// A body in the evaluated model. #[derive(Clone, Debug)] pub struct ModelBody { @@ -40,6 +47,11 @@ pub struct ModelBody { joint_faces: Arc>, /// Lazy canonical reference triangles for a proper rigid occurrence placement. mesh_placement: Option>, + /// For a mirrored copy: its faces as a world state shows them, a rigid move of the source's + /// [`placed_mesh::OppositeHand`]. Display only: the model reads the copy's own triangles. + mirrored_mesh: Option>, + /// The first mirrored copy made of this body, shared by its clones. + opposite_hand: Arc>, /// The display plan (none when the body has no plan: a mesh body, or one the planner /// refuses), shared like the mesh. A GPU viewport draws it. plan: Arc<[OnceLock>>; 4]>, @@ -72,9 +84,12 @@ pub struct ModelBody { /// [`kernel::measure`] of `body` (with the body it was measured on), worked out once and /// shared by clones: inspecting a design again measures only the bodies that changed. measured: Arc)>>, - /// [`Body::is_surface`] of `body` (with the body it was measured on), worked out once and - /// shared by clones. + /// Whether `body` is open (with the body it was measured on): a B-rep one a surface body + /// ([`Body::is_surface`]), a mesh one with a side only one triangle has + /// ([`Body::is_closed_mesh`]); worked out once and shared by clones. surface: Arc>, + /// [`ModelBody::iso_lines`] worked out so far, shared by clones. + iso: Arc>, } impl ModelBody { @@ -88,6 +103,8 @@ impl ModelBody { mesh: Arc::new(OnceLock::new()), joint_faces: Arc::new(OnceLock::new()), mesh_placement: None, + mirrored_mesh: None, + opposite_hand: Arc::new(OnceLock::new()), plan: Arc::new(Default::default()), plan_mesh: Arc::new(Default::default()), key: 0, @@ -102,6 +119,7 @@ impl ModelBody { volume: Arc::new(OnceLock::new()), measured: Arc::new(OnceLock::new()), surface: Arc::new(OnceLock::new()), + iso: Default::default(), } } @@ -119,10 +137,22 @@ impl ModelBody { /// A surface body: some shell does not close ([`Body::is_surface`]), worked out once. pub fn is_surface(&self) -> bool { - match self.surface.get_or_init(|| (self.body.clone(), self.body.is_surface())) { + !self.body.is_mesh() && self.is_open() + } + + /// The body encloses a volume: a solid whose shells all close ([`ModelBody::is_surface`]), + /// or a mesh body every side of which two triangles share ([`Body::is_closed_mesh`]). + /// Worked out once. + pub fn is_closed(&self) -> bool { + !self.is_open() + } + + fn is_open(&self) -> bool { + let open = |b: &Body| if b.is_mesh() { !b.is_closed_mesh() } else { b.is_surface() }; + match self.surface.get_or_init(|| (self.body.clone(), open(&self.body))) { (measured, s) if measured.same(&self.body) => *s, // The body was replaced in this cell's holder since: look again. - _ => self.body.is_surface(), + _ => open(&self.body), } } @@ -227,7 +257,7 @@ impl ModelBody { .get(q.index())? .get_or_init(|| match self.mesh_placement.as_deref() { Some(placed) => placed.plan_mesh(q, &self.name), - None => self.display_plan_at(q).and_then(|plan| self.body.display_mesh_of(&plan).ok()).map(Arc::new), + None => self.display_plan_at(q).and_then(|plan| self.body.mesh_of(&plan).ok()).map(Arc::new), }) .clone() } @@ -313,7 +343,7 @@ impl ModelBody { return None; } let body = self.clone(); - let started = std::thread::Builder::new().name("plan-mesh".into()).spawn(move || { + let started = kernel::kernel_thread("plan-mesh").spawn(move || { let _ = body.plan_mesh_at(q); if let Ok(mut warming) = WARMING.lock() { warming.retain(|k| *k != key); @@ -335,14 +365,17 @@ impl ModelBody { if k == 0 { return Some((self.display_plan_at(q)?, self.plan_mesh_at(q)?)); } - let plan = match self.body.display_plan_angular(q.refined_chord(self.body.size(), k), q.refined_angle(k)) { + let plan = match self + .body + .mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.refined_chord(self.body.size(), k), angle: Some(q.refined_angle(k)) }) + { Ok(plan) => plan, Err(e) => { log::debug!("{}: no display plan refined {k} steps ({e})", self.name); return None; } }; - let mesh = self.body.display_mesh_of(&plan).ok()?; + let mesh = self.body.mesh_of(&plan).ok()?; Some((Arc::new(plan), Arc::new(mesh))) } @@ -356,6 +389,32 @@ impl ModelBody { pub fn cached_mesh(&self) -> Option> { self.mesh.get().cloned() } + + /// The isoparametric curves of face `face` for Isocurve Analysis: `count` each way, evenly + /// spaced across the face (faces on one surface spaced together, so they share them), exact + /// and cut to its trims ([`kernel::iso_grid`]), their points at the chord + /// tolerance of the viewport's display quality. Worked out once per face, count and display + /// quality, and shared by every clone of this body (timeline snapshots, world states). A mesh + /// body has no surfaces, so none. + pub fn iso_lines(&self, face: usize, count: usize) -> Result> { + if self.body.is_mesh() { + return Err(DocError::Invalid(format!("{} is a mesh body: its faces have no surface parameters, so no isoparametric curves", self.name))); + } + let quality = crate::display_quality::current(); + let key = (face, count, quality.index()); + let make = || kernel::iso_grid(&self.body, face, count, quality.chord(self.body.size())).map(Arc::from); + let Ok(mut cache) = self.iso.lock() else { return Ok(make()?) }; + if !cache.0.as_ref().is_some_and(|b| b.same(&self.body)) { + // A body replaced in this cell's holder since: what was worked out was on another. + *cache = (Some(self.body.clone()), Default::default()); + } + if let Some(lines) = cache.1.get(&key) { + return Ok(lines.clone()); + } + let lines = make()?; + cache.1.insert(key, lines.clone()); + Ok(lines) + } } /// A solved sketch in the evaluated model. @@ -371,412 +430,66 @@ pub struct SolvedSketch { pub ends: solidcraft_sketch::EndReport, } -/// A cosmetic thread: on which cylinder, its size, and the threaded part of the axis. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ThreadInfo { - pub feature: u64, - pub body: String, - pub designation: String, - pub major_diameter: f64, - /// Radius of the actual cylindrical face when the cosmetic thread is evaluated. - pub radius: f64, - pub pitch: f64, - pub internal: bool, - #[serde(default)] - pub handedness: crate::ThreadHandedness, - pub axis_point: Vec3, - pub axis: UnitVec3, - /// Threaded part along the axis from `axis_point`. - pub start: f64, - pub end: f64, -} - -/// ISO metric coarse threads: (nominal diameter, pitch). -const ISO_COARSE: [(f64, f64); 22] = [ - (1.6, 0.35), - (2.0, 0.4), - (2.5, 0.45), - (3.0, 0.5), - (4.0, 0.7), - (5.0, 0.8), - (6.0, 1.0), - (8.0, 1.25), - (10.0, 1.5), - (12.0, 1.75), - (14.0, 2.0), - (16.0, 2.0), - (18.0, 2.5), - (20.0, 2.5), - (22.0, 2.5), - (24.0, 3.0), - (27.0, 3.0), - (30.0, 3.5), - (36.0, 4.0), - (42.0, 4.5), - (48.0, 5.0), - (56.0, 5.5), -]; - -/// Nominal diameters and coarse pitches (mm) used for automatic ISO metric thread sizing. -/// Other diameter/pitch pairs can be supplied as explicit designations. -pub fn metric_thread_sizes() -> &'static [(f64, f64)] { - &ISO_COARSE -} - -/// "M8" or "M8x1" → (nominal diameter, pitch). -pub fn parse_metric_thread(s: &str) -> Option<(f64, f64)> { - let t = s.trim().to_ascii_uppercase(); - let body = t.strip_prefix('M')?; - let (d, p) = match body.split_once(['X', '×']) { - Some((d, p)) => (d.trim().parse::().ok()?, Some(p.trim().parse::().ok()?)), - None => (body.trim().parse::().ok()?, None), - }; - let pitch = match p { - Some(p) => p, - None => ISO_COARSE.iter().find(|(n, _)| (n - d).abs() < 1e-9)?.1, - }; - (d.is_finite() && pitch.is_finite() && d > 0.0 && pitch > 0.0 && pitch < d).then_some((d, pitch)) -} - -/// The metric thread a cylinder of this diameter takes: a shaft is the major diameter, a hole -/// the tap drill (major − pitch). -fn thread_for(diameter: f64, internal: bool) -> Option<(f64, f64)> { - ISO_COARSE - .iter() - .map(|&(n, p)| (n, p, if internal { n - p } else { n })) - .min_by(|a, b| (a.2 - diameter).abs().total_cmp(&(b.2 - diameter).abs())) - .filter(|(_, _, want)| (want - diameter).abs() <= 0.15 * diameter) - .map(|(n, p, _)| (n, p)) -} - -pub(crate) fn format_thread(d: f64, p: f64) -> String { - let coarse = ISO_COARSE.iter().any(|(n, q)| (n - d).abs() < 1e-9 && (q - p).abs() < 1e-9); - let num = |x: f64| if (x - x.round()).abs() < 1e-9 { format!("{}", x.round()) } else { format!("{x}") }; - if coarse { format!("M{}", num(d)) } else { format!("M{}x{}", num(d), num(p)) } -} - -/// The automatic ISO metric designation for a cylindrical face, using the same fit check as -/// a thread feature without an explicit size. This query does not change the model. -pub fn suggested_thread(st: &ModelState, p: Vec3) -> Result { - thread_on(st, 0, p, None, None, false, crate::ThreadHandedness::Right).map(|t| t.designation) -} - -/// A cosmetic thread on the cylindrical face at `p`. A `turned` (modelled) thread also fits a -/// shaft thicker than it, which it turns down to its major diameter first. -fn thread_on( - st: &ModelState, - feature: u64, - p: Vec3, - designation: Option<&str>, - length: Option, - turned: bool, - handedness: crate::ThreadHandedness, -) -> Result { - thread_on_impl(st, feature, p, designation, length, false, turned, handedness) -} - -// Tapped holes admit verified Unified and parallel pipe sizes; the separate Thread feature remains metric, -// including when an untrusted design requests modelled geometry. -fn thread_on_impl( - st: &ModelState, - feature: u64, - p: Vec3, - designation: Option<&str>, - length: Option, - tapped: bool, - turned: bool, - handedness: crate::ThreadHandedness, -) -> Result { - let (body, cyl) = st - .bodies - .iter() - .filter_map(|b| kernel::cylinder_face_at(&b.body, p).map(|c| (b.name.clone(), c))) - .min_by(|a, b| { - let dist = |c: &kernel::CylinderFace| ((p - c.axis_point - c.axis * (p - c.axis_point).dot(c.axis)).len() - c.radius).abs(); - dist(&a.1).total_cmp(&dist(&b.1)) - }) - .ok_or_else(|| DocError::Invalid("no cylindrical face there to thread".into()))?; - let dia = cyl.radius * 2.0; - let tapped_size = if tapped { - let name = designation.ok_or_else(|| DocError::Invalid("a tapped hole needs a designation".into()))?; - Some( - crate::parse_tapped_thread(name) - .ok_or_else(|| DocError::Invalid(format!("unknown tapped thread `{name}` (ISO metric or a catalogued UNC/UNF, G or Rp size)")))?, - ) - } else { - None - }; - let (major, pitch) = match &tapped_size { - Some(size) => (size.major_diameter, size.pitch), - None => match designation { - Some(s) => parse_metric_thread(s).ok_or_else(|| DocError::Invalid(format!("unknown thread `{s}` (ISO metric, like M8 or M8x1)")))?, - None => thread_for(dia, cyl.internal).ok_or_else(|| DocError::Invalid(format!("no metric thread fits a {dia:.2} mm cylinder")))?, - }, - }; - let name = tapped_size.as_ref().map(|s| s.designation.clone()).unwrap_or_else(|| format_thread(major, pitch)); - let fits = if let Some(size) = tapped_size.as_ref().filter(|s| s.family != crate::TappedThreadFamily::Metric) { - // Fit the recommended physical drill, without borrowing an ISO minor-diameter rule. - cyl.internal && (size.tap_drill - dia).abs() < 0.15 * major - } else if cyl.internal { - (major - pitch * 1.0825 - dia).abs() < 0.2 * major || (major - pitch - dia).abs() < 0.15 * major - } else { - (major - dia).abs() < 0.15 * major || (turned && dia > major) - }; - if !fits { - return Err(DocError::Invalid(format!("an {} thread does not fit a {dia:.2} mm {}", name, if cyl.internal { "hole" } else { "shaft" }))); - } - // From the end of the face nearest the point. - let s = (p - cyl.axis_point).dot(cyl.axis); - let (mut a, mut b) = (cyl.start, cyl.end); - if let Some(l) = length { - if !(l > 0.0) { - return Err(DocError::Invalid("thread length must be positive".into())); - } - if (s - a).abs() <= (b - s).abs() { - b = (a + l).min(b); - } else { - a = (b - l).max(a); - } - } - Ok(ThreadInfo { - feature, - body, - designation: name, - major_diameter: major, - radius: cyl.radius, - pitch, - internal: cyl.internal, - handedness, - axis_point: cyl.axis_point, - axis: cyl.axis, - start: a, - end: b, - }) -} - -/// The helical space between the teeth of a modelled ISO metric thread (ISO 68-1 basic -/// profile, 60° flanks): cut from the shaft (external) or the hole wall (internal), running from -/// `start` to `end` along the axis. `radius` is the face's own radius; `open` says which ends -/// of the threaded length are free ends of the face. -fn thread_groove(t: &ThreadInfo, radius: f64, open: (bool, bool)) -> Result { - let (p, d) = (t.pitch, t.major_diameter); - let h = p * 3f64.sqrt() / 2.0; - let slope = (std::f64::consts::PI / 6.0).tan(); - let len = t.end - t.start; - if !(p > 1e-3 && len > 1e-6) { - return Err(DocError::Invalid("thread too short".into())); - } - if len / p > 190.0 { - return Err(DocError::Invalid(format!("a modelled thread is limited to 190 turns ({:.0} mm at this pitch); use a cosmetic one", 190.0 * p))); - } - // How deep the groove cuts into the material: from the hole wall out to the major diameter, - // or from the shaft's surface in to the root. Next to nothing (a hole as wide as the thread, - // #995) is refused: the faceted cut would leave the face faceted and unthreaded. - let basic = 5.0 * h / 8.0; - let depth = if t.internal { d / 2.0 - radius } else { radius - (d / 2.0 - basic) }; - if !(depth >= basic / 4.0) { - let (m, dia) = (&t.designation, 2.0 * radius); - let cut = format!("it would cut {:.2} mm of the thread's {basic:.2} mm depth", depth.max(0.0)); - let alt = thread_for(dia, t.internal).map(|(n, q)| format_thread(n, q)).filter(|a| a != m); - let shown = show_mm(dia); - return Err(DocError::Invalid(if t.internal { - let alt = alt.map(|a| format!(", or thread this hole {a}")).unwrap_or_default(); - format!("this {shown} mm hole is too wide for a modelled {m} thread: {cut}; drill {} mm for {m}{alt}", show_mm(d - p)) - } else { - let alt = alt.map(|a| format!(", or thread this shaft {a}")).unwrap_or_default(); - format!("this {shown} mm shaft is too thin for a modelled {m} thread: {cut}; make the shaft {} mm for {m}{alt}", show_mm(d)) - })); - } - // (radius, half width of the groove) at its two ends: a trapezoid in the axial plane. - let (r0, w0, r1, w1) = if t.internal { - // From inside the hole wall out to the major diameter, where the bolt's crest sits - // (the root flat is P/8 wide). - let r_in = radius.min(d / 2.0 - 5.0 * h / 8.0) - 0.1 * p; - (r_in, (p / 8.0 + 2.0 * (d / 2.0 - r_in) * slope) / 2.0, d / 2.0, p / 16.0) - } else { - // From the root (5H/8 under the major diameter, flat P/4 wide) out past the surface. - let r_root = d / 2.0 - 5.0 * h / 8.0; - let r_out = radius.max(d / 2.0) + 0.05 * p; - (r_root, p / 8.0, r_out, (p / 4.0 + 2.0 * (r_out - r_root) * slope) / 2.0) - }; - if w0.max(w1) * 2.0 >= p * 0.98 { - // The groove would be wider than a pitch: the face is far inside the thread (a hole - // narrower than its minor diameter, a shaft thicker than its major one, #2688). - let (m, dia) = (&t.designation, 2.0 * radius); - let alt = thread_for(dia, t.internal).map(|(n, q)| format_thread(n, q)).filter(|a| a != m); - let shown = show_mm(dia); - return Err(DocError::Invalid(if t.internal { - let alt = alt.map(|a| format!(", or thread this hole {a}")).unwrap_or_default(); - format!( - "this {shown} mm hole is too narrow for a modelled {m} thread (its teeth would fill the hole); drill {} mm for {m}{alt}", - show_mm(d - p) - ) - } else { - let alt = alt.map(|a| format!(", or thread this shaft {a}")).unwrap_or_default(); - format!("this {shown} mm shaft is too thick for a modelled {m} thread; make the shaft {} mm for {m}{alt}", show_mm(d)) - })); - } - let k = t.axis; - let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); - let u = u.normalized().ok_or_else(|| DocError::Invalid("thread axis".into()))?; - // Past a free end of the face the groove runs out into the air; elsewhere it stops square - // at the threaded length's end. - let (s0, s1) = (if open.0 { t.start - p } else { t.start }, if open.1 { t.end + p } else { t.end }); - let base = t.axis_point + k * s0; - let plane = Plane { origin: base, x: u, y: *k }; - let section = [Vec2::new(r0, -w0), Vec2::new(r1, -w1), Vec2::new(r1, w1), Vec2::new(r0, w0)]; - // Keep radial chord error below 1% of the pitch, rather than a fixed fraction of the - // diameter. At 48 stations a large fine thread cuts too deeply; its outer tool facets - // can even dip under the shaft surface. The existing coarse sizes still use 48. - let outer = r0.abs().max(r1.abs()); - if !outer.is_finite() { - return Err(DocError::Invalid("thread dimensions are too large".into())); - } - let angle = (1.0 - (p * 0.01 / outer).min(1.0)).acos(); - let stations = (std::f64::consts::PI / angle).ceil().max(48.0); - if !stations.is_finite() || stations > 720.0 { - return Err(DocError::Invalid("the modelled thread is too fine for this diameter; use a cosmetic thread".into())); - } - // The kernel rotates positively about its sweep axis. Reversing both that axis and the - // pitch mirrors the angular motion while the lift stays +k * p per turn. The physical - // axis, start/end, radial profile and station count remain exactly as for a right thread. - let (sweep_axis, sweep_pitch) = match t.handedness { - crate::ThreadHandedness::Right => (*k, p), - crate::ThreadHandedness::Left => (-*k, -p), - }; - Ok(kernel::sweep_helix_mesh(&plane, §ion, base, sweep_axis, sweep_pitch, (s1 - s0) / p, stations as usize)?) -} - -#[cfg(test)] -mod thread_handedness_tests { - use super::*; - - #[test] - fn thread_handedness_groove_reflects_exactly_about_the_physical_axis() { - for direction in [Vec3::Z, Vec3::X, Vec3::new(1.0, 2.0, 3.0)] { - for internal in [false, true] { - let axis = UnitVec3::new(direction).unwrap(); - let radius = if internal { 2.5 } else { 3.0 }; - let mut info = ThreadInfo { - feature: 1, - body: "Stock".into(), - designation: "M6x1".into(), - major_diameter: 6.0, - radius, - pitch: 1.0, - internal, - handedness: crate::ThreadHandedness::Right, - axis_point: Vec3::new(7.0, -5.0, 2.0), - axis, - start: 1.3, - end: 4.3, - }; - let right = thread_groove(&info, radius, (false, true)).unwrap(); - info.handedness = crate::ThreadHandedness::Left; - let left = thread_groove(&info, radius, (false, true)).unwrap(); - // Reflection in the radial plane of the initial profile, independent of the - // helix parameterization: the projected coordinate along the axis stays fixed. - let seed = if axis.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }; - let normal = (seed - *axis * axis.dot(seed)).normalized().unwrap(); - assert_eq!(right.positions.len(), left.positions.len()); - for (r, l) in right.positions.iter().zip(&left.positions) { - let expected = *r - normal * (2.0 * (*r - info.axis_point).dot(normal)); - assert!((*l - expected).len() < 1e-10, "physical reflection: {direction:?}/{internal}"); - assert!(((*r - *l).dot(*axis)).abs() < 1e-10, "axial extent must not change"); - } - let (r, l) = (right.measure(), left.measure()); - assert!(r.volume > 0.0 && l.volume > 0.0, "outward, watertight sweep"); - assert!((r.volume - l.volume).abs() < r.volume * 1e-12, "exact tool volume: {r:?}/{l:?}"); - } - } - } -} - -/// What a modelled external thread turns off a shaft thicker than its major diameter before it -/// cuts, as a lathe would: the ring between the major diameter and the shaft over the threaded -/// length, run on past an end of the face that nothing of the part (`mb`) lies beyond. `None` -/// for a shaft no thicker than the thread. Its inner wall is the turned face, named `turned`; -/// an end that stops inside the face leaves a shoulder, `shoulder:start` or `shoulder:end`. -fn thread_turn(t: &ThreadInfo, cyl: &kernel::CylinderFace, mb: &ModelBody) -> Result> { - let (p, r) = (t.pitch, t.major_diameter / 2.0); - if t.internal || !(cyl.radius > r * (1.0 + 1e-6)) { - return Ok(None); - } - let k = t.axis; - let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); - let u = u.normalized().ok_or_else(|| DocError::Invalid("thread axis".into()))?; - let v = k.cross(u); - let mesh = mb.mesh(); - let solid_round = |s: f64, radius: f64| { - (0..12).any(|i| { - let a = std::f64::consts::TAU * f64::from(i) / 12.0; - mesh.contains(t.axis_point + *k * s + (u * a.cos() + v * a.sin()) * radius) - }) - }; - // The ring reaches a little past the shaft; the part must not go on there (a shaft standing - // in a corner, a rounded edge), or the turning would cut into it. - let out = cyl.radius + 0.1 * p; - if [0.25, 0.5, 0.75].iter().any(|f| solid_round(t.start + (t.end - t.start) * f, cyl.radius + 0.05 * p)) { - return Err(DocError::Invalid(format!( - "this {} mm shaft is too thick for a modelled {} thread, and the part around it keeps it from being turned down; make the shaft {} mm", - show_mm(2.0 * cyl.radius), - t.designation, - show_mm(t.major_diameter) - ))); - } - // Past a free end of the face out into the air; elsewhere square at the threaded length's end. - let tol = p * 1e-3; - let mid = (r + cyl.radius) / 2.0; - let free = |at: f64, s: f64, past: f64| (at - s).abs() < tol && !solid_round(s + past * 0.5 * p, mid); - let (open0, open1) = (free(cyl.start, t.start, -1.0), free(cyl.end, t.end, 1.0)); - let s0 = if open0 { t.start - p } else { t.start }; - let s1 = if open1 { t.end + p } else { t.end }; - let plane = Plane { origin: t.axis_point, x: u, y: *k }; - let ring = [Vec2::new(r, s0), Vec2::new(out, s0), Vec2::new(out, s1), Vec2::new(r, s1)]; - let region = Region2 { outer: solidcraft_geom::Loop2::polygon(&ring), holes: vec![] }; - let ring = kernel::revolve(&plane, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)? - .into_iter() - .next() - .ok_or_else(|| DocError::Invalid("thread: the shaft turned down to the thread".into()))?; - // The ring's sides by profile segment: its start end, outside, end end, inner wall. - let role = |segment: usize| -> Vec { - match segment { - 0 if !open0 => vec!["shoulder:start".into()], - 2 if !open1 => vec!["shoulder:end".into()], - 3 => vec!["turned".into()], - _ => Vec::new(), - } - }; - let roles = ring.history().filter(|h| h.operands == 0).map(|h| { - h.faces - .iter() - .map(|f| match f.origins.as_slice() { - [kernel::history::FaceOrigin::Profile { segment }] => role(*segment), - _ => Vec::new(), - }) - .collect() - }); - Ok(Some(Traced::made(ring, roles))) -} - /// A constant fillet of `edges`; with [`FilletFit::Reduce`](crate::FilletFit::Reduce), a radius too /// large for the geometry around them is reduced where it doesn't fit, to the largest that works /// for each group of edges sharing a face; the radius per edge is returned. With -/// [`FilletFit::Taper`](crate::FilletFit::Taper) it tapers along each edge it doesn't fit. +/// [`FilletFit::Taper`](crate::FilletFit::Taper) it tapers along each edge it doesn't fit. With +/// the exact fit a radius too large is refused, naming the largest that fits ([`with_largest_fit`]). +/// Also the picks whose edges a round overflowing its faces removed whole ([`kernel::fillet_removing`]). fn fillet_fitted( body: &kernel::Body, edges: &[Vec3], r: f64, fit: crate::FilletFit, -) -> std::result::Result<(kernel::Body, Option>), kernel::KernelError> { - match kernel::fillet(body, edges, r) { - Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Reduce => match kernel::fillet_max_each(body, edges, r) { + turn: kernel::FilletTurn, +) -> std::result::Result<(kernel::Body, Option>, Vec), kernel::KernelError> { + match kernel::fillet_removing(body, edges, r, turn) { + Ok((b, gone)) => Ok((b, None, gone)), + Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Exact => { + Err(with_largest_fit(why, "radius", || kernel::fillet_max(body, edges, r, turn))) + } + Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Reduce => match kernel::fillet_max_each(body, edges, r, turn)? { // Built at the radius asked for after all (the groups apart): nothing reduced. - Some((used, b)) => Ok((b, used.iter().any(|u| *u < r).then_some(used))), + Some((used, b)) => Ok((b, used.iter().any(|u| *u < r).then_some(used), Vec::new())), None => Err(kernel::KernelError::TooLarge(why)), }, - Err(kernel::KernelError::TooLarge(_)) if fit == crate::FilletFit::Taper => kernel::fillet_tapered(body, edges, r).map(|(b, _)| (b, None)), - other => other.map(|b| (b, None)), + Err(kernel::KernelError::TooLarge(_)) if fit == crate::FilletFit::Taper => { + kernel::fillet_tapered(body, edges, r).map(|(b, _)| (b, None, Vec::new())) + } + Err(e) => Err(e), + } +} + +/// The warning of a fillet some of whose edges a larger round, overflowing its faces, removed +/// whole: they are gone, so they are not rounded. +fn removed_note(gone: &[Vec3]) -> String { + let at = |p: &Vec3| format!("({}, {}, {})", show_mm(p.x), show_mm(p.y), show_mm(p.z)); + match gone { + [one] => format!("the edge at {} was removed by the larger round, so it is not rounded", at(one)), + _ => format!("the edges at {} were removed by the larger round, so they are not rounded", gone.iter().map(at).collect::>().join(", ")), + } +} + +/// A blend's refusal as too large (`why`) with the largest `size` (radius, distance) that fits, +/// as `search` finds it by building candidates ([`kernel::fillet_max`]): the refusal as it is +/// when none fits or the search itself fails (a candidate failing for another reason says +/// nothing about the size). +fn with_largest_fit( + why: String, + size: &str, + search: impl FnOnce() -> std::result::Result, kernel::KernelError>, +) -> kernel::KernelError { + // On solidcore the refusal names a size already, less a margin (34.99 where 35 builds), and + // its edge: the edge stays, the size is the largest the search builds, solidcore's where the + // search finds none. + match search() { + Ok(Some((largest, _))) if kernel::names_largest_fit(&why) => kernel::KernelError::TooLarge(kernel::with_fit_note(&why, size, largest)), + Ok(Some((largest, _))) => kernel::KernelError::TooLarge(format!("{why}; {}", kernel::largest_fit_note(size, largest))), + Ok(None) => kernel::KernelError::TooLarge(why), + Err(e) => { + log::debug!("the largest {size} that fits: {e}"); + kernel::KernelError::TooLarge(why) + } } } @@ -855,6 +568,12 @@ impl ModelState { self.fitted.get(&feature)?.iter().fold(None, |acc, r| Some(acc.map_or((*r, *r), |(lo, hi): (f64, f64)| (lo.min(*r), hi.max(*r))))) } + /// How the pieces join `feature` split off into bodies of their own touched the others, when + /// it split any off. + pub fn kept_separate(&self, feature: u64) -> Option { + self.kept_separate.get(&feature).copied() + } + /// Each edge fillet `feature` tapered (a point on it) with the radius spline it was given. pub fn tapered(&self, feature: u64) -> Option<&[(Vec3, kernel::Taper)]> { self.tapered.get(&feature).map(Vec::as_slice) @@ -903,6 +622,46 @@ pub struct ModelState { /// The radius spline of each edge a fillet tapered (a point on the edge with it, by feature /// id, see `FilletFit::Taper`). tapered: BTreeMap>, + /// How the pieces a join split off into bodies of their own touched the others (by feature + /// id), for its notice. + kept_separate: BTreeMap, + /// For a feature saved before format 14 that split a body, a digest of the later features' + /// picks its pieces were named by (by feature id, see [`crate::lineage::order_legacy_lumps`]): + /// the state stands for the feature only while those picks are the same. + legacy_picks: BTreeMap, +} + +/// How a piece a join split off into a body of its own (`Touching::Separate`) touched the +/// pieces it was joined with: the most any such piece shared with another, least first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum KeptSeparate { + /// A point. + AtPoint, + /// A line or a point their boundaries don't hold (a face tangent to another): found on the + /// exact geometry, which doesn't say which. + Touching, + /// A curve: an edge of both. + AlongEdge, +} + +impl KeptSeparate { + /// Its id in a feature's result: `at_point`, `touching` or `along_edge`. + pub fn id(self) -> &'static str { + match self { + KeptSeparate::AtPoint => "at_point", + KeptSeparate::Touching => "touching", + KeptSeparate::AlongEdge => "along_edge", + } + } + + /// What a feature's result says about it. + pub fn notice(self) -> &'static str { + match self { + KeptSeparate::AtPoint => "These bodies only touch at a point, so they were kept as separate bodies.", + KeptSeparate::Touching => "These bodies only touch along a line or at a point, so they were kept as separate bodies.", + KeptSeparate::AlongEdge => "These bodies only touch along an edge, so they were kept as separate bodies.", + } + } } impl ModelState { @@ -980,7 +739,7 @@ impl ModelState { /// After a feature evaluated to this state from `before` with cache key `key`: bodies it /// made or changed take that key, sketches it made a digest of their solved geometry (see /// [`quantize`]); the rest keep theirs. - fn stamp(&mut self, before: &Arc, f: &Feature, key: u64, mats: Vec) { + fn stamp(&mut self, doc: &Document, before: &Arc, f: &Feature, key: u64, mats: Vec) { let feature = f.id; let depth = before.bodies.iter().filter_map(|b| b.names.depth()).max().unwrap_or(0) + 1; let sheets = if f.kind.is_sheet() { self.sheets.clone() } else { Vec::new() }; @@ -989,7 +748,13 @@ impl ModelState { // the feature was saved when they were named in that order). if !f.shell_piece_order { crate::lineage::order_lumps(&mut self.bodies, &origin); + } else { + crate::lineage::order_legacy_lumps(&mut self.bodies, before, doc, f); } + match crate::lineage::legacy_picks_digest(&self.bodies, before, doc, f) { + 0 => self.legacy_picks.remove(&f.id), + d => self.legacy_picks.insert(f.id, d), + }; // The bodies before the feature by name, in their order (names repeat only in damaged // states): every lookup below is the first match of a linear search, without walking // every earlier body for every body, after every feature. @@ -1025,6 +790,7 @@ impl ModelState { && let Some(lines) = olds.first().and_then(|x| x.body.split_lines()) { b.body = b.body.clone().with_split_lines(Some(lines.clone())); + b.mirrored_mesh = None; } // An imported look outlives the operations on the body. if b.body.paint().is_none() @@ -1068,7 +834,8 @@ pub struct EvalCache { struct CachedEval { error: Option, warning: Option, - boolean_diagnostics: kernel::BooleanDiagnostics, + import_report: Option>, + repair: Option>, ms: f64, state: Arc, /// What the state costs, worked out once when it was stored (see @@ -1226,17 +993,27 @@ impl ModelState { /// to the budget keep only its last few states, so setting a parameter back recomputed what /// had dropped out. fn added_bytes(&self, before: &ModelState) -> usize { + // `before`'s bodies by solid, and its sketches by address: looked up per body and sketch, + // not searched (every feature's result is charged, so searching was bodies² per feature). + // Bodies sharing a solid are still told apart by `same_shape` (the mesh as well). + let mut solids: std::collections::HashMap> = std::collections::HashMap::with_capacity(before.bodies.len()); + for o in &before.bodies { + solids.entry(o.body.solid_id()).or_default().push(&o.body); + } let bodies: usize = self .bodies .iter() - .filter(|b| !before.bodies.iter().any(|o| o.body.same_shape(&b.body))) + .filter(|b| !solids.get(&b.body.solid_id()).is_some_and(|os| os.iter().any(|o| o.same_shape(&b.body)))) .map(|b| if b.bytes > 0 { b.bytes } else { b.body.retained_bytes() }) .sum(); - let sketches: usize = self.sketches.iter().filter(|s| !before.sketches.iter().any(|o| Arc::ptr_eq(o, s))).map(|s| s.retained_bytes()).sum(); + let kept: std::collections::HashSet<*const SolvedSketch> = before.sketches.iter().map(Arc::as_ptr).collect(); + let sketches: usize = self.sketches.iter().filter(|s| !kept.contains(&Arc::as_ptr(s))).map(|s| s.retained_bytes()).sum(); bodies + sketches + self.sheets.len() * 4096 + self.threads.len() * 192 + self.construct.len() * 192 } pub fn body(&self, name: &str) -> Option<&ModelBody> { + #[cfg(test)] + cost_tests::count(|c| c.body_searches += 1); self.bodies.iter().find(|b| b.name == name) } @@ -1288,8 +1065,18 @@ pub struct FeatureResult { pub id: u64, pub name: String, pub error: Option, + /// `error` is the kernel's internal error (a panic it caught, [`kernel::KernelError::Internal`]), + /// not the feature's failure: the command that made the feature reports it as one. + #[serde(skip)] + pub internal: bool, pub warning: Option, - pub boolean_diagnostics: kernel::BooleanDiagnostics, + /// An Import feature's warnings by kind and part, with what came in of the file's parts + /// (`warning` is the first of them as the kernel words them). + #[serde(skip_serializing_if = "Option::is_none")] + pub import_report: Option>, + /// What a Repair Part feature changed, face by face (the command's reply says it). + #[serde(skip)] + pub repair: Option>, pub ms: f64, pub skipped: bool, /// Not evaluated on the document's current inputs: a feature at or after a sketch shown live @@ -1331,6 +1118,10 @@ pub struct Model { kept: KeptSlot, /// The imported texts' digests the last `evaluate` fingerprinted the features with. step_digests: StepDigests, + /// The address of the shared document whose fingerprints the results were last given in + /// full, with [`fingerprints_digest`] of them then ([`Model::pinned_prefix`]). Only an + /// address: a reference to the document would make every in-place edit of it a copy. + fingerprinted: Option<(usize, u64)>, /// The document context the last `evaluate` ran in ([`context_digest`]). context: u64, /// The last active result of each feature hidden by the history marker, with its document @@ -1342,6 +1133,8 @@ pub struct Model { primed: Option<(u64, Arc>)>, /// Shared with copies of this evaluator; states hold only a weak reference. frame_bodies: Arc>, + /// When SMLib's check runs on the features this model evaluates ([`Model::set_validation`]). + validation: kernel::Validation, /// Inputs proven to describe placement-independent geometry, and the state they produced. placement_inputs: Option, /// All evaluated features use supported local inputs; computed with the existing owner index. @@ -1450,32 +1243,40 @@ fn quantize(sk: &mut solidcraft_sketch::Sketch) { /// file's text by its digest. /// Hash [`feature_json`] of `f` into `h`. Every evaluation fingerprints every feature, and in a /// design built command by command almost all of them are the same as last time: the text of a -/// feature is kept (per thread, by id) with the feature it was written from, and written again -/// only when the feature differs. An Import's text also depends on its STEP digest, so it is -/// written each time as before. +/// feature is kept (by id) with the feature it was written from, and written again only when the +/// feature differs. An Import's text also depends on its STEP digest, so it is written each time +/// as before. +/// +/// The texts are shared by every thread: a command evaluated ahead runs on a new worker thread +/// each time (the desktop's deferred commands and delete checks, the control channel's ahead +/// jobs), and a per-thread store started empty there, so every ahead run wrote out every +/// feature again. The lock is held only to look up or store an entry, never while a feature is +/// compared or written; an entry is the same whichever thread wrote it, since the text is a +/// function of the feature alone. fn hash_feature_json(f: &Feature, steps: &StepDigests, h: &mut impl Hasher) { + type Written = std::collections::HashMap>; + static WRITTEN: std::sync::LazyLock> = std::sync::LazyLock::new(Default::default); if matches!(f.kind, FeatureKind::Import { .. }) { feature_json(f, steps).hash(h); return; } - thread_local! { - static WRITTEN: std::cell::RefCell> = std::cell::RefCell::new(std::collections::HashMap::new()); + let seen = WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).get(&f.id).cloned(); + if let Some(seen) = seen + && seen.0 == *f + { + seen.1.hash(h); + return; } - WRITTEN.with(|written| { - let mut written = written.borrow_mut(); - if let Some((seen, json)) = written.get(&f.id) - && seen == f - { - json.hash(h); - return; - } - let json = feature_json(f, steps); - json.hash(h); - if written.len() >= 1 << 15 { - written.clear(); - } - written.insert(f.id, (f.clone(), json)); - }); + #[cfg(test)] + cost_tests::count_written(); + let json = feature_json(f, steps); + json.hash(h); + let entry = Arc::new((f.clone(), json)); + let mut written = WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if written.len() >= 1 << 15 { + written.clear(); + } + written.insert(f.id, entry); } fn feature_json(f: &Feature, steps: &StepDigests) -> String { @@ -1675,6 +1476,42 @@ fn context_digest(doc: &Document, vals: &BTreeMap) -> u64 { h.finish() } +/// What the validation mode adds to the context digest: nothing for checking every step (how +/// every evaluation before the mode checked, so its results and saved caches stand), so a result +/// is taken from the cache only under the mode it was evaluated in. +fn validation_digest(validation: kernel::Validation) -> u64 { + match validation { + kernel::Validation::EachStep => 0, + v => { + let mut h = std::collections::hash_map::DefaultHasher::new(); + ("validation", v.id()).hash(&mut h); + h.finish() + } + } +} + +/// SMLib's check of every body a feature made or changed (in `after`, not in `before`, the +/// state it started from), once its steps left their checks to its end: the first that fails is +/// the feature's error, naming the body. +fn check_kept(before: &ModelState, after: &ModelState) -> kernel::Result<()> { + for b in &after.bodies { + if before.bodies.iter().any(|old| old.body.same_shape(&b.body)) { + continue; + } + kernel::check_kept(&b.body).map_err(|e| kernel::KernelError::Failed(format!("body `{}`: {e}", b.name)))?; + } + Ok(()) +} + +/// Whether `after`, a state feature `f` evaluated to from `before` in an earlier evaluation, is +/// still its result in `doc`: a feature saved before format 14 names the pieces it splits a body +/// into as the later features pick them ([`crate::lineage::order_legacy_lumps`]), which neither +/// its fingerprint nor its cache key cover. (A script replays those features after it: the state +/// made before they were there named the pieces otherwise.) +fn legacy_current(doc: &Document, f: &Feature, before: &ModelState, after: &ModelState) -> bool { + !f.shell_piece_order || after.legacy_picks.get(&f.id).copied().unwrap_or(0) == crate::lineage::legacy_picks_digest(&after.bodies, before, doc, f) +} + /// The cache key of a feature evaluation: its own inputs, the document context and the state it /// starts from. Features that replay other features' definitions (patterns and mirrors of /// features) also take the chain fingerprint, which covers every earlier definition. @@ -1820,6 +1657,8 @@ fn hash_placement(m: &Mat, h: &mut impl Hasher) { fn mirror_placements_digest(doc: &Document, f: &Feature, placements: &[Vec], bodies: &[crate::BodyName]) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); doc.component_transform(f.component).iter().flatten().for_each(|x| x.to_bits().hash(&mut h)); + // A feature added after the mirror that builds on its copies needs them made for that. + placement_reuse::copies_only_shown(doc, f).hash(&mut h); for placed in placements.iter().map(|path| mirror_copy_frame(doc, path)) { placed.is_some().hash(&mut h); if let Some((component, frame, picked)) = placed { @@ -1970,13 +1809,7 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64 None => u8::MAX.hash(&mut h), } } - for name in &reads.bodies { - name.hash(&mut h); - match st.and_then(|st| st.body(name)) { - Some(b) => hash_placement(&crate::mat_mul(&inverse, &body_world(doc, b)), &mut h), - None => u8::MAX.hash(&mut h), - } - } + hash_placed_bodies(doc, st, &reads.bodies, &inverse, &mut h); // Legacy and component-wide reads still need the conservative offset dependency. Body // reads above already include just their own offsets, in the frame that evaluates them. if reads.all || !reads.components.is_empty() || !reads.paths.is_empty() { @@ -1986,6 +1819,38 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64 h.finish() | 1 } +/// The bodies part of [`placement_digest`]: each body read, in name order, and where it is placed +/// relative to the reading frame `inverse` (`u8::MAX` for one not in `st`), as [`body_world`] +/// places it. The bodies, their components and the components' frames are looked up once: a +/// join or cut without targets reads every body of its component, and searching the model, the +/// timeline and the placements again for each of them made every evaluation, even one served +/// from the cache, quadratic in the bodies. +fn hash_placed_bodies(doc: &Document, st: Option<&ModelState>, names: &std::collections::BTreeSet, inverse: &Mat, h: &mut impl Hasher) { + let (Some(st), false) = (st, names.is_empty()) else { + names.iter().for_each(|name| (name, u8::MAX).hash(h)); + return; + }; + // The first body of a name, as `ModelState::body` finds it. + let mut index: std::collections::HashMap<&str, usize> = std::collections::HashMap::with_capacity(st.bodies.len()); + for (i, b) in st.bodies.iter().enumerate() { + index.entry(b.name.as_str()).or_insert(i); + } + let components = doc.model_body_components(st); + let mut frames: std::collections::HashMap = std::collections::HashMap::new(); + for name in names { + name.hash(h); + let found = index.get(name.as_str()).and_then(|&i| Some((st.bodies.get(i)?, *components.get(i)?))); + match found { + Some((b, component)) => { + let m = *frames.entry(component).or_insert_with(|| doc.component_transform(component)); + let world = doc.model_body_offset(b).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m); + hash_placement(&crate::mat_mul(inverse, &world), h); + } + None => u8::MAX.hash(h), + } + } +} + /// Every occurrence's placement and every body offset (a feature read from a frame that cannot /// be inverted). fn placements_hash(doc: &Document) -> u64 { @@ -2160,9 +2025,24 @@ impl Model { self.primed = None; } + /// When SMLib's check runs on the features this model evaluates. + pub fn validation(&self) -> kernel::Validation { + self.validation + } + + /// Check the features evaluated from now on under `validation` ([`kernel::Validation`]): + /// after every sweep, boolean and blend, once on the bodies each feature keeps, or not at + /// all. The results already there stand until their features are evaluated again; the cache + /// keeps results apart by mode, so one evaluated under another mode is not taken up. + pub fn set_validation(&mut self, validation: kernel::Validation) { + self.validation = validation; + } + /// Re-evaluate the document, reusing results up to the first changed feature. pub fn evaluate(&mut self, doc: &Document) { + let _span = solidcraft_profile::span("doc", "evaluate"); self.placement_inputs = None; + self.fingerprinted = None; self.placement_local = true; let (vals, perr) = evaluation_values(doc); self.param_errors = perr; @@ -2177,7 +2057,8 @@ impl Model { let mut recomputed = 0; let mut restored = 0; let marker = doc.marker.unwrap_or(usize::MAX); - let ctx = context_digest(doc, &vals); + let validation = self.validation; + let ctx = context_digest(doc, &vals) ^ validation_digest(validation); let previous_context = self.context; let mut rolled_results = std::mem::take(&mut self.rolled_results); self.context = ctx; @@ -2225,9 +2106,11 @@ impl Model { if f.suppressed && !rolled_back { reserved.extend(f.body_names.iter().map(|n| n.trim()).filter(|n| !n.is_empty()).map(str::to_string)); } + // A feature that names its pieces as later features pick them (saved before format 14) + // has a result only while those picks are what they were. if reuse && !unkept - && let Some(old) = self.results.get(i).filter(current) + && let Some(old) = self.results.get(i).filter(current).filter(|old| old.skipped || legacy_current(doc, f, &state, &old.state)) { if !old.skipped { state = old.state.clone(); @@ -2241,8 +2124,10 @@ impl Model { id: f.id, name: f.name.clone(), error: None, + internal: false, warning: None, - boolean_diagnostics: Default::default(), + import_report: None, + repair: None, ms: 0.0, skipped: true, stale: false, @@ -2273,8 +2158,10 @@ impl Model { id: f.id, name: f.name.clone(), error: Some(e), + internal: false, warning: None, - boolean_diagnostics: Default::default(), + import_report: None, + repair: None, ms: 0.0, skipped: false, stale: false, @@ -2289,7 +2176,13 @@ impl Model { cache_key(f, fp, fingerprint(doc, 0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state); let kept = self.kept.0.as_ref().filter(|_| !self.no_cache); if !self.no_cache - && let Some(c) = self.cache.lock().ok().and_then(|mut m| m.get(key)).or_else(|| kept.and_then(|k| k.get(key))) + && let Some(c) = self + .cache + .lock() + .ok() + .and_then(|mut m| m.get(key)) + .or_else(|| kept.and_then(|k| k.get(key))) + .filter(|c| c.error.is_some() || legacy_current(doc, f, &state, &c.state)) { if let Some(k) = kept { k.put(key, &c); @@ -2304,8 +2197,10 @@ impl Model { id: f.id, name: f.name.clone(), error: c.error, + internal: false, warning: c.warning, - boolean_diagnostics: c.boolean_diagnostics, + import_report: c.import_report, + repair: c.repair, ms: c.ms, skipped: false, stale: false, @@ -2317,7 +2212,12 @@ impl Model { } // An active result hidden by the marker, or evaluated ahead on these same inputs // (the same chain of definitions from the start). Changed inputs never reuse it. - if let Some(r) = rolled.as_ref().filter(current).or_else(|| primed.as_ref().and_then(|p| p.get(&f.id)).filter(current)) { + if let Some(r) = rolled + .as_ref() + .filter(current) + .or_else(|| primed.as_ref().and_then(|p| p.get(&f.id)).filter(current)) + .filter(|r| r.error.is_some() || legacy_current(doc, f, &state, &r.state)) + { restored += 1; if r.error.is_none() { state = r.state.clone(); @@ -2327,6 +2227,8 @@ impl Model { continue; } recomputed += 1; + // Each feature computed is a profiler span named after its kind. + let _feature_span = solidcraft_profile::span("feature", f.kind.type_name()); let before = state.clone(); let t0 = now(); let mut next = (*state).clone(); @@ -2337,27 +2239,42 @@ impl Model { b.made = crate::lineage::Made::Before; } let mut warning = None; + let mut import_report = None; + let mut repair = None; // Face references by name: move each face point onto its named face (on the body the // feature names, when it names one and the face is there). let renamed; + let mut frame_error: Option = None; let f = match with_named_face_points(doc, &state, f) { - Some((g, notes)) => { + Ok(Some((g, notes))) => { if !notes.is_empty() { warning = Some(notes.join("; ")); } renamed = g; &renamed } - None => f, + Ok(None) => f, + Err(e) => { + frame_error = Some(e.in_feature(&f.name).to_string()); + f + } }; // A parameter with an error fails the features using it, with that error. let bad_param = param_names(f).into_iter().find_map(|n| self.param_errors.get(&n).map(|e| format!("parameter `{n}`: {e}"))); - let (r, mut boolean_diagnostics) = kernel::capture_boolean_diagnostics(|| match bad_param { + let r = match frame_error.or(bad_param) { Some(e) => Err(kernel::KernelError::Failed(e)), None => kernel::guard(&f.name, || { - eval_feature(doc, &vals, f, &mut next, &mut warning).map_err(|e| kernel::KernelError::Failed(e.to_string())) + let (r, deferred) = + kernel::validating(validation, || eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report, &mut repair)); + r.map_err(|e| match e { + // A panic the kernel caught stays one. + crate::DocError::Kernel(kernel::KernelError::Internal(m)) => kernel::KernelError::Internal(m), + e => kernel::KernelError::Failed(e.in_feature(&f.name).to_string()), + })?; + // The checks the feature's steps left to its end: the bodies it keeps. + if deferred { check_kept(&state, &next) } else { Ok(()) } }), - }); + }; if r.is_ok() { // Profiles picked by curves that no longer bound a profile exactly were found // by their best match: say which. @@ -2369,15 +2286,11 @@ impl Model { } } } - if let Some(note) = boolean_diagnostics.warning() { - append_warning(&mut warning, note); - } track_altered_sheets(&state, &mut next, f, &mut warning); note_join_apart(&state, &next, f, &mut warning); - } else { - boolean_diagnostics = Default::default(); } let ms = t0.elapsed().as_secs_f64() * 1000.0; + let internal = matches!(r, Err(kernel::KernelError::Internal(_))); let error = match r { Ok(()) => { // Copies are named after their sources through the instance transforms. @@ -2395,7 +2308,17 @@ impl Model { } _ => mats, }; - next.stamp(&state, f, key, mats); + next.stamp(doc, &state, f, key, mats); + // Evaluated again only for what came before it (a mirror moved by a drag). + if let Some(old) = self.results.get(i).filter(|old| old.id == f.id) { + let made = old.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| (b.name.as_str(), b)); + let made: std::collections::HashMap<&str, &ModelBody> = made.collect(); + for b in next.bodies.iter_mut().filter(|b| b.feature == f.id) { + if let Some(old) = made.get(b.name.as_str()) { + b.keep_meshes_of(old); + } + } + } for b in &mut next.bodies { if !b.transferred { b.component = match doc.body_components.get(&b.name) { @@ -2411,11 +2334,13 @@ impl Model { } Err(e) => Some(e.to_string().trim_start_matches("the operation failed: ").to_string()), }; - if !self.no_cache && !watched.cancelled() { + // A panic is no result to reuse: the kernel was replaced after it. + if !self.no_cache && !watched.cancelled() && !internal { let e = CachedEval { error: error.clone(), warning: warning.clone(), - boolean_diagnostics: boolean_diagnostics.clone(), + import_report: import_report.clone(), + repair: repair.clone(), ms, bytes: state.added_bytes(&before), state: state.clone(), @@ -2432,8 +2357,10 @@ impl Model { id: f.id, name: f.name.clone(), error, + internal, warning, - boolean_diagnostics, + import_report, + repair, ms, skipped: false, stale: false, @@ -2564,19 +2491,76 @@ impl Model { /// Set every result's fingerprint to `doc`'s, so the next evaluation reuses every result /// (after a change that builds nothing differently). pub fn refingerprint(&mut self, doc: &Document) { + self.refingerprint_from(doc, 0); + } + + /// How many leading results keep their fingerprints when `doc` has the body names of the + /// features `renamed` pinned, and nothing else changed (see [`Model::refingerprint_shared`]). + /// Every command pins, and fingerprinting the whole timeline again for it cost as much as + /// the fingerprinting of the evaluation itself. When the results hold `doc`'s fingerprints + /// (the address and digest kept when they were given prove it), those before the first + /// renamed feature stand, since nothing they read changes, unless a pattern or mirror of + /// features among them replays a renamed one (it fingerprints its sources' definitions + /// wherever they are). Without that proof: none. + pub fn pinned_prefix(&self, doc: &Arc, renamed: &[u64]) -> usize { + let proven = self.fingerprinted.is_some_and(|(of, digest)| of == Arc::as_ptr(doc) as usize && digest == fingerprints_digest(&self.results)); + if !proven { + return 0; + } + let Some(first) = doc.features.iter().position(|f| renamed.contains(&f.id)) else { return doc.features.len() }; + let replays_renamed = |f: &Feature| match &f.kind { + FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } => { + bodies.is_empty() && !features.is_empty() && replayed_sources(doc, features).iter().any(|g| renamed.contains(&g.id)) + } + _ => false, + }; + doc.features.iter().take(first).position(replays_renamed).unwrap_or(first) + } + + /// Drop the proof [`Model::pinned_prefix`] reads: the document at that address is about to + /// change in place. + pub fn forget_fingerprints(&mut self) { + self.fingerprinted = None; + } + + /// Fingerprint the results from `start` on for `doc`, chained onto the fingerprint before. + pub(crate) fn refingerprint_from(&mut self, doc: &Document, start: usize) { self.placement_inputs = None; + self.fingerprinted = None; + self.step_digests = StepDigests::of(doc, &self.step_digests); + let start = start.min(self.results.len()).min(doc.features.len()); + if start == self.results.len().min(doc.features.len()) { + return; + } let (vals, _) = evaluation_values(doc); let marker = doc.marker.unwrap_or(usize::MAX); - self.step_digests = StepDigests::of(doc, &self.step_digests); - let mut prev = 0; + let last = start.checked_sub(1).and_then(|i| self.results.get(i)); + let mut prev = last.map_or(0, |r| r.fingerprint); // Each feature's fingerprint reads the model it starts from, as evaluating does. - let mut before = Arc::new(ModelState::default()); - for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate() { + let mut before = last.map_or_else(|| Arc::new(ModelState::default()), |r| r.state.clone()); + for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate().skip(start) { prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests, Some(&before)); r.fingerprint = prev; before = r.state.clone(); } } + + /// Note that the results now hold `doc`'s fingerprints (for [`Model::pinned_prefix`]). + pub(crate) fn mark_fingerprinted(&mut self, doc: &Arc) { + self.fingerprinted = Some((Arc::as_ptr(doc) as usize, fingerprints_digest(&self.results))); + } +} + +/// A digest of the results' features and fingerprints, which proves they are still the ones +/// [`Model::mark_fingerprinted`] saw (whatever changed them since). +fn fingerprints_digest(results: &[FeatureResult]) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + results.len().hash(&mut h); + for r in results { + r.id.hash(&mut h); + r.fingerprint.hash(&mut h); + } + h.finish() } /// Key of the design's length unit (mm per unit) among the values (no parameter can be named @@ -2636,6 +2620,42 @@ fn refuse_loft_holes(r: &Region2) -> Result<()> { Err(DocError::Invalid("not supported yet: lofting a section with holes to a point".into())) } +/// What each way of closing a taper's corners ([`kernel::DraftCorner`]) gives at each sharp +/// corner of the profiles `sel` picks in `ss`, extruded `distance` with a taper of `taper` radians +/// (positive grows the profile), the profiles merged as an extrude merges them: per corner, how +/// far each offset curve runs on (or is trimmed), whether the corner cuts in, or why the rule +/// refuses it. A dialog offers the other rules where the chosen one is a poor fit. +pub fn draft_corner_options(ss: &SolvedSketch, sel: &ProfileSel, distance: f64, taper: f64) -> Result> { + let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, sel)?); + let mut out = Vec::new(); + for r in ®ions { + out.extend(kernel::draft_corners(r, distance, taper)?); + } + Ok(out) +} + +/// The corner rule a taper takes for profile `r` of `ss` when the user chose none: preserve +/// curvature, unless a corner of the profile cannot keep it exactly (a curve that is neither a +/// line nor an arc), then the tangent rule, with a note in `notes` saying where and why. +fn draft_corner_for(ss: &SolvedSketch, r: &Region2, distance: f64, taper: f64, notes: &mut Vec) -> Result { + let reports = kernel::draft_corners(r, distance, taper)?; + let inexact = reports + .iter() + .find(|c| c.options.iter().any(|o| o.rule == kernel::DraftCorner::PreserveCurvature && o.fill == Err(kernel::CornerRefusal::NotExact))); + Ok(match inexact { + Some(c) => { + notes.push(format!( + "the taper's corners of profile at ({}, {}) in {} use the tangent rule: a curve of it is neither a line nor an arc, so its walls cannot continue as themselves exactly; corner: round also builds", + show_mm(c.at.x), + show_mm(c.at.y), + ss.name + )); + kernel::DraftCorner::Tangent + } + None => kernel::DraftCorner::PreserveCurvature, + }) +} + pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result> { let ps = &ss.profiles; if ps.is_empty() { @@ -2885,29 +2905,22 @@ fn sheet_boolean_changes(body: &Body, tools: &[Body], op: Operation) -> Result) -> Result> { if tools.len() > 1000 || tools.iter().fold(0usize, |n, t| n.saturating_add(t.body.face_count())) > 16_384 { return Err(DocError::Invalid("intersection tools exceed the bounded geometry budget".into())); } - let mut groups = tools; - while groups.len() > 1 { - let mut next = Vec::new(); - let mut iter = groups.into_iter(); - while let Some(a) = iter.next() { - match iter.next() { - Some(b) => { - let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)? - .ok_or_else(|| DocError::Invalid("intersection tool union is empty".into()))?; - next.push(Traced::step(u, &[&a, &b])); - } - None => next.push(a), - } - } - groups = next; + if tools.len() < 2 { + return Ok(tools); } - Ok(groups) + Ok(vec![union_all(&tools.iter().collect::>())?]) +} + +/// The union of `operands` (traced bodies) in one kernel call, keeping their lineage. +fn union_all(operands: &[&Traced]) -> Result { + let bodies: Vec<&Body> = operands.iter().map(|t| &t.body).collect(); + Ok(Traced::step(kernel::union_all(&bodies)?, operands)) } /// After a cut handled some sheet bodies as flat machining, apply it to the other targets. @@ -2937,29 +2950,6 @@ fn apply_beside_sheet_cut( apply_traced(doc, st, f, tools, op, &rest) } -/// Only one target meets every separated tool. A tool with no contact must retain -/// Join's first-target fallback; tools touching different targets must retain absorption order. -fn common_join_target(state: &ModelState, indices: &[usize], tools: &[Traced]) -> Result> { - if indices.len() > 64 { - return Ok(None); - } - let bodies: Vec<_> = tools.iter().map(|tool| tool.body.clone()).collect(); - let mut contacts = vec![None; tools.len()]; - for &index in indices { - let body = state.bodies.get(index).ok_or_else(|| DocError::Invalid("join target disappeared".into()))?; - for (contact, meets) in contacts.iter_mut().zip(body.body.meets_each(&bodies)?) { - if meets { - if contact.is_some() { - return Ok(None); - } - *contact = Some(index); - } - } - } - let common = contacts.first().copied().flatten(); - Ok(common.filter(|index| contacts.iter().all(|contact| *contact == Some(*index)))) -} - fn apply_op(doc: &Document, state: &mut ModelState, f: &Feature, tools: Vec, op: Operation, targets: &[String]) -> Result<()> { apply_traced(doc, state, f, tools.into_iter().map(Traced::unnamed).collect(), op, targets) } @@ -2967,16 +2957,16 @@ fn apply_op(doc: &Document, state: &mut ModelState, f: &Feature, tools: Vec) -> Vec { +fn clear_tools_as_one(tools: Vec) -> Result> { if tools.len() < 8 { - return tools; + return Ok(tools); } let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); - match kernel::union_apart(&bodies) { + Ok(match kernel::union_apart(&bodies)? { // Each piece's faces keep the names of the tool it is. - Ok(Some(one)) => vec![Traced::step(one, &tools.iter().collect::>())], - _ => tools, - } + Some(one) => vec![Traced::step(one, &tools.iter().collect::>())], + None => tools, + }) } /// An intersect never deletes a body by accident (#5295): it is refused when nothing of a named @@ -3113,111 +3103,70 @@ fn apply_traced_with( return Ok(()); } if matches!(op, Operation::Cut | Operation::Intersect) { + // A cut that cannot reach a sheet leaves it as it is (#10226): a sheet whose box lies + // clear of every tool's, in its own frame, needs no boolean to show it. An intersect + // removes the sheets it misses, and checks each one as before. + let mut reach: Option>> = None; for &i in &target_idx { if let Some(mb) = state.bodies.get(i).filter(|b| state.sheets.iter().any(|s| s.body == b.name)) { let m = tool_frame(&mb.name); + if op == Operation::Cut && m.is_none() && !mb.body.is_mesh() && !tools.iter().any(|t| t.body.is_mesh()) { + let reach = reach.get_or_insert_with(|| tools.iter().map(|t| more::exact_box(&t.body)).collect()); + if !reach.is_empty() + && let Some(target) = more::exact_box(&mb.body) + && reach.iter().all(|tool| more::boxes_apart(&Some(target), tool)) + { + continue; + } + } let bodies: Vec = tools.iter().map(|t| tool_in(t, m).map(|t| t.body)).collect::>()?; + #[cfg(test)] + cost_tests::count(|c| c.cut += 1); sheet_boolean_unchanged(&mb.body, &bodies, op)?; } } } - // Batching solid targets must preserve Join's absorption order, - // sheet material tracking and the separate bodies of a New Body extrusion. - if tools.len() > 1 - && matches!(f.kind, FeatureKind::Extrude { .. }) - && matches!(op, Operation::Join | Operation::Cut) - && !target_idx.is_empty() - && target_idx.iter().all(|i| state.bodies.get(*i).is_some_and(|b| !b.body.is_mesh() && !state.sheets.iter().any(|s| s.body == b.name))) - && let Ok(Some(compound)) = kernel::compound_disjoint_extrusions(&tools.iter().map(|tool| tool.body.clone()).collect::>()) - { - let target = if target_idx.len() == 1 { - target_idx.first().copied() - } else if op == Operation::Join { - common_join_target(state, &target_idx, &tools).ok().flatten() - } else { - None - }; - // The optimization must not reject geometry the original sequential path can - // handle. A failed batch leaves the model untouched and retries the original tools. - let batch_targets = if op == Operation::Cut { - // Subtracting a union equals subtracting its separated tools in order. - // Keep ALL original participants; no sampled contact test excludes a body. - Some(target_idx.iter().filter_map(|index| state.bodies.get(*index).map(|body| body.name.clone())).collect::>()) - } else { - target.and_then(|index| state.bodies.get(index)).map(|body| vec![body.name.clone()]) - }; - if let Some(names) = batch_targets { - let mut batched = state.clone(); - // Preserve the original participants. For Join, the compound's larger - // size must not expand the contact tolerance and absorb a nearby body. - if apply_traced(doc, &mut batched, f, vec![Traced::step(compound, &tools.iter().collect::>())], op, &names).is_ok() { - *state = batched; - return Ok(()); - } - } - } match op { Operation::Join => { - // Each tool joins every target it meets into one body, kept under the first one's - // name; a tool that meets none joins the first target as a separate lump. A sheet - // metal body keeps its own identity: only the first body met may be one. - let mut live: Vec = target_idx.iter().filter_map(|i| state.bodies.get(*i).map(|b| b.name.clone())).collect(); - // Each union keeps the lineage of what it joins, so the joined body's faces keep - // their names (the tool's new faces are named by their roles). - let union = |a: &Traced, b: &Traced| -> Result { - let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)?.ok_or_else(|| DocError::Invalid("join produced nothing".into()))?; - Ok(Traced::step(u, &[a, b])) - }; - for tool in &tools { - let mut met: Vec = Vec::new(); - for name in &live { - let Some(mb) = state.body(name) else { continue }; - let sheet = state.sheets.iter().any(|s| &s.body == name); - if mb.body.is_mesh() || (!met.is_empty() && sheet) { - continue; - } - // Each body is met where it is shown: the tool goes into its frame (#3383). - if mb.body.meets(&tool_in(tool, tool_frame(name))?.body)? { - met.push(name.clone()); - } + let joined = join(state, tools, &target_idx)?; + if f.touching == crate::Touching::Separate { + let mut kept = None; + for name in joined { + kept = kept.max(separate_touching(state, &name)?); } - let Some(keep) = met.first().or(live.first()).cloned() else { return Ok(()) }; - let Some(base) = state.body(&keep).map(ModelBody::traced) else { continue }; - let into_keep = tool_frame(&keep); - let mut acc = union(&base, &tool_in(tool, into_keep)?)?; - for name in met.iter().skip(1) { - if let Some(b) = state.body(name) { - // A body placed differently from the one kept joins it where it is shown. - let from = match tool_frame(name) { - Some(m) => crate::mat_inverse(&m), - None => Some(crate::IDENTITY), - }; - let m = from.map(|from| crate::mat_mul(&into_keep.unwrap_or(crate::IDENTITY), &from)).filter(|m| !crate::is_identity(m)); - acc = union(&acc, &tool_in(&b.traced(), m)?)?; - } + if let Some(k) = kept { + let most = state.kept_separate.entry(f.id).or_insert(k); + *most = (*most).max(k); } - let absorbed: std::collections::BTreeSet = met.into_iter().skip(1).collect(); - if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == keep) { - *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature); - } - state.bodies.retain(|b| !absorbed.contains(&b.name)); - for t in state.threads.iter_mut().filter(|t| absorbed.contains(&t.body)) { - t.body = keep.clone(); - } - live.retain(|n| !absorbed.contains(n)); } } Operation::Cut | Operation::Intersect => { let bop = if op == Operation::Cut { BoolOp::Cut } else { BoolOp::Intersect }; - let tools = if op == Operation::Cut { clear_tools_as_one(tools) } else { tools }; + let tools = if op == Operation::Cut { clear_tools_as_one(tools)? } else { tools }; // Each target's pieces before the cut: a body joined from separate pieces stays one. let affected: std::collections::BTreeMap = target_idx.iter().filter_map(|i| state.bodies.get(*i)).map(|b| (b.name.clone(), b.body.lumps().map_or(1, |l| l.len()))).collect(); let mut remove = Vec::new(); + // A cut hands a body its tools cannot reach back as it was, but only after a whole + // boolean: in a design of many bodies that was most of a hole's time (#10225). A body + // whose exact box lies clear of every tool's is left as it is. A body shown in another + // frame, and a mesh body, are cut as before; an intersect removes the bodies it misses. + let reach: Option>> = + (op == Operation::Cut && !tools.iter().any(|t| t.body.is_mesh())).then(|| tools.iter().map(|t| more::exact_box(&t.body)).collect()); for &ti in &target_idx { let Some(mut acc) = state.bodies.get(ti).map(|b| Some(b.traced())) else { continue }; // The tools meet the target where it is shown: in its frame (#3383). let into = state.bodies.get(ti).and_then(|b| tool_frame(&b.name)); + if let (Some(reach), None, Some(mb)) = (&reach, into, state.bodies.get(ti)) + && !reach.is_empty() + && !mb.body.is_mesh() + && let Some(target) = more::exact_box(&mb.body) + && reach.iter().all(|tool| more::boxes_apart(&Some(target), tool)) + { + continue; + } + #[cfg(test)] + cost_tests::count(|c| c.cut += 1); for t in &tools { let t = &tool_in(t, into)?; acc = match acc { @@ -3270,6 +3219,11 @@ fn apply_traced_with( // Not yet: a cut that splits one piece of such a body still splits all of them; keeping // the untouched ones together needs each new piece traced to the piece it came from. let mut taken: std::collections::BTreeSet = state.bodies.iter().map(|b| b.name.clone()).collect(); + // The pieces past the first belong to this feature, like a split's pieces (#10123): + // `body.rename` stores their names in this feature's `body_names`, in this order, so a + // renamed piece keeps its own name through a rebuild instead of landing on a sibling + // of the body it was cut from. + let mut extra = 0usize; let mut split: Vec = Vec::new(); for mb in std::mem::take(&mut state.bodies) { let Some(&had) = affected.get(&mb.name).filter(|_| !state.sheets.iter().any(|s| s.body == mb.name)) else { @@ -3281,18 +3235,7 @@ fn apply_traced_with( split.push(mb); continue; } - // Each piece's faces are named after the whole's, worked out once for the whole - // (so pieces of one face in different bodies are told apart). - let lineages = crate::lineage::Lineage::lumps(&mb.body, mb.lineage().as_deref(), &pieces); - for (k, (p, lineage)) in pieces.into_iter().zip(lineages).enumerate() { - let name = if k == 0 { - mb.name.clone() - } else { - (k..=k + taken.len()).map(|j| format!("{} ({j})", mb.name)).find(|n| !taken.contains(n)).unwrap_or_default() - }; - taken.insert(name.clone()); - split.push(ModelBody::new(name, p, mb.feature).with_lineage(lineage)); - } + split.extend(named_pieces_of(&mb, pieces, &mut taken, f.id, &f.body_names, &mut extra)); } state.bodies = split; } @@ -3301,6 +3244,259 @@ fn apply_traced_with( Ok(()) } +/// Join `tools` into the bodies at `target_idx`: each tool joins every target it meets into one +/// body, kept under the first one's name; a tool that meets none joins the first target as a +/// separate piece. A sheet metal body keeps its own identity: only the first body met may be +/// one. The names of the bodies the tools went into. +fn join(state: &mut ModelState, tools: Vec, target_idx: &[usize]) -> Result> { + let mut live: Vec = target_idx.iter().filter_map(|i| state.bodies.get(*i).map(|b| b.name.clone())).collect(); + // Each union keeps the lineage of what it joins, so the joined body's faces keep + // their names (the tool's new faces are named by their roles). + let union = |a: &Traced, b: &Traced| -> Result { + let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)?.ok_or_else(|| DocError::Invalid("join produced nothing".into()))?; + Ok(Traced::step(u, &[a, b])) + }; + // One target takes every tool, whichever it meets: the result is the union of all of + // them in one kernel call, checked once. + if let [keep] = live.as_slice() + && tools.len() > 1 + { + let Some(base) = state.body(keep).map(ModelBody::traced) else { return Ok(Vec::new()) }; + // The tools go into the kept body's frame, where it is shown (#3383). + let into_keep = tool_frame(keep); + let tools = tools.iter().map(|tool| tool_in(tool, into_keep)).collect::>>()?; + let operands: Vec<&Traced> = std::iter::once(&base).chain(&tools).collect(); + let acc = union_all(&operands)?; + if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == *keep) { + *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature); + } + return Ok(vec![keep.clone()]); + } + let mut joined = Vec::new(); + for tool in &tools { + let mut met: Vec = Vec::new(); + for name in &live { + let Some(mb) = state.body(name) else { continue }; + let sheet = state.sheets.iter().any(|s| &s.body == name); + if mb.body.is_mesh() || (!met.is_empty() && sheet) { + continue; + } + // Each body is met where it is shown: the tool goes into its frame (#3383). + if mb.body.meets(&tool_in(tool, tool_frame(name))?.body)? { + met.push(name.clone()); + } + } + let Some(keep) = met.first().or(live.first()).cloned() else { return Ok(joined) }; + let Some(base) = state.body(&keep).map(ModelBody::traced) else { continue }; + let into_keep = tool_frame(&keep); + let mut acc = union(&base, &tool_in(tool, into_keep)?)?; + for name in met.iter().skip(1) { + if let Some(b) = state.body(name) { + // A body placed differently from the one kept joins it where it is shown. + let from = match tool_frame(name) { + Some(m) => crate::mat_inverse(&m), + None => Some(crate::IDENTITY), + }; + let m = from.map(|from| crate::mat_mul(&into_keep.unwrap_or(crate::IDENTITY), &from)).filter(|m| !crate::is_identity(m)); + acc = union(&acc, &tool_in(&b.traced(), m)?)?; + } + } + let absorbed: std::collections::BTreeSet = met.into_iter().skip(1).collect(); + if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == keep) { + *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature); + } + state.bodies.retain(|b| !absorbed.contains(&b.name)); + for t in state.threads.iter_mut().filter(|t| absorbed.contains(&t.body)) { + t.body = keep.clone(); + } + live.retain(|n| !absorbed.contains(n)); + if !joined.contains(&keep) { + joined.push(keep); + } + } + Ok(joined) +} + +/// With `Touching::Separate`: the joined body `name` never keeps two pieces that touch only +/// along an edge or at a point, since they cannot be one solid. Its pieces that share a face are +/// one group. The groups that hold the material of the body before the feature (the first group +/// where that is not known) stay in it, each unless it touches one already kept; every other +/// group that touches another along an edge or at a point (as the record says, or on the exact +/// geometry where SMLib left the contact out) becomes a body of its own, named as a cut's pieces +/// are; groups that touch nothing stay in the joined body, which keeps its name. How +/// the pieces split off touched, when any were (a sheet metal or mesh body keeps its pieces). +fn separate_touching(state: &mut ModelState, name: &str) -> Result> { + let Some(i) = state.bodies.iter().position(|b| b.name == name) else { return Ok(None) }; + let Some(mb) = state.bodies.get(i).filter(|b| !b.body.is_mesh() && !state.sheets.iter().any(|s| s.body == name)) else { return Ok(None) }; + let n = mb.body.record().material_regions().len(); + if n < 2 { + return Ok(None); + } + // Pieces sharing a face are one solid: each group is listed under its least piece. + let contacts = mb.body.region_contacts()?; + let mut root: Vec = (0..n).collect(); + let find = |root: &[usize], mut k: usize| { + while let Some(&r) = root.get(k).filter(|&&r| r != k) { + k = r; + } + k + }; + for c in contacts.iter().filter(|c| c.contact == Contact::Face) { + let [a, b] = c.regions.map(|k| find(&root, k)); + if let Some(slot) = root.get_mut(a.max(b)) { + *slot = a.min(b); + } + } + let mut groups: Vec> = Vec::new(); + let mut group_of: Vec = Vec::with_capacity(n); + let mut by_root: BTreeMap = BTreeMap::new(); + for k in 0..n { + let g = *by_root.entry(find(&root, k)).or_insert_with(|| { + groups.push(Vec::new()); + groups.len() - 1 + }); + if let Some(list) = groups.get_mut(g) { + list.push(k); + } + group_of.push(g); + } + // The groups each group touches along an edge or at a point (groups never share a face), and + // the most any two of them share. + let mut touches: Vec> = vec![Vec::new(); groups.len()]; + let mut most: Option = None; + for c in &contacts { + let (Some(&a), Some(&b)) = (group_of.get(c.regions[0]), group_of.get(c.regions[1])) else { continue }; + if a == b { + continue; + } + for (g, h) in [(a, b), (b, a)] { + if let Some(list) = touches.get_mut(g).filter(|l| !l.contains(&h)) { + list.push(h); + } + } + most = most.max(Some(if c.contact == Contact::Vertex { KeptSeparate::AtPoint } else { KeptSeparate::AlongEdge })); + } + // Groups the record has apart may still touch where SMLib left the contact out of the + // topology (a face tangent to another along a line). + if groups.len() > 1 { + for [a, b] in unrecorded_touches(&mb.body.parts(&groups)?, &touches)? { + for (g, h) in [(a, b), (b, a)] { + if let Some(list) = touches.get_mut(g) { + list.push(h); + } + } + most = most.max(Some(KeptSeparate::Touching)); + } + } + let Some(most) = most else { return Ok(None) }; + // What stays in the joined body: the groups that touch nothing, and those of the body before + // the feature, each unless it touches one already kept. + let mut anchor = groups_from_body(mb, &groups).filter(|a| a.contains(&true)).unwrap_or_default(); + if anchor.is_empty() { + anchor = (0..groups.len()).map(|g| g == 0).collect(); + } + let mut stays: Vec = touches.iter().map(Vec::is_empty).collect(); + for g in 0..groups.len() { + let free = touches.get(g).is_some_and(|t| !t.iter().any(|h| stays.get(*h) == Some(&true))); + if free + && anchor.get(g) == Some(&true) + && let Some(slot) = stays.get_mut(g) + { + *slot = true; + } + } + let mut kept: Vec = groups.iter().zip(&stays).filter(|(_, s)| **s).flat_map(|(g, _)| g.iter().copied()).collect(); + kept.sort_unstable(); + let parts: Vec> = std::iter::once(kept).chain(groups.into_iter().zip(&stays).filter(|(_, s)| !**s).map(|(g, _)| g)).collect(); + let pieces = mb.body.parts(&parts)?; + let mut taken: std::collections::BTreeSet = state.bodies.iter().map(|b| b.name.clone()).collect(); + let named = named_pieces(mb, pieces, &mut taken); + state.bodies.splice(i..=i, named); + Ok(Some(most)) +} + +/// The pairs of `pieces` (positions) that touch though `touches` (the pieces each touches, as +/// the record says) doesn't list them: their least distance on the exact faces and edges is +/// within the larger of their record tolerances. A distance only the meshes give is not trusted +/// to say they touch. +fn unrecorded_touches(pieces: &[Body], touches: &[Vec]) -> Result> { + let meshes = pieces + .iter() + .map(|p| { + let chord = (p.size() * 1e-4).max(1e-6); + Ok((p.mesh(&kernel::MeshTolerance::chord(chord))?, chord)) + }) + .collect::>>()?; + let shapes: Vec = pieces.iter().zip(&meshes).map(|(p, (m, chord))| kernel::DistanceShape::new(p, m, *chord)).collect(); + let mut out = Vec::new(); + for (a, (sa, pa)) in shapes.iter().zip(pieces).enumerate() { + for (b, (sb, pb)) in shapes.iter().zip(pieces).enumerate().skip(a + 1) { + if touches.get(a).is_some_and(|t| t.contains(&b)) || !sa.bounds().meets(&sb.bounds()) { + continue; + } + let tol = pa.record().tolerance.max(pb.record().tolerance); + if kernel::body_distance(sa, sb, tol)?.is_some_and(|d| d.exact && d.distance <= tol) { + out.push([a, b]); + } + } + } + Ok(out) +} + +/// Which of `groups` (of positions in `mb`'s material regions) hold material of the body named +/// as `mb` before the feature: a face of theirs came from one of its faces. `None` where the +/// body's lineage is not known. +fn groups_from_body(mb: &ModelBody, groups: &[Vec]) -> Option> { + let from = mb.lineage()?.faces_from_body(&mb.name); + let record = mb.body.record(); + let regions = record.material_regions(); + let holds = |k: usize| { + let shells = regions.get(k).and_then(|&r| record.regions.get(r)).map(|r| r.shells.as_slice()).unwrap_or_default(); + shells.iter().any(|&s| match record.shells.get(s as usize) { + Some(solidcore_record::brep::Shell::Faces { faces, .. }) => faces.iter().any(|f| from.get(f.face as usize) == Some(&true)), + _ => false, + }) + }; + Some(groups.iter().map(|g| g.iter().any(|&k| holds(k))).collect()) +} + +/// The bodies the pieces of `mb` become: the first keeps its name, the others are numbered after +/// it ("Bar (1)") on past the names already `taken`. Each piece's faces are named after the +/// whole's, worked out once for the whole (so pieces of one face in different bodies are told +/// apart). +fn named_pieces(mb: &ModelBody, pieces: Vec, taken: &mut std::collections::BTreeSet) -> Vec { + named_pieces_of(mb, pieces, taken, mb.feature, &[], &mut 0) +} + +/// [`named_pieces`] for a feature that made the pieces past the first: they are `feature`'s, and +/// take the names stored for it from `stored`, from the place `extra` keeps (#10123), where one +/// is set and free. +fn named_pieces_of( + mb: &ModelBody, + pieces: Vec, + taken: &mut std::collections::BTreeSet, + feature: u64, + stored: &[String], + extra: &mut usize, +) -> Vec { + let lineages = crate::lineage::Lineage::lumps(&mb.body, mb.lineage().as_deref(), &pieces); + let mut out = Vec::with_capacity(pieces.len()); + for (k, (p, lineage)) in pieces.into_iter().zip(lineages).enumerate() { + let (name, made_by) = if k == 0 { + (mb.name.clone(), mb.feature) + } else { + let kept = stored.get(*extra).filter(|n| !n.trim().is_empty() && !taken.contains(*n)).cloned(); + *extra += 1; + let name = + kept.unwrap_or_else(|| (k..=k + taken.len()).map(|j| format!("{} ({j})", mb.name)).find(|n| !taken.contains(n)).unwrap_or_default()); + (name, feature) + }; + taken.insert(name.clone()); + out.push(ModelBody::new(name, p, made_by).with_lineage(lineage)); + } + out +} + /// Distance that reaches through every target body from the sketch plane (either side). pub fn through_all_distance(st: &ModelState, plane: &Plane, targets: &[String]) -> Result { let mut far: f64 = 0.0; @@ -3326,466 +3522,6 @@ pub fn through_all_distance(st: &ModelState, plane: &Plane, targets: &[String]) Ok(far * 1.02 + 1.0) } -/// Sample points inside a region (sketch coordinates). -fn region_samples(r: &Region2) -> Vec { - let mut out = vec![r.interior_point()]; - let solidcraft_geom::Aabb2 { min: lo, max: hi } = r.outer.polyline(1e-2).bounds(); - for i in 0..5 { - for j in 0..5 { - let p = Vec2::new(lo.x + (hi.x - lo.x) * (0.1 + 0.2 * i as f64), lo.y + (hi.y - lo.y) * (0.1 + 0.2 * j as f64)); - if r.contains(p) { - out.push(p); - } - } - } - out -} - -/// The region with each hole filled whose inside the tool would sweep with no change to the -/// targets: all empty for a cut (the profile drawn round a hole in the part), all material for a -/// join. Then the tool's walls don't lie on the part's walls there (the boolean can't intersect -/// walls lying on each other, #1360), and what it cuts or joins is the same. A hole is filled only -/// when points across it at levels through the tool are all empty (or all material) and no -/// vertex of the targets lies inside the column over it (an island in it, a floor). -fn fill_void_holes(st: &ModelState, r: &Region2, op: Operation, targets: &[String], plane: &Plane, (lo, hi): (f64, f64)) -> Region2 { - if r.holes.is_empty() || !matches!(op, Operation::Cut | Operation::Join) || hi - lo <= 0.0 { - return r.clone(); - } - let bodies: Vec<&ModelBody> = st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name)).collect(); - if bodies.is_empty() { - return r.clone(); - } - let meshes: Vec> = bodies.iter().map(|b| b.mesh()).collect(); - let size = bodies.iter().map(|b| b.body.size()).fold(0.0, f64::max); - let margin = (size * 1e-4).max(1e-4); - let n = plane.normal(); - // Many probes on one mesh each: indexed, the same answers as `Mesh::contains`. - let inside: Vec<_> = meshes.iter().map(|m| m.inside_index()).collect(); - let inside_any = |p: Vec3| inside.iter().any(|m| m.contains(p)); - let want = op == Operation::Join; - let mut holes = Vec::with_capacity(r.holes.len()); - for h in &r.holes { - let column = Region2 { outer: h.ccw(), holes: vec![] }; - let samples = region_samples(&column); - let swept = (1..=8).all(|k| { - let z = lo + (hi - lo) * (k as f64 - 0.5) / 8.0; - samples.iter().all(|s| inside_any(plane.to_world(*s) + n * z) == want) - }); - // No boundary of the targets within the column (shrunk off its wall, short of its ends). - let clear = swept - && meshes.iter().all(|m| { - m.positions.iter().all(|p| { - let z = (*p - plane.origin).dot(n); - let q = plane.to_local(*p); - !(z > lo + margin - && z < hi - margin - && column.contains(q) - && h.segs.iter().all(|sg| sg.point_at(sg.closest_param(q)).dist(q) > margin)) - }) - }); - if !clear { - holes.push(h.clone()); - } - } - Region2 { outer: r.outer.clone(), holes } -} - -/// The bodies a cut or join works on (its targets, else every body), asked what its tool would -/// take or add if it reached past its sketch. -struct Surroundings<'a> { - /// Each body with its display mesh and, once something near it is asked, its faces. - bodies: Vec<(&'a ModelBody, Arc, std::cell::OnceCell>>)>, - op: Operation, - /// The largest body's size. - size: f64, - /// Faces this close to a plane lie in it (the kernel's measure for coincident faces). - skin: f64, - /// How far off a round face a space must stay to be asked about: the face's triangles may - /// stand off it by twice the chord they are made with, and the check pads them as far again. - round: f64, -} - -impl<'a> Surroundings<'a> { - /// The chord of the meshes the bodies' faces are asked on, as a share of each one's size. - const CHORD: f64 = 2e-4; - - /// `None` for an operation other than a cut or a join, or without a body to work on. - fn of(st: &'a ModelState, op: Operation, targets: &[String]) -> Option> { - if !matches!(op, Operation::Cut | Operation::Join) { - return None; - } - let bodies: Vec<_> = - st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name)).map(|b| (b, b.mesh(), std::cell::OnceCell::new())).collect(); - let size = bodies.iter().map(|(b, _, _)| b.body.size()).fold(0.0, f64::max); - (!bodies.is_empty()).then(|| Surroundings { bodies, op, size, skin: (size * 1e-6).max(1e-8), round: 4.0 * Self::CHORD * size }) - } - - /// Does the space the triangles `pieces` of `plane` sweep along its normal, from the height - /// `lo` to `hi`, hold just what the tool may gain without changing the result: nothing of - /// the bodies (a cut), or one body's material (a join)? Decided on the bodies' faces (see - /// [`kernel::Clearance`]), so a wall, a rib, a gap or a hole anywhere in it counts. - /// `margin`: how far the region reaches past the triangles sideways (negative: their sides - /// are drawn in, so that faces lying against them don't count). - fn harmless(&self, plane: &Plane, pieces: &[[Vec2; 3]], margin: f64, lo: f64, hi: f64) -> bool { - let n = plane.normal(); - let faces: Vec<([Vec3; 3], f64)> = pieces.iter().map(|t| (t.map(|p| plane.to_world(p)), margin)).collect(); - let mut space = solidcraft_geom::Aabb3::EMPTY; - for p in faces.iter().flat_map(|(t, _)| t) { - space.add(*p + n * lo); - space.add(*p + n * hi); - } - let mut full = false; - for (body, mesh, faces_of) in &self.bodies { - // A body well away from that space holds none of it (its faces lie within the - // display mesh's chord tolerance of the mesh). - let (b, pad) = (mesh.bounds(), margin.abs() + 2.0 * body.display_tol()); - let away = |lo: Vec3, hi: Vec3| lo.x > hi.x + pad || lo.y > hi.y + pad || lo.z > hi.z + pad; - if !b.is_empty() && (away(b.min, space.max) || away(space.min, b.max)) { - continue; - } - let Some(clearance) = faces_of.get_or_init(|| kernel::Clearance::new(&body.body, body.body.size() * Self::CHORD)) else { return false }; - match clearance.swept(&faces, n, lo, hi) { - kernel::Occupancy::Mixed => return false, - kernel::Occupancy::Full => full = true, - kernel::Occupancy::Empty => {} - } - } - full == (self.op == Operation::Join) - } -} - -/// The outward normal (away from the profile) at parameter `t` of a segment of a -/// counterclockwise loop: the tangent turned clockwise. -fn outward(s: &solidcraft_geom::Seg2, t: f64) -> Option { - use solidcraft_geom::Seg2; - match *s { - Seg2::Line { a, b } => (b - a).normalized().map(|d| Vec2::new(d.y, -d.x)), - Seg2::Arc { start, sweep, .. } => Some(Vec2::from_angle(start + sweep * t) * sweep.signum()), - _ => None, - } -} - -/// A counterclockwise loop of lines and arcs, each moved out by `by` where `grow` says so: a -/// line moves out and meets its neighbours again, an arc keeps its centre and changes its -/// radius. `None` when an edge would turn round (too short for the move), edges in one line -/// would part, a segment would leave a tangent neighbour behind, or an arc would move at a -/// sharp corner. -fn offset_segs(segs: &[solidcraft_geom::Seg2], grow: &[bool], by: f64) -> Option> { - use solidcraft_geom::Seg2; - let n = segs.len(); - let tangent = |a: &Seg2, b: &Seg2| a.end_tangent().cross(b.start_tangent()).abs() < 1e-6 && a.end_tangent().dot(b.start_tangent()) > 0.0; - let step = |g: bool| if g { by } else { 0.0 }; - // Where segment `i` starts once moved: the corner of it and the one before. - let mut starts = Vec::with_capacity(n); - for i in 0..n { - let (prev, cur, g0, g1) = (segs.get((i + n - 1) % n)?, segs.get(i)?, *grow.get((i + n - 1) % n)?, *grow.get(i)?); - let corner = cur.start(); - if !g0 && !g1 { - starts.push(corner); - } else if tangent(prev, cur) { - // Moved together, a tangent joint moves along the common normal and stays tangent. - if g0 != g1 { - return None; - } - starts.push(corner + outward(cur, 0.0)? * by); - } else { - let (Seg2::Line { a: a0, b: b0 }, Seg2::Line { a: a1, b: b1 }) = (*prev, *cur) else { return None }; - let (d0, d1) = ((b0 - a0).normalized()?, (b1 - a1).normalized()?); - let (p0, p1) = (a0 + Vec2::new(d0.y, -d0.x) * step(g0), a1 + Vec2::new(d1.y, -d1.x) * step(g1)); - let den = d0.cross(d1); - if den.abs() >= 1e-12 { - starts.push(p0 + d0 * ((p1 - p0).cross(d1) / den)); - } else if g0 == g1 { - starts.push(p1); - } else { - return None; - } - } - } - let mut out = Vec::with_capacity(n); - for (i, seg) in segs.iter().enumerate() { - let (a, b, g) = (*starts.get(i)?, *starts.get((i + 1) % n)?, *grow.get(i)?); - out.push(match *seg { - Seg2::Line { a: a0, b: b0 } if (b - a).dot(b0 - a0) > 0.0 => Seg2::Line { a, b }, - Seg2::Arc { center, radius, start, sweep } if radius + step(g) * sweep.signum() > 0.0 => { - Seg2::Arc { center, radius: radius + step(g) * sweep.signum(), start, sweep } - } - _ => return None, - }); - } - Some(out) -} - -/// Grow profile edges that lie on a face of a body away from the profile, by a small amount, -/// so that the boolean meets no coincident face there. `probe` maps a sketch point to the -/// world points where the tool would be (along the extrude, around the revolve): an edge with -/// material on one side and room on the other at three points along it may grow. It grows -/// only where `gains` finds the whole strip it would add (triangles in the sketch) harmless, -/// asked a quarter wider than it grows, so that the moved side comes near nothing either: -/// three points miss the walls at the edge's ends, a neighbour across a gap, or a wall thinner -/// than the step. Elsewhere the edge stays where it was drawn. Loops of lines and arcs are -/// adjusted: a line moves out, an arc keeps its centre and changes its radius (a rounded corner -/// of a face cut whole, #1275); an arc's strip, and a line's where it meets one, is asked from -/// a little off the round face the arc lies on (see [`Surroundings`]'s `round`). Edges in one -/// line move together or not at all; arcs move only where both of their ends meet tangent -/// neighbours that move with them, otherwise the loop is left as it is. -fn grow_profile_for_coplanar(sur: &Surroundings, r: &Region2, probe: &dyn Fn(Vec2) -> Vec, gains: &dyn Fn(&[[Vec2; 3]]) -> bool) -> Region2 { - use solidcraft_geom::Seg2; - let delta = (sur.size * 0.005).max(1e-3); - let lp = r.outer.ccw(); - let segs = &lp.segs; - if segs.is_empty() || !segs.iter().all(|s| matches!(s, Seg2::Line { .. } | Seg2::Arc { .. })) { - return r.clone(); - } - let n = segs.len(); - // Many probes on one mesh each: indexed, the same answers as `Mesh::contains`. - let inside: Vec<_> = sur.bodies.iter().map(|(_, m, _)| m.inside_index()).collect(); - let inside_any = |p: Vec3| inside.iter().any(|m| m.contains(p)); - let want_outer = sur.op == Operation::Join; - let mut grow: Vec = segs - .iter() - .map(|seg| { - if let Seg2::Arc { radius, sweep, .. } = *seg - && sweep < 0.0 - && radius <= 2.0 * delta - { - // A concave arc too small to shrink by the step. - return false; - } - // Is the edge on a body face? Material on exactly one side of it. - let mids: Vec<(Vec2, Vec2)> = [0.25, 0.5, 0.75].iter().filter_map(|t| Some((seg.point_at(*t), outward(seg, *t)?))).collect(); - if mids.len() < 3 { - return false; - } - let side = |k: f64| mids.iter().flat_map(|(m, out)| probe(*m + *out * (delta * k))).map(&inside_any).collect::>(); - let (outer, inner) = (side(0.5), side(-0.5)); - let on_face = outer.iter().all(|x| *x == want_outer) && inner.iter().any(|x| *x != want_outer); - on_face && side(1.0).iter().all(|x| *x == want_outer) - }) - .collect(); - let in_line = |i: usize| match (segs.get(i % n), segs.get((i + 1) % n)) { - (Some(Seg2::Line { a: a0, b: b0 }), Some(Seg2::Line { a: a1, b: b1 })) => { - matches!(((*b0 - *a0).normalized(), (*b1 - *a1).normalized()), (Some(d0), Some(d1)) if d0.cross(d1).abs() < 1e-12) - } - _ => false, - }; - let round = |k: usize| matches!(segs.get(k % n), Some(Seg2::Arc { .. })); - // What segment `i` gains moving out to `moved`, as triangles in the sketch; `None` when - // nothing of it can be asked. - let strip = |i: usize, seg: &Seg2, moved: &Seg2| -> Option> { - match (*seg, *moved) { - (Seg2::Line { a, b }, Seg2::Line { a: a2, b: b2 }) => { - // Its ends drawn back from the round faces of arcs it runs into. - let d = (b - a).normalized()?; - let s0 = if round(i + n - 1) { sur.round } else { 0.0 }; - let s1 = if round(i + 1) { sur.round } else { 0.0 }; - if (b - a).len() <= s0 + s1 { - return None; - } - let (a, a2, b, b2) = (a + d * s0, a2 + d * s0, b - d * s1, b2 - d * s1); - Some(vec![[a, b, b2], [a, b2, a2]]) - } - (Seg2::Arc { center, radius, start, sweep }, Seg2::Arc { radius: far, .. }) => { - // From `round` off the face out to the moved arc, in pieces whose chords stand off - // the circles by less than `round`: on circles drawn round those circles' chords - // where the arc is convex (the chords then stay off the face and reach past the - // moved arc), on the circles themselves where it is concave. - let near = radius + sur.round * sweep.signum(); - let steps = ((sweep.abs() / (8.0 * sur.round / radius.max(far)).sqrt()).ceil() as usize).clamp(1, 256); - let scale = if sweep > 0.0 { 1.0 / (sweep.abs() / steps as f64 / 2.0).cos() } else { 1.0 }; - let at = |k: usize, rad: f64| center + Vec2::from_angle(start + sweep * k as f64 / steps as f64) * (rad * scale); - Some((0..steps).flat_map(|k| [[at(k, near), at(k + 1, near), at(k + 1, far)], [at(k, near), at(k + 1, far), at(k, far)]]).collect()) - } - _ => None, - } - }; - for _ in 0..=n { - // Edges in one line move together or not at all. - while let Some(i) = (0..n).find(|&i| grow.get(i) != grow.get((i + 1) % n) && in_line(i)) { - grow.iter_mut().enumerate().filter(|(k, _)| *k == i || *k == (i + 1) % n).for_each(|(_, g)| *g = false); - } - if !grow.contains(&true) { - return r.clone(); - } - let Some(reach) = offset_segs(segs, &grow, delta * 1.25) else { return r.clone() }; - let mut dropped = false; - for (i, (seg, moved)) in segs.iter().zip(&reach).enumerate() { - if grow.get(i) == Some(&true) - && !strip(i, seg, moved).is_some_and(|pieces| gains(&pieces)) - && let Some(g) = grow.get_mut(i) - { - *g = false; - dropped = true; - } - } - if !dropped { - return match offset_segs(segs, &grow, delta) { - Some(segs) => Region2 { outer: solidcraft_geom::Loop2 { segs }, holes: r.holes.clone() }, - None => r.clone(), - }; - } - } - r.clone() -} - -/// Booleans struggle with coincident faces (a cut starting on the face it cuts, a boss -/// starting on the face it joins). Extending the tool past such an end changes nothing when the -/// space beyond is empty (cut) or already material (join), so do exactly that. Only an end -/// that lies on a body face parallel to it moves, by less than half the way to the next such -/// face level, and only when the whole slab it gains (asked a quarter further than it moves) -/// is harmless on the bodies' faces (see [`Surroundings::harmless`]): sample points miss a rib -/// beyond the end, a thin floor between a recess above and a ring pocket below, or a hole or a -/// gap behind it. -fn extend_for_coplanar(sur: &Surroundings, plane: &Plane, r: &Region2, lo: f64, hi: f64) -> (f64, f64) { - let size = sur.size; - let delta = (size * 0.01).max(1e-3).min((hi - lo).abs().max(1e-3)); - let samples = region_samples(r); - let n = plane.normal(); - // Many probes on one mesh each: indexed, the same answers as `Mesh::contains`. - let inside: Vec<_> = sur.bodies.iter().map(|(_, m, _)| m.inside_index()).collect(); - let inside_any = |p: Vec3| inside.iter().any(|m| m.contains(p)); - // Heights of the bodies' faces parallel to the profile plane. - let tol = (size * 1e-7).max(1e-9); - let levels: Vec = sur - .bodies - .iter() - .map(|(_, m, _)| m) - .flat_map(|m| { - m.triangles.iter().filter_map(|t| { - let [a, b, c] = m.tri(t)?; - let normal = (b - a).cross(c - a).normalized()?; - (normal.dot(n).abs() > 1.0 - 1e-9).then(|| (a - plane.origin).dot(n)) - }) - }) - .collect(); - // How far the end at `h` may move in `dir`: zero unless a face lies on it, then short of - // half the gap to the next face level beyond it. - let room = |h: f64, dir: f64| { - if !levels.iter().any(|z| (z - h).abs() < tol) { - return 0.0; - } - let gap = levels.iter().map(|z| (z - h) * dir).filter(|g| *g > tol).fold(f64::INFINITY, f64::min); - delta.min(gap * 0.5) - }; - // The profile's triangles; curved sides stand off their chords by up to `chord`. - let chord = (size * 2e-4).max(1e-6); - let straight = std::iter::once(&r.outer).chain(&r.holes).flat_map(|l| &l.segs).all(|s| matches!(s, solidcraft_geom::Seg2::Line { .. })); - let ok_beyond = |h: f64, dir: f64, step: f64| { - let sampled = samples.iter().all(|s| { - let base = plane.to_world(*s); - [0.5, 1.0].iter().all(|k| inside_any(base + n * (h + dir * step * k)) == (sur.op == Operation::Join)) - }); - if !sampled { - return false; - } - let pieces = r.triangulate(chord); - // Triangles that leave part of a straight profile uncovered leave it unasked. - let covered: f64 = pieces.iter().map(|[a, b, c]| (*b - *a).cross(*c - *a).abs() * 0.5).sum(); - if pieces.is_empty() || (straight && (covered - r.area()).abs() > 1e-7 * r.area()) { - return false; - } - let (h0, h1) = if dir > 0.0 { (h + sur.skin, h + step * 1.25) } else { (h - step * 1.25, h - sur.skin) }; - sur.harmless(plane, &pieces, if straight { -sur.skin } else { 2.0 * chord }, h0, h1) - }; - let (down, up) = (room(lo, -1.0), room(hi, 1.0)); - let lo2 = if down > tol && ok_beyond(lo, -1.0, down) { lo - down } else { lo }; - let hi2 = if up > tol && ok_beyond(hi, 1.0, up) { hi + up } else { hi }; - (lo2, hi2) -} - -/// Remove ends of a join tool already wholly inside its targets. A tab extending -/// a rib otherwise shares the rib's side faces through its buried portion; on a -/// chamfered base those coincident faces can defeat every boolean retry (#2059). -/// Only straight profiles are trimmed, after checking the entire swept material -/// against the targets' faces, with the same clearance used when extending ends. -fn trim_embedded_join_ends(sur: &Surroundings, plane: &Plane, r: &Region2, lo: f64, hi: f64) -> (f64, f64) { - if sur.op != Operation::Join - || !std::iter::once(&r.outer).chain(&r.holes).flat_map(|l| &l.segs).all(|s| matches!(s, solidcraft_geom::Seg2::Line { .. })) - { - return (lo, hi); - } - let pieces = r.triangulate(1e-6); - let covered: f64 = pieces.iter().map(|[a, b, c]| (*b - *a).cross(*c - *a).abs() * 0.5).sum(); - if pieces.is_empty() || (covered - r.area()).abs() > 1e-7 * r.area() { - return (lo, hi); - } - let n = plane.normal(); - let mut levels: Vec = sur - .bodies - .iter() - .flat_map(|(_, mesh, _)| { - mesh.triangles.iter().filter_map(|t| { - let [a, b, c] = mesh.tri(t)?; - let normal = (b - a).cross(c - a).normalized()?; - (normal.dot(n).abs() > 1.0 - 1e-9).then(|| (a - plane.origin).dot(n)) - }) - }) - .filter(|h| *h > lo + sur.skin && *h < hi - sur.skin) - .collect(); - levels.sort_by(f64::total_cmp); - levels.dedup_by(|a, b| (*a - *b).abs() < sur.skin); - if levels.len() > 256 { - return (lo, hi); - } - let start = levels.iter().rev().copied().find(|h| sur.harmless(plane, &pieces, -sur.skin, lo + sur.skin, h - sur.skin)).unwrap_or(lo); - let end = - levels.iter().copied().find(|h| *h > start + sur.skin && sur.harmless(plane, &pieces, -sur.skin, h + sur.skin, hi - sur.skin)).unwrap_or(hi); - (start, end) -} - -/// Whether a tapered tool, run on by `depth` behind the plane it starts in (`dir` the way it -/// extrudes), stays where running on changes nothing: in the targets for a join, out of them for -/// a cut. Its sides keep their slope, so the section there is the profile grown by up to `widen` -/// all round; that grown outline is probed at two depths. -#[allow(clippy::too_many_arguments)] -fn taper_run_on_fits(st: &ModelState, start: &Plane, dir: Vec3, r: &Region2, depth: f64, widen: f64, op: Operation, targets: &[String]) -> bool { - const MAX_SEGMENTS: usize = 2_000; - let meshes: Vec> = st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name)).map(|b| b.mesh()).collect(); - if meshes.is_empty() || !depth.is_finite() || !widen.is_finite() { - return false; - } - let want = op == Operation::Join; - // Each loop counterclockwise with the side away from the material: right of the outer loop, - // left of a hole. - let loops: Vec<(solidcraft_geom::Loop2, f64)> = std::iter::once((r.outer.ccw(), 1.0)).chain(r.holes.iter().map(|h| (h.ccw(), -1.0))).collect(); - let count: usize = loops.iter().map(|(l, _)| l.segs.len()).sum(); - if count > MAX_SEGMENTS { - return false; - } - loops.iter().all(|(lp, side)| { - lp.segs.iter().all(|seg| { - [0.0, 0.25, 0.5, 0.75].iter().all(|t| { - let Some(d) = seg.derivative(*t).normalized() else { return true }; - let out = Vec2::new(d.y, -d.x) * *side; - [0.5, 1.0].iter().all(|k| { - let p = start.to_world(seg.point_at(*t) + out * (widen * k)) - dir * (depth * k); - meshes.iter().any(|m| m.contains(p)) == want - }) - }) - }) - }) -} - -/// How high (mm) a tapered tool's sides stand straight where it starts on a face it can't run -/// on into. -const TAPER_FOOT: f64 = 0.01; - -/// Whether a face of the targets (all bodies when none are named) lies in the plane at height -/// `h` along `plane`'s normal. -fn face_level_at(st: &ModelState, plane: &Plane, h: f64, targets: &[String]) -> bool { - let n = plane.normal(); - st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name)).any(|b| { - let m = b.mesh(); - let tol = (b.body.size() * 1e-7).max(1e-9); - m.triangles.iter().any(|t| { - m.tri(t).is_some_and(|[a, b, c]| { - (b - a).cross(c - a).normalized().is_some_and(|normal| normal.dot(n).abs() > 1.0 - 1e-9) - && ((a - plane.origin).dot(n) - h).abs() < tol - }) - }) - }) -} - /// The body a face-based feature applies to: by name, or the one whose surface is nearest the /// first point. fn body_at(st: &ModelState, body: &Option, points: &[Vec3]) -> Result { @@ -3808,8 +3544,9 @@ fn body_at(st: &ModelState, body: &Option, points: &[Vec3]) -> /// A hole stays on its face when the model changes: a position now inside a body moves back /// against the drilling direction to the surface, one now above it moves down onto it. Only the -/// bodies in `scope` count (every body when it is empty, see [`hole_scope`]). -fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 { +/// bodies in `scope` count (every body when it is empty, see [`hole_scope`]). Edit Hole seeds from +/// this point so the dialog's face pick matches where evaluation drills (#10689). +pub fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 { let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max); let eps = size * 1e-6; let mut best: Option = None; @@ -3857,6 +3594,18 @@ fn faces_through(st: &ModelState, p: Vec3, reach: f64) -> Vec<(f64, Vec3, Option ((v - axis * v.dot(axis)).normalized(), None) } Some(kernel::FaceSurface::Sphere { center, .. }) => ((p - center).normalized(), None), + // Square to the line through the apex, not the nearest facet's normal (#10698). + Some(kernel::FaceSurface::Cone { apex, axis, half_angle }) => { + let v = p - apex; + let out = (v - axis * v.dot(axis)).normalized(); + (out.and_then(|u| (u * half_angle.cos() - axis * half_angle.sin()).normalized()), None) + } + // Away from the nearest point of the ring the tube goes round. + Some(kernel::FaceSurface::Torus { center, axis, major, .. }) => { + let v = p - center; + let ring = (v - axis * v.dot(axis)).normalized().map(|u| center + u * major); + (ring.and_then(|q| (p - q).normalized()), None) + } _ => (None, None), }; let n = match exact { @@ -3955,7 +3704,8 @@ pub fn edge_refs(st: &ModelState, body: &Option, pts: &[Vec3]) } /// Persistent names of the edges picked at `pts`, each on the body it lies on (see -/// [`picked_bodies`]). +/// [`picked_bodies`]): of the edge a blend takes at each pick (at a vertex where a seam meets a +/// rim, the rim), else of the nearest edge. pub fn edge_names_for(st: &ModelState, body: &Option, pts: &[Vec3]) -> Vec { let Some(on) = picked_bodies(st, body, pts) else { return Vec::new() }; let mut out = vec![String::new(); pts.len()]; @@ -3969,7 +3719,14 @@ pub fn edge_names_for(st: &ModelState, body: &Option, pts: &[Ve // The body's names are worked out once for all its picks. let idx: Vec = on.iter().enumerate().filter(|(_, t)| **t == ti).map(|(i, _)| i).collect(); let at: Vec = idx.iter().filter_map(|i| pts.get(*i).copied()).collect(); - for (i, n) in idx.into_iter().zip(crate::naming::edge_names_at(b, &at)) { + let names = match kernel::blend_edges(&b.body, &at) { + Ok(edges) => { + let all = crate::naming::edge_names(b); + edges.iter().map(|e| all.get(*e).cloned().unwrap_or_default()).collect() + } + Err(_) => crate::naming::edge_names_at(b, &at), + }; + for (i, n) in idx.into_iter().zip(names) { if let Some(slot) = out.get_mut(i) { *slot = n; } @@ -4005,7 +3762,7 @@ fn resolve_edges(b: &Body, pts: &[Vec3], refs: &[EdgeRef], warning: &mut Option< let edges = b.edges((size * 1e-3).max(1e-3))?; let tight = (size * 2e-3).max(1e-3); let dist = |p: Vec3, e: &kernel::EdgeInfo| e.points.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min); - let now = b.tessellate((size * 1e-2).max(1e-2)).map(|m| m.bounds()).ok(); + let now = b.mesh(&solidcraft_kernel::MeshTolerance::chord((size * 1e-2).max(1e-2))).map(|m| m.bounds()).ok(); let (mut out, mut moved, mut lost) = (Vec::new(), 0, 0); for (i, p) in pts.iter().enumerate() { let on = edges.iter().any(|e| dist(*p, e) <= tight); @@ -4058,7 +3815,7 @@ fn resolve_edges(b: &Body, pts: &[Vec3], refs: &[EdgeRef], warning: &mut Option< } /// The body a fillet/chamfer applies to: by name, or the one closest to the first edge point. -fn blend_target(state: &ModelState, body: &Option, edges: &[Vec3]) -> Result { +pub fn blend_target(state: &ModelState, body: &Option, edges: &[Vec3]) -> Result { if let Some(n) = body { return state.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`"))); } @@ -4103,18 +3860,18 @@ fn trusted_edge_name(f: &Feature, i: usize, p: Vec3) -> Option<&str> { } /// The body (index) an edge name finds an edge on, when one does: the one where the edge still -/// runs through the pick `p`, else where the name is one edge (not split), else the nearest. +/// runs through the pick `p`, else the nearest. fn named_body(st: &ModelState, name: &str, p: Vec3) -> Option { // Names start with the feature that made the face: only bodies with such a face can hold it. let bare = crate::naming::legacy_name(name).unwrap_or(name); let token = bare.find(':').map(|k| &bare[..=k]); - let mut best: Option<(usize, (bool, bool, f64))> = None; + let mut best: Option<(usize, (bool, f64))> = None; for (i, b) in st.bodies.iter().enumerate() { if b.body.is_mesh() || token.is_some_and(|t| !crate::naming::face_names(b).iter().any(|n| n.contains(t))) { continue; } let Ok(hit) = crate::naming::locate_edge(b, name, p) else { continue }; - let score = (hit.on_point, !hit.split, -hit.point.dist(p)); + let score = (hit.on_point, -hit.point.dist(p)); if best.as_ref().is_none_or(|(_, s)| score.partial_cmp(s).is_some_and(|o| o.is_gt())) { best = Some((i, score)); } @@ -4186,8 +3943,9 @@ fn blend_bodies(st: &ModelState, f: &Feature, body: &Option, pt Ok(out) } -/// The edges `idx` of blend `f` found on body `mb`: by name first; a name that is gone falls back -/// to the point, with a warning. +/// The edges `idx` of blend `f` found on body `mb`: by name, where the edge was stored with one. +/// A name that no longer finds exactly its edge fails the blend, asking for the edge to be picked +/// again; so does a name a build stored for the wrong body (see `trusted_edge_name`). fn blend_edges_on(mb: &ModelBody, f: &Feature, edges: &[crate::Position], idx: &[usize], warning: &mut Option) -> Result> { let pick = |i: usize| edges.get(i).map(|p| p.0).unwrap_or(Vec3::ZERO); if !f.edge_names.iter().any(|n| !n.is_empty()) { @@ -4198,51 +3956,34 @@ fn blend_edges_on(mb: &ModelBody, f: &Feature, edges: &[crate::Position], idx: & let (mut out, mut notes) = (Vec::new(), Vec::new()); for &i in idx { let p = pick(i); - let stored = f.edge_names.get(i).filter(|n| !n.is_empty()); - let trusted = trusted_edge_name(f, i, p); - // A name recorded on another body (see `trusted_edge_name`): the pick alone. - if stored.is_some() && trusted.is_none() { + let Some(stored) = f.edge_names.get(i).filter(|n| !n.is_empty()) else { + // An edge picked without a name: by its point. A pick on the axis of a round must not + // fall through to the tangency seam (#775). let mut w = None; - match resolve_edges(&mb.body, &[p], &[], &mut w) { - Ok(q) => out.extend(q), - Err(_) => notes.push("an edge reference was not found at its point and was skipped".to_string()), + let refs: Vec = f.edge_refs.get(i).cloned().into_iter().collect(); + let skipped = "edge `?` no longer exists and was skipped"; + if pick_lies_on_a_round_axis(&mb.body, p) { + notes.push(skipped.into()); + } else if let Ok(q) = resolve_edges(&mb.body, &[p], &refs, &mut w) { + out.extend(q); + notes.push("an edge reference without a name was found by its point".into()); + } else { + notes.push(skipped.into()); } - notes.extend(w); continue; + }; + let hit = + trusted_edge_name(f, i, p).and_then(|n| crate::naming::locate_edge(mb, n, p).ok()).ok_or_else(|| DocError::reselect(stored.as_str()))?; + if let Some(note) = hit.note(stored) { + notes.push(note); } - match trusted.map(|n| (n, crate::naming::locate_edge(mb, n, p))) { - Some((n, Ok(hit))) => { - if let Some(note) = hit.note(n) { - notes.push(note); - } - // The body changed since the pick: the pick may now sit at an end of the edge. - let moved = f.edge_refs.get(i).is_some_and(|r| { - let now = mb.mesh().bounds(); - let tight = (mb.body.size() * 2e-3).max(1e-3); - now.min.dist(r.min) > tight || now.max.dist(r.max) > tight - }); - out.push(if moved { off_the_ends(mb, hit.edge, hit.point) } else { hit.point }); - } - Some((_, Err(_))) | None => { - let mut w = None; - let refs: Vec = f.edge_refs.get(i).cloned().into_iter().collect(); - let skipped = format!("edge `{}` no longer exists and was skipped", stored.map(String::as_str).unwrap_or("?")); - // The name is gone. A pick on the axis of a round must not fall through to the - // tangency seam (#775). A sharp edge that moved still resolves from the point, - // which an edit relies on. - if pick_lies_on_a_round_axis(&mb.body, p) { - notes.push(skipped); - } else if let Ok(q) = resolve_edges(&mb.body, &[p], &refs, &mut w) { - out.extend(q); - notes.push(match stored { - Some(n) => format!("edge `{n}` no longer exists; using the edge at the picked point"), - None => "an edge reference without a name was found by its point".into(), - }); - } else { - notes.push(skipped); - } - } - } + // The body changed since the pick: the pick may now sit at an end of the edge. + let moved = f.edge_refs.get(i).is_some_and(|r| { + let now = mb.mesh().bounds(); + let tight = (mb.body.size() * 2e-3).max(1e-3); + now.min.dist(r.min) > tight || now.max.dist(r.max) > tight + }); + out.push(if moved { off_the_ends(mb, hit.edge, hit.point) } else { hit.point }); } if out.is_empty() { let why = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join("; ")) }; @@ -4281,6 +4022,19 @@ fn off_the_ends(mb: &ModelBody, edge: usize, p: Vec3) -> Vec3 { /// The edges a tapered fillet tapered (a point on each, with its taper). type Tapered = Vec<(Vec3, kernel::Taper)>; +/// A blend's refusal when the feature blended the picked edges' tangent chains too (tangent +/// propagation, the default), saying so and how to blend the picked edges alone. +fn with_propagation_hint(e: DocError) -> DocError { + const HINT: &str = " (tangent propagation blended the picked edges' tangent chain with them; with it off, tangent_chain: false, only the picked edges are blended)"; + match e { + DocError::Kernel(kernel::KernelError::TooLarge(m)) => DocError::Kernel(kernel::KernelError::TooLarge(m + HINT)), + DocError::Kernel(kernel::KernelError::Invalid(m)) => DocError::Kernel(kernel::KernelError::Invalid(m + HINT)), + DocError::Kernel(kernel::KernelError::Failed(m)) => DocError::Kernel(kernel::KernelError::Failed(m + HINT)), + DocError::Invalid(m) => DocError::Invalid(m + HINT), + e => e, + } +} + /// Body `mb` with blend `f` applied at `edges` (radius or distance `r`), the radii a fitted fillet /// used (when it reduced any) and the edges it tapered. fn blend_body( @@ -4293,10 +4047,33 @@ fn blend_body( ) -> Result<(Traced, Option>, Tapered)> { let input = mb.traced(); let (mut used, mut tapered) = (None, Vec::new()); + if let FeatureKind::Fillet { turn: crate::FilletTurn::Swept, style, fit, corner, setbacks, .. } = &f.kind + && (!style.is_constant() || *fit == crate::FilletFit::Taper || !corner.is_rolling() || !setbacks.is_empty()) + { + return Err(DocError::Invalid(crate::SWEPT_TAKES.into())); + } // The blended body, and the lineage of what the last blend started from. let (nb, from) = match &f.kind { - FeatureKind::Fillet { corner: crate::FilletCorner::G2, .. } => (kernel::fillet_g2_corners(&mb.body, edges, r)?, input), - FeatureKind::Fillet { style: crate::FilletStyle::Curvature, .. } => (kernel::fillet_g2(&mb.body, edges, r)?, input), + // A curvature-continuous fillet's corners are G2 patches, whatever `corner` says: SMLib's + // own corner patch is only tangent to its rounds. + FeatureKind::Fillet { style: crate::FilletStyle::Curvature, setbacks, .. } => { + let mut corners = Vec::with_capacity(setbacks.len()); + for c in setbacks { + corners.push((c.vertex.0, val(vals, &c.distance, Kind::Length)?)); + } + (kernel::fillet_g2_with_g2_corners(&mb.body, edges, r, &corners)?, input) + } + FeatureKind::Fillet { corner, setbacks, .. } if matches!(corner, crate::FilletCorner::G2) || !setbacks.is_empty() => { + // Each setback: its corner's vertex and its distance. + let mut corners = Vec::with_capacity(setbacks.len()); + for c in setbacks { + corners.push((c.vertex.0, val(vals, &c.distance, Kind::Length)?)); + } + match corner { + crate::FilletCorner::G2 => (kernel::fillet_g2_corners(&mb.body, edges, r, &corners)?, input), + crate::FilletCorner::Rolling => (kernel::fillet_setback(&mb.body, edges, r, &corners)?, input), + } + } FeatureKind::Fillet { style: crate::FilletStyle::Chord, .. } => (kernel::fillet_chord(&mb.body, edges, r)?, input), FeatureKind::Fillet { style: crate::FilletStyle::Variable { radius2, start, mid, smooth }, .. } => { let r2 = val(vals, radius2, Kind::Length)?; @@ -4322,11 +4099,14 @@ fn blend_body( tapered = edges.iter().copied().zip(tapers).filter_map(|(p, t)| Some((p, t?))).collect(); (b, input) } - FeatureKind::Fillet { fit, .. } => { - let (b, u) = fillet_fitted(&mb.body, edges, r, *fit)?; + FeatureKind::Fillet { fit, turn, .. } => { + let (b, u, gone) = fillet_fitted(&mb.body, edges, r, *fit, turn.kernel())?; if let Some(u) = &u { append_warning(warning, reduced_note(u, r)); } + if !gone.is_empty() { + append_warning(warning, removed_note(&gone)); + } used = u; (b, input) } @@ -4389,11 +4169,12 @@ pub(crate) fn revolve_axis( } /// The model a revolve axis is found in: what construction geometry of component `comp` is built -/// on when the axis is an edge or face of it (only then is it worth placing). -pub(super) fn axis_state<'a>(doc: &Document, st: &'a ModelState, comp: u64, axis: &AxisRef) -> std::borrow::Cow<'a, ModelState> { +/// on when the axis is an edge or face of it (only then is it worth placing); a model that cannot +/// be placed is the error. +pub(super) fn axis_state<'a>(doc: &Document, st: &'a ModelState, comp: u64, axis: &AxisRef) -> Result> { match axis { AxisRef::Model { .. } => construction_state(doc, st, comp), - _ => std::borrow::Cow::Borrowed(st), + _ => Ok(std::borrow::Cow::Borrowed(st)), } } @@ -4508,7 +4289,7 @@ fn hole_spots(vals: &BTreeMap, st: &ModelState, f: &Feature) -> R _ => { let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; let at = hole_on_surface(st, single_hole_position(vals, st, position, at, points)?, dir, &[]); - let at = with_references(vals, st, f, at, dir)?; + let at = with_references(vals, st, f, at, dir, true)?; let dir = hole_dir_into_face(st, at, dir); return Ok((vec![hole_on_surface(st, at, dir, &[])], dir)); } @@ -4556,7 +4337,7 @@ fn hole_spots_raw(vals: &BTreeMap, st: &ModelState, f: &Feature) _ => { let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; let p = single_hole_position(vals, st, position, at, points)?; - let p = if hole_references(f).is_empty() { p } else { with_references(vals, st, f, hole_on_surface(st, p, dir, &[]), dir)? }; + let p = if hole_references(f).is_empty() { p } else { with_references(vals, st, f, hole_on_surface(st, p, dir, &[]), dir, false)? }; Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir, &[]), dir))) } } @@ -4590,13 +4371,15 @@ fn hole_references(f: &Feature) -> &[crate::HoleReference] { /// plane of the flat face at its base, square to its axis. fn cylinder_base(vals: &BTreeMap, st: &ModelState, f: &Feature, base: &crate::PointExpr, axis: Vec3) -> Result { let at = point(vals, base)?; - with_references(vals, st, f, at, -axis) + with_references(vals, st, f, at, -axis, true) } /// Where a Single hole (or a cylinder) with reference edges (#37) is placed: at its distances /// from the edges' lines, in the plane of the face at `at` (on the surface), the edges found by -/// their names, else their points. A feature without reference edges stays at `at`. -fn with_references(vals: &BTreeMap, st: &ModelState, f: &Feature, at: Vec3, dir: Vec3) -> Result { +/// their names, else their points. A feature without reference edges stays at `at`. With +/// `on_face` the centre must lie on that face; a pattern or mirror replaying a hole that is +/// already drilled finds its centre in the opening and doesn't ask (#8055). +fn with_references(vals: &BTreeMap, st: &ModelState, f: &Feature, at: Vec3, dir: Vec3, on_face: bool) -> Result { let references = hole_references(f); if references.is_empty() { return Ok(at); @@ -4608,7 +4391,7 @@ fn with_references(vals: &BTreeMap, st: &ModelState, f: &Feature, let edges: Vec<(Vec3, Option<&str>)> = references.iter().enumerate().map(|(i, r)| (r.edge.0, f.edge_names.get(i).map(String::as_str))).collect(); let frame = crate::hole_reference::reference_frame(st, at, dir, &edges, false)?; let centre = frame.place(at, &distances)?; - if !crate::hole_reference::on_reference_face(st, &frame, centre) { + if on_face && !crate::hole_reference::on_reference_face(st, &frame, centre) { return Err(DocError::Invalid("the reference distances put the hole's centre off its face".into())); } Ok(centre) @@ -4633,6 +4416,16 @@ fn parallel_tapped_wall(st: &ModelState, entry: Vec3, inward: Vec3, radius: f64) let tol = (radius * 1e-6).max(1e-6); let mut best: Option<(f64, Vec3)> = None; for body in &st.bodies { + // A wall found lies on the line through `entry` along `inward`, give or take its radius + // (and the slant its axis may have off `inward` over the body's distance), and its + // faces lie in the body's exact box: a body whose box that line misses by more holds + // none, and its faces are not read one by one (#10227). + let far = more::exact_box(&body.body).map_or(f64::INFINITY, |b| (b.min - entry).len().max((b.max - entry).len()) + b.diagonal()); + if far.is_finite() && more::line_beyond_reach(body, entry, inward, radius * 1.01 + tol + 1e-3 + 2e-4 * far) { + continue; + } + #[cfg(test)] + cost_tests::count(|c| c.tapped_wall += 1); let mesh = body.mesh(); for face in 0..body.body.face_count() { let Some(c) = kernel::cylinder_face(&body.body, &mesh, face) else { continue }; @@ -4693,15 +4486,15 @@ fn sheet_hole_cut( // Many plain drills along one axis (a hole on each of a pattern's points): all in one pass. let prisms: Option> = tools.iter().map(|(_, prism)| *prism).collect(); if let Some(prisms) = prisms { - match more::sheet_drill_cuts(f, st, &prisms, &mut parted) { - Ok(Some(done)) => { + match more::sheet_drill_cuts(f, st, &prisms, &mut parted)? { + Some(done) => { if let Some(note) = parted { append_warning(warning, note); } return Ok(done); } - // Not all of them that way, or refused at once: one by one, from the model as it was. - Ok(None) | Err(_) => { + // Not all of them that way: one by one, from the model as it was. + None => { (st.sheets, st.bodies) = saved.clone(); parted = None; } @@ -4709,28 +4502,27 @@ fn sheet_hole_cut( } for (tool, prism) in tools { let tool = &tool.body; + // Square across the panels it meets, a flat cut-out; along them into a rim, a bore. let done = match prism { - Some(prism) => match more::sheet_primitive_cut(f, st, tool, *prism, Operation::Cut, true, &mut parted) { - Ok(done) => done, - // Drilled along a panel (into a rim) the hole is no flat cut-out: a bore of - // that panel, when it stays inside it. - Err(e) => match more::sheet_bore_cut(f, st, *prism)? { - Some(done) => done, - None => return Err(e), - }, + Some(prism) => match more::sheet_drill(f, st, *prism)? { + Some(more::Drill::Across) => more::sheet_primitive_cut(f, st, tool, *prism, Operation::Cut, true, &mut parted)?, + Some(more::Drill::Along) => more::sheet_bore_cut(f, st, *prism)?.unwrap_or_default(), + None => Vec::new(), }, None => Vec::new(), }; - let done = match (done.is_empty(), prism) { - (true, Some(prism)) => more::sheet_bore_cut(f, st, *prism)?.unwrap_or_default(), - _ => done, - }; if done.is_empty() { + // A sheet whose box lies clear of the tool's cannot meet it (#10226). + let reach = more::exact_box(tool); let mut meets = false; for sheet in &st.sheets { - if let Some(mb) = st.body(&sheet.body) - && kernel::boolean(&mb.body, tool, BoolOp::Intersect)?.is_some() - { + let Some(mb) = st.body(&sheet.body) else { continue }; + if more::boxes_apart(&more::exact_box(&mb.body), &reach) { + continue; + } + #[cfg(test)] + cost_tests::count(|c| c.cut += 1); + if kernel::boolean(&mb.body, tool, BoolOp::Intersect)?.is_some() { meets = true; break; } @@ -4767,8 +4559,8 @@ fn hole_tools( } /// The scale a hole's tools are sized by: the largest body the hole's axis meets (#2904), so a -/// large body elsewhere in the model changes neither the tool's reach above the face (and so -/// the countersink's outline) nor its depth. A hole whose axis meets no body is sized by the +/// large body elsewhere in the model changes neither the tool's reach above the face nor its +/// depth. A hole whose axis meets no body is sized by the /// largest body of the model, as before. fn hole_axis_size(st: &ModelState, position: &Vec3, dir: Vec3) -> f64 { let along = |b: &ModelBody| { @@ -4832,7 +4624,7 @@ fn hole_tools_and_prisms( let seam = std::cell::Cell::new(0.0); let disc = |rad: f64| { seam.set(seam.get() + 0.613); - Region2 { outer: solidcraft_geom::Loop2::circle_from(Vec2::ZERO, rad, seam.get()), holes: vec![] } + Region2 { outer: solidcore_record::Loop2::circle_from(Vec2::ZERO, rad, seam.get()), holes: vec![] } }; let cyl = |rad: f64, lo: f64, hi: f64, part: &str| -> Result<(Traced, Option)> { let tool = kernel::extrude(&plane, &[disc(rad)], lo, hi)?.pop().ok_or_else(|| DocError::Invalid("hole tool".into()))?; @@ -4848,8 +4640,13 @@ fn hole_tools_and_prisms( // face, which would lie on the drill point's shoulder (a through hole, as drilled). let at = |h: f64| *position + dir * (-h); let eps = size * 1e-6; - let solid_at = |h: f64| st.bodies.iter().any(|b| b.body.contains(at(h))); - let exits_at_shoulder = solid_at(bottom + eps) && !solid_at(bottom - eps); + // Exact classification against every body: material where one has the point inside, + // air where all have it outside; a point within a body's tolerance of its boundary is + // neither, and the hole is then not taken to exit at its shoulder. + let classes = |h: f64| st.bodies.iter().map(|b| b.body.classify_point(at(h))).collect::, _>>(); + let solid = classes(bottom + eps)?.contains(&kernel::PointClass::Inside); + let air = classes(bottom - eps)?.iter().all(|c| *c == kernel::PointClass::Outside); + let exits_at_shoulder = solid && air; if depth.is_some() && half > 1e-3 && half < std::f64::consts::FRAC_PI_2 && !exits_at_shoulder { // One revolved tool (cylinder with a drill point). let tip = r / half.tan(); @@ -4857,7 +4654,7 @@ fn hole_tools_and_prisms( let side = up.any_perp(); let rp = Plane::new(*position, side, up).ok_or_else(|| DocError::Invalid("hole axis".into()))?; let pts = [Vec2::new(0.0, top), Vec2::new(r, top), Vec2::new(r, bottom), Vec2::new(0.0, bottom - tip)]; - let region = Region2 { outer: solidcraft_geom::Loop2::polygon(&pts), holes: vec![] }; + let region = Region2 { outer: solidcore_record::Loop2::polygon(&pts), holes: vec![] }; return Ok(kernel::revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)? .into_iter() .map(|tool| (crate::lineage::part_tool(tool, "bore"), None)) @@ -4884,12 +4681,21 @@ fn hole_tools_and_prisms( if !(rc > r && half > 1e-3 && half < std::f64::consts::FRAC_PI_2) { return Err(DocError::Invalid("the countersink must be wider than the hole".into())); } - // Cone from above the face to just inside the hole radius, then the hole. - let r_top = rc + top * half.tan(); + // One revolved tool: the cone from its rim on the face to just inside the hole + // radius, and above the face the rim's cylinder, as the bore's own cylinder runs on + // above it. The cone widening on above the face would cut what stands beside the rim + // (#5041). The cone is the profile's first segment (`csink:side:0`). let r_end = r * 0.9; - let len = (r_top - r_end) / half.tan(); - let top_plane = plane.offset(top); - tools.push((crate::lineage::part_tool(kernel::extrude_tapered(&top_plane, &disc(r_top), len, -1.0, -half)?, "csink"), None)); + let len = (rc - r_end) / half.tan(); + let up = -dir; + let rp = Plane::new(*position, up.any_perp(), up).ok_or_else(|| DocError::Invalid("hole axis".into()))?; + let pts = [Vec2::new(rc, 0.0), Vec2::new(r_end, -len), Vec2::new(0.0, -len), Vec2::new(0.0, top), Vec2::new(rc, top)]; + let region = Region2 { outer: solidcore_record::Loop2::polygon(&pts), holes: vec![] }; + tools.extend( + kernel::revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)? + .into_iter() + .map(|tool| (crate::lineage::part_tool(tool, "csink"), None)), + ); tools.extend(bore(tip_angle.as_ref())?); } } @@ -4929,6 +4735,29 @@ pub fn revolve_extent_with_convention( symmetric: bool, to: Option, convention: crate::RevolveConvention, +) -> Result { + let extent = revolve_extent_for_handle(st, plane, regions, (origin, axis), (angle, angle2), symmetric, to, convention)?; + // A solid needs an open sweep inside one full turn. Zero and a turn past 360° keep a + // handle frame (`revolve_extent_for_handle`) and still fail here, with the same message. + if !(extent.sweep.abs() > 1e-9 && extent.sweep.abs() <= std::f64::consts::TAU + 1e-9) { + return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into())); + } + Ok(extent) +} + +/// Where the angle handle sits. A sweep of zero, or past a full turn, builds no solid and +/// [`revolve_extent_with_convention`] refuses it. The boundary is still a point on the circle, +/// and the grab point stays there so the angle can be dragged back into range. +#[allow(clippy::too_many_arguments)] +pub fn revolve_extent_for_handle( + st: &ModelState, + plane: &Plane, + regions: &[Region2], + (origin, axis): (Vec3, Vec3), + (angle, angle2): (f64, Option), + symmetric: bool, + to: Option, + convention: crate::RevolveConvention, ) -> Result { let (start, sweep) = match (to, angle2, symmetric) { (Some(point), _, _) => { @@ -4968,7 +4797,7 @@ pub fn revolve_extent_with_convention( (None, None, true) => (-angle / 2.0, angle), (None, None, false) => (0.0, angle), }; - if !(sweep.is_finite() && start.is_finite() && sweep.abs() > 1e-9 && sweep.abs() <= std::f64::consts::TAU + 1e-9) { + if !(sweep.is_finite() && start.is_finite()) { return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into())); } let points: Vec = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect(); @@ -5001,85 +4830,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))], - thin: None, - }; - 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), None).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), None).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, 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, @@ -5108,8 +4858,13 @@ fn centered_extrude( }; // Fit cap surfaces in their own coordinates. Fitting a distant world-space // wire can tilt an otherwise exact planar cap through numeric cancellation. - // A side drawn in collinear pieces is one face (#1788). - let bodies = kernel::extrude_whole_sides(&Plane::XY, std::slice::from_ref(region), start, end)?; + // A side drawn in collinear pieces is one face (#1788), and so is a side along one ellipse + // or spline, whatever pieces the profile holds it in. + let curves = sketch.map(crate::config::ExactSketchCurves::new); + let one_curve = |s: &solidcore_record::Seg2, t: &solidcore_record::Seg2| { + curves.as_ref().is_some_and(|c| c.find_free_form(s).is_some_and(|id| c.find_free_form(t).is_some_and(|other| other == id))) + }; + let bodies = kernel::extrude_whole_sides(&Plane::XY, std::slice::from_ref(region), start, end, &one_curve)?; if *plane == Plane::XY { return Ok(bodies.into_iter().map(|body| roles.tool(body, None)).collect()); } @@ -5176,6 +4931,7 @@ fn feature_tools_with_constructor( st: &ModelState, constructor: &mut Option, to_body: &mut Option, + warning: &mut Option, ) -> Result> { *to_body = None; let unnamed = |bodies: Vec| -> Vec { bodies.into_iter().map(Traced::unnamed).collect() }; @@ -5203,7 +4959,7 @@ fn feature_tools_with_constructor( // model is seen from there: a target in another, moved component where it is shown. let n = ss.plane.normal(); let tst = - if extent.to.is_some() || extent.from.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; + if extent.to.is_some() || extent.from.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) }; // Through all, and where the tool meets its targets, is measured where they are shown. let shown = targets_as_shown(st, f, &crate::plain(targets))?; let st: &ModelState = &shown; @@ -5211,8 +4967,9 @@ fn feature_tools_with_constructor( let name = |k: usize| f.face_names.get(k).map(String::as_str); let (to_name, from_name) = if extent.to.is_some() { (name(0), name(1)) } else { (None, name(0)) }; let to_face = extent.to.and_then(|p| object_face(&tst, to_name, p.0, Some(n))); - // The body the extent runs to: a Join to it joins that body too (#6424). - *to_body = to_face.and_then(|(bi, _)| tst.bodies.get(bi)).map(|b| b.name.clone()); + // The body the extent runs to: a Join to it joins that body too (#6424), unless the + // design was built before it did (#8151). + *to_body = to_face.filter(|_| !extent.to_body_apart).and_then(|(bi, _)| tst.bodies.get(bi)).map(|b| b.name.clone()); let centre = { let pts: Vec = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect(); let c = pts.iter().fold(Vec2::default(), |a, p| a + *p) * (1.0 / pts.len().max(1) as f64); @@ -5261,73 +5018,25 @@ fn feature_tools_with_constructor( Some(crate::lineage::extrude_cap_role(base)), Some(crate::lineage::extrude_cap_role(if sign < 0.0 { base - len } else { base + len })), ]; - // How far a tool grows past its profile at either end, at most. - let mut growth: f64 = 0.0; - // A face of the targets in the profile's plane (the same for every profile). - let plain_targets: Vec = crate::plain(targets); - let on_face = matches!(operation, Operation::Join | Operation::Cut) && face_level_at(st, &ss.plane, base, &plain_targets); - let surroundings = Surroundings::of(st, *operation, &plain_targets); + // How far a tool grows past its profile, at most: its sides' run over its length. + let growth = len * taper.tan().abs(); + let mut notes = Vec::new(); let tools: Vec = regions .iter() .map(|r| { - // An end on a face of the target runs on into it, as a prism's does: tapered - // sides standing on a face are curved where they meet it (along text, say), - // and the boolean finds no result there. The sides keep their slope, so - // the profile stays the section at the start. let roles = crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone(), thin: thin_roles.as_ref() }; - // A start that is a whole face of the target (a foot under a part's base) is sewn on - // along it, as it lies: run on, the sides would leave the face through its edges. - if on_face - && *operation == Operation::Join - && let Ok(exact) = kernel::extrude_tapered_between(&start_plane, r, 0.0, len, 0.0, sign, taper) - && st - .bodies - .iter() - .filter(|t| targets.is_empty() || targets.iter().any(|x| *x == t.name)) - .any(|t| kernel::can_join_touching_faces(&t.body, &exact)) - { - growth = growth.max(len * taper.tan().abs()); - return Ok(roles.tool(exact, None)); - } - let (lo, hi) = if sign < 0.0 { (base - len, base) } else { (base, base + len) }; - let (l2, h2) = surroundings.as_ref().map_or((lo, hi), |sur| extend_for_coplanar(sur, &ss.plane, r, lo, hi)); - let (mut a, b) = if sign < 0.0 { (base - h2, base - l2) } else { (l2 - base, h2 - base) }; - // A taper that narrows the tool away from the face widens it as it runs on into it, past - // the profile (where the profile is the whole face, out through the body's sides, #1534): - // then it starts on the face instead. - if a < 0.0 && a * taper.tan() > 0.0 { - let dir = n * sign; - if !taper_run_on_fits(st, &start_plane, dir, r, -a, a * taper.tan(), *operation, &plain_targets) { - a = 0.0; - } - } - // A start that can't run on (the profile hangs over the face's edge): - // the sides stand straight for a hair first, so the boolean can push the - // face the tool stands on into the body. - let build = |a: f64| { - let foot = if a >= 0.0 && on_face { TAPER_FOOT.min((b - a) * 0.01) } else { 0.0 }; - kernel::extrude_tapered_between(&start_plane, r, a, b, foot, sign, taper) + let corner = match extent.corner { + Some(c) => c, + None => draft_corner_for(&ss, r, len, taper, &mut notes)?, }; - let mut body = build(a); - // A taper that widens the tool where it cuts narrows it behind its start, so - // the run on can close a small corner arc the tool itself never shrinks - // (#4825): run on less, then start on the face. - for k in [0.5, 0.25, 0.0] { - if body.is_ok() || a >= 0.0 { - break; - } - let shorter = build(a * k); - if shorter.is_ok() { - a *= k; - body = shorter; - } - } - let body = body?; - growth = growth.max(a.abs().max(b.abs()) * taper.tan().abs()); + let body = kernel::extrude_tapered_between(&start_plane, r, 0.0, len, 0.0, sign, taper, corner)?; Ok(roles.tool(body, None)) }) .collect::>()?; + for note in notes { + append_warning(warning, note); + } // Profiles apart by more than the tools grow (the letters of a text): the tools // are apart too, and go into the body as one, in one boolean rather than one per // profile, each on a body grown or cut by the ones before. (A join meeting several @@ -5342,7 +5051,7 @@ fn feature_tools_with_constructor( }; if at_once && tools.len() > 1 && regions_apart(®ions, APART_GAP + 2.0 * growth) { let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); - if let Ok(Some(one)) = kernel::join_apart(&bodies) { + if let Some(one) = kernel::join_apart(&bodies)? { return Ok(vec![Traced::step(one, &tools.iter().collect::>())]); } } @@ -5373,151 +5082,27 @@ fn feature_tools_with_constructor( lo = hs.iter().cloned().fold(lo, f64::min) - margin; } } + let untrimmed = extent.to.is_none() && extent.from.is_none() && !extent.through_all; let mut tools = Vec::new(); - let mut untrimmed = extent.to.is_none() && extent.from.is_none() && !extent.through_all; - // The footprint of each tool in the sketch: a tool lies in the prism over it. - let mut footprints = Vec::with_capacity(regions.len()); - // Each tool's extent along the normal (they differ where one is run on into a face). - let mut extents: Vec<(f64, f64)> = Vec::with_capacity(regions.len()); - let plain_targets: Vec = crate::plain(targets); - let exact_planar_cut = *operation == Operation::Cut - && ss.sketch.links.len() > 1 - && ss.sketch.links.iter().all(|link| matches!(&link.source, solidcraft_sketch::LinkSource::Face { .. })) - && st - .bodies - .iter() - .filter(|body| plain_targets.is_empty() || plain_targets.iter().any(|target| target == "*" || target == &body.name)) - .all(|body| kernel::is_planar(&body.body)); - let mut touching_batch = false; - // Generated face profiles have full source seams. Check all of them in - // one guarded construction; arbitrary sketch profiles retain their existing path. - if *operation == Operation::Join - && regions.len() > 1 - && ss.sketch.links.len() > 1 - && ss.sketch.links.iter().all(|link| matches!(&link.source, solidcraft_sketch::LinkSource::Face { .. })) - { - let exact = regions - .iter() - .map(|region| centered_extrude(&ss.plane, region, lo + off, hi + off, Some(&ss), thin_roles.as_ref())) - .collect::>>()? - .into_iter() - .flatten() - .collect::>(); - if let Ok(Some(compound)) = kernel::compound_disjoint_extrusions(&exact.iter().map(|tool| tool.body.clone()).collect::>()) - && st - .bodies - .iter() - .filter(|body| plain_targets.is_empty() || plain_targets.contains(&body.name)) - .any(|body| kernel::can_join_all_touching_faces(&body.body, &compound)) - { - tools = exact; - touching_batch = true; - } - } - let surroundings = if exact_planar_cut || touching_batch { None } else { Surroundings::of(st, *operation, &plain_targets) }; - let join_surroundings = if *operation == Operation::Join && !touching_batch { - // Trimming may discard a tool's material, so only bodies this feature - // actually joins can establish that the discarded end is already filled. - let participants = if plain_targets.is_empty() { &f.participants } else { &plain_targets }; - let trim_targets: Vec = st - .bodies - .iter() - .filter(|b| { - if participants.is_empty() { - b.component == f.component || b.feature == f.id - } else { - participants.iter().any(|t| t == "*" || t == &b.name) - } - }) - .map(|b| b.name.clone()) - .collect(); - - if trim_targets.is_empty() { None } else { Surroundings::of(st, *operation, &trim_targets) } - } else { - 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), thin_roles.as_ref())?; - if exact.iter().all(|tool| { - st.bodies - .iter() - .filter(|b| targets.is_empty() || targets.iter().any(|t| *t == b.name)) - .any(|b| kernel::can_join_touching_faces(&b.body, &tool.body)) - }) { - // Preserve a whole touching face: extending into a chamfer replaces - // the sewable seam with a coincident curved intersection. - tools.extend(exact); - footprints.push(r.clone()); - extents.push((lo + off, hi + off)); - continue; - } - } - let (l2, h2) = surroundings.as_ref().map_or((lo + off, hi + off), |sur| extend_for_coplanar(sur, &ss.plane, r, lo + off, hi + off)); - let (l2, h2) = join_surroundings.as_ref().map_or((l2, h2), |sur| { - // Trim only material in the requested extent. A run-on added - // above to resolve a touching cap must keep doing its job. - let (l, h) = trim_embedded_join_ends(sur, &ss.plane, r, lo + off, hi + off); - (if l > lo + off { l } else { l2 }, if h < hi + off { h } else { h2 }) - }); - let probe = |p: Vec2| (1..4).map(|k| ss.plane.to_world(p) + n * (lo + off + (hi - lo) * k as f64 / 4.0)).collect::>(); - let original = r; - let grown = |gains: &dyn Fn(&[[Vec2; 3]]) -> bool| match &surroundings { - Some(sur) => grow_profile_for_coplanar(sur, r, &probe, gains), - None => r.clone(), - }; - // A hole of the profile over empty space (a cut) or material (a join) is taken in. - let filled = |p: Region2| fill_void_holes(st, &p, *operation, &plain_targets, &ss.plane, (l2, h2)); - // A side's strip runs the tool's height, drawn back by a hair from its ends. - let mut r = filled(grown(&|pieces| { - surroundings.as_ref().is_some_and(|sur| sur.harmless(&ss.plane, pieces, -sur.skin, l2 + sur.skin, h2 - sur.skin)) - })); - let mut built = centered_extrude(&ss.plane, &r, l2, h2, Some(&ss), thin_roles.as_ref()); - if built.is_err() { - // A profile the kernel cannot build as drawn (a square some hundredths of a - // micrometre across, away from the origin, defeats truck's plane fit) grows - // wherever the samples find room, as it used to. - let loose = filled(grown(&|_| true)); - if loose != r { - built = centered_extrude(&ss.plane, &loose, l2, h2, Some(&ss), thin_roles.as_ref()); - r = loose; - } - } - untrimmed &= l2 == lo + off && h2 == hi + off && &r == original; - tools.extend(built?); - footprints.push(r); - extents.push((l2, h2)); + for r in ®ions { + tools.extend(centered_extrude(&ss.plane, r, lo + off, hi + off, Some(&ss), thin_roles.as_ref())?); } // A cut or a join by profiles apart in the sketch (the letters of a text): each tool - // lies in the prism over its footprint, so the tools are apart too (whatever their - // heights, and trimmed or not). The body is then cut once by all of them, or joined to + // lies in the prism over its profile, so the tools are apart too. The body is then cut once by all of them, or joined to // all of them at once, rather than once per profile, each on a body grown or cut by // the ones before. (A join meeting several bodies keeps joining them tool by tool; // sheet metal keeps its own way of cutting, tool by tool, to keep its flat pattern.) let sheet = if targets.is_empty() { !st.sheets.is_empty() } else { targets.iter().any(|t| st.sheets.iter().any(|sheet| &sheet.body == t)) }; let one_target = if targets.is_empty() { st.bodies.len() == 1 } else { targets.len() == 1 }; - // A join at once only of tools alike in height (one prism of them all, which the - // boolean joins exactly): tools that start at different levels (some run on into the - // face, one hanging over its edge) keep joining one by one. - let alike = extents.windows(2).all(|w| (w[0].0 - w[1].0).abs() < 1e-9 && (w[0].1 - w[1].1).abs() < 1e-9); let at_once = match operation { Operation::Cut => !sheet, - Operation::Join => one_target && !sheet && alike, + Operation::Join => one_target && !sheet, _ => false, }; - if at_once && tools.len() > 1 && regions_apart(&footprints, APART_GAP) { + if at_once && tools.len() > 1 && regions_apart(®ions, APART_GAP) { let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); - if let Ok(Some(one)) = kernel::join_apart(&bodies) { + if let Some(one) = kernel::join_apart(&bodies)? { tools = vec![Traced::step(one, &tools.iter().collect::>())]; } } @@ -5525,7 +5110,9 @@ fn feature_tools_with_constructor( let start = if hi > 0.0 { lo + off } else { hi + off }; tools = trim_to_body(tools, tb, |q: Vec3| ((q - ss.plane.origin).dot(n) - start).abs())?; } - if untrimmed { + // A join's profile grows into the material it joins; its sketch plane and depth as drawn + // still serve a join into sheet metal (`sheet_join`), which takes the sketch's regions. + if untrimmed || (*operation == Operation::Join && curved.is_none()) { *constructor = Some(ExtrudeConstructor { plane: ss.plane, interval: (lo + off, hi + off) }); } // A Join tool's faces outlive the boolean where they stay on the result, so they are @@ -5556,7 +5143,7 @@ fn feature_tools_with_constructor( cap_bindings.as_ref().and_then(|bindings| bindings.get(body_index)).cloned().unwrap_or_else(|| vec![None; curves.len()]); // A cap moved off its designed height (into a Join target, or past a // curved To face) is not the feature's start or end face. - let nominal = |plane: &solidcraft_geom::Plane| { + let nominal = |plane: &solidcore_record::Plane| { let height = (plane.origin - ss.plane.origin).dot(n); let tolerance = 1e-9 * (1.0 + height.abs() + (lo + off).abs() + (hi + off).abs()); (height - (lo + off)).abs() <= tolerance || (height - (hi + off)).abs() <= tolerance @@ -5582,12 +5169,9 @@ fn feature_tools_with_constructor( )?; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); let (o, d) = - revolve_axis(&ss, axis, &axis_state(doc, st, f.component, axis), &|name| construction_axis_in(Some(doc), st, name, f.component))?; + revolve_axis(&ss, axis, &*axis_state(doc, st, f.component, axis)?, &|name| construction_axis_in(Some(doc), st, name, f.component))?; // To Object is in this feature's component frame: the model as seen from there. - let tst = if to.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; - // Where the tool meets its targets is measured where they are shown (#3383). - let shown = targets_as_shown(st, f, &feature_op(f).1)?; - let st: &ModelState = &shown; + let tst = if to.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) }; let angles = if to.is_some() { (0.0, None) } else { @@ -5623,36 +5207,9 @@ fn feature_tools_with_constructor( } }) .collect::>>()?; - let (operation, targets) = feature_op(f); + let (operation, _) = feature_op(f); let axis_w = ss.plane.dir_to_world(d); let origin_w = ss.plane.to_world(o); - let surroundings = Surroundings::of(st, operation, &targets); - let regions: Vec = regions - .iter() - .zip(®ion_extents) - .map(|(r, region_extent)| { - let rotation_axis = match convention { - crate::RevolveConvention::LegacyAxisStart => axis_w, - crate::RevolveConvention::SketchNormal => kernel::canonical_revolve_axis(&ss.plane, r, o, d)?, - }; - let probe = |p: Vec2| { - let q = ss.plane.to_world(p); - (1..4) - .map(|k| { - let a = region_extent.sweep * k as f64 / 4.0 - + if *convention == crate::RevolveConvention::SketchNormal { region_extent.start } else { 0.0 }; - let v = q - origin_w; - origin_w + v * a.cos() + rotation_axis.cross(v) * a.sin() + rotation_axis * (rotation_axis.dot(v) * (1.0 - a.cos())) - }) - .collect::>() - }; - // Around the axis the strips are rings, which the faces are not asked about yet. - Ok(match &surroundings { - Some(sur) => grow_profile_for_coplanar(sur, r, &probe, &|_| true), - None => r.clone(), - }) - }) - .collect::>>()?; // To a curved face: turn past the whole target body, then cut back to its surface // (the piece that starts at the profile). let curved = curved_face(&tst, to.and_then(|p| object_face(&tst, f.face_names.first().map(String::as_str), p.0, None)), None); @@ -5790,10 +5347,10 @@ fn feature_tools_with_constructor( let plane = Plane { origin: *base, x, y: k }; let c = Vec2::new(r, 0.0); let outer = match section { - crate::CoilSection::Circular => solidcraft_geom::Loop2::circle(c, s / 2.0), + crate::CoilSection::Circular => solidcore_record::Loop2::circle(c, s / 2.0), crate::CoilSection::Square => { let h = s / 2.0; - solidcraft_geom::Loop2::polygon(&[c + Vec2::new(-h, -h), c + Vec2::new(h, -h), c + Vec2::new(h, h), c + Vec2::new(-h, h)]) + solidcore_record::Loop2::polygon(&[c + Vec2::new(-h, -h), c + Vec2::new(h, -h), c + Vec2::new(h, h), c + Vec2::new(-h, h)]) } }; let region = Region2 { outer, holes: Vec::new() }; @@ -5853,21 +5410,15 @@ fn feature_tools_with_constructor( let points = path_points(ps, path, start)?; let segs = match points { Some(_) => Vec::new(), - None => path_segments(ps, path, start)?, + None => path_segments_at(ps, path, start, Some(&ss.plane))?, }; - let path_start = points - .as_ref() - .and_then(|p| p.first().copied()) - .or_else(|| match segs.first() { - Some(kernel::PathSeg::Line { a, .. } | kernel::PathSeg::Arc { a, .. }) => Some(*a), - None => None, - }) - .unwrap_or(start); + let path_start = + points.as_ref().and_then(|p| p.points().first().copied()).or_else(|| segs.first().map(kernel::PathSeg::start)).unwrap_or(start); let rails = rail_polylines(doc, st, rails, f.component, path_start)?; let ctl = sweep_control(vals, orientation, twist, scale, rails, *rail_fit)?; - // A path through 3D sketch curves follows them as points. - if let Some(pts) = points { - return regions.iter().map(|r| Ok(tool(r, kernel::sweep_path_with(&ss.plane, r, &pts, &ctl)?))).collect(); + // A path through 3D sketch curves: its drawn splines exactly, the rest as points. + if let Some(path) = points { + return regions.iter().map(|r| Ok(tool(r, kernel::sweep_point_path_with(&ss.plane, r, &path, &ctl)?))).collect(); } regions.iter().map(|r| Ok(tool(r, kernel::sweep_with(&ss.plane, r, &segs, &ctl)?))).collect() } @@ -5880,19 +5431,22 @@ fn feature_tools_with_constructor( if !(r > 1e-6) { return Err(DocError::Invalid("pipe diameter must be positive".into())); } - if let Some(pts) = path_points(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))? { + if let Some(along) = path_points(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))? { + let pts = along.points(); let (Some(a), Some(b)) = (pts.first().copied(), pts.get(1).copied()) else { return Err(DocError::Invalid("empty path".into())) }; let t = (b - a).normalized().ok_or_else(|| DocError::Invalid("path direction".into()))?; let plane = Plane::from_normal(a, t).ok_or_else(|| DocError::Invalid("pipe profile plane".into()))?; - return Ok(unnamed(vec![kernel::sweep_path(&plane, &pipe_region(vals, r, wall)?, &pts)?])); + return Ok(unnamed(vec![kernel::sweep_point_path_with( + &plane, + &pipe_region(vals, r, wall)?, + &along, + &kernel::SweepControl::default(), + )?])); } let segs = path_segments(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))?; let first = segs.first().ok_or_else(|| DocError::Invalid("empty path".into()))?; - let (start, tangent) = match *first { - kernel::PathSeg::Line { a, b } => (a, b - a), - kernel::PathSeg::Arc { a, center, axis, .. } => (a, axis.cross(a - center)), - }; - let t = tangent.normalized().ok_or_else(|| DocError::Invalid("path direction".into()))?; + let start = first.start(); + let (t, _) = first.tangents().ok_or_else(|| DocError::Invalid("path direction".into()))?; let plane = Plane::from_normal(start, t).ok_or_else(|| DocError::Invalid("pipe profile plane".into()))?; Ok(unnamed(vec![kernel::sweep(&plane, &pipe_region(vals, r, wall)?, &segs)?])) } @@ -5979,7 +5533,7 @@ pub(crate) fn rail_polylines(doc: &Document, st: &ModelState, rails: &[crate::Sw let mapped = path_in_frame(doc, rs, consumer)?; let rs = mapped.as_ref(); match path_points(rs, &rail.curves, start)? { - Some(pts) => Ok(pts), + Some(path) => Ok(path.points()), None => Ok(kernel::path_polyline(&path_segments(rs, &rail.curves, start)?)?), } }) @@ -5994,25 +5548,15 @@ fn pipe_region(vals: &BTreeMap, r: f64, wall: &Option 0.0 && wt < r) { return Err(DocError::Invalid("the wall must be thinner than the radius".into())); } - vec![solidcraft_geom::Loop2::circle(Vec2::ZERO, r - wt).reversed()] + vec![solidcore_record::Loop2::circle(Vec2::ZERO, r - wt).reversed()] } None => Vec::new(), }; - Ok(Region2 { outer: solidcraft_geom::Loop2::circle(Vec2::ZERO, r), holes }) + Ok(Region2 { outer: solidcore_record::Loop2::circle(Vec2::ZERO, r), holes }) } pub fn map_wire(wire: &mut solidcraft_sketch::Wire, matrix: &Mat) { - for point in wire.pts.iter_mut().chain(&mut wire.fit) { - *point = crate::apply_point(matrix, *point); - } - if let Some(arc) = &mut wire.arc { - let normal = crate::apply_vector(matrix, arc.normal); - arc.center = crate::apply_point(matrix, arc.center); - arc.start = crate::apply_point(matrix, arc.start); - arc.end = crate::apply_point(matrix, arc.end); - arc.normal = normal.normalized().unwrap_or(arc.normal); - arc.radius = arc.center.dist(arc.start); - } + wire.map(|p| crate::apply_point(matrix, p), |v| crate::apply_vector(matrix, v)); } /// A feature's sketch as its component sees it: a sketch of another component that is placed @@ -6065,121 +5609,184 @@ fn path_in_frame<'a>(doc: &Document, sketch: &'a SolvedSketch, consumer: u64) -> Ok(Cow::Owned(mapped)) } -/// A path that uses 3D sketch curves (wires), as one chain of world points from the end nearest -/// `start` (no start: the first curve runs toward the second). `None` when the path is all -/// planar curves. -fn path_points(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result>> { +/// A path that uses 3D sketch curves (wires), as one chain of pieces from the end nearest +/// `start` (no start: the first curve runs toward the second): each drawn 3D spline as its fit +/// points (the kernel has its exact curve), each curve held exactly (a planar sketch curve, a +/// linked curve with [`solidcraft_sketch::Wire::exact`]) as its path segments, and a linked +/// curve known only as points as those points. `None` when the path is all planar curves. +fn path_points(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result> { if !ids.iter().any(|id| ps.sketch.wire_index(id).is_some()) { return Ok(None); } if ids.len() > 1000 { return Err(DocError::Invalid("the path needs 1…1000 curves".into())); } - let mut pieces: Vec> = Vec::with_capacity(ids.len()); + let mut pieces: Vec = Vec::with_capacity(ids.len()); for id in ids { if let Some(wi) = ps.sketch.wire_index(id) { - pieces.push(ps.sketch.wires.get(wi).map(|w| w.pts.clone()).unwrap_or_default()); + pieces.push(match ps.sketch.wires.get(wi) { + // A drawn 3D arc is its circle, from its start counter-clockwise about its normal + // (its three fit points define it; a spline through them is not the arc). + Some(solidcraft_sketch::Wire { arc: Some(arc), .. }) => { + let x = (arc.start - arc.center).normalized().ok_or_else(|| DocError::Invalid("a 3D arc of no radius".into()))?; + let y = arc.normal.cross(x); + let frame = solidcore_record::brep::Frame { origin: arc.center.into(), x_axis: x.into(), y_axis: y.into() }; + let circle = solidcore_record::brep::Curve::Circle { frame, radius: arc.radius }; + kernel::PathPiece::Segs(kernel::curve_path(&circle, [0.0, solidcraft_sketch::arc_sweep(arc)])?) + } + Some(w) if w.fit.len() >= 3 => kernel::PathPiece::Spline { fit: w.fit.clone(), reversed: false }, + Some(w) if !w.exact.is_empty() => { + let mut segs = Vec::new(); + for c in &w.exact { + segs.extend(kernel::curve_path(&c.curve, c.interval)?); + } + kernel::PathPiece::Segs(segs) + } + w => kernel::PathPiece::Polyline(w.map(|w| w.pts.clone()).unwrap_or_default()), + }); } else { let ci = ps.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("path curve `{id}`")))?; - let mut pts: Vec = Vec::new(); - for s in ps.sketch.segs(ci) { - for q in s.polyline(1e-2) { - let w = ps.plane.to_world(q); - if pts.last().is_none_or(|l| l.dist(w) > 1e-9) { - pts.push(w); - } - } - } - pieces.push(pts); + let segs = ps.sketch.exact_segs(ci).unwrap_or_else(|| ps.sketch.segs(ci)); + pieces.push(kernel::PathPiece::Segs(segs.iter().map(|s| kernel::PathSeg::of_sketch(&ps.plane, s)).collect())); } } // Pieces meet within the sketch's tolerance (projected curves are only that close). let tol = 1e-3; - let ends = |p: &Vec| (p.first().copied().unwrap_or_default(), p.last().copied().unwrap_or_default()); - if let Some(f) = pieces.first().cloned() { - let (a, b) = ends(&f); - let flip = if start.is_finite() { - b.dist(start) < a.dist(start) - } else { - pieces.get(1).is_some_and(|n| { - let (na, nb) = ends(n); - na.dist(a).min(nb.dist(a)) < na.dist(b).min(nb.dist(b)) - }) - }; - if flip && let Some(p0) = pieces.first_mut() { - p0.reverse(); + let ends = |p: &kernel::PathPiece| { + let pts = p.points(); + (pts.first().copied().unwrap_or_default(), pts.last().copied().unwrap_or_default()) + }; + let mut pieces = pieces.into_iter(); + let Some(first) = pieces.next() else { return Ok(None) }; + let rest: Vec = pieces.collect(); + let (a, b) = ends(&first); + let flip = if start.is_finite() { + b.dist(start) < a.dist(start) + } else { + rest.first().is_some_and(|n| { + let (na, nb) = ends(n); + na.dist(a).min(nb.dist(a)) < na.dist(b).min(nb.dist(b)) + }) + }; + let first = if flip { first.reversed() } else { first }; + let mut last = ends(&first).1; + let mut chain = vec![first]; + for p in rest { + let (a, b) = ends(&p); + let (p, a, b) = if b.dist(last) < a.dist(last) { (p.reversed(), b, a) } else { (p, a, b) }; + if a.dist(last) > tol { + return Err(DocError::Invalid("the path curves are not connected end to end".into())); } + chain.push(p); + last = b; } - let mut chain: Vec = Vec::new(); - for mut p in pieces { - if let Some(last) = chain.last().copied() { - let (a, b) = ends(&p); - if b.dist(last) < a.dist(last) { - p.reverse(); - } - if p.first().is_some_and(|a| a.dist(last) > tol) { - return Err(DocError::Invalid("the path curves are not connected end to end".into())); - } - chain.extend(p.into_iter().skip(1)); - } else { - chain = p; - } - } - Ok(Some(chain)) + Ok(Some(kernel::PointPath { pieces: chain })) } fn path_segments(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result> { + path_segments_at(ps, ids, start, None) +} + +/// [`path_segments`] for a profile in `profile`: a closed path is followed from where the +/// profile's plane crosses it nearest `start`, the curve there split in two, when that is not +/// already where the chain starts (#3345). Swept from anywhere else, the profile would stand +/// off the path by the distance between the two. +pub(crate) fn path_segments_at(ps: &SolvedSketch, ids: &[String], start: Vec3, profile: Option<&Plane>) -> Result> { if ids.is_empty() || ids.len() > 1000 { return Err(DocError::Invalid("the path needs 1…1000 curves".into())); } // A path through 3D sketch curves is followed as a 3D polyline. - if let Some(pts) = path_points(ps, ids, start)? { - return Ok(pts.windows(2).map(|w| kernel::PathSeg::Line { a: w[0], b: w[1] }).collect()); + if let Some(path) = path_points(ps, ids, start)? { + return Ok(path.points().windows(2).map(|w| kernel::PathSeg::Line { a: w[0], b: w[1] }).collect()); } - let mut segs: Vec = Vec::new(); + // Each curve as its exact pieces (Béziers, conics) where it has them, in its own direction + // of travel. A curve is turned round whole: its pieces stay one run. + let mut curves: Vec> = Vec::with_capacity(ids.len()); for id in ids { let ci = ps.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("path curve `{id}`")))?; - segs.extend(ps.sketch.segs(ci)); + curves.push(ps.sketch.exact_segs(ci).unwrap_or_else(|| ps.sketch.segs(ci))); } - // Orient the chain: the first segment starts at the end nearest `start`, each next one - // starts where the previous ended. + curves.retain(|c| !c.is_empty()); + let ends = |c: &[solidcore_record::Seg2]| c.first().zip(c.last()).map(|(f, l)| (f.start(), l.end())); + let reversed = |c: Vec| c.into_iter().rev().map(|s| s.reversed()).collect::>(); + // Where two curves meet: one tolerance for telling which ends touch and for the joint. + const JOINT: f64 = 1e-5; + // Orient the first curve: it runs toward the second where it meets it at one end only; + // otherwise (one curve, or a second meeting it at both ends) from the end nearest `start` + // (no start given, a pipe: as drawn). let w = |p: Vec2| ps.plane.to_world(p); - if let (Some(f), true) = (segs.first().copied(), !segs.is_empty()) - && w(f.end()).dist(start) < w(f.start()).dist(start) - && (segs.len() == 1 || segs.get(1).is_some_and(|n| n.start().dist(f.start()) < 1e-6 || n.end().dist(f.start()) < 1e-6)) - { - segs[0] = f.reversed(); - } - // No start given (a pipe): the first curve runs toward the second. - if !start.is_finite() - && let (Some(f), Some(n)) = (segs.first().copied(), segs.get(1).copied()) - && (n.start().dist(f.start()) < 1e-6 || n.end().dist(f.start()) < 1e-6) - { - segs[0] = f.reversed(); - } - for i in 1..segs.len() { - let prev_end = segs[i - 1].end(); - if segs[i].end().dist(prev_end) < segs[i].start().dist(prev_end) { - segs[i] = segs[i].reversed(); - } - if segs[i].start().dist(prev_end) > 1e-5 { - return Err(DocError::Invalid("the path curves are not connected end to end".into())); + if let Some((a, b)) = curves.first().and_then(|c| ends(c)) { + let touches = |p: Vec2| curves.get(1).and_then(|n| ends(n)).is_some_and(|(na, nb)| na.dist(p) <= JOINT || nb.dist(p) <= JOINT); + let flip = match (touches(a), touches(b)) { + (true, false) => true, + (false, true) => false, + _ => start.is_finite() && w(b).dist(start) < w(a).dist(start), + }; + if flip && let Some(first) = curves.first_mut() { + *first = reversed(std::mem::take(first)); } } - let n = ps.plane.normal(); - Ok(segs + // Each next curve starts where the previous one ended. + let mut segs: Vec = Vec::new(); + for curve in curves { + let (Some(prev_end), Some((a, b))) = (segs.last().map(solidcore_record::Seg2::end), ends(&curve)) else { + segs.extend(curve); + continue; + }; + let curve = if b.dist(prev_end) < a.dist(prev_end) { reversed(curve) } else { curve }; + segs.extend(curve); + } + if segs.windows(2).any(|pair| pair[1].start().dist(pair[0].end()) > JOINT) { + return Err(DocError::Invalid("the path curves are not connected end to end".into())); + } + if let Some(profile) = profile { + segs = from_profile_on_closed_path(segs, &ps.plane, profile, start); + } + Ok(segs.iter().map(|s| kernel::PathSeg::of_sketch(&ps.plane, s)).collect()) +} + +/// A closed chain `segs` (in the plane `path`) begun where `profile`'s plane crosses it nearest +/// `start`: the curve there split in two, its second part first and its first part last (or the +/// chain begun at the joint there). Unchanged when the chain is open, already starts on the +/// profile's plane, or its point nearest `start` is off that plane. +fn from_profile_on_closed_path(segs: Vec, path: &Plane, profile: &Plane, start: Vec3) -> Vec { + let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return segs }; + let size: f64 = segs.iter().map(solidcore_record::Seg2::length).sum(); + let on_plane = |p: Vec2| profile.height(path.to_world(p)).abs() <= (size * 1e-9).max(1e-9); + if !start.is_finite() || !(size > 0.0 && size.is_finite()) || last.end().dist(first.start()) > 1e-5 || on_plane(first.start()) { + return segs; + } + let local = path.to_local(start); + let Some((k, t, q)) = segs .iter() - .flat_map(|s| match *s { - solidcraft_geom::Seg2::Line { a, b } => vec![kernel::PathSeg::Line { a: w(a), b: w(b) }], - solidcraft_geom::Seg2::Arc { center, sweep, .. } => { - vec![kernel::PathSeg::Arc { a: w(s.start()), center: w(center), axis: n * sweep.signum(), angle: sweep.abs() }] - } - // Free-form path curves are followed as polylines. - solidcraft_geom::Seg2::Cubic { .. } | solidcraft_geom::Seg2::Conic { .. } | solidcraft_geom::Seg2::Bezier { .. } => { - s.polyline(1e-2).windows(2).map(|q| kernel::PathSeg::Line { a: w(q[0]), b: w(q[1]) }).collect() - } + .enumerate() + .map(|(k, s)| { + let t = s.closest_param(local); + (k, t, path.to_world(s.point_at(t))) }) - .collect()) + .min_by(|a, b| a.2.dist(start).total_cmp(&b.2.dist(start))) + else { + return segs; + }; + if profile.height(q).abs() > (size * 1e-6).max(1e-6) { + return segs; + } + let Some(seg) = segs.get(k).copied() else { return segs }; + let n = segs.len(); + let from = |k: usize| segs.iter().cycle().skip(k % n).take(n).copied().collect::>(); + let at = |p: Vec2| path.to_world(p).dist(q) <= 1e-6; + if at(seg.start()) { + return from(k); + } + if at(seg.end()) { + return from(k + 1); + } + let (before, after) = seg.split_at(t); + let mut out = Vec::with_capacity(n + 1); + out.push(after); + out.extend(from(k + 1).into_iter().take(n - 1)); + out.push(before); + out } /// Where an extrude of distance `d` starts and ends along the sketch normal, before any start @@ -6385,7 +5992,8 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("path sketch {path_sketch}")))?; let mapped = path_in_frame(doc, ps, component)?; let ps = mapped.as_ref(); - let mut segs = path_segments(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))?; + // Free-form curves measured along their polylines. + let mut segs = kernel::PathSeg::flattened(&path_segments(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))?); if *flip { segs = segs.iter().rev().map(reverse_seg).collect(); } @@ -6413,11 +6021,19 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model } } crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_ref, axis_feature } => { - // On an edge or round face: about it as it is now; on a construction axis: where it is. + // On an edge or round face: about it as it is now; on a construction axis: where it is; + // else through its origin, whose expressions follow the parameters (#10852). let (origin, axis) = match (axis_ref, axis_feature) { - (Some(g), _) => crate::construct::model_axis(&construction_state(doc, st, component), g)?, + (Some(g), _) => crate::construct::model_axis(&*construction_state(doc, st, component)?, g)?, (None, Some(name)) => construction_axis_in(Some(doc), st, name, component)?, - (None, None) => (origin.0, axis.0), + (None, None) => { + let [x, y, z] = origin; + let o = Vec3::new(val(vals, x, Kind::Length)?, val(vals, y, Kind::Length)?, val(vals, z, Kind::Length)?); + if ![o.x, o.y, o.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) { + return Err(DocError::Invalid("the pattern's axis origin is out of range".into())); + } + (o, axis.0) + } }; let n = count(c)?; let total = val(vals, angle, Kind::Angle)?; @@ -6441,6 +6057,8 @@ fn seg_len(s: &kernel::PathSeg) -> f64 { match *s { kernel::PathSeg::Line { a, b } => (b - a).len(), kernel::PathSeg::Arc { a, center, angle, .. } => (a - center).len() * angle.abs(), + // Patterns flatten their paths; a curve left is measured along its chord. + kernel::PathSeg::Curve { .. } | kernel::PathSeg::Bezier(_) => s.start().dist(s.end()), } } @@ -6464,18 +6082,16 @@ fn seg_at(s: &kernel::PathSeg, t: f64) -> (Vec3, Vec3) { let v = rotate_vec(a - center, k, s * t / r); (center + v, k.cross(v).normalized().unwrap_or(Vec3::X) * s) } + kernel::PathSeg::Curve { .. } | kernel::PathSeg::Bezier(_) => { + let (a, b) = (s.start(), s.end()); + let d = (b - a).normalized().unwrap_or(Vec3::X); + (a + d * t, d) + } } } fn reverse_seg(s: &kernel::PathSeg) -> kernel::PathSeg { - match *s { - kernel::PathSeg::Line { a, b } => kernel::PathSeg::Line { a: b, b: a }, - kernel::PathSeg::Arc { a, center, axis, angle } => { - let k = axis.normalized().unwrap_or(Vec3::Z); - let end = center + rotate_vec(a - center, k, angle); - kernel::PathSeg::Arc { a: end, center, axis: k * -1.0, angle } - } - } + s.reversed() } /// Point and tangent at arc length `d` along a chain (clamped to its ends). @@ -6492,6 +6108,35 @@ fn path_at(segs: &[kernel::PathSeg], d: f64) -> (Vec3, Vec3) { } /// Whether a copy has no material to cut in any of its eligible targets. +/// The bodies a hole cuts: those its feature names, else its component's and its own (as +/// `apply_traced` picks a cut's targets). +fn hole_targets<'a>(st: &'a ModelState, f: &Feature) -> Vec<&'a ModelBody> { + let all = f.participants.len() == 1 && f.participants.first().is_some_and(|t| t == "*"); + st.bodies + .iter() + .filter(|b| all || if f.participants.is_empty() { b.component == f.component || b.feature == f.id } else { f.participants.contains(&b.name) }) + .collect() +} + +/// Whether hole tool `tool` is clear of every body the hole cuts, by their exact boxes (#10701). +/// Boxes only: a probe boolean for every hole of a large hole pattern would double its work. A +/// body whose exact box is unknown, or one of another component (in another frame), leaves the +/// hole not known to miss. +fn hole_misses(st: &ModelState, f: &Feature, tool: &Body) -> bool { + let targets = hole_targets(st, f); + let bounds = tool.outline_bounds(); + if targets.is_empty() + || targets.iter().any(|b| b.component != f.component) + || bounds.is_empty() + || !bounds.min.is_finite() + || !bounds.max.is_finite() + { + return false; + } + let tool_box = Some(bounds.inflated(1e-6)); + targets.iter().all(|b| more::boxes_apart(&tool_box, &b.body.exact_bounds().ok())) +} + fn copy_misses(st: &ModelState, f: &Feature, targets: &[String], tools: &[Traced]) -> bool { let targets = if targets.is_empty() { &f.participants } else { targets }; let all = targets.len() == 1 && targets.first().is_some_and(|t| t == "*"); @@ -6500,10 +6145,8 @@ fn copy_misses(st: &ModelState, f: &Feature, targets: &[String], tools: &[Traced .filter(|b| all || if targets.is_empty() { b.component == f.component || b.feature == f.id } else { targets.contains(&b.name) }) .all(|b| { tools.iter().all(|t| { - // A diagnostic must neither reject an otherwise valid cut nor add its own - // retries to the feature's report. An inconclusive probe is not a miss. - let (intersection, _) = kernel::capture_boolean_diagnostics(|| kernel::boolean(&b.body, &t.body, BoolOp::Intersect)); - matches!(intersection, Ok(None)) + // An inconclusive probe is not a miss: it must not reject an otherwise valid cut. + matches!(kernel::boolean(&b.body, &t.body, BoolOp::Intersect), Ok(None)) }) }) } @@ -6545,14 +6188,15 @@ fn copied_features(doc: &Document, vals: &BTreeMap, st: &ModelSta /// `mats`' own (which keep the numbers they always had), each nested source in a block of its /// own, so no two copies of one feature share an instance. Suppressed sources copy nothing. /// `f` with each face point moved onto its named face (on the body the feature names, when it -/// names one and the face is there) in `state`, and notes for names that no longer find their -/// face. `None` when `f` names no face. -fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Option<(Feature, Vec)> { +/// names one and the face is there) in `state`, and notes on how the faces were found. `None` +/// when `f` names no face; an error when a name no longer finds its face (the feature asks for +/// it to be picked again), or when the frame the faces are looked up in cannot be made. +fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Result)>> { // Cylindrical emboss resolves its named face in the selected body's frame // and certifies an analytic anchor; mesh projection here would undo that. let explicit_emboss = matches!(&f.kind, FeatureKind::Emboss { face: Some(_), .. }); if explicit_emboss || !f.face_names.iter().any(|n| !n.is_empty()) { - return None; + return Ok(None); } let mut g = f.clone(); let mut notes = Vec::new(); @@ -6563,7 +6207,7 @@ fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Op FeatureKind::Hole { direction, points: None | Some(crate::SketchPoints { single: true, .. }), .. } => direction.normalized(), _ => None, }; - let fst = face_point_state(doc, state, &f.kind, f.component); + let fst = face_point_state(doc, state, &f.kind, f.component)?; for (k, (p, n)) in g.kind.face_points_mut().into_iter().zip(&f.face_names).enumerate() { if n.is_empty() { continue; @@ -6583,13 +6227,13 @@ fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Op p.x, p.y, p.z )), }, - _ => *p = hit.point, + _ => *p = hit.pick_point(&fst, *p), } } - None => notes.push(format!("face `{n}` no longer exists; using the face at the picked point")), + None => return Err(DocError::reselect(n.as_str())), } } - Some((g, notes)) + Ok(Some((g, notes))) } fn copy_plan<'a>( @@ -6717,12 +6361,12 @@ fn replay( let nb = match &src.kind { FeatureKind::Chamfer { distance2, angle, flip, .. } => chamfer_with(vals, &mb.body, &moved, r, distance2, angle, *flip)?, // A copy is congruent to the original: the radius it was reduced to first. - FeatureKind::Fillet { fit, .. } => match st.fitted.get(&src.id) { + FeatureKind::Fillet { fit, turn, .. } => match st.fitted.get(&src.id) { Some(used) => { let used: Vec = idx.iter().map(|i| used.get(*i).copied().unwrap_or(r)).collect(); - kernel::fillet_each(&mb.body, &moved, &used).or_else(|_| fillet_fitted(&mb.body, &moved, r, *fit).map(|x| x.0))? + kernel::fillet_each(&mb.body, &moved, &used, turn.kernel())? } - None => fillet_fitted(&mb.body, &moved, r, *fit)?.0, + None => fillet_fitted(&mb.body, &moved, r, *fit, turn.kernel())?.0, }, _ => kernel::fillet(&mb.body, &moved, r)?, }; @@ -6781,8 +6425,8 @@ fn replay( // Each copy's faces are named as the source feature's, with the instance. Its face // points follow their named faces, as the feature's own did (#2121): a To Object // extrude's copies reach the face where it is now, not where it was picked. - let moved = with_named_face_points(doc, st, src).map(|(g, _)| g); - let tools = feature_tools_with_constructor(doc, vals, moved.as_ref().unwrap_or(src), st, &mut None, &mut None)?; + let moved = with_named_face_points(doc, st, src)?.map(|(g, _)| g); + let tools = feature_tools_with_constructor(doc, vals, moved.as_ref().unwrap_or(src), st, &mut None, &mut None, &mut None)?; for (k, m) in mats.iter().enumerate() { let start = copies.len(); for t in &tools { @@ -6849,6 +6493,10 @@ pub use model_cache::SavedModel; pub(crate) mod frame_member; #[path = "eval_surface.rs"] mod surface; +#[path = "eval_thread.rs"] +mod thread; +use thread::thread_on; +pub use thread::{ThreadInfo, metric_thread_sizes, parse_metric_thread, suggested_thread, suggested_thread_in}; /// Height above `plane` (along its normal) of the object at `p` as seen from `centre`: the face /// there if it is planar and parallel (its plane), else where a ray from `centre` along the @@ -6976,8 +6624,10 @@ fn trim_to_body(tools: Vec, target: &ModelBody, dist_to_start: impl Fn(V let lineages = crate::lineage::Lineage::lumps(&cut.body, cut.lineage.as_ref(), &lumps); for (lump, lineage) in lumps.into_iter().zip(lineages) { let tol = (lump.size() * 1e-4).max(1e-6); - let touches = - lump.tessellate((lump.size() * 1e-2).max(1e-2)).map(|m| m.positions.iter().any(|q| dist_to_start(*q) < tol)).unwrap_or(false); + let touches = lump + .mesh(&solidcraft_kernel::MeshTolerance::chord((lump.size() * 1e-2).max(1e-2))) + .map(|m| m.positions.iter().any(|q| dist_to_start(*q) < tol)) + .unwrap_or(false); if touches { out.push(Traced { body: lump, lineage }); } @@ -7105,58 +6755,32 @@ pub(crate) fn sheet_face_plane_in_frame(doc: &Document, st: &ModelState, comp: u }) } -/// The plane of the body face a sketch sits on, found again: among planar faces with the -/// picked plane's normal, the one nearest `at`. The picked frame moves along its normal onto it. -fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> (Plane, Option) { +/// The plane of the body face a sketch sits on, found again: the face its stored `name` finds, +/// which must still be planar and face the picked plane's way (else the sketch fails, asking for +/// its face to be picked again); without a name, among planar faces with the picked plane's +/// normal, the one nearest `at`. The picked frame moves along its normal onto it. +fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> Result<(Plane, Option)> { let n = picked.normal(); - // By name first: the face (or a piece of it) with that name, facing the same way. if let Some(name) = name { - // (distance from `at`, plane offset along n, what to say about how it was found) - let mut found: Option<(f64, f64, Option)> = None; - for b in st.bodies.iter().filter(|b| !b.body.is_mesh()) { - let named = crate::naming::faces_with_stem(b, name); - if named.is_empty() { - continue; - } - let tol = (b.body.size() * 1e-3).max(1e-3); - let Ok(faces) = b.body.faces(tol) else { continue }; - for f in faces { - let hit = named.contains(&f.index); - if let (true, Some(fnrm)) = (hit, f.plane_normal) - && fnrm.dot(n) > 1.0 - 1e-6 - { - let d = f.centroid.dist(at); - if found.as_ref().is_none_or(|x| d < x.0) { - // A name saved before format 14 is found as it was then, without a note. - let note = if crate::naming::legacy_name(name).is_some() { - None - } else if !crate::naming::face_has_name(b, f.index, name) { - Some(format!("face `{name}` was split; using the piece nearest the picked point")) - } else if !crate::naming::face_name_exact(b, f.index) && (f.centroid - at).dot(n).abs() > tol { - // Named from geometry and moved off the picked plane: geometry alone decided. - Some(format!("face `{name}` was found by geometry, not exact history; check it")) - } else { - None - }; - found = Some((d, f.centroid.dot(n), note)); - } - } - } + let hit = crate::naming::locate_face(st, name, at).ok_or_else(|| DocError::reselect(name))?; + let b = st.bodies.get(hit.body).ok_or_else(|| DocError::reselect(name))?; + let tol = (b.body.size() * 1e-3).max(1e-3); + let face = b.body.faces(tol)?.into_iter().find(|f| f.index == hit.face).ok_or_else(|| DocError::reselect(name))?; + if !face.plane_normal.is_some_and(|fnrm| fnrm.dot(n) > 1.0 - 1e-6) { + return Err(DocError::reselect(name)); } - if let Some((_, off, note)) = found { - return (picked.offset(off - picked.origin.dot(n)), note); - } - let (pl, w) = face_plane(st, picked, at, None); - let note = format!( - "the face `{name}` the sketch was on no longer exists; {}", - if w.is_some() { "the sketch stays where it was" } else { "using the face at the picked point" } - ); - return (pl, Some(note)); + let note = if !crate::naming::face_name_exact(b, hit.face) && (face.centroid - at).dot(n).abs() > tol { + // Named from geometry and moved off the picked plane: geometry alone decided. + Some(format!("face `{}` was found by geometry, not exact history; check it", crate::name_lookup::quoted(name))) + } else { + None + }; + return Ok((picked.offset(face.centroid.dot(n) - picked.origin.dot(n)), note)); } let mut best: Option<(f64, f64)> = None; // (distance from `at`, plane offset along n) for b in &st.bodies { let tol = (b.body.size() * 1e-3).max(1e-3); - let (Ok(faces), Ok(mesh)) = (b.body.faces(tol), b.body.tessellate(tol)) else { continue }; + let (Ok(faces), Ok(mesh)) = (b.body.faces(tol), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol))) else { continue }; for f in faces { let Some(fnrm) = f.plane_normal else { continue }; if fnrm.dot(n) < 1.0 - 1e-6 { @@ -7175,13 +6799,13 @@ fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> } } } - match best { + Ok(match best { Some((_, off)) => { let shift = off - picked.origin.dot(n); (picked.offset(shift), None) } None => (*picked, Some("the face the sketch was on is gone; the sketch stays where it was".into())), - } + }) } /// A chamfer, equal or by its second distance or angle. @@ -7201,11 +6825,22 @@ fn chamfer_with( }; Ok(match side { Some(s) => kernel::chamfer_sides(b, edges, d, s, flip)?, - None => kernel::chamfer(b, edges, d)?, + None => match kernel::chamfer(b, edges, d) { + Err(kernel::KernelError::TooLarge(why)) => return Err(with_largest_fit(why, "distance", || kernel::chamfer_max(b, edges, d)).into()), + other => other?, + }, }) } -fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState, warning: &mut Option) -> Result<()> { +fn eval_feature( + doc: &Document, + vals: &BTreeMap, + f: &Feature, + st: &mut ModelState, + warning: &mut Option, + import_report: &mut Option>, + repair: &mut Option>, +) -> Result<()> { // Its tools meet bodies in other placements where those are shown (#3383). let _frames = ToolFrames::install(doc, f, st); match &f.kind { @@ -7256,7 +6891,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // component's bodies moved into its frame: placing every body of a large // assembly again is what made each sketch edit as slow as the design is big. None if !plane_reads_geometry(plane) && sketch.links.is_empty() => std::borrow::Cow::Borrowed(st), - None => state_in_frame(doc, st, f.component), + None => state_in_frame(doc, st, f.component)?, }; let (plane, face_warning) = match (anchor, plane) { (Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?, @@ -7264,7 +6899,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: (None, plane) if crate::sheet::plane_sheet_face(plane).is_some() => { (doc.resolve_plane_in(vals, &sheet_face_plane_in_frame(doc, st, f.component, plane)?, 0, Some(&fst))?, None) } - (None, PlaneRef::Face { plane: picked, at, name, anchor: None }) => face_plane(&fst, picked, *at, name.as_deref()), + (None, PlaneRef::Face { plane: picked, at, name, anchor: None }) => face_plane(&fst, picked, *at, name.as_deref())?, (None, other) => (doc.resolve_plane_in(vals, other, 0, Some(&fst))?, None), }; let mut sk = sketch.clone(); @@ -7272,8 +6907,8 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // ones its expressions give come first. doc.apply_text_values(vals, &mut sk)?; let mut warns = match anchor { - Some(anchor) => crate::project::refresh_face_anchor_links(doc, vals, &fst, &plane, &mut sk, anchor), - None => crate::project::refresh_links(doc, vals, &fst, &plane, &mut sk), + Some(anchor) => crate::project::refresh_face_anchor_links(doc, vals, &fst, &plane, &mut sk, anchor)?, + None => crate::project::refresh_links(doc, vals, &fst, &plane, &mut sk)?, }; drop(fst); sk.refresh_offsets()?; @@ -7314,7 +6949,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: | FeatureKind::Sweep { operation, targets, .. } => { let mut constructor = None; let mut to_body = None; - let tools = feature_tools_with_constructor(doc, vals, f, st, &mut constructor, &mut to_body)?; + let tools = feature_tools_with_constructor(doc, vals, f, st, &mut constructor, &mut to_body, warning)?; // Cuts through sheet metal become cut-outs of its flat pattern. if matches!(operation, Operation::Cut | Operation::Intersect) && matches!(f.kind, FeatureKind::Extrude { .. }) && !st.sheets.is_empty() { let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); @@ -7323,16 +6958,30 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: return apply_beside_sheet_cut(doc, st, f, tools, *operation, &crate::plain(targets), &handled); } } + // A join one sheet thick in the plane of a panel becomes part of that panel. A Join to an + // object (#6424) is left to the generic path below, which joins the object as well. + if *operation == Operation::Join && to_body.is_none() && matches!(f.kind, FeatureKind::Extrude { .. }) && !st.sheets.is_empty() { + let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); + if !more::sheet_join(f, st, &bodies, &crate::plain(targets), constructor.as_ref())?.is_empty() { + return Ok(()); + } + } // A Join extrude to an object joins that object too (#6424): the tool and the body // it runs to are one body, not only the body the profile was sketched on. let extra: Vec = if *operation == Operation::Join { to_body.into_iter().collect() } else { Vec::new() }; apply_traced_with(doc, st, f, tools, *operation, &crate::plain(targets), &extra) } - FeatureKind::Hole { thread, thread_depth, diameter, handedness, .. } => { + FeatureKind::Hole { thread, thread_depth, diameter, hand, modeled, ease_out, .. } => { let thread_depth = thread_depth.as_ref().map(|d| val(vals, d, Kind::Length)).transpose()?; if thread_depth.is_some() && thread.is_none() { return Err(DocError::Invalid("thread depth requires a tapped hole".into())); } + if *modeled && thread.is_none() { + return Err(DocError::Invalid("a modelled thread needs a tapped hole".into())); + } + if ease_out.is_some() && !*modeled { + return Err(DocError::Invalid("a runout is cut only on a modelled thread".into())); + } if thread_depth.is_some_and(|d| !d.is_finite() || d <= 0.0) { return Err(DocError::Invalid("thread depth must be finite and positive".into())); } @@ -7341,21 +6990,55 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let handled = sheet_hole_cut(st, f, &tools, warning)?; let tools: Vec = tools.into_iter().map(|(tool, _)| tool).collect(); if handled.is_empty() { + // A hole moved off the material (a changed position, parameter or sketch point) + // cuts nothing: it says so, as a pattern does of its copies (#10701). + let missed = tools.iter().filter(|tool| hole_misses(st, f, &tool.body)).count(); + let total = tools.len(); + let targets: Vec = hole_targets(st, f).iter().map(|b| b.name.clone()).collect(); apply_traced(doc, st, f, tools, Operation::Cut, &[])?; + match (missed, total) { + (0, _) => {} + (_, 1) => append_warning(warning, "the hole removes no material".into()), + _ => append_warning(warning, format!("{missed} of {total} holes remove no material")), + } + // A hole wider than the part takes all of it away (#10702): almost never what a + // hole means, so it says which bodies are gone. + let gone: Vec<&str> = targets.iter().map(String::as_str).filter(|n| st.body(n).is_none()).collect(); + if !gone.is_empty() { + append_warning(warning, format!("the hole removes all of {}", gone.join(", "))); + } } else { apply_beside_sheet_cut(doc, st, f, tools, Operation::Cut, &[], &handled)?; } if let Some(d) = thread { // Find the bore beyond any entry recess, including shallow and through holes. let r = val(vals, diameter, Kind::Length)? / 2.0; - let parallel_pipe = crate::pipe_thread_catalog::parse_pipe_thread(d).is_some(); + // A pipe thread's wall must be found: no fallback place on a guessed wall. + let pipe = crate::parse_tapped_thread(d).is_some_and(|t| { + matches!( + t.family, + crate::TappedThreadFamily::G | crate::TappedThreadFamily::Rp | crate::TappedThreadFamily::Rc | crate::TappedThreadFamily::Npt + ) + }); + let ease = thread::runout(vals, ease_out)?; for p in spots { - let wall = if parallel_pipe { + let wall = if pipe { parallel_tapped_wall(st, p, dir, r).ok_or_else(|| DocError::Invalid("no cylindrical pipe-thread wall remains".into()))? } else { parallel_tapped_wall(st, p, dir, r).unwrap_or(p + dir.any_perp() * r + dir * (r * 0.5)) }; - let mut t = thread_on_impl(st, f.id, wall, Some(d), None, true, false, *handedness)?; + let ask = thread::ThreadAsk { designation: Some(d), tapped: true, hand: *hand, ..Default::default() }; + if *modeled { + // Cut from the entry, as deep as `thread_depth` or along the whole wall: + // at a blind hole's bottom the groove stops clear of it, or fades out + // before it with a runout. + let extent = thread_depth.map_or(thread::Extent::Full, thread::Extent::Length); + let ask = thread::ThreadAsk { modeled: true, extent, from: Some(p), ease_out: ease, ..ask }; + let on = thread_on(st, f.id, wall, &ask)?; + thread::cut(st, on, (crate::thread_forms::ThreadTip::None, None, None))?; + continue; + } + let mut t = thread_on(st, f.id, wall, &ask)?.info; if let Some(depth) = thread_depth { let available = t.end - t.start; if depth > available { @@ -7378,47 +7061,15 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } Ok(()) } - FeatureKind::Thread { face, designation, length, modeled, handedness } => { - let l = match length { - Some(e) => Some(val(vals, e, Kind::Length)?), - None => None, - }; - let t = thread_on(st, f.id, face.0, designation.as_deref(), l, *modeled, *handedness)?; - if !*modeled { - st.threads.push(t); - return Ok(()); - } - let i = st.bodies.iter().position(|b| b.name == t.body).ok_or_else(|| DocError::Invalid("threaded body".into()))?; - let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; - let cyl = kernel::cylinder_face_at(&mb.body, face.0).ok_or_else(|| DocError::Invalid("no cylindrical face there to thread".into()))?; - let tol = t.pitch * 1e-3; - // A shaft thicker than the thread is turned down to its major diameter first. - let input = mb.traced(); - let (input, radius) = match thread_turn(&t, &cyl, &mb)? { - Some(ring) => { - let turned = kernel::boolean(&input.body, &ring.body, BoolOp::Cut)? - .ok_or_else(|| DocError::Invalid("turning the shaft down removed everything".into()))?; - (Traced::step(turned, &[&input, &ring]), t.major_diameter / 2.0) - } - None => (input, cyl.radius), - }; - let groove = thread_groove(&t, radius, ((t.start - cyl.start).abs() < tol, (t.end - cyl.end).abs() < tol))?; - // The B-rep boolean can't take helical walls in reasonable time: the body is cut - // faceted (curved faces within a two-hundredth of the pitch). - let nb = kernel::faceted_boolean(&input.body, &groove, BoolOp::Cut, t.pitch * 0.005)? - .ok_or_else(|| DocError::Invalid("the thread removed everything".into()))?; - // The groove's faces are its triangles, with no role to name them by. - let groove = crate::lineage::Lineage::unnamed_faces(groove.triangles.len()); - let lineage = input.lineage.and_then(|l| crate::lineage::Lineage::step(&nb, &[&l, &groove])); - let nb = Traced { body: nb, lineage }; - if let Some(slot) = st.bodies.get_mut(i) { - *slot = ModelBody::traced_new(mb.name, nb, mb.feature); - } - Ok(()) - } + FeatureKind::Thread { .. } => thread::eval(doc, vals, f, st, warning), FeatureKind::Shell { faces, thickness, body, direction, tangent_chain } => { let t = val(vals, thickness, Kind::Length)?; - let i = body_at(st, body, &crate::plain(faces))?; + // No face opened (a closed hollow body) picks no body: the one there is, or the named one. + let i = match (faces.is_empty(), body, st.bodies.len()) { + (true, None, 1) => 0, + (true, None, _) => return Err(DocError::Invalid("a shell that opens no face needs the body named".into())), + _ => body_at(st, body, &crate::plain(faces))?, + }; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; let picks = crate::plain(faces); let open = if *tangent_chain { @@ -7456,7 +7107,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // The cavity's faces are the shell's inner walls, named after the faces they offset. let inner = mb.before_as(crate::lineage::Operand::Inner(mb.name.clone())); let cavity = if inn > 0.0 { Traced::step(kernel::offset_faces(&mb.body, &walls, -inn)?, &[&inner]) } else { inner }; - let cavity = Traced::step(kernel::offset_faces(&cavity.body, &open, 2.0 * t + 1.0)?, &[&cavity]); + // The open faces pushed out of the way (none: the cavity stays sealed inside). + let cavity = + if open.is_empty() { cavity } else { Traced::step(kernel::offset_faces(&cavity.body, &open, 2.0 * t + 1.0)?, &[&cavity]) }; let cut = kernel::boolean(&outer.body, &cavity.body, BoolOp::Cut)? .ok_or_else(|| DocError::Invalid("the shell removed everything".into()))?; (cut, vec![outer, cavity]) @@ -7500,25 +7153,40 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // A plane of numbers alone reads no body: placing them all is the design's size. None if plane_is_fixed(plane) => doc.resolve_plane_in(vals, plane, 0, Some(st))?, // Picks on bodies of other (moved) components are where those bodies are shown. - None => doc.resolve_plane_in(vals, plane, 0, Some(&construction_state(doc, st, f.component)))?, + None => doc.resolve_plane_in(vals, plane, 0, Some(&*construction_state(doc, st, f.component)?))?, }; - st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Plane(pl) }); + st.construct.push(crate::construct::Construct { + feature: f.id, + name: f.name.clone(), + geom: crate::construct::ConstructGeom::Plane(pl), + bodies: Vec::new(), + }); Ok(()) } FeatureKind::ConstructionAxis { def } => { - let (origin, dir) = - crate::construct::resolve_axis(&crate::construct::Ctx { doc, vals, st: &construction_state(doc, st, f.component), depth: 0 }, def)?; + let cst = construction_state(doc, st, f.component)?; + let ctx = crate::construct::Ctx { doc, vals, st: &cst, depth: 0 }; + let (origin, dir) = crate::construct::resolve_axis(&ctx, def)?; + let bodies = crate::construct::source_bodies(&ctx, &def.refs()); st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Axis { origin, dir }, + bodies, }); Ok(()) } FeatureKind::ConstructionPoint { def } => { - let p = - crate::construct::resolve_point(&crate::construct::Ctx { doc, vals, st: &construction_state(doc, st, f.component), depth: 0 }, def)?; - st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Point(p) }); + let cst = construction_state(doc, st, f.component)?; + let ctx = crate::construct::Ctx { doc, vals, st: &cst, depth: 0 }; + let p = crate::construct::resolve_point(&ctx, def)?; + let bodies = crate::construct::source_bodies(&ctx, &def.refs()); + st.construct.push(crate::construct::Construct { + feature: f.id, + name: f.name.clone(), + geom: crate::construct::ConstructGeom::Point(p), + bodies, + }); Ok(()) } FeatureKind::BoundaryFill { tools, cells, operation, remove_tools } => { @@ -7573,7 +7241,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: (None, Some(sid)) => { let ss = st.sketch(sid.0).ok_or_else(|| DocError::Unknown(format!("sketch {sid}")))?; // Each curve's exact segments (lines and arcs split by their own plane and cylinder). - let curves: Vec> = (0..ss.sketch.curves.len()) + let curves: Vec> = (0..ss.sketch.curves.len()) .filter(|ci| ss.sketch.curves.get(*ci).is_some_and(|c| !c.construction)) .map(|ci| ss.sketch.segs(ci)) .filter(|segs| !segs.is_empty()) @@ -7691,6 +7359,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } let m = mirror_matrix(&pl); let mut output = 0; + // Copies evaluated on each frame a placement is dragged, which nothing cuts or joins: + // searching their revolved faces again was nearly all that took. + let shown_only = !*combine && !placements.is_empty() && placement_reuse::copies_only_shown(doc, f); for (k, n) in bodies.iter().enumerate() { let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?; let Some(mb) = st.bodies.get(i).cloned() else { continue }; @@ -7707,7 +7378,12 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } None => (None, m, m), }; - let mirrored = moved_copy(&mb, kernel::transform_matrix(&mb.body, if *combine { own } else { copy })?, 1); + let copied = if shown_only { + kernel::place_matrix(&mb.body, copy) + } else { + kernel::transform_matrix(&mb.body, if *combine { own } else { copy }) + }; + let mirrored = moved_copy(&mb, copied?, 1); if *combine { let joined = kernel::boolean(&mb.body, &mirrored.body, BoolOp::Union)? .ok_or_else(|| DocError::Invalid("the mirror join produced nothing".into()))?; @@ -7729,6 +7405,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let name = copy_body_name(st, f, output, &mb.name); copy_sheet(st, &mb.name, &name, ©); let mut body = ModelBody::traced_new(name, mirrored, f.id); + if !placements.is_empty() { + body.mirrored_mesh = placed_mesh::PlacedMesh::mirrored(&mb, &body.body, ©).map(Arc::new); + } if let Some(c) = component.filter(|c| *c != f.component) { // Kept in that component as a moved body is (and through later features). body.component = c; @@ -7751,6 +7430,13 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } // Each edge is found on its own body (picked over several bodies, the edges of each // are blended on it), all against the bodies as they were before this feature. + // Corner setbacks likewise: SMLib sets back the corners of constant-radius rounds. + if let FeatureKind::Fillet { setbacks, style, fit, .. } = &f.kind + && !setbacks.is_empty() + && (!matches!(style, crate::FilletStyle::Constant) || !matches!(fit, crate::FilletFit::Exact)) + { + return Err(DocError::Invalid("corner setbacks are built for a constant-radius fillet (type: constant, fit: exact) only".into())); + } let on = blend_bodies(st, f, body, &crate::plain(edges))?; let mut groups: Vec<(usize, Vec)> = Vec::new(); for (i, ti) in on.iter().enumerate() { @@ -7761,16 +7447,30 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } let (mut found, mut notes, mut fitted, mut tapered_all) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); let mut reduced = false; + // The kernel blends exactly the edges given: the feature adds each one's tangent + // chain when it asks for it. A radius law runs along one edge, so a variable or + // spline round takes its edge alone. + let chain = match &f.kind { + FeatureKind::Fillet { tangent_chain, style, .. } => { + *tangent_chain && !matches!(style, crate::FilletStyle::Variable { .. } | crate::FilletStyle::Spline { .. }) + } + FeatureKind::Chamfer { tangent_chain, .. } => *tangent_chain, + _ => false, + }; let mut blended = Vec::new(); for (ti, idx) in &groups { let Some(mb) = st.bodies.get(*ti) else { return Err(DocError::Invalid("body".into())) }; let mut w = None; let edges = blend_edges_on(mb, f, edges, idx, &mut w)?; + let picked = edges.len(); + let edges = if chain { kernel::tangent_chain(&mb.body, &edges)? } else { edges }; if let Some(w) = w { notes.push(w); } let mut note = None; - let (nb, used, tapered) = blend_body(vals, f, mb, &edges, r, &mut note)?; + let propagated = edges.len() > picked; + let (nb, used, tapered) = + blend_body(vals, f, mb, &edges, r, &mut note).map_err(|e| if propagated { with_propagation_hint(e) } else { e })?; if let Some(n) = note { notes.push(n); } @@ -7987,6 +7687,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: *slot = ModelBody::traced_new(mb.name.clone(), Traced::step(nb, &[&mb.traced()]), mb.feature); } } + if !*copy { + move_constructions_with(doc, st, bodies, &crate::rigid(t, Vec3::ZERO, axis, ang)); + } Ok(()) } FeatureKind::MeshConvert { body, tolerance } => { @@ -8003,6 +7706,30 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: *target = result; Ok(()) } + FeatureKind::Repair { body, gap, patch_holes } => { + let gap = val(vals, gap, Kind::Length)?; + let index = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; + let source = st.bodies.get(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; + let (repaired, report) = kernel::repair(&source.body, &kernel::RepairOptions { gap, patch_holes: *patch_holes })?; + let repaired = repaired.with_color(source.body.color()); + let result = ModelBody::new(source.name.clone(), repaired, source.feature); + let mut left: Vec = + report.refused.iter().map(|r| format!("SMLib still refuses face {} ({:?}): {}", r.face + 1, r.surface, r.why)).collect(); + left.extend( + report + .holes + .iter() + .filter(|h| !h.patched) + .map(|h| h.why.clone().unwrap_or_else(|| format!("a hole of {} edges is left open", h.edges.len()))), + ); + if !left.is_empty() { + *warning = Some(left.join("; ")); + } + let target = st.bodies.get_mut(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; + *target = result; + *repair = Some(Arc::new(report)); + Ok(()) + } FeatureKind::MeshImport { meshes, .. } => { for (k, (name, b)) in mesh_bodies(meshes)?.into_iter().enumerate() { let name = copy_body_name(st, f, k, &name); @@ -8025,6 +7752,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let shown: Vec<&str> = imp.warnings.iter().take(3).map(String::as_str).collect(); let more = if n > 3 { format!(" (+{} more)", n - 3) } else { String::new() }; *warning = Some(format!("{}{more}", shown.join("; "))); + *import_report = Some(Arc::new(imp.report.clone())); } Ok(()) } @@ -8115,13 +7843,43 @@ fn unique_body_name(st: &ModelState, base: &str) -> String { /// What construction geometry of component `comp` is built on: the model as that component sees /// it, other components' bodies where they are placed. In the root, every placement of a /// component (its pasted instances too) is there, as the viewport shows it. -fn construction_state<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std::borrow::Cow<'a, ModelState> { +fn construction_state<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> Result> { if comp == 0 && !doc.occurrences.is_empty() { - return std::borrow::Cow::Owned(world_state(doc, st)); + return Ok(std::borrow::Cow::Owned(world_state(doc, st)?)); } state_in_frame(doc, st, comp) } +/// Construction axes and points built on bodies a Move moves go with them (#10127): an axis +/// through a cylinder turns with the cylinder, as its faces do. Only those built from the moved +/// bodies alone (`Construct::bodies`) follow; one also held by a fixed point, a plane or another +/// body stays. `m` is the move in the bodies' own frame; each construction is kept in its +/// component's frame (`construction_state`), so the move is carried over into that frame. +fn move_constructions_with(doc: &Document, st: &mut ModelState, moved: &[crate::BodyName], m: &Mat) { + let frame_of = |feature: u64| { + let comp = doc.feature(feature).map(|f| f.component).unwrap_or(0); + if comp == 0 && !doc.occurrences.is_empty() { crate::IDENTITY } else { doc.component_transform(comp) } + }; + let world: BTreeMap<&str, Mat> = + st.bodies.iter().filter(|b| moved.iter().any(|n| *n == b.name)).map(|b| (b.name.as_str(), body_world(doc, b))).collect(); + let mut placed = Vec::new(); + for (k, c) in st.construct.iter().enumerate() { + let Some(body) = c.bodies.first().and_then(|b| world.get(b.as_str())) else { continue }; + if !c.bodies.iter().all(|b| world.contains_key(b.as_str())) { + continue; + } + let frame = frame_of(c.feature); + let (Some(body_inv), Some(frame_inv)) = (crate::mat_inverse(body), crate::mat_inverse(&frame)) else { continue }; + let in_frame = crate::mat_mul(&crate::mat_mul(&frame_inv, body), &crate::mat_mul(m, &crate::mat_mul(&body_inv, &frame))); + placed.push((k, c.geom.placed(&in_frame))); + } + for (k, geom) in placed { + if let Some(c) = st.construct.get_mut(k) { + c.geom = geom; + } + } +} + /// Whether `plane` is given by the origin planes and numbers alone. fn plane_is_fixed(plane: &PlaneRef) -> bool { match plane { @@ -8142,6 +7900,7 @@ fn plane_reads_geometry(plane: &PlaneRef) -> bool { PlaneRef::ThroughPoint { .. } | PlaneRef::Midplane { .. } | PlaneRef::TwoEdges { .. } + | PlaneRef::AxisPoint { .. } | PlaneRef::ThreePoints { .. } | PlaneRef::Tangent { .. } | PlaneRef::AlongPath { .. } @@ -8260,7 +8019,7 @@ fn tool_in(tool: &Traced, m: Option) -> Result { } } -pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std::borrow::Cow<'a, ModelState> { +pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> Result> { state_in_frame_at(doc, st, comp, doc.component_transform(comp)) } @@ -8269,30 +8028,39 @@ pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std: /// (`comp`): the model as that component sees it, a target in another, moved component where it /// is shown (#928). Other face points are picks, kept in the frame of the body they lie on: the /// model itself. -pub fn face_point_state<'a>(doc: &Document, st: &'a ModelState, kind: &FeatureKind, comp: u64) -> std::borrow::Cow<'a, ModelState> { +pub fn face_point_state<'a>(doc: &Document, st: &'a ModelState, kind: &FeatureKind, comp: u64) -> Result> { match kind { FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. } => state_in_frame(doc, st, comp), - _ => std::borrow::Cow::Borrowed(st), + _ => Ok(std::borrow::Cow::Borrowed(st)), } } /// The names of the faces a feature's face points lie on (empty where none), found in /// [`face_point_state`]. A To / From point is named after the nearest face over every body, the /// one `object_height` resolves it to, not the first body with a face within tolerance: a part -/// resting a hair from the picked face would otherwise take its name. -pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, comp: u64) -> Vec { +/// resting a hair from the picked face would otherwise take its name. Another feature's point is +/// named on the bodies of the feature's own component first: each component's bodies lie in its +/// own coordinates there, where a part inserted twice has a face at the same point in each. +pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, comp: u64) -> Result> { let pts = kind.face_points(); if !matches!(kind, FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. }) { - return crate::naming::face_names_at(st, &pts); + let own = ModelState { bodies: st.bodies.iter().filter(|b| doc.model_body_component(b) == comp).cloned().collect(), ..ModelState::default() }; + let names = crate::naming::face_names_at(&own, &pts); + return Ok(names + .into_iter() + .zip(&pts) + .map(|(name, p)| if name.is_empty() { crate::naming::face_names_at(st, std::slice::from_ref(p)).pop().unwrap_or_default() } else { name }) + .collect()); } - let fst = face_point_state(doc, st, kind, comp); + let fst = face_point_state(doc, st, kind, comp)?; let normal = match kind { FeatureKind::Extrude { sketch, .. } => { st.sketch(sketch.0).and_then(|ss| sketch_in_feature_frame(doc, ss, comp).ok()).map(|ss| ss.plane.normal()) } _ => None, }; - pts.iter() + Ok(pts + .iter() .map(|p| { fst.bodies .iter() @@ -8305,16 +8073,16 @@ pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, com .and_then(|(_, b, fi)| crate::naming::face_names(b).get(fi).cloned()) .unwrap_or_default() }) - .collect() + .collect()) } /// As `state_in_frame`, using the exact active placement for its shared source geometry. -pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, frame: Mat) -> std::borrow::Cow<'a, ModelState> { +pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, frame: Mat) -> Result> { use std::borrow::Cow; if doc.occurrences.is_empty() && doc.body_offsets.is_empty() { - return Cow::Borrowed(st); + return Ok(Cow::Borrowed(st)); } - let Some(inv) = crate::mat_inverse(&frame) else { return Cow::Borrowed(st) }; + let inv = crate::mat_inverse(&frame).ok_or_else(|| DocError::Invalid(format!("component {comp}'s frame cannot be inverted")))?; let comp_of_feature = |id: u64| doc.feature(id).map(|f| f.component).unwrap_or(0); let rel = |c: u64, body: Option<&str>| { let m = crate::mat_mul(&inv, &if c == comp { frame } else { doc.component_transform(c) }); @@ -8335,13 +8103,12 @@ pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, fram let world_wires_need_mapping = !crate::is_identity(&inv) && st.sketches.iter().any(|sketch| sketch.sketch.wires.iter().any(|wire| wire.space == solidcraft_sketch::WireSpace::World)); if body_m.iter().chain(&sketch_m).all(crate::is_identity) && !world_wires_need_mapping { - return Cow::Borrowed(st); + return Ok(Cow::Borrowed(st)); } let mut out = st.clone(); for (b, m) in out.bodies.iter_mut().zip(&body_m) { - if !crate::is_identity(m) - && let Ok(moved) = st.body_in_frame(b, m) - { + if !crate::is_identity(m) { + let moved = st.body_in_frame(b, m).map_err(|e| DocError::Invalid(format!("body `{}` cannot be moved into the frame: {e}", b.name)))?; *b = moved; } } @@ -8352,24 +8119,22 @@ pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, fram continue; } let s = Arc::make_mut(s); - if !crate::is_identity(m) - && let Some(np) = Plane::new(crate::apply_point(m, s.plane.origin), crate::apply_vector(m, s.plane.x), crate::apply_vector(m, s.plane.y)) - { - s.plane = np; + if !crate::is_identity(m) { + s.plane = placed_plane(m, &s.plane)?; } for wire in &mut s.sketch.wires { let matrix = if wire.space == solidcraft_sketch::WireSpace::Component { m } else { &inv }; map_wire(wire, matrix); } } - Cow::Owned(out) + Ok(Cow::Owned(out)) } /// The model placed in the world: each component's bodies, sketches, threads and construction /// geometry through every occurrence of it (bodies of the first placement keep their names; /// further instances get the occurrence path in brackets). Without components this is the model /// itself. -pub fn world_state(doc: &Document, st: &ModelState) -> ModelState { +pub fn world_state(doc: &Document, st: &ModelState) -> Result { world_state_reusing(doc, st, &mut PlacedBodies::default()) } @@ -8401,19 +8166,21 @@ impl PlacedBodies { .map(|(_, placed)| placed) } - /// The body `b` placed by `m`, from an earlier call when `b` is the same body as then. - fn placed(&self, b: &ModelBody, m: &crate::Mat, name: String) -> ModelBody { + /// The body `b` placed by `m`, from an earlier call when `b` is the same body as then; an + /// error when it cannot be placed. + fn placed(&self, b: &ModelBody, m: &crate::Mat, name: String) -> Result { if let Some(placed) = self.taken(b, m, &name) { - return placed; - } - match kernel::place_matrix(&b.body, *m) { - Ok(body) => { - let mut fresh = ModelBody::new(name, body, b.feature); - fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new); - fresh - } - Err(_) => ModelBody::new(name, b.body.clone(), b.feature), + return Ok(placed); } + // The identity places the body as it is, without a copy through the kernel. + let body = if crate::is_identity(m) { + b.body.clone() + } else { + kernel::place_matrix(&b.body, *m).map_err(|e| DocError::Invalid(format!("body `{}` cannot be placed: {e}", b.name)))? + }; + let mut fresh = ModelBody::new(name, body, b.feature); + fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new); + Ok(fresh) } /// The body `b` placed by `m` as an earlier call placed it, when `b` is the same body as then. @@ -8512,14 +8279,23 @@ fn placed_key(b: &ModelBody, m: &crate::Mat) -> (usize, [u64; 16]) { (Arc::as_ptr(&b.mesh) as usize, bits) } +/// Whether a world state shows `b`, placed by `m`, apart from the model's body. A mirrored copy +/// always is: it is drawn from its source's opposite hand, and the model keeps its own triangles. +fn placed_apart(b: &ModelBody, m: &crate::Mat) -> bool { + !crate::is_identity(m) || b.mirrored_mesh.is_some() +} + /// [`world_state`], reusing the bodies `placed` holds from an earlier call and leaving it holding /// this call's. -pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut PlacedBodies) -> ModelState { +pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut PlacedBodies) -> Result { if doc.occurrences.is_empty() { - return st.clone(); + return Ok(st.clone()); } let mut placed_now = PlacedBodies::default(); - let comp_of_feature = |id: u64| doc.feature(id).map(|f| f.component).unwrap_or(0); + // Looked up once: every sketch, construction and tap asked the timeline, and every placement + // went through all bodies, each time searching (a large assembly paid this every command). + let feature_components: std::collections::HashMap = doc.features.iter().rev().map(|f| (f.id, f.component)).collect(); + let comp_of_feature = |id: u64| feature_components.get(&id).copied().unwrap_or(0); let first_path = |comp: u64| -> Vec { let mut path = Vec::new(); let mut c = comp; @@ -8542,11 +8318,28 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut let mut jobs = Vec::new(); let owners = doc.model_body_components(st); let names = crate::WorldNames::new(doc, st); - let bodies_of = |comp: u64| st.bodies.iter().zip(&owners).filter(move |(_, owner)| **owner == comp).map(|(b, _)| b); + let mut by_component: std::collections::HashMap> = std::collections::HashMap::new(); + for (b, owner) in st.bodies.iter().zip(&owners) { + by_component.entry(*owner).or_default().push(b); + } + let bodies_of = |comp: u64| by_component.get(&comp).into_iter().flatten().copied(); + // Each tap's component and the offset of the body it is on (the first body of that name). + let mut first_body: std::collections::HashMap<&str, (&ModelBody, u64)> = std::collections::HashMap::new(); + for (b, owner) in st.bodies.iter().zip(&owners).rev() { + first_body.insert(b.name.as_str(), (b, *owner)); + } + let tap_frames: Vec<(u64, Option<&crate::Mat>)> = st + .threads + .iter() + .map(|t| match first_body.get(t.body.as_str()) { + Some((body, owner)) => (*owner, doc.model_body_offset(body)), + None => (comp_of_feature(t.feature), None), + }) + .collect(); for (comp, path, m) in &placements { for b in bodies_of(*comp) { let bm = body_matrix(b, m); - if !crate::is_identity(&bm) { + if placed_apart(b, &bm) { jobs.push((b, bm, names.name(&b.name, *comp, path))); } } @@ -8556,7 +8349,10 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut let reused: Vec<_> = jobs.iter().map(|(b, bm, name)| placed_before.taken(b, bm, name)).collect(); let fresh: Vec<_> = jobs.iter().zip(&reused).filter(|(_, r)| r.is_none()).map(|(job, _)| job).collect(); let mut placed_fresh = kernel::map_on_threads(&fresh, 16, |(b, bm, name)| placed_before.placed(b, bm, name.clone())).into_iter(); - let mut moved = reused.into_iter().map(|r| r.or_else(|| placed_fresh.next().flatten())).zip(&jobs); + let mut moved = reused.into_iter().map(|r| match r { + Some(placed) => Some(Ok(placed)), + None => placed_fresh.next().flatten(), + }); for (comp, path, m) in placements { let primary = path == first_path(comp); let ident = crate::is_identity(&m); @@ -8564,16 +8360,16 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut let bm = body_matrix(b, &m); // Identical geometry also shares its display mesh cell with the definition. // A changed placement keeps a distinct mesh, at that placement's coordinates. - let mut placed = if crate::is_identity(&bm) { + let mut placed = if !placed_apart(b, &bm) { let mut placed = b.clone(); placed.name = names.name(&b.name, comp, &path); placed } else { - // The same order as the jobs: this body's, made above (again here if it failed). + // The same order as the jobs: this body's, made above. let placed = match moved.next() { - Some((Some(placed), _)) => placed, - Some((None, (_, _, name))) => placed_before.placed(b, &bm, name.clone()), - None => placed_before.placed(b, &bm, names.name(&b.name, comp, &path)), + Some(Some(placed)) => placed?, + Some(None) => return Err(DocError::Invalid(format!("body `{}` could not be placed (its worker failed)", b.name))), + None => return Err(DocError::Invalid(format!("body `{}` has no placement", b.name))), }; placed_now.by_source.insert(placed_key(b, &bm), (b.clone(), placed.clone())); placed @@ -8600,12 +8396,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut continue; } let mut s2 = SolvedSketch::clone(s); - if !ident { - let p = &s.plane; - if let Some(np) = Plane::new(crate::apply_point(&m, p.origin), crate::apply_vector(&m, p.x), crate::apply_vector(&m, p.y)) { - s2.plane = np; - } - } + s2.plane = placed_plane(&m, &s.plane)?; for wire in &mut s2.sketch.wires { if wire.space == solidcraft_sketch::WireSpace::Component { map_wire(wire, &m); @@ -8622,21 +8413,24 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut } } // Unlike editable sketch guides, cosmetic surfaces belong to every occurrence. - for t in st - .threads - .iter() - .filter(|t| st.body(&t.body).map(|body| doc.model_body_component(body)).unwrap_or_else(|| comp_of_feature(t.feature)) == comp) - { + for (t, (_, offset)) in st.threads.iter().zip(&tap_frames).filter(|(_, (owner, _))| *owner == comp) { let mut t2 = t.clone(); t2.body = names.name(&t.body, comp, &path); - let frame = st.body(&t.body).and_then(|body| doc.model_body_offset(body)).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m); + let frame = offset.map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m); t2.axis_point = crate::apply_point(&frame, t.axis_point); - t2.axis = crate::apply_vector(&frame, *t.axis).unit().unwrap_or(t.axis); + t2.axis = crate::apply_vector(&frame, *t.axis).unit().ok_or_else(|| DocError::Invalid("a thread's axis cannot be placed".into()))?; out.threads.push(t2); } } *placed_before = placed_now; - out + Ok(out) +} + +/// `plane` moved by the placement `m`; an error when `m` does not keep it a plane (a placement +/// that is not a rigid motion, which [`Document`] does not take). +fn placed_plane(m: &crate::Mat, plane: &Plane) -> Result { + Plane::new(crate::apply_point(m, plane.origin), crate::apply_vector(m, plane.x), crate::apply_vector(m, plane.y)) + .ok_or_else(|| DocError::Invalid("a sketch plane cannot be placed: the placement is not a rigid motion".into())) } #[cfg(test)] @@ -8713,7 +8507,7 @@ mod world_placement_cache_tests { let source = &state.bodies[0]; assert!(source.names.origin.is_some()); assert!(source.mesh.get().is_none()); - let world = world_state(&doc, &state); + let world = world_state(&doc, &state).unwrap(); let names = crate::naming::face_names(&world.bodies[0]); assert!(Arc::ptr_eq(&names, &crate::naming::face_names(source))); assert!(names.iter().all(|name| name.starts_with(&format!("F{feature}:")))); @@ -8736,7 +8530,7 @@ mod world_placement_cache_tests { state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1)); state.bodies[0].key = 1234; let source = &state.bodies[0]; - let world = world_state(&doc, &state); + let world = world_state(&doc, &state).unwrap(); assert_eq!(world.bodies.len(), 2); let first = world.body("Block").unwrap(); let second_name = doc.world_body_name(&state, "Block", component, &[second]); @@ -8759,7 +8553,7 @@ mod world_placement_cache_tests { assert!(Arc::ptr_eq(&names, &crate::naming::face_names(placed))); let original_mesh = source.mesh(); assert!(Arc::ptr_eq(&original_mesh, &first.mesh())); - let again = world_state(&doc, &state); + let again = world_state(&doc, &state).unwrap(); assert!(Arc::ptr_eq(&original_mesh, &again.body("Block").unwrap().mesh())); assert!(Arc::ptr_eq(&names, &crate::naming::face_names(again.body(&second_name).unwrap()))); } @@ -8793,6 +8587,9 @@ mod chain_tests { style: crate::FilletStyle::Constant, fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), + turn: Default::default(), + tangent_chain: true, }, None, ) @@ -8810,15 +8607,56 @@ mod chain_tests { } assert_eq!(tangent_face_chain(b, &[Vec3::new(20.0, 15.0, 20.0); 2]), pts); } + + fn fillet(at: Vec3, radius: &str, tangent_chain: bool) -> FeatureKind { + FeatureKind::Fillet { + edges: vec![crate::Position(at)], + radius: radius.into(), + body: None, + style: crate::FilletStyle::Constant, + fit: Default::default(), + corner: Default::default(), + setbacks: Vec::new(), + turn: Default::default(), + tangent_chain, + } + } + + /// A 20 box's top edge along y rounded r2, then the top front edge (along x) rounded r3: that + /// edge runs on tangentially into the round's end arc, so by default (tangent propagation) + /// the arc is rounded with it, which an r3 round on an r2 arc cannot be: refused, saying that + /// propagation blended the chain and how to blend the edge alone. With propagation off the + /// edge is rounded alone, ending on the r2 round. + #[test] + fn a_propagated_chain_that_cannot_build_says_how_to_blend_the_edge_alone() { + let build = |chain: bool| { + let mut doc = Document::new("T"); + let solid = FeatureKind::Box { + corner: crate::point_expr(Vec3::ZERO), + length: "20".into(), + width: "20".into(), + height: "20".into(), + operation: Operation::NewBody, + }; + doc.add_feature(solid, None).unwrap(); + doc.add_feature(fillet(Vec3::new(20.0, 10.0, 20.0), "2", true), None).unwrap(); + let last = doc.add_feature(fillet(Vec3::new(10.0, 0.0, 20.0), "3", chain), None).unwrap(); + let mut m = Model::new(); + m.evaluate(&doc); + (m.result(last).and_then(|r| r.error.clone()), m.state().bodies.first().map(|b| b.body.face_count())) + }; + let (on, _) = build(true); + let on = on.expect("the propagated chain is refused"); + assert!(on.contains("with it off, tangent_chain: false, only the picked edges are blended"), "{on}"); + let (off, faces) = build(false); + assert_eq!(off, None); + assert_eq!(faces, Some(8)); + } } #[cfg(test)] #[path = "eval_cost_tests.rs"] -mod cost_tests; - -#[cfg(test)] -#[path = "eval_whole_face_tests.rs"] -mod whole_face_tests; +pub(crate) mod cost_tests; #[cfg(test)] mod body_name_tests { @@ -8850,121 +8688,6 @@ mod body_name_tests { } } -#[cfg(test)] -mod coplanar_growth_tests { - use super::*; - - #[test] - fn buried_join_ends_stop_at_material_boundaries() { - let block = kernel::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 8.0)).unwrap(); - let profile = rect(2.0, 2.0, 4.0, 4.0); - let st = state(vec![block.clone()]); - let sur = Surroundings::of(&st, Operation::Join, &[]).unwrap(); - assert_eq!(trim_embedded_join_ends(&sur, &Plane::XY, &profile, 0.0, 16.0), (8.0, 16.0)); - assert_eq!(trim_embedded_join_ends(&sur, &Plane::XY, &profile, -8.0, 8.0), (-8.0, 0.0)); - // A thin sealed void between the old start and the rib's top must still - // be filled by the join. The remaining tool must start before that void. - let void = kernel::box_solid(Vec3::new(1.0, 1.0, 3.01), Vec3::new(5.0, 5.0, 3.02)).unwrap(); - let hollow = kernel::boolean(&block, &void, BoolOp::Cut).unwrap().unwrap(); - let st = state(vec![hollow]); - let sur = Surroundings::of(&st, Operation::Join, &[]).unwrap(); - let (lo, hi) = trim_embedded_join_ends(&sur, &Plane::XY, &profile, 0.0, 16.0); - assert!(lo <= 3.01, "trimming past {lo} would discard material the join adds in the void"); - assert_eq!(hi, 16.0); - let cut = Surroundings::of(&st, Operation::Cut, &[]).unwrap(); - assert_eq!(trim_embedded_join_ends(&cut, &Plane::XY, &profile, 0.0, 16.0), (0.0, 16.0)); - } - - fn state(bodies: Vec) -> ModelState { - ModelState { bodies: bodies.into_iter().enumerate().map(|(i, b)| ModelBody::new(format!("Body{i}"), b, 0)).collect(), ..Default::default() } - } - - fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Region2 { - let p = Vec2::new; - Region2 { outer: solidcraft_geom::Loop2::polygon(&[p(x0, y0), p(x1, y0), p(x1, y1), p(x0, y1)]), holes: Vec::new() } - } - - /// The rectangle `x0` … `x1` by `y0` … `y1` with its corners rounded to `rad`, counterclockwise. - fn rounded(x0: f64, y0: f64, x1: f64, y1: f64, rad: f64) -> Region2 { - use solidcraft_geom::Seg2; - let p = Vec2::new; - let quarter = std::f64::consts::FRAC_PI_2; - let arc = |cx: f64, cy: f64, k: f64| Seg2::Arc { center: p(cx, cy), radius: rad, start: k * quarter, sweep: quarter }; - let segs = vec![ - Seg2::Line { a: p(x0 + rad, y0), b: p(x1 - rad, y0) }, - arc(x1 - rad, y0 + rad, 3.0), - Seg2::Line { a: p(x1, y0 + rad), b: p(x1, y1 - rad) }, - arc(x1 - rad, y1 - rad, 0.0), - Seg2::Line { a: p(x1 - rad, y1), b: p(x0 + rad, y1) }, - arc(x0 + rad, y1 - rad, 1.0), - Seg2::Line { a: p(x0, y1 - rad), b: p(x0, y0 + rad) }, - arc(x0 + rad, y0 + rad, 2.0), - ]; - Region2 { outer: solidcraft_geom::Loop2 { segs }, holes: Vec::new() } - } - - /// The extrude's growth of `r` (a cut from the plane z = `z`, `lo` … `hi` along +z), as - /// `feature_tools_with_constructor` asks for it. - fn grown(st: &ModelState, z: f64, r: &Region2, lo: f64, hi: f64) -> (Region2, f64, f64) { - let sur = Surroundings::of(st, Operation::Cut, &[]).unwrap(); - let plane = Plane { origin: Vec3::new(0.0, 0.0, z), ..Plane::XY }; - let (l2, h2) = extend_for_coplanar(&sur, &plane, r, lo, hi); - let probe = |p: Vec2| (1..4).map(|k| plane.to_world(p) + Vec3::Z * (lo + (hi - lo) * k as f64 / 4.0)).collect::>(); - let gains = |pieces: &[[Vec2; 3]]| sur.harmless(&plane, pieces, -sur.skin, l2 + sur.skin, h2 - sur.skin); - (grow_profile_for_coplanar(&sur, r, &probe, &gains), l2, h2) - } - - /// A cut's tool still grows past the faces it lies on where all it gains is empty space: a - /// notch 10 deep into the corner of a 100 × 60 × 30 block, flush with two of its sides, - /// grows out of those sides by 0.5 % of the block's size and up out of its top by 1 %. - /// Cut into the end wall of a tray of that size, flush with the wall's inner face, the - /// strip its side would gain holds the start of the long walls: there it stays as drawn. - #[test] - fn the_tool_grows_only_where_it_gains_nothing() { - let block = kernel::box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); - let st = state(vec![block.clone()]); - let notch = rect(0.0, 0.0, 20.0, 20.0); - let (r, lo, hi) = grown(&st, 30.0, ¬ch, -10.0, 0.0); - let step = block.size() * 0.005; - for p in [Vec2::new(-0.9 * step, 10.0), Vec2::new(10.0, -0.9 * step), Vec2::new(-0.9 * step, -0.9 * step)] { - assert!(r.contains(p) && !notch.contains(p), "{p:?}: {r:?}"); - } - assert!(!r.contains(Vec2::new(20.0 + 0.1 * step, 10.0)) && !r.contains(Vec2::new(10.0, 20.0 + 0.1 * step)), "{r:?}"); - assert_eq!(lo, -10.0); - assert!((hi - block.size() * 0.01).abs() < 1e-9, "{hi}"); - - let inner = kernel::box_solid(Vec3::new(2.0, 2.0, 2.0), Vec3::new(98.0, 58.0, 40.0)).unwrap(); - let tray = kernel::boolean(&block, &inner, BoolOp::Cut).unwrap().unwrap(); - let st = state(vec![tray]); - let end_wall = rect(-1.0, -1.0, 2.0, 70.0); - assert_eq!(grown(&st, 2.0, &end_wall, 0.0, 40.0), (end_wall, 0.0, 40.0)); - } - - /// Arcs grow too (#1275), on the same terms. A cut of the whole top face of a 40 × 40 × 20 - /// block with corners rounded to 8 grows out of every side, its corners' arcs by the same step - /// as its edges. A post standing 0.1 off one corner's arc, between the points the samples - /// look at, would lose a sliver to the grown arc: there the loop stays as drawn. - #[test] - fn arcs_grow_only_where_they_gain_nothing() { - let face = rounded(0.0, 0.0, 40.0, 40.0, 8.0); - let block = kernel::extrude(&Plane::XY, std::slice::from_ref(&face), 0.0, 20.0).unwrap().remove(0); - let step = block.size() * 0.005; - let st = state(vec![block.clone()]); - let (r, _, _) = grown(&st, 20.0, &face, -5.0, 0.0); - let corner = |k: f64| Vec2::new(8.0, 8.0) + Vec2::from_angle(1.25 * std::f64::consts::PI) * (8.0 + k * step); - for q in [Vec2::new(-0.9 * step, 20.0), Vec2::new(20.0, 40.0 + 0.9 * step), corner(0.9)] { - assert!(r.contains(q) && !face.contains(q), "{q:?}: {r:?}"); - } - assert!(!r.contains(corner(1.1)), "{r:?}"); - - // The post's corner nearest the arc's centre (8, 8) lies 8.1 from it, at 190 degrees; the - // samples look at 202.5, 225 and 247.5 degrees. - let post = kernel::box_solid(Vec3::new(-2.0, 5.0, 0.0), Vec3::new(8.0 - 7.977, 8.0 - 1.407, 20.0)).unwrap(); - let st = state(vec![block, post]); - assert_eq!(grown(&st, 20.0, &face, -5.0, 0.0).0, face); - } -} - /// The parts of a body split by a plane, on its positive side first (only the non-empty ones). /// Each part's cut face is named `section` after the half-space box that cut it, so it takes an /// attachment that follows the plane (#565); the box's other faces never reach the part. @@ -8988,7 +8711,7 @@ pub fn sketch_line_plane(st: &ModelState, sketch: u64, line: &str) -> Result (*a, *b), + [solidcore_record::Seg2::Line { a, b }] => (*a, *b), _ => return Err(DocError::Invalid(format!("`{line}` is not a straight line: split by a sketch line"))), }; let (wa, wb) = (ss.plane.to_world(a), ss.plane.to_world(b)); @@ -9038,7 +8761,7 @@ mod named_face_lookup_tests { assert!(b.mesh.get().is_none(), "{} was meshed", b.name); } let h = hit.unwrap(); - assert_eq!((h.body, h.split, h.merged), (7, false, false)); + assert_eq!(h.body, 7); assert_eq!(found(hit), found(crate::naming::locate_face(&st, &name, top))); // Looking over every body names (and so meshes) them all. assert!(st.bodies.iter().all(|b| b.mesh.get().is_some())); @@ -9059,12 +8782,12 @@ mod named_face_lookup_tests { } } let moved = crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, top).unwrap(); - assert_eq!((moved.body, moved.split), (2, false)); + assert_eq!(moved.body, 2); } /// A copy of a body has its source's face names. Over every body the name finds the face on - /// both, and the one nearest the point is taken as a piece of a split face. A feature on the - /// copy takes the copy's face, whole. + /// both, and takes the one the point lies on; a point on neither finds no face (it is never + /// told apart by the nearest). A feature on the copy takes the copy's face. #[test] fn the_same_face_on_a_copy_is_not_a_piece_of_the_named_bodys_face() { let mut st = parts(2); @@ -9076,7 +8799,8 @@ mod named_face_lookup_tests { let on_copy = crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, top).unwrap(); let everywhere = crate::naming::locate_face(&st, &name, top).unwrap(); assert_eq!((on_copy.body, on_copy.face, on_copy.point), (everywhere.body, everywhere.face, everywhere.point)); - assert_eq!((on_copy.split, everywhere.split), (false, true)); assert_eq!(on_copy.note(&name), None); + assert!(crate::naming::locate_face(&st, &name, Vec3::new(15.0, 5.0, 30.0)).is_none()); + assert_eq!(crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, Vec3::new(15.0, 5.0, 30.0)).map(|hit| hit.body), Some(1)); } } diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rs index 146b57416..5e2d62f75 100644 --- a/crates/doc/src/eval_cost_tests.rs +++ b/crates/doc/src/eval_cost_tests.rs @@ -4,28 +4,49 @@ //! component into its frame, and every evaluation wrote every imported STEP file out again to //! fingerprint it, so each sketch command took longer the more parts were inserted. +use solidcraft_geom::prelude::*; use std::cell::Cell; use std::collections::BTreeMap; use std::sync::Arc; -use solidcraft_geom::{Plane, Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; use solidcraft_kernel as kernel; use solidcraft_sketch::Sketch; +use crate::eval::{PlacementReads, body_world, hash_placement, placement_digest}; use crate::*; /// Work counted on this thread: bodies moved, STEP texts digested, joint faces and bodies -/// measured. +/// measured, bodies searched for by name, features searched for by id, bodies a cut (or +/// intersect) ran its booleans on, bodies searched for the cylinder a tap marking lies on, and +/// bodies whose faces a tapped hole read for its wall. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct Counts { pub moved: usize, pub digested: usize, pub joint_faces: usize, pub measures: usize, + pub body_searches: usize, + pub feature_searches: usize, + pub cut: usize, + pub cylinder_search: usize, + pub tapped_wall: usize, } thread_local! { - static COUNTS: Cell = const { Cell::new(Counts { moved: 0, digested: 0, joint_faces: 0, measures: 0 }) }; + static COUNTS: Cell = const { + Cell::new(Counts { + moved: 0, + digested: 0, + joint_faces: 0, + measures: 0, + body_searches: 0, + feature_searches: 0, + cut: 0, + cylinder_search: 0, + tapped_wall: 0, + }) + }; } pub(super) fn count(f: impl FnOnce(&mut Counts)) { @@ -36,6 +57,33 @@ pub(super) fn count(f: impl FnOnce(&mut Counts)) { }); } +thread_local! { + static WRITTEN: Cell = const { Cell::new(0) }; +} + +/// A feature written out on this thread to be fingerprinted. +pub(super) fn count_written() { + WRITTEN.with(|c| c.set(c.get() + 1)); +} + +/// The features `f` writes out on this thread to fingerprint them. +fn written(f: impl FnOnce()) -> usize { + WRITTEN.with(|c| c.set(0)); + f(); + WRITTEN.with(Cell::get) +} + +/// A search on this thread through all of a design's features for one. +pub(crate) fn count_feature_search() { + count(|c| c.feature_searches += 1); +} + +/// The searches `f` makes on this thread through all features or all bodies. +fn searched(f: impl FnOnce()) -> usize { + let n = counted(f); + n.feature_searches + n.body_searches +} + /// The work `f` does on this thread. fn counted(f: impl FnOnce()) -> Counts { COUNTS.with(|c| c.set(Counts::default())); @@ -143,6 +191,25 @@ fn joint_face_measurements_never_follow_a_replaced_body_or_stale_offset() { assert_eq!(work.joint_faces, 0, "offsets are applied after the shared face measurements"); } +/// Every solve of a drag resolves its edge origins again: they share the joint faces' one +/// measurement, as a face origin does, instead of tessellating the whole body each time. +#[test] +fn an_edge_origin_measures_its_faces_once() { + use crate::joints::{JointOrigin, Snap}; + let doc = Document::new("edge origin"); + let mut state = ModelState::default(); + state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(), 0)); + let pick = Vec3::new(5.0, 0.0, 10.0); + let origin = JointOrigin { occurrence: 0, snap: Snap::Edge { pick, edge: None, face: None, corner: None, axis: None } }; + let work = counted(|| { + for _ in 0..8 { + let frame = joints::resolve_origin(&doc, &state.clone(), &origin).unwrap(); + assert!(apply_point(&frame, Vec3::ZERO).dist(pick) < 1e-9); + } + }); + assert_eq!(work.joint_faces, 1, "a solve must not measure the faces again: {work:?}"); +} + /// `parts` imported files of two boxes each, every one in its own component placed away from /// the origin (as inserted parts are). fn placed_imports(parts: usize) -> Document { @@ -248,7 +315,7 @@ fn sketch_on_a_turned_occurrence() -> (Document, Model, u64, u64, FaceAnchor, Pl let state = model.state(); let raw = state.bodies.first().unwrap(); let index = raw.body.face_sources().unwrap().iter().position(|s| matches!(s, Some(kernel::FaceSource::Box { axis: 2, high: true, .. }))).unwrap(); - let world = world_state(&doc, &state); + let world = world_state(&doc, &state).unwrap(); let shown = world.bodies.first().unwrap(); let picked = shown.body.face_plane(index).unwrap(); let anchor = doc.capture_face_anchor(raw, index, &picked, &path, 0, &[]).unwrap(); @@ -358,6 +425,132 @@ fn an_imported_file_is_fingerprinted_by_its_text() { assert_eq!(model.state().bodies.len(), 3); } +/// Pinning body names fingerprints the timeline again only from the first renamed feature on +/// (`Model::pinned_prefix`), and gives the fingerprints the full pass gives: random pins +/// on a timeline of boxes, cuts, patterns of features (one placed before its source, as one made +/// with the timeline rolled back is), a suppressed feature and a history marker, after an +/// evaluation and after earlier pins. +#[test] +fn pinning_body_names_fingerprints_as_the_full_pass_does() { + let kind = |v: serde_json::Value| serde_json::from_value::(v).unwrap(); + let mut doc = Document::new("pins"); + let mut ids = Vec::new(); + for i in 0..10 { + let x = 20.0 * i as f64; + let b = + kind(serde_json::json!({"type": "box", "corner": [x, 0.0, 0.0], "length": "10", "width": "10", "height": "10", "operation": "new_body"})); + ids.push(doc.add_feature(b, None).unwrap()); + if i % 3 == 1 { + let c = kind( + serde_json::json!({"type": "cylinder", "axis": [0.0, 0.0, 1.0], "base": [x + 5.0, 5.0, -1.0], "height": "12", "radius": "2", "operation": "cut"}), + ); + ids.push(doc.add_feature(c, None).unwrap()); + } + } + let circular = |features: Vec| { + kind(serde_json::json!({"type": "pattern", "features": features, "bodies": [], + "pattern": {"type": "circular", "angle": "360 deg", "axis": [0.0, 0.0, 1.0], "count": "3", "origin": [0.0, -40.0, 0.0]}})) + }; + ids.push(doc.add_feature(circular(vec![ids[2]]), None).unwrap()); + // A pattern of a later feature, placed early in the timeline. + let early = doc.add_feature(circular(vec![ids[9]]), None).unwrap(); + let at = doc.features.iter().position(|f| f.id == early).unwrap(); + let f = doc.features.remove(at); + doc.features.insert(3, f); + ids.push(early); + doc.feature_mut(ids[5]).unwrap().suppressed = true; + + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n as u64) as usize + }; + let fps = |m: &Model| m.results.iter().map(|r| (r.id, r.fingerprint)).collect::>(); + let mut old = Arc::new(doc); + let mut model = Model::new(); + model.evaluate_shared(&old); + let (mut proven, mut kept) = (0, 0); + for round in 0..60 { + if round % 20 == 10 { + // From an evaluation's fingerprints again, with the marker in some rounds. + let mut d = (*old).clone(); + d.marker = (round == 30).then_some(d.features.len() - 2); + old = Arc::new(d); + model.evaluate_shared(&old); + } + let mut new = (*old).clone(); + let mut renamed = Vec::new(); + for _ in 0..1 + next(3) { + let f = &mut new.features[next(old.features.len())]; + let slot = next(3); + f.body_names.resize(f.body_names.len().max(slot + 1), String::new()); + f.body_names[slot] = format!("Pinned {round} {slot}"); + renamed.push(f.id); + } + new.reserved_body_names.insert(format!("Body{}", 100 + round)); + let new = Arc::new(new); + let start = model.pinned_prefix(&old, &renamed); + let first = new.features.iter().position(|f| renamed.contains(&f.id)).unwrap(); + assert!(start <= first, "round {round}: kept {start} past the first renamed feature {first}"); + proven += usize::from(start > 0); + kept += start; + let mut partial = model.clone(); + partial.refingerprint_shared(&new, start); + let mut full = model.clone(); + full.refingerprint_shared(&new, 0); + assert_eq!(fps(&partial), fps(&full), "round {round}"); + assert_ne!(fps(&partial), fps(&model), "round {round}: the names are fingerprinted"); + // The pinned fingerprints prove themselves for the next pin, as the full pass's do. + assert_eq!(partial.fingerprinted.as_ref().map(|(_, d)| *d), full.fingerprinted.as_ref().map(|(_, d)| *d)); + model = partial; + old = new; + } + assert!(proven > 40 && kept > 0, "the stored fingerprints were reused: {proven} rounds, {kept} results"); + + // No proof, no reuse: results changed since, another design, or the design about to change + // in place. + let last = [*ids.last().unwrap()]; + assert!(model.pinned_prefix(&old, &last) > 0); + let mut changed = model.clone(); + changed.results[0].fingerprint ^= 1; + assert_eq!(changed.pinned_prefix(&old, &last), 0); + assert_eq!(model.pinned_prefix(&Arc::new((*old).clone()), &last), 0); + let mut forgot = model.clone(); + forgot.forget_fingerprints(); + assert_eq!(forgot.pinned_prefix(&old, &last), 0); +} + +/// A design evaluated ahead, on a worker thread of its own, fingerprints its features from the +/// texts the window's evaluation wrote: none is written out again there (the store was per +/// thread, and every ahead run started it empty), and the fingerprints are the same. +#[test] +fn an_evaluation_on_another_thread_reuses_the_written_features() { + let mut doc = Document::new("ahead"); + // Ids no other test's design uses: the store is shared by the tests running beside this one. + doc.next_id = 0x0007_e57a_4ead_0000; + for i in 0..40 { + let x = 20.0 * i as f64; + let b = serde_json::json!({"type": "box", "corner": [x, 0.0, 0.0], "length": "10", "width": "10", "height": "10", "operation": "new_body"}); + doc.add_feature(serde_json::from_value(b).unwrap(), None).unwrap(); + } + let mut window = Model::new(); + let first = written(|| window.evaluate(&doc)); + assert!(first >= doc.features.len(), "{first} written"); + let fps = |m: &Model| m.results.iter().map(|r| r.fingerprint).collect::>(); + let (doc2, mut ahead) = (doc.clone(), window.clone()); + ahead.no_cache = true; + let (work, ahead_fps) = std::thread::spawn(move || { + let work = written(|| ahead.evaluate(&doc2)); + (work, fps(&ahead)) + }) + .join() + .unwrap(); + assert_eq!(work, 0, "features written out again"); + assert_eq!(ahead_fps, fps(&window)); +} + /// A 10 mm square plate per hole along X, 4 mm thick, in component `comp`, with `holes` square /// holes cut through it by boxes drawn in component `tools` (the plate's own, usually). The /// plate's body name. @@ -500,9 +693,9 @@ fn placed_bodies_taken_as_before_keep_their_measure() { let mut state = ModelState::default(); state.bodies.push(ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2.0, 8.0).unwrap(), 1)); let mut cache = PlacedBodies::default(); - let before = world_state_reusing(&doc, &state, &mut cache); + let before = world_state_reusing(&doc, &state, &mut cache).unwrap(); let centroid = before.bodies[0].measure().unwrap().centroid; - let again = world_state_reusing(&doc, &state, &mut cache); + let again = world_state_reusing(&doc, &state, &mut cache).unwrap(); assert_eq!(counted(|| assert_eq!(again.bodies[0].measure().unwrap().centroid, centroid)).measures, 0); } @@ -647,3 +840,647 @@ fn shared_evaluation_refreshes_live_sketches_and_keeps_unknown_features_conserva assert!(model.results.iter().all(|r| r.error.is_none())); assert!(model.evaluate_shared(&doc), "an unclassified feature must keep the ordinary evaluation path"); } + +/// A saved model writes each set of sketch keys once, as the keys it sets and drops relative to +/// the set written before it (every state repeating its whole set made a 5,484-feature design's +/// model too large for its file, which then kept only some states and evaluated the rest on +/// opening). Every state reads back the keys it was evaluated with, also in a model thinned to +/// fewer states; a set that names no set before it is refused. +#[test] +fn saved_states_read_back_their_sketch_keys() { + let mut doc = Document::new("Sketch keys"); + for i in 0..4 { + doc.add_feature(line_sketch(PlaneRef::Origin { name: "XY".into() }, Vec2::new(f64::from(i) + 1.0, 1.0)), None).unwrap(); + for j in 0..3 { + let corner = point_expr(Vec3::new(f64::from(i) * 20.0, f64::from(j) * 20.0, 0.0)); + let kind = FeatureKind::Box { corner, length: "5".into(), width: "5".into(), height: "5".into(), operation: Operation::NewBody }; + doc.add_feature(kind, None).unwrap(); + } + } + let mut model = Model::new(); + model.evaluate(&doc); + let keys = |m: &Model| m.results.iter().map(|r| r.state.sketch_keys.clone()).collect::>(); + assert_eq!(model.state().sketch_keys.len(), 4); + let saved = model.saved(&doc).unwrap(); + assert_eq!(saved.records["sketch_key_sets"].as_array().unwrap().len(), 4, "one set per sketch"); + assert_eq!(saved.records["states"].as_array().unwrap().len(), doc.features.len()); + assert_eq!(keys(&Model::adopt(&doc, &saved).unwrap()), keys(&model)); + // The final state alone (every body costs more than the budget): the sets are all kept. + let pieces: Vec> = (0..saved.bodies.len()).map(|i| vec![(i, 1 << 20)]).collect(); + let (thinned, _, _) = saved.thinned(&pieces, 0).unwrap(); + assert_eq!(thinned.records["states"].as_array().unwrap().len(), 1); + assert_eq!(thinned.final_state().unwrap().sketch_keys, model.state().sketch_keys); + assert_eq!(keys(&Model::adopt(&doc, &thinned).unwrap()), keys(&model)); + // Sets and drops read as written; a base that is not an earlier set is refused. + let with_sets = |sets: serde_json::Value| SavedModel { + records: { + let mut r = saved.records.clone(); + r["sketch_key_sets"] = sets; + r + }, + bodies: saved.bodies.clone(), + }; + let first = *model.state().sketch_keys.keys().next().unwrap(); + let dropped = with_sets(serde_json::json!([ + {"set": [[first, "0000000000000001"], [7, "0000000000000002"]], "drop": []}, + {"base": 0, "set": [], "drop": []}, + {"base": 1, "set": [[8, "0000000000000003"]], "drop": [first]}, + {"base": 0, "set": [[7, "00000000000000ff"]], "drop": []}, + ])); + let want: BTreeMap = [(7, 0xff), (first, 1)].into(); + assert_eq!(dropped.final_state().unwrap().sketch_keys, want); + let dropped = with_sets(serde_json::json!([ + {"set": [[first, "0000000000000001"], [7, "0000000000000002"]], "drop": []}, + {"base": 0, "set": [], "drop": []}, + {"base": 0, "set": [], "drop": []}, + {"base": 1, "set": [[8, "0000000000000003"]], "drop": [first]}, + ])); + assert_eq!(dropped.final_state().unwrap().sketch_keys, [(7, 2), (8, 3)].into()); + for base in [3, 4] { + let sets = + serde_json::json!([{"set": [], "drop": []}, {"set": [], "drop": []}, {"set": [], "drop": []}, {"base": base, "set": [], "drop": []}]); + assert!(with_sets(sets).final_state().is_err(), "base {base}"); + } +} + +/// The dirty check and autosave compare the whole document after every edit; a scanned +/// part's shared triangles must not be read for that. A coordinate that equals nothing (not a +/// number) shows whether the shared arrays were read: only reading them makes a mesh differ +/// from its own copy. +#[test] +fn comparing_a_copied_mesh_does_not_read_its_shared_arrays() { + let mesh = MeshData { + name: "Scan".into(), + positions: Arc::from([0., 0., 0., 1., 0., 0., 0., 1., f64::NAN]), + triangles: Arc::from([0, 1, 2]), + color: None, + }; + let copy = mesh.clone(); + assert!(copy == mesh, "a copy shares the arrays and is the same mesh without reading them"); + let mut renamed = mesh.clone(); + renamed.name = "Other".into(); + assert!(renamed != mesh); + let mut coloured = mesh.clone(); + coloured.color = Some([0.2, 0.4, 0.6]); + assert!(coloured != mesh); + let unshared = MeshData { positions: Arc::from(mesh.positions.to_vec()), ..mesh.clone() }; + assert!(unshared != mesh, "arrays that are not shared still compare value by value"); + let finite = MeshData { positions: Arc::from([0., 0., 0., 1., 0., 0., 0., 1., 0.]), ..mesh.clone() }; + let equal = MeshData { positions: Arc::from(finite.positions.to_vec()), triangles: Arc::from(finite.triangles.to_vec()), ..finite.clone() }; + assert!(equal == finite, "equal values in other arrays are the same mesh"); + let flipped = MeshData { triangles: Arc::from([0, 2, 1]), ..finite.clone() }; + assert!(flipped != finite); +} + +/// `blocks` boxes, each its own body, in component `comp`, then a cut box without targets +/// through each of the first `cuts` (it cuts every body of its component). +fn blocks_with_cuts(doc: &mut Document, comp: u64, blocks: usize, cuts: usize) { + let y = 100.0 * comp as f64; + for k in 0..blocks { + let corner = point_expr(Vec3::new(20.0 * k as f64, y, 0.0)); + let kind = FeatureKind::Box { corner, length: "10".into(), width: "10".into(), height: "4".into(), operation: Operation::NewBody }; + let id = doc.add_feature(kind, None).unwrap(); + doc.feature_mut(id).unwrap().component = comp; + } + for k in 0..cuts { + let corner = point_expr(Vec3::new(20.0 * k as f64 + 4.0, y + 4.0, -1.0)); + let kind = FeatureKind::Box { corner, length: "2".into(), width: "2".into(), height: "6".into(), operation: Operation::Cut }; + let id = doc.add_feature(kind, None).unwrap(); + doc.feature_mut(id).unwrap().component = comp; + } +} + +#[test] +fn an_evaluation_from_the_cache_does_not_search_the_bodies_for_each_cut() { + // Each cut reads where every body of its component is placed; looking each one up by name + // made an evaluation quadratic in the bodies, even with every feature taken from the cache. + let searches = |blocks: usize| { + let mut doc = Document::new("blocks"); + blocks_with_cuts(&mut doc, 0, blocks, 3); + let mut model = Model::new(); + model.evaluate(&doc); + assert!(model.results.iter().all(|r| r.error.is_none()), "{:?}", model.results.iter().find(|r| r.error.is_some())); + let work = counted(|| model.evaluate(&doc)); + assert_eq!(model.last_recomputed, 0); + work.body_searches + }; + let (few, many) = (searches(4), searches(24)); + assert_eq!(few, many, "searches grew with the bodies: {few} for 4 blocks, {many} for 24"); +} + +/// The bodies part of the placement digest as it was before the bodies were looked up once: +/// each body searched by name, placed through [`body_world`]. +fn digest_searching_each_body(doc: &Document, f: &Feature, st: &ModelState) -> u64 { + use std::hash::{Hash, Hasher}; + let mut reads = PlacementReads::default(); + reads.drawn_targets(Some(st), f); + let inverse = mat_inverse(&doc.component_transform(f.component)).unwrap(); + let mut h = std::collections::hash_map::DefaultHasher::new(); + for name in &reads.bodies { + name.hash(&mut h); + match st.body(name) { + Some(b) => hash_placement(&mat_mul(&inverse, &body_world(doc, b)), &mut h), + None => u8::MAX.hash(&mut h), + } + } + h.finish() | 1 +} + +#[test] +fn looking_bodies_up_once_keeps_every_placement_digest() { + // Two parts placed apart, a body moved into the other part and one moved within its part: + // each cut's digest is the one searching each body gave, bit for bit, so saved caches stay + // valid. + let mut doc = Document::new("digests"); + let a = doc.add_component(Some("A"), 0).unwrap(); + let b = doc.add_component(Some("B"), 0).unwrap(); + blocks_with_cuts(&mut doc, a, 5, 2); + blocks_with_cuts(&mut doc, b, 4, 2); + blocks_with_cuts(&mut doc, 0, 3, 1); + place(&mut doc, a, rigid(Vec3::new(3.0, -7.0, 1.5), Vec3::ZERO, Vec3::Z, 0.4)); + place(&mut doc, b, rigid(Vec3::new(-20.0, 5.0, 0.0), Vec3::ZERO, Vec3::X, 0.25)); + let mut model = Model::new(); + model.evaluate(&doc); + let names: Vec = model.state().bodies.iter().map(|b| b.name.clone()).collect(); + assert_eq!(names.len(), 12); + doc.body_components.insert(names[1].clone(), b); + doc.body_offsets.insert(names[2].clone(), rigid(Vec3::new(0.0, 0.0, 2.0), Vec3::ZERO, Vec3::Y, 0.1)); + doc.body_offsets.insert(names[6].clone(), rigid(Vec3::new(1.0, 1.0, 0.0), Vec3::ZERO, Vec3::Z, -0.3)); + model.evaluate(&doc); + let st = model.state(); + let cuts: Vec<&Feature> = doc.features.iter().filter(|f| matches!(f.kind, FeatureKind::Box { operation: Operation::Cut, .. })).collect(); + assert_eq!(cuts.len(), 5); + for f in cuts { + let digest = placement_digest(&doc, f, Some(&st)); + assert_ne!(digest, 0); + assert_eq!(digest, digest_searching_each_body(&doc, f, &st), "cut {}", f.id); + } +} + +/// `comps` parts, each with `bodies` boxes, `sketches` sketches and `taps` taps, placed `copies` +/// times: a design and its state, made without evaluating it. +fn placed_parts(comps: usize, bodies: usize, sketches: usize, taps: usize, copies: usize) -> (Document, ModelState) { + let mut doc = Document::new("placed parts"); + let mut one = Document::new("one sketch"); + one.add_feature(line_sketch(PlaneRef::Origin { name: "XY".into() }, Vec2::new(3.0, 4.0)), None).unwrap(); + let mut m = Model::new(); + m.evaluate(&one); + let solved = m.state().sketches.first().unwrap().clone(); + let mut st = ModelState::default(); + let solid = kernel::box_solid(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)).unwrap(); + for c in 0..comps { + let comp = doc.add_component(Some(&format!("C{c}")), 0).unwrap(); + let o = doc.occurrences.iter_mut().find(|o| o.component == comp).unwrap(); + o.transform = rigid(Vec3::new(10.0 * c as f64, 0.0, 0.0), Vec3::ZERO, Vec3::Z, 0.01 * c as f64); + for k in 1..copies { + doc.add_occurrence(comp, 0, rigid(Vec3::new(10.0 * c as f64, 20.0 * k as f64, 0.0), Vec3::ZERO, Vec3::Z, 0.02 * k as f64)).unwrap(); + } + let mut names = Vec::new(); + for b in 0..bodies { + let kind = + serde_json::from_value(serde_json::json!({"type": "box", "corner": [0, 0, 0], "length": "2", "width": "3", "height": "4"})).unwrap(); + let name = format!("B{c}_{b}"); + let id = doc.add_feature(kind, Some(&name)).unwrap(); + doc.feature_mut(id).unwrap().component = comp; + st.bodies.push(ModelBody::new(name.clone(), solid.clone(), id)); + names.push((name, id)); + } + for s in 0..sketches { + let id = doc.add_feature(line_sketch(PlaneRef::Origin { name: "XY".into() }, Vec2::new(1.0 + s as f64, 2.0)), None).unwrap(); + doc.feature_mut(id).unwrap().component = comp; + let mut s2 = SolvedSketch::clone(&solved); + s2.feature = id; + st.sketches.push(Arc::new(s2)); + } + for t in 0..taps { + let (body, feature) = names[t % names.len()].clone(); + st.threads.push(ThreadInfo { + feature, + body, + designation: "M6".into(), + major_diameter: 6.0, + radius: 3.0, + pitch: 1.0, + internal: true, + axis_point: Vec3::new(1.0, 1.0, 0.0), + axis: solidcraft_geom::UnitVec3::Z, + start: 0.0, + end: 4.0, + form: Default::default(), + hand: Default::default(), + starts: 1, + }); + } + } + (doc, st) +} + +#[test] +fn placing_parts_looks_each_sketch_and_tap_up_once() { + // A large assembly searched all features for every sketch and construction, and all bodies + // twice for every tap and placement, each time its world state was made (every command). + let searches = |sketches: usize, taps: usize| { + let (doc, state) = placed_parts(4, 2, sketches, taps, 3); + let mut world = ModelState::default(); + let n = searched(|| world = world_state(&doc, &state).unwrap()); + assert_eq!(world.bodies.len(), 4 * 2 * 3); + assert_eq!(world.sketches.len(), 4 * sketches); + assert_eq!(world.threads.len(), 4 * taps * 3); + n + }; + assert_eq!(searches(8, 6), searches(1, 1)); +} + +#[test] +fn a_placed_tap_follows_its_body_offset() { + let (mut doc, state) = placed_parts(1, 1, 0, 1, 1); + let comp = doc.components[0].id; + doc.body_offsets.insert("B0_0".into(), rigid(Vec3::new(0.0, 0.0, 7.0), Vec3::ZERO, Vec3::Z, 0.0)); + let world = world_state(&doc, &state).unwrap(); + let tap = world.threads.first().unwrap(); + let expected = + apply_point(&mat_mul(&doc.component_transform(comp), &rigid(Vec3::new(0.0, 0.0, 7.0), Vec3::ZERO, Vec3::Z, 0.0)), Vec3::new(1.0, 1.0, 0.0)); + assert!(tap.axis_point.dist(expected) < 1e-9, "{:?} {expected:?}", tap.axis_point); +} + +/// What adding a feature of `kind` at the end of `doc` did to the bodies already there: how many +/// its cut ran booleans on, and which it left exactly as they were (the same geometry, its name, +/// key and face names carried over). A cut that cannot reach a body hands it back as it was, and +/// must not pay a whole boolean to find that out (#10225); the sheet metal hole (#10226) and the +/// cosmetic thread (#10227) check their own shortcuts with it too. +pub(super) struct CutWork { + pub cut: usize, + pub kept: Vec, + pub model: Model, +} + +pub(super) fn cut_work(doc: &mut Document, kind: FeatureKind) -> CutWork { + let mut model = Model::new(); + model.evaluate(doc); + let id = doc.add_feature(kind, None).unwrap(); + let work = counted(|| model.evaluate(doc)); + let result = model.result(id).unwrap(); + assert_eq!(result.error, None, "the feature builds"); + let before = model.state_before(id); + let kept = result + .state + .bodies + .iter() + .filter(|b| { + before + .body(&b.name) + .is_some_and(|old| old.body.same(&b.body) && old.key == b.key && crate::naming::face_names(old) == crate::naming::face_names(b)) + }) + .map(|b| b.name.clone()) + .collect(); + CutWork { cut: work.cut, kept, model } +} + +/// A box body named `name`, `size` long on each side from `corner`. +fn block(doc: &mut Document, name: &str, corner: Vec3, size: [f64; 3]) { + let id = doc + .add_feature( + FeatureKind::Box { + corner: point_expr(corner), + length: size[0].to_string().into(), + width: size[1].to_string().into(), + height: size[2].to_string().into(), + operation: Operation::NewBody, + }, + None, + ) + .unwrap(); + doc.feature_mut(id).unwrap().body_names = vec![name.into()]; +} + +/// A cylinder that cuts, standing on `base` along Z. +fn cutter(base: Vec3, radius: f64, height: f64) -> FeatureKind { + FeatureKind::Cylinder { + base: point_expr(base), + axis: Dir(Vec3::Z), + radius: radius.to_string().into(), + height: height.to_string().into(), + operation: Operation::Cut, + references: Vec::new(), + } +} + +/// A cut leaves the bodies its tool cannot reach as they were, without a boolean on each: in a +/// design of many bodies those booleans were most of a hole's time (#10225). +#[test] +fn a_cut_leaves_bodies_it_cannot_reach_as_they_were() { + let mut doc = Document::new("far"); + block(&mut doc, "Near", Vec3::ZERO, [50.0, 40.0, 30.0]); + // 0.5 mm clear of the tool, and far off. + block(&mut doc, "Beside", Vec3::new(13.5, 0.0, 0.0), [20.0, 40.0, 30.0]); + for i in 0..5 { + block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]); + } + // Near and Beside overlap; the hole goes through Near only, beside Beside. + let work = cut_work(&mut doc, cutter(Vec3::new(10.0, 20.0, -5.0), 3.0, 40.0)); + assert_eq!(work.cut, 1, "only the body the tool reaches goes through the boolean"); + assert_eq!(work.kept, ["Beside", "Far0", "Far1", "Far2", "Far3", "Far4"]); + assert!(volume(&work.model, "Near") < 60_000.0 - 800.0, "and it is cut"); +} + +/// A cut still goes through the boolean wherever its tool reaches a body: on a face, along a +/// line, into a dome above its edge circle. The boxes are exact, so a tool clear of a body by +/// more than their tolerances leaves it out. (Bodies its tool cannot reach are left out of it: +/// `a_cut_leaves_bodies_it_cannot_reach_as_they_were`.) +#[test] +fn a_cut_still_runs_where_its_tool_touches_grazes_or_meets_a_curved_face() { + // A cylinder whose side is tangent to the face x = 50, one 0.5 µm clear of it (far past the + // bodies' tolerances, so left out), one 0.1 mm in. + for (x, cuts, boolean) in [(53.0, false, 1), (53.0005, false, 0), (52.9, true, 1)] { + let mut doc = Document::new("graze"); + block(&mut doc, "A", Vec3::ZERO, [50.0, 40.0, 30.0]); + let work = cut_work(&mut doc, cutter(Vec3::new(x, 20.0, 0.0), 3.0, 30.0)); + assert_eq!(work.cut, boolean, "the tool at x = {x} goes through the boolean {boolean} time(s)"); + let v = volume(&work.model, "A"); + assert_eq!(v < 60_000.0 - 1.0, cuts, "the tool at x = {x} cuts material: {v}"); + assert!(!cuts || work.kept.is_empty(), "a body cut is a new body"); + } + // A box meeting the block only along its top edge. + let mut doc = Document::new("edge"); + block(&mut doc, "A", Vec3::ZERO, [50.0, 40.0, 30.0]); + let along = FeatureKind::Box { + corner: point_expr(Vec3::new(50.0, 0.0, 30.0)), + length: "10".into(), + width: "40".into(), + height: "10".into(), + operation: Operation::Cut, + }; + assert_eq!(cut_work(&mut doc, along).cut, 1); + // A dome: a sphere's cap rising 10 mm above the circle it stands on. A thin tool drilled into + // its top near the apex, well above that circle, cuts it. + let mut doc = Document::new("dome"); + doc.add_feature(FeatureKind::Sphere { center: point_expr(Vec3::new(0.0, 0.0, -10.0)), radius: "20".into(), operation: Operation::NewBody }, None) + .unwrap(); + let below = FeatureKind::Box { + corner: point_expr(Vec3::new(-30.0, -30.0, -40.0)), + length: "60".into(), + width: "60".into(), + height: "40".into(), + operation: Operation::Cut, + }; + doc.add_feature(below, None).unwrap(); + let mut model = Model::new(); + model.evaluate(&doc); + let dome = model.state().bodies[0].name.clone(); + let whole = volume(&model, &dome); + let work = cut_work(&mut doc, cutter(Vec3::new(2.0, 1.0, 8.0), 1.0, 5.0)); + assert_eq!(work.cut, 1); + assert!(volume(&work.model, &dome) < whole - 1.0, "the drill cuts into the dome"); + assert!(work.kept.is_empty()); +} + +/// A cylinder body named `name` standing on `base` along Z. +fn shaft(doc: &mut Document, name: &str, base: Vec3, radius: f64, height: f64) { + let id = doc + .add_feature( + FeatureKind::Cylinder { + base: point_expr(base), + axis: Dir(Vec3::Z), + radius: radius.to_string().into(), + height: height.to_string().into(), + operation: Operation::NewBody, + references: Vec::new(), + }, + None, + ) + .unwrap(); + doc.feature_mut(id).unwrap().body_names = vec![name.into()]; +} + +/// The work of adding `kind` at the end of `doc`, and the tap markings the design then has. +fn marking_work(doc: &mut Document, kind: FeatureKind) -> (Counts, Vec) { + let mut model = Model::new(); + model.evaluate(doc); + let id = doc.add_feature(kind, None).unwrap(); + let work = counted(|| model.evaluate(doc)); + assert_eq!(model.result(id).unwrap().error, None, "the feature builds"); + (work, model.state().threads.clone()) +} + +/// A cosmetic tap marking at `p`. +fn marking(p: Vec3) -> FeatureKind { + FeatureKind::Thread { + face: FacePick(p), + designation: Some("M6".into()), + length: None, + modeled: false, + from: None, + up_to: None, + form: Default::default(), + hand: crate::thread_forms::ThreadHand::Right, + starts: 1, + ease_out: None, + tip: Default::default(), + chamfer_angle: None, + chamfer_depth: None, + steep_flank: Default::default(), + old_auto_size: false, + } +} + +/// A tap marking looks for its cylinder in the bodies near it only: each body searched was +/// tessellated again, so many markings in a design of many bodies took quadratic time (#10227). +#[test] +fn a_tap_marking_searches_only_the_bodies_near_it() { + let mut doc = Document::new("far"); + shaft(&mut doc, "Shaft", Vec3::ZERO, 3.0, 6.0); + for i in 0..5 { + block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]); + } + let (work, threads) = marking_work(&mut doc, marking(Vec3::new(3.0, 0.0, 3.0))); + assert_eq!(work.cylinder_search, 1, "only the shaft is searched"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, "Shaft"); + assert_eq!(threads[0].designation, "M6"); + assert!((threads[0].radius - 3.0).abs() < 1e-6 && !threads[0].internal); + + // A tapped hole in a plate among far bodies: only the plate is searched for its wall. + let mut doc = Document::new("tapped"); + block(&mut doc, "Plate", Vec3::ZERO, [60.0, 60.0, 12.0]); + for i in 0..5 { + block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]); + } + let hole = FeatureKind::Hole { + position: FacePick(Vec3::new(30.0, 30.0, 12.0)), + at: None, + direction: Dir(-Vec3::Z), + diameter: "5".into(), + depth: Some("10".into()), + hole: HoleKind::default(), + points: None, + thread: Some("M6".into()), + thread_depth: None, + hand: crate::thread_forms::ThreadHand::Right, + modeled: false, + ease_out: None, + to: None, + references: Vec::new(), + }; + let (work, threads) = marking_work(&mut doc, hole); + assert_eq!(work.cylinder_search, 1, "only the plate is searched"); + assert_eq!(work.tapped_wall, 1, "only the plate's faces are read for the wall"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, "Plate"); + assert!(threads[0].internal && (threads[0].radius - 2.5).abs() < 1e-6); +} + +/// Bodies within reach of a tap marking are still searched: the shaft it lies on, a block 3 mm +/// off (within a twentieth of the block's size, where the cylinder search itself looks), and one +/// 3.6 mm off (just past it, but within the margin the boxes keep); a block 4.5 mm off is not. +/// The marking stays on the shaft. +#[test] +fn a_tap_marking_still_searches_the_bodies_within_its_reach() { + let mut doc = Document::new("near"); + shaft(&mut doc, "Shaft", Vec3::ZERO, 3.0, 6.0); + // Each block is 50 x 40 x 30 (a twentieth of its size is 3.54 mm), its face x = 3 + gap. + for (name, gap) in [("Close", 3.0), ("Edge", 3.6), ("Clear", 4.5)] { + block(&mut doc, name, Vec3::new(3.0 + gap, -20.0, 0.0), [50.0, 40.0, 30.0]); + } + let (work, threads) = marking_work(&mut doc, marking(Vec3::new(3.0, 0.0, 3.0))); + assert_eq!(work.cylinder_search, 3, "the shaft, Close and Edge are searched"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, "Shaft"); + + // A pin in a hole a hair wider: a marking on the pin, and one on the hole's wall. + for (p, body, internal) in [(Vec3::new(2.0, 0.0, 5.0), "Pin", false), (Vec3::new(2.5, 0.0, 5.0), "Plate", true)] { + let mut doc = Document::new("pin"); + block(&mut doc, "Plate", Vec3::new(-20.0, -20.0, 0.0), [40.0, 40.0, 10.0]); + let bore = FeatureKind::Cylinder { + base: point_expr(Vec3::new(0.0, 0.0, -1.0)), + axis: Dir(Vec3::Z), + radius: "2.5".into(), + height: "12".into(), + operation: Operation::Cut, + references: Vec::new(), + }; + doc.add_feature(bore, None).unwrap(); + shaft(&mut doc, "Pin", Vec3::ZERO, 2.0, 10.0); + let mut kind = marking(p); + if let FeatureKind::Thread { designation, .. } = &mut kind { + *designation = None; + } + let (work, threads) = marking_work(&mut doc, kind); + assert_eq!(work.cylinder_search, 2, "both bodies are searched for {body}"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, body); + assert_eq!(threads[0].internal, internal); + } +} + +/// A flat sheet of the default rule (2.5 mm steel) on a `w` x `h` rectangle from `corner` on XY. +fn flat_sheet(doc: &mut Document, corner: Vec2, w: f64, h: f64) { + let mut sk = Sketch::new(); + let p = [corner, corner + Vec2::new(w, 0.0), corner + Vec2::new(w, h), corner + Vec2::new(0.0, h)].map(|q| sk.add_point(q, None).unwrap()); + for k in 0..4 { + sk.add_line_pts(p[k], p[(k + 1) % 4], None).unwrap(); + } + let sketch = doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: sk }, None).unwrap(); + doc.add_feature(FeatureKind::SheetBase { sketch: SketchId(sketch), profiles: ProfileSel::All, rule: None, flip: false }, None).unwrap(); +} + +/// A hole of `diameter` at `position`, drilling along `direction` through all. +fn hole(position: Vec3, direction: Vec3, diameter: f64) -> FeatureKind { + serde_json::from_value(serde_json::json!({ + "type": "hole", "position": [position.x, position.y, position.z], "direction": [direction.x, direction.y, direction.z], + "diameter": diameter.to_string(), + })) + .unwrap() +} + +/// The sheet metal bodies of a model. +fn sheet_bodies(model: &Model) -> Vec { + model.state().sheets.iter().map(|s| s.body.clone()).collect() +} + +/// A cut leaves the sheets it cannot reach as they were, without checking that it would leave +/// each one unchanged (#10226). +#[test] +fn a_cut_leaves_sheets_it_cannot_reach_as_they_were() { + let mut doc = Document::new("far sheets"); + for i in 0..5 { + flat_sheet(&mut doc, Vec2::new(200.0 * i as f64, 0.0), 150.0, 100.0); + } + block(&mut doc, "Plate", Vec3::new(0.0, -200.0, 0.0), [60.0, 60.0, 12.0]); + let work = cut_work(&mut doc, cutter(Vec3::new(30.0, -170.0, -1.0), 3.0, 20.0)); + assert_eq!(work.cut, 1, "only the plate goes through a boolean"); + assert_eq!(work.kept, sheet_bodies(&work.model), "every sheet is left as it was"); + assert!(volume(&work.model, "Plate") < 43_200.0 - 300.0, "and the plate is cut"); +} + +/// A tapped hole reads for its wall the faces of the bodies its drill line comes near: the plate +/// it is drilled in, a block far below on the same line, and one whose side lies a radius off the +/// line; not a block beside it. The marking stays in the plate's hole. +#[test] +fn a_tapped_hole_reads_the_bodies_along_its_drill_line() { + let mut doc = Document::new("line"); + block(&mut doc, "Plate", Vec3::ZERO, [60.0, 60.0, 12.0]); + block(&mut doc, "Below", Vec3::new(20.0, 20.0, -150.0), [20.0, 20.0, 20.0]); + block(&mut doc, "Grazing", Vec3::new(32.5, 20.0, -60.0), [20.0, 20.0, 20.0]); + block(&mut doc, "Beside", Vec3::new(50.0, 20.0, -60.0), [20.0, 20.0, 20.0]); + let hole = FeatureKind::Hole { + position: FacePick(Vec3::new(30.0, 30.0, 12.0)), + at: None, + direction: Dir(-Vec3::Z), + diameter: "5".into(), + depth: Some("10".into()), + hole: HoleKind::default(), + points: None, + thread: Some("M6".into()), + thread_depth: None, + hand: crate::thread_forms::ThreadHand::Right, + modeled: false, + ease_out: None, + to: None, + references: Vec::new(), + }; + let (work, threads) = marking_work(&mut doc, hole); + assert_eq!(work.tapped_wall, 3, "Plate, Below and Grazing are read"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, "Plate"); + assert!(threads[0].internal && (threads[0].radius - 2.5).abs() < 1e-6); +} + +/// A hole leaves the sheets it cannot reach as they were, without drilling, checking or cutting +/// each one: in a design of many sheet parts that was most of a hole's time (#10226). +#[test] +fn a_hole_leaves_sheets_it_cannot_reach_as_they_were() { + let mut doc = Document::new("far sheets"); + for i in 0..5 { + flat_sheet(&mut doc, Vec2::new(200.0 * i as f64, 0.0), 150.0, 100.0); + } + block(&mut doc, "Plate", Vec3::new(0.0, -200.0, 0.0), [60.0, 60.0, 12.0]); + let work = cut_work(&mut doc, hole(Vec3::new(30.0, -170.0, 12.0), Vec3::new(0.0, 0.0, -1.0), 6.0)); + let sheets = sheet_bodies(&work.model); + assert_eq!(sheets.len(), 5); + assert_eq!(work.cut, 1, "only the plate goes through a boolean"); + assert_eq!(work.kept, sheets, "every sheet is left as it was"); + assert!(volume(&work.model, "Plate") < 43_200.0 - 300.0, "and the plate is drilled"); +} + +/// A hole drilled into a sheet's rim still bores that sheet, beside sheets it cannot reach. +#[test] +fn a_hole_into_a_rim_still_bores_its_sheet_beside_far_ones() { + let mut doc = Document::new("rim"); + for i in 0..4 { + flat_sheet(&mut doc, Vec2::new(200.0 * i as f64, 0.0), 60.0, 40.0); + } + let mut model = Model::new(); + model.evaluate(&doc); + let near = sheet_bodies(&model)[0].clone(); + let whole = volume(&model, &near); + let d = 1.5; + let work = cut_work(&mut doc, hole(Vec3::new(60.0, 20.0, 1.25), Vec3::new(-1.0, 0.0, 0.0), d)); + assert_eq!(work.cut, 1, "only the sheet the drill meets is bored"); + assert_eq!(work.kept, sheet_bodies(&work.model)[1..]); + let state = work.model.state(); + let sheet = state.sheets.iter().find(|s| s.body == near).unwrap(); + assert_eq!(sheet.bores.len(), 1, "kept as a bore of the sheet"); + let removed = whole - volume(&work.model, &near); + let bore = std::f64::consts::PI * (d / 2.0).powi(2) * 60.0; + assert!((removed - bore).abs() < 0.02 * bore, "removed {removed} of {bore}"); +} diff --git a/crates/doc/src/eval_frame.rs b/crates/doc/src/eval_frame.rs index 35ab2b0fc..7abd78ec7 100644 --- a/crates/doc/src/eval_frame.rs +++ b/crates/doc/src/eval_frame.rs @@ -1,10 +1,12 @@ //! Frame members (#4003): one body per straight line of a frame sketch, its cross-section a //! profile laid square to the line (`frame::member_axes`) and run from one end to the other. +use solidcraft_geom::prelude::*; use std::borrow::Cow; use std::collections::{BTreeMap, HashSet}; -use solidcraft_geom::{Aabb2, Plane, Region2, Ring, Vec2, Vec3}; +use solidcore_record::{Plane, Region2, Vec2, Vec3}; +use solidcraft_geom::{Aabb2, Ring}; use solidcraft_kernel as kernel; use solidcraft_sketch::CurveKind; diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index d6e3e5e74..48d8993ad 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -5,7 +5,8 @@ use super::*; use crate::EmbossFace; use crate::apply_point; use crate::sheet; -use solidcraft_geom::{Aabb3, ArcMap, Loop2, Ring, Seg2}; +use solidcore_record::{Loop2, Seg2}; +use solidcraft_geom::{Aabb3, ArcMap, Ring}; pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { match &f.kind { @@ -44,17 +45,8 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, { let mut scoped = ModelState::default(); scoped.bodies.push(mb.clone()); - let (picked, split) = crate::naming::point_on_face(&scoped, name, at) - .ok_or_else(|| DocError::Invalid("selected cylinder face no longer exists".into()))?; - if split { - return Err(DocError::Invalid("selected cylinder face was split".into())); - } - let (index, _, _) = crate::project::nearest_face(&mb.mesh(), picked) - .ok_or_else(|| DocError::Invalid("selected cylinder face cannot be resolved".into()))?; - if !crate::naming::face_has_name(&mb, index as usize, name) { - return Err(DocError::Invalid("selected cylinder face is ambiguous".into())); - } - at = kernel::cylinder_emboss_anchor(&mb.body, index as usize, picked)?; + let hit = crate::name_lookup::locate_face(&scoped, name, at).ok_or_else(|| DocError::reselect(name.as_str()))?; + at = kernel::cylinder_emboss_anchor(&mb.body, hit.face, hit.point)?; } let result = kernel::emboss_cylinder_at(&mb.body, at, &plane, ®ions, if *deboss { -d } else { d })?; if let Some(slot) = st.bodies.get_mut(i) { @@ -97,17 +89,26 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, } Ok(()) } - FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip, from_plane, to_plane } => { + FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip, from_plane, to_plane, axes, from_frame, to_frame, angle } => { // A plane on either side is worked out now, so the bodies follow it when it moves. let (mut from, mut from_normal) = (from.0, from_normal.and_then(|n| n.normalized())); if let Some(p) = from_plane { let pl = doc.resolve_plane_in(vals, p, 0, Some(&*st))?; (from, from_normal) = (pl.origin, Some(pl.normal())); } - let target = to_plane.as_ref().map(|p| doc.resolve_plane_in(vals, p, 0, Some(&*st))).transpose()?; - let (to, to_normal) = match &target { - Some(pl) => (pl.origin, Some(pl.normal())), - None => (to.0, to_normal.and_then(|n| n.normalized())), + // So is a frame (#6257): its origin and z, found again from the geometry. + if let Some(fr) = from_frame { + let (o, z) = fr.resolve(doc, st)?; + (from, from_normal) = (o, Some(z)); + } + let target = match to_frame { + Some(_) => None, + None => to_plane.as_ref().map(|p| doc.resolve_plane_in(vals, p, 0, Some(&*st))).transpose()?, + }; + let (to, to_normal) = match (to_frame, &target) { + (Some(fr), _) => fr.resolve(doc, st).map(|(o, z)| (o, Some(z)))?, + (None, Some(pl)) => (pl.origin, Some(pl.normal())), + (None, None) => (to.0, to_normal.and_then(|n| n.normalized())), }; let mut m = translation(Vec3::ZERO); if let (Some(a), Some(b)) = (from_normal, to_normal) { @@ -126,9 +127,44 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, (Some(_), Some(n)) => n * (to - from).dot(n), _ => to - from, }; + // Point-to-point alignment can keep only the chosen world X/Y/Z directions, + // stored in the bodies' frame. A missing list means all three (the full offset). + let d = match axes { + None => d, + Some(dirs) if dirs.is_empty() => { + return Err(DocError::Invalid("the align axes enable none of X, Y and Z".into())); + } + Some(dirs) => { + let mut kept = Vec3::ZERO; + let mut used = false; + for a in dirs { + if let Some(a) = a.0.normalized() { + kept += a * d.dot(a); + used = true; + } + } + if !used { + return Err(DocError::Invalid("the align axes have no direction".into())); + } + kept + } + }; m[3][0] += d.x; m[3][1] += d.y; m[3][2] += d.z; + // Then the turn about the target's direction, through where `from` landed. + if let Some(e) = angle { + let a = val(vals, e, Kind::Angle)?; + if !a.is_finite() { + return Err(DocError::Invalid("the Align angle is not a finite number".into())); + } + let n = to_normal.ok_or_else(|| { + DocError::Invalid("an Align angle turns about the target's direction: move onto a frame, a face or a plane".into()) + })?; + if a.abs() > 1e-12 { + m = crate::mat_mul(&rotation(apply_point(&m, from), n, a), &m); + } + } if bodies.is_empty() { return Err(DocError::Invalid("no bodies to align".into())); } @@ -198,7 +234,7 @@ pub(super) fn rib_tools(vals: &BTreeMap, st: &ModelState, f: &Fea fn planar_normal_at(b: &Body, p: Vec3) -> Option { let tol = (b.size() * 2e-3).max(1e-3); let faces = b.faces(tol).ok()?; - let mesh = b.tessellate(tol).ok()?; + let mesh = b.mesh(&solidcraft_kernel::MeshTolerance::chord(tol)).ok()?; let mut near = vec![f64::INFINITY; faces.len()]; for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) { if let (Some([u, v, w]), Some(d)) = (mesh.tri(t), near.get_mut(*f as usize)) { @@ -573,10 +609,7 @@ pub(super) fn sheet_eval( } let rr = match radius { Some(e) => val(vals, e, Kind::Length)?, - None => { - let rule = st.sheets.get(i).map(|s| s.rule.clone()).unwrap_or_default(); - doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.bend_radius - } + None => sheet_rule_values(doc, vals, st, i)?.bend_radius, }; // The corner relief these flanges ask for in place of the rule's. let relief = sheet::ReliefOverride { @@ -656,7 +689,7 @@ pub(super) fn sheet_eval( tag_flanges(sh, n0, f.id); rebuild_sheet(st, i) } - FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body } => { + FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body, sketch, profiles } => { // Without a body name the field goes on the newest sheet, as the command's own body lookup does. let i = match body { Some(_) => sheet_for(st, body, None)?, @@ -678,8 +711,18 @@ pub(super) fn sheet_eval( "perforation needs diameter > 0, pitch > diameter and margin >= 0 (diameter {d}, pitch {pitch}, margin {margin})" ))); } + // The outline sketch's profiles, where they lie on the sheet now. + let outline = match sketch { + Some(sk) => { + let ss = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk}")))?; + let regions = select_profiles(ss, profiles.as_ref().unwrap_or(&ProfileSel::All))?; + let sh = st.sheets.get(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; + Some(sh.perforation_outline(&ss.plane, ®ions)?) + } + None => None, + }; let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; - sh.perforations.push(crate::sheet::SheetPerforation { feature: f.id, diameter: d, pitch, margin, square, from_right: false }); + sh.perforations.push(crate::sheet::SheetPerforation { feature: f.id, diameter: d, pitch, margin, square, from_right: false, outline }); Ok(()) } FeatureKind::SheetHem { edges, length, gap, flip, body } => { @@ -687,10 +730,7 @@ pub(super) fn sheet_eval( let l = val(vals, length, Kind::Length)?; let g = match gap { Some(e) => val(vals, e, Kind::Length)?, - None => { - let rule = st.sheets.get(i).map(|s| s.rule.clone()).unwrap_or_default(); - doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.hem_gap - } + None => sheet_rule_values(doc, vals, st, i)?.hem_gap, }; let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; let picks = sheet_picks(sh, f, &crate::plain(edges), warning); @@ -718,10 +758,7 @@ pub(super) fn sheet_eval( let ang = val(vals, angle, Kind::Angle)?; let rr = match radius { Some(e) => val(vals, e, Kind::Length)?, - None => { - let rule = st.sheets.get(i).map(|s| s.rule.clone()).unwrap_or_default(); - doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.bend_radius - } + None => sheet_rule_values(doc, vals, st, i)?.bend_radius, }; // A fixed point that touches no material at all (e.g. far above the sheet) still picks // the side it lies on, so a stored fold keeps recomputing; it says so (#371). @@ -761,28 +798,26 @@ pub(super) fn sheet_eval( FeatureKind::SheetConvert { body, face, rule, bends } if !bends.is_empty() => { let mb = st.body(body).cloned().ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; let r = doc.sheet_rule(rule.as_deref()); - let rv = doc.rule_values(vals, &r)?; - // The bend edges by name first; a name that is gone keeps its point, with a warning. + let values = |t: Option| doc.rule_values_at(vals, &r, t); + // The bend edges by name where they have one: a name that no longer finds its edge + // fails the conversion, asking for the edge to be picked again. let mut picks = Vec::with_capacity(bends.len()); for (i, p) in bends.iter().enumerate() { let name = f.edge_names.get(i).filter(|n| !n.is_empty()); - picks.push(match name.map(|n| (n, crate::naming::locate_edge(&mb, n, p.0))) { - Some((n, Ok(hit))) => { + picks.push(match name { + Some(n) => { + let hit = crate::naming::locate_edge(&mb, n, p.0).map_err(|_| DocError::reselect(n.as_str()))?; if let Some(note) = hit.note(n) { append_warning(warning, note); } hit.point } - Some((n, Err(_))) => { - append_warning(warning, format!("edge `{n}` no longer exists; using the edge at the picked point")); - p.0 - } None => p.0, }); } let placement = doc.component_transform(doc.model_body_component(&mb)); let body_to_world = doc.model_body_offset(&mb).map(|offset| crate::mat_mul(&placement, offset)).unwrap_or(placement); - let (mut sh, notes) = sheet::convert_body(&mb, &r.name, &rv, face.0, &picks, &body_to_world)?; + let (mut sh, notes) = sheet::convert_body(&mb, &r.name, &values, face.0, &picks, &body_to_world)?; for note in notes { append_warning(warning, note); } @@ -801,11 +836,11 @@ pub(super) fn sheet_eval( // thin plate that thousandth passes the thickness: the far side's triangles counted as // this face's (no outline was left), and a hole of a smaller radius than that fell out. let mut tol = (mb.body.size() * 1e-3).max(1e-3); - let mut mesh = mb.body.tessellate(tol)?; + let mut mesh = mb.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol))?; let (mut lo, mut hi) = extent(&mesh); if hi - lo > 0.0 && tol > (hi - lo) * 0.1 { tol = ((hi - lo) * 0.1).max(1e-6); - mesh = mb.body.tessellate(tol)?; + mesh = mb.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol))?; (lo, hi) = extent(&mesh); } let t = hi - lo; @@ -815,12 +850,12 @@ pub(super) fn sheet_eval( // (its outer level, `hi`) with z into the material, as with bend edges, so the sheet // takes the plate's place: its thickness runs from `hi` back to `lo`. let plane = Plane::from_normal(face.0 + n * hi, n * -1.0).ok_or_else(|| DocError::Invalid("face".into()))?; + let slice = FaceSlice { mesh: &mesh, plane, at: face.0, n, tol }; // Recesses in one face (an engraved label) become pockets; the outline is the other face's. - let recesses = plate_recesses(&mb.body, &mesh, &plane, face.0, n, (lo, hi), tol)?; + let recesses = slice.recesses(&mb.body, (lo, hi))?; let mut walls = std::collections::HashMap::new(); let mut wall = |f: u32| *walls.entry(f).or_insert_with(|| sheet::round_wall(&mb.body, &plane, n, f)); - let mut loops: Vec = - face_outline(&mesh, &plane, face.0, n, recesses.level, tol).iter().map(|l| sheet::outline_loop(l, &mut wall, tol * 1e-2)).collect(); + let mut loops: Vec = slice.outline(recesses.level).iter().map(|l| sheet::outline_loop(l, &mut wall, tol * 1e-2)).collect(); loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs())); let mut it = loops.into_iter(); let outer = it.next().ok_or_else(|| DocError::Invalid("no outline on that face".into()))?.ccw(); @@ -833,8 +868,7 @@ pub(super) fn sheet_eval( )); } let r = doc.sheet_rule(rule.as_deref()); - let mut rv = doc.rule_values(vals, &r)?; - rv.thickness = t; + let rv = doc.rule_values_at(vals, &r, Some(t))?; let mut sh = sheet::base_flange(body, &r.name, &rv, plane, Region2 { outer: region.outer.clone(), holes: Vec::new() }); sh.holes = region.holes.iter().map(|h| Region2 { outer: h.ccw(), holes: Vec::new() }).collect(); let mut work = sheet::FlatWork::new(); @@ -847,9 +881,21 @@ pub(super) fn sheet_eval( } } -/// Current unmodified extrusion caps, including placement, certify the tool's depth. -/// Tessellation can drift in thickness at distant coordinates and cannot certify a slab. +/// The tool's depth along the sketch normal (from `source`), the roundoff of that depth and the +/// tool's current footprint where it differs from the profile: from its current unmodified +/// extrusion caps, including placement, else from its exact record proving it a uniform prism +/// along the normal (a To Object tool trimmed by the body it runs to, whose boolean leaves no +/// extrusion faces: its section is its footprint). Tessellation can drift in thickness at +/// distant coordinates and cannot certify a slab. fn sheet_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> { + extrusion_tool_span(body, source).or_else(|| { + let prism = kernel::certified_prism_section(body, source).ok().flatten()?; + (prism.tolerance <= 1e-7).then_some((prism.lo, prism.hi, prism.tolerance, Some((*source, prism.region)))) + }) +} + +/// [`sheet_tool_span`] from the tool's extrusion caps. +fn extrusion_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> { use kernel::FaceSource; #[derive(PartialEq)] enum Signature<'a> { @@ -993,6 +1039,164 @@ fn extrude_cut(st: &ModelState, f: &Feature) -> Result> { Ok(Some(ExtrudeCut { plane: ss.plane, regions, text, operation: *operation, bound: extent.to.is_some() })) } +/// An untapered extrude join one sheet thick in the plane of a panel of sheet metal (the base or +/// a flange's panel, unfolded or folded) that touches that panel and nothing else of the sheet: +/// the material becomes part of the panel's outline, so the flat pattern, its DXF and a refold +/// keep it, and it follows its sketch's parameters as a cut made there does. Cut-outs it covers +/// are filled. Returns the sheets it took; none (and the generic path's warning) for any other +/// join: another depth, out of every panel's plane, reaching into a bend zone or another panel, +/// apart from the sheet, or over a pocket, label, bore or perforation. +pub(super) fn sheet_join( + f: &Feature, + st: &mut ModelState, + tools: &[Body], + targets: &[String], + constructor: Option<&ExtrudeConstructor>, +) -> Result> { + let FeatureKind::Extrude { sketch, profiles, operation: Operation::Join, extent, .. } = &f.kind else { return Ok(Vec::new()) }; + if extent.taper.is_some() || tools.is_empty() || !any_eligible_sheet(f, st, targets) { + return Ok(Vec::new()); + } + let Some(ss) = st.sketch(sketch.0).cloned() else { return Ok(Vec::new()) }; + // The depth the extrude was given, along its sketch's normal: only an untrimmed extrude has one. + let Some(c) = constructor.filter(|c| c.plane == ss.plane) else { return Ok(Vec::new()) }; + let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); + let plane = ss.plane; + let n = plane.normal(); + let (lo, hi) = (c.interval.0.min(c.interval.1), c.interval.0.max(c.interval.1)); + let roundoff = 128.0 * f64::EPSILON * (plane.origin.len() + lo.abs() + hi.abs()).max(1.0); + let mut work = sheet::FlatWork::new(); + let mut plans = Vec::new(); + for original in &st.sheets { + if !sheet_eligible(f, st, targets, original) { + continue; + } + let Some(sh) = sheet_join_one(original, &plane, n, ®ions, (lo, hi, roundoff), &mut work)? else { return Ok(Vec::new()) }; + let body = sh.solid()?; + plans.push((sh, body)); + } + let handled = plans.iter().map(|(sh, _)| sh.body.clone()).collect(); + for (sh, body) in plans { + if let Some(mb) = st.bodies.iter_mut().find(|b| b.name == sh.body) { + replace_sheet_body(mb, body); + } + if let Some(target) = st.sheets.iter_mut().find(|s| s.body == sh.body) { + *target = sh; + } + } + Ok(handled) +} + +/// [`sheet_join`] on one sheet: the sheet with each of the join's `regions` (in `plane`, the +/// depth `span` along its normal `n`) taken into the one panel it fits, or None where one of them +/// fits none. +fn sheet_join_one( + original: &sheet::SheetBody, + plane: &Plane, + n: Vec3, + regions: &[Region2], + span: (f64, f64, f64), + work: &mut sheet::FlatWork, +) -> Result> { + let (lo, hi, roundoff) = span; + let sh = original; + let region_of = |pi: Option| match pi { + None => Some(sh.base.clone()), + Some(i) => sh.flanges.get(i).map(|f| sh.panel(f)), + }; + let all: Vec> = std::iter::once(None).chain((0..sh.flanges.len()).map(Some)).collect(); + // The panels whose faces are the sheet's thickness apart along the sketch's normal, the join + // filling exactly that slab. + let pieces: Vec> = all + .iter() + .copied() + .filter(|&pi| { + let w = sh.world(pi); + let sign = crate::apply_vector(&w, Vec3::Z).dot(n); + if sign.abs() < 1.0 - 1e-9 { + return false; + } + let zorigin = (apply_point(&w, Vec3::ZERO) - plane.origin).dot(n); + let (a, b) = ((lo - zorigin) / sign, (hi - zorigin) / sign); + let tol = 1e-6 + roundoff; + a.min(b).abs() <= tol && (a.max(b) - sh.t).abs() <= tol + }) + .collect(); + let zones: Vec = sh.flanges.iter().map(|f| sh.zone(f)).collect(); + let touches = |a: &Region2, b: &Region2, work: &mut sheet::FlatWork| -> Result { + Ok(sheet::material_boolean(std::slice::from_ref(a), std::slice::from_ref(b), kernel::BoolOp::Union, work)?.len() == 1) + }; + // Each region joins the one panel it is one piece with, apart from every bend zone and the + // other panels (touching one along an edge, the flat pattern would lose the cut between them). + let mut fits: Vec<(Option, Region2)> = Vec::new(); + for r in regions { + let mut found = None; + for &pi in &pieces { + let Some(piece) = region_of(pi) else { continue }; + let flat = sh.region_to_flat(pi, plane, r)?; + if !touches(&piece, &flat, work)? { + continue; + } + let mut apart = true; + for other in zones.iter().cloned().chain(all.iter().filter(|&&q| q != pi).filter_map(|&q| region_of(q))) { + if touches(&other, &flat, work)? { + apart = false; + break; + } + } + if !apart { + continue; + } + if found.is_some() { + // Two panels in the plane both take it. + return Ok(None); + } + found = Some((pi, flat)); + } + let Some(fit) = found else { return Ok(None) }; + fits.push(fit); + } + // Pockets, labels, bores and perforations keep their own outlines: not under a join yet. + if !sh.bores.is_empty() || !sh.perforations.is_empty() { + return Ok(None); + } + let flats: Vec = fits.iter().map(|(_, r)| r.clone()).collect(); + let covered: f64 = { + let kept: Vec = sh.pockets.iter().map(|p| p.region.clone()).chain(sh.labels.iter().cloned()).collect(); + sheet::material_boolean(&kept, &flats, kernel::BoolOp::Intersect, work)?.iter().map(Region2::area).sum() + }; + if covered > 1e-9 { + return Ok(None); + } + let mut sh = original.clone(); + for &pi in &all { + let mine: Vec = fits.iter().filter(|(q, _)| *q == pi).map(|(_, r)| r.clone()).collect(); + if mine.is_empty() { + continue; + } + let Some(piece) = region_of(pi) else { return Ok(None) }; + let joined = sheet::material_boolean(std::slice::from_ref(&piece), &mine, kernel::BoolOp::Union, work)?; + let [one] = joined.as_slice() else { return Ok(None) }; + match pi { + None => sh.base = one.clone(), + Some(i) => { + if !one.holes.is_empty() { + return Ok(None); + } + let Some(f) = sh.flanges.get_mut(i) else { return Ok(None) }; + f.exact = Some(one.outer.clone()); + } + } + } + // Cut-outs it covers are filled. + let mut holes = Vec::with_capacity(sh.holes.len()); + for h in &sh.holes { + holes.extend(sheet::material_boolean(std::slice::from_ref(h), &flats, kernel::BoolOp::Cut, work)?); + } + sh.holes = holes; + Ok(Some(sh)) +} + /// Whether a cut of `f` with these targets (else its participants, else its component's /// bodies) machines the sheet `original`. fn sheet_eligible(f: &Feature, st: &ModelState, targets: &[String], original: &crate::sheet::SheetBody) -> bool { @@ -1028,15 +1232,17 @@ pub(super) fn sheet_primitive_cut( return Ok(Vec::new()); } // The first sheet the primitive meets decides the machining direction. Sheets clear of it - // by their boxes are passed over; the one sheet left needs no boolean to show it is met (that - // boolean came out empty against a sheet carrying a label's cut-outs, and the hole was then - // cut into the solid without a place in the flat pattern). - let tool_box = body_box(tool); - let near: Vec<&sheet::SheetBody> = st - .sheets - .iter() - .filter(|sh| sheet_eligible(f, st, &[], sh) && st.body(&sh.body).is_some_and(|mb| !boxes_apart(&mesh_box(mb), &tool_box))) - .collect(); + // by their exact boxes ([`kernel::apart`]) are passed over; the one sheet left needs no + // boolean to show it is met (that boolean came out empty against a sheet carrying a label's + // cut-outs, and the hole was then cut into the solid without a place in the flat pattern). + let mut near: Vec<&sheet::SheetBody> = Vec::new(); + for sh in st.sheets.iter().filter(|sh| sheet_eligible(f, st, &[], sh)) { + if let Some(mb) = st.body(&sh.body) + && !kernel::apart(&mb.body, tool)? + { + near.push(sh); + } + } let mut normal = None; for sh in &near { if let Some(mb) = st.body(&sh.body) @@ -1059,24 +1265,61 @@ pub(super) fn sheet_primitive_cut( sheet_prism_cut(f, st, &plane, std::slice::from_ref(®ion), operation, &tools, &[], None, false, &[], warning) } +/// How a hole's straight drill machines the sheets it meets, from the panels it passes through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Drill { + /// Square across every panel it meets: a cut-out or pocket of the flat pattern + /// ([`sheet_primitive_cut`]). + Across, + /// Along every panel it meets, into a rim: a bore of each ([`sheet_bore_cut`]). + Along, +} + +/// Which [`Drill`] a hole's straight drill is for the sheets `f` machines; None when it meets +/// none of them. A box is a prism across its sheet. A drill square to some panels it meets and +/// along others, or at an angle to one, has no exact place in the flat pattern and is refused. +pub(super) fn sheet_drill(f: &Feature, st: &ModelState, prism: PrimitivePrism) -> Result> { + let PrimitivePrism::Cylinder { base, axis, radius, height } = prism else { return Ok(Some(Drill::Across)) }; + let mut squares = Vec::new(); + for sh in st.sheets.iter().filter(|sh| sheet_eligible(f, st, &[], sh)) { + squares.extend(sh.drilled_panels(base, axis, radius, height)?.into_iter().map(|(_, square)| square)); + } + if squares.is_empty() { + Ok(None) + } else if squares.iter().all(|s| *s >= 1.0 - 1e-6) { + Ok(Some(Drill::Across)) + } else if squares.iter().all(|s| *s <= 1e-6) { + Ok(Some(Drill::Along)) + } else { + Err(DocError::Invalid("this hole crosses a sheet panel at an angle; drill it square to the panel, or along it into a rim".into())) + } +} + /// A hole's straight drill along a panel of a sheet (into its rim), kept as a bore of each /// panel it meets (see [`crate::sheet::SheetBore`]), so the sheet still unfolds. Returns the -/// sheet bodies it machined; None, with the model as it was, when the drill is not a plain -/// cylinder or a sheet it meets can't keep it that way (it runs into a bend, or crosses a -/// panel at an angle). +/// sheet bodies it machined; None when the drill is not a plain cylinder or meets no sheet. pub(super) fn sheet_bore_cut(f: &Feature, st: &mut ModelState, prism: PrimitivePrism) -> Result>> { let PrimitivePrism::Cylinder { base, axis, radius, height } = prism else { return Ok(None) }; + // Drilling a sheet builds each of its panels and runs a boolean on it, only to find that a + // drill far off meets none (#10226): a sheet whose box lies clear of the drill's is left out. + // Both boxes are the exact ones, grown by the bodies' tolerances, as for the other sheet + // cuts. A drill a sheet refuses whatever it meets (not a cylinder, or the + // sheet holds all the bores it may) is still put to every sheet. + let reach = drill_box(base, axis, radius, height); let mut plans = Vec::new(); for original in &st.sheets { if !sheet_eligible(f, st, &[], original) { continue; } + if !original.bores_full() && st.body(&original.body).is_some_and(|mb| boxes_apart(&exact_box(&mb.body), &reach)) { + continue; + } let mut sh = original.clone(); + #[cfg(test)] + super::cost_tests::count(|c| c.cut += 1); match sh.add_bore(base, axis, radius, height) { Ok(true) => {} Ok(false) => continue, - // Refused here, the hole keeps the message of the machining it was first tried as. - Err(DocError::Invalid(_)) => return Ok(None), Err(e) => return Err(e), } let body = sh.solid()?; @@ -1098,6 +1341,16 @@ pub(super) fn sheet_bore_cut(f: &Feature, st: &mut ModelState, prism: PrimitiveP Ok(Some(handled)) } +/// [`exact_box`] of a hole's drill as [`crate::sheet::SheetBody::add_bore`] makes it; None +/// (never apart) for a drill it refuses. +fn drill_box(base: Vec3, axis: Vec3, radius: f64, height: f64) -> Option { + let axis = axis.normalized()?; + if ![base.x, base.y, base.z, radius, height].iter().all(|v| v.is_finite()) || !(radius > 0.0) || height == 0.0 { + return None; + } + exact_box(&kernel::cylinder(base, axis, radius, height).ok()?) +} + /// The most hole tools machined in one pass by [`sheet_drill_cuts`]. const MAX_DRILLS_AT_ONCE: usize = 1000; @@ -1106,8 +1359,8 @@ const MAX_DRILLS_AT_ONCE: usize = 1000; /// of them, rather than one per drill, each on a sheet machined by the ones before. /// The drills are the cut-outs and pockets [`sheet_primitive_cut`] makes of them one at a time. /// None when they can't all be taken this way (they are not all cylinders along one axis that -/// every sheet they may machine takes square, or a sheet keeps one some other way): the caller -/// then puts the model back and drills them one by one. +/// every sheet they may machine takes square, or a depth of them meets no sheet): the caller then +/// puts the model back and drills them one by one. pub(super) fn sheet_drill_cuts( f: &Feature, st: &mut ModelState, @@ -1321,9 +1574,6 @@ fn sheet_prism_cut( } else { Vec::new() }; - // Boxes around the tools: a tool clear of a bend by its box needs no boolean to show it (a - // label's letters against every bend and flange of a tray). - let tool_boxes: Vec> = tools.iter().map(body_box).collect(); let mut plans = Vec::new(); let mut notes = Vec::new(); 'sheets: for original in &st.sheets { @@ -1343,12 +1593,10 @@ fn sheet_prism_cut( // is exact, and a cut that machines nothing there is checked against the solid after it. // (That boolean cost each label hundreds of milliseconds, and against a sheet already // carrying a label's cut-outs it came out empty: the next cut was dropped.) + // A tool clear of a bend by its exact box (a label's letters against every bend and + // flange of a tray) costs no intersection work: the boolean answers it from the boxes. for bends in sh.unmodeled_solids(plane)? { - let bends_box = body_box(&bends); - for (tool, tool_box) in tools.iter().zip(&tool_boxes) { - if boxes_apart(&bends_box, tool_box) { - continue; - } + for tool in tools { if kernel::boolean(&bends, tool, kernel::BoolOp::Intersect)?.is_some() { return Err(DocError::Invalid( "this machining intersects a folded bend or a nonparallel panel; unfold the sheet before machining that material".into(), @@ -1400,6 +1648,13 @@ fn sheet_prism_cut( } let (a, b) = nominal_depth.unwrap_or((a, b)); let (z0, z1) = (a.min(b).max(0.0), a.max(b).min(sh.t)); + // A depth within a few units in the last place of the numbers it is worked out from + // is on the face: a flange panel's frame, turned by the cosine and sine of its angle, + // puts its faces an ulp (2e-16 mm) off the tool's cap they meet. A thinner layer is + // the tool's own and stays (refused below when under the resolution). + let ulps = + 4.0 * f64::EPSILON * (apply_point(&w, Vec3::ZERO).len() + plane.origin.len() + span.0.abs() + span.1.abs() + sh.t) / sign.abs(); + let (z0, z1) = (if z0 <= ulps { 0.0 } else { z0 }, if sh.t - z1 <= ulps { sh.t } else { z1 }); // Sub-resolution layers must not be silently erased by endpoint snapping. let depth_resolved = ![z0, sh.t - z1, z1 - z0].into_iter().any(|d| d > 0.0 && d < 1e-6); labels.extend(letters.iter().filter_map(|r| sh.region_to_flat(pi, plane, r).ok())); @@ -1526,25 +1781,36 @@ fn sheet_prism_cut( Ok(handled) } -/// A box around `body`, grown past its mesh's deflection from the exact faces (and a hair -/// more): bodies whose boxes are apart do not meet. None when it can't be worked out. -fn body_box(body: &Body) -> Option { - let tol = (body.size() * 1e-3).max(1e-4); - padded_box(&body.tessellate(tol).ok()?, tol) +/// The exact box of `body`, grown by twice its tolerance: bodies whose boxes are apart do not +/// meet. None when it can't be worked out. +pub(super) fn exact_box(body: &Body) -> Option { + let b = body.exact_bounds().ok()?; + (!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| b.inflated(2.0 * body.record().tolerance + 1e-6)) } -/// [`body_box`] of a model body, from the mesh it keeps. -fn mesh_box(mb: &ModelBody) -> Option { - padded_box(&mb.mesh(), mb.display_tol()) -} - -fn padded_box(mesh: &solidcraft_geom::Mesh, tol: f64) -> Option { - let b = mesh.bounds(); - (!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| b.inflated(2.0 * tol + 1e-6)) +/// Whether the line through `at` along `dir` is known to pass farther than `reach` from the +/// exact box of `mb` ([`exact_box`]) everywhere, and so from every point of the body. Unknown is +/// never. +pub(super) fn line_beyond_reach(mb: &ModelBody, at: Vec3, dir: Vec3, reach: f64) -> bool { + let Some(b) = exact_box(&mb.body) else { return false }; + let b = b.inflated(reach); + let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY); + for (a, d, min, max) in [(at.x, dir.x, b.min.x, b.max.x), (at.y, dir.y, b.min.y, b.max.y), (at.z, dir.z, b.min.z, b.max.z)] { + if d == 0.0 { + if a < min || a > max { + return true; + } + continue; + } + let (t0, t1) = ((min - a) / d, (max - a) / d); + lo = lo.max(t0.min(t1)); + hi = hi.min(t0.max(t1)); + } + lo > hi } /// Whether two boxes are known to be apart (an unknown box is never apart). -fn boxes_apart(a: &Option, b: &Option) -> bool { +pub(super) fn boxes_apart(a: &Option, b: &Option) -> bool { let (Some(a), Some(b)) = (a, b) else { return false }; a.max.x < b.min.x || b.max.x < a.min.x || a.max.y < b.min.y || b.max.y < a.min.y || a.max.z < b.min.z || b.max.z < a.min.z } @@ -1578,43 +1844,58 @@ fn parted_note(sh: &sheet::SheetBody, material: &[Region2], before: &sheet::Shee }) } -/// Outline loops (in `plane` coordinates) of the mesh triangles lying in the plane at distance -/// `level` from `at` along `n`: the edges used by one of them only, chained. -fn face_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3, level: f64, tol: f64) -> Vec> { - face_outline(mesh, plane, at, n, level, tol).into_iter().map(|l| l.into_iter().map(|(p, _)| p).collect()).collect() +/// The face that [`FaceSlice::loops`], [`FaceSlice::outline`] and [`FaceSlice::recesses`] measure: +/// the mesh, the plane the outline's coordinates live in, the point `at` and normal `n` that levels +/// are measured from, and the tolerance. Callers build it once and pass it on unchanged. +/// (`n` stays a `Vec3` until #2675 lands `UnitVec3` upstream.) +struct FaceSlice<'a> { + mesh: &'a Mesh, + plane: Plane, + at: Vec3, + n: Vec3, + tol: f64, } -/// [`face_loops`] with each point's B-rep face across the outline from it to the next point (the -/// wall the outline runs along there): the face off the plane that meets both points. -fn face_outline(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3, level: f64, tol: f64) -> Vec)>> { - let on_plane = |t: &[u32; 3]| t.iter().all(|k| mesh.positions.get(*k as usize).is_some_and(|p| ((*p - at).dot(n) - level).abs() < tol)); - let on: Vec<[u32; 3]> = mesh.triangles.iter().copied().filter(on_plane).collect(); - let pos = |k: u32| mesh.positions.get(k as usize).copied().unwrap_or_default(); - let q = |p: Vec3| ((p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64, (p.z * 1e6).round() as i64); - // The faces off the plane at each point on it, by position to a millionth of a millimetre - // either way (a neighbouring face's mesh may round a shared point differently). - let mut touch: std::collections::HashMap<(i64, i64, i64), Vec> = Default::default(); - for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face).filter(|(t, _)| !on_plane(t)) { - for p in t.iter().map(|k| pos(*k)).filter(|p| ((*p - at).dot(n) - level).abs() < tol) { - let faces = touch.entry(q(p)).or_default(); - if !faces.contains(f) { - faces.push(*f); +impl FaceSlice<'_> { + /// Outline loops (in `plane` coordinates) of the mesh triangles lying in the plane at distance + /// `level` from `at` along `n`: the edges used by one of them only, chained. + fn loops(&self, level: f64) -> Vec> { + self.outline(level).into_iter().map(|l| l.into_iter().map(|(p, _)| p).collect()).collect() + } + + /// [`FaceSlice::loops`] with each point's B-rep face across the outline from it to the next + /// point (the wall the outline runs along there): the face off the plane that meets both points. + fn outline(&self, level: f64) -> Vec)>> { + let (mesh, plane, at, n, tol) = (self.mesh, &self.plane, self.at, self.n, self.tol); + let on_plane = |t: &[u32; 3]| t.iter().all(|k| mesh.positions.get(*k as usize).is_some_and(|p| ((*p - at).dot(n) - level).abs() < tol)); + let on: Vec<[u32; 3]> = mesh.triangles.iter().copied().filter(on_plane).collect(); + let pos = |k: u32| mesh.positions.get(k as usize).copied().unwrap_or_default(); + let q = |p: Vec3| ((p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64, (p.z * 1e6).round() as i64); + // The faces off the plane at each point on it, by position to a millionth of a millimetre + // either way (a neighbouring face's mesh may round a shared point differently). + let mut touch: std::collections::HashMap<(i64, i64, i64), Vec> = Default::default(); + for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face).filter(|(t, _)| !on_plane(t)) { + for p in t.iter().map(|k| pos(*k)).filter(|p| ((*p - at).dot(n) - level).abs() < tol) { + let faces = touch.entry(q(p)).or_default(); + if !faces.contains(f) { + faces.push(*f); + } } } + let near = |p: Vec3| { + let (x, y, z) = q(p); + let cells = (-1..=1).flat_map(|i| (-1..=1).flat_map(move |j| (-1..=1).map(move |k| (x + i, y + j, z + k)))); + let mut faces: Vec = cells.filter_map(|c| touch.get(&c)).flatten().copied().collect(); + faces.sort_unstable(); + faces.dedup(); + faces + }; + let across = |a: Vec3, b: Vec3| { + let at_b = near(b); + near(a).into_iter().find(|f| at_b.contains(f)) + }; + chain_loops(mesh, plane, &on, across) } - let near = |p: Vec3| { - let (x, y, z) = q(p); - let cells = (-1..=1).flat_map(|i| (-1..=1).flat_map(move |j| (-1..=1).map(move |k| (x + i, y + j, z + k)))); - let mut faces: Vec = cells.filter_map(|c| touch.get(&c)).flatten().copied().collect(); - faces.sort_unstable(); - faces.dedup(); - faces - }; - let across = |a: Vec3, b: Vec3| { - let at_b = near(b); - near(a).into_iter().find(|f| at_b.contains(f)) - }; - chain_loops(mesh, plane, &on, across) } /// The loops (in `plane` coordinates) that bound the triangles `on` of the mesh. @@ -1704,138 +1985,142 @@ struct LevelFace { tris: Vec<(Vec3, f64)>, } -/// The recesses of a plate lying between levels `lo` and `hi` along `n` (measured from `at`), -/// whose sheet is built in `plane`. A recess's floor is a face parallel to the plate inside its -/// thickness, lying in an opening of the face it is cut into, and its walls are square to the -/// plate (walls that are not show as material the plate's volume doesn't account for). A body -/// that is no plate once its recesses are filled has none, so the plate check refuses it as -/// before: a bent part, whose legs' faces lie inside its extent. Recesses are taken in one face -/// only, up to half the thickness deep, and no larger than the face they are cut into (a plate -/// raised in places is no plate of the raised thickness). -fn plate_recesses(body: &Body, mesh: &Mesh, plane: &Plane, at: Vec3, n: Vec3, (lo, hi): (f64, f64), tol: f64) -> Result { - let t = hi - lo; - let eps = t * 1e-3; - let level = |p: Vec3| (p - at).dot(n); - let mut faces: BTreeMap> = BTreeMap::new(); - for (tri, f) in mesh.triangles.iter().zip(&mesh.tri_face) { - let Some([a, b, c]) = mesh.tri(tri) else { continue }; - let cr = (b - a).cross(c - a); - let len = cr.len(); - if !(len > 1e-12) { - continue; - } - let up = cr.dot(n) > 0.0; - let entry = faces.entry(*f).or_insert(Some(LevelFace { lo: f64::MAX, hi: f64::MIN, up, area: 0.0, at: a, tris: Vec::new() })); - match entry { - Some(face) if face.up == up && cr.dot(n).abs() >= len * (1.0 - 1e-6) => { - for p in [a, b, c] { - face.lo = face.lo.min(level(p)); - face.hi = face.hi.max(level(p)); +impl FaceSlice<'_> { + /// The recesses of a plate lying between levels `lo` and `hi` along `n` (measured from `at`), + /// whose sheet is built in `plane`. A recess's floor is a face parallel to the plate inside its + /// thickness, lying in an opening of the face it is cut into, and its walls are square to the + /// plate (walls that are not show as material the plate's volume doesn't account for). A body + /// that is no plate once its recesses are filled has none, so the plate check refuses it as + /// before: a bent part, whose legs' faces lie inside its extent. Recesses are taken in one face + /// only, up to half the thickness deep, and no larger than the face they are cut into (a plate + /// raised in places is no plate of the raised thickness). + fn recesses(&self, body: &Body, (lo, hi): (f64, f64)) -> Result { + let (mesh, plane, at, n, tol) = (self.mesh, &self.plane, self.at, self.n, self.tol); + let t = hi - lo; + let eps = t * 1e-3; + let level = |p: Vec3| (p - at).dot(n); + let mut faces: BTreeMap> = BTreeMap::new(); + for (tri, f) in mesh.triangles.iter().zip(&mesh.tri_face) { + let Some([a, b, c]) = mesh.tri(tri) else { continue }; + let cr = (b - a).cross(c - a); + let len = cr.len(); + if !(len > 1e-12) { + continue; + } + let up = cr.dot(n) > 0.0; + let entry = faces.entry(*f).or_insert(Some(LevelFace { lo: f64::MAX, hi: f64::MIN, up, area: 0.0, at: a, tris: Vec::new() })); + match entry { + Some(face) if face.up == up && cr.dot(n).abs() >= len * (1.0 - 1e-6) => { + for p in [a, b, c] { + face.lo = face.lo.min(level(p)); + face.hi = face.hi.max(level(p)); + } + face.area += len / 2.0; + face.tris.push(((a + b + c) / 3.0, len / 2.0)); } - face.area += len / 2.0; - face.tris.push(((a + b + c) / 3.0, len / 2.0)); + _ => *entry = None, } - _ => *entry = None, } - } - // The floors (face index, level, the face), and the areas of the plate's two faces (at `lo` - // and at `hi`). - let mut floors: Vec<(usize, f64, &LevelFace)> = Vec::new(); - let (mut bottom, mut top) = (0.0, 0.0); - for (f, face) in faces.iter().filter_map(|(f, face)| Some((*f as usize, face.as_ref()?))) { - let d = (face.lo + face.hi) / 2.0; - if face.hi - face.lo > eps { - continue; - } else if (d - hi).abs() <= eps && face.up { - top += face.area; - } else if (d - lo).abs() <= eps && !face.up { - bottom += face.area; - } else if d > lo + eps && d < hi - eps { - floors.push((f, d, face)); + // The floors (face index, level, the face), and the areas of the plate's two faces (at `lo` + // and at `hi`). + let mut floors: Vec<(usize, f64, &LevelFace)> = Vec::new(); + let (mut bottom, mut top) = (0.0, 0.0); + for (f, face) in faces.iter().filter_map(|(f, face)| Some((*f as usize, face.as_ref()?))) { + let d = (face.lo + face.hi) / 2.0; + if face.hi - face.lo > eps { + continue; + } else if (d - hi).abs() <= eps && face.up { + top += face.area; + } else if (d - lo).abs() <= eps && !face.up { + bottom += face.area; + } else if d > lo + eps && d < hi - eps { + floors.push((f, d, face)); + } } - } - let none = || Recesses { level: lo, pockets: Vec::new(), volume: 0.0 }; - if floors.is_empty() { - return Ok(none()); - } - // A floor is a recess's where (most of) it lies in an opening of the face it is cut into: - // inside that face's outline and in a hole of it, not on an island in the hole. (Its - // triangles are those at its level within `eps`: `tol` may exceed a recess's depth.) - let loops_at = |level: f64| -> Vec { face_loops(mesh, plane, at, n, level, eps).into_iter().map(|l| Loop2::polygon(&l)).collect() }; - let (top_loops, bottom_loops) = (loops_at(hi), loops_at(lo)); - floors.retain(|(_, _, face)| { - let loops = if face.up { &top_loops } else { &bottom_loops }; - let open = |p: Vec2| { - let k = loops.iter().filter(|l| l.contains(p)).count(); - k >= 2 && k.is_multiple_of(2) - }; - face.tris.iter().filter(|(c, _)| open(plane.to_local(*c))).map(|(_, a)| a).sum::() > face.area / 2.0 - }); - let Some(&(_, _, first)) = floors.first() else { return Ok(none()) }; - // Filled, the recesses leave a plate: its outline as large at `lo` as at `hi` once their - // openings count, and its volume with theirs the outline times the thickness. Else (a bent - // part) they are none. - let depth_in = |d: f64, up: bool| if up { hi - d } else { d - lo }; - let opened = |up: bool| floors.iter().filter(|f| f.2.up == up).map(|f| f.2.area).sum::(); - let outline = bottom + opened(false); - let removed: f64 = floors.iter().map(|f| f.2.area * depth_in(f.1, f.2.up)).sum(); - let volume = kernel::measure(body)?.volume; - if (outline - top - opened(true)).abs() > 1e-3 * outline || (outline * t - volume - removed).abs() > 1e-3 * volume.max(1.0) { - return Ok(none()); - } - let pt = |p: Vec3| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z); - let up = first.up; - if let Some(other) = floors.iter().find(|f| f.2.up != up) { - return Err(DocError::Invalid(format!( - "not supported yet: converting a plate with recesses in both faces (at {} and {}); recesses in one face become pockets", - pt(first.at), - pt(other.2.at) - ))); - } - let depth_of = |d: f64| depth_in(d, up); - if let Some(deep) = floors.iter().find(|f| depth_of(f.1) > t / 2.0 + eps) { - return Err(DocError::Invalid(format!( - "not supported yet: the recess at {} is {:.3} mm deep, more than half the plate's {:.3} mm; shallower recesses (an engraving, a label) become pockets", - pt(deep.2.at), - depth_of(deep.1), - t - ))); - } - let face_area = if up { top } else { bottom }; - if floors.iter().map(|f| f.2.area).sum::() > face_area { - return Err(DocError::Invalid(format!( - "not supported yet: converting a plate whose recesses are larger than the face they are in (a plate thinner than {t:.3} mm, raised in places)" - ))); - } - // The floors' outlines, from a mesh fine enough to mark them by. - let fine = body.tessellate((t * 1e-2).min(tol).max(1e-4))?; - floors.sort_by(|a, b| depth_of(a.1).total_cmp(&depth_of(b.1))); - // Floors at one depth are one pocket where they meet. - let mut groups: Vec<(f64, Vec)> = Vec::new(); - for (f, d, ..) in &floors { - let on: Vec<[u32; 3]> = fine.triangles.iter().zip(&fine.tri_face).filter(|(_, g)| **g as usize == *f).map(|(tri, _)| *tri).collect(); - let mut loops = boundary_loops(&fine, plane, &on); - loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs())); - let mut it = loops.into_iter(); - let Some(outline) = it.next() else { continue }; - let region = Region2 { outer: Loop2::polygon(&outline).ccw(), holes: it.map(|l| Loop2::polygon(&l).ccw().reversed()).collect() }; - match groups.last_mut() { - Some((depth, regions)) if depth_of(*d) - *depth <= eps => regions.push(region), - _ => groups.push((depth_of(*d), vec![region])), + let none = || Recesses { level: lo, pockets: Vec::new(), volume: 0.0 }; + if floors.is_empty() { + return Ok(none()); } - } - // The sheet's z starts from the picked face when its plane faces away from that face. - let from_zero = up == (plane.normal().dot(n) < 0.0); - let mut work = sheet::FlatWork::new(); - let (mut pockets, mut volume) = (Vec::new(), 0.0); - for (depth, regions) in groups { - let (z0, z1) = if from_zero { (0.0, depth) } else { (t - depth, t) }; - for region in sheet::material_union(regions, &mut work)? { - volume += region.area().abs() * depth; - pockets.push((region, z0, z1)); + // A floor is a recess's where (most of) it lies in an opening of the face it is cut into: + // inside that face's outline and in a hole of it, not on an island in the hole. (Its + // triangles are those at its level within `eps`: `tol` may exceed a recess's depth.) + let probe = FaceSlice { mesh, plane: self.plane, at, n, tol: eps }; + let loops_at = |level: f64| -> Vec { probe.loops(level).into_iter().map(|l| Loop2::polygon(&l)).collect() }; + let (top_loops, bottom_loops) = (loops_at(hi), loops_at(lo)); + floors.retain(|(_, _, face)| { + let loops = if face.up { &top_loops } else { &bottom_loops }; + let open = |p: Vec2| { + let k = loops.iter().filter(|l| l.contains(p)).count(); + k >= 2 && k.is_multiple_of(2) + }; + face.tris.iter().filter(|(c, _)| open(plane.to_local(*c))).map(|(_, a)| a).sum::() > face.area / 2.0 + }); + let Some(&(_, _, first)) = floors.first() else { return Ok(none()) }; + // Filled, the recesses leave a plate: its outline as large at `lo` as at `hi` once their + // openings count, and its volume with theirs the outline times the thickness. Else (a bent + // part) they are none. + let depth_in = |d: f64, up: bool| if up { hi - d } else { d - lo }; + let opened = |up: bool| floors.iter().filter(|f| f.2.up == up).map(|f| f.2.area).sum::(); + let outline = bottom + opened(false); + let removed: f64 = floors.iter().map(|f| f.2.area * depth_in(f.1, f.2.up)).sum(); + let volume = kernel::measure(body)?.volume; + if (outline - top - opened(true)).abs() > 1e-3 * outline || (outline * t - volume - removed).abs() > 1e-3 * volume.max(1.0) { + return Ok(none()); } + let pt = |p: Vec3| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z); + let up = first.up; + if let Some(other) = floors.iter().find(|f| f.2.up != up) { + return Err(DocError::Invalid(format!( + "not supported yet: converting a plate with recesses in both faces (at {} and {}); recesses in one face become pockets", + pt(first.at), + pt(other.2.at) + ))); + } + let depth_of = |d: f64| depth_in(d, up); + if let Some(deep) = floors.iter().find(|f| depth_of(f.1) > t / 2.0 + eps) { + return Err(DocError::Invalid(format!( + "not supported yet: the recess at {} is {:.3} mm deep, more than half the plate's {:.3} mm; shallower recesses (an engraving, a label) become pockets", + pt(deep.2.at), + depth_of(deep.1), + t + ))); + } + let face_area = if up { top } else { bottom }; + if floors.iter().map(|f| f.2.area).sum::() > face_area { + return Err(DocError::Invalid(format!( + "not supported yet: converting a plate whose recesses are larger than the face they are in (a plate thinner than {t:.3} mm, raised in places)" + ))); + } + // The floors' outlines, from a mesh fine enough to mark them by. + let fine = body.mesh(&solidcraft_kernel::MeshTolerance::chord((t * 1e-2).min(tol).max(1e-4)))?; + floors.sort_by(|a, b| depth_of(a.1).total_cmp(&depth_of(b.1))); + // Floors at one depth are one pocket where they meet. + let mut groups: Vec<(f64, Vec)> = Vec::new(); + for (f, d, ..) in &floors { + let on: Vec<[u32; 3]> = fine.triangles.iter().zip(&fine.tri_face).filter(|(_, g)| **g as usize == *f).map(|(tri, _)| *tri).collect(); + let mut loops = boundary_loops(&fine, plane, &on); + loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs())); + let mut it = loops.into_iter(); + let Some(outline) = it.next() else { continue }; + let region = Region2 { outer: Loop2::polygon(&outline).ccw(), holes: it.map(|l| Loop2::polygon(&l).ccw().reversed()).collect() }; + match groups.last_mut() { + Some((depth, regions)) if depth_of(*d) - *depth <= eps => regions.push(region), + _ => groups.push((depth_of(*d), vec![region])), + } + } + // The sheet's z starts from the picked face when its plane faces away from that face. + let from_zero = up == (plane.normal().dot(n) < 0.0); + let mut work = sheet::FlatWork::new(); + let (mut pockets, mut volume) = (Vec::new(), 0.0); + for (depth, regions) in groups { + let (z0, z1) = if from_zero { (0.0, depth) } else { (t - depth, t) }; + for region in sheet::material_union(regions, &mut work)? { + volume += region.area().abs() * depth; + pockets.push((region, z0, z1)); + } + } + Ok(Recesses { level: if up { lo } else { hi }, pockets, volume }) } - Ok(Recesses { level: if up { lo } else { hi }, pockets, volume }) } /// The body a placed plastic feature joins: by name, else the one under the point. @@ -1857,27 +2142,6 @@ fn local_frame(z: Vec3, x: Option) -> Result<(Vec3, Vec3, Vec3)> { Ok((x, y, z)) } -/// Offset a closed polygon to its left by `d` (mitred corners). -fn offset_left(p: &[Vec2], d: f64) -> Vec { - let m = p.len(); - let line = |i: usize| -> Option<(Vec2, Vec2)> { - let (a, b) = (*p.get(i)?, *p.get((i + 1) % m)?); - let t = (b - a).normalized()?; - Some((a + Vec2::new(-t.y, t.x) * d, t)) - }; - (0..m) - .filter_map(|i| { - let (p0, d0) = line((i + m - 1) % m)?; - let (p1, d1) = line(i)?; - let den = d0.cross(d1); - if den.abs() < 1e-12 { - return Some(p1); - } - Some(p0 + d0 * ((p1 - p0).cross(d1) / den)) - }) - .collect() -} - /// The smallest size a plastic feature's lengths may have, in millimetres. Thinner walls and /// shorter arms than this are below what the solid booleans can resolve. const PLASTIC_MIN_SIZE: f64 = 0.01; @@ -1899,7 +2163,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F let rule = |target: &str| -> Result> { doc.plastic_rule_for(target).map(|r| doc.plastic_values(vals, &r)).transpose() }; - // Tools start a little inside the material so they overlap it instead of touching a face. + // Each tool stands on the face as drawn: SMLib joins and cuts touching faces exactly. match &f.kind { FeatureKind::Boss { position, @@ -1931,16 +2195,14 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F if r_top <= 0.0 { return Err(DocError::Invalid("the draft closes the boss before its top".into())); } - let delta = (h * 0.05).clamp(1e-3, 0.5); let (x, _, z) = local_frame(direction.0, None)?; - // The post: a (tapered) cylinder from a little inside the face. - let base = Plane::new(position.0 - z * delta, x, z.cross(x)).ok_or_else(|| DocError::Invalid("boss frame".into()))?; - let r_in = r0 + delta * dr.tan(); - let disc = Region2 { outer: Loop2::circle(Vec2::ZERO, r_in), holes: Vec::new() }; + // The post: a (tapered) cylinder standing on the face. + let base = Plane::new(position.0, x, z.cross(x)).ok_or_else(|| DocError::Invalid("boss frame".into()))?; + let disc = Region2 { outer: Loop2::circle(Vec2::ZERO, r0), holes: Vec::new() }; let post = if dr.abs() > 1e-12 { - vec![kernel::extrude_tapered(&base, &disc, h + delta, 1.0, -dr)?] + vec![kernel::extrude_tapered(&base, &disc, h, 1.0, -dr, kernel::DraftCorner::default())?] } else { - kernel::extrude(&base, &[disc], 0.0, h + delta)? + kernel::extrude(&base, &[disc], 0.0, h)? }; let mut tools: Vec = post.into_iter().map(|b| crate::lineage::part_tool(b, "post")).collect(); if let Some(n) = ribs { @@ -1979,7 +2241,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F ]), holes: Vec::new(), }; - tools.extend(kernel::extrude(&rp, &[rect], -delta, hr)?.into_iter().map(|b| crate::lineage::part_tool(b, &format!("rib{k}")))); + tools.extend(kernel::extrude(&rp, &[rect], 0.0, hr)?.into_iter().map(|b| crate::lineage::part_tool(b, &format!("rib{k}")))); } } apply_traced(doc, st, f, tools, Operation::Join, std::slice::from_ref(&target))?; @@ -2004,7 +2266,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F return Err(DocError::Invalid("the boss hole must fit inside the boss".into())); } let hp = Plane::new(position.0, x, z.cross(x)).ok_or_else(|| DocError::Invalid("hole frame".into()))?; - let tool = kernel::extrude(&hp, &[Region2 { outer: Loop2::circle(Vec2::ZERO, rh), holes: Vec::new() }], h - depth, h + delta)?; + let tool = kernel::extrude(&hp, &[Region2 { outer: Loop2::circle(Vec2::ZERO, rh), holes: Vec::new() }], h - depth, h)?; let tool = tool.into_iter().map(|b| crate::lineage::part_tool(b, "hole")).collect(); apply_traced(doc, st, f, tool, Operation::Cut, std::slice::from_ref(&target))?; } @@ -2026,8 +2288,9 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F } let plane = Plane::from_normal(face.0, n).ok_or_else(|| DocError::Invalid("rim plane".into()))?; let tol = (mb.body.size() * 1e-3).max(1e-3); - let mesh = mb.body.tessellate(tol)?; - let mut loops = face_loops(&mesh, &plane, face.0, n, 0.0, tol); + let mesh = mb.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol))?; + let slice = FaceSlice { mesh: &mesh, plane, at: face.0, n, tol }; + let mut loops = slice.loops(0.0); loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs())); let ccw = |l: &Ring| if l.signed_area() < 0.0 { l.iter().rev().copied().collect::>() } else { l.clone() }; // The inner edge is an opening (the cavity under a rim): not the foot of a boss or a @@ -2048,55 +2311,32 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F [a, b, ..] => b.signed_area().abs() > 0.5 * a.signed_area().abs(), _ => false, }; - let (Some(outer), Some(inner), false) = (outer, openings.first().cloned(), alike) else { + let (Some(_), Some(_), false) = (outer, openings.first(), alike) else { + // A solid box top has no opening: Shell that face first, then pick the rim + // around the cavity (#10437). let what = match (loops.len(), openings.len()) { - (0 | 1, _) => "pick the rim face of a shelled body (a face with an inner and an outer edge)".to_string(), - (_, 0) => "pick the rim face of a shelled body: this face's inner edges are where other features stand on it, not an opening" + (0 | 1, _) => "Lip needs the rim of a shelled body: Shell a face open first, then pick the rim around that opening (a face with an outer edge and an inner hole)" .to_string(), - (_, k) => format!("pick the rim face of a shelled body (round one opening): this face has {k} openings alike in size"), + (_, 0) => "Lip needs a rim around an opening: this face's inner edges are where other features stand on it, not a shell cavity. Shell a face open, then pick that rim" + .to_string(), + (_, k) => format!( + "Lip needs one clear opening as the rim: this face has {k} openings alike in size (for example a plate of holes). Shell one cavity, or pick a rim that rings a single opening" + ), }; return Err(DocError::Invalid(what)); }; - let bw = if *groove { w + g } else { w }; - // A lip: the band raised from the rim's own faces (its walls continue the walls - // below, which a join can't do: they would coincide). - if !*groove - && let Ok(b) = kernel::raise_band(&mb.body, face.0, w, h, *outside) - && let Some(slot) = st.bodies.iter_mut().find(|x| x.name == target) - { + // A lip: the band raised from the rim's own faces, its walls continuing the walls below. + if !*groove { + let b = kernel::raise_band(&mb.body, face.0, w, h, *outside)?; + let slot = st.bodies.iter_mut().find(|x| x.name == target).ok_or_else(|| DocError::Invalid("body".into()))?; *slot = ModelBody::traced_new(target.clone(), Traced::step(b, &[&mb.traced()]), slot.feature); return Ok(()); } - // The band along the chosen edge, inside the rim face. A groove's cutter reaches past - // the edge into the free side (the cavity, or outside), so no wall coincides. - let free = if *groove { bw } else { 0.0 }; - let (plane, band) = if let Ok(exact) = kernel::rim_band(&mb.body, face.0, bw, free, *outside) { - exact - } else if *outside { - ( - plane, - Region2 { - outer: Loop2::polygon(&offset_left(&outer, -free)).ccw(), - holes: vec![Loop2::polygon(&offset_left(&outer, bw)).ccw().reversed()], - }, - ) - } else { - ( - plane, - Region2 { - outer: Loop2::polygon(&offset_left(&inner, -bw)).ccw(), - holes: vec![Loop2::polygon(&offset_left(&inner, free)).ccw().reversed()], - }, - ) - }; - let delta = (h * 0.05).clamp(1e-3, 0.5); - if *groove { - let tool = kernel::extrude(&plane, &[band], -(h + g), delta)?.into_iter().map(|b| crate::lineage::part_tool(b, "groove")).collect(); - apply_traced(doc, st, f, tool, Operation::Cut, std::slice::from_ref(&target)) - } else { - let tool = kernel::extrude(&plane, &[band], -delta, h)?.into_iter().map(|b| crate::lineage::part_tool(b, "lip")).collect(); - apply_traced(doc, st, f, tool, Operation::Join, std::slice::from_ref(&target)) - } + // A groove: the band along the chosen edge, inside the rim face, its gap included, + // cut down from the face. + let (plane, band) = kernel::rim_band(&mb.body, face.0, w + g, 0.0, *outside)?; + let tool = kernel::extrude(&plane, &[band], -(h + g), 0.0)?.into_iter().map(|b| crate::lineage::part_tool(b, "groove")).collect(); + apply_traced(doc, st, f, tool, Operation::Cut, std::slice::from_ref(&target)) } FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, base_height, new_body, body } => { let target = body_under(st, body, position.0)?; @@ -2108,11 +2348,9 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F return Err(DocError::Invalid("the snap fit's catch must be shorter than its arm".into())); } let (x, y, z) = local_frame(direction.0, Some(hook.0))?; - let delta = (l * 0.05).clamp(1e-3, 0.5); // Side profile (x = toward the catch, y = up the arm), extruded across the width. - // The base reaches `base_height` below the face; a joined arm bites `delta` into - // the wall, a separate body sits flush on it. - let y0 = if *new_body { -bh } else { -delta - bh }; + // The base reaches `base_height` below the face, joined or a separate body. + let y0 = -bh; let pts = [Vec2::new(-t, y0), Vec2::new(0.0, y0), Vec2::new(0.0, l - cl), Vec2::new(cd, l - cl), Vec2::new(0.0, l), Vec2::new(-t, l)]; let o = position.0 - y * (w / 2.0); let pl = Plane::new(o, x, z).ok_or_else(|| DocError::Invalid("snap fit frame".into()))?; @@ -2151,10 +2389,8 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F if closes { return Err(DocError::Invalid("the draft closes the rest before its top".into())); } - let delta = (h * 0.05).clamp(1e-3, 0.5); - let (x, y, z) = local_frame(direction.0, along.map(Vec3::from))?; - // Sized at the face: the tool starts a little inside, grown by the draft over that. - let e = delta * dr.tan(); + let (x, y, _) = local_frame(direction.0, along.map(Vec3::from))?; + // Sized at the face, where the tool starts. let shape = |grow: f64| match l { Some(l) => Loop2::polygon(&[ Vec2::new(-l / 2.0 - grow, -w / 2.0 - grow), @@ -2165,15 +2401,15 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F None => Loop2::circle(Vec2::ZERO, w / 2.0 + grow), }; let holes = match t { - Some(t) => vec![shape(-t - e).reversed()], + Some(t) => vec![shape(-t).reversed()], None => Vec::new(), }; - let region = Region2 { outer: shape(e), holes }; - let base = Plane::new(position.0 - z * delta, x, y).ok_or_else(|| DocError::Invalid("rest frame".into()))?; + let region = Region2 { outer: shape(0.0), holes }; + let base = Plane::new(position.0, x, y).ok_or_else(|| DocError::Invalid("rest frame".into()))?; let tool = if dr.abs() > 1e-12 { - vec![kernel::extrude_tapered(&base, ®ion, h + delta, 1.0, -dr)?] + vec![kernel::extrude_tapered(&base, ®ion, h, 1.0, -dr, kernel::DraftCorner::default())?] } else { - kernel::extrude(&base, &[region], 0.0, h + delta)? + kernel::extrude(&base, &[region], 0.0, h)? }; let tool = tool.into_iter().map(|b| crate::lineage::part_tool(b, "rest")).collect(); apply_traced(doc, st, f, tool, Operation::Join, std::slice::from_ref(&target)) @@ -2203,6 +2439,13 @@ fn sheet_picks(sh: &crate::sheet::SheetBody, f: &Feature, edges: &[Vec3], warnin out } +/// The values of sheet `i`'s rule for that sheet: `Thickness` in them is the sheet's own +/// thickness, which a converted body takes from its walls. +fn sheet_rule_values(doc: &Document, vals: &BTreeMap, st: &ModelState, i: usize) -> Result { + let sh = st.sheets.get(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; + doc.rule_values_at(vals, &doc.sheet_rule(Some(&sh.rule)), Some(sh.t)) +} + /// Tag the flanges a feature just added (`F.`). fn tag_flanges(sh: &mut crate::sheet::SheetBody, from: usize, feature: u64) { for (k, fl) in sh.flanges.iter_mut().enumerate().skip(from) { diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index e4e6a18d7..090dce4bb 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -4,7 +4,7 @@ use super::*; use crate::{RuledCorners, RuledMode, SheetSection}; -use solidcraft_geom::Seg2; +use solidcore_record::Seg2; pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState, warning: &mut Option) -> Result<()> { match &f.kind { @@ -20,6 +20,10 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, if !edges.is_empty() { let i = body_at(st, body, &crate::plain(edges))?; let b = st.bodies.get(i).ok_or_else(|| DocError::Invalid("body".into()))?; + // A design may carry an order the fill does not build yet: refused, not built lower. + for g in std::iter::once(continuity.all).chain(continuity.edges.iter().map(|e| e.g)) { + g.built_by(kernel::Construction::Patch)?; + } let spec = kernel::PatchSpec { continuity: continuity.all, edges: continuity.edges.iter().map(|e| (e.edge.0, e.g)).collect(), @@ -229,7 +233,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, return Err(DocError::Invalid("a match needs a chain of the target's edges".into())); } // Picked by a point on the face; without picks, the body's first face. - let picked: Vec = if faces.is_empty() { + let picked: Vec = if faces.is_empty() { let faces = mb.body.faces(mb.body.size() * 1e-2)?; vec![faces.first().ok_or_else(|| DocError::Invalid(format!("`{body}` has no face to match")))?.centroid] } else { @@ -304,7 +308,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; - let (o, d) = revolve_axis(&ss, axis, &super::axis_state(doc, st, f.component, axis), &|name| { + let (o, d) = revolve_axis(&ss, axis, &*super::axis_state(doc, st, f.component, axis)?, &|name| { construction_axis_in(Some(doc), st, name, f.component) })?; let a = val(vals, angle, Kind::Angle)?; @@ -371,17 +375,15 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, let pts: Vec = chains.iter().flatten().flat_map(|s| s.polyline(1e-2)).collect(); let start = ss.plane.to_world(pts.iter().fold(Vec2::default(), |a, p| a + *p) * (1.0 / pts.len().max(1) as f64)); let body = match path_points(ps, path, start)? { - Some(pts) => { + Some(path) => { + let pts = path.points(); let rails = crate::eval::rail_polylines(doc, st, rails, f.component, pts.first().copied().unwrap_or(start))?; let ctl = crate::eval::sweep_control(vals, orientation, twist, scale, rails, *rail_fit)?; kernel::sweep_sheet_points_with(&ss.plane, &chains, &pts, &ctl)? } None => { - let segs = path_segments(ps, path, start)?; - let path_start = match segs.first() { - Some(kernel::PathSeg::Line { a, .. } | kernel::PathSeg::Arc { a, .. }) => *a, - None => start, - }; + let segs = path_segments_at(ps, path, start, Some(&ss.plane))?; + let path_start = segs.first().map_or(start, kernel::PathSeg::start); let rails = crate::eval::rail_polylines(doc, st, rails, f.component, path_start)?; let ctl = crate::eval::sweep_control(vals, orientation, twist, scale, rails, *rail_fit)?; kernel::sweep_sheet_with(&ss.plane, &chains, &segs, &ctl)? @@ -432,7 +434,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, kernel::loft_sheet_with_rails(&secs, &rails, crate::eval::kernel_rail_fit(*rail_fit))? }; // Each wall named by the section curves it runs between, as a loft's sides are. - let loops: Vec = secs.iter().map(|(_, c)| solidcraft_geom::Loop2 { segs: c.clone() }).collect(); + let loops: Vec = secs.iter().map(|(_, c)| solidcore_record::Loop2 { segs: c.clone() }).collect(); let traced = crate::lineage::SectionRoles { sections: sketches.iter().zip(&loops).map(|(s, lp)| (s, vec![lp])).collect() }.tool(body); push_sheet(st, f, traced); Ok(()) @@ -459,7 +461,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st.bodies.push(ModelBody::traced_new(name, made, f.id)); Ok(()) } - FeatureKind::SurfaceRuled { body, edges, distance, mode, angle, direction, flip, corners, face } => { + FeatureKind::SurfaceRuled { body, edges, distance, mode, angle, direction, flip, corners, face, far } => { let d = val(vals, distance, Kind::Length)?; let mode = match mode { RuledMode::Normal => kernel::RuledMode::Normal, @@ -478,7 +480,8 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, }; let mb = st.body(body).cloned().ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; let r = kernel::Ruled { distance: d, mode, flip: *flip, corners, face: face.map(Vec3::from) }; - let made = Traced::step(kernel::ruled_surface(&mb.body, &crate::plain(edges), &r)?, &[&mb.traced()]); + let handles: Vec>> = far.iter().map(|h| h.as_ref().map(|pts| crate::plain(pts))).collect(); + let made = Traced::step(kernel::ruled_surface_with(&mb.body, &crate::plain(edges), &r, &handles)?, &[&mb.traced()]); let name = new_name(st, f, 0); st.bodies.push(ModelBody::traced_new(name, made, f.id)); Ok(()) @@ -569,7 +572,7 @@ fn loop_patch(ss: &SolvedSketch, curves: &[String]) -> Result { /// A network curve resolved in the feature's frame, owning what it is built from. enum NetSource { - Sketch(solidcraft_geom::Plane, Vec), + Sketch(solidcore_record::Plane, Vec), Points(Vec), Edges(kernel::Body, Vec), Point(Vec3), @@ -611,7 +614,7 @@ fn network_sources( // 3D sketch curves are followed through their points; planar ones exactly. let mapped = path_in_frame(doc, raw, f.component)?; match path_points(&mapped, &c.curves, Vec3::new(f64::NAN, f64::NAN, f64::NAN))? { - Some(pts) => NetSource::Points(pts), + Some(path) => NetSource::Points(path.points()), None => { let ss = sketch_in_feature_frame(doc, raw, f.component)?; let mut chains = curve_chains(&ss, &c.curves)?.into_iter(); @@ -659,7 +662,7 @@ fn boundary_frames( use solidcraft_kernel::{Boundary, Frame}; // The stations along each curve, evenly in its own arclength, so every side carries the same // number of frames and the patch's net is square. - let mut sides: Vec> = Vec::with_capacity(curves.len()); + let mut sides: Vec> = Vec::with_capacity(curves.len()); for id in curves { let ci = ss.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("sketch curve `{id}`")))?; let pieces = ss.sketch.exact_pieces(ci); @@ -687,7 +690,7 @@ fn boundary_frames( } // The middle of the loop, so every side leaves towards the inside of the patch. let count = sides.iter().map(Vec::len).sum::().max(1) as f64; - let centre = sides.iter().flatten().fold(solidcraft_geom::Vec3::ZERO, |a, p| a + *p) * (1.0 / count); + let centre = sides.iter().flatten().fold(solidcore_record::Vec3::ZERO, |a, p| a + *p) * (1.0 / count); let mut out = Vec::with_capacity(sides.len()); for (side, pts) in sides.iter().enumerate() { let mut frames = Vec::with_capacity(pts.len()); @@ -826,8 +829,8 @@ fn loft_blend( ) -> Result<()> { /// One section: a chain of sketch curves in its plane, or a body's edge chain. enum Piece { - Sketch(solidcraft_geom::Plane, Vec), - Body(String, Vec), + Sketch(solidcore_record::Plane, Vec), + Body(String, Vec), } let mut pieces = Vec::with_capacity(sections.len()); let mut centres = Vec::with_capacity(sections.len()); @@ -837,7 +840,7 @@ fn loft_blend( return Err(DocError::Invalid("a loft section picked from a body needs a chain of its edges".into())); } let n = sec.edges.len() as f64; - centres.push(sec.edges.iter().fold(solidcraft_geom::Vec3::ZERO, |a, p| a + **p) * (1.0 / n)); + centres.push(sec.edges.iter().fold(solidcore_record::Vec3::ZERO, |a, p| a + **p) * (1.0 / n)); pieces.push(Piece::Body(name.to_string(), crate::plain(&sec.edges))); continue; } @@ -855,7 +858,7 @@ fn loft_blend( return Err(DocError::Invalid("each loft section must be one chain: one profile without holes, or curves meeting end to end".into())); }; let pts: Vec = chain.iter().flat_map(|s| s.polyline(1e-2)).collect(); - let centre = pts.iter().fold(solidcraft_geom::Vec3::ZERO, |a, p| a + ss.plane.to_world(*p)) * (1.0 / pts.len().max(1) as f64); + let centre = pts.iter().fold(solidcore_record::Vec3::ZERO, |a, p| a + ss.plane.to_world(*p)) * (1.0 / pts.len().max(1) as f64); centres.push(centre); pieces.push(Piece::Sketch(ss.plane, chain)); } @@ -867,7 +870,7 @@ fn loft_blend( let (from, to) = if i < last { (i, i + 1) } else { (last, last.saturating_sub(1)) }; let leave = match (centres.get(from), centres.get(to)) { (Some(a), Some(b)) => *b - *a, - _ => solidcraft_geom::Vec3::ZERO, + _ => solidcore_record::Vec3::ZERO, }; match piece { Piece::Body(name, edges) => { @@ -886,9 +889,9 @@ fn loft_blend( /// The frames of one sketch chain, sampled by arclength at `stations` stations: a sketch has no /// face behind it, so the surface leaves along the run with no curvature to repeat there. fn chain_frames( - plane: &solidcraft_geom::Plane, - chain: &[solidcraft_geom::Seg2], - leave: solidcraft_geom::Vec3, + plane: &solidcore_record::Plane, + chain: &[solidcore_record::Seg2], + leave: solidcore_record::Vec3, stations: usize, ) -> Vec { let mut pts: Vec = Vec::new(); @@ -917,14 +920,19 @@ fn chain_frames( } let (Some(a), Some(b)) = (pts.get(k).copied(), pts.get(k + 1).copied()) else { if let Some(p) = pts.get(k).copied() { - out.push(kernel::Frame { p: plane.to_world(p), leave, bend: solidcraft_geom::Vec3::ZERO, bend_change: solidcraft_geom::Vec3::ZERO }); + out.push(kernel::Frame { + p: plane.to_world(p), + leave, + bend: solidcore_record::Vec3::ZERO, + bend_change: solidcore_record::Vec3::ZERO, + }); } continue; }; let span = (b - a).len(); let t = if span > 1e-12 { ((want - walked) / span).clamp(0.0, 1.0) } else { 0.0 }; let p = a * (1.0 - t) + b * t; - out.push(kernel::Frame { p: plane.to_world(p), leave, bend: solidcraft_geom::Vec3::ZERO, bend_change: solidcraft_geom::Vec3::ZERO }); + out.push(kernel::Frame { p: plane.to_world(p), leave, bend: solidcore_record::Vec3::ZERO, bend_change: solidcore_record::Vec3::ZERO }); } out } diff --git a/crates/doc/src/eval_thread.rs b/crates/doc/src/eval_thread.rs new file mode 100644 index 000000000..9490817af --- /dev/null +++ b/crates/doc/src/eval_thread.rs @@ -0,0 +1,1125 @@ +//! Threads: the cosmetic thread on a cylindrical face, and the modelled +//! thread's groove cut along a helix. + +use super::*; +use crate::thread_forms::{SteepFlank, ThreadForm, ThreadHand, ThreadTip}; + +/// A cosmetic thread: on which cylinder, its size, and the threaded part of the axis. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ThreadInfo { + pub feature: u64, + pub body: String, + pub designation: String, + pub major_diameter: f64, + /// Radius of the actual cylindrical face when the cosmetic thread is evaluated (0 in a + /// state saved without it: the cosmetic display then leaves the thread out). + #[serde(default)] + pub radius: f64, + pub pitch: f64, + pub internal: bool, + pub axis_point: Vec3, + pub axis: UnitVec3, + /// Threaded part along the axis from `axis_point`. + pub start: f64, + pub end: f64, + #[serde(default)] + pub form: ThreadForm, + #[serde(default)] + pub hand: ThreadHand, + #[serde(default = "crate::thread_forms::one_start")] + pub starts: u32, +} + +/// Nominal diameters and coarse pitches (mm) used for automatic ISO metric thread sizing. +/// Other diameter/pitch pairs can be supplied as explicit designations. +pub fn metric_thread_sizes() -> &'static [(f64, f64)] { + crate::thread_forms::ISO_COARSE +} + +/// "M8" or "M8x1" → (nominal diameter, pitch). +pub fn parse_metric_thread(s: &str) -> Option<(f64, f64)> { + ThreadForm::Metric.parse(s, 1).ok().filter(|z| (z.lead - z.pitch).abs() < 1e-12).map(|z| (z.major, z.pitch)) +} + +/// The automatic ISO metric designation for a cylindrical face, using the same fit check as +/// a thread feature without an explicit size. This query does not change the model. +pub fn suggested_thread(st: &ModelState, p: Vec3) -> Result { + suggested_thread_in(st, p, ThreadForm::Metric) +} + +/// The standard designation of `form` that fits the cylindrical face at `p` (a shaft its major +/// diameter, a hole its drill), with the same fit check as a thread feature without an explicit +/// size. This query does not change the model. +pub fn suggested_thread_in(st: &ModelState, p: Vec3, form: ThreadForm) -> Result { + thread_on(st, 0, p, &ThreadAsk { form: Some(form), ..Default::default() }).map(|t| t.info.designation) +} + +/// How far a thread runs along its face. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) enum Extent { + /// The whole face. + #[default] + Full, + /// This long, from the end it starts at. + Length(f64), + /// From the end it starts at to where this plane crosses the axis. + UpTo(Plane), + /// From the end it starts at to this point's place along the axis. + UpToPoint(Vec3), +} + +/// What a thread feature asks for: its size, how far it runs and from which end. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct ThreadAsk<'a> { + /// The form; `None`: the one `designation`'s prefix names, else metric. + pub form: Option, + pub designation: Option<&'a str>, + pub hand: ThreadHand, + /// Starts; 0 is taken as 1. + pub starts: u32, + pub steep: SteepFlank, + pub extent: Extent, + /// A point near the end of the face the thread starts at. + pub from: Option, + /// A modelled thread needs to know how each of its ends meets the face's ends. + pub modeled: bool, + /// The runout at the end away from where the thread starts, as (mm, pitches): its length + /// is mm + pitches x the pitch. The start never fades: it runs off its free end. + pub ease_out: (f64, f64), + /// A tapped hole's thread: `designation` is a catalogue size (ISO metric, or a catalogued + /// UNC/UNF, G, Rp, Rc or NPT size), and a size that is not metric fits the hole drilled for it. + pub tapped: bool, + /// A design saved before holes were sized by their nominal diameter: with no designation, a + /// hole is matched by its tap drill alone ([`ThreadForm::fit_with`]), so it keeps its size. + pub old_auto_size: bool, +} + +/// How one end of a thread's length meets its face. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum End { + /// At an end of the face past which there is no material in the groove's way: the groove + /// runs out into the air (or through a chamfer). + Free, + /// At (or within half a pitch of) an end of the face where material goes on past it, a + /// shoulder, a head, a blind hole's bottom: the groove stops short, clear of it. + Closed, + /// At an end of an external thread's face where a shoulder starts and stays beyond the face's + /// end: the groove runs on through the plane of that end and is trimmed there, so the root + /// reaches the shoulder at every angle, a nut bottoms out on it, and nothing past the plane + /// is cut. + Shoulder, + /// Inside the face: the groove stops square there. + Inside, +} + +/// A thread resolved on its face. +pub(super) struct ThreadOn { + pub info: ThreadInfo, + cyl: kernel::CylinderFace, + /// How the thread's start and end meet the face (modelled threads only). + ends: [End; 2], + steep: SteepFlank, + /// Runout lengths (mm) at the thread's start and end along the axis. + ease: [f64; 2], + /// The end of the axis (0: its start, 1: its end) the thread starts from. + from: usize, + /// A modelled internal thread in a hole wider than it needs: the radius the bore is narrowed + /// to (the thread's minor radius) before the groove is cut, with the hole's own radius. + narrow: Option, + /// A shoulder keeps the square stop because the kernel couldn't check whether it stays beyond + /// the face's end. + shoulder_unchecked: bool, +} + +/// The free-end test of a face's two ends (`side` 0 at its start, 1 at its end), each made +/// once. The groove's one-pitch overrun past a free end reaches 1.5 pitches past it. An end is +/// closed when, within that reach, material lies outside the face's cylinder (inside it, for a +/// hole) at the radii the groove cuts beyond the face: a shoulder, a plate, a head, a blind +/// hole's bottom, however thin, the material stepping out past the face. It is closed too when +/// material lies in the groove's band of radii beyond its first pitch: the face's cylinder going +/// on past a split. A chamfer, a neck, a countersink or a counterbore steps the other way and +/// leaves the end free: the groove runs out through it. +struct FaceEnds<'a> { + body: &'a Body, + cyl: &'a kernel::CylinderFace, + band: (f64, f64), + /// The radii the groove cuts beyond the face's own: from it out to the groove's outer edge + /// (external), or in to its inner edge (internal). + beyond: (f64, f64), + pitch: f64, + free: [Option; 2], +} + +impl FaceEnds<'_> { + fn free(&mut self, side: usize) -> Result { + if let Some(Some(f)) = self.free.get(side) { + return Ok(*f); + } + let p = self.pitch; + let past = + |from: f64, to: f64| if side == 0 { (self.cyl.start - to, self.cyl.start - from) } else { (self.cyl.end + from, self.cyl.end + to) }; + // Material that only touches the band's rims (a counterbore as wide as the thread, the + // face's own end) is not in the groove's way. + let e = p * 1e-3; + let stepped_out = kernel::material_in_ring(self.body, self.cyl, self.beyond.0 + e, self.beyond.1 - e, past(e, 1.5 * p))?; + let free = !stepped_out && !kernel::material_in_ring(self.body, self.cyl, self.band.0 + e, self.band.1 - e, past(p, 1.5 * p))?; + if let Some(slot) = self.free.get_mut(side) { + *slot = Some(free); + } + Ok(free) + } + + /// Does the shoulder at this closed end stay beyond the plane of the face's end? Not where it + /// rises back along the face (a slanted plate, a boss on a round body), which a groove + /// running to that plane would cut into: there is material outside the face just inside it. + /// The caller keeps the square stop, and says so, when the kernel can't make the check. + fn clear_of_end_plane(&self, side: usize) -> Result { + #[cfg(test)] + if tests::FAIL_CLEARANCE.get() { + return Err(kernel::KernelError::Failed("clearance refused for the test".into()).into()); + } + let (p, e) = (self.pitch, self.pitch * 1e-3); + let inside = if side == 0 { (self.cyl.start + e, self.cyl.start + p) } else { (self.cyl.end - p, self.cyl.end - e) }; + // All the radii the groove cuts beyond the face; only touching their rims is not in its + // way, as in `free`. + kernel::material_in_ring(self.body, self.cyl, self.beyond.0 + e, self.beyond.1 - e, inside).map(|hit| !hit).map_err(DocError::from) + } +} + +/// A thread on the cylindrical face at `p`: its size, and the part of the face it runs over. +pub(super) fn thread_on(st: &ModelState, feature: u64, p: Vec3, ask: &ThreadAsk) -> Result { + let (bi, cyl) = st + .bodies + .iter() + .enumerate() + .filter_map(|(i, b)| { + #[cfg(test)] + super::cost_tests::count(|c| c.cylinder_search += 1); + kernel::cylinder_face_at(&b.body, p).map(|c| (i, c)) + }) + .min_by(|a, b| { + let dist = |c: &kernel::CylinderFace| ((p - c.axis_point - c.axis * (p - c.axis_point).dot(c.axis)).len() - c.radius).abs(); + dist(&a.1).total_cmp(&dist(&b.1)) + }) + .ok_or_else(|| DocError::Invalid("no cylindrical face there to thread".into()))?; + let mb = st.bodies.get(bi).ok_or_else(|| DocError::Invalid("threaded body".into()))?; + let dia = cyl.radius * 2.0; + let form = match (ask.form, ask.designation.and_then(ThreadForm::of_designation)) { + (Some(f), _) | (None, Some(f)) => f, + (None, None) => ThreadForm::Metric, + }; + if let Some(why) = form.refused() { + return Err(DocError::Invalid(why.into())); + } + let starts = ask.starts.max(1); + if starts > 8 { + return Err(DocError::Invalid("a thread has 1 to 8 starts".into())); + } + // A tapped hole's size is the catalogue's. + let tapped = match (ask.tapped, ask.designation) { + (false, _) => None, + (true, None) => return Err(DocError::Invalid("a tapped hole needs a designation".into())), + (true, Some(name)) => Some(crate::parse_tapped_thread(name).ok_or_else(|| { + DocError::Invalid(format!("unknown tapped thread `{name}` (ISO metric or a catalogued UNC/UNF, G, Rp, Rc or NPT size)")) + })?), + }; + let size = match (&tapped, ask.designation) { + (Some(t), _) => crate::thread_forms::ThreadSize { form, major: t.major_diameter, pitch: t.pitch, lead: t.pitch }, + (None, Some(s)) => form.parse(s, starts).map_err(DocError::Invalid)?, + (None, None) => { + let (d, p) = form.fit_with(dia, cyl.internal, ask.old_auto_size).ok_or_else(|| { + DocError::Invalid(if form.sizes().is_empty() { + format!("{} threads have no size table: give the designation ({})", form.name(), form.format(50.8, 25.4 / 8.0, 25.4 / 8.0)) + } else { + format!("no {} thread fits a {dia:.2} mm cylinder", form.name()) + }) + })?; + crate::thread_forms::ThreadSize { form, major: d, pitch: p, lead: p * f64::from(starts) } + } + }; + let (major, pitch) = (size.major, size.pitch); + // A designation that gives the lead (M16xPh3P1.5, Tr40x14(P7)) gives the starts. + let named = (size.lead / pitch).round() as u32; + if ask.starts > 1 && named != starts { + return Err(DocError::Invalid(format!("`{}` has {named} start(s), not {starts}", ask.designation.unwrap_or_default()))); + } + let starts = named.max(1); + let mut designation = tapped.as_ref().map(|t| t.designation.clone()).unwrap_or_else(|| form.format(major, pitch, size.lead)); + if !form.pipe_sizes().is_empty() && tapped.is_none() { + if ask.hand == ThreadHand::Both { + return Err(DocError::Invalid("a pipe thread turns one way: right or left".into())); + } + // ISO 7-1's Rp is the parallel internal thread an R screws into; there is no external Rp. + if form == ThreadForm::Rp && !cyl.internal { + return Err(DocError::Invalid(format!( + "`{designation}` on this shaft: Rp is an internal thread (ISO 7-1); an external pipe thread is R (taper, ISO 7-1) or G (ISO 228-1)" + ))); + } + // ISO 7-1 names the internal taper thread Rc and the external one R. + if form == ThreadForm::Bspt { + if let Some(given) = ask.designation + && ThreadForm::pipe_internal(given) != cyl.internal + { + let want = if cyl.internal { "an internal taper thread is Rc" } else { "an external taper thread is R" }; + return Err(DocError::Invalid(format!("`{given}` on this {}: {want} (ISO 7-1)", if cyl.internal { "hole" } else { "shaft" }))); + } + if cyl.internal { + designation = designation.replacen("R ", "Rc ", 1); + } + } + } + let minor = 2.0 * form.groove(major, pitch, true).crest_r; + let fits = if let Some(t) = tapped.as_ref().filter(|t| t.family != crate::TappedThreadFamily::Metric) { + // The hole drilled for it, without borrowing an ISO minor-diameter rule. + cyl.internal && (t.tap_drill - dia).abs() < 0.15 * major + } else if cyl.internal { + (minor - dia).abs() < 0.2 * major || (form.drill(major, pitch) - dia).abs() < 0.15 * major || (major - dia).abs() < 0.15 * major + } else { + (major - dia).abs() < 0.15 * major + }; + if !fits { + let kind = if cyl.internal { "hole" } else { "shaft" }; + let try_instead = form + .fit(dia, cyl.internal) + .map(|(n, q)| form.format(n, q, q)) + .filter(|a| *a != designation) + .map(|a| format!("; this {kind} takes {a}")) + .unwrap_or_default(); + return Err(DocError::Invalid(format!("an {designation} thread does not fit a {dia:.2} mm {kind}{try_instead}"))); + } + // The radii the groove cuts: from the external thread's minor diameter (a nut's: its minor) + // to the major (a nut's root), and to the face itself where it lies outside that. + let (r_lo, r_hi) = if cyl.internal { + let g = form.groove(major, pitch, true); + (g.crest_r, g.root_r) + } else { + (form.groove(major, pitch, false).root_r, major / 2.0) + }; + let band = (cyl.radius.min(r_lo), cyl.radius.max(r_hi)); + // As far beyond the face as the groove's section reaches ([`thread_grooves`]). + let beyond = + if cyl.internal { ((cyl.radius.min(r_lo) - 0.1 * pitch).max(0.0), cyl.radius) } else { (cyl.radius, cyl.radius.max(r_hi) + 0.05 * pitch) }; + let mut ends = FaceEnds { body: &mb.body, cyl: &cyl, band, beyond, pitch, free: [None; 2] }; + let (lo, hi) = (cyl.start, cyl.end); + let along = |q: Vec3| (q - cyl.axis_point).dot(cyl.axis); + let span = |side: usize, to: f64| -> Result<(f64, f64)> { + let (a, b) = if side == 0 { (lo, to.min(hi)) } else { (to.max(lo), hi) }; + if !(b - a > pitch * 1e-3) { + return Err(DocError::Invalid("the thread's limit is not along the face from the end it starts at".into())); + } + Ok((a, b)) + }; + let from_side = |ends: &mut FaceEnds| start_side(ends, ask.from.map(along), along(p)); + // An external taper thread runs its standard length (ISO 7-1's useful thread, NPT's + // effective thread L2) unless told otherwise; an internal one the face, as a tapped hole. + let extent = match (ask.extent, form.is_taper() && !cyl.internal) { + (Extent::Full, true) => form.pipe_size(major).map_or(Extent::Full, |z| Extent::Length(z.length)), + (e, _) => e, + }; + let (a, b, side) = match extent { + Extent::Full => (lo, hi, ask.from.map(|q| usize::from((along(q) - lo).abs() > (hi - along(q)).abs())).unwrap_or(0)), + Extent::Length(l) => { + if !(l > 0.0) { + return Err(DocError::Invalid("thread length must be positive".into())); + } + if l >= hi - lo - pitch * 1e-3 { + // As long as the face (or longer): it runs the whole face from either end. + (lo, hi, ask.from.map(|q| usize::from((along(q) - lo).abs() > (hi - along(q)).abs())).unwrap_or(0)) + } else { + let side = from_side(&mut ends)?; + let (a, b) = span(side, if side == 0 { lo + l } else { hi - l })?; + (a, b, side) + } + } + Extent::UpTo(pl) => { + let n = pl.normal(); + let k = n.dot(*cyl.axis); + if k.abs() < 1e-9 { + return Err(DocError::Invalid("the plane the thread runs up to is parallel to its axis".into())); + } + let to = n.dot(pl.origin - cyl.axis_point) / k; + let side = from_side(&mut ends)?; + let (a, b) = span(side, to)?; + (a, b, side) + } + Extent::UpToPoint(q) => { + let side = from_side(&mut ends)?; + let (a, b) = span(side, along(q))?; + (a, b, side) + } + }; + // The runout at each end of the axis: only at the end away from where it starts. + let e_out = ask.ease_out.0 + ask.ease_out.1 * pitch; + let ease = if side == 0 { [0.0, e_out] } else { [e_out, 0.0] }; + if ease.iter().any(|e| !(*e >= 0.0 && e.is_finite())) { + return Err(DocError::Invalid("a runout length must be positive".into())); + } + // How each end of the thread meets the face: at a face end, or within half a pitch (and its + // runout) of one, where the groove would reach past it, that end's free-end test decides. + let near = |at: f64, side: usize| if side == 0 { at - lo } else { hi - at } < pitch / 2.0 + ease.get(side).copied().unwrap_or(0.0); + // A shoulder whose check the kernel couldn't make keeps the square stop, and the feature says so. + let mut unchecked = false; + let mut kind = |at: f64, side: usize| -> Result { + Ok(if !ask.modeled || !near(at, side) { + End::Inside + } else if !ends.free(side)? { + let at_end = (if side == 0 { at - lo } else { hi - at }) < pitch * 1e-3; + let square = ease.get(side).copied().unwrap_or(0.0) == 0.0; + let clear = at_end && square && !cyl.internal && !form.is_taper() && { + let check = ends.clear_of_end_plane(side); + unchecked |= matches!(check, Err(DocError::Kernel(_))); + match check { + Err(DocError::Kernel(_)) => false, + other => other?, + } + }; + if clear { End::Shoulder } else { End::Closed } + } else if (if side == 0 { at - lo } else { hi - at }) < pitch * 1e-3 { + End::Free + } else { + End::Inside + }) + }; + let ends = [kind(a, 0)?, kind(b, 1)?]; + if form.is_taper() && ask.modeled && ends.get(side) != Some(&End::Free) { + return Err(DocError::Invalid(format!( + "a taper pipe thread starts at a free end, the pipe's end or the {}: start it there (`from`, a point near that end)", + if cyl.internal { "hole's mouth" } else { "shaft's end" } + ))); + } + let info = ThreadInfo { + feature, + body: mb.name.clone(), + designation, + major_diameter: major, + radius: cyl.radius, + pitch, + internal: cyl.internal, + axis_point: cyl.axis_point, + axis: cyl.axis, + start: a, + end: b, + form, + hand: ask.hand, + starts, + }; + // A hole already as wide as the thread's major diameter (a 12 mm hole for M12) has no wall to + // cut a groove into: the bore is narrowed to the thread's minor diameter first. + let narrow = (ask.modeled && cyl.internal && tapped.is_none() && !form.is_taper()) + .then(|| form.groove(major, pitch, true)) + .filter(|g| !(g.root_r - cyl.radius >= g.basic_depth / 4.0)) + .map(|g| g.crest_r); + Ok(ThreadOn { info, cyl, ends, steep: ask.steep, ease, from: side, narrow, shoulder_unchecked: unchecked }) +} + +/// The end of the face (0: its start, 1: its end) a thread of limited length starts at: the end +/// nearest `from` (an axial position) when given, else the face's only free end, else the end the +/// pick `at` lies near (within a third of the face). A pick in the middle of a face whose ends are +/// alike is refused rather than guessed. +fn start_side(ends: &mut FaceEnds, from: Option, at: f64) -> Result { + let (lo, hi) = (ends.cyl.start, ends.cyl.end); + if let Some(s) = from { + return match (s - lo).abs().total_cmp(&(hi - s).abs()) { + std::cmp::Ordering::Less => Ok(0), + std::cmp::Ordering::Greater => Ok(1), + std::cmp::Ordering::Equal => Err(DocError::Invalid("`from` is as near one end of the face as the other".into())), + }; + } + match (ends.free(0)?, ends.free(1)?) { + (true, false) => return Ok(0), + (false, true) => return Ok(1), + _ => {} + } + let third = (hi - lo) / 3.0; + if at - lo < third { + Ok(0) + } else if hi - at < third { + Ok(1) + } else { + let alike = if ends.free(0)? { "both ends of the face are free" } else { "material goes on past both ends of the face" }; + Err(DocError::Invalid(format!("{alike}: say which end the thread starts from (`from`, a point near that end)"))) + } +} + +/// A thread's groove as a screw sweep: its `section` in `plane` (an axial plane through `base`), +/// carried `turns` turns about `axis` through `base`, rising `pitch` per turn (negative: a +/// left-handed groove). +struct GrooveShape { + plane: Plane, + section: Vec, + base: Vec3, + axis: Vec3, + pitch: f64, + turns: f64, + /// The section's move off the axis (turn, mm), piecewise linear: the runouts. Empty: none. + law: Vec<(f64, f64)>, +} + +/// The helical spaces between the teeth of a modelled thread of the form's profile: cut from +/// the shaft (external) or the hole wall (internal), running from `start` to `end` along the +/// axis, one groove per start and hand. `radius` is the face's own radius, `face` its extent +/// along the axis and `ends` how the thread's two ends meet it. A taper thread's `taper` is +/// (its major diameter where it starts, the end of the axis it starts from): its diameters grow +/// 1 in 16 from there into an external thread's material and shrink into an internal one's. +fn thread_grooves( + t: &ThreadInfo, + radius: f64, + face: (f64, f64), + ends: [End; 2], + steep: SteepFlank, + ease: [f64; 2], + taper: Option<(f64, usize)>, +) -> Result> { + let (p, d, form) = (t.pitch, t.major_diameter, t.form); + let lead = p * f64::from(t.starts.max(1)); + let len = t.end - t.start; + if !(p > 1e-3 && len > 1e-6) { + return Err(DocError::Invalid("thread too short".into())); + } + if len / lead > 190.0 { + return Err(DocError::Invalid(format!( + "a modelled thread is limited to 190 turns ({:.0} mm at this lead); use a cosmetic one", + 190.0 * lead + ))); + } + // The major diameter at axial position z: fixed, or a taper's from where it starts. + let major_at = |z: f64| match taper { + Some((d0, from)) => { + let (z0, into) = if from == 0 { (t.start, 1.0) } else { (t.end, -1.0) }; + let grow = if t.internal { -1.0 } else { 1.0 }; + d0 + grow * into * (z - z0) / 16.0 + } + None => d, + }; + let d = taper.map_or(d, |(d0, _)| d0); + let profile = |d: f64| { + let mut g = form.groove(d, p, t.internal); + if steep == SteepFlank::Start { + std::mem::swap(&mut g.flank_lo, &mut g.flank_hi); + } + g + }; + let g = profile(d); + let alt = |dia: f64| form.fit(dia, t.internal).map(|(n, q)| form.format(n, q, q)).filter(|a| *a != t.designation); + // How deep the groove cuts into the material: from the hole wall out to the internal + // thread's root, or from the shaft's surface in to the external thread's root. Next to + // nothing (a hole as wide as the thread, #995) is refused: the cut would leave the face + // unthreaded. + let basic = g.basic_depth; + let depth = if t.internal { g.root_r - radius } else { radius - g.root_r }; + let drill = show_mm(form.drill(d, p)); + if !(depth >= basic / 4.0) { + let (m, dia) = (&t.designation, 2.0 * radius); + let cut = format!("it would cut {:.2} mm of the thread's {basic:.2} mm depth", depth.max(0.0)); + let shown = show_mm(dia); + return Err(DocError::Invalid(if t.internal { + let alt = alt(dia).map(|a| format!(", or thread this hole {a}")).unwrap_or_default(); + format!("this {shown} mm hole is too wide for a modelled {m} thread: {cut}; drill {drill} mm for {m}{alt}") + } else { + let alt = alt(dia).map(|a| format!(", or thread this shaft {a}")).unwrap_or_default(); + format!("this {shown} mm shaft is too thin for a modelled {m} thread: {cut}; make the shaft {} mm for {m}{alt}", show_mm(d)) + })); + } + // The section: from the root out past the surface (external), or from inside the hole wall + // out to the root (internal), so the cut leaves no skin, its flanks the groove's. + // A taper thread's crests are cut by its major cone (external) or minor cone (internal), + // as the die or tap cuts them ([`taper_envelope`]): its groove reaches past the crest by as + // much as narrows the tooth's crest flat by a quarter (NPT's flat is 0.038 P). The cone + // changes 1 in 32 along the axis (`major_at`) across the section's own width, so its edge + // there follows the cone at that margin rather than being cut square: square, its deeper + // corner stops short of the cone and leaves a sliver of each flank. + let cone = taper.map_or(0.0, |_| (major_at(t.start + 1.0) - major_at(t.start)) / 2.0); + let section_of = |g: &crate::thread_forms::GrooveProfile| -> (Vec, f64) { + let (tl, th) = (g.flank_lo.tan(), g.flank_hi.tan()); + if taper.is_none() { + let (r0, r1) = if t.internal { (radius.min(g.crest_r) - 0.1 * p, g.root_r) } else { (g.root_r, radius.max(d / 2.0) + 0.05 * p) }; + let ((lo0, hi0), (lo1, hi1)) = (g.extents(p, r0), g.extents(p, r1)); + let wide = g.width(p, if t.internal { r0 } else { r1 }); + return (vec![Vec2::new(r0, -lo0), Vec2::new(r1, -lo1), Vec2::new(r1, hi1), Vec2::new(r0, hi0)], wide); + } + // Depth from the root, out towards the crest: d(z) = dc + q·z along the edge, which + // meets the flanks z = −(h + d·tl) and z = h + d·th. + let o = if t.internal { -1.0 } else { 1.0 }; + let q = o * cone; + let h = g.width(p, g.root_r) / 2.0; + let dc = o * (g.crest_r - g.root_r) + 0.25 * g.crest_flat / (tl + th); + let (z_lo, z_hi) = (-(h + dc * tl) / (1.0 + q * tl), (h + dc * th) / (1.0 - q * th)); + let r = |z: f64| g.root_r + o * (dc + q * z); + let (root, edge) = ([Vec2::new(g.root_r, -h), Vec2::new(g.root_r, h)], [Vec2::new(r(z_lo), z_lo), Vec2::new(r(z_hi), z_hi)]); + // In the order the square section has: the inner radius's corners first. + let pts = if t.internal { vec![edge[0], root[0], root[1], edge[1]] } else { vec![root[0], edge[0], edge[1], root[1]] }; + (pts, z_hi - z_lo) + }; + let (mut section, wide) = section_of(&g); + let radii = |s: &[Vec2]| s.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), v| (a.min(v.x), b.max(v.x))); + let (r0, r1) = radii(§ion); + if wide >= p * 0.98 { + // The groove would be wider than a pitch: the face is far inside the thread (a hole + // narrower than its minor diameter, a shaft thicker than its major one, #2688). + let (m, dia) = (&t.designation, 2.0 * radius); + let shown = show_mm(dia); + return Err(DocError::Invalid(if t.internal { + let alt = alt(dia).map(|a| format!(", or thread this hole {a}")).unwrap_or_default(); + format!("this {shown} mm hole is too narrow for a modelled {m} thread (its teeth would fill the hole); drill {drill} mm for {m}{alt}") + } else { + let alt = alt(dia).map(|a| format!(", or thread this shaft {a}")).unwrap_or_default(); + format!("this {shown} mm shaft is too thick for a modelled {m} thread; make the shaft {} mm for {m}{alt}", show_mm(d)) + })); + } + if !(r0.is_finite() && r1.is_finite() && r0 > 0.0) { + return Err(DocError::Invalid("thread dimensions are out of range".into())); + } + // Past a free end of the face the groove runs out into the air, a pitch beyond it. Before + // a closed one it stops with its section clear of the face's end (its centre as far inside + // as the section reaches that way), so it never cuts into the shoulder there; inside the + // face it stops square at the threaded length's end. At a shoulder it can be trimmed against + // ([`End::Shoulder`]) its whole section runs past the plane of the face's end, so every angle + // of the last turn is cut down to that plane ([`trim_at_shoulders`] takes off the rest). + // + // A runout `e` at an end (ISO 3508) fades the groove out over `e`: its section moves out of + // the material (an external thread's away from the axis, past the surface; an internal + // one's towards it, into the hole) as it turns. It lies past the full-form length, up to the + // shoulder's clearance; at a free end, inside the face, the groove reaching nothing there. + // How far the section reaches each way along the axis. + let (w_lo, w_hi) = section.iter().fold((0.0_f64, 0.0_f64), |(a, b), v| (a.max(-v.y), b.max(v.y))); + let s0 = match (ends[0], ease[0] > 0.0) { + (End::Free, false) => t.start - p, + (End::Free, true) => t.start, + (End::Closed, _) => (t.start - ease[0]).max(face.0 + w_lo), + (End::Shoulder, _) => face.0 - w_hi - 0.1 * p, + (End::Inside, _) => t.start - ease[0], + }; + let s1 = match (ends[1], ease[1] > 0.0) { + (End::Free, false) => t.end + p, + (End::Free, true) => t.end, + (End::Closed, _) => (t.end + ease[1]).min(face.1 - w_hi), + (End::Shoulder, _) => face.1 + w_lo + 0.1 * p, + (End::Inside, _) => t.end + ease[1], + }; + if !(s1 - s0 > p * 1e-3) { + return Err(DocError::Invalid(format!( + "the thread is too short to model between the shoulders: its groove needs {} mm clear of each", + show_mm(w_lo.max(w_hi)) + ))); + } + let turns = (s1 - s0) / lead; + // A taper thread's section is the profile where the sweep begins, moved off the axis as it + // turns by the taper's 1/32 of the axial travel. + let mut r0 = r0; + let taper_rate = match taper { + Some(_) => { + section = section_of(&profile(major_at(s0))).0; + r0 = radii(§ion).0; + (major_at(s0 + lead) - major_at(s0)) / 2.0 + } + None => 0.0, + }; + // How far the section moves to leave the material, a little past it. + let out = if t.internal { -(r1 - radius + 0.05 * p) } else { radius - r0 + 0.05 * p }; + if t.internal && r0 + out < 0.1 * p { + return Err(DocError::Invalid("the hole is too small for this thread's runout".into())); + } + let (r_in, r_out) = (ease[0] / lead, ease[1] / lead); + let mut law = Vec::new(); + if r_in > 0.0 { + law.extend([(0.0, out), (r_in, 0.0)]); + } + if r_out > 0.0 { + law.extend([(turns - r_out, 0.0), (turns, out)]); + } + if r_in > 0.0 && r_out > 0.0 && !(turns - r_out > r_in + 1e-9) || r_in.max(r_out) > turns { + return Err(DocError::Invalid(format!("the runout ({} mm) is longer than the thread", show_mm(ease[0].max(ease[1]))))); + } + if taper_rate != 0.0 { + law = with_taper(&law, turns, taper_rate); + if t.internal && law.iter().any(|(_, o)| r0 + o < 0.1 * p) { + return Err(DocError::Invalid("the hole is too small for this taper thread".into())); + } + } + let k = *t.axis; + let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); + let u = u.normalized().ok_or_else(|| DocError::Invalid("thread axis".into()))?; + let base = t.axis_point + k * s0; + let hands: &[f64] = match t.hand { + ThreadHand::Right => &[1.0], + ThreadHand::Left => &[-1.0], + ThreadHand::Both => &[1.0, -1.0], + }; + let n = t.starts.max(1); + let mut grooves = Vec::new(); + for &h in hands { + for j in 0..n { + // Start j is the first turned a j-th of a turn on: the same helix a j-th of the + // lead along. + let a = std::f64::consts::TAU * f64::from(j) / f64::from(n); + let x = u * a.cos() + k.cross(u) * a.sin(); + // A left-handed groove: turning the same way about the reversed axis while rising + // along it (the screw motion about −k rising −lead per turn). + let (axis, pitch) = if h > 0.0 { (k, lead) } else { (-k, -lead) }; + grooves.push(GrooveShape { + plane: Plane { origin: base, x, y: k }, + section: section.clone(), + base, + axis, + pitch, + turns, + law: law.clone(), + }); + } + } + Ok(grooves) +} + +/// A radial law (turn, offset) with a taper's `rate` mm per turn added: the law's own points and +/// both ends, each offset the law's (held past its first and last points) plus the taper's. +fn with_taper(law: &[(f64, f64)], turns: f64, rate: f64) -> Vec<(f64, f64)> { + let at = |t: f64| -> f64 { + match (law.first(), law.last()) { + (Some(a), _) if t <= a.0 => a.1, + (_, Some(b)) if t >= b.0 => b.1, + _ => law + .windows(2) + .find_map(|w| match w { + [a, b] if t >= a.0 && t <= b.0 && b.0 > a.0 => Some(a.1 + (b.1 - a.1) * (t - a.0) / (b.0 - a.0)), + _ => None, + }) + .unwrap_or(0.0), + } + }; + let mut ts: Vec = law.iter().map(|(t, _)| *t).chain([0.0, turns]).collect(); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-12); + ts.into_iter().map(|t| (t, at(t) + rate * t)).collect() +} + +/// A taper thread's crests, as its die or tap cuts them: the ring of material outside its major +/// cone (external) or inside its minor cone (internal) along the thread, from a pitch past the +/// end it starts at (`from`, a free end; `d0` its major diameter there) to its other end (a pitch +/// past that too when it is free). None when the cone misses the material. +fn taper_envelope(t: &ThreadInfo, radius: f64, ends: [End; 2], (d0, from): (f64, usize)) -> Result> { + let p = t.pitch; + let k = *t.axis; + let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); + let u = u.normalized().ok_or_else(|| DocError::Invalid("thread axis".into()))?; + let (at, into) = if from == 0 { (t.start, k) } else { (t.end, -k) }; + let far = 1 - from.min(1); + let len = t.end - t.start + if ends.get(far) == Some(&End::Free) { p } else { 0.0 }; + let e = p; + // In the plane: x radial, y along the axis into the material from the start. + let plane = Plane { origin: t.axis_point + k * at, x: u, y: into }; + let pts = if t.internal { + // The minor cone shrinks into the hole: what lies inside it, down to well inside the hole. + let minor0 = t.form.groove(d0, p, true).crest_r; + let rm = |y: f64| minor0 - y / 32.0; + if !(rm(-e) > radius) { + return Ok(None); + } + let r_in = 0.5 * radius.min(rm(len)); + if !(r_in > 0.0) { + return Err(DocError::Invalid("the hole is too small for this taper thread".into())); + } + vec![Vec2::new(r_in, -e), Vec2::new(rm(-e), -e), Vec2::new(rm(len), len), Vec2::new(r_in, len)] + } else { + // The major cone grows into the shaft: what lies outside it, out past the surface. + let rc = |y: f64| d0 / 2.0 + y / 32.0; + let r_out = radius + 0.1 * p; + if !(rc(-e) < r_out) { + return Ok(None); + } + let hit = (r_out - d0 / 2.0) * 32.0; + if hit < len { + vec![Vec2::new(rc(-e), -e), Vec2::new(r_out, hit), Vec2::new(r_out, -e)] + } else { + vec![Vec2::new(rc(-e), -e), Vec2::new(rc(len), len), Vec2::new(r_out, len), Vec2::new(r_out, -e)] + } + }; + let region = Region2 { outer: solidcore_record::Loop2::polygon(&pts), holes: Vec::new() }; + let mut ring = kernel::revolve(&plane, &[region], Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), std::f64::consts::TAU)?; + Ok(ring.pop()) +} + +/// The groove with what runs past a shoulder's plane taken off ([`End::Shoulder`]), so cutting it +/// leaves the shoulder whole. +fn trim_at_shoulders(mut tool: Body, axis: Vec3, ends: [End; 2], face: (f64, f64), k: UnitVec3) -> Result { + for (end, at, keep_positive) in [(ends[0], face.0, true), (ends[1], face.1, false)] { + if end != End::Shoulder { + continue; + } + let plane = Plane::from_normal(axis + k * at, *k).ok_or_else(|| DocError::Invalid("thread axis".into()))?; + // An error of the cut, like the kernel's own: `cut` then falls back to the square stop. + let missed = || kernel::KernelError::Failed("the thread's groove misses its face".into()); + let kept = kernel::half_space(&tool, &plane, keep_positive)?.0; + #[cfg(test)] + let kept = kept.filter(|_| !tests::EMPTY_TRIM.get()); + tool = kept.ok_or_else(missed)?; + } + Ok(tool) +} + +/// Evaluate a thread feature: a cosmetic thread is listed in the model's threads, a modelled +/// one cut into its body. +pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState, warning: &mut Option) -> Result<()> { + let FeatureKind::Thread { + face, + designation, + length, + modeled, + from, + up_to, + form, + hand, + starts, + ease_out, + tip, + chamfer_angle, + chamfer_depth, + steep_flank, + old_auto_size, + } = &f.kind + else { + return Err(DocError::Invalid("not a thread".into())); + }; + if *tip != ThreadTip::None && !*modeled { + return Err(DocError::Invalid("a chamfered tip is cut only on a modelled thread".into())); + } + let extent = match (length, up_to) { + (Some(e), _) => Extent::Length(val(vals, e, Kind::Length)?), + (None, Some(crate::ThreadLimit::Face(q))) => Extent::UpToPoint(q.0), + (None, Some(crate::ThreadLimit::Plane(pl))) => Extent::UpTo(doc.resolve_plane_in(vals, pl, 0, Some(st))?), + (None, None) => Extent::Full, + }; + // A form left at its default is the one the designation names (`Tr20x4`). + let form = (*form != ThreadForm::Metric).then_some(*form); + let ask = ThreadAsk { + form, + designation: designation.as_deref(), + hand: *hand, + starts: *starts, + steep: *steep_flank, + extent, + from: from.map(|q| q.0), + modeled: *modeled, + ease_out: (0.0, 0.0), + tapped: false, + old_auto_size: *old_auto_size, + }; + if ease_out.is_some() && !*modeled { + return Err(DocError::Invalid("a runout is cut only on a modelled thread".into())); + } + let ask = ThreadAsk { ease_out: runout(vals, ease_out)?, ..ask }; + let on = thread_on(st, f.id, face.0, &ask)?; + if !*modeled { + st.threads.push(on.info); + return Ok(()); + } + let angle = chamfer_angle.as_deref().map(|e| val(vals, e, Kind::Angle)).transpose()?; + let depth = chamfer_depth.as_deref().map(|e| val(vals, e, Kind::Length)).transpose()?; + if let Some(r) = on.narrow { + let note = format!( + "narrowed the {} mm hole to {} mm (the {} thread's minor diameter) so the thread has material to cut into", + show_mm(2.0 * on.cyl.radius), + show_mm(2.0 * r), + on.info.designation + ); + *warning = Some(match warning.take() { + Some(w) => format!("{w}; {note}"), + None => note, + }); + } + if let Some(note) = cut(st, on, (*tip, angle, depth))? { + *warning = Some(match warning.take() { + Some(w) => format!("{w}; {note}"), + None => note, + }); + } + Ok(()) +} + +/// A runout as (mm, pitches): ISO 3508's standard 2.5 P and short 1.25 P, or a length. +pub(super) fn runout(vals: &BTreeMap, e: &Option) -> Result<(f64, f64)> { + Ok(match e { + None => (0.0, 0.0), + Some(crate::ThreadRunout::Standard) => (0.0, 2.5), + Some(crate::ThreadRunout::Short) => (0.0, 1.25), + Some(crate::ThreadRunout::Length { length }) => (val(vals, length, Kind::Length)?, 0.0), + }) +} + +/// Cut a modelled thread resolved on its face into its body: the grooves (SMLib's exact screw +/// sweeps, a taper's crests by its envelope) by one B-rep boolean, then the chamfered tip +/// (`tip`, with its angle and depth when given). What the user should be told about the result, if +/// anything, is returned. +pub(super) fn cut(st: &mut ModelState, on: ThreadOn, (tip, angle, depth): (ThreadTip, Option, Option)) -> Result> { + let ThreadOn { info: t, cyl, ends, steep, ease, from: from_side, narrow, shoulder_unchecked } = on; + let i = st.bodies.iter().position(|b| b.name == t.body).ok_or_else(|| DocError::Invalid("threaded body".into()))?; + let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; + let (mut input, radius) = (mb.traced(), cyl.radius); + // A hole wider than the thread needs is filled in to the thread's minor radius over the + // threaded length first, so the groove has the wall to cut into. + let mut groove_radius = radius; + if let Some(r_min) = narrow { + let (lo, hi) = ((t.start - ease[0]).max(cyl.start), (t.end + ease[1]).min(cyl.end)); + let k = *t.axis; + let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); + let u = u.normalized().ok_or_else(|| DocError::Invalid("thread axis".into()))?; + let plane = Plane { origin: t.axis_point + k * lo, x: u, y: k }; + let r_out = radius + 0.1 * t.pitch; + let pts = [Vec2::new(r_min, 0.0), Vec2::new(r_out, 0.0), Vec2::new(r_out, hi - lo), Vec2::new(r_min, hi - lo)]; + let region = Region2 { outer: solidcore_record::Loop2::polygon(&pts), holes: Vec::new() }; + let sleeve = kernel::revolve(&plane, &[region], Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), std::f64::consts::TAU)? + .pop() + .ok_or_else(|| DocError::Invalid("the narrowed bore".into()))?; + let faces = sleeve.face_count(); + let filled = + kernel::boolean(&input.body, &sleeve, BoolOp::Union)?.ok_or_else(|| DocError::Invalid("narrowing the hole removed everything".into()))?; + let unnamed = crate::lineage::Lineage::unnamed_faces(faces); + let lineage = input.lineage.and_then(|l| crate::lineage::Lineage::step(&filled, &[&l, &unnamed])); + input = Traced { body: filled, lineage }; + groove_radius = r_min; + } + // The exact grooves: SMLib's screw sweeps, cut by one B-rep boolean. + // A taper thread starts at its free end at the major diameter its standard puts there: an + // internal one's gauge (reference) plane at its face, an external one's that far in. + let taper = match t.form.is_taper() { + true => { + let z = t.form.pipe_size(t.major_diameter).ok_or_else(|| DocError::Invalid(format!("no pipe size {}", t.designation)))?; + Some((if t.internal { t.major_diameter } else { t.major_diameter - z.gauge / 16.0 }, from_side)) + } + false => None, + }; + let cut_grooves = |ends: [End; 2]| -> Result<(Option, usize)> { + let mut grooves = Vec::new(); + for g in thread_grooves(&t, groove_radius, (cyl.start, cyl.end), ends, steep, ease, taper)? { + let section = Region2 { outer: solidcore_record::Loop2::polygon(&g.section), holes: Vec::new() }; + grooves.push(kernel::sweep_helix_radial(&g.plane, §ion, g.base, g.axis, g.pitch, g.turns, &g.law)?); + } + if let Some(taper) = taper + && let Some(envelope) = taper_envelope(&t, radius, ends, taper)? + { + grooves.push(envelope); + } + let tool = match grooves.as_slice() { + [one] => one.clone(), + many => kernel::union_all(&many.iter().collect::>())?, + }; + let tool = trim_at_shoulders(tool, t.axis_point, ends, (cyl.start, cyl.end), t.axis)?; + let cut = kernel::boolean(&input.body, &tool, BoolOp::Cut)?; + // Now rather than at the feature's end, where it could only fail the feature. + if ends.contains(&End::Shoulder) + && let Some(body) = &cut + { + kernel::check_kept(body)?; + } + Ok((cut, tool.face_count())) + }; + // A design that built with the square stop keeps building: where the kernel can't make the + // trimmed cut, the groove stops clear of the shoulder as it did, and the feature says so. + let mut made = cut_grooves(ends); + let mut square_stop = shoulder_unchecked; + if matches!(made, Err(DocError::Kernel(_))) && ends.contains(&End::Shoulder) { + made = cut_grooves(ends.map(|e| if e == End::Shoulder { End::Closed } else { e })); + square_stop = true; + } + let note = (square_stop && made.is_ok()).then(|| { + format!( + "the {} thread's groove could not be run down to the shoulder here, so it stops clear of it and its last turn is left uncut", + t.designation + ) + }); + let (nb, groove_faces) = made?; + let nb = nb.ok_or_else(|| DocError::Invalid("the thread removed everything".into()))?; + // The groove's faces have no role to name them by. + let groove = crate::lineage::Lineage::unnamed_faces(groove_faces); + let lineage = input.lineage.and_then(|l| crate::lineage::Lineage::step(&nb, &[&l, &groove])); + let mut nb = Traced { body: nb, lineage }; + if tip != ThreadTip::None { + for cone in tip_cones(&t, radius, ends, (tip, from_side), angle, depth, taper)? { + let faces = cone.face_count(); + let cut = kernel::boolean(&nb.body, &cone, BoolOp::Cut)?.ok_or_else(|| DocError::Invalid("the chamfer removed everything".into()))?; + let unnamed = crate::lineage::Lineage::unnamed_faces(faces); + let lineage = nb.lineage.and_then(|l| crate::lineage::Lineage::step(&cut, &[&l, &unnamed])); + nb = Traced { body: cut, lineage }; + } + } + if let Some(slot) = st.bodies.get_mut(i) { + *slot = ModelBody::traced_new(mb.name, nb, mb.feature); + } + Ok(note) +} + +/// The chamfered tip of an external thread (ISO 4753, chamfered end CH) at the free ends `tip` +/// names (`Start`: the end of the axis `from`, which must be free; `Both`: each free end): +/// the material outside a cone `angle` to the axis (default 45°) that reaches the diameter +/// d_f = d - 2 `depth` at the face's end, as a ring to cut after the groove, so the last teeth +/// taper into it. ISO 4753 bounds d_f by the external thread's minor diameter; the default is +/// that bound, d3 = d - 1.226869 P (ISO 724, the rounded root of the design profile). It lies +/// below the modelled basic root d1, so the cone crosses the root cylinder and leaves a whole +/// ring on the end; one ending on the root itself would pinch to nothing wherever the groove +/// reaches the end. ISO 4753 is for ISO metric threads: other forms give `depth`. A taper +/// thread's `taper` (its major diameter where it starts, the end it starts from) puts each end's +/// major diameter where the taper has it there, and `depth` is measured from that. +fn tip_cones( + t: &ThreadInfo, + radius: f64, + ends: [End; 2], + (tip, from): (ThreadTip, usize), + angle: Option, + depth: Option, + taper: Option<(f64, usize)>, +) -> Result> { + if t.internal { + return Err(DocError::Invalid("a chamfered tip is for an external thread (ISO 4753); countersink the hole's entry instead".into())); + } + let g = t.form.groove(t.major_diameter, t.pitch, false); + let a = angle.unwrap_or(std::f64::consts::FRAC_PI_4); + if !(a > 1f64.to_radians() && a < 89f64.to_radians()) { + return Err(DocError::Invalid("the chamfer's angle to the axis must be between 1° and 89°".into())); + } + // The major diameter at each end of the axis: a taper's grows 1 in 16 from where it starts. + let major = |side: usize| match taper { + Some((d0, start)) if side == start => d0, + Some((d0, _)) => d0 + (t.end - t.start) / 16.0, + None => t.major_diameter, + }; + let depth = match (depth, t.form) { + (Some(d), _) => d, + // ISO 724: d3 = d1 - H/6 = d - 2 (17/24) H. + (None, ThreadForm::Metric) => 17.0 / 24.0 * t.pitch * 3f64.sqrt() / 2.0, + (None, form) => { + return Err(DocError::Invalid(format!( + "ISO 4753's chamfered end is for ISO metric threads: give a {} thread its chamfer depth (its root is {} mm deep)", + form.name(), + show_mm(t.major_diameter / 2.0 - g.root_r) + ))); + } + }; + let smallest = major(0).min(major(1)) / 2.0; + if !(depth > 0.0 && smallest - depth > 1e-3) { + return Err(DocError::Invalid(format!("the chamfer's depth must be between 0 and {} mm", show_mm(smallest)))); + } + let k = *t.axis; + let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); + let u = u.normalized().ok_or_else(|| DocError::Invalid("thread axis".into()))?; + let slope = a.tan(); + // Past the end only the radii the groove's overrun already reaches (r >= d_f / 2), so + // nothing past a free end beyond the thread is touched. + let e = 0.5 * t.pitch; + let mut out = Vec::new(); + let free = |side: usize| ends.get(side) == Some(&End::Free); + if tip == ThreadTip::Start && !free(from) { + return Err(DocError::Invalid("the end the thread starts from is not a free end (material goes on past it, or the thread stops inside the face): chamfer it with `tip: both`, or start the thread from its free end".into())); + } + for (side, at, out_dir) in [(0usize, t.start, -k), (1, t.end, k)] { + if !free(side) || (tip == ThreadTip::Start && side != from) { + continue; + } + let r_f = major(side) / 2.0 - depth; + let r_out = radius.max(major(side) / 2.0) + 0.1 * t.pitch; + // In the plane: x radial, y outward along the axis from the end. + let plane = Plane { origin: t.axis_point + k * at, x: u, y: out_dir }; + let pts = [Vec2::new(r_f, 0.0), Vec2::new(r_f, e), Vec2::new(r_out, e), Vec2::new(r_out, -(r_out - r_f) / slope)]; + let region = Region2 { outer: solidcore_record::Loop2::polygon(&pts), holes: Vec::new() }; + let mut ring = kernel::revolve(&plane, &[region], Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), std::f64::consts::TAU)?; + out.push(ring.pop().ok_or_else(|| DocError::Invalid("chamfer".into()))?); + } + if out.is_empty() { + return Err(DocError::Invalid("a chamfered tip needs a free end of the thread (one with no material past it)".into())); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + thread_local! { + /// Make [`trim_at_shoulders`] find nothing of the groove left. + pub(super) static EMPTY_TRIM: Cell = const { Cell::new(false) }; + /// Make the rising-shoulder check fail as the kernel would. + pub(super) static FAIL_CLEARANCE: Cell = const { Cell::new(false) }; + } + + fn ask() -> ThreadAsk<'static> { + ThreadAsk { + form: None, + designation: Some("M10"), + hand: ThreadHand::Right, + starts: 1, + steep: SteepFlank::default(), + extent: Extent::Full, + from: None, + modeled: true, + ease_out: (0.0, 0.0), + tapped: false, + old_auto_size: false, + } + } + + /// How a thread's ends meet the face at (5, 0, z) of `body`. + fn ends_of(body: Body, z: f64) -> [End; 2] { + let mut st = ModelState::default(); + st.bodies.push(ModelBody::new("Part".into(), body, 1)); + thread_on(&st, 1, Vec3::new(5.0, 0.0, z), &ask()).unwrap().ends + } + + /// A shoulder that stays beyond the face's end takes the trim. One rising back along the face + /// (a slanted plate, a boss on a round body) keeps the square stop. + #[test] + fn only_a_shoulder_that_stays_beyond_the_faces_end_takes_the_trim() { + let z = Vec3::new(0.0, 0.0, 1.0); + let join = |a: &Body, b: &Body| kernel::boolean(a, b, BoolOp::Union).unwrap().unwrap(); + let boss = kernel::cylinder(Vec3::new(0.0, 0.0, 2.0), z, 5.0, 26.0).unwrap(); + let plate = kernel::box_solid(Vec3::new(-20.0, -20.0, -6.0), Vec3::new(20.0, 20.0, 2.0)).unwrap(); + let flat = ends_of(join(&plate, &boss), 20.0); + assert!(flat.contains(&End::Shoulder), "{flat:?}"); + let tilted = kernel::cylinder(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.2, 0.0, 1.0), 20.0, 6.0).unwrap(); + let slanted = ends_of(join(&tilted, &boss), 20.0); + assert!(slanted.contains(&End::Closed) && !slanted.contains(&End::Shoulder), "{slanted:?}"); + let round = kernel::cylinder(Vec3::new(0.0, -20.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 10.0, 40.0).unwrap(); + let on_round = ends_of(join(&round, &boss), 20.0); + assert!(on_round.contains(&End::Closed) && !on_round.contains(&End::Shoulder), "{on_round:?}"); + } + + /// Where the kernel can't check the shoulder, the thread still builds with the square stop, and + /// the feature says its last turn is left uncut. + #[test] + fn a_shoulder_the_kernel_cannot_check_keeps_the_square_stop_and_says_so() { + let plate = kernel::box_solid(Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, 20.0, 6.0)).unwrap(); + let boss = kernel::cylinder(Vec3::new(0.0, 0.0, 6.0), Vec3::new(0.0, 0.0, 1.0), 5.0, 16.0).unwrap(); + let body = kernel::boolean(&plate, &boss, BoolOp::Union).unwrap().unwrap(); + let mut st = ModelState::default(); + st.bodies.push(ModelBody::new("Part".into(), body, 1)); + FAIL_CLEARANCE.set(true); + let on = thread_on(&st, 1, Vec3::new(5.0, 0.0, 14.0), &ask()); + FAIL_CLEARANCE.set(false); + let on = on.unwrap(); + assert!(on.ends.contains(&End::Closed) && !on.ends.contains(&End::Shoulder), "{:?}", on.ends); + let note = cut(&mut st, on, (ThreadTip::None, None, None)).unwrap(); + assert!(note.is_some_and(|n| n.contains("M10") && n.contains("left uncut"))); + } + + /// Where the trim leaves nothing of the groove, a thread at a shoulder that built with the + /// square stop still builds with it, and the feature says its last turn is left uncut. + #[test] + fn a_shoulder_cut_the_kernel_refuses_falls_back_to_the_square_stop_and_says_so() { + let plate = kernel::box_solid(Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, 20.0, 6.0)).unwrap(); + let boss = kernel::cylinder(Vec3::new(0.0, 0.0, 6.0), Vec3::new(0.0, 0.0, 1.0), 5.0, 16.0).unwrap(); + let body = kernel::boolean(&plate, &boss, BoolOp::Union).unwrap().unwrap(); + let build = |fail: bool| { + let mut st = ModelState::default(); + st.bodies.push(ModelBody::new("Part".into(), body.clone(), 1)); + let on = thread_on(&st, 1, Vec3::new(5.0, 0.0, 14.0), &ask()).unwrap(); + EMPTY_TRIM.set(fail); + let note = cut(&mut st, on, (ThreadTip::None, None, None)); + EMPTY_TRIM.set(false); + (note.unwrap(), kernel::measure(&st.bodies[0].body).unwrap().volume) + }; + let (none, trimmed) = build(false); + assert_eq!(none, None); + let (note, square) = build(true); + assert!(note.is_some_and(|n| n.contains("M10") && n.contains("left uncut"))); + // The square stop leaves about half a pitch's worth of groove uncut: well over a mm³. + assert!(square > trimmed + 1.0, "{square} vs {trimmed}"); + } +} diff --git a/crates/doc/src/eval_whole_face_tests.rs b/crates/doc/src/eval_whole_face_tests.rs deleted file mode 100644 index 348a9480e..000000000 --- a/crates/doc/src/eval_whole_face_tests.rs +++ /dev/null @@ -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 = 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 = 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); -} diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs index a60768b06..8a95cda3a 100644 --- a/crates/doc/src/expr.rs +++ b/crates/doc/src/expr.rs @@ -304,6 +304,28 @@ pub fn value_in_unit(v: Value, unit: &str) -> f64 { } } +/// The number a reply reports for a value: millimetres for a length, degrees for an angle, +/// as-is for a unit-less or compound value. One meaning of `value` in every reply (#10747). +pub fn reported_value(v: Value) -> f64 { + match v.kind() { + Some(Kind::Angle) => v.v.to_degrees(), + _ => v.v, + } +} + +/// The number a person would read for `v`: the shortest decimal that reads back after +/// rounding off the last few bits (12 significant digits), so `30 deg` stored as +/// 29.999999999999996 reports 30 and `0.1 + 0.2` reports 0.3. Only what is *reported* +/// is rounded; stored values and evaluation keep full precision (#10747). +pub fn round_reported(v: f64) -> f64 { + if !v.is_finite() { + return v; + } + // `:.11e` keeps 12 significant digits; parsing back gives the f64 nearest that decimal, + // which serializes as the shortest form that reads back to it. + format!("{v:.11e}").parse().unwrap_or(v) +} + fn unit(name: &str) -> Option { UNITS.iter().find(|(n, _, _)| *n == name).map(|(_, k, s)| match k { Kind::Angle => Value::angle(*s), @@ -350,8 +372,9 @@ fn lex_spans(s: &str) -> Result, DocError> { let at = |i: usize| cs.get(i).map(|x| x.0).unwrap_or(s.len()); let mut i = 0; let mut out = Vec::new(); - // Parentheses open at this point: a comma outside them can only be a decimal comma. - let mut depth = 0usize; + // Parentheses open at this point, innermost last, true for a function call's: a comma directly + // in a call separates its arguments, and anywhere else can only be a decimal comma (#9408). + let mut parens: Vec = Vec::new(); // A single leading `=` marks the text as a formula (`=d3`, #4681) and is not part of it. if let Some(k) = cs.iter().position(|(_, c)| !c.is_whitespace()) && cs.get(k).is_some_and(|(_, c)| *c == '=') @@ -369,7 +392,7 @@ fn lex_spans(s: &str) -> Result, DocError> { while let Some(&(_, c)) = cs.get(i) { if c.is_whitespace() { i += 1; - } else if c.is_ascii_digit() || c == '.' || leading_decimal_comma(&cs, i, depth, out.last()) { + } else if c.is_ascii_digit() || c == '.' || leading_decimal_comma(&cs, i, in_call(&parens), out.last()) { let st = i; // A leading decimal comma (`,5` for 0,5, #2966) starts the number as `.5` would. let leading_comma = c == ','; @@ -380,11 +403,17 @@ fn lex_spans(s: &str) -> Result, DocError> { i += 1; } // A decimal comma (`2,5 mm`, as typed with a numeric keypad in many locales, #1347): - // a comma between digits, in a number with no point, outside any parentheses (inside - // them a comma separates a function's arguments: `max(1,2)`). + // a comma between digits, in a number with no point, not directly in a function call + // (there a comma separates arguments: `max(1,2)`). let digit = |k: usize| cs.get(k).is_some_and(|(_, c)| c.is_ascii_digit()); let has_point = cs.get(st..i).is_some_and(|ds| ds.iter().any(|(_, c)| *c == '.')); - if depth == 0 && !leading_comma && !has_point && digit(i.wrapping_sub(1)) && cs.get(i).is_some_and(|(_, c)| *c == ',') && digit(i + 1) { + if !in_call(&parens) + && !leading_comma + && !has_point + && digit(i.wrapping_sub(1)) + && cs.get(i).is_some_and(|(_, c)| *c == ',') + && digit(i + 1) + { i += 1; while digit(i) { i += 1; @@ -406,7 +435,7 @@ fn lex_spans(s: &str) -> Result, DocError> { // A mixed number, as imperial sizes are written (`2 1/8"` is 2.125 in, #1802): a whole // number, then a proper fraction of whole numbers, is one value, not `2 × 1/8`. if t.chars().all(|c| c.is_ascii_digit()) - && let Some((fraction, end)) = mixed_fraction(&cs, i, depth) + && let Some((fraction, end)) = mixed_fraction(&cs, i, in_call(&parens)) { out.push((Tok::Num(v + fraction), at(st), at(end))); i = end; @@ -444,8 +473,10 @@ fn lex_spans(s: &str) -> Result, DocError> { i += 1; } else if "+-*/^(),%".contains(c) { match c { - '(' => depth += 1, - ')' => depth = depth.saturating_sub(1), + '(' => parens.push(matches!(out.last(), Some((Tok::Id(_), _, _)))), + ')' => { + parens.pop(); + } _ => {} } out.push((Tok::Op(c), at(i), at(i + 1))); @@ -457,27 +488,32 @@ fn lex_spans(s: &str) -> Result, DocError> { Ok(out) } +/// Whether the innermost open parenthesis is a function call's. +fn in_call(parens: &[bool]) -> bool { + parens.last() == Some(&true) +} + /// Whether the comma at `i` starts a number, as a leading decimal comma (`,5` for 0,5, #2966). -/// It must be outside parentheses (inside them a comma separates arguments, as for any decimal -/// comma), be followed by a digit, and stand where an operand is expected: at the start or right -/// after `+ - * / ^`. A comma after a number, name, `)` or `%` keeps its meaning (`2 ,5` and -/// `1,5,3` stay errors). -fn leading_decimal_comma(cs: &[(usize, char)], i: usize, depth: usize, prev: Option<&(Tok, usize, usize)>) -> bool { - depth == 0 +/// It must not be directly in a function call (`in_call`: there a comma separates arguments, as +/// for any decimal comma), be followed by a digit, and stand where an operand is expected: at the +/// start or right after `( + - * / ^`. A comma after a number, name, `)` or `%` keeps its meaning +/// (`2 ,5` and `1,5,3` stay errors). +fn leading_decimal_comma(cs: &[(usize, char)], i: usize, in_call: bool, prev: Option<&(Tok, usize, usize)>) -> bool { + !in_call && cs.get(i).is_some_and(|(_, c)| *c == ',') && cs.get(i + 1).is_some_and(|(_, c)| c.is_ascii_digit()) && match prev { None => true, - Some((Tok::Op(op), _, _)) => "+-*/^".contains(*op), + Some((Tok::Op(op), _, _)) => "(+-*/^".contains(*op), Some(_) => false, } } /// The proper fraction of a mixed number whose whole part ends at `i`: spaces, digits, `/`, /// digits, with nothing after them that would continue the number (`2 1/8.5`, `2 1/8e3`, a -/// decimal comma outside parentheses: `2 1/8,5`). Its value and where it ends. `depth`: the -/// parentheses open there (inside them a comma separates arguments: `max(2 1/8,1)`). -fn mixed_fraction(cs: &[(usize, char)], mut i: usize, depth: usize) -> Option<(f64, usize)> { +/// decimal comma: `2 1/8,5`). Its value and where it ends. `in_call`: directly in a function call +/// there (a comma separates arguments: `max(2 1/8,1)`). +fn mixed_fraction(cs: &[(usize, char)], mut i: usize, in_call: bool) -> Option<(f64, usize)> { let digits = |from: usize| cs.get(from..).map_or(0, |rest| rest.iter().take_while(|(_, c)| c.is_ascii_digit()).count()); let space = i; while cs.get(i).is_some_and(|(_, c)| *c == ' ' || *c == '\t') { @@ -491,7 +527,7 @@ fn mixed_fraction(cs: &[(usize, char)], mut i: usize, depth: usize) -> Option<(f let end = i + numerator + 1 + denominator; let next = |k: usize| cs.get(end + k).map(|(_, c)| *c); let continues = matches!(next(0), Some('.')) - || (depth == 0 && matches!(next(0), Some(',')) && next(1).is_some_and(|c| c.is_ascii_digit())) + || (!in_call && matches!(next(0), Some(',')) && next(1).is_some_and(|c| c.is_ascii_digit())) || (matches!(next(0), Some('e' | 'E')) && next(1).is_some_and(|c| c.is_ascii_digit() || c == '-' || c == '+')); if denominator == 0 || continues { return None; @@ -936,7 +972,11 @@ fn call(f: &str, args: &[Value], d: Defaults) -> Result { let a = one()?; unit_fn(a.v.abs(), a) } - "sign" => Value::num(one()?.v.signum()), + "sign" => { + let x = one()?.v; + // `f64::signum` gives 1 for +0 and -1 for -0; the sign of zero is 0. + Value::num(if x == 0.0 { 0.0 } else { x.signum() }) + } "floor" | "ceil" | "round" | "trunc" => { let a = one()?; // Round in the value's own default unit (round(2.4 in) = 2 in for an inch parameter). @@ -1240,7 +1280,13 @@ mod tests { // Inside parentheses a comma still separates a function's arguments. assert_eq!(ev("max(1,2)", Kind::Unitless).unwrap(), 2.0); assert_eq!(ev("max(1 mm, 3, 2)", Kind::Length).unwrap(), 3.0); - assert_eq!(ev("(2,5)", Kind::Unitless).ok(), None, "a comma inside parentheses is not a decimal comma"); + // Plain parentheses have no arguments to separate (#9408), also inside a call. + assert_eq!(ev("(2,5)", Kind::Unitless).unwrap(), 2.5); + assert_eq!(ev("-(width-0,5)/2", Kind::Length).unwrap(), -19.75); + assert_eq!(ev("(,5)", Kind::Unitless).unwrap(), 0.5); + assert_eq!(ev("(2 1/8,5)", Kind::Unitless).unwrap(), 2.0 / 8.5); + assert_eq!(ev("max((1,5), 1)", Kind::Unitless).unwrap(), 1.5); + assert_eq!(ev("(max(1,2))", Kind::Unitless).unwrap(), 2.0); // Not between two digits, or a second comma: still an error. for bad in ["2,", "2 ,5", "2, 5", "1,5,3", "1.5,3", ",5,3", ",5.3", "width ,5", "(1) ,5"] { assert!(ev(bad, Kind::Unitless).is_err(), "{bad}"); @@ -1388,6 +1434,16 @@ mod tests { } } + /// `sign(0)` is 0, not 1 (Rust's `signum` takes the sign bit, so it calls zero positive). + #[test] + fn sign_of_zero_is_zero() { + for (e, want) in + [("sign(0)", 0.0), ("sign(-0)", 0.0), ("sign(0 mm)", 0.0), ("sign(5)", 1.0), ("sign(-2 mm)", -1.0), ("sign(width - 40)", 0.0)] + { + assert_eq!(ev(e, Kind::Unitless).unwrap(), want, "{e}"); + } + } + /// A count from a length (`(L - 20) / 210`, the 210 read as unit-less) names the fix (#5901). #[test] fn a_length_where_a_count_is_expected_says_to_divide_by_a_length() { @@ -1617,4 +1673,36 @@ mod tests { defs[2].expr = "bad +".into(); assert!(eval_params(&defs, 1.0).1.contains_key("c")); } + + /// #10747: reported numbers are the shortest decimals that read back after rounding off + /// the last few bits (12 significant digits); stored values keep full precision. + #[test] + fn round_reported_reads_as_a_person_would() { + for (noisy, read) in [ + (30f64.to_radians().to_degrees(), 30.0), + (0.1 + 0.2, 0.3), + (3.0 * 25.4, 76.2), + (1.2 * 25.4, 30.48), + (29.999999999999996, 30.0), + (0.30000000000000004, 0.3), + (-0.1 - 0.2, -0.3), + ] { + assert_eq!(round_reported(noisy), read, "{noisy}"); + } + // A number with real digits of its own keeps them up to 12 significant digits. + assert_eq!(round_reported(1.234567890123), 1.23456789012); + assert_eq!(round_reported(1.0000000000001), 1.0); + // Zero and non-finite values pass through. + assert_eq!(round_reported(0.0), 0.0); + assert!(round_reported(f64::INFINITY).is_infinite()); + assert!(round_reported(f64::NAN).is_nan()); + } + + /// #10747: `value` means millimetres and degrees in every reply. + #[test] + fn reported_value_is_mm_and_degrees() { + assert_eq!(reported_value(Value::length(50.8)), 50.8); + assert_eq!(round_reported(reported_value(Value::angle(30f64.to_radians()))), 30.0); + assert_eq!(reported_value(Value::num(4.0)), 4.0); + } } diff --git a/crates/doc/src/face_anchor.rs b/crates/doc/src/face_anchor.rs index 2820d3f4f..f9cbc3f39 100644 --- a/crates/doc/src/face_anchor.rs +++ b/crates/doc/src/face_anchor.rs @@ -4,7 +4,8 @@ use crate::config::ConfigFaceTarget; use crate::{DocError, Document, EmbossFace, FeatureKind, Model, ModelBody, ModelState, PlaneRef, Result}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use solidcraft_geom::Plane; +use solidcore_record::Plane; +use solidcraft_geom::prelude::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -13,12 +14,30 @@ pub struct FaceAnchor { pub component: u64, pub path: Vec, pub author_path: Vec, + /// Source component to author component at capture, for an independently placed part. + /// Body offsets and source geometry remain live; later assembly moves do not reshape it. + /// Older attachments without this field retain their live placement relationship. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub placement: Option, /// Origin and x direction in the exact canonical face plane's coordinates. pub coordinates: [f64; 2], pub x_axis: [f64; 2], } impl FaceAnchor { + /// Re-express a captured context when definitions (not their occurrences) change frames. + pub fn reframe_placement(&mut self, author: &crate::Mat, source: &crate::Mat) -> Result<()> { + if let Some(placement) = self.placement { + let inverse = crate::mat_inverse(source).ok_or_else(|| DocError::Invalid("attached source frame is invalid".into()))?; + let placement = crate::mat_mul(&crate::mat_mul(author, &placement), &inverse); + if !crate::valid_transfer_matrix(&placement) { + return Err(DocError::Invalid("invalid captured face placement".into())); + } + self.placement = Some(placement); + } + Ok(()) + } + pub fn remap_target( &mut self, features: &std::collections::BTreeMap, @@ -47,6 +66,7 @@ impl FaceAnchor { || self.path.iter().chain(&self.author_path).any(|id| *id == 0) || (self.component == 0 && !self.path.is_empty()) || (self.component != 0 && self.path.is_empty()) + || self.placement.as_ref().is_some_and(|m| !crate::valid_transfer_matrix(m)) || self.coordinates.iter().any(|value| !value.is_finite() || value.abs() > 1e9) || self.x_axis.iter().any(|value| !value.is_finite()) || (self.x_axis[0].hypot(self.x_axis[1]) - 1.).abs() > 1e-6 @@ -70,13 +90,11 @@ impl FaceAnchor { } let inverse = crate::mat_inverse(&self.author_frame(doc, author)?) .ok_or_else(|| DocError::Invalid("attached sketch author frame is invalid".into()))?; - let source = EmbossFace { - body: self.target.body.clone().into(), - at: crate::FacePick(self.target.point), - path: self.path.clone(), - author_path: self.author_path.clone(), - }; - Ok(crate::mat_mul(&inverse, &source.body_frame(doc, body)?)) + // Resolve both paths even with a captured placement: a missing or reparented source + // must still fail explicitly rather than silently reusing an unrelated definition. + let source = EmbossFace::component_frame(doc, self.component, &self.path)?; + let relative = self.placement.unwrap_or_else(|| crate::mat_mul(&inverse, &source)); + Ok(doc.model_body_offset(body).map_or(relative, |offset| crate::mat_mul(&relative, offset))) } } @@ -171,7 +189,43 @@ impl Document { author: u64, author_path: &[u64], ) -> Result { - // A construction certificate that names this face alone, else its exact history name. + let target = self.flat_face_target(body, index)?; + let source = self + .anchor_face_plane(body, index, target.certificate.as_ref()) + .ok_or_else(|| DocError::Invalid("this face has no exact planar source; choose a fixed plane instead".into()))?; + let mut anchor = FaceAnchor { + target, + component: self.model_body_component(body), + path: target_path.to_vec(), + author_path: author_path.to_vec(), + placement: None, + coordinates: [0., 0.], + x_axis: [1., 0.], + }; + let canonical = map_plane(&anchor.source_to_author(self, author, body)?, &source)?; + if picked.normal().dot(canonical.normal()) < 1. - 1e-7 || (picked.origin - canonical.origin).dot(canonical.normal()).abs() > 1e-7 { + return Err(DocError::Invalid("picked plane does not match its exact source face".into())); + } + let delta = picked.origin - canonical.origin; + anchor.coordinates = [delta.dot(canonical.x), delta.dot(canonical.y)]; + anchor.x_axis = [picked.x.dot(canonical.x), picked.x.dot(canonical.y)]; + // A part built against another component uses that assembly context to define its + // own shape. Moving either occurrence later must not move the sketch inside the part. + // Root sketches and references inside the same component keep their live placements. + if author != 0 && author != anchor.component { + let inverse = crate::mat_inverse(&anchor.author_frame(self, author)?) + .ok_or_else(|| DocError::Invalid("attached sketch author frame is invalid".into()))?; + let source = EmbossFace::component_frame(self, anchor.component, &anchor.path)?; + anchor.placement = Some(crate::mat_mul(&inverse, &source)); + } + anchor.validate()?; + Ok(anchor) + } + + /// A target for flat face `index` of `body` that a rebuild finds again: a construction + /// certificate that names this face alone, else its exact history name. What a sketch on a + /// face and a print face hold. + pub(crate) fn flat_face_target(&self, body: &ModelBody, index: usize) -> Result { let certified = body .body .face_plane(index) @@ -184,39 +238,24 @@ impl Document { let indices = self.configuration_face_indices(body, &target)?; // A copy a pattern or mirror made on the same body carries its seed's certificate, // which finds the seed's face: the copy is attached by its own history name below. + // A face that is no copy, on the plane of the pieces the certificate finds, is + // another piece of that face (a piece a later join left bordering another body, + // and named after it): the certificate stands for it too (#9465). if !indices.contains(&index) { - return Err(DocError::Invalid("this face has no supported construction certificate; choose a fixed plane instead".into())); + let names = crate::naming::names(body); + let copy = names.faces.get(index).is_none_or(|name| crate::persistent_name::is_copy(name)); + let all: Vec = indices.iter().copied().chain([index]).collect(); + if copy || self.coplanar_pieces(body, &all, |_| true).is_err() { + return Err(DocError::Invalid("this face has no supported construction certificate; choose a fixed plane instead".into())); + } } self.coplanar_pieces(body, &indices, |_| true)?; Ok(target) }); - let target = match certified { - Ok(target) => target, - Err(error) => match body.body.planar_face(index).and_then(|plane| self.lineage_face_target(body, index, plane.origin)) { - Some(target) => target, - None => return Err(error), - }, - }; - let source = self - .anchor_face_plane(body, index, target.certificate.as_ref()) - .ok_or_else(|| DocError::Invalid("this face has no exact planar source; choose a fixed plane instead".into()))?; - let mut anchor = FaceAnchor { - target, - component: self.model_body_component(body), - path: target_path.to_vec(), - author_path: author_path.to_vec(), - coordinates: [0., 0.], - x_axis: [1., 0.], - }; - let canonical = map_plane(&anchor.source_to_author(self, author, body)?, &source)?; - if picked.normal().dot(canonical.normal()) < 1. - 1e-7 || (picked.origin - canonical.origin).dot(canonical.normal()).abs() > 1e-7 { - return Err(DocError::Invalid("picked plane does not match its exact source face".into())); + match certified { + Ok(target) => Ok(target), + Err(error) => body.body.planar_face(index).and_then(|plane| self.lineage_face_target(body, index, plane.origin)).ok_or(error), } - let delta = picked.origin - canonical.origin; - anchor.coordinates = [delta.dot(canonical.x), delta.dot(canonical.y)]; - anchor.x_axis = [picked.x.dot(canonical.x), picked.x.dot(canonical.y)]; - anchor.validate()?; - Ok(anchor) } /// The faces an attachment stands for, and a note when they were found by fallback. @@ -229,12 +268,7 @@ impl Document { /// is not guessed). It never does while the exact cap is still on another body (profiles /// reordered: the bodies swapped names). The note names what changed. Every other identity /// stays exact. - pub(crate) fn anchored_face_indices( - &self, - state: &ModelState, - body: &ModelBody, - target: &ConfigFaceTarget, - ) -> Result<(Vec, Option)> { + pub fn anchored_face_indices(&self, state: &ModelState, body: &ModelBody, target: &ConfigFaceTarget) -> Result<(Vec, Option)> { let error = match self.configuration_face_indices(body, target) { Ok(indices) => return Ok((indices, None)), Err(error) => error, @@ -377,7 +411,8 @@ impl Document { pub fn validate_face_anchor_json(value: &Value) -> Result<()> { let fields = value.as_object().ok_or_else(|| DocError::Invalid("face anchor must be an object".into()))?; - if fields.len() != 6 || fields.keys().any(|key| !["target", "component", "path", "author_path", "coordinates", "x_axis"].contains(&key.as_str())) + if !(6..=7).contains(&fields.len()) + || fields.keys().any(|key| !["target", "component", "path", "author_path", "placement", "coordinates", "x_axis"].contains(&key.as_str())) { return Err(DocError::Invalid("unknown or missing face anchor fields".into())); } @@ -411,6 +446,15 @@ pub fn validate_face_anchor_json(value: &Value) -> Result<()> { return Err(DocError::Invalid("face anchor basis must be normalized".into())); } } + if let Some(placement) = fields.get("placement").filter(|v| !v.is_null()) { + if placement.as_array().is_none_or(|rows| rows.len() != 4 || rows.iter().any(|row| row.as_array().is_none_or(|row| row.len() != 4))) { + return Err(DocError::Invalid("face anchor placement requires a 4x4 matrix".into())); + } + let matrix: crate::Mat = serde_json::from_value(placement.clone()).map_err(|_| DocError::Invalid("invalid face anchor placement".into()))?; + if !crate::valid_transfer_matrix(&matrix) { + return Err(DocError::Invalid("face anchor placement must be a finite rigid transform".into())); + } + } Ok(()) } @@ -455,7 +499,7 @@ pub fn validate_face_anchors_json(value: &Value) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; fn fixture() -> (Document, ModelBody, usize, Plane) { let mut doc = Document::default(); let kind: FeatureKind = @@ -519,6 +563,44 @@ mod tests { .unwrap(); assert!(doc.resolve_face_anchor(&anchor, 0, &state).is_err(), "reused name cannot replace the producer"); } + #[test] + fn captured_component_placement_is_rigid_and_legacy_anchors_stay_live() { + let (mut doc, body, index, picked) = fixture(); + let author = doc.add_component(Some("Part"), 0).unwrap(); + let path = doc.first_path(author); + let anchor = doc.capture_face_anchor(&body, index, &picked, &[], author, &path).unwrap(); + assert_eq!(anchor.placement, Some(crate::IDENTITY)); + let raw = serde_json::to_value(&anchor).unwrap(); + assert!(validate_face_anchor_json(&raw).is_ok()); + let restored: FaceAnchor = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(restored, anchor); + for placement in [ + serde_json::json!([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]), + serde_json::json!([[2, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]), + serde_json::json!([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]), + serde_json::json!([[1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]), + serde_json::json!([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1e10, 0, 0, 1]]), + ] { + let mut invalid = raw.clone(); + invalid["placement"] = placement; + assert!(validate_face_anchor_json(&invalid).is_err(), "{invalid}"); + if let Ok(invalid) = serde_json::from_value::(invalid) { + assert!(invalid.validate().is_err()); + } + } + let mut legacy = raw; + legacy.as_object_mut().unwrap().remove("placement"); + assert!(validate_face_anchor_json(&legacy).is_ok()); + let legacy: FaceAnchor = serde_json::from_value(legacy).unwrap(); + doc.occurrences.iter_mut().find(|o| o.component == author).unwrap().transform[3][0] = 40.; + let mut state = ModelState::default(); + state.bodies.push(body); + assert!(doc.resolve_face_anchor(&anchor, author, &state).unwrap().origin.dist(picked.origin) < 1e-9); + assert!(doc.resolve_face_anchor(&legacy, author, &state).unwrap().origin.dist(picked.origin - Vec3::X * 40.) < 1e-9); + doc.occurrences.clear(); + assert!(doc.resolve_face_anchor(&anchor, author, &state).is_err(), "a captured context still validates its paths"); + } + #[test] fn nested_anchor_offset_tracks_source_and_raw_budgets_precede_decode() { let (doc, body, index, picked) = fixture(); @@ -544,7 +626,7 @@ mod tests { } #[test] fn extrude_cap_profile_reordering_never_retargets_an_ordinal_body() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; let mut sketch = solidcraft_sketch::Sketch::new(); for offset in [0., 30.] { let points: Vec<_> = [(0., 0.), (10., 0.), (10., 10.), (0., 10.)] @@ -637,7 +719,7 @@ mod tests { } #[test] fn warm_root_body_offset_edit_matches_cold_attached_sketch_and_downstream_bounds() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; let (mut doc, _, _, _) = fixture(); let mut warm = Model::new(); warm.evaluate(&doc); diff --git a/crates/doc/src/feature_geometry.rs b/crates/doc/src/feature_geometry.rs index 09a0a4881..f5536a212 100644 --- a/crates/doc/src/feature_geometry.rs +++ b/crates/doc/src/feature_geometry.rs @@ -4,7 +4,7 @@ //! The walk (`crate::walk`) is behind `transform_geometry`, `face_points`, `profile_sels` and //! `point_expr`. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::walk::Walk; use crate::{FeatureKind, PointExpr, ProfileSel}; @@ -55,7 +55,7 @@ impl FeatureKind { /// The body a feature that works on one body's faces names (shell, draft, split, offset, /// delete and replace face, surface offset, the placed plastic features, sheet metal - /// conversion, ruled surface): its face points pick faces of that body. + /// conversion, ruled surface, untrim): its face points pick faces of that body. pub fn face_body(&self) -> Option<&str> { match self { FeatureKind::Shell { body, .. } @@ -69,6 +69,7 @@ impl FeatureKind { | FeatureKind::SnapFit { body, .. } | FeatureKind::Rest { body, .. } => body.as_deref(), FeatureKind::SheetConvert { body, .. } | FeatureKind::SurfaceRuled { body, .. } => Some(body.as_ref()), + FeatureKind::SurfaceUntrim { face, .. } => Some(face.body.as_ref()), _ => None, } } diff --git a/crates/doc/src/feature_walk_tests.rs b/crates/doc/src/feature_walk_tests.rs index 5f5c22e90..4becb99f1 100644 --- a/crates/doc/src/feature_walk_tests.rs +++ b/crates/doc/src/feature_walk_tests.rs @@ -202,6 +202,7 @@ fn construction_names_follow_renames_in_every_definition() { let planes = [ json!({"type": "midplane", "a": plane, "b": plane}), json!({"type": "two_edges", "a": axis, "b": axis}), + json!({"type": "axis_point", "axis": axis, "point": point}), json!({"type": "three_points", "a": point, "b": point, "c": point}), json!({"type": "tangent", "face": plane, "at": [0, 0, 0]}), json!({"type": "along_path", "path": axis, "t": "0.5"}), diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index 27037f33e..c166586a6 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -148,7 +148,10 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ("sheet_hem", json!({"type": "sheet_hem", "edges": [o], "length": "hem.length", "gap": "hem.gap"})), ( "sheet_perforate", - json!({"type": "sheet_perforate", "diameter": "perforate.diameter", "pitch": "perforate.pitch", "margin": "perforate.margin"}), + json!({ + "type": "sheet_perforate", "diameter": "perforate.diameter", "pitch": "perforate.pitch", "margin": "perforate.margin", + "sketch": 1, "profiles": {"type": "all"} + }), ), ( "sheet_fold", @@ -236,6 +239,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ("import", json!({"type": "import", "file": "a.step", "step": ""})), ("mesh_convert", json!({"type": "mesh_convert", "body": "B", "tolerance": "mesh_convert.tolerance"})), ("mesh_import", json!({"type": "mesh_import", "file": "a.stl", "meshes": []})), + ("repair", json!({"type": "repair", "body": "B", "gap": "repair.gap", "patch_holes": true})), ] } diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index fc766b6a5..c940c102b 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -107,7 +107,7 @@ pattern_circular inputs: Quantity = circ.count (Unitless) Total angle = circ.angle (Angle) - expressions: circ.count, circ.angle + expressions: circ.count, circ.angle, 0, 0, 0 pattern_path inputs: Quantity = path.count (Unitless) @@ -435,3 +435,7 @@ mesh_convert Tolerance = mesh_convert.tolerance (Length) expressions: mesh_convert.tolerance mesh_import +repair + inputs: + Gap = repair.gap (Length) + expressions: repair.gap diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index ce58eadb2..1c41447e0 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -47,6 +47,7 @@ pattern_rectangular moves: pattern.dir1[0], pattern.dir1[1], pattern.dir2[1], pattern.dir2[2] pattern_circular moves: pattern.axis[0], pattern.axis[2], pattern.origin[0], pattern.origin[1], pattern.origin[2] + placement: 0, 0, 0 pattern_path mirror moves: plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] @@ -133,6 +134,7 @@ sheet_flange sheet_hem moves: edges[0][0], edges[0][1], edges[0][2] sheet_perforate + profiles: 1 all sheet_fold moves: a[0], a[1], a[2], b[1], b[2], fixed[0], fixed[1], fixed[2] sheet_path @@ -210,3 +212,4 @@ move import mesh_convert mesh_import +repair diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 303007b9d..ca57f8315 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -143,6 +143,8 @@ sheet_flange sheet_hem remap_bodies: body sheet_perforate + sketches: [1] + remap_refs: sketch remap_bodies: body sheet_fold sketches: [7] @@ -239,3 +241,5 @@ import mesh_convert remap_bodies: body mesh_import +repair + remap_bodies: body diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 918dc3580..1247a5bec 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -497,8 +497,8 @@ const JSON_STEPS: [JsonStep; HAND_WRITTEN as usize - 1] = [ ]; /// Stored face and edge names were worked out from geometry before format 14; they get the -/// legacy mark (`?`, see `naming::LEGACY_MARK`) so they are found again as those builds found -/// them, and an older design evaluates as it was saved. The step marks the fields that store +/// legacy mark (`?`, see `naming::LEGACY_MARK`), which finds no face or edge: a feature holding +/// one fails, asking for its reference to be picked again. The step marks the fields that store /// such a name, by their place in the schema: /// - each feature's `face_names`, and fillets' and chamfers' `edge_names` (other features' edge /// names are sheet metal's own); @@ -726,6 +726,13 @@ pub fn read(s: &str) -> Result { let mut grouped_features = std::collections::BTreeSet::new(); let joint_ids: std::collections::BTreeSet<_> = d.assembly.joints.iter().map(|joint| joint.id).collect(); let mut grouped_joints = std::collections::BTreeSet::new(); + // A folder entry naming a feature or joint the design doesn't have, or one a folder already + // holds, is dropped, and the design opens: folders only group the timeline, so nothing else + // is lost. Editing a feature inside a folder used to leave such entries (#9373). + for group in &mut d.timeline_groups { + group.joints.retain(|joint| joint_ids.contains(joint) && grouped_joints.insert(*joint)); + group.features.retain(|feature| feature_ids.contains(feature) && grouped_features.insert(*feature)); + } for group in &d.timeline_groups { if group.name.trim().is_empty() || group.name.len() > 128 || !group_ids.insert(group.id) { return Err(DocError::Invalid("damaged design: invalid timeline folder".into())); @@ -733,12 +740,6 @@ pub fn read(s: &str) -> Result { if group.parent.is_some_and(|parent| parent == group.id) { return Err(DocError::Invalid("damaged design: timeline folder cannot contain itself".into())); } - if group.joints.iter().any(|joint| !joint_ids.contains(joint) || !grouped_joints.insert(*joint)) { - return Err(DocError::Invalid("damaged design: invalid joint in a timeline folder".into())); - } - if group.features.iter().any(|feature| !feature_ids.contains(feature) || !grouped_features.insert(*feature)) { - return Err(DocError::Invalid("damaged design: invalid feature in a timeline folder".into())); - } } for group in &d.timeline_groups { if let Some(parent) = group.parent { @@ -758,10 +759,14 @@ pub fn read(s: &str) -> Result { if let Some(id) = crate::non_contiguous_timeline_group(&d.features, &d.timeline_groups) { return Err(DocError::Invalid(format!("damaged design: timeline folder {id} is not contiguous"))); } - for o in &d.occurrences { - if !rigid(&o.transform) { - return Err(DocError::Invalid(format!("damaged design: occurrence `{}` has an invalid placement", o.name))); - } + // Every occurrence whose placement is not a rigid motion within range, by name. + let unplaced: Vec = d.occurrences.iter().filter(|o| !crate::is_placement(&o.transform)).map(|o| format!("`{}`", o.name)).collect(); + if !unplaced.is_empty() { + return Err(DocError::Invalid(format!( + "damaged design: {} not placed by a rigid motion within 1e9 mm: {}", + if unplaced.len() == 1 { "an occurrence is" } else { "occurrences are" }, + unplaced.join(", ") + ))); } if !all_unique(d.features.iter().map(|f| f.id)) || !all_unique(d.components.iter().map(|c| c.id)) @@ -776,6 +781,7 @@ pub fn read(s: &str) -> Result { sketch.validate_wires().map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; sketch.validate_patterns().map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; sketch.validate_periodic_splines().map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; + sketch.validate_spline_knots().map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; } if let crate::FeatureKind::BodyTransfer { from, to, .. } = &feature.kind && [from, to].into_iter().any(|id| !component_ids.contains(id)) @@ -1238,26 +1244,6 @@ fn check_numbers(v: &Value, noun: &str, depth: usize) -> Result<()> { Ok(()) } -/// A placement: rotation (orthonormal, not mirrored) and a translation in range. -fn rigid(m: &crate::Mat) -> bool { - let row = |i: usize| m.get(i).copied().unwrap_or_default(); - let (x, y, z, t) = (row(0), row(1), row(2), row(3)); - let dot = |a: [f64; 4], b: [f64; 4]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - let unit = |a: [f64; 4]| (dot(a, a) - 1.0).abs() < 1e-6; - let det = x[0] * (y[1] * z[2] - y[2] * z[1]) - x[1] * (y[0] * z[2] - y[2] * z[0]) + x[2] * (y[0] * z[1] - y[1] * z[0]); - m.iter().flatten().all(|v| v.is_finite()) - && unit(x) - && unit(y) - && unit(z) - && dot(x, y).abs() < 1e-6 - && dot(y, z).abs() < 1e-6 - && dot(x, z).abs() < 1e-6 - && det > 0.0 - && [x[3], y[3], z[3]].iter().all(|v| v.abs() < 1e-9) - && (t[3] - 1.0).abs() < 1e-9 - && t[..3].iter().all(|v| v.abs() <= MAX_REAL) -} - /// Feature input names and component occurrences, which format 1 files may predate. fn normalise(d: &mut Document) -> Result<()> { d.normalise_component_color_indices()?; @@ -1273,6 +1259,7 @@ fn normalise(d: &mut Document) -> Result<()> { #[cfg(test)] mod tests { use super::*; + use solidcraft_geom::prelude::*; /// A pending change that records that its step ran, in `trace`. fn traced(name: &'static str) -> Part { @@ -1703,7 +1690,7 @@ mod tests { #[test] fn version_twenty_three_designs_open_and_an_edge_flange_relief_is_saved_in_twenty_four() { let flange = |shape: Option<&str>, size: Option<&str>| crate::FeatureKind::SheetFlange { - edges: vec![crate::FlangeEdge::at(solidcraft_geom::Vec3::ZERO)], + edges: vec![crate::FlangeEdge::at(solidcore_record::Vec3::ZERO)], height: "10 mm".into(), angle: "90 deg".into(), radius: None, @@ -1809,7 +1796,7 @@ mod tests { #[test] fn version_nine_wire_spaces_preserve_saved_points_and_explicit_markers() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; use solidcraft_sketch::{LinkKind, LinkSource, Sketch, WireSpace}; let mut sketch = Sketch::new(); sketch.add_drawn_wire(&[Vec3::new(12.0, 3.0, 4.0)]).unwrap(); @@ -1922,9 +1909,11 @@ mod tests { start_offset: None, through_all: false, taper: Some("0 deg".into()), - to: Some(crate::FacePick(solidcraft_geom::Vec3::new(0.0, 0.0, 10.0))), + corner: Default::default(), + to: Some(crate::FacePick(solidcore_record::Vec3::new(0.0, 0.0, 10.0))), to_offset: Some("offset + 1 mm".into()), - from: Some(crate::FacePick(solidcraft_geom::Vec3::new(0.0, 0.0, 5.0))), + from: Some(crate::FacePick(solidcore_record::Vec3::new(0.0, 0.0, 5.0))), + to_body_apart: false, }, operation: Operation::NewBody, targets: vec![], @@ -1969,7 +1958,7 @@ mod tests { #[test] fn saved_offset_cannot_alias_and_overwrite_its_source_geometry() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::{CurveKind, Sketch}; let mut sketch = Sketch::new(); let center = sketch.add_point(Vec2::ZERO, None).unwrap(); @@ -2108,7 +2097,7 @@ mod tests { #[test] fn periodic_file_validation_refuses_damaged_closed_geometry() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::{CurveKind, Sketch}; let mut sketch = Sketch::new(); let mut pts = Vec::new(); @@ -2118,7 +2107,7 @@ mod tests { let first = pts[0]; let neighbor = pts[1]; let closing = pts[3]; - sketch.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: true }, None).unwrap(); + sketch.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: true, nurbs: None }, None).unwrap(); let mut document = Document::new("periodic file validation"); document.add_feature(crate::FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap(); assert_eq!(read(&document.to_json()).unwrap(), document); @@ -2258,7 +2247,7 @@ mod tests { #[test] fn version_seven_origin_sketch_keeps_geometry_dimension_ids_and_expressions() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::{ConstraintKind, Sketch}; let mut d = Document::new("legacy origin dimensions"); d.set_param("reach", "25 mm", Some("mm"), None).unwrap(); @@ -2288,7 +2277,7 @@ mod tests { #[test] fn version_eight_persistent_angle_sweep_and_slot_dimensions_roundtrip() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::{ConstraintKind, Sketch}; let mut d = Document::new("persistent typed dimensions"); let heading = d.new_model_param("45 deg", "deg"); @@ -2407,12 +2396,12 @@ mod tests { let (values, errors) = migrated.param_values(); assert!(errors.is_empty()); let p = migrated.resolve_plane(&values, plane, 0).unwrap(); - assert_eq!(p.y, solidcraft_geom::Vec3::Z); - assert_eq!(p.normal(), -solidcraft_geom::Vec3::Y); - assert_eq!(p.origin, solidcraft_geom::Vec3::new(0.0, -7.0, 0.0)); + assert_eq!(p.y, solidcore_record::Vec3::Z); + assert_eq!(p.normal(), -solidcore_record::Vec3::Y); + assert_eq!(p.origin, solidcore_record::Vec3::new(0.0, -7.0, 0.0)); assert_eq!(read(&migrated.to_json()).unwrap(), migrated); let fresh = doc.resolve_plane(&values, &crate::PlaneRef::Origin { name: "XZ".into() }, 0).unwrap(); - assert_eq!(fresh.normal(), solidcraft_geom::Vec3::Y); + assert_eq!(fresh.normal(), solidcore_record::Vec3::Y); } #[test] @@ -2460,7 +2449,7 @@ mod tests { let mut sketch = Sketch::new(); let mut previous = 0; while sketch.points.len() < MAX_POINTS { - let i = sketch.add_point(solidcraft_geom::Vec2::new(0.001 * sketch.points.len() as f64, 0.0), None).unwrap(); + let i = sketch.add_point(solidcore_record::Vec2::new(0.001 * sketch.points.len() as f64, 0.0), None).unwrap(); sketch.add_constraint(solidcraft_sketch::ConstraintKind::Coincident { p: previous, q: i }, None).unwrap(); previous = i; } @@ -2572,7 +2561,7 @@ mod tests { #[test] fn integer_valued_coordinates_are_range_checked_and_large_ids_still_load() { let mut sketch = solidcraft_sketch::Sketch::new(); - sketch.add_point(solidcraft_geom::Vec2::new(40.0, 0.0), None).unwrap(); + sketch.add_point(solidcore_record::Vec2::new(40.0, 0.0), None).unwrap(); let mut d = Document::new("range"); d.add_feature(crate::FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap(); let last = |v: &Value| v["features"][0]["sketch"]["points"].as_array().map_or(0, |a| a.len() - 1); @@ -2629,7 +2618,7 @@ mod tests { "orientation": {"direction": [0.0, 1.0, 0.0]}, "twist": "90 deg", "scale": "0.5"}); let k: FeatureKind = serde_json::from_value(new.clone()).unwrap(); let FeatureKind::SurfaceSweep { orientation, .. } = &k else { panic!("{k:?}") }; - assert_eq!(*orientation, SweepOrientation::Direction(crate::Dir(solidcraft_geom::Vec3::Y))); + assert_eq!(*orientation, SweepOrientation::Direction(crate::Dir(solidcore_record::Vec3::Y))); assert_eq!(serde_json::to_value(&k).unwrap(), new); let parallel: SweepOrientation = serde_json::from_value(serde_json::json!("parallel")).unwrap(); assert_eq!(parallel, SweepOrientation::Parallel); diff --git a/crates/doc/src/format/pending/fillet-turn.rs b/crates/doc/src/format/pending/fillet-turn.rs new file mode 100644 index 000000000..34c49ca99 --- /dev/null +++ b/crates/doc/src/format/pending/fillet-turn.rs @@ -0,0 +1,5 @@ +//! A fillet saves `turn: "swept"` when two of its rounds that turn round a sharp side edge (the +//! rounds along a boss's base, at its upright edges) are swept round that edge, their corner an +//! exact torus; absent, the default `mitre`, they meet in a mitre, as designs before this change were +//! built. An older design has none and keeps its mitres. The last release refuses a design with +//! this change (the newer format number). diff --git a/crates/doc/src/format/v45/browser-nested-groups.rs b/crates/doc/src/format/v45/browser-nested-groups.rs new file mode 100644 index 000000000..13c98678e --- /dev/null +++ b/crates/doc/src/format/v45/browser-nested-groups.rs @@ -0,0 +1,6 @@ +//! Browser groups can nest and be ordered. A group saves its `parent` group (omitted at the top +//! level); a group's items and a folder's `browser_order` list may name groups as numbers beside +//! item keys as strings; and `browser_order` has a `"/components"` list ordering a +//! component's sub-components by placement id. Older designs read unchanged: they have no +//! parents and no group entries. The last release refuses the newer format and asks for an +//! update instead of dropping the nesting and the order. diff --git a/crates/doc/src/format/v45/point-cloud-properties.rs b/crates/doc/src/format/v45/point-cloud-properties.rs new file mode 100644 index 000000000..ea8097212 --- /dev/null +++ b/crates/doc/src/format/v45/point-cloud-properties.rs @@ -0,0 +1,7 @@ +//! A point cloud keeps the other properties its file gives its points (#8816): named numbers per +//! point in `complex` (`columns`, each whole-numbered or not, and the `names` a whole-numbered one's +//! values carry), and it can be coloured by one of them (`color_by: "property"`, with +//! `color_property`, the ramp over `height_range`) and shown only where `filters` keep it (ranges, +//! or sets of named values). Older designs need no transformation: their clouds have no other +//! properties and no filters. The last release refuses a design saved with this (the newer format +//! number) instead of opening its clouds without their properties, colouring and filters. diff --git a/crates/doc/src/format/v45/print-faces.rs b/crates/doc/src/format/v45/print-faces.rs new file mode 100644 index 000000000..88c7101e6 --- /dev/null +++ b/crates/doc/src/format/v45/print-faces.rs @@ -0,0 +1,5 @@ +//! A design saves the print face of its bodies (`print_faces`, by body name): the flat face a +//! slicer export lays on the print bed, held by the same face target a sketch on a face holds. +//! An older design has none, and every body is exported as it lies, as before. The last +//! release refuses a design that has print faces and asks for an update, instead of opening it +//! and losing them on the next save. diff --git a/crates/doc/src/format/v46/align-axis-mask.rs b/crates/doc/src/format/v46/align-axis-mask.rs new file mode 100644 index 000000000..e79d666c1 --- /dev/null +++ b/crates/doc/src/format/v46/align-axis-mask.rs @@ -0,0 +1,5 @@ +//! A point-to-point Align can save `axes`: the directions it moves along, as the chosen world +//! X/Y/Z axes in the frame of the bodies being moved (if it is absent, all three axes are used and +//! the offset is applied in full). Older designs need no transformation: they align on all three +//! axes as before. The last release refuses a design that has this (it refuses the newer format +//! number) rather than moving the bodies on all three axes. diff --git a/crates/doc/src/format/v46/equation-variable-unit.rs b/crates/doc/src/format/v46/equation-variable-unit.rs new file mode 100644 index 000000000..d94a59a94 --- /dev/null +++ b/crates/doc/src/format/v46/equation-variable-unit.rs @@ -0,0 +1,5 @@ +//! An equation curve can save `variable_unit: "range"`: its variable is a length, as its range is, +//! instead of a plain number (#9333). An older design has none, and its variable stays a plain +//! number, as before; a curve with a plain variable saves nothing new. The last release refuses a +//! design with this change and asks for an update, instead of opening it and losing the key on the +//! next save. diff --git a/crates/doc/src/format/v46/link-file-digests.rs b/crates/doc/src/format/v46/link-file-digests.rs new file mode 100644 index 000000000..bb367c530 --- /dev/null +++ b/crates/doc/src/format/v46/link-file-digests.rs @@ -0,0 +1,5 @@ +//! A linked component's link saves `file_sha256`, the SHA-256 of the linked design file's bytes +//! as the assembly last read them, so an assembly opened again knows which linked designs changed +//! while it was closed (#9739). Older designs read unchanged: their links have no digest and are +//! taken as up to date until Update Links reads them. The last release refuses the newer format +//! and asks for an update instead of dropping the digests. diff --git a/crates/doc/src/format/v47/component-history-hidden.rs b/crates/doc/src/format/v47/component-history-hidden.rs new file mode 100644 index 000000000..e05770754 --- /dev/null +++ b/crates/doc/src/format/v47/component-history-hidden.rs @@ -0,0 +1,5 @@ +//! A component marked out of the History bar saves `history_hidden: true` on its component +//! entry, so its features (and its children's) stay out of the History bar while still +//! rebuilding. Older designs carry no such flag and every component shows its features, which +//! is exactly the flag's default; the last release refuses this newer format and asks for an +//! update instead of silently dropping the flag on the next save. diff --git a/crates/doc/src/format/v47/face-anchor-placement.rs b/crates/doc/src/format/v47/face-anchor-placement.rs new file mode 100644 index 000000000..b39a55e3d --- /dev/null +++ b/crates/doc/src/format/v47/face-anchor-placement.rs @@ -0,0 +1,5 @@ +//! Cross-component face anchors in a part save the source-to-author component placement at +//! creation, so assembly moves do not reshape the part. Source geometry and body offsets stay +//! associative. Older anchors without `placement` retain their live placement relationship; +//! redefining their sketch plane captures a new context. The last release refuses this newer +//! format and asks for an update instead of dropping the captured placement. diff --git a/crates/doc/src/format/v47/plane-axis-point.rs b/crates/doc/src/format/v47/plane-axis-point.rs new file mode 100644 index 000000000..d749e10a1 --- /dev/null +++ b/crates/doc/src/format/v47/plane-axis-point.rs @@ -0,0 +1,3 @@ +//! Construction planes can store an associative axis and off-axis point reference. +//! Older designs keep their existing plane definitions unchanged. The last release +//! asks for an update rather than opening a design with this new plane definition. diff --git a/crates/doc/src/format/v48/circular-pattern-origin-expressions.rs b/crates/doc/src/format/v48/circular-pattern-origin-expressions.rs new file mode 100644 index 000000000..7919fbe64 --- /dev/null +++ b/crates/doc/src/format/v48/circular-pattern-origin-expressions.rs @@ -0,0 +1,4 @@ +//! A circular pattern's axis `origin` can hold length expressions (strings) as well as numbers, +//! so a pattern about a parameter-driven point follows the parameter (#10852). An origin of +//! plain numbers is saved as before, and older designs need no transformation. The last release +//! refuses this newer format and asks for an update instead of failing to read the origin. diff --git a/crates/doc/src/format/v48/sheet-perforation-outline.rs b/crates/doc/src/format/v48/sheet-perforation-outline.rs new file mode 100644 index 000000000..423133a3b --- /dev/null +++ b/crates/doc/src/format/v48/sheet-perforation-outline.rs @@ -0,0 +1,4 @@ +//! A perforation field can be bounded by a sketch: a `sheet_perforate` feature saves an optional `sketch` and +//! `profiles` (its outline), and a sheet's perforation the outline in flat coordinates (`outline`). Holes go only +//! inside the outline. Older designs need no transformation: a field without an outline covers the whole sheet as +//! before. The last release refuses a design saved with this (the newer format number). diff --git a/crates/doc/src/format/v48/tangent-plane-reference.rs b/crates/doc/src/format/v48/tangent-plane-reference.rs new file mode 100644 index 000000000..5f8ce101b --- /dev/null +++ b/crates/doc/src/format/v48/tangent-plane-reference.rs @@ -0,0 +1,5 @@ +//! A tangent construction plane can save a `reference` (a plane or planar face) and an `angle` +//! (#8822): the plane touches the face where it turns towards the reference, turned by the angle +//! about the face's axis. An older design has neither, and its tangent planes touch where they +//! were picked, as before. The last release refuses a design that has them (it asks for an +//! update) instead of opening those planes at the picked point, away from their reference. diff --git a/crates/doc/src/format/v49/ball-patch-faces.rs b/crates/doc/src/format/v49/ball-patch-faces.rs new file mode 100644 index 000000000..3c716145f --- /dev/null +++ b/crates/doc/src/format/v49/ball-patch-faces.rs @@ -0,0 +1,4 @@ +//! A face may save `surface` as a `ball_patch` {center, radius}: the corner of three equal rounds +//! as SMLib holds it, a rational patch on that sphere, always with its `nurbs`, the patch itself. +//! An older design has these faces as plain NURBS faces and keeps them so. The last release +//! refuses a design with this change (the newer format number). diff --git a/crates/doc/src/format/v49/blend-tangent-chain.rs b/crates/doc/src/format/v49/blend-tangent-chain.rs new file mode 100644 index 000000000..6e76c6aa8 --- /dev/null +++ b/crates/doc/src/format/v49/blend-tangent-chain.rs @@ -0,0 +1,4 @@ +//! A fillet or chamfer saves `tangent_chain: false` when it blends only its picked edges; absent, +//! the default, it blends each picked edge's tangent chain too, as designs before this change were +//! built (SMLib followed the chains itself). An older design has none and keeps its chains. The +//! last release refuses a design with this change (the newer format number). diff --git a/crates/doc/src/format/v49/continuity-g4.rs b/crates/doc/src/format/v49/continuity-g4.rs new file mode 100644 index 000000000..62e6c8155 --- /dev/null +++ b/crates/doc/src/format/v49/continuity-g4.rs @@ -0,0 +1,4 @@ +//! A continuity order may be saved as `g4` (the curvature's change also changes smoothly across +//! the seam) wherever a design saves one (`g0` … `g3` before): a patch's, blend's, boundary's, +//! loft's or match surface's continuity. An older design has none and means what it did. The last +//! release refuses a design with this change (the newer format number) instead of misreading it. diff --git a/crates/doc/src/format/v49/draft-corner.rs b/crates/doc/src/format/v49/draft-corner.rs new file mode 100644 index 000000000..9f6d7e114 --- /dev/null +++ b/crates/doc/src/format/v49/draft-corner.rs @@ -0,0 +1,7 @@ +//! An extrude's taper saves how it closes the profile's sharp corners when the user chose: +//! `extent.corner`, `preserve_curvature` (each wall continues as itself until it meets its +//! neighbour), `tangent` (each offset curve continued straight along its end tangent) or `round` +//! (an arc about the corner). Without it each profile preserves curvature where every curve is a +//! line or an arc and takes the tangent rule where another curve has a corner, the feature's +//! warning saying so; an older design has none and gets that choice. The last release refuses a +//! design with this change (the newer format number). diff --git a/crates/doc/src/format/v49/edge-nurbs-form.rs b/crates/doc/src/format/v49/edge-nurbs-form.rs new file mode 100644 index 000000000..51e5fb203 --- /dev/null +++ b/crates/doc/src/format/v49/edge-nurbs-form.rs @@ -0,0 +1,4 @@ +//! An edge on a line, circle or ellipse may save `nurbs`: the NURBS form it is parameterised on, +//! as SMLib holds it. Its interval and the pcurves' parameter are then that NURBS's, and `curve` +//! only says what the edge is. An older design has none and keeps the curve's own parameter. The +//! last release refuses a design with this change (the newer format number). diff --git a/crates/doc/src/format/v49/face-nurbs-form.rs b/crates/doc/src/format/v49/face-nurbs-form.rs new file mode 100644 index 000000000..70f468807 --- /dev/null +++ b/crates/doc/src/format/v49/face-nurbs-form.rs @@ -0,0 +1,4 @@ +//! A face on a cylinder, cone, sphere or torus may save `nurbs`: the NURBS form it is +//! parameterised on, as SMLib holds it. Its domain and pcurves are then that NURBS's (u, v), and +//! `surface` only says what the face is. An older design has none and keeps the analytic (u, v). +//! The last release refuses a design with this change (the newer format number). diff --git a/crates/doc/src/format/v49/join-to-body-apart.rs b/crates/doc/src/format/v49/join-to-body-apart.rs new file mode 100644 index 000000000..4bfca9851 --- /dev/null +++ b/crates/doc/src/format/v49/join-to-body-apart.rs @@ -0,0 +1,70 @@ +//! A Join extrude To Object may save `to_body_apart: true` in its `extent`: the body it runs to +//! stays its own body and only the Join's targets take the tool. Since 0.24.1 a Join To Object +//! also joins the body it runs to (#6424); designs saved by 0.24.0 and earlier (format 39 and +//! older) were built without that, so their later features name the body it would swallow and +//! the faces the union would merge (#8151). Such a design gets the field on every Join extrude +//! To Object as it opens, and keeps its bodies; designs of format 40 and later are left as they +//! are. The last release refuses a design that has the field (it refuses the newer format +//! number). + +use serde_json::Value; + +use crate::Result; + +/// The first format whose Join extrudes To Object also joined the body they run to. +const JOINS_TO_BODY: u32 = 40; + +pub fn step(v: &mut Value) -> Result<()> { + // The file's own format is still in it: upgrades never rewrite `format`, and a file without + // one is format 1. + let version = match v.get("format").and_then(Value::as_str) { + Some(format) => crate::format::version_of(format), + None => Some(1), + }; + if version.is_none_or(|n| n >= JOINS_TO_BODY) { + return Ok(()); + } + for feature in v.get_mut("features").and_then(Value::as_array_mut).into_iter().flatten() { + let join_extrude = feature.get("type").and_then(Value::as_str) == Some("extrude") + && feature.get("operation").and_then(Value::as_str) == Some("join"); + if !join_extrude { + continue; + } + if let Some(extent) = feature.get_mut("extent").and_then(Value::as_object_mut) + && extent.get("to").is_some_and(|to| !to.is_null()) + { + extent.insert("to_body_apart".into(), Value::Bool(true)); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use serde_json::json; + + fn design(format: &str) -> serde_json::Value { + json!({"format": format, "features": [ + {"type": "extrude", "operation": "join", "extent": {"distance": "0", "to": [0.0, 0.0, 30.0]}}, + {"type": "extrude", "operation": "join", "extent": {"distance": "10 mm"}}, + {"type": "extrude", "operation": "cut", "extent": {"distance": "0", "to": [0.0, 0.0, 30.0]}}, + ]}) + } + + fn apart(v: &serde_json::Value) -> Vec { + v["features"].as_array().unwrap().iter().map(|f| f["extent"]["to_body_apart"] == json!(true)).collect() + } + + #[test] + fn only_joins_to_an_object_saved_before_format_40_keep_the_body_apart() { + let mut old = design("solidcraft/39"); + super::step(&mut old).unwrap(); + assert_eq!(apart(&old), [true, false, false]); + for newer in ["solidcraft/40", "solidcraft/46"] { + let mut v = design(newer); + super::step(&mut v).unwrap(); + assert_eq!(apart(&v), [false, false, false], "{newer}"); + } + } +} diff --git a/crates/doc/src/format/v49/join-touching-bodies.rs b/crates/doc/src/format/v49/join-touching-bodies.rs new file mode 100644 index 000000000..a61bc4ca5 --- /dev/null +++ b/crates/doc/src/format/v49/join-touching-bodies.rs @@ -0,0 +1,26 @@ +//! A feature that joins saves what it makes of pieces that share no face: `touching`, +//! `separate` (the default, not saved: a piece that touches another only along an edge or at a +//! point becomes a body of its own, pieces that touch nothing stay one body) or `one_body` (every +//! piece in one body). Older builds kept every join's pieces in one body, also those touching +//! along an edge or at a point, so this step gives each feature of an older design that can join +//! `one_body`, which keeps its bodies as they were (only a join with such a contact would +//! change). The last release refuses a design with this change (the newer format number). +use serde_json::Value; + +/// Feature types that join without an `operation` saying so: a combine (whose `new` joins too), +/// patterns and mirrors (which repeat a join), and the features that add material to a body. +const JOINING: [&str; 8] = ["combine", "pattern", "mirror", "emboss", "rib", "boss", "snap_fit", "rest"]; + +pub fn step(v: &mut Value) -> crate::Result<()> { + let Some(Value::Array(features)) = v.get_mut("features") else { + return Ok(()); + }; + for feature in features { + let joins = feature.get("type").and_then(Value::as_str).is_some_and(|t| JOINING.contains(&t)) + || feature.get("operation").and_then(Value::as_str) == Some("join"); + if joins && let Some(f) = feature.as_object_mut() { + f.insert("touching".into(), Value::from("one_body")); + } + } + Ok(()) +} diff --git a/crates/doc/src/format/v49/pipe-threads.rs b/crates/doc/src/format/v49/pipe-threads.rs new file mode 100644 index 000000000..6c1d326c2 --- /dev/null +++ b/crates/doc/src/format/v49/pipe-threads.rs @@ -0,0 +1,5 @@ +//! A thread's `form` may be `bspp` (ISO 228-1 parallel pipe thread, `G 1/2`), `rp` (ISO 7-1's +//! parallel internal thread, `Rp 1/2`), `bspt` (ISO 7-1 taper, `R 1/2` external, `Rc 1/2` +//! internal) or `npt` (ASME B1.20.1 taper, `1/2-14 NPT`), and a tapped hole's `thread` may be +//! `Rc 1/2` or `1/2-14 NPT`. An older design has none of them and needs no rewrite. The last +//! release refuses a design saved with this (the newer format number). diff --git a/crates/doc/src/format/v49/repair-part.rs b/crates/doc/src/format/v49/repair-part.rs new file mode 100644 index 000000000..9718c18cf --- /dev/null +++ b/crates/doc/src/format/v49/repair-part.rs @@ -0,0 +1,5 @@ +//! A design can hold Repair Part (#8371): a `repair` feature with the `body` it repairs, the +//! widest `gap` between free edges it sews (a length expression) and `patch_holes` (default false, +//! not saved: the loops of free edges left are patched and sewn in). Older designs need no +//! transformation: they have no such feature. The last release refuses a design saved with this +//! (the newer format number). diff --git a/crates/doc/src/format/v49/ruled-far-handles.rs b/crates/doc/src/format/v49/ruled-far-handles.rs new file mode 100644 index 000000000..c67adcfcf --- /dev/null +++ b/crates/doc/src/format/v49/ruled-far-handles.rs @@ -0,0 +1,4 @@ +//! A ruled surface saves the handles of its free strips' far curves: `far`, per chain edge, the +//! interior control points of the curve a strip whose rulings turn freely along its edge is ruled +//! to (or null for the kernel's default curve). An older design has none and gets the default +//! curves. The last release refuses a design with this change (the newer format number). diff --git a/crates/doc/src/format/v49/spline-knots.rs b/crates/doc/src/format/v49/spline-knots.rs new file mode 100644 index 000000000..8fd839e95 --- /dev/null +++ b/crates/doc/src/format/v49/spline-knots.rs @@ -0,0 +1,6 @@ +//! A sketch's control spline may save `nurbs`: its own `knots` (clamped, the point count plus +//! the degree plus one) and `weights` (one per point; none: all 1). A projected free-form edge +//! comes in as that one exact curve, where it came in as one spline per Bézier span. An older +//! design has none: its splines are the clamped uniform B-splines they were, and its projected +//! edges are read again as they rebuild. The last release refuses a design with this change +//! (the newer format number). diff --git a/crates/doc/src/format/v49/thread-ends.rs b/crates/doc/src/format/v49/thread-ends.rs new file mode 100644 index 000000000..670a8ca6c --- /dev/null +++ b/crates/doc/src/format/v49/thread-ends.rs @@ -0,0 +1,51 @@ +//! A modelled thread saves how its ends are finished: `ease_out`, the runout at the inner end, +//! away from where it starts (`standard` 2.5 P, `short` 1.25 P or `{length}`, ISO 3508), and +//! `tip`, which free ends are chamfered (`start`: the end it starts from, `both`: each free end; +//! ISO 4753), with `chamfer_angle` and `chamfer_depth`. A tapped hole saves `modeled` (its thread +//! cut into the wall) and that thread's `ease_out` towards the bottom. Without them, as in an +//! older design, the groove stops square, no end is chamfered and a tapped hole's thread is only +//! listed. Designs saved while these were being made are +//! rewritten as they open: `tip: chamfer` (every free end) becomes `both`, and an `ease_in` (a +//! runout at the start, which now always runs off its free end) is dropped. The last release +//! refuses a design saved with this (the newer format number). +use serde_json::Value; + +pub fn step(v: &mut Value) -> crate::Result<()> { + let Some(Value::Array(features)) = v.get_mut("features") else { + return Ok(()); + }; + for feature in features { + let Some(object) = feature.as_object_mut() else { continue }; + if object.get("type").and_then(Value::as_str) != Some("thread") { + continue; + } + if object.get("tip").and_then(Value::as_str) == Some("chamfer") { + object.insert("tip".into(), Value::String("both".into())); + } + object.remove("ease_in"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + #[test] + fn a_chamfered_tip_becomes_both_ends_and_the_start_runout_goes() { + let mut v = json!({"features": [ + {"type": "thread", "designation": "M10", "modeled": true, "tip": "chamfer", "ease_in": "standard", "ease_out": "short"}, + {"type": "thread", "designation": "M10", "modeled": true}, + {"type": "chamfer", "tip": "chamfer"} + ]}); + super::step(&mut v).unwrap(); + assert_eq!(v["features"][0]["tip"], json!("both")); + assert!(v["features"][0].get("ease_in").is_none()); + assert_eq!(v["features"][0]["ease_out"], json!("short")); + assert!(v["features"][1].get("tip").is_none()); + assert_eq!(v["features"][2]["tip"], json!("chamfer"), "only threads"); + let mut empty = json!({"name": "Untitled"}); + super::step(&mut empty).unwrap(); + assert_eq!(empty, json!({"name": "Untitled"})); + } +} diff --git a/crates/doc/src/format/v49/thread-hand.rs b/crates/doc/src/format/v49/thread-hand.rs new file mode 100644 index 000000000..52a05662e --- /dev/null +++ b/crates/doc/src/format/v49/thread-hand.rs @@ -0,0 +1,26 @@ +//! A thread's direction is saved as `hand` on Hole features too (`right`, the default, not +//! saved, or `left`), as Thread features already save it (`right`, `left` or `both`). Format 39 +//! (v0.24.0) saved the direction of both as `handedness: "left"`; this step renames it to +//! `hand`, so a left-hand thread or tapped hole opens left-handed, and drops a `handedness: +//! "right"`. Older designs have neither and need nothing. The last release refuses a design with +//! this change (the newer format number). +use serde_json::Value; + +pub fn step(v: &mut Value) -> crate::Result<()> { + let Some(Value::Array(features)) = v.get_mut("features") else { + return Ok(()); + }; + for feature in features { + let threaded = matches!(feature.get("type").and_then(Value::as_str), Some("hole" | "thread")); + let Some(f) = feature.as_object_mut().filter(|_| threaded) else { continue }; + match f.remove("handedness") { + None => {} + Some(Value::String(h)) if h == "right" => {} + Some(Value::String(h)) if h == "left" => { + f.insert("hand".into(), Value::from("left")); + } + Some(other) => return Err(crate::DocError::Invalid(format!("a thread's `handedness` must be right or left, not {other}"))), + } + } + Ok(()) +} diff --git a/crates/doc/src/format/v49/torus-tube-start.rs b/crates/doc/src/format/v49/torus-tube-start.rs new file mode 100644 index 000000000..992cdb958 --- /dev/null +++ b/crates/doc/src/format/v49/torus-tube-start.rs @@ -0,0 +1,5 @@ +//! A torus surface may save `tube_start`: the tube angle (radians) its v counts from, so that a +//! face's form starts its tube where the face begins (a face covering most of the tube, off the +//! tube's quarter lines, imported from STEP). An older design has none and counts from the outer +//! equator, as before. The last release refuses a design with this change (the newer format +//! number). diff --git a/crates/doc/src/format/v49/wire-exact-curves.rs b/crates/doc/src/format/v49/wire-exact-curves.rs new file mode 100644 index 000000000..40ae67d2b --- /dev/null +++ b/crates/doc/src/format/v49/wire-exact-curves.rs @@ -0,0 +1,6 @@ +//! A linked 3D sketch curve (an included edge or an included sketch curve that leaves the sketch +//! plane) saves its exact geometry with its points: `wires[].exact`, the record curves (schema 4 +//! curve records with their intervals) end to end along the curve, so a sweep along it follows +//! the curve itself rather than its points. An older design has none and gets them when its +//! links are next resolved; until then such a curve is followed as its points. The last release +//! refuses a design with this change (the newer format number). diff --git a/crates/doc/src/format/v50/align-frames.rs b/crates/doc/src/format/v50/align-frames.rs new file mode 100644 index 000000000..e1793d1e3 --- /dev/null +++ b/crates/doc/src/format/v50/align-frames.rs @@ -0,0 +1,7 @@ +//! An Align feature (`FeatureKind::Align`) saves optional `from_frame` and `to_frame` (a joint +//! origin on the model, `{"type": "origin", "origin": {...}}`, or a sketch point or the centre of a +//! sketch circle, arc or ellipse, `{"type": "sketch_point", "sketch": id, "point": ""}` / +//! `{"type": "sketch_curve", "sketch": id, "curve": ""}`), found again from the geometry on +//! every evaluation so the bodies follow them, and an optional `angle` expression (a turn about the +//! target's direction). Older designs have none of them and evaluate as before. The last release +//! refuses a design with this change by its newer format number. diff --git a/crates/doc/src/format/v50/thread-nominal-size.rs b/crates/doc/src/format/v50/thread-nominal-size.rs new file mode 100644 index 000000000..6de719f22 --- /dev/null +++ b/crates/doc/src/format/v50/thread-nominal-size.rs @@ -0,0 +1,45 @@ +//! A thread with no `designation` (its size left automatic) now takes, for a hole, the size +//! whose nominal diameter the hole has (a 12 mm hole is M12); before, it took the size whose tap +//! drill the hole matches (a 12 mm hole was M14, the drill M14 is tapped at). A design saved +//! before keeps its size: each such thread is saved with `old_auto_size`, which an automatic +//! thread made now does not have. A modelled thread in a hole wider than it needs also narrows +//! the bore now, rather than being refused. The last release refuses a design saved with this +//! (the newer format number). +use serde_json::Value; + +pub fn step(v: &mut Value) -> crate::Result<()> { + let Some(Value::Array(features)) = v.get_mut("features") else { + return Ok(()); + }; + for feature in features { + let Some(object) = feature.as_object_mut() else { continue }; + if object.get("type").and_then(Value::as_str) != Some("thread") { + continue; + } + if object.get("designation").is_none_or(Value::is_null) { + object.insert("old_auto_size".into(), Value::Bool(true)); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + #[test] + fn an_automatic_thread_keeps_the_old_rule_and_a_named_one_is_left_alone() { + let mut v = json!({"features": [ + {"type": "thread", "face": [6, 0, 5]}, + {"type": "thread", "designation": "M12"}, + {"type": "hole", "thread": "M12"} + ]}); + super::step(&mut v).unwrap(); + assert_eq!(v["features"][0]["old_auto_size"], json!(true)); + assert!(v["features"][1].get("old_auto_size").is_none()); + assert!(v["features"][2].get("old_auto_size").is_none()); + let mut empty = json!({"name": "Untitled"}); + super::step(&mut empty).unwrap(); + assert_eq!(empty, json!({"name": "Untitled"})); + } +} diff --git a/crates/doc/src/format_offsets.rs b/crates/doc/src/format_offsets.rs index d1ce0a38e..2e398295a 100644 --- a/crates/doc/src/format_offsets.rs +++ b/crates/doc/src/format_offsets.rs @@ -411,9 +411,9 @@ mod tests { #[test] fn formats_one_through_eleven_keep_legacy_offset_geometry_and_ids() { let mut sketch = solidcraft_sketch::Sketch::new(); - let center = sketch.add_point(solidcraft_geom::Vec2::new(4., 7.), Some("center")).unwrap(); - sketch.add_circle(solidcraft_geom::Vec2::new(4., 7.), 10., Some(center), Some("source")).unwrap(); - sketch.add_circle(solidcraft_geom::Vec2::new(4., 7.), 9., Some(center), Some("offset")).unwrap(); + let center = sketch.add_point(solidcore_record::Vec2::new(4., 7.), Some("center")).unwrap(); + sketch.add_circle(solidcore_record::Vec2::new(4., 7.), 10., Some(center), Some("source")).unwrap(); + sketch.add_circle(solidcore_record::Vec2::new(4., 7.), 9., Some(center), Some("offset")).unwrap(); sketch.offsets.push(solidcraft_sketch::OffsetChain { sources: vec![("source".into(), true)], outputs: vec!["offset".into()], @@ -447,7 +447,7 @@ mod tests { fn missing_boundary_or_defining_sketch_reopens_as_a_model_error_without_retarget() { for missing_sketch in [false, true] { let mut sketch = solidcraft_sketch::Sketch::new(); - sketch.add_circle(solidcraft_geom::Vec2::new(0., 0.), 10., None, Some("unrelated-circle")).unwrap(); + sketch.add_circle(solidcore_record::Vec2::new(0., 0.), 10., None, Some("unrelated-circle")).unwrap(); let mut document = Document::new("repairable lost boundary"); let id = document.add_feature(FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap(); document @@ -464,9 +464,11 @@ mod tests { start_offset: None, through_all: false, taper: None, + corner: Default::default(), to: None, to_offset: None, from: None, + to_body_apart: false, }, operation: crate::Operation::NewBody, targets: vec![], diff --git a/crates/doc/src/frame.rs b/crates/doc/src/frame.rs index 604047817..47b9b02d4 100644 --- a/crates/doc/src/frame.rs +++ b/crates/doc/src/frame.rs @@ -13,10 +13,11 @@ //! of the profile's bounding box at the origin. The outline runs counter-clockwise and holes //! clockwise, as [`Region2`] expects. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Loop2, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2, Vec3}; use crate::expr::Kind; use crate::{DocError, Expr, Result}; diff --git a/crates/doc/src/history_names.rs b/crates/doc/src/history_names.rs index 039ed4fbf..2e1f75a1e 100644 --- a/crates/doc/src/history_names.rs +++ b/crates/doc/src/history_names.rs @@ -12,7 +12,10 @@ //! piece of `F2:top` bounded by the block's left wall and the slot's left wall. Pieces nothing //! around them tells apart are numbered (`#1`, `#2`): in the order of what they came from when //! that differs (exact), else in the kernel's order (unverified). A face made of several (a -//! coplanar join) takes one name and answers to the others (aliases). +//! coplanar join) takes one name and keeps the others as aliases: a reference to one of them is +//! to a face that is no longer as it was picked, and finds nothing. A face a feature built from +//! several of its own roles (a side drawn in collinear pieces) has each of them as a name +//! (synonyms): each names that very face. //! //! A piece that is split again keeps the face's stem and the bounds that told the piece it //! came from apart: its name lists the faces around it, not the qualifiers of the pieces @@ -21,7 +24,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, OnceLock}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_kernel::history::{FaceOrigin, FaceProv, History}; use crate::ModelBody; @@ -38,8 +41,13 @@ pub struct Names { /// What a face answers to besides its name, and how sure its name is. #[derive(Clone, Debug, Default)] pub(crate) struct FaceInfo { - /// Names of the other faces merged into it (a reference to one of them finds this face). + /// Names of the other faces merged into it. A reference to one of them is to a face that is + /// not this one as it was picked: a feature's reference by one finds nothing (`name_lookup`). pub aliases: Vec, + /// Other names of this very face: the roles besides its first of a face the feature that + /// built it made from several (a side drawn in collinear pieces is one face, made by each). + /// A reference by one of them finds the face as its name does. + pub synonyms: Vec, /// The stems of the faces around it: what tells it apart from other pieces of its face. pub bounds: BTreeSet, /// Whether the name follows exact history (`false`: worked out from geometry, or a piece @@ -54,7 +62,7 @@ impl Names { pub(crate) fn unverified(names: Vec, adjacent: &[(usize, usize)], centres: Option<&dyn Fn() -> Vec>) -> Names { let named = names .into_iter() - .map(|name| Named { name: crate::naming::strip_piece(&name).to_string(), aliases: Vec::new(), verified: false, origins: None }) + .map(|name| Named { name: crate::naming::strip_piece(&name).to_string(), verified: false, ..Named::default() }) .collect(); qualify_at(named, adjacent, centres) } @@ -72,10 +80,11 @@ impl Names { } /// A face's name before pieces are told apart. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] struct Named { name: String, aliases: Vec, + synonyms: Vec, verified: bool, /// What it came from (`None`: not known): faces with one name but different origins (an /// extrude's two caps both above its sketch plane) are numbered in this order. @@ -96,7 +105,7 @@ pub(crate) fn derive(b: &ModelBody, o: &NamingOrigin, lineage: &Lineage) -> Opti let geometric = crate::naming::geometric_names(b, o, named.len()); for (slot, name) in named.iter_mut().zip(geometric) { if slot.is_none() { - *slot = Some(Named { name: crate::naming::strip_piece(&name).to_string(), aliases: Vec::new(), verified: false, origins: None }); + *slot = Some(Named { name: crate::naming::strip_piece(&name).to_string(), verified: false, ..Named::default() }); } } } @@ -161,35 +170,42 @@ impl<'a> OperandNames<'a> { fn face(&self, face: usize, fid: u64) -> Option { let given = |names: &Names| { let info = names.info.get(face)?; - Some(Named { name: names.faces.get(face)?.clone(), aliases: info.aliases.clone(), verified: info.verified, origins: None }) + Some(Named { + name: names.faces.get(face)?.clone(), + aliases: info.aliases.clone(), + synonyms: info.synonyms.clone(), + verified: info.verified, + origins: None, + }) }; match self.operand { Operand::Body(_) | Operand::Stage(_) => given(&self.names), - Operand::Copy { instance, .. } => given(&self.names).map(|n| Named { - name: format!("{}@F{fid}.{instance}", n.name), - aliases: n.aliases.iter().map(|a| format!("{a}@F{fid}.{instance}")).collect(), - verified: n.verified, - origins: None, - }), - Operand::Inner(_) => given(&self.names).map(|n| Named { - name: format!("F{fid}:inner:{}", n.name), - aliases: Vec::new(), - verified: n.verified, - origins: None, + Operand::Copy { instance, .. } => given(&self.names).map(|n| { + let copied = |names: &[String]| names.iter().map(|a| format!("{a}@F{fid}.{instance}")).collect(); + Named { + name: format!("{}@F{fid}.{instance}", n.name), + aliases: copied(&n.aliases), + synonyms: copied(&n.synonyms), + verified: n.verified, + origins: None, + } }), + Operand::Inner(_) => { + given(&self.names).map(|n| Named { name: format!("F{fid}:inner:{}", n.name), verified: n.verified, ..Named::default() }) + } Operand::Made(roles) => { let (first, rest) = roles.get(face)?.split_first()?; Some(Named { name: format!("F{fid}:{first}"), - aliases: rest.iter().map(|r| format!("F{fid}:{r}")).collect(), + synonyms: rest.iter().map(|r| format!("F{fid}:{r}")).collect(), verified: true, - origins: None, + ..Named::default() }) } Operand::CopiedTool { roles, feature, instance } => { let named = |role: &String| format!("F{feature}:{role}@F{fid}.{instance}"); let (first, rest) = roles.get(face)?.split_first()?; - Some(Named { name: named(first), aliases: rest.iter().map(named).collect(), verified: true, origins: None }) + Some(Named { name: named(first), synonyms: rest.iter().map(named).collect(), verified: true, ..Named::default() }) } } } @@ -219,11 +235,11 @@ fn from_origins(face: &FaceProv, operands: &[OperandNames], fid: u64) -> Option< FaceOrigin::Face { operand, face } => operands.get(operand)?.face(face, fid)?, FaceOrigin::Edge { operand, edge } => { let (edge, verified) = operands.get(operand)?.edge(edge)?; - Named { name: format!("F{fid}:blend:{edge}"), aliases: Vec::new(), verified, origins: None } + Named { name: format!("F{fid}:blend:{edge}"), verified, ..Named::default() } } FaceOrigin::Offset { operand, face } => { let source = operands.get(operand)?.face(face, fid)?; - Named { name: format!("F{fid}:inner:{}", source.name), aliases: Vec::new(), verified: source.verified, origins: None } + Named { name: format!("F{fid}:inner:{}", source.name), verified: source.verified, ..Named::default() } } // A profile or cap of a body made from nothing: only a built body's own roles name // these, and those come in as `Made` operands. @@ -237,7 +253,8 @@ fn from_origins(face: &FaceProv, operands: &[OperandNames], fid: u64) -> Option< } /// One name for a face made of faces with these names: the face they are all pieces of, else the -/// first (the target's before a tool's); the others become aliases. +/// first (the target's before a tool's); the others become aliases. The synonyms of the face +/// whose name it takes stay its synonyms. fn merged(names: Vec) -> Option { let verified = names.iter().all(|n| n.verified); let first = names.first()?.name.clone(); @@ -249,15 +266,21 @@ fn merged(names: Vec) -> Option { common = crate::naming::parent_piece(c); } let name = common_piece(&names).or_else(|| common.map(str::to_string)).unwrap_or(first); - let mut aliases: Vec = Vec::new(); + let (mut aliases, mut synonyms): (Vec, Vec) = (Vec::new(), Vec::new()); for n in names { - for alias in std::iter::once(n.name).chain(n.aliases) { + let (kept, merged) = if n.name == name { (n.synonyms, n.aliases) } else { (Vec::new(), [vec![n.name], n.synonyms, n.aliases].concat()) }; + for synonym in kept { + if synonym != name && !synonyms.contains(&synonym) { + synonyms.push(synonym); + } + } + for alias in merged { if alias != name && !aliases.contains(&alias) { aliases.push(alias); } } } - Some(Named { name, aliases, verified, origins: None }) + Some(Named { name, aliases, synonyms, verified, origins: None }) } /// The name the faces have in common: their stem, the faces their qualifiers share and the @@ -441,7 +464,12 @@ fn qualify_at(named: Vec, adjacent: &[(usize, usize)], centres: Option<&d } } } - let info = named.into_iter().zip(bounds).zip(verified).map(|((x, bounds), verified)| FaceInfo { aliases: x.aliases, bounds, verified }).collect(); + let info = named + .into_iter() + .zip(bounds) + .zip(verified) + .map(|((x, bounds), verified)| FaceInfo { aliases: x.aliases, synonyms: x.synonyms, bounds, verified }) + .collect(); Names { faces: Arc::new(names), info } } @@ -526,6 +554,10 @@ pub(crate) fn matches(names: &Names, index: usize, name: &str) -> Option if current == name { return Some(Match::Exact); } + // Another name of this very face; of a piece of it, when the face was split since. + if info.is_some_and(|i| i.synonyms.iter().any(|a| a == name)) { + return Some(if crate::naming::strip_piece(current) == current { Match::Exact } else { Match::Piece }); + } if info.is_some_and(|i| i.aliases.iter().any(|a| a == name)) { return Some(Match::Alias); } diff --git a/crates/doc/src/history_names_tests.rs b/crates/doc/src/history_names_tests.rs index 40972a26f..b9bbaaba0 100644 --- a/crates/doc/src/history_names_tests.rs +++ b/crates/doc/src/history_names_tests.rs @@ -23,7 +23,7 @@ fn piece_names_parse_into_stem_and_bounding_faces() { } fn named(names: &[&str]) -> Vec { - names.iter().map(|n| Named { name: n.to_string(), aliases: Vec::new(), verified: true, origins: None }).collect() + names.iter().map(|n| Named { name: n.to_string(), verified: true, ..Named::default() }).collect() } #[test] @@ -125,6 +125,28 @@ fn a_merged_face_takes_the_shared_stem_or_the_first_name_and_answers_to_the_othe assert_eq!(matches(&names, 0, "F9:top"), Some(Match::Alias)); } +/// A side drawn in two collinear pieces is one face its feature made from both: each piece's role +/// names that very face, a piece of it once it is split. Joined with another feature's face, it +/// keeps them, and the other face's names are aliases only. +#[test] +fn a_face_made_from_several_roles_is_named_by_each_and_keeps_them_when_merged() { + let side = Named { name: "F2:side:c1".into(), synonyms: vec!["F2:side:c2".into()], verified: true, ..Named::default() }; + let names = qualify(vec![side.clone()], &[]); + assert_eq!(names.faces[0], "F2:side:c1"); + assert_eq!(matches(&names, 0, "F2:side:c2"), Some(Match::Exact)); + let other = Named { name: "F9:side:a".into(), synonyms: vec!["F9:side:b".into()], verified: true, ..Named::default() }; + let m = merged(vec![side.clone(), other]).unwrap(); + assert_eq!((m.name.as_str(), m.synonyms.as_slice()), ("F2:side:c1", ["F2:side:c2".to_string()].as_slice())); + assert_eq!(m.aliases, vec!["F9:side:a".to_string(), "F9:side:b".to_string()]); + let names = qualify(vec![m], &[]); + assert_eq!(matches(&names, 0, "F2:side:c2"), Some(Match::Exact)); + assert_eq!(matches(&names, 0, "F9:side:b"), Some(Match::Alias)); + // Split by a cut: each piece is a piece of what either role names. + let names = qualify(vec![side.clone(), side, Named { name: "F4:side:x".into(), ..Named::default() }], &[(0, 2)]); + assert_eq!(names.faces[0], "F2:side:c1#[F4:side:x]"); + assert_eq!(matches(&names, 0, "F2:side:c2"), Some(Match::Piece)); +} + /// #3330: a linked design's faces are named after the names that design gave them, so what the /// name holds must mean nothing else in the assembly, while its pieces stay pieces. #[test] diff --git a/crates/doc/src/hole_reference.rs b/crates/doc/src/hole_reference.rs index 9241104f1..ff77ff1d1 100644 --- a/crates/doc/src/hole_reference.rs +++ b/crates/doc/src/hole_reference.rs @@ -3,7 +3,9 @@ //! measured in the face's plane. The edges are found again by their persistent names, else by //! their stored points, so the hole follows them when the part changes. -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; +use solidcraft_geom::prelude::*; use crate::{DocError, ModelBody, ModelState, Result}; @@ -175,12 +177,16 @@ fn to_polyline(p: Vec3, e: &[Vec3]) -> f64 { e.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min) } -/// Reference edge `k` (its ends, and its index in the mesh), found by `name`, else by the edge -/// nearest `p`: one that runs through `p` for a fresh pick, within a quarter of the body for a -/// stored one. It must be straight. +/// Reference edge `k` (its ends, and its index in the mesh), found by `name` (a name that finds +/// no edge fails, asking for the edge to be picked again), else by the edge nearest `p`: one +/// that runs through `p` for a fresh pick, within a quarter of the body for a stored one. It +/// must be straight. fn find_edge(b: &ModelBody, m: &Mesh, k: usize, p: Vec3, name: Option<&str>, exact: bool) -> Result<(Vec3, Vec3, usize)> { let size = b.body.size().max(1e-9); - let by_name = name.filter(|n| !n.is_empty()).and_then(|n| crate::naming::locate_edge(b, n, p).ok()).map(|hit| hit.edge); + let by_name = match name.filter(|n| !n.is_empty()) { + Some(n) => Some(crate::naming::locate_edge(b, n, p).map_err(|_| DocError::reselect(n))?.edge), + None => None, + }; let i = match by_name { Some(i) => i, None => { diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index 16a62a9b7..01ad85485 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -14,10 +14,12 @@ //! linkage, a slider-crank) are met by moving the values of the other joints around the loop; //! those that still disagree are reported. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Aabb3; use solidcraft_sketch::linalg; @@ -1184,7 +1186,8 @@ impl Placements<'_, '_, '_> { } /// Values the loop solver moves at most in one group of loops, and loop-closing joints it takes -/// on at most: larger ones are only checked. +/// on at most: larger ones are only checked (a group with more values moves only those of its +/// loops that need to move, `moving_loops_values`). const MAX_LOOP_VALUES: usize = 64; const MAX_LOOPS: usize = 100; /// Loop-closing joints one solve takes on at most, over all its groups: a part placed by several @@ -1328,19 +1331,7 @@ type Group = (Vec, BTreeSet, BTreeSet<(u64, usize)>); fn loop_groups(tree: &Tree, closing: &[u64], asm: &Assembly, linked: &BTreeSet<(u64, usize)>) -> Vec { let mut groups: Vec = Vec::new(); for id in closing { - let Some(j) = tree.joints.get(id) else { continue }; - // A joint between an occurrence and itself (only a hand-edited file has one) is only checked. - if j.a.occurrence == j.b.occurrence { - continue; - } - let side = |occ: u64| -> BTreeSet { tree.path(occ).1.iter().map(|(k, _)| *k).collect() }; - let mut around: BTreeSet = side(j.a.occurrence).symmetric_difference(&side(j.b.occurrence)).copied().collect(); - around.insert(*id); - // The values the loop depends on: its joints' and those its links read. Loops tie together - // through a shared value only (a rigid joint on both paths has none; two values of one - // joint can feed two independent loops). - let mut touches = link_chains(asm, tree, &around, linked).0; - touches.extend(around.iter().filter_map(|id| tree.joints.get(id)).flat_map(|j| (0..j.kind.dofs().len()).map(|i| (j.id, i)))); + let Some((mut around, mut touches)) = one_loop(tree, *id, asm, linked) else { continue }; let mut members = vec![*id]; groups.retain(|(c, a, t)| { if t.is_disjoint(&touches) { @@ -1356,6 +1347,79 @@ fn loop_groups(tree: &Tree, closing: &[u64], asm: &Assembly, linked: &BTreeSet<( groups } +/// One loop: the closing joint `id` and the joints on the tree paths between its sides, and the +/// values it depends on (its joints' and those its links read). Loops tie together through a +/// shared value only (a rigid joint on both paths has none; two values of one joint can feed two +/// independent loops). None for a joint between an occurrence and itself (only a hand-edited file +/// has one), which is only checked. +fn one_loop(tree: &Tree, id: u64, asm: &Assembly, linked: &BTreeSet<(u64, usize)>) -> Option<(BTreeSet, BTreeSet<(u64, usize)>)> { + let j = tree.joints.get(&id)?; + if j.a.occurrence == j.b.occurrence { + return None; + } + let side = |occ: u64| -> BTreeSet { tree.path(occ).1.iter().map(|(k, _)| *k).collect() }; + let mut around: BTreeSet = side(j.a.occurrence).symmetric_difference(&side(j.b.occurrence)).copied().collect(); + around.insert(id); + let mut touches = link_chains(asm, tree, &around, linked).0; + touches.extend(around.iter().filter_map(|id| tree.joints.get(id)).flat_map(|j| (0..j.kind.dofs().len()).map(|i| (j.id, i)))); + Some((around, touches)) +} + +/// The values to move in a group of loops with more than the solver moves at once (a frame of +/// profiles held by many planar joints, #9687): those of the loops that need to move, open at the +/// start (beyond what the conflict check lets pass) or reading a held value that moves, and the +/// closing joints' of the closed loops those values move, when they are few enough. Every loop of +/// the group is still kept closed. None when no loop needs to move, or those that do have too +/// many values themselves. A solve that needs other values of a closed loop (one whose closing +/// joint is rigid) is not found: that group stays a conflict, as a group this size was before. +fn moving_loops_values( + tree: &Tree, + closing: &[u64], + moves: &[(u64, usize, f64, f64)], + asm: &Assembly, + held: &Held, + linked: &BTreeSet<(u64, usize)>, + vals: &Values, + scale: f64, +) -> Option> { + let moved: BTreeSet<(u64, usize)> = moves.iter().map(|(id, i, ..)| (*id, *i)).collect(); + let mut gaps = Vec::with_capacity(closing.len() * 9); + closure_gaps(&mut PlacementWorkspace::new(tree), closing, vals, scale, &mut gaps)?; + let loose = loose_gap(scale); + let (mut around, mut others) = (BTreeSet::new(), Vec::new()); + for (id, gap) in closing.iter().zip(gaps.chunks(9)) { + let Some((joints, touches)) = one_loop(tree, *id, asm, linked) else { continue }; + if largest(gap) > loose || !touches.is_disjoint(&moved) { + around.extend(joints); + } else { + others.push((*id, touches)); + } + } + let mut vars = unknowns(tree, &around, asm, linked, held); + if vars.is_empty() { + return None; + } + // A closed loop through a value that moves stays closed by its own closing joint's values + // (a part slid on one planar joint slides on its second): they are on no tree path, so no other + // loop runs through them, but a motion link setting one moves the value its chain starts from, + // and the loops through that follow the same way. + while vars.len() <= MAX_LOOP_VALUES { + let moving: BTreeSet<(u64, usize)> = vars.iter().copied().collect(); + let follow: BTreeSet = others.iter().filter(|(_, touches)| !touches.is_disjoint(&moving)).map(|(id, _)| *id).collect(); + others.retain(|(id, _)| !follow.contains(id)); + let before = vars.len(); + for v in unknowns(tree, &follow, asm, linked, held) { + if !vars.contains(&v) { + vars.push(v); + } + } + if vars.len() == before { + break; + } + } + (vars.len() <= MAX_LOOP_VALUES).then_some(vars) +} + /// The values a solve of the loops `around` moves: every value of their joints but the `held` /// ones and motion-link targets, and the values the targets' link chains start from. fn unknowns(tree: &Tree, around: &BTreeSet, asm: &Assembly, linked: &BTreeSet<(u64, usize)>, held: &Held) -> Vec<(u64, usize)> { @@ -1655,12 +1719,16 @@ fn close_group( spent: &std::cell::Cell, vals: &mut Values, ) -> Option> { - let vars = unknowns(tree, around, asm, linked, held); + let scale = loop_scale(tree, around, vals); + let mut vars = unknowns(tree, around, asm, linked, held); if vars.len() > MAX_LOOP_VALUES { - return Some(BTreeMap::new()); + // Too many to move at once: only the loops that need to move, or none. + match moving_loops_values(tree, closing, moves, asm, held, linked, vals, scale) { + Some(few) => vars = few, + None => return Some(BTreeMap::new()), + } } let bounds = limit_bounds(tree, &vars); - let scale = loop_scale(tree, around, vals); // Closer than the conflict check needs: 1e-7 mm, and turns of 1e-10 rad across the loop. let tol = (1e-10 * scale).min(1e-7); // The values with the held ones `t` of the way along (and the unknowns at `x`). @@ -1912,6 +1980,15 @@ pub fn solve_holding_with_analysis(doc: &Document, st: &ModelState, held: &Held, dof.clear(); } placed.remove(&0); + // A placement that is not a rigid motion within range (values that ran off to infinity, say) + // is not applied: the joints placing that occurrence report it. + let bad: Vec = placed.iter().filter(|(_, m)| !crate::is_placement(m)).map(|(occ, _)| *occ).collect(); + for occ in bad { + placed.remove(&occ); + for j in asm.joints.iter().filter(|j| !j.suppressed && (j.a.occurrence == occ || j.b.occurrence == occ)) { + sol.errors.push((j.id, j.name.clone(), format!("it would place occurrence {occ} outside a rigid placement within 1e9 mm"))); + } + } sol.world = placed; sol.dof = dof; sol diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rs index f072037fa..df899e5e1 100644 --- a/crates/doc/src/joints_cam.rs +++ b/crates/doc/src/joints_cam.rs @@ -12,10 +12,12 @@ //! oscillating one from its arm pointing away from the cam's axis) and stops where it first //! touches the profile: the follower stays in contact, as a spring would hold it. +use solidcraft_geom::prelude::*; use std::f64::consts::TAU; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Aabb2, Aabb3, Ring, Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; +use solidcraft_geom::{Aabb2, Aabb3, Ring}; use super::{JointKind, JointOrigin, MotionLink, Size, component_bodies, component_of, flip_of, occurrence_world, size_of}; use crate::{DocError, Document, IDENTITY, Mat, ModelState, Result, apply_point, apply_vector, mat_inverse, mat_mul}; @@ -322,8 +324,10 @@ fn profile_points(doc: &Document, st: &ModelState, p: &CamProfile, cam: &super:: } // Each body sampled to its own size (a large part beside the cam leaves the cam fine). // Each body's edges with the faces beside them. - let meshes: Vec = - bodies.iter().map(|b| b.body.tessellate(tolerance(b.body.size()))).collect::>()?; + let meshes: Vec = bodies + .iter() + .map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tolerance(b.body.size())))) + .collect::>()?; let edges: Vec<(usize, &Vec, &[u32])> = meshes .iter() .enumerate() @@ -339,7 +343,7 @@ fn profile_points(doc: &Document, st: &ModelState, p: &CamProfile, cam: &super:: let (body, p) = bodies .iter() .enumerate() - .find_map(|(i, b)| crate::naming::find_edge(b, name, *pick).ok().map(|(p, _)| (i, p))) + .find_map(|(i, b)| crate::naming::find_edge(b, name, *pick).ok().map(|p| (i, p))) .ok_or_else(|| bad(&format!("the edge `{name}` no longer exists (edit the cam to pick again)")))?; (on, at) = (Some(body), p); } @@ -484,7 +488,7 @@ pub fn sketch_profile<'a>(sk: &'a crate::SolvedSketch, curves: &[String]) -> Opt } /// A loop's polyline within `tol`, segment by segment: `None` past `MAX_PROFILE_POINTS` points. -fn sampled(lp: &solidcraft_geom::Loop2, tol: f64) -> Option> { +fn sampled(lp: &solidcore_record::Loop2, tol: f64) -> Option> { let mut out = Vec::new(); for seg in &lp.segs { let p = seg.polyline(tol); diff --git a/crates/doc/src/joints_edge.rs b/crates/doc/src/joints_edge.rs index 218489b3e..bb134e0d3 100644 --- a/crates/doc/src/joints_edge.rs +++ b/crates/doc/src/joints_edge.rs @@ -8,7 +8,8 @@ //! corner x and y run along the two edges, away from the corner into the face, in the order that //! makes the frame right-handed. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::{EdgeAxis, Snap, component_bodies, frame}; use crate::{DocError, Document, IDENTITY, Mat, ModelBody, ModelState, Result, apply_point, mat_inverse, mat_mul}; @@ -50,11 +51,11 @@ fn edge_index(b: &ModelBody, name: Option<&str>, pick: Vec3) -> Option { fn face_of(b: &ModelBody, i: usize, name: Option<&str>, pick: Vec3) -> Result<(usize, Vec3, Vec3)> { let m = b.mesh(); let beside: Vec = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default(); - let infos = b.body.faces(tol(b))?; + let infos = b.joint_faces()?; let planar = |f: usize| infos.iter().find(|x| x.index == f).and_then(|x| x.plane_normal.map(|n| (x.index, n, x.centroid, x.area))); let chosen = match name { Some(n) => { - let (f, _, _) = crate::naming::face_on_body(b, n, pick) + let (f, _) = crate::naming::face_on_body(b, n, pick) .ok_or_else(|| DocError::Invalid(format!("joint origin: the face `{n}` no longer exists (edit the joint to pick again)")))?; if !beside.contains(&f) { return Err(DocError::Invalid(format!("joint origin: the face `{n}` no longer meets its edge (edit the joint to pick again)"))); @@ -190,7 +191,7 @@ pub fn edge_snap(doc: &Document, st: &ModelState, comp: u64, pick: Vec3, on: Opt Some(p) => { let f = crate::naming::face_name_at_body(b, p) .and_then(|n| crate::naming::face_on_body(b, &n, p)) - .map(|(f, _, _)| f) + .map(|(f, _)| f) .ok_or_else(|| DocError::Invalid("joint origin: `on` is not on a face of that body".into()))?; if !beside.contains(&f) { return Err(DocError::Invalid("joint origin: `on` picks a face the edge doesn't bound".into())); diff --git a/crates/doc/src/joints_face.rs b/crates/doc/src/joints_face.rs index 18da16b76..fc9d41af9 100644 --- a/crates/doc/src/joints_face.rs +++ b/crates/doc/src/joints_face.rs @@ -4,9 +4,11 @@ //! A round origin's end is kept by the name of the face across the rim at that end, so it is the //! same end after the design changes; an x reference keeps the origin's turn about its axis. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; -use solidcraft_geom::{Loop2, Mesh, Plane, Ring, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Vec2, Vec3}; +use solidcraft_geom::{Mesh, Ring}; use solidcraft_kernel::CylinderFace; use super::{Snap, XRef, component_bodies}; @@ -32,17 +34,16 @@ fn gone(name: &str) -> DocError { /// The face called `name` on the bodies of `component` nearest `pick` (an error when it is gone: /// a joint must not quietly attach elsewhere). Each body is looked at in its own coordinates, and -/// a face the name finds exactly comes before a piece of it or a face it was merged into. Only the -/// component's own bodies: the parts of one STEP import share their face names, and another +/// the nearest of the faces the name finds is taken. Only the component's own bodies: the parts of one STEP import share their face names, and another /// part's face of that name can lie nearer the pick than this part's own. pub(super) fn named_face<'a>(doc: &Document, st: &'a ModelState, component: u64, pick: Vec3, name: &str) -> Result> { let own = component_bodies(doc, st, component).into_iter().filter_map(|body| { let offset = doc.model_body_offset(body).copied().unwrap_or(IDENTITY); - let (face, at, inexact) = crate::naming::face_on_body(body, name, apply_point(&mat_inverse(&offset)?, pick))?; + let (face, at) = crate::naming::face_on_body(body, name, apply_point(&mat_inverse(&offset)?, pick))?; let point = apply_point(&offset, at); - Some(((inexact, point.dist(pick)), NamedFace { body, face, point, offset })) + Some((point.dist(pick), NamedFace { body, face, point, offset })) }); - if let Some((_, nf)) = own.min_by(|(a, _), (b, _)| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))) { + if let Some((_, nf)) = own.min_by(|(a, _), (b, _)| a.total_cmp(b)) { return Ok(nf); } // On none of them (the face's body has gone to another component since): wherever the name @@ -53,7 +54,7 @@ pub(super) fn named_face<'a>(doc: &Document, st: &'a ModelState, component: u64, return Ok(NamedFace { body, face: hit.face, point: hit.point, offset: IDENTITY }); }; let inv = mat_inverse(&offset).ok_or_else(|| gone(name))?; - let (face, at, _) = crate::naming::face_on_body(body, name, apply_point(&inv, pick)).ok_or_else(|| gone(name))?; + let (face, at) = crate::naming::face_on_body(body, name, apply_point(&inv, pick)).ok_or_else(|| gone(name))?; Ok(NamedFace { body, face, point: apply_point(&offset, at), offset }) } diff --git a/crates/doc/src/joints_handles.rs b/crates/doc/src/joints_handles.rs index 6cc267e78..a9a3dc29a 100644 --- a/crates/doc/src/joints_handles.rs +++ b/crates/doc/src/joints_handles.rs @@ -1,10 +1,11 @@ //! The instantaneous motion a joint value gives a selected occurrence. Probe the same //! placement graph and loop solver as a drive, including reversed joints and motion links. +use solidcraft_geom::prelude::*; use std::collections::BTreeSet; use super::{Analysis, Held, MAX_LOOP_VALUES, Solution, apply_links, build, joint_values, link_chains, solve_holding_with_analysis}; use crate::{Document, Mat, ModelState, apply_point, apply_vector, mat_inverse, mat_mul}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; /// A driveable value, expressed as an axis of the selected occurrence in world coordinates. #[derive(Clone, Debug)] diff --git a/crates/doc/src/joints_reach.rs b/crates/doc/src/joints_reach.rs index 7e87749e3..f74f903f8 100644 --- a/crates/doc/src/joints_reach.rs +++ b/crates/doc/src/joints_reach.rs @@ -2,10 +2,11 @@ //! point of it reaches a target (and an axis of it points a given way), every value within its //! limits, motion links followed, and the closed loops those values are in kept closed. +use solidcraft_geom::prelude::*; use std::cell::Cell; use std::collections::BTreeSet; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_sketch::linalg; use super::{ diff --git a/crates/doc/src/joints_relations.rs b/crates/doc/src/joints_relations.rs index cd3f5fe0f..1b8ffb77b 100644 --- a/crates/doc/src/joints_relations.rs +++ b/crates/doc/src/joints_relations.rs @@ -16,14 +16,11 @@ const TURNS: [f64; 4] = [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, /// Starts tried at most (angle values beyond the first three start at 0). const MAX_STARTS: usize = 64; -/// The values of relation `j` that move B least from where it is now: B's joint frame as it sits -/// in A's, met as nearly as the relation allows (its origin as near as it can be to where it is, -/// and its axes, each weighed as a point a part's size along it). `None` for a joint that is not a relation, or whose -/// origins can't be found. +/// The values of joint `j` that move B least from where it is now: B's joint frame as it sits +/// in A's, met as nearly as the joint allows (its origin as near as it can be to where it is, +/// and its axes, each weighed as a point a part's size along it). Used for relations and for +/// typed joints that close a loop. `None` when the origins or finite values can't be found. pub fn relation_values(doc: &Document, st: &ModelState, j: &Joint) -> Option> { - if !j.kind.is_relation() { - return None; - } let world = |occ: u64| if occ == 0 { IDENTITY } else { occurrence_world(doc, occ) }; let fa = mat_mul(&world(j.a.occurrence), &resolve_origin(doc, st, &j.a).ok()?); let fb = mat_mul(&world(j.b.occurrence), &resolve_origin(doc, st, &j.b).ok()?); @@ -79,7 +76,7 @@ mod tests { #![allow(clippy::unwrap_used)] use super::*; use crate::joints::{JointKind, JointOrigin, Snap}; - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; fn joint(kind: JointKind) -> Joint { let at = |occurrence| JointOrigin { occurrence, snap: Snap::Point { point: Vec3::ZERO, z: None, x: None } }; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 0123c4bac..729fb7275 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -11,6 +11,7 @@ mod assembly; mod body_transfer; mod body_transfer_sheet; pub mod bom; +mod browser_tree; pub mod pbr_appearance; pub use body_transfer::{valid_transfer_matrix, validate_body_transfer}; pub mod canvas; @@ -54,15 +55,22 @@ pub mod persistent_name; pub mod physical_material; mod piece_names; pub mod pipe_thread_catalog; +pub mod pipe_thread_sizes; pub mod point_cloud; +mod point_cloud_complex; +pub mod point_cloud_distribution; mod points; mod profile_refs; pub mod progress; mod thread_catalog; -pub use thread_catalog::{TappedThread, TappedThreadFamily, parse_tapped_thread, tapped_thread_sizes}; +pub use thread_catalog::{ + DRILL_ALLOWANCE, TaperDrill, TappedThread, TappedThreadFamily, metric_tap_drill, parse_tapped_thread, tapped_thread_sizes, untabulated_taper_tap, +}; mod walk; pub use profile_refs::{capture_profile_selection, profile_fallback_notes, profile_selection_indices, profile_selection_indices_lenient}; pub mod plastic; +mod print_face; +pub use print_face::PrintFace; pub mod project; mod project3d; pub mod render_aging; @@ -71,22 +79,23 @@ pub mod render_optics; pub mod render_resources; pub mod render_settings; pub mod render_surface; -pub use project3d::iso_grid; pub mod sheet; pub mod sketch_equation; pub mod text_params; +pub mod thread_forms; pub use assembly::{ - BomType, IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, WorldNames, apply_point, apply_vector, is_identity, map_plane, - map_point_expr, map_vector_expr, mat_inverse, mat_mul, mat_volume_scale, rigid, + BomType, IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, WorldNames, apply_point, apply_vector, is_identity, is_placement, + map_plane, map_point_expr, map_vector_expr, mat_inverse, mat_mul, mat_volume_scale, rigid, }; pub use document::*; pub use eval::{ - EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error, - edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, join_pieces_added, map_wire, - metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, - sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance, - world_state, world_state_reusing, + EdgeRef, FeatureResult, KeptSeparate, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, + blend_target, curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, + hole_on_surface, import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, + revolve_extent, revolve_extent_for_handle, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, + state_in_frame, state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, world_state, + world_state_reusing, }; pub use eval::{EvalCache, KeptResults}; pub use expr::Expr; @@ -108,6 +117,41 @@ pub enum DocError { Sketch(#[from] solidcraft_sketch::SketchError), #[error(transparent)] Kernel(#[from] solidcraft_kernel::KernelError), + /// A stored reference (a face or edge name, a piece of a split face) no longer finds exactly + /// what it named: the feature using it fails, and the user picks it again. `feature` is + /// empty until the evaluation of the feature fills it in ([`DocError::in_feature`]). + #[error("{}", reselect_message(feature, reference))] + Reselect { feature: String, reference: String }, +} + +impl DocError { + /// A feature's `reference` that no longer finds what it named ([`DocError::Reselect`]), for + /// the feature being evaluated. + pub fn reselect(reference: impl Into) -> Self { + DocError::Reselect { feature: String::new(), reference: reference.into() } + } + + /// This error, raised while feature `feature` was evaluated: a [`DocError::Reselect`] names it. + pub fn in_feature(self, feature: &str) -> Self { + match self { + DocError::Reselect { feature: f, reference } if f.is_empty() => DocError::Reselect { feature: feature.into(), reference }, + other => other, + } + } +} + +/// What a feature that lost a reference says ([`DocError::Reselect`]). +fn reselect_message(feature: &str, reference: &str) -> String { + let feature = if feature.is_empty() { "this feature" } else { feature }; + format!("{feature}: the reference `{reference}` no longer exists as it was picked; reselect it") +} + +/// The feature and the reference of a [`DocError::Reselect`] message, read back from its text +/// (a feature's error is kept as text): `None` for any other message. +pub fn reselect_parts(text: &str) -> Option<(&str, &str)> { + let (feature, rest) = text.split_once(": the reference `")?; + let reference = rest.strip_suffix("` no longer exists as it was picked; reselect it")?; + Some((feature, reference)) } pub type Result = std::result::Result; diff --git a/crates/doc/src/lineage.rs b/crates/doc/src/lineage.rs index 169d541e8..386e1c333 100644 --- a/crates/doc/src/lineage.rs +++ b/crates/doc/src/lineage.rs @@ -9,11 +9,12 @@ //! bodies the feature built itself (whose faces are named by their role: the sketch curve they //! sweep, the cap they are). Naming (`history_names`) reads it; nothing here samples geometry. +use solidcraft_geom::prelude::*; use std::sync::{Arc, OnceLock}; -use solidcraft_geom::Region2; +use solidcore_record::{Region2, Vec3}; use solidcraft_kernel::Body; -use solidcraft_kernel::history::{Change, FaceOrigin, FaceProv, History}; +use solidcraft_kernel::history::{BodyHistory, Change, FaceOrigin, FaceProv, History}; use crate::SolvedSketch; @@ -96,6 +97,24 @@ impl Lineage { Lineage { history: self.history.clone(), operands } } + /// Whether each face of the body this is the lineage of came, in whole or in part, from a + /// face or edge of `name`, a body of the model before the feature. + pub(crate) fn faces_from_body(&self, name: &str) -> Vec { + let from: Vec = self.operands.iter().map(|op| matches!(op.as_ref(), Operand::Body(n) if n == name)).collect(); + self.history + .faces + .iter() + .map(|face| { + face.origins.iter().any(|origin| match *origin { + FaceOrigin::Face { operand, .. } | FaceOrigin::Edge { operand, .. } | FaceOrigin::Offset { operand, .. } => { + from.get(operand) == Some(&true) + } + FaceOrigin::Profile { .. } | FaceOrigin::Cap { .. } => false, + }) + }) + .collect() + } + /// A tool of `faces` faces and no edges (a mesh's triangles) whose faces have no role. pub(crate) fn unnamed_faces(faces: usize) -> Lineage { let faces = (0..faces).map(|face| FaceProv { origins: vec![FaceOrigin::Face { operand: 0, face }], change: Change::Kept }).collect(); @@ -214,13 +233,16 @@ impl<'a> ProfileRoles<'a> { if history.operands != 0 { return None; } - let segments: Vec<&solidcraft_geom::Seg2> = + let segments: Vec<&solidcore_record::Seg2> = self.region.map(|r| std::iter::once(&r.outer).chain(&r.holes).flat_map(|l| &l.segs).collect()).unwrap_or_default(); let curves = self.sketch.map(crate::config::ExactSketchCurves::new); // Every curve the segment is drawn on (one, or several coincident or collinear ones). let curve = |segment: usize| -> Vec { let (Some(curves), Some(segment)) = (curves.as_ref(), segments.get(segment)) else { return Vec::new() }; - let drawn: Vec = curves.find_all_along(segment).into_iter().map(|id| format!("side:{id}")).collect(); + let mut drawn: Vec = curves.find_all_along(segment).into_iter().map(|id| format!("side:{id}")).collect(); + if drawn.is_empty() { + drawn.extend(curves.find_free_form(segment).map(|id| format!("side:{id}"))); + } match self.thin { // A thin wall's side beside its curve (the other side may lie on it). Some(thin) if drawn.is_empty() => curves.find_offset(segment, &thin.curves, thin.distances), @@ -276,7 +298,7 @@ impl<'a> ProfileRoles<'a> { /// numbered through the chains in order. It has no caps. pub(crate) struct ChainRoles<'a> { pub sketch: &'a SolvedSketch, - pub chains: &'a [Vec], + pub chains: &'a [Vec], } impl ChainRoles<'_> { @@ -287,7 +309,7 @@ impl ChainRoles<'_> { } fn of(&self, history: &History) -> Vec> { - let segments: Vec<&solidcraft_geom::Seg2> = self.chains.iter().flatten().collect(); + let segments: Vec<&solidcore_record::Seg2> = self.chains.iter().flatten().collect(); let curves = crate::config::ExactSketchCurves::new(self.sketch); history .faces @@ -318,7 +340,7 @@ impl ChainRoles<'_> { /// answering to the others; its caps `start` and `end`. pub(crate) struct SectionRoles<'a> { /// Each section's sketch and loops (outer, then holes), in the order given. - pub sections: Vec<(&'a SolvedSketch, Vec<&'a solidcraft_geom::Loop2>)>, + pub sections: Vec<(&'a SolvedSketch, Vec<&'a solidcore_record::Loop2>)>, } impl SectionRoles<'_> { @@ -550,6 +572,150 @@ impl crate::ModelBody { } } +/// The pieces feature `f` (saved before format 14) split a body into, named so the later +/// features of the design find them. Those builds named the pieces in truck's shell order, which +/// SMLib's need not follow, and a later feature names the piece it works on (`body`) and keeps +/// the points it picked on it: each name goes to the piece nearest the points the features +/// naming it picked. Pieces no later feature names keep the order they came in; so do all of +/// them where the picks do not tell the pieces apart. +pub(crate) fn order_legacy_lumps(bodies: &mut [crate::ModelBody], before: &crate::ModelState, doc: &crate::Document, f: &crate::Feature) { + for members in made_families(bodies, before) { + order_legacy_family(bodies, &members, doc, f); + } +} + +/// The families of [`lump_families`] the feature that left `bodies` after `before` made: a family +/// it left as it was keeps its names. +fn made_families(bodies: &[crate::ModelBody], before: &crate::ModelState) -> Vec> { + lump_families(bodies) + .into_iter() + .filter(|members| members.iter().filter_map(|i| bodies.get(*i)).any(|b| !before.bodies.iter().any(|o| o.body.same(&b.body)))) + .collect() +} + +/// What [`order_legacy_lumps`] named the pieces of `bodies` (the state feature `f` left after +/// `before`) by: a digest of each piece name with the points the later features of `doc` naming +/// it picked, 0 where `f` was saved since format 14 or split nothing. Those features come after +/// `f`, so the state is `f`'s only while this is the same: a script replays them after it, and +/// an edit may change what they pick or name. +pub(crate) fn legacy_picks_digest(bodies: &[crate::ModelBody], before: &crate::ModelState, doc: &crate::Document, f: &crate::Feature) -> u64 { + use std::hash::{Hash, Hasher}; + if !f.shell_piece_order { + return 0; + } + let families = made_families(bodies, before); + if families.is_empty() { + return 0; + } + let mut h = std::collections::hash_map::DefaultHasher::new(); + for members in families { + let mut names: Vec = members.iter().filter_map(|i| bodies.get(*i).map(|b| b.name.clone())).collect(); + names.sort(); + for (name, points) in names.iter().zip(later_picks(doc, f, &names)) { + name.hash(&mut h); + for p in points { + [p.x, p.y, p.z].map(f64::to_bits).hash(&mut h); + } + } + } + // 0 means "nothing named so"; a digest that happens to be 0 must not read as that. + h.finish().max(1) +} + +/// The pieces each body a feature cut in two or more came out as (the bodies whose lineage is +/// that one operand), as [`order_lumps`] finds them. +fn lump_families(bodies: &[crate::ModelBody]) -> Vec> { + let mut families: Vec<(*const Operand, Vec)> = Vec::new(); + for (i, b) in bodies.iter().enumerate() { + let Made::Traced(l) = &b.made else { continue }; + let [op] = l.operands.as_slice() else { continue }; + if !matches!(op.as_ref(), Operand::Stage(_)) { + continue; + } + let key = Arc::as_ptr(op); + match families.iter_mut().find(|(k, _)| *k == key) { + Some((_, members)) => members.push(i), + None => families.push((key, vec![i])), + } + } + families.into_iter().map(|(_, m)| m).filter(|m| m.len() > 1).collect() +} + +/// Per name of `names`: the points the features after `f` in `doc` that name that body picked +/// on it. +fn later_picks(doc: &crate::Document, f: &crate::Feature, names: &[String]) -> Vec> { + let later = doc.features.iter().skip_while(|g| g.id != f.id).skip(1); + let mut picks: Vec> = vec![Vec::new(); names.len()]; + for g in later { + let Ok(kind) = serde_json::to_value(&g.kind) else { continue }; + let Some(k) = kind.get("body").and_then(|b| b.as_str()).and_then(|b| names.iter().position(|n| n == b)) else { continue }; + for key in ["edges", "faces", "face", "position"] { + let point = |v: &serde_json::Value| -> Option { + let a = v.as_array().filter(|a| a.len() == 3)?; + Some(Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?)) + }; + let found: Vec = match kind.get(key) { + Some(v) => { + point(v).map(|p| vec![p]).unwrap_or_else(|| v.as_array().map(|a| a.iter().filter_map(point).collect()).unwrap_or_default()) + } + None => Vec::new(), + }; + if let Some(slot) = picks.get_mut(k) { + slot.extend(found); + } + } + } + picks +} + +fn order_legacy_family(bodies: &mut [crate::ModelBody], members: &[usize], doc: &crate::Document, f: &crate::Feature) { + if members.len() > 64 { + return; + } + let names: Vec = members.iter().filter_map(|i| bodies.get(*i).map(|b| b.name.clone())).collect(); + let picks = later_picks(doc, f, &names); + // How far piece `i` is from the points of name `k` (the mesh's nearest triangle). + let far = |piece: usize, pts: &[Vec3]| -> f64 { + let Some(b) = members.get(piece).and_then(|i| bodies.get(*i)) else { return f64::INFINITY }; + let m = b.mesh(); + pts.iter() + .map(|p| { + m.triangles + .iter() + .filter_map(|t| m.tri(t)) + .map(|[a, b, c]| solidcraft_geom::compare::closest_on_triangle(*p, a, b, c).dist(*p)) + .fold(f64::INFINITY, f64::min) + }) + .fold(0.0, f64::max) + }; + let mut order: Vec> = vec![None; names.len()]; + let mut taken = vec![false; members.len()]; + for (k, pts) in picks.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + let best = + (0..members.len()).filter(|i| !taken.get(*i).copied().unwrap_or(true)).map(|i| (far(i, pts), i)).min_by(|a, b| a.0.total_cmp(&b.0)); + let Some((d, i)) = best else { return }; + // Only a piece the points lie on: a pick off every piece tells nothing. + let size = members.get(i).and_then(|m| bodies.get(*m)).map_or(1.0, |b| b.body.size().max(1.0)); + if d > size * 1e-3 { + return; + } + if let (Some(o), Some(t)) = (order.get_mut(k), taken.get_mut(i)) { + *o = Some(i); + *t = true; + } + } + let mut free = (0..members.len()).filter(|i| !taken.get(*i).copied().unwrap_or(true)); + let order: Vec = order.into_iter().map(|o| o.or_else(|| free.next())).collect::>().unwrap_or_default(); + if order.len() != names.len() { + return; + } + for (name, piece) in names.into_iter().zip(order) { + if let Some(b) = members.get(piece).and_then(|i| bodies.get_mut(*i)) { + b.name = name; + } + } +} + /// Name the pieces a body fell into after their faces: of the bodies in `bodies` that are lumps /// of one body (made in the same step, from one stage), the one whose least face name sorts first /// takes the first of their body names, and so on. The kernel's shell order, which named them @@ -571,7 +737,12 @@ pub(crate) fn order_lumps(bodies: &mut [crate::ModelBody], origin: &Arc 1) { let feature = members.first().and_then(|i| bodies.get(*i)).map(|b| b.feature); - if members.iter().any(|i| bodies.get(*i).map(|b| b.feature) != feature) { + // A cut's pieces past the first belong to the cut itself (#10123), so its family spans + // two features: the piece that kept the body's name comes from the body's own feature + // and the rest from this feature. Any other mix is not a split's family: leave it be. + let same = members.iter().all(|i| bodies.get(*i).map(|b| b.feature) == feature); + let foreign = members.iter().filter(|i| bodies.get(**i).map(|b| b.feature) != Some(origin.feature.id)).count(); + if !same && foreign > 1 { continue; } let least = |b: &crate::ModelBody| { @@ -582,10 +753,23 @@ pub(crate) fn order_lumps(bodies: &mut [crate::ModelBody], origin: &Arc> = members.iter().map(|i| bodies.get(*i).and_then(least).map(|k| (k, *i))).collect(); let Some(mut keys) = keys else { continue }; keys.sort(); - let names: Vec = members.iter().filter_map(|i| bodies.get(*i).map(|b| b.name.clone())).collect(); - for (name, (_, i)) in names.into_iter().zip(keys) { - if let Some(b) = bodies.get_mut(i) { - b.name = name; + // A name moves with the feature it belongs to: in a cut's family the first name is the + // cut body's own feature's and the rest are the cut's, and `body.rename` stores a name in + // the `body_names` of the feature a body says made it (#10438). + let names: Vec<(String, u64)> = members.iter().filter_map(|i| bodies.get(*i).map(|b| (b.name.clone(), b.feature))).collect(); + // The pieces take the family's places in that order too, so the state lists them as + // their names run. The session pins a feature's body names in state order, and the next + // evaluation hands them out in this order: listed in the kernel's order, the pieces + // swapped names once the design was evaluated again from its pinned names (opened). + let moved: Vec = keys.iter().filter_map(|(_, i)| bodies.get(*i).cloned()).collect(); + if moved.len() != members.len() || names.len() != members.len() { + continue; + } + for ((mut b, (name, feature)), place) in moved.into_iter().zip(names).zip(&members) { + b.name = name; + b.feature = feature; + if let Some(slot) = bodies.get_mut(*place) { + *slot = b; } } } diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs index 71b1f4b63..7a1e9b3c8 100644 --- a/crates/doc/src/model_cache.rs +++ b/crates/doc/src/model_cache.rs @@ -22,24 +22,14 @@ pub struct SavedModel { /// Records refer to these at most. const MAX_ITEMS: usize = 1_000_000; -/// Bodies, sketches and sheet bodies all the states hold together, at most (a state is a list of clones). +/// Bodies, sketches, sheet bodies and sketch keys all the states hold together, at most (a state is +/// a list of clones). const MAX_HELD: usize = 50_000_000; /// Longest text a record holds (bytes). A feature's warning can quote every generated name of /// the edges it picked: 122,701 characters in one design, whose saved model was refused, so it /// evaluated again on every open (#8541). const MAX_TEXT: usize = 1 << 24; -/// A feature's boolean retries as saved. The kernel leaves `rejected` out when it is empty, and -/// the field has no default when read, so a saved model whose booleans retried was refused and -/// the design evaluated on every open (#5286): an absent list is an empty one. -fn saved_diagnostics(d: &Json) -> Result { - let mut d = d.clone(); - if let Some(fields) = d.as_object_mut() { - fields.entry("rejected").or_insert_with(|| json!([])); - } - serde_json::from_value(d).map_err(|_| bad("saved model: diagnostics")) -} - fn hex(v: u64) -> String { format!("{v:016x}") } @@ -48,13 +38,17 @@ fn unhex(v: &Json) -> Result { v.as_str().and_then(|s| u64::from_str_radix(s, 16).ok()).ok_or_else(|| bad("saved model: key")) } +/// A sketch-key set's list `key` (`set` or `drop`). +fn keys_list<'a>(set: &'a Json, key: &str) -> Result<&'a Vec> { + set.get(key).and_then(Json::as_array).filter(|l| l.len() <= MAX_ITEMS).ok_or_else(|| bad("saved model: sketch keys")) +} + fn bad(what: &str) -> DocError { DocError::Invalid(what.into()) } -/// A design whose stored face or edge names were saved before format 14 (marked -/// [`crate::naming::LEGACY_MARK`]) finds them through names worked out from geometry on demand, -/// which a saved model does not keep. +/// A design holding a face or edge name saved before format 14 (marked +/// [`crate::naming::LEGACY_MARK`]): it saves without a model. fn has_legacy_names(doc: &Document) -> bool { let mark = format!("\"{}", crate::naming::LEGACY_MARK); doc.features.iter().any(|f| match &f.kind { @@ -128,25 +122,54 @@ struct Writer { sheet_index: HashMap, states: Vec, state_index: HashMap, + /// Each kernel body's place in `bodies`, by its record. + body_index: HashMap, + /// The rounds that made bodies (`Body::rounds`): the body, the body they were made on (both + /// places in `bodies`), and the edges they rounded there with their radii. + rounds: Vec, + /// The states' sketch keys, each distinct map once, written as the changes from the set + /// written before it: every state used to repeat the whole map (one entry per solved sketch), + /// 85 % of a 5,484-feature design's records, which then did not fit the cache's manifest. + sketch_key_sets: Vec, + sketch_key_index: HashMap, usize>, + last_sketch_keys: Option<(BTreeMap, usize)>, } impl Writer { + /// The place of `keys` among the sketch-key sets, written the first time a state holds them + /// (as the changes from the set written last: a later state mostly adds a sketch or two). + fn sketch_key_set(&mut self, keys: &BTreeMap) -> usize { + if let Some(i) = self.sketch_key_index.get(keys) { + return *i; + } + let record = match &self.last_sketch_keys { + Some((base, at)) => { + let set: Vec = keys.iter().filter(|(f, k)| base.get(f) != Some(k)).map(|(f, k)| json!([f, hex(*k)])).collect(); + let drop: Vec = base.keys().filter(|f| !keys.contains_key(f)).copied().collect(); + json!({"base": at, "set": set, "drop": drop}) + } + None => json!({"set": keys.iter().map(|(f, k)| json!([f, hex(*k)])).collect::>(), "drop": []}), + }; + self.sketch_key_sets.push(record); + let i = self.sketch_key_sets.len() - 1; + self.sketch_key_index.insert(keys.clone(), i); + self.last_sketch_keys = Some((keys.clone(), i)); + i + } + fn names(&mut self, b: &ModelBody) -> usize { let id = b.names.id(); if let Some(i) = self.names_index.get(&id) { return *i; } let names = crate::naming::names(b); - let info: Vec = names.info.iter().map(|i| json!([i.aliases, i.bounds, i.verified])).collect(); + let info: Vec = names.info.iter().map(|i| json!([i.aliases, i.bounds, i.verified, i.synonyms])).collect(); self.names.push(json!({"faces": *names.faces, "info": info})); self.names_index.insert(id, self.names.len() - 1); self.names.len() - 1 } fn model_body(&mut self, b: &ModelBody) -> Option { - if b.body.is_mesh() { - return None; - } let key = BodyKey::of(b); if let Some(i) = self.model_body_index.get(&key) { return Some(*i); @@ -171,13 +194,41 @@ impl Writer { let faces: Vec = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect(); r["imported"] = json!({"color": look.color, "opacity": look.opacity, "faces": faces}); } - r["body"] = json!(self.bodies.len()); - self.bodies.push(b.body.clone()); + r["body"] = json!(self.body(&b.body)); self.model_bodies.push(r); self.model_body_index.insert(key, self.model_bodies.len() - 1); Some(self.model_bodies.len() - 1) } + /// The place of a model body's kernel body: its own (a placed copy shares its record with + /// the part's other copies, but not its display), with the bodies the rounds that made it + /// were made on, each written once though no state holds it: a later round at a corner where + /// they meet blends them again, in a model opened from the file as in one evaluated anew. + fn body(&mut self, body: &Body) -> usize { + let key = |b: &Body| std::ptr::from_ref(b.record()).addr(); + self.bodies.push(body.clone()); + let first = self.bodies.len() - 1; + self.body_index.entry(key(body)).or_insert(first); + let (mut at, mut of) = (body.clone(), first); + // Down the rounds, until a body made on one already written. + while let Some((before, edges)) = at.rounds().map(|(b, e)| (b.clone(), e.to_vec())) { + let (i, new) = match self.body_index.get(&key(&before)) { + Some(i) => (*i, false), + None => { + self.bodies.push(before.clone()); + self.body_index.insert(key(&before), self.bodies.len() - 1); + (self.bodies.len() - 1, true) + } + }; + self.rounds.push(json!({"body": of, "before": i, "edges": edges})); + if !new { + break; + } + (at, of) = (before, i); + } + first + } + fn sketch(&mut self, s: &Arc) -> Option { let id = Arc::as_ptr(s) as usize; if let Some(i) = self.sketch_index.get(&id) { @@ -193,11 +244,15 @@ impl Writer { } fn sheet(&mut self, sheet: &crate::sheet::SheetBody) -> Option { - let record = serde_json::to_value(sheet).ok()?; - let key = record.to_string(); + // Keyed by the sheet written as text, straight from the sheet: every state asks for each + // of its sheets, and building the record (a JSON tree) each time only to find it written + // already took most of a sheet-metal design's save (906 states, 300 sheets: 0.8 s). Two + // sheets are the same text exactly when they are the same record. + let key = serde_json::to_string(sheet).ok()?; if let Some(i) = self.sheet_index.get(&key) { return Some(*i); } + let record = serde_json::to_value(sheet).ok()?; self.sheets.push(record); self.sheet_index.insert(key, self.sheets.len() - 1); Some(self.sheets.len() - 1) @@ -216,7 +271,7 @@ impl Writer { "reserved_body_names": st.reserved_body_names.iter().collect::>(), "sheets": sheets, "construct": serde_json::to_value(&st.construct).ok()?, "threads": serde_json::to_value(&st.threads).ok()?, - "sketch_keys": st.sketch_keys.iter().map(|(f, k)| json!([f, hex(*k)])).collect::>(), + "sketch_key_set": self.sketch_key_set(&st.sketch_keys), "blend_edges": serde_json::to_value(&st.blend_edges).ok()?, "fitted": serde_json::to_value(&st.fitted).ok()?, "tapered": serde_json::to_value(&st.tapered).ok()?, }); @@ -228,7 +283,7 @@ impl Writer { impl Model { /// The model as a design file keeps it: `None` unless it is `doc`'s evaluation without an - /// error, holds no mesh bodies, and `doc` keeps no names saved before format 14. Works out + /// error and `doc` keeps no names saved before format 14. Works out /// the face names not asked for yet (a saved model keeps them as worked out). pub fn saved(&self, doc: &Document) -> Option { if self.results.is_empty() || self.results.iter().any(|r| r.error.is_some()) || !self.is_current(doc) || has_legacy_names(doc) { @@ -243,14 +298,15 @@ impl Model { if let Some(w) = &r.warning { f["warning"] = json!(w); } - if r.boolean_diagnostics != kernel::BooleanDiagnostics::default() { - f["diagnostics"] = serde_json::to_value(&r.boolean_diagnostics).map_err(|e| kernel::KernelError::Invalid(e.to_string()))?; + if let Some(report) = &r.import_report { + f["import_report"] = serde_json::to_value(report.as_ref()).map_err(|e| kernel::KernelError::Invalid(e.to_string()))?; } features.push(f); } + // The check mode the results were evaluated under: they are another mode's results. let records = json!({ "features": features, "states": w.states, "model_bodies": w.model_bodies, "names": w.names, "sketches": w.sketches, - "sheets": w.sheets, + "sheets": w.sheets, "validation": self.validation().id(), "rounds": w.rounds, "sketch_key_sets": w.sketch_key_sets, }); Ok(SavedModel { records, bodies: w.bodies }) }) @@ -261,7 +317,8 @@ impl Model { impl SavedModel { /// The states the records hold, every record checked. fn states(&self) -> Result>> { - let (records, bodies) = (&self.records, &self.bodies); + let bodies = &self.bodies_with_rounds()?; + let records = &self.records; let list = |key: &str| records.get(key).and_then(Json::as_array).filter(|l| l.len() <= MAX_ITEMS).ok_or_else(|| bad("saved model: list")); let index = |v: Option<&Json>, len: usize| { v.and_then(Json::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|i| *i < len).ok_or_else(|| bad("saved model: index")) @@ -272,12 +329,12 @@ impl SavedModel { let mut names = Vec::new(); for n in list("names")? { let faces: Vec = serde_json::from_value(parse(n.get("faces"))?).map_err(|_| bad("saved model: names"))?; - let info: Vec<(Vec, std::collections::BTreeSet, bool)> = + let info: Vec<(Vec, std::collections::BTreeSet, bool, Vec)> = serde_json::from_value(parse(n.get("info"))?).map_err(|_| bad("saved model: names"))?; if info.len() != faces.len() { return Err(bad("saved model: names")); } - let info = info.into_iter().map(|(aliases, bounds, verified)| FaceInfo { aliases, bounds, verified }).collect(); + let info = info.into_iter().map(|(aliases, bounds, verified, synonyms)| FaceInfo { aliases, synonyms, bounds, verified }).collect(); names.push(Arc::new(Names { faces: Arc::new(faces), info })); } let mut sketches = Vec::new(); @@ -331,9 +388,49 @@ impl SavedModel { for s in list("sheets")? { sheets.push(serde_json::from_value::(s.clone()).map_err(|_| bad("saved model: sheet"))?); } - let mut states = Vec::new(); + // The sketch-key sets, each the changes from an earlier one (`base`): a short record can + // stand for a large set, so what they hold counts towards MAX_HELD as they are built. + let mut key_sets: Vec> = Vec::new(); let mut held = 0usize; - for s in list("states")? { + for k in list("sketch_key_sets")? { + // A set is the changes from one before it. + let base = match k.get("base") { + Some(b) => Some(key_sets.get(index(Some(b), key_sets.len())?).ok_or_else(|| bad("saved model: sketch keys"))?), + None => None, + }; + let (drop, set) = (keys_list(k, "drop")?, keys_list(k, "set")?); + // Counted before the base is copied: at most what the set can hold. + held = held.saturating_add(base.map_or(0, BTreeMap::len)).saturating_add(set.len()); + if held > MAX_HELD { + return Err(bad("saved model: sketch keys")); + } + let mut keys = base.cloned().unwrap_or_default(); + for f in drop { + keys.remove(&f.as_u64().ok_or_else(|| bad("saved model: sketch keys"))?); + } + for e in set { + keys.insert(e.get(0).and_then(Json::as_u64).ok_or_else(|| bad("saved model: sketch keys"))?, unhex(e.get(1).unwrap_or(&Json::Null))?); + } + key_sets.push(keys); + } + let records = list("states")?; + // What every state holds, counted from its runs and its sketch-key set before any is + // built (a hostile file cannot make the states clone more than MAX_HELD items). + for s in records { + for key in ["bodies", "sketches"] { + for run in s.get(key).and_then(Json::as_array).ok_or_else(|| bad("saved model: state"))? { + held = held.saturating_add(run.get(1).and_then(Json::as_u64).and_then(|n| usize::try_from(n).ok()).unwrap_or(usize::MAX)); + } + } + held = held.saturating_add(s.get("sheets").and_then(Json::as_array).map_or(0, Vec::len)); + held = held.saturating_add(key_sets.get(index(s.get("sketch_key_set"), key_sets.len())?).map_or(0, BTreeMap::len)); + if held > MAX_HELD { + return Err(bad("saved model: states")); + } + } + // Each state is independent of the others once the records they share are read: built + // on threads (a 5,484-feature design spent 3.5 s building them one after another). + let built = kernel::map_on_threads(records, 16, |s: &Json| -> Result { // Runs of consecutive indices, each within the list it indexes. let ids = |key: &str, len: usize| -> Result> { let mut out = Vec::new(); @@ -349,12 +446,8 @@ impl SavedModel { }; let field = |key: &str| parse(s.get(key)); let invalid = |_| bad("saved model: state"); - let mut sketch_keys = BTreeMap::new(); - for k in s.get("sketch_keys").and_then(Json::as_array).ok_or_else(|| bad("saved model: state"))? { - sketch_keys - .insert(k.get(0).and_then(Json::as_u64).ok_or_else(|| bad("saved model: state"))?, unhex(k.get(1).unwrap_or(&Json::Null))?); - } - let st = ModelState { + let sketch_keys = key_sets.get(index(s.get("sketch_key_set"), key_sets.len())?).cloned().ok_or_else(|| bad("saved model: state"))?; + Ok(ModelState { frame_bodies: Default::default(), bodies: ids("bodies", model_bodies.len())?.into_iter().filter_map(|i| model_bodies.get(i).cloned()).collect(), sketches: ids("sketches", sketches.len())?.into_iter().filter_map(|i| sketches.get(i).cloned()).collect(), @@ -377,16 +470,67 @@ impl SavedModel { blend_edges: serde_json::from_value(field("blend_edges")?).map_err(invalid)?, fitted: serde_json::from_value(field("fitted")?).map_err(invalid)?, tapered: serde_json::from_value(field("tapered")?).map_err(invalid)?, - }; - held = held.saturating_add(st.bodies.len()).saturating_add(st.sketches.len()).saturating_add(st.sheets.len()); - if held > MAX_HELD { - return Err(bad("saved model: states")); - } - states.push(Arc::new(st)); - } + // A join's notice is for the evaluation that made it, not kept with the cache. + kept_separate: BTreeMap::new(), + // Not kept either: a saved model's states carry no lineage, so the check of a + // legacy split's picks (`lineage::legacy_picks_digest`) finds no pieces in them + // and takes them as the design's evaluation they were saved as. + legacy_picks: BTreeMap::new(), + }) + }); + let states = built.into_iter().map(|r| r.unwrap_or_else(|| Err(bad("saved model: state"))).map(Arc::new)).collect::>>()?; Ok(states) } + /// The kernel bodies with the rounds that made them ([`kernel::Body::rounds`]) as the records + /// list them, each body's before it is taken as another's body before its rounds. + fn bodies_with_rounds(&self) -> Result> { + let refused = || bad("saved model: rounds"); + let list = self.records.get("rounds").and_then(Json::as_array).filter(|l| l.len() <= self.bodies.len()).ok_or_else(refused)?; + let place = |v: Option<&Json>| v.and_then(Json::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|i| *i < self.bodies.len()); + // Per body, the body its rounds were made on and their edges. + let mut made: Vec)>> = vec![None; self.bodies.len()]; + for r in list { + let (body, before) = (place(r.get("body")).ok_or_else(refused)?, place(r.get("before")).ok_or_else(refused)?); + let edges: Vec<(usize, f64)> = serde_json::from_value(r.get("edges").cloned().ok_or_else(refused)?).map_err(|_| refused())?; + match made.get_mut(body) { + Some(slot @ None) => *slot = Some((before, edges)), + _ => return Err(refused()), + } + } + // Each body after the one its rounds were made on, down each chain once (a cycle is refused). + let mut bodies = self.bodies.clone(); + let (mut done, mut on_chain) = (vec![false; bodies.len()], vec![false; bodies.len()]); + for start in 0..bodies.len() { + let mut chain = Vec::new(); + let mut at = start; + while let Some(seen @ false) = done.get_mut(at) { + *seen = true; + chain.push(at); + if let Some(on) = on_chain.get_mut(at) { + *on = true; + } + match made.get(at).and_then(Option::as_ref) { + Some((before, _)) => at = *before, + None => break, + } + if on_chain.get(at).copied().unwrap_or(false) { + return Err(refused()); + } + } + for &k in chain.iter().rev() { + if let Some(on) = on_chain.get_mut(k) { + *on = false; + } + let Some(Some((before, edges))) = made.get(k) else { continue }; + let before = bodies.get(*before).cloned().ok_or_else(refused)?; + let body = bodies.get(k).cloned().ok_or_else(refused)?; + *bodies.get_mut(k).ok_or_else(refused)? = body.with_rounds_of(&before, edges.clone())?; + } + } + Ok(bodies) + } + /// The model's final state (what a picture of it shows), without checking that it is a /// document's evaluation. pub fn final_state(&self) -> Result> { @@ -432,6 +576,20 @@ impl SavedModel { let state_sketches = states.iter().map(|s| held(s, "sketches", sketches.len())).collect::>>()?; let body_of = model_bodies.iter().map(|r| at(r.get("body"), self.bodies.len())).collect::>>()?; let names_of = model_bodies.iter().map(|r| at(r.get("names"), names.len())).collect::>>()?; + // The body each body's rounds were made on: kept with it, though no kept state holds it. + let rounds = list("rounds")?; + let mut before_of = HashMap::new(); + for r in rounds { + before_of.insert(at(r.get("body"), self.bodies.len())?, at(r.get("before"), self.bodies.len())?); + } + // A kernel body and the bodies down its rounds (a cycle, refused on reading, ends it). + let with_before = |k: usize| -> Vec { + let mut out = vec![k]; + while let Some(b) = out.last().and_then(|k| before_of.get(k)).filter(|b| !out.contains(b)) { + out.push(*b); + } + out + }; // What each record takes in the file. let bytes = |list: &[Json]| list.iter().map(|r| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len().saturating_add(1))).collect::>(); let (state_bytes, body_bytes) = (bytes(states.as_slice()), bytes(model_bodies.as_slice())); @@ -457,7 +615,8 @@ impl SavedModel { let mut stored = std::collections::HashSet::new(); // The sheet bodies, each written once and named by place in the states: all kept. let sheets = list("sheets").cloned().unwrap_or_default(); - let mut used = bytes(sheets.as_slice()).iter().fold(0usize, |t, b| t.saturating_add(*b)); + let key_sets = list("sketch_key_sets").cloned().unwrap_or_default(); + let mut used = bytes(sheets.as_slice()).iter().chain(bytes(key_sets.as_slice()).iter()).fold(0usize, |t, b| t.saturating_add(*b)); for s in std::iter::once(last).chain(order) { let (mut adds, mut new_names, mut new_sketches) = (HashMap::new(), std::collections::HashSet::new(), std::collections::HashSet::new()); let mut records = *state_bytes.get(s)?; @@ -468,9 +627,11 @@ impl SavedModel { if names_used.get(n) == Some(&false) && new_names.insert(n) { records = records.saturating_add(*name_bytes.get(n)?); } - for &(piece, bytes) in pieces.get(*body_of.get(m)?)? { - if !stored.contains(&piece) { - adds.insert(piece, bytes); + for k in with_before(*body_of.get(m)?) { + for &(piece, bytes) in pieces.get(k)? { + if !stored.contains(&piece) { + adds.insert(piece, bytes); + } } } } @@ -500,7 +661,9 @@ impl SavedModel { // What the states kept refer to, numbered again in the order it had. let mut kernel_used = vec![false; self.bodies.len()]; for m in (0..model_bodies.len()).filter(|m| kept_bodies.get(*m) == Some(&true)) { - *kernel_used.get_mut(*body_of.get(m)?)? = true; + for k in with_before(*body_of.get(m)?) { + *kernel_used.get_mut(k)? = true; + } } let renumber = |used: &[bool]| -> Vec> { let mut next = 0; @@ -547,10 +710,25 @@ impl SavedModel { }; out_features.push(f); } - let records = json!({ + let mut out_rounds = Vec::new(); + for r in rounds { + let Some(body) = new(&new_kernel, at(r.get("body"), self.bodies.len())?) else { continue }; + let before = new(&new_kernel, at(r.get("before"), self.bodies.len())?)?; + let mut r = r.clone(); + let o = r.as_object_mut()?; + o.insert("body".into(), json!(body)); + o.insert("before".into(), json!(before)); + out_rounds.push(r); + } + let mut records = json!({ "features": out_features, "states": out_states, "model_bodies": out_bodies, "names": kept_of(names.as_slice(), &names_used), - "sketches": kept_of(sketches.as_slice(), &sketches_used), "sheets": sheets, + "sketches": kept_of(sketches.as_slice(), &sketches_used), "sheets": sheets, "rounds": out_rounds, "sketch_key_sets": key_sets, }); + // The check mode the results were evaluated under, as the model records it (a model + // that records none stays without one: adopting it is refused either way). + if let (Some(validation), Some(out)) = (self.records.get("validation"), records.as_object_mut()) { + out.insert("validation".into(), validation.clone()); + } let kept: Vec = (0..self.bodies.len()).filter(|i| kernel_used.get(*i) == Some(&true)).collect(); let bodies = kept.iter().filter_map(|i| self.bodies.get(*i).cloned()).collect(); Some((SavedModel { records, bodies }, kept, used)) @@ -560,8 +738,9 @@ impl SavedModel { impl Model { /// The model a design file kept for `doc` ([`Model::saved`]), taken as `doc`'s evaluation: /// every feature's result as saved, nothing evaluated but the features whose state the file - /// did not keep ([`SavedModel::thinned`]). Refused (an error) unless every feature's - /// fingerprint is the one `doc` gives it now, and every record is well formed. + /// did not keep ([`SavedModel::thinned`]), under the check mode it was evaluated in + /// ([`Model::validation`]). Refused (an error) unless every feature's fingerprint is the one + /// `doc` gives it now, and every record is well formed. pub fn adopt(doc: &Document, saved: &SavedModel) -> Result { let mut states = saved.states()?; let frame_bodies = Arc::new(std::sync::Mutex::new(FrameBodies::default())); @@ -575,13 +754,16 @@ impl Model { let text = |v: Option<&Json>| v.and_then(Json::as_str).filter(|s| s.len() <= MAX_TEXT).map(str::to_owned).ok_or_else(|| bad("saved model: text")); let features = records.get("features").and_then(Json::as_array).ok_or_else(|| bad("saved model: features"))?; + let validation = + records.get("validation").and_then(Json::as_str).and_then(kernel::Validation::parse).ok_or_else(|| bad("saved model: validation"))?; if features.len() != doc.features.len() { return Err(bad("saved model: features")); } let (vals, param_errors) = evaluation_values(doc); let step_digests = StepDigests::of(doc, &StepDigests::default()); let marker = doc.marker.unwrap_or(usize::MAX); - let ctx = context_digest(doc, &vals); + // As `evaluate` digests the context under the mode, so the next evaluation reuses these. + let ctx = context_digest(doc, &vals) ^ validation_digest(validation); let mut before = Arc::new(ModelState::default()); // Whether `before` is the state before the feature: one the file left out only stands in. let mut exact = true; @@ -604,11 +786,13 @@ impl Model { id: f.id, name: f.name.clone(), error: None, + internal: false, warning: r.get("warning").map(|w| text(Some(w))).transpose()?, - boolean_diagnostics: match r.get("diagnostics") { - Some(d) => saved_diagnostics(d)?, - None => Default::default(), - }, + import_report: r + .get("import_report") + .map(|v| serde_json::from_value::(v.clone()).map(Arc::new).map_err(|_| bad("saved model: import report"))) + .transpose()?, + repair: None, ms, skipped: r.get("skipped").and_then(Json::as_bool).ok_or_else(|| bad("saved model: skipped"))?, stale: false, @@ -622,7 +806,7 @@ impl Model { } results.push(result); } - let mut model = Model { results, param_errors, step_digests, context: ctx, frame_bodies, ..Model::default() }; + let mut model = Model { results, param_errors, step_digests, context: ctx, frame_bodies, validation, ..Model::default() }; let unkept = model.results.iter().filter(|r| r.unkept).count(); if unkept > 0 { // The features whose state the file did not keep, each evaluated again from the state @@ -646,7 +830,8 @@ impl Model { CachedEval { error: None, warning: r.warning.clone(), - boolean_diagnostics: r.boolean_diagnostics.clone(), + import_report: r.import_report.clone(), + repair: r.repair.clone(), ms: r.ms, bytes: r.state.retained_bytes(), state: r.state.clone(), diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 8d5dd8302..c4c342141 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -3,7 +3,7 @@ //! shown without changing the design). use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; /// The motion retained by an associative trace. Joint bounds keep their expressions, in /// command units (degrees or millimetres); studies are referenced by their stable identity. diff --git a/crates/doc/src/name_lookup.rs b/crates/doc/src/name_lookup.rs index ffd560349..d9c112a22 100644 --- a/crates/doc/src/name_lookup.rs +++ b/crates/doc/src/name_lookup.rs @@ -1,27 +1,31 @@ //! Finding a face or edge again by the name a feature stored for it. //! -//! The face with that name is the face; else the one face answering to it (a face merged into -//! it, or the named piece told apart by the faces around it, which still bound it); else, when -//! several faces are pieces of the named one, the piece nearest the reference's point, and the -//! feature says the face was split. Names saved before format 14 ([`LEGACY_MARK`]) are found -//! among the names geometry gives, as the builds that saved them found them. A face whose name -//! was worked out from geometry, found where the reference's point no longer lies, is reported: -//! only geometry decided. +//! The face with that name is the face (a face its feature made from several of its roles, a +//! side drawn in collinear pieces, has each as a name); else the one face answering to it as +//! exactly: the named piece told apart by the faces around it, which still bound it. Nothing +//! else is: when the named face was split into several pieces, when it was merged into another +//! face, when only a face of the same stem is left, when the name is on several bodies, or when +//! the name was saved before format 14 ([`LEGACY_MARK`]), the name finds nothing and the feature +//! that uses it fails, asking for the reference to be picked again +//! ([`crate::DocError::Reselect`]). A face whose name was worked out from geometry, found where +//! the reference's point no longer lies, is reported: only geometry decided. use std::sync::Arc; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; +use solidcraft_geom::prelude::*; use crate::history_names::{Match, Names}; -use crate::naming::{self, closest, edge_names, face_names, legacy_edge_names, legacy_face_names, strip_piece}; -use crate::piece_names::{strip_edge_number, strip_edge_piece}; +use crate::naming::{self, closest, edge_names, face_names, strip_piece}; +use crate::piece_names::strip_edge_number; use crate::{ModelBody, ModelState}; /// The mark on a name saved before format 14 (`?F2:top#2`). Those names were worked out from -/// geometry, and a few of them name a face that exact history names differently (a tube's outer -/// wall was named after the nearest sketch curve to its centre, its inner circle): such a name is -/// found again among the names that geometry gives today, as the build that saved it did, so an -/// older design evaluates as it was saved. Picking the face again stores its exact name. +/// geometry, and some of them name a face that exact history names differently (a tube's outer +/// wall was named after the nearest sketch curve to its centre, its inner circle): such a name +/// finds no face, and the feature using it asks for the face to be picked again, which stores +/// its exact name. pub const LEGACY_MARK: char = '?'; /// A name saved before format 14, without its mark (`None`: an exact name). @@ -36,15 +40,11 @@ pub struct EdgeHit { pub edge: usize, /// A point on the edge: the reference's own point when it lies on it, else the edge's middle. pub point: Vec3, - /// The named edge is not one edge any more: the piece nearest the point was taken. - pub split: bool, /// Whether the names of the faces it separates follow exact history (and the edge is not /// one of several between them, numbered by where they lie). pub verified: bool, /// Whether the reference's point still lies on the edge. pub on_point: bool, - /// The name was saved before format 14 and found as that build did ([`LEGACY_MARK`]). - pub legacy: bool, } /// A body's edge names and face names, worked out once for every edge name looked up on it. @@ -104,36 +104,50 @@ impl BodyEdges { } } -/// The edge of a body a stored edge name finds: the edge [`BodyEdges::matching`] gives, else the -/// piece of it nearest `near` (`split`). `Err` explains when there is none. +/// The edge of a body a stored edge name finds: the edge with that name; else the one edge +/// between the faces it names exactly (see [`exactly`]). `Err` explains when there is none: no +/// such edge, the named edge split into several, or a name saved before format 14. pub fn locate_edge(b: &ModelBody, name: &str, near: Vec3) -> Result { - if let Some(old) = legacy_name(name) { - return legacy_locate_edge(b, old, near).map_err(|_| format!("edge `{name}` no longer exists")); + if legacy_name(name).is_some() { + return Err(format!("edge `{name}` was named by a build before format 14")); } - let edges = BodyEdges::new(b); - let m = &edges.mesh; - let gone = || format!("edge `{name}` no longer exists"); - match edges.matching(name).ok_or_else(gone)? { - EdgeMatch::Edge(i) => { - let on = edge_near(b, m, i, near); - edge_mid(m, i) - .map(|p| EdgeHit { - edge: i, - point: if on { near } else { p }, - split: false, - verified: edges.verified(i), - on_point: on, - legacy: false, - }) - .ok_or_else(|| "edge".into()) - } - EdgeMatch::Pieces(cands) => cands - .iter() - .filter_map(|i| edge_mid(m, *i).map(|p| (p, *i))) - .min_by(|a, b| a.0.dist(near).total_cmp(&b.0.dist(near))) - .map(|(p, i)| EdgeHit { edge: i, point: p, split: true, verified: edges.verified(i), on_point: false, legacy: false }) - .ok_or_else(gone), + let m = b.mesh(); + let names = edge_names(b); + let faces = naming::names(b); + let mid = |i: usize| edge_mid(&m, i); + // Several edges between the same two faces are numbered by where they lie: not exact. + let verified = |i: usize| { + m.edge_faces.get(i).is_some_and(|fs| fs.iter().all(|f| faces.verified(*f as usize))) + && names.get(i).is_some_and(|n| strip_edge_number(n).len() == n.len()) + }; + let exact = |i: usize| -> Result { + let on = edge_near(b, &m, i, near); + mid(i).map(|p| EdgeHit { edge: i, point: if on { near } else { p }, verified: verified(i), on_point: on }).ok_or_else(|| "edge".into()) + }; + if let Some(i) = names.iter().position(|n| n == name) { + return exact(i); } + // By the faces it separates: the best way any edge matches. + let wanted = strip_edge_number(name); + let mut best: Option<(Match, Vec)> = None; + for (i, fs) in m.edge_faces.iter().enumerate() { + let [fa, fb] = fs.as_slice() else { continue }; + let Some(level) = edge_match(&faces, *fa as usize, *fb as usize, wanted).filter(|level| exactly(*level)) else { continue }; + keep_best(&mut best, level, i); + } + let (_, cands) = best.ok_or_else(|| format!("edge `{name}` no longer exists"))?; + match cands.as_slice() { + [i] => exact(*i), + _ => Err(format!("edge `{name}` is no longer one edge")), + } +} + +/// Whether a face found at `level` is exactly the face a name named: the very name (or another +/// name of that very face: a face its feature made from several roles has each), or the named +/// piece told apart by the faces around it. A face the named one was merged into, or a face of +/// the same stem, is not. +fn exactly(level: Match) -> bool { + matches!(level, Match::Exact | Match::Piece) } /// Whether the picked point `near` lies on edge `i` of body `b` (whose mesh is `m`): then a @@ -176,27 +190,6 @@ fn edge_mid(m: &Mesh, i: usize) -> Option { e.first().copied() } -/// [`locate_edge`] for a name saved before format 14 (without its mark), as those builds found -/// it: the edge with that name among the names geometry gives, else the piece of it nearest -/// `near`. -fn legacy_locate_edge(b: &ModelBody, name: &str, near: Vec3) -> Result { - let m = b.mesh(); - let names = legacy_edge_names(b); - if let Some(i) = names.iter().position(|n| n == name) { - let on = edge_near(b, &m, i, near); - return edge_mid(&m, i) - .map(|p| EdgeHit { edge: i, point: if on { near } else { p }, split: false, verified: false, on_point: on, legacy: true }) - .ok_or(()); - } - let stem = strip_edge_piece(name); - (0..names.len()) - .filter(|i| names.get(*i).is_some_and(|n| strip_edge_piece(n) == stem)) - .filter_map(|i| edge_mid(&m, i).map(|p| (p, i))) - .min_by(|a, b| a.0.dist(near).total_cmp(&b.0.dist(near))) - .map(|(p, i)| EdgeHit { edge: i, point: p, split: true, verified: false, on_point: false, legacy: true }) - .ok_or(()) -} - /// How well the stored edge name `wanted` (without its own number) names the edge between faces /// `a` and `b`: the weaker of its two faces' matches, read every way the name splits into two /// face names (a face name may hold `|` itself: a fillet face is named after its edge). @@ -231,29 +224,29 @@ pub struct FaceHit { pub face: usize, /// The point on the face nearest the reference's point. pub point: Vec3, - /// The named face is not one face any more (split, or found on several bodies): the piece - /// nearest the point was taken. - pub split: bool, - /// The named face was merged into this one. - pub merged: bool, /// Whether the face's name follows exact history. pub verified: bool, /// Whether the reference's point still lies on the face (so a name worked out from geometry /// and the pick agree). pub on_point: bool, - /// The name was saved before format 14 and found as that build did ([`LEGACY_MARK`]). - pub legacy: bool, +} + +/// Why a stored face name finds no face. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Miss { + /// No face has the name, or only a face it was merged into or a face of the same stem is + /// left, or the name was saved before format 14. + Gone, + /// Several faces answer to it as well: the pieces of a split face, or the same face on + /// several bodies. + Several, } impl FaceHit { /// What a feature says about how it found a face by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { - if self.split { - Some(format!("face `{name}` was split; using the piece nearest the picked point")) - } else if self.merged { - Some(format!("face `{name}` was merged into another face; using that face")) - } else if !self.verified && !self.on_point && !self.legacy { - Some(format!("face `{name}` was found by geometry, not exact history; check it")) + if !self.verified && !self.on_point { + Some(format!("face `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None } @@ -287,181 +280,216 @@ impl FaceHit { } best.map(|t| p + d * t) } + + /// A point that picks the face found again by itself: [`point`](Self::point) when the + /// reference's point still lies on the face clear of its edges; else the point of the face + /// nearest `p` that keeps clear of every edge of it. The nearest point of a face the + /// reference's point no longer lies on is on the face's boundary (a parameter moved the face + /// away from the pick), where a pick by point finds the face beside it as well (#2531). + pub fn pick_point(&self, st: &ModelState, p: Vec3) -> Vec3 { + let Some(b) = st.bodies.get(self.body) else { return self.point }; + let m = b.mesh(); + // Clear of the edges by a few pick tolerances, or by half the face's roomiest triangle + // on a face narrower than that. + let Some(margin) = roomiest_inradius(&m, self.face).map(|r| (4.0 * (b.body.size() * 1e-3).max(1e-3)).min(r * 0.5)) else { + return self.point; + }; + if self.on_point && edge_clearance(&m, self.face, self.point) >= margin { + return self.point; + } + inside_nearest(&m, self.face, p, margin).unwrap_or(self.point) + } +} + +/// The incentre and inradius of triangle abc (`None`: degenerate). +fn incircle(a: Vec3, b: Vec3, c: Vec3) -> Option<(Vec3, f64)> { + // The incentre weighs each corner by the side opposite it; the inradius is area / half the perimeter. + let (la, lb, lc) = (b.dist(c), c.dist(a), a.dist(b)); + let perimeter = la + lb + lc; + let radius = (b - a).cross(c - a).len() / perimeter; + let centre = (a * la + b * lb + c * lc) / perimeter; + (radius.is_finite() && radius > 0.0 && centre.is_finite()).then_some((centre, radius)) +} + +/// The triangles of face `face` of a mesh. +fn face_triangles(m: &Mesh, face: usize) -> impl Iterator + '_ { + m.triangles.iter().zip(&m.tri_face).filter(move |(_, f)| **f as usize == face).filter_map(|(t, _)| m.tri(t)) +} + +/// The greatest inradius of the triangles of face `face` of a mesh (`None`: it has none). +fn roomiest_inradius(m: &Mesh, face: usize) -> Option { + face_triangles(m, face).filter_map(|[a, b, c]| incircle(a, b, c)).map(|(_, r)| r).reduce(f64::max) +} + +/// How far `q` is from the nearest edge bounding face `face` of a mesh (infinite: it has none). +fn edge_clearance(m: &Mesh, face: usize, q: Vec3) -> f64 { + m.edges + .iter() + .zip(&m.edge_faces) + .filter(|(_, fs)| fs.iter().any(|f| *f as usize == face)) + .flat_map(|(e, _)| e.windows(2).map(|w| q.dist_to_segment(w[0], w[1]))) + .filter(|d| d.is_finite()) + .fold(f64::INFINITY, f64::min) +} + +/// The point of face `face` of a mesh nearest `p` among the points at least `margin` inside one +/// of its triangles (each triangle shrunk about its incentre by `margin`): such a point is at +/// least `margin` from every edge of the face, which runs along the sides of its triangles. +/// `None`: no triangle of the face is roomier than `margin`. +fn inside_nearest(m: &Mesh, face: usize, p: Vec3, margin: f64) -> Option { + let mut best: Option<(f64, Vec3)> = None; + for [a, b, c] in face_triangles(m, face) { + let Some((centre, radius)) = incircle(a, b, c).filter(|(_, r)| *r > margin) else { continue }; + // Shrunk about the incentre so each side moves in by `margin`. + let s = (radius - margin) / radius; + let shrink = |v: Vec3| centre + (v - centre) * s; + let q = closest(p, shrink(a), shrink(b), shrink(c)); + let d = q.dist(p); + if d.is_finite() && best.is_none_or(|(old, _)| d < old) { + best = Some((d, q)); + } + } + best.map(|(_, q)| q) +} + +/// A stored name as a message quotes it: whole up to about 80 characters, else its start and +/// end around an ellipsis. Generated names grow with the history (a split edge's name holds both +/// its faces' names), and a chamfer's warning that quoted fourteen of them in full ran to 122,701 +/// characters (#8541). +pub(crate) fn quoted(name: &str) -> String { + const HEAD: usize = 48; + const TAIL: usize = 24; + let n = name.chars().count(); + if n <= HEAD + TAIL + 8 { + return name.to_string(); + } + let head: String = name.chars().take(HEAD).collect(); + let tail: String = name.chars().skip(n - TAIL).collect(); + format!("{head}…{tail}") } impl EdgeHit { /// What a feature says about how it found an edge by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { - if self.split { - Some(format!("edge `{name}` was split; using the piece nearest the picked point")) - } else if !self.verified && !self.on_point && !self.legacy { - Some(format!("edge `{name}` was found by geometry, not exact history; check it")) + if !self.verified && !self.on_point { + Some(format!("edge `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None } } } -/// The face a stored face name finds, on any body: the face with that name, or the one face -/// answering to it (merged into it, or the named piece told apart by the faces around it); else -/// the piece of it nearest `p` (`split`). +/// The face a stored face name finds, on any body: the face with that name, or the named piece +/// told apart by the faces around it. `None` when no face does, or several do. pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option { if crate::sheet::split_sheet_face_name(name).is_some() { - return sheet_locate(st, name, p); + return sheet_locate(st, name, p).ok(); + } + if legacy_name(name).is_some() { + return None; } // Every body's names are read below: work out the ones not known yet on all cores first // (each body's names are its own, whichever thread works them out). - if legacy_name(name).is_none() { - naming::warm_names(st.bodies.iter().filter(|b| !b.body.is_mesh())); - } - locate_in(st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()), name, p) + naming::warm_names(st.bodies.iter().filter(|b| !b.body.is_mesh())); + locate_in(st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()), name, p).ok() } /// [`locate_face`] for a feature that works on the faces of the body called `body` (a shell, a -/// draft…): the one face of that body with the very name, found without working out the names -/// of every other body (a body named from geometry is meshed for it: seconds in a large model). -/// Else as [`locate_face`], over every body: the name moved to another body (a combine took the -/// face), or on this body it names a piece of a split face or a merged one. The same face on -/// another body (a copy of this one) is not a piece of this body's face. -pub(crate) fn locate_face_on_body(st: &ModelState, body: Option<&str>, name: &str, p: Vec3) -> Option { - if crate::sheet::split_sheet_face_name(name).is_some() { - return sheet_locate(st, name, p); +/// draft…): the face of that body the name finds, found without working out the names of every +/// other body (a body named from geometry is meshed for it: seconds in a large model). When +/// that body has no such face, as [`locate_face`] over every body: the name moved to another +/// body (a combine took the face). The same face on another body (a copy of this one) does not +/// make this body's face ambiguous. +pub fn locate_face_on_body(st: &ModelState, body: Option<&str>, name: &str, p: Vec3) -> Option { + if crate::sheet::split_sheet_face_name(name).is_some() || legacy_name(name).is_some() { + return locate_face(st, name, p); } - if legacy_name(name).is_none() - && let Some(i) = body.and_then(|n| st.bodies.iter().position(|b| b.name == n)) + if let Some(i) = body.and_then(|n| st.bodies.iter().position(|b| b.name == n)) && let Some(b) = st.bodies.get(i).filter(|b| !b.body.is_mesh()) - && let Some(hit) = locate_in(std::iter::once((i, b)), name, p) - && !hit.split - && naming::names(b).faces.get(hit.face).is_some_and(|n| n == name) { - return Some(hit); + match locate_in(std::iter::once((i, b)), name, p) { + Ok(hit) => return Some(hit), + Err(Miss::Several) => return None, + Err(Miss::Gone) => {} + } } locate_face(st, name, p) } /// [`locate_face`] for a sheet face's readable name (`sheet:::`, see -/// [`crate::sheet::body_sheet_face_names`]): the face of that body the sheet names so, else the -/// piece of it nearest `p` (`split`). The sheet itself says which face it is, so the name holds -/// however the faces of the body are numbered. -fn sheet_locate(st: &ModelState, name: &str, p: Vec3) -> Option { - let (body, _) = crate::sheet::split_sheet_face_name(name)?; - let (bi, b) = st.bodies.iter().enumerate().find(|(_, b)| b.name == body && !b.body.is_mesh())?; +/// [`crate::sheet::body_sheet_face_names`]): the face of that body the sheet names so. The sheet +/// itself says which face it is, so the name holds however the faces of the body are numbered. +fn sheet_locate(st: &ModelState, name: &str, p: Vec3) -> Result { + let (body, _) = crate::sheet::split_sheet_face_name(name).ok_or(Miss::Gone)?; + let (bi, b) = st.bodies.iter().enumerate().find(|(_, b)| b.name == body && !b.body.is_mesh()).ok_or(Miss::Gone)?; let names = crate::sheet::body_sheet_face_names(st, b); let faces: Vec = names.iter().enumerate().filter(|(_, n)| n.as_deref() == Some(name)).map(|(i, _)| i).collect(); - let m = b.mesh(); - let (distance, face, point) = - faces.iter().filter_map(|f| nearest_on_face(&m, *f, p).map(|(d, q)| (d, *f, q))).min_by(|a, c| a.0.total_cmp(&c.0))?; - Some(FaceHit { - body: bi, - face, - point, - split: faces.len() > 1, - merged: false, - verified: true, - on_point: distance <= (b.body.size() * 1e-3).max(1e-3), - legacy: false, - }) + let face = match faces.as_slice() { + [face] => *face, + [] => return Err(Miss::Gone), + _ => return Err(Miss::Several), + }; + let (distance, point) = nearest_on_face(&b.mesh(), face, p).ok_or(Miss::Gone)?; + Ok(FaceHit { body: bi, face, point, verified: true, on_point: distance <= (b.body.size() * 1e-3).max(1e-3) }) } -/// [`locate_face`] among `bodies` (with their indices). -fn locate_in<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Option { - if let Some(old) = legacy_name(name) { - return legacy_locate(bodies, old, p); +/// [`locate_face`] among `bodies` (with their indices): the one face the name finds there. +fn locate_in<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Result { + if legacy_name(name).is_some() { + return Err(Miss::Gone); } let mut best: Option<(Match, Vec<(usize, &ModelBody, usize)>)> = None; for (bi, b) in bodies { let names = naming::names(b); for face in 0..names.faces.len() { - if let Some(level) = crate::history_names::matches(&names, face, name) { + if let Some(level) = crate::history_names::matches(&names, face, name).filter(|level| exactly(*level)) { keep_best(&mut best, level, (bi, b, face)); } } } - let (level, faces) = best?; - let unique = faces.len() == 1 && level >= Match::Piece; - let mut nearest: Option<(f64, usize, &ModelBody, usize, Vec3)> = None; - for (bi, b, face) in faces { - if let Some((d, q)) = nearest_on_face(&b.mesh(), face, p) - && nearest.as_ref().is_none_or(|n| d < n.0) - { - nearest = Some((d, bi, b, face, q)); - } - } - let (distance, body, b, face, point) = nearest?; - let on_point = distance <= (b.body.size() * 1e-3).max(1e-3); - Some(FaceHit { - body, - face, - point, - split: !unique, - merged: level == Match::Alias, - verified: naming::names(b).verified(face), - on_point, - legacy: false, - }) -} - -/// [`locate_face`] for a name saved before format 14 (without its mark), as those builds found -/// it: among the names geometry gives, the face with that name (or a piece of the same face, if -/// nearer `p`), the nearest point on it. -fn legacy_locate<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Option { - let stem = strip_piece(name); - let mut best: Option<(f64, usize, usize, Vec3, bool, f64)> = None; - for (bi, b) in bodies { - let names = legacy_face_names(b); - let tol = (b.body.size() * 1e-3).max(1e-3); - let m = b.mesh(); - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - let Some(n) = names.get(*f as usize) else { continue }; - let exact = n == name; - if !exact && strip_piece(n) != stem { - continue; - } - let Some([a, bb, c]) = m.tri(t) else { continue }; - let q = closest(p, a, bb, c); - let d = q.dist(p) - if exact { 1e-9 } else { 0.0 }; - if d.is_finite() && best.is_none_or(|x| d < x.0) { - best = Some((d, bi, *f as usize, q, !exact, tol)); - } - } - } - best.map(|(d, body, face, point, split, tol)| FaceHit { - body, - face, - point, - split, - merged: false, - verified: false, - on_point: d <= tol, - legacy: true, - }) -} - -/// Whether face `index` of a body is the face a stored name names: that name (or one merged into -/// it); for a name saved before format 14, that name among the names those builds gave. -pub fn face_has_name(b: &ModelBody, index: usize, name: &str) -> bool { - match legacy_name(name) { - Some(old) => legacy_face_names(b).get(index).is_some_and(|n| n == old), - None => crate::history_names::matches(&naming::names(b), index, name).is_some_and(|m| m >= Match::Alias), - } -} - -/// The faces of a body that are the stored name's face or pieces of it (by stem), as the name's -/// own era names them. -pub fn faces_with_stem(b: &ModelBody, name: &str) -> Vec { - let (names, wanted) = match legacy_name(name) { - Some(old) => (legacy_face_names(b), old), - None => (face_names(b), name), + let (level, faces) = best.ok_or(Miss::Gone)?; + let found = |(body, b, face): (usize, &ModelBody, usize)| { + let (distance, point) = nearest_on_face(&b.mesh(), face, p)?; + Some(FaceHit { body, face, point, verified: naming::names(b).verified(face), on_point: distance <= (b.body.size() * 1e-3).max(1e-3) }) }; - let stem = strip_piece(wanted); - let aliases = - |i: usize| legacy_name(name).is_none() && naming::names(b).info.get(i).is_some_and(|x| x.aliases.iter().any(|a| strip_piece(a) == stem)); + if let [one] = faces.as_slice() { + return found(*one).ok_or(Miss::Gone); + } + // The very face on several bodies (a body and its copies, whose faces keep their names): the + // one the reference's point lies on. Pieces of one face are never told apart by a point. + let mut bodies: Vec = faces.iter().map(|(bi, _, _)| *bi).collect(); + bodies.dedup(); + if level != Match::Exact || bodies.len() < faces.len() { + return Err(Miss::Several); + } + let mut on = faces.into_iter().filter_map(found).filter(|hit| hit.on_point); + match (on.next(), on.next()) { + (Some(hit), None) => Ok(hit), + _ => Err(Miss::Several), + } +} + +/// Whether face `index` of a body is exactly the face a stored name names (see [`exactly`]). A +/// name saved before format 14 names no face. +pub fn face_has_name(b: &ModelBody, index: usize, name: &str) -> bool { + legacy_name(name).is_none() && crate::history_names::matches(&naming::names(b), index, name).is_some_and(exactly) +} + +/// The faces of a body that are the stored name's face or pieces of it (by stem). A name saved +/// before format 14 has none. +pub fn faces_with_stem(b: &ModelBody, name: &str) -> Vec { + if legacy_name(name).is_some() { + return Vec::new(); + } + let names = face_names(b); + let stem = strip_piece(name); + let aliases = |i: usize| naming::names(b).info.get(i).is_some_and(|x| x.synonyms.iter().chain(&x.aliases).any(|a| strip_piece(a) == stem)); (0..names.len()).filter(|i| names.get(*i).is_some_and(|n| strip_piece(n) == stem) || aliases(*i)).collect() } /// [`locate_face`] on one body. pub(crate) fn locate_on(body: &ModelBody, name: &str, p: Vec3) -> Option { - locate_in(std::iter::once((0, body)), name, p) + locate_in(std::iter::once((0, body)), name, p).ok() } /// The one face a name `model.faces` lists finds, on the body called `body` or, without one, on @@ -478,11 +506,10 @@ pub fn locate_one(st: &ModelState, body: Option<&str>, name: &str) -> Result format!("no face is named `{name}` (`model.faces` lists the names)"), + Miss::Several => format!("`{name}` names more than one face (pieces of a split face): give the name of one piece"), + }); } let bodies: Vec<(usize, &ModelBody)> = st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh() && body.is_none_or(|n| b.name == n)).collect(); @@ -490,11 +517,10 @@ pub fn locate_one(st: &ModelState, body: Option<&str>, name: &str) -> Result 1 && legacy_name(name).is_none() { naming::warm_names(bodies.iter().map(|(_, b)| *b)); } - let hit = locate_in(bodies.into_iter(), name, Vec3::ZERO).ok_or_else(|| format!("no face is named `{name}` (`model.faces` lists the names)"))?; - if hit.split { - return Err(format!( - "`{name}` names more than one face (pieces of a split face, or faces of several bodies): give `body`, or the name of one piece" - )); - } - Ok(hit) + locate_in(bodies.into_iter(), name, Vec3::ZERO).map_err(|miss| match miss { + Miss::Gone => format!("no face is named `{name}` (`model.faces` lists the names)"), + Miss::Several => { + format!("`{name}` names more than one face (pieces of a split face, or faces of several bodies): give `body`, or the name of one piece") + } + }) } diff --git a/crates/doc/src/named_projection_tests.rs b/crates/doc/src/named_projection_tests.rs index 4adae985d..37169c1f6 100644 --- a/crates/doc/src/named_projection_tests.rs +++ b/crates/doc/src/named_projection_tests.rs @@ -1,5 +1,6 @@ use crate::{Document, ModelBody, ModelState}; -use solidcraft_geom::{Plane, Vec3}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{LinkKind, LinkSource, Sketch}; use std::collections::BTreeMap; use std::sync::Arc; @@ -28,7 +29,7 @@ fn named_manual_projection_keeps_its_body_and_face_at_shared_boundaries() { sketch.links[0].source = LinkSource::Face { body: "Source".into(), at: Vec3::new(0., 0., 10.) }; let mut current = ModelState::default(); current.bodies.extend([named_box("Source", 20., 20.), named_box("Control", 5., 10.)]); - assert!(crate::project::refresh_links(&doc, &BTreeMap::new(), ¤t, &plane, &mut sketch).is_empty()); + assert!(crate::project::refresh_links(&doc, &BTreeMap::new(), ¤t, &plane, &mut sketch).unwrap().is_empty()); assert!(!sketch.links[0].lost); assert!(sketch.points.iter().any(|point| point.pos.x > 19.)); assert!(sketch.points.iter().any(|point| point.pos.y > 19.)); @@ -40,9 +41,9 @@ fn named_manual_projection_keeps_its_body_and_face_at_shared_boundaries() { let saved = sketch.clone(); let mut missing = ModelState::default(); missing.bodies.push(named_box("Control", 5., 10.)); - let warnings = crate::project::refresh_links(&doc, &BTreeMap::new(), &missing, &plane, &mut sketch); - assert!(sketch.links[0].lost); - assert!(!warnings.is_empty()); + // Its body gone, the named face finds nothing: the sketch fails, asking for it again. + let error = crate::project::refresh_links(&doc, &BTreeMap::new(), &missing, &plane, &mut sketch).unwrap_err(); + assert!(matches!(&error, crate::DocError::Reselect { reference, .. } if reference == "shared:top"), "{error}"); assert_eq!(sketch.curves, saved.curves); assert_eq!(sketch.points, saved.points); assert_eq!(sketch.links[0].id, link); diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index d653516b5..3ae234ee2 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -15,9 +15,11 @@ //! are looked up on the input's faces. Those names are marked unverified, and references that //! resolve through them say so. Names are worked out lazily, on first request. +use solidcraft_geom::prelude::*; use std::sync::{Arc, OnceLock}; -use solidcraft_geom::{Aabb3, Mesh, Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; +use solidcraft_geom::{Aabb3, Mesh}; use crate::history_names::Names; use crate::lineage::Lineage; @@ -42,9 +44,7 @@ pub struct NameCell { /// What the body's faces came from, when the feature that made it reports it. lineage: Option>, names: Arc>>, - /// The names designs saved before format 14 gave its faces (see [`LEGACY_MARK`]). - legacy: Arc>>>, - /// The body this one is a moved copy of (its legacy names are that body's). + /// The body this one is a moved copy of (its names are that body's). copy_of: Option>, /// How deep the chain of features that named it is, for names taken from a saved model /// (which has no origin): see [`NameCell::depth`]. @@ -57,15 +57,11 @@ impl NameCell { } /// Names of a body made by `origin`'s feature, following `lineage` where it is known. pub(crate) fn traced(origin: Option>, lineage: Option>) -> Self { - NameCell { origin, lineage, names: Arc::new(OnceLock::new()), legacy: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None } + NameCell { origin, lineage, names: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None } } /// Names already known, taken as they are. pub fn known(names: Arc>) -> Self { - let legacy = OnceLock::new(); - let _ = legacy.set(names.clone()); - let mut cell = Self::shared(Arc::new(Names::given(names))); - cell.legacy = Arc::new(legacy); - cell + Self::shared(Arc::new(Names::given(names))) } /// The names of `body` (a moved copy of a body keeps its faces' names, and how sure they are). /// @@ -102,7 +98,7 @@ impl NameCell { fn shared(names: Arc) -> Self { let cell = OnceLock::new(); let _ = cell.set(names); - NameCell { origin: None, lineage: None, names: Arc::new(cell), legacy: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None } + NameCell { origin: None, lineage: None, names: Arc::new(cell), copy_of: None, saved_depth: None } } } @@ -154,7 +150,9 @@ impl Drop for NameCell { } } -pub use crate::name_lookup::{EdgeHit, FaceHit, LEGACY_MARK, face_has_name, faces_with_stem, legacy_name, locate_edge, locate_face, locate_one}; +pub use crate::name_lookup::{ + EdgeHit, FaceHit, LEGACY_MARK, face_has_name, faces_with_stem, legacy_name, locate_edge, locate_face, locate_face_on_body, locate_one, +}; pub use crate::piece_names::parent_piece; /// Deeper chains than this are named by position only (bounded work and stack). @@ -164,7 +162,7 @@ const MAX_DEPTH: usize = 400; const SAMPLES: usize = 9; /// Up to this many sample points per face where a sheet's panel kept in place names the face it is -/// part of (see [`geometric_from`]). +/// part of (see [`geometric_names`]). const PANEL_SAMPLES: usize = 256; /// Unit normals of each face's triangles. @@ -289,6 +287,129 @@ pub fn face_name_exact(b: &ModelBody, index: usize) -> bool { names(b).verified(index) } +/// What a face a fillet or chamfer made (a round, a chamfer face or a corner patch: named +/// `F:blend:`) meets across one of its seams. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BlendSeamKind { + /// A face either side of an edge the blend replaced: what it was made to meet along its + /// length (a round is tangent to it, a chamfer meets it at its angle). + Contact, + /// Another blend face: the next round of a chain, or a corner patch and the rounds it joins. + Blend, +} + +/// A seam of a blend face ([`blend_seams`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BlendSeam { + /// The edge, by mesh edge index (the body's edge order). + pub edge: usize, + pub kind: BlendSeamKind, + /// Whether one side is a corner patch: a blend face made from several replaced edges (its + /// name and its aliases each name one), where the rounds of those edges meet. + pub corner: bool, +} + +/// The seams of a body's blend faces with what they were made to meet: the faces either side of +/// each edge a blend replaced, and other blend faces. A blend's seam with any other face (an end +/// face its round runs into) is not one. Read from the faces' names, so a body named from +/// geometry ([`face_name_exact`] false) gives its blends' nearest edges. +pub fn blend_seams(b: &ModelBody) -> Vec { + const MARK: &str = ":blend:"; + let n = names(b); + // Per face: the names it answers to, and the edges a blend face replaced (each as + // `|`, without qualifiers or numbers). + let all = |i: usize| -> Vec<&str> { + let (aliases, synonyms) = n.info.get(i).map(|f| (f.aliases.as_slice(), f.synonyms.as_slice())).unwrap_or_default(); + n.faces.get(i).map(String::as_str).into_iter().chain(synonyms.iter().chain(aliases).map(String::as_str)).collect() + }; + let replaced: Vec> = (0..n.faces.len()) + .map(|i| { + all(i) + .into_iter() + .filter_map(|name| { + let (core, instance) = split_instance(name); + let (_, edge) = core.split_once(MARK)?; + Some((crate::piece_names::strip_edge_piece(edge), instance.to_string())) + }) + .collect() + }) + .collect(); + let blend = |i: usize| replaced.get(i).is_some_and(|r| !r.is_empty()); + let corner = |i: usize| replaced.get(i).is_some_and(|r| r.len() > 1); + // Whether face `j` is a side of an edge blend face `i` replaced. + let contact = |i: usize, j: usize| -> bool { + let Some(edges) = replaced.get(i) else { return false }; + all(j).into_iter().any(|name| { + let (core, instance) = split_instance(name); + let face = crate::piece_names::strip_qualifiers(core); + edges.iter().any(|(edge, at)| at == instance && edge_sides(edge).is_some_and(|(a, b)| a == face || b == face)) + }) + }; + let mut out = Vec::new(); + for (edge, faces) in b.mesh().edge_faces.iter().enumerate() { + let [f, g] = faces.as_slice() else { continue }; + let (f, g) = (*f as usize, *g as usize); + let kind = if blend(f) && blend(g) { + BlendSeamKind::Blend + } else if (blend(f) && contact(f, g)) || (blend(g) && contact(g, f)) { + BlendSeamKind::Contact + } else { + continue; + }; + out.push(BlendSeam { edge, kind, corner: corner(f) || corner(g) }); + } + out +} + +/// The two faces an edge name `|` joins. A blend face's own name holds the edge it +/// replaced (`F:blend:|`), so a side's name can hold `|` too: the split is the +/// one `|` outside every blend face's edge (`F1:+y` and `F3:blend:F1:+z|F2:side` for +/// `F1:+y|F3:blend:F1:+z|F2:side`). `None` for a name that is not two faces. +fn edge_sides(edge: &str) -> Option<(&str, &str)> { + let first = face_name_end(edge, 0)?; + if edge.as_bytes().get(first) != Some(&b'|') || face_name_end(edge, first + 1)? != edge.len() { + return None; + } + Some((edge.get(..first)?, edge.get(first + 1..)?)) +} + +/// Where the face name starting at byte `from` of `s` ends: at the next `|`, or for a blend face +/// past the two faces of the edge its name holds (and theirs, for blends of blends). +fn face_name_end(s: &str, from: usize) -> Option { + const MARK: &str = ":blend:"; + // The faces still to read: a blend face's name is read as the two of its edge. + let (mut pending, mut at) = (1usize, from); + loop { + let rest = s.get(at..)?; + let bar = rest.find('|').unwrap_or(rest.len()); + if let Some(m) = rest.get(..bar)?.find(MARK) { + pending += 1; + at += m + MARK.len(); + continue; + } + pending -= 1; + at += bar; + if pending == 0 { + return Some(at); + } + if s.as_bytes().get(at) != Some(&b'|') { + return None; + } + at += 1; + } +} + +/// A name and the copy it names (`@F.`, a pattern's or a paste's copy of a +/// tool face; empty for the original). +fn split_instance(name: &str) -> (&str, &str) { + match name.rfind('@') { + Some(i) if name.get(i + 1..).is_some_and(|t| t.starts_with('F') && t.bytes().skip(1).all(|c| c.is_ascii_digit() || c == b'.')) => { + (name.get(..i).unwrap_or(name), name.get(i..).unwrap_or("")) + } + _ => (name, ""), + } +} + /// Prepare only names not yet known before a lookup reads several bodies. A ready cell is /// shared by snapshots and poses: dispatching threads just to read it costs more than a lookup. pub(crate) fn warm_names<'a>(bodies: impl Iterator) { @@ -381,45 +502,6 @@ pub(crate) fn names(b: &ModelBody) -> Arc { .clone() } -/// The names builds before format 14 gave a body's faces: from geometry, over the inputs' names -/// as those builds gave them, pieces of a split face numbered along the longest axis of their -/// spread (`#1`, `#2`, …). -pub(crate) fn legacy_face_names(b: &ModelBody) -> Arc> { - if let Some(known) = b.names.legacy.get() { - return known.clone(); - } - warm_chain( - b, - |x| x.names.legacy.get().is_some(), - |x| { - let _ = legacy_face_names(x); - }, - ); - if let Some(source) = &b.names.copy_of { - return legacy_face_names(source); - } - b.names - .legacy - .get_or_init(|| { - let nf = face_count(b); - let names = match b.names.origin.as_ref() { - Some(o) if o.depth < MAX_DEPTH => { - let mut names = geometric_from(b, o, nf, legacy_face_names); - number_pieces(&mut names, &samples(&b.mesh(), nf), '#'); - names - } - _ => (0..nf).map(|k| format!("{}:face:{k}", b.name)).collect(), - }; - Arc::new(names) - }) - .clone() -} - -/// The names builds before format 14 gave a body's edges. -pub(crate) fn legacy_edge_names(b: &ModelBody) -> Vec { - edge_names_from(b, &legacy_face_names(b)) -} - /// Pairs of faces of a body that share an edge (from its mesh's edges). pub(crate) fn mesh_adjacency(b: &ModelBody) -> Vec<(usize, usize)> { crate::history_names::face_pairs(b.mesh().edge_faces.iter().map(|fs| fs.iter().map(|f| *f as usize))) @@ -429,17 +511,12 @@ pub(crate) fn mesh_adjacency(b: &ModelBody) -> Vec<(usize, usize)> { /// geometry: where each face's sample points lie on the input's faces. Faces sharing a name are /// pieces of one, told apart afterwards. pub(crate) fn geometric_names(b: &ModelBody, o: &NamingOrigin, nf: usize) -> Vec { - geometric_from(b, o, nf, face_names) -} - -/// [`geometric_names`], the input bodies' faces named by `names_of`. -fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&ModelBody) -> Arc>) -> Vec { // A rigid Move changes coordinates, not topology or face ownership. Geometric // overlap with the unmoved input cannot recover the names at the new position. if matches!(o.feature.kind, FeatureKind::Move { .. }) && let Some(input) = o.before.body(&b.name) { - return names_of(input).as_ref().clone(); + return face_names(input).as_ref().clone(); } let m = b.mesh(); let size = b.body.size().max(1e-6); @@ -476,7 +553,7 @@ fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&Mode .take(64) .map(|x| { let n = face_count(x); - (x, FaceIndex::new(&x.mesh(), n), names_of(x)) + (x, FaceIndex::new(&x.mesh(), n), face_names(x)) }) .collect(); let fid = o.feature.id; @@ -491,7 +568,7 @@ fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&Mode .iter() .filter(|x| !x.body.is_mesh()) .take(64) - .map(|x| (x, FaceIndex::new(&x.mesh(), face_count(x)), names_of(x))) + .map(|x| (x, FaceIndex::new(&x.mesh(), face_count(x)), face_names(x))) .collect(); let mut best: Option<(usize, usize, Vec>)> = None; for (k, mat) in o.mats.iter().enumerate() { @@ -538,6 +615,19 @@ fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&Mode } } } + // A feature that built a tool and reported no history. Two meshes of one curved face are only + // as close as their chord tolerances, which follow the body's size: a tool that makes the body + // bigger divides its round walls differently, and those walls miss their own faces at `tol`. + // Named by role they would become faces of this feature, nowhere near what it built. + if matches!(o.feature.kind, FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. } | FeatureKind::Sweep { .. } | FeatureKind::Loft { .. }) { + let chord = b.display_tol() + inputs.iter().map(|(x, _, _)| x.display_tol()).fold(0.0, f64::max); + for (fi, name) in names.iter_mut().enumerate().filter(|(_, name)| name.is_none()) { + let curved = ns.get(fi).is_some_and(|n| n.windows(2).any(|w| w[0].cross(w[1]).len() > 1e-6)); + if curved && let Some(ps) = pts.get(fi) { + *name = vote(ps, &inputs, chord, None); + } + } + } let empty = Vec::new(); let curves = std::cell::OnceCell::new(); let names: Vec = names @@ -930,10 +1020,10 @@ fn edge_names_from(b: &ModelBody, faces: &[String]) -> Vec { names } -/// The edge of a body with this name: exact, else the pieces of the same edge nearest `near` -/// (`Err` explains when there is none). -pub fn find_edge(b: &ModelBody, name: &str, near: Vec3) -> Result<(Vec3, bool), String> { - locate_edge(b, name, near).map(|hit| (hit.point, hit.split)) +/// A point on the edge of a body this name finds (see [`locate_edge`]; `Err` explains when there +/// is none). +pub fn find_edge(b: &ModelBody, name: &str, near: Vec3) -> Result { + locate_edge(b, name, near).map(|hit| hit.point) } /// Names of the edges nearest each point on a body (for storing references). @@ -1091,21 +1181,20 @@ pub fn named_face_point(st: &ModelState, body: Option<&str>, name: &str) -> Resu face_spot(b, hit.face).map(|spot| spot.point).ok_or_else(|| format!("face `{name}` has no surface to pick")) } -/// The point on the face with this name nearest `p` (a split face: its nearest piece, with -/// `true` for "not exactly that face": split, or merged into another); `None` when no face has -/// the name. -pub fn point_on_face(st: &ModelState, name: &str, p: Vec3) -> Option<(Vec3, bool)> { - locate_face(st, name, p).map(|hit| (hit.point, hit.split || hit.merged)) +/// The point on the face this name finds nearest `p`; `None` when the name finds no face (see +/// [`locate_face`]). +pub fn point_on_face(st: &ModelState, name: &str, p: Vec3) -> Option { + locate_face(st, name, p).map(|hit| hit.point) } /// Resolve a legacy named face only on its recorded source body. Return the /// selected face index as well as the closest point, which may lie on a shared /// edge and therefore must not be used to pick the face a second time. -pub fn face_on_body(body: &ModelBody, name: &str, p: Vec3) -> Option<(usize, Vec3, bool)> { +pub fn face_on_body(body: &ModelBody, name: &str, p: Vec3) -> Option<(usize, Vec3)> { if body.body.is_mesh() { return None; } - crate::name_lookup::locate_on(body, name, p).map(|hit| (hit.face, hit.point, hit.split || hit.merged)) + crate::name_lookup::locate_on(body, name, p).map(|hit| (hit.face, hit.point)) } #[cfg(test)] @@ -1131,7 +1220,7 @@ mod tests { fn same_hit(a: &FaceHit, b: &FaceHit) { assert_eq!((a.body, a.face, a.point), (b.body, b.face, b.point)); - assert_eq!((a.split, a.merged, a.verified, a.on_point, a.legacy), (b.split, b.merged, b.verified, b.on_point, b.legacy)); + assert_eq!((a.verified, a.on_point), (b.verified, b.on_point)); } #[test] @@ -1359,7 +1448,7 @@ mod tests { let ss = crate::SolvedSketch { feature: 1, name: "S".into(), - plane: solidcraft_geom::Plane::XY, + plane: solidcore_record::Plane::XY, sketch, report, profiles, diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs index 2b76231a3..baa210b4f 100644 --- a/crates/doc/src/params.rs +++ b/crates/doc/src/params.rs @@ -90,7 +90,11 @@ pub struct ParamRow { pub name: String, pub expression: String, pub unit: String, + /// Always millimetres for a length, degrees for an angle, whatever the parameter's own + /// unit — the same meaning `value` has in every reply (#10747). pub value: Option, + /// The value in the parameter's own `unit`, as the Parameters window shows it. + pub display_value: Option, pub error: Option, pub comment: String, /// "user", "sketch" (a dimension) or "feature". @@ -367,14 +371,20 @@ impl Document { } } let used_by = |n: &str| -> Vec { users.get(n).cloned().unwrap_or_default() }; - let value = |n: &str, k: Kind| vals.get(n).and_then(|v| v.to_kind(k).ok()).map(|x| if k == Kind::Angle { x.to_degrees() } else { x }); + let value = |n: &str, k: Kind| { + vals.get(n).and_then(|v| v.to_kind(k).ok()).map(|x| if k == Kind::Angle { x.to_degrees() } else { x }).map(expr::round_reported) + }; + // `value` is mm / degrees in every row (#10747); the parameter's own unit goes to + // `display_value`. Both carry the number a person would read, not the float noise. + let unified = |n: &str| vals.get(n).map(|v| expr::round_reported(expr::reported_value(*v))); let mut rows = Vec::new(); for p in &self.params { rows.push(ParamRow { name: p.name.clone(), expression: p.expr.clone(), unit: p.unit.clone(), - value: self.param_display_value(&vals, &p.name), + value: unified(&p.name), + display_value: self.param_display_value(&vals, &p.name).map(expr::round_reported), error: errs.get(&p.name).cloned(), comment: p.comment.clone(), source: if p.model { "sketch" } else { "user" }, @@ -396,6 +406,8 @@ impl Document { expression: e, unit: unit_of(k).into(), value: value(name, k), + // A feature input's own unit is mm / deg, so its display value is its value. + display_value: value(name, k), error: errs.get(name).cloned(), comment: self.param_comments.get(name).cloned().unwrap_or_default(), source: "feature", @@ -415,6 +427,7 @@ impl Document { expression: p.text.clone(), unit: crate::text_params::TEXT_UNIT.into(), value: None, + display_value: None, error: None, comment: p.comment.clone(), source: "user", @@ -460,9 +473,10 @@ impl Document { Ok(()) } - /// User parameters as CSV (`name,unit,expression,value,comment`). + /// User parameters as CSV (`name,unit,expression,value,comment`). The `value` column is the + /// number in the `unit` column, rounded for reading (#10747); import reads `expression`. pub fn params_csv(&self) -> String { - let q = |s: &str| if s.contains([',', '"', '\n']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() }; + let q = |s: &str| if s.contains([',', '"', '\r', '\n']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() }; let mut out = String::from("name,unit,expression,value,comment,favorite\n"); for r in self.param_rows().into_iter().filter(|r| r.source == "user") { out += &format!( @@ -470,7 +484,7 @@ impl Document { q(&r.name), q(&r.unit), q(&r.expression), - r.value.map(|v| format!("{v}")).unwrap_or_default(), + r.display_value.or(r.value).map(|v| format!("{v}")).unwrap_or_default(), q(&r.comment), r.favorite ); @@ -497,23 +511,25 @@ impl Document { }) .collect::>()? } else { - let mut lines = text.lines(); - let header: Vec = parse_csv_line(lines.next().unwrap_or_default()).into_iter().map(|h| h.trim().to_ascii_lowercase()).collect(); - let col = |n: &str| header.iter().position(|h| h == n); + let mut records = split_csv(text.strip_prefix('\u{feff}').unwrap_or(text), '\n'); + let header = csv_fields(records.next().unwrap_or_default())?; + let col = |n: &str| header.iter().position(|h| h.trim().eq_ignore_ascii_case(n)); let (Some(ni), Some(ei)) = (col("name"), col("expression").or(col("value"))) else { return Err(DocError::Invalid("the CSV needs `name` and `expression` columns".into())); }; let (ui, ci) = (col("unit"), col("comment")); - lines - .filter(|l| !l.trim().is_empty()) - .map(|l| { - let c = parse_csv_line(l); + records + .filter(|record| !record.trim().is_empty()) + .take(MAX_PARAMS + 1) + .map(|record| { + let c = csv_fields(record)?; let get = |i: Option| i.and_then(|i| c.get(i)).map(|s| s.trim().to_string()); - (get(Some(ni)).unwrap_or_default(), get(Some(ei)).unwrap_or_default(), get(ui), get(ci)) + let comment = ci.and_then(|i| c.get(i)).cloned(); + Ok((get(Some(ni)).unwrap_or_default(), get(Some(ei)).unwrap_or_default(), get(ui), comment)) }) - .collect() + .collect::>()? }; - if rows.len() > 10_000 { + if rows.len() > MAX_PARAMS { return Err(DocError::Invalid("too many parameters".into())); } // Each row is checked and applied as `change_param` would, but the parameters are @@ -1084,25 +1100,32 @@ impl Document { } } -/// One CSV line with quoted fields. -fn parse_csv_line(l: &str) -> Vec { - let mut out = Vec::new(); - let mut cur = String::new(); +/// Split records or fields only outside quotes. A doubled quote toggles twice +/// before the next separator, leaving it inside the same field. +fn split_csv(text: &str, separator: char) -> impl Iterator { let mut quoted = false; - let mut chars = l.chars().peekable(); - while let Some(c) = chars.next() { - match (c, quoted) { - ('"', true) if chars.peek() == Some(&'"') => { - cur.push('"'); - chars.next(); - } - ('"', _) => quoted = !quoted, - (',', false) => out.push(std::mem::take(&mut cur)), - (c, _) => cur.push(c), + text.split(move |c| { + if c == '"' { + quoted = !quoted; } - } - out.push(cur); - out + c == separator && !quoted + }) +} + +fn csv_fields(record: &str) -> Result> { + split_csv(record, ',') + .map(|raw| { + let field = raw.trim(); + if !field.contains('"') { + return Ok(field.to_string()); + } + let inner = field.strip_prefix('"').and_then(|s| s.strip_suffix('"')); + match inner { + Some(s) if s.split("\"\"").all(|part| !part.contains('"')) => Ok(s.replace("\"\"", "\"")), + _ => Err(DocError::Invalid("invalid quoting in parameter CSV".into())), + } + }) + .collect() } /// Parameters whose definitions depend on each other in a loop. diff --git a/crates/doc/src/pbr_appearance.rs b/crates/doc/src/pbr_appearance.rs index 4172f5714..d4b967aec 100644 --- a/crates/doc/src/pbr_appearance.rs +++ b/crates/doc/src/pbr_appearance.rs @@ -1,7 +1,7 @@ //! Persistable opaque optical parameters, independent of engineering material data. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_render::surface::{OpaqueSurface, SurfaceError, srgb8_to_linear}; /// Explicitly selected opaque response. Existing scalar looks have no such record. diff --git a/crates/doc/src/persistent_name.rs b/crates/doc/src/persistent_name.rs index dec333ee2..bd263c9e2 100644 --- a/crates/doc/src/persistent_name.rs +++ b/crates/doc/src/persistent_name.rs @@ -5,12 +5,14 @@ //! (`F3:inner:`), or, without history, a body and an index (`Body1:face:3`). Suffixes //! follow: a pattern copy (`@F7.2`), a piece of a split face told apart by the faces around it //! (`#[,…]`, `#k` after it for a tie), an older design's numbered piece (`#k`). An edge is -//! the two faces it separates, `~k` for one of several between them. +//! the two faces it separates, `~k` for one of several between them; a seam, whose two sides are +//! the same face, names that face once. //! //! The text form, read by [`FaceName::parse`] and [`EdgeName::parse`] and written by `Display`: //! //! ```text -//! edge = face { "|" face } [TIE] one face for an open boundary, more where several meet +//! edge = face { "|" face } [TIE] one face for an open boundary or a seam (both of an +//! edge's sides on one face), more where several meet //! face = base { suffix } //! base = FEATURE ":" "blend" ":" ( edge | NUMBER ) //! | FEATURE ":" "inner" ":" face @@ -152,6 +154,27 @@ pub enum NameError { }, } +/// Whether `text` can be written into a name whole. +/// +/// A curve's id goes into the name of the faces the curve makes (`F2:side:`), and a +/// name reads some characters as its own: `|` separates the faces of an edge, `,` the faces +/// around a piece, `~` numbers the edges between two faces, `#` numbers a piece and `]` +/// closes one. An id holding one of them splits every name it lands in: the id `c|1` gave +/// the edges of an extrusion the names `F2:side:c|1#1|F2:side:c|1#2~1`, three separators +/// where an edge names two faces and separates them once (#5858). +/// +/// The test is the name's own round trip rather than a list of characters: the text is +/// written into a name and read back, and it must read back as itself. A list would have +/// to follow every change of the grammar (#5861), and would miss an id that reads back as +/// something else (`s1.l4` reads as profile 1 of curve `l4`). +pub fn text_fits_name(text: &str) -> bool { + let name = format!("F0:side:{text}"); + match FaceName::parse(&name) { + Ok(f) => f.to_string() == name && matches!(&f.base, Base::Made { role: Role::Side { profile: None, curve }, .. } if curve == text), + Err(_) => false, + } +} + impl FaceName { /// The feature that made the face: its base's, a copy's when it is one. pub fn feature(&self) -> Option { diff --git a/crates/doc/src/persistent_name/tests.rs b/crates/doc/src/persistent_name/tests.rs index 899f06dbb..8149d3499 100644 --- a/crates/doc/src/persistent_name/tests.rs +++ b/crates/doc/src/persistent_name/tests.rs @@ -236,3 +236,15 @@ fn hostile_names_never_panic() { // A fillet on an open boundary's edge. assert!(matches!(face("F1:blend:F10:start").base, Base::Blend { rounds: Rounds::Edge(ref e), .. } if e.faces.len() == 1)); } + +#[test] +fn a_text_that_cannot_be_written_into_a_name_whole_is_told() { + // A curve's id goes into the name of the faces the curve makes, so it has to come + // back out of the name as itself (#5858). + for good in ["c1", "l4", "s01.l4", "c-1", "c_1", "a.b", "x"] { + assert!(text_fits_name(good), "`{good}` fits a name"); + } + for bad in ["c|1", "c,1", "c~1", "c]1", "c#1", "", "s1.l4"] { + assert!(!text_fits_name(bad), "`{bad}` does not fit a name"); + } +} diff --git a/crates/doc/src/piece_names.rs b/crates/doc/src/piece_names.rs index 8974c12df..7c9e07ee5 100644 --- a/crates/doc/src/piece_names.rs +++ b/crates/doc/src/piece_names.rs @@ -80,7 +80,13 @@ fn split_top_level(s: &str) -> Vec<&str> { /// numbered pieces of older designs), so pieces of a split edge, or of an edge between split /// faces, match. pub(crate) fn strip_edge_piece(n: &str) -> String { - let n = strip_edge_number(n); + strip_qualifiers(strip_edge_number(n)) +} + +/// A name without any face's piece qualifiers (`#[…]`, and the numbered pieces of older designs), +/// wherever they are in it: the face a piece name is a piece of, with every face it names +/// unqualified too. An edge's own number (`~k`) stays. +pub(crate) fn strip_qualifiers(n: &str) -> String { let mut out = String::with_capacity(n.len()); let bytes = n.as_bytes(); let mut i = 0; diff --git a/crates/doc/src/pipe_thread_sizes.rs b/crates/doc/src/pipe_thread_sizes.rs new file mode 100644 index 000000000..b6d8363d0 --- /dev/null +++ b/crates/doc/src/pipe_thread_sizes.rs @@ -0,0 +1,148 @@ +//! The sizes of the pipe-thread forms a modelled thread cuts: ISO 7-1 (55°, taper R external and +//! Rc internal; its gauge-plane diameters are also the parallel G sizes of ISO 228-1) and ASME +//! B1.20.1 NPT (60°, taper). Lengths and diameters in mm; the taper is 1 in 16 on the diameter. +//! +//! Sources (docs/threads.md): +//! - ISO 7-1:1978, Table 1, columns 1 to 8 and 15, as the public preview prints them: +//! . +//! - NBS Handbook H28 (1957) Part II, Table VII.2, "Basic dimensions of American Standard taper +//! pipe threads, NPT" (a U.S. government publication): +//! . + +const INCH: f64 = 25.4; + +/// One taper pipe-thread size, by the plane its diameters are given at (the reference plane). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PipeSize { + /// The nominal size as the standard writes it: `1/2`, `1 1/4`. + pub nominal: &'static str, + /// Threads per inch. + pub tpi: f64, + /// The major diameter at the reference plane: ISO 7-1's gauge diameter d, NPT's E1 + h. + pub major: f64, + /// From the small end of the external thread to the reference plane: ISO 7-1's basic gauge + /// length, NPT's hand-tight engagement L1. The internal thread has it at its face. + pub gauge: f64, + /// The external thread's length: ISO 7-1's useful thread for the basic gauge length (not + /// less than), NPT's effective thread L2. + pub length: f64, +} + +impl PipeSize { + pub fn pitch(&self) -> f64 { + INCH / self.tpi + } +} + +/// ISO 7-1:1978 Table 1: designation, threads per 25.4 mm, major (gauge) diameter d, basic gauge +/// length, useful thread for the basic gauge length (columns 1, 2, 5, 8 and 15). +const ISO_7_1: &[(&str, f64, f64, f64, f64)] = &[ + ("1/16", 28.0, 7.723, 4.0, 6.5), + ("1/8", 28.0, 9.728, 4.0, 6.5), + ("1/4", 19.0, 13.157, 6.0, 9.7), + ("3/8", 19.0, 16.662, 6.4, 10.1), + ("1/2", 14.0, 20.955, 8.2, 13.2), + ("3/4", 14.0, 26.441, 9.5, 14.5), + ("1", 11.0, 33.249, 10.4, 16.8), + ("1 1/4", 11.0, 41.910, 12.7, 19.1), + ("1 1/2", 11.0, 47.803, 12.7, 19.1), + ("2", 11.0, 59.614, 15.9, 23.4), + ("2 1/2", 11.0, 75.184, 17.5, 26.7), + ("3", 11.0, 87.884, 20.6, 29.8), + ("4", 11.0, 113.030, 25.4, 35.8), + ("5", 11.0, 138.430, 28.6, 40.1), + ("6", 11.0, 163.830, 28.6, 40.1), +]; + +/// H28 Table VII.2 (inches): nominal size, outside diameter of pipe D, threads per inch, pitch +/// diameter at the beginning of the external thread E0, hand-tight engagement L1, effective +/// thread L2 (columns 1, 2, 3, 5, 6 and 9). +const NPT: &[(&str, f64, f64, f64, f64, f64)] = &[ + ("1/16", 0.3125, 27.0, 0.27118, 0.160, 0.2611), + ("1/8", 0.405, 27.0, 0.36351, 0.1615, 0.2639), + ("1/4", 0.540, 18.0, 0.47739, 0.2278, 0.4018), + ("3/8", 0.675, 18.0, 0.61201, 0.240, 0.4078), + ("1/2", 0.840, 14.0, 0.75843, 0.320, 0.5337), + ("3/4", 1.050, 14.0, 0.96768, 0.339, 0.5457), + ("1", 1.315, 11.5, 1.21363, 0.400, 0.6828), + ("1 1/4", 1.660, 11.5, 1.55713, 0.420, 0.7068), + ("1 1/2", 1.900, 11.5, 1.79609, 0.420, 0.7235), + ("2", 2.375, 11.5, 2.26902, 0.436, 0.7565), + ("2 1/2", 2.875, 8.0, 2.71953, 0.682, 1.1375), + ("3", 3.500, 8.0, 3.34062, 0.766, 1.2000), + ("3 1/2", 4.000, 8.0, 3.83750, 0.821, 1.2500), + ("4", 4.500, 8.0, 4.33438, 0.844, 1.3000), + ("5", 5.563, 8.0, 5.39073, 0.937, 1.4063), + ("6", 6.625, 8.0, 6.44609, 0.958, 1.5125), + ("8", 8.625, 8.0, 8.43359, 1.063, 1.7125), + ("10", 10.750, 8.0, 10.54531, 1.210, 1.9250), + ("12", 12.750, 8.0, 12.53281, 1.360, 2.1250), +]; + +/// NPT's thread height h = 0.8 p (H28 VII.2.2). +pub const NPT_HEIGHT: f64 = 0.8; + +/// The ISO 7-1 sizes (R, Rc; their diameters are ISO 228-1's G sizes too). +pub fn iso_7_1() -> impl Iterator { + ISO_7_1.iter().map(|&(nominal, tpi, major, gauge, length)| PipeSize { nominal, tpi, major, gauge, length }) +} + +/// The NPT sizes, the major diameter at the hand-tight plane E1 + h (E1 = E0 + L1/16). +pub fn npt() -> impl Iterator { + NPT.iter().map(|&(nominal, _, tpi, e0, l1, l2)| { + let e1 = e0 + l1 / 16.0; + PipeSize { nominal, tpi, major: (e1 + NPT_HEIGHT / tpi) * INCH, gauge: l1 * INCH, length: l2 * INCH } + }) +} + +/// The pipe's outside diameter D an NPT size is cut on (mm). +pub fn npt_pipe_od(nominal: &str) -> Option { + NPT.iter().find(|r| r.0 == nominal).map(|r| r.1 * INCH) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The transcribed ISO 7-1 rows against the standard's own relations: P = 25.4/n, h = + /// 0.640327 P, d2 = d - h, d1 = d - 2h (columns 3, 4, 6, 7, rounded to 3 decimals there). + #[test] + fn iso_7_1_rows_follow_their_formulas() { + let cols: [(f64, f64, f64, f64); 15] = [ + (0.907, 0.581, 7.142, 6.561), + (0.907, 0.581, 9.147, 8.566), + (1.337, 0.856, 12.301, 11.445), + (1.337, 0.856, 15.806, 14.950), + (1.814, 1.162, 19.793, 18.631), + (1.814, 1.162, 25.279, 24.117), + (2.309, 1.479, 31.770, 30.291), + (2.309, 1.479, 40.431, 38.952), + (2.309, 1.479, 46.324, 44.845), + (2.309, 1.479, 58.135, 56.656), + (2.309, 1.479, 73.705, 72.226), + (2.309, 1.479, 86.405, 84.926), + (2.309, 1.479, 111.551, 110.072), + (2.309, 1.479, 136.951, 135.472), + (2.309, 1.479, 162.351, 160.872), + ]; + for (s, (p, h, d2, d1)) in iso_7_1().zip(cols) { + assert!((s.pitch() - p).abs() < 5e-4, "{}", s.nominal); + assert!((0.640327 * s.pitch() - h).abs() < 5e-4, "{}", s.nominal); + assert!((s.major - h - d2).abs() < 1.5e-3 && (s.major - 2.0 * h - d1).abs() < 1.5e-3, "{}", s.nominal); + } + } + + /// The transcribed NPT rows against H28's formulas: E0 = D - (0.05 D + 1.1) p and L2 = (0.80 D + /// + 6.8) p (VII.3.4 and VII.3.5). + #[test] + fn npt_rows_follow_their_formulas() { + for &(n, d, tpi, e0, _, l2) in NPT { + let p = 1.0 / tpi; + assert!((d - (0.05 * d + 1.1) * p - e0).abs() < 2e-5, "{n}"); + assert!(((0.80 * d + 6.8) * p - l2).abs() < 1e-4, "{n}"); + } + let half = npt().find(|s| s.nominal == "1/2").unwrap(); + // E1 = 0.77843 in (column 7), h = 0.8/14. + assert!((half.major - (0.77843 + 0.8 / 14.0) * INCH).abs() < 1e-4); + } +} diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs index f79ff4786..31006ca9d 100644 --- a/crates/doc/src/placed_mesh.rs +++ b/crates/doc/src/placed_mesh.rs @@ -1,9 +1,11 @@ //! Reference triangles belong to a definition, even while its occurrences move. Keep one lazy //! source mesh and map it into each pose; retain the exact placed B-rep separately in ModelBody. +use solidcraft_geom::prelude::*; use std::sync::{Arc, OnceLock}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use solidcraft_geom::tess::TessPlan; -use solidcraft_geom::{Mesh, Vec3}; use solidcraft_kernel::{self as kernel, Body}; use super::ModelBody; @@ -16,23 +18,57 @@ pub(super) struct PlacedMesh { /// each placement draws them moved, so a part is planned once however often it is placed. plans: Arc<[OnceLock>>; 4]>, plan_meshes: Arc<[OnceLock>>; 4]>, + /// The definition's own opposite hand: a copy of a copy is a rigid move of that. + opposite_hand: Arc>, transform: crate::Mat, pub(super) tolerance: f64, } +/// A body's opposite hand: the first mirrored copy made of it, and the matrix that made it. A +/// reflection reverses each face's edge walk, so a copy can't be drawn from its source's triangles. +/// Two reflections do cancel, though: every later mirrored copy of the body, wherever dragging a +/// placement puts it, is a proper rigid move of this one, whose triangles are made once. +#[derive(Debug)] +pub(super) struct OppositeHand { + /// The body it mirrors, to tell a holder whose body was replaced. + source: Body, + definition: ModelBody, + matrix: crate::Mat, +} + impl PlacedMesh { + /// Where `copy` (`source` transformed by `matrix`) stands relative to `source`'s opposite + /// hand. `None` shows it from its own mesh: a matrix that isn't a reflection of the first. + /// A copy of a copy goes by what its source is drawn from, which outlives that source. + pub(super) fn mirrored(source: &ModelBody, copy: &Body, matrix: &crate::Mat) -> Option { + let (cell, body, matrix) = match source.mirrored_mesh.as_deref() { + Some(drawn) => (&drawn.opposite_hand, &drawn.body, crate::mat_mul(matrix, &drawn.transform)), + None => (&source.opposite_hand, &source.body, *matrix), + }; + let hand = cell.get_or_init(|| OppositeHand { + source: body.clone(), + definition: ModelBody::new(String::new(), copy.clone(), source.feature), + matrix, + }); + if !same_triangles(&hand.source, body) { + return None; + } + Self::new(&hand.definition, &crate::mat_mul(&matrix, &crate::mat_inverse(&hand.matrix)?)) + } + /// Share the original definition, never a chain of previously placed meshes. A source's /// OnceLock lives with its immutable geometry, so edits get a new source automatically. pub(super) fn new(source: &ModelBody, transform: &crate::Mat) -> Option { if !proper_rigid(transform) { return None; } - Some(match source.mesh_placement.as_deref() { + Some(match source.mesh_placement.as_deref().or(source.mirrored_mesh.as_deref()) { Some(original) => Self { body: original.body.clone(), mesh: original.mesh.clone(), plans: original.plans.clone(), plan_meshes: original.plan_meshes.clone(), + opposite_hand: original.opposite_hand.clone(), transform: crate::mat_mul(transform, &original.transform), tolerance: original.tolerance, }, @@ -41,6 +77,7 @@ impl PlacedMesh { mesh: source.mesh.clone(), plans: source.plan.clone(), plan_meshes: source.plan_mesh.clone(), + opposite_hand: source.opposite_hand.clone(), transform: *transform, tolerance: source.display_tol(), }, @@ -75,7 +112,7 @@ impl PlacedMesh { let source = cell .get_or_init(|| { let plan = definition_plan(&self.body, self.plans.get(q.index())?, q, name)?; - self.body.display_mesh_of(&plan).ok().map(Arc::new) + self.body.mesh_of(&plan).ok().map(Arc::new) }) .clone()?; Some((source, self.transform)) @@ -98,6 +135,29 @@ impl PlacedMesh { } } +/// Whether two bodies mesh to the same triangles: the same shape, split along the same lines. +fn same_triangles(a: &Body, b: &Body) -> bool { + a.same_shape(b) + && match (a.split_lines(), b.split_lines()) { + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (None, None) => true, + _ => false, + } +} + +impl ModelBody { + /// Keep the meshes `old` holds when this body is the same shape: a feature evaluated again + /// that gives the same solids (an import, from its shared file) doesn't mesh them again. + pub(super) fn keep_meshes_of(&mut self, old: &ModelBody) { + if same_triangles(&self.body, &old.body) { + self.mesh = old.mesh.clone(); + self.plan = old.plan.clone(); + self.plan_mesh = old.plan_mesh.clone(); + self.opposite_hand = old.opposite_hand.clone(); + } + } +} + /// The display plan of a definition `body` at quality `q`, made once in `cell`. pub(super) fn definition_plan( body: &Body, @@ -105,7 +165,7 @@ pub(super) fn definition_plan( q: crate::display_quality::DisplayQuality, name: &str, ) -> Option> { - cell.get_or_init(|| match body.display_plan_angular(q.chord(body.size()), q.angle()) { + cell.get_or_init(|| match body.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.chord(body.size()), angle: Some(q.angle()) }) { Ok(plan) => Some(Arc::new(plan)), Err(e) => { log::debug!("{name}: no display plan ({e})"); @@ -117,7 +177,7 @@ pub(super) fn definition_plan( pub(super) fn reference_mesh(body: &Body, mesh: &OnceLock>, tolerance: f64) -> Arc { mesh.get_or_init(|| { - let mut mesh = body.reference_display_mesh_angular(tolerance, kernel::DISPLAY_ANGLE).unwrap_or_default(); + let mut mesh = body.mesh(&solidcraft_kernel::MeshTolerance { chord: tolerance, angle: Some(kernel::DISPLAY_ANGLE) }).unwrap_or_default(); if let Some((positions, triangles)) = body.triangle_mesh() { mesh.edges = mesh_outlines(positions, triangles); mesh.display_only_edges = true; @@ -156,11 +216,55 @@ fn mesh_outlines(positions: &[Vec3], triangles: &[[u32; 3]]) -> Vec> { [(_, _, i), (_, _, j)] => normal(*i as usize).zip(normal(*j as usize)).is_some_and(|(n, m)| n.dot(m) <= cos), _ => true, }; - if visible && let (Some(&a), Some(&b)) = (positions.get(a as usize), positions.get(b as usize)) { - edges.push(vec![a, b]); + if visible && positions.get(a as usize).is_some() && positions.get(b as usize).is_some() { + edges.push((a, b)); } } - edges + straight_runs(positions, &edges) +} + +/// The outline sides `sides` (vertex index pairs) as polylines: sides that run on straight +/// through a vertex no other outline side meets are one line. A mesh whose straight edges are +/// in pieces (a box exported at a grid's spacing) then has one outline per edge, as its CAD +/// model did, and a click on it measures the whole edge. +fn straight_runs(positions: &[Vec3], sides: &[(u32, u32)]) -> Vec> { + let mut at: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (i, &(a, b)) in sides.iter().enumerate() { + at.entry(a).or_default().push(i); + at.entry(b).or_default().push(i); + } + let point = |v: u32| positions.get(v as usize).copied().unwrap_or(Vec3::ZERO); + let other = |i: usize, v: u32| sides.get(i).map_or(v, |&(a, b)| if a == v { b } else { a }); + // The side that continues `i` straight on through `v`, when `v` joins exactly two. + let next = |i: usize, v: u32| -> Option { + let [p, q] = at.get(&v)?.as_slice() else { return None }; + let j = if *p == i { *q } else { *p }; + let (into, out) = ((point(v) - point(other(i, v))).normalized()?, (point(other(j, v)) - point(v)).normalized()?); + (into.dot(out) > 1.0 - 1e-9).then_some(j) + }; + let mut used = vec![false; sides.len()]; + // Marks side `i` used; false when it already was. + let mut take = |i: usize| used.get_mut(i).is_some_and(|u| !std::mem::replace(u, true)); + let mut runs = Vec::new(); + for (i, &(a, b)) in sides.iter().enumerate() { + if !take(i) { + continue; + } + let mut run = std::collections::VecDeque::from([a, b]); + for (mut side, mut end, front) in [(i, b, false), (i, a, true)] { + while let Some(j) = next(side, end).filter(|j| take(*j)) { + end = other(j, end); + side = j; + if front { + run.push_front(end); + } else { + run.push_back(end); + } + } + } + runs.push(run.into_iter().map(point).collect()); + } + runs } /// Only proper rotations and translations preserve triangle winding, normal lengths and the @@ -178,13 +282,14 @@ fn proper_rigid(m: &crate::Mat) -> bool { } #[cfg(test)] mod tests { - use solidcraft_geom::{Plane, Vec2}; + use solidcore_record::{Plane, Vec2}; use super::*; #[test] fn mesh_outlines_keep_boundaries_and_creases_without_smooth_facet_lines() { - for (degrees, expected) in [(0.0f64, 4), (15.0, 4), (30.0, 5), (45.0, 5), (90.0, 5)] { + // Flat (0 degrees), the sides from Y through the origin to -Y run straight on: one line. + for (degrees, expected) in [(0.0f64, 3), (15.0, 4), (30.0, 5), (45.0, 5), (90.0, 5)] { let angle = degrees.to_radians(); let p = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(0., -angle.cos(), angle.sin())]; let triangles = [[0, 1, 2], [1, 0, 3]]; @@ -217,6 +322,12 @@ mod tests { let edges = mesh_outlines(&p, &triangles); assert_eq!(edges.len(), 2 * n as usize); assert!(edges.iter().all(|e| e[0].z == e[1].z)); + // A straight edge in pieces (a node at its middle, where the facets of the face meet) + // is one outline; its corners stay corners. + let p = [Vec3::ZERO, Vec3::X * 2., Vec3::new(2., 1., 0.), Vec3::Y, Vec3::X]; + let edges = mesh_outlines(&p, &[[0, 4, 3], [4, 1, 2], [4, 2, 3]]); + assert_eq!(edges.len(), 4, "{edges:?}"); + assert!(edges.iter().any(|e| e == &[Vec3::ZERO, Vec3::X, Vec3::X * 2.] || e == &[Vec3::X * 2., Vec3::X, Vec3::ZERO]), "{edges:?}"); // Bad indices and zero-area facets do not invent outlines or panic. assert!(mesh_outlines(&[Vec3::ZERO, Vec3::X, Vec3::X * 2.], &[[0, 1, 99], [0, 1, 2]]).is_empty()); } @@ -401,18 +512,18 @@ mod tests { let mut state = crate::ModelState::default(); state.bodies.push(ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2., 8.).unwrap(), 1)); let mut cache = super::super::PlacedBodies::default(); - let before = super::super::world_state_reusing(&doc, &state, &mut cache); + let before = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); assert!(state.bodies[0].cached_mesh().is_none(), "placing bodies must remain lazy"); let old = before.bodies[0].mesh(); assert!(state.bodies[0].cached_mesh().is_some()); let (_, work) = kernel::profile::capture(|| before.bodies[1].mesh()); assert_eq!(work.tessellate_ms, 0., "the second instance shares the first one's triangulation"); doc.occurrences.iter_mut().find(|o| o.id == first).unwrap().transform = crate::rigid(Vec3::new(30., 0., 0.), Vec3::ZERO, Vec3::Y, 0.9); - let moved = super::super::world_state_reusing(&doc, &state, &mut cache); + let moved = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); let (_, work) = kernel::profile::capture(|| moved.bodies[0].mesh()); assert_eq!(work.tessellate_ms, 0., "a new pose shares the same definition"); state.bodies[0] = ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 4., 8.).unwrap(), 1); - let edited = super::super::world_state_reusing(&doc, &state, &mut cache); + let edited = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); assert!(state.bodies[0].cached_mesh().is_none()); let new = edited.bodies[0].mesh(); assert!(state.bodies[0].cached_mesh().is_some(), "changed geometry warms its new definition cache"); @@ -431,12 +542,12 @@ mod tests { let mut state = crate::ModelState::default(); state.bodies.push(ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2., 8.).unwrap(), 1)); let mut cache = super::super::PlacedBodies::default(); - let before = super::super::world_state_reusing(&doc, &state, &mut cache); + let before = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); let meshes: Vec<_> = before.bodies.iter().map(|b| b.mesh()).collect(); // The middle placement moves: the other two are taken as they were, it is placed again. doc.occurrences.iter_mut().find(|o| o.id == second).unwrap().transform = crate::rigid(Vec3::new(0., 40., 0.), Vec3::ZERO, Vec3::X, 0.2); - let after = super::super::world_state_reusing(&doc, &state, &mut cache); - let fresh = super::super::world_state_reusing(&doc, &state, &mut super::super::PlacedBodies::default()); + let after = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); + let fresh = super::super::world_state_reusing(&doc, &state, &mut super::super::PlacedBodies::default()).unwrap(); let names = |st: &crate::ModelState| st.bodies.iter().map(|b| b.name.clone()).collect::>(); assert_eq!(names(&after), names(&fresh)); assert_eq!(names(&after), names(&before)); diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rs index 2d276d4de..b5dcccf95 100644 --- a/crates/doc/src/placement_reuse.rs +++ b/crates/doc/src/placement_reuse.rs @@ -31,6 +31,7 @@ impl Model { return false; } self.evaluate(doc); + self.mark_fingerprinted(doc); if !self.no_cache && self.primed.is_none() && self.placement_local { self.placement_inputs = Some(Inputs { document: doc.clone(), state: Arc::downgrade(&self.state()) }); } @@ -38,13 +39,16 @@ impl Model { } /// [`Model::refingerprint`] for a shared document: a proof that held for the results before - /// is kept for `doc`, since nothing was built differently (pinned body names, say). - pub fn refingerprint_shared(&mut self, doc: &Arc) { + /// is kept for `doc`, since nothing was built differently (pinned body names, say). The + /// first `keep` results keep their fingerprints: [`Model::pinned_prefix`] of the document + /// before the pins, or 0. + pub fn refingerprint_shared(&mut self, doc: &Arc, keep: usize) { let proven = !self.no_cache && self.primed.is_none() && self.placement_inputs.as_ref().is_some_and(|inputs| inputs.state.upgrade().is_some_and(|state| Arc::ptr_eq(&state, &self.state()))) && !self.is_stale(); - self.refingerprint(doc); + self.refingerprint_from(doc, keep); + self.mark_fingerprinted(doc); if proven && self.placement_local { self.placement_inputs = Some(Inputs { document: doc.clone(), state: Arc::downgrade(&self.state()) }); } @@ -64,6 +68,21 @@ fn local_plane(plane: &PlaneRef, depth: usize) -> bool { } } +/// Whether no feature after the mirror `f` can cut, join or otherwise build on bodies: only +/// features that read none, and further mirrors, which copy them. A boolean depends on how a +/// copy's revolved faces are turned, so a copy it may reach is made with +/// [`solidcraft_kernel::transform_matrix`]; one that is only shown needs no search for that. It +/// depends on the design alone, so a design evaluates the same however it was reached. +pub(super) fn copies_only_shown(doc: &Document, f: &Feature) -> bool { + let mut later = doc.features.iter().skip_while(|g| g.id != f.id).skip(1); + let mut components = std::collections::HashMap::with_capacity(doc.features.len()); + for g in &doc.features { + components.entry(g.id).or_insert(g.component); + } + let copies = |g: &Feature| matches!(&g.kind, FeatureKind::Mirror { features, combine: false, .. } if features.is_empty()); + later.all(|g| copies(g) || local_geometry(g, &components)) +} + pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap) -> bool { // Persistent picked-face/edge attachments can move an otherwise literal input. if !f.face_names.is_empty() || !f.edge_names.is_empty() || !f.edge_refs.is_empty() { @@ -91,6 +110,8 @@ pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap to, to_offset: _, from, + corner: _, + to_body_apart: _, } = extent; to.is_none() && from.is_none() && !through_all && components.get(&sketch.0) == Some(&f.component) } @@ -129,6 +150,7 @@ fn same_geometry_inputs(a: &Document, b: &Document) -> bool { text_params, next_component_color_index, materials, + print_faces, user_materials, appearances, body_components, @@ -164,6 +186,7 @@ fn same_geometry_inputs(a: &Document, b: &Document) -> bool { && *text_params == b.text_params && *next_component_color_index == b.next_component_color_index && *materials == b.materials + && *print_faces == b.print_faces && *user_materials == b.user_materials && *appearances == b.appearances && *body_components == b.body_components @@ -190,6 +213,7 @@ fn same_feature(a: &Feature, b: &Feature) -> bool { edge_names, face_names, participants, + touching, shell_piece_order, kernel_piece_order, inserted, @@ -206,6 +230,7 @@ fn same_feature(a: &Feature, b: &Feature) -> bool { && *edge_names == b.edge_names && *face_names == b.face_names && *participants == b.participants + && *touching == b.touching && *shell_piece_order == b.shell_piece_order && *kernel_piece_order == b.kernel_piece_order && *inserted == b.inserted diff --git a/crates/doc/src/point_cloud.rs b/crates/doc/src/point_cloud.rs index 25ad4e176..ab174333d 100644 --- a/crates/doc/src/point_cloud.rs +++ b/crates/doc/src/point_cloud.rs @@ -5,12 +5,14 @@ //! cloud's own `origin` (double precision), so a scan far from the design's origin keeps its //! detail. +use solidcraft_geom::prelude::*; use std::sync::Arc; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::canvas::{base64_decode, base64_encode}; +pub use crate::point_cloud_complex::{Column, Complex, Filter, Floats, Keep, MAX_COLUMNS, MAX_NAMES, Names}; use crate::{DocError, IDENTITY, Mat, Result}; /// Most points one cloud may hold. @@ -19,6 +21,10 @@ pub const MAX_POINTS: usize = 20_000_000; pub const MAX_COORD: f64 = 1e9; /// Point sizes on screen (pixels). pub const POINT_SIZE: std::ops::RangeInclusive = 0.5..=16.0; +/// Most filters on one cloud. +pub const MAX_FILTERS: usize = 8; +/// Properties every cloud has besides its file's: the coordinates in the design. +pub const COORDINATES: [&str; 3] = ["x", "y", "z"]; /// Length units a point cloud file may be in, and millimetres per unit. pub const UNITS: [(&str, f64); 5] = [("mm", 1.0), ("cm", 10.0), ("m", 1000.0), ("in", 25.4), ("ft", 304.8)]; @@ -65,6 +71,24 @@ pub struct PointCloud { pub height_range: Option<[f64; 2]>, #[serde(default = "yes")] pub visible: bool, + /// The file's other properties of the points. + #[serde(default, skip_serializing_if = "Complex::is_empty")] + pub complex: Complex, + /// The property `color_by: property` colours by. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color_property: Option, + /// Only the points every filter keeps are shown. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub filters: Vec, +} + +/// Where a property's values come from. +#[derive(Clone, Copy, Debug)] +pub enum Source<'a> { + /// A coordinate of each point in the design. + Coordinate(usize), + /// A column of the file: each point's. + Column(&'a [f32]), } /// How a cloud's points are coloured. @@ -78,6 +102,8 @@ pub enum ColorBy { Single, /// By height in the design: blue low, through cyan, green and yellow, to red high. Height, + /// By `color_property`: the height ramp over its range or, for whole numbers, a palette. + Property, } impl ColorBy { @@ -90,6 +116,7 @@ impl ColorBy { "file" => Some(ColorBy::File), "single" => Some(ColorBy::Single), "height" => Some(ColorBy::Height), + "property" => Some(ColorBy::Property), _ => None, } } @@ -98,6 +125,7 @@ impl ColorBy { ColorBy::File => "file", ColorBy::Single => "single", ColorBy::Height => "height", + ColorBy::Property => "property", } } } @@ -120,6 +148,27 @@ pub fn height_ramp(t: f64) -> [u8; 3] { std::array::from_fn(|c| (a[c] * (1.0 - f) + b[c] * f).round().clamp(0.0, 255.0) as u8) } +/// Colours of whole-number labels, the label modulo their count; negative labels are grey. +pub const PALETTE: [[u8; 3]; 10] = [ + [240, 140, 40], + [245, 205, 65], + [230, 65, 65], + [165, 75, 190], + [65, 190, 115], + [75, 150, 220], + [240, 120, 180], + [140, 105, 75], + [120, 215, 215], + [190, 190, 80], +]; + +pub fn label_color(v: f64) -> [u8; 3] { + if !(v.is_finite() && v >= 0.0) { + return PLAIN.map(byte); + } + PALETTE[(v.round() as usize) % PALETTE.len()] +} + /// A colour channel (0..1) as a byte. pub fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 @@ -182,15 +231,57 @@ impl PointCloud { let (lo, hi) = (at(HEIGHT_TAIL)?, at(1.0 - HEIGHT_TAIL)?); Some(if hi - lo > 1e-9 { [lo, hi] } else { [lo - 0.5, lo + 0.5] }) } + /// The property colours come from: a column, or a coordinate (`z` for the height ramp). + pub fn colored_property(&self) -> Option<&str> { + match self.color_by { + ColorBy::Height => Some("z"), + ColorBy::Property => self.color_property.as_deref(), + ColorBy::File | ColorBy::Single => None, + } + } + /// Where the values of `name` are: a coordinate of each point or a column of the file. + pub fn source(&self, name: &str) -> Option> { + if let Some(k) = COORDINATES.iter().position(|n| *n == name) { + return Some(Source::Coordinate(k)); + } + self.complex.column(name).map(|col| Source::Column(&col.values.0)) + } + /// Every property the cloud can be coloured and filtered by: its coordinates, then its columns. + pub fn property_names(&self) -> impl Iterator { + COORDINATES.into_iter().chain(self.complex.columns.iter().map(|c| c.name.as_str())) + } + /// The smallest and largest value of a property, the coordinates in the design. + pub fn span(&self, property: &str) -> Option<[f64; 2]> { + if let Some(span) = self.complex.span(property) { + return Some(span); + } + let k = COORDINATES.iter().position(|n| *n == property)?; + let v = self.world_corners()?.map(|p| [p.x, p.y, p.z][k]); + Some([v.iter().copied().fold(f64::INFINITY, f64::min), v.iter().copied().fold(f64::NEG_INFINITY, f64::max)]) + } + /// The ramp's range as far as it can be told without the elements: the one set, or else the + /// coloured property's span within every range filtering it. The automatic range colouring + /// by a property is exactly what the filters keep + /// ([`crate::point_cloud_distribution::color_range`]), which this bounds. + pub fn color_range(&self) -> Option<[f64; 2]> { + if self.height_range.is_some() { + return self.height_range; + } + let property = self.colored_property()?; + let span = if self.color_by == ColorBy::Height { self.auto_height_range() } else { self.span(property) }?; + let shown = + self.filters.iter().filter(|f| f.property == property).filter_map(Filter::range).fold(span, |[lo, hi], [a, b]| [lo.max(a), hi.min(b)]); + Some(if shown[0] <= shown[1] { crate::point_cloud_distribution::ramp_range(shown) } else { span }) + } /// The heights the height ramp runs between now: the cloud's own, else the automatic ones. pub fn height_range_now(&self) -> Option<[f64; 2]> { self.height_range.or_else(|| self.auto_height_range()) } - /// The colour of each point (by index) as the cloud is shown. - pub fn shade(&self) -> impl Fn(usize) -> [u8; 3] + '_ { + /// The colour of each point (by index) as the cloud is shown, the ramp over `range`. + pub fn shade(&self, range: Option<[f64; 2]>) -> impl Fn(usize) -> [u8; 3] + '_ { let single = self.color.unwrap_or(PLAIN).map(byte); let plain = PLAIN.map(byte); - let range = if self.color_by == ColorBy::Height { self.height_range_now() } else { None }; + let column = self.color_property.as_deref().and_then(|n| self.complex.column(n)); move |i| match self.color_by { ColorBy::File => self.colors.get(i).unwrap_or(plain), ColorBy::Single => single, @@ -198,6 +289,14 @@ impl PointCloud { (Some([lo, hi]), Some(p)) => height_ramp((self.world_z(p) - lo) / (hi - lo)), _ => plain, }, + ColorBy::Property => match (column, column.and_then(|c| c.values.0.get(i))) { + (Some(c), Some(v)) if c.integer => label_color(f64::from(*v)), + (Some(_), Some(v)) => match range { + Some([lo, hi]) if hi > lo => height_ramp((f64::from(*v) - lo) / (hi - lo)), + _ => plain, + }, + _ => plain, + }, } } /// The corners of the box around the points, placed in the design (mm). @@ -240,6 +339,18 @@ impl PointCloud { if !rigid(&self.transform) { return bad("its placement is not a rigid move"); } + self.complex.check(self.points.len())?; + if self.filters.len() > MAX_FILTERS + || self.filters.iter().any(|f| match &f.keep { + Keep::Range { range: [lo, hi] } => !(lo.is_finite() && hi.is_finite() && lo <= hi), + Keep::Values { values } => values.len() > MAX_NAMES, + }) + { + return bad("its filters are not ranges, lowest first"); + } + if self.color_by == ColorBy::Property && self.color_property.is_none() { + return bad("it is coloured by a property without naming it"); + } Ok(()) } } @@ -422,6 +533,9 @@ mod tests { color: None, height_range: None, visible: true, + complex: Complex::default(), + color_property: None, + filters: Vec::new(), } } @@ -443,6 +557,20 @@ mod tests { assert_eq!((unit_scale("M"), unit_scale("yd")), (Some(1000.0), None)); } + #[test] + fn the_ramp_spans_what_is_shown_unless_set() { + let mut c = cloud(vec![0.0; 9], Vec::new()); + c.complex.columns.push(Column { name: "t".into(), integer: false, values: Floats(vec![0.0, 10.0, 20.0].into()) }); + (c.color_by, c.color_property) = (ColorBy::Property, Some("t".into())); + assert_eq!(c.color_range(), Some([0.0, 20.0]), "the whole span"); + c.filters = vec![Filter { property: "t".into(), keep: Keep::Range { range: [5.0, 50.0] } }]; + assert_eq!(c.color_range(), Some([5.0, 20.0]), "the span within the filter"); + c.filters.push(Filter { property: "layer".into(), keep: Keep::Range { range: [0.0, 1.0] } }); + assert_eq!(c.color_range(), Some([5.0, 20.0]), "another property's filter changes nothing"); + c.height_range = Some([1.0, 2.0]); + assert_eq!(c.color_range(), Some([1.0, 2.0]), "a range set is kept"); + } + #[test] fn damaged_clouds_are_refused() { // Not whole points, not finite, not base64. @@ -474,26 +602,26 @@ mod tests { let colors: Vec = (0..102).flat_map(|i| [i as u8, 7, 9]).collect(); let mut c = cloud(values, colors); c.origin = Vec3::ZERO; - assert_eq!(c.shade()(3), [3, 7, 9], "the file's colours"); + assert_eq!(c.shade(c.color_range())(3), [3, 7, 9], "the file's colours"); c.colors = Colors::default(); - assert_eq!(c.shade()(3), PLAIN.map(byte), "none: plain"); + assert_eq!(c.shade(c.color_range())(3), PLAIN.map(byte), "none: plain"); c.color_by = ColorBy::Single; c.color = Some([1.0, 0.5, 0.0]); - assert_eq!(c.shade()(50), [255, 128, 0]); + assert_eq!(c.shade(c.color_range())(50), [255, 128, 0]); // The stray point doesn't stretch the automatic range. c.color_by = ColorBy::Height; // 102 points: the 2nd and the 99th (of 0…101) once sorted. assert_eq!(c.auto_height_range(), Some([2.0, 99.0])); { - let shade = c.shade(); + let shade = c.shade(c.color_range()); assert_eq!((shade(0), shade(100), shade(101)), (height_ramp(0.0), height_ramp(1.0), height_ramp(1.0))); assert_eq!(shade(50), height_ramp(48.0 / 97.0)); } // A range of its own; moved up 100 mm, everything is above it. c.height_range = Some([0.0, 50.0]); - assert_eq!(c.shade()(25), height_ramp(0.5)); + assert_eq!(c.shade(c.color_range())(25), height_ramp(0.5)); c.transform[3][2] = 100.0; - assert_eq!(c.shade()(0), height_ramp(1.0)); + assert_eq!(c.shade(c.color_range())(0), height_ramp(1.0)); assert_eq!((height_ramp(0.0), height_ramp(1.0), height_ramp(f64::NAN)), ([40, 70, 200], [230, 70, 50], [40, 70, 200])); let back: PointCloud = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap(); assert_eq!(back, c); diff --git a/crates/doc/src/point_cloud_complex.rs b/crates/doc/src/point_cloud_complex.rs new file mode 100644 index 000000000..6635996c7 --- /dev/null +++ b/crates/doc/src/point_cloud_complex.rs @@ -0,0 +1,215 @@ +//! What a point cloud holds besides its points' places and colours: named numbers on its points +//! (a PLY file's other vertex properties), to colour the cloud by and to filter it with. Whole +//! numbers may have names (`role: 0 outer wall, 1 inner wall` in a PLY file's comments): they +//! are labels, filtered by a set of values rather than a range. + +use std::sync::Arc; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::canvas::{base64_decode, base64_encode}; +use crate::point_cloud::MAX_POINTS; +use crate::{DocError, Result}; + +/// Most named numbers per point. +pub const MAX_COLUMNS: usize = 64; + +/// One named number on every point. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Column { + pub name: String, + /// Whole numbers (labels, counts): coloured by a palette rather than a ramp. + #[serde(default)] + pub integer: bool, + pub values: Floats, +} + +impl Column { + /// The smallest and largest finite value. + pub fn span(&self) -> Option<[f64; 2]> { + let mut it = self.values.0.iter().filter(|v| v.is_finite()).map(|v| f64::from(*v)); + let first = it.next()?; + Some(it.fold([first, first], |[lo, hi], v| [lo.min(v), hi.max(v)])) + } +} + +/// The complex a cloud's points form: named numbers on the points, and the names of +/// whole-numbered ones. Points alone are a complex of dimension 0. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Complex { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub columns: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub names: Vec, +} + +/// Most named values of one label. +pub const MAX_NAMES: usize = 256; + +/// The names of a label's values. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Names { + pub property: String, + pub values: Vec<(i32, String)>, +} + +impl Names { + /// `property: 0 name, 1 another name, -1 none`, or `None` for any other text. + pub fn parse(text: &str) -> Option { + let (property, rest) = text.split_once(':')?; + let property = property.trim(); + if property.is_empty() || property.contains(char::is_whitespace) { + return None; + } + let values = rest + .split(',') + .map(|entry| { + let (value, name) = entry.trim().split_once(' ')?; + let name = name.trim(); + (!name.is_empty()).then(|| Some((value.parse::().ok()?, name.to_string()))).flatten() + }) + .collect::>>()?; + (!values.is_empty() && values.len() <= MAX_NAMES).then(|| Names { property: property.to_string(), values }) + } + pub fn name(&self, value: i32) -> Option<&str> { + self.values.iter().find(|(v, _)| *v == value).map(|(_, n)| n.as_str()) + } +} + +impl Complex { + pub fn is_empty(&self) -> bool { + self.columns.is_empty() && self.names.is_empty() + } + /// The column named `name`. + pub fn column(&self, name: &str) -> Option<&Column> { + self.columns.iter().find(|c| c.name == name) + } + /// The smallest and largest value named `name`. + pub fn span(&self, name: &str) -> Option<[f64; 2]> { + self.column(name).and_then(Column::span) + } + /// The names of `property`'s values, when it is a label. + pub fn names(&self, property: &str) -> Option<&Names> { + self.names.iter().find(|n| n.property == property).filter(|_| self.integer(property)) + } + /// Whether the values named `name` are whole numbers. + pub fn integer(&self, name: &str) -> bool { + self.column(name).is_some_and(|c| c.integer) + } + /// Every column has one number per point, the cloud having `points` points. + pub fn check(&self, points: usize) -> Result<()> { + let bad = |what: String| Err(DocError::Invalid(format!("point cloud properties: {what}"))); + if self.columns.len() > MAX_COLUMNS { + return bad("too many properties".into()); + } + for c in &self.columns { + if c.values.0.len() != points { + return bad(format!("property `{}` does not have one number per point", c.name)); + } + } + if self.names.len() > MAX_COLUMNS || self.names.iter().any(|n| n.values.is_empty() || n.values.len() > MAX_NAMES) { + return bad("too many named values".into()); + } + Ok(()) + } +} + +/// Which points are shown: those whose property lies in a range (both ends included), or, for a +/// label, is one of a set of values. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Filter { + pub property: String, + #[serde(flatten)] + pub keep: Keep, +} + +/// The values a filter keeps. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum Keep { + Range { range: [f64; 2] }, + Values { values: Vec }, +} + +impl Filter { + pub fn range(&self) -> Option<[f64; 2]> { + match &self.keep { + Keep::Range { range } => Some(*range), + Keep::Values { .. } => None, + } + } +} + +/// Numbers, shared between copies of the design. +#[derive(Clone, Debug, Default)] +pub struct Floats(pub Arc<[f32]>); + +impl PartialEq for Floats { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) || self.0.iter().map(|v| v.to_bits()).eq(other.0.iter().map(|v| v.to_bits())) + } +} + +/// The largest base64 text of `n` four-byte words. +fn base64_len(n: usize) -> usize { + (n * 4).div_ceil(3) * 4 + 16 +} + +fn words<'de, D: Deserializer<'de>>(d: D, max: usize) -> std::result::Result, D::Error> { + let s = String::deserialize(d)?; + if s.len() > base64_len(max) { + return Err(serde::de::Error::custom("too many numbers")); + } + let b = base64_decode(&s).ok_or_else(|| serde::de::Error::custom("numbers are not base64"))?; + if !b.len().is_multiple_of(4) { + return Err(serde::de::Error::custom("numbers are not whole four-byte words")); + } + Ok(b.as_chunks::<4>().0.to_vec()) +} + +impl Serialize for Floats { + fn serialize(&self, s: S) -> std::result::Result { + s.serialize_str(&base64_encode(&self.0.iter().flat_map(|v| v.to_le_bytes()).collect::>())) + } +} + +impl<'de> Deserialize<'de> for Floats { + fn deserialize>(d: D) -> std::result::Result { + Ok(Floats(words(d, MAX_POINTS)?.into_iter().map(f32::from_le_bytes).collect())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn properties_round_trip_and_are_checked_against_the_points() { + let complex = Complex { + columns: vec![ + Column { name: "t".into(), integer: false, values: Floats(vec![0.0, 0.5, 1.0].into()) }, + Column { name: "role".into(), integer: true, values: Floats(vec![0.0, 4.0, 4.0].into()) }, + ], + names: Vec::new(), + }; + let back: Complex = serde_json::from_str(&serde_json::to_string(&complex).unwrap()).unwrap(); + assert_eq!(back, complex); + complex.check(3).unwrap(); + assert!(complex.check(2).is_err(), "three numbers for two points"); + assert_eq!(complex.span("role"), Some([0.0, 4.0])); + assert!(complex.integer("role") && !complex.integer("t") && !complex.integer("nope")); + // Named values make a label, and a filter keeps a range or a set of them. + let names = Names::parse("role: 0 outer wall, 4 bridge, -1 none").unwrap(); + assert_eq!((names.name(4), names.name(-1), names.name(2)), (Some("bridge"), Some("none"), None)); + for text in ["t: seconds since the start", "role 0 wall", ": 0 a", "role: x wall", "role: 0 "] { + assert!(Names::parse(text).is_none(), "{text}"); + } + let mut named = complex.clone(); + named.names = vec![names, Names::parse("t: 0 zero").unwrap()]; + assert!(named.names("role").is_some() && named.names("t").is_none(), "only whole numbers are labels"); + let set: Filter = serde_json::from_str(r#"{"property": "role", "values": [0, 4]}"#).unwrap(); + let range: Filter = serde_json::from_str(r#"{"property": "t", "range": [1, 3]}"#).unwrap(); + assert_eq!((set.range(), range.range()), (None, Some([1.0, 3.0]))); + assert_eq!(serde_json::to_value(&set).unwrap(), serde_json::json!({"property": "role", "values": [0, 4]})); + } +} diff --git a/crates/doc/src/point_cloud_distribution.rs b/crates/doc/src/point_cloud_distribution.rs new file mode 100644 index 000000000..4d9e052f8 --- /dev/null +++ b/crates/doc/src/point_cloud_distribution.rs @@ -0,0 +1,246 @@ +//! How much of a point cloud lies at each value of one of its properties, over what its filters +//! keep: the histograms the Edit Point Cloud card draws in its range tracks, split into the +//! colours the view draws, and the values where a label changes along a property, which the +//! tracks snap to. +//! +//! Each point weighs the same, the cloud weighing 1. A range filter keeps the points between its +//! ends, as the view does; a filter by values keeps those whose rounded value it holds; the +//! colour sorts the points kept into the colours they are drawn in. The values the points kept +//! take, from the least to the greatest, are the ramp's automatic range: the colours span exactly +//! what is shown. + +use crate::point_cloud::{ColorBy, Filter, Keep, PALETTE, PointCloud, Source}; + +/// Most bins of one histogram. +pub const MAX_BINS: usize = 8192; + +/// What the histograms need of a cloud's geometry, worked out once for its points. +#[derive(Clone, Debug, Default)] +pub struct Geometry { + /// Each point in the design. + world: Vec<[f64; 3]>, +} + +impl Geometry { + pub fn of(c: &PointCloud) -> Geometry { + Geometry { world: (0..c.len()).map(|i| c.world_point(i).map_or([0.0; 3], |p| [p.x, p.y, p.z])).collect() } + } +} + +/// How a histogram is split by colour, into slots; the last slot holds what has no value to be +/// coloured by. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Colour<'a> { + /// One colour. + One, + /// The ramp over `range` of `property`, in `bands` equal bands; below and above the range + /// count with the first and the last. + Ramp { property: &'a str, range: [f64; 2], bands: usize }, + /// The palette of a whole-numbered `property`: a slot per colour of [`PALETTE`], then one + /// for negative values. + Palette { property: &'a str }, +} + +impl Colour<'_> { + /// How many slots the histogram has. + pub fn slots(&self) -> usize { + match self { + Colour::One => 1, + Colour::Ramp { bands, .. } => bands + 1, + Colour::Palette { .. } => PALETTE.len() + 2, + } + } + fn property(&self) -> Option<&str> { + match self { + Colour::One => None, + Colour::Ramp { property, .. } | Colour::Palette { property } => Some(property), + } + } + /// How a property's values are cut into bands, and the slot of each band. + fn cut(&self) -> Option { + match *self { + Colour::One => None, + Colour::Ramp { range: [lo, hi], bands, .. } => Some(Cut::Grid { start: lo, step: (hi - lo) / bands as f64, count: bands + 1 }), + Colour::Palette { .. } => Some(INTEGERS), + } + } + fn slot(&self, band: usize) -> usize { + match *self { + Colour::One => 0, + Colour::Ramp { bands, .. } => band.saturating_sub(1).min(bands.saturating_sub(1)), + Colour::Palette { .. } => match integer(band) { + Some(v) if v >= 0 => v as usize % PALETTE.len(), + _ => PALETTE.len(), + }, + } + } +} + +/// How much lies in each bin, by colour slot. +#[derive(Clone, Debug, PartialEq)] +pub struct Histogram { + pub bins: usize, + /// `slots[s][b]`: the measure of slot `s` in bin `b`. + pub slots: Vec>, + /// The least and the greatest value the points kept take, within the axis or not. + pub extent: Option<[f64; 2]>, +} + +/// Where values are cut into bands, by increasing values. +#[derive(Clone, Copy, Debug)] +enum Cut { + /// Below (band 0), within (1, both ends included) and above (2) a range. + Range([f64; 2]), + /// `count` values `start + k·step`: band 0 lies below the first, band `k` from the `k`th on. + Grid { start: f64, step: f64, count: usize }, +} + +/// The bands of whole numbers: band `k` holds the values rounding to `k - 2³¹`. +const INTEGERS: Cut = Cut::Grid { start: 0.5 - 2_147_483_648.0, step: 1.0, count: u32::MAX as usize }; + +/// The whole number a band of [`INTEGERS`] holds. +fn integer(band: usize) -> Option { + i64::try_from(band).ok().map(|k| k - 2_147_483_648) +} + +impl Cut { + fn band(&self, v: f64) -> usize { + match *self { + Cut::Range([a, b]) => usize::from(v >= a) + usize::from(v > b), + Cut::Grid { start, step, count } => { + if !(v >= start) { + return 0; + } + (((v - start) / step).floor() as usize).saturating_add(1).min(count) + } + } + } +} + +/// A filter as a cut and the bands it keeps. +struct Kept<'a> { + cut: Cut, + values: Option<&'a [i32]>, +} + +impl Kept<'_> { + fn of(f: &Filter) -> Kept<'_> { + match &f.keep { + Keep::Range { range } => Kept { cut: Cut::Range(*range), values: None }, + Keep::Values { values } => Kept { cut: INTEGERS, values: Some(values) }, + } + } + fn keeps(&self, v: f64) -> bool { + let band = self.cut.band(v); + match self.values { + None => band == 1, + Some(values) => integer(band).is_some_and(|v| values.iter().any(|k| i64::from(*k) == v)), + } + } +} + +/// The value of `s` at point `i`. +fn value(s: Source, i: usize, world: &[[f64; 3]]) -> f64 { + match s { + Source::Coordinate(k) => world.get(i).and_then(|p| p.get(k)).copied().unwrap_or(f64::NAN), + Source::Column(v) => v.get(i).map_or(f64::NAN, |x| f64::from(*x)), + } +} + +/// How much of the cloud lies in each of `bins` bins over `axis` of `property`, by `colour`, +/// within every one of `filters`; `None` for an axis or a number of bins it can't have. +pub fn histogram( + c: &PointCloud, + g: &Geometry, + property: &str, + axis: [f64; 2], + bins: usize, + colour: &Colour, + filters: &[Filter], +) -> Option { + if !(axis[0].is_finite() && axis[1].is_finite() && axis[1] > axis[0]) || bins == 0 || bins > MAX_BINS { + return None; + } + if let Colour::Ramp { range: [lo, hi], bands, .. } = *colour + && !(hi > lo && bands > 0 && bands <= MAX_BINS) + { + return None; + } + let slots = colour.slots(); + let mut out = vec![vec![0.0; bins]; slots]; + let mut extent = None; + let Some(p) = c.source(property) else { return Some(Histogram { bins, slots: out, extent }) }; + // A point is not filtered by a property the cloud doesn't have, as in the view. + let kept: Vec<(Kept, Source)> = filters.iter().filter_map(|f| Some((Kept::of(f), c.source(&f.property)?))).collect(); + let coloured = colour.property().and_then(|n| c.source(n)); + let (colour_cut, plain) = (colour.cut(), slots - 1); + let m = 1.0 / g.world.len().max(1) as f64; + let width = (axis[1] - axis[0]) / bins as f64; + for i in 0..g.world.len() { + if !kept.iter().all(|(k, s)| k.keeps(value(*s, i, &g.world))) { + continue; + } + let v = value(p, i, &g.world); + if !v.is_finite() { + continue; + } + extent = Some(extent.map_or([v, v], |[lo, hi]: [f64; 2]| [lo.min(v), hi.max(v)])); + if !(v >= axis[0] && v <= axis[1]) { + continue; + } + let slot = match (colour_cut, coloured) { + (Some(cut), Some(s)) => colour.slot(cut.band(value(s, i, &g.world))), + (Some(_), None) => plain, + (None, _) => 0, + }; + // The last bin holds the axis' upper end too. + let bin = (((v - axis[0]) / width).floor() as usize).min(bins - 1); + if let Some(b) = out.get_mut(slot).and_then(|s| s.get_mut(bin)) { + *b += m; + } + } + Some(Histogram { bins, slots: out, extent }) +} + +/// A range for a ramp from the values it spans: a single value gets one unit around it. +pub fn ramp_range([lo, hi]: [f64; 2]) -> [f64; 2] { + if hi > lo { [lo, hi] } else { [lo - 0.5, lo + 0.5] } +} + +/// The ramp's range: the one set; else, coloured by a property, exactly the values it takes over +/// what `filters` keep (the cloud's own bound, [`PointCloud::color_range`], when nothing is +/// kept); coloured by height, the cloud's own (its points but the highest and lowest few). +pub fn color_range(c: &PointCloud, g: &Geometry, filters: &[Filter]) -> Option<[f64; 2]> { + color_range_by(c, |property, axis| histogram(c, g, property, axis, 1, &Colour::One, filters).and_then(|h| h.extent)) +} + +/// [`color_range`], with the values the coloured property takes over what is kept given by +/// `extent` (of the property and an axis over its span): worked out elsewhere, or not yet. +pub fn color_range_by(c: &PointCloud, extent: impl FnOnce(&str, [f64; 2]) -> Option<[f64; 2]>) -> Option<[f64; 2]> { + let property = c.colored_property()?; + if c.height_range.is_some() || c.color_by != ColorBy::Property { + return c.color_range(); + } + let axis = ramp_range(c.span(property)?); + extent(property, axis).map(ramp_range).or_else(|| c.color_range()) +} + +/// The values of `property` where the whole-numbered `label` changes, point after point in order +/// of `property`, lowest first. +pub fn label_changes(c: &PointCloud, g: &Geometry, label: &str, property: &str) -> Vec { + let (Some(p), Some(l)) = (c.source(property), c.source(label)) else { return Vec::new() }; + let mut at: Vec<(f64, i64)> = (0..g.world.len()) + .filter_map(|i| { + let (v, l) = (value(p, i, &g.world), value(l, i, &g.world)); + v.is_finite().then(|| (v, if l.is_finite() { l.round() as i64 } else { i64::MIN })) + }) + .collect(); + at.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec = at.windows(2).filter(|w| w[0].1 != w[1].1).map(|w| w[1].0).collect(); + out.dedup(); + out +} + +#[cfg(test)] +#[path = "point_cloud_distribution_tests.rs"] +mod tests; diff --git a/crates/doc/src/point_cloud_distribution_tests.rs b/crates/doc/src/point_cloud_distribution_tests.rs new file mode 100644 index 000000000..cee5d0044 --- /dev/null +++ b/crates/doc/src/point_cloud_distribution_tests.rs @@ -0,0 +1,125 @@ +use solidcore_record::Vec3; + +use super::*; +use crate::IDENTITY; +use crate::point_cloud::{ColorBy, Colors, Column, Complex, Floats, Points}; + +/// A cloud of `points` with `columns` on them. +fn cloud(points: &[[f32; 3]], columns: Vec) -> PointCloud { + PointCloud { + id: 1, + name: "c".into(), + file: String::new(), + origin: Vec3::new(0.0, 0.0, 0.0), + points: Points::new(points.iter().flatten().copied().collect::>().into()), + colors: Colors::default(), + source_points: points.len() as u64, + units: "mm".into(), + transform: IDENTITY, + point_size: 2.0, + color_by: ColorBy::File, + color: None, + height_range: None, + visible: true, + complex: Complex { columns, names: Vec::new() }, + color_property: None, + filters: Vec::new(), + } +} + +fn column(name: &str, integer: bool, values: &[f32]) -> Column { + Column { name: name.into(), integer, values: Floats(values.to_vec().into()) } +} + +fn range(property: &str, range: [f64; 2]) -> Filter { + Filter { property: property.into(), keep: Keep::Range { range } } +} + +fn close(a: &[f64], b: &[f64]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +/// Ten points along x, `t` the same as x. +fn row() -> PointCloud { + let points: Vec<[f32; 3]> = (0..10).map(|i| [i as f32 + 0.5, 0.0, 0.0]).collect(); + let t: Vec = points.iter().map(|p| p[0]).collect(); + cloud(&points, vec![column("t", false, &t)]) +} + +#[test] +fn each_point_weighs_alike_and_a_range_keeps_those_within_it() { + let c = row(); + let g = Geometry::of(&c); + let all = histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[]).unwrap(); + assert!(close(&all.slots[0], &[0.2; 5])); + // Kept from t = 2 to 5: three points, ends included. + let kept = histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[range("t", [2.0, 5.0])]).unwrap(); + assert!(close(&kept.slots[0], &[0.0, 0.2, 0.1, 0.0, 0.0])); + // Filtered by another property: x from 0 to 4 keeps t from 0 to 4. + let by_x = histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[range("x", [0.0, 4.0])]).unwrap(); + assert!(close(&by_x.slots[0], &[0.2, 0.2, 0.0, 0.0, 0.0])); + // A filter on a property the cloud doesn't have keeps everything, as in the view. + assert_eq!(histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[range("nope", [0.0, 1.0])]), Some(all)); + // An axis or a number of bins it can't have. + for (axis, bins) in [([1.0, 1.0], 4), ([0.0, f64::NAN], 4), ([0.0, 1.0], 0), ([0.0, 1.0], MAX_BINS + 1)] { + assert!(histogram(&c, &g, "t", axis, bins, &Colour::One, &[]).is_none()); + } +} + +#[test] +fn colours_split_what_is_kept() { + // Four points, roles 0, 3, 3 and -1, t from 0 to 3. + let c = cloud( + &[[0.0; 3], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], + vec![column("t", false, &[0.0, 1.0, 2.0, 3.0]), column("role", true, &[0.0, 3.0, 3.0, -1.0])], + ); + let g = Geometry::of(&c); + let colour = Colour::Palette { property: "role" }; + let h = histogram(&c, &g, "t", [0.0, 4.0], 4, &colour, &[]).unwrap(); + assert_eq!(h.slots.len(), colour.slots()); + assert!(close(&h.slots[0], &[0.25, 0.0, 0.0, 0.0])); + assert!(close(&h.slots[3], &[0.0, 0.25, 0.25, 0.0])); + assert!(close(&h.slots[PALETTE.len()], &[0.0, 0.0, 0.0, 0.25]), "a negative label"); + // A filter by values keeps role 3 only. + let three = Filter { property: "role".into(), keep: Keep::Values { values: vec![3] } }; + let kept = histogram(&c, &g, "t", [0.0, 4.0], 4, &colour, &[three]).unwrap(); + let total: f64 = kept.slots.iter().flatten().sum(); + assert!((total - 0.5).abs() < 1e-9 && close(&kept.slots[3], &h.slots[3])); + // A ramp over t in two bands, and coloured by a property the cloud doesn't have: plain. + let ramp = Colour::Ramp { property: "t", range: [0.0, 4.0], bands: 2 }; + let r = histogram(&c, &g, "t", [0.0, 4.0], 4, &ramp, &[]).unwrap(); + assert!(close(&r.slots[0], &[0.25, 0.25, 0.0, 0.0]) && close(&r.slots[1], &[0.0, 0.0, 0.25, 0.25])); + let none = histogram(&c, &g, "t", [0.0, 4.0], 4, &Colour::Palette { property: "nope" }, &[]).unwrap(); + assert!(close(&none.slots[PALETTE.len() + 1], &[0.25; 4])); +} + +#[test] +fn labels_change_where_the_next_point_has_another() { + // Six points in order of t, layers 0 0 1 1 2 2. + let points: Vec<[f32; 3]> = (0..6).map(|i| [i as f32, 0.0, 0.0]).collect(); + let c = cloud(&points, vec![column("t", false, &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), column("layer", true, &[0.0, 0.0, 1.0, 1.0, 2.0, 2.0])]); + let g = Geometry::of(&c); + assert_eq!(label_changes(&c, &g, "layer", "t"), vec![2.0, 4.0]); + assert!(label_changes(&c, &g, "nope", "t").is_empty()); +} + +#[test] +fn the_automatic_range_is_what_every_filter_keeps() { + // Filtered by x from 2 to 4, coloured by t: the range is what is kept of t, though no filter + // is on t (its span within filters on t would be all of it). + let mut c = cloud(&[[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [4.0, 0.0, 0.0], [20.0, 0.0, 0.0]], vec![column("t", false, &[0.0, 3.0, 5.0, 7.0])]); + c.color_by = ColorBy::Property; + c.color_property = Some("t".into()); + let g = Geometry::of(&c); + let x = [range("x", [2.0, 4.0])]; + assert_eq!(c.color_range(), Some([0.0, 7.0])); + assert_eq!(color_range(&c, &g, &x), Some([3.0, 5.0])); + // The point at x = 20 alone: one value, one unit wide. + assert_eq!(color_range(&c, &g, &[range("x", [19.0, 21.0])]), Some([6.5, 7.5])); + // Nothing kept: the cloud's own bound; a range set is kept as it is. + assert_eq!(color_range(&c, &g, &[range("x", [50.0, 60.0])]), Some([0.0, 7.0])); + c.height_range = Some([1.0, 2.0]); + assert_eq!(color_range(&c, &g, &x), Some([1.0, 2.0])); + let h = histogram(&c, &g, "t", [0.0, 1.0], 4, &Colour::One, &x).unwrap(); + assert_eq!(h.extent, Some([3.0, 5.0]), "the extent reaches past the axis"); +} diff --git a/crates/doc/src/points.rs b/crates/doc/src/points.rs index f8c785f96..8c8f5a98b 100644 --- a/crates/doc/src/points.rs +++ b/crates/doc/src/points.rs @@ -5,7 +5,7 @@ use std::ops::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; macro_rules! point_type { ($(#[$doc:meta])* $name:ident) => { diff --git a/crates/doc/src/print_face.rs b/crates/doc/src/print_face.rs new file mode 100644 index 000000000..6d61e2a74 --- /dev/null +++ b/crates/doc/src/print_face.rs @@ -0,0 +1,106 @@ +//! The print face: the flat face of a body that a slicer export lays on the print bed (#8429). +//! A body has at most one (`Document::print_faces`, by body name). It is held by the target a +//! sketch on a face holds ([`Document::flat_face_target`]), so a rebuild that adds, removes or +//! reorders faces finds the same face again, or says it is gone. + +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; + +use crate::config::ConfigFaceTarget; +use crate::{DocError, Document, ModelBody, ModelState, Result}; + +/// Where a print face is: a point on it and its outward unit normal, in the coordinates of the +/// body it was found on. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PrintFace { + /// The face's index on the body (its first piece, when a change split it). + pub index: usize, + pub point: Vec3, + pub normal: Vec3, +} + +impl Document { + /// The target that marks flat face `index` of `body` as its print face. + pub fn print_face_target(&self, body: &ModelBody, index: usize) -> Result { + if body.body.is_mesh() { + return Err(DocError::Invalid("not supported yet: a print face on a mesh body".into())); + } + if body.body.planar_face(index).is_none() { + return Err(DocError::Invalid("only a flat face can be the print face".into())); + } + // The sketch-on-a-face wording ("choose a fixed plane") offers what a print face has not. + self.flat_face_target(body, index).map_err(|_| { + DocError::Invalid( + "this face can't be the print face: the body's history no longer tells it apart from its other faces (as after a shell of a shell body); pick a face of another body, or edit the feature that reshaped it".into(), + ) + }) + } + + /// Where `body`'s print face is now. `None`: it has none. An error: the face can't be found + /// any more, or is no longer flat. + pub fn print_face(&self, state: &ModelState, body: &ModelBody) -> Option> { + let target = self.print_faces.get(body.definition_name())?; + Some(self.locate_print_face(state, body, target)) + } + + /// The print face a copy of `source` gets (Move/Copy, Mirror): the face of `copy` named after + /// `source`'s print face (a copy's faces carry their source's names, followed by the copy's + /// instance, `F1:+x@F2.1`). `None`: + /// `source` has no print face. + pub fn copied_print_face(&self, state: &ModelState, source: &ModelBody, copy: &ModelBody) -> Option> { + let target = self.print_faces.get(source.definition_name())?; + let found = || { + let (indices, _) = self.anchored_face_indices(state, source, target)?; + let first = indices.first().copied().ok_or_else(|| DocError::Unknown("the print face no longer exists".into()))?; + let names = crate::naming::face_names(source); + let name = + names.get(first).map(|n| crate::naming::strip_piece(n)).ok_or_else(|| DocError::Unknown("the print face has no name".into()))?; + let index = crate::naming::face_names(copy) + .iter() + .position(|n| crate::naming::strip_piece(without_last_instance(n)) == name) + .ok_or_else(|| DocError::Unknown(format!("the copy has no face `{name}`")))?; + self.print_face_target(copy, index) + }; + Some(found()) + } + + fn locate_print_face(&self, state: &ModelState, body: &ModelBody, target: &ConfigFaceTarget) -> Result { + if body.body.is_mesh() { + return Err(DocError::Invalid("not supported yet: a print face on a mesh body".into())); + } + let (indices, _) = self.anchored_face_indices(state, body, target)?; + let first = indices.first().copied().ok_or_else(|| DocError::Unknown("the print face no longer exists".into()))?; + let plane = body.body.planar_face(first).ok_or_else(|| DocError::Invalid("the print face is no longer flat".into()))?; + let scale = 1. + body.body.size(); + for index in indices.iter().skip(1) { + let other = body.body.planar_face(*index).ok_or_else(|| DocError::Invalid("the print face is no longer flat".into()))?; + if plane.normal().dot(other.normal()).abs() < 1. - 1e-8 || (other.origin - plane.origin).dot(plane.normal()).abs() > 1e-7 * scale { + return Err(DocError::Invalid("the print face's pieces no longer lie on one plane".into())); + } + } + // The surface's own orientation is how the kernel built it, so the side the material is + // on is taken from the face's triangles, which point out of the body. + let mesh = body.mesh(); + let mut area = Vec3::ZERO; + for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) { + if let (true, Some([a, b, c])) = (indices.contains(&(*f as usize)), mesh.tri(t)) { + area += (b - a).cross(c - a); + } + } + let normal = plane.normal().normalized().ok_or_else(|| DocError::Invalid("the print face's plane is degenerate".into()))?; + let outward = area.dot(normal); + if !(outward.abs() > 0.) { + return Err(DocError::Invalid("the print face has no surface to lie on".into())); + } + Ok(PrintFace { index: first, point: plane.origin, normal: if outward < 0. { -normal } else { normal } }) + } +} + +/// A face name without the copy instance at its end (`F1:+x@F2.1` is `F1:+x`; a copy of a copy, +/// `F1:+x@F2.1@F5.1`, is `F1:+x@F2.1`). +fn without_last_instance(n: &str) -> &str { + let Some(at) = n.rfind('@') else { return n }; + let instance = n.get(at + 1..).and_then(|t| t.strip_prefix('F')).and_then(|t| t.split_once('.')); + let digits = |t: &str| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()); + if instance.is_some_and(|(feature, k)| digits(feature) && digits(k)) { n.get(..at).unwrap_or(n) } else { n } +} diff --git a/crates/doc/src/profile_refs.rs b/crates/doc/src/profile_refs.rs index eb11c7cdb..ccd4335b0 100644 --- a/crates/doc/src/profile_refs.rs +++ b/crates/doc/src/profile_refs.rs @@ -1,4 +1,5 @@ //! Exact profile references through analytic offset topology transitions. +use solidcraft_geom::prelude::*; use std::collections::BTreeSet; use crate::{DocError, ProfileSel, Result, SolvedSketch, WholeProfileBoundary}; @@ -364,7 +365,7 @@ mod tests { #![allow(clippy::unwrap_used, clippy::panic)] use super::*; use serde_json::json; - use solidcraft_geom::{Plane, Vec2}; + use solidcore_record::{Plane, Vec2}; use solidcraft_sketch::{Sketch, find_profiles, solve}; fn rounded_source(sketch: &mut Sketch, radius: f64) -> Vec<(String, bool)> { @@ -453,9 +454,11 @@ mod tests { start_offset: None, through_all: false, taper: None, + corner: Default::default(), to: None, to_offset: None, from: None, + to_body_apart: false, }, operation: crate::Operation::NewBody, targets: vec![], @@ -635,9 +638,11 @@ mod tests { start_offset: None, through_all: false, taper: None, + corner: Default::default(), to: None, to_offset: None, from: None, + to_body_apart: false, }, operation: crate::Operation::NewBody, targets: vec![], diff --git a/crates/doc/src/progress.rs b/crates/doc/src/progress.rs index ded665453..5da224c12 100644 --- a/crates/doc/src/progress.rs +++ b/crates/doc/src/progress.rs @@ -223,7 +223,8 @@ impl Evaluation { if !due { return; } - let world = Arc::new(crate::world_state(doc, state)); + // A world that cannot be placed is shown with the evaluation's own error, at its end. + let Ok(world) = crate::world_state(doc, state).map(Arc::new) else { return }; if let Ok(mut p) = progress.partial.lock() { *p = (Some(Partial { features, world }), Some(web_time::Instant::now())); } @@ -292,7 +293,7 @@ mod tests { fn partial_models_go_only_to_a_watcher_that_wants_them() { let mut doc = crate::Document::new("partial"); let block = crate::FeatureKind::Box { - corner: crate::point_expr(solidcraft_geom::Vec3::ZERO), + corner: crate::point_expr(solidcore_record::Vec3::ZERO), length: "2 mm".into(), width: "3 mm".into(), height: "4 mm".into(), diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index 088995265..1ecfed6fb 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -10,10 +10,12 @@ //! lines and circular arcs are recovered exactly, the rest (an ellipse from a tilted circle, //! a spline edge running out of the plane) becomes a chain of lines. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; -use solidcraft_geom::{Mesh, Plane, Seg2, Vec2, Vec3}; -use solidcraft_sketch::{CurveKind, LinkGeom, LinkKind, LinkSource, Sketch}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::Mesh; +use solidcraft_sketch::{CurveKind, LinkGeom, LinkKind, LinkSource, Sketch, WireCurve}; use crate::eval::ModelState; use crate::expr::Value; @@ -33,6 +35,9 @@ pub struct Resolved { pub geom: Vec, /// 3D curves (world coordinates). pub wires: Vec>, + /// Each wire's exact curve where its source has one (an included edge or sketch curve), + /// one list per wire, empty for a curve known only as points ([`solidcraft_sketch::Wire::exact`]). + pub exact: Vec>, pub source: LinkSource, /// The reference was not exactly where it was and was re-found on the nearest geometry. pub moved: bool, @@ -108,6 +113,7 @@ fn resolve_uncached( let mut edge_index = None; let mut source = src.clone(); let mut wires: Vec> = Vec::new(); + let mut exact: Vec> = Vec::new(); let geom = match src { LinkSource::Edge { body, at } => { let (bi, mesh) = body_mesh(st, body, *at)?; @@ -120,8 +126,9 @@ fn resolve_uncached( let name = st.bodies.get(bi).map(|b| b.name.clone()).unwrap_or_else(|| body.clone()); source = LinkSource::Edge { body: name, at: q }; edge_index = Some(e); - let exact = st.bodies.get(bi).and_then(|b| exact_edges(b, plane, &[e]).pop().flatten()); - edge_geom(plane, kind, exact, mesh.edges.get(e).cloned().unwrap_or_default(), &mut wires) + let planar = st.bodies.get(bi).and_then(|b| exact_edges(b, plane, &[e]).pop().flatten()); + let pts = mesh.edges.get(e).cloned().unwrap_or_default(); + edge_geom(plane, kind, planar, (pts, || edge_curves(st.bodies.get(bi), e)), &mut wires, &mut exact) } LinkSource::Face { body, at } => { let (bi, mesh) = body_mesh(st, body, *at)?; @@ -148,7 +155,7 @@ fn resolve_uncached( let mesh = b.mesh(); match kind { LinkKind::Intersect => section(plane, &mesh, None), - _ => silhouette(plane, &mesh), + _ => silhouette(plane, &mesh, Some(&b.body)), } } LinkSource::Vertex { body, at } => { @@ -182,6 +189,7 @@ fn resolve_uncached( let pts: Vec = ss.sketch.polyline(ci).iter().map(|p| ss.plane.to_world(*p)).collect(); if off_plane(plane, &pts) { wires.push(pts); + exact.push(sketch_curves(ss, ci)); Vec::new() } else { project_sketch_curve(&ss.sketch, &ss.plane, ci, plane) @@ -202,13 +210,32 @@ fn resolve_uncached( } let name = st.bodies.get(bi).map(|b| b.name.clone()).unwrap_or_else(|| body.clone()); source = LinkSource::OnSurface { sketch: *sketch, curve: curve.clone(), body: name, at: q }; - wires = crate::project3d::onto_face(&mesh, f, &pts, plane.normal()); + match st.bodies.get(bi).filter(|b| !b.body.is_mesh()) { + // A solid's face: SMLib's projection of the sketch curve itself. + Some(target) => { + let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)); + (wires, exact) = projected_wires(target, q, ss, &segs, plane.normal(), size)?; + } + // A mesh body has only its triangles: the curve projected onto them. + None => { + wires = crate::project3d::onto_face(&mesh, f, &pts, plane.normal()); + exact = vec![Vec::new(); wires.len()]; + } + } Vec::new() } LinkSource::Intersection { a, b } => { - let (ma, fa) = crate::project3d::mesh_of(st, a).ok_or_else(|| lost(&a.describe()))?; - let (mb, fb) = crate::project3d::mesh_of(st, b).ok_or_else(|| lost(&b.describe()))?; - wires = crate::project3d::mesh_intersection(&ma, fa, &mb, fb); + // Where the bodies (or faces) meet, as the edges SMLib's imprint of one by the other + // makes: each its exact record curve, its points at the display tolerance. + let (ba, fa) = crate::project3d::part_of(st, a).ok_or_else(|| lost(&a.describe()))?; + let (bb, fb) = crate::project3d::part_of(st, b).ok_or_else(|| lost(&b.describe()))?; + let chord = (ba.body.size().max(bb.body.size()) * 1e-3).max(1e-3); + for e in + crate::kernel::meeting_edges(&ba.body, fa.as_ref().map(std::slice::from_ref), &bb.body, fb.as_ref().map(std::slice::from_ref), chord)? + { + wires.push(e.points); + exact.push(vec![WireCurve { curve: e.curve, interval: e.interval }]); + } Vec::new() } LinkSource::Iso { body, at, dir } => { @@ -220,7 +247,29 @@ fn resolve_uncached( } let name = st.bodies.get(bi).map(|b| b.name.clone()).unwrap_or_else(|| body.clone()); source = LinkSource::Iso { body: name, at: q, dir: dir.clone() }; - wires = crate::project3d::iso_curve(&mesh, f, q, dir); + match st.bodies.get(bi).filter(|b| !b.body.is_mesh()) { + Some(target) => { + let face = usize::try_from(f).map_err(|_| DocError::Invalid("face index exceeds platform limit".into()))?; + let curves = match dir.trim().to_ascii_lowercase().as_str() { + // Along the face's own parameter: the surface's isoparametric curve. + "u" => crate::kernel::iso_curves(&target.body, face, q, true)?, + "v" => crate::kernel::iso_curves(&target.body, face, q, false)?, + // Along a direction: the face cut by the plane through the point that + // holds the face's normal there and the direction. + other => { + let v: Vec = other.split([',', ' ']).filter_map(|x| x.trim().parse().ok()).collect(); + let [x, y, z] = v[..] else { return Err(DocError::Invalid(format!("iso direction `{dir}`"))) }; + crate::kernel::face_section_along(&target.body, face, q, Vec3::new(x, y, z))? + } + }; + (wires, exact) = joined_wires(curves, size * 1e-6)?; + } + // A mesh body has only its triangles: their section. + None => { + wires = crate::project3d::iso_curve(&mesh, f, q, dir); + exact = vec![Vec::new(); wires.len()]; + } + } Vec::new() } LinkSource::Spun { body, origin, dir } => { @@ -238,13 +287,14 @@ fn resolve_uncached( } LinkSource::Origin => vec![LinkGeom::Point(plane.to_local(Vec3::ZERO))], LinkSource::Axis { name } => { - let d = match name.to_ascii_uppercase().as_str() { - "X" => Vec3::X, - "Y" => Vec3::Y, - "Z" => Vec3::Z, - _ => return Err(DocError::Unknown(format!("axis `{name}`"))), + let (o, d) = match name.to_ascii_uppercase().as_str() { + "X" => (Vec3::ZERO, Vec3::X), + "Y" => (Vec3::ZERO, Vec3::Y), + "Z" => (Vec3::ZERO, Vec3::Z), + // A construction axis, by name (#9324), where the timeline so far puts it. + _ => crate::eval::construction_axis_in(Some(doc), st, name, 0)?, }; - let o = plane.to_local(Vec3::ZERO); + let o = plane.to_local(o); let d2 = Vec2::new(d.dot(plane.x), d.dot(plane.y)); match d2.normalized() { Some(u) if d2.len() > 1e-9 => vec![LinkGeom::Line(o - u * AXIS_HALF, o + u * AXIS_HALF)], @@ -275,7 +325,7 @@ fn resolve_uncached( if geom.is_empty() && wires.is_empty() { return Err(DocError::Invalid(format!("the {} projects to nothing on this sketch plane", src.describe()))); } - Ok(Resolved { geom: merge_split_circles(geom), wires, source, moved, face_index, edge_index }) + Ok(Resolved { geom: merge_split_circles(geom), wires, exact, source, moved, face_index, edge_index }) } /// Whether a curve (world points) leaves the sketch plane: included, it then stays 3D. @@ -285,25 +335,282 @@ fn off_plane(plane: &Plane, pts: &[Vec3]) -> bool { } /// What a body edge (its `exact` curve when read, and its polyline `pts`) gives a sketch: its -/// section with the sketch plane, itself as a 3D curve (into `wires`) when it is included and -/// leaves the plane, else its projection (the exact curve, or the polyline fitted). -fn edge_geom(plane: &Plane, kind: LinkKind, exact: Option>, pts: Vec, wires: &mut Vec>) -> Vec { +/// section with the sketch plane, itself as a 3D curve (its points into `wires`, its exact +/// curve into `exact`) when it is included and leaves the plane, else its projection (the exact +/// planar curve `planar`, or the polyline fitted). +fn edge_geom( + plane: &Plane, + kind: LinkKind, + planar: Option>, + (pts, curves): (Vec, impl FnOnce() -> Vec), + wires: &mut Vec>, + exact: &mut Vec>, +) -> Vec { match kind { LinkKind::Intersect => section_of_polyline(plane, &pts), LinkKind::Include if off_plane(plane, &pts) => { wires.push(pts); + exact.push(curves()); Vec::new() } - _ => exact.unwrap_or_else(|| fit_world(plane, &pts)), + _ => planar.unwrap_or_else(|| fit_world(plane, &pts)), } } +/// Edge `e` of `body` (its index in the body's edge order) as its exact curve from the body's +/// record; none for a mesh body or an intersection curve the record holds no curve for. +fn edge_curves(body: Option<&crate::ModelBody>, e: usize) -> Vec { + let Some(body) = body.filter(|b| !b.body.is_mesh()) else { return Vec::new() }; + let Ok(record) = crate::kernel::brep_record(&body.body) else { return Vec::new() }; + record + .edges + .get(e) + .filter(|edge| !matches!(edge.curve, solidcore_record::brep::Curve::SurfaceIntersection { .. })) + .map(|edge| vec![WireCurve { curve: edge.parameters().clone(), interval: edge.interval }]) + .unwrap_or_default() +} + +/// The sketch segments `segs` of `ss` projected along the sketch normal `normal` (turned toward +/// the face) onto the face of `target` at `at`: SMLib's projection, the side of the face the +/// projection meets first ([`first_hits`]), the pieces that meet end to end joined into one wire +/// each, every wire its points (for display) and its exact curves. +fn projected_wires( + target: &crate::ModelBody, + at: Vec3, + ss: &crate::eval::SolvedSketch, + segs: &[Seg2], + normal: Vec3, + size: f64, +) -> Result<(Vec>, Vec>)> { + let from = segs.first().map(|s| ss.plane.to_world(s.start())).unwrap_or(at); + let toward = if (at - from).dot(normal) < 0.0 { normal * -1.0 } else { normal }; + let curves = crate::kernel::project_onto_face(&target.body, at, &ss.plane, segs, toward)?; + joined_wires(first_hits(target, curves, toward)?, size * 1e-6) +} + +/// Of the curves a parallel projection along `toward` made on a face of `target`, the ones the +/// projection meets first: SMLib gives every curve where the projecting lines cross the face +/// (both sides of a sphere), and a projection onto a surface is where they first hit it. A curve +/// is kept when the first hit along the line through its middle, on the body's mesh, is the +/// curve itself (within the mesh's chord tolerance, a few times over), not a point of the body +/// in front of it. +fn first_hits( + target: &crate::ModelBody, + curves: Vec<(solidcore_record::brep::Curve, [f64; 2])>, + toward: Vec3, +) -> Result> { + let Some(dir) = toward.normalized() else { return Ok(curves) }; + let mesh = target.mesh(); + let reach = 2.0 * mesh.bounds().diagonal().max(1e-9); + let slack = 4.0 * target.display_tol(); + let mut kept = Vec::with_capacity(curves.len()); + for (curve, interval) in curves { + let eval = solidcraft_geom::brep::eval::CurveEval::new(&curve).map_err(|e| DocError::Invalid(format!("projected curve: {e}")))?; + let mid = eval.point(0.5 * (interval[0] + interval[1])).ok_or_else(|| DocError::Invalid("projected curve: no middle point".into()))?; + let origin = mid - dir * reach; + let front = mesh.raycast(origin, dir).is_some_and(|(t, _)| t < reach - slack); + if !front { + kept.push((curve, interval)); + } + } + Ok(kept) +} + +/// Record curves as wires: curves that meet end to end (within `tol`) one wire, in any order and +/// direction they come (a projection split at a sphere's pole into two pieces that both end there +/// joins again there, the second run the other way), each wire its points (for display) and its +/// exact curves. +fn joined_wires(curves: Vec<(solidcore_record::brep::Curve, [f64; 2])>, tol: f64) -> Result<(Vec>, Vec>)> { + let (mut wires, mut exact): (Vec>, Vec>) = (Vec::new(), Vec::new()); + for (curve, interval) in curves { + let pts = crate::kernel::PathPiece::Segs(crate::kernel::curve_path(&curve, interval)?).points(); + if pts.is_empty() { + continue; + } + wires.push(pts); + exact.push(vec![WireCurve { curve, interval }]); + } + // Join a wire onto the one that ends where it starts (or ends, turned round), until no two + // meet: each join removes a wire. + 'join: loop { + for i in 0..wires.len() { + for j in 0..wires.len() { + let (Some(a), Some(b)) = (wires.get(i), wires.get(j)) else { continue }; + let (Some(end), Some(start), Some(last)) = (a.last(), b.first(), b.last()) else { continue }; + let turned = if i == j { + continue; + } else if end.dist(*start) <= tol { + false + } else if end.dist(*last) <= tol && exact.get(j).is_some_and(|e| e.iter().all(|c| reversed(c).is_some())) { + true + } else { + continue; + }; + let (mut w, mut e) = (wires.remove(j), exact.remove(j)); + if turned { + w.reverse(); + e = e.iter().rev().filter_map(reversed).collect(); + } + let i = if j < i { i - 1 } else { i }; + if let (Some(into), Some(curves)) = (wires.get_mut(i), exact.get_mut(i)) { + into.extend(w.into_iter().skip(1)); + curves.extend(e); + } + continue 'join; + } + } + break; + } + Ok((wires, exact)) +} + +/// `c` run the other way: the same points, its parameter `t` now `c0 + c1 - t` over the curve's +/// own knots (a line's `1 - t`, a circle's or ellipse's angle negated with its y axis turned). +/// Exact; `None` for a curve kind it doesn't turn. +fn reversed(c: &WireCurve) -> Option { + use solidcore_record::brep::{Curve, Frame}; + let [t0, t1] = c.interval; + let flip = |frame: &Frame| Frame { origin: frame.origin, x_axis: frame.x_axis, y_axis: frame.y_axis.map(|v| -v) }; + let (curve, interval) = match &c.curve { + Curve::Line { start, end } => (Curve::Line { start: *end, end: *start }, [1.0 - t1, 1.0 - t0]), + Curve::Circle { frame, radius } => (Curve::Circle { frame: flip(frame), radius: *radius }, [-t1, -t0]), + Curve::Ellipse { frame, radii } => (Curve::Ellipse { frame: flip(frame), radii: *radii }, [-t1, -t0]), + Curve::Spline { knots, points } => { + let sum = knots.first()? + knots.last()?; + ( + Curve::Spline { knots: knots.iter().rev().map(|k| sum - k).collect(), points: points.iter().rev().copied().collect() }, + [sum - t1, sum - t0], + ) + } + Curve::RationalSpline { knots, homogeneous } => { + let sum = knots.first()? + knots.last()?; + ( + Curve::RationalSpline { + knots: knots.iter().rev().map(|k| sum - k).collect(), + homogeneous: homogeneous.iter().rev().copied().collect(), + }, + [sum - t1, sum - t0], + ) + } + _ => return None, + }; + Some(WireCurve { curve, interval }) +} + +/// Curve `ci` of the solved sketch `ss` as its exact pieces in space, in the order its polyline +/// runs; none where a piece has no record curve. +fn sketch_curves(ss: &crate::eval::SolvedSketch, ci: usize) -> Vec { + let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)); + segs.iter() + .map(|s| crate::kernel::sketch_record_curve(&ss.plane, s).map(|(curve, interval)| WireCurve { curve, interval })) + .collect::>() + .unwrap_or_default() +} + /// Edges `edges` of `body` (indices into its mesh's `edges`) on `plane` as their exact curves: -/// lines, circles and arcs, and the Bézier pieces of a free-form curve. `None` for an edge that -/// doesn't lie in a plane parallel to `plane` or isn't read exactly (a mesh body's): it is -/// fitted to its polyline instead. +/// lines, circles and arcs, and a free-form curve as the one spline it is, its knots and weights +/// its own. `None` for an edge that doesn't lie in a plane parallel to `plane`, isn't read +/// exactly (a mesh body's) or is a spline no sketch holds (past degree 9 or 500 points): it is +/// fitted to its polyline instead. An edge read as free-form pieces, or not read, that runs +/// along a circle in a plane parallel to `plane` comes in as that circle ([`circular`]): a +/// round's edge is a spline that only follows its circle. fn exact_edges(body: &crate::ModelBody, plane: &Plane, edges: &[usize]) -> Vec>> { - body.body.planar_edges(plane, edges).into_iter().map(|segs| segs?.iter().map(link_geom).collect()).collect() + use crate::kernel::PlanarPiece; + let free_form = |p: &PlanarPiece| matches!(p, PlanarPiece::Spline(_) | PlanarPiece::Seg(Seg2::Cubic { .. } | Seg2::Bezier { .. })); + let link = |p: &PlanarPiece| match p { + PlanarPiece::Seg(s) => link_geom(s), + PlanarPiece::Spline(s) => link_spline(s), + }; + let mut mesh = None; + body.body + .planar_edges(plane, edges) + .into_iter() + .zip(edges) + .map(|(pieces, e)| match pieces { + Some(pieces) if !pieces.iter().any(free_form) => pieces.iter().map(link).collect(), + Some(pieces) => { + let samples: Option> = pieces.iter().map(piece_samples).collect::>>().map(|s| s.concat()); + match samples.as_deref().and_then(circular) { + Some((g, _)) => Some(vec![g]), + None => pieces.iter().map(link).collect(), + } + } + None if body.body.is_mesh() => None, + None => { + // Not read: its polyline lies on the curve, but only many points of it show a circle. + let pts = mesh.get_or_insert_with(|| body.mesh()).edges.get(*e).filter(|pts| pts.len() > 8)?; + let level = plane.height(*pts.first()?); + let (g, radius) = circular(&pts.iter().map(|p| plane.to_local(*p)).collect::>())?; + pts.iter().all(|p| (plane.height(*p) - level).abs() <= radius * CIRCLE_TOL).then(|| vec![g]) + } + }) + .collect() +} + +/// A free-form edge's B-spline as the control spline that is the same curve, with its own knots +/// and weights. `None` for one a sketch can't hold. +fn link_spline(s: &crate::kernel::PlanarSpline) -> Option { + let degree = u8::try_from(s.degree).ok()?; + let nurbs = solidcraft_sketch::Nurbs { knots: s.knots.clone(), weights: s.weights.clone() }; + nurbs.check(s.points.len(), degree).ok()?; + Some(LinkGeom::Spline { pts: s.points.clone(), control: true, degree, periodic: false, nurbs: Some(nurbs) }) +} + +/// Points sampled along each free-form piece of an edge to see whether it runs along a circle. +const CIRCLE_SAMPLES: u16 = 16; +/// How far round (radians) a curve turns at least to be taken for a circle: a letter's nearly +/// straight stroke lies near a large circle too. +const CIRCLE_MIN_TURN: f64 = 0.1; +/// How far (a fraction of its radius) a curve may stray from a circle and still be that circle: +/// a round's edge keeps to it within 3e-7, a curve that merely looks round (a letter's bowl of +/// four cubic spans) only within 3e-4. +const CIRCLE_TOL: f64 = 1e-5; + +/// The circle (closing points) or arc through `samples`, taken in order along a curve, with +/// its radius: when they all lie on one within [`CIRCLE_TOL`]. The arc ends at the first and +/// last sample, so it meets what the curve met. +fn circular(samples: &[Vec2]) -> Option<(LinkGeom, f64)> { + let (first, last) = (*samples.first()?, *samples.last()?); + let (c, radius) = ls_circle(samples)?; + let tol = radius * CIRCLE_TOL; + if !(radius.is_finite() && tol > 0.0) || samples.iter().any(|p| (p.dist(c) - radius).abs() > tol) { + return None; + } + let mut sweep = 0.0; + for w in samples.windows(2) { + let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; + let mut d = (*b - c).angle() - (*a - c).angle(); + if d > std::f64::consts::PI { + d -= std::f64::consts::TAU; + } else if d < -std::f64::consts::PI { + d += std::f64::consts::TAU; + } + sweep += d; + } + let turn = sweep.abs(); + if turn > std::f64::consts::TAU + 1e-6 || turn < CIRCLE_MIN_TURN { + return None; + } + if first.dist(last) <= tol { + return (turn > std::f64::consts::TAU - 1e-6).then_some((LinkGeom::Circle(c, radius), radius)); + } + // Counter-clockwise from `a` to `b`. + let (a, b) = if sweep > 0.0 { (first, last) } else { (last, first) }; + Some((LinkGeom::Arc { c, a, b }, radius)) +} + +/// [`CIRCLE_SAMPLES`] + 1 points along a piece of an edge, ends included; `None` for a spline +/// whose knots don't fit its points. +fn piece_samples(piece: &crate::kernel::PlanarPiece) -> Option> { + let at = |i: u16| f64::from(i) / f64::from(CIRCLE_SAMPLES); + match piece { + crate::kernel::PlanarPiece::Seg(s) => Some((0..=CIRCLE_SAMPLES).map(|i| s.point_at(at(i))).collect()), + crate::kernel::PlanarPiece::Spline(s) => { + let degree = u8::try_from(s.degree).ok()?; + let nurbs = solidcraft_sketch::Nurbs { knots: s.knots.clone(), weights: s.weights.clone() }; + (0..=CIRCLE_SAMPLES).map(|i| nurbs.point(&s.points, degree, at(i))).collect() + } + } } /// `edges` of `body` projected on `plane`: each exactly ([`exact_edges`]) or fitted to its @@ -347,7 +654,10 @@ fn projected_edges_apart(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, ed let mut out = Vec::new(); for (e, exact) in edges.iter().zip(exact_edges(body, plane, edges)) { match exact { - Some(g) => out.extend(g), + Some(mut g) => { + at_vertices(body, mesh, plane, *e, &mut g); + out.extend(g); + } None => { if let Some(pts) = mesh.edges.get(*e) { out.extend(fit_world(plane, pts)); @@ -358,6 +668,60 @@ fn projected_edges_apart(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, ed out } +/// Edge `e`'s exact pieces `g` with their outer ends on the edge's vertices, where they lie +/// within the edge's and the reading's tolerance of them. An edge's curve need only pass within +/// its tolerance of its vertices, and an arc is read off a NURBS within the planar-edge +/// tolerance: one SMLib made (a shell's offset corner) ended 2e-6 mm from the line it meets, and +/// the two ends, not taken for one point, left the loop open, so an offset of one curve found +/// no chain to follow. The vertex is the point both edges share. +fn at_vertices(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, e: usize, g: &mut [LinkGeom]) { + let record = body.body.record(); + let Some(edge) = record.edges.get(e) else { return }; + let Some((first, last)) = mesh.edges.get(e).and_then(|pts| pts.first().zip(pts.last())) else { return }; + // The pieces are read within the planar-edge tolerance of the edge's curve, which passes + // within its own tolerance of the vertices. + let tol = edge.vertices.iter().filter_map(|v| record.vertices.get(*v as usize)).map(|v| v.tolerance).fold(edge.tolerance, f64::max) + + body.body.planar_edges_tolerance(); + // Each vertex moves the piece end nearest it (the pieces' order and direction need not be + // the edge's). + for v in [plane.to_local(*first), plane.to_local(*last)] { + let mut best: Option<(f64, &mut Vec2)> = None; + for piece in g.iter_mut() { + let ends = match piece { + LinkGeom::Line(a, b) | LinkGeom::Arc { a, b, .. } | LinkGeom::Conic { a, b, .. } => Some((a, b)), + // A control spline's end points are its ends. + LinkGeom::Spline { pts, control: true, periodic: false, .. } => match pts.as_mut_slice() { + [a, .., b] => Some((a, b)), + _ => None, + }, + _ => None, + }; + if let Some((a, b)) = ends { + for p in [a, b] { + let d = p.dist(v); + if d <= tol && best.as_ref().is_none_or(|(bd, _)| d < *bd) { + best = Some((d, p)); + } + } + } + } + if let Some((_, p)) = best { + *p = v; + } + } + // An arc is its centre and two ends on one circle: with its ends moved, its centre moves to + // the nearest point equally far from both (on their bisector), or the sketch would move an + // end back off the vertex onto the circle through the other. + for piece in g.iter_mut() { + if let LinkGeom::Arc { c, a, b } = piece + && let Some(across) = Vec2::new(a.y - b.y, b.x - a.x).normalized() + { + let mid = (*a + *b) * 0.5; + *c = mid + across * (*c - mid).dot(across); + } + } +} + /// A boundary segment as the link geometry that is the same curve. fn link_geom(s: &Seg2) -> Option { Some(match *s { @@ -370,8 +734,8 @@ fn link_geom(s: &Seg2) -> Option { LinkGeom::Arc { c: center, a, b } } Seg2::Conic { a, apex, b, w } => LinkGeom::Conic { a, apex, b, rho: w / (1. + w) }, - Seg2::Cubic { p0, p1, p2, p3 } => LinkGeom::Spline { pts: vec![p0, p1, p2, p3], control: true, degree: 3, periodic: false }, - Seg2::Bezier { n, p } => LinkGeom::Spline { pts: p.get(..=usize::from(n))?.to_vec(), control: true, degree: n, periodic: false }, + Seg2::Cubic { p0, p1, p2, p3 } => LinkGeom::Spline { pts: vec![p0, p1, p2, p3], control: true, degree: 3, periodic: false, nurbs: None }, + Seg2::Bezier { n, p } => LinkGeom::Spline { pts: p.get(..=usize::from(n))?.to_vec(), control: true, degree: n, periodic: false, nurbs: None }, }) } @@ -383,20 +747,24 @@ pub fn resolved_edge_name(st: &ModelState, r: &Resolved) -> Option { crate::naming::edge_names(body).get(index).filter(|name| !name.is_empty()).cloned() } -/// Re-resolve every link of a sketch (in place). Returns warnings for lost, moved or rebuilt -/// links; lost links keep their last geometry. fn lost(reference: &str) -> DocError { DocError::Unknown(format!("{reference} no longer exists")) } /// The edge a link's stored name finds, and the body it is on: the link's body, or, when no -/// body has that name any more (it was joined into another), the body on which the name finds -/// the edge nearest the link's point. +/// body has that name any more (it was joined into another), the one body on which the name +/// finds an edge. fn locate_named_edge(st: &ModelState, body: &str, name: &str, at: Vec3) -> Option<(String, crate::naming::EdgeHit)> { let hit = |b: &crate::ModelBody| crate::naming::locate_edge(b, name, at).ok().map(|hit| (b.name.clone(), hit)); match st.body(body) { Some(b) => hit(b), - None => st.bodies.iter().filter(|b| !b.body.is_mesh()).filter_map(hit).min_by(|a, b| a.1.point.dist(at).total_cmp(&b.1.point.dist(at))), + None => { + let mut found = st.bodies.iter().filter(|b| !b.body.is_mesh()).filter_map(hit); + match (found.next(), found.next()) { + (Some(one), None) => Some(one), + _ => None, + } + } } } @@ -410,14 +778,14 @@ fn resolve_named_edge(st: &ModelState, plane: &Plane, kind: LinkKind, body: &str .filter_map(|w| Some(closest_on_segment(near, *w.first()?, *w.get(1)?))) .min_by(|a, b| a.dist(near).total_cmp(&b.dist(near))) .ok_or_else(|| lost("named projection edge"))?; - let mut wires = Vec::new(); - let exact = exact_edges(target, plane, &[index]).pop().flatten(); - let geom = edge_geom(plane, kind, exact, pts, &mut wires); + let (mut wires, mut exact) = (Vec::new(), Vec::new()); + let planar = exact_edges(target, plane, &[index]).pop().flatten(); + let geom = edge_geom(plane, kind, planar, (pts, || edge_curves(Some(target), index)), &mut wires, &mut exact); if geom.is_empty() && wires.is_empty() { return Err(DocError::Invalid("named edge projects to nothing on this sketch plane".into())); } let source = LinkSource::Edge { body: body.into(), at }; - Ok(Resolved { geom: merge_split_circles(geom), wires, source, moved: false, face_index: None, edge_index: Some(index) }) + Ok(Resolved { geom: merge_split_circles(geom), wires, exact, source, moved: false, face_index: None, edge_index: Some(index) }) } fn resolve_named_face(st: &ModelState, plane: &Plane, kind: LinkKind, body: &str, index: usize, at: Vec3) -> Result { @@ -438,7 +806,15 @@ fn resolve_named_face(st: &ModelState, plane: &Plane, kind: LinkKind, body: &str if geom.is_empty() { return Err(DocError::Invalid("named face projects to nothing on this sketch plane".into())); } - Ok(Resolved { geom, wires: Vec::new(), source: LinkSource::Face { body: body.into(), at }, moved: false, face_index, edge_index: None }) + Ok(Resolved { + geom, + wires: Vec::new(), + exact: Vec::new(), + source: LinkSource::Face { body: body.into(), at }, + moved: false, + face_index, + edge_index: None, + }) } fn projection_face_edges(body: &crate::ModelBody, mesh: &Mesh, index: u32, plane: &Plane) -> Result> { @@ -519,6 +895,7 @@ pub fn resolve_face_indices(st: &ModelState, plane: &Plane, kind: LinkKind, body Ok(Resolved { geom: merge_split_circles(geometry), wires: Vec::new(), + exact: Vec::new(), source: LinkSource::Face { body: body.name.clone(), at: point }, moved: false, face_index: if indices.len() == 1 { indices.first().copied() } else { None }, @@ -526,6 +903,7 @@ pub fn resolve_face_indices(st: &ModelState, plane: &Plane, kind: LinkKind, body }) } +/// [`refresh_links`] for a sketch attached to a face by `anchor`. pub fn refresh_face_anchor_links( doc: &Document, vals: &BTreeMap, @@ -533,7 +911,7 @@ pub fn refresh_face_anchor_links( plane: &Plane, sk: &mut Sketch, anchor: &crate::FaceAnchor, -) -> Vec { +) -> Result> { refresh_links_in(doc, vals, st, plane, sk, Some(anchor)) } @@ -606,7 +984,11 @@ fn merge_family_lines(geom: Vec) -> Result> { Ok(result) } -pub fn refresh_links(doc: &Document, vals: &BTreeMap, st: &ModelState, plane: &Plane, sk: &mut Sketch) -> Vec { +/// Re-resolve every link of a sketch (in place). Returns warnings for lost, moved or rebuilt +/// links; lost links keep their last geometry. A link kept by the name of a face or edge that no +/// longer finds exactly that face or edge is not lost: the sketch fails, asking for the +/// reference to be picked again ([`DocError::Reselect`]). +pub fn refresh_links(doc: &Document, vals: &BTreeMap, st: &ModelState, plane: &Plane, sk: &mut Sketch) -> Result> { refresh_links_in(doc, vals, st, plane, sk, None) } @@ -643,7 +1025,7 @@ fn refresh_links_in( plane: &Plane, sk: &mut Sketch, anchor: Option<&crate::FaceAnchor>, -) -> Vec { +) -> Result> { let mut warn = Vec::new(); let links = sk.links.clone(); for l in &links { @@ -652,45 +1034,18 @@ fn refresh_links_in( if !l.auto_face && let (Some(name), LinkSource::Face { body, at }) = (&l.face_name, &mut source) { - if let Some((index, p, split)) = st.body(body).and_then(|target| crate::naming::face_on_body(target, name, *at)) { - let stem = crate::naming::strip_piece(name); - let removed_piece = split - && name != stem - && st.body(body).is_some_and(|target| { - (certified_planar_construction(target, index) || target.body.face_was_coalesced(index)) - && crate::naming::face_has_name(target, index, stem) - }); - if removed_piece { - sk.set_link_lost(&l.id, true); - warn.push(format!("projected face piece `{name}` no longer exists; last geometry retained")); - continue; - } - *at = p; - named_face = Some((body.clone(), index, p)); - if split { - warn.push(format!("projected face `{name}` was split; using the nearest piece")); - } - } else { - sk.set_link_lost(&l.id, true); - warn.push(format!("projected face `{name}` no longer exists")); - continue; - } + let (index, p) = + st.body(body).and_then(|target| crate::naming::face_on_body(target, name, *at)).ok_or_else(|| DocError::reselect(name.as_str()))?; + *at = p; + named_face = Some((body.clone(), index, p)); } // An edge the link keeps by name is that edge of its body, wherever it went. When no - // edge has the name any more the link is lost: no other edge is taken for it. + // edge has the name any more no other edge is taken for it: the sketch fails. let mut named_edge = None; if let (Some(name), LinkSource::Edge { body, at }) = (&l.edge_name, &source) { - match locate_named_edge(st, body, name, *at) { - Some((body, hit)) => { - warn.extend(hit.note(name).map(|note| format!("projected {note}"))); - named_edge = Some((body, hit.edge, *at)); - } - None => { - sk.set_link_lost(&l.id, true); - warn.push(format!("projected reference lost: edge `{name}` no longer exists; last geometry retained")); - continue; - } - } + let (body, hit) = locate_named_edge(st, body, name, *at).ok_or_else(|| DocError::reselect(name.as_str()))?; + warn.extend(hit.note(name).map(|note| format!("projected {note}"))); + named_edge = Some((body, hit.edge, *at)); } let resolved = if matches!(source, LinkSource::Text { .. }) { // A text needs nothing outside its sketch; one on a path follows a curve of it. @@ -698,7 +1053,7 @@ fn refresh_links_in( if geom.is_empty() { return Err(DocError::Invalid(format!("the {} makes no outline", source.describe()))); } - Ok(Resolved { geom, wires: Vec::new(), source: source.clone(), moved: false, face_index: None, edge_index: None }) + Ok(Resolved { geom, wires: Vec::new(), exact: Vec::new(), source: source.clone(), moved: false, face_index: None, edge_index: None }) }) } else if l.auto_face { anchor @@ -725,7 +1080,9 @@ fn refresh_links_in( link.edge_name = Some(name); } sk.set_link_source(&l.id, r.source); - let _ = sk.set_link_wires(&l.id, &r.wires); + if let Err(e) = sk.set_link_wires(&l.id, &r.wires).and_then(|()| sk.set_link_wire_curves(&l.id, &r.exact)) { + warn.push(format!("projected {}: {e}", l.source.describe())); + } // Words built from text parameters change shape when the parameters do: that // rebuild is the text following them, not a reference that changed under it. let words_follow = matches!(&l.source, LinkSource::Text { exprs, .. } if exprs.text.is_some()); @@ -751,7 +1108,7 @@ fn refresh_links_in( } } } - warn + Ok(warn) } // --------------------------------------------------------------------------------------------- @@ -883,9 +1240,10 @@ fn project_sketch_curve(sk: &Sketch, from: &Plane, ci: usize, to: &Plane) -> Vec (Some(c), Some(m)) => vec![LinkGeom::Ellipse { c: map(c), major: map(m), minor: *r }], _ => Vec::new(), }, - Some(CurveKind::Spline { pts, control, degree, periodic }) if parallel => { + Some(CurveKind::Spline { pts, control, degree, periodic, nurbs }) if parallel => { let p: Option> = pts.iter().map(|q| sk.point(*q).map(map)).collect(); - p.map(|pts| vec![LinkGeom::Spline { pts, control: *control, degree: *degree, periodic: *periodic }]).unwrap_or_default() + p.map(|pts| vec![LinkGeom::Spline { pts, control: *control, degree: *degree, periodic: *periodic, nurbs: nurbs.clone() }]) + .unwrap_or_default() } Some(CurveKind::Conic { a, b, apex, rho }) if parallel => match (sk.point(*a), sk.point(*apex), sk.point(*b)) { (Some(a), Some(x), Some(b)) => vec![LinkGeom::Conic { a: map(a), apex: map(x), b: map(b), rho: *rho }], @@ -1001,7 +1359,7 @@ fn as_spline(pts: &[Vec2], tol: f64) -> Option { <= tol }); if ok { - return Some(LinkGeom::Spline { pts: fit, control: false, degree: 3, periodic: false }); + return Some(LinkGeom::Spline { pts: fit, control: false, degree: 3, periodic: false, nurbs: None }); } } None @@ -1056,37 +1414,191 @@ fn section_of_polyline(plane: &Plane, pts: &[Vec3]) -> Vec { out } -/// The outline of a body seen along the sketch normal: mesh edges between triangles facing the -/// sketch and triangles facing away (or edge-on), projected and fitted. -fn silhouette(plane: &Plane, m: &Mesh) -> Vec { - let n = plane.normal(); - let size = m.bounds().diagonal().max(1e-9); - let q = size * 1e-7; - let key = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64); - // Undirected mesh edge → facing flags of the triangles using it. - let mut edges: BTreeMap<((i64, i64, i64), (i64, i64, i64)), (Vec3, Vec3, Vec)> = BTreeMap::new(); - for t in &m.triangles { - let Some([a, b, c]) = m.tri(t) else { continue }; - let fnrm = (b - a).cross(c - a); - let Some(un) = fnrm.normalized() else { continue }; - let front = un.dot(n) > 1e-6; - for (p, r) in [(a, b), (b, c), (c, a)] { - let (kp, kr) = (key(p), key(r)); - let k = if kp <= kr { (kp, kr) } else { (kr, kp) }; - edges.entry(k).or_insert_with(|| (p, r, Vec::new())).2.push(front); +/// Which way the surface faces at triangle `t`: its normals at the corners, added. A flat triangle +/// close to the outline can tip the other way from the surface it approximates (one whose far +/// corner lies inside the chord of its near edge), which would add spurs to the outline. The +/// triangle's own normal `flat` when a corner has none, or when they aren't that surface's: unit, +/// and close to `flat` (normals averaged across a crease, as an imported mesh may have, are not). +fn surface_facing(m: &Mesh, t: &[u32; 3], flat: Vec3) -> Vec3 { + /// Least cosine between a corner's normal and the triangle's: about 26 degrees. + const AGREES: f64 = 0.9; + let mut sum = Vec3::ZERO; + for i in t { + match m.normals.get(*i as usize).and_then(|v| v.normalized()) { + Some(v) if v.dot(flat) >= AGREES => sum += v, + _ => return flat, } } - let segs: Vec<(Vec2, Vec2)> = edges + sum.normalized().unwrap_or(flat) +} + +/// The outline of a body seen along the sketch normal: mesh edges between triangles facing the +/// sketch and triangles facing away (or edge-on), projected and fitted. A face of `body` that +/// faces one way all over ([`face_facing`]) does so in every triangle, though they lean a hair +/// either way: a round wall seen edge-on joins its two rims at different angles, and thin +/// slivers of a narrow chamfer can point the other way. Any other triangle faces as the surface +/// does at its corners ([`surface_facing`]). +fn silhouette(plane: &Plane, m: &Mesh, body: Option<&solidcraft_kernel::Body>) -> Vec { + let n = plane.normal(); + let size = m.bounds().diagonal().max(1e-9); + // Vertices welded within this: the copies of a vertex on the seam between two faces can lie + // a few 1e-7 apart, and an edge used by one triangle only is outline. + let weld = size * 1e-6; + let cell = |p: Vec3| ((p.x / weld).floor() as i64, (p.y / weld).floor() as i64, (p.z / weld).floor() as i64); + let mut grid: BTreeMap<(i64, i64, i64), Vec> = BTreeMap::new(); + let mut verts: Vec = Vec::new(); + let mut vertex = |p: Vec3| -> usize { + let (x, y, z) = cell(p); + for dx in -1..=1 { + for dy in -1..=1 { + for dz in -1..=1 { + let found = grid + .get(&(x + dx, y + dy, z + dz)) + .and_then(|ids| ids.iter().copied().find(|i| verts.get(*i).is_some_and(|v| v.dist(p) <= weld))); + if let Some(i) = found { + return i; + } + } + } + } + verts.push(p); + grid.entry((x, y, z)).or_default().push(verts.len() - 1); + verts.len() - 1 + }; + let tris: Vec<([Vec3; 3], Vec3, Option, &[u32; 3])> = m + .triangles + .iter() + .enumerate() + .filter_map(|(ti, t)| { + let [a, b, c] = m.tri(t)?; + Some(([a, b, c], (b - a).cross(c - a), m.tri_face.get(ti).copied(), t)) + }) + .collect(); + // Each face's area-weighted facing, and whether any triangle of it is in doubt: near + // edge-on, or facing against the rest of its face. Only those faces ask what they are. + let mut faces: BTreeMap = BTreeMap::new(); + for (_, w, f, _) in &tris { + if let Some(f) = f { + faces.entry(*f).or_default().0 += w.dot(n); + } + } + for (_, w, f, _) in &tris { + let (Some(f), Some(un)) = (f, w.normalized()) else { continue }; + if let Some(face) = faces.get_mut(f) { + face.1 |= un.dot(n).abs() < 0.5 || (un.dot(n) > 0.0) != (face.0 > 0.0); + } + } + let facing: BTreeMap = match body { + Some(body) => faces.iter().filter(|(_, (_, doubt))| *doubt).filter_map(|(f, (sum, _))| Some((*f, face_facing(body, *f, n, *sum)?))).collect(), + None => BTreeMap::new(), + }; + // Undirected mesh edge → facing flags of the triangles using it. + let ids: Vec<[usize; 3]> = tris.iter().map(|([a, b, c], _, _, _)| [vertex(*a), vertex(*b), vertex(*c)]).collect(); + let mut edges: BTreeMap<(usize, usize), (Vec3, Vec3, Vec<(bool, Option)>)> = BTreeMap::new(); + for ((_, w, f, t), [ia, ib, ic]) in tris.iter().zip(ids) { + let Some(un) = w.normalized() else { continue }; + let front = match f.and_then(|f| facing.get(&f)) { + Some(Facing::Front) => true, + Some(Facing::Away) => false, + None => surface_facing(m, t, un).dot(n) > 1e-6, + }; + for (p, r) in [(ia, ib), (ib, ic), (ic, ia)] { + if p == r { + continue; + } + let (Some(vp), Some(vr)) = (verts.get(p).copied(), verts.get(r).copied()) else { continue }; + edges.entry((p.min(r), p.max(r))).or_insert((vp, vr, Vec::new())).2.push((front, *f)); + } + } + let mut segs: Vec<(Vec2, Vec2)> = edges .values() .filter(|(_, _, f)| { - let fronts = f.iter().filter(|x| **x).count(); - fronts > 0 && fronts < f.len() || (f.len() == 1 && fronts == 1) + let fronts = f.iter().filter(|x| x.0).count(); + fronts > 0 && fronts < f.len() }) .map(|(a, b, _)| (plane.to_local(*a), plane.to_local(*b))) .collect(); + let singles: Vec<(Vec3, Vec3, bool, Option)> = edges + .values() + .filter_map(|(a, b, f)| match f.as_slice() { + [(front, face)] => Some((*a, *b, *front, *face)), + _ => None, + }) + .collect(); + segs.extend(open_edges(&singles, size).into_iter().map(|(a, b)| (plane.to_local(a), plane.to_local(b)))); fit_segments(&segs, size, true) } +/// Of the mesh edges used by one triangle each (`a`, `b`, whether the triangle faces the sketch, +/// its face), those facing the sketch that are outline: an open sheet's border. Where two faces +/// meet, one face's triangles can split the seam at a vertex the other's run straight past, and +/// both sides are then used once; a seam whose other side faces the sketch too is no outline. +fn open_edges(singles: &[(Vec3, Vec3, bool, Option)], size: f64) -> Vec<(Vec3, Vec3)> { + // The two sides of a seam stray from each other by at most a chord's sag. + let seam = size * 2e-3; + let cell = seam * 8.0; + let at = |p: Vec3| ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64, (p.z / cell).floor() as i64); + let mut grid: BTreeMap<(i64, i64, i64), Vec> = BTreeMap::new(); + let mut long: Vec = Vec::new(); + for (i, (a, b, front, _)) in singles.iter().enumerate() { + if !front { + continue; + } + let (lo, hi) = (at(a.min(*b) - Vec3::new(seam, seam, seam)), at(a.max(*b) + Vec3::new(seam, seam, seam))); + let cells = (hi.0 - lo.0 + 1).saturating_mul(hi.1 - lo.1 + 1).saturating_mul(hi.2 - lo.2 + 1); + if cells > 512 { + long.push(i); + continue; + } + for x in lo.0..=hi.0 { + for y in lo.1..=hi.1 { + for z in lo.2..=hi.2 { + grid.entry((x, y, z)).or_default().push(i); + } + } + } + } + singles + .iter() + .enumerate() + .filter(|(i, (a, b, front, face))| { + let m = (*a + *b) * 0.5; + *front + && !grid + .get(&at(m)) + .into_iter() + .flatten() + .chain(&long) + .any(|j| singles.get(*j).is_some_and(|(p, q, _, other)| j != i && other != face && m.dist_to_segment(*p, *q) <= seam)) + }) + .map(|(_, (a, b, _, _))| (*a, *b)) + .collect() +} + +/// Which way a whole face of a body faces, seen along a sketch normal. +#[derive(Clone, Copy)] +enum Facing { + Front, + /// Away from the sketch or edge-on. + Away, +} + +/// Which way face `face` of `body` faces seen along `n`, when it faces one way all over: a +/// plane (edge-on when it contains `n`), a cylinder about `n` (edge-on), a cone about `n`. +/// `sum` is the face's triangles' normals weighted by their areas, dotted with `n`: the side a +/// plane or such a cone faces. `None` for any other face: each triangle says. +fn face_facing(body: &solidcraft_kernel::Body, face: u32, n: Vec3, sum: f64) -> Option { + use solidcraft_kernel::FaceSurface; + let side = if sum > 0.0 { Facing::Front } else { Facing::Away }; + match solidcraft_kernel::face_surface(body, face as usize)? { + FaceSurface::Plane { normal, .. } if normal.vec().dot(n).abs() < 1e-9 => Some(Facing::Away), + FaceSurface::Plane { .. } => Some(side), + FaceSurface::Cylinder { axis, .. } if axis.vec().dot(n).abs() > 1.0 - 1e-12 => Some(Facing::Away), + FaceSurface::Cone { axis, .. } if axis.vec().dot(n).abs() > 1.0 - 1e-12 => Some(side), + _ => None, + } +} + /// Section of a mesh (or one of its faces) with the sketch plane. pub(crate) fn section(plane: &Plane, m: &Mesh, face: Option) -> Vec { let size = m.bounds().diagonal().max(1e-9); @@ -1338,8 +1850,9 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) { for i in 0..out.len() { let Some(LinkGeom::Arc { c, a, b }) = out.get(i).cloned() else { continue }; let r = (c.dist(a) + c.dist(b)) / 2.0; - // (arc end, line index, line end index, tangent point, unit normal towards the centre, centre distance) - let mut hits: Vec<(usize, usize, usize, Vec2, Vec2, f64)> = Vec::new(); + // Per arc end: (gap to the line's end, line index, line end index, tangent point, unit + // normal towards the centre, centre distance) + let mut hits: [Vec<(f64, usize, usize, Vec2, Vec2, f64)>; 2] = [Vec::new(), Vec::new()]; for (end, e) in [a, b].into_iter().enumerate() { for (j, g) in out.iter().enumerate() { let LinkGeom::Line(p, q) = g else { continue }; @@ -1357,17 +1870,39 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) { if (foot - far).dot(near_pt - far) <= 0.0 || near_pt.dist(foot) > 0.25 * r { continue; } - hits.push((end, j, near, foot, n, d)); + // When this end of the arc already meets another piece of the outline and the line + // doesn't end there, the line lies further along (past that piece, as along a + // conic fitted with several arcs): moving the end onto it would leave a gap. + let gap = near_pt.dist(e); + let meets = |g: &LinkGeom| match *g { + LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => s.dist(e) <= tol || t.dist(e) <= tol, + _ => false, + }; + if gap > tol && out.iter().enumerate().any(|(k, g)| k != i && k != j && meets(g)) { + continue; + } + if let Some(h) = hits.get_mut(end) { + h.push((gap, j, near, foot, n, d)); + } } } - let mut hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [None, None]; - for (end, j, near, foot, n, d) in hits { - if let Some(slot) = hits_by_end.get_mut(end) - && slot.is_none() - { - *slot = Some((j, near, foot, n, d)); - } + for h in &mut hits { + h.sort_by(|x, y| x.0.total_cmp(&y.0)); } + // Each end takes the line ending nearest it. Both ends on one line would pull the arc down + // to a point: the end nearer that line's end keeps it, the other takes its next line. + let [ha, hb] = &hits; + let (ta, tb) = match (ha.first(), hb.first()) { + (Some(x), Some(y)) if x.1 == y.1 => { + if x.0 <= y.0 { + (Some(x), hb.iter().find(|h| h.1 != x.1)) + } else { + (ha.iter().find(|h| h.1 != y.1), Some(y)) + } + } + pair => pair, + }; + let hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [ta, tb].map(|h| h.map(|&(_, j, near, foot, n, d)| (j, near, foot, n, d))); let (mut c, mut r) = (c, r); if let [Some((_, _, _, n1, d1)), Some((_, _, _, n2, d2))] = hits_by_end { // One circle tangent to both lines: equal distance to each. diff --git a/crates/doc/src/project3d.rs b/crates/doc/src/project3d.rs index 42f23a37c..cf3b0fbbb 100644 --- a/crates/doc/src/project3d.rs +++ b/crates/doc/src/project3d.rs @@ -1,26 +1,22 @@ -//! 3D sketch curves from the model: curves projected onto faces, intersection curves of bodies -//! and faces (on their display meshes), and spun profiles. +//! 3D sketch curves from the model: curves projected onto faces (on their display meshes), the +//! bodies and faces an intersection curve is taken on, and spun profiles. -use std::collections::BTreeMap; -use std::sync::Arc; - -use solidcraft_geom::{Mesh, Plane, Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; +use solidcraft_geom::Mesh; +use solidcraft_geom::prelude::*; use solidcraft_sketch::LinkSource; use crate::eval::ModelState; -/// Most triangle pairs examined by one intersection. -const MAX_PAIRS: usize = 20_000_000; - -/// The mesh (and face, for a face source) of a body or face reference. -pub(crate) fn mesh_of(st: &ModelState, src: &LinkSource) -> Option<(Arc, Option)> { +/// The body of a body or face reference, and the face (its index in the body's face order) for a +/// face reference: the face nearest its point, on the named body or else the nearest body. +pub(crate) fn part_of<'a>(st: &'a ModelState, src: &LinkSource) -> Option<(&'a crate::ModelBody, Option)> { match src { - LinkSource::Body { body } => Some((st.body(body)?.mesh(), None)), + LinkSource::Body { body } => Some((st.body(body)?, None)), LinkSource::Face { body, at } => { let b = st.body(body).or_else(|| st.bodies.iter().min_by(|x, y| dist_to(&x.mesh(), *at).total_cmp(&dist_to(&y.mesh(), *at))))?; - let m = b.mesh(); - let (f, _, _) = crate::project::nearest_face(&m, *at)?; - Some((m, Some(f))) + let (f, _, _) = crate::project::nearest_face(&b.mesh(), *at)?; + Some((b, usize::try_from(f).ok())) } _ => None, } @@ -99,160 +95,6 @@ pub(crate) fn onto_face(m: &Mesh, f: u32, pts: &[Vec3], dir: Vec3) -> Vec Option<(Vec3, Vec3)> { - let nb = (b[1] - b[0]).cross(b[2] - b[0]).normalized()?; - let na = (a[1] - a[0]).cross(a[2] - a[0]).normalized()?; - // Points where one triangle's edges pass through the other's plane. - let cut = |t: &[Vec3; 3], n: Vec3, o: Vec3| -> Option<(Vec3, Vec3)> { - let h: Vec = t.iter().map(|p| (*p - o).dot(n)).collect(); - if h.iter().all(|x| *x > 1e-12) || h.iter().all(|x| *x < -1e-12) { - return None; - } - let mut pts = Vec::new(); - for (i, j) in [(0usize, 1usize), (1, 2), (2, 0)] { - let (hi, hj) = (h[i], h[j]); - if (hi > 0.0) != (hj > 0.0) { - pts.push(t[i].lerp(t[j], hi / (hi - hj))); - } else if hi == 0.0 { - pts.push(t[i]); - } - } - match pts[..] { - [p, q, ..] => Some((p, q)), - _ => None, - } - }; - if na.cross(nb).len() < 1e-9 { - return None; - } - let (a0, a1) = cut(a, nb, b[0])?; - let (b0, b1) = cut(b, na, a[0])?; - // Overlap of the two segments on the common line. - let dir = na.cross(nb); - let pr = |p: Vec3| p.dot(dir); - let (sa0, sa1) = if pr(a0) <= pr(a1) { (a0, a1) } else { (a1, a0) }; - let (sb0, sb1) = if pr(b0) <= pr(b1) { (b0, b1) } else { (b1, b0) }; - let lo = if pr(sa0) >= pr(sb0) { sa0 } else { sb0 }; - let hi = if pr(sa1) <= pr(sb1) { sa1 } else { sb1 }; - (pr(hi) - pr(lo) > 1e-12).then_some((lo, hi)) -} - -/// Where two meshes (or faces of them) meet, as polylines. -pub(crate) fn mesh_intersection(ma: &Mesh, fa: Option, mb: &Mesh, fb: Option) -> Vec> { - let (ta, tb) = (tris(ma, fa), tris(mb, fb)); - let bbox = |t: &[Vec3; 3]| (t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2])); - // Uniform grid over B. - let lo = tb.iter().fold(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), |m, t| m.min(bbox(t).0)); - let hi = tb.iter().fold(Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |m, t| m.max(bbox(t).1)); - if !(lo.is_finite() && hi.is_finite()) { - return Vec::new(); - } - let n = ((tb.len() as f64).cbrt().ceil() as usize).clamp(1, 48); - let ext = hi - lo; - let cell = |p: Vec3| -> [usize; 3] { - let f = |v: f64, l: f64, e: f64| if e > 1e-12 { (((v - l) / e) * n as f64).floor().clamp(0.0, (n - 1) as f64) as usize } else { 0 }; - [f(p.x, lo.x, ext.x), f(p.y, lo.y, ext.y), f(p.z, lo.z, ext.z)] - }; - let mut grid: BTreeMap<[usize; 3], Vec> = BTreeMap::new(); - for (i, t) in tb.iter().enumerate() { - let (b0, b1) = bbox(t); - let (c0, c1) = (cell(b0), cell(b1)); - for x in c0[0]..=c1[0] { - for y in c0[1]..=c1[1] { - for z in c0[2]..=c1[2] { - grid.entry([x, y, z]).or_default().push(i); - } - } - } - } - let mut segs: Vec<(Vec3, Vec3)> = Vec::new(); - let mut pairs = 0usize; - for t in &ta { - let (b0, b1) = bbox(t); - if b1.x < lo.x || b1.y < lo.y || b1.z < lo.z || b0.x > hi.x || b0.y > hi.y || b0.z > hi.z { - continue; - } - let (c0, c1) = (cell(b0), cell(b1)); - let mut cand: Vec = Vec::new(); - for x in c0[0]..=c1[0] { - for y in c0[1]..=c1[1] { - for z in c0[2]..=c1[2] { - if let Some(v) = grid.get(&[x, y, z]) { - cand.extend(v); - } - } - } - } - cand.sort_unstable(); - cand.dedup(); - for j in cand { - pairs += 1; - if pairs > MAX_PAIRS { - break; - } - if let Some(u) = tb.get(j) - && let Some(sg) = tri_tri(t, u) - { - segs.push(sg); - } - } - } - chain3(&segs, ma.bounds().diagonal().max(mb.bounds().diagonal()).max(1e-9)) -} - -/// Chain 3D segments into polylines by shared end points. -fn chain3(segs: &[(Vec3, Vec3)], size: f64) -> Vec> { - let q = size * 1e-7; - let key = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64); - let mut adj: BTreeMap<(i64, i64, i64), (Vec3, Vec)> = BTreeMap::new(); - let mut uniq: Vec<((i64, i64, i64), (i64, i64, i64))> = Vec::new(); - let mut seen = std::collections::BTreeSet::new(); - for (a, b) in segs { - let (ka, kb) = (key(*a), key(*b)); - if ka == kb { - continue; - } - let k = if ka <= kb { (ka, kb) } else { (kb, ka) }; - if !seen.insert(k) { - continue; - } - let i = uniq.len(); - uniq.push(k); - adj.entry(ka).or_insert_with(|| (*a, Vec::new())).1.push(i); - adj.entry(kb).or_insert_with(|| (*b, Vec::new())).1.push(i); - } - let mut used = vec![false; uniq.len()]; - let mut out = Vec::new(); - let starts: Vec<(i64, i64, i64)> = adj.iter().filter(|(_, v)| v.1.len() != 2).map(|(k, _)| *k).chain(adj.keys().copied()).collect(); - for s in starts { - while let Some(first) = adj.get(&s).and_then(|v| v.1.iter().copied().find(|e| !used.get(*e).copied().unwrap_or(true))) { - let mut chain = vec![adj.get(&s).map(|v| v.0).unwrap_or_default()]; - let mut cur = s; - let mut e = first; - loop { - if let Some(u) = used.get_mut(e) { - *u = true; - } - let Some(&(ka, kb)) = uniq.get(e) else { break }; - cur = if ka == cur { kb } else { ka }; - chain.push(adj.get(&cur).map(|v| v.0).unwrap_or_default()); - let Some(next) = adj - .get(&cur) - .and_then(|v| if v.1.len() == 2 { v.1.iter().copied().find(|x| !used.get(*x).copied().unwrap_or(true)) } else { None }) - else { - break; - }; - e = next; - } - if chain.len() >= 2 { - out.push(chain); - } - } - } - out -} - /// Outline of a body spun about the axis `origin + t·dir`: the largest distance from the axis /// at each station along it, laid into the sketch plane on the side of the axis the plane's /// in-plane perpendicular points to. @@ -351,55 +193,6 @@ pub(crate) fn iso_curve(m: &Mesh, f: u32, p: Vec3, dir: &str) -> Vec> if len(&a) >= len(&b) { a } else { b } } -/// Isocurve analysis: `count` curves each way across face `f` (picked at `p`), as world -/// polylines. Each family is the face cut by parallel planes spaced evenly over the face. -pub fn iso_grid(m: &Mesh, f: u32, p: Vec3, count: usize) -> Vec> { - let count = count.clamp(1, 100); - let verts: Vec = m.triangles.iter().zip(&m.tri_face).filter(|(_, x)| **x == f).filter_map(|(t, _)| m.tri(t)).flatten().collect(); - if verts.is_empty() { - return Vec::new(); - } - let mut out = Vec::new(); - for dir in ["u", "v"] { - // The family's cutting direction, from the curve through p. - let Some(first) = iso_curve(m, f, p, dir).into_iter().next() else { continue }; - let pts: Vec = first.to_vec(); - // Normal of the plane that curve lies in. - let Some(c) = pts.first().copied() else { continue }; - let mut n = Vec3::ZERO; - for w in pts.windows(2) { - n += (w[0] - c).cross(w[1] - c); - } - let cut_n = match n.normalized() { - Some(n) => n, - // A straight curve: across it, within the face. - None => { - let d = pts.last().copied().unwrap_or(c) - c; - let np = (verts[1] - verts[0]).cross(verts[2] - verts[0]); - match d.cross(np).normalized() { - Some(x) => x, - None => continue, - } - } - }; - let (lo, hi) = verts.iter().map(|v| v.dot(cut_n)).fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), x| (a.min(x), b.max(x))); - if !(hi - lo > 1e-9) { - continue; - } - for k in 1..=count { - let d = lo + (hi - lo) * k as f64 / (count + 1) as f64; - let Some(pl) = Plane::from_normal(cut_n * d, cut_n) else { continue }; - for g in crate::project::section(&pl, m, Some(f)) { - let w: Vec = link_polyline(&g).into_iter().map(|q| pl.to_world(q)).collect(); - if w.len() >= 2 { - out.push(w); - } - } - } - } - out -} - /// Join polylines whose ends meet into longer ones. fn join_wires(mut ws: Vec>, tol: f64) -> Vec> { let mut out: Vec> = Vec::new(); @@ -456,7 +249,9 @@ fn link_polyline(g: &solidcraft_sketch::LinkGeom) -> Vec { LinkGeom::Ellipse { c, major, minor } => { (0..=96).map(|i| solidcraft_sketch::ellipse_point(c, major, minor, i as f64 / 96.0 * std::f64::consts::TAU)).collect() } - LinkGeom::Spline { ref pts, control, degree, periodic } => solidcraft_sketch::spline_polyline_mode(pts, control, degree, periodic), + LinkGeom::Spline { ref pts, control, degree, periodic, ref nurbs } => { + solidcraft_sketch::spline_polyline_mode(pts, control, degree, periodic, nurbs.as_ref()) + } LinkGeom::Point(_) => Vec::new(), } } diff --git a/crates/doc/src/project_order.rs b/crates/doc/src/project_order.rs index f59cdfa79..29792b4fe 100644 --- a/crates/doc/src/project_order.rs +++ b/crates/doc/src/project_order.rs @@ -1,9 +1,11 @@ //! Stable face projection order: outer boundary first, then holes by geometry. //! B-rep edge indices depend on face enumeration and must not choose sketch curve IDs. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; -use solidcraft_geom::{Aabb3, Mesh, Plane, Vec3}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::{Aabb3, Mesh}; use crate::{DocError, Result}; @@ -177,6 +179,26 @@ fn boundary_edges(mesh: &Mesh, mut edges: Vec, faces: &BTreeSet, p mod tests { use super::*; + /// A cube's outline from above is its four sides whatever normals its mesh carries: none, too + /// few, zero or not numbers fall back to each triangle's own normal, and so do normals + /// averaged across its creases, as an imported mesh may have them. + #[test] + fn a_silhouette_takes_the_triangles_own_normal_where_the_mesh_has_no_surface_normal() { + let corner = |i: u32| Vec3::new(f64::from(i & 1), f64::from((i >> 1) & 1), f64::from((i >> 2) & 1)) * 10.0; + let positions: Vec = (0..8).map(corner).collect(); + 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 triangles: Vec<[u32; 3]> = quads.iter().flat_map(|[a, b, c, d]| [[*a, *b, *c], [*a, *c, *d]]).collect(); + let averaged: Vec = positions.iter().map(|p| (*p - Vec3::new(5.0, 5.0, 5.0)).normalized().unwrap_or(Vec3::Z)).collect(); + let nan = Vec3::new(f64::NAN, 0.0, 0.0); + for normals in [Vec::new(), vec![Vec3::Z; 3], vec![Vec3::ZERO; 8], vec![nan; 8], vec![Vec3::new(f64::INFINITY, 0.0, 0.0); 8], averaged] { + let tri_face = vec![0; triangles.len()]; + let mesh = Mesh { positions: positions.clone(), normals: normals.clone(), triangles: triangles.clone(), tri_face, ..Mesh::default() }; + let outline = super::super::silhouette(&Plane::XY, &mesh, None); + let sides = outline.iter().filter(|g| matches!(g, solidcraft_sketch::LinkGeom::Line(a, b) if (a.dist(*b) - 10.0).abs() < 1e-9)).count(); + assert_eq!((outline.len(), sides), (4, 4), "{normals:?}: {outline:?}"); + } + } + #[test] fn face_family_omits_only_exact_shared_topological_edges() { let mut mesh = Mesh::default(); @@ -208,7 +230,7 @@ mod tests { #[test] fn coarsely_tessellated_round_silhouette_fits_an_arc() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::LinkGeom; let on = |deg: f64| Vec2::new(5. + 5. * deg.to_radians().cos(), 5. + 5. * deg.to_radians().sin()); let mut chain = vec![Vec2::new(0., -20.)]; @@ -221,7 +243,7 @@ mod tests { #[test] fn tangent_snapping_leaves_unrelated_collinear_lines_alone() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::LinkGeom; let v = Vec2::new; // A rounded corner of radius 2 meeting the top edge, and an unrelated collinear edge. @@ -235,6 +257,117 @@ mod tests { let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.get(1), out.get(2)) else { panic!("{out:?}") }; assert!(a.dist(*p) < 1e-9, "{out:?}"); } + + #[test] + fn tangent_snapping_leaves_a_line_further_along_alone() { + use solidcore_record::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + // The arc's end at x = 0.5 already meets the next piece; the line along y = 0 ends at + // x = 0.3, further along the outline the other way. Snapping onto it would pull the end + // off the piece it meets. + let mut out = vec![ + LinkGeom::Arc { c: v(0., 2.), a: v(0.5, y(0.5)), b: v(-1.5, y(-1.5)) }, + LinkGeom::Line(v(0.3, 0.), v(10., 0.)), + LinkGeom::Line(v(0.5, y(0.5)), v(3., 3.)), + ]; + let before = out.clone(); + super::super::snap_tangent_arcs(&mut out, 0.05); + assert_eq!(out.get(1), before.get(1), "{out:?}"); + let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.first(), out.get(2)) else { panic!("{out:?}") }; + assert!(a.dist(*p) < 1e-9, "{out:?}"); + } + + #[test] + fn tangent_snapping_gives_one_line_to_one_end_of_an_arc() { + use solidcore_record::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + // A short arc whose two ends both lie near the end of one line: both snapping onto it + // would shrink the arc to the tangent point. + let mut out = vec![LinkGeom::Arc { c: v(0., 2.), a: v(-0.2, y(-0.2)), b: v(0.2, y(0.2)) }, LinkGeom::Line(v(-10., 0.), v(0., 0.))]; + super::super::snap_tangent_arcs(&mut out, 0.05); + let Some(LinkGeom::Arc { a, b, .. }) = out.first() else { panic!("{out:?}") }; + assert!(a.dist(*b) > 0.1, "{out:?}"); + } + + #[test] + fn tangent_snapping_moves_the_other_end_of_an_arc_to_its_next_line() { + use solidcore_record::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + let (a, b) = (v(-0.2, y(-0.2)), v(0.2, y(0.2))); + // The line along y = 0 ends nearest both ends of the arc but nearer b, which keeps it; a + // takes the next line, tangent to the circle at a and ending a little past it. + let back = (v(0., 2.) - a).normalized().map(|n| v(-n.y, n.x)).unwrap_or(Vec2::X); + let mut out = + vec![LinkGeom::Arc { c: v(0., 2.), a, b }, LinkGeom::Line(v(0.1, 0.), v(10., 0.)), LinkGeom::Line(a + back * 10., a + back * 0.35)]; + super::super::snap_tangent_arcs(&mut out, 0.05); + let (Some(LinkGeom::Arc { a, b, .. }), Some(LinkGeom::Line(p, _)), Some(LinkGeom::Line(_, q))) = (out.first(), out.get(1), out.get(2)) else { + panic!("{out:?}") + }; + assert!(b.dist(*p) < 1e-9 && a.dist(*q) < 1e-9 && a.dist(*b) > 0.1, "{out:?}"); + } + + #[test] + fn tangent_snapping_closes_a_conic_corner_in_any_order() { + use solidcore_record::Vec2; + use solidcraft_sketch::LinkGeom; + // A square of side 150 with a conic round of 10 mm legs at each corner, fitted with lines + // and arcs the way a silhouette is, then snapped with the pieces in each order. + for rho in [0.1, 0.15, 0.5, 0.8, 0.9] { + let w = rho / (1. - rho); + let conic = |s: Vec2, apex: Vec2, e: Vec2, t: f64| { + let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t); + (s * b0 + apex * b1 + e * b2) * (1. / (b0 + b1 + b2)) + }; + let v = Vec2::new; + let corners = [ + (v(-75., 65.), v(-75., 75.), v(-65., 75.)), + (v(65., 75.), v(75., 75.), v(75., 65.)), + (v(75., -65.), v(75., -75.), v(65., -75.)), + (v(-65., -75.), v(-75., -75.), v(-75., -65.)), + ]; + let mut chain = Vec::new(); + for (s, apex, e) in corners { + chain.extend((0..=40).map(|k| conic(s, apex, e, f64::from(k) / 40.))); + } + if let Some(&first) = chain.first() { + chain.push(first); + } + let mut fitted = Vec::new(); + super::super::fit_chain_with_arcs(&chain, Some(212. * 1e-5), &mut fitted, true); + assert!(fitted.iter().any(|g| matches!(g, LinkGeom::Arc { .. })), "{fitted:?}"); + let ends = |g: &LinkGeom| match *g { + LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => vec![s, t], + _ => Vec::new(), + }; + for k in 0..fitted.len() { + let mut out = fitted.clone(); + out.rotate_left(k); + super::super::snap_tangent_arcs(&mut out, 212. * 1e-3); + // Every end still meets another piece's end. An end left without a line moves a little + // when the arc's radius is set from the lines (well under 0.01 mm here); before, ends + // pulled onto lines further along left gaps of 0.25 to 0.55 mm. + for (i, g) in out.iter().enumerate() { + for e in ends(g) { + let gap = out + .iter() + .enumerate() + .filter(|(j, _)| *j != i) + .flat_map(|(_, h)| ends(h)) + .map(|x| x.dist(e)) + .fold(f64::INFINITY, f64::min); + assert!(gap < 212. * 1e-3 * 0.02, "rho {rho}, rotation {k}: gap {gap} at {e:?}: {out:?}"); + } + } + } + } + } + #[test] fn boundaries_touching_at_a_vertex_project() { // Two squares of one face family meet only at the corner (1, 1): four boundary edges meet @@ -279,7 +412,7 @@ mod tests { #[test] fn family_line_normalization_preserves_corners_arcs_branches_and_retracing() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::LinkGeom; let line = |a, b| LinkGeom::Line(Vec2::new(a, 0.), Vec2::new(b, 0.)); assert_eq!(super::super::merge_family_lines(vec![line(0., 1.), line(2., 1.)]).unwrap(), vec![line(0., 2.)]); @@ -291,7 +424,13 @@ mod tests { vec![ line(0., 1.), line(1., 2.), - LinkGeom::Spline { pts: vec![Vec2::new(1., 0.), Vec2::new(2., 1.), Vec2::new(3., 1.)], control: false, degree: 2, periodic: false }, + LinkGeom::Spline { + pts: vec![Vec2::new(1., 0.), Vec2::new(2., 1.), Vec2::new(3., 1.)], + control: false, + degree: 2, + periodic: false, + nurbs: None, + }, ], vec![line(0., 1.), LinkGeom::Arc { c: Vec2::new(1., 1.), a: Vec2::new(1., 0.), b: Vec2::new(2., 1.) }], vec![line(0., 1.), line(1.00001, 2.)], @@ -361,7 +500,7 @@ mod tests { #[test] fn rounded_boundary_arc_sweeps_survive_individual_edge_reversal() { - use solidcraft_geom::{Seg2, Vec2}; + use solidcore_record::{Seg2, Vec2}; use solidcraft_sketch::LinkGeom; let mut mesh = Mesh::default(); for (extent, radius) in [(10.0, 3.0), (8.0, 1.0)] { @@ -456,7 +595,7 @@ mod tests { #[test] fn curve_ends_a_hair_apart_become_one_point_and_distant_ones_stay() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::LinkGeom; let mut geom = vec![ LinkGeom::Line(Vec2::new(0., 0.), Vec2::new(10., 0.)), @@ -465,13 +604,20 @@ mod tests { control: true, degree: 3, periodic: false, + nurbs: None, }, LinkGeom::Line(Vec2::new(12., 5. - 1e-5), Vec2::new(0., 0.1)), ]; super::super::meet_at_shared_ends(&mut geom, 1e-4); assert_eq!( geom[1], - LinkGeom::Spline { pts: vec![Vec2::new(10., 0.), Vec2::new(11., 1.), Vec2::new(12., 5.)], control: true, degree: 3, periodic: false } + LinkGeom::Spline { + pts: vec![Vec2::new(10., 0.), Vec2::new(11., 1.), Vec2::new(12., 5.)], + control: true, + degree: 3, + periodic: false, + nurbs: None + } ); assert_eq!(geom[2], LinkGeom::Line(Vec2::new(12., 5.), Vec2::new(0., 0.1))); } diff --git a/crates/doc/src/render_optics.rs b/crates/doc/src/render_optics.rs index c6e7db74f..2915d9398 100644 --- a/crates/doc/src/render_optics.rs +++ b/crates/doc/src/render_optics.rs @@ -5,7 +5,7 @@ use crate::{ render_surface::{RenderBodyTarget, bounded_sequence}, }; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_render::{ surface::OpaqueSurface, transmission::{Transmission, subsurface::Subsurface}, diff --git a/crates/doc/src/render_settings.rs b/crates/doc/src/render_settings.rs index 4bec6f7c2..d1a62568b 100644 --- a/crates/doc/src/render_settings.rs +++ b/crates/doc/src/render_settings.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_render::{BackendId, Camera, RenderFormat, RenderLimits, RenderMode, UpAxis}; pub use crate::render_job::{CpuJob, GpuJob, RenderJob, SkyEnvironment}; @@ -39,6 +39,12 @@ pub struct RenderSetup { pub stage: solidcraft_render::stage::Stage, } +/// The CPU request a size check belongs to, so a refusal can name the profile that admits it. +#[derive(Clone, Copy)] +struct CpuSize { + progressive: Option, +} + // Reuse Camera's representation and defaults, but reject misspelled saved fields. A remote // derive constructs Camera itself, so adding a Camera field requires updating this adapter. // Navigation/named-view deserialization keeps its existing compatibility policy. @@ -80,27 +86,29 @@ impl Default for RenderSetup { impl RenderSetup { pub fn validate(&self) -> Result<()> { - let limits = match &self.job { - Some(RenderJob::CpuRaytrace { options }) => options.budget.image_limits(options.progressive.is_some()), - Some(RenderJob::GpuPath { .. }) => solidcraft_render::job::GPU_PATH_LIMITS, - _ => RenderLimits::default(), + let (limits, cpu) = match &self.job { + Some(RenderJob::CpuRaytrace { options }) => { + (options.budget.image_limits(options.progressive.is_some()), Some(CpuSize { progressive: options.progressive })) + } + Some(RenderJob::GpuPath { .. }) => (solidcraft_render::job::GPU_PATH_LIMITS, None), + _ => (RenderLimits::default(), None), }; - self.validate_with_limits(limits) + self.validate_with_limits(limits, cpu) } /// Runtime CPU lowering has already moved typed options out of this setup. /// Saving still uses validate(), so a legacy setup cannot smuggle a large profile. pub fn validate_for_cpu(&self, budget: solidcraft_render::job::CpuBudget) -> Result<()> { budget.validate_image(self.width, self.height, None).map_err(|e| DocError::Invalid(e.to_string()))?; - self.validate_with_limits(budget.image_limits(false)) + self.validate_with_limits(budget.image_limits(false), Some(CpuSize { progressive: None })) } /// Typed GPU options have already been lowered; retain their dimension envelope. pub fn validate_for_gpu(&self) -> Result<()> { - self.validate_with_limits(solidcraft_render::job::GPU_PATH_LIMITS) + self.validate_with_limits(solidcraft_render::job::GPU_PATH_LIMITS, None) } - fn validate_with_limits(&self, limits: RenderLimits) -> Result<()> { + fn validate_with_limits(&self, limits: RenderLimits, cpu: Option) -> Result<()> { self.surfaces.validate()?; self.optics.validate()?; if !self.optics.is_empty() && !matches!(self.job, Some(RenderJob::GpuPath { .. })) { @@ -123,9 +131,14 @@ impl RenderSetup { if let Some((w, h)) = limits.fit(width, height, None) && (w, h) != (width, height) { + // A CPU refusal names the profile that can render the size (#8941). It is never + // selected for the person: resolution and profile change only when they choose. + let advice = cpu.map_or_else(String::new, |cpu| { + format!("; {}", solidcraft_render::job::CpuBudget::size_advice(self.width, self.height, cpu.progressive)) + }); return Err(DocError::Invalid(format!( "render output {width} × {height} exceeds the image limits ({} pixels per side, {} pixels in all); \ - the largest image at this aspect is {w} × {h}", + the largest image at this aspect is {w} × {h}{advice}", limits.max_dimension, limits.max_pixels ))); } @@ -538,9 +551,58 @@ mod tests { let setup = RenderSetup { width: 7680, height: 4320, ..Default::default() }; let message = setup.validate().unwrap_err().to_string(); assert!(message.contains("the largest image at this aspect is 27"), "{message}"); + assert!(!message.contains("CPU resource profile"), "a raster refusal names no CPU profile: {message}"); assert!(RenderSetup { width: 2048, height: 2048, ..Default::default() }.validate().is_ok()); } + /// #8941: 4K UHD under the default Compact profile names Studio, the profile that renders it; + /// a 16K-wide image under Studio names Workstation; past Workstation no profile is named. + /// The saved profile is never changed by the check, and GPU path tracing keeps its own limits. + #[test] + fn a_cpu_size_refusal_names_the_profile_that_can_render_it() { + use solidcraft_render::job::CpuBudget; + let cpu = |budget, width, height| RenderSetup { + width, + height, + job: Some(RenderJob::CpuRaytrace { options: CpuJob { budget, ..Default::default() } }), + ..Default::default() + }; + let compact = cpu(CpuBudget::Compact, 3840, 2160); + let message = compact.validate().unwrap_err().to_string(); + assert!(message.contains("3840 × 2160 exceeds the image limits (4096 pixels per side, 4194304 pixels in all)"), "{message}"); + assert!(message.contains("the largest image at this aspect is 2730 × 1536"), "{message}"); + assert!(message.contains("choose the Studio CPU resource profile, or a smaller size"), "{message}"); + assert!(matches!(&compact.job, Some(RenderJob::CpuRaytrace { options }) if options.budget == CpuBudget::Compact)); + let message = compact.validate_for_cpu(CpuBudget::Compact).unwrap_err().to_string(); + assert!(message.contains("choose the Studio CPU resource profile"), "{message}"); + + cpu(CpuBudget::Studio, 3840, 2160).validate().unwrap(); + RenderSetup { width: 3840, height: 2160, ..Default::default() }.validate_for_cpu(CpuBudget::Studio).unwrap(); + + let message = cpu(CpuBudget::Studio, 15360, 4320).validate().unwrap_err().to_string(); + assert!(message.contains("choose the Workstation CPU resource profile"), "{message}"); + cpu(CpuBudget::Workstation, 15360, 4320).validate().unwrap(); + + let message = cpu(CpuBudget::Workstation, 16384, 16384).validate().unwrap_err().to_string(); + assert!(message.contains("no CPU resource profile accepts this size; choose a smaller size"), "{message}"); + for profile in ["Compact", "Studio", "Workstation"] { + assert!(!message.contains(&format!("the {profile} CPU")), "{message}"); + } + + // GPU path tracing: 4K renders, an over-limit size names no CPU profile. + let gpu = |width, height| RenderSetup { + width, + height, + job: Some(RenderJob::GpuPath { transparent_background: false, options: Default::default() }), + ..Default::default() + }; + gpu(3840, 2160).validate().unwrap(); + gpu(3840, 2160).validate_for_gpu().unwrap(); + let message = gpu(8193, 8193).validate().unwrap_err().to_string(); + assert!(message.contains("(8192 pixels per side, 16777216 pixels in all)"), "{message}"); + assert!(!message.contains("CPU resource profile"), "{message}"); + } + #[test] fn portable_jobs_preserve_complete_numerical_intent_and_legacy_omission() { use serde_json::json; diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 67802bafa..40ece1ede 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -10,7 +10,9 @@ //! together; the flat solid is the outline extruded through the thickness. use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Aabb2, ArcMap, LINEAR_TOL, Loop2, Plane, Region2, Ring, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Aabb2, ArcMap, LINEAR_TOL, Ring}; use solidcraft_kernel::{self as kernel, Body, EdgeSpec, FaceSpec, SurfSpec}; use crate::expr::{self, Kind, Value}; @@ -461,8 +463,17 @@ impl Document { /// Evaluate a rule: `Thickness` in its expressions is the rule's thickness. pub fn rule_values(&self, vals: &std::collections::BTreeMap, r: &SheetRule) -> Result { + self.rule_values_at(vals, r, None) + } + + /// Evaluate a rule for a sheet `thickness` thick (a converted body's own thickness), or the + /// rule's thickness: `Thickness` in its expressions is the sheet's. + pub fn rule_values_at(&self, vals: &std::collections::BTreeMap, r: &SheetRule, thickness: Option) -> Result { let look = |n: &str| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))); - let t = expr::eval_with(&r.thickness, &look)?.to_kind(Kind::Length)?; + let t = match thickness { + Some(t) => t, + None => expr::eval_with(&r.thickness, &look)?.to_kind(Kind::Length)?, + }; if !(t > 0.0 && t < 1e4) { return Err(DocError::Invalid("the sheet thickness must be positive".into())); } @@ -529,6 +540,10 @@ pub struct SheetFlange { /// (flat coordinates, counter-clockwise). #[serde(default, skip_serializing_if = "Option::is_none")] pub exact: Option, + /// A fold's bend zone as drawn, when a curved edge of the sheet crosses it (flat coordinates, + /// counter-clockwise): `zone` is this instead of straight ends. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub zone_shape: Option, /// Which feature made it: `F.` (persistent edge names). #[serde(default, skip_serializing_if = "String::is_empty")] pub tag: String, @@ -688,6 +703,10 @@ pub struct SheetPerforation { /// copy, whose holes are the mirror image of its source's. #[serde(skip_serializing_if = "std::ops::Not::not")] pub from_right: bool, + /// The field's outline in flat coordinates (see [`SheetBody::perforation_outline`]): holes only inside these + /// regions, margin clear of their edges, on a grid that starts from their bounding box. None: the whole flat. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outline: Option>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -830,6 +849,205 @@ fn rect(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Region2 { Region2 { outer: lp, holes: Vec::new() } } +/// How a fold's bend runs along its line `d`: where its start line starts and ends, how far its far +/// edge runs on past those ends, and which ends are cut askew (`SheetFlange::ext`, `tear`). +type FoldEnds = (f64, f64, (f64, f64), (bool, bool)); + +/// The ends of a fold's zone (`strip`, between the lines at `s0` and `s0 + ba` along `n`) when +/// straight edges of the sheet slant across it, so that it folds as a bend with torn ends. Every +/// corner must lie on one of the two lines: a curved edge has corners in between, and an S of the +/// same area as a straight end would pass on area alone. +fn slanted_zone(strip: &[Vec2], n: Vec2, d: Vec2, s0: f64, ba: f64) -> Option { + let on_line = |q: &Vec2, s: f64| (q.dot(n) - s).abs() <= ZONE_SQUARE_TOL; + if !strip.iter().all(|q| on_line(q, s0) || on_line(q, s0 + ba)) { + return None; + } + let span = |s: f64| { + let mut along = strip.iter().filter(|q| on_line(q, s)).map(|q| q.dot(d)); + let first = along.next()?; + Some(along.fold((first, first), |(lo, hi), u| (lo.min(u), hi.max(u)))) + }; + let ((a0, a1), (e0, e1)) = (span(s0)?, span(s0 + ba)?); + let (start, far) = (a1 - a0, e1 - e0); + let trapezoid = (start + far) / 2.0 * ba; + if start <= ZONE_SQUARE_TOL + || far <= ZONE_SQUARE_TOL + || (trapezoid - signed_area(strip).abs()).abs() > 1e-6 * start.max(far).max(1.0) * ba.max(1.0) + { + return None; + } + let end = |on: f64| if on.abs() > ZONE_SQUARE_TOL { (on, true) } else { (0.0, false) }; + let ((on0, torn0), (on1, torn1)) = (end(a0 - e0), end(e1 - a1)); + Some((a0, a1, (on0, on1), (torn0, torn1))) +} + +/// A turn sharper than this (its sine) between two edges of an outline is a corner. Smooth curves +/// and their chords turn less: a chord at the sheet's 0.001 mm tolerance turns about 5° on a 1 mm +/// radius. +const CORNER_TURN: f64 = 0.17; + +/// Where two edges of an outline meet at a corner. +fn outline_corners(outline: &Loop2) -> Vec { + let segs = &outline.segs; + let mut corners = Vec::new(); + for (i, next) in segs.iter().enumerate() { + let Some(prev) = segs.get((i + segs.len() - 1) % segs.len()) else { continue }; + let (t0, t1) = (prev.end_tangent(), next.start_tangent()); + if t0.cross(t1).abs() > CORNER_TURN || t0.dot(t1) < 0.0 { + corners.push(next.start()); + } + } + corners +} + +/// `seg` in pieces, cut where it crosses the line `level` along `n`, into `out`. A curve that only +/// touches the line stays whole. +fn cut_at_level(seg: &Seg2, n: Vec2, level: f64, out: &mut Vec) { + const SAMPLES: usize = 64; + const MAX_CROSSINGS: usize = 16; + const ON_LINE: f64 = 1e-9; + let off = |s: &Seg2, t: f64| s.point_at(t).dot(n) - level; + let mut rest = *seg; + for _ in 0..MAX_CROSSINGS { + // The first change of side, skipping samples on the line itself. + let (mut last, mut crossing) = (None::<(f64, f64)>, None); + for k in 0..=SAMPLES { + let t = k as f64 / SAMPLES as f64; + let v = off(&rest, t); + if v.abs() <= ON_LINE { + continue; + } + match last { + Some((was, before)) if before * v < 0.0 => { + crossing = Some((was, t, before)); + break; + } + _ => last = Some((t, v)), + } + } + let Some((mut lo, mut hi, before)) = crossing else { break }; + // On the distance itself: the cut lands on the line, and what's left starts on it. + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if off(&rest, mid) * before > 0.0 { + lo = mid; + } else { + hi = mid; + } + } + let (first, second) = rest.split_at((lo + hi) / 2.0); + out.push(first); + rest = second; + } + out.push(rest); +} + +/// A panel's outline cut exactly across a fold whose zone a curved edge crosses, each piece +/// keeping its exact curves. +#[derive(Clone, Debug, PartialEq)] +struct CurvedFold { + fixed: Loop2, + zone: Loop2, + moving: Loop2, + ends: FoldEnds, +} + +/// `outline` cut into the side short of the zone between the lines at `s0` and `s0 + ba` along `n`, +/// the zone, and the side past it. It must run from one side through the zone to the other and +/// back through the zone, once: a notch, several tabs on the line or a zone that reaches the +/// outline's tip is `None`. Both of the zone's ends count as torn: their edges aren't square across. +fn curved_fold(outline: &Loop2, n: Vec2, d: Vec2, s0: f64, ba: f64) -> Option { + const ON_LINE: f64 = 1e-6; + if outline.segs.len() > MAX_FLAT_POINTS { + return None; + } + let outline = outline.ccw(); + let mut pieces = Vec::new(); + for seg in &outline.segs { + let mut near = Vec::new(); + cut_at_level(seg, n, s0, &mut near); + for piece in &near { + cut_at_level(piece, n, s0 + ba, &mut pieces); + } + } + // The band each piece lies in: 0 short of the zone, 1 in it, 2 past it. A piece along either + // line is an edge square across the bend, not one crossing it. + let mut bands = Vec::with_capacity(pieces.len()); + for piece in &pieces { + let v = piece.mid().dot(n); + if !v.is_finite() || (v - s0).abs() <= ON_LINE || (v - s0 - ba).abs() <= ON_LINE { + return None; + } + bands.push(if v < s0 { + 0 + } else if v > s0 + ba { + 2 + } else { + 1 + }); + } + // Round the outline from where it enters the side short of the zone. + let count = pieces.len(); + let first = (0..count).find(|&i| bands.get(i) == Some(&0) && bands.get((i + count - 1) % count) != Some(&0))?; + let mut runs: Vec<(i32, Vec)> = Vec::new(); + for k in 0..count { + let i = (first + k) % count; + let (band, piece) = (*bands.get(i)?, *pieces.get(i)?); + match runs.last_mut() { + Some((b, run)) if *b == band => run.push(piece), + _ => runs.push((band, vec![piece])), + } + } + let [(0, near), (1, there), (2, far), (1, back)] = runs.as_slice() else { return None }; + let ends_of = |run: &[Seg2]| Some((run.first()?.start(), run.last()?.end())); + let ((near0, near1), (there0, there1), (far0, far1), (back0, back1)) = (ends_of(near)?, ends_of(there)?, ends_of(far)?, ends_of(back)?); + let on = |q: Vec2, s: f64| (q.dot(n) - s).abs() <= ON_LINE; + if !(on(near0, s0) && on(near1, s0) && on(far0, s0 + ba) && on(far1, s0 + ba)) { + return None; + } + let closed = |run: &[Seg2], to: Vec2, from: Vec2| { + let mut segs = run.to_vec(); + segs.push(Seg2::Line { a: to, b: from }); + segs + }; + let mut zone = closed(there, there1, back0); + zone.extend_from_slice(back); + zone.push(Seg2::Line { a: back1, b: there0 }); + let span = |p: Vec2, q: Vec2| (p.dot(d).min(q.dot(d)), p.dot(d).max(q.dot(d))); + let ((a0, a1), (e0, e1)) = (span(near0, near1), span(far0, far1)); + if a1 - a0 <= ON_LINE || e1 - e0 <= ON_LINE { + return None; + } + Some(CurvedFold { + fixed: Loop2 { segs: closed(near, near1, near0) }, + zone: Loop2 { segs: zone }, + moving: Loop2 { segs: closed(far, far1, far0) }, + ends: (a0, a1, (a0 - e0, e1 - a1), (true, true)), + }) +} + +/// Two counter-clockwise loops joined along a straight edge they share, running opposite ways: +/// every curve of both exactly as it was, which the planar booleans wouldn't hand back. +fn join_along_seam(a: &Loop2, b: &Loop2) -> Option { + const SAME: f64 = 1e-6; + if a.segs.len().saturating_mul(b.segs.len()) > MAX_FLAT_POINTS { + return None; + } + for (i, ea) in a.segs.iter().enumerate() { + let Seg2::Line { a: p, b: q } = *ea else { continue }; + for (j, eb) in b.segs.iter().enumerate() { + let Seg2::Line { a: r, b: s } = *eb else { continue }; + if p.dist(s) <= SAME && q.dist(r) <= SAME { + let mut segs = Vec::with_capacity(a.segs.len() + b.segs.len()); + segs.extend(a.segs.iter().skip(i + 1).chain(a.segs.iter().take(i)).cloned()); + segs.extend(b.segs.iter().skip(j + 1).chain(b.segs.iter().take(j)).cloned()); + return Some(Loop2 { segs }); + } + } + } + None +} + /// Round to a 1e-9 mm grid (keeps trimmed edges exactly where the kernel expects them). fn snap(v: Vec2) -> Vec2 { let r = |x: f64| (x * 1e9).round() / 1e9; @@ -1087,6 +1305,9 @@ impl SheetBody { /// Flat region of a flange's bend zone: square across the bend at both ends, but at a torn /// end its far edge ends where the panel's does. pub fn zone(&self, f: &SheetFlange) -> Region2 { + if let Some(lp) = &f.zone_shape { + return Region2 { outer: lp.ccw(), holes: Vec::new() }; + } let ba = self.allowance(f); let (u0, u1) = self.zone_span(f); let (a, b) = (f.p + f.d * u0, f.p + f.d * u1); @@ -1103,6 +1324,32 @@ impl SheetBody { (if f.tear.0 { -f.ext.0 } else { u0 }, if f.tear.1 { f.len + f.ext.1 } else { u1 }) } + /// How far a bend's zone reaches along the bend from `p`: a torn end runs askew, and a curved + /// edge may bulge past both of its ends. + pub(crate) fn zone_reach(&self, f: &SheetFlange) -> (f64, f64) { + if let Some(lp) = &f.zone_shape { + return lp.polyline(1e-3).iter().map(|q| (*q - f.p).dot(f.d)).fold((f64::MAX, f64::MIN), |(lo, hi), u| (lo.min(u), hi.max(u))); + } + let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f)); + (u0.min(e0), u1.max(e1)) + } + + /// Where a bend's centre line starts and ends, along the bend from `p`: between the middles + /// of the bend's two ends (a torn end is askew), or where a curved edge crosses it. + fn centre_line(&self, f: &SheetFlange) -> (f64, f64) { + if let Some(lp) = &f.zone_shape { + let mut at = Vec::new(); + for e in &lp.segs { + line_hits(f.p + f.n * (self.allowance(f) / 2.0), f.d, e, &mut at); + } + if let (Some(lo), Some(hi)) = (at.iter().copied().reduce(f64::min), at.iter().copied().reduce(f64::max)) { + return (lo, hi); + } + } + let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f)); + ((u0 + e0) / 2.0, (u1 + e1) / 2.0) + } + /// Folded (in the flat frame, as `fold`), the point of a bend's end (the one at `p`, or the /// other one when `at_end`) at the turn `phi` of the bend and the height `z` in the sheet. A /// torn end runs evenly along the bend while the bend turns, from its start line's end to @@ -1141,7 +1388,9 @@ impl SheetBody { if let Some(shape) = &f.shape && let Some((lo, hi)) = edge_span(shape, f.p + f.n * self.allowance(f)) { - return (span.0.max(lo), span.1.min(hi)); + // A torn end runs askew to where the panel's end starts, so the panel's root doesn't + // limit the bend there. + return (if f.tear.0 { span.0 } else { span.0.max(lo) }, if f.tear.1 { span.1 } else { span.1.min(hi) }); } span } @@ -1396,11 +1645,22 @@ impl SheetBody { let mut v = Vec::new(); for e in segs { let Seg2::Line { a, b } = *e else { - split_edges += 1; - if split_edges > MAX_FLAT_POINTS { - return Err(flat_budget_error()); + // A closed curve (a whole circle is one arc, `Loop2::circle`) in its two + // exact halves: a sewn edge runs between two vertices, and an arc's wall is + // the cylinder through its ends and middle. + let halves = if e.start().dist(e.end()) < LINEAR_TOL { + let (h0, h1) = e.split_half(); + vec![h0, h1] + } else { + vec![*e] + }; + for h in halves { + split_edges += 1; + if split_edges > MAX_FLAT_POINTS { + return Err(flat_budget_error()); + } + v.push(h); } - v.push(*e); continue; }; let d = b - a; @@ -1668,54 +1928,27 @@ impl SheetBody { let slab = kernel::extrude_planar_regions(&Plane::XY, &cells, 0.0, self.t)?; let drill = kernel::cylinder(bore.base, bore.axis, bore.radius, bore.height)?; let Some(inside) = kernel::boolean(&drill, &slab, kernel::BoolOp::Intersect)? else { continue }; - // Cut with the drill clipped to the panel. Where its ends, flush with the panel's - // rims, leave coincident faces the cut can't resolve, cut with the drill as long as - // the panel's material along it and a hair past it instead (the same material). + // Cut with the drill clipped to the panel, its ends flush with the panel's rims. let place = |tool: Body| if self.flat { Ok(tool) } else { kernel::transform_matrix(&tool, self.world(bore.panel)) }; - let mut last = None; - for longer in [false, true] { - let tool = if longer { - let axis = bore.axis.normalized().ok_or_else(|| DocError::Invalid("invalid sheet bore".into()))?; - let mesh = inside.tessellate((bore.radius * 0.1).max(1e-4))?; - let (lo, hi) = - mesh.positions.iter().map(|p| (*p - bore.base).dot(axis)).fold((f64::MAX, f64::MIN), |(lo, hi), d| (lo.min(d), hi.max(d))); - if !(lo <= hi) { - break; - } - let past = (bore.radius * 0.05).max(1e-3); - kernel::cylinder(bore.base + axis * (lo - past), axis, bore.radius, hi - lo + 2.0 * past)? - } else { - inside.clone() - }; - match kernel::boolean(&body, &place(tool)?, kernel::BoolOp::Cut) { - Ok(Some(cut)) => { - body = cut; - last = None; - break; - } - Ok(None) => last = Some(DocError::Invalid("a sheet bore removes all sheet material".into())), - Err(e) => last = Some(e.into()), - } - } - if let Some(e) = last { - return Err(e); - } + body = kernel::boolean(&body, &place(inside)?, kernel::BoolOp::Cut)? + .ok_or_else(|| DocError::Invalid("a sheet bore removes all sheet material".into()))?; } Ok(body) } - /// Record a round bore drilled along the sheet (a hole into a rim): the world cylinder from - /// `base` along `axis`, one record per panel whose material it meets. Ok(false) when it - /// meets no material; an error when it meets a bend, or crosses a panel other than along - /// its plane (that machining has no exact place in the flat pattern). - pub(crate) fn add_bore(&mut self, base: Vec3, axis: Vec3, radius: f64, height: f64) -> Result { + /// Whether the sheet holds all the bores it may: [`Self::add_bore`] refuses any more. + pub(crate) fn bores_full(&self) -> bool { + self.bores.len() >= MAX_BORES + } + + /// The panels a straight drill (the world cylinder from `base` along `axis`) meets, each with + /// how square the drill is to it: |panel normal · axis|, 1 across the panel and 0 along it. + /// A drill that meets a bend is refused (a bend's material has no flat place for a hole). + pub(crate) fn drilled_panels(&self, base: Vec3, axis: Vec3, radius: f64, height: f64) -> Result, f64)>> { let axis = axis.normalized().ok_or_else(|| DocError::Invalid("bore axis".into()))?; if ![base.x, base.y, base.z, radius, height].iter().all(|v| v.is_finite()) || !(radius > 0.0) || height == 0.0 { return Err(DocError::Invalid("invalid sheet bore".into())); } - if self.bores.len() >= MAX_BORES { - return Err(flat_budget_error()); - } let mut work = FlatWork::new(); let drill = kernel::cylinder(base, axis, radius, height)?; let mut found = Vec::new(); @@ -1739,11 +1972,29 @@ impl SheetBody { )); }; let w = self.world(if self.flat { None } else { pi }); - if apply_vector(&w, Vec3::Z).dot(axis).abs() > 1e-6 { + found.push((pi, apply_vector(&w, Vec3::Z).dot(axis).abs())); + } + Ok(found) + } + + /// Record a round bore drilled along the sheet (a hole into a rim): the world cylinder from + /// `base` along `axis`, one record per panel whose material it meets. Ok(false) when it + /// meets no material; an error when it meets a bend, or crosses a panel other than along + /// its plane (that machining has no exact place in the flat pattern). + pub(crate) fn add_bore(&mut self, base: Vec3, axis: Vec3, radius: f64, height: f64) -> Result { + if self.bores_full() { + return Err(flat_budget_error()); + } + let panels = self.drilled_panels(base, axis, radius, height)?; + let axis = axis.normalized().ok_or_else(|| DocError::Invalid("bore axis".into()))?; + let mut found = Vec::new(); + for (pi, square) in panels { + if square > 1e-6 { return Err(DocError::Invalid( "this hole crosses a sheet panel at an angle; drill it square to the panel, or along it into a rim".into(), )); } + let w = self.world(if self.flat { None } else { pi }); let inv = mat_inverse(&w).ok_or_else(|| DocError::Invalid("invalid sheet panel frame".into()))?; let bore = SheetBore { panel: pi, base: apply_point(&inv, base), axis: apply_vector(&inv, axis), radius, height }; if !found.contains(&bore) { @@ -1925,6 +2176,60 @@ impl SheetBody { Ok(regions) } + /// The sheet's panels and bend zones. Where a free-form edge crosses a fold, the zone and the + /// panels either side are already joined along their seams, so the edge stays the curve it + /// was drawn as: merged by the planar booleans it would come back as fitted arcs. A seam + /// another feature changed is left to them. + fn flat_pieces(&self) -> Result> { + let mut owners: Vec> = Vec::new(); + let mut slots: Vec> = Vec::new(); + for (pi, r) in self.panels() { + owners.push(pi); + slots.push(Some(planar_region(&r)?)); + } + let panel_slot = |pi: Option| owners.iter().position(|o| *o == pi); + let panels = slots.len(); + for f in &self.flanges { + slots.push(Some(planar_region(&self.zone(f))?)); + } + // Which slot now holds each: joined pieces live in the one they joined. + let mut held_by: Vec = (0..slots.len()).collect(); + let free_form = |slots: &[Option], at: usize| slots.get(at).and_then(Option::as_ref).is_some_and(|r| !r.outer.is_line_arc()); + for (i, f) in self.flanges.iter().enumerate() { + // A fold's pieces share whole seams; an edge flange's bend needn't span its edge. + if f.shape.is_none() { + continue; + } + let zone = panels + i; + let sides = [panel_slot(f.parent), panel_slot(Some(i))]; + if !free_form(&slots, zone) && !sides.iter().flatten().any(|&p| free_form(&slots, held_by.get(p).copied().unwrap_or(p))) { + continue; + } + for side in sides.into_iter().flatten() { + let at = |held_by: &[usize], k: usize| held_by.get(k).copied().unwrap_or(k); + let (a, b) = (at(&held_by, zone), at(&held_by, side)); + if a == b { + continue; + } + let (Some(Some(ra)), Some(Some(rb))) = (slots.get(a), slots.get(b)) else { continue }; + let Some(joined) = join_along_seam(&ra.outer, &rb.outer) else { continue }; + let holes = ra.holes.iter().chain(&rb.holes).cloned().collect(); + if let Some(slot) = slots.get_mut(a) { + *slot = Some(Region2 { outer: joined, holes }); + } + if let Some(slot) = slots.get_mut(b) { + *slot = None; + } + for k in &mut held_by { + if *k == b { + *k = a; + } + } + } + } + Ok(slots.into_iter().flatten().collect()) + } + pub(crate) fn flat_material(&self) -> Result> { let mut work = FlatWork::new(); // Merge structural pieces before cutting: clipping each panel first introduces @@ -1938,16 +2243,12 @@ impl SheetBody { } let mut regions = Vec::new(); let mut panel_points = 0usize; - for (_, r) in self.panels() { - let r = planar_region(&r)?; + for r in self.flat_pieces()? { panel_points = panel_points.saturating_add(region_complexity(std::slice::from_ref(&r))?.1); if panel_points > MAX_FLAT_POINTS { return Err(flat_budget_error()); } regions.push(r); - } - for f in &self.flanges { - regions.push(planar_region(&self.zone(f))?); region_complexity(®ions)?; } let regions = material_union(regions, &mut work)?; @@ -2079,9 +2380,7 @@ impl SheetBody { let mut out = Vec::new(); for (i, f) in self.flanges.iter().enumerate() { let ba = self.allowance(f); - // The centre line runs between the middles of the bend's two ends (a torn end is askew). - let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f)); - let (u0, u1) = ((u0 + e0) / 2.0, (u1 + e1) / 2.0); + let (u0, u1) = self.centre_line(f); let a = f.p + f.n * (ba / 2.0) + f.d * u0; for (s0, s1) in clear_of(a, f.d, u1 - u0, &cuts) { out.push(BendInfo { @@ -2104,9 +2403,45 @@ impl SheetBody { self.flanges.iter().map(|f| self.zone(f)).collect() } + /// A perforation field's outline (#732) in flat coordinates: closed regions of a sketch in `plane` (world). An + /// unfolded sheet takes them as drawn on the flat; a folded one through each panel whose material the plane lies + /// in, clipped to that panel, so an outline on one face never reaches a flange in the flat. Refused when the + /// plane lies in no panel. + pub fn perforation_outline(&self, plane: &Plane, regions: &[Region2]) -> Result> { + let on = |pi: Option| { + let w = self.world(pi); + let n = apply_vector(&w, Vec3::Z); + let z = (plane.origin - apply_point(&w, Vec3::ZERO)).dot(n); + n.cross(plane.normal()).len() < 1e-6 && (-LINEAR_TOL..=self.t + LINEAR_TOL).contains(&z) + }; + if self.flat { + if !on(None) { + return Err(DocError::Invalid("the perforation's outline sketch must lie on the flat sheet".into())); + } + return regions.iter().map(|r| self.region_to_flat(None, plane, r)).collect(); + } + let mut work = FlatWork::new(); + let mut out = Vec::new(); + let mut found = false; + for (pi, panel) in self.parallel_panels(plane) { + if !on(pi) { + continue; + } + found = true; + let mapped = regions.iter().map(|r| self.region_to_flat(pi, plane, r)).collect::>>()?; + out.extend(material_boolean(std::slice::from_ref(&panel), &mapped, kernel::BoolOp::Intersect, &mut work)?); + } + if !found { + return Err(DocError::Invalid("the perforation's outline sketch must lie on a face of the sheet".into())); + } + Ok(out) + } + /// Hole centres of a perforation field (#732), flat coordinates: a staggered (60°, odd rows shifted half a pitch) /// or square grid from the flat bounding box's lower-left corner plus margin + radius; a hole is kept where it is - /// at least margin clear of the material's edges and cut-outs and of every bend zone. + /// at least margin clear of the material's edges and cut-outs and of every bend zone. A field with an outline + /// keeps its holes inside the outline and margin clear of its edges too, on a grid from the lower-left corner of + /// the outline's bounding box (within the flat's). pub fn perforation_holes(&self, p: &SheetPerforation) -> Result> { let regions = self.flat_regions()?; let zones = self.bend_zones(); @@ -2127,6 +2462,20 @@ impl SheetBody { if !(lo.x <= hi.x) || !(p.pitch > 0.0) { return Ok(Vec::new()); } + // The rows and columns span the flat, or the outline's part of it; the bucket grid below stays the flat's. + let mut field = Aabb2 { min: lo, max: hi }; + if let Some(outline) = &p.outline { + let n = segs.len(); + for r in outline { + for l in std::iter::once(&r.outer).chain(&r.holes) { + segs.extend(l.polyline(1e-3).edges().map(|(&a, &b)| (a, b))); + } + } + field = field.intersection(&segs.get(n..).unwrap_or(&[]).iter().map(|(a, _)| *a).collect::()); + if !(field.min.x <= field.max.x && field.min.y <= field.max.y) { + return Ok(Vec::new()); + } + } // Segments bucketed in a grid, so each hole only checks the edges near it. let cell = (2.0 * clear).max(p.pitch).max(1.0); let (nx, ny) = (((hi.x - lo.x) / cell) as usize + 1, ((hi.y - lo.y) / cell) as usize + 1); @@ -2153,20 +2502,22 @@ impl SheetBody { let dy = if p.square { p.pitch } else { p.pitch * 3f64.sqrt() / 2.0 }; let mut out = Vec::new(); let mut row = 0usize; + let Aabb2 { min: flo, max: fhi } = field; loop { - let y = lo.y + clear + row as f64 * dy; - if y > hi.y - clear + 1e-9 { + let y = flo.y + clear + row as f64 * dy; + if y > fhi.y - clear + 1e-9 { break; } let shift = if !p.square && row % 2 == 1 { p.pitch / 2.0 } else { 0.0 }; // Steps across the row from its first hole; a mirrored field counts from the right. let mut step = 0.0; - while lo.x + clear + shift + step <= hi.x - clear + 1e-9 { - let x = if p.from_right { hi.x - clear - shift - step } else { lo.x + clear + shift + step }; + while flo.x + clear + shift + step <= fhi.x - clear + 1e-9 { + let x = if p.from_right { fhi.x - clear - shift - step } else { flo.x + clear + shift + step }; let c = Vec2::new(x, y); let (i, j) = idx(x, y); let near = grid.get(j * nx + i).map(Vec::as_slice).unwrap_or(&[]); if regions.iter().any(|r| r.contains(c)) + && p.outline.as_ref().is_none_or(|o| o.iter().any(|r| r.contains(c))) && !zones.iter().any(|z| z.contains(c)) && near.iter().all(|&k| segs.get(k).is_none_or(|&s| dist(c, s) >= clear - 1e-9)) { @@ -2287,6 +2638,92 @@ impl SheetBody { best } + /// The cut-out whose edge across the base is the sheet's edge nearest the world point `p`, + /// nearer than any edge of a panel's outline (`edge_at`, which doesn't see cut-outs): the + /// edge of a notch. + fn base_cut_edge_at(&self, p: Vec3) -> Option { + let inv = mat_inverse(&self.world(None))?; + let q = apply_point(&inv, p); + let (q2, dz) = (Vec2::new(q.x, q.y), q.z.abs().min((q.z - self.t).abs())); + let outline = self.base.outer.ccw().polyline(1e-3); + let panel_edge = self.edge_at(p).map_or(f64::INFINITY, |e| e.4); + let mut best: Option<(usize, f64)> = None; + for (k, cut) in self.holes.iter().enumerate() { + let pts = cut.outer.polyline(1e-3); + let m = pts.len(); + for i in 0..m { + let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % m)) else { continue }; + let d = b - a; + let mid = (a + b) * 0.5; + // Only where it runs across the base's material is it an edge of the sheet. + if d.len2() < 1e-18 || !outline.contains(mid) || self.holes.iter().enumerate().any(|(j, h)| j != k && h.contains(mid)) { + continue; + } + let t = ((q2 - a).dot(d) / d.len2()).clamp(0.0, 1.0); + let dist = ((a + d * t) - q2).len().hypot(dz); + if dist < panel_edge - 1e-9 && best.is_none_or(|x| dist < x.1) { + best = Some((k, dist)); + } + } + } + best.map(|x| x.0) + } + + /// Run the base's outline round its cut-out `k`, a notch, so that the notch's edges are the + /// base's own. What the cut-out takes of the flanges stays a cut-out; the rest of it is in + /// the base's outline now, and a flange laid out in the flat where the notch was keeps its + /// material. A cut-out that leaves a hole in the base or splits it has no edge a flange can + /// stand on yet. + fn open_base_to(&mut self, k: usize) -> Result<()> { + let cut = planar_region(self.holes.get(k).ok_or_else(|| DocError::Invalid("cut-out".into()))?)?; + let mut work = FlatWork::new(); + let mut left = material_boolean(&[planar_region(&self.base)?], std::slice::from_ref(&cut), kernel::BoolOp::Cut, &mut work)?; + let open = match (left.pop(), left.is_empty()) { + (Some(open), true) if open.holes.len() == self.base.holes.len() => open, + _ => { + return Err(DocError::Invalid( + "not supported yet: a flange on the edge of a hole in the sheet, or of a cut-out that splits it".into(), + )); + } + }; + let mut pieces = Vec::with_capacity(self.flanges.len() * 2); + for f in &self.flanges { + pieces.push(planar_region(&self.zone(f))?); + if f.leg > 1e-9 { + pieces.push(planar_region(&self.panel(f))?); + } + } + let rest = if pieces.is_empty() { Vec::new() } else { material_boolean(&[cut], &pieces, kernel::BoolOp::Intersect, &mut work)? }; + self.base = open; + self.holes.splice(k..=k, rest); + Ok(()) + } + + /// Where the base's outline already runs along the bend line (through `o`, along `d`) beside a + /// picked edge that spans [ua, ub] along d: the end of the nearest such run before it and the + /// start of the nearest after it (none: unbounded). Trimmed back to that line, the picked edge + /// merges with those runs, as beside the steps of a stepped outline; the flange stays off them. + fn bend_line_runs(&self, o: Vec2, d: Vec2, ua: f64, ub: f64) -> (f64, f64) { + let n = Vec2::new(-d.y, d.x); + let pts = self.base.outer.ccw().polyline(1e-3); + let m = pts.len(); + let (mut lo, mut hi) = (f64::MIN, f64::MAX); + for i in 0..m { + let (Some(&p), Some(&q)) = (pts.get(i), pts.get((i + 1) % m)) else { continue }; + if (p - o).dot(n).abs() > 1e-6 || (q - o).dot(n).abs() > 1e-6 { + continue; + } + let (u0, u1) = (p.dot(d).min(q.dot(d)), p.dot(d).max(q.dot(d))); + if u1 <= ua + 1e-9 { + lo = lo.max(u1); + } + if u0 >= ub - 1e-9 { + hi = hi.min(u0); + } + } + (lo, hi) + } + /// What `cuts` (the sheet's cut-outs) leave of a panel's edge a→b: the stretch nearest `pick` /// (a world point), as distances from `a` along the edge; of two as near, the first. `None` /// where they have taken the edge whole. @@ -2379,10 +2816,8 @@ impl SheetBody { return Err(DocError::Invalid("not supported yet: a partial side-edge flange beside a cut-out".into())); } let clipped = if side || original.shape.is_some() || original.exact.is_some() { + // A panel with curves gives way to its 0.001 mm chords here. let region = self.panel(original); - if !region.outer.segs.iter().all(|s| matches!(s, Seg2::Line { .. })) { - return Err(DocError::Invalid("not supported yet: a flange setback on a curved flange panel".into())); - } let points = clip(®ion.outer.ccw().polyline(1e-3), a + inward * by, inward); if points.len() < 3 { return Err(DocError::Invalid("the flange's setback removes the whole panel".into())); @@ -2600,6 +3035,13 @@ impl SheetBody { } sizes.push((setback, leg)); } + // A pick on an edge of a notch (a cut-out that opens the base's outline) is on an edge of + // the base: its outline runs round the notch first (#5306). + for e in edges { + if let Some(k) = self.base_cut_edge_at(e.pick) { + self.open_base_to(k)?; + } + } // Find every edge before anything moves: of an edge that cut-outs have taken part of, the // stretch they leave nearest the pick, and at which of its ends a cut-out is. let cuts = self.cut_outs(); @@ -2632,17 +3074,23 @@ impl SheetBody { let (s0, s1) = self .edge_left(panel, a, b, e.pick, &cuts) .ok_or_else(|| DocError::Invalid(format!("{}a cut-out has taken that edge away; pick an edge the sheet still has", on(k))))?; + // Where the base already runs along the bend line beside this edge (a stepped outline): + // the flange stays off it, though trimming merges the two. + let run = match panel { + None => self.bend_line_runs(a - outward * setback, d, a.dot(d), b.dot(d)), + Some(_) => (f64::MIN, f64::MAX), + }; let cut = (s0 > 1e-9, s1 < a.dist(b) - 1e-9); let (a, b) = (if cut.0 { a + d * s0 } else { a }, if cut.1 { a + d * s1 } else { b }); - found.push((panel, a, b, d, top, setback, leg, e.angle, cut)); + found.push((panel, a, b, d, top, setback, leg, e.angle, cut, run)); } - for (panel, a, b, _, _, setback, _, _, cut) in &found { + for (panel, a, b, _, _, setback, _, _, cut, _) in &found { self.trim(*panel, *a, *b, *setback, *cut)?; } let mut made = Vec::new(); // Whether a cut-out has freed each new bend's ends (start, end) of the base beside them. let mut freed = Vec::new(); - for (panel, a, b, d, top, setback, leg, angle, cut) in found { + for (panel, a, b, d, top, setback, leg, angle, cut, run) in found { let outward = Vec2::new(d.y, -d.x); let line_o = a - outward * setback; // The trimmed edge: along d, on the moved line. @@ -2691,6 +3139,16 @@ impl SheetBody { .ok_or_else(|| DocError::Invalid("the flange's edge was trimmed away".into()))? } }; + // Not over the base's own edge where it already ran along the bend line (beyond a + // step of the outline): the flange stops where the picked edge did. + let (start, len) = { + let u = start.dot(d); + let (u0, u1) = (u.max(run.0), (u + len).min(run.1)); + if !(u1 - u0 > 1e-9) { + return Err(DocError::Invalid("the flange's edge was trimmed away".into())); + } + (start + d * (u0 - u), u1 - u0) + }; // Where a cut-out ends the edge, the flange ends with it. let (start, len) = if cut.0 || cut.1 { let u = (start - a).dot(d); @@ -2718,6 +3176,7 @@ impl SheetBody { leg: leg.max(0.0), shape: None, exact: None, + zone_shape: None, tag: String::new(), ext: (0.0, 0.0), slope: (0.0, 0.0), @@ -3616,6 +4075,7 @@ impl SheetBody { tear: (false, false), shape: None, exact: None, + zone_shape: None, tag: String::new(), }); Ok(self.flanges.len() - 1) @@ -3629,7 +4089,8 @@ impl SheetBody { /// flat). On the base the side holding `fixed` (default: the larger side) stays put; on a /// flange the side toward its own bend does. `flip` folds the other way. A `fixed` point that /// touches no material still picks the side it lies on, and sets `warning` (see - /// [`FOLD_FIXED_OFF_SHEET`]). + /// [`FOLD_FIXED_OFF_SHEET`]). The outline may cross the zone on straight slanted edges or on + /// any curve; a sharp corner in the zone is refused, by name. #[allow(clippy::too_many_arguments)] pub fn add_fold( &mut self, @@ -3684,11 +4145,12 @@ impl SheetBody { let pts = dedup(&r.outer.ccw().polyline(1e-3)); let (a2, b2) = (Vec2::new(fa.x, fa.y), Vec2::new(fb.x, fb.y)); if pts.contains((a2 + b2) * 0.5) || polys_cross(&pts, &[a2, b2, (a2 + b2) * 0.5]) { - found = Some((pi, inv, a2, b2, pts)); + found = Some((pi, inv, a2, b2, pts, r.outer)); break; } } - let (panel, inv, a2, b2, pts) = found.ok_or_else(|| DocError::Invalid("the fold line must lie on a flat face of the sheet".into()))?; + let (panel, inv, a2, b2, pts, outline) = + found.ok_or_else(|| DocError::Invalid("the fold line must lie on a flat face of the sheet".into()))?; let d = (b2 - a2).normalized().ok_or_else(|| DocError::Invalid("the fold line has no length".into()))?; let mut n = Vec2::new(-d.y, d.x); let l0 = a2.dot(n); @@ -3741,6 +4203,7 @@ impl SheetBody { tear: (false, false), shape: None, exact: None, + zone_shape: None, tag: String::new(), }; let ba = self.allowance(&probe); @@ -3771,26 +4234,46 @@ impl SheetBody { let angle = if flip { -angle } else { angle }; return self.fold_tabs(panel, &pts, (n, d), (s0, ba), span, (angle, radius), &strips); } - // The bend zone must be a rectangle across the panel (a slanted or curved edge would - // run across the bend as a helix, which the sheet's faces can't carry yet). + // The bend zone is a rectangle across the panel, or straight edges of the sheet slant + // across it, or curved ones do. Those ends fold to helices and curves, as torn ends and + // cut-outs across a bend do. let us: Vec = strip.iter().map(|q| q.dot(d)).collect(); let (u0, u1) = (us.iter().cloned().fold(f64::MAX, f64::min), us.iter().cloned().fold(f64::MIN, f64::max)); + let mut ends: FoldEnds = (u0, u1, (0.0, 0.0), (false, false)); + let mut zone_shape = None; + // An outline with curves is cut exactly, wherever the curves are, so they stay as drawn in + // the flat pattern; a cut that doesn't come out whole falls back on the chords. + let cut = if outline.segs.iter().all(|e| matches!(e, Seg2::Line { .. })) { None } else { curved_fold(&outline, n, d, s0, ba) }; if ((u1 - u0) * ba - signed_area(&strip).abs()).abs() > 1e-6 * (u1 - u0).max(1.0) * ba.max(1.0) { - // A corner of the outline inside the zone (e.g. a fold right at a tab's root): name - // it and how far the line has to move to clear it. - let corners: Vec<(Vec2, f64)> = pts.iter().map(|q| (*q, q.dot(n) - s0)).filter(|(_, s)| *s > 1e-6 && *s < ba - 1e-6).collect(); - if let Some(&(c, _)) = corners.first() { - let on = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(*s)); - let back = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(ba - *s)); - let w = apply_point(&self.world(panel), Vec3::new(c.x, c.y, self.t)); - return Err(DocError::Invalid(format!( - "the bend zone ({ba:.3} mm wide) reaches a corner of the sheet's outline at ({:.3}, {:.3}, {:.3}): \ - move the fold line at least {on:.3} mm toward the side that folds or {back:.3} mm toward the side that stays", - w.x, w.y, w.z - ))); + if let Some(slanted) = slanted_zone(&strip, n, d, s0, ba) { + ends = slanted; + } else { + // A corner of the outline inside the zone (e.g. a fold right at a tab's root): name + // it and how far the line has to move to clear it. + let corners: Vec<(Vec2, f64)> = + outline_corners(&outline).into_iter().map(|q| (q, q.dot(n) - s0)).filter(|(_, s)| *s > 1e-6 && *s < ba - 1e-6).collect(); + if let Some(&(c, _)) = corners.first() { + let on = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(*s)); + let back = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(ba - *s)); + let w = apply_point(&self.world(panel), Vec3::new(c.x, c.y, self.t)); + return Err(DocError::Invalid(format!( + "the bend zone ({ba:.3} mm wide) reaches a corner of the sheet's outline at ({:.3}, {:.3}, {:.3}): \ + move the fold line at least {on:.3} mm toward the side that folds or {back:.3} mm toward the side that stays", + w.x, w.y, w.z + ))); + } + let Some(curved) = &cut else { + return Err(DocError::Invalid("not supported yet: folds whose bend zone crosses a slanted or curved edge of the sheet".into())); + }; + ends = curved.ends; + zone_shape = Some(curved.zone.clone()); } - return Err(DocError::Invalid("not supported yet: folds whose bend zone crosses a slanted or curved edge of the sheet".into())); } + let (u0, u1, ext, tear) = ends; + let (fixed_exact, moving_exact) = match cut { + Some(cut) => (Some(cut.fixed), Some(cut.moving)), + None => (None, None), + }; let up = !flip; let leg = moving.iter().map(|q| q.dot(n) - s0 - ba).fold(0.0, f64::max); let p0 = n * s0 + d * u0; @@ -3801,11 +4284,14 @@ impl SheetBody { v.into_iter().map(snap).collect::>() }; match panel { - None => self.base = Region2 { outer: Loop2::polygon(&fixed_part).ccw(), holes: self.base.holes.clone() }, + None => { + self.base = + Region2 { outer: fixed_exact.clone().unwrap_or_else(|| Loop2::polygon(&fixed_part)).ccw(), holes: self.base.holes.clone() } + } Some(j) => { if let Some(f) = self.flanges.get_mut(j) { f.shape = Some(ccw(fixed_part.clone())); - f.exact = None; + f.exact = fixed_exact; } } } @@ -3818,11 +4304,12 @@ impl SheetBody { angle: if up { angle } else { -angle }, radius, leg, - ext: (0.0, 0.0), + ext, slope: (0.0, 0.0), - tear: (false, false), + tear, shape: Some(ccw(moving)), - exact: None, + exact: moving_exact, + zone_shape, tag: String::new(), }); let i = self.flanges.len() - 1; @@ -3967,6 +4454,7 @@ impl SheetBody { tear: (false, false), shape: Some(ccw(moving)), exact: None, + zone_shape: None, tag: String::new(), }); } @@ -4009,8 +4497,12 @@ impl SheetBody { } } - /// The persistent name of the sheet edge nearest a world point. + /// The persistent name of the sheet edge nearest a world point. An edge a notch made (see + /// `base_cut_edge_at`) has none: no line of the base sketch runs along it. pub fn edge_name(&self, pick: Vec3) -> Option { + if self.base_cut_edge_at(pick).is_some() { + return None; + } let (panel, a, b, top, _) = self.edge_at(pick)?; self.edge_name_of(panel, a, b, top) } @@ -4698,6 +5190,9 @@ impl SheetBody { if let Some(exact) = &mut f.exact { *exact = flip_x_loop(exact); } + if let Some(zone) = &mut f.zone_shape { + *zone = flip_x_loop(zone); + } } for r in self.holes.iter_mut().chain(self.labels.iter_mut()).chain(self.pockets.iter_mut().map(|p| &mut p.region)) { *r = flip_x_region(r); @@ -4708,6 +5203,9 @@ impl SheetBody { } for p in &mut self.perforations { p.from_right = !p.from_right; + for r in p.outline.iter_mut().flatten() { + *r = flip_x_region(r); + } } for (_, a, b) in &mut self.base_curves { (*a, *b) = (flip_x(*b), flip_x(*a)); @@ -4839,6 +5337,7 @@ pub fn contour_flange(body: &str, rule: &str, rv: &RuleValues, plane: &Plane, pt tear: (false, false), shape: None, exact: None, + zone_shape: None, tag: String::new(), }; let ba = sheet.allowance(&f); @@ -5361,9 +5860,14 @@ mod tests { let expected = (6000.0 - std::f64::consts::PI * 120.0) * 2.5 - std::f64::consts::PI * 60.0; assert!((vol(&s.solid().unwrap()) - expected).abs() < 0.5, "{}", vol(&s.solid().unwrap())); assert!((vol(&s.flat_solid().unwrap()) - expected).abs() < 0.5, "{}", vol(&s.flat_solid().unwrap())); - // The machining record keeps the pocket's exact outline. + // The machining record keeps the pocket's exact outline: its four conics in their order, + // the loop started at any of them. let machined = s.machining().unwrap(); - assert!(machined.len() == 1 && machined[0].region.outer == pocket.outer, "{} records", machined.len()); + let same_loop = |l: &Loop2| { + let n = pocket.outer.segs.len(); + l.segs.len() == n && (0..n).any(|k| (0..n).all(|i| l.segs[(i + k) % n] == pocket.outer.segs[i])) + }; + assert!(machined.len() == 1 && same_loop(&machined[0].region.outer), "{machined:?}"); } #[test] @@ -5558,6 +6062,145 @@ mod tests { } } + /// Any closed curve the sheet's outlines can hold: a circle, conics, cubics, and a mix. + fn curved_outlines() -> Vec<(&'static str, Loop2)> { + let w = std::f64::consts::FRAC_1_SQRT_2; + let v = |x: f64, y: f64| Vec2::new(x, y); + let conic = |a: Vec2, apex: Vec2, b: Vec2| Seg2::Conic { a, apex, b, w }; + let ellipse = vec![ + conic(v(80.0, 0.0), v(80.0, 40.0), v(0.0, 40.0)), + conic(v(0.0, 40.0), v(-80.0, 40.0), v(-80.0, 0.0)), + conic(v(-80.0, 0.0), v(-80.0, -40.0), v(0.0, -40.0)), + conic(v(0.0, -40.0), v(80.0, -40.0), v(80.0, 0.0)), + ]; + let cubic = |p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2| Seg2::Cubic { p0, p1, p2, p3 }; + // An uneven blob: its sides aren't symmetric about the fold or each other. + let spline = vec![ + cubic(v(70.0, -5.0), v(75.0, 30.0), v(30.0, 55.0), v(0.0, 40.0)), + cubic(v(0.0, 40.0), v(-30.0, 25.0), v(-90.0, 45.0), v(-85.0, 0.0)), + cubic(v(-85.0, 0.0), v(-80.0, -45.0), v(-20.0, -60.0), v(0.0, -35.0)), + cubic(v(0.0, -35.0), v(20.0, -10.0), v(65.0, -40.0), v(70.0, -5.0)), + ]; + // A D: a straight side the fold runs across, and an arc it also crosses. + let d_shape = vec![ + Seg2::Line { a: v(-50.0, -50.0), b: v(0.0, -50.0) }, + Seg2::Arc { center: v(0.0, 0.0), radius: 50.0, start: -std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI }, + Seg2::Line { a: v(0.0, 50.0), b: v(-50.0, 50.0) }, + Seg2::Line { a: v(-50.0, 50.0), b: v(-50.0, -50.0) }, + ]; + vec![ + ("circle", Loop2::circle(v(0.0, 0.0), 50.0)), + ("ellipse", Loop2 { segs: ellipse }), + ("spline", Loop2 { segs: spline }), + ("D", Loop2 { segs: d_shape }), + ] + } + + #[test] + fn a_curved_outline_is_cut_exactly_across_a_fold_whatever_the_curve() { + let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0)); + for (name, lp) in curved_outlines() { + for (s0, ba) in [(-2.8, 5.6), (-30.0, 12.0), (10.0, 1.5)] { + let cut = curved_fold(&lp, n, d, s0, ba).unwrap_or_else(|| panic!("{name} at {s0}")); + // The pieces are the outline: nothing lost, nothing doubled, and all closed. + let area = |l: &Loop2| l.signed_area(); + let sum = area(&cut.fixed) + area(&cut.zone) + area(&cut.moving); + assert!((sum - lp.signed_area().abs()).abs() < 1e-6, "{name} at {s0}: {sum} vs {}", lp.signed_area()); + for piece in [&cut.fixed, &cut.zone, &cut.moving] { + assert!(piece.is_closed(1e-9) && piece.is_ccw(), "{name} at {s0}: {piece:?}"); + } + // Each lies wholly in its band, on the outline's own curves: sampled densely. + let band = |l: &Loop2, lo: f64, hi: f64| l.polyline(1e-3).iter().all(|q| q.dot(n) >= lo - 1e-6 && q.dot(n) <= hi + 1e-6); + assert!(band(&cut.fixed, f64::MIN, s0) && band(&cut.zone, s0, s0 + ba) && band(&cut.moving, s0 + ba, f64::MAX), "{name} at {s0}"); + // A curve is cut, not replaced by chords: the same kind of segment comes back. + let curves = |l: &Loop2| l.segs.iter().filter(|e| !matches!(e, Seg2::Line { .. })).count(); + assert!(curves(&cut.fixed) + curves(&cut.zone) + curves(&cut.moving) >= curves(&lp), "{name} at {s0}"); + assert!(cut.ends.3 == (true, true), "{name}: both ends are torn"); + } + } + } + + /// What keeps a flat pattern true: unrolling a bend keeps lengths on its neutral surface, so + /// a curved edge is as long folded as in the flat there, and only there. + #[test] + fn a_curved_edge_keeps_its_length_on_the_neutral_surface() { + for (name, lp) in curved_outlines() { + let mut s = plate(10.0, 10.0); + s.base = Region2 { outer: lp, holes: Vec::new() }; + let t = s.t; + let mut warning = None; + let (a, b) = (Vec3::new(5.0, -200.0, t), Vec3::new(5.0, 200.0, t)); + let i = + s.add_fold(a, b, std::f64::consts::FRAC_PI_2, 3.0, "centerline", false, None, &mut warning).unwrap_or_else(|e| panic!("{name}: {e}")); + let zone = s.flanges[i].zone_shape.clone().unwrap_or_else(|| panic!("{name}: no exact zone")); + let neutral = t - s.k * t; + let mut edges = 0; + for e in zone.segs.iter().filter(|e| !matches!(zone_edge_kind(&s.flanges[i], e), ZoneEdge::Along)) { + edges += 1; + const N: usize = 400; + let at = |k: usize| e.point_at(k as f64 / N as f64); + let flat: f64 = (0..N).map(|k| at(k).dist(at(k + 1))).sum(); + let folded = |z: f64| -> f64 { (0..N).map(|k| s.map3(Piece::Zone(i), at(k), z).dist(s.map3(Piece::Zone(i), at(k + 1), z))).sum() }; + assert!((folded(neutral) - flat).abs() < 1e-3, "{name}: {} folded vs {flat} flat", folded(neutral)); + // The test can tell: on the inside of the bend the edge is shorter. + assert!(flat - folded(t) > 0.05, "{name}: {} on the inside vs {flat} flat", folded(t)); + } + assert!(edges >= 2, "{name}: {zone:?}"); + } + } + + #[test] + fn a_fold_across_an_outline_that_doesnt_pass_through_once_is_refused() { + let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0)); + let v = |x: f64, y: f64| Vec2::new(x, y); + let circle = Loop2::circle(v(0.0, 0.0), 50.0); + // The zone reaches the tip: nothing lies past it, or short of it. + assert!(curved_fold(&circle, n, d, 49.0, 5.0).is_none()); + assert!(curved_fold(&circle, n, d, -54.0, 5.0).is_none()); + // Wholly off the sheet. + assert!(curved_fold(&circle, n, d, 60.0, 5.0).is_none()); + // Two tabs on the line: the outline crosses the zone four times. + let tabs = Loop2::polygon(&[ + v(-10.0, -30.0), + v(10.0, -30.0), + v(10.0, -5.0), + v(-10.0, -5.0), + v(-10.0, 5.0), + v(10.0, 5.0), + v(10.0, 30.0), + v(-10.0, 30.0), + v(-20.0, 30.0), + v(-20.0, -30.0), + ]); + assert!(curved_fold(&tabs, n, d, -2.0, 4.0).is_none()); + // An edge square across the bend, along the zone's line. + let along = Loop2::polygon(&[v(-10.0, -10.0), v(2.0, -10.0), v(2.0, 10.0), v(-10.0, 10.0)]); + assert!(curved_fold(&along, n, d, -2.0, 4.0).is_none()); + // Numbers that aren't. + assert!(curved_fold(&circle, n, d, f64::NAN, 5.0).is_none()); + assert!(curved_fold(&Loop2 { segs: Vec::new() }, n, d, 0.0, 5.0).is_none()); + } + + #[test] + fn a_fold_zone_with_straight_ends_is_told_from_a_curved_or_cornered_one() { + let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)); + let zone = |pts: &[(f64, f64)]| slanted_zone(&pts.iter().map(|&(x, y)| Vec2::new(x, y)).collect::>(), n, d, 0.0, 4.0); + // Narrowing, widening, leaning one way, and square at one end. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 1.0), (4.0, 9.0), (0.0, 10.0)]), Some((0.0, 10.0, (-1.0, -1.0), (true, true)))); + assert_eq!(zone(&[(0.0, 1.0), (4.0, 0.0), (4.0, 10.0), (0.0, 9.0)]), Some((1.0, 9.0, (1.0, 1.0), (true, true)))); + assert_eq!(zone(&[(0.0, 0.0), (4.0, 2.0), (4.0, 12.0), (0.0, 10.0)]), Some((0.0, 10.0, (-2.0, 2.0), (true, true)))); + assert_eq!(zone(&[(0.0, 0.0), (4.0, 0.0), (4.0, 9.0), (0.0, 10.0)]), Some((0.0, 10.0, (0.0, -1.0), (false, true)))); + // An S across the zone encloses what the straight end would: its corners give it away. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 1.0), (4.0, 9.0), (2.0, 10.0), (2.0, 9.0), (0.0, 10.0)]), None); + // A curved end, as a polyline. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 0.0), (4.0, 9.0), (3.0, 9.8), (1.0, 9.8), (0.0, 9.0)]), None); + // Nothing to bend across: the zone comes to a point on either line, or isn't there. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 5.0), (0.0, 10.0)]), None); + assert_eq!(zone(&[(0.0, 5.0), (4.0, 0.0), (4.0, 10.0)]), None); + assert_eq!(zone(&[]), None); + assert_eq!(zone(&[(f64::NAN, 0.0), (4.0, 0.0), (4.0, 10.0), (0.0, 10.0)]), None); + } + #[test] fn a_slanted_flat_edge_folds_to_its_exact_helix() { // A 72° flange, inside: the bend's axis runs along x through y = setback, z = T + R, @@ -6942,10 +7585,12 @@ mod tests { assert!((length - outline).abs() < 1e-9, "{position}: {length} vs {outline}"); assert!((s.base.area() - (whole - below(line))).abs() < 1e-9, "{position}: {} vs {}", s.base.area(), whole - below(line)); // The flat pattern: the base and f.len × (BA + 37) of flange, its outline the base's - // with the flange's two sides (bend and panel, a line each) in place of nothing. + // with the flange's two sides and its end in place of the trimmed line. Each side is + // one line through the bend and the panel: the union of the two has no vertex where + // their sides meet in line. let regions = s.flat_regions().unwrap(); let (arcs, edges, length, shortest) = arcs_and_edges(®ions[0].outer); - assert!(regions[0].outer.is_line_arc() && (arcs, edges) == (4, 12) && shortest > 2.0, "{position}: {:?}", regions[0].outer); + assert!(regions[0].outer.is_line_arc() && (arcs, edges) == (4, 10) && shortest > 2.0, "{position}: {:?}", regions[0].outer); assert!((length - (outline + 2.0 * (ba + panel))).abs() < 1e-9, "{position}: {length}"); let flat = whole - below(line) + f.len * (ba + panel); assert!((regions[0].area() - flat).abs() < 1e-9, "{position}: {} vs {flat}", regions[0].area()); @@ -7104,13 +7749,12 @@ mod tests { } #[test] - fn a_base_trimmed_through_a_free_form_curve_follows_it_with_arcs() { + fn a_base_trimmed_through_a_free_form_curve_keeps_it_exact() { // A 200 x 60 plate under a parabola 40 high: y = 60 + 160·(x/200)·(1 − x/200), a conic // of weight 1. A flange 40 high inside on the right edge trims the base to x = 197, // through the curve's end: 183.564 goes (∫ y from 197 to 200), and the bend runs up the - // line x = 197 to the curve, at y = 62.364. The planar booleans follow a curve they - // cut with tangent arcs within 0.001 mm: over the parabola's 220 mm that is at most - // 0.22 mm² of the base, and 0.001/cos 38° = 0.0013 of the bend where it meets the curve. + // line x = 197 to the curve, at y = 62.364. The planar booleans cut the curve exactly: + // the base keeps what is left of it as one conic, so the strip and the bend are exact. // It used to become about 200 chords. let (ba, quarter) = (std::f64::consts::PI, std::f64::consts::FRAC_PI_2); let crowned = || { @@ -7133,11 +7777,12 @@ mod tests { let mut s = crowned(); let i = s.add_flange(pick, 40.0, quarter, 1.0, "inside", false).unwrap(); let outer = &s.base.outer; - let arcs = outer.segs.iter().filter(|e| matches!(e, Seg2::Arc { .. })).count(); - assert!(outer.is_line_arc() && arcs > 1 && outer.segs.len() == arcs + 3 && arcs < 64, "{what}: {arcs} arcs of {}", outer.segs.len()); - assert!((s.base.area() - (whole - strip)).abs() < 0.22, "{what}: {} vs {}", s.base.area(), whole - strip); + let conics = outer.segs.iter().filter(|e| matches!(e, Seg2::Conic { .. })).count(); + let lines = outer.segs.iter().filter(|e| matches!(e, Seg2::Line { .. })).count(); + assert!((conics, lines) == (1, 3), "{what}: {:?}", outer.segs); + assert!((s.base.area() - (whole - strip)).abs() < 1e-6, "{what}: {} vs {}", s.base.area(), whole - strip); let f = s.flanges[i].clone(); - assert!(f.p.dist(start) < 1e-9 && (f.len - len).abs() < 2e-3, "{what}: {f:?}"); + assert!(f.p.dist(start) < 1e-9 && (f.len - len).abs() < 1e-9, "{what}: {f:?}"); assert!((flat_area(&s) - (s.base.area() + f.len * (ba + 37.0))).abs() < 1e-6, "{what}: {}", flat_area(&s)); holds_the_flat_material(&s, what); let mut c = chorded(&crowned()); diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rs index ef9fd60ec..e5eaa83f5 100644 --- a/crates/doc/src/sheet_convert.rs +++ b/crates/doc/src/sheet_convert.rs @@ -47,10 +47,12 @@ //! edges that end at a bend or a cut edge, loops of bends, two faces that meet along more than //! one edge, a wall on part of an edge of a face other than the fixed one. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Ring, Seg2, UnitVec3, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Mesh, Ring, UnitVec3}; use solidcraft_kernel::{Body, FaceSurface, face_surface}; use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, polys_cross, signed_area, snap}; @@ -429,7 +431,8 @@ fn other_skin(b: &Body, mesh: &Mesh, c: &Chamfer, tol: f64) -> Option { /// Face `g`'s outline with each picked chamfer along it taken out: the edge along the chamfer /// moves to where `g`'s plane meets the plane of the face across the chamfer (its corners -/// sliding along the edges before and after it), and runs along that face. +/// sliding along the edges before and after it, or stepping down to it where the face goes on +/// past the chamfer's end), and runs along that face. fn without_chamfers(b: &Body, mut face: Face, g: usize, chamfers: &[Chamfer], tol: f64) -> Result { for c in chamfers { let other = if c.a == g { @@ -447,29 +450,57 @@ fn without_chamfers(b: &Body, mut face: Face, g: usize, chamfers: &[Chamfer], to let &[k] = along.as_slice() else { return err("not supported yet: a chamfer picked as a bend that runs along a face more than once"); }; - // Its corners slide along the edges before and after it: those must be straight. - if [k + m - 1, k + 1].iter().any(|i| face.round.get(i % m).is_some_and(Option::is_some)) { - return err("not supported yet: a round edge of a face that ends at a chamfer picked as a bend"); - } - // Each end of the edge slides along the edge on its other side, out to the other plane. - let slide = |corner: usize, before: usize| -> Option { + let (Some(&p0), Some(&q0)) = (face.pts.get(k), face.pts.get((k + 1) % m)) else { return err("a face of the sheet has no outline") }; + let Some(e) = (q0 - p0).normalized() else { return err("a face of the sheet has an edge without length") }; + // Each end of the edge slides along the straight edge on its other side, out to the + // other plane. + let slide = |corner: usize, before: usize, edge: usize| -> Option { + if face.round.get(edge % m).is_some_and(Option::is_some) { + return None; + } let (p, q) = (*face.pts.get(corner % m)?, *face.pts.get(before % m)?); let d = (p - q).normalized()?; let s = (o - p).dot(n) / d.dot(n); - (s.is_finite() && s >= -tol).then_some(p + d * s) + (d.cross(e).len() > 1e-6 && s.is_finite() && s >= -tol).then_some(p + d * s) }; - let (Some(p), Some(q)) = (slide(k, k + m - 1), slide(k + 1, k + 2)) else { - return err("a face beside a chamfer picked as a bend does not reach the face across it"); + // Where that edge is round or runs on along the chamfer's line (the face goes on past + // the chamfer's end), the end keeps its corner and steps down square to the edge onto + // the other plane: a step the bend's setback takes up again. + let w = face.n.cross(e); + let drop = |p: Vec3| -> Result { + let s = (o - p).dot(n) / w.dot(n); + if s.is_finite() { Ok(p + w * s) } else { err("a face beside a chamfer picked as a bend does not reach the face across it") } }; - if let Some(x) = face.pts.get_mut(k) { - *x = p; - } - if let Some(x) = face.pts.get_mut((k + 1) % m) { - *x = q; - } - if let Some(x) = face.across.get_mut(k) { - *x = Some(other); + let (next_across, next_round) = (face.across.get((k + 1) % m).copied().flatten(), face.round.get((k + 1) % m).copied().flatten()); + let start: Vec<(Vec3, Option)> = match slide(k, k + m - 1, k + m - 1) { + Some(p) => vec![(p, Some(other))], + None => vec![(p0, None), (drop(p0)?, Some(other))], + }; + let end: Vec<(Vec3, Option, Option<(Vec3, Vec3)>)> = match slide(k + 1, k + 2, k + 1) { + Some(q) => vec![(q, next_across, next_round)], + None => vec![(drop(q0)?, None, None), (q0, next_across, next_round)], + }; + let (mut pts, mut across, mut round) = (Vec::with_capacity(m + 2), Vec::with_capacity(m + 2), Vec::with_capacity(m + 2)); + for i in 0..m { + if i == k { + for (p, a) in &start { + pts.push(*p); + across.push(*a); + round.push(None); + } + } else if i == (k + 1) % m { + for (p, a, r) in &end { + pts.push(*p); + across.push(*a); + round.push(*r); + } + } else { + pts.push(face.pts.get(i).copied().unwrap_or_default()); + across.push(face.across.get(i).copied().flatten()); + round.push(face.round.get(i).copied().flatten()); + } } + (face.pts, face.across, face.round) = (pts, across, round); } Ok(face) } @@ -489,8 +520,10 @@ fn rip_cut(x: &Face, y: &Face, e: Vec3, t: f64, gap: f64) -> Result { /// A counter-clockwise outline with each edge moved in by its own amount. Moved edges meet /// where their lines cross; two edges in one line that move by different amounts are joined by -/// a square step. Returns the corners and, per edge, the edge it was (none for a step). -fn inset(pts: &[Vec2], by: &[f64]) -> Result<(Vec, Vec>)> { +/// a square step. An edge left shorter than `tol` (a step down to a bend's line that the bend's +/// setback takes up) is dropped, with the corner it shares with the edge that moved further. +/// Returns the corners and, per edge, the edge it was (none for a step). +fn inset(pts: &[Vec2], by: &[f64], tol: f64) -> Result<(Vec, Vec>)> { let n = pts.len(); if n < 3 { return err("a face of the sheet has no outline"); @@ -518,6 +551,15 @@ fn inset(pts: &[Vec2], by: &[f64]) -> Result<(Vec, Vec>)> { } from.push(Some(i)); } + let moved_by = |from: &[Option], j: usize| from.get(j).copied().flatten().and_then(|i| by.get(i)).map_or(0.0, |b| b.abs()); + while out.len() > 3 { + let m = out.len(); + let short = (0..m).find(|j| matches!((out.get(*j), out.get((j + 1) % m)), (Some(a), Some(b)) if a.dist(*b) <= tol)); + let Some(j) = short else { break }; + let corner = if moved_by(&from, (j + m - 1) % m) > moved_by(&from, (j + 1) % m) { j } else { (j + 1) % m }; + out.remove(corner); + from.remove(j); + } // Every edge still runs the way it did, and the outline is still one simple loop. let m = out.len(); let kept = (0..m).all(|j| match (from.get(j).copied().flatten().and_then(moved), out.get(j), out.get((j + 1) % m)) { @@ -597,10 +639,11 @@ fn end_at_wall(base: &mut Face, wall: &mut Face, ids: (usize, usize), by: f64, b if let Some(x) = wall.pts.get_mut((k + 1) % m) { *x = q1; } - let kept = |j: usize, out: &[usize]| !out.contains(&((j + m - k) % m)); - wall.pts = wall.pts.iter().enumerate().filter(|(j, _)| kept(*j, &corners_out)).map(|(_, x)| *x).collect(); - wall.across = wall.across.iter().enumerate().filter(|(j, _)| kept(*j, &edges_out)).map(|(_, x)| *x).collect(); - wall.round = wall.round.iter().enumerate().filter(|(j, _)| kept(*j, &edges_out)).map(|(_, x)| *x).collect(); + // Counted from the bend's edge, so each kept corner is still followed by its own edge + // wherever the face's loop starts. + wall.pts = kept_from(&wall.pts, k, &corners_out); + wall.across = kept_from(&wall.across, k, &edges_out); + wall.round = kept_from(&wall.round, k, &edges_out); // The fixed face's edge: the bend from `p1` to `q1` (it runs the other way along it), no bend // beside it. let (Some(&a), Some(&b)) = (base.pts.get(i), base.pts.get((i + 1) % n)) else { return }; @@ -620,6 +663,15 @@ fn end_at_wall(base: &mut Face, wall: &mut Face, ids: (usize, usize), by: f64, b base.round.splice(i..=i, std::iter::repeat_n(None, count)); } +/// The items of a loop's per-corner or per-edge list `of`, counted from item `k` on, less those +/// at the places `out` (counted from `k`). Corners and edges taken out at the same places counted +/// from one start stay paired (edge `j` from corner `j`); taken out at their places in the list +/// they would not where the places run across the list's start. +fn kept_from(of: &[T], k: usize, out: &[usize]) -> Vec { + let m = of.len(); + (0..m).filter(|j| !out.contains(j)).filter_map(|j| of.get((k + j) % m).copied()).collect() +} + /// Give flange `i` its panel: `outline` in flat coordinates, counter-clockwise, its edge at the /// bend first trimmed to the end of the bend zone. fn set_panel(sh: &mut SheetBody, i: usize, outline: &[Vec2]) { @@ -691,15 +743,16 @@ pub fn bend_edge_names(st: &crate::ModelState, body: &str, pts: &[Vec3]) -> Vec< pts.iter().zip(crate::naming::edge_names_at(b, pts)).map(|(p, name)| if on(p) { name } else { String::new() }).collect() } -/// Convert body `mb` to a sheet under the rule `rule` with values `rv`: `face` is a point on the -/// fixed face and `bends` are points on the sharp edges that become bends, in the middle of -/// chamfers or on bend cylinders that do (the body's coordinates, mm). See the module docs. -/// `body_to_world` places diagnostic points in world coordinates. Geometry and picks stay local. -/// Returns the sheet and a note for every corner or end of a bend not finished as the rule says. +/// Convert body `mb` to a sheet under the rule `rule`, whose values for a sheet of a thickness +/// (`None`: the rule's own) are `values`: `face` is a point on the fixed face and `bends` are +/// points on the sharp edges that become bends, in the middle of chamfers or on bend cylinders +/// that do (the body's coordinates, mm). See the module docs. `body_to_world` places diagnostic +/// points in world coordinates. Geometry and picks stay local. Returns the sheet and a note for +/// every corner or end of a bend not finished as the rule says. pub fn convert_body( mb: &ModelBody, rule: &str, - rv: &RuleValues, + values: &dyn Fn(Option) -> Result, face: Vec3, bends: &[Vec3], body_to_world: &crate::Mat, @@ -708,9 +761,7 @@ pub fn convert_body( if bends.is_empty() || bends.len() > MAX_BENDS { return err(format!("pick 1…{MAX_BENDS} bend edges")); } - if !(rv.gap >= 0.0 && rv.bend_radius >= 0.0) { - return err("the rule's gap and bend radius must not be negative"); - } + let rv = values(None)?; let (b, mesh) = (&mb.body, mb.mesh()); let size = b.size(); if !(size.is_finite() && size > 0.0) { @@ -763,6 +814,12 @@ pub fn convert_body( .flatten() .collect(); let t = shell.map_or(rv.thickness, |d| (d * 1e9).round() / 1e9); + // A shell's sheet is as thick as its walls: the rule's values that follow its thickness (a + // bend radius of `Thickness`, the gap, the reliefs) follow the walls', not the rule's own. + let rv = if shell.is_some() { values(Some(t))? } else { rv }; + if !(rv.gap >= 0.0 && rv.bend_radius >= 0.0) { + return err("the rule's gap and bend radius must not be negative"); + } let r = rv.bend_radius; let joined = |x: usize, y: usize| { mesh.edge_faces.iter().any(|faces| faces.contains(&(x as u32)) && faces.contains(&(y as u32))) @@ -841,7 +898,7 @@ pub fn convert_body( } panels.insert(g, wall); } - let mut sh = base_flange(&mb.name, rule, &RuleValues { thickness: t, ..*rv }, frame, Region2::default()); + let mut sh = base_flange(&mb.name, rule, &RuleValues { thickness: t, ..rv }, frame, Region2::default()); // How far behind a face of the sheet the body's face `g` starts and ends: a hole's wall // reaches through the sheet, a pocket's ends on its floor, an island's starts at the face. let mut points: BTreeMap> = BTreeMap::new(); @@ -899,7 +956,7 @@ pub fn convert_body( } let first = panel.face.pts.first().copied().unwrap_or_default(); let face_at = |e: DocError| DocError::Invalid(format!("{e} (the face at {})", at(first))); - let (trimmed, from) = inset(&pts, &by).map_err(face_at)?; + let (trimmed, from) = inset(&pts, &by, tol).map_err(face_at)?; let exact = drawn(&trimmed, &from, &pts, &round).map_err(face_at)?; match fl { None => sh.base.outer = exact.unwrap_or_else(|| Loop2::polygon(&trimmed.iter().map(|q| snap(*q)).collect::>())), @@ -1011,6 +1068,7 @@ pub fn convert_body( slope: (0.0, 0.0), shape: None, exact: None, + zone_shape: None, tag: String::new(), tear: (false, false), }); @@ -1046,21 +1104,21 @@ mod tests { fn edges_move_in_by_their_own_amounts_and_step_along_one_line() { let v = Vec2::new; let square = [v(0.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)]; - let (p, from) = inset(&square, &[1.0, 0.0, 2.0, 0.0]).unwrap(); + let (p, from) = inset(&square, &[1.0, 0.0, 2.0, 0.0], 1e-6).unwrap(); assert_eq!(p, vec![v(0.0, 1.0), v(10.0, 1.0), v(10.0, 8.0), v(0.0, 8.0)]); assert_eq!(from, vec![Some(0), Some(1), Some(2), Some(3)]); // Two edges in one line that move by different amounts: a square step between them, // so 5 x 2 goes from the 10 x 10. let split = [v(0.0, 0.0), v(5.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)]; - let (p, from) = inset(&split, &[0.0, 2.0, 0.0, 0.0, 0.0]).unwrap(); + let (p, from) = inset(&split, &[0.0, 2.0, 0.0, 0.0, 0.0], 1e-6).unwrap(); assert_eq!(p, vec![v(0.0, 0.0), v(5.0, 0.0), v(5.0, 2.0), v(10.0, 2.0), v(10.0, 10.0), v(0.0, 10.0)]); assert_eq!(from, vec![Some(0), None, Some(1), Some(2), Some(3), Some(4)]); // A slanted end keeps its line: the corner slides along it (2 up a 45° edge is 2 along). let slanted = [v(0.0, 0.0), v(10.0, 0.0), v(15.0, 5.0), v(0.0, 5.0)]; - let (p, _) = inset(&slanted, &[2.0, 0.0, 0.0, 0.0]).unwrap(); + let (p, _) = inset(&slanted, &[2.0, 0.0, 0.0, 0.0], 1e-6).unwrap(); assert!(p[1].dist(v(12.0, 2.0)) < 1e-12 && p[0].dist(v(0.0, 2.0)) < 1e-12, "{p:?}"); // Setbacks longer than the face leave nothing of it. - assert!(inset(&square, &[6.0, 0.0, 6.0, 0.0]).is_err()); - assert!(inset(&square, &[f64::NAN, 0.0, 0.0, 0.0]).is_err()); + assert!(inset(&square, &[6.0, 0.0, 6.0, 0.0], 1e-6).is_err()); + assert!(inset(&square, &[f64::NAN, 0.0, 0.0, 0.0], 1e-6).is_err()); } } diff --git a/crates/doc/src/sheet_face_names.rs b/crates/doc/src/sheet_face_names.rs index 3e37736f5..c761858e0 100644 --- a/crates/doc/src/sheet_face_names.rs +++ b/crates/doc/src/sheet_face_names.rs @@ -5,7 +5,8 @@ //! neighbouring flange), the rim along the bend there, `:rim.ext0` and `rim.ext1`. A panel is `base` or a flange's tag (`F.`), so the names //! say what each face is and stay with it when sizes change or other flanges come and go. -use solidcraft_geom::{Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use super::SheetBody; use crate::{ModelBody, ModelState, apply_point, mat_inverse}; @@ -13,6 +14,9 @@ use crate::{ModelBody, ModelState, apply_point, mat_inverse}; /// The share of a face's sample points that must agree on a name for the face to take it. const AGREE: f64 = 0.8; +/// The sine of the angle within which a flat face's plane faces along a triangle's normal. +const FACING: f64 = 1e-3; + impl SheetBody { /// The readable name of the face of this sheet a point lies on (sheet coordinates, within /// `tol`, kept below a quarter of the thickness): a flat face's (see @@ -21,6 +25,24 @@ impl SheetBody { self.panel_face_at(p, tol).map(|(name, _)| name).or_else(|| self.bend_face_at(p, tol)).or_else(|| self.ext_rim_at(p, tol)) } + /// [`face_name_at`](Self::face_name_at) for a point on a face whose normal is `normal` (a + /// mesh triangle's, either way round): a flat face's name is taken only where its plane faces + /// along `normal`. A rim is as narrow as the sheet is thick, so the centres of its triangles + /// can lie within `tol` of the panel's top or bottom face beside it. + fn face_name_facing(&self, p: Vec3, normal: Vec3, tol: f64) -> Option { + let facing = |plane: &Plane| plane.normal().cross(normal).len() < FACING; + match self.panel_face_at(p, tol) { + Some((name, plane)) if facing(&plane) => Some(name), + Some(_) => self + .rim_face_at(p, tol) + .filter(|(_, plane)| facing(plane)) + .map(|(name, _)| name) + .or_else(|| self.bend_face_at(p, tol)) + .or_else(|| self.ext_rim_at(p, tol)), + None => self.bend_face_at(p, tol).or_else(|| self.ext_rim_at(p, tol)), + } + } + /// The rim of a flange's panel along its bend line, where the panel runs on past the /// bend's start (`:rim.ext0`) or end (`rim.ext1`). fn ext_rim_at(&self, p: Vec3, tol: f64) -> Option { @@ -68,8 +90,8 @@ impl SheetBody { let Some(inverse) = mat_inverse(&world) else { continue }; let q = apply_point(&inverse, p) - o; let u = q.dot(d); - let (u0, u1) = self.zone_span(f); - if u < u0 - tol || u > u1 + tol { + let (lo, hi) = self.zone_reach(f); + if u < lo - tol || u > hi + tol { continue; } let radial = q - d * u; @@ -106,12 +128,13 @@ pub fn body_sheet_face_names(st: &ModelState, b: &ModelBody) -> Vec= 48 { continue; } *n += 1; - if let Some(name) = sheet.face_name_at((a + b2 + c) * (1.0 / 3.0), tol) { + if let Some(name) = sheet.face_name_facing((a + b2 + c) * (1.0 / 3.0), normal, tol) { match v.iter_mut().find(|(x, _)| *x == name) { Some(x) => x.1 += 1, None => v.push((name, 1)), diff --git a/crates/doc/src/sketch_equation.rs b/crates/doc/src/sketch_equation.rs index dcfdbcbbc..646b07fc6 100644 --- a/crates/doc/src/sketch_equation.rs +++ b/crates/doc/src/sketch_equation.rs @@ -5,10 +5,11 @@ //! between the points, up to the most a spline takes. When the parameters change, the same //! number of points is placed again (`Document::apply_equation_values`), before every solve. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; -use solidcraft_geom::Vec2; -use solidcraft_sketch::{EquationCurve, MAX_COORD, MAX_EQUATION_TEXT, MAX_SPLINE_POINTS, Sketch, fit_beziers_mode}; +use solidcore_record::Vec2; +use solidcraft_sketch::{EquationCurve, MAX_COORD, MAX_EQUATION_TEXT, MAX_SPLINE_POINTS, Sketch, VariableUnit, fit_beziers_mode}; use crate::expr::{self, Defaults, Kind, Value}; use crate::{DocError, Result}; @@ -36,8 +37,13 @@ pub struct EquationFit { pub deviation: f64, } -/// How bare numbers read in the formulas: angles in radians (the variable is a plain number, -/// `sin(t)` its sine), lengths in the design's unit. +/// Why a range cannot give the variable its unit (#9333): a length and an angle have no unit in +/// common, and two plain numbers have none to give. +const RANGE_UNIT_REFUSED: &str = + "with the variable in its range's unit, start and end must both be lengths, or one a length and the other a plain number"; + +/// How bare numbers read in the formulas: angles in radians (a plain variable's `sin(t)` is its +/// sine), lengths in the design's unit. fn defaults(vals: &BTreeMap) -> Defaults { let len = vals.get(crate::eval::DESIGN_LEN).map(|v| v.v).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0); Defaults { len, ang: 1.0 } @@ -54,31 +60,45 @@ fn checked_text<'a>(what: &str, e: &'a str) -> Result<&'a str> { Ok(e) } +/// The variable as the formulas see it, where it is `at` (a number, or the design's unit). +fn variable_value(eq: &EquationCurve, at: f64, d: Defaults) -> Value { + match eq.variable_unit { + VariableUnit::Number => Value::num(at), + VariableUnit::Range => Value::length(at * d.len), + } +} + /// A formula's value (mm) where the variable is `at`. The variable hides a parameter of its name. -fn formula(vals: &BTreeMap, e: &str, variable: &str, at: f64, d: Defaults) -> Result { +fn formula(vals: &BTreeMap, e: &str, variable: &str, at: Value, d: Defaults) -> Result { let lookup = |n: &str| { - if n == variable { Ok(Value::num(at)) } else { vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))) } + if n == variable { Ok(at) } else { vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))) } }; let v = expr::eval_with_defaults(e, &lookup, d)?.to_kind_in(Kind::Length, d)?; if v.is_finite() && v.abs() < MAX_COORD { Ok(v) } else { Err(DocError::Expr("the curve goes out of range".into())) } } -/// Where the variable starts or ends, as the plain number the formulas see: a number, an angle -/// (in radians) or a length (in the design's unit). -fn range_end(vals: &BTreeMap, e: &str, d: Defaults) -> Result { +/// Where the variable starts or ends, as a number: a number, an angle (in radians) or a length +/// (in the design's unit); and which of them it is. +fn range_end(vals: &BTreeMap, e: &str, d: Defaults) -> Result<(f64, Kind)> { let v = expr::eval_with_defaults(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), d)?; - let out = match v.kind() { - Some(Kind::Unitless | Kind::Angle) => v.v, - Some(Kind::Length) => v.v / d.len, + let (out, kind) = match v.kind() { + Some(kind @ (Kind::Unitless | Kind::Angle)) => (v.v, kind), + Some(Kind::Length) => (v.v / d.len, Kind::Length), None => return Err(DocError::Expr(format!("expected a number, an angle or a length, got {}", v.describe()))), }; - if out.is_finite() { Ok(out) } else { Err(DocError::Expr("not a finite number".into())) } + if out.is_finite() { Ok((out, kind)) } else { Err(DocError::Expr("not a finite number".into())) } } /// The variable's range, checked. fn range(vals: &BTreeMap, eq: &EquationCurve, d: Defaults) -> Result<(f64, f64)> { - let a = range_end(vals, checked_text("the start", &eq.start)?, d).map_err(|e| DocError::Expr(format!("start: {e}")))?; - let b = range_end(vals, checked_text("the end", &eq.end)?, d).map_err(|e| DocError::Expr(format!("end: {e}")))?; + let (a, start) = range_end(vals, checked_text("the start", &eq.start)?, d).map_err(|e| DocError::Expr(format!("start: {e}")))?; + let (b, end) = range_end(vals, checked_text("the end", &eq.end)?, d).map_err(|e| DocError::Expr(format!("end: {e}")))?; + // A plain number beside a length is in the design's unit, as `range_end` already reads it. + if eq.variable_unit == VariableUnit::Range + && !matches!((start, end), (Kind::Length, Kind::Length | Kind::Unitless) | (Kind::Unitless, Kind::Length)) + { + return Err(DocError::Invalid(RANGE_UNIT_REFUSED.into())); + } if (b - a).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0) { return Err(DocError::Invalid("the start and the end of the range must differ".into())); } @@ -91,8 +111,9 @@ fn range(vals: &BTreeMap, eq: &EquationCurve, d: Defaults) -> Res /// The curve's point where the variable is `at`. fn point_at(vals: &BTreeMap, eq: &EquationCurve, at: f64, d: Defaults) -> Result { let variable = eq.variable(); + let value = variable_value(eq, at, d); let x = match &eq.x { - Some(e) => formula(vals, e, variable, at, d).map_err(|e| DocError::Expr(format!("x: {e}")))?, + Some(e) => formula(vals, e, variable, value, d).map_err(|e| DocError::Expr(format!("x: {e}")))?, // The explicit form: x is the variable, in the design's unit. None => { let x = at * d.len; @@ -102,7 +123,7 @@ fn point_at(vals: &BTreeMap, eq: &EquationCurve, at: f64, d: Defa x } }; - let y = formula(vals, &eq.y, variable, at, d).map_err(|e| DocError::Expr(format!("y: {e}")))?; + let y = formula(vals, &eq.y, variable, value, d).map_err(|e| DocError::Expr(format!("y: {e}")))?; Ok(Vec2::new(x, y)) } @@ -286,9 +307,24 @@ mod tests { start: start.into(), end: end.into(), tolerance: DEFAULT_TOLERANCE, + variable_unit: VariableUnit::Number, } } + /// The same curve with its variable in its range's unit. + fn with_range_unit(eq: EquationCurve) -> EquationCurve { + EquationCurve { variable_unit: VariableUnit::Range, ..eq } + } + + fn with_a(mm: f64, design_len: Option) -> BTreeMap { + let mut vals = BTreeMap::new(); + vals.insert("a".to_string(), Value::length(mm)); + if let Some(len) = design_len { + vals.insert(crate::eval::DESIGN_LEN.to_string(), Value::num(len)); + } + vals + } + #[test] fn a_circle_closes_and_stays_within_the_tolerance() { let vals = BTreeMap::new(); @@ -360,4 +396,92 @@ mod tests { let long = "t + ".repeat(400) + "t"; assert!(fit(&vals, &eq(Some(&long), "t", "0", "1")).is_err()); } + + /// The issue's parabola (#9333): y = a^2 / (4 t) over t from a to 3a, where t is a length. + /// Every point is exact, and the curve is the same in millimetres whatever the design's unit. + #[test] + fn a_variable_in_its_ranges_unit_gives_the_exact_parabola_in_any_design_unit() { + for design_len in [None, Some(25.4)] { + let vals = with_a(10.0, design_len); + let e = with_range_unit(eq(Some("t"), "a ^ 2 / (4 * t)", "a", "3 * a")); + let fit = fit(&vals, &e).unwrap(); + let (first, last) = (fit.points[0], *fit.points.last().unwrap()); + assert!((first - Vec2::new(10.0, 2.5)).len() < 1e-9, "{design_len:?} {first:?}"); + assert!((last - Vec2::new(30.0, 100.0 / 120.0)).len() < 1e-9, "{design_len:?} {last:?}"); + for p in &fit.points { + assert!((p.y - 100.0 / (4.0 * p.x)).abs() < 1e-9 && (10.0 - 1e-9..=30.0 + 1e-9).contains(&p.x), "{design_len:?} {p:?}"); + } + assert!(fit.deviation <= DEFAULT_TOLERANCE); + } + } + + /// The explicit form names its variable x; bare numbers beside it are in the design's unit. + #[test] + fn the_explicit_form_and_bare_numbers_follow_the_design_unit() { + let vals = with_a(25.4, Some(25.4)); + let fit = fit(&vals, &with_range_unit(eq(None, "x + 1", "0", "a"))).unwrap(); + let (first, last) = (fit.points[0], *fit.points.last().unwrap()); + assert!((first - Vec2::new(0.0, 25.4)).len() < 1e-9, "{first:?}"); + assert!((last - Vec2::new(25.4, 50.8)).len() < 1e-9, "{last:?}"); + } + + /// The rule the issue settled for the range's two ends (#9333). + #[test] + fn a_range_gives_its_unit_only_from_lengths_and_plain_numbers_beside_them() { + // A plain number beside a length is in the design's unit, on either side. + for (design_len, unit) in [(None, 1.0), (Some(25.4), 25.4)] { + let vals = with_a(100.0, design_len); + let up = fit(&vals, &with_range_unit(eq(Some("t"), "t / 2", "1", "a"))).unwrap(); + assert!((up.points[0] - Vec2::new(unit, unit / 2.0)).len() < 1e-9, "{:?}", up.points[0]); + assert!((*up.points.last().unwrap() - Vec2::new(100.0, 50.0)).len() < 1e-9); + let down = fit(&vals, &with_range_unit(eq(Some("t"), "t / 2", "a", "1"))).unwrap(); + assert!((down.points[0] - Vec2::new(100.0, 50.0)).len() < 1e-9); + assert!((*down.points.last().unwrap() - Vec2::new(unit, unit / 2.0)).len() < 1e-9); + } + // Nothing else: a length and an angle, and ends with no length to give. + let vals = with_a(10.0, None); + for (a, b) in [("a", "90 deg"), ("90 deg", "a"), ("0 deg", "90 deg"), ("0", "90 deg"), ("90 deg", "0"), ("0", "1")] { + let why = fit(&vals, &with_range_unit(eq(Some("t"), "t", a, b))).unwrap_err().to_string(); + assert!( + why.contains( + "with the variable in its range's unit, start and end must both be lengths, or one a length and the other a plain number" + ), + "{a}..{b}: {why}" + ); + } + // Off, the same ranges build, with the variable a plain number. + assert!(fit(&vals, &eq(Some("t"), "t", "a", "90 deg")).is_ok()); + } + + /// Off (#9333): the variable is a plain number over a length range, as saved curves expect. + #[test] + fn without_the_flag_the_variable_stays_a_plain_number() { + let vals = with_a(10.0, None); + let plain = fit(&vals, &eq(Some("t"), "t * t / 20", "0 mm", "40 mm")).unwrap(); + let last = *plain.points.last().unwrap(); + assert!((last - Vec2::new(40.0, 80.0)).len() < 1e-9, "{last:?}"); + assert!(fit(&vals, &eq(Some("t"), "a ^ 2 / (4 * t)", "a", "3 * a")).unwrap_err().to_string().contains("length^2")); + // On, that plain-number formula is a length squared, and is refused rather than misread. + assert!(fit(&vals, &with_range_unit(eq(Some("t"), "t * t / 20", "0 mm", "40 mm"))).is_err()); + } + + #[test] + fn hostile_formulas_with_the_variable_in_its_ranges_unit_are_refused() { + let vals = with_a(10.0, Some(25.4)); + for (x, y, a, b) in [ + ("t", "a ^ 2 / (4 * t)", "0", "a"), + ("t", "sqrt(t)", "a", "3 * a"), + ("t", "t ^ 1000", "a", "3 * a"), + ("t", "t", "a", "a"), + ("t", "t", "0", "1e300 mm"), + ("t", "t", "a", "1e308 in"), + ("t", "t", "a", "nan"), + ("t", "t", "a * a", "3 * a"), + ("1e300 * t", "t", "a", "3 * a"), + ("sin(t)", "t", "a", "3 * a"), + ("t", "unknown_name * t", "a", "3 * a"), + ] { + assert!(fit(&vals, &with_range_unit(eq(Some(x), y, a, b))).is_err(), "{x} {y} {a}..{b}"); + } + } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 4a126f483..d6f4c9a56 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -1,4 +1,4 @@ -use solidcraft_geom::{Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; use solidcraft_kernel::measure; use solidcraft_sketch::{ConstraintKind, Sketch}; @@ -40,9 +40,11 @@ fn plate_doc() -> (Document, u64) { start_offset: None, through_all: false, taper: None, + corner: Default::default(), to: None, to_offset: None, from: None, + to_body_apart: false, }, operation: Operation::NewBody, targets: vec![], @@ -159,6 +161,21 @@ fn results_kept_ahead_outlive_the_cache() { assert!(rel(measure(&m.state().bodies[0].body).unwrap().volume, 30000.0) < 1e-9); } +/// A warning quotes a long generated name by its start and end (#8541: fourteen split edges' +/// full names made one chamfer warning 122,701 characters long); a short name stays whole. +#[test] +fn warnings_quote_long_names_by_their_ends() { + let face = |i: usize| format!("Extrude{i}.side(Sketch{i}.l{i})·Fillet{i}.blend(Chamfer{i}.cap)"); + let long = (0..40).map(face).collect::>().join("|"); + let q = crate::name_lookup::quoted(&long); + assert!(q.chars().count() <= 80, "{q}"); + assert!(q.starts_with("Extrude0.side") && q.ends_with(&long[long.len() - 10..]) && q.contains('…'), "{q}"); + assert_eq!(crate::name_lookup::quoted("Extrude1.side|Box1.top"), "Extrude1.side|Box1.top"); + // Characters, not bytes: a name of non-ASCII characters is cut between characters. + let wide = "Ü".repeat(200); + assert_eq!(crate::name_lookup::quoted(&wide).chars().count(), 73); +} + /// A saved model whose feature warning is longer than 65,536 characters is still taken on open /// (#8541): Save writes it, so Open reads it. #[test] @@ -277,6 +294,9 @@ fn box_fillet_cut_timeline() { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), + turn: Default::default(), + tangent_chain: true, }, None, ) @@ -297,9 +317,11 @@ fn box_fillet_cut_timeline() { start_offset: None, through_all: false, taper: None, + corner: Default::default(), to: None, to_offset: None, from: None, + to_body_apart: false, }, operation: Operation::Cut, targets: vec![], @@ -348,6 +370,9 @@ fn errors_are_reported_not_fatal() { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), + turn: Default::default(), + tangent_chain: true, }, None, ) @@ -581,6 +606,33 @@ fn feature_inserted_at_a_marker_inside_a_timeline_folder_joins_it() { assert!(Document::from_json(&doc.to_json()).is_ok(), "the inserted feature must leave a reopenable design"); } +/// #9373: a timeline folder that names a feature or joint the design doesn't have, or a feature +/// a folder already lists, no longer stops the design opening. Those entries are dropped and +/// everything else is kept. Editing a feature inside a folder used to save such entries. +#[test] +fn a_folder_naming_missing_or_repeated_features_still_opens() { + let mut doc = Document::new("stale folder entries"); + let sketch = || FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }; + let a = doc.add_feature(sketch(), Some("A")).unwrap(); + let b = doc.add_feature(sketch(), Some("B")).unwrap(); + let c = doc.add_feature(sketch(), Some("C")).unwrap(); + let missing = doc.next_id + 10; + doc.timeline_groups.push(TimelineGroup { id: 100, name: "Repeats".into(), parent: None, features: vec![a, b, b], joints: vec![] }); + doc.timeline_groups.push(TimelineGroup { + id: 101, + name: "Stale".into(), + parent: None, + features: vec![b, c, missing, missing, missing], + joints: vec![missing, missing], + }); + let opened = Document::from_json(&doc.to_json()).expect("the design opens"); + assert_eq!(opened.features.iter().map(|f| f.id).collect::>(), vec![a, b, c]); + assert_eq!(opened.timeline_groups[0].features, vec![a, b], "listed once"); + assert_eq!(opened.timeline_groups[1].features, vec![c], "no missing feature, nor one the first folder holds"); + assert!(opened.timeline_groups[1].joints.is_empty()); + assert_eq!(opened.timeline_groups.iter().map(|g| g.name.as_str()).collect::>(), ["Repeats", "Stale"], "both folders are kept"); +} + /// A marker after the last feature leaves every feature active, as no marker does, so a feature /// added then is active too, not added rolled back (#7741: editing the last feature from the /// History runs its command with the marker there). @@ -653,6 +705,28 @@ fn new_names_take_the_first_free_number() { assert_eq!(name(&doc, next), names[0], "the first freed number is taken again"); } +#[test] +fn construction_plane_name_collisions_leave_the_document_unchanged() { + let plane = || FeatureKind::ConstructionPlane { plane: PlaneRef::Origin { name: "XY".into() } }; + let sketch = || FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }; + for (first, second) in [(plane(), plane()), (plane(), sketch()), (sketch(), plane())] { + let mut doc = Document::new("names"); + let id = doc.add_feature(first, Some("Mid")).unwrap(); + // A suppressed feature beyond the marker still owns its name. + doc.feature_mut(id).unwrap().suppressed = true; + doc.marker = Some(0); + let before = doc.clone(); + for name in ["Mid", " Mid "] { + let error = doc.add_feature(second.clone(), Some(name)).unwrap_err().to_string(); + assert!(error.contains("another feature is called `Mid`"), "{error}"); + assert_eq!(doc, before, "a refused name must not consume an id or change the timeline"); + } + let other = doc.add_feature(second, Some("Upper")).unwrap(); + assert_eq!(doc.feature(other).unwrap().name, "Upper"); + assert_eq!(other, before.next_id); + } +} + #[test] fn empty_boolean_targets_name_overlapping_component() { for (operation, offset) in [(Operation::Cut, 0.0), (Operation::Intersect, 0.0), (Operation::Cut, 40.0)] { @@ -703,6 +777,131 @@ fn empty_boolean_targets_without_overlap_keep_plain_message() { } } +/// A box of `size` at `corner`, made with `operation`. +fn cube(doc: &mut Document, corner: Vec3, size: [f64; 3], operation: Operation) -> u64 { + let [length, width, height] = size.map(|x| Expr::new(x.to_string())); + doc.add_feature(FeatureKind::Box { corner: point_expr(corner), length, width, height, operation }, None).unwrap() +} + +/// The bodies of `doc` evaluated, by name with their volumes and pieces, and how feature +/// `feature`'s join touched the pieces it split off. +fn joined(doc: &Document, feature: u64) -> (Vec<(String, f64, usize)>, Option) { + let mut m = Model::new(); + m.evaluate(doc); + assert!(m.results.iter().all(|r| r.error.is_none()), "{:?}", m.results); + let kept = m.results.iter().find(|r| r.id == feature).and_then(|r| r.state.kept_separate(feature)); + let bodies = m.state().bodies.iter().map(|b| (b.name.clone(), measure(&b.body).unwrap().volume, b.body.lumps().unwrap().len())).collect(); + (bodies, kept) +} + +/// Two blocks joined along an edge cannot be one solid: the join splits them into two bodies and +/// says they touch along an edge. +#[test] +fn a_join_splits_blocks_touching_along_an_edge() { + let mut doc = Document::new("edge"); + cube(&mut doc, Vec3::ZERO, [10.0; 3], Operation::NewBody); + let join = cube(&mut doc, Vec3::new(10.0, 10.0, 0.0), [10.0; 3], Operation::Join); + let (bodies, kept) = joined(&doc, join); + assert_eq!(bodies.len(), 2, "{bodies:?}"); + assert!(bodies.iter().all(|(_, v, lumps)| rel(*v, 1000.0) < 1e-6 && *lumps == 1), "{bodies:?}"); + assert_eq!(kept, Some(KeptSeparate::AlongEdge)); + assert!(KeptSeparate::AlongEdge.notice().contains("along an edge")); +} + +/// Two blocks apart joined stay one body of two pieces, and the join says nothing. +#[test] +fn a_join_keeps_blocks_apart_in_one_body() { + let mut doc = Document::new("apart"); + cube(&mut doc, Vec3::ZERO, [10.0; 3], Operation::NewBody); + let join = cube(&mut doc, Vec3::new(20.0, 0.0, 0.0), [10.0; 3], Operation::Join); + let (bodies, kept) = joined(&doc, join); + assert_eq!(bodies.len(), 1, "{bodies:?}"); + assert!(rel(bodies[0].1, 2000.0) < 1e-6 && bodies[0].2 == 2, "{bodies:?}"); + assert_eq!(kept, None); +} + +/// A square ring joined with an arm touching its outer corner along an edge and a hub apart in +/// its hole: the ring and the hub stay one body under the ring's name, the arm is split off, and +/// the join says it touched along an edge. +#[test] +fn a_join_splits_off_only_what_touches_along_an_edge() { + let mut doc = Document::new("ring"); + cube(&mut doc, Vec3::new(-30.0, -30.0, 0.0), [60.0, 60.0, 6.0], Operation::NewBody); + cube(&mut doc, Vec3::new(-24.0, -24.0, -1.0), [48.0, 48.0, 8.0], Operation::Cut); + cube(&mut doc, Vec3::new(-5.0, -5.0, 0.0), [10.0, 10.0, 6.0], Operation::NewBody); + cube(&mut doc, Vec3::new(30.0, 30.0, 0.0), [20.0, 20.0, 6.0], Operation::NewBody); + let combine = doc + .add_feature( + FeatureKind::Combine { + target: "Body1".into(), + tools: vec!["Body3".into(), "Body2".into()], + operation: Operation::Join, + keep_tools: false, + }, + None, + ) + .unwrap(); + let (bodies, kept) = joined(&doc, combine); + let (ring, hub, arm) = (60.0 * 60.0 * 6.0 - 48.0 * 48.0 * 6.0, 600.0, 2400.0); + assert_eq!(bodies.len(), 2, "{bodies:?}"); + let named = |name: &str| bodies.iter().find(|(n, _, _)| n == name).cloned(); + let one = named("Body1").unwrap_or_else(|| panic!("{bodies:?}")); + assert!(rel(one.1, ring + hub) < 1e-6 && one.2 == 2, "the ring and the hub: {bodies:?}"); + let other = bodies.iter().find(|(n, _, _)| n != "Body1").cloned().unwrap_or_else(|| panic!("{bodies:?}")); + assert!(rel(other.1, arm) < 1e-6 && other.2 == 1, "the arm: {bodies:?}"); + assert_eq!(kept, Some(KeptSeparate::AlongEdge)); +} + +/// A fillet saved before corner setbacks reads with none and writes no `setbacks`; one with a +/// setback keeps it through a save, its distance an expression. +#[test] +fn fillet_setbacks_default_to_none_and_round_trip() { + let old = serde_json::json!({"type": "fillet", "edges": [[30.0, 40.0, 20.0]], "radius": "5"}); + let kind: FeatureKind = serde_json::from_value(old).unwrap(); + let FeatureKind::Fillet { setbacks, .. } = &kind else { panic!("{kind:?}") }; + assert!(setbacks.is_empty()); + assert!(serde_json::to_value(&kind).unwrap().get("setbacks").is_none()); + let set = FeatureKind::Fillet { + edges: vec![Position(Vec3::new(30.0, 40.0, 20.0))], + radius: "5".into(), + body: None, + style: Default::default(), + fit: Default::default(), + corner: Default::default(), + setbacks: vec![CornerSetback { vertex: Position(Vec3::new(60.0, 40.0, 20.0)), distance: "8 mm".into() }], + turn: Default::default(), + tangent_chain: true, + }; + let back: FeatureKind = serde_json::from_value(serde_json::to_value(&set).unwrap()).unwrap(); + assert_eq!(back, set); +} + +/// A fillet saved before turns reads as mitred and writes no `turn`; a swept one saves +/// `turn: "swept"` and keeps it through a save and an open; a turn of another name is refused. +#[test] +fn fillet_turn_defaults_to_mitre_round_trips_and_refuses_unknown_turns() { + let old = serde_json::json!({"type": "fillet", "edges": [[15.0, 0.0, 10.0]], "radius": "2"}); + let kind: FeatureKind = serde_json::from_value(old.clone()).unwrap(); + let FeatureKind::Fillet { turn, .. } = &kind else { panic!("{kind:?}") }; + assert_eq!(*turn, crate::FilletTurn::Mitre); + assert!(serde_json::to_value(&kind).unwrap().get("turn").is_none()); + let mut swept = old.clone(); + swept["turn"] = serde_json::json!("swept"); + let kind: FeatureKind = serde_json::from_value(swept).unwrap(); + assert!(matches!(kind, FeatureKind::Fillet { turn: crate::FilletTurn::Swept, .. }), "{kind:?}"); + assert_eq!(serde_json::to_value(&kind).unwrap()["turn"], "swept"); + let mut doc = Document::new("turn"); + doc.add_feature(kind.clone(), None).unwrap(); + let saved = doc.to_json(); + let opened = Document::from_json(&saved).unwrap(); + assert_eq!(opened.features.last().map(|f| &f.kind), Some(&kind)); + assert_eq!(opened.to_json(), saved); + let mut unknown = old; + unknown["turn"] = serde_json::json!("round"); + let e = serde_json::from_value::(unknown).unwrap_err().to_string(); + assert!(e.contains("unknown variant `round`") && e.contains("mitre") && e.contains("swept"), "{e}"); +} + #[test] fn timeline_group_legacy_json_omits_empty_joint_membership() { let old = serde_json::json!({"id":100, "name":"Folder", "parent":null, "features":[]}); @@ -741,3 +940,221 @@ fn a_sketch_too_large_to_search_whole_says_profiles_may_be_missing() { m.evaluate(&plate); assert!(m.result(plate_sketch).and_then(|r| r.warning.as_deref()).is_none()); } + +fn browser_group(id: u64, component: u64, folder: &str, parent: Option, items: &[BrowserEntry]) -> BrowserGroup { + BrowserGroup { id, name: format!("G{id}"), component, folder: folder.into(), parent, items: items.to_vec() } +} + +fn item(key: &str) -> BrowserEntry { + BrowserEntry::item(key) +} + +fn group(id: u64) -> BrowserEntry { + BrowserEntry::Group(id) +} + +/// The design with what `browser_pruned` drops gone (the design itself when nothing is). +fn pruned(doc: &Document) -> Document { + let mut out = doc.clone(); + if let Some((groups, order)) = doc.browser_pruned() { + (out.browser_groups, out.browser_order) = (groups, order); + } + out +} + +/// Pruning keeps every group but cuts a parent that loops, is the group itself, is past the +/// nesting limit, or is in another component or folder, to the top level; and it drops entries +/// for deleted sketches and placements, repeats, and the lists of a missing component. Body names +/// are never judged. +#[test] +fn browser_pruning_cuts_bad_parents_and_drops_stale_and_repeated_entries() { + let mut doc = Document::new("prune"); + let sketch = doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }, None).unwrap(); + let key = sketch.to_string(); + doc.components.push(Component { id: 7, name: "Part".into(), ..Default::default() }); + doc.occurrences.push(Occurrence { id: 20, component: 7, parent: 0, name: "Part".into(), transform: IDENTITY, grounded: false, bom_type: None }); + let deep = MAX_GROUP_NESTING as u64 + 2; + doc.browser_groups = vec![ + browser_group(1, 0, "bodies", Some(2), &[]), + browser_group(2, 0, "bodies", Some(1), &[]), + browser_group(3, 0, "bodies", Some(3), &[]), + browser_group(4, 7, "bodies", Some(5), &[]), + browser_group(5, 0, "bodies", None, &[item("a"), group(7), group(7), item("a")]), + browser_group(6, 0, "sketches", Some(5), &[item(&key), item("999")]), + browser_group(7, 0, "bodies", Some(5), &[]), + browser_group(8, 0, "bodies", None, &[item("a"), item("b")]), + ]; + doc.browser_groups.extend((0..deep).map(|i| browser_group(100 + i, 0, "construction", i.checked_sub(1).map(|p| 100 + p), &[]))); + doc.browser_order.insert("0/bodies".into(), vec![item("Lid"), item("Ghost"), item("Lid"), group(5), group(5)]); + doc.browser_order.insert("0/components".into(), vec![item("21"), item("20")]); + doc.browser_order.insert("99/bodies".into(), vec![item("x")]); + let after = pruned(&doc); + let parent = |id| after.browser_group(id).unwrap().parent; + assert_eq!(after.browser_groups.len(), doc.browser_groups.len(), "no group is dropped"); + assert_eq!([1, 2, 3, 4, 6].map(parent), [None; 5], "a loop, itself, another component, another folder"); + assert_eq!(parent(7), Some(5)); + for i in 0..deep { + assert_eq!(parent(100 + i), (1..MAX_GROUP_NESTING as u64).contains(&i).then(|| 99 + i), "level {} of a chain {deep} deep", i + 1); + } + assert_eq!(after.browser_group(5).unwrap().items, [item("a"), group(7)]); + assert_eq!(after.browser_group(8).unwrap().items, [item("b")], "an item stays in the first group that has it"); + assert_eq!(after.browser_group(6).unwrap().items, [item(&key)], "the deleted sketch goes"); + assert_eq!(after.browser_order["0/bodies"], [item("Lid"), item("Ghost"), group(5)], "body names stay; repeats go"); + assert_eq!(after.browser_order["0/components"], [item("20")], "the deleted placement goes"); + assert!(!after.browser_order.contains_key("99/bodies")); + assert!(Document::new("clean").browser_pruned().is_none(), "nothing to prune is not a change"); +} + +/// Levels and ancestry follow the parents. Groups a list does not name go after the last one it +/// names, in creation order, or first when it names none: above the items, as a design saved +/// before groups could be ordered has always shown them. +#[test] +fn group_levels_and_the_order_of_groups_a_list_does_not_name() { + let mut doc = Document::new("order"); + doc.browser_groups = vec![ + browser_group(1, 0, "bodies", None, &[item("x")]), + browser_group(2, 0, "bodies", None, &[]), + browser_group(3, 0, "bodies", None, &[]), + browser_group(4, 0, "bodies", Some(1), &[]), + browser_group(5, 0, "bodies", Some(4), &[]), + ]; + assert_eq!([1, 2, 4, 5].map(|id| doc.group_level(id)), [1, 1, 2, 3]); + assert!(doc.group_within(5, 1) && doc.group_within(5, 5) && !doc.group_within(1, 5) && !doc.group_within(2, 5)); + assert_eq!(doc.group_height(1), 3); + let top = |doc: &Document| doc.ordered_entries(0, "bodies", None); + assert_eq!(top(&doc), [group(1), group(2), group(3)], "no list: creation order"); + doc.browser_order.insert("0/bodies".into(), vec![item("a")]); + assert_eq!(top(&doc), [group(1), group(2), group(3), item("a")], "a list of items only: groups above them"); + doc.browser_order.insert("0/bodies".into(), vec![item("a"), group(2), item("b"), group(2), group(9)]); + assert_eq!(top(&doc), [item("a"), group(2), group(1), group(3), item("b")], "after the last listed; repeats and unknown ignored"); + assert_eq!(doc.ordered_entries(0, "bodies", Some(1)), [group(4), item("x")], "inside a group too"); +} + +/// Nested groups and a `components` order survive a save and a load, saved as numbers (groups) and +/// strings (items). A design from before groups could nest reads with the browser it always had: +/// no parents, groups in creation order above the items in their saved order, saved back as read. +#[test] +fn browser_data_survives_a_save_and_old_designs_read_unchanged() { + let mut doc = Document::new("nested"); + doc.components.push(Component { id: 7, name: "Part".into(), ..Default::default() }); + for id in [20, 21] { + doc.occurrences.push(Occurrence { + id, + component: 7, + parent: 0, + name: format!("P{id}"), + transform: IDENTITY, + grounded: false, + bom_type: None, + }); + } + doc.browser_groups = vec![browser_group(2, 0, "bodies", None, &[item("Lid"), group(3)]), browser_group(3, 0, "bodies", Some(2), &[item("Base")])]; + doc.browser_order.insert("0/bodies".into(), vec![item("Cap"), group(2)]); + doc.browser_order.insert("0/components".into(), vec![item("21"), item("20")]); + let saved = doc.to_json(); + let value: serde_json::Value = serde_json::from_str(&saved).unwrap(); + assert_eq!(value["browser_order"]["0/bodies"], serde_json::json!(["Cap", 2])); + assert_eq!((&value["browser_groups"][1]["parent"], value["browser_groups"][0].get("parent")), (&serde_json::json!(2), None)); + let loaded = Document::from_json(&saved).unwrap(); + assert_eq!((&loaded.browser_groups, &loaded.browser_order), (&doc.browser_groups, &doc.browser_order)); + let resaved: serde_json::Value = serde_json::from_str(&loaded.to_json()).unwrap(); + assert_eq!((&resaved["browser_groups"], &resaved["browser_order"]), (&value["browser_groups"], &value["browser_order"])); + + let groups = serde_json::json!([ + {"id": 3, "name": "Fasteners", "component": 0, "folder": "bodies", "items": ["Bolt", "Nut"]}, + {"id": 4, "name": "Plates", "component": 0, "folder": "bodies", "items": ["Plate"]}, + ]); + for (order, top) in [ + (serde_json::json!({}), vec![group(3), group(4)]), + (serde_json::json!({"0/bodies": ["Washer", "Bolt", "Cap"]}), vec![group(3), group(4), item("Washer"), item("Bolt"), item("Cap")]), + ] { + let mut old: serde_json::Value = serde_json::from_str(&Document::new("old").to_json()).unwrap(); + (old["browser_groups"], old["browser_order"]) = (groups.clone(), order.clone()); + let loaded = Document::from_json(&old.to_string()).unwrap(); + assert!(loaded.browser_groups.iter().all(|g| g.parent.is_none()), "{order}"); + assert_eq!(loaded.ordered_entries(0, "bodies", None), top, "{order}"); + let resaved: serde_json::Value = serde_json::from_str(&loaded.to_json()).unwrap(); + assert_eq!(resaved["browser_groups"], groups, "{order}"); + } +} + +/// #10748: verify that type names map to their canonical design-file kind keys. +#[test] +fn feature_kind_key_and_type_name_mappings() { + assert_eq!(FeatureKind::type_name_to_kind_key("HoleFeature"), Some("hole")); + assert_eq!(FeatureKind::type_name_to_kind_key("BoxFeature"), Some("box")); + assert_eq!(FeatureKind::type_name_to_kind_key("EdgeFlangeFeature"), Some("sheet_flange")); + assert_eq!(FeatureKind::type_name_to_kind_key("RectangularPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("PathPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("CircularPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("ExtrudeFeature"), Some("extrude")); + assert_eq!(FeatureKind::type_name_to_kind_key("SplitBodyFeature"), Some("split")); + assert_eq!(FeatureKind::type_name_to_kind_key("BaseFeature"), Some("import")); + assert_eq!(FeatureKind::type_name_to_kind_key("MeshFeature"), Some("mesh_import")); + assert_eq!(FeatureKind::type_name_to_kind_key("NonExistent"), None); +} + +/// An extruded ellipse has one side face, and a spline in a profile one wall, each named by its +/// sketch curve alone (no piece number): the same names on a second build and after reopening. +#[test] +fn an_extruded_ellipse_or_spline_is_one_wall_named_by_its_curve() { + let extrude = |sketch: u64| FeatureKind::Extrude { + thin: None, + sketch: crate::SketchId(sketch), + profiles: ProfileSel::All, + extent: Extent { + convention: crate::ExtrudeConvention::LegacyPerSide, + distance: "20".into(), + direction: Direction::Positive, + distance2: None, + start_offset: None, + through_all: false, + taper: None, + corner: Default::default(), + to: None, + to_offset: None, + from: None, + to_body_apart: false, + }, + operation: Operation::NewBody, + targets: vec![], + }; + for spline in [false, true] { + let mut sk = Sketch::new(); + let curve = if spline { + let pts: Vec = + [(0., 0.), (10., -3.), (20., 4.), (30., 0.)].iter().map(|&(x, y)| sk.add_point(Vec2::new(x, y), None).unwrap()).collect(); + let (a, b) = (sk.add_point(Vec2::new(30., 20.), None).unwrap(), sk.add_point(Vec2::new(0., 20.), None).unwrap()); + let curve = sk + .add_curve(solidcraft_sketch::CurveKind::Spline { pts: pts.clone(), control: false, degree: 3, periodic: false, nurbs: None }, None) + .unwrap(); + sk.add_line_pts(pts[3], a, None).unwrap(); + sk.add_line_pts(a, b, None).unwrap(); + sk.add_line_pts(b, pts[0], None).unwrap(); + curve + } else { + let m = sk.add_point(Vec2::new(10., 0.), None).unwrap(); + sk.add_curve(solidcraft_sketch::CurveKind::Ellipse { c: 0, m, r: 5. }, None).unwrap() + }; + let id = sk.curves[curve].id.clone(); + let mut doc = Document::new("one wall"); + let s = doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: sk }, None).unwrap(); + let f = doc.add_feature(extrude(s), None).unwrap(); + let names = |doc: &Document| { + let mut m = Model::new(); + m.evaluate(doc); + assert!(m.results.iter().all(|r| r.error.is_none()), "{:?}", m.results); + let st = m.state(); + let mut names = crate::naming::face_names(&st.bodies[0]).as_ref().clone(); + names.sort(); + names + }; + let first = names(&doc); + let wall = format!("F{f}:side:{id}"); + assert_eq!(first.iter().filter(|n| **n == wall).count(), 1, "{first:?}"); + assert_eq!(first.len(), if spline { 6 } else { 3 }, "{first:?}"); + assert!(first.iter().all(|n| !n.contains('#')), "no piece names: {first:?}"); + assert_eq!(names(&doc), first, "a second build"); + assert_eq!(names(&Document::from_json(&doc.to_json()).unwrap()), first, "reopened"); + } +} diff --git a/crates/doc/src/text_params.rs b/crates/doc/src/text_params.rs index 7fb35bb1d..53866b029 100644 --- a/crates/doc/src/text_params.rs +++ b/crates/doc/src/text_params.rs @@ -3,9 +3,17 @@ //! kept apart from the number parameters: a text has no unit and no number expression reads it. //! A parameter edit or a configuration row that sets one relabels every text built from it, and //! the features that use those texts follow in the same rebuild. +//! +//! The words can show a number parameter's value too (#9281): `'Width: ' + Width` reads +//! `Width: 85 mm`, a length in the design's units, an angle in degrees (`30°`), up to three +//! decimals without trailing zeros. `number(Width)` is the number alone (`85`) and +//! `number(Width, 2)` gives it two decimals (`85.00`). use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +use crate::expr::Value; use crate::{DocError, Document, FeatureKind, MAX_PARAMS, Result}; /// The unit that marks a text parameter where parameters are listed, added or imported. @@ -49,8 +57,29 @@ pub fn unquote(s: &str) -> String { enum Term { Text(String), Name(String), + /// `number(name)` or `number(name, decimals)`, with the name's byte range. + Number { + name: String, + at: (usize, usize), + decimals: Option, + }, } +/// How the words show a number parameter. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Show { + /// As named: its value and unit, up to three decimals. + Named, + /// In `number(...)`: the number alone, with these decimals or up to three. + Number(Option), +} + +/// The function that shows a number parameter's value without its unit. +const NUMBER: &str = "number"; + +/// Most decimals `number(name, decimals)` takes. +const MAX_DECIMALS: u8 = 8; + /// The terms of a words expression with their byte ranges: quoted texts (single or double /// quotes, a quote doubled inside stands for one) and parameter names, joined by `+`. fn terms(s: &str) -> Result> { @@ -96,10 +125,16 @@ fn terms(s: &str) -> Result> { want_term = false; } else if c.is_alphabetic() || c == '_' { let start = i; - while cs.get(i).is_some_and(|x| x.1.is_alphanumeric() || x.1 == '_') { - i += 1; + i = word_end(&cs, i); + let word = s.get(at(start)..at(i)).unwrap_or_default().to_string(); + let open = skip_blanks(&cs, i); + if word == NUMBER && cs.get(open).is_some_and(|x| x.1 == '(') { + let (term, end) = number_call(s, &cs, open + 1)?; + i = end; + out.push((term, at(start), at(i))); + } else { + out.push((Term::Name(word), at(start), at(i))); } - out.push((Term::Name(s.get(at(start)..at(i)).unwrap_or_default().to_string()), at(start), at(i))); want_term = false; } else { return Err(DocError::Expr(format!("unexpected `{c}`: a text expression joins quoted texts and text parameters with +"))); @@ -112,11 +147,88 @@ fn terms(s: &str) -> Result> { Ok(out) } +fn word_end(cs: &[(usize, char)], mut i: usize) -> usize { + while cs.get(i).is_some_and(|x| x.1.is_alphanumeric() || x.1 == '_') { + i += 1; + } + i +} + +fn skip_blanks(cs: &[(usize, char)], mut i: usize) -> usize { + while cs.get(i).is_some_and(|x| x.1.is_whitespace()) { + i += 1; + } + i +} + +/// `number(` has been read up to `i`: the name, optional decimals and `)`; the term and where +/// it ends. +fn number_call(s: &str, cs: &[(usize, char)], i: usize) -> Result<(Term, usize)> { + let at = |i: usize| cs.get(i).map_or(s.len(), |x| x.0); + let usage = || DocError::Expr("number() takes a number parameter and, if wanted, its decimals: number(Width, 2)".into()); + let start = skip_blanks(cs, i); + if !cs.get(start).is_some_and(|x| x.1.is_alphabetic() || x.1 == '_') { + return Err(usage()); + } + let end = word_end(cs, start); + let name = s.get(at(start)..at(end)).unwrap_or_default().to_string(); + let mut i = skip_blanks(cs, end); + let mut decimals = None; + if cs.get(i).is_some_and(|x| x.1 == ',') { + let from = skip_blanks(cs, i + 1); + let mut to = from; + while cs.get(to).is_some_and(|x| x.1.is_ascii_digit()) { + to += 1; + } + let digits = s.get(at(from)..at(to)).unwrap_or_default(); + let n: u8 = digits.parse().map_err(|_| usage())?; + if n > MAX_DECIMALS { + return Err(DocError::Expr(format!("number() shows at most {MAX_DECIMALS} decimals"))); + } + decimals = Some(n); + i = skip_blanks(cs, to); + } + if !cs.get(i).is_some_and(|x| x.1 == ')') { + return Err(usage()); + } + Ok((Term::Number { name, at: (at(start), at(end)), decimals }, i + 1)) +} + +/// A number parameter's value as the words show it: `v` in millimetres, radians or no unit +/// (`len`, `ang`: its dimension), lengths in `units`. +pub fn show_number(v: f64, len: i8, ang: i8, units: &str, show: Show) -> Result { + let (value, unit) = match (len, ang) { + (0, 0) => (v, ""), + (1, 0) => { + let (scale, name) = crate::display_units::unit_scale(units); + (v * scale, name) + } + (0, 1) => (v.to_degrees(), "°"), + _ => return Err(DocError::Expr("a text shows lengths, angles and plain numbers only".into())), + }; + if !value.is_finite() || value.abs() > 1e12 { + return Err(DocError::Expr("the number is out of range for a text".into())); + } + let digits = match show { + Show::Number(Some(d)) => format!("{value:.*}", usize::from(d)), + Show::Named | Show::Number(None) => { + let t = format!("{value:.3}"); + let t = t.trim_end_matches('0').trim_end_matches('.'); + if t == "-0" { "0".to_string() } else { t.to_string() } + } + }; + Ok(match (show, unit) { + (Show::Number(_), _) | (_, "") => digits, + (Show::Named, "°") => format!("{digits}°"), + (Show::Named, unit) => format!("{digits} {unit}"), + }) +} + /// The parameters a words expression names (none when it does not parse). pub fn references(s: &str) -> Vec { let mut out: Vec = Vec::new(); for (t, _, _) in terms(s).unwrap_or_default() { - if let Term::Name(n) = t + if let Term::Name(n) | Term::Number { name: n, .. } = t && !out.contains(&n) { out.push(n); @@ -131,23 +243,27 @@ pub fn rename_reference(s: &str, old: &str, new: &str) -> String { let mut out = String::with_capacity(s.len()); let mut last = 0; for (t, a, b) in terms { - if matches!(&t, Term::Name(n) if n == old) { - out.push_str(s.get(last..a).unwrap_or_default()); - out.push_str(new); - last = b; - } + let at = match &t { + Term::Name(n) if n == old => (a, b), + Term::Number { name, at, .. } if name == old => *at, + _ => continue, + }; + out.push_str(s.get(last..at.0).unwrap_or_default()); + out.push_str(new); + last = at.1; } out.push_str(s.get(last..).unwrap_or_default()); out } /// The words an expression comes to, each parameter's text from `lookup`. -pub fn eval(s: &str, lookup: &dyn Fn(&str) -> Result) -> Result { +pub fn eval(s: &str, lookup: &dyn Fn(&str, Show) -> Result) -> Result { let mut out = String::new(); for (t, _, _) in terms(s)? { match t { Term::Text(text) => out.push_str(&text), - Term::Name(n) => out.push_str(&lookup(&n)?), + Term::Name(n) => out.push_str(&lookup(&n, Show::Named)?), + Term::Number { name, decimals, .. } => out.push_str(&lookup(&name, Show::Number(decimals))?), } if out.len() > MAX_LEN { return Err(DocError::Expr("the text is too long".into())); @@ -161,12 +277,14 @@ impl Document { self.text_params.iter().find(|p| p.name == name) } - /// The words a words expression comes to in this design. - pub fn eval_words(&self, e: &str) -> Result { - eval(e, &|n| match self.text_param(n) { - Some(p) => Ok(p.text.clone()), - None if self.name_taken(n) => Err(DocError::Expr(format!("`{n}` is a number parameter: a text's words take text parameters"))), - None => Err(DocError::Expr(format!("unknown text parameter `{n}`"))), + /// The words a words expression comes to in this design, number parameters from `vals`. + pub fn eval_words(&self, e: &str, vals: &BTreeMap) -> Result { + eval(e, &|n, show| match (self.text_param(n), vals.get(n)) { + (Some(_), _) if show != Show::Named => Err(DocError::Expr(format!("`{n}` is a text parameter: number() takes a number parameter"))), + (Some(p), _) => Ok(p.text.clone()), + (None, Some(v)) => show_number(v.v, v.len, v.ang, &self.units, show).map_err(|error| DocError::Expr(format!("`{n}`: {error}"))), + (None, None) if self.name_taken(n) => Err(DocError::Expr(format!("`{n}` has no value"))), + (None, None) => Err(DocError::Expr(format!("unknown parameter `{n}`"))), }) } @@ -230,7 +348,7 @@ mod tests { #[test] fn words_expressions_join_quoted_texts_and_parameters() { - let look = |n: &str| match n { + let look = |n: &str, _: Show| match n { "Label" => Ok("TAG-1".to_string()), _ => Err(DocError::Expr(format!("unknown text parameter `{n}`"))), }; @@ -249,4 +367,30 @@ mod tests { assert_eq!(unquote("'a' + 'b'"), "'a' + 'b'"); assert_eq!(unquote("TAG-1"), "TAG-1"); } + + /// #9281: a number parameter in the words shows its value; `number()` drops the unit and + /// can fix the decimals; a rename reaches inside `number()`. + #[test] + fn number_parameters_show_their_value_in_the_words() { + let look = |n: &str, show: Show| match n { + "Width" => show_number(85.0, 1, 0, "mm", show), + "Gap" => show_number(12.7, 1, 0, "in", show), + "Tilt" => show_number(30f64.to_radians(), 0, 1, "mm", show), + "Count" => show_number(4.0, 0, 0, "mm", show), + "Area" => show_number(1.0, 2, 0, "mm", show), + _ => Err(DocError::Expr(format!("unknown parameter `{n}`"))), + }; + assert_eq!(eval("'Width: ' + Width", &look).unwrap(), "Width: 85 mm"); + assert_eq!(eval("Gap", &look).unwrap(), "0.5 in"); + assert_eq!(eval("Tilt + ' / ' + Count", &look).unwrap(), "30° / 4"); + assert_eq!(eval("number(Width) + 'x' + number( Width , 2 )", &look).unwrap(), "85x85.00"); + assert_eq!(eval("number(Tilt, 1)", &look).unwrap(), "30.0"); + for bad in ["number(Width", "number()", "number(Width, x)", "number(Width, 9)", "number(Width 2)", "Area", "number('a')"] { + assert!(eval(bad, &look).is_err(), "{bad}"); + } + assert_eq!(references("number(Width, 1) + Count"), ["Width", "Count"]); + assert_eq!(rename_reference("number(Width, 1) + Width + 'Width'", "Width", "W"), "number(W, 1) + W + 'Width'"); + assert_eq!(show_number(-0.0001, 1, 0, "mm", Show::Named).unwrap(), "0 mm"); + assert!(show_number(f64::NAN, 0, 0, "mm", Show::Named).is_err()); + } } diff --git a/crates/doc/src/thread_catalog.rs b/crates/doc/src/thread_catalog.rs index a780a6c2a..642c8b44f 100644 --- a/crates/doc/src/thread_catalog.rs +++ b/crates/doc/src/thread_catalog.rs @@ -8,6 +8,10 @@ pub enum TappedThreadFamily { Unf, G, Rp, + /// ISO 7-1's internal taper thread (`Rc 1/2`). + Rc, + /// ASME B1.20.1's taper pipe thread, internal (`1/2-14 NPT`). + Npt, } #[derive(Clone, Debug, PartialEq)] @@ -22,7 +26,7 @@ pub struct TappedThread { impl TappedThread { pub fn profile_degrees(&self) -> f64 { match self.family { - TappedThreadFamily::G | TappedThreadFamily::Rp => 55.0, + TappedThreadFamily::G | TappedThreadFamily::Rp | TappedThreadFamily::Rc => 55.0, _ => 60.0, } } @@ -42,6 +46,110 @@ fn pipe_size(size: crate::pipe_thread_catalog::PipeThread) -> TappedThread { } } +/// The drill of an internal taper thread (Rc, NPT). `diameter` is the tap maker's tabulated +/// drill for a straight (not reamed) hole; `exact` is the standard's internal minor diameter where +/// the thread ends (mm), the reference plane's minor at the face (d - 2h for ISO 7-1, E1 - h for +/// NPT) less the 1 in 16 taper over the thread's length (ISO 7-1's useful thread, NPT's effective +/// thread L2), which the dialog shows beside it. +#[derive(Clone, Debug, PartialEq)] +pub struct TaperDrill { + pub exact: f64, + pub diameter: f64, +} + +/// Rc (ISO 7-1, "PT") drills: Yamawa YEU23, printed p.709 ("Taper Internal Pipe Threads - +/// Rc(BSPT)-PT"), the maximum size of a straight bored hole when the threads have non-full +/// threads (the same values as the Rc tap's bored hole A on printed p.121), for the sizes of +/// ISO 7-1's table it lists (1/16 to 4). +/// +const RC_DRILLS: &[(&str, f64)] = &[ + ("1/16", 6.1), + ("1/8", 8.1), + ("1/4", 10.7), + ("3/8", 14.2), + ("1/2", 17.6), + ("3/4", 23.0), + ("1", 29.0), + ("1 1/4", 37.6), + ("1 1/2", 43.5), + ("2", 55.0), + ("2 1/2", 70.3), + ("3", 82.8), + ("4", 107.6), +]; + +/// NPT drills: Yamawa YEU23, printed p.710 ("American Taper Pipe Threads (NPT)", referring to +/// ASME B1.20.1), the maximum size of a straight bored hole, 1/16 to 3. +const NPT_DRILLS: &[(&str, f64)] = &[ + ("1/16", 6.05), + ("1/8", 8.39), + ("1/4", 10.85), + ("3/8", 14.27), + ("1/2", 17.60), + ("3/4", 22.91), + ("1", 28.78), + ("1 1/4", 37.50), + ("1 1/2", 43.57), + ("2", 55.58), + ("2 1/2", 66.28), + ("3", 82.05), +]; + +/// The drill of an Rc or NPT size the tap maker tabulates; none for the others. +fn taper_drill(family: TappedThreadFamily, size: &crate::pipe_thread_sizes::PipeSize) -> Option { + let (table, h) = match family { + TappedThreadFamily::Npt => (NPT_DRILLS, crate::pipe_thread_sizes::NPT_HEIGHT * size.pitch()), + _ => (RC_DRILLS, 0.640327 * size.pitch()), + }; + let diameter = table.iter().find(|(n, _)| *n == size.nominal)?.1; + Some(TaperDrill { exact: size.major - 2.0 * h - size.length / 16.0, diameter }) +} + +/// The pipe sizes of a taper family. +fn taper_sizes(family: TappedThreadFamily) -> Vec { + match family { + TappedThreadFamily::Rc => crate::pipe_thread_sizes::iso_7_1().collect(), + TappedThreadFamily::Npt => crate::pipe_thread_sizes::npt().collect(), + _ => Vec::new(), + } +} + +impl TappedThread { + /// An Rc or NPT size's drill: the tap maker's and the standard's exact value. + pub fn taper_drill(&self) -> Option { + taper_sizes(self.family).iter().find(|z| (z.major - self.major_diameter).abs() < 1e-9).and_then(|z| taper_drill(self.family, z)) + } +} + +/// Why an Rc or NPT designation is no tapped hole's: a size of its standard the tap maker's table +/// has no drill for. None for any other text. +pub fn untabulated_taper_tap(text: &str) -> Option { + use crate::thread_forms::ThreadForm; + let (family, form, listed) = match ThreadForm::of_designation(text) { + Some(ThreadForm::Bspt) if ThreadForm::pipe_internal(text) => (TappedThreadFamily::Rc, ThreadForm::Bspt, "Rc 1/16 to Rc 4"), + Some(ThreadForm::Npt) => (TappedThreadFamily::Npt, ThreadForm::Npt, "1/16 to 3 NPT"), + _ => return None, + }; + let size = form.parse(text, 1).ok()?; + let z = taper_sizes(family).into_iter().find(|z| (z.major - size.major).abs() < 1e-9)?; + taper_drill(family, &z).is_none().then(|| { + format!("no tap drill is tabulated for `{}` (Yamawa's table, which the tapped-hole drills come from, lists {listed}): it is not offered as a tapped hole", text.trim()) + }) +} + +/// An internal taper thread (Rc, NPT) of the size tables a modelled thread cuts +/// ([`crate::pipe_thread_sizes`]), drilled with the tap maker's drill ([`TaperDrill`]); none for +/// a size without one. +fn taper_size(family: TappedThreadFamily, size: crate::pipe_thread_sizes::PipeSize) -> Option { + use crate::thread_forms::ThreadForm; + let p = size.pitch(); + let form = if family == TappedThreadFamily::Npt { ThreadForm::Npt } else { ThreadForm::Bspt }; + let designation = form.format(size.major, p, p); + let designation = if form == ThreadForm::Bspt { designation.replacen("R ", "Rc ", 1) } else { designation }; + let tap_drill = taper_drill(family, &size)?.diameter; + Some(TappedThread { family, designation, major_diameter: size.major, pitch: p, tap_drill }) +} + // Diameter/pitch pairs verified against Guhring, plus Yamawa for M12x1.25. const METRIC_FINE: &[(f64, f64)] = &[ (3.0, 0.35), @@ -94,14 +202,308 @@ const UNIFIED: &[(&str, TappedThreadFamily, f64, u32, f64)] = &[ ("1-12 UNF", TappedThreadFamily::Unf, 25.4, 12, 23.3), ]; +/// ISO metric cutting-tap drills (nominal diameter, pitch, drill; mm): Yamawa YEU23, "Drill size +/// and recommended hole size for cutting taps", printed p.704 (M, coarse) and pp.704 to 706 (MF, +/// fine), the drill size column. MF 70 x 1.5 is left out: its printed drill (68.00) lies below +/// the printed minimum minor diameter (68.376), a misprint. +/// +const METRIC_DRILLS: &[(f64, f64, f64)] = &[ + (1.0, 0.2, 0.8), + (1.0, 0.25, 0.75), + (1.1, 0.2, 0.9), + (1.1, 0.25, 0.85), + (1.2, 0.2, 1.0), + (1.2, 0.25, 0.95), + (1.4, 0.2, 1.2), + (1.4, 0.3, 1.1), + (1.6, 0.2, 1.4), + (1.6, 0.35, 1.25), + (1.7, 0.2, 1.5), + (1.7, 0.35, 1.35), + (1.8, 0.2, 1.6), + (1.8, 0.35, 1.45), + (2.0, 0.25, 1.75), + (2.0, 0.4, 1.6), + (2.2, 0.25, 1.95), + (2.2, 0.45, 1.75), + (2.3, 0.25, 2.05), + (2.3, 0.4, 1.9), + (2.5, 0.35, 2.2), + (2.5, 0.45, 2.1), + (2.6, 0.35, 2.3), + (2.6, 0.45, 2.2), + (3.0, 0.35, 2.7), + (3.0, 0.5, 2.5), + (3.5, 0.35, 3.2), + (3.5, 0.6, 2.9), + (4.0, 0.5, 3.5), + (4.0, 0.7, 3.3), + (4.5, 0.5, 4.0), + (4.5, 0.75, 3.8), + (5.0, 0.5, 4.5), + (5.0, 0.8, 4.2), + (5.5, 0.5, 5.0), + (6.0, 0.5, 5.5), + (6.0, 0.75, 5.3), + (6.0, 1.0, 5.0), + (7.0, 0.5, 6.5), + (7.0, 0.75, 6.3), + (7.0, 1.0, 6.0), + (8.0, 0.5, 7.5), + (8.0, 0.75, 7.3), + (8.0, 1.0, 7.0), + (8.0, 1.25, 6.8), + (9.0, 0.75, 8.3), + (9.0, 1.0, 8.0), + (9.0, 1.25, 7.8), + (10.0, 0.5, 9.5), + (10.0, 0.75, 9.3), + (10.0, 1.0, 9.0), + (10.0, 1.25, 8.8), + (10.0, 1.5, 8.5), + (11.0, 0.5, 10.5), + (11.0, 0.75, 10.3), + (11.0, 1.0, 10.0), + (11.0, 1.5, 9.5), + (12.0, 0.5, 11.5), + (12.0, 1.0, 11.0), + (12.0, 1.25, 10.8), + (12.0, 1.5, 10.5), + (12.0, 1.75, 10.3), + (14.0, 1.0, 13.0), + (14.0, 1.5, 12.5), + (14.0, 2.0, 12.0), + (15.0, 1.0, 14.0), + (15.0, 1.5, 13.5), + (16.0, 1.0, 15.0), + (16.0, 1.5, 14.5), + (16.0, 2.0, 14.0), + (17.0, 1.0, 16.0), + (17.0, 1.5, 15.5), + (18.0, 1.0, 17.0), + (18.0, 1.5, 16.5), + (18.0, 2.0, 16.0), + (18.0, 2.5, 15.5), + (20.0, 1.0, 19.0), + (20.0, 1.5, 18.5), + (20.0, 2.0, 18.0), + (20.0, 2.5, 17.5), + (22.0, 1.0, 21.0), + (22.0, 1.5, 20.5), + (22.0, 2.0, 20.0), + (22.0, 2.5, 19.5), + (24.0, 1.0, 23.0), + (24.0, 1.5, 22.5), + (24.0, 2.0, 22.0), + (24.0, 3.0, 21.0), + (25.0, 1.0, 24.0), + (25.0, 1.5, 23.5), + (25.0, 2.0, 23.0), + (26.0, 1.5, 24.5), + (27.0, 1.0, 26.0), + (27.0, 1.5, 25.5), + (27.0, 2.0, 25.0), + (27.0, 3.0, 24.0), + (28.0, 1.0, 27.0), + (28.0, 1.5, 26.5), + (28.0, 2.0, 26.0), + (30.0, 1.0, 29.0), + (30.0, 1.5, 28.5), + (30.0, 2.0, 28.0), + (30.0, 3.0, 27.0), + (30.0, 3.5, 26.5), + (32.0, 1.5, 30.5), + (32.0, 2.0, 30.0), + (33.0, 1.5, 31.5), + (33.0, 2.0, 31.0), + (33.0, 3.0, 30.0), + (33.0, 3.5, 29.5), + (35.0, 1.5, 33.5), + (36.0, 1.5, 34.5), + (36.0, 2.0, 34.0), + (36.0, 3.0, 33.0), + (36.0, 4.0, 32.0), + (38.0, 1.5, 36.5), + (39.0, 1.5, 37.5), + (39.0, 2.0, 37.0), + (39.0, 3.0, 36.0), + (39.0, 4.0, 35.0), + (40.0, 1.5, 38.5), + (40.0, 2.0, 38.0), + (40.0, 3.0, 37.0), + (42.0, 1.5, 40.5), + (42.0, 2.0, 40.0), + (42.0, 3.0, 39.0), + (42.0, 4.0, 38.0), + (42.0, 4.5, 37.5), + (45.0, 1.5, 43.5), + (45.0, 2.0, 43.0), + (45.0, 3.0, 42.0), + (45.0, 4.0, 41.0), + (45.0, 4.5, 40.5), + (48.0, 1.5, 46.5), + (48.0, 2.0, 46.0), + (48.0, 3.0, 45.0), + (48.0, 4.0, 44.0), + (48.0, 5.0, 43.0), + (50.0, 1.5, 48.5), + (50.0, 2.0, 48.0), + (50.0, 3.0, 47.0), + (52.0, 1.5, 50.5), + (52.0, 2.0, 50.0), + (52.0, 3.0, 49.0), + (52.0, 4.0, 48.0), + (52.0, 5.0, 47.0), + (55.0, 1.5, 53.5), + (55.0, 2.0, 53.0), + (55.0, 3.0, 52.0), + (55.0, 4.0, 51.0), + (56.0, 1.5, 54.5), + (56.0, 2.0, 54.0), + (56.0, 3.0, 53.0), + (56.0, 4.0, 52.0), + (56.0, 5.5, 50.5), + (58.0, 1.5, 56.5), + (58.0, 2.0, 56.0), + (58.0, 3.0, 55.0), + (58.0, 4.0, 54.0), + (60.0, 1.5, 58.5), + (60.0, 2.0, 58.0), + (60.0, 3.0, 57.0), + (60.0, 4.0, 56.0), + (60.0, 5.5, 54.5), + (62.0, 1.5, 60.5), + (62.0, 2.0, 60.0), + (62.0, 3.0, 59.0), + (62.0, 4.0, 58.0), + (64.0, 1.5, 62.5), + (64.0, 2.0, 62.0), + (64.0, 3.0, 61.0), + (64.0, 4.0, 60.0), + (64.0, 6.0, 58.0), + (65.0, 1.5, 63.5), + (65.0, 2.0, 63.0), + (65.0, 3.0, 62.0), + (65.0, 4.0, 61.0), + (68.0, 1.5, 66.5), + (68.0, 2.0, 66.0), + (68.0, 3.0, 65.0), + (68.0, 4.0, 64.0), + (68.0, 6.0, 62.0), + (70.0, 2.0, 68.0), + (70.0, 3.0, 67.0), + (70.0, 4.0, 66.0), + (70.0, 6.0, 64.0), + (72.0, 1.5, 70.5), + (72.0, 2.0, 70.0), + (72.0, 3.0, 69.0), + (72.0, 4.0, 68.0), + (72.0, 6.0, 66.0), + (75.0, 1.5, 73.5), + (75.0, 2.0, 73.0), + (75.0, 3.0, 72.0), + (75.0, 4.0, 71.0), + (76.0, 1.5, 74.5), + (76.0, 2.0, 74.0), + (76.0, 3.0, 73.0), + (76.0, 4.0, 72.0), + (76.0, 6.0, 70.0), + (78.0, 2.0, 76.0), + (80.0, 1.5, 78.5), + (80.0, 2.0, 78.0), + (80.0, 3.0, 77.0), + (80.0, 4.0, 76.0), + (80.0, 6.0, 74.0), + (82.0, 2.0, 80.0), + (85.0, 2.0, 83.0), + (85.0, 3.0, 82.0), + (85.0, 4.0, 81.0), + (85.0, 6.0, 79.0), + (90.0, 2.0, 88.0), + (90.0, 3.0, 87.0), + (90.0, 4.0, 86.0), + (90.0, 6.0, 84.0), + (95.0, 2.0, 93.0), + (95.0, 3.0, 92.0), + (95.0, 4.0, 91.0), + (95.0, 6.0, 89.0), + (100.0, 2.0, 98.0), + (100.0, 3.0, 97.0), + (100.0, 4.0, 96.0), + (100.0, 6.0, 94.0), +]; + +/// The drill of an ISO metric tapped hole: the tap maker's for a tabulated size, else (a custom +/// size) the major diameter less the pitch, to the micrometre. +pub fn metric_tap_drill(major_diameter: f64, pitch: f64) -> f64 { + let same = |a: f64, b: f64| (a - b).abs() < 1e-9; + METRIC_DRILLS + .iter() + .find(|(d, p, _)| same(*d, major_diameter) && same(*p, pitch)) + .map_or_else(|| ((major_diameter - pitch) * 1000.0).round() / 1000.0, |r| r.2) +} + fn metric_size(major_diameter: f64, pitch: f64) -> TappedThread { TappedThread { family: TappedThreadFamily::Metric, - designation: crate::eval::format_thread(major_diameter, pitch), + designation: crate::thread_forms::ThreadForm::Metric.format(major_diameter, pitch, pitch), major_diameter, pitch, - // Preserve the existing metric estimate and rounding used by solid.hole. - tap_drill: ((major_diameter - pitch) * 1000.0).round() / 1000.0, + tap_drill: metric_tap_drill(major_diameter, pitch), + } +} + +/// How much larger than the tap maker's drill a tapped hole may be drilled: 5%. +pub const DRILL_ALLOWANCE: f64 = 0.05; + +impl TappedThread { + /// Whether the drill is a tap maker's tabulated one (every catalogued size; not a custom + /// metric size, which takes the major less the pitch). + pub fn drill_is_tabulated(&self) -> bool { + self.family != TappedThreadFamily::Metric + || METRIC_DRILLS.iter().any(|(d, p, _)| (d - self.major_diameter).abs() < 1e-9 && (p - self.pitch).abs() < 1e-9) + } + + /// The internal thread's standard minor diameter: ISO metric and Unified D1 = D - 1.082532 P + /// (the basic profile, ISO 68-1 / ASME B1.1), G and Rp the basic minor of their table, Rc and + /// NPT the minor where the thread ends ([`TaperDrill`]). + pub fn minor_diameter(&self) -> f64 { + match self.family { + TappedThreadFamily::Metric | TappedThreadFamily::Unc | TappedThreadFamily::Unf => { + self.major_diameter - 1.25 * 3f64.sqrt() / 2.0 * self.pitch + } + TappedThreadFamily::G | TappedThreadFamily::Rp => crate::pipe_thread_catalog::parse_pipe_thread(&self.designation) + .map_or(self.major_diameter - 1.280654 * self.pitch, |t| t.size().minor), + TappedThreadFamily::Rc | TappedThreadFamily::Npt => self.taper_drill().map_or(self.tap_drill, |d| d.exact), + } + } + + /// The drills a tapped hole of this size accepts (mm): from the standard minor diameter (or + /// the tap maker's drill, where that lies below it, as a taper or Rp drill does) up to + /// [`DRILL_ALLOWANCE`] over the tap maker's drill. + pub fn drill_range(&self) -> (f64, f64) { + (self.minor_diameter().min(self.tap_drill), self.tap_drill * (1.0 + DRILL_ALLOWANCE)) + } + + /// Whether a hole of `diameter` mm can be tapped to this size; the error names the range. + pub fn check_drill(&self, diameter: f64) -> Result<(), String> { + let (lo, hi) = self.drill_range(); + let (show, d) = + (|v: f64| format!("{:.3}", (v * 1000.0).round() / 1000.0).trim_end_matches('0').trim_end_matches('.').to_string(), &self.designation); + let why = if !(diameter.is_finite() && diameter >= lo - 1e-9) { + "smaller than the thread's minor diameter: the tap cannot cut it" + } else if diameter > hi + 1e-9 { + "more than 5% over the tap maker's drill: too little of the thread would engage" + } else { + return Ok(()); + }; + Err(format!( + "a {d} tapped hole takes a drill from {} to {} mm (the tap maker's drill {} mm): {} mm is {why}", + show(lo), + show(hi), + show(self.tap_drill), + show(diameter) + )) } } @@ -110,6 +512,10 @@ pub fn tapped_thread_sizes(family: TappedThreadFamily) -> Vec { if matches!(family, TappedThreadFamily::G | TappedThreadFamily::Rp) { return crate::pipe_thread_catalog::pipe_thread_sizes().map(pipe_size).filter(|s| s.family == family).collect(); } + match family { + TappedThreadFamily::Rc | TappedThreadFamily::Npt => return taper_sizes(family).into_iter().filter_map(|z| taper_size(family, z)).collect(), + _ => {} + } if family == TappedThreadFamily::Metric { let mut sizes: Vec<_> = crate::metric_thread_sizes().iter().chain(METRIC_FINE).map(|&(d, p)| metric_size(d, p)).collect(); @@ -131,7 +537,8 @@ pub fn tapped_thread_sizes(family: TappedThreadFamily) -> Vec { } /// Explicit metric custom sizes remain supported. Unified sizes must be in the verified -/// catalogue and include their UNC/UNF suffix. G/Rp use explicit process drills; modeled Thread stays metric-only. +/// catalogue and include their UNC/UNF suffix. G/Rp use explicit process drills, Rc/NPT the tap +/// maker's tabulated drills ([`TaperDrill`]); an Rc or NPT size without one is none. pub fn parse_tapped_thread(text: &str) -> Option { if text.len() > 128 { return None; @@ -142,6 +549,18 @@ pub fn parse_tapped_thread(text: &str) -> Option { if let Some(size) = crate::pipe_thread_catalog::parse_pipe_thread(text) { return Some(pipe_size(size)); } + // An internal taper thread: Rc or NPT (an external R is no hole's). + use crate::thread_forms::ThreadForm; + let taper = match ThreadForm::of_designation(text) { + Some(ThreadForm::Bspt) if ThreadForm::pipe_internal(text) => Some((TappedThreadFamily::Rc, ThreadForm::Bspt)), + Some(ThreadForm::Bspt) => return None, + Some(ThreadForm::Npt) => Some((TappedThreadFamily::Npt, ThreadForm::Npt)), + _ => None, + }; + if let Some((family, form)) = taper { + let size = form.parse(text, 1).ok()?; + return tapped_thread_sizes(family).into_iter().find(|s| (s.major_diameter - size.major).abs() < 1e-9); + } let normalized = text.split_whitespace().collect::>().join(" ").to_ascii_uppercase(); let &(name, family, major_diameter, tpi, tap_drill) = UNIFIED.iter().find(|row| row.0 == normalized)?; Some(TappedThread { family, designation: name.into(), major_diameter, pitch: 25.4 / f64::from(tpi), tap_drill }) @@ -163,14 +582,104 @@ mod tests { } } + /// Rc and NPT holes: the size tables' diameters, the tap maker's drill (Yamawa YEU23 pp.709 + /// and 710) and the standard's minor where the thread ends (Rc 1/2: d1 18.631 at the face less + /// 13.2 mm of useful thread at 1 in 16; 1/2 NPT: E1 - h = 0.77843 - 0.05714 in at the face less + /// L2 = 0.5337 in at 1 in 16), a size without a tabulated drill refused, and no external R. + #[test] + fn internal_taper_threads_take_the_tap_makers_drill() { + let rc = parse_tapped_thread("Rc1/2").unwrap(); + assert_eq!((rc.family, rc.designation.as_str(), rc.major_diameter, rc.tap_drill), (TappedThreadFamily::Rc, "Rc 1/2", 20.955, 17.6)); + let d = rc.taper_drill().unwrap(); + assert!((d.exact - (18.631 - 13.2 / 16.0)).abs() < 2e-3, "{d:?}"); + let npt = parse_tapped_thread("1/2 NPT").unwrap(); + assert_eq!((npt.family, npt.designation.as_str(), npt.tap_drill), (TappedThreadFamily::Npt, "1/2-14 NPT", 17.6)); + let d = npt.taper_drill().unwrap(); + assert!((d.exact - (0.77843 - 0.8 / 14.0 - 0.5337 / 16.0) * 25.4).abs() < 2e-3, "{d:?}"); + assert_eq!(rc.profile_degrees(), 55.0); + assert_eq!(npt.profile_degrees(), 60.0); + assert!(parse_tapped_thread("R 1/2").is_none(), "an external taper thread is no hole's"); + for untabulated in ["Rc 5", "Rc 6", "4-8 NPT", "12 NPT"] { + assert!(parse_tapped_thread(untabulated).is_none(), "{untabulated}"); + assert!(untabulated_taper_tap(untabulated).is_some_and(|e| e.contains("no tap drill is tabulated")), "{untabulated}"); + } + assert!(untabulated_taper_tap("Rc 1/2").is_none() && untabulated_taper_tap("M8").is_none()); + // Each tabulated drill lies within a pitch of the standard's minor where the thread ends. + for family in [TappedThreadFamily::Rc, TappedThreadFamily::Npt] { + for s in tapped_thread_sizes(family) { + let d = s.taper_drill().unwrap(); + assert!((d.diameter - d.exact).abs() < s.pitch, "{}: {d:?}", s.designation); + } + } + } + + /// A tapped hole may be drilled from the standard minor diameter (or the tap maker's drill + /// where it lies below, Rc and Rp) up to 5% over the tap maker's drill. + #[test] + fn a_tapped_hole_accepts_drills_from_its_minor_to_five_percent_over() { + let m8 = parse_tapped_thread("M8").unwrap(); + let (lo, hi) = m8.drill_range(); + assert!((lo - (8.0 - 1.082532 * 1.25)).abs() < 1e-5 && (hi - 6.8 * 1.05).abs() < 1e-9, "{lo} {hi}"); + for ok in [6.8, 6.75, 6.648, 7.14] { + assert!(m8.check_drill(ok).is_ok(), "{ok}"); + } + assert!(m8.check_drill(6.5).unwrap_err().contains("the tap cannot cut")); + let e = m8.check_drill(7.2).unwrap_err(); + assert!(e.contains("from 6.647 to 7.14 mm") && e.contains("too little of the thread"), "{e}"); + let rc = parse_tapped_thread("Rc 1/2").unwrap(); + assert_eq!(rc.drill_range().0, 17.6, "a taper's drill lies under its minor at the end"); + assert!(rc.check_drill(17.6).is_ok() && rc.check_drill(17.5).is_err()); + let rp = parse_tapped_thread("Rp 1/2").unwrap(); + assert_eq!(rp.drill_range().0, 18.5); + for family in [ + TappedThreadFamily::Metric, + TappedThreadFamily::Unc, + TappedThreadFamily::Unf, + TappedThreadFamily::G, + TappedThreadFamily::Rp, + TappedThreadFamily::Rc, + TappedThreadFamily::Npt, + ] { + for s in tapped_thread_sizes(family) { + assert!(s.check_drill(s.tap_drill).is_ok(), "{}", s.designation); + assert!(s.minor_diameter() < s.major_diameter && s.minor_diameter() > 0.5 * s.major_diameter, "{}", s.designation); + } + } + } + + /// The metric drills as Yamawa prints them: each between its thread's minimum (basic) minor + /// diameter and the major. + #[test] + fn metric_drills_lie_between_the_minor_and_the_major() { + for &(d, p, drill) in METRIC_DRILLS { + let minor = d - 1.25 * 3f64.sqrt() / 2.0 * p; + assert!(drill >= minor - 1.5e-3 && drill < d, "M{d}x{p}: {drill}"); + } + assert_eq!(metric_tap_drill(8.0, 1.25), 6.8); + assert_eq!(metric_tap_drill(8.5, 1.0), 7.5, "a custom size: the major less the pitch"); + } + #[test] fn tapped_catalogue_has_unique_valid_sizes_and_round_trips() { let mut names = std::collections::HashSet::new(); - for family in [TappedThreadFamily::Metric, TappedThreadFamily::Unc, TappedThreadFamily::Unf, TappedThreadFamily::G, TappedThreadFamily::Rp] { + for family in [ + TappedThreadFamily::Metric, + TappedThreadFamily::Unc, + TappedThreadFamily::Unf, + TappedThreadFamily::G, + TappedThreadFamily::Rp, + TappedThreadFamily::Rc, + TappedThreadFamily::Npt, + ] { let sizes = tapped_thread_sizes(family); - if family != TappedThreadFamily::Metric { - assert_eq!(sizes.len(), if matches!(family, TappedThreadFamily::G | TappedThreadFamily::Rp) { 6 } else { 14 }); - } + let count = match family { + TappedThreadFamily::Metric => sizes.len(), + TappedThreadFamily::G | TappedThreadFamily::Rp => 6, + TappedThreadFamily::Rc => RC_DRILLS.len(), + TappedThreadFamily::Npt => NPT_DRILLS.len(), + _ => 14, + }; + assert_eq!(sizes.len(), count, "{family:?}"); for size in sizes { assert!(names.insert(size.designation.clone())); assert_eq!(parse_tapped_thread(&size.designation), Some(size.clone())); @@ -196,11 +705,13 @@ mod tests { #[test] fn tapped_catalogue_preserves_metric_custom_and_rejects_unverified_threads() { - for (name, d, p, drill) in [("M8", 8.0, 1.25, 6.75), ("M8x1", 8.0, 1.0, 7.0), ("M8.5x1", 8.5, 1.0, 7.5)] { + // The tap maker's drill where it tabulates the size (Yamawa p.704: M8 6.8, MF 8 x 1 7.0), + // the major less the pitch for a custom one. + for (name, d, p, drill) in [("M8", 8.0, 1.25, 6.8), ("M8x1", 8.0, 1.0, 7.0), ("M8.5x1", 8.5, 1.0, 7.5), ("M12", 12.0, 1.75, 10.3)] { let size = parse_tapped_thread(name).unwrap(); assert_eq!((size.major_diameter, size.pitch, size.tap_drill), (d, p, drill)); } - for invalid in ["1/4-20 UNF", "#10-32 UNC", "1/4-19 BSP", "Rc1/4", "R1/4", "1/4-18 NPT", "1/4-20", "M8xNaN", "M8x8"] { + for invalid in ["1/4-20 UNF", "#10-32 UNC", "1/4-19 BSP", "Rc 7/8", "R1/4", "1/4-27 NPT", "1/4-20", "M8xNaN", "M8x8"] { assert!(parse_tapped_thread(invalid).is_none(), "{invalid}"); } } diff --git a/crates/doc/src/thread_forms.rs b/crates/doc/src/thread_forms.rs new file mode 100644 index 000000000..d846cf503 --- /dev/null +++ b/crates/doc/src/thread_forms.rs @@ -0,0 +1,790 @@ +//! Thread forms from the standards: each form's basic or design profile, its standard sizes and +//! its designations. docs/threads.md gives the values and where they come from. +//! +//! A groove is the space between the teeth, in an axial half-plane: a polygon in (r, z), r from +//! the axis, z along it, the groove's walls straight flanks (crest and root radii are not +//! modelled, so every groove is a polygon the screw sweep carries exactly). + +use serde::{Deserialize, Serialize}; + +const INCH: f64 = 25.4; + +/// A thread form. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ThreadForm { + /// ISO metric, 60° (ISO 68-1 basic profile, ISO 261/262 sizes): `M10`, `M10x1`. + #[default] + Metric, + /// ISO metric trapezoidal, 30° (ISO 2904 design profile, ISO 2902 sizes): `Tr20x4`. + Trapezoidal, + /// General purpose Acme, 29° (ASME B1.5): `1/2-10 ACME`. + Acme, + /// Metric buttress (saw-tooth), 3°/30° (DIN 513-1): `S20x4`. + Buttress, + /// Buttress inch, 7°/45° (ASME B1.9 basic profile): `2.5-8 BUTT`. + ButtressAsme, + /// The square thread: no current standard defines it, so it is refused. + Square, + /// Parallel pipe thread, 55° (ISO 228-1, the Whitworth form with H = 0.960491 P): `G 1/2`. + Bspp, + /// Parallel internal pipe thread, 55° (ISO 7-1's Rp, the parallel form with H = 0.960491 P at + /// the gauge diameters): `Rp 1/2`, which a taper external `R` thread screws into. + Rp, + /// Taper pipe thread, 55°, taper 1 in 16 (ISO 7-1, H = 0.960237 P): `R 1/2` external, `Rc 1/2` + /// internal. + Bspt, + /// American National Standard taper pipe thread, 60°, taper 1 in 16 (ASME B1.20.1): + /// `1/2-14 NPT`. + Npt, +} + +/// Which way a thread turns. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ThreadHand { + #[default] + Right, + Left, + /// A right- and a left-handed groove crossing on one face (a reversing screw). + Both, +} + +/// Which way the steep (load) flank of a buttress screw's teeth faces along the thread: towards +/// the thread's end (the way its axis points) or its start. A nut cut with the same setting mates. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SteepFlank { + Start, + #[default] + End, +} + +/// Which of the thread's free ends are chamfered (ISO 4753's chamfered end). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ThreadTip { + /// Every end as cut. + #[default] + None, + /// The end the thread starts from, which must be free. + Start, + /// Every free end the thread reaches. + Both, +} + +/// For `skip_serializing_if`: a field at its default is left out of the saved document. +pub fn is_default(t: &T) -> bool { + *t == T::default() +} + +pub fn one_start() -> u32 { + 1 +} + +pub fn is_one_start(n: &u32) -> bool { + *n == 1 +} + +/// A thread's size: nominal (major) diameter, pitch and lead, all in mm. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ThreadSize { + pub form: ThreadForm, + pub major: f64, + pub pitch: f64, + /// starts × pitch. + pub lead: f64, +} + +/// ISO 261/262 coarse pitches: (nominal diameter, pitch). +pub(crate) const ISO_COARSE: &[(f64, f64)] = &[ + (1.6, 0.35), + (2.0, 0.4), + (2.5, 0.45), + (3.0, 0.5), + (4.0, 0.7), + (5.0, 0.8), + (6.0, 1.0), + (8.0, 1.25), + (10.0, 1.5), + (12.0, 1.75), + (14.0, 2.0), + (16.0, 2.0), + (18.0, 2.5), + (20.0, 2.5), + (22.0, 2.5), + (24.0, 3.0), + (27.0, 3.0), + (30.0, 3.5), + (36.0, 4.0), + (42.0, 4.5), + (48.0, 5.0), + (56.0, 5.5), +]; + +/// The ISO 2902 diameter-pitch series' middle pitch per diameter, which ISO 2904 (trapezoidal) +/// and DIN 513-2 (buttress, from 10 mm) share: (nominal diameter, pitch). +const ISO_2902_MEDIUM: &[(f64, f64)] = &[ + (8.0, 1.5), + (9.0, 2.0), + (10.0, 2.0), + (11.0, 2.0), + (12.0, 3.0), + (14.0, 3.0), + (16.0, 4.0), + (18.0, 4.0), + (20.0, 4.0), + (22.0, 5.0), + (24.0, 5.0), + (26.0, 5.0), + (28.0, 5.0), + (30.0, 6.0), + (32.0, 6.0), + (34.0, 6.0), + (36.0, 6.0), + (38.0, 7.0), + (40.0, 7.0), + (42.0, 7.0), + (44.0, 7.0), + (46.0, 8.0), + (48.0, 8.0), + (50.0, 8.0), + (52.0, 8.0), + (55.0, 9.0), + (60.0, 9.0), + (65.0, 10.0), + (70.0, 10.0), + (75.0, 10.0), + (80.0, 10.0), + (85.0, 12.0), + (90.0, 12.0), + (95.0, 12.0), + (100.0, 12.0), + (105.0, 12.0), + (110.0, 12.0), + (115.0, 14.0), + (120.0, 14.0), + (125.0, 14.0), + (130.0, 14.0), +]; + +/// ASME B1.5 general purpose Acme: (nominal diameter, threads per inch), in inches. +const ACME_SIZES: &[(&str, f64, f64)] = &[ + ("1/4", 0.25, 16.0), + ("5/16", 0.3125, 14.0), + ("3/8", 0.375, 12.0), + ("7/16", 0.4375, 12.0), + ("1/2", 0.5, 10.0), + ("5/8", 0.625, 8.0), + ("3/4", 0.75, 6.0), + ("7/8", 0.875, 6.0), + ("1", 1.0, 5.0), + ("1 1/8", 1.125, 5.0), + ("1 1/4", 1.25, 5.0), + ("1 3/8", 1.375, 4.0), + ("1 1/2", 1.5, 4.0), + ("1 3/4", 1.75, 4.0), + ("2", 2.0, 4.0), + ("2 1/4", 2.25, 3.0), + ("2 1/2", 2.5, 3.0), + ("2 3/4", 2.75, 3.0), + ("3", 3.0, 2.0), + ("3 1/2", 3.5, 2.0), + ("4", 4.0, 2.0), + ("4 1/2", 4.5, 2.0), + ("5", 5.0, 2.0), +]; + +/// The radii and widths of a form's groove, external or internal, for one size. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GrooveProfile { + /// The flank angles from the radial direction of the groove's wall towards −z and towards +z. + pub flank_lo: f64, + pub flank_hi: f64, + /// Where the groove's teeth have their crest: the major radius (external) or the minor one + /// (internal), and the tooth's width there. + pub crest_r: f64, + pub crest_flat: f64, + /// The groove's root: the minor radius (external) or the major one (internal). + pub root_r: f64, + /// The basic depth of engagement, for the "cuts next to nothing" check. + pub basic_depth: f64, + /// A nut's groove: its teeth's crests towards the axis. + pub internal: bool, +} + +impl GrooveProfile { + /// The groove's axial width at radius `r`: the pitch less the tooth there. + pub fn width(&self, pitch: f64, r: f64) -> f64 { + // How far `r` is from the crest towards the root (negative past the crest, in the air + // the groove reaches into). + let into = if self.internal { r - self.crest_r } else { self.crest_r - r }; + pitch - self.crest_flat - into * (self.flank_lo.tan() + self.flank_hi.tan()) + } + /// The groove's (−z, +z) extents at radius `r`, its root flat centred on z = 0. + pub fn extents(&self, pitch: f64, r: f64) -> (f64, f64) { + let root = self.width(pitch, self.root_r) / 2.0; + let d = (r - self.root_r).abs(); + (root + d * self.flank_lo.tan(), root + d * self.flank_hi.tan()) + } + /// One turn of the groove over radii `a..b` (between root and crest): 2π∫ r w(r) dr. + pub fn turn_volume(&self, pitch: f64, a: f64, b: f64) -> f64 { + // w(r) = c0 + c1 r, linear in r. + let (w0, w1) = (self.width(pitch, a), self.width(pitch, b)); + if (b - a).abs() < 1e-15 { + return 0.0; + } + let c1 = (w1 - w0) / (b - a); + let c0 = w0 - c1 * a; + let f = |r: f64| c0 * r * r / 2.0 + c1 * r * r * r / 3.0; + 2.0 * std::f64::consts::PI * (f(b) - f(a)) + } +} + +impl ThreadForm { + pub const ALL: [ThreadForm; 10] = [ + ThreadForm::Metric, + ThreadForm::Trapezoidal, + ThreadForm::Acme, + ThreadForm::Buttress, + ThreadForm::ButtressAsme, + ThreadForm::Square, + ThreadForm::Bspp, + ThreadForm::Rp, + ThreadForm::Bspt, + ThreadForm::Npt, + ]; + + pub fn name(self) -> &'static str { + match self { + ThreadForm::Metric => "metric", + ThreadForm::Trapezoidal => "trapezoidal", + ThreadForm::Acme => "acme", + ThreadForm::Buttress => "buttress", + ThreadForm::ButtressAsme => "buttress_asme", + ThreadForm::Square => "square", + ThreadForm::Bspp => "bspp", + ThreadForm::Rp => "rp", + ThreadForm::Bspt => "bspt", + ThreadForm::Npt => "npt", + } + } + + pub fn from_name(s: &str) -> Option { + ThreadForm::ALL.into_iter().find(|f| f.name().eq_ignore_ascii_case(s.trim())) + } + + /// The standard a form's profile and sizes come from. + pub fn standard(self) -> &'static str { + match self { + ThreadForm::Metric => "ISO 68-1, ISO 261", + ThreadForm::Trapezoidal => "ISO 2904, ISO 2902", + ThreadForm::Acme => "ASME B1.5", + ThreadForm::Buttress => "DIN 513-1, DIN 513-2", + ThreadForm::ButtressAsme => "ASME B1.9", + ThreadForm::Square => "none", + ThreadForm::Bspp => "ISO 228-1", + ThreadForm::Rp | ThreadForm::Bspt => "ISO 7-1", + ThreadForm::Npt => "ASME B1.20.1", + } + } + + /// A taper pipe thread (1 in 16 on the diameter). + pub fn is_taper(self) -> bool { + matches!(self, ThreadForm::Bspt | ThreadForm::Npt) + } + + /// The pipe sizes of a pipe-thread form (ISO 228-1's G sizes are ISO 7-1's gauge diameters). + pub fn pipe_sizes(self) -> Vec { + match self { + ThreadForm::Bspp | ThreadForm::Rp | ThreadForm::Bspt => crate::pipe_thread_sizes::iso_7_1().collect(), + ThreadForm::Npt => crate::pipe_thread_sizes::npt().collect(), + _ => Vec::new(), + } + } + + /// The pipe size of major diameter `d` (at its reference plane). + pub fn pipe_size(self, d: f64) -> Option { + self.pipe_sizes().into_iter().find(|s| (s.major - d).abs() < 1e-6) + } + + /// Why a form cannot be cut, if it cannot. + pub fn refused(self) -> Option<&'static str> { + (self == ThreadForm::Square).then_some( + "no current standard defines a square thread (ISO, ASME and DIN have none; Machinery's Handbook gives only historical proportions): use trapezoidal (ISO 2904) or acme (ASME B1.5)", + ) + } + + /// The form a designation's prefix names: `M` metric, `Tr` trapezoidal, `S` buttress, an inch + /// size with `ACME` or `BUTT`. + pub fn of_designation(s: &str) -> Option { + let t = s.trim().to_ascii_uppercase(); + let then_size = |rest: &str| rest.trim_start().starts_with(|c: char| c.is_ascii_digit()); + if t.contains("NPT") { + Some(ThreadForm::Npt) + } else if t.contains("ACME") { + Some(ThreadForm::Acme) + } else if t.contains("BUTT") { + Some(ThreadForm::ButtressAsme) + } else if t.starts_with("TR") { + Some(ThreadForm::Trapezoidal) + } else if t.starts_with('S') { + Some(ThreadForm::Buttress) + } else if t.starts_with('M') { + Some(ThreadForm::Metric) + } else if t.strip_prefix("RP").is_some_and(then_size) { + Some(ThreadForm::Rp) + } else if t.strip_prefix("RC").or_else(|| t.strip_prefix('R')).is_some_and(then_size) { + Some(ThreadForm::Bspt) + } else if t.strip_prefix('G').is_some_and(then_size) { + Some(ThreadForm::Bspp) + } else { + None + } + } + + /// The standard sizes, (nominal diameter, pitch) in mm; none for ASME buttress (its pitch is + /// always given) and the square thread. + pub fn sizes(self) -> Vec<(f64, f64)> { + match self { + ThreadForm::Metric => ISO_COARSE.to_vec(), + ThreadForm::Trapezoidal => ISO_2902_MEDIUM.to_vec(), + ThreadForm::Buttress => ISO_2902_MEDIUM.iter().copied().filter(|(d, _)| *d >= 10.0).collect(), + ThreadForm::Acme => ACME_SIZES.iter().map(|(_, d, n)| (d * INCH, INCH / n)).collect(), + ThreadForm::ButtressAsme | ThreadForm::Square => Vec::new(), + ThreadForm::Bspp | ThreadForm::Rp | ThreadForm::Bspt | ThreadForm::Npt => { + self.pipe_sizes().iter().map(|s| (s.major, s.pitch())).collect() + } + } + } + + /// The standard designations of [`sizes`](Self::sizes), in order. + pub fn designations(self) -> Vec { + self.sizes().into_iter().map(|(d, p)| self.format(d, p, p)).collect() + } + + /// The size a designation names (`starts` starts unless the designation gives its lead). + pub fn parse(self, s: &str, starts: u32) -> Result { + if let Some(why) = self.refused() { + return Err(why.into()); + } + let bad = || format!("unknown {} thread `{s}` ({})", self.name(), self.example()); + if let Some(f) = ThreadForm::of_designation(s) + && f != self + { + return Err(format!("`{s}` is a {} designation, not {}", f.name(), self.name())); + } + if !self.pipe_sizes().is_empty() { + let size = self.pipe_designation(s).ok_or_else(bad)?; + if starts > 1 { + return Err(format!("a pipe thread has one start (`{s}`)")); + } + return Ok(ThreadSize { form: self, major: size.major, pitch: size.pitch(), lead: size.pitch() }); + } + let t = s.trim().to_ascii_uppercase().replace('×', "X").replace(' ', ""); + let n = f64::from(starts.max(1)); + let (major, pitch, lead) = match self { + ThreadForm::Metric => { + let body = t.strip_prefix('M').ok_or_else(bad)?; + // M16xPh3P1.5 (ISO 965-1: lead 3, pitch 1.5), M10x1.5, M10. + match body.split_once('X') { + Some((d, rest)) => { + let d = num(d).ok_or_else(bad)?; + match rest.strip_prefix("PH").and_then(|r| r.split_once('P')) { + Some((l, p)) => (d, num(p).ok_or_else(bad)?, num(l).ok_or_else(bad)?), + None => { + let p = num(rest).ok_or_else(bad)?; + (d, p, p * n) + } + } + } + None => { + let d = num(body).ok_or_else(bad)?; + let p = self.coarse(d).ok_or_else(|| no_coarse_pitch(d).unwrap_or_else(bad))?; + (d, p, p * n) + } + } + } + ThreadForm::Trapezoidal | ThreadForm::Buttress => { + let body = t.strip_prefix(if self == ThreadForm::Trapezoidal { "TR" } else { "S" }).ok_or_else(bad)?; + // Tr40x7, Tr40x14(P7) (ISO 2903: lead 14, pitch 7), Tr40 (the standard pitch). + match body.split_once('X') { + Some((d, rest)) => { + let d = num(d).ok_or_else(bad)?; + match rest.split_once("(P") { + Some((l, p)) => (d, num(p.strip_suffix(')').ok_or_else(bad)?).ok_or_else(bad)?, num(l).ok_or_else(bad)?), + None => { + let p = num(rest).ok_or_else(bad)?; + (d, p, p * n) + } + } + } + None => { + let d = num(body).ok_or_else(bad)?; + let p = self.coarse(d).ok_or_else(|| format!("no standard pitch for a {} mm {} thread: give it", show(d), self.name()))?; + (d, p, p * n) + } + } + } + ThreadForm::Acme | ThreadForm::ButtressAsme => { + // 1/2-10 ACME, 1 1/4-5, 2.5-8 BUTT (a class such as -2G or -2A is a tolerance, ignored). + let body = t.trim_end_matches("ACME").trim_end_matches("PUSH-BUTT").trim_end_matches("PULL-BUTT").trim_end_matches("BUTT"); + let body = body.trim_end_matches('-'); + let mut parts = body.split('-'); + let d = parts.next().and_then(inches).ok_or_else(bad)?; + let tpi = parts.next().and_then(num).ok_or_else(bad)?; + if let Some(rest) = parts.next() + && !(rest.len() == 2 && rest.ends_with(['G', 'C', 'A', 'B'])) + { + return Err(bad()); + } + let p = INCH / tpi; + (d * INCH, p, p * n) + } + ThreadForm::Square | ThreadForm::Bspp | ThreadForm::Rp | ThreadForm::Bspt | ThreadForm::Npt => return Err(bad()), + }; + if !(major.is_finite() && pitch.is_finite() && lead.is_finite() && major > 0.0 && pitch > 0.0 && pitch < major) { + return Err(bad()); + } + let k = lead / pitch; + if !(k >= 1.0 - 1e-9 && (k - k.round()).abs() < 1e-6 && k.round() <= 8.0) { + return Err(format!("the lead of `{s}` is not 1 to 8 times its pitch")); + } + Ok(ThreadSize { form: self, major, pitch, lead }) + } + + fn example(self) -> &'static str { + match self { + ThreadForm::Metric => "like M8 or M8x1", + ThreadForm::Trapezoidal => "like Tr20x4 or Tr40x14(P7)", + ThreadForm::Acme => "like 1/2-10 ACME", + ThreadForm::Buttress => "like S20x4 or S40x14(P7)", + ThreadForm::ButtressAsme => "like 2.5-8 BUTT", + ThreadForm::Square => "no standard", + ThreadForm::Bspp => "like G 1/2 (ISO 228-1, 1/16 to 6)", + ThreadForm::Rp => "like Rp 1/2, internal (ISO 7-1, 1/16 to 6)", + ThreadForm::Bspt => "like R 1/2 external or Rc 1/2 internal (ISO 7-1, 1/16 to 6)", + ThreadForm::Npt => "like 1/2-14 NPT (1/16 to 12)", + } + } + + /// The pipe size a pipe-thread designation names: `G 1/2` (a class A or B after it is a + /// tolerance, ignored), `Rp 1/2`, `R 1 1/4`, `Rc 1/2`, `1/2-14 NPT` or `1/2 NPT`. + fn pipe_designation(self, s: &str) -> Option { + let t = s.trim().to_ascii_uppercase().replace(' ', ""); + let same = |n: &str, given: &str| n.replace(' ', "") == given; + let find = |given: &str| self.pipe_sizes().into_iter().find(|z| same(z.nominal, given)); + match self { + ThreadForm::Bspp => { + let body = t.strip_prefix('G')?; + find(body.strip_suffix(['A', 'B']).unwrap_or(body)) + } + ThreadForm::Rp => find(t.strip_prefix("RP")?), + ThreadForm::Bspt => find(t.strip_prefix("RC").or_else(|| t.strip_prefix('R'))?), + ThreadForm::Npt => { + let body = t.strip_suffix("NPT")?; + let (nominal, tpi) = match body.split_once('-') { + Some((n, tpi)) => (n, Some(num(tpi)?)), + None => (body, None), + }; + find(nominal).filter(|z| tpi.is_none_or(|n| (n - z.tpi).abs() < 1e-9)) + } + _ => None, + } + } + + /// An ISO 7-1 designation on an internal thread: `Rc` (the taper internal thread), else `R`. + pub fn pipe_internal(designation: &str) -> bool { + designation.trim().to_ascii_uppercase().starts_with("RC") + } + + /// The standard pitch of a diameter in the form's table. + fn coarse(self, d: f64) -> Option { + self.sizes().into_iter().find(|(n, _)| (n - d).abs() < 1e-9).map(|(_, p)| p) + } + + /// A size's designation, in the form its standard writes it. + pub fn format(self, d: f64, p: f64, lead: f64) -> String { + let multi = (lead - p).abs() > 1e-9; + match self { + ThreadForm::Metric => { + if multi { + format!("M{}xPh{}P{}", show(d), show(lead), show(p)) + } else if self.coarse(d).is_some_and(|q| (q - p).abs() < 1e-9) { + format!("M{}", show(d)) + } else { + format!("M{}x{}", show(d), show(p)) + } + } + ThreadForm::Trapezoidal | ThreadForm::Buttress => { + let pre = if self == ThreadForm::Trapezoidal { "Tr" } else { "S" }; + if multi { format!("{pre}{}x{}(P{})", show(d), show(lead), show(p)) } else { format!("{pre}{}x{}", show(d), show(p)) } + } + ThreadForm::Acme | ThreadForm::ButtressAsme => { + // Acme sizes by their fractions (ASME B1.5's table), buttress in decimal inches. + let di = d / INCH; + let named = ACME_SIZES.iter().find(|(_, x, _)| self == ThreadForm::Acme && (x - di).abs() < 1e-9); + let name = named.map(|(n, _, _)| n.to_string()).unwrap_or_else(|| show(di)); + let tpi = show(INCH / p); + format!("{name}-{tpi} {}", if self == ThreadForm::Acme { "ACME" } else { "BUTT" }) + } + ThreadForm::Square => format!("{}x{}", show(d), show(p)), + ThreadForm::Bspp | ThreadForm::Rp | ThreadForm::Bspt | ThreadForm::Npt => match self.pipe_size(d) { + Some(z) if self == ThreadForm::Npt => format!("{}-{} NPT", z.nominal, show(z.tpi)), + Some(z) => { + let pre = match self { + ThreadForm::Bspp => "G", + ThreadForm::Rp => "Rp", + _ => "R", + }; + format!("{pre} {}", z.nominal) + } + None => format!("{}x{}", show(d), show(p)), + }, + } + } + + /// The minor diameter a hole for this size is drilled to: the tap maker's drill for metric + /// ([`crate::metric_tap_drill`]), the internal thread's minor diameter for the others. + pub fn drill(self, d: f64, p: f64) -> f64 { + match self { + ThreadForm::Metric => crate::metric_tap_drill(d, p), + _ => 2.0 * self.groove(d, p, true).crest_r, + } + } + + /// The standard size a cylinder of this diameter takes: a shaft is the major diameter, a hole + /// its nominal diameter, else the drill ([`fit_with`](Self::fit_with)). None when no size is within 15% (or the form has no size table). + pub fn fit(self, diameter: f64, internal: bool) -> Option<(f64, f64)> { + self.fit_with(diameter, internal, false) + } + + /// [`fit`](Self::fit) as designs saved before the nominal rule had it (`old_rule`: a hole is + /// matched by the tap drill alone, so a 12 mm hole is M14's) or as it is now: a hole as wide + /// as a size's nominal diameter (within 1% and 0.03 mm) is that size, a 12 mm hole is M12, + /// and only a hole near no nominal diameter is matched by tap drill. + pub fn fit_with(self, diameter: f64, internal: bool, old_rule: bool) -> Option<(f64, f64)> { + if internal && !old_rule { + let near = |n: f64| (n - diameter).abs() <= 0.01 * diameter + 0.03; + if let Some((n, p)) = self.sizes().into_iter().find(|(n, _)| near(*n)) { + return Some((n, p)); + } + } + self.sizes() + .into_iter() + .map(|(n, p)| (n, p, if internal { self.drill(n, p) } else { n })) + .min_by(|a, b| (a.2 - diameter).abs().total_cmp(&(b.2 - diameter).abs())) + .filter(|(_, _, want)| (want - diameter).abs() <= 0.15 * diameter) + .map(|(n, p, _)| (n, p)) + } + + /// The groove of size (d, P): external (between a screw's teeth) or internal (a nut's). + /// `flank_lo`/`flank_hi` are for a buttress with its steep flank towards the end (+z); the + /// caller swaps them for [`SteepFlank::Start`]. + pub fn groove(self, d: f64, p: f64, internal: bool) -> GrooveProfile { + let deg = |a: f64| a.to_radians(); + let half = |a: f64| (deg(a), deg(a)); + // (flanks, tooth crest flat, basic depth, external minor radius, internal minor radius, + // internal major radius) + let (fl, flat, depth, r3, r1, r4) = match self { + ThreadForm::Metric | ThreadForm::Square => { + // ISO 68-1: H = P sqrt3/2, basic depth 5H/8, flats P/8 at the major and P/4 at + // the minor diameter. + let h = p * 3f64.sqrt() / 2.0; + let r_minor = d / 2.0 - 5.0 * h / 8.0; + let flat = if internal { p / 4.0 } else { p / 8.0 }; + (half(30.0), flat, 5.0 * h / 8.0, r_minor, r_minor, d / 2.0) + } + ThreadForm::Trapezoidal => { + // ISO 2904: 30°, H1 = P/2, flats P/2 - P/2 tan 15° (0.366 P) at both crests, + // clearance ac on the external minor and internal major diameters. + let ac = if p <= 1.5 { + 0.15 + } else if p <= 5.0 { + 0.25 + } else if p <= 12.0 { + 0.5 + } else { + 1.0 + }; + let flat = p / 2.0 - p / 2.0 * deg(15.0).tan(); + (half(15.0), flat, p / 2.0, d / 2.0 - p / 2.0 - ac, d / 2.0 - p / 2.0, d / 2.0 + ac) + } + ThreadForm::Acme => { + // ASME B1.5 general purpose: 29°, h = P/2, flat 0.3707 P, the external minor + // 0.020" under the basic minor (0.010" finer than 10 per inch), the internal + // major as far over the basic major. + let a = if p >= INCH / 10.0 - 1e-9 { 0.020 * INCH } else { 0.010 * INCH }; + let flat = p / 2.0 - p / 2.0 * deg(14.5).tan(); + (half(14.5), flat, p / 2.0, d / 2.0 - p / 2.0 - a / 2.0, d / 2.0 - p / 2.0, d / 2.0 + a / 2.0) + } + ThreadForm::Buttress => { + // DIN 513-1: 3° load flank, 30° clearance flank, H1 = 0.75 P, flats w = 0.26384 P, + // the external minor h3 = 0.86777 P deep (clearance ac = 0.11777 P), the internal + // thread from D1 = d - 1.5 P to D = d. + let (t3, t30) = (deg(3.0).tan(), deg(30.0).tan()); + let flat = (p - 0.75 * p * (t3 + t30)) / 2.0; + ((deg(3.0), deg(30.0)), flat, 0.75 * p, d / 2.0 - 0.86777 * p, d / 2.0 - 0.75 * p, d / 2.0) + } + ThreadForm::ButtressAsme => { + // ASME B1.9 basic profile: 7° load flank, 45° clearance flank, h = 0.6 P, flats + // (P - 0.6 P (tan 7° + tan 45°))/2 = 0.16316 P, no allowances. + let flat = (p - 0.6 * p * (deg(7.0).tan() + deg(45.0).tan())) / 2.0; + ((deg(7.0), deg(45.0)), flat, 0.6 * p, d / 2.0 - 0.6 * p, d / 2.0 - 0.6 * p, d / 2.0) + } + ThreadForm::Bspp | ThreadForm::Rp | ThreadForm::Bspt | ThreadForm::Npt => { + // ISO 228-1 / ISO 7-1: 55°, h = 0.640327 P of the triangle H = 0.960491 P + // (parallel) or 0.960237 P (taper), rounded equally at crest and root (r = + // 0.137329 P / 0.137278 P), modelled as flats where the rounds would be. ASME + // B1.20.1: 60°, h = 0.8 P of H = 0.866025 P, truncated equally at crest and root + // (the minimum, 0.033 P). The flanks' bisector is square to the axis. + let (half_angle, big_h, h) = match self { + ThreadForm::Bspp | ThreadForm::Rp => (27.5, 0.960491 * p, 0.640327 * p), + ThreadForm::Bspt => (27.5, 0.960237 * p, 0.640327 * p), + _ => (30.0, 0.866025 * p, crate::pipe_thread_sizes::NPT_HEIGHT * p), + }; + let flat = (big_h - h) * deg(half_angle).tan(); + (half(half_angle), flat, h, d / 2.0 - h, d / 2.0 - h, d / 2.0) + } + }; + // The steep flank faces +z on the screw's teeth: the external groove's −z wall, the + // internal groove's +z wall (the nut's teeth face the other way). + let (lo, hi) = if internal { (fl.1, fl.0) } else { fl }; + if internal { + GrooveProfile { flank_lo: lo, flank_hi: hi, crest_r: r1, crest_flat: flat, root_r: r4, basic_depth: depth, internal } + } else { + GrooveProfile { flank_lo: lo, flank_hi: hi, crest_r: d / 2.0, crest_flat: flat, root_r: r3, basic_depth: depth, internal } + } + } +} + +/// A number; fractions allowed (`1/2`). +fn num(s: &str) -> Option { + let s = s.trim(); + let v = match s.split_once('/') { + Some((a, b)) => a.parse::().ok()? / b.parse::().ok()?, + None => s.parse::().ok()?, + }; + v.is_finite().then_some(v) +} + +/// An inch size: `1`, `0.75`, `3/4`, `1 1/4` (spaces already gone: `11/4` is read as 1 1/4 only +/// from the table's names). +fn inches(s: &str) -> Option { + if let Some((_, d, _)) = ACME_SIZES.iter().find(|(n, _, _)| n.replace(' ', "") == s) { + return Some(*d); + } + num(s) +} + +/// The refusal for a plain `M` with no ISO coarse pitch: the two coarsest fine pitches to +/// give that suit the diameter. `None` for a diameter no metric thread has. +pub fn no_coarse_pitch(d: f64) -> Option { + const PITCHES: [f64; 9] = [2.0, 1.5, 1.25, 1.0, 0.75, 0.5, 0.35, 0.25, 0.2]; + if !(d.is_finite() && d > 0.2 && d <= 1e4) { + return None; + } + let first = PITCHES.iter().position(|p| *p <= 0.12 * d).unwrap_or(PITCHES.len() - 1); + let pitches: Vec = PITCHES.iter().skip(first).take(2).filter(|p| **p < d).map(|p| format!("M{}x{}", show(d), show(*p))).collect(); + (!pitches.is_empty()).then(|| format!("M{} has no coarse ISO pitch: give one, e.g. {}", show(d), pitches.join(" or "))) +} + +fn show(v: f64) -> String { + let s = format!("{v:.6}"); + s.trim_end_matches('0').trim_end_matches('.').to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pipe-thread designations read to their table's size and write back as the standards write + /// them; a size or a threads-per-inch the table lacks is refused. + #[test] + fn pipe_designations_read_and_write_back() { + for (s, form, major, tpi, written) in [ + ("G 1/2", ThreadForm::Bspp, 20.955, 14.0, "G 1/2"), + ("G1/2A", ThreadForm::Bspp, 20.955, 14.0, "G 1/2"), + ("Rp 1/2", ThreadForm::Rp, 20.955, 14.0, "Rp 1/2"), + ("RP3/4", ThreadForm::Rp, 26.441, 14.0, "Rp 3/4"), + ("R 1 1/4", ThreadForm::Bspt, 41.910, 11.0, "R 1 1/4"), + ("Rc1/2", ThreadForm::Bspt, 20.955, 14.0, "R 1/2"), + ("1/2-14 NPT", ThreadForm::Npt, (0.77843 + 0.8 / 14.0) * INCH, 14.0, "1/2-14 NPT"), + ("1 NPT", ThreadForm::Npt, (1.21363 + 0.4 / 16.0 + 0.8 / 11.5) * INCH, 11.5, "1-11.5 NPT"), + ] { + assert_eq!(ThreadForm::of_designation(s), Some(form), "{s}"); + let z = form.parse(s, 1).unwrap(); + assert!((z.major - major).abs() < 1e-9 && (z.pitch - INCH / tpi).abs() < 1e-12, "{s}"); + assert_eq!(form.format(z.major, z.pitch, z.lead), written); + } + for bad in ["G 7/8", "R 1/2x", "1/2-18 NPT", "Rp 7/8"] { + let parsed = ThreadForm::of_designation(bad).map(|f| f.parse(bad, 1)); + assert!(!matches!(parsed, Some(Ok(_))), "{bad}"); + } + assert!(ThreadForm::Npt.parse("1/2 NPT", 2).is_err()); + assert!(ThreadForm::Bspt.is_taper() && ThreadForm::Npt.is_taper() && !ThreadForm::Bspp.is_taper()); + } + + #[test] + fn designations_read_and_write_back() { + for (form, s, d, p, l) in [ + (ThreadForm::Metric, "M10", 10.0, 1.5, 1.5), + (ThreadForm::Metric, "M10x1", 10.0, 1.0, 1.0), + (ThreadForm::Metric, "M16xPh3P1.5", 16.0, 1.5, 3.0), + (ThreadForm::Trapezoidal, "Tr20x4", 20.0, 4.0, 4.0), + (ThreadForm::Trapezoidal, "Tr40x14(P7)", 40.0, 7.0, 14.0), + (ThreadForm::Buttress, "S40x7", 40.0, 7.0, 7.0), + (ThreadForm::Acme, "1/2-10 ACME", 12.7, 2.54, 2.54), + (ThreadForm::Acme, "1 1/4-5 ACME", 31.75, 5.08, 5.08), + (ThreadForm::ButtressAsme, "2.5-8 BUTT", 63.5, 3.175, 3.175), + ] { + let z = form.parse(s, 1).unwrap(); + assert!((z.major - d).abs() < 1e-9 && (z.pitch - p).abs() < 1e-9 && (z.lead - l).abs() < 1e-9, "{s}: {z:?}"); + assert_eq!(form.format(z.major, z.pitch, z.lead), s); + assert_eq!(ThreadForm::of_designation(s), Some(form), "{s}"); + } + assert!(ThreadForm::Trapezoidal.parse("M10", 1).is_err()); + assert!(ThreadForm::Square.parse("20x4", 1).is_err()); + assert_eq!(ThreadForm::Trapezoidal.parse("Tr20x4", 2).unwrap().lead, 8.0); + } + + /// The design diameters against the standards' tables: ISO 2904 (Tr10x2: d3 7.5, D4 10.5, D1 8; + /// Tr40x7: 32, 41, 33; Tr100x20: 78, 102, 80), DIN 513 (S10x2: d3 6.529, D1 7; S40x7: 27.851, + /// 29.5), ISO 68-1 (M10: d1 = 8.376). + #[test] + fn design_diameters_match_the_tables() { + let ext = |f: ThreadForm, d: f64, p: f64| 2.0 * f.groove(d, p, false).root_r; + let int = |f: ThreadForm, d: f64, p: f64| (2.0 * f.groove(d, p, true).crest_r, 2.0 * f.groove(d, p, true).root_r); + let tr = ThreadForm::Trapezoidal; + for (d, p, d3, d4, d1) in [(10.0, 2.0, 7.5, 10.5, 8.0), (40.0, 7.0, 32.0, 41.0, 33.0), (100.0, 20.0, 78.0, 102.0, 80.0)] { + assert!((ext(tr, d, p) - d3).abs() < 1e-9 && (int(tr, d, p).0 - d1).abs() < 1e-9 && (int(tr, d, p).1 - d4).abs() < 1e-9); + } + let s = ThreadForm::Buttress; + for (d, p, d3, d1) in [(10.0, 2.0, 6.529, 7.0), (40.0, 7.0, 27.851, 29.5)] { + assert!((ext(s, d, p) - d3).abs() < 5e-4 && (int(s, d, p).0 - d1).abs() < 1e-9, "S{d}x{p}"); + } + assert!((ext(ThreadForm::Metric, 10.0, 1.5) - 8.376).abs() < 5e-4); + // DIN 513 flat w = 0.26384 P. + assert!((s.groove(10.0, 2.0, false).crest_flat - 0.26384 * 2.0).abs() < 1e-5); + // ASME B1.9 flat 0.16316 P, B1.5 flat 0.3707 P. + assert!((ThreadForm::ButtressAsme.groove(50.0, 4.0, false).crest_flat - 0.16316 * 4.0).abs() < 1e-4); + assert!((ThreadForm::Acme.groove(25.4, 5.08, false).crest_flat - 0.3707 * 5.08).abs() < 1e-3); + } + + /// The basic profiles mesh: at the pitch line (half the basic depth in from the crest) groove + /// and tooth are each half a pitch (symmetric forms), and an external tooth fits the internal + /// groove of the same size. + #[test] + fn grooves_are_half_a_pitch_at_the_pitch_line() { + for f in [ThreadForm::Metric, ThreadForm::Trapezoidal, ThreadForm::Acme] { + let (d, p) = (20.0, 2.5); + let g = f.groove(d, p, false); + let r = d / 2.0 + - match f { + ThreadForm::Metric => 3.0 * p * 3f64.sqrt() / 16.0, + _ => p / 4.0, + }; + assert!((g.width(p, r) - p / 2.0).abs() < 1e-9, "{f:?}"); + } + } +} diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index 025e436f1..26bd9441f 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -5,7 +5,7 @@ //! traits here carry the walks through the types the fields have: options, lists, arrays, planes //! and construction definitions. -pub(crate) use solidcraft_geom::Vec3; +pub(crate) use solidcore_record::Vec3; pub(crate) use crate::ProfileSel; use crate::construct::{AxisDef, GeoRef, PointDef}; @@ -50,9 +50,11 @@ impl Walk for solidcraft_sketch::PatternAlignment {} impl Walk for solidcraft_kernel::StepNode {} impl Walk for crate::document::Operation {} impl Walk for solidcraft_kernel::Continuity {} +impl Walk for solidcraft_kernel::DraftCorner {} impl Walk for crate::document::Direction {} impl Walk for crate::document::FilletFit {} impl Walk for crate::document::FilletCorner {} +impl Walk for crate::document::FilletTurn {} impl Walk for crate::document::MeshData {} impl Walk for crate::document::RevolveConvention {} impl Walk for crate::document::RailFit {} @@ -62,6 +64,12 @@ impl Walk for crate::document::ExtendMode {} impl Walk for crate::document::RuledMode {} impl Walk for crate::document::RuledCorners {} impl Walk for crate::document::ExtrudeConvention {} +impl Walk for crate::thread_forms::ThreadForm {} +impl Walk for crate::thread_forms::ThreadHand {} +impl Walk for crate::thread_forms::ThreadTip {} +impl Walk for crate::thread_forms::SteepFlank {} +// An Align frame's joint origin: picks in its component's coordinates, found by their names. +impl Walk for Box {} /// A reference walks itself: a sketch, a feature or a body. macro_rules! reference { @@ -335,6 +343,7 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + PlaneRef::Tangent { angle: Some(angle), .. } => return f(("Angle", angle, Kind::Angle, ExprRole::Input)), // A plane seen from behind keeps its base's expressions (a sketch made with // `flip` on an offset plane did not follow the offset's parameter). PlaneRef::Flipped { base, .. } | PlaneRef::ThroughPoint { base, .. } => p = base, @@ -361,6 +370,7 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + PlaneRef::Tangent { angle: Some(angle), .. } => return f(("Angle", angle, Kind::Angle, ExprRole::Input)), // A plane seen from behind keeps its base's expressions (a sketch made with // `flip` on an offset plane did not follow the offset's parameter). PlaneRef::Flipped { base, .. } | PlaneRef::ThroughPoint { base, .. } => p = base, @@ -406,7 +416,7 @@ impl PlaneRef { g.walk_feature_refs(f, depth + 1); } } - Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::Perpendicular { plane: a, line: b } => { + Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::AxisPoint { axis: a, point: b } | Self::Perpendicular { plane: a, line: b } => { a.walk_feature_refs(f, depth + 1); b.walk_feature_refs(f, depth + 1); } @@ -415,7 +425,13 @@ impl PlaneRef { b.walk_feature_refs(f, depth + 1); c.walk_feature_refs(f, depth + 1); } - Self::Tangent { face, .. } | Self::AlongPath { path: face, .. } => face.walk_feature_refs(f, depth + 1), + Self::Tangent { face, reference, .. } => { + face.walk_feature_refs(f, depth + 1); + if let Some(r) = reference { + r.walk_feature_refs(f, depth + 1); + } + } + Self::AlongPath { path, .. } => path.walk_feature_refs(f, depth + 1), Self::Origin { .. } | Self::Custom { .. } | Self::Placed { .. } | Self::Face { .. } => {} } } @@ -437,7 +453,7 @@ impl PlaneRef { g.walk_feature_refs_mut(f, depth + 1); } } - Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::Perpendicular { plane: a, line: b } => { + Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::AxisPoint { axis: a, point: b } | Self::Perpendicular { plane: a, line: b } => { a.walk_feature_refs_mut(f, depth + 1); b.walk_feature_refs_mut(f, depth + 1); } @@ -446,7 +462,13 @@ impl PlaneRef { b.walk_feature_refs_mut(f, depth + 1); c.walk_feature_refs_mut(f, depth + 1); } - Self::Tangent { face, .. } | Self::AlongPath { path: face, .. } => face.walk_feature_refs_mut(f, depth + 1), + Self::Tangent { face, reference, .. } => { + face.walk_feature_refs_mut(f, depth + 1); + if let Some(r) = reference { + r.walk_feature_refs_mut(f, depth + 1); + } + } + Self::AlongPath { path, .. } => path.walk_feature_refs_mut(f, depth + 1), Self::Origin { .. } | Self::Custom { .. } | Self::Placed { .. } | Self::Face { .. } => {} } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4239cc0ae..604fe4be1 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,6 +17,10 @@ raytrace-cpu = ["solidcraft-render/raytrace-cpu"] # `src/schema/record.rs`), for checking a new contract against the whole test suite. param-audit = [] solver-profiling = ["solidcraft-sketch/solver-profiling"] +# Compile the profiler in (solidcraft-profile/enabled): every app turns it on by default, so any +# build can be profiled; it records only once switched on (SOLIDCRAFT_PROFILE=1, the CLI's +# --profile, the app's preference, diagnostics.profile). +profile = ["solidcraft-profile/enabled"] [[example]] name = "sketch_analysis_bench" @@ -31,12 +35,15 @@ name = "sketch_target_bench" required-features = ["solver-profiling"] [dependencies] +solidcore-record = { workspace = true } solidcraft-geom = { workspace = true } solidcraft-sketch = { workspace = true } solidcraft-kernel = { workspace = true } solidcraft-doc = { workspace = true } solidcraft-io = { workspace = true } solidcraft-render = { workspace = true } +solidcraft-profile = { workspace = true } +# reference pictures for inspect.compare_picture (PNG and JPEG decode, PNG encode) image = { workspace = true, features = ["jpeg"] } serde = { workspace = true } serde_json = { workspace = true } @@ -48,6 +55,7 @@ log = { workspace = true } web-time = { workspace = true } [dev-dependencies] +solidcraft-profile = { workspace = true, features = ["enabled"] } # Model-cache tests also run in a source tarball build (no git commit). solidcraft-io = { workspace = true, features = ["trust-unknown-source"] } # Normal CI exercises profiling assertions without enabling the production feature. diff --git a/crates/engine/examples/sketch_analysis_bench.rs b/crates/engine/examples/sketch_analysis_bench.rs index e7a10daaa..6c29b7194 100644 --- a/crates/engine/examples/sketch_analysis_bench.rs +++ b/crates/engine/examples/sketch_analysis_bench.rs @@ -3,8 +3,8 @@ use std::{error::Error, io::Write, path::PathBuf, sync::Arc, time::Instant}; use serde_json::{Value, json}; +use solidcore_record::Vec2; use solidcraft_engine::Session; -use solidcraft_geom::Vec2; use solidcraft_sketch::{ConstraintKind, Sketch, profiling::capture}; type Result = std::result::Result>; diff --git a/crates/engine/examples/sketch_drag_bench.rs b/crates/engine/examples/sketch_drag_bench.rs index df15c6975..fff6c4d62 100644 --- a/crates/engine/examples/sketch_drag_bench.rs +++ b/crates/engine/examples/sketch_drag_bench.rs @@ -2,8 +2,8 @@ use std::{error::Error, io::Write, path::PathBuf, sync::Arc, time::Instant}; use serde_json::{Value, json}; +use solidcore_record::Vec2; use solidcraft_engine::Session; -use solidcraft_geom::Vec2; use solidcraft_sketch::{Analysis, ConstraintKind, Hold, Sketch, profiling::capture, solve_with}; type Result = std::result::Result>; diff --git a/crates/engine/examples/sketch_target_bench.rs b/crates/engine/examples/sketch_target_bench.rs index b07f66126..bc2a210de 100644 --- a/crates/engine/examples/sketch_target_bench.rs +++ b/crates/engine/examples/sketch_target_bench.rs @@ -3,7 +3,7 @@ mod four_bar; use four_bar::Result; use serde_json::json; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_sketch::profiling::capture; use std::{io::Write, time::Instant}; diff --git a/crates/engine/src/agent_setup.rs b/crates/engine/src/agent_setup.rs index 8dbed63ad..3f951874a 100644 --- a/crates/engine/src/agent_setup.rs +++ b/crates/engine/src/agent_setup.rs @@ -1,9 +1,9 @@ //! `solidcraft-cli mcp setup` and Help > Connect AI assistants: add a `solidcraft` MCP server entry //! to the AI clients installed on this machine, using the `solidcraft-cli` path given. //! -//! The clients' own files are edited in place, not rewritten: only the `solidcraft` entries change, -//! every other byte (other servers, other settings, comments, key order) stays as it was. The file -//! is copied to `.bak` first. A file that cannot be read as JSON (with comments) or TOML is +//! Only the `solidcraft` entries change; every other byte (other servers, other settings, comments, +//! key order) stays as it was. Updates replace the file atomically, keeping the previous version +//! as `.bak`. A file that cannot be read as JSON (with comments) or TOML is //! left alone, and so is an entry the user changed (its command is not a SolidCraft CLI, or its //! arguments differ); an entry that only has an old path to the CLI is updated. //! A client counts as installed when its configuration folder exists; no client program is run. @@ -606,11 +606,7 @@ fn toml_to_json(t: &toml_edit::Table) -> Value { /// One client's outcome, a line of the report. fn configure_file(t: &Target, exe: &str, live: bool, dry_run: bool, mode: Mode) -> Result<(String, Vec<(&'static str, Change)>), String> { let fail = |e: String| format!("{}: {e}; left unchanged", t.file.display()); - let existing = match std::fs::read_to_string(&t.file) { - Ok(s) => Some(s), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, - Err(e) => return Err(format!("{}: {e}", t.file.display())), - }; + let existing = read_config(&t.file).map_err(|e| format!("{}: {e}", t.file.display()))?; let mut text = existing.clone().unwrap_or_default(); let changes = if t.shape == Shape::Codex { edit_toml(&mut text, exe, live, mode) } else { edit_json(&mut text, t.shape, exe, live, mode) }.map_err(fail)?; @@ -633,20 +629,30 @@ fn configure_file(t: &Target, exe: &str, live: bool, dry_run: bool, mode: Mode) if !changed { return done(said); } - if existing.is_some() { - let mut bak = t.file.clone().into_os_string(); - bak.push(".bak"); - // The first backup is the user's original: later runs keep it. - if !Path::new(&bak).exists() { - std::fs::copy(&t.file, &bak).map_err(|e| format!("{}: cannot back up: {e}", t.file.display()))?; - } - } else if let Some(dir) = t.file.parent() { - std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; - } - std::fs::write(&t.file, text).map_err(|e| format!("{}: {e}", t.file.display()))?; + write_config(&t.file, existing.as_deref(), &text).map_err(|e| format!("{}: {e}", t.file.display()))?; done(format!("{said} ({})", t.file.display())) } +fn read_config(path: &Path) -> std::io::Result> { + match std::fs::read_to_string(path) { + Ok(text) => Ok(Some(text)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// Refuse a stale edit before writing. Other clients do not share a lock with SolidCraft, so +/// this narrows the race with their writes; it cannot exclude a write after the comparison. +fn write_config(path: &Path, expected: Option<&str>, text: &str) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + if read_config(path)?.as_deref() != expected { + return Err(std::io::Error::other("configuration changed during setup; left unchanged, try again")); + } + solidcraft_io::safe_write::write_atomic(path, text.as_bytes(), true) +} + /// Set up every detected client (or `--client NAME`; flags `--dry-run`, `--live`) for the /// `solidcraft-cli` at `exe`. Returns the result lines, one per client file, and whether every /// client succeeded. @@ -842,6 +848,96 @@ mod tests { assert!(toml.contains("[mcp_servers.other]") && !toml.contains("solidcraft"), "{toml}"); } + fn config_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-agent-config-{label}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn configuration_backup_tracks_the_file_before_each_change() { + let dir = config_dir("backup"); + let target = Target { client: "claude-code", file: dir.join("config.json"), shape: Shape::ClaudeCode }; + let backup = dir.join("config.json.bak"); + let original = "{\n \"personal_setting\": true\n}\n"; + std::fs::write(&target.file, original).unwrap(); + configure_file(&target, EXE, false, false, Mode::Add).unwrap(); + assert_eq!(std::fs::read_to_string(&backup).unwrap(), original); + let changed_by_client = std::fs::read_to_string(&target.file).unwrap().replace("true", "false"); + std::fs::write(&target.file, &changed_by_client).unwrap(); + configure_file(&target, "/new/solidcraft-cli", false, false, Mode::Add).unwrap(); + assert_eq!(std::fs::read_to_string(&backup).unwrap(), changed_by_client); + let current = std::fs::read_to_string(&target.file).unwrap(); + assert!(current.contains("false") && current.contains("/new/solidcraft-cli")); + // A no-op or dry run must leave both the file and its backup alone. + configure_file(&target, "/new/solidcraft-cli", false, false, Mode::Add).unwrap(); + configure_file(&target, "/future/solidcraft-cli", false, true, Mode::Add).unwrap(); + assert_eq!(std::fs::read_to_string(&target.file).unwrap(), current); + assert_eq!(std::fs::read_to_string(&backup).unwrap(), changed_by_client); + configure_file(&target, "/new/solidcraft-cli", false, false, Mode::Remove).unwrap(); + assert_eq!(std::fs::read_to_string(&backup).unwrap(), current); + assert!(!std::fs::read_to_string(&target.file).unwrap().contains("solidcraft")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn configuration_is_unchanged_when_its_backup_cannot_be_replaced() { + let dir = config_dir("backup-failure"); + let target = Target { client: "codex", file: dir.join("config.toml"), shape: Shape::Codex }; + let original = "# personal setting\nmodel = \"custom\"\n"; + std::fs::write(&target.file, original).unwrap(); + std::fs::create_dir(dir.join("config.toml.bak")).unwrap(); + assert!(configure_file(&target, EXE, false, false, Mode::Add).is_err()); + assert_eq!(std::fs::read_to_string(&target.file).unwrap(), original); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2, "no temporary files remain"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn configuration_refuses_an_edit_based_on_an_outdated_read() { + let dir = config_dir("concurrent"); + let path = dir.join("config.json"); + let backup = dir.join("config.json.bak"); + std::fs::write(&backup, "previous backup").unwrap(); + for (expected, current) in [(Some("old"), Some("new")), (Some("old"), None), (None, Some("new"))] { + if let Some(text) = current { + std::fs::write(&path, text).unwrap(); + } else { + std::fs::remove_file(&path).unwrap(); + } + let error = write_config(&path, expected, "stale edit").unwrap_err(); + assert!(error.to_string().contains("configuration changed"), "{error}"); + assert_eq!(read_config(&path).unwrap().as_deref(), current); + assert_eq!(std::fs::read_to_string(&backup).unwrap(), "previous backup"); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn configuration_replaces_a_complete_file_and_keeps_links_and_permissions() { + use std::io::Read; + use std::os::unix::fs::{PermissionsExt, symlink}; + let dir = config_dir("atomic"); + let real = dir.join("real.json"); + let target = Target { client: "claude-code", file: dir.join("config.json"), shape: Shape::ClaudeCode }; + let original = "{\"personal_setting\": true}\n"; + std::fs::write(&real, original).unwrap(); + std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap(); + symlink("real.json", &target.file).unwrap(); + let mut reader = std::fs::File::open(&target.file).unwrap(); + configure_file(&target, EXE, false, false, Mode::Add).unwrap(); + let mut old = String::new(); + reader.read_to_string(&mut old).unwrap(); + assert_eq!(old, original, "an existing reader sees the complete old file"); + assert!(std::fs::read_to_string(&target.file).unwrap().contains(EXE)); + assert!(std::fs::symlink_metadata(&target.file).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::metadata(&real).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::read_to_string(dir.join("real.json.bak")).unwrap(), original); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn quiet_adds_only_the_plain_entry_and_names_new_clients_once() { let h = std::env::temp_dir().join(format!("solidcraft-quiet-{}", std::process::id())); diff --git a/crates/engine/src/batch_preflight.rs b/crates/engine/src/batch_preflight.rs index f16aef3da..638e7c79c 100644 --- a/crates/engine/src/batch_preflight.rs +++ b/crates/engine/src/batch_preflight.rs @@ -33,7 +33,7 @@ impl Refusal { /// The batch reply for a batch refused before its first step: as a failed step's reply, /// with nothing completed, nothing undone and every step not run. pub fn reply(&self, steps: usize) -> Value { - json!({ + let mut reply = json!({ "completed": 0, "results": [], "failed": {"index": self.index, "command": self.command, "error": self.error}, @@ -41,7 +41,11 @@ impl Refusal { "rolled_back": false, "not_run": (0..steps).collect::>(), "note": "nothing was run: the batch was checked before its first step", - }) + }); + if let Some(reason) = crate::panels::commands::structured_error(&self.error) { + reply["failed"]["panel_error"] = reason; + } + reply } } @@ -82,6 +86,15 @@ pub fn contracts(steps: &[Value]) -> Option { /// Step `index`'s refusal when its parameters break the typed contract of its command `id`. fn contract_refusal(index: usize, id: &str, step: &Value) -> Option { + if crate::panels::commands::is_command(id) { + let empty = json!({}); + let params = step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty); + return crate::panels::commands::parse_command(id, params).err().map(|reason| Refusal { + index, + command: Some(id.into()), + error: crate::panels::commands::error_text(reason), + }); + } let first = crate::schema::issues(id, step.get("params").unwrap_or(&Value::Null)).into_iter().next()?; Some(Refusal { index, command: Some(id.to_string()), error: crate::params::bad(id, first.message).to_string() }) } diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 9a6b73a4a..57773fa9d 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -2,6 +2,7 @@ //! `examples/regressions/` (each script's description says what went wrong). use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -21,7 +22,7 @@ fn check_partial_face_contact_pattern() { let (mut volume, mut area, mut shells) = (0.0, 0.0, 0); for b in &s.model.state().bodies { assert!(b.body.validity().is_empty(), "{:?}", b.body.validity()); - let m = b.body.tessellate(1e-5).unwrap().measure(); + let m = b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure(); volume += m.volume; area += m.area; shells += b.body.shell_count(); @@ -55,7 +56,16 @@ fn intersection_never_keeps_material_outside_the_trimming_cylinder() { let before = volume(&s, "Base"); let r = s.execute("solid.cylinder", &json!({"radius": 16.65, "height": 14.59, "operation": "intersect", "targets": ["Base"]})); let state = s.model.state(); - let reach = state.body("Base").unwrap().body.tessellate(1e-3).unwrap().positions.iter().map(|p| p.x.hypot(p.y)).fold(0.0, f64::max); + let reach = state + .body("Base") + .unwrap() + .body + .mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)) + .unwrap() + .positions + .iter() + .map(|p| p.x.hypot(p.y)) + .fold(0.0, f64::max); match r { Ok(_) => assert!(reach < 16.65 + 1e-2, "kept material out to radius {reach}"), Err(e) => assert!((volume(&s, "Base") - before).abs() < 1e-9 && reach > 16.9, "{e}"), @@ -78,7 +88,8 @@ fn volume(s: &Session, body: &str) -> f64 { /// Dividing one of the cut's intersection edges met a point that projects onto neither surface, /// and the fallback unwrapped that same failed projection: a kernel panic, recorded as a crash. /// Nothing panics now; the box loses the eighth of the ball inside it, or the cut is refused -/// and the box is left whole. +/// and the box is left whole. The side face is picked by its point (the report's face index +/// was truck's order): `p3` is its corner (15, -5, 0) and `l4` the box's upright edge there. #[test] fn revolve_cut_round_a_box_corner_does_not_panic() { use std::sync::Arc; @@ -89,7 +100,7 @@ fn revolve_cut_round_a_box_corner_does_not_panic() { ("sketch.rectangle.two_point", json!({"p0": [-5.4, 7.0], "p1": [15.0, -5.0]})), ("sketch.finish", json!({})), ("solid.extrude", json!({"direction": "positive", "distance": "10 mm", "operation": "new", "profiles": [0], "sketch": 1})), - ("sketch.create", json!({"plane": {"body": "Body1", "face": [12.721266146083186, -5.0, 7.034827173055135], "index": 1, "path": []}})), + ("sketch.create", json!({"plane": {"face": [12.721266146083186, -5.0, 7.034827173055135]}})), ("sketch.circle.center", json!({"center": "p3", "radius": 4.664761515876241})), ("sketch.options", json!({"slice": true})), ("sketch.finish", json!({})), @@ -167,8 +178,8 @@ fn step_export_of_an_enclosure_with_a_screw_hole_finishes_and_reads_back() { let s = replay(include_str!("../../../examples/regressions/step_export_screw_hole_enclosure.json")); let state = s.model.state(); let body = &state.body("Unterteil").unwrap().body; - // 27 faces; the kernel splits each of the three whole turns (the hole, two standoffs) in two. - assert_eq!(body.face_count(), 30); + // 27 faces, as the file holds them: each whole turn (the hole, two standoffs) is one face. + assert_eq!(body.face_count(), 27); let (text, file_faces) = read_back(&s, body); assert_eq!(text.matches("CYLINDRICAL_SURFACE(").count(), 7, "the seven round faces stay cylinders"); assert_eq!(file_faces, 27); @@ -217,11 +228,11 @@ fn shallow_cuts_rebuild_after_inserting_an_earlier_pocket() { assert!(body.validity().is_empty(), "{:?}", body.validity()); let actual = volume(&session, "Plate"); assert!((actual - expected).abs() < 0.02, "{actual} vs {expected}"); - let mesh = body.tessellate(0.001).unwrap(); - assert!(!mesh.contains(solidcraft_geom::Vec3::new(12.0, 14.0, 9.0))); - assert!(mesh.contains(solidcraft_geom::Vec3::new(12.0, 14.0, 8.0))); - assert!(!mesh.contains(solidcraft_geom::Vec3::new(20.0, 20.0, 9.5))); - assert!(mesh.contains(solidcraft_geom::Vec3::new(20.0, 20.0, 9.0))); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap(); + assert!(!mesh.contains(solidcore_record::Vec3::new(12.0, 14.0, 9.0))); + assert!(mesh.contains(solidcore_record::Vec3::new(12.0, 14.0, 8.0))); + assert!(!mesh.contains(solidcore_record::Vec3::new(20.0, 20.0, 9.5))); + assert!(mesh.contains(solidcore_record::Vec3::new(20.0, 20.0, 9.0))); } } @@ -237,7 +248,7 @@ fn eighteen_tabs_join_the_ribs_of_a_chamfered_base() { let body = &state.body("Base").unwrap().body; assert_eq!(body.shell_count(), 1); assert!(body.validity().is_empty(), "{:?}", body.validity()); - let mesh = body.tessellate(1e-4).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap(); // R40 x 4 disc less its 1 x 1 chamfer, six 32 x 2 ribs // standing 4 above it, and eighteen 1 x 2 tabs another 8 higher. let expected = std::f64::consts::PI * (6400.0 - 40.0 + 1.0 / 3.0) + 1536.0 + 288.0; @@ -246,7 +257,7 @@ fn eighteen_tabs_join_the_ribs_of_a_chamfered_base() { println!("#2059 volume {got:.6} / {expected:.6} mm³; one valid shell, eighteen tabs"); for k in 0..6 { let angle = k as f64 * std::f64::consts::TAU / 6.0; - let p = |x: f64, y: f64, z| solidcraft_geom::Vec3::new(x * angle.cos() - y * angle.sin(), x * angle.sin() + y * angle.cos(), z); + let p = |x: f64, y: f64, z| solidcore_record::Vec3::new(x * angle.cos() - y * angle.sin(), x * angle.sin() + y * angle.cos(), z); for x in [15.5, 25.5, 35.5] { assert!(mesh.contains(p(x, 0.0, 12.0)), "tab {k} at {x}"); assert!(!mesh.contains(p(x, 1.2, 12.0)), "tab {k} grew sideways at {x}"); @@ -400,7 +411,14 @@ fn ribs_flush_with_a_window_change_nothing_away_from_them() { s.run_script(&Value::Array(lid.to_vec())).unwrap(); let measure = |s: &Session| s.model.state().body("Lid").map(|b| solidcraft_kernel::measure(&b.body).unwrap()).unwrap(); let (v0, a0) = (measure(&s).volume, measure(&s).area); - assert!((v0 - 6703.5222).abs() < 1e-3, "{v0}"); + // The plate with its rounded corners, the skirt, less the window, the slot and the notch + // through the skirt: (76.8 × 89.3 - (4 - π) × 9) × 2.4 + (71.5 × 84 - 68.5 × 81) × 3 + // - 68 × 61 × 2.4 - 44 × 10 × 2.4 - 22 × 1.5 × 3. + let lid = (76.8 * 89.3 - (4.0 - std::f64::consts::PI) * 9.0) * 2.4 + (71.5 * 84.0 - 68.5 * 81.0) * 3.0 + - 68.0 * 61.0 * 2.4 + - 44.0 * 10.0 * 2.4 + - 22.0 * 1.5 * 3.0; + assert!((v0 - lid).abs() < 1e-3, "{v0} vs {lid}"); for (i, rib) in ribs.iter().enumerate() { let reply = s.execute(rib["command"].as_str().unwrap(), &rib["params"]).unwrap(); let id = reply["feature"].as_u64().unwrap(); @@ -409,15 +427,17 @@ fn ribs_flush_with_a_window_change_nothing_away_from_them() { assert!(!result.warning.as_deref().unwrap_or_default().contains("tool displacement"), "{:?}", result.warning); let m = measure(&s); let n = (i + 1) as f64; + // The measure's accuracy: SMLib's mass properties come within 2e-7 of a closed form. + let (dv, da) = (2e-7 * m.volume, 2e-7 * m.area); // 1.6 x 6 x 11.7 less the 1.35 x 6 x 3 inside the skirt. - assert!((m.volume - (v0 + n * 88.02)).abs() < 1e-6, "rib {}: {}", i + 1, m.volume - v0); + assert!((m.volume - (v0 + n * 88.02)).abs() < dv, "rib {}: {}", i + 1, m.volume - v0); // Top 9.6, outer side 6 x 8.7 above the skirt, inner side 6 x 11.7 (flush with the // window's side), ends 2 x (1.6 x 11.7 - 1.35 x 3); the skirt top 8.1, its inner side // 18 and 1.5 of the plate go under the rib. let area = 9.6 + 52.2 + 70.2 + 29.34 - 8.1 - 18.0 - 1.5; - assert!((m.area - (a0 + n * area)).abs() < 1e-6, "rib {}: area {} (no slit adds any)", i + 1, m.area - a0); + assert!((m.area - (a0 + n * area)).abs() < da, "rib {}: area {} (no slit adds any)", i + 1, m.area - a0); } - let bounds = s.model.state().body("Lid").unwrap().body.tessellate(0.01).unwrap().bounds(); + let bounds = s.model.state().body("Lid").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().bounds(); assert!((bounds.max.z - 14.1).abs() < 1e-9, "{}", bounds.max.z); } @@ -502,7 +522,7 @@ fn lip_swept_flush_round_a_corner_joins() { assert_eq!(b.body.shell_count(), 1); let block = (50.0 * 40.0 - (4.0 - std::f64::consts::PI) * 4.5 * 4.5) * 10.0; let lip = 41.0 + 31.0 + 41.0 + 2.0 * std::f64::consts::PI * (4.5 * 4.5 - 3.5 * 3.5) / 4.0; - let volume = b.body.tessellate(1e-5).unwrap().measure().volume; + let volume = b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume; assert!((volume - block - lip).abs() < 0.02, "{volume} expected {}", block + lip); } @@ -520,7 +540,7 @@ fn cut_of_a_whole_face_beside_round_corners_after_a_chamfer() { let block = (40.0 * 40.0 - (4.0 - pi) * 8.0 * 8.0) * 15.0; // The chamfer's 2 × 2 triangle swept along the loop (Pappus: its centroid is 2/3 mm in). let chamfer = 2.0 * (4.0 * 24.0 + 2.0 * pi * (8.0 - 2.0 / 3.0)); - let mesh = b.body.tessellate(1e-4).unwrap(); + let mesh = b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap(); let volume = mesh.measure().volume; assert!((volume - (block - chamfer)).abs() < 0.05, "{volume} expected {}", block - chamfer); let top = mesh.bounds().max.z; @@ -544,7 +564,8 @@ fn joined_loft_frames_plan_their_display_at_every_quality() { let body = &state.body(name).unwrap().body; for q in DisplayQuality::ALL { for k in 0..=MAX_REFINE { - let plan = body.display_plan_angular(q.refined_chord(body.size(), k), q.refined_angle(k)); + let plan = + body.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.refined_chord(body.size(), k), angle: Some(q.refined_angle(k)) }); assert!(plan.is_ok(), "{name} at {} + {k}: {:?}", q.id(), plan.err()); } } @@ -562,16 +583,24 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/oblique_cuts_through_chamfered_ring.json")).unwrap(); let steps = script.get("commands").and_then(Value::as_array).unwrap(); let mut s = Session::default(); - let mut volumes = Vec::new(); + // The ring after the move and after each cut, and what each cut took away (the ring before it + // less the ring after it: a small body that measures to its own accuracy, where the difference + // of the whole ring's volumes is lost in the integration's 1e-6 of 1149 mm³). + let mut rings: Vec = Vec::new(); for step in steps { let reply = s.execute(step["command"].as_str().unwrap(), &step["params"]).unwrap(); if step["command"] == "solid.extrude" { assert!(reply["warning"].is_null(), "{reply}"); } if matches!(step["command"].as_str(), Some("solid.move" | "solid.extrude")) { - volumes.push(s.model.state().body("R").unwrap().body.tessellate(1e-5).unwrap().measure().volume); + rings.push(s.model.state().body("R").unwrap().body.clone()); } } + let taken = |k: usize| -> f64 { + let piece = solidcraft_kernel::boolean(&rings[k], &rings[k + 1], solidcraft_kernel::BoolOp::Cut).unwrap().unwrap(); + solidcraft_kernel::measure(&piece).unwrap().volume + }; + let volumes: Vec = rings.iter().map(|b| b.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume).collect(); // Pappus: the profile's moment about the axis turned through 240°. let profile = [(16.6, 0.0), (17.5, 0.0), (18.5, 1.0), (18.5, 7.0), (17.5, 8.0), (16.6, 8.0), (16.4, 7.8), (16.4, 0.2)]; let moment: f64 = (0..profile.len()) @@ -581,25 +610,27 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { }) .sum(); let ring = moment.abs() * 4.0 * std::f64::consts::PI / 3.0; - let [whole, first, second, notched] = volumes[..] else { panic!("{volumes:?}") }; + let [whole, _, _, _] = volumes[..] else { panic!("{volumes:?}") }; // Volumes from meshes at 1e-5 mm: within a few millionths of the ring's. assert!((whole - ring).abs() < 1e-5 * ring, "{whole} vs {ring}"); // The ring and the two prisms are mirror images across XZ. - let (cut1, cut2) = (whole - first, first - second); - assert!(cut1 > 5.0 && (cut1 - cut2).abs() < 1e-6, "{cut1} vs {cut2}"); - let notch = ring_notch(); - assert!(((second - notched) - notch).abs() < 1e-4, "{} vs {notch}", second - notched); + let (cut1, cut2) = (taken(0), taken(1)); + assert!(cut1 > 5.0 && (cut1 - cut2).abs() < 1e-6 * cut1, "{cut1} vs {cut2}"); + let (notched, notch) = (taken(2), ring_notch()); + assert!((notched - notch).abs() < 1e-5 * notch, "{notched} vs {notch}"); let state = s.model.state(); let body = &state.body("R").unwrap().body; assert!(body.validity().is_empty(), "{:?}", body.validity()); // Faces meshed coarsely keep to their surfaces: chords cut a little area off round faces, // and nothing adds any (triangles fanning across a chamfer from the notch's hole or from the // cuts' trims, folded over each other, added a few mm² each). - let (coarse, fine) = (body.tessellate(0.05).unwrap().measure().area, body.tessellate(1e-5).unwrap().measure().area); + let (coarse, fine) = ( + body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap().measure().area, + body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().area, + ); assert!(coarse < fine && coarse > fine - 2.0, "area meshed at 0.05: {coarse} vs {fine}"); println!( - "ring {whole:.6} / {ring:.6} mm³; cuts {cut1:.6}, {cut2:.6}; notch {:.6} / {notch:.6}; area meshed at 0.05 {coarse:.4} / {fine:.4}", - second - notched + "ring {whole:.6} / {ring:.6} mm³; cuts {cut1:.6}, {cut2:.6}; notch {notched:.6} / {notch:.6}; area meshed at 0.05 {coarse:.4} / {fine:.4}" ); } @@ -611,16 +642,18 @@ fn notch_into_a_ring_chamfer_is_cut_exactly() { let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/oblique_cuts_through_chamfered_ring.json")).unwrap(); let steps = script.get("commands").and_then(Value::as_array).unwrap(); let mut s = Session::default(); - let measure = |s: &Session| s.model.state().body("R").unwrap().body.tessellate(1e-5).unwrap().measure().volume; s.run_script(&Value::Array(steps[..5].to_vec())).unwrap(); - let before = measure(&s); + let before = s.model.state().body("R").unwrap().body.clone(); // The notch's sketch and its cut. for step in &steps[steps.len() - 4..] { let reply = s.execute(step["command"].as_str().unwrap(), &step["params"]).unwrap(); assert!(reply["warning"].is_null(), "{reply}"); } - let (got, want) = (before - measure(&s), ring_notch()); - assert!((got - want).abs() < 1e-4, "{got} vs {want}"); + // What the cut took: the ring before it less the ring after it, measured as a body of its own + // (the difference of the two rings' volumes is lost in the integration's 1e-6 of 1149 mm³). + let piece = solidcraft_kernel::boolean(&before, &s.model.state().body("R").unwrap().body, solidcraft_kernel::BoolOp::Cut).unwrap().unwrap(); + let (got, want) = (solidcraft_kernel::measure(&piece).unwrap().volume, ring_notch()); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); } /// What the ring's notch takes: a band 0.9 wide about a radius, from 17.6 out along it, and from @@ -650,7 +683,7 @@ fn ring_notch() -> f64 { } /// The wedge of #1617: a side profile in (y, z) extruded 138 mm along x, its back face leaning -/// by `lean` (the tangent of its angle), with the issue's rounds. The last one runs along the +/// by `lean` (the tangent of its angle), with the issue's rounds, each on the edges it picked. The last one runs along the /// outline of both ends. The issue asked for R1 with `fit: reduce`, which reduces it to 0.854 mm; /// that radius is asked for here directly, which builds the same body without the fit's search /// (about a minute). @@ -668,7 +701,14 @@ fn raked_wedge(lean: f64) -> Session { ("solid.fillet", json!({"body": "Wedge", "radius": 1.2, "edges": [[0, -60, 22]]})), ("solid.fillet", json!({"body": "Wedge", "radius": 1.5, "edges": [[0, -22, 22]]})), ("solid.fillet", json!({"body": "Wedge", "radius": 1.5, "edges": [[0, 38, 60]]})), - ("solid.fillet", json!({"body": "Wedge", "radius": 4, "edges": [[-69, -60, 12], [69, -60, 12], [-69, back, 30], [69, back, 30]]})), + // The issue's R4 rounds these four end edges alone: carried on round the end outline + // (tangent propagation, the feature's default since 84bd2daad, after this test), it would + // run onto the R1.2 round's end arc, where its rail on the end face would be an arc of + // radius 1.2 - 4 < 0. + ( + "solid.fillet", + json!({"body": "Wedge", "radius": 4, "tangent_chain": false, "edges": [[-69, -60, 12], [69, -60, 12], [-69, back, 30], [69, back, 30]]}), + ), ("solid.fillet", json!({"body": "Wedge", "radius": 0.854, "edges": ends})), ]; for (command, params) in steps { @@ -703,7 +743,7 @@ fn box_intersect_splits_the_end_off_a_raked_wedge_after_its_end_rounds() { let state = s.model.state(); let body = &state.body(&target).unwrap().body; assert!(body.validity().is_empty(), "lean {lean}, x >= {x0}, {op}: {:?}", body.validity()); - (solidcraft_kernel::measure(body).unwrap().volume, body.tessellate(1e-3).unwrap().bounds()) + (solidcraft_kernel::measure(body).unwrap().volume, body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap().bounds()) }; let (slice, at) = piece("intersect"); let (rest, _) = piece("cut"); @@ -757,10 +797,10 @@ fn closed_sweep_redefines_to_a_half_turn_torus_cut() { assert_eq!(s.model.state().bodies.len(), 1); let body = &s.model.state().bodies[0].body; assert!(body.validity().is_empty(), "{:?}", body.validity()); - let mesh = body.tessellate(0.02).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.02)).unwrap(); let expected = (std::f64::consts::PI * 64.0 - 64.0) * std::f64::consts::TAU * 30.0; assert!((mesh.measure().volume - expected).abs() < expected * 0.015); - for (point, material) in [(solidcraft_geom::Vec3::new(30.0, 0.0, 0.0), false), (solidcraft_geom::Vec3::new(30.0, 0.0, 7.0), true)] { + for (point, material) in [(solidcore_record::Vec3::new(30.0, 0.0, 0.0), false), (solidcore_record::Vec3::new(30.0, 0.0, 7.0), true)] { assert_eq!(mesh.contains(point), material, "material at {point:?}"); } } @@ -792,7 +832,7 @@ fn many_extrusion_profiles_preserve_material_and_body_identity() { assert!((volume(&s, "Stock") - expected).abs() < 1e-6); let stock = state.body("Stock").unwrap(); for (point, present) in [([3.0, 3.0, 22.0], operation == "join"), ([3.0, 3.0, 18.0], operation != "cut"), ([7.0, 3.0, 18.0], true)] { - assert_eq!(stock.mesh().contains(solidcraft_geom::Vec3::from(point)), present, "{operation}: {point:?}"); + assert_eq!(stock.mesh().contains(solidcore_record::Vec3::from(point)), present, "{operation}: {point:?}"); } assert!(stock.body.validity().is_empty()); assert!(s.revision > before); @@ -825,10 +865,10 @@ fn many_circular_extrusion_profiles_cut_a_curved_target() { let stock = state.body("Stock").unwrap(); assert!(stock.body.validity().is_empty()); let mesh = stock.mesh(); - assert!(mesh.contains(solidcraft_geom::Vec3::new(0.0, 0.0, 10.0))); + assert!(mesh.contains(solidcore_record::Vec3::new(0.0, 0.0, 10.0))); for x in [-9.0, -3.0, 3.0, 9.0] { for y in [-9.0, -3.0, 3.0, 9.0] { - assert!(!mesh.contains(solidcraft_geom::Vec3::new(x, y, 10.0)), "hole at {x}, {y}"); + assert!(!mesh.contains(solidcore_record::Vec3::new(x, y, 10.0)), "hole at {x}, {y}"); } } } @@ -888,7 +928,7 @@ fn unsupported_face_groups_are_atomic() { #[test] fn imported_rotated_face_extrusions_preserve_other_operations_and_bodies() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut source = Session::default(); source.execute("solid.box", &json!({"corner":[-16,-16,-3],"length":32,"width":32,"height":1,"body_name":"Other"})).unwrap(); source.execute("solid.cylinder", &json!({"radius":14,"height":8,"body_name":"Stock"})).unwrap(); @@ -942,7 +982,10 @@ fn imported_rotated_face_extrusions_preserve_other_operations_and_bodies() { let reference = expected.body(&body.name).unwrap(); // Fixed fine chord tolerance: cap subdivision can change the default // adaptive mesh's cylinder faceting without changing its analytic surface. - let (a, b) = (body.body.tessellate(1e-5).unwrap().measure().volume, reference.body.tessellate(1e-5).unwrap().measure().volume); + let (a, b) = ( + body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume, + reference.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume, + ); assert!((a - b).abs() < b.max(1.) * 1e-6, "{operation}: {} {a} vs {b}", body.name); assert!(body.body.validity().is_empty(), "{operation}: {}", body.name); let (a, b) = (body.mesh(), reference.mesh()); @@ -957,7 +1000,11 @@ fn imported_rotated_face_extrusions_preserve_other_operations_and_bodies() { let unchanged = &actual.body("Other").unwrap().body; assert_eq!(unchanged.face_count(), other.face_count()); assert_eq!(unchanged.color(), other.color()); - assert_eq!(unchanged.tessellate(0.01).unwrap().positions, other.tessellate(0.01).unwrap().positions, "unaffected imported body"); + assert_eq!( + unchanged.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().positions, + other.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().positions, + "unaffected imported body" + ); } } } @@ -1021,8 +1068,15 @@ fn cut_keeps_posts_joined_while_apart_in_one_body() { // A cut through the middle of the case still leaves two bodies, and says it made the second. s.execute("solid.box", &json!({"length": 2, "width": 80, "height": 80, "center": [0, 0, 20], "operation": "new", "body_name": "Saw"})).unwrap(); let saw = s.execute("solid.combine", &json!({"target": "Case", "tools": ["Saw"], "operation": "cut"})).unwrap(); - assert_eq!(saw["bodies"], json!(["Case", "Case (1)"]), "{saw}"); + // `bodies` lists them in the kernel's order. The piece whose least face name sorts first keeps + // the name (`lineage::order_lumps`): the +x half, whose `F1:+x` sorts before the -x half's + // least, its piece of the case's `F1:+y`. + let mut bodies: Vec<&str> = saw["bodies"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + bodies.sort_unstable(); + assert_eq!(bodies, ["Case", "Case (1)"], "{saw}"); assert_eq!(saw["created_bodies"], json!(["Case (1)"]), "{saw}"); + let low_x = |name: &str| s.model.state().body(name).unwrap().mesh().bounds().min.x; + assert!((low_x("Case") - 1.0).abs() < 1e-9 && (low_x("Case (1)") + 30.0).abs() < 1e-9); let half = (60.0 - 2.0) / 2.0 * 40.0 * 10.0 + posts / 2.0; for name in ["Case", "Case (1)"] { assert!((volume(&s, name) - half).abs() < 1e-6 * half, "{name}: {} vs {half}", volume(&s, name)); @@ -1115,12 +1169,17 @@ fn prism_edge_in_a_round_cornered_slab_end_face_joins() { /// of the bodies as they lie left the hole closed by a skin of no thickness (the plate's top face /// whole over the hole, the tool's end face under it), which no volume shows and which was kept. /// The hole is open, and the cut takes the whole tool: the circle of radius 3.04 the two -/// profiles make, from the barrel cut's floor at z 1.6 up to the plate's top at z 2.8. +/// profiles make, from the barrel cut's floor at z 1.6 up to the plate's top at z 2.8. The design +/// was saved by an older build: Extrude13 starts from a piece of a face that is no longer that +/// piece, so it fails, asking for its face again; the rest builds. #[test] fn cut_up_to_the_plate_top_face_opens_the_hole() { let mut script: Value = serde_json::from_str(include_str!("../../../examples/regressions/cut_up_to_face_leaves_skin.json")).unwrap(); let s = replay_value(&script); - assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let failed = + |r: &solidcraft_doc::FeatureResult| r.error.as_deref().and_then(solidcraft_doc::reselect_parts).map(|(feature, _)| feature.to_string()); + assert!(s.model.results.iter().all(|r| r.error.is_none() || failed(r).as_deref() == Some("Extrude13")), "{:?}", s.model.results); + assert!(s.model.results.iter().any(|r| failed(r).as_deref() == Some("Extrude13"))); let state = s.model.state(); let body = &state.body("Body7").unwrap().body; assert!(body.validity().is_empty(), "{:?}", body.validity()); @@ -1135,7 +1194,8 @@ fn cut_up_to_the_plate_top_face_opens_the_hole() { // The same design without the cut. script["commands"].as_array_mut().unwrap().pop(); let before = replay_value(&script); - let fine = |s: &Session| s.model.state().body("Body7").unwrap().body.tessellate(1e-5).unwrap().measure().volume; + let fine = + |s: &Session| s.model.state().body("Body7").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume; let (removed, want) = (fine(&before) - fine(&s), std::f64::consts::PI * 3.04 * 3.04 * 1.2); assert!((removed - want).abs() < 0.01, "removed {removed} mm³, want {want}"); } @@ -1176,7 +1236,7 @@ fn cut_beside_a_sealed_void_keeps_the_body() { assert_eq!(body.shell_count(), if operation == "cut" { 2 } else { 1 }); assert!(body.validity().is_empty(), "{:?}", body.validity()); // The revolved side's mesh stays 0.3 mm³ under its cylinder at any finer tolerance. - body.tessellate(1e-5).unwrap().measure().volume + body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume }; // A box over the bottom edge: the segment beyond x = 15, 5 high. let edge_box = [("solid.box", json!({"length": 15, "width": 60, "height": 10, "corner": [15, -30, -5], "operation": "new", "body_name": "K"}))]; @@ -1228,8 +1288,8 @@ fn joined_loft_frames_reference_mesh_covers_each_face_once() { a }; let size = body.size(); - let mesh = per_face(&body.reference_display_mesh_angular(size * 3e-4, 12f64.to_radians()).unwrap()); - let fine = per_face(&body.reference_display_mesh_angular(size * 3e-5, 3f64.to_radians()).unwrap()); + let mesh = per_face(&body.mesh(&solidcraft_kernel::MeshTolerance { chord: size * 3e-4, angle: Some(12f64.to_radians()) }).unwrap()); + let fine = per_face(&body.mesh(&solidcraft_kernel::MeshTolerance { chord: size * 3e-5, angle: Some(3f64.to_radians()) }).unwrap()); for (fi, (m, f)) in mesh.iter().zip(&fine).enumerate() { assert!((m - f).abs() <= 0.01 * f.max(1.0), "{name} face {fi}: mesh {m:.0} mm², finer mesh {f:.0} mm²"); } diff --git a/crates/engine/src/cmd/appearance_chain.rs b/crates/engine/src/cmd/appearance_chain.rs index cd4317424..cb48737c6 100644 --- a/crates/engine/src/cmd/appearance_chain.rs +++ b/crates/engine/src/cmd/appearance_chain.rs @@ -21,16 +21,20 @@ fn component(s: &Session, cmd: &str, value: &Value) -> Result { Value::Number(_) => value.as_u64().ok_or_else(|| bad(cmd, "component must be a name or unsigned id"))?.to_string(), _ => return Err(bad(cmd, "component must be a name or unsigned id")), }; - s.doc.find_component(&key).filter(|id| *id != 0).ok_or_else(|| bad(cmd, "unknown or root component")) + // A placement's name (`K:2`) means its component, as appearance.assign takes it (#9740). + s.component_or_placement(&key).ok_or_else(|| bad(cmd, "unknown or root component")) } pub(super) fn chain(s: &mut Session, p: &Value) -> Result { let cmd = "appearance.chain"; let target = p.get("target").and_then(Value::as_object).ok_or_else(|| bad(cmd, "give one target object"))?; - let target = match (target.get("body"), target.get("face"), target.get("component")) { - (Some(body), None, None) if target.len() == 1 => AppearanceTarget::Body(name(cmd, body)?), + // A placed copy's name (`KB (K:2)`) means the body it shows, as appearance.assign takes it + // (#9740); a name that is neither is left for the chain to refuse. + let body = target.get("body").map(|b| name(cmd, b).map(|n| s.own_body_name(n).unwrap_or_else(|| n.to_string()))).transpose()?; + let target = match (body.as_deref(), target.get("face"), target.get("component")) { + (Some(body), None, None) if target.len() == 1 => AppearanceTarget::Body(body), (Some(body), Some(face), None) if target.len() == 2 => AppearanceTarget::Face { - body: name(cmd, body)?, + body, face: face.as_u64().and_then(|f| usize::try_from(f).ok()).ok_or_else(|| bad(cmd, "face must be a zero-based unsigned index"))?, }, (None, None, Some(id)) if target.len() == 1 => AppearanceTarget::Component(component(s, cmd, id)?), @@ -80,12 +84,18 @@ fn scope(s: &Session, cmd: &str, value: &Value) -> Result { if object.contains_key("bodies") { let state = s.model.state(); let bodies: BTreeSet<_> = state.bodies.iter().map(|b| b.name.as_str()).collect(); + // A placed copy's name means the body it shows (#9740). Built once, and only when a + // name is not the model's own. + let mut placed: Option> = None; for body in list("bodies")? { let body = name(cmd, body)?; - if !bodies.contains(body) { - return Err(bad(cmd, "unknown body in scope")); - } - scope.bodies.insert(body.into()); + let own = if bodies.contains(body) { + body.to_string() + } else { + let placed = placed.get_or_insert_with(|| s.body_frames().iter().map(|(world, own, _)| (world.clone(), own.clone())).collect()); + placed.get(body).cloned().ok_or_else(|| bad(cmd, "unknown body in scope"))? + }; + scope.bodies.insert(own); } } if object.contains_key("components") { @@ -93,11 +103,13 @@ fn scope(s: &Session, cmd: &str, value: &Value) -> Result { // 10000-component design once per target. let ids: BTreeSet<_> = s.doc.components.iter().map(|c| c.id).collect(); let names: BTreeMap<_, _> = s.doc.components.iter().rev().map(|c| (c.name.as_str(), c.id)).collect(); + // A placement's name (`K:2`) means its component (#9740). + let placements: BTreeMap<_, _> = s.doc.occurrences.iter().rev().map(|o| (o.name.as_str(), o.component)).collect(); for target in list("components")? { let id = match target { Value::String(_) => { let key = name(cmd, target)?; - key.parse::().ok().filter(|id| ids.contains(id)).or_else(|| names.get(key).copied()) + key.parse::().ok().filter(|id| ids.contains(id)).or_else(|| names.get(key).copied()).or_else(|| placements.get(key).copied()) } Value::Number(_) => target.as_u64().filter(|id| ids.contains(id)), _ => None, diff --git a/crates/engine/src/cmd/bom.rs b/crates/engine/src/cmd/bom.rs index 25d3846b3..3c008080d 100644 --- a/crates/engine/src/cmd/bom.rs +++ b/crates/engine/src/cmd/bom.rs @@ -18,10 +18,11 @@ use solidcraft_doc::metadata::{BOM_KEYS, BOM_QUANTITY, BOM_TYPE, MATERIAL, MAX_K use super::CommandSpec; use crate::params::{bad, str_}; -use crate::schema::bom::{OccurrenceBomTypeParams, OccurrenceBomTypeResult}; +use crate::schema::bom::{BomParams, OccurrenceBomTypeParams, OccurrenceBomTypeResult}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; +const BOM_CONTRACT: TypedContract = TypedContract::new(); const OCCURRENCE_BOM_TYPE_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ @@ -54,7 +55,13 @@ pub static COMMANDS: &[CommandSpec] = &[ (as its component again). One undo step → occurrence, bom_type (its own, or same_as_component), effective (the type it \ counts as), changed", ), - CommandSpec::new("assembly.bom", "Bill of Materials", bom).at("SOLID", "INSPECT").icon("bom").noundo().params( + CommandSpec::new("assembly.bom", "Bill of Materials", crate::checked!("assembly.bom", bom)) + .at("SOLID", "INSPECT") + .icon("bom") + .noundo() + .contract(&BOM_CONTRACT) + .output(output_schema_for::) + .params( "component?: id or name (default the design); levels?: flat (default: every part at any depth, counted through its \ subassemblies) | top (the component's direct children, subassemblies as one row each) | all (as top, each subassembly's \ own rows listed after it, to any depth: items 1.1, 1.1.1, as in the CSV); show_purchased_contents?: true (in all, a \ @@ -69,7 +76,7 @@ pub static COMMANDS: &[CommandSpec] = &[ a .csv (columns item, part_number, description, revision, count, definition, material, quantity) or .json file (children as \ items 1.1, 1.2…); format?: csv|json (default from the path). Each placement counts as \ its occurrence's bom_type, else its component's: phantom has no row (what it holds counts here; its own bodies, \ - if it has any, are a row of their own), reference counts nowhere, purchased and inseparable are one row (in flat, an inseparable one's purchased parts are listed too); placements \ + if it has any, are a row of their own), reference counts nowhere, purchased and inseparable are one row (in flat, an inseparable one's purchased parts are listed too, under it with group_children and a part number); placements \ of one component that count as different types are different rows → rows: [{item, part_number, description, revision, \ bom_type, count, definition, material (the physical materials of the definitions' own bodies, \"; \" between them; a \ row that weighs what is placed inside it shows the one material all of that shares, else \"\"), mass_g?, quantity? \ @@ -82,7 +89,7 @@ pub static COMMANDS: &[CommandSpec] = &[ (the view's item numbers are saved: assembly.bom.renumber). In a numbered view each level is listed by item number \ and a row says provisional (its number not saved yet: a row added since shows the next number at its level, saved \ by the next change), locked and duplicate when true", - ), + ), CommandSpec::new("assembly.bom.renumber", "Renumber Items", renumber).icon("bom").params( "component?, levels?, group_by?, group_children?, show_purchased_contents?: the view, as assembly.bom takes them; \ start?: 1; step?: 1 (whole numbers, 1 to 999999); order?: list (default: by part number, as an unnumbered view \ diff --git a/crates/engine/src/cmd/bom_tests.rs b/crates/engine/src/cmd/bom_tests.rs index 3e6ed7873..6b5731e4a 100644 --- a/crates/engine/src/cmd/bom_tests.rs +++ b/crates/engine/src/cmd/bom_tests.rs @@ -499,6 +499,91 @@ fn bom_types_decide_what_is_a_row_and_what_counts_inside_it() { assert_eq!(run(&mut s, "component.metadata", json!({"component": "Gearbox"}))["bom_type"], "normal"); } +#[test] +fn group_children_keeps_an_inseparable_parts_purchased_children_in_its_row() { + let mut s = Session::default(); + for (name, parent, part_number, bom_type) in + [("Sub", "root", "SUB-1", "inseparable"), ("Screw", "Sub", "M2x10", "purchased"), ("Pin", "Sub", "PIN-1", "normal")] + { + run(&mut s, "component.create", json!({"name": name, "parent": parent, "activate": false})); + run(&mut s, "component.metadata.set", json!({"component": name, "part_number": part_number, "bom_type": bom_type})); + } + run(&mut s, "occurrence.copy", json!({"component": "Screw", "parent": "Sub"})); + run(&mut s, "occurrence.copy", json!({"component": "Sub"})); + let plain = run(&mut s, "assembly.bom", json!({})); + assert_eq!(typed(&plain), [row("M2x10", "purchased", 4), row("SUB-1", "inseparable", 2)]); + for levels in ["flat", "top"] { + for group in ["part_number", "definition"] { + let r = run(&mut s, "assembly.bom", json!({"levels": levels, "group_by": [group], "group_children": true})); + assert_eq!(typed(&r), [row("SUB-1", "inseparable", 2)], "{r}"); + assert_eq!(r["total_occurrences"], plain["total_occurrences"]); + let children = r["rows"][0]["children"].as_array().unwrap(); + assert_eq!(children.len(), 1, "the made Pin stays inside the inseparable part: {r}"); + assert_eq!(children[0]["item"], "1.1"); + assert_eq!(children[0]["part_number"], "M2x10"); + assert_eq!(children[0]["bom_type"], "purchased"); + assert_eq!(children[0]["each"], 2); + assert_eq!(children[0]["count"], 4); + } + } + let path = scratch("inseparable-kit").join("bom.csv"); + run(&mut s, "assembly.bom", json!({"group_children": true, "path": path})); + let text = std::fs::read_to_string(path).unwrap(); + let rows: Vec<&str> = text.lines().skip(1).collect(); + assert_eq!(rows, ["\"1\",\"SUB-1\",\"\",\"\",\"2\",\"Sub\",\"\",\"\"", "\"1.1\",\"M2x10\",\"\",\"\",\"4\",\"Screw\",\"\",\"\""]); + + // In its own context the component still lists all its parts, regardless of its type. + let own = run(&mut s, "assembly.bom", json!({"component": "Sub", "group_children": true})); + assert_eq!(typed(&own), [row("M2x10", "purchased", 2), row("PIN-1", "normal", 1)]); + // Only numbered parts fold; turning the option off or removing the number keeps the flat list. + run(&mut s, "component.metadata.set", json!({"component": "Sub", "part_number": ""})); + assert_eq!(run(&mut s, "assembly.bom", json!({"group_children": true}))["rows"], run(&mut s, "assembly.bom", json!({}))["rows"]); +} + +#[test] +fn an_inseparable_kit_finds_nested_purchased_parts_without_opening_purchased_or_reference_parts() { + let mut s = Session::default(); + for (name, parent, bom_type) in [ + ("Sub", "root", "inseparable"), + ("Carrier", "Sub", "normal"), + ("Nested", "Carrier", "inseparable"), + ("Bolt", "Nested", "purchased"), + ("Phantom", "Sub", "phantom"), + ("Reference", "Sub", "reference"), + ("Bought", "Sub", "purchased"), + ] { + run(&mut s, "component.create", json!({"name": name, "parent": parent, "activate": false})); + run(&mut s, "component.metadata.set", json!({"component": name, "part_number": name, "bom_type": bom_type})); + } + for parent in ["Phantom", "Reference", "Bought"] { + run(&mut s, "occurrence.copy", json!({"component": "Bolt", "parent": parent})); + } + let plain = run(&mut s, "assembly.bom", json!({})); + assert_eq!(typed(&plain), [row("Bolt", "purchased", 2), row("Bought", "purchased", 1), row("Sub", "inseparable", 1)]); + let folded = run(&mut s, "assembly.bom", json!({"group_children": true})); + assert_eq!(typed(&folded), [row("Sub", "inseparable", 1)]); + assert_eq!(folded["total_occurrences"], plain["total_occurrences"]); + let children = &folded["rows"][0]["children"]; + assert_eq!(children.as_array().unwrap().len(), 2, "{folded}"); + assert_eq!(children[0]["part_number"], "Bolt"); + assert_eq!(children[0]["each"], 2); + assert_eq!(children[1]["part_number"], "Bought"); + assert_eq!(children[1]["each"], 1); + + // Two definitions with the same number but different purchased contents stay separate kits. + run(&mut s, "component.create", json!({"name": "Other", "activate": false})); + run(&mut s, "component.metadata.set", json!({"component": "Other", "part_number": "Sub", "bom_type": "inseparable"})); + run(&mut s, "occurrence.copy", json!({"component": "Bolt", "parent": "Other"})); + let different = run(&mut s, "assembly.bom", json!({"group_children": true})); + assert_eq!(typed(&different), [row("Sub", "inseparable", 1), row("Sub", "inseparable", 1)]); + assert_eq!(different["total_occurrences"], 6); + // Buying the whole parent makes one purchased row, with no children listed. + set_type(&mut s, "Sub", "purchased"); + let bought = run(&mut s, "assembly.bom", json!({"group_children": true})); + let sub = bought["rows"].as_array().unwrap().iter().find(|r| r["definition"] == "Sub").unwrap(); + assert!(sub.get("children").is_none(), "{bought}"); +} + #[test] fn a_phantom_counts_what_it_holds_in_its_parent_merged_with_the_same_parts() { // A fastener set (no bodies) of two screws, placed three times, and one more screw placed directly. diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 1ea32cb0a..c75286f6e 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -11,26 +11,42 @@ use std::collections::BTreeMap; use serde_json::{Value, json}; -use solidcraft_doc::FeatureKind; +use solidcraft_doc::{BrowserEntry, FeatureKind, MAX_GROUP_NESTING}; use super::CommandSpec; -use crate::params::{bad, bool_, str_}; +use super::features::{add_feature, check_expr}; +use crate::params::{bad, bool_, expr, str_}; +use crate::schema::browser::{DocumentUnitsParams, DocumentUnitsResult, RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; +const REPAIR_CONTRACT: TypedContract = TypedContract::new(); +const UNITS_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("body.rename", "Rename Body", rename_body).icon("rename").params("body: its name, name: the new name (features that use the body follow)"), + // The import and failed operations offer it for a part the modelling kernel refuses. + CommandSpec::new("body.repair", "Repair Part", crate::checked!("body.repair", repair_body)) + .icon("body") + .contract(&REPAIR_CONTRACT) + .output(output_schema_for::) + .params( + "body: its name (a part the modelling kernel refuses, or an open part that should be a solid); gap?: expr (default 0.2 mm, at most 1 mm: free edges that pair up within it are sewn, each sewn edge carrying its own gap as its tolerance); patch_holes?: bool (default false: loops of free edges left are patched, in the plane of the faces around them where those are that plane, else tangent to them, and sewn in; otherwise the reply offers the patches); name? → the feature, and repair: what changed face by face (rebuilt and refused faces, sewn gaps, holes with their surface.patch), faces and largest edge tolerance before and after, closed, modelling, volume. Refused with why when nothing applies", + ), CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", redefine_sketch) .icon("plane") .params("sketch: id or name; plane: as sketch.create; frame?: as sketch.create; author_path?: exact owner occurrence ids; explicitly rebinds or freezes the plane while preserving geometry and dimension names"), CommandSpec::new("browser.group", "New Group", group) .icon("folder") - .params("folder: bodies|sketches|construction; component?: id (default 0); name?; items?: [keys] (they leave other groups)"), - CommandSpec::new("browser.ungroup", "Ungroup", ungroup).icon("folder").params("group: id (its items go back to the folder)"), + .params("folder?: bodies|sketches|construction; component?: id (default 0); parent?: group id (the new group nests in it, taking its component and folder; at most 8 levels); name?; items?: [keys] (they leave other groups)"), + CommandSpec::new("browser.ungroup", "Ungroup", ungroup).icon("folder").params("group: id (its items and child groups go up to the group that holds it, or the folder)"), CommandSpec::new("browser.rename_group", "Rename Group", rename_group).icon("rename").params("group: id, name"), CommandSpec::new("browser.move", "Move Browser Items", move_items).icon("reorder") - .params("folder, component?, items: [keys]; group?: id (into it; omit to take them out of groups); before?: key (position in the group)"), - CommandSpec::new("document.units", "Change Design Units", document_units) + .params("folder, component?, items: [keys (strings) and group ids (numbers)]; group?: id (into it; omit for the folder's top level); before?: key or group id (position in it; default the end). A group cannot go into itself or past 8 levels"), + CommandSpec::new("document.units", "Change Design Units", crate::checked!("document.units", document_units)) .icon("settings") + .contract(&UNITS_CONTRACT) + .output(crate::schema::output_schema_for::) .params("units: mm|cm|m|in|ft (display and unit-less parameters; values keep their meaning)"), CommandSpec::new("view.save", "New Named View", view_save) .icon("camera") @@ -41,14 +57,14 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("view.apply", "Restore Named View", view_apply).icon("camera").noundo().params( "view?: front|back|top|bottom|left|right|iso|home (frames the model) | a named view's name; or camera?: {target: [x,y,z], yaw, pitch, distance, fov?, roll?} (radians, mm, about the up axis; yaw: heading of the line of sight, 0 along +Y (Front), π/2 along +X (Left), π (Back), −π/2 (Right); pitch: the eye's elevation, within ±π/2, π/2 = Top; roll defaults to 0, turns the picture clockwise, must be finite and is clamped to ±π; the View angles readout shows these in degrees; up is refused: the up axis comes from the design settings) → camera. The viewport (and the MCP screenshot) moves there. View state: not saved, not an undo step", ), - CommandSpec::new("browser.order", "Order Browser Items", order).icon("reorder").params("folder, component?, order: [keys] (the folder's items in display order)"), + CommandSpec::new("browser.order", "Order Browser Items", order).icon("reorder").params("folder: bodies|sketches|construction|components, component?, order: [keys (strings) and top-level group ids (numbers)] (display order; for `components`, the ids of the components placed in it)"), CommandSpec::new("browser.visibility", "Show/Hide", visibility).icon("eye").params( "visible: bool; items?: [sketch id or name | body name | construction name | joint name | O|X|Y|Z|XY|XZ|YZ]; \ or joints?: [joint id or name] (their glyphs; they still constrain and move parts); \ or features?: [feature id or name] (the bodies they made; path?: [occurrence ids] for only that placement's); \ or folder?: bodies|sketches|construction|origin|joints|all (all of it; showing also shows its browser folders and groups, and `all` takes in the occurrence hides too); \ or tree_folders?: [browser folder or group key: c0/bodies, o:4/sketches, c0/g7, c0/joints, c0/canvases, c0/point_clouds] (the folder or group itself: its items keep their own state); \ - or paths?: [[occurrence ids]] (exact placements and descendants), isolate?: bool (requires paths and visible:true). Saved with the design and undone like any other change (the camera is not)", + or paths?: [[occurrence ids]] (exact placements and descendants), isolate?: bool (with paths or items of bodies, and visible:true: everything else is hidden, other placements as placements). Saved with the design and undone like any other change (the camera is not)", ), CommandSpec::new("browser.expand_all", "Expand All", expand_all).icon("folder").noundo().params( "path?: [occurrence ids] (that placement and its descendants); component?: id (that component's own folders); \ @@ -98,11 +114,102 @@ fn group_id(s: &Session, p: &Value, cmd: &str) -> Result { if s.doc.browser_groups.iter().any(|g| g.id == id) { Ok(id) } else { Err(bad(cmd, format!("no group {id}"))) } } +/// A list of groups (numbers) and items (strings): a number is always a group. +fn entries(p: &Value, k: &str, cmd: &str) -> Result> { + let list = match p.get(k) { + Some(Value::Array(a)) => a + .iter() + .map(|x| match x { + Value::String(s) => Some(BrowserEntry::Item(s.clone())), + _ => x.as_u64().map(BrowserEntry::Group), + }) + .collect::>>(), + None => Some(Vec::new()), + _ => None, + }; + let list = list.ok_or_else(|| bad(cmd, format!("`{k}` must be a list of item keys (strings) and group ids (numbers)")))?; + if list.len() > 10_000 || list.iter().any(|e| e.as_item().is_some_and(|k| k.is_empty() || k.len() > 256)) { + return Err(bad(cmd, format!("`{k}` has bad keys"))); + } + Ok(list) +} + +/// A number in a list of items or an order names a group; say so when there is none, as a sketch +/// or plane id passed as a number is the likely mistake (item keys are strings). +fn no_group(cmd: &str, id: u64) -> crate::EngineError { + bad(cmd, format!("no group {id} (a number is a group id; pass item keys as strings)")) +} + +/// The group a command names under `key`, if it names one (`null` or absent: none). +fn optional_group(s: &Session, p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let id = v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a group id")))?; + if s.doc.browser_group(id).is_some() { Ok(Some(id)) } else { Err(no_group(cmd, id)) } + } + } +} + +/// The list a group's contents (or the folder's top level, `None`) are ordered by. +fn holder_list<'a>(d: &'a mut solidcraft_doc::Document, component: u64, folder: &str, holder: Option) -> Option<&'a mut Vec> { + match holder { + Some(g) => d.browser_groups.iter_mut().find(|x| x.id == g).map(|g| &mut g.items), + None => Some(d.browser_order.entry(format!("{component}/{folder}")).or_default()), + } +} + +/// Name every group under `holder` in its list, where they are drawn, so a position among them +/// can be found. +fn settle(d: &mut solidcraft_doc::Document, component: u64, folder: &str, holder: Option) { + let all = d.ordered_entries(component, folder, holder); + if let Some(list) = holder_list(d, component, folder, holder) { + *list = all; + } +} + +/// Take entries out of every list of a component's folder: its groups' and the top level's. +fn take_out(d: &mut solidcraft_doc::Document, component: u64, folder: &str, gone: &[BrowserEntry]) { + for g in d.browser_groups.iter_mut().filter(|g| g.component == component && g.folder == folder) { + g.items.retain(|e| !gone.contains(e)); + } + if let Some(list) = d.browser_order.get_mut(&format!("{component}/{folder}")) { + list.retain(|e| !gone.contains(e)); + if list.is_empty() { + d.browser_order.remove(&format!("{component}/{folder}")); + } + } +} + fn group(s: &mut Session, p: &Value) -> Result { let cmd = "browser.group"; - let folder = folder_of(p, cmd)?; - let component = component_of(s, p, cmd)?; - let items = keys(p, "items", cmd)?; + let parent = optional_group(s, p, "parent", cmd)?; + let (mut component, mut folder) = (None, None); + if let Some(g) = parent.and_then(|g| s.doc.browser_group(g)) { + // Omitted, they come from the parent; given, they must agree with it. + if p.get("component").is_some() && component_of(s, p, cmd)? != g.component { + return Err(bad(cmd, "`parent` belongs to another component")); + } + if p.get("folder").is_some() && folder_of(p, cmd)? != g.folder { + return Err(bad(cmd, "`parent` belongs to another folder")); + } + if s.doc.group_level(g.id) >= MAX_GROUP_NESTING { + return Err(bad(cmd, format!("groups nest at most {MAX_GROUP_NESTING} levels"))); + } + (component, folder) = (Some(g.component), Some(g.folder.clone())); + } + let folder = match folder { + Some(f) => f, + None => folder_of(p, cmd)?, + }; + let component = match component { + Some(c) => c, + None => component_of(s, p, cmd)?, + }; + let items = match entries(p, "items", cmd)?.into_iter().map(|e| e.as_item().map(str::to_string)).collect::>>() { + Some(items) => items, + None => return Err(bad(cmd, "`items` are item keys: move groups with browser.move")), + }; let d = s.doc_mut(); let id = d.allocate_id()?; let name = match str_(p, "name").map(str::trim).filter(|n| !n.is_empty()) { @@ -110,16 +217,32 @@ fn group(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "`name` is too long")), None => format!("Group{}", d.browser_groups.iter().filter(|g| g.folder == folder).count() + 1), }; - for g in d.browser_groups.iter_mut().filter(|g| g.component == component && g.folder == folder) { - g.items.retain(|k| !items.contains(k)); - } - d.browser_groups.push(solidcraft_doc::BrowserGroup { id, name: name.clone(), component, folder, items }); - Ok(json!({ "group": id, "name": name })) + let gone: Vec = items.iter().map(|k| BrowserEntry::item(k)).collect(); + take_out(d, component, &folder, &gone); + let items = gone; + d.browser_groups.push(solidcraft_doc::BrowserGroup { id, name: name.clone(), component, folder, parent, items }); + Ok(json!({ "group": id, "name": name, "parent": parent })) } +/// A group's contents go up to the group that holds it (the folder's top level for a top-level +/// group), in the place the group had; so do its child groups. Its own entry goes. fn ungroup(s: &mut Session, p: &Value) -> Result { let id = group_id(s, p, "browser.ungroup")?; - s.doc_mut().browser_groups.retain(|g| g.id != id); + let d = s.doc_mut(); + let Some(g) = d.browser_group(id).cloned() else { return Ok(json!({ "group": id })) }; + settle(d, g.component, &g.folder, Some(id)); + settle(d, g.component, &g.folder, g.parent); + let inside = d.browser_group(id).map(|g| g.items.clone()).unwrap_or_default(); + for child in d.browser_groups.iter_mut().filter(|c| c.parent == Some(id)) { + child.parent = g.parent; + } + if let Some(list) = holder_list(d, g.component, &g.folder, g.parent) + && let Some(at) = list.iter().position(|e| *e == BrowserEntry::Group(id)) + { + list.splice(at..=at, inside); + } + take_out(d, g.component, &g.folder, &[BrowserEntry::Group(id)]); + d.browser_groups.retain(|x| x.id != id); Ok(json!({ "group": id })) } @@ -138,43 +261,91 @@ fn move_items(s: &mut Session, p: &Value) -> Result { let cmd = "browser.move"; let folder = folder_of(p, cmd)?; let component = component_of(s, p, cmd)?; - let items = keys(p, "items", cmd)?; + let items = entries(p, "items", cmd)?; if items.is_empty() { - return Err(bad(cmd, "`items` must list item keys")); + return Err(bad(cmd, "`items` must list item keys or group ids")); } - let to = match p.get("group") { - Some(Value::Null) | None => None, - Some(_) => Some(group_id(s, p, cmd)?), - }; + let to = optional_group(s, p, "group", cmd)?; if let Some(g) = to && !s.doc.browser_groups.iter().any(|x| x.id == g && x.component == component && x.folder == folder) { return Err(bad(cmd, "that group is in another folder")); } - let before = str_(p, "before").map(str::to_string); - let d = s.doc_mut(); - for g in d.browser_groups.iter_mut().filter(|g| g.component == component && g.folder == folder) { - g.items.retain(|k| !items.contains(k)); - if Some(g.id) == to { - let at = before.as_ref().and_then(|b| g.items.iter().position(|k| k == b)).unwrap_or(g.items.len()); - for (i, k) in items.iter().enumerate() { - g.items.insert(at + i, k.clone()); - } + let to_level = to.map_or(0, |g| s.doc.group_level(g)); + for e in &items { + let BrowserEntry::Group(id) = e else { continue }; + let Some(g) = s.doc.browser_group(*id) else { return Err(no_group(cmd, *id)) }; + if g.component != component || g.folder != folder { + return Err(bad(cmd, format!("group {id} is in another folder"))); } + if to.is_some_and(|t| s.doc.group_within(t, *id)) { + return Err(bad(cmd, format!("group {id} cannot go inside itself"))); + } + if to_level + s.doc.group_height(*id) > MAX_GROUP_NESTING { + return Err(bad(cmd, format!("groups nest at most {MAX_GROUP_NESTING} levels"))); + } + } + let before = match p.get("before") { + None | Some(Value::Null) => None, + Some(Value::String(k)) => Some(BrowserEntry::Item(k.clone())), + Some(v) => { + let id = v.as_u64().ok_or_else(|| bad(cmd, "`before` must be an item key or a group id"))?; + if s.doc.browser_group(id).is_none() { + return Err(no_group(cmd, id)); + } + Some(BrowserEntry::Group(id)) + } + }; + let d = s.doc_mut(); + // Where a group list is silent about its child groups, the ones it names come first: name + // them all, so `before` can be one of them. + settle(d, component, &folder, to); + take_out(d, component, &folder, &items); + for e in &items { + if let BrowserEntry::Group(id) = e + && let Some(g) = d.browser_groups.iter_mut().find(|g| g.id == *id) + { + g.parent = to; + } + } + if let Some(list) = holder_list(d, component, &folder, to) { + let at = before.as_ref().and_then(|b| list.iter().position(|e| e == b)).unwrap_or(list.len()); + list.splice(at..at, items.iter().cloned()); } Ok(json!({ "items": items, "group": to })) } fn order(s: &mut Session, p: &Value) -> Result { let cmd = "browser.order"; - let folder = folder_of(p, cmd)?; let component = component_of(s, p, cmd)?; - let order = keys(p, "order", cmd)?; + let components = str_(p, "folder") == Some("components"); + let folder = if components { "components".to_string() } else { folder_of(p, cmd)? }; + let order = entries(p, "order", cmd)?; + for e in &order { + match e { + // Sub-components, by placement id, all of them placed in this component. + BrowserEntry::Item(k) if components => { + let placed = k.parse::().ok().is_some_and(|o| s.doc.occurrences.iter().any(|x| x.id == o && x.parent == component)); + if !placed { + return Err(bad(cmd, "the `components` folder is ordered by the ids of the components placed in it")); + } + } + BrowserEntry::Item(_) => {} + BrowserEntry::Group(id) => match s.doc.browser_group(*id) { + None => return Err(no_group(cmd, *id)), + Some(g) if components || g.component != component || g.folder != folder || g.parent.is_some() => { + return Err(bad(cmd, format!("group {id} is not a top-level group of this folder"))); + } + Some(_) => {} + }, + } + } let key = format!("{component}/{folder}"); let d = s.doc_mut(); if order.is_empty() { d.browser_order.remove(&key); } else { + // An item that sits in a group belongs to the group's list only. d.browser_order.insert(key, order); } Ok(json!({})) @@ -196,29 +367,30 @@ fn is_construction(k: &FeatureKind) -> bool { matches!(k, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. }) } -/// The item a key names, or `None` when it names none. +/// The item a key names, or `None` when it names none; bodies are looked for in the placed model +/// `world`. /// /// The rule, the same for showing and for hiding: an exact name wins over a name that only /// matches it by case, so the body called "Back Lid" is not the sketch called "Back lid" /// (#6967). Among the exact matches the order is the one there always was: a feature (by id /// or by name), then a body, then a joint. With no exact match the name is compared without /// regard to case, as it always was: a feature first, then an origin item. -fn shown_item(s: &Session, key: &str) -> Option { - shown_item_exact(s, key).or_else(|| shown_item_ignore_case(s, key)) +fn shown_item(s: &Session, world: &solidcraft_doc::ModelState, key: &str) -> Option { + shown_item_exact(s, world, key).or_else(|| shown_item_ignore_case(s, world, key)) } /// The item a key names exactly: a feature, a body or a joint whose name is the key itself. -fn shown_item_exact(s: &Session, key: &str) -> Option { +fn shown_item_exact(s: &Session, world: &solidcraft_doc::ModelState, key: &str) -> Option { // A feature is found by id or by name, as `find_feature` does, but the name must be the // key itself here. let feature = match key.parse::() { Ok(id) => s.doc.feature(id).or_else(|| s.doc.features.iter().find(|f| f.name == key)), Err(_) => s.doc.features.iter().find(|f| f.name == key), }; - if let Some(shown) = feature.and_then(|f| shown_feature(s, f, key)) { + if let Some(shown) = feature.and_then(|f| shown_feature(world, f, key)) { return Some(shown); } - if s.world_state().bodies.iter().any(|b| b.name == key) { + if world.bodies.iter().any(|b| b.name == key) { return Some(Shown::Body(key.to_string())); } s.doc.assembly.joints.iter().find(|j| j.name == key).map(|j| Shown::Joint(j.id)) @@ -226,8 +398,8 @@ fn shown_item_exact(s: &Session, key: &str) -> Option { /// The item a key names when nothing matches it exactly: the name is compared without regard to /// case, as it always was. -fn shown_item_ignore_case(s: &Session, key: &str) -> Option { - if let Some(shown) = s.doc.find_feature(key).and_then(|f| shown_feature(s, f, key)) { +fn shown_item_ignore_case(s: &Session, world: &solidcraft_doc::ModelState, key: &str) -> Option { + if let Some(shown) = s.doc.find_feature(key).and_then(|f| shown_feature(world, f, key)) { return Some(shown); } ORIGIN.iter().find(|o| o.eq_ignore_ascii_case(key)).map(|o| Shown::Origin(o.to_string())) @@ -236,12 +408,12 @@ fn shown_item_ignore_case(s: &Session, key: &str) -> Option { /// The item a feature is: a sketch, or construction geometry by name. A feature that is neither /// (an extrude, a fillet) is not an item of its own, and the key goes on to the next kind. A /// sketch that shares its name with a body is the body's (#7206). -fn shown_feature(s: &Session, f: &solidcraft_doc::Feature, key: &str) -> Option { +fn shown_feature(world: &solidcraft_doc::ModelState, f: &solidcraft_doc::Feature, key: &str) -> Option { if matches!(f.kind, FeatureKind::Sketch { .. }) { // A sketch and a body with exactly the same name, a sketch named after the body it // makes (#7206): the name is the body's. The browser names a sketch by its id and a // body only by its name, so the body could not be reached otherwise. - if f.name == key && s.world_state().bodies.iter().any(|b| b.name == key) { + if f.name == key && world.bodies.iter().any(|b| b.name == key) { return Some(Shown::Body(key.to_string())); } return Some(Shown::Sketch(f.id)); @@ -264,6 +436,89 @@ fn tree_folder_key(k: &str) -> bool { k.len() <= 2048 && scope_ok && last_ok } +/// Isolate bodies (#7896): the picked bodies stay, and so do the placements that hold them, down +/// to their own; those placements' other bodies and the root's other bodies are hidden one by +/// one, and every other placement is hidden as a placement, so its Browser row shows it is off and +/// its eye brings it back. +fn isolate_bodies(s: &mut Session, p: &Value, visible: bool) -> Result { + let cmd = "browser.visibility"; + if !visible { + return Err(bad(cmd, "isolate requires visible:true")); + } + if ["folder", "features", "joints"].iter().any(|k| p.get(*k).is_some()) { + return Err(bad(cmd, "isolate takes `paths` or `items` (bodies)")); + } + let keys = keys(p, "items", cmd)?; + if keys.is_empty() { + return Err(bad(cmd, "isolate needs `paths` or `items` (bodies)")); + } + let world = s.world_state()?; + let keep: Vec = keys + .iter() + .map(|k| match shown_item(s, &world, k) { + Some(Shown::Body(name)) => Ok(name), + _ => Err(bad(cmd, format!("no body `{k}`"))), + }) + .collect::>()?; + let mut hidden_bodies: Vec = + s.model.state().bodies.iter().filter(|b| s.doc.model_body_component(b) == 0 && !keep.contains(&b.name)).map(|b| b.name.clone()).collect(); + let mut hidden = Vec::new(); + let mut stack = vec![Vec::::new()]; + let mut count = 0; + while let Some(parent) = stack.pop() { + for child in s.occurrence_children(&parent)? { + count += 1; + if count > 100_000 { + return Err(bad(cmd, "isolate exceeds 100000 placements")); + } + if s.occurrence_bodies_shared(&child.path, true)?.iter().any(|b| keep.contains(b)) { + hidden_bodies.extend(child.bodies.into_iter().map(|b| b.world).filter(|b| !keep.contains(b))); + stack.push(child.path); + } else { + hidden.push(child.path); + } + } + } + // A hidden Bodies folder or group a picked body is in would keep it hidden: those show + // again. Their other bodies are hidden one by one above, as the root's are. + let shown_folders = folders_holding(s, &keep); + s.visibility.hidden_folders.retain(|k| !shown_folders.contains(k)); + s.visibility.hidden_occurrences = hidden; + s.visibility.hidden_bodies = hidden_bodies; + s.refresh_display(); + Ok(json!({"visible":true,"isolated":keep,"visibility":s.visibility})) +} + +/// The tree keys of the Bodies folders and groups (with the groups they are in) that hold the +/// bodies named `world` in some placement. +fn folders_holding(s: &Session, world: &[String]) -> std::collections::BTreeSet { + let mut keys = std::collections::BTreeSet::new(); + if s.visibility.hidden_folders.is_empty() { + return keys; + } + let st = s.model.state(); + let names = solidcraft_doc::WorldNames::new(&s.doc, &st); + // Each body's component, found once rather than once per placement. + let owned: Vec<(u64, &str)> = s.doc.model_body_components(&st).into_iter().zip(st.bodies.iter().map(|b| b.name.as_str())).collect(); + for (component, path, _) in s.doc.placements() { + let scope = Session::folder_scope(&path); + for b in owned.iter().filter(|(c, _)| *c == component).map(|(_, name)| *name) { + if !world.contains(&names.name(b, component, &path)) { + continue; + } + keys.insert(format!("{scope}/bodies")); + for g in s.doc.browser_groups.iter().filter(|g| g.component == component && g.folder == "bodies" && g.has_item(b)) { + for id in std::iter::successors(Some(g.id), |id| s.doc.browser_group(*id).and_then(|g| g.parent)) + .take(solidcraft_doc::MAX_GROUP_NESTING + 1) + { + keys.insert(format!("{scope}/g{id}")); + } + } + } + } + keys +} + fn visibility(s: &mut Session, p: &Value) -> Result { let cmd = "browser.visibility"; let visible = bool_(p, "visible").ok_or_else(|| bad(cmd, "`visible` must be true or false"))?; @@ -353,6 +608,9 @@ fn visibility(s: &mut Session, p: &Value) -> Result { s.refresh_display(); return Ok(json!({"visible":visible,"changed":paths.len(),"visibility":s.visibility})); } + if bool_(p, "isolate").unwrap_or(false) { + return isolate_bodies(s, p, visible); + } let items: Vec = match (str_(p, "folder"), p.get("items")) { _ if p.get("features").is_some() => { if ["items", "folder", "joints"].iter().any(|k| p.get(*k).is_some()) { @@ -372,7 +630,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result { list.iter().map(|j| super::joints::joint_id(s, Some(j), cmd).map(Shown::Joint)).collect::>()? } (Some(_), Some(_)) => return Err(bad(cmd, "give `items` or `folder`, not both")), - (Some("bodies"), None) => s.world_state().bodies.iter().map(|b| Shown::Body(b.name.clone())).collect(), + (Some("bodies"), None) => s.world_state()?.bodies.iter().map(|b| Shown::Body(b.name.clone())).collect(), (Some("sketches"), None) => s.model.state().sketches.iter().map(|x| Shown::Sketch(x.feature)).collect(), (Some("construction"), None) => s.doc.features.iter().filter(|f| is_construction(&f.kind)).map(|f| Shown::Origin(f.name.clone())).collect(), (Some("origin"), None) => ORIGIN.iter().map(|o| Shown::Origin(o.to_string())).collect(), @@ -380,7 +638,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result { // Everything at once, for a single "show all" step: every body, sketch, construction // item, origin item and joint. (Some("all"), None) => { - let mut all: Vec = s.world_state().bodies.iter().map(|b| Shown::Body(b.name.clone())).collect(); + let mut all: Vec = s.world_state()?.bodies.iter().map(|b| Shown::Body(b.name.clone())).collect(); all.extend(s.model.state().sketches.iter().map(|x| Shown::Sketch(x.feature))); all.extend(s.doc.features.iter().filter(|f| is_construction(&f.kind)).map(|f| Shown::Origin(f.name.clone()))); all.extend(ORIGIN.iter().map(|o| Shown::Origin(o.to_string()))); @@ -394,8 +652,9 @@ fn visibility(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`items` must list sketches, bodies or construction geometry")); } // Every item is found before anything changes. + let world = s.world_state()?; keys.iter() - .map(|k| shown_item(s, k).ok_or_else(|| bad(cmd, format!("no sketch, body, construction item or joint `{k}`")))) + .map(|k| shown_item(s, &world, k).ok_or_else(|| bad(cmd, format!("no sketch, body, construction item or joint `{k}`")))) .collect::>()? } (None, None) => return Err(bad(cmd, "`items` or `folder` is required")), @@ -411,6 +670,10 @@ fn visibility(s: &mut Session, p: &Value) -> Result { s.visibility.hidden_folders.retain(|k| !k.ends_with(&own) && !groups.iter().any(|g| k.ends_with(g.as_str()))); } } + // Only a sketch a feature uses is kept shown on its own: one nothing uses yet is shown anyway, + // and marking it would keep it shown once an Extrude uses it (#9954). + let used: Vec = + items.iter().filter_map(|it| if let Shown::Sketch(id) = it { crate::view::sketch_consumed(s, *id).then_some(*id) } else { None }).collect(); let v = &mut s.visibility; match str_(p, "folder") { Some("bodies" | "all") if visible => { @@ -429,7 +692,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result { Shown::Sketch(id) => { if visible { v.hidden_sketches.retain(|x| x != id); - if !v.shown_sketches.contains(id) { + if used.contains(id) && !v.shown_sketches.contains(id) { v.shown_sketches.push(*id); } } else { @@ -670,8 +933,11 @@ fn document_units(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`units` must be mm, cm, m, in or ft")); } let old = s.doc.units.clone(); + let reply = |kept: Vec| { + serde_json::to_value(DocumentUnitsResult { units: u.to_string(), kept, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string())) + }; if old == u { - return Ok(json!({ "units": u, "kept": [] })); + return reply(Vec::new()); } // What the geometry reads: every feature's length inputs. let matched_configuration = s.doc.configuration_matches().then(|| s.doc.configs.active.clone()).flatten(); @@ -712,7 +978,7 @@ fn document_units(s: &mut Session, p: &Value) -> Result { s.doc_mut().apply_configuration(&row)?; } s.settle_value_edit(&solved)?; - Ok(json!({ "units": u, "kept": kept })) + reply(kept) } fn view_save(s: &mut Session, p: &Value) -> Result { @@ -764,9 +1030,9 @@ fn view_apply(s: &mut Session, p: &Value) -> Result { // Standard view names come first, as in the browser's Named Views folder. (Some(name), None) => match crate::render::StandardView::parse(name) { Some(sv) => { - let mut c = crate::view::home_camera(s); + let mut c = crate::view::home_camera(s)?; c.set_view(sv); - c.fit(&crate::view::bounds(s)); + c.fit(&crate::view::bounds(s)?); c } None => s.doc.named_views.iter().find(|v| v.name == name).map(camera_of).ok_or_else(|| bad(cmd, format!("no named view `{name}`")))?, @@ -852,9 +1118,83 @@ pub(crate) fn counted(f: &solidcraft_doc::Feature, i: usize) -> bool { f.body_names.get(i).is_none_or(|n| n.trim().is_empty()) && (f.shell_piece_order || i < f.body_names.len() || !first) } +/// Repair Part (#8371): a feature, which repairs the part as it evaluates (a part with nothing +/// to repair fails it, with why, and the command changes nothing); the reply is what that +/// evaluation changed, face by face. +fn repair_body(s: &mut Session, p: &Value) -> Result { + use solidcraft_doc::expr::Kind; + use solidcraft_kernel::{Continuity, SurfaceKind}; + let cmd = "body.repair"; + let name = str_(p, "body").filter(|b| !b.trim().is_empty()).ok_or_else(|| bad(cmd, "`body` must name the part to repair"))?.to_string(); + let state = s.model.state(); + let source = state.body(&name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?; + if source.body.is_mesh() { + return Err(bad(cmd, "a mesh body has no faces to repair: convert it first")); + } + let gap = expr(p, "gap").unwrap_or_else(|| "0.2 mm".into()); + check_expr(s, &gap, Kind::Length, cmd, "gap")?; + let patch_holes = bool_(p, "patch_holes").unwrap_or(false); + let v = add_feature(s, p, FeatureKind::Repair { body: name.clone().into(), gap, patch_holes })?; + let field = |k: &str| v.get(k).cloned().unwrap_or(Value::Null); + let feature = field("feature").as_u64().unwrap_or(0); + let report = s + .model + .result(feature) + .and_then(|r| r.repair.clone()) + .ok_or_else(|| crate::EngineError::Other(format!("{cmd}: the feature kept no report of the repair")))?; + let repaired = s.model.state().body(&name).map(|b| b.body.clone()); + let volume = repaired.filter(|_| report.closed).and_then(|b| solidcraft_kernel::measure(&b).ok()).map(|m| m.volume); + let surface = |k: SurfaceKind| format!("{k:?}").to_lowercase(); + let face = |face: usize, k: SurfaceKind, why: &str| RepairFace { face, surface: surface(k), why: why.to_string() }; + let done = RepairDone { + rebuilt: report.rebuilt.iter().map(|r| face(r.face, r.surface, &r.why)).collect(), + refused: report.refused.iter().map(|r| face(r.face, r.surface, &r.why)).collect(), + sewn: report.sewn.iter().map(|g| RepairSewn { faces: g.faces, gap: g.gap, at: [g.at.x, g.at.y, g.at.z] }).collect(), + holes: report + .holes + .iter() + .map(|h| { + let g = if h.continuity == Continuity::G0 { "g0" } else { "g1" }; + let edges: Vec<[f64; 3]> = h.edges.iter().map(|q| [q.x, q.y, q.z]).collect(); + RepairHole { + faces: h.faces.clone(), + continuity: g.into(), + patched: h.patched, + why: h.why.clone(), + patch: json!({"command": "surface.patch", "params": {"body": name, "edges": edges, "continuity": g}}), + } + }) + .collect(), + faces: report.faces, + largest_edge_tolerance: report.largest_edge_tolerance, + closed: report.closed, + modelling: report.modelling, + volume, + }; + let list = + |k: &str| v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); + let reply = RepairResult { + feature, + name: field("name").as_str().unwrap_or_default().to_string(), + bodies: list("bodies"), + created_bodies: list("created_bodies"), + changed_bodies: list("changed_bodies"), + removed_bodies: list("removed_bodies"), + warning: field("warning").as_str().map(str::to_string), + ms: field("ms").as_f64(), + repair: done, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + fn rename_body(s: &mut Session, p: &Value) -> Result { let cmd = "body.rename"; - let old = str_(p, "body").ok_or_else(|| bad(cmd, "`body` must be a body name"))?.to_string(); + let given = str_(p, "body").ok_or_else(|| bad(cmd, "`body` must be a body name"))?; + // A placed copy's name (`KB (K:2)`, the name the browser lists a pasted placement's body by) + // means the body it shows, as appearance.assign takes it (#9740): renaming it renames that body, + // in every placement of its component (#10017). + let old = s.own_body_name(given).ok_or_else(|| bad(cmd, format!("no body `{given}`")))?; let name = str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` must be 1…128 characters"))?; if name == old { @@ -979,9 +1319,6 @@ fn rename_body(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, e)); } d.rename_body_keys(&old, name); - for b in s.visibility.locked_bodies.iter_mut().filter(|b| **b == old) { - *b = name.to_string(); - } s.remember_body_rename(&previous, &old, name); Ok(json!({"body": old, "name": name})) } @@ -1113,6 +1450,69 @@ mod tests { s.model.state().bodies.iter().map(|b| b.name.clone()).collect() } + /// #10017: a pasted placement's body is listed by its placed name (`KB (K:2)`), and Rename + /// sends that name. It renames the body that placement shows, so both placements show the new + /// name; a name that is neither a body's nor a placed copy's is still refused. + #[test] + fn a_placed_copys_body_renames_by_its_placed_name() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "K"})); + run(&mut s, "solid.box", json!({"body_name": "KB", "length": 10, "width": 10, "height": 10})); + run(&mut s, "occurrence.copy", json!({"component": "K", "translate": [30, 0, 0]})); + // The copy hidden first stays hidden under its new name, and one undo brings both names + // back. + run(&mut s, "browser.visibility", json!({"items": ["KB (K:2)"], "visible": false})); + let r = run(&mut s, "body.rename", json!({"body": "KB (K:2)", "name": "Lid"})); + assert_eq!((r["body"].as_str(), r["name"].as_str()), (Some("KB"), Some("Lid")), "{r}"); + let world = |s: &Session| s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect::>(); + let renamed = world(&s); + assert!(renamed.iter().any(|n| n == "Lid") && renamed.iter().any(|n| n == "Lid (K:2)"), "{renamed:?}"); + assert!(!renamed.iter().any(|n| n.starts_with("KB")), "{renamed:?}"); + assert!(!s.body_visible("Lid (K:2)") && s.body_visible("Lid"), "{:?}", s.visibility.hidden_bodies); + assert!(s.execute("body.rename", &json!({"body": "Lid (K:9)", "name": "Other"})).is_err()); + run(&mut s, "edit.undo", json!({})); + let back = world(&s); + assert!(back.iter().any(|n| n == "KB") && back.iter().any(|n| n == "KB (K:2)"), "{back:?}"); + } + + #[test] + fn repair_part_patches_a_missing_face_as_one_undoable_feature() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); + run(&mut s, "surface.unstitch", json!({"body": "Box", "faces": [[5, 5, 10]]})); + let open = |s: &Session| s.model.state().body("Box").is_some_and(|b| b.body.is_surface()); + assert!(open(&s)); + // A hole alone: nothing is sewn, and the reason names the hole. + let err = s.execute("body.repair", &json!({"body": "Box"})).unwrap_err().to_string(); + assert!(err.contains("a loop of 4 edges"), "{err}"); + let features = s.doc.features.len(); + let v = run(&mut s, "body.repair", json!({"body": "Box", "patch_holes": true})); + assert_eq!(s.doc.features.len(), features + 1); + let done = &v["repair"]; + assert_eq!(done["holes"][0]["patched"], json!(true), "{v}"); + assert_eq!(done["holes"][0]["continuity"], json!("g0"), "{v}"); + assert_eq!(done["holes"][0]["patch"]["command"], json!("surface.patch"), "{v}"); + assert_eq!(done["faces"], json!([5, 6])); + assert_eq!((done["closed"].clone(), done["modelling"].clone()), (json!(true), json!(true))); + assert!((done["volume"].as_f64().unwrap() - 1000.0).abs() < 1e-6, "{v}"); + assert_eq!(v["changed_bodies"], json!(["Box"])); + assert!(!open(&s)); + // Saved and opened again, the feature repairs the part again. + let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(cold.model.state().body("Box").is_some_and(|b| !b.body.is_surface())); + run(&mut s, "edit.undo", json!({})); + assert!(open(&s)); + // A solid with nothing to repair, an unknown body, a gap out of range: refused, nothing added. + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "Solid"})); + for p in + [json!({"body": "Solid"}), json!({"body": "Nope"}), json!({}), json!({"body": "Box", "gap": "5 mm"}), json!({"body": "Box", "gap": "-1"})] + { + let n = s.doc.features.len(); + assert!(s.execute("body.repair", &p).is_err(), "{p}"); + assert_eq!(s.doc.features.len(), n, "{p}"); + } + } + #[test] fn body_rename_preserves_plastic_rules_and_current_visibility_through_history() { let mut s = Session::default(); @@ -1163,6 +1563,127 @@ mod tests { assert!(!s.body_visible("Stud")); } + /// Two 5 mm boxes, `A` and `B`, as the #9737 repro script makes them. + fn two_boxes(s: &mut Session) { + run(s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "A"})); + run(s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [10, 0, 0], "body_name": "B"})); + } + + fn delete_selection(s: &mut Session) -> Value { + let items: Vec = s.selection.iter().map(|x| serde_json::to_value(x).unwrap()).collect(); + match s.execute("selection.delete", &json!({"items": items})) { + Ok(v) => v, + Err(e) => panic!("selection.delete: {e}"), + } + } + + #[test] + fn selection_follows_body_rename_and_delete_hits_the_renamed_body() { + // #9737: after renaming a selected body the selection is the new name, and Delete + // deletes it — the "nothing to delete" and the wrong-body delete are both gone. + let mut s = Session::default(); + two_boxes(&mut s); + run(&mut s, "select.set", json!({"items": [{"type": "body", "name": "A"}]})); + run(&mut s, "body.rename", json!({"body": "A", "name": "Renamed"})); + assert_eq!(s.selection, vec![crate::Sel::Body { name: "Renamed".into() }]); + delete_selection(&mut s); + assert_eq!(names(&s), ["B"]); + // The old name is free; B takes it, and Delete finds nothing — B is never deleted. + run(&mut s, "body.rename", json!({"body": "B", "name": "A"})); + assert!(s.execute("selection.delete", &json!({"items": []})).is_err()); + assert_eq!(names(&s), ["A"]); + } + + #[test] + fn renaming_the_selection_leaves_the_old_name_for_another_body_to_take() { + // The wrong-body delete, head on: B takes A's name before Delete is pressed. The + // selection followed the rename, so Delete takes `Renamed` and B (now `A`) survives. + let mut s = Session::default(); + two_boxes(&mut s); + run(&mut s, "select.set", json!({"items": [{"type": "body", "name": "A"}]})); + run(&mut s, "body.rename", json!({"body": "A", "name": "Renamed"})); + run(&mut s, "body.rename", json!({"body": "B", "name": "A"})); + assert_eq!(s.selection, vec![crate::Sel::Body { name: "Renamed".into() }]); + delete_selection(&mut s); + assert_eq!(names(&s), ["A"]); + } + + #[test] + fn face_selection_follows_the_body_rename() { + let mut s = Session::default(); + two_boxes(&mut s); + let face = json!({"type": "face", "body": "A", "index": 0, "point": [2.5, 2.5, 0]}); + run(&mut s, "select.set", json!({"items": [face]})); + run(&mut s, "body.rename", json!({"body": "A", "name": "Renamed"})); + assert_eq!(s.selection, vec![crate::Sel::Face { body: "Renamed".into(), index: 0, point: [2.5, 2.5, 0.0].into() }]); + } + + #[test] + fn a_selected_body_that_goes_away_leaves_the_selection() { + // A stale selection is how a later body taking the name gets deleted: once the body + // is gone the selection drops it, at the refresh that removed the body. + let mut s = Session::default(); + two_boxes(&mut s); + run(&mut s, "select.set", json!({"items": [{"type": "body", "name": "A"}]})); + run(&mut s, "solid.remove", json!({"bodies": ["A"]})); + assert!(s.selection.is_empty(), "the gone body must not stay selected: {:?}", s.selection); + } + + #[test] + fn select_set_refuses_a_body_name_that_is_not_there() { + let mut s = Session::default(); + two_boxes(&mut s); + assert!(s.execute("select.set", &json!({"items": [{"type": "body", "name": "NoSuchBody"}]})).is_err()); + assert!(s.selection.is_empty()); + run(&mut s, "select.set", json!({"items": [{"type": "body", "name": "A"}, {"type": "body", "name": "B"}]})); + assert_eq!(s.selection.len(), 2); + } + + /// The viewport asks whether each body is shown several times a frame: a lookup reads the + /// set of hidden bodies, not the list, and follows every change of the list, one written in + /// place included. + #[test] + fn hidden_body_lookups_do_not_walk_the_hidden_body_list() { + use crate::occurrences::visibility_work; + + let mut s = Session::default(); + let hide_many = |s: &mut Session, n: usize| { + s.visibility.hidden_bodies.clear(); + s.visibility.hidden_bodies.extend((0..n).map(|i| format!("Hidden{i}"))); + }; + let walked_by = |s: &Session, name: &str| { + visibility_work::take(); + let visible = s.body_visible(name); + (visible, visibility_work::take()) + }; + hide_many(&mut s, 10); + let (_, few) = walked_by(&s, "Shown"); + hide_many(&mut s, 10_000); + visibility_work::built_take(); + let (visible, many) = walked_by(&s, "Shown"); + assert!(visible); + assert!(many <= few, "a lookup walked {many} entries of 10,000 hidden bodies and {few} of 10"); + assert_eq!(visibility_work::built_take(), 10_000, "the hidden bodies are read into the set once"); + for i in 0..300 { + assert!(walked_by(&s, &format!("Body{i}")) == (true, 0)); + } + assert_eq!(visibility_work::built_take(), 0, "and not again for the next lookups"); + assert!(!s.body_visible("Hidden5000") && !s.body_visible("Hidden9999")); + s.visibility.hidden_bodies.retain(|name| name != "Hidden5000"); + assert!(s.body_visible("Hidden5000"), "shown again in place"); + s.visibility.hidden_bodies.push("Shown".into()); + assert!(!s.body_visible("Shown"), "hidden in place"); + s.visibility.hidden_bodies.clear(); + assert!(s.body_visible("Shown") && s.body_visible("Hidden0"), "all shown"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Peg"})); + run(&mut s, "browser.visibility", json!({"items": ["Peg"], "visible": false})); + assert!(!s.body_visible("Peg")); + run(&mut s, "edit.undo", json!({})); + assert!(s.body_visible("Peg"), "undo shows it again"); + run(&mut s, "edit.redo", json!({})); + assert!(!s.body_visible("Peg"), "redo hides it again"); + } + #[test] fn show_all_bodies_clears_stale_hidden_names() { for folder in ["bodies", "all"] { @@ -1195,6 +1716,51 @@ mod tests { assert!(!s.body_visible("Stud")); } + #[test] + fn body_rename_reusing_a_hidden_name_preserves_visibility_and_history() { + for computed in [false, true] { + for hidden in [false, true] { + let mut s = Session::default(); + two_boxes(&mut s); + let retired = s.doc.features[0].id; + run(&mut s, "browser.visibility", json!({"items": ["A"], "visible": false})); + run(&mut s, "timeline.delete", json!({"feature": retired})); + if hidden { + run(&mut s, "browser.visibility", json!({"items": ["B"], "visible": false})); + } + let before = s.visibility.clone(); + assert_eq!(s.body_visible("B"), !hidden); + if computed { + let mut scratch = s.scratch(); + run(&mut scratch, "body.rename", json!({"body": "B", "name": "A"})); + s.accept_computed(scratch); + } else { + run(&mut s, "body.rename", json!({"body": "B", "name": "A"})); + } + assert_eq!(names(&s), ["A"]); + assert_eq!(s.body_visible("A"), !hidden, "computed={computed}, hidden={hidden}: rename preserves visibility"); + assert_eq!(s.visibility.hidden_bodies, if hidden { vec!["A"] } else { vec![] }); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), ["B"]); + assert_eq!(s.visibility, before, "undo restores the original hidden names, including the deleted body's"); + assert_eq!(s.body_visible("B"), !hidden, "undo must not transfer the stale hide to B"); + if !hidden { + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), ["A", "B"]); + assert!(!s.body_visible("A") && s.body_visible("B"), "restoring the deleted body restores its own visibility"); + run(&mut s, "edit.redo", json!({})); + } + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.body_visible("A"), !hidden, "redo preserves visibility"); + let mut saved = (*s.doc).clone(); + saved.visibility = s.visibility.clone(); + let reopened = Session::new(serde_json::from_str(&serde_json::to_string(&saved).unwrap()).unwrap()); + assert_eq!(names(&reopened), ["A"]); + assert_eq!(reopened.body_visible("A"), !hidden, "reopening preserves visibility"); + } + } + } + #[test] fn renamed_body_keeps_its_users() { let mut s = Session::default(); @@ -1213,6 +1779,90 @@ mod tests { assert_eq!(names(&s)[1], b); } + /// #10123: renaming a piece cut off a frame member must land on that piece after a rebuild, + /// not on the first line's member. The repro is the issue's, verbatim. + #[test] + fn renaming_a_cut_off_frame_piece_lands_on_that_piece_after_rebuild() { + let dir = std::env::temp_dir().join(format!("sc-10123-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let saved = dir.join("rename_repro.sc"); + let mut s = Session::default(); + run(&mut s, "document.units", json!({"units": "in"})); + run( + &mut s, + "timeline.add", + json!({"feature": { + "id": 1, "name": "Lines", "type": "sketch", "suppressed": false, + "plane": {"name": "XY", "type": "origin"}, + "sketch": { + "constraints": [{"id": "k1", "p": 0, "q": 1, "type": "coincident"}], + "counters": {"k": 1, "l": 2}, + "curves": [ + {"a": 1, "b": 2, "construction": false, "id": "l1", "type": "line"}, + {"a": 3, "b": 4, "construction": false, "id": "l2", "type": "line"} + ], + "points": [ + {"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, + {"fixed": false, "id": "l1.start", "pos": [0.0, 0.0]}, + {"fixed": false, "id": "l1.end", "pos": [100.0, 0.0]}, + {"fixed": false, "id": "l2.start", "pos": [0.0, 50.0]}, + {"fixed": false, "id": "l2.end", "pos": [100.0, 50.0]} + ] + } + }}), + ); + run( + &mut s, + "timeline.add", + json!({"feature": { + "id": 2, "name": "Members", "type": "frame_member", "suppressed": false, + "body_names": ["A", "B"], "names": {"l1": "A", "l2": "B"}, "param_names": ["d1"], + "path_sketch": 1, + "profile": {"profile": {"diameter": "10 mm", "kind": "round_bar"}, "source": "library"} + }}), + ); + run( + &mut s, + "timeline.add", + json!({"feature": { + "id": 3, "name": "Cutter", "type": "box", "suppressed": false, + "body_names": ["Cutter"], "corner": [45.0, 40.0, -10.0], + "height": "20 mm", "length": "10 mm", "width": "20 mm", + "operation": "new_body", "param_names": ["d2", "d3", "d4"] + }}), + ); + run( + &mut s, + "timeline.add", + json!({"feature": { + "id": 4, "name": "Cut B", "type": "combine", "suppressed": false, + "operation": "cut", "target": "B", "tools": ["Cutter"], "keep_tools": true + }}), + ); + let sorted = |v: Vec| { + let mut v = v; + v.sort(); + v + }; + assert_eq!(sorted(names(&s)), ["A", "B", "B (1)", "Cutter"]); + run(&mut s, "body.rename", json!({"body": "B (1)", "name": "B2"})); + assert_eq!(sorted(names(&s)), ["A", "B", "B2", "Cutter"]); + // The new name is the cut's second piece's, stored by the cut, not in the members' slots. + let stored = |id: u64| s.doc.features.iter().find(|f| f.id == id).map(|f| f.body_names.clone()).unwrap_or_default(); + assert!(!stored(2).contains(&"B2".to_string()), "members: {:?}", stored(2)); + assert_eq!(stored(4), ["B2"], "the cut stores its piece's name"); + run(&mut s, "file.save_as", json!({"path": saved.to_string_lossy()})); + let mut reopened = Session::default(); + run(&mut reopened, "doc.open", json!({"path": saved.to_string_lossy()})); + assert_eq!(sorted(names(&reopened)), ["A", "B", "B2", "Cutter"], "the rename must not move to member A on rebuild"); + // `solidcraft-cli eval` of the saved file rebuilds it from its features alone, with no + // saved model to take the names from (#10438). + let rebuilt = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert_eq!(sorted(names(&rebuilt)), ["A", "B", "B2", "Cutter"], "a rebuild from the features alone keeps the rename too"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn renaming_a_body_to_a_removed_name_preserves_the_design() { for removed_name in ["Base", "Body1"] { @@ -1367,7 +2017,9 @@ mod tests { run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0], "operation": "new", "body_name": "Tab"})); run(&mut s, "solid.combine", json!({"target": "A", "tools": ["Tab"], "operation": "join", "name": "Joined"})); let want = total(&mut s); + s.evaluations = 0; run(&mut s, "body.rename", json!({"body": "A", "name": "B"})); + assert_eq!(s.evaluations, 0, "renaming primitive participants changes no geometry"); assert!( s.model.results.iter().all(|r| r.error.is_none()), "{:?}", @@ -1377,6 +2029,7 @@ mod tests { assert!((total(&mut s) - want).abs() < 1e-6); run(&mut s, "edit.undo", json!({})); assert_eq!(s.doc.find_feature("Hole").unwrap().participants, vec!["A".to_string()]); + assert_eq!(s.evaluations, 0); } /// #1109: renaming counted bodies (`Body1`, `Body2` of one pattern) leaves the counted bodies @@ -1440,14 +2093,80 @@ mod tests { assert_eq!(names(&s), vec!["Plate".to_string(), "B".to_string()]); assert_eq!(s.evaluations, 0, "undo and redo of a rename evaluate nothing"); assert_eq!(meshes(&s), shown); - // A body a later feature uses is renamed in that feature too: that is evaluated. + // A later feature's body reference follows the rename without rebuilding geometry. run(&mut s, "solid.combine", json!({"target": "Plate", "tools": ["B"], "operation": "join", "keep_tools": true})); + let shown = meshes(&s); s.evaluations = 0; run(&mut s, "body.rename", json!({"body": "B", "name": "Tool"})); - assert!(s.evaluations > 0); + assert_eq!(s.evaluations, 0); + assert_eq!(meshes(&s), shown); assert!(names(&s).contains(&"Tool".to_string())); } + /// #6287: one rename in a timeline of named body references used to rebuild every feature + /// and replace every mesh, including the other bodies' meshes. + #[test] + fn renaming_a_body_with_downstream_references_keeps_every_mesh() { + let mut s = Session::default(); + for i in 0..18 { + run( + &mut s, + "solid.box", + json!({"length": 40, "width": 30, "height": 10, "center": [50 * i, 0, 0], "operation": "new", "body_name": format!("Block{i}")}), + ); + } + for _ in 0..2 { + for i in 0..18 { + run(&mut s, "solid.move", json!({"bodies": [format!("Block{i}")], "translate": [0, 5, 0]})); + } + } + assert_eq!(s.doc.features.len(), 54); + let meshes = |s: &Session| s.model.state().bodies.iter().map(|b| b.mesh()).collect::>(); + let looks = |s: &Session| { + s.model.state().bodies.iter().map(|b| (b.name.clone(), (*solidcraft_doc::naming::face_names(b)).clone())).collect::>() + }; + let shown = meshes(&s); + let before = looks(&s); + let measurements = run(&mut s, "inspect.measure", json!({}))["total"].clone(); + assert!((measurements["volume_mm3"].as_f64().unwrap() - 216_000.0).abs() < 1e-6); + s.evaluations = 0; + run(&mut s, "body.rename", json!({"body": "Block0", "name": "Bracket"})); + assert_eq!(s.evaluations, 0, "renaming references must not evaluate the timeline"); + let after = looks(&s); + assert_eq!(after[0].0, "Bracket"); + let mut fresh = Session::new((*s.doc).clone()); + fresh.refresh(); + assert_eq!(looks(&fresh), after, "the same bodies and face names as rebuilding"); + assert_eq!(run(&mut fresh, "inspect.measure", json!({}))["total"], measurements); + run(&mut s, "edit.undo", json!({})); + assert_eq!(looks(&s), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(looks(&s), after); + assert_eq!(s.evaluations, 0, "undo and redo must also retain the evaluated model"); + assert!(shown.iter().zip(meshes(&s)).all(|(a, b)| std::sync::Arc::ptr_eq(a, &b)), "every body retains its display mesh"); + } + + #[test] + fn a_body_rename_with_changed_dimensions_still_evaluates() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Block"})); + run(&mut s, "solid.move", json!({"bodies": ["Block"], "translate": [5, 0, 0]})); + let before = s.doc.clone(); + let model = s.model.clone(); + run(&mut s, "body.rename", json!({"body": "Block", "name": "Bracket"})); + // An outside edit can include a rename and a geometry change together. It must not + // take the rename shortcut merely because the later Move's body reference matches. + let solidcraft_doc::FeatureKind::Box { height, .. } = &mut s.doc_mut().features[0].kind else { panic!("expected the box") }; + *height = "20".into(); + s.model = model; + s.evaluations = 0; + s.refresh_from(&before, false); + assert_eq!(s.evaluations, 1); + assert_eq!(names(&s), ["Bracket"]); + let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + assert!((volume - 24_000.0).abs() < 1e-6, "the changed height must be evaluated: {volume}"); + } + #[test] fn renaming_a_body_leaves_other_text_with_its_name_alone() { let mut s = Session::default(); @@ -1539,7 +2258,7 @@ mod tests { assert!(s.camera.is_none()); let r = run(&mut s, "view.apply", json!({"view": "Photo"})); let c = s.camera.expect("a camera for the view"); - assert_eq!((c.target, c.yaw, c.pitch, c.distance), (solidcraft_geom::Vec3::new(1.0, 2.0, 3.0), 0.5, -0.6, 150.0)); + assert_eq!((c.target, c.yaw, c.pitch, c.distance), (solidcore_record::Vec3::new(1.0, 2.0, 3.0), 0.5, -0.6, 150.0)); assert_eq!(r["camera"]["yaw"], 0.5); // A standard view looks from its direction and frames the model. run(&mut s, "view.apply", json!({"view": "top"})); @@ -1704,6 +2423,23 @@ mod tests { assert!(s.visibility.hidden_bodies.is_empty()); } + /// #9954: a sketch hidden and shown again before an Extrude uses it hides itself once the + /// Extrude uses it, as a sketch never hidden does; shown after the Extrude, it stays shown. + #[test] + fn a_sketch_shown_before_an_extrude_hides_itself_once_the_extrude_uses_it() { + let mut s = Session::default(); + let sketch = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "browser.visibility", json!({"items": [sketch], "visible": false})); + run(&mut s, "browser.visibility", json!({"items": [sketch], "visible": true})); + assert!(crate::view::sketch_shown(&s, sketch)); + run(&mut s, "solid.extrude", json!({"sketch": sketch, "distance": 10})); + assert!(!crate::view::sketch_shown(&s, sketch), "the Extrude uses it: it hides itself"); + run(&mut s, "browser.visibility", json!({"items": [sketch], "visible": true})); + assert!(crate::view::sketch_shown(&s, sketch), "shown on its own, it stays shown"); + } + #[test] fn a_sheet_metal_flange_hides_its_sketch_as_an_extrude_does() { // #6804: the base flange's sketch stayed shown; its line on the plate's bottom edge then @@ -1782,7 +2518,7 @@ mod tests { let body = s.model.state().bodies[0].name.clone(); let drain_name = s.doc.feature(drain).unwrap().name.clone(); let cam = solidcraft_render::Camera::default(); - let lines = |s: &Session| crate::view::scene(s, &cam).lines.len(); + let lines = |s: &Session| crate::view::scene(s, &cam).unwrap().lines.len(); let shown = |s: &mut Session| { let d = run(s, "document.inspect", json!({})); d["sketches"].as_array().unwrap().iter().filter(|x| x["visible"] == true).count() @@ -1801,7 +2537,7 @@ mod tests { assert_eq!(lines(&s), n0); // The browser's Sketches folder hidden: sketches shown one by one aren't drawn either, // only the sketch being edited. - assert!(s.visibility.shown_sketches.contains(&floor)); + assert!(crate::view::sketch_shown(&s, floor)); run(&mut s, "browser.visibility", json!({"tree_folders": ["c0/sketches"], "visible": false})); assert!([floor, drain].iter().all(|id| !crate::view::sketch_shown(&s, *id))); s.active_sketch = Some(floor); @@ -1810,7 +2546,7 @@ mod tests { run(&mut s, "browser.visibility", json!({"tree_folders": ["c0/sketches"], "visible": true})); // Bodies (following a rename) and construction planes. run(&mut s, "browser.visibility", json!({"items": [body.clone(), "Floor", "xy"], "visible": false})); - assert!(crate::view::scene(&s, &cam).meshes.is_empty()); + assert!(crate::view::scene(&s, &cam).unwrap().meshes.is_empty()); assert_eq!(s.visibility.hidden_origin, vec!["Floor".to_string(), "XY".to_string()]); run(&mut s, "body.rename", json!({"body": body, "name": "Tray"})); assert_eq!(s.visibility.hidden_bodies, vec!["Tray".to_string()]); @@ -1865,7 +2601,8 @@ mod tests { assert!(s.visibility.hidden_bodies.is_empty()); run(&mut s, "browser.visibility", json!({"items": ["BACK LID"], "visible": true})); assert!(s.visibility.hidden_sketches.is_empty()); - assert_eq!(s.visibility.shown_sketches, vec![sketch]); + // Nothing uses the sketch: shown again, it is on neither list (#9954). + assert!(s.visibility.shown_sketches.is_empty() && crate::view::sketch_shown(&s, sketch)); } /// #2219: hiding is a step of its own, so Ctrl+Z brings the body back instead of undoing the @@ -1876,7 +2613,7 @@ mod tests { run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); s.mark_saved(); let cam = solidcraft_render::Camera::default(); - let drawn = |s: &Session| crate::view::scene(s, &cam).meshes.len(); + let drawn = |s: &Session| crate::view::scene(s, &cam).unwrap().meshes.len(); assert!(drawn(&s) > 0, "the box is drawn"); assert!(!s.is_dirty()); let steps = s.undo.len(); @@ -2022,17 +2759,17 @@ mod tests { let g = run(&mut s, "browser.group", json!({"folder": "bodies", "items": [a.clone()]}))["group"].as_u64().unwrap(); assert_eq!(s.doc.browser_groups[0].name, "Group1"); run(&mut s, "browser.move", json!({"folder": "bodies", "items": [b.clone()], "group": g, "before": a.clone()})); - assert_eq!(s.doc.browser_groups[0].items, vec![b.clone(), a.clone()]); + assert_eq!(s.doc.browser_groups[0].items, vec![b.clone().into(), a.clone().into()]); run(&mut s, "browser.rename_group", json!({"group": g, "name": "Fasteners"})); run(&mut s, "body.rename", json!({"body": a, "name": "Bolt"})); - assert_eq!(s.doc.browser_groups[0].items, vec![b.clone(), "Bolt".to_string()]); + assert_eq!(s.doc.browser_groups[0].items, vec![b.clone().into(), "Bolt".into()]); // Out of the group, then a folder order; saved with the design. run(&mut s, "browser.move", json!({"folder": "bodies", "items": [b.clone()]})); - assert_eq!(s.doc.browser_groups[0].items, vec!["Bolt".to_string()]); + assert_eq!(s.doc.browser_groups[0].items, vec!["Bolt".into()]); run(&mut s, "browser.order", json!({"folder": "bodies", "order": [b.clone(), "Bolt"]})); let saved: solidcraft_doc::Document = serde_json::from_str(&serde_json::to_string(&*s.doc).unwrap()).unwrap(); assert_eq!(saved.browser_groups, s.doc.browser_groups); - assert_eq!(saved.browser_order["0/bodies"], vec![b, "Bolt".to_string()]); + assert_eq!(saved.browser_order["0/bodies"], vec![b.into(), "Bolt".into()]); run(&mut s, "browser.ungroup", json!({"group": g})); assert!(s.doc.browser_groups.is_empty()); // Hostile input is refused. @@ -2215,4 +2952,107 @@ mod tests { let e = s.execute("browser.visibility", &json!({"visible": false, "features": ["Sphere1"], "path": [first]})).expect_err("other component"); assert!(e.to_string().contains("component"), "{e}"); } + + use solidcraft_doc::{BrowserEntry, MAX_GROUP_NESTING}; + + fn three_bodies(s: &mut Session) { + for (i, name) in ["A", "B", "C"].into_iter().enumerate() { + run(s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [i as f64 * 20.0, 0, 0], "body_name": name})); + } + } + + fn new_group(s: &mut Session, mut p: Value) -> u64 { + p["folder"] = json!("bodies"); + run(s, "browser.group", p)["group"].as_u64().unwrap() + } + + fn state(s: &Session) -> (Vec, std::collections::BTreeMap>) { + (s.doc.browser_groups.clone(), s.doc.browser_order.clone()) + } + + fn refused(s: &mut Session, id: &str, p: Value) { + let before = s.doc.to_json(); + let r = s.execute(id, &p); + assert!(matches!(r, Err(crate::EngineError::BadParams { .. })), "{id} {p}: {r:?}"); + assert_eq!(s.doc.to_json(), before, "{id} {p}: a refused command changes nothing"); + } + + /// Nest a group, order groups and components, ungroup; each step undoes and redoes, and none of + /// it evaluates anything. + #[test] + fn groups_nest_reorder_and_ungroup_with_undo_redo_and_no_evaluation() { + let mut s = Session::default(); + three_bodies(&mut s); + let mut placed = Vec::new(); + for name in ["P", "Q"] { + placed.push(run(&mut s, "component.create", json!({"name": name}))["occurrence"].as_u64().unwrap()); + run(&mut s, "component.activate", json!({"component": 0})); + } + let mut states = vec![state(&s)]; + s.evaluations = 0; + let outer = new_group(&mut s, json!({"items": ["A"]})); + states.push(state(&s)); + // The inner group takes its component and folder from the parent. + let inner = run(&mut s, "browser.group", json!({"parent": outer, "items": ["B"]}))["group"].as_u64().unwrap(); + states.push(state(&s)); + let g = s.doc.browser_group(inner).unwrap(); + assert_eq!((g.parent, g.component, g.folder.as_str()), (Some(outer), 0, "bodies")); + run(&mut s, "browser.order", json!({"folder": "components", "order": [placed[1].to_string(), placed[0].to_string()]})); + states.push(state(&s)); + let mut shown = placed.clone(); + s.doc.sort_placements(0, &mut shown); + assert_eq!(shown, [placed[1], placed[0]]); + run(&mut s, "browser.order", json!({"folder": "bodies", "order": ["C", outer]})); + states.push(state(&s)); + run(&mut s, "browser.move", json!({"folder": "bodies", "items": [inner], "before": "C"})); + states.push(state(&s)); + assert_eq!(s.doc.ordered_entries(0, "bodies", None), [BrowserEntry::Group(inner), "C".into(), BrowserEntry::Group(outer)]); + run(&mut s, "browser.ungroup", json!({"group": outer})); + states.push(state(&s)); + // The group's items go where it was. + assert_eq!(s.doc.browser_order["0/bodies"], [BrowserEntry::Group(inner), "C".into(), "A".into()]); + for i in (0..states.len() - 1).rev() { + run(&mut s, "edit.undo", json!({})); + assert_eq!(state(&s), states[i], "undo to step {i}"); + } + for (i, expected) in states.iter().enumerate().skip(1) { + run(&mut s, "edit.redo", json!({})); + assert_eq!(state(&s), *expected, "redo to step {i}"); + } + assert_eq!(s.evaluations, 0, "changing only the browser evaluates nothing"); + } + + #[test] + fn nesting_and_ordering_that_cannot_stand_are_refused() { + let mut s = Session::default(); + three_bodies(&mut s); + let part = run(&mut s, "component.create", json!({"name": "Part"})); + run(&mut s, "component.activate", json!({"component": 0})); + let outer = new_group(&mut s, json!({"items": ["A"]})); + let inner = new_group(&mut s, json!({"parent": outer})); + // A group inside itself or its own child. + refused(&mut s, "browser.move", json!({"folder": "bodies", "items": [outer], "group": outer})); + refused(&mut s, "browser.move", json!({"folder": "bodies", "items": [outer], "group": inner})); + // Past eight levels, by a new group or by moving one with a child of its own. + let mut chain = vec![new_group(&mut s, json!({}))]; + while chain.len() < MAX_GROUP_NESTING { + chain.push(new_group(&mut s, json!({"parent": chain[chain.len() - 1]}))); + } + refused(&mut s, "browser.group", json!({"folder": "bodies", "parent": chain[MAX_GROUP_NESTING - 1]})); + let heavy = new_group(&mut s, json!({})); + new_group(&mut s, json!({"parent": heavy})); + refused(&mut s, "browser.move", json!({"folder": "bodies", "items": [heavy], "group": chain[MAX_GROUP_NESTING - 2]})); + // A parent that is missing, or in another folder or component. + refused(&mut s, "browser.group", json!({"folder": "bodies", "parent": 424242})); + refused(&mut s, "browser.group", json!({"folder": "sketches", "parent": outer})); + refused(&mut s, "browser.group", json!({"parent": outer, "component": part["component"]})); + // Orders and moves naming a group that cannot be there; a number is a group, not an item key. + refused(&mut s, "browser.order", json!({"folder": "bodies", "order": [inner]})); + refused(&mut s, "browser.order", json!({"folder": "bodies", "order": [424242]})); + refused(&mut s, "browser.move", json!({"folder": "bodies", "items": ["B"], "before": 424242})); + refused(&mut s, "browser.group", json!({"folder": "bodies", "items": [12]})); + // The components folder takes placements of that component, and nothing else. + refused(&mut s, "browser.order", json!({"folder": "components", "order": ["424242"]})); + refused(&mut s, "browser.order", json!({"folder": "components", "order": [outer]})); + } } diff --git a/crates/engine/src/cmd/canvas_sketch.rs b/crates/engine/src/cmd/canvas_sketch.rs index 61b425383..47411a4d6 100644 --- a/crates/engine/src/cmd/canvas_sketch.rs +++ b/crates/engine/src/cmd/canvas_sketch.rs @@ -10,8 +10,9 @@ //! size), and the decoder itself runs under the same limit. use serde_json::{Value, json}; +use solidcore_record::Vec2; use solidcraft_doc::canvas::{Canvas, base64_decode, image_info}; -use solidcraft_geom::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_io::Geom2; use super::CommandSpec; diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index 4f107813e..89ee1e357 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -9,16 +9,28 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; -use serde_json::{Value, json}; +use serde_json::Value; use solidcraft_geom::mesh_distance::box_gap; +use solidcraft_geom::prelude::*; use solidcraft_geom::{Aabb3, Mesh}; use solidcraft_kernel::{BodyDistance, DistanceShape}; use super::CommandSpec; use crate::params::{bad, num, str_, string_list}; +use crate::schema::clearance::{ + Clearance as ClearanceReply, ClearanceParams, MAX_CLEARANCE, MAX_NEAREST, NearPair, Neighbour, Overlap, OverlapBounds, Unchecked, +}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "Clearance", clearance).icon("interference").noundo().params( +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "Clearance", crate::checked!("inspect.clearance", clearance)) + .icon("interference") + .noundo() + .contract(&CONTRACT) + .output(output_schema_for::) + .params( "bodies?: [names] (default: every solid body, in world placement, but those in `against`; mesh bodies are not measured); against?: [names] (only pairs with one body in `bodies` and the other here); \ min_volume?: mm³ (default 0.01: smaller overlaps count as contact); clearance?: mm (default 0: report pairs closer than this); \ nearest?: n (each body of `bodies` gets its n nearest others); skip_within?: \"occurrence\" (pairs of bodies of one occurrence) | \ @@ -33,10 +45,6 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "C const MAX_BODIES: usize = 20_000; /// Most pairs whose grown boxes meet that one call measures. const MAX_PAIRS: usize = 200_000; -/// Most neighbours a body's `nearest` list holds. -const MAX_NEAREST: usize = 1000; -/// Largest clearance (mm). -const MAX_CLEARANCE: f64 = 1e6; #[derive(Clone, Copy, PartialEq, Eq)] enum SkipWithin { @@ -47,9 +55,6 @@ enum SkipWithin { /// Most pairs [`PairCache`] keeps; it starts over when full. const MAX_CACHED: usize = 2 * MAX_PAIRS; -/// The kernel's tries at intersecting a pin with its hole on one cylinder (each about a second -/// on real parts; a plain pin on its axis needs one or two). -const PIN_ATTEMPTS: usize = 4; /// Pairs measured before, by the two bodies' geometry where they stood /// ([`solidcraft_doc::ModelBody::geometry_key`]) and the settings that shape the result @@ -61,7 +66,7 @@ pub(crate) struct PairCache(HashMap<(u64, u64, [u64; 3]), PairResult>); #[derive(Clone, Default)] struct PairResult { /// Shared volume, area, box and centre. - overlap: Option<(f64, f64, Aabb3, solidcraft_geom::Vec3)>, + overlap: Option<(f64, f64, Aabb3, solidcore_record::Vec3)>, distance: Option, unchecked: Option, } @@ -91,7 +96,7 @@ fn clearance(s: &mut Session, p: &Value) -> Result { }, }; - let st = s.world_state(); + let st = s.world_state()?; let (mesh_bodies, solid): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = st.bodies.iter().partition(|b| b.body.is_mesh()); // Mesh bodies are not measured. A mesh body named in `bodies` or `against` is left out of the // pairs and listed as unchecked, rather than refused as "no solid body". @@ -193,7 +198,7 @@ fn clearance(s: &mut Session, p: &Value) -> Result { p.into_iter().for_each(|v| bx.add(v)); } let chord = b.display_tol(); - let g = solidcraft_geom::Vec3::new(1.0, 1.0, 1.0) * if chord.is_finite() && chord > 0.0 { chord } else { 0.0 }; + let g = solidcore_record::Vec3::new(1.0, 1.0, 1.0) * if chord.is_finite() && chord > 0.0 { chord } else { 0.0 }; if bx.is_empty() { bx } else { Aabb3 { min: bx.min - g, max: bx.max + g } } } _ => Aabb3::EMPTY, @@ -201,7 +206,7 @@ fn clearance(s: &mut Session, p: &Value) -> Result { .collect(); // Pairs whose boxes, grown by half the clearance each, meet. - let half = solidcraft_geom::Vec3::new(1.0, 1.0, 1.0) * (gap / 2.0); + let half = solidcore_record::Vec3::new(1.0, 1.0, 1.0) * (gap / 2.0); let grown: Vec = boxes.iter().map(|b| if b.is_empty() { *b } else { Aabb3 { min: b.min - half, max: b.max + half } }).collect(); let (close, truncated) = super::joints::overlapping_pairs(&grown, MAX_PAIRS); let has_mesh = |i: usize| meshes.get(i).is_some_and(Option::is_some); @@ -263,48 +268,56 @@ fn clearance(s: &mut Session, p: &Value) -> Result { for k in ["bodies", "against"] { asked.extend(string_list(cmd, p, k)?); } - let mut unchecked: Vec = mesh_bodies + let mut unchecked: Vec = mesh_bodies .iter() .filter(|b| p.get("bodies").is_none_or(Value::is_null) || asked.contains(&b.name)) - .map(|b| json!({"a": b.name, "b": null, "reason": super::interference::MESH_NOT_CHECKED})) + .map(|b| Unchecked { a: b.name.clone(), b: None, reason: super::interference::MESH_NOT_CHECKED.to_string() }) .collect(); let name = |i: usize| solid.get(i).map_or("", |b| b.name.as_str()); + let pair = |i: usize, j: usize, reason: String| Unchecked { a: name(i).to_string(), b: Some(name(j).to_string()), reason }; for (&(i, j), r) in close.iter().zip(results) { let r = match r { Ok(r) => r, Err(e) => { - unchecked.push(json!({"a": name(i), "b": name(j), "reason": e.to_string()})); + unchecked.push(pair(i, j, e.to_string())); continue; } }; if let Some(reason) = r.unchecked { - unchecked.push(json!({"a": name(i), "b": name(j), "reason": reason})); + unchecked.push(pair(i, j, reason)); continue; } if let Some((volume, area, bbox, center)) = r.overlap && volume >= min_volume { - overlaps.push(json!({"a": name(i), "b": name(j), "volume_mm3": volume, "area_mm2": area, - "bbox": {"min": bbox.min, "max": bbox.max}, "center": center})); + overlaps.push(Overlap { + a: name(i).to_string(), + b: name(j).to_string(), + volume_mm3: volume, + area_mm2: area, + bbox: OverlapBounds { min: bbox.min.into(), max: bbox.max.into() }, + center: center.into(), + }); known.insert((i, j), 0.0); continue; } let Some(d) = r.distance else { continue }; known.insert((i, j), d.distance); if d.distance < gap { - let mut e = json!({"a": name(i), "b": name(j), "distance_mm": d.distance, "from": d.from, "to": d.to}); - if let Some((v, ..)) = r.overlap.filter(|o| o.0 > 0.0) { - e["overlap_mm3"] = json!(v); - } - if !d.exact { - e["exact"] = json!(false); - } - near.push(e); + near.push(NearPair { + a: name(i).to_string(), + b: name(j).to_string(), + distance_mm: d.distance, + from: d.from.into(), + to: d.to.into(), + overlap_mm3: r.overlap.filter(|o| o.0 > 0.0).map(|o| o.0), + exact: (!d.exact).then_some(false), + }); } } - near.sort_by(|x, y| x["distance_mm"].as_f64().unwrap_or(0.0).total_cmp(&y["distance_mm"].as_f64().unwrap_or(0.0))); + near.sort_by(|x, y| x.distance_mm.total_cmp(&y.distance_mm)); - let mut nearest_out = serde_json::Map::new(); + let mut nearest_out = BTreeMap::new(); if nearest > 0 { let lists = nearest_lists(&subjects, n, nearest, &boxes, &allowed, &mut known, |pairs| { solidcraft_kernel::map_with_local_pools(pairs, usize::MAX, |&(i, j)| { @@ -313,23 +326,25 @@ fn clearance(s: &mut Session, p: &Value) -> Result { }) }); for (i, list) in lists { - let rows: Vec = list.iter().map(|&(j, d)| json!({"body": name(j), "distance_mm": d})).collect(); - nearest_out.insert(name(i).to_string(), Value::Array(rows)); + let rows = list.iter().map(|&(j, d)| Neighbour { body: name(j).to_string(), distance_mm: d }).collect(); + nearest_out.insert(name(i).to_string(), rows); } } - Ok(json!({ - "overlaps": overlaps, - "near": near, - "nearest": nearest_out, - "unchecked": unchecked, - "bodies": subjects.len(), - "pairs_checked": close.len(), - "pairs_reused": reused, - "pairs_pruned": total.saturating_sub(close.len()), - "truncated": truncated > 0, - "ms": started.elapsed().as_secs_f64() * 1000.0, - })) + let reply = ClearanceReply { + overlaps, + near, + nearest: nearest_out, + unchecked, + bodies: subjects.len(), + pairs_checked: close.len(), + pairs_reused: reused, + pairs_pruned: total.saturating_sub(close.len()), + truncated: truncated > 0, + ms: started.elapsed().as_secs_f64() * 1000.0, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) } /// One pair: its overlap when the meshes meet or one holds the other, otherwise its distance @@ -360,78 +375,19 @@ fn measure_pair( let touching = mesh.is_some_and(|m| m.distance <= slack); if touching || holds(ba, bb) || holds(bb, ba) { // A pair whose shared part can't be worked out is reported, not passed as clear. - let region = shared_region(a, b); - let (ca, cb) = (clipped(ka, region), clipped(kb, region)); - // A pin of one in a hole of the other of its own size. On its very axis the boolean takes - // the two walls as one and answers plain ones at once, but with blends next to them it - // tries for minutes and gives up; a hair off the axis it cannot intersect them at all - // (and may pass the pin as clear). So a pin on its axis gets a few tries of the boolean - // first, and what the walls share is otherwise worked out apart, with a few tries of the - // boolean left for when that declines. The body left whole is cut down to where the - // other's piece is first, so that both meet only the faces there. - let candidate = solidcraft_kernel::coaxial_candidate(ca.as_ref().unwrap_or(ka), cb.as_ref().unwrap_or(kb)); - let pin = candidate.is_some(); - let (ca, cb) = match (ca, cb) { - (Some(x), None) if pin => { - let y = narrowed(kb, &x); - (Some(x), y) - } - (None, Some(y)) if pin => (narrowed(ka, &y), Some(y)), - other => other, - }; - // A body left whole is the copy that keeps its meshes: meeting several others at one - // size, it is meshed once for the booleans of all of them. - let (pa, pb) = (ca.as_ref().unwrap_or(ka), cb.as_ref().unwrap_or(kb)); - let intersect = || { - solidcraft_kernel::capture_boolean_diagnostics(|| { - let run = || solidcraft_kernel::boolean(pa, pb, solidcraft_kernel::BoolOp::Intersect); - if pin { solidcraft_kernel::with_attempt_budget(PIN_ATTEMPTS, run) } else { run() } - }) - }; - let first = (candidate != Some(false)).then(intersect); - let answered = first.as_ref().is_some_and(|(r, report)| r.is_ok() && report.unverified().is_none()); - let coaxial = if pin && !answered { solidcraft_kernel::coaxial_overlap(pa, pb) } else { None }; - if let Some(o) = coaxial { - if o.volume > 0.0 { - out.overlap = Some((o.volume, o.area, o.bbox, o.centroid)); - } - } else { - let (shared, report) = first.unwrap_or_else(intersect); - let failed = - |why: String| if pin { format!("a pin on one cylinder with its hole, whose walls could not be intersected ({why})") } else { why }; - let shared = match shared { - Err(e) => { - out.unchecked = Some(failed(e.to_string())); - return out; - } - Ok(shared) => shared, - }; - if let Some(reason) = report.unverified() { - out.unchecked = Some(failed(reason)); + match solidcraft_kernel::boolean(ka, kb, solidcraft_kernel::BoolOp::Intersect) { + Err(e) => { + out.unchecked = Some(e.to_string()); return out; } - if let Some(o) = shared { - match measure_near_origin(&o, region.center()) { - Ok(m) if !plausible(m.volume, m.centroid, m.bbox) => { - out.unchecked = Some(format!( - "the shared part came out malformed ({:.4} mm³ with its centre outside its own box), so it is not measured", - m.volume - )); - return out; - } - Ok(m) => { - if let Some(reason) = union_disagrees(pa, pb, m.volume, region.center()) { - out.unchecked = Some(reason); - return out; - } - out.overlap = Some((m.volume, m.area, m.bbox, m.centroid)); - } - Err(e) => { - out.unchecked = Some(e.to_string()); - return out; - } + Ok(Some(o)) => match measure_near_origin(&o, shared_region(a, b).center()) { + Ok(m) => out.overlap = Some((m.volume, m.area, m.bbox, m.centroid)), + Err(e) => { + out.unchecked = Some(e.to_string()); + return out; } - } + }, + Ok(None) => {} } if out.overlap.is_some_and(|o| o.0 >= min_volume) { return out; @@ -459,8 +415,7 @@ fn measure_pair( out } -/// The box where two bodies may share volume: where their boxes meet, grown by a margin so that -/// a cut there stays clear of both bodies' faces. +/// The box where two bodies may share volume: where their boxes meet, grown by a margin. fn shared_region(a: &DistanceShape, b: &DistanceShape) -> Aabb3 { let (x, y) = (a.bounds(), b.bounds()); let min = x.min.max(y.min); @@ -469,113 +424,20 @@ fn shared_region(a: &DistanceShape, b: &DistanceShape) -> Aabb3 { return Aabb3::EMPTY; } let grow = 1.0 + 0.05 * min.dist(max); - let g = solidcraft_geom::Vec3::new(grow, grow, grow); + let g = solidcore_record::Vec3::new(grow, grow, grow); Aabb3 { min: min - g, max: max + g } } -/// `body` cut down to `region` when the body is much larger than it. The boolean works to a -/// tolerance that grows with the bodies' size: a 0.01 mm overlap against a plate 1.7 m long -/// comes out a quarter too small, and thinner ones not at all. Cut to the region first, the -/// body is small and its faces there are the same faces. `None`: use the whole body. -fn clipped(body: &solidcraft_kernel::Body, region: Aabb3) -> Option { - if region.is_empty() || body.size() <= 4.0 * region.diagonal() { - return None; - } - let cut = solidcraft_kernel::box_solid(region.min, region.max).ok()?; - let (r, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(body, &cut, solidcraft_kernel::BoolOp::Intersect)); - match r { - Ok(Some(c)) if report.unverified().is_none() => Some(c), - _ => None, - } -} - -/// `body` cut down to where it may meet `piece` (their boxes' common part, grown as -/// [`shared_region`] grows it), when that leaves part of it out. `None`: use the whole body. -fn narrowed(body: &solidcraft_kernel::Body, piece: &solidcraft_kernel::Body) -> Option { - let bounds = |b: &solidcraft_kernel::Body| b.tessellate_with((b.size() * 1e-3).max(1e-4), false).ok().map(|m| m.bounds()); - let (x, y) = (bounds(body)?, bounds(piece)?); - let (min, max) = (x.min.max(y.min), x.max.min(y.max)); - if x.is_empty() || y.is_empty() || !(min.x <= max.x && min.y <= max.y && min.z <= max.z) { - return None; - } - let grow = 1.0 + 0.05 * min.dist(max); - let g = solidcraft_geom::Vec3::new(grow, grow, grow); - let region = Aabb3 { min: min - g, max: max + g }; - if region.min.x <= x.min.x - && region.min.y <= x.min.y - && region.min.z <= x.min.z - && x.max.x <= region.max.x - && x.max.y <= region.max.y - && x.max.z <= region.max.z - { - return None; - } - let cut = solidcraft_kernel::box_solid(region.min, region.max).ok()?; - let (r, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(body, &cut, solidcraft_kernel::BoolOp::Intersect)); - match r { - Ok(Some(c)) if report.unverified().is_none() => Some(c), - _ => None, - } -} - /// [`solidcraft_kernel::measure`] of `body` moved by `-at` and back: far from the origin, the /// centre of a thin part loses its precision (its moments are large numbers that nearly cancel). -fn measure_near_origin(body: &solidcraft_kernel::Body, at: solidcraft_geom::Vec3) -> solidcraft_kernel::Result { - let Ok(moved) = solidcraft_kernel::transform(body, -at, solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::Z, 0.0) else { - return solidcraft_kernel::measure(body); - }; +fn measure_near_origin(body: &solidcraft_kernel::Body, at: solidcore_record::Vec3) -> solidcraft_kernel::Result { + let moved = solidcraft_kernel::transform(body, -at, solidcore_record::Vec3::ZERO, solidcore_record::Vec3::Z, 0.0)?; let mut m = solidcraft_kernel::measure(&moved)?; m.centroid += at; m.bbox = Aabb3 { min: m.bbox.min + at, max: m.bbox.max + at }; Ok(m) } -/// Does the shared volume of `a` and `b` disagree with the one their union implies, -/// vol(a) + vol(b) − vol(a ∪ b)? The intersection can come out well formed and still wrong (a -/// mirrored pair read three times its volume). `None` when they agree, or when the union gives no -/// answer to compare with. -fn union_disagrees(a: &solidcraft_kernel::Body, b: &solidcraft_kernel::Body, shared: f64, at: solidcraft_geom::Vec3) -> Option { - let (union, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(a, b, solidcraft_kernel::BoolOp::Union)); - let union = union.ok().flatten().filter(|_| report.unverified().is_none())?; - let volume = |x: &solidcraft_kernel::Body| measure_near_origin(x, at).ok().map(|m| m.volume).filter(|v| v.is_finite()); - contradicted(shared, volume(a)?, volume(b)?, volume(&union)?) -} - -/// How far vol(a) + vol(b) − vol(a ∪ b) can stray from the shared volume by measuring alone, -/// as a share of vol(a) + vol(b) + vol(a ∪ b). [`solidcraft_kernel::measure`] facets a curved -/// face with chords of up to 3e-4 of its radius where the radius sets them, which leaves the -/// volume it encloses short by up to (4/3) × 3e-4 = 4e-4. That shortfall is the same for a face -/// measured on its own body and in the union, and cancels in the difference, except where the -/// chord changes with the body measured (it also follows the body's size). Measured, that -/// change stays near 2e-5 of the three volumes: 2.1e-5 for a 40 mm roller pressed 0.2 mm into a -/// 2 m plate (`a_roller_pressed_into_a_large_plate_is_reported`), 2e-5 and 1e-6 in the examples -/// of `the_union_check_allows_for_the_bodies_measuring_error`. This allows five times that. -const VOLUME_NOISE: f64 = 1e-4; - -/// [`union_disagrees`] on measured volumes: `shared` against vol(a) + vol(b) − vol(a ∪ b). -/// That difference of large numbers carries the measuring error of all three, so a small overlap -/// on large bodies can come out near zero or below it: then the union cannot tell, and a shared -/// part small next to both bodies stands. A shared part the union clearly contradicts (412 mm³ -/// where the bodies of a few thousand and their union imply 141) does not. -fn contradicted(shared: f64, va: f64, vb: f64, vu: f64) -> Option { - let implied = va + vb - vu; - let noise = VOLUME_NOISE * (va + vb + vu) + 1e-6; - let allowed = 0.01 * shared.max(implied.abs()) + noise; - let unresolved = implied <= noise && shared <= 0.1 * va.min(vb); - ((implied - shared).abs() > allowed && !unresolved) - .then(|| format!("the shared part measures {shared:.4} mm³ but the bodies and their union imply {implied:.4} mm³, so neither is reported")) -} - -/// Is a measured shared part well formed? A part whose shell came out inside out or open can -/// carry a volume with its centre outside its own box, or more volume than its box holds. -fn plausible(volume: f64, centre: solidcraft_geom::Vec3, bbox: Aabb3) -> bool { - let slack = 1e-6 * bbox.diagonal().max(1.0); - let (lo, hi) = (bbox.min, bbox.max); - let inside = [(centre.x, lo.x, hi.x), (centre.y, lo.y, hi.y), (centre.z, lo.z, hi.z)].iter().all(|&(c, l, h)| c >= l - slack && c <= h + slack); - let s = bbox.size(); - volume.is_finite() && volume >= 0.0 && inside && volume <= s.x * s.y * s.z + slack -} - /// Each subject's `count` nearest bodies, nearest first: pairs are measured in the order of their /// boxes' gaps (a lower bound of their distance), in rounds, until the boxes of the next ones /// are farther apart than the last neighbour kept. `known` holds distances already measured. diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 026b094f3..68dfe0758 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -217,18 +217,6 @@ fn a_thin_overlap_with_a_large_plate_is_measured_in_full() { } } -/// A shared part whose centre lies outside its own box, or which holds more than its box, is -/// malformed: the pair is reported unchecked rather than with that volume. -#[test] -fn a_malformed_shared_part_is_not_measured() { - use solidcraft_geom::{Aabb3, Vec3}; - let bbox = Aabb3 { min: Vec3::new(0.0, 0.0, 0.0), max: Vec3::new(10.0, 10.0, 1.0) }; - assert!(super::plausible(50.0, Vec3::new(5.0, 5.0, 0.5), bbox)); - assert!(!super::plausible(50.0, Vec3::new(5.0, 5.0, 3.0), bbox)); - assert!(!super::plausible(1239.0, Vec3::new(5.0, 5.0, 0.5), bbox)); - assert!(!super::plausible(f64::NAN, Vec3::new(5.0, 5.0, 0.5), bbox)); -} - /// Two plates 0.2 mm apart, the upper one set 10 mm in from the lower one's corner, and two set /// side by side with a 0.2 mm gap: 0.2, not 0 (a point past a corner, on the line of one of its /// edges, was taken for a point of the face). Gaps under twice the meshes' chord went wrong. @@ -348,13 +336,8 @@ fn a_body_that_changed_shape_is_measured_again() { /// A flanged bushing and a headed pin seated in it line to line, on its very axis, the head on /// the flange. Plain, they touch and share nothing; sunk 0.2 into the flange, the head shares the /// ring under it. With a fillet under the head against the bore's sharp edge, the fillet's ring -/// is in the flange (about 0.49 mm³), next to walls that lie on one another: the boolean tried -/// for minutes there and gave up; now it is reported as such within seconds. -/// -/// The clock is not read: what is under test is the result, and the boolean that gives up is -/// reported as such instead of hanging the test. The wall that lies on the other one is what -/// makes the pair unchecked, and that is what the assertions below check (#2999 dropped the clock -/// from the sibling tests the same way). +/// is in the flange (about 0.49 mm³), next to walls that lie on one another: an overlap. The clock +/// is not read: what is under test is the result (#2999 dropped it from the sibling tests). #[test] fn a_pin_seated_line_to_line_in_its_bushing_is_measured() { let ring = std::f64::consts::PI * (7.0f64.powi(2) - 4.0f64.powi(2)) * 0.2; @@ -371,11 +354,11 @@ fn a_pin_seated_line_to_line_in_its_bushing_is_measured() { run(&mut s, "solid.fillet", json!({"edges": [[107, 0, z + 1.5]], "radius": 0.5, "body": "Pin"})); } let r = run(&mut s, "inspect.clearance", json!({"bodies": ["Pin"], "against": ["Bush"], "min_volume": 0.01, "clearance": 1e-6})); + assert_eq!(r["unchecked"], json!([]), "sunk {sunk}: {r}"); if fillet { - assert!(r["unchecked"][0]["reason"].as_str().is_some_and(|w| w.contains("pin on one cylinder")), "{r}"); + assert!(f(&r["overlaps"][0]["volume_mm3"]) > 0.01, "{r}"); continue; } - assert_eq!(r["unchecked"], json!([]), "sunk {sunk}: {r}"); if sunk == 0.0 { assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(0), "{r}"); assert_eq!(f(&r["near"][0]["distance_mm"]), 0.0, "{r}"); @@ -386,9 +369,9 @@ fn a_pin_seated_line_to_line_in_its_bushing_is_measured() { } } -/// A chamfered pin through a hole of its own radius, its axis a hair off the hole's: the boolean -/// cannot intersect walls all but tangent along two lines and once passed the pair as clear. -/// The crescent the pin shares with the plate is reported, against the lens of two circles. +/// A chamfered pin through a hole of its own radius, its axis a hair off the hole's, the walls +/// all but tangent along two lines: the crescent the pin shares with the plate is reported, +/// against the lens of two circles. #[test] fn a_pin_a_hair_off_its_hole_shares_its_crescent() { let crescent = |r: f64, e: f64| std::f64::consts::PI * r * r - (2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt()); @@ -406,38 +389,6 @@ fn a_pin_a_hair_off_its_hole_shares_its_crescent() { } } -/// The shared volume is checked against the bodies and their union: two 10 mm cubes sharing a -/// 3 mm corner cube agree at 27 mm³, and a shared part read as three times that (as a mirrored -/// pair once was) does not. -#[test] -fn a_shared_volume_the_union_contradicts_is_caught() { - use solidcraft_geom::Vec3; - let a = solidcraft_kernel::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 10.0)).unwrap_or_else(|e| panic!("{e}")); - let b = solidcraft_kernel::box_solid(Vec3::new(7.0, 7.0, 7.0), Vec3::new(17.0, 17.0, 17.0)).unwrap_or_else(|e| panic!("{e}")); - let at = Vec3::new(8.5, 8.5, 8.5); - assert_eq!(super::union_disagrees(&a, &b, 27.0, at), None); - assert!(super::union_disagrees(&a, &b, 81.0, at).is_some()); -} - -/// The check works on measured volumes, and vol(a) + vol(b) − vol(a ∪ b) carries the error of -/// all three: a small overlap on large bodies can come out near zero, or below it. A union that -/// cannot resolve the shared part leaves it standing; one that clearly contradicts it does not. -#[test] -fn the_union_check_allows_for_the_bodies_measuring_error() { - use super::contradicted; - // 0.96 mm³ shared where the union of 40 000 and 300 mm³ implies -0.75: noise, not a contradiction. - assert_eq!(contradicted(0.96, 40_000.0, 300.0, 40_300.75), None); - // 5.92 mm³ of a small body in a large sheet, with the union 0.4 mm³ off the bodies' sum. - assert_eq!(contradicted(5.92, 250_000.0, 80.0, 250_074.48), None); - // Past the noise, but the union implies nothing at all while the shared part is small next - // to both bodies: the union cannot tell, and the shared part stands. - assert_eq!(contradicted(6.0, 400.0, 200.0, 600.5), None); - // 412 mm³ shared where bodies of a few thousand and their union imply 141: caught. - assert!(contradicted(411.98, 3_200.0, 3_150.0, 6_350.0 - 141.18).is_some()); - // A large shared part the union says is not there at all: caught too. - assert!(contradicted(900.0, 3_200.0, 3_150.0, 6_350.0).is_some()); -} - /// A small box pressed 0.6 mm into a 2000 × 1000 × 1 mm plate shares 3 × 3 × 0.6 = 5.4 mm³: an /// overlap, not an unchecked pair. #[test] @@ -490,7 +441,7 @@ fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); } let _ = std::fs::remove_dir_all(&dir); - s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() + s.world_state().unwrap().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() } /// #3249: mesh bodies are not measured, and used to vanish from the answer (`bodies: 0`, nothing diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 6042da3f5..566756418 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use solidcraft_doc::{FeatureKind, PlaneRef}; use super::CommandSpec; -use crate::params::{bad, name_or_id_list, vec3}; +use crate::params::{bad, name_or_id_values, vec3}; use crate::{Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ @@ -16,25 +16,24 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("timeline.paste", "Paste Features", paste).icon("paste").params( "translate?: [x,y,z] (moves the copies' geometry); component?: where the copies go (default: the active one), \ component_path?: its placement (default: the active one, else its only one); the copies go at the marker, each where \ - its original is in the world (copies into their own component keep its coordinates); body transfers are left out", + its original is in the world (copies into their own component keep its coordinates); body transfers are left out; \ + from_design?: true to paste sketch features from the host's cross-design clipboard snapshot", ), ]; fn copy(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.copy"; // The features are named or numbered, and both kinds can sit in one list. - let keys = name_or_id_list(cmd, p, "features")?; + let keys = name_or_id_values(cmd, p, "features")?; if keys.is_empty() || keys.len() > 1000 { return Err(bad(cmd, "`features` must list 1…1000 features")); } - let mut ids = Vec::new(); - for k in &keys { - ids.push(s.doc.find_feature(k).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{k}`")))?); - } + let ids = keys.iter().map(|key| super::edit::feature_id(s, Some(key), cmd)).collect::>>()?; // Keep timeline order so sketches come before the features that use them. let copied: Vec = s.doc.features.iter().filter(|f| ids.contains(&f.id)).cloned().collect(); let names: Vec = copied.iter().map(|f| f.name.clone()).collect(); s.clipboard = copied; + s.foreign_copy = Some(std::sync::Arc::new(crate::ForeignCopy::of_features(s))); Ok(json!({"copied": names})) } @@ -42,7 +41,7 @@ fn copy(s: &mut Session, p: &Value) -> Result { pub(in crate::cmd) fn explicit_planes(p: &mut PlaneRef) { match p { PlaneRef::Origin { name } => { - if let Some(plane) = solidcraft_geom::Plane::named(name) { + if let Some(plane) = solidcore_record::Plane::named(name) { *p = PlaneRef::Custom { plane }; } } @@ -55,6 +54,11 @@ pub(in crate::cmd) fn explicit_planes(p: &mut PlaneRef) { fn paste(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.paste"; + match p.get("from_design") { + Some(Value::Bool(true)) => return super::clipboard_foreign::paste(s, p), + None | Some(Value::Bool(false)) => {} + _ => return Err(bad(cmd, "`from_design` must be true or false")), + } if s.clipboard.is_empty() { return Err(bad(cmd, "nothing copied (timeline.copy first)")); } @@ -146,6 +150,10 @@ fn paste(s: &mut Session, p: &Value) -> Result { if !internal { notices.push(format!("pasted sketch retains external exact face attachment to {}", anchor.target.body)); } + if internal { + let source = solidcraft_doc::mat_mul(&shift, frame_change.get(&anchor.component).unwrap_or(&solidcraft_doc::IDENTITY)); + anchor.reframe_placement(&m, &source)?; + } anchor.remap_target(&sketches, &bodies)?; if internal { anchor.component = comp; @@ -235,6 +243,7 @@ fn paste(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { use serde_json::{Value, json}; + use solidcraft_geom::prelude::*; use crate::Session; @@ -249,6 +258,219 @@ mod tests { run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN) } + fn dimensioned_sketch() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.change", json!({"name": "base", "expression": "5 mm"})); + run(&mut s, "parameters.change", json!({"name": "width", "expression": "base * 4"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})); + run(&mut s, "sketch.constraint.coincident", json!({"a": "p1", "b": "origin"})); + let width = run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "width"}))["param"].as_str().unwrap().to_string(); + run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": format!("{width} / 2")})); + run(&mut s, "sketch.finish", json!({})); + s + } + + fn sketch_area(s: &Session, id: u64) -> f64 { + s.model.state().sketch(id).unwrap().profiles.iter().map(|p| p.area).sum() + } + + #[test] + fn foreign_sketch_paste_keeps_parameter_graph_snapshot_and_undo() { + let mut source = dimensioned_sketch(); + run(&mut source, "timeline.copy", json!({"features": ["S"]})); + let mut target = dimensioned_sketch(); + run(&mut target, "document.units", json!({"units": "in"})); + run(&mut target, "parameters.change", json!({"name": "base", "expression": "7 mm"})); + target.foreign_copy = source.foreign_copy.clone(); + run(&mut source, "parameters.change", json!({"name": "base", "expression": "30 mm"})); + drop(source); + let before = target.doc.to_json(); + let undo = target.undo.len(); + let result = run(&mut target, "timeline.paste", json!({"from_design": true})); + let id = result["pasted"][0]["id"].as_u64().unwrap(); + assert_eq!(result["pasted"][0]["name"], "S (2)"); + assert!((sketch_area(&target, id) - 200.).abs() < 1e-6); + assert_eq!(target.doc.param("base").unwrap().expr, "7 mm"); + assert_eq!(target.doc.param("base_2").unwrap().expr, "5 mm"); + assert_eq!(target.doc.param("width_2").unwrap().expr, "base_2 * 4"); + assert_eq!(target.undo.len(), undo + 1); + let after = target.doc.to_json(); + run(&mut target, "edit.undo", json!({})); + assert_eq!(target.doc.to_json(), before); + run(&mut target, "edit.redo", json!({})); + assert_eq!(target.doc.to_json(), after); + let second = run(&mut target, "timeline.paste", json!({"from_design": true}))["pasted"][0]["id"].as_u64().unwrap(); + assert!((sketch_area(&target, second) - 200.).abs() < 1e-6); + run(&mut target, "parameters.change", json!({"name": "base_2", "expression": "10 mm"})); + assert!((sketch_area(&target, id) - 800.).abs() < 1e-6); + assert!((sketch_area(&target, second) - 200.).abs() < 1e-6, "each paste owns its parameters"); + assert!(solidcraft_doc::Document::from_json(&target.doc.to_json()).is_ok()); + } + + #[test] + fn foreign_sketch_paste_preserves_world_position_in_a_placed_component() { + use solidcore_record::Vec3; + + let mut source = dimensioned_sketch(); + let arc = [Vec3::new(1., 0., 0.), Vec3::new(0., 0., 1.), Vec3::new(-1., 0., 0.)]; + for space in [solidcraft_sketch::WireSpace::World, solidcraft_sketch::WireSpace::Component] { + source.doc_mut().sketch_mut(1).unwrap().add_drawn_arc_in(&arc, space).unwrap(); + } + source.refresh(); + run(&mut source, "timeline.copy", json!({"features": ["S"]})); + let mut target = Session::default(); + let made = run(&mut target, "component.create", json!({"name": "Target", "activate": false})); + let component = made["component"].as_u64().unwrap(); + let occurrence = made["occurrence"].as_u64().unwrap(); + run(&mut target, "occurrence.ground", json!({"occurrence": occurrence, "grounded": false})); + run(&mut target, "occurrence.move", json!({"occurrence": occurrence, "translate": [100, 20, 30], "axis": [0, 0, 1], "angle": "90 deg"})); + target.foreign_copy = source.foreign_copy.clone(); + let id = run(&mut target, "timeline.paste", json!({"from_design": true, "component": component, "component_path": [occurrence]}))["pasted"] + [0]["id"] + .as_u64() + .unwrap(); + let original = source.world_state().unwrap().sketch(1).unwrap().plane; + let pasted = target.world_state().unwrap().sketch(id).unwrap().plane; + assert!(pasted.origin.dist(original.origin) < 1e-6, "{original:?} vs {pasted:?}"); + assert!(pasted.x.dist(original.x) < 1e-6); + assert!(pasted.y.dist(original.y) < 1e-6); + assert!((sketch_area(&target, id) - 200.).abs() < 1e-6); + assert_eq!(target.doc.feature(id).unwrap().component, component); + for (original, pasted) in + source.world_state().unwrap().sketch(1).unwrap().sketch.wires.iter().zip(&target.world_state().unwrap().sketch(id).unwrap().sketch.wires) + { + for (a, b) in original.pts.iter().chain(&original.fit).zip(pasted.pts.iter().chain(&pasted.fit)) { + assert!(a.dist(*b) < 1e-6, "wire {:?}: {a:?} vs {b:?}", original.space); + } + let (a, b) = (original.arc.unwrap(), pasted.arc.unwrap()); + assert!(a.center.dist(b.center) < 1e-6); + assert!(a.normal.dist(b.normal) < 1e-6); + assert!((a.radius - b.radius).abs() < 1e-6); + } + let moved = run( + &mut target, + "timeline.paste", + json!({"from_design": true, "component": component, "component_path": [occurrence], "translate": [2, 3, 4]}), + )["pasted"][0]["id"] + .as_u64() + .unwrap(); + let frame = target.placed_document().path_transform(component, &[occurrence]).unwrap(); + let delta = solidcraft_doc::apply_vector(&frame, Vec3::new(2., 3., 4.)); + for (original, pasted) in source + .world_state() + .unwrap() + .sketch(1) + .unwrap() + .sketch + .wires + .iter() + .zip(&target.world_state().unwrap().sketch(moved).unwrap().sketch.wires) + { + for (a, b) in original.pts.iter().chain(&original.fit).zip(pasted.pts.iter().chain(&pasted.fit)) { + assert!((*a + delta).dist(*b) < 1e-6, "translated wire {:?}: {a:?} vs {b:?}", original.space); + } + } + } + + #[test] + fn foreign_sketch_paste_refuses_external_references_and_bad_parameters_atomically() { + let mut source = dimensioned_sketch(); + let mut target = dimensioned_sketch(); + // The same numeric ID in the target must never become the sketch's missing plane. + if let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &mut source.doc_mut().feature_mut(1).unwrap().kind { + *plane = solidcraft_doc::PlaneRef::Construction { feature: 1.into() }; + } + run(&mut source, "timeline.copy", json!({"features": ["S"]})); + target.foreign_copy = source.foreign_copy.clone(); + let before = target.doc.to_json(); + let undo = target.undo.len(); + let error = target.execute("timeline.paste", &json!({"from_design": true})).unwrap_err().to_string(); + assert!(error.contains("fixed plane"), "{error}"); + assert_eq!(target.doc.to_json(), before); + assert_eq!(target.undo.len(), undo); + for params in + [json!({"from_design":"yes"}), json!({"from_design":true,"translate":"bad"}), json!({"from_design":true,"component_path":["bad"]})] + { + assert!(target.execute("timeline.paste", ¶ms).is_err()); + assert_eq!(target.doc.to_json(), before); + } + } + + #[test] + fn foreign_sketch_paste_remaps_links_and_rejects_missing_source_sketches() { + let mut source = dimensioned_sketch(); + run(&mut source, "sketch.create", json!({"plane":"XY","offset":5,"name":"Projected"})); + run(&mut source, "sketch.project", json!({"refs":[{"sketch":1,"curve":"l1"}]})); + run(&mut source, "sketch.finish", json!({})); + let mut target = dimensioned_sketch(); + run(&mut source, "timeline.copy", json!({"features":["Projected"]})); + target.foreign_copy = source.foreign_copy.clone(); + let before = target.doc.to_json(); + let err = target.execute("timeline.paste", &json!({"from_design":true})).unwrap_err().to_string(); + assert!(err.contains("external projected geometry"), "{err}"); + assert_eq!(before, target.doc.to_json()); + run(&mut source, "timeline.copy", json!({"features":["S","Projected"]})); + target.foreign_copy = source.foreign_copy.clone(); + let result = run(&mut target, "timeline.paste", json!({"from_design":true})); + let first = result["pasted"][0]["id"].as_u64().unwrap(); + let second = result["pasted"][1]["id"].as_u64().unwrap(); + let copied = target.doc.sketch(second).unwrap(); + assert!(matches!(copied.links[0].source, solidcraft_sketch::LinkSource::SketchCurve { sketch, .. } if sketch == first)); + assert!(target.model.result(second).unwrap().error.is_none()); + } + + #[test] + fn foreign_sketch_paste_keeps_plane_input_units_and_text_parameters() { + let mut source = Session::default(); + run(&mut source, "document.units", json!({"units":"in"})); + run(&mut source, "parameters.add", json!({"name":"height","expression":"2","unit":""})); + run(&mut source, "parameters.add", json!({"name":"Label","expression":"ABC","unit":"text"})); + run(&mut source, "sketch.create", json!({"plane":"XY","offset":"height","name":"Text"})); + run(&mut source, "sketch.text", json!({"text_expression":"Label + '-X'","at":[0,0],"height":"5 mm"})); + run(&mut source, "sketch.finish", json!({})); + run(&mut source, "timeline.copy", json!({"features":["Text"]})); + let mut target = Session::default(); + run(&mut target, "parameters.add", json!({"name":"Label","expression":"other","unit":"text"})); + run(&mut target, "parameters.add", json!({"name":"d1","expression":"reserved","unit":"text"})); + target.foreign_copy = source.foreign_copy.clone(); + let id = run(&mut target, "timeline.paste", json!({"from_design":true}))["pasted"][0]["id"].as_u64().unwrap(); + assert!((target.model.state().sketch(id).unwrap().plane.origin.z - 50.8).abs() < 1e-9); + assert_eq!(target.doc.text_param("Label").unwrap().text, "other"); + assert_eq!(target.doc.text_param("Label_2").unwrap().text, "ABC"); + assert_eq!(target.doc.text_param("d1").unwrap().text, "reserved"); + assert!(target.doc.param("d1").is_none()); + let state = target.model.state(); + let text = &state.sketch(id).unwrap().sketch.links[0].source; + assert!(matches!(text, solidcraft_sketch::LinkSource::Text { text, .. } if text == "ABC-X")); + assert!(solidcraft_doc::Document::from_json(&target.doc.to_json()).is_ok()); + } + + #[test] + fn foreign_sketch_paste_copies_equation_parameters_but_not_the_local_variable() { + let mut source = Session::default(); + run(&mut source, "parameters.add", json!({"name":"height","expression":"3 mm"})); + run(&mut source, "sketch.create", json!({"plane":"XY","name":"Curve"})); + run(&mut source, "sketch.equation_curve", json!({"x":"t","y":"height + t * t","start":-2,"end":2})); + run(&mut source, "sketch.finish", json!({})); + run(&mut source, "timeline.copy", json!({"features":["Curve"]})); + let mut target = Session::default(); + run(&mut target, "parameters.add", json!({"name":"height","expression":"99 mm"})); + target.foreign_copy = source.foreign_copy.clone(); + let id = run(&mut target, "timeline.paste", json!({"from_design":true}))["pasted"][0]["id"].as_u64().unwrap(); + let state = target.model.state(); + let sketch = &state.sketch(id).unwrap().sketch; + let equation = &sketch.equations[0]; + assert_eq!(equation.x.as_deref(), Some("t")); + assert_eq!(equation.y, "height_2 + t * t"); + let curve = sketch.curves.iter().find(|c| c.id == equation.curve).unwrap(); + for point in curve.kind.point_ids() { + let p = sketch.points[point].pos; + assert!((p.y - 3. - p.x * p.x).abs() < 1e-8, "{p:?}"); + } + assert!(target.doc.param("t").is_none()); + } + /// Features pasted into a component placed elsewhere (offset and turned) are carried into its /// frame: the pasted body sits where the original is in the world, in that component, and the /// pasted sketch is named after the original. @@ -267,7 +489,7 @@ mod tests { let r = run(&mut s, "timeline.paste", json!({"component": a, "component_path": [at]})); assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}"); assert_eq!(r["pasted"][0]["name"], "S (2)"); - let world = s.world_state(); + let world = s.world_state().unwrap(); let (original, copy) = (world.body("Block").unwrap().mesh().bounds(), world.body("Block (2)").unwrap().mesh().bounds()); assert!(copy.min.dist(original.min) < 1e-6 && copy.max.dist(original.max) < 1e-6, "{original:?} vs {copy:?}"); let state = s.model.state(); @@ -624,7 +846,7 @@ mod tests { let spring = r["pasted"][1]["name"].as_str().unwrap_or_default().to_string(); let def = run(&mut s, "timeline.inspect", json!({"feature": spring})); assert_eq!(def["definition"]["targets"], json!(["Plate (2)"]), "{def}"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let v = |name: &str| solidcraft_kernel::measure(&st.body(name).unwrap().body).unwrap().volume; // A spring on the wrong plate is hundreds of mm³ off. The two plates are measured apart // (one moved 50 mm), which the boolean and the measure each round in their own way: diff --git a/crates/engine/src/cmd/clipboard_foreign.rs b/crates/engine/src/cmd/clipboard_foreign.rs new file mode 100644 index 000000000..b33960a8c --- /dev/null +++ b/crates/engine/src/cmd/clipboard_foreign.rs @@ -0,0 +1,310 @@ +//! Independent sketch features pasted from the immutable clipboard of another design. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Value, json}; +use solidcraft_doc::{Document, Feature, FeatureKind, Mat, PlaneRef}; + +use crate::params::{bad, vec3}; +use crate::{Result, Sel, Session}; + +const CMD: &str = "timeline.paste"; + +/// References to geometry outside the copied sketches must never resolve against coincident +/// IDs or names in the destination. Fixed and expression-placed planes are self-contained. +fn independent_plane(plane: &PlaneRef, depth: usize) -> Result<()> { + if depth > 64 { + return Err(bad(CMD, "copied plane nesting exceeds 64")); + } + match plane { + PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } => Ok(()), + PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } | PlaneRef::AtAngle { base, line: None, .. } => { + independent_plane(base, depth + 1) + } + _ => Err(bad(CMD, "the copied sketch's plane depends on model geometry; convert it to a fixed plane before pasting into another design")), + } +} + +fn independent_links(sketch: &solidcraft_sketch::Sketch, features: &BTreeSet, moved: bool) -> Result<()> { + use solidcraft_sketch::LinkSource as L; + for link in &sketch.links { + let supported = match &link.source { + L::Text { .. } | L::SketchAxis { .. } => true, + L::SketchCurve { sketch, .. } | L::SketchPoint { sketch, .. } => features.contains(sketch), + L::Origin | L::Axis { .. } => !moved, + L::Plane { name } => !moved && solidcore_record::Plane::named(name).is_some(), + _ => false, + }; + if !supported { + return Err(bad( + CMD, + "the copied sketch has external projected geometry; unlink it or copy its source sketches before pasting into another design", + )); + } + } + Ok(()) +} + +fn free_parameter_name(base: &str, taken: &mut BTreeSet) -> Result { + for index in 1..=solidcraft_doc::MAX_PARAMS + 1 { + let name = if index == 1 { base.to_string() } else { format!("{base}_{index}") }; + if Document::param_name_problem(&name).is_none() && taken.insert(name.clone()) { + return Ok(name); + } + } + Err(bad(CMD, format!("no free name for copied parameter {base}"))) +} + +fn model_parameter_name(taken: &mut BTreeSet) -> Result { + for index in 1..=taken.len() + 1 { + let name = format!("d{index}"); + if taken.insert(name.clone()) { + return Ok(name); + } + } + Err(bad(CMD, "no free model parameter name")) +} + +/// Bring the complete expression dependency graph, including dimensions driven by another +/// dimension. Use the source definitions' units, never a destination parameter with the same name. +fn parameters(target: &mut Document, source: &Document, features: &[Feature], mapped: &mut BTreeMap) -> Result<()> { + let definitions: BTreeMap<_, _> = source.param_defs().into_iter().map(|p| (p.name.clone(), p)).collect(); + let mut pending: Vec = features.iter().flat_map(|f| f.kind.expressions()).flat_map(solidcraft_doc::expr::references).collect(); + let mut texts = BTreeSet::new(); + for feature in features { + if let FeatureKind::Sketch { sketch, .. } = &feature.kind { + pending.extend(sketch.constraints.iter().filter_map(|c| c.param.clone())); + let text_and_points = sketch + .links + .iter() + .filter_map(|l| match &l.source { + solidcraft_sketch::LinkSource::Text { exprs, .. } => Some(exprs.list()), + _ => None, + }) + .flatten() + .chain(sketch.points.iter().filter_map(|p| p.exprs.as_deref()).flat_map(solidcraft_sketch::PointExprs::list)); + pending.extend(text_and_points.flat_map(|(_, e)| solidcraft_doc::expr::references(e))); + for equation in &sketch.equations { + pending + .extend(equation.list().into_iter().flat_map(|(_, e)| solidcraft_doc::expr::references(e)).filter(|n| n != equation.variable())); + } + texts.extend(sketch.text_word_exprs().into_iter().flat_map(|e| solidcraft_doc::text_params::references(e))); + } + } + let mut used = BTreeSet::new(); + let mut work = 0; + while let Some(name) = pending.pop() { + work += 1; + if work > 100_000 { + return Err(bad(CMD, "copied parameter references exceed work limit")); + } + if used.insert(name.clone()) { + let p = definitions.get(&name).ok_or_else(|| bad(CMD, format!("copied sketch uses missing parameter {name}")))?; + pending.extend(solidcraft_doc::expr::references(&p.expr)); + } + } + if target.params.len() + target.text_params.len() + used.len() + texts.len() > solidcraft_doc::MAX_PARAMS { + return Err(bad(CMD, "too many copied parameters")); + } + let mut taken: BTreeSet<_> = target.param_defs().into_iter().map(|p| p.name).chain(target.text_params.iter().map(|p| p.name.clone())).collect(); + for name in &used { + if mapped.contains_key(name) { + continue; + } + let definition = definitions.get(name).ok_or_else(|| bad(CMD, "missing copied parameter definition"))?; + let model = source.param(name).is_none_or(|p| p.model); + let new = if model { + let new = model_parameter_name(&mut taken)?; + target.params.push(solidcraft_doc::Param { + name: new.clone(), + expr: definition.expr.clone(), + unit: definition.unit.clone(), + comment: String::new(), + model: true, + }); + new + } else { + let new = free_parameter_name(name, &mut taken)?; + let mut p = source.param(name).cloned().ok_or_else(|| bad(CMD, "missing copied user parameter"))?; + p.name = new.clone(); + target.params.push(p); + new + }; + mapped.insert(name.clone(), new); + } + for name in texts { + let mut p = source.text_param(&name).cloned().ok_or_else(|| bad(CMD, format!("copied sketch uses missing text parameter {name}")))?; + p.name = free_parameter_name(&name, &mut taken)?; + mapped.insert(name, p.name.clone()); + target.text_params.push(p); + } + for (old, new) in mapped.iter() { + if let Some(definition) = definitions.get(old) + && let Some(p) = target.params.iter_mut().find(|p| p.name == *new) + { + p.expr = solidcraft_doc::clone_expression(&definition.expr, mapped); + p.comment = source.param(old).map(|p| p.comment.clone()).or_else(|| source.param_comments.get(old).cloned()).unwrap_or_default(); + } + if let Some(comment) = source.param_comments.get(old) { + target.param_comments.insert(new.clone(), comment.clone()); + } + } + Ok(()) +} + +fn text_expression(source: &str, mapped: &BTreeMap) -> String { + let mut result = source.to_string(); + let mut temporary = Vec::new(); + for (i, (old, new)) in mapped.iter().enumerate() { + let mut token = format!("__paste_text_{i}"); + while source.contains(&token) || mapped.keys().chain(mapped.values()).any(|name| name == &token) { + token.push('_'); + } + result = solidcraft_doc::text_params::rename_reference(&result, old, &token); + temporary.push((token, new)); + } + for (token, new) in temporary { + result = solidcraft_doc::text_params::rename_reference(&result, &token, new); + } + result +} + +pub(super) fn paste(s: &mut Session, p: &Value) -> Result { + let copy = s.foreign_copy.clone().ok_or_else(|| bad(CMD, "nothing was copied in another design"))?; + if copy.features.is_empty() || copy.features.len() > 1000 { + return Err(bad(CMD, "copy 1…1000 sketches before pasting into another design")); + } + let component = match p.get("component") { + None => s.active_component, + Some(v) => { + let key = match v { + Value::String(name) => name.clone(), + Value::Number(n) => n.to_string(), + _ => return Err(bad(CMD, "`component` must be a component id or name")), + }; + s.doc.find_component(&key).ok_or_else(|| bad(CMD, format!("no component `{key}`")))? + } + }; + let path = match p.get("component_path") { + Some(v) => v + .as_array() + .filter(|a| a.len() <= 64) + .and_then(|a| a.iter().map(Value::as_u64).collect::>>()) + .ok_or_else(|| bad(CMD, "`component_path` must list 0..64 occurrence ids"))?, + None if component == s.active_component => s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(component)), + None => super::component::placing::placement_of(s, &s.placed_document(), component, None, "component_path", CMD)?.0, + }; + let placed = s.placed_document(); + let frame = placed.path_transform(component, &path).ok_or_else(|| bad(CMD, "that path is not a placement of the target"))?; + let into_target = solidcraft_doc::mat_inverse(&frame).ok_or_else(|| bad(CMD, "the target's frame is not invertible"))?; + drop(placed); + let mut shift = solidcraft_doc::IDENTITY; + if let Some(t) = p.get("translate") { + let t = vec3(t).ok_or_else(|| bad(CMD, "`translate` must be [x, y, z]"))?; + shift[3] = [t.x, t.y, t.z, 1.]; + } + let world_shift = solidcraft_doc::mat_mul(&frame, &solidcraft_doc::mat_mul(&shift, &into_target)); + let mut placed_source = (*copy.doc).clone(); + for occurrence in &mut placed_source.occurrences { + if let Some(m) = copy.pending_moves.get(&occurrence.id) { + occurrence.transform = *m; + } + } + let selected: BTreeSet<_> = copy.features.iter().map(|f| f.id).collect(); + let mut transforms: BTreeMap = BTreeMap::new(); + for feature in ©.features { + let FeatureKind::Sketch { plane, sketch } = &feature.kind else { + return Err(bad(CMD, "only sketch features can be pasted between designs; copy a component to include other feature history")); + }; + independent_plane(plane, 0)?; + let source_frame = placed_source + .path_transform(feature.component, &placed_source.first_path(feature.component)) + .ok_or_else(|| bad(CMD, "the copied sketch's component placement is missing"))?; + let transform = solidcraft_doc::mat_mul(&shift, &solidcraft_doc::mat_mul(&into_target, &source_frame)); + independent_links(sketch, &selected, !solidcraft_doc::is_identity(&transform))?; + transforms.insert(feature.id, transform); + } + let mut scratch = s.scratch(); + let mut mapped = BTreeMap::new(); + let mut ids = BTreeMap::new(); + let mut names = BTreeMap::new(); + let mut made = Vec::new(); + for feature in ©.features { + let taken = |name: &str| scratch.doc.features.iter().any(|f| f.name == name); + let name = if taken(&feature.name) { solidcraft_doc::copy_name(&feature.name, taken) } else { feature.name.clone() }; + let id = scratch.doc_mut().add_feature(feature.kind.clone(), Some(&name))?; + let mut taken: BTreeSet<_> = + scratch.doc.param_defs().into_iter().map(|p| p.name).chain(scratch.doc.text_params.iter().map(|p| p.name.clone())).collect(); + let text_names: BTreeSet<_> = scratch.doc.text_params.iter().map(|p| p.name.clone()).collect(); + if let Some(added) = scratch.doc_mut().feature_mut(id) { + for name in &mut added.param_names { + if text_names.contains(name) { + *name = model_parameter_name(&mut taken)?; + } + } + } + if let Some(added) = scratch.doc.feature(id) { + mapped.extend(feature.param_names.iter().cloned().zip(added.param_names.iter().cloned())); + } + ids.insert(feature.id, id); + names.insert(feature.name.clone(), name.clone()); + made.push(json!({"id": id, "name": name, "from": feature.name})); + } + parameters(scratch.doc_mut(), ©.doc, ©.features, &mut mapped)?; + let source_values = copy.doc.param_values().0; + for original in ©.features { + let mut feature = original.clone(); + let transform = transforms.get(&original.id).ok_or_else(|| bad(CMD, "missing copied sketch transform"))?; + // Nonliteral unitless length inputs are interpreted in their design's display units. + // Make that unit explicit before moving the expressions to a design with other units. + if copy.doc.units != s.doc.units { + for (_, e, kind) in feature.kind.inputs_mut() { + if kind == solidcraft_doc::expr::Kind::Length + && !solidcraft_doc::expr::is_literal(e) + && let Some((solidcraft_doc::expr::Kind::Length, scale)) = solidcraft_doc::expr::unit_info(copy.doc.units.trim()) + && solidcraft_doc::expr::eval_with(e, &|name| { + source_values.get(name).copied().ok_or_else(|| solidcraft_doc::DocError::Expr(format!("unknown parameter {name}"))) + })? + .unitless() + { + *e = format!("({e}) * {scale} mm").into(); + } + } + } + feature.remap_clone(&ids, &names, &BTreeMap::new(), &mapped)?; + if let FeatureKind::Sketch { plane, sketch } = &mut feature.kind { + // 3D wires carry their own coordinate space, independently of the sketch plane. + for wire in &mut sketch.wires { + let matrix = if wire.space == solidcraft_sketch::WireSpace::Component { transform } else { &world_shift }; + solidcraft_doc::map_wire(wire, matrix); + } + // Patterns and text words have expressions outside FeatureKind's numeric inputs. + for pattern in &mut sketch.patterns { + for e in pattern.count_expression.iter_mut().chain(pattern.expressions.values_mut()) { + *e = solidcraft_doc::clone_expression(e, &mapped); + } + } + for e in sketch.text_word_exprs_mut() { + *e = text_expression(e, &mapped); + } + if !solidcraft_doc::is_identity(transform) { + super::clipboard::explicit_planes(plane); + } + } + feature.kind.transform_geometry(transform); + let id = *ids.get(&original.id).ok_or_else(|| bad(CMD, "missing copied sketch id"))?; + let added = scratch.doc_mut().feature_mut(id).ok_or_else(|| bad(CMD, "missing pasted sketch"))?; + added.kind = feature.kind; + added.component = component; + added.suppressed = original.suppressed; + } + scratch.refresh(); + for id in ids.values() { + if let Some(error) = scratch.model.result(*id).and_then(|r| r.error.as_ref()) { + return Err(bad(CMD, format!("the pasted sketch did not rebuild: {error}"))); + } + } + scratch.selection = ids.values().map(|id| Sel::Feature { id: *id }).collect(); + s.accept_computed(scratch); + Ok(json!({"pasted": made, "errors": [], "notices": []})) +} diff --git a/crates/engine/src/cmd/compare.rs b/crates/engine/src/cmd/compare.rs index 439198c1c..00ae0abfa 100644 --- a/crates/engine/src/cmd/compare.rs +++ b/crates/engine/src/cmd/compare.rs @@ -1,36 +1,51 @@ //! Compare Bodies: two versions of one part laid over each other. Both are measured, each //! surface's distance to the other is sampled, and the places where only one of them has -//! material are found, measured and, on request, coloured. It works from the surfaces -//! ([`solidcraft_geom::compare`]), not from a boolean of the two bodies, so bodies that share -//! almost every face compare as well as any. +//! material are found, measured and, on request, coloured. The places are found from the +//! surfaces ([`solidcraft_geom::compare`]), so bodies that share almost every face compare as +//! well as any; each place's volume, centre and box are then measured exactly, on the pieces of +//! the two cuts a − b and b − a that lie there, as `inspect.measure` measures a body. -use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use serde_json::Value; +use solidcore_record::Vec3; +use solidcraft_geom::Aabb3; use solidcraft_geom::compare::{self, CompareOptions, Side}; +use solidcraft_geom::prelude::*; use super::CommandSpec; use crate::params::bad; +use crate::schema::compare::{ + Bounds, CompareParams, CompareSide, Comparison, Deviation, Deviations, Difference, MeasuredBy, Region, Resolution, Sampling, SideTotal, +}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Sel, Session}; -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.compare", "Compare Bodies", compare_bodies).icon("compare").params( +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.compare", "Compare Bodies", crate::checked!("inspect.compare", compare_bodies)) + .icon("compare") + .contract(&CONTRACT) + .output(output_schema_for::) + .params( "a, b: body names (default: the two selected bodies, or the design's only two), in world placement; tolerance?: mm (0.001 to 10, default 0.01): \ surfaces closer than this agree; spacing?: mm (default 0.5): the largest piece of a face sampled as one point, coarser for a body that would need \ more than max_points? (default 8 million, up to 50 million) samples; max_regions? (default 50); color?: true | {only_in_a?, only_in_b?: \"#rrggbb\"} \ (colours the faces that hold a region, red where only a has material and green where only b has: the faces mostly beyond the tolerance, else the \ one with the largest share; an undo step) → a, b: volume_mm3, area_mm2, center_of_mass, bbox; difference: b − a; \ - deviation: a_to_b, b_to_a (max_mm, mean_mm, at, area_beyond_mm2); regions, largest first: side (only_in_a | only_in_b), volume_mm3 (integrated along \ - lines through the region: resolution), area_mm2, max_deviation_mm, at, center, bbox, faces_a, faces_b (face indices, as model.faces lists them); \ - identical; verdict; warnings (a body whose surface does not enclose what it measures, lines left out). Works from the two surfaces, without a boolean of the bodies, so near-identical bodies compare too", + deviation: a_to_b, b_to_a (max_mm, mean_mm, at, area_beyond_mm2); regions, largest first: side (only_in_a | only_in_b), volume_mm3, center and bbox (measured_by: \"boolean\": exact, the pieces of a − b or \ + b − a there, measured as inspect.measure does; \"not measured\": the cut could not be made, so volume_mm3 and center are null and \ + not_measured says why, never an estimate), area_mm2, max_deviation_mm, at, faces_a, faces_b (face indices, as model.faces lists them); identical; verdict; warnings \ + (a body whose surface does not enclose what it measures, lines left out, a cut that could not be made). The regions are found from the two \ + surfaces, so near-identical bodies compare too", )]; /// Default colours: red for material only `a` has, green for material only `b` has. const ONLY_IN_A: [u8; 3] = [0xe0, 0x31, 0x31]; const ONLY_IN_B: [u8; 3] = [0x2f, 0x9e, 0x44]; -fn side_name(s: Side) -> &'static str { +fn side_of(s: Side) -> CompareSide { match s { - Side::OnlyInA => "only_in_a", - Side::OnlyInB => "only_in_b", + Side::OnlyInA => CompareSide::OnlyInA, + Side::OnlyInB => CompareSide::OnlyInB, } } @@ -100,21 +115,21 @@ fn v3(v: &Value) -> Option { } /// b − a of the two bodies' measures. -fn difference(ma: &Value, mb: &Value) -> Value { +fn difference(ma: &Value, mb: &Value) -> Difference { let f = |m: &Value, k: &str| m.get(k).and_then(Value::as_f64); let sub = |x: Option, y: Option| x.zip(y).map(|(x, y)| y - x); let (va, vb) = (f(ma, "volume_mm3"), f(mb, "volume_mm3")); let com = v3(&ma["center_of_mass"]).zip(v3(&mb["center_of_mass"])).map(|(a, b)| b - a); - let corner = |k: &str| v3(&ma["bbox"][k]).zip(v3(&mb["bbox"][k])).map(|(a, b)| b - a); - json!({ - "volume_mm3": sub(va, vb), - "volume_percent": va.zip(vb).filter(|(a, _)| a.abs() > 0.0).map(|(a, b)| 100.0 * (b - a) / a), - "area_mm2": sub(f(ma, "area_mm2"), f(mb, "area_mm2")), - "center_of_mass": com, - "center_of_mass_distance_mm": com.map(Vec3::len), - "bbox_min": corner("min"), - "bbox_max": corner("max"), - }) + let corner = |k: &str| v3(&ma["bbox"][k]).zip(v3(&mb["bbox"][k])).map(|(a, b)| (b - a).into()); + Difference { + volume_mm3: sub(va, vb), + volume_percent: va.zip(vb).filter(|(a, _)| a.abs() > 0.0).map(|(a, b)| 100.0 * (b - a) / a), + area_mm2: sub(f(ma, "area_mm2"), f(mb, "area_mm2")), + center_of_mass: com.map(Into::into), + center_of_mass_distance_mm: com.map(Vec3::len), + bbox_min: corner("min"), + bbox_max: corner("max"), + } } /// The volume a closed mesh encloses (divergence theorem, about its box's centre). @@ -124,8 +139,8 @@ fn enclosed_volume(m: &solidcraft_geom::Mesh) -> f64 { } /// What makes the comparison less certain: a body whose surface does not enclose what it -/// measures (open, or faces that failed), lines left out of region volumes. -fn warnings(bodies: [(&str, &Value, &solidcraft_geom::Mesh); 2], chord: f64, c: &compare::Comparison) -> Vec { +/// measures (open, or faces that failed). +fn warnings(bodies: [(&str, &Value, &solidcraft_geom::Mesh); 2], chord: f64) -> Vec { let mut out = Vec::new(); for (name, measure, mesh) in bodies { let (Some(v), area) = (measure["volume_mm3"].as_f64(), measure["area_mm2"].as_f64().unwrap_or(0.0)) else { continue }; @@ -137,15 +152,111 @@ fn warnings(bodies: [(&str, &Value, &solidcraft_geom::Mesh); 2], chord: f64, c: )); } } - let skipped: usize = c.regions.iter().map(|r| r.lines.skipped).sum(); - if skipped > 0 { - out.push(format!("{skipped} line(s) through the regions crossed a gap in a surface and were left out of their volumes")); - } out } -fn deviation_json(d: &compare::Deviation) -> Value { - json!({"max_mm": d.max, "mean_mm": d.mean, "at": d.at, "area_beyond_mm2": d.beyond_area, "area_mm2": d.area, "points": d.points}) +/// A region's volume, centre and box, measured exactly. +#[derive(Clone, Copy, Debug)] +struct Measured { + volume: f64, + center: Vec3, + bbox: Aabb3, +} + +/// The pieces of `from` − `tool`, the material only `from` has, each measured as +/// `inspect.measure` measures a body (none when `tool` takes all of it). +fn cut_pieces(from: &solidcraft_kernel::Body, tool: &solidcraft_kernel::Body) -> std::result::Result, String> { + let rest = solidcraft_kernel::boolean(from, tool, solidcraft_kernel::BoolOp::Cut).map_err(|e| e.to_string())?; + let Some(rest) = rest else { return Ok(Vec::new()) }; + rest.lumps() + .map_err(|e| e.to_string())? + .iter() + .map(|piece| { + let m = solidcraft_kernel::measure_mass(piece).map_err(|e| e.to_string())?; + Ok(Measured { volume: m.volume, center: m.centroid, bbox: m.bbox }) + }) + .collect() +} + +/// How much of `piece` lies by `region`: the volume their boxes, each grown by `pad`, share +/// (0 when they do not meet). Grown, so a region found as a flat patch of surface still holds +/// the piece on it. +fn overlap(piece: &Aabb3, region: &Aabb3, pad: f64) -> f64 { + let shared = piece.inflated(pad).intersection(®ion.inflated(pad)); + if shared.is_empty() { + return 0.0; + } + let d = shared.size(); + d.x * d.y * d.z +} + +/// Each region's exact measure: the pieces of the cut on its side (a − b for material only `a` +/// has, b − a for material only `b` has), each given to the region of that side whose box holds +/// most of it, summed. A piece by no region is thinner than the tolerance or in a region not +/// listed. `None` for a region whose cut could not be made or that no piece fell to; the second +/// value says why, once per side. +fn exact_regions( + a: &solidcraft_kernel::Body, + b: &solidcraft_kernel::Body, + c: &compare::Comparison, + pad: f64, +) -> (Vec>, Vec) { + let sides = [Side::OnlyInA, Side::OnlyInB]; + let wanted: Vec = sides.into_iter().filter(|side| c.regions.iter().any(|r| r.side == *side)).collect(); + let cuts = solidcraft_kernel::map_on_threads(&wanted, 2, |side| match side { + Side::OnlyInA => cut_pieces(a, b), + Side::OnlyInB => cut_pieces(b, a), + }); + // (volume, volume × centre, box) of the pieces each region holds. + let mut sums: Vec> = vec![None; c.regions.len()]; + let mut failed = Vec::new(); + for (side, cut) in wanted.iter().zip(cuts) { + let pieces = match cut { + Some(Ok(pieces)) => pieces, + Some(Err(e)) => { + failed.push((*side, e)); + continue; + } + None => { + failed.push((*side, "the cut failed".to_string())); + continue; + } + }; + for p in pieces.iter().filter(|p| p.volume.is_finite() && p.center.is_finite() && p.volume > 0.0) { + let best = c + .regions + .iter() + .enumerate() + .filter(|(_, r)| r.side == *side) + .map(|(i, r)| (i, overlap(&p.bbox, &r.bbox, pad))) + .filter(|(_, o)| *o > 0.0) + .max_by(|x, y| x.1.total_cmp(&y.1)); + let Some((i, _)) = best else { continue }; + if let Some(slot) = sums.get_mut(i) { + let (v, m, bb) = slot.get_or_insert((0.0, Vec3::ZERO, Aabb3::EMPTY)); + *v += p.volume; + *m += p.center * p.volume; + *bb = bb.union(&p.bbox); + } + } + } + let measured = sums.into_iter().map(|x| x.map(|(v, m, bbox)| Measured { volume: v, center: m / v, bbox })).collect::>(); + let mut notes: Vec = failed + .iter() + .map(|(side, e)| { + let (from, tool) = if *side == Side::OnlyInA { ("a", "b") } else { ("b", "a") }; + format!("the cut {from} − {tool} could not be made ({e}): its regions' volumes are not measured") + }) + .collect(); + let unmatched = c.regions.iter().zip(&measured).filter(|(r, m)| m.is_none() && !failed.iter().any(|(side, _)| *side == r.side)).count(); + if unmatched > 0 { + notes.push(format!("{unmatched} region(s) held no piece of the cut: their volumes are not measured")); + } + (measured, notes) +} + +fn deviation(d: &compare::Deviation) -> Deviation { + Deviation { max_mm: d.max, mean_mm: d.mean, at: d.at.into(), area_beyond_mm2: d.beyond_area, area_mm2: d.area, points: d.points } } fn compare_bodies(s: &mut Session, p: &Value) -> Result { @@ -155,15 +266,17 @@ fn compare_bodies(s: &mut Session, p: &Value) -> Result { let max_points = number(cmd, p, "max_points", 8e6, 1e4..=5e7)? as usize; let max_regions = number(cmd, p, "max_regions", 50.0, 1.0..=1000.0)? as usize; let colors = colours(cmd, p)?; - let st = s.world_state(); + let st = s.world_state()?; let (na, nb) = pair(s, &st, p, cmd)?; let (Some(ba), Some(bb)) = (st.body(&na), st.body(&nb)) else { return Err(bad(cmd, "no such body")) }; // Meshed within a quarter of the tolerance (the kernel goes no finer than a millionth of a // body's size), so two meshes of one surface agree well within it. let chord = tolerance / 4.0; - let mut done = solidcraft_kernel::map_on_threads(&[ba, bb], 2, |b| (super::inspect::measure_json(b), b.body.tessellate_with(chord, true))) - .into_iter() - .zip([&na, &nb]); + let mut done = solidcraft_kernel::map_on_threads(&[ba, bb], 2, |b| { + (super::inspect::measure_json(b), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(chord))) + }) + .into_iter() + .zip([&na, &nb]); let mut next = || -> Result<(Value, solidcraft_geom::Mesh)> { let Some((r, name)) = done.next() else { return Err(bad(cmd, "no such body")) }; let (m, mesh) = r.ok_or_else(|| bad(cmd, format!("`{name}`: measuring it failed")))?; @@ -180,71 +293,112 @@ fn compare_bodies(s: &mut Session, p: &Value) -> Result { solidcraft_kernel::for_each_on_threads(&jobs, 16, |i| job(*i)); }; let c = compare::compare(&mesh_a, &mesh_b, &options, &each); + // The regions' exact volumes, from the cuts of two bodies that enclose volumes. + let (exact, exact_notes) = if c.regions.is_empty() { + (Vec::new(), Vec::new()) + } else if super::inspect::encloses_volume(&ba.body) && super::inspect::encloses_volume(&bb.body) { + exact_regions(&ba.body, &bb.body, &c, c.spacing.max(tolerance)) + } else { + (vec![None; c.regions.len()], vec!["a body encloses no volume, so the regions' volumes are not measured".to_string()]) + }; + // A region's exact volume, centre and box, or none: never the lines' estimate in its place. + let measured = |i: usize| exact.get(i).copied().flatten(); + // Largest first: by the exact volume, then (unmeasured) by area. + let mut order: Vec = (0..c.regions.len()).collect(); + let key = |i: usize| (measured(i).map(|m| m.volume), c.regions.get(i).map_or(0.0, |r| r.area_a + r.area_b)); + order.sort_by(|&x, &y| match (key(x).0, key(y).0) { + (Some(vx), Some(vy)) => vy.total_cmp(&vx), + (Some(_), None) => std::cmp::Ordering::Less, + (None, Some(_)) => std::cmp::Ordering::Greater, + (None, None) => key(y).1.total_cmp(&key(x).1), + }); + let reason = |i: usize| -> String { + let side = c.regions.get(i).map(|r| r.side); + let mine = |n: &&String| side.is_some_and(|s| n.starts_with(if s == Side::OnlyInA { "the cut a" } else { "the cut b" })); + exact_notes.iter().find(mine).or_else(|| exact_notes.last()).cloned().unwrap_or_else(|| "the exact cut gave no piece here".to_string()) + }; let axis = |k: usize| ["X", "Y", "Z"].get(k).copied().unwrap_or("?"); - let regions: Vec = c - .regions + let regions: Vec = order .iter() .enumerate() - .map(|(i, r)| { - json!({ - "index": i + 1, - "side": side_name(r.side), - "material_of": if r.side == Side::OnlyInA { &na } else { &nb }, - "volume_mm3": r.volume, - "area_mm2": r.area_a + r.area_b, - "area_a_mm2": r.area_a, - "area_b_mm2": r.area_b, - "max_deviation_mm": r.max_deviation, - "at": r.at, - "center": r.center, - "bbox": {"min": r.bbox.min, "max": r.bbox.max}, - "faces_a": r.faces_a.iter().map(|x| x.0).collect::>(), - "faces_b": r.faces_b.iter().map(|x| x.0).collect::>(), - "resolution": {"along": axis(r.lines.axis), "line_spacing_mm": r.lines.spacing, "lines": r.lines.count, "skipped_lines": r.lines.skipped}, - }) + .filter_map(|(i, &k)| c.regions.get(k).map(|r| (i, k, r))) + .map(|(i, k, r)| { + let m = measured(k); + let bbox = m.map_or(r.bbox, |m| m.bbox); + Region { + index: i + 1, + side: side_of(r.side), + material_of: if r.side == Side::OnlyInA { na.clone() } else { nb.clone() }, + volume_mm3: m.map(|m| m.volume), + measured_by: if m.is_some() { MeasuredBy::Boolean } else { MeasuredBy::NotMeasured }, + not_measured: if m.is_some() { None } else { Some(reason(k)) }, + area_mm2: r.area_a + r.area_b, + area_a_mm2: r.area_a, + area_b_mm2: r.area_b, + max_deviation_mm: r.max_deviation, + at: r.at.into(), + center: m.map(|m| m.center.into()), + bbox: Bounds { min: bbox.min.into(), max: bbox.max.into() }, + faces_a: r.faces_a.iter().map(|x| x.0).collect(), + faces_b: r.faces_b.iter().map(|x| x.0).collect(), + resolution: Resolution { + along: axis(r.lines.axis).to_string(), + line_spacing_mm: r.lines.spacing, + lines: r.lines.count, + skipped_lines: r.lines.skipped, + }, + } }) .collect(); + // A side's total, or none when one of its regions is not measured. let total = |side: Side| { - let rs: Vec<&compare::Region> = c.regions.iter().filter(|r| r.side == side).collect(); + let rs: Vec> = + (0..c.regions.len()).filter(|&i| c.regions.get(i).is_some_and(|r| r.side == side)).map(|i| measured(i).map(|m| m.volume)).collect(); // `+ 0.0`: an empty sum is -0.0. - (rs.len(), rs.iter().map(|r| r.volume).filter(|v| v.is_finite()).sum::() + 0.0) + (rs.len(), rs.iter().copied().sum::>().map(|v| v + 0.0)) }; let ((ca, va), (cb, vb)) = (total(Side::OnlyInA), total(Side::OnlyInB)); let worst = c.a_to_b.max.max(c.b_to_a.max); let identical = c.regions.is_empty() && c.unlisted == 0; - let warnings = warnings([(na.as_str(), &measure_a, &mesh_a), (nb.as_str(), &measure_b, &mesh_b)], chord, &c); + let mut warnings = warnings([(na.as_str(), &measure_a, &mesh_a), (nb.as_str(), &measure_b, &mesh_b)], chord); + warnings.extend(exact_notes); let mut verdict = if identical { format!("identical within {tolerance} mm (largest deviation {worst:.4} mm)") } else { let more = if c.unlisted > 0 { format!(" (and {} more, not measured)", c.unlisted) } else { String::new() }; format!( - "{} {} by more than {tolerance} mm: {ca} with material only in `{na}` ({va:.3} mm³), {cb} only in `{nb}` ({vb:.3} mm³){more}", + "{} {} by more than {tolerance} mm: {ca} with material only in `{na}` ({}), {cb} only in `{nb}` ({}){more}", c.regions.len(), - if c.regions.len() == 1 { "region differs" } else { "regions differ" } + if c.regions.len() == 1 { "region differs" } else { "regions differ" }, + va.map_or("volume not measured".to_string(), |v| format!("{v:.3} mm³")), + vb.map_or("volume not measured".to_string(), |v| format!("{v:.3} mm³")), ) }; if !warnings.is_empty() { verdict += &format!(" ({} warning{})", warnings.len(), if warnings.len() == 1 { "" } else { "s" }); } - let mut out = json!({ - "a": measure_a, - "b": measure_b, - "difference": difference(&measure_a, &measure_b), - "tolerance_mm": tolerance, - "deviation": {"a_to_b": deviation_json(&c.a_to_b), "b_to_a": deviation_json(&c.b_to_a), "max_mm": worst}, - "identical": identical, - "verdict": verdict, - "regions": regions, - "only_in_a": {"regions": ca, "volume_mm3": va}, - "only_in_b": {"regions": cb, "volume_mm3": vb}, - "unlisted_regions": c.unlisted, - "warnings": warnings, - "sampling": {"spacing_mm": c.spacing, "chord_mm": chord, "triangles_a": mesh_a.triangles.len(), "triangles_b": mesh_b.triangles.len()}, - }); - if let Some(colors) = colors { - out["colored_faces"] = json!(color_regions(s, &c, [&na, &nb], colors)?); - } - Ok(out) + let colored_faces = match colors { + Some(colors) => Some(color_regions(s, &c, [&na, &nb], colors)?), + None => None, + }; + let out = Comparison { + difference: difference(&measure_a, &measure_b), + a: measure_a.as_object().cloned().unwrap_or_default(), + b: measure_b.as_object().cloned().unwrap_or_default(), + tolerance_mm: tolerance, + deviation: Deviations { a_to_b: deviation(&c.a_to_b), b_to_a: deviation(&c.b_to_a), max_mm: worst }, + identical, + verdict, + regions, + only_in_a: SideTotal { regions: ca, volume_mm3: va }, + only_in_b: SideTotal { regions: cb, volume_mm3: vb }, + unlisted_regions: c.unlisted, + warnings, + sampling: Sampling { spacing_mm: c.spacing, chord_mm: chord, triangles_a: mesh_a.triangles.len(), triangles_b: mesh_b.triangles.len() }, + colored_faces, + param_warnings: Vec::new(), + }; + serde_json::to_value(out).map_err(|e| bad(cmd, e.to_string())) } /// A face is coloured for a region when at least this share of it deviates there. diff --git a/crates/engine/src/cmd/compare_picture.rs b/crates/engine/src/cmd/compare_picture.rs new file mode 100644 index 000000000..6dce661b0 --- /dev/null +++ b/crates/engine/src/cmd/compare_picture.rs @@ -0,0 +1,692 @@ +//! Compare the model with a reference picture (#1486): agents model to a picture, and an +//! overlap score plus per-edge mm offsets tell the agent which edge to move and by how much. + +use std::collections::{HashMap, VecDeque}; +use std::io::Cursor; + +use serde_json::{Value, json}; +use solidcraft_doc::canvas::base64_encode; + +use super::CommandSpec; +use super::silhouette::{self, Silhouette}; +use crate::params::bad; +use crate::{Result, Session}; + +const CMD: &str = "inspect.compare_picture"; +/// A reference picture is read through the vfs with a byte cap, like `screenshot` output. +const MAX_REFERENCE_BYTES: usize = 32 << 20; +/// Decoded pixels are capped as well, so a small file cannot unfold into a huge raster. +const MAX_DECODED_PIXELS: u64 = 16 << 20; +/// The comparison grid each mask is fitted into at most — the picture's and the fitted +/// model's alike; keeps the slide search and the memory it needs bounded. +const MAX_GRID: usize = 1024; +/// Background grows from the border only through steps of at most this per channel, so a +/// backdrop's gradual shading belongs to it and the step at the part's outline stops it. +const BG_STEP: u16 = 12; +/// When the first pass finds no part, the flood retries at this stricter step: a white part +/// on a (245, 245, 245) studio backdrop is a step of 10, which BG_STEP lets through. +const BG_STEP_STRICT: u16 = 4; +/// A picture whose border is mostly transparent: a pixel below this alpha is see-through. +const ALPHA_BG: u8 = 128; +/// The global retry's backdrop: a pixel within this of the border's main colour is +/// background. A light JPEG (white on (245, 245, 245) at quality 75) blurs the step at the +/// part's outline below any local limit, so that pass compares to the backdrop's colour. +const BG_NEAR: u16 = 8; +/// Stations per side for the edge offsets. +const STATIONS: usize = 9; + +// For agents modelling to a picture; nothing to show a person, so no toolbar button. +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Compare Picture", run).noundo().icon("compare").params( + "reference: path to a PNG or JPEG the model should match; view?/camera?/bodies?/rows? as inspect.silhouette; \ + crop_px?: [x, y, w, h] in pixels, or crop_fraction?: [x, y, w, h] as fractions 0..1 of the picture \ + (to take one view off a board); part_fills_crop?: false — with true the crop box is the part itself \ + and no background search runs, for a crop that tightly frames the part; \ + fit?: \"width\" | \"height\" | \"both\" (default \"width\"): one uniform scale, taken from the named \ + dimension (\"both\" claims both and scales by width, reporting aspect_mismatch when the shapes differ); \ + overlay?: false leaves the overlay PNG out → overlap (0..1), edges: top|bottom|left|right in mm at nine stations \ + (positive where the model reaches past the picture, null where a station misses one of the two), the grid and its \ + mm_per_px, and overlay_png (red model, blue picture) as base64 PNG. The compare is outline only: \ + holes are not compared — both the picture's and the model's holes are filled", +)]; + +fn run(s: &mut Session, p: &Value) -> Result { + let reference = p + .get("reference") + .and_then(Value::as_str) + .filter(|v| !v.trim().is_empty()) + .ok_or_else(|| bad(CMD, "`reference` is required: a path to a PNG or JPEG"))?; + let fit = match p.get("fit") { + None => Fit::Width, + Some(Value::String(v)) => match v.as_str() { + "width" => Fit::Width, + "height" => Fit::Height, + "both" => Fit::Both, + other => return Err(bad(CMD, format!("`fit` must be \"width\", \"height\" or \"both\", not `{other}`"))), + }, + Some(_) => return Err(bad(CMD, "`fit` must be a string")), + }; + let overlay = p.get("overlay").map(|v| v.as_bool().unwrap_or(false)).unwrap_or(true); + let part_fills_crop = p.get("part_fills_crop").and_then(Value::as_bool).unwrap_or(false); + + // The model side: the same outline inspect.silhouette returns, as filled rows. + let camera = silhouette::camera(p)?; + let rows = silhouette::rows(p)?; + let wanted = silhouette::body_names(p)?; + let model = silhouette::outline(s, &camera, wanted.as_deref(), rows)?; + + // The picture side: decode, crop, and find the part. + let bytes = solidcraft_io::vfs::read(reference, MAX_REFERENCE_BYTES).map_err(|e| bad(CMD, format!("{reference}: {e}")))?; + let img = decode(&bytes)?; + let img = apply_crop(img, p.get("crop_px"), p.get("crop_fraction"))?; + let picture = if part_fills_crop { + part_from_box(&img).map_err(|reason| bad(CMD, format!("the crop cannot be the part: {reason}")))? + } else { + find_part(&img).map_err(|reason| bad(CMD, format!("no part found in the picture: {reason}")))? + }; + + // Fit the model outline to the picture's scale, then slide it to the best overlap. + let (mw, mh, mmpp_x, mmpp_y) = fit_model(&model, picture.width, picture.height, fit); + let mut model_scaled = resample(&model.mask, model.width, model.height, mw, mh); + // The same hole rule the picture side has: a through-hole in the model counts as its + // outline, not as a hole the picture has to match. + fill_holes(&mut model_scaled); + let best = best_overlap(&model_scaled, &picture); + let placed = Placed { dx: best.dx, dy: best.dy, mask: &model_scaled }; + let aspect_mismatch = (picture.width as f64 * mh as f64) / (picture.height as f64 * mw as f64); + + let mut out = json!({ + "overlap": round4(best.overlap), + "stations": STATIONS, + "edges": { + "top": edge_offsets(&placed, &picture, Edge::Top, mmpp_y), + "bottom": edge_offsets(&placed, &picture, Edge::Bottom, mmpp_y), + "left": edge_offsets(&placed, &picture, Edge::Left, mmpp_x), + "right": edge_offsets(&placed, &picture, Edge::Right, mmpp_x), + }, + "fit": match fit { Fit::Width => "width", Fit::Height => "height", Fit::Both => "both" }, + "aspect_mismatch": round4(aspect_mismatch), + "mm_per_px": {"x": round4(mmpp_x), "y": round4(mmpp_y)}, + "model": {"width": model.width, "height": model.height, "box_mm": [[round4(model.lo[0]), round4(model.lo[1])], [round4(model.hi[0]), round4(model.hi[1])]], "bodies": model.bodies}, + "picture": {"width": picture.width, "height": picture.height, "source": reference}, + }); + if overlay { + out["overlay_png"] = json!(base64_encode(&overlay_png(&picture, &placed))); + } + Ok(out) +} + +#[derive(Clone, Copy)] +enum Fit { + Width, + Height, + Both, +} + +#[derive(Clone, Copy)] +enum Edge { + Top, + Bottom, + Left, + Right, +} + +/// A picture mask, tightly framed to the found part. +struct Part { + width: usize, + height: usize, + mask: Vec>, +} + +/// A model mask placed relative to the picture: its top-left sits at (dx, dy) in the +/// picture's own pixel coordinates, which may be negative. +struct Placed<'a> { + dx: i64, + dy: i64, + mask: &'a [Vec], +} + +/// Decode PNG or JPEG to RGBA8, refusing anything else and anything that unfolds too large. +fn decode(bytes: &[u8]) -> Result { + let guess = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + if !matches!(guess.format(), Some(image::ImageFormat::Png) | Some(image::ImageFormat::Jpeg)) { + return Err(bad(CMD, "the reference must be a PNG or a JPEG")); + } + let (w, h) = guess.into_dimensions().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + if w as u64 * h as u64 > MAX_DECODED_PIXELS { + return Err(bad(CMD, format!("the picture is {w}x{h}: over the {} megapixel limit", MAX_DECODED_PIXELS >> 20))); + } + let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + let img = reader.decode().map_err(|e| bad(CMD, format!("cannot decode the picture: {e}")))?; + Ok(img.to_rgba8()) +} + +/// Apply `crop_px: [x, y, w, h]` (pixels) or `crop_fraction: [x, y, w, h]` (fractions 0..1 +/// of the picture). Explicit units: a crop of `[0, 0, 1, 1]` means one pixel, not the whole. +fn apply_crop(img: image::RgbaImage, crop_px: Option<&Value>, crop_fraction: Option<&Value>) -> Result { + match (crop_px, crop_fraction) { + (Some(_), Some(_)) => Err(bad(CMD, "give `crop_px` or `crop_fraction`, not both")), + (None, None) => Ok(img), + (Some(v), None) => { + let nums = crop_nums(v, "crop_px")?; + let (w, h) = img.dimensions(); + crop_to(img, nums[0].round() as usize, nums[1].round() as usize, nums[2].round() as usize, nums[3].round() as usize, w, h) + } + (None, Some(v)) => { + let nums = crop_nums(v, "crop_fraction")?; + if nums.iter().any(|f| *f > 1.0) { + return Err(bad(CMD, "`crop_fraction` values must be 0..1")); + } + let (w, h) = img.dimensions(); + crop_to( + img, + (nums[0] * w as f64).round() as usize, + (nums[1] * h as f64).round() as usize, + (nums[2] * w as f64).round() as usize, + (nums[3] * h as f64).round() as usize, + w, + h, + ) + } + } +} + +fn crop_nums(v: &Value, name: &str) -> Result> { + let nums: Vec = v + .as_array() + .filter(|a| a.len() == 4) + .and_then(|a| a.iter().map(|v| v.as_f64()).collect()) + .ok_or_else(|| bad(CMD, format!("`{name}` must be [x, y, w, h]")))?; + if nums.iter().any(|v| !v.is_finite() || *v < 0.0) { + return Err(bad(CMD, format!("`{name}` values must be non-negative"))); + } + Ok(nums) +} + +fn crop_to(img: image::RgbaImage, x: usize, y: usize, cw: usize, ch: usize, w: u32, h: u32) -> Result { + if x >= w as usize || y >= h as usize { + return Err(bad(CMD, "the crop starts outside the picture")); + } + let cw = cw.max(1).min(w as usize - x); + let ch = ch.max(1).min(h as usize - y); + Ok(image::imageops::crop_imm(&img, x as u32, y as u32, cw as u32, ch as u32).to_image()) +} + +/// Find the part. Alpha decides only when the backdrop really is transparent — most border +/// pixels see-through — so one stray translucent pixel cannot switch the read; then any ink +/// is part, so a part drawn at a faint alpha survives. Otherwise grow the background in from +/// the border through small colour steps only — seeded from the border pixels close to the +/// border's main colour, so a part touching the border is not eaten by its own edge — keep +/// what the background did not reach, and keep the largest 4-connected piece. On a retry the +/// step is stricter, so a white part on a (245, 245, 245) backdrop (a step of 10) still +/// separates; on a second retry the backdrop is taken globally — within BG_NEAR of the +/// border's main colour — because a light JPEG blurs the step at the part's outline below +/// any local limit. Says which happened when no part is found. +fn find_part(img: &image::RgbaImage) -> std::result::Result { + let (w, h) = (img.width() as usize, img.height() as usize); + if w < 2 || h < 2 { + return Err("the picture is smaller than 2 x 2 pixels".to_string()); + } + let px = |x: usize, y: usize| -> [u16; 3] { + let p = img.get_pixel(x as u32, y as u32).0; + [p[0] as u16, p[1] as u16, p[2] as u16] + }; + let step = |a: [u16; 3], b: [u16; 3]| (a[0].abs_diff(b[0])).max(a[1].abs_diff(b[1])).max(a[2].abs_diff(b[2])); + + // Alpha decides only when the border is mostly see-through: a single backdrop pixel at + // alpha 254 in an otherwise opaque picture must not turn the whole read into alpha. + let mut border = 0usize; + let mut see_through = 0usize; + for x in 0..w { + for y in [0, h - 1] { + border += 1; + if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG { + see_through += 1; + } + } + } + for y in 0..h { + for x in [0, w - 1] { + border += 1; + if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG { + see_through += 1; + } + } + } + let uses_alpha = see_through * 2 > border; + + let (part, too_small): (Vec, String) = if uses_alpha { + let mask: Vec = img.pixels().map(|p| p[3] > 0).collect(); + (mask, "the picture is transparent: no pixel holds any ink".to_string()) + } else { + let bg = flood_background(&px, w, h, BG_STEP, &step); + let mask: Vec = (0..w * h).map(|i| !bg[i]).collect(); + if largest_piece(&mask, w, h).len() >= 16 { + (mask, "the picture holds no piece big enough to be a part".to_string()) + } else { + let bg = flood_background(&px, w, h, BG_STEP_STRICT, &step); + let mask: Vec = (0..w * h).map(|i| !bg[i]).collect(); + if largest_piece(&mask, w, h).len() >= 16 { + (mask, "the picture holds no piece big enough to be a part".to_string()) + } else { + // The local step fails on a light JPEG: the codec blurs the 10-level step + // at the part's outline into steps of a few levels each, under any limit. + // Take the backdrop globally instead: near the border's main colour. + let main = border_main_colour(&px, w, h); + let mask: Vec = (0..w * h).map(|i| step(main, px(i % w, i / w)) > BG_NEAR).collect(); + (mask, "the background grew from the border over the whole picture, even with a stricter colour step: the part's colour is too close to the backdrop's".to_string()) + } + } + }; + + let best = largest_piece(&part, w, h); + if best.len() < 16 { + return Err(too_small); + } + // Tight frame, then downscale to the comparison grid at need. + let (x0, y0, x1, y1) = frame(&best, w); + let (pw, ph) = (x1 - x0 + 1, y1 - y0 + 1); + let mut mask = vec![vec![false; pw]; ph]; + for &i in &best { + let (x, y) = (i % w, i / w); + mask[y - y0][x - x0] = true; + } + let (dw, dh) = fit_grid(pw, ph); + let mut mask = if (dw, dh) == (pw, ph) { mask } else { resample(&mask, pw, ph, dw, dh) }; + fill_holes(&mut mask); + Ok(Part { width: dw, height: dh, mask }) +} + +/// The crop box is the part itself (`part_fills_crop`): no background search. This is how +/// one view cropped tight off a board says so — a part touching three sides leaves the +/// border's main colour the part's own, and the flood would keep the backdrop strip instead. +fn part_from_box(img: &image::RgbaImage) -> std::result::Result { + let (w, h) = (img.width() as usize, img.height() as usize); + if w < 2 || h < 2 { + return Err("the crop is smaller than 2 x 2 pixels".to_string()); + } + let (dw, dh) = fit_grid(w, h); + Ok(Part { width: dw, height: dh, mask: vec![vec![true; dw]; dh] }) +} + +/// The border's main colour: the border colour it has most of. A part crossing the border +/// is in the border too, but the backdrop is what most of the border shows. +fn border_main_colour(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize) -> [u16; 3] { + let mut counts: HashMap<[u16; 3], usize> = HashMap::new(); + for x in 0..w { + for y in [0, h - 1] { + *counts.entry(px(x, y)).or_default() += 1; + } + } + for y in 0..h { + for x in [0, w - 1] { + *counts.entry(px(x, y)).or_default() += 1; + } + } + counts.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or([0; 3]) +} + +/// The background mask: grown from every border pixel whose colour is close to the border's +/// main colour, crossing only steps of at most `limit` per channel. +fn flood_background(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize, limit: u16, step: &impl Fn([u16; 3], [u16; 3]) -> u16) -> Vec { + let main = border_main_colour(px, w, h); + + let mut bg = vec![false; w * h]; + let mut queue: VecDeque<(usize, usize)> = VecDeque::new(); + let mut seed = |x: usize, y: usize| { + if step(main, px(x, y)) <= limit && !bg[y * w + x] { + bg[y * w + x] = true; + queue.push_back((x, y)); + } + }; + for x in 0..w { + seed(x, 0); + seed(x, h - 1); + } + for y in 0..h { + seed(0, y); + seed(w - 1, y); + } + while let Some((x, y)) = queue.pop_front() { + let here = px(x, y); + for (nx, ny) in neighbours(x, y, w, h) { + if !bg[ny * w + nx] && step(here, px(nx, ny)) <= limit { + bg[ny * w + nx] = true; + queue.push_back((nx, ny)); + } + } + } + bg +} + +/// The largest 4-connected piece of a mask, as indices into `w`-wide rows. +fn largest_piece(mask: &[bool], w: usize, h: usize) -> Vec { + let mut best: Vec = Vec::new(); + let mut seen = vec![false; w * h]; + for start in 0..w * h { + if !mask[start] || seen[start] { + continue; + } + let mut piece: Vec = Vec::new(); + let mut queue: VecDeque = VecDeque::new(); + seen[start] = true; + queue.push_back(start); + while let Some(i) = queue.pop_front() { + piece.push(i); + let (x, y) = (i % w, i / w); + for (nx, ny) in neighbours(x, y, w, h) { + let j = ny * w + nx; + if mask[j] && !seen[j] { + seen[j] = true; + queue.push_back(j); + } + } + } + if piece.len() > best.len() { + best = piece; + } + } + best +} + +/// Fill the holes: pixels the outside never reaches become part — the rule the picture's +/// border flood gives the picture side for free, given to the model's mask as well. +fn fill_holes(mask: &mut [Vec]) { + let (h, w) = (mask.len(), mask.first().map_or(0, Vec::len)); + if w < 2 || h < 2 { + return; + } + let mut outside = vec![false; w * h]; + let mut queue: VecDeque = VecDeque::new(); + for x in 0..w { + for y in [0, h - 1] { + if !mask[y][x] && !outside[y * w + x] { + outside[y * w + x] = true; + queue.push_back(y * w + x); + } + } + } + for y in 0..h { + for x in [0, w - 1] { + if !mask[y][x] && !outside[y * w + x] { + outside[y * w + x] = true; + queue.push_back(y * w + x); + } + } + } + while let Some(i) = queue.pop_front() { + let (x, y) = (i % w, i / w); + for (nx, ny) in neighbours(x, y, w, h) { + let j = ny * w + nx; + if !mask[ny][nx] && !outside[j] { + outside[j] = true; + queue.push_back(j); + } + } + } + for y in 0..h { + for x in 0..w { + if !mask[y][x] && !outside[y * w + x] { + mask[y][x] = true; + } + } + } +} + +fn neighbours(x: usize, y: usize, w: usize, h: usize) -> impl Iterator { + [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)].into_iter().filter(move |(nx, ny)| *nx < w && *ny < h) +} + +fn frame(pixels: &[usize], w: usize) -> (usize, usize, usize, usize) { + let mut x0 = usize::MAX; + let mut y0 = usize::MAX; + let mut x1 = 0; + let mut y1 = 0; + for &i in pixels { + let (x, y) = (i % w, i / w); + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x); + y1 = y1.max(y); + } + (x0, y0, x1, y1) +} + +fn fit_grid(w: usize, h: usize) -> (usize, usize) { + let scale = (MAX_GRID as f64 / w.max(h) as f64).min(1.0); + (((w as f64 * scale).round() as usize).max(2), ((h as f64 * scale).round() as usize).max(2)) +} + +/// Nearest-neighbour resample of a mask to (w1, h1). +fn resample(mask: &[Vec], w0: usize, h0: usize, w1: usize, h1: usize) -> Vec> { + (0..h1) + .map(|y| { + let row = &mask[((y * h0) / h1.max(1)).min(h0 - 1)]; + (0..w1).map(|x| row[((x * w0) / w1.max(1)).min(w0 - 1)]).collect() + }) + .collect() +} + +/// The model outline's size in picture pixels and the mm per pixel that follows. One +/// uniform scale, taken from the dimension the two share — the axes are never stretched +/// apart, which would hide the very mismatch the tool is for. `both` claims both dimensions +/// and scales by width; the result's `aspect_mismatch` says how far the shapes are apart. +/// The fitted size takes the same MAX_GRID cap as the picture's: a narrow model fitted by +/// width against a wide picture would otherwise ask for hundreds of megabytes of mask. +fn fit_model(model: &Silhouette, pw: usize, ph: usize, fit: Fit) -> (usize, usize, f64, f64) { + let s = match fit { + Fit::Width | Fit::Both => pw as f64 / model.width as f64, + Fit::Height => ph as f64 / model.height as f64, + }; + let mw = ((model.width as f64 * s).round() as usize).max(2); + let mh = ((model.height as f64 * s).round() as usize).max(2); + let (mw, mh) = fit_grid(mw, mh); + (mw, mh, model.width as f64 * model.mm_per_px / mw as f64, model.height as f64 * model.mm_per_px / mh as f64) +} + +struct Best { + overlap: f64, + dx: i64, + dy: i64, +} + +/// Slide the model mask over the picture mask to the best intersection-over-union. The +/// coarse pass covers the whole range of placements where the two frames can share a +/// pixel — a tenth of the picture around the centre is not enough when the heights differ — +/// and the fine pass walks every offset around its winner. +fn best_overlap(model: &[Vec], picture: &Part) -> Best { + let pic = spans_of(&picture.mask); + let mdl = spans_of(model); + let model_area: i64 = mdl.iter().flatten().map(|[a, b]| (b - a) as i64).sum(); + let pic_area: i64 = pic.iter().flatten().map(|[a, b]| (b - a) as i64).sum(); + + let (mw, mh) = (model[0].len() as i64, model.len() as i64); + let (lo_x, hi_x) = (1 - mw, picture.width as i64); + let (lo_y, hi_y) = (1 - mh, picture.height as i64); + // About 64 coarse samples per axis, never finer than 4 px, never coarser than 32. + let step_x = ((hi_x - lo_x) / 64).clamp(4, 32); + let step_y = ((hi_y - lo_y) / 64).clamp(4, 32); + + // The frames' aligned corners: both masks are tightly framed, so the best placement of a + // matching picture is at or near here. + let (mut bx, mut by) = (0i64, 0i64); + for round in 0..2 { + // Coarse: the whole range at the step; fine: every offset within one coarse step + // of the coarse winner. + let (sx, sy, x0, x1, y0, y1) = if round == 0 { + (step_x, step_y, lo_x, hi_x, lo_y, hi_y) + } else { + (1, 1, (bx - step_x).max(lo_x), (bx + step_x).min(hi_x), (by - step_y).max(lo_y), (by + step_y).min(hi_y)) + }; + let (mut best_score, mut best_x, mut best_y) = (i64::MIN, bx, by); + let mut dy = y0; + while dy <= y1 { + let mut dx = x0; + while dx <= x1 { + let hits = intersection(&mdl, &pic, dx, dy); + let union = model_area + pic_area - hits; + let score = if union <= 0 { i64::MIN } else { hits * 1_000_000 / union }; + if score > best_score { + best_score = score; + best_x = dx; + best_y = dy; + } + dx += sx; + } + dy += sy; + } + bx = best_x; + by = best_y; + } + + let hits = intersection(&mdl, &pic, bx, by); + let union = model_area + pic_area - hits; + Best { overlap: if union <= 0 { 0.0 } else { hits as f64 / union as f64 }, dx: bx, dy: by } +} + +fn spans_of(mask: &[Vec]) -> Vec> { + mask.iter().map(|row| silhouette::spans(row)).collect() +} + +/// Pixels the model shares with the picture at model offset (dx, dy), from run-length rows. +fn intersection(mdl: &[Vec<[usize; 2]>], pic: &[Vec<[usize; 2]>], dx: i64, dy: i64) -> i64 { + let mut hits = 0i64; + for (r, spans) in mdl.iter().enumerate() { + if spans.is_empty() { + continue; + } + let Some(y) = (dy + r as i64).try_into().ok().and_then(|y: usize| pic.get(y)) else { continue }; + if y.is_empty() { + continue; + } + for &[a, b] in spans { + let (mut lo, hi) = ((a as i64 + dx).max(0), b as i64 + dx); + if hi <= lo { + continue; + } + for &[pa, pb] in y { + let (s, e) = (lo.max(pa as i64), hi.min(pb as i64)); + if e > s { + hits += e - s; + } + lo = lo.max(pb as i64); + if lo >= hi || pb as i64 >= hi { + break; + } + } + } + } + hits +} + +/// The model's edge against the picture's, in mm, at nine stations along one side; positive +/// where the model reaches past the picture, null where a station misses one of the two. +fn edge_offsets(model: &Placed, picture: &Part, side: Edge, mmpp: f64) -> Vec { + (1..=STATIONS) + .map(|i| { + let station = match side { + Edge::Top | Edge::Bottom => (picture.width as u64 * i as u64 / (STATIONS as u64 + 1)) as usize, + Edge::Left | Edge::Right => (picture.height as u64 * i as u64 / (STATIONS as u64 + 1)) as usize, + }; + let offset = match side { + Edge::Top | Edge::Bottom => { + let pic = column_edge(&picture.mask, station, matches!(side, Edge::Top)); + let mdl = (station as i64 - model.dx) + .try_into() + .ok() + .and_then(|mx: usize| column_edge(model.mask, mx, matches!(side, Edge::Top))) + .map(|e| e as i64 + model.dy); + match (mdl, pic) { + (Some(m), Some(p)) => Some(match side { + Edge::Top => (p as f64 - m as f64) * mmpp, + _ => (m as f64 - p as f64) * mmpp, + }), + _ => None, + } + } + Edge::Left | Edge::Right => { + let pic = row_edge(&picture.mask, station, matches!(side, Edge::Left)); + let mdl = (station as i64 - model.dy) + .try_into() + .ok() + .and_then(|my: usize| row_edge(model.mask, my, matches!(side, Edge::Left))) + .map(|e| e as i64 + model.dx); + match (mdl, pic) { + (Some(m), Some(p)) => Some(match side { + Edge::Left => (p as f64 - m as f64) * mmpp, + _ => (m as f64 - p as f64) * mmpp, + }), + _ => None, + } + } + }; + offset.map(|mm| json!(round3(mm))).unwrap_or(Value::Null) + }) + .collect() +} + +/// The first (or last, when `first` is false) row holding column `x`; None if none does. +fn column_edge(mask: &[Vec], x: usize, first: bool) -> Option { + let mut found = None; + for (y, row) in mask.iter().enumerate() { + if row.get(x).copied().unwrap_or(false) { + if first { + return Some(y); + } + found = Some(y); + } + } + found +} + +/// The first (or last) column set in row `y`; None if the row is empty or missing. +fn row_edge(mask: &[Vec], y: usize, first: bool) -> Option { + let row = mask.get(y)?; + if first { row.iter().position(|&on| on) } else { row.iter().rposition(|&on| on) } +} + +/// The overlay PNG: the picture in blue, the model in red, on a canvas that holds both. +fn overlay_png(picture: &Part, model: &Placed) -> Vec { + // A margin so a model that hangs off the picture still fits the canvas. + let m = 8i64; + let (x0, y0) = (0.min(model.dx) - m, 0.min(model.dy) - m); + let (x1, y1) = ( + (picture.width as i64).max(model.dx + model.mask.first().map_or(0, |r| r.len()) as i64) + m, + (picture.height as i64).max(model.dy + model.mask.len() as i64) + m, + ); + let (w, h) = ((x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32); + let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([250, 250, 250, 255])); + for (y, row) in picture.mask.iter().enumerate() { + for (x, &on) in row.iter().enumerate() { + if on { + img.put_pixel((x as i64 - x0) as u32, (y as i64 - y0) as u32, image::Rgba([70, 110, 230, 255])); + } + } + } + for (r, row) in model.mask.iter().enumerate() { + for (c, &on) in row.iter().enumerate() { + if !on { + continue; + } + let (x, y) = (model.dx + c as i64 - x0, model.dy + r as i64 - y0); + if (0..w as i64).contains(&x) && (0..h as i64).contains(&y) { + img.put_pixel(x as u32, y as u32, image::Rgba([235, 60, 60, 255])); + } + } + } + let mut out = Cursor::new(Vec::new()); + // Encoding a mask-sized PNG cannot realistically fail; if it ever does, no overlay. + let enc = image::codecs::png::PngEncoder::new(&mut out); + use image::ImageEncoder as _; + if enc.write_image(img.as_raw(), img.width(), img.height(), image::ExtendedColorType::Rgba8).is_err() { + return Vec::new(); + } + out.into_inner() +} + +fn round4(v: f64) -> f64 { + if v.abs() < 1e12 { (v * 10_000.0).round() / 10_000.0 } else { v } +} + +fn round3(v: f64) -> f64 { + if v.abs() < 1e12 { (v * 1_000.0).round() / 1_000.0 } else { v } +} diff --git a/crates/engine/src/cmd/compare_picture_tests.rs b/crates/engine/src/cmd/compare_picture_tests.rs new file mode 100644 index 000000000..fe8f44390 --- /dev/null +++ b/crates/engine/src/cmd/compare_picture_tests.rs @@ -0,0 +1,490 @@ +//! Tests for `inspect.compare_picture` (#1486): synthetic reference pictures drawn in code, +//! written to the temp dir and read back through the vfs like any other reference. + +use std::io::Cursor; + +use serde_json::{Value, json}; + +use super::super::Session; +use image::ImageEncoder as _; + +fn run(s: &mut Session, cmd: &str, params: Value) -> Value { + s.execute(cmd, ¶ms).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn box_body(s: &mut Session, name: &str, x1: f64, y1: f64, z: f64) { + let sketch = format!("{name}Sketch"); + run(s, "sketch.create", json!({"plane": "XY", "name": sketch})); + run(s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [x1, y1]})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": sketch, "distance": z, "operation": "new_body", "body_name": name})); +} + +/// A PNG whose pixels come from `paint`. +fn png(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + png_rgba(w, h, |x, y| { + let [r, g, b] = paint(x, y); + [r, g, b, 255] + }) +} + +/// A PNG with alpha, whose pixels come from `paint`. +fn png_rgba(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 4]) -> Vec { + let mut img = image::RgbaImage::new(w as u32, h as u32); + for y in 0..h { + for x in 0..w { + img.put_pixel(x as u32, y as u32, image::Rgba(paint(x, y))); + } + } + let mut out = Cursor::new(Vec::new()); + image::codecs::png::PngEncoder::new(&mut out).write_image(img.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgba8).unwrap(); + out.into_inner() +} + +fn jpeg(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + jpeg_q(w, h, 90, paint) +} + +fn jpeg_q(w: usize, h: usize, q: u8, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + let mut img = image::RgbaImage::new(w as u32, h as u32); + for y in 0..h { + for x in 0..w { + let [r, g, b] = paint(x, y); + img.put_pixel(x as u32, y as u32, image::Rgba([r, g, b, 255])); + } + } + let rgb = image::DynamicImage::ImageRgba8(img).to_rgb8(); + let mut out = Cursor::new(Vec::new()); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, q) + .write_image(rgb.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgb8) + .unwrap(); + out.into_inner() +} + +/// Write a reference into the temp dir and return its path. +fn reference(name: &str, bytes: &[u8]) -> String { + let path = std::env::temp_dir().join(format!("solidcraft-compare-picture-{}-{name}", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +/// A white rectangle on a grey backdrop: `x0..x1, y0..y1` in pixels. +fn rect_picture(w: usize, h: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Vec { + png(w, h, |x, y| if (x0..x1).contains(&x) && (y0..y1).contains(&y) { [255, 255, 255] } else { [200, 200, 200] }) +} + +fn edges(v: &Value) -> Vec>> { + ["top", "bottom", "left", "right"] + .iter() + .map(|side| v["edges"][side].as_array().unwrap().iter().map(|e| e.as_f64()).collect::>>()) + .collect() +} + +fn near(v: Option, want: f64, tol: f64) -> bool { + v.is_some_and(|e| (e - want).abs() <= tol) +} + +#[test] +fn a_matching_picture_scores_high_with_flat_edges() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall + let path = reference("match.png", &rect_picture(200, 280, 20, 20, 180, 260)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + for side in edges(&out) { + for e in side { + assert!(near(e, 0.0, 0.6), "edge {e:?}"); + } + } + assert!(!out["overlay_png"].as_str().unwrap().is_empty()); +} + +#[test] +fn a_step_in_the_bottom_edge_shows_up_in_mm() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // The aligned picture: a plain part 160 x 240 px — the model's own shape at 8 px per mm. + let aligned_path = reference("aligned.png", &rect_picture(200, 280, 20, 20, 180, 260)); + let aligned = run(&mut s, "inspect.compare_picture", json!({"reference": aligned_path, "view": "front"})); + // The stepped picture: over its right half the part's bottom edge sits 35 px higher. + // The width fit gives 8 px per mm, so 35 px is 4.375 mm of the model reaching past + // the picture. + let stepped_path = reference( + "stepped.png", + &png(200, 280, |x, y| { + let bottom = if x >= 100 { 225 } else { 260 }; + if (20..180).contains(&x) && (20..bottom).contains(&y) { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let stepped = run(&mut s, "inspect.compare_picture", json!({"reference": stepped_path, "view": "front"})); + let flat = edges(&aligned)[1].clone(); + let step = edges(&stepped)[1].clone(); + for e in flat.iter() { + assert!(near(*e, 0.0, 0.6), "flat bottom {e:?}"); + } + // Stations sit at local x = 16..144 px; the notch starts at local x = 80 (global 100), + // so stations 5..9 are over it. + for e in step.iter().take(4) { + assert!(near(*e, 0.0, 0.6), "step bottom left {e:?}"); + } + for e in step.iter().skip(4) { + assert!(near(*e, 4.375, 0.6), "step bottom right {e:?}"); + } + assert!(stepped["overlap"].as_f64().unwrap() < aligned["overlap"].as_f64().unwrap()); +} + +/// #1486's example, pinned: `examples/bracket.json` as it is (upright 30 mm) against the +/// same bracket at 40 mm, both from the front, scaled by the 40 mm arm they share. +/// The issue's prototype numbers: overlap 0.865, bottom −9.9 mm at the upright (6 % across), +/// 0.0 mm everywhere else. +#[test] +fn the_issue_bracket_pins_overlap_and_the_short_upright() { + let mut s = Session::default(); + // The bracket profile of examples/bracket.json: a 40 x 6 arm with a 6-wide upright to + // 30 mm, on XZ so the front view shows the upright hanging below the arm. + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Profile"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 6], [6, 6], [6, 30], [0, 30]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 20.0, "direction": "negative", "body_name": "Bracket"})); + // The same bracket with the upright at 40 mm, at 20 px per mm: an 800 x 800 part, the + // 800 x 120 arm on top and the 120-wide upright down to 800, on a grey margin. + let path = reference( + "bracket.png", + &png(840, 840, |x, y| { + let part = ((20..820).contains(&x) && (20..140).contains(&y)) || ((20..140).contains(&x) && (20..820).contains(&y)); + if part { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "rows": 480, "overlay": false})); + let overlap = out["overlap"].as_f64().unwrap(); + assert!((overlap - 0.865).abs() <= 0.01, "overlap {overlap}"); + let e = edges(&out); + // The upright is the first station (x = 80 of 800): the model is 10 mm short there. + assert!(near(e[1][0], -10.0, 0.2), "bottom at the upright {:?}", e[1][0]); + for side in 1..9 { + assert!(near(e[1][side], 0.0, 0.1), "bottom elsewhere {:?}", e[1]); + } + for i in 0..9 { + assert!(near(e[0][i], 0.0, 0.1), "top {:?}", e[0]); + // Below the model's 30 mm upright the model has no row to answer with: those + // side stations are null, as documented. + for side in [e[2].clone(), e[3].clone()] { + match side[i] { + None => {} + Some(v) => assert!(v.abs() <= 0.1, "side {side:?}"), + } + } + } +} + +#[test] +fn a_gradient_backdrop_still_separates_from_the_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // A backdrop that shifts one step per row: the border flood follows it; the step at the + // part's outline (to white) stops it. + let path = reference( + "gradient.png", + &png(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [200 + (y / 30) as u8, 200, 200] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} + +#[test] +fn a_jpeg_reference_works_too() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = + reference("match.jpg", &jpeg(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [40, 40, 40] })); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} + +#[test] +fn crop_takes_one_part_off_the_board() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // Two parts side by side; the crop keeps the left one, a plain rectangle that matches + // the model. The right part is bigger overall but L-shaped, so without the crop the + // largest piece wins and the score drops. + let path = reference( + "two.png", + &png(400, 300, |x, y| { + let left = (20..180).contains(&x) && (20..260).contains(&y); + let right = (210..390).contains(&x) && (5..295).contains(&y) && !((300..390).contains(&x) && (100..200).contains(&y)); + if left || right { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_fraction": [0.0, 0.0, 0.5, 1.0]})); + // The picture size is the found part's tight frame: the left rectangle is 160 x 240 px. + assert_eq!(out["picture"]["width"], 160); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + let whole = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(whole["overlap"].as_f64().unwrap() < out["overlap"].as_f64().unwrap()); +} + +#[test] +fn crop_px_has_explicit_units() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = reference("px.png", &rect_picture(200, 280, 20, 20, 180, 260)); + // Pixels mean pixels: [10, 10, 180, 260] keeps the part with a margin, and a crop of + // one pixel is one pixel, not the whole picture. + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_px": [10, 10, 180, 260]})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + let dot = reference("dot.png", &rect_picture(200, 280, 100, 100, 101, 101)); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": dot, "crop_px": [0, 0, 1, 1]})).unwrap_err().to_string().contains("no part found") + ); + // Giving both spellings is refused, and so is a fraction above 1. + assert!( + s.execute("inspect.compare_picture", &json!({"reference": path, "crop_px": [0, 0, 10, 10], "crop_fraction": [0.0, 0.0, 0.1, 0.1]})) + .unwrap_err() + .to_string() + .contains("not both") + ); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": path, "crop_fraction": [0.0, 0.0, 1.5, 1.0]})) + .unwrap_err() + .to_string() + .contains("0..1") + ); +} + +#[test] +fn fit_both_never_stretches_the_axes_apart() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall + // A 20 x 20 mm square picture of a 20 x 30 mm model: `both` used to stretch the model + // to the square and report a perfect 1.000 with every edge at 0.0 mm. One uniform + // scale (from the width they share) leaves the 10 mm of overhang visible instead. + let path = reference("square.png", &rect_picture(220, 220, 10, 10, 210, 210)); + let both = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "fit": "both", "overlay": false})); + assert!((both["overlap"].as_f64().unwrap() - 200.0 / 300.0).abs() < 0.02, "overlap {}", both["overlap"]); + assert!((both["aspect_mismatch"].as_f64().unwrap() - 1.5).abs() < 0.01, "aspect_mismatch {}", both["aspect_mismatch"]); + // And `width` is the default: leaving `fit` out answers the same as naming it. + let plain = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert_eq!(plain["overlap"], both["overlap"]); + assert_eq!(plain["edges"], both["edges"]); +} + +#[test] +fn fit_width_keeps_the_models_aspect() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // The picture part is 160 x 160 px: fit=width scales the model uniformly to 160 x 240, + // so it hangs 80 px (10 mm) over the picture's height in total, wherever the slide puts + // it. The overlap of a contained model is 160/240 wherever it sits. + let path = reference("short.png", &rect_picture(200, 220, 20, 20, 180, 180)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "fit": "width"})); + assert!((out["overlap"].as_f64().unwrap() - 160.0 / 240.0).abs() < 0.05, "overlap {}", out["overlap"]); + let bottom: Vec> = out["edges"]["bottom"].as_array().unwrap().iter().map(|e| e.as_f64()).collect(); + let top: Vec> = out["edges"]["top"].as_array().unwrap().iter().map(|e| e.as_f64()).collect(); + for i in 0..9 { + // The overhang splits between top and bottom but always totals the extra 10 mm. + assert!(bottom[i].unwrap() >= 0.0 && top[i].unwrap() >= 0.0, "bottom {:?} top {:?}", bottom[i], top[i]); + assert!((bottom[i].unwrap() + top[i].unwrap() - 10.0).abs() < 0.6, "bottom {:?} top {:?}", bottom[i], top[i]); + } +} + +#[test] +fn a_narrow_model_fits_the_grid_not_the_memory() { + let mut s = Session::default(); + // A 2 mm x 1000 mm sliver seen from the front: fitted by width against a 1024-wide + // picture it used to become 1024 x 524 288 booleans. The fitted model now takes the + // same MAX_GRID cap as the picture, so the comparison just runs. + box_body(&mut s, "Sliver", 2.0, 1.0, 1000.0); + let path = reference("sliver.png", &rect_picture(1030, 1010, 3, 5, 1027, 1005)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The shapes are nothing alike (the sliver is 1:500, the picture 1024:1000), and the + // capped model grid keeps the overlap small — what matters is that it ran at all. + assert!(out["overlap"].as_f64().unwrap() < 0.1, "overlap {}", out["overlap"]); +} + +#[test] +fn ordinary_pictures_keep_their_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // A part touching the picture's border: only border pixels close to the border's main + // colour seed the background, so the part's own border pixels do not flood it. + let border = reference("border.png", &rect_picture(200, 280, 0, 20, 160, 260)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": border, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "border overlap {}", out["overlap"]); + // A white part on a (245, 245, 245) studio backdrop: the step of 10 is below BG_STEP, + // but the stricter retry separates it. + let studio = reference( + "studio.png", + &png(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": studio, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "studio overlap {}", out["overlap"]); + // A part on a transparent background: alpha below 128 is background. + let alpha = reference( + "alpha.png", + &png_rgba(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [90, 90, 90, 255] } else { [0, 0, 0, 0] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": alpha, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "alpha overlap {}", out["overlap"]); +} + +#[test] +fn a_through_hole_counts_the_same_on_both_sides() { + let mut s = Session::default(); + // A 200 x 200 mm plate with a 100 x 100 mm through-hole, against a picture of itself + // at 1 px per mm, seen from the top (the hole goes through the plate's faces). The + // picture's hole is filled by the border flood; the model's hole now gets the same + // rule, so the plate scores ~1.0 instead of 0.75. + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Plate"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [200.0, 200.0]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Plate", "distance": 10.0, "operation": "new_body", "body_name": "Plate"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Hole"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [50.0, 50.0], "p1": [150.0, 150.0]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Hole", "distance": 20.0, "operation": "cut"})); + let path = reference( + "plate.png", + &png(220, 220, |x, y| { + let plate = (10..210).contains(&x) && (10..210).contains(&y); + let hole = (60..160).contains(&x) && (60..160).contains(&y); + if plate && !hole { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "top", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]); + for side in edges(&out) { + for e in side { + assert!(near(e, 0.0, 0.6), "edge {e:?}"); + } + } +} + +#[test] +fn hostile_and_empty_references_fail_cleanly() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + assert!(s.execute("inspect.compare_picture", &json!({})).is_err()); + // Not an image at all. + let text = reference("not.png", b"just text, not a picture"); + assert!(s.execute("inspect.compare_picture", &json!({"reference": text})).unwrap_err().to_string().contains("PNG or a JPEG")); + // A uniform picture: the background eats everything, and says so. + let flat = reference("flat.png", &png(64, 64, |_, _| [200, 200, 200])); + assert!(s.execute("inspect.compare_picture", &json!({"reference": flat})).unwrap_err().to_string().contains("no part found")); + // A fully transparent picture: alpha says there is nothing there. + let clear = reference("clear.png", &png_rgba(64, 64, |_, _| [0, 0, 0, 0])); + assert!(s.execute("inspect.compare_picture", &json!({"reference": clear})).unwrap_err().to_string().contains("transparent")); + // A missing file. + assert!(s.execute("inspect.compare_picture", &json!({"reference": "no-such-file.png"})).is_err()); + // A bad fit name. + let path = reference("match2.png", &rect_picture(200, 280, 20, 20, 180, 260)); + assert!(s.execute("inspect.compare_picture", &json!({"reference": path, "fit": "diagonal"})).is_err()); + // overlay: false leaves the PNG out. + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert!(out.get("overlay_png").is_none()); +} + +/// Reviewer re-test case: a 60 x 60 opaque PNG with a white 40 x 40 square and a single +/// backdrop pixel at alpha 254 used to be read as all part — 1.000 against the 40 x 40 +/// square at 0.067 mm/px instead of 0.1. Alpha now decides only when the border is mostly +/// see-through, and a part drawn at alpha 100 on a transparent backdrop is still the part. +#[test] +fn one_translucent_pixel_does_not_switch_to_alpha() { + let mut s = Session::default(); + box_body(&mut s, "Square", 4.0, 1.0, 4.0); // front view: 4 x 4 mm + let path = reference( + "speck.png", + &png_rgba(60, 60, |x, y| { + let alpha = if x == 5 && y == 55 { 254 } else { 255 }; + let c = if (10..50).contains(&x) && (10..50).contains(&y) { 255u8 } else { 128 }; + [c, c, c, alpha] + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The part is the 40 x 40 square: 4 mm over 40 px is 0.1 mm/px, not 4/60 = 0.067. + let mmpp = out["mm_per_px"]["x"].as_f64().unwrap(); + assert!((mmpp - 0.1).abs() < 0.01, "mm_per_px {mmpp}"); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); + // A part drawn at alpha 100 on a transparent backdrop is the part, not the background. + let faint = reference( + "faint.png", + &png_rgba(60, 60, |x, y| if (10..50).contains(&x) && (10..50).contains(&y) { [255, 255, 255, 100] } else { [0, 0, 0, 0] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": faint, "view": "front", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "faint overlap {}", out["overlap"]); + let mmpp = out["mm_per_px"]["x"].as_f64().unwrap(); + assert!((mmpp - 0.1).abs() < 0.01, "faint mm_per_px {mmpp}"); +} + +/// Reviewer re-test case: one view cropped off a board — the part touches three sides and +/// takes 270 of the 400 border samples, so the border's main colour is the part's own and +/// the flood eats it: the 15 px backdrop strip becomes "the part" and an exact model scores +/// 0.18. `part_fills_crop: true` says the crop box is the part: no flood, exact model ~1.0. +#[test] +fn a_tight_crop_can_declare_the_box_is_the_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 17.0, 10.0, 20.0); // front view: 17 wide, 20 tall + // The tight crop: the white part fills x 0..85 of a 100 x 100 box, touching three + // sides — 270 of the border samples — with a 15 px backdrop strip down the right. + let path = reference("tight.png", &png(100, 100, |x, _| if x < 85 { [255, 255, 255] } else { [200, 200, 200] })); + let flood = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "overlay": false})); + assert!(flood["overlap"].as_f64().unwrap() < 0.5, "the flood keeps the strip: overlap {}", flood["overlap"]); + let out = run( + &mut s, + "inspect.compare_picture", + json!({"reference": path, "view": "front", "crop_px": [0, 0, 85, 100], "part_fills_crop": true, "overlay": false}), + ); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + // 17 mm over the 85 px the part fills: 0.2 mm/px. + assert!((out["mm_per_px"]["x"].as_f64().unwrap() - 0.2).abs() < 0.01, "mm_per_px {}", out["mm_per_px"]); + // A crop of a 2 x 2 box is the part; a 1 px box is refused. + let dot = reference("tight-dot.png", &png(4, 4, |_, _| [255, 255, 255])); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": dot, "part_fills_crop": true, "crop_px": [0, 0, 1, 1]})) + .unwrap_err() + .to_string() + .contains("2 x 2") + ); +} + +/// Reviewer re-test case: holes are filled on both sides, so a model missing a 100 x 100 +/// through-hole scores ~1.000 against a picture that shows the hole. That is the contract — +/// outline only — and the command description must say so, so an agent does not read 1.000 +/// as "matches". +#[test] +fn the_compare_is_outline_only_holes_are_not_compared() { + assert!( + crate::cmd::compare_picture::COMMANDS[0].params.contains("holes are not compared"), + "the command description must say the compare is outline only" + ); + let mut s = Session::default(); + // A solid 200 x 200 mm plate against a picture of a plate with a 100 x 100 through-hole. + box_body(&mut s, "Plate", 200.0, 10.0, 200.0); + let path = reference( + "hole-only.png", + &png(220, 220, |x, y| { + let plate = (10..210).contains(&x) && (10..210).contains(&y); + let hole = (60..160).contains(&x) && (60..160).contains(&y); + if plate && !hole { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The outlines match: the hole is not compared, as the description says. + assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]); +} + +/// Reviewer re-test case: a white part on (245, 245, 245) saved as JPEG at quality 75 gave +/// "no part" even on the stricter retry — the codec blurs the 10-level step at the part's +/// outline into steps of a few levels each, under any local limit. The third pass takes the +/// backdrop globally: near the border's main colour. +#[test] +fn a_light_jpeg_keeps_its_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = reference( + "light.jpg", + &jpeg_q(200, 300, 75, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} diff --git a/crates/engine/src/cmd/compare_tests.rs b/crates/engine/src/cmd/compare_tests.rs index f0066db8e..a3fbea9d3 100644 --- a/crates/engine/src/cmd/compare_tests.rs +++ b/crates/engine/src/cmd/compare_tests.rs @@ -58,19 +58,21 @@ fn a_pocket_is_material_only_the_plain_box_has() { let g = &rs[0]; assert_eq!(g["side"], "only_in_a"); assert_eq!(g["material_of"], "A"); - assert!(close(f(&g["volume_mm3"]), 40.0, 0.01), "{g}"); + // Measured exactly, on the cut a − b: the pocket's own volume, box and centre. + assert_eq!(g["measured_by"], "boolean", "{g}"); + assert!(close(f(&g["volume_mm3"]), 40.0, 1e-9), "{g}"); assert!((f(&g["max_deviation_mm"]) - 0.5).abs() < 1e-6, "{g}"); let (lo, hi) = (&g["bbox"]["min"], &g["bbox"]["max"]); for (k, (want_lo, want_hi)) in [(10.0, 20.0), (10.0, 18.0), (9.5, 10.0)].into_iter().enumerate() { - assert!((f(&lo[k]) - want_lo).abs() < 0.05 && (f(&hi[k]) - want_hi).abs() < 0.05, "{g}"); + assert!((f(&lo[k]) - want_lo).abs() < 1e-6 && (f(&hi[k]) - want_hi).abs() < 1e-6, "{g}"); } let c = &g["center"]; - assert!((f(&c[0]) - 15.0).abs() < 0.02 && (f(&c[1]) - 14.0).abs() < 0.02 && (f(&c[2]) - 9.75).abs() < 1e-6, "{g}"); + assert!((f(&c[0]) - 15.0).abs() < 1e-9 && (f(&c[1]) - 14.0).abs() < 1e-9 && (f(&c[2]) - 9.75).abs() < 1e-9, "{g}"); // The pocket's floor and walls, and a's top. assert_eq!(g["faces_b"].as_array().map(Vec::len), Some(5), "{g}"); assert_eq!(g["faces_a"].as_array().map(Vec::len), Some(1), "{g}"); assert!(close(f(&r["difference"]["volume_mm3"]), -40.0, 1e-6), "{}", r["difference"]); - assert!(close(f(&r["only_in_a"]["volume_mm3"]), 40.0, 0.01)); + assert!(close(f(&r["only_in_a"]["volume_mm3"]), 40.0, 1e-9)); assert_eq!(r["only_in_b"]["regions"], 0); // The other way round, the same material is only in b. let r = run(&mut s, "inspect.compare", json!({"a": "A (2)", "b": "A"})); @@ -88,7 +90,7 @@ fn a_boss_is_material_only_the_box_with_it_has() { let rs = regions(&r); assert_eq!(rs.len(), 1, "{r}"); assert_eq!(rs[0]["side"], "only_in_b"); - assert!(close(f(&rs[0]["volume_mm3"]), 60.0, 0.01), "{}", rs[0]); + assert!(close(f(&rs[0]["volume_mm3"]), 60.0, 1e-9), "{}", rs[0]); assert!((f(&rs[0]["max_deviation_mm"]) - 2.0).abs() < 1e-6); assert!(close(f(&r["difference"]["volume_mm3"]), 60.0, 1e-6)); // Coloured green: the boss's top and four sides, all of them beyond the tolerance; not a's top, @@ -104,6 +106,27 @@ fn a_boss_is_material_only_the_box_with_it_has() { assert_eq!(s.doc.appearances.faces.iter().filter(|x| x.look.color == [0, 0, 255]).count(), 5); } +#[test] +fn a_taller_box_has_a_slab_only_it_has() { + // b is 5 mm taller on the same footprint: b − a is the slab z 20..25, 40 x 30 x 5 = 6000 mm³ + // at (20, 15, 22.5), sharing four side faces and the bottom with a. Exact, from the cut. + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 25, "body_name": "B"})); + let r = run(&mut s, "inspect.compare", json!({"a": "A", "b": "B"})); + let rs = regions(&r); + assert_eq!(rs.len(), 1, "{r}"); + let g = &rs[0]; + assert_eq!((g["side"].as_str(), g["measured_by"].as_str()), (Some("only_in_b"), Some("boolean")), "{g}"); + assert!(close(f(&g["volume_mm3"]), 6000.0, 1e-9), "{g}"); + let c = &g["center"]; + assert!((f(&c[0]) - 20.0).abs() < 1e-9 && (f(&c[1]) - 15.0).abs() < 1e-9 && (f(&c[2]) - 22.5).abs() < 1e-9, "{g}"); + assert!((f(&g["bbox"]["min"][2]) - 20.0).abs() < 1e-6 && (f(&g["bbox"]["max"][2]) - 25.0).abs() < 1e-6, "{g}"); + assert!(close(f(&r["only_in_b"]["volume_mm3"]), 6000.0, 1e-9), "{r}"); + assert_eq!(f(&r["only_in_a"]["volume_mm3"]), 0.0); + assert_eq!(r["warnings"], json!([]), "{r}"); +} + /// A 100 x 60 sheet-metal plate with a 20 mm flange along y = 0 and a 5 mm hole at (x, 40). fn bracket(s: &mut Session, name: &str, x: f64) { run(s, "sketch.create", json!({"plane": "XY", "name": format!("{name} base")})); @@ -131,9 +154,10 @@ fn a_hole_moved_2_mm_leaves_two_crescents() { let crescent = (std::f64::consts::PI * rr * rr - 2.0 * rr * rr * (d / (2.0 * rr)).acos() + d / 2.0 * (4.0 * rr * rr - d * d).sqrt()) * t; assert!((crescent - 24.316_34).abs() < 1e-4); for g in &rs { - assert!(close(f(&g["volume_mm3"]), crescent, 0.02), "{g}"); + assert_eq!(g["measured_by"], "boolean", "{g}"); + assert!(close(f(&g["volume_mm3"]), crescent, 1e-6), "{g}"); let c = &g["center"]; - assert!((f(&c[1]) - 40.0).abs() < 0.05 && (f(&c[2]) - 1.25).abs() < 0.01, "{g}"); + assert!((f(&c[1]) - 40.0).abs() < 1e-6 && (f(&c[2]) - 1.25).abs() < 1e-6, "{g}"); // Material only Before has is where After's hole is (beyond x = 51), and the reverse. match g["side"].as_str() { Some("only_in_a") => assert!(f(&c[0]) > 51.5, "{g}"), @@ -179,6 +203,30 @@ fn a_part_and_its_step_round_trips_are_identical() { } } +/// With a body that encloses no volume (an open tube of four walls) the exact cut can't be made: +/// every region says so and gives no volume or centre, never an estimate, while the deviation, +/// which needs no cut, is still measured. +#[test] +fn a_region_the_cut_cannot_measure_has_no_volume_and_says_why() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Block"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Square"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "surface.extrude", json!({"sketch": "Square", "distance": "10 mm", "name": "Tube", "body_name": "Tube"})); + let r = run(&mut s, "inspect.compare", json!({"a": "Block", "b": "Tube"})); + assert!(f(&r["deviation"]["max_mm"]).is_finite(), "{r}"); + let rs = regions(&r); + assert!(!rs.is_empty(), "the tube lacks the block's top and bottom: {r}"); + for g in &rs { + assert_eq!(g["measured_by"], "not measured", "{g}"); + assert!(g["volume_mm3"].is_null() && g["center"].is_null(), "{g}"); + assert!(g["not_measured"].as_str().is_some_and(|w| w.contains("encloses no volume")), "{g}"); + } + assert!(r["only_in_a"]["volume_mm3"].is_null(), "{r}"); + assert!(r["verdict"].as_str().is_some_and(|v| v.contains("volume not measured")), "{r}"); +} + #[test] fn bad_parameters_are_refused() { let mut s = two_boxes(); @@ -207,6 +255,6 @@ fn bad_parameters_are_refused() { assert_eq!(r["a"]["name"], "A"); assert_eq!(r["b"]["name"], "C"); assert_eq!(r["only_in_a"]["regions"], 1, "{r}"); - assert!(close(f(&r["only_in_a"]["volume_mm3"]), 12_000.0 - 125.0, 0.01), "{r}"); + assert!(close(f(&r["only_in_a"]["volume_mm3"]), 12_000.0 - 125.0, 1e-9), "{r}"); assert!(r["verdict"].as_str().unwrap_or_default().starts_with("1 region differs by more than 0.01 mm"), "{}", r["verdict"]); } diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index f4cbc4581..b7ef7b25a 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -3,19 +3,20 @@ //! belong to their feature's component unless moved; occurrences place components (instances //! share contents, "paste new" copies them) and can be grounded and moved. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::bom; use solidcraft_doc::metadata::{BOM_QUANTITY, VIRTUAL}; use solidcraft_doc::{Document, Feature, FeatureKind, Mat, Occurrence}; -use solidcraft_geom::Vec3; use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list, vec3}; use crate::schema::component::{ - EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, MoveFeaturesParams, MoveFeaturesResult, OccurrenceAlignParams, - OccurrenceAlignResult, ReparentItemsParams, ReparentItemsResult, + EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, MoveFeaturesParams, MoveFeaturesResult, MoveSketchesToPartsParams, + MoveSketchesToPartsResult, OccurrenceAlignParams, OccurrenceAlignResult, ReparentItemsParams, ReparentItemsResult, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -23,6 +24,7 @@ use crate::{EngineError, Result, Session}; const EDIT_IN_PLACE_CONTRACT: TypedContract = TypedContract::new(); const FINISH_EDIT_CONTRACT: TypedContract = TypedContract::new(); const MOVE_FEATURES_CONTRACT: TypedContract = TypedContract::new(); +const MOVE_SKETCHES_TO_PARTS_CONTRACT: TypedContract = TypedContract::new(); const REPARENT_ITEMS_CONTRACT: TypedContract = TypedContract::new(); #[path = "component_align.rs"] @@ -43,9 +45,15 @@ pub(super) mod properties; mod reparent; #[path = "component_reparent_items.rs"] mod reparent_items; +#[path = "component_sketches_to_parts.rs"] +mod sketches_to_parts; #[path = "component_transfer.rs"] mod transfer; +#[cfg(test)] +#[path = "component_history_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod history_tests; #[cfg(test)] #[path = "occurrence_tests.rs"] #[allow(clippy::unwrap_used, clippy::expect_used)] @@ -55,6 +63,12 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.cycle_color", "Cycle Component Color", cycle_color) .icon("colored_components").doc_only() .params("component: id or name; saves the next identification colour and enables Component Colors; shared by every instance, separate from appearances"), + CommandSpec::new("component.hide_history", "Hide Component History", hide_history) + .icon("eye").doc_only() + .params("component: id or name; keeps the component's features in the design but leaves them out of the History bar (#10393)"), + CommandSpec::new("component.show_history", "Show Component History", show_history) + .icon("eye").doc_only() + .params("component: id or name; puts a component's features back in the History bar after Hide Component History (#10393)"), CommandSpec::new("component.create", "New Component", new_component) .at("SOLID", "ASSEMBLE") .icon("component") @@ -130,7 +144,21 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("component.move_sketches", "Move Sketches to Component", move_sketches) .icon("move") - .params("sketches: [ids or names], component; the sketches keep their own coordinates (component.move_features keeps them where they are in the world)"), + .params("sketches: [ids or names], component; the sketches keep their own coordinates (component.move_features keeps them where they are in the world), except that a sketch on an exactly attached face stays where it is on the face"), + CommandSpec::new( + "component.move_sketches.to_parts", + "Move Sketches to Their Parts", + crate::checked!("component.move_sketches.to_parts", sketches_to_parts::to_parts), + ) + .icon("move") + .contract(&MOVE_SKETCHES_TO_PARTS_CONTRACT) + .output(output_schema_for::) + .params( + "sketches?: [ids or names] (default: every sketch in the design) → moved, stayed, sketches [{sketch, name, component, part}], \ + kept [{sketch, name, code, reason}]. Each sketch whose plane is an exactly attached face of a part's body goes to that part, as \ + component.move_sketches moves it, and stays where it is on the face; the others (on an origin, construction or fixed \ + plane, on a body of the design itself, or already in their part) stay where they are. One undo step", + ), CommandSpec::new("component.move_features", "Move Features to Component", crate::checked!("component.move_features", move_features::move_features)) .icon("move") .contract(&MOVE_FEATURES_CONTRACT) @@ -237,17 +265,7 @@ pub(crate) fn refuse_filled_virtual(before: &Document, after: &Document) -> Resu } pub(super) fn valid_position(m: &Mat) -> bool { - let column = |i: usize| Vec3::new(m[i][0], m[i][1], m[i][2]); - let (x, y, z) = (column(0), column(1), column(2)); - m.iter().flatten().all(|x| x.is_finite()) - && m[3][..3].iter().all(|x| x.abs() <= 1e9) - && [x, y, z].iter().all(|axis| (axis.dot(*axis) - 1.0).abs() < 1e-6) - && x.dot(y).abs() < 1e-6 - && x.dot(z).abs() < 1e-6 - && y.dot(z).abs() < 1e-6 - && x.cross(y).dot(z) > 0.0 - && [m[0][3], m[1][3], m[2][3]].iter().all(|x| x.abs() < 1e-9) - && (m[3][3] - 1.0).abs() < 1e-9 + solidcraft_doc::is_placement(m) } pub(super) fn new_component(s: &mut Session, p: &Value) -> Result { @@ -572,6 +590,7 @@ fn move_sketches(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`sketches` must list sketches")); } for id in &ids { + sketches_to_parts::reauthor(s, *id, to, cmd)?; if let Some(f) = s.doc_mut().feature_mut(*id) { f.component = to; } @@ -603,8 +622,8 @@ pub(super) fn copy_occurrence(s: &mut Session, p: &Value) -> Result { let m = if bool_(p, "in_place") == Some(true) { placing::in_place(s, &occurrence_path(s, p, src.id, cmd)?, parent, placing::parent_path(p, cmd)?.as_deref(), t, cmd)? } else { - let base = s.pending_moves.get(&src.id).unwrap_or(&src.transform); - solidcraft_doc::mat_mul(&translation(t), base) + let base = s.uncaptured_moves().get(&src.id).copied().unwrap_or(src.transform); + solidcraft_doc::mat_mul(&translation(t), &base) }; if !valid_position(&m) { return Err(bad(cmd, "copy transform exceeds supported numeric range")); @@ -642,7 +661,7 @@ fn paste_new(s: &mut Session, p: &Value) -> Result { let transform = match occ.as_ref().filter(|_| bool_(p, "in_place") == Some(true)) { Some(o) => placing::in_place(s, &occurrence_path(s, p, o.id, cmd)?, parent, placing::parent_path(p, cmd)?.as_deref(), t, cmd)?, None => { - let base = occ.as_ref().map(|o| s.pending_moves.get(&o.id).copied().unwrap_or(o.transform)).unwrap_or(solidcraft_doc::IDENTITY); + let base = occ.as_ref().map(|o| s.uncaptured_moves().get(&o.id).copied().unwrap_or(o.transform)).unwrap_or(solidcraft_doc::IDENTITY); solidcraft_doc::mat_mul(&translation(t), &base) } }; @@ -738,7 +757,7 @@ fn move_occurrence(s: &mut Session, p: &Value) -> Result { } let path = if p.get("path").is_some() || space == "world" { Some(occurrence_path(s, p, id, cmd)?) } else { None }; let delta = if space == "world" { - let placement = s.occurrence_placement(path.as_deref().unwrap_or(&[]))?; + let placement = s.occurrence_placement_with(path.as_deref().unwrap_or(&[]), &s.uncaptured_moves())?; let inverse = solidcraft_doc::mat_inverse(&placement.parent_world).ok_or_else(|| bad(cmd, "parent frame is singular"))?; solidcraft_doc::mat_mul(&solidcraft_doc::mat_mul(&inverse, &delta), &placement.parent_world) } else { @@ -757,7 +776,7 @@ fn move_occurrence(s: &mut Session, p: &Value) -> Result { } base } else { - s.pending_moves.get(&id).copied().unwrap_or(o.transform) + s.uncaptured_moves().get(&id).copied().unwrap_or(o.transform) }; let next = solidcraft_doc::mat_mul(&delta, &cur); if !valid_position(&next) { @@ -789,7 +808,9 @@ fn ground(s: &mut Session, p: &Value) -> Result { } fn capture(s: &mut Session, _p: &Value) -> Result { - let moves = std::mem::take(&mut s.pending_moves); + // The exploded view is shown, never captured: it stays shown, the design keeps its placements. + let moves = s.uncaptured_moves().into_owned(); + s.pending_moves.retain(|id, _| !moves.contains_key(id)); let n = moves.len(); for (id, m) in moves { if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == id) { @@ -846,3 +867,21 @@ fn cycle_color(s: &mut Session, p: &Value) -> Result { s.colored_components = Some(()); Ok(json!({"component": id, "color": next})) } + +/// Mark a component's features out of the History bar, or back in (#10393). The features still +/// rebuild; only the History bar leaves them out. +fn set_history_hidden(s: &mut Session, p: &Value, hidden: bool) -> Result { + let cmd = if hidden { "component.hide_history" } else { "component.show_history" }; + let id = component(s, p, "component", cmd)?; + let c = s.doc_mut().components.iter_mut().find(|c| c.id == id).ok_or_else(|| bad(cmd, "choose a component below the design root"))?; + c.history_hidden = hidden; + Ok(json!({"component": id, "history_hidden": hidden})) +} + +fn hide_history(s: &mut Session, p: &Value) -> Result { + set_history_hidden(s, p, true) +} + +fn show_history(s: &mut Session, p: &Value) -> Result { + set_history_hidden(s, p, false) +} diff --git a/crates/engine/src/cmd/component_align.rs b/crates/engine/src/cmd/component_align.rs index b8371b6db..7e8ed0978 100644 --- a/crates/engine/src/cmd/component_align.rs +++ b/crates/engine/src/cmd/component_align.rs @@ -3,8 +3,9 @@ //! without modifying shared component geometry across other instances. use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{IDENTITY, mat_inverse, mat_mul, rigid}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use super::{occurrence, occurrence_path, valid_position}; use crate::params::{bad, vec3}; @@ -105,7 +106,7 @@ fn world_pick( if p.get(pk).is_some() || p.get(fk).is_some() { return Err(bad(cmd, format!("give `{pk}_plane` or `{pk}`/`{fk}`, not both"))); } - let world = s.world_state(); + let world = s.world_state()?; let pl = s.placed_document().resolve_plane_in(vals, pl_ref, 0, Some(&*world)).map_err(|e| bad(cmd, e.to_string()))?; return Ok((pl.origin, Some(pl.normal()))); } @@ -129,7 +130,7 @@ fn world_pick( Some(Value::String(k)) if matches!(k.as_str(), "vertex" | "edge_mid" | "face_center" | "circle_center") => k.as_str(), _ => return Err(bad(cmd, format!("`{pk}.snap` must be vertex, edge_mid, face_center or circle_center"))), }; - return super::super::features_more::snap_point(s, kind, at) + return super::super::features_more::snap_point(&*s.world_state()?, kind, at) .map(|q| (q, None)) .ok_or_else(|| bad(cmd, format!("no {kind} to snap to near `{pk}`"))); } diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index 1fb4572ca..6ee0a0d1b 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -1,5 +1,6 @@ //! Independent copies of a component definition graph, assembled and evaluated atomically. use solidcraft_doc::BodyName; +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; use crate::params::bad; @@ -10,7 +11,7 @@ use solidcraft_doc::{Document, Feature, FeatureKind, Mat, Occurrence}; const CMD: &str = "component.paste_new"; const MAX_WORK: usize = 10_000; -fn mesh_distance(mesh: &solidcraft_geom::Mesh, point: solidcraft_geom::Vec3) -> f64 { +fn mesh_distance(mesh: &solidcraft_geom::Mesh, point: solidcore_record::Vec3) -> f64 { mesh.triangles .iter() .filter_map(|triangle| mesh.tri(triangle)) @@ -33,7 +34,7 @@ fn mesh_distance(mesh: &solidcraft_geom::Mesh, point: solidcraft_geom::Vec3) -> .fold(f64::INFINITY, f64::min) } -fn material_probe_matches(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh, point: solidcraft_geom::Vec3, tol_a: f64, tol_b: f64) -> bool { +fn material_probe_matches(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh, point: solidcore_record::Vec3, tol_a: f64, tol_b: f64) -> bool { if !point.is_finite() || !tol_a.is_finite() || !tol_b.is_finite() || tol_a <= 0. || tol_b <= 0. { return false; } @@ -48,7 +49,7 @@ fn material_probe_matches(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh, let offset = 4. * tol_a.max(tol_b); let mut material = false; let mut void = false; - for axis in [solidcraft_geom::Vec3::X, solidcraft_geom::Vec3::Y, solidcraft_geom::Vec3::Z] { + for axis in [solidcore_record::Vec3::X, solidcore_record::Vec3::Y, solidcore_record::Vec3::Z] { for sign in [-1., 1.] { let q = point + axis * (sign * offset); if !q.is_finite() { @@ -190,7 +191,7 @@ fn graph(doc: &Document, root: u64) -> Result> { pub(super) struct Source<'a> { pub doc: &'a Document, pub model: &'a solidcraft_doc::Model, - pub pending_moves: &'a BTreeMap, + pub pending_moves: std::borrow::Cow<'a, BTreeMap>, /// Another design than the target: the copy can't point at anything outside it (it is /// refused, saying what), and the user parameters it uses come along. pub other_design: bool, @@ -199,12 +200,12 @@ pub(super) struct Source<'a> { impl<'a> Source<'a> { /// The session's own design. pub fn of(s: &'a Session) -> Source<'a> { - Source { doc: &s.doc, model: &s.model, pending_moves: &s.pending_moves, other_design: false } + Source { doc: &s.doc, model: &s.model, pending_moves: s.uncaptured_moves(), other_design: false } } /// What was copied in another design. pub fn copied(copy: &'a crate::ForeignCopy) -> Source<'a> { - Source { doc: ©.doc, model: ©.model, pending_moves: ©.pending_moves, other_design: true } + Source { doc: ©.doc, model: ©.model, pending_moves: std::borrow::Cow::Borrowed(©.pending_moves), other_design: true } } } @@ -563,7 +564,6 @@ pub(super) fn build( } if let Some(name) = &face.name { face.point = solidcraft_doc::naming::point_on_face(&state, name, face.point) - .map(|(point, _)| point) .ok_or_else(|| bad(CMD, "source frozen face appearance lost its identity"))?; } let source_body = state.body(&face.body).ok_or_else(|| bad(CMD, "source frozen face appearance lost its body"))?; @@ -758,8 +758,8 @@ pub(super) fn build( let mut material_matches = true; let tol_a = (a.size() * 1e-3).max(1e-3).max(a.size() * 1e-6); let tol_b = (b.size() * 1e-3).max(1e-3).max(b.size() * 1e-6); - let mesh_a = a.display_mesh(tol_a)?; - let mesh_b = b.display_mesh(tol_b)?; + let mesh_a = a.mesh(&solidcraft_kernel::MeshTolerance::chord(tol_a))?; + let mesh_b = b.mesh(&solidcraft_kernel::MeshTolerance::chord(tol_b))?; // Precharge all 27 candidates, six possible replacements, their triangle // distances and the three containment rays before any proof traversal. proof_work = proof_work.saturating_add(mesh_a.triangles.len().saturating_add(mesh_b.triangles.len()).saturating_mul(27 * 7 * 4)); @@ -770,7 +770,7 @@ pub(super) fn build( for y in [0.2, 0.5, 0.8] { for z in [0.2, 0.5, 0.8] { let d = ma.bbox.max - ma.bbox.min; - let p = ma.bbox.min + solidcraft_geom::Vec3::new(d.x * x, d.y * y, d.z * z); + let p = ma.bbox.min + solidcore_record::Vec3::new(d.x * x, d.y * y, d.z * z); let roundoff = 64. * f64::EPSILON * (1. + p.len()); material_matches &= material_probe_matches(&mesh_a, &mesh_b, p, tol_a + roundoff, tol_b + roundoff); } diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index b52459acb..4956d6548 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -1,9 +1,9 @@ #![allow(clippy::unwrap_used, clippy::panic)] use super::*; +use solidcore_record::Vec3; use solidcraft_doc::joints::{Coupling, Joint, JointKind, MotionLink, NamedOrigin, Size, Snap, XRef}; use solidcraft_doc::motion::{ContactSet, ExplodedView, MotionStudy, StudyKey}; use solidcraft_doc::{IDENTITY, Occurrence}; -use solidcraft_geom::Vec3; fn at(occurrence: u64) -> JointOrigin { JointOrigin { occurrence, snap: Snap::Point { point: Vec3::ZERO, z: None, x: None } } diff --git a/crates/engine/src/cmd/component_clone_tests.rs b/crates/engine/src/cmd/component_clone_tests.rs index b2888fdd6..727d21b9d 100644 --- a/crates/engine/src/cmd/component_clone_tests.rs +++ b/crates/engine/src/cmd/component_clone_tests.rs @@ -1,6 +1,7 @@ #![allow(clippy::unwrap_used)] use crate::Session; use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap() } @@ -256,7 +257,7 @@ fn configuration_rows_follow_copied_parameters_material_and_strict_face_lineage( body: "Cube".into(), origin_feature: source, name: format!("F{source}:+z"), - point: solidcraft_geom::Vec3::new(1.0, 1.0, 2.0), + point: solidcore_record::Vec3::new(1.0, 1.0, 2.0), certificate: None, }; run(&mut s, "config.configure", json!({"params":[length],"materials":["Cube"],"component_appearances":[part],"face_appearances":[target]})); @@ -294,7 +295,7 @@ fn configured_extrude_cap_copy_keeps_independent_semantic_lineage() { body: body_name, origin_feature: feature, name: format!("F{feature}:top"), - point: solidcraft_geom::Vec3::new(1.0, 1.0, 2.0), + point: solidcore_record::Vec3::new(1.0, 1.0, 2.0), certificate: None, }; run(&mut s, "config.configure", json!({"face_appearances":[target]})); @@ -358,7 +359,7 @@ fn reassigned_sample_plate_paste_new_preserves_complex_frozen_geometry() { run(&mut s, "occurrence.ground", json!({"occurrence":occurrence,"grounded":true})); let original_volume = volume(&mut s, part); let source_mesh = s.model.state().body(&body).unwrap().mesh(); - let boss_probe = solidcraft_geom::Vec3::new(40.0, 35.0, 12.0); + let boss_probe = solidcore_record::Vec3::new(40.0, 35.0, 12.0); let source_boss = source_mesh.contains(boss_probe); let copied = run(&mut s, "component.paste_new", json!({"component":part,"translate":[10,10,0]})); assert_eq!(s.doc.components.len(), 2); @@ -373,7 +374,7 @@ fn reassigned_sample_plate_paste_new_preserves_complex_frozen_geometry() { for (point, expected) in [([5.0, 25.0, 4.0], true), ([12.0, 25.0, 4.0], false), ([68.0, 25.0, 4.0], false), ([40.0, 25.0, 12.0], false), ([0.0, 0.0, 4.0], false)] { - assert_eq!(mesh.contains(solidcraft_geom::Vec3::new(point[0], point[1], point[2])), expected, "{point:?}"); + assert_eq!(mesh.contains(solidcore_record::Vec3::new(point[0], point[1], point[2])), expected, "{point:?}"); } assert_eq!(mesh.contains(boss_probe), source_boss); assert_eq!(state.body(&body).unwrap().mesh().contains(boss_probe), source_boss); @@ -473,13 +474,13 @@ fn transferred_frozen_face_paint_ignores_consumed_legacy_offset() { run(&mut s, "appearance.assign", json!({"body":"Foreign","faces":[[1,1,2]],"color":"#00ff00"})); s.doc_mut().body_offsets.insert( "Foreign".into(), - solidcraft_doc::rigid(solidcraft_geom::Vec3::new(7.0, 0.0, 0.0), solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::Z, 0.0), + solidcraft_doc::rigid(solidcore_record::Vec3::new(7.0, 0.0, 0.0), solidcore_record::Vec3::ZERO, solidcore_record::Vec3::Z, 0.0), ); s.refresh(); let part = component(&mut s, "Part"); run(&mut s, "component.move_bodies", json!({"component":part,"bodies":["Foreign"]})); let original = s.doc.appearances.faces.iter().find(|face| face.body == "Foreign").unwrap(); - let expected = solidcraft_doc::naming::point_on_face(&s.model.state(), original.name.as_ref().unwrap(), original.point).unwrap().0; + let expected = solidcraft_doc::naming::point_on_face(&s.model.state(), original.name.as_ref().unwrap(), original.point).unwrap(); copy(&mut s, part); let paint = s.doc.appearances.faces.iter().find(|face| face.body == "Foreign (2)").unwrap(); assert!(paint.point.dist(expected) < 1e-6, "{:?} versus {expected:?}", paint.point); @@ -487,18 +488,28 @@ fn transferred_frozen_face_paint_ignores_consumed_legacy_offset() { #[test] fn boundary_material_proof_requires_resolvable_stock_and_void() { - use solidcraft_geom::Vec3; - let a = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap().tessellate(1e-3).unwrap(); - let b = solidcraft_kernel::box_solid(Vec3::new(1e-5, 0., 0.), Vec3::new(10.00001, 10., 10.)).unwrap().tessellate(1e-3).unwrap(); + use solidcore_record::Vec3; + let a = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap(); + let b = solidcraft_kernel::box_solid(Vec3::new(1e-5, 0., 0.), Vec3::new(10.00001, 10., 10.)) + .unwrap() + .mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)) + .unwrap(); let p = Vec3::new(5e-6, 5., 5.); assert_ne!(a.contains(p), b.contains(p)); assert!((super::mesh_distance(&a, p) - 5e-6).abs() < 1e-12); assert!((super::mesh_distance(&b, p) - 5e-6).abs() < 1e-12); assert!(super::material_probe_matches(&a, &b, p, 1e-3, 1e-3)); - let shifted = solidcraft_kernel::box_solid(Vec3::new(1., 0., 0.), Vec3::new(11., 10., 10.)).unwrap().tessellate(1e-3).unwrap(); + let shifted = solidcraft_kernel::box_solid(Vec3::new(1., 0., 0.), Vec3::new(11., 10., 10.)) + .unwrap() + .mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)) + .unwrap(); assert!(!super::material_probe_matches(&a, &shifted, p, 1e-3, 1e-3)); - let thin = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 1e-4)).unwrap().tessellate(1e-6).unwrap(); - let thin_shifted = solidcraft_kernel::box_solid(Vec3::new(0., 0., 1e-4), Vec3::new(10., 10., 2e-4)).unwrap().tessellate(1e-6).unwrap(); + let thin = + solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 1e-4)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-6)).unwrap(); + let thin_shifted = solidcraft_kernel::box_solid(Vec3::new(0., 0., 1e-4), Vec3::new(10., 10., 2e-4)) + .unwrap() + .mesh(&solidcraft_kernel::MeshTolerance::chord(1e-6)) + .unwrap(); // Every resolvable replacement is void: thin ambiguous material is refused. assert!(!super::material_probe_matches(&thin, &thin_shifted, Vec3::new(5., 5., 5e-5), 1e-3, 1e-3)); assert!(!super::material_probe_matches(&a, &b, p, f64::INFINITY, 1e-3)); @@ -506,7 +517,7 @@ fn boundary_material_proof_requires_resolvable_stock_and_void() { #[test] fn frozen_bore_boundary_copy_preserves_stock_void_and_reopen() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let bore = |center: f64| { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length":30,"width":20,"height":10,"body_name":"Drilled"})); @@ -514,12 +525,13 @@ fn frozen_bore_boundary_copy_preserves_stock_void_and_reopen() { s }; let mut s = bore(10.); - let source = s.model.state().body("Drilled").unwrap().body.tessellate(1e-3).unwrap(); + let source = s.model.state().body("Drilled").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap(); // The exact R4 wall passes through x6; a chord may end either side of that // cardinal angle, so its distance is bounded by the requested sag tolerance. assert!(super::mesh_distance(&source, Vec3::new(6., 10., 5.)) <= 1e-3); - let shifted = bore(11.).model.state().body("Drilled").unwrap().body.tessellate(1e-3).unwrap(); - let lost = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(30., 20., 10.)).unwrap().tessellate(1e-3).unwrap(); + let shifted = bore(11.).model.state().body("Drilled").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap(); + let lost = + solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(30., 20., 10.)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap(); assert!(!super::material_probe_matches(&source, &shifted, Vec3::new(6.5, 10., 5.), 1e-3, 1e-3)); assert!(!super::material_probe_matches(&source, &lost, Vec3::new(10., 10., 5.), 1e-3, 1e-3)); let created = run(&mut s, "component.from_bodies", json!({"bodies":["Drilled"]})); @@ -528,7 +540,7 @@ fn frozen_bore_boundary_copy_preserves_stock_void_and_reopen() { let check = |session: &Session| { let state = session.model.state(); let body = state.bodies.iter().find(|body| session.doc.model_body_component(body) == copied).unwrap(); - let mesh = body.body.tessellate(1e-3).unwrap(); + let mesh = body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap(); for (point, stock) in [(Vec3::new(5.5, 10., 5.), true), (Vec3::new(6.5, 10., 5.), false), (Vec3::new(10., 10., 5.), false), (Vec3::new(18., 10., 5.), true)] { @@ -541,7 +553,7 @@ fn frozen_bore_boundary_copy_preserves_stock_void_and_reopen() { #[test] fn frozen_r6_bore_copy_uses_current_geometry_despite_mesh_measure_bias() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut s = Session::default(); run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10,"body_name":"Drilled"})); run(&mut s, "solid.cylinder", json!({"base":[10,10,0],"radius":6,"height":10,"operation":"cut"})); @@ -555,7 +567,7 @@ fn frozen_r6_bore_copy_uses_current_geometry_despite_mesh_measure_bias() { let state = session.model.state(); let body = state.bodies.iter().find(|b| session.doc.model_body_component(b) == copied).unwrap(); assert_eq!(solidcraft_kernel::certified_prism_equivalent(&source, &body.body).unwrap(), Some(true)); - let mesh = body.body.tessellate(1e-3).unwrap(); + let mesh = body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap(); for (point, material) in [(Vec3::new(3., 10., 5.), true), (Vec3::new(5., 10., 5.), false), (Vec3::new(10., 10., 5.), false), (Vec3::new(18., 10., 5.), true)] { diff --git a/crates/engine/src/cmd/component_drag_tests.rs b/crates/engine/src/cmd/component_drag_tests.rs index 2f2cc3b50..bc0629fa7 100644 --- a/crates/engine/src/cmd/component_drag_tests.rs +++ b/crates/engine/src/cmd/component_drag_tests.rs @@ -193,7 +193,7 @@ fn a_drag_and_a_world_move_leave_the_same_design() { run(&mut dragged, "occurrence.drag", json!({"occurrence": free, "at": [25, 0, 0], "point": [25, 15, 0]})); run(&mut moved, "occurrence.move", json!({"occurrence": free, "space": "world", "translate": [0, 15, 0]})); assert_eq!(dragged.doc.to_json(), moved.doc.to_json()); - let shown = |s: &Session| format!("{:?}", s.world_state().sketches.iter().map(|k| &k.sketch.points).collect::>()); + let shown = |s: &Session| format!("{:?}", s.world_state().unwrap().sketches.iter().map(|k| &k.sketch.points).collect::>()); assert_eq!(shown(&dragged), shown(&moved)); } diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs index 4a7022091..2ac92d4c3 100644 --- a/crates/engine/src/cmd/component_extract.rs +++ b/crates/engine/src/cmd/component_extract.rs @@ -10,14 +10,15 @@ //! as it did before. Anything that crosses the component's boundary (a feature outside that uses //! its sketches, bodies moved in or out, a joint to one of its subcomponents) is refused. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{DesignLink, Document, FeatureKind, ModelBody, ModelState}; -use solidcraft_geom::Vec3; -use super::{absolute, component_key, inherit_properties, resolve, session_bodies, stored}; +use super::{absolute, component_key, file_sha256, inherit_properties, resolve, session_bodies, stored}; use crate::params::{bad, str_}; use crate::{EngineError, Result, Session}; @@ -131,10 +132,10 @@ fn keep_component_looks(doc: &mut Document, owners: &BTreeMap, comp /// What the bodies `new` call the face or edge that `old` calls `name`, found where it is. fn renamed(old: &ModelState, new: &[&ModelBody], name: &str, near: Vec3) -> Option { use solidcraft_doc::{appearance::face_index_at, naming}; - if let Some((p, _)) = naming::point_on_face(old, name, near) { + if let Some(p) = naming::point_on_face(old, name, near) { return new.iter().find_map(|b| face_index_at(b, p).and_then(|i| naming::face_names(b).get(i).cloned())); } - let p = old.bodies.iter().find_map(|b| naming::find_edge(b, name, near).ok())?.0; + let p = old.bodies.iter().find_map(|b| naming::find_edge(b, name, near).ok())?; new.iter().find(|b| face_index_at(b, p).is_some()).and_then(|b| naming::edge_names_at(b, &[p]).pop()) } @@ -228,7 +229,7 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result { if source.marker.is_some_and(|m| m < source.features.len()) { return Err(bad(cmd, "move the timeline marker to the end first")); } - if !s.pending_moves.is_empty() { + if !s.uncaptured_moves().is_empty() { return Err(bad(cmd, "capture or revert the moved components first")); } let subtree: BTreeSet = source.components.iter().filter(|c| source.component_within(c.id, comp)).map(|c| c.id).collect(); @@ -381,7 +382,7 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio if !source.configs.is_empty() { notices.push(format!("the configurations stay in this design; {stem} has none")); } - let part = Session::new(part); + let part = Session::opened_validating(part, None, s.validation()); let failing: Vec = part.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| format!("{} ({e})", r.name))).take(5).collect(); if !failing.is_empty() { return Err(bad(cmd, format!("{name} does not build on its own: {}", failing.join("; ")))); @@ -458,14 +459,14 @@ struct Before { } impl Before { - fn take(s: &Session) -> Before { + fn take(s: &Session) -> Result { let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state()); - Before { - world: s.world_state(), + Ok(Before { + world: s.world_state()?, placements: s.doc.occurrences.iter().map(|o| (o.id, o.transform)).collect(), errors: s.model.results.iter().map(|r| (r.id, r.error.is_some())).collect(), joint_errors: sol.errors.iter().chain(&sol.conflicts).map(|(_, n, _)| n.clone()).collect(), - } + }) } /// Refuse a swap that made a feature fail or changed a body; warn about joints it broke and @@ -487,7 +488,7 @@ impl Before { o.transform = *t; } } - let world = if moved.is_empty() { s.world_state() } else { std::sync::Arc::new(solidcraft_doc::world_state(&placed, &s.model.state())) }; + let world = if moved.is_empty() { s.world_state()? } else { std::sync::Arc::new(solidcraft_doc::world_state(&placed, &s.model.state())?) }; let (was, now): (Vec<&ModelBody>, Vec<&ModelBody>) = (self.world.bodies.iter().collect(), world.bodies.iter().collect()); if let Some(what) = unmatched(&was, &now)? { return Err(bad(cmd, format!("{what} would look different without the history of {name}"))); @@ -534,7 +535,7 @@ fn copies_of(s: &Session, linked: u64) -> Result> { } let Ok(sc) = scope(s, c.id, CMD) else { continue }; let Ok((part, _)) = part_design(s, &sc, &c.name, CMD) else { continue }; - let world = part.world_state(); + let world = part.world_state()?; let built: Vec<&ModelBody> = world.bodies.iter().collect(); if same_solids(&reference, &built)? { out.push(c.id); @@ -574,12 +575,12 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result { let (_, sf, faces, _, properties) = session_bodies(&part, &shown)?; // The link has a body per piece: a body in pieces keeps its name on the first let mut solids: Vec = Vec::new(); - for b in part.world_state().bodies.iter().filter(|b| !b.body.is_mesh()) { + for b in part.world_state()?.bodies.iter().filter(|b| !b.body.is_mesh()) { let pieces = b.body.lumps()?.len().max(1); solids.extend((1..=pieces).map(|n| if n == 1 { b.name.clone() } else { format!("{} ({n})", b.name) })); } let state = s.model.state(); - let before = Before::take(s); + let before = Before::take(s)?; let last = s.doc.features.iter().rposition(|f| sc.inside.contains(&f.id)).unwrap_or(s.doc.features.len()); let at = s.doc.features.iter().take(last).filter(|f| !sc.inside.contains(&f.id)).count(); clear_history(s, &sc); @@ -597,7 +598,7 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result { f.link_faces = faces; } let path = stored(s.path.as_deref(), &file); - s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id, inherited: Vec::new() }); + s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id, ..Default::default() }); s.refresh(); rename_joint_faces(s, &state, id, &sc.own); if let Some(e) = s.model.result(id).and_then(|r| r.error.clone()) { @@ -611,6 +612,12 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result { part.path = s.path.clone(); part.execute("file.save", &json!({"path": shown}))?; + // The link keeps what the new file holds, as Insert Design's does (#9739). + if let Some(read) = file_sha256(&file, s.path.as_deref()) + && let Some(link) = s.doc_mut().links.get_mut(&comp) + { + link.file_sha256 = Some(read); + } Ok(json!({"component": comp, "feature": id, "path": path, "file": shown, "bodies": sc.bodies, "notices": notices, "warnings": warnings, "copies": named(s, &copies)})) } @@ -668,12 +675,12 @@ pub(super) fn replace_with_link(s: &mut Session, p: &Value) -> Result { let (part, _) = part_design(s, &sc, &sc.name, cmd)?; let state = s.model.state(); let reference: Vec<&ModelBody> = state.bodies.iter().filter(|b| b.feature == link.feature).collect(); - let world = part.world_state(); + let world = part.world_state()?; let built: Vec<&ModelBody> = world.bodies.iter().collect(); if !same_solids(&reference, &built)? { return Err(bad(cmd, format!("{} is not the same as {lname}", sc.name))); } - let before = Before::take(s); + let before = Before::take(s)?; clear_history(s, &sc); let d = s.doc_mut(); // Named as the linked component's next placements, as add_occurrence names them @@ -726,6 +733,7 @@ mod tests { fn volumes(s: &Session) -> BTreeMap { s.world_state() + .unwrap() .bodies .iter() .map(|b| (b.name.clone(), (solidcraft_kernel::measure(&b.body).unwrap().volume * 1000.0).round() as i64)) @@ -734,6 +742,7 @@ mod tests { fn centroids(s: &Session) -> BTreeMap { s.world_state() + .unwrap() .bodies .iter() .map(|b| { @@ -748,6 +757,7 @@ mod tests { fn shapes(s: &Session) -> Vec<[i64; 4]> { let mut out: Vec<[i64; 4]> = s .world_state() + .unwrap() .bodies .iter() .map(|b| { @@ -894,12 +904,12 @@ mod tests { let plate_occ = s.doc.occurrence_of(plate).map(|o| o.id).unwrap(); let other_occ = s.doc.occurrence_of(other).map(|o| o.id).unwrap(); let top = { - let w = s.world_state(); + let w = s.world_state().unwrap(); let m = solidcraft_kernel::measure(&w.body("PlateBody").unwrap().body).unwrap(); [(m.bbox.min.x + m.bbox.max.x) / 2.0, (m.bbox.min.y + m.bbox.max.y) / 2.0, m.bbox.max.z] }; let bottom = { - let w = s.world_state(); + let w = s.world_state().unwrap(); let m = solidcraft_kernel::measure(&w.body("OtherBody").unwrap().body).unwrap(); [(m.bbox.min.x + m.bbox.max.x) / 2.0, (m.bbox.min.y + m.bbox.max.y) / 2.0, m.bbox.min.z] }; diff --git a/crates/engine/src/cmd/component_foreign_tests.rs b/crates/engine/src/cmd/component_foreign_tests.rs index a566a1b1d..1e989339e 100644 --- a/crates/engine/src/cmd/component_foreign_tests.rs +++ b/crates/engine/src/cmd/component_foreign_tests.rs @@ -1,6 +1,7 @@ #![allow(clippy::unwrap_used)] use crate::{ForeignCopy, Session}; use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use std::sync::Arc; fn run(s: &mut Session, cmd: &str, p: Value) -> Value { @@ -20,7 +21,7 @@ fn design(name: &str) -> Session { } /// `s` copies its placement `path` for another design. fn copied(s: &Session, path: Vec) -> Option> { - Some(Arc::new(ForeignCopy::of(s, Vec::new(), vec![path]))) + ForeignCopy::of(s, Vec::new(), vec![path]).ok().map(Arc::new) } /// A component copied in another design pastes as an independent copy of it and what it holds: @@ -37,7 +38,7 @@ fn a_component_from_another_design_pastes_with_its_history() { run(&mut source, "component.activate", json!({"component": 0})); run(&mut source, "occurrence.ground", json!({"occurrence": at, "grounded": false})); run(&mut source, "occurrence.move", json!({"occurrence": at, "translate": [0, 30, 0]})); - let was = source.world_state().body("Cube").unwrap().mesh().bounds(); + let was = source.world_state().unwrap().body("Cube").unwrap().mesh().bounds(); let box_features = source.doc.features.len(); let mut s = design("Frame"); @@ -55,7 +56,7 @@ fn a_component_from_another_design_pastes_with_its_history() { assert_eq!(s.doc.features.len(), box_features, "the box's history came along"); assert!((volume(&mut s, new) - 16.0).abs() < 1e-6); assert_eq!(s.doc.appearances.bodies["Cube"].color, [0xab, 0xcd, 0xef]); - let is = s.world_state().body("Cube").unwrap().mesh().bounds(); + let is = s.world_state().unwrap().body("Cube").unwrap().mesh().bounds(); assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}"); // Its history is its own: changing it here leaves the original as it was. let copy = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Box { .. })).unwrap(); diff --git a/crates/engine/src/cmd/component_history_tests.rs b/crates/engine/src/cmd/component_history_tests.rs new file mode 100644 index 000000000..62b6b0a8b --- /dev/null +++ b/crates/engine/src/cmd/component_history_tests.rs @@ -0,0 +1,34 @@ +// Per-component History hiding (#10393) through the same commands the Browser menu runs. +use crate::Session; +use serde_json::json; + +#[test] +fn hide_and_show_history_mark_the_component_flag_and_undo() { + let mut s = Session::default(); + s.execute("component.create", &json!({ "name": "Copy" })).unwrap(); + s.execute("component.activate", &json!({ "component": "root" })).unwrap(); + assert_eq!(s.execute("component.hide_history", &json!({ "component": "Copy" })).unwrap()["history_hidden"], json!(true)); + assert!(s.doc.components.iter().find(|c| c.name == "Copy").unwrap().history_hidden); + assert_eq!(s.execute("component.show_history", &json!({ "component": "Copy" })).unwrap()["history_hidden"], json!(false)); + assert!(!s.doc.components.iter().find(|c| c.name == "Copy").unwrap().history_hidden); + // Undo of the show puts the flag back; undo of the hide takes it away. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc.components.iter().find(|c| c.name == "Copy").unwrap().history_hidden); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.doc.components.iter().find(|c| c.name == "Copy").unwrap().history_hidden); +} + +#[test] +fn hide_history_needs_a_real_component_and_survives_a_save_round_trip() { + let mut s = Session::default(); + s.execute("component.create", &json!({ "name": "Copy" })).unwrap(); + assert!(s.execute("component.hide_history", &json!({ "component": "root" })).is_err()); + s.execute("component.hide_history", &json!({ "component": "Copy" })).unwrap(); + // The flag rides in the design JSON and comes back on read. + let json = s.doc.to_json(); + let read = solidcraft_doc::Document::from_json(&json).unwrap(); + assert!(read.components.iter().find(|c| c.name == "Copy").unwrap().history_hidden); + // A design without the flag reads as shown, as always. + let plain = solidcraft_doc::Document::from_json(&Session::default().doc.to_json()).unwrap(); + assert!(!plain.components.iter().any(|c| c.history_hidden)); +} diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index 32ca56c7c..b2e0bedb6 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -8,6 +8,7 @@ //! the design gives them (`Feature::link_faces`), so a joint on a linked face stays on that face //! when the design changes, as it would inside the design, and reports it when the face is gone. +use solidcraft_geom::prelude::*; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Mutex; @@ -31,15 +32,18 @@ mod relink_tests; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params( "path: a .sc design → a new component linked to it, holding its solid bodies as placed in that design and a copy of its design properties; \ - name? (default: the design's name); parent?: component id or name (default: the active one); translate?: [x,y,z]; \ + name? (default: the design's name); parent?: component id or name (default: the active one); \ + translate?: [x,y,z] in mm from the destination parent's origin (default [0,0,0], also with reuse); \ reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available", ), CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params( - "component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed; \ - → updated, unchanged, warnings (also joints whose faces are gone or that no longer solve)", + "component?: id or name (default: every linked component); components?: a list of ids or names, which goes on past a design it \ + cannot read (that one keeps its bodies, is named in failed and gets a warning) — reads the linked designs again and replaces \ + their bodies where they changed, as one undo step; → updated, unchanged, failed ([{component, name, error}]), warnings (also \ + joints whose faces are gone or that no longer solve)", ), CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params( - "component: id or name of a linked component; path: a saved .sc design — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts", + "component: id or name of a linked component; path: a saved design (.sc or .json) — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts", ), CommandSpec::new("component.break_link", "Break Link", break_link) .icon("break") @@ -59,7 +63,8 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("component.links", "List Links", list_links).icon("chain").noundo().params( "→ linked components: component, name, path, file (resolved), found (null when the file is on a network location not allowed, \ - or names a device: it is not looked for), and then host (the network location) and reason", + or names a device: it is not looked for), changed (whether the file is no longer what this design last read: Update Links \ + reads it again; null when not found or the link is older than this record), and then host (the network location) and reason", ), ]; @@ -170,14 +175,43 @@ fn read_link(file: &Path, own: Option<&str>) -> Result> { }) } -/// The solid bodies of the design at `file`, evaluated, as an Import feature. -fn linked_bodies(file: &Path, own: Option<&str>) -> Result { - design_bodies(file, &read_link(file, own)?) +/// The solid bodies of the design at `file`, evaluated under `validation`, as an Import feature, with the digest of +/// the bytes read, which the link keeps ([`DesignLink::file_sha256`], #9739). +fn linked_bodies_read(file: &Path, own: Option<&str>, validation: solidcraft_kernel::Validation) -> Result<(Linked, String)> { + let bytes = read_link(file, own)?; + Ok((design_bodies(file, &bytes, validation)?, DesignLink::file_digest(&bytes))) +} + +/// Linked files' digests as [`file_sha256`] last worked them out, by file, with the time and +/// size the file had then. Bounded, oldest first out. +static DIGESTS: Mutex> = Mutex::new(Vec::new()); +const DIGESTS_SIZE: usize = 256; + +/// The digest of the design file at `file` now ([`DesignLink::file_digest`]), `None` when it +/// can't be read. `component.links` asks each time a tab is shown, so a file is read again only +/// when its time or size changed since; the browser build keeps no times and reads it each time. +pub(super) fn file_sha256(file: &Path, own: Option<&str>) -> Option { + let file = absolute(file); + let stamp = solidcraft_io::vfs::design_path_stamp(&file.to_string_lossy(), own); + if let Some(stamp) = stamp + && let Some(known) = DIGESTS.lock().ok()?.iter().find(|(f, s, _)| *f == file && *s == stamp).map(|(_, _, d)| d.clone()) + { + return Some(known); + } + let digest = DesignLink::file_digest(&read_link(&file, own).ok()?); + if let (Some(stamp), Ok(mut digests)) = (stamp, DIGESTS.lock()) { + digests.retain(|(f, _, _)| *f != file); + if digests.len() >= DIGESTS_SIZE { + digests.remove(0); + } + digests.push((file, stamp, digest.clone())); + } + Some(digest) } /// The solid bodies of `bytes`, the design at `file`, as an Import feature. The model the file /// keeps is its evaluation when this build saved it for exactly that design, as when it is opened. -fn design_bodies(file: &Path, bytes: &[u8]) -> Result { +fn design_bodies(file: &Path, bytes: &[u8], validation: solidcraft_kernel::Validation) -> Result { #[cfg(test)] EVALUATED.with(|n| n.set(n.get() + 1)); let shown = file.display().to_string(); @@ -189,7 +223,8 @@ fn design_bodies(file: &Path, bytes: &[u8]) -> Result { } else { (solidcraft_io::read_design(bytes).map_err(fail)?, None) }; - let (name, feature, faces, metadata, properties) = session_bodies(&Session::opened_at(doc, saved.as_ref(), Some(&shown)), &shown)?; + let (name, feature, faces, metadata, properties) = + session_bodies(&Session::opened_at_validating(doc, saved.as_ref(), Some(&shown), validation), &shown)?; remember_read(file, digest(bytes), &feature, &faces, &properties); Ok((name, feature, faces, metadata, properties)) } @@ -200,7 +235,7 @@ fn session_bodies(part: &Session, shown: &str) -> Result { if let Some(e) = part.model.results.iter().find_map(|r| r.error.clone()) { return Err(EngineError::Other(format!("{shown}: the design has a feature that fails ({e}); fix it before linking it"))); } - let world = part.world_state(); + let world = part.world_state()?; let solids: Vec = world.bodies.iter().filter(|b| !b.body.is_mesh()).map(|b| b.name.clone()).collect(); if solids.is_empty() { return Err(EngineError::Other(format!("{shown}: the design has no solid bodies to link"))); @@ -462,7 +497,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { let cmd = "component.insert_design"; let given = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))?; let translate = match p.get("translate") { - None => solidcraft_geom::Vec3::ZERO, + None => solidcore_record::Vec3::ZERO, Some(v) => vec3(v).filter(|t| t.is_finite() && t.len() < 1e9).ok_or_else(|| bad(cmd, "`translate` must be [x, y, z] in mm"))?, }; // A network or device path is judged from its text, as given, before anything reads it. @@ -474,11 +509,16 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { if p.get("reuse").and_then(Value::as_bool).unwrap_or(false) { let existing = s.doc.links.iter().find(|(_, link)| absolute(&resolve(s.path.as_deref(), &link.path)) == file).map(|(id, _)| *id); if let Some(component) = existing { - let parent = p.get("parent").cloned().unwrap_or_else(|| json!(s.active_component)); - return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate})); + let parent = if p.get("parent").is_some() { component_key(s, p, "parent", cmd)? } else { s.active_component }; + // Reuse the definition, not another placement's captured or pending move. + // Insert Design places from the parent origin whether the link is new or reused. + let mut transform = solidcraft_doc::IDENTITY; + transform[3] = [translate.x, translate.y, translate.z, 1.0]; + let occurrence = s.doc_mut().add_occurrence(component, parent, transform)?; + return Ok(json!({"occurrence": occurrence, "component": component})); } } - let (design_name, sf, faces, metadata, properties) = linked_bodies(&file, s.path.as_deref())?; + let ((design_name, sf, faces, metadata, properties), read) = linked_bodies_read(&file, s.path.as_deref(), s.validation())?; let name = str_(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string).unwrap_or(design_name); let mut create = json!({"name": name, "activate": false}); // Clipboard insertion uses reuse even for the first paste, which must stay movable. @@ -505,7 +545,9 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { o.transform[3] = [translate.x, translate.y, translate.z, 1.0]; } let path = stored(s.path.as_deref(), &file); - s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id, inherited: Vec::new() }); + s.doc_mut() + .links + .insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id, inherited: Vec::new(), file_sha256: Some(read) }); s.refresh(); if let Some(e) = s.model.result(id).and_then(|r| r.error.clone()) { return Err(EngineError::Other(e)); @@ -521,14 +563,25 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { fn update_links(s: &mut Session, p: &Value) -> Result { let cmd = "component.update_links"; - let only = if p.get("component").is_some() { Some(component_key(s, p, "component", cmd)?) } else { None }; - if let Some(c) = only - && !s.doc.links.contains_key(&c) - { - return Err(bad(cmd, "that component is not linked to a design")); + let only = match (p.get("component"), p.get("components")) { + (Some(_), Some(_)) => return Err(bad(cmd, "give `component` or `components`, not both")), + (Some(_), None) => Some(vec![component_key(s, p, "component", cmd)?]), + (None, Some(Value::Array(list))) if !list.is_empty() && list.len() <= 10_000 => { + Some(list.iter().map(|c| component_key(s, &json!({"component": c}), "component", cmd)).collect::>>()?) + } + (None, Some(_)) => return Err(bad(cmd, "`components` must be a list of component ids or names")), + (None, None) => None, + }; + if let Some(c) = only.iter().flatten().find(|c| !s.doc.links.contains_key(c)) { + let name = s.doc.components.iter().find(|x| x.id == *c).map_or_else(|| c.to_string(), |x| x.name.clone()); + return Err(bad(cmd, format!("{name}: that component is not linked to a design"))); } - let links: Vec<(u64, DesignLink)> = s.doc.links.iter().filter(|(c, _)| only.is_none_or(|o| o == **c)).map(|(c, l)| (*c, l.clone())).collect(); - let (mut updated, mut unchanged, mut warnings) = (Vec::new(), Vec::new(), Vec::new()); + // A list goes on past a design it cannot read: that link keeps its bodies and is named in + // `failed`, so the others still come in as one step (#9743). + let go_on = p.get("components").is_some(); + let links: Vec<(u64, DesignLink)> = + s.doc.links.iter().filter(|(c, _)| only.as_ref().is_none_or(|o| o.contains(c))).map(|(c, l)| (*c, l.clone())).collect(); + let (mut updated, mut unchanged, mut warnings, mut failed) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); let count = links.len(); for (index, (comp, link)) in links.into_iter().enumerate() { let cname = s.doc.components.iter().find(|c| c.id == comp).map(|c| c.name.clone()); @@ -539,16 +592,23 @@ fn update_links(s: &mut Session, p: &Value) -> Result { }; // A window running this off its thread names the design being read again (#5329). solidcraft_doc::progress::item(Some((&cname, index, count))); - let Some(FeatureKind::Import { step: old, .. }) = s.doc.feature(link.feature).filter(|f| f.component == comp).map(|f| &f.kind) else { - return Err(bad( - cmd, - format!("{cname}: its linked bodies (feature {}) are gone; break the link or insert the design again", link.feature), - )); + let (old, file, bytes) = match read_linked(s, comp, &link) { + Ok(read) => read, + Err(e) if go_on => { + failed.push(json!({"component": comp, "name": cname, "error": e})); + warnings.push(format!("{cname} keeps its bodies: {e}")); + continue; + } + Err(e) => return Err(bad(cmd, format!("{cname}: {e}"))), }; - let old = old.clone(); - link_refused(s.path.as_deref(), &link.path).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; - let file = resolve(s.path.as_deref(), &link.path); - let bytes = read_link(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; + // The link keeps what it read, so opening this design again knows whether the file + // changed while it was closed (#9739). + let read = DesignLink::file_digest(&bytes); + if link.file_sha256.as_deref() != Some(read.as_str()) + && let Some(kept) = s.doc_mut().links.get_mut(&comp) + { + kept.file_sha256 = Some(read); + } // A link that has not recorded the properties it inherited (made before they were) is read again. let kept_faces = s .doc @@ -567,7 +627,19 @@ fn update_links(s: &mut Session, p: &Value) -> Result { } continue; } - let (_, sf, faces, _, properties) = design_bodies(&file, &bytes).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; + let (_, sf, faces, _, properties) = match design_bodies(&file, &bytes, s.validation()) { + Ok(read) => read, + Err(e) if go_on => { + // It keeps its bodies, so it has not taken this file in yet. + if let Some(kept) = s.doc_mut().links.get_mut(&comp) { + kept.file_sha256.clone_from(&link.file_sha256); + } + failed.push(json!({"component": comp, "name": cname, "error": e.to_string()})); + warnings.push(format!("{cname} keeps its bodies: {e}")); + continue; + } + Err(e) => return Err(bad(cmd, format!("{cname}: {e}"))), + }; warnings.extend(sf.warnings.iter().cloned()); let same = matches!(&sf.kind, FeatureKind::Import { step, .. } if *step == old); let kept = s.doc.feature(link.feature).map(|f| &f.link_faces); @@ -605,6 +677,11 @@ fn update_links(s: &mut Session, p: &Value) -> Result { if changed { updated.push(cname) } else { unchanged.push(cname) } } solidcraft_doc::progress::item(None); + // None could be read: nothing to take back either. + if updated.is_empty() && unchanged.is_empty() && !failed.is_empty() { + let (name, why) = (failed[0]["name"].as_str().unwrap_or_default(), failed[0]["error"].as_str().unwrap_or_default()); + return Err(bad(cmd, format!("{name}: {why}"))); + } s.refresh(); if let Some(e) = s.doc.links.values().find_map(|l| s.model.result(l.feature).and_then(|r| r.error.clone())) { return Err(EngineError::Other(e)); @@ -614,7 +691,19 @@ fn update_links(s: &mut Session, p: &Value) -> Result { let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state()); warnings.extend(sol.errors.iter().chain(&sol.conflicts).map(|(_, name, why)| format!("joint {name}: {why}"))); } - Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings})) + Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings, "failed": failed})) +} + +/// `comp`'s linked design as it was last read (its bodies) and as its file is now, read before +/// anything in the design changes. +fn read_linked(s: &Session, comp: u64, link: &DesignLink) -> std::result::Result<(std::sync::Arc, PathBuf, Vec), String> { + let Some(FeatureKind::Import { step: old, .. }) = s.doc.feature(link.feature).filter(|f| f.component == comp).map(|f| &f.kind) else { + return Err(format!("its linked bodies (feature {}) are gone; break the link or insert the design again", link.feature)); + }; + link_refused(s.path.as_deref(), &link.path).map_err(|e| e.to_string())?; + let file = resolve(s.path.as_deref(), &link.path); + let bytes = read_link(&file, s.path.as_deref()).map_err(|e| e.to_string())?; + Ok((old.clone(), file, bytes)) } /// The joints and joint origins on occurrences of `comp` that name its linked faces by their @@ -640,8 +729,9 @@ fn relink(s: &mut Session, p: &Value) -> Result { } let given = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))?; let file = absolute(Path::new(given)); - if !solidcraft_io::is_design_container_path(&file) { - return Err(bad(cmd, "choose a saved .sc design")); + // Any design Insert Design takes: a .sc container (or a legacy one) or a plain JSON design. + if !solidcraft_io::is_design_path(given) { + return Err(bad(cmd, "choose a saved design (.sc or .json)")); } // A network or device path is judged from its text before the disk is asked anything. link_refused(s.path.as_deref(), given).map_err(|e| bad(cmd, e.to_string()))?; @@ -654,7 +744,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { } // Read/evaluate the candidate before changing anything. Session::execute owns the single // undo step and restores both the document and evaluated state on any later failure. - let (_, sf, faces, _, properties) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?; + let ((_, sf, faces, _, properties), read) = linked_bodies_read(&file, s.path.as_deref(), s.validation()).map_err(|e| bad(cmd, e.to_string()))?; let geometry_changed = match (s.doc.feature(link.feature).map(|f| &f.kind), &sf.kind) { (Some(FeatureKind::Import { step: old, .. }), FeatureKind::Import { step, .. }) => old != step, _ => true, @@ -677,7 +767,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { f.kind = sf.kind; f.link_faces = faces; } - s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), ..link.clone() }); + s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), file_sha256: Some(read), ..link.clone() }); s.refresh(); if let Some(error) = s.model.result(link.feature).and_then(|r| r.error.clone()) { return Err(bad(cmd, error)); @@ -717,8 +807,17 @@ fn list_links(s: &mut Session, _p: &Value) -> Result { // A refused path is not looked for at all: on Windows asking whether a file on // `\\host\share` exists already connects to the host. match link_refusal(s.path.as_deref(), &l.path) { - None => json!({"component": c, "name": name, "path": path, "file": file, - "found": solidcraft_io::vfs::design_path_is_file(&file, s.path.as_deref())}), + None => { + let found = solidcraft_io::vfs::design_path_is_file(&file, s.path.as_deref()); + // Whether the file is no longer what this design last read (#9739): `null` + // when it isn't found, or the link keeps no digest (made before they were). + let changed = l + .file_sha256 + .as_ref() + .filter(|_| found == Some(true)) + .and_then(|kept| file_sha256(Path::new(file.as_ref()), s.path.as_deref()).map(|now| now != *kept)); + json!({"component": c, "name": name, "path": path, "file": file, "found": found, "changed": changed}) + } Some(solidcraft_io::vfs::Remote::Network(host)) => json!({"component": c, "name": name, "path": path, "file": file, "found": null, "host": host, "reason": format!("on the network location \\\\{host}, which is not allowed")}), Some(solidcraft_io::vfs::Remote::Device) => json!({"component": c, "name": name, "path": path, "file": file, @@ -913,6 +1012,84 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// #9739: a link keeps what it read of its file, so an assembly opened again says which + /// linked designs changed while it was closed; Update Links takes the change and the record. + #[test] + fn a_link_says_its_file_changed_while_the_design_was_closed() { + let dir = std::env::temp_dir().join(format!("solidcraft-link-changed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (part, assembly) = (dir.join("p.sc"), dir.join("a.sc")); + save_box(&part, 10.0); + let mut a = Session::default(); + run(&mut a, "component.insert_design", json!({"path": part})); + run(&mut a, "file.save", json!({"path": assembly})); + let changed = |s: &mut Session| run(s, "component.links", json!({}))["links"][0]["changed"].clone(); + assert_eq!(changed(&mut a), json!(false)); + // The part is edited while the assembly is closed. + save_box(&part, 30.0); + let mut opened = Session::default(); + run(&mut opened, "doc.open", json!({"path": assembly})); + assert_eq!(changed(&mut opened), json!(true)); + assert!((volume(&mut opened) - 2000.0).abs() < 1e-6, "{}", volume(&mut opened)); + assert_eq!(run(&mut opened, "component.update_links", json!({}))["updated"], json!(["p"])); + assert_eq!(changed(&mut opened), json!(false)); + assert!((volume(&mut opened) - 6000.0).abs() < 1e-6, "{}", volume(&mut opened)); + // Saved, it opens up to date. + run(&mut opened, "file.save", json!({})); + let mut again = Session::default(); + run(&mut again, "doc.open", json!({"path": assembly})); + assert_eq!(changed(&mut again), json!(false)); + // A link made before the record says nothing; Update Links gives it one. + again.doc_mut().links.values_mut().for_each(|l| l.file_sha256 = None); + assert_eq!(changed(&mut again), Value::Null); + assert_eq!(run(&mut again, "component.update_links", json!({}))["unchanged"], json!(["p"])); + assert_eq!(changed(&mut again), json!(false)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #9743: a list of links is read in one step that goes on past a design it can't read. + #[test] + fn update_links_given_a_list_reads_them_in_one_step_past_a_design_it_cannot_read() { + let dir = std::env::temp_dir().join(format!("solidcraft-link-list-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (plate, block) = (dir.join("plate.solidcraft"), dir.join("block.solidcraft")); + save_box(&plate, 30.0); + save_box(&block, 10.0); + let mut a = Session::default(); + let first = run(&mut a, "component.insert_design", json!({"path": plate}))["component"].clone(); + let second = run(&mut a, "component.insert_design", json!({"path": plate, "translate": [50, 0, 0]}))["component"].clone(); + let third = run(&mut a, "component.insert_design", json!({"path": block, "translate": [100, 0, 0]}))["component"].clone(); + assert!((volume(&mut a) - 14000.0).abs() < 1e-6, "{}", volume(&mut a)); + // Two links to the same changed file come in together, and one Undo takes both back. + save_box(&plate, 45.0); + let r = run(&mut a, "component.update_links", json!({"components": [first, second]})); + assert_eq!((r["updated"].as_array().map(Vec::len), r["failed"].clone()), (Some(2), json!([])), "{r}"); + assert!((volume(&mut a) - 20000.0).abs() < 1e-6, "{}", volume(&mut a)); + run(&mut a, "edit.undo", json!({})); + assert!((volume(&mut a) - 14000.0).abs() < 1e-6, "{}", volume(&mut a)); + // A design it can't read keeps its bodies and is named; the others still come in. + std::fs::write(&block, b"not a design").unwrap(); + let r = run(&mut a, "component.update_links", json!({"components": [first, third]})); + assert_eq!(r["updated"].as_array().map(Vec::len), Some(1), "{r}"); + assert_eq!((r["failed"][0]["component"].clone(), r["failed"][0]["name"].clone()), (third.clone(), json!("block")), "{r}"); + assert!(r["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("block")))), "{r}"); + assert!((volume(&mut a) - 17000.0).abs() < 1e-6, "{}", volume(&mut a)); + // Not taken in, it still says its file changed (#9739). + let links = run(&mut a, "component.links", json!({})); + let block_link = links["links"].as_array().and_then(|l| l.iter().find(|l| l["component"] == third)).cloned(); + assert_eq!(block_link.map(|l| l["changed"].clone()), Some(json!(true)), "{links}"); + // None it can read: an error, and nothing to undo. + let err = a.execute("component.update_links", &json!({"components": [third]})).unwrap_err().to_string(); + assert!(err.contains("block"), "{err}"); + // Malformed lists are refused. + for bad in + [json!({"components": []}), json!({"components": 3}), json!({"components": [first], "component": first}), json!({"components": ["nope"]})] + { + assert!(a.execute("component.update_links", &bad).is_err(), "{bad}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn inserting_a_missing_file_or_bad_parameters_changes_nothing() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/component_move_features.rs b/crates/engine/src/cmd/component_move_features.rs index 50bf4ef34..3cddebc15 100644 --- a/crates/engine/src/cmd/component_move_features.rs +++ b/crates/engine/src/cmd/component_move_features.rs @@ -93,6 +93,15 @@ pub(super) fn move_features(s: &mut Session, p: &Value) -> Result { FeatureKind::Sketch { plane, .. } => { if let Some(anchor) = crate::cmd::sketch::face::anchor_mut(plane) { let moved_body = moved_bodies.contains(&anchor.target.body); + let author_delta = if authored_here { + let old = s.doc.feature(f.id).ok_or_else(|| bad(cmd, "attached sketch no longer exists"))?; + mat_mul(&to_dest, &s.doc.component_transform(old.component)) + } else { + solidcraft_doc::IDENTITY + }; + let source_delta = + if moved_body { mat_mul(&to_dest, &s.doc.component_transform(anchor.component)) } else { solidcraft_doc::IDENTITY }; + anchor.reframe_placement(&author_delta, &source_delta)?; rewrite(&anchor.target.body, &mut anchor.path, &mut anchor.author_path); if moved_body { anchor.component = dest; diff --git a/crates/engine/src/cmd/component_placing.rs b/crates/engine/src/cmd/component_placing.rs index 60b0628ec..01aeb03a2 100644 --- a/crates/engine/src/cmd/component_placing.rs +++ b/crates/engine/src/cmd/component_placing.rs @@ -21,7 +21,7 @@ pub(super) fn parent_path(p: &Value, cmd: &str) -> Result>> { /// is in the world, then moved by `translate` (in the world). The parent is placed by /// [`placement_of`]: in its other instances the copy sits in the same place within them. pub(super) fn in_place(s: &Session, path: &[u64], parent: u64, parent_path: Option<&[u64]>, translate: Vec3, cmd: &str) -> Result { - let doc = s.placed_document(); + let doc = s.design_document(); let component = path.last().and_then(|id| doc.occurrences.iter().find(|o| o.id == *id)).map(|o| o.component).ok_or_else(|| bad(cmd, "no placement"))?; let world = doc.path_transform(component, path).ok_or_else(|| bad(cmd, "that placement is gone"))?; diff --git a/crates/engine/src/cmd/component_properties.rs b/crates/engine/src/cmd/component_properties.rs index 5acb06e4c..20d34b011 100644 --- a/crates/engine/src/cmd/component_properties.rs +++ b/crates/engine/src/cmd/component_properties.rs @@ -1,10 +1,13 @@ //! Physical properties of an assembly placement, with original body material assignments. -use serde_json::{Value, json}; -use solidcraft_doc::{BomType, Document, Mat}; -use solidcraft_geom::inertia::{self, Tensor3}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet, HashSet}; +use serde_json::{Value, json}; +use solidcore_record::Vec3; +use solidcraft_doc::{BomType, Document, Mat}; +use solidcraft_geom::Aabb3; +use solidcraft_geom::inertia::{self, Tensor3}; + use crate::params::bad; use crate::{Result, Session}; @@ -34,19 +37,24 @@ fn linear(m: &Mat) -> Tensor3 { } fn placed_doc(s: &Session) -> Document { - let mut doc = (*s.doc).clone(); - for occurrence in &mut doc.occurrences { - if let Some(transform) = s.pending_moves.get(&occurrence.id) { - occurrence.transform = *transform; - } - } - doc + s.design_document().into_owned() } /// A property total must cover the entire assembly. The display traversal intentionally /// truncates hostile designs, so use an explicit error instead of accepting its prefix. pub(in crate::cmd) fn placements(doc: &Document, cmd: &str) -> Result, Mat)>> { - doc.placements_below(0, &[], solidcraft_doc::IDENTITY).map_err(|e| bad(cmd, e.to_string())) + subtree(doc, (0, Vec::new(), solidcraft_doc::IDENTITY), true, cmd) +} + +/// `root` and, with `descendants`, every placement under it, each with its world transform. +/// The occurrences are grouped by parent once: searching all of them at every placement made a +/// large assembly's traversal quadratic. +fn subtree(doc: &Document, root: (u64, Vec, Mat), descendants: bool, cmd: &str) -> Result, Mat)>> { + if !descendants { + return Ok(vec![root]); + } + let (component, path, world) = root; + doc.placements_below(component, &path, world).map_err(|e| bad(cmd, e.to_string())) } pub(super) fn component(s: &mut Session, p: &Value) -> Result { @@ -86,6 +94,95 @@ pub(super) fn occurrence(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The linear part of `m` is a rotation (no scale, shear or mirror), to rounding. +fn proper_rotation(m: &Mat) -> bool { + let column = |i: usize| m.get(i).map_or(Vec3::ZERO, |c| Vec3::new(c[0], c[1], c[2])); + let (x, y, z) = (column(0), column(1), column(2)); + m.iter().flatten().all(|v| v.is_finite()) + && [x, y, z].iter().all(|a| (a.dot(*a) - 1.0).abs() < 1e-9) + && x.dot(y).abs() < 1e-9 + && x.dot(z).abs() < 1e-9 + && y.dot(z).abs() < 1e-9 + && x.cross(y).dot(z) > 0.0 +} + +/// Every axis of `m` goes to an axis (a quarter turn, or none): a box turned so stays a box. +fn square_to_axes(m: &Mat) -> bool { + m.iter().take(3).all(|c| c.iter().take(3).filter(|v| v.abs() > 1e-12).count() == 1) +} + +/// The box around the corners of `b` placed by `m`. +fn placed_box(m: &Mat, b: &Aabb3) -> Aabb3 { + let mut out = Aabb3::EMPTY; + if b.is_empty() { + return out; + } + for i in 0..8 { + let pick = |bit: usize, lo: f64, hi: f64| if i & bit == 0 { lo } else { hi }; + out.add(solidcraft_doc::apply_point(m, Vec3::new(pick(1, b.min.x, b.max.x), pick(2, b.min.y, b.max.y), pick(4, b.min.z, b.max.z)))); + } + out +} + +/// A body's measurements where a placement puts it. +struct Placed { + volume: f64, + area: f64, + centroid: Vec3, + bbox: Aabb3, + closed: bool, + faces: usize, + edges: usize, + vertices: usize, +} + +/// `body` measured where `transform` places it. A rigid placement moves nothing but the centre +/// and the box: the body's own measurement (worked out once and shared by every placement of it, +/// [`solidcraft_doc::ModelBody::measure`]) is reused, where measuring each placed copy again took +/// three fine tessellations per copy and made Properties of a large assembly take minutes +/// (#8706). A placement that turns the body off the axes takes its box from the body's mesh +/// placed there (shared with the display). Any other placement (scaled or mirrored) is measured +/// as placed, as before. +fn measure_placed(body: &solidcraft_doc::ModelBody, transform: Mat) -> Result { + if proper_rotation(&transform) { + let m = body.measure()?; + let bbox = if square_to_axes(&transform) { + placed_box(&transform, &m.bbox) + } else { + let mesh = body.mesh(); + let mut b = Aabb3::EMPTY; + for p in &mesh.positions { + b.add(solidcraft_doc::apply_point(&transform, *p)); + } + if b.is_empty() { placed_box(&transform, &m.bbox) } else { b } + }; + return Ok(Placed { + volume: m.volume, + area: m.area, + centroid: solidcraft_doc::apply_point(&transform, m.centroid), + bbox, + closed: crate::cmd::inspect::encloses_volume(&body.body), + faces: m.merged.faces, + edges: m.merged.edges, + vertices: m.merged.vertices, + }); + } + #[cfg(test)] + work::count(|w| w.placed_measures += 1); + let placed = solidcraft_kernel::transform_matrix(&body.body, transform)?; + let m = solidcraft_kernel::measure(&placed)?; + Ok(Placed { + volume: m.volume, + area: m.area, + centroid: m.centroid, + bbox: m.bbox, + closed: crate::cmd::inspect::encloses_volume(&placed), + faces: m.merged.faces, + edges: m.merged.edges, + vertices: m.merged.vertices, + }) +} + fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, about: Option, cmd: &str) -> Result { let state = s.model.state(); let mut bodies = Vec::new(); @@ -96,31 +193,41 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, let mut placement_count = 0; let mut skipped = 0; let selected_placements = if selected.is_empty() { - if descendants { placements(doc, cmd)? } else { vec![(0, Vec::new(), solidcraft_doc::IDENTITY)] } + subtree(doc, (0, Vec::new(), solidcraft_doc::IDENTITY), descendants, cmd)? } else { - let placement = s.occurrence_placement(selected).map_err(|e| bad(cmd, e.to_string()))?; - if descendants { - doc.placements_below(placement.component, selected, placement.world).map_err(|e| bad(cmd, e.to_string()))? - } else { - vec![(placement.component, selected.to_vec(), placement.world)] - } + let placement = s.occurrence_placement_with(selected, &s.uncaptured_moves()).map_err(|e| bad(cmd, e.to_string()))?; + subtree(doc, (placement.component, selected.to_vec(), placement.world), descendants, cmd)? }; // As in the bill of materials, a placement that counts as a reference adds nothing, nor does // anything inside it; the one measured counts whatever its type. let reference: HashSet = doc.occurrences.iter().zip(doc.occurrence_bom_types()).filter(|(_, t)| *t == BomType::Reference).map(|(o, _)| o.id).collect(); + // Each component's bodies (with their index in the model), the timeline looked up once rather + // than for every body at every placement. + let mut by_component: std::collections::HashMap> = std::collections::HashMap::new(); + for (index, (body, component)) in state.bodies.iter().zip(doc.model_body_components(&state)).enumerate() { + by_component.entry(component).or_default().push((index, body)); + } // How each closed body's volume spreads about its centre of mass (#8095): one tessellation // however often it is placed, which each placement then turns. let components: BTreeSet = selected_placements.iter().map(|(component, _, _)| *component).collect(); - let spread_bodies: Vec = (0..state.bodies.len()) - .filter(|&i| { - state.bodies.get(i).is_some_and(|b| components.contains(&doc.model_body_component(b)) && crate::cmd::inspect::encloses_volume(&b.body)) - }) + let spread_bodies: Vec = components + .iter() + .filter_map(|c| by_component.get(c)) + .flatten() + .filter(|(_, b)| crate::cmd::inspect::encloses_volume(&b.body)) + .map(|(i, _)| *i) .collect(); + #[cfg(test)] + work::count(|w| w.spreads += spread_bodies.len()); let spreads = solidcraft_kernel::map_on_threads(&spread_bodies, 16, |&i| { state.bodies.get(i).and_then(|b| solidcraft_io::mass_properties(&b.body).ok().flatten()).and_then(|m| m.gyration()) }); let spread: BTreeMap = spread_bodies.into_iter().zip(spreads).filter_map(|(i, g)| Some((i, g.flatten()?))).collect(); + // A window waiting for the result (the Properties window) sees how far it is and can stop it. + let watch = solidcraft_kernel::watch::current(); + let total_bodies: usize = selected_placements.iter().map(|(c, _, _)| by_component.get(c).map_or(0, Vec::len)).sum(); + let mut done = 0; // Closed bodies' (mass, centre of mass, inertia about it), all in world axes. let mut parts: Vec<(f64, Vec3, Option)> = Vec::new(); for (component, path, transform) in selected_placements { @@ -128,16 +235,22 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, continue; } placement_count += 1; - for (index, body) in state.bodies.iter().enumerate().filter(|(_, b)| doc.model_body_component(b) == component) { + for &(index, body) in by_component.get(&component).into_iter().flatten() { + if let Some(w) = &watch { + if w.cancelled() { + return Err(bad(cmd, "cancelled")); + } + w.progress("measuring", done, total_bodies); + } + done += 1; let transform: Mat = doc.model_body_offset(body).map(|offset| solidcraft_doc::mat_mul(&transform, offset)).unwrap_or(transform); - let placed = solidcraft_kernel::transform_matrix(&body.body, transform)?; - let measured = solidcraft_kernel::measure(&placed)?; + let measured = measure_placed(body, transform)?; // The volume the bill of materials weighs too, measured once for the model; the area, // the centre, the box and the counts are the placed body's. let body_volume = body.volume().map_or(measured.volume, |v| v * solidcraft_doc::mat_volume_scale(&transform)); let density = doc.density(&body.name); let body_mass = body_volume * density / 1000.0; - let closed = crate::cmd::inspect::encloses_volume(&placed); + let closed = measured.closed; // The mesh's spread with the exact mass, so the tensor agrees with the mass shown. let body_inertia = spread .get(&index) @@ -154,9 +267,9 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, } area += measured.area; bounds = bounds.union(&measured.bbox); - faces += measured.merged.faces; - edges += measured.merged.edges; - vertices += measured.merged.vertices; + faces += measured.faces; + edges += measured.edges; + vertices += measured.vertices; bodies.push(json!({"name": body.name, "component": component, "path": path, "material": doc.body_material(&body.name), "closed": closed, "density_g_cm3": closed.then_some(density), @@ -166,6 +279,9 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, "bbox": {"min": measured.bbox.min, "max": measured.bbox.max}})); } } + if let Some(w) = &watch { + w.progress("measuring", done, total_bodies); + } if !(volume.is_finite() && area.is_finite() && mass.is_finite() && moment.is_finite()) { return Err(bad(cmd, "physical properties exceed supported numeric range")); } @@ -198,6 +314,46 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, Ok(out) } +/// The tessellating work a properties command did on this thread, for tests: placed copies +/// measured afresh (transformed, then tessellated) and bodies whose inertia spread was +/// tessellated. Counted where the work is asked for, on the command's own thread. +#[cfg(test)] +pub(super) mod work { + use std::cell::Cell; + + #[derive(Clone, Copy, Debug, Default, PartialEq)] + pub struct Work { + pub placed_measures: usize, + pub spreads: usize, + } + + thread_local! { + static WORK: Cell = const { Cell::new(Work { placed_measures: 0, spreads: 0 }) }; + } + + pub(super) fn count(f: impl FnOnce(&mut Work)) { + WORK.with(|w| { + let mut work = w.get(); + f(&mut work); + w.set(work); + }); + } + + /// `f`'s result and the work it did. + pub fn capture(f: impl FnOnce() -> T) -> (T, Work) { + let before = WORK.with(Cell::get); + let out = f(); + let after = WORK.with(Cell::get); + ( + out, + Work { + placed_measures: after.placed_measures.saturating_sub(before.placed_measures), + spreads: after.spreads.saturating_sub(before.spreads), + }, + ) + } +} + #[cfg(test)] #[path = "component_properties_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/component_properties_tests.rs b/crates/engine/src/cmd/component_properties_tests.rs index ff45ecb20..dcdf409c8 100644 --- a/crates/engine/src/cmd/component_properties_tests.rs +++ b/crates/engine/src/cmd/component_properties_tests.rs @@ -1,5 +1,6 @@ use crate::Session; use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, cmd: &str, params: Value) -> Value { s.execute(cmd, ¶ms).unwrap() @@ -500,3 +501,82 @@ fn configurations_switch_to_a_user_defined_material() { run(&mut s, "material.delete", json!({"material": "Black Walnut", "replace": "Default"})); assert!(!s.doc.materials.contains_key("Slat")); } + +/// #8706: Properties of a large assembly took minutes because every placed copy of a body was +/// transformed and measured again (three fine tessellations each). Every placement of a body now +/// reuses one measurement of it: 41 placements measure no placed copy afresh and tessellate +/// each distinct body's inertia spread (#8095) once, exactly as one placement does, and the +/// answer is the same when measured again. +#[test] +fn repeated_placements_reuse_one_measurement_of_their_body() { + let mut s = Session::default(); + let (component, _, _) = box_in(&mut s, "Block"); + run(&mut s, "solid.cylinder", json!({"diameter": 4, "height": 30})); + for i in 1..40 { + run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20 * i, 0, 0]})); + } + let turned = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [0, 50, 0]})); + run(&mut s, "occurrence.move", json!({"occurrence": turned["occurrence"], "translate": [0, 0, 0], "axis": [1, 1, 1], "angle": "30 deg"})); + let first = run(&mut s, "component.properties", json!({"component": "root"})); + assert_eq!(first["body_count"], 82, "{first}"); + let (again, all) = super::work::capture(|| run(&mut s, "component.properties", json!({"component": "root"}))); + assert_eq!(first, again); + let (block, one) = super::work::capture(|| run(&mut s, "occurrence.properties", json!({"occurrence": turned["occurrence"]}))); + // Before, every placed copy was transformed and tessellated afresh (82 here); now no copy + // is, and the work is the same for 41 placements as for one: one spread per distinct body. + let per_body = super::work::Work { placed_measures: 0, spreads: 2 }; + assert_eq!(all, per_body, "41 placements"); + assert_eq!(one, per_body, "one placement"); + close(&first["total"]["volume_mm3"], 41.0 * block["total"]["volume_mm3"].as_f64().unwrap()); +} + +/// #8706: a body measured where a rigid placement puts it, from its own measurement, matches its +/// placed copy measured afresh: volume, area, centre and counts, and the box (to the chord of +/// the meshes it is taken from) also when the placement turns it off the axes. +#[test] +fn a_placed_body_measures_as_its_placed_copy() { + use solidcore_record::Vec3; + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"diameter": 4, "height": 30})); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 5})); + let state = s.model.state(); + let placements = [ + solidcraft_doc::IDENTITY, + solidcraft_doc::rigid(Vec3::new(5.0, -3.0, 7.0), Vec3::ZERO, Vec3::Z, std::f64::consts::FRAC_PI_2), + solidcraft_doc::rigid(Vec3::new(100.0, 0.0, 0.0), Vec3::new(1.0, 2.0, 3.0), Vec3::new(1.0, 1.0, 1.0), 0.5), + ]; + for body in &state.bodies { + for m in placements { + let fast = super::measure_placed(body, m).unwrap(); + let placed = solidcraft_kernel::transform_matrix(&body.body, m).unwrap(); + let slow = solidcraft_kernel::measure(&placed).unwrap(); + let near = |a: f64, b: f64, tol: f64| assert!((a - b).abs() <= tol * b.abs().max(1.0), "{} {a} != {b}", body.name); + near(fast.volume, slow.volume, 1e-4); + near(fast.area, slow.area, 1e-4); + assert!((fast.centroid - slow.centroid).len() < 1e-3, "{} centre {:?} != {:?}", body.name, fast.centroid, slow.centroid); + let box_near = (fast.bbox.min - slow.bbox.min).len() < 0.05 && (fast.bbox.max - slow.bbox.max).len() < 0.05; + assert!(box_near, "{} box {:?} != {:?}", body.name, fast.bbox, slow.bbox); + assert_eq!((fast.faces, fast.edges, fast.vertices), (slow.merged.faces, slow.merged.edges, slow.merged.vertices)); + assert_eq!(fast.closed, crate::cmd::inspect::encloses_volume(&placed)); + } + } +} + +/// #8706: a window waiting for the properties sees how many bodies are measured and can stop the +/// measuring part way. +#[test] +fn a_watcher_sees_the_bodies_measured_and_can_stop_them() { + use std::sync::Arc; + let mut s = Session::default(); + let (component, _, _) = box_in(&mut s, "Block"); + for i in 1..4 { + run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20 * i, 0, 0]})); + } + let progress = Arc::new(solidcraft_doc::progress::Progress::default()); + let r = solidcraft_doc::progress::watch(progress.clone(), || s.execute("component.properties", &json!({"component": "root"}))); + assert_eq!(r.unwrap()["body_count"], 4); + assert_eq!(progress.work(), Some(("measuring", 4, 4))); + progress.cancel(); + let stopped = solidcraft_doc::progress::watch(progress, || s.execute("component.properties", &json!({"component": "root"}))); + assert!(stopped.unwrap_err().to_string().contains("cancelled")); +} diff --git a/crates/engine/src/cmd/component_relink_tests.rs b/crates/engine/src/cmd/component_relink_tests.rs index 16c9b049a..672279a87 100644 --- a/crates/engine/src/cmd/component_relink_tests.rs +++ b/crates/engine/src/cmd/component_relink_tests.rs @@ -161,6 +161,90 @@ fn reused_design_insertion_is_free_even_before_a_link_exists() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn reused_design_insertion_uses_the_requested_position_and_survives_undo_and_reopen() { + let dir = folder("reuse-position"); + let file = dir.join("part.sc"); + part(&file, 30); + for first_reuses in [false, true] { + let mut s = Session::default(); + let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0], "reuse": first_reuses})); + let before = s.doc.to_json(); + let undo = s.undo.len(); + let second = run(&mut s, "component.insert_design", json!({"path": file, "translate": [40, 5, 7], "reuse": true})); + assert_eq!(first["component"], second["component"]); + assert_eq!(s.doc.links.len(), 1); + assert_eq!(s.doc.features.len(), 1); + assert_eq!(s.undo.len(), undo + 1); + let occurrence = second["occurrence"].as_u64().unwrap(); + assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + assert_linked_bounds(&mut s, first["occurrence"].as_u64().unwrap(), [20.0, 0.0, 0.0], [30.0, 20.0, 30.0]); + assert!(!s.doc.occurrences.iter().find(|o| o.id == occurrence).unwrap().grounded); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + let assembly = dir.join("assembly.sc"); + run(&mut s, "file.save", json!({"path": assembly})); + let mut cold = Session::default(); + run(&mut cold, "doc.open", json!({"path": assembly})); + assert_linked_bounds(&mut cold, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + let at_origin = run(&mut cold, "component.insert_design", json!({"path": file, "reuse": true}))["occurrence"].as_u64().unwrap(); + assert_linked_bounds(&mut cold, at_origin, [0.0, 0.0, 0.0], [10.0, 20.0, 30.0]); + } + let _ = std::fs::remove_dir_all(dir); +} + +fn assert_linked_bounds(s: &mut Session, occurrence: u64, min: [f64; 3], max: [f64; 3]) { + let p = run(s, "occurrence.properties", json!({"occurrence": occurrence})); + assert_eq!(p["body_count"], 1); + assert!((p["total"]["volume_mm3"].as_f64().unwrap() - 6000.0).abs() < 1e-6, "{p}"); + for (key, expected) in [("min", min), ("max", max)] { + for (axis, expected) in expected.into_iter().enumerate() { + assert!((p["total"]["bbox"][key][axis].as_f64().unwrap() - expected).abs() < 1e-6, "{key}[{axis}] != {expected}: {p}"); + } + } +} + +#[test] +fn reused_design_insertion_ignores_existing_moves_and_uses_the_destination_parent() { + let dir = folder("reuse-parent"); + let file = dir.join("part.sc"); + part(&file, 30); + for capture in [false, true] { + let mut s = Session::default(); + let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0]})); + run( + &mut s, + "occurrence.move", + json!({"occurrence": first["occurrence"], "translate": [0, 10, 0], "axis": [0, 0, 1], "angle": "90 deg", "capture": capture, "move_grounded": true}), + ); + let original = s.doc.occurrences.clone(); + let pending = s.pending_moves.clone(); + let parent = run(&mut s, "component.create", json!({"name": "Parent", "activate": false})); + run(&mut s, "occurrence.move", json!({"occurrence": parent["occurrence"], "translate": [100, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"})); + for explicit_parent in [true, false] { + let mut params = json!({"path": file, "translate": [40, 5, 7], "reuse": true}); + if explicit_parent { + params["parent"] = json!("Parent"); + } else { + run(&mut s, "component.activate", json!({"component": parent["component"]})); + } + let inserted = run(&mut s, "component.insert_design", params); + assert_eq!(inserted["component"], first["component"]); + assert_linked_bounds(&mut s, inserted["occurrence"].as_u64().unwrap(), [75.0, 40.0, 7.0], [95.0, 50.0, 37.0]); + assert_eq!(s.doc.occurrences.first(), original.first()); + assert_eq!(s.pending_moves, pending); + } + let before = s.doc.to_json(); + for parent in [json!("missing"), first["component"].clone()] { + assert!(s.execute("component.insert_design", &json!({"path": file, "parent": parent, "reuse": true})).is_err()); + assert_eq!(s.doc.to_json(), before); + } + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn linked_design_properties_update_density_without_geometry_and_keep_edited_cards() { let dir = folder("properties-density"); @@ -194,8 +278,8 @@ fn linked_design_properties_update_density_without_geometry_and_keep_edited_card #[test] fn linked_design_properties_keep_opaque_pbr_and_face_color_after_reload() { + use solidcore_record::Vec3; use solidcraft_doc::appearance::{FaceLook, Look}; - use solidcraft_geom::Vec3; let dir = folder("properties-optics"); let file = dir.join("source.solidcraft"); let mut part = properties_part(&file, "Steel", None, [12, 34, 56]); @@ -237,8 +321,8 @@ fn linked_design_properties_keep_opaque_pbr_and_face_color_after_reload() { #[test] fn linked_face_overrides_update_independently_and_preserve_local_edits_and_removals() { + use solidcore_record::Vec3; use solidcraft_doc::appearance::{FaceLook, Look}; - use solidcraft_geom::Vec3; let dir = folder("properties-faces"); let file = dir.join("source.solidcraft"); let mut part = properties_part(&file, "Steel", None, [12, 34, 56]); @@ -332,7 +416,7 @@ fn linked_face_removal_without_a_body_look_does_not_reveal_baked_source_paint() part.doc_mut().appearances.bodies.clear(); part.doc_mut().appearances.faces.push(FaceLook { body: "Cube".into(), - point: solidcraft_geom::Vec3::new(5.0, 5.0, 10.0), + point: solidcore_record::Vec3::new(5.0, 5.0, 10.0), look: Look::custom([190, 20, 30], 0.65), name: None, strict_name: false, @@ -360,7 +444,7 @@ fn unchanged_linked_face_overrides_do_not_reorder_assignments_or_report_updates( let mut part = properties_part(&file, "Steel", None, [12, 34, 56]); part.doc_mut().appearances.faces.push(FaceLook { body: "Cube".into(), - point: solidcraft_geom::Vec3::new(5.0, 5.0, 10.0), + point: solidcore_record::Vec3::new(5.0, 5.0, 10.0), look: Look::custom([190, 20, 30], 0.65), name: None, strict_name: false, @@ -509,6 +593,24 @@ fn relink_rejects_bad_sources_and_targets_without_touching_the_design_or_undo() let _ = std::fs::remove_dir_all(dir); } +/// Relink takes any design Insert Design takes: a plain JSON design too, and back to a container. +#[test] +fn relink_takes_a_json_design_as_insert_design_does() { + let dir = folder("json"); + let (container, plain) = (dir.join("source.sc"), dir.join("source.json")); + part(&container, 30); + part(&plain, 45); + assert!(!solidcraft_io::is_design_container(&std::fs::read(&plain).unwrap()), "file.save writes a .json design as plain JSON"); + let mut s = Session::default(); + let component = run(&mut s, "component.insert_design", json!({"path": container}))["component"].as_u64().unwrap(); + let to_json = run(&mut s, "component.relink", json!({"component": component, "path": plain})); + assert_eq!(to_json["geometry_changed"], true); + assert!((volume(&mut s) - 9000.0).abs() < 1e-5); + run(&mut s, "component.relink", json!({"component": component, "path": container})); + assert!((volume(&mut s) - 6000.0).abs() < 1e-5); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn relink_keeps_joint_definitions_and_reports_solver_diagnostics() { let dir = folder("joints"); @@ -542,7 +644,7 @@ fn relink_keeps_joint_definitions_and_reports_solver_diagnostics() { // requiring relink to guess which face of a different design was intended. let joint = s.doc_mut().assembly.joints.first_mut().unwrap(); joint.b.snap = - solidcraft_doc::joints::Snap::FaceCenter { pick: solidcraft_geom::Vec3::ZERO, face: Some("no-such-linked-face".to_string()), x: None }; + solidcraft_doc::joints::Snap::FaceCenter { pick: solidcore_record::Vec3::ZERO, face: Some("no-such-linked-face".to_string()), x: None }; s.refresh(); let result = run(&mut s, "component.relink", json!({"component": component, "path": replacement})); assert!(result["joint_errors"].as_array().unwrap().iter().any(|e| e["name"] == "Seat")); diff --git a/crates/engine/src/cmd/component_reparent.rs b/crates/engine/src/cmd/component_reparent.rs index 35edd2d0b..159a09058 100644 --- a/crates/engine/src/cmd/component_reparent.rs +++ b/crates/engine/src/cmd/component_reparent.rs @@ -3,8 +3,8 @@ //! once is one definition: what goes in it goes in every instance, placed by the one instance //! named (`parent_path`, else the active placement) and in the same place in the others. Paths //! through the placement change: the session's paths (selection, active and hidden placements, -//! hidden folders) follow it, and a move that would leave a feature failing that worked before -//! (a face attachment found through the old path) is refused. +//! hidden folders) and the design's face attachments found through it follow it, and a move that +//! would still leave a feature failing that worked before is refused. use super::placing::{parent_path, placement_of}; use super::*; @@ -35,7 +35,7 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result { // From the placement named (`path`), into the parent's placement named (`parent_path`). let moved = occurrence_path(s, p, id, cmd)?; let to_given = parent_path(p, cmd)?; - let doc = s.placed_document(); + let doc = s.design_document(); let (from_path, from_frame) = placement_of(s, &doc, o.parent, moved.split_last().map(|(_, up)| up), "path", cmd)?; let (to_path, to_frame) = placement_of(s, &doc, to, to_given.as_deref(), "parent_path", cmd)?; let local = doc.occurrences.iter().find(|x| x.id == id).map(|x| x.transform).unwrap_or(o.transform); @@ -52,10 +52,12 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result { let mut scratch = s.scratch(); // Pending moves along both parents and of the placement itself are kept: its new transform // was worked out from them. + // The exploded view is shown only: an ancestor it moves keeps its placement, and stays shown. + let uncaptured = s.uncaptured_moves().into_owned(); for ancestor in from_path.iter().chain(&to_path) { - if let Some(pending) = scratch.pending_moves.remove(ancestor) - && let Some(x) = scratch.doc_mut().occurrences.iter_mut().find(|x| x.id == *ancestor) - { + let Some(pending) = uncaptured.get(ancestor).copied() else { continue }; + scratch.pending_moves.remove(ancestor); + if let Some(x) = scratch.doc_mut().occurrences.iter_mut().find(|x| x.id == *ancestor) { x.transform = pending; } } @@ -71,6 +73,37 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result { { c.parent = to; } + // Face attachments found through it follow it too (#11063): a sketch on a face of a body + // inside it kept the old path, which no longer starts at the design, and the move was refused. + // A path through it by way of any placement of its old parent (a parent placed more than once + // is one definition) now runs through its one new place. A path that would grow past the 64 + // placements a design keeps is refused here rather than saved where it can't be read back. + let mut too_deep = false; + let mut rebase = |path: &mut Vec| { + if let Some(at) = path.iter().position(|x| *x == id) { + let moved: Vec = new_path.iter().chain(&path[at + 1..]).copied().collect(); + too_deep |= moved.len() > 64; + *path = moved; + } + }; + for f in &mut scratch.doc_mut().features { + match &mut f.kind { + FeatureKind::Emboss { face: Some(face), .. } => { + rebase(&mut face.path); + rebase(&mut face.author_path); + } + FeatureKind::Sketch { plane, .. } | FeatureKind::ConstructionPlane { plane } => { + if let Some(anchor) = crate::cmd::sketch::face::anchor_mut(plane) { + rebase(&mut anchor.path); + rebase(&mut anchor.author_path); + } + } + _ => {} + } + } + if too_deep { + return Err(bad(cmd, format!("moving {} would nest a face attachment more than 64 placements deep", o.name))); + } // The paths through it follow it before the model is worked out again: that drops a selected // or active placement whose path no longer leads anywhere. for sel in &mut scratch.selection { diff --git a/crates/engine/src/cmd/component_sketches_to_parts.rs b/crates/engine/src/cmd/component_sketches_to_parts.rs new file mode 100644 index 000000000..f2e2dae2d --- /dev/null +++ b/crates/engine/src/cmd/component_sketches_to_parts.rs @@ -0,0 +1,140 @@ +//! Sketches and the component that owns them: a face-attached sketch moved to another component +//! keeps its place on the face, and `component.move_sketches.to_parts` (#10218) moves sketches +//! to the part whose face they are drawn on. +use serde_json::{Value, json}; +use solidcore_record::Plane; +use solidcraft_doc::{EmbossFace, FeatureKind, PlaneRef, apply_point, apply_vector, mat_inverse, mat_mul}; +use solidcraft_geom::prelude::*; + +use crate::params::{bad, name_or_id_list}; +use crate::schema::component::{MoveSketchesToPartsResult, SketchKeptInPlace, SketchMovedToPart}; +use crate::{Result, Session}; + +/// The face a sketch's plane is built on, beneath an offset, flip or angle. +fn face_mut(mut plane: &mut PlaneRef) -> Option<&mut PlaneRef> { + for _ in 0..64 { + match plane { + PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::ThroughPoint { base, .. } => { + plane = base + } + PlaneRef::Face { .. } => return Some(plane), + _ => return None, + } + } + None +} + +/// Make the face-attached sketch `id`, about to belong to `to`, authored in a placement of `to`: +/// the placement its face is in when `to` owns the face, the design for the design, else `to`'s +/// first. The picked point, the repair plane and an angle's axis are carried into that placement, +/// so the sketch stays where it is on the face. Other sketches keep their own coordinates. +pub(super) fn reauthor(s: &mut Session, id: u64, to: u64, cmd: &str) -> Result<()> { + let Some(feature) = s.doc.feature(id) else { return Ok(()) }; + let from = feature.component; + let FeatureKind::Sketch { plane, .. } = &feature.kind else { return Ok(()) }; + let Some(anchor) = solidcraft_doc::face_anchor::plane_face_anchor(plane) else { return Ok(()) }; + if from == to { + return Ok(()); + } + let doc = s.placed_document(); + let path = if to == anchor.component { + anchor.path.clone() + } else if to == 0 { + Vec::new() + } else { + doc.first_path(to) + }; + let new_frame = EmbossFace::component_frame(&doc, to, &path)?; + let inverse = mat_inverse(&new_frame).ok_or_else(|| bad(cmd, "the component's placement can't be inverted"))?; + // A sketch whose old placement no longer resolves only gets the new one: its face anchor + // places it, and the picked point and repair plane are a guide. + let relative = anchor.author_frame(&doc, from).ok().map(|old| mat_mul(&inverse, &old)); + let Some(feature) = s.doc_mut().feature_mut(id) else { return Ok(()) }; + let FeatureKind::Sketch { plane, .. } = &mut feature.kind else { return Ok(()) }; + if let (Some(relative), PlaneRef::AtAngle { axis_origin, axis_dir, .. }) = (relative, &mut *plane) { + *axis_origin = apply_point(&relative, *axis_origin); + *axis_dir = apply_vector(&relative, *axis_dir); + } + let Some(PlaneRef::Face { plane: picked, at, anchor: Some(anchor), .. }) = face_mut(plane) else { return Ok(()) }; + anchor.author_path = path; + if let Some(relative) = relative { + *at = apply_point(&relative, *at); + if let Some(moved) = Plane::new(apply_point(&relative, picked.origin), apply_vector(&relative, picked.x), apply_vector(&relative, picked.y)) { + *picked = moved; + } + } + Ok(()) +} + +/// Why a sketch stays where it is (a code and its text), or the component whose face it is on. +fn part_of(s: &Session, owner: u64, plane: &PlaneRef) -> std::result::Result { + let mut base = plane; + for _ in 0..64 { + match base { + PlaneRef::Offset { base: inner, .. } + | PlaneRef::Flipped { base: inner, .. } + | PlaneRef::AtAngle { base: inner, .. } + | PlaneRef::ThroughPoint { base: inner, .. } => base = inner, + _ => break, + } + } + let PlaneRef::Face { anchor, .. } = base else { return Err(("not_on_face", "not on a face")) }; + let Some(anchor) = anchor else { + return Err(("no_exact_attachment", "its face has no exact attachment (a sheet metal panel, or picked before exact attachments)")); + }; + if anchor.component == 0 { + return Err(("design_body", "on a body of the design itself, not of a part")); + } + if s.doc.components.iter().all(|component| component.id != anchor.component) { + return Err(("part_missing", "its face's part is no longer in the design")); + } + if anchor.component == owner { + return Err(("already_in_part", "already in its part")); + } + Ok(anchor.component) +} + +/// `component.move_sketches.to_parts`: each sketch given (every sketch when none are) whose plane +/// is a face of a part's body goes to that part, as `component.move_sketches` moves it. One undo +/// step; the reply lists what moved and what stayed, and why. +pub(super) fn to_parts(s: &mut Session, p: &Value) -> Result { + let cmd = "component.move_sketches.to_parts"; + let ids: Vec = if p.get("sketches").is_some() { + let keys = name_or_id_list(cmd, p, "sketches")?; + let mut ids = Vec::with_capacity(keys.len().min(10_000)); + for key in &keys { + match s.doc.find_feature(key) { + Some(f) if matches!(f.kind, FeatureKind::Sketch { .. }) => { + if !ids.contains(&f.id) { + ids.push(f.id); + } + } + _ => return Err(bad(cmd, format!("no sketch `{key}`"))), + } + } + ids + } else { + s.doc.features.iter().filter(|f| matches!(f.kind, FeatureKind::Sketch { .. })).map(|f| f.id).collect() + }; + let mut result = MoveSketchesToPartsResult::default(); + let mut moves = Vec::new(); + for id in ids { + let Some(f) = s.doc.feature(id) else { continue }; + let FeatureKind::Sketch { plane, .. } = &f.kind else { continue }; + match part_of(s, f.component, plane) { + Ok(component) => { + let part = s.doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default(); + result.sketches.push(SketchMovedToPart { sketch: id, name: f.name.clone(), component, part }); + moves.push((id, component)); + } + Err((code, reason)) => { + result.kept.push(SketchKeptInPlace { sketch: id, name: f.name.clone(), code: code.to_string(), reason: reason.to_string() }) + } + } + } + for (id, component) in moves { + super::move_sketches(s, &json!({"sketches": [id.to_string()], "component": component}))?; + } + (result.moved, result.stayed) = (result.sketches.len(), result.kept.len()); + serde_json::to_value(result).map_err(|e| bad(cmd, e.to_string())) +} diff --git a/crates/engine/src/cmd/component_transfer.rs b/crates/engine/src/cmd/component_transfer.rs index 9c7724a24..8d742cd05 100644 --- a/crates/engine/src/cmd/component_transfer.rs +++ b/crates/engine/src/cmd/component_transfer.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet}; type UniqueFrames = BTreeMap, Mat)>>; fn unique_frames(s: &Session, cmd: &str) -> Result { - let doc = s.placed_document(); + let doc = s.design_document(); let mut children = BTreeMap::>::new(); for occurrence in &doc.occurrences { children.entry(occurrence.parent).or_default().push(occurrence); @@ -54,7 +54,7 @@ fn transfer(s: &mut Session, name: &str, to: u64, frames: &UniqueFrames, cmd: &s let state = s.model.state(); let body = state.body(name).ok_or_else(|| bad(cmd, "body is missing"))?; let from = s.doc.model_body_component(body); - let doc = s.placed_document(); + let doc = s.design_document(); let unique = |component| { frames.get(&component).and_then(Option::as_ref).ok_or_else(|| { bad(cmd, "body transfer requires one source and destination placement; shared instances cannot preserve a unique world pose") @@ -78,7 +78,9 @@ fn transfer(s: &mut Session, name: &str, to: u64, frames: &UniqueFrames, cmd: &s } let inherited = (!s.doc.appearances.bodies.contains_key(name)).then(|| s.doc.appearances.components.get(&from).cloned()).flatten(); let paths: BTreeSet = source.0.iter().chain(&destination.0).copied().collect(); - let captures: Vec<_> = paths.into_iter().filter_map(|id| s.pending_moves.get(&id).map(|transform| (id, *transform))).collect(); + let uncaptured = s.uncaptured_moves(); + let captures: Vec<_> = paths.into_iter().filter_map(|id| uncaptured.get(&id).map(|transform| (id, *transform))).collect(); + drop(uncaptured); if captures.iter().any(|(_, transform)| !solidcraft_doc::valid_transfer_matrix(transform)) { return Err(bad(cmd, "pending transfer position is not a supported rigid transform")); } @@ -164,13 +166,13 @@ fn move_at_boundary(s: &mut Session, p: &Value, allow_boundary: bool) -> Result< // component placed more than once gets the bodies in every instance, placed by that one. let given = path_param(p, "component_path", cmd)?; if given.is_some() || frames.get(&to).is_some_and(Option::is_none) { - let placed = super::placing::placement_of(&scratch, &scratch.placed_document(), to, given.as_deref(), "component_path", cmd)?; + let placed = super::placing::placement_of(&scratch, &scratch.design_document(), to, given.as_deref(), "component_path", cmd)?; frames.insert(to, Some(placed)); } // The bodies move from the placement named (`from_path`: one of several where their component // is placed), as that placement shows them. if let Some(path) = path_param(p, "from_path", cmd)? { - let placed = scratch.placed_document(); + let placed = scratch.design_document(); let component = path .last() .and_then(|id| placed.occurrences.iter().find(|o| o.id == *id)) diff --git a/crates/engine/src/cmd/component_transfer_tests.rs b/crates/engine/src/cmd/component_transfer_tests.rs index 86df8a7b0..03cff0885 100644 --- a/crates/engine/src/cmd/component_transfer_tests.rs +++ b/crates/engine/src/cmd/component_transfer_tests.rs @@ -24,10 +24,10 @@ fn recorded_assignment_preserves_sample_joined_material_and_timeline() { let index = s.doc.feature_index(feature).unwrap(); s.doc_mut().marker = Some(index); s.refresh(); - assert_eq!(s.world_state().body("Plate").unwrap().component, 0); + assert_eq!(s.world_state().unwrap().body("Plate").unwrap().component, 0); s.doc_mut().marker = None; s.refresh(); - assert_eq!(s.world_state().body("Plate").unwrap().component, to); + assert_eq!(s.world_state().unwrap().body("Plate").unwrap().component, to); } #[test] @@ -39,19 +39,19 @@ fn transformed_pending_destination_repeated_transfer_preserves_world_pose() { let occurrence = created["occurrence"].as_u64().unwrap(); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,20,0],"angle":90,"axis":[0,0,1],"capture":false})); run(&mut s, "component.move_bodies", json!({"component":to,"bodies":["Block"]})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let bounds = state.body("Block").unwrap().mesh().bounds(); assert!(bounds.min.dist(Vec3::ZERO) < 1e-6); assert!(bounds.max.dist(Vec3::new(10.0, 10.0, 10.0)) < 1e-6); assert!(!s.pending_moves.contains_key(&occurrence)); let mut destination_reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; destination_reopened.refresh(); - assert!(destination_reopened.world_state().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); + assert!(destination_reopened.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); run(&mut s, "component.move_bodies", json!({"component":0,"bodies":["Block"]})); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - assert!(reopened.world_state().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); + assert!(reopened.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); } #[test] @@ -134,7 +134,7 @@ fn failed_transfer_cannot_change_evaluated_world_owner() { .unwrap(); s.refresh(); assert!(s.model.result(id).unwrap().error.is_some()); - assert_eq!(s.world_state().body("Block").unwrap().component, 0); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, 0); } #[test] @@ -142,18 +142,18 @@ fn transferred_thread_follows_body_frame_without_changing_world_axis() { let mut s = Session::default(); run(&mut s, "solid.cylinder", json!({"radius":4,"height":20,"body_name":"Shaft"})); run(&mut s, "solid.thread", json!({"face":[4,0,10],"designation":"M8"})); - let before = s.world_state().threads[0].clone(); + let before = s.world_state().unwrap().threads[0].clone(); let c = run(&mut s, "component.create", json!({"name":"Threaded","grounded":false})); let to = c["component"].as_u64().unwrap(); let occurrence = c["occurrence"].as_u64().unwrap(); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,20,10],"axis":[1,0,0],"angle":90,"capture":true})); run(&mut s, "component.move_bodies", json!({"component":to,"bodies":["Shaft"]})); - let after = s.world_state().threads[0].clone(); + let after = s.world_state().unwrap().threads[0].clone(); assert!(after.axis_point.dist(before.axis_point) < 1e-6); assert!(after.axis.dist(*before.axis) < 1e-6); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - assert!(reopened.world_state().threads[0].axis.dist(*before.axis) < 1e-6); + assert!(reopened.world_state().unwrap().threads[0].axis.dist(*before.axis) < 1e-6); } #[test] @@ -178,10 +178,10 @@ fn inherited_component_appearance_and_legacy_assignment_survive_transfer() { legacy.refresh(); assert!(!legacy.model.state().body("Old").unwrap().transferred); run(&mut legacy, "component.move_bodies", json!({"component":0,"bodies":["Old"]})); - assert!((legacy.world_state().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); + assert!((legacy.world_state().unwrap().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&legacy.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - assert!((reopened.world_state().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); + assert!((reopened.world_state().unwrap().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); } #[test] @@ -209,7 +209,7 @@ fn earlier_selected_cylinder_emboss_keeps_source_frame_after_transfer_and_edit() run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-2,5],"p1":[2,10]})); run(&mut s, "sketch.finish", json!({})); let emboss = run(&mut s, "solid.emboss", json!({"sketch":"Badge","face":[30,10,7.5],"depth":1}))["feature"].as_u64().unwrap(); - let before = solidcraft_kernel::measure(&s.world_state().body("Sleeve").unwrap().body).unwrap().volume; + let before = solidcraft_kernel::measure(&s.world_state().unwrap().body("Sleeve").unwrap().body).unwrap().volume; run(&mut s, "component.activate", json!({"component":0})); let destination = run(&mut s, "component.create", json!({"name":"Destination"})); let to = destination["component"].as_u64().unwrap(); @@ -220,10 +220,10 @@ fn earlier_selected_cylinder_emboss_keeps_source_frame_after_transfer_and_edit() let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); assert!(reopened.doc.features.iter().all(|feature| reopened.model.result(feature.id).is_some_and(|result| result.error.is_none()))); - assert!((solidcraft_kernel::measure(&reopened.world_state().body("Sleeve").unwrap().body).unwrap().volume - before).abs() < 1e-5); + assert!((solidcraft_kernel::measure(&reopened.world_state().unwrap().body("Sleeve").unwrap().body).unwrap().volume - before).abs() < 1e-5); let depth = reopened.doc.feature(emboss).unwrap().param_names[0].clone(); run(&mut reopened, "parameters.change", json!({"name":depth,"expression":"2 mm"})); - assert!(solidcraft_kernel::measure(&reopened.world_state().body("Sleeve").unwrap().body).unwrap().volume > before); + assert!(solidcraft_kernel::measure(&reopened.world_state().unwrap().body("Sleeve").unwrap().body).unwrap().volume > before); } #[test] @@ -235,16 +235,16 @@ fn transfer_undo_redo_restores_original_pending_source_world_pose() { run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Block"})); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":false})); let pending = s.pending_moves.clone(); - let before = s.world_state().body("Block").unwrap().mesh().bounds(); + let before = s.world_state().unwrap().body("Block").unwrap().mesh().bounds(); run(&mut s, "component.move_bodies", json!({"component":0,"bodies":["Block"]})); run(&mut s, "edit.undo", json!({})); assert_eq!(s.pending_moves, pending); - assert_eq!(s.world_state().body("Block").unwrap().component, source); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, source); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); run(&mut s, "edit.redo", json!({})); assert!(s.pending_moves.is_empty()); - assert_eq!(s.world_state().body("Block").unwrap().component, 0); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, 0); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); } #[test] @@ -256,15 +256,15 @@ fn transfer_checkpoint_restores_pending_world_pose_and_history() { run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Block"})); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":false})); let pending = s.pending_moves.clone(); - let before = s.world_state().body("Block").unwrap().mesh().bounds(); + let before = s.world_state().unwrap().body("Block").unwrap().mesh().bounds(); let undo_count = s.undo.len(); let checkpoint = s.checkpoint(); run(&mut s, "component.move_bodies", json!({"component":0,"bodies":["Block"]})); s.restore_checkpoint(checkpoint).unwrap(); assert_eq!(s.pending_moves, pending); assert_eq!(s.undo.len(), undo_count); - assert_eq!(s.world_state().body("Block").unwrap().component, source); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, source); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); } #[test] @@ -312,6 +312,7 @@ fn block_and_part() -> (Session, u64) { /// The lowest corner of every body in the world, rounded. fn world_corners(s: &Session) -> Vec> { s.world_state() + .unwrap() .bodies .iter() .map(|b| { diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rs index bf9dbe906..6bf8a3071 100644 --- a/crates/engine/src/cmd/config.rs +++ b/crates/engine/src/cmd/config.rs @@ -7,27 +7,48 @@ use solidcraft_doc::config::{Column, ConfigRow, MAX_COLUMNS, MAX_ROWS}; use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list}; +use crate::schema::config::{ConfigActivation, ConfigRowParams, ConfigTable, ConfigTableParams, ConfigTableReply, ConfigTableRow, ConfigTarget}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; +const TABLE_CONTRACT: TypedContract = TypedContract::new(); +const ROW_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("config.configure", "Configure", configure).at("SOLID", "CONFIGURE").icon("params").params( "params?: [parameter names]; features?: [feature names]; materials?: [body names]; appearances?: [body names] (columns to add; with no rows yet, a \"Default\" row takes the current values)", ), - CommandSpec::new("config.table", "Display Configuration Table", show) + CommandSpec::new("config.table", "Display Configuration Table", crate::checked!("config.table", show)) .at("SOLID", "CONFIGURE") .icon("configuration_table") .noundo() + .contract(&TABLE_CONTRACT) + .output(output_schema_for::) .params("→ columns (param: or suppress:), rows, the active row and whether the design still matches it"), CommandSpec::new("config.column", "Configuration Column", column).icon("configuration_table").params("param? | feature? | material? | appearance? (target name); delete?: bool"), CommandSpec::new("config.row", "Configuration Row", row).icon("configuration_table").params( "name; from? (row to copy; default current values); values?: {column key: expression, suppression, material name, appearance name or Look object}; rename?; delete?: bool", ), - CommandSpec::new("config.activate", "Activate Configuration", activate).icon("activate").params("row: name — sets its parameter values and suppressions"), - CommandSpec::new("config.preview", "Preview Configuration", preview).icon("eye").noundo().params("row: name — validates a rebuild without changing the design or history"), + CommandSpec::new("config.activate", "Activate Configuration", crate::checked!("config.activate", activate)) + .icon("activate") + .contract(&ROW_CONTRACT) + .output(output_schema_for::) + .params("row: name — sets its parameter values and suppressions"), + CommandSpec::new("config.preview", "Preview Configuration", crate::checked!("config.preview", preview)) + .icon("eye") + .noundo() + .contract(&ROW_CONTRACT) + .output(output_schema_for::) + .params("row: name — validates a rebuild without changing the design or history"), CommandSpec::new("config.rule", "Configuration Rule", rule).icon("configuration_table").params( "rule?: {id,name,enabled,condition,effect}; rules?: [rule…] (added or replaced together, then the rows checked once); id? + delete?; id? + index? (ordered move)", ), - CommandSpec::new("config.rules", "Configuration Rules", show).icon("list").noundo().params("ordered typed rules, rows and active state"), + CommandSpec::new("config.rules", "Configuration Rules", crate::checked!("config.rules", show)) + .icon("list") + .noundo() + .contract(&TABLE_CONTRACT) + .output(output_schema_for::) + .params("ordered typed rules, rows and active state"), ]; fn column_of(s: &Session, p: &Value, cmd: &str) -> Result { @@ -77,7 +98,7 @@ fn column_of(s: &Session, p: &Value, cmd: &str) -> Result { } let body_name = value.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "face body required"))?; let point = value.get("point").and_then(crate::params::vec3).ok_or_else(|| bad(cmd, "finite face point required"))?; - let world = s.world_state(); + let world = s.world_state()?; let body = world.body(body_name).ok_or_else(|| bad(cmd, "no face body"))?; if body.body.is_mesh() { return Err(bad(cmd, "mesh faces have no supported semantic lineage")); @@ -166,14 +187,21 @@ fn configure(s: &mut Session, p: &Value) -> Result { } fn show(s: &mut Session, _p: &Value) -> Result { + let table = table(s, "config.table")?; + to_reply("config.table", ConfigTableReply { table, param_warnings: Vec::new() }) +} + +fn to_reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) +} + +/// The table as the read-only commands, and an activation after its switch, return it. +fn table(s: &Session, cmd: &str) -> Result { let t = &s.doc.configs; let keys: Vec = t.columns.iter().map(|c| s.doc.config_key(c)).collect(); - let rows: Vec = t - .rows - .iter() - .map(|r| json!({"name": r.name, "values": keys.iter().zip(&r.cells).map(|(k, v)| (k.clone(), json!(v))).collect::>()})) - .collect(); - let targets: Vec = t + let rows = + t.rows.iter().map(|r| ConfigTableRow { name: r.name.clone(), values: keys.iter().cloned().zip(r.cells.iter().cloned()).collect() }).collect(); + let targets = t .columns .iter() .map(|column| { @@ -190,13 +218,22 @@ fn show(s: &mut Session, _p: &Value) -> Result { } _ => s.doc.config_key(column), }; - json!({"key":s.doc.config_key(column),"label":label,"target":column}) + let target = serde_json::to_value(column).map_err(|e| bad(cmd, e.to_string()))?; + Ok(ConfigTarget { key: s.doc.config_key(column), label, target }) }) - .collect(); + .collect::>>()?; + let rules = t.rules.iter().map(|r| serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))).collect::>>()?; let styles = s.doc.configuration_style_status(&s.model.state()); - Ok( - json!({"columns": keys, "targets":targets, "rows": rows, "rules": t.rules, "active": t.active, "matches": s.doc.configuration_matches() && styles.is_ok(), "style_status":styles.as_ref().ok(),"style_error":styles.err().map(|error|error.to_string())}), - ) + Ok(ConfigTable { + columns: keys, + targets, + rows, + rules, + active: t.active.clone(), + matches: s.doc.configuration_matches() && styles.is_ok(), + style_error: styles.as_ref().err().map(|error| error.to_string()), + style_status: styles.ok(), + }) } fn column(s: &mut Session, p: &Value) -> Result { @@ -294,6 +331,27 @@ fn row(s: &mut Session, p: &Value) -> Result { if rename.as_ref().is_some_and(|n| n != &name && s.doc.configs.rows.iter().any(|r| &r.name == n)) { return Err(bad(cmd, "configuration name already exists")); } + for (column, value) in s.doc.configs.columns.iter().zip(&cells) { + if matches!(column, Column::Suppress(_)) { + solidcraft_doc::config::suppression_cell(value).map_err(|e| bad(cmd, e.to_string()))?; + } + } + let changes: Vec<_> = s + .doc + .configs + .columns + .iter() + .zip(&cells) + .filter_map(|(column, value)| match column { + Column::Param(name) => Some((name.clone(), value.clone())), + _ => None, + }) + .collect(); + if !changes.is_empty() { + // Check the final parameter graph without activating the row or rebuilding geometry. + let mut trial = s.doc.as_ref().clone(); + trial.change_params_atomic(&changes).map_err(|e| bad(cmd, e.to_string()))?; + } let t = &mut s.doc_mut().configs; let validated_name = rename.clone().unwrap_or_else(|| name.clone()); match idx { @@ -396,6 +454,12 @@ fn rule(s: &mut Session, p: &Value) -> Result { } fn activate(s: &mut Session, p: &Value) -> Result { + to_reply("config.activate", activation(s, p)?) +} + +/// Switch to the row `p` names and say what that did, as `config.activate` and +/// `config.preview` return it. +fn activation(s: &mut Session, p: &Value) -> Result { let cmd = "config.activate"; let r = str_(p, "row").ok_or_else(|| bad(cmd, "`row` is required"))?.to_string(); let mut trial = s.scratch(); @@ -421,19 +485,18 @@ fn activate(s: &mut Session, p: &Value) -> Result { s.doc = trial.doc; s.settle_value_edit(&solved)?; let errors: Vec = s.model.results.iter().filter_map(|x| x.error.clone()).collect(); - let mut out = show(s, p)?; - out["errors"] = json!(errors); - out["trace"] = json!(trace); - out["styles"] = json!(styles); - Ok(out) + let trace = trace.iter().map(|t| serde_json::to_value(t).map_err(|e| bad(cmd, e.to_string()))).collect::>>()?; + Ok(ConfigActivation { table: table(s, cmd)?, errors, trace, styles, preview: None, parameters: None, param_warnings: Vec::new() }) } fn preview(s: &mut Session, p: &Value) -> Result { + let cmd = "config.preview"; let mut trial = s.scratch(); - let mut out = activate(&mut trial, p)?; - out["preview"] = json!(true); - out["parameters"] = json!(trial.doc.param_rows()); - Ok(out) + let mut out = activation(&mut trial, p)?; + out.preview = Some(true); + out.parameters = + Some(trial.doc.param_rows().iter().map(|r| serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))).collect::>>()?); + to_reply(cmd, out) } #[cfg(test)] @@ -664,6 +727,124 @@ mod tests { assert!((volume(&mut s) - 2000.0).abs() < 1e-6); } + #[test] + fn configuration_rows_reject_invalid_parameter_expressions_without_changes() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name":"L", "expression":"10 mm"})); + run(&mut s, "config.configure", json!({"params":["L"]})); + let before = s.doc.clone(); + let undo_len = s.undo.len(); + for expression in ["abc", "1/", "1/0"] { + for params in [ + json!({"name":"Bad", "values":{"param:L":expression}}), + json!({"name":"Copy", "from":"Default", "values":{"L":expression}}), + json!({"name":"Default", "rename":"Renamed", "values":{"L":expression}}), + ] { + let error = s.execute("config.row", ¶ms).expect_err("invalid expressions must be rejected when saving a row"); + assert!(error.to_string().contains("parameter `L`"), "{params}: {error}"); + assert_eq!(s.doc, before, "{params}"); + assert_eq!(s.undo.len(), undo_len, "{params}"); + } + } + } + + #[test] + fn configuration_rows_reject_invalid_suppression_without_changes() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY", "name":"TestSketch"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "config.configure", json!({"features":["TestSketch"]})); + let before = s.doc.clone(); + let undo_len = s.undo.len(); + for value in [json!("banana"), json!(""), json!(2), json!(-1)] { + for params in [ + json!({"name":"Bad", "values":{"suppress:TestSketch":value}}), + json!({"name":"Copy", "from":"Default", "values":{"TestSketch":value}}), + json!({"name":"Default", "rename":"Renamed", "values":{"TestSketch":value}}), + ] { + let error = s.execute("config.row", ¶ms).expect_err("invalid suppression must be rejected when saving a row"); + assert!(error.to_string().contains("suppression must be true or false"), "{params}: {error}"); + assert_eq!(s.doc, before, "{params}"); + assert_eq!(s.undo.len(), undo_len, "{params}"); + } + } + } + + #[test] + fn configuration_rows_validate_inherited_suppression_and_allow_repair() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY", "name":"TestSketch"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "config.configure", json!({"features":["TestSketch"]})); + // A row saved by an older reader may already contain invalid suppression text. + s.doc_mut().configs.rows[0].cells[0] = "banana".into(); + let before = s.doc.clone(); + let undo_len = s.undo.len(); + for params in [json!({"name":"Copy", "from":"Default"}), json!({"name":"Default", "rename":"Renamed"})] { + let error = s.execute("config.row", ¶ms).expect_err("inherited invalid suppression must also be checked"); + assert!(error.to_string().contains("suppression must be true or false"), "{params}: {error}"); + assert_eq!(s.doc, before, "{params}"); + assert_eq!(s.undo.len(), undo_len, "{params}"); + } + run(&mut s, "config.row", json!({"name":"Default", "values":{"TestSketch":false}})); + assert_eq!(s.doc.configs.rows[0].cells[0], "false"); + run(&mut s, "config.activate", json!({"row":"Default"})); + assert!(!s.doc.features[0].suppressed); + } + + #[test] + fn configuration_rows_keep_supported_suppression_spellings() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY", "name":"TestSketch"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "config.configure", json!({"features":["TestSketch"]})); + for (value, suppressed) in [ + (json!(true), true), + (json!(false), false), + (json!(1), true), + (json!(0), false), + (json!("true"), true), + (json!("false"), false), + (json!(" YES "), true), + (json!(" No "), false), + (json!("1"), true), + (json!("0"), false), + ] { + let before = s.doc.features.clone(); + run(&mut s, "config.row", json!({"name":"Accepted", "values":{"suppress:TestSketch":value}})); + assert_eq!(s.doc.features, before, "saving a row does not activate it"); + let text = value.as_str().map(str::to_owned).unwrap_or_else(|| value.to_string()); + assert_eq!(s.doc.configs.rows[1].cells[0], text, "accepted spellings are preserved"); + run(&mut s, "config.activate", json!({"row":"Accepted"})); + assert_eq!(s.doc.features[0].suppressed, suppressed, "{value}"); + } + } + + #[test] + fn configuration_rows_validate_the_final_parameter_graph_without_activating_it() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name":"L", "expression":"10 mm"})); + run(&mut s, "parameters.add", json!({"name":"W", "expression":"L + 2 mm"})); + run(&mut s, "config.configure", json!({"params":["L", "W"]})); + let before = s.doc.clone(); + // Changing L first would make a cycle with W's current expression. The final row is valid. + run(&mut s, "config.row", json!({"name":"Reordered", "values":{"L":"W + 2 mm", "W":"20 mm"}})); + assert_eq!(s.doc.params, before.params); + assert_eq!(s.doc.configs.active, before.configs.active); + let saved = s.doc.clone(); + let undo_len = s.undo.len(); + assert!(s.execute("config.row", &json!({"name":"Cycle", "from":"Reordered", "values":{"W":"L"}})).is_err()); + assert_eq!(s.doc, saved); + assert_eq!(s.undo.len(), undo_len); + run(&mut s, "config.activate", json!({"row":"Reordered"})); + let (values, errors) = s.doc.param_values(); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!(values["L"].v, 22.0); + assert_eq!(values["W"].v, 20.0); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, saved); + } + #[test] fn configured_feature_inputs_and_suppression_match_typed_cells() { let mut s = Session::default(); @@ -746,9 +927,7 @@ mod tests { // Bad input. assert!(s.execute("config.row", &json!({"name": "X", "values": {"nope": 1}})).is_err()); assert!(s.execute("config.activate", &json!({"row": "Missing"})).is_err()); - run(&mut s, "config.row", json!({"name": "Broken", "values": {"length": "1/"}})); - assert!(s.execute("config.activate", &json!({"row": "Broken"})).is_err()); - run(&mut s, "config.row", json!({"name": "Broken", "delete": true})); + assert!(s.execute("config.row", &json!({"name": "Broken", "values": {"length": "1/"}})).is_err()); run(&mut s, "config.column", json!({"feature": fillet, "delete": true})); assert_eq!(run(&mut s, "config.table", json!({}))["columns"].as_array().map(Vec::len), Some(1)); } diff --git a/crates/engine/src/cmd/config_certificate_tests.rs b/crates/engine/src/cmd/config_certificate_tests.rs index 34fd0d8f0..5c9a450a9 100644 --- a/crates/engine/src/cmd/config_certificate_tests.rs +++ b/crates/engine/src/cmd/config_certificate_tests.rs @@ -1,10 +1,11 @@ use crate::Session; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{ FeatureKind, config::{Column, FaceCertificate}, }; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; fn run(session: &mut Session, command: &str, params: Value) -> Value { session.execute(command, ¶ms).unwrap_or_else(|error| panic!("{command} {params}: {error}")) @@ -15,12 +16,14 @@ fn paint(session: &mut Session, body: &str, point: Value) { run(session, "config.row", json!({"name":"Painted","values":{key:"ABS - Red"}})); run(session, "config.activate", json!({"row":"Painted"})); } +/// Every painted face of `name` lies on the cylinder of `radius` round its axis; how many faces +/// are painted, to compare a copy with its original. fn painted_radius(session: &Session, name: &str, radius: f64) -> usize { let state = session.model.state(); let body = state.body(name).unwrap_or_else(|| panic!("missing {name}; bodies {:?}", state.bodies.iter().map(|body| &body.name).collect::>())); let painted = session.doc.face_colors(body); - let mesh = body.body.tessellate(0.001).unwrap(); + let mesh = body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap(); let inverse = solidcraft_doc::mat_inverse(&body.source_transform).unwrap(); for (triangle, face) in mesh.triangles.iter().zip(&mesh.tri_face) { if painted.iter().any(|(index, _)| *index == *face as usize) { @@ -30,7 +33,7 @@ fn painted_radius(session: &Session, name: &str, radius: f64) -> usize { } } } - assert!(!painted.is_empty()); + assert!(!painted.is_empty(), "{name}: nothing painted"); painted.len() } @@ -49,22 +52,22 @@ fn certified_annulus_side_rows_follow_radius_edits_and_clone() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"distance":10,"profiles":[{"point":[9.5,0]}],"body_name":"Ring"})); paint(&mut s, "Ring", json!([10, 0, 5])); - assert_eq!(painted_radius(&s, "Ring", 10.), 2, "both constructed arc pieces share outer curve"); + let pieces = painted_radius(&s, "Ring", 10.); let Column::FaceAppearance(target) = &s.doc.configs.columns[0] else { panic!() }; assert_eq!(target.certificate, Some(FaceCertificate::ExtrudeSide { sketch, curve: "outer".into() })); run(&mut s, "parameters.change", json!({"name":dimensions[0],"expression":"12 mm"})); run(&mut s, "parameters.change", json!({"name":dimensions[1],"expression":"9.25 mm"})); run(&mut s, "config.activate", json!({"row":"Painted"})); - assert_eq!(painted_radius(&s, "Ring", 12.), 2); + assert_eq!(painted_radius(&s, "Ring", 12.), pieces); run(&mut s, "component.paste_new", json!({"component":part,"translate":[30,0,0]})); assert_eq!(s.doc.configs.columns.len(), 2); run(&mut s, "config.activate", json!({"row":"Painted"})); - assert_eq!(painted_radius(&s, "Ring (2)", 12.), 2); + assert_eq!(painted_radius(&s, "Ring (2)", 12.), pieces); let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); let mut reopened = Session::new(reopened); run(&mut reopened, "config.activate", json!({"row":"Painted"})); - assert_eq!(painted_radius(&reopened, "Ring", 12.), 2); - assert_eq!(painted_radius(&reopened, "Ring (2)", 12.), 2); + assert_eq!(painted_radius(&reopened, "Ring", 12.), pieces); + assert_eq!(painted_radius(&reopened, "Ring (2)", 12.), pieces); run(&mut reopened, "config.activate", json!({"row":"Default"})); assert!(reopened.doc.appearances.faces.is_empty()); } @@ -90,7 +93,7 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam let step = solidcraft_kernel::step_export(&[&cylinder], "legacy anchored cylinder").unwrap(); let source = imported(&mut s, step, "Sleeve"); run(&mut s, "material.assign", json!({"bodies":["Sleeve"],"material":"Steel"})); - let before_volume = s.model.state().body("Sleeve").unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume; + let before_volume = s.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let legacy_names = solidcraft_doc::naming::face_names(s.model.state().body("Sleeve").unwrap()); assert!(legacy_names.iter().all(|name| name.starts_with(&format!("F{source}:face:")))); run(&mut s, "appearance.assign", json!({"faces":[{"body":"Sleeve","point":[6,0,20]}],"appearance":"ABS - Blue"})); @@ -104,7 +107,7 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam run(&mut s, "solid.emboss", json!({"sketch":"Badge","profiles":"all","depth":1,"targets":["Sleeve"],"name":"Raised Badge"})); let anchored = s.doc.find_feature("Raised Badge").unwrap().clone(); assert!(matches!(anchored.kind, FeatureKind::Emboss { face: None, .. })); - let volume = s.model.state().body("Sleeve").unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume; + let volume = s.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; assert!((volume - std::f64::consts::PI * 2000. - 16.).abs() < 0.1, "volume {volume}"); assert!((volume - before_volume - 16.).abs() < 0.01, "addedvolume {} baseline {before_volume}", volume - before_volume); let paint = s.doc.appearances.faces.clone(); @@ -112,11 +115,14 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam legacy["format"] = json!("solidcraft/9"); let reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap()); // Saved before format 14, it keeps naming the pieces it makes in the kernel's shell order, - // and numbering the pieces of its faces as that build did (#3902). - let anchored = solidcraft_doc::Feature { shell_piece_order: true, kernel_piece_order: true, ..anchored }; + // and numbering the pieces of its faces as that build did (#3902); saved before joins split + // off pieces that touch only along an edge or at a point, it keeps them in + // one body. + let anchored = + solidcraft_doc::Feature { shell_piece_order: true, kernel_piece_order: true, touching: solidcraft_doc::Touching::OneBody, ..anchored }; assert_eq!(reopened.doc.feature(anchored.id).unwrap(), &anchored); - // Names saved before format 14 keep naming the face they named, marked so they are found as - // the build that saved them found them. + // Names saved before format 14 open with the legacy mark; the sketch is held by its anchor, + // not by its name. let mark = |name: &Option| name.as_ref().map(|n| format!("{}{n}", solidcraft_doc::naming::LEGACY_MARK)); let mut saved_plane = saved_plane; if let solidcraft_doc::PlaneRef::Face { name, .. } = &mut saved_plane { @@ -138,7 +144,7 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam assert!(reopened.model.result(anchored.id).unwrap().error.is_none()); let state = reopened.model.state(); let body = state.body("Sleeve").unwrap(); - assert!((body.body.tessellate_with(1e-4, true).unwrap().measure().volume - volume).abs() < 1e-8); + assert!((body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume - volume).abs() < 1e-8); assert!(!reopened.doc.face_colors(body).is_empty()); } @@ -170,7 +176,7 @@ fn certified_side_refuses_reused_body_name_from_a_new_producer() { } #[test] -fn legacy_v9_annulus_outer_side_emboss_keeps_its_original_heuristic_anchor() { +fn legacy_v9_annulus_outer_side_emboss_asks_for_its_face_again() { let mut s = Session::default(); run(&mut s, "sketch.create", json!({"plane":"XY"})); run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":10,"id":"outer"})); @@ -190,20 +196,25 @@ fn legacy_v9_annulus_outer_side_emboss_keeps_its_original_heuristic_anchor() { assert_eq!(feature.face_names, vec![name]); assert!(feature.face_names.iter().all(|name| names.contains(name))); let feature_id = feature.id; - let volume = s.model.state().body("Sleeve").unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume; + let volume = s.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; assert!((volume - std::f64::consts::PI * 380. - 21.).abs() < 0.2, "volume {volume}"); let mut legacy: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); legacy["format"] = json!("solidcraft/9"); // What a version 9 design stored for that pick: the centroid-family name of the outer wall - // piece holding the point. It keeps finding that piece, as it did when saved. + // piece holding the point, worked out from geometry. It names no face today (the outer wall + // is one face, named after its own curve): the emboss fails and asks for its face again, + // and the sleeve is built without it. for feature in legacy["features"].as_array_mut().unwrap() { if feature["id"] == json!(feature_id) { feature["face_names"] = json!(["F2:side:inner#4"]); } } let reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap()); - assert!(reopened.model.result(feature_id).unwrap().error.is_none()); - assert!((reopened.model.state().body("Sleeve").unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume - volume).abs() < 1e-8); + let error = reopened.model.result(feature_id).unwrap().error.clone().unwrap(); + assert_eq!(solidcraft_doc::reselect_parts(&error), Some(("Raised Badge", "?F2:side:inner#4")), "{error}"); + let sleeve = reopened.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; + assert!((sleeve - std::f64::consts::PI * 380.).abs() < 0.2, "volume {sleeve}"); + assert!(reopened.model.results.iter().filter(|r| r.id != feature_id).all(|r| r.error.is_none()), "{:?}", reopened.model.results); } #[test] @@ -220,15 +231,15 @@ fn certified_side_transfer_preserves_geometry_and_unsupported_taper_refuses_atom run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,20,0],"angle":90,"axis":[0,0,1],"capture":false})); run(&mut s, "component.move_bodies", json!({"component":destination,"bodies":["Round"]})); run(&mut s, "config.activate", json!({"row":"Painted"})); - assert_eq!(painted_radius(&s, "Round", 10.), 2); - let before = s.world_state().body("Round").unwrap().mesh().bounds(); + let pieces = painted_radius(&s, "Round", 10.); + let before = s.world_state().unwrap().body("Round").unwrap().mesh().bounds(); let mut s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); run(&mut s, "config.activate", json!({"row":"Painted"})); - assert_eq!(painted_radius(&s, "Round", 10.), 2); + assert_eq!(painted_radius(&s, "Round", 10.), pieces); assert!( - s.world_state().body("Round").unwrap().mesh().bounds().min.dist(before.min) < 1e-8, + s.world_state().unwrap().body("Round").unwrap().mesh().bounds().min.dist(before.min) < 1e-8, "before {before:?}, reopened {:?}", - s.world_state().body("Round").unwrap().mesh().bounds() + s.world_state().unwrap().body("Round").unwrap().mesh().bounds() ); // A successful ordinary modifier has no exact untapered source certificate. let FeatureKind::Extrude { extent, .. } = &mut s.doc_mut().feature_mut(source).unwrap().kind else { panic!() }; diff --git a/crates/engine/src/cmd/config_style_tests.rs b/crates/engine/src/cmd/config_style_tests.rs index c34b81340..7c25af895 100644 --- a/crates/engine/src/cmd/config_style_tests.rs +++ b/crates/engine/src/cmd/config_style_tests.rs @@ -1,6 +1,7 @@ use crate::Session; use serde_json::{Value, json}; use solidcraft_doc::config::{Column, ConfigFaceTarget}; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap_or_else(|error| panic!("{command} {params}: {error}")) } @@ -23,11 +24,11 @@ fn component_appearance_shared_definition_inheritance_and_delete() { let key = table["columns"][0].as_str().unwrap().to_string(); run(&mut s, "config.row", json!({"name":"Red","values":{key.clone():"ABS - Red"}})); run(&mut s, "config.activate", json!({"row":"Red"})); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), 2); assert!(world.bodies.iter().all(|body| s.doc.model_body_look(body).unwrap().name == "ABS - Red")); run(&mut s, "appearance.assign", json!({"bodies":[body],"appearance":"ABS - Yellow"})); - assert!(s.world_state().bodies.iter().all(|body| s.doc.model_body_look(body).unwrap().name == "ABS - Yellow")); + assert!(s.world_state().unwrap().bodies.iter().all(|body| s.doc.model_body_look(body).unwrap().name == "ABS - Yellow")); run(&mut s, "config.activate", json!({"row":"Default"})); assert!(!s.doc.appearances.components.contains_key(&component)); assert_eq!(s.doc.appearances.bodies[&body].name, "ABS - Yellow"); @@ -130,7 +131,7 @@ fn strict_face_missing_lineage_never_retargets_and_rolls_back() { let look = solidcraft_doc::appearance::library("ABS - Red").unwrap(); s.doc_mut().appearances.faces.push(solidcraft_doc::appearance::FaceLook { body: body.clone(), - point: solidcraft_geom::Vec3::new(5., 5., 10.), + point: solidcore_record::Vec3::new(5., 5., 10.), name: Some(format!("F{other}:+z")), strict_name: true, certificate: None, @@ -147,17 +148,17 @@ fn face_occurrence_pick_uses_definition_identity_and_coordinates() { let component = run(&mut s, "component.create", json!({"name":"Part"}))["component"].as_u64().unwrap(); let body = block(&mut s); run(&mut s, "occurrence.copy", json!({"component":component,"translate":[30,0,0]})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let placed = world.bodies.iter().find(|body| body.name != body.definition_name()).unwrap(); let placed_name = placed.name.clone(); - let point = solidcraft_doc::apply_point(&placed.source_transform, solidcraft_geom::Vec3::new(5., 5., 10.)); + let point = solidcraft_doc::apply_point(&placed.source_transform, solidcore_record::Vec3::new(5., 5., 10.)); let key = face_column(&mut s, &placed_name, json!(point)); let Column::FaceAppearance(target) = &s.doc.configs.columns[0] else { panic!() }; assert_eq!(target.body, body); - assert!(target.point.dist(solidcraft_geom::Vec3::new(5., 5., 10.)) < 1e-8); + assert!(target.point.dist(solidcore_record::Vec3::new(5., 5., 10.)) < 1e-8); run(&mut s, "config.row", json!({"name":"Paint","values":{key:"ABS - Blue"}})); run(&mut s, "config.activate", json!({"row":"Paint"})); - assert!(s.world_state().bodies.iter().all(|body| s.doc.face_colors(body).len() == 1)); + assert!(s.world_state().unwrap().bodies.iter().all(|body| s.doc.face_colors(body).len() == 1)); } #[test] @@ -216,7 +217,7 @@ fn hostile_and_uncertified_face_targets_are_rejected() { body: body.clone(), origin_feature: id, name: format!("F{id}:face:0"), - point: solidcraft_geom::Vec3::ZERO, + point: solidcore_record::Vec3::ZERO, certificate: None, }; assert!(s.doc.certify_config_face(&target).is_err()); diff --git a/crates/engine/src/cmd/construct.rs b/crates/engine/src/cmd/construct.rs index 400a21fb0..938d13821 100644 --- a/crates/engine/src/cmd/construct.rs +++ b/crates/engine/src/cmd/construct.rs @@ -7,17 +7,17 @@ //! persistent names. use serde_json::Value; +use solidcore_record::Vec3; use solidcraft_doc::construct::{AxisDef, GeoRef, PointDef}; use solidcraft_doc::{FeatureKind, PlaneRef}; -use solidcraft_geom::Vec3; use super::CommandSpec; use super::features::{add_feature, check_expr, plane_param, sketch_id}; use crate::params::{bad, req_expr, str_, vec3}; use crate::schema::construct::{ AxisEdgeParams, AxisNormalToFaceParams, AxisThroughCylinderParams, AxisTwoPlanesParams, AxisTwoPointsParams, MidplaneParams, - PlaneAlongPathParams, PlanePerpendicularParams, PlaneTangentParams, PlaneThreePointsParams, PlaneTwoEdgesParams, PointAlongPathParams, - PointCenterParams, PointEdgePlaneParams, PointThreePlanesParams, PointTwoEdgesParams, PointVertexParams, + PlaneAlongPathParams, PlaneAxisPointParams, PlanePerpendicularParams, PlaneTangentParams, PlaneThreePointsParams, PlaneTwoEdgesParams, + PointAlongPathParams, PointCenterParams, PointEdgePlaneParams, PointThreePlanesParams, PointTwoEdgesParams, PointVertexParams, }; use crate::schema::features::FeatureResult; use crate::schema::{TypedContract, output_schema_for}; @@ -39,6 +39,7 @@ const POINT_EDGE_PLANE_CONTRACT: TypedContract = TypedCont const POINT_ALONG_PATH_CONTRACT: TypedContract = TypedContract::new(); const PLANE_MIDPLANE_CONTRACT: TypedContract = TypedContract::new(); const PLANE_TWO_EDGES_CONTRACT: TypedContract = TypedContract::new(); +const PLANE_AXIS_POINT_CONTRACT: TypedContract = TypedContract::new(); const PLANE_THREE_POINTS_CONTRACT: TypedContract = TypedContract::new(); const PLANE_TANGENT_CONTRACT: TypedContract = TypedContract::new(); const PLANE_ALONG_PATH_CONTRACT: TypedContract = TypedContract::new(); @@ -123,6 +124,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .contract(&PLANE_TWO_EDGES_CONTRACT) .output(output_schema_for::) .params("a, b: straight edge or line refs in one plane; name?"), + CommandSpec::new("construct.plane.axis_point", "Plane Through Axis And Point", crate::checked!("construct.plane.axis_point", plane_axis_point)) + .at("SOLID", "CONSTRUCT") + .icon("plane_axis_point") + .contract(&PLANE_AXIS_POINT_CONTRACT) + .output(output_schema_for::) + .params("axis: origin axis, construction axis, straight edge or sketch line ref; point: off-axis point ref; name?"), CommandSpec::new("construct.plane.three_points", "Plane Through Three Points", crate::checked!("construct.plane.three_points", plane_points)) .at("SOLID", "CONSTRUCT") .icon("plane_three_points") @@ -134,7 +141,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("plane_tangent") .contract(&PLANE_TANGENT_CONTRACT) .output(output_schema_for::) - .params("face: ref (cylinder, cone, sphere or torus); at?: [x,y,z] where it touches (default: the face pick); name?"), + .params("face: ref (cylinder, cone, sphere or torus); at?: [x,y,z] where it touches (default: the face pick); reference?: plane or planar face ref (the plane touches where the face turns towards it: parallel to it, on the side of `at`); angle?: expr (with reference, default 0 deg: turned that far about the face's axis; not on a sphere); name?"), CommandSpec::new("construct.plane.along_path", "Plane Along Path", crate::checked!("construct.plane.along_path", plane_along)) .at("SOLID", "CONSTRUCT") .icon("plane_along_path") @@ -164,7 +171,7 @@ pub(crate) fn is_model_axis(v: &Value) -> bool { pub(super) fn model_axis_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result> { let Some(v) = v.filter(|v| is_model_axis(v)) else { return Ok(None) }; let g = geo(s, Some(v), cmd, "axis")?; - let (o, d) = solidcraft_doc::construct::model_axis(&s.world_state(), &g).map_err(|e| bad(cmd, format!("`axis`: {e}")))?; + let (o, d) = solidcraft_doc::construct::model_axis(&*s.world_state()?, &g).map_err(|e| bad(cmd, format!("`axis`: {e}")))?; Ok(Some((g, o, d))) } @@ -374,6 +381,19 @@ fn plane_edges(s: &mut Session, p: &Value) -> Result { plane(s, p, PlaneRef::TwoEdges { a: Box::new(a), b: Box::new(b) }) } +fn plane_axis_point(s: &mut Session, p: &Value) -> Result { + let kind = plane_axis_point_kind(s, p)?; + add_feature(s, p, kind) +} + +/// Shared parser for the constructor and its world-to-authoring-frame boundary. +pub(crate) fn plane_axis_point_kind(s: &Session, p: &Value) -> Result { + let cmd = "construct.plane.axis_point"; + let axis = geo(s, p.get("axis"), cmd, "axis")?; + let point = geo(s, p.get("point"), cmd, "point")?; + Ok(FeatureKind::ConstructionPlane { plane: PlaneRef::AxisPoint { axis: Box::new(axis), point: Box::new(point) } }) +} + fn plane_points(s: &mut Session, p: &Value) -> Result { let cmd = "construct.plane.three_points"; let (a, b, c) = (geo(s, p.get("a"), cmd, "a")?, geo(s, p.get("b"), cmd, "b")?, geo(s, p.get("c"), cmd, "c")?); @@ -388,7 +408,20 @@ fn plane_tangent(s: &mut Session, p: &Value) -> Result { (None, GeoRef::Face { at, .. }) => *at, _ => return Err(bad(cmd, "`at` is required: where the plane touches the face")), }; - plane(s, p, PlaneRef::Tangent { face: Box::new(face), at }) + let reference = match p.get("reference").filter(|v| !v.is_null()) { + Some(_) => Some(Box::new(geo(s, p.get("reference"), cmd, "reference")?)), + None => None, + }; + let angle = match p.get("angle").filter(|v| !v.is_null()) { + Some(_) if reference.is_none() => return Err(bad(cmd, "`angle` turns the plane from a `reference`: give one")), + Some(_) => { + let angle = req_expr(cmd, p, "angle")?; + check_expr(s, &angle, solidcraft_doc::expr::Kind::Angle, cmd, "angle")?; + Some(angle) + } + None => None, + }; + plane(s, p, PlaneRef::Tangent { face: Box::new(face), at, reference, angle }) } fn plane_along(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/contact_sweep.rs b/crates/engine/src/cmd/contact_sweep.rs index e9a3593a2..d507ad3d7 100644 --- a/crates/engine/src/cmd/contact_sweep.rs +++ b/crates/engine/src/cmd/contact_sweep.rs @@ -1,12 +1,17 @@ -//! Bounded, chronological checks of a joint trajectory. This samples tessellated geometry; -//! it is deliberately not advertised as exact continuous collision detection. +//! Bounded, chronological checks of a joint trajectory. The motion is sampled, so this is not +//! continuous collision detection. A joint drive decides on the exact bodies whether they pass +//! into each other at a sample ([`ContactGeometry::overlaps`]) and closes in on where they first +//! touch through placements known to be clear ([`ContactGeometry::gap`]); gaps and interference +//! depths are measured on the bodies' contact meshes. +use solidcraft_geom::prelude::*; use std::cell::Cell; use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; +use solidcore_record::Vec3; use solidcraft_doc::joints; use solidcraft_doc::{Document, IDENTITY, Mat, apply_point, mat_mul}; -use solidcraft_geom::{Aabb3, Bvh, Mesh, Vec3}; +use solidcraft_geom::{Aabb3, Bvh, Mesh}; use crate::params::bad; use crate::{Result, Session}; @@ -16,6 +21,9 @@ const MAX_PLACEMENTS: usize = 4096; const MAX_BODIES: usize = 256; const MAX_TRIANGLES: usize = 50_000; const MAX_WORK: usize = 50_000_000; +/// Most exact intersections one joint drive works out: one per pair of bodies whose exact boxes +/// meet, at each sample and bisection step. +const MAX_INTERSECTIONS: usize = 2048; fn limit(message: &str) -> crate::EngineError { bad("contact.sweep", message) @@ -25,6 +33,9 @@ fn limit(message: &str) -> crate::EngineError { struct CachedBody { path: Vec, offset: Mat, + /// The body itself, for the exact checks, and its exact box in its own frame. + body: solidcraft_kernel::Body, + exact_box: Aabb3, mesh: Arc, size: f64, /// How far its mesh may stray from its faces: 0 when every face is flat (the mesh is the @@ -52,7 +63,7 @@ pub(crate) struct ContactMeshes(HashMap); /// Tessellate `body` for contact checks and measure how thin it is. fn contact_mesh(body: &solidcraft_doc::ModelBody) -> Result { let tolerance = (body.body.size() * 1e-3).max(1e-3); - let mesh = body.body.tessellate(tolerance)?; + let mesh = body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tolerance))?; if mesh.triangles.len() > MAX_TRIANGLES || mesh.positions.len().saturating_add(mesh.triangles.len().saturating_mul(4)) > 200_000 { return Err(limit("body exceeds contact sweep tessellation budget")); } @@ -94,6 +105,15 @@ fn contact_mesh(body: &solidcraft_doc::ModelBody) -> Result { /// A member of a contact set: (occurrence id, name). pub(super) type Member = (u64, String); +/// Two set members whose bodies pass into each other: their names, and the bodies (indices in +/// [`ContactGeometry`]) that do. +pub(super) struct Overlap { + pub(super) a: String, + pub(super) b: String, + bodies: (usize, usize), +} + +#[derive(Clone)] pub(super) struct ContactGeometry { bodies: Vec, /// Body indices, and the set members (occurrence id, name) they are under. @@ -171,6 +191,8 @@ impl ContactGeometry { out.bodies.push(CachedBody { path: path.clone(), offset: s.doc.model_body_offset(body).copied().unwrap_or(IDENTITY), + body: body.body.clone(), + exact_box: body.body.exact_bounds()?, mesh, size: body.body.size(), chord, @@ -211,6 +233,12 @@ impl ContactGeometry { ContactGeometry { bodies: self.bodies.clone(), pairs: taken, step: self.step } } + /// The diagonal of the box the bodies fill in `s`: past it, a part moving in a straight + /// line meets nothing it has not met. + pub(super) fn reach(&self, s: &Session) -> Result { + Ok(self.bounds(s)?.size().len()) + } + /// How many mesh points are placed for each check. pub(super) fn vertex_count(&self) -> usize { self.bodies.iter().map(|b| b.mesh.positions.len()).fold(0, usize::saturating_add) @@ -301,8 +329,119 @@ impl ContactGeometry { .collect() } - pub(super) fn first_hit(&self, s: &Session, work: &mut usize) -> Result> { - Ok(self.hits(s, work, MAX_WORK, false)?.into_iter().next().map(|(a, b, depth)| (a.1, b.1, depth))) + /// The pairs of bodies of set members that pass into each other in `s` (every pair, or the + /// first found when `all` is false), decided on the exact bodies: their intersection holds + /// volume. Bodies that only touch, such as a cam and its follower, share none. Only bodies + /// whose exact boxes meet are intersected; `intersections` counts them, refused past the + /// drive's budget. + pub(super) fn overlaps(&self, s: &Session, intersections: &mut usize, all: bool) -> Result> { + let frames = self.frames(s)?; + let boxes: Vec = self.bodies.iter().zip(&frames).map(|(b, f)| placed_box(&b.exact_box, f)).collect(); + let mut placed: Vec> = vec![None; self.bodies.len()]; + let mut out = Vec::new(); + for (a, b, oa, ob) in &self.pairs { + let (Some(xa), Some(xb)) = (boxes.get(*a), boxes.get(*b)) else { + return Err(limit("invalid contact geometry pair")); + }; + if !xa.meets(xb) { + continue; + } + *intersections = intersections.saturating_add(1); + if *intersections > MAX_INTERSECTIONS { + return Err(limit("motion exceeds contact sweep intersection budget; simplify the contact set or use smaller increments")); + } + let undecided = |e: &dyn std::fmt::Display| { + bad("contact.sweep", format!("whether {} and {} pass into each other could not be decided ({e})", oa.1, ob.1)) + }; + let (pa, pb) = (self.placed_body(*a, &frames, &mut placed)?, self.placed_body(*b, &frames, &mut placed)?); + let Some(shared) = solidcraft_kernel::boolean(&pa, &pb, solidcraft_kernel::BoolOp::Intersect).map_err(|e| undecided(&e))? else { + continue; + }; + if solidcraft_kernel::measure_mass(&shared).map_err(|e| undecided(&e))?.volume > 0.0 { + out.push(Overlap { a: oa.1.clone(), b: ob.1.clone(), bodies: (*a, *b) }); + if !all { + break; + } + } + } + Ok(out) + } + + /// The least gap between the bodies of `pairs` in `s`, where they are clear of each other: their + /// exact distance ([`solidcraft_kernel::body_distance`]), less the meshes' chord tolerances + /// where it could only be measured on the meshes, so the gap is never more than the bodies'. + /// Between bodies that pass into each other it means nothing (a distance does not tell them + /// from touching ones): it is asked only of placements known to be clear. + pub(super) fn gap(&self, s: &Session, pairs: &[Overlap]) -> Result { + let frames = self.frames(s)?; + let mut placed: Vec> = vec![None; self.bodies.len()]; + let mut least = f64::INFINITY; + for pair in pairs { + let (a, b) = pair.bodies; + let (Some(ca), Some(cb), Some(fa), Some(fb)) = (self.bodies.get(a), self.bodies.get(b), frames.get(a), frames.get(b)) else { + return Err(limit("invalid contact geometry pair")); + }; + let (pa, pb) = (self.placed_body(a, &frames, &mut placed)?, self.placed_body(b, &frames, &mut placed)?); + let mesh = |c: &CachedBody, f: &Mat| Mesh { + positions: c.mesh.positions.iter().map(|p| apply_point(f, *p)).collect(), + triangles: c.mesh.triangles.clone(), + ..Mesh::default() + }; + let (ma, mb) = (mesh(ca, fa), mesh(cb, fb)); + let (sa, sb) = (solidcraft_kernel::DistanceShape::new(&pa, &ma, ca.chord), solidcraft_kernel::DistanceShape::new(&pb, &mb, cb.chord)); + let Some(d) = solidcraft_kernel::body_distance(&sa, &sb, f64::INFINITY)? else { + return Err(limit("invalid contact geometry pair")); + }; + let gap = if d.exact { d.distance } else { d.distance - ca.chord - cb.chord }; + least = least.min(gap.max(0.0)); + } + Ok(least) + } + + /// The furthest a point of the bodies of `pairs` moves toward the other body of its pair + /// from where `from` ([`ContactGeometry::frames`]) placed them to where `to` has them + /// (bounded by the two bodies' own furthest moves, each by the corners of its exact box, + /// which a rigid move takes furthest). + pub(super) fn pair_travel(&self, from: &[Mat], to: &Session, pairs: &[Overlap]) -> Result { + let moved = |i: usize| -> Result { + let (Some(body), Some(fa)) = (self.bodies.get(i), from.get(i)) else { + return Err(limit("invalid contact geometry pair")); + }; + let fb = Self::frame(body, to)?; + let local = &body.exact_box; + let mut most = 0.0_f64; + for c in 0..8 { + let pick = |bit: usize, lo: f64, hi: f64| if c & bit == 0 { lo } else { hi }; + let corner = Vec3::new(pick(1, local.min.x, local.max.x), pick(2, local.min.y, local.max.y), pick(4, local.min.z, local.max.z)); + most = most.max(apply_point(fa, corner).dist(apply_point(&fb, corner))); + } + Ok(most) + }; + let mut most = 0.0_f64; + for pair in pairs { + most = most.max(moved(pair.bodies.0)? + moved(pair.bodies.1)?); + } + Ok(most) + } + + /// Where `s` places each body. + pub(super) fn frames(&self, s: &Session) -> Result> { + self.bodies.iter().map(|b| Self::frame(b, s)).collect() + } + + /// Body `i` placed by `frames`, made once per check. + fn placed_body(&self, i: usize, frames: &[Mat], placed: &mut [Option]) -> Result { + if let Some(Some(done)) = placed.get(i) { + return Ok(done.clone()); + } + let (Some(body), Some(frame)) = (self.bodies.get(i), frames.get(i)) else { + return Err(limit("invalid contact geometry pair")); + }; + let moved = solidcraft_kernel::transform_matrix(&body.body, *frame)?; + if let Some(slot) = placed.get_mut(i) { + *slot = Some(moved.clone()); + } + Ok(moved) } /// The pairs of set members whose bodies pass through each other in `s`, with how deep the @@ -315,38 +454,12 @@ impl ContactGeometry { let meshes = self.placed(s)?; // Each mesh's box once, not once per pair it is in. let boxes: Vec = meshes.iter().map(Mesh::bounds).collect(); - for (a, b, oa, ob) in &self.pairs { + for (i, (_, _, oa, ob)) in self.pairs.iter().enumerate() { // Members already found colliding need no more of their bodies tested. if found.contains(&(oa.0.min(ob.0), oa.0.max(ob.0))) { continue; } - let (Some(ma), Some(mb), Some(ba), Some(bb)) = (meshes.get(*a), meshes.get(*b), self.bodies.get(*a), self.bodies.get(*b)) else { - return Err(limit("invalid contact geometry pair")); - }; - let (Some(aabb), Some(bbb)) = (boxes.get(*a), boxes.get(*b)) else { - return Err(limit("invalid contact geometry pair")); - }; - if aabb.max.x < bbb.min.x - || bbb.max.x < aabb.min.x - || aabb.max.y < bbb.min.y - || bbb.max.y < aabb.min.y - || aabb.max.z < bbb.min.z - || bbb.max.z < aabb.min.z - { - continue; - } - let cost = ma - .positions - .len() - // 4 sample points and 3 edges to probe per triangle of `a` against each triangle of `b` (#3323), and the other way round. - .saturating_add(ma.triangles.len().saturating_mul(7)) - .saturating_mul(mb.triangles.len()) - .saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(7)).saturating_mul(ma.triangles.len())); - *work = work.saturating_add(cost); - if *work > budget { - return Err(limit("motion exceeds contact sweep collision budget; simplify the contact set or use smaller increments")); - } - if let Some(depth) = super::mesh_overlap(ma, mb, 1e-4 * ba.size.max(bb.size).max(1.0)) { + if let Some(depth) = self.depth(i, &meshes, &boxes, work, budget)? { found.insert((oa.0.min(ob.0), oa.0.max(ob.0))); out.push((oa.clone(), ob.clone(), depth)); if !all { @@ -356,6 +469,66 @@ impl ContactGeometry { } Ok(out) } + + /// How deep the bodies of each pair pass into each other in `s` (0 where they don't), in + /// the order of the pairs. `work` adds up the cost, refused past `budget`. + pub(super) fn depths(&self, s: &Session, work: &mut usize, budget: usize) -> Result> { + let meshes = self.placed(s)?; + let boxes: Vec = meshes.iter().map(Mesh::bounds).collect(); + (0..self.pairs.len()).map(|i| Ok(self.depth(i, &meshes, &boxes, work, budget)?.unwrap_or(0.0))).collect() + } + + /// The set members pair `i` is between. + pub(super) fn members(&self, i: usize) -> Option<(Member, Member)> { + self.pairs.get(i).map(|(_, _, a, b)| (a.clone(), b.clone())) + } + + /// How far the meshes of pair `i` may stray from their faces (see [`ContactGeometry::chord`]). + pub(super) fn pair_chord(&self, i: usize) -> f64 { + let chord = |b: usize| self.bodies.get(b).map_or(0.0, |b| b.chord); + self.pairs.get(i).map_or(0.0, |(a, b, _, _)| chord(*a).max(chord(*b))) + } + + /// Pair `i` alone (with the same bodies). + pub(super) fn only(&self, i: usize) -> ContactGeometry { + ContactGeometry { bodies: self.bodies.clone(), pairs: self.pairs.get(i).cloned().into_iter().collect(), step: self.step } + } + + /// How deep the bodies of pair `i` (placed as `meshes`, in `boxes`) pass into each other, + /// when more than a touch. + fn depth(&self, i: usize, meshes: &[Mesh], boxes: &[Aabb3], work: &mut usize, budget: usize) -> Result> { + let Some((a, b, _, _)) = self.pairs.get(i) else { return Err(limit("invalid contact geometry pair")) }; + let (Some(ma), Some(mb), Some(ba), Some(bb)) = (meshes.get(*a), meshes.get(*b), self.bodies.get(*a), self.bodies.get(*b)) else { + return Err(limit("invalid contact geometry pair")); + }; + let (Some(aabb), Some(bbb)) = (boxes.get(*a), boxes.get(*b)) else { + return Err(limit("invalid contact geometry pair")); + }; + // Boxes apart, or only touching (parts end to end): `mesh_overlap` finds nothing there, + // so it costs nothing (#5968). + let tol = 1e-4 * ba.size.max(bb.size).max(1.0); + if aabb.max.x < bbb.min.x + tol + || bbb.max.x < aabb.min.x + tol + || aabb.max.y < bbb.min.y + tol + || bbb.max.y < aabb.min.y + tol + || aabb.max.z < bbb.min.z + tol + || bbb.max.z < aabb.min.z + tol + { + return Ok(None); + } + let cost = ma + .positions + .len() + // 4 sample points and 3 edges to probe per triangle of `a` against each triangle of `b` (#3323), and the other way round. + .saturating_add(ma.triangles.len().saturating_mul(7)) + .saturating_mul(mb.triangles.len()) + .saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(7)).saturating_mul(ma.triangles.len())); + *work = work.saturating_add(cost); + if *work > budget { + return Err(limit("motion exceeds contact sweep collision budget; simplify the contact set or use smaller increments")); + } + Ok(super::mesh_overlap(ma, mb, tol)) + } } /// How near two set members come: the bodies under them nearest each other. @@ -431,6 +604,20 @@ impl ContactGeometry { } } +/// The box holding `local` placed by `frame` (its corners' box: a rigid motion keeps the box's +/// contents inside it). +fn placed_box(local: &Aabb3, frame: &Mat) -> Aabb3 { + let mut world = Aabb3::EMPTY; + for c in 0..8 { + let pick = |bit: usize, lo: f64, hi: f64| if c & bit == 0 { lo } else { hi }; + world.add(apply_point( + frame, + Vec3::new(pick(1, local.min.x, local.max.x), pick(2, local.min.y, local.max.y), pick(4, local.min.z, local.max.z)), + )); + } + world +} + fn limit_error(message: &str) -> crate::EngineError { limit(message) } diff --git a/crates/engine/src/cmd/contact_sweep_tests.rs b/crates/engine/src/cmd/contact_sweep_tests.rs index 51bcc140b..9828e7557 100644 --- a/crates/engine/src/cmd/contact_sweep_tests.rs +++ b/crates/engine/src/cmd/contact_sweep_tests.rs @@ -1,6 +1,6 @@ use crate::Session; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; fn run(s: &mut Session, command: &str, p: Value) -> Value { s.execute(command, &p).unwrap() @@ -167,8 +167,11 @@ fn thin_tilted_plates_cannot_cross_between_axis_bound_samples() { assert!(value > -2.0 && value < -1.9, "{value}"); } +/// A slider carrying a sphere or a box with a rounded edge stops where it meets a block 5 mm +/// away (the sphere's and the box's near sides at x = 15, the block's at 10): ordinary curved +/// bodies sweep within the contact sampling budget, however their faces are meshed. #[test] -fn ordinary_curved_bodies_keep_a_practical_sampling_step() { +fn ordinary_curved_bodies_stop_at_their_contact_within_the_sampling_budget() { for curved in ["sphere", "fillet"] { let mut s = Session::default(); run(&mut s, "component.create", json!({"name": "Blocker"})); @@ -187,8 +190,6 @@ fn ordinary_curved_bodies_keep_a_practical_sampling_step() { json!({"type": "slider", "a": 0, "b": "Curved", "at": {"occurrence": 0, "point": [0,0,0], "z": [1,0,0]}, "name": "Slide"}), ); run(&mut s, "contact.create", json!({"occurrences": ["Blocker", "Curved"]})); - let geometry = super::ContactGeometry::new(&s).unwrap(); - assert!(geometry.step > 1.0, "{curved}: tessellation must not force tiny steps: {}", geometry.step); let result = run(&mut s, "joint.drive", json!({"joint": "Slide", "value": -30})); assert!(result["stopped_by_contact"].is_object(), "{curved}: {result}"); let value = s.doc.assembly.joints.iter().find(|j| j.name == "Slide").unwrap().values[0]; diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs index cffa7f63f..bb1e36e5e 100644 --- a/crates/engine/src/cmd/delete.rs +++ b/crates/engine/src/cmd/delete.rs @@ -8,8 +8,8 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{FeatureKind, ids}; -use solidcraft_geom::Vec3; use super::{CommandSpec, sketch_store}; use crate::params::{bad, bool_}; @@ -39,6 +39,9 @@ fn keys(p: &Value, k: &str) -> Vec { fn delete(s: &mut Session, p: &Value) -> Result { if bool_(p, "dry_run").unwrap_or(false) { let mut t = s.scratch(); + // What the check computes is kept where this session keeps it (a check run ahead, off a + // front end's window thread), so the delete itself finds it there (#9917). + t.model.keep(s.model.kept()); return apply(&mut t, p); } let r = apply(s, p)?; @@ -220,8 +223,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { done = true; } if !features.is_empty() { - let ids: Vec = features.iter().map(u64::to_string).collect(); - sub(s, "timeline.delete", json!({ "features": ids }))?; + sub(s, "timeline.delete", json!({ "features": features }))?; done = true; } // Bodies still there (not made by a feature deleted above) get a Remove feature. @@ -403,6 +405,69 @@ mod tests { assert!(s.model.state().sketch(sk).unwrap().sketch.constraints.iter().all(|c| c.id != angle)); } + /// #9917: the check before a delete in a sketch with a rolled-back history after it builds the + /// history before the delete only when a feature fails after it. Deleting a hole in the plate + /// changes the plate and every cut after it and breaks none of them: the check reports + /// nothing. Deleting a side of the plate's outline breaks the plate, and the check still says + /// so, with the cache too small to keep a state (as on a large design). + #[test] + fn a_delete_in_a_rolled_back_history_reports_what_breaks_after_the_marker_and_nothing_else() { + let mut s = Session::default(); + let sk = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap(); + let outline = run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [30, 20], [10, 20]], "closed": true}))["curves"][0] + .as_str() + .unwrap() + .to_string(); + let hole = run(&mut s, "sketch.circle.center", json!({"center": [30, 15], "radius": 2}))["curves"][0].as_str().unwrap().to_string(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5, "name": "Plate"})); + for i in 0..6 { + run(&mut s, "solid.cylinder", json!({"base": [12 + 3 * i, 8, -1], "radius": 1, "height": 10, "operation": "cut"})); + } + run(&mut s, "timeline.roll_to", json!({"position": 1})); + run(&mut s, "sketch.edit", json!({"sketch": sk})); + *s.model.cache.lock().unwrap() = solidcraft_doc::EvalCache::with_budget(1); + let doc = s.doc.clone(); + let dry = run(&mut s, "selection.delete", json!({"items": [{"type": "sketch_curve", "id": hole}], "dry_run": true})); + assert_eq!(dry["would_fail"], json!([]), "{dry}"); + let dry = run(&mut s, "selection.delete", json!({"items": [{"type": "sketch_curve", "id": outline}], "dry_run": true})); + assert!(dry["would_fail"].as_array().unwrap().contains(&json!("Plate")), "{dry}"); + assert_eq!(*s.doc, *doc, "the checks change nothing"); + } + + /// #9917: a delete checked ahead (off a front end's window thread) keeps what its dry run + /// builds of the history after the marker, and the delete run with that finds all of it: + /// nothing is built again on the window thread, where it took half a minute. + #[test] + fn a_delete_checked_ahead_keeps_the_history_it_builds_for_the_delete() { + let mut s = Session::default(); + let sk = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [30, 20], [10, 20]], "closed": true})); + let hole = run(&mut s, "sketch.circle.center", json!({"center": [30, 15], "radius": 2}))["curves"][0].as_str().unwrap().to_string(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5, "name": "Plate"})); + let later = 6; + for i in 0..later { + run(&mut s, "solid.cylinder", json!({"base": [12 + 3 * i, 8, -1], "radius": 1, "height": 10, "operation": "cut"})); + } + run(&mut s, "timeline.roll_to", json!({"position": 1})); + run(&mut s, "sketch.edit", json!({"sketch": sk})); + // A cache too small to keep a state, as on a large design: only what is kept carries over. + *s.model.cache.lock().unwrap() = solidcraft_doc::EvalCache::with_budget(1); + let items = json!([{"type": "sketch_curve", "id": hole}]); + let ahead = s.ahead(); + let kept = ahead.kept(); + let replies = ahead.replies(&[("selection.delete".to_string(), json!({"items": items, "dry_run": true}))]); + assert!(replies.iter().all(Result::is_ok), "{replies:?}"); + let built = kept.len(); + assert!(built > later, "the check kept the history after the marker: {built} results"); + s.model.keep(Some(kept.clone())); + run(&mut s, "selection.delete", json!({"items": items})); + s.model.keep(None); + assert_eq!(kept.len(), built, "the delete found everything it builds among what the check kept"); + assert!(s.model.state().sketch(sk).unwrap().sketch.curves.iter().all(|c| c.id != hole)); + } + #[test] fn mixed_selection_is_one_undo_step() { let (mut s, _) = part(); @@ -873,7 +938,7 @@ mod tests { run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3, "id": "hole"})); let index = { let st = s.model.state(); - solidcraft_sketch::profile_at_point(&st.sketch(sk).unwrap().profiles, solidcraft_geom::Vec2::new(30.0, 10.0)).unwrap() + solidcraft_sketch::profile_at_point(&st.sketch(sk).unwrap().profiles, solidcore_record::Vec2::new(30.0, 10.0)).unwrap() }; let before = curves(&s, sk); assert_eq!(before.len(), 5, "four lines and a circle: {before:?}"); diff --git a/crates/engine/src/cmd/diagnostics.rs b/crates/engine/src/cmd/diagnostics.rs index bac6ec4e8..f7c5c6b4a 100644 --- a/crates/engine/src/cmd/diagnostics.rs +++ b/crates/engine/src/cmd/diagnostics.rs @@ -1,56 +1,128 @@ //! Crash reports, for agents and people (see `crate::crash` and docs/crash-reports.md): list -//! them, read one, delete them. They live on this computer and are never sent anywhere. +//! them, read one, delete them. They live on this computer and are never sent anywhere. And the +//! profiler (`solidcraft_profile`, docs/perf.md): where the time goes, SMLib's calls to commands. -use serde_json::{Value, json}; +use serde_json::Value; use super::CommandSpec; use crate::params::{bad, str_}; +use crate::schema::diagnostics::{ + CrashReport, CrashReportList, CrashReportParams, CrashReportsClearParams, CrashReportsCleared, CrashReportsParams, CrashTestParams, + CrashTestResult, +}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session, crash}; +const LIST_CONTRACT: TypedContract = TypedContract::new(); +const READ_CONTRACT: TypedContract = TypedContract::new(); +const CLEAR_CONTRACT: TypedContract = TypedContract::new(); +const CRASH_TEST_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("diagnostics.crash_reports", "Crash Reports", list).any_part().icon("bug_report").noundo().params( - "limit?: number (default 20). Lists this computer's crash reports, newest first: {dir, reports: [{id, kind, time, message, \ - command, count, version, path, replayable}]}. kind: command_panic | panic | kernel_panic_recovered | unclean_exit. \ - Read one with diagnostics.crash_report; reproduce it with `solidcraft-cli crashes replay `", - ), - CommandSpec::new("diagnostics.crash_report", "Crash Report", read).any_part().icon("bug_report").noundo().params( - "id: report id. The whole report: message, location, backtrace, app version and commit, system, the command that \ - crashed and the recent ones, notes, and design_path / replay_path when the crash can be replayed \ - (`solidcraft-cli run --in `)", - ), - CommandSpec::new("diagnostics.crash_reports.clear", "Delete Crash Reports", clear) + CommandSpec::new("diagnostics.crash_reports", "Crash Reports", crate::checked!("diagnostics.crash_reports", list)) + .any_part() + .icon("bug_report") + .noundo() + .contract(&LIST_CONTRACT) + .output(output_schema_for::) + .params( + "limit?: number (default 20). Lists this computer's crash reports, newest first: {dir, reports: [{id, kind, time, message, \ + command, count, version, path, replayable}]}. kind: command_panic | panic | kernel_panic_recovered | unclean_exit. \ + Read one with diagnostics.crash_report; reproduce it with `solidcraft-cli crashes replay `", + ), + CommandSpec::new("diagnostics.crash_report", "Crash Report", crate::checked!("diagnostics.crash_report", read)) + .any_part() + .icon("bug_report") + .noundo() + .contract(&READ_CONTRACT) + .output(output_schema_for::) + .params( + "id: report id. The whole report: message, location, backtrace, app version and commit, system, the command that \ + crashed and the recent ones, notes, and design_path / replay_path when the crash can be replayed \ + (`solidcraft-cli run --in `)", + ), + CommandSpec::new("diagnostics.crash_reports.clear", "Delete Crash Reports", crate::checked!("diagnostics.crash_reports.clear", clear)) .any_part() .icon("delete") .noundo() + .contract(&CLEAR_CONTRACT) + .output(output_schema_for::) .params("id?: one report (default: all). Returns {deleted}"), - CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).any_part().icon("bug_report").noundo().enabled(crash_test_enabled).params( - "mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \ - the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \ - at the next start). Only when the SOLIDCRAFT_CRASH_TEST environment variable is set", - ), + CommandSpec::new("diagnostics.profile", "Profile", crate::checked!("diagnostics.profile", profile)) + .any_part() + .icon("bug_report") + .noundo() + .contract(&PROFILE_CONTRACT) + .output(crate::schema::output_schema_for::) + .params( + "enabled?: bool (start or stop recording); reset?: bool (forget what was recorded); top?: rows (default 20, 0: all); \ + trace?: path (write the recorded spans as a Chrome trace-event file, for chrome://tracing or Perfetto). Returns what \ + was recorded before enabled and reset apply: {compiled, enabled, wall_ms, spans, dropped, by_category: [{category, \ + self_ms, share}], rows: [{category, name, count, total_ms, self_ms, max_ms}], rows_total, trace?}, the rows the most \ + self time first. Categories: solidcore (the kernel's calls), kernel, feature (one per feature \ + computed, by its type), doc, command, import (STEP/IGES stages), io. Self time is a span's time less the spans \ + inside it; total counts its outermost run only. Recording also starts with SOLIDCRAFT_PROFILE=1, the CLI's \ + --profile and the app's preference; off, it costs nothing measurable. Read-only", + ), + CommandSpec::new("diagnostics.validation", "Validation", crate::checked!("diagnostics.validation", validation)) + .any_part() + .icon("bug_report") + .noundo() + .contract(&VALIDATION_CONTRACT) + .output(crate::schema::output_schema_for::) + .params( + "mode?: each_step | each_feature | off (default: leave it). When the kernel's full check runs on the features computed \ + from now on: after every sweep, boolean and blend (each_step), once on the bodies each feature makes or changes \ + (each_feature, the default; a body it refuses still fails its feature, with the check's reason), or never (off, \ + experimental). Results already there stand until their features are computed again (timeline.compute_all). \ + The app's preference of the same name sets it. Returns {mode, previous}", + ), + CommandSpec::new("diagnostics.crash_test", "Crash Test", crate::checked!("diagnostics.crash_test", crash_test)) + .any_part() + .icon("bug_report") + .noundo() + .enabled(crash_test_enabled) + .contract(&CRASH_TEST_CONTRACT) + .output(output_schema_for::) + .params( + "mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \ + the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \ + at the next start). Only when the SOLIDCRAFT_CRASH_TEST environment variable is set", + ), ]; fn dir(cmd: &str) -> Result { crash::default_dir().ok_or_else(|| bad(cmd, "no crash folder on this system")) } +fn reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) +} + fn list(_: &mut Session, p: &Value) -> Result { - let d = dir("diagnostics.crash_reports")?; + let cmd = "diagnostics.crash_reports"; + let d = dir(cmd)?; let limit = p.get("limit").and_then(Value::as_u64).map_or(20, |n| n.min(1000)) as usize; let mut reports = crash::list(&d); reports.truncate(limit); - Ok(json!({ "dir": d.to_string_lossy(), "reports": reports })) + reply(cmd, CrashReportList { dir: d.to_string_lossy().into_owned(), reports, param_warnings: Vec::new() }) } fn read(_: &mut Session, p: &Value) -> Result { let cmd = "diagnostics.crash_report"; let id = str_(p, "id").ok_or_else(|| bad(cmd, "`id` is required (see diagnostics.crash_reports)"))?; - crash::read(&dir(cmd)?, id).map_err(|e| bad(cmd, e)) + // `crash::read` gives only a report that is a JSON object. + let report = match crash::read(&dir(cmd)?, id).map_err(|e| bad(cmd, e))? { + Value::Object(report) => report, + _ => return Err(bad(cmd, format!("no crash report `{id}`"))), + }; + reply(cmd, CrashReport { report, param_warnings: Vec::new() }) } fn clear(_: &mut Session, p: &Value) -> Result { - let d = dir("diagnostics.crash_reports.clear")?; - Ok(json!({ "deleted": crash::clear(&d, str_(p, "id")) })) + let cmd = "diagnostics.crash_reports.clear"; + let d = dir(cmd)?; + reply(cmd, CrashReportsCleared { deleted: crash::clear(&d, str_(p, "id")), param_warnings: Vec::new() }) } fn crash_test_enabled(_: &Session) -> std::result::Result<(), String> { @@ -65,12 +137,69 @@ fn crash_test(_: &mut Session, p: &Value) -> Result { match str_(p, "mode") { Some("panic") => std::panic::panic_any(String::from("crash test: an internal error in a command")), Some("kernel") => { - solidcraft_kernel::guard("crash test", || -> solidcraft_kernel::Result<()> { - std::panic::panic_any(String::from("an internal error in the kernel")) - })?; + solidcraft_kernel::crash_test()?; Err(EngineError::Other("crash test: the kernel error was not caught".into())) } Some("abort") => std::process::abort(), _ => Err(bad(cmd, "`mode` must be panic, kernel or abort")), } } + +const PROFILE_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +const VALIDATION_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +fn validation(s: &mut Session, p: &Value) -> Result { + let cmd = "diagnostics.validation"; + let mode = match p.get("mode") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_str() + .and_then(solidcraft_kernel::Validation::parse) + .ok_or_else(|| bad(cmd, format!("`mode` {}", crate::schema::diagnostics::VALIDATION_MODES)))?, + ), + }; + let previous = s.validation(); + if let Some(mode) = mode { + s.set_validation(mode); + } + let out = crate::schema::diagnostics::ValidationReply { mode: s.validation().into(), previous: previous.into() }; + serde_json::to_value(out).map_err(|e| EngineError::Other(format!("{cmd}: {e}"))) +} + +/// Rows `diagnostics.profile` returns at most. +const MAX_PROFILE_ROWS: u64 = 10_000; + +fn profile(_: &mut Session, p: &Value) -> Result { + let cmd = "diagnostics.profile"; + let flag = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), + }; + let (enabled, reset) = (flag("enabled")?, flag("reset")?); + let top = match p.get("top") { + None | Some(Value::Null) => 20, + Some(v) => v.as_u64().ok_or_else(|| bad(cmd, "`top` must be a whole number of rows (0: all)"))?.min(MAX_PROFILE_ROWS) as usize, + }; + let trace = match p.get("trace") { + None | Some(Value::Null) => None, + Some(_) => Some(str_(p, "trace").filter(|t| !t.trim().is_empty() && t.len() < 4096).ok_or_else(|| bad(cmd, "`trace` must be a file path"))?), + }; + let report = solidcraft_profile::report(); + let mut out = crate::schema::diagnostics::ProfileReport::new(&report, top); + if let Some(path) = trace { + let mut bytes = Vec::new(); + solidcraft_profile::write_chrome_trace(&mut bytes).map_err(|e| bad(cmd, format!("trace: {e}")))?; + solidcraft_io::vfs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + out.trace = Some(path.to_string()); + } + if reset == Some(true) { + solidcraft_profile::reset(); + } + if let Some(on) = enabled { + solidcraft_profile::set_enabled(on); + out.enabled = solidcraft_profile::enabled(); + } + serde_json::to_value(out).map_err(|e| EngineError::Other(format!("{cmd}: {e}"))) +} diff --git a/crates/engine/src/cmd/drawing_dimension.rs b/crates/engine/src/cmd/drawing_dimension.rs index 0dfd29570..9978789f1 100644 --- a/crates/engine/src/cmd/drawing_dimension.rs +++ b/crates/engine/src/cmd/drawing_dimension.rs @@ -8,11 +8,12 @@ use std::sync::Arc; use serde_json::Value; +use solidcore_record::Vec3; use solidcraft_doc::drawing::Drawing; use solidcraft_doc::drawing::dimension::{Candidate, Dimension, DimensionKind, Silhouette, Status, TextPlace, check_chain_length}; use solidcraft_doc::ids; -use solidcraft_geom::Vec3; use solidcraft_geom::drawing_measure::{LinearDirection, Reading}; +use solidcraft_geom::prelude::*; use super::CommandSpec; use crate::params::bad; diff --git a/crates/engine/src/cmd/drawing_dimension_tests.rs b/crates/engine/src/cmd/drawing_dimension_tests.rs index 9fef6bb9d..d775b9554 100644 --- a/crates/engine/src/cmd/drawing_dimension_tests.rs +++ b/crates/engine/src/cmd/drawing_dimension_tests.rs @@ -1,9 +1,9 @@ use std::collections::BTreeSet; use serde_json::json; +use solidcore_record::Vec3; use solidcraft_doc::drawing::view::{View, ViewKind, ViewPlace}; use solidcraft_doc::drawing_view::{ViewDirection, ViewOverrides}; -use solidcraft_geom::Vec3; use solidcraft_geom::drawing_view::NamedView; use super::*; @@ -224,15 +224,14 @@ fn a_point_on_a_curved_edge_finds_it_between_its_chords() { let (sin, cos) = degrees.to_radians().sin_cos(); json!([40.0 + radius * cos, 0.0, 15.0 + radius * sin]) }; - // The hole's rim is two half circles, and each point names one of them. Whole steps never land on - // where they meet, which names both and is refused. + // The hole's rim is one closed edge, and every point on it names that edge. let mut named = BTreeSet::new(); for step in 0..55 { let at = add(&mut s, view, json!({"radial": {"edge": rim(6.0, 3.3 + 6.5 * f64::from(step))}})); reads(&at, 12.0, "Ø12.00"); named.insert(at["record"]["kind"]["radial"]["edge"]["name"].as_str().unwrap().to_string()); } - assert_eq!(named.len(), 2, "{named:?}"); + assert_eq!(named.len(), 1, "{named:?}"); assert!(refused(&mut s, json!({"view": ids::encode(view), "kind": {"radial": {"edge": rim(7.0, 20.0)}}})).contains("no edge")); let (sin, cos) = 45f64.to_radians().sin_cos(); reads(&add(&mut s, view, json!({"radial": {"edge": [75.0 + 5.0 * cos, 0.0, 25.0 + 5.0 * sin]}})), 5.0, "R5.00"); diff --git a/crates/engine/src/cmd/drawing_view.rs b/crates/engine/src/cmd/drawing_view.rs index 3bede22d4..70228fb8b 100644 --- a/crates/engine/src/cmd/drawing_view.rs +++ b/crates/engine/src/cmd/drawing_view.rs @@ -24,6 +24,8 @@ use std::sync::Arc; use serde::Serialize; use serde_json::Value; +use solidcore_record::Plane; +use solidcore_record::Vec2; use solidcraft_doc::display_units::unit_scale; use solidcraft_doc::drawing::Drawing; use solidcraft_doc::drawing::balloon::Balloon; @@ -31,14 +33,14 @@ use solidcraft_doc::drawing::dimension::{Dimension, LabelKind, MAX_DECIMALS, rea use solidcraft_doc::drawing::view::{ResolvedView, SetBy, Setting, View, ViewKind, ViewPlace}; use solidcraft_doc::drawing_view::{Looking, TangentEdges, ViewDirection, ViewOverrides}; use solidcraft_doc::ids; -use solidcraft_geom::Plane; +use solidcraft_geom::Aabb2; use solidcraft_geom::drawing_measure::{self, AngleFrom, LinearDirection, Measured, Reading}; use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Sheet}; use solidcraft_geom::drawing_view::{Invalid, NamedView, PRESETS, ProjectedSide, Scale}; use solidcraft_geom::hlr::{Source, Visibility}; use solidcraft_geom::paper::{MAX_COORDINATE_MM, Picture}; +use solidcraft_geom::prelude::*; use solidcraft_geom::section::CurveAccuracy; -use solidcraft_geom::{Aabb2, Vec2}; use solidcraft_io::paper::MAX_PICTURE_DPI; use solidcraft_render::VisualStyle; diff --git a/crates/engine/src/cmd/drawing_view_tests.rs b/crates/engine/src/cmd/drawing_view_tests.rs index ef4671cb0..e923d8257 100644 --- a/crates/engine/src/cmd/drawing_view_tests.rs +++ b/crates/engine/src/cmd/drawing_view_tests.rs @@ -502,7 +502,7 @@ fn a_base_view_fits_what_its_percent_shows() { // In the drawing space; it may still lie over the title block, and is listed if it does. let space = s.drawing("test").unwrap().sheets[0].drawing_space().unwrap().inflated(1e-9); let corner = - |at: &str| solidcraft_geom::Vec2::new(made["boundary_mm"][at][0].as_f64().unwrap(), made["boundary_mm"][at][1].as_f64().unwrap()); + |at: &str| solidcore_record::Vec2::new(made["boundary_mm"][at][0].as_f64().unwrap(), made["boundary_mm"][at][1].as_f64().unwrap()); assert!(space.contains(corner("min")) && space.contains(corner("max")), "{made}"); assert_eq!(saved(&s, id).reference_shown_percent, percent); } @@ -914,16 +914,16 @@ fn two_touching_blocks_draw_their_shared_side_once() { } /// Every segment of `v`'s pieces at `visibility`, lines and arcs alike, on the sheet. -fn drawn(v: &Value, visibility: &str) -> Vec { +fn drawn(v: &Value, visibility: &str) -> Vec { let pieces = v["lines"].as_array().into_iter().flatten().flat_map(|l| l["pieces"].as_array().into_iter().flatten()); let segs = pieces.filter(|p| p["visibility"] == visibility).flat_map(|p| p["path"].as_array().into_iter().flatten()); segs.map(|seg| serde_json::from_value(seg.clone()).unwrap()).collect() } /// The points of `seg` furthest out: its ends, and for an arc each quarter-turn point it passes. -fn reach(seg: &solidcraft_geom::Seg2) -> Vec { +fn reach(seg: &solidcore_record::Seg2) -> Vec { let mut out = vec![seg.start(), seg.end()]; - if let solidcraft_geom::Seg2::Arc { center, radius, start, sweep } = *seg { + if let solidcore_record::Seg2::Arc { center, radius, start, sweep } = *seg { let (lo, span) = if sweep >= 0.0 { (start, sweep) } else { (start + sweep, -sweep) }; for k in 0..8 { let angle = f64::from(k) * std::f64::consts::FRAC_PI_2; @@ -937,8 +937,8 @@ fn reach(seg: &solidcraft_geom::Seg2) -> Vec { /// Whether `a` and `b` share a stretch longer than 1e-6 mm: collinear lines that overlap, or arcs /// of one circle whose turns overlap. -fn share_a_stretch(a: &solidcraft_geom::Seg2, b: &solidcraft_geom::Seg2) -> bool { - use solidcraft_geom::Seg2::{Arc, Line}; +fn share_a_stretch(a: &solidcore_record::Seg2, b: &solidcore_record::Seg2) -> bool { + use solidcore_record::Seg2::{Arc, Line}; use std::f64::consts::TAU; match (*a, *b) { (Line { a: p, b: q }, Line { a: c, b: d }) => { @@ -1116,7 +1116,7 @@ fn each_placements_hole_is_its_own_exact_circle() { } /// Every stroke of `v`'s paper scene: its path, whether it is closed, and its width. -fn strokes(v: &Value) -> Vec<(Vec, bool, f64)> { +fn strokes(v: &Value) -> Vec<(Vec, bool, f64)> { use solidcraft_geom::paper::{Item, Scene}; let scene: Scene = serde_json::from_value(v["scene"].clone()).unwrap(); let items = scene.groups.into_iter().flat_map(|g| g.items); @@ -1161,7 +1161,7 @@ fn a_holes_rim_is_arcs_in_the_scene() { let mut round = 0.0; for (path, closed, _) in strokes(&v) { for seg in &path { - if let solidcraft_geom::Seg2::Arc { center, radius, sweep, .. } = *seg { + if let solidcore_record::Seg2::Arc { center, radius, sweep, .. } = *seg { assert!(center.dist(Vec2::new(210.0, 148.5)) < 1e-9 && (radius - 5.0).abs() < 1e-9, "{v}"); round += radius * sweep.abs(); let whole = path.len() == 1 && (sweep.abs() - std::f64::consts::TAU).abs() < 1e-9; @@ -1321,7 +1321,10 @@ fn a_reference_part_much_bigger_than_the_model_is_held_or_refused() { let fitted = |s: &mut Session, percent: f64| snap(s, json!({"view": "top", "reference_shown_percent": percent})); let (near, far) = (fitted(&mut s, 0.0), fitted(&mut s, 100.0)); assert_ne!(near["scale"], far["scale"], "{far}"); - assert!(role_length(&far, true, "visible") > role_length(&near, true, "visible"), "{far}"); + // At 0% the view shows the two sides of the big part that cross the model, cut off at the view's + // edges; at 100% all four. + let reference_lines = |v: &Value| v["lines"].as_array().unwrap().iter().filter(|l| l["reference"] == true).count(); + assert_eq!((reference_lines(&near), reference_lines(&far)), (2, 4), "{far}"); // Fitted round the model's middle, the side it grows on still stays on the sheet. let position = (point(&near["boundary_mm"]["min"]) + point(&near["boundary_mm"]["max"])) * 0.5; let (low, high) = (point(&far["boundary_mm"]["min"]), point(&far["boundary_mm"]["max"])); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d35899c40..ed7ad87ba 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1,5 +1,6 @@ //! Undo/redo, the timeline, deletion and selection. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use std::sync::Arc; @@ -8,12 +9,35 @@ use solidcraft_doc::drawing::{self, Drawing}; use solidcraft_doc::{Document, Feature, FeatureKind}; use super::CommandSpec; -use crate::params::{bad, bool_, name_or_id_list, num, str_}; +use crate::params::{bad, bool_, name_or_id_values, num, str_}; use crate::{EngineError, Result, Sel, Session, Snapshot}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("edit.undo", "Undo", undo).any_part().icon("undo").key("Ctrl+Z").noundo().doc_only(), - CommandSpec::new("edit.redo", "Redo", redo).any_part().icon("redo").key("Ctrl+Y").noundo().doc_only(), + CommandSpec::new("ui.assistant", "Toggle Assistant", crate::checked!("ui.assistant", assistant)) + .any_part() + .icon("assistant") + .key("Ctrl+Shift+A") + .noundo() + .doc_only() + .contract(&ASSISTANT_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("Show or hide Assistant in the app. Headless calls are refused without changing the design"), + CommandSpec::new("edit.undo", "Undo", crate::checked!("edit.undo", undo)) + .any_part() + .icon("undo") + .key("Ctrl+Z") + .noundo() + .doc_only() + .contract(&UNDO_CONTRACT) + .output(crate::schema::output_schema_for::), + CommandSpec::new("edit.redo", "Redo", crate::checked!("edit.redo", redo)) + .any_part() + .icon("redo") + .key("Ctrl+Y") + .noundo() + .doc_only() + .contract(&REDO_CONTRACT) + .output(crate::schema::output_schema_for::), CommandSpec::new("edit.repeat", "Repeat Last Command", crate::checked!("edit.repeat", repeat)) .icon("redo") .key("Shift+R") @@ -22,14 +46,18 @@ pub static COMMANDS: &[CommandSpec] = &[ .contract(&REPEAT_CONTRACT) .output(crate::schema::output_schema_for::) .params("Starts the last tool or dialog started in the app again, with its defaults (a toolbar click, not a replay of its values). Only the app has a tool to start: called here it is refused, and changes nothing"), - CommandSpec::new("edit.checkpoint", "Checkpoint", checkpoint).any_part().icon("checkpoint") + CommandSpec::new("edit.checkpoint", "Checkpoint", crate::checked!("edit.checkpoint", checkpoint)).any_part().icon("checkpoint") .noundo() .doc_only() - .params("→ {checkpoint: id}: remember the design, active sketch and undo history (restore with edit.restore_checkpoint)"), - CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", restore_checkpoint).any_part().icon("restore") + .contract(&CHECKPOINT_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("→ {checkpoint: id}: remember the design, active sketch and undo history (restore with edit.restore_checkpoint; the last 16 are kept, the oldest dropped first)"), + CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", crate::checked!("edit.restore_checkpoint", restore_checkpoint)).any_part().icon("restore") .noundo() .doc_only() - .params("checkpoint: id; forget?: bool (true = drop it without going back). Goes back to it, undo history included"), + .contract(&RESTORE_CHECKPOINT_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("checkpoint: id; forget?: bool (true = drop it without going back). Goes back to it, undo history included. Restoring or forgetting uses it and every later checkpoint up: take a new one to go back again"), CommandSpec::new("timeline.compute_all", "Compute All", compute_all).at("SOLID", "MODIFY").icon("compute").noundo(), CommandSpec::new("timeline.play", "Play History", crate::checked!("timeline.play", play)) .at("INSPECT", "HISTORY") @@ -90,7 +118,7 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("select.set", "Select", select_set).any_part().icon("select") .noundo() - .params("items: [{type: body|edge|face|feature|sketch_curve|sketch_point|profile, …} or {type: drawing, drawing, object: ids of the drawing open and of a view, dimension or balloon of it}], add?: bool"), + .params("items: [{type: body|edge|face|feature|sketch_curve|sketch_point|profile, …} or {type: drawing, drawing, object: ids of the drawing open and of a view, dimension or balloon of it}], add?: bool; face/edge: body plus point [x,y,z] in world mm or index (both also accepted); a point uses Measure's pick tolerance, an index supplies a point on the item; invalid partial picks leave the selection unchanged"), CommandSpec::new("select.filter", "Selection filter", select_filter).icon("select").noundo().doc_only() .params("mode: body|face|component → validated UI pick granularity; headless echo only, no document edits or undo"), CommandSpec::new("select.clear", "Clear Selection", select_clear).any_part().icon("select").noundo(), @@ -105,12 +133,22 @@ fn play(_s: &mut Session, p: &Value) -> Result { serde_json::to_value(crate::schema::edit::TimelinePlayResult { action: request.action }).map_err(|e| EngineError::Other(e.to_string())) } +const UNDO_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const REDO_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const CHECKPOINT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const RESTORE_CHECKPOINT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +/// A reply built from its schema's type, so the two can't drift apart. +fn reply(cmd: &str, r: impl serde::Serialize) -> Result { + serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string())) +} + fn undo(s: &mut Session, _p: &Value) -> Result { let prev = latest(&mut s.undo, s.open_drawing).ok_or_else(|| nothing(s, "undo"))?; let now = go_to(s, prev); let label = now.label.clone(); s.redo.push(now); - Ok(json!({"undone": label})) + reply("edit.undo", crate::schema::edit::UndoResult { undone: label, param_warnings: Vec::new() }) } fn redo(s: &mut Session, _p: &Value) -> Result { @@ -118,7 +156,13 @@ fn redo(s: &mut Session, _p: &Value) -> Result { let now = go_to(s, next); let label = now.label.clone(); s.undo.push(now); - Ok(json!({"redone": label})) + reply("edit.redo", crate::schema::edit::RedoResult { redone: label, param_warnings: Vec::new() }) +} + +const ASSISTANT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +fn assistant(_s: &mut Session, _p: &Value) -> Result { + Err(EngineError::Other("ui.assistant shows or hides Assistant in the app; no assistant panel exists in a headless session".into())) } const REPEAT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); @@ -202,68 +246,63 @@ fn drawings_from(mut step: Arc, now: &Document) -> Arc { } fn checkpoint(s: &mut Session, _p: &Value) -> Result { - Ok(json!({"checkpoint": s.checkpoint()})) + let checkpoint = s.checkpoint(); + reply("edit.checkpoint", crate::schema::edit::CheckpointResult { checkpoint, restored: None, param_warnings: Vec::new() }) } fn restore_checkpoint(s: &mut Session, p: &Value) -> Result { let cmd = "edit.restore_checkpoint"; let id = p.get("checkpoint").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`checkpoint` must be an id from edit.checkpoint"))?; + let done = + |restored: bool| reply(cmd, crate::schema::edit::CheckpointResult { checkpoint: id, restored: Some(restored), param_warnings: Vec::new() }); if bool_(p, "forget") == Some(true) { s.drop_checkpoint(id); - return Ok(json!({"checkpoint": id, "restored": false})); + return done(false); } s.restore_checkpoint(id)?; - Ok(json!({"checkpoint": id, "restored": true})) + done(true) } fn compute_all(s: &mut Session, _p: &Value) -> Result { + let validation = s.validation(); s.model = solidcraft_doc::Model::new(); + s.set_validation(validation); s.refresh(); let errors = s.model.results.iter().filter(|r| r.error.is_some()).count(); Ok(json!({"features": s.model.results.len(), "errors": errors})) } -fn feature_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result { - let key = match v { - Some(Value::Number(n)) => n.to_string(), - Some(Value::String(x)) => x.clone(), - _ => return Err(bad(cmd, "`feature` must be an id or name")), - }; - s.doc.find_feature(&key).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{key}`"))) +pub(super) fn feature_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result { + match v { + Some(Value::Number(n)) => n.as_u64().and_then(|id| s.doc.feature(id)).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{n}`"))), + Some(Value::String(name)) => s.doc.resolve_feature_name(name).map(|f| f.id).map_err(|e| bad(cmd, e.to_string())), + _ => Err(bad(cmd, "`feature` must be an id or name")), + } } fn delete(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.delete"; - // The features are named or numbered, and both kinds can sit in one list. - let mut keys = name_or_id_list(cmd, p, "features")?; - if let Some(f) = p.get("feature") { - keys.push(match f { - Value::Number(n) => n.to_string(), - Value::String(x) => x.clone(), - _ => String::new(), - }); - } + // Resolve every key against the same timeline. A cascade or a repeated key must never + // redirect a later delete to another feature that happens to match after the first one. + let keys = name_or_id_values(cmd, p, "features")?; + let mut ids = keys.iter().chain(p.get("feature")).map(|v| feature_id(s, Some(v), cmd)).collect::>>()?; let groups = group_ids(s, p, false, cmd)?; - if keys.is_empty() && groups.is_empty() { + if ids.is_empty() && groups.is_empty() { return Err(bad(cmd, "`features` must list features, or `groups` timeline folders")); } // A folder goes with its features and nested folders, its features in timeline order. let (folders, contents) = group_tree(&s.doc, &groups); let joints = group_joint_ids(&s.doc, &groups); - keys.extend(s.doc.features.iter().filter(|f| contents.contains(&f.id)).map(|f| f.id.to_string())); + ids.extend(s.doc.features.iter().filter(|f| contents.contains(&f.id)).map(|f| f.id)); // Features that work now; any of them failing after the delete is reported (a later // feature that names a deleted body, #267). let worked: std::collections::BTreeSet = s.model.results.iter().filter(|r| r.error.is_none() && !r.skipped).map(|r| r.id).collect(); super::joints::delete_joints(s.doc_mut(), &joints); let mut gone = Vec::new(); - for k in keys { - let Some(id) = s.doc.find_feature(&k).map(|f| f.id) else { - if gone.is_empty() { - return Err(bad(cmd, format!("no feature `{k}`"))); - } - continue; - }; - gone.extend(s.doc_mut().delete_feature(id)?); + for id in ids { + if s.doc.feature(id).is_some() { + gone.extend(s.doc_mut().delete_feature(id)?); + } } if !folders.is_empty() { s.doc_mut().timeline_groups.retain(|group| !folders.contains(&group.id)); @@ -1177,10 +1216,9 @@ fn inspect_feature(s: &mut Session, p: &Value) -> Result { let rolled_back = s.doc.features.iter().position(|x| x.id == id).is_some_and(|i| i >= marker); let r = s.model.result(id); Ok(json!({ - "id": f.id, "name": f.name, "type": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back, + "id": f.id, "name": f.name, "type": f.kind.kind_key(), "type_name": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back, "definition": def, "omitted": omitted, "inputs": inputs, "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone()), - "boolean_diagnostics": r.map(|r| &r.boolean_diagnostics), })) } @@ -1197,7 +1235,10 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { resolve_feature_names(&mut v, &s.doc, cmd)?; let mut nf: Feature = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("invalid feature: {e}")))?; nf.id = f.id; - if let (FeatureKind::Extrude { extent: old, .. }, FeatureKind::Extrude { extent: new, .. }) = (&f.kind, &mut nf.kind) + // A one-sided extrude made symmetric takes the convention a new one would: its old marker + // never read a symmetric distance. + if let (FeatureKind::Extrude { extent: old, .. }, FeatureKind::Extrude { extent: new, .. }) + | (FeatureKind::SurfaceExtrude { extent: old, .. }, FeatureKind::SurfaceExtrude { extent: new, .. }) = (&f.kind, &mut nf.kind) && old.direction != solidcraft_doc::Direction::Symmetric && new.direction == solidcraft_doc::Direction::Symmetric && set.get("extent").and_then(|e| e.get("convention")).is_none() @@ -1267,7 +1308,7 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { } // New face points: their faces' names now. if nf.kind.face_points() != f.kind.face_points() { - nf.face_names = solidcraft_doc::face_point_names(&s.doc, &s.model.state_before(id), &nf.kind, nf.component); + nf.face_names = solidcraft_doc::face_point_names(&s.doc, &s.model.state_before(id), &nf.kind, nf.component)?; } if let Some(slot) = s.doc_mut().feature_mut(id) { *slot = nf; @@ -1279,6 +1320,65 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { Ok(json!({"feature": id, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored})) } +/// Complete a partial script pick without changing the stored selection type or reinterpreting +/// an existing index-and-point pair. Unlike Measure, selection keeps the exact face/edge index: +/// it must not merge a cylinder's patches or a circular rim's arcs into a different item. +fn selection_item(s: &Session, value: Value) -> Result { + use solidcore_record::Vec3; + + let kind = value.get("type").and_then(Value::as_str); + if !matches!(kind, Some("face" | "edge")) || (value.get("index").is_some() && value.get("point").is_some()) { + return serde_json::from_value(value).map_err(|e| bad("select.set", e.to_string())); + } + let face = kind == Some("face"); + #[derive(serde::Deserialize)] + struct Pick { + body: String, + index: Option, + point: Option, + } + let Pick { body, index, point } = serde_json::from_value(value).map_err(|e| bad("select.set", e.to_string()))?; + let state = s.world_state()?; + let b = state.body(&body).ok_or_else(|| bad("select.set", format!("no body `{body}`")))?; + let missing = || bad("select.set", format!("no {} of `{body}` at the given index or point", if face { "face" } else { "edge" })); + let (index, point) = match (index, point) { + (Some(index), None) => { + let point = if face { + solidcraft_doc::naming::face_spot(b, index).map(|spot| spot.point) + } else { + let mesh = b.mesh(); + mesh.edges.get(index).and_then(|edge| match edge.as_slice() { + [a, b] => Some(a.lerp(*b, 0.5)), + // Use a sample on the curve, not the midpoint of a chord inside it. + points if points.len() > 2 => points.get(points.len() / 2).copied(), + _ => None, + }) + }; + (index, point.filter(|p| p.is_finite()).ok_or_else(missing)?) + } + (None, Some(point)) if point.is_finite() => { + let index = if face { + solidcraft_doc::appearance::face_index_at(b, point) + } else { + let mesh = b.mesh(); + mesh.edges + .iter() + .enumerate() + .filter_map(|(index, edge)| { + let distance = + edge.windows(2).filter_map(|w| Some(point.dist_to_segment(*w.first()?, *w.get(1)?))).fold(f64::INFINITY, f64::min); + (distance <= solidcraft_doc::appearance::pick_tolerance(b)).then_some((index, distance)) + }) + .min_by(|(_, a), (_, b)| a.total_cmp(b)) + .map(|(index, _)| index) + }; + (index.ok_or_else(missing)?, point) + } + _ => return Err(bad("select.set", "a face or edge needs an index or a finite point")), + }; + Ok(if face { Sel::Face { body, index, point } } else { Sel::Edge { body, index, point } }) +} + fn select_set(s: &mut Session, p: &Value) -> Result { let items = p.get("items").and_then(Value::as_array).cloned().unwrap_or_default(); if items.len() > 10_000 { @@ -1286,9 +1386,20 @@ fn select_set(s: &mut Session, p: &Value) -> Result { } let mut sel: Vec = Vec::new(); for it in items { - let one: Sel = serde_json::from_value(it).map_err(|e| bad("select.set", e.to_string()))?; - if let Sel::Occurrence { path } = &one { - s.occurrence_bodies(path, true).map_err(|e| bad("select.set", e.to_string()))?; + let one = selection_item(s, it)?; + match &one { + Sel::Occurrence { path } => { + s.occurrence_bodies(path, true).map_err(|e| bad("select.set", e.to_string()))?; + } + // A selection may not name a body that isn't there: left selected it would delete + // nothing, or the next body to take that name (#9737). + other => { + if let Some(name) = other.body_name() + && s.world_state()?.body(name).is_none() + { + return Err(bad("select.set", format!("no body `{name}`"))); + } + } } if let Sel::Drawing { drawing, object } = &one && !s.selectable_in_drawing(*drawing, *object) @@ -1306,7 +1417,7 @@ fn select_set(s: &mut Session, p: &Value) -> Result { s.selection.push(x); } } - s.revision += 1; + s.refresh_display(); Ok(json!({"selected": s.selection.len()})) } @@ -1341,7 +1452,7 @@ fn select_same_look(s: &mut Session, p: &Value) -> Result { _ => None, }) .ok_or_else(|| bad("select.same_look", "select an object or face"))?; - let state = s.world_state(); + let state = s.world_state()?; let body = state.body(name).ok_or_else(|| bad("select.same_look", "unknown object"))?; let face = request.face.or(match selected { Some(Sel::Face { body, index, .. }) if request.body.is_none() && body == name => Some(*index), @@ -1363,7 +1474,7 @@ fn select_same_look(s: &mut Session, p: &Value) -> Result { fn select_clear(s: &mut Session, _p: &Value) -> Result { s.selection.clear(); - s.revision += 1; + s.refresh_display(); Ok(json!({"selected": 0})) } @@ -1398,11 +1509,21 @@ pub(super) fn newly_broken_in_history( let whole = |doc: &solidcraft_doc::Document, model: &solidcraft_doc::Model| { let mut doc = doc.clone(); doc.marker = None; - let mut model = model.clone(); - model.evaluate(&doc); - model + // A copy keeps nothing on its own: it keeps what the model keeps, so a delete checked + // ahead finds this build there when it runs (#9917). + let mut copy = model.clone(); + copy.keep(model.kept()); + copy.evaluate(&doc); + copy }; - newly_broken(&whole(before_doc, before), &whole(after_doc, after)) + // Only a feature that fails after the change can be newly broken: when none does, the + // history before it needn't be built again (#9917: each build ran every boolean after the + // marker, half a minute on a large design). + let after = whole(after_doc, after); + if after.results.iter().all(|r| r.error.is_none()) { + return Vec::new(); + } + newly_broken(&whole(before_doc, before), &after) } /// Whether `after_doc` differs from `before_doc` only in sketch constraints and dimensions (and @@ -1669,7 +1790,7 @@ fn redefine(s: &mut Session, p: &Value) -> Result { && matches!(cid, "solid.extrude" | "surface.extrude") && let Some(parameters) = params.as_object_mut() { - let convention = if cid == "surface.extrude" || extent.direction == solidcraft_doc::Direction::Symmetric { + let convention = if extent.direction == solidcraft_doc::Direction::Symmetric { extent.convention } else { solidcraft_doc::ExtrudeConvention::TotalDistance @@ -1682,6 +1803,15 @@ fn redefine(s: &mut Session, p: &Value) -> Result { { parameters.entry("convention").or_insert_with(|| json!(convention)); } + // A thread saved before holes were sized by their nominal diameter keeps the size it had + // when it is edited without naming one. + if let FeatureKind::Thread { old_auto_size: true, .. } = &old.kind + && cid == "solid.thread" + && let Some(parameters) = params.as_object_mut() + && parameters.get("designation").is_none_or(|d| d.is_null() || d.as_str().is_some_and(|d| d.trim().is_empty())) + { + parameters.entry("old_auto_size").or_insert_with(|| json!(true)); + } // Members keep their names through an edit, unless it gives them another name. if let FeatureKind::FrameMember { names, body_name, .. } = &old.kind && cid == "frame.member" @@ -1717,6 +1847,11 @@ fn redefine(s: &mut Session, p: &Value) -> Result { } trial.doc_mut().marker = Some(idx + 1); trial.refresh(); + // The edited feature keeps its name. Its temporary replacement needs a fresh one while + // the original remains in the trial as a placeholder (including construction planes). + if let Some(parameters) = params.as_object_mut() { + parameters.remove("name"); + } let r = spec.run_nested(&mut trial, ¶ms)?; let made = r.get("feature").and_then(Value::as_u64).ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?; let mut new = trial.doc.feature(made).cloned().ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?; @@ -1728,6 +1863,21 @@ fn redefine(s: &mut Session, p: &Value) -> Result { { *after = before.clone(); } + // A perforation keeps its outline through an edit that names no sketch (the Perforate dialog has no outline). + if let (FeatureKind::SheetPerforate { sketch: Some(before), profiles: picked, .. }, FeatureKind::SheetPerforate { sketch, profiles, .. }) = + (&old.kind, &mut new.kind) + && sketch.is_none() + && params.get("sketch").is_none() + { + *sketch = Some(*before); + *profiles = picked.clone(); + } + // An old design's Join To Object keeps the body it runs to apart through an edit (#8151). + if let (FeatureKind::Extrude { extent: before, .. }, FeatureKind::Extrude { extent: after, .. }) = (&old.kind, &mut new.kind) + && after.to.is_some() + { + after.to_body_apart = before.to_body_apart; + } // A boundary surface's loop of sketch curves and its curve network are one command's two // forms: an edit may turn one into the other. let boundary = |k: &FeatureKind| matches!(k, FeatureKind::SurfaceBoundary { .. } | FeatureKind::SurfaceNetwork { .. }); @@ -1755,6 +1905,11 @@ fn redefine(s: &mut Session, p: &Value) -> Result { }) .collect(); trial.doc_mut().features.retain(|f| f.id != made); + // Made right after the edited feature, the trial joined the timeline folder holding both: + // it leaves it too, or its id stays there, and is given out again below (#9373). + for group in &mut trial.doc_mut().timeline_groups { + group.features.retain(|f| *f != made); + } let added = trial.doc.features.len().saturating_sub(s.doc.features.len()); trial.doc_mut().marker = s.doc.marker.map(|marker| if marker > idx { marker.saturating_add(added) } else { marker }); if made == s.doc.next_id && trial.doc.next_id == made.saturating_add(1) { diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index bbab9166e..3d750a765 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -8,6 +8,107 @@ fn run(s: &mut Session, id: &str, params: Value) -> Value { s.execute(id, ¶ms).unwrap_or_else(|e| panic!("{id} {params}: {e}")) } +#[test] +fn select_geometry_resolves_points_and_indices_without_changing_history() { + use solidcore_record::Vec3; + + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"body_name":"Block", "corner":[20,30,40], "length":10, "width":10, "height":10})); + let before = (s.doc.to_json(), s.undo.len()); + for (kind, point) in [("face", Vec3::new(25.0, 35.0, 50.0)), ("edge", Vec3::new(25.0, 30.0, 50.0))] { + assert_eq!(run(&mut s, "select.set", json!({"items":[{"type":kind,"body":"Block","point":point}]}))["selected"], 1); + let index = match &s.selection[0] { + Sel::Face { index, point: actual, .. } | Sel::Edge { index, point: actual, .. } => { + assert_eq!(*actual, point); + *index + } + other => panic!("unexpected selection: {other:?}"), + }; + let measured = s.measure_items(&s.selection); + let (field, expected) = if kind == "face" { ("area_mm2", 100.0) } else { ("length_mm", 10.0) }; + assert!((measured["items"][0][field].as_f64().unwrap() - expected).abs() < 1e-9, "{measured}"); + run(&mut s, "select.set", json!({"items":[{"type":kind,"body":"Block","index":index}]})); + let complete = serde_json::to_value(&s.selection[0]).unwrap(); + assert_eq!(complete["index"], index); + let mut point_only = complete.clone(); + point_only.as_object_mut().unwrap().remove("index"); + run(&mut s, "select.set", json!({"items":[point_only]})); + assert_eq!(serde_json::to_value(&s.selection[0]).unwrap(), complete); + } + assert_eq!((s.doc.to_json(), s.undo.len()), before); +} + +#[test] +fn select_geometry_curved_picks_round_trip_and_add_without_duplicates() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"body_name":"Round", "radius":5, "height":10})); + for (kind, point) in [("face", [3, 4, 5]), ("edge", [3, 4, 10])] { + run(&mut s, "select.set", json!({"items":[{"type":kind,"body":"Round","point":point}]})); + let index = serde_json::to_value(&s.selection[0]).unwrap()["index"].clone(); + run(&mut s, "select.set", json!({"items":[{"type":kind,"body":"Round","index":index}]})); + let complete = serde_json::to_value(&s.selection[0]).unwrap(); + let pick: solidcore_record::Vec3 = serde_json::from_value(complete["point"].clone()).unwrap(); + assert!((pick.x.hypot(pick.y) - 5.0).abs() < 1e-6, "the inferred point lies on the cylinder: {complete}"); + let mut partial = complete.clone(); + partial.as_object_mut().unwrap().remove("index"); + run(&mut s, "select.set", json!({"items":[partial, complete],"add":true})); + assert_eq!(s.selection.len(), 1); + assert_eq!(serde_json::to_value(&s.selection[0]).unwrap(), complete); + let measured = s.measure_items(&s.selection); + assert!((measured["items"][0]["diameter"].as_f64().unwrap() - 10.0).abs() < 1e-6, "{measured}"); + } +} + +#[test] +fn select_geometry_uses_the_placed_body_in_world_coordinates() { + let mut s = Session::default(); + let created = run(&mut s, "component.create", json!({"name":"Part"})); + run(&mut s, "solid.box", json!({"body_name":"Block", "length":2, "width":3, "height":4})); + let second = run(&mut s, "occurrence.copy", json!({"occurrence":created["occurrence"]}))["occurrence"].as_u64().unwrap(); + run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[10,20,0],"axis":[0,0,1],"angle":"90 deg","capture":false})); + let name = s.occurrence_placement(&[second]).unwrap().bodies[0].world.clone(); + for (kind, point) in [("face", [8.5, 21.0, 4.0]), ("edge", [8.5, 20.0, 4.0])] { + run(&mut s, "select.set", json!({"items":[{"type":kind,"body":name,"point":point}]})); + let complete = serde_json::to_value(&s.selection[0]).unwrap(); + assert_eq!(complete["body"], name); + run(&mut s, "select.set", json!({"items":[{"type":kind,"body":name,"index":complete["index"]}]})); + let inferred = serde_json::to_value(&s.selection[0]).unwrap(); + let pick: solidcore_record::Vec3 = serde_json::from_value(inferred["point"].clone()).unwrap(); + assert!((pick.z - 4.0).abs() < 1e-9 && (7.0..=10.0).contains(&pick.x) && (20.0..=22.0).contains(&pick.y), "{inferred}"); + assert!(s.execute("select.set", &json!({"items":[{"type":kind,"body":name,"point":[1,1,4]}]})).is_err()); + assert_eq!(serde_json::to_value(&s.selection[0]).unwrap(), inferred); + } +} + +#[test] +fn select_geometry_invalid_partial_picks_leave_selection_and_revision_unchanged() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"body_name":"Block", "length":10, "width":10, "height":10})); + run(&mut s, "select.set", json!({"items":[{"type":"body","name":"Block"}]})); + let before = (s.selection.clone(), s.revision, s.undo.len()); + for kind in ["face", "edge"] { + for fields in [ + json!({}), + json!({"index":999999}), + json!({"index":-1}), + json!({"index":"0"}), + json!({"point":[500,500,500]}), + json!({"point":[1,2]}), + json!({"point":[1e308,1e308,1e308]}), + ] { + let mut item = json!({"type":kind,"body":"Block"}); + item.as_object_mut().unwrap().extend(fields.as_object().unwrap().clone()); + for add in [false, true] { + let result = s.execute("select.set", &json!({"items":[{"type":"face","body":"Block","point":[5,5,10]},item],"add":add})); + assert!(result.is_err(), "accepted {item}"); + assert_eq!((s.selection.clone(), s.revision, s.undo.len()), before, "{item}"); + } + } + } + assert!(s.execute("select.set", &json!({"items":[{"type":"face","body":"Missing","point":[5,5,10]}]})).is_err()); + assert_eq!((s.selection, s.revision, s.undo.len()), before); +} + #[test] fn history_playback_is_a_typed_display_request_without_history_edits() { let mut s = Session::default(); @@ -148,9 +249,11 @@ fn redefining_a_fillet_as_g2_on_sloped_ends_survives_undo_and_reopen() { let volume = |s: &Session| { let bodies = &s.model.state().bodies; assert_eq!(bodies.len(), 1); - bodies.first().unwrap().body.tessellate(0.0001).unwrap().measure().volume + bodies.first().unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.0001)).unwrap().measure().volume }; - let expected = |r: f64| 12000.0 - 40.0 * 113.0 / 756.0 * r.powi(2) + 13711.0 / 486486.0 * r.powi(3); + // The curvature section at its equal-area thumbweight removes (1 - pi/4) r² at the square + // corner, first moment 0.0474559669443 r³ (Green's theorem on the section). + let expected = |r: f64| 12000.0 - 40.0 * (1.0 - std::f64::consts::FRAC_PI_4) * r.powi(2) + 0.0474559669443 * r.powi(3); let actual = volume(&s); assert!((actual - expected(5.0)).abs() < 0.05, "{actual} vs {}", expected(5.0)); let edited = s.doc.clone(); @@ -388,17 +491,17 @@ fn redefine_keeps_allocator_above_component_and_occurrence_ids() { assert!( matches!(&s.doc.features[combine_index + 1].kind, solidcraft_doc::FeatureKind::BodyTransfer { bodies, to, .. } if bodies == &["Base"] && *to == destination) ); - assert!((solidcraft_kernel::measure(&s.world_state().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); - assert_eq!(s.world_state().bodies.len(), 1); + assert!((solidcraft_kernel::measure(&s.world_state().unwrap().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); run(&mut s, "timeline.rollback", json!({"position":combine_index + 1})); - assert_eq!(s.world_state().body("Base").unwrap().component, 0, "the result transfers only AFTER Combine"); + assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, 0, "the result transfers only AFTER Combine"); run(&mut s, "edit.undo", json!({})); run(&mut s, "edit.undo", json!({})); assert_eq!(*s.doc, *original); run(&mut s, "edit.redo", json!({})); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert_eq!(reopened.world_state().body("Base").unwrap().component, destination); - assert!((solidcraft_kernel::measure(&reopened.world_state().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); + assert_eq!(reopened.world_state().unwrap().body("Base").unwrap().component, destination); + assert!((solidcraft_kernel::measure(&reopened.world_state().unwrap().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); let max_id = s.doc.components.iter().map(|c| c.id).chain(s.doc.occurrences.iter().map(|o| o.id)).chain(s.doc.features.iter().map(|f| f.id)).max().unwrap(); assert!(s.doc.next_id > max_id); @@ -430,7 +533,7 @@ fn redefine_cannot_publish_a_second_transfer_that_breaks_existing_ownership() { assert_eq!(s.pending_moves, pending); } let reopened = Session::new(solidcraft_doc::Document::from_json(&full).unwrap()); - assert_eq!(reopened.world_state().body("Base").unwrap().component, reopened.doc.find_component("Original").unwrap()); + assert_eq!(reopened.world_state().unwrap().body("Base").unwrap().component, reopened.doc.find_component("Original").unwrap()); assert!(reopened.doc.features.iter().all(|feature| reopened.model.result(feature.id).is_some_and(|result| result.error.is_none()))); } @@ -542,6 +645,29 @@ fn timeline_folders_are_command_backed_saved_undoable_and_follow_feature_ids() { assert!(s.doc.timeline_groups.is_empty()); } +/// #9373: editing a feature inside a timeline folder left the id of the edit's trial feature in +/// the folder and gave that id out again, so every edit there added it once more, and a feature +/// made later took it and was listed twice: the saved design then would not open. Edited, the +/// folder keeps its own features, once each, and the design opens again. +#[test] +fn editing_a_feature_inside_a_folder_leaves_the_folder_as_it_was() { + let mut s = Session::default(); + for (name, height) in [("Base", 10), ("Post", 20), ("Pin", 30)] { + run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": height, "operation": "new", "name": name})); + } + let ids: Vec = s.doc.features.iter().map(|f| f.id).collect(); + run(&mut s, "timeline.group", json!({"name": "Parts", "features": ids})); + for width in [5, 6, 7] { + run(&mut s, "timeline.redefine", json!({"feature": "Post", "command": "solid.box", "params": {"length": 4, "width": width, "height": 20}})); + } + assert_eq!(s.doc.timeline_groups[0].features, ids, "no trial feature is left in the folder"); + let made = + run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "operation": "new", "name": "Later"}))["feature"].as_u64().unwrap(); + assert!(!s.doc.timeline_groups[0].features.contains(&made), "a feature made after the folder is not in it"); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.timeline_groups, s.doc.timeline_groups); +} + #[test] fn timeline_reorders_selected_features_as_one_block_and_removes_folders_in_one_step() { let mut s = Session::default(); @@ -774,6 +900,45 @@ fn feature_names(s: &Session) -> Vec { s.doc.features.iter().map(|feature| feature.name.clone()).collect() } +#[test] +fn timeline_keys_distinguish_numeric_names_from_ids() { + let mut s = four_boxes(); + let id = s.doc.find_feature("Second").unwrap().id; + let named = s.doc.find_feature("Third").unwrap().id; + let key = id.to_string(); + run(&mut s, "timeline.rename", json!({"feature": named, "name": key})); + + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": key}))["id"], named); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": id}))["id"], id); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": named.to_string()}))["id"], named); + assert_eq!(run(&mut s, "timeline.copy", json!({"features": [key, id]}))["copied"], json!(["Second", key])); + + // Resolve the whole request before deleting: a repeated name must not turn into an id + // after the first deletion removes the feature with that name. + assert_eq!(run(&mut s, "timeline.delete", json!({"features": [key, key]}))["deleted"], json!([named])); + assert!(s.doc.feature(id).is_some()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "selection.delete", json!({"items": [Sel::Feature { id }]})); + assert!(s.doc.feature(id).is_none()); + assert!(s.doc.feature(named).is_some()); +} + +#[test] +fn timeline_keys_prefer_exact_case_and_refuse_an_ambiguous_fallback() { + let mut s = four_boxes(); + let second = s.doc.find_feature("Second").unwrap().id; + let third = s.doc.find_feature("Third").unwrap().id; + run(&mut s, "timeline.rename", json!({"feature": third, "name": "second"})); + + let before = s.doc.clone(); + let error = s.execute("timeline.delete", &json!({"features": ["First", "SECOND"]})).unwrap_err().to_string(); + assert!(error.contains("ambiguous"), "{error}"); + assert_eq!(s.doc, before); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": "Second"}))["id"], second); + assert_eq!(run(&mut s, "timeline.suppress", json!({"feature": "second"}))["feature"], third); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": "FIRST"}))["name"], "First"); +} + /// `timeline.delete {groups}` deletes a folder with its features and nested folders in one undo /// step; other folders and features stay, and `timeline.ungroup` still keeps the features (#7219). #[test] @@ -1069,6 +1234,57 @@ fn counted_body_names_stay_when_the_timeline_changes() { assert_eq!(bodies(&s), named(&[("Body2", "B"), ("Body3", "C"), ("Body4", "E")])); } +/// Pinning reads each feature's bodies once and keeps them with the state it read them from; +/// the names it pins and reserves, and the fingerprints it leaves, are those of reading every +/// feature's bodies again: random boxes (named and counted), moves, suppressions, deletions, +/// reorders, undo and redo, against a session that forgets what it read before every command and +/// against fingerprinting the whole timeline again. +#[test] +fn pinning_with_the_bodies_it_read_before_pins_as_reading_them_again() { + let (mut kept, mut fresh) = (Session::default(), Session::default()); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n as u64) as usize + }; + for step in 0..60 { + let features: Vec = kept.doc.features.iter().map(|f| f.name.clone()).collect(); + let counted: Vec = kept.model.state().bodies.iter().map(|b| b.name.clone()).collect(); + let pick = |names: &[String], k: usize| names.get(k % names.len().max(1)).cloned().unwrap_or_default(); + let x = 15 * step; + let (id, params) = match next(9) { + _ if features.len() < 3 => ("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})), + 0 | 1 => ("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})), + 2 => ("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "body_name": format!("Named {step}")})), + 3 => ("solid.move", json!({"bodies": [pick(&counted, next(64))], "translate": [0, 5, 0]})), + 4 => ("timeline.suppress", json!({"feature": pick(&features, next(64)), "suppressed": next(2) == 0})), + 5 => ("timeline.delete", json!({"feature": pick(&features, next(64))})), + 6 => ("timeline.reorder", json!({"feature": pick(&features, next(64)), "position": next(features.len()), "active": true})), + 7 => ("edit.undo", json!({})), + _ => ("edit.redo", json!({})), + }; + fresh.made_bodies.clear(); + let (a, b) = (kept.execute(id, ¶ms), fresh.execute(id, ¶ms)); + assert_eq!(a.is_ok(), b.is_ok(), "step {step}: {id} {params}"); + assert_eq!(kept.doc.to_json(), fresh.doc.to_json(), "step {step}: {id} {params}"); + // The fingerprints match the design as fingerprinting the whole timeline again makes them + // match it: evaluating it again reuses the same results (all, as a rule; the others are + // computed or taken from the cache the copies share). + let again = |model: &solidcraft_doc::Model| { + let mut m = model.clone(); + m.evaluate(&kept.doc); + m.last_recomputed + m.last_restored + }; + let mut full = kept.model.clone(); + full.refingerprint(&kept.doc); + assert_eq!(again(&kept.model), again(&full), "step {step}: {id} {params}"); + assert_eq!(again(&kept.model), again(&fresh.model), "step {step}: {id} {params}"); + } + assert!(kept.doc.features.len() > 5 && !kept.doc.reserved_body_names.is_empty()); +} + /// The value at a dotted path of a definition. fn dotted<'a>(def: &'a Value, path: &str) -> &'a Value { path.split('.').fold(def, |v, k| &v[k]) @@ -1299,8 +1515,8 @@ fn select_same_look_uses_resolved_looks_without_document_history_edits_and_refus let history = (s.undo.len(), s.redo.len(), s.evaluations); run(&mut s, "select.same_look", json!({"body":"A"})); assert_eq!(s.selection.len(), 3); - let point = solidcraft_geom::Vec3::new(40.0, 5.0, 5.0); - let face = solidcraft_doc::appearance::face_index_at(s.world_state().body("C").unwrap(), point).unwrap(); + let point = solidcore_record::Vec3::new(40.0, 5.0, 5.0); + let face = solidcraft_doc::appearance::face_index_at(s.world_state().unwrap().body("C").unwrap(), point).unwrap(); run(&mut s, "select.set", json!({"items":[Sel::Face {body:"C".into(),index:face,point}]})); run(&mut s, "select.same_look", json!({})); assert_eq!(s.selection.len(), 3); @@ -1368,11 +1584,13 @@ fn timeline_joint_folders_are_mixed_saved_and_undoable() { let saved = s.doc.to_json(); let reopened = solidcraft_doc::Document::from_json(&saved).unwrap(); assert_eq!(reopened.to_json(), saved); + // A folder naming a joint the design doesn't have, or one twice, opens without that entry + // (#9373). let mut damaged: Value = serde_json::from_str(&saved).unwrap(); damaged["timeline_groups"][0]["joints"] = json!([u64::MAX]); - assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).is_err()); + assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).unwrap().timeline_groups[0].joints.is_empty()); damaged["timeline_groups"][0]["joints"] = json!([joint, joint]); - assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).is_err()); + assert_eq!(solidcraft_doc::Document::from_json(&damaged.to_string()).unwrap().timeline_groups[0].joints, [joint]); let destination = run(&mut s, "timeline.group", json!({"name":"Destination"}))["group"].as_u64().unwrap(); run(&mut s, "timeline.move_to_group", json!({"joints":[joint], "group":destination})); assert!(s.doc.timeline_groups[0].joints.is_empty()); @@ -1437,3 +1655,36 @@ fn timeline_joint_folders_reject_hostile_joint_references_atomically() { } } } + +/// A reference image is shared, not copied, by every edit after it: each undo state holds the +/// design as it was, and a copied image of up to 16 MiB per state would hold gigabytes. +#[test] +fn edits_after_a_canvas_share_its_image_with_every_undo_state() { + let mut s = Session::default(); + let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + png.extend([0, 0, 0, 4, 0, 0, 0, 2, 8, 6, 0, 0, 0, 0, 0, 0, 0]); + png.resize(64 << 10, 0); + run(&mut s, "canvas.insert", json!({"data": solidcraft_doc::canvas::base64_encode(&png), "plane": "XY", "width": 40})); + for i in 0..20 { + run(&mut s, "parameters.add", json!({"name": format!("p{i}"), "expression": "10 mm"})); + } + let image = s.doc.canvases[0].data.as_ptr(); + let copies = s.undo.iter().filter_map(|u| u.doc.canvases.first()).filter(|c| c.data.as_ptr() != image).count(); + assert_eq!(copies, 0, "undo states holding their own copy of the image"); + for _ in 0..20 { + run(&mut s, "edit.undo", json!({})); + } + assert_eq!(s.doc.canvases[0].data.as_ptr(), image, "undo brings back the same image"); + assert_eq!(s.doc.canvases[0].bytes().as_deref(), Some(png.as_slice())); +} + +#[test] +fn assistant_toggle_is_refused_headlessly_without_changing_the_document() { + let mut s = Session::default(); + let before = (s.doc.to_json(), s.undo.len()); + let error = s.execute("ui.assistant", &json!({})).unwrap_err().to_string(); + assert!(error.contains("headless session"), "{error}"); + assert_eq!((s.doc.to_json(), s.undo.len()), before); + let spec = crate::find_command("ui.assistant").unwrap(); + assert_eq!((spec.shortcut, spec.tab, spec.undoable), (Some("Ctrl+Shift+A"), "", false)); +} diff --git a/crates/engine/src/cmd/extrude_convention_tests.rs b/crates/engine/src/cmd/extrude_convention_tests.rs index 09d2a223e..97845aa51 100644 --- a/crates/engine/src/cmd/extrude_convention_tests.rs +++ b/crates/engine/src/cmd/extrude_convention_tests.rs @@ -123,23 +123,74 @@ fn symmetric_extrude_thin_wall_uses_total_distance_and_to_object_remains_one_sid check(&fixture(json!({"to":[0,0,10]})), 0.0, 10.0); } +/// The z range of surface body `name`. +fn sheet_z(s: &Session, name: &str) -> (f64, f64) { + assert!(s.model.results.iter().all(|r| r.error.is_none())); + let st = s.model.state(); + let bounds = st.body(name).unwrap().mesh().bounds(); + (bounds.min.z, bounds.max.z) +} + +fn assert_z(s: &Session, name: &str, lo: f64, hi: f64) { + let (z0, z1) = sheet_z(s, name); + assert!((z0 - lo).abs() < 1e-7 && (z1 - hi).abs() < 1e-7, "{name}: {z0}..{z1}, want {lo}..{hi}"); +} + +/// A symmetric surface extrude reads its distance as a solid one does: the total, split evenly +/// around the start plane, through a redefine and a save. #[test] -fn surface_extrude_shared_extent_retains_its_existing_per_side_semantics() { +fn surface_extrude_symmetric_distance_is_the_total_like_solid_extrude() { let mut s = fixture(json!({})); run(&mut s, "surface.extrude", json!({"sketch":"Square","distance":"10 mm","direction":"symmetric","name":"Sheet","body_name":"Sheet"})); - let check_sheet = |s: &Session| { - let st = s.model.state(); - let bounds = st.body("Sheet").unwrap().mesh().bounds(); - assert!((bounds.min.z + 10.0).abs() < 1e-7 && (bounds.max.z - 10.0).abs() < 1e-7); - }; - check_sheet(&s); + assert_z(&s, "Sheet", -5.0, 5.0); + let FeatureKind::SurfaceExtrude { extent, .. } = &s.doc.find_feature("Sheet").unwrap().kind else { panic!("surface extrude") }; + assert_eq!(extent.convention, ExtrudeConvention::TotalDistance); run( &mut s, "timeline.redefine", json!({"feature":"Sheet","command":"surface.extrude","params":{"sketch":"Square","distance":"10 mm","direction":"symmetric","body_name":"Sheet"}}), ); - check_sheet(&s); - check_sheet(&Session::new(Document::from_json(&s.doc.to_json()).unwrap())); + assert_z(&s, "Sheet", -5.0, 5.0); + assert_z(&Session::new(Document::from_json(&s.doc.to_json()).unwrap()), "Sheet", -5.0, 5.0); + // A one-sided surface extrude made symmetric splits its distance too, as a solid one does. + run(&mut s, "surface.extrude", json!({"sketch":"Square","distance":"10 mm","convention":"legacy_per_side","name":"Wall","body_name":"Wall"})); + assert_z(&s, "Wall", 0.0, 10.0); + run(&mut s, "timeline.edit", json!({"feature":"Wall","set":{"extent":{"direction":"symmetric"}}})); + assert_z(&s, "Wall", -5.0, 5.0); +} + +/// Surface extrudes saved before they matched solid ones stored `legacy_per_side` (or, older +/// still, no marker): they rebuild the distance on each side, and keep it through edits. +#[test] +fn older_symmetric_surface_extrudes_keep_the_distance_on_each_side() { + let mut s = fixture(json!({})); + run( + &mut s, + "surface.extrude", + json!({"sketch":"Square","distance":"10 mm","direction":"symmetric","convention":"legacy_per_side","name":"Sheet","body_name":"Sheet"}), + ); + assert_z(&s, "Sheet", -10.0, 10.0); + let marked: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + let mut unmarked = marked.clone(); + unmarked["format"] = json!("solidcraft/21"); + unmarked.as_object_mut().unwrap().remove("format_pending"); + for f in unmarked["features"].as_array_mut().unwrap() { + if let Some(extent) = f.get_mut("extent").and_then(Value::as_object_mut) { + extent.remove("convention"); + } + } + for saved in [marked, unmarked] { + let mut s = Session::new(Document::from_json(&saved.to_string()).unwrap()); + assert_z(&s, "Sheet", -10.0, 10.0); + run(&mut s, "timeline.edit", json!({"feature":"Sheet","set":{"extent":{"distance":"12 mm"}}})); + assert_z(&s, "Sheet", -12.0, 12.0); + run( + &mut s, + "timeline.redefine", + json!({"feature":"Sheet","command":"surface.extrude","params":{"sketch":"Square","distance":"10 mm","direction":"symmetric","body_name":"Sheet"}}), + ); + assert_z(&s, "Sheet", -10.0, 10.0); + } } /// A second distance goes the other way from the first side (#2700): along the normal when the diff --git a/crates/engine/src/cmd/face.rs b/crates/engine/src/cmd/face.rs index 5571f43ca..adb56c4bc 100644 --- a/crates/engine/src/cmd/face.rs +++ b/crates/engine/src/cmd/face.rs @@ -3,8 +3,10 @@ //! edges become lines, circular edges circles or arcs, anything else a chain of lines. use serde_json::{Value, json}; +use solidcore_record::{Vec2, Vec3}; use solidcraft_doc::{EmbossFace, apply_point, mat_inverse, mat_mul}; -use solidcraft_geom::{Mesh, Vec2, Vec3}; +use solidcraft_geom::Mesh; +use solidcraft_geom::prelude::*; use crate::params::{bad, vec3}; use crate::{Result, Session}; @@ -109,7 +111,7 @@ fn inside_hull(sorted: &[(f64, f64)], q: (f64, f64)) -> bool { /// The outward normal of the planar face at the world point `p`: on the model as the view /// places it (moved components where they are shown). pub(super) fn face_normal_world(s: &Session, p: Vec3) -> Option { - let (m, f, d, _) = face_at_state(&s.world_state(), p, None).ok().flatten()?; + let (m, f, d, _) = face_at_state(&*s.world_state().ok()?, p, None).ok().flatten()?; let tol = (m.bounds().diagonal() * 1e-3).max(1e-3); if d > tol * 10.0 { return None; @@ -149,7 +151,7 @@ pub(super) fn face_ref(s: &Session, v: &Value, body: Option<&str>, cmd: &str) -> match face_ref_form(v).map_err(|why| bad(cmd, why))? { FaceRefForm::Point(p) => Ok(p), FaceRefForm::Name(name) => { - let st = if crate::frames::mapped() { s.model.state() } else { s.world_state() }; + let st = if crate::frames::mapped() { s.model.state() } else { s.world_state()? }; solidcraft_doc::naming::named_face_point(&st, body, name).map_err(|why| bad(cmd, why)) } } @@ -254,7 +256,7 @@ pub(super) fn sketch_of_faces(s: &mut Session, points: &[Vec3], cmd: &str, face_ } let state = s.model.state(); let mut picked = Vec::new(); - let mut common: Option<(String, solidcraft_geom::Plane)> = None; + let mut common: Option<(String, solidcore_record::Plane)> = None; for &point in points { if !point.is_finite() { return Err(bad(cmd, "faces must be finite points")); diff --git a/crates/engine/src/cmd/face_join_tests.rs b/crates/engine/src/cmd/face_join_tests.rs index ca5f61430..ca8ba1ec4 100644 --- a/crates/engine/src/cmd/face_join_tests.rs +++ b/crates/engine/src/cmd/face_join_tests.rs @@ -3,8 +3,9 @@ use crate::Session; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{Document, FeatureKind}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap_or_else(|error| panic!("{command}: {error}")) @@ -28,7 +29,7 @@ fn check_wall(s: &Session, count: usize) { let measure = solidcraft_kernel::measure(&wall.body).unwrap(); assert!((measure.volume - 30_000.0).abs() < 1e-6, "{measure:?}"); assert!(measure.bbox.max.dist(Vec3::new(50.0, 30.0, 20.0)) < 1e-9); - assert!(wall.body.contains(Vec3::new(49.0, 15.0, 10.0))); + assert_eq!(wall.body.classify_point(Vec3::new(49.0, 15.0, 10.0)).unwrap(), solidcraft_kernel::PointClass::Inside); let cap = solidcraft_kernel::measure(&state.body("Cap").unwrap().body).unwrap(); assert!((cap.volume - 6000.0).abs() < 1e-6); assert!(cap.bbox.max.dist(Vec3::new(40.0, 30.0, 25.0)) < 1e-9); @@ -81,16 +82,22 @@ fn face_join_maps_the_picked_instance_body_and_point_together() { run(&mut s, "component.activate", json!({"component":0})); let occurrence = run(&mut s, "occurrence.copy", json!({"component":component,"translate":[100,0,0]}))["occurrence"].as_u64().unwrap(); run(&mut s, "component.activate", json!({"component":component,"occurrence":occurrence})); - let world = s.world_state(); - let body = world.bodies.iter().find(|body| body.body.contains(Vec3::new(139.0, 15.0, 10.0))).unwrap().name.clone(); + let world = s.world_state().unwrap(); + let body = world + .bodies + .iter() + .find(|body| body.body.classify_point(Vec3::new(139.0, 15.0, 10.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + .unwrap() + .name + .clone(); assert_ne!(body, "Wall", "exercise an instance body name"); let result = run(&mut s, "solid.extrude", json!({"face":[140,15,10],"face_body":body,"distance":10,"operation":"join"})); let FeatureKind::Extrude { targets, .. } = &s.doc.feature(result["feature"].as_u64().unwrap()).unwrap().kind else { panic!("extrude") }; assert_eq!(targets, &["Wall"]); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), 2); for point in [Vec3::new(49.0, 15.0, 10.0), Vec3::new(149.0, 15.0, 10.0)] { - assert!(world.bodies.iter().any(|body| body.body.contains(point)), "{point:?}"); + assert!(world.bodies.iter().any(|body| body.body.classify_point(point).unwrap() == solidcraft_kernel::PointClass::Inside), "{point:?}"); } } @@ -230,3 +237,50 @@ fn join_extrude_to_another_body_joins_that_body() { assert!((volume("Base") - 60_000.0).abs() < 1e-6, "the target took the tool: {}", volume("Base")); assert_eq!(state.body("Base").unwrap().body.lumps().map_or(1, |l| l.len()), 1, "one piece"); } + +/// #8151: a design saved before a Join To Object also joined the body it runs to (format 39 and +/// older) keeps that body apart when it opens, so its later features still find it, and an edit +/// of the extrude keeps it apart too. +#[test] +fn join_extrude_to_another_body_saved_before_it_joined_keeps_that_body() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":40,"width":40,"height":10,"body_name":"Base"})); + run(&mut s, "solid.box", json!({"corner":[0,0,40],"length":40,"width":40,"height":20,"body_name":"Target"})); + let sketch = run(&mut s, "sketch.create", json!({"plane":{"face":[20,20,10]}}))["sketch"].as_u64().unwrap(); + let plane = s.model.state().sketch(sketch).unwrap().plane; + let at = |x: f64, y: f64| { + let p = plane.to_local(Vec3::new(x, y, 10.0)); + json!([p.x, p.y]) + }; + run(&mut s, "sketch.rectangle.two_point", json!({"p0": at(10.0,10.0), "p1": at(30.0,30.0)})); + run(&mut s, "sketch.finish", json!({})); + // A feature after the extrude names the body it runs to, as the lid's sketch and moves did. + // Today's join leaves no such body to name, so the move is made first and put last below. + let moved = run(&mut s, "solid.move", json!({"bodies":["Target"],"translate":[0,0,5]}))["feature"].clone(); + let extrude = run(&mut s, "solid.extrude", json!({"sketch":sketch,"to":[20,20,40],"operation":"join","targets":["Base"]}))["feature"].clone(); + let mut saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + let features = saved["features"].as_array_mut().unwrap(); + let at_move = features.iter().position(|f| f["id"] == moved).unwrap(); + let feature = features.remove(at_move); + features.push(feature); + saved["format"] = json!("solidcraft/39"); + saved.as_object_mut().unwrap().remove("format_pending"); + let mut old = Session::new(solidcraft_doc::format::read(&saved.to_string()).unwrap()); + let check = |s: &Session| { + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let state = s.model.state(); + let volume = |name: &str| solidcraft_kernel::measure(&state.body(name).unwrap().body).unwrap().volume; + assert_eq!(state.bodies.len(), 2, "the body the extrude runs to stays its own body"); + assert!((volume("Base") - 28_000.0).abs() < 1e-6, "the base took the tool: {}", volume("Base")); + assert!((volume("Target") - 32_000.0).abs() < 1e-6, "the target is untouched: {}", volume("Target")); + }; + check(&old); + run( + &mut old, + "timeline.redefine", + json!({"feature":extrude,"command":"solid.extrude","params":{"sketch":sketch,"to":[20,20,40],"operation":"join","targets":["Base"]}}), + ); + check(&old); + // The design saves the choice and opens with it again. + check(&Session::new(solidcraft_doc::format::read(&old.doc.to_json()).unwrap())); +} diff --git a/crates/engine/src/cmd/face_tests.rs b/crates/engine/src/cmd/face_tests.rs index c180e83e2..2c0fdfb3e 100644 --- a/crates/engine/src/cmd/face_tests.rs +++ b/crates/engine/src/cmd/face_tests.rs @@ -1,8 +1,9 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use crate::Session; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{Document, FeatureKind, PlaneRef}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use std::f64::consts::PI; fn run(s: &mut Session, command: &str, params: Value) -> Value { @@ -15,10 +16,15 @@ fn check(s: &mut Session, want: f64, hole: bool, height: f64) { let got: f64 = state.bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); // Legacy linked outlines fit tessellated curves; enforce the existing 1e-4 material envelope. assert!((got - want).abs() < want * 1e-4, "{got} vs {want}"); - assert!(state.bodies.iter().any(|b| b.body.contains(Vec3::new(5.0, 5.0, height - 1.0)))); - assert!(!state.bodies.iter().any(|b| b.body.contains(Vec3::new(5.0, 5.0, height + 1.0)))); + assert!(state.bodies.iter().any(|b| b.body.classify_point(Vec3::new(5.0, 5.0, height - 1.0)).unwrap() == solidcraft_kernel::PointClass::Inside)); + assert!(!state.bodies.iter().any(|b| b.body.classify_point(Vec3::new(5.0, 5.0, height + 1.0)).unwrap() == solidcraft_kernel::PointClass::Inside)); if hole { - assert!(!state.bodies.iter().any(|b| b.body.contains(Vec3::new(20.0, 15.0, height - 1.0)))); + assert!( + !state + .bodies + .iter() + .any(|b| b.body.classify_point(Vec3::new(20.0, 15.0, height - 1.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); } } #[test] @@ -48,8 +54,12 @@ fn generated_face_profiles_keep_exact_links_live_after_edit_and_reopen() { let area = 1500.0 - if hole { 25.0 * PI } else { 0.0 }; check(&mut s, area * 35.0, hole, 35.0); let edited = s.model.state(); - assert!(edited.bodies.iter().any(|body| body.body.contains(Vec3::new(49.0, 5.0, 34.0)))); - assert!(!edited.bodies.iter().any(|body| body.body.contains(Vec3::new(51.0, 5.0, 34.0)))); + assert!( + edited.bodies.iter().any(|body| body.body.classify_point(Vec3::new(49.0, 5.0, 34.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); + assert!( + !edited.bodies.iter().any(|body| body.body.classify_point(Vec3::new(51.0, 5.0, 34.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); assert!(edited.sketch(sketch.0).unwrap().sketch.links.iter().all(|link| link.auto_face && !link.lost)); let solved = edited.sketch(sketch.0).unwrap().plane; assert!((solved.origin.z - 25.0).abs() < 1e-6); @@ -67,6 +77,108 @@ fn generated_face_profiles_keep_exact_links_live_after_edit_and_reopen() { } } } +#[test] +fn a_component_extruded_from_another_components_face_moves_independently() { + let mut s = Session::default(); + let reference = run(&mut s, "component.create", json!({"name":"Reference","grounded":false})); + run(&mut s, "solid.box", json!({"length":20,"width":20,"height":20,"name":"Base","body_name":"Stock"})); + run(&mut s, "component.activate", json!({"component":0})); + let part = run(&mut s, "component.create", json!({"name":"Part"})); + run(&mut s, "solid.extrude", json!({"face":[10,10,20],"distance":10,"operation":"new","body_name":"Pad"})); + run(&mut s, "component.activate", json!({"component":0})); + let measure = |s: &mut Session, center: [f64; 3], volume: f64| { + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let got = run(s, "inspect.center_of_mass", json!({"bodies":["Pad"]})); + for (i, want) in center.iter().enumerate() { + assert!((got["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{got}; expected {center:?}"); + } + assert!((got["volume"].as_f64().unwrap() - volume).abs() < 1e-6, "{got}"); + }; + measure(&mut s, [10., 10., 25.], 4000.); + run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[40,0,0],"capture":true})); + measure(&mut s, [50., 10., 25.], 4000.); + run(&mut s, "edit.undo", json!({})); + measure(&mut s, [10., 10., 25.], 4000.); + run(&mut s, "edit.redo", json!({})); + measure(&mut s, [50., 10., 25.], 4000.); + // Moving the reference is an assembly placement, not an edit to its shape. + run(&mut s, "occurrence.move", json!({"occurrence":reference["occurrence"],"translate":[0,50,0],"capture":true})); + measure(&mut s, [50., 10., 25.], 4000.); + // Both the attached plane and its projected outline still follow source dimensions. + run(&mut s, "timeline.edit", json!({"feature":"Base","set":{"length":"30","height":"25"}})); + measure(&mut s, [55., 10., 30.], 6000.); + let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); + measure(&mut reopened, [55., 10., 30.], 6000.); + run(&mut reopened, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[0,0,10],"capture":true})); + measure(&mut reopened, [55., 10., 40.], 6000.); + run(&mut reopened, "timeline.copy", json!({"features":["Base","Sketch1","Extrude1"]})); + run(&mut reopened, "timeline.paste", json!({"translate":[0,0,50]})); + let copy = run(&mut reopened, "inspect.center_of_mass", json!({"bodies":["Pad (2)"]})); + for (i, want) in [55., 10., 90.].iter().enumerate() { + assert!((copy["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{copy}"); + } + assert!((copy["volume"].as_f64().unwrap() - 6000.).abs() < 1e-6); + // Reorganizing the feature definitions must preserve the captured context too. + run(&mut reopened, "component.move_features", json!({"features":["Base","Sketch1","Extrude1"],"component":0})); + measure(&mut reopened, [55., 10., 40.], 6000.); +} + +#[test] +fn a_cross_component_face_profile_keeps_its_rotated_creation_context() { + let mut s = Session::default(); + let source = run(&mut s, "component.create", json!({"name":"Reference","grounded":false})); + run(&mut s, "solid.box", json!({"length":20,"width":20,"height":20,"body_name":"Stock"})); + run(&mut s, "occurrence.move", json!({"occurrence":source["occurrence"],"translate":[30,20,0],"angle":"90 deg"})); + let part = run(&mut s, "component.create", json!({"name":"Part","parent":0})); + run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[-20,10,0],"angle":"-90 deg","capture":false})); + run(&mut s, "solid.extrude", json!({"face":[20,30,20],"distance":10,"operation":"new","body_name":"Pad"})); + assert!(s.pending_moves.is_empty(), "face capture records the author's pending placement"); + run(&mut s, "component.activate", json!({"component":0})); + let center = |s: &mut Session, want: [f64; 3]| { + let got = run(s, "inspect.center_of_mass", json!({"bodies":["Pad"]})); + for (i, want) in want.iter().enumerate() { + assert!((got["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{got}"); + } + assert!((got["volume"].as_f64().unwrap() - 4000.).abs() < 1e-6); + }; + center(&mut s, [20., 30., 25.]); + run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[50,0,5],"angle":"90 deg","capture":false})); + center(&mut s, [20., 20., 30.]); + run(&mut s, "component.capture_position", json!({})); + center(&mut s, [20., 20., 30.]); + let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); + center(&mut reopened, [20., 20., 30.]); +} + +#[test] +fn moving_the_original_face_derived_component_does_not_move_its_copies_backwards() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name":"Reference"})); + run(&mut s, "solid.box", json!({"length":20,"width":20,"height":20})); + let part = run(&mut s, "component.create", json!({"name":"Part","parent":0})); + run(&mut s, "solid.extrude", json!({"face":[10,10,20],"distance":10,"operation":"new","body_name":"Pad"})); + run(&mut s, "component.activate", json!({"component":0})); + let copy = run(&mut s, "occurrence.copy", json!({"component":part["component"],"translate":[0,40,0]})); + run(&mut s, "occurrence.copy", json!({"component":part["component"],"translate":[0,80,0]})); + run(&mut s, "occurrence.move", json!({"occurrence":copy["occurrence"],"translate":[10,0,0],"capture":true})); + let centers = |s: &mut Session, original: [f64; 3]| { + for (body, want) in [("Pad", original), ("Pad (Part:2)", [20., 50., 25.]), ("Pad (Part:3)", [10., 90., 25.])] { + let got = run(s, "inspect.center_of_mass", json!({"bodies":[body]})); + for (i, want) in want.iter().enumerate() { + assert!((got["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{body}: {got}"); + } + assert!((got["volume"].as_f64().unwrap() - 4000.).abs() < 1e-6, "{got}"); + } + }; + centers(&mut s, [10., 10., 25.]); + run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[40,0,0],"capture":true})); + centers(&mut s, [50., 10., 25.]); + let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); + centers(&mut reopened, [50., 10., 25.]); + run(&mut reopened, "occurrence.move", json!({"occurrence":part["occurrence"],"angle":"90 deg","capture":true})); + centers(&mut reopened, [-10., 50., 25.]); +} + #[test] fn internal_capture_does_not_bypass_missing_ambiguous_or_invalid_path_picks() { let mut s = Session::default(); @@ -113,19 +225,24 @@ fn generated_profiles_and_press_pull_convert_rotated_occurrence_picks_once() { run(&mut s, "edit.redo", json!({})); assert_eq!(s.doc.to_json(), after_cut); check(&mut s, area * height, hole, height); - let world = s.world_state(); + let world = s.world_state().unwrap(); let occupied = Vec3::new(35.0, 21.0 - height, 15.0); let absent = Vec3::new(35.0, 19.0 - height, 15.0); - assert!(world.bodies.iter().any(|body| body.body.contains(occupied))); - assert!(!world.bodies.iter().any(|body| body.body.contains(absent))); + assert!(world.bodies.iter().any(|body| body.body.classify_point(occupied).unwrap() == solidcraft_kernel::PointClass::Inside)); + assert!(!world.bodies.iter().any(|body| body.body.classify_point(absent).unwrap() == solidcraft_kernel::PointClass::Inside)); if hole { - assert!(!world.bodies.iter().any(|body| body.body.contains(Vec3::new(50.0, 21.0 - height, 25.0)))); + assert!( + !world + .bodies + .iter() + .any(|body| body.body.classify_point(Vec3::new(50.0, 21.0 - height, 25.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); } let before_volume: f64 = world.bodies.iter().map(|body| solidcraft_kernel::measure(&body.body).unwrap().volume).sum(); let before_bounds: Vec<_> = world.bodies.iter().map(|body| (body.name.clone(), body.mesh().bounds())).collect(); let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); - let after = reopened.world_state(); - assert!(after.bodies.iter().any(|body| body.body.contains(occupied))); + let after = reopened.world_state().unwrap(); + assert!(after.bodies.iter().any(|body| body.body.classify_point(occupied).unwrap() == solidcraft_kernel::PointClass::Inside)); let v: f64 = after.bodies.iter().map(|body| solidcraft_kernel::measure(&body.body).unwrap().volume).sum(); assert!((v - area * height).abs() < area * height * 1e-4); assert!((v - before_volume).abs() < 1e-6); @@ -137,20 +254,23 @@ fn generated_profiles_and_press_pull_convert_rotated_occurrence_picks_once() { } /// A 40 x 30 x 20 box whose top is split at x = 20 and its left half raised 5 by Offset Face: -/// the raised top has no construction certificate and no exact history name yet (#494). +/// the raised top has no construction certificate, and an exact history name from SMLib's +/// offset history. fn raised_half(s: &mut Session, body: &str) { run(s, "solid.box", json!({"length":40,"width":30,"height":20,"body_name":body})); run(s, "solid.split_face", json!({"faces":[[10,15,20]],"plane":{"origin":[20,0,0],"normal":[1,0,0]}})); run(s, "solid.offset_face", json!({"faces":[[10,15,20]],"distance":5})); } +/// Internal capture of a face in another component whose occurrence has an uncaptured move: +/// the raised top has no construction certificate, but its exact history name keeps it, so the +/// capture is an exact (lineage) anchor on that occurrence's path, whose pending position is +/// captured when the attachment is made (`capture_positions`). Capturing changes nothing. #[test] -fn legacy_internal_capture_refuses_an_uncaptured_source_in_another_component() { +fn internal_capture_in_another_component_anchors_an_offset_face_by_its_history_name() { let mut s = Session::default(); let component = run(&mut s, "component.create", json!({"name":"Source","grounded":false})); let occurrence = component["occurrence"].as_u64().unwrap(); - // A face Offset Face raised has no construction certificate or exact history name yet: - // the legacy path. raised_half(&mut s, "Stock"); run(&mut s, "component.activate", json!({"component":0})); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0],"capture":false})); @@ -165,15 +285,41 @@ fn legacy_internal_capture_refuses_an_uncaptured_source_in_another_component() { .into_iter() .find(|face| face.plane_normal.is_some_and(|normal| normal.z > 0.999) && (face.centroid.z - 25.0).abs() < 1e-6) .unwrap(); + assert!(state.body("Stock").unwrap().body.face_plane(end.index).is_none(), "the raised top has no construction certificate"); let before = s.doc.to_json(); - let error = super::super::sketch::face::capture_internal( + let pending = s.pending_moves.clone(); + let plane = super::super::sketch::face::capture_internal( &s, &json!({"face":[40,15,25],"body":"Stock","index":end.index,"path":[occurrence]}), "internal", ) - .unwrap_err(); + .unwrap(); + let anchor = super::super::sketch::face::anchor(&plane).expect("an exact attachment"); + assert_eq!(anchor.target.certificate, Some(solidcraft_doc::config::FaceCertificate::Lineage)); + assert_eq!(anchor.path, vec![occurrence]); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.pending_moves, pending); +} + +/// Extrude from a face in another component whose occurrence has an uncaptured move, where the +/// face has neither a construction certificate nor an exact history name: a half of a box's top +/// that Split Face divided. The face profile would take the legacy path, which can't capture the +/// source's pending position, so the extrude is refused and changes nothing. +#[test] +fn face_extrude_of_a_split_face_in_another_component_refuses_an_uncaptured_source() { + let mut s = Session::default(); + let component = run(&mut s, "component.create", json!({"name":"Source","grounded":false})); + let occurrence = component["occurrence"].as_u64().unwrap(); + run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Stock"})); + run(&mut s, "solid.split_face", json!({"faces":[[10,15,20]],"plane":{"origin":[20,0,0],"normal":[1,0,0]}})); + run(&mut s, "component.activate", json!({"component":0})); + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0],"capture":false})); + let before = s.doc.to_json(); + let pending = s.pending_moves.clone(); + let error = s.execute("solid.extrude", &json!({"face":[40,15,20],"distance":5,"operation":"new"})).unwrap_err(); assert!(error.to_string().contains("capture the source occurrence position"), "{error}"); assert_eq!(s.doc.to_json(), before); + assert_eq!(s.pending_moves, pending); } #[test] @@ -191,10 +337,10 @@ fn repeated_source_face_profile_requires_and_uses_the_exact_active_occurrence() assert_eq!(s.doc.to_json(), before); run(&mut s, "component.activate", json!({"component":cid,"occurrence":occurrence})); run(&mut s, "solid.extrude", json!({"face":[55,5,10],"distance":5,"operation":"new"})); - let state = s.world_state(); + let state = s.world_state().unwrap(); for x in [5.0, 55.0] { - assert!(state.bodies.iter().any(|body| body.body.contains(Vec3::new(x, 5.0, 14.0)))); - assert!(!state.bodies.iter().any(|body| body.body.contains(Vec3::new(x, 5.0, 16.0)))); + assert!(state.bodies.iter().any(|body| body.body.classify_point(Vec3::new(x, 5.0, 14.0)).unwrap() == solidcraft_kernel::PointClass::Inside)); + assert!(!state.bodies.iter().any(|body| body.body.classify_point(Vec3::new(x, 5.0, 16.0)).unwrap() == solidcraft_kernel::PointClass::Inside)); } } diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index a9b53ef0b..311bfe333 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1,19 +1,20 @@ //! Solid feature commands: extrude, revolve, fillet, chamfer, primitives, combine, move. use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{ AxisRef, Direction, Expr, Extent, FeatureKind, Operation, PointExpr, ProfileSel, RailFit, SweepOrientation, SweepRail, ThinSide, ThinWall, - expr::Kind, point_expr, + Touching, expr::Kind, point_expr, }; use solidcraft_doc::{BodyName, FeatureName, SketchId}; use solidcraft_doc::{Dir, FacePick, Position}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use super::{CommandSpec, not_in_sketch}; use crate::params::{UNKNOWN_COMMAND, bad, bool_, expr, expr_problem, req_expr, str_, string_list, string_list_or_default, vec2, vec3}; use crate::schema::features::{ - BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, OffsetPlaneParams, PipeParams, PlaneAtAngleParams, - ScaleParams, SphereParams, TorusParams, + AppliedRadius, BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureNotice, FeatureResult, FilletParams, + FilletResult, NoticeAction, OffsetPlaneParams, PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -29,6 +30,7 @@ const BOUNDING_SOLID_CONTRACT: TypedContract = TypedContrac const SCALE_CONTRACT: TypedContract = TypedContract::new(); const OFFSET_PLANE_CONTRACT: TypedContract = TypedContract::new(); const PLANE_AT_ANGLE_CONTRACT: TypedContract = TypedContract::new(); +const FILLET_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.extrude", "Extrude", crate::checked!("solid.extrude", extrude)) @@ -37,53 +39,55 @@ pub static COMMANDS: &[CommandSpec] = &[ .key("E") .contract(&EXTRUDE_CONTRACT) .output(output_schema_for::) - .params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"), + .params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (how a symmetric distance is read; default total_distance, split evenly around the start plane; legacy_per_side: the distance on each side, as older symmetric extrudes keep); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"), CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") .icon("revolve") - .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | {type: world, axis: X|Y|Z} (as returned by timeline.inspect) | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, targets?, name?, body_name?"), + .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | {type: world, axis: X|Y|Z} (as returned by timeline.inspect) | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, touching?, targets?, name?, body_name?"), CommandSpec::new("solid.sweep", "Sweep", sweep) .at("SOLID", "CREATE") .icon("sweep") - .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, targets?, name?, body_name?"), - CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, targets? (Join excludes hidden bodies from automatic targets; explicit targets or participants may include them), name?, body_name?"), + .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, touching?, targets?, name?, body_name?"), + CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, touching?, targets? (Join excludes hidden bodies from automatic targets; explicit targets or participants may include them), name?, body_name?"), CommandSpec::new("solid.box", "Box", crate::checked!("solid.box", prim_box)) .at("SOLID", "CREATE") .icon("box") .contract(&BOX_CONTRACT) .output(output_schema_for::) - .params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), + .params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.cylinder", "Cylinder", crate::checked!("solid.cylinder", prim_cylinder)) .at("SOLID", "CREATE") .icon("cylinder") .contract(&CYLINDER_CONTRACT) .output(output_schema_for::) - .params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); references?: [{edge: [x,y,z] on a straight edge of the face it stands on, distance: expr}] (at most two, as solid.hole's: the base centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric base only); operation?, targets?: [body], name?, body_name?"), + .params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); references?: [{edge: [x,y,z] on a straight edge of the face it stands on, distance: expr}] (at most two, as solid.hole's: the base centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric base only); operation?, touching?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.sphere", "Sphere", crate::checked!("solid.sphere", prim_sphere)) .at("SOLID", "CREATE") .icon("sphere") .contract(&SPHERE_CONTRACT) .output(output_schema_for::) - .params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), + .params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.torus", "Torus", crate::checked!("solid.torus", prim_torus)) .at("SOLID", "CREATE") .icon("torus") .contract(&TORUS_CONTRACT) .output(output_schema_for::) - .params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), + .params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.cone", "Cone", crate::checked!("solid.cone", prim_cone)) .at("SOLID", "CREATE") .icon("cone") .contract(&CONE_CONTRACT) .output(output_schema_for::) - .params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"), - CommandSpec::new("solid.fillet", "Fillet", fillet) + .params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, touching?, targets?: [body], name?, body_name?"), + CommandSpec::new("solid.fillet", "Fillet", crate::checked!("solid.fillet", fillet)) .at("SOLID", "MODIFY") .icon("fillet") .key("F") - .params("edges: [[x,y,z] point on edge | {body, index}]; radius: expr; body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"), - CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}]; distance: expr; distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"), - CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"), + .contract(&FILLET_CONTRACT) + .output(output_schema_for::) + .params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; a curvature round's corners are always g2 patches, between its own sections; g2: each corner where three or more rounded edges meet, and every edge there is rounded, is set back (1.5 × the radius along each edge unless `setbacks` names it) and filled with a patch meeting the rounds and the faces round it to the second order (curvature-continuous seams, clear of the points where a round's section ends on a face), constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets only; with `corner: g2`, the G2 patch's corners); turn?: mitre|swept (where two rounds turn round a sharp, straight, convex side edge square to both on a plane, such as the rounds along a boss's base at its upright edges: mitre, the default, runs them on to meet in a mitre; swept ends them at the side edge and fills the corner with their section revolved about it, a torus; swept takes type: constant, corner: rolling, no setbacks and fit: exact or reduce, and is refused with the reason where the rounds are unequal or the side edge is concave, curved or tangent); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused, naming the largest that fits; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"), + CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"), + CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"), CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect) .at("SOLID", "CREATE") .icon("pattern_rect") @@ -91,7 +95,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.pattern.circular", "Circular Pattern", pattern_circ) .at("SOLID", "CREATE") .icon("pattern_circ") - .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), + .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} (origin coordinates may be length expressions; the pattern follows them) | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), CommandSpec::new("solid.pattern.path", "Pattern on Path", pattern_path) .at("SOLID", "CREATE") .icon("pattern_path") @@ -101,7 +105,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("hole") .key("H") - .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole: metric major minus pitch or tabulated UNC/UNF, G or Rp cut-tap drill) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" or \"1/4-20 UNC\" (cosmetic); handedness?: right|left (default right, needs thread for left); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"), + .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole, drilled with the tap maker's tabulated drill: ISO metric (a custom metric size: major minus pitch), UNC/UNF, G, Rp, Rc 1/16 to 4, NPT 1/16 to 3; a `diameter` given with it chooses another drill, from the thread's minor diameter to 5% over the tap maker's) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\", \"1/4-20 UNC\", \"G 1/4\", \"Rp 1/4\", \"Rc 1/4\" or \"1/4-18 NPT\" (cosmetic unless modeled); hand?: right|left (the tapped thread's hand; default right; needs thread); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); modeled?: bool (needs thread: the tapped thread cut into the wall, the groove between its teeth, as solid.thread's modelled one; default false: listed only); ease_out?: expr|standard|short (modelled tapped threads: the inner end, towards the bottom, fades out over this length, ISO 3508's runout, standard 2.5 P, short 1.25 P; without it the groove stops square at thread_depth, or clear of a blind hole's bottom); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"), CommandSpec::new("solid.pipe", "Pipe", crate::checked!("solid.pipe", pipe)) .at("SOLID", "CREATE") .icon("pipe") @@ -131,11 +135,11 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.thread", "Thread", thread) .at("SOLID", "CREATE") .icon("thread") - .params("face: [x,y,z] on a cylindrical face; designation?: ISO metric (\"M8\", \"M8x1\"; default: the size that fits); length?: expr (default: the whole face); handedness?: right|left (default right); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body; a shaft thicker than the thread is first turned down to its major diameter over the threaded length"), + .params("face: [x,y,z] on a cylindrical face; form?: metric|trapezoidal|acme|buttress|buttress_asme|bspp|rp|bspt|npt (default: the one `designation` names, else metric; square is refused: no current standard defines it); designation?: the size, as its standard writes it: metric \"M8\", \"M8x1\", \"M16xPh3P1.5\" (ISO 68-1, ISO 261, ISO 965-1); trapezoidal \"Tr20x4\", \"Tr40x14(P7)\" (ISO 2904, ISO 2903); buttress \"S20x4\", \"S40x14(P7)\" (DIN 513, 3°/30°); acme \"1/2-10 ACME\" (ASME B1.5); buttress_asme \"2.5-8 BUTT\" (ASME B1.9, 7°/45°, basic profile; no size table); bspp \"G 1/2\" (ISO 228-1, 55° parallel); rp \"Rp 1/2\" (ISO 7-1's parallel internal thread, 55°, an R screws into it; internal only); bspt \"R 1/2\" external, \"Rc 1/2\" internal (ISO 7-1, 55°, taper 1 in 16); npt \"1/2-14 NPT\" (ASME B1.20.1, 60°, taper 1 in 16) — a taper thread starts at a free end (the pipe end or the hole mouth) with its standard diameter there, and an external one runs its standard length unless `length` or `up_to` says otherwise (default: the standard size that fits the face, a shaft its major diameter, a hole its nominal diameter (a 12 mm hole is M12) or else the size whose tap drill it is); hand?: right|left|both (default right; both: a right- and a left-handed groove crossing); old_auto_size?: bool (an automatic size keeps the rule of designs saved before a hole was sized by its nominal diameter: a 12 mm hole is M14; set on those threads, keeps them as they were when edited); steep_flank?: start|end (buttress only, default end: the steep flank of the screw's teeth faces the thread's end, the way its axis points); starts?: 1..8 (lead = starts x pitch: that many grooves, each a turn's starts-th further round; a designation that gives the lead gives the starts); ease_out?: expr|standard|short (modelled threads: the inner end, away from where the thread starts, fades out over this length (shorter than a turn too), its section moving out of the material as it turns; standard 2.5 P, short 1.25 P per ISO 3508; it lies past the full-form length, up to a shoulder's clearance; at a free end, inside the face; without it the groove stops square there, ending in its own profile; the start never fades: it runs off its free end, plain or chamfered (`tip`)); tip?: none|start|both (modelled external threads: start chamfers the end the thread starts from, which must be free, both each free end the thread reaches, after the groove is cut, ISO 4753's chamfered end, the last teeth tapering into the cone; chamfer_angle?: angle expr to the axis, default 45 deg; chamfer_depth?: expr, radial from the major diameter, default for a metric thread down to the external minor diameter d3 = d - 1.226869 P (ISO 724), the largest ISO 4753 allows; other forms give it); extent?: full|length|up_to (default: length when `length` is given, up_to when `up_to` is, else full: the whole face); length?: expr (from the end the thread starts at); up_to?: [x,y,z] (a point, such as on a shoulder face: the thread runs to its place along the axis) | plane name or {origin, normal} (to where the plane crosses the axis); from?: [x,y,z] near the end of the face the thread starts at (default: the face's only free end, the one with no material past it; else the end the `face` point lies within a third of the face of; a pick in the middle of a face whose ends are alike is refused); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body: past a free end the groove runs out a pitch into the air (or through a chamfer); at a shoulder, a head or a blind hole's bottom it stops with its section clear of it, never cutting into it; a hole as wide as the thread or wider is narrowed to the thread's minor diameter first, and the reply's warning says so; a shaft thicker than the thread is refused with the size to make it, never turned down"), CommandSpec::new("solid.shell", "Shell", shell) .at("SOLID", "MODIFY") .icon("shell") - .params("faces: [[x,y,z] points on the faces to remove, or face names from model.faces]; thickness: expr; direction?: inside|outside|both; tangent_chain?: bool (also open faces joined smoothly to the picked ones); body?"), + .params("faces: [[x,y,z] points on the faces to remove, or face names from model.faces; none: a closed hollow body]; thickness: expr; direction?: inside|outside|both; tangent_chain?: bool (also open faces joined smoothly to the picked ones); body? (needed with no faces when there are several bodies)"), CommandSpec::new("solid.draft", "Draft", draft) .at("SOLID", "MODIFY") .icon("draft") @@ -167,7 +171,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("presspull") .key("Q") .params("face: [x,y,z] and distance: expr (positive adds material, negative cuts), or edges: [[x,y,z]…] and distance (a fillet)"), - CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place)"), + CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place); occurrences?: [occurrence paths, root first] (only with copy: each component is copied as an independent component, as Paste New copies it, and the copy moves by the same translate, axis and angle in the world; the reply lists the copies in occurrences)"), ]; /// Where an extrude starts and which way is positive: a point inside the (first) profile or @@ -221,8 +225,12 @@ const START_PROBE_MM: f64 = 0.1; /// "Goes into a body" is decided where the extrude starts: just past the profile in the /// direction it grows, or halfway along it. With the halfway point alone, a cut dragged far /// past a body's far side read as a Join (#1257). -pub fn auto_operation(s: &Session, p: &Value) -> Option<&'static str> { - auto_operation_in(s, p, true) +/// +/// Faces picked in the world are probed in the placed model; one that cannot be placed is the +/// error. +pub fn auto_operation(s: &Session, p: &Value) -> Result> { + let st = if grouped_face(p).is_some() { s.world_state()? } else { s.model.state() }; + Ok(auto_operation_in(s, p, &st)) } impl Session { @@ -235,17 +243,22 @@ impl Session { } } -fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'static str> { +/// The first of an extrude's grouped face picks. +fn grouped_face(p: &Value) -> Option { + p.get("faces").and_then(Value::as_array).and_then(|faces| faces.first()).and_then(vec3) +} + +/// [`auto_operation`] probing the model `st`. +fn auto_operation_in(s: &Session, p: &Value, st: &solidcraft_doc::ModelState) -> Option<&'static str> { let symmetric = p.get("to").is_none() && str_(p, "direction").is_some_and(|d| d.eq_ignore_ascii_case("symmetric")); // Imported face groups can belong to a child of an empty active component. // Probe in the same coordinate frame as the face picks. - let grouped = p.get("faces").and_then(Value::as_array).and_then(|faces| faces.first()).and_then(vec3); - let st = if grouped.is_some() && world_faces { s.world_state() } else { s.model.state() }; + let grouped = grouped_face(p); // The body the extrude starts on, when it is in a component inside the active one: it takes // part as the active component's own bodies do (#5679). let mut started_on = None; let (base, n) = if let Some(point) = grouped { - let (mesh, index, distance, name) = super::face::face_at_state(&st, point, str_(p, "face_body")).ok().flatten()?; + let (mesh, index, distance, name) = super::face::face_at_state(st, point, str_(p, "face_body")).ok().flatten()?; if distance > (mesh.bounds().diagonal() * 1e-3).max(1e-3) * 10.0 { return None; } @@ -271,7 +284,7 @@ fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'stat } else if let Some(d) = extrude_reach(s, p) { if p.get("to").is_some() { d - start } else { d } } else { - through_all_reach(&st, p, base)? + through_all_reach(st, p, base)? }; if st.bodies.is_empty() || !d.is_finite() { return Some("new"); @@ -290,7 +303,7 @@ fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'stat } else if implicit_all { st.bodies.iter().collect() } else { - active_scope(s, &st) + active_scope(s, st) }; if parts.is_empty() && let Some(body) = started_on.as_deref().and_then(|name| st.body(name)) @@ -662,6 +675,11 @@ pub(super) fn add_feature(s: &mut Session, p: &Value, kind: FeatureKind) -> Resu /// `add_feature`; `world` is false when `kind` is already in the active component's frame. fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> Result { let name = str_(p, "name"); + // What a join makes of pieces that share no face (`Touching`): separate unless asked. + let touching = match p.get("touching") { + None | Some(Value::Null) => Touching::Separate, + Some(v) => v.as_str().and_then(Touching::parse).ok_or_else(|| EngineError::Other("`touching` must be separate or one_body".into()))?, + }; // The bodies before the feature, to say which ones it changed or removed. let before = s.model.state(); // Commands speak world coordinates; the feature is authored in the active component. @@ -727,7 +745,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> } else if pts.is_empty() { Vec::new() } else { - solidcraft_doc::face_point_names(&s.doc, &s.model.state(), &kind, s.active_component) + solidcraft_doc::face_point_names(&s.doc, &s.model.state(), &kind, s.active_component)? } }; // Primitives have no `targets` of their own: their `targets` are the bodies taking part (#259). @@ -757,6 +775,17 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> } else { participants }; + // An extrude's Join, Cut or Intersect with no bodies picked changes the bodies of the active + // component that are shown, never a hidden one (#2464). The shown ones are kept as its + // participants, so showing or hiding bodies later doesn't change the model. + let participants = match &kind { + FeatureKind::Extrude { operation: Operation::Join | Operation::Cut | Operation::Intersect, targets, .. } + if participants.is_empty() && targets.is_empty() => + { + shown_scope(s).unwrap_or_default() + } + _ => participants, + }; if matches!(kind, FeatureKind::ConstructionPlane { .. }) && let Some(n) = name { @@ -765,6 +794,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> let id = s.doc_mut().add_feature(kind, name)?; if let Some(f) = s.doc_mut().feature_mut(id) { f.participants = participants; + f.touching = touching; f.edge_refs = refs; f.edge_names = names; f.face_names = face_names; @@ -800,8 +830,10 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> } } let r = s.model.result(id).cloned(); - if let Some(e) = r.as_ref().and_then(|r| r.error.clone()) { - return Err(EngineError::Other(e)); + if let Some(r) = &r + && let Some(e) = r.error.clone() + { + return Err(EngineError::of_feature(r, e)); } let st = s.model.state(); let bodies: Vec<&str> = st.bodies.iter().map(|b| b.name.as_str()).collect(); @@ -815,9 +847,20 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> st.bodies.iter().filter(|b| b.feature != id && old.get(b.name.as_str()).is_some_and(|o| !o.same(&b.body))).map(|b| b.name.as_str()).collect(); let removed: Vec<&str> = before.bodies.iter().map(|b| b.name.as_str()).filter(|n| !now.contains(n)).collect(); let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default(); - // A warning (a Boolean that needed a retry, a reference found again elsewhere) is part of + // A warning (a reference found again elsewhere, a reduced radius) is part of // the reply: a script or an agent sees it without asking the timeline (#616). let warning = r.as_ref().and_then(|r| r.warning.clone()); + // A join that split pieces touching along an edge or at a point into bodies of their own says + // so, with the edit that makes them one body instead. + let notice = r.as_ref().and_then(|r| r.state.kept_separate(id)).map(|kept| FeatureNotice { + message: kept.notice().to_string(), + contact: kept.id().to_string(), + action: NoticeAction { + label: "Make one body".into(), + command: "timeline.edit".into(), + params: json!({"feature": id, "set": {"touching": "one_body"}}), + }, + }); let owned = |names: Vec<&str>| names.into_iter().map(str::to_string).collect(); let reply = FeatureResult { feature: id, @@ -827,6 +870,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> changed_bodies: owned(changed), removed_bodies: owned(removed), warning, + notice, ms: r.map(|r| r.ms), param_warnings: Vec::new(), }; @@ -873,7 +917,9 @@ fn extrude(s: &mut Session, p: &Value) -> Result { _ => None, }; let operation = match str_(p, "operation") { - Some(o) if o.eq_ignore_ascii_case("auto") => Operation::parse(auto_operation_in(s, p, false).unwrap_or("new")).unwrap_or(Operation::NewBody), + Some(o) if o.eq_ignore_ascii_case("auto") => { + Operation::parse(auto_operation_in(s, p, &s.model.state()).unwrap_or("new")).unwrap_or(Operation::NewBody) + } _ => operation(p, cmd)?, }; let mut targets = string_list(cmd, p, "targets")?; @@ -892,10 +938,6 @@ fn extrude(s: &mut Session, p: &Value) -> Result { } else if let Some(parts) = cut_scope(s, &p, operation, sketch, face_body, cmd)? { p.to_mut()["participants"] = json!(parts); } - if matches!(operation, Operation::Cut | Operation::Intersect) && targets.is_empty() && string_list(cmd, &p, "participants")?.is_empty() { - // With every body hidden, every body, as before. - targets = shown_scope(s).unwrap_or_default(); - } let kind = FeatureKind::Extrude { sketch: SketchId(sketch), profiles: match face_profile { @@ -1143,7 +1185,7 @@ fn thin_param(s: &Session, p: &Value, sketch: u64, cmd: &str) -> Result std::result::Result, String> { +fn thin_regions(s: &Session, ss: &solidcraft_doc::SolvedSketch, thin: &ThinWall) -> std::result::Result, String> { let length = |e: &str| s.doc.eval(&s.doc.with_design_unit(e, Kind::Length), Kind::Length).map_err(|e| e.to_string()); let t = length(&thin.thickness)?; let (inside, outside) = match thin.side { @@ -1152,7 +1194,7 @@ fn thin_regions(s: &Session, ss: &solidcraft_doc::SolvedSketch, thin: &ThinWall) ThinSide::Outside => (0.0, t), ThinSide::TwoSides => (t, length(thin.thickness2.as_deref().unwrap_or("0"))?), }; - let curves: Vec> = thin + let curves: Vec> = thin .curves .iter() .filter_map(|id| ss.sketch.curve_index(id)) @@ -1178,6 +1220,10 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result if let Some(t) = &taper { check_expr(s, t, Kind::Angle, cmd, "taper")?; } + let corner = match p.get("corner") { + None => None, + Some(value) => Some(serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`corner` must be preserve_curvature, tangent or round"))?), + }; let direction = match str_(p, "direction").map(str::to_ascii_lowercase).as_deref() { None | Some("positive") | Some("one_side") => Direction::Positive, Some("negative") | Some("reverse") | Some("flip") => Direction::Negative, @@ -1192,9 +1238,9 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result if let Some(d) = &start_offset { check_expr(s, d, Kind::Length, cmd, "start_offset")?; } + // A symmetric distance the call doesn't qualify is the total, split evenly around the start + // plane, for solid and surface extrudes alike. let convention = match p.get("convention") { - // Surface Extrude shares Extent but retains its existing per-side distance semantics. - None if cmd == "surface.extrude" => solidcraft_doc::ExtrudeConvention::LegacyPerSide, None => solidcraft_doc::ExtrudeConvention::TotalDistance, Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`convention` must be total_distance or legacy_per_side"))?, }; @@ -1206,9 +1252,11 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result start_offset, through_all, taper, + corner, to: p.get("to").and_then(vec3).map(FacePick), to_offset: expr(p, "to_offset"), from: p.get("from").and_then(vec3).map(FacePick), + to_body_apart: false, }) } @@ -1512,8 +1560,19 @@ fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result> { let tol = (size * 2e-3).max(1e-3); // The display mesh flags seams (a smooth surface meeting itself, as down the side // of a cylinder), which nobody means by a pick where they end. - match b.body.display_mesh(tol) { - Ok(m) => Some((size, m.edges, m.seams)), + match b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol)) { + // An edge where the faces meet tangentially (the spans of a spline wall + // meeting) can't be blended either: nobody means it by a pick. + Ok(m) => Some(( + size, + m.edges, + m.seams + .iter() + .zip(&m.smooth_edges) + .map(|(s, t)| *s || *t) + .chain(m.seams.iter().skip(m.smooth_edges.len()).copied()) + .collect(), + )), Err(_) => b.body.edges(tol).ok().map(|edges| (size, edges.into_iter().map(|e| e.points).collect(), Vec::new())), } }) @@ -1521,7 +1580,8 @@ fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result> { }); // A point where several edges meet (a corner) is ambiguous: the kernel would round one of // them, picked silently (#5173). Edges that carry straight on through the point (the two - // halves of a circle) are one edge to whoever picked it, and seams don't count. Directions + // halves of a circle) are one edge to whoever picked it, and seams and tangent joins don't + // count. Directions // come from the polylines' end chords, which lean off a curve's tangent: within about 45° // of opposite counts as carrying on (edges at a real corner are far from opposite). let mut nearest = f64::INFINITY; @@ -1591,8 +1651,8 @@ pub(crate) fn edge_ref_form(e: &Value) -> std::result::Result, & Ok(EdgeRefForm::Index { body, index }) } -/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); an -/// edge is rounded (a fillet). +/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); a +/// fillet's or chamfer's face changes that feature's size; an edge is rounded (a fillet). fn press_pull(s: &mut Session, p: &Value) -> Result { let cmd = "solid.press_pull"; let distance = req_expr(cmd, p, "distance")?; @@ -1604,10 +1664,9 @@ fn press_pull(s: &mut Session, p: &Value) -> Result { if d.abs() < 1e-9 { return Err(bad(cmd, "the distance must not be zero")); } - // A fillet's or chamfer's face: its size changes by the distance (the feature is edited). - if let Some(fp) = vec3(face) - && super::face::face_is_planar(s, fp) == Some(false) - { + // A fillet's or chamfer's face: its size changes by the distance (the feature is edited). A + // chamfer's face is flat, so this is asked before whether the face is planar (#4986). + if let Some(fp) = vec3(face) { let name = solidcraft_doc::naming::face_names_at(&s.model.state(), &[fp]).into_iter().next().unwrap_or_default(); let fid = solidcraft_doc::persistent_name::made_by(&name); if solidcraft_doc::persistent_name::is_blend(&name) { @@ -1625,8 +1684,10 @@ fn press_pull(s: &mut Session, p: &Value) -> Result { return Ok(json!({"feature": f.id, "edited": f.name, key: new, "recomputed": out.get("recomputed"), "restored": out.get("restored")})); } // Another curved face moves along its normal. - let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?; - return (r.run)(s, &json!({"faces": [face], "distance": distance})); + if super::face::face_is_planar(s, fp) == Some(false) { + let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?; + return (r.run)(s, &json!({"faces": [face], "distance": distance})); + } } // Pushed in: the extrude cuts the other way by as much (a bare number stays one, so it keeps // being read as a bare number typed into the extrude). @@ -1716,6 +1777,29 @@ fn fillet(s: &mut Session, p: &Value) -> Result { if !corner.is_rolling() && (!style.is_constant() || !fit.is_exact()) { return Err(bad(cmd, "`corner: g2` is built for a constant-radius fillet (`type: constant`, `fit: exact`) only")); } + // Corner setbacks: each a vertex and the distance its patch starts along the edges there. + let mut setbacks = Vec::new(); + if let Some(list) = p.get("setbacks") { + let list = list.as_array().ok_or_else(|| bad(cmd, "`setbacks` is a list of {vertex: [x,y,z], distance: expr}"))?; + for item in list { + let vertex = item.get("vertex").and_then(vec3).ok_or_else(|| bad(cmd, "each setback needs `vertex`: [x,y,z] at the corner"))?; + let distance = expr(item, "distance").ok_or_else(|| bad(cmd, "each setback needs `distance`: a length"))?; + check_expr(s, &distance, Kind::Length, cmd, "setback distance")?; + setbacks.push(solidcraft_doc::CornerSetback { vertex: Position(vertex), distance }); + } + if !setbacks.is_empty() && (!style.is_constant() || !fit.is_exact()) { + return Err(bad(cmd, "`setbacks` are built for a constant-radius fillet (`type: constant`, `fit: exact`) only")); + } + } + // How two rounds turn at a sharp side edge. + let turn = match str_(p, "turn").map(str::to_ascii_lowercase).as_deref() { + None | Some("mitre") => solidcraft_doc::FilletTurn::Mitre, + Some("swept") => solidcraft_doc::FilletTurn::Swept, + Some(o) => return Err(bad(cmd, format!("unknown turn `{o}` (mitre or swept)"))), + }; + if !turn.is_mitre() && (!style.is_constant() || fit == solidcraft_doc::FilletFit::Taper || !corner.is_rolling() || !setbacks.is_empty()) { + return Err(bad(cmd, solidcraft_doc::SWEPT_TAKES)); + } let mut out = add_feature( s, p, @@ -1726,6 +1810,9 @@ fn fillet(s: &mut Session, p: &Value) -> Result { style, fit, corner, + setbacks, + turn, + tangent_chain: bool_(p, "tangent_chain").unwrap_or(true), }, )?; // The radii the fillet used, when `fit: reduce` reduced it. @@ -1734,9 +1821,9 @@ fn fillet(s: &mut Session, p: &Value) -> Result { && let Some(r) = state.fitted_radius(id) { out["radius_applied"] = serde_json::json!(r); - let each: Vec = - state.fitted_edges(id).unwrap_or_default().into_iter().map(|(p, r)| serde_json::json!({"edge": [p.x, p.y, p.z], "radius": r})).collect(); - out["radii_applied"] = Value::Array(each); + let each: Vec = + state.fitted_edges(id).unwrap_or_default().into_iter().map(|(p, radius)| AppliedRadius { edge: [p.x, p.y, p.z], radius }).collect(); + out["radii_applied"] = serde_json::to_value(each).map_err(|e| EngineError::Internal(cmd.into(), e.to_string()))?; } Ok(out) } @@ -1767,6 +1854,7 @@ fn chamfer(s: &mut Session, p: &Value) -> Result { angle, flip, body: str_(p, "body").map(BodyName::from), + tangent_chain: bool_(p, "tangent_chain").unwrap_or(true), }, ) } @@ -1803,16 +1891,73 @@ fn combine(s: &mut Session, p: &Value) -> Result { } fn move_bodies(s: &mut Session, p: &Value) -> Result { + if let Some(paths) = copied_components(p)? { + return copy_components(s, p, paths); + } if let Some(plan) = crate::frames::placements_moved(s, p) { return move_placements(s, p, plan); } + // Bodies in differently placed frames: one Move feature per frame, each moving its bodies + // by the world vector and turn mapped into that frame (#9660). + if let Some(moves) = crate::frames::split_move(s, p)? { + return move_split(s, &moves); + } move_body_feature(s, p) } -/// A move of several placements of one part (`frames::placements_moved`, #4768): each placement -/// moved in the world by the move's translation and turn (about the world origin, as the Move -/// feature turns bodies), and the root component's bodies listed moved as bodies, in one step. -fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMove) -> Result { +/// The moves of `frames::split_move`, in one step, with one reply: the features made, and the +/// bodies made, changed and removed by any of them. +fn move_split(s: &mut Session, moves: &[Value]) -> Result { + let mut features = Vec::new(); + let mut lists: [(&str, Vec); 3] = [("created_bodies", Vec::new()), ("changed_bodies", Vec::new()), ("removed_bodies", Vec::new())]; + let mut last = Value::Null; + for p in moves { + let reply = move_body_feature(s, p)?; + features.push(reply.get("feature").cloned().unwrap_or(Value::Null)); + for (key, list) in &mut lists { + for name in reply.get(*key).and_then(Value::as_array).into_iter().flatten() { + if !list.contains(name) { + list.push(name.clone()); + } + } + } + last = reply; + } + if let Some(out) = last.as_object_mut() { + if let Some(first) = features.first() { + out.insert("feature".into(), first.clone()); + } + out.insert("features".into(), Value::Array(features)); + for (key, list) in lists { + out.insert(key.into(), Value::Array(list)); + } + } + Ok(last) +} + +/// The occurrence paths a copying move copies (`occurrences`, root first), `None` when it names +/// none. A component is only ever copied, so the move must set `copy`. +fn copied_components(p: &Value) -> Result>>> { + let cmd = "solid.move"; + let Some(list) = p.get("occurrences") else { return Ok(None) }; + let paths: Vec> = list + .as_array() + .into_iter() + .flatten() + .map(|path| path.as_array().and_then(|ids| ids.iter().map(Value::as_u64).collect::>>()).filter(|ids| !ids.is_empty())) + .collect::>() + .ok_or_else(|| bad(cmd, "`occurrences` must list occurrence paths, each a list of occurrence ids"))?; + if paths.is_empty() || paths.len() > 1000 { + return Err(bad(cmd, "`occurrences` must list 1…1000 occurrence paths")); + } + if p.get("copy").and_then(Value::as_bool) != Some(true) { + return Err(bad(cmd, "`occurrences` are copied: set `copy` to true")); + } + Ok(Some(paths)) +} + +/// The translation (mm) and turn (radians, if any) of a move in the world. +fn world_move(s: &Session, p: &Value) -> Result<(Vec, Option)> { let cmd = "solid.move"; let length = |v: &Value| -> Result { match v { @@ -1830,6 +1975,79 @@ fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMov Some(a) => Some(s.doc.eval(&a, Kind::Angle).map_err(|e| bad(cmd, format!("angle: {e}")))?), None => None, }; + Ok((translate, angle)) +} + +/// A copying move of components (`occurrences`, with `copy`): each picked placement's component is +/// copied as an independent component, as Paste New copies it (`component.paste_new`), placed where +/// the placement is; the copy then moves by the move's translation and turn in the world, as +/// `occurrence.move` moves a placement. The bodies listed are copied as bodies (see +/// `move_body_feature`) in the same command, so the whole move is one undo step. +fn copy_components(s: &mut Session, p: &Value, paths: Vec>) -> Result { + let cmd = "solid.move"; + let (translate, angle) = world_move(s, p)?; + let paste = super::find_command("component.paste_new").ok_or_else(|| EngineError::UnknownCommand("component.paste_new".into()))?; + let mover = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?; + // A component inside another one copied here comes with its parent's copy. + let mut paths: Vec> = paths.into_iter().fold(Vec::new(), |mut out, path| { + if !out.contains(&path) { + out.push(path); + } + out + }); + let all = paths.clone(); + paths.retain(|p| !all.iter().any(|q| q.len() < p.len() && p.starts_with(q))); + // The bodies are given in the world; their own component's frame turns them, as a move of bodies + // alone is turned, so they are mapped the same way, before any copy is made. + let has_bodies = match p.get("bodies") { + None => false, + Some(Value::Array(bodies)) => !bodies.is_empty(), + Some(_) => return Err(bad(cmd, "`bodies` must list bodies")), + }; + let mut rest = p.clone(); + if let Some(object) = rest.as_object_mut() { + object.remove("occurrences"); + } + // Bodies in differently placed frames split by frame (`frames::split_move`, #9660), as a move of them alone does. + let split = crate::frames::split_move(s, &rest)?; + let bodies = if has_bodies && split.is_none() { Some(crate::frames::to_local(s, cmd, &rest)?.unwrap_or_else(|| rest.clone())) } else { None }; + let mut copies = Vec::new(); + for path in &paths { + let Some(&source) = path.last() else { continue }; + let component = + s.doc.occurrences.iter().find(|o| o.id == source).map(|o| o.component).ok_or_else(|| bad(cmd, "`occurrences` names no occurrence"))?; + let made = paste.run_nested(s, &json!({"component": component, "occurrence": source, "path": path}))?; + let copy = made.get("occurrence").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "the copy has no occurrence"))?; + // The copy is placed by the same parent placement as its source. + let mut at = path[..path.len() - 1].to_vec(); + at.push(copy); + let mut q = json!({"occurrence": copy, "path": at, "space": "world", "translate": translate}); + if let Some(axis) = p.get("axis") { + q["axis"] = axis.clone(); + } + if let Some(angle) = angle { + q["angle"] = json!(angle); + } + mover.run_nested(s, &q)?; + copies.push(copy); + } + // The reply is a solid.move reply: the bodies' feature reply, with the copies made alongside. + let mut out = match (split, bodies) { + (Some(moves), _) => move_split(s, &moves)?, + (None, Some(local)) => move_body_feature(s, &local)?, + (None, None) => json!({}), + }; + if let Some(object) = out.as_object_mut() { + object.insert("occurrences".into(), json!(copies)); + } + Ok(out) +} + +/// A move of several placements of one part (`frames::placements_moved`, #4768): each placement +/// moved in the world by the move's translation and turn (about the world origin, as the Move +/// feature turns bodies), and the root component's bodies listed moved as bodies, in one step. +fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMove) -> Result { + let (translate, angle) = world_move(s, p)?; let spec = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?; let mut moved = Vec::new(); for path in &plan.paths { @@ -1892,6 +2110,7 @@ fn move_body_feature(s: &mut Session, p: &Value) -> Result { )?; if copy { copy_keeps_appearance(s, &reply, &bodies, cmd)?; + super::print_face::copies_keep_print_faces(s, &reply, &bodies); } Ok(reply) } @@ -2044,16 +2263,32 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result { finish_pattern(s, p, features, pattern, bodies) } +/// The line a circular pattern turns about, as [`axis_line`] reads it, except that the origin of +/// `{origin, dir}` may be length expressions, kept so the pattern follows them (#10852). +fn pattern_axis(s: &Session, p: &Value, cmd: &str) -> Result<(PointExpr, Vec3, Option, Option)> { + if let Some(a @ Value::Object(o)) = p.get("axis") + && o.contains_key("origin") + && !super::is_model_axis(a) + { + // Read under its full name, so a refusal says which origin it means. + let origin = point_param(s, &json!({ "axis.origin": o.get("origin") }), "axis.origin", cmd)?; + let dir = a.get("dir").and_then(vec3).and_then(|d| d.normalized()).ok_or_else(|| bad(cmd, "axis needs a non-zero `dir`"))?; + return Ok((origin.unwrap_or_else(|| solidcraft_doc::point_expr(Vec3::ZERO)), dir, None, None)); + } + let (origin, dir, axis_ref, axis_feature) = axis_line(s, p, cmd)?; + Ok((solidcraft_doc::point_expr(origin), dir, axis_ref, axis_feature)) +} + fn pattern_circ(s: &mut Session, p: &Value) -> Result { let cmd = "solid.pattern.circular"; let (features, bodies) = pattern_sources(s, p, cmd)?; - let (origin, axis, axis_ref, axis_feature) = axis_line(s, p, cmd)?; + let (origin, axis, axis_ref, axis_feature) = pattern_axis(s, p, cmd)?; let count = req_expr(cmd, p, "count")?; check_count(s, &count, cmd, "count")?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); check_expr(s, &angle, Kind::Angle, cmd, "angle")?; let pattern = solidcraft_doc::PatternKind::Circular { - origin: Position(origin), + origin, axis: Dir(axis), count, angle, @@ -2098,7 +2333,12 @@ fn mirror(s: &mut Session, p: &Value) -> Result { let plane = plane_param(s, p.get("plane"), cmd)?; let combine = bool_(p, "combine").unwrap_or(false); let (bodies, placements) = placed_bodies(s, bodies, cmd)?; - add_feature(s, p, FeatureKind::Mirror { features, plane, bodies: bodies.into_iter().map(BodyName).collect(), combine, placements }) + let reply = + add_feature(s, p, FeatureKind::Mirror { features, plane, bodies: bodies.iter().cloned().map(BodyName).collect(), combine, placements })?; + if !combine { + super::print_face::copies_keep_print_faces(s, &reply, &bodies); + } + Ok(reply) } /// Bodies picked where the viewport shows them: each world name ("Body1", or "Body1 (Occ:2)" @@ -2119,9 +2359,13 @@ fn placed_bodies(s: &Session, names: Vec, cmd: &str) -> Result<(Vec Result<()> { /// What [`check_plane_name`] says about `name`, or `None` when a construction plane may take it. pub(crate) fn plane_name_problem(name: &str) -> Option { - solidcraft_geom::Plane::named(name.trim()).map(|_| { + solidcore_record::Plane::named(name.trim()).map(|_| { format!("`{}` is reserved for an origin plane (XY, XZ, YZ, Top, Front, Right); give the construction plane another name", name.trim()) }) } @@ -2160,10 +2404,10 @@ pub(crate) const PLANE_FORMS: &str = /// The plane an explicit plane object gives through `origin`, as [`plane_param`] reads it: from /// `x_dir` and `y_dir` when both are points, else from `normal`; `None` when they don't make one. -pub(crate) fn explicit_plane(o: &Value, origin: Vec3) -> Option { +pub(crate) fn explicit_plane(o: &Value, origin: Vec3) -> Option { match (o.get("x_dir").and_then(vec3), o.get("y_dir").and_then(vec3), o.get("normal").and_then(vec3)) { - (Some(x), Some(y), _) => solidcraft_geom::Plane::new(origin, x, y), - (_, _, Some(n)) => solidcraft_geom::Plane::from_normal(origin, n), + (Some(x), Some(y), _) => solidcore_record::Plane::new(origin, x, y), + (_, _, Some(n)) => solidcore_record::Plane::from_normal(origin, n), _ => None, } } @@ -2181,7 +2425,7 @@ pub(super) fn plane_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result Err(bad(cmd, format!("no plane `{r}` (a plane is {WANT})"))), }; match v { - Some(Value::String(n)) if solidcraft_geom::Plane::named(n.trim()).is_some() => { + Some(Value::String(n)) if solidcore_record::Plane::named(n.trim()).is_some() => { if let Some(f) = s.doc.find_feature(n.trim()) && matches!(f.kind, FeatureKind::ConstructionPlane { .. }) { @@ -2392,25 +2636,10 @@ fn clearance_diameter(size: &str, fit: &str) -> Option { } } -/// The refusal for a thread designation `parse_metric_thread` does not know. A plain `M` with -/// a sane diameter but no ISO coarse pitch (M28, M7) gets two pitches to try: the largest common -/// pitch up to about an eighth of the diameter, and the next finer one. -fn unknown_metric_thread(t: &str, examples: &str) -> String { - fine_only_hint(t).unwrap_or_else(|| format!("unknown thread `{t}` (ISO metric, like {examples})")) -} - /// The pitches to try for a plain `M` that has no ISO coarse pitch, `None` for anything else. fn fine_only_hint(t: &str) -> Option { - const PITCHES: [f64; 9] = [2.0, 1.5, 1.25, 1.0, 0.75, 0.5, 0.35, 0.25, 0.2]; let diameter = t.trim().strip_prefix(['M', 'm']).and_then(|d| d.trim().parse::().ok()); - if let Some(d) = diameter.filter(|d| d.is_finite() && *d > 0.2 && *d <= 1e4) { - let first = PITCHES.iter().position(|p| *p <= 0.12 * d).unwrap_or(PITCHES.len() - 1); - let pitches: Vec = PITCHES.iter().skip(first).take(2).filter(|p| **p < d).map(|p| format!("M{d}x{p}")).collect(); - if !pitches.is_empty() { - return Some(format!("M{d} has no coarse ISO pitch: give one, e.g. {}", pitches.join(" or "))); - } - } - None + diameter.and_then(solidcraft_doc::thread_forms::no_coarse_pitch) } /// Largest nominal diameter automatic thread sizing knows (the last ISO coarse size). @@ -2479,22 +2708,36 @@ fn hole(s: &mut Session, p: &Value) -> Result { _ => None, }; let thread = str_(p, "thread").map(|t| t.trim().to_string()).filter(|t| !t.is_empty()); - let handedness = thread_handedness(p, cmd)?; - if thread.is_none() && !handedness.is_right() { - return Err(bad(cmd, "`handedness` needs `thread` (a tapped hole)")); + let hand = match str_(p, "hand") { + None | Some("right") => solidcraft_doc::thread_forms::ThreadHand::Right, + Some("left") => solidcraft_doc::thread_forms::ThreadHand::Left, + Some(h) => return Err(bad(cmd, format!("unknown hand `{h}` (right or left)"))), + }; + if thread.is_none() && hand != solidcraft_doc::thread_forms::ThreadHand::Right { + return Err(bad(cmd, "`hand` needs `thread` (a tapped hole)")); } if let Some(t) = &thread && solidcraft_doc::parse_tapped_thread(t).is_none() { return Err(bad( cmd, - fine_only_hint(t).unwrap_or_else(|| format!("unknown tapped thread `{t}` (ISO metric or a catalogued UNC/UNF, G or Rp size)")), + fine_only_hint(t) + .or_else(|| solidcraft_doc::untabulated_taper_tap(t)) + .unwrap_or_else(|| format!("unknown tapped thread `{t}` (ISO metric or a catalogued UNC/UNF, G, Rp, Rc or NPT size)")), )); } let thread_depth = match p.get("thread_depth") { None | Some(Value::Null) => None, Some(_) => Some(req_expr(cmd, p, "thread_depth")?), }; + let modeled = p.get("modeled").and_then(Value::as_bool).unwrap_or(false); + if modeled && thread.is_none() { + return Err(bad(cmd, "`modeled` needs `thread` (a tapped hole)")); + } + let ease_out = runout_param(s, p, cmd, "ease_out")?; + if ease_out.is_some() && !modeled { + return Err(bad(cmd, "`ease_out` is cut only on a modelled thread (`modeled: true`)")); + } if let Some(d) = &thread_depth { if thread.is_none() { return Err(bad(cmd, "`thread_depth` requires `thread` (a tapped hole)")); @@ -2579,6 +2822,14 @@ fn hole(s: &mut Session, p: &Value) -> Result { (None, None, None) => return Err(bad(cmd, "needs `diameter`, `thread` (a tapped hole) or `clearance` (a bolt size)")), }; check_expr(s, &diameter, Kind::Length, cmd, "diameter")?; + // A tapped hole drilled to another size than the tap maker's: from the thread's minor + // diameter to 5% over that drill. + if let (Some(t), Some(_)) = (&thread, expr(p, "diameter")) + && let Some(size) = solidcraft_doc::parse_tapped_thread(t) + { + let given = s.doc.eval(&diameter, Kind::Length).map_err(|e| bad(cmd, format!("`diameter`: {e}")))?; + size.check_drill(given).map_err(|e| bad(cmd, e))?; + } let depth = expr(p, "depth"); if let Some(d) = &depth { check_expr(s, d, Kind::Length, cmd, "depth")?; @@ -2640,13 +2891,31 @@ fn hole(s: &mut Session, p: &Value) -> Result { points: points.map(|x| x.0), thread, thread_depth, - handedness, + hand, + modeled, + ease_out, to: to.map(FacePick), references, }, ) } +/// A thread's runout parameter: a length, `standard` (ISO 3508's 2.5 P) or `short` (1.25 P); +/// none or 0: no runout. +fn runout_param(s: &Session, p: &Value, cmd: &str, key: &str) -> Result> { + Ok(match p.get(key) { + None | Some(Value::Null) => None, + Some(Value::String(t)) if t == "standard" => Some(solidcraft_doc::ThreadRunout::Standard), + Some(Value::String(t)) if t == "short" => Some(solidcraft_doc::ThreadRunout::Short), + Some(Value::Number(n)) if n.as_f64() == Some(0.0) => None, + Some(_) => { + let e = expr(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a length, \"standard\" or \"short\"")))?; + check_expr(s, &e, Kind::Length, cmd, key)?; + Some(solidcraft_doc::ThreadRunout::Length { length: e }) + } + }) +} + /// Where reference edges (#37) put a hole's (or a cylinder's) centre picked at `at` on a flat /// face, `dir` into it: at their distances from the edges, which must be straight edges at the /// given points, and cross. @@ -2731,7 +3000,11 @@ fn face_points(s: &Session, p: &Value, cmd: &str) -> Result> { fn shell(s: &mut Session, p: &Value) -> Result { let cmd = "solid.shell"; - let faces = face_points(s, p, cmd)?; + // No face opened: a closed hollow body, its void sealed inside. + let faces = match p.get("faces").and_then(Value::as_array) { + Some(a) if a.is_empty() => Vec::new(), + _ => face_points(s, p, cmd)?, + }; let thickness = req_expr(cmd, p, "thickness")?; check_expr(s, &thickness, Kind::Length, cmd, "thickness")?; let direction = str_(p, "direction").map(str::to_ascii_lowercase).unwrap_or_default(); @@ -2961,40 +3234,129 @@ fn loft(s: &mut Session, p: &Value) -> Result { add_feature(s, p, FeatureKind::Loft { sections, operation, targets, rails, rail_fit }) } -fn thread_handedness(p: &Value, cmd: &str) -> Result { - match p.get("handedness") { - None => Ok(solidcraft_doc::ThreadHandedness::Right), - Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`handedness` must be `right` or `left`")), - } -} - fn thread(s: &mut Session, p: &Value) -> Result { let cmd = "solid.thread"; let face = p .get("face") .and_then(|v| vec3(v).or_else(|| v.get("point").and_then(vec3))) .ok_or_else(|| bad(cmd, "`face` must be a point [x, y, z] on a cylindrical face"))?; + use solidcraft_doc::thread_forms::{SteepFlank, ThreadForm, ThreadHand, ThreadTip}; let designation = str_(p, "designation").map(|t| t.trim().to_string()).filter(|t| !t.is_empty()); - if let Some(t) = &designation - && solidcraft_doc::parse_metric_thread(t).is_none() - { - return Err(bad(cmd, unknown_metric_thread(t, "M8 or M8x1"))); + let form = match str_(p, "form") { + Some(f) => ThreadForm::from_name(f).ok_or_else(|| { + bad(cmd, format!("unknown thread form `{f}` (metric, trapezoidal, acme, buttress, buttress_asme, bspp, rp, bspt, npt or square)")) + })?, + None => designation.as_deref().and_then(ThreadForm::of_designation).unwrap_or_default(), + }; + if let Some(why) = form.refused() { + return Err(bad(cmd, why)); } + let starts = match p.get("starts") { + None | Some(Value::Null) => 1, + Some(v) => v.as_u64().filter(|n| (1..=8).contains(n)).ok_or_else(|| bad(cmd, "`starts` must be a whole number from 1 to 8"))? as u32, + }; + if let Some(t) = &designation { + form.parse(t, starts).map_err(|e| bad(cmd, e))?; + } + let hand = match str_(p, "hand") { + None | Some("right") => ThreadHand::Right, + Some("left") => ThreadHand::Left, + Some("both") => ThreadHand::Both, + Some(h) => return Err(bad(cmd, format!("unknown hand `{h}` (right, left or both)"))), + }; + let steep_flank = match str_(p, "steep_flank") { + None | Some("end") => SteepFlank::End, + Some("start") => SteepFlank::Start, + Some(h) => return Err(bad(cmd, format!("unknown steep_flank `{h}` (start or end)"))), + }; + if p.get("steep_flank").is_some() && !matches!(form, ThreadForm::Buttress | ThreadForm::ButtressAsme) { + return Err(bad(cmd, "`steep_flank` is for the buttress forms")); + } + let tip = match str_(p, "tip") { + None | Some("none") => ThreadTip::None, + Some("start") => ThreadTip::Start, + Some("both") => ThreadTip::Both, + Some("chamfer") => return Err(bad(cmd, "tip `chamfer` is now `both` (every free end) or `start` (the end the thread starts from)")), + Some(t) => return Err(bad(cmd, format!("unknown tip `{t}` (none, start or both)"))), + }; + let angled = |key: &str, kind: Kind| -> Result> { + let e = expr(p, key); + if let Some(e) = &e { + check_expr(s, e, kind, cmd, key)?; + } + Ok(e) + }; + let chamfer_angle = angled("chamfer_angle", Kind::Angle)?; + let chamfer_depth = angled("chamfer_depth", Kind::Length)?; + if tip == ThreadTip::None && (chamfer_angle.is_some() || chamfer_depth.is_some()) { + return Err(bad(cmd, "`chamfer_angle` and `chamfer_depth` go with a chamfered tip (`tip: start` or `both`)")); + } + if p.get("ease_in").is_some() { + return Err(bad( + cmd, + "`ease_in` is gone: a thread's start runs off its free end, plain or chamfered (`tip: start`); fade the inner end with `ease_out`", + )); + } + let ease_out = runout_param(s, p, cmd, "ease_out")?; let length = expr(p, "length"); if let Some(l) = &length { check_expr(s, l, Kind::Length, cmd, "length")?; } + let up_to = match p.get("up_to") { + None | Some(Value::Null) => None, + Some(v) => Some(match vec3(v) { + Some(q) => solidcraft_doc::ThreadLimit::Face(FacePick(q)), + None => solidcraft_doc::ThreadLimit::Plane(plane_param(s, Some(v), cmd)?), + }), + }; + match (str_(p, "extent"), &length, &up_to) { + (None, Some(_), Some(_)) => return Err(bad(cmd, "give `length` or `up_to`, not both")), + (None, ..) | (Some("full"), None, None) | (Some("length"), Some(_), None) | (Some("up_to"), None, Some(_)) => {} + (Some("full"), ..) => return Err(bad(cmd, "`extent: full` runs the whole face: it takes no `length` or `up_to`")), + (Some("length"), ..) => return Err(bad(cmd, "`extent: length` needs `length` (and no `up_to`)")), + (Some("up_to"), ..) => return Err(bad(cmd, "`extent: up_to` needs `up_to` (and no `length`)")), + (Some(e), ..) => return Err(bad(cmd, format!("unknown extent `{e}` (full, length or up_to)"))), + } + let from = match p.get("from") { + None | Some(Value::Null) => None, + Some(v) => Some(Position(vec3(v).ok_or_else(|| bad(cmd, "`from` must be a point [x, y, z] near the end the thread starts at"))?)), + }; let modeled = p.get("modeled").and_then(Value::as_bool).unwrap_or(false); + // The coarse metric range bounds only a metric thread with no designation given. if designation.is_none() + && form == ThreadForm::Metric && let Some(msg) = beyond_coarse_range(&s.model.state(), face) { return Err(bad(cmd, msg)); } - let handedness = thread_handedness(p, cmd)?; - let v = add_feature(s, p, FeatureKind::Thread { face: FacePick(face), designation, length, modeled, handedness })?; + let designation_is_none = designation.is_none(); + let kind = FeatureKind::Thread { + face: FacePick(face), + designation, + length, + modeled, + from, + up_to, + form, + hand, + starts, + ease_out, + tip, + chamfer_angle, + chamfer_depth, + steep_flank, + // Only a thread saved before holes were sized by nominal diameter, edited by `timeline.redefine`. + old_auto_size: designation_is_none && bool_(p, "old_auto_size").unwrap_or(false), + }; + let v = add_feature(s, p, kind)?; let st = s.model.state(); let t = v.get("feature").and_then(Value::as_u64).and_then(|id| st.threads.iter().find(|t| t.feature == id).cloned()); - Ok(json!({"feature": v.get("feature"), "name": v.get("name"), "thread": t})) + let mut reply = json!({"feature": v.get("feature"), "name": v.get("name"), "thread": t}); + // A hole narrowed to the thread's minor diameter says so. + if let Some(w) = v.get("warning").filter(|w| !w.is_null()) { + reply["warning"] = w.clone(); + } + Ok(reply) } fn pipe(s: &mut Session, p: &Value) -> Result { @@ -3151,8 +3513,8 @@ mod thin_extrude_tests; #[path = "extrude_convention_tests.rs"] mod extrude_convention_tests; /// `solid.fillet corner?: rolling|g2`: the default keeps the rolling ball's sphere corner, `g2` -/// is accepted and refuses (item 10's patch is built but not sewn in yet, see `corner_g2`), and an -/// unknown word is refused. +/// sets the corner back and fills it with the G2 patch (`solidcraft_kernel::fillet_g2_corners`), +/// with `setbacks` naming its distance, and an unknown word is refused. #[cfg(test)] #[allow(clippy::unwrap_used)] mod corner_tests { @@ -3177,26 +3539,127 @@ mod corner_tests { } #[test] - fn the_default_corner_is_the_rolling_ball_and_g2_refuses_clearly() { + fn the_default_corner_is_the_rolling_ball_and_g2_sets_it_back_for_its_patch() { let (default, reply) = cornered(None); assert_eq!(reply["warning"], json!(null), "{reply}"); let (rolling, _) = cornered(Some("rolling")); - let ball = default.world_state().body("B").unwrap().body.clone(); - let same = rolling.world_state().body("B").unwrap().body.clone(); + let ball = default.world_state().unwrap().body("B").unwrap().body.clone(); + let same = rolling.world_state().unwrap().body("B").unwrap().body.clone(); // `corner: rolling` is the default: the same body, to the last bit of its area. assert_eq!(solidcraft_kernel::measure(&ball).unwrap().area, solidcraft_kernel::measure(&same).unwrap().area); assert!(solidcraft_kernel::measure(&ball).unwrap().volume > 7000.0); - // `corner: g2`: accepted, and refused with a clear message until the patch sews in. + // `corner: g2`: the corner set back (1.5 r by default, or as `setbacks` says) and filled + // with the G2 patch: one closed solid of the box's faces, the rounds and the patch, a + // little fuller than the ball's corner (its patch spans the setback, not the ball). + let ball_volume = solidcraft_kernel::measure(&ball).unwrap().volume; + for setbacks in [json!([]), json!([{"vertex": [0, 0, 0], "distance": 7}])] { + let mut s = Session::default(); + run(&mut s, "solid.box", &json!({"length": 20, "width": 20, "height": 20, "body_name": "B"})); + run(&mut s, "solid.fillet", &json!({"edges": [[10, 0, 0], [0, 10, 0], [0, 0, 10]], "radius": 4, "corner": "g2", "setbacks": setbacks})); + let body = s.world_state().unwrap().body("B").unwrap().body.clone(); + assert!(body.validity().is_empty(), "{:?}", body.validity()); + let m = solidcraft_kernel::measure(&body).unwrap(); + eprintln!("corner g2, setbacks {setbacks}: {} faces, volume {:.4} (ball {:.4})", m.faces, m.volume, ball_volume); + assert_eq!(m.faces, 10); + assert!((m.volume - ball_volume).abs() < 1e-3 * ball_volume, "{} vs {}", m.volume, ball_volume); + } let mut s = Session::default(); run(&mut s, "solid.box", &json!({"length": 20, "width": 20, "height": 20, "body_name": "B"})); - let err = - s.execute("solid.fillet", &json!({"edges": [[10, 0, 0], [0, 10, 0], [0, 0, 10]], "radius": 4, "corner": "g2"})).unwrap_err().to_string(); - eprintln!("corner g2: {err}"); - assert!(err.contains("not supported yet:") && err.contains("G2 corner"), "{err}"); // An unknown word, and a style the G2 corner has no patch for, are refused as parameters. assert!(s.execute("solid.fillet", &json!({"edges": [[10, 0, 0]], "radius": 4, "corner": "round"})).is_err()); assert!(s.execute("solid.fillet", &json!({"edges": [[10, 0, 0]], "radius": 4, "corner": "g2", "type": "chord"})).is_err()); assert!(s.execute("solid.fillet", &json!({"edges": [[10, 0, 0]], "radius": 4, "corner": "g2", "fit": "reduce"})).is_err()); + // A corner where convex and concave rounds meet (the top of a notch's inner edge, two + // convex rounds and the concave one) is refused, the message naming it and why. + let mut s = Session::default(); + run(&mut s, "solid.box", &json!({"length": 60, "width": 40, "height": 20, "body_name": "B"})); + run(&mut s, "solid.box", &json!({"corner": [40, 20, 10], "length": 30, "width": 30, "height": 20, "body_name": "N"})); + run(&mut s, "solid.combine", &json!({"target": "B", "tools": ["N"], "operation": "cut"})); + let mixed = json!({"edges": [[40, 20, 15], [50, 20, 20], [40, 30, 20]], "radius": 3, "corner": "g2"}); + let err = s.execute("solid.fillet", &mixed).unwrap_err().to_string(); + eprintln!("mixed corner g2: {err}"); + assert!(err.contains("not supported yet") && err.contains("(40.000, 20.000, 20.000)") && err.contains("all convex or all concave"), "{err}"); + } + + /// `solid.fillet turn?: mitre|swept` on the four base edges of a 10 x 10 x 5 boss on a + /// 40 x 30 x 10 plate, r 1: at each upright boss edge the two rounds turn round it. Each base + /// edge gains the spandrel A = (1 - π/4) r² along its 10, and the corners the rounds' part + /// beyond both walls, whose section's first moment about the upright edge is + /// M = (5/6 - π/4) r³: mitred (the default), 8 M; swept, that section revolved a quarter turn at + /// each corner, 2π M, the corner's face the horn torus of radii r, r about the upright edge, + /// centred r above the plate. The turn is saved; an unknown turn and a swept chord round are + /// refused as parameters, and swept rounds along a pocket's floor (its upright edges concave) + /// with the kernel's reason. + #[test] + fn rounds_turning_round_a_boss_edge_are_mitred_or_swept() { + use std::f64::consts::PI; + const BASE: [[f64; 3]; 4] = [[20.0, 10.0, 10.0], [25.0, 15.0, 10.0], [20.0, 20.0, 10.0], [15.0, 15.0, 10.0]]; + let boss = || { + let mut s = Session::default(); + run(&mut s, "solid.box", &json!({"length": 40, "width": 30, "height": 10, "body_name": "B"})); + run(&mut s, "solid.box", &json!({"corner": [15, 10, 10], "length": 10, "width": 10, "height": 5, "operation": "join"})); + s + }; + let turned = |turn: Option<&str>| { + let mut s = boss(); + let mut p = json!({"edges": BASE, "radius": 1}); + if let Some(t) = turn { + p["turn"] = json!(t); + } + let reply = run(&mut s, "solid.fillet", &p); + assert_eq!(reply["warning"], json!(null), "{reply}"); + let body = s.world_state().unwrap().body("B").unwrap().body.clone(); + assert!(body.validity().is_empty(), "{:?}", body.validity()); + (s, solidcraft_kernel::measure(&body).unwrap(), body) + }; + let (mitred, mitre, _) = turned(None); + let (_, named, _) = turned(Some("mitre")); + let (swept_session, swept, body) = turned(Some("swept")); + eprintln!("mitre: {} faces, {:.9}; swept: {} faces, {:.9}", mitre.faces, mitre.volume, swept.faces, swept.volume); + let r: f64 = 1.0; + let (a, m) = ((1.0 - PI / 4.0) * r * r, (5.0 / 6.0 - PI / 4.0) * r * r * r); + let near = |v: f64, want: f64| (v - want).abs() < 1e-9 * want; + assert!(near(mitre.volume, 12500.0 + 40.0 * a + 8.0 * m), "{}", mitre.volume); + assert!(near(swept.volume, 12500.0 + 40.0 * a + 2.0 * PI * m), "{}", swept.volume); + assert_eq!(named.volume.to_bits(), mitre.volume.to_bits(), "mitre is the default"); + assert_eq!((mitre.faces, swept.faces), (15, 19)); + // The four corner faces (the record's torus is a ring torus, so a horn torus is its exact + // rational form): every point on the horn torus about its upright edge. + let mut corners = 0; + for f in &body.record().faces { + if !matches!(f.surface, solidcore_record::brep::Surface::RationalSpline { .. }) { + continue; + } + corners += 1; + let eval = solidcraft_geom::brep::eval::SurfaceEval::new(&f.surface).unwrap(); + let [[u0, u1], [v0, v1]] = f.domain; + for i in 0..=4 { + for j in 0..=4 { + let p = eval.point([u0 + (u1 - u0) * f64::from(i) / 4.0, v0 + (v1 - v0) * f64::from(j) / 4.0]).unwrap(); + let (cx, cy) = (if p.x < 20.0 { 15.0 } else { 25.0 }, if p.y < 15.0 { 10.0 } else { 20.0 }); + let rho = (p.x - cx).hypot(p.y - cy); + let off = ((rho - r).powi(2) + (p.z - 10.0 - r).powi(2)).sqrt() - r; + assert!(off.abs() < 1e-9, "{p:?} is {off} off the horn torus"); + } + } + } + assert_eq!(corners, 4); + assert!(!mitred.doc.to_json().contains("\"turn\"")); + assert!(swept_session.doc.to_json().contains("\"turn\": \"swept\"")); + let mut s = boss(); + let e = s.execute("solid.fillet", &json!({"edges": BASE, "radius": 1, "turn": "round"})).unwrap_err().to_string(); + assert!(e.contains("unknown turn `round` (mitre or swept)"), "{e}"); + let e = s.execute("solid.fillet", &json!({"edges": BASE, "radius": 1, "turn": "swept", "type": "chord"})).unwrap_err().to_string(); + assert!(e.contains(solidcraft_doc::SWEPT_TAKES), "{e}"); + // A pocket 5 deep in the plate, its floor's edges rounded: the rounds meet at its concave + // upright edges. + let mut s = Session::default(); + run(&mut s, "solid.box", &json!({"length": 40, "width": 30, "height": 10, "body_name": "P"})); + run(&mut s, "solid.box", &json!({"corner": [10, 10, 5], "length": 20, "width": 10, "height": 6, "operation": "cut"})); + let rim = json!([[20, 10, 5], [30, 15, 5], [20, 20, 5], [10, 15, 5]]); + let e = s.execute("solid.fillet", &json!({"edges": rim, "radius": 1, "turn": "swept"})).unwrap_err().to_string(); + eprintln!("swept along a pocket's rim: {e}"); + assert!(e.contains("swept corner at (") && e.contains("round that edge at a radius of at least 1 first"), "{e}"); } } #[cfg(test)] diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs index 77b80fe35..b23dae96c 100644 --- a/crates/engine/src/cmd/features_more.rs +++ b/crates/engine/src/cmd/features_more.rs @@ -1,11 +1,12 @@ //! Rib, Web, Emboss, Replace Face, Align and Remove. use serde_json::Value; -use solidcraft_doc::FeatureKind; +use solidcore_record::Vec3; use solidcraft_doc::expr::Kind; +use solidcraft_doc::{AlignFrame, FeatureKind}; use solidcraft_doc::{BodyName, SketchId}; use solidcraft_doc::{Dir, FacePick, Position}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use super::CommandSpec; use super::features::{ @@ -43,7 +44,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.align", "Align", align) .at("SOLID", "MODIFY") .icon("align") - .params("bodies: [names]; from: [x,y,z] | \"origin\" | {snap: vertex|edge_mid|face_center|circle_center, at: [x,y,z]} | from_face: [x,y,z] | from_plane: XY|XZ|YZ|construction or offset plane name or id|{origin, normal}; to: (the same) | to_face: [x,y,z] | to_plane: (a plane as from_plane; the point or face goes onto it along its normal, and the plane may move later: the bodies follow); faces and planes also turn to meet; flip?: bool"), + .params("bodies: [names]; from: [x,y,z] | \"origin\" | {snap: vertex|edge_mid|face_center|circle_center, at: [x,y,z]} | from_face: [x,y,z] | from_plane: XY|XZ|YZ|construction or offset plane name or id|{origin, normal}; to: (the same) | to_face: [x,y,z] | to_plane: (a plane as from_plane; the point or face goes onto it along its normal, and the plane may move later: the bodies follow); from_frame / to_frame: a frame found again whenever the design changes, so the bodies follow it, in place of that side's point, face or plane: a joint origin as joint.create takes one ({face|circle|edge|point: [x,y,z]}, a face's name, a named joint origin) or {sketch, point|curve} (a sketch point, or a circle's, arc's or ellipse's centre, z along the sketch's normal), on the bodies' own component; faces, planes and frames also turn to meet; flip?: bool; axes?: [x, y, z] (point-to-point only: which world axes the offset moves along; default all three, at least one true); angle?: expr (a turn about the target's direction after the move)"), CommandSpec::new("solid.remove", "Remove", remove).at("SOLID", "MODIFY").icon("delete").params("bodies: [names] (removed from here on in the timeline)"), ]; @@ -189,7 +190,7 @@ fn emboss(s: &mut Session, p: &Value) -> Result { let face = if let Some(value) = p.get("face") { let local = vec3(value).ok_or_else(|| bad(cmd, "`face` must be a finite point [x,y,z]"))?; let at = solidcraft_doc::apply_point(&s.active_component_frame(), local); - let state = s.world_state(); + let state = s.world_state()?; let mut candidates = Vec::new(); // The nearest face off the point: (distance, body), for the error when none holds it. let mut nearest: Option<(f64, &str)> = None; @@ -328,7 +329,7 @@ fn infer_emboss_selection( let regions = solidcraft_doc::select_profiles(ss, profiles).map_err(|e| bad(cmd, e.to_string()))?; let sketch_owner = s.doc.feature(sketch).map(|f| f.component).ok_or_else(|| bad(cmd, "profile sketch no longer exists"))?; let d = s.doc.eval(&s.doc.with_design_unit(depth, Kind::Length), Kind::Length).map_err(|e| bad(cmd, e.to_string()))?; - let world = s.world_state(); + let world = s.world_state()?; let placed = s.placed_document(); let mut chosen = None; let mut faces = 0usize; @@ -349,7 +350,7 @@ fn infer_emboss_selection( let body_frame = face.body_frame(&placed, raw).map_err(|e| bad(cmd, e.to_string()))?; let inverse = solidcraft_doc::mat_inverse(&body_frame).ok_or_else(|| bad(cmd, "invalid cylinder body frame"))?; let displayed = world.sketch(sketch).ok_or_else(|| bad(cmd, "the profile sketch is not displayed"))?; - let plane = solidcraft_geom::Plane::new( + let plane = solidcore_record::Plane::new( solidcraft_doc::apply_point(&inverse, displayed.plane.origin), solidcraft_doc::apply_vector(&inverse, displayed.plane.x), solidcraft_doc::apply_vector(&inverse, displayed.plane.y), @@ -389,7 +390,7 @@ fn replace_face(s: &mut Session, p: &Value) -> Result { let target = match p.get("target_face").and_then(vec3) { Some(tp) => { let n = super::face::face_normal(s, tp).ok_or_else(|| bad(cmd, "the target face must be planar"))?; - let plane = solidcraft_geom::Plane::from_normal(tp, n).ok_or_else(|| bad(cmd, "the target face's plane"))?; + let plane = solidcore_record::Plane::from_normal(tp, n).ok_or_else(|| bad(cmd, "the target face's plane"))?; solidcraft_doc::PlaneRef::Custom { plane } } None => plane_param(s, p.get("target"), cmd)?, @@ -398,6 +399,21 @@ fn replace_face(s: &mut Session, p: &Value) -> Result { add_feature(s, p, FeatureKind::ReplaceFace { faces: faces.into_iter().map(FacePick).collect(), target, body: body.map(BodyName) }) } +/// `axes`: three booleans, one per world axis, for a point-to-point Align. +/// `None` when the call does not restrict the move. +fn axes_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("axes").filter(|v| !v.is_null()) else { return Ok(None) }; + let a = v.as_array().filter(|a| a.len() == 3).ok_or_else(|| bad(cmd, "`axes` must be [x, y, z] booleans"))?; + let mut mask = [false; 3]; + for (slot, v) in mask.iter_mut().zip(a) { + *slot = v.as_bool().ok_or_else(|| bad(cmd, "`axes` must be [x, y, z] booleans"))?; + } + if !mask.iter().any(|on| *on) { + return Err(bad(cmd, "`axes` must enable at least one of X, Y and Z")); + } + Ok((mask != [true; 3]).then_some(mask)) +} + fn align(s: &mut Session, p: &Value) -> Result { let cmd = "solid.align"; let bodies = string_list(cmd, p, "bodies")?; @@ -428,12 +444,26 @@ fn align(s: &mut Session, p: &Value) -> Result { p.get(key).map(|_| super::features::plane_param(s, p.get(key), cmd)).transpose() }; let (from_plane, to_plane) = (plane(s, "from_plane")?, plane(s, "to_plane")?); - let world_pick = |s: &Session, pk: &str, fk: &str, plane: &Option| -> Result<(Vec3, Option)> { - if plane.is_some() { + // Or a frame (#6257), found again when the feature is evaluated. + let (from_frame, to_frame) = (align_frame(s, p, "from", &bodies)?, align_frame(s, p, "to", &bodies)?); + // A target on the bodies that move would move away with them: it must be found the same + // without them. + if let Some(fr @ AlignFrame::Origin { .. }) = &to_frame { + let st = s.model.state(); + let mut rest = (*st).clone(); + rest.bodies.retain(|b| !bodies.contains(&b.name)); + let same = |(a, n): (Vec3, Vec3), (b, m): (Vec3, Vec3)| a.dist(b) <= 1e-9 * (1.0 + a.len()) && n.dot(m) > 1.0 - 1e-12; + if !matches!((fr.resolve(&s.doc, &st), fr.resolve(&s.doc, &rest)), (Ok(a), Ok(b)) if same(a, b)) { + return Err(bad(cmd, "`to_frame` is on a body that moves: pick the target on another body or on a sketch")); + } + } + // Worked out from the plane or the frame when the feature is evaluated. + let held = |plane: &Option, frame: &Option| plane.is_some() || frame.is_some(); + let world_pick = |s: &Session, pk: &str, fk: &str, held: bool| -> Result<(Vec3, Option)> { + if held { if p.get(pk).is_some() || p.get(fk).is_some() { return Err(bad(cmd, format!("give `{pk}_plane` or `{pk}`/`{fk}`, not both"))); } - // Worked out from the plane when the feature is evaluated. return Ok((Vec3::ZERO, None)); } if let Some(fp) = p.get(fk).and_then(vec3) { @@ -448,28 +478,52 @@ fn align(s: &mut Session, p: &Value) -> Result { if let Some(o) = p.get(pk).filter(|v| v.is_object()) { let at = o.get("at").and_then(vec3).ok_or_else(|| bad(cmd, format!("`{pk}.at` must be [x, y, z]")))?; let kind = o.get("snap").and_then(Value::as_str).unwrap_or("vertex"); - return snap_point(s, kind, at).map(|q| (q, None)).ok_or_else(|| bad(cmd, format!("no {kind} to snap to near `{pk}`"))); + return snap_point(&*s.world_state()?, kind, at).map(|q| (q, None)).ok_or_else(|| bad(cmd, format!("no {kind} to snap to near `{pk}`"))); } p.get(pk) .and_then(vec3) .map(|v| (v, None)) .ok_or_else(|| bad(cmd, format!("give `{pk}`, `{fk}` or `{pk}_plane` ([x, y, z], \"origin\", or a plane)"))) }; - let pick = |s: &Session, pk: &str, fk: &str, plane: &Option| -> Result<(Vec3, Option)> { - let (at, n) = world_pick(s, pk, fk, plane)?; - if plane.is_some() { + let pick = |s: &Session, pk: &str, fk: &str, held: bool| -> Result<(Vec3, Option)> { + let (at, n) = world_pick(s, pk, fk, held)?; + if held { return Ok((at, n)); } Ok((solidcraft_doc::apply_point(&inverse, at), n.and_then(|n| solidcraft_doc::apply_vector(&inverse, n).normalized()))) }; - let (from, from_normal) = pick(s, "from", "from_face", &from_plane)?; - let (to, to_normal) = pick(s, "to", "to_face", &to_plane)?; - // Faces turn only to meet another face or a plane; a plane's normal is read when evaluated. + let (from, from_normal) = pick(s, "from", "from_face", held(&from_plane, &from_frame))?; + let (to, to_normal) = pick(s, "to", "to_face", held(&to_plane, &to_frame))?; + // A turn about the target's direction after the move. + let angle = expr(p, "angle"); + if let Some(a) = &angle { + check_expr(s, a, Kind::Angle, cmd, "angle")?; + if to_normal.is_none() && !held(&to_plane, &to_frame) { + return Err(bad(cmd, "`angle` turns about the target's direction: give `to_frame`, `to_face` or `to_plane`")); + } + } + // Faces turn only to meet another face, a plane or a frame; a plane's normal and a frame's z + // are read when evaluated. A target face's normal is also the axis of an `angle`. let (from_normal, to_normal) = match (from_normal, to_normal) { (Some(a), Some(b)) => (Some(a), Some(b)), - (a, b) if from_plane.is_some() || to_plane.is_some() => (a, b), + (a, b) if held(&from_plane, &from_frame) || held(&to_plane, &to_frame) || angle.is_some() => (a, b), _ => (None, None), }; + let axes = axes_param(p, cmd)?; + if axes.is_some() && (held(&from_plane, &from_frame) || held(&to_plane, &to_frame) || from_normal.is_some() || to_normal.is_some()) { + return Err(bad( + cmd, + "`axes` applies to point-to-point alignment: leave out `from_face`, `to_face`, `from_plane`, `to_plane`, `from_frame` and `to_frame`", + )); + } + // The directions are stored in the same frame as `from`/`to` (the first moved body's frame). + let axes = axes.map(|mask| { + mask.into_iter() + .zip([Vec3::X, Vec3::Y, Vec3::Z]) + .filter(|&(on, _)| on) + .map(|(_, world)| Dir(solidcraft_doc::apply_vector(&inverse, world).normalized().unwrap_or(world))) + .collect::>() + }); let flip = bool_(p, "flip").unwrap_or(false); add_feature( s, @@ -483,10 +537,58 @@ fn align(s: &mut Session, p: &Value) -> Result { flip, from_plane, to_plane, + axes, + from_frame, + to_frame, + angle, }, ) } +/// The longest sketch point or curve id an Align frame takes. +const MAX_SKETCH_ID: usize = 256; + +/// An Align side's frame (#6257), `_frame`: a joint origin as `joint.create` takes one, or a +/// sketch point or the centre of a sketch circle, arc or ellipse (`{sketch, point|curve}`), on the +/// moved bodies' component (all of them on one, placed once). It takes the place of ``, +/// `_face` and `_plane`, and is checked to resolve now. +fn align_frame(s: &Session, p: &Value, key: &str, bodies: &[String]) -> Result> { + let cmd = "solid.align"; + let fk = format!("{key}_frame"); + let Some(v) = p.get(&fk).filter(|v| !v.is_null()) else { return Ok(None) }; + if let Some(other) = [key.to_string(), format!("{key}_face"), format!("{key}_plane")].into_iter().find(|k| p.get(k).is_some()) { + return Err(bad(cmd, format!("give `{fk}` or `{other}`, not both"))); + } + let st = s.model.state(); + let (frame, on) = match v.get("sketch") { + Some(sk) => { + let sketch = super::features::sketch_id(s, Some(sk), cmd, &fk)?; + let id = |k: &str| str_(v, k).filter(|n| !n.is_empty() && n.chars().count() <= MAX_SKETCH_ID).map(str::to_string); + let frame = match (id("point"), id("curve")) { + (Some(point), None) => AlignFrame::SketchPoint { sketch: SketchId(sketch), point }, + (None, Some(curve)) => AlignFrame::SketchCurve { sketch: SketchId(sketch), curve }, + _ => return Err(bad(cmd, format!("`{fk}`: a sketch frame takes `point` or `curve` (an id of 1 to {MAX_SKETCH_ID} characters)"))), + }; + (frame, s.doc.feature(sketch).map_or(0, |f| f.component)) + } + None => { + let origin = super::joints::origin_param(s, Some(v), cmd)?; + let on = super::joints::component_of(s, origin.occurrence); + (AlignFrame::Origin { origin: Box::new(origin) }, on) + } + }; + // The move is worked out in that component's coordinates: every body must be in it, and a + // component placed twice would not say which placement the picks were made in. + if bodies.iter().any(|b| st.body(b).map_or(0, |b| s.doc.model_body_component(b)) != on) { + return Err(bad(cmd, format!("not supported yet: `{fk}` on another component than the bodies"))); + } + if on != 0 && s.doc.occurrences.iter().filter(|o| o.component == on).count() != 1 { + return Err(bad(cmd, format!("not supported yet: `{fk}` on a component placed more than once"))); + } + frame.resolve(&s.doc, &st).map_err(|e| bad(cmd, format!("`{fk}`: {e}")))?; + Ok(Some(frame)) +} + fn remove(s: &mut Session, p: &Value) -> Result { let cmd = "solid.remove"; let bodies = string_list(cmd, p, "bodies")?; @@ -505,9 +607,8 @@ fn remove(s: &mut Session, p: &Value) -> Result { mod tests; /// A snap point near `at` on the model: the nearest vertex, edge midpoint, planar face's centre -/// or circular edge's centre (the end of a cylindrical face). -pub(crate) fn snap_point(s: &Session, kind: &str, at: Vec3) -> Option { - let st = s.world_state(); +/// or circular edge's centre (the end of a cylindrical face) of the placed model `st`. +pub(crate) fn snap_point(st: &solidcraft_doc::ModelState, kind: &str, at: Vec3) -> Option { let near = |pts: Vec| pts.into_iter().min_by(|a, b| a.dist(at).total_cmp(&b.dist(at))); match kind { "vertex" => near( diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index a3fb1bc8a..83ea9ad97 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -1,4 +1,5 @@ use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -17,14 +18,14 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() { for (height, expected) in [(8., "cut"), (12., "join")] { let params = json!({"faces":[[offset+2.,2,10],[offset+8.,8,10]],"face_body":"Stock", "to":[offset+5.,5,height],"direction":"negative"}); - assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected)); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some(expected)); } for distance in [-2., 2.] { let mut params = json!({"faces":[[offset+2.,2,10],[offset+8.,8,10]],"distance":distance}); let expected = if distance < 0. { "cut" } else { "join" }; - assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected)); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some(expected)); params["face_body"] = json!("Stock"); - assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected)); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some(expected)); let mut actual = s.scratch(); if offset != 0. { run(&mut actual, "component.activate", json!({"component":part["component"]})); @@ -54,7 +55,7 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() { let mut params = json!({"faces":[[32,2,10],[38,8,10]],"face_body":"Stock","distance":-2}); // The picked part takes part beside the active component's own body (#5679): going in cuts // it, and the top level's own body is left alone. - assert_eq!(crate::auto_operation(&s, ¶ms), Some("cut"), "the picked body takes part beside the active component's own"); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some("cut"), "the picked body takes part beside the active component's own"); for operation in ["auto", "cut"] { let mut t = s.scratch(); let mut p = params.clone(); @@ -69,9 +70,9 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() { ); } params["participants"] = json!(["Stock"]); - assert_eq!(crate::auto_operation(&s, ¶ms), Some("cut")); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some("cut")); params["participants"] = json!(["Other"]); - assert_eq!(crate::auto_operation(&s, ¶ms), Some("join")); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some("join")); } /// A part inserted into a new design (a STEP file) sits in its own component under the empty @@ -95,7 +96,7 @@ fn sketch_on_a_part_in_another_component_joins_and_cuts_it() { // Through All with no distance cut nothing and made a separate body. (json!({"through_all":true,"direction":"negative"}), "cut", 1000. - 10. / 3. * added), ] { - assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected), "{params}"); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some(expected), "{params}"); for operation in ["auto", expected] { let mut t = s.scratch(); let mut p = params.clone(); @@ -156,7 +157,7 @@ fn every_inward_extrude_into_a_part_in_another_component_cuts_it() { if from_sketch { p["profiles"] = json!("all"); } - let auto = crate::auto_operation(&t, &p); + let auto = crate::auto_operation(&t, &p).unwrap(); if operation == "auto" && auto != Some(expected) { wrong.push(format!("{params}: auto reads {auto:?}, expected {expected}")); } @@ -193,7 +194,7 @@ fn turned_part(base: bool) -> (Session, solidcraft_doc::Mat) { } /// A sketch on the face at world point `at`, with `draw` given the point's place in the sketch. -fn sketch_on_face(s: &mut Session, at: solidcraft_geom::Vec3, draw: impl FnOnce(&mut Session, solidcraft_geom::Vec2, solidcraft_geom::Plane)) { +fn sketch_on_face(s: &mut Session, at: solidcore_record::Vec3, draw: impl FnOnce(&mut Session, solidcore_record::Vec2, solidcore_record::Plane)) { run(s, "sketch.create", json!({"plane": {"face": [at.x, at.y, at.z]}, "project_edges": false})); let plane = s .doc @@ -223,12 +224,12 @@ fn a_sketch_on_a_turned_sub_components_face_cuts_and_joins_it_from_the_top_level let hole = std::f64::consts::PI * 4.0 * 3.0; for base in [false, true] { let (mut s, placed) = turned_part(base); - let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0)); + let top = solidcraft_doc::apply_point(&placed, solidcore_record::Vec3::new(5.0, 5.0, 10.0)); sketch_on_face(&mut s, top, |s, c, _| { run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); }); for (distance, expected) in [(-3.0, "cut"), (3.0, "join")] { - assert_eq!(crate::auto_operation(&s, &json!({"distance": distance})), Some(expected), "base {base}, {distance}"); + assert_eq!(crate::auto_operation(&s, &json!({"distance": distance})).unwrap(), Some(expected), "base {base}, {distance}"); for operation in ["auto", expected] { let mut t = s.scratch(); run(&mut t, "solid.extrude", json!({"distance": distance, "operation": operation})); @@ -239,7 +240,7 @@ fn a_sketch_on_a_turned_sub_components_face_cuts_and_joins_it_from_the_top_level assert!((body_volume(&t, "Stock") - want).abs() < 1e-3 * hole, "{case}: {}", body_volume(&t, "Stock")); // In the part's own frame: through the middle of its top, not beside it. let stock = t.model.state().body("Stock").unwrap().mesh(); - let at = |x: f64, y: f64, z: f64| stock.contains(solidcraft_geom::Vec3::new(x, y, z)); + let at = |x: f64, y: f64, z: f64| stock.contains(solidcore_record::Vec3::new(x, y, z)); if expected == "cut" { assert!(!at(5.0, 5.0, 8.0) && at(5.0, 5.0, 6.0) && at(1.0, 1.0, 9.0), "{case}"); } else { @@ -261,7 +262,7 @@ fn a_revolve_from_a_turned_sub_components_face_joins_and_cuts_it_from_the_top_le let half = std::f64::consts::PI * 3.0; for (operation, want) in [("join", 1000.0 + half), ("cut", 1000.0 - half)] { let (mut s, placed) = turned_part(true); - let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0)); + let top = solidcraft_doc::apply_point(&placed, solidcore_record::Vec3::new(5.0, 5.0, 10.0)); let mut axis = json!(null); sketch_on_face(&mut s, top, |s, c, plane| { run(s, "sketch.rectangle.two_point", json!({"p0": [c.x - 3.0, c.y], "p1": [c.x + 3.0, c.y + 1.0]})); @@ -281,8 +282,8 @@ fn a_revolve_from_a_turned_sub_components_face_joins_and_cuts_it_from_the_top_le #[test] fn a_loft_from_a_turned_sub_components_face_joins_it_from_the_top_level() { let (mut s, placed) = turned_part(true); - let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0)); - let mut centre = solidcraft_geom::Vec2::new(0.0, 0.0); + let top = solidcraft_doc::apply_point(&placed, solidcore_record::Vec3::new(5.0, 5.0, 10.0)); + let mut centre = solidcore_record::Vec2::new(0.0, 0.0); sketch_on_face(&mut s, top, |s, c, _| { run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); centre = c; @@ -307,13 +308,13 @@ fn a_loft_from_a_turned_sub_components_face_joins_it_from_the_top_level() { fn a_cut_from_the_top_level_shows_in_every_placement_and_a_later_placement_is_refused() { let (mut s, placed) = turned_part(true); let second = run(&mut s, "occurrence.copy", json!({"component": "Part", "translate": [0, 40, 0]}))["occurrence"].as_u64().unwrap(); - let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0)); + let top = solidcraft_doc::apply_point(&placed, solidcore_record::Vec3::new(5.0, 5.0, 10.0)); let mut first = s.scratch(); sketch_on_face(&mut first, top, |s, c, _| { run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); }); run(&mut first, "solid.extrude", json!({"distance": -3, "operation": "cut"})); - let world = first.world_state(); + let world = first.world_state().unwrap(); let placements: Vec = world.bodies.iter().filter(|b| b.definition_name() == "Stock").map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); let want = 1000.0 - std::f64::consts::PI * 4.0 * 3.0; @@ -321,7 +322,7 @@ fn a_cut_from_the_top_level_shows_in_every_placement_and_a_later_placement_is_re assert!(placements.iter().all(|v| (v - want).abs() < 1e-2), "{placements:?}"); let (_, moved) = s.doc.path_placement(&[second]).unwrap(); - let top = solidcraft_doc::apply_point(&moved, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0)); + let top = solidcraft_doc::apply_point(&moved, solidcore_record::Vec3::new(5.0, 5.0, 10.0)); sketch_on_face(&mut s, top, |s, c, _| { run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); }); @@ -339,11 +340,11 @@ fn a_cut_from_the_top_level_shows_in_every_placement_and_a_later_placement_is_re #[test] fn a_sketch_on_a_top_level_body_beside_a_turned_part_cuts_only_that_body() { let (mut s, _) = turned_part(true); - sketch_on_face(&mut s, solidcraft_geom::Vec3::new(-30.0, -30.0, 5.0), |s, c, _| { + sketch_on_face(&mut s, solidcore_record::Vec3::new(-30.0, -30.0, 5.0), |s, c, _| { run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); }); - assert_eq!(crate::auto_operation(&s, &json!({"distance": -2})), Some("cut")); - assert_eq!(crate::auto_operation(&s, &json!({"distance": 2})), Some("join")); + assert_eq!(crate::auto_operation(&s, &json!({"distance": -2})).unwrap(), Some("cut")); + assert_eq!(crate::auto_operation(&s, &json!({"distance": 2})).unwrap(), Some("join")); let made = run(&mut s, "solid.extrude", json!({"distance": -2, "operation": "auto"})); let feature = s.doc.feature(made["feature"].as_u64().unwrap()).unwrap(); assert!(feature.participants.is_empty(), "{:?}", feature.participants); @@ -529,12 +530,12 @@ fn cylinder_badge() -> Session { } fn exact_cylinder_volume(s: &Session) -> f64 { - s.model.state().body("Sleeve").unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume + s.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume } #[test] fn cylinder_emboss_persists_selection_and_replays_radial_depth() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut s = cylinder_badge(); let before = exact_cylinder_volume(&s); run( @@ -546,7 +547,7 @@ fn cylinder_emboss_persists_selection_and_replays_radial_depth() { let state = s.model.state(); let body = &state.body("Sleeve").unwrap().body; assert_eq!(body.shell_count(), 1); - let mesh = body.tessellate_with(0.001, true).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap(); assert!(mesh.contains(Vec3::new(-10.5 * 0.15_f64.sin(), 10.5 * 0.15_f64.cos(), 7.5))); let feature = s.doc.find_feature("Raised Badge").unwrap(); assert!( @@ -628,9 +629,16 @@ fn cylinder_cross_component_emboss_keeps_source_owner_and_placements() { let placements = serde_json::to_value(&s.doc.occurrences).unwrap(); let target = s .world_state() + .unwrap() .bodies .iter() - .find(|b| b.body.tessellate_with(0.001, true).unwrap().contains(solidcraft_geom::Vec3::new(40.5 + pick_offset, 0., 7.5))) + .find(|b| { + b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(solidcore_record::Vec3::new( + 40.5 + pick_offset, + 0., + 7.5, + )) + }) .unwrap() .name .clone(); @@ -652,9 +660,15 @@ fn cylinder_cross_component_emboss_keeps_source_owner_and_placements() { let selected = s.doc.features.last().unwrap().face_names.first().unwrap(); assert!(!selected.is_empty() && source_names.contains(selected), "{selected:?} not in {source_names:?}"); assert!((exact_cylinder_volume(&s) - before - 21.).abs() < 0.02); - let world = s.world_state(); + let world = s.world_state().unwrap(); for x in [39.5, 119.5] { - assert!(world.bodies.iter().any(|b| b.body.tessellate_with(0.001, true).unwrap().contains(solidcraft_geom::Vec3::new(x, 0., 7.5)))); + assert!( + world.bodies.iter().any(|b| b + .body + .mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)) + .unwrap() + .contains(solidcore_record::Vec3::new(x, 0., 7.5))) + ); } let mut loaded = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Default::default() }; loaded.refresh(); @@ -802,7 +816,16 @@ fn check_body_offset(auto: bool) { assert!((exact_cylinder_volume(&s) - before - 21.).abs() < 0.02); assert_eq!(s.doc.body_offsets["Sleeve"], offset); assert_eq!(s.doc.body_component("Sleeve", s.model.state().body("Sleeve").unwrap().feature), holder); - assert!(s.world_state().body("Sleeve").unwrap().body.tessellate_with(0.001, true).unwrap().contains(solidcraft_geom::Vec3::new(0., 10.5, 7.5))); + assert!( + s.world_state() + .unwrap() + .body("Sleeve") + .unwrap() + .body + .mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)) + .unwrap() + .contains(solidcore_record::Vec3::new(0., 10.5, 7.5)) + ); } #[test] @@ -833,6 +856,50 @@ fn replace_face_align_remove() { assert_eq!(measure(&mut s)["body_count"], 1); } +#[test] +fn align_can_keep_the_offset_to_chosen_axes() { + let aligned = |axes: Option| { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + run(&mut s, "solid.box", json!({"corner": [50, 20, 30], "length": 10, "width": 10, "height": 10, "body_name": "B"})); + let mut p = json!({"bodies": ["A"], "from": [0, 0, 0], "to": [50, 20, 30]}); + if let Some(axes) = axes { + p["axes"] = axes; + } + run(&mut s, "solid.align", p); + s + }; + let min = |s: &mut Session| { + let m = measure(s); + let a = m["bodies"].as_array().unwrap().iter().find(|b| b["name"] == "A").unwrap().clone(); + let g = |i: usize| a["bbox"]["min"][i].as_f64().unwrap_or(f64::NAN); + [g(0), g(1), g(2)] + }; + let close = |got: [f64; 3], want: [f64; 3]| got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-6); + assert!(close(min(&mut aligned(Some(json!([false, false, true])))), [0.0, 0.0, 30.0])); + assert!(close(min(&mut aligned(Some(json!([true, false, false])))), [50.0, 0.0, 0.0])); + assert!(close(min(&mut aligned(Some(json!([false, true, false])))), [0.0, 20.0, 0.0])); + assert!(close(min(&mut aligned(Some(json!([true, true, true])))), [50.0, 20.0, 30.0])); + assert!(close(min(&mut aligned(None)), [50.0, 20.0, 30.0])); + + // Refusal cases + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + for axes in [json!([false, false, false]), json!([true, false]), json!([true, false, "yes"])] { + assert!(s.execute("solid.align", &json!({"bodies": ["A"], "from": [0, 0, 0], "to": [1, 2, 3], "axes": axes})).is_err(), "{axes}"); + } + // Face/plane alignment cannot take an axis mask. + assert!( + s.execute("solid.align", &json!({"bodies": ["A"], "from_face": [5, 5, 10], "to_face": [5, 5, 20], "axes": [true, false, false]})).is_err() + ); + + // Normalisation: all axes true normalises to None in the saved feature + let made = run(&mut s, "solid.align", json!({"bodies": ["A"], "from": [0, 0, 0], "to": [1, 2, 3], "axes": [true, true, true]})); + let id = made["feature"].as_u64().expect("the feature id"); + let f = s.doc.feature(id).expect("the saved feature"); + assert!(matches!(&f.kind, solidcraft_doc::FeatureKind::Align { axes: None, .. })); +} + /// The z range and the x minimum of body `name`. fn z_x(s: &mut Session, name: &str) -> (f64, f64, f64) { let m = measure(s); @@ -884,6 +951,120 @@ fn align_takes_planes_and_the_origin() { assert!(s.execute("solid.align", &json!({"bodies": ["C"], "from": [0, 0, 0], "to_plane": "Nowhere"})).is_err()); } +/// The bounding box of body `name`: min and max. +fn bounds(s: &mut Session, name: &str) -> ([f64; 3], [f64; 3]) { + let m = measure(s); + let b = m["bodies"].as_array().and_then(|bs| bs.iter().find(|b| b["name"] == name)).cloned().unwrap_or_else(|| panic!("no body {name}: {m}")); + let g = |k: &str, i: usize| b["bbox"][k][i].as_f64().unwrap_or(f64::NAN); + ([g("min", 0), g("min", 1), g("min", 2)], [g("max", 0), g("max", 1), g("max", 2)]) +} + +fn assert_bounds(s: &mut Session, name: &str, lo: [f64; 3], hi: [f64; 3]) { + let (a, b) = bounds(s, name); + let near = |x: [f64; 3], y: [f64; 3]| x.iter().zip(y).all(|(p, q)| (p - q).abs() < 1e-6); + assert!(near(a, lo) && near(b, hi), "{name}: {a:?}..{b:?}, want {lo:?}..{hi:?}"); +} + +/// Align by frames (#6257): a body's face centre lands on a sketch circle's centre and follows it +/// when the parameter that places the circle changes; a turn about the target's z, a sketch point +/// as the target with a flip, and a frame on the body that follows the body's own edits. +#[test] +fn align_by_frames_follows_its_target() { + // B is 10 x 20 x 10 at (50, 0, 20); sketch S on XY has a circle at (X, 5) and a point at (20, X). + let target = || { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "X", "expression": "0 mm"})); + run(&mut s, "parameters.add", json!({"name": "H", "expression": "10 mm"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": "H", "corner": [50, 0, 20], "body_name": "B"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.circle.center", json!({"center": ["X", 5], "radius": 3, "id": "ring"})); + run(&mut s, "sketch.point", json!({"point": [20, "X"], "id": "p"})); + run(&mut s, "sketch.line", json!({"points": [[0, 30], [10, 30]], "ids": ["edge"]})); + run(&mut s, "sketch.finish", json!({})); + s + }; + let bottom = json!({"face": [55, 10, 20]}); + let ring = json!({"sketch": "S", "curve": "ring"}); + // The bottom face (z down) onto the circle (z up): no turn, B sits on XY centred on it. + let mut s = target(); + run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": bottom, "to_frame": ring})); + assert_bounds(&mut s, "B", [-5., -5., 0.], [5., 15., 10.]); + // The circle moves: B follows it, and still does in the saved design. + run(&mut s, "parameters.change", json!({"name": "X", "expression": "30 mm"})); + assert_bounds(&mut s, "B", [25., -5., 0.], [35., 15., 10.]); + let mut r = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert_bounds(&mut r, "B", [25., -5., 0.], [35., 15., 10.]); + // A quarter turn about the circle's z through its centre. + let mut s = target(); + run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": bottom, "to_frame": ring, "angle": 90})); + assert_bounds(&mut s, "B", [-10., 0., 0.], [10., 10., 10.]); + // The top face onto the sketch point, flipped (z along z): B hangs under XY. The frame on B + // follows B's own height. + let mut s = target(); + run( + &mut s, + "solid.align", + json!({"bodies": ["B"], "from_frame": {"face": [55, 10, 30]}, "to_frame": {"sketch": "S", "point": "p"}, "flip": true}), + ); + assert_bounds(&mut s, "B", [15., -10., -10.], [25., 10., 0.]); + run(&mut s, "parameters.change", json!({"name": "H", "expression": "15 mm"})); + assert_bounds(&mut s, "B", [15., -10., -15.], [25., 10., 0.]); + // A face pick with an angle about the target face's normal; a sketch frame onto a fixed point. + let mut s = target(); + run(&mut s, "solid.align", json!({"bodies": ["B"], "from": [50, 0, 20], "to_face": [55, 10, 30], "angle": 0})); + run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": {"sketch": "S", "point": "p"}, "to": [20, 0, 5]})); + // Refused: a side given twice, an angle with no target direction, a frame on the bodies that + // move, unknown or wrong sketch geometry, ids out of range, a degenerate frame. + let mut s = target(); + for bad in [ + json!({"from": [0, 0, 0], "from_frame": bottom, "to_frame": ring}), + json!({"from_frame": bottom, "to_frame": ring, "to_plane": "XY"}), + json!({"from_frame": bottom, "to": [0, 0, 0], "angle": 30}), + json!({"from_frame": bottom, "to_frame": ring, "angle": "3 mm"}), + json!({"from_frame": bottom, "to_frame": {"face": [55, 10, 30]}}), + json!({"from_frame": bottom, "to_frame": {"sketch": "Nope", "point": "p"}}), + json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": "zz"}}), + json!({"from_frame": bottom, "to_frame": {"sketch": "S", "curve": "edge"}}), + json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": "p", "curve": "ring"}}), + json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": ""}}), + json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": "q".repeat(300)}}), + json!({"from_frame": bottom, "to_frame": {"frame": {"origin": [0, 0, 0], "z": [0, 0, 0]}}}), + json!({"from_frame": {"face": "no such face"}, "to_frame": ring}), + ] { + let mut p = bad.clone(); + p["bodies"] = json!(["B"]); + assert!(s.execute("solid.align", &p).is_err(), "{bad}"); + } + // One frame does not move bodies of two components. + run(&mut s, "component.create", json!({"name": "Part"})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [80, 0, 0], "body_name": "P"})); + run(&mut s, "component.activate", json!({"component": "root"})); + assert!(s.execute("solid.align", &json!({"bodies": ["B", "P"], "from_frame": bottom, "to_frame": ring})).is_err()); + assert!(!s.doc.features.iter().any(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Align { .. })), "nothing refused was added"); + // A design file whose frame no longer resolves (here a degenerate one) fails the feature + // with a message; it never panics. + let mut s = target(); + run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": bottom, "to_frame": ring})); + let mut v: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + fn spoil(v: &mut Value) { + match v { + Value::Object(o) if o.get("type").and_then(Value::as_str) == Some("align") => { + o.insert( + "to_frame".into(), + json!({"type": "origin", "origin": {"occurrence": 0, "snap": {"type": "frame", "origin": [0, 0, 0], "z": [0, 0, 0]}}}), + ); + } + Value::Object(o) => o.values_mut().for_each(spoil), + Value::Array(a) => a.iter_mut().for_each(spoil), + _ => {} + } + } + spoil(&mut v); + let mut r = Session::new(solidcraft_doc::Document::from_json(&v.to_string()).unwrap()); + measure(&mut r); + assert!(r.model.results.iter().any(|x| x.error.as_deref().is_some_and(|e| e.contains("degenerate"))), "the Align reports its frame"); +} + #[test] fn coil_and_loft_to_a_point() { use std::f64::consts::{PI, TAU}; @@ -946,7 +1127,14 @@ fn loft_cut_through_a_shelled_basin_in_either_order() { assert!(r.is_ok(), "{pad:?} reverse {reverse}: {r:?}"); let v = volume(&mut s); assert!((v - want).abs() < 1.0, "{pad:?} reverse {reverse}: {v} vs {want}"); - assert_eq!(measure(&mut s)["body_count"], 1); + // The loft's top section is the basin's whole outline at z = 10, so the cut leaves the + // walls above it touching the rest only along their outer rim: two bodies, as a cut's + // pieces are (18480 mm³ of walls from z = 10 to 30, and the floor part below). + let m = measure(&mut s); + assert_eq!(m["body_count"], 2, "{m}"); + let upper = + m["bodies"].as_array().unwrap().iter().find(|b| b["bbox"]["min"][2].as_f64().is_some_and(|z| (z - 10.0).abs() < 1e-9)).unwrap(); + assert!((upper["volume_mm3"].as_f64().unwrap() - 18480.0).abs() < 1e-6, "{upper}"); } } // As a new body and joined: a valid solid of positive volume either way. @@ -963,7 +1151,7 @@ fn loft_cut_through_a_shelled_basin_in_either_order() { #[test] fn cylinder_auto_inference_saves_a_profile_anchor_and_replays_both_depth_signs() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; for mode in ["emboss", "deboss"] { let mut s = cylinder_badge(); let before = exact_cylinder_volume(&s); @@ -984,7 +1172,11 @@ fn cylinder_auto_inference_saves_a_profile_anchor_and_replays_both_depth_signs() let body = &state.body("Sleeve").unwrap().body; assert_eq!(body.shell_count(), 1); assert_eq!( - body.tessellate_with(0.001, true).unwrap().contains(Vec3::new(0., if mode == "emboss" { 10.5 } else { 9.5 }, 7.5)), + body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(Vec3::new( + 0., + if mode == "emboss" { 10.5 } else { 9.5 }, + 7.5 + )), mode == "emboss" ); run(&mut s, "edit.undo", json!({})); @@ -1019,16 +1211,19 @@ fn cylinder_auto_inference_ignores_remote_finite_tangent_walls_in_each_body_orde run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-2,5],"p1":[2,10]})); run(&mut s, "sketch.finish", json!({})); let before = exact_cylinder_volume(&s); - let remote = s.model.state().body("Remote").unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume; + let remote = s.model.state().body("Remote").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; run(&mut s, "solid.emboss", json!({"sketch":"Badge","depth":1})); assert!((exact_cylinder_volume(&s) - before - 21.).abs() < 0.02); - assert_eq!(s.model.state().body("Remote").unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume, remote); + assert_eq!( + s.model.state().body("Remote").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume, + remote + ); } } #[test] fn cylinder_auto_inference_retains_selected_holes_and_nested_islands() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; for mode in ["emboss", "deboss"] { let mut s = cylinder_badge(); run(&mut s, "sketch.edit", json!({"sketch":"Badge"})); @@ -1043,7 +1238,7 @@ fn cylinder_auto_inference_retains_selected_holes_and_nested_islands() { let st = s.model.state(); let body = &st.body("Sleeve").unwrap().body; assert_eq!(body.shell_count(), 1); - let mesh = body.tessellate_with(0.001, true).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap(); for (s, raised) in [(0., true), (0.75, false), (1.5, true)] { let theta = s / 10.0_f64; let radius = if mode == "emboss" { 10.5 } else { 9.5 }; @@ -1113,7 +1308,7 @@ fn loft_joined_onto_a_box_exports_one_connected_mesh() { let v = volume(&mut s); assert!(rel(v, 24000.0 + loft) < 1e-5, "{v} vs {}", 24000.0 + loft); // The exported mesh, its vertices merged, is one connected piece. - let mesh = s.model.state().body("Box").unwrap().body.tessellate(0.01).unwrap(); + let mesh = s.model.state().body("Box").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); let (positions, triangles) = solidcraft_io::weld(&mesh.positions, &mesh.triangles, 1e-4); let mut piece: Vec = (0..positions.len()).collect(); let root = |piece: &mut Vec, mut i: usize| { @@ -1293,7 +1488,7 @@ fn cutting_a_text_removes_each_letter_whether_its_letters_stand_apart_or_touch() } else { run(&mut s, "sketch.text", json!({"text":text,"at":[5,12],"height":14})); } - let state = s.world_state(); + let state = s.world_state().unwrap(); let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); // The profiles cut: the letters, not their counters (the inside of an O, whose outline // is a hole of its letter). @@ -1308,16 +1503,79 @@ fn cutting_a_text_removes_each_letter_whether_its_letters_stand_apart_or_touch() run(&mut s, "solid.extrude", json!({"distance":2,"operation":"cut"})); let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); assert!((volume - (200.0 * 40.0 * 10.0 - 2.0 * area)).abs() < 1e-3 * area, "{text:?}: {volume} for {area} mm² cut 2 mm deep"); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } } +/// The area, perimeter and Steiner coefficient C of `regions`: offset outward by e, convex +/// corners rounded and reflex ones trimmed where the offsets cross, a region's area is +/// A + P e + C e² while the offset meets nothing, C being half each loop's turning (π for an +/// outer loop, −π for a hole) less tan(t/2) − t/2 at each reflex corner of turn t. +fn steiner(regions: &[&solidcore_record::Region2]) -> (f64, f64, f64) { + let (mut a, mut p, mut c) = (0.0, 0.0, 0.0); + for r in regions { + a += r.area(); + // Each loop with the material on its left. + let outer = (r.outer.ccw(), std::f64::consts::PI); + let holes = r.holes.iter().map(|h| (h.ccw().reversed(), -std::f64::consts::PI)); + for (l, half_turning) in std::iter::once(outer).chain(holes) { + p += l.segs.iter().map(|s| s.length()).sum::(); + c += half_turning; + for (s, n) in l.joints() { + let (u, v) = (s.end_tangent(), n.start_tangent()); + let t = -u.cross(v).atan2(u.dot(v)); + if t > 0.0 { + c -= (t / 2.0).tan() - t / 2.0; + } + } + } + } + (a, p, c) +} + +/// The text's letters (its profiles less their counters, a counter being a profile too). +fn letters(s: &Session) -> Vec { + let state = s.world_state().unwrap(); + let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); + let sorted = |ids: &[String]| { + let mut ids = ids.to_vec(); + ids.sort(); + ids + }; + let counter = |p: &solidcraft_sketch::Profile| ss.profiles.iter().any(|q| q.hole_curves.iter().any(|h| sorted(h) == sorted(&p.outer_curves))); + ss.profiles.iter().filter(|p| !counter(p)).map(|p| p.region.clone()).collect() +} + /// A text joined onto a block with a taper: its letters are spline and conic outlines whose -/// sides slope, standing on the block's face (run on into it) or hanging over its edge (a -/// straight foot first). An outward taper adds a little more than the straight text; one -/// steeper than the letters' strokes is refused, saying so. +/// sides slope, standing on the block's face or hanging over its edge. An outward taper grows +/// every letter, the t too (SMLib drafted it inward: its loop's normal, summed from the cross +/// products of its chords, pointed down). Each letter's section at height z is its outline +/// offset by e = z tan a, by the Round rule of area A + P e + C e² while the offset trims +/// nothing (Steiner, [`steiner`]), so the letter is A h + P k h²/2 + C k² h³/3 (k = tan a). That +/// holds exactly for the t at 3° and for s, l and o at 3° and 15°, each extruded alone (SMLib +/// measures them to 1e-9 of it). The concave joins of r, n, g and e are tighter than e already +/// at 3°, their swallowtails trimmed, the t's arms meet the trim by 15°, and the letters grow +/// into each other on the block: the whole word is checked for what holds exactly, one closed +/// body with the block, every letter's section half-way up holding the straight letter. #[test] fn a_tapered_text_joins_a_block_on_its_face_or_hanging_over_its_edge() { + let h = 2.0; + for (text, degs) in [("t", &[3.0f64][..]), ("s", &[3.0, 15.0]), ("l", &[3.0, 15.0]), ("o", &[3.0, 15.0])] { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY"})); + run(&mut s, "sketch.text", json!({"text":text,"at":[5,12],"height":8})); + let regions = letters(&s); + let (a, p, c) = steiner(®ions.iter().collect::>()); + run(&mut s, "sketch.finish", json!({})); + for ° in degs { + let k = deg.to_radians().tan(); + let exact = a * h + p * k * h * h / 2.0 + c * k * k * h.powi(3) / 3.0; + let mut t = s.scratch(); + run(&mut t, "solid.extrude", json!({"distance":h,"taper":format!("{deg} deg"),"corner":"round"})); + let v = volume(&mut t); + assert!((v - exact).abs() < 1e-6 * exact, "{text:?} {deg}°: {v}, {exact} by its outline"); + } + } for (at, hanging) in [([5.0, 12.0], false), ([150.0, 12.0], true)] { let mut s = Session::default(); run(&mut s, "sketch.create", json!({"plane":"XY"})); @@ -1326,24 +1584,39 @@ fn a_tapered_text_joins_a_block_on_its_face_or_hanging_over_its_edge() { run(&mut s, "solid.extrude", json!({"distance":-10})); run(&mut s, "sketch.create", json!({"plane":"XY"})); run(&mut s, "sketch.text", json!({"text":"tres long","at":at,"height":8})); - let state = s.world_state(); - let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); - // The letters' area, counters left out (a letter's hole is its own profile too). - let sorted = |ids: &[String]| { - let mut ids = ids.to_vec(); - ids.sort(); - ids - }; - let counter = |p: &solidcraft_sketch::Profile| ss.profiles.iter().any(|q| q.hole_curves.iter().any(|h| sorted(h) == sorted(&p.outer_curves))); - let area: f64 = ss.profiles.iter().filter(|p| !counter(p)).map(|p| p.area).sum(); + let regions = letters(&s); run(&mut s, "sketch.finish", json!({})); - let steep = s.execute("solid.extrude", &json!({"distance":2,"operation":"join","taper":"15 deg"})).unwrap_err(); - assert!(steep.to_string().contains("the taper closes the profile"), "{steep}"); - run(&mut s, "solid.extrude", json!({"distance":2,"operation":"join","taper":"3 deg"})); - let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); - let (block, text) = (200.0 * 40.0 * 10.0, 2.0 * area); - assert!(volume > block + text && volume < block + 1.3 * text, "hanging {hanging}: {volume} for {text} mm³ of straight text"); - assert_eq!(s.world_state().bodies.len(), 1); + for deg in [3.0, 15.0] { + for corner in [None, Some("round")] { + let mut t = s.scratch(); + let mut params = json!({"distance":h,"operation":"join","taper":format!("{deg} deg")}); + if let Some(corner) = corner { + params["corner"] = json!(corner); + } + run(&mut t, "solid.extrude", params); + let m = measure(&mut t); + let what = format!("hanging {hanging}, {deg}° {corner:?}"); + assert_eq!(m["bodies"].as_array().map(Vec::len), Some(1), "{what}: {m}"); + assert_eq!(m["bodies"][0]["closed"], true, "{what}: {m}"); + // Half-way up each letter is its outline grown by h/2 tan a: every point of the + // straight letter's outline lies inside. + let state = t.model.state(); + let mesh = state.bodies[0].body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap(); + for r in ®ions { + for seg in std::iter::once(&r.outer).chain(&r.holes).flat_map(|l| &l.segs) { + for i in 0..8 { + let q = seg.point_at(f64::from(i) / 8.0); + assert!( + mesh.contains(solidcore_record::Vec3::new(q.x, q.y, h / 2.0)), + "{what}: ({}, {}) outside the letter half-way up", + q.x, + q.y + ); + } + } + } + } + } } } @@ -1371,7 +1644,7 @@ fn a_tapered_cut_that_widens_cuts_from_small_corners() { let pocket = w * h * l + k * (w + h) * l * l + 4.0 / 3.0 * k * k * l.powi(3) - c * (r * r * l + r * k * l * l + k * k * l.powi(3) / 3.0); let v = volume(&mut s); assert!((v - (318.0 * 212.0 * 20.0 - pocket)).abs() < 1e-3 * pocket, "{deg}°: {v}, a {pocket} mm³ pocket"); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } } @@ -1418,7 +1691,7 @@ fn a_tapered_foot_under_a_part_joins_as_drawn() { // for a hair first. let tol = if round || half < 15.0 { 2e-4 } else { 1e-9 } * (part + frustum); assert!((v - (part + frustum)).abs() < tol, "round {round}, half {half}, taper {taper}: {v} for {}", part + frustum); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); let state = s.model.state(); let mesh = state.body("B").unwrap().mesh(); // Beside the part, above the foot's start: nothing. @@ -1610,7 +1883,7 @@ fn knife_edge_part() -> Session { /// the concave arc). It holds to about 1e-3 of what a blend removes here; the bounds below are /// about twice what each test reads. fn planned(s: &Session) -> f64 { - s.model.state().bodies.iter().map(|b| b.body.display_plan(2e-4).unwrap().evaluate().measure().volume).sum() + s.model.state().bodies.iter().map(|b| b.body.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(2e-4)).unwrap().evaluate().measure().volume).sum() } /// The middle of the part's arc. @@ -1689,38 +1962,6 @@ fn fillet_straight_edges_that_end_at_the_arc_wall() { } } -/// The vertical knife edge at the tip (the arc and the back face meeting at no angle) rounds to -/// the ball 2 from both, about 13 back from the tip: the cusp beyond the ball, on the tip's side -/// of its contacts, all the way up. -#[test] -fn fillet_the_knife_edge_at_the_tip() { - let cx = 62.166666666666664; - let (kx, ky) = (cx - (23.0f64 * 23.0 - 19.0 * 19.0).sqrt(), -2.0); - let (hx, hy) = (0.002, 0.0005); - let mut area = 0.0; - let mut x = kx + hx / 2.0; - while x < cx { - let lo = -21.0 + (441.0 - (x - cx) * (x - cx)).max(0.0).sqrt(); - for j in 0..((0.0 - lo) / hy).ceil() as usize { - let (y0, y1) = (lo + j as f64 * hy, (lo + (j + 1) as f64 * hy).min(0.0)); - let y = (y0 + y1) * 0.5; - let a = (y - ky).atan2(x - kx); - if (x - kx).hypot(y - ky) > 2.0 && a >= (-21.0 - ky).atan2(cx - kx) { - area += (y1 - y0) * hx; - } - } - x += hx; - } - let mut s = knife_edge_part(); - let before = planned(&s); - run(&mut s, "solid.fillet", json!({"edges": [[cx, 0.0, 5.0]], "radius": 2})); - let after = planned(&s); - assert!(rel(before - after, area * 10.0) < 5e-4, "removed {} vs {}", before - after, area * 10.0); - let mut s = knife_edge_part(); - run(&mut s, "solid.chamfer", json!({"edges": [[cx, 0.0, 5.0]], "distance": 2})); - assert!(before - planned(&s) > before - after, "the chamfer takes the ball's bulge off too"); -} - /// Rounds of the edges at the arc's top front corner, two or all three together (r 2): they meet /// in creases (with all three, a piece of sphere fills the corner). Each set takes off its rounds /// alone, less what each alone takes in a box about the corner, plus what they take there @@ -1750,7 +1991,10 @@ fn fillet_edges_meeting_at_the_front_corner_of_the_arc() { } /// The long top front edge rounded, then the small front-left upright as a fillet of its own -/// (as in the app): the new round ends in the earlier one, taking off what both take together. +/// (as in the app). The upright's tangent chain (the Fillet default, since 84bd2daad) runs on +/// through the first round's end, the quarter circle on the left face, to the top-left edge, so +/// the second fillet rounds the upright and the top-left edge: it takes off what the three edges +/// take together. #[test] fn fillet_the_long_edge_then_the_small_left_edge() { let mut s = knife_edge_part(); @@ -1759,7 +2003,7 @@ fn fillet_the_long_edge_then_the_small_left_edge() { run(&mut s, "solid.fillet", json!({"edges": [[0.0, -21.0, 5.0]], "radius": 2})); let one_by_one = before - planned(&s); let mut s = knife_edge_part(); - run(&mut s, "solid.fillet", json!({"edges": [[20.0, -21.0, 10.0], [0.0, -21.0, 5.0]], "radius": 2})); + run(&mut s, "solid.fillet", json!({"edges": [[20.0, -21.0, 10.0], [0.0, -21.0, 5.0], [0.0, -10.0, 10.0]], "radius": 2})); let together = before - planned(&s); // Within the display meshes' accuracy (the two are built of different faces). assert!(rel(one_by_one, together) < 2e-4, "one by one {one_by_one} vs together {together}"); @@ -1799,7 +2043,7 @@ fn a_line_of_text_cuts_into_a_block_at_any_depth() { run(&mut s, "solid.extrude", json!({"distance":-40})); run(&mut s, "sketch.create", json!({"plane":"XY"})); run(&mut s, "sketch.text", json!({"text":"textvraiment tres long","at":[3,9],"height":7.81})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); // The letters' area, counters left out (a letter's hole is its own profile too). let sorted = |ids: &[String]| { @@ -1813,7 +2057,7 @@ fn a_line_of_text_cuts_into_a_block_at_any_depth() { run(&mut s, "solid.extrude", json!({"distance":-depth,"operation":"cut"})); let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); removed.push((105.0 * 26.0 * 40.0 - volume) / depth); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } let (shallow, deep) = (removed[0], removed[1]); assert!((deep - shallow).abs() < 1e-3 * shallow, "{shallow} mm² taken out at 1 mm, {deep} mm² at 3.5 mm"); @@ -1822,21 +2066,32 @@ fn a_line_of_text_cuts_into_a_block_at_any_depth() { /// A design saved before tapered sides were built through `taper_loop` (#1014), by the build /// before it: two tapered bosses apart from each other (now joined in one boolean), a fillet on -/// a sloping side edge of one and on the top edge of the other, both saved by edge name. They -/// still find their edges, and the part comes out the same. +/// a sloping side edge of one and on the top edge of the other, both saved by edge name. The +/// sloping edge is still the edge its name names. The top edge was saved as an edge of piece `#1` +/// of the cone's side, which is one face now: no edge is that edge any more, so that fillet fails +/// and asks for its edge to be picked again (never the nearest edge of the whole face), and the +/// rest of the part comes out as before. #[test] -fn fillets_on_tapered_bosses_saved_before_still_find_their_edges() { +fn a_fillet_saved_on_a_piece_of_a_tapered_side_that_is_whole_now_asks_for_its_edge_again() { let text = include_str!("../../../../tests/taper/before-1014/two_tapered_bosses_filleted.json"); let mut s = Session::new(solidcraft_doc::Document::from_json(text).unwrap()); let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); - for name in ["Extrude2", "Fillet1", "Fillet2"] { + for name in ["Extrude2", "Fillet1"] { let id = s.doc.find_feature(name).unwrap().id; let r = s.model.result(id).unwrap(); assert!(r.error.is_none() && r.warning.is_none(), "{name}: {:?} {:?}", r.error, r.warning); } - // The build that saved it measured 69454.885209 mm³. - assert!((volume - 69454.8852092132).abs() < 1e-3, "{volume}"); - assert_eq!(s.world_state().bodies.len(), 1); + let fillet = s.doc.find_feature("Fillet2").unwrap().id; + let error = s.model.result(fillet).unwrap().error.clone().unwrap(); + assert_eq!(solidcraft_doc::reselect_parts(&error), Some(("Fillet2", "F4:side:c1#1|F4:top#[F4:side:c1]")), "{error}"); + // In closed form: the 80 × 40 × 20 block, the 20 × 20 boss 10 high tapered 5° in (a frustum, + // top 20 − 20 tan 5° square: 3660.251034), the Ø16 boss tapered alike (a cone frustum, top + // radius 8 − 10 tan 5°: 1798.751833); less the R1 round along a sloping corner (the corner's + // section, r²(cot φ/2 − (π − φ)/2) at its dihedral angle φ = 90.435°, times its length + // between z = 20 and 30: 2.124401). The R0.5 round all round the cone's top (1.928463) is + // the failed fillet's. + assert!((volume - 69456.878467).abs() < 1e-3, "{volume}"); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } /// #1360: a ring drawn round a hole, its inner circle on the hole's wall, cut into a chamfered @@ -1865,12 +2120,7 @@ fn a_ring_cut_round_a_hole_takes_in_the_hole_it_is_drawn_round() { let before = volume(&mut s); // Profile 2: the ring between the hole's wall and the larger circle. let r = s.execute("solid.extrude", &json!({"direction":"negative","distance":"3","operation":"cut","profiles":[2]})); - let clean = r - .as_ref() - .ok() - .and_then(|v| v["feature"].as_u64()) - .and_then(|id| s.model.result(id)) - .is_some_and(|f| f.boolean_diagnostics.events.is_empty()); + let clean = r.as_ref().ok().and_then(|v| v["feature"].as_u64()).and_then(|id| s.model.result(id)).is_some_and(|f| f.error.is_none()); (r.is_ok(), before - volume(&mut s), clean) }; let taken = std::f64::consts::PI * (36.0 - 9.0) * 3.0; @@ -1932,7 +2182,7 @@ fn a_line_of_text_is_cut_in_one_exact_boolean() { run(&mut s, "sketch.finish", json!({})); let id = run(&mut s, "solid.extrude", json!({"distance":-depth,"operation":"cut"}))["feature"].as_u64().unwrap(); let r = s.model.result(id).unwrap(); - assert!(r.error.is_none() && r.boolean_diagnostics.events.is_empty(), "{at:?} {depth}: {r:?}"); + assert!(r.error.is_none(), "{at:?} {depth}: {r:?}"); before - volume(&mut s) }; // Straight walls: the material taken grows with the depth, the letters' area each mm. @@ -1961,7 +2211,7 @@ fn a_line_of_text_cut_through_or_joined_in_relief_is_one_boolean() { run(&mut s, "sketch.finish", json!({})); let id = run(&mut s, "solid.extrude", json!({"distance":distance,"operation":op}))["feature"].as_u64().unwrap(); let r = s.model.result(id).unwrap(); - assert!(r.error.is_none() && r.boolean_diagnostics.events.is_empty(), "{op}: {r:?}"); + assert!(r.error.is_none(), "{op}: {r:?}"); (before, volume(&mut s), s.model.state().bodies.len()) }; let (before, through, pieces) = text("cut", -40.0); @@ -1995,7 +2245,7 @@ fn a_line_of_text_cut_again_deeper_is_one_exact_boolean() { run(s, "sketch.finish", json!({})); let id = run(s, "solid.extrude", json!({"distance":-depth,"operation":"cut"}))["feature"].as_u64().unwrap(); let r = s.model.result(id).unwrap(); - assert!(r.error.is_none() && r.boolean_diagnostics.events.is_empty(), "{depth}: {r:?}"); + assert!(r.error.is_none(), "{depth}: {r:?}"); before - volume(s) }; let first = cut(&mut s, 1.0); @@ -2021,7 +2271,7 @@ fn text_cut_through_a_large_plate_is_one_exact_boolean() { run(&mut s, "sketch.finish", json!({})); let id = run(&mut s, "solid.extrude", json!({"distance":-2,"operation":"cut"}))["feature"].as_u64().unwrap(); let r = s.model.result(id).unwrap(); - assert!(r.error.is_none() && r.boolean_diagnostics.events.is_empty(), "{w} x {h}: {r:?}"); + assert!(r.error.is_none(), "{w} x {h}: {r:?}"); before - volume(&mut s) }; let (small, large) = (taken(200.0, 120.0, [60.0, 40.0]), taken(2000.0, 1200.0, [860.0, 125.0])); @@ -2070,7 +2320,7 @@ fn duplicate_and_excess_profile_picks_are_refused_quickly() { let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": points})).unwrap_err().to_string(); assert!(e.contains("2 profile points are given, but Bottom has 1"), "{e}"); assert!(started.elapsed().as_secs_f64() < 5.0, "refusing took {:?}", started.elapsed()); - assert!(s.world_state().bodies.is_empty(), "nothing was built"); + assert!(s.world_state().unwrap().bodies.is_empty(), "nothing was built"); // One pick of the profile still builds. run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom", "profiles": [0]}, {"sketch": "Top"}]})); } @@ -2252,7 +2502,7 @@ fn a_sketch_coil_never_panics_on_hostile_parameters() { } fn placed_bounds(s: &Session, name: &str) -> solidcraft_geom::Aabb3 { - s.world_state().body(name).unwrap_or_else(|| panic!("no {name}")).mesh().bounds() + s.world_state().unwrap().body(name).unwrap_or_else(|| panic!("no {name}")).mesh().bounds() } fn about(a: f64, b: f64) -> bool { @@ -2276,7 +2526,7 @@ fn twice_placed_blade(s: &mut Session) -> (String, String) { let copy = run(s, "occurrence.copy", json!({"occurrence": made["occurrence"]})); run(s, "occurrence.move", json!({"occurrence": copy["occurrence"], "axis": [1, 0, 0], "angle": "90 deg"})); run(s, "occurrence.move", json!({"occurrence": copy["occurrence"], "translate": [100, 0, 0], "space": "world"})); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); assert_eq!(names.len(), 2, "{names:?}"); unground_all(s); (names[0].clone(), names[1].clone()) @@ -2333,7 +2583,7 @@ fn an_imported_assembly_with_a_repeated_part_moves_as_one() { let mut s = Session::default(); run(&mut s, "file.insert_step", json!({"path": path})); unground_all(&mut s); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); assert_eq!(names.len(), 2, "{names:?}"); let before: Vec<_> = names.iter().map(|n| placed_bounds(&s, n)).collect(); let r = run(&mut s, "solid.move", json!({"bodies": names, "translate": [240, -100, 0]})); @@ -2362,7 +2612,7 @@ fn placed_plate(s: &mut Session, name: &str, x0: f64, angle: f64) { } fn world_bounds(s: &Session, name: &str) -> solidcraft_geom::Aabb3 { - s.world_state().body(name).unwrap_or_else(|| panic!("no {name}")).mesh().bounds() + s.world_state().unwrap().body(name).unwrap_or_else(|| panic!("no {name}")).mesh().bounds() } fn near(a: f64, b: f64) -> bool { @@ -2404,3 +2654,17 @@ fn align_takes_both_ends_where_they_are_shown_across_placed_components() { assert!(near(a.min.z, 8.0) && near(a.max.z, 16.0), "on B's top, not across it: {a:?}"); assert!(near(0.5 * (a.min.x + a.max.x), 60.0) && near(0.5 * (a.min.y + a.max.y), 15.0), "centred on the picked point: {a:?}"); } + +#[test] +fn align_axes_are_world_axes_on_a_placed_component() { + let mut s = Session::default(); + placed_plate(&mut s, "Plate", 0.0, 90.0); + let before = world_bounds(&s, "Plate"); + run(&mut s, "solid.align", json!({"bodies": ["Plate"], "from": [0, 0, 0], "to": [50, 20, 30], "axes": [false, true, false]})); + let after = world_bounds(&s, "Plate"); + // World Y is masked in; X and Z stay where they were. A local-boolean mask would move + // along the component's local Y (world Z) instead. + assert!(near(after.min.x, before.min.x) && near(after.max.x, before.max.x), "x: {after:?}"); + assert!(near(after.min.y, before.min.y + 20.0) && near(after.max.y, before.max.y + 20.0), "y: {after:?}"); + assert!(near(after.min.z, before.min.z) && near(after.max.z, before.max.z), "z: {after:?}"); +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c062624bb..79bcb7cac 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -9,6 +9,9 @@ mod easyprint; #[path = "file_import.rs"] pub(crate) mod import; +#[path = "file_open_steps.rs"] +pub(crate) mod open_steps; + #[cfg(not(target_arch = "wasm32"))] #[path = "file_send.rs"] mod send; @@ -18,6 +21,7 @@ use solidcraft_doc::Document; use solidcraft_io::Format; use super::CommandSpec; +use super::print_face; use crate::params::{bad, bool_, num, str_, string_list}; use crate::{EngineError, Result, Session}; @@ -40,12 +44,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("save") .key("Ctrl+S") .noundo() - .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (replace the design's file even though another program or computer changed it since it was opened or saved; without it that save is refused)"), + .params("path? (default: current file; a name that opens as another kind of file, such as .step, .stl or .dxf, is refused: file.export writes those); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (replace the design's file even though another program or computer changed it since it was opened or saved; without it that save is refused)"), CommandSpec::new("file.save_as", "Save As", save_as).any_part() .icon("save") .key("Ctrl+Shift+S") .noundo() - .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (as file.save, when `path` is the design's own file)"), + .params("path (a design file name, .sc as a rule; one that opens as another kind of file, such as .step, .stl or .dxf, is refused: file.export writes those); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (as file.save, when `path` is the design's own file)"), CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).any_part().icon("restore") .noundo() .params("dir? (default: the recovery folder) → designs autosaved by apps that crashed or closed with unsaved changes"), @@ -57,6 +61,39 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("export") .noundo() .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"), + // One command per format, so each File › Export item can have a key of its own; started + // from a key or command search, the app opens the save picker (the mesh dialog for STL and + // 3MF). Each takes `file.export`'s parameters for its format, without `format`. + CommandSpec::new("file.export_step", "Export STEP", crate::checked!("file.export_step", export_step)) + .icon("export") + .noundo() + .contract(&EXPORT_STEP_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body; a design with components then exports as a STEP assembly) → {path, bytes, format}: STEP, whatever the path's extension"), + CommandSpec::new("file.export_stl", "Export STL", crate::checked!("file.export_stl", export_stl)) + .icon("mesh_export") + .noundo() + .contract(&EXPORT_STL_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format}: binary STL, whatever the path's extension"), + CommandSpec::new("file.export_3mf", "Export 3MF", crate::checked!("file.export_3mf", export_3mf)) + .icon("mesh_export") + .noundo() + .contract(&EXPORT_3MF_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard); objects?: body|component (as file.export) → {path, bytes, format}: 3MF, whatever the path's extension"), + CommandSpec::new("file.export_obj", "Export OBJ", crate::checked!("file.export_obj", export_obj_cmd)) + .icon("export") + .noundo() + .contract(&EXPORT_OBJ_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format, files}: OBJ, with the colours of the bodies in a material library (`.mtl`) next to it"), + CommandSpec::new("file.export_urdf", "Export URDF", crate::checked!("file.export_urdf", export_urdf_cmd)) + .icon("export") + .noundo() + .contract(&EXPORT_URDF_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; mesh_prefix?; effort? (default 1000); velocity? (default 10) → {path, format, files, links, joints, warnings}: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md"), CommandSpec::new("file.save_mesh", "Save As Mesh", save_mesh) .at("INSERT", "FILES") .icon("mesh_export") @@ -80,9 +117,17 @@ pub static COMMANDS: &[CommandSpec] = &[ fn new_doc(s: &mut Session, p: &Value) -> Result { let name = str_(p, "name").unwrap_or("Untitled"); s.replace_design(Session::new(Document::new(name))); + // A name given here is the user's own, so Save As keeps it (#4907); "Untitled" is none. + s.user_named = !name.trim().is_empty() && name.trim() != DEFAULT_NAME; Ok(json!({"name": name})) } +const EXPORT_STEP_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_STL_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_3MF_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_OBJ_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_URDF_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + fn path_arg<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> { str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required")) } @@ -136,12 +181,17 @@ fn exporter_up(import: &solidcraft_kernel::StepImport) -> Option<(&'static str, /// A quarter turn about X through the origin: a file's Y up becomes Z up. fn quarter_turn_x() -> solidcraft_doc::Mat { - solidcraft_doc::rigid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::X, std::f64::consts::FRAC_PI_2) + solidcraft_doc::rigid(solidcore_record::Vec3::ZERO, solidcore_record::Vec3::ZERO, solidcore_record::Vec3::X, std::f64::consts::FRAC_PI_2) } /// Add an Import feature for a STEP file to the session's design, in a new component named /// after the file (#1386). +/// +/// While the profiler records, the reply's `profile` is the import's share of it (reading, +/// building the solids in SMLib, placing, meshing and evaluating them), as +/// `diagnostics.profile` reports it. fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptions) -> Result { + let profiled = solidcraft_profile::enabled().then(solidcraft_profile::mark); let sf = read_step(path, options.names)?; let fname = name.filter(|n| !n.trim().is_empty()).unwrap_or(&sf.name).to_string(); let cname = import::component_name(path, name); @@ -160,6 +210,10 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio if let Some(turned) = turned { out["stand_up"] = json!(turned); } + if let Some(mark) = profiled { + let report = crate::schema::diagnostics::ProfileReport::new(&mark.report(), 20); + out["profile"] = serde_json::to_value(report).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + } Ok(out) } @@ -262,7 +316,11 @@ fn insert_step(s: &mut Session, p: &Value) -> Result { if let Some(m) = placement { let occ = out["occurrence"].as_u64().ok_or_else(|| EngineError::Other("the import has no placement to move".into()))?; if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) { - o.transform = solidcraft_doc::mat_mul(&m, &o.transform); + let placed = solidcraft_doc::mat_mul(&m, &o.transform); + if !solidcraft_doc::is_placement(&placed) { + return Err(bad(cmd, "`matrix` moves the import out of a rigid placement within 1e9 mm")); + } + o.transform = placed; out["transform"] = json!(o.transform); } s.refresh(); @@ -281,6 +339,7 @@ fn open(s: &mut Session, p: &Value) -> Result { if let Some(command) = super::drawing_import_command(path) { let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into()); let mut fresh = Session::new(Document::new(&stem)); + fresh.set_validation(s.validation()); let mut out = fresh.execute(command, &json!({"path": path}))?; fresh.undo.clear(); s.replace_design(fresh); @@ -312,6 +371,7 @@ fn open(s: &mut Session, p: &Value) -> Result { // A new, unsaved design holding the file's bodies. let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into()); let mut fresh = Session::new(Document::new(&stem)); + fresh.set_validation(s.validation()); let r = if solidcraft_io::is_step_path(path) { add_step(&mut fresh, path, None, &step_options(p, "doc.open")?)? } else { @@ -336,11 +396,30 @@ fn open(s: &mut Session, p: &Value) -> Result { let read_only = bool_(p, "read_only").unwrap_or(false); // Stamped before it is read: a write while it is being read is a change too. let disk = solidcraft_io::design_lock::stamp(path); + let (doc, saved) = read_design(s, path)?; + let opened = Session::opened_at_validating(doc, saved.as_ref(), Some(path), s.validation()); + opened_design(s, opened, path, read_only, disk) +} + +/// Read the design file at `path` for `doc.open`, under its file's name if it has none of its own. +fn read_design(s: &mut Session, path: &str) -> Result<(Document, Option)> { let (mut doc, saved) = solidcraft_io::read_design_file(path, s.open_preview.take()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; if let Some(stem) = default_name_for(&doc.name, path) { doc.name = stem; } - s.replace_design(Session::opened_at(doc, saved.as_ref(), Some(path))); + Ok((doc, saved)) +} + +/// `doc.open` of a design: `opened`, the design read from `path` and evaluated, takes `s`'s +/// place, and the reply says what it is. +fn opened_design( + s: &mut Session, + opened: Session, + path: &str, + read_only: bool, + disk: Option, +) -> Result { + s.replace_design(opened); s.disk = disk; s.read_only = read_only; let errors = s.model.results.iter().filter(|r| r.error.is_some()).count(); @@ -369,17 +448,22 @@ fn default_name_for(name: &str, path: &str) -> Option { (!stem.is_empty()).then_some(stem) } -/// The name a design takes when saved to `path`, if it changes: its file's name while it has -/// none of its own ([`default_name_for`]), or while it still has the name it took from the file -/// it was saved as before, so Save As under another name renames it too (#1710). A name the -/// user chose is kept. -fn saved_name(name: &str, old_path: Option<&str>, path: &str) -> Option { +/// The name a design takes when saved to `path`, if it changes. A design with no name of its +/// own takes the file's ([`default_name_for`]). Otherwise a name the user chose is kept, while +/// a borrowed one — taken from the file it was saved as before (#1710), from a sample, or from +/// a file that stored another design's name — follows a Save As to the new file's name, so +/// after Save As the open design *is* the new file (#4907). A plain Save to the same file +/// never renames. +fn saved_name(name: &str, old_path: Option<&str>, path: &str, user_named: bool) -> Option { if let Some(stem) = default_name_for(name, path) { return Some(stem); } + if user_named { + return None; + } let stem = |p: &str| std::path::Path::new(p).file_stem().map(|x| x.to_string_lossy().trim().to_string()).filter(|x| !x.is_empty()); - let (old, new) = (stem(old_path?)?, stem(path)?); - (name.trim() == old && new != old).then_some(new) + let new = stem(path)?; + (old_path != Some(path) && name.trim() != new).then_some(new) } /// Rename the design, and the undo and redo states that still carry the old name, so undo @@ -404,8 +488,36 @@ fn rename_design(s: &mut Session, from: &str, to: &str) { } } -fn write(s: &mut Session, path: &str, format: &str, compression: &str, preview: bool, cache: bool, overwrite: bool) -> Result { +/// The kind of file `doc.open` reads `path` as when that is not a design, by its extension. A +/// design saved under such a name would not open again as the design (#9745). +fn other_file_kind(path: &str) -> Option<&'static str> { + if solidcraft_io::is_step_path(path) { + Some("a STEP or other CAD exchange file") + } else if solidcraft_io::is_mesh_path(path) { + Some("a mesh") + } else if super::drawing_import_command(path).is_some() { + Some("a 2D drawing") + } else if solidcraft_io::is_point_cloud_path(path) { + Some("a point cloud") + } else { + None + } +} + +/// Refuse to save a design under a name [`other_file_kind`] opens as another kind of file, +/// pointing to `file.export` when that writes the format. +fn check_design_name(cmd: &str, path: &str) -> Result<()> { + let Some(kind) = other_file_kind(path) else { return Ok(()) }; + let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default(); + let export = if solidcraft_io::Format::from_name(&ext).is_ok() { format!(", or write a .{ext} file with file.export") } else { String::new() }; + Err(bad(cmd, format!("{path}: a .{ext} file opens as {kind}, not as a design; save the design as .{}{export}", solidcraft_io::DESIGN_EXT))) +} + +#[allow(clippy::too_many_arguments)] +fn write(s: &mut Session, cmd: &str, path: &str, format: &str, compression: &str, preview: bool, cache: bool, overwrite: bool) -> Result { + // A path outside the agent's folders says so first, whatever its name. solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?; + check_design_name(cmd, path)?; if s.path.as_deref() == Some(path) { if s.read_only { return Err(EngineError::Other(format!("{path}: the design was opened read-only; save it to another file with file.save_as"))); @@ -416,9 +528,9 @@ fn write(s: &mut Session, path: &str, format: &str, compression: &str, preview: ))); } } - // Saving an unnamed design, or one named after the file it was saved as, names it after its - // file (not an undoable edit). - let renamed = saved_name(&s.doc.name, s.path.as_deref(), path).map(|stem| (s.doc.name.clone(), stem)); + // Saving an unnamed or borrowed-named design to a new file names it after that file + // (not an undoable edit); a name the user chose is kept (#4907). + let renamed = saved_name(&s.doc.name, s.path.as_deref(), path, s.user_named).map(|stem| (s.doc.name.clone(), stem)); if let Some((from, to)) = &renamed { rename_design(s, from, to); } @@ -465,9 +577,24 @@ fn write_bytes( impl Session { /// Open a design with its file location, resolving component links before history keeps /// them. Absolute in-memory targets survive Save As, undo, redo and recovery unchanged. - pub fn opened_at(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>, path: Option<&str>) -> Self { + pub fn opened_at(doc: Document, saved: Option<&solidcraft_doc::SavedModel>, path: Option<&str>) -> Self { + Self::opened_at_validating(doc, saved, path, solidcraft_kernel::Validation::default()) + } + + /// [`Self::opened_at`], its features evaluated under `validation` ([`Session::set_validation`]). + pub fn opened_at_validating( + mut doc: Document, + saved: Option<&solidcraft_doc::SavedModel>, + path: Option<&str>, + validation: solidcraft_kernel::Validation, + ) -> Self { super::component_link::resolve_design_links(&mut doc, path); - let mut session = Self::opened(doc, saved); + Self::opened_validating(doc, saved, validation).located(path) + } + + /// This session, just opened, as the design in the file at `path`. + pub(crate) fn located(self, path: Option<&str>) -> Self { + let mut session = self; session.path = path.map(str::to_owned); // A design saved before body names were pinned (#6403) is pinned now, as its first // command would pin it: that command pinned them as part of itself, so undoing it went @@ -586,6 +713,7 @@ fn save(s: &mut Session, p: &Value) -> Result { }; write( s, + "file.save", &path, str_(p, "format").unwrap_or(default_design_format(&path)), str_(p, "compression").unwrap_or("fast"), @@ -603,6 +731,7 @@ fn save_as(s: &mut Session, p: &Value) -> Result { let path = path_arg(p, "file.save_as")?.to_string(); write( s, + "file.save_as", &path, str_(p, "format").unwrap_or(default_design_format(&path)), str_(p, "compression").unwrap_or("fast"), @@ -663,6 +792,7 @@ fn component_parts(s: &Session) -> Vec<(String, Vec)> { fn export_to( s: &Session, + cmd: &str, path: &str, format: Format, bodies: &[String], @@ -677,7 +807,7 @@ fn export_to( // A design with components exports as a STEP assembly; otherwise bodies as placed. let bytes = if format == Format::Design { if !bodies.is_empty() { - return Err(bad("file.export", "design JSON exports the complete document; omit bodies")); + return Err(bad(cmd, "design JSON exports the complete document; omit bodies")); } solidcraft_io::write_design(&s.design()) } else if format == Format::Step && bodies.is_empty() && !s.doc.occurrences.is_empty() { @@ -685,22 +815,75 @@ fn export_to( } else { // Bodies carry the colour they are shown in (appearance, material or imported), and the // file the design's properties where the format has a place for them. - solidcraft_io::export_with_parts(&s.doc.painted(&s.world_state()), bodies, parts, format, &name, &s.doc.metadata, quality)? + solidcraft_io::export_with_parts(&s.doc.painted(&*s.world_state()?), bodies, parts, format, &name, &s.doc.metadata, quality)? }; solidcraft_io::vfs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; Ok(json!({"path": path, "bytes": bytes.len(), "format": format!("{format:?}")})) } +/// [`export_to`] for a mesh file a slicer is sent (STL or 3MF): each body laid on its print face. +#[cfg(not(target_arch = "wasm32"))] +fn export_laid_to( + s: &Session, + path: &str, + format: Format, + bodies: &[String], + parts: &[(String, Vec)], + quality: solidcraft_io::MeshQuality, +) -> Result { + let name = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| s.doc.name.clone()); + let mut state = s.doc.painted(&*s.world_state()?); + let laid = print_face::lay_on_print_faces(s, &mut state, bodies, parts); + let bytes = solidcraft_io::export_with_parts(&state, bodies, parts, format, &name, &s.doc.metadata, quality)?; + solidcraft_io::vfs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let mut out = json!({"path": path, "bytes": bytes.len(), "format": format!("{format:?}")}); + laid.report(&mut out); + Ok(out) +} + fn export(s: &mut Session, p: &Value) -> Result { let cmd = "file.export"; let path = path_arg(p, cmd)?; let format = Format::from_name(str_(p, "format").unwrap_or(path))?; if format == Format::Urdf { - return export_urdf(s, path, p); + if !string_list(cmd, p, "bodies")?.is_empty() { + return Err(bad(cmd, "urdf exports the whole assembly; omit bodies")); + } + return export_urdf(s, cmd, path, p); } let quality = mesh_quality(p, cmd)?; let parts = mesh_parts(s, p, cmd, format)?; - export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) + export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) +} + +fn export_step(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_step"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::Step, &string_list(cmd, p, "bodies")?, &[], solidcraft_io::MeshQuality::default()) +} + +fn export_stl(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_stl"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::StlBinary, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?) +} + +fn export_3mf(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_3mf"; + let path = path_arg(p, cmd)?; + let parts = mesh_parts(s, p, cmd, Format::ThreeMf)?; + export_to(s, cmd, path, Format::ThreeMf, &string_list(cmd, p, "bodies")?, &parts, mesh_quality(p, cmd)?) +} + +fn export_obj_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_obj"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::Obj, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?) +} + +fn export_urdf_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_urdf"; + export_urdf(s, cmd, path_arg(p, cmd)?, p) } /// The OBJ export: the mesh file and the material library beside it, with the colours of the @@ -709,7 +892,7 @@ fn export(s: &mut Session, p: &Value) -> Result { fn export_obj(s: &Session, path: &str, bodies: &[String], quality: solidcraft_io::MeshQuality) -> Result { let mtl_path = std::path::Path::new(path).with_extension("mtl"); let mtl_name = mtl_path.file_name().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| String::from("model.mtl")); - let files = solidcraft_io::export_obj(&s.doc.painted(&s.world_state()), bodies, &mtl_name, quality)?; + let files = solidcraft_io::export_obj(&s.doc.painted(&*s.world_state()?), bodies, &mtl_name, quality)?; let mut targets: Vec<(String, &[u8])> = Vec::new(); if !files.mtl.is_empty() { targets.push((mtl_path.to_string_lossy().to_string(), files.mtl.as_bytes())); @@ -731,11 +914,7 @@ fn export_obj(s: &Session, path: &str, bodies: &[String], quality: solidcraft_io /// The assembly as a URDF and its meshes next to it (docs/urdf.md). Every path is checked before /// anything is written; the meshes go first and the `.urdf` last. -fn export_urdf(s: &Session, path: &str, p: &Value) -> Result { - let cmd = "file.export"; - if !string_list(cmd, p, "bodies")?.is_empty() { - return Err(bad(cmd, "urdf exports the whole assembly; omit bodies")); - } +fn export_urdf(s: &Session, cmd: &str, path: &str, p: &Value) -> Result { let positive = |k: &str| match p.get(k) { None | Some(Value::Null) => Ok(None), Some(_) => num(p, k).filter(|x| *x > 0.0).map(Some).ok_or_else(|| bad(cmd, format!("`{k}` must be a positive number"))), @@ -750,13 +929,15 @@ fn export_urdf(s: &Session, path: &str, p: &Value) -> Result { // their links. let st = s.model.state(); let mut held = Vec::new(); - let doc = if s.pending_moves.is_empty() { + // The exploded view is shown only: the links are where the design places them. + let moves = s.uncaptured_moves(); + let doc = if moves.is_empty() { std::borrow::Cow::Borrowed(&*s.doc) } else { let placed = solidcraft_doc::joints::solve(&s.doc, &st).world; let mut doc = (*s.doc).clone(); for o in &mut doc.occurrences { - match s.pending_moves.get(&o.id) { + match moves.get(&o.id) { Some(_) if placed.contains_key(&o.id) => held.push(o.name.clone()), Some(t) => o.transform = *t, None => {} @@ -830,7 +1011,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result { }, ); } - export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) + export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) } /// The browser build can't start a program. @@ -906,7 +1087,7 @@ fn recover(s: &mut Session, p: &Value) -> Result { if let Some(stem) = entry.path.as_deref().and_then(|path| default_name_for(&doc.name, path)) { doc.name = stem; } - s.replace_design(Session::opened_at(doc, None, entry.path.as_deref())); + s.replace_design(Session::opened_at_validating(doc, None, entry.path.as_deref(), s.validation())); s.mark_unsaved(); if bool_(p, "discard").unwrap_or(false) { crate::recovery::remove(&dir, id)?; @@ -937,6 +1118,30 @@ mod urdf_tests; mod tests { use super::*; + /// While the profiler records, a STEP import's reply carries its own profile: the import's + /// stages and the kernel's calls, as diagnostics.profile reports them. + #[test] + fn a_step_import_reports_its_profile_while_the_profiler_records() { + let _serial = crate::schema::diagnostics::PROFILE_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let dir = std::env::temp_dir().join(format!("solidcraft-import-profile-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("block.step").to_string_lossy().to_string(); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5})).unwrap(); + s.execute("file.export", &json!({"path": path})).unwrap(); + // The first read of the file (a second one finds it in the import cache). + solidcraft_profile::set_enabled(true); + let out = Session::default().execute("file.insert_step", &json!({"path": path})).unwrap(); + solidcraft_profile::set_enabled(false); + let plain = Session::default().execute("file.insert_step", &json!({"path": path})).unwrap(); + assert!(plain.get("profile").is_none(), "nothing recorded, nothing reported: {plain}"); + let p = &out["profile"]; + let rows = p["rows"].as_array().unwrap(); + let has = |cat: &str| rows.iter().any(|r| r["category"] == cat); + assert!(has("import") && has("solidcore"), "{p}"); + assert!(p["by_category"].as_array().is_some_and(|c| !c.is_empty()) && p["wall_ms"].as_f64().is_some_and(|w| w > 0.0), "{p}"); + } + /// #8139: with `objects: "component"` a 3MF has one object for each placement of a component /// with two or more bodies, its bodies the object's parts; the design's own bodies stay objects /// of their own. The default (and `objects: "body"`) is one object per body, as before. Read @@ -993,6 +1198,43 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Each format's own export command (one key each in Keyboard Shortcuts) writes that format + /// whatever the path's extension, as `file.export` does with `format`, and says so. + #[test] + fn each_format_has_an_export_command_of_its_own() { + let dir = std::env::temp_dir().join(format!("solidcraft-export-per-format-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let at = |n: &str| dir.join(n).to_string_lossy().to_string(); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap(); + for (cmd, format, signature) in [ + ("file.export_step", "Step", &b"ISO-10303-21;"[..]), + ("file.export_3mf", "ThreeMf", &b"PK"[..]), + ("file.export_obj", "Obj", &b""[..]), + ("file.export_stl", "StlBinary", &b""[..]), + ] { + // A name with another format's extension: the command, not the name, picks the format. + let path = at(&format!("{format}.txt")); + let r = s.execute(cmd, &json!({"path": path})).unwrap(); + assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(path.as_str()), Some(format)), "{cmd}: {r}"); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64), "{cmd}"); + assert!(bytes.starts_with(signature), "{cmd}"); + } + // The triangles `file.export` writes (the 80-byte header holds the file's name): a box is + // 12 triangles, 84 + 50 bytes each. + s.execute("file.export", &json!({"path": at("box.stl")})).unwrap(); + assert_eq!(std::fs::read(at("StlBinary.txt")).unwrap()[80..], std::fs::read(at("box.stl")).unwrap()[80..]); + assert_eq!(std::fs::metadata(at("box.stl")).unwrap().len(), 84 + 50 * 12); + let obj = std::fs::read_to_string(at("Obj.txt")).unwrap(); + assert_eq!(obj.lines().filter(|l| l.starts_with("f ")).count(), 12, "{obj}"); + let r = s.execute("file.export_urdf", &json!({"path": at("robot.urdf")})).unwrap(); + assert_eq!(r["format"], "Urdf"); + assert!(std::fs::read_to_string(at("robot.urdf")).unwrap().contains(" = sheets.iter().map(Value::to_string).collect(); + assert_eq!(texts.len(), sheets.len(), "each sheet once"); + let mut held = std::collections::HashSet::new(); + for (r, feature) in s.model.results.iter().zip(records["features"].as_array().unwrap()) { + let state = &records["states"][feature["state"].as_u64().unwrap() as usize]; + let named = state["sheets"].as_array().unwrap(); + assert_eq!(named.len(), r.state.sheets.len()); + for (i, sheet) in named.iter().zip(&r.state.sheets) { + let written = &sheets[i.as_u64().unwrap() as usize]; + assert_eq!(*written, serde_json::to_value(sheet).unwrap(), "{}: the record of its own sheet", r.name); + held.insert(written.to_string()); + } + } + assert_eq!(held, texts, "every record written is one a state holds"); + assert!(sheets.len() >= 6, "each part's base, then with its flange: {}", sheets.len()); } /// A design whose saved model would give a body back with other topology opens with the @@ -1422,7 +1675,7 @@ mod tests { fn saved_model_needs_no_meshes_and_is_adopted_only_for_its_document() { let mut session = Session::new(Document::new("Saved model")); session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving the model must not triangulate"); @@ -1453,6 +1706,51 @@ mod tests { std::fs::remove_file(path).unwrap(); } + /// #9170: a design holding a mesh body (an inserted STL) keeps its saved model and opens from + /// it. One mesh body left the cache out for the whole model, so every feature, the boxes + /// too, was evaluated again on opening. + #[test] + fn a_design_with_a_mesh_body_keeps_its_saved_model() { + let dir = std::env::temp_dir().join(format!("solidcraft-mesh-cache-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let stl = dir.join("tetra.stl"); + let facets = [ + [[0, 0, 0], [0, 10, 0], [10, 0, 0]], + [[0, 0, 0], [10, 0, 0], [0, 0, 10]], + [[0, 0, 0], [0, 0, 10], [0, 10, 0]], + [[10, 0, 0], [0, 10, 0], [0, 0, 10]], + ]; + let mut text = String::from("solid tetra\n"); + for f in facets { + text += "facet normal 0 0 0\nouter loop\n"; + for [x, y, z] in f { + text += &format!("vertex {x} {y} {z}\n"); + } + text += "endloop\nendfacet\n"; + } + std::fs::write(&stl, text + "endsolid tetra\n").unwrap(); + let mut session = Session::new(Document::new("Boxes and a mesh")); + for x in [0, 40, 80] { + session.execute("solid.box", &json!({"length": 20, "width": 20, "height": 20, "corner": [x, 0, 0], "operation": "new_body"})).unwrap(); + } + session.execute("file.insert_mesh", &json!({"path": stl})).unwrap(); + let triangles = |s: &Session| s.model.state().bodies.iter().filter_map(|b| b.body.triangle_mesh().map(|(_, t)| t.len())).collect::>(); + assert_eq!(triangles(&session), [4], "one mesh body"); + let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap(); + assert!(solidcraft_io::read_design_geometry(&bytes).is_some(), "the model is saved with the mesh body"); + let path = dir.join("boxes-mesh.solidcraft"); + std::fs::write(&path, &bytes).unwrap(); + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path": path})).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(reopened.model.results.len(), session.model.results.len()); + assert!(reopened.model.results.iter().zip(&session.model.results).all(|(a, b)| a.ms == b.ms), "taken from the file, not evaluated"); + assert_eq!(triangles(&reopened), [4]); + let volume = |s: &mut Session| s.execute("inspect.measure", &json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap(); + let (saved, opened) = (volume(&mut session), volume(&mut reopened)); + assert!((opened - saved).abs() < 1e-9 && (saved - (3. * 8000. + 1000. / 6.)).abs() < 1e-6, "{opened} vs {saved}"); + } + /// A sheet-metal design keeps each sheet body once in its saved model, not again with every /// later feature's state: a design of many features after its sheet metal wrote the sheets /// over and over, and past the cache's size limit kept only some of its states. @@ -1496,13 +1794,61 @@ mod tests { std::fs::remove_file(path).unwrap(); } + /// A design's saved model keeps each set of sketch keys once, not again with every state: + /// every state wrote the key of each sketch before it, so a design of many sketches and many + /// features after them (5,484 features) passed the cache's size limit and kept only some of + /// its states. A set is written as the changes from the one before it; the model opens from + /// the file with every state (the keys read back: `eval_cost_tests`). + #[test] + fn a_saved_model_keeps_each_set_of_sketch_keys_once() { + let mut s = Session::new(Document::new("Sketches")); + let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap(); + for i in 0..6 { + run(&mut s, "sketch.create", json!({"plane":"XY","name":format!("Pad{i}")})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0":[20 * i,0],"p1":[20 * i + 10,10]})); + run(&mut s, "solid.extrude", json!({"distance":5,"operation":"new"})); + } + for i in 0..10 { + run(&mut s, "solid.box", json!({"length":5,"width":5,"height":5,"corner":[20 * i,40,0],"operation":"new"})); + } + let saved = saved_geometry(&s, &s.doc).unwrap(); + let features = saved.records["features"].as_array().unwrap(); + assert_eq!(features.len(), s.doc.features.len()); + assert!(features.iter().all(|f| f.get("state").is_some()), "every state kept"); + let states = saved.records["states"].as_array().unwrap(); + let sets = saved.records["sketch_key_sets"].as_array().unwrap(); + // One set per sketch: each later one adds that sketch's key to the one before it. + assert_eq!(sets.len(), 6, "{sets:?}"); + assert_eq!(sets[0]["set"].as_array().unwrap().len(), 1); + for (i, set) in sets.iter().enumerate().skip(1) { + assert_eq!( + (set["base"].as_u64(), set["set"].as_array().unwrap().len(), set["drop"].as_array().unwrap().len()), + (Some(i as u64 - 1), 1, 0) + ); + } + let last = sets.len() - 1; + assert_eq!( + states.iter().filter(|st| st["sketch_key_set"] == json!(last)).count(), + 2 + 10, + "the last sketch, its extrude and every box share one set" + ); + let path = std::env::temp_dir().join(format!("solidcraft-sketch-key-cache-{}.solidcraft", std::process::id())); + let bytes = solidcraft_io::write_design_container_with_cache(&s.doc, solidcraft_io::DesignCompression::Fast, None, Some(&saved)).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path": path})).unwrap(); + assert_eq!(reopened.model.last_recomputed, 0, "taken from the file, not evaluated"); + assert!(reopened.model.results.iter().zip(&s.model.results).all(|(a, b)| a.ms == b.ms)); + std::fs::remove_file(path).unwrap(); + } + #[test] #[ignore = "manual native cache save benchmark; generate issue303-step.json first"] fn benchmark_native_cache_save() { let target = std::env::var_os("CARGO_TARGET_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| std::path::PathBuf::from("target")); let input = std::env::var_os("SOLIDCRAFT_BENCH_FILE").map(std::path::PathBuf::from).unwrap_or_else(|| target.join("issue303-step.json")); let mut session = Session::new(solidcraft_io::read_design(&std::fs::read(input).unwrap()).unwrap()); - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } let modes = [("json", false, "fast"), ("container", false, "fast"), ("container", true, "fast"), ("container", true, "compact")]; @@ -1544,7 +1890,7 @@ mod tests { assert_eq!(result["errors"], 0); let reconstructed = start.elapsed().as_secs_f64() * 1000.; let mut triangles = 0; - let world = session.world_state(); + let world = session.world_state().unwrap(); for body in &world.bodies { triangles += body.mesh().triangles.len(); } @@ -1598,6 +1944,34 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn a_design_is_not_saved_under_a_name_that_opens_as_another_file() { + // #9745: a design saved as `part.step` or `part.stl` was refused or opened as a broken mesh. + let dir = name_dir("other-kind"); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + for name in ["part.step", "part.STP", "part.igs", "part.stl", "part.obj", "part.3mf", "part.glb", "part.dxf", "part.svg", "part.ply"] { + let path = dir.join(name); + for command in ["file.save_as", "file.save"] { + let e = s.execute(command, &json!({"path":path})).unwrap_err().to_string(); + assert!(e.contains("not as a design") && e.contains(".sc"), "{command} {name}: {e}"); + assert!(!path.exists(), "{command} {name} wrote the file"); + } + } + let e = s.execute("file.save_as", &json!({"path":dir.join("part.stl")})).unwrap_err().to_string(); + assert!(e.contains("file.export"), "STL is an export format: {e}"); + assert!(s.path.is_none() && s.is_dirty(), "a refused save changes nothing"); + // Names that open again as the design still save, and what they write opens as it. + for name in ["part.sc", "part.json", "part.txt", "part"] { + let path = dir.join(name); + s.execute("file.save_as", &json!({"path":path})).unwrap(); + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path":path})).unwrap(); + assert_eq!(reopened.doc.features.len(), 1, "{name} reopens as the design"); + } + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn save_as_keeps_a_name_the_user_chose() { let dir = name_dir("named"); @@ -1611,6 +1985,44 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// #4907: after Save As the open design *is* the new file — tab, browser and the name stored + /// in the file — whenever its name didn't come from its current file: a sample's name, or a + /// file renamed outside SolidCraft or named by someone else. A plain Save never renames. + #[test] + fn save_as_names_a_borrowed_name_after_the_new_file() { + let dir = name_dir("borrowed"); + // The issue's steps: the sample "Sample Plate" saved as "Bracket v2.solidcraft". + let mut s = Session::default(); + s.doc_mut().name = "Sample Plate".into(); + s.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); + let path = dir.join("Bracket v2.solidcraft"); + let r = s.execute("file.save_as", &json!({"path":path})).unwrap(); + assert_eq!(r["name"], "Bracket v2"); + assert_eq!(s.doc.name, "Bracket v2"); + assert!(!s.is_dirty(), "taking the new file's name is part of the save"); + assert_eq!(solidcraft_io::read_design(&std::fs::read(&path).unwrap()).unwrap().name, "Bracket v2"); + // Undoing the box does not bring the sample's name back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc.name, "Bracket v2"); + // Reopening shows the new name too. + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path":path})).unwrap(); + assert_eq!(reopened.doc.name, "Bracket v2"); + // A file whose stored name is not its own (renamed outside SolidCraft, or saved by a + // version before #1710): Save As names the design after the new file, while a plain + // Save to the file it has leaves the name alone. + let odd = dir.join("renamed.solidcraft"); + std::fs::write(&odd, solidcraft_io::write_design(&Document::new("Sample Plate"))).unwrap(); + let mut s = Session::default(); + s.execute("doc.open", &json!({"path":odd})).unwrap(); + assert_eq!(s.doc.name, "Sample Plate"); + s.execute("file.save", &json!({})).unwrap(); + assert_eq!(s.doc.name, "Sample Plate", "a plain Save does not rename behind the user's back"); + s.execute("file.save_as", &json!({"path":dir.join("Bracket v3.solidcraft")})).unwrap(); + assert_eq!(s.doc.name, "Bracket v3"); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn opening_an_untitled_file_shows_its_file_name() { let dir = name_dir("open"); @@ -1682,14 +2094,122 @@ mod tests { let mut opened = Session::default(); watch(progress.clone(), || opened.execute("doc.open", &json!({"path":path}))).unwrap(); assert_eq!(progress.features(), (3, 3)); - assert_eq!(opened.world_state().bodies.len(), 3); + assert_eq!(opened.world_state().unwrap().bodies.len(), 3); let progress = Arc::new(Progress::default()); progress.cancel(); let mut stopped = Session::default(); watch(progress, || stopped.execute("doc.open", &json!({"path":path}))).unwrap(); assert!(stopped.model.results.iter().all(|r| r.skipped), "no feature was rebuilt after Cancel"); - assert!(stopped.world_state().bodies.is_empty()); + assert!(stopped.world_state().unwrap().bodies.is_empty()); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// #10198: a design opened a feature at a time ([`OpenSteps`]) is the design `doc.open` + /// opens: the same features, results, bodies and history marker, with its file and name. Its + /// import is offered before the step that evaluates it, and other files are left to `doc.open`. + #[test] + fn a_design_opened_a_feature_at_a_time_is_the_one_doc_open_opens() { + use super::open_steps::OpenSteps; + let dir = std::env::temp_dir().join(format!("solidcraft-open-steps-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("steps.sc").to_string_lossy().to_string(); + let step = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/step-conformance/cylinder_seam.step"); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + s.execute("file.insert_step", &json!({"path": step})).unwrap(); + s.execute("component.activate", &json!({"component": "root"})).unwrap(); + s.execute("solid.box", &json!({"length":5,"width":5,"height":5,"corner":[40,0,0]})).unwrap(); + s.execute("solid.box", &json!({"length":5,"width":5,"height":5,"corner":[60,0,0]})).unwrap(); + let features = s.doc.features.len(); + s.execute("timeline.rollback", &json!({"position": features - 1})).unwrap(); + s.execute("file.save", &json!({"path": path, "cache": false})).unwrap(); + + let mut whole = Session::default(); + let opened = whole.execute("doc.open", &json!({"path": path, "read_only": true})).unwrap(); + + let mut steps = + OpenSteps::start(&json!({"path": path, "read_only": true}), Default::default()).unwrap().expect("a design is opened in steps"); + assert_eq!(steps.path(), path); + assert_eq!(steps.progress(), (0, features - 1), "the saved marker is where evaluation stops"); + let mut imports = 0; + let mut n = 0; + while !steps.done() { + if let Some(text) = steps.next_import() { + assert!(text.contains("ISO-10303-21")); + imports += 1; + } + steps.step(); + n += 1; + assert_eq!(steps.progress().0, n); + } + assert_eq!((imports, n), (1, features - 1)); + assert!(!steps.step(), "nothing is left to evaluate"); + let mut stepped = Session::default(); + let reply = steps.finish(&mut stepped).unwrap(); + + assert_eq!(reply, opened); + assert_eq!(stepped.doc, whole.doc); + assert_eq!(stepped.doc.marker, Some(features - 1)); + assert_eq!((stepped.path.as_deref(), stepped.read_only), (Some(path.as_str()), true)); + let summary = |s: &Session| -> Vec<(u64, bool, bool)> { s.model.results.iter().map(|r| (r.id, r.skipped, r.error.is_some())).collect() }; + assert_eq!(summary(&stepped), summary(&whole)); + let bodies = |s: &Session| -> Vec<(String, usize)> { + s.world_state().unwrap().bodies.iter().map(|b| (b.name.clone(), b.mesh().triangles.len())).collect() + }; + assert_eq!(bodies(&stepped), bodies(&whole)); + assert_eq!(stepped.world_state().unwrap().bodies.len(), 3, "the box, the cylinder and the box before the marker"); + assert!(stepped.model.is_current(&stepped.doc)); + + // Other files, and STEP-only options, are opened by `doc.open`. + for p in [json!({"path": step}), json!({"path": "part.stl"}), json!({"path": path, "up": "y"}), json!({})] { + assert!(OpenSteps::start(&p, Default::default()).unwrap().is_none(), "{p}"); + } + assert!(OpenSteps::start(&json!({"path": dir.join("missing.sc").to_string_lossy()}), Default::default()).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A design opened a feature at a time is evaluated under the session's check mode, as + /// `doc.open` is. Started under another mode than the session's (the mode changed meanwhile), + /// nothing evaluated under it stands: every feature is evaluated again. The bar's last round + /// is one the check refuses on solidcore (kernel case + /// fillets/1207-fillet-bar-top-edge-after-boss-arc-round-r0-5), so there the modes differ in + /// their errors too. + #[test] + fn a_design_opened_a_feature_at_a_time_is_checked_under_the_sessions_mode() { + use super::open_steps::OpenSteps; + use solidcraft_kernel::Validation; + let dir = std::env::temp_dir().join(format!("solidcraft-open-steps-mode-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("steps.sc").to_string_lossy().to_string(); + let mut s = Session::default(); + s.set_validation(Validation::Off); + s.execute("solid.box", &json!({"length": 100, "width": 30, "height": 10, "corner": [0, -15, 0], "body_name": "Arm"})).unwrap(); + s.execute("solid.cylinder", &json!({"diameter": 40, "height": 20, "base": [0, 0, 0], "operation": "join", "targets": ["Arm"]})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[16, 12, 10]], "radius": 2})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[60, -15, 10]], "radius": 0.5})).unwrap(); + s.execute("file.save", &json!({"path": path, "cache": false})).unwrap(); + let errors = |s: &Session| s.model.results.iter().filter(|r| r.error.is_some()).count(); + let open = |mode: Validation| { + let mut whole = Session::default(); + whole.set_validation(mode); + whole.execute("doc.open", &json!({"path": path})).unwrap(); + errors(&whole) + }; + for mode in Validation::ALL { + for started in [mode, Validation::EachFeature, Validation::Off] { + let mut steps = OpenSteps::start(&json!({"path": path}), started).unwrap().expect("a design is opened in steps"); + while steps.step() {} + let mut stepped = Session::default(); + stepped.set_validation(mode); + steps.finish(&mut stepped).unwrap(); + assert_eq!(stepped.validation(), mode); + assert_eq!(errors(&stepped), open(mode), "started under {started:?}, the session's mode {mode:?}"); + let again = if started == mode { 0 } else { stepped.doc.features.len() }; + assert_eq!(stepped.model.last_recomputed, again, "started under {started:?}, the session's mode {mode:?}"); + assert!(stepped.model.is_current(&stepped.doc)); + } + } std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/src/cmd/file_easyprint.rs b/crates/engine/src/cmd/file_easyprint.rs index ab8739269..720cf7694 100644 --- a/crates/engine/src/cmd/file_easyprint.rs +++ b/crates/engine/src/cmd/file_easyprint.rs @@ -19,10 +19,12 @@ pub(super) struct Exported { pub fell_back: bool, /// The bodies that went in: the ones named, else the selected ones. pub bodies: Vec, + /// The bodies laid on their print face, and the ones that couldn't be. + pub laid: super::print_face::Laid, } -/// Export the bodies (the selected ones when none are named). A 3MF that can't be written is -/// written as an STL, and `fell_back` says so. +/// Export the bodies (the selected ones when none are named), each laid on its print face. A +/// 3MF that can't be written is written as an STL, and `fell_back` says so. pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Format) -> Result { let mut bodies = named.to_vec(); if bodies.is_empty() { @@ -31,7 +33,8 @@ pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Fo if bodies.is_empty() { return Err(bad(cmd, "select the bodies to send, or give `bodies`")); } - let doc = s.doc.painted(&s.world_state()); + let mut doc = s.doc.painted(&*s.world_state()?); + let laid = super::print_face::lay_on_print_faces(s, &mut doc, &bodies, &[]); let write = |format| solidcraft_io::export_with_metadata(&doc, &bodies, format, &s.doc.name, &s.doc.metadata); let mut fell_back = false; let (bytes, ext) = match (format, write(format)) { @@ -42,7 +45,7 @@ pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Fo } (_, Err(e)) => return Err(e.into()), }; - Ok(Exported { bytes, ext, fell_back, bodies }) + Ok(Exported { bytes, ext, fell_back, bodies, laid }) } pub(super) fn open_in_easyprint(s: &mut Session, p: &Value) -> Result { @@ -56,7 +59,7 @@ pub(super) fn open_in_easyprint(s: &mut Session, p: &Value) -> Result { if !bool_(p, "consent").unwrap_or(false) { return Err(bad(cmd, "this uploads the model to Printables' servers: ask the user, then pass `consent: true`")); } - let Exported { bytes, ext, fell_back, .. } = export_bodies(s, cmd, &string_list(cmd, p, "bodies")?, format)?; + let Exported { bytes, ext, fell_back, laid, .. } = export_bodies(s, cmd, &string_list(cmd, p, "bodies")?, format)?; if bytes.len() > MAX_BYTES { let mb = bytes.len().div_ceil(1_000_000); return Err(bad(cmd, format!("the model is {mb} MB and EasyPrint takes {} MB at most: send fewer bodies", MAX_BYTES / 1_000_000))); @@ -64,5 +67,7 @@ pub(super) fn open_in_easyprint(s: &mut Session, p: &Value) -> Result { let name = easyprint::file_name(&s.doc.name, ext); let size = bytes.len(); upload(&name, bytes).map_err(|e| bad(cmd, e))?; - Ok(json!({"file_name": name, "bytes": size, "format": ext, "stl_fallback": fell_back, "uploading": true})) + let mut out = json!({"file_name": name, "bytes": size, "format": ext, "stl_fallback": fell_back, "uploading": true}); + laid.report(&mut out); + Ok(out) } diff --git a/crates/engine/src/cmd/file_import.rs b/crates/engine/src/cmd/file_import.rs index 0a3ea1d10..4577435d8 100644 --- a/crates/engine/src/cmd/file_import.rs +++ b/crates/engine/src/cmd/file_import.rs @@ -10,10 +10,10 @@ use std::collections::HashMap; use std::hash::{Hash, Hasher}; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::joints::{Joint, JointKind, JointOrigin, Snap}; use solidcraft_doc::kernel::{StepImport, StepNode}; use solidcraft_doc::{FeatureKind, IDENTITY, Mat}; -use solidcraft_geom::Vec3; use crate::{EngineError, Result, Session}; diff --git a/crates/engine/src/cmd/file_open_steps.rs b/crates/engine/src/cmd/file_open_steps.rs new file mode 100644 index 000000000..589596c8e --- /dev/null +++ b/crates/engine/src/cmd/file_open_steps.rs @@ -0,0 +1,138 @@ +//! Opening a design a feature at a time, for a caller that must keep doing other work while a +//! large design is read: the web app has one thread, which has to keep drawing frames (and offer +//! Cancel) meanwhile (#10198). [`OpenSteps::start`] reads the file, [`OpenSteps::step`] evaluates +//! the next feature of its timeline, and [`OpenSteps::finish`] puts the design in the session's +//! place as `doc.open` does. The result is the same design, evaluated the same way: each step +//! moves a copy's history marker one feature on, so the evaluation reuses every result before it. + +use std::sync::Arc; + +use serde_json::Value; +use solidcraft_doc::{Document, FeatureKind, Model, Visibility}; + +use super::{opened_design, read_design}; +use crate::params::bool_; +use crate::{Result, Session}; + +/// A design file being opened ([`OpenSteps::start`]). +pub struct OpenSteps { + path: String, + read_only: bool, + disk: Option, + /// The design as the session will hold it, its history marker moved to `next` meanwhile. + doc: Arc, + /// The history marker the design was saved with. + marker: Option, + visibility: Visibility, + model: Model, + /// Features evaluated so far, and where evaluation stops (the saved marker, or the end). + next: usize, + stop: usize, + /// The model came from the file and needs no evaluation. + adopted: bool, +} + +impl OpenSteps { + /// Read the design file `doc.open` would open with parameters `p`, without evaluating it. + /// `None` when `p` names a file `doc.open` reads in another way (a CAD, mesh or drawing file, + /// or a point cloud), or asks for something only those take: run `doc.open` for it. + pub fn start(p: &Value, validation: solidcraft_kernel::Validation) -> Result> { + let Some(path) = p.get("path").and_then(Value::as_str) else { return Ok(None) }; + let other = solidcraft_io::is_step_path(path) + || solidcraft_io::is_mesh_path(path) + || solidcraft_io::is_point_cloud_path(path) + || super::super::drawing_import_command(path).is_some() + || ["names", "up"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null())); + if other || path.trim().is_empty() || path.len() >= 4096 { + return Ok(None); + } + let read_only = bool_(p, "read_only").unwrap_or(false); + // Stamped before it is read, as `doc.open` does. + let disk = solidcraft_io::design_lock::stamp(path); + let (mut doc, saved) = read_design(&mut Session::default(), path)?; + super::super::component_link::resolve_design_links(&mut doc, Some(path)); + // What `Session::opened` does before it evaluates. + solidcraft_io::vfs::install_checks(); + let visibility = std::mem::take(&mut doc.visibility); + let doc = Arc::new(doc); + let marker = doc.marker; + let stop = marker.unwrap_or(usize::MAX).min(doc.features.len()); + // A model saved under another check mode holds that mode's results: evaluated again. + let adopted = Session::saved_model(&doc, saved.as_ref()).filter(|model| model.validation() == validation); + let steps = OpenSteps { + path: path.to_string(), + read_only, + disk, + doc, + marker, + visibility, + next: if adopted.is_some() { stop } else { 0 }, + stop, + adopted: adopted.is_some(), + model: adopted.unwrap_or_else(|| under(validation)), + }; + Ok(Some(steps)) + } + + /// The file being opened. + pub fn path(&self) -> &str { + &self.path + } + + /// Features evaluated so far, and how many there are to evaluate. + pub fn progress(&self) -> (usize, usize) { + (self.next, self.stop) + } + + /// Whether every feature has been evaluated ([`Self::finish`] is next). + pub fn done(&self) -> bool { + self.next >= self.stop + } + + /// The STEP text the next feature imports, when it is an import that is not suppressed: a + /// caller can read it in parts first (`kernel::StepReading`), and while it holds that + /// reading's result the step finds the file read. + pub fn next_import(&self) -> Option> { + let f = self.doc.features.get(self.next).filter(|_| !self.done())?; + match &f.kind { + FeatureKind::Import { step, .. } if !f.suppressed => Some(step.clone()), + _ => None, + } + } + + /// Evaluate the next feature. False once there is none left. + pub fn step(&mut self) -> bool { + if self.done() { + return false; + } + self.next += 1; + Arc::make_mut(&mut self.doc).marker = Some(self.next); + self.model.evaluate(&self.doc); + !self.done() + } + + /// Put the design in `s`'s place as `doc.open` does, and answer as it does. Features not + /// yet evaluated are evaluated now. + pub fn finish(mut self, s: &mut Session) -> Result { + Arc::make_mut(&mut self.doc).marker = self.marker; + // The results so far hold another mode's checks: evaluated again, as `Session::opened` would. + if self.model.validation() != s.validation() { + self.model = under(s.validation()); + self.adopted = false; + } + if !self.adopted { + // Every result is current: this takes them all and keeps the placement proof + // `Session::opened` keeps. + self.model.evaluate_shared(&self.doc); + } + let opened = Session::with_model(self.doc, self.visibility, self.model).located(Some(&self.path)); + opened_design(s, opened, &self.path, self.read_only, self.disk) + } +} + +/// A model with no results yet, checking its features under `validation`. +fn under(validation: solidcraft_kernel::Validation) -> Model { + let mut model = Model::default(); + model.set_validation(validation); + model +} diff --git a/crates/engine/src/cmd/file_send.rs b/crates/engine/src/cmd/file_send.rs index 1ed3d64bc..dd8788704 100644 --- a/crates/engine/src/cmd/file_send.rs +++ b/crates/engine/src/cmd/file_send.rs @@ -11,7 +11,7 @@ use serde_json::{Value, json}; use solidcraft_io::Format; use super::easyprint::{Exported, export_bodies}; -use super::export_to; +use super::export_laid_to; use crate::params::bad; use crate::slicers::{self, Slicer, TargetKind}; use crate::{EngineError, Result, Session}; @@ -81,7 +81,7 @@ pub(super) fn send(s: &mut Session, r: Send<'_>) -> Result { return Err(bad(r.cmd, format!("{} does not take {}", target.name, format_name(r.format)))); } let mut out = match r.dest { - Dest::Path(path) => export_to(s, path, r.format, &r.bodies, &r.parts, r.quality)?, + Dest::Path(path) => export_laid_to(s, path, r.format, &r.bodies, &r.parts, r.quality)?, Dest::Folder => write_in_folder(s, &r)?, }; let path = out.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); @@ -92,11 +92,13 @@ pub(super) fn send(s: &mut Session, r: Send<'_>) -> Result { /// Write the bodies into the slicer folder. fn write_in_folder(s: &mut Session, r: &Send<'_>) -> Result { use crate::slicer_files; - let Exported { bytes, ext, fell_back, bodies } = export_bodies(s, r.cmd, &r.bodies, r.format)?; + let Exported { bytes, ext, fell_back, bodies, laid } = export_bodies(s, r.cmd, &r.bodies, r.format)?; let dir = slicer_files::dir().ok_or_else(|| bad(r.cmd, "no per-user folder on this system"))?; let stem = slicer_files::stem(&s.doc.name, s.path.as_deref(), s.uid, &bodies); let (file, numbered) = slicer_files::write(&dir, &stem, ext, &bytes).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?; - Ok(json!({"path": file.to_string_lossy(), "bytes": bytes.len(), "format": ext, "numbered": numbered, "stl_fallback": fell_back})) + let mut out = json!({"path": file.to_string_lossy(), "bytes": bytes.len(), "format": ext, "numbered": numbered, "stl_fallback": fell_back}); + laid.report(&mut out); + Ok(out) } /// Hand the file at `path` to `target`, starting it first if it has to be, and say what happened in diff --git a/crates/engine/src/cmd/file_thumbnail.rs b/crates/engine/src/cmd/file_thumbnail.rs index bc3c4ff95..c377b1c73 100644 --- a/crates/engine/src/cmd/file_thumbnail.rs +++ b/crates/engine/src/cmd/file_thumbnail.rs @@ -37,7 +37,7 @@ fn scene(s: &Session) -> Option<(Scene, Camera)> { let face_colors = s.doc.face_colors(body).into_iter().map(|(face, look)| (face as u32, Rgb(look.color[0], look.color[1], look.color[2]))).collect(); let opacity = s.doc.model_body_opacity(body) as f32; - scene.meshes.push(SceneMesh { mesh, color, face_colors, opacity }); + scene.meshes.push(SceneMesh { mesh, color, face_colors, opacity, closed: body.is_closed(), hatch: Default::default() }); } if bounds.is_empty() { return None; @@ -62,7 +62,7 @@ mod tests { session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30,"body_name":"Visible"})).unwrap(); session.execute("solid.box", &serde_json::json!({"length":100,"width":100,"height":100,"body_name":"Hidden"})).unwrap(); session.execute("browser.visibility", &serde_json::json!({"items":["Hidden"],"visible":false})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); for body in &world.bodies { body.mesh(); } @@ -85,7 +85,7 @@ mod tests { crate::capture::install_test_renderer(); let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); assert!(saved(&session).is_none()); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); @@ -106,7 +106,7 @@ mod tests { fn without_a_renderer_a_save_has_no_thumbnail() { let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } let (scene, camera) = scene(&session).unwrap(); diff --git a/crates/engine/src/cmd/frame.rs b/crates/engine/src/cmd/frame.rs index d0fec7a26..4eabb3edb 100644 --- a/crates/engine/src/cmd/frame.rs +++ b/crates/engine/src/cmd/frame.rs @@ -3,13 +3,14 @@ //! the built-in profiles, `frame.profile.properties` works out a profile's section, and //! `frame.profile.insert` draws one into a sketch. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use serde_json::{Value, json}; +use solidcore_record::{Loop2, Seg2, Vec2}; use solidcraft_doc::expr::Kind; use solidcraft_doc::frame::{self, Anchor, MemberProfile, Profile, ProfileSpec}; use solidcraft_doc::{FeatureKind, SketchId}; -use solidcraft_geom::{Loop2, Seg2, Vec2}; use solidcraft_sketch::Sketch; use super::features::{add_feature, check_expr, sketch_id}; diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index b288ef343..6ba2c33f9 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -1,5 +1,6 @@ //! Inspection: measure bodies, describe the document, sketches and model topology. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use std::hash::{BuildHasher, RandomState}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -10,8 +11,15 @@ use solidcraft_sketch::CurveKind; use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list}; +use crate::schema::inspect::{ + BodyListParams, FaceCylinder, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads, ModelThreadsParams, +}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; +const BODY_LIST_CONTRACT: TypedContract = TypedContract::new(); +const THREADS_CONTRACT: TypedContract = TypedContract::new(); + #[path = "appearance_chain.rs"] mod appearance_chain; @@ -27,27 +35,47 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("measure") .key("I") .noundo() - .params("bodies?: [names] (default all) → closed per body; volume_mm3, center_of_mass, density_g_cm3 and mass_g only for closed, consistently oriented bodies; area, bbox and counts for all; total.open_bodies_skipped counts bodies excluded from volume/mass totals; or items: [1-2 selections] (face/edge: type, body, point; index optional) → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"), + .params("bodies?: [names] (default all); names_only?: bool (each world body's name and its definition's, nothing measured) → closed per body; volume_mm3, center_of_mass, density_g_cm3 and mass_g only for closed, consistently oriented bodies; area, bbox and counts for all; total.open_bodies_skipped counts bodies excluded from volume/mass totals; or items: [1-2 selections] (face/edge: type, body, point; index optional) → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"), CommandSpec::new("document.inspect", "Inspect Design", inspect).icon("inspect").noundo().params("measure?: bool (include body measurements)"), CommandSpec::new("document.revision", "Design Revision", revision).icon("inspect").noundo().params( "→ document_id (this open design's id: kept while it stays open, another for each design started or opened), \ revision (moves whenever the design, what is hidden or a component's uncaptured position changes, \ never on a selection or a view; from one counter for the whole run, so it never repeats). Read-only", ), - CommandSpec::new("sketch.inspect", "Inspect Sketch", sketch_inspect).icon("inspect").noundo().params("sketch?: id|name (default active)"), - CommandSpec::new("model.edges", "List Edges", model_edges).icon("inspect").noundo().params("body: name"), - CommandSpec::new("model.faces", "List Faces", model_faces).icon("inspect").noundo().params( + CommandSpec::new("sketch.inspect", "Inspect Sketch", sketch_inspect).at("SKETCH", "INSPECT").icon("inspect").noundo().params("sketch?: id|name (default active)"), + CommandSpec::new("model.edges", "List Edges", crate::checked!("model.edges", model_edges)) + .icon("inspect") + .noundo() + .contract(&BODY_LIST_CONTRACT) + .output(output_schema_for::) + .params("body: name"), + CommandSpec::new("model.faces", "List Faces", crate::checked!("model.faces", model_faces)) + .icon("inspect") + .noundo() + .contract(&BODY_LIST_CONTRACT) + .output(output_schema_for::) + .params( "body: name → per face: index, name (what face.delete, sheet.convert `face`, solid.shell … take in place of a point), exact, area, centroid (not always on the face), \ plane_normal, point (a point on the face that picks it), cylinder? ({origin, axis, radius} of a cylindrical face), \ sheet_face? (a folded sheet's face: `sheet:::`, panel base or a flange's tag F., side top | bottom | rim. | bend.inner | bend.outer; \ taken wherever a face name is, and it holds while sizes change and flanges come and go)", ), - CommandSpec::new("model.threads", "List Threads", model_threads).icon("inspect").noundo(), + CommandSpec::new("model.threads", "List Threads", crate::checked!("model.threads", model_threads)) + .icon("inspect") + .noundo() + .contract(&THREADS_CONTRACT) + .output(output_schema_for::), CommandSpec::new("material.assign", "Physical Material", physical_material) .at("SOLID", "MODIFY") .icon("material") .params("bodies: [names]; material: name (Steel, Aluminum, ABS Plastic, …, or one made with material.create; `material.list`)"), - CommandSpec::new("appearance.assign", "Appearance", appearance).at("SOLID", "MODIFY").icon("appearance").key("A").params( + CommandSpec::new("appearance.assign", "Appearance", crate::checked!("appearance.assign", appearance)) + .at("SOLID", "MODIFY") + .icon("appearance") + .key("A") + .contract(&ASSIGN_CONTRACT) + .output(crate::schema::output_schema_for::) + .params( "bodies?: [names]; faces?: [[x,y,z] on faces] (body?: which body, default the nearest); components?: [names or ids, or occurrence names]; \ appearance?: library name or stable starter.* ID (appearance.library) | color: \"#rrggbb\" or [r, g, b] (0–255), opacity? (0–1, default 1); \ name?: inert copied look label (requires color, mutually exclusive with appearance); pbr?: {metallic:0..1, roughness:0.045..1, dielectric_ior:1..3} (requires color/appearance and opacity 1); a starter ID or registered starter name resolves its recipe before color overrides; omitted pbr retains that response and pbr: null explicitly clears it. Unavailable glass recipes refuse through either selector. Other custom labels with an explicit color retain legacy scalar behavior. Neither appearance nor color (or color: null): clear, so the face follows its body, the body its component, the component its material", @@ -59,17 +87,23 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("appearance.favorite", "Favorite Look", appearance_gestures::favorite).icon("star").noundo().doc_only() .params("look: appearance.assign look; favorite: bool → validated look and preference request; UI library preference only, no document change or dialogs."), CommandSpec::new("appearance.chain", "Appearance Chain", appearance_chain::chain).icon("inspect").noundo().params( - "target: {body: name} | {body: name, face: zero-based model.faces index} | {component: name or id}. Returns steps [{step: face|body|component|material, look: {name,color,opacity,pbr?} or null}] in precedence order and active (step or null). Component material is the common default look of its directly owned bodies, null if mixed/empty. Imported paint is a display fallback outside the four steps. Read-only; no dialogs", + "target: {body: name} | {body: name, face: zero-based model.faces index} | {component: name or id}; a placed copy's name (`KB (K:2)`, `K:2`) means the body or component it shows. Returns steps [{step: face|body|component|material, look: {name,color,opacity,pbr?} or null}] in precedence order and active (step or null). Component material is the common default look of its directly owned bodies, null if mixed/empty. Imported paint is a display fallback outside the four steps. Read-only; no dialogs", ), CommandSpec::new("appearance.replace", "Replace Appearance", appearance_chain::replace).icon("appearance").params( - "from: library name | saved look {name,color,opacity,pbr?} (copy appearance.list in_design); to: library name | assignment look {appearance? | color, name?, opacity?, pbr?} (appearance.assign rules; no clear). Matches the full look including name and PBR. scope?: {bodies?: [names], components?: [names or ids]}, at most 10000 targets; body scope includes face overrides, component scope selects only the component override. Omitted scope means all overrides, including hidden/suppressed ones; physical defaults are unchanged. Duplicate targets count once. Returns count of rewritten overrides; zero adds no history. One undo step, atomic; no dialogs. Designs above 100000 overrides refuse", + "from: library name | saved look {name,color,opacity,pbr?} (copy appearance.list in_design); to: library name | assignment look {appearance? | color, name?, opacity?, pbr?} (appearance.assign rules; no clear). Matches the full look including name and PBR. scope?: {bodies?: [names], components?: [names or ids]} (a placed copy's name means the body or component it shows), at most 10000 targets; body scope includes face overrides, component scope selects only the component override. Omitted scope means all overrides, including hidden/suppressed ones; physical defaults are unchanged. Duplicate targets count once. Returns count of rewritten overrides; zero adds no history. One undo step, atomic; no dialogs. Designs above 100000 overrides refuse", ), - CommandSpec::new("appearance.library", "Appearance Library", appearance_library).icon("library") + CommandSpec::new("appearance.library", "Appearance Library", crate::checked!("appearance.library", appearance_library)) + .icon("library") .noundo() + .contract(&LIBRARY_CONTRACT) + .output(crate::schema::output_schema_for::) .params("→ 20 legacy scalar appearances, six opaque PBR finishes and 40 starter recipes with IDs, categories, provenance, requirements and availability; six starter glass recipes are unavailable"), - CommandSpec::new("appearance.list", "List Appearances", appearance_list).icon("list") + CommandSpec::new("appearance.list", "List Appearances", crate::checked!("appearance.list", appearance_list)) + .icon("list") .noundo() - .params("body?: name → assigned appearances; with body, its resolved look and its faces' (face index, look)"), + .contract(&LIST_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("body?: name (or a placed copy's, `KB (K:2)`: the body it shows) → assigned appearances; with body, its resolved look and its faces' (face index, look)"), CommandSpec::new("material.list", "List Materials", material_list).icon("list") .noundo() .doc_only() @@ -109,6 +143,8 @@ pub fn measure_json(b: &solidcraft_doc::ModelBody) -> Value { "vertices": m.merged.vertices, "face_types": m.merged.face_types, "kernel": {"faces": m.faces, "edges": m.edges, "vertices": m.vertices, "shells": m.shells}, + "measured_by": m.measured_by, + "notes": m.notes, }) } Err(e) => json!({"name": b.name, "error": e.to_string()}), @@ -121,8 +157,15 @@ fn measure(s: &mut Session, p: &Value) -> Result { return super::measure_sel::measure_items(s, items); } let want = string_list(cmd, p, "bodies")?; - let st = s.world_state(); + let st = s.world_state()?; let selected: Vec<_> = st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).collect(); + if !want.is_empty() && selected.len() != want.len() { + return Err(bad(cmd, "unknown body name")); + } + if bool_(p, "names_only").unwrap_or(false) { + let bodies: Vec<_> = selected.iter().map(|b| json!({"name": b.name, "definition": b.definition_name()})).collect(); + return Ok(json!({"body_count": bodies.len(), "bodies": bodies})); + } // Each body is measured on its own: on all cores, in body order. let mut bodies: Vec = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_json(b)) .into_iter() @@ -140,9 +183,6 @@ fn measure(s: &mut Session, p: &Value) -> Result { b["mass_g"] = json!(v * rho / 1000.0); } } - if !want.is_empty() && bodies.len() != want.len() { - return Err(bad(cmd, "unknown body name")); - } // Sheet metal keeps the edges where bends meet flat faces (so bends stay visible): count its // B-rep faces as they are, without merging coplanar neighbours. let sheets = s.model.state().sheets.clone(); @@ -185,11 +225,10 @@ fn measure(s: &mut Session, p: &Value) -> Result { ) } -fn sketch_json(s: &Session, id: u64) -> Option { +/// Sketch `id`, placed where the placed model `world` has it (its component's placement). +fn sketch_json(s: &Session, world: &solidcraft_doc::ModelState, id: u64) -> Option { let state = s.model.state(); let ss = state.sketch(id)?; - // Where the sketch is in the world (its component's placement). - let world = s.world_state(); let plane = world.sketch(id).map(|w| w.plane).unwrap_or(ss.plane); let sk = &ss.sketch; let curves: Vec = sk @@ -204,7 +243,17 @@ fn sketch_json(s: &Session, id: u64) -> Option { CurveKind::Circle { c: cc, r } => json!({"id": c.id, "type": "circle", "center": pid(cc), "center_at": sk.point(cc), "radius": r, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}), CurveKind::Arc { c: cc, a, b } => json!({"id": c.id, "type": "arc", "center": pid(cc), "start": pid(a), "end": pid(b), "center_at": sk.point(cc), "start_at": sk.point(a), "end_at": sk.point(b), "radius": sk.radius(i), "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}), CurveKind::Ellipse { c: cc, m, r } => json!({"id": c.id, "type": "ellipse", "center": pid(cc), "major": pid(m), "center_at": sk.point(cc), "major_at": sk.point(m), "minor_radius": r, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}), - CurveKind::Spline { ref pts, control, degree, periodic } => json!({"id": c.id, "type": "spline", "points": pts.iter().map(|q| pid(*q)).collect::>(), "points_at": pts.iter().map(|q| sk.point(*q)).collect::>(), "control": control, "degree": degree, "periodic": periodic, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}), + CurveKind::Spline { ref pts, control, degree, periodic, ref nurbs } => { + let mut v = json!({"id": c.id, "type": "spline", "points": pts.iter().map(|q| pid(*q)).collect::>(), "points_at": pts.iter().map(|q| sk.point(*q)).collect::>(), "control": control, "degree": degree, "periodic": periodic, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}); + // A control spline with its own knots (a projected free-form edge) says them. + if let (Some(n), Some(o)) = (nurbs, v.as_object_mut()) { + o.insert("knots".into(), json!(n.knots)); + if !n.weights.is_empty() { + o.insert("weights".into(), json!(n.weights)); + } + } + v + } CurveKind::Conic { a, b, apex, rho } => json!({"id": c.id, "type": "conic", "start": pid(a), "end": pid(b), "apex": pid(apex), "start_at": sk.point(a), "end_at": sk.point(b), "apex_at": sk.point(apex), "rho": rho, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}), }; if let (Some(l), Some(o)) = (&c.link, v.as_object_mut()) { @@ -267,7 +316,7 @@ fn sketch_json(s: &Session, id: u64) -> Option { fn sketch_inspect(s: &mut Session, p: &Value) -> Result { let id = super::sketch_store::target(s, p, "sketch.inspect")?; - sketch_json(s, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into())) + sketch_json(s, &*s.world_state()?, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into())) } /// Revisions of every design of this run (#6646). @@ -343,7 +392,6 @@ fn inspect(s: &mut Session, p: &Value) -> Result { json!({ "id": f.id, "name": f.name, "type": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": i >= marker, "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone()), "ms": r.map(|r| r.ms), - "boolean_diagnostics": r.map(|r| &r.boolean_diagnostics), }) }) .collect(); @@ -387,21 +435,32 @@ fn body_of<'a>(st: &'a solidcraft_doc::ModelState, p: &Value, cmd: &str) -> Resu } fn model_edges(s: &mut Session, p: &Value) -> Result { - let st = s.world_state(); + let st = s.world_state()?; let b = body_of(&st, p, "model.edges")?; let tol = (b.body.size() * 2e-3).max(1e-3); let names = solidcraft_doc::naming::edge_names(b); - let edges: Vec = b + let edges = b .body .edges(tol)? .iter() - .map(|e| json!({"index": e.index, "name": names.get(e.index), "mid": e.mid, "length": e.length, "start": e.points.first(), "end": e.points.last()})) + .map(|e| ModelEdge { + index: e.index, + name: names.get(e.index).cloned(), + mid: e.mid.into(), + length: e.length, + start: e.points.first().map(|&p| p.into()), + end: e.points.last().map(|&p| p.into()), + }) .collect(); - Ok(json!({"body": b.name, "edges": edges})) + reply("model.edges", ModelEdges { body: b.name.clone(), edges, param_warnings: Vec::new() }) +} + +fn reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) } fn model_faces(s: &mut Session, p: &Value) -> Result { - let st = s.world_state(); + let st = s.world_state()?; let b = body_of(&st, p, "model.faces")?; let names = solidcraft_doc::naming::face_names(b); let tol = (b.body.size() * 2e-3).max(1e-3); @@ -410,26 +469,32 @@ fn model_faces(s: &mut Session, p: &Value) -> Result { // the body's own coordinates. let model = s.model.state(); let sheet_names = model.body(&b.name).map(|own| solidcraft_doc::sheet::body_sheet_face_names(&model, own)).unwrap_or_default(); - let faces: Vec = b + let faces = b .body .faces(tol)? .iter() .map(|f| { let spot = spots.get(f.index).copied().flatten(); - let mut v = json!({"index": f.index, "name": names.get(f.index), "exact": solidcraft_doc::naming::face_name_exact(b, f.index), - "area": f.area, "centroid": f.centroid, "plane_normal": f.plane_normal, "point": spot.map(|x| x.point)}); - if let (Some(Some(name)), Some(o)) = (sheet_names.get(f.index), v.as_object_mut()) { - o.insert("sheet_face".into(), json!(name)); + let cylinder = match spot.and_then(|x| x.surface) { + Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }) => { + Some(FaceCylinder { origin: origin.into(), axis: solidcore_record::Vec3::from(axis).into(), radius }) + } + _ => None, + }; + ModelFace { + index: f.index, + name: names.get(f.index).cloned(), + exact: solidcraft_doc::naming::face_name_exact(b, f.index), + area: f.area, + centroid: f.centroid.into(), + plane_normal: f.plane_normal.map(Into::into), + point: spot.map(|x| x.point.into()), + cylinder, + sheet_face: sheet_names.get(f.index).and_then(|n| n.as_ref().map(|n| n.to_string())), } - if let (Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }), Some(o)) = - (spot.and_then(|x| x.surface), v.as_object_mut()) - { - o.insert("cylinder".into(), json!({"origin": origin, "axis": axis, "radius": radius})); - } - v }) .collect(); - Ok(json!({"body": b.name, "faces": faces})) + reply("model.faces", ModelFaces { body: b.name.clone(), faces, param_warnings: Vec::new() }) } const DESCRIBE_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); @@ -454,8 +519,8 @@ fn commands(s: &mut Session, _p: &Value) -> Result { } fn model_threads(s: &mut Session, _p: &Value) -> Result { - let st = s.world_state(); - Ok(json!({ "threads": st.threads })) + let st = s.world_state()?; + reply("model.threads", ModelThreads { threads: st.threads.iter().map(ModelThread::from).collect(), param_warnings: Vec::new() }) } fn physical_material(s: &mut Session, p: &Value) -> Result { @@ -478,7 +543,7 @@ fn physical_material(s: &mut Session, p: &Value) -> Result { } /// A colour parameter: `"#rrggbb"` or `[r, g, b]` (0–255). -pub(super) fn color_param(v: &Value) -> Option<[u8; 3]> { +pub(crate) fn color_param(v: &Value) -> Option<[u8; 3]> { if let Some(t) = v.as_str() { let h = t.trim().trim_start_matches('#'); if h.len() != 6 || !h.is_ascii() { @@ -492,6 +557,21 @@ pub(super) fn color_param(v: &Value) -> Option<[u8; 3]> { Some([c(0)?, c(1)?, c(2)?]) } +use crate::schema::appearance::{ + AppearanceAssignParams, AppearanceAssignResult, AppearanceLibraryParams, AppearanceLibraryResult, AppearanceListParams, AppearanceListResult, + BodyLooks, ComponentLookReply, FaceIndexLook, FaceLookReply, FaceSpot, LibraryAppearance, LookInDesign, LookReply, PbrReply, PlainAppearance, + StarterAppearance, +}; + +const ASSIGN_CONTRACT: TypedContract = TypedContract::new(); +const LIBRARY_CONTRACT: TypedContract = TypedContract::new(); +const LIST_CONTRACT: TypedContract = TypedContract::new(); + +/// An appearance command's reply, built from its schema's type so the two can't drift apart. +fn appearance_reply(cmd: &str, r: impl serde::Serialize) -> Result { + serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string())) +} + pub(super) fn appearance(s: &mut Session, p: &Value) -> Result { use solidcraft_doc::appearance::FaceLook; let cmd = "appearance.assign"; @@ -502,7 +582,7 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`bodies` must list existing bodies")); } // Faces: a point on each, on the named body or the nearest one. - let mut faces: Vec<(String, solidcraft_geom::Vec3)> = Vec::new(); + let mut faces: Vec<(String, solidcore_record::Vec3)> = Vec::new(); if let Some(list) = p.get("faces") { let list = list.as_array().filter(|a| a.len() <= 10_000).ok_or_else(|| bad(cmd, "`faces` must list points [x, y, z]"))?; for v in list { @@ -519,19 +599,14 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result { } let mut comps: Vec = Vec::new(); for c in string_list(cmd, p, "components")? { - let id = s - .doc - .find_component(&c) - .or_else(|| s.doc.occurrences.iter().find(|o| o.name == c).map(|o| o.component)) - .filter(|id| *id != 0) - .ok_or_else(|| bad(cmd, format!("no component `{c}`")))?; + let id = s.component_or_placement(&c).ok_or_else(|| bad(cmd, format!("no component `{c}`")))?; comps.push(id); } if bodies.is_empty() && faces.is_empty() && comps.is_empty() { return Err(bad(cmd, "give `bodies`, `faces` or `components`")); } // Persistent names of the picked faces. - let st_names: Vec<(String, solidcraft_geom::Vec3, Option)> = faces + let st_names: Vec<(String, solidcore_record::Vec3, Option)> = faces .iter() .map(|(b, pt)| { let n = st.body(b).and_then(|mb| { @@ -591,12 +666,9 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result { }) }); } - Ok(json!({ - "bodies": bodies, - "faces": faces.iter().map(|(b, p)| json!({"body": b, "point": p})).collect::>(), - "components": comps, - "appearance": look.as_ref().map(look_json), - })) + let faces = faces.iter().map(|(body, p)| FaceSpot { body: body.clone(), point: [p.x, p.y, p.z] }).collect(); + let appearance = look.as_ref().map(LookReply::from); + appearance_reply(cmd, AppearanceAssignResult { bodies, faces, components: comps, appearance, param_warnings: Vec::new() }) } /// Shared look parser for assignment and atomic replacement. @@ -668,9 +740,9 @@ pub(super) fn appearance_look(cmd: &str, p: &Value) -> Result f64 { +fn dist_to(b: &solidcraft_doc::ModelBody, p: solidcore_record::Vec3) -> f64 { let bb = b.mesh().bounds(); - let c = solidcraft_geom::Vec3::new(p.x.clamp(bb.min.x, bb.max.x), p.y.clamp(bb.min.y, bb.max.y), p.z.clamp(bb.min.z, bb.max.z)); + let c = solidcore_record::Vec3::new(p.x.clamp(bb.min.x, bb.max.x), p.y.clamp(bb.min.y, bb.max.y), p.z.clamp(bb.min.z, bb.max.z)); c.dist(p) } @@ -718,35 +790,45 @@ pub(super) fn attach_pbr(cmd: &str, params: &Value, look: &mut solidcraft_doc::a } fn appearance_library(_s: &mut Session, _p: &Value) -> Result { - let mut list: Vec = solidcraft_doc::appearance::LIBRARY + let category = |name: &str| name.split(" - ").next().unwrap_or(name).to_string(); + let mut list: Vec = solidcraft_doc::appearance::LIBRARY .iter() .map(|(n, c, o)| { - let category = n.split(" - ").next().unwrap_or(n); - json!({"name": n, "category": category, "color": format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]), "opacity": o}) + let look = LookReply { name: n.to_string(), color: format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]), opacity: *o, pbr: None }; + LibraryAppearance::Plain(PlainAppearance { look, category: category(n) }) }) .collect(); list.extend(solidcraft_doc::appearance::OPAQUE_FINISHES.iter().filter_map(|(name, ..)| { let look = solidcraft_doc::appearance::library(name)?; - let mut value = look_json(&look); - value["category"] = json!(name.split(" - ").next().unwrap_or(name)); - Some(value) + Some(LibraryAppearance::Plain(PlainAppearance { look: LookReply::from(&look), category: category(name) })) })); for preset in solidcraft_doc::appearance_pack::STARTER_PACK { let c = preset.preview_color(); - let pbr = preset.opaque_look().ok().and_then(|look| look.pbr); - list.push(json!({"id":preset.id,"name":preset.name,"category":preset.category,"revision":preset.revision, - "color":format!("#{:02x}{:02x}{:02x}",c[0],c[1],c[2]),"opacity":1.0,"pbr":pbr, - "available":preset.is_opaque(),"requirements":preset.requirements,"provenance":preset.provenance, - "recipe":preset.recipe,"preview_note":preset.preview_note,"future_texture_recipe":preset.future_texture_recipe})); + list.push(LibraryAppearance::Starter(StarterAppearance { + id: preset.id.to_string(), + name: preset.name.to_string(), + category: json!(preset.category), + revision: preset.revision, + color: format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]), + opacity: 1.0, + pbr: preset.opaque_look().ok().and_then(|look| look.pbr).map(PbrReply::from), + available: preset.is_opaque(), + requirements: json!(preset.requirements), + provenance: json!(preset.provenance), + recipe: json!(preset.recipe), + preview_note: preset.preview_note.to_string(), + future_texture_recipe: json!(preset.future_texture_recipe), + })); } - Ok(json!({"appearances": list})) + appearance_reply("appearance.library", AppearanceLibraryResult { appearances: list, param_warnings: Vec::new() }) } fn appearance_list(s: &mut Session, p: &Value) -> Result { let a = &s.doc.appearances; // "In this design": each look used, with where. - let mut used: Vec<(solidcraft_doc::appearance::Look, Vec, Vec, Vec)> = Vec::new(); - fn slot(used: &mut Vec<(solidcraft_doc::appearance::Look, Vec, Vec, Vec)>, l: &solidcraft_doc::appearance::Look) -> usize { + type Used = Vec<(solidcraft_doc::appearance::Look, Vec, Vec, Vec)>; + let mut used: Used = Vec::new(); + fn slot(used: &mut Used, l: &solidcraft_doc::appearance::Look) -> usize { match used.iter().position(|(u, ..)| u == l) { Some(i) => i, None => { @@ -758,48 +840,49 @@ fn appearance_list(s: &mut Session, p: &Value) -> Result { for (b, l) in &a.bodies { let i = slot(&mut used, l); if let Some(u) = used.get_mut(i) { - u.1.push(json!(b)); + u.1.push(b.clone()); } } for f in &a.faces { let i = slot(&mut used, &f.look); if let Some(u) = used.get_mut(i) { - u.2.push(json!({"body": f.body, "point": f.point})); + u.2.push(FaceSpot { body: f.body.clone(), point: [f.point.x, f.point.y, f.point.z] }); } } for (c, l) in &a.components { let i = slot(&mut used, l); if let Some(u) = used.get_mut(i) { - u.3.push(json!(c)); + u.3.push(*c); } } - let in_design: Vec = used - .iter() - .map(|(l, b, f, c)| { - let mut value = look_json(l); - value["bodies"] = json!(b); - value["faces"] = json!(f); - value["components"] = json!(c); - value - }) - .collect(); - let mut out = json!({ - "in_design": in_design, - "bodies": a.bodies.iter().map(|(b, l)| (b.clone(), look_json(l))).collect::>(), - "faces": a.faces.iter().map(|f| json!({"body": f.body, "point": f.point, "appearance": look_json(&f.look)})).collect::>(), - "components": a.components.iter().map(|(c, l)| json!({"component": c, "appearance": look_json(l)})).collect::>(), - }); + let in_design = + used.into_iter().map(|(l, bodies, faces, components)| LookInDesign { look: LookReply::from(&l), bodies, faces, components }).collect(); + let mut out = AppearanceListResult { + in_design, + bodies: a.bodies.iter().map(|(b, l)| (b.clone(), LookReply::from(l))).collect(), + faces: a + .faces + .iter() + .map(|f| FaceLookReply { body: f.body.clone(), point: [f.point.x, f.point.y, f.point.z], appearance: LookReply::from(&f.look) }) + .collect(), + components: a.components.iter().map(|(c, l)| ComponentLookReply { component: *c, appearance: LookReply::from(l) }).collect(), + body: None, + param_warnings: Vec::new(), + }; if let Some(name) = str_(p, "body") { let st = s.model.state(); - let b = st.body(name).ok_or_else(|| bad("appearance.list", format!("no body `{name}`")))?; - out["body"] = json!({ - "name": name, - "appearance": s.doc.model_body_look(b).map(|l| look_json(&l)), - "color": s.doc.body_color(b), - "faces": s.doc.face_colors(b).iter().map(|(i, l)| json!({"face": i, "appearance": look_json(l)})).collect::>(), + // A placed copy's name (`KB (K:2)`) means the body it shows, as appearance.assign takes + // it (#9740): the reply names that body. + let own = s.own_body_name(name); + let b = own.as_deref().and_then(|n| st.body(n)).ok_or_else(|| bad("appearance.list", format!("no body `{name}`")))?; + out.body = Some(BodyLooks { + name: b.name.clone(), + appearance: s.doc.model_body_look(b).as_ref().map(LookReply::from), + color: s.doc.body_color(b), + faces: s.doc.face_colors(b).iter().map(|(i, l)| FaceIndexLook { face: *i, appearance: LookReply::from(l) }).collect(), }); } - Ok(out) + appearance_reply("appearance.list", out) } fn material_list(s: &mut Session, _p: &Value) -> Result { diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rs index 453495178..69dec681c 100644 --- a/crates/engine/src/cmd/interference.rs +++ b/crates/engine/src/cmd/interference.rs @@ -14,8 +14,9 @@ use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_geom::mesh_distance::TriangleSet; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcraft_geom::{Aabb3, Mesh}; use solidcraft_kernel::Body; use solidcraft_kernel::profile::KernelTimes; @@ -56,8 +57,6 @@ enum Outcome { /// One pair's answer and where its time went. struct Done { outcome: Outcome, - /// Unverified boolean results are listed as unchecked and still reported as a hit. - note: Option, ms: f64, kernel: KernelTimes, } @@ -74,7 +73,12 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { }; let budget = std::time::Duration::from_secs_f64(budget_s); let want = string_list(cmd, p, "bodies")?; - let st = s.world_state(); + let st = s.world_state()?; + // A name that is no body is refused, as inspect.clearance refuses it. Dropped, a misspelled + // body was never checked and the answer read as no interference (#9740). + if let Some(n) = want.iter().find(|n| st.body(n).is_none()) { + return Err(bad(cmd, super::no_body(n, st.bodies.iter().map(|b| b.name.as_str())))); + } let (meshes_left, bodies): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).partition(|b| b.body.is_mesh()); @@ -171,9 +175,6 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { json!({"a": a, "b": b, "ms": round_ms(d.ms), "boolean_ms": round_ms(d.kernel.boolean_ms), "tessellate_ms": round_ms(d.kernel.tessellate_ms)}), )); - if let Some(reason) = d.note { - unchecked.push(json!({"a": a, "b": b, "reason": reason})); - } match d.outcome { Outcome::Hit(v) => hits.push(v), Outcome::Clear => {} @@ -263,92 +264,31 @@ fn any_inside(points: &[Vec3], outer: &Mesh) -> bool { } } -/// The exact check of one pair: a pin a hair off the axis of its hole by the walls' crescent, -/// otherwise the intersection measured. +/// The exact check of one pair: the bodies' intersection, measured. fn check(job: &Job) -> Done { let started = web_time::Instant::now(); - let ((outcome, note), kernel) = solidcraft_kernel::profile::capture(|| check_pair(&job.a, &job.b, &job.names)); - Done { outcome, note, ms: started.elapsed().as_secs_f64() * 1000.0, kernel } + let (outcome, kernel) = solidcraft_kernel::profile::capture(|| check_pair(&job.a, &job.b, &job.names)); + Done { outcome, ms: started.elapsed().as_secs_f64() * 1000.0, kernel } } -fn check_pair(a: &Body, b: &Body, (na, nb): &(String, String)) -> (Outcome, Option) { +fn check_pair(a: &Body, b: &Body, (na, nb): &(String, String)) -> Outcome { let threshold = 1e-9 * a.size().max(1.0).powi(3); - // A pin a hair off the axis of its hole: the crescent the walls share, which the boolean - // can't intersect. - if let Some(o) = solidcraft_kernel::coaxial_overlap(a, b) { - if o.volume > threshold { - let hit = json!({"a": na, "b": nb, "volume_mm3": o.volume, "area_mm2": o.area, "center": o.centroid, - "bbox": {"min": o.bbox.min, "max": o.bbox.max}, "near_coaxial": {"offset_mm": o.offset, "length_mm": o.length}}); - return (Outcome::Hit(hit), None); - } - return (Outcome::Clear, None); - } // A pair whose shared part can't be worked out is reported, not passed as clear. - let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(a, b, solidcraft_kernel::BoolOp::Intersect)); - let shared = match shared { - Ok(o) => o, - Err(e) => return (Outcome::Unchecked(e.to_string()), None), + let shared = match solidcraft_kernel::boolean(a, b, solidcraft_kernel::BoolOp::Intersect) { + Ok(Some(o)) => o, + Ok(None) => return Outcome::Clear, + Err(e) => return Outcome::Unchecked(e.to_string()), }; - let mut note = report.unverified(); - let pieces = match shared { - Some(o) => vec![o], - // A body in several pieces, one of them wholly inside the other body: the whole bodies' - // boolean can come out empty, so the pieces are intersected one by one. - None if a.shell_count() > 1 || b.shell_count() > 1 => match by_pieces(a, b) { - Ok((pieces, unverified)) => { - note = note.or(unverified); - pieces - } - Err(e) => return (Outcome::Unchecked(e), note), - }, - None => return (Outcome::Clear, note), + let m = match solidcraft_kernel::measure_mass(&shared) { + Ok(m) => m, + Err(e) => return Outcome::Unchecked(e.to_string()), }; - // The shared parts measured together: volumes and areas add, the centre is the volumes'. - let mut measured = Vec::new(); - for o in &pieces { - match solidcraft_kernel::measure_mass(o) { - Ok(m) => measured.push(m), - Err(e) => return (Outcome::Unchecked(e.to_string()), note), - } + if m.volume > threshold { + let hit = json!({"a": na, "b": nb, "volume_mm3": m.volume, "area_mm2": m.area, "center": m.centroid, + "bbox": {"min": m.bbox.min, "max": m.bbox.max}}); + return Outcome::Hit(hit); } - let volume: f64 = measured.iter().map(|m| m.volume).sum(); - if volume > threshold { - let area: f64 = measured.iter().map(|m| m.area).sum(); - let bbox = measured.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bbox)); - let center = match measured.as_slice() { - [m] => m.centroid, - _ => measured.iter().fold(Vec3::ZERO, |c, m| c + m.centroid * m.volume) / volume, - }; - let hit = json!({"a": na, "b": nb, "volume_mm3": volume, "area_mm2": area, "center": center, "bbox": {"min": bbox.min, "max": bbox.max}}); - return (Outcome::Hit(hit), note); - } - (Outcome::Clear, note) -} - -/// Most pairs of pieces [`by_pieces`] intersects. -const MAX_PIECE_PAIRS: usize = 256; - -/// The shared parts of two bodies, a piece of each at a time, and why any of them is unverified. -fn by_pieces(a: &Body, b: &Body) -> std::result::Result<(Vec, Option), String> { - let (la, lb) = (a.lumps().map_err(|e| e.to_string())?, b.lumps().map_err(|e| e.to_string())?); - if la.len() < 2 && lb.len() < 2 { - return Ok((Vec::new(), None)); - } - if la.len().saturating_mul(lb.len()) > MAX_PIECE_PAIRS { - return Err(format!("not checked: {} by {} pieces are more than {MAX_PIECE_PAIRS} pairs of pieces", la.len(), lb.len())); - } - let (mut out, mut note) = (Vec::new(), None); - for x in &la { - for y in &lb { - let (r, report) = - solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(x, y, solidcraft_kernel::BoolOp::Intersect)); - note = note.or(report.unverified()); - if let Some(o) = r.map_err(|e| e.to_string())? { - out.push(o); - } - } - } - Ok((out, note)) + Outcome::Clear } /// Each job's answer (in pair order, with the pair's names; `None`: not finished within @@ -385,13 +325,12 @@ fn run_ordered(jobs: Vec, budget: std::time::Duration) -> (Vec let mut threads = 0; for _ in 0..want { let (jobs, next, stop, tx) = (jobs.clone(), next.clone(), stop.clone(), tx.clone()); - let spawned = std::thread::Builder::new().name("solidcraft-interference".into()).spawn(move || { + let spawned = solidcraft_kernel::kernel_thread("solidcraft-interference").spawn(move || { while !stop.load(Ordering::Relaxed) { let k = next.fetch_add(1, Ordering::Relaxed); let Some(job) = jobs.get(k) else { break }; let done = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(job))).unwrap_or_else(|_| Done { outcome: Outcome::Unchecked("internal error while checking this pair".into()), - note: None, ms: 0.0, kernel: KernelTimes::default(), }); diff --git a/crates/engine/src/cmd/interference_tests.rs b/crates/engine/src/cmd/interference_tests.rs index 2be9c0383..d7204a223 100644 --- a/crates/engine/src/cmd/interference_tests.rs +++ b/crates/engine/src/cmd/interference_tests.rs @@ -70,7 +70,7 @@ fn a_piece_of_a_body_inside_another_is_still_found() { run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Block"})); run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [5, 5, 5], "operation": "new", "body_name": "Pieces"})); run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [30, 5, 5], "operation": "join", "targets": ["Pieces"]})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let pieces = st.bodies.iter().find(|b| b.name == "Pieces").map(|b| b.body.shell_count()); assert_eq!(pieces, Some(2), "the two cubes are one body in two pieces"); let i = run(&mut s, "inspect.interference", json!({})); @@ -122,7 +122,7 @@ pub(super) fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); } let _ = std::fs::remove_dir_all(&dir); - s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() + s.world_state().unwrap().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() } /// #3249: mesh bodies (STL, 3MF, OBJ imports) are not intersected, but they used to vanish from @@ -156,3 +156,24 @@ fn mesh_bodies_are_listed_as_unchecked_not_dropped() { assert_eq!(i["checked"], 1, "{i}"); assert_eq!(i["unchecked"][0]["a"].as_str(), Some(meshes[0].as_str()), "{i}"); } + +/// A name that is no body is refused, as inspect.clearance refuses it. Dropped, a misspelled or +/// wrongly cased body was never checked and two overlapping cubes read as no interference (#9740). +#[test] +fn a_body_name_that_is_no_body_is_refused() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [9, 0, 0], "operation": "new_body", "body_name": "B"})); + let i = run(&mut s, "inspect.interference", json!({"bodies": ["A", "B"]})); + assert_eq!((&i["count"], &i["checked"]), (&json!(1), &json!(2)), "{i}"); + for (names, says) in + [(json!(["A", "Typo"]), "no body `Typo`"), (json!(["A", "b"]), "no body `b`; did you mean `B`?"), (json!(["Typo"]), "no body `Typo`")] + { + let e = s.execute("inspect.interference", &json!({"bodies": names})).map(|r| r.to_string()).unwrap_or_else(|e| e.to_string()); + assert!(e.contains(says), "{names}: {e}"); + } + assert!( + !s.execute("inspect.interference", &json!({"bodies": ["Typo"]})).unwrap_err().to_string().contains("did you mean"), + "nothing is near `Typo`" + ); +} diff --git a/crates/engine/src/cmd/join_pieces.rs b/crates/engine/src/cmd/join_pieces.rs index ab773f6fe..cbb3ce9ae 100644 --- a/crates/engine/src/cmd/join_pieces.rs +++ b/crates/engine/src/cmd/join_pieces.rs @@ -3,6 +3,7 @@ //! result OK makes, and with the warning a Join apart gets (#4434). use serde_json::Value; +use solidcraft_geom::prelude::*; use crate::Session; @@ -71,7 +72,9 @@ impl crate::Ahead { if inside && adds_nothing(&before, &state, &tools) { return (Some(Addition::Inside), None); } - after.world_state().warm_display(); + if let Ok(world) = after.world_state() { + world.warm_display(); + } (Some(Addition::Joins), Some(crate::Evaluated(after.model))) } } diff --git a/crates/engine/src/cmd/joint_edge_tests.rs b/crates/engine/src/cmd/joint_edge_tests.rs index e47170382..00721f911 100644 --- a/crates/engine/src/cmd/joint_edge_tests.rs +++ b/crates/engine/src/cmd/joint_edge_tests.rs @@ -1,7 +1,8 @@ //! Joint origins on an edge of a face (its middle, or a corner) follow the face as it changes size. use serde_json::json; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{place, run}; use crate::Session; diff --git a/crates/engine/src/cmd/joint_frames_tests.rs b/crates/engine/src/cmd/joint_frames_tests.rs index c0d2cc06b..28b8ef70c 100644 --- a/crates/engine/src/cmd/joint_frames_tests.rs +++ b/crates/engine/src/cmd/joint_frames_tests.rs @@ -1,7 +1,8 @@ //! A joint origin on a face or a hole keeps its turn about z as the geometry tilts. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{occ, run}; use crate::Session; diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 0608885f1..ee8a3db87 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -3,18 +3,24 @@ //! joint graph and moves the occurrences it places; the session re-solves after any edit too, //! so joints follow the geometry their origins snap to. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use solidcraft_doc::expr::Kind; +use solidcore_record::Vec3; +use solidcraft_doc::expr::{self, Kind}; use solidcraft_doc::joints::cam::{self, Cam, CamProfile, Follower}; use solidcraft_doc::joints::{self, Coupling, Joint, JointExprs, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap, XRef}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcraft_geom::Aabb3; use super::CommandSpec; use crate::params::{bad, bool_, num, str_, vec3}; +use crate::schema::joints::EditJointResult; +use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; +const EDIT_CONTRACT: TypedContract = TypedContract::new(); + #[path = "joints_inspect.rs"] mod inspect; @@ -26,7 +32,8 @@ pub static COMMANDS: &[CommandSpec] = &[ "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball, or a relation: parallel|perpendicular|angle|point_on_plane|point_on_line|line_on_plane \ (ties only some directions or points, made where the parts are; several between two parts add up); a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"\"; z? for a point, end?, x? as joint.origin} | origin name); \ values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \ - b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \ + b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z and x stay as they are; \ + a point origin without x takes its x from z, so give x on both, or use joint.as_built, to keep a turned part where it is); \ offset?: mm or an expression; angle?: deg or an expression (an angle relation's tilt from mated; for other joints the default \ is none, or a half turn where that turns b less, so faces that already meet stay as they are); name?; quiet?: bool (leave \ out dof and fixed). An expression (text) is \ @@ -41,9 +48,11 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("joint.drive", "Drive Joints", drive).at("SOLID", "ASSEMBLE").icon("drive").params( "joint: id|name; value | values: [angles in deg or expressions, distances] (values not given keep theirs; a value driven drops the expression joint.create gave it; clamped to the limits; the other joints of a \ closed loop follow, and the motion stops where the loop can no longer close → stopped_by_loop); quiet?: bool (leave out dof \ - and fixed) → values: [{name, value, unit: deg|mm, limits}] as joint.list gives them; moved: whether any occurrence moved; \ - reason: why the joint can move nothing (suppressed, its origins lost, or its chain joined to nothing grounded → unconnected: \ - the occurrence named); index?: zero-based coordinate to drive with value (the other coordinates follow); continuous?: bool (drag frame, suppress UI echo)", + and fixed) → values: [{name, value, unit: deg|mm, limits}] as joint.list gives them; requested: the values asked for, in the same form; \ + held: [{name, requested, value, unit, why}] for each driven value that ended up elsewhere (a motion link sets it, as a screw's \ + travel follows its turn; a limit; contact; a closed loop); moved: whether any occurrence moved; \ + reason: why the joint can move nothing (suppressed: nothing is stored; its origins lost; its chain joined to nothing grounded → unconnected: \ + the occurrence named; or, when nothing moved, the first held value's why); index?: zero-based coordinate to drive with value (the other coordinates follow); continuous?: bool (drag frame, suppress UI echo)", ), CommandSpec::new("joint.reach", "Reach Point", reach).icon("reach").params( "occurrence: id|name; point: [x,y,z] (where its point goes, world); at?: [x,y,z] (its point, in the world where it is now; default: the centre of its bodies' box); z?: [x,y,z] (the way its axis then points); axis?: [x,y,z] (that axis, in the world now; default: its own z); joints?: [ids or names] (only these move toward the point; the other joints of a closed loop they are in follow); quiet?: bool; continuous?: bool (a frame of a drag: the answer says continuous, and the app's command line doesn't echo it). Moves the values of the joints on its chain from where they are to the nearest pose, within their limits, through motion links, keeping closed loops closed as joint.drive does (contact sets are not checked) → reached; error_mm (and error_deg with z): how close it got; point: where its point is; values: [{joint, name, values}] of the joints that moved, as joint.list gives them; moved; stopped_by_limit: [{joint, value, limit: min|max}]: the limits it rests on short of the point; stopped_by_loop: {joint}: the closed loop that stopped it (its chain alone gets closer); reason: why nothing can move", @@ -75,9 +84,16 @@ pub static COMMANDS: &[CommandSpec] = &[ "a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is, also when the link replaces another (at the current pose)", ), CommandSpec::new("joint.limits", "Joint Limits", limits).icon("joint").params("joint; index?: value index (default 0); min?, max? (omit both to clear)"), - CommandSpec::new("joint.edit", "Edit Joint", edit) + CommandSpec::new("joint.edit", "Edit Joint", crate::checked!("joint.edit", edit)) .icon("edit") - .params("joint; type?, flip?, offset?, angle? (a number, or an expression the joint then follows), suppressed?, name?"), + .contract(&EDIT_CONTRACT) + .output(output_schema_for::) + .params( + "joint; a?, b?: joint origins as joint.create takes them (a side left out keeps its place; the two must stay on different occurrences); \ + type?, flip?, offset?, angle? (a number, or an expression the joint then follows), suppressed?, name?; the joint re-solves, keeping \ + its limits and expressions (a relation's values start again where its parts are); an edit that places it again (not a rename alone) \ + meets a loop it closes as joint.create does, turning an angle a half turn where only that meets it", + ), CommandSpec::new("joint.delete", "Delete Joint", delete).icon("delete").params("joint: id|name (or origin: name, link: index)"), CommandSpec::new("joint.list", "List Joints", list).icon("list").noundo().params( "→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \ @@ -94,7 +110,7 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"), CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params( - "bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: [{a, b, reason}], the pairs that could not be checked, with the reason, and each mesh body (STL, 3MF or OBJ import: not intersected) as {a: name, b: null, reason: \"mesh body: not checked\"}, so count: 0 is not read as no overlap (checked counts the solid bodies). Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms", + "bodies?: [names] (default: all, in world placement; a name that is no body is refused); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre; unchecked: [{a, b, reason}], the pairs that could not be checked, with the reason, and each mesh body (STL, 3MF or OBJ import: not intersected) as {a: name, b: null, reason: \"mesh body: not checked\"}, so count: 0 is not read as no overlap (checked counts the solid bodies). Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms", ), ]; @@ -219,7 +235,8 @@ fn sol_json(sol: &joints::Solution, p: &Value) -> Value { } /// A joint's values as `joint.list` gives them: degrees for angles, mm for distances, each with -/// its name and limits. +/// its name and limits. The numbers are rounded for reading (#10747); the joint keeps full +/// precision. pub(crate) fn named_values(j: &Joint, q: &[f64]) -> Vec { j.kind .dofs() @@ -227,8 +244,8 @@ pub(crate) fn named_values(j: &Joint, q: &[f64]) -> Vec { .enumerate() .map(|(i, n)| { let (v, angle) = (q.get(i).copied().unwrap_or(0.0), j.kind.is_angle(i)); - json!({"name": n, "value": if angle { v.to_degrees() } else { v }, "unit": if angle { "deg" } else { "mm" }, - "limits": j.limits.get(i).copied().flatten().map(|(a, b)| if angle { [a.to_degrees(), b.to_degrees()] } else { [a, b] })}) + json!({"name": n, "value": expr::round_reported(if angle { v.to_degrees() } else { v }), "unit": if angle { "deg" } else { "mm" }, + "limits": j.limits.get(i).copied().flatten().map(|(a, b)| if angle { [expr::round_reported(a.to_degrees()), expr::round_reported(b.to_degrees())] } else { [expr::round_reported(a), expr::round_reported(b)] })}) }) .collect() } @@ -481,7 +498,7 @@ fn same_frame(s: &Session, o: &JointOrigin, at: Vec3, z: Vec3) -> bool { const MAX_FACE_NAME: usize = 16_384; /// The component an occurrence places (0 for the root, or an unknown occurrence). -fn component_of(s: &Session, occurrence: u64) -> u64 { +pub(crate) fn component_of(s: &Session, occurrence: u64) -> u64 { if occurrence == 0 { 0 } else { s.doc.occurrences.iter().find(|o| o.id == occurrence).map_or(0, |o| o.component) } } @@ -671,18 +688,59 @@ fn limits_param(s: &Session, p: &Value, kind: JointKind, cmd: &str) -> Result Result<()> { + if a.occurrence == b.occurrence { + return Err(bad( + cmd, + "a joint needs two different occurrences: both origins are on one component; give each part a component of its own first \ + (component.from_bodies)", + )); + } + Ok(()) +} + +/// A path already joins the two sides, including paths through grounded occurrences. +fn closes_loop(s: &Session, j: &Joint) -> bool { + let mut at: BTreeMap> = BTreeMap::new(); + for joint in s.doc.assembly.joints.iter().filter(|j| !j.suppressed).take(joints::MAX_JOINTS) { + at.entry(joint.a.occurrence).or_default().push(joint.b.occurrence); + at.entry(joint.b.occurrence).or_default().push(joint.a.occurrence); + } + // The solver fixes the root and every grounded occurrence in the same world frame. + for o in s.doc.occurrences.iter().filter(|o| o.grounded) { + at.entry(0).or_default().push(o.id); + at.entry(o.id).or_default().push(0); + } + let mut seen = BTreeSet::from([j.a.occurrence]); + let mut pending = vec![j.a.occurrence]; + while let Some(occ) = pending.pop() { + if occ == j.b.occurrence { + return true; + } + for other in at.get(&occ).into_iter().flatten() { + if seen.insert(*other) { + pending.push(*other); + } + } + } + false +} + fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result { if s.doc.assembly.joints.len() >= 10_000 { return Err(EngineError::Other("too many joints".into())); } - // Several parts as bodies of one component (a multi-body STEP import, #1239): say how to - // get two components. - if j.a.occurrence == j.b.occurrence { - return Err(bad( - "joint.create", - "a joint needs two different occurrences: both origins are on one component; give each part a component of its own first \ - (component.from_bodies)", - )); + check_sides(&j.a, &j.b, "joint.create")?; + // Relations and loop-closing typed joints start where their parts are. A typed joint in + // an open chain keeps its usual initial values; explicitly supplied values also keep theirs. + if p.get("values").is_none() + && p.get("value").is_none() + && (j.kind.is_relation() || closes_loop(s, &j)) + && let Some(q) = joints::relation_values(&s.doc, &s.model.state(), &j) + { + j.values = q; } // It starts at its values inside its limits. A value moved to a limit moves the part as it // is joined, which the answer says. @@ -713,7 +771,10 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result { // A new joint starts shown, even if a stale visibility entry came from an older design. s.visibility.hidden_joints.retain(|h| *h != id); s.doc_mut().assembly.joints.push(j); - let sol = resolve(s); + let mut sol = resolve(s); + if sol.conflicts.iter().any(|(c, ..)| *c == id) && close_by_half_turn(s, id, &sol) { + sol = resolve(s); + } let mut out = sol_json(&sol, p); out["joint"] = json!(id); out["name"] = json!(name); @@ -723,6 +784,96 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result { Ok(out) } +/// Sets of angle values a new loop-closing joint tries a half turn round, at most. +const HALF_TURN_TRIALS: usize = 16; + +/// A new joint that closes a loop is met from where the loop's parts sit. Where its parts only +/// meet with one of them turned a half turn about a joint on the way between them (a second +/// planar joint mating two faces that point the same way, #10331), the loop solve starts at a +/// pose turned exactly away and sees no way round, and the joint is left as a conflict. As the +/// first joint of a chain moves its part into place, turn the new joint's own angle, each angle +/// on the shortest joint path between its two parts, or one of each, a half turn, and keep the +/// first that meets it with no new conflict or error elsewhere than `before` had (stored, for +/// the caller's resolve). False, and nothing changed, when none does. Values a motion link or an +/// expression sets, and turns their limits stop short, are left alone. `joint.edit` does the same +/// for a joint it places again (#9687). +fn close_by_half_turn(s: &mut Session, id: u64, before: &joints::Solution) -> bool { + let asm = &s.doc.assembly; + let Some(new) = asm.joints.iter().find(|j| j.id == id) else { return false }; + let (from, to) = (new.a.occurrence, new.b.occurrence); + // Breadth first over the other joints, from A's occurrence to B's. + let mut reached: BTreeMap> = BTreeMap::from([(from, None)]); + let mut frontier = vec![from]; + while !frontier.is_empty() && !reached.contains_key(&to) { + let mut next = Vec::new(); + for at in frontier { + for (k, j) in asm.joints.iter().enumerate().filter(|(_, j)| j.id != id && !j.suppressed) { + let other = if j.a.occurrence == at { + j.b.occurrence + } else if j.b.occurrence == at { + j.a.occurrence + } else { + continue; + }; + if let std::collections::btree_map::Entry::Vacant(e) = reached.entry(other) { + e.insert(Some(k)); + next.push(other); + } + } + } + frontier = next; + } + let mut path = Vec::new(); + let mut at = to; + while let Some(Some(k)) = reached.get(&at).copied() { + let Some(j) = asm.joints.get(k) else { break }; + path.push(k); + at = if j.a.occurrence == at { j.b.occurrence } else { j.a.occurrence }; + } + let linked: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect(); + // The angle values that may turn: on the path, and the new joint's own (turned exactly + // away about its axis, its own value sees no way round either). + let angles = |ks: &[usize]| -> Vec<(usize, usize)> { + ks.iter() + .filter_map(|k| asm.joints.get(*k).map(|j| (*k, j))) + .flat_map(|(k, j)| (0..j.kind.dofs().len()).filter(move |i| j.kind.is_angle(*i)).map(move |i| (k, j, i))) + .filter(|(_, j, i)| j.exprs.value(*i).is_none() && !linked.contains(&(j.id, *i))) + .map(|(k, _, i)| (k, i)) + .collect() + }; + let own = asm.joints.iter().position(|j| j.id == id).map(|k| angles(&[k])).unwrap_or_default(); + let mut trials: Vec> = own.iter().map(|v| vec![*v]).collect(); + for v in angles(&path) { + trials.push(vec![v]); + trials.extend(own.iter().map(|w| vec![v, *w])); + } + trials.truncate(HALF_TURN_TRIALS); + let st = s.model.state(); + 'trial: for turns in trials { + let mut doc = (*s.doc).clone(); + for (k, i) in turns { + let Some(j) = doc.assembly.joints.get_mut(k) else { continue 'trial }; + j.values.resize(j.kind.dofs().len(), 0.0); + let Some(q) = j.values.get(i).copied() else { continue 'trial }; + let mut turned = j.values.clone(); + if let Some(slot) = turned.get_mut(i) { + *slot = q + std::f64::consts::PI; + } + joints::clamp(j, &mut turned); + if turned.get(i).is_none_or(|v| (v - q - std::f64::consts::PI).abs() > 1e-9) { + continue 'trial; + } + j.values = turned; + } + let sol = joints::solve_holding_with_analysis(&doc, &st, &BTreeMap::new(), joints::Analysis::Placement); + if sol.conflicts.len() < before.conflicts.len() && !sol.conflicts.iter().any(|(c, ..)| *c == id) && sol.errors.len() <= before.errors.len() { + s.doc_mut().assembly.joints = doc.assembly.joints; + return true; + } + } + false +} + fn joint_origin(s: &mut Session, p: &Value) -> Result { let cmd = "joint.origin"; let origin = origin_param(s, Some(p), cmd)?; @@ -780,13 +931,6 @@ fn joint(s: &mut Session, p: &Value) -> Result { suppressed: false, exprs: JointExprs { offset: typed(p.get("offset")), angle: typed(p.get("angle")), values: value_exprs(p) }, }; - // A relation given no values starts from where its parts are: B moves no further than it must. - if p.get("values").is_none() - && p.get("value").is_none() - && let Some(q) = joints::relation_values(&s.doc, &s.model.state(), &j) - { - j.values = q; - } // No angle given: B keeps its turn about the joint's axis where a half turn would otherwise // come only from how its origin's x was chosen. (An angle relation's angle is its tilt.) if angle.is_none() && !j.kind.is_relation() { @@ -882,32 +1026,43 @@ fn drive(s: &mut Session, p: &Value) -> Result { if p.get("values").is_none() && p.get("value").is_none() { return Err(bad(cmd, "give `value` or `values`")); } - let doc = s.doc_mut(); - let Some(j) = doc.assembly.joints.iter_mut().find(|j| j.id == id) else { return Err(bad(cmd, "joint")) }; // Values not given (after `value`'s first, or past the end of `values`) keep theirs. let given = match p.get("values") { Some(Value::Array(a)) => a.len(), _ => 1, }; + let joint = s.doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| bad(cmd, "joint"))?; if index.is_none() { for (i, v) in q.iter_mut().enumerate().skip(given) { - *v = j.values.get(i).copied().unwrap_or(*v); + *v = joint.values.get(i).copied().unwrap_or(*v); } } - joints::clamp(j, &mut q); - // Moved as far toward `q` as contact sets and closed loops allow. Values left out of - // `values` are not driven: in a closed loop they follow. - // Driving moves the joint by hand: the values driven drop their expressions (an expression - // given here is worked out once, as contact or a loop may stop the motion short of it). - if let Some(index) = index { - j.exprs.set_value(index, None); + // What was asked for, before limits and motion links have their say. + let requested = q.clone(); + let driven: Vec = match index { + Some(index) => vec![index], + None => (0..given.min(kind.dofs().len())).collect(), + }; + // A suppressed joint places nothing: a value stored now would move the part only when the + // joint is unsuppressed, and leave an undo step for a drive whose reply says nothing moved + // (#9742). A joint in a motion link still carries its value to the joints it drives. + let hold = joint.suppressed && !s.doc.assembly.links.iter().any(|l| l.a == id || l.b == id); + let before = super::motion::positions(s); + let r = if hold { + json!({"stopped_by_contact": null, "stopped_by_loop": null}) } else { - for i in 0..given.min(kind.dofs().len()) { + let doc = s.doc_mut(); + let Some(j) = doc.assembly.joints.iter_mut().find(|j| j.id == id) else { return Err(bad(cmd, "joint")) }; + joints::clamp(j, &mut q); + // Moved as far toward `q` as contact sets and closed loops allow. Values left out of + // `values` are not driven: in a closed loop they follow. + // Driving moves the joint by hand: the values driven drop their expressions (an expression + // given here is worked out once, as contact or a loop may stop the motion short of it). + for &i in &driven { j.exprs.set_value(i, None); } - } - let before = super::motion::positions(s); - let r = if let Some(index) = index { super::motion::drive_joint_index(s, id, q, index)? } else { super::motion::drive_joint(s, id, q, given)? }; + if let Some(index) = index { super::motion::drive_joint_index(s, id, q, index)? } else { super::motion::drive_joint(s, id, q, given)? } + }; let sol = solution(s, &BTreeMap::new(), response_analysis(p)); let mut out = sol_json(&sol, p); out["joint"] = json!(id); @@ -917,7 +1072,20 @@ fn drive(s: &mut Session, p: &Value) -> Result { } out["stopped_by_contact"] = r["stopped_by_contact"].clone(); out["stopped_by_loop"] = r["stopped_by_loop"].clone(); - out["moved"] = json!(super::motion::moved(&before, &super::motion::positions(s)).next().is_some()); + let moved = super::motion::moved(&before, &super::motion::positions(s)).next().is_some(); + out["moved"] = json!(moved); + if let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == id) { + out["requested"] = json!(named_values(j, &requested)); + let held = if hold { Vec::new() } else { held_values(s, j, &requested, &driven, &r) }; + if let Some(first) = held.first() + && !moved + { + out["reason"] = first["why"].clone(); + } + if !held.is_empty() { + out["held"] = json!(held); + } + } if let Some((why, unconnected)) = cannot_move(s, &sol, id) { out["reason"] = json!(why); if let Some(o) = unconnected { @@ -927,6 +1095,52 @@ fn drive(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The driven values of `j` that ended up other than `requested`, each with why: a motion link +/// sets it from another coordinate (a screw's travel follows its turn), a limit holds it, or +/// contact or a closed loop stopped the motion short. Degrees and mm, as `values` (#9742). +fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &Value) -> Vec { + let now = joints::joint_values(&s.doc.assembly).remove(&j.id).unwrap_or_else(|| j.values.clone()); + let names = j.kind.dofs(); + let mut out = Vec::new(); + for &i in driven { + let (Some(&want), Some(&got)) = (requested.get(i), now.get(i)) else { continue }; + if (want - got).abs() <= 1e-9 * want.abs().max(got.abs()).max(1.0) { + continue; + } + let angle = j.kind.is_angle(i); + let shown = |v: f64| expr::round_reported(if angle { v.to_degrees() } else { v }); + let name = names.get(i).copied().unwrap_or("value"); + let why = if let Some(l) = s.doc.assembly.links.iter().find(|l| l.b == j.id && l.ib == i) { + let coupling = match &l.coupling { + Some(joints::Coupling::Gear { .. }) => " (gears)", + Some(joints::Coupling::RackPinion { .. }) => " (rack and pinion)", + Some(joints::Coupling::Screw { .. }) => " (screw)", + Some(joints::Coupling::Cam(_)) => " (cam)", + None => "", + }; + let from = s.doc.assembly.joints.iter().find(|o| o.id == l.a); + let coordinate = from.and_then(|o| o.kind.dofs().get(l.ia).copied()).unwrap_or("value"); + if l.a == j.id { + format!("{name} follows its {coordinate} through a motion link{coupling}") + } else { + format!("{name} follows {}'s {coordinate} through a motion link{coupling}", from.map_or("another joint", |o| o.name.as_str())) + } + } else if let Some(Some((lo, hi))) = j.limits.get(i) + && (want < lo.min(*hi) || want > hi.max(*lo)) + { + format!("{name} is held to its limits, {} to {} {}", shown(lo.min(*hi)), shown(hi.max(*lo)), if angle { "deg" } else { "mm" }) + } else if r["stopped_by_contact"].is_object() { + format!("{name} stopped at contact") + } else if r["stopped_by_loop"].is_object() { + format!("{name} stopped where a closed loop can no longer close") + } else { + continue; + }; + out.push(json!({"name": name, "requested": shown(want), "value": shown(got), "unit": if angle { "deg" } else { "mm" }, "why": why})); + } + out +} + /// Joints `joint.reach` takes at most in `joints`. const MAX_REACH_JOINTS: usize = 1000; @@ -1366,8 +1580,22 @@ fn edit(s: &mut Session, p: &Value) -> Result { Some(v) => Some(value(s, v, true, cmd)?), None => None, }; + // The sides, read as joint.create reads them; a side left out keeps its place. + let a = p.get("a").map(|v| origin_param(s, Some(v), cmd)).transpose()?; + let b = p.get("b").map(|v| origin_param(s, Some(v), cmd)).transpose()?; + let sides = a.is_some() || b.is_some(); + if sides { + let j = s.doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| bad(cmd, "joint"))?; + check_sides(a.as_ref().unwrap_or(&j.a), b.as_ref().unwrap_or(&j.b), cmd)?; + } let doc = s.doc_mut(); let Some(j) = doc.assembly.joints.iter_mut().find(|j| j.id == id) else { return Err(bad(cmd, "joint")) }; + if let Some(a) = a { + j.a = a; + } + if let Some(b) = b { + j.b = b; + } if let Some(k) = kind { let was = j.kind; j.kind = k; @@ -1399,17 +1627,35 @@ fn edit(s: &mut Session, p: &Value) -> Result { if let Some(x) = bool_(p, "suppressed") { suppress_joints(s.doc_mut(), &[id], x); } + // A side moved without an angle turns B as joint.create would: the least turn from where it + // is now (a relation's angle is its tilt, which stays; an angle expression keeps driving it). + if sides + && p.get("angle").is_none() + && let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == id).filter(|j| !j.kind.is_relation() && j.exprs.angle.is_none()).cloned() + { + let turn = joints::least_turn_angle(&s.doc, &s.model.state(), &j); + if let Some(j) = s.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id) { + j.angle = turn; + } + } // A relation whose type, offset, tilt or flip changes starts again from where its parts are. - let reseat = kind.is_some() || offset.is_some() || angle.is_some() || p.get("flip").is_some(); + let reseat = kind.is_some() || offset.is_some() || angle.is_some() || p.get("flip").is_some() || sides; if reseat { - let edited = s.doc.assembly.joints.iter().find(|j| j.id == id).cloned(); + let edited = s.doc.assembly.joints.iter().find(|j| j.id == id).filter(|j| j.kind.is_relation()).cloned(); if let Some(q) = edited.and_then(|j| joints::relation_values(&s.doc, &s.model.state(), &j)) && let Some(j) = s.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id) { j.values = q; } } - let sol = resolve(s); + let mut sol = resolve(s); + // An edit that places the joint again (Edit Joint's OK, Unsuppress) meets a loop it closes as + // joint.create does: a joint saved as a conflict before create turned its part (#9687), or + // unsuppressed after its part was turned away, is met then. A rename alone moves nothing. + let placed = reseat || bool_(p, "suppressed") == Some(false); + if placed && sol.conflicts.iter().any(|(c, ..)| *c == id) && close_by_half_turn(s, id, &sol) { + sol = resolve(s); + } Ok(sol_json(&sol, p)) } diff --git a/crates/engine/src/cmd/joints_as_built_tests.rs b/crates/engine/src/cmd/joints_as_built_tests.rs index 9acd97e54..5fa016fa5 100644 --- a/crates/engine/src/cmd/joints_as_built_tests.rs +++ b/crates/engine/src/cmd/joints_as_built_tests.rs @@ -2,7 +2,8 @@ //! the design changes, instead of holding the frame where it was made. use serde_json::json; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{occ, place, run}; use crate::Session; diff --git a/crates/engine/src/cmd/joints_cam_tests.rs b/crates/engine/src/cmd/joints_cam_tests.rs index 3ed46a746..780426cd3 100644 --- a/crates/engine/src/cmd/joints_cam_tests.rs +++ b/crates/engine/src/cmd/joints_cam_tests.rs @@ -158,7 +158,9 @@ fn picked_edges_give_the_sketch_s_table() { s.doc.assembly.links.first().map(|l| (l.lift.clone(), l.offset)).unwrap_or_default() }; let (sketch, a) = table(json!({"sketch": "CamSketch"})); - let (edges, b) = table(json!({"edges": [[E + R, 0, 5]]})); + // Picked on the rim a quarter turn from where the extruded circle's seam meets it: a pick on + // that vertex could be either edge. + let (edges, b) = table(json!({"edges": [[E, R, 5]]})); assert_eq!((sketch.len(), edges.len()), (360, 360)); assert!(sketch.iter().zip(&edges).all(|(x, y)| close(*x, *y, 1e-3)) && close(a, b, 1e-3)); // A second disc of the cam's component touching it in the same plane is not part of its loop. @@ -171,7 +173,7 @@ fn picked_edges_give_the_sketch_s_table() { assert!(touching.len() == 360 && touching.iter().zip(&sketch).all(|(x, y)| close(*x, *y, 1e-3)), "{touching:?}"); let mut s = cam_on_base(); tappet(&mut s, 0.0, E + R); - run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E + R, 0, 5]]}})); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E, R, 5]]}})); assert!(matches!( s.doc.assembly.links.first().and_then(|l| l.coupling.clone()), Some(Coupling::Cam(c)) if matches!(&c.profile, CamProfile::Edges { names, .. } if names.first().is_some_and(|n| !n.is_empty())) diff --git a/crates/engine/src/cmd/joints_coupling_tests.rs b/crates/engine/src/cmd/joints_coupling_tests.rs index 9eba99aab..57e78995b 100644 --- a/crates/engine/src/cmd/joints_coupling_tests.rs +++ b/crates/engine/src/cmd/joints_coupling_tests.rs @@ -408,3 +408,24 @@ fn a_motion_link_takes_its_driven_joints_freedom_with_nothing_grounded() { } } } + +/// Rolling the marker back works a gear's ratio out from the faces as they were then, so the +/// editor's pinned model and its source differ in the link's ratio, and the edit still goes +/// through. +#[test] +fn an_editor_accepts_the_ratios_rolling_the_marker_works_out() { + let mut s = gear_train(); + let before = s.doc.features.len(); + // G1's wall moves out to a radius of 12, so the link's ratio goes from -0.5 to -0.6. + run(&mut s, "solid.offset_face", json!({"faces": [[10, 0, 2.5]], "distance": 2})); + let ratio = |s: &Session| s.doc.assembly.links.first().map(|l| l.ratio).unwrap_or(f64::NAN); + assert!(close_to(ratio(&s), -0.6), "{}", ratio(&s)); + let original = s.scratch(); + run(&mut s, "timeline.roll_to", json!({"position": before})); + let source = s.scratch(); + assert!(close_to(ratio(&source), -0.5), "before the offset, the pitch radius is 10: {}", ratio(&source)); + let prepared = s.scratch().compute_editor_commands(&[], &source, original).unwrap(); + s.accept_commands(prepared).unwrap(); + assert_eq!(s.doc.marker, None); + assert!(close_to(ratio(&s), -0.6), "{}", ratio(&s)); +} diff --git a/crates/engine/src/cmd/joints_exprs_tests.rs b/crates/engine/src/cmd/joints_exprs_tests.rs index d3cdfa05b..a8d95531c 100644 --- a/crates/engine/src/cmd/joints_exprs_tests.rs +++ b/crates/engine/src/cmd/joints_exprs_tests.rs @@ -1,7 +1,8 @@ //! Joints whose offset, angle or values are typed as expressions follow the parameters they name. use serde_json::json; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{occ, place, run}; use crate::Session; diff --git a/crates/engine/src/cmd/joints_face_tests.rs b/crates/engine/src/cmd/joints_face_tests.rs index 181e532f6..f461d89ac 100644 --- a/crates/engine/src/cmd/joints_face_tests.rs +++ b/crates/engine/src/cmd/joints_face_tests.rs @@ -2,8 +2,9 @@ //! side and turned the same way, as the design's parameters change. use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::joints::{Snap, XRef}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{occ, place, run}; use crate::Session; diff --git a/crates/engine/src/cmd/joints_point_x_tests.rs b/crates/engine/src/cmd/joints_point_x_tests.rs index c74b0b8bd..b6a09b646 100644 --- a/crates/engine/src/cmd/joints_point_x_tests.rs +++ b/crates/engine/src/cmd/joints_point_x_tests.rs @@ -2,7 +2,8 @@ //! and x meet as they are, whichever way their parts are turned. use serde_json::json; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{occ, place, run}; use crate::Session; diff --git a/crates/engine/src/cmd/joints_reach_tests.rs b/crates/engine/src/cmd/joints_reach_tests.rs index d9003e756..c1fcb3314 100644 --- a/crates/engine/src/cmd/joints_reach_tests.rs +++ b/crates/engine/src/cmd/joints_reach_tests.rs @@ -2,7 +2,8 @@ //! out of reach, limits, and a four-bar reached through its rocker. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{four_bar, meet, occ, part, pin, place, run}; use crate::Session; diff --git a/crates/engine/src/cmd/joints_relations_tests.rs b/crates/engine/src/cmd/joints_relations_tests.rs index e858ea0f2..176f02455 100644 --- a/crates/engine/src/cmd/joints_relations_tests.rs +++ b/crates/engine/src/cmd/joints_relations_tests.rs @@ -3,7 +3,8 @@ //! parts are, and they keep holding as the parts change size. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{occ, place, run}; use crate::Session; @@ -60,6 +61,43 @@ fn clean(r: &Value) -> bool { r["conflicts"] == json!([]) && r["errors"] == json!([]) } +#[test] +fn closing_planar_joint_starts_from_the_current_placement() { + let mut s = Session::default(); + for name in ["Base", "Part"] { + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 6})); + run(&mut s, "component.activate", json!({"component": "root"})); + } + let base = occ(&s, "Base"); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + let r = run( + &mut s, + "joint.create", + json!({"type": "planar", "name": "First", "flip": true, "angle": 0, + "a": {"occurrence": "Base", "point": [0, 0, 0], "x": [1, 0, 0]}, + "b": {"occurrence": "Part", "point": [0, 0, 0], "x": [1, 0, 0]}, "values": [50, 30, 120]}), + ); + assert!(clean(&r), "{r}"); + // Check a frame, so a turn as well as a translation is observable. + let points = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z]; + let before = points.map(|p| place(&s, "Part", p)); + let at = before[0]; + let x = before[1] - at; + let r = run( + &mut s, + "joint.create", + json!({"type": "planar", "name": "Closing", "flip": true, "angle": 0, + "a": {"occurrence": "Base", "point": [0, 0, 0], "x": [1, 0, 0]}, + "b": {"occurrence": "Part", "point": [at.x, at.y, at.z], "x": [x.x, x.y, x.z]}}), + ); + assert!(clean(&r), "{r}"); + for (p, want) in points.into_iter().zip(before) { + let got = place(&s, "Part", p); + assert!(near(got, want, 1e-6), "{p:?}: {got:?}, expected {want:?}"); + } +} + #[test] fn stacked_relations_place_a_part_and_follow_the_panel() { let mut s = panel(); diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 6bf63d80d..bfe07b643 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -1,7 +1,8 @@ +use solidcraft_geom::prelude::*; use std::f64::consts::FRAC_PI_2; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -238,21 +239,40 @@ fn interference_finds_a_peg_overlapping_a_small_rib() { assert!((lo[0].as_f64().unwrap_or(0.0) - 19.7).abs() < 1e-6 && (hi[0].as_f64().unwrap_or(0.0) - 19.85).abs() < 1e-6, "{i}"); } -/// An arc revolved up to a post ends on the post's wall, where the two bodies can't be -/// intersected: the pair is listed as unchecked instead of passing as clear. +/// A pair interference can't check is listed as unchecked, with its reason, instead of passing +/// as clear. Truck could not intersect an arc revolved up to a post's wall; SMLib does, exactly, +/// so the pair that can't be checked is now an imported mesh beside a solid. #[test] fn interference_lists_a_pair_it_could_not_check() { + // A quarter ring revolved round z through the post, brought in as an imported mesh (an STL + // of it): a mesh body has no exact surfaces to intersect, so its pair with the post is listed + // as not checked, with the reason, rather than read as clear. + let dir = std::env::temp_dir().join(format!("solidcraft-unchecked-pair-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let stl = dir.join("arc.stl"); + let mut source = Session::default(); + run(&mut source, "sketch.create", json!({"name": "Profile", "plane": "XZ"})); + run(&mut source, "sketch.rectangle.two_point", json!({"p0": [10, 0], "p1": [15, 5]})); + run(&mut source, "sketch.finish", json!({})); + run( + &mut source, + "solid.revolve", + json!({"sketch": "Profile", "axis": {"origin": [0, 0, 0], "dir": [0, 0, 1]}, "angle": "90 deg", "body_name": "Arc"}), + ); + run(&mut source, "file.export", json!({"path": stl.to_string_lossy()})); let mut s = Session::default(); run(&mut s, "solid.cylinder", json!({"base": [0, 14, -5], "radius": 4, "height": 15, "body_name": "Post"})); - run(&mut s, "sketch.create", json!({"name": "Profile", "plane": "XZ"})); - run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 0], "p1": [15, 5]})); - run(&mut s, "sketch.finish", json!({})); - run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"origin": [0, 0, 0], "dir": [0, 0, 1]}, "to": [4, 14, 2], "body_name": "Arc"})); + run(&mut s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); + let _ = std::fs::remove_dir_all(&dir); + let mesh: Vec = s.world_state().unwrap().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect(); + assert_eq!(mesh.len(), 1, "{mesh:?}"); let i = run(&mut s, "inspect.interference", json!({})); assert_eq!(i["count"], 0, "{i}"); let unchecked = i["unchecked"].as_array().cloned().unwrap_or_default(); assert_eq!(unchecked.len(), 1, "{i}"); - assert!(unchecked[0]["reason"].as_str().is_some_and(|r| r.starts_with("not verified") && !r.contains("displacement")), "{i}"); + assert_eq!(unchecked[0]["a"].as_str(), mesh.first().map(String::as_str), "{i}"); + assert_eq!(unchecked[0]["reason"], "mesh body: not checked", "{i}"); // Bodies that are clear of each other, or overlap plainly, leave the list empty. let mut s = two_cubes(); let i = run(&mut s, "inspect.interference", json!({})); @@ -304,6 +324,114 @@ fn faces_mate_by_default() { assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 10.0)), Vec3::new(5.0, 5.0, 0.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 10.0))); } +/// Edit Joint takes new sides as joint.create does: the joint moves its attachment to them, and +/// keeps its limits, its drive and the expression its offset follows. +#[test] +fn edit_moves_a_side_and_keeps_limits_and_expressions() { + let mut s = two_cubes(); + run(&mut s, "parameters.add", json!({"name": "gap", "expression": "2 mm"})); + run( + &mut s, + "joint.create", + json!({"type": "slider", "name": "Rail", "offset": "gap", "limits": [[0, 10]], "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}), + ); + run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 4})); + // B's bottom centre rides 2 mm (the gap) plus 4 mm (the drive) above A's top centre. + assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 0.0)), Vec3::new(5.0, 5.0, 16.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 0.0))); + // B's top centre, where B is placed now, is the new side (`face` is a world point). + let top = place(&s, "B", Vec3::new(25.0, 5.0, 10.0)); + let r = run(&mut s, "joint.edit", json!({"joint": "Rail", "b": {"occurrence": "B", "face": [top.x, top.y, top.z]}})); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 10.0)), Vec3::new(5.0, 5.0, 16.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 10.0))); + let j = s.doc.assembly.joints.first().cloned().unwrap_or_else(|| panic!("no joint")); + assert_eq!(j.limits, vec![Some((0.0, 10.0))]); + assert_eq!(j.exprs.offset.as_deref(), Some("gap")); + assert_eq!(j.values, vec![4.0]); + assert_eq!(j.name, "Rail"); +} + +/// Sides left out of joint.edit stay as they are; the other parameters still change. +#[test] +fn omitted_sides_stay() { + let mut s = two_cubes(); + run(&mut s, "joint.create", json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}})); + let before = s.doc.assembly.joints[0].clone(); + run(&mut s, "joint.edit", json!({"joint": "Stack", "flip": true, "name": "Flipped"})); + let after = &s.doc.assembly.joints[0]; + assert_eq!((&after.a, &after.b), (&before.a, &before.b)); + assert!(after.flip && after.name == "Flipped"); +} + +/// One undo step puts the sides back, and the parts with them. +#[test] +fn one_undo_restores_the_old_sides() { + let mut s = two_cubes(); + run(&mut s, "joint.create", json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}})); + let before = s.doc.assembly.joints[0].clone(); + let top = place(&s, "B", Vec3::new(25.0, 5.0, 10.0)); + run(&mut s, "joint.edit", json!({"joint": "Stack", "b": {"occurrence": "B", "face": [top.x, top.y, top.z]}})); + assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 10.0)), Vec3::new(5.0, 5.0, 10.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 10.0))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.assembly.joints[0], before); + assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 0.0)), Vec3::new(5.0, 5.0, 10.0))); +} + +/// Moving a side re-solves the joint as joint.create would at the same pose: the turn B keeps +/// about the joint's axis follows its new origin, so B does not turn by a half turn (or any turn +/// a fresh create would not give). Both designs start from the same pose; one moves the side, +/// the other deletes the joint and creates it with the new sides. +#[test] +fn moving_a_side_places_the_part_as_create_would() { + let a_faces = [[5, 5, 10], [5, 0, 5], [5, 10, 5], [10, 5, 5], [0, 5, 5]]; + let b_faces = [[25, 5, 0], [25, 5, 10], [25, 0, 5], [25, 10, 5], [20, 5, 5], [30, 5, 5]]; + // A point of B off the axes of every face above. + let probe = |s: &Session| place(s, "B", Vec3::new(22.0, 3.0, 7.0)); + let mut differ = Vec::new(); + for a in a_faces { + for b in b_faces { + let mut edited = two_cubes(); + run(&mut edited, "joint.create", json!({"type": "rigid", "name": "J", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}})); + let mut created = Session::new(solidcraft_doc::Document::from_json(&edited.doc.to_json()).unwrap()); + // The new sides in world coordinates, where B is before the move. + let (aw, bw) = (Vec3::new(a[0] as f64, a[1] as f64, a[2] as f64), place(&edited, "B", Vec3::new(b[0] as f64, b[1] as f64, b[2] as f64))); + let side = |occurrence: &str, p: Vec3| json!({"occurrence": occurrence, "face": [p.x, p.y, p.z]}); + run(&mut edited, "joint.edit", json!({"joint": "J", "a": side("A", aw), "b": side("B", bw)})); + run(&mut created, "joint.delete", json!({"joint": "J"})); + run(&mut created, "joint.create", json!({"type": "rigid", "name": "J", "a": side("A", aw), "b": side("B", bw)})); + if !near(probe(&edited), probe(&created)) { + differ.push((a, b, probe(&edited), probe(&created))); + } + } + } + assert!(differ.is_empty(), "moved sides place B differently from create: {differ:?}"); +} + +/// A side that makes no joint is refused, and the joint is left as it was: a side on the other +/// side's component, a side that is not a joint origin, an unknown occurrence. +#[test] +fn an_invalid_side_is_refused_and_the_joint_is_kept() { + let mut s = two_cubes(); + run(&mut s, "joint.create", json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}})); + let before = s.doc.assembly.joints[0].clone(); + // A is a's occurrence and B is b's: each side is tried on the other's occurrence, and with + // the faults every side can have. + let cases = [ + ("a", json!({"occurrence": "B", "face": [25, 5, 10]})), + ("a", json!({"occurrence": "Nope", "face": [5, 5, 10]})), + ("a", json!({"occurrence": "A"})), + ("a", json!(5)), + ("b", json!({"occurrence": "A", "face": [5, 5, 0]})), + ("b", json!({"occurrence": "Nope", "face": [25, 5, 0]})), + ("b", json!({"occurrence": "B"})), + ("b", json!("NoSuchOrigin")), + ]; + for (key, side) in cases { + let r = s.execute("joint.edit", &json!({"joint": "Stack", key: side.clone()})); + assert!(r.is_err(), "{key}: {side} should be refused"); + assert_eq!(s.doc.assembly.joints[0], before, "{key}: {side} changed the joint"); + } +} + /// A move of a jointed part that the joint takes back: the model is evaluated for the /// placements the solve leaves, so a mirror of the part's body, made from the root, is where a /// fresh evaluation of the design puts it. The model was the one evaluated for the move before @@ -572,6 +700,197 @@ fn values_left_out_of_a_drive_follow_the_loop() { assert!(near(place(&s, "Plate", Vec3::ZERO), Vec3::new(10.0, 10.0, 0.0)), "{:?}", place(&s, "Plate", Vec3::ZERO)); } +/// Two boards 400 x 100 x 20 for #10331: yellow at the origin, grounded, and red 300 mm along Y. +fn boards() -> Session { + let mut s = Session::default(); + for (name, corner) in [("Yellow", [0.0, 0.0, 0.0]), ("Red", [0.0, 300.0, 0.0])] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name, "grounded": false})); + run(&mut s, "solid.box", json!({"length": 400, "width": 100, "height": 20, "corner": corner})); + } + let y = occ(&s, "Yellow"); + run(&mut s, "occurrence.ground", json!({"occurrence": y, "grounded": true})); + s +} + +/// #10331: a board on a planar joint, mated by a second planar joint at a face that points the +/// same way as the face it meets. It meets it turned a half turn on the first joint, the way the +/// first joint moves its part into place, in either pick order, and still slides along the +/// line the two planes share. Faces that can never meet stay a conflict, and nothing moves. +#[test] +fn a_second_planar_joint_turns_its_part_a_half_turn_to_meet() { + // Each case: the yellow face, the red face (world points once red lies on yellow, at + // x 0..400, y 0..100, z 20..40), and where red's origin ends up. + let cases = [ + ("fronts", [200.0, 0.0, 10.0], [200.0, 0.0, 30.0], Some(Vec3::new(400.0, 300.0, 20.0))), + ("ends", [0.0, 50.0, 10.0], [0.0, 50.0, 30.0], Some(Vec3::new(0.0, 400.0, 20.0))), + ("top against front", [200.0, 0.0, 10.0], [200.0, 50.0, 40.0], None), + ]; + for red_first in [false, true] { + for (case, yellow_face, red_face, expected) in cases { + let mut s = boards(); + let planar = |s: &mut Session, name: &str, yellow: [f64; 3], red: [f64; 3]| { + let (yellow, red) = (json!({"occurrence": "Yellow", "face": yellow}), json!({"occurrence": "Red", "face": red})); + let (a, b) = if red_first { (red, yellow) } else { (yellow, red) }; + run(s, "joint.create", json!({"type": "planar", "a": a, "b": b, "name": name})) + }; + let r = planar(&mut s, "Top", [200.0, 50.0, 20.0], [200.0, 350.0, 0.0]); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{case}: {r}"); + let on_top = place(&s, "Red", Vec3::ZERO); + let r = planar(&mut s, "Side", yellow_face, red_face); + let label = format!("{case}, red picked first: {red_first}"); + let Some(expected) = expected else { + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(1), "{label}: {r}"); + assert!(near(place(&s, "Red", Vec3::ZERO), on_top), "{label}: {:?}", place(&s, "Red", Vec3::ZERO)); + continue; + }; + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{label}: {r}"); + assert!(place(&s, "Red", Vec3::ZERO).dist(expected) < 1e-6, "{label}: {:?}", place(&s, "Red", Vec3::ZERO)); + assert_eq!(dof_of(&mut s, "Red"), 1, "{label}"); + let axes = solidcraft_doc::joints::motion_axes(&s.doc, &s.model.state(), occ(&s, "Red")); + assert!(axes.len() == 1 && !axes.iter().any(|a| a.angular), "{label}: {axes:?}"); + } + } +} + +/// #10331, with the board turned on the table first (the report's board was turned 40 degrees): +/// a second planar joint between any side of the yellow board and any side of the red one meets, +/// whichever turn the red board needs on the first joint to get there. +#[test] +fn any_two_sides_of_turned_boards_meet_on_a_second_planar_joint() { + // The sides' centres, the red ones where the red board was made. + let reds = [ + ("red front", Vec3::new(200.0, 300.0, 10.0)), + ("red back", Vec3::new(200.0, 400.0, 10.0)), + ("red left end", Vec3::new(0.0, 350.0, 10.0)), + ("red right end", Vec3::new(400.0, 350.0, 10.0)), + ]; + let yellows = [ + ("yellow front", [200.0, 0.0, 10.0]), + ("yellow back", [200.0, 100.0, 10.0]), + ("yellow left end", [0.0, 50.0, 10.0]), + ("yellow right end", [400.0, 50.0, 10.0]), + ]; + for turn in [40.0f64, 0.0, 137.0] { + for (yn, yp) in yellows { + for (rn, rl) in reds { + let mut s = boards(); + run( + &mut s, + "occurrence.move", + json!({"occurrence": "Red:1", "space": "world", "axis": [0, 0, 1], "angle": format!("{turn} deg"), "origin": [200, 350, 0]}), + ); + let top = place(&s, "Red", Vec3::new(200.0, 350.0, 0.0)); + run( + &mut s, + "joint.create", + json!({"type": "planar", "a": {"occurrence": "Yellow", "face": [200, 50, 20]}, "b": {"occurrence": "Red", "face": [top.x, top.y, top.z]}, "name": "Top"}), + ); + let rp = place(&s, "Red", rl); + let r = run( + &mut s, + "joint.create", + json!({"type": "planar", "a": {"occurrence": "Yellow", "face": yp}, "b": {"occurrence": "Red", "face": [rp.x, rp.y, rp.z]}, "name": "Side"}), + ); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "turned {turn} degrees, {yn} against {rn}: {r}"); + } + } + } +} + +/// #9687: a second planar joint left as a conflict, as a design saved before joint.create turned +/// its part a half turn keeps it, meets when Edit Joint's OK places it again, and one unsuppressed +/// after its part was turned away on the first joint meets too. A rename alone moves nothing. +#[test] +fn editing_or_unsuppressing_a_conflicting_second_planar_joint_turns_its_part_to_meet() { + let conflicts = |r: &Value| r["conflicts"].as_array().map(Vec::len); + let values = |s: &Session, name: &str| s.doc.assembly.joints.iter().find(|j| j.name == name).map(|j| j.values.clone()).unwrap_or_default(); + let pose = |s: &Session| [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z].map(|p| place(s, "Red", p)); + let mut s = boards(); + let planar = |s: &mut Session, name: &str, yellow: [f64; 3], red: [f64; 3]| { + run( + s, + "joint.create", + json!({"type": "planar", "a": {"occurrence": "Yellow", "face": yellow}, "b": {"occurrence": "Red", "face": red}, "name": name}), + ) + }; + planar(&mut s, "Top", [200.0, 50.0, 20.0], [200.0, 350.0, 0.0]); + let on_top = values(&s, "Top"); + // The fronts point the same way: Side meets with Red turned a half turn on Top. + let r = planar(&mut s, "Side", [200.0, 0.0, 10.0], [200.0, 0.0, 30.0]); + assert_eq!(conflicts(&r), Some(0), "{r}"); + let met = pose(&s); + // Red as it met, slid along the line the two planes share (X) at most. + let meets = |s: &Session| { + let now = pose(s); + let dx = Vec3::new(now[0].x - met[0].x, 0.0, 0.0); + now.iter().zip(&met).all(|(p, q)| near(*p, *q + dx)) + }; + // As a design saved before joint.create turned Red: Top's values from before Side. + if let Some(j) = s.doc_mut().assembly.joints.iter_mut().find(|j| j.name == "Top") { + j.values = on_top; + } + let r = run(&mut s, "joint.solve", json!({})); + assert_eq!(conflicts(&r), Some(1), "{r}"); + let saved = pose(&s); + assert!(!meets(&s), "{saved:?}"); + let r = run(&mut s, "joint.edit", json!({"joint": "Side", "name": "Front"})); + assert_eq!(conflicts(&r), Some(1), "a rename: {r}"); + assert!(pose(&s).iter().zip(&saved).all(|(p, q)| near(*p, *q)), "a rename moved Red: {:?}", pose(&s)); + // Edit Joint's OK sends the type, flip and offset. + let r = run(&mut s, "joint.edit", json!({"joint": "Front", "type": "planar", "flip": false, "offset": 0})); + assert_eq!(conflicts(&r), Some(0), "Edit Joint's OK: {r}"); + assert!(meets(&s), "Edit Joint's OK: {:?}", pose(&s)); + assert_eq!(dof_of(&mut s, "Red"), 1); + // Suppressed, Red turned a half turn away on Top, then unsuppressed. + run(&mut s, "joint.edit", json!({"joint": "Front", "suppressed": true})); + let angle = values(&s, "Top").get(2).copied().unwrap_or(f64::NAN).to_degrees(); + run(&mut s, "joint.drive", json!({"joint": "Top", "index": 2, "value": angle + 180.0})); + assert!(!meets(&s), "turned away: {:?}", pose(&s)); + let r = run(&mut s, "joint.edit", json!({"joint": "Front", "suppressed": false})); + assert_eq!(conflicts(&r), Some(0), "unsuppressed: {r}"); + assert!(meets(&s), "unsuppressed: {:?}", pose(&s)); +} + +/// #9687: a frame held by many planar joints ties its loops into one group with more values than +/// the loop solver moves at once, which was then only checked: a new joint closing a loop in it +/// stayed a conflict, and a drive in it moved nothing. A table on the ground, parts each on the +/// table and on the ground (11 parts: 70 values with the peg), and a peg 10 mm from where P0's +/// pin point sits: P0 slides onto it as it does with one part, and turns about it when driven. +#[test] +fn a_loop_in_a_group_over_the_solvers_values_still_closes_and_drives() { + let conflicts = |r: &Value| r["conflicts"].as_array().map(Vec::len); + for parts in [1usize, 11] { + let mut s = Session::default(); + part(&mut s, "Ground", [-1.0, -1.0, -2.0]); + let g = occ(&s, "Ground"); + run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true})); + part(&mut s, "Table", [-1.0, -1.0, 0.0]); + pin(&mut s, "planar", "Base", "Ground", "Table", Vec3::ZERO, Vec3::Z); + for k in 0..parts { + let (name, c) = (format!("P{k}"), Vec3::new(10.0 * k as f64, 20.0, 0.0)); + part(&mut s, &name, [c.x - 1.0, c.y - 1.0, 0.0]); + pin(&mut s, "planar", &format!("{name} on table"), "Table", &name, c, Vec3::Z); + pin(&mut s, "planar", &format!("{name} on ground"), "Ground", &name, c, Vec3::Z); + } + let at = |o: &str, p: [f64; 3]| json!({"occurrence": o, "point": p, "z": [0, 0, 1]}); + let peg = json!({"type": "revolute", "name": "Peg", "a": at("Ground", [10.0, 20.0, 0.0]), "b": at("P0", [0.0, 20.0, 0.0]), "flip": true}); + let r = run(&mut s, "joint.create", peg); + assert_eq!(conflicts(&r), Some(0), "{parts} parts: {r}"); + let pin_point = Vec3::new(10.0, 20.0, 0.0); + assert!(near(place(&s, "P0", Vec3::new(0.0, 20.0, 0.0)), pin_point), "{parts} parts: {:?}", place(&s, "P0", Vec3::new(0.0, 20.0, 0.0))); + // P0's point 1 mm along X from its pin point (closing the loop may have turned P0 a little + // about the peg), then 30 degrees further round. + let (p, q0) = (Vec3::new(1.0, 20.0, 0.0), place(&s, "P0", Vec3::new(1.0, 20.0, 0.0))); + let turn = s.doc.assembly.joints.iter().find(|j| j.name == "Peg").and_then(|j| j.values.first().copied()).unwrap_or(f64::NAN); + let r = run(&mut s, "joint.drive", json!({"joint": "Peg", "value": turn.to_degrees() + 30.0})); + assert!(r["stopped_by_loop"].is_null() && conflicts(&r) == Some(0), "{parts} parts: {r}"); + let (a, b) = (q0 - pin_point, place(&s, "P0", p) - pin_point); + let sin = a.x * b.y - a.y * b.x; + assert!((b.len() - 1.0).abs() < 1e-6 && (sin.abs() - 0.5).abs() < 1e-6 && b.z.abs() < 1e-6, "{parts} parts: {a:?} to {b:?}"); + } +} + /// A slider-crank: crank 15 about the origin, rod 40, a piston sliding along X. Returns the crank /// pin and the wrist pin. fn slider_crank() -> (Session, Vec3, Vec3) { @@ -1179,6 +1498,87 @@ fn hidden_joints_still_drive_and_are_saved_with_the_design() { let _ = std::fs::remove_dir_all(&dir); } +/// #3892: a large nested STEP assembly hides thousands of joints, and the browser asks about +/// every joint of the design on every frame: the answer must not walk the hidden-joint list, +/// so the work must not grow with the number of hidden joints. The hidden joint stays hidden, +/// the shown one stays shown, and undo and redo keep the hiding right. +#[test] +fn hidden_joint_lookups_do_not_walk_the_hidden_joint_list() { + use crate::occurrences::visibility_work; + + let mut s = hinged(); + let (hinge, glue) = (joint(&s, "Hinge"), joint(&s, "Glue")); + + // The hidden joints of an imported assembly: thousands of ids (#3892). + let hide_many = |s: &mut Session, n: u64| { + s.visibility.hidden_joints.clear(); + for id in 0..n { + s.visibility.hidden_joints.push(id); + } + }; + // The entries one lookup walked, for a joint that is not hidden. + let walked_by = |s: &Session, id: u64| { + visibility_work::take(); + let visible = s.joint_visible(id); + let walked = visibility_work::take(); + assert!(visible, "joint {id} is not hidden here"); + walked + }; + + hide_many(&mut s, 10); + let few = walked_by(&s, 9_000_001); + hide_many(&mut s, 10_000); + let many = walked_by(&s, 9_000_001); + assert!( + many <= few + 4, + "a joint lookup walked {many} entries of a 10,000-entry hidden-joint list and {few} of a \ + 10-entry one: the work must not grow with the number of hidden joints" + ); + + // The behaviour is unchanged: the hidden joint is hidden, the shown one is shown, and undo + // and redo keep the hiding right. + s.visibility.hidden_joints.clear(); + run(&mut s, "browser.visibility", json!({"joints": ["Hinge"], "visible": false})); + assert!(!s.joint_visible(hinge) && s.joint_visible(glue)); + run(&mut s, "edit.undo", json!({})); + assert!(s.joint_visible(hinge), "undo shows the hinge again"); + run(&mut s, "edit.redo", json!({})); + assert!(!s.joint_visible(hinge), "redo hides it again"); +} + +/// The cost of a frame's worth of joint questions, with few and with many hidden joints: the +/// manual measurement behind #3892. Run it with `--ignored --nocapture`. +#[test] +#[ignore = "manual scaling measurement"] +fn joint_visibility_lookup_cost_by_hidden_joint_count() { + use crate::occurrences::visibility_work; + + let joints = 1_000u64; + for hidden in [0u64, 10, 100, 1_000, 10_000] { + let mut s = Session::default(); + for id in 0..hidden { + s.visibility.hidden_joints.push(id); + } + let mut times = Vec::new(); + for _ in 0..11 { + let start = std::time::Instant::now(); + for id in 0..joints { + let _ = s.joint_visible(id + hidden + 1); + } + times.push(start.elapsed().as_secs_f64() * 1e3); + } + times.sort_by(f64::total_cmp); + // The index is built once per change of the view, apart from the answers themselves. + println!( + "hidden_joints={hidden:>6} questions={joints} median_ms={:.3} min_ms={:.3} max_ms={:.3} built_entries={}", + times[times.len() / 2], + times[0], + times[times.len() - 1], + visibility_work::built_take() + ); + } +} + /// #1160: a design saved before joints could be hidden (format 19, no `hidden_joints`) opens /// with every joint shown; and a new joint that takes a deleted hidden joint's id starts shown. #[test] @@ -1302,8 +1702,52 @@ fn quiet_joint_answers_and_a_drive_to_where_it_is() { assert!(r["dof"].is_array() && r["moved"] == false && r.get("reason").is_none(), "{r}"); // A suppressed joint with no motion link moves nothing, and says why. run(&mut s, "joint.edit", json!({"joint": "Rail", "suppressed": true})); + let (doc, undo) = (s.doc.clone(), s.undo.len()); let r = run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 8})); assert!(r["moved"] == false && r["reason"] == "Rail is suppressed" && r.get("unconnected").is_none(), "{r}"); + // Nor does it store the value, as it did with an undo step: unsuppressed, the part jumped to + // it (#9742). The reply keeps what was asked apart from what the joint holds. + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc) && s.undo.len() == undo, "a drive of a suppressed joint changed the design"); + assert_eq!((&r["requested"][0]["value"], &r["values"][0]["value"]), (&json!(8.0), &json!(5.0)), "{r}"); + assert!(r.get("held").is_none(), "{r}"); +} + +/// A screw's travel follows its turn, so a distance asked of it is not reached: the reply says +/// what was asked and why the joint holds another value, and a drive of the distance alone, +/// which moves nothing, says why. A limit is named the same way (#9742). +#[test] +fn a_drive_says_which_values_a_motion_link_or_a_limit_held() { + let mut s = two_cubes(); + run(&mut s, "joint.create", json!({"type": "cylindrical", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "name": "Cy"})); + run(&mut s, "joint.screw", json!({"joint": "Cy", "pitch": 2})); + let follows = json!("distance follows its angle through a motion link (screw)"); + let r = run(&mut s, "joint.drive", json!({"joint": "Cy", "values": [90, 5]})); + assert!(r["moved"] == true && r.get("reason").is_none(), "{r}"); + assert_eq!((&r["requested"][0]["value"], &r["requested"][1]["value"]), (&json!(90.0), &json!(5.0)), "{r}"); + let held = r["held"].as_array().cloned().unwrap_or_default(); + assert_eq!(held.len(), 1, "only the distance is held: {r}"); + assert_eq!( + (&held[0]["name"], &held[0]["requested"], &held[0]["unit"], &held[0]["why"]), + (&json!("distance"), &json!(5.0), &json!("mm"), &follows), + "{r}" + ); + assert!((held[0]["value"].as_f64().unwrap_or(f64::NAN) - 0.5).abs() < 1e-9, "a quarter turn at pitch 2 travels 0.5 mm: {r}"); + // The distance alone: nothing moves, and the reply says why. + let r = run(&mut s, "joint.drive", json!({"joint": "Cy", "index": 1, "value": 4})); + assert_eq!((&r["moved"], &r["reason"], &r["held"][0]["requested"]), (&json!(false), &follows, &json!(4.0)), "{r}"); + + let mut s = two_cubes(); + run(&mut s, "joint.as_built", json!({"type": "slider", "a": "A", "b": "B", "name": "Rail", "limits": [[0, 5]]})); + let r = run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 20})); + assert!(r["moved"] == true && r.get("reason").is_none(), "{r}"); + assert_eq!( + r["held"], + json!([{"name": "distance", "requested": 20.0, "value": 5.0, "unit": "mm", "why": "distance is held to its limits, 0 to 5 mm"}]), + "{r}" + ); + // Within the limits, nothing is held. + let r = run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 3})); + assert!(r.get("held").is_none() && r["requested"][0]["value"] == 3.0, "{r}"); } /// An as-built joint takes a name and limits like any other joint. @@ -1861,10 +2305,9 @@ mod motion_analysis; mod motion_sweep; /// A pin through a hole of its own radius whose axis is a hair off the hole's (parts placed from -/// rounded coordinates): the walls are all but tangent along two lines, which the boolean can't -/// intersect. Each offset gets a checked answer: clear on the axis and within the kernel's -/// same-surface tolerance, and otherwise the crescent the pin shares with the plate, against -/// the textbook lens of two circles. The pin is chamfered, so it is not a plain prism. +/// rounded coordinates): the walls are all but tangent along two lines. Each offset gets a +/// checked answer: clear on the axis and within the kernel's same-surface tolerance, and +/// otherwise the crescent the pin shares with the plate, against the textbook lens of two circles. The pin is chamfered, so it is not a plain prism. #[test] fn interference_of_a_pin_a_hair_off_its_hole() { let crescent = |r: f64, e: f64| std::f64::consts::PI * r * r - (2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt()); @@ -1884,7 +2327,6 @@ fn interference_of_a_pin_a_hair_off_its_hole() { let want = 5.0 * crescent(3.0, offset); let got = i["interferences"][0]["volume_mm3"].as_f64().unwrap_or(0.0); assert!((got - want).abs() < 1e-6 * want, "{offset}: {got} against {want}: {i}"); - assert!((i["interferences"][0]["near_coaxial"]["offset_mm"].as_f64().unwrap_or(0.0) - offset).abs() < 1e-9, "{i}"); } } @@ -1905,7 +2347,6 @@ fn interference_of_a_headed_pin_a_hair_off_a_bush_of_its_heads_radius() { let want = 5.0 * crescent(3.0, offset); let got = i["interferences"][0]["volume_mm3"].as_f64().unwrap_or(0.0); assert!((got - want).abs() < 1e-6 * want, "{got} against {want}: {i}"); - assert!(i["interferences"][0]["near_coaxial"].is_object(), "{i}"); } /// A headed pin made before the plate it sits in, a hair off the plate's hole: the crescent @@ -2239,3 +2680,21 @@ fn driving_one_cylindrical_coordinate_preserves_the_other_expression_and_reports assert!(s.execute("joint.drive", &json!({"joint":joint,"index":bad,"value":0})).is_err()); } } + +/// #10747: driving a joint to 30 reports 30, not 29.999999999999996; the joint keeps +/// full precision. +#[test] +fn driving_an_angle_reports_the_number_a_person_would_read() { + let mut s = two_cubes(); + run( + &mut s, + "joint.create", + json!({"type": "revolute", "a": {"occurrence": "A", "point": [5.0, 5.0, 10.0]}, "b": {"occurrence": "B", "point": [25.0, 5.0, 10.0]}, "name": "Turn"}), + ); + let r = run(&mut s, "joint.drive", json!({"joint": "Turn", "value": 30})); + assert_eq!(r["values"][0]["value"], json!(30.0), "{r}"); + assert_eq!(r["requested"][0]["value"], json!(30.0), "{r}"); + // Only what is reported is rounded: the stored value keeps full precision. + let j = s.doc.assembly.joints.iter().find(|j| j.name == "Turn").unwrap(); + assert_ne!(j.values[0].to_degrees(), 30.0, "the stored angle keeps its bits"); +} diff --git a/crates/engine/src/cmd/joints_turn_tests.rs b/crates/engine/src/cmd/joints_turn_tests.rs index 4e645a8ef..bd5bf7894 100644 --- a/crates/engine/src/cmd/joints_turn_tests.rs +++ b/crates/engine/src/cmd/joints_turn_tests.rs @@ -2,7 +2,8 @@ //! already meet stay as they are instead of the part spinning a half turn about their normal. use serde_json::json; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::tests::{occ, place, run}; use crate::Session; diff --git a/crates/engine/src/cmd/libraries.rs b/crates/engine/src/cmd/libraries.rs index ecc1c0b1e..4b04415de 100644 --- a/crates/engine/src/cmd/libraries.rs +++ b/crates/engine/src/cmd/libraries.rs @@ -1,65 +1,33 @@ //! Local material libraries: inspect/export files and copy exact revisions into a design. use super::CommandSpec; +use crate::schema::libraries::{ + LibraryApplied, LibraryApplyParams, LibraryExportParams, LibraryExported, LibraryInspectParams, LibraryInspected, LibraryTargets, +}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session, params::bad}; -use serde::Deserialize; use serde_json::{Value, json}; -use solidcraft_io::catalog::{Catalog, Definition, Provenance}; +use solidcraft_io::catalog::{Catalog, Definition}; + +const INSPECT_CONTRACT: TypedContract = TypedContract::new(); +const EXPORT_CONTRACT: TypedContract = TypedContract::new(); +const APPLY_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("library.inspect", "Inspect Local Library", inspect).icon("inspect").noundo().doc_only() + CommandSpec::new("library.inspect", "Inspect Local Library", crate::checked!("library.inspect", inspect)).icon("inspect").noundo().doc_only() + .contract(&INSPECT_CONTRACT) + .output(output_schema_for::) .params("path: v1/v2 library JSON; returns validated catalog and exact entry revisions, without changing the design"), - CommandSpec::new("library.export", "Export Design Library", export).icon("export").noundo().doc_only() + CommandSpec::new("library.export", "Export Design Library", crate::checked!("library.export", export)).icon("export").noundo().doc_only() + .contract(&EXPORT_CONTRACT) + .output(output_schema_for::) .params("path: .json; id? (default user.local), name?, provenance?, overwrite? false, format? solidcraft-library/2 (default) | solidcraft-library/1 (refuses PBR/cards). Copies assigned looks and design-local physical definitions; never changes the design"), - CommandSpec::new("library.apply", "Apply Local Library Entry", apply).icon("import").enabled(super::not_in_sketch) + CommandSpec::new("library.apply", "Apply Local Library Entry", crate::checked!("library.apply", apply)).icon("import").enabled(super::not_in_sketch) + .contract(&APPLY_CONTRACT) + .output(output_schema_for::) .params("path, entry: qualified ID, revision: exact content SHA-256; targets?: {bodies?, faces?: [{body,point}], components?}; name?: physical material name on import. Copies values in one undo step; material conflicts are explicit"), ]; -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Inspect { - path: String, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Export { - path: String, - #[serde(default = "default_id")] - id: String, - #[serde(default = "default_name")] - name: String, - #[serde(default)] - provenance: Provenance, - #[serde(default)] - overwrite: bool, - #[serde(default = "default_format")] - format: String, -} -fn default_format() -> String { - solidcraft_io::catalog::FORMAT.into() -} -fn default_id() -> String { - "user.local".into() -} -fn default_name() -> String { - "My library".into() -} -#[derive(Default, Deserialize, serde::Serialize)] -#[serde(deny_unknown_fields)] -struct Targets { - #[serde(default)] - bodies: Vec, - #[serde(default)] - faces: Vec, - #[serde(default)] - components: Vec, -} -#[derive(Deserialize, serde::Serialize)] -#[serde(deny_unknown_fields)] -struct Face { - body: String, - point: [f64; 3], -} -impl Targets { +impl LibraryTargets { fn validate(&self) -> Result<()> { let cmd = "library.apply"; if self.bodies.len().saturating_add(self.faces.len()).saturating_add(self.components.len()) > 1024 { @@ -79,35 +47,28 @@ impl Targets { self.bodies.is_empty() && self.faces.is_empty() && self.components.is_empty() } } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Apply { - path: String, - entry: String, - revision: String, - #[serde(default)] - targets: Targets, - name: Option, -} fn path(cmd: &str, value: &str) -> Result<()> { if value.is_empty() || value.len() > 4096 || value.chars().any(char::is_control) { return Err(bad(cmd, "invalid library path")); } solidcraft_io::vfs::check(value).map_err(|e| bad(cmd, e.to_string())) } +fn reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) +} fn nested(s: &mut Session, id: &str, p: &Value) -> Result { crate::find_command(id).ok_or_else(|| bad("library.apply", "required assignment command is unavailable"))?.run_nested(s, p) } fn inspect(_s: &mut Session, p: &Value) -> Result { let cmd = "library.inspect"; - let request: Inspect = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, e.to_string()))?; + let request: LibraryInspectParams = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, e.to_string()))?; path(cmd, &request.path)?; let catalog = Catalog::read(&request.path).map_err(|e| bad(cmd, e.to_string()))?; - Ok(json!({"catalog":catalog})) + reply(cmd, LibraryInspected { catalog, param_warnings: Vec::new() }) } fn export(s: &mut Session, p: &Value) -> Result { let cmd = "library.export"; - let request: Export = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, e.to_string()))?; + let request: LibraryExportParams = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, e.to_string()))?; path(cmd, &request.path)?; if !request.path.to_ascii_lowercase().ends_with(".json") { return Err(bad(cmd, "library export path must end in .json")); @@ -129,11 +90,12 @@ fn export(s: &mut Session, p: &Value) -> Result { solidcraft_io::vfs::write(&request.path, &bytes) }; result.map_err(|e| bad(cmd, format!("could not export library: {e}")))?; - Ok(json!({"path":request.path,"entries":catalog.entries.len(),"bytes":bytes.len(),"catalog":catalog})) + let entries = catalog.entries.len(); + reply(cmd, LibraryExported { path: request.path, entries, bytes: bytes.len(), catalog, param_warnings: Vec::new() }) } fn apply(s: &mut Session, p: &Value) -> Result { let cmd = "library.apply"; - let request: Apply = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, e.to_string()))?; + let request: LibraryApplyParams = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, e.to_string()))?; path(cmd, &request.path)?; request.targets.validate()?; if request.entry.len() > 129 || request.revision.len() != 64 { @@ -205,7 +167,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { json!({"material":name,"reused":reused,"bodies":request.targets.bodies}) } }; - Ok(json!({"entry":entry.id,"revision":entry.revision,"copied":true,"result":result})) + reply(cmd, LibraryApplied { entry: entry.id.clone(), revision: entry.revision.clone(), copied: true, result, param_warnings: Vec::new() }) } #[cfg(test)] diff --git a/crates/engine/src/cmd/libraries_tests.rs b/crates/engine/src/cmd/libraries_tests.rs index 50e0abadc..b18dfe08b 100644 --- a/crates/engine/src/cmd/libraries_tests.rs +++ b/crates/engine/src/cmd/libraries_tests.rs @@ -1,5 +1,6 @@ use super::*; -use solidcraft_io::catalog::{Definition, Entry, FORMAT, LibraryLook, LibraryMaterial}; +use solidcraft_geom::prelude::*; +use solidcraft_io::catalog::{Definition, Entry, FORMAT, LibraryLook, LibraryMaterial, Provenance}; use std::sync::{ Arc, atomic::{AtomicU64, Ordering}, @@ -87,10 +88,10 @@ fn catalog_world_instance_targets_map_once_and_invalid_targets_are_atomic() { assert_eq!(s.doc.appearances.bodies[&source], look.to_look()); let face = &s.doc.appearances.faces[0]; assert_eq!(face.body, source); - assert!(face.point.dist(solidcraft_geom::Vec3::new(1., 1., 2.)) < 1e-9); + assert!(face.point.dist(solidcore_record::Vec3::new(1., 1., 2.)) < 1e-9); assert_eq!(face.look, look.to_look()); assert_eq!(s.undo.len(), history.0 + 1); - let world = s.world_state(); + let world = s.world_state().unwrap(); let placed = world.body(&instance).unwrap(); assert!(s.doc.face_colors(placed).iter().any(|(_, assigned)| assigned == &look.to_look())); apply_entry(&mut s, &file, &c.entries[1], json!({"bodies":[instance]})).unwrap(); diff --git a/crates/engine/src/cmd/lineage_face_tests.rs b/crates/engine/src/cmd/lineage_face_tests.rs index 680dfb1fd..0c3346ba1 100644 --- a/crates/engine/src/cmd/lineage_face_tests.rs +++ b/crates/engine/src/cmd/lineage_face_tests.rs @@ -7,6 +7,7 @@ use crate::Session; use serde_json::{Value, json}; use solidcraft_doc::FaceAttachmentStatus; use solidcraft_doc::config::FaceCertificate; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap_or_else(|e| panic!("{command} {params}: {e}")) @@ -22,7 +23,7 @@ fn status(s: &Session, sketch: &str) -> FaceAttachmentStatus { s.placed_document().sketch_face_attachment(id, &s.model) } -fn healthy(s: &Session, sketch: &str) -> (solidcraft_geom::Plane, Option) { +fn healthy(s: &Session, sketch: &str) -> (solidcore_record::Plane, Option) { match status(s, sketch) { FaceAttachmentStatus::Healthy { plane, target, .. } => (plane, target.certificate), other => panic!("{sketch}: {other:?}"), @@ -107,7 +108,7 @@ fn a_chamfer_face_takes_a_sketch_that_follows_the_chamfer() { let n = std::f64::consts::FRAC_1_SQRT_2; assert!((plane.normal().x - n).abs() < 1e-9 && (plane.normal().z - n).abs() < 1e-9, "{plane:?}"); // A bigger chamfer moves the face inward: the sketch goes with it. - let height = |p: &solidcraft_geom::Plane| (p.origin - solidcraft_geom::Vec3::new(40., 0., 10.)).dot(p.normal()); + let height = |p: &solidcore_record::Plane| (p.origin - solidcore_record::Vec3::new(40., 0., 10.)).dot(p.normal()); assert!((height(&plane) + 3. * n).abs() < 1e-9, "{plane:?}"); run(&mut s, "parameters.change", json!({"name": "bevel", "expression": "5 mm"})); no_errors(&s); @@ -248,10 +249,10 @@ fn counterbore_floors_and_their_pattern_copies_take_a_sketch() { } /// The middle of the largest triangle of each flat face of the first body. -fn flat_faces(s: &Session) -> Vec<(usize, solidcraft_geom::Vec3)> { +fn flat_faces(s: &Session) -> Vec<(usize, solidcore_record::Vec3)> { let state = s.model.state(); let body = &state.bodies[0].body; - let mesh = body.tessellate(0.01).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); (0..body.face_count()) .filter(|index| body.planar_face(*index).is_some()) .filter_map(|index| { diff --git a/crates/engine/src/cmd/loft_rails_tests.rs b/crates/engine/src/cmd/loft_rails_tests.rs index eca940d01..45a33464f 100644 --- a/crates/engine/src/cmd/loft_rails_tests.rs +++ b/crates/engine/src/cmd/loft_rails_tests.rs @@ -56,7 +56,7 @@ fn setup() -> Session { } fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { - solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() + solidcraft_kernel::measure(&s.world_state().unwrap().body(body).unwrap().body).unwrap() } fn loft(s: &mut Session, body: &str, extra: Value) -> Result { diff --git a/crates/engine/src/cmd/mass_properties.rs b/crates/engine/src/cmd/mass_properties.rs new file mode 100644 index 000000000..fc76e680f --- /dev/null +++ b/crates/engine/src/cmd/mass_properties.rs @@ -0,0 +1,364 @@ +//! Mass, centre of mass and inertia tensor per occurrence and per rigid group (#9715): what a +//! multibody dynamics solver needs of each moving part. +//! +//! Bodies are measured as `component.properties` measures them (docs/assembly-properties.md): +//! volume and centre from the kernel's measurement, the inertia from how the welded export mesh +//! spreads that volume (`solidcraft_geom::inertia`), at the body's material density (the default +//! material's when none is assigned). Each body is measured once however often it is placed; +//! each placement moves its centre and turns its tensor, and an occurrence's bodies combine by +//! the parallel-axis theorem. An open body adds no mass and is counted. +//! +//! Rigid groups are the occurrences that move as one body: those an unsuppressed rigid joint +//! ties together, and a nested occurrence that no joint places with the occurrence it sits in +//! (the joint solver leaves it where its parent puts it). A group holding the design itself or +//! a grounded occurrence is fixed. Occurrences are taken where the joint solver places them, so +//! an occurrence inside a subassembly placed more than once is listed at the subassembly's first +//! placement (a warning says so). + +use solidcraft_geom::prelude::*; +use std::collections::{BTreeMap, HashMap, HashSet}; + +use serde_json::Value; +use solidcore_record::Vec3; +use solidcraft_doc::joints::{self, JointKind, MAX_JOINTS}; +use solidcraft_doc::{Document, IDENTITY, MAX_PLACEMENTS, Mat, ModelState, apply_point, mat_inverse, mat_mul}; +use solidcraft_geom::inertia::{self, Tensor3}; + +use super::CommandSpec; +use crate::params::bad; +use crate::schema::mass_properties::{AssemblyMassParams, AssemblyMassResult, BodyMassEntry, MassFrame, OccurrenceMass, RigidGroupMass, RigidMass}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session}; + +const CMD: &str = "assembly.mass_properties"; +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Mass Properties", crate::checked!("assembly.mass_properties", run)) + .icon("measure") + .noundo() + .contract(&CONTRACT) + .output(output_schema_for::) + .params( + "no parameters → occurrences: [{occurrence (0: the design's own bodies), name, component, path, group, fixed, frame \ + {origin, x, y, z}, bodies: [{name, material, density_g_cm3, closed, volume_mm3, mass_kg}], open_bodies_skipped, mass}], \ + groups: [{group, occurrences, fixed, frame_occurrence, frame, mass}] (occurrences an unsuppressed rigid joint ties \ + together, and a nested occurrence no joint places with its parent; fixed: holds the design or a grounded occurrence), \ + warnings. mass: {mass_kg, center_of_mass_mm (world), center_of_mass_local_mm, inertia_world_kg_mm2, \ + inertia_local_kg_mm2 (about the centre of mass, in world and frame axes)} or null when massless. Read-only; pending \ + moves count; each body at its material's density (the default material's when none is assigned)", + )]; + +/// One rigid body's mass properties: mass (kg), centre of mass (mm, world) and the inertia +/// tensor about it (kg·mm², world axes; `None` when a closed body's mesh did not close). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct MassBody { + pub mass: f64, + pub center: Vec3, + pub inertia: Option, +} + +impl MassBody { + pub fn is_finite(&self) -> bool { + self.mass.is_finite() && self.center.is_finite() && self.inertia.is_none_or(|i| i.iter().flatten().all(|x| x.is_finite())) + } + + /// Bodies taken as one: the masses add, the centre is mass-weighted, and each tensor moves to + /// the common centre by the parallel-axis theorem. The tensor is `None` when any part's is. + /// `None` when the total mass is not positive or a value is not finite. + pub fn combine(parts: &[MassBody]) -> Option { + let mass: f64 = parts.iter().map(|p| p.mass).sum(); + if !(mass > 0.0 && mass.is_finite()) { + return None; + } + let center = parts.iter().fold(Vec3::ZERO, |acc, p| acc + p.center * p.mass) * (1.0 / mass); + let inertia = parts.iter().try_fold([[0.0f64; 3]; 3], |sum, p| { + let i = inertia::shifted(&p.inertia?, p.mass, p.center - center); + Some([0, 1, 2].map(|r| [0, 1, 2].map(|k| sum[r][k] + i[r][k]))) + }); + let out = MassBody { mass, center, inertia }; + out.is_finite().then_some(out) + } +} + +/// The 3 × 3 linear part of a placement, row by row (`Mat` is column-major). +fn linear(m: &Mat) -> Tensor3 { + [0, 1, 2].map(|i| [0, 1, 2].map(|j| m[j][i])) +} + +fn transpose(a: &Tensor3) -> Tensor3 { + [0, 1, 2].map(|i| [0, 1, 2].map(|j| a[j][i])) +} + +fn det3(a: &Tensor3) -> f64 { + a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) +} + +/// The rotation (or reflection) a placement's axes make, when they are orthonormal. +fn rotation(m: &Mat) -> Option { + let a = linear(m); + let ata = inertia::transformed(&[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], &transpose(&a)); + let ok = (0..3).all(|i| (0..3).all(|j| (ata[i][j] - if i == j { 1.0 } else { 0.0 }).abs() <= 1e-9)); + ok.then_some(a) +} + +fn xyz(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +fn frame_of(m: &Mat) -> MassFrame { + let axis = |k: usize| { + let v = Vec3::new(m[k][0], m[k][1], m[k][2]); + let len = v.len(); + xyz(if len > 0.0 && len.is_finite() { v * (1.0 / len) } else { v }) + }; + MassFrame { origin: [m[3][0], m[3][1], m[3][2]], x: axis(0), y: axis(1), z: axis(2) } +} + +/// A world [`MassBody`] as the frame `m` sees it. +fn rigid_mass(b: &MassBody, m: &Mat) -> RigidMass { + let local = mat_inverse(m).map(|inv| apply_point(&inv, b.center)).unwrap_or(b.center); + RigidMass { + mass_kg: b.mass, + center_of_mass_mm: xyz(b.center), + center_of_mass_local_mm: xyz(local), + inertia_world_kg_mm2: b.inertia, + // Rᵀ I R: the world tensor in the frame's axes. + inertia_local_kg_mm2: b.inertia.zip(rotation(m)).map(|(i, r)| inertia::transformed(&i, &transpose(&r))), + } +} + +/// Union-find over occurrence indices; the lower index roots a group, so the design (index 0) +/// roots its own. +struct Groups(Vec); + +impl Groups { + fn root(&self, mut i: usize) -> usize { + // Bounded: each step goes to a lower index. + for _ in 0..self.0.len() { + match self.0.get(i) { + Some(&parent) if parent != i => i = parent, + _ => break, + } + } + i + } + fn join(&mut self, a: usize, b: usize) { + let (ra, rb) = (self.root(a), self.root(b)); + if let Some(slot) = self.0.get_mut(ra.max(rb)) { + *slot = ra.min(rb); + } + } +} + +/// Occurrence ids from the top of the assembly down, as `joints::occurrence_world` walks them. +fn canonical_path(doc: &Document, occ: u64) -> Vec { + let mut path = Vec::new(); + let mut cur = doc.occurrences.iter().find(|o| o.id == occ); + for _ in 0..1000 { + let Some(o) = cur else { break }; + path.push(o.id); + if o.parent == 0 { + break; + } + cur = doc.occurrence_of(o.parent); + } + path.reverse(); + path +} + +fn out_of_range() -> EngineError { + bad(CMD, "mass properties exceed supported numeric range") +} + +impl Session { + /// Mass, centre of mass and inertia of every occurrence and rigid group of the design, as + /// `assembly.mass_properties` returns them (kg, mm, kg·mm²), pending moves included. + pub fn mass_properties(&self) -> Result { + let mut doc = (*self.doc).clone(); + for occurrence in &mut doc.occurrences { + if let Some(transform) = self.pending_moves.get(&occurrence.id) { + occurrence.transform = *transform; + } + } + let state = self.model.state(); + assembly(&doc, &state) + } +} + +/// A body measured once: closed, and if so its volume (mm³), centre (mm) and spread, all in its +/// component's frame before its offset. +struct Shape { + closed: bool, + volume: f64, + centroid: Vec3, + gyration: Option, +} + +/// [`Session::mass_properties`] of a document and its evaluated state. +pub fn assembly(doc: &Document, state: &ModelState) -> Result { + if doc.occurrences.len() >= MAX_PLACEMENTS { + return Err(bad(CMD, format!("assembly exceeds {MAX_PLACEMENTS} occurrences"))); + } + let mut warnings = Vec::new(); + // Index 0 is the design itself; then the occurrences by id. + let mut ids: Vec = doc.occurrences.iter().map(|o| o.id).filter(|id| *id != 0).collect(); + ids.sort_unstable(); + ids.dedup(); + ids.insert(0, 0); + let index: HashMap = ids.iter().enumerate().map(|(i, id)| (*id, i)).collect(); + + let mut groups = Groups((0..ids.len()).collect()); + let live: Vec<_> = doc.assembly.joints.iter().filter(|j| !j.suppressed).take(MAX_JOINTS).collect(); + let jointed: HashSet = live.iter().flat_map(|j| [j.a.occurrence, j.b.occurrence]).collect(); + for j in live.iter().filter(|j| j.kind == JointKind::Rigid) { + if let (Some(&a), Some(&b)) = (index.get(&j.a.occurrence), index.get(&j.b.occurrence)) { + groups.join(a, b); + } + } + for o in doc.occurrences.iter().filter(|o| o.parent != 0 && !jointed.contains(&o.id)) { + if let (Some(&child), Some(&parent)) = (index.get(&o.id), doc.occurrence_of(o.parent).and_then(|p| index.get(&p.id))) { + groups.join(child, parent); + } + } + for c in doc.components.iter().filter(|c| doc.occurrences.iter().any(|o| o.parent == c.id)) { + let copies = doc.occurrences.iter().filter(|o| o.component == c.id).count(); + if copies > 1 { + warnings.push(format!( + "`{}` is placed {copies} times: the occurrences inside it are listed at its first placement only, where joints place them", + c.name + )); + } + } + + // Each placed body measured once, on worker threads. + let owners = doc.model_body_components(state); + let placed: HashSet = + ids.iter().map(|id| if *id == 0 { 0 } else { doc.occurrences.iter().find(|o| o.id == *id).map_or(u64::MAX, |o| o.component) }).collect(); + let measured: Vec = (0..state.bodies.len()).filter(|i| owners.get(*i).is_some_and(|c| placed.contains(c))).collect(); + let shapes = solidcraft_kernel::map_on_threads(&measured, 16, |&i| -> Result { + let body = state.bodies.get(i).ok_or_else(|| EngineError::Other("body index out of range".into()))?; + let closed = crate::cmd::inspect::encloses_volume(&body.body); + if !closed { + return Ok(Shape { closed, volume: 0.0, centroid: Vec3::ZERO, gyration: None }); + } + let m = solidcraft_kernel::measure_mass(&body.body)?; + let gyration = solidcraft_io::mass_properties(&body.body)?.and_then(|p| p.gyration()); + Ok(Shape { closed, volume: m.volume, centroid: m.centroid, gyration }) + }); + let mut shape: BTreeMap = BTreeMap::new(); + for (i, s) in measured.into_iter().zip(shapes) { + shape.insert(i, s.ok_or_else(|| bad(CMD, "measuring a body failed"))??); + } + + let mut occurrences = Vec::with_capacity(ids.len()); + let mut totals: Vec> = Vec::with_capacity(ids.len()); + for (i, &id) in ids.iter().enumerate() { + let (component, name, world, path, fixed) = if id == 0 { + (0, doc.name.clone(), IDENTITY, Vec::new(), true) + } else { + // Every id came from `doc.occurrences`, so the occurrence is there. + let o = doc.occurrences.iter().find(|o| o.id == id); + let (component, name, grounded) = o.map_or((u64::MAX, String::new(), false), |o| (o.component, o.name.clone(), o.grounded)); + (component, name, joints::occurrence_world(doc, id), canonical_path(doc, id), grounded) + }; + if world.iter().flatten().any(|x| !x.is_finite()) { + return Err(out_of_range()); + } + let (mut bodies, mut parts, mut skipped) = (Vec::new(), Vec::new(), 0); + for (k, body) in state.bodies.iter().enumerate().filter(|(k, _)| owners.get(*k) == Some(&component)) { + let Some(s) = shape.get(&k) else { continue }; + let density = doc.density(&body.name); + let mut entry = BodyMassEntry { + name: body.name.clone(), + material: doc.body_material(&body.name), + density_g_cm3: density, + closed: s.closed, + ..BodyMassEntry::default() + }; + if s.closed { + let at = doc.model_body_offset(body).map_or(world, |offset| mat_mul(&world, offset)); + let l = linear(&at); + let volume = s.volume * det3(&l).abs(); + // g/cm³ × mm³ is mg; kg is 1e-6 of that. + let mass = volume * density * 1e-6; + let inertia = s.gyration.map(|g| inertia::from_gyration(&inertia::transformed(&g, &l), mass)); + let part = MassBody { mass, center: apply_point(&at, s.centroid), inertia }; + if !(part.is_finite() && volume.is_finite()) { + return Err(out_of_range()); + } + if inertia.is_none() { + warnings.push(format!("body `{}`: its mesh does not close, so its inertia is unknown", body.name)); + } + parts.push(part); + entry.volume_mm3 = Some(volume); + entry.mass_kg = Some(mass); + } else { + skipped += 1; + warnings.push(format!("body `{}` is not a closed solid: it adds no mass", body.name)); + } + bodies.push(entry); + } + let total = MassBody::combine(&parts); + if total.is_none() && parts.iter().map(|p| p.mass).sum::() > 0.0 { + return Err(out_of_range()); + } + if total.is_some() && rotation(&world).is_none() { + warnings.push(format!("`{name}` is scaled: its inertia in its own axes is left out")); + } + totals.push(total); + occurrences.push(OccurrenceMass { + occurrence: id, + name, + component, + path, + group: i, + fixed, + frame: frame_of(&world), + bodies, + open_bodies_skipped: skipped, + mass: total.map(|t| rigid_mass(&t, &world)), + }); + } + + // Groups in order of their lowest occurrence id (their union-find root). + let mut by_root: BTreeMap> = BTreeMap::new(); + for i in 0..occurrences.len() { + by_root.entry(groups.root(i)).or_default().push(i); + } + let mut out_groups = Vec::with_capacity(by_root.len()); + for (g, members) in by_root.values().enumerate() { + let fixed = members.iter().any(|&m| occurrences.get(m).is_some_and(|o| o.fixed)); + let frame_occurrence = members.first().and_then(|&m| ids.get(m)).copied().unwrap_or(0); + let world = if frame_occurrence == 0 { IDENTITY } else { joints::occurrence_world(doc, frame_occurrence) }; + let parts: Vec = members.iter().filter_map(|&m| totals.get(m).copied().flatten()).collect(); + let total = MassBody::combine(&parts); + if total.is_none() && !parts.is_empty() { + return Err(out_of_range()); + } + for &m in members { + if let Some(o) = occurrences.get_mut(m) { + o.group = g; + } + } + out_groups.push(RigidGroupMass { + group: g, + occurrences: members.iter().filter_map(|&m| ids.get(m).copied()).collect(), + fixed, + frame_occurrence, + frame: frame_of(&world), + mass: total.map(|t| rigid_mass(&t, &world)), + }); + } + Ok(AssemblyMassResult { occurrences, groups: out_groups, warnings, param_warnings: Vec::new() }) +} + +fn run(s: &mut Session, _p: &Value) -> Result { + let r = s.mass_properties()?; + serde_json::to_value(r).map_err(|e| EngineError::Other(e.to_string())) +} + +#[cfg(test)] +#[path = "mass_properties_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests; diff --git a/crates/engine/src/cmd/mass_properties_tests.rs b/crates/engine/src/cmd/mass_properties_tests.rs new file mode 100644 index 000000000..cbab572d2 --- /dev/null +++ b/crates/engine/src/cmd/mass_properties_tests.rs @@ -0,0 +1,269 @@ +//! `assembly.mass_properties` against closed-form values: a box, a cylinder, two boxes apart +//! (parallel axis), a turned occurrence, a rigid group, and inputs that must not panic. + +use std::f64::consts::PI; + +use serde_json::{Value, json}; + +use super::MassBody; +use crate::Session; +use solidcore_record::Vec3; +use solidcraft_geom::inertia::Tensor3 as Tensor; + +fn run(s: &mut Session, cmd: &str, params: Value) -> Value { + s.execute(cmd, ¶ms).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn num(v: &Value) -> f64 { + v.as_f64().unwrap_or_else(|| panic!("not a number: {v}")) +} + +fn near(actual: f64, expected: f64, rel: f64) { + assert!((actual - expected).abs() <= rel * expected.abs().max(1e-9), "{actual} != {expected} (rel {rel})"); +} + +fn tensor(v: &Value) -> Tensor { + let mut t = [[0.0; 3]; 3]; + for (i, row) in t.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = num(&v[i][j]); + } + } + t +} + +fn diag(t: &Tensor, expected: [f64; 3], rel: f64) { + let scale = expected.iter().fold(0.0f64, |a, b| a.max(b.abs())); + for i in 0..3 { + near(t[i][i], expected[i], rel); + for j in 0..3 { + if i != j { + assert!(t[i][j].abs() <= rel * scale, "off-diagonal [{i}][{j}] = {} in {t:?}", t[i][j]); + } + } + } +} + +/// A new component (not grounded) holding a box; its occurrence id and the body's name. +fn part(s: &mut Session, name: &str, size: [f64; 3], material: &str) -> (u64, u64, String) { + run(s, "component.activate", json!({"component": "root"})); + let c = run(s, "component.create", json!({"name": name, "grounded": false})); + run(s, "solid.box", json!({"length": size[0], "width": size[1], "height": size[2]})); + let body = s.model.state().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); + run(s, "material.assign", json!({"bodies": [body], "material": material})); + (c["component"].as_u64().unwrap_or(0), c["occurrence"].as_u64().unwrap_or(0), body) +} + +fn occurrence(r: &Value, id: u64) -> &Value { + r["occurrences"].as_array().and_then(|a| a.iter().find(|o| o["occurrence"] == id)).unwrap_or_else(|| panic!("no occurrence {id} in {r}")) +} + +/// Box `a × b × c` of mass `m` about its centre: `m/12 (b² + c²)` and so on. +fn box_inertia(m: f64, [a, b, c]: [f64; 3]) -> [f64; 3] { + [m / 12.0 * (b * b + c * c), m / 12.0 * (a * a + c * c), m / 12.0 * (a * a + b * b)] +} + +#[test] +fn a_box_has_its_closed_form_mass_centre_and_inertia() { + let mut s = Session::default(); + let (_, occ, body) = part(&mut s, "Block", [10.0, 20.0, 30.0], "Steel"); + let rho = s.doc.density(&body); + let m = 6000.0 * rho * 1e-6; + let r = run(&mut s, "assembly.mass_properties", json!({})); + let o = occurrence(&r, occ); + assert_eq!(o["bodies"][0]["material"], "Steel"); + assert_eq!(o["bodies"][0]["closed"], true); + near(num(&o["bodies"][0]["volume_mm3"]), 6000.0, 1e-9); + let mass = &o["mass"]; + near(num(&mass["mass_kg"]), m, 1e-9); + for (k, c) in [5.0, 10.0, 15.0].iter().enumerate() { + near(num(&mass["center_of_mass_mm"][k]), *c, 1e-9); + near(num(&mass["center_of_mass_local_mm"][k]), *c, 1e-9); + } + diag(&tensor(&mass["inertia_world_kg_mm2"]), box_inertia(m, [10.0, 20.0, 30.0]), 1e-9); + diag(&tensor(&mass["inertia_local_kg_mm2"]), box_inertia(m, [10.0, 20.0, 30.0]), 1e-9); + // The design itself is a fixed group of its own, without mass. + assert_eq!(r["groups"][0]["occurrences"], json!([0])); + assert_eq!(r["groups"][0]["fixed"], true); + assert!(r["groups"][0]["mass"].is_null()); + let g = &r["groups"][o["group"].as_u64().unwrap_or(0) as usize]; + assert_eq!(g["occurrences"], json!([occ])); + assert_eq!(g["fixed"], false); + near(num(&g["mass"]["mass_kg"]), m, 1e-9); +} + +#[test] +fn a_cylinder_matches_its_closed_form_within_the_tessellation() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Shaft", "grounded": false})); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 40})); + let body = s.model.state().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); + let rho = s.doc.density(&body); + let (r_, h) = (10.0f64, 40.0f64); + let m = PI * r_ * r_ * h * rho * 1e-6; + let r = run(&mut s, "assembly.mass_properties", json!({})); + let o = &r["occurrences"][1]; + assert_eq!(o["bodies"][0]["material"], s.doc.body_material(&body)); + let mass = &o["mass"]; + near(num(&mass["mass_kg"]), m, 1e-3); + near(num(&mass["center_of_mass_mm"][2]), 20.0, 1e-3); + assert!(num(&mass["center_of_mass_mm"][0]).abs() < 1e-3); + let side = m * (3.0 * r_ * r_ + h * h) / 12.0; + diag(&tensor(&mass["inertia_world_kg_mm2"]), [side, side, m * r_ * r_ / 2.0], 2e-3); +} + +#[test] +fn two_boxes_apart_combine_by_the_parallel_axis_theorem() { + let mut s = Session::default(); + let (_, occ, body) = part(&mut s, "Pair", [10.0, 10.0, 10.0], "Aluminum"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0]})); + let second = s.model.state().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); + assert_ne!(second, body); + let (r1, r2) = (s.doc.density(&body), s.doc.density(&second)); + let (m1, m2) = (1000.0 * r1 * 1e-6, 1000.0 * r2 * 1e-6); + let m = m1 + m2; + // Centres at x = 5 and x = 35. + let cx = (5.0 * m1 + 35.0 * m2) / m; + let r = run(&mut s, "assembly.mass_properties", json!({})); + let mass = &occurrence(&r, occ)["mass"]; + near(num(&mass["mass_kg"]), m, 1e-9); + near(num(&mass["center_of_mass_mm"][0]), cx, 1e-9); + let own = |mi: f64| mi / 12.0 * 200.0; + let shift = m1 * (cx - 5.0).powi(2) + m2 * (35.0 - cx).powi(2); + diag(&tensor(&mass["inertia_world_kg_mm2"]), [own(m1) + own(m2), own(m1) + own(m2) + shift, own(m1) + own(m2) + shift], 1e-9); +} + +#[test] +fn a_turned_occurrence_turns_its_world_tensor_but_not_its_own() { + let mut s = Session::default(); + let (_, occ, body) = part(&mut s, "Block", [10.0, 20.0, 30.0], "Steel"); + let m = 6000.0 * s.doc.density(&body) * 1e-6; + // A quarter turn about z, kept pending (pending moves count, as Properties shows them). + run(&mut s, "occurrence.move", json!({"occurrence": occ, "axis": [0, 0, 1], "angle": "90 deg", "translate": [100, 0, 0], "capture": false})); + let r = run(&mut s, "assembly.mass_properties", json!({})); + let o = occurrence(&r, occ); + let frame = &o["frame"]; + near(num(&frame["x"][1]), 1.0, 1e-9); + near(num(&frame["y"][0]), -1.0, 1e-9); + let mass = &o["mass"]; + let local = box_inertia(m, [10.0, 20.0, 30.0]); + diag(&tensor(&mass["inertia_world_kg_mm2"]), [local[1], local[0], local[2]], 1e-9); + diag(&tensor(&mass["inertia_local_kg_mm2"]), local, 1e-9); + for (k, c) in [5.0, 10.0, 15.0].iter().enumerate() { + near(num(&mass["center_of_mass_local_mm"][k]), *c, 1e-9); + } + // World centre: (5, 10, 15) turned about z then moved. + let world: Vec = (0..3).map(|k| num(&mass["center_of_mass_mm"][k])).collect(); + let expected = [num(&frame["origin"][0]) - 10.0, num(&frame["origin"][1]) + 5.0, num(&frame["origin"][2]) + 15.0]; + for (a, e) in world.iter().zip(expected) { + near(*a, e, 1e-9); + } +} + +#[test] +fn a_rigid_group_is_one_body_and_other_joints_keep_bodies_apart() { + let mut s = Session::default(); + let (_, a, body_a) = part(&mut s, "Base", [10.0, 10.0, 10.0], "Steel"); + let (_, b, body_b) = part(&mut s, "Cap", [10.0, 10.0, 10.0], "Steel"); + run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [0, 0, 40]})); + let (_, c, _) = part(&mut s, "Loose", [10.0, 10.0, 10.0], "Steel"); + run(&mut s, "occurrence.move", json!({"occurrence": c, "translate": [100, 0, 0]})); + run(&mut s, "joint.rigid_group", json!({"occurrences": [a, b]})); + let r = run(&mut s, "assembly.mass_properties", json!({})); + let (ga, gb, gc) = (occurrence(&r, a)["group"].clone(), occurrence(&r, b)["group"].clone(), occurrence(&r, c)["group"].clone()); + assert_eq!(ga, gb); + assert_ne!(ga, gc); + let g = &r["groups"][ga.as_u64().unwrap_or(0) as usize]; + let mut held: Vec = vec![a, b]; + held.sort_unstable(); + assert_eq!(g["occurrences"], json!(held)); + assert_eq!(g["frame_occurrence"], json!(held[0])); + let m1 = 1000.0 * s.doc.density(&body_a) * 1e-6; + let m2 = 1000.0 * s.doc.density(&body_b) * 1e-6; + let m = m1 + m2; + let mass = &g["mass"]; + near(num(&mass["mass_kg"]), m, 1e-9); + // Centres at z = 5 and z = 45: the common one halfway, each 20 mm off it. + near(num(&mass["center_of_mass_mm"][2]), 25.0, 1e-9); + let own = m1 / 12.0 * 200.0 + m2 / 12.0 * 200.0; + let shift = m1 * 400.0 + m2 * 400.0; + diag(&tensor(&mass["inertia_world_kg_mm2"]), [own + shift, own + shift, own], 1e-9); +} + +#[test] +fn a_nested_occurrence_no_joint_places_moves_with_its_parent() { + let mut s = Session::default(); + let outer = run(&mut s, "component.create", json!({"name": "Assembly", "grounded": false})); + let inner = run(&mut s, "component.create", json!({"name": "Inner", "grounded": false})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + let r = run(&mut s, "assembly.mass_properties", json!({})); + let (o, i) = (outer["occurrence"].as_u64().unwrap_or(0), inner["occurrence"].as_u64().unwrap_or(0)); + assert_eq!(occurrence(&r, o)["group"], occurrence(&r, i)["group"]); + assert!(occurrence(&r, o)["mass"].is_null(), "the outer component has no bodies of its own"); + assert_eq!(occurrence(&r, i)["path"], json!([o, i])); +} + +#[test] +fn hostile_and_degenerate_inputs_never_panic() { + // An empty design: the design itself, without mass. + let mut s = Session::default(); + let r = run(&mut s, "assembly.mass_properties", json!({})); + assert_eq!(r["occurrences"].as_array().map(Vec::len), Some(1)); + assert!(r["occurrences"][0]["mass"].is_null()); + // A pending placement that is not finite is refused, not propagated. + let (_, occ, _) = part(&mut s, "Block", [10.0, 10.0, 10.0], "Steel"); + let mut bad = solidcraft_doc::IDENTITY; + bad[3][0] = f64::NAN; + s.pending_moves.insert(occ, bad); + assert!(s.execute("assembly.mass_properties", &json!({})).is_err()); + let mut huge = solidcraft_doc::IDENTITY; + huge[0][0] = 1e200; + huge[1][1] = 1e200; + huge[2][2] = 1e200; + s.pending_moves.insert(occ, huge); + assert!(s.execute("assembly.mass_properties", &json!({})).is_err()); + // A flattening placement: no volume, so no mass, and no panic. + let mut flat = solidcraft_doc::IDENTITY; + flat[2][2] = 0.0; + s.pending_moves.insert(occ, flat); + let r = run(&mut s, "assembly.mass_properties", json!({})); + assert!(occurrence(&r, occ)["mass"].is_null(), "{r}"); + // A rigid joint to an occurrence that is gone is ignored. + s.pending_moves.clear(); + let mut doc = (*s.doc).clone(); + if let Some(j) = doc.assembly.joints.first_mut() { + j.b.occurrence = 999_999; + } + s.doc = std::sync::Arc::new(doc); + run(&mut s, "assembly.mass_properties", json!({})); + + // The combination itself. + assert_eq!(MassBody::combine(&[]), None); + let neg = MassBody { mass: -1.0, ..MassBody::default() }; + assert_eq!(MassBody::combine(&[neg]), None); + let nan = MassBody { mass: 1.0, center: Vec3::new(f64::NAN, 0.0, 0.0), ..MassBody::default() }; + assert_eq!(MassBody::combine(&[nan]), None); + let inf = MassBody { mass: f64::INFINITY, ..MassBody::default() }; + assert_eq!(MassBody::combine(&[inf]), None); + // A part whose tensor is unknown leaves the total's unknown, not wrong. + let known = MassBody { mass: 1.0, center: Vec3::ZERO, inertia: Some([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) }; + let unknown = MassBody { mass: 1.0, center: Vec3::new(2.0, 0.0, 0.0), inertia: None }; + let both = MassBody::combine(&[known, unknown]).unwrap_or_else(|| panic!("positive mass")); + assert_eq!(both.inertia, None); + near(both.center.x, 1.0, 1e-12); +} + +#[test] +fn combining_two_point_like_bodies_adds_the_parallel_axis_terms() { + let unit: Tensor = [[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]]; + let a = MassBody { mass: 1.0, center: Vec3::new(0.0, 0.0, 0.0), inertia: Some(unit) }; + let b = MassBody { mass: 3.0, center: Vec3::new(4.0, 4.0, 0.0), inertia: Some(unit) }; + let t = MassBody::combine(&[a, b]).and_then(|t| t.inertia).unwrap_or_else(|| panic!("combines")); + // Centre (3, 3, 0); a is (−3, −3) from it, b (1, 1): Σ m d² terms and −Σ m dx dy. + let (sxx, sxy) = (1.0 * 9.0 + 3.0 * 1.0, 1.0 * 9.0 + 3.0 * 1.0); + near(t[0][0], 2.0 + sxx, 1e-12); + near(t[1][1], 4.0 + sxx, 1e-12); + near(t[2][2], 6.0 + 2.0 * sxx, 1e-12); + near(t[0][1], -sxy, 1e-12); + near(t[1][0], -sxy, 1e-12); +} diff --git a/crates/engine/src/cmd/material_card_persistence_tests.rs b/crates/engine/src/cmd/material_card_persistence_tests.rs index 6afe0d20f..0af0766ab 100644 --- a/crates/engine/src/cmd/material_card_persistence_tests.rs +++ b/crates/engine/src/cmd/material_card_persistence_tests.rs @@ -77,6 +77,9 @@ fn omission_retains_null_clears_and_unrelated_material_edits_retain_cards() { .and_then(|c| c.in_format(solidcraft_io::catalog::V1_FORMAT)) .unwrap_err(); assert!(error.to_string().contains("engineering cards")); + // A library copy carries the card as it is. + let copy = solidcraft_io::catalog::LibraryMaterial::from_material(&s.doc.user_materials[1]).unwrap(); + assert_eq!(copy.physical_card, original); s.execute("material.edit", &json!({"material":"Renamed","physical_card":null})).unwrap(); assert!(s.doc.user_materials[1].physical_card.is_none()); s.execute("edit.undo", &json!({})).unwrap(); @@ -137,15 +140,20 @@ fn configurations_rename_and_paste_new_keep_design_owned_material_semantics() { assert!(loaded.configs.rows.iter().any(|r| r.cells.iter().any(|c| c == "Renamed candidate"))); } +/// Formats 20 (before engineering cards) and 21 (with them), as they were written (no pending +/// format list): materials without cards come in with their optical look unchanged, upgraded. #[test] -fn format21_materials_without_cards_keep_their_optical_look() { +fn format20_and_21_materials_without_cards_keep_their_optical_look() { let s = fixture(); - let mut saved = serde_json::to_value(&*s.doc).unwrap(); - saved["format"] = json!("solidcraft/21"); - let loaded = Document::from_json(&saved.to_string()).unwrap(); - assert_eq!(loaded.user_materials, s.doc.user_materials); - assert!(loaded.user_materials[0].physical_card.is_none()); - assert_eq!(loaded.format, solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT)); + for format in [20, 21] { + let mut saved = serde_json::to_value(&*s.doc).unwrap(); + saved["format"] = json!(format!("solidcraft/{format}")); + saved.as_object_mut().unwrap().remove("format_pending"); + let loaded = Document::from_json(&saved.to_string()).unwrap(); + assert_eq!(loaded.user_materials, s.doc.user_materials, "format {format}"); + assert!(loaded.user_materials[0].physical_card.is_none(), "format {format}"); + assert_eq!(loaded.format, solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT), "format {format}"); + } } #[test] @@ -208,17 +216,6 @@ fn native_container_keeps_large_si_card_values_sources_conditions_and_density_se assert_eq!(material["physical_validation"]["source_review_required"], json!(["fixture"])); } -#[test] -fn format20_materials_without_cards_upgrade_to21_without_changing_their_optical_look() { - let s = fixture(); - let mut saved = serde_json::to_value(&*s.doc).unwrap(); - saved["format"] = json!("solidcraft/20"); - let loaded = Document::from_json(&saved.to_string()).unwrap(); - assert_eq!(loaded.user_materials, s.doc.user_materials); - assert!(loaded.user_materials[0].physical_card.is_none()); - assert_eq!(loaded.format, solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT)); -} - #[test] fn card_number_admission_preserves_metadata_without_exempting_other_material_fields() { let s = fixture(); diff --git a/crates/engine/src/cmd/material_properties.rs b/crates/engine/src/cmd/material_properties.rs index cc6dce33f..d4fa9df33 100644 --- a/crates/engine/src/cmd/material_properties.rs +++ b/crates/engine/src/cmd/material_properties.rs @@ -1,15 +1,24 @@ //! Read-only validation of candidate engineering data; no assignment or simulation. use super::CommandSpec; use crate::params::bad; +use crate::schema::material_properties::{CardModulus, CardValidated, DirectionalModulusParams, ValidateCardParams}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; -use serde_json::{Value, json}; +use serde_json::Value; -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("material.properties.validate", "Validate Physical Material Data", validate) +const VALIDATE_CONTRACT: TypedContract = TypedContract::new(); +const DIRECTIONAL_CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("material.properties.validate", "Validate Physical Material Data", crate::checked!("material.properties.validate", validate)) .icon("material") .noundo() .doc_only() + .contract(&VALIDATE_CONTRACT) + .output(output_schema_for::) .params("card: schema_version 1 engineering material card in SI units. Returns numerical consistency, derived isotropic moduli, missing conditions and sources needing review. Read-only; does not assign/save properties or provide an analysis solver. See docs/physical-material-cards.md"), - CommandSpec::new("material.properties.directional", "Directional Elastic Modulus", directional).icon("material").noundo().doc_only() + CommandSpec::new("material.properties.directional", "Directional Elastic Modulus", crate::checked!("material.properties.directional", directional)).icon("material").noundo().doc_only() + .contract(&DIRECTIONAL_CONTRACT) + .output(output_schema_for::) .params("card: schema_version 1 engineering material card; direction: three finite nonzero-vector components in the card's material-local axes. Returns normalized direction, Young modulus in Pa and source/condition review. Read-only constitutive query; no structural solver, persistence or body-axis assignment. See docs/physical-material-cards.md")]; fn directional(_: &mut Session, params: &Value) -> Result { @@ -28,7 +37,7 @@ fn directional(_: &mut Session, params: &Value) -> Result { let direction = [component(0)?, component(1)?, component(2)?]; let card = solidcraft_doc::physical_material::admit_card(value).map_err(|e| bad(cmd, e.to_string()))?; let response = card.directional_modulus(direction).map_err(|e| bad(cmd, e.to_string()))?; - serde_json::to_value(response).map_err(|e| bad(cmd, e.to_string())) + serde_json::to_value(CardModulus::from(response)).map_err(|e| bad(cmd, e.to_string())) } fn validate(_: &mut Session, params: &Value) -> Result { @@ -38,13 +47,15 @@ fn validate(_: &mut Session, params: &Value) -> Result { .ok_or_else(|| bad("material.properties.validate", "expected {card: ...}"))?; let card = object.get("card").ok_or_else(|| bad("material.properties.validate", "missing card"))?; let result = solidcraft_doc::physical_material::validate_card(card).map_err(|e| bad("material.properties.validate", e.to_string()))?; - Ok(json!({"valid":true,"validation":result})) + let reply = CardValidated { valid: true, validation: result.into(), param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| bad("material.properties.validate", e.to_string())) } #[cfg(test)] mod tests { use super::*; - use crate::{doc::Document, product_scene}; + use crate::doc::Document; + use serde_json::json; use std::sync::Arc; fn card() -> Value { @@ -69,43 +80,6 @@ mod tests { s } - #[test] - fn card_edits_preserve_mass_optics_and_geometry_and_survive_undo_reopen() { - let mut s = fixture(); - let scene = product_scene::extract(&s).unwrap(); - let mass = s.execute("component.properties", &json!({})).unwrap(); - let before_undo = s.undo.len(); - let out = s.execute("material.edit", &json!({"material":"Synthetic","physical_card":card()})).unwrap(); - assert_eq!(out["physical_validation"]["isotropic_moduli"]["shear_pa"], 4.9e9); - assert_eq!(out["density_comparison"]["assigned_density_kg_m3"], 800.0); - assert_eq!(out["density_comparison"]["matches_within_relative_tolerance"], false); - assert_eq!(out["physical_validation"]["source_review_required"], json!(["fixture"])); - assert_eq!(out["physical_validation"]["analysis_solver_available"], false); - assert_eq!(s.undo.len(), before_undo + 1); - assert_eq!(s.execute("component.properties", &json!({})).unwrap(), mass); - let after = product_scene::extract(&s).unwrap(); - assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &after.meshes[0].mesh)); - assert_eq!(scene.meshes[0].surface, after.meshes[0].surface); - let saved = s.doc.to_json(); - let saved_json: Value = serde_json::from_str(&saved).unwrap(); - assert_eq!(saved_json["format"], crate::doc::format::format_string(crate::doc::format::FORMAT)); - s.execute("edit.undo", &json!({})).unwrap(); - assert!(s.doc.user_materials[0].physical_card.is_none()); - s.execute("edit.redo", &json!({})).unwrap(); - let mut reopened = Session::new(Document::from_json(&saved).unwrap()); - assert_eq!(reopened.execute("component.properties", &json!({})).unwrap(), mass); - assert_eq!(reopened.doc.user_materials, s.doc.user_materials); - let modulus = reopened.doc.user_materials[0].physical_card.as_ref().unwrap().card().directional_modulus([1., 2., 3.]).unwrap(); - assert_eq!(modulus.young_modulus_pa, 12.25e9); - let doc = reopened.doc.clone(); - let before = (reopened.revision, reopened.undo.len(), reopened.camera, reopened.selection.clone()); - let list = reopened.execute("material.list", &json!({})).unwrap(); - let material = list["materials"].as_array().unwrap().iter().find(|m| m["name"] == "Synthetic").unwrap(); - assert_eq!(material["physical_card"], out["physical_card"]); - assert!(Arc::ptr_eq(&doc, &reopened.doc)); - assert_eq!(before, (reopened.revision, reopened.undo.len(), reopened.camera, reopened.selection.clone())); - } - #[test] fn personal_format29_cards_upgrade_to_current_pending_format_without_changing_values() { let mut s = fixture(); @@ -126,184 +100,6 @@ mod tests { assert_eq!(session.execute("component.properties", &json!({})).unwrap(), mass); } - #[test] - fn omission_retains_null_clears_and_unrelated_material_edits_retain_cards() { - let mut s = fixture(); - s.execute("material.create", &json!({"name":"With card","density_g_cm3":0.7,"physical_card":card()})).unwrap(); - let original = s.doc.user_materials[1].physical_card.clone(); - for p in [json!({"density_g_cm3":0.9}), json!({"color":"#112233"}), json!({"name":"Renamed"})] { - let mut p = p; - p["material"] = json!(s.doc.user_materials[1].name); - s.execute("material.edit", &p).unwrap(); - assert_eq!(s.doc.user_materials[1].physical_card, original); - } - let copy = solidcraft_io::catalog::LibraryMaterial::from_material(&s.doc.user_materials[1]).unwrap(); - assert_eq!(copy.physical_card, original); - s.execute("material.edit", &json!({"material":"Renamed","physical_card":null})).unwrap(); - assert!(s.doc.user_materials[1].physical_card.is_none()); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(s.doc.user_materials[1].physical_card, original); - } - - #[test] - fn hostile_cards_refuse_atomically_and_saved_card_admission_is_not_bypassed() { - let mut s = fixture(); - let mut bad = card(); - bad["properties"][1]["data"]["model"]["poisson_ratio"] = json!(0.6); - let mut oversized = card(); - oversized["sources"] = json!(vec![json!({}); 33]); - let mut unknown = card(); - unknown["unrecognized"] = json!(true); - let mut missing = card(); - missing["properties"][0]["source_id"] = json!("missing"); - let doc = s.doc.clone(); - let before = (s.undo.len(), s.redo.len(), s.revision, s.camera, s.selection.clone()); - for candidate in [bad, oversized, unknown, missing, json!(true)] { - assert!(s.execute("material.edit", &json!({"material":"Synthetic","physical_card":candidate})).is_err()); - assert!(s.execute("material.create", &json!({"name":"Refused","density_g_cm3":1,"physical_card":candidate})).is_err()); - assert!(Arc::ptr_eq(&doc, &s.doc)); - assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.camera, s.selection.clone())); - let mut saved = serde_json::to_value(&*s.doc).unwrap(); - saved["user_materials"][0]["physical_card"] = candidate; - assert!(Document::from_json(&saved.to_string()).is_err()); - assert!(serde_json::from_value::(saved).is_err()); - } - // Large finite SI constants are accepted only in this typed card, not geometry. - let mut saved = serde_json::to_value(&*s.doc).unwrap(); - saved["user_materials"][0]["physical_card"] = card(); - assert!(Document::from_json(&saved.to_string()).is_ok()); - saved["hostile_numeric_probe"] = json!(12.25e9); - assert!(Document::from_json(&saved.to_string()).unwrap_err().to_string().contains("number")); - } - - #[test] - fn configurations_rename_and_paste_new_keep_design_owned_material_semantics() { - let mut s = Session::default(); - let part = s.execute("component.create", &json!({"name":"Part"})).unwrap()["component"].as_u64().unwrap(); - s.execute("solid.box", &json!({"body_name":"Specimen","length":10,"width":10,"height":10})).unwrap(); - s.execute("material.create", &json!({"name":"Synthetic","density_g_cm3":0.8,"physical_card":card()})).unwrap(); - s.execute("config.configure", &json!({"materials":["Specimen"]})).unwrap(); - s.execute("config.row", &json!({"name":"Candidate","values":{"material:Specimen":"Synthetic"}})).unwrap(); - s.execute("config.activate", &json!({"row":"Candidate"})).unwrap(); - s.execute("component.activate", &json!({"component":0})).unwrap(); - s.execute("component.paste_new", &json!({"component":part,"translate":[30,0,0]})).unwrap(); - assert_eq!(s.doc.user_materials.len(), 1); - assert_eq!(s.doc.materials.values().filter(|m| *m == "Synthetic").count(), 2); - let original = s.doc.user_materials[0].physical_card.clone(); - s.execute("material.edit", &json!({"material":"Synthetic","name":"Renamed candidate"})).unwrap(); - s.execute("config.activate", &json!({"row":"Default"})).unwrap(); - s.execute("config.activate", &json!({"row":"Candidate"})).unwrap(); - let loaded = Document::from_json(&s.doc.to_json()).unwrap(); - assert_eq!(loaded.user_materials[0].physical_card, original); - assert_eq!(loaded.materials.values().filter(|m| *m == "Renamed candidate").count(), 2); - assert!(loaded.configs.rows.iter().any(|r| r.cells.iter().any(|c| c == "Renamed candidate"))); - } - - #[test] - fn format21_materials_without_cards_keep_their_optical_look() { - let s = fixture(); - let mut saved = serde_json::to_value(&*s.doc).unwrap(); - saved["format"] = json!("solidcraft/21"); - saved.as_object_mut().unwrap().remove("format_pending"); - let loaded = Document::from_json(&saved.to_string()).unwrap(); - assert_eq!(loaded.user_materials, s.doc.user_materials); - assert!(loaded.user_materials[0].physical_card.is_none()); - assert_eq!(loaded.format, crate::doc::format::format_string(crate::doc::format::FORMAT)); - } - - #[test] - fn scalar_catalog_refuses_card_export_without_creating_or_replacing_files_or_history() { - struct ProbeFile(std::path::PathBuf); - impl Drop for ProbeFile { - fn drop(&mut self) { - let _ = std::fs::remove_file(&self.0); - } - } - let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let file = ProbeFile(std::env::temp_dir().join(format!("solidcraft-card-refusal-{}-{unique}.json", std::process::id()))); - let mut s = Session::default(); - s.execute("material.create", &json!({"name":"Card only","density_g_cm3":0.8,"physical_card":card()})).unwrap(); - s.mark_saved(); - let doc = s.doc.clone(); - let history = (s.undo.len(), s.redo.len(), s.revision); - for existing in [false, true] { - if existing { - std::fs::write(&file.0, b"keep existing catalog").unwrap(); - } - for overwrite in [false, true] { - let error = s - .execute("library.export", &json!({"path":file.0,"format":solidcraft_io::catalog::V1_FORMAT,"overwrite":overwrite})) - .unwrap_err(); - assert!(error.to_string().contains("cannot preserve PBR or engineering cards")); - if existing { - assert_eq!(std::fs::read(&file.0).unwrap(), b"keep existing catalog"); - } else { - assert!(!file.0.exists()); - } - assert!(Arc::ptr_eq(&doc, &s.doc)); - assert_eq!((s.undo.len(), s.redo.len(), s.revision), history); - assert!(!s.is_dirty()); - } - } - } - - #[test] - fn native_container_keeps_large_si_card_values_sources_conditions_and_density_separate() { - let mut s = fixture(); - s.execute("material.edit", &json!({"material":"Synthetic","physical_card":card()})).unwrap(); - let before = s.execute("component.properties", &json!({})).unwrap(); - let scene = product_scene::extract(&s).unwrap(); - let native = solidcraft_io::write_design_container(&s.doc).unwrap(); - assert!(solidcraft_io::is_design_container(&native)); - let loaded = solidcraft_io::read_design(&native).unwrap(); - assert_eq!(loaded.format, crate::doc::format::format_string(crate::doc::format::FORMAT)); - assert_eq!(loaded.user_materials, s.doc.user_materials); - let mut reopened = Session::new(loaded); - assert_eq!(reopened.execute("component.properties", &json!({})).unwrap(), before); - assert_eq!(product_scene::extract(&reopened).unwrap().meshes[0].surface, scene.meshes[0].surface); - let list = reopened.execute("material.list", &json!({})).unwrap(); - let material = list["materials"].as_array().unwrap().iter().find(|m| m["name"] == "Synthetic").unwrap(); - assert_eq!(material["physical_card"], serde_json::to_value(s.doc.user_materials[0].physical_card.as_ref().unwrap()).unwrap()); - assert_eq!(material["density_comparison"]["assigned_density_kg_m3"], 800.0); - assert_eq!(material["density_comparison"]["card_density_kg_m3"], 700.0); - assert_eq!(material["physical_validation"]["source_review_required"], json!(["fixture"])); - } - - #[test] - fn format20_materials_without_cards_upgrade_without_changing_their_optical_look() { - let s = fixture(); - let mut saved = serde_json::to_value(&*s.doc).unwrap(); - saved["format"] = json!("solidcraft/20"); - saved.as_object_mut().unwrap().remove("format_pending"); - let loaded = Document::from_json(&saved.to_string()).unwrap(); - assert_eq!(loaded.user_materials, s.doc.user_materials); - assert!(loaded.user_materials[0].physical_card.is_none()); - assert_eq!(loaded.format, crate::doc::format::format_string(crate::doc::format::FORMAT)); - } - - #[test] - fn card_number_admission_preserves_metadata_without_exempting_other_material_fields() { - let s = fixture(); - let mut saved = serde_json::to_value(&*s.doc).unwrap(); - saved["user_materials"][0]["physical_card"] = card(); - let metadata = json!({"org.example.measurement":{"value":12.25e9,"physical_card":{"untyped":12.25e9}}}); - saved["metadata"] = metadata.clone(); - let loaded = Document::from_json(&saved.to_string()).unwrap(); - let reopened = solidcraft_io::read_design(&solidcraft_io::write_design_container(&loaded).unwrap()).unwrap(); - assert_eq!(serde_json::to_value(&reopened.metadata).unwrap(), metadata); - assert_eq!(reopened.user_materials, loaded.user_materials); - - // Only the exact root user-material card receives SI admission. The same key - // nested elsewhere must not exempt a hostile number from geometry limits. - for field in ["appearance", "unrecognized"] { - let mut hostile = saved.clone(); - hostile["user_materials"][0][field] = json!({"physical_card":{"untyped":12.25e9}}); - assert!(Document::from_json(&hostile.to_string()).unwrap_err().to_string().contains("number")); - } - saved["user_materials"][0]["density"] = json!(12.25e9); - assert!(Document::from_json(&saved.to_string()).unwrap_err().to_string().contains("number")); - } - #[test] fn material_inspection_preserves_legacy_entries_and_reports_unknowns_and_density_separately() { let mut s = fixture(); diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rs index f55cbfe99..8a75cbb19 100644 --- a/crates/engine/src/cmd/measure_sel.rs +++ b/crates/engine/src/cmd/measure_sel.rs @@ -5,7 +5,9 @@ //! have a direction (planar faces, straight edges), the angle. use serde_json::{Value, json}; -use solidcraft_geom::{Mesh, UnitVec3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Mesh, UnitVec3}; use super::measure_shape::{Shape, Slot, add_round, centre}; use crate::params::bad; @@ -216,7 +218,7 @@ fn sketch_curve(ss: &solidcraft_doc::SolvedSketch, id: &str) -> Option { /// A profile (closed region of a sketch): its area, and when it is a circle or a slot, its /// sizes. fn profile(ss: &solidcraft_doc::SolvedSketch, index: usize) -> Option { - use solidcraft_geom::{Seg2, Vec2}; + use solidcore_record::{Seg2, Vec2}; let pr = ss.profiles.get(index)?; let outline: Vec = pr.region.outer.polyline(1e-3).iter().map(|p| ss.plane.to_world(*p)).collect(); let mut json = json!({"type": "profile", "area_mm2": pr.region.area()}); @@ -282,10 +284,35 @@ fn face_slot(b: &solidcraft_doc::ModelBody, m: &Mesh, shape: &Shape, pts: &[Vec3 super::measure_shape::slot_from_faces(shape, pts, &surfaces) } -fn describe(s: &Session, sel: &Sel) -> Option { - let st = s.world_state(); +/// `sel` in the placed model `st`. +fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option { let plain = |geo, dir, json| Some(Item { geo, dir, json, shape: Shape::Other, slot: None }); match sel { + Sel::Plane { name } => { + let (point, normal) = plane_named(s, name)?; + Some(Item { + geo: Geo::Points(vec![point]), + dir: Some(normal), + json: json!({"type": "plane", "point": point, "normal": normal}), + shape: Shape::Plane { point, normal: UnitVec3::new(normal)? }, + slot: None, + }) + } + Sel::Axis { name } => { + let (origin, dir) = axis_named(s, name)?; + let (a, b) = (origin - dir * 1e6, origin + dir * 1e6); + Some(Item { + geo: Geo::Points(vec![origin, a, b]), + dir: Some(dir), + json: json!({"type": "axis", "origin": origin, "direction": dir}), + shape: Shape::Line { a, b }, + slot: None, + }) + } + Sel::ConstructionPoint { name } => { + let p = crate::view::construction_points(s).into_iter().find(|(_, n, _)| n == name).map(|(_, _, p)| p)?; + Some(Item { geo: Geo::Points(vec![p]), dir: None, json: json!({"type": "point", "position": p}), shape: Shape::Point(p), slot: None }) + } Sel::Vertex { point, .. } => Some(Item { geo: Geo::Points(vec![*point]), dir: None, @@ -328,7 +355,8 @@ fn describe(s: &Session, sel: &Sel) -> Option { let planar = normals.first().copied().filter(|n0| normals.iter().all(|n| n.dot(*n0) > 1.0 - 1e-6)); let mut json = json!({"type": "face", "area_mm2": area, "planar": planar.is_some()}); let verts: Vec = tris.iter().flat_map(|t| t.iter().copied()).collect(); - let shape = match solidcraft_kernel::face_surface(&b.body, *index) { + let surface = solidcraft_kernel::face_surface(&b.body, *index); + let shape = match surface { Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }) => { super::measure_shape::cylinder(origin, axis, radius, &verts).unwrap_or(Shape::Other) } @@ -340,6 +368,7 @@ fn describe(s: &Session, sel: &Sel) -> Option { _ => Shape::Other, }; add_round(&mut json, &shape); + super::measure_shape::add_curved(&mut json, surface); let slot = if matches!(shape, Shape::Round { .. }) && !shape.full() { face_slot(b, &m, &shape, &verts) } else { None }; if let Some(sl) = &slot { json["slot"] = sl.json(); @@ -354,8 +383,8 @@ fn describe(s: &Session, sel: &Sel) -> Option { let v = m.measure().volume; plain(Geo::Tris(tris), None, json!({"type": "body", "name": name, "closed": closed, "volume_mm3": closed.then_some(v)})) } - Sel::SketchCurve { id, sketch } => sketch_curve(sketch_of(s, &st, *sketch, |sk| sk.curve_index(id).is_some())?, id), - Sel::ExternalSketchCurve { sketch, id } => sketch_curve(sketch_of(s, &st, Some(*sketch), |_| true)?, id), + Sel::SketchCurve { id, sketch } => sketch_curve(sketch_of(s, st, *sketch, |sk| sk.curve_index(id).is_some())?, id), + Sel::ExternalSketchCurve { sketch, id } => sketch_curve(sketch_of(s, st, Some(*sketch), |_| true)?, id), Sel::SketchPoint { id } | Sel::ExternalSketchPoint { id, .. } => { let given = match sel { Sel::ExternalSketchPoint { sketch, .. } => Some(*sketch), @@ -366,7 +395,7 @@ fn describe(s: &Session, sel: &Sel) -> Option { Some((k, p)) if given.is_none() => (Some(k), p), _ => (given, id.as_str()), }; - let ss = sketch_of(s, &st, given, |sk| sk.point_index(id).is_some())?; + let ss = sketch_of(s, st, given, |sk| sk.point_index(id).is_some())?; let p = ss.plane.to_world(ss.sketch.points.get(ss.sketch.point_index(id)?)?.pos); Some(Item { geo: Geo::Points(vec![p]), @@ -384,7 +413,8 @@ fn describe(s: &Session, sel: &Sel) -> Option { /// A picked item's exact shape with its points (an edge's polyline) and triangles (a face's), /// as Measure sees it: what [`crate::snap`] takes an item's centres, middle and ends from. pub(crate) fn shape_of(s: &Session, sel: &Sel) -> Option<(Shape, Vec, Vec<[Vec3; 3]>)> { - let item = describe(s, sel)?; + let world = s.world_state().ok()?; + let item = describe(s, &world, sel)?; Some(match item.geo { Geo::Points(p) => (item.shape, p, Vec::new()), Geo::Tris(t) => (item.shape, Vec::new(), t), @@ -397,6 +427,122 @@ fn sample(v: &[T], max: usize) -> Vec { } /// Closest pair of points between two pieces of geometry. +/// An origin plane (XY, XZ, YZ) or a construction plane's point and normal. +fn plane_named(s: &Session, name: &str) -> Option<(Vec3, Vec3)> { + match name { + "XY" => Some((Vec3::ZERO, Vec3::Z)), + "XZ" => Some((Vec3::ZERO, Vec3::Y)), + "YZ" => Some((Vec3::ZERO, Vec3::X)), + _ => crate::view::construction_planes(s).into_iter().find(|(_, n, _)| n == name).map(|(_, _, p)| (p.origin, p.x.cross(p.y))), + } +} + +/// An origin axis (X, Y, Z) or a construction axis's point and unit direction. +fn axis_named(s: &Session, name: &str) -> Option<(Vec3, Vec3)> { + match name { + "X" => Some((Vec3::ZERO, Vec3::X)), + "Y" => Some((Vec3::ZERO, Vec3::Y)), + "Z" => Some((Vec3::ZERO, Vec3::Z)), + _ => crate::view::construction_axes(s).into_iter().find(|(_, n, _, _)| n == name).map(|(_, _, origin, dir)| (origin, dir)), + } +} + +/// The closest points of two exact shapes, where the sampled points would be wrong: a plane or +/// an axis runs on, so a point set of it is not the object. +fn exact_min(a: &Shape, b: &Shape) -> Option<(f64, Vec3, Vec3)> { + use Shape::*; + let to_plane = |p: Vec3, point: Vec3, normal: UnitVec3| { + let n = normal.vec(); + let h = (p - point).dot(n); + (h.abs(), p, p - n * h) + }; + let to_line = |p: Vec3, a: Vec3, b: Vec3| { + let d = b - a; + let t = if d.len() > 1e-12 { ((p - a).dot(d) / d.dot(d)).clamp(0.0, 1.0) } else { 0.0 }; + let q = a + d * t; + (p.dist(q), p, q) + }; + match (a, b) { + (Point(p), Plane { point, normal }) => Some(to_plane(*p, *point, *normal)), + (Plane { point, normal }, Point(p)) => { + let (d, f, t) = to_plane(*p, *point, *normal); + Some((d, t, f)) + } + (Point(p), Line { a: la, b: lb }) => Some(to_line(*p, *la, *lb)), + (Line { a: la, b: lb }, Point(p)) => { + let (d, f, t) = to_line(*p, *la, *lb); + Some((d, t, f)) + } + (Point(p), Point(q)) => Some((p.dist(*q), *p, *q)), + (Plane { point: p1, normal: n1 }, Plane { point: p2, normal: n2 }) => { + let (v1, v2) = (n1.vec(), n2.vec()); + if v1.cross(v2).len() < 1e-9 { + let h = (*p2 - *p1).dot(v1); + Some((h.abs(), *p1, *p2 - v1 * h)) + } else { + // They meet: a point on the line of intersection has distance zero. + let dir = v1.cross(v2); + let t = -(*p1 - *p2).dot(v2) / dir.dot(v2); + let p = *p1 + dir * t; + Some((0.0, p, p)) + } + } + (Plane { point, normal }, Line { a: la, b: lb }) => { + let d = *lb - *la; + let den = d.dot(normal.vec()); + if den.abs() < 1e-9 { + let (dist, _, q) = { + let h = (*la - *point).dot(normal.vec()); + (h.abs(), *la, *la - normal.vec() * h) + }; + Some((dist, q, *la)) + } else { + let t = (*point - *la).dot(normal.vec()) / den; + let p = *la + d * t; + Some((0.0, p, p)) + } + } + (Line { a: la, b: lb }, Plane { point, normal }) => { + let d = *lb - *la; + let den = d.dot(normal.vec()); + if den.abs() < 1e-9 { + let h = (*la - *point).dot(normal.vec()); + Some((h.abs(), *la, *la - normal.vec() * h)) + } else { + let t = (*point - *la).dot(normal.vec()) / den; + let p = *la + d * t; + Some((0.0, p, p)) + } + } + (Line { a: a1, b: b1 }, Line { a: a2, b: b2 }) => { + let (d1, d2) = (*b1 - *a1, *b2 - *a2); + let n = d1.cross(d2); + if n.len() < 1e-9 { + let (dist, _, q) = { + let dd = d1; + let t = if dd.len() > 1e-12 { ((*a2 - *a1).dot(dd) / dd.dot(dd)).clamp(0.0, 1.0) } else { 0.0 }; + let q = *a1 + dd * t; + ((*a2).dist(q), *a2, q) + }; + Some((dist, q, *a2)) + } else { + let w = *a1 - *a2; + let a = d1.dot(d1); + let b = d1.dot(d2); + let c = d2.dot(d2); + let d = d1.dot(w); + let e = d2.dot(w); + let den = a * c - b * b; + let (t, s) = if den.abs() < 1e-12 { (0.0, e / c) } else { ((b * e - c * d) / den, (a * e - b * d) / den) }; + let p = *a1 + d1 * t; + let q = *a2 + d2 * s; + Some((p.dist(q), p, q)) + } + } + _ => None, + } +} + fn closest(a: &Geo, b: &Geo) -> Option<(Vec3, Vec3)> { let pts_to_tris = |pts: &[Vec3], tris: &[[Vec3; 3]]| -> Option<(Vec3, Vec3)> { let pts = sample(pts, MAX_POINTS); @@ -491,7 +637,7 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result { if list.is_empty() || list.len() > 1000 { return Err(bad(cmd, "measure one or two items")); } - let st = s.world_state(); + let st = s.world_state()?; let mut sels = Vec::new(); for value in list { let sel = match value.get("type").and_then(Value::as_str) { @@ -510,10 +656,12 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result { return Err(bad(cmd, "measure one or two items")); } } + let world = s.world_state()?; let mut described = Vec::new(); for x in &sels { described.push( - describe(s, x).ok_or_else(|| bad(cmd, "an item can't be measured (pick vertices, edges, faces, bodies, sketch curves or profiles)"))?, + describe(s, &world, x) + .ok_or_else(|| bad(cmd, "an item can't be measured (pick vertices, edges, faces, bodies, sketch curves or profiles)"))?, ); } let mut out = json!({"items": described.iter().map(|d| d.json.clone()).collect::>()}); @@ -555,6 +703,13 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result { out["delta"] = json!(q - p); out["min"] = json!(d); } + if let Some((d, p, q)) = exact_min(&a.shape, &b.shape) { + out["distance_mm"] = json!(d); + out["from"] = json!(p); + out["to"] = json!(q); + out["delta"] = json!(q - p); + out["min"] = json!(d); + } if let (Some((p, q)), Some(d)) = (far, max) { out["max"] = json!(d); out["max_from"] = json!(p); diff --git a/crates/engine/src/cmd/measure_shape.rs b/crates/engine/src/cmd/measure_shape.rs index 71fb6904a..eb61dddfd 100644 --- a/crates/engine/src/cmd/measure_shape.rs +++ b/crates/engine/src/cmd/measure_shape.rs @@ -4,7 +4,9 @@ //! round item measures from its centre or axis, with the closest and farthest distances too. use serde_json::{Value, json}; -use solidcraft_geom::{UnitVec3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::UnitVec3; +use solidcraft_geom::prelude::*; use std::f64::consts::{PI, TAU}; @@ -68,6 +70,27 @@ pub(crate) fn add_round(v: &mut Value, shape: &Shape) { }); } +/// The radius of a toroidal or spherical face, added to its description: a fillet round a +/// circular edge is a torus whose tube radius is the fillet's (`major_radius` is the ring +/// through the middle of the rolling ball), a ball or a spherical corner patch a sphere. These +/// faces have no axis to measure from, so they stay out of [`Shape`]. +pub(crate) fn add_curved(v: &mut Value, surface: Option) { + use solidcraft_kernel::FaceSurface; + let (radius, kind) = match surface { + Some(FaceSurface::Torus { minor, major, .. }) if minor.is_finite() && minor > 0.0 => { + if major.is_finite() { + v["major_radius"] = json!(major.abs()); + } + (minor, "torus") + } + Some(FaceSurface::Sphere { radius, .. }) if radius.is_finite() && radius > 0.0 => (radius, "sphere"), + _ => return, + }; + v["diameter"] = json!(2.0 * radius); + v["radius"] = json!(radius); + v["surface"] = json!(kind); +} + /// Cylinder `axis` through `origin` of radius `radius` over the points of its face: the /// round shape, centred level with the middle of the face, with its extent and coverage. pub(crate) fn cylinder(origin: Vec3, axis: UnitVec3, radius: f64, pts: &[Vec3]) -> Option { @@ -267,9 +290,9 @@ impl Slot { /// sides. `arcs` are (centre, radius, swept angle) with pieces of one end already merged, /// `lines` the straight pieces (2D, in the sketch plane). pub(crate) fn slot_outline( - arcs: &[(solidcraft_geom::Vec2, f64, f64)], - lines: &[(solidcraft_geom::Vec2, solidcraft_geom::Vec2)], -) -> Option<(solidcraft_geom::Vec2, solidcraft_geom::Vec2, f64)> { + arcs: &[(solidcore_record::Vec2, f64, f64)], + lines: &[(solidcore_record::Vec2, solidcore_record::Vec2)], +) -> Option<(solidcore_record::Vec2, solidcore_record::Vec2, f64)> { let [(c1, r1, s1), (c2, r2, s2)] = arcs else { return None }; let tol = 1e-6 * (1.0 + r1.abs() + c1.dist(*c2)); if (r1 - r2).abs() > tol || (s1.abs() - PI).abs() > 1e-4 || (s2.abs() - PI).abs() > 1e-4 || c1.dist(*c2) <= tol || lines.is_empty() { @@ -277,7 +300,7 @@ pub(crate) fn slot_outline( } let along = (*c2 - *c1).normalized()?; // Every straight piece runs along the slot, `r` to one side of the centre line. - let side = |p: solidcraft_geom::Vec2| (p - *c1).cross(along); + let side = |p: solidcore_record::Vec2| (p - *c1).cross(along); let ok = lines.iter().all(|(a, b)| { let d = *b - *a; d.cross(along).abs() <= tol * (1.0 + d.len()) && (side(*a).abs() - r1).abs() <= tol && (side(*b).abs() - r1).abs() <= tol @@ -338,7 +361,7 @@ pub(crate) fn slot_from_faces(picked: &Shape, picked_pts: &[Vec3], faces: &[(sol #[cfg(test)] mod tests { use super::*; - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; fn circle(c: Vec3, r: f64) -> Shape { Shape::Round { center: c, axis: UnitVec3::Z, radius: r, angle: TAU, planar: true, lo: 0.0, hi: 0.0 } diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs index 44cb8eee1..48c1c338c 100644 --- a/crates/engine/src/cmd/metadata.rs +++ b/crates/engine/src/cmd/metadata.rs @@ -12,29 +12,57 @@ use solidcraft_doc::metadata::{self, MAX_KEYS, Owner, PART_ONLY}; use super::CommandSpec; use crate::params::{bad, str_}; +use crate::schema::metadata::{MetadataParams, MetadataRemoveParams, MetadataRemoveResult, MetadataResult, MetadataSetParams, MetadataSetResult}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; +const READ_CONTRACT: TypedContract = TypedContract::new(); +const SET_CONTRACT: TypedContract = TypedContract::new(); +const REMOVE_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("document.metadata", "Design Properties", read).icon("settings").noundo().doc_only().params( - "→ metadata: the design's metadata object as saved (other tools' keys too); properties: each of SolidCraft's design \ - properties (project, part number, revision…), its text or null (absent, or not text)", - ), - CommandSpec::new("document.metadata.set", "Change Design Properties", set).icon("settings").doc_only().params( - "key and value, or values: {key: value, …} (all or nothing, one undo step). SolidCraft's keys, the ones document.metadata's \ - properties lists, take text (\"\" or null removes); another tool's data goes under its reverse-DNS key such as \ - com.example.tool (an object; null removes) → metadata, changed: [keys]", - ), - CommandSpec::new("document.metadata.remove", "Remove Design Property", remove) + CommandSpec::new("document.metadata", "Design Properties", crate::checked!("document.metadata", read)) + .icon("settings") + .noundo() + .doc_only() + .contract(&READ_CONTRACT) + .output(output_schema_for::) + .params( + "→ metadata: the design's metadata object as saved (other tools' keys too); properties: each of SolidCraft's design \ + properties (project, part number, revision…), its text or null (absent, or not text)", + ), + CommandSpec::new("document.metadata.set", "Change Design Properties", crate::checked!("document.metadata.set", set)) + .icon("settings") + .doc_only() + .contract(&SET_CONTRACT) + .output(output_schema_for::) + .params( + "key and value, or values: {key: value, …} (all or nothing, one undo step). SolidCraft's keys, the ones document.metadata's \ + properties lists, take text (\"\" or null removes); another tool's data goes under its reverse-DNS key such as \ + com.example.tool (an object; null removes) → metadata, changed: [keys]", + ), + CommandSpec::new("document.metadata.remove", "Remove Design Property", crate::checked!("document.metadata.remove", remove)) .icon("delete") .doc_only() + .contract(&REMOVE_CONTRACT) + .output(output_schema_for::) .params("key, or keys: [keys] (any key, also one another tool wrote) → metadata, removed: [keys that were there]"), ]; +/// A reply built from its schema's type, so the two can't drift apart. +fn reply(cmd: &str, r: impl serde::Serialize) -> Result { + serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string())) +} + +/// SolidCraft's properties in `m`, each its text or null. +fn properties(m: &Metadata) -> Map { + metadata::keys(Owner::Design).map(|k| (k.name.to_string(), json!(m.text(k.name)))).collect() +} + /// What reading `m` answers: the object as saved, and SolidCraft's properties, each its text or /// null. pub(super) fn reading(m: &Metadata) -> Value { - let properties: Map = metadata::keys(Owner::Design).map(|k| (k.name.to_string(), json!(m.text(k.name)))).collect(); - json!({"metadata": m, "properties": properties}) + json!({"metadata": m, "properties": properties(m)}) } /// `m` with a call's `key` and `value`, or its `values`, set (all or nothing), and the keys that @@ -86,24 +114,27 @@ pub(super) fn removing(cmd: &str, m: &Metadata, p: &Value) -> Result<(Metadata, } fn read(s: &mut Session, _: &Value) -> Result { - Ok(reading(&s.doc.metadata)) + let m = &s.doc.metadata; + reply("document.metadata", MetadataResult { metadata: m.0.clone(), properties: properties(m) }) } fn set(s: &mut Session, p: &Value) -> Result { - let (next, changed) = setting("document.metadata.set", &s.doc.metadata, p)?; + let cmd = "document.metadata.set"; + let (next, changed) = setting(cmd, &s.doc.metadata, p)?; // Only a real change touches the design (an undo step, unsaved changes). if next != s.doc.metadata { s.doc_mut().metadata = next; } - Ok(json!({"metadata": s.doc.metadata, "changed": changed})) + reply(cmd, MetadataSetResult { metadata: s.doc.metadata.0.clone(), changed, param_warnings: Vec::new() }) } fn remove(s: &mut Session, p: &Value) -> Result { - let (next, removed) = removing("document.metadata.remove", &s.doc.metadata, p)?; + let cmd = "document.metadata.remove"; + let (next, removed) = removing(cmd, &s.doc.metadata, p)?; if !removed.is_empty() { s.doc_mut().metadata = next; } - Ok(json!({"metadata": s.doc.metadata, "removed": removed})) + reply(cmd, MetadataRemoveResult { metadata: s.doc.metadata.0.clone(), removed, param_warnings: Vec::new() }) } #[cfg(test)] diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 9325c607f..5975713ca 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -24,13 +24,17 @@ mod bom; mod browser; pub(crate) mod clearance; mod clipboard; +mod clipboard_foreign; mod compare; +mod compare_picture; +#[cfg(test)] +mod compare_picture_tests; mod component; mod component_clone; mod component_clone_assembly; mod construct; mod delete; -mod diagnostics; +pub(crate) mod diagnostics; mod drawing; mod drawing_balloon; mod drawing_dimension; @@ -48,19 +52,27 @@ mod features_more; mod join_pieces; pub(crate) use bom::{SAME_AS_COMPONENT, occurrence_bom_type, record_item_numbers}; pub(crate) use component::{path_ids, refuse_filled_virtual}; -pub(crate) use construct::{GeoForm, GeoFormError, REF as GEO_REF_FORMS, SKETCH_PART, geo_form, is_model_axis}; +pub(crate) use construct::{GeoForm, GeoFormError, REF as GEO_REF_FORMS, SKETCH_PART, geo_form, is_model_axis, plane_axis_point_kind}; pub use drawing_ui::pending_icon as drawing_pending_icon; pub(crate) use face::{FaceRefForm, face_ref_form}; pub(crate) use features::profiles as feature_profiles; pub(crate) use features::{EdgeRefForm, PLANE_FORMS, axis_dir_form, axis_line_object, edge_ref_form, explicit_plane, plane_name_problem, sketch_key}; pub use features::{auto_operation, extrude_reach, shown_scope}; +pub use file::open_steps::OpenSteps; +pub(crate) use inspect::color_param; pub use join_pieces::{Addition, addition}; +pub use parts::part_length_label; pub use sketch::dimension_roles; pub(crate) use sketch::face::face_pick_form; -pub use sketch_construction::{ConstructionLine, construction_line_choice, construction_line_mode, construction_line_solutions}; +pub use sketch_construction::{ + ConstructionLine, construction_line_choice, construction_line_mode, construction_line_solutions, construction_line_takes_length, + construction_segment, +}; +pub use sketch_create::{tangent_arc_preview, tangent_arc_starts_at}; pub use sketch_import::drawing_import_command; pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece}; pub use view_dxf::sketch::exportable as view_dxf_exportable; +pub(crate) use view_navigation::camera_form; pub use view_navigation::standard_view; mod component_link; pub use component_link::resolve_design_links; @@ -72,6 +84,7 @@ pub(crate) mod inspect; mod interference; pub(crate) mod joints; mod libraries; +pub mod mass_properties; mod material_properties; mod materials; mod measure_sel; @@ -88,9 +101,11 @@ pub(crate) use measure_sel::{measure_items, shape_of}; pub(crate) use measure_shape::Shape; #[cfg(test)] mod kernel_heal_tests; +mod panels; mod parameter_sweep; mod parameters; mod plastic; +mod print_face; mod render; mod render_ui; #[cfg(test)] @@ -98,11 +113,12 @@ mod script_tests; mod sheet; pub(crate) use sheet::{ FlangeType, ThenStep, flange_edge, flange_edge_list, flange_position, flange_type, fold_points, fold_position, perforation_pattern, sheet_points, - then_list, + sheet_rule_name, then_list, }; mod silhouette; mod sketch; pub(crate) use sketch::author_path_for_rebind; +pub(crate) use sketch::collapse_reason; pub(crate) use sketch::created as sketch_created; mod canvas_sketch; mod sketch_3d; @@ -289,6 +305,12 @@ impl CommandSpec { other => other, } } + /// The refusal this command gives when it is not available in this session: none when it + /// is. It is the engine's own wording (`EngineError::Disabled`), so a caller that only has + /// the message can tell it from a failure of the command itself. + pub fn disabled_refusal(&self, s: &Session) -> Option { + (self.enabled)(s).err().map(|why| crate::EngineError::Disabled(self.id.to_string(), why).to_string()) + } pub fn info(&self, s: &Session) -> CommandInfo { let e = self.allowed(s); let (label, icon) = match self.id { @@ -372,9 +394,11 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(joints::COMMANDS.iter()); v.extend(clearance::COMMANDS.iter()); v.extend(motion::COMMANDS.iter()); + v.extend(panels::COMMANDS.iter()); v.extend(config::COMMANDS.iter()); v.extend(parts::COMMANDS.iter()); v.extend(bom::COMMANDS.iter()); + v.extend(mass_properties::COMMANDS.iter()); v.extend(browser::COMMANDS.iter()); v.extend(delete::COMMANDS.iter()); v.extend(edit::COMMANDS.iter()); @@ -384,9 +408,11 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(parameters::COMMANDS.iter()); v.extend(parameter_sweep::COMMANDS.iter()); v.extend(file::COMMANDS.iter()); + v.extend(print_face::COMMANDS.iter()); v.extend(metadata::COMMANDS.iter()); v.extend(inspect::COMMANDS.iter()); v.extend(compare::COMMANDS.iter()); + v.extend(compare_picture::COMMANDS.iter()); v.extend(silhouette::COMMANDS.iter()); v.extend(materials::COMMANDS.iter()); v.extend(material_properties::COMMANDS.iter()); @@ -442,6 +468,20 @@ pub(crate) fn did_you_mean(id: &str) -> String { } } +/// "no body `name`", and the closest of `bodies` when it is near enough to be a typo or another +/// case of the same name (`b` for `B`): `no body `Bdy`; did you mean `Body`?` (#9740). +pub(crate) fn no_body<'a>(name: &str, bodies: impl IntoIterator) -> String { + let want = name.to_lowercase(); + let near = (want.chars().count() / 3).max(1); + let closest = (want.len() <= 256) + .then(|| bodies.into_iter().map(|b| (edit_distance(&want, &b.to_lowercase()), b)).filter(|(d, _)| *d <= near).min_by_key(|(d, _)| *d)) + .flatten(); + match closest { + Some((_, b)) => format!("no body `{name}`; did you mean `{b}`?"), + None => format!("no body `{name}`"), + } +} + /// Levenshtein distance: the single-character edits that turn `a` into `b`. pub(crate) fn edit_distance(a: &str, b: &str) -> usize { let b: Vec = b.chars().collect(); diff --git a/crates/engine/src/cmd/model_axis_tests.rs b/crates/engine/src/cmd/model_axis_tests.rs index 5b5ae8521..d8d376400 100644 --- a/crates/engine/src/cmd/model_axis_tests.rs +++ b/crates/engine/src/cmd/model_axis_tests.rs @@ -2,10 +2,11 @@ //! Revolve, Circular Pattern and Plane at Angle turn about a circular edge's or a cylinder's //! axis, and follow it when a parameter moves the cylinder. +use solidcraft_geom::prelude::*; use std::f64::consts::PI; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; use crate::view::construction_planes; @@ -82,7 +83,7 @@ fn surface_revolve_about_a_circular_edge() { ring_profile(&mut s); run(&mut s, "surface.revolve", json!({"sketch": "Profile", "axis": {"edge": [45, 0, 0]}, "angle": "180 deg"})); run(&mut s, "parameters.change", json!({"name": "cx", "expression": "41 mm"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); // A half turn about x = 41: the far side of the profile ends up at x = 41 − 7 ± 1. let b = st.bodies.last().map(|b| b.mesh().bounds()).unwrap(); assert!((b.min.x - (41.0 - 7.0)).abs() < 1e-3, "{b:?}"); @@ -98,15 +99,21 @@ fn circular_pattern_about_a_boss_wall_follows_the_boss() { run(&mut s, "solid.hole", json!({"position": [130, 100, 5], "diameter": 2, "name": "Hole"})); run(&mut s, "solid.pattern.circular", json!({"features": ["Hole"], "axis": {"face": [110, 100, 10]}, "count": 4, "name": "Ring"})); let holes = |s: &Session, cx: f64, r: f64| { - let st = s.world_state(); + let st = s.world_state().unwrap(); let body = &st.bodies[0].body; - [(r, 0.0), (0.0, r), (-r, 0.0), (0.0, -r)].iter().all(|(dx, dy)| !body.contains(Vec3::new(cx + dx, 100.0 + dy, 2.5))) + [(r, 0.0), (0.0, r), (-r, 0.0), (0.0, -r)] + .iter() + .all(|(dx, dy)| body.classify_point(Vec3::new(cx + dx, 100.0 + dy, 2.5)).unwrap() == solidcraft_kernel::PointClass::Outside) }; assert!(holes(&s, 100.0, 30.0), "four holes round the boss"); run(&mut s, "parameters.change", json!({"name": "cx", "expression": "90 mm"})); assert!(holes(&s, 90.0, 40.0), "the copies turn about the boss where it is now"); - let st = s.world_state(); - assert!(st.bodies[0].body.contains(Vec3::new(100.0, 130.0, 2.5)), "not where the boss was"); + let st = s.world_state().unwrap(); + assert_eq!( + st.bodies[0].body.classify_point(Vec3::new(100.0, 130.0, 2.5)).unwrap(), + solidcraft_kernel::PointClass::Inside, + "not where the boss was" + ); } #[test] @@ -158,7 +165,7 @@ fn the_axis_keeps_its_turn_whichever_way_the_edge_runs() { let mut s = shaft(); ring_profile(&mut s); run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"edge": edge}, "angle": "90 deg", "operation": "new"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); st.bodies.last().map(|b| b.mesh().bounds()).unwrap() }; let (top, bottom) = (quarter([45.0, 0.0, 10.0]), quarter([45.0, 0.0, 0.0])); diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index 2580e8c7b..fdafc4a21 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -1,19 +1,25 @@ //! Contact Sets, Motion Study and Exploded views. +use solidcraft_geom::prelude::*; use std::collections::BTreeSet; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::Mat; use solidcraft_doc::joints::{self, JointKind}; use solidcraft_doc::motion::{ContactSet, ExplodedView, MotionStudy, StudyKey}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcraft_geom::Aabb3; use solidcraft_kernel::Body; use super::CommandSpec; use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, place_holding, value}; use crate::params::{bad, bool_, str_, vec3}; +use crate::schema::motion::{FindLimitsParams, FindLimitsResult}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; +const FIND_LIMITS_CONTRACT: TypedContract = TypedContract::new(); + #[path = "motion_analysis.rs"] mod analysis; #[path = "motion_animation.rs"] @@ -101,9 +107,15 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .params(analysis::INTERFERENCE_DOC), CommandSpec::new("joint.sweep", "Sweep Joint", sweep::sweep).icon("interference").params(sweep::SWEEP_DOC), + CommandSpec::new("joint.find_limits", "Find Joint Limits", crate::checked!("joint.find_limits", sweep::find_limits)) + .icon("interference") + .noundo() + .contract(&FIND_LIMITS_CONTRACT) + .output(output_schema_for::) + .params(sweep::FIND_LIMITS_DOC), CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(), CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"), - CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").params( + CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").enabled(has_parts_to_explode).params( "name?; scale? (automatic: each occurrence pushed away from the assembly's centre by scale × its offset, default 1); \ moves?: [{occurrence, translate: [x,y,z]}] (instead of automatic)", ), @@ -117,6 +129,14 @@ pub static COMMANDS: &[CommandSpec] = &[ const MAX_ITEMS: usize = 10_000; +/// `prefix` and the first number from 1 that no name in `taken` has: a default name never repeats +/// one in use, after a delete either, as joints' and the app's dialogs' default names (#9738). +fn free_name<'a>(prefix: &str, taken: impl Iterator) -> String { + let taken: BTreeSet<&str> = taken.collect(); + let n = (1..=taken.len() + 1).find(|n| !taken.contains(format!("{prefix}{n}").as_str())).unwrap_or(1); + format!("{prefix}{n}") +} + fn occurrences(s: &Session, p: &Value, cmd: &str) -> Result> { let list = p.get("occurrences").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`occurrences` must list occurrences"))?; if list.len() > MAX_ITEMS { @@ -195,7 +215,10 @@ pub fn collisions(s: &Session) -> Vec<(String, String, f64)> { /// Edges are tested for crossing the other's surface too: plates crossing face to face have /// no sample point inside (#3323). fn overlap(a: &Body, b: &Body) -> Option { - let (ma, mb) = (a.tessellate((a.size() * 1e-3).max(1e-3)).ok()?, b.tessellate((b.size() * 1e-3).max(1e-3)).ok()?); + let (ma, mb) = ( + a.mesh(&solidcraft_kernel::MeshTolerance::chord((a.size() * 1e-3).max(1e-3))).ok()?, + b.mesh(&solidcraft_kernel::MeshTolerance::chord((b.size() * 1e-3).max(1e-3))).ok()?, + ); mesh_overlap(&ma, &mb, 1e-4 * a.size().max(b.size()).max(1.0)) } @@ -401,30 +424,62 @@ fn drive_with_contact(s: &mut Session, want: &[(u64, Vec)], given: &BTreeSe let mut end = s.scratch(); set(&mut end, 1.0); let samples = cache.samples(s, &end)?; - let mut work = 0; + let mut intersections = 0; set(s, 0.0); // Keep the existing recovery behaviour: an initially overlapping assembly may move // out of its invalid placement. Sweeps constrain motions that start collision-free. - if cache.first_hit(s, &mut work)?.is_none() { + if cache.overlaps(s, &mut intersections, false)?.is_empty() { let mut lo = 0.0; let mut bracket = None; for sample in 1..=samples { let hi = sample as f64 / samples as f64; set(s, hi); - if let Some(hit) = cache.first_hit(s, &mut work)? { - bracket = Some((lo, hi, hit)); + let hits = cache.overlaps(s, &mut intersections, true)?; + if !hits.is_empty() { + bracket = Some((lo, hi, hits)); break; } lo = hi; } - if let Some((mut lo, mut hi, hit)) = bracket { - for _ in 0..14 { - let mid = (lo + hi) / 2.0; - set(s, mid); - if cache.first_hit(s, &mut work)?.is_none() { lo = mid } else { hi = mid } + // Where the bodies found passing into each other first touch, closed in on from the + // clear side (conservative advancement): from a clear placement, a move in which no + // point of a pair goes further than the pair's gap keeps it clear. Only clear + // placements are measured, so no intersection is asked to tell touching bodies from + // overlapping ones within its tolerance. + if let Some((lo, hi, hits)) = bracket { + let touch = 1e-9 * cache.scale(); + let mut t = lo; + set(s, t); + for _ in 0..MAX_ADVANCES { + let gap = cache.gap(s, &hits)?; + if gap <= touch { + break; + } + let from = cache.frames(s)?; + // The furthest step whose move stays within the gap: guessed from the move to + // `hi` (nearly proportional over a sample), then halved until it does. + set(s, hi); + let whole = cache.pair_travel(&from, s, &hits)?; + let mut step = if whole > 0.0 { (hi - t) * (0.5 * gap / whole).min(1.0) } else { hi - t }; + let mut next = None; + for _ in 0..64 { + set(s, t + step); + if cache.pair_travel(&from, s, &hits)? < gap { + next = Some(t + step); + break; + } + step *= 0.5; + } + match next { + Some(n) if n > t => t = n, + _ => break, + } + set(s, t); } + let lo = t; sol = set(s, lo); - stopped = Some(json!({"a": hit.0, "b": hit.1, "fraction": lo})); + let (a, b) = hits.first().map(|h| (h.a.clone(), h.b.clone())).unwrap_or_default(); + stopped = Some(json!({"a": a, "b": b, "fraction": lo})); } else { sol = set(s, 1.0); } @@ -455,6 +510,10 @@ fn drive_with_contact(s: &mut Session, want: &[(u64, Vec)], given: &BTreeSe Ok((out, sol)) } +/// Most steps a joint drive takes closing in on a contact. Each moves the pair by up to half its +/// gap; past the last, the drive stops at the last clear placement, short of the touch. +const MAX_ADVANCES: usize = 200; + /// Drive one joint (joint.drive), honouring contact sets. pub fn drive_joint(s: &mut Session, id: u64, q: Vec, given: usize) -> Result { let given = (0..given.min(q.len())).map(|i| (id, i)).collect(); @@ -496,7 +555,8 @@ fn new_set(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "too many contact sets")); } let id = s.doc_mut().allocate_id()?; - let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| format!("Contact Set{}", s.doc.assembly.contact_sets.len() + 1)); + let name = + str_(p, "name").map(str::to_string).unwrap_or_else(|| free_name("Contact Set", s.doc.assembly.contact_sets.iter().map(|c| c.name.as_str()))); let a = &mut s.doc_mut().assembly; a.contact_sets.push(ContactSet { id, name: name.clone(), occurrences: occ, suppressed: false }); a.contact_enabled = true; @@ -629,7 +689,7 @@ fn study(s: &mut Session, p: &Value) -> Result { } let m = MotionStudy { id, - name: str_(p, "name").map(str::to_string).unwrap_or_else(|| format!("Motion Study{}", count + 1)), + name: str_(p, "name").map(str::to_string).unwrap_or_else(|| free_name("Motion Study", a.studies.iter().map(|m| m.name.as_str()))), steps: steps.unwrap_or(100), keys, }; @@ -979,7 +1039,30 @@ fn keep_sampled_trace( } fn list_studies(s: &mut Session, _p: &Value) -> Result { - Ok(json!({"studies": s.doc.assembly.studies, "traces": associative::list(s)})) + let studies: Vec = s.doc.assembly.studies.iter().map(|m| study_json(s, m)).collect(); + Ok(json!({"studies": studies, "traces": associative::list(s)})) +} + +/// A study as `motion.list` gives it: key values in the units `motion.study` takes — degrees +/// for angles, mm for distances, like `joint.list`'s values — each key with its joint's name, +/// so a listed study can be fed back to `motion.study` unchanged. +fn study_json(s: &Session, m: &MotionStudy) -> Value { + let keys: Vec = m + .keys + .iter() + .map(|k| { + let joint = s.doc.assembly.joints.iter().find(|j| j.id == k.joint); + let angle = joint.is_some_and(|j| j.kind.is_angle(k.index)); + json!({ + "joint": k.joint, + "joint_name": joint.map(|j| j.name.clone()).unwrap_or_else(|| k.joint.to_string()), + "index": k.index, + "unit": if angle { "deg" } else { "mm" }, + "points": k.points.iter().map(|(step, v)| json!([step, if angle { v.to_degrees() } else { *v }])).collect::>(), + }) + }) + .collect(); + json!({"id": m.id, "name": m.name, "steps": m.steps, "keys": keys}) } fn delete_study(s: &mut Session, p: &Value) -> Result { @@ -990,6 +1073,16 @@ fn delete_study(s: &mut Session, p: &Value) -> Result { // ---- Exploded views ---- +/// Why Exploded View is greyed out: it pulls components apart, so a design of plain bodies, or +/// with a single component, has nothing to separate (#9142). +const EXPLODE_NEEDS_COMPONENTS: &str = + "Exploded View pulls components apart, so the design needs two or more of them (New Component, Insert Design or Create Components from Bodies)"; + +/// Exploded View is offered once the design has two or more occurrences to move apart (#9142). +fn has_parts_to_explode(s: &Session) -> std::result::Result<(), String> { + if s.doc.occurrences.len() >= 2 { Ok(()) } else { Err(EXPLODE_NEEDS_COMPONENTS.into()) } +} + fn view_index(s: &Session, p: &Value, cmd: &str) -> Result { let key = match p.get("view") { Some(Value::Number(n)) => n.to_string(), @@ -1006,7 +1099,7 @@ fn centres(s: &Session) -> Vec<(u64, Vec3)> { for o in s.doc.occurrences.iter().filter(|o| o.parent == 0) { let mut bounds = Aabb3::EMPTY; for (_, b) in bodies.iter().filter(|(path, _)| path.first() == Some(&o.id)) { - if let Ok(m) = b.tessellate((b.size() * 1e-2).max(1e-2)) { + if let Ok(m) = b.mesh(&solidcraft_kernel::MeshTolerance::chord((b.size() * 1e-2).max(1e-2))) { bounds = bounds.union(&m.bounds()); } } @@ -1054,7 +1147,8 @@ fn explode_create(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "too many exploded views")); } let id = s.doc_mut().allocate_id()?; - let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| format!("Exploded View{}", s.doc.assembly.exploded.len() + 1)); + let name = + str_(p, "name").map(str::to_string).unwrap_or_else(|| free_name("Exploded View", s.doc.assembly.exploded.iter().map(|v| v.name.as_str()))); s.doc_mut().assembly.exploded.push(ExplodedView { id, name: name.clone(), moves: moves.clone() }); Ok(json!({"view": id, "name": name, "moves": moves.iter().map(|(o, t)| json!({"occurrence": o, "translate": t})).collect::>()})) } @@ -1063,12 +1157,19 @@ fn explode_show(s: &mut Session, p: &Value) -> Result { let cmd = "explode.show"; if p.get("view").is_none_or(|v| v.is_null() || v.as_str().is_some_and(|x| x.eq_ignore_ascii_case("none"))) { s.pending_moves.clear(); + s.exploded.clear(); s.revision += 1; return Ok(json!({"view": null})); } let i = view_index(s, p, cmd)?; let v = s.doc.assembly.exploded.get(i).cloned().ok_or_else(|| bad(cmd, "view"))?; - s.pending_moves = exploded_at(&explode_moves(s, &v), 1.0); + let moves = exploded_at(&explode_moves(s, &v), 1.0); + if !moves.values().all(solidcraft_doc::is_placement) { + return Err(bad(cmd, format!("exploded view `{}` moves an occurrence out of range", v.name))); + } + // Shown only: `exploded` marks these as the view's, so the design's placements leave them out. + s.exploded.clone_from(&moves); + s.pending_moves = moves; s.revision += 1; Ok(json!({"view": v.id, "name": v.name})) } diff --git a/crates/engine/src/cmd/motion_analysis.rs b/crates/engine/src/cmd/motion_analysis.rs index d10cc911b..8e3092c53 100644 --- a/crates/engine/src/cmd/motion_analysis.rs +++ b/crates/engine/src/cmd/motion_analysis.rs @@ -3,14 +3,15 @@ //! joint values and a point's path with their velocities and accelerations; `motion.interference` //! answers the pairs of parts that pass through each other along the way. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; -use std::sync::Arc; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::joints; use solidcraft_doc::motion::MotionStudy; use solidcraft_doc::{Document, Mat, apply_point, mat_mul}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcraft_geom::Aabb3; use super::contact_sweep::{ContactGeometry, Member}; use super::{drive_with_contact, joint_id, keyed, occurrences, path_world, study_index, traced_point, values_at}; @@ -32,8 +33,10 @@ pub const INTERFERENCE_DOC: &str = "study: id|name; occurrences?: [ids or names] as an arm against the parts it must miss), or contact_sets?: true (the pairs of the design's contact sets); samples? \ (2…1000, default the study's steps + 1); budget_s?: seconds (above 0, at most 86400; default a fixed work budget): the \ time the check may take instead, looked at between samples, for a mechanism such as a gear train that needs longer → collisions: [{a, b, first_step, last_step, steps: [[from, to]…] (the step ranges where they overlap), \ - depth_mm (how far into each other, the most at deepest_step), volume_mm3 (their overlap there; null when it was not \ - cheap to work out)}], clear (every sample checked and none collide; never while truncated), \ + volume_mm3 (the most volume they share at a sample, worked out exactly from the bodies), deepest_step (the first sample \ + sharing that volume), not_measured (null, or why the volume was not worked out at every sample they overlap, such as \ + a budget it ran past: then volume_mm3 and deepest_step are null, never an estimate), depth_mm (how far into each \ + other at most: an estimate from points of the bodies' contact meshes, not exact)}], clear (every sample checked and none collide; never while truncated), \ pairs (checked), samples (taken), truncated (the work budget, or budget_s, ran out; checked_to: the last step checked), budget_s \ (when given), stopped_at, \ stopped_by_loop. The study plays as motion.play plays it but contact sets do not stop it, on a copy (the design is not \ @@ -47,9 +50,10 @@ const MAX_SERIES: usize = 256; const MAX_WORK: usize = 500_000_000; /// Longest time an interference check may be given (`budget_s`): a day, as `inspect.interference`. const MAX_BUDGET_S: f64 = 86_400.0; -/// Most colliding pairs whose overlap volume is worked out, and most body booleans that takes. +/// Most colliding pairs whose overlap volume is worked out, and most body booleans that takes +/// over the whole study (one per pair of overlapping bodies at each sample a pair collides). const MAX_VOLUMES: usize = 16; -const MAX_BOOLEANS: usize = 64; +const MAX_BOOLEANS: usize = 256; /// How many samples `p` asks for (`min`…`MAX_SAMPLES`, default the study's steps + 1). fn samples(p: &Value, m: &MotionStudy, min: usize, cmd: &str) -> Result { @@ -254,15 +258,26 @@ struct Collision { names: (String, String), /// The samples where they overlap, in order. samples: Vec, + /// The most sampled mesh depth. depth: f64, - deepest: usize, - /// The design at the deepest sample (its placements). - at_deepest: Arc, + /// The most exact shared volume and the first sample sharing it, or why it is not measured + /// (a sample's volume was not worked out). + most_volume: std::result::Result<(f64, usize), String>, } -/// The volume the parts under occurrences `a` and `b` share, placed as in `doc` (`None`: not -/// worked out). Only bodies whose boxes overlap are intersected, at most `booleans` of them. -fn shared_volume(s: &Session, doc: &Document, a: u64, b: u64, booleans: &mut usize) -> Option { +impl Collision { + /// Takes the exact shared volume at sample `k`, or why it was not worked out. A volume + /// larger by no more than the booleans' rounding is a tie, which keeps the earlier sample. + fn take_volume(&mut self, k: usize, volume: std::result::Result) { + if let Ok((best, at)) = self.most_volume { + self.most_volume = volume.map(|v| if v > best + 1e-9 * best.max(1.0) { (v, k) } else { (best, at) }); + } + } +} + +/// The volume the parts under occurrences `a` and `b` share, placed as in `doc`, or why it was +/// not worked out. Only bodies whose boxes overlap are intersected, at most `booleans` of them. +fn shared_volume(s: &Session, doc: &Document, a: u64, b: u64, booleans: &mut usize) -> std::result::Result { let st = s.model.state(); // The bodies under each (and not under the other), with their world frames and boxes. let mut sides: [Vec<(Mat, Aabb3, &solidcraft_doc::ModelBody)>; 2] = Default::default(); @@ -282,24 +297,31 @@ fn shared_volume(s: &Session, doc: &Document, a: u64, b: u64, booleans: &mut usi let corner = Vec3::new(pick(1, local.min.x, local.max.x), pick(2, local.min.y, local.max.y), pick(4, local.min.z, local.max.z)); world.add(apply_point(&frame, corner)); } - sides.get_mut(side)?.push((frame, world, body)); + if let Some(list) = sides.get_mut(side) { + list.push((frame, world, body)); + } } } + let [first, second] = &sides; let mut total = 0.0; - for (fa, xa, ba) in sides.first()? { - for (fb, xb, bb) in sides.get(1)? { + for (fa, xa, ba) in first { + for (fb, xb, bb) in second { if xa.max.x < xb.min.x || xb.max.x < xa.min.x || xa.max.y < xb.min.y || xb.max.y < xa.min.y || xa.max.z < xb.min.z || xb.max.z < xa.min.z { continue; } - *booleans = booleans.checked_sub(1)?; - let (pa, pb) = (solidcraft_kernel::transform_matrix(&ba.body, *fa).ok()?, solidcraft_kernel::transform_matrix(&bb.body, *fb).ok()?); - if let Some(shared) = solidcraft_kernel::boolean(&pa, &pb, solidcraft_kernel::BoolOp::Intersect).ok()? { - total += solidcraft_kernel::measure(&shared).ok()?.volume; + *booleans = booleans.checked_sub(1).ok_or_else(|| format!("the check's {MAX_BOOLEANS} body intersections ran out"))?; + let failed = |e: &dyn std::fmt::Display| format!("the intersection of {} and {} could not be made ({e})", ba.name, bb.name); + let (pa, pb) = ( + solidcraft_kernel::transform_matrix(&ba.body, *fa).map_err(|e| failed(&e))?, + solidcraft_kernel::transform_matrix(&bb.body, *fb).map_err(|e| failed(&e))?, + ); + if let Some(shared) = solidcraft_kernel::boolean(&pa, &pb, solidcraft_kernel::BoolOp::Intersect).map_err(|e| failed(&e))? { + total += solidcraft_kernel::measure(&shared).map_err(|e| failed(&e))?.volume; } } } - Some(total) + Ok(total) } /// Contiguous runs of samples, as study step ranges. @@ -385,6 +407,7 @@ fn interference_within(s: &mut Session, p: &Value, budget: usize, seconds: Optio let geometry = checked_pairs(s, p, cmd)?; let mut found: BTreeMap<(u64, u64), Collision> = BTreeMap::new(); let (mut work, mut checked, mut truncated) = (0usize, 0usize, false); + let mut booleans = MAX_BOOLEANS; let stop = play(s, &m, n, false, |t, k| { if deadline.is_some_and(|d| web_time::Instant::now() >= d) { truncated = true; @@ -408,18 +431,25 @@ fn interference_within(s: &mut Session, p: &Value, budget: usize, seconds: Optio for ((a, an), (b, bn), depth) in hits { // Each pair once, the older occurrence (the lower id) first. let ((a, an), (b, bn)) = if a <= b { ((a, an), (b, bn)) } else { ((b, bn), (a, an)) }; + // The first MAX_VOLUMES pairs found have their shared volume worked out. + let slots = found.len() < MAX_VOLUMES; let c = found.entry((a, b)).or_insert_with(|| Collision { names: (an, bn), samples: Vec::new(), depth: 0.0, - deepest: k, - at_deepest: t.doc.clone(), + most_volume: if slots { + Ok((0.0, k)) + } else { + Err(format!("more than {MAX_VOLUMES} pairs collide: only the first {MAX_VOLUMES} found have their volumes worked out")) + }, }); - if c.samples.last() != Some(&k) { - c.samples.push(k); + if c.samples.last() == Some(&k) { + continue; } - if depth > c.depth { - (c.depth, c.deepest, c.at_deepest) = (depth, k, t.doc.clone()); + c.samples.push(k); + c.depth = c.depth.max(depth); + if c.most_volume.is_ok() { + c.take_volume(k, shared_volume(s, &t.doc, a, b, &mut booleans)); } } Ok(true) @@ -436,16 +466,17 @@ fn interference_within(s: &mut Session, p: &Value, budget: usize, seconds: Optio } let mut list: Vec<(&(u64, u64), &Collision)> = found.iter().collect(); list.sort_by_key(|(_, c)| c.samples.first().copied().unwrap_or(usize::MAX)); - let mut booleans = MAX_BOOLEANS; let collisions: Vec = list .iter() - .enumerate() - .map(|(i, ((a, b), c))| { - let volume = if i < MAX_VOLUMES { shared_volume(s, &c.at_deepest, *a, *b, &mut booleans) } else { None }; + .map(|(_, c)| { + let (volume, deepest, not_measured) = match &c.most_volume { + Ok((v, at)) => (Some(*v), Some(step_of(&m, *at, n)), None), + Err(why) => (None, None, Some(why.clone())), + }; let first = c.samples.first().map(|k| step_of(&m, *k, n)); let last = c.samples.last().map(|k| step_of(&m, *k, n)); json!({"a": c.names.0, "b": c.names.1, "first_step": first, "last_step": last, "steps": ranges(&m, &c.samples, n), - "depth_mm": c.depth, "deepest_step": step_of(&m, c.deepest, n), "volume_mm3": volume}) + "depth_mm": c.depth, "deepest_step": deepest, "volume_mm3": volume, "not_measured": not_measured}) }) .collect(); // A check cut short says nothing about the steps it did not reach, so it is not clear (#7855). diff --git a/crates/engine/src/cmd/motion_analysis_tests.rs b/crates/engine/src/cmd/motion_analysis_tests.rs index ccfa73b4e..522686028 100644 --- a/crates/engine/src/cmd/motion_analysis_tests.rs +++ b/crates/engine/src/cmd/motion_analysis_tests.rs @@ -2,7 +2,7 @@ //! `motion.interference` on two blocks pushed through each other at a known step. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use super::{four_bar, occ, part, pin, rocker_pin, run, slider_crank}; use crate::Session; @@ -147,10 +147,9 @@ fn interference_names_the_step_two_parts_start_to_collide() { assert_eq!((c["a"].as_str(), c["b"].as_str()), (Some("A:1"), Some("B:1")), "{r}"); assert_eq!((c["first_step"].as_f64(), c["last_step"].as_f64()), (Some(11.0), Some(15.0)), "{r}"); assert_eq!(c["steps"], json!([[11.0, 15.0]]), "{r}"); - let deepest = c["deepest_step"].as_f64().unwrap_or(f64::NAN); - assert!(c["depth_mm"].as_f64().unwrap_or(0.0) > 1.0 && (11.0..=15.0).contains(&deepest), "{r}"); - let volume = c["volume_mm3"].as_f64().unwrap_or(f64::NAN); - assert!((volume - 100.0 * (deepest - 10.0)).abs() < 1e-6, "{r}"); + // Deepest where they share the most: 5 mm of the 10 x 10 face at the end. + assert!(c["depth_mm"].as_f64().unwrap_or(0.0) > 1.0 && c["deepest_step"] == 15.0, "{r}"); + assert!((c["volume_mm3"].as_f64().unwrap_or(f64::NAN) - 500.0).abs() < 1e-6, "{r}"); } // B against a far block C only: B's pass through A is not asked about. run(&mut s, "component.create", json!({"name": "C"})); @@ -167,6 +166,57 @@ fn interference_names_the_step_two_parts_start_to_collide() { assert!(r["clear"] == true && r["collisions"] == json!([]), "{r}"); } +/// An arm (40 x 10 x 10 from (0, -5, 0)) turns on a hinge at the origin from 0 to 90 degrees in +/// 9 steps into a grounded block (50 x 10 x 10 from (-10, 30, 0)). Its corner (40, 5) reaches +/// y = 40 sin θ + 5 cos θ, past 30 from 40.97 degrees, so it overlaps from step 5. Every point of +/// the slab is within 5 mm of z = 0 or z = 10, so from 60 degrees on (where the arm's side +/// crosses y = 35) the depth is 5 mm at every step: only the shared volume, which grows to the +/// arm's 10 x 10 x 10 end inside the block at 90 degrees, tells the deepest step. Sampled twice +/// as densely (5 degrees a sample), the overlap is seen from step 4.5 (45 degrees) and is still +/// deepest at the end. +#[test] +fn interference_is_deepest_where_the_parts_share_the_most_volume() { + let mut s = Session::default(); + for (name, size, corner) in [("Base", [20, 20, 10], [-10, -10, -10]), ("Arm", [40, 10, 10], [0, -5, 0]), ("Stop", [50, 10, 10], [-10, 30, 0])] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + for name in ["Base", "Stop"] { + let o = occ(&s, name); + run(&mut s, "occurrence.ground", json!({"occurrence": o, "grounded": true})); + } + let end = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [0, 0, 1]}); + run(&mut s, "joint.create", json!({"type": "revolute", "name": "Hinge", "flip": true, "a": end("Base"), "b": end("Arm"), "quiet": true})); + run(&mut s, "motion.study", json!({"name": "Open", "steps": 9, "keys": [{"joint": "Hinge", "points": [[0, 0], [9, 90]]}]})); + for (samples, first) in [(10, 5.0), (19, 4.5)] { + let r = run(&mut s, "motion.interference", json!({"study": "Open", "samples": samples, "occurrences": ["Arm"], "against": ["Stop"]})); + let c = &r["collisions"][0]; + assert!(r["clear"] == false && c["first_step"] == first && c["last_step"] == 9.0 && c["deepest_step"] == 9.0, "{samples}: {r}"); + assert!((c["volume_mm3"].as_f64().unwrap_or(f64::NAN) - 1000.0).abs() < 1e-6, "{samples}: {r}"); + assert!(c["depth_mm"].as_f64().is_some_and(|d| d > 0.0 && d <= 5.0 + 1e-9), "{samples}: {r}"); + } +} + +/// Pushed through A at 1000 samples, B overlaps it at about 330 of them, one intersection each: +/// past the check's 256, so the volume is not measured and no deepest step is guessed. Where +/// they overlap is still answered. +#[test] +fn interference_past_its_intersection_budget_says_the_volume_is_not_measured() { + let mut s = rail(); + run(&mut s, "motion.study", json!({"name": "Push", "steps": 15, "keys": [{"joint": "Rail", "points": [[0, 10], [15, -5]]}]})); + let r = run(&mut s, "motion.interference", json!({"study": "Push", "samples": 1000})); + let c = &r["collisions"][0]; + assert!(r["clear"] == false && r["truncated"] == false && c["last_step"] == 15.0, "{r}"); + assert!(c["first_step"].as_f64().is_some_and(|f| f > 10.0 && f < 10.1), "{r}"); + assert!(c["volume_mm3"].is_null() && c["deepest_step"].is_null(), "{r}"); + assert!(c["not_measured"].as_str().is_some_and(|w| w.contains("256 body intersections ran out")), "{r}"); + // Within the budget, it is measured. + let r = run(&mut s, "motion.interference", json!({"study": "Push"})); + assert!(r["collisions"][0]["not_measured"].is_null() && r["collisions"][0]["deepest_step"] == 15.0, "{r}"); +} + /// A number names a study by its id first, text by its name first: a study may be named like /// another's id. #[test] diff --git a/crates/engine/src/cmd/motion_animation.rs b/crates/engine/src/cmd/motion_animation.rs index 4c820a433..d4b3144c6 100644 --- a/crates/engine/src/cmd/motion_animation.rs +++ b/crates/engine/src/cmd/motion_animation.rs @@ -6,8 +6,8 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::Mat; -use solidcraft_geom::Vec3; use super::{Plan, drive_with_contact, explode_moves, exploded_at, motion_plan, sample_count, view_index}; use crate::capture::{self, Renderer}; @@ -98,11 +98,11 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - Motion::Explode(moves, _) => { let mut t = s.scratch(); t.pending_moves.clear(); - let assembled = crate::view::bounds(&t); + let assembled = crate::view::bounds(&t)?; t.pending_moves = exploded_at(moves, 1.0); - let mut c = crate::view::home_camera(&t); - c.fit(&assembled.union(&crate::view::bounds(&t))); - c + let mut c = crate::view::home_camera(&t)?; + c.fit(&assembled.union(&crate::view::bounds(&t)?)); + Ok(c) } Motion::Drive(..) => crate::view::home_camera(s), }; @@ -144,7 +144,7 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - t.pending_moves = exploded_at(moves, if *back { 1.0 - (2.0 * u - 1.0).abs() } else { u }); } } - let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides); + let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides)?; let picture = capture::rgba_with(Some(renderer), &scene, &cam, width, height).map_err(|e| bad(cmd, e))?; drawn_by = picture.renderer; if gif { @@ -178,8 +178,11 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - /// The camera the frames are drawn from: the session's (`view.apply`), or `home` framing the /// model, with the fields `given` sets (`ui.camera`'s reply sets them all). -fn camera(s: &Session, home: impl FnOnce() -> Camera, given: Option<&Value>, cmd: &str) -> Result { - let base = s.camera.unwrap_or_else(home); +fn camera(s: &Session, home: impl FnOnce() -> Result, given: Option<&Value>, cmd: &str) -> Result { + let base = match s.camera { + Some(c) => c, + None => home()?, + }; let Some(given) = given else { return Ok(base) }; let fields = given.as_object().ok_or_else(|| bad(cmd, "`camera` must be an object, such as ui.camera's reply"))?; let mut v = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?; diff --git a/crates/engine/src/cmd/motion_sweep.rs b/crates/engine/src/cmd/motion_sweep.rs index faca1f5c8..fb6b35781 100644 --- a/crates/engine/src/cmd/motion_sweep.rs +++ b/crates/engine/src/cmd/motion_sweep.rs @@ -2,19 +2,23 @@ //! toward `to` on a copy of the design (closed loops following on their branch), measures the //! gaps between parts at each sample and bisects the first contact down to `refine`, so a hinge, //! door or linkage answers how far it opens, what stops it and how much room each part has. +//! `joint.find_limits` sweeps each value both ways from where it is, for the joint dialog's Find +//! Limits. use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::Document; -use solidcraft_geom::Vec3; +use solidcraft_doc::joints::JointKind; use super::analysis::checked_pairs; use super::contact_sweep::{ContactGeometry, Gap}; use super::{drive_with_contact, joint_id, value}; use crate::params::{bad, bool_}; -use crate::{Result, Session}; +use crate::schema::motion::{FindLimitsResult, FoundLimits, Overlap, Stop, Why}; +use crate::{EngineError, Result, Session}; pub const SWEEP_DOC: &str = "joint: id|name; from, to: its value the sweep runs between (degrees for angles, mm for distances, \ or expressions); index? (which value, default 0); step? (between samples, in the joint's unit; default: fine enough that \ @@ -31,12 +35,29 @@ pub const SWEEP_DOC: &str = "joint: id|name; from, to: its value the sweep runs on its frame: these stop it only once they pass into each other deeper than they start), applied. The parts are tested at the samples and through the bisection; the motion is on a copy (closed loops \ follow, contact sets do not stop it)"; +pub const FIND_LIMITS_DOC: &str = "joint: id|name; index? (one value; default every value); refine?, step?, occurrences?, \ + against?, contact_sets? (as joint.sweep) → values: [{index, dof, unit, value (now), min, max, min_by, max_by, range}], \ + each value swept both ways from where it is, its own limits ignored, closed loops following; each side stops at the \ + first contact (bisected to `refine`), where a loop cannot close, or at another limit (another value's, or another joint's through a motion link): min_by/max_by {a, b, at} | \ + \"loop\" | \"limit\" | \"turn\" (an angle with no contact within a turn: a turn from the other side, or ±180° from \ + now when nothing is met at all) | \"range\" (a distance with no contact within the parts' reach: min/max null); \ + touching_at_start, overlapping_at_start: [{a, b, depth_mm}] (already passing into each other: they stop it only going \ + deeper), refine_mm, gap_method, gap_tolerance_mm, pairs (0: no two parts to check, so nothing is swept). The design is \ + not changed"; + /// Most samples a sweep takes before its bisection: each is a solve. const MAX_SAMPLES: usize = 4096; /// Most bisection steps: each halves the bracket around the first contact. const MAX_BISECTIONS: usize = 64; /// Most gap work over a whole sweep (see `ContactGeometry::gaps`). const MAX_WORK: usize = 500_000_000; +/// Most gap work each side of a limit search takes: a whole turn of curved pins passing into each +/// other costs about 20 M a sample, some 500 samples a turn (a few seconds). A 32-bit build, the +/// web, takes half what its `usize` holds, so the work it adds up can still pass it. +const FIND_WORK: usize = { + let most = MAX_WORK.saturating_mul(40); + if most > usize::MAX / 2 { usize::MAX / 2 } else { most } +}; /// The nearest a part came to another along the sweep. struct Nearest { @@ -45,23 +66,86 @@ struct Nearest { to: String, } -pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { - let cmd = "joint.sweep"; +/// One sweep of a joint value. +#[derive(Clone, Copy)] +struct Sweep { + id: u64, + index: usize, + from: f64, + to: f64, + step: Option, + refine: f64, + report_gaps: bool, + /// The gap work it may take. + budget: usize, + /// The value's own limit left out (the copy only). + free: bool, +} + +/// What a sweep found. +struct Swept { + /// The last value clear of contact (or where a loop or limit stopped it), and what stopped + /// it; `None`: it reached `to`. + stop: Option<(f64, Stop)>, + samples: Vec, + nearest: BTreeMap, + touching: Vec<[String; 2]>, + /// Pairs of parts passing into each other at the start deeper than a touch: (a, b, mm). + overlapping: Vec<(String, String, f64)>, + pairs: usize, + chord: f64, + /// The design where it stopped. + doc: Arc, +} + +/// The joint a command sweeps: its id, name and kind (a rigid joint is refused). +fn swept_joint(s: &Session, p: &Value, cmd: &str) -> Result<(u64, String, JointKind)> { let id = joint_id(s, p.get("joint"), cmd)?; let joint = s.doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| bad(cmd, "joint"))?; - let (kind, name) = (joint.kind, joint.name.clone()); - let dofs = kind.dofs().len(); - if dofs == 0 { + if joint.kind.dofs().is_empty() { return Err(bad(cmd, "a rigid joint does not move")); } - let index = match p.get("index") { - None | Some(Value::Null) => 0, + Ok((id, joint.name.clone(), joint.kind)) +} + +/// `index`, below `dofs` (`None`: not given). +fn value_index(p: &Value, dofs: usize, cmd: &str) -> Result> { + match p.get("index") { + None | Some(Value::Null) => Ok(None), Some(v) => v .as_u64() .and_then(|i| usize::try_from(i).ok()) .filter(|i| *i < dofs) - .ok_or_else(|| bad(cmd, format!("`index` must be below {dofs}, the joint's value count")))?, - }; + .map(Some) + .ok_or_else(|| bad(cmd, format!("`index` must be below {dofs}, the joint's value count"))), + } +} + +/// A number above 0, at most `max` (`None`: not given). +fn positive(p: &Value, key: &str, max: f64, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .filter(|x| x.is_finite() && *x > 0.0 && *x <= max) + .map(Some) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0, at most {max}"))), + } +} + +/// The parts the command checks, refused when there are no two to check against each other. +fn pairs_to_check(s: &Session, p: &Value, cmd: &str) -> Result { + let geometry = checked_pairs(s, p, cmd)?; + if !geometry.has_pairs() { + return Err(bad(cmd, "no pairs of parts to check: list two or more `occurrences` with bodies, or give `against`")); + } + Ok(geometry) +} + +pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.sweep"; + let (id, name, kind) = swept_joint(s, p, cmd)?; + let index = value_index(p, kind.dofs().len(), cmd)?.unwrap_or(0); let angle = kind.is_angle(index); // Shown in degrees for angles, mm for distances. let shown = |v: f64| if angle { v.to_degrees() } else { v }; @@ -70,29 +154,152 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the sweep runs between (no `{key}`)"))), }; let (from, to) = (end("from")?, end("to")?); - let positive = |key: &str, max: f64| -> Result> { - match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(v) => v - .as_f64() - .filter(|x| x.is_finite() && *x > 0.0 && *x <= max) - .map(Some) - .ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0, at most {max}"))), - } - }; - let refine = positive("refine", 1e3)?.unwrap_or(0.01); - let step = positive("step", 1e9)?.map(|x| if angle { x.to_radians() } else { x }); + let refine = positive(p, "refine", 1e3, cmd)?.unwrap_or(0.01); + let step = positive(p, "step", 1e9, cmd)?.map(|x| if angle { x.to_radians() } else { x }); let report_gaps = bool_(p, "report_gaps").unwrap_or(false); let apply = bool_(p, "apply").unwrap_or(false); + let geometry = pairs_to_check(s, p, cmd)?; + let sweep = Sweep { id, index, from, to, step, refine, report_gaps, budget: MAX_WORK, free: false }; + let r = run(s, geometry, sweep, cmd)?; - let mut geometry = checked_pairs(s, p, cmd)?; - if !geometry.has_pairs() { - return Err(bad(cmd, "no pairs of parts to check: list two or more `occurrences` with bodies, or give `against`")); + let applied = apply && !Arc::ptr_eq(&r.doc, &s.doc); + if applied { + let mut doc = (*r.doc).clone(); + doc.assembly.contact_enabled = s.doc.assembly.contact_enabled; + *s.doc_mut() = doc; } + let by = |stop: &Stop| serde_json::to_value(stop).map_err(|e| EngineError::Other(e.to_string())); + let mut out = json!({ + "joint": id, "name": name, "index": index, "unit": if angle { "deg" } else { "mm" }, + "from": shown(from), "to": shown(to), + "stopped_at": r.stop.as_ref().map(|(v, _)| shown(*v)), + "stopped_by": r.stop.as_ref().map(|(_, stop)| by(stop)).transpose()?, + "samples": r.samples, + "refine_mm": refine, + "gap_method": "mesh", "gap_tolerance_mm": r.chord, + "pairs": r.pairs, + "touching_at_start": r.touching, + "applied": applied, + }); + if report_gaps { + out["min_gap"] = + r.nearest.into_iter().map(|(k, g)| (k, json!({"mm": g.mm, "at_value": g.at, "to": g.to}))).collect::>().into(); + } + Ok(out) +} + +pub(super) fn find_limits(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.find_limits"; + // Every search is on a copy: the design is only read. + let s: &Session = s; + let (id, name, kind) = swept_joint(s, p, cmd)?; + let indices: Vec = match value_index(p, kind.dofs().len(), cmd)? { + Some(i) => vec![i], + None => (0..kind.dofs().len()).collect(), + }; + let refine = positive(p, "refine", 1e3, cmd)?.unwrap_or(0.01); + let step = positive(p, "step", 1e9, cmd)?; + // No two parts to check (the joint turns the only part with bodies): nothing can be met, but + // a closed loop or a limit can still stop an angle, swept a degree at a time; a distance has + // nothing to search over. Parts the call names that make no pair are refused, as + // `joint.sweep` refuses them. + let named = p.get("occurrences").is_some_and(|v| !v.is_null()) || bool_(p, "contact_sets").unwrap_or(false); + let geometry = if named { pairs_to_check(s, p, cmd)? } else { checked_pairs(s, p, cmd)? }; + let paired = geometry.has_pairs(); + let now = s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.values.clone()).unwrap_or_default(); + // A distance is searched as far as the parts reach: past it, a straight move meets nothing new. + let reach = if paired { geometry.reach(s)? } else { 0.0 }; + if paired && (!reach.is_finite() || reach <= 0.0) { + return Err(bad(cmd, "the parts have no size to search over")); + } + let turn = std::f64::consts::TAU; + let mut values = Vec::with_capacity(indices.len()); + let mut first: Option = None; + for index in indices { + let angle = kind.is_angle(index); + let shown = |v: f64| if angle { v.to_degrees() } else { v }; + let c = now.get(index).copied().unwrap_or(0.0); + if !c.is_finite() { + return Err(bad(cmd, "the joint's value is not a number")); + } + let range = if angle { turn } else { reach }; + let step = match step { + Some(x) => Some(if angle { x.to_radians() } else { x }), + None if !paired => Some(1f64.to_radians()), + None => None, + }; + let side = |to: f64| { + if !angle && !paired { + return Ok(None); + } + let sweep = Sweep { id, index, from: c, to, step, refine, report_gaps: false, budget: FIND_WORK, free: true }; + Ok::<_, EngineError>(Some(run(s, geometry.clone(), sweep, cmd)?)) + }; + // (value, what stopped it) for each side; `None` value: no limit that side. An angle is + // searched a turn up, then down to a turn below where that stopped: a span of at most a + // turn, each side checked (a motion link can make the way down differ from the way up). + let up = side(c + range)?; + let up_stop = up.as_ref().and_then(|u| u.stop.clone()); + let down = side(if angle { up_stop.as_ref().map_or(c, |(u, _)| *u) - turn } else { c - range })?.and_then(|d| d.stop); + let turned = |v: f64| (Some(v), Stop::Other(Why::Turn)); + let (min, max) = match (angle, up_stop, down) { + (true, None, None) => (turned(c - turn / 2.0), turned(c + turn / 2.0)), + (true, None, Some((d, by))) => ((Some(d), by), turned(d + turn)), + (true, Some((u, by)), None) => (turned(u - turn), (Some(u), by)), + (_, up, down) => { + let found = |stop: Option<(f64, Stop)>| stop.map_or((None, Stop::Other(Why::Range)), |(v, by)| (Some(v), by)); + (found(down), found(up)) + } + }; + values.push(FoundLimits { + index, + dof: kind.dofs().get(index).copied().unwrap_or("value").to_string(), + unit: if angle { "deg" } else { "mm" }.to_string(), + value: shown(c), + min: min.0.map(shown), + max: max.0.map(shown), + min_by: min.1, + max_by: max.1, + range: shown(range), + }); + if first.is_none() { + first = up; + } + } + let reply = FindLimitsResult { + joint: id, + name, + values, + refine_mm: refine, + gap_method: "mesh".into(), + gap_tolerance_mm: first.as_ref().map_or(0.0, |f| f.chord), + pairs: first.as_ref().map_or(0, |f| f.pairs), + touching_at_start: first.as_ref().map(|f| f.touching.clone()).unwrap_or_default(), + overlapping_at_start: first + .map(|f| f.overlapping) + .unwrap_or_default() + .into_iter() + .map(|(a, b, depth_mm)| Overlap { a, b, depth_mm }) + .collect(), + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + +/// Drive the value `sw` names from `sw.from` toward `sw.to` on a copy of `s`, checking the pairs +/// of `geometry` at each sample, and bisect the first contact. +fn run(s: &Session, mut geometry: ContactGeometry, sw: Sweep, cmd: &str) -> Result { + let Sweep { id, index, from, to, step, refine, report_gaps, budget, free } = sw; + let (dofs, angle) = + s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| (j.kind.dofs().len(), j.kind.is_angle(index))).ok_or_else(|| bad(cmd, "joint"))?; + let shown = |v: f64| if angle { v.to_degrees() } else { v }; // On a copy, played from where the parts are placed; contact sets do not stop it. let mut t = s.scratch(); t.pending_moves.clear(); t.doc_mut().assembly.contact_enabled = false; + if free && let Some(limit) = t.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id).and_then(|j| j.limits.get_mut(index)) { + *limit = None; + } let given = BTreeSet::from([(id, index)]); let drive_to = |t: &mut Session, v: f64| -> Result { let mut q = t.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.values.clone()).unwrap_or_default(); @@ -118,17 +325,26 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { let key = |x: u64, y: u64| (x.min(y), x.max(y)); // Pairs touching where the sweep starts (parts joined face to face, a door on its frame) // stop it only when they pass into each other, deeper than they start (by more than their - // meshes can be off): a door resting on its frame cannot sweep through it. - let start: Vec = geometry.gaps(&t, touch, &mut work, MAX_WORK)?; + // meshes can be off): a door resting on its frame cannot sweep through it. Each pair of their + // bodies is held to its own depth: pins already in each other don't hide arms of the same + // parts meeting later, and plates that only come flush (parts end to end) never stop it. + let start: Vec = geometry.gaps(&t, touch, &mut work, budget)?; let touching: BTreeSet<(u64, u64)> = start.iter().map(|g| key(g.a.0, g.b.0)).collect(); - let touching_names: Vec = start.iter().map(|g| json!([g.a.1, g.b.1])).collect(); + let touching_names: Vec<[String; 2]> = start.iter().map(|g| [g.a.1.clone(), g.b.1.clone()]).collect(); let resting = geometry.take_pairs(|x, y| touching.contains(&key(x, y))); - let rest_depth: BTreeMap<(u64, u64), f64> = if resting.has_pairs() { - resting.hits(&t, &mut work, MAX_WORK, true)?.into_iter().map(|(a, b, d)| (key(a.0, b.0), d)).collect() - } else { - BTreeMap::new() - }; - let margin = touch.max(2.0 * resting.chord()); + let rest_depth: Vec = if resting.has_pairs() { resting.depths(&t, &mut work, budget)? } else { Vec::new() }; + // A pair of bodies' own margin: flat faces against flat faces are exact. + let margin = |i: usize| touch.max(2.0 * resting.pair_chord(i)); + // Parts already passing into each other, deeper than a touch: the deepest of their bodies. + let mut overlapping: BTreeMap<(u64, u64), (String, String, f64)> = BTreeMap::new(); + for (i, depth) in rest_depth.iter().enumerate() { + if *depth > margin(i) + && let Some((a, b)) = resting.members(i) + { + let entry = overlapping.entry(key(a.0, b.0)).or_insert((a.1, b.1, 0.0)); + entry.2 = entry.2.max(*depth); + } + } // The samples run to where the joint gets: a limit or a loop can stop it short of `to`, and // the default count is for the motion up to there. One more drive toward `to` then finds @@ -145,7 +361,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { let mut end = t.scratch(); drive_to(&mut end, to)?; let n = geometry.samples(&t, &end).map_err(|e| match e { - crate::EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (or give a `step`)")), + EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (or give a `step`)")), e => e, })?; let got = reached(&end); @@ -163,7 +379,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { samples.push(json!({"value": shown(v)})); return Ok(()); } - let gaps = geometry.gaps(t, f64::INFINITY, work, MAX_WORK)?; + let gaps = geometry.gaps(t, f64::INFINITY, work, budget)?; match gaps.first() { Some(g) => samples.push(json!({"value": shown(v), "min_gap_mm": g.mm, "pair": [g.a.1, g.b.1]})), None => samples.push(json!({"value": shown(v), "min_gap_mm": null, "pair": null})), @@ -178,24 +394,23 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { Ok(()) }; let contact = |t: &Session, work: &mut usize, geometry: &ContactGeometry| -> Result> { - if let Some(g) = geometry.gaps(t, touch, work, MAX_WORK)?.into_iter().next() { + if let Some(g) = geometry.gaps(t, touch, work, budget)?.into_iter().next() { return Ok(Some(g)); } if !resting.has_pairs() { return Ok(None); } - let deeper = - resting.hits(t, work, MAX_WORK, true)?.into_iter().find(|(a, b, d)| *d > rest_depth.get(&key(a.0, b.0)).copied().unwrap_or(0.0) + margin); - let Some((a, b, _)) = deeper else { return Ok(None) }; - // Where: the nearest points of that pair (passing into each other, at no gap). - let k = key(a.0, b.0); - let at = resting.gaps(t, touch, work, MAX_WORK)?.into_iter().find(|g| key(g.a.0, g.b.0) == k).map_or((Vec3::ZERO, Vec3::ZERO), |g| g.at); + let depths = resting.depths(t, work, budget)?; + let deeper = depths.iter().enumerate().find(|(i, d)| **d > rest_depth.get(*i).copied().unwrap_or(0.0) + margin(*i)).map(|(i, _)| i); + let Some((i, (a, b))) = deeper.and_then(|i| resting.members(i).map(|m| (i, m))) else { return Ok(None) }; + // Where: the nearest points of those bodies (passing into each other, at no gap). + let at = resting.only(i).gaps(t, touch, work, budget)?.into_iter().next().map_or((Vec3::ZERO, Vec3::ZERO), |g| g.at); Ok(Some(Gap { a, b, mm: 0.0, at })) }; record(&t, from, &mut work, &geometry)?; let (mut lo_doc, mut lo_v): (Arc, f64) = (t.doc.clone(), from); - let mut stop: Option<(f64, Value)> = None; + let mut stop: Option<(f64, Stop)> = None; for target in targets { let r = drive_to(&mut t, target)?; let v = reached(&t); @@ -217,7 +432,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { } t.doc = lo_doc.clone(); let at = (hit.at.0 + hit.at.1) * 0.5; - stop = Some((lo_v, json!({"a": hit.a.1, "b": hit.b.1, "at": [at.x, at.y, at.z]}))); + stop = Some((lo_v, Stop::Contact { a: hit.a.1, b: hit.b.1, at: [at.x, at.y, at.z] })); break; } // (The drive on toward `to` past a limit stays where the last sample was.) @@ -225,37 +440,24 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { record(&t, v, &mut work, &geometry)?; } if r["stopped_by_loop"].is_object() { - stop = Some((v, json!("loop"))); + stop = Some((v, Stop::Other(Why::Loop))); break; } if (v - target).abs() > 1e-9 { - stop = Some((v, json!("limit"))); + stop = Some((v, Stop::Other(Why::Limit))); break; } (lo_doc, lo_v) = (t.doc.clone(), v); } - - let applied = apply && !Arc::ptr_eq(&t.doc, &s.doc); - if applied { - let mut doc = (*t.doc).clone(); - doc.assembly.contact_enabled = s.doc.assembly.contact_enabled; - *s.doc_mut() = doc; - } - let mut out = json!({ - "joint": id, "name": name, "index": index, "unit": if angle { "deg" } else { "mm" }, - "from": shown(from), "to": shown(to), - "stopped_at": stop.as_ref().map(|(v, _)| shown(*v)), - "stopped_by": stop.map(|(_, by)| by), - "samples": samples, - "refine_mm": refine, - "gap_method": "mesh", "gap_tolerance_mm": geometry.chord(), - "pairs": geometry.pair_count() + resting.pair_count(), - "touching_at_start": touching_names, - "applied": applied, - }); - if report_gaps { - out["min_gap"] = - nearest.into_iter().map(|(k, g)| (k, json!({"mm": g.mm, "at_value": g.at, "to": g.to}))).collect::>().into(); - } - Ok(out) + let pairs = geometry.pair_count() + resting.pair_count(); + Ok(Swept { + stop, + samples, + nearest, + touching: touching_names, + overlapping: overlapping.into_values().collect(), + pairs, + chord: geometry.chord(), + doc: t.doc, + }) } diff --git a/crates/engine/src/cmd/motion_sweep_tests.rs b/crates/engine/src/cmd/motion_sweep_tests.rs index 4802100d2..9d85dfe6d 100644 --- a/crates/engine/src/cmd/motion_sweep_tests.rs +++ b/crates/engine/src/cmd/motion_sweep_tests.rs @@ -1,9 +1,12 @@ //! `joint.sweep` against stops worked out by hand: a door swinging into a block, the four-bar's //! rocker meeting a stop and a Watt six-bar's output link meeting one, each checked against the //! linkage solved with circle intersections and a separating-axis test of the parts' outlines. +//! `joint.find_limits` against the same stops met both ways, a slider, the four-bar's toggles +//! and the Hinge Assembly sample. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::{four_bar, meet, occ, part, pin, run}; use crate::Session; @@ -305,3 +308,174 @@ fn a_watt_six_bar_output_meets_a_stop() { let names = [r["stopped_by"]["a"].as_str(), r["stopped_by"]["b"].as_str()]; assert!(names.contains(&Some("Output:1")) && names.contains(&Some("Stop:1")), "{r}"); } + +/// The limits `joint.find_limits` found for the joint's first value: (min, max, min_by, max_by). +fn limits(r: &Value) -> (f64, f64, Value, Value) { + let v = &r["values"][0]; + (num(&v["min"]), num(&v["max"]), v["min_by"].clone(), v["max_by"].clone()) +} + +/// A stop (or overlap) between parts `a` and `b`. +fn by_parts(by: &Value, a: &str, b: &str) -> bool { + let names = [by["a"].as_str(), by["b"].as_str()]; + names.contains(&Some(a)) && names.contains(&Some(b)) +} + +/// Opened, the door meets the block as in `a_door_swings_until_it_meets_the_block`; closed the +/// other way round, the face through its hinge line reaches the block's corner (60, 50) first, +/// a turn back. Its own limits are left out of the search, and the design is not changed. +#[test] +fn find_limits_meets_the_block_both_ways_round() { + let mut s = door(); + run(&mut s, "joint.limits", json!({"joint": "Hinge", "min": -30, "max": 10})); + let corner = |x: f64, y: f64| y.atan2(x) - (4.0 / x.hypot(y)).asin(); + let max = [(60.0, 30.0), (80.0, 30.0), (60.0, 50.0), (80.0, 50.0)].iter().map(|(x, y)| corner(*x, *y)).fold(f64::INFINITY, f64::min).to_degrees(); + let min = 50f64.atan2(60.0).to_degrees() - 360.0; + let before = s.doc.clone(); + let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge", "refine": 0.001})); + assert_eq!(*s.doc, *before, "the search leaves the design as it was"); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert!((hi - max).abs() < 0.01 && hi <= max + 1e-9, "max {hi}°, the block is met at {max}°: {r}"); + assert!((lo - min).abs() < 0.01 && lo >= min - 1e-9, "min {lo}°, the block is met at {min}°: {r}"); + assert!(by_parts(&lo_by, "Door:1", "Block:1") && by_parts(&hi_by, "Door:1", "Block:1"), "{r}"); + assert_eq!((r["values"][0]["unit"].as_str(), num(&r["values"][0]["value"]), num(&r["values"][0]["range"])), (Some("deg"), 0.0, 360.0)); + assert!(r["touching_at_start"].as_array().is_some_and(Vec::is_empty) && r["overlapping_at_start"].as_array().is_some_and(Vec::is_empty), "{r}"); +} + +/// A door that meets nothing on a whole turn either way gets a turn, half each way from where +/// it is: alone (nothing to meet, nothing swept) and with a lamp above it. +#[test] +fn find_limits_of_a_door_that_meets_nothing_spans_a_turn() { + let mut s = Session::default(); + block(&mut s, "Door", [0.0, 0.0, 0.0], [100.0, 4.0, 50.0]); + run( + &mut s, + "joint.create", + json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}), + ); + run(&mut s, "joint.drive", json!({"joint": "Hinge", "value": 30})); + for lamp in [false, true] { + if lamp { + block(&mut s, "Lamp", [0.0, 0.0, 80.0], [20.0, 20.0, 20.0]); + } + let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge"})); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert!((lo + 150.0).abs() < 1e-6 && (hi - 210.0).abs() < 1e-6, "{lo}° … {hi}°"); + assert_eq!((lo_by, hi_by, num(&r["pairs"])), (json!("turn"), json!("turn"), if lamp { 1.0 } else { 0.0 }), "{r}"); + } +} + +/// A slider pushed into a wall stops where they meet; the other way it meets nothing within the +/// parts' reach, and that side has no limit. +#[test] +fn find_limits_of_a_slider_leaves_a_free_side_open() { + let mut s = Session::default(); + block(&mut s, "Slide", [0.0, 0.0, 0.0], [10.0, 10.0, 10.0]); + block(&mut s, "Wall", [50.0, -20.0, -20.0], [10.0, 50.0, 50.0]); + let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [1, 0, 0]}); + run(&mut s, "joint.create", json!({"type": "slider", "a": at("Wall"), "b": at("Slide"), "flip": true, "name": "Rail"})); + let id = occ(&s, "Wall"); + run(&mut s, "occurrence.ground", json!({"occurrence": id, "grounded": true})); + let r = run(&mut s, "joint.find_limits", json!({"joint": "Rail", "refine": 0.001})); + let v = &r["values"][0]; + // The joint's value grows one way or the other along X: the wall is met 40 mm away. + let (closed, open) = if v["max"].is_null() { ("min", "max") } else { ("max", "min") }; + assert!((num(&v[closed]).abs() - 40.0).abs() < 0.002 && num(&v[closed]).abs() <= 40.0 + 1e-9, "{r}"); + assert!(by_parts(&v[format!("{closed}_by")], "Slide:1", "Wall:1"), "{r}"); + assert!(v[open].is_null() && v[format!("{open}_by")] == "range", "{r}"); + assert_eq!(v["unit"], "mm"); + assert!(num(&v["range"]) > 60.0, "the parts reach past the wall: {r}"); +} + +/// The four-bar's rocker swings between its toggles, where the loop can no longer close (|Q| = +/// 70 and |Q| = 30, about 69.3° and 139.2° from the ground line): both sides stop there. +#[test] +fn find_limits_of_a_four_bar_rocker_stops_at_its_toggles() { + let (mut s, _, q0) = four_bar(); + let start = q0.y.atan2(q0.x - 45.0).to_degrees(); + // |Q|² = 45² + 40² + 2·45·40·cos φ. + let toggle = |q: f64| ((q * q - 3625.0) / 3600.0).acos().to_degrees() - start; + let r = run(&mut s, "joint.find_limits", json!({"joint": "Rocker", "occurrences": ["Rocker"], "against": ["Ground"]})); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert_eq!((lo_by, hi_by), (json!("loop"), json!("loop")), "{r}"); + assert!(hi > toggle(30.0) - 1.0 && hi <= toggle(30.0) + 1e-6, "max {hi}°, the loop closes up to {}°", toggle(30.0)); + assert!(lo < toggle(70.0) + 1.0 && lo >= toggle(70.0) - 1e-6, "min {lo}°, the loop closes down to {}°", toggle(70.0)); +} + +/// The Hinge Assembly sample (#5968): its leaves sit end to end along the pin, mated face to face +/// at the pin's end, so they touch across that end and meet nothing else on a whole turn either +/// way. A whole turn each way is what `joint.sweep` ran out of work on (from 60° to 360°); the +/// search has the room for it. +#[test] +fn find_limits_of_the_hinge_sample_spans_a_turn() { + let sample = crate::sample::samples().into_iter().find(|x| x.name == "Hinge Assembly").expect("the hinge sample"); + let mut s = Session::default(); + s.run_script(&(sample.script)()).unwrap_or_else(|e| panic!("{e}")); + let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge"})); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert!((lo + 120.0).abs() < 1e-6 && (hi - 240.0).abs() < 1e-6, "{lo}° … {hi}°: {r}"); + assert_eq!((lo_by, hi_by), (json!("turn"), json!("turn")), "{r}"); + let touching = r["touching_at_start"].as_array().cloned().unwrap_or_default(); + assert!(touching.len() == 1 && touching[0].as_array().is_some_and(|p| p.contains(&json!("Leaf A:1")) && p.contains(&json!("Leaf B:1"))), "{r}"); + assert!(r["overlapping_at_start"].as_array().is_some_and(Vec::is_empty), "{r}"); + // The same whole turn fits `joint.sweep`'s own work now (pairs whose boxes only touch cost + // nothing), where it ran out going from 60° to 0° two degrees at a time. + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 60, "to": 0, "step": 2})); + assert!(r["stopped_by"].is_null(), "{r}"); +} + +/// Two parts of two bodies each: a post with a pin of radius 5 on Z and a stop block at +/// (40…50, 10…20), and an arm turning about Z with a pin of radius 3 inside the post's (the pins +/// are in each other where it starts, as deep wherever the arm turns) and a 4 mm plate from x 10 +/// to 60. The plate's faces, 2 mm off the axis, meet the block's corners as the door's do: the +/// pins in each other must not hide that. +#[test] +fn find_limits_sees_arms_meet_behind_pins_already_in_each_other() { + let mut s = Session::default(); + for (name, corner, size, radius) in [("Post", [40.0, 10.0, 0.0], [10.0, 10.0, 20.0], 5), ("Arm", [10.0, -2.0, 0.0], [50.0, 4.0, 20.0], 3)] { + block(&mut s, name, corner, size); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 0], "axis": [0, 0, 1], "radius": radius, "height": 20, "operation": "new"})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + let post = occ(&s, "Post"); + run(&mut s, "occurrence.ground", json!({"occurrence": post, "grounded": true})); + let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [0, 0, 1]}); + run(&mut s, "joint.create", json!({"type": "revolute", "a": at("Post"), "b": at("Arm"), "flip": true, "name": "Swing"})); + let corners = [(40.0f64, 10.0f64), (50.0, 10.0), (40.0, 20.0), (50.0, 20.0)]; + let max = corners.iter().map(|(x, y)| y.atan2(*x) - (2.0 / x.hypot(*y)).asin()).fold(f64::INFINITY, f64::min).to_degrees(); + let min = corners.iter().map(|(x, y)| y.atan2(*x) + (2.0 / x.hypot(*y)).asin()).fold(f64::NEG_INFINITY, f64::max).to_degrees() - 360.0; + let r = run(&mut s, "joint.find_limits", json!({"joint": "Swing", "refine": 0.001})); + let (lo, hi, lo_by, hi_by) = limits(&r); + // The joint's value may grow either way round Z. + let near = |a: f64, b: f64| (a - b).abs() < 0.05; + assert!((near(hi, max) && near(lo, min)) || (near(hi, -min) && near(lo, -max)), "{lo}° … {hi}°, the block is met at {max}° and {min}°: {r}"); + assert!(by_parts(&lo_by, "Arm:1", "Post:1") && by_parts(&hi_by, "Arm:1", "Post:1"), "{r}"); + let overlapping = r["overlapping_at_start"].as_array().cloned().unwrap_or_default(); + assert!(overlapping.len() == 1 && by_parts(&overlapping[0], "Arm:1", "Post:1") && num(&overlapping[0]["depth_mm"]) > 1.0, "{r}"); +} + +#[test] +fn find_limits_refuses_what_it_cannot_do() { + let mut s = door(); + for p in [ + json!({}), + json!({"joint": "Nope"}), + json!({"joint": 5.5}), + json!({"joint": "Hinge", "index": 1}), + json!({"joint": "Hinge", "index": -1}), + json!({"joint": "Hinge", "refine": 0}), + json!({"joint": "Hinge", "refine": 1e9}), + json!({"joint": "Hinge", "refine": "nan"}), + json!({"joint": "Hinge", "step": 0}), + json!({"joint": "Hinge", "step": -1}), + json!({"joint": "Hinge", "step": 1e-9}), + json!({"joint": "Hinge", "occurrences": ["Door"]}), + json!({"joint": "Hinge", "against": ["Block"]}), + json!({"joint": "Hinge", "occurrences": ["Door"], "against": ["Door"]}), + json!({"joint": "Hinge", "occurrences": ["Door", "Block"], "contact_sets": true}), + ] { + assert!(s.execute("joint.find_limits", &p).is_err(), "{p}"); + } + run(&mut s, "joint.as_built", json!({"type": "rigid", "a": "Block", "b": "Door", "name": "Lock"})); + assert!(s.execute("joint.find_limits", &json!({"joint": "Lock"})).is_err(), "a rigid joint does not move"); +} diff --git a/crates/engine/src/cmd/motion_tests.rs b/crates/engine/src/cmd/motion_tests.rs index f4e88fb36..eca7cc1ae 100644 --- a/crates/engine/src/cmd/motion_tests.rs +++ b/crates/engine/src/cmd/motion_tests.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::Session; @@ -38,6 +39,46 @@ fn deleted_motion_item_ids_are_not_reused_after_reopening() { } } +/// #9738: a default name skips the names in use, after a delete too: contact sets, motion +/// studies, exploded views, and the placements of a component. +#[test] +fn default_names_skip_names_in_use() { + for (create, delete, key, params, prefix) in [ + ("contact.create", "contact.edit", "set", json!({"occurrences": ["A", "B"]}), "Contact Set"), + ("motion.study", "motion.delete", "study", json!({"steps": 10}), "Motion Study"), + ("explode.create", "explode.delete", "view", json!({"moves": [{"occurrence": "B", "translate": [20, 0, 0]}]}), "Exploded View"), + ] { + let mut s = Session::default(); + for name in ["A", "B"] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + } + let made = |s: &mut Session| { + let r = run(s, create, params.clone()); + (r[key].as_u64().unwrap(), r["name"].as_str().unwrap().to_string()) + }; + let (first, one) = made(&mut s); + let (_, two) = made(&mut s); + assert_eq!([one, two], [format!("{prefix}1"), format!("{prefix}2")]); + run(&mut s, delete, json!({key: first, "delete": true})); + assert_eq!(made(&mut s).1, format!("{prefix}1"), "{create}: the free name, not {prefix}2 again"); + } + // Placements: with the first deleted, a copy takes a name none has. + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Arm"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(&mut s, "component.activate", json!({"component": "root"})); + let arm = occ(&s, "Arm"); + for _ in 0..2 { + run(&mut s, "occurrence.copy", json!({"occurrence": arm, "translate": [20, 0, 0]})); + } + let names = |s: &Session| s.doc.occurrences.iter().map(|o| o.name.clone()).collect::>(); + assert_eq!(names(&s), ["Arm:1", "Arm:2", "Arm:3"]); + run(&mut s, "selection.delete", json!({"occurrences": ["Arm:1"]})); + run(&mut s, "occurrence.copy", json!({"occurrence": "Arm:3", "translate": [20, 0, 0]})); + assert_eq!(names(&s), ["Arm:2", "Arm:3", "Arm:1"]); +} + /// Where B's corner (20, 0, 0) is now. fn b_x(s: &Session) -> f64 { super::world_point(s, occ(s, "B"), Vec3::new(20.0, 0.0, 0.0)).x @@ -107,7 +148,7 @@ fn assert_joint_only_moves(s: &mut Session, joint: &str) { use std::sync::Arc; let definitions = s.model.state(); let meshes: Vec<_> = definitions.bodies.iter().map(|b| b.mesh()).collect(); - for body in &s.world_state().bodies { + for body in &s.world_state().unwrap().bodies { std::hint::black_box(body.mesh()); std::hint::black_box(body.display_plan()); } @@ -127,7 +168,7 @@ fn assert_joint_only_moves(s: &mut Session, joint: &str) { for (b, mesh) in current.bodies.iter().zip(&meshes) { assert!(Arc::ptr_eq(&b.mesh(), mesh), "{}: canonical mesh replaced", b.name); } - let world = s.world_state(); + let world = s.world_state().unwrap(); let (_, work) = crate::kernel::profile::capture(|| { for b in &world.bodies { let local = definitions.body(b.definition_name()).unwrap().mesh(); @@ -200,7 +241,7 @@ fn joint_pose_second_occurrence_shares_the_definition() { let mut s = joined_motion_part(PartAuthoring::InComponent, JoinSelection::Named); let second = run(&mut s, "occurrence.copy", json!({"component":"Rotor","translate":[40,0,0]}))["occurrence"].as_u64().unwrap(); run(&mut s, "joint.as_built", json!({"type":"revolute","name":"Copy turn","a":0,"b":second,"at":{"occurrence":0,"point":[40,0,0],"z":[0,0,1]}})); - assert_eq!(s.world_state().bodies.len(), 2); + assert_eq!(s.world_state().unwrap().bodies.len(), 2); assert_joint_only_moves(&mut s, "Copy turn"); assert_motion_matches_full_rebuild(&s); } @@ -639,6 +680,35 @@ fn motion_study_plays_and_exports() { assert_eq!(run(&mut s, "motion.list", json!({}))["studies"].as_array().map(Vec::len), Some(0)); } +/// Regression (#9741): `motion.study` takes degrees for angle keys, so `motion.list` must give +/// the keys back in those same units — feeding a listed study straight back to `motion.study` +/// must not turn a 90° key into 1.57°. +#[test] +fn motion_list_round_trips_key_units_through_motion_study() { + let hinge_deg = |s: &mut Session| { + run(s, "joint.list", json!({}))["joints"] + .as_array() + .and_then(|a| a.iter().find(|j| j["name"] == "Hinge").cloned()) + .and_then(|j| j["values"][0]["value"].as_f64()) + .unwrap_or(f64::NAN) + }; + let mut s = hinged_plates(0.0); + run(&mut s, "motion.study", json!({"name": "Turn", "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [10, 90]]}]})); + run(&mut s, "motion.play", json!({"study": "Turn", "step": 10})); + assert!((hinge_deg(&mut s) - 90.0).abs() < 1e-6, "playing step 10 gave {}°", hinge_deg(&mut s)); + let listed = run(&mut s, "motion.list", json!({})); + let key = &listed["studies"][0]["keys"][0]; + assert_eq!(key["joint_name"], "Hinge"); + assert_eq!(key["unit"], "deg"); + assert!((key["points"][1][1].as_f64().unwrap_or(f64::NAN) - 90.0).abs() < 1e-6, "{listed}"); + // The listed keys go back to `motion.study` unchanged and the study still plays 90°. + let keys = listed["studies"][0]["keys"].clone(); + run(&mut s, "motion.study", json!({"study": "Turn", "keys": keys})); + run(&mut s, "motion.play", json!({"study": "Turn", "step": 0})); + run(&mut s, "motion.play", json!({"study": "Turn", "step": 10})); + assert!((hinge_deg(&mut s) - 90.0).abs() < 1e-6, "the round-tripped study played {}°", hinge_deg(&mut s)); +} + #[test] fn exploded_views_show_without_changing_the_design() { let mut s = rail(); @@ -648,10 +718,22 @@ fn exploded_views_show_without_changing_the_design() { run(&mut s, "explode.show", json!({"view": "Apart"})); // Centres at x 5 and 25 → middle 15: each moves 10 mm further out. let bb = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["bodies"][0]["bbox"]["min"][0].as_f64().unwrap_or(f64::NAN); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); assert!((bb(&mut s, &names[0]) + 10.0).abs() < 1e-6, "{names:?}"); assert!((bb(&mut s, &names[1]) - 30.0).abs() < 1e-6); assert_eq!(s.doc.occurrences, before, "shown only"); + // The design's placements are not the view's: the properties report where the design + // places B, and Capture Position has nothing of the view's to keep (it stays shown). + let b_id = occ(&s, "B"); + let centre = + |s: &mut Session| run(s, "occurrence.properties", json!({"occurrence": b_id}))["total"]["center_of_mass"][0].as_f64().unwrap_or(f64::NAN); + run(&mut s, "explode.show", json!({"view": null})); + let placed = centre(&mut s); + run(&mut s, "explode.show", json!({"view": "Apart"})); + assert!((centre(&mut s) - placed).abs() < 1e-9, "{} shown, {placed} placed", centre(&mut s)); + assert_eq!(run(&mut s, "component.capture_position", json!({}))["captured"], 0); + assert_eq!(s.doc.occurrences, before, "the exploded view is never captured"); + assert!((bb(&mut s, &names[1]) - 30.0).abs() < 1e-6, "still shown"); run(&mut s, "explode.show", json!({"view": null})); assert!(bb(&mut s, &names[0]).abs() < 1e-6); run(&mut s, "explode.create", json!({"name": "Hand", "moves": [{"occurrence": "B", "translate": [0, 0, 50]}]})); @@ -662,6 +744,33 @@ fn exploded_views_show_without_changing_the_design() { assert_eq!(run(&mut s, "explode.list", json!({}))["views"].as_array().map(Vec::len), Some(2)); } +/// #9142: on a part of plain bodies (the sample plate) Exploded View opened its dialog and failed +/// on OK ("an exploded view needs two or more occurrences"). It is greyed out instead, saying why, +/// until the design has two components to pull apart. +#[test] +fn exploded_view_is_greyed_out_until_there_are_two_components() { + let spec = crate::cmd::find_command("explode.create").unwrap(); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Plate"})); + let info = spec.info(&s); + assert!(!info.enabled, "a part of plain bodies has nothing to explode"); + assert_eq!(info.disabled_reason.as_deref(), Some(super::EXPLODE_NEEDS_COMPONENTS)); + let e = s.execute("explode.create", &json!({"scale": 1.62})).unwrap_err(); + assert!(e.to_string().contains("two or more of them"), "{e}"); + assert!(s.doc.assembly.exploded.is_empty(), "nothing was added: {e}"); + // One component is still nothing to pull apart. + run(&mut s, "component.from_bodies", json!({"bodies": ["Plate"]})); + assert_eq!(s.doc.occurrences.len(), 1); + assert!(!spec.info(&s).enabled); + // A second one brings it back, and the automatic view separates the two. + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Lid"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0]})); + assert!(spec.info(&s).enabled, "{:?}", spec.info(&s).disabled_reason); + let r = run(&mut s, "explode.create", json!({"scale": 1.62})); + assert_eq!(r["moves"].as_array().map(Vec::len), Some(2), "{r}"); +} + /// Pictures drawn by the CPU rasterizer (the engine has no GPU): real views of the scene. fn cpu(scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32) -> Result { Ok(crate::capture::Picture { rgba: crate::render::render(scene, cam, w as usize, h as usize).rgba, renderer: "cpu" }) diff --git a/crates/engine/src/cmd/motion_trace.rs b/crates/engine/src/cmd/motion_trace.rs index 531bf5657..dad460307 100644 --- a/crates/engine/src/cmd/motion_trace.rs +++ b/crates/engine/src/cmd/motion_trace.rs @@ -1,14 +1,15 @@ //! Associative trace definitions and dependency checks. Sampling uses the existing motion //! driver on a scratch session; only a changed generated wire is handed to the evaluator. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::joints::{self, JointOrigin, Snap}; use solidcraft_doc::motion::{MotionTrace, TraceMotion}; use solidcraft_doc::{IDENTITY, apply_point}; -use solidcraft_geom::Vec3; use crate::params::{bad, bool_}; use crate::{Result, Session}; diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index e259e017b..b2c8552f9 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -1,6 +1,7 @@ // Exact occurrence workflows through the same commands used by the Browser. use crate::Session; use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, command: &str, p: Value) -> Value { s.execute(command, &p).unwrap() @@ -101,6 +102,38 @@ fn renaming_a_parent_preserves_hidden_nested_copies_with_ambiguous_labels() { } } +#[test] +fn body_rename_reusing_hidden_names_preserves_each_copy() { + let mut s = Session::default(); + let (component, first) = created(&mut s, "Part"); + let retired = run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "Retired"}))["feature"].as_u64().unwrap(); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [10, 0, 0], "body_name": "Visible"})); + let second = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20, 0, 0]}))["occurrence"].as_u64().unwrap(); + let name = |s: &Session, source: &str, path: &[u64]| { + s.occurrence_placement(path).unwrap().bodies.iter().find(|b| b.source == source).unwrap().world.clone() + }; + let retired_names = [name(&s, "Retired", &[first]), name(&s, "Retired", &[second])]; + run(&mut s, "browser.visibility", json!({"items": retired_names, "visible": false})); + run(&mut s, "timeline.delete", json!({"feature": retired})); + let hidden = name(&s, "Visible", &[second]); + run(&mut s, "browser.visibility", json!({"items": [hidden], "visible": false})); + let before = s.visibility.clone(); + for (command, params, source) in [ + ("body.rename", json!({"body": "Visible", "name": "Retired"}), "Retired"), + ("edit.undo", json!({}), "Visible"), + ("edit.redo", json!({}), "Retired"), + ] { + run(&mut s, command, params); + assert!(s.body_visible(&name(&s, source, &[first])), "{command}: the first copy stays visible"); + assert!(!s.body_visible(&name(&s, source, &[second])), "{command}: the second copy stays hidden"); + if command == "edit.undo" { + assert_eq!(s.visibility, before); + } else { + assert_eq!(s.visibility.hidden_bodies, [name(&s, source, &[second])]); + } + } +} + /// The world name of a placed body as `Document::world_body_name` worked it out before /// `WorldNames` (each name scanning the whole design), kept to prove the two agree. fn world_name_by_scanning(doc: &crate::doc::Document, st: &crate::doc::ModelState, source: &str, component: u64, path: &[u64]) -> String { @@ -248,7 +281,7 @@ fn instance_selection_delete_removes_only_selected_instance() { run(&mut s, "selection.delete", json!({"items": items})); assert!(s.doc.occurrences.iter().any(|o| o.id == first)); assert!(!s.doc.occurrences.iter().any(|o| o.id == second)); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); assert!(s.doc.components.iter().any(|c| c.id == component)); } @@ -343,7 +376,7 @@ fn synthesized_name_collision_keeps_source_and_instance_separate() { let instance = s.occurrence_bodies(&[second], false).unwrap()[0].clone(); assert_ne!(instance, candidate); let frames = s.doc.body_frames(&s.model.state()); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(frames.iter().all(|(name, _, _, _)| world.body(name).is_some())); assert_eq!(world.bodies.len(), world.bodies.iter().map(|b| &b.name).collect::>().len()); run(&mut s, "browser.visibility", json!({"visible":false,"paths":[[second]]})); @@ -497,7 +530,7 @@ fn isolate_nested_child_hides_ancestor_material_and_sibling() { .add_occurrence( child_component, parent_component, - solidcraft_doc::rigid(crate::geom::Vec3::new(20.0, 0.0, 0.0), crate::geom::Vec3::ZERO, crate::geom::Vec3::Z, 0.0), + solidcraft_doc::rigid(solidcore_record::Vec3::new(20.0, 0.0, 0.0), solidcore_record::Vec3::ZERO, solidcore_record::Vec3::Z, 0.0), ) .unwrap(); s.refresh(); @@ -508,6 +541,84 @@ fn isolate_nested_child_hides_ancestor_material_and_sibling() { } } +/// #7896: isolating a body hides its own component's other bodies one by one and every other +/// placement as a placement, so the Browser row of a component shows it is off and its eye +/// brings it back. A second placement of the body's own component is another placement. +/// #7896: isolating a body inside a hidden Bodies folder or group shows that folder and group +/// again, so the body is visible; the folder's other bodies stay hidden. +#[test] +fn isolate_shows_the_hidden_folder_and_group_a_picked_body_is_in() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Kept"})); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"corner":[20,0,0],"body_name":"Other","operation":"new"})); + let group = run(&mut s, "browser.group", json!({"folder": "bodies", "items": ["Kept"], "name": "Held"})); + let group = group["group"].as_u64().or_else(|| group["id"].as_u64()).expect("the group's id"); + run(&mut s, "browser.visibility", json!({"tree_folders": ["c0/bodies", format!("c0/g{group}")], "visible": false})); + assert!(!s.body_visible("Kept") && !s.body_visible("Other")); + run(&mut s, "browser.visibility", json!({"items": ["Kept"], "visible": true, "isolate": true})); + assert!(s.body_visible("Kept"), "the picked body shows: {:?}", s.visibility.hidden_folders); + assert!(!s.body_visible("Other"), "the folder's other body stays hidden"); + assert!(s.visibility.hidden_folders.is_empty(), "{:?}", s.visibility.hidden_folders); +} + +#[test] +fn isolate_bodies_hides_other_components_as_components() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"corner":[-20,0,0],"body_name":"Root"})); + let comp = |s: &mut Session, name: &str| { + let c = run(s, "component.create", json!({"name": name, "parent": "root", "grounded": false})); + c["occurrence"].as_u64().unwrap() + }; + let a = comp(&mut s, "CompA"); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"BoxA"})); + run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":[0,0,20],"body_name":"BoxA2"})); + let b = comp(&mut s, "CompB"); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"corner":[20,0,0],"body_name":"BoxB1"})); + run(&mut s, "solid.box", json!({"length":5,"width":5,"height":5,"corner":[40,0,0],"body_name":"BoxB2"})); + let a2 = run(&mut s, "occurrence.copy", json!({"occurrence":a,"translate":[0,40,0]}))["occurrence"].as_u64().unwrap(); + let in_a = s.occurrence_bodies(&[a], false).unwrap(); + let (box_a, box_a2) = (in_a.iter().find(|n| !n.contains("BoxA2")).unwrap().clone(), in_a.iter().find(|n| n.contains("BoxA2")).unwrap().clone()); + + let out = run(&mut s, "browser.visibility", json!({"visible":true,"items":[box_a],"isolate":true})); + assert_eq!(out["isolated"], json!([box_a])); + let mut occurrences = s.visibility.hidden_occurrences.clone(); + occurrences.sort(); + let mut others = vec![vec![b], vec![a2]]; + others.sort(); + assert_eq!(occurrences, others, "CompB and CompA's other placement go as placements"); + let mut bodies = s.visibility.hidden_bodies.clone(); + bodies.sort(); + assert_eq!(bodies, vec![box_a2.clone(), "Root".to_string()], "only bodies beside BoxA go one by one"); + assert!(s.body_visible(&box_a) && !s.body_visible(&box_a2) && !s.body_visible("Root")); + for name in s.occurrence_bodies(&[b], false).unwrap().iter().chain(&s.occurrence_bodies(&[a2], false).unwrap()) { + assert!(!s.body_visible(name), "{name}"); + } + // CompB's eye brings it back whole. + run(&mut s, "browser.visibility", json!({"visible":true,"paths":[[b]]})); + assert!(s.occurrence_bodies(&[b], false).unwrap().iter().all(|n| s.body_visible(n))); + + // Isolating a root body hides every placement as a placement and no body one by one. + run(&mut s, "browser.visibility", json!({"visible":true,"items":["Root"],"isolate":true})); + let mut occurrences = s.visibility.hidden_occurrences.clone(); + occurrences.sort(); + let mut all = vec![vec![a], vec![b], vec![a2]]; + all.sort(); + assert_eq!(occurrences, all); + assert!(s.visibility.hidden_bodies.is_empty() && s.body_visible("Root"), "{:?}", s.visibility.hidden_bodies); + + // Only bodies isolate, and only shown; a refusal changes nothing. + let before = s.visibility.clone(); + for p in [ + json!({"visible":false,"items":["Root"],"isolate":true}), + json!({"visible":true,"items":["XY"],"isolate":true}), + json!({"visible":true,"items":["Nope"],"isolate":true}), + json!({"visible":true,"folder":"bodies","isolate":true}), + ] { + assert!(s.execute("browser.visibility", &p).is_err(), "{p}"); + } + assert_eq!(s.visibility, before); +} + #[test] fn context_new_child_uses_inactive_parent_placement() { let mut s = Session::default(); @@ -556,10 +667,10 @@ fn instance_styles_follow_source_identity_after_collision_rename_and_pending_mov let instance = s.occurrence_bodies(&[second], false).unwrap()[0].clone(); let source = s.occurrence_placement(&[second]).unwrap().bodies[0].source.clone(); run(&mut s, "material.assign", json!({"bodies":[instance],"material":"Brass"})); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(s.doc.body_color(world.body(&instance).unwrap()), s.doc.body_color(world.body(&source).unwrap())); run(&mut s, "appearance.assign", json!({"components":[component.to_string()],"color":"#0000ff","opacity":0.7})); - assert_eq!(s.doc.body_color(s.world_state().body(&instance).unwrap()), Some([0.0, 0.0, 1.0])); + assert_eq!(s.doc.body_color(s.world_state().unwrap().body(&instance).unwrap()), Some([0.0, 0.0, 1.0])); run(&mut s, "appearance.assign", json!({"bodies":[instance],"color":"#ff0000","opacity":0.5})); run(&mut s, "appearance.assign", json!({"faces":[{"body":instance,"point":[21,1,2]}],"color":"#00ff00","opacity":0.4})); // Exercise the point-based face fallback as well as persistent face-name matching. @@ -568,7 +679,7 @@ fn instance_styles_follow_source_identity_after_collision_rename_and_pending_mov } run(&mut s, "body.rename", json!({"body":source,"name":"Shared Renamed"})); run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0],"capture":false})); - let world = s.world_state(); + let world = s.world_state().unwrap(); for id in [first, second] { let bodyname = s.occurrence_bodies(&[id], false).unwrap()[0].clone(); let body = world.body(&bodyname).unwrap(); @@ -583,7 +694,7 @@ fn instance_styles_follow_source_identity_after_collision_rename_and_pending_mov assert!((measured["bodies"][0]["mass_g"].as_f64().unwrap() - 0.068).abs() < 1e-8); } let definition = s.model.state(); - assert_eq!(solidcraft_kernel::measure(&definition.body("Shared Renamed").unwrap().body).unwrap().bbox.min, crate::geom::Vec3::ZERO); + assert_eq!(solidcraft_kernel::measure(&definition.body("Shared Renamed").unwrap().body).unwrap().bbox.min, solidcore_record::Vec3::ZERO); let painted = s.doc.painted(&world); let secondname = s.occurrence_bodies(&[second], false).unwrap()[0].clone(); let body = painted.body(&secondname).unwrap(); @@ -734,7 +845,7 @@ fn a_cut_or_join_from_the_top_level_into_a_linked_part_is_refused() { _ => None, }) .unwrap(); - let c = plane.to_local(solidcraft_geom::Vec3::new(55.0, 10.0, 30.0)); + let c = plane.to_local(solidcore_record::Vec3::new(55.0, 10.0, 30.0)); run(&mut s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); run(&mut s, "sketch.finish", json!({})); let features = s.doc.features.len(); @@ -854,7 +965,7 @@ fn a_stood_up_nested_step_part_is_cut_and_joined_from_its_face() { run(&mut src, "occurrence.move", json!({"occurrence": carrier, "translate": [12, 7, 5], "axis": [0, 0, 1], "angle": "30 deg"})); run(&mut src, "occurrence.move", json!({"occurrence": nested, "translate": [3, 11, 2], "axis": [0, 1, 0], "angle": "20 deg"})); // The middle of the top face, in the file's frame: the imported root's. - let top = solidcraft_doc::apply_point(&src.doc.component_transform(part), solidcraft_geom::Vec3::new(20.0, 12.0, 10.0)); + let top = solidcraft_doc::apply_point(&src.doc.component_transform(part), solidcore_record::Vec3::new(20.0, 12.0, 10.0)); run(&mut src, "file.export", json!({"path": path, "format": "step"})); // #5679: the same from the top level, where the part is two moved and turned levels down @@ -881,8 +992,8 @@ fn a_stood_up_nested_step_part_is_cut_and_joined_from_its_face() { .unwrap(); run(&mut s, "sketch.circle.center", json!({"center": [centre.x, centre.y], "radius": 3})); run(&mut s, "sketch.finish", json!({})); - assert_eq!(crate::auto_operation(&s, &json!({"distance": -5})), Some("cut"), "top level {top_level}"); - assert_eq!(crate::auto_operation(&s, &json!({"distance": 5})), Some("join"), "top level {top_level}"); + assert_eq!(crate::auto_operation(&s, &json!({"distance": -5})).unwrap(), Some("cut"), "top level {top_level}"); + assert_eq!(crate::auto_operation(&s, &json!({"distance": 5})).unwrap(), Some("join"), "top level {top_level}"); let volume = |s: &mut Session| run(s, "inspect.measure", json!({"bodies": ["NestedBlock"]}))["total"]["volume_mm3"].as_f64().unwrap(); let block = 40.0 * 24.0 * 10.0; let hole = std::f64::consts::PI * 3.0 * 3.0; @@ -1060,7 +1171,7 @@ fn component_delete_removes_joints_to_its_occurrences_and_undo_restores_them() { /// opened with its imported root active, and a sketch on the part's top face. Returns the /// session, the sketch, the middle of the top face in the root's frame, the face's outward /// normal and that middle in the sketch's coordinates. -fn nested_part_face_sketch() -> (Session, u64, solidcraft_geom::Vec3, solidcraft_geom::Vec3, solidcraft_geom::Vec2) { +fn nested_part_face_sketch() -> (Session, u64, solidcore_record::Vec3, solidcore_record::Vec3, solidcore_record::Vec2) { let dir = std::env::temp_dir().join(format!("solidcraft-nested-scope-{}-{:?}", std::process::id(), std::thread::current().id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("nested.step"); @@ -1070,7 +1181,7 @@ fn nested_part_face_sketch() -> (Session, u64, solidcraft_geom::Vec3, solidcraft run(&mut src, "solid.box", json!({"length": 40, "width": 24, "height": 10, "body_name": "NestedBlock"})); run(&mut src, "occurrence.move", json!({"occurrence": carrier, "translate": [12, 7, 5], "axis": [0, 0, 1], "angle": "30 deg"})); run(&mut src, "occurrence.move", json!({"occurrence": nested, "translate": [3, 11, 2], "axis": [0, 1, 0], "angle": "20 deg"})); - let top = solidcraft_doc::apply_point(&src.doc.component_transform(part), solidcraft_geom::Vec3::new(20.0, 12.0, 10.0)); + let top = solidcraft_doc::apply_point(&src.doc.component_transform(part), solidcore_record::Vec3::new(20.0, 12.0, 10.0)); run(&mut src, "file.export", json!({"path": path, "format": "step"})); let mut s = Session::default(); run(&mut s, "doc.open", json!({"path": path, "up": "y"})); @@ -1271,6 +1382,54 @@ fn reparent_keeps_the_world_position_and_follows_paths() { /// A component can't go inside itself or what it holds. Out of a parent placed more than once it /// moves from the placement named, keeping that one's place in the world. +/// #11063: a part with a hole cut from a sketch on its disc's top face moves into another +/// component. The sketch's face attachment was found through the part's old placement path, +/// which no longer starts at the design once the part is inside the other component, and the +/// move was refused ("would break Sketch2"). The attachment follows the move, and the hole stays. +#[test] +fn reparent_carries_a_sketch_on_a_face_inside_the_moved_part() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Component1", "activate": false})); + run(&mut s, "component.create", json!({"name": "Component2"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Sketch1"})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Sketch1", "distance": 3, "operation": "new"})); + run(&mut s, "sketch.create", json!({"plane": {"face": [0, 5, 3]}, "name": "Sketch2"})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 3})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Sketch2", "distance": -3, "operation": "cut"})); + let volume = |s: &Session| s.world_state().unwrap().bodies.iter().map(|b| b.mesh().measure().volume.abs()).sum::(); + let before = volume(&s); + let r = run(&mut s, "occurrence.reparent", json!({"occurrence": "Component2:1", "parent": "Component1"})); + assert_eq!(r["path"].as_array().map(Vec::len), Some(2), "{r}"); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "every feature still builds"); + assert!((volume(&s) - before).abs() < 1e-6, "the disc keeps its hole: {} vs {before}", volume(&s)); + let reopened = Session::new(crate::doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(reopened.model.results.iter().all(|r| r.error.is_none()), "and after reopening"); +} + +/// A parent placed twice is one definition: a sketch on the child's face made through the +/// second placement moves along when the child is moved out through the first one, to the +/// child's one new place. +#[test] +fn reparent_carries_a_face_sketch_made_through_another_placement_of_the_parent() { + let mut s = Session::default(); + let (parent, first_parent) = created(&mut s, "Assembly"); + let (_, child) = created(&mut s, "Knob"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 0], "body_name": "Knob"})); + let second_parent = run(&mut s, "occurrence.copy", json!({"component": parent, "translate": [20, 0, 0]}))["occurrence"].as_u64().unwrap(); + run(&mut s, "sketch.create", json!({"plane": {"face": [25, 5, 10], "path": [second_parent, child]}, "name": "OnTop"})); + run(&mut s, "sketch.finish", json!({})); + let out = run(&mut s, "occurrence.reparent", json!({"occurrence": child, "parent": "root", "path": [first_parent, child]})); + assert_eq!(out["path"], json!([child])); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "the sketch still finds its face"); + let sketch = s.doc.features.iter().find(|f| f.name == "OnTop").unwrap(); + let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &sketch.kind else { panic!("OnTop is no sketch") }; + let anchor = crate::cmd::sketch::face::anchor(plane).unwrap(); + assert_eq!(anchor.path, vec![child], "{anchor:?}"); +} + #[test] fn reparent_refuses_cycles_and_moves_out_of_a_named_instance() { let mut s = Session::default(); @@ -1351,10 +1510,10 @@ fn pasted_and_moved_things_survive_reopening() { run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [50, 0, 0], "body_name": "Pin"})); run(&mut s, "component.activate", json!({"component": 0})); run(&mut s, "occurrence.reparent", json!({"occurrence": b_at, "parent": a})); - let before = s.world_state(); + let before = s.world_state().unwrap(); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - let after = reopened.world_state(); + let after = reopened.world_state().unwrap(); for name in ["Cube", "Cube (2)", "Pin"] { let (was, is) = (before.body(name).unwrap().mesh().bounds(), after.body(name).unwrap().mesh().bounds()); assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{name}: {was:?} → {is:?}"); @@ -1377,7 +1536,7 @@ fn a_body_seen_in_another_placement_copies_from_there() { assert_ne!(shown, "Cube"); let out = run(&mut s, "component.copy_bodies", json!({"bodies": [shown.clone()], "component": 0})); assert_eq!(out["bodies"], json!(["Cube (2)"])); - let world = s.world_state(); + let world = s.world_state().unwrap(); let (seen, copy) = (world.body(&shown).unwrap().mesh().bounds(), world.body("Cube (2)").unwrap().mesh().bounds()); assert!(seen.min.dist(copy.min) < 1e-6 && seen.max.dist(copy.max) < 1e-6, "{seen:?} vs {copy:?}"); let state = s.model.state(); @@ -1461,7 +1620,7 @@ fn join_extrude_to_a_body_of_another_component_leaves_that_body_alone() { run(&mut s, "solid.cylinder", json!({"radius":6,"height":10,"body_name":"Connector"})); let sketch = run(&mut s, "sketch.create", json!({"plane":{"face":[0,0,10]},"project_edges":false}))["sketch"].as_u64().unwrap(); let plane = s.model.state().sketch(sketch).unwrap().plane; - let centre = plane.to_local(solidcraft_geom::Vec3::new(0.0, 0.0, 10.0)); + let centre = plane.to_local(solidcore_record::Vec3::new(0.0, 0.0, 10.0)); run(&mut s, "sketch.circle.center", json!({"center":[centre.x, centre.y],"radius":4})); run(&mut s, "sketch.finish", json!({})); // The boss runs up to the shell's underside and joins the connector it was sketched on. @@ -1534,7 +1693,7 @@ fn occurrence_align_moves_only_selected_instance_including_90_degree_face_mate() ); assert_eq!(s.doc.features.len(), features_before, "aligning an occurrence must not add a body feature to the shared component"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let b1 = st.body("Beam").unwrap().mesh().bounds(); assert!((b1.min.x - 0.0).abs() < 1e-5 && (b1.max.x - 10.0).abs() < 1e-5, "{b1:?}"); assert!((b1.min.y - 0.0).abs() < 1e-5 && (b1.max.y - 10.0).abs() < 1e-5, "{b1:?}"); @@ -1562,7 +1721,7 @@ fn occurrence_align_supports_snaps_planes_flip_nested_paths_and_pending_capture( run(&mut s, "component.activate", json!({"component": "root"})); // Align the child under a 90-deg rotated parent onto XY plane along plane normal only (capture: false). - let before = s.world_state().body("Plate").unwrap().mesh().bounds(); + let before = s.world_state().unwrap().body("Plate").unwrap().mesh().bounds(); run( &mut s, "occurrence.align", @@ -1573,13 +1732,13 @@ fn occurrence_align_supports_snaps_planes_flip_nested_paths_and_pending_capture( "capture": false }), ); - let moved = s.world_state().body("Plate").unwrap().mesh().bounds(); + let moved = s.world_state().unwrap().body("Plate").unwrap().mesh().bounds(); assert!((moved.min.z - 0.0).abs() < 1e-5 && (moved.max.z - 4.0).abs() < 1e-5, "{moved:?}"); assert!((moved.center().x - before.center().x).abs() < 1e-5 && (moved.center().y - before.center().y).abs() < 1e-5, "{moved:?}"); // Revert drops the pending alignment; re-align with capture: true and vertex snap to origin. run(&mut s, "component.revert_position", json!({})); - assert!((s.world_state().body("Plate").unwrap().mesh().bounds().min.z - 10.0).abs() < 1e-5); + assert!((s.world_state().unwrap().body("Plate").unwrap().mesh().bounds().min.z - 10.0).abs() < 1e-5); run( &mut s, @@ -1591,8 +1750,8 @@ fn occurrence_align_supports_snaps_planes_flip_nested_paths_and_pending_capture( "to": "origin" }), ); - let at_origin = s.world_state().body("Plate").unwrap().mesh().bounds(); - assert!(at_origin.min.dist(solidcraft_geom::Vec3::ZERO) < 1e-5, "{at_origin:?}"); + let at_origin = s.world_state().unwrap().body("Plate").unwrap().mesh().bounds(); + assert!(at_origin.min.dist(solidcore_record::Vec3::ZERO) < 1e-5, "{at_origin:?}"); // Hostile / invalid parameters never panic. for bad_params in [ @@ -1617,7 +1776,7 @@ fn occurrence_align_keeps_every_pick_and_reports_shared_definitions() { run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 4, "body_name": "Plate"})); run(&mut s, "component.activate", json!({"component": "root"})); let b = run(&mut s, "occurrence.copy", json!({"component": frame, "translate": [0, 50, 0]}))["occurrence"].as_u64().unwrap(); - let origin = |s: &Session, path: &[u64]| solidcraft_doc::apply_point(&s.occurrence_placement(path).unwrap().world, solidcraft_geom::Vec3::ZERO); + let origin = |s: &Session, path: &[u64]| solidcraft_doc::apply_point(&s.occurrence_placement(path).unwrap().world, solidcore_record::Vec3::ZERO); let (a0, ab0, b0, bb0) = (origin(&s, &[a]), origin(&s, &[a, bracket]), origin(&s, &[b]), origin(&s, &[b, bracket])); assert!(!s.occurrence_shared(&[a]) && !s.occurrence_shared(&[b]), "top-level placements are their own"); @@ -1627,7 +1786,7 @@ fn occurrence_align_keeps_every_pick_and_reports_shared_definitions() { assert_eq!(r["paths"], json!([[a, bracket], [b]]), "{r}"); assert_eq!(r["shared"], json!([[a, bracket]]), "{r}"); - let shift = solidcraft_geom::Vec3::new(5.0, 0.0, 0.0); + let shift = solidcore_record::Vec3::new(5.0, 0.0, 0.0); assert!(origin(&s, &[a]).dist(a0) < 1e-9, "A itself stays"); assert!(origin(&s, &[a, bracket]).dist(ab0 + shift) < 1e-9, "the picked Bracket moves"); assert!(origin(&s, &[b]).dist(b0 + shift) < 1e-9, "B moves"); @@ -1649,8 +1808,8 @@ fn a_body_copied_in_another_design_pastes_as_an_imported_body() { let (_, holder) = created(&mut source, "Holder"); run(&mut source, "occurrence.move", json!({"occurrence": holder, "translate": [0,50,0]})); run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})); - let was = source.world_state().body("Cube").unwrap().mesh().bounds(); - let copy = crate::ForeignCopy::of(&source, vec!["Cube".into()], Vec::new()); + let was = source.world_state().unwrap().body("Cube").unwrap().mesh().bounds(); + let copy = crate::ForeignCopy::of(&source, vec!["Cube".into()], Vec::new()).unwrap(); let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Cube"})); @@ -1662,7 +1821,7 @@ fn a_body_copied_in_another_design_pastes_as_an_imported_body() { assert_eq!(out["bodies"], json!(["Cube (2)"])); assert_eq!(out["feature"], "Import1"); assert_eq!(s.undo.len(), undo + 1); - let is = s.world_state().body("Cube (2)").unwrap().mesh().bounds(); + let is = s.world_state().unwrap().body("Cube (2)").unwrap().mesh().bounds(); assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}"); let state = s.model.state(); assert_eq!(s.doc.model_body_component(state.body("Cube (2)").unwrap()), a); @@ -1684,13 +1843,13 @@ fn a_body_seen_in_another_placement_pastes_into_another_design_under_its_own_nam run(&mut source, "occurrence.move", json!({"occurrence": second, "translate": [0,40,0]})); let seen = source.placed_document().world_body_name(&source.model.state(), "Cube", holder, &[second]); assert_ne!(seen, "Cube"); - let was = source.world_state().body(&seen).unwrap().mesh().bounds(); - let copy = crate::ForeignCopy::of(&source, vec![seen], Vec::new()); + let was = source.world_state().unwrap().body(&seen).unwrap().mesh().bounds(); + let copy = crate::ForeignCopy::of(&source, vec![seen], Vec::new()).unwrap(); assert_eq!(copy.names, vec!["Cube".to_string()]); let mut s = Session { foreign_copy: Some(std::sync::Arc::new(copy)), ..Default::default() }; let out = run(&mut s, "component.paste_from_design", json!({})); assert_eq!(out["bodies"], json!(["Cube"])); - let is = s.world_state().body("Cube").unwrap().mesh().bounds(); + let is = s.world_state().unwrap().body("Cube").unwrap().mesh().bounds(); assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}"); } diff --git a/crates/engine/src/cmd/offset_edit_guard_tests.rs b/crates/engine/src/cmd/offset_edit_guard_tests.rs index 87187cb67..bbb7bec53 100644 --- a/crates/engine/src/cmd/offset_edit_guard_tests.rs +++ b/crates/engine/src/cmd/offset_edit_guard_tests.rs @@ -1,7 +1,8 @@ #![allow(clippy::unwrap_used, clippy::panic)] use serde_json::{Value, json}; +use solidcore_record::Vec2; use solidcraft_doc::{Document, FeatureKind, ProfileSel}; -use solidcraft_geom::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{CurveKind, Sketch}; use crate::{Session, Snapshot}; @@ -100,10 +101,10 @@ fn offset_guard_live_child_follows_radius_then_retirement_is_honest() { } Ok(_) => { assert!(s.model.results.iter().any(|r| r.error.is_some()), "retired parent must not keep a stale successful child"); - assert!(s.world_state().body("Child").is_none()); + assert!(s.world_state().unwrap().body("Child").is_none()); let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); assert!(reopened.model.results.iter().any(|r| r.error.is_some())); - assert!(reopened.world_state().body("Child").is_none()); + assert!(reopened.world_state().unwrap().body("Child").is_none()); } } } @@ -174,7 +175,7 @@ fn offset_guard_complete_delete_keeps_dangling_profile_loadable_without_circle_r let check = |s: &Session| { assert!(solved(s, sketch).curve_index("Unrelated").is_some()); assert!(s.model.results.iter().find(|r| r.id == s.doc.find_feature("OffsetBody").unwrap().id).unwrap().error.is_some()); - assert!(s.world_state().body("Selected").is_none(), "dangling selection must never adopt the unrelated circle"); + assert!(s.world_state().unwrap().body("Selected").is_none(), "dangling selection must never adopt the unrelated circle"); }; check(&s); let reopened = Session::new(Document::from_json(&saved).unwrap()); diff --git a/crates/engine/src/cmd/offset_ends_tests.rs b/crates/engine/src/cmd/offset_ends_tests.rs index 9ebb58dcd..9c8e9eb55 100644 --- a/crates/engine/src/cmd/offset_ends_tests.rs +++ b/crates/engine/src/cmd/offset_ends_tests.rs @@ -2,6 +2,7 @@ //! #2424: curves start at the ends of an associated offset spline, and follow them. use serde_json::{Value, json}; use solidcraft_doc::Document; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch}; use crate::Session; diff --git a/crates/engine/src/cmd/offset_identity_tests.rs b/crates/engine/src/cmd/offset_identity_tests.rs index df7aba63f..7ceb6e55a 100644 --- a/crates/engine/src/cmd/offset_identity_tests.rs +++ b/crates/engine/src/cmd/offset_identity_tests.rs @@ -129,7 +129,7 @@ fn pasted_offset_boundary_has_scoped_identity_and_independent_dimensions_and_mat healthy(&reopened); assert!((volume(&reopened, extrusion) - sharp).abs() < 1e-6); assert!((volume(&reopened, copied_extrusion) - rounded).abs() < 0.002); - let state = reopened.world_state(); + let state = reopened.world_state().unwrap(); let bounds = state.body(&copied_body).unwrap().mesh().bounds(); assert!((bounds.min.x - (100. - 37.6)).abs() < 1e-6); assert!((bounds.max.x - (100. + 37.6)).abs() < 1e-6); diff --git a/crates/engine/src/cmd/offset_plane_face_tests.rs b/crates/engine/src/cmd/offset_plane_face_tests.rs index 2047ba1c4..db08ed6ea 100644 --- a/crates/engine/src/cmd/offset_plane_face_tests.rs +++ b/crates/engine/src/cmd/offset_plane_face_tests.rs @@ -1,9 +1,10 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use crate::Session; use serde_json::{Value, json}; +use solidcore_record::Plane; use solidcraft_doc::construct::ConstructGeom; use solidcraft_doc::{Document, FeatureKind, PlaneRef}; -use solidcraft_geom::Plane; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap_or_else(|e| panic!("{command} {params}: {e}")) diff --git a/crates/engine/src/cmd/offset_topology_tests.rs b/crates/engine/src/cmd/offset_topology_tests.rs index 1d418e1fa..6880434de 100644 --- a/crates/engine/src/cmd/offset_topology_tests.rs +++ b/crates/engine/src/cmd/offset_topology_tests.rs @@ -1,7 +1,7 @@ #![allow(clippy::unwrap_used, clippy::panic)] use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{FeatureKind, ProfileSel}; -use solidcraft_geom::Vec3; use crate::Session; @@ -18,7 +18,7 @@ fn breaking_offset_preserves_downstream_material_history_and_source_independence let curves = session.model.state().sketch(sketch).unwrap().sketch.offset_boundary(&association).unwrap(); run(&mut session, "sketch.finish", json!({})); run(&mut session, "solid.extrude", json!({"sketch":sketch,"profiles":{"offset_boundaries":[association]},"distance":2,"operation":"new"})); - let before_volume = session.world_state().bodies.last().unwrap().mesh().measure().volume.abs(); + let before_volume = session.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs(); run(&mut session, "sketch.edit", json!({"sketch":sketch})); let before = session.doc.to_json(); let history = session.undo.len(); @@ -29,17 +29,17 @@ fn breaking_offset_preserves_downstream_material_history_and_source_independence matches!(&session.doc.features.last().unwrap().kind, FeatureKind::Extrude { profiles: ProfileSel::Curves { loops }, .. } if loops == &vec![curves.clone()]) ); let frozen = session.doc.to_json(); - assert!((session.world_state().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); + assert!((session.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); run(&mut session, "edit.undo", json!({})); assert_eq!(session.doc.to_json(), before); run(&mut session, "edit.redo", json!({})); assert_eq!(session.doc.to_json(), frozen); run(&mut session, "parameters.change", json!({"name":radius,"expression":"2 mm"})); assert!(session.model.results.iter().all(|result| result.error.is_none())); - assert!((session.world_state().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); + assert!((session.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); let reopened = Session::new(solidcraft_doc::Document::from_json(&session.doc.to_json()).unwrap()); assert!(reopened.model.results.iter().all(|result| result.error.is_none())); - assert!((reopened.world_state().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); + assert!((reopened.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); } } @@ -76,7 +76,7 @@ fn inset_past_corner_radius_creates_a_real_boundary_and_saved_profile_identity() assert!(matches!(&feature.kind, FeatureKind::Extrude { profiles: ProfileSel::OffsetBoundaries { associations }, .. } if associations.len() == 1)); let check = |session: &Session| { assert!(session.model.results.iter().all(|result| result.error.is_none())); - let state = session.world_state(); + let state = session.world_state().unwrap(); let body = state.bodies.last().unwrap(); // The exact inward parallel set is a sharp 73.2 by 63.2 rectangle. let mesh = body.mesh(); @@ -107,3 +107,44 @@ fn inset_past_corner_radius_creates_a_real_boundary_and_saved_profile_identity() assert_eq!(session.redo.len(), redo); } } + +/// #10984: a dog bone whose round ends touch at a cusp on each side. Drawn 2 mm outside, the +/// outline meets in each notch outside the bone, where the two ends' copies cross before +/// their ends. One notch ran both copies on to their far crossing instead, a loop into the +/// bone, as both crossings are as far from the notch. +#[test] +fn an_outline_outside_a_dog_bone_meets_outside_both_notches() { + let mut session = Session::default(); + run(&mut session, "sketch.create", json!({"plane":"XY","name":"Bone"})); + let sketch = session.active_sketch.unwrap(); + run(&mut session, "sketch.line", json!({"points":[[-10,-10],[10,-10]]})); + run(&mut session, "sketch.arc.center_point", json!({"center":[20,-10],"start":[10,-10],"end":[20,0]})); + run(&mut session, "sketch.arc.center_point", json!({"center":[20,10],"start":[20,0],"end":[10,10]})); + run(&mut session, "sketch.line", json!({"points":[[10,10],[-10,10]]})); + run(&mut session, "sketch.arc.center_point", json!({"center":[-20,10],"start":[-10,10],"end":[-20,0]})); + run(&mut session, "sketch.arc.center_point", json!({"center":[-20,-10],"start":[-20,0],"end":[-10,-10]})); + run(&mut session, "sketch.offset", json!({"curves":["l1"],"distance":2,"side":[0,-40]})); + let state = session.model.state(); + let sk = &state.sketch(sketch).unwrap().sketch; + let record = sk.offsets.last().unwrap(); + assert_eq!(record.outputs.len(), 6); + let mut notches: Vec = Vec::new(); + for id in &record.outputs { + let curve = &sk.curves[sk.curve_index(id).unwrap()]; + let (a, b) = match curve.kind { + solidcraft_sketch::CurveKind::Line { a, b } | solidcraft_sketch::CurveKind::Arc { a, b, .. } => (a, b), + _ => panic!("{id} is no line or arc"), + }; + for p in [sk.points[a].pos, sk.points[b].pos] { + if p.y.abs() < 1e-6 { + notches.push(p.x); + } + } + } + notches.sort_by(f64::total_cmp); + // The copies have radius 12 about centres 20 apart: they cross 12² − 10² = 44, √44 off + // the notch's line, outside it: x = ±(20 + √44). + let outside = 20.0 + 44f64.sqrt(); + assert_eq!(notches.len(), 4, "{notches:?}"); + assert!(notches.iter().zip([-outside, -outside, outside, outside]).all(|(x, want)| (x - want).abs() < 1e-6), "{notches:?}"); +} diff --git a/crates/engine/src/cmd/panels.rs b/crates/engine/src/cmd/panels.rs new file mode 100644 index 000000000..67badaf06 --- /dev/null +++ b/crates/engine/src/cmd/panels.rs @@ -0,0 +1,175 @@ +//! Registry metadata for externally injected application-layout commands. +use super::CommandSpec; +use crate::schema::panels as wire; + +fn unavailable(_: &mut crate::Session, _: &serde_json::Value) -> crate::Result { + Err(crate::EngineError::Panel(crate::panels::error(crate::panels::Rule::Capability, "application layout backend was not injected"))) +} + +macro_rules! command { + ($id:literal, $icon:literal, $label:literal, $input:ty, $output:ty, $params:literal) => { + CommandSpec::new($id, $label, crate::checked!($id, unavailable)) + .icon($icon) + .noundo() + .doc_only() + .contract(&wire::CommandContract::<$input>::new($id)) + .output(wire::strict_output::<$output>) + .params($params) + }; +} + +pub static COMMANDS: &[CommandSpec] = &[ + command!( + "layout.apply", + "open", + "Apply Layout", + wire::Apply, + crate::panels::LayoutReply, + "name, expected_revision?: apply preset to current workspace through retained runtime" + ), + command!("layout.get", "list", "Inspect Layout", wire::Empty, wire::GetReply, "{}: committed state and registered workspace summaries"), + command!( + "layout.reset", + "restore", + "Reset Layout", + wire::Revision, + crate::panels::LayoutReply, + "expected_revision?: restore current workspace's registered default" + ), + command!( + "layout.save", + "save", + "Save Layout", + wire::Save, + wire::SaveReply, + "name, overwrite?: false, expected_revision?: save complete envelope in injected catalogue" + ), + command!( + "layout.workspace.select", + "display", + "Select Layout Workspace", + wire::WorkspaceSelect, + wire::WorkspaceReply, + "workspace, expected_revision?: atomically remember outgoing and replace with destination" + ), + command!( + "panel.activate", + "activate", + "Activate Panel Tab", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: activate open tab without focus" + ), + command!( + "panel.close", + "close", + "Close Panel", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: explicit guarded close" + ), + command!( + "panel.collapse", + "fold", + "Collapse Panel Section", + wire::Collapse, + crate::panels::LayoutReply, + "target or legacy id, collapsed, expected_revision?" + ), + command!( + "panel.dismiss", + "close", + "Dismiss Panel Peek", + wire::Revision, + crate::panels::LayoutReply, + "expected_revision?: dismiss temporary collapsed-panel presentation" + ), + command!( + "panel.float", + "move", + "Float Panel", + wire::Move, + crate::panels::LayoutReply, + "target or legacy id, destination: new_section with floating location, expected_revision?" + ), + command!( + "panel.focus", + "fit", + "Focus Panel", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: reopen retained state, activate and request focus" + ), + command!( + "panel.list", + "list", + "List Panels", + wire::Empty, + wire::ListReply, + "{}: committed state, active tabs, capabilities, availability and registered kinds" + ), + command!( + "panel.move", + "move", + "Move Panel", + wire::Move, + crate::panels::LayoutReply, + "target or legacy id, destination: new_section or join_tab, expected_revision?" + ), + command!( + "panel.native_close", + "restore", + "Redock Native Panel Section", + wire::Select, + crate::panels::LayoutReply, + "target: native_host, expected_revision?: native close redocks without cancelling content" + ), + command!( + "panel.open", + "open", + "Open Panel", + wire::Open, + crate::panels::LayoutReply, + "kind, instance, destination?: required for new instance, expected_revision?" + ), + command!( + "panel.peek", + "eye", + "Peek Collapsed Panel", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: transient presentation without resizing" + ), + command!( + "panel.popout", + "display", + "Pop Out Panel", + wire::Move, + crate::panels::LayoutReply, + "target or legacy id, destination: new_section with window location, expected_revision?: web lowers to floating" + ), + command!( + "panel.reset_pair", + "restore", + "Reset Panel Sash", + wire::ResetPair, + crate::panels::LayoutReply, + "first, second, expected_revision?: reset adjacent dock pair to registered default ratio" + ), + command!( + "panel.resize", + "scale", + "Resize Panel Section", + wire::Resize, + crate::panels::LayoutReply, + "target or legacy id, size: {width,height}, expected_revision?" + ), + command!( + "panel.resize_pair", + "scale", + "Resize Panel Sash", + wire::ResizePair, + crate::panels::LayoutReply, + "first, second, first_size, second_size, expected_revision?: conserve adjacent dock pair extent" + ), +]; diff --git a/crates/engine/src/cmd/parameter_sweep.rs b/crates/engine/src/cmd/parameter_sweep.rs index 174f13a65..35664beb9 100644 --- a/crates/engine/src/cmd/parameter_sweep.rs +++ b/crates/engine/src/cmd/parameter_sweep.rs @@ -4,10 +4,11 @@ //! design, many sizes) can be checked across its whole range before it is trusted, and the //! report says what moved where, so a lost face or a flipped joint is found before a part is. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use super::CommandSpec; use crate::params::{bad, num, str_}; diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs index 3f22f176b..cda10522b 100644 --- a/crates/engine/src/cmd/parameters.rs +++ b/crates/engine/src/cmd/parameters.rs @@ -23,8 +23,8 @@ pub static COMMANDS: &[CommandSpec] = &[ activation; driven parameters and restrictions wait for a configuration edit or activation)", ), CommandSpec::new("parameters.list", "List Parameters", list).icon("list").noundo().doc_only().params( - "favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value in its unit, \ - source, feature/input, comment, favorite, uses, used_by, error) and cycles", + "favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value (mm/deg in every \ + reply), display_value (in its own unit), source, feature/input, comment, favorite, uses, used_by, error) and cycles", ), CommandSpec::new("parameters.add", "Add User Parameter", add) .icon("new") @@ -177,8 +177,8 @@ fn change_param(s: &mut Session, p: &Value) -> Result { if let Some(t) = s.doc.text_param(&name) { out["text"] = json!(t.text); } - out["value"] = json!(vals.get(&name).map(|v| v.v)); - out["display_value"] = json!(s.doc.param_display_value(&vals, &name)); + out["value"] = json!(vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v)))); + out["display_value"] = json!(s.doc.param_display_value(&vals, &name).map(expr::round_reported)); out["recomputed"] = json!(s.model.last_recomputed); out["restored"] = json!(s.model.last_restored); out["errors"] = json!(failing(s)); @@ -230,7 +230,18 @@ fn keep_dimension_start(s: &mut Session, name: &str) { } let reference: Vec<_> = stored.points.iter().map(|p| p.pos).collect(); let hold = Hold { points: vec![start], radii: Vec::new() }; - if !solve_with(&mut trial, &hold, Some(&reference), Analysis::StatusOnly, None).keeps_orientation() { + let solved = if trial.offsets.is_empty() && trial.freeform_offsets.is_empty() { + solve_with(&mut trial, &hold, Some(&reference), Analysis::StatusOnly, None).keeps_orientation() + } else { + // A solve against stale offset points can stretch an attached cap into a different + // tangency branch. Keep the start through the complete solve/refresh sequence. + let Some(p) = trial.points.get_mut(start) else { continue }; + p.fixed = true; + s.doc + .solve_sketch_with_analysis(&vals, &mut trial, &stored.driving_values(), Some(stored), Analysis::StatusOnly) + .is_ok_and(|report| report.keeps_orientation()) + }; + if !solved { continue; } if stored.points.len() == trial.points.len() { @@ -269,7 +280,8 @@ fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) - } s.settle_value_edit(solved)?; let (vals, _) = s.doc.param_values(); - let values: serde_json::Map = list.iter().map(|(n, _)| (n.clone(), json!(vals.get(n).map(|v| v.v)))).collect(); + let values: serde_json::Map = + list.iter().map(|(n, _)| (n.clone(), json!(vals.get(n).map(|v| expr::round_reported(expr::reported_value(*v)))))).collect(); let mut out = json!({"changed": values, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored, "errors": failing(s)}); if !switched.is_empty() { out["switched"] = json!(switched); @@ -332,7 +344,7 @@ fn add(s: &mut Session, p: &Value) -> Result { return Ok(json!({"name": name, "unit": solidcraft_doc::text_params::TEXT_UNIT, "text": t.text, "value": null})); } Ok( - json!({"name": name, "unit": s.doc.param(&name).map(|x| x.unit.clone()), "value": vals.get(&name).map(|v| v.v), "display_value": s.doc.param_display_value(&vals, &name)}), + json!({"name": name, "unit": s.doc.param(&name).map(|x| x.unit.clone()), "value": vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))), "display_value": s.doc.param_display_value(&vals, &name).map(expr::round_reported)}), ) } @@ -415,7 +427,9 @@ fn export(s: &mut Session, p: &Value) -> Result { .param_rows() .into_iter() .filter(|r| r.source == "user") - .map(|r| json!({"name": r.name, "expression": r.expression, "unit": r.unit, "value": r.value, "comment": r.comment, "favorite": r.favorite})) + // The `value` field keeps the number in the parameter's own unit, as the CSV + // column does, rounded for reading (#10747). + .map(|r| json!({"name": r.name, "expression": r.expression, "unit": r.unit, "value": r.display_value.or(r.value), "comment": r.comment, "favorite": r.favorite})) .collect(); serde_json::to_string_pretty(&rows).map_err(|e| bad(cmd, e.to_string()))? } @@ -490,7 +504,7 @@ fn evaluate(s: &mut Session, p: &Value) -> Result { (None, Kind::Angle) => v.to_degrees(), (None, _) => v, }; - json!({"ok": true, "value": v, "kind": k, "display_value": shown, "references": refs}) + json!({"ok": true, "value": expr::round_reported(v), "kind": k, "display_value": expr::round_reported(shown), "references": refs}) } Err(err) => json!({"ok": false, "error": err.to_string().trim_start_matches("expression: ").to_string(), "references": refs}), }; @@ -515,7 +529,8 @@ fn complete(s: &mut Session, p: &Value) -> Result { // parameters, then the others. rows.sort_by_key(|r| (!starts(&r.name), !r.favorite, r.source != "user")); for r in rows.into_iter().take(200) { - let v = r.value.map(|v| format!("{v:.4} {}", r.unit).trim().to_string()).unwrap_or_else(|| "error".into()); + // The completion shows the parameter's own unit, so it reads `display_value`. + let v = r.display_value.or(r.value).map(|v| format!("{v:.4} {}", r.unit).trim().to_string()).unwrap_or_else(|| "error".into()); let mut detail = format!("{} = {v}", r.expression); if let (Some(f), Some(i)) = (&r.feature, r.input) { detail.push_str(&format!(" ({f} {i})")); diff --git a/crates/engine/src/cmd/parameters_tests.rs b/crates/engine/src/cmd/parameters_tests.rs index 3c1fe01e1..210737840 100644 --- a/crates/engine/src/cmd/parameters_tests.rs +++ b/crates/engine/src/cmd/parameters_tests.rs @@ -1,4 +1,5 @@ use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::{EngineError, Session}; @@ -60,7 +61,9 @@ fn width_follows_an_expression() { run(&mut s, "parameters.change", json!({"name": "len", "expression": "5", "unit": "in"})); assert!(rel(volume(&mut s), 40.0 * 63.5 * 10.0) < 1e-9); let l = run(&mut s, "parameters.list", json!({})); - assert_eq!(row(&l, "len")["value"], 5.0, "{l}"); + // `value` is mm in every reply; the own-unit number is `display_value` (#10747). + assert_eq!(row(&l, "len")["value"], 127.0, "{l}"); + assert_eq!(row(&l, "len")["display_value"], 5.0, "{l}"); assert_eq!(row(&l, "len")["unit"], "in"); // A failing parameter fails the features using it, with its error. let e = err(&mut s, "parameters.change", json!({"name": "len", "expression": "5 deg"})); @@ -326,6 +329,43 @@ fn csv_and_json_round_trip() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn csv_round_trips_comments_with_line_breaks() { + for comment in ["line one\nline two", "\r\nfirst, \"quoted\"\r\n\r\nlast\r\n", "one\rtwo"] { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "L", "expression": "30", "comment": comment})); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "10"})); + let exported = run(&mut s, "parameters.export", json!({"format": "csv"})); + + let mut fresh = Session::default(); + let imported = run(&mut fresh, "parameters.import", json!({"text": exported["text"]})); + assert_eq!(imported["imported"], json!(["L", "W"])); + let list = run(&mut fresh, "parameters.list", json!({})); + assert_eq!(row(&list, "L")["comment"], comment); + assert_eq!(row(&list, "L")["value"], 30.0); + assert_eq!(row(&list, "W")["value"], 10.0); + } +} + +#[test] +fn csv_import_accepts_a_bom_before_the_header() { + let mut s = Session::default(); + let csv = "\u{feff}\"NAME\",expression\r\n\r\nA,5"; + let imported = run(&mut s, "parameters.import", json!({"text": csv})); + assert_eq!(imported["imported"], json!(["A"])); + assert_eq!(row(&run(&mut s, "parameters.list", json!({})), "A")["value"], 5.0); +} + +#[test] +fn csv_import_with_an_unclosed_quote_leaves_parameters_alone() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "L", "expression": "10"})); + let before = s.doc.to_json(); + let csv = "name,expression,comment\nL,30,updated\nW,5,\"unfinished\n"; + assert!(s.execute("parameters.import", &json!({"text": csv})).is_err()); + assert_eq!(s.doc.to_json(), before); +} + /// #8960: the text marker accepts ASCII case variants without changing numeric units. #[test] fn text_parameter_imports_accept_mixed_case_units() { @@ -352,7 +392,8 @@ fn text_parameter_imports_accept_mixed_case_units() { assert_eq!(label["comment"], "quoted label"); assert!(label["value"].is_null()); assert_eq!(row(&list, "width")["unit"], "in"); - assert_eq!(row(&list, "width")["value"], 1.0); + assert_eq!(row(&list, "width")["value"], 25.4); + assert_eq!(row(&list, "width")["display_value"], 1.0); assert_eq!(s.doc.param_values().0["width"].v, 25.4); } // Export still uses the canonical marker and round-trips the unquoted text. @@ -628,7 +669,7 @@ fn a_failed_auto_constrain_keeps_the_stored_sketch_consistent() { } /// The stored sketch's points, by id. -fn stored_points(s: &Session, feature: u64) -> Vec { +fn stored_points(s: &Session, feature: u64) -> Vec { s.doc.sketch(feature).unwrap().points.iter().map(|p| p.pos).collect() } @@ -659,7 +700,7 @@ fn an_unsolvable_value_edit_is_refused_and_changes_nothing() { fn value_edits_continue_from_the_last_solved_state() { // A → B → C, each a small edit solved in one jump; C is solved from B (the stored state), // and setting both values back reproduces A (the linkage is fully constrained). - let close = |a: &[solidcraft_geom::Vec2], b: &[solidcraft_geom::Vec2], tol: f64| a.iter().zip(b).all(|(p, q)| p.dist(*q) < tol); + let close = |a: &[solidcore_record::Vec2], b: &[solidcore_record::Vec2], tol: f64| a.iter().zip(b).all(|(p, q)| p.dist(*q) < tol); let (mut s, feature, params) = linkage_session(); run(&mut s, "sketch.finish", json!({})); let a = stored_points(&s, feature); @@ -896,8 +937,8 @@ fn a_parameter_added_without_a_unit_takes_the_design_unit() { let r = run(s, "parameters.add", p); (r["unit"].as_str().unwrap_or("?").to_string(), r["value"].as_f64().unwrap_or(f64::NAN), r["display_value"].as_f64().unwrap_or(f64::NAN)) }; - let close = |got: (String, f64, f64), unit: &str, mm: f64, shown: f64| { - assert!(got.0 == unit && rel(got.1, mm) < 1e-9 && rel(got.2, shown) < 1e-9, "{got:?}, expected {unit} {mm} mm ({shown})"); + let close = |got: (String, f64, f64), unit: &str, val: f64, shown: f64| { + assert!(got.0 == unit && rel(got.1, val) < 1e-9 && rel(got.2, shown) < 1e-9, "{got:?}, expected {unit} {val} ({shown})"); }; // A millimetre design is as it was. let mut s = Session::default(); @@ -914,8 +955,8 @@ fn a_parameter_added_without_a_unit_takes_the_design_unit() { // One that refers to another parameter: its bare number is an inch too. close(added(&mut s, json!({"name": "more", "expression": "v + 1"})), "in", 533.4, 21.0); close(added(&mut s, json!({"name": "half", "expression": "v / 2"})), "in", 254.0, 10.0); - // An angle stays in degrees, a unit-less count stays unit-less. - close(added(&mut s, json!({"name": "turn", "expression": "30 deg"})), "deg", 30f64.to_radians(), 30.0); + // An angle reports degrees like every other reply, a unit-less count stays unit-less. + close(added(&mut s, json!({"name": "turn", "expression": "30 deg"})), "deg", 30.0, 30.0); close(added(&mut s, json!({"name": "n", "expression": "4", "unit": ""})), "", 4.0, 4.0); close(added(&mut s, json!({"name": "twice", "expression": "n * 2"})), "", 8.0, 8.0); // parameters.change and parameters.import make a new parameter the same way. @@ -1108,3 +1149,101 @@ fn a_feature_on_a_failed_sketch_names_the_sketch() { assert_eq!(r["errors"], json!([]), "{r}"); assert!(rel(volume(&mut s), 40.0 * 20.0 * 5.0 + 500.0) < 1e-9); } + +/// A finished sketch with one line (0,0)-(30,0) whose length is dimensioned to parameter `L`. +fn line_dimensioned_by_a_parameter() -> (Session, u64) { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "L", "expression": "30"})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [30, 0]]})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "L"})); + run(&mut s, "sketch.finish", json!({})); + let feature = s.doc.find_feature("Sketch1").map(|f| f.id).unwrap_or_default(); + (s, feature) +} + +/// #9729: `sketch.dimension` refuses 0 ("that would shrink l1 to a point") but a value edit +/// let it through: the line collapsed to a point and every later value counted as a conflict, +/// so only Undo recovered — and after a save and reopen there is no Undo. A value edit now +/// runs the same shrink/fling checks `settle` runs, so the zero is refused where it happens. +#[test] +fn a_parameter_that_shrinks_a_dimensioned_line_to_a_point_is_refused() { + let (mut s, feature) = line_dimensioned_by_a_parameter(); + let e = err(&mut s, "parameters.change", json!({"name": "L", "expression": "0"})); + assert!(e.contains("shrink l1 to a point") && e.contains("the values were not changed"), "{e}"); + // The line is where it was and the sketch still solves. + assert!((far_x(&s, feature) - 30.0).abs() < 1e-6); + assert!(s.model.state().sketch(feature).unwrap().report.keeps_orientation()); + // Other values still work, in both directions: the sketch was never stored collapsed. + run(&mut s, "parameters.change", json!({"name": "L", "expression": "20"})); + assert!((far_x(&s, feature) - 20.0).abs() < 1e-6); + run(&mut s, "parameters.change", json!({"name": "L", "expression": "30"})); + assert!((far_x(&s, feature) - 30.0).abs() < 1e-6); +} + +/// The largest x among the stored sketch's points: the line's far end. +fn far_x(s: &Session, feature: u64) -> f64 { + stored_points(s, feature).iter().map(|p| p.x).fold(f64::MIN, f64::max) +} + +/// The same through a configuration row: activating a row whose value collapses the line is +/// refused, and the Default row can still be activated afterwards. +#[test] +fn a_configuration_row_that_shrinks_a_dimensioned_line_to_a_point_is_refused() { + let (mut s, feature) = line_dimensioned_by_a_parameter(); + run(&mut s, "config.configure", json!({"params": ["L"]})); + run(&mut s, "config.row", json!({"name": "Zero", "values": {"param:L": "0"}})); + let e = err(&mut s, "config.activate", json!({"row": "Zero"})); + assert!(e.contains("shrink l1 to a point"), "{e}"); + // The Default row still activates and the line is untouched. + run(&mut s, "config.activate", json!({"row": "Default"})); + assert!((far_x(&s, feature) - 30.0).abs() < 1e-6); +} + +/// #10747: `value` means millimetres (and degrees) in every reply — add, change and list — +/// with the parameter's own unit in `display_value`. Reported numbers carry no float noise; +/// stored values keep full precision. +#[test] +fn value_means_the_same_unit_in_every_reply() { + let mut s = Session::default(); + run(&mut s, "document.units", json!({"units": "in"})); + let a = run(&mut s, "parameters.add", json!({"name": "L", "expression": "2"})); + assert_eq!((a["value"].as_f64(), a["display_value"].as_f64()), (Some(50.8), Some(2.0)), "{a}"); + // The change reply is rounded too: 3 in is 76.2, not 76.19999999999999. + let c = run(&mut s, "parameters.change", json!({"name": "L", "expression": "3"})); + assert_eq!((c["value"].as_f64(), c["display_value"].as_f64()), (Some(76.2), Some(3.0)), "{c}"); + run(&mut s, "parameters.add", json!({"name": "d1", "expression": "L"})); + run(&mut s, "parameters.add", json!({"name": "d2", "expression": "1 in"})); + let l = run(&mut s, "parameters.list", json!({})); + // Every row's `value` is mm, whatever the parameter's own unit (#10747). + for (name, mm) in [("L", 76.2), ("d1", 76.2), ("d2", 25.4)] { + assert_eq!(row(&l, name)["value"], mm, "{name}: {l}"); + } + assert_eq!(row(&l, "L")["display_value"], 3.0, "{l}"); + assert_eq!(row(&l, "d2")["display_value"], 1.0, "{l}"); + // An angle reports degrees like every other reply, without the noise. + let a = run(&mut s, "parameters.add", json!({"name": "ang", "expression": "30 deg"})); + assert_eq!((a["value"].as_f64(), a["display_value"].as_f64()), (Some(30.0), Some(30.0)), "{a}"); + // Only what is reported is rounded: the stored value keeps full precision — the raw + // own-unit conversion still says 29.999999999999996. + let (vals, _) = s.doc.param_values(); + assert_eq!(s.doc.param_display_value(&vals, "ang"), Some(29.999999999999996), "the stored angle keeps its bits"); +} + +/// #10747: exports carry the numbers a person would read, not float noise. The `value` +/// column keeps the number in the parameter's own unit, as it always did. +#[test] +fn exports_round_reported_numbers() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "ang", "expression": "30 deg"})); + run(&mut s, "parameters.add", json!({"name": "w", "expression": "1.2 in"})); + run(&mut s, "parameters.add", json!({"name": "s", "expression": "0.1 + 0.2"})); + let csv = run(&mut s, "parameters.export", json!({"format": "csv"}))["text"].as_str().unwrap_or_default().to_string(); + assert!(csv.contains("ang,deg,30 deg,30,,false"), "{csv}"); + assert!(csv.contains("w,mm,1.2 in,30.48,,false"), "{csv}"); + assert!(csv.contains("s,mm,0.1 + 0.2,0.3,,false"), "{csv}"); + let json_text = run(&mut s, "parameters.export", json!({"format": "json"}))["text"].as_str().unwrap_or_default().to_string(); + let rows: Vec = serde_json::from_str(&json_text).unwrap_or_default(); + let vals: Vec = rows.iter().filter_map(|r| r["value"].as_f64()).collect(); + assert_eq!(vals, vec![30.0, 30.48, 0.3], "{json_text}"); +} diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index 95aae7da9..a2ac92cf5 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -1,32 +1,41 @@ -//! Standard parts: ISO metric fasteners, dowel pins and ball bearings, generated in code from -//! the dimensions in the public standards tables (no vendor geometry). Each part is inserted as +//! Standard parts: ISO metric and ASME/ANSI inch fasteners, dowel pins and ball bearings, +//! generated in code from the dimensions in the public standards tables (no vendor geometry). +//! Inch parts are tabled in inches and built in millimetres like the rest. Each part is inserted as //! its own component, built by ordinary features (so it stays parametric and editable), with a //! cosmetic thread where it has one; at a hole it gets a rigid joint that puts its axis on the -//! hole's and seats it on the face. +//! hole's and seats it on the face. Inserted at several holes it is still one component, placed +//! once per hole, each placement with its own joint. //! //! Part frame: the seating plane is z = 0 (the underside of a head, the bottom of a nut or //! washer, the top of a set screw or pin); the shank runs down −z. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::CommandSpec; use crate::params::{bad, num, str_, vec3}; use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("parts.library", "Standard Parts", library).icon("library") + CommandSpec::new("parts.library", "Standard Parts", library) + .icon("library") .noundo() - .params("family? → families (name, standard, sizes, lengths) and, with family, each size's dimensions (mm)"), - CommandSpec::new("parts.fastener", "Insert Fastener", insert).at("SOLID", "INSERT").icon("fastener").params( - "the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction?, name?", + .params("family? → families (name, standard, system: metric|inch, sizes, lengths) and, with family, each size's dimensions (mm)"), + CommandSpec::new("parts.fastener", "Insert Fastener", insert_atomic) + .at("SOLID", "INSERT") + .icon("fastener") + .params("the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction?, name?"), + CommandSpec::new("parts.insert", "Insert Part", insert_atomic).icon("fastener").params( + "family (socket_head_cap_screw | button_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing | \ + hex_cap_screw_inch | hex_nut_inch | washer_sae | washer_uss); size (\"M6\", \"608\" for bearings, \"1/2-13 UNC\" for inch screws and nuts, \ + \"1/2\" for inch washers); length? (mm, inch parts too; screws, bolts, set screws, pins; default a standard length near 2.5 d); \ + at?: [x,y,z] on a hole's rim or wall (the part seats on the hole's face with a rigid joint), or a list of them (one component, \ + placed and seated once per hole) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name? → component, occurrence, joint?, \ + and with at: occurrences, joints (one per hole, in pick order)", ), - CommandSpec::new("parts.insert", "Insert Part", insert).icon("fastener").params( - "family (socket_head_cap_screw | button_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing); size (\"M6\", or \"608\" for bearings); \ - length? (mm; screws, bolts, set screws, pins; default a standard length near 2.5 d); \ - at?: [x,y,z] on a hole's rim or wall (the part seats on the hole's face with a rigid joint) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name?", - ), - CommandSpec::new("parts.resize", "Change Part Size", resize_atomic).icon("scale") + CommandSpec::new("parts.resize", "Change Part Size", resize_atomic) + .icon("scale") .params("component: id|name of an inserted part; size?; length? — rebuilds it (joints keep it seated)"), ]; @@ -40,6 +49,10 @@ const FAMILIES: &[(&str, &str, &str)] = &[ ("set_screw", "Hex socket set screw, flat point", "ISO 4026"), ("dowel_pin", "Parallel pin (dowel)", "ISO 8734"), ("bearing", "Deep groove ball bearing (envelope)", "ISO 15 (6000/6200/600 series)"), + ("hex_cap_screw_inch", "Hex cap screw (inch)", "ASME B18.2.1"), + ("hex_nut_inch", "Hex nut (inch)", "ASME B18.2.2"), + ("washer_sae", "Plain washer, SAE (narrow)", "ANSI B18.22.1 Type A"), + ("washer_uss", "Plain washer, USS (wide)", "ANSI B18.22.1 Type A"), ]; /// ISO metric coarse: (size, d, pitch). @@ -187,6 +200,127 @@ const BEARINGS: [(&str, f64, f64, f64); 13] = [ const LENGTHS: [f64; 22] = [4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70.0, 80.0, 90.0, 100.0, 120.0]; +/// Millimetres per inch. +const INCH: f64 = 25.4; + +/// ASME B18.2.1 hex cap screw, in inches: (nominal size, width across flats F, head height H). +/// 9/16 is left out until the thread catalogue has its UNC and UNF threads. +const INCH_HEX_CAP: [(&str, f64, f64); 9] = [ + ("1/4", 0.4375, 0.156), + ("5/16", 0.5, 0.203), + ("3/8", 0.5625, 0.234), + ("7/16", 0.625, 0.281), + ("1/2", 0.75, 0.312), + ("5/8", 0.9375, 0.391), + ("3/4", 1.125, 0.469), + ("7/8", 1.3125, 0.547), + ("1", 1.5, 0.609), +]; + +/// ASME B18.2.2 hex nut, in inches: (nominal size, width across flats F, thickness H). +const INCH_HEX_NUT: [(&str, f64, f64); 9] = [ + ("1/4", 0.4375, 0.219), + ("5/16", 0.5, 0.266), + ("3/8", 0.5625, 0.328), + ("7/16", 0.6875, 0.375), + ("1/2", 0.75, 0.438), + ("5/8", 0.9375, 0.547), + ("3/4", 1.125, 0.641), + ("7/8", 1.3125, 0.75), + ("1", 1.5, 0.859), +]; + +/// ANSI B18.22.1 Type A plain washers, in inches: (nominal size, inside diameter, outside +/// diameter, thickness). SAE is the standard's narrow (N) series, USS its wide (W) one. +const WASHER_SAE: [(&str, f64, f64, f64); 9] = [ + ("1/4", 0.281, 0.625, 0.065), + ("5/16", 0.344, 0.688, 0.065), + ("3/8", 0.406, 0.812, 0.065), + ("7/16", 0.469, 0.922, 0.065), + ("1/2", 0.531, 1.062, 0.095), + ("5/8", 0.656, 1.312, 0.095), + ("3/4", 0.812, 1.469, 0.134), + ("7/8", 0.938, 1.75, 0.134), + ("1", 1.062, 2.0, 0.134), +]; +const WASHER_USS: [(&str, f64, f64, f64); 9] = [ + ("1/4", 0.312, 0.734, 0.065), + ("5/16", 0.375, 0.875, 0.083), + ("3/8", 0.438, 1.0, 0.083), + ("7/16", 0.5, 1.25, 0.083), + ("1/2", 0.562, 1.375, 0.109), + ("5/8", 0.688, 1.75, 0.134), + ("3/4", 0.812, 2.0, 0.148), + ("7/8", 0.938, 2.25, 0.165), + ("1", 1.062, 2.5, 0.165), +]; + +/// Standard lengths for inch cap screws (inches). +const INCH_LENGTHS: [f64; 19] = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 8.0]; + +fn inch_lengths() -> Vec { + INCH_LENGTHS.iter().map(|l| l * INCH).collect() +} + +/// The first standard length at or above 2.5 d. Both sides are inches turned into mm, so the +/// comparison allows for rounding: a 1/2 screw's 2.5 d is exactly 1-1/4. +fn default_inch_length(d: f64) -> f64 { + inch_lengths().into_iter().find(|l| *l >= 2.5 * d - 1e-9).unwrap_or(8.0 * INCH) +} + +fn is_inch(family: &str) -> bool { + matches!(family, "hex_cap_screw_inch" | "hex_nut_inch" | "washer_sae" | "washer_uss") +} + +/// A unified inch thread from the catalogue (`1/2-13 UNC`): its nominal size (`1/2`), and its +/// major diameter and pitch (mm). +fn unified(size: &str) -> Option<(String, f64, f64)> { + use solidcraft_doc::TappedThreadFamily::{Unc, Unf}; + let t = solidcraft_doc::parse_tapped_thread(size).filter(|t| matches!(t.family, Unc | Unf))?; + let nominal = t.designation.split('-').next()?.to_string(); + Some((nominal, t.major_diameter, t.pitch)) +} + +/// The catalogue's threads for a nominal inch size, UNC before UNF. +fn unified_sizes(nominal: &str) -> Vec { + use solidcraft_doc::TappedThreadFamily::{Unc, Unf}; + [Unc, Unf].into_iter().flat_map(solidcraft_doc::tapped_thread_sizes).filter(|t| t.designation.split('-').next() == Some(nominal)).collect() +} + +/// A length (mm) in fractional inches to the nearest 1/64 (`1-1/2`), or none off that grid. +fn inch_fraction(mm: f64) -> Option { + let n = mm / INCH * 64.0; + let r = n.round(); + if !r.is_finite() || r <= 0.0 || r > 1e6 || (n - r).abs() > 1e-6 { + return None; + } + let r = r as u64; + let (whole, mut num, mut den) = (r / 64, r % 64, 64); + while num > 0 && num % 2 == 0 { + num /= 2; + den /= 2; + } + Some(match (whole, num) { + (w, 0) => w.to_string(), + (0, n) => format!("{n}/{den}"), + (w, n) => format!("{w}-{n}/{den}"), + }) +} + +/// How a part's length (mm) is shown where its family has a unit of its own: `1-1/2 in` for an +/// inch family, none for a metric one (shown in the design's units). +pub fn part_length_label(family: &str, mm: f64) -> Option { + is_inch(family).then(|| inch_fraction(mm)).flatten().map(|f| format!("{f} in")) +} + +/// A part's size with its length, as names and part numbers write it: `M6x20`, `1/2-13 UNC x 2`. +fn size_with_length(family: &str, size: &str, len: f64) -> String { + match is_inch(family).then(|| inch_fraction(len)).flatten() { + Some(l) => format!("{size} x {l}"), + None => format!("{size}x{len}"), + } +} + fn metric(size: &str) -> Option<(f64, f64)> { METRIC.iter().find(|(s, _, _)| s.eq_ignore_ascii_case(size)).map(|(_, d, p)| (*d, *p)) } @@ -199,9 +333,11 @@ fn default_length(d: f64) -> f64 { #[derive(Clone, Debug, PartialEq)] enum Shape { /// A head (round, domed or hex), a shank down −z, an optional hex socket in the head's top. - Screw { d: f64, pitch: f64, len: f64, head: Head, socket: Option<(f64, f64)> }, + /// `pitch` is that of a metric cosmetic thread; inch parts have none, as `solid.thread` takes + /// only metric designations (#9571). + Screw { d: f64, pitch: Option, len: f64, head: Head, socket: Option<(f64, f64)> }, /// A hex prism with a through hole (nut), z 0…m. - Nut { d: f64, pitch: f64, s: f64, m: f64 }, + Nut { d: f64, pitch: Option, s: f64, m: f64 }, /// A ring (washer, bearing envelope), z 0…h. Ring { d_in: f64, d_out: f64, h: f64 }, /// A cylinder down −z with a socket in its top (set screw), or plain (pin). @@ -234,22 +370,43 @@ fn shape(family: &str, size: &str, length: Option) -> std::result::Result { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, dk, k, s, t) = SHCS.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4762"))?; - Shape::Screw { d, pitch, len: len(d), head: Head::Round { dk, k }, socket: Some((s, t)) } + Shape::Screw { d, pitch: Some(pitch), len: len(d), head: Head::Round { dk, k }, socket: Some((s, t)) } } "button_head_cap_screw" => { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, dk, k, s, t) = BHCS.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 7380-1"))?; - Shape::Screw { d, pitch, len: len(d), head: Head::Dome { dk, k, flat: BUTTON_FLAT * s }, socket: Some((s, t)) } + Shape::Screw { d, pitch: Some(pitch), len: len(d), head: Head::Dome { dk, k, flat: BUTTON_FLAT * s }, socket: Some((s, t)) } } "hex_bolt" => { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, s, k) = HEX_BOLT.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4014"))?; - Shape::Screw { d, pitch, len: len(d), head: Head::Hex { s, k }, socket: None } + Shape::Screw { d, pitch: Some(pitch), len: len(d), head: Head::Hex { s, k }, socket: None } } "hex_nut" => { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, s, m) = HEX_NUT.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4032"))?; - Shape::Nut { d, pitch, s, m } + Shape::Nut { d, pitch: Some(pitch), s, m } + } + "hex_cap_screw_inch" => { + let (nominal, d, _) = unified(size).ok_or_else(|| need("UNC/UNF"))?; + let (_, f, h) = INCH_HEX_CAP.iter().find(|r| r.0 == nominal).copied().ok_or_else(|| need("ASME B18.2.1"))?; + Shape::Screw { + d, + pitch: None, + len: length.unwrap_or_else(|| default_inch_length(d)), + head: Head::Hex { s: f * INCH, k: h * INCH }, + socket: None, + } + } + "hex_nut_inch" => { + let (nominal, d, _) = unified(size).ok_or_else(|| need("UNC/UNF"))?; + let (_, f, h) = INCH_HEX_NUT.iter().find(|r| r.0 == nominal).copied().ok_or_else(|| need("ASME B18.2.2"))?; + Shape::Nut { d, pitch: None, s: f * INCH, m: h * INCH } + } + "washer_sae" | "washer_uss" => { + let table = if family == "washer_sae" { &WASHER_SAE } else { &WASHER_USS }; + let (_, d1, d2, h) = table.iter().find(|r| r.0 == size.trim()).copied().ok_or_else(|| need("ANSI B18.22.1"))?; + Shape::Ring { d_in: d1 * INCH, d_out: d2 * INCH, h: h * INCH } } "washer" => { let (_, d1, d2, h) = WASHER.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 7089"))?; @@ -387,12 +544,16 @@ fn build(s: &mut Session, sh: &Shape) -> Result<()> { if let Some((af, t)) = socket { hex(s, af, k, k - t, "cut")?; } - thread(s, d, pitch, Vec3::new(d / 2.0, 0.0, -len / 2.0)); + if let Some(p) = pitch { + thread(s, d, p, Vec3::new(d / 2.0, 0.0, -len / 2.0)); + } } Shape::Nut { d, pitch, s: af, m } => { hex(s, af, 0.0, m, "new")?; cyl(s, d, -1.0, m + 1.0, "cut")?; - thread(s, d, pitch, Vec3::new(d / 2.0, 0.0, m / 2.0)); + if let Some(p) = pitch { + thread(s, d, p, Vec3::new(d / 2.0, 0.0, m / 2.0)); + } } Shape::Ring { d_in, d_out, h } => { revolve(s, &[(d_in / 2.0, 0.0), (d_out / 2.0, 0.0), (d_out / 2.0, h), (d_in / 2.0, h)], "new")?; @@ -421,11 +582,26 @@ fn library(_s: &mut Session, p: &Value) -> Result { "set_screw" => SET_SCREW.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "socket": r.1, "socket_depth": r.2})).collect(), "dowel_pin" => DOWEL.iter().map(|d| json!({"size": format!("{d}"), "d": d})).collect(), "bearing" => BEARINGS.iter().map(|r| json!({"size": r.0, "bore": r.1, "outer": r.2, "width": r.3})).collect(), + "hex_cap_screw_inch" => INCH_HEX_CAP + .iter() + .flat_map(|r| unified_sizes(r.0).into_iter().map(move |t| json!({"size": t.designation, "d": t.major_diameter, "pitch": t.pitch, "across_flats": r.1 * INCH, "head_height": r.2 * INCH}))) + .collect(), + "hex_nut_inch" => INCH_HEX_NUT + .iter() + .flat_map(|r| unified_sizes(r.0).into_iter().map(move |t| json!({"size": t.designation, "d": t.major_diameter, "pitch": t.pitch, "across_flats": r.1 * INCH, "height": r.2 * INCH}))) + .collect(), + "washer_sae" | "washer_uss" => { + let table = if id == "washer_sae" { &WASHER_SAE } else { &WASHER_USS }; + table.iter().map(|r| json!({"size": r.0, "inner": r.1 * INCH, "outer": r.2 * INCH, "thickness": r.3 * INCH})).collect() + } _ => Vec::new(), }; let (_, name, standard) = FAMILIES.iter().find(|f| f.0 == id).copied().unwrap_or(("", "", "")); - let lengths = - matches!(id, "socket_head_cap_screw" | "button_head_cap_screw" | "hex_bolt" | "set_screw" | "dowel_pin").then_some(LENGTHS.to_vec()); + let lengths = match id { + "socket_head_cap_screw" | "button_head_cap_screw" | "hex_bolt" | "set_screw" | "dowel_pin" => Some(LENGTHS.to_vec()), + "hex_cap_screw_inch" => Some(inch_lengths()), + _ => None, + }; if lengths.is_some() { for row in &mut sizes { let Some(size) = row.get("size").and_then(Value::as_str).map(str::to_string) else { continue }; @@ -435,7 +611,8 @@ fn library(_s: &mut Session, p: &Value) -> Result { } } } - json!({"family": id, "name": name, "standard": standard, "sizes": sizes, "lengths": lengths}) + let system = if is_inch(id) { "inch" } else { "metric" }; + json!({"family": id, "name": name, "standard": standard, "system": system, "sizes": sizes, "lengths": lengths}) }; match str_(p, "family") { Some(f) if FAMILIES.iter().any(|x| x.0 == f) => Ok(fam(f)), @@ -446,16 +623,17 @@ fn library(_s: &mut Session, p: &Value) -> Result { fn part_name(family: &str, size: &str, sh: &Shape) -> String { match sh { - Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{} {size}x{len}", label(family)), + Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{} {}", label(family), size_with_length(family, size, *len)), _ => format!("{} {size}", label(family)), } } -/// A standard part's part number and description: its standard and size (`ISO 4762 M6x20`), or -/// a bearing's designation, and the family's name with the size. +/// A standard part's part number and description: its standard and size (`ISO 4762 M6x20`, +/// `ASME B18.2.1 1/2-13 UNC x 2`, an inch washer with its series: `ANSI B18.22.1 1/2 N`), or a +/// bearing's designation, and the family's name with the size. fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) { let size = match sh { - Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{size}x{len}"), + Shape::Screw { len, .. } | Shape::Rod { len, .. } => size_with_length(family, size, *len), _ => size.to_string(), }; let standard = match family { @@ -466,10 +644,18 @@ fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) { "washer" => "ISO 7089", "set_screw" => "ISO 4026", "dowel_pin" => "ISO 8734", + "hex_cap_screw_inch" => "ASME B18.2.1", + "hex_nut_inch" => "ASME B18.2.2", + "washer_sae" | "washer_uss" => "ANSI B18.22.1", + _ => "", + }; + let series = match family { + "washer_sae" => " N", + "washer_uss" => " W", _ => "", }; let name = FAMILIES.iter().find(|f| f.0 == family).map_or("Part", |f| f.1); - let part_number = if standard.is_empty() { size.clone() } else { format!("{standard} {size}") }; + let part_number = if standard.is_empty() { size.clone() } else { format!("{standard} {size}{series}") }; (part_number, format!("{name} {size}")) } @@ -500,6 +686,10 @@ fn label(family: &str) -> &'static str { "washer" => "Washer", "set_screw" => "Set Screw", "dowel_pin" => "Dowel Pin", + "hex_cap_screw_inch" => "Hex Cap Screw", + "hex_nut_inch" => "Hex Nut", + "washer_sae" => "SAE Washer", + "washer_uss" => "USS Washer", _ => "Bearing", } } @@ -514,18 +704,40 @@ fn length_param(p: &Value, cmd: &str) -> Result> { } } +/// Building the part and seating it runs many feature and joint commands: as in +/// [`resize_atomic`], they run on a scratch session and the insert is one undo step. +fn insert_atomic(s: &mut Session, p: &Value) -> Result { + let mut computed = s.scratch(); + let result = insert(&mut computed, p)?; + computed.undo.clear(); + computed.active_component = s.active_component; + computed.active_occurrence_path = s.active_occurrence_path.clone(); + computed.active_sketch = s.active_sketch.filter(|id| computed.doc.feature(*id).is_some()); + s.accept_computed(computed); + Ok(result) +} + fn insert(s: &mut Session, p: &Value) -> Result { let cmd = "parts.insert (Insert Fastener)"; let family = str_(p, "family").ok_or_else(|| bad(cmd, "`family` is required (parts.library)"))?.to_string(); let size = str_(p, "size").ok_or_else(|| bad(cmd, "`size` is required"))?.to_string(); let sh = shape(&family, &size, length_param(p, cmd)?).map_err(|e| bad(cmd, e))?; // A pick on a hole's rim also touches its end face: step onto the wall just inside the rim. - let at = p.get("at").and_then(vec3).map(|a| hole_wall(s, a).unwrap_or(a)); - // The occurrence the hole belongs to, found before the part exists. - let host = match at { - Some(a) => Some(super::joints::occurrence_at(s, a).ok_or_else(|| bad(cmd, "no body at `at` (pick a hole's rim or wall)"))?), - None => None, - }; + // Each hole's occurrence is found before the part exists, so a pick off every body fails the + // insert before anything is made. + let mut holes = Vec::new(); + let mut seats: Vec<(u64, Vec3)> = Vec::new(); + for a in hole_picks(p, cmd)? { + let (a, seat) = hole_wall(s, a).unwrap_or((a, a)); + let host = super::joints::occurrence_at(s, a).ok_or_else(|| bad(cmd, "no body at `at` (pick a hole's rim or wall)"))?; + // A rim is drawn as more than one edge, and one click on it picks them all: the picks + // of one rim seat one part. + if seats.iter().any(|(h, q)| *h == host && (*q - seat).len() < 1e-3) { + continue; + } + seats.push((host, seat)); + holes.push((a, host)); + } let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| part_name(&family, &size, &sh)); let active = s.active_component; // Hardware is fitted to other parts: it starts free even as the design's first part (#2804). @@ -536,15 +748,29 @@ fn insert(s: &mut Session, p: &Value) -> Result { set_identity(s, comp, identity(&family, &size, &sh), None); run(s, "component.activate", json!({"component": active}))?; let mut out = json!({"component": comp, "occurrence": occ, "name": name}); - if let (Some(a), Some(h)) = (at, host) { - // Seat it: its axis on the hole's, its seating plane on the hole's face, the shank going - // into the hole (the joint mates the part's −z with the face's outward z). - let j = run( - s, - "joint.create", - json!({"type": "rigid", "a": {"occurrence": h, "circle": a}, "b": {"occurrence": occ, "point": [0, 0, 0], "z": [0, 0, -1]}, "name": format!("{name} seat")}), - )?; - out["joint"] = j["joint"].clone(); + if !holes.is_empty() { + // The first hole has the placement the component came with; each further hole places the + // same part again. All are made before any is seated, while each is still at the part's + // own origin, where the joint below takes the part's seating point to be. + let mut occurrences = vec![json!(occ)]; + for _ in 1..holes.len() { + occurrences.push(run(s, "occurrence.copy", json!({"component": comp}))?["occurrence"].clone()); + } + let mut joints = Vec::new(); + for (i, ((a, h), o)) in holes.into_iter().zip(&occurrences).enumerate() { + // Seat it: its axis on the hole's, its seating plane on the hole's face, the shank + // going into the hole (the joint mates the part's −z with the face's outward z). + let seat = if i == 0 { format!("{name} seat") } else { format!("{name} seat {}", i + 1) }; + let j = run( + s, + "joint.create", + json!({"type": "rigid", "a": {"occurrence": h, "circle": a}, "b": {"occurrence": o, "point": [0, 0, 0], "z": [0, 0, -1]}, "name": seat}), + )?; + joints.push(j["joint"].clone()); + } + out["joint"] = joints.first().cloned().unwrap_or(Value::Null); + out["occurrences"] = Value::Array(occurrences); + out["joints"] = Value::Array(joints); } else if let Some(pt) = p.get("point").and_then(vec3) { // Placed at a point, its +z along `direction`. let dir = p.get("direction").and_then(vec3).and_then(|d| d.normalized()).unwrap_or(Vec3::Z); @@ -556,6 +782,9 @@ fn insert(s: &mut Session, p: &Value) -> Result { ); let mut m = m; m[3] = [pt.x, pt.y, pt.z, 1.0]; + if !solidcraft_doc::is_placement(&m) { + return Err(bad(cmd, "`point` must be within 1e9 mm and `direction` finite")); + } if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) { o.transform = m; } @@ -563,9 +792,30 @@ fn insert(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// A point on the cylindrical wall of the hole at `a`, a little in from the picked rim. -fn hole_wall(s: &Session, a: Vec3) -> Option { - let st = s.model.state(); +/// The most holes one insert seats a part in. +const MAX_HOLES: usize = 1000; + +/// The hole picks in `at`: one point, or a list of them. +fn hole_picks(p: &Value, cmd: &str) -> Result> { + let finite = |a: Vec3| a.x.is_finite() && a.y.is_finite() && a.z.is_finite(); + let one = |v: &Value| vec3(v).filter(|a| finite(*a)).ok_or_else(|| bad(cmd, "`at` must be [x,y,z] or a list of them")); + match p.get("at") { + None | Some(Value::Null) => Ok(Vec::new()), + Some(Value::Array(list)) if list.first().is_some_and(Value::is_array) || list.is_empty() => { + if list.len() > MAX_HOLES { + return Err(bad(cmd, format!("`at` takes at most {MAX_HOLES} holes"))); + } + list.iter().map(one).collect() + } + Some(v) => Ok(vec![one(v)?]), + } +} + +/// A point on the cylindrical wall of the hole at `a`, a little in from the picked rim, and the +/// point on the hole's axis level with it (the same for every pick on one rim). +fn hole_wall(s: &Session, a: Vec3) -> Option<(Vec3, Vec3)> { + // Picks are in world coordinates, including rims on already placed standard parts. + let st = s.world_state().ok()?; let dirs = [Vec3::Z * -1.0, Vec3::Z, Vec3::X, Vec3::X * -1.0, Vec3::Y, Vec3::Y * -1.0]; for step in [0.2, 0.5, 1.0, 2.0] { for b in &st.bodies { @@ -576,7 +826,7 @@ fn hole_wall(s: &Session, a: Vec3) -> Option { let along = v.dot(c.axis); let on_wall = ((v - c.axis * along).len() - c.radius).abs() < 1e-3 && along > c.start && along < c.end; if on_wall { - return Some(q); + return Some((q, c.axis_point + c.axis * along)); } } } @@ -643,6 +893,7 @@ fn resize(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { use serde_json::{Value, json}; + use solidcraft_geom::prelude::*; use crate::Session; @@ -653,8 +904,8 @@ mod tests { } } - fn bbox(s: &Session, prefix: &str) -> (solidcraft_geom::Vec3, solidcraft_geom::Vec3) { - let st = s.world_state(); + fn bbox(s: &Session, prefix: &str) -> (solidcore_record::Vec3, solidcore_record::Vec3) { + let st = s.world_state().unwrap(); let comp = s.doc.components.iter().find(|c| c.name.starts_with(prefix)).map(|c| c.id).unwrap_or(0); let b = st .bodies @@ -717,6 +968,93 @@ mod tests { } } + /// #10316: ASME/ANSI inch hex cap screws, hex nuts and SAE/USS washers, tabled in inches and + /// built in millimetres, with sizes from the UNC/UNF thread catalogue and fractional-inch names. + #[test] + fn inch_parts_follow_the_asme_and_ansi_tables() { + const IN: f64 = 25.4; + let across_corners = |af: f64| af / (std::f64::consts::PI / 6.0).cos(); + let part_number = |s: &Session, out: &Value| { + let comp = out["component"].as_u64().unwrap_or(0); + s.doc.components.iter().find(|c| c.id == comp).and_then(|c| c.metadata.text(solidcraft_doc::metadata::PART_NUMBER)).map(str::to_string) + }; + // Every nominal size 1/4 to 1 but 9/16, coarse and fine. + let l = run(&mut Session::default(), "parts.library", json!({"family": "hex_cap_screw_inch"})); + let sizes: Vec<&str> = l["sizes"].as_array().map(|a| a.iter().filter_map(|x| x["size"].as_str()).collect()).unwrap_or_default(); + assert_eq!(sizes.len(), 18, "{sizes:?}"); + assert_eq!(sizes[..2], ["1/4-20 UNC", "1/4-28 UNF"]); + assert_eq!(sizes[16..], ["1-8 UNC", "1-12 UNF"]); + assert_eq!((l["standard"].as_str(), l["system"].as_str()), (Some("ASME B18.2.1"), Some("inch"))); + let all = run(&mut Session::default(), "parts.library", json!({})); + let inch: Vec<&str> = all["families"] + .as_array() + .map(|a| a.iter().filter(|f| f["system"] == "inch").filter_map(|f| f["family"].as_str()).collect()) + .unwrap_or_default(); + assert_eq!(inch, ["hex_cap_screw_inch", "hex_nut_inch", "washer_sae", "washer_uss"]); + let lengths: Vec = l["lengths"].as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); + assert_eq!((lengths.first().copied(), lengths.last().copied(), lengths.len()), (Some(0.5 * IN), Some(8.0 * IN), 19)); + // A 1/2-13 x 2 cap screw: 3/4 across flats, head 0.312 high, shank 2 in long, no thread mark. + let mut s = Session::default(); + let out = run(&mut s, "parts.insert", json!({"family": "hex_cap_screw_inch", "size": "1/2-13 UNC", "length": 2.0 * IN})); + assert_eq!(out["name"], "Hex Cap Screw 1/2-13 UNC x 2"); + assert_eq!(part_number(&s, &out).as_deref(), Some("ASME B18.2.1 1/2-13 UNC x 2")); + let (lo, hi) = bbox(&s, "Hex Cap Screw 1/2-13 UNC x 2"); + let w = (hi.x - lo.x).max(hi.y - lo.y); + assert!((w - across_corners(0.75 * IN)).abs() < 1e-6 && (lo.z + 2.0 * IN).abs() < 1e-6 && (hi.z - 0.312 * IN).abs() < 1e-6, "{lo:?} {hi:?}"); + assert!(s.model.state().threads.is_empty(), "solid.thread takes only metric designations (#9571)"); + // Its default length is the first standard length at or above 2.5 d: 1-1/4 for a 1/2. + let mut d = Session::default(); + assert_eq!( + run(&mut d, "parts.insert", json!({"family": "hex_cap_screw_inch", "size": "1/2-20 UNF"}))["name"], + "Hex Cap Screw 1/2-20 UNF x 1-1/4" + ); + // A 1/2-13 nut: 3/4 across flats, 0.438 thick, with the 1/2 in hole through it. + let mut n = Session::default(); + let out = run(&mut n, "parts.insert", json!({"family": "hex_nut_inch", "size": "1/2-13 UNC"})); + assert_eq!(part_number(&n, &out).as_deref(), Some("ASME B18.2.2 1/2-13 UNC")); + let (lo, hi) = bbox(&n, "Hex Nut 1/2-13 UNC"); + let (w, h) = ((hi.x - lo.x).max(hi.y - lo.y), hi.z - lo.z); + assert!((w - across_corners(0.75 * IN)).abs() < 1e-6 && (h - 0.438 * IN).abs() < 1e-6, "{w} {h}"); + // 1/2 washers: SAE 1.062 x 0.095, USS 1.375 x 0.109, the series in the part number. + for (family, label, od, t, number) in [ + ("washer_sae", "SAE Washer 1/2", 1.062, 0.095, "ANSI B18.22.1 1/2 N"), + ("washer_uss", "USS Washer 1/2", 1.375, 0.109, "ANSI B18.22.1 1/2 W"), + ] { + let mut w = Session::default(); + let out = run(&mut w, "parts.insert", json!({"family": family, "size": "1/2"})); + assert_eq!(part_number(&w, &out).as_deref(), Some(number)); + let (lo, hi) = bbox(&w, label); + assert!((hi.x - lo.x - od * IN).abs() < 1e-6 && (hi.z - lo.z - t * IN).abs() < 1e-6, "{family}: {lo:?} {hi:?}"); + } + // Resizing keeps it inch, and sizes the tables don't have are refused. + let r = run(&mut s, "parts.resize", json!({"component": "Hex Cap Screw 1/2-13 UNC x 2", "size": "3/8-16 UNC", "length": 1.0 * IN})); + assert_eq!(r["name"], "Hex Cap Screw 3/8-16 UNC x 1"); + for (family, size) in [ + ("hex_cap_screw_inch", "9/16-12 UNC"), + ("hex_cap_screw_inch", "#10-24 UNC"), + ("hex_cap_screw_inch", "M12"), + ("hex_cap_screw_inch", "1/2-20 UNC"), + ("hex_nut_inch", "1/2"), + ("washer_sae", "9/16"), + ("washer_uss", "1/2-13 UNC"), + ] { + assert!(Session::default().execute("parts.insert", &json!({"family": family, "size": size})).is_err(), "{family} {size}"); + } + } + + #[test] + fn inch_lengths_read_as_fractions() { + assert_eq!(super::part_length_label("hex_cap_screw_inch", 1.5 * 25.4).as_deref(), Some("1-1/2 in")); + assert_eq!(super::part_length_label("hex_cap_screw_inch", 0.75 * 25.4).as_deref(), Some("3/4 in")); + assert_eq!(super::part_length_label("hex_cap_screw_inch", 8.0 * 25.4).as_deref(), Some("8 in")); + // Off the 1/64 grid, or a metric family: shown as millimetres in the design's units. + assert_eq!(super::part_length_label("hex_cap_screw_inch", 20.0), None); + assert_eq!(super::part_length_label("socket_head_cap_screw", 25.4), None); + for bad in [f64::NAN, f64::INFINITY, -25.4, 0.0, 1e300] { + assert_eq!(super::part_length_label("hex_cap_screw_inch", bad), None, "{bad}"); + } + } + /// #7692: a button head cap screw (ISO 7380-1) takes the same parameters as a socket head /// cap screw, with a domed crown in place of the cylindrical head. #[test] @@ -737,7 +1075,7 @@ mod tests { // The profile: full width at the rim and up the flank (0.15 k = 0.50 high), drawing in // over the crown (r = 4.62 halfway up the head), and a flat top of 0.7 s = 2.8, which // leaves a ring of material around the socket's corners at r = 2.31. - let st = s.world_state(); + let st = s.world_state().unwrap(); let widest = |above: f64| { st.bodies.iter().flat_map(|b| b.mesh().positions.clone()).filter(|p| p.z > above).map(|p| p.x.hypot(p.y)).fold(0.0, f64::max) }; @@ -800,6 +1138,90 @@ mod tests { assert!(s.model.state().threads.iter().any(|t| t.designation == "M8" && (t.pitch - 1.25).abs() < 1e-9)); } + #[test] + fn a_screw_seats_on_a_translated_washer() { + for z in [11.6, 11.2] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":60,"width":60,"height":10,"body_name":"Plate"})); + run(&mut s, "solid.hole", json!({"position":[19.6,33.948,10],"diameter":8.4})); + let washer = run(&mut s, "parts.insert", json!({"family":"washer","size":"M8","at":[23.8,33.948,10]})); + let before = s.doc.clone(); + let undo = s.undo.len(); + // Both the top bore rim and the wall are world picks on the seated washer (#9648). + let screw = run(&mut s, "parts.fastener", json!({"family":"socket_head_cap_screw","size":"M8","length":20,"at":[23.8,33.948,z]})); + let joint = s.doc.assembly.joints.iter().find(|j| Some(j.id) == screw["joint"].as_u64()).unwrap(); + assert_eq!(Some(joint.a.occurrence), washer["occurrence"].as_u64()); + let (lo, hi) = bbox(&s, "SHCS M8x20"); + assert!((lo.z + 8.4).abs() < 1e-6 && (hi.z - 19.6).abs() < 1e-6, "{lo:?} {hi:?}"); + assert!(((lo.x + hi.x) / 2.0 - 19.6).abs() < 1e-6 && ((lo.y + hi.y) / 2.0 - 33.948).abs() < 1e-6, "{lo:?} {hi:?}"); + assert_eq!(s.undo.len(), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before); + } + } + + #[test] + fn a_screw_seats_on_a_rotated_washer() { + let mut s = Session::default(); + let washer = run(&mut s, "parts.insert", json!({"family":"washer","size":"M8","point":[40,50,60],"direction":[1,0,0]})); + run(&mut s, "occurrence.ground", json!({"occurrence":washer["occurrence"],"grounded":true})); + let screw = run(&mut s, "parts.insert", json!({"family":"socket_head_cap_screw","size":"M8","length":20,"at":[41.6,54.2,60]})); + let joint = s.doc.assembly.joints.iter().find(|j| Some(j.id) == screw["joint"].as_u64()).unwrap(); + assert_eq!(Some(joint.a.occurrence), washer["occurrence"].as_u64()); + // The seating face is X = 41.6: the 20 mm shank runs along -X and the 8 mm head along +X. + let (lo, hi) = bbox(&s, "SHCS M8x20"); + assert!(lo.dist(solidcore_record::Vec3::new(21.6, 43.5, 53.5)) < 1e-6, "{lo:?}"); + assert!(hi.dist(solidcore_record::Vec3::new(49.6, 56.5, 66.5)) < 1e-6, "{hi:?}"); + } + + /// Several holes in one insert: one component placed and seated once per hole, in one undo + /// step (#9341); two picks of one rim are one hole; a pick off every body fails the whole + /// insert. + #[test] + fn one_insert_seats_a_screw_in_each_hole() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"})); + let centres = [(8.0, 8.0), (32.0, 8.0), (32.0, 22.0), (8.0, 22.0)]; + for (x, y) in centres { + run(&mut s, "solid.hole", json!({"position": [x, y, 10], "diameter": 3.4})); + } + let (comps, occs, undo) = (s.doc.components.len(), s.doc.occurrences.len(), s.undo.len()); + // A hole off the plate fails the insert, and nothing is made. + let off = json!({"family": "socket_head_cap_screw", "size": "M3", "length": 8, "at": [[9.7, 8, 10], [100, 100, 100]]}); + assert!(s.execute("parts.insert", &off).is_err()); + assert_eq!((s.doc.components.len(), s.doc.occurrences.len()), (comps, occs)); + // Each rim picked at the top face. + // The first hole is picked twice, on both halves of its rim, as one click on a rim picks + // every edge of it: it still gets one screw. + let mut at: Vec<_> = centres.iter().map(|(x, y)| json!([x + 1.7, y, 10])).collect(); + at.insert(1, json!([centres[0].0 - 1.7, centres[0].1, 10])); + let r = run(&mut s, "parts.fastener", json!({"family": "socket_head_cap_screw", "size": "M3", "length": 8, "at": at})); + assert_eq!(s.doc.components.len(), comps + 1, "one part: {r}"); + let comp = r["component"].as_u64().unwrap_or(0); + let placed: Vec = r["occurrences"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + assert_eq!(placed.len(), 4, "{r}"); + assert!(placed.iter().all(|o| s.doc.occurrences.iter().any(|x| x.id == *o && x.component == comp)), "{r}"); + assert_eq!(r["joints"].as_array().map(|j| j.iter().filter(|j| j.is_number()).count()), Some(4), "{r}"); + assert_eq!(r["joint"], r["joints"][0]); + // Each placement sits in its own hole: the head flush on the top face, the shank down + // the hole's axis. + let st = s.world_state().unwrap(); + let mut seated: Vec<(f64, f64)> = Vec::new(); + for b in st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp) { + let (lo, hi) = (b.mesh().bounds().min, b.mesh().bounds().max); + assert!((hi.z - 13.0).abs() < 1e-6 && (lo.z - 2.0).abs() < 1e-6, "{lo:?} {hi:?}"); + seated.push(((lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0)); + } + assert_eq!(seated.len(), 4, "{seated:?}"); + for (x, y) in centres { + assert!(seated.iter().any(|c| (c.0 - x).abs() < 1e-6 && (c.1 - y).abs() < 1e-6), "no screw at ({x}, {y}): {seated:?}"); + } + // One undo takes them all away. + assert_eq!(s.undo.len(), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!((s.doc.components.len(), s.doc.occurrences.len()), (comps, occs)); + } + #[test] fn every_sketch_of_a_standard_part_is_fully_defined() { for (family, size, resized) in [ @@ -811,6 +1233,10 @@ mod tests { ("set_screw", "M6", "M8"), ("dowel_pin", "6", "8"), ("bearing", "608", "6200"), + ("hex_cap_screw_inch", "1/2-13 UNC", "5/8-11 UNC"), + ("hex_nut_inch", "1/2-13 UNC", "5/8-18 UNF"), + ("washer_sae", "1/2", "5/8"), + ("washer_uss", "1/2", "5/8"), ] { let mut s = Session::default(); let part = run(&mut s, "parts.insert", json!({"family": family, "size": size})); @@ -850,8 +1276,8 @@ mod tests { assert!(s.model.state().threads.iter().any(|t| t.designation == "M8" && (t.pitch - 1.25).abs() < 1e-9), "{family} {units}"); } if family == "dowel_pin" { - assert!(b.0.dist(solidcraft_geom::Vec3::new(10., 46., 56.)) < 1e-6, "{b:?}"); - assert!(b.1.dist(solidcraft_geom::Vec3::new(40., 54., 64.)) < 1e-6, "{b:?}"); + assert!(b.0.dist(solidcore_record::Vec3::new(10., 46., 56.)) < 1e-6, "{b:?}"); + assert!(b.1.dist(solidcore_record::Vec3::new(40., 54., 64.)) < 1e-6, "{b:?}"); } bounds.push(b); } diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs index 2ea9aa128..5e2609c02 100644 --- a/crates/engine/src/cmd/patterns_tests.rs +++ b/crates/engine/src/cmd/patterns_tests.rs @@ -93,16 +93,19 @@ fn rectangular_cut_pattern_counts_only_target_contacts_and_keeps_landing_copies( run(&mut s, "solid.cylinder", json!({"radius":2,"height":20,"base":[10,15,-5],"operation":"cut","targets":["Plate"],"name":"Cut"})); let reply = run(&mut s, "solid.pattern.rectangular", json!({"features":["Cut"],"dir1":[1,0,0],"count1":4,"spacing1":20})); assert_eq!(reply["warning"], "2 of 3 cut copies remove no material"); - let state = s.world_state(); + let state = s.world_state().unwrap(); let plate = &state.body("Plate").unwrap().body; - assert!(!plate.contains(solidcraft_geom::Vec3::new(30., 15., 5.))); - assert!(state.body("Neighbor").unwrap().body.contains(solidcraft_geom::Vec3::new(50., 15., 5.))); + assert_eq!(plate.classify_point(solidcore_record::Vec3::new(30., 15., 5.)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!( + state.body("Neighbor").unwrap().body.classify_point(solidcore_record::Vec3::new(50., 15., 5.)).unwrap(), + solidcraft_kernel::PointClass::Inside + ); assert!(rel(volume(&mut s), 24000.0 - 2.0 * PI * 4.0 * 10.0) < 1e-3); } #[test] fn feature_rectangular_center_flip_and_oblique_direction_keep_source_and_recompute() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; for flipped in [false, true] { let mut s = feature_pattern_plate(); let before = s.doc.to_json(); @@ -116,14 +119,14 @@ fn feature_rectangular_center_flip_and_oblique_direction_keep_source_and_recompu }), ); let sign = if flipped { -1.0 } else { 1.0 }; - let st = s.world_state(); + let st = s.world_state().unwrap(); let body = &st.bodies[0].body; // Analytic slots: the source, +1, -1, +2. The second direction is independent. for i in [0.0, 1.0, -1.0, 2.0] { for j in [0.0, 1.0] { let p = Vec3::new(60.0 + sign * (15.0 * i + 12.0 * j), 60.0 + sign * 16.0 * j, 2.5); - assert!(!body.contains(p), "hole at {p:?}"); - assert!(body.contains(p + Vec3::new(0.0, 2.0, 0.0))); + assert_eq!(body.classify_point(p).unwrap(), solidcraft_kernel::PointClass::Outside, "hole at {p:?}"); + assert_eq!(body.classify_point(p + Vec3::new(0.0, 2.0, 0.0)).unwrap(), solidcraft_kernel::PointClass::Inside); } } assert!(rel(volume(&mut s), 120.0 * 120.0 * 5.0 - 8.0 * PI * 5.0) < 1e-5); @@ -142,7 +145,7 @@ fn feature_rectangular_center_flip_and_oblique_direction_keep_source_and_recompu #[test] fn feature_circular_center_flip_uses_partial_arc_endpoints_and_full_circle_spacing() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; for total in [90.0_f64, 360.0] { for flipped in [false, true] { let mut s = feature_pattern_plate(); @@ -155,12 +158,15 @@ fn feature_circular_center_flip_uses_partial_arc_endpoints_and_full_circle_spaci }), ); let step = total / if total == 360.0 { 6.0 } else { 5.0 }; - let st = s.world_state(); + let st = s.world_state().unwrap(); for slot in [0.0, 1.0, -1.0, 2.0, -2.0, 3.0] { let a = (step * slot * if flipped { -1.0 } else { 1.0 }).to_radians(); let p = Vec3::new(40.0 + 20.0 * a.cos(), 60.0 + 20.0 * a.sin(), 2.5); - assert!(!st.bodies[0].body.contains(p), "hole at {p:?}"); - assert!(st.bodies[0].body.contains(p + Vec3::new(2.0 * a.cos(), 2.0 * a.sin(), 0.0))); + assert_eq!(st.bodies[0].body.classify_point(p).unwrap(), solidcraft_kernel::PointClass::Outside, "hole at {p:?}"); + assert_eq!( + st.bodies[0].body.classify_point(p + Vec3::new(2.0 * a.cos(), 2.0 * a.sin(), 0.0)).unwrap(), + solidcraft_kernel::PointClass::Inside + ); } assert!(rel(volume(&mut s), 120.0 * 120.0 * 5.0 - 6.0 * PI * 5.0) < 1e-5); let saved = s.doc.to_json(); @@ -240,27 +246,79 @@ fn circular_axis_origin_rejects_invalid_values_atomically() { run(&mut s, "parameters.add", json!({"name":"cy","expression":"25 mm"})); let before = s.doc.to_json(); let undo = s.undo.len(); - for origin in [ - json!(["cx", "cy", 0]), - json!(["50", 25, 0]), - json!([0, 0]), - json!([0, 0, 0, 0]), - json!(null), - json!(false), - json!({"x":0,"y":0}), - json!([1e9, 0, 0]), - json!([0, 1e100, 0]), - ] { - for (cmd, params) in [ - ("solid.pattern.circular", json!({"features":["Hole1"],"axis":{"origin":origin,"dir":[0,0,1]},"count":4})), - ("construct.plane.at_angle", json!({"base":"XY","axis":{"origin":origin,"dir":[1,0,0]},"angle":45})), - ] { - let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); - assert!(error.contains("axis.origin") && error.contains("expressions are not supported"), "{error}"); - assert_eq!(s.doc.to_json(), before); - assert_eq!(s.undo.len(), undo); - } + let invalid = [json!([0, 0]), json!([0, 0, 0, 0]), json!(null), json!(false), json!({"x":0,"y":0}), json!([1e9, 0, 0]), json!([0, 1e100, 0])]; + // A circular pattern's origin takes length expressions (#10852); an angled plane's doesn't. + for origin in invalid.iter().chain(&[json!(["nope", 0, 0]), json!(["2 deg", 0, 0])]) { + let params = json!({"features":["Hole1"],"axis":{"origin":origin,"dir":[0,0,1]},"count":4}); + let error = s.execute("solid.pattern.circular", ¶ms).unwrap_err().to_string(); + assert!(error.contains("axis.origin"), "{origin}: {error}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); } + for origin in invalid.iter().chain(&[json!(["cx", "cy", 0]), json!(["50", 25, 0])]) { + let params = json!({"base":"XY","axis":{"origin":origin,"dir":[1,0,0]},"angle":45}); + let error = s.execute("construct.plane.at_angle", ¶ms).unwrap_err().to_string(); + assert!(error.contains("axis.origin") && error.contains("expressions are not supported"), "{error}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + } +} + +/// #10852: a circular pattern about `{origin, dir}` with length expressions in the origin turns +/// about the point they give now, so the copies follow the parameters as the seed does. The +/// expressions are saved, renamed with their parameter, and can be set by `timeline.edit`. +#[test] +fn circular_axis_origin_expressions_follow_their_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name":"cx","expression":"50 mm"})); + run(&mut s, "parameters.add", json!({"name":"cy","expression":"40 mm"})); + // A 2 mm cube 20 mm from (cx, cy), turned about the vertical line there. + run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":["cx + 20 mm","cy",0],"body_name":"Cube"})); + run(&mut s, "solid.pattern.circular", json!({"bodies":["Cube"],"axis":{"origin":["cx","cy",0],"dir":[0,0,1]},"count":4})); + // The x and y extent of the four cubes: 22 mm either side of the axis while it is 20 mm away. + let span = |s: &Session| { + let st = s.model.state(); + assert_eq!(st.bodies.len(), 4); + let mut out = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY]; + for b in st.bodies.iter().filter_map(|mb| solidcraft_kernel::measure(&mb.body).ok()).map(|m| m.bbox) { + out = [out[0].min(b.min.x), out[1].max(b.max.x), out[2].min(b.min.y), out[3].max(b.max.y)]; + } + out + }; + let about_at = |s: &Session, x: f64, y: f64, half: f64| { + for (got, want) in span(s).into_iter().zip([x - half, x + half, y - half, y + half]) { + assert!((got - want).abs() < 1e-6, "{:?} is not {half} mm either side of ({x}, {y})", span(s)); + } + }; + let about = |s: &Session, x: f64, y: f64| about_at(s, x, y, 22.0); + // The origin as the pattern saves it. + let saved_origin = |s: &Session| match s.doc.features.last().map(|f| &f.kind) { + Some(solidcraft_doc::FeatureKind::Pattern { pattern, .. }) => serde_json::to_value(pattern).unwrap_or_default()["origin"].clone(), + other => panic!("not a pattern: {other:?}"), + }; + about(&s, 50.0, 40.0); + assert_eq!(saved_origin(&s), json!(["cx", "cy", 0.0]), "the expressions are saved"); + run(&mut s, "parameters.change", json!({"name":"cx","expression":"60 mm"})); + about(&s, 60.0, 40.0); + // Renaming a parameter renames it in the origin, and the pattern still follows it. + run(&mut s, "parameters.rename", json!({"name":"cy","new_name":"py"})); + run(&mut s, "parameters.change", json!({"name":"py","expression":"45 mm"})); + about(&s, 60.0, 45.0); + assert_eq!(saved_origin(&s), json!(["cx", "py", 0.0])); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap_or_else(|e| panic!("{e}"))); + about(&reopened, 60.0, 45.0); + // timeline.edit sets the origin as expressions too: 10 mm back, so the cube is 30 mm away. + let pattern = s.doc.features.last().map(|f| f.id).unwrap_or_default(); + run(&mut s, "timeline.edit", json!({"feature":pattern,"set":{"pattern.origin":["cx - 10 mm","py","0 mm"]}})); + about_at(&s, 50.0, 45.0, 32.0); + run(&mut s, "edit.undo", json!({})); + about(&s, 60.0, 45.0); + // Plain numbers are saved as numbers, as before. + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":[70,40,0],"body_name":"Cube"})); + run(&mut s, "solid.pattern.circular", json!({"bodies":["Cube"],"axis":{"origin":[50,40,0],"dir":[0,0,1]},"count":4})); + about(&s, 50.0, 40.0); + assert_eq!(saved_origin(&s), json!([50.0, 40.0, 0.0])); } #[test] @@ -665,7 +723,6 @@ fn pattern_of_touching_cuts_needs_no_fallback() { let (mut s, id) = sawtooth_bar(40, true); let result = s.model.result(id.unwrap()).unwrap(); assert!(result.error.is_none() && result.warning.is_none(), "{result:?}"); - assert!(result.boolean_diagnostics.events.is_empty(), "{:?}", result.boolean_diagnostics); let m = run(&mut s, "inspect.measure", json!({})); let (mut one, _) = sawtooth_bar(40, false); let single = run(&mut one, "inspect.measure", json!({})); @@ -703,7 +760,6 @@ fn pattern_of_cuts_beside_a_round_needs_no_retries() { let id = created["feature"].as_u64().unwrap(); let result = s.model.result(id).unwrap(); assert!(result.error.is_none() && result.warning.is_none(), "{result:?}"); - assert!(result.boolean_diagnostics.events.is_empty(), "{:?}", result.boolean_diagnostics); } // The bar, less the rounds' corners and 40 teeth (a 4 x 2 triangle below the top, 16 wide). let expected = 16000.0 - 400.0 * (1.0 - PI / 4.0) - 40.0 * 4.0 * 16.0; @@ -740,7 +796,9 @@ fn copies_of_a_primitive_cut_only_its_targets() { } /// #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. +/// that body, as before #2755, instead of looking for the target the join used up. The spoke +/// starts 1 mm inside the hub, so it shares volume with both (one tangent to the hub would only +/// touch it along a line, and the join would keep the hub a body of its own). #[test] fn copies_of_a_join_that_merged_its_targets_join_the_merged_body() { for (copy, n) in [ @@ -752,7 +810,7 @@ fn copies_of_a_join_that_merged_its_targets_join_the_merged_body() { 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"}); + let spoke = json!({"length": 53, "width": 3, "height": 2.5, "corner": [11, 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()); @@ -770,7 +828,7 @@ fn copies_of_a_join_that_merged_its_targets_join_the_merged_body() { /// middle; the rib's triangle (8, 5)-(8, 25)-(30, 5) in the XZ plane, 4 thick, is 880 mm³. #[test] fn patterns_and_mirrors_of_a_rib() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let rib = 0.5 * 22.0 * 20.0 * 4.0; let ribbed = || { let mut s = Session::default(); @@ -789,15 +847,15 @@ fn patterns_and_mirrors_of_a_rib() { run(&mut s, "solid.pattern.circular", json!({"features": ["Rib"], "axis": {"origin": [0, 0, -100], "dir": [0, 0, 1]}, "count": 4, "angle": 360})); let ribs = [Vec3::new(12.0, 0.0, 8.0), Vec3::new(0.0, 12.0, 8.0), Vec3::new(-12.0, 0.0, 8.0), Vec3::new(0.0, -12.0, 8.0)]; let check = |s: &Session, inside: &[Vec3]| { - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results.iter().map(|r| &r.error).collect::>()); assert_eq!(st.bodies.len(), 1); let body = &st.bodies[0].body; for p in inside { - assert!(body.contains(*p), "a rib at {p:?}"); + assert_eq!(body.classify_point(*p).unwrap(), solidcraft_kernel::PointClass::Inside, "a rib at {p:?}"); // Beside it, across its thickness: no material (clear of the boss too). let side = if p.y == 0.0 { Vec3::new(0.0, 3.0, 0.0) } else { Vec3::new(3.0, 0.0, 0.0) }; - assert!(!body.contains(*p + side), "nothing beside the rib at {p:?}"); + assert_eq!(body.classify_point(*p + side).unwrap(), solidcraft_kernel::PointClass::Outside, "nothing beside the rib at {p:?}"); } }; check(&s, &ribs); @@ -814,7 +872,7 @@ fn patterns_and_mirrors_of_a_rib() { /// box with a hole `H` at (−15, −10) and `Pat`, two more holes along x at 10 mm steps. #[test] fn patterns_and_mirrors_of_patterns_and_mirrors() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let hole = PI * 1.5 * 1.5 * 20.0; let design = || { let mut s = Session::default(); @@ -886,15 +944,19 @@ fn patterns_and_mirrors_of_patterns_and_mirrors() { for r in &s.model.results { assert!(r.error.is_none(), "{what}: {}: {:?}", r.name, r.error); } - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 1, "{what}"); let body = &st.bodies[0].body; for [x, y] in &holes { - assert!(!body.contains(Vec3::new(*x, *y, 10.0)), "{what}: a hole at ({x}, {y})"); - assert!(body.contains(Vec3::new(*x, *y + 2.5, 10.0)), "{what}: material beside ({x}, {y})"); + assert_eq!(body.classify_point(Vec3::new(*x, *y, 10.0)).unwrap(), solidcraft_kernel::PointClass::Outside, "{what}: a hole at ({x}, {y})"); + assert_eq!( + body.classify_point(Vec3::new(*x, *y + 2.5, 10.0)).unwrap(), + solidcraft_kernel::PointClass::Inside, + "{what}: material beside ({x}, {y})" + ); } for [x, y] in &material { - assert!(body.contains(Vec3::new(*x, *y, 10.0)), "{what}: no hole at ({x}, {y})"); + assert_eq!(body.classify_point(Vec3::new(*x, *y, 10.0)).unwrap(), solidcraft_kernel::PointClass::Inside, "{what}: no hole at ({x}, {y})"); } // The listed holes the steps added (in the last two cases `Mir` made the first of them). let added = holes.len(); @@ -949,8 +1011,13 @@ fn circular_pattern_of_a_hole_and_its_chamfers_copies_all_of_them() { assert!(rel(v0, v1) < 1e-9); run(&mut s, "solid.pattern.circular", json!({"features": ["Bore", "TopChamfer", "BottomChamfer"], "axis": "Z", "count": 6, "angle": 360})); let v = volume(&mut s); - println!("{v1} -> {v}"); - assert!(v < v1 - 5.0 * 0.9 * (std::f64::consts::PI * 9.0 * 10.0), "pattern had no effect: {v1} -> {v}"); + // One chamfered hole takes its bore, π·3²·10, and two rings of the chamfer's triangle, + // 0.5 × 0.5 / 2, about the bore's axis at its centroid's radius 3 + 0.5/3 (Pappus). The + // copies, 20 apart on the radius 20, do not meet: the pattern takes five more. + let pi = std::f64::consts::PI; + let hole = pi * 9.0 * 10.0 + 2.0 * 2.0 * pi * (3.0 + 0.5 / 3.0) * 0.125; + assert!((v1 - (pi * 900.0 * 10.0 - hole)).abs() < 4e-7 * v1, "{v1}"); + assert!((v - (v1 - 5.0 * hole)).abs() < 4e-7 * v1, "{v1} -> {v}, expected {}", v1 - 5.0 * hole); } /// The features are copied in timeline order, not in the order they were picked in: a chamfer @@ -1103,3 +1170,51 @@ fn editing_a_rolled_back_pattern_says_it_is_not_built() { assert_eq!(reply["rolled_back"], json!(true), "{reply}"); assert_eq!(reply["warning"], "1 of 1 cut copies remove no material", "{reply}"); } + +/// A 100 x 60 x 30 box shelled 5 mm (floor included) with a 20 x 11 boss joined to its +Y wall: +/// 67,500 mm³ hollow, 73,500 mm³ with the boss, which adds 6,000 mm³ (#6452). +fn hollow_box_with_join_boss() -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-50, -30], "p1": [50, 30]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Base", "distance": 30, "operation": "new", "name": "Block", "body_name": "Box"})); + run(&mut s, "solid.shell", json!({"faces": [[0, 0, 30]], "thickness": 5, "name": "Shell"})); + assert!(rel(volume(&mut s), 67500.0) < 1e-6, "hollow box"); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Boss"})); + run(&mut s, "sketch.line", json!({"closed": true, "points": [[20, 29], [40, 29], [40, 40], [20, 40]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Boss", "distance": 30, "operation": "join", "targets": ["Box"], "name": "Join Boss"})); + assert!(rel(volume(&mut s), 73500.0) < 1e-6, "joined boss"); + s +} + +/// The copy of a join is built where the source stands, and the source's own material used to +/// read as the target already filling the copy's bottom band: the mirrored boss lost its +/// 20 x 10 x 5 mm floor-level slice with no warning (#6452). +#[test] +fn mirror_of_a_join_on_a_hollow_part_copies_the_whole_boss() { + let mut s = hollow_box_with_join_boss(); + run(&mut s, "solid.mirror", json!({"features": ["Join Boss"], "plane": "XZ", "name": "Mirror Boss"})); + assert!(rel(volume(&mut s), 79500.0) < 1e-6, "mirrored copy lost material"); +} + +#[test] +fn mirror_of_a_join_on_a_hollow_part_copies_the_whole_boss_across_a_custom_plane() { + let mut s = hollow_box_with_join_boss(); + run(&mut s, "solid.mirror", json!({"features": ["Join Boss"], "plane": {"origin": [0, 0, 0], "normal": [0, 1, 0]}, "name": "Mirror Boss"})); + assert!(rel(volume(&mut s), 79500.0) < 1e-6, "mirrored copy lost material"); +} + +/// A pure translation loses the same slice: the copy must be congruent to the original, +/// whatever filled the space where its tool was rebuilt (#6452). +#[test] +fn rectangular_pattern_of_a_join_on_a_hollow_part_copies_the_whole_boss() { + let mut s = hollow_box_with_join_boss(); + run( + &mut s, + "solid.pattern.rectangular", + json!({"features": ["Join Boss"], "dir1": [0, -1, 0], "count1": 2, "spacing1": 69, "name": "Pattern Boss"}), + ); + assert!(rel(volume(&mut s), 79500.0) < 1e-6, "patterned copy lost material"); +} diff --git a/crates/engine/src/cmd/pbr_appearance_tests.rs b/crates/engine/src/cmd/pbr_appearance_tests.rs index 1d16a05ed..4653a5f67 100644 --- a/crates/engine/src/cmd/pbr_appearance_tests.rs +++ b/crates/engine/src/cmd/pbr_appearance_tests.rs @@ -945,3 +945,38 @@ fn appearance_gestures_favorite_is_a_validated_transient_request() { assert!(Arc::ptr_eq(&before, &s.doc)); assert_eq!((s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()), state); } + +/// A placed copy's name (`KB (K:2)`, the name inspect.measure lists) and a placement's (`K:2`) +/// mean the body and component they show in appearance.chain, appearance.list and +/// appearance.replace's scope, as appearance.assign already takes them (#9740). +#[test] +fn appearance_reads_and_scopes_take_a_placed_copys_name() { + let mut s = Session::default(); + s.execute("component.create", &json!({"name":"K"})).unwrap(); + s.execute("solid.box", &json!({"body_name":"KB","length":10,"width":10,"height":10})).unwrap(); + s.execute("occurrence.copy", &json!({"component":"K","translate":[30,0,0]})).unwrap(); + let world: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); + assert!(world.iter().any(|n| n == "KB (K:2)"), "{world:?}"); + s.execute("appearance.assign", &json!({"bodies":["KB"],"appearance":"ABS - Red"})).unwrap(); + s.execute("appearance.assign", &json!({"components":["K"],"appearance":"ABS - Blue"})).unwrap(); + + assert_eq!(chain_read(&mut s, json!({"body":"KB (K:2)"})), chain_read(&mut s, json!({"body":"KB"}))); + assert_eq!(chain_read(&mut s, json!({"body":"KB (K:2)","face":0})), chain_read(&mut s, json!({"body":"KB","face":0}))); + assert_eq!(chain_read(&mut s, json!({"component":"K:2"})), chain_read(&mut s, json!({"component":"K"}))); + let listed = |s: &mut Session, body: &str| s.execute("appearance.list", &json!({"body":body})).unwrap()["body"].clone(); + let placed = listed(&mut s, "KB (K:2)"); + assert_eq!(placed["name"], "KB", "the reply names the body the copy shows: {placed}"); + assert_eq!(placed, listed(&mut s, "KB")); + + let scope = json!({"bodies":["KB (K:2)"],"components":["K:2"]}); + let r = s.execute("appearance.replace", &json!({"from":"ABS - Red","to":"ABS - Blue","scope":scope})).unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(s.doc.appearances.bodies["KB"], s.doc.appearances.components[&s.doc.find_component("K").unwrap()]); + + // A name that is neither the model's nor a placed copy's is still refused. + assert!(s.execute("appearance.chain", &json!({"target":{"body":"KB (K:9)"}})).is_err()); + assert!(s.execute("appearance.chain", &json!({"target":{"component":"K:9"}})).is_err()); + assert!(s.execute("appearance.list", &json!({"body":"KB (K:9)"})).is_err()); + assert!(s.execute("appearance.replace", &json!({"from":"ABS - Blue","to":"ABS - Red","scope":{"bodies":["KB (K:9)"]}})).is_err()); + assert!(s.execute("appearance.replace", &json!({"from":"ABS - Blue","to":"ABS - Red","scope":{"components":["K:9"]}})).is_err()); +} diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rs index caf3e3343..f2daa1667 100644 --- a/crates/engine/src/cmd/plastic.rs +++ b/crates/engine/src/cmd/plastic.rs @@ -1,12 +1,13 @@ //! Plastic (enclosure) features: Boss, Lip / Groove, Snap Fit and Rest, and plastic rules. use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::BodyName; use solidcraft_doc::FeatureKind; use solidcraft_doc::expr::Kind; use solidcraft_doc::plastic::PlasticRule; use solidcraft_doc::{Dir, FacePick, Position}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use super::CommandSpec; use super::features::{add_feature, check_expr}; @@ -272,7 +273,8 @@ fn snap_fit(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; + use solidcraft_geom::prelude::*; use std::f64::consts::PI; use serde_json::{Value, json}; @@ -348,9 +350,9 @@ mod tests { for groove in [false, true] { let mut s = Session::default(); let plane = if tilted { - solidcraft_geom::Plane::new(Vec3::new(7., -3., 5.), Vec3::new(1., -1., 0.), Vec3::new(1., 1., -2.)).unwrap() + solidcore_record::Plane::new(Vec3::new(7., -3., 5.), Vec3::new(1., -1., 0.), Vec3::new(1., 1., -2.)).unwrap() } else { - solidcraft_geom::Plane::XY + solidcore_record::Plane::XY }; if obround { run(&mut s, "sketch.create", json!({"plane": plane, "name": "Rim"})); @@ -402,7 +404,7 @@ mod tests { s.run_script(&crate::sample::script()).unwrap(); let lip = json!({"body": "Plate", "face": [51.89, 45.2, 8.0], "width": "1.5 mm", "height": "3.5 mm", "side": "inside", "type": "lip"}); let e = s.execute("plastic.lip", &lip).unwrap_err().to_string(); - assert!(e.contains("rim face") && e.contains("2 openings alike"), "{e}"); + assert!(e.contains("one clear opening") && e.contains("2 openings alike"), "{e}"); // The boss alone, no holes: its foot is not an opening either. let mut b = Session::default(); run(&mut b, "solid.box", json!({"length": 80, "width": 50, "height": 8, "body_name": "Plate"})); @@ -509,8 +511,7 @@ mod tests { let before = s.model.state_before(feature.id); let name = feature.face_names.first().unwrap(); let point = solidcraft_doc::naming::point_on_face(&before, name, Vec3::new(0., -28., 20.)) - .expect("the original wall identity survives merged pieces") - .0; + .expect("the original wall identity survives merged pieces"); assert!((point - Vec3::new(0., -33., 20.)).len() < 1e-8, "{point:?}"); assert!(s.model.results.iter().all(|result| result.error.is_none())); let check = |session: &Session| { diff --git a/crates/engine/src/cmd/point_cloud.rs b/crates/engine/src/cmd/point_cloud.rs index 80e0b8618..78bfb0283 100644 --- a/crates/engine/src/cmd/point_cloud.rs +++ b/crates/engine/src/cmd/point_cloud.rs @@ -3,7 +3,9 @@ use serde_json::{Value, json}; use solidcraft_doc::Mat; -use solidcraft_doc::point_cloud::{ColorBy, Colors, MAX_COORD, MAX_POINTS, POINT_SIZE, PointCloud, Points, UNITS, unit_scale}; +use solidcraft_doc::point_cloud::{ + ColorBy, Colors, Filter, Keep, MAX_COORD, MAX_FILTERS, MAX_NAMES, MAX_POINTS, POINT_SIZE, PointCloud, Points, UNITS, unit_scale, +}; use super::CommandSpec; use crate::params::{bad, bool_, str_}; @@ -13,16 +15,16 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("pointcloud.insert", "Insert Point Cloud", insert) .at("SOLID", "INSERT") .icon("import") - .params("path: .ply, .xyz or .pts file (its points join the design as a point cloud: drawn as points, never a body; a PLY's red, green and blue are its colours) → cloud, name, points, source_points, bounds, warnings; name?; units?: mm|cm|m|in|ft (the file's length unit, default mm); max_points?: most points kept (default 5000000, at most 20000000; a larger file is thinned evenly); center?: bool (move the cloud so the middle of its base sits at the origin); point_size?: pixels (0.5…16, default 2); color_by?: file|single|height (the file's colours, the default; one colour; or a ramp by height, blue low to red high); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); height_range?: [low, high] design Z in mm for the height ramp, or null to work it out from the points (all but the lowest and highest 2 %)"), + .params("path: .ply, .xyz or .pts file (its points join the design as a point cloud: drawn as points, never a body; a PLY's red, green and blue are its colours, its other vertex properties can colour and filter it) → cloud, name, points, source_points, bounds, warnings; name?; units?: mm|cm|m|in|ft (the file's length unit, default mm); max_points?: most points kept (default 5000000, at most 20000000; a larger file is thinned evenly); center?: bool (move the cloud so the middle of its base sits at the origin); point_size?: pixels (0.5…16, default 2); color_by?: file|single|height or a property's name (the file's colours, the default; one colour; a ramp by height, blue low to red high; or by any property of the file, a ramp over its values or a palette for whole numbers); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); color_range?: [low, high] the ramp runs between (design Z in mm by height), or null for the automatic range (by height all but the lowest and highest 2 % of the points; by a property the values it takes over what the filters keep); height_range?: the same as color_range; filters?: [{property, range: [low, high]} or {property, values: [whole numbers]} for a property with named values], or null (only what every filter keeps is shown)"), CommandSpec::new("pointcloud.edit", "Edit Point Cloud", edit) .icon("edit") - .params("cloud: id or name; name?; visible?; point_size?: pixels (0.5…16); color_by?: file|single|height (the file's colours, the default; one colour; or a ramp by height, blue low to red high); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); height_range?: [low, high] design Z in mm for the height ramp, or null to work it out from the points (all but the lowest and highest 2 %); units?: mm|cm|m|in|ft (the file's length unit: the points are scaled from the unit they came in as); matrix?: [12 or 16 numbers] (where the cloud sits: a rigid row-major 3x4 or 4x4 matrix, as occurrence.move takes it); tolerance? → cloud"), + .params("cloud: id or name; name?; visible?; point_size?: pixels (0.5…16); color_by?: file|single|height or a property's name (the file's colours, the default; one colour; a ramp by height, blue low to red high; or by any property of the file, a ramp over its values or a palette for whole numbers); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); color_range?: [low, high] the ramp runs between (design Z in mm by height), or null for the automatic range (by height all but the lowest and highest 2 % of the points; by a property the values it takes over what the filters keep); height_range?: the same as color_range; units?: mm|cm|m|in|ft (the file's length unit: the points are scaled from the unit they came in as); matrix?: [12 or 16 numbers] (where the cloud sits: a rigid row-major 3x4 or 4x4 matrix, as occurrence.move takes it); tolerance?; filters?: [{property, range: [low, high]} or {property, values: [whole numbers]} for a property with named values], or null (only what every filter keeps is shown) → cloud"), CommandSpec::new("pointcloud.delete", "Delete Point Cloud", delete).icon("delete").params("cloud: id or name → deleted"), CommandSpec::new("pointcloud.list", "Point Clouds", list) .icon("list") .noundo() .doc_only() - .params("→ clouds: [{cloud, name, file, points, source_points, units, visible, point_size, color_by, color, colored, height_range (the ramp's now, its own or worked out), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"), + .params("→ clouds: [{cloud, name, file, points, source_points, units, visible, point_size, color_by (file, single, height or a property's name), color, colored, properties: [{name, integer, span, names}], filters, color_range (the ramp's now, exact over what the filters keep), height_range (the ramp's own range or the automatic one by height), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"), ]; fn units_of(p: &Value, cmd: &str) -> Result> { @@ -64,18 +66,74 @@ fn color(p: &Value, cmd: &str) -> Result>> { } } -/// `color_by`: absent (`None`), or file, single or height. -fn color_by(p: &Value, cmd: &str) -> Result> { +/// `color_by`: absent (`None`), file, single or height, or the name of a property. +fn color_by(p: &Value, cmd: &str) -> Result)>> { match p.get("color_by") { None | Some(Value::Null) => Ok(None), - Some(v) => v.as_str().and_then(ColorBy::parse).map(Some).ok_or_else(|| bad(cmd, "`color_by` must be file, single or height")), + Some(Value::String(v)) => Ok(Some(match ColorBy::parse(v) { + Some(b) if b != ColorBy::Property => (b, None), + _ => (ColorBy::Property, Some(v.clone())), + })), + Some(_) => Err(bad(cmd, "`color_by` must be file, single, height or a property's name")), } } +/// `filters`: absent (`None`), null for none, or [{property, range: [low, high]} or +/// {property, values: [whole numbers]}]. +fn filters(p: &Value, cmd: &str) -> Result>> { + let refuse = || { + bad( + cmd, + format!( + "`filters` must be at most {MAX_FILTERS} {{property, range: [low, high]}} (lowest first) or {{property, values: [whole numbers]}}, or null" + ), + ) + }; + match p.get("filters") { + None => Ok(None), + Some(Value::Null) => Ok(Some(Vec::new())), + Some(Value::Array(a)) if a.len() <= MAX_FILTERS => a + .iter() + .map(|f| { + let property = f.get("property").and_then(Value::as_str).ok_or_else(refuse)?.to_string(); + if let Some(values) = f.get("values") { + let values = values.as_array().ok_or_else(refuse)?; + let whole = |v: &Value| v.as_i64().and_then(|n| i32::try_from(n).ok()); + let values = values.iter().map(whole).collect::>>().filter(|v| v.len() <= MAX_NAMES).ok_or_else(refuse)?; + return Ok(Filter { property, keep: Keep::Values { values } }); + } + match f.get("range").and_then(Value::as_array).map(|r| r.iter().map(Value::as_f64).collect::>>()) { + Some(Some(r)) if matches!(r.as_slice(), &[lo, hi] if lo.is_finite() && hi.is_finite() && lo <= hi) => { + Ok(Filter { property, keep: Keep::Range { range: [r[0], r[1]] } }) + } + _ => Err(refuse()), + } + }) + .collect::>>() + .map(Some), + Some(_) => Err(refuse()), + } +} + +/// A cloud colours and filters only by properties it has. +fn check_properties(c: &PointCloud, cmd: &str) -> Result<()> { + let names: Vec<&str> = c.property_names().collect(); + for n in c.color_property.iter().filter(|_| c.color_by == ColorBy::Property).chain(c.filters.iter().map(|f| &f.property)) { + if !names.contains(&n.as_str()) { + return Err(bad(cmd, format!("the point cloud has no property `{n}` (it has {})", names.join(", ")))); + } + } + // A set of values filters a label: a property with named whole numbers. + if let Some(f) = c.filters.iter().find(|f| matches!(f.keep, Keep::Values { .. }) && c.complex.names(&f.property).is_none()) { + return Err(bad(cmd, format!("`{}` has no named values: filter it with a range", f.property))); + } + Ok(()) +} + /// `height_range`: absent (`None`), null for the automatic one (`Some(None)`), or [low, high]. fn height_range(p: &Value, cmd: &str) -> Result>> { - let refuse = || bad(cmd, "`height_range` must be [low, high] heights in mm, lowest first, or null"); - match p.get("height_range") { + let refuse = || bad(cmd, "`height_range` (or `color_range`) must be [low, high], lowest first, or null"); + match p.get("color_range").or_else(|| p.get("height_range")) { None => Ok(None), Some(Value::Null) => Ok(Some(None)), Some(Value::Array(a)) => match a.iter().map(Value::as_f64).collect::>>().as_deref() { @@ -90,13 +148,18 @@ fn height_range(p: &Value, cmd: &str) -> Result>> { /// Apply `color_by`, `color` and `height_range`: a colour given alone means one colour, and /// `color: null` the file's. -fn set_colors(c: &mut PointCloud, by: Option, color: Option>, range: Option>) { +fn set_colors(c: &mut PointCloud, by: Option<(ColorBy, Option)>, color: Option>, range: Option>) { if let Some(k) = color { c.color = k.or(c.color); c.color_by = if k.is_some() { ColorBy::Single } else { ColorBy::File }; } - if let Some(b) = by { + if let Some((b, property)) = by { + if property != c.color_property && range.is_none() { + // Another property's values have another range. + c.height_range = None; + } c.color_by = b; + c.color_property = property.or(c.color_property.take().filter(|_| b == ColorBy::Property)); } if let Some(r) = range { c.height_range = r; @@ -172,8 +235,12 @@ fn insert(s: &mut Session, p: &Value) -> Result { color: None, height_range: None, visible: true, + complex: read.complex, + color_property: None, + filters: filters(p, cmd)?.unwrap_or_default(), }; set_colors(&mut cloud, colors.0, colors.1, colors.2); + check_properties(&cloud, cmd)?; if center && let Some((lo, hi)) = cloud.local_bounds() { cloud.transform[3] = [-(lo.x + hi.x) / 2.0, -(lo.y + hi.y) / 2.0, -lo.z, 1.0]; } @@ -207,6 +274,7 @@ fn edit(s: &mut Session, p: &Value) -> Result { let i = find(s, p, cmd)?; let size = point_size(p, cmd)?; let colors = (color_by(p, cmd)?, color(p, cmd)?, height_range(p, cmd)?); + let filters = filters(p, cmd)?; let units = units_of(p, cmd)?; let placement = match p.get("matrix") { None | Some(Value::Null) => None, @@ -236,6 +304,10 @@ fn edit(s: &mut Session, p: &Value) -> Result { c.point_size = v; } set_colors(&mut c, colors.0, colors.1, colors.2); + if let Some(f) = filters { + c.filters = f; + } + check_properties(&c, cmd)?; if let Some(v) = bool_(p, "visible") { c.visible = v; } @@ -271,7 +343,13 @@ fn list(s: &mut Session, _: &Value) -> Result { "units": c.units, "visible": c.visible, "point_size": c.point_size, - "color_by": c.color_by.name(), + "color_by": c.colored_property().filter(|_| c.color_by == ColorBy::Property).unwrap_or(c.color_by.name()), + "properties": c + .property_names() + .map(|n| json!({"name": n, "integer": c.complex.integer(n), "span": c.span(n), "names": c.complex.names(n).map(|m| &m.values)})) + .collect::>(), + "filters": c.filters, + "color_range": solidcraft_doc::point_cloud_distribution::color_range(c, &solidcraft_doc::point_cloud_distribution::Geometry::of(c), &c.filters), "color": c.color, "colored": !c.colors.is_empty(), "height_range": c.height_range_now(), diff --git a/crates/engine/src/cmd/print_face.rs b/crates/engine/src/cmd/print_face.rs new file mode 100644 index 000000000..db203ba2d --- /dev/null +++ b/crates/engine/src/cmd/print_face.rs @@ -0,0 +1,418 @@ +//! Laying bodies on their print face for a slicer (#8429). The bodies being sent are copied (the +//! state the export writes is already a copy), and each copy whose body has a print face is +//! turned so the face points down, its centre of mass moved onto the world origin in X and Y, +//! and the face moved onto Z = 0: one rigid transform, applied once. The design and its timeline +//! are not touched. Each body is placed on its own, so several land on the origin together and +//! the slicer arranges them. + +use serde_json::Value; +use solidcore_record::Vec3; +use solidcraft_doc::{ModelState, PrintFace}; +use solidcraft_geom::prelude::*; + +use super::CommandSpec; +use crate::params::{bad, str_}; +use crate::schema::print_face::PrintFaceResult; +use crate::{EngineError, Result, Session}; + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("body.print_face", "Print Face", crate::checked!("body.print_face", print_face)) + .icon("print_face") + .key("Ctrl+B") + .contract(&PRINT_FACE_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("body: its name; point?: [x, y, z] on a flat face of it, in mm (omit to clear) → {body, face?}: marks the face a slicer export (file.send_to_slicer, file.save_mesh with slicer, file.open_in_easyprint) lays the body on: turned so the face points down at Z = 0, the centre of mass over the origin. One per body, replacing the last; flat faces of solid bodies only. A print face that is gone or no longer flat is reported in the export's warnings, and the body exported as it lies")]; + +const PRINT_FACE_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +/// Mark or clear a body's print face. +fn print_face(s: &mut Session, p: &Value) -> Result { + let cmd = "body.print_face"; + let name = str_(p, "body").ok_or_else(|| bad(cmd, "give `body`"))?; + let point = match p.get("point") { + None | Some(Value::Null) => None, + Some(v) => Some(crate::params::vec3(v).ok_or_else(|| bad(cmd, "`point` must be [x, y, z] of numbers"))?), + }; + let world = s.world_state()?; + let body = world.body(name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?; + let key = body.definition_name().to_string(); + let face = match point { + None => { + s.doc_mut().print_faces.remove(&key); + None + } + Some(point) => { + let index = solidcraft_doc::appearance::face_index_at(body, point).ok_or_else(|| bad(cmd, "no face of the body at `point`"))?; + let target = s.doc.print_face_target(body, index).map_err(|e| bad(cmd, e.to_string()))?; + let face = target.name.clone(); + s.doc_mut().print_faces.insert(key, target); + Some(face) + } + }; + let reply = PrintFaceResult { body: name.to_string(), face, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + +/// Which bodies were laid on their print face, and a warning for each that has one but was +/// exported as it lies. +#[derive(Debug, Default)] +pub(super) struct Laid { + pub bodies: Vec, + pub warnings: Vec, +} + +impl Laid { + /// Add what happened to an export's reply. + pub(super) fn report(self, out: &mut serde_json::Value) { + let Some(obj) = out.as_object_mut() else { return }; + if !self.bodies.is_empty() { + obj.insert("print_faces".into(), serde_json::json!(self.bodies)); + } + if !self.warnings.is_empty() { + obj.insert("warnings".into(), serde_json::json!(self.warnings)); + } + } +} + +/// Copies keep the print faces of the bodies they were made from (Move/Copy, Mirror), as they +/// keep their look: the copies are the bodies feature `reply` made, in the order of `sources`. +/// A copy whose face can't be matched is left without one. +pub(super) fn copies_keep_print_faces(s: &mut Session, reply: &Value, sources: &[String]) { + let Some(id) = reply.get("feature").and_then(Value::as_u64) else { return }; + let state = s.model.state(); + let copies: Vec<_> = state.bodies.iter().filter(|b| b.feature == id).collect(); + if copies.len() != sources.len() { + return; + } + let mut inherited = Vec::new(); + for (source, copy) in sources.iter().zip(copies) { + let Some(source) = state.body(source) else { continue }; + if let Some(Ok(target)) = s.doc.copied_print_face(&state, source, copy) { + inherited.push((copy.definition_name().to_string(), target)); + } + } + for (body, target) in inherited { + s.doc_mut().print_faces.insert(body, target); + } +} + +/// Lay the bodies of `state` named in `bodies` (all of them when it is empty) on their print faces. +/// A body that is one of several parts of a 3MF object (`parts`, `objects: component`) stays as it +/// lies, so the object keeps its shape: turning one part on its own would pull it out of the rest. +pub(super) fn lay_on_print_faces(s: &Session, state: &mut ModelState, bodies: &[String], parts: &[(String, Vec)]) -> Laid { + let mut laid = Laid::default(); + let mut moves = Vec::new(); + for (i, b) in state.bodies.iter().enumerate() { + if !bodies.is_empty() && !bodies.contains(&b.name) { + continue; + } + if let Some((object, _)) = parts.iter().find(|(_, members)| members.contains(&b.name)) { + if s.doc.print_faces.contains_key(b.definition_name()) { + laid.warnings.push(format!("`{}` was exported as it lies: it is a part of the object `{object}`, which keeps its shape", b.name)); + } + continue; + } + let face = match s.doc.print_face(state, b) { + None => continue, + Some(Ok(face)) => face, + Some(Err(e)) => { + laid.warnings.push(format!("`{}` was exported as it lies: {e}", b.name)); + continue; + } + }; + let centre = match solidcraft_kernel::measure_mass(&b.body) { + Ok(m) => m.centroid, + Err(e) => { + laid.warnings.push(format!("`{}` was exported as it lies: no centre of mass ({e})", b.name)); + continue; + } + }; + moves.push((i, bed_matrix(face, centre))); + } + for (i, m) in moves { + let Some(b) = state.bodies.get_mut(i) else { continue }; + match solidcraft_kernel::transform_matrix(&b.body, m) { + Ok(body) => { + b.body = body; + laid.bodies.push(b.name.clone()); + } + Err(e) => laid.warnings.push(format!("`{}` was exported as it lies: {e}", b.name)), + } + } + laid +} + +/// The rotation (rows) that turns unit vector `n` to −Z. A face that already points down is +/// left as it is; one that points straight up is turned half a turn about X. +fn turn_down(n: Vec3) -> [Vec3; 3] { + let down = Vec3::new(0., 0., -1.); + let c = n.dot(down); + let v = n.cross(down); + let s2 = v.len2(); + if s2 <= 1e-24 { + return if c > 0. { [Vec3::X, Vec3::Y, Vec3::Z] } else { [Vec3::X, -Vec3::Y, -Vec3::Z] }; + } + // Rodrigues: R e = e + v × e + v × (v × e) (1 − c) / |v|²; these are R's columns. + let k = (1. - c) / s2; + let [x, y, z] = [Vec3::X, Vec3::Y, Vec3::Z].map(|e| e + v.cross(e) + v.cross(v.cross(e)) * k); + [Vec3::new(x.x, y.x, z.x), Vec3::new(x.y, y.y, z.y), Vec3::new(x.z, y.z, z.z)] +} + +/// The column-major transform that lays `face` on the bed with `centre` above the origin. +fn bed_matrix(face: PrintFace, centre: Vec3) -> [[f64; 4]; 4] { + let r = turn_down(face.normal); + let apply = |p: Vec3| Vec3::new(r[0].dot(p), r[1].dot(p), r[2].dot(p)); + let c = apply(centre); + let z = apply(face.point).z; + let t = Vec3::new(-c.x, -c.y, -z); + [[r[0].x, r[1].x, r[2].x, 0.], [r[0].y, r[1].y, r[2].y, 0.], [r[0].z, r[1].z, r[2].z, 0.], [t.x, t.y, t.z, 1.]] +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } + } + + /// A box `L` x 10 x 5 (L = 20 mm) from the origin, called Block. + fn block() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "L", "expression": "20 mm"})); + run(&mut s, "solid.box", json!({"length": "L", "width": 10, "height": 5, "corner": [0, 0, 0], "body_name": "Block"})); + s + } + + /// Lay every body of `s` on its print face, as a slicer export does: Block's box and centre + /// of mass afterwards, and what was reported. + fn laid(s: &Session) -> (solidcraft_geom::Aabb3, Vec3, Laid) { + let mut state = s.doc.painted(&s.world_state().unwrap()); + let laid = lay_on_print_faces(s, &mut state, &[], &[]); + let block = state.bodies.iter().find(|b| b.name == "Block").expect("Block"); + let m = solidcraft_kernel::measure_mass(&block.body).expect("measure"); + (m.bbox, m.centroid, laid) + } + + fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 + } + + #[test] + fn a_part_of_a_3mf_object_keeps_its_place_in_the_object() { + // With `objects: component` the bodies of a component are the parts of one object: + // turning one of them on its own would pull it out of the others, so it stays as it lies. + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [20, 5, 2.5]})); + let mut state = s.doc.painted(&s.world_state().unwrap()); + let parts = [("Bracket".to_string(), vec!["Block".to_string(), "Other".to_string()])]; + let laid = lay_on_print_faces(&s, &mut state, &[], &parts); + assert!(laid.bodies.is_empty(), "{:?}", laid.bodies); + assert_eq!(laid.warnings.len(), 1, "{:?}", laid.warnings); + assert!(laid.warnings.first().is_some_and(|w| w.contains("Block") && w.contains("Bracket")), "{:?}", laid.warnings); + let block = state.bodies.iter().find(|b| b.name == "Block").expect("Block"); + let bbox = solidcraft_kernel::measure_mass(&block.body).expect("measure").bbox; + assert!(near(bbox.min.x, 0.) && near(bbox.max.x, 20.) && near(bbox.max.z, 5.), "{bbox:?}"); + } + + #[test] + fn a_side_face_is_laid_down_at_z_0_with_the_centre_of_mass_over_the_origin() { + let mut s = block(); + let reply = run(&mut s, "body.print_face", json!({"body": "Block", "point": [20, 5, 2.5]})); + assert!(reply["face"].is_string(), "{reply}"); + let (bbox, centre, laid) = laid(&s); + assert_eq!(laid.bodies, ["Block"]); + assert!(laid.warnings.is_empty(), "{:?}", laid.warnings); + // The 10 x 5 end face is on the bed, so the 20 mm length now stands up. + assert!(near(bbox.min.z, 0.) && near(bbox.max.z, 20.), "{bbox:?}"); + assert!(near(centre.x, 0.) && near(centre.y, 0.) && near(centre.z, 10.), "{centre:?}"); + assert!(near((bbox.max.x - bbox.min.x) * (bbox.max.y - bbox.min.y), 50.), "{bbox:?}"); + // The design itself has not moved. + let m = solidcraft_kernel::measure_mass(&s.model.state().bodies[0].body).expect("measure"); + assert!(near(m.bbox.min.x, 0.) && near(m.bbox.max.x, 20.) && near(m.bbox.max.z, 5.), "{:?}", m.bbox); + } + + #[test] + fn a_face_that_points_up_is_turned_over() { + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [10, 5, 5]})); + let (bbox, centre, laid) = laid(&s); + assert_eq!(laid.bodies, ["Block"]); + assert!(near(bbox.min.z, 0.) && near(bbox.max.z, 5.), "{bbox:?}"); + assert!(near(bbox.max.x - bbox.min.x, 20.) && near(bbox.max.y - bbox.min.y, 10.), "{bbox:?}"); + assert!(near(centre.x, 0.) && near(centre.y, 0.) && near(centre.z, 2.5), "{centre:?}"); + } + + #[test] + fn the_print_face_follows_the_body_through_a_rebuild() { + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [20, 5, 2.5]})); + run(&mut s, "parameters.change", json!({"name": "L", "expression": "30 mm"})); + let (bbox, centre, laid) = laid(&s); + assert!(laid.warnings.is_empty(), "{:?}", laid.warnings); + assert!(near(bbox.min.z, 0.) && near(bbox.max.z, 30.), "{bbox:?}"); + assert!(near(centre.x, 0.) && near(centre.y, 0.) && near(centre.z, 15.), "{centre:?}"); + } + + #[test] + fn without_a_print_face_the_body_is_exported_as_it_lies() { + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [10, 5, 5]})); + let reply = run(&mut s, "body.print_face", json!({"body": "Block"})); + assert!(reply.get("face").is_none(), "{reply}"); + assert!(s.doc.print_faces.is_empty()); + let (bbox, _, laid) = laid(&s); + assert!(laid.bodies.is_empty() && laid.warnings.is_empty()); + assert!(near(bbox.min.x, 0.) && near(bbox.max.x, 20.) && near(bbox.min.z, 0.) && near(bbox.max.z, 5.), "{bbox:?}"); + } + + #[test] + fn a_print_face_that_was_cut_away_is_reported_and_the_body_exported_as_it_lies() { + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [10, 5, 5]})); + // A cut takes the top 2 mm off: the marked face is gone; the new top is the cut's. + run(&mut s, "solid.box", json!({"length": 30, "width": 20, "height": 5, "corner": [-5, -5, 3], "operation": "cut"})); + let (bbox, _, laid) = laid(&s); + assert!(laid.bodies.is_empty()); + assert_eq!(laid.warnings.len(), 1, "{:?}", laid.warnings); + assert!(laid.warnings[0].contains("Block"), "{:?}", laid.warnings); + assert!(near(bbox.min.x, 0.) && near(bbox.max.z, 3.), "{bbox:?}"); + } + + #[test] + fn a_print_face_is_saved_with_the_design_and_an_older_design_has_none() { + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [10, 5, 5]})); + let saved = serde_json::to_value(&*s.doc).expect("save"); + assert!(saved["print_faces"]["Block"].is_object(), "{}", saved["print_faces"]); + let opened: solidcraft_doc::Document = serde_json::from_value(saved.clone()).expect("open"); + assert_eq!(opened.print_faces, s.doc.print_faces); + let mut older = saved; + older.as_object_mut().expect("object").remove("print_faces"); + let opened: solidcraft_doc::Document = serde_json::from_value(older).expect("open"); + assert!(opened.print_faces.is_empty()); + } + + #[test] + fn renaming_the_body_keeps_its_print_face() { + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [10, 5, 5]})); + run(&mut s, "body.rename", json!({"body": "Block", "name": "Lid"})); + assert!(s.doc.print_faces.contains_key("Lid") && !s.doc.print_faces.contains_key("Block")); + assert_eq!(s.doc.print_faces["Lid"].body, "Lid"); + } + + /// Every body laid on its print face: (name, box, centre of mass) of those laid. + fn all_laid(s: &Session) -> Vec<(String, solidcraft_geom::Aabb3, Vec3)> { + let mut state = s.doc.painted(&s.world_state().unwrap()); + let laid = lay_on_print_faces(s, &mut state, &[], &[]); + assert!(laid.warnings.is_empty(), "{:?}", laid.warnings); + laid.bodies + .iter() + .map(|name| { + let b = state.bodies.iter().find(|b| &b.name == name).expect("laid body"); + let m = solidcraft_kernel::measure_mass(&b.body).expect("measure"); + (name.clone(), m.bbox, m.centroid) + }) + .collect() + } + + #[test] + fn a_copy_keeps_the_print_face_of_the_body_it_was_copied_from() { + let mut s = block(); + run(&mut s, "body.print_face", json!({"body": "Block", "point": [20, 5, 2.5]})); + run(&mut s, "solid.move", json!({"bodies": ["Block"], "translate": [0, 50, 0], "copy": true})); + assert_eq!(s.doc.print_faces.len(), 2, "{:?}", s.doc.print_faces.keys().collect::>()); + let laid = all_laid(&s); + assert_eq!(laid.len(), 2, "{laid:?}"); + for (name, bbox, centre) in &laid { + assert!(near(bbox.min.z, 0.) && near(bbox.max.z, 20.), "{name}: {bbox:?}"); + assert!(near(centre.x, 0.) && near(centre.y, 0.), "{name}: {centre:?}"); + } + } + + #[test] + fn a_mirrored_copy_keeps_the_mirrored_print_face() { + let mut s = block(); + // The end at X = 20; its mirror image in YZ is the copy's end at X = -20. + run(&mut s, "body.print_face", json!({"body": "Block", "point": [20, 5, 2.5]})); + run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "YZ"})); + assert_eq!(s.doc.print_faces.len(), 2, "{:?}", s.doc.print_faces.keys().collect::>()); + let copy = s.doc.print_faces.keys().find(|k| *k != "Block").expect("the copy's print face").clone(); + let world = s.world_state().unwrap(); + let body = world.body(©).expect("copy"); + let face = s.doc.print_face(&world, body).expect("marked").expect("found"); + assert!(near(face.point.x, -20.) && near(face.normal.x, -1.), "{face:?}"); + let laid = all_laid(&s); + assert_eq!(laid.len(), 2, "{laid:?}"); + for (name, bbox, _) in &laid { + assert!(near(bbox.min.z, 0.) && near(bbox.max.z, 20.), "{name}: {bbox:?}"); + } + } + + #[test] + fn a_copy_of_a_body_without_a_print_face_gets_none() { + let mut s = block(); + run(&mut s, "solid.move", json!({"bodies": ["Block"], "translate": [0, 50, 0], "copy": true})); + run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "XZ"})); + assert!(s.doc.print_faces.is_empty()); + } + + #[test] + fn a_point_off_the_body_or_a_body_that_is_not_there_is_refused() { + let mut s = block(); + assert!(s.execute("body.print_face", &json!({"body": "Block", "point": [100, 100, 100]})).is_err()); + assert!(s.execute("body.print_face", &json!({"body": "Nope", "point": [10, 5, 5]})).is_err()); + assert!(s.execute("body.print_face", &json!({"body": "Block", "point": "top"})).is_err()); + assert!(s.doc.print_faces.is_empty()); + } + + fn turned(n: Vec3) -> Vec3 { + let r = turn_down(n); + Vec3::new(r[0].dot(n), r[1].dot(n), r[2].dot(n)) + } + + #[test] + fn every_normal_is_turned_to_point_down_by_a_rotation() { + let down = Vec3::new(0., 0., -1.); + for n in [Vec3::X, -Vec3::X, Vec3::Y, -Vec3::Y, Vec3::Z, -Vec3::Z, Vec3::new(1., 2., 3.), Vec3::new(-0.3, 0.1, 0.9), Vec3::new(1e-9, 0., 1.)] + { + let n = n.normalized().unwrap(); + assert!(turned(n).dist(down) < 1e-12, "{n:?} → {:?}", turned(n)); + let r = turn_down(n); + // Orthonormal rows with a positive determinant: a rotation, never a mirror. + for i in 0..3 { + assert!((r[i].len() - 1.).abs() < 1e-12); + for j in i + 1..3 { + assert!(r[i].dot(r[j]).abs() < 1e-12); + } + } + assert!((r[0].cross(r[1]).dot(r[2]) - 1.).abs() < 1e-12); + } + } + + #[test] + fn a_face_that_points_straight_up_is_turned_half_a_turn_about_x() { + let r = turn_down(Vec3::Z); + assert_eq!(r, [Vec3::X, -Vec3::Y, -Vec3::Z]); + } + + #[test] + fn the_bed_matrix_puts_the_face_at_z_0_and_the_centre_over_the_origin() { + let face = PrintFace { index: 0, point: Vec3::new(3., 4., 10.), normal: Vec3::Z }; + let m = bed_matrix(face, Vec3::new(3., 4., 5.)); + let apply = |p: Vec3| { + Vec3::new( + m[0][0] * p.x + m[1][0] * p.y + m[2][0] * p.z + m[3][0], + m[0][1] * p.x + m[1][1] * p.y + m[2][1] * p.z + m[3][1], + m[0][2] * p.x + m[1][2] * p.y + m[2][2] * p.z + m[3][2], + ) + }; + assert!(apply(face.point).z.abs() < 1e-12); + let c = apply(Vec3::new(3., 4., 5.)); + assert!(c.x.abs() < 1e-12 && c.y.abs() < 1e-12 && c.z > 0., "{c:?}"); + } +} diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index 71b669936..150734229 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -68,13 +68,13 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("render.optics.unbind","Remove Optical Binding",optical_bindings::unbind).icon("appearance").doc_only() .params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."), CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only() - .params("job: exact completed JobId; presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), + .params("job?: exact completed JobId (default selected result); presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only() .params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."), CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo() .params("No parameters. Returns the explicitly defined current view camera, or null if the session has no camera override. No camera is fitted, no job is started and no saved setup or engineering document is changed."), CommandSpec::new("render.camera.fit", "Frame Render Subject", fit_camera).icon("camera").noundo() - .params("No parameters. Fits the current camera to the visible product bounds through the shared Camera::fit contract; changes only view state, not a saved setup, rendering job, stage or engineering geometry."), + .params("aspect?: the picture's width over its height, 0.000001 to 1000000 (default 1). Fits the current camera to the visible product bounds through the shared Camera::fit contract, moving back for a picture taller than wide so its sides hold the product too; changes only view state, not a saved setup, rendering job, stage or engineering geometry."), CommandSpec::new("render.preset.resolve", "Review Native Studio", studio_presets::resolve).icon("render_scene").noundo() .params("id: NATIVE-STUDIO-001..025; name; set?: typed GPU setup patch; expected_revision?:u64. Resolves original built-in HDR/rig/passive ground with conservative geometry clearance, returns all replacements and preserved fields without mutation. Unbound SCENE-* concepts are not accepted."), CommandSpec::new("render.preset.apply", "Apply Native Studio", studio_presets::apply).icon("render_scene") @@ -91,18 +91,24 @@ CommandSpec::new("render.library.preview", "Inspect Original Surface Map", libra .params("id: SURF-*. Returns bounded hash-verified original base-color PNG bytes and source-map fidelity label, not a rendered material thumbnail. No external paths, rendering or document edits."), CommandSpec::new("render.library.physical.prepare", "Prepare Physical Reference", physical_library::prepare).icon("inspect").noundo().doc_only() .params("id: named built-in physical profile, name: proposed new material label, acknowledge_reference:true. Read-only loss-aware creation plan using native ValidatedCard admission and one point density; returns source receipts, extended fields and omissions. Does not execute material.create, assign bodies or infer effective-part physics."), -CommandSpec::new("render.stage.ground", "Save Render Ground", staging::ground).icon("render_scene") +CommandSpec::new("render.stage.ground", "Save Render Ground", crate::checked!("render.stage.ground", staging::ground)).icon("render_scene") + .contract(&staging::GROUND_CONTRACT) + .output(crate::schema::output_schema_for::) .params("name: typed raytrace setup, set?: setup patch, margin_fraction?:0.25, gap_mm?:0.1, reflectance_linear?:[0.18,0.18,0.18], replace_stage?:false. Fits one finite passive ground below the visible product once and saves its physical transforms in one undo. Product AABB separation is rechecked on every render."), -CommandSpec::new("render.stage.backdrop", "Save Physical Render Background", staging::backdrop).icon("render_scene").doc_only() +CommandSpec::new("render.stage.backdrop", "Save Physical Render Background", crate::checked!("render.stage.backdrop", staging::backdrop)).icon("render_scene").doc_only() + .contract(&staging::BACKDROP_CONTRACT) + .output(crate::schema::output_schema_for::) .params("name: typed raytrace setup, set?: setup patch, kind: floor_wall or cyclorama, reflectance_linear?: [0.18,0.18,0.18], expected_revision: reviewed revision, replace_stage?:false. Fits a finite floor/wall or a 24-strip polygonal cyclorama behind the visible subject using the saved camera azimuth; world +Z up and a minimum one-mm stage envelope. Preserves subject geometry, lighting, output, pose and engineering materials; one undo and rechecked product separation. Not an infinite/analytically smooth/terrain background."), -CommandSpec::new("render.stage.clear", "Remove Render Stage", staging::clear).icon("render_scene").doc_only() +CommandSpec::new("render.stage.clear", "Remove Render Stage", crate::checked!("render.stage.clear", staging::clear)).icon("render_scene").doc_only() + .contract(&staging::CLEAR_CONTRACT) + .output(crate::schema::output_schema_for::) .params("name: setup, set?: setup patch. Removes saved render-only panels atomically; CAD geometry and lighting are unchanged."), CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_bindings::bind).icon("appearance") .params("name: GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."), CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only() .params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."), CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only() - .params("job: completed JobId, or null to release the displayed-result pin. Retains at most one completed result independently of a newer completion; preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), + .params("job?: completed JobId (default selected result), or null to clear selection. Selects within the eight retained completed results; oldest is evicted first. Preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo() .params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."), CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only() @@ -128,13 +134,13 @@ CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).ic CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image") .params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"), CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only() - .params("job: {session, serial, generation}. Non-blocking progress, error, optional CPU preview metadata {frame_sequence,samples_per_pixel,frame}, and completed frame metadata, optional sampling allocation/work counts and retained-master presentation provenance; no image bytes and no rendering in this call. Preview is separate from the exportable final image."), + .params("job?: {session, serial, generation}. Non-blocking progress, errors and captured frame metadata with queue:{running,waiting,job,shot,error}. Without job returns queue only. Advances an explicitly started render.batch through render.start as jobs finish; never pumps render work. Preview is separate from the exportable final image."), CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete").noundo().doc_only() - .params("job: {session, serial, generation}. Requests cooperative cancellation; completed jobs remain completed. Late cancelled frames cannot be published."), + .params("job?: {session, serial, generation}, default the active render.batch job. Requests cooperative cancellation and drops its waiting shots; completed jobs remain completed. Late cancelled frames cannot be published."), CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only() - .params("job: completed JobId. Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."), + .params("job?: completed JobId (default selected result). Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."), CommandSpec::new("render.export", "Export Render Image", jobs::export).icon("export").noundo().doc_only() - .params("job: {session, serial, generation}, path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), + .params("job?: {session, serial, generation} (default selected result), path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), CommandSpec::new("render.backends", "Render Backends", backends).icon("list") .noundo() .doc_only() @@ -169,13 +175,20 @@ fn get_camera(s: &mut Session, params: &Value) -> Result { } fn fit_camera(s: &mut Session, params: &Value) -> Result { - if !params.as_object().is_some_and(|p| p.is_empty()) { - return Err(bad("render.camera.fit", "expected an empty parameter object")); - } + let aspect = match params.as_object() { + Some(p) if p.is_empty() => 1.0, + Some(p) if p.len() == 1 && p.contains_key("aspect") => match p["aspect"].as_f64() { + // The range a preview frame can show (`frame_rect` in the Render workspace). + Some(a) if (1e-6..=1e6).contains(&a) => a, + _ => return Err(bad("render.camera.fit", "aspect must be a number from 0.000001 to 1000000: the picture's width over its height")), + }, + _ => return Err(bad("render.camera.fit", "expected an empty parameter object or {aspect}")), + }; let scene = crate::product_scene::extract(s)?; let mut camera = s.camera.unwrap_or_default(); - if !scene.bounds.is_empty() { - camera.fit(&scene.bounds); + // Publish only a valid fitted camera; the previous one stays otherwise. + if !camera.fit_aspect(&scene.bounds, aspect) && !scene.bounds.is_empty() { + return Err(bad("render.camera.fit", "the product cannot be framed at this aspect: the fitted camera is out of range")); } s.camera = Some(camera); Ok(json!({"camera":camera,"empty":scene.bounds.is_empty(),"document_changed":false})) diff --git a/crates/engine/src/cmd/render/clear_coat.rs b/crates/engine/src/cmd/render/clear_coat.rs index f8a47a35c..4e71dc325 100644 --- a/crates/engine/src/cmd/render/clear_coat.rs +++ b/crates/engine/src/cmd/render/clear_coat.rs @@ -1,7 +1,7 @@ //! Request-only coat overrides on immutable captured geometry; no saved appearance changes. use crate::{Result, params::bad}; use serde::Deserialize; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_render::{ ProductScene, clear_coat::ClearCoat, diff --git a/crates/engine/src/cmd/render/job_tests.rs b/crates/engine/src/cmd/render/job_tests.rs index 47c6e4d15..52166ac08 100644 --- a/crates/engine/src/cmd/render/job_tests.rs +++ b/crates/engine/src/cmd/render/job_tests.rs @@ -924,7 +924,7 @@ fn native_spatial_aa_preflight_and_host_forwarding_change_actual_edge_png() { let center = scene.bounds.center(); let mut camera = solidcraft_render::Camera { distance: 2.0, fov: 0.0, ..Default::default() }; camera.set_view(solidcraft_render::StandardView::Top); - camera.target = solidcraft_geom::Vec3::new(scene.bounds.min.x, center.y, center.z); + camera.target = solidcore_record::Vec3::new(scene.bounds.min.x, center.y, center.z); let doc = s.doc.clone(); let before = (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len()); let mut legacy: Option> = None; @@ -1052,6 +1052,14 @@ fn completed_png_content_identity_matches_status_and_exact_retained_export() { finish(&host); let newer = s.execute("render.status", &json!({"job":replacement})).unwrap(); assert_ne!(newer["frame"]["png_sha256"], metadata["png_sha256"]); + let still_retained = dir.join("still-retained.png"); + s.execute("render.export", &json!({"job":id,"path":still_retained})).unwrap(); + assert_eq!(std::fs::read(still_retained).unwrap(), bytes); + for _ in 0..7 { + let next = start(&mut s); + finish(&host); + s.execute("render.status", &json!({"job":next})).unwrap(); + } let evicted = dir.join("evicted.png"); assert!(s.execute("render.export", &json!({"job":id,"path":evicted})).is_err()); assert!(!evicted.exists()); @@ -1183,9 +1191,26 @@ fn registered_product_camera_fit_changes_only_view_and_keeps_orientation() { assert_eq!(fitted["document_changed"], false); let after = s.camera.unwrap(); assert_eq!((after.yaw, after.pitch, after.roll), (camera.yaw, camera.pitch, camera.roll)); + // A picture taller than wide moves the camera back by the ratio, keeping the orientation + // and the target; a wide one is the plain fit. + let tall = s.execute("render.camera.fit", &json!({"aspect":0.5})).unwrap(); + assert_eq!(tall["document_changed"], false); + let back = s.camera.unwrap(); + assert!((back.distance - 2.0 * after.distance).abs() < 1e-9, "{} vs {}", back.distance, after.distance); + assert_eq!((back.yaw, back.pitch, back.roll, back.target), (after.yaw, after.pitch, after.roll, after.target)); + s.execute("render.camera.fit", &json!({"aspect":2.0})).unwrap(); + assert_eq!(s.camera.unwrap(), after); assert_eq!(s.doc.to_json(), doc); assert_eq!(s.undo.len(), undo); + // Hostile aspects are refused and leave the finite camera, the document and undo alone: + // a subnormal one would otherwise divide the fitted distance into infinity. + for aspect in [json!(0), json!(-1), json!(1e-320), json!(1e-7), json!(1e7), json!("tall")] { + assert!(s.execute("render.camera.fit", &json!({"aspect":aspect})).is_err(), "aspect {aspect}"); + assert_eq!(s.camera.unwrap(), after); + } assert!(s.execute("render.camera.fit", &json!({"scale":0})).is_err()); + assert_eq!(s.doc.to_json(), doc); + assert_eq!(s.undo.len(), undo); } #[test] @@ -1264,7 +1289,12 @@ fn output_viewer_copy_validates_completed_job_without_mutation_or_pixel_payloads assert_eq!(copied["frame"]["job"], json!(job)); assert_eq!(copied["frame"]["width"], 16); assert!(copied.get("png").is_none()); - for params in [json!({}), json!(null), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})] { + for params in [json!({}), json!(null)] { + assert_eq!(s.execute("render.result.copy", ¶ms).unwrap(), copied, "an omitted job uses the selected result"); + } + for params in + [json!({"job":1e300}), json!({"job":"selected"}), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})] + { assert!(s.execute("render.result.copy", ¶ms).is_err()); } assert!(Arc::ptr_eq(&document, &s.doc)); diff --git a/crates/engine/src/cmd/render/jobs.rs b/crates/engine/src/cmd/render/jobs.rs index b0b0b29de..86d4161db 100644 --- a/crates/engine/src/cmd/render/jobs.rs +++ b/crates/engine/src/cmd/render/jobs.rs @@ -675,7 +675,12 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result { p.scene, p.request, p.replace, - crate::render_jobs::Execution { executor: p.executor, options: p.options, environment: p.environment }, + crate::render_jobs::Execution { + executor: p.executor, + options: p.options, + environment: p.environment, + shot: params.get("setup").and_then(Value::as_str).map(str::to_owned), + }, ) .map_err(job_error)?; let mut status = json!(status); @@ -688,24 +693,32 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Regrade { - job: JobId, + job: Option, presentation: solidcraft_render::job::presentation::Presentation, } pub(super) fn regrade(s: &mut Session, params: &Value) -> Result { let input: Regrade = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.regrade", e.to_string()))?; input.presentation.validate().map_err(job_error)?; - Ok(json!(s.render_jobs.regrade(input.job, input.presentation).map_err(job_error)?)) + let job = result_source(s, input.job, "render.result.regrade")?; + Ok(json!(s.render_jobs.regrade(job, input.presentation).map_err(job_error)?)) } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Job { - job: JobId, +fn result_source(s: &mut Session, job: Option, command: &str) -> Result { + s.render_jobs.collect().map_err(job_error)?; + job.or_else(|| s.render_selected_result()).ok_or_else(|| bad(command, "no completed result is selected")) } pub(super) fn status(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?; - Ok(json!(s.render_jobs.status(input.job).map_err(job_error)?)) + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?; + s.advance_render_batch()?; + let Some(job) = input.job else { + return Ok(json!({"queue":s.render_queue_state()})); + }; + let mut reply = json!(s.render_jobs.status(job).map_err(job_error)?); + if let Some(object) = reply.as_object_mut() { + object.insert("queue".into(), json!(s.render_queue_state())); + } + Ok(reply) } #[derive(Deserialize)] @@ -714,18 +727,23 @@ struct Pin { job: Option, } pub(super) fn pin(s: &mut Session, params: &Value) -> Result { - if params.get("job").is_none() { - return Err(bad("render.result.pin", "job or explicit null is required")); - } let input: Pin = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.pin", e.to_string()))?; - Ok(json!({"frame":s.render_jobs.pin(input.job).map_err(job_error)?})) + let job = if params.get("job").is_some_and(Value::is_null) { None } else { Some(result_source(s, input.job, "render.result.pin")?) }; + Ok(json!({"frame":s.render_jobs.pin(job).map_err(job_error)?})) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ResultJob { + job: Option, } pub(super) fn copy(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?; + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?; + let job = result_source(s, input.job, "render.result.copy")?; let frame = s .render_jobs - .handle(input.job) + .handle(job) .map_err(job_error)? .frame() .map_err(job_error)? @@ -738,12 +756,14 @@ pub(super) fn copy(s: &mut Session, params: &Value) -> Result { } pub(super) fn cancel(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; - let status = s.render_jobs.status(input.job).map_err(job_error)?; + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; + let job = input.job.or(s.render_queue_state().job).ok_or_else(|| bad("render.cancel", "job is required without an active shot queue"))?; + let status = s.render_jobs.status(job).map_err(job_error)?; + s.cancel_render_batch(job); if status.progress.phase.terminal() { return Ok(json!(status)); } - Ok(json!(s.render_jobs.handle(input.job).map_err(job_error)?.cancel().map_err(job_error)?)) + Ok(json!(s.render_jobs.handle(job).map_err(job_error)?.cancel().map_err(job_error)?)) } #[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] @@ -766,7 +786,7 @@ impl ExportFormat { struct Export { #[serde(default)] format: ExportFormat, - job: JobId, + job: Option, path: String, #[serde(default)] overwrite: bool, @@ -784,7 +804,8 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result { // Atomic native writers are also used for the app's own files and do not // apply a request's path scope. Check the caller's destination explicitly. solidcraft_io::vfs::check(&input.path).map_err(|e| bad("render.export", e.to_string()))?; - let frame = s.render_jobs.frame(input.job).map_err(job_error)?; + let job = result_source(s, input.job, "render.export")?; + let frame = s.render_jobs.frame(job).map_err(job_error)?; let bytes = match input.format { ExportFormat::Png => frame.png(), ExportFormat::Exr => frame @@ -797,7 +818,7 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result { if input.overwrite { solidcraft_io::write_atomic(path, bytes, false) } else { solidcraft_io::safe_write::create_atomic(path, bytes) }; result.map_err(|e| bad("render.export", format!("could not export completed {}: {e}", input.format.extension())))?; Ok( - json!({"job":input.job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}), + json!({"job":job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}), ) } diff --git a/crates/engine/src/cmd/render/settings_tests.rs b/crates/engine/src/cmd/render/settings_tests.rs index ee567667d..de1a59acc 100644 --- a/crates/engine/src/cmd/render/settings_tests.rs +++ b/crates/engine/src/cmd/render/settings_tests.rs @@ -1,5 +1,6 @@ use super::*; use solidcraft_doc::render_settings::RenderJob; +use solidcraft_geom::prelude::*; fn save(s: &mut Session, patch: Value) { s.execute("render.settings.set", &json!({"name":"Studio", "set":patch})).unwrap(); @@ -181,7 +182,7 @@ fn light_fixture(s: &mut Session, method: &str) { #[test] fn render_lights_small_area_pose_and_resize_preserve_aspect_and_emitting_side() { use crate::schema::render_lights::Geometry; - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut s = Session::default(); save( &mut s, @@ -666,7 +667,7 @@ fn portable_job_save_is_host_independent_atomic_and_undoable_without_geometry_ch assert!(s.render_job_host().is_none()); let original = s.doc.clone(); let model = s.model.state(); - let world = s.world_state(); + let world = s.world_state().unwrap(); let undo = s.undo.len(); s.evaluations = 0; let setup: RenderSetup = serde_json::from_value(json!({ @@ -712,7 +713,7 @@ fn portable_job_save_is_host_independent_atomic_and_undoable_without_geometry_ch ); assert_eq!(s.doc.render.setups["Studio"].exposure_ev, 2.5); assert!(Arc::ptr_eq(&model, &s.model.state())); - assert!(Arc::ptr_eq(&world, &s.world_state())); + assert!(Arc::ptr_eq(&world, &s.world_state().unwrap())); assert_eq!(s.evaluations, 0); } @@ -746,7 +747,7 @@ fn settings_history_preserves_geometry_cache_and_dirty_state() { s.execute("occurrence.move", &json!({"occurrence":component["occurrence"],"translate":[30,0,0]})).unwrap(); s.mark_saved(); let model = s.model.state(); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(!Arc::ptr_eq(&model, &world), "exercise the prepared occurrence cache"); let mesh = model.bodies[0].mesh(); let undo = s.undo.len(); @@ -779,7 +780,7 @@ fn settings_history_preserves_geometry_cache_and_dirty_state() { assert_eq!(s.doc.render.setups["Studio"].width, 1024); assert!(Arc::ptr_eq(&model, &s.model.state())); assert!(Arc::ptr_eq(&mesh, &s.model.state().bodies[0].mesh())); - assert!(Arc::ptr_eq(&world, &s.world_state())); + assert!(Arc::ptr_eq(&world, &s.world_state().unwrap())); assert_eq!(s.evaluations, 0); // A geometry change and its history still require normal evaluation. s.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap(); diff --git a/crates/engine/src/cmd/render/staging.rs b/crates/engine/src/cmd/render/staging.rs index 60540f601..4130f3576 100644 --- a/crates/engine/src/cmd/render/staging.rs +++ b/crates/engine/src/cmd/render/staging.rs @@ -1,7 +1,8 @@ //! Explicit saved render-only ground. Does not add engineering bodies or material cards. +use crate::schema::TypedContract; +use crate::schema::render_stage::{BackdropKind, BackdropParams, ClearParams, GroundParams, StageSaved}; use crate::{Result, Session, params::bad}; -use serde::Deserialize; -use serde_json::{Value, json}; +use serde_json::Value; use solidcraft_doc::render_settings::{RenderJob, RenderSetup}; use solidcraft_render::{ ProductScene, @@ -9,49 +10,41 @@ use solidcraft_render::{ stage::{Stage, StagePanel}, }; use std::sync::Arc; -fn patch() -> Value { - json!({}) -} -fn margin() -> f64 { - 0.25 -} -fn gap() -> f64 { - 0.1 -} -fn reflectance() -> [f64; 3] { - [0.18; 3] -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Ground { - name: String, - #[serde(default = "patch")] - set: Value, - #[serde(default = "margin")] - margin_fraction: f64, - #[serde(default = "gap")] - gap_mm: f64, - #[serde(default = "reflectance")] - reflectance_linear: [f64; 3], - #[serde(default)] - replace_stage: bool, -} + +pub(super) const GROUND_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const BACKDROP_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const CLEAR_CONTRACT: TypedContract = TypedContract::new(); + pub(super) fn apply(scene: &mut ProductScene, setup: &RenderSetup, command: &str) -> Result<()> { setup.stage.append_to(scene, &CancelToken::default()).map_err(|e| bad(command, e.to_string())) } -fn save(s: &mut Session, name: String, setup: RenderSetup, command: &str) -> Result { +fn save(s: &mut Session, name: String, setup: RenderSetup, command: &str) -> Result { let mut settings = (*s.doc.render).clone(); settings.setups.insert(name.clone(), setup.clone()); settings.validate().map_err(|e| bad(command, e.to_string()))?; + let setup = serde_json::to_value(&setup).map_err(|e| bad(command, e.to_string()))?; if settings != *s.doc.render { s.doc_mut().render = Arc::new(settings); } - Ok(json!({"name":name,"setup":setup,"engineering_geometry_unchanged":true,"stage_only":true, - "clearance":"conservative product AABB separation; not a B-rep collision proof"})) + Ok(StageSaved { + name, + setup, + engineering_geometry_unchanged: true, + stage_only: true, + clearance: "conservative product AABB separation; not a B-rep collision proof".into(), + geometry_kind: None, + light_transport: None, + camera_preserved: None, + limitations: None, + param_warnings: Vec::new(), + }) +} +fn reply(command: &str, saved: StageSaved) -> Result { + serde_json::to_value(saved).map_err(|e| bad(command, e.to_string())) } pub(super) fn ground(s: &mut Session, params: &Value) -> Result { let command = "render.stage.ground"; - let input: Ground = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: GroundParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if !input.margin_fraction.is_finite() || !(0.0..=10.0).contains(&input.margin_fraction) || !input.gap_mm.is_finite() @@ -88,48 +81,22 @@ pub(super) fn ground(s: &mut Session, params: &Value) -> Result { }]) .map_err(|e| bad(command, e.to_string()))?; apply(&mut scene, &setup, command)?; - save(s, input.name, setup, command) -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Clear { - name: String, - #[serde(default = "patch")] - set: Value, + reply(command, save(s, input.name, setup, command)?) } pub(super) fn clear(s: &mut Session, params: &Value) -> Result { let command = "render.stage.clear"; - let input: Clear = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: ClearParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; let mut setup = super::patched_settings(s, &input.name, &input.set, command)?; setup.stage = Stage::default(); - save(s, input.name, setup, command) + reply(command, save(s, input.name, setup, command)?) } -#[derive(Clone, Copy, Debug, Deserialize)] -#[serde(rename_all = "snake_case")] -enum BackdropKind { - FloorWall, - Cyclorama, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct BackdropInput { - name: String, - #[serde(default = "patch")] - set: Value, - kind: BackdropKind, - #[serde(default = "reflectance")] - reflectance_linear: [f64; 3], - #[serde(default)] - replace_stage: bool, - expected_revision: u64, -} /// Original world-space stage derived from captured subject bounds and the chosen /// camera azimuth. Twenty-four explicit planar strips approximate the round cove; /// it is not an analytic smooth surface, terrain or engineering model operation. pub(super) fn backdrop(s: &mut Session, params: &Value) -> Result { let command = "render.stage.backdrop"; - let input: BackdropInput = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: BackdropParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if input.expected_revision != s.revision { return Err(bad(command, "the design changed; review the stage again")); } @@ -156,8 +123,8 @@ pub(super) fn backdrop(s: &mut Session, params: &Value) -> Result { } // Camera back projects toward the camera; the stage depth points away. let yaw = setup.camera.yaw; - let depth = solidcraft_geom::Vec3::new(yaw.sin(), yaw.cos(), 0.); - let horizontal = solidcraft_geom::Vec3::new(yaw.cos(), -yaw.sin(), 0.); + let depth = solidcore_record::Vec3::new(yaw.sin(), yaw.cos(), 0.); + let horizontal = solidcore_record::Vec3::new(yaw.cos(), -yaw.sin(), 0.); let extent = extent.max(1.0); // minimum one-mm stage envelope, never scales the subject let radius = extent * 0.5; let near = -2.5 * extent; @@ -204,17 +171,20 @@ pub(super) fn backdrop(s: &mut Session, params: &Value) -> Result { setup.stage = Stage::new(panels).map_err(|e| bad(command, e.to_string()))?; apply(&mut scene, &setup, command)?; let mut result = save(s, input.name, setup, command)?; - result["geometry_kind"] = json!(match input.kind { - BackdropKind::FloorWall => "finite_floor_and_wall", - BackdropKind::Cyclorama => "24_segment_polygonal_cyclorama", - }); - result["light_transport"] = - json!("nonemissive world-space stage; receives native lighting and casts reflections/shadows supported by the selected executor"); - result["camera_preserved"] = json!(true); - result["limitations"] = json!([ - "Finite background, not an infinite floor or a terrain mesh.", - "Cyclorama is an explicit 24-strip polygonal approximation, not a smooth CAD face.", - "No change to HDR, light energy, subject optics, pose or engineering properties." + result.geometry_kind = Some( + match input.kind { + BackdropKind::FloorWall => "finite_floor_and_wall", + BackdropKind::Cyclorama => "24_segment_polygonal_cyclorama", + } + .into(), + ); + result.light_transport = + Some("nonemissive world-space stage; receives native lighting and casts reflections/shadows supported by the selected executor".into()); + result.camera_preserved = Some(true); + result.limitations = Some(vec![ + "Finite background, not an infinite floor or a terrain mesh.".into(), + "Cyclorama is an explicit 24-strip polygonal approximation, not a smooth CAD face.".into(), + "No change to HDR, light energy, subject optics, pose or engineering properties.".into(), ]); - Ok(result) + reply(command, result) } diff --git a/crates/engine/src/cmd/render/surface_bindings.rs b/crates/engine/src/cmd/render/surface_bindings.rs index 9f2781b2e..f71a31dfd 100644 --- a/crates/engine/src/cmd/render/surface_bindings.rs +++ b/crates/engine/src/cmd/render/surface_bindings.rs @@ -3,12 +3,12 @@ use crate::{Result, Session, params::bad}; use serde::Deserialize; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{ render_resources::HdrId, render_settings::{RenderJob, RenderSetup}, render_surface::{BuiltinSurfaceSource, RenderBodyTarget, SavedSurface, SurfaceBindings}, }; -use solidcraft_geom::Vec3; use solidcraft_render::{ProductScene, job::textures::PlanarFrame}; use std::{collections::BTreeMap, sync::Arc}; @@ -79,7 +79,7 @@ pub(super) fn resolve(s: &Session, scene: &ProductScene, bindings: &SurfaceBindi return Ok(Vec::new()); } let identities = targets(s, command)?; - let world = s.world_state(); + let world = s.world_state()?; let world_by_name: BTreeMap<_, _> = world.bodies.iter().map(|body| (body.name.as_str(), body)).collect(); let visible: BTreeMap<_, _> = scene.meshes.iter().enumerate().map(|(i, body)| (body.name.as_str(), i)).collect(); let mut result = Vec::new(); @@ -147,7 +147,7 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result { if matches.next().is_some() { return Err(bad(command, "surface target is ambiguous")); } - let world = s.world_state(); + let world = s.world_state()?; let body = world.body(name).ok_or_else(|| bad(command, "surface target disappeared"))?; let inverse = solidcraft_doc::mat_inverse(&body.source_transform).ok_or_else(|| bad(command, "surface mapping transform is singular"))?; let frame: PlanarFrame = serde_json::from_value(prepared["texture"]["frame"].clone()).map_err(|e| bad(command, e.to_string()))?; diff --git a/crates/engine/src/cmd/render/textures.rs b/crates/engine/src/cmd/render/textures.rs index a527d9198..a02f163a9 100644 --- a/crates/engine/src/cmd/render/textures.rs +++ b/crates/engine/src/cmd/render/textures.rs @@ -89,7 +89,7 @@ pub(super) fn validate_targets(scene: &ProductScene, overrides: &[Override], com for x in [bounds.min.x, bounds.max.x] { for y in [bounds.min.y, bounds.max.y] { for z in [bounds.min.z, bounds.max.z] { - input.frame.uv(solidcraft_geom::Vec3::new(x, y, z)).map_err(|e| bad(command, e.to_string()))?; + input.frame.uv(solidcore_record::Vec3::new(x, y, z)).map_err(|e| bad(command, e.to_string()))?; } } } @@ -156,7 +156,7 @@ mod tests { color: [255; 3], opacity: 1., surface: None, - transmission: Some(solidcraft_render::transmission::Transmission::new(solidcraft_geom::Vec3::ZERO, Some(1.)).unwrap()), + transmission: Some(solidcraft_render::transmission::Transmission::new(solidcore_record::Vec3::ZERO, Some(1.)).unwrap()), faces: vec![], }], }; diff --git a/crates/engine/src/cmd/render/transmission.rs b/crates/engine/src/cmd/render/transmission.rs index 557003e10..bec310e97 100644 --- a/crates/engine/src/cmd/render/transmission.rs +++ b/crates/engine/src/cmd/render/transmission.rs @@ -2,7 +2,7 @@ //! Keep wire details here until the CPU contract is published. Never save them. use crate::{Result, params::bad}; use serde::Deserialize; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_render::{ ProductScene, surface::{OpaqueSurface, srgb8_to_linear}, diff --git a/crates/engine/src/cmd/render_ui.rs b/crates/engine/src/cmd/render_ui.rs index d6f4f28d2..261ee48d1 100644 --- a/crates/engine/src/cmd/render_ui.rs +++ b/crates/engine/src/cmd/render_ui.rs @@ -1,7 +1,10 @@ -//! Planned Render interactions, with explicit non-mutating refusals. +//! Transient Render view requests and explicit refusals for planned interactions. use super::CommandSpec; use crate::schema::render_lights::{MuteParams, SoloParams}; -use crate::schema::{TypedContract, output_schema_for, render_ui::CheckReport}; +use crate::schema::{ + TypedContract, output_schema_for, + render_ui::{BatchParams, BatchResult, CheckReport, CompareDivider, CompareParams, CompareSide, ResultIndex}, +}; use crate::{Result, Session, params::bad}; use serde::Deserialize; use serde_json::{Value, json}; @@ -33,19 +36,10 @@ fn mute(_: &mut crate::Session, params: &serde_json::Value) -> crate::Result { - CommandSpec::new($id, $label, |_, _| Err(crate::EngineError::Other(concat!("not supported yet: ", $reason).into()))) - .enabled(|_| Err(concat!("not supported yet: ", $reason).into())) - .planned("5493") - .noundo() - .doc_only() - .at($tab, $panel) - .icon($icon) - .params("No supported parameters. Always refuses without changing the design or history.") - }; -} +const RESULT_INDEX: TypedContract = TypedContract::new(); +const COMPARE: TypedContract = TypedContract::new(); +const DIVIDER: TypedContract = TypedContract::new(); +const BATCH: TypedContract = TypedContract::new(); const CHECK_REPORT: TypedContract = TypedContract::new(); @@ -57,6 +51,16 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .doc_only() .params("text: nonempty report, at most 65536 bytes. Validated clipboard request; headless echo only, never renders or edits a design."), + CommandSpec::new("render.result.select", "Select Render Result", crate::checked!("render.result.select", select_result)) + .icon("render_image").noundo().doc_only() + .enabled(results_ready) + .contract(&RESULT_INDEX).output(output_schema_for::) + .params("index: integer 0..7, oldest first; must be retained. Selects a completed result as transient per-document view state; echoes index."), + CommandSpec::new("render.result.discard", "Discard Render Result", crate::checked!("render.result.discard", discard_result)) + .icon("delete").noundo().doc_only() + .enabled(results_ready) + .contract(&RESULT_INDEX).output(output_schema_for::) + .params("index: integer 0..7, oldest first; must be retained. Drops only that transient result, selecting the newest remaining result if necessary; echoes index."), CommandSpec::new("render.output.size", "Set Render Output Size", output_size) .icon("settings") .noundo() @@ -88,8 +92,20 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo().doc_only().icon("render_scene").at("RENDER SCENE","LIGHTS") .contract(&MUTE).output(crate::schema::output_schema_for::) .params("id: kind:slot light address; mute:bool. Validates and echoes per-document UI view state, applied to live preview and captured render copies only. Never changes saved settings or history."), - waiting!("render.compare", "Compare Images", "RENDER", "RESULT", "compare", "retained image comparison"), - waiting!("render.batch", "Render All Shots", "RENDER", "BATCH", "render_image", "the saved-shot render queue"), + CommandSpec::new("render.compare", "Compare Images", crate::checked!("render.compare", compare)) + .icon("compare").noundo().doc_only().at("RENDER", "RESULT") + .enabled(results_ready) + .contract(&COMPARE).output(output_schema_for::) + .params("left, right: live or retained result index 0..7 (oldest first), distinct and retained; OR off:true. Validated per-document comparison view request; headless echo, no rendering or design/history change."), + CommandSpec::new("render.compare.divider", "Move Render Comparison Divider", crate::checked!("render.compare.divider", divider)) + .icon("compare").noundo().doc_only() + .contract(&DIVIDER).output(output_schema_for::) + .params("position: finite number, clamped to 0.05..0.95. Transient comparison divider request; headless echo only."), + CommandSpec::new("render.batch", "Render All Shots", crate::checked!("render.batch", batch)) + .icon("render_image").noundo().doc_only().at("RENDER", "BATCH") + .enabled(|s| s.render_batch_ready()) + .contract(&BATCH).output(output_schema_for::) + .params("request?: render.start parameters, shared across all saved shots except camera. Default: first saved setup in name order. Captures up to 32 shot cameras and queues sequentially through render.start; returns {queued:n}. Refuses active renders, no shots or stale geometry. render.status (also with {}) and the UI tick advance the queue; Cancel on the active job drops waiting shots. No design/history/revision change."), ]; fn copy_check(_: &mut Session, params: &Value) -> Result { @@ -100,6 +116,110 @@ fn copy_check(_: &mut Session, params: &Value) -> Result { Ok(json!({"text":report.text})) } +fn compare(s: &mut Session, params: &Value) -> Result { + let input: CompareParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare", e.to_string()))?; + match input { + CompareParams::Off(off) if off.off => { + s.render_jobs.set_comparison(None); + Ok(json!({"off":true})) + } + CompareParams::Pair(pair) => { + if pair.left == pair.right { + return Err(bad("render.compare", "comparison sides must differ")); + } + let results = s.render_retained_results()?; + for side in [pair.left, pair.right] { + if let CompareSide::Result(index) = side + && (index > 7 || results.get(index as usize).is_none()) + { + return Err(bad("render.compare", "retained result index is out of bounds")); + } + } + let resolve = |side| match side { + CompareSide::Live(_) => None, + CompareSide::Result(index) => results.get(index as usize).map(|result| result.frame.job), + }; + s.render_jobs.set_comparison(Some([resolve(pair.left), resolve(pair.right)])); + Ok(json!({"left":pair.left,"right":pair.right})) + } + _ => Err(bad("render.compare", "off must be true")), + } +} + +fn divider(_: &mut Session, params: &Value) -> Result { + let input: CompareDivider = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare.divider", e.to_string()))?; + if !input.position.is_finite() { + return Err(bad("render.compare.divider", "position must be finite")); + } + Ok(json!({"position":input.position.clamp(0.05,0.95)})) +} + +fn batch(s: &mut Session, params: &Value) -> Result { + let input: BatchParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.batch", e.to_string()))?; + s.render_batch_ready().map_err(|reason| bad("render.batch", reason))?; + if s.model.is_stale() { + return Err(bad("render.batch", "finish the modelling gesture before rendering shots")); + } + for name in s.doc.render.setups.keys() { + solidcraft_doc::render_settings::RenderSettings::validate_name(name).map_err(|error| bad("render.batch", error.to_string()))?; + } + let common = if let Some(request) = input.request { + Value::Object(request.into_iter().collect()) + } else { + let setup = s.doc.render.setups.values().next().ok_or_else(|| bad("render.batch", "no saved shots"))?; + json!({"settings":setup}) + }; + let mut request = common.as_object().cloned().ok_or_else(|| bad("render.batch", "request must be an object"))?; + let settings = if let Some(name) = request.get("setup") { + let name = name.as_str().ok_or_else(|| bad("render.batch", "setup must be a saved name"))?; + if request.contains_key("settings") { + return Err(bad("render.batch", "choose either setup or settings")); + } + s.doc.render.setups.get(name).cloned().ok_or_else(|| bad("render.batch", "unknown saved setup"))? + } else if let Some(settings) = request.get("settings") { + serde_json::from_value(settings.clone()).map_err(|e| bad("render.batch", e.to_string()))? + } else { + s.doc.render.setups.values().next().cloned().ok_or_else(|| bad("render.batch", "no saved shots"))? + }; + request.remove("setup"); + // A batch never replaces an active job; malformed replace values must still refuse. + if request.get("replace").is_some_and(|value| value != &json!(false)) { + return Err(bad("render.batch", "replace must be false or omitted")); + } + request.insert("settings".into(), json!(settings)); + let request = std::sync::Arc::new(Value::Object(request)); + let shots = s + .doc + .render + .setups + .iter() + .map(|(name, shot)| crate::render_jobs::BatchShot { name: name.clone(), camera: shot.camera, request: request.clone() }) + .collect(); + let queued = s.start_render_batch(shots)?; + Ok(json!({"queued":queued})) +} + +fn results_ready(s: &Session) -> std::result::Result<(), String> { + if s.render_jobs.has_results() { Ok(()) } else { Err("no completed render results are retained".into()) } +} + +fn indexed_result(s: &mut Session, params: &Value, command: &str, discard: bool) -> Result { + let input: ResultIndex = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + if input.index > 7 { + return Err(bad(command, "index must be in 0..7")); + } + s.render_jobs.result_index(input.index as usize, discard).map_err(crate::render_jobs::job_error)?; + Ok(json!({"index":input.index})) +} + +fn select_result(s: &mut Session, params: &Value) -> Result { + indexed_result(s, params, "render.result.select", false) +} + +fn discard_result(s: &mut Session, params: &Value) -> Result { + indexed_result(s, params, "render.result.discard", true) +} + #[cfg(test)] #[test] fn render_lights_remaining_planned_commands_refuse_without_mutation() { @@ -149,17 +269,21 @@ fn output_size(_: &mut Session, params: &Value) -> Result { struct ResultView { view: String, } -fn result_view(_: &mut Session, params: &Value) -> Result { +fn result_view(s: &mut Session, params: &Value) -> Result { let input: ResultView = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.view", e.to_string()))?; if !matches!(input.view.as_str(), "model" | "image" | "fit" | "actual") { return Err(bad("render.result.view", "view must be model, image, fit or actual")); } + if input.view == "model" { + s.render_jobs.set_comparison(None); + } Ok(json!({"view":input.view})) } -fn close_result(_: &mut Session, params: &Value) -> Result { +fn close_result(s: &mut Session, params: &Value) -> Result { if !params.as_object().is_some_and(|p| p.is_empty()) { return Err(bad("render.result.close", "expected no parameters")); } + s.render_jobs.set_comparison(None); Ok(json!({"view":"model"})) } @@ -210,3 +334,344 @@ fn output_sections_copy_report_validates_without_design_history_or_job_changes() assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); } + +#[cfg(test)] +fn complete_result(s: &mut Session, shot: &str) -> solidcraft_render::job::JobId { + let reply = s.execute("render.start", &json!({"setup":shot})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = s.render_job_host().unwrap().clone(); + for _ in 0..1000 { + host.pump(4096).unwrap(); + if s.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" { + return job; + } + } + panic!("bounded result fixture did not complete"); +} + +#[cfg(test)] +#[test] +fn retained_results_cap_order_metadata_and_selection_never_edit_a_design() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16,"height":8}})).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":32}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.redo.len(), 1, "view commands must preserve an available redo step"); + let document = s.doc.clone(); + let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()); + let jobs: Vec<_> = (0..10).map(|_| complete_result(&mut s, "Hero")).collect(); + let results = s.render_retained_results().unwrap(); + assert_eq!(results.len(), 8); + assert_eq!(results.iter().map(|result| result.frame.job).collect::>(), jobs[2..]); + for result in &results { + assert_eq!(result.shot.as_deref(), Some("Hero")); + assert_eq!((result.frame.width, result.frame.height), (16, 8)); + assert!(result.seconds.is_finite() && result.seconds >= 0.0); + assert_eq!(result.frame.scene_generation, s.revision); + assert!(!result.stale); + } + assert!(s.render_job_handle(jobs[0]).is_err()); + assert!(s.render_job_handle(jobs[1]).is_err()); + assert_eq!(s.render_selected_result(), Some(jobs[9])); + assert_eq!(s.execute("render.result.select", &json!({"index":0})).unwrap(), json!({"index":0})); + assert_eq!(s.render_selected_result(), Some(jobs[2])); + assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(jobs[2])); + assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(jobs[2])); + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + assert_eq!(s.render_selected_result(), Some(jobs[9])); + assert!(s.render_job_handle(jobs[2]).is_err()); + s.execute("render.result.select", &json!({"index":2})).unwrap(); + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + assert_eq!(s.render_selected_result(), Some(jobs[5]), "discarding an earlier row preserves the selected identity"); + while !s.render_retained_results().unwrap().is_empty() { + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + } + assert!(s.render_selected_result().is_none()); + assert!(s.execute("render.result.copy", &json!({})).is_err()); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn retained_result_requests_refuse_hostile_and_missing_indices_atomically() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Front","set":{"width":8,"height":8}})).unwrap(); + let job = complete_result(&mut s, "Front"); + let document = s.doc.clone(); + let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()); + let retained = s.render_job_host().unwrap().admitted_bytes(); + for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] { + s.param_check = mode; + for command in ["render.result.select", "render.result.discard"] { + let spec = super::find_command(command).unwrap(); + assert!(spec.contract.is_some() && spec.output.is_some()); + for request in [ + json!(null), + json!([]), + json!({}), + json!({"index":-1}), + json!({"index":0.5}), + json!({"index":1e300}), + json!({"index":u64::MAX}), + json!({"index":"0"}), + json!({"index":null}), + json!({"index":true}), + json!({"index":1}), + json!({"index":8}), + json!({"index":0,"extra":true}), + ] { + assert!(s.execute(command, &request).is_err(), "{command}: {request}"); + assert_eq!(s.render_retained_results().unwrap().len(), 1); + assert_eq!(s.render_selected_result(), Some(job)); + assert_eq!(s.render_job_host().unwrap().admitted_bytes(), retained); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty())); + } + } + } + s.execute("render.settings.set", &json!({"name":"Front","set":{"width":16}})).unwrap(); + assert!(s.render_retained_results().unwrap()[0].stale); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.render_retained_results().unwrap()[0].stale, "undo does not recapture pixels"); + assert_eq!(s.render_retained_results().unwrap()[0].frame.scene_generation, before.2); + let mut other = Session::default(); + assert!(other.render_retained_results().unwrap().is_empty()); + assert!(other.execute("render.result.select", &json!({"index":0})).is_err()); + assert!(other.render_job_handle(job).is_err()); +} + +#[cfg(test)] +#[test] +fn render_results_compare_validates_both_sides_and_clamps_only_finite_dividers_without_mutation() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":8,"height":8}})).unwrap(); + complete_result(&mut s, "Hero"); + complete_result(&mut s, "Hero"); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let selected = s.selection.clone(); + for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] { + s.param_check = mode; + for request in [json!({"left":"live","right":0}), json!({"left":1,"right":0}), json!({"left":0,"right":"live"}), json!({"off":true})] { + assert_eq!(s.execute("render.compare", &request).unwrap(), request); + } + for request in [ + json!({}), + json!([]), + json!({"off":false}), + json!({"off":true,"left":0}), + json!({"left":"live","right":"live"}), + json!({"left":0,"right":0}), + json!({"left":"unknown","right":0}), + json!({"left":"live","right":2}), + json!({"left":8,"right":0}), + json!({"left":-1,"right":0}), + json!({"left":0.5,"right":0}), + json!({"left":1e300,"right":"live"}), + json!({"left":null,"right":0}), + json!({"left":"0","right":1}), + json!({"left":true,"right":0}), + json!({"left":"live","right":0,"extra":true}), + ] { + assert!(s.execute("render.compare", &request).is_err(), "{request}"); + } + for (position, expected) in [(-1e300, 0.05), (0.0, 0.05), (0.25, 0.25), (1.0, 0.95), (1e300, 0.95)] { + assert_eq!(s.execute("render.compare.divider", &json!({"position":position})).unwrap(), json!({"position":expected})); + } + for request in [json!({}), json!({"position":null}), json!({"position":"NaN"}), json!({"position":true}), json!({"position":0.5,"extra":1})] { + assert!(s.execute("render.compare.divider", &request).is_err()); + } + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + assert_eq!(s.selection, selected); + assert_eq!(s.render_retained_results().unwrap().len(), 2); + } + let mut empty = Session::default(); + assert!(empty.execute("render.compare", &json!({"left":"live","right":0})).is_err()); + assert!(empty.execute("render.compare", &json!({"off":true})).is_err()); + for id in ["render.compare", "render.compare.divider", "render.batch"] { + let command = super::find_command(id).unwrap(); + assert!(command.contract.is_some() && command.output.is_some() && command.planned.is_none()); + assert!(!command.undoable && !command.reads_model); + } +} + +#[cfg(test)] +fn batch_fixture(count: usize) -> Session { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + for index in 0..count { + let camera = solidcraft_render::Camera { yaw: index as f64 * 0.2, roll: index as f64 * 0.01, ..Default::default() }; + s.execute("render.settings.set", &json!({"name":format!("Shot {index:02}"),"set":{"camera":camera,"width":8+index,"height":8}})).unwrap(); + } + s +} + +#[cfg(test)] +#[test] +fn render_results_batch_is_sequential_uses_snapshot_cameras_and_one_setup_without_design_or_history_changes() { + let mut s = batch_fixture(3); + s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let cameras: Vec<_> = s.doc.render.setups.values().map(|setup| setup.camera).collect(); + s.param_check = crate::schema::ParamCheck::Strict; + assert_eq!( + s.execute("render.batch", &json!({"request":{"settings":{"width":12,"height":10,"background":[7,8,9]}}})).unwrap(), + json!({"queued":3}) + ); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 2)); + assert!(s.execute("render.batch", &json!({})).is_err()); + let host = s.render_job_host().unwrap().clone(); + let mut jobs = Vec::new(); + for (index, camera) in cameras.iter().enumerate() { + let queue = s.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 2 - index)); + let job = queue.job.unwrap(); + let status = s.render_job_handle(job).unwrap().status().unwrap(); + assert_eq!(status.request.camera, *camera); + assert_eq!((status.request.width, status.request.height, status.request.background), (12, 10, [7, 8, 9])); + assert_eq!(queue.shot, Some(format!("Shot {index:02}"))); + jobs.push(job); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + let reply = s.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(reply["progress"]["phase"], "completed"); + } + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().job.is_none()); + let results = s.render_retained_results().unwrap(); + assert_eq!(results.iter().map(|result| result.frame.job).collect::>(), jobs); + assert_eq!(results.iter().map(|result| result.shot.clone().unwrap()).collect::>(), ["Shot 00", "Shot 01", "Shot 02"]); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn render_results_batch_caps_at_32_and_cancel_discards_every_waiting_shot() { + let mut s = batch_fixture(32); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + assert_eq!(s.execute("render.batch", &json!({})).unwrap(), json!({"queued":32})); + let queue = s.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 31)); + let job = queue.job.unwrap(); + assert!(s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).is_err()); + s.execute("render.cancel", &json!({})).unwrap(); + assert_eq!(s.render_queue_state().waiting, 0); + assert!(s.render_queue_state().job.is_none()); + s.render_job_host().unwrap().pump(4096).unwrap(); + assert!(s.render_job_handle(job).unwrap().frame().unwrap().is_none()); + for _ in 0..3 { + assert_eq!(s.execute("render.status", &json!({})).unwrap()["queue"]["waiting"], 0); + } + assert!(s.render_retained_results().unwrap().is_empty()); + let next = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + assert_eq!(next["job"]["serial"], 2, "Cancel must not start any waiting shot"); + s.execute("render.cancel", &json!({"job":next["job"]})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut s.doc).render).setups.insert("Over limit".into(), Default::default()); + assert!(s.execute("render.batch", &json!({})).unwrap_err().to_string().contains("32")); + assert_eq!(s.render_queue_state().waiting, 0); +} + +#[cfg(test)] +#[test] +fn render_results_batch_refuses_missing_shots_busy_hostile_and_failed_requests_without_queuing() { + let mut empty = batch_fixture(0); + assert!(empty.execute("render.batch", &json!({})).is_err()); + let mut s = batch_fixture(2); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + for request in [ + json!([]), + json!({"request":1e300}), + json!({"request":[]}), + json!({"request":{"bogus":true}}), + json!({"request":{"replace":true}}), + json!({"request":{"settings":{"width":0}}}), + json!({"extra":true}), + ] { + assert!(s.execute("render.batch", &request).is_err(), "{request}"); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().job.is_none()); + } + let job = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap()["job"].clone(); + assert!(s.execute("render.batch", &json!({})).is_err()); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 0)); + s.execute("render.cancel", &json!({"job":job})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + s.set_render_job_host(None).unwrap(); + assert!(s.execute("render.batch", &json!({})).is_err()); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().error.is_some()); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn render_results_batch_cameras_and_common_setup_are_captured_before_later_shot_edits() { + let mut s = batch_fixture(2); + let original = s.doc.render.setups.get("Shot 01").unwrap().camera; + s.execute("render.batch", &json!({"request":{"setup":"Shot 00"}})).unwrap(); + let first = s.render_queue_state().job.unwrap(); + let changed = solidcraft_render::Camera { yaw: 2.0, ..Default::default() }; + s.execute("render.settings.set", &json!({"name":"Shot 01","set":{"camera":changed}})).unwrap(); + s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + let host = s.render_job_host().unwrap().clone(); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + let reply = s.execute("render.status", &json!({})).unwrap(); + let next: solidcraft_render::job::JobId = serde_json::from_value(reply["queue"]["job"].clone()).unwrap(); + assert_ne!(next, first); + let request = s.render_job_handle(next).unwrap().status().unwrap().request; + assert_eq!(request.camera, original); + assert_eq!(request.width, 8); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); + s.execute("render.cancel", &json!({"job":next})).unwrap(); +} + +#[cfg(test)] +#[test] +fn render_results_compare_keeps_copy_on_the_visible_result_until_a_source_is_evicted() { + let mut s = batch_fixture(1); + let first = complete_result(&mut s, "Shot 00"); + complete_result(&mut s, "Shot 00"); + s.execute("render.compare", &json!({"left":"live","right":0})).unwrap(); + assert_eq!(s.render_comparison(), Some([None, Some(first)])); + assert_eq!(s.render_selected_result(), Some(first)); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + let mut newest = first; + for index in 0..7 { + newest = complete_result(&mut s, "Shot 00"); + if index < 6 { + assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(first)); + assert_eq!(s.render_comparison(), Some([None, Some(first)])); + } + } + assert!(s.render_comparison().is_none()); + assert_eq!(s.render_selected_result(), Some(newest)); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); +} diff --git a/crates/engine/src/cmd/revolve_convention_tests.rs b/crates/engine/src/cmd/revolve_convention_tests.rs index a41ff7718..3a395f633 100644 --- a/crates/engine/src/cmd/revolve_convention_tests.rs +++ b/crates/engine/src/cmd/revolve_convention_tests.rs @@ -2,8 +2,9 @@ use crate::Session; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::{Document, FeatureKind, RevolveConvention}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI, SQRT_2}; fn run(s: &mut Session, cmd: &str, p: Value) -> Value { @@ -31,11 +32,16 @@ fn check_centered(s: &Session, opposed: bool) { let volume: f64 = state.bodies.iter().map(|mb| solidcraft_kernel::measure(&mb.body).unwrap().volume).sum(); assert!((volume - expected).abs() < 0.03, "{volume} vs {expected}"); for sign in if opposed { vec![1.0, -1.0] } else { vec![1.0] } { - let body = &state.bodies.iter().find(|mb| mb.body.contains(Vec3::new(sign * 3.0, 5.0, 0.0))).unwrap().body; - assert!(!body.contains(Vec3::new(0.0, 5.0, 3.0))); - assert!(body.contains(Vec3::new(sign * 3.0 * (PI / 6.0).cos(), 5.0, 1.5))); - assert!(body.contains(Vec3::new(sign * 3.0 * (PI / 6.0).cos(), 5.0, -1.5))); - let bounds = body.tessellate(1e-4).unwrap().bounds(); + let body = &state + .bodies + .iter() + .find(|mb| mb.body.classify_point(Vec3::new(sign * 3.0, 5.0, 0.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + .unwrap() + .body; + assert_eq!(body.classify_point(Vec3::new(0.0, 5.0, 3.0)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(sign * 3.0 * (PI / 6.0).cos(), 5.0, 1.5)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(sign * 3.0 * (PI / 6.0).cos(), 5.0, -1.5)).unwrap(), solidcraft_kernel::PointClass::Inside); + let bounds = body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().bounds(); assert!((bounds.min.z + 2.0 * SQRT_2).abs() < 1e-6, "{bounds:?}"); assert!((bounds.max.z - 2.0 * SQRT_2).abs() < 1e-6, "{bounds:?}"); let inner_x = if sign > 0.0 { bounds.min.x } else { -bounds.max.x }; @@ -80,13 +86,13 @@ fn two_sided_revolves_use_the_canonical_negative_and_positive_limits() { turn(&mut s, sign, json!({"direction":"positive","angle":"60 deg","angle2":"30 deg"})); let state = s.model.state(); let body = &state.bodies[0].body; - let bounds = body.tessellate(1e-4).unwrap().bounds(); + let bounds = body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().bounds(); assert!((bounds.min.x - 1.0).abs() < 1e-6, "{bounds:?}"); assert!((bounds.max.x - 4.0).abs() < 1e-4); assert!((bounds.min.z + 2.0).abs() < 1e-6); assert!((bounds.max.z - 2.0 * 3.0f64.sqrt()).abs() < 1e-6); - assert!(body.contains(Vec3::new(3.0, 5.0, 0.0))); - assert!(!body.contains(Vec3::new(0.0, 5.0, 3.0))); + assert_eq!(body.classify_point(Vec3::new(3.0, 5.0, 0.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(0.0, 5.0, 3.0)).unwrap(), solidcraft_kernel::PointClass::Outside); assert!((solidcraft_kernel::measure(body).unwrap().volume - 30.0 * PI).abs() < 0.03); } } @@ -107,9 +113,9 @@ fn legacy_missing_convention_keeps_geometry_through_edit_redefine_undo_and_reope assert_eq!(s.doc.find_feature("Turn").unwrap().kind, original); let state = s.model.state(); let body = &state.bodies[0].body; - assert!(body.contains(Vec3::new(0.0, 5.0, 3.0))); - assert!(!body.contains(Vec3::new(3.0, 5.0, 0.0))); - let bounds = body.tessellate(1e-4).unwrap().bounds(); + assert_eq!(body.classify_point(Vec3::new(0.0, 5.0, 3.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(3.0, 5.0, 0.0)).unwrap(), solidcraft_kernel::PointClass::Outside); + let bounds = body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().bounds(); assert!((bounds.min.x + 2.0 * SQRT_2).abs() < 1e-6); assert!((bounds.max.x - 2.0 * SQRT_2).abs() < 1e-6); assert!((bounds.min.z - SQRT_2).abs() < 1e-6); @@ -118,8 +124,8 @@ fn legacy_missing_convention_keeps_geometry_through_edit_redefine_undo_and_reope let angle_input = s.doc.find_feature("Turn").unwrap().param_names[0].clone(); run(&mut s, "parameters.change", json!({"name":angle_input,"expression":"60 deg"})); let changed = s.model.state(); - assert!(changed.bodies[0].body.contains(Vec3::new(1.5, 5.0, 3.0 * 3.0f64.sqrt() / 2.0))); - assert!(!changed.bodies[0].body.contains(Vec3::new(3.0, 5.0, 0.0))); + assert_eq!(changed.bodies[0].body.classify_point(Vec3::new(1.5, 5.0, 3.0 * 3.0f64.sqrt() / 2.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(changed.bodies[0].body.classify_point(Vec3::new(3.0, 5.0, 0.0)).unwrap(), solidcraft_kernel::PointClass::Outside); run(&mut s, "edit.undo", json!({})); check(&s); run(&mut s, "timeline.edit", json!({"feature":"Turn","set":{"angle":"90 deg"}})); @@ -175,11 +181,11 @@ fn symmetric_revolve_preserves_a_translated_rotated_sketch_frame() { run(&mut s, "solid.revolve", json!({"sketch":"Profile","axis":{"origin":[10,20,30],"dir":[-1,0,0]},"angle":"90 deg","direction":"symmetric"})); let state = s.model.state(); let body = &state.bodies[0].body; - let bounds = body.tessellate(1e-4).unwrap().bounds(); + let bounds = body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().bounds(); assert!(bounds.min.dist(Vec3::new(10.0, 20.0 - 2.0 * SQRT_2, 30.0 + SQRT_2)) < 1e-6, "{bounds:?}"); assert!(bounds.max.dist(Vec3::new(20.0, 20.0 + 2.0 * SQRT_2, 34.0)) < 1e-4, "{bounds:?}"); - assert!(body.contains(Vec3::new(15.0, 20.0, 33.0))); - assert!(!body.contains(Vec3::new(15.0, 23.0, 30.0))); + assert_eq!(body.classify_point(Vec3::new(15.0, 20.0, 33.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(15.0, 23.0, 30.0)).unwrap(), solidcraft_kernel::PointClass::Outside); assert!((solidcraft_kernel::measure(body).unwrap().volume - 30.0 * PI).abs() < 0.03); } @@ -193,7 +199,7 @@ fn copied_revolves_keep_their_convention_and_angular_material() { run(&mut s, "timeline.paste", json!({"translate":[0,20,0]})); let state = s.model.state(); let probe = if convention == "sketch_normal" { Vec3::new(3.0, 25.0, 0.0) } else { Vec3::new(0.0, 25.0, 3.0) }; - assert!(state.bodies.iter().any(|mb| mb.body.contains(probe))); + assert!(state.bodies.iter().any(|mb| mb.body.classify_point(probe).unwrap() == solidcraft_kernel::PointClass::Inside)); let modes: Vec<_> = s .doc .features @@ -203,7 +209,7 @@ fn copied_revolves_keep_their_convention_and_angular_material() { assert_eq!(modes.len(), 2); assert_eq!(modes[0], modes[1]); let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); - assert!(reopened.model.state().bodies.iter().any(|mb| mb.body.contains(probe))); + assert!(reopened.model.state().bodies.iter().any(|mb| mb.body.classify_point(probe).unwrap() == solidcraft_kernel::PointClass::Inside)); } } @@ -222,7 +228,7 @@ fn centered_coplanar_cut_uses_the_actual_angular_interval() { assert!((total - expected).abs() < 0.05, "{volumes:?}: total{total}, expected{expected}"); assert_eq!(state.bodies.len(), 2); assert!(volumes.iter().all(|v| (*v - expected / 2.0).abs() < 0.025)); - let contains = |p| state.bodies.iter().any(|mb| mb.body.contains(p)); + let contains = |p| state.bodies.iter().any(|mb| mb.body.classify_point(p).unwrap() == solidcraft_kernel::PointClass::Inside); assert!(!contains(Vec3::new(3.0, 5.0, 0.0))); assert!(contains(Vec3::new(3.0, 5.0, 3.5))); assert!(contains(Vec3::new(3.0, 5.0, -3.5))); @@ -238,8 +244,11 @@ fn one_sided_and_full_revolves_keep_the_existing_material() { turn(&mut s, sign, json!({"angle":angle,"direction":"positive","convention":convention})); let state = s.model.state(); let body = &state.bodies[0].body; - assert!(body.contains(Vec3::new(3.0 / SQRT_2, 5.0, 3.0 / SQRT_2))); - assert_eq!(body.contains(Vec3::new(-3.0 / SQRT_2, 5.0, -3.0 / SQRT_2)), angle == "360 deg"); + assert_eq!(body.classify_point(Vec3::new(3.0 / SQRT_2, 5.0, 3.0 / SQRT_2)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!( + body.classify_point(Vec3::new(-3.0 / SQRT_2, 5.0, -3.0 / SQRT_2)).unwrap() == solidcraft_kernel::PointClass::Inside, + angle == "360 deg" + ); let expected = if angle == "360 deg" { 120.0 * PI } else { 30.0 * PI }; assert!((solidcraft_kernel::measure(body).unwrap().volume - expected).abs() < 0.08); } @@ -258,10 +267,31 @@ fn point_targets_use_each_profiles_canonical_axis_for_both_axis_signs() { let expected = 30.0 * PI * if opposed { 2.0 } else { 1.0 }; let volume: f64 = state.bodies.iter().map(|mb| solidcraft_kernel::measure(&mb.body).unwrap().volume).sum(); assert!((volume - expected).abs() < 0.05, "{volume}"); - assert!(state.bodies.iter().any(|mb| mb.body.contains(Vec3::new(3.0 / SQRT_2, 5.0, 3.0 / SQRT_2)))); - assert!(!state.bodies.iter().any(|mb| mb.body.contains(Vec3::new(3.0 / SQRT_2, 5.0, -3.0 / SQRT_2)))); - assert_eq!(state.bodies.iter().any(|mb| mb.body.contains(Vec3::new(-3.0 / SQRT_2, 5.0, 3.0 / SQRT_2))), opposed); - assert!(!state.bodies.iter().any(|mb| mb.body.contains(Vec3::new(-3.0 / SQRT_2, 5.0, -3.0 / SQRT_2)))); + assert!( + state + .bodies + .iter() + .any(|mb| mb.body.classify_point(Vec3::new(3.0 / SQRT_2, 5.0, 3.0 / SQRT_2)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); + assert!( + !state + .bodies + .iter() + .any(|mb| mb.body.classify_point(Vec3::new(3.0 / SQRT_2, 5.0, -3.0 / SQRT_2)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); + assert_eq!( + state + .bodies + .iter() + .any(|mb| mb.body.classify_point(Vec3::new(-3.0 / SQRT_2, 5.0, 3.0 / SQRT_2)).unwrap() == solidcraft_kernel::PointClass::Inside), + opposed + ); + assert!( + !state + .bodies + .iter() + .any(|mb| mb.body.classify_point(Vec3::new(-3.0 / SQRT_2, 5.0, -3.0 / SQRT_2)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); } } } @@ -295,9 +325,15 @@ fn curved_targets_keep_only_the_material_before_the_post_for_both_axis_signs() { assert_eq!(arcs.len(), if opposed { 2 } else { 1 }); for side in if opposed { vec![1.0, -1.0] } else { vec![1.0] } { let probe = Vec3::new(side * 12.0 * (PI / 6.0).cos(), 6.0, -2.5); - let arc = &arcs.iter().find(|mb| mb.body.contains(probe)).unwrap().body; - assert!(!arc.contains(Vec3::new(-side * 12.0 * (PI / 6.0).cos(), 6.0, -2.5))); - assert!(!arc.contains(Vec3::new(side * 12.0 * (PI / 6.0).cos(), -6.0, -2.5))); + let arc = &arcs.iter().find(|mb| mb.body.classify_point(probe).unwrap() == solidcraft_kernel::PointClass::Inside).unwrap().body; + assert_eq!( + arc.classify_point(Vec3::new(-side * 12.0 * (PI / 6.0).cos(), 6.0, -2.5)).unwrap(), + solidcraft_kernel::PointClass::Outside + ); + assert_eq!( + arc.classify_point(Vec3::new(side * 12.0 * (PI / 6.0).cos(), -6.0, -2.5)).unwrap(), + solidcraft_kernel::PointClass::Outside + ); let full = PI * (225.0 - 100.0) * 5.0; let angle = solidcraft_kernel::measure(arc).unwrap().volume / full * 360.0; assert!(angle > 60.0 && angle < 90.0, "{angle}"); diff --git a/crates/engine/src/cmd/script.rs b/crates/engine/src/cmd/script.rs index d67c33095..24a4a13dc 100644 --- a/crates/engine/src/cmd/script.rs +++ b/crates/engine/src/cmd/script.rs @@ -21,7 +21,7 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("timeline.export_script", "Export Command Script", export_script).icon("export").noundo().doc_only().params( "path?: write the script to this file → script: {commands: [...]} that rebuilds the design (solidcraft-cli eval/run), \ - steps, omitted: what the script leaves out (appearances, folders, views, configurations); components and assemblies \ + steps, omitted: what the script leaves out (appearances, folders, views, configurations, print-face assignments); components and assemblies \ are not supported yet", ), ]; @@ -36,6 +36,19 @@ fn add(s: &mut Session, p: &Value) -> Result { .and_then(Value::as_object) .ok_or_else(|| bad(cmd, "`feature` must be a feature object, as a design file or timeline.inspect has it"))?; let mut raw = raw.clone(); + if let Some(Value::Object(def)) = raw.remove("definition") { + for (k, v) in def { + raw.entry(k).or_insert(v); + } + } + for meta in ["omitted", "inputs", "error", "warning", "boolean_diagnostics", "rolled_back", "type_name"] { + raw.remove(meta); + } + if let Some(kind_str) = raw.get("type").and_then(Value::as_str) + && let Some(canonical) = FeatureKind::type_name_to_kind_key(kind_str) + { + raw.insert("type".into(), json!(canonical)); + } resolve_legacy_names(&mut raw, &s.doc); let feature = recorded_feature(cmd, &raw)?; let params = step_params(cmd, p.get("params"))?; @@ -198,6 +211,7 @@ pub(crate) fn script_steps(doc: &Document) -> Result<(Vec, Vec)> (doc.configs.is_empty(), "configurations"), (doc.canvases.is_empty(), "canvases (reference images)"), (doc.point_clouds.is_empty(), "point clouds"), + (doc.print_faces.is_empty(), "print-face assignments (body.print_face)"), (doc.named_views.is_empty(), "named views"), (doc.browser_groups.is_empty() && doc.browser_order.is_empty(), "Browser folders and order"), (doc.timeline_groups.is_empty(), "timeline folders"), diff --git a/crates/engine/src/cmd/script_tests.rs b/crates/engine/src/cmd/script_tests.rs index 1528d6174..2952e10cc 100644 --- a/crates/engine/src/cmd/script_tests.rs +++ b/crates/engine/src/cmd/script_tests.rs @@ -103,12 +103,13 @@ fn ids_names_suppression_marker_and_failures_survive() { run(&mut s, "parameters.add", json!({"name": "twice_depth", "expression": format!("{depth} * 2")})); run(&mut s, "parameters.comment", json!({"name": depth, "comment": "plate depth"})); run(&mut s, "parameters.favorite", json!({"name": depth})); - // A fillet that a parameter change makes too big fails, and the design keeps it. + // A fillet that a parameter change makes impossible (a radius below zero) fails, and the + // design keeps it. (A convex round wider than its faces is built now, by subtraction.) run(&mut s, "parameters.add", json!({"name": "r", "expression": "1 mm"})); // Pick only the plate's edge, clear of the overlapping box's edge. run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": "r"})); let fillet = s.doc.features.last().unwrap().id; - run(&mut s, "parameters.change", json!({"name": "r", "expression": "50 mm"})); + run(&mut s, "parameters.change", json!({"name": "r", "expression": "-1 mm"})); assert!(s.model.result(fillet).and_then(|r| r.error.clone()).is_some(), "the fillet fails"); run(&mut s, "timeline.rollback", json!({"position": 3})); let mut t = replay(&script(&mut s)); @@ -170,6 +171,25 @@ fn what_the_script_leaves_out_is_listed_and_components_are_refused() { assert!(e.contains("not supported yet"), "{e}"); } +#[test] +fn omitted_print_faces_are_reported_without_changing_the_design() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})); + assert_eq!(run(&mut s, "timeline.export_script", json!({}))["omitted"], json!([])); + + run(&mut s, "body.print_face", json!({"body": "Block", "point": [10, 5, 0]})); + let before = (*s.doc).clone(); + let r = run(&mut s, "timeline.export_script", json!({})); + assert_eq!(r["omitted"], json!(["print-face assignments (body.print_face)"])); + assert_eq!(*s.doc, before, "export must keep the saved print-face assignment"); + let mut t = replay(&r["script"]); + assert!(t.doc.print_faces.is_empty(), "the reported omission matches the replay"); + same(&mut s, &mut t); + + run(&mut s, "body.print_face", json!({"body": "Block"})); + assert_eq!(run(&mut s, "timeline.export_script", json!({}))["omitted"], json!([])); +} + #[test] fn a_recorded_feature_that_does_not_fit_is_refused_and_changes_nothing() { let mut s = Session::default(); @@ -224,6 +244,34 @@ fn a_recorded_feature_that_does_not_fit_is_refused_and_changes_nothing() { assert!(s.doc.feature(r["feature"].as_u64().unwrap()).is_some_and(|f| !f.param_names.is_empty()), "its inputs get parameter names"); } +/// #10748: `timeline.inspect` reports a feature's design variant name in `type` and display name +/// in `type_name`; `timeline.add` accepts `timeline.inspect` results and inspect type names. +#[test] +fn timeline_add_accepts_inspect_result_and_type_names() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 5, "name": "Block"})); + let mut inspected = run(&mut s, "timeline.inspect", json!({"feature": "Block"})); + assert_eq!(inspected["type"], "box", "inspect type is the design file variant name"); + assert_eq!(inspected["type_name"], "BoxFeature", "inspect type_name is the display type"); + + // 1. timeline.add accepts the full inspected object directly in a new session + let mut s2 = Session::default(); + let added = run(&mut s2, "timeline.add", json!({"feature": inspected.clone()})); + assert!(added["error"].is_null(), "{added}"); + assert_eq!(s2.doc.features.len(), 1); + + // 2. timeline.add with id 0 allocates a new id in the current session + inspected["id"] = json!(0); + let added2 = run(&mut s, "timeline.add", json!({"feature": inspected})); + assert!(added2["error"].is_null(), "{added2}"); + assert_eq!(s.doc.features.len(), 2); + + // 3. timeline.add accepts the inspect type name (e.g. BoxFeature, HoleFeature) + let added_by_type_name = + run(&mut s, "timeline.add", json!({"feature": {"type": "BoxFeature", "length": "5", "width": "5", "height": "5", "corner": [50, 0, 0]}})); + assert!(added_by_type_name["error"].is_null(), "{added_by_type_name}"); +} + #[test] fn the_script_is_written_to_a_file_that_replays() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/section.rs b/crates/engine/src/cmd/section.rs index 80cc6d62d..54dcd9736 100644 --- a/crates/engine/src/cmd/section.rs +++ b/crates/engine/src/cmd/section.rs @@ -1,15 +1,20 @@ //! Section Analysis: a view-only cut through the model by a plane (what is on the plane's //! positive side is hidden). It changes no geometry and is not an undo step. -use serde_json::{Value, json}; -use solidcraft_geom::{Plane, Vec3}; +use serde_json::Value; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::prelude::*; use super::CommandSpec; use crate::params::{bad, bool_, expr, vec3}; +use crate::schema::{TypedContract, output_schema_for, section as contract}; use crate::{Result, Session}; +const SECTION: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = - &[CommandSpec::new("inspect.section", "Section Analysis", section).at("SOLID", "INSPECT").icon("section").noundo().params( + &[CommandSpec::new("inspect.section", "Section Analysis", crate::checked!("inspect.section", section)) + .contract(&SECTION).output(output_schema_for::) + .at("SOLID", "INSPECT").icon("section").noundo().params( "plane: XY|XZ|YZ | construction plane name or id | {origin, normal}; offset?: expr along the plane's normal (XY: +Z, XZ: +Y, YZ: +X); \ at?: expr, the cut's world coordinate on the named plane's axis (XY: Z, XZ: Y, YZ: X), instead of offset; \ flip?: bool; hatch?: bool (hatch the cut faces, in each body's colour; default true); or clear: true. Returns the cut's origin and normal, and for a named plane its axis and at", @@ -20,8 +25,8 @@ fn section(s: &mut Session, p: &Value) -> Result { if bool_(p, "clear").unwrap_or(false) { s.section = None; s.status_slot(crate::status_items::StatusId::Section, false); - s.revision += 1; - return Ok(json!({"section": null})); + s.refresh_display(); + return serde_json::to_value(contract::SectionResult { section: None, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string())); } // A named plane's world axis: which component of a point lies along its normal. let (origin, normal, axis) = match p.get("plane") { @@ -78,13 +83,15 @@ fn section(s: &mut Session, p: &Value) -> Result { s.section_hatch = bool_(p, "hatch").unwrap_or(true); s.status_slot(crate::status_items::StatusId::Section, true); s.status_activated(crate::status_items::StatusId::Section); - s.revision += 1; - let mut section = json!({"origin": origin, "normal": normal, "hatch": s.section_hatch}); - if let Some(i) = axis { - section["axis"] = json!(["X", "Y", "Z"].get(i).copied().unwrap_or("?")); - section["at"] = json!(axis_component(origin, i)); - } - Ok(json!({"section": section})) + s.refresh_display(); + let section = contract::Section { + origin: [origin.x, origin.y, origin.z], + normal: [normal.x, normal.y, normal.z], + hatch: s.section_hatch, + axis: axis.and_then(|i| ["X", "Y", "Z"].get(i).map(|v| (*v).to_owned())), + at: axis.map(|i| axis_component(origin, i)), + }; + serde_json::to_value(contract::SectionResult { section: Some(section), param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string())) } fn axis_component(v: Vec3, i: usize) -> f64 { diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index dcb986257..5cdce0e7a 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -2,18 +2,23 @@ //! the flat pattern (outline, bend lines, bend table) and its DXF export. use serde_json::{Value, json}; +use solidcore_record::{Vec2, Vec3}; use solidcraft_doc::expr::Kind; use solidcraft_doc::sheet::{self, SheetBody, SheetRule}; use solidcraft_doc::{BodyName, SketchId}; use solidcraft_doc::{FacePick, Position}; use solidcraft_doc::{FeatureKind, FlangeEdge}; -use solidcraft_geom::{Aabb2, Ring, Vec2, Vec3}; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Aabb2, Ring}; use super::CommandSpec; use super::features::{add_feature, check_expr, feature_sketch, profiles, sketch_id}; use crate::params::{bad, bool_, expr, expr_problem, req_expr, str_, string_list, vec3}; use crate::schema::features::FeatureResult; -use crate::schema::sheet::{ConvertParams, FlangeParams, FoldParams, HemParams, PerforateParams, UnfoldParams}; +use crate::schema::sheet::{ + ConvertParams, FlangeParams, FoldParams, HemParams, ListedRule, ManageRulesParams, ManageRulesResult, PerforateParams, RuleFeatureError, + RuleReply, RulesParams, RulesResult, UnfoldParams, +}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -24,6 +29,9 @@ const FOLD_CONTRACT: TypedContract = TypedContract::new(); const UNFOLD_CONTRACT: TypedContract = TypedContract::new(); const CONVERT_CONTRACT: TypedContract = TypedContract::new(); +const RULES_CONTRACT: TypedContract = TypedContract::new(); +const MANAGE_RULES_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sheet.flange", "Flange", crate::checked!("sheet.flange", flange)) .at("SHEET METAL", "CREATE") @@ -56,7 +64,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .contract(&PERFORATE_CONTRACT) .output(output_schema_for::) .params( - "diameter, pitch: expr; margin?: expr (clear of edges, cut-outs and bends; default: the diameter); pattern?: staggered (60°, default) | square; body? - a perforation field over the whole flat sheet: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)", + "diameter, pitch: expr; margin?: expr (clear of edges, cut-outs, bends and the outline; default: the diameter); pattern?: staggered (60°, default) | square; body?; sketch? + profiles? (the outline: closed profiles of a sketch on a face of the sheet; holes only inside them, out of their inner loops) - a perforation field over the whole flat sheet or inside the outline: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)", ), CommandSpec::new("sheet.hem", "Hem", crate::checked!("sheet.hem", hem)) .at("SHEET METAL", "CREATE") @@ -101,7 +109,8 @@ pub static COMMANDS: &[CommandSpec] = &[ two flat faces tangent to it, either skin), makes it one bend of the rule's radius at their virtual sharp; \ the faces' holes become cut-outs and their engravings, up to half the thickness deep, pockets)", ), - CommandSpec::new("sheet.manage_rules", "Sheet Metal Rules", rules).at("SHEET METAL", "MODIFY").icon("sheet_rules").params( + CommandSpec::new("sheet.manage_rules", "Sheet Metal Rules", crate::checked!("sheet.manage_rules", rules)) + .contract(&MANAGE_RULES_CONTRACT).output(output_schema_for::).at("SHEET METAL", "MODIFY").icon("sheet_rules").params( "name (new or existing); thickness?, k_factor?, bend_radius?, relief_width?, relief_depth?, corner_relief?, hem_gap?, gap? (expressions; `Thickness` is the rule's; \ gap: between flanges that meet at a corner, whose ends are closed toward each other at any angle); \ corner_relief_shape?: notch|round|rectangular|tear (what is cut where two bends meet at a corner of the base: round and rectangular a relief \ @@ -110,7 +119,8 @@ pub static COMMANDS: &[CommandSpec] = &[ left between the bend's sides, 180° less it; the bend table gives both, and a flange's `angle` is always the bend angle); \ active?: bool; delete?: bool", ), - CommandSpec::new("sheet.rules", "List Sheet Metal Rules", list_rules).icon("sheet_rules").noundo().doc_only().params("→ rules with their expressions and values, and the active one"), + CommandSpec::new("sheet.rules", "List Sheet Metal Rules", crate::checked!("sheet.rules", list_rules)) + .contract(&RULES_CONTRACT).output(output_schema_for::).icon("sheet_rules").noundo().doc_only().params("→ rules with their expressions and values, and the active one"), CommandSpec::new("sheet.flat_pattern", "Create Flat Pattern", flat_pattern) .at("SHEET METAL", "CREATE") .icon("flat") @@ -472,7 +482,14 @@ fn perforate(s: &mut Session, p: &Value) -> Result { check_expr(s, m, Kind::Length, cmd, "margin")?; } let pattern = str_(p, "pattern").map(|t| perforation_pattern(t).map(str::to_string).map_err(|why| bad(cmd, why))).transpose()?; - add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from) }) + // The outline: only a sketch named here, never the active one. + let sketch = match p.get("sketch") { + Some(_) => Some(SketchId(feature_sketch(s, p, cmd)?)), + None if p.get("profiles").is_some() => return Err(bad(cmd, "`profiles` picks the outline's profiles: it needs `sketch`")), + None => None, + }; + let profiles = p.get("profiles").map(|_| profiles(p, cmd)).transpose()?; + add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from), sketch, profiles }) } fn hem(s: &mut Session, p: &Value) -> Result { @@ -511,7 +528,7 @@ fn fold(s: &mut Session, p: &Value) -> Result { let ss = st.sketch(sk).ok_or_else(|| bad(cmd, "no such sketch"))?; let ci = ss.sketch.curve_index(&c).ok_or_else(|| bad(cmd, format!("no curve `{c}` in the sketch")))?; let (a, b) = match ss.sketch.segs(ci).as_slice() { - [solidcraft_geom::Seg2::Line { a, b }] => (ss.plane.to_world(*a), ss.plane.to_world(*b)), + [solidcore_record::Seg2::Line { a, b }] => (ss.plane.to_world(*a), ss.plane.to_world(*b)), _ => return Err(bad(cmd, "the fold line must be a sketch line")), }; (Some(sk), Some(c), a, b) @@ -617,9 +634,13 @@ fn convert(s: &mut Session, p: &Value) -> Result { ) } +pub(crate) fn sheet_rule_name(v: &Value) -> std::result::Result<&str, &'static str> { + v.as_str().map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or("`name` is required") +} + fn rules(s: &mut Session, p: &Value) -> Result { let cmd = "sheet.manage_rules"; - let name = str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` is required"))?.to_string(); + let name = sheet_rule_name(p.get("name").unwrap_or(&Value::Null)).map_err(|why| bad(cmd, why))?.to_string(); if bool_(p, "delete").unwrap_or(false) { let doc = s.doc_mut(); let before = doc.sheet.rules.len(); @@ -630,7 +651,7 @@ fn rules(s: &mut Session, p: &Value) -> Result { if doc.sheet.active.as_deref() == Some(name.as_str()) { doc.sheet.active = None; } - return Ok(json!({"deleted": name})); + return serde_json::to_value(ManageRulesResult::Deleted { deleted: name, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string())); } let mut rule = s.doc.sheet.rules.iter().find(|r| r.name == name).cloned().unwrap_or_else(|| SheetRule { name: name.clone(), ..s.doc.sheet_rule(None) }); @@ -663,18 +684,15 @@ fn rules(s: &mut Session, p: &Value) -> Result { doc.sheet.active = Some(name.clone()); } s.refresh(); - let errors: Vec = s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| json!({"feature": r.name, "error": e}))).collect(); - Ok(json!({"rule": rule_json(&rule), "values": values, "errors": errors})) -} - -/// A rule as the rule commands list it: as saved, and with its `angle_display` also while it is -/// the `bend` a design leaves out. -fn rule_json(r: &SheetRule) -> Value { - let mut v = json!(r); - if let Value::Object(m) = &mut v { - m.insert("angle_display".into(), json!(r.angle_display)); - } - v + let errors = + s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| RuleFeatureError { feature: r.name.clone(), error: e.clone() })).collect(); + serde_json::to_value(ManageRulesResult::Changed { + rule: Box::new(RuleReply::from(&rule)), + values: values.into(), + errors, + param_warnings: Vec::new(), + }) + .map_err(|e| bad(cmd, e.to_string())) } fn list_rules(s: &mut Session, _p: &Value) -> Result { @@ -683,9 +701,9 @@ fn list_rules(s: &mut Session, _p: &Value) -> Result { if all.is_empty() { all.push(SheetRule::steel()); } - let rules: Vec = all.iter().map(|r| json!({"rule": rule_json(r), "values": s.doc.rule_values(&vals, r).ok()})).collect(); + let rules = all.iter().map(|r| ListedRule { rule: r.into(), values: s.doc.rule_values(&vals, r).ok().map(Into::into) }).collect(); let active = s.doc.sheet_rule(None).name; - Ok(json!({"rules": rules, "active": active})) + serde_json::to_value(RulesResult { rules, active, param_warnings: Vec::new() }).map_err(|e| bad("sheet.rules", e.to_string())) } fn no_sheet_body(cmd: &str) -> EngineError { @@ -704,8 +722,8 @@ fn sheet_of(s: &Session, p: &Value, cmd: &str) -> Result { } /// The centre and radius of a loop that is one whole circle (often two semicircles). -fn loop_circle(lp: &solidcraft_geom::Loop2) -> Option<(Vec2, f64)> { - use solidcraft_geom::Seg2; +fn loop_circle(lp: &solidcore_record::Loop2) -> Option<(Vec2, f64)> { + use solidcore_record::Seg2; let Some(Seg2::Arc { center, radius, sweep, .. }) = lp.segs.first() else { return None }; let total: f64 = lp.segs.iter().filter_map(|s| if let Seg2::Arc { sweep, .. } = s { Some(*sweep) } else { None }).sum(); let circular = lp.segs.iter().all( @@ -716,8 +734,8 @@ fn loop_circle(lp: &solidcraft_geom::Loop2) -> Option<(Vec2, f64)> { /// A loop's exact shape for the flat pattern JSON: a circle, or its lines and arcs (other /// curves as point lists at the flat pattern's 0.001 mm tolerance). -fn loop_shape(lp: &solidcraft_geom::Loop2) -> Value { - use solidcraft_geom::Seg2; +fn loop_shape(lp: &solidcore_record::Loop2) -> Value { + use solidcore_record::Seg2; let pt = |v: Vec2| json!([v.x, v.y]); if let Some((center, radius)) = loop_circle(lp) { return json!({"circle": {"center": pt(center), "radius": radius}}); @@ -917,7 +935,7 @@ pub fn flat_dxf(sh: &SheetBody, o: &DxfOptions) -> Result { .iter() .enumerate() .map(|(j, r)| { - let probe = r.outer.segs.first().map(solidcraft_geom::Seg2::mid); + let probe = r.outer.segs.first().map(solidcore_record::Seg2::mid); probe.is_some_and(|p| regions.iter().enumerate().any(|(i, other)| i != j && other.outer.contains(p))) }) .collect(); @@ -929,7 +947,7 @@ pub fn flat_dxf(sh: &SheetBody, o: &DxfOptions) -> Result { Pocket, Outline, } - let mut loops: Vec<(Pass, &solidcraft_geom::Loop2, String)> = Vec::new(); + let mut loops: Vec<(Pass, &solidcore_record::Loop2, String)> = Vec::new(); for (j, r) in regions.iter().enumerate() { for (k, lp) in std::iter::once(&r.outer).chain(&r.holes).enumerate() { let (pass, layer) = if k == 0 && !nested.get(j).copied().unwrap_or(false) { diff --git a/crates/engine/src/cmd/sheet_convert_tests.rs b/crates/engine/src/cmd/sheet_convert_tests.rs index 1618b1a24..7735324ae 100644 --- a/crates/engine/src/cmd/sheet_convert_tests.rs +++ b/crates/engine/src/cmd/sheet_convert_tests.rs @@ -1,6 +1,7 @@ //! Convert to Sheet Metal: solid and shelled bodies with bend edges (with holes and round edges in //! their faces), plates read from STEP files whose walls come in pieces, and plates with recesses. +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI, SQRT_2}; use serde_json::{Value, json}; @@ -632,6 +633,23 @@ fn a_channel_with_its_bends_modelled_folds_back_into_itself_under_its_own_radius assert!((volume(&mut s) - solid).abs() < 1e-3 * solid); } +/// A rule's values follow the sheet's own thickness (#4328): an L shell 2 thick, its bend +/// modelled R 2 inside, converted under the default rule (2.5 thick, bends R `Thickness`) is a +/// sheet 2 thick bent R 2, the solid unchanged; an edge flange added to it bends R 2 as well. +#[test] +fn a_converted_shell_takes_its_rules_values_at_its_own_thickness() { + let mut s = Session::default(); + let (outer, _) = bent_section(&mut s, &[(0.0, 40.0), (0.0, 0.0), (60.0, 0.0)], 2.0, 2.0, 100.0)[0]; + let solid = volume(&mut s); + run(&mut s, "sheet.convert", json!({"body": "Section", "face": [30, 0, 50], "bends": [outer]})); + assert!((volume(&mut s) - solid).abs() < 1e-6 * solid, "{} vs {solid}", volume(&mut s)); + let f = flat(&mut s); + assert_eq!((f["thickness"].as_f64(), f["bends"][0]["radius"].as_f64()), (Some(2.0), Some(2.0)), "{f}"); + run(&mut s, "sheet.flange", json!({"edges": [[0, 40, 50]], "height": 10})); + let f = flat(&mut s); + assert_eq!(f["bends"][1]["radius"].as_f64(), Some(2.0), "{f}"); +} + #[test] fn a_filleted_edge_of_a_solid_block_is_a_bend() { // A block's bottom edge rounded R 5: the faces either side meet at the old sharp edge, @@ -1109,7 +1127,11 @@ fn label_rectangle(s: &mut Session) { } fn contains(s: &Session, p: [f64; 3]) -> bool { - s.model.state().bodies.first().is_some_and(|b| b.body.contains(solidcraft_geom::Vec3::new(p[0], p[1], p[2]))) + s.model + .state() + .bodies + .first() + .is_some_and(|b| b.body.classify_point(solidcore_record::Vec3::new(p[0], p[1], p[2])).unwrap() == solidcraft_kernel::PointClass::Inside) } /// The LINE entities a DXF draws on `layer` (group codes and values alternate, a line each). @@ -1650,18 +1672,18 @@ fn a_converted_trays_corners_are_closed_and_relieved_as_a_flanged_trays_are() { // corners R + T in from the sharps, 92 and 52 apart. if shape == "round" { let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); - let arcs: Vec<(solidcraft_geom::Vec2, f64)> = solidcraft_io::read_dxf(&dxf) + let arcs: Vec<(solidcore_record::Vec2, f64)> = solidcraft_io::read_dxf(&dxf) .unwrap_or_default() .iter() .filter_map(|g| if let solidcraft_io::Geom2::Arc { c, a, .. } = g { Some((*c, a.dist(*c))) } else { None }) .collect(); assert_eq!(arcs.len(), 4, "{arcs:?}"); - let lo = solidcraft_geom::Vec2::new( + let lo = solidcore_record::Vec2::new( arcs.iter().map(|(c, _)| c.x).fold(f64::MAX, f64::min), arcs.iter().map(|(c, _)| c.y).fold(f64::MAX, f64::min), ); for (x, y) in [(0.0, 0.0), (92.0, 0.0), (92.0, 52.0), (0.0, 52.0)] { - let at = lo + solidcraft_geom::Vec2::new(x, y); + let at = lo + solidcore_record::Vec2::new(x, y); assert!(arcs.iter().any(|(c, r)| c.dist(at) < 1e-6 && (r - 4.0).abs() < 1e-6), "({x}, {y}): {arcs:?}"); } } @@ -1777,3 +1799,80 @@ fn a_wall_on_part_of_an_edge_meets_a_wall_at_a_relieved_corner_and_is_relieved_a run(&mut s, "sheet.refold", json!({})); assert!((volume(&mut s) - v).abs() < 1e-6 * v); } + +/// A tray of this build's own sheet metal: a 120 x 90 base, T 1, R 1, K 0.5, gap 0.6, its four +/// walls 30 high under the rule's corner relief `shape`, made in one edge flange feature or in +/// two (long walls, then short), written to a STEP and inserted into a new design as a plain +/// solid. Its bends are picked at mid-length on their outer cylinders, (R + T) out from their +/// axes 45° round from the base. Returns the new design (with the rule), the picks and the +/// design the tray was made in. +fn tray_round_trip(shape: &str, two: bool) -> (Session, Vec<[f64; 3]>, Session) { + let (t, r) = (1.0, 1.0); + let rule = json!({"name": "T", "thickness": "1 mm", "k_factor": "0.5", "bend_radius": "1 mm", "gap": "0.6 mm", "corner_relief_shape": shape, "corner_relief": "3 mm", "active": true}); + let mut a = Session::default(); + run(&mut a, "sheet.manage_rules", rule.clone()); + run(&mut a, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(&mut a, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [120, 90]})); + run(&mut a, "sketch.finish", json!({})); + run(&mut a, "sheet.flange", json!({"type": "base", "sketch": "Base", "rule": "T"})); + let (long, short) = (json!([[60, 0, 1], [60, 90, 1]]), json!([[120, 45, 1], [0, 45, 1]])); + if two { + run(&mut a, "sheet.flange", json!({"edges": long, "height": 30})); + run(&mut a, "sheet.flange", json!({"edges": short, "height": 30})); + } else { + let mut all = long.as_array().cloned().unwrap_or_default(); + all.extend(short.as_array().cloned().unwrap_or_default()); + run(&mut a, "sheet.flange", json!({"edges": all, "height": 30})); + } + let path = std::env::temp_dir().join(format!("solidcraft-tray-round-trip-{shape}-{two}-{}.step", std::process::id())); + run(&mut a, "file.export", json!({"path": path.to_string_lossy()})); + let mut s = Session::default(); + run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy()})); + let _ = std::fs::remove_file(&path); + run(&mut s, "sheet.manage_rules", rule); + // Each bend's axis lies R + T in from the base's edge and R + T above its bottom face. + let (o, d) = (r + t, (r + t) * std::f64::consts::FRAC_1_SQRT_2); + let picks = vec![[60.0, o - d, o - d], [60.0, 90.0 - o + d, o - d], [120.0 - o + d, 45.0, o - d], [o - d, 45.0, o - d]]; + (s, picks, a) +} + +/// The flat's outline area and its bends' lengths, longest first. +fn flat_area_and_bends(s: &mut Session) -> (f64, Vec) { + let f = flat(s); + let ring = |l: &Value| { + let p: Vec<(f64, f64)> = + l.as_array().into_iter().flatten().map(|q| (q[0].as_f64().unwrap_or(f64::NAN), q[1].as_f64().unwrap_or(f64::NAN))).collect(); + (0..p.len()).map(|i| p[i].0 * p[(i + 1) % p.len()].1 - p[(i + 1) % p.len()].0 * p[i].1).sum::().abs() / 2.0 + }; + let area = f["outline"].as_array().into_iter().flatten().map(ring).sum(); + let mut bends: Vec = f["bends"].as_array().into_iter().flatten().map(|b| b["length"].as_f64().unwrap_or(f64::NAN)).collect(); + bends.sort_by(|x, y| y.total_cmp(x)); + (area, bends) +} + +/// A tray made with this build's sheet metal converts back to the same tray: the walls that run +/// on past their bends' ends (a notch, a tear) step down to the bend there, and a round relief's +/// arc stays; also with the short walls made in a second feature, where the corners are notched +/// or round (a torn butt corner is torn differently from one feature's corner). +#[test] +fn trays_of_its_own_sheet_metal_convert_back() { + for shape in ["notch", "tear", "round"] { + for two in [false, true].into_iter().filter(|two| !(*two && shape == "tear")) { + let what = format!("{shape}, {}", if two { "two features" } else { "one feature" }); + let (mut s, picks, mut source) = tray_round_trip(shape, two); + let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let out = s.execute("sheet.convert", &json!({"body": body, "face": [60, 45, 0], "bends": picks, "rule": "T"})); + assert!(out.is_ok(), "{what}: {}", out.err().map(|e| e.to_string()).unwrap_or_default()); + // The same tray: its solid, and its flat with the same bends. + let (v, size, (area, bends)) = (volume(&mut source), flat_size(&mut source), flat_area_and_bends(&mut source)); + assert!((volume(&mut s) - v).abs() < 1e-9 * v, "{what}: {} vs {v}", volume(&mut s)); + assert!(same_size(flat_size(&mut s), size, 1e-6), "{what}: {:?} vs {size:?}", flat_size(&mut s)); + let (got_area, got_bends) = flat_area_and_bends(&mut s); + assert!((got_area - area).abs() < 1e-9 * area, "{what}: {got_area} vs {area}"); + assert!( + got_bends.len() == bends.len() && got_bends.iter().zip(&bends).all(|(x, y)| (x - y).abs() < 1e-6), + "{what}: {got_bends:?} vs {bends:?}" + ); + } + } +} diff --git a/crates/engine/src/cmd/sheet_dxf_tests.rs b/crates/engine/src/cmd/sheet_dxf_tests.rs index 8a99ce6eb..53b994084 100644 --- a/crates/engine/src/cmd/sheet_dxf_tests.rs +++ b/crates/engine/src/cmd/sheet_dxf_tests.rs @@ -2,10 +2,11 @@ //! a laser-cutting shop can use it as it is: layers by role, bend notes, letters cut or etched, //! one file per sheet body. +use solidcraft_geom::prelude::*; use std::f64::consts::{PI, TAU}; use serde_json::{Value, json}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; use crate::Session; @@ -103,7 +104,7 @@ fn point(e: &Entity, code: i32) -> Vec2 { } /// All loops of the flat pattern (outlines, cut-outs, islands). -fn loops(s: &Session) -> Vec { +fn loops(s: &Session) -> Vec { let regions = s.model.state().sheets[0].flat_regions().unwrap_or_default(); regions.iter().flat_map(|r| std::iter::once(r.outer.clone()).chain(r.holes.clone())).collect() } @@ -345,7 +346,7 @@ fn the_flat_pattern_is_on_layers_by_role_and_inner_contours_come_first() { // OUTLINE: the tray's outer contour alone, one entity for each of its segments (lines and arcs). let regions = s.model.state().sheets[0].flat_regions().unwrap_or_default(); let plate = - regions.iter().max_by(|a, b| a.area().total_cmp(&b.area())).map(|r| r.outer.clone()).unwrap_or(solidcraft_geom::Loop2 { segs: Vec::new() }); + regions.iter().max_by(|a, b| a.area().total_cmp(&b.area())).map(|r| r.outer.clone()).unwrap_or(solidcore_record::Loop2 { segs: Vec::new() }); assert_eq!(on("OUTLINE").len(), solidcraft_io::loop_shapes(&plate).len()); assert!(on("OUTLINE").iter().all(|e| e.0 == "LINE" || e.0 == "ARC"), "{:?}", on("OUTLINE").iter().map(|e| &e.0).collect::>()); // CUT: what is cut out inside it that is no text: the Ø5 hole as one CIRCLE, the slot's four lines. @@ -614,3 +615,59 @@ fn bend_lines_can_be_left_out_and_everything_put_on_layer_0() { assert!(s.execute("sheet.export_dxf", &bad).is_err(), "{bad}"); } } + +/// The DXF of a sheet folded across a curved outer outline has the curve as drawn, not arcs fitted +/// to it, and no seams where the fold cut it: the blank, with its bend line where the bend is. +#[test] +fn a_curved_outline_folded_across_stays_its_curve_in_the_dxf() { + let blanks: [(&str, &str, Value, &str); 3] = [ + ("circle", "sketch.circle.center", json!({"center": [0, 0], "radius": 50}), "CIRCLE"), + ("ellipse", "sketch.ellipse", json!({"center": [0, 0], "major": [80, 0], "minor_radius": 40}), "ELLIPSE"), + ( + "spline", + "sketch.spline.fit_point", + json!({"points": [[70, -5], [40, 40], [0, 40], [-50, 35], [-85, 0], [-40, -50], [0, -35], [35, -25]], "periodic": true}), + "SPLINE", + ), + ]; + for (name, id, p, kind) in blanks { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + run(&mut s, id, p); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Blank"})); + let flat_loops = loops(&s); + let area: f64 = flat_loops.iter().map(|l| l.signed_area().abs()).sum(); + run(&mut s, "sheet.fold", json!({"points": [[10, -200, 2.5], [10, 200, 2.5]]})); + let dxf = export(&mut s, json!({})); + let es = entities(&dxf); + assert!(count(&es, kind) >= 1, "{name}: no {kind}: {:?}", es.iter().map(|e| e.0.as_str()).collect::>()); + if kind != "CIRCLE" { + assert_eq!(count(&es, "ARC"), 0, "{name}: curves came back as fitted arcs"); + } + // The only straight line is the bend line, across the sheet on the zone's centre line. + let lines: Vec<&Entity> = es.iter().filter(|e| e.0 == "LINE").collect(); + assert_eq!(lines.len(), 1, "{name}: seams left in the outline"); + let (a, b) = (point(lines[0], 10), point(lines[0], 11)); + assert!((a.x - 10.0).abs() < 1e-6 && (b.x - 10.0).abs() < 1e-6, "{name}: bend line {a:?} to {b:?}"); + // The blank is the blank: as much of it as was drawn, exactly. + let after: f64 = loops(&s).iter().map(|l| l.signed_area().abs()).sum(); + assert!((after - area).abs() < 1e-6 * area, "{name}: {after} vs {area}"); + } +} + +/// A fold across the straight part of a curved outline keeps the curve as drawn as well: an arc +/// stays one arc, not the 0.001 mm chords a fold used to leave. +#[test] +fn a_curve_away_from_a_fold_stays_its_curve_in_the_dxf() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + run(&mut s, "sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})); + run(&mut s, "sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Blank"})); + run(&mut s, "sheet.fold", json!({"points": [[-20, -200, 2.5], [-20, 200, 2.5]]})); + let es = entities(&export(&mut s, json!({}))); + assert_eq!(count(&es, "ARC"), 1, "{:?}", es.iter().map(|e| e.0.as_str()).collect::>()); + assert!(count(&es, "LINE") < 12, "the arc went to chords: {} lines", count(&es, "LINE")); +} diff --git a/crates/engine/src/cmd/sheet_face_names_tests.rs b/crates/engine/src/cmd/sheet_face_names_tests.rs index 6c5d656f3..ffd6065cf 100644 --- a/crates/engine/src/cmd/sheet_face_names_tests.rs +++ b/crates/engine/src/cmd/sheet_face_names_tests.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::Session; @@ -59,9 +60,10 @@ fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() { let mut s = Session::default(); let (width, fb, sd) = tray(&mut s, 320.0); let all = faces(&mut s); - // Every face but the hole's wall (two halves) has a sheet name, and no two faces share one. + // Every face but the hole's wall (r 3.3, however many faces the kernel makes it of) has a + // sheet name, and no two faces share one. let unnamed: Vec<_> = all.iter().filter(|f| f.0.is_none()).collect(); - assert!(unnamed.len() == 2 && unnamed.iter().all(|f| f.2.is_some_and(|r| (r - 3.3).abs() < 1e-6)), "only the hole's wall: {unnamed:?}"); + assert!(!unnamed.is_empty() && unnamed.iter().all(|f| f.2.is_some_and(|r| (r - 3.3).abs() < 1e-6)), "only the hole's wall: {unnamed:?}"); let mut names: Vec<&str> = all.iter().filter_map(|f| f.0.as_deref()).collect(); names.sort_unstable(); let n = names.len(); @@ -84,7 +86,9 @@ fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() { let radius = |name: &str| named(&all, name).first().and_then(|f| f.2); assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.inner")).map(|r| (r * 1e6).round() / 1e6), Some(1.0)); assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.outer")).map(|r| (r * 1e6).round() / 1e6), Some(2.0)); - // 80 mm wider: the same names, each on the same face where it now is. + // 80 mm wider: the same names, each on the same face where it now is. A name's point is + // somewhere on its face: the right flange's top is the plane x = w − 1, the back flange's + // far rim the strip z = 30, 199 <= y <= 200 (the flange 1 thick, its outside at y = 200). let right = point(&s, &format!("sheet:Body1:F{sd}.1:top")); assert!((right.x - 319.0).abs() < 1e-3, "{right:?}"); run(&mut s, "parameters.change", json!({"name": width, "expression": "400"})); @@ -94,8 +98,53 @@ fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() { assert_eq!(again, names); let right = point(&s, &format!("sheet:Body1:F{sd}.1:top")); assert!((right.x - 399.0).abs() < 1e-3, "{right:?}"); - let far = point(&s, &format!("sheet:Body1:F{fb}.1:rim.far")); - assert!((far.y - 199.5).abs() < 1e-3 && (far.z - 30.0).abs() < 1e-3, "{far:?}"); + let rim = format!("sheet:Body1:F{fb}.1:rim.far"); + let far = point(&s, &rim); + let st = s.model.state(); + let hit = solidcraft_doc::naming::locate_one(&st, None, &rim).unwrap(); + on_planar_face(&st.bodies[hit.body].body, hit.face, far); + assert!((far.z - 30.0).abs() < 1e-9 && (199.0..=200.0).contains(&far.y), "the back flange's far rim: {far:?}"); +} + +/// `p` lies on face `face` of `body`, on its exact geometry: within rounding at the part's scale +/// of the plane the face lies on, and inside the boundary its edges trace there (each a line, +/// counted by crossings). +fn on_planar_face(body: &solidcraft_kernel::Body, face: usize, p: Vec3) { + use solidcore_record::brep::{Curve, Loop}; + let rounding = 1e-12 * body.size().max(1.0); + let surface = solidcraft_kernel::face_surface(body, face).unwrap(); + let on = surface.nearest(p).unwrap(); + assert!(on.dist(p) <= rounding, "{p:?} is {} off face {face}'s surface", on.dist(p)); + let solidcraft_kernel::FaceSurface::Plane { normal, .. } = surface else { panic!("face {face} is not planar: {surface:?}") }; + // Coordinates in the plane: along `x` and `y`, square to its normal. + let x = if normal.cross(Vec3::X).len() > 0.5 { normal.cross(Vec3::X).normalized().unwrap() } else { normal.cross(Vec3::Y).normalized().unwrap() }; + let y = normal.cross(x); + let local = |q: Vec3| ((q - p).dot(x), (q - p).dot(y)); + let record = body.record(); + let point = |v: u32| { + let q = record.vertices[v as usize].point; + Vec3::new(q[0], q[1], q[2]) + }; + // Crossings of the ray from `p` along +x with the face's boundary. + let mut crossings = 0; + for l in &record.faces[face].loops { + let Loop::Edges { edges } = l else { continue }; + for e in edges { + let edge = &record.edges[e.edge as usize]; + assert!(matches!(edge.parameters(), Curve::Line { .. }), "an edge of face {face} is not a line: {:?}", edge.parameters()); + let [a, b] = edge.vertices.map(|v| local(point(v))); + let distance = { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let t = (-(a.0 * dx + a.1 * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + (a.0 + t * dx).hypot(a.1 + t * dy) + }; + assert!(distance > rounding, "{p:?} is on the boundary of face {face}"); + if (a.1 > 0.0) != (b.1 > 0.0) && a.0 + (b.0 - a.0) * (0.0 - a.1) / (b.1 - a.1) > 0.0 { + crossings += 1; + } + } + } + assert_eq!(crossings % 2, 1, "{p:?} is outside face {face}'s boundary"); } #[test] @@ -112,3 +161,23 @@ fn a_flanges_sheet_names_hold_when_another_flange_goes() { assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), None, &gone).is_err()); assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), Some("Body2"), &right).is_err()); } + +/// A fold at 45° across a strip, with a bend zone wide for the strip: about a third of the bend's +/// faces lies beyond the ends of its start line, along the bend, and they still take its names. +#[test] +fn a_bend_askew_across_a_sheet_keeps_its_names() { + let mut s = Session::default(); + run(&mut s, "sheet.manage_rules", json!({"name": "R10", "thickness": "1 mm", "bend_radius": "10 mm", "active": true})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Strip"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [200, 20]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Strip"})); + run(&mut s, "sheet.fold", json!({"points": [[90, -5, 1], [115, 20, 1]], "fixed": [10, 10, 1]})); + let fold = s.doc.features.last().map_or(0, |f| f.id); + let all = faces(&mut s); + for (side, radius) in [("inner", 10.0), ("outer", 11.0)] { + let name = format!("sheet:Body1:F{fold}.0:bend.{side}"); + let f = named(&all, &name); + assert!(f.len() == 1 && f[0].2.is_some_and(|r| (r - radius).abs() < 1e-6), "{name}: {all:?}"); + } +} diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index adc6e3f10..717547480 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -1,3 +1,4 @@ +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI}; use serde_json::{Value, json}; @@ -60,7 +61,7 @@ fn plain_solid_sheet_operations_explain_how_to_start_sheet_metal() { #[test] fn side_edge_flanges_across_a_bend_keep_their_relief_through_rebuild_and_reopen() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; for shape in ["round", "rectangular"] { for reverse in [false, true] { @@ -132,8 +133,8 @@ fn shallow_sheet_pocket_preserves_material_depth_export_undo_and_reopen() { assert!((volume(&mut s) - 14900.0).abs() < 1e-6); let state = s.model.state(); let body = &state.bodies[0].body; - assert!(!body.contains(solidcraft_geom::Vec3::new(25.0, 25.0, 0.5))); - assert!(body.contains(solidcraft_geom::Vec3::new(25.0, 25.0, 1.5))); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(25.0, 25.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(25.0, 25.0, 1.5)).unwrap(), solidcraft_kernel::PointClass::Inside); } let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((volume(&mut reopened) - 14900.0).abs() < 1e-6); @@ -286,10 +287,10 @@ fn intersect_preserves_both_material_regions_of_a_logical_ring_sheet() { let area: f64 = regions.iter().map(|r| r.area()).sum(); assert!((area - (900.0 - PI * 75.0)).abs() < 1e-8, "area={area}"); let body = &state.bodies[0].body; - assert!(body.contains(solidcraft_geom::Vec3::new(50.0, 30.0, 1.0))); - assert!(!body.contains(solidcraft_geom::Vec3::new(57.0, 30.0, 1.0))); - assert!(body.contains(solidcraft_geom::Vec3::new(64.0, 30.0, 1.0))); - assert!(!body.contains(solidcraft_geom::Vec3::new(70.0, 30.0, 1.0))); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(50.0, 30.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(57.0, 30.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(64.0, 30.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(70.0, 30.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Outside); assert!((volume(&mut s) - (900.0 - PI * 75.0) * 2.5).abs() < 0.2); } let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap().to_string(); @@ -298,14 +299,14 @@ fn intersect_preserves_both_material_regions_of_a_logical_ring_sheet() { #[test] fn machining_a_folded_parallel_panel_preserves_its_pocket_on_unfold() { + use solidcore_record::Vec3; use solidcraft_doc::{apply_point, apply_vector}; - use solidcraft_geom::Vec3; let mut s = Session::default(); base(&mut s, 100.0, 60.0); run(&mut s, "sheet.flange", json!({"edges":[[50,0,2.5]],"height":20})); let sh = s.model.state().sheets[0].clone(); let points = sh.panel(&sh.flanges[0]).outer.polyline(1e-3); - let c = points.iter().copied().fold(solidcraft_geom::Vec2::ZERO, |sum, p| sum + p) / (points.len() as f64); + let c = points.iter().copied().fold(solidcore_record::Vec2::ZERO, |sum, p| sum + p) / (points.len() as f64); let w = sh.world(Some(0)); let origin = apply_point(&w, Vec3::ZERO); let x = apply_vector(&w, Vec3::X); @@ -322,8 +323,8 @@ fn machining_a_folded_parallel_panel_preserves_its_pocket_on_unfold() { run(&mut s, "sheet.unfold", json!({})); let state = s.model.state(); let body = &state.bodies[0].body; - assert!(!body.contains(Vec3::new(c.x, c.y, 0.5))); - assert!(body.contains(Vec3::new(c.x, c.y, 1.5))); + assert_eq!(body.classify_point(Vec3::new(c.x, c.y, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(c.x, c.y, 1.5)).unwrap(), solidcraft_kernel::PointClass::Inside); assert_eq!(flat(&mut s)["pockets"][0]["depth_mm"], 1.0); run(&mut s, "sheet.refold", json!({})); assert!((volume(&mut s) - (18972.62196081845 - 16.0)).abs() < 0.2); @@ -342,8 +343,14 @@ fn flipped_sheet_pocket_keeps_depth_in_the_local_thickness_direction() { } assert!((volume(&mut s) - 14900.0).abs() < 1e-6); let state = s.model.state(); - assert!(!state.bodies[0].body.contains(solidcraft_geom::Vec3::new(25.0, 25.0, -0.5))); - assert!(state.bodies[0].body.contains(solidcraft_geom::Vec3::new(25.0, 25.0, -1.5))); + assert_eq!( + state.bodies[0].body.classify_point(solidcore_record::Vec3::new(25.0, 25.0, -0.5)).unwrap(), + solidcraft_kernel::PointClass::Outside + ); + assert_eq!( + state.bodies[0].body.classify_point(solidcore_record::Vec3::new(25.0, 25.0, -1.5)).unwrap(), + solidcraft_kernel::PointClass::Inside + ); } } @@ -374,10 +381,21 @@ fn multiple_profile_intersect_keeps_tool_union_for_solids_and_sheet_groups() { } let state = s.model.state(); for x in [25.0, 65.0] { - assert!(state.bodies.iter().any(|b| b.body.contains(solidcraft_geom::Vec3::new(x, 25.0, 1.0)))); + assert!( + state + .bodies + .iter() + .any(|b| b.body.classify_point(solidcore_record::Vec3::new(x, 25.0, 1.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); } - assert!(!state.bodies.iter().any(|b| b.body.contains(solidcraft_geom::Vec3::new(50.0, 25.0, 1.0)))); - assert!(state.bodies.iter().any(|b| b.name == "Control" && b.body.contains(solidcraft_geom::Vec3::new(205.0, 5.0, 5.0)))); + assert!( + !state + .bodies + .iter() + .any(|b| b.body.classify_point(solidcore_record::Vec3::new(50.0, 25.0, 1.0)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); + assert!(state.bodies.iter().any(|b| b.name == "Control" + && b.body.classify_point(solidcore_record::Vec3::new(205.0, 5.0, 5.0)).unwrap() == solidcraft_kernel::PointClass::Inside)); } } @@ -396,14 +414,14 @@ fn deleting_sheet_material_prunes_cosmetic_threads_and_undo_restores_them() { assert!(s.model.state().bodies.is_empty()); assert!(s.model.state().sheets.is_empty()); assert!(s.model.state().threads.is_empty()); - assert!(solidcraft_doc::world_state(&s.doc, &s.model.state()).threads.is_empty()); + assert!(solidcraft_doc::world_state(&s.doc, &s.model.state()).unwrap().threads.is_empty()); run(&mut s, "edit.undo", json!({})); assert_eq!(s.model.state().threads.len(), 1); } #[test] fn sheet_pocket_transfer_keeps_local_depth_world_pose_and_history() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; fn check(s: &Session, name: &str, owner: u64, local_origin: Vec3, local_y: Vec3, transferred: bool) { let state = s.model.state(); let mb = state.body(name).unwrap(); @@ -415,17 +433,17 @@ fn sheet_pocket_transfer_keeps_local_depth_world_pose_and_history() { assert!(sh.frame.y.dist(local_y) < 1e-8); assert_eq!(sh.pockets.len(), 1); assert_eq!((sh.pockets[0].z0, sh.pockets[0].z1), (0.0, 1.0)); - let cut = sh.frame.to_world(solidcraft_geom::Vec2::new(25.0, 25.0)) + sh.frame.normal() * 0.5; - let floor = sh.frame.to_world(solidcraft_geom::Vec2::new(25.0, 25.0)) + sh.frame.normal() * 1.5; - assert!(!mb.body.contains(cut)); - assert!(mb.body.contains(floor)); - let world = s.world_state(); + let cut = sh.frame.to_world(solidcore_record::Vec2::new(25.0, 25.0)) + sh.frame.normal() * 0.5; + let floor = sh.frame.to_world(solidcore_record::Vec2::new(25.0, 25.0)) + sh.frame.normal() * 1.5; + assert_eq!(mb.body.classify_point(cut).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(mb.body.classify_point(floor).unwrap(), solidcraft_kernel::PointClass::Inside); + let world = s.world_state().unwrap(); let body = &world.body(name).unwrap().body; - let bounds = body.tessellate(1e-3).unwrap().bounds(); + let bounds = body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap().bounds(); assert!(bounds.min.dist(Vec3::ZERO) < 1e-6, "{bounds:?}"); assert!(bounds.max.dist(Vec3::new(100.0, 60.0, 2.5)) < 1e-6, "{bounds:?}"); - assert!(!body.contains(Vec3::new(25.0, 25.0, 0.5))); - assert!(body.contains(Vec3::new(25.0, 25.0, 1.5))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 1.5)).unwrap(), solidcraft_kernel::PointClass::Inside); assert!((solidcraft_kernel::measure(body).unwrap().volume - 14900.0).abs() < 1e-6); } let mut s = Session::default(); @@ -839,6 +857,99 @@ fn a_pattern_of_a_cut_in_the_flat_is_kept_like_the_cut() { assert!(rel(volume(&mut s), folded - 4.0 * each) < 1e-9, "{} vs {}", volume(&mut s), folded - 4.0 * each); } +/// Material joined in the flat, one sheet thick in the plane of a panel, becomes part of that +/// panel as a cut made there does: kept in the flat pattern and refolded, its size following a +/// parameter. A tab on the base's free edge and one beside the flange's panel. A join that +/// reaches into the bend zone keeps the warning that the flat pattern can't include it. +#[test] +fn a_join_in_the_flat_is_kept_like_a_cut() { + // The rule's 2.5 mm sheet, R 2.5, K 0.44: the flange on y = 50 sets the base back to y = 45 and + // bends across BA = π/2·(2.5 + 0.44·2.5); its panel runs on from y = 45 + BA, x 0 to 80. + let (t, ba) = (2.5, FRAC_PI_2 * (2.5 + 0.44 * 2.5)); + let tab = |s: &mut Session, name: &str, points: Value| { + run(s, "sketch.create", json!({"plane": "XY", "name": name})); + run(s, "sketch.line", json!({"points": points, "closed": true})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": name, "distance": t, "operation": "join", "name": format!("{name}_Join")})) + }; + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "TabW", "expression": "10 mm"})); + base(&mut s, 80.0, 50.0); + run(&mut s, "sheet.flange", json!({"edges": [[40, 50, 2.5]], "height": 20})); + let folded = volume(&mut s); + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + // 15 x TabW on the base's free edge at x = 80. + let out = tab(&mut s, "Base_Tab", json!([["80 mm", "10 mm"], ["95 mm", "10 mm"], ["95 mm", "10 mm + TabW"], ["80 mm", "10 mm + TabW"]])); + assert!(out["warning"].is_null(), "{out}"); + assert!(rel(volume(&mut s), unfolded + 15.0 * 10.0 * t) < 1e-9, "{}", volume(&mut s)); + // 10 x 5 beside the flange's panel, 3 mm past its bend. + let y = 45.0 + ba + 3.0; + let out = tab(&mut s, "Panel_Tab", json!([[80, y], [90, y], [90, y + 5.0], [80, y + 5.0]])); + assert!(out["warning"].is_null(), "{out}"); + let added = |w: f64| 15.0 * w * t + 10.0 * 5.0 * t; + assert!(rel(volume(&mut s), unfolded + added(10.0)) < 1e-9, "{}", volume(&mut s)); + assert!((flat(&mut s)["flat_size_mm"][0].as_f64().unwrap_or(0.0) - 95.0).abs() < 1e-9); + run(&mut s, "sheet.refold", json!({})); + assert!(rel(volume(&mut s), folded + added(10.0)) < 1e-9, "{} vs {}", volume(&mut s), folded + added(10.0)); + run(&mut s, "parameters.change", json!({"name": "TabW", "expression": "20 mm"})); + assert!(rel(volume(&mut s), folded + added(20.0)) < 1e-9, "{} vs {}", volume(&mut s), folded + added(20.0)); + // One join with a tab on each: each joins the panel it is beside. + let mut s = Session::default(); + base(&mut s, 80.0, 50.0); + run(&mut s, "sheet.flange", json!({"edges": [[40, 50, 2.5]], "height": 20})); + let folded = volume(&mut s); + run(&mut s, "sheet.unfold", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Tabs"})); + run(&mut s, "sketch.line", json!({"points": [[80, 10], [95, 10], [95, 20], [80, 20]], "closed": true})); + run(&mut s, "sketch.line", json!({"points": [[80, y], [90, y], [90, y + 5.0], [80, y + 5.0]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + let out = run(&mut s, "solid.extrude", json!({"sketch": "Tabs", "distance": t, "operation": "join"})); + assert!(out["warning"].is_null(), "{out}"); + run(&mut s, "sheet.refold", json!({})); + assert!(rel(volume(&mut s), folded + added(10.0)) < 1e-9, "{} vs {}", volume(&mut s), folded + added(10.0)); + // Into the bend zone (it starts at y = 45): the generic path, with its warning. + let mut s = Session::default(); + base(&mut s, 80.0, 50.0); + run(&mut s, "sheet.flange", json!({"edges": [[40, 50, 2.5]], "height": 20})); + run(&mut s, "sheet.unfold", json!({})); + let out = tab(&mut s, "Zone_Tab", json!([[80, 40], [90, 40], [90, 48], [80, 48]])); + assert!(out["warning"].as_str().is_some_and(|w| w.contains("can't include this change")), "{out}"); + // The same two tabs in a 1 mm sheet (R 1.18) and a 3 mm one (R 3), each joined one sheet + // thick: kept, refolded and following the parameter alike. + for (t, r) in [(1.0, 1.18), (3.0, 3.0)] { + let what = format!("T {t} R {r}"); + let ba = FRAC_PI_2 * (r + 0.44 * t); + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "TabW", "expression": "10 mm"})); + let rule = json!({"name": "Rule", "active": true, "thickness": format!("{t} mm"), "k_factor": "0.44", "bend_radius": format!("{r} mm")}); + run(&mut s, "sheet.manage_rules", rule); + base(&mut s, 80.0, 50.0); + run(&mut s, "sheet.flange", json!({"edges": [[40, 50, t]], "height": 20})); + let folded = volume(&mut s); + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + let join = |s: &mut Session, name: &str, points: Value| { + run(s, "sketch.create", json!({"plane": "XY", "name": name})); + run(s, "sketch.line", json!({"points": points, "closed": true})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": name, "distance": t, "operation": "join"})) + }; + let out = join(&mut s, "Base_Tab", json!([["80 mm", "10 mm"], ["95 mm", "10 mm"], ["95 mm", "10 mm + TabW"], ["80 mm", "10 mm + TabW"]])); + assert!(out["warning"].is_null(), "{what}: {out}"); + // The panel starts BA past the base, set back R + T from y = 50. + let y = 50.0 - (r + t) + ba + 3.0; + let out = join(&mut s, "Panel_Tab", json!([[80, y], [90, y], [90, y + 5.0], [80, y + 5.0]])); + assert!(out["warning"].is_null(), "{what}: {out}"); + let added = |w: f64| 15.0 * w * t + 10.0 * 5.0 * t; + assert!(rel(volume(&mut s), unfolded + added(10.0)) < 1e-9, "{what}: {}", volume(&mut s)); + run(&mut s, "sheet.refold", json!({})); + assert!(rel(volume(&mut s), folded + added(10.0)) < 1e-9, "{what}: {} vs {}", volume(&mut s), folded + added(10.0)); + run(&mut s, "parameters.change", json!({"name": "TabW", "expression": "20 mm"})); + assert!(rel(volume(&mut s), folded + added(20.0)) < 1e-9, "{what}: {} vs {}", volume(&mut s), folded + added(20.0)); + } +} + /// A plate (15, -20) (0, 0) (-100, 0) (-100, -20) with a 20 mm inside flange on its slanted edge /// (2 mm sheet, R 2, K 0.5: the folded sheet holds its flat area times the thickness), unfolded, /// and a triangle cut out with a corner on the bend line: where the line ends on the plate's @@ -1234,7 +1345,11 @@ fn cut_through(s: &mut Session, sketch: &str) { } fn contains(s: &Session, p: [f64; 3]) -> bool { - s.model.state().bodies.first().is_some_and(|b| b.body.contains(solidcraft_geom::Vec3::new(p[0], p[1], p[2]))) + s.model + .state() + .bodies + .first() + .is_some_and(|b| b.body.classify_point(solidcore_record::Vec3::new(p[0], p[1], p[2])).unwrap() == solidcraft_kernel::PointClass::Inside) } #[test] @@ -1640,6 +1755,46 @@ fn plate_with_a_cut(s: &mut Session, cut: [[f64; 2]; 2]) { run(s, "solid.extrude", json!({"sketch": "Cut", "through_all": true, "direction": "symmetric", "operation": "cut"})); } +/// A flange picked on the edge inside a notch is on that edge (#5306): the notch's bottom (y 30, +/// x 80 … 120) bends 90° up, inside (setback 3), its outer face on the edge (y 30 … 32), the base +/// set back under it; the plate's outer edge beside the notch keeps no flange. An edge of a hole +/// (a cut-out inside the plate) is refused, not taken for the outline's nearest edge. +#[test] +fn an_edge_flange_picked_inside_a_notch_is_on_the_notchs_edge() { + let mut s = Session::default(); + plate_with_a_cut(&mut s, [[80.0, -10.0], [120.0, 30.0]]); + run(&mut s, "sheet.flange", json!({"edges": [[100, 30, 2]], "height": 40, "angle": 90, "position": "inside"})); + let f = flat(&mut s); + let bends = f["bends"].as_array().cloned().unwrap_or_default(); + let span = |b: &Value| { + let (x0, x1) = (b["start"][0].as_f64().unwrap_or(f64::NAN), b["end"][0].as_f64().unwrap_or(f64::NAN)); + (x0.min(x1), x0.max(x1), b["start"][1].as_f64().unwrap_or(f64::NAN)) + }; + assert_eq!(bends.len(), 1, "{f}"); + let (lo, hi, y) = span(&bends[0]); + assert!((lo - 80.0).abs() < 1e-9 && (hi - 120.0).abs() < 1e-9 && y > 30.0, "{f}"); + assert_eq!(f["outline"].as_array().map(Vec::len), Some(1), "{f}"); + for (p, inside) in [ + ([100.0, 31.0, 20.0], true), + ([100.0, 30.5, 0.5], false), + ([100.0, 34.0, 1.0], true), + ([40.0, 1.0, 20.0], false), + ([160.0, 1.0, 20.0], false), + ([40.0, 0.2, 0.2], true), + ] { + assert_eq!(contains(&s, p), inside, "{p:?}"); + } + let state = s.model.state(); + let body = &state.bodies[0].body; + assert!(body.validity().is_empty() && body.shell_count() == 1); + drop(state); + + let mut s = Session::default(); + plate_with_a_cut(&mut s, [[80.0, 30.0], [120.0, 60.0]]); + let error = s.execute("sheet.flange", &json!({"edges": [[100, 30, 2]], "height": 40, "angle": 90})).unwrap_err().to_string(); + assert!(error.contains("not supported yet: a flange on the edge of a hole"), "{error}"); +} + #[test] fn edge_flanges_on_either_side_of_a_notch_span_the_side_they_were_picked_on() { // A notch 40 wide and 30 deep in the middle of the bottom edge leaves x 0 … 80 and 120 … 200 of @@ -1804,7 +1959,9 @@ fn a_flange_bent_inside_keeps_the_base_sketchs_arcs_in_the_flat_pattern_and_the_ // bottom edge (2 mm, R 1, K 0.5: setback 3 inside, half of it in the middle; BA π, panel // 37). With the bend inside or in the middle the base is cut back through the two lower // arcs: the DXF's outline was about 150 LINEs then, every arc as chords a quarter - // millimetre long, where the bend outside gives 8 LINEs and 4 ARCs. + // millimetre long, where the bend outside gives 6 LINEs and 4 ARCs: each of the flange's + // sides is one line through its bend and its panel (their union has no vertex where the + // two sides meet in line). let h = 8.0 * (1.0 - 0.5f64.sqrt()); // ∫ √(64 − z²): the area under an arc of radius 8, from its centre's height on. let under = |z: f64| z / 2.0 * (64.0 - z * z).sqrt() + 32.0 * (z / 8.0).asin(); @@ -1829,8 +1986,9 @@ fn a_flange_bent_inside_keeps_the_base_sketchs_arcs_in_the_flat_pattern_and_the_ let lines = shapes.iter().filter(|g| matches!(g, solidcraft_io::Geom2::Line(..))).count(); let radii: Vec = shapes.iter().filter_map(|g| if let solidcraft_io::Geom2::Arc { c, a, .. } = g { Some(c.dist(*a)) } else { None }).collect(); - // Eight lines of outline and the bend's centre line; the four corners. - assert_eq!((lines, radii.len(), shapes.len()), (9, 4, 13), "{position}"); + // Six lines of outline (the plate's top, left and right; the flange's two sides and its + // end) and the bend's centre line; the four corners. + assert_eq!((lines, radii.len(), shapes.len()), (7, 4, 11), "{position}"); assert!(radii.iter().all(|r| (r - 8.0).abs() < 1e-9), "{position}: {radii:?}"); // The plate less what lies below the bend line, ∫ 184 + 2·√(64 − (8 − y)²) from 0 to the // setback, and the flange along the trimmed edge, which runs from arc to arc. @@ -1998,7 +2156,7 @@ fn malformed_fold_points_are_rejected_atomically() { #[test] fn flat_dxf_preserves_exact_cutout_entities() { - use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; + use solidcore_record::{Loop2, Region2, Seg2, Vec2}; let mut s = Session::default(); base(&mut s, 100.0, 60.0); let mut sh = s.model.state().sheets[0].clone(); @@ -2099,8 +2257,8 @@ fn inherited_round_hole_survives_flange_and_unfold_in_flipped_frames() { let sh = s.model.state().sheets[0].clone(); let regions = sh.flat_regions().unwrap(); assert_eq!(regions[0].holes[0].segs.len(), 2); - assert!(regions[0].holes[0].segs.iter().all(|s| matches!(s, solidcraft_geom::Seg2::Arc { radius, .. } if (*radius - 5.0).abs() < 1e-9))); - let expected = regions.iter().map(solidcraft_geom::Region2::area).sum::() * 2.5; + assert!(regions[0].holes[0].segs.iter().all(|s| matches!(s, solidcore_record::Seg2::Arc { radius, .. } if (*radius - 5.0).abs() < 1e-9))); + let expected = regions.iter().map(solidcore_record::Region2::area).sum::() * 2.5; run(&mut s, "sheet.unfold", json!({})); assert!((volume(&mut s) - expected).abs() < 0.1); run(&mut s, "sheet.refold", json!({})); @@ -2115,7 +2273,7 @@ fn faces(s: &mut Session) -> (u64, u64) { #[test] fn elliptic_cut_out_stays_exact_in_the_flat_pattern_and_follows_arcs_when_folded() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; let mut s = Session::default(); base(&mut s, 100.0, 60.0); run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})); @@ -2165,7 +2323,7 @@ fn flipped_base_flange_keeps_its_elliptic_outline() { let regions = s.model.state().sheets[0].flat_regions().unwrap(); let outline = ®ions[0].outer.segs; assert!( - outline.len() == 4 && outline.iter().all(|x| matches!(x, solidcraft_geom::Seg2::Conic { .. })), + outline.len() == 4 && outline.iter().all(|x| matches!(x, solidcore_record::Seg2::Conic { .. })), "flip {flip}: {} segments", outline.len() ); @@ -2281,32 +2439,38 @@ fn cut_across_a_concave_notch_uses_crossings_not_just_contained_corners() { assert!((volume(&mut s) - 10500.0).abs() < 1e-6); } +/// A round flange stays an exact circle through unfold, refold and DXF (never a polyline), and a +/// cut close to its rim stays a hole in the flat pattern. #[test] -fn tiny_cut_inside_exact_circle_survives_unfold_refold_and_dxf() { +fn a_round_flange_stays_a_circle_and_keeps_a_cut_near_its_rim_through_unfold_refold_and_dxf() { for initially_flat in [false, true] { let mut s = Session::default(); run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Disc"})); run(&mut s, "sketch.circle.center", json!({"center": [0,0], "radius": 10})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "sheet.flange", json!({"sketch": "Disc"})); - let circle = s.model.state().sheets[0].base.outer.clone(); - let displayed = circle.polyline(1e-3); - let at = (displayed[0] + displayed[1]).normalized().unwrap() * 9.9998; - assert!(!circle.contains(at)); if initially_flat { run(&mut s, "sheet.unfold", json!({})); } - run(&mut s, "sketch.create", json!({"plane": "XY", "name": "TinyCut"})); - run(&mut s, "sketch.rectangle.two_point", json!({"p0": [at.x-0.000025,at.y-0.000025], "p1": [at.x+0.000025,at.y+0.000025]})); + // A 1 mm square whose outer side is 0.5 mm inside the rim. + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Cut"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [8.5,-0.5], "p1": [9.5,0.5]})); run(&mut s, "sketch.finish", json!({})); - run(&mut s, "solid.extrude", json!({"sketch": "TinyCut", "through_all": true, "operation": "cut", "direction": "symmetric"})); + run(&mut s, "solid.extrude", json!({"sketch": "Cut", "through_all": true, "operation": "cut", "direction": "symmetric"})); for stage in ["sheet.unfold", "sheet.refold"] { let regions = s.model.state().sheets[0].flat_regions().unwrap(); + let rim = ®ions[0].outer.segs; + assert!( + !rim.is_empty() && rim.iter().all(|seg| matches!(seg, solidcore_record::Seg2::Arc { radius, .. } if (*radius - 10.0).abs() < 1e-12)), + "{rim:?}" + ); assert_eq!(regions[0].holes.len(), 1); - assert!((regions[0].holes[0].signed_area().abs() - 2.5e-9).abs() < 1e-13); + assert!((regions[0].holes[0].signed_area().abs() - 1.0).abs() < 1e-12); assert_eq!(s.model.state().bodies.len(), 1); let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap().to_string(); - assert_eq!(solidcraft_io::read_dxf(&dxf).unwrap().len(), 5); + let drawn = solidcraft_io::read_dxf(&dxf).unwrap(); + assert!(drawn.iter().any(|g| matches!(g, solidcraft_io::Geom2::Circle(_, r) if (*r - 10.0).abs() < 1e-12)), "{drawn:?}"); + assert_eq!(drawn.len(), 5, "the circle and the square's four sides: {drawn:?}"); if stage == "sheet.unfold" && initially_flat { run(&mut s, "sheet.refold", json!({})); } @@ -2348,8 +2512,8 @@ fn unrelated_box_cut_preserves_logical_ring_sheet_compound() { assert_eq!(s.model.state().bodies.len(), 2); let state = s.model.state(); let body = &state.bodies.iter().find(|b| b.name == sheet_name).unwrap().body; - assert!(body.contains(solidcraft_geom::Vec3::new(50.0, 30.0, 1.25))); - assert!(!body.contains(solidcraft_geom::Vec3::new(57.0, 30.0, 1.25))); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(50.0, 30.0, 1.25)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(57.0, 30.0, 1.25)).unwrap(), solidcraft_kernel::PointClass::Outside); } } @@ -2384,9 +2548,9 @@ fn specialized_sheet_cuts_respect_component_and_explicit_participants() { fn ring_cut_preserves_retained_island_through_unfold_and_refold() { fn material_probes(s: &Session) { let body = &s.model.state().bodies[0].body; - assert!(body.contains(solidcraft_geom::Vec3::new(50.0, 30.0, 1.25))); - assert!(!body.contains(solidcraft_geom::Vec3::new(57.0, 30.0, 1.25))); - assert!(body.contains(solidcraft_geom::Vec3::new(65.0, 30.0, 1.25))); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(50.0, 30.0, 1.25)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(57.0, 30.0, 1.25)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(65.0, 30.0, 1.25)).unwrap(), solidcraft_kernel::PointClass::Inside); } let mut s = Session::default(); base(&mut s, 100.0, 60.0); @@ -2404,9 +2568,9 @@ fn ring_cut_preserves_retained_island_through_unfold_and_refold() { material_probes(&s); assert_eq!(flat(&mut s)["outline"].as_array().map(Vec::len), Some(2)); let regions = s.model.state().sheets[0].flat_regions().unwrap(); - assert!(regions.iter().any(|r| r.contains(solidcraft_geom::Vec2::new(50.0, 30.0)))); - assert!(!regions.iter().any(|r| r.contains(solidcraft_geom::Vec2::new(57.0, 30.0)))); - assert!(regions.iter().any(|r| r.contains(solidcraft_geom::Vec2::new(65.0, 30.0)))); + assert!(regions.iter().any(|r| r.contains(solidcore_record::Vec2::new(50.0, 30.0)))); + assert!(!regions.iter().any(|r| r.contains(solidcore_record::Vec2::new(57.0, 30.0)))); + assert!(regions.iter().any(|r| r.contains(solidcore_record::Vec2::new(65.0, 30.0)))); let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap().to_string(); let mut reopened = Session::default(); run(&mut reopened, "sketch.insert_dxf", json!({"text": dxf, "name": "RingBlank"})); @@ -2422,27 +2586,31 @@ fn ring_cut_preserves_retained_island_through_unfold_and_refold() { } fn retained_depth_check(s: &mut Session, want: f64, z0: f64, z1: f64) { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; assert!((volume(s) - want).abs() < 1e-6, "{} vs {want}", volume(s)); let state = s.model.state(); assert_eq!(state.sheets.len(), 1); assert_eq!(state.sheets[0].t, 2.5, "rule stock gauge is preserved"); - assert!(state.bodies.iter().any(|b| b.body.contains(Vec3::new(25.0, 25.0, (z0 + z1) * 0.5)))); - assert!(!state.bodies.iter().any(|b| b.body.contains(Vec3::new(25.0, 25.0, z0 - 0.1)))); - assert!(!state.bodies.iter().any(|b| b.body.contains(Vec3::new(25.0, 25.0, z1 + 0.1)))); - assert!(!state.bodies.iter().any(|b| b.body.contains(Vec3::new(10.0, 25.0, (z0 + z1) * 0.5)))); + assert!( + state.bodies.iter().any(|b| b.body.classify_point(Vec3::new(25.0, 25.0, (z0 + z1) * 0.5)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); + assert!(!state.bodies.iter().any(|b| b.body.classify_point(Vec3::new(25.0, 25.0, z0 - 0.1)).unwrap() == solidcraft_kernel::PointClass::Inside)); + assert!(!state.bodies.iter().any(|b| b.body.classify_point(Vec3::new(25.0, 25.0, z1 + 0.1)).unwrap() == solidcraft_kernel::PointClass::Inside)); + assert!( + !state.bodies.iter().any(|b| b.body.classify_point(Vec3::new(10.0, 25.0, (z0 + z1) * 0.5)).unwrap() == solidcraft_kernel::PointClass::Inside) + ); let bounds = state.bodies[0].mesh().bounds(); assert!((bounds.min.z - z0).abs() < 1e-8 && (bounds.max.z - z1).abs() < 1e-8, "{bounds:?}"); } -fn depth_step_reopen(s: &mut Session, suffix: &str, want: f64, inside: solidcraft_geom::Vec3, outside: solidcraft_geom::Vec3) { +fn depth_step_reopen(s: &mut Session, suffix: &str, want: f64, inside: solidcore_record::Vec3, outside: solidcore_record::Vec3) { let path = std::env::temp_dir().join(format!("solidcraft-depth-intersect-{suffix}-{}.step", std::process::id())); run(s, "file.export", json!({"path":path.to_string_lossy()})); let mut imported = Session::default(); run(&mut imported, "doc.open", json!({"path":path.to_string_lossy()})); assert!((volume(&mut imported) - want).abs() < 1e-6); - assert!(imported.model.state().bodies.iter().any(|b| b.body.contains(inside))); - assert!(!imported.model.state().bodies.iter().any(|b| b.body.contains(outside))); + assert!(imported.model.state().bodies.iter().any(|b| b.body.classify_point(inside).unwrap() == solidcraft_kernel::PointClass::Inside)); + assert!(!imported.model.state().bodies.iter().any(|b| b.body.classify_point(outside).unwrap() == solidcraft_kernel::PointClass::Inside)); std::fs::remove_file(path).unwrap(); } @@ -2472,7 +2640,7 @@ fn dxf_outline_only(text: &str) -> String { #[test] fn partial_depth_intersect_retains_bottom_top_and_middle_material_through_history_and_exports() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; for (offset, z0, z1, layers) in [ (0.0, 0.0, 1.0, vec![("top", 1.0, 2.5)]), (1.5, 1.5, 2.5, vec![("bottom", 0.0, 1.5)]), @@ -2520,7 +2688,7 @@ fn partial_depth_intersect_retains_bottom_top_and_middle_material_through_histor #[test] fn partial_depth_intersect_preserves_prior_pockets_and_actual_interval_intersections() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut s = Session::default(); base(&mut s, 100.0, 60.0); rectangle_tool(&mut s, "OldPocket", [20.0, 20.0], [25.0, 30.0]); @@ -2534,10 +2702,10 @@ fn partial_depth_intersect_preserves_prior_pockets_and_actual_interval_intersect assert!((volume(&mut s) - 75.0).abs() < 1e-6); let state = s.model.state(); let body = &state.bodies[0].body; - assert!(!body.contains(Vec3::new(22.0, 25.0, 0.75))); - assert!(body.contains(Vec3::new(22.0, 25.0, 1.25))); - assert!(body.contains(Vec3::new(27.0, 25.0, 0.75))); - assert!(!body.contains(Vec3::new(27.0, 25.0, 0.25))); + assert_eq!(body.classify_point(Vec3::new(22.0, 25.0, 0.75)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(22.0, 25.0, 1.25)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(27.0, 25.0, 0.75)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(27.0, 25.0, 0.25)).unwrap(), solidcraft_kernel::PointClass::Outside); } let records = s.model.state().sheets[0].pockets.clone(); run(&mut s, "solid.extrude", json!({"sketch":"RetainDepth","distance":1.5,"start_offset":0.25,"operation":"intersect"})); @@ -2554,7 +2722,7 @@ fn partial_depth_intersect_preserves_prior_pockets_and_actual_interval_intersect #[test] fn partial_depth_intersect_keeps_disconnected_tool_islands_and_annular_curves() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut s = Session::default(); base(&mut s, 100.0, 60.0); rectangle_tool(&mut s, "Islands", [20.0, 20.0], [30.0, 30.0]); @@ -2569,9 +2737,9 @@ fn partial_depth_intersect_keeps_disconnected_tool_islands_and_annular_curves() assert!((volume(&mut s) - 200.0).abs() < 1e-6); assert_eq!(s.model.state().sheets[0].flat_regions().unwrap().len(), 2); for x in [25.0, 65.0] { - assert!(s.model.state().bodies[0].body.contains(Vec3::new(x, 25.0, 0.5))); + assert_eq!(s.model.state().bodies[0].body.classify_point(Vec3::new(x, 25.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Inside); } - assert!(!s.model.state().bodies[0].body.contains(Vec3::new(45.0, 25.0, 0.5))); + assert_eq!(s.model.state().bodies[0].body.classify_point(Vec3::new(45.0, 25.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); } depth_step_reopen(&mut s, "islands", 200.0, Vec3::new(65.0, 25.0, 0.5), Vec3::new(45.0, 25.0, 0.5)); let mut ring = Session::default(); @@ -2590,9 +2758,9 @@ fn partial_depth_intersect_keeps_disconnected_tool_islands_and_annular_curves() let area: f64 = state.sheets[0].flat_regions().unwrap().iter().map(|r| r.area()).sum(); assert!((area - 75.0 * PI).abs() < 1e-8); assert!((volume(&mut ring) - 75.0 * PI).abs() < 0.1); - assert!(state.bodies[0].body.contains(Vec3::new(57.0, 30.0, 0.5))); - assert!(!state.bodies[0].body.contains(Vec3::new(50.0, 30.0, 0.5))); - assert!(!state.bodies[0].body.contains(Vec3::new(57.0, 30.0, 1.5))); + assert_eq!(state.bodies[0].body.classify_point(Vec3::new(57.0, 30.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(state.bodies[0].body.classify_point(Vec3::new(50.0, 30.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(state.bodies[0].body.classify_point(Vec3::new(57.0, 30.0, 1.5)).unwrap(), solidcraft_kernel::PointClass::Outside); } let dxf = run(&mut ring, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap().to_string(); assert!(dxf.contains("POCKET_TOP_Z1.000000_TO_2.500000_MM")); @@ -2615,7 +2783,7 @@ fn partial_depth_intersect_of_material_already_removed_by_a_pocket_is_refused() #[test] fn partial_depth_intersect_flipped_tool_and_transferred_sheet_keep_depth_side_and_world_pose() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut flipped = Session::default(); base(&mut flipped, 100.0, 60.0); run(&mut flipped, "sketch.create", json!({"name":"FlippedTool","plane":{"origin":[0,0,2.5],"x_dir":[1,0,0],"y_dir":[0,-1,0]}})); @@ -2629,7 +2797,7 @@ fn partial_depth_intersect_flipped_tool_and_transferred_sheet_keep_depth_side_an base(&mut s, 100.0, 60.0); rectangle_tool(&mut s, "RetainDepth", [20.0, 20.0], [30.0, 30.0]); run(&mut s, "solid.extrude", json!({"sketch":"RetainDepth","distance":1,"start_offset":0.5,"operation":"intersect","name":"RetainSlab"})); - let before = s.world_state().bodies[0].mesh().bounds(); + let before = s.world_state().unwrap().bodies[0].mesh().bounds(); let name = s.model.state().sheets[0].body.clone(); let destination = run(&mut s, "component.create", json!({"name":"Destination","parent":0,"grounded":false})); let owner = destination["component"].as_u64().unwrap(); @@ -2648,31 +2816,31 @@ fn partial_depth_intersect_flipped_tool_and_transferred_sheet_keep_depth_side_an assert_eq!(sh.pockets.len(), 2); assert_eq!(state.body(&name).unwrap().component, owner); assert!(state.body(&name).unwrap().transferred); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = &world.body(&name).unwrap().body; - assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 0.25))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 2.0))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 0.25)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 2.0)).unwrap(), solidcraft_kernel::PointClass::Outside); let bounds = world.body(&name).unwrap().mesh().bounds(); assert!(before.min.dist(bounds.min) < 1e-8 && before.max.dist(bounds.max) < 1e-8); assert!((solidcraft_kernel::measure(body).unwrap().volume - 100.0).abs() < 1e-6); } let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - let reopened_world = reopened.world_state(); + let reopened_world = reopened.world_state().unwrap(); let body = &reopened_world.body(&name).unwrap().body; - assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Inside); assert!((solidcraft_kernel::measure(body).unwrap().volume - 100.0).abs() < 1e-6); run(&mut reopened, "timeline.edit", json!({"feature":"RetainSlab","set":{"extent":{"distance":"1.5"}}})); - let world = reopened.world_state(); + let world = reopened.world_state().unwrap(); let body = &world.body(&name).unwrap().body; assert!((solidcraft_kernel::measure(body).unwrap().volume - 150.0).abs() < 1e-6); - assert!(body.contains(Vec3::new(25.0, 25.0, 1.75))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 2.25))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 1.75)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 2.25)).unwrap(), solidcraft_kernel::PointClass::Outside); } #[test] fn partial_depth_intersect_full_gauge_in_rotated_frames_does_not_invent_pockets() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; for (angle, translate) in [(37.0, [30.0, 20.0, 10.0]), (121.0, [12345.678, 98765.432, 4321.123])] { let mut s = Session::default(); base(&mut s, 100.0, 60.0); @@ -2715,12 +2883,12 @@ fn partial_depth_intersect_full_gauge_in_rotated_frames_does_not_invent_pockets( run(&mut s, command, json!({})); } assert!(s.model.state().sheets[0].pockets.is_empty(), "full gauge must not acquire roundoff-depth pockets"); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = &world.body(&name).unwrap().body; assert!((solidcraft_kernel::measure(body).unwrap().volume - 250.0).abs() < 1e-5); - assert!(body.contains(Vec3::new(25.0, 25.0, 0.1))); - assert!(body.contains(Vec3::new(25.0, 25.0, 2.4))); - assert!(!body.contains(Vec3::new(10.0, 25.0, 1.0))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 0.1)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 2.4)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(10.0, 25.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Outside); } let mut cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!(cold.model.state().sheets[0].pockets.is_empty()); @@ -2731,26 +2899,26 @@ fn partial_depth_intersect_full_gauge_in_rotated_frames_does_not_invent_pockets( run(&mut s, command, json!({})); } assert_eq!(s.model.state().sheets[0].pockets.len(), 2); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = &world.body(&name).unwrap().body; let measured = solidcraft_kernel::measure(body).unwrap().volume; assert!((measured - 100.0).abs() < 1e-5, "retained volume {measured}"); - assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 0.1))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 2.4))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 0.1)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 2.4)).unwrap(), solidcraft_kernel::PointClass::Outside); } let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - let world = cold.world_state(); + let world = cold.world_state().unwrap(); let body = &world.body(&name).unwrap().body; assert!((solidcraft_kernel::measure(body).unwrap().volume - 100.0).abs() < 1e-5); - assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 0.1))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 0.1)).unwrap(), solidcraft_kernel::PointClass::Outside); } } #[test] fn partial_depth_intersect_planar_to_object_retains_current_target_depth() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut s = Session::default(); base(&mut s, 100.0, 60.0); let name = s.model.state().sheets[0].body.clone(); @@ -2764,9 +2932,9 @@ fn partial_depth_intersect_planar_to_object_retains_current_target_depth() { let state = s.model.state(); let body = &state.body(&name).unwrap().body; assert!((solidcraft_kernel::measure(body).unwrap().volume - 100.0).abs() < 1e-6); - assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 0.1))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 2.0))); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 1.0)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 0.1)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 2.0)).unwrap(), solidcraft_kernel::PointClass::Outside); assert_eq!(state.sheets[0].pockets.len(), 2); assert!((solidcraft_kernel::measure(&state.body("Roof").unwrap().body).unwrap().volume - 100.0).abs() < 1e-6); } @@ -2798,7 +2966,7 @@ fn partial_depth_intersect_curved_to_object_refuses_unrepresentable_depth_atomic #[test] fn partial_depth_intersect_curved_to_object_preserves_current_trimmed_cap_footprint() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let mut s = Session::default(); base(&mut s, 100.0, 60.0); let name = s.model.state().sheets[0].body.clone(); @@ -2811,8 +2979,8 @@ fn partial_depth_intersect_curved_to_object_preserves_current_trimmed_cap_footpr let ts = tool_session.model.state(); let witness = &ts.body("TrimWitness").unwrap().body; assert!((solidcraft_kernel::measure(witness).unwrap().volume - (100.0 - 4.0 * std::f64::consts::PI)).abs() < 0.01); - assert!(witness.contains(Vec3::new(21.0, 21.0, 0.5))); - assert!(!witness.contains(Vec3::new(25.0, 25.0, 0.5))); + assert_eq!(witness.classify_point(Vec3::new(21.0, 21.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(witness.classify_point(Vec3::new(25.0, 25.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); run(&mut s, "solid.extrude", json!({"sketch":"Tool","to":[27,25,10],"operation":"intersect","participants":[name]})); for command in [None, Some("sheet.unfold"), Some("sheet.refold")] { if let Some(command) = command { @@ -2824,12 +2992,15 @@ fn partial_depth_intersect_curved_to_object_preserves_current_trimmed_cap_footpr assert!((measured - (100.0 - 4.0 * std::f64::consts::PI)).abs() < 0.01); let area: f64 = state.sheets[0].flat_regions().unwrap().iter().map(|r| r.area()).sum(); assert!((area - (100.0 - 4.0 * std::f64::consts::PI)).abs() < 1e-8); - assert!(body.contains(Vec3::new(21.0, 21.0, 0.5))); - assert!(!body.contains(Vec3::new(25.0, 25.0, 0.5))); - assert!(!body.contains(Vec3::new(21.0, 21.0, 1.5))); + assert_eq!(body.classify_point(Vec3::new(21.0, 21.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(25.0, 25.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!(body.classify_point(Vec3::new(21.0, 21.0, 1.5)).unwrap(), solidcraft_kernel::PointClass::Outside); } let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert!(!cold.model.state().body(&name).unwrap().body.contains(Vec3::new(25.0, 25.0, 0.5))); + assert_eq!( + cold.model.state().body(&name).unwrap().body.classify_point(Vec3::new(25.0, 25.0, 0.5)).unwrap(), + solidcraft_kernel::PointClass::Outside + ); let dxf = run(&mut s, "sheet.export_dxf", json!({"body":name}))["dxf"].as_str().unwrap().to_string(); assert!(dxf.contains("POCKET_TOP_Z1.000000_TO_2.500000_MM")); let outline = dxf_outline_only(&dxf); @@ -2839,13 +3010,16 @@ fn partial_depth_intersect_curved_to_object_preserves_current_trimmed_cap_footpr run(&mut outline_import, "sketch.finish", json!({})); run(&mut outline_import, "solid.extrude", json!({"distance":1,"profiles":[{"point":[21,21]}]})); assert!((volume(&mut outline_import) - (100.0 - 4.0 * std::f64::consts::PI)).abs() < 0.01); - assert!(!outline_import.model.state().bodies[0].body.contains(Vec3::new(25.0, 25.0, 0.5))); + assert_eq!( + outline_import.model.state().bodies[0].body.classify_point(Vec3::new(25.0, 25.0, 0.5)).unwrap(), + solidcraft_kernel::PointClass::Outside + ); let path = std::env::temp_dir().join(format!("solidcraft-current-trim-cap-{}.step", std::process::id())); run(&mut s, "file.export", json!({"path":path.to_string_lossy(),"bodies":[name]})); let mut imported = Session::default(); run(&mut imported, "doc.open", json!({"path":path.to_string_lossy()})); assert!((volume(&mut imported) - (100.0 - 4.0 * std::f64::consts::PI)).abs() < 0.01); - assert!(!imported.model.state().bodies[0].body.contains(Vec3::new(25.0, 25.0, 0.5))); + assert_eq!(imported.model.state().bodies[0].body.classify_point(Vec3::new(25.0, 25.0, 0.5)).unwrap(), solidcraft_kernel::PointClass::Outside); std::fs::remove_file(path).unwrap(); } @@ -2875,7 +3049,7 @@ fn partial_depth_intersect_sub_extrusion_resolution_layers_refuse_atomically() { assert!(error.contains("resolution") || error.contains("distance is zero") || error.contains("sheet machining"), "{error}"); assert_eq!(s.doc.to_json(), before); assert!(s.model.state().sheets[0].pockets.is_empty()); - assert!((solidcraft_kernel::measure(&s.world_state().body(&name).unwrap().body).unwrap().volume - 15000.0).abs() < 1e-5); + assert!((solidcraft_kernel::measure(&s.world_state().unwrap().body(&name).unwrap().body).unwrap().volume - 15000.0).abs() < 1e-5); } } @@ -3094,6 +3268,397 @@ fn fold_at_a_tab_root_names_the_real_cause() { run(&mut ok, "sheet.fold", json!({"points": [[40, 51, 0.8], [60, 51, 0.8]], "fixed": [50, 25, 0.8]})); } +/// The sheet of the folds across slanted edges below: 2 mm thick, R 1, K 0.4. +fn t2_blank(s: &mut Session, outline: Value) { + run(s, "sheet.manage_rules", json!({"name": "T2", "thickness": "2 mm", "bend_radius": "1 mm", "k_factor": "0.4", "active": true})); + run(s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + run(s, "sketch.line", json!({"points": outline, "closed": true})); + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "Blank"})); +} + +/// 160 long, 50 wide at x = 0 and 100 wide at x = 160: 12000 mm², and 75 wide at its midline. +fn t2_trapezoid(s: &mut Session) { + t2_blank(s, json!([[0, -25], [160, -50], [160, 50], [0, 25]])); +} + +/// A point on `t2_trapezoid`'s lower slanted side, on the sheet's top. +fn t2_slant(x: f64) -> [f64; 3] { + [x, -25.0 - 25.0 * x / 160.0, 2.0] +} + +/// What the T2 sheet's flat pattern says it weighs. A bend of turn θ takes θ·(R + K·T) of the flat +/// and has θ·T·(R + T/2) of section, so it adds θ·T²·(½ − K) per mm across it; ruled ends keep the +/// zone's mean width at its centre line's length, however askew they are. +fn t2_volume_from_flat(f: &Value) -> f64 { + let area = |loops: &Value| -> f64 { + let ring = |l: &Value| { + let p: Vec<(f64, f64)> = + l.as_array().into_iter().flatten().map(|q| (q[0].as_f64().unwrap_or(f64::NAN), q[1].as_f64().unwrap_or(f64::NAN))).collect(); + (0..p.len()).map(|i| p[i].0 * p[(i + 1) % p.len()].1 - p[(i + 1) % p.len()].0 * p[i].1).sum::().abs() / 2.0 + }; + loops.as_array().into_iter().flatten().map(ring).sum() + }; + let bends: f64 = f["bends"] + .as_array() + .into_iter() + .flatten() + .map(|b| b["angle_deg"].as_f64().unwrap_or(f64::NAN).to_radians() * 0.4 * b["length"].as_f64().unwrap_or(f64::NAN)) + .sum(); + (area(&f["outline"]) - area(&f["cutouts"])) * 2.0 + bends +} + +/// The midline of a trapezoid crosses its slanted sides: the bend zone isn't square across, and +/// the sheet keeps its real outline (#10621). +#[test] +fn a_fold_across_slanted_edges_keeps_the_sheets_outline() { + let zone = FRAC_PI_2 * 1.8; + let flat_volume = 12000.0 * 2.0; + let want = flat_volume + 75.0 * FRAC_PI_2 * 0.4; + // Both legs are as long, R + T + 80 - BA / 2 high when folded. + let (wide, narrow) = ([80.0 + zone / 2.0 - 3.0, 160.0], [0.0, 80.0 - zone / 2.0 + 3.0]); + for (name, fixed, x) in + [("no side named: the larger stays", None, wide), ("the wide end", Some([150, 0, 0]), wide), ("the narrow end", Some([10, 0, 0]), narrow)] + { + let mut s = Session::default(); + t2_trapezoid(&mut s); + let mut fold = json!({"points": [[80, -60, 2], [80, 60, 2]]}); + if let Some(p) = fixed { + fold["fixed"] = json!(p); + } + run(&mut s, "sheet.fold", fold); + let v = volume(&mut s); + assert!(rel(v, want) < 1e-5, "{name}: volume {v} vs {want}"); + let b = bbox(&mut s); + let at = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + assert!((at(&b["min"][0]) - x[0]).abs() < 1e-6 && (at(&b["max"][0]) - x[1]).abs() < 1e-6, "{name}: {b}"); + assert!((at(&b["max"][2]) - (3.0 + 80.0 - zone / 2.0)).abs() < 1e-6, "{name}: {b}"); + let f = flat(&mut s); + assert!((at(&f["flat_size_mm"][0]) - 160.0).abs() < 1e-6 && (at(&f["flat_size_mm"][1]) - 100.0).abs() < 1e-6, "{name}: {f}"); + assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(0), "{name}: the outline is the sheet's, not a trimmed rectangle: {f}"); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(1), "{name}: {f}"); + assert!((at(&f["bends"][0]["length"]) - 75.0).abs() < 1e-6 && (at(&f["bends"][0]["allowance"]) - zone).abs() < 1e-9, "{name}: {f}"); + assert!(rel(t2_volume_from_flat(&f), want) < 1e-9, "{name}: {f}"); + // Flat again it weighs the sheet it was, and it folds back the same. + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + assert!(rel(unfolded, flat_volume) < 1e-9, "{name}: unfolded {unfolded}"); + run(&mut s, "sheet.refold", json!({})); + let refolded = volume(&mut s); + assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}"); + } +} + +/// A fold across slanted edges leaves panels with their real outlines, so flanges and other folds +/// go on it as on any fold, before or after it. +#[test] +fn flanges_and_folds_go_on_a_sheet_folded_across_slanted_edges() { + let mid = json!({"points": [[80, -60, 2], [80, 60, 2]], "fixed": [150, 0, 0]}); + let wide = json!({"edges": [[160, 0, 2]], "height": 20}); + let slanted = json!({"edges": [t2_slant(120.0)], "height": 20}); + let flange = "sheet.flange"; + let fold = "sheet.fold"; + let cases: [(&str, Vec<(&str, &Value)>); 3] = [ + ("flange on the wide end after", vec![(fold, &mid), (flange, &wide)]), + ("flange on the wide end before", vec![(flange, &wide), (fold, &mid)]), + ("flange on the slanted side after", vec![(fold, &mid), (flange, &slanted)]), + ]; + let mut volumes = Vec::new(); + for (name, steps) in cases { + let mut s = Session::default(); + t2_trapezoid(&mut s); + for (id, p) in steps { + run(&mut s, id, p.clone()); + } + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{name}: {f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "{name}: volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + volumes.push(v); + } + // A flange beside the fold: the order doesn't matter. + assert!(rel(volumes[0], volumes[1]) < 1e-6, "{volumes:?}"); + + // A flange along the whole slanted side has its bend where the fold would cross: refused, + // for that reason, as on a rectangle. + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, flange, slanted.clone()); + match s.execute(fold, &mid) { + Ok(v) => panic!("the fold goes through the flange's bend: {v}"), + Err(e) => assert!(e.to_string().contains("a fold through a flange's bend"), "{e}"), + } + + // A second fold, 87.5 wide at x = 120 and square to the first, or askew across the same sides. + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, fold, mid.clone()); + run(&mut s, fold, json!({"points": [[120, -60, 2], [120, 60, 2]], "fixed": [150, 0, 0]})); + let want = 24000.0 + (75.0 + 87.5) * FRAC_PI_2 * 0.4; + let v = volume(&mut s); + assert!(rel(v, want) < 1e-5, "volume {v} vs {want}"); + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, fold, mid.clone()); + run(&mut s, fold, json!({"points": [[100, 60, 2], [140, -60, 2]], "fixed": [155, 0, 0]})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + + // Askew on the blank itself. + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, fold, json!({"points": [[60, 60, 2], [100, -60, 2]], "fixed": [155, 0, 0]})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); +} + +/// Walls leaning at 70° close the trapezoid's corner on a slanted line, so a fold across the wide +/// end's wall crosses a slanted edge of a flange: the wall widens evenly up to its top, and the +/// bend with it (#10621). +#[test] +fn a_fold_across_a_flanges_slanted_end_folds() { + let lean = 70f64.to_radians(); + let walls = json!({"edges": [[160, 0, 2], t2_slant(120.0)], "height": 40, "angle": "70 deg"}); + // The wall's outer face, from where the wall alone reaches: its top's outer corner is the + // farthest out, its inner corner the highest. + let mut one = Session::default(); + t2_trapezoid(&mut one); + run(&mut one, "sheet.flange", json!({"edges": [[160, 0, 2]], "height": 40, "angle": "70 deg"})); + let b = bbox(&mut one); + let (x_out, z_in) = (b["max"][0].as_f64().unwrap_or(f64::NAN), b["max"][2].as_f64().unwrap_or(f64::NAN)); + let z_out = z_in - 2.0 * lean.cos(); + let mut lengths = Vec::new(); + for z in [14.0, 22.0, 30.0] { + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, "sheet.flange", walls.clone()); + let x = x_out - (z_out - z) / lean.tan(); + run(&mut s, "sheet.fold", json!({"points": [[x, -90.0, z], [x, 90.0, z]], "angle": "30 deg"})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(3), "z {z}: {f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "z {z}: volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + lengths.push(f["bends"][2]["length"].as_f64().unwrap_or(f64::NAN)); + } + let (rise, more) = (lengths[1] - lengths[0], lengths[2] - lengths[1]); + assert!(rise > 1e-3 && (rise - more).abs() < 1e-6, "{lengths:?}"); +} + +/// A blank whose outer outline is curved: `draw` makes it in a sketch, on the T2 sheet. +fn t2_curved_blank(s: &mut Session, draw: &[(&str, Value)], k: &str) { + run(s, "sheet.manage_rules", json!({"name": "T2", "thickness": "2 mm", "bend_radius": "1 mm", "k_factor": k, "active": true})); + run(s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + for (id, p) in draw { + run(s, id, p.clone()); + } + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "Blank"})); +} + +/// A circle or an ellipse as the sheet's outer outline, folded at `x` off its centre. The bend +/// adds θ·T²·(½ − K) per mm of the zone's mean width, which is the material in the zone over BA: +/// for semi-axes a (across the fold) and b, the chord (b / a)·2√(a² − s²) over the zone. The bend +/// allowance sets how high the part that folds stands, so K shows there: compensation. +#[test] +fn a_fold_across_a_round_outer_outline_is_compensated() { + let circle = ("sketch.circle.center", json!({"center": [0, 0], "radius": 50})); + let ellipse = ("sketch.ellipse", json!({"center": [0, 0], "major": [80, 0], "minor_radius": 40})); + for (name, draw, a, b) in [("circle", circle, 50.0_f64, 50.0_f64), ("ellipse", ellipse, 80.0_f64, 40.0_f64)] { + for (x, k) in [(10.0_f64, 0.4_f64), (-20.0, 0.3), (10.0, 0.5)] { + let zone = FRAC_PI_2 * (1.0 + k * 2.0); + let integral = |s: f64| s * (a * a - s * s).sqrt() + a * a * (s / a).asin(); + let in_zone = (b / a) * (integral(x + zone / 2.0) - integral(x - zone / 2.0)); + let want = PI * a * b * 2.0 + FRAC_PI_2 * 4.0 * (0.5 - k) * in_zone / zone; + let mut s = Session::default(); + t2_curved_blank(&mut s, std::slice::from_ref(&draw), &k.to_string()); + run(&mut s, "sheet.fold", json!({"points": [[x, -200, 2], [x, 200, 2]], "fixed": [-(a - 1.0) * x.signum(), 0, 2]})); + let name = format!("{name} at x = {x}, K {k}"); + // The volume measure works on facets: a flat ellipse reads about 1e-4 low on its own. + let v = volume(&mut s); + assert!(rel(v, want) < 3e-4, "{name}: volume {v} vs {want}"); + // The part past the bend stands R + T + its flat length past the zone. + let leg = a - x.abs() - zone / 2.0; + let high = bbox(&mut s)["max"][2].as_f64().unwrap_or(f64::NAN); + assert!((high - (3.0 + leg)).abs() < 1e-3, "{name}: {high} high vs {}", 3.0 + leg); + // The flat pattern is the blank as drawn, the bend line on the zone's centre line. + let f = flat(&mut s); + let at = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + // (The size is measured on 0.001 mm chords, so up to that short on each side.) + assert!((at(&f["flat_size_mm"][0]) - 2.0 * a).abs() < 2.5e-3 && (at(&f["flat_size_mm"][1]) - 2.0 * b).abs() < 2.5e-3, "{name}: {f}"); + let chord = 2.0 * b * (1.0 - (x / a).powi(2)).sqrt(); + assert!((at(&f["bends"][0]["length"]) - chord).abs() < 1e-3 && (at(&f["bends"][0]["allowance"]) - zone).abs() < 1e-9, "{name}: {f}"); + assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(0), "{name}: {f}"); + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + assert!(rel(unfolded, PI * a * b * 2.0) < 3e-4, "{name}: unfolded {unfolded}"); + run(&mut s, "sheet.refold", json!({})); + let refolded = volume(&mut s); + assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}"); + } + } +} + +/// Any curve, not only conics: a closed spline, an open spline closed by a line, an arc with lines, +/// each folded where its curves cross the zone, then folded again. +#[test] +fn a_fold_crosses_any_curve_of_the_outer_outline() { + let spline = vec![( + "sketch.spline.fit_point", + json!({"points": [[70, -5], [40, 40], [0, 40], [-50, 35], [-85, 0], [-40, -50], [0, -35], [35, -25]], "periodic": true}), + )]; + let open = vec![ + ("sketch.spline.fit_point", json!({"points": [[-60, 0], [-30, 45], [10, 30], [60, 50]]})), + ("sketch.line", json!({"points": [[60, 50], [60, -30], [-60, -30], [-60, 0]]})), + ]; + let d_shape = vec![ + ("sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})), + ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})), + ]; + for (name, draw, line_at) in [("closed spline", spline, 5.0), ("open spline and lines", open, 7.0), ("arc and lines", d_shape, 20.0)] { + let mut s = Session::default(); + t2_curved_blank(&mut s, &draw, "0.4"); + let flat_volume = volume(&mut s); + run(&mut s, "sheet.fold", json!({"points": [[line_at, -200, 2], [line_at, 200, 2]]})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(1), "{name}: {f}"); + // The bend adds what it adds to the flat sheet, here on a centre line that varies little. + let gain = v - flat_volume; + let want = f["bends"][0]["length"].as_f64().unwrap_or(f64::NAN) * FRAC_PI_2 * 0.4; + assert!((gain - want).abs() < 0.03 * want + 1.5, "{name}: gained {gain} vs {want}"); + // Flat again it weighs what it did, and it folds back the same. + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + assert!(rel(unfolded, flat_volume) < 3e-4, "{name}: unfolded {unfolded} vs {flat_volume}"); + run(&mut s, "sheet.refold", json!({})); + let refolded = volume(&mut s); + assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}"); + // A second fold across the part that stayed, where the curves cross it too. + run(&mut s, "sheet.fold", json!({"points": [[line_at - 30.0, -200, 2], [line_at - 30.0, 200, 2]], "fixed": [line_at - 50.0, 0, 2]})); + let f = flat(&mut s); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{name}: second fold: {f}"); + } +} + +/// A curved outline with a hole across the zone: the bend adds what the material in the zone +/// holds, between the outline's chord and the hole's. +#[test] +fn a_cut_out_crosses_a_fold_across_a_round_outer_outline() { + let (r, hole, x, k) = (50.0_f64, 15.0_f64, 10.0_f64, 0.4_f64); + let zone = FRAC_PI_2 * (1.0 + k * 2.0); + let integral = |a: f64, s: f64| { + let s = s.clamp(-a, a); + s * (a * a - s * s).sqrt() + a * a * (s / a).asin() + }; + let in_zone = integral(r, x + zone / 2.0) - integral(r, x - zone / 2.0) - (integral(hole, zone / 2.0) - integral(hole, -zone / 2.0)); + let want = PI * (r * r - hole * hole) * 2.0 + FRAC_PI_2 * 4.0 * (0.5 - k) * in_zone / zone; + let mut s = Session::default(); + t2_curved_blank(&mut s, &[("sketch.circle.center", json!({"center": [0, 0], "radius": r}))], "0.4"); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Hole"})); + run(&mut s, "sketch.circle.center", json!({"center": [x, 0], "radius": hole})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Hole", "distance": 20, "direction": "symmetric", "operation": "cut", "targets": ["Body1"]})); + run(&mut s, "sheet.fold", json!({"points": [[x, -200, 2], [x, 200, 2]], "fixed": [-49, 0, 2]})); + let v = volume(&mut s); + assert!(rel(v, want) < 3e-4, "volume {v} vs {want}"); + let f = flat(&mut s); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "the hole parts the bend line: {f}"); +} + +/// Curves away from the zone stay curves too, and a flange still goes on either side of a fold +/// across the straight part of a curved outline (the side with the arc gives way to chords). +#[test] +fn flanges_go_on_a_curved_outline_folded_across_its_straight_part() { + let d_shape = vec![ + ("sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})), + ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})), + ]; + let fold = json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [-50, 0, 2]}); + // The side that stays is square; the arc goes up with the side that folds. + let mut s = Session::default(); + t2_curved_blank(&mut s, &d_shape, "0.4"); + run(&mut s, "sheet.fold", fold.clone()); + run(&mut s, "sheet.flange", json!({"edges": [[-60, 0, 2]], "height": 20})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 3e-4, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + // The side with the arc stays; the flange goes on the square side that folded. + let mut s = Session::default(); + t2_curved_blank(&mut s, &d_shape, "0.4"); + run(&mut s, "sheet.fold", json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [40, 0, 2]})); + let high = bbox(&mut s)["max"][2].as_f64().unwrap_or(f64::NAN); + run(&mut s, "sheet.flange", json!({"edges": [[-20.0 + FRAC_PI_2 * 0.9 - 3.0, 0, high]], "height": 20})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 3e-4, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); +} + +/// A sharp corner in the zone stays refused, by name: the material beside it wouldn't hang from +/// anything. A fold clear of it, on the same outline, folds. Where the lines run smoothly into the +/// arc is no corner. +#[test] +fn a_corner_of_a_curved_outline_in_the_zone_is_named() { + let stepped = vec![ + ("sketch.line", json!({"points": [[0, 50], [-20, 50], [-20, 30], [-60, 30], [-60, -30], [-20, -30], [-20, -50], [0, -50]]})), + ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})), + ]; + let mut s = Session::default(); + t2_curved_blank(&mut s, &stepped, "0.4"); + match s.execute("sheet.fold", &json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [40, 0, 2]})) { + Ok(v) => panic!("the zone holds the corners at x = -20: {v}"), + Err(e) => assert!(e.to_string().contains("corner of the sheet's outline"), "{e}"), + } + run(&mut s, "sheet.fold", json!({"points": [[0, -200, 2], [0, 200, 2]], "fixed": [40, 0, 2]})); +} + +/// A circle or an ellipse cut out across a fold that crosses slanted edges, before the fold or in +/// the flat after it: the outline's edges and the cut-out's both cross the bend. +#[test] +fn round_cut_outs_cross_a_fold_across_slanted_edges() { + let zone = FRAC_PI_2 * 1.8; + let fold = json!({"points": [[80, -60, 2], [80, 60, 2]], "fixed": [150, 0, 0]}); + let cut = |s: &mut Session, draw: &(&str, Value)| { + run(s, "sketch.create", json!({"plane": "XY", "name": "Hole"})); + run(s, draw.0, draw.1.clone()); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": "Hole", "distance": 20, "direction": "symmetric", "operation": "cut", "targets": ["Body1"]})); + }; + let circle = ("sketch.circle.center", json!({"center": [80, 0], "radius": 15})); + let ellipse = ("sketch.ellipse", json!({"center": [80, 0], "major": [100, 0], "minor_radius": 10})); + for (name, draw, a, b) in [("circle", circle, 15.0_f64, 15.0_f64), ("ellipse", ellipse, 20.0_f64, 10.0_f64)] { + // What it takes out of the zone: its chord (b / a)·2√(a² − s²) across s in ±BA / 2. + let h = zone / 2.0; + let in_zone = 2.0 * (b / a) * (h * (a * a - h * h).sqrt() + a * a * (h / a).asin()); + let flat_volume = (12000.0 - PI * a * b) * 2.0; + let want = flat_volume + (75.0 - in_zone / zone) * FRAC_PI_2 * 0.4; + + let mut before = Session::default(); + t2_trapezoid(&mut before); + cut(&mut before, &draw); + run(&mut before, "sheet.fold", fold.clone()); + let v = volume(&mut before); + assert!(rel(v, want) < 1e-5, "{name}: volume {v} vs {want}"); + // One cut-out, and the centre line in two pieces either side of it. + let f = flat(&mut before); + assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(1), "{name}: {f}"); + let bends = f["bends"].as_array().cloned().unwrap_or_default(); + let length: f64 = bends.iter().map(|b| b["length"].as_f64().unwrap_or(f64::NAN)).sum(); + assert!(bends.len() == 2 && (length - (75.0 - 2.0 * b)).abs() < 1e-3, "{name}: {f}"); + run(&mut before, "sheet.unfold", json!({})); + // A round hole's volume is measured on its facets: 0.235 mm³ over for this circle, as on + // a plain rectangle. + let unfolded = volume(&mut before); + assert!(rel(unfolded, flat_volume) < 2e-5, "{name}: unfolded {unfolded} vs {flat_volume}"); + + let mut after = Session::default(); + t2_trapezoid(&mut after); + run(&mut after, "sheet.fold", fold.clone()); + run(&mut after, "sheet.unfold", json!({})); + cut(&mut after, &draw); + run(&mut after, "sheet.refold", json!({})); + let refolded = volume(&mut after); + assert!(rel(refolded, want) < 1e-5, "{name}: refolded {refolded} vs {want}"); + } +} + /// #296: two bends meeting at an open corner relief touch only along an edge, so the folded /// material the machining guard checks must not be sewn into one solid. #[test] @@ -3112,7 +3677,13 @@ fn hole_beside_two_adjacent_edge_flanges_cuts_and_bends_stay_guarded() { let mut s = Session::default(); build(&mut s); let before = volume(&mut s); - assert!((before - 14057.2).abs() < 0.1, "{before}"); + // Folded, the sheet (2.5 mm, R 2.5, K 0.44) holds its flat area times the thickness, less + // each bend's flat strip (its length times the allowance (R + K·t)·π/2) and plus its sector + // (R + t/2)·π/2: t·A + t²·(½ − K)·(π/2)·L for the bends' length L. + let flat_area: f64 = s.model.state().sheets[0].flat_regions().unwrap().iter().map(|r| r.area()).sum(); + let bends: f64 = flat(&mut s)["bends"].as_array().unwrap().iter().map(|b| b["length"].as_f64().unwrap()).sum(); + let want = 2.5 * flat_area + 2.5 * 2.5 * (0.5 - 0.44) * FRAC_PI_2 * bends; + assert!(rel(before, want) < 1e-9, "{before} vs {want}"); if let Err(e) = hole(&mut s, "Hole", [25.0, 20.0]) { panic!("hole beside two flanges: {e}"); } @@ -3170,7 +3741,7 @@ fn has_round_cutout(f: &Value, c: [f64; 2], r: f64) -> bool { /// Whether the flat DXF holds the circle of radius `r` about `c` as a `CIRCLE`. fn dxf_has_circle(s: &mut Session, c: [f64; 2], r: f64) -> bool { let dxf = run(s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); - let centre = solidcraft_geom::Vec2::new(c[0], c[1]); + let centre = solidcore_record::Vec2::new(c[0], c[1]); solidcraft_io::read_dxf(&dxf) .unwrap_or_default() .iter() @@ -3422,7 +3993,7 @@ fn closed_corners_reach_the_flat_pattern_and_the_dxf() { #[test] fn corner_reliefs_of_the_rule_reach_the_part_the_flat_pattern_and_the_dxf() { - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; // The tray at 72°: its bends meet at the corners of the base, s0 = 3·tan 36° in from the sheet's // edges, and are BA = 2θ wide in the flat. A relief 8 mm across reaches r = 4 mm along both edges // and takes, at each corner, r²·π/4 (round) or r² (rectangular) of the base and r of two bends. @@ -3674,7 +4245,7 @@ fn a_tear_of_the_rule_reaches_the_part_the_flat_pattern_and_the_dxf() { // The DXF: the outline in straight lines, each cut one of them, and four bend lines. let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); assert_eq!(dxf.matches("0\nLINE\n").count(), outline.len() + 4, "{deg}"); - let cut_end = solidcraft_geom::Vec2::new(x_end(s0), s0 - ba); + let cut_end = solidcore_record::Vec2::new(x_end(s0), s0 - ba); let read = solidcraft_io::read_dxf(&dxf).unwrap_or_default(); let at_cut_end = |g: &solidcraft_io::Geom2| matches!(g, solidcraft_io::Geom2::Line(a, b) if a.dist(cut_end) < 1e-6 || b.dist(cut_end) < 1e-6); assert!(read.iter().any(at_cut_end), "{deg}"); @@ -3750,7 +4321,7 @@ fn two_flange_groups(rule: Value, near: Value, far: Value) -> Session { /// What the DXF of the flat pattern draws of the corner reliefs: the arcs (centre, radius) and the /// lines' end points. -fn relief_drawing(s: &mut Session) -> (Vec<(solidcraft_geom::Vec2, f64)>, Vec) { +fn relief_drawing(s: &mut Session) -> (Vec<(solidcore_record::Vec2, f64)>, Vec) { let dxf = run(s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); let read = solidcraft_io::read_dxf(&dxf).unwrap_or_default(); let arcs = read.iter().filter_map(|g| if let solidcraft_io::Geom2::Arc { c, a, .. } = g { Some((*c, a.dist(*c))) } else { None }).collect(); @@ -3760,7 +4331,7 @@ fn relief_drawing(s: &mut Session) -> (Vec<(solidcraft_geom::Vec2, f64)>, Vec Vec<(usize, solidcraft_geom::Vec3, solidcraft_geom::Vec3)> { +fn flat_face_points(s: &Session) -> Vec<(usize, solidcore_record::Vec3, solidcore_record::Vec3)> { let state = s.model.state(); let body = &state.bodies[0].body; - let mesh = body.tessellate(0.01).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); (0..body.face_count()) .filter_map(|index| { let normal = body.planar_face(index)?.normal(); @@ -4975,7 +5546,9 @@ fn a_hole_drilled_into_a_rim_is_a_bore_the_sheet_keeps_when_it_unfolds() { let f = flat(&mut s); assert_eq!(f["bores"].as_array().map(Vec::len), Some(1), "{f}"); assert_eq!(f["cutouts"], json!([])); - let inside = |s: &Session, p: [f64; 3]| s.model.state().bodies[0].body.contains(solidcraft_geom::Vec3::new(p[0], p[1], p[2])); + let inside = |s: &Session, p: [f64; 3]| { + s.model.state().bodies[0].body.classify_point(solidcore_record::Vec3::new(p[0], p[1], p[2])).unwrap() == solidcraft_kernel::PointClass::Inside + }; // The flat pattern loses the same bore (the bends unroll to their own length). let flat_after = unfolded_volume(&mut s); assert!(rel(flat_before - flat_after, removed) < 0.02, "flat: removed {} of {removed}", flat_before - flat_after); @@ -5002,7 +5575,9 @@ fn a_rim_hole_in_a_flange_follows_it_into_the_flat_pattern() { let t = l_bracket(&mut s); let before = volume(&mut s); let flat_before = unfolded_volume(&mut s); - let inside = |s: &Session, p: [f64; 3]| s.model.state().bodies[0].body.contains(solidcraft_geom::Vec3::new(p[0], p[1], p[2])); + let inside = |s: &Session, p: [f64; 3]| { + s.model.state().bodies[0].body.classify_point(solidcore_record::Vec3::new(p[0], p[1], p[2])).unwrap() == solidcraft_kernel::PointClass::Inside + }; // Halfway up the flange, in the middle of its thickness (whichever way the rule put it). let mid = [[40.0 - t / 2.0, 15.0], [40.0 - t / 2.0, -15.0], [40.0 + t / 2.0, 15.0], [40.0 + t / 2.0, -15.0]] .into_iter() @@ -5215,6 +5790,102 @@ fn perforate_supports_a_square_pattern_and_refuses_impossible_values() { } } +/// The hole centres `staggered_count` counts, over the box (x0, y0)..(x1, y1). +fn staggered_centres(x0: f64, y0: f64, x1: f64, y1: f64, d: f64, pitch: f64, margin: f64) -> Vec<(f64, f64)> { + let (clear, dy) = (d / 2.0 + margin, pitch * 3f64.sqrt() / 2.0); + let mut out = Vec::new(); + let mut row = 0; + while y0 + clear + row as f64 * dy <= y1 - clear + 1e-9 { + let mut x = x0 + clear + if row % 2 == 1 { pitch / 2.0 } else { 0.0 }; + while x <= x1 - clear + 1e-9 { + out.push((x, y0 + clear + row as f64 * dy)); + x += pitch; + } + row += 1; + } + out +} + +/// A 100 x 60 x 0.8 sheet with a sketch on its face: a 50 x 30 rectangle at (10, 10) with a Ø10 circle at (35, 25). +fn sheet_with_a_field_outline(s: &mut Session) { + outline_blank(s, json!([[0, 0], [100, 0], [100, 60], [0, 60]])); + run(s, "sketch.create", json!({"plane": "XY", "name": "Field"})); + run(s, "sketch.rectangle.two_point", json!({"p0": [10, 10], "p1": [60, 40]})); + run(s, "sketch.circle.center", json!({"center": [35, 25], "radius": 5})); + run(s, "sketch.finish", json!({})); +} + +/// #732: a sketch bounds the field. The ring of the rectangle less the circle takes Rv 1.0-1.5 only inside it, margin +/// clear of both its loops, on the grid from the outline's lower-left corner; an edit without a sketch keeps it. +#[test] +fn perforation_outline_bounds_the_field_and_keeps_out_its_inner_loops() { + let mut s = Session::default(); + sheet_with_a_field_outline(&mut s); + let made = + run(&mut s, "sheet.perforate", json!({"diameter": "1", "pitch": "1.5", "margin": "1", "sketch": "Field", "profiles": [{"point": [15, 15]}]})); + let expected: Vec<(f64, f64)> = + staggered_centres(10.0, 10.0, 60.0, 40.0, 1.0, 1.5, 1.0).into_iter().filter(|&(x, y)| (x - 35.0).hypot(y - 25.0) >= 6.5).collect(); + assert_eq!(flat(&mut s)["perforations"][0]["count"].as_u64(), Some(expected.len() as u64)); + let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); + let holes = perforation_circles(&dxf); + assert_eq!(holes.len(), expected.len()); + assert!((holes[0].0 - 11.5).abs() < 1e-9 && (holes[0].1 - 11.5).abs() < 1e-9, "first hole at the outline's corner: {:?}", holes[0]); + assert!(holes.iter().all(|&(x, y, _)| (11.5 - 1e-9..=58.5 + 1e-9).contains(&x) && (11.5 - 1e-9..=38.5 + 1e-9).contains(&y))); + assert!(holes.iter().all(|&(x, y, _)| (x - 35.0).hypot(y - 25.0) >= 6.5 - 1e-9), "no hole in or near the inner loop"); + let n = holes.len(); + run( + &mut s, + "timeline.redefine", + json!({"feature": made["feature"], "command": "sheet.perforate", "params": {"diameter": "1", "pitch": "1.5", "margin": "1"}}), + ); + assert_eq!(flat(&mut s)["perforations"][0]["count"].as_u64(), Some(n as u64), "the edit keeps the outline"); +} + +/// #732: on a folded sheet the outline goes through the panel its sketch lies on and stops there: an outline that +/// reaches past the bend puts no hole in the flange. A sketch on no face of the sheet is refused. +#[test] +fn perforation_outline_on_a_folded_sheet_stays_in_its_panel() { + let mut s = Session::default(); + outline_blank(&mut s, json!([[0, 0], [100, 0], [100, 60], [0, 60]])); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 0.8]], "height": 20})); + for (name, z) in [("Top", 0.8), ("Above", 10.0)] { + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": name})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-50, -50], "p1": [150, 110]})); + run(&mut s, "sketch.finish", json!({})); + } + run(&mut s, "sheet.perforate", json!({"diameter": "1", "pitch": "1.5", "margin": "1", "sketch": "Top"})); + let zone = &flat(&mut s)["bend_zones"][0]; // [min x, max x, min y, max y] of the bend zone, flat coordinates + let top = zone[3].as_f64().unwrap_or(f64::NAN); + let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); + let holes = perforation_circles(&dxf); + assert!(!holes.is_empty()); + assert!(holes.iter().all(|&(_, y, r)| y - r - 1.0 >= top - 1e-9), "every hole is in the base, beyond the bend zone's y {top}"); + let refused = s.execute("sheet.perforate", &json!({"diameter": "1", "pitch": "1.5", "sketch": "Above"})); + assert!(refused.is_err_and(|e| e.to_string().contains("must lie on a face of the sheet"))); +} + +/// #732: a mirrored copy's bounded field is the mirror image of its source's. +#[test] +fn a_mirrored_sheet_copy_mirrors_its_perforation_outline() { + let mut s = Session::default(); + sheet_with_a_field_outline(&mut s); + run(&mut s, "sheet.perforate", json!({"diameter": "1", "pitch": "1.5", "margin": "1", "sketch": "Field", "profiles": [{"point": [15, 15]}]})); + run(&mut s, "solid.mirror", json!({"bodies": ["Body1"], "plane": "YZ"})); + let holes = |s: &mut Session, body: &str, sx: f64| -> Vec<(i64, i64)> { + let dxf = run(s, "sheet.export_dxf", json!({"body": body}))["dxf"].as_str().unwrap_or_default().to_string(); + let c = perforation_circles(&dxf); + // Relative to the field's own lower-left hole, x scaled by sx, rounded to 1e-6 mm. + let x0 = c.iter().map(|h| h.0 * sx).fold(f64::INFINITY, f64::min); + let y0 = c.iter().map(|h| h.1).fold(f64::INFINITY, f64::min); + let mut v: Vec<(i64, i64)> = c.iter().map(|h| (((h.0 * sx - x0) * 1e6).round() as i64, ((h.1 - y0) * 1e6).round() as i64)).collect(); + v.sort_unstable(); + v + }; + let original = holes(&mut s, "Body1", -1.0); + assert!(!original.is_empty()); + assert_eq!(holes(&mut s, "Body1 (2)", 1.0), original); +} + /// A 100 x 60 tray with one 45° flange 40 high on its y = 0 edge (2.5 mm, R 2.5, K 0.44), and on /// it a return 10 high when asked. Returns the far edge of the last panel in the flat pattern: /// the base starts at the setback s = (t + R)·tan 22.5°, each bend's zone is (π/4)·(R + K·t) long, @@ -5243,7 +5914,7 @@ fn parted_note(area: f64, at: [f64; 2]) -> String { } fn flat_pieces(s: &Session) -> Vec { - s.model.state().sheets[0].flat_regions().unwrap().iter().map(solidcraft_geom::Region2::area).collect() + s.model.state().sheets[0].flat_regions().unwrap().iter().map(solidcore_record::Region2::area).collect() } #[test] @@ -5373,9 +6044,72 @@ fn flat_exports(s: &mut Session) -> Vec> { calls.iter().map(|(id, p)| s.execute(id, p).map_err(|e| e.to_string())).collect() } -/// A mirror combined into a sheet, or a tab extruded onto it and joined, makes a part its -/// flat pattern does not have (the mirrored half, the tab): the flat pattern, the DXF and the -/// bend table are refused with the feature's name instead of writing the sheet without it. +/// A sheet metal body mirrored, or patterned, into new bodies makes sheet metal bodies (#3353): +/// each copy has a flat pattern and a bend table, and a sheet metal feature on a copy rebuilds it +/// from its moved model where it is. A mirrored copy's model is its source's mirrored in the +/// flat (x → −x) with the same thickness side (`SheetBody::copied`, d9d6af51c, as +/// `a_mirrored_sheet_copy_is_the_opposite_hand_with_the_mirror_image_flat_pattern` has it): the +/// opposite hand's blank, each bend turning the same way, its pocket on the same face. +#[test] +fn a_mirrored_or_patterned_sheet_body_is_sheet_metal_with_its_flat_pattern() { + use solidcore_record::Vec3; + let mut s = Session::default(); + run(&mut s, "sheet.manage_rules", json!({"name": "S", "thickness": "2 mm", "active": true, "bend_radius": "2 mm", "k_factor": 0.4})); + base(&mut s, 100.0, 60.0); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20})); + rectangle_tool(&mut s, "Pocket", [20.0, 20.0], [30.0, 30.0]); + run(&mut s, "solid.extrude", json!({"sketch": "Pocket", "distance": 1, "operation": "cut"})); + let source = s.model.state().sheets[0].body.clone(); + let before = volume(&mut s); + let blank = run(&mut s, "sheet.flat_pattern", json!({"body": source})); + + run(&mut s, "solid.mirror", json!({"bodies": [source], "plane": "YZ"})); + let copy = s.model.state().bodies[1].name.clone(); + assert!(rel(volume(&mut s), 2.0 * before) < 1e-9); + let mirrored = run(&mut s, "sheet.flat_pattern", json!({"body": copy})); + // The source's blank and pocket mirrored, the same size, bend and pocket side. + assert_eq!(mirrored["flat_size_mm"], blank["flat_size_mm"], "{mirrored}"); + assert_eq!(flat_points(&mirrored["outline"], 1.0), flat_points(&blank["outline"], -1.0), "the mirrored blank: {mirrored}"); + let pocket = |f: &Value| json!([f["pockets"][0]["outline"]]); + assert_eq!(flat_points(&pocket(&mirrored), 1.0), flat_points(&pocket(&blank), -1.0), "{mirrored}"); + assert_eq!((&blank["pockets"][0]["side"], &mirrored["pockets"][0]["side"]), (&json!("bottom"), &json!("bottom")), "{mirrored}"); + assert_eq!((&blank["bends"][0]["direction"], &mirrored["bends"][0]["direction"]), (&json!("up"), &json!("up")), "{mirrored}"); + run(&mut s, "sheet.export_bend_table", json!({"body": copy})); + + // The copy's model is where its body is: a flange on the copy rebuilds it in place, its + // first flange still up on the y = 0 edge and its pocket still from below. + run(&mut s, "sheet.flange", json!({"body": copy, "edges": [[-100, 30, 2]], "height": 10})); + let state = s.model.state(); + let body = &state.body(©).expect("the copy").body; + for (p, inside) in [ + (Vec3::new(-50.0, 1.0, 15.0), true), + (Vec3::new(-50.0, 1.0, -15.0), false), + (Vec3::new(-25.0, 25.0, 0.5), false), + (Vec3::new(-25.0, 25.0, 1.5), true), + (Vec3::new(-99.0, 30.0, 8.0), true), + (Vec3::new(-99.0, 30.0, -8.0), false), + ] { + assert_eq!(body.classify_point(p).unwrap() == solidcraft_kernel::PointClass::Inside, inside, "{p:?}"); + } + drop(state); + + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + let source = s.model.state().sheets[0].body.clone(); + run(&mut s, "solid.pattern.rectangular", json!({"bodies": [source], "dir1": [1, 0, 0], "count1": 2, "spacing1": 150})); + let state = s.model.state(); + assert_eq!(state.sheets.len(), state.bodies.len(), "every copy is sheet metal"); + let names: Vec = state.bodies.iter().map(|b| b.name.clone()).collect(); + drop(state); + for n in names { + run(&mut s, "sheet.flat_pattern", json!({"body": n})); + } +} + +/// A mirror combined into a sheet, or a block extruded onto it and joined, makes a part its +/// flat pattern does not have (the mirrored half, the block): the flat pattern, the DXF and the +/// bend table are refused with the feature's name instead of writing the sheet without it. (A +/// tab joined in the sheet's own plane becomes part of it: `a_join_in_the_flat_is_kept_like_a_cut`.) #[test] fn a_mirror_or_a_join_into_a_sheet_refuses_its_flat_pattern_naming_the_feature() { let mut s = Session::default(); @@ -5391,12 +6125,21 @@ fn a_mirror_or_a_join_into_a_sheet_refuses_its_flat_pattern_naming_the_feature() let mut s = Session::default(); base(&mut s, 100.0, 60.0); - rectangle_tool(&mut s, "Tab", [40.0, 60.0], [60.0, 75.0]); - run(&mut s, "solid.extrude", json!({"sketch": "Tab", "distance": 2.5, "operation": "join"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 2.5, "name": "Block"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [40, 20], "p1": [60, 35]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Block", "distance": 10, "operation": "join"})); for result in flat_exports(&mut s) { - let error = result.expect_err("a joined tab the flat pattern lacks"); + let error = result.expect_err("a joined block the flat pattern lacks"); assert!(error.contains("can't include Extrude1"), "{error}"); } + // The tab beside the base's edge, joined in its plane, is in the flat pattern. + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + rectangle_tool(&mut s, "Tab", [40.0, 60.0], [60.0, 75.0]); + run(&mut s, "solid.extrude", json!({"sketch": "Tab", "distance": 2.5, "operation": "join"})); + assert!(flat_exports(&mut s).into_iter().all(|r| r.is_ok())); + assert!((flat(&mut s)["flat_size_mm"][1].as_f64().unwrap_or(0.0) - 75.0).abs() < 1e-9); } /// A fillet on a sheet's corner is refused in the flat pattern until a sheet metal feature @@ -5530,9 +6273,12 @@ fn a_mirrored_sheet_copy_is_the_opposite_hand_with_the_mirror_image_flat_pattern assert_eq!(bends(&mirrored), bends(&original)); assert_eq!(bends(&mirrored).len(), 2); // The hole is where the mirror put it, on the copy and in its flat pattern. - let in_copy = |p: [f64; 3]| { - s.model.state().bodies.iter().find(|b| b.name == "Body1 (2)").is_some_and(|b| b.body.contains(solidcraft_geom::Vec3::new(p[0], p[1], p[2]))) - }; + let in_copy = + |p: [f64; 3]| { + s.model.state().bodies.iter().find(|b| b.name == "Body1 (2)").is_some_and(|b| { + b.body.classify_point(solidcore_record::Vec3::new(p[0], p[1], p[2])).unwrap() == solidcraft_kernel::PointClass::Inside + }) + }; assert!(!in_copy([-25.0, 40.0, 1.0]) && in_copy([-35.0, 40.0, 1.0])); let hole = flat_points(&mirrored["cutouts"], 1.0); let cx = hole.iter().map(|p| p.0 as f64).sum::() / hole.len().max(1) as f64 * 1e-6; @@ -5618,3 +6364,98 @@ fn an_unfolded_sheets_flat_face_is_named_after_its_base_at_every_size() { } } } + +/// A primitive cut passes over a sheet its exact box is clear of: that sheet comes back the very +/// same body, and the sheet the cut meets gets the hole. +#[test] +fn a_primitive_cut_passes_over_a_sheet_clear_of_it_by_its_exact_box() { + let mut s = Session::default(); + for (name, x) in [("Left", 0.0), ("Right", 100.2)] { + run(&mut s, "solid.box", json!({"corner": [x, 0, 0], "length": 100, "width": 60, "height": 2.5, "body_name": name})); + run(&mut s, "sheet.convert", json!({"body": name, "face": [x + 50.0, 30, 2.5]})); + } + let body = |s: &Session, name: &str| s.model.state().bodies.iter().find(|b| b.name == name).map(|b| b.body.clone()).unwrap(); + let left = body(&s, "Left"); + let right_volume = body_volume(&mut s, "Right"); + // 0.2 mm from the Left sheet's end: within the display mesh's tolerance of it, clear of its exact box. + run(&mut s, "solid.cylinder", json!({"base": [102.9, 30, -1], "radius": 2.5, "height": 5, "operation": "cut"})); + assert!(body(&s, "Left").same(&left), "the sheet clear of the cut is passed over"); + let holes = |s: &Session, name: &str| s.model.state().sheets.iter().find(|sh| sh.body == name).map(|sh| sh.holes.len()); + assert_eq!(holes(&s, "Left"), Some(0)); + assert_eq!(holes(&s, "Right"), Some(1)); + assert!((right_volume - body_volume(&mut s, "Right") - PI * 6.25 * 2.5).abs() < 1e-3); +} + +/// A cut that only grazes a bend's curved faces near the edge where the bend meets the base is +/// checked against the bend and refused (the sheet is unchanged); one clear of the bend's exact +/// box cuts the base. +#[test] +fn a_cut_grazing_a_bend_near_its_edge_is_refused_and_one_clear_of_its_exact_box_cuts() { + // `plate_with_flange`: the bend (R 2.5, T 2.5) runs from y = 0 to y = 5, where the base + // panel starts. + for (y0, grazes) in [(4.9, true), (5.1, false)] { + let mut s = Session::default(); + plate_with_flange(&mut s); + let v0 = volume(&mut s); + rectangle_tool(&mut s, "Slot", [40.0, y0], [60.0, 15.0]); + let cut = json!({"sketch": "Slot", "through_all": true, "direction": "symmetric", "operation": "cut"}); + if grazes { + let before = s.doc.to_json(); + let e = s.execute("solid.extrude", &cut).unwrap_err().to_string(); + assert!(e.contains("intersects a folded bend"), "{e}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(volume(&mut s), v0); + } else { + run(&mut s, "solid.extrude", cut); + assert!((v0 - volume(&mut s) - 20.0 * (15.0 - y0) * 2.5).abs() < 1e-3, "{}", v0 - volume(&mut s)); + assert_eq!(flat(&mut s)["cutouts"].as_array().map(Vec::len), Some(1)); + } + } +} + +/// A base flange 1 thick (R 1, K 0.44) from the closed outline `pts` on XY. +fn sheet_from_outline(s: &mut Session, pts: Value) { + run(s, "sheet.manage_rules", json!({"name": "S1", "thickness": "1", "bend_radius": "1", "k_factor": 0.44, "active": true})); + run(s, "sketch.create", json!({"plane": "XY", "name": "B"})); + run(s, "sketch.line", json!({"points": pts, "closed": true})); + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "B"})); +} + +/// The bends of the flat pattern as (length, lower y, upper y), sorted by the lower y. +fn bend_spans(s: &mut Session) -> Vec<(f64, f64, f64)> { + let f = flat(s); + let mut v: Vec<(f64, f64, f64)> = f["bends"] + .as_array() + .unwrap() + .iter() + .map(|b| { + let (y0, y1) = (b["start"][1].as_f64().unwrap(), b["end"][1].as_f64().unwrap()); + (b["length"].as_f64().unwrap(), y0.min(y1), y0.max(y1)) + }) + .collect(); + v.sort_by(|a, b| a.1.total_cmp(&b.1)); + v +} + +const STEPPED: [[f64; 2]; 8] = + [[-106.9, 5.4], [108.9, 5.4], [108.9, 408.9], [-106.9, 408.9], [-106.9, 388.3], [-108.9, 388.3], [-108.9, 10.5], [-106.9, 10.5]]; + +/// A flange on part of a stepped outline spans that part: on the X −108.9 segment (Y 10.5…388.3) +/// of a base whose edge beyond it is already at the bend line (X −106.9), the bend is 377.8 long +/// and no relief is cut. Before, it ran the face's whole length (403.5). +#[test] +fn a_flange_on_part_of_a_stepped_outline_spans_that_part() { + let mut s = Session::default(); + sheet_from_outline(&mut s, json!(STEPPED)); + run(&mut s, "sheet.flange", json!({"edges": [[-108.9, 200, 1]], "height": 20})); + let spans = bend_spans(&mut s); + assert_eq!(spans.len(), 1); + let (len, y0, y1) = spans[0]; + assert!((len - 377.8).abs() < 1e-9 && (y0 - 10.5).abs() < 1e-9 && (y1 - 388.3).abs() < 1e-9, "{spans:?}"); + // The base trimmed back to X −106.9 (215.8 × 403.5), and the bend (allowance (π/2)(R + K·t)) and + // the 18 leg along the 377.8: no relief. + let allowance = PI / 2.0 * (1.0 + 0.44 * 1.0); + let expected = 215.8 * 403.5 + 377.8 * (allowance + 18.0); + assert!(rel(flat_area(&flat(&mut s)), expected) < 1e-9, "{} vs {expected}", flat_area(&flat(&mut s))); +} diff --git a/crates/engine/src/cmd/silhouette.rs b/crates/engine/src/cmd/silhouette.rs index f44a9f02f..2a0c377f1 100644 --- a/crates/engine/src/cmd/silhouette.rs +++ b/crates/engine/src/cmd/silhouette.rs @@ -1,7 +1,8 @@ //! A tightly framed, view-aligned union of the projected body meshes. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::CommandSpec; use crate::params::bad; @@ -20,19 +21,50 @@ fn run(s: &mut Session, p: &Value) -> Result { let camera = camera(p)?; let rows = rows(p)?; let wanted = body_names(p)?; - let state = s.world_state(); - if let Some(names) = &wanted { + let out = outline(s, &camera, wanted.as_deref(), rows)?; + let mask: Vec> = out.mask.iter().map(|row| spans(row)).collect(); + Ok(json!({ + "width": out.width, + "height": out.height, + "mm_per_px": round4(out.mm_per_px), + "box_mm": [[round4(out.lo[0]), round4(out.lo[1])], [round4(out.hi[0]), round4(out.hi[1])]], + "right": [clean(out.right.x), clean(out.right.y), clean(out.right.z)], + "up": [clean(out.up.x), clean(out.up.y), clean(out.up.z)], + "projection": if out.perspective { "perspective" } else { "parallel" }, + "bodies": out.bodies, + "triangles": out.triangles, + "mask": mask, + })) +} + +/// A projected, tightly framed silhouette: the pixel grid, its scale and placement, and the +/// filled mask as one row of booleans per pixel row. `inspect.silhouette` renders this as +/// run-length rows; `inspect.compare_picture` uses the filled rows directly. +pub(crate) struct Silhouette { + pub width: usize, + pub height: usize, + pub mm_per_px: f64, + /// The view-plane box the mask frames, in mm (u along `right`, v along `up`). + pub lo: [f64; 2], + pub hi: [f64; 2], + pub right: Vec3, + pub up: Vec3, + pub perspective: bool, + pub bodies: usize, + pub triangles: usize, + pub mask: Vec>, +} + +pub(crate) fn outline(s: &Session, camera: &Camera, wanted: Option<&[String]>, rows: usize) -> Result { + let state = s.world_state()?; + if let Some(names) = wanted { for name in names { if !state.bodies.iter().any(|b| b.name == *name) { return Err(bad(CMD, format!("unknown body name `{name}`"))); } } } - let bodies: Vec<_> = state - .bodies - .iter() - .filter(|b| wanted.as_ref().map_or_else(|| s.body_visible(&b.name), |names| names.iter().any(|name| name == &b.name))) - .collect(); + let bodies: Vec<_> = state.bodies.iter().filter(|b| wanted.map_or_else(|| s.body_visible(&b.name), |names| names.contains(&b.name))).collect(); if bodies.is_empty() { return Err(bad(CMD, "nothing visible to outline")); } @@ -133,22 +165,22 @@ fn run(s: &mut Session, p: &Value) -> Result { } } - let mask: Vec> = covered.chunks_exact(width).map(spans).collect(); - Ok(json!({ - "width": width, - "height": height, - "mm_per_px": round4(mm_per_px), - "box_mm": [[round4(lo[0]), round4(lo[1])], [round4(hi[0]), round4(hi[1])]], - "right": [clean(right.x), clean(right.y), clean(right.z)], - "up": [clean(up.x), clean(up.y), clean(up.z)], - "projection": if perspective { "perspective" } else { "parallel" }, - "bodies": bodies.len(), - "triangles": triangle_count, - "mask": mask, - })) + Ok(Silhouette { + width, + height, + mm_per_px, + lo, + hi, + right, + up, + perspective, + bodies: bodies.len(), + triangles: triangle_count, + mask: covered.chunks_exact(width).map(|row| row.to_vec()).collect(), + }) } -fn camera(p: &Value) -> Result { +pub(crate) fn camera(p: &Value) -> Result { if p.get("view").is_some() && p.get("camera").is_some() { return Err(bad(CMD, "give `view` or `camera`, not both")); } @@ -171,7 +203,7 @@ fn camera(p: &Value) -> Result { Ok(camera) } -fn body_names(p: &Value) -> Result>> { +pub(crate) fn body_names(p: &Value) -> Result>> { match p.get("bodies") { None => Ok(None), Some(Value::String(name)) => Ok(Some(vec![name.clone()])), @@ -184,7 +216,7 @@ fn body_names(p: &Value) -> Result>> { } } -fn rows(p: &Value) -> Result { +pub(crate) fn rows(p: &Value) -> Result { match p.get("rows") { None => Ok(240), Some(v) => { @@ -209,7 +241,7 @@ fn edge(a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> f64 { (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) } -fn spans(row: &[bool]) -> Vec<[usize; 2]> { +pub(crate) fn spans(row: &[bool]) -> Vec<[usize; 2]> { let mut out = Vec::new(); let mut start = None; for (x, &on) in row.iter().enumerate() { diff --git a/crates/engine/src/cmd/single_hole_tests.rs b/crates/engine/src/cmd/single_hole_tests.rs index 9249abbee..63876d752 100644 --- a/crates/engine/src/cmd/single_hole_tests.rs +++ b/crates/engine/src/cmd/single_hole_tests.rs @@ -1,10 +1,11 @@ //! A Single hole at a sketch point follows the point when the sketch changes (#2110), drilled //! into the face it was placed on, and keeps doing so after the design is saved and reopened. +use solidcraft_geom::prelude::*; use std::f64::consts::PI; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -20,7 +21,7 @@ fn volume(s: &mut Session) -> f64 { } fn solid_at(s: &Session, p: Vec3) -> bool { - s.model.state().bodies.iter().any(|b| b.body.contains(p)) + s.model.state().bodies.iter().any(|b| b.body.classify_point(p).unwrap() == solidcraft_kernel::PointClass::Inside) } /// The circle `c1`'s centre: its point id and where it is in the world. @@ -133,3 +134,29 @@ fn a_far_body_does_not_change_a_countersunk_hole() { assert_eq!(small_changed, large_changed, "bodies changed"); assert_eq!(large_changed, json!(["lid"]), "only the lid is drilled"); } + +/// #5041: a countersunk Ø6.4 hole (Ø13.7, 90°) 0.15 mm from a wall standing on the plate cuts +/// nothing above the entry face: the countersink's rim (y 29.85) stays clear of the wall (y 30). +/// 10 faces: bottom, the two L-shaped ends, front and back, the plate top, the wall's front and +/// top, the cone and the bore. +#[test] +fn a_countersink_beside_a_wall_stays_below_the_face() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 8, "corner": [0, 0, 0]})); + run(&mut s, "solid.box", json!({"length": 40, "width": 10, "height": 30, "corner": [0, 30, 8], "operation": "join"})); + run( + &mut s, + "solid.hole", + json!({"position": [20, 23, 8], "direction": [0, 0, -1], "diameter": 6.4, "type": "countersink", "cs_diameter": 13.7, "cs_angle": 90}), + ); + let st = s.model.state(); + let [body] = st.bodies.as_slice() else { panic!("one body, got {}", st.bodies.len()) }; + assert_eq!(body.body.face_count(), 10, "the wall is not notched"); + // In the wall's foot, 0.4 mm above the face: still solid. + assert!(solid_at(&s, Vec3::new(20.0, 30.2, 8.4)), "the wall's foot is cut"); + let (rr, r, h) = (6.85_f64, 3.2_f64, 3.65_f64); + let removed = PI * h / 3.0 * (rr * rr + rr * r + r * r) + PI * r * r * (8.0 - h); + let want = 24800.0 - removed; + let got = volume(&mut s); + assert!((got - want).abs() < 1e-3, "volume {got}, want {want}"); +} diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index e2c5342d0..21254c698 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -1,13 +1,16 @@ //! Sketch commands: create/edit/finish sketches, draw curves, constraints and dimensions. use serde_json::{Value, json}; +use solidcore_record::{Plane, Vec2, Vec3}; use solidcraft_doc::{FeatureKind, PlaneRef, expr::Kind}; -use solidcraft_geom::{Plane, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, PointExprs, Sketch, SolveReport, TwoCircles, solve, solve_with}; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec3}; -use crate::{EngineError, Result, Session, SketchEntry}; +use crate::schema::sketch::{CancelResult, EditParams, EditResult, ExitParams, FinishResult}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session, SketchEntry, Snapshot}; #[path = "sketch_dimensioned.rs"] mod dimensioned; @@ -33,18 +36,28 @@ macro_rules! model_operand_doc { }; } +const EDIT_CONTRACT: TypedContract = TypedContract::new(); +const EXIT_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.create", "Create Sketch", create_sketch) .at("SOLID", "CREATE") .icon("sketch") - .params("plane: XY|XZ|YZ | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} (in world coordinates unless frame says otherwise; a named plane is the active component's own) | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), frame?: world (default) | component (which coordinates an explicit plane is in; the reply's `frame` says which, with a `note` when the active component is moved or turned), project_edges?: bool, name?"), - CommandSpec::new("sketch.edit", "Edit Sketch", edit_sketch).noundo().icon("sketch").params("sketch: id or name"), - CommandSpec::new("sketch.finish", "Finish Sketch", finish_sketch).at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch).noundo(), - CommandSpec::new("sketch.cancel", "Cancel Sketch", cancel_sketch) + .params("plane: XY|XZ|YZ (sketch x, y along world +X, +Y on XY; +X, -Z on XZ; +Y, +Z on YZ) | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} (in world coordinates unless frame says otherwise; a named plane is the active component's own) | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), frame?: world (default) | component (which coordinates an explicit plane is in; the reply's `frame` says which, with a `note` when the active component is moved or turned), project_edges?: bool, activate_part?: bool (default false; on a face of a body of another component than the active one: activate that component at the picked placement first, as component.activate would, and make the sketch there; it stays active afterwards and the reply's `activated` names it), name?"), + CommandSpec::new("sketch.edit", "Edit Sketch", crate::checked!("sketch.edit", edit_sketch)) + .noundo().icon("sketch") + .contract(&EDIT_CONTRACT).output(output_schema_for::) + .params("sketch: id or name; restore_marker?: nonnegative timeline position or null (end). When provided, temporarily roll to this sketch and restore that position on Finish or Cancel; Finish groups the edit into one Undo step. Omit to leave the timeline in place"), + CommandSpec::new("sketch.finish", "Finish Sketch", crate::checked!("sketch.finish", finish_sketch)) + .at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch).noundo() + .contract(&EXIT_CONTRACT).output(output_schema_for::) + .params("restore_marker?: bool (default true); false transfers the temporary marker directly to another editor without rebuilding the intervening timeline"), + CommandSpec::new("sketch.cancel", "Cancel Sketch", crate::checked!("sketch.cancel", cancel_sketch)) .at("SKETCH", "FINISH SKETCH") .icon("sketch_cancel") .enabled(in_sketch) - .params("Leaves the sketch without keeping what changed since it was created or opened for editing: the design goes back to how it was then (a new sketch is removed), as one step that Undo brings back. Refused when the undo history no longer leads back to that point (use Undo instead)"), + .contract(&EXIT_CONTRACT).output(output_schema_for::) + .params("Leaves the sketch without keeping what changed since it was created or opened for editing: the design goes back to how it was then (a new sketch is removed), as one step that Undo brings back. Refused when the undo history no longer leads back to that point (use Undo instead). restore_marker?: bool (default true); false transfers the temporary marker to another editor"), CommandSpec::new("sketch.line", "Line", draw_line) .at("SKETCH", "CREATE") .icon("line") @@ -59,7 +72,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("rect") .key("R") .enabled(in_sketch) - .params(concat!("p0, p1: opposite corners [x,y]; construction?. Returns sides {bottom, right, top, left} (line ids) and corners {bottom_left, bottom_right, top_right, top_left} (point ids)", connect_doc!(), created_doc!())), + .params(concat!("p0, p1: opposite corners [x,y] (a coordinate may be an expression over the design's parameters: the corner follows them); construction?. Returns sides {bottom, right, top, left} (line ids) and corners {bottom_left, bottom_right, top_right, top_left} (point ids)", connect_doc!(), created_doc!())), CommandSpec::new("sketch.rectangle.three_point", "3-Point Rectangle", rect_three_point) .at("SKETCH", "CREATE") .icon("rect3") @@ -69,19 +82,19 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "CREATE") .icon("rect_rounded") .enabled(in_sketch) - .params(concat!("p0, p1: opposite corners [x,y]; radius: expr (the corner radius, less than half the shorter side); construction?. A 2-point rectangle whose four corners are filleted alike: one radius dimension (`param`), the other arcs equal to it. Returns sides {bottom, right, top, left} (line ids) and arcs (the corner arcs: bottom-left, bottom-right, top-right, top-left)", connect_doc!(), created_doc!())), + .params(concat!("p0, p1: opposite corners [x,y] (a coordinate may be an expression over the design's parameters: the corner follows them, as in `sketch.rectangle.two_point`); radius: expr (the corner radius, less than half the shorter side); construction?. A 2-point rectangle whose four corners are filleted alike: one radius dimension (`param`), the other arcs equal to it. Returns sides {bottom, right, top, left} (line ids) and arcs (the corner arcs: bottom-left, bottom-right, top-right, top-left)", connect_doc!(), created_doc!())), CommandSpec::new("sketch.rectangle.center", "Center Rectangle", rect_center) .at("SKETCH", "CREATE") .icon("rect_center") .enabled(in_sketch) - .params(concat!("center, corner; construction?: bool. Returns sides {bottom, right, top, left} (line ids) and corners {bottom_left, bottom_right, top_right, top_left} (point ids)", connect_doc!(), created_doc!())), + .params(concat!("center, corner: [x,y] (a coordinate may be an expression over the design's parameters: the point follows them); construction?: bool. Returns sides {bottom, right, top, left} (line ids) and corners {bottom_left, bottom_right, top_right, top_left} (point ids)", connect_doc!(), created_doc!())), CommandSpec::new("sketch.circle.center", "Center Diameter Circle", circle_center) .at("SKETCH", "CREATE") .icon("circle") .key("C") .enabled(in_sketch) .params(concat!( - "center: [x,y] or point ref, radius | diameter: number; through?: point ref (a point the circle passes through, kept on it: where the tool's second click snapped); construction?: bool", + "center: [x,y] or point ref (a coordinate may be an expression over the design's parameters: the centre follows them), radius | diameter: number or expression (an expression naming a parameter is a dimension driven by it; with `through` a point ref, that and the point both fix the radius); through?: point ref (a point the circle passes through, kept on it: where the tool's second click snapped); construction?: bool", connect_doc!(), created_doc!() )), @@ -94,7 +107,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "CREATE") .icon("circle3") .enabled(in_sketch) - .params(concat!("p0, p1, p2; construction?: bool", connect_doc!(), created_doc!())), + .params(concat!("p0, p1, p2: [x,y] or point ref (a referenced point stays on the circle); construction?: bool", connect_doc!(), created_doc!())), CommandSpec::new("sketch.arc.three_point", "3-Point Arc", arc_three).at("SKETCH", "CREATE").icon("arc3").enabled(in_sketch).params(concat!("start, end, through: [x,y] or point ref (a referenced through point stays on the arc); construction?: bool", connect_doc!(), created_doc!())), CommandSpec::new("sketch.arc.center_point", "Center Point Arc", arc_center) .at("SKETCH", "CREATE") @@ -139,7 +152,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "CONSTRAINTS") .icon("c_coincident") .enabled(in_sketch) - .params(concat!("a, b: points, a point and a curve or sketch axis (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or two distinct lines (joins their closest endpoints), or two circles/arcs (the second lies on the first: concentric and equal, `constraints` lists both)", model_operand_doc!())), + .params(concat!("a, b: points (or a line's middle as {midpoint: line}, which becomes a point tied there), a point and a curve or sketch axis (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or two distinct lines (joins their closest endpoints), or two circles/arcs (the second lies on the first: concentric and equal, `constraints` lists both)", model_operand_doc!())), CommandSpec::new("sketch.constraint.tangent", "Tangent", c_tangent) .at("SKETCH", "CONSTRAINTS") .icon("c_tangent") @@ -174,7 +187,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "CONSTRAINTS") .icon("c_concentric") .enabled(in_sketch) - .params(concat!("a, b: circles/arcs", model_operand_doc!())), + .params(concat!("a, b: two circles/arcs, or a circle/arc and a sketch point (including origin), in either order; the point and the curve's centre become coincident", model_operand_doc!())), CommandSpec::new("sketch.constraint.collinear", "Collinear", c_collinear) .at("SKETCH", "CONSTRAINTS") .icon("c_collinear") @@ -288,6 +301,9 @@ pub(super) fn edit_solved( } // The stored sketch is solved for its stored values. let stored = sk.driving_values(); + // The constraints the sketch has before the edit: a conflict message must not name one the + // edit itself adds (the trial already holds it under the id it would get, #9735). + let pre: Vec = sk.constraints.iter().map(|c| c.id.clone()).collect(); let (out, left) = f(&mut sk, &mut doc)?; // A curve that took an offset spline's generated node (drawn from its end) gets its own point there. sk.detach_offset_points()?; @@ -307,7 +323,7 @@ pub(super) fn edit_solved( sk.refresh_offsets()?; rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), analysis, None); } - Some(settle(strict, rep, &mut sk, unsolved)?) + Some(settle(strict, rep, &mut sk, unsolved, &pre)?) } // Solved for the document's values, continuing from the stored solved state. Left::Solved | Left::Unsolved => { @@ -317,20 +333,32 @@ pub(super) fn edit_solved( #[cfg(test)] solve_counts::record(analysis); let rep = doc.solve_sketch_with_analysis(&vals, &mut sk, &stored, None, analysis)?; - Some(settle(strict, rep, &mut sk, unsolved)?) + Some(settle(strict, rep, &mut sk, unsolved, &pre)?) } }; sketch_store::checked(&sk)?; sketch_store::write(&mut doc, id, sk)?; - *s.doc_mut() = doc; + s.set_doc(doc); Ok((out, rep)) } /// An edit's solve outcome: with `strict`, a solve that fails or turns the sketch over is an /// error; otherwise such a sketch is stored as the edit left it before the solve, its values /// and geometry together, so the stored sketch stays solved for its stored values. -fn settle(strict: bool, rep: SolveReport, sk: &mut Sketch, unsolved: Sketch) -> Result { +/// `pre` are the constraint ids the sketch had before the edit: the trial already holds any +/// constraint the edit adds, under the id it would get, so a conflict list that named it would +/// name an id the sketch does not have yet (#9735). +fn settle(strict: bool, mut rep: SolveReport, sk: &mut Sketch, unsolved: Sketch, pre: &[String]) -> Result { if strict && !rep.keeps_orientation() { + if rep.folded.is_empty() && rep.oversized.is_none() && !rep.failing.is_empty() { + let had: Vec = rep.failing.iter().filter(|id| pre.iter().any(|p| p == *id)).cloned().collect(); + if had.is_empty() { + return Err(EngineError::Other( + "that would over-constrain the sketch (it conflicts with what the other constraints already determine)".into(), + )); + } + rep.failing = had; + } return Err(EngineError::Other(rep.failure(|f| format!("that would over-constrain the sketch (conflicts with {f})")))); } // A solve that throws points far beyond the sketch found a far solution of its constraints, @@ -373,6 +401,21 @@ fn shrunk(before: &Sketch, after: &Sketch) -> Option { /// dimension value) has thrown the geometry to a far solution. const FLUNG: f64 = 1000.0; +/// Why a solve from `before` into `after` collapses the sketch, in the words `settle` uses to +/// refuse an edit's solve: a line or circle shrunk to a point, or points thrown far away. +/// `None` when the solved shape is one the edit can mean. Value edits (`Session::settle_value_edit`) +/// run the same checks, so a parameter, a configuration row or the dimension editor cannot +/// store a sketch whose curve has been squeezed away and which can never be solved back. +pub(crate) fn collapse_reason(before: &Sketch, after: &Sketch) -> Option { + if let Some(curve) = shrunk(before, after) { + return Some(format!("that would shrink {curve} to a point: its constraints can only be met without it")); + } + if flung(before, after) { + return Some("that would throw points of the sketch far away: its constraints have no solution near the sketch as it is".into()); + } + None +} + /// Did solving `before` into `after` throw some point further than [`FLUNG`] times the sketch's /// size, or to no number at all? fn flung(before: &Sketch, after: &Sketch) -> bool { @@ -438,10 +481,13 @@ pub(super) mod solve_counts { } /// How close (mm) a new point must land to an existing one to be connected to it. -const CONNECT_TOL: f64 = 1e-6; +pub(super) const CONNECT_TOL: f64 = 1e-6; /// New points (index `first` on) that land on an existing point, the origin included, get a /// coincident constraint to it, as when a click snaps there; `connect: false` leaves them free. +/// A point placed by parameter expressions is never tied: it follows its expressions, and a +/// Coincident to where the expressions happened to come to at draw time conflicts with the +/// next parameter change (#10703). fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result> { if !bool_(p, "connect").unwrap_or(true) { return Ok(Vec::new()); @@ -451,6 +497,9 @@ fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result) -> Result { let i = sk.add_point(at, id)?; - if let Some(q) = sk.points.get_mut(i) { - q.fixed = true; - q.exprs = Some(Box::new(exprs)); - } + place_point(sk, Some(&i), exprs); Ok(i) } @@ -791,8 +837,43 @@ fn create_sketch(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("`{key}` belongs inside `plane`: {example}"))); } } + let activate = match p.get("activate_part") { + None | Some(Value::Null) => false, + Some(Value::Bool(on)) => *on, + Some(_) => return Err(bad(cmd, "`activate_part` must be true or false")), + }; let frame = plane_frame(p, cmd)?; - let mut plane = plane_ref(s, p, cmd)?; + let plane = plane_ref(s, p, cmd)?; + // On a face of another component's body, `activate_part` activates that component at the + // picked placement first, as `component.activate` would, and the sketch is made there. It + // stays active, as after an explicit activate, so what is built from the sketch lands in the + // same part. On an error the active component goes back to what it was. + let owner = match p.get("plane") { + Some(value) if activate && face::is_face(p) => face::pick_owner(s, value, &plane, cmd)?, + _ => None, + }; + let Some((component, path)) = owner.filter(|(component, _)| *component != s.active_component) else { + return create_sketch_on(s, p, plane, frame, cmd); + }; + let before = (s.active_component, s.active_occurrence_path.clone()); + s.active_component = component; + s.active_occurrence_path = (!path.is_empty()).then(|| path.clone()); + s.revision += 1; + let made = plane_ref(s, p, cmd).and_then(|plane| create_sketch_on(s, p, plane, frame, cmd)); + match made { + Ok(mut out) => { + out["activated"] = json!({"component": component, "path": path}); + Ok(out) + } + Err(error) => { + (s.active_component, s.active_occurrence_path) = before; + Err(error) + } + } +} + +/// The rest of `sketch.create` once the active component is settled: `flip`, the sketch, the reply's `frame`. +fn create_sketch_on(s: &mut Session, p: &Value, mut plane: PlaneRef, frame: Option<&str>, cmd: &str) -> Result { if let Some(about_y) = flip_param(s, p, &plane, cmd)? { plane = PlaneRef::Flipped { base: Box::new(plane), about_y }; } @@ -878,6 +959,16 @@ pub(super) fn create_sketch_with_plane(s: &mut Session, p: &Value, plane: PlaneR } fn edit_sketch(s: &mut Session, p: &Value) -> Result { + let restore_marker = p + .get("restore_marker") + .map(|v| { + serde_json::from_value::>(v.clone()) + .map_err(|_| bad("sketch.edit", "`restore_marker` must be a nonnegative timeline position or null")) + }) + .transpose()?; + if restore_marker.flatten().is_some_and(|m| m > s.doc.features.len()) { + return Err(bad("sketch.edit", "`restore_marker` is past the end of the timeline")); + } let key = match p.get("sketch") { Some(Value::Number(n)) => n.to_string(), Some(Value::String(x)) => x.clone(), @@ -899,7 +990,16 @@ fn edit_sketch(s: &mut Session, p: &Value) -> Result { s.active_occurrence_path = (!path.is_empty()).then_some(path); } if s.active_sketch != Some(id) || s.sketch_entry.as_ref().is_none_or(|entry| entry.sketch != id) { - s.sketch_entry = Some(SketchEntry { sketch: id, ..entry_point(s) }); + s.sketch_entry = Some(SketchEntry { sketch: id, restore_marker, ..entry_point(s) }); + if restore_marker.is_some() + && let Some(index) = s.doc.feature_index(id) + { + let marker = (index + 1 < s.doc.features.len()).then_some(index + 1); + if s.doc.marker != marker { + s.doc_mut().marker = marker; + } + s.selection.clear(); + } } s.active_sketch = Some(id); s.revision += 1; @@ -908,15 +1008,32 @@ fn edit_sketch(s: &mut Session, p: &Value) -> Result { /// The design and undo history as they are now, where a sketch is entered (its id set after). fn entry_point(s: &Session) -> SketchEntry { - SketchEntry { sketch: 0, doc: s.doc.clone(), undo_len: s.undo.len(), undo_top: s.undo.last().map(|snap| snap.doc.clone()) } + SketchEntry { + sketch: 0, + doc: s.doc.clone(), + undo_len: s.undo.len(), + undo_top: s.undo.last().map(|snap| snap.doc.clone()), + restore_marker: None, + pending_moves: s.pending_moves.clone(), + visibility: s.visibility.clone(), + } +} + +fn restore_on_exit(cmd: &str, p: &Value) -> Result { + match p.get("restore_marker") { + None => Ok(true), + Some(Value::Bool(restore)) => Ok(*restore), + _ => Err(bad(cmd, "`restore_marker` must be a boolean")), + } } /// Cancel Sketch (#3838): the design as it was when the open sketch was entered. The entry is /// used only while the undo history still runs through it: the same steps before it, and every /// step since taken in this sketch. Otherwise the steps since can't be told apart from others, /// and Undo is the way back. -fn cancel_sketch(s: &mut Session, _p: &Value) -> Result { +fn cancel_sketch(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.cancel"; + let restore = restore_on_exit(cmd, p)?; let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?; let entry = s.sketch_entry.clone().filter(|entry| entry.sketch == id); let current = entry.filter(|entry| { @@ -936,26 +1053,102 @@ fn cancel_sketch(s: &mut Session, _p: &Value) -> Result { return Err(bad(cmd, "the undo history no longer leads back to where this sketch was opened: use Undo to go back")); }; let created = entry.doc.feature(id).is_none(); + let marker = if restore { entry.restore_marker.unwrap_or(entry.doc.marker) } else { s.doc.marker }; // As Undo does: the session evaluates the design it is given. + // Undo of Cancel reopens this edit, so retain its return position for a later Finish. + s.sketch_entry = entry.restore_marker.map(|_| entry.clone()); s.doc = entry.doc; + let marker = marker.filter(|m| *m < s.doc.features.len()); + if s.doc.marker != marker { + s.doc_mut().marker = marker; + } s.active_sketch = None; - s.sketch_entry = None; s.selection.clear(); s.revision += 1; Ok(json!({"sketch": id, "removed": created})) } -fn finish_sketch(s: &mut Session, _p: &Value) -> Result { +fn finish_sketch(s: &mut Session, p: &Value) -> Result { + let restore = restore_on_exit("sketch.finish", p)?; let id = s.active_sketch.take(); - s.sketch_entry = None; - s.revision += 1; let profiles = id.and_then(|i| s.model.state().sketch(i).map(|ss| ss.profiles.len())).unwrap_or(0); + if let Some(entry) = s.sketch_entry.take().filter(|entry| Some(entry.sketch) == id) + && let Some(marker) = entry.restore_marker + { + finish_edit_history(s, &entry, marker); + if restore { + let marker = marker.filter(|m| *m < s.doc.features.len()); + if s.doc.marker != marker { + s.doc_mut().marker = marker; + } + } + s.selection.clear(); + } + s.revision += 1; Ok(json!({"sketch": id, "profiles": profiles})) } +/// Fold only the steps still belonging to this edit. Its snapshots describe the complete +/// design, never the temporary marker. The anchor may have moved when the undo limit trimmed +/// older steps; if it is gone, only a stack entirely from this sketch can be folded safely. +fn finish_edit_history(s: &mut Session, entry: &SketchEntry, marker: Option) { + use std::sync::Arc; + let start = match &entry.undo_top { + Some(top) => s.undo.iter().rposition(|snap| Arc::ptr_eq(&snap.doc, top)).map(|i| i + 1), + None => Some(0), + } + .or_else(|| (s.undo.len() == crate::MAX_UNDO && s.undo.iter().all(|snap| snap.active_sketch == Some(entry.sketch))).then_some(0)); + let Some(start) = + start.filter(|&start| s.undo.get(start..).is_some_and(|steps| steps.iter().all(|snap| snap.active_sketch == Some(entry.sketch)))) + else { + return; + }; + let mut before = (*entry.doc).clone(); + before.marker = marker.filter(|m| *m < before.features.len()); + let mut after = (*s.doc).clone(); + after.marker = marker.filter(|m| *m < after.features.len()); + let changed = before != after || entry.pending_moves != s.pending_moves || entry.visibility != s.visibility; + s.undo.truncate(start); + if changed { + s.undo.push(Snapshot { + label: "Edit Sketch".into(), + doc: Arc::new(before), + active_sketch: None, + pending_moves: entry.pending_moves.clone(), + visibility: entry.visibility.clone(), + part: None, + }); + if s.undo.len() > crate::MAX_UNDO { + s.undo.remove(0); + } + } + // Redo of a step undone while editing must not reopen a finished temporary rollback. + for snap in &mut s.redo { + if snap.active_sketch == Some(entry.sketch) { + let doc = Arc::make_mut(&mut snap.doc); + doc.marker = marker.filter(|m| *m < doc.features.len()); + snap.active_sketch = None; + } + } +} + // --------------------------------------------------------------------------------------------- // Drawing +/// The id a drawing command gives its geometry, checked against the names that geometry +/// will carry: a curve's id goes into the name of the faces the curve makes +/// (`F2:side:`), and a name reads some characters as its own. An id holding one of +/// them would split every name it lands in, so it is refused here (#5858). +fn named_id(cmd: &str, id: Option<&str>) -> Result> { + match id { + Some(i) if !solidcraft_doc::persistent_name::text_fits_name(i) => { + Err(bad(cmd, format!("the id `{i}` cannot be written into a name whole; give an id without `|`, `,`, `~`, `#` or `]`"))) + } + Some(i) => Ok(Some(i.to_string())), + None => Ok(None), + } +} + fn draw_line(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.line"; let p = &super::sketch_project::snap_points(s, p, cmd)?; @@ -966,6 +1159,9 @@ fn draw_line(s: &mut Session, p: &Value) -> Result { let closed = bool_(p, "closed").unwrap_or(false); let infer = bool_(p, "infer").unwrap_or(false); let ids = string_list(cmd, p, "ids")?; + for id in &ids { + named_id(cmd, Some(id))?; + } let ((curves, cons), info) = draw(s, p, cmd, |sk, doc| { let args: Vec = list.iter().map(|v| parg(sk, doc, v, cmd)).collect::>()?; let n = args.len(); @@ -976,7 +1172,8 @@ fn draw_line(s: &mut Session, p: &Value) -> Result { for i in 0..segs { let j = (i + 1) % n; let (Some(a), Some(b)) = (args.get(i), args.get(j)) else { continue }; - if a.pos().dist(b.pos()) < 1e-9 { + // Ends closer than this would both be connected to one point (#11001). + if a.pos().dist(b.pos()) < CONNECT_TOL { return Err(bad(cmd, "zero-length line")); } let id = ids.get(i).map(String::as_str); @@ -1067,18 +1264,20 @@ fn rect_constraints(sk: &mut Sketch, l: &[usize]) -> Result> { Ok(cons) } -/// Whether line `l` being horizontal (`horizontal`) or vertical already follows from another -/// constraint than `own`: its ends coincide with the ends of a line constrained the same way (a -/// side two rectangles share), or with two points constrained level (or plumb). -fn axis_implied(sk: &Sketch, l: usize, horizontal: bool, own: &str) -> bool { - let Some(CurveKind::Line { a, b }) = sk.curves.get(l).map(|c| &c.kind) else { return false }; - let (a, b) = (*a, *b); - // Coincident points as one (union-find over the coincident constraints). +/// Canonical point indices for shared and transitively coincident sketch endpoints. +/// Kept inside the engine for command connectivity and implied-axis checks. +pub(super) fn coincident_points(sk: &Sketch) -> Vec { let mut parent: Vec = (0..sk.points.len()).collect(); - let root = |parent: &[usize], mut i: usize| { + let root = |parent: &mut [usize], mut i: usize| { for _ in 0..parent.len() { match parent.get(i) { - Some(&up) if up != i => i = up, + Some(&up) if up != i => { + let grandparent = parent.get(up).copied().unwrap_or(up); + if let Some(slot) = parent.get_mut(i) { + *slot = grandparent; + } + i = up; + } _ => break, } } @@ -1086,7 +1285,7 @@ fn axis_implied(sk: &Sketch, l: usize, horizontal: bool, own: &str) -> bool { }; for c in &sk.constraints { if let ConstraintKind::Coincident { p, q } = c.kind { - let (rp, rq) = (root(&parent, p), root(&parent, q)); + let (rp, rq) = (root(&mut parent, p), root(&mut parent, q)); if rp != rq && let Some(slot) = parent.get_mut(rp) { @@ -1094,7 +1293,18 @@ fn axis_implied(sk: &Sketch, l: usize, horizontal: bool, own: &str) -> bool { } } } - let (ra, rb) = (root(&parent, a), root(&parent, b)); + (0..parent.len()).map(|i| root(&mut parent, i)).collect() +} + +/// Whether line `l` being horizontal (`horizontal`) or vertical already follows from another +/// constraint than `own`: its ends coincide with the ends of a line constrained the same way (a +/// side two rectangles share), or with two points constrained level (or plumb). +fn axis_implied(sk: &Sketch, l: usize, horizontal: bool, own: &str) -> bool { + let Some(CurveKind::Line { a, b }) = sk.curves.get(l).map(|c| &c.kind) else { return false }; + let (a, b) = (*a, *b); + let groups = coincident_points(sk); + let root = |i: usize| groups.get(i).copied().unwrap_or(i); + let (ra, rb) = (root(a), root(b)); sk.constraints.iter().filter(|c| c.id != own).any(|c| { let ends = match (&c.kind, horizontal) { (ConstraintKind::Horizontal { l: m }, true) | (ConstraintKind::Vertical { l: m }, false) if *m != l => { @@ -1107,7 +1317,7 @@ fn axis_implied(sk: &Sketch, l: usize, horizontal: bool, own: &str) -> bool { _ => None, }; ends.is_some_and(|(p, q)| { - let (rp, rq) = (root(&parent, p), root(&parent, q)); + let (rp, rq) = (root(p), root(q)); rp != rq && ((rp, rq) == (ra, rb) || (rp, rq) == (rb, ra)) }) }) @@ -1156,16 +1366,42 @@ fn rect_result(sk_out: (Vec, Vec), names: Value, info: Value) -> out } +/// A rectangle corner: `[x, y]` of numbers, or with a coordinate typed as an expression (as a +/// `sketch.line` point is): where it is now and the expressions that place it. +fn corner_arg(doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str) -> Result<(Vec2, PointExprs)> { + let v = p.get(k).ok_or_else(|| bad(cmd, format!("`{k}` must be a point [x, y]")))?; + match expr_point(doc, v, cmd)? { + Some((at, exprs)) => Ok((at, exprs.unwrap_or_default())), + None => Ok((req_vec2(cmd, p, k)?, PointExprs::default())), + } +} + +/// Holds sketch point `i` where `exprs` place it, when it has any (see [`add_placed_point`]). +fn place_point(sk: &mut Sketch, i: Option<&usize>, exprs: PointExprs) { + if exprs.x.is_none() && exprs.y.is_none() { + return; + } + if let Some(q) = i.and_then(|i| sk.points.get_mut(*i)) { + q.fixed = true; + q.exprs = Some(Box::new(exprs)); + } +} + fn rect_two_point(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.rectangle.two_point"; - let (a, b) = (req_vec2(cmd, p, "p0")?, req_vec2(cmd, p, "p1")?); + let ((a, ea), (b, eb)) = (corner_arg(&s.doc, p, "p0", cmd)?, corner_arg(&s.doc, p, "p1", cmd)?); if (a.x - b.x).abs() < 1e-9 || (a.y - b.y).abs() < 1e-9 { return Err(bad(cmd, "the corners must differ in x and y")); } let (lo, hi) = (Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))); + // Each side of the rectangle takes its coordinate from the corner it comes from. + let (lo_x, hi_x) = if a.x <= b.x { (&ea.x, &eb.x) } else { (&eb.x, &ea.x) }; + let (lo_y, hi_y) = if a.y <= b.y { (&ea.y, &eb.y) } else { (&eb.y, &ea.y) }; let ((out, names), info) = edit(s, p, cmd, false, |sk, _| { let first = sk.points.len(); let (l, pts) = polygon_lines(sk, &[lo, Vec2::new(hi.x, lo.y), hi, Vec2::new(lo.x, hi.y)])?; + place_point(sk, pts.first(), PointExprs { x: lo_x.clone(), y: lo_y.clone() }); + place_point(sk, pts.get(2), PointExprs { x: hi_x.clone(), y: hi_y.clone() }); let mut cons = rect_constraints(sk, &l)?; mark_construction(sk, &l, p); cons.extend(connect_points(sk, first, p)?); @@ -1179,7 +1415,9 @@ fn rect_two_point(s: &mut Session, p: &Value) -> Result { /// fillet run in a scratch session that replaces the design only when both succeed. fn rect_rounded(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.rectangle.rounded"; - let (a, b) = (req_vec2(cmd, p, "p0")?, req_vec2(cmd, p, "p1")?); + // The corners may be typed as expressions: `sketch.rectangle.two_point` below places them, so + // here they are only worked out to check the radius against the sides. + let ((a, _), (b, _)) = (corner_arg(&s.doc, p, "p0", cmd)?, corner_arg(&s.doc, p, "p1", cmd)?); let r_expr = req_expr(cmd, p, "radius")?; let r = s.doc.eval(&r_expr, Kind::Length).map_err(|e| bad(cmd, format!("radius: {e}")))?; if !(r > 1e-9 && r < 1e8) { @@ -1241,7 +1479,7 @@ fn rect_rounded(s: &mut Session, p: &Value) -> Result { fn rect_center(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.rectangle.center"; - let (c, k) = (req_vec2(cmd, p, "center")?, req_vec2(cmd, p, "corner")?); + let ((c, ec), (k, ek)) = (corner_arg(&s.doc, p, "center", cmd)?, corner_arg(&s.doc, p, "corner", cmd)?); let h = Vec2::new((k.x - c.x).abs(), (k.y - c.y).abs()); if h.x < 1e-9 || h.y < 1e-9 { return Err(bad(cmd, "the corner must differ from the centre in x and y")); @@ -1249,6 +1487,14 @@ fn rect_center(s: &mut Session, p: &Value) -> Result { let ((out, names), info) = edit(s, p, cmd, false, |sk, _| { let first = sk.points.len(); let (l, pts) = polygon_lines(sk, &[c - h, Vec2::new(c.x + h.x, c.y - h.y), c + h, Vec2::new(c.x - h.x, c.y + h.y)])?; + // The corner given sits in the quadrant it was drawn in. + let at = match (k.x >= c.x, k.y >= c.y) { + (true, true) => 2, + (false, true) => 3, + (true, false) => 1, + (false, false) => 0, + }; + place_point(sk, pts.get(at), ek); let mut cons = rect_constraints(sk, &l)?; // Both diagonals (construction), the centre at their crossing. Only the first carries // the midpoint constraint: diagonals of a parallelogram bisect each other, so a second @@ -1262,6 +1508,7 @@ fn rect_center(s: &mut Session, p: &Value) -> Result { } } let cp = sk.add_point(c, None)?; + place_point(sk, Some(&cp), ec); cons.push(add_c(sk, ConstraintKind::Midpoint { p: cp, l: diag })?); } mark_construction(sk, &l, p); @@ -1298,17 +1545,44 @@ fn rect_three_point(s: &mut Session, p: &Value) -> Result { pub(super) fn radius_arg(p: &Value, cmd: &str) -> Result { let r = match (num(p, "radius"), num(p, "diameter")) { (Some(r), _) => r, + // `radius` wins over `diameter` whatever its form, so a bad one is not passed over. + (None, _) if p.get("radius").is_some_and(|v| !v.is_null()) => return Err(bad(cmd, "`radius` must be a number")), (None, Some(d)) => d / 2.0, - _ => return Err(bad(cmd, "needs `radius` or `diameter`")), + // A value that is there but is no number is not a missing one. + _ => { + let given = ["radius", "diameter"].into_iter().find(|k| p.get(k).is_some_and(|v| !v.is_null())); + return Err(bad(cmd, given.map_or_else(|| "needs `radius` or `diameter`".to_string(), |k| format!("`{k}` must be a number")))); + } }; if r > 1e-9 { Ok(r) } else { Err(bad(cmd, "radius must be positive")) } } +/// The size of a circle: [`radius_arg`], or a `radius` / `diameter` typed as an expression over +/// the design's parameters, which is then a driving dimension on the circle (the parameter +/// `dN` holds the expression) so that the circle follows it. A bare number reads in the design's +/// unit, and an expression naming no parameter is just the number it comes to. Returns the +/// radius, and the expression with whether it is a diameter. `radius` wins over `diameter`. +fn circle_size(s: &Session, p: &Value, cmd: &str) -> Result<(f64, Option<(String, bool)>)> { + let radius_given = p.get("radius").is_some_and(|v| !v.is_null()); + let key = if radius_given { "radius" } else { "diameter" }; + if !p.get(key).is_some_and(Value::is_string) { + return Ok((radius_arg(p, cmd)?, None)); + } + let e = s.doc.with_design_unit(req_expr(cmd, p, key)?.as_str(), Kind::Length); + let v = s.doc.eval(&e, Kind::Length).map_err(|e| bad(cmd, format!("{key}: {e}")))?; + let r = if key == "diameter" { v / 2.0 } else { v }; + if !(r > 1e-9 && r < 1e8) { + return Err(bad(cmd, "radius must be positive")); + } + let driven = !solidcraft_doc::expr::references(&e).is_empty(); + Ok((r, driven.then_some((e, key == "diameter")))) +} + fn circle_center(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.circle.center"; let p = &super::sketch_project::snap_points(s, p, cmd)?; - let r = radius_arg(p, cmd)?; - let id = str_(p, "id").map(str::to_string); + let (r, size) = circle_size(s, p, cmd)?; + let id = named_id(cmd, str_(p, "id"))?; let (out, info) = draw(s, p, cmd, |sk, doc| { let c = req_parg(sk, doc, p, "center", cmd)?; // The origin is the sketch's frame, not a hold on the geometry: a circle centred there @@ -1326,6 +1600,13 @@ fn circle_center(s: &mut Session, p: &Value) -> Result { { cons.push(add_c(sk, ConstraintKind::PointOnCurve { p: q, c: ci })?); } + // A size typed as an expression is a dimension driven by the parameters it names. + if let Some((e, diameter)) = &size { + let unit = solidcraft_doc::expr::length_unit_or_mm(&doc.units).to_string(); + let pname = doc.new_model_param(e, &unit); + let kind = if *diameter { ConstraintKind::Diameter { c: ci, value: 2.0 * r } } else { ConstraintKind::Radius { c: ci, value: r } }; + cons.push(sk.add_constraint(kind, Some(pname))?); + } Ok((ids_of(sk, &[ci]), cons)) })?; Ok(result(out, info)) @@ -1362,12 +1643,21 @@ pub(super) fn circumcircle(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> { fn circle_three(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.circle.three_point"; - let (a, b, c) = (req_vec2(cmd, p, "p0")?, req_vec2(cmd, p, "p1")?, req_vec2(cmd, p, "p2")?); - let (o, r) = circumcircle(a, b, c).ok_or_else(|| bad(cmd, "the points are collinear"))?; - let (out, info) = draw(s, p, cmd, |sk, _| { + let p = &super::sketch_project::snap_points(s, p, cmd)?; + let (out, info) = draw(s, p, cmd, |sk, doc| { + let (a, b, c) = (req_parg(sk, doc, p, "p0", cmd)?, req_parg(sk, doc, p, "p1", cmd)?, req_parg(sk, doc, p, "p2", cmd)?); + let (o, r) = circumcircle(a.pos(), b.pos(), c.pos()).ok_or_else(|| bad(cmd, "the points are collinear"))?; let ci = sk.add_circle(o, r, None, None)?; mark_construction(sk, &[ci], p); - Ok((ids_of(sk, &[ci]), Vec::new())) + // A click snapped to a point keeps the circle on it (#9858), as the centre circle's + // `through` click does (#3099) and the 3-Point Arc's clicks do. + let mut cons = Vec::new(); + for q in [a, b, c] { + if let Some(point) = q.idx() { + cons.push(add_c(sk, ConstraintKind::PointOnCurve { p: point, c: ci })?); + } + } + Ok((ids_of(sk, &[ci]), cons)) })?; Ok(result(out, info)) } @@ -1375,7 +1665,7 @@ fn circle_three(s: &mut Session, p: &Value) -> Result { fn arc_three(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.three_point"; let p = &super::sketch_project::snap_points(s, p, cmd)?; - let id = str_(p, "id").map(str::to_string); + let id = named_id(cmd, str_(p, "id"))?; let (out, info) = draw(s, p, cmd, |sk, doc| { let (a, b) = (req_parg(sk, doc, p, "start", cmd)?, req_parg(sk, doc, p, "end", cmd)?); let t = req_parg(sk, doc, p, "through", cmd)?; @@ -1402,7 +1692,7 @@ fn arc_three(s: &mut Session, p: &Value) -> Result { fn arc_center(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.center_point"; let p = &super::sketch_project::snap_points(s, p, cmd)?; - let id = str_(p, "id").map(str::to_string); + let id = named_id(cmd, str_(p, "id"))?; let sweep = num(p, "sweep"); let (out, info) = draw(s, p, cmd, |sk, doc| { let c = req_parg(sk, doc, p, "center", cmd)?; @@ -1597,7 +1887,7 @@ fn slot_overall(s: &mut Session, p: &Value) -> Result { fn draw_point(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.point"; - let id = str_(p, "id").map(str::to_string); + let id = named_id(cmd, str_(p, "id"))?; // A point snapped while drawing (`"mid:"`, `"on::x,y"`, a model vertex or edge): // the snap makes it, held by its constraint, as it does for a line's end. Taken as bare // coordinates it was free to move off the midpoint it was put on (#4691). @@ -1660,7 +1950,7 @@ fn constrain(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Sketch) // fully determined: it is then redundant, see `redundancy`). let holds = residual.is_some_and(|r| r <= solidcraft_sketch::CONSISTENT); if let Some((first, second)) = order.filter(|_| !holds) { - apply_in_order(sk, &rep, &[first], second, cmd)?; + apply_in_order(sk, &rep, &[first], second, cmd, std::slice::from_ref(&id))?; } Ok(id) })?; @@ -1749,7 +2039,9 @@ fn keep_size(sk: &Sketch, e: Ent) -> Vec { /// If the second can't move (fixed, projected or fully determined), the first moves instead; /// if neither can, the constraint conflicts and nothing changes. Everything else moves as /// little as it can. Later solves are ordinary ones (nothing is held). -pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent], second: Ent, cmd: &str) -> Result<()> { +/// `new` are the ids of the constraints the command just added: the refusal names the +/// constraints the new one conflicts with, never the new one's own id (#9735). +pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent], second: Ent, cmd: &str, new: &[String]) -> Result<()> { let second_locked = ent_locked(sk, rep, second); // (held geometry, temporary size constraints) to try in turn. let mut tries: Vec<(Hold, Vec)> = Vec::new(); @@ -1809,9 +2101,90 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent], return Ok(()); } } + // Neither holding one side nor a plain solve places it. Name the constraints the new one + // conflicts with (the sketch may well have free degrees of freedom: the conflict is with + // its own constraints, not the entities being fixed or fully constrained, #9735). The + // violated solve names only what it gave up on; the conflict is the sketch's own set of + // constraints that leaves the new one unsatisfiable. + let conflicts: Vec = sk + .constraints + .iter() + .position(|c| new.contains(&c.id)) + .map(|ci| solidcraft_sketch::determined_by(sk, ci)) + .unwrap_or_default() + .into_iter() + .filter_map(|k| sk.constraints.get(k)) + .filter(|c| !new.contains(&c.id)) + .map(|c| c.id.clone()) + .collect(); + let conflicts = if conflicts.is_empty() { conflict_probe(sk, new) } else { conflicts }; + let conflicts = if conflicts.is_empty() { direction_conflicts(sk, new) } else { conflicts }; + if !conflicts.is_empty() { + return Err(bad(cmd, format!("that conflicts with the sketch: it conflicts with {}", conflicts.join(", ")))); + } Err(bad(cmd, "that conflicts with the sketch: neither entity can move to satisfy it (they are fixed or fully constrained)")) } +/// A sketch this large is not probed constraint by constraint for a conflict message. +const CONFLICT_PROBE_MAX: usize = 64; + +/// The sketch's own constraints (ids, in creation order) that keep the just-added constraints +/// `new` unsatisfiable: each constraint whose removal lets the sketch solve again is dropped, +/// so what is left is a set the new constraint genuinely conflicts with (a constraint the +/// failure does not need is not named). A solve that collapses or flings the sketch is not a +/// solution. Empty when the sketch is too large to probe, already solves, or fails whatever +/// the sketch's own constraints — the new one asks the impossible of the geometry itself. +fn conflict_probe(sk: &Sketch, new: &[String]) -> Vec { + let is_new = |c: &solidcraft_sketch::Constraint| new.contains(&c.id); + let holds = |s: &Sketch| { + let mut t = s.clone(); + let rep = solve_with(&mut t, &Hold::default(), None, Analysis::StatusOnly, None); + rep.ok() && shrunk(s, &t).is_none() && !flung(s, &t) + }; + if sk.constraints.len() > CONFLICT_PROBE_MAX || holds(sk) { + return Vec::new(); + } + let mut keep: std::collections::HashSet = sk.constraints.iter().filter(|c| !is_new(c)).map(|c| c.id.clone()).collect(); + for id in sk.constraints.iter().filter(|c| !is_new(c)).map(|c| c.id.clone()).collect::>() { + if !keep.contains(&id) { + continue; + } + let mut t = sk.clone(); + t.constraints.retain(|c| is_new(c) || (c.id != id && keep.contains(&c.id))); + if !holds(&t) { + keep.remove(&id); + } + } + sk.constraints.iter().filter(|c| keep.contains(&c.id)).map(|c| c.id.clone()).collect() +} + +/// The existing direction constraints (horizontal, vertical, angle, parallel …) that read one +/// of the two lines of a just-added Parallel or Perpendicular: the solver cannot turn a line +/// off a direction another constraint already fixed (and reads no gradient to turn with at a +/// line pair already at the forbidden angle), so those constraints are what it conflicts with. +/// Empty for any other kind of new constraint. +fn direction_conflicts(sk: &Sketch, new: &[String]) -> Vec { + let pair = sk.constraints.iter().find(|c| new.contains(&c.id)).and_then(|c| match c.kind { + ConstraintKind::Parallel { a, b } | ConstraintKind::Perpendicular { a, b } => Some((a, b)), + _ => None, + }); + let Some((a, b)) = pair else { return Vec::new() }; + sk.constraints + .iter() + .filter(|c| !new.contains(&c.id)) + .filter(|c| { + matches!(c.kind, + ConstraintKind::Horizontal { l } | ConstraintKind::Vertical { l } | ConstraintKind::LineAngle { l, .. } + if l == a || l == b + ) || matches!(c.kind, + ConstraintKind::Parallel { a: x, b: y } | ConstraintKind::Perpendicular { a: x, b: y } | ConstraintKind::Collinear { a: x, b: y } | ConstraintKind::Angle { a: x, b: y, .. } + if x == a || x == b || y == a || y == b + ) + }) + .map(|c| c.id.clone()) + .collect() +} + /// Degrees of freedom of a sketch as it is. pub(super) fn dof_now(sk: &Sketch) -> usize { solve_with(&mut sk.clone(), &Hold::default(), None, Analysis::Freedom, None).dof @@ -1997,17 +2370,38 @@ fn c_coincident(s: &mut Session, p: &Value) -> Result { if let Some((a, b)) = line_points { return Ok(ConstraintKind::Coincident { p: a, q: b }); } + // A line's middle, `{midpoint: line}` as a selected midpoint is sent (#10311): the point + // tied there by a Midpoint constraint stands for it, made as Horizontal/Vertical makes it. + let middle = |sk: &mut Sketch, key: &str| -> Result> { + let Some(line) = p.get(key).and_then(|v| v.get("midpoint")) else { return Ok(None) }; + let l = curve_ref(sk, Some(line), cmd, "midpoint")?; + AlignmentTarget::Midpoint(l).materialize(sk, cmd).map(Some) + }; + let (a_mid, b_mid) = (middle(sk, "a")?, middle(sk, "b")?); let aref = p.get("a").and_then(Value::as_str).unwrap_or_default(); - let bref = p.get("b").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`b` must be a point or curve"))?; + let bref = p.get("b").and_then(Value::as_str); + let b_point = match (b_mid, bref) { + (Some(b), _) => Some(b), + (None, Some(r)) => sk.resolve_point(r), + (None, None) => return Err(bad(cmd, "`b` must be a point or curve")), + }; + let bref = bref.unwrap_or_default(); // A curve (or sketch axis) picked first and a point second: the point goes onto it. - if sk.resolve_point(aref).is_none() - && let Some(q) = sk.resolve_point(bref) + if a_mid.is_none() + && sk.resolve_point(aref).is_none() + && let Some(q) = b_point && let Some(c) = curve_or_axis(sk, aref)? { return Ok(ConstraintKind::PointOnCurve { p: q, c }); } - let a = point_ref(sk, p.get("a"), cmd, "a")?; - if let Some(b) = sk.resolve_point(bref) { + let a = match a_mid { + Some(a) => a, + None => point_ref(sk, p.get("a"), cmd, "a")?, + }; + if let Some(b) = b_point { + if a == b && (a_mid.is_some() || b_mid.is_some()) { + return Err(bad(cmd, "that point is already the line's midpoint")); + } return Ok(ConstraintKind::Coincident { p: a, q: b }); } let c = curve_or_axis(sk, bref)?.ok_or_else(|| bad(cmd, format!("unknown entity `{bref}`")))?; @@ -2055,7 +2449,7 @@ fn coincident_circles(s: &mut Session, p: &Value, cmd: &str, a: usize, b: usize) if ids.is_empty() { return Err(bad(cmd, "these circles already lie on each other")); } - apply_in_order(sk, &rep, &[Ent::Curve(a)], Ent::Curve(b), cmd)?; + apply_in_order(sk, &rep, &[Ent::Curve(a)], Ent::Curve(b), cmd, &ids)?; Ok(ids) })?; Ok(json!({"constraint": ids[0], "constraints": ids, "sketch": info})) @@ -2180,11 +2574,21 @@ fn c_perpendicular(s: &mut Session, p: &Value) -> Result { }) } fn c_concentric(s: &mut Session, p: &Value) -> Result { - let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.concentric", &["a", "b"])?; - constrain(s, p, "sketch.constraint.concentric", |sk| { - two_curves(sk, p, "sketch.constraint.concentric") - .and_then(|ab| two_different("sketch.constraint.concentric", ab)) - .map(|(a, b)| ConstraintKind::Concentric { a, b }) + let cmd = "sketch.constraint.concentric"; + let p = &super::sketch_project::project_operands(s, p, cmd, &["a", "b"])?; + constrain(s, p, cmd, |sk| { + let centre = |key: &str| { + let curve = sk.curves.get(sk.curve_index(p.get(key)?.as_str()?)?)?; + match curve.kind { + CurveKind::Circle { c, .. } | CurveKind::Arc { c, .. } => Some(c), + _ => None, + } + }; + let point = |key: &str| sk.resolve_point(p.get(key)?.as_str()?); + if let Some((p, q)) = centre("a").zip(point("b")).or_else(|| centre("b").zip(point("a"))) { + return Ok(ConstraintKind::Coincident { p, q }); + } + two_curves(sk, p, cmd).and_then(|ab| two_different(cmd, ab)).map(|(a, b)| ConstraintKind::Concentric { a, b }) }) } fn c_collinear(s: &mut Session, p: &Value) -> Result { @@ -2345,7 +2749,7 @@ fn c_symmetry(s: &mut Session, p: &Value) -> Result { } // The first entity and the symmetry line stay; the second mirrors onto it. if let Some((a, b)) = order { - apply_in_order(sk, &rep, &[a, Ent::Curve(l)], b, cmd)?; + apply_in_order(sk, &rep, &[a, Ent::Curve(l)], b, cmd, &out)?; } Ok(out) })?; @@ -2397,7 +2801,7 @@ fn symmetry_about_point(sk: &mut Sketch, p: &Value, c: usize, cmd: &str) -> Resu let mut out = symmetry_pairs(sk, &[(pa, pb)], c, cmd)?; out.push(add_c(sk, ConstraintKind::Equal { a: ca, b: cb })?); if let Some((a, b)) = order { - apply_in_order(sk, &rep, &[a, Ent::Point(c)], b, cmd)?; + apply_in_order(sk, &rep, &[a, Ent::Point(c)], b, cmd, &out)?; } return Ok(out); } @@ -2408,7 +2812,7 @@ fn symmetry_about_point(sk: &mut Sketch, p: &Value, c: usize, cmd: &str) -> Resu let out = symmetry_pairs(sk, &pairs, c, cmd)?; // The first entity and the centre stay; the second mirrors onto it. if let Some((a, b)) = order { - apply_in_order(sk, &rep, &[a, Ent::Point(c)], b, cmd)?; + apply_in_order(sk, &rep, &[a, Ent::Point(c)], b, cmd, &out)?; } Ok(out) } @@ -2898,7 +3302,7 @@ fn diameter_about(sk: &Sketch, l: usize, ty: &str) -> bool { fn arc_len(sk: &Sketch, c: usize) -> Option { match sk.segs(c).first()? { - solidcraft_geom::Seg2::Arc { radius, sweep, .. } if matches!(sk.curves.get(c)?.kind, CurveKind::Arc { .. }) => Some(radius * sweep), + solidcore_record::Seg2::Arc { radius, sweep, .. } if matches!(sk.curves.get(c)?.kind, CurveKind::Arc { .. }) => Some(radius * sweep), _ => None, } } diff --git a/crates/engine/src/cmd/sketch_3d.rs b/crates/engine/src/cmd/sketch_3d.rs index de10b0603..365800159 100644 --- a/crates/engine/src/cmd/sketch_3d.rs +++ b/crates/engine/src/cmd/sketch_3d.rs @@ -4,7 +4,7 @@ //! point, and usable as sweep and pipe paths. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_sketch::WireSpace; use super::sketch::edit; diff --git a/crates/engine/src/cmd/sketch_3d_frame_tests.rs b/crates/engine/src/cmd/sketch_3d_frame_tests.rs index 9354fcf38..b1f786aa0 100644 --- a/crates/engine/src/cmd/sketch_3d_frame_tests.rs +++ b/crates/engine/src/cmd/sketch_3d_frame_tests.rs @@ -1,6 +1,7 @@ use crate::Session; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_sketch::WireSpace; fn run(s: &mut Session, cmd: &str, params: Value) -> Value { @@ -40,7 +41,7 @@ fn wire_frame_second_occurrence_world_inputs_move_and_reopen() { } near(sk.wires[sk.wire_index(&a).unwrap()].fit[0], Vec3::new(2.0, 3.0, 5.0)); near(sk.wires[sk.wire_index(&point).unwrap()].fit[0], Vec3::new(2.0, 3.0, 5.0)); - let world = s.world_state(); + let world = s.world_state().unwrap(); let ws = &world.sketch(sketch).unwrap().sketch; let sw = &ws.wires[ws.wire_index(&spline).unwrap()]; near(sw.fit[0], Vec3::new(14.0, 32.0, 55.0)); @@ -61,9 +62,9 @@ fn wire_frame_second_occurrence_world_inputs_move_and_reopen() { assert_eq!(restored.sketch(sketch).unwrap().wires, s.doc.sketch(sketch).unwrap().wires); // Same definition at the first placement has the local geometry; selected second is exact. run(&mut s, "component.activate", json!({"component":component,"occurrence":first,"path":[first]})); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(3.0, 2.0, 6.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(3.0, 2.0, 6.0)); run(&mut s, "component.activate", json!({"component":component,"occurrence":second,"path":[second]})); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(18.0, 33.0, 46.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(18.0, 33.0, 46.0)); } #[test] @@ -77,10 +78,10 @@ fn wire_frame_pending_moves_other_owner_and_legacy_world_do_not_join() { run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0],"capture":false})); let point = run(&mut s, "sketch.point3d", json!({"point":[22,32,45]}))["point"].as_str().unwrap().to_string(); near(s.doc.sketch(sketch).unwrap().wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(2.0, 3.0, 5.0)); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == legacy).unwrap().fit[0], Vec3::new(2.0, 3.0, 5.0)); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == legacy).unwrap().fit[0], Vec3::new(2.0, 3.0, 5.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); run(&mut s, "component.capture_position", json!({})); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); // Explicit target in root must not inherit the unrelated active component frame. run(&mut s, "sketch.finish", json!({})); run(&mut s, "component.activate", json!({"component":0})); @@ -138,7 +139,7 @@ fn wire_frame_include_other_component_refresh_break_lost_and_reopen() { let sk = s.doc.sketch(sketch).unwrap(); assert_eq!(sk.wires[0], initial); assert!(!sk.link(&link).unwrap().lost); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(world.sketch(sketch).unwrap().sketch.wires[0].pts.iter().all(|p| (p.x - 10.0).abs() < 1e-7)); let before = s.doc.to_json(); run(&mut s, "sketch.break_link", json!({"link":link})); @@ -179,7 +180,7 @@ fn wire_frame_pipe_component_and_world_paths_have_analytic_volume_and_position() }; run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.pipe", json!({"path_sketch":sketch,"path":[wire],"diameter":4})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); // Property measurement uses fine adaptive tessellation; the viewport mesh alone // undershoots a small circular profile by about 0.64% at its display chord tolerance. @@ -188,7 +189,7 @@ fn wire_frame_pipe_component_and_world_paths_have_analytic_volume_and_position() let bounds = body.mesh().bounds(); near((bounds.min + bounds.max) / 2.0, Vec3::new(17.0, 32.0, 50.0)); run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0]})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); let bounds = body.mesh().bounds(); near((bounds.min + bounds.max) / 2.0, Vec3::new(if space == WireSpace::Component { 22.0 } else { 17.0 }, 32.0, 50.0)); @@ -243,7 +244,7 @@ fn wire_frame_cross_owner_sweep_follows_world_path_edit_undo_and_reopen() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.sweep", json!({"sketch":profile,"path_sketch":path_sketch,"path":[wire],"operation":"new"})); let check = |s: &Session, length: f64| { - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); let measure = solidcraft_kernel::measure(&body.body).unwrap(); assert!((measure.volume - 4.0 * std::f64::consts::PI * length).abs() < 0.05, "{}", measure.volume); @@ -285,7 +286,7 @@ fn wire_frame_three_owner_sweep_profile_move_invalidates_warm_cache() { run(&mut s, "occurrence.move", json!({"occurrence":consumer_occurrence,"axis":[0,0,1],"angle":"90 deg","translate":[100,-30,20]})); run(&mut s, "solid.sweep", json!({"sketch":profile,"path_sketch":path_sketch,"path":[wire],"operation":"new"})); let measure = |session: &Session, x: f64| { - let state = session.world_state(); + let state = session.world_state().unwrap(); let body = state.bodies.last().unwrap(); assert_eq!(body.component, consumer["component"].as_u64().unwrap()); let result = solidcraft_kernel::measure(&body.body).unwrap(); @@ -366,14 +367,14 @@ fn arc3d_follows_the_sketch_owner_placement() { near(arc.center, Vec3::new(0.0, 0.0, 5.0)); assert!((arc.radius - 10.0).abs() < 1e-7, "radius {}", arc.radius); let _ = sk; - let world = s.world_state(); + let world = s.world_state().unwrap(); let ws = &world.sketch(sketch).unwrap().sketch; let arc = ws.wires[ws.wire_index(&id).unwrap()].arc.unwrap(); near(arc.center, Vec3::new(20.0, 30.0, 45.0)); near(ws.wires[ws.wire_index(&id).unwrap()].fit[0], Vec3::new(20.0, 40.0, 45.0)); drop(world); run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0]})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let ws = &world.sketch(sketch).unwrap().sketch; let arc = ws.wires[ws.wire_index(&id).unwrap()].arc.unwrap(); near(arc.center, Vec3::new(25.0, 30.0, 45.0)); @@ -412,7 +413,7 @@ fn arc3d_pipes_along_the_arc() { let wire = run(&mut s, "sketch.arc3d", json!({"start":[20,0,0],"through":[d,d,0],"end":[0,20,0]}))["curves"][0].as_str().unwrap().to_string(); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.pipe", json!({"path_sketch":sketch,"path":[wire],"diameter":4})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); let measure = solidcraft_kernel::measure(&body.body).unwrap(); let quarter = 20.0 * std::f64::consts::FRAC_PI_2; @@ -440,3 +441,36 @@ fn line3d_spline3d_point3d_need_a_3d_sketch() { assert!(info.enabled, "{id} not offered inside a 3D sketch: {:?}", info.disabled_reason); } } + +#[test] +fn wire_frame_copies_keep_component_and_legacy_coordinates() { + let (mut s, _, first, second) = second_frame(); + let sketch = s.active_sketch.unwrap(); + let fit = [Vec3::new(20.0, 40.0, 45.0), Vec3::new(10.0, 30.0, 45.0), Vec3::new(20.0, 20.0, 45.0)]; + let local = run(&mut s, "sketch.arc3d", json!({"start":fit[0],"through":fit[1],"end":fit[2]}))["curves"][0].as_str().unwrap().to_owned(); + let legacy = s.doc_mut().sketch_mut(sketch).unwrap().add_drawn_arc_in(&fit, WireSpace::World).unwrap(); + s.refresh(); + let originals = s.doc.sketch(sketch).unwrap().wires.clone(); + let out = run(&mut s, "sketch.move", json!({"entities":[local,legacy],"copy":true,"translate":[1.6,0],"angle":90})); + let copied: Vec<_> = out["curves"].as_array().unwrap().iter().map(|id| id.as_str().unwrap().to_owned()).collect(); + assert_eq!(copied.len(), 2); + let sk = s.doc.sketch(sketch).unwrap(); + assert_eq!(&sk.wires[..2], &originals); + assert_eq!(sk.wires[2].space, WireSpace::Component); + assert_eq!(sk.wires[3].space, WireSpace::World); + near(sk.wires[2].arc.unwrap().center, Vec3::new(1.6, 0.0, 5.0)); + near(sk.wires[3].arc.unwrap().center, Vec3::new(20.0, 31.6, 45.0)); + for wire in s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().filter(|w| copied.contains(&w.id)) { + near(wire.arc.unwrap().center, Vec3::new(20.0, 31.6, 45.0)); + near(wire.fit[0], Vec3::new(10.0, 31.6, 45.0)); + } + let component = s.active_component; + run(&mut s, "component.activate", json!({"component":component,"occurrence":first,"path":[first]})); + let world = s.world_state().unwrap(); + let wires = &world.sketch(sketch).unwrap().sketch.wires; + near(wires.iter().find(|w| w.id == copied[0]).unwrap().arc.unwrap().center, Vec3::new(1.6, 0.0, 5.0)); + near(wires.iter().find(|w| w.id == copied[1]).unwrap().arc.unwrap().center, Vec3::new(20.0, 31.6, 45.0)); + run(&mut s, "component.activate", json!({"component":component,"occurrence":second,"path":[second]})); + let restored = solidcraft_doc::format::read(&s.doc.to_json()).unwrap(); + assert_eq!(restored.sketch(sketch).unwrap().wires, s.doc.sketch(sketch).unwrap().wires); +} diff --git a/crates/engine/src/cmd/sketch_axis_ref_tests.rs b/crates/engine/src/cmd/sketch_axis_ref_tests.rs index 828b44ee0..41329fe10 100644 --- a/crates/engine/src/cmd/sketch_axis_ref_tests.rs +++ b/crates/engine/src/cmd/sketch_axis_ref_tests.rs @@ -3,7 +3,8 @@ //! reported in `created`, and left out of profiles. A real curve with that id wins. use serde_json::{Value, json}; -use solidcraft_geom::{Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{CurveKind, LinkSource, Sketch}; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_canvas.rs b/crates/engine/src/cmd/sketch_canvas.rs index ed3775443..689fb5a76 100644 --- a/crates/engine/src/cmd/sketch_canvas.rs +++ b/crates/engine/src/cmd/sketch_canvas.rs @@ -1,8 +1,9 @@ //! Canvases (reference images on planes) and decals (images on planar faces). use serde_json::{Value, json}; +use solidcore_record::Vec2; use solidcraft_doc::canvas::{Canvas, MAX_CANVAS_BYTES, base64_decode, base64_encode, image_info}; -use solidcraft_geom::Vec2; +use solidcraft_geom::prelude::*; use super::CommandSpec; use crate::params::{bad, bool_, num, str_, vec2}; @@ -67,7 +68,7 @@ fn make(s: &mut Session, p: &Value, cmd: &str, decal: bool) -> Result { id, name: name.clone(), format: format.into(), - data: base64_encode(&bytes), + data: base64_encode(&bytes).into(), pixels, plane, center, diff --git a/crates/engine/src/cmd/sketch_centre_align_tests.rs b/crates/engine/src/cmd/sketch_centre_align_tests.rs index c9a1e53f5..1f39fb37d 100644 --- a/crates/engine/src/cmd/sketch_centre_align_tests.rs +++ b/crates/engine/src/cmd/sketch_centre_align_tests.rs @@ -4,7 +4,7 @@ //! acceptance criteria the reporter's manual tool path needed. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_circle_edge_tests.rs b/crates/engine/src/cmd/sketch_circle_edge_tests.rs index b59961c24..c4544b52c 100644 --- a/crates/engine/src/cmd/sketch_circle_edge_tests.rs +++ b/crates/engine/src/cmd/sketch_circle_edge_tests.rs @@ -5,7 +5,8 @@ //! reopening. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::Session; @@ -152,8 +153,16 @@ fn a_tube_keeps_its_bore_when_its_inner_diameter_changes() { let volume = m["total"]["volume_mm3"].as_f64().unwrap(); assert!((volume / (100.0 * area) - 1.0).abs() < 0.001, "{m}"); let body = &s.model.state().bodies[0].body; - assert!(!body.contains(solidcraft_geom::Vec3::new(0.0, 0.0, 50.0)), "the bore stays empty"); - assert!(body.contains(solidcraft_geom::Vec3::new(inner + 5.0, 0.0, 50.0)), "the wall stays solid"); + assert_eq!( + body.classify_point(solidcore_record::Vec3::new(0.0, 0.0, 50.0)).unwrap(), + solidcraft_kernel::PointClass::Outside, + "the bore stays empty" + ); + assert_eq!( + body.classify_point(solidcore_record::Vec3::new(inner + 5.0, 0.0, 50.0)).unwrap(), + solidcraft_kernel::PointClass::Inside, + "the wall stays solid" + ); } for dimension_first in [false, true] { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs index b9eddfa49..8497a0d68 100644 --- a/crates/engine/src/cmd/sketch_clipboard.rs +++ b/crates/engine/src/cmd/sketch_clipboard.rs @@ -8,7 +8,8 @@ use std::collections::BTreeMap; use serde_json::{Value, json}; -use solidcraft_geom::{Aabb2, Vec2}; +use solidcore_record::Vec2; +use solidcraft_geom::Aabb2; use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch}; use super::sketch::edit; @@ -71,6 +72,38 @@ pub struct SketchClip { pub pastes: u32, } +impl SketchClip { + /// This clipboard as another design pastes it (#9258): at the same sketch coordinates (its + /// sketch ids mean nothing there), and with nothing that names the copied design's + /// parameters. A dimension whose expression names a parameter keeps its value, in its unit + /// (another design's parameter of the same name would be another thing); a text keeps its + /// words, height and angle as numbers. + pub fn for_another_design(&self) -> SketchClip { + let mut clip = self.clone(); + clip.sketch = u64::MAX; + clip.pastes = 0; + for c in &mut clip.constraints { + let Some((expr, unit)) = c.param.as_mut() else { continue }; + if solidcraft_doc::expr::references(expr).is_empty() { + continue; + } + let v = c.kind.value().unwrap_or_default(); + if solidcraft_doc::expr::unit_info(unit).is_none() { + *unit = if c.kind.is_angle() { "rad" } else { "mm" }.into(); + } + let value = if c.kind.is_angle() { solidcraft_doc::expr::Value::angle(v) } else { solidcraft_doc::expr::Value::length(v) }; + let shown = solidcraft_doc::expr::value_in_unit(value, unit); + *expr = format!("{}", if shown.is_finite() { shown } else { 0.0 }); + } + for (src, _) in &mut clip.texts { + if let LinkSource::Text { exprs, .. } = src { + *exprs = Default::default(); + } + } + clip + } +} + /// Curve and point ids named by `entities`, or the selected sketch geometry. fn chosen(s: &Session, p: &Value, cmd: &str) -> Result> { if p.get("entities").is_some() { diff --git a/crates/engine/src/cmd/sketch_clipboard_tests.rs b/crates/engine/src/cmd/sketch_clipboard_tests.rs index 7d1e919e9..8809c6a2c 100644 --- a/crates/engine/src/cmd/sketch_clipboard_tests.rs +++ b/crates/engine/src/cmd/sketch_clipboard_tests.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, Sketch}; use crate::{Sel, Session}; @@ -188,7 +189,7 @@ fn paste_into_another_sketch_lands_on_its_plane() { assert!(p[0].dist(Vec2::new(0.0, 0.0)) < 1e-6 && p[1].dist(Vec2::new(20.0, 0.0)) < 1e-6, "{p:?}"); assert_eq!(sk.constraints.iter().filter(|c| c.kind.is_dimension()).count(), 3); assert!(!sk.constraints.iter().any(|c| c.kind.refers_to_point(0))); - let st = s.world_state(); + let st = s.world_state().unwrap(); let ss = st.sketch(b).unwrap(); let w = ss.plane.to_world(Vec2::new(20.0, 10.0)); assert!(w.y.abs() < 1e-9 && (w.x - 20.0).abs() < 1e-9, "{w:?}"); @@ -251,3 +252,45 @@ fn clipboard_commands_refuse_parameters_that_are_not_an_object() { // Nothing was cut or pasted by the refused calls. assert!(s.execute("sketch.paste", &json!({})).is_ok(), "the clipboard still holds the copy"); } + +/// Sketch geometry copied in one design pastes into a sketch of another (#9258): at the same +/// coordinates, with its constraints and dimensions. A dimension that named the first design's +/// parameter keeps its value as a number in its unit (the other design's `w` is another thing); +/// one typed as a number keeps it. +#[test] +fn sketch_geometry_pastes_into_another_design_with_values_not_foreign_parameters() { + let mut a = Session::default(); + run(&mut a, "parameters.change", json!({"name": "w", "expression": "1 in"})); + run(&mut a, "sketch.create", json!({"plane": "XY"})); + let rect = strs(&run(&mut a, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [30, 15]}))["curves"]); + run(&mut a, "sketch.dimension", json!({"entities": [rect[0]], "value": "w"})); + run(&mut a, "sketch.dimension", json!({"entities": [rect[1]], "value": 10})); + let sa = a.active_sketch.unwrap(); + let corner = pos(sketch(&a, sa), &rect[0]); + run(&mut a, "sketch.copy", json!({"entities": rect})); + let clip = a.sketch_clipboard.clone().unwrap(); + + let mut b = Session::default(); + // Another design with its own `w`, and a sketch with the copied one's id. + run(&mut b, "parameters.change", json!({"name": "w", "expression": "3 mm"})); + run(&mut b, "sketch.create", json!({"plane": "XZ"})); + let sb = b.active_sketch.unwrap(); + assert_eq!(sb, sa, "same id: the copy must still not be offset as if pasted back into its own sketch"); + b.sketch_clipboard = Some(clip.for_another_design()); + let pasted = strs(&run(&mut b, "sketch.paste", json!({}))["curves"]); + assert_eq!(pasted.len(), 4); + let sk = sketch(&b, sb); + let at = pos(sk, &pasted[0]); + assert!(at.iter().zip(&corner).all(|(p, q)| p.dist(*q) < 1e-6), "{at:?} vs {corner:?}"); + let exprs: Vec = sk.constraints.iter().filter_map(|c| c.param.as_ref()).filter_map(|n| b.doc.param(n)).map(|p| p.expr.clone()).collect(); + assert_eq!(exprs.len(), 2, "{exprs:?}"); + assert!(exprs.iter().all(|e| solidcraft_doc::expr::references(e).is_empty()), "{exprs:?}"); + assert!(exprs.iter().any(|e| e == "10"), "{exprs:?}"); + let width = sk.constraints.iter().filter_map(|c| c.kind.value()).fold(0.0_f64, f64::max); + assert!((width - 25.4).abs() < 1e-6, "the width stays 1 in, not the other design's w: {width}"); + assert!(b.doc.params.iter().filter(|p| p.name == "w").all(|p| p.expr == "3 mm"), "its own w is untouched"); + // Each paste without a position lands at the copied coordinates. + let again = strs(&run(&mut b, "sketch.paste", json!({}))["curves"]); + let at = pos(sketch(&b, sb), &again[0]); + assert!(at.iter().zip(&corner).all(|(p, q)| p.dist(*q) < 1e-6), "{at:?}"); +} diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rs index 2fad3462a..f64e45d51 100644 --- a/crates/engine/src/cmd/sketch_constraints.rs +++ b/crates/engine/src/cmd/sketch_constraints.rs @@ -2,7 +2,8 @@ //! inference for interactive tools. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch}; use super::sketch::{add_c, constraint_result, dof_now, edit, listed, redundancy, residual_of}; diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs index 1c21d29e7..a60e08d68 100644 --- a/crates/engine/src/cmd/sketch_constraints_tests.rs +++ b/crates/engine/src/cmd/sketch_constraints_tests.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::ConstraintKind; use crate::Session; @@ -25,6 +26,59 @@ fn sketch(s: &Session) -> solidcraft_sketch::Sketch { s.model.state().sketch(s.active_sketch.unwrap()).unwrap().sketch.clone() } +#[test] +fn concentric_centres_a_circle_or_arc_on_a_point_in_either_order() { + for arc in [false, true] { + for origin in [false, true] { + for reverse in [false, true] { + let mut s = new_sketch(); + let made = if arc { + run(&mut s, "sketch.arc.center_point", json!({"center": [20, 10], "start": [25, 10], "end": [20, 15]})) + } else { + run(&mut s, "sketch.circle.center", json!({"center": [20, 10], "radius": 5})) + }; + let curve = ids(&made["curves"])[0].clone(); + let (point, expected) = if origin { + ("origin", Vec2::new(0.0, 0.0)) + } else { + run(&mut s, "sketch.point", json!({"point": [-7, 4], "id": "target"})); + run(&mut s, "sketch.constraint.fix", json!({"entity": "target"})); + ("target", Vec2::new(-7.0, 4.0)) + }; + let before = s.doc.to_json(); + let undo = s.undo.len(); + let params = if reverse { json!({"a": point, "b": curve}) } else { json!({"a": curve, "b": point}) }; + let result = run(&mut s, "sketch.constraint.concentric", params); + let sk = sketch(&s); + let index = sk.curve_index(&curve).unwrap(); + assert!(sk.center(index).unwrap().dist(expected) < 1e-6, "arc={arc}, origin={origin}, reverse={reverse}"); + assert!((sk.radius(index).unwrap() - 5.0).abs() < 1e-6); + assert!(matches!( + sk.constraints.iter().find(|c| c.id == result["constraint"].as_str().unwrap()).unwrap().kind, + ConstraintKind::Coincident { .. } + )); + assert_eq!(s.undo.len(), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + } + } + } +} + +#[test] +fn concentric_rejects_invalid_point_pairs_without_changing_the_sketch() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center": [20, 10], "radius": 5, "id": "circle"})); + run(&mut s, "sketch.line", json!({"points": [[10, 10], [20, 20]], "ids": ["line"]})); + let before = s.doc.to_json(); + let undo = s.undo.len(); + for (a, b) in [("line", "origin"), ("origin", "line"), ("origin", "circle.center"), ("circle", "circle.center"), ("circle", "missing")] { + assert!(s.execute("sketch.constraint.concentric", &json!({"a": a, "b": b})).is_err(), "{a}, {b}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + } +} + #[test] fn redundant_dimensions_are_refused_driven_ones_measure() { let mut s = new_sketch(); @@ -129,7 +183,7 @@ fn curvature_polygon_arc_length_linear_diameter() { let sk = sketch(&s); let ai = sk.curve_index(&a).unwrap(); let len = match sk.segs(ai)[0] { - solidcraft_geom::Seg2::Arc { radius, sweep, .. } => radius * sweep, + solidcore_record::Seg2::Arc { radius, sweep, .. } => radius * sweep, _ => 0.0, }; assert!((len - 20.0).abs() < 1e-6, "{len}"); @@ -455,6 +509,27 @@ fn drawing_at_a_curve_crossing_keeps_the_point_on_both() { assert!(st.y > 0.0, "the upper crossing: {st:?}"); } +#[test] +fn drawing_at_an_infinite_line_crossing_keeps_the_point_on_both() { + let mut s = new_sketch(); + let a = ids(&run(&mut s, "sketch.construction_line.vertical", json!({"at": [20, 40]}))["curves"])[0].clone(); + let b = ids(&run(&mut s, "sketch.construction_line.horizontal", json!({"at": [40, 15]}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.line", json!({"points": [format!("x:{a}+{b}:20.4,15.4"), [30, 25]], "infer": false, "connect": false})); + let line = ids(&r["curves"])[0].clone(); + let sk = sketch(&s); + let start = sk.resolve_point(&format!("{line}.start")).unwrap(); + assert!(sk.point(start).unwrap().dist(Vec2::new(20.0, 15.0)) < 1e-9); + for name in [a, b] { + let curve = sk.curve_index(&name).unwrap(); + assert!(sk.constraints.iter().any(|k| matches!(k.kind, crate::sketch::ConstraintKind::PointOnCurve { p, c } if p == start && c == curve))); + } + let before_undo = s.doc.to_json(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s).curves.len(), 2); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.to_json(), before_undo); +} + #[test] fn drawing_at_a_curve_crossing_refuses_hostile_arguments() { let mut s = new_sketch(); @@ -782,6 +857,61 @@ fn midpoint_alignment_rejects_invalid_or_conflicting_references_atomically() { } } +/// #10311: Coincident takes a line's middle as `{midpoint: line}`, first or second. With another +/// line the middle lies on it, with a point it lands on the point; a point tied to the middle by +/// a Midpoint constraint stands for it, in one undo step. +#[test] +fn coincident_takes_a_line_midpoint_either_way_round() { + for other in ["l2", "target"] { + for reverse in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})); + run(&mut s, "sketch.line", json!({"points":[[0,40],[60,40]],"infer":false,"connect":false})); + run(&mut s, "sketch.point", json!({"point":[24,50],"id":"target"})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["l2","target"]})); + let before = s.doc.to_json(); + let undo = s.undo.len(); + let middle = json!({"midpoint":"l1"}); + let (a, b) = if reverse { (json!(other), middle) } else { (middle, json!(other)) }; + let result = run(&mut s, "sketch.constraint.coincident", json!({"a":a,"b":b})); + assert_eq!(result["created"]["points"].as_array().unwrap().len(), 1, "{other} {reverse}: {result}"); + assert_eq!(s.undo.len(), undo + 1); + let sk = sketch(&s); + let mid = line_midpoint(&sk, "l1"); + if other == "l2" { + assert!((mid.y - 40.0).abs() < 1e-6, "{other} {reverse}: middle at {mid:?}"); + } else { + assert!(mid.dist(Vec2::new(24.0, 50.0)) < 1e-6, "{other} {reverse}: middle at {mid:?}"); + } + assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. }))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + } + } +} + +/// A middle Coincident can't take (not a line, an unknown curve, the same middle twice, or the +/// point already tied there) is refused and leaves the sketch as it was. +#[test] +fn coincident_refuses_a_midpoint_it_cannot_take_atomically() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})); + run(&mut s, "sketch.circle.center", json!({"center":[40,50],"radius":3})); + let tied = run(&mut s, "sketch.point", json!({"point":"mid:l1"}))["point"].as_str().unwrap().to_owned(); + for (a, b) in [ + (json!({"midpoint":"c1"}), json!("origin")), + (json!({"midpoint":"missing"}), json!("origin")), + (json!({"midpoint":"l1"}), json!({"midpoint":"l1"})), + (json!({"midpoint":"l1"}), json!(tied)), + ] { + let before = s.doc.to_json(); + let undo = s.undo.len(); + assert!(s.execute("sketch.constraint.coincident", &json!({"a":a,"b":b})).is_err(), "{a} {b}"); + assert_eq!(s.doc.to_json(), before, "{a} {b}"); + assert_eq!(s.undo.len(), undo); + } +} + fn line_midpoint(sk: &solidcraft_sketch::Sketch, id: &str) -> Vec2 { // Read the curve's current endpoints: after a corner cut an original endpoint // id can still name the retained construction side's corner. @@ -1578,7 +1708,7 @@ fn an_arc_and_its_end_point_dimension_the_arc_length() { let arc_length = |s: &Session, a: &str| { let sk = sketch(s); match sk.segs(sk.curve_index(a).unwrap())[0] { - solidcraft_geom::Seg2::Arc { radius, sweep, .. } => radius * sweep.abs(), + solidcore_record::Seg2::Arc { radius, sweep, .. } => radius * sweep.abs(), _ => f64::NAN, } }; @@ -1641,3 +1771,52 @@ fn inward_bulging_arc_pairs_keep_the_gap_dimension() { sk.constraints.iter().map(|c| &c.kind).collect::>() ); } + +/// #9735: the over-constrain conflict list named the refused dimension's own id — the trial +/// sketch already holds the new constraint under the id it would get, and the next constraint +/// added takes that id. The list names only constraints the sketch already has. +#[test] +fn over_constrain_message_leaves_out_the_refused_dimensions_own_id() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 50})); + // The sketch holds k1..k6: the refused dimension would take k7, which is not yet one of them. + let e = s.execute("sketch.dimension", &json!({"entities": ["l3"], "value": 30})).unwrap_err().to_string(); + assert!(e.contains("would over-constrain the sketch (conflicts with"), "{e}"); + assert!(e.contains("k3") && e.contains("k4") && e.contains("k6"), "{e}"); + assert!(!e.contains("k7"), "{e}: the refused dimension's own id must not be listed"); + // The next constraint takes k7: the id the message must not have burned. + run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": 25})); + assert_eq!(sketch(&s).constraints.last().unwrap().id, "k7"); +} + +/// #9735: "neither entity can move … (they are fixed or fully constrained)" fired for sketches +/// with free degrees of freedom. The refusal now lists the constraints the new one conflicts +/// with by id, as the over-constrain message does. +#[test] +fn conflict_lists_the_constraints_instead_of_claiming_the_entities_are_fixed() { + // A rectangle from (10,10): 4 degrees of freedom, nothing fixed; its bottom side cannot be + // made parallel to its right side — the conflict is with the rectangle's own constraints. + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 10], "p1": [50, 30]})); + let before = serde_json::to_value(sketch(&s)).unwrap(); + let e = s.execute("sketch.constraint.parallel", &json!({"a": "l1", "b": "l2"})).unwrap_err().to_string(); + assert!(!e.contains("fixed or fully constrained"), "{e}"); + // The horizontal on l1 (k1) and the vertical on l2 (k3) are what the parallel conflicts with. + assert!(e.contains("conflicts with k1, k3"), "{e}"); + assert!(!e.contains("k5"), "{e}: the refused constraint's own id must not be listed"); + assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before, "the sketch does not change"); + // A rectangle drawn from the origin (2 degrees of freedom): the same refusals name the + // constraints they conflict with, not fixed entities. + for (cmd, params) in [ + ("sketch.constraint.parallel", json!({"a": "l1", "b": "l2"})), + ("sketch.constraint.coincident", json!({"a": "p1", "b": "p3"})), + ("sketch.constraint.perpendicular", json!({"a": "l1", "b": "l3"})), + ] { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]})); + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(!e.contains("fixed or fully constrained"), "{cmd} {params}: {e}"); + assert!(e.contains("conflicts with"), "{cmd} {params}: {e}"); + } +} diff --git a/crates/engine/src/cmd/sketch_construction.rs b/crates/engine/src/cmd/sketch_construction.rs index bac231724..1a86b15bd 100644 --- a/crates/engine/src/cmd/sketch_construction.rs +++ b/crates/engine/src/cmd/sketch_construction.rs @@ -1,10 +1,12 @@ -//! Fast infinite reference lines. Preview and creation use the same analytic solutions. +//! Fast reference lines, infinite or with a length (#10258). Preview and creation use the same +//! analytic solutions. use serde_json::{Value, json}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch}; -use super::sketch::{add_c, curve_ref, edit, ids_of, line_or_axis_ref, line_pts, req_parg, result}; +use super::sketch::{CONNECT_TOL, add_c, curve_ref, edit, ids_of, line_or_axis_ref, line_pts, req_parg, result}; use super::{CommandSpec, in_sketch}; use crate::params::{bad, expr, num, str_, vec2}; use crate::schema::sketch_create::{ConstructionLineParams, ConstructionLineResult}; @@ -23,7 +25,7 @@ macro_rules! variant { .enabled(in_sketch) .contract(&CONTRACT) .output(output_schema_for::) - .params(concat!("Infinite construction line, ", $mode, ". at: point; through?: second point; curve?, curve2?: sketch references; angle?: degrees from sketch X; near?: solution selector; solution?: zero-based solution index. Tangents take circles/arcs, or an open spline/conic endpoint for tangent_at.", created_doc!())) + .params(concat!("Construction line, ", $mode, ". at: point; through?: second point; curve?, curve2?: sketch references; angle?: degrees from sketch X; near?: solution selector, and the side a line with a length runs towards; solution?: zero-based solution index; length?: a segment of this length from `at`, held by a length dimension, instead of an infinite line (horizontal, vertical, angle, parallel, perpendicular); construction?: false makes that segment a normal line. Tangents take circles/arcs, or an open spline/conic endpoint for tangent_at.", created_doc!())) }; } @@ -54,6 +56,19 @@ impl ConstructionLine { } } +/// The methods that take a `length`: the ones whose line starts at `at` with a known direction. +pub fn construction_line_takes_length(mode: &str) -> bool { + matches!(mode, "horizontal" | "vertical" | "angle" | "parallel" | "perpendicular") +} + +/// The two ends of a construction line cut to `length` from its start: along its direction, or +/// the other way when `near` lies behind the start. The preview draws exactly what is created. +pub fn construction_segment(line: ConstructionLine, length: f64, near: Option) -> (Vec2, Vec2) { + let behind = near.is_some_and(|q| (q - line.start).dot(line.direction) < 0.0); + let direction = if behind { -line.direction } else { line.direction }; + (line.start, line.start + direction * length) +} + /// The method belonging to an interactive command. The generic command defaults to two points. pub fn construction_line_mode(id: &str) -> Option<&str> { if id == CMD { Some("free") } else { id.strip_prefix("sketch.construction_line.") } @@ -246,6 +261,10 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result { let first_new = sk.points.len(); let at = req_parg(sk, doc, &p, "at", CMD)?; let through = if mode == "free" { Some(req_parg(sk, doc, &p, "through", CMD)?) } else { None }; + // A through-point next to the start leaves a line whose direction no constraint holds (#11001). + if through.as_ref().is_some_and(|q| q.pos().dist(at.pos()) < CONNECT_TOL) { + return Err(bad(CMD, "the through point must lie away from the start point")); + } let mut params = p.clone(); params["at"] = json!([at.pos().x, at.pos().y]); let angle_expression = if mode == "angle" { @@ -277,6 +296,29 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result { } else { None }; + let length = match p.get("length") { + None | Some(Value::Null) => None, + Some(_) if !construction_line_takes_length(mode) => { + return Err(bad(CMD, "`length` is for the horizontal, vertical, angle, parallel and perpendicular methods")); + } + Some(_) => { + let e = expr(&p, "length").ok_or_else(|| bad(CMD, "`length` must be a length or expression"))?; + let e = doc.with_design_unit(e.as_str(), solidcraft_doc::expr::Kind::Length); + let value = doc.eval(&e, solidcraft_doc::expr::Kind::Length).map_err(|e| bad(CMD, format!("length: {e}")))?; + if !(value > 1e-9 && value < 1e8) { + return Err(bad(CMD, "length must be positive")); + } + Some((e, value)) + } + }; + let construction = match p.get("construction") { + None | Some(Value::Null) => true, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad(CMD, "`construction` must be a boolean")), + }; + if !construction && length.is_none() { + return Err(bad(CMD, "only a line with a `length` can be a normal line: an infinite line is construction geometry")); + } let solutions = construction_line_solutions(sk, ¶ms, mode)?; let choice = construction_line_choice(&solutions, ¶ms)?; let chosen = solutions.get(choice).ok_or_else(|| bad(CMD, "no solution"))?; @@ -294,11 +336,15 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result { } else { at.idx() }; - let end = through.as_ref().map_or(chosen.start + chosen.direction * 10.0, |q| q.pos()); - let l = sk.add_line(chosen.start, end, start_ref, through.as_ref().and_then(|q| q.idx()), None)?; + let near = p.get("near").and_then(vec2); + let (start, end) = match &length { + Some((_, value)) => construction_segment(*chosen, *value, near), + None => (chosen.start, through.as_ref().map_or(chosen.start + chosen.direction * 10.0, |q| q.pos())), + }; + let l = sk.add_line(start, end, start_ref, through.as_ref().and_then(|q| q.idx()), None)?; if let Some(c) = sk.curves.get_mut(l) { - c.infinite = true; - c.construction = true; + c.infinite = length.is_none(); + c.construction = construction; } let mut cons = Vec::new(); let kind = match (mode, reference) { @@ -314,6 +360,11 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result { let parameter = angle_expression.map(|e| doc.new_model_param(&e, "deg")); cons.push(sk.add_constraint(k, parameter)?); } + if let Some((e, value)) = &length { + let unit = solidcraft_doc::expr::length_unit_or_mm(&doc.units).to_string(); + let parameter = doc.new_model_param(e, &unit); + cons.push(sk.add_constraint(ConstraintKind::Length { l, value: *value }, Some(parameter))?); + } if let ("tangent_two", Some(b)) = (mode, second) { cons.push(add_c(sk, ConstraintKind::Tangent { a: l, b })?); } diff --git a/crates/engine/src/cmd/sketch_corner_tests.rs b/crates/engine/src/cmd/sketch_corner_tests.rs index f49402bd5..b2e86e8a1 100644 --- a/crates/engine/src/cmd/sketch_corner_tests.rs +++ b/crates/engine/src/cmd/sketch_corner_tests.rs @@ -3,6 +3,7 @@ //! corner (a clear error that leaves the sketch as it was). use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -98,6 +99,59 @@ fn fillet_and_chamfer_corners() { assert!((area(&s) - (a0 - 8.0)).abs() < 1e-6, "{}", area(&s)); } +/// Each chamfer cuts several corners at once (`points`), as a fillet rounds them: every corner +/// alike, in one edit, and a corner that can't be cut, or is named twice, refuses them all. +#[test] +fn chamfers_cut_several_corners() { + let corners = json!(["l1.start", "l1.end", "l2.end", "l3.end"]); + for (cmd, sizes, cut) in [ + ("sketch.chamfer.equal_distance", json!({"distance": 4}), 8.0), + ("sketch.chamfer.two_distance", json!({"distance": 2, "distance2": 6}), 6.0), + ("sketch.chamfer.distance_angle", json!({"distance": 3, "angle": 45}), 4.5), + ] { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let mut p = sizes.clone(); + p["points"] = corners.clone(); + let out = run(&mut s, cmd, p); + assert_eq!(curves(&out).len(), 4, "{cmd}: {out}"); + assert_eq!(sk(&s).curves.len(), 8, "{cmd}"); + assert!(solved(&s), "{cmd}"); + assert!((area(&s) - (1200.0 - 4.0 * cut)).abs() < 1e-6, "{cmd}: {}", area(&s)); + } + // A corner named by its two lines, beside one named by its point. + let mut s = new_sketch(); + let c = curves(&run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}))); + run(&mut s, "sketch.chamfer.equal_distance", json!({"points": [{"a": c[0], "b": c[1]}, "l3.end"], "distance": 4})); + assert!((area(&s) - (1200.0 - 2.0 * 8.0)).abs() < 1e-6, "{}", area(&s)); + // Two lines that share no end are brought to where they meet, beside a corner they already + // make; named again by its point once they meet, that corner is listed twice. + let mut s = new_sketch(); + let la = curves(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "connect": false})))[0].clone(); + let lb = curves(&run(&mut s, "sketch.line", json!({"points": [[20, 5], [20, 20]], "connect": false})))[0].clone(); + run(&mut s, "sketch.line", json!({"points": [format!("{lb}.end"), [0, 20]]})); + let e = s.execute("sketch.chamfer.equal_distance", &json!({"points": [{"a": la, "b": lb}, format!("{la}.end")], "distance": 4})); + assert!(e.unwrap_err().to_string().contains("listed twice")); + assert_eq!(sk(&s).curves.len(), 3); + let out = run(&mut s, "sketch.chamfer.equal_distance", json!({"points": [{"a": la, "b": lb}, format!("{lb}.end")], "distance": 4})); + assert_eq!(curves(&out).len(), 2, "{out}"); + assert!(solved(&s)); + let refused = [ + // 20 mm back from both ends of a 30 mm side: the second corner doesn't fit. + json!({"points": corners, "distance": 20}), + // One corner by both of its lines' ends: cut once, the second name would be a new corner. + json!({"points": ["l1.end", "l2.start"], "distance": 4}), + json!({"points": [], "distance": 1}), + ]; + for p in refused { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + assert!(s.execute("sketch.chamfer.equal_distance", &p).is_err(), "{p}"); + assert_eq!(sk(&s).curves.len(), 4, "{p}"); + assert!((area(&s) - 1200.0).abs() < 1e-6, "{p}"); + } +} + /// A chamfer where the two lines have no corner is refused, as a fillet there is: two lines /// lying on each other made a chamfer line of no length between their cut-back ends (found by a /// local trim fuzzer), and two lines in line with each other have no corner either. @@ -246,9 +300,9 @@ fn a_fillet_keeps_the_dimensions_of_its_corner_on_a_virtual_sharp() { // The virtual corner sits where the corner was, and the part keeps its size. let k = sk(&s); let vc = k.point(k.point_index(&corner).unwrap()).unwrap(); - assert!(vc.dist(solidcraft_geom::Vec2::new(0.0, 100.0)) < 1e-6, "{vc:?}"); + assert!(vc.dist(solidcore_record::Vec2::new(0.0, 100.0)) < 1e-6, "{vc:?}"); let top_end = k.point(k.resolve_point("top.end").unwrap()).unwrap(); - assert!(top_end.dist(solidcraft_geom::Vec2::new(-80.0, 100.0)) < 1e-6, "{top_end:?}"); + assert!(top_end.dist(solidcore_record::Vec2::new(-80.0, 100.0)) < 1e-6, "{top_end:?}"); let (lo, hi) = k.bounds().unwrap(); assert!((hi.x - lo.x - 80.0).abs() < 1e-6 && (hi.y - lo.y - 100.0).abs() < 1e-6, "{lo:?} {hi:?}"); // It is drawn with extension lines from both lines' ends to it. @@ -297,3 +351,63 @@ fn a_fillet_of_a_nearly_straight_or_folded_corner_with_dimensions_does_not_panic assert!(sk(&s).points.iter().all(|p| p.pos.is_finite())); } } + +/// Two lines that share no end are brought to where they meet before the corner is rounded or +/// cut (#6912, #7759, #7985). A line that stops short is extended, and one that runs past the +/// other is cut there, losing its shorter piece; the far ends stay. Parallel lines, an end held +/// by other geometry and a dimensioned length are refused, and change nothing. +#[test] +fn a_fillet_or_chamfer_brings_two_separate_lines_to_where_they_meet() { + use solidcore_record::Vec2; + use solidcraft_sketch::CurveKind; + let lines = |s: &mut Session, a: [[f64; 2]; 2], b: [[f64; 2]; 2]| { + let la = curves(&run(s, "sketch.line", json!({"points": a, "connect": false})))[0].clone(); + let lb = curves(&run(s, "sketch.line", json!({"points": b, "connect": false})))[0].clone(); + (la, lb) + }; + let ends = |s: &Session, id: &str| { + let k = sk(s); + let CurveKind::Line { a, b } = k.curves[k.curve_index(id).unwrap()].kind else { panic!("{id} is a line") }; + (k.point(a).unwrap(), k.point(b).unwrap()) + }; + let near = |q: Vec2, x: f64, y: f64| q.dist(Vec2::new(x, y)) < 1e-6; + // Stopping short of each other (a gap), and crossing with a short piece past the corner. + for (a, b) in [([[0.0, 0.0], [10.0, 0.0]], [[20.0, 5.0], [20.0, 20.0]]), ([[0.0, 0.0], [24.0, 0.0]], [[20.0, -4.0], [20.0, 20.0]])] { + let mut s = new_sketch(); + let (la, lb) = lines(&mut s, a, b); + let r = run(&mut s, "sketch.fillet", json!({"a": la, "b": lb, "radius": 3})); + assert!(solved(&s), "{r}"); + let k = sk(&s); + let arc = k.curve_index(&curves(&r)[0]).unwrap(); + let CurveKind::Arc { c, .. } = k.curves[arc].kind else { panic!("an arc") }; + assert!(near(k.point(c).unwrap(), 17.0, 3.0), "{:?}", k.point(c)); + let ((a0, a1), (b0, b1)) = (ends(&s, &la), ends(&s, &lb)); + assert!(near(a0, 0.0, 0.0) && near(a1, 17.0, 0.0), "{la}: {a0:?} {a1:?}"); + assert!(near(b0, 20.0, 3.0) && near(b1, 20.0, 20.0), "{lb}: {b0:?} {b1:?}"); + assert_eq!(k.curves.len(), 3, "the two lines and the arc, nothing left past the corner"); + assert!(k.points.iter().all(|q| !near(q.pos, 24.0, 0.0) && !near(q.pos, 20.0, -4.0) && !near(q.pos, 20.0, 0.0)), "{:?}", k.points); + } + // A chamfer the same way. + let mut s = new_sketch(); + let (la, lb) = lines(&mut s, [[0.0, 0.0], [10.0, 0.0]], [[20.0, 5.0], [20.0, 20.0]]); + run(&mut s, "sketch.chamfer.equal_distance", json!({"a": la, "b": lb, "distance": 4})); + assert!(solved(&s)); + let ((_, a1), (b0, _)) = (ends(&s, &la), ends(&s, &lb)); + assert!(near(a1, 16.0, 0.0) && near(b0, 20.0, 4.0), "{a1:?} {b0:?}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sk(&s).curves.len(), 2, "undo brings back the two separate lines"); + + // Refused: parallel lines, an end joined to a third line, a dimensioned length. + let mut s = new_sketch(); + let (pa, pb) = lines(&mut s, [[0.0, 0.0], [10.0, 0.0]], [[0.0, 5.0], [10.0, 5.0]]); + let (la, lb) = lines(&mut s, [[0.0, 20.0], [10.0, 20.0]], [[20.0, 25.0], [20.0, 40.0]]); + run(&mut s, "sketch.line", json!({"points": [format!("{la}.end"), [10, 30]], "connect": false})); + let (da, db) = lines(&mut s, [[0.0, 50.0], [10.0, 50.0]], [[20.0, 55.0], [20.0, 70.0]]); + run(&mut s, "sketch.dimension", json!({"entities": [da], "value": 10})); + let before = sk(&s); + for (a, b, why) in [(&pa, &pb, "parallel"), (&la, &lb, "held by other geometry"), (&da, &db, "length is held")] { + let e = s.execute("sketch.fillet", &json!({"a": a, "b": b, "radius": 2})).unwrap_err().to_string(); + assert!(e.contains(why), "{a}, {b}: {e}"); + } + assert_eq!(sk(&s), before, "refusals change nothing"); +} diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index 38d8e5387..d231b6c12 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -2,7 +2,8 @@ //! arc slots. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Shape, Sketch, TextAlign, TextExprs, TextStyle}; /// The style parameters of `sketch.text` and `sketch.edit_text`. @@ -16,7 +17,7 @@ use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_pa use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, num, req_vec2, str_, string_list}; -use crate::schema::sketch_create::{SplineReverseParams, SplineReverseResult}; +use crate::schema::sketch_create::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -29,6 +30,7 @@ mod text_move_tests; mod text_expr_tests; const SPLINE_REVERSE_CONTRACT: TypedContract = TypedContract::new(); +const SPLINE_REMOVE_POINT_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line) @@ -37,7 +39,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .enabled(in_sketch) .params(concat!("mid: [x,y], point ref or snap (\"mid:\", \"on::x,y\", model vertex/edge); end: [x,y]; construction?", created_doc!())), CommandSpec::new("sketch.arc.tangent", "Tangent Arc", arc_tangent).at("SKETCH", "CREATE").icon("arc_tangent").enabled(in_sketch).params(concat!( - "start: end point of a line or arc (\"l1.end\"), end: [x,y]; curve?: the curve to be tangent to (default: the one ending at start)", + "start: end point of a line or arc (\"l1.end\"), end: [x,y] or an existing point's id (\"l2.start\": the arc ends on that point); curve?: the curve to be tangent to (default: the one ending at start)", created_doc!() )), CommandSpec::new("sketch.circle.two_tangent", "2-Tangent Circle", circle_tan_tan) @@ -88,6 +90,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("spline") .enabled(in_sketch) .params("curve: fit point spline id, at: [x,y]: a fit point is inserted where the curve passes nearest to it, between its neighbours (the curve still runs through it and all its old points; constraints on them stay); end?: start|end: `at` becomes the spline's new first or last point instead, and the curve runs on to it (refused when that end is joined to other geometry). Control point splines take no new points yet. Returns point: the new point's id"), + CommandSpec::new("sketch.spline.remove_point", "Remove Spline Point", crate::checked!("sketch.spline.remove_point", spline_remove_point)) + .icon("spline") + .enabled(in_sketch) + .contract(&SPLINE_REMOVE_POINT_CONTRACT) + .output(output_schema_for::) + .params("curve: spline id, point: one of its points (a point id, or the curve's start or end such as s1.end): the spline runs through (or over) its other points only, and the point goes with the constraints on it unless another curve uses it. Fit point, control point and closed splines. Refused for a closed spline's closing point, for an end joined to other geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed spline), and for a projected, offset or patterned spline. Returns curve, point: the point's id, deleted: whether the point went too"), CommandSpec::new("sketch.spline.reverse", "Reverse Spline Direction", crate::checked!("sketch.spline.reverse", spline_reverse)) .icon("spline") .enabled(in_sketch) @@ -116,7 +124,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .enabled(in_sketch) .params("curves: [line ids], value?: bool (default toggles): infinite line type (#1359): construction geometry drawn across the whole view through the line's two points; off, a normal line"), CommandSpec::new("sketch.text", "Text", text).at("SKETCH", "CREATE").icon("sketch_text").enabled(in_sketch).params(concat!( - "text: string (\\n breaks lines), or text_expression: the words built from text parameters (parameters.add with unit text) and quoted texts joined by + (\"Label + '-L'\"): the text keeps it, its words follow the parameters (a parameter edit or a configuration row relabels it) and `exprs` returns it as `text`; at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg; at's x and y, height and angle each take a number or an expression over the design's parameters as a string (\"plate_width / 2\", \"label_size\"): the text keeps the expression, follows the parameters, and returns it in `exprs`; an expression naming no parameter is the number it comes to, a bare number in one is in the design's units, \ + "text: string (\\n breaks lines), or text_expression: the words built from text parameters (parameters.add with unit text), number parameters and quoted texts joined by + (\"Label + '-L'\", \"'W' + Width\"; a number parameter shows its value in the design's units, \"85 mm\", an angle in degrees, \"30°\"; number(Width) is the number alone and number(Width, 2) has 2 decimals): the text keeps it, its words follow the parameters (a parameter edit or a configuration row relabels it) and `exprs` returns it as `text`; at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg; at's x and y, height and angle each take a number or an expression over the design's parameters as a string (\"plate_width / 2\", \"label_size\"): the text keeps the expression, follows the parameters, and returns it in `exprs`; an expression naming no parameter is the number it comes to, a bare number in one is in the design's units, \ font?: an installed font's family or full name, or a .ttf/.otf file path (~ and %VAR% expand; default: the built-in Liberation Sans), ", text_style_doc!(), created_doc!() @@ -222,7 +230,7 @@ fn text_source(doc: &solidcraft_doc::Document, p: &Value, cmd: &str, old: Option t.clone() } (None, Some(Value::String(e))) => { - let words = doc.eval_words(e.trim()).map_err(|error| bad(cmd, format!("`text_expression`: {error}")))?; + let words = doc.eval_words(e.trim(), &doc.param_values().0).map_err(|error| bad(cmd, format!("`text_expression`: {error}")))?; exprs.text = Some(e.trim().to_string()); words } @@ -451,14 +459,8 @@ fn end_of(sk: &Sketch, pi: usize) -> Option<(usize, Vec2)> { fn blend_order(p: &Value, cmd: &str) -> Result { match p.get("continuity") { None | Some(Value::Null) => Ok(1), - Some(Value::String(v)) => match v.trim().to_ascii_lowercase().as_str() { - "" | "g1" => Ok(1), - "g2" => Ok(2), - "g3" => Ok(3), - "g4" => Ok(4), - _ => Err(bad(cmd, "`continuity` must be g1, g2, g3 or g4")), - }, - Some(_) => Err(bad(cmd, "`continuity` must be g1, g2, g3 or g4")), + Some(Value::String(v)) if v.trim().is_empty() => Ok(1), + given => Ok(crate::params::continuity(cmd, given, "`continuity`", solidcraft_kernel::Construction::BlendCurve)?.order()), } } @@ -522,7 +524,7 @@ fn blend(s: &mut Session, p: &Value) -> Result { let (sp, cons) = if order <= 1 { let c1 = sk.add_point(qa + ta * (l / 3.0), None)?; let c2 = sk.add_point(qb + tb * (l / 3.0), None)?; - let sp = sk.add_curve(CurveKind::Spline { pts: vec![pa, c1, c2, pb], control: true, degree: 3, periodic: false }, None)?; + let sp = sk.add_curve(CurveKind::Spline { pts: vec![pa, c1, c2, pb], control: true, degree: 3, periodic: false, nurbs: None }, None)?; let cons = vec![add_c(sk, ConstraintKind::Tangent { a: ca, b: sp })?, add_c(sk, ConstraintKind::Tangent { a: cb, b: sp })?]; (sp, cons) } else { @@ -544,7 +546,7 @@ fn blend(s: &mut Session, p: &Value) -> Result { }); } let degree = u8::try_from(cps.len().saturating_sub(1)).map_err(|_| bad(cmd, "the blend curve needs too many control points"))?; - let sp = sk.add_curve(CurveKind::Spline { pts, control: true, degree, periodic: false }, None)?; + let sp = sk.add_curve(CurveKind::Spline { pts, control: true, degree, periodic: false, nurbs: None }, None)?; (sp, Vec::new()) }; solve_new_only(sk, first_new); @@ -672,7 +674,7 @@ fn spline(s: &mut Session, p: &Value, cmd: &str, control: bool, degree: u8) -> R { pts.push(*pts.first().ok_or_else(|| bad(cmd, "missing first point"))?); } - let c = sk.add_curve(CurveKind::Spline { pts, control, degree, periodic }, None)?; + let c = sk.add_curve(CurveKind::Spline { pts, control, degree, periodic, nurbs: None }, None)?; mark_construction(sk, &[c], p); Ok((ids_of(sk, &[c]), Vec::new())) })?; @@ -711,6 +713,22 @@ fn spline_insert_point(s: &mut Session, p: &Value) -> Result { Ok(json!({"point": point, "curve": p.get("curve"), "sketch": info})) } +/// One point taken out of a spline (#10783). +fn spline_remove_point(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.spline.remove_point"; + let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); + let point = str_(p, "point").ok_or_else(|| bad(cmd, "`point` must be one of the spline's points"))?.to_string(); + let ((point, deleted), info) = edit(s, p, cmd, false, |sk, _| { + let c = sk.curve_index(&id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; + let at = sk.resolve_point(&point).ok_or_else(|| bad(cmd, format!("unknown sketch point `{point}`")))?; + let name = sk.points.get(at).map_or(point.clone(), |q| q.id.clone()); + let deleted = sk.remove_spline_point(c, at).map_err(|e| bad(cmd, e.to_string()))?; + Ok((name, deleted)) + })?; + let reply = SplineRemovePointResult { curve: id, point, deleted, sketch: info, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + fn spline_reverse(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.spline.reverse"; let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); @@ -819,18 +837,82 @@ pub(super) fn leaving_dir(sk: &Sketch, ci: usize, pi: usize) -> Option { } } +/// The centre of the arc that leaves `start` in direction `dir` and ends at `end`, and whether it +/// runs counter-clockwise. `None` straight ahead (or back), where no arc does. +fn tangent_arc_centre(dir: Vec2, start: Vec2, end: Vec2) -> Option<(Vec2, bool)> { + let n = dir.perp(); + let d = end - start; + let den = 2.0 * n.dot(d); + if den.abs() < 1e-9 * d.len().max(1e-9) || d.len() < 1e-9 { + return None; + } + Some((start + n * (d.len2() / den), den > 0.0)) +} + +/// The arc `sketch.arc.tangent` would draw from point `start` on `curve` to `end`, alone in a +/// sketch of its own for a preview. `None` where the command would refuse. +pub fn tangent_arc_preview(sk: &Sketch, curve: &str, start: &str, end: Vec2) -> Option { + let pi = sk.resolve_point(start)?; + let s0 = sk.point(pi)?; + let (center, ccw) = tangent_arc_centre(leaving_dir(sk, sk.curve_index(curve)?, pi)?, s0, end)?; + if !center.is_finite() { + return None; + } + let mut out = Sketch::new(); + if ccw { + out.add_arc(center, s0, end, [None; 3], None).ok()?; + } else { + out.add_arc(center, end, s0, [None; 3], None).ok()?; + out.curves.first_mut()?.reversed = true; + } + Some(out) +} + +/// The picked point, then any other point at the same place: a trimmed arc's end is its own +/// point, lying on the end of the curve that trimmed it, which is the one a click picks (#1485). +fn tangent_start_candidates(sk: &Sketch, picked: usize) -> Vec { + let at = sk.point(picked).unwrap_or_default(); + let tol = 1e-6 * at.len().max(1.0); + std::iter::once(picked).chain((0..sk.points.len()).filter(|&q| q != picked && sk.point(q).is_some_and(|x| x.dist(at) <= tol))).collect() +} + +/// The first drawn curve (and which of the candidate points) a tangent arc can leave from. +fn tangent_start_curve(sk: &Sketch, candidates: &[usize]) -> Option<(usize, usize)> { + candidates + .iter() + .find_map(|&q| sk.curves.iter().enumerate().find(|(i, c)| !c.construction && leaving_dir(sk, *i, q).is_some()).map(|(i, _)| (i, q))) +} + +/// Whether `sketch.arc.tangent` can start at sketch point `start` (an id such as `l1.end`): the +/// end of a drawn line, arc or spline there. A tool asks before taking the click (#10653). +pub fn tangent_arc_starts_at(sk: &Sketch, start: &str) -> bool { + sk.resolve_point(start).is_some_and(|picked| tangent_start_curve(sk, &tangent_start_candidates(sk, picked)).is_some()) +} + fn arc_tangent(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.tangent"; - let end = req_vec2(cmd, p, "end")?; + // An id ends the arc on that point, so a chain can close; coordinates make a new point. + let end_ref = p.get("end").and_then(Value::as_str); + let at = if end_ref.is_some() { None } else { Some(req_vec2(cmd, p, "end")?) }; let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let (end, end_point) = match (end_ref, at) { + (Some(r), _) => { + let q = sk.resolve_point(r).ok_or_else(|| bad(cmd, format!("unknown sketch point `{r}`")))?; + (sk.point(q).ok_or_else(|| bad(cmd, format!("unknown sketch point `{r}`")))?, Some(q)) + } + (None, Some(at)) => (at, None), + (None, None) => return Err(bad(cmd, "missing `end`")), + }; + // A snapped place that is no point yet (`on:l3:…` on a line, `mid:l1` at its middle: a + // click between a line's ends) is no end to start from: said so, not as an unknown point + // (#10653). Point ids (`l1.end`, `p3`, `origin`) have no colon. + let not_an_end = || bad(cmd, "`start` must be the end point of a line or arc"); + if str_(p, "start").is_some_and(|start| start.contains(':')) { + return Err(not_an_end()); + } let st = req_parg(sk, doc, p, "start", cmd)?; - let picked = st.idx().ok_or_else(|| bad(cmd, "`start` must be the end point of a line or arc"))?; - // The picked point, then any other point at the same place: a trimmed arc's end is its own - // point, lying on the end of the curve that trimmed it, which is the one a click picks (#1485). - let at = st.pos(); - let tol = 1e-6 * at.len().max(1.0); - let candidates: Vec = - std::iter::once(picked).chain((0..sk.points.len()).filter(|&q| q != picked && sk.point(q).is_some_and(|x| x.dist(at) <= tol))).collect(); + let picked = st.idx().ok_or_else(not_an_end)?; + let candidates = tangent_start_candidates(sk, picked); let (ci, pi) = match str_(p, "curve") { Some(id) => { let ci = sk.curve_index(id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; @@ -841,24 +923,15 @@ fn arc_tangent(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| bad(cmd, "`start` is not an end of that curve"))?; (ci, pi) } - None => candidates - .iter() - .find_map(|&q| sk.curves.iter().enumerate().find(|(i, c)| !c.construction && leaving_dir(sk, *i, q).is_some()).map(|(i, _)| (i, q))) - .ok_or_else(|| bad(cmd, "no line or arc ends at `start`"))?, + None => tangent_start_curve(sk, &candidates).ok_or_else(|| bad(cmd, "no line or arc ends at `start`"))?, }; let t = leaving_dir(sk, ci, pi).ok_or_else(|| bad(cmd, "`start` is not an end of that curve"))?; let s0 = st.pos(); - let n = t.perp(); - let d = end - s0; - let den = 2.0 * n.dot(d); - if den.abs() < 1e-9 * d.len().max(1e-9) || d.len() < 1e-9 { - return Err(bad(cmd, "the end is straight ahead: draw a line instead")); - } - let center = s0 + n * (d.len2() / den); - let a = if den > 0.0 { - sk.add_arc(center, s0, end, [None, Some(pi), None], None)? + let (center, ccw) = tangent_arc_centre(t, s0, end).ok_or_else(|| bad(cmd, "the end is straight ahead: draw a line instead"))?; + let a = if ccw { + sk.add_arc(center, s0, end, [None, Some(pi), end_point], None)? } else { - let a = sk.add_arc(center, end, s0, [None, None, Some(pi)], None)?; + let a = sk.add_arc(center, end, s0, [None, end_point, Some(pi)], None)?; if let Some(c) = sk.curves.get_mut(a) { c.reversed = true; } @@ -959,6 +1032,8 @@ fn tangent_circle(s: &mut Session, p: &Value, cmd: &str, n: usize, radius: Optio fn circle_tan_tan(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.circle.two_tangent"; let r = match (crate::params::expr(p, "radius"), num(p, "diameter")) { + // A bare number typed as text reads in the design's unit, as in `sketch.dimension`. + (Some(r), _) if p.get("radius").is_some_and(Value::is_string) => s.doc.with_design_unit(r.as_str(), solidcraft_doc::expr::Kind::Length), (Some(r), _) => r.into_string(), (None, Some(d)) => format!("{}", d / 2.0), _ => return Err(bad(cmd, "needs `radius` or `diameter`")), @@ -1079,7 +1154,8 @@ pub(super) fn solve_new_only(sk: &mut Sketch, first_new: usize) { #[cfg(test)] mod blend_tests { use serde_json::{Value, json}; - use solidcraft_geom::{Seg2, Vec2}; + use solidcore_record::{Seg2, Vec2}; + use solidcraft_geom::prelude::*; use solidcraft_sketch::CurveKind; use crate::Session; @@ -1111,7 +1187,7 @@ mod blend_tests { } /// The derivatives 1…`order` of exact piece `seg` at its end (`at_end`), from the piece's own - /// geometry: what a blend must match, computed here independently of `Seg2::derivatives`. + /// geometry: what a blend must match, computed here independently of `Seg2Geom::derivatives`. fn piece_derivatives(seg: &Seg2, at_end: bool, order: usize) -> Vec { let t = if at_end { 1.0 } else { 0.0 }; let p = seg.point_at(t); @@ -1395,13 +1471,13 @@ mod blend_tests { let mut broken = solidcraft_sketch::Sketch::new(); let p0 = broken.add_point(Vec2::new(1.0, 1.0), None).unwrap(); let p1 = broken.add_point(Vec2::ZERO, None).unwrap(); - let l = broken.add_curve(CurveKind::Spline { pts: vec![p1, p0], control: true, degree: 1, periodic: false }, None).unwrap(); + let l = broken.add_curve(CurveKind::Spline { pts: vec![p1, p0], control: true, degree: 1, periodic: false, nurbs: None }, None).unwrap(); broken.points[p0].pos = Vec2::new(f64::NAN, 4.0); assert!(super::joint_derivatives(&broken, l, p1, 2, true, "a", "sketch.blend_curve").is_err(), "non-finite geometry"); let mut flat = solidcraft_sketch::Sketch::new(); let q0 = flat.add_point(Vec2::new(3.0, 3.0), None).unwrap(); let q1 = flat.add_point(Vec2::new(3.0, 3.0), None).unwrap(); - let d = flat.add_curve(CurveKind::Spline { pts: vec![q0, q1], control: true, degree: 1, periodic: false }, None).unwrap(); + let d = flat.add_curve(CurveKind::Spline { pts: vec![q0, q1], control: true, degree: 1, periodic: false, nurbs: None }, None).unwrap(); let e = super::joint_derivatives(&flat, d, q0, 2, true, "a", "sketch.blend_curve").unwrap_err().to_string(); assert!(e.contains("no tangent"), "{e}"); assert!(solidcraft_geom::hermite_bezier(Vec2::ZERO, Vec2::X, &[Vec2::Y; 5], &[Vec2::Y; 5]).is_none(), "no order above g4"); diff --git a/crates/engine/src/cmd/sketch_dimensioned.rs b/crates/engine/src/cmd/sketch_dimensioned.rs index db158803f..1ecd6806c 100644 --- a/crates/engine/src/cmd/sketch_dimensioned.rs +++ b/crates/engine/src/cmd/sketch_dimensioned.rs @@ -11,8 +11,8 @@ //! creator joins [`dimension_roles`] with its roles and entities, and `locate` gets a frame with a //! Z direction; the UI routes the 3D tools through `tools::draw`, which asks `dimension_roles`. use serde_json::{Map, Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::expr::{Kind, definition}; -use solidcraft_geom::Vec3; use crate::{ Result, Session, @@ -31,6 +31,7 @@ pub fn dimension_roles(creator: &str) -> Option<&'static [&'static str]> { // A circle is dimensioned by its diameter unless a radius is given. "sketch.circle.center" | "sketch.circle.two_point" | "sketch.circle.three_point" => &["diameter", "radius"], "sketch.arc.center_point" => &["radius", "sweep"], + "sketch.ellipse" => &["major_radius", "minor_radius"], "sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point" => &["length", "width"], "sketch.slot.arc_center" => &["radius", "sweep", "width"], "sketch.slot.arc_three_point" => &["width"], @@ -152,6 +153,9 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result { (c, "width" | "height") if c.starts_with("sketch.rectangle.") => (vec![curve(usize::from(role == "height"))?], "length"), (c, "radius" | "diameter") if c.starts_with("sketch.circle.") => (vec![curve(0)?], role), ("sketch.arc.center_point", "radius" | "sweep") => (vec![curve(0)?], role), + // `sketch.dimension` gives an ellipse its major radius as `major`, else its minor one. + ("sketch.ellipse", "major_radius") => (vec![curve(0)?], "major"), + ("sketch.ellipse", "minor_radius") => (vec![curve(0)?], "radius"), ("sketch.slot.center_to_center" | "sketch.slot.center_point", "length") => (vec![curve(0)?], "length"), ("sketch.slot.overall", "length") => (vec![curve(1)?, curve(3)?], "overall_length"), (c, "width") if c.starts_with("sketch.slot.") => (vec![curve(1)?], "diameter"), diff --git a/crates/engine/src/cmd/sketch_dimensioned_tests.rs b/crates/engine/src/cmd/sketch_dimensioned_tests.rs index 81e452e62..93a7805e2 100644 --- a/crates/engine/src/cmd/sketch_dimensioned_tests.rs +++ b/crates/engine/src/cmd/sketch_dimensioned_tests.rs @@ -1,5 +1,6 @@ use crate::Session; use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::ConstraintKind; fn run(s: &mut Session, command: &str, params: Value) -> Value { @@ -251,7 +252,7 @@ fn dimensioned_authoring_uses_selected_occurrence_and_keeps_local_geometry() { let local = model.sketch(s.active_sketch.unwrap()).unwrap(); close(local.plane.origin.x, 0.0); close(local.plane.origin.z, 2.0); - let world = s.world_state(); + let world = s.world_state().unwrap(); let displayed = world.sketch(s.active_sketch.unwrap()).unwrap(); close(displayed.plane.origin.x, 20.0); close(displayed.plane.origin.z, 2.0); @@ -355,6 +356,7 @@ fn sample(creator: &str) -> Option { "sketch.circle.two_point" => json!({"p0":[0,0],"p1":[10,0]}), "sketch.circle.three_point" => json!({"p0":[0,0],"p1":[10,0],"p2":[5,5]}), "sketch.arc.center_point" => json!({"center":[0,0],"start":[10,0],"end":[0,10]}), + "sketch.ellipse" => json!({"center":[0,0],"major":[10,6],"minor_radius":4}), "sketch.slot.center_to_center" | "sketch.slot.overall" => json!({"p0":[2,3],"p1":[22,3],"width":4}), "sketch.slot.center_point" => json!({"center":[12,3],"end":[22,3],"width":4}), "sketch.slot.arc_center" => json!({"center":[0,0],"start":[20,0],"end":[0,20],"width":6}), @@ -450,6 +452,19 @@ fn as_drawn_keeps_typed_values_alternatives_and_leaves_out_determined_sizes() { assert_eq!(out["dimensions"].as_object().unwrap().keys().collect::>(), ["width"]); } +/// An ellipse takes its major and minor radius (#10279): typed values drive it. +#[test] +fn an_ellipse_takes_a_typed_major_and_minor_radius() { + let mut s = session(); + let out = + draw(&mut s, "sketch.ellipse", json!({"center":[0,0],"major":[10,0],"minor_radius":4}), json!({"major_radius":"12 mm","minor_radius":5})); + let mut placed: Vec<&String> = out["dimensions"].as_object().unwrap().keys().collect(); + placed.sort(); + assert_eq!(placed, ["major_radius", "minor_radius"]); + close(measure(&s, |k| matches!(k, ConstraintKind::Distance { .. })), 12.0); + close(measure(&s, |k| matches!(k, ConstraintKind::Radius { .. })), 5.0); +} + /// Every `[x, y]` point of a sample moved by `(dx, dy)`; sizes and counts stay. fn shifted(v: &Value, dx: f64, dy: f64) -> Value { match v { diff --git a/crates/engine/src/cmd/sketch_drag.rs b/crates/engine/src/cmd/sketch_drag.rs index 0337546f1..78e822577 100644 --- a/crates/engine/src/cmd/sketch_drag.rs +++ b/crates/engine/src/cmd/sketch_drag.rs @@ -12,9 +12,10 @@ //! geometry cannot reach stop short at the edge of that stretch and go on past it. It steps only //! when the move is long next to the dragged geometry, so a normal mouse frame is a single solve. +use solidcraft_geom::prelude::*; use std::f64::consts::{PI, TAU}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, Sketch, conic_rho_from_point}; use super::{Ent, Left, counted_solve}; @@ -40,6 +41,17 @@ const HALVINGS: usize = 16; const AHEAD: usize = 8; /// An arc whose sweep gets this close (radians) to 0 or a full turn has run into its start. const SWEEP_EPS: f64 = 1e-6; +/// A line or circle longer or wider than this before a step and shorter or narrower than +/// `SHRINK_TO` after it was shrunk to a point by that step. An edit's `shrunk` stops at 1e-5, +/// but a drag's first step shrank a horizontal 20 mm line to 1.05e-5 (#9062): its direction +/// rows (`b.y - a.y`) scale with its length, so the solve stops wherever the length times the +/// tilt is under the tolerance, and the next frames took it the rest of the way. +const SHRINK_FROM: f64 = 1e-3; +const SHRINK_TO: f64 = 1e-4; + +/// A step that moves some point further than this many times the sketch's size and the +/// drag's way has thrown the geometry to a far solution: it is taken as failed. +const FLUNG: f64 = 1000.0; /// What a drag moves, from where it is (`t = 0`) to where the cursor puts it (`t = 1`). enum Path { @@ -169,6 +181,10 @@ pub(super) fn drag_entity( let line_grab = if with.is_empty() { LineGrab::new(sk, e, from) } else { None }; let start = line_grab.and_then(|g| g.point(sk)).or_else(|| if let Ent::Point(q) = e { sk.point(q) } else { None }); let mut frame = live.then(frame_budget); + let reach = FLUNG * (extent(sk) + path.length()).max(1.0); + // The sketch as the drag found it: no step may press one of its lines to no length. + let mut as_found = Geometry::default(); + as_found.take(sk); // Only success matters to these solves: the degrees of freedom of a sketch with the entity // held are not the sketch's. Each is seeded on the last solved state (`last`), so what the // constraints pin down keeps the orientation it had there. A failed or wrapping step is @@ -179,7 +195,9 @@ pub(super) fn drag_entity( let held = |sk: &mut Sketch, last: &Geometry, t: f64, budget: &mut Budget| { path.apply(sk, t); let kept = keep.as_ref().is_some_and(|keep| { - let ok = counted_solve(sk, keep, Some(&last.pos), Analysis::StatusOnly, Some(&mut *budget)).ok() && !last.sweep_wrapped(sk); + let ok = counted_solve(sk, keep, Some(&last.pos), Analysis::StatusOnly, Some(&mut *budget)).ok() + && !last.sweep_wrapped(sk) + && !last.shrank(sk); if !ok { last.restore(sk); path.apply(sk, t); @@ -197,10 +215,13 @@ pub(super) fn drag_entity( solves.work += budget.spent() - spent; solves.cut |= budget.exhausted(); solves.numeric |= budget.numeric_exhausted(); - let outcome = if !ok { + // A step that shrank a line to a point only met its constraints without that line. + let outcome = if !ok || last.shrank(sk) { Step::Failed } else if last.sweep_wrapped(sk) { Step::Wrapped + } else if last.flung(sk, reach) || as_found.squashed(sk) { + Step::Failed } else { return Step::Solved; }; @@ -332,7 +353,11 @@ pub(super) fn drag_entity( let valid = |before: &Sketch, after: &Sketch| { let mut geometry = Geometry::default(); geometry.take(before); - !geometry.sweep_wrapped(after) && solidcraft_sketch::fillets_kept(before, after) + !geometry.sweep_wrapped(after) + && !geometry.shrank(after) + && !geometry.flung(after, reach) + && !as_found.squashed(after) + && solidcraft_sketch::fillets_kept(before, after) }; let followed = match (e, line_grab) { (Ent::Point(q), _) => solidcraft_sketch::move_point_towards(sk, q, to, max_step, frame.as_mut(), valid), @@ -572,6 +597,23 @@ impl Geometry { } } + /// Did the step press a line to (nearly) no length: under 1/1000 of what it had when this + /// geometry was taken? A line with no length has no direction left for the constraints on + /// it, so an end dragged past the point where its line would have to turn over stops there. + fn squashed(&self, sk: &Sketch) -> bool { + self.curves.iter().any(|(kind, _)| { + let CurveKind::Line { a, b } = *kind else { return false }; + let (Some(a0), Some(b0)) = (self.pos.get(a), self.pos.get(b)) else { return false }; + let before = a0.dist(*b0); + before > 1e-3 && sk.point(a).zip(sk.point(b)).is_some_and(|(a1, b1)| a1.dist(b1) < before * 1e-3) + }) + } + + /// Did the step throw some point further than `reach` (or to no number at all)? + fn flung(&self, sk: &Sketch, reach: f64) -> bool { + sk.points.iter().zip(&self.pos).any(|(p, was)| !(p.pos.dist(*was) <= reach)) + } + /// Did the step drive some arc's end through its start: the sweep jumped through 0 / a full /// turn, or ran from clear of them onto one? An arc already that close may still move. /// Measured on the arc's ends as they were before the step (a solve may swap them). @@ -585,6 +627,22 @@ impl Geometry { (s1 - s0).abs() > PI || (clear(s0) && !clear(s1)) }) } + + /// Did the step shrink a line or circle to a point (from longer or wider than `SHRINK_FROM` + /// to under `SHRINK_TO`)? A line with no length has no direction left, so its horizontal, + /// parallel or point-on-line constraints hold anything: a solve took that to put a point it + /// couldn't reach on the line, and the construction line it was on vanished (#9062). + fn shrank(&self, sk: &Sketch) -> bool { + let was = |q: usize| self.pos.get(q).copied(); + self.curves.iter().zip(&sk.curves).any(|((kind, _), now)| match (kind, &now.kind) { + (CurveKind::Line { a, b }, _) => match (was(*a).zip(was(*b)), sk.point(*a).zip(sk.point(*b))) { + (Some((a0, b0)), Some((a1, b1))) => a0.dist(b0) > SHRINK_FROM && !(a1.dist(b1) >= SHRINK_TO), + _ => false, + }, + (CurveKind::Circle { r: r0, .. }, CurveKind::Circle { r: r1, .. }) => *r0 > SHRINK_FROM && !(*r1 >= SHRINK_TO), + _ => false, + }) + } } /// The held solves dragging `e` from `from` to `to` takes (0 when it cannot move): the plan @@ -801,6 +859,29 @@ impl Group<'_> { } } +/// The size of the sketch: the diagonal of its points' box and its circles' diameters. +fn extent(sk: &Sketch) -> f64 { + let (lo, hi) = sk + .points + .iter() + .map(|p| p.pos) + .filter(|p| p.x.is_finite() && p.y.is_finite()) + .fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| { + (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))) + }); + let radius = sk + .curves + .iter() + .filter_map(|c| match c.kind { + CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } => Some(r.abs()), + _ => None, + }) + .filter(|r| r.is_finite()) + .fold(0.0, f64::max); + let diagonal = if lo.x <= hi.x { lo.dist(hi) } else { 0.0 }; + diagonal + 2.0 * radius +} + /// The smallest size that can make a constrained shape take another solution (of the geometry /// in `group`, or of the whole sketch), or infinity when there is none: every length the /// constraints hold. That is driving length dimensions (offsets along an axis or from a line diff --git a/crates/engine/src/cmd/sketch_drag_live_tests.rs b/crates/engine/src/cmd/sketch_drag_live_tests.rs index 2e46b658d..d3df28daa 100644 --- a/crates/engine/src/cmd/sketch_drag_live_tests.rs +++ b/crates/engine/src/cmd/sketch_drag_live_tests.rs @@ -2,7 +2,8 @@ //! rank analysis, and evaluates nothing after it; the gesture's end evaluates the model once. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::solve_counts; use crate::Session; @@ -93,17 +94,17 @@ fn frames(s: &mut Session, n: usize, live: bool) -> Vec { } fn body_contains(s: &Session, p: Vec3) -> bool { - s.model.state().bodies.first().expect("a body").body.contains(p) + s.model.state().bodies.first().expect("a body").body.classify_point(p).unwrap() == solidcraft_kernel::PointClass::Inside } -fn pt(s: &Session, id: &str) -> solidcraft_geom::Vec2 { +fn pt(s: &Session, id: &str) -> solidcore_record::Vec2 { let sk = s.active_sketch.and_then(|i| s.doc.sketch(i).ok()).expect("sketch mode"); sk.resolve_point(id).and_then(|i| sk.point(i)).expect("the point") } -fn corner(s: &Session) -> solidcraft_geom::Vec2 { +fn corner(s: &Session) -> solidcore_record::Vec2 { let id = s.active_sketch.expect("sketch mode"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let sk = &st.sketch(id).expect("the shown sketch").sketch; sk.resolve_point("l1.start").and_then(|i| sk.point(i)).expect("the corner") } @@ -120,12 +121,29 @@ fn a_live_frame_solves_once_and_leaves_the_features_after_the_sketch_stale() { assert_eq!(r["sketch"]["solved"], json!(true)); assert_eq!(r["sketch"]["dof"], json!(2), "the degrees of freedom from before the drag"); // The sketch shows its new place; the extrude keeps its last result. - assert!(corner(&s).dist(solidcraft_geom::Vec2::new(4.0, 5.0)) < 1e-9); + assert!(corner(&s).dist(solidcore_record::Vec2::new(4.0, 5.0)) < 1e-9); let result = s.model.result(extrude).expect("the extrude's result"); assert!(result.stale); assert!(s.model.state().bodies.first().expect("a body").body.same(&body), "the body is not rebuilt"); } +/// A frame copies the design once, to edit it: its undo step holds the design as it was, and a +/// second copy for storing the edited one would double the work on a large design. +#[test] +fn a_live_frame_copies_the_design_once_and_its_undo_step_keeps_the_design_before() { + let (mut s, _) = extruded(); + let before = s.doc.clone(); + let undo = s.undo.len(); + crate::tests::doc_copies::take(); + frames(&mut s, 1, true); + assert_eq!(crate::tests::doc_copies::take(), 0, "the edited design is stored, not copied again"); + assert!(corner(&s).dist(solidcore_record::Vec2::new(4.0, 5.0)) < 1e-9); + assert_eq!(s.undo.len(), undo + 1); + assert!(s.undo.last().is_some_and(|u| std::sync::Arc::ptr_eq(&u.doc, &before)), "undo goes back to the design before"); + run(&mut s, "edit.undo", json!({})); + assert!(std::sync::Arc::ptr_eq(&s.doc, &before)); +} + #[test] fn the_drag_end_evaluates_once_to_the_scripted_drags_result() { let (mut live, extrude) = extruded(); @@ -147,7 +165,7 @@ fn the_drag_end_evaluates_once_to_the_scripted_drags_result() { assert!(live.model.result(extrude).is_some_and(|r| !r.stale && r.error.is_none())); // One undo step for the gesture is the UI's business; each frame is still undoable. run(&mut live, "edit.undo", json!({})); - assert!(corner(&live).dist(solidcraft_geom::Vec2::new(3.0, 5.0)) < 1e-9); + assert!(corner(&live).dist(solidcore_record::Vec2::new(3.0, 5.0)) < 1e-9); } #[test] @@ -193,8 +211,8 @@ fn a_drag_reports_how_far_the_geometry_followed() { // The grabbed midpoint follows a 15 mm circle around the fixed start. let r = run(&mut s, "sketch.drag", json!({"entity": "l1", "from": [25, 10], "to": [25, 20], "live": live})); let at = crate::params::vec2(&r["at"]).expect("`at`"); - let base = solidcraft_geom::Vec2::new(10.0, 10.0); - let expected = base + solidcraft_geom::Vec2::new(15.0, 10.0).normalized().unwrap() * 15.0; + let base = solidcore_record::Vec2::new(10.0, 10.0); + let expected = base + solidcore_record::Vec2::new(15.0, 10.0).normalized().unwrap() * 15.0; assert!(at.dist(expected) < 1e-4, "{r}"); assert!(at.dist((pt(&s, "l1.start") + pt(&s, "l1.end")) * 0.5) < 1e-6); assert!((r["reached"].as_f64().unwrap() - (at.y - 10.0) / 10.0).abs() < 1e-6); @@ -216,7 +234,7 @@ fn a_live_drag_of_a_lone_sketch_shows_it_without_evaluating() { assert_eq!(s.evaluations, 0); assert_eq!(solve_counts::take(), (2, 0)); // The free rectangle's corner moves alone; its profile follows. - assert!(corner(&s).dist(solidcraft_geom::Vec2::new(3.0, 5.0)) < 1e-9); + assert!(corner(&s).dist(solidcore_record::Vec2::new(3.0, 5.0)) < 1e-9); let st = s.model.state(); let profile = st.sketches[0].profiles.first().expect("a profile"); assert!((profile.area - 22.0 * 15.0).abs() < 1e-9, "{}", profile.area); @@ -244,8 +262,8 @@ fn the_grab_follows_the_points_that_move() { run(&mut s, "sketch.line", json!({"points": [[10, 10], [30, 10]]})); run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]})); ui_frames(&mut s, "l1", [20.0, 10.0], &[[0.0, 1.0]; 6]); - assert!(pt(&s, "l1.end").dist(solidcraft_geom::Vec2::new(30.0, 22.0)) < 1e-6, "{:?}", pt(&s, "l1.end")); - assert!(pt(&s, "l1.start").dist(solidcraft_geom::Vec2::new(10.0, 10.0)) < 1e-12); + assert!(pt(&s, "l1.end").dist(solidcore_record::Vec2::new(30.0, 22.0)) < 1e-6, "{:?}", pt(&s, "l1.end")); + assert!(pt(&s, "l1.start").dist(solidcore_record::Vec2::new(10.0, 10.0)) < 1e-12); } #[test] @@ -346,7 +364,7 @@ fn a_drag_with_the_rest_of_a_selection_moves_it_as_one() { run(&mut s, "sketch.circle.center", json!({"center": [40, 10], "radius": 3, "id": "c1"})); s }; - let v = solidcraft_geom::Vec2::new; + let v = solidcore_record::Vec2::new; for live in [false, true] { // Dragged alone, the line leaves the tail's free end where it was as far as it can. let mut s = start(); @@ -370,7 +388,7 @@ fn a_drag_with_the_rest_of_a_selection_moves_it_as_one() { /// A 5 x 5 square drawn on the top face of a 30 x 20 x 10 box, the face's edges projected into /// its sketch; returns the session and a corner of the square (its id and where it is). -fn on_a_face() -> (Session, String, solidcraft_geom::Vec2) { +fn on_a_face() -> (Session, String, solidcore_record::Vec2) { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 30, "width": 20, "height": 10})); run(&mut s, "sketch.create", json!({"plane": {"face": [15, 10, 10]}})); @@ -386,10 +404,10 @@ fn on_a_face() -> (Session, String, solidcraft_geom::Vec2) { } /// One live frame moving `point` from `at` by `dx`; returns where it went. -fn live_frame(s: &mut Session, point: &str, at: solidcraft_geom::Vec2, dx: f64) -> solidcraft_geom::Vec2 { +fn live_frame(s: &mut Session, point: &str, at: solidcore_record::Vec2, dx: f64) -> solidcore_record::Vec2 { let to = [at.x + dx, at.y]; run(s, "sketch.drag", json!({"entity": point, "from": [at.x, at.y], "to": to, "live": true})); - solidcraft_geom::Vec2::new(to[0], to[1]) + solidcore_record::Vec2::new(to[0], to[1]) } #[test] diff --git a/crates/engine/src/cmd/sketch_ends.rs b/crates/engine/src/cmd/sketch_ends.rs index 2f41d6fba..18e1dc2c5 100644 --- a/crates/engine/src/cmd/sketch_ends.rs +++ b/crates/engine/src/cmd/sketch_ends.rs @@ -1,63 +1,85 @@ //! Loose ends of a sketch's profile curves: the ones that touch nothing (open) and the ones that //! touch another curve only by position (untied), and tying the untied ones. -use serde_json::{Value, json}; +use serde_json::Value; use solidcraft_sketch::{ConstraintKind, EndReport, EndTouch, Sketch, loose_ends}; use super::sketch::{add_c, edit}; use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, string_list}; +use crate::schema::sketch_ends::{LooseEnds, LooseEndsParams, OpenEnd, TieLooseEndsParams, TiedLooseEnds, Touches, UntiedEnd}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; +const LOOSE_ENDS_CONTRACT: TypedContract = TypedContract::new(); +const TIE_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("sketch.loose_ends", "Loose Ends", loose_ends_cmd).icon("c_coincident").enabled(in_sketch).noundo().params( + CommandSpec::new("sketch.loose_ends", "Loose Ends", crate::checked!("sketch.loose_ends", loose_ends_cmd)) + .icon("c_coincident") + .enabled(in_sketch) + .noundo() + .contract(&LOOSE_ENDS_CONTRACT) + .output(output_schema_for::) + .params( "sketch?: id|name (default active): the ends of profile curves (not construction, projected or text) that can make a profile fail. open: [{point, curve, at}] ends that touch no other profile curve (no profile runs through them); untied: [{point, curve, at, touches: {point}|{curve}}] ends that touch another curve only by position (the profile closes now, but nothing keeps it closed when a dimension changes)", - ), - CommandSpec::new("sketch.loose_ends.tie", "Tie Loose Ends", tie_cmd).icon("c_coincident").enabled(in_sketch).params( + ), + CommandSpec::new("sketch.loose_ends.tie", "Tie Loose Ends", crate::checked!("sketch.loose_ends.tie", tie_cmd)) + .icon("c_coincident") + .enabled(in_sketch) + .contract(&TIE_CONTRACT) + .output(output_schema_for::) + .params( "sketch?: id|name (default active); points?: [point ids] (default: every untied end): ties each untied end to what it touches, coincident with another curve's end or on another curve. Returns constraints: [ids added], and the untied ends left", - ), + ), ]; -fn point_id(sk: &Sketch, i: usize) -> Value { - sk.points.get(i).map_or(Value::Null, |p| json!(p.id)) +fn point_id(sk: &Sketch, i: usize) -> Option { + sk.points.get(i).map(|p| p.id.clone()) } -fn curve_id(sk: &Sketch, i: usize) -> Value { - sk.curves.get(i).map_or(Value::Null, |c| json!(c.id)) +fn curve_id(sk: &Sketch, i: usize) -> Option { + sk.curves.get(i).map(|c| c.id.clone()) } -fn at(sk: &Sketch, i: usize) -> Value { - sk.point(i).map_or(Value::Null, |v| json!([v.x, v.y])) +fn at(sk: &Sketch, i: usize) -> Option<[f64; 2]> { + sk.point(i).map(|v| [v.x, v.y]) } /// The point that is an end of curve `c` (for `curve` in the report). -fn end_curve(sk: &Sketch, p: usize) -> Value { +fn end_curve(sk: &Sketch, p: usize) -> Option { let c = sk.curves.iter().position(|c| c.kind.ends().is_some_and(|(a, b)| a == p || b == p) && !(c.construction || c.centerline || c.infinite)); - c.map_or(Value::Null, |c| curve_id(sk, c)) + c.and_then(|c| curve_id(sk, c)) } -fn report_json(sk: &Sketch, r: &EndReport) -> Value { - let open: Vec = r.open.iter().map(|&p| json!({"point": point_id(sk, p), "curve": end_curve(sk, p), "at": at(sk, p)})).collect(); - let untied: Vec = r +fn ends_report(sk: &Sketch, r: &EndReport) -> LooseEnds { + let open = r.open.iter().map(|&p| OpenEnd { point: point_id(sk, p), curve: end_curve(sk, p), at: at(sk, p) }).collect(); + let untied = r .untied .iter() - .map(|u| { - let touches = match u.touches { - EndTouch::Point(q) => json!({"point": point_id(sk, q)}), - EndTouch::Curve(c) => json!({"curve": curve_id(sk, c)}), - }; - json!({"point": point_id(sk, u.point), "curve": curve_id(sk, u.curve), "at": at(sk, u.point), "touches": touches}) + .map(|u| UntiedEnd { + point: point_id(sk, u.point), + curve: curve_id(sk, u.curve), + at: at(sk, u.point), + touches: match u.touches { + EndTouch::Point(q) => Touches::Point(point_id(sk, q)), + EndTouch::Curve(c) => Touches::Curve(curve_id(sk, c)), + }, }) .collect(); - json!({"open": open, "untied": untied}) + LooseEnds { open, untied, param_warnings: Vec::new() } +} + +fn reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) } fn loose_ends_cmd(s: &mut Session, p: &Value) -> Result { let id = sketch_store::target(s, p, "sketch.loose_ends")?; let st = s.model.state(); let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch has not been evaluated".into()))?; - Ok(report_json(&ss.sketch, &ss.ends)) + reply("sketch.loose_ends", ends_report(&ss.sketch, &ss.ends)) } fn tie_cmd(s: &mut Session, p: &Value) -> Result { @@ -86,11 +108,11 @@ fn tie_cmd(s: &mut Session, p: &Value) -> Result { }; added.push(add_c(sk, kind)?); } - let left = report_json(sk, &loose_ends(sk)).get("untied").cloned().unwrap_or(Value::Null); + let left = ends_report(sk, &loose_ends(sk)).untied; Ok((added, left)) })?; let (added, left) = added; - Ok(json!({"constraints": added, "sketch": info, "untied": left})) + reply(cmd, TiedLooseEnds { constraints: added, sketch: info, untied: left, param_warnings: Vec::new() }) } #[cfg(test)] diff --git a/crates/engine/src/cmd/sketch_equation.rs b/crates/engine/src/cmd/sketch_equation.rs index 5aac5da3e..1ab4bf5b2 100644 --- a/crates/engine/src/cmd/sketch_equation.rs +++ b/crates/engine/src/cmd/sketch_equation.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use solidcraft_doc::sketch_equation::{self, DEFAULT_TOLERANCE, EquationFit}; -use solidcraft_sketch::{EquationCurve, Sketch}; +use solidcraft_sketch::{EquationCurve, Sketch, VariableUnit}; use super::sketch::{edit, mark_construction}; use super::{CommandSpec, in_sketch}; @@ -31,8 +31,10 @@ pub static COMMANDS: &[CommandSpec] = &[ .params(concat!( "x: x(t), y: y(t): formulas of t in the design's expression language and parameters (\"r * (cos(t) + t * sin(t))\"); or explicit: true and y: f(x) alone (no x); \ start, end: the range of t (or of x): a number or an expression (\"2 * pi\", \"360 deg\" is 2·pi, a length is in the design's unit); \ - tolerance?: mm (default 0.01): how far the curve may stray from the formulas (0.0001 to 10); construction?: bool. \ + tolerance?: mm (default 0.01): how far the curve may stray from the formulas (0.0001 to 10); construction?: bool; \ + variable_unit?: \"number\" (default) or \"range\". \ The variable is a plain number: sin(t) reads it in radians; a result without a unit is in the design's length unit. \ + With variable_unit \"range\" it is a length, so a ^ 2 / (4 * t) is a length when a is one: start and end must both be lengths, or one a length and the other a plain number, which is then in the design's unit. \ Makes a fit point spline through fixed points, as many as the tolerance needs (up to 500), closed smoothly when it ends where it starts; \ the points are placed again from the formulas whenever the parameters change. Returns curve, points (how many), closed, deviation (mm)", created_doc!() @@ -43,7 +45,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .contract(&EDIT_CONTRACT) .output(output_schema_for::) .params( - "curve: an equation curve's id; x?, y?, explicit?, start?, end?, tolerance?: as in sketch.equation_curve, each kept when left out (explicit: true drops x; false needs x). \ + "curve: an equation curve's id; x?, y?, explicit?, start?, end?, tolerance?, variable_unit?: as in sketch.equation_curve, each kept when left out (explicit: true drops x; false needs x). \ The points are chosen again for the new formulas; the curve's start point (and the end point of an open curve) keeps its id, so geometry joined there stays joined. Returns curve, points, closed, deviation", ), ]; @@ -81,6 +83,13 @@ fn explicit(p: &Value, cmd: &str) -> Result> { } } +fn variable_unit(p: &Value, cmd: &str) -> Result> { + match p.get("variable_unit") { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_str().and_then(VariableUnit::parse).map(Some).ok_or_else(|| bad(cmd, "`variable_unit` must be \"number\" or \"range\"")), + } +} + /// The equation a command's parameters give, over `old` (each left out kept). fn equation(p: &Value, cmd: &str, old: Option<&EquationCurve>) -> Result { let x = text(p, cmd, "x")?; @@ -111,6 +120,7 @@ fn equation(p: &Value, cmd: &str, old: Option<&EquationCurve>) -> Result String { + run(s, "parameters.add", json!({"name": "a", "expression": "10 mm"})); + run(s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(s, "sketch.equation_curve", json!({"x": "t", "y": "a ^ 2 / (4 * t)", "start": "a", "end": "3 * a", "variable_unit": "range"})); + assert_eq!(r["closed"], false, "{r}"); + let id = r["curve"].as_str().unwrap().to_string(); + run(s, "sketch.finish", json!({})); + no_trouble(s); + id +} + +#[test] +fn a_variable_in_its_ranges_unit_follows_the_parameter_and_the_design_unit() { + let mut s = Session::default(); + // Without the flag this very formula is refused, as it always was. + run(&mut s, "parameters.add", json!({"name": "b", "expression": "10 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Off"})); + let why = s.execute("sketch.equation_curve", &json!({"x": "t", "y": "b ^ 2 / (4 * t)", "start": "b", "end": "3 * b"})).unwrap_err().to_string(); + assert!(why.contains("length^2"), "{why}"); + run(&mut s, "sketch.finish", json!({})); + + let id = range_unit_curve(&mut s); + assert_parabola(&s, &id, 10.0); + run(&mut s, "parameters.change", json!({"name": "a", "expression": "20 mm"})); + no_trouble(&s); + assert_parabola(&s, &id, 20.0); + // In millimetres the parameter's length does not depend on the design's unit, nor the curve. + run(&mut s, "document.units", json!({"units": "in"})); + no_trouble(&s); + assert_parabola(&s, &id, 20.0); + // A parameter given in inches, in an inch design. + run(&mut s, "parameters.change", json!({"name": "a", "expression": "2 in"})); + no_trouble(&s); + assert_parabola(&s, &id, 50.8); +} + +/// A plain end is in the design's unit, so it moves when the unit changes (#9333). +#[test] +fn a_plain_end_of_the_range_takes_the_design_unit() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "a", "expression": "100 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.equation_curve", json!({"x": "t", "y": "t / 2", "start": 1, "end": "a", "variable_unit": "range"})); + let id = r["curve"].as_str().unwrap().to_string(); + run(&mut s, "sketch.finish", json!({})); + assert!((curve_points(&s, &id)[0] - Vec2::new(1.0, 0.5)).len() < 1e-9); + run(&mut s, "document.units", json!({"units": "in"})); + no_trouble(&s); + let pts = curve_points(&s, &id); + assert!((pts[0] - Vec2::new(25.4, 12.7)).len() < 1e-9, "{:?}", pts[0]); + assert!((*pts.last().unwrap() - Vec2::new(100.0, 50.0)).len() < 1e-9); +} + +#[test] +fn the_refused_range_says_why_and_changes_nothing() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "a", "expression": "10 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let before = s.doc.to_json(); + for (start, end) in [("a", "90 deg"), ("90 deg", "a"), ("0", "1")] { + let p = json!({"x": "t", "y": "t", "start": start, "end": end, "variable_unit": "range"}); + let why = s.execute("sketch.equation_curve", &p).unwrap_err().to_string(); + assert!( + why.contains("with the variable in its range's unit, start and end must both be lengths, or one a length and the other a plain number"), + "{p}: {why}" + ); + assert_eq!(s.doc.to_json(), before, "{p} changed the design"); + } + for bad in [json!("mm"), json!(1), json!(true), json!({}), json!("Range")] { + assert!(s.execute("sketch.equation_curve", &json!({"x": "t", "y": "t", "start": 0, "end": "a", "variable_unit": bad})).is_err(), "{bad}"); + } +} + +/// A design file is hostile (#9333): a range the rule refuses is reported on the sketch, and a +/// value that means nothing refuses the file. Neither crashes. +#[test] +fn a_hostile_saved_flag_or_range_is_an_error_not_a_crash() { + let mut s = Session::default(); + range_unit_curve(&mut s); + let saved = s.doc.to_json(); + assert!(saved.contains("3 * a") && saved.contains("\"range\""), "{saved}"); + let angle = saved.replace("3 * a", "90 deg"); + let r = Session::new(solidcraft_doc::Document::from_json(&angle).unwrap()); + let res = r.model.results.iter().find(|r| r.name == "S").unwrap(); + assert!(res.error.as_deref().is_some_and(|e| e.contains("equation curve") && e.contains("must both be lengths")), "{:?}", res.error); + assert!(solidcraft_doc::Document::from_json(&saved.replace("\"range\"", "\"furlong\"")).is_err()); +} + +#[test] +fn an_edit_keeps_the_flag_until_told_and_a_saved_design_keeps_it() { + use solidcraft_sketch::VariableUnit; + let mut s = Session::default(); + let id = range_unit_curve(&mut s); + let f = s.doc.find_feature("S").unwrap().id; + // The file says it, and reopening follows it. + let saved = s.doc.to_json(); + assert!(saved.contains("variable_unit"), "not saved"); + let mut r = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + no_trouble(&r); + assert_eq!(r.doc.sketch(f).unwrap().equation_of(&id).unwrap().variable_unit, VariableUnit::Range); + assert_parabola(&r, &id, 10.0); + run(&mut r, "parameters.change", json!({"name": "a", "expression": "20 mm"})); + assert_parabola(&r, &id, 20.0); + // An edit that leaves it out keeps it. + run(&mut s, "sketch.edit", json!({"sketch": "S"})); + run(&mut s, "sketch.equation_curve.edit", json!({"curve": id, "tolerance": 0.005})); + assert_eq!(s.doc.sketch(f).unwrap().equation_of(&id).unwrap().variable_unit, VariableUnit::Range); + // Off again, that formula is refused and the curve stays as it was. + assert!(s.execute("sketch.equation_curve.edit", &json!({"curve": id, "variable_unit": "number"})).is_err()); + assert_eq!(s.doc.sketch(f).unwrap().equation_of(&id).unwrap().variable_unit, VariableUnit::Range); + run(&mut s, "sketch.equation_curve.edit", json!({"curve": id, "y": "t / 2", "start": 0, "end": 10, "variable_unit": "number"})); + assert_eq!(s.doc.sketch(f).unwrap().equation_of(&id).unwrap().variable_unit, VariableUnit::Number); + assert!(!s.doc.to_json().contains("variable_unit")); +} + +/// A design written without the flag (#9333): nothing in the file changes, and its curve is what +/// it was, with the variable a plain number over a range in length. +#[test] +fn a_design_saved_without_the_flag_reopens_the_same() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.equation_curve", json!({"x": "t", "y": "t * t / 20", "start": "0 mm", "end": "40 mm"})); + let id = r["curve"].as_str().unwrap().to_string(); + run(&mut s, "sketch.finish", json!({})); + let saved = s.doc.to_json(); + assert!(!saved.contains("variable_unit"), "a curve without the flag writes no new key"); + let want = curve_points(&s, &id); + assert!((*want.last().unwrap() - Vec2::new(40.0, 80.0)).len() < 1e-9); + // The format before this change, as the last release wrote it. + let mut old: Value = serde_json::from_str(&saved).unwrap(); + old["format"] = json!(solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT - 1)); + if let Some(o) = old.as_object_mut() { + o.remove("format_pending"); + } + let r = Session::new(solidcraft_doc::Document::from_json(&old.to_string()).unwrap()); + no_trouble(&r); + assert_eq!(curve_points(&r, &id), want); +} diff --git a/crates/engine/src/cmd/sketch_face.rs b/crates/engine/src/cmd/sketch_face.rs index 2742b8ada..e628b42aa 100644 --- a/crates/engine/src/cmd/sketch_face.rs +++ b/crates/engine/src/cmd/sketch_face.rs @@ -2,8 +2,9 @@ use crate::params::{bad, vec3}; use crate::{Result, Session}; use serde_json::Value; +use solidcore_record::Plane; use solidcraft_doc::{EmbossFace, PlaneRef, apply_point, apply_vector, mat_inverse, mat_mul}; -use solidcraft_geom::Plane; +use solidcraft_geom::prelude::*; pub(in crate::cmd) fn is_face(p: &Value) -> bool { p.get("plane").and_then(|plane| plane.get("face")).is_some() @@ -22,7 +23,7 @@ pub(in crate::cmd) fn capture_internal(s: &Session, value: &Value, cmd: &str) -> /// looks at the design. pub(crate) struct FacePickForm<'a> { /// The picked point, in world coordinates. - pub point: solidcraft_geom::Vec3, + pub point: solidcore_record::Vec3, /// Keep the plane as it is now instead of following the face. pub fixed: bool, /// The exact pick: the world body and the face's index, given together. @@ -142,7 +143,7 @@ fn capture_impl(s: &Session, value: &Value, cmd: &str, internal: bool) -> Result continue; } let faces = body.body.faces(tolerance)?; - let mesh = body.body.tessellate(tolerance)?; + let mesh = body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tolerance))?; // The triangles are grouped by face once, and a face's test reads only its own: the // work is the mesh plus one plane test per face, not the mesh once per face (a // modelled thread leaves thousands of faces, #6720). @@ -275,6 +276,27 @@ pub(in crate::cmd) fn capture_positions(s: &mut Session, plane: &PlaneRef) -> Re Ok(()) } +/// The component and placement (occurrence path, empty for the design) whose body a face pick +/// `value` lies on: the pick's `path`, else its `body`'s first placement, else the exact +/// attachment `captured` from it. `None` when none of them names one (a sheet metal panel +/// face picked by its point alone, or a fixed plane picked by its point alone). +pub(in crate::cmd) fn pick_owner(s: &Session, value: &Value, captured: &PlaneRef, cmd: &str) -> Result)>> { + let form = face_pick_form(value).map_err(|why| bad(cmd, why))?; + if let Some(path) = form.path { + if path.is_empty() { + return Ok(Some((0, path))); + } + let component = s.occurrence_placement(&path)?.component; + return Ok(Some((component, path))); + } + if let Some(body) = form.body { + let state = s.model.state(); + let doc = s.placed_document(); + return Ok(state.body(body).map(|body| doc.model_body_component(body)).map(|component| (component, doc.first_path(component)))); + } + Ok(anchor(captured).map(|anchor| (anchor.component, anchor.path.clone()))) +} + #[cfg(test)] #[path = "sketch_face_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/sketch_face_tests.rs b/crates/engine/src/cmd/sketch_face_tests.rs index f6d195c99..44c60602f 100644 --- a/crates/engine/src/cmd/sketch_face_tests.rs +++ b/crates/engine/src/cmd/sketch_face_tests.rs @@ -1,12 +1,13 @@ use crate::Session; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap_or_else(|error| panic!("{command} {params}: {error}")) } fn top_pick(s: &Session, body: &str) -> Value { - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.body(body).unwrap(); let face = body .body @@ -35,11 +36,11 @@ fn exact_selected_base_follows_height_and_never_retargets_control() { let height = s.doc.find_feature("BaseFeature").unwrap().param_names[2].clone(); run(&mut s, "parameters.change", json!({"name":height,"expression":"20 mm"})); assert!((s.model.state().sketch(sketch).unwrap().plane.origin.z - 20.).abs() < 1e-6); - assert!((s.world_state().body("Badge").unwrap().mesh().bounds().max.z - 22.).abs() < 1e-6); + assert!((s.world_state().unwrap().body("Badge").unwrap().mesh().bounds().max.z - 22.).abs() < 1e-6); run(&mut s, "timeline.delete", json!({"features":["BaseFeature"]})); assert!(s.model.result(sketch).unwrap().error.is_some()); assert!(s.model.state().body("Badge").is_none()); - assert!((s.world_state().body("Control").unwrap().mesh().bounds().max.z - 30.).abs() < 1e-6); + assert!((s.world_state().unwrap().body("Control").unwrap().mesh().bounds().max.z - 30.).abs() < 1e-6); let before = s.doc.to_json(); let reopened = Session::new(solidcraft_doc::Document::from_json(&before).unwrap()); assert!(reopened.model.result(sketch).unwrap().error.is_some()); @@ -75,11 +76,26 @@ fn explicit_rebind_preserves_geometry_dimensions_context_and_one_undo() { #[test] fn unsupported_face_has_explicit_fixed_alternative_and_no_live_projection() { let mut s = Session::default(); - // A top half Offset Face raised: no construction certificate and no exact history name yet. - run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Base"})); - run(&mut s, "solid.split_face", json!({"faces":[[10,15,20]],"plane":{"origin":[20,0,0],"normal":[1,0,0]}})); - run(&mut s, "solid.offset_face", json!({"faces":[[10,15,20]],"distance":5})); - let mut pick = top_pick(&s, "Base"); + // A rib's wall: a rib reports no roles for the faces it builds (Traced::unnamed), so the + // wall has no construction certificate and no exact history name to attach by. + run(&mut s, "solid.box", json!({"length":40,"width":20,"height":5,"corner":[0,0,0],"body_name":"L"})); + run(&mut s, "solid.box", json!({"length":5,"width":20,"height":40,"corner":[0,0,0],"operation":"join"})); + run(&mut s, "sketch.create", json!({"plane":{"origin":[0,10,0],"x_dir":[1,0,0],"y_dir":[0,0,1]},"name":"RibSketch"})); + run(&mut s, "sketch.line", json!({"points":[[5,25],[25,5]],"ids":["l1"]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.rib", json!({"sketch":"RibSketch","curves":["l1"],"thickness":4})); + let mut pick = { + let world = s.world_state().unwrap(); + let body = world.body("L").unwrap(); + let face = body + .body + .faces(0.01) + .unwrap() + .into_iter() + .find(|face| face.plane_normal.is_some_and(|n| n.dot(Vec3::Y) > 0.999) && (face.centroid.y - 12.0).abs() < 1e-6) + .unwrap(); + json!({"body":"L","index":face.index,"face":[face.centroid.x,face.centroid.y,face.centroid.z]}) + }; let before = s.doc.to_json(); let error = s.execute("sketch.create", &json!({"plane":pick})).unwrap_err(); assert!(error.to_string().contains("fixed"), "{error}"); @@ -163,7 +179,7 @@ fn exact_nested_source_and_cross_owner_pending_paths_capture_only_involved_posit run(&mut s, "occurrence.move", json!({"occurrence":unrelated["occurrence"],"translate":[300,0,0],"capture":false})); let author = run(&mut s, "component.create", json!({"name":"Author","parent":0})); run(&mut s, "occurrence.move", json!({"occurrence":author["occurrence"],"translate":[100,0,0],"angle":"90 deg","capture":false})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let key = s .placed_document() .body_frames_with_source(&s.model.state()) @@ -353,6 +369,10 @@ fn freezing_rebuilt_arc_borders_keeps_authored_dimension_entity_indices() { run(&mut s, "sketch.line", json!({"points":[format!("{arc}.end"),format!("{arc}.start")],"infer":false})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch":profile,"distance":10,"operation":"new","body_name":"Sector"})); + // A notch clear of the sector until `notch` moves it across the arc at 90°: then the top face's + // arc border is rebuilt in two arcs and the notch's sides. + run(&mut s, "parameters.add", json!({"name":"notch","expression":"30 mm"})); + run(&mut s, "solid.box", json!({"corner":["-1 mm","notch","-1 mm"],"length":2,"width":2,"height":12,"operation":"cut","targets":["Sector"]})); let pick = top_pick(&s, "Sector"); let id = run(&mut s, "sketch.create", json!({"plane":pick}))["sketch"].as_u64().unwrap(); let circle = run(&mut s, "sketch.circle.center", json!({"center":[20,20],"radius":2}))["curves"][0].as_str().unwrap().to_owned(); @@ -360,7 +380,8 @@ fn freezing_rebuilt_arc_borders_keeps_authored_dimension_entity_indices() { run(&mut s, "sketch.finish", json!({})); let before_count = s.model.state().sketch(id).unwrap().sketch.curves.len(); run(&mut s, "parameters.change", json!({"name":"turn","expression":"300 deg"})); - assert!(s.model.result(id).unwrap().error.is_none()); + run(&mut s, "parameters.change", json!({"name":"notch","expression":"9 mm"})); + assert!(s.model.result(id).unwrap().error.is_none(), "{:?}", s.model.result(id).unwrap().error); let visible = s.model.state().sketch(id).unwrap().sketch.clone(); assert_ne!(visible.curves.len(), before_count, "fixture must rebuild projected topology"); let mut pick = top_pick(&s, "Sector"); @@ -487,7 +508,7 @@ fn rounded_enclosure_shell_side_and_floor_attach_through_width_wall_and_reopen() assert!((state.sketch(side).unwrap().plane.origin.x - 50.).abs() < 1e-6); assert!((state.sketch(floor).unwrap().plane.origin.z - 3.).abs() < 1e-6); assert!(state.sketch(floor).unwrap().plane.normal().dot(Vec3::Z) > 0.999); - let mesh = state.body("Case").unwrap().body.tessellate_with(1e-4, true).unwrap(); + let mesh = state.body("Case").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap(); let case = &state.body("Case").unwrap().body; let corners: Vec<_> = (0..case.face_count()).filter(|i| matches!(solidcraft_kernel::face_surface(case, *i), Some(solidcraft_kernel::FaceSurface::Cylinder { radius, .. }) if (radius - 6.).abs() < 1e-6)).collect(); assert_eq!(corners.len(), 4, "later port/boss features must not subdivide untouched outer corners"); @@ -506,7 +527,7 @@ fn rounded_enclosure_shell_side_and_floor_attach_through_width_wall_and_reopen() assert!(!mesh.contains(Vec3::new(49., 0., 12.)), "USB must remain open after resize/reopen"); assert!(mesh.contains(Vec3::new(49., 15., 12.)), "adjacent right wall remains solid"); assert!(mesh.contains(Vec3::new(-49., 0., 12.)), "opposite wall must stay solid"); - let seed = state.sketch(floor).unwrap().plane.to_world(solidcraft_geom::Vec2::new(40., 20.)) + Vec3::Z * 6.; + let seed = state.sketch(floor).unwrap().plane.to_world(solidcore_record::Vec2::new(40., 20.)) + Vec3::Z * 6.; assert!(mesh.contains(seed), "seed boss starts on current floor"); for shift in [Vec3::ZERO, Vec3::new(-80., 0., 0.), Vec3::new(0., -40., 0.), Vec3::new(-80., -40., 0.)] { assert!(mesh.contains(seed + shift), "each patterned boss must survive resize/reopen at {:?}", seed + shift); @@ -552,7 +573,7 @@ fn offset_rectangle_pocket_has_one_logical_outer_wall_and_closed_face_projection assert_eq!(solidcraft_kernel::step_export(&[&control], "control snapshot").unwrap(), before_control); let state = s.model.state(); let body = state.body("Stock").unwrap(); - let display = body.body.display_mesh(0.01).unwrap(); + let display = body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); let face = body .body .faces(0.01) @@ -573,14 +594,14 @@ fn offset_rectangle_pocket_has_one_logical_outer_wall_and_closed_face_projection let sketch = &state.sketch(attached).unwrap().sketch; assert!(sketch.links.iter().all(|link| !link.lost)); assert_eq!(sketch.curves.len(), 4, "whole outer-wall rectangle has no floor-height stations"); - let mesh = state.body("Stock").unwrap().body.display_mesh(0.01).unwrap(); + let mesh = state.body("Stock").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); assert!(mesh.contains(Vec3::new(0., 0., 0.5))); assert!(!mesh.contains(Vec3::new(0., 0., 5.))); assert!(mesh.contains(Vec3::new(28., 0., 5.))); let control = &state.body("Control").unwrap().body; assert_eq!(control.faces(0.01).unwrap().len(), 6); assert_eq!(control.edges(0.01).unwrap().len(), 12); - let control_mesh = control.tessellate(0.01).unwrap(); + let control_mesh = control.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); assert!((control_mesh.measure().volume - 160.).abs() < 1e-6); assert!(control_mesh.contains(Vec3::new(102., 102., 0.5))); assert!(control_mesh.contains(Vec3::new(102., 102., 5.))); @@ -592,7 +613,7 @@ fn offset_rectangle_pocket_has_one_logical_outer_wall_and_closed_face_projection /// Every flat face of every body: (body, face index, a point well inside it, its normal). The /// middle of the face's largest triangle, so an L-shaped face is picked on itself. fn flat_faces(s: &Session) -> Vec<(String, usize, Vec3, Vec3)> { - let world = s.world_state(); + let world = s.world_state().unwrap(); let mut out = Vec::new(); for body in &world.bodies { let mesh = body.mesh(); @@ -673,7 +694,7 @@ fn every_flat_face_of_one_sketch_extruded_up_and_down_takes_an_attached_sketch() let script: Value = serde_json::from_str(&std::fs::read_to_string(root.join("up-down-join.json")).unwrap()).unwrap(); let mut s = Session::default(); s.run_script(&script).unwrap(); - assert_eq!(s.world_state().bodies.len(), 1, "the two extrudes join into one body"); + assert_eq!(s.world_state().unwrap().bodies.len(), 1, "the two extrudes join into one body"); assert_eq!(sketch_and_extrude_on_every_flat_face(&s, &dir, "synthetic"), 12, "8 side walls, top, bottom, 2 at the sketch plane"); let reopened = save_and_reopen(&mut s, &dir, "synthetic.solidcraft"); assert_eq!(sketch_and_extrude_on_every_flat_face(&reopened, &dir, "synthetic-reopened"), 12); @@ -744,17 +765,29 @@ fn a_sketch_on_a_face_meshes_its_body_once() { assert!(s.model.state().body("Base").unwrap().cached_mesh().is_some(), "the sketch's projection meshed a copy of the body"); } /// Issue 6720: a face picked by its point alone was refused on a body with many faces. The -/// search charged the whole mesh once per face, and the 5 000 facets a modelled thread leaves -/// put a plain block past the limit. The search reads each face's own triangles now. +/// search charged the whole mesh once per face, and the 5 000 facets a modelled thread left put a +/// plain block past the limit. The search reads each face's own triangles now. A modelled thread +/// is a few exact helical faces on SMLib, so the many faces are a block drilled with 256 holes: +/// the old charge (every face times the whole mesh) is past the 2 000 000 budget, the new one +/// (the mesh once, plus a test per face) well inside it. #[test] -fn a_face_picked_by_point_on_a_block_with_a_modelled_thread_is_found() { +fn a_face_picked_by_point_on_a_block_with_many_faces_is_found() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"corner":[-20,-20,0],"length":40,"width":40,"height":20,"body_name":"Block"})); - run(&mut s, "solid.cylinder", json!({"base":[0,0,-1],"radius":3.4,"height":22,"body_name":"Bore"})); - run(&mut s, "solid.combine", json!({"target":"Block","tools":["Bore"],"operation":"cut"})); - run(&mut s, "solid.thread", json!({"face":[3.4,0,10],"designation":"M8","modeled":true})); - assert!(s.model.state().body("Block").unwrap().body.face_count() > 1000); - run(&mut s, "sketch.create", json!({"plane":{"face":[15,15,20],"fixed":true}})); + run(&mut s, "sketch.create", json!({"plane":"XY","offset":20,"name":"Drills"})); + for i in 0..16 { + for j in 0..16 { + run(&mut s, "sketch.point", json!({"point":[-15.0 + 2.0 * f64::from(i), -15.0 + 2.0 * f64::from(j)]})); + } + } + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.hole", json!({"sketch":"Drills","diameter":0.8})); + let body = s.model.state().body("Block").unwrap().body.clone(); + // The search's own mesh (sketch_face: the tolerance it meshes the body at). + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord((body.size() * 1e-4).max(1e-5))).unwrap(); + let (faces, triangles) = (body.face_count(), mesh.triangles.len()); + assert!(faces > 256 && faces * triangles > 2_000_000 && faces + triangles < 2_000_000, "{faces} faces, {triangles} triangles"); + run(&mut s, "sketch.create", json!({"plane":{"face":[19,19,20],"fixed":true}})); let plane = run(&mut s, "sketch.inspect", json!({}))["plane"].clone(); assert!((plane["origin"][2].as_f64().unwrap() - 20.0).abs() < 1e-6, "{plane}"); } @@ -767,7 +800,7 @@ fn a_sketch_on_the_mirrored_half_of_a_combined_body_sits_on_that_half() { run(&mut s, "solid.mirror", json!({"bodies":["Part"],"plane":"XY","combine":true,"name":"Mirror1"})); assert_eq!(s.model.state().bodies.len(), 1, "the mirror combined"); let pick = |s: &Session, normal: Vec3, point: Vec3| { - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.body("Part").unwrap(); let face = body .body @@ -792,3 +825,71 @@ fn a_sketch_on_the_mirrored_half_of_a_combined_body_sits_on_that_half() { assert!((plane.origin - point).dot(normal).abs() < 1e-6, "{name}: origin {:?}", plane.origin); } } +/// The sensor enclosure's lid rests on the case, and its lip, joined below it, parts its underside +/// into a ring and a panel. Where the join names the ring after the case's top it rests on, the +/// lid's cap certificate finds only the panel: the ring is another piece of the same face and takes +/// a sketch attached by that certificate, as it did before #8278 (#9465, nightly action matrix). +/// Where the join's history names it a piece of the lid's own start (SMLib), the certificate finds +/// it directly. Either way the ring is the underside piece under the pick, whatever its name. +#[test] +fn a_sketch_on_the_ring_of_a_lid_underside_parted_by_its_lip_keeps_the_cap() { + let mut s = Session::default(); + let script: Value = serde_json::from_str(include_str!("../../../../examples/acceptance/sensor_enclosure.json")).unwrap(); + s.run_script(&script).unwrap(); + let world = s.world_state().unwrap(); + let lid = world.body("Lid").unwrap(); + let names = solidcraft_doc::naming::face_names(lid); + let down: Vec = (0..names.len()) + .filter(|index| lid.body.planar_face(*index).is_some_and(|plane| plane.normal().dot(-Vec3::Z) > 0.999 && (plane.origin.z - 25.).abs() < 1e-6)) + .collect(); + assert!(down.len() > 1, "the lip parts the lid's underside: {down:?}"); + let at = Vec3::new(12.0, 29.266_666_666_665, 25.0); + let under = solidcraft_doc::naming::face_name_at_body(lid, at); + let ring = *down.iter().find(|index| under.as_ref() == Some(&names[**index])).unwrap_or_else(|| panic!("the ring ({under:?}), among {names:?}")); + let pick = json!({"body":"Lid","index":ring,"face":[at.x, at.y, at.z]}); + drop(world); + let id = run(&mut s, "sketch.create", json!({"name":"On ring","plane":pick,"project_edges":false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.finish", json!({})); + let plane = s.model.state().sketch(id).unwrap().plane; + assert!(plane.normal().dot(-Vec3::Z) > 0.999 && (plane.origin.z - 25.).abs() < 1e-6, "{plane:?}"); + // The attachment survives an edit that widens the lid. + run(&mut s, "parameters.change", json!({"name": "board_w", "expression": "(60 mm) * 1.1"})); + assert!(timeline_errors(&s).is_empty(), "{:?}", timeline_errors(&s)); + let plane = s.model.state().sketch(id).unwrap().plane; + assert!(plane.normal().dot(-Vec3::Z) > 0.999 && (plane.origin.z - 25.).abs() < 1e-6, "{plane:?}"); +} + +/// `activate_part` (#10215): a sketch on a face of another component's body is made in that +/// component, which stays active; without it the sketch belongs to the active component. +#[test] +fn activate_part_makes_the_sketch_in_the_faces_component() { + for activate in [true, false] { + let mut s = Session::default(); + let part = run(&mut s, "component.create", json!({"name":"Part","parent":0,"grounded":false})); + let (component, occurrence) = (part["component"].as_u64().unwrap(), part["occurrence"].as_u64().unwrap()); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Base"})); + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0]})); + run(&mut s, "component.activate", json!({"component":0})); + let mut pick = top_pick(&s, "Base"); + pick["path"] = json!([occurrence]); + let out = run(&mut s, "sketch.create", json!({"name":"OnFace","plane":pick,"activate_part":activate,"project_edges":false})); + let id = out["sketch"].as_u64().unwrap(); + let owner = s.doc.feature(id).unwrap().component; + if activate { + assert_eq!(owner, component); + assert_eq!((s.active_component, s.active_occurrence_path.clone()), (component, Some(vec![occurrence]))); + assert_eq!(out["activated"], json!({"component": component, "path": [occurrence]})); + let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &s.doc.feature(id).unwrap().kind else { panic!("not sketch") }; + assert_eq!(super::anchor(plane).unwrap().author_path, vec![occurrence]); + } else { + assert_eq!(owner, 0); + assert_eq!(s.active_component, 0); + assert!(out.get("activated").is_none()); + } + let world = s.world_state().unwrap(); + let plane = world.sketch(id).unwrap().plane; + assert!((plane.origin.z - 10.).abs() < 1e-6 && plane.normal().z > 1. - 1e-9, "{activate}: {plane:?}"); + draw(&mut s); + assert!(s.model.result(id).unwrap().error.is_none()); + } +} diff --git a/crates/engine/src/cmd/sketch_flip_tests.rs b/crates/engine/src/cmd/sketch_flip_tests.rs index 2385cb743..0c6a07584 100644 --- a/crates/engine/src/cmd/sketch_flip_tests.rs +++ b/crates/engine/src/cmd/sketch_flip_tests.rs @@ -2,8 +2,9 @@ //! sketch keeps the plane's own side, and older designs open, rebuild and save as before. use serde_json::{Value, json}; +use solidcore_record::{Plane, Vec2, Vec3}; use solidcraft_doc::{FeatureKind, PlaneRef}; -use solidcraft_geom::{Plane, Vec3}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -26,6 +27,20 @@ fn close(a: Vec3, b: Vec3) -> bool { a.dist(b) < 1e-9 } +/// The origin planes' sketch axes, as `sketch.create` documents them: sketch x and y run along world +X, +Y on XY; +/// +X, -Z on XZ; +Y, +Z on YZ. +#[test] +fn origin_planes_put_the_sketch_axes_where_sketch_create_says() { + let (x, y, z) = (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)); + for (name, u, v) in [("XY", x, y), ("XZ", x, z * -1.0), ("YZ", y, z)] { + let mut s = Session::default(); + let id = run(&mut s, "sketch.create", json!({"plane": name}))["sketch"].as_u64().unwrap(); + let p = sketch_plane(&s, id); + let (su, sv) = (p.to_world(Vec2::new(1.0, 0.0)), p.to_world(Vec2::new(0.0, 1.0))); + assert!(close(su, u) && close(sv, v), "{name}: sketch x lands on {su:?}, sketch y on {sv:?}"); + } +} + #[test] fn without_flip_a_sketch_keeps_the_planes_own_side_and_saves_as_before() { for name in ["XY", "XZ", "YZ"] { diff --git a/crates/engine/src/cmd/sketch_freeform.rs b/crates/engine/src/cmd/sketch_freeform.rs index 6d8763a33..03710ddc2 100644 --- a/crates/engine/src/cmd/sketch_freeform.rs +++ b/crates/engine/src/cmd/sketch_freeform.rs @@ -3,7 +3,8 @@ //! stays exact; the pieces replace the original curve. use serde_json::{Value, json}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch}; use super::sketch::add_c; @@ -156,20 +157,20 @@ fn add_pieces(sk: &mut Sketch, segs: &[Seg2], start: Option, end: Option< Seg2::Line { .. } => CurveKind::Line { a: prev, b: to }, Seg2::Cubic { p1, p2, .. } => { let (c1, c2) = (sk.add_point(p1, None)?, sk.add_point(p2, None)?); - CurveKind::Spline { pts: vec![prev, c1, c2, to], control: true, degree: 3, periodic: false } + CurveKind::Spline { pts: vec![prev, c1, c2, to], control: true, degree: 3, periodic: false, nurbs: None } } Seg2::Conic { apex, w, .. } => { let x = sk.add_point(apex, None)?; CurveKind::Conic { a: prev, b: to, apex: x, rho: w / (1.0 + w) } } Seg2::Bezier { n, p } => { - let k = (n as usize).clamp(1, solidcraft_geom::MAX_BEZIER_DEGREE); + let k = (n as usize).clamp(1, solidcore_record::MAX_BEZIER_DEGREE); let mut pts = vec![prev]; for q in p.iter().take(k).skip(1) { pts.push(sk.add_point(*q, None)?); } pts.push(to); - CurveKind::Spline { pts, control: true, degree: n, periodic: false } + CurveKind::Spline { pts, control: true, degree: n, periodic: false, nurbs: None } } Seg2::Arc { .. } => return Err(bad("trim", "unexpected arc piece")), }; diff --git a/crates/engine/src/cmd/sketch_ids_tests.rs b/crates/engine/src/cmd/sketch_ids_tests.rs index cb3d61cb5..1297ae368 100644 --- a/crates/engine/src/cmd/sketch_ids_tests.rs +++ b/crates/engine/src/cmd/sketch_ids_tests.rs @@ -353,3 +353,68 @@ fn conic_curves_take_the_n_prefix_not_the_constraints_k() { assert!(id.starts_with('n'), "a pattern copy keeps the conic prefix: {id}"); } } + +/// A curve id goes into the face names of the features that use the curve, so an id with a +/// character the name grammar reads (`|`, `,`, `~`, `]`, `#`) would split every name it +/// lands in: an id of `c|1` gave the edges of an extrusion the names +/// `F2:side:c|1#1|F2:side:c|1#2~1`, three separators where an edge has two faces and one +/// separator. An id that cannot be written into a name whole is refused instead (#5858). +#[test] +fn a_curve_id_that_cannot_be_written_into_a_name_is_refused() { + let mut s = new_sketch(); + for id in ["c|1", "c,1", "c~1", "c]1", "c#1"] { + let p = json!({"center": [0, 0], "radius": 5, "id": id}); + let e = match s.execute("sketch.circle.center", &p) { + Ok(v) => panic!("the id `{id}` was taken: {v:?}"), + Err(e) => e.to_string(), + }; + assert!(e.contains(id), "the error names the id: {e}"); + } + // The id that can be written into a name is still taken, and the faces it makes are + // named with it whole. + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5, "id": "c1"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 10})); + let edges = run(&mut s, "model.edges", json!({"body": "Body1"})); + let listed: Vec = edges["edges"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str().map(str::to_string)).collect(); + assert!(!listed.is_empty(), "{edges}"); + // Every edge names each face it bounds once, whole, separated by one `|` each: two faces + // where it separates two (the rims), one where both its sides are the same face (the side's + // seam, on a kernel that keeps the side whole). The id is never cut. + let world = s.world_state().unwrap(); + let body = world.body("Body1").unwrap(); + let faces = solidcraft_doc::naming::face_names(body); + let names = solidcraft_doc::naming::edge_names(body); + let mesh = body.mesh(); + assert_eq!(names.len(), mesh.edge_faces.len()); + let mut sorted = names.clone(); + sorted.sort(); + let mut shown = listed.clone(); + shown.sort(); + assert_eq!(sorted, shown, "model.edges lists the body's edge names"); + assert!(faces.iter().any(|f| f == "F2:side:c1" || f.starts_with("F2:side:c1#")), "the side is named with the id whole: {faces:?}"); + let mut rims = 0; + for ((name, between), points) in names.iter().zip(&mesh.edge_faces).zip(&mesh.edges) { + let whole = name.rsplit_once('~').filter(|(_, k)| k.parse::().is_ok()).map_or(name.as_str(), |(n, _)| n); + let parts: Vec<&str> = whole.split('|').collect(); + let own: Vec<&str> = between.iter().map(|f| faces[*f as usize].as_str()).collect(); + assert_eq!(parts.len(), own.len(), "an edge names each face it bounds, separated once each: {name}"); + for part in &parts { + assert!(own.contains(part), "`{part}` of {name} is a whole face name among {own:?}"); + } + match own.as_slice() { + [_, _] => rims += 1, + [side] => { + // A seam: along the side from the bottom to the top, at one place on the circle. + assert!(side.starts_with("F2:side:c1"), "only the side has a seam: {name}"); + let (Some(a), Some(b)) = (points.first(), points.last()) else { panic!("an empty edge: {name}") }; + assert!( + (a.z - b.z).abs() > 9.999 && (a.x - b.x).hypot(a.y - b.y) < 1e-6 && (a.x.hypot(a.y) - 5.).abs() < 1e-6, + "{name}: {a:?} {b:?}" + ); + } + other => panic!("{name} bounds {other:?}"), + } + } + assert!(rims >= 2, "the top and bottom rims: {names:?}"); +} diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs index dc6a8c77a..1ef7b0505 100644 --- a/crates/engine/src/cmd/sketch_import.rs +++ b/crates/engine/src/cmd/sketch_import.rs @@ -1,9 +1,10 @@ //! Sketch drawing exchange: Insert DXF, Insert SVG and sketch DXF export. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_io::{Geom2, MAX_DRAWING_BYTES}; use solidcraft_sketch::{CurveKind, LinkKind, LinkSource, Sketch}; @@ -43,7 +44,7 @@ pub fn drawing_import_command(path: &str) -> Option<&'static str> { } } -fn source_text(p: &Value, cmd: &str) -> Result { +fn source_text(p: &Value, cmd: &str, svg: bool) -> Result { if let Some(t) = str_(p, "text") { if t.len() > MAX_DRAWING_BYTES { return Err(bad(cmd, "the drawing is too large")); @@ -52,9 +53,22 @@ fn source_text(p: &Value, cmd: &str) -> Result { } let path = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "give `path` or `text`"))?; let bytes = solidcraft_io::vfs::read(path, MAX_DRAWING_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + if svg { + return solidcraft_io::decode_svg(&bytes).map_err(|e| drawing_error(p, svg, e.to_string())); + } Ok(String::from_utf8_lossy(&bytes).to_string()) } +/// A problem with the drawing file's contents (not with the command's parameters), named after +/// the file so the message says which drawing it is about (#9641). +fn drawing_error(p: &Value, svg: bool, msg: String) -> EngineError { + let name = str_(p, "path") + .and_then(|x| std::path::Path::new(x).file_name()) + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| if svg { "SVG" } else { "DXF" }.to_string()); + EngineError::Other(format!("{name}: {msg}")) +} + /// Add imported geometry to a sketch, sharing end points that meet. /// Adds the geometry; end points closer than `q` (mm) become one point, so drawings whose /// ends almost meet still make closed profiles. @@ -102,7 +116,7 @@ pub(super) fn add_geometry(sk: &mut Sketch, geom: &[Geom2], f: &dyn Fn(Vec2) -> idx.push(i); } } - (idx.len() >= 2).then_some(CurveKind::Spline { pts: idx, control: *control, degree: *degree, periodic: false }) + (idx.len() >= 2).then_some(CurveKind::Spline { pts: idx, control: *control, degree: *degree, periodic: false, nurbs: None }) } Geom2::Conic { a, apex, b, rho } => { let (a, x, b) = (pt(sk, *a)?, pt(sk, *apex)?, pt(sk, *b)?); @@ -156,7 +170,7 @@ fn bounds_of(geom: &[Geom2]) -> Option<(Vec2, Vec2)> { // Points along the curve, not its apex, which can lie well outside it (an elliptical // arc of a DXF comes in as conics, #8155). Geom2::Conic { a, apex, b, rho } if *rho > 0.0 && *rho < 1.0 => { - let seg = solidcraft_geom::Seg2::Conic { a: *a, apex: *apex, b: *b, w: rho / (1.0 - rho) }; + let seg = solidcore_record::Seg2::Conic { a: *a, apex: *apex, b: *b, w: rho / (1.0 - rho) }; pts.extend((0..=64).map(|i| seg.point_at(f64::from(i) / 64.0))); } Geom2::Conic { a, apex, b, .. } => pts.extend([*a, *apex, *b]), @@ -168,9 +182,16 @@ fn bounds_of(geom: &[Geom2]) -> Option<(Vec2, Vec2)> { (lo.x.is_finite() && lo.y.is_finite() && hi.x.is_finite() && hi.y.is_finite()).then_some((lo, hi)) } -fn read_drawing(p: &Value, cmd: &str, svg: bool) -> Result> { - let text = source_text(p, cmd)?; - if svg { solidcraft_io::read_svg(&text) } else { solidcraft_io::read_dxf(&text) }.map_err(|e| bad(cmd, e.to_string())) +/// The drawing's geometry and the box around it; a drawing with none is an error that says why +/// (#9641). +fn read_drawing(p: &Value, cmd: &str, svg: bool) -> Result<(Vec, (Vec2, Vec2))> { + let text = source_text(p, cmd, svg)?; + let geom = if svg { solidcraft_io::read_svg(&text) } else { solidcraft_io::read_dxf(&text) }.map_err(|e| drawing_error(p, svg, e.to_string()))?; + let Some(bounds) = bounds_of(&geom) else { + let why = if svg { solidcraft_io::svg_nothing_to_import(&text) } else { "the DXF has no entities SolidCraft reads".to_string() }; + return Err(drawing_error(p, svg, why)); + }; + Ok((geom, bounds)) } /// How big a drawing is in its own file, to size it before it is inserted. @@ -181,22 +202,18 @@ fn drawing_bounds(_s: &mut Session, p: &Value) -> Result { Some(f) => !f.eq_ignore_ascii_case("dxf"), None => !name_is_dxf, }; - let geom = read_drawing(p, cmd, svg)?; - let (lo, hi) = bounds_of(&geom).ok_or_else(|| bad(cmd, "the drawing has no geometry SolidCraft reads"))?; + let (_, (lo, hi)) = read_drawing(p, cmd, svg)?; Ok(json!({"min": [lo.x, lo.y], "max": [hi.x, hi.y], "width": hi.x - lo.x, "height": hi.y - lo.y})) } fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { - let geom = read_drawing(p, cmd, svg)?; - if geom.is_empty() { - return Err(bad(cmd, "the drawing has no geometry SolidCraft reads")); - } + let (geom, (lo, hi)) = read_drawing(p, cmd, svg)?; // A size in millimetres wins over a factor; the aspect ratio is always kept. - let natural = bounds_of(&geom).map(|(lo, hi)| (hi.x - lo.x, hi.y - lo.y)); + let natural = (hi.x - lo.x, hi.y - lo.y); let sized = |key: &str, of: fn(&(f64, f64)) -> f64| -> Result> { let Some(v) = p.get(key) else { return Ok(None) }; let want = v.as_f64().filter(|w| w.is_finite() && *w > 0.0).ok_or_else(|| bad(cmd, format!("`{key}` must be a positive number (mm)")))?; - let have = natural.as_ref().map(of).filter(|h| *h > 1e-9).ok_or_else(|| bad(cmd, format!("the drawing has no {key} to size")))?; + let have = Some(of(&natural)).filter(|h| *h > 1e-9).ok_or_else(|| bad(cmd, format!("the drawing has no {key} to size")))?; Ok(Some(want / have)) }; let from_size = match sized("width", |n| n.0)? { @@ -211,7 +228,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { let (sin, cos) = angle.sin_cos(); let pivot = match str_(p, "align") { None | Some("origin") => Vec2::ZERO, - Some("center") => bounds_of(&geom).map(|(lo, hi)| (lo + hi) * 0.5).unwrap_or(Vec2::ZERO), + Some("center") => (lo + hi) * 0.5, Some(_) => return Err(bad(cmd, "`align` must be \"origin\" or \"center\"")), }; let off = p.get("at").and_then(vec2).unwrap_or(Vec2::ZERO); @@ -229,6 +246,11 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { let v = (q - pivot) * k; Vec2::new(v.x * cos - v.y * sin, v.x * sin + v.y * cos) + off }; + // A dense SVG/DXF (a floorplan) can yield far more entities than a sketch takes; refuse + // before adding so the message names the cap (#10874). Scale alone does not shrink the count. + if geom.len() > solidcraft_sketch::MAX_POINTS { + return Err(solidcraft_sketch::SketchError::TooLarge.into()); + } let ((curves, texts), info) = edit(s, p, cmd, false, |sk, _| { let (cs, texts) = add_geometry(sk, &geom, &f, k, tol)?; Ok((ids_of(sk, &cs), texts)) @@ -355,6 +377,49 @@ mod tests { } } + /// #10874: a drawing with more entities than a sketch can hold is refused with the point + /// cap and that scale alone does not help (a floorplan SVG often hits this). + #[test] + fn a_drawing_with_too_many_entities_names_the_sketch_cap() { + let n = solidcraft_sketch::MAX_POINTS + 1; + let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n"); + for i in 0..n { + dxf.push_str(&format!("0\nLINE\n10\n{i}\n20\n0\n11\n{}\n21\n1\n", i + 1)); + } + dxf.push_str("0\nENDSEC\n0\nEOF\n"); + let mut s = Session::default(); + let e = s.execute("sketch.insert_dxf", &json!({"text": dxf})).unwrap_err().to_string(); + assert!(e.contains("20000") && e.contains("scale"), "{e}"); + assert!(s.active_sketch.is_none(), "a refused insert leaves no empty sketch behind"); + } + + /// #9641: an SVG with nothing SolidCraft can draw (here only an embedded picture) is refused + /// with a message naming the file and saying why, not "invalid parameters … no geometry"; a + /// UTF-16 SVG file inserts. + #[test] + fn an_svg_with_nothing_to_import_says_why() { + let dir = std::env::temp_dir().join(format!("solidcraft-9641-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let picture = dir.join("logo.svg"); + std::fs::write( + &picture, + r#""#, + ) + .unwrap(); + let mut s = Session::default(); + for cmd in ["sketch.insert_svg", "sketch.drawing_bounds"] { + let e = s.execute(cmd, &json!({"path": picture.to_string_lossy(), "align": "center"})).unwrap_err().to_string(); + assert!(e.starts_with("logo.svg: ") && e.contains("embedded picture") && !e.contains("invalid parameters"), "{cmd}: {e}"); + } + assert!(s.active_sketch.is_none(), "a refused insert leaves no empty sketch behind"); + let square = r#""#; + let utf16 = dir.join("square.svg"); + std::fs::write(&utf16, [0xFF, 0xFE].into_iter().chain(square.encode_utf16().flat_map(u16::to_le_bytes)).collect::>()).unwrap(); + let r = s.execute("sketch.insert_svg", &json!({"path": utf16.to_string_lossy()})).unwrap(); + assert_eq!(r["curves"], 4, "{r}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// #8155: an elliptical arc of a DXF (as Fusion writes one) comes into the sketch as exact /// conics, and the drawing's size is the arc's own, not the box round the conics' apexes. #[test] diff --git a/crates/engine/src/cmd/sketch_infinite_tests.rs b/crates/engine/src/cmd/sketch_infinite_tests.rs index 85f30fb00..e0c53eb9f 100644 --- a/crates/engine/src/cmd/sketch_infinite_tests.rs +++ b/crates/engine/src/cmd/sketch_infinite_tests.rs @@ -3,7 +3,8 @@ //! profile. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{CurveKind, Sketch}; use crate::Session; @@ -29,6 +30,44 @@ fn new_sketch() -> Session { s } +#[test] +fn a_short_horizontal_reference_holds_through_dimension_edits_drag_and_reopen() { + let mut s = new_sketch(); + let id = s.active_sketch.unwrap(); + // A saved infinite line may have very close defining points (#11001). + let sk = s.doc_mut().sketch_mut(id).unwrap(); + let end = sk.add_point(Vec2::new(6.36e-8, 0.0), Some("axis.end")).unwrap(); + let arm_end = sk.add_point(Vec2::new(12.0, 10.0), Some("arm.end")).unwrap(); + let axis = sk.add_line_pts(0, end, Some("axis")).unwrap(); + sk.curves[axis].infinite = true; + sk.curves[axis].construction = true; + sk.add_line_pts(0, arm_end, Some("arm")).unwrap(); + sk.add_constraint(solidcraft_sketch::ConstraintKind::Horizontal { l: axis }, None).unwrap(); + s.refresh(); + + let check = |s: &Session, degrees: f64| { + let state = s.model.state(); + let solved = state.sketch(id).unwrap(); + assert!(solved.report.ok(), "{:?}", solved.report); + let axis = solved.sketch.points[end].pos.normalized().unwrap(); + let arm = solved.sketch.points[arm_end].pos.normalized().unwrap(); + assert!(axis.dist(Vec2::X) < 1e-6, "the horizontal reference rotated: {axis:?}"); + assert!((arm.y.atan2(arm.x) - degrees.to_radians()).abs() < 1e-6, "the free line has the wrong angle: {arm:?}"); + }; + let out = run(&mut s, "sketch.dimension", json!({"entities": ["axis", "arm"], "type": "angle", "value": "30 deg"})); + check(&s, 30.0); + run(&mut s, "parameters.change", json!({"name": out["param"], "expression": "15 deg"})); + check(&s, 15.0); + let at = sketch(&s).points[arm_end].pos; + run(&mut s, "sketch.drag", json!({"entity": "arm.end", "from": [at.x, at.y], "to": [14, 10]})); + run(&mut s, "sketch.drag_end", json!({})); + check(&s, 15.0); + let doc = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + *s.doc_mut() = doc; + s.refresh(); + check(&s, 15.0); +} + fn profiles(s: &Session) -> usize { s.model.state().sketch(s.active_sketch.unwrap()).unwrap().profiles.len() } @@ -57,6 +96,87 @@ fn construction_line_methods_make_infinite_lines_with_direction_constraints() { assert!(s.execute("sketch.construction_line", &json!({"mode": "parallel", "at": [0, 0], "curve": "missing"})).is_err()); } +#[test] +fn construction_lines_with_a_length_are_segments_held_by_a_dimension() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [3, 4]], "ids": ["reference"], "infer": false})); + for (mode, near, expected) in [ + ("horizontal", json!([20, 10]), Vec2::new(1.0, 0.0)), + ("horizontal", json!([0, 10]), Vec2::new(-1.0, 0.0)), + ("vertical", json!([10, 0]), Vec2::new(0.0, -1.0)), + ("angle", json!([20, 20]), Vec2::new(0.5, 3.0_f64.sqrt() / 2.0)), + ("parallel", json!([20, 20]), Vec2::new(0.6, 0.8)), + ("perpendicular", json!([0, 20]), Vec2::new(-0.8, 0.6)), + ] { + let p = json!({"mode": mode, "at": [10, 10], "curve": "reference", "angle": 60, "length": 25, "near": near}); + let out = run(&mut s, "sketch.construction_line", p); + let sk = sketch(&s); + let c = curve(&sk, out["curves"][0].as_str().unwrap()); + assert!(c.construction && !c.infinite, "{mode}: a construction segment"); + let CurveKind::Line { a, b } = c.kind else { panic!("expected a line") }; + let (a, b) = (sk.point(a).unwrap(), sk.point(b).unwrap()); + assert!(a.dist(Vec2::new(10.0, 10.0)) < 1e-6, "{mode}: starts at `at`"); + assert!(((b - a).len() - 25.0).abs() < 1e-6, "{mode}: {:?}", b - a); + assert!((b - a).normalized().unwrap().dist(expected) < 1e-6, "{mode} towards {near}: {:?}", b - a); + assert_eq!(out["constraints"].as_array().unwrap().len(), 2, "{mode}: direction and length"); + assert!( + sk.constraints.iter().any(|k| matches!(k.kind, solidcraft_sketch::ConstraintKind::Length { value, .. } if (value - 25.0).abs() < 1e-9)) + ); + } + // The length is a dimension: it follows its parameter, and the line keeps its direction. + run(&mut s, "parameters.add", json!({"name": "rib", "expression": "40 mm"})); + let out = run(&mut s, "sketch.construction_line.parallel", json!({"at": [0, 10], "curve": "reference", "length": "rib"})); + let id = out["curves"][0].as_str().unwrap().to_string(); + run(&mut s, "parameters.change", json!({"name": "rib", "expression": "15 mm"})); + let sk = sketch(&s); + let CurveKind::Line { a, b } = curve(&sk, &id).kind else { panic!("line") }; + let v = sk.point(b).unwrap() - sk.point(a).unwrap(); + assert!((v.len() - 15.0).abs() < 1e-6 && v.cross(Vec2::new(0.6, 0.8)).abs() < 1e-6, "{v:?}"); + // It is saved as a finite construction line. + let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + let c = curve(back.sketch(s.active_sketch.unwrap()).unwrap(), &id); + assert!(c.construction && !c.infinite); + // Refused, leaving the design as it was: bad lengths, and the methods without a start and + // direction of their own. + run(&mut s, "sketch.circle.center", json!({"center": [50, 0], "radius": 5, "id": "c"})); + for p in [ + json!({"mode": "horizontal", "at": [0, 0], "length": 0}), + json!({"mode": "horizontal", "at": [0, 0], "length": -3}), + json!({"mode": "horizontal", "at": [0, 0], "length": "nonsense +"}), + json!({"mode": "horizontal", "at": [0, 0], "length": true}), + json!({"at": [0, 0], "through": [5, 5], "length": 10}), + json!({"mode": "tangent_external", "at": [70, 0], "curve": "c", "length": 10}), + ] { + let before = s.doc.to_json(); + assert!(s.execute("sketch.construction_line", &p).is_err(), "{p}"); + assert_eq!(s.doc.to_json(), before, "{p}"); + } +} + +#[test] +fn a_construction_line_with_a_length_can_be_a_normal_line() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]})); + let p = json!({"at": [20, -10], "length": 40, "near": [20, 30]}); + let guide = run(&mut s, "sketch.construction_line.vertical", p.clone()); + assert!(curve(&sketch(&s), guide["curves"][0].as_str().unwrap()).construction); + assert_eq!(profiles(&s), 1, "by default it is construction geometry: no profile"); + let mut p = p; + p["construction"] = json!(false); + let out = run(&mut s, "sketch.construction_line.vertical", p); + let sk = sketch(&s); + let c = curve(&sk, out["curves"][0].as_str().unwrap()); + assert!(!c.construction && !c.infinite); + assert_eq!(profiles(&s), 2, "a normal line cuts the rectangle in two"); + let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert!(!curve(back.sketch(s.active_sketch.unwrap()).unwrap(), out["curves"][0].as_str().unwrap()).construction); + for p in [json!({"at": [0, 0], "construction": false}), json!({"at": [0, 0], "length": 5, "construction": "no"})] { + let before = s.doc.to_json(); + assert!(s.execute("sketch.construction_line.horizontal", &p).is_err(), "{p}"); + assert_eq!(s.doc.to_json(), before, "{p}"); + } +} + #[test] fn construction_angle_keeps_its_parameter_expression() { let mut s = new_sketch(); @@ -206,6 +326,25 @@ fn construction_tangents_respect_arc_sweeps_and_invalid_inputs_are_atomic() { } } +#[test] +fn a_second_point_next_to_the_first_is_refused() { + // #11001: a through-point 0.0000001 mm from the start made an infinite line whose direction + // Horizontal no longer held, and a line that short collapsed onto the origin. + let mut s = new_sketch(); + for (id, p) in [ + ("sketch.construction_line", json!({"at":[0,0],"through":[0.0000001,0]})), + ("sketch.construction_line", json!({"at":[5,5],"through":[5,5.0000005]})), + ("sketch.line", json!({"points":[[0,0],[0.0000001,0]]})), + ("sketch.line", json!({"points":[[5,5],[10,5],[10,5.0000005]]})), + ] { + let before = s.doc.to_json(); + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + assert_eq!(s.doc.to_json(), before, "{id} {p}"); + } + run(&mut s, "sketch.construction_line", json!({"at":[0,0],"through":[0.00001,0]})); + run(&mut s, "sketch.line", json!({"points":[[5,5],[5.00001,5]]})); +} + #[test] fn construction_relations_follow_source_edits_without_an_auxiliary_dimension() { let mut s = new_sketch(); diff --git a/crates/engine/src/cmd/sketch_inspect.rs b/crates/engine/src/cmd/sketch_inspect.rs index abe4d354d..743b75e96 100644 --- a/crates/engine/src/cmd/sketch_inspect.rs +++ b/crates/engine/src/cmd/sketch_inspect.rs @@ -1,34 +1,72 @@ //! Inspection: curvature combs and minimum radius on sketch curves, model edges and faces; //! centre of mass of bodies. -use serde_json::{Value, json}; -use solidcraft_geom::{Aabb3, Seg2, Vec2, Vec3}; +use serde_json::Value; +use solidcore_record::{Seg2, Vec2, Vec3}; +use solidcraft_geom::Aabb3; +use solidcraft_geom::prelude::*; use super::CommandSpec; -use crate::params::{bad, num, string_list, vec3}; -use crate::{EngineError, Result, Session}; +use crate::params::{bad, bool_, num, string_list, vec3}; +use crate::schema::sketch_inspect::{ + AnalysisCleared, BodyCenter, CenterOfMassParams, CentersOfMass, Comb, CurvatureCombParams, CurvatureCombReply, CurvatureCombs, IsoFace, + IsocurveParams, IsocurveReply, Isocurves, MAX_ISO_FACES, MinimumRadii, MinimumRadiusParams, RadiusItem, SkippedBody, +}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{CombPick, CombView, EngineError, Result, Session}; + +const COMB_CONTRACT: TypedContract = TypedContract::new(); +const RADIUS_CONTRACT: TypedContract = TypedContract::new(); +const ISOCURVE_CONTRACT: TypedContract = TypedContract::new(); +const CENTER_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("inspect.curvature_comb", "Curvature Comb Analysis", curvature_comb) + CommandSpec::new("inspect.curvature_comb", "Curvature Comb Analysis", crate::checked!("inspect.curvature_comb", curvature_comb)) .at("SKETCH", "INSPECT") .icon("curvature_comb") .noundo() - .params("curves?: [sketch curve ids] (sketch?: id|name, default active) | edges?: [[x,y,z] points on body edges] | faces?: [[x,y,z] points on faces] with count?: isoparametric curves each way (default 4; combs along the face's iso grid); density?: teeth per curve (default 40), scale?: comb length per unit curvature (default auto)"), - CommandSpec::new("inspect.minimum_radius", "Minimum Radius Analysis", minimum_radius) + .contract(&COMB_CONTRACT) + .output(output_schema_for::) + .params( + "curves?: [sketch curve ids] (sketch?: id|name, default active) | edges?: [[x,y,z] points on body edges: the edge whose \ + exact curve passes nearest] | faces?: [[x,y,z] points on faces] with count?: isoparametric curves each way (default 4; \ + combs along the face's iso grid); density?: teeth per curve, 2…2000 (default 40; on an edge or an iso curve exactly \ + that many, evenly spaced along its parameter); scale?: comb length per unit curvature (default auto: the longest \ + tooth a fifth of the combs' size); length?: a multiplier on the automatic scale, 0.01…100 (default 1; ignored with \ + `scale`); add?: true keeps the combs shown and adds these, every comb again at one scale (with nothing picked it \ + draws those shown again with this call's options, or turns the analysis on with none); clear?: true turns the \ + analysis off. Every comb of a call shares one scale, so tooth lengths compare across curves; the viewport draws \ + them. The curvature is exact: from each sketch curve, edge curve (line, circle, ellipse, B-spline, NURBS, \ + intersection curve) or face surface's own derivatives, never from the display mesh; a face's teeth are the \ + surface's normal curvature along each iso curve, along the surface normal. → combs: [{curve, teeth: [[foot, tip]], \ + envelope: [tip], max_curvature, min_radius}] (those shown, with `add`), scale", + ), + CommandSpec::new("inspect.minimum_radius", "Minimum Radius Analysis", crate::checked!("inspect.minimum_radius", minimum_radius)) .at("SKETCH", "INSPECT") .icon("min_radius") .noundo() + .contract(&RADIUS_CONTRACT) + .output(output_schema_for::) .params("curves?: [sketch curve ids] (sketch?) | edges?: [[x,y,z]…] | faces?: [[x,y,z]…] (default: every face of every body); the smallest radius of curvature of each and where it is"), - CommandSpec::new("inspect.isocurve", "Isocurve Analysis", isocurves) + CommandSpec::new("inspect.isocurve", "Isocurve Analysis", crate::checked!("inspect.isocurve", isocurves)) .at("SKETCH", "INSPECT") .icon("iso_analysis") .noundo() - .params("faces: [[x,y,z]…] points on faces; count?: curves each way (default 8): the faces' isoparametric curves"), - CommandSpec::new("inspect.center_of_mass", "Center of Mass", center_of_mass) + .contract(&ISOCURVE_CONTRACT) + .output(output_schema_for::) + .params( + "faces: [[x,y,z]…] points on faces (1…100); count?: whole number of curves each way, 1…100 (default 8); \ + add?: true keeps the faces already shown; clear?: true turns the analysis off. → each face's isoparametric \ + curves, u = const and v = const of its surface, evenly spaced across it and cut to its trims, as points \ + (`curves`) and per face (`faces`); the viewport draws them", + ), + CommandSpec::new("inspect.center_of_mass", "Center of Mass", crate::checked!("inspect.center_of_mass", center_of_mass)) .at("SKETCH", "INSPECT") .icon("center_of_mass") .noundo() - .params("bodies?: [names] (default all): the centre of mass (uniform density) of each and of all together"), + .contract(&CENTER_CONTRACT) + .output(output_schema_for::) + .params("bodies?: [names] (default all): the centre of mass (uniform density) of each and of all together, from the exact mass properties `inspect.measure` takes → center, volume, bodies: [{body, center, volume}], skipped: [{body, reason}] (bodies that enclose no volume or could not be measured)"), ]; /// Curvature (signed, 1/mm) and unit normal of a segment at `t`. @@ -56,56 +94,102 @@ fn teeth_2d(segs: &[Seg2], density: usize) -> Vec<(Vec2, f64, Vec2)> { out } -/// Teeth along a 3D polyline (discrete curvature from three consecutive points). -fn teeth_3d(pts: &[Vec3]) -> Vec<(Vec3, f64, Vec3)> { - let mut out = Vec::new(); - for w in pts.windows(3) { - let (a, b, c) = (w[0], w[1], w[2]); - let (ab, bc, ca) = (b - a, c - b, a - c); - let area2 = ab.cross(bc).len(); - let den = ab.len() * bc.len() * ca.len(); - let k = if den > 1e-300 { 2.0 * area2 / den } else { 0.0 }; - // Towards the centre of curvature. - let n = (a + c - b * 2.0).normalized().unwrap_or(Vec3::ZERO); - out.push((b, k, n)); - } - out +/// Teeth from the kernel's exact comb: (foot, curvature, unit normal towards the centre of +/// curvature; zero where straight). +fn teeth_exact(teeth: &[crate::kernel::CombTooth]) -> Vec<(Vec3, f64, Vec3)> { + teeth + .iter() + .map(|t| { + let k = t.curvature.len(); + (t.at, k, if k > 0.0 { t.curvature * (1.0 / k) } else { Vec3::ZERO }) + }) + .collect() } +/// The comb of the body edge whose exact curve passes nearest `at`, over the model's B-rep bodies +/// (mesh bodies have no curves): `density` exact teeth along it. +fn edge_teeth(st: &solidcraft_doc::ModelState, at: Vec3, density: usize) -> Result>> { + let mut best: Option<(f64, &solidcraft_doc::ModelBody, usize)> = None; + for b in st.bodies.iter().filter(|b| !b.body.is_mesh()) { + if let Some((d, edge)) = crate::kernel::comb_edge_near(&b.body, at)? + && best.is_none_or(|x| d < x.0) + { + best = Some((d, b, edge)); + } + } + match best { + Some((_, b, edge)) => Ok(Some(teeth_exact(&crate::kernel::edge_comb(&b.body, edge, density)?))), + None => Ok(None), + } +} + +/// Most curves Curvature Comb Analysis shows at once. +const MAX_COMB_PICKS: usize = 1000; + +/// The combs of one pick, each as (id, teeth (foot, curvature, unit normal)): one for a curve or +/// an edge, one per iso curve for a face. +fn pick_teeth(s: &Session, pick: &CombPick, density: usize) -> Result)>> { + let cmd = "inspect.curvature_comb"; + match pick { + CombPick::Curve { sketch, curve } => { + let st = s.model.state(); + let ss = st.sketch(*sketch).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; + let ci = ss.sketch.curve_index(curve).ok_or_else(|| bad(cmd, format!("unknown curve `{curve}`")))?; + let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)); + let teeth = teeth_2d(&segs, density).into_iter().map(|(q, k, n)| (ss.plane.to_world(q), k, ss.plane.dir_to_world(n))).collect(); + Ok(vec![(curve.clone(), teeth)]) + } + CombPick::Edge { at } => { + let teeth = edge_teeth(&s.model.state(), *at, density)?.ok_or_else(|| bad(cmd, "no edge there"))?; + Ok(vec![(format!("edge@{},{},{}", at.x, at.y, at.z), teeth)]) + } + CombPick::Face { at, count } => { + let world = s.world_state()?; + let (body, face) = iso_face_at(s, &world, *at).ok_or_else(|| bad(cmd, "no face there"))?; + let mut out = Vec::new(); + for (k, line) in body.iso_lines(face, *count)?.iter().enumerate() { + out.push((format!("face@{},{},{}#{k}", at.x, at.y, at.z), teeth_exact(&crate::kernel::iso_comb(&body.body, face, line, density)?))); + } + Ok(out) + } + } +} + +/// `inspect.curvature_comb`: the combs of the picked curves, edges and faces (with `add`, those +/// already shown too), all at one scale, kept so the viewport draws them. View state only. fn curvature_comb(s: &mut Session, p: &Value) -> Result { let cmd = "inspect.curvature_comb"; - let density = num(p, "density").map(|d| d.clamp(2.0, 2000.0) as usize).unwrap_or(40); - let st = s.model.state(); - let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new(); + if bool_(p, "clear").unwrap_or(false) { + s.comb = None; + s.revision += 1; + return reply( + cmd, + CurvatureCombReply::Cleared(AnalysisCleared { analysis: "curvature_comb".into(), cleared: true, param_warnings: Vec::new() }), + ); + } + let add = bool_(p, "add").unwrap_or(false); + let shown = if add { s.comb.clone() } else { None }; + let density = num(p, "density") + .filter(|d| d.is_finite()) + .map(|d| d.clamp(crate::kernel::MIN_COMB_TEETH as f64, crate::kernel::MAX_COMB_TEETH as f64) as usize) + .unwrap_or(shown.as_ref().map_or(40, |v| v.density)); + let length = match p.get("length") { + None | Some(Value::Null) => shown.as_ref().map_or(1.0, |v| v.length), + Some(v) => v.as_f64().filter(|x| (0.01..=100.0).contains(x)).ok_or_else(|| bad(cmd, "`length` must be a multiplier 0.01…100"))?, + }; + let fixed_scale = match p.get("scale") { + None | Some(Value::Null) => shown.as_ref().and_then(|v| v.fixed_scale), + Some(_) => num(p, "scale").filter(|x| x.is_finite() && *x > 0.0), + }; + let mut picks: Vec = Vec::new(); let curves = string_list(cmd, p, "curves")?; if !curves.is_empty() { let id = super::sketch_store::target(s, p, cmd)?; - let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; - for c in curves.iter().take(1000) { - let ci = ss.sketch.curve_index(c).ok_or_else(|| bad(cmd, format!("unknown curve `{c}`")))?; - let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)); - let teeth = teeth_2d(&segs, density).into_iter().map(|(q, k, n)| (ss.plane.to_world(q), k, ss.plane.dir_to_world(n))).collect(); - combs.push((c.clone(), teeth)); - } + picks.extend(curves.iter().take(MAX_COMB_PICKS).map(|c| CombPick::Curve { sketch: id, curve: c.clone() })); } if let Some(edges) = p.get("edges").and_then(Value::as_array) { - for e in edges.iter().take(1000) { - let at = vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))?; - let mut best: Option<(f64, Vec)> = None; - for b in &st.bodies { - let m = b.mesh(); - for (i, pts) in m.edges.iter().enumerate() { - if m.seams.get(i).copied().unwrap_or(false) { - continue; - } - let d = pts.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min); - if best.as_ref().is_none_or(|x| d < x.0) { - best = Some((d, pts.clone())); - } - } - } - let (_, pts) = best.ok_or_else(|| bad(cmd, "no edge there"))?; - combs.push((format!("edge@{},{},{}", at.x, at.y, at.z), teeth_3d(&pts))); + for e in edges.iter().take(MAX_COMB_PICKS) { + picks.push(CombPick::Edge { at: vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))? }); } } if let Some(faces) = p.get("faces") { @@ -117,38 +201,61 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result { } }; for v in faces.iter().take(100) { - let at = vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?; - let (bi, f) = face_at(&st, at).ok_or_else(|| bad(cmd, "no face there"))?; - let m = st.bodies.get(bi).map(|b| b.mesh()).ok_or_else(|| bad(cmd, "that face's body is not evaluated"))?; - for (k, w) in solidcraft_doc::iso_grid(&m, f, at, count).iter().enumerate() { - combs.push((format!("face@{},{},{}#{k}", at.x, at.y, at.z), teeth_3d(w))); - } + picks.push(CombPick::Face { at: vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?, count }); } } - if combs.is_empty() { + if picks.is_empty() && !add { return Err(bad(cmd, "give `curves`, `edges` or `faces`")); } + let shown_picks = shown.map(|v| v.picks).unwrap_or_default(); + if shown_picks.len() + picks.len() > MAX_COMB_PICKS { + return Err(bad(cmd, format!("at most {MAX_COMB_PICKS} curves can be combed at once"))); + } + // The curves shown are combed again with these options; one gone with a model change since + // (its sketch, edge or face no longer there) is dropped. A new pick must be there. + let mut kept: Vec = Vec::new(); + let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new(); + for pick in shown_picks { + if let Ok(teeth) = pick_teeth(s, &pick, density) { + combs.extend(teeth); + kept.push(pick); + } + } + for pick in picks { + combs.extend(pick_teeth(s, &pick, density)?); + kept.push(pick); + } // One scale for all combs: the longest tooth is a fifth of the largest curve's size. let kmax = combs.iter().flat_map(|c| c.1.iter().map(|t| t.1.abs())).fold(0.0_f64, f64::max); let bounds: Aabb3 = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).collect(); let diag = bounds.diagonal(); - let scale = - num(p, "scale").filter(|x| *x > 0.0).unwrap_or(if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 }); - let out: Vec = combs + let auto = if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 }; + let scale = fixed_scale.unwrap_or(auto * length); + let mut drawn = Vec::with_capacity(combs.len()); + let out: Vec = combs .iter() .map(|(id, teeth)| { - let lines: Vec<[[f64; 3]; 2]> = teeth.iter().map(|(q, k, n)| [(*q).into(), (*q - *n * (k * scale)).into()]).collect(); + let lines: Vec<[Vec3; 2]> = teeth.iter().map(|(q, k, n)| [*q, *q - *n * (k * scale)]).collect(); let kmax_c = teeth.iter().map(|t| t.1.abs()).fold(0.0_f64, f64::max); - json!({ - "curve": id, - "teeth": lines, - "envelope": lines.iter().map(|l| l[1]).collect::>(), - "max_curvature": kmax_c, - "min_radius": if kmax_c > 1e-12 { Value::from(1.0 / kmax_c) } else { Value::Null }, - }) + let reply: Vec<[[f64; 3]; 2]> = lines.iter().map(|[a, b]| [(*a).into(), (*b).into()]).collect(); + let comb = Comb { + curve: id.clone(), + envelope: reply.iter().map(|l| l[1]).collect(), + teeth: reply, + max_curvature: kmax_c, + min_radius: (kmax_c > 1e-12).then(|| 1.0 / kmax_c), + }; + drawn.push(lines); + comb }) .collect(); - Ok(json!({"combs": out, "scale": scale})) + s.analyses_off(Some("inspect.curvature_comb")); + s.comb = Some(CombView { picks: kept, density, length, fixed_scale, scale, teeth: drawn }); + reply(cmd, CurvatureCombReply::Combs(CurvatureCombs { combs: out, scale, param_warnings: Vec::new() })) +} + +fn reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) } /// Smallest radius along teeth: (radius, where), or None when straight. @@ -238,21 +345,8 @@ fn minimum_radius(s: &mut Session, p: &Value) -> Result { if let Some(edges) = p.get("edges").and_then(Value::as_array) { for e in edges.iter().take(1000) { let at = vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))?; - let mut best: Option<(f64, Vec)> = None; - for b in &st.bodies { - let m = b.mesh(); - for (i, pts) in m.edges.iter().enumerate() { - if m.seams.get(i).copied().unwrap_or(false) { - continue; - } - let d = pts.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min); - if best.as_ref().is_none_or(|x| d < x.0) { - best = Some((d, pts.clone())); - } - } - } - let (_, pts) = best.ok_or_else(|| bad(cmd, "no edge there"))?; - items.push((format!("edge@{},{},{}", at.x, at.y, at.z), min_of(&teeth_3d(&pts)))); + let teeth = edge_teeth(&st, at, 400)?.ok_or_else(|| bad(cmd, "no edge there"))?; + items.push((format!("edge@{},{},{}", at.x, at.y, at.z), min_of(&teeth))); } } let faces: Vec = match p.get("faces").and_then(Value::as_array) { @@ -275,63 +369,145 @@ fn minimum_radius(s: &mut Session, p: &Value) -> Result { } } let overall = items.iter().filter_map(|i| i.1).min_by(|a, b| a.0.total_cmp(&b.0)); - let fmt = |x: Option<(f64, Vec3)>| match x { - Some((r, at)) => json!({"min_radius": r, "at": [at.x, at.y, at.z]}), - None => json!({"min_radius": null}), - }; - Ok(json!({ - "items": items.iter().map(|(id, x)| { let mut v = fmt(*x); v["item"] = json!(id); v }).collect::>(), - "min_radius": overall.map(|o| o.0), - "at": overall.map(|o| [o.1.x, o.1.y, o.1.z]), - })) + let items = items.into_iter().map(|(item, x)| RadiusItem { item, min_radius: x.map(|x| x.0), at: x.map(|x| x.1.into()) }).collect(); + reply(cmd, MinimumRadii { items, min_radius: overall.map(|o| o.0), at: overall.map(|o| o.1.into()), param_warnings: Vec::new() }) } +/// Isocurves each way when the call does not say (`count`), and most faces one call may pick. +const DEFAULT_ISO_COUNT: usize = 8; + +/// The visible model body whose face is nearest `at` (within its pick tolerance), and that face. +fn iso_face_at<'a>(s: &Session, st: &'a solidcraft_doc::ModelState, at: Vec3) -> Option<(&'a solidcraft_doc::ModelBody, usize)> { + st.bodies + .iter() + .filter(|b| s.body_visible(&b.name)) + .filter_map(|b| { + let (d, f) = solidcraft_doc::appearance::nearest_face(b, at)?; + (d <= solidcraft_doc::appearance::pick_tolerance(b)).then_some((d, b, f)) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, b, f)| (b, f)) +} + +/// `inspect.isocurve`: the picked faces' isoparametric curves (`count` each way, exact and cut to +/// each face's trims, [`solidcraft_doc::ModelBody::iso_lines`]), kept so the viewport draws them. +/// View state only, like the other analyses: the design and its undo history are untouched. fn isocurves(s: &mut Session, p: &Value) -> Result { let cmd = "inspect.isocurve"; - let count = num(p, "count").map(|c| c.clamp(1.0, 100.0) as usize).unwrap_or(8); - let faces = p.get("faces").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?; - if faces.is_empty() { - return Err(bad(cmd, "`faces` is empty")); + if bool_(p, "clear").unwrap_or(false) { + s.isocurves.clear(); + s.revision += 1; + return reply(cmd, IsocurveReply::Cleared(AnalysisCleared { analysis: "isocurve".into(), cleared: true, param_warnings: Vec::new() })); } - let st = s.model.state(); - let mut out = Vec::new(); - for v in faces.iter().take(100) { - let at = vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?; - let (bi, f) = face_at(&st, at).ok_or_else(|| bad(cmd, "no face there"))?; - let m = st.bodies.get(bi).map(|b| b.mesh()).ok_or_else(|| bad(cmd, "body"))?; - for w in solidcraft_doc::iso_grid(&m, f, at, count) { - out.push(w.iter().map(|q| [q.x, q.y, q.z]).collect::>()); + let max = crate::kernel::MAX_ISO_COUNT; + let count = match p.get("count") { + None | Some(Value::Null) => DEFAULT_ISO_COUNT, + Some(v) => v + .as_f64() + .filter(|c| c.fract() == 0.0 && (1.0..=max as f64).contains(c)) + .map(|c| c as usize) + .ok_or_else(|| bad(cmd, format!("`count` must be a whole number of curves each way, 1…{max}")))?, + }; + let faces = p.get("faces").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z] on faces"))?; + if faces.is_empty() || faces.len() > MAX_ISO_FACES { + return Err(bad(cmd, format!("`faces` must list 1…{MAX_ISO_FACES} points [x,y,z] on faces"))); + } + let st = s.world_state()?; + let (mut picks, mut curves, mut shown) = (Vec::new(), Vec::new(), Vec::new()); + for v in faces { + let at = vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z] on faces"))?; + let (body, face) = iso_face_at(s, &st, at).ok_or_else(|| bad(cmd, "no face there"))?; + let lines = body.iso_lines(face, count)?; + let along_u = lines.iter().filter(|l| l.along_u).count(); + shown.push(IsoFace { body: body.name.clone(), face, count, u_curves: along_u, v_curves: lines.len() - along_u }); + curves.extend(lines.iter().map(|l| l.points.iter().map(|q| [q.x, q.y, q.z]).collect::>())); + picks.push((face, crate::IsoPick { body: body.name.clone(), at, count })); + } + if bool_(p, "add").unwrap_or(false) { + // A face picked again shows its new count, once. + let again = |k: &crate::IsoPick| { + picks + .iter() + .any(|(f, n)| n.body == k.body && st.body(&k.body).and_then(|b| solidcraft_doc::appearance::face_index_at(b, k.at)) == Some(*f)) + }; + s.isocurves.retain(|k| !again(k)); + } else { + s.isocurves.clear(); + } + s.isocurves.extend(picks.into_iter().map(|(_, k)| k)); + s.analyses_off(Some("inspect.isocurve")); + reply(cmd, IsocurveReply::Curves(Isocurves { curves, faces: shown, param_warnings: Vec::new() })) +} + +impl Session { + /// The curves Isocurve Analysis shows, for the viewport to draw: those of each face in + /// [`Session::isocurves`] of a visible body, found again from its picked point (worked out + /// once per face and count, [`solidcraft_doc::ModelBody::iso_lines`]). A pick whose body or + /// face is gone shows nothing. + pub fn isocurve_lines(&self) -> Vec> { + if self.isocurves.is_empty() { + return Vec::new(); } + let Ok(st) = self.world_state() else { return Vec::new() }; + self.isocurves + .iter() + .filter_map(|k| { + let b = st.body(&k.body).filter(|b| self.body_visible(&b.name))?; + let face = solidcraft_doc::appearance::face_index_at(b, k.at)?; + b.iso_lines(face, k.count).ok() + }) + .collect() } - Ok(json!({"curves": out})) } fn center_of_mass(s: &mut Session, p: &Value) -> Result { let cmd = "inspect.center_of_mass"; let names = string_list(cmd, p, "bodies")?; // The world state, as Measure reads: placed occurrences where they are, each placement once. - let st = s.world_state(); + let st = s.world_state()?; let mut out = Vec::new(); let (mut vol, mut moment) = (0.0, Vec3::ZERO); + let mut skipped = Vec::new(); + // Each body's exact mass properties, as `inspect.measure` takes them: a body that encloses no + // volume (a surface body, an open mesh) or that cannot be measured has no centre of mass. for b in st.bodies.iter().filter(|b| names.is_empty() || names.contains(&b.name)) { - let m = b.mesh().measure(); - if !(m.volume.is_finite() && m.centroid.is_finite()) { + if !super::inspect::encloses_volume(&b.body) { + skipped.push(SkippedBody { body: b.name.clone(), reason: "it encloses no volume".into() }); continue; } + let m = match b.measure() { + Ok(m) if m.volume.is_finite() && m.centroid.is_finite() => m, + Ok(_) => { + skipped.push(SkippedBody { body: b.name.clone(), reason: "its measure is not finite".into() }); + continue; + } + Err(e) => { + skipped.push(SkippedBody { body: b.name.clone(), reason: e.to_string() }); + continue; + } + }; vol += m.volume; moment += m.centroid * m.volume; - out.push(json!({"body": b.name, "center": [m.centroid.x, m.centroid.y, m.centroid.z], "volume": m.volume})); + out.push(BodyCenter { body: b.name.clone(), center: m.centroid.into(), volume: m.volume }); } if out.is_empty() { - return Err(bad(cmd, if names.is_empty() { "there are no bodies" } else { "no such bodies" })); + return Err(bad( + cmd, + match skipped.first() { + Some(why) => format!("no body to measure: `{}`: {}", why.body, why.reason), + None if names.is_empty() => "there are no bodies".to_string(), + None => "no such bodies".to_string(), + }, + )); } let c = if vol.abs() > 1e-300 { moment / vol } else { Vec3::ZERO }; - Ok(json!({"center": [c.x, c.y, c.z], "volume": vol, "bodies": out})) + reply(cmd, CentersOfMass { center: c.into(), volume: vol, bodies: out, skipped, param_warnings: Vec::new() }) } #[cfg(test)] mod tests { use serde_json::{Value, json}; + use solidcraft_geom::prelude::*; use crate::Session; @@ -352,7 +528,7 @@ mod tests { s.execute("sketch.finish", &json!({})).unwrap(); s.execute("solid.cylinder", &json!({"base": [50, 0, 0], "radius": 8, "height": 10})).unwrap(); let r = s.execute("inspect.curvature_comb", &json!({"edges": [[58, 0, 10]]})).unwrap(); - assert!((r["combs"][0]["min_radius"].as_f64().unwrap() - 8.0).abs() < 0.5, "{r}"); + assert!((r["combs"][0]["min_radius"].as_f64().unwrap() - 8.0).abs() < 1e-9, "{r}"); assert!(s.execute("inspect.curvature_comb", &json!({})).is_err()); // Combs along the side face's isocurves: rings of radius 8 and straight lines along it. let r = s.execute("inspect.curvature_comb", &json!({"faces": [[58, 0, 5]], "count": 3})).unwrap(); @@ -365,6 +541,158 @@ mod tests { assert!(s.execute("inspect.curvature_comb", &json!({"faces": [[58, 0, 5]], "count": "x"})).is_err()); } + /// The combs shown are kept in the session: `add` adds to them and draws them all again at + /// one scale (an R5 circle's teeth twice an R10 circle's), with nothing picked it takes new + /// options, a sketch curve keeps its own sketch, and `clear` turns the analysis off. + #[test] + fn added_combs_share_one_scale_and_clear_turns_them_off() { + use solidcore_record::Vec3; + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius": 5, "height": 10})).unwrap(); + s.execute("solid.cylinder", &json!({"base": [40, 0, 0], "radius": 10, "height": 10})).unwrap(); + let one = s.execute("inspect.curvature_comb", &json!({"edges": [[0, 5, 10]], "density": 8})).unwrap(); + let both = s.execute("inspect.curvature_comb", &json!({"edges": [[40, 10, 10]], "add": true})).unwrap(); + let shown = s.comb.as_ref().unwrap(); + assert_eq!((shown.picks.len(), shown.teeth.len(), shown.density), (2, 2, 8), "the first call's density is kept"); + assert_eq!(both["combs"].as_array().unwrap().len(), 2); + let tooth = |c: &[[Vec3; 2]]| c[0][0].dist(c[0][1]); + assert!((tooth(&shown.teeth[0]) / tooth(&shown.teeth[1]) - 2.0).abs() < 1e-9); + assert_ne!(one["scale"], both["scale"], "the scale is the pair's, not the first comb's"); + let longer = s.execute("inspect.curvature_comb", &json!({"add": true, "length": 2})).unwrap(); + assert!((longer["scale"].as_f64().unwrap() - 2.0 * both["scale"].as_f64().unwrap()).abs() < 1e-9); + assert_eq!(s.comb.as_ref().unwrap().picks.len(), 2); + // A sketch curve keeps its sketch after another becomes active. + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + let c = s.execute("sketch.circle.center", &json!({"center": [0, 30], "radius": 5})).unwrap()["curves"][0].clone(); + s.execute("inspect.curvature_comb", &json!({"curves": [c], "add": true})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("sketch.create", &json!({"plane": "XZ"})).unwrap(); + let r = s.execute("inspect.curvature_comb", &json!({"add": true})).unwrap(); + assert_eq!(r["combs"].as_array().unwrap().len(), 3, "{r}"); + s.execute("inspect.curvature_comb", &json!({"clear": true})).unwrap(); + assert!(s.comb.is_none()); + let on = s.execute("inspect.curvature_comb", &json!({"add": true})).unwrap(); + assert!(on["combs"].as_array().unwrap().is_empty() && s.comb.as_ref().is_some_and(|v| v.picks.is_empty())); + } + + /// Each tooth of a comb reply as (foot, curvature): the tooth's length over the scale. + fn tooth_curvatures(r: &Value, comb: usize) -> Vec<([f64; 3], f64)> { + let scale = r["scale"].as_f64().unwrap(); + r["combs"][comb]["teeth"] + .as_array() + .unwrap() + .iter() + .map(|t| { + let [a, b] = [0, 1].map(|i| [0, 1, 2].map(|k| t[i][k].as_f64().unwrap())); + (a, (0..3).map(|k| (b[k] - a[k]).powi(2)).sum::().sqrt() / scale) + }) + .collect() + } + + /// An edge's comb is its exact curve's: on a cylinder's circular edge of radius R every tooth + /// reads 1/R to 1e-9, at any display quality (the comb never reads the mesh), the teeth stand + /// out of the circle (away from its centre), and `density` is the number of teeth. + #[test] + fn an_edge_comb_is_exact_and_has_density_teeth() { + use solidcraft_doc::display_quality::{DisplayQuality, set_current}; + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"base": [50, 0, 0], "radius": 0.75, "height": 40})).unwrap(); + let mut feet = Vec::new(); + for quality in [DisplayQuality::Coarse, DisplayQuality::Ultra] { + set_current(quality); + let r = s.execute("inspect.curvature_comb", &json!({"edges": [[50.75, 0, 40]], "density": 7})).unwrap(); + let teeth = tooth_curvatures(&r, 0); + assert_eq!(teeth.len(), 7, "{r}"); + for (foot, k) in &teeth { + assert!((k - 1.0 / 0.75).abs() < 1e-9, "{k} at {foot:?}"); + assert!(((foot[0] - 50.0).hypot(foot[1]) - 0.75).abs() < 1e-9 && (foot[2] - 40.0).abs() < 1e-9, "{foot:?}"); + } + let tip = &r["combs"][0]["envelope"][2]; + assert!((tip[0].as_f64().unwrap() - 50.0).hypot(tip[1].as_f64().unwrap()) > 0.75, "outside the circle"); + assert!((r["combs"][0]["max_curvature"].as_f64().unwrap() - 1.0 / 0.75).abs() < 1e-9); + feet.push(r["combs"][0]["teeth"].clone()); + } + set_current(DisplayQuality::Normal); + assert_eq!(feet[0], feet[1], "the same comb at any display quality"); + let r = s.execute("inspect.curvature_comb", &json!({"edges": [[50.75, 0, 0]], "density": 123})).unwrap(); + assert_eq!(r["combs"][0]["teeth"].as_array().unwrap().len(), 123); + for density in [json!("x"), json!(-5), json!(1e300)] { + assert!(s.execute("inspect.curvature_comb", &json!({"edges": [[50.75, 0, 0]], "density": density})).is_ok(), "{density}: clamped"); + } + } + + /// An ellipse's curvature, a b / (b² cos² t + a² sin² t)^{3/2} at angle t, is a/b² at the ends of + /// its major axis and b/a² at those of its minor one: the comb of an extruded ellipse's edge + /// reads it at every tooth, the ends included. + #[test] + fn an_ellipse_edge_comb_matches_the_closed_form() { + let (a, b) = (10.0_f64, 4.0_f64); + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + s.execute("sketch.ellipse", &json!({"center": [0, 0], "major": [a, 0], "minor_radius": b})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("solid.extrude", &json!({"distance": 5})).unwrap(); + let r = s.execute("inspect.curvature_comb", &json!({"edges": [[0, b, 5]], "density": 40})).unwrap(); + let exact = |p: [f64; 3]| { + let (c, sn) = (p[0] / a, p[1] / b); + a * b / (b * b * c * c + a * a * sn * sn).powf(1.5) + }; + let teeth = tooth_curvatures(&r, 0); + assert!(teeth.len() >= 20, "{r}"); + for (foot, k) in &teeth { + assert!(((foot[0] / a).hypot(foot[1] / b) - 1.0).abs() < 1e-9, "on the ellipse: {foot:?}"); + assert!((k - exact(*foot)).abs() < 1e-9 * exact(*foot), "{k} vs {} at {foot:?}", exact(*foot)); + } + // The vertices: the teeth at the ends of the axes, wherever the edge's parameter puts them. + let at = |q: [f64; 2]| teeth.iter().find(|(f, _)| (f[0] - q[0]).hypot(f[1] - q[1]) < 1e-9).map(|t| t.1); + let major = [[a, 0.0], [-a, 0.0]].into_iter().filter_map(at).collect::>(); + let minor = [[0.0, b], [0.0, -b]].into_iter().filter_map(at).collect::>(); + assert!(!major.is_empty() && !minor.is_empty(), "teeth at the vertices: {teeth:?}"); + assert!(major.iter().all(|k| (k - a / (b * b)).abs() < 1e-9), "{major:?}"); + assert!(minor.iter().all(|k| (k - b / (a * a)).abs() < 1e-12), "{minor:?}"); + assert!((r["combs"][0]["max_curvature"].as_f64().unwrap() - a / (b * b)).abs() < 1e-9, "{r}"); + } + + /// A face comb follows the surface: on a cylinder's side the iso curves round it read 1/R at + /// every tooth and those along it 0, the teeth along the surface normal; `scale` sets the teeth's + /// length per unit curvature and `length` multiplies the automatic one. + #[test] + fn a_face_comb_is_the_normal_curvature_and_scale_sets_its_length() { + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius": 6, "height": 30})).unwrap(); + let r = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3, "density": 9})).unwrap(); + let combs = r["combs"].as_array().unwrap(); + let (mut rings, mut lines) = (0, 0); + for (i, comb) in combs.iter().enumerate() { + let teeth = tooth_curvatures(&r, i); + assert_eq!(teeth.len(), 9, "{comb}"); + if teeth.iter().all(|(_, k)| *k == 0.0) { + lines += 1; + assert!(comb["min_radius"].is_null()); + } else { + rings += 1; + assert!(teeth.iter().all(|(_, k)| (k - 1.0 / 6.0).abs() < 1e-9), "{teeth:?}"); + // Out of the surface, along its normal (radially, at the tooth's height). + for t in comb["teeth"].as_array().unwrap() { + let q = |i: usize, k: usize| t[i][k].as_f64().unwrap(); + assert!((q(1, 2) - q(0, 2)).abs() < 1e-9 && q(1, 0).hypot(q(1, 1)) > 6.0 + 1e-6, "{t}"); + } + } + } + assert_eq!((rings, lines), (3, 3), "{r}"); + // Tooth length is curvature × scale. + let tooth = |r: &Value| tooth_curvatures(r, 0)[0].1 * r["scale"].as_f64().unwrap(); + let auto = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3})).unwrap(); + let fixed = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3, "scale": 12})).unwrap(); + assert!((tooth(&fixed) - 2.0).abs() < 1e-9, "12 × 1/6: {}", tooth(&fixed)); + let longer = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3, "length": 3})).unwrap(); + assert!((longer["scale"].as_f64().unwrap() - 3.0 * auto["scale"].as_f64().unwrap()).abs() < 1e-9); + assert!((tooth(&longer) - 3.0 * tooth(&auto)).abs() < 1e-9); + for bad in [json!(0), json!(-1), json!(1000), json!("2")] { + assert!(s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "length": bad})).is_err(), "{bad}"); + } + } + #[test] fn minimum_radius_and_center_of_mass() { let mut s = Session::default(); @@ -386,14 +714,17 @@ mod tests { let r = s.execute("inspect.center_of_mass", &json!({})).unwrap(); let (vb, vc) = (1000.0, std::f64::consts::PI * 640.0); let want = (5.0 * vb + 50.0 * vc) / (vb + vc); - assert!((r["center"][0].as_f64().unwrap() - want).abs() < 0.1, "{r}"); - assert!((r["center"][2].as_f64().unwrap() - 5.0).abs() < 0.05, "{r}"); + // From the exact faces, not the display mesh, whose chords cut the cylinder short. + assert!((r["center"][0].as_f64().unwrap() - want).abs() < 1e-6 * want, "{r}"); + assert!((r["center"][2].as_f64().unwrap() - 5.0).abs() < 1e-9, "{r}"); + assert!((r["bodies"][0]["volume"].as_f64().unwrap() - vc).abs() < 1e-6 * vc, "{r}"); + assert!((r["volume"].as_f64().unwrap() - (vb + vc)).abs() < 1e-6 * (vb + vc), "{r}"); assert!(s.execute("inspect.center_of_mass", &json!({"bodies": ["nope"]})).is_err()); // Isocurves on the cylinder's side: rings around it and lines along it. let r = s.execute("inspect.isocurve", &json!({"faces": [[58, 0, 5]], "count": 4})).unwrap(); let curves = r["curves"].as_array().unwrap(); let ring = - |c: &Value| c.as_array().unwrap().iter().all(|q| ((q[0].as_f64().unwrap() - 50.0).hypot(q[1].as_f64().unwrap()) - 8.0).abs() < 0.2); + |c: &Value| c.as_array().unwrap().iter().all(|q| ((q[0].as_f64().unwrap() - 50.0).hypot(q[1].as_f64().unwrap()) - 8.0).abs() < 1e-6); assert!(curves.len() >= 8, "{}", curves.len()); assert!(curves.iter().all(ring), "every curve lies on the cylinder"); let flat = |c: &Value| { @@ -404,6 +735,130 @@ mod tests { assert!(s.execute("inspect.isocurve", &json!({"faces": []})).is_err()); } + /// Points of a reply's `curves`. + fn curve_points(r: &Value) -> Vec> { + r["curves"] + .as_array() + .unwrap() + .iter() + .map(|c| c.as_array().unwrap().iter().map(|q| [0, 1, 2].map(|k| q[k].as_f64().unwrap())).collect()) + .collect() + } + + /// Isocurve Analysis draws a face's exact isoparametric curves, `count` each way, cut to its + /// trims: on a cylinder's side they lie on the cylinder and the lines along it stop where they + /// meet a hole through it; the view state keeps the face, and hostile counts are refused. + #[test] + fn isocurves_are_exact_and_stop_at_a_hole() { + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius": 10, "height": 40})).unwrap(); + // Untrimmed but for its ends: `count` curves each way, each one piece. + let r = s.execute("inspect.isocurve", &json!({"faces": [[10, 0, 20]], "count": 5})).unwrap(); + let face = &r["faces"][0]; + assert_eq!((face["u_curves"].as_u64(), face["v_curves"].as_u64()), (Some(5), Some(5)), "{face}"); + assert_eq!(s.isocurves.len(), 1); + assert_eq!(s.isocurve_lines().iter().map(|l| l.len()).sum::(), 10); + // A hole of radius 3 through it along X, at half height. + s.execute("solid.cylinder", &json!({"radius": 3, "height": 30, "base": [-15, 0, 20], "axis": "X", "operation": "cut"})).unwrap(); + let r = s.execute("inspect.isocurve", &json!({"faces": [[0, 10, 20]], "count": 9})).unwrap(); + let curves = curve_points(&r); + assert!(!curves.is_empty(), "{r}"); + let from_hole = |q: &[f64; 3]| q[1].hypot(q[2] - 20.0) - 3.0; + for c in &curves { + for q in c { + assert!((q[0].hypot(q[1]) - 10.0).abs() < 1e-6, "on the cylinder: {q:?}"); + assert!(from_hole(q) > -1e-3, "not in the hole: {q:?}"); + assert!((-1e-6..=40.0 + 1e-6).contains(&q[2]), "within its ends: {q:?}"); + } + } + // The lines along the axis that cross the hole stop at its rim: their ends there lie on + // the hole's edge. + let mut at_rim = 0; + for c in &curves { + for q in [c.first().unwrap(), c.last().unwrap()] { + if q[2] > 1e-3 && q[2] < 40.0 - 1e-3 && from_hole(q) < 0.5 { + assert!(from_hole(q).abs() < 1e-3, "an end on the hole's edge: {q:?} is {} from it", from_hole(q)); + at_rim += 1; + } + } + } + assert!(at_rim >= 4, "the lines crossing the hole stop at it ({at_rim} ends there)"); + // Picking the face again replaces it; `add` keeps the others; `clear` ends it. + s.execute("inspect.isocurve", &json!({"faces": [[0, -10, 5]], "count": 3, "add": true})).unwrap(); + let shown = s.isocurves.len(); + s.execute("inspect.isocurve", &json!({"faces": [[0, -10, 5]], "count": 4, "add": true})).unwrap(); + assert_eq!(s.isocurves.len(), shown, "the same face again replaces its curves"); + assert_eq!(s.isocurves.last().map(|k| k.count), Some(4)); + let before = s.doc.clone(); + s.execute("inspect.isocurve", &json!({"clear": true})).unwrap(); + assert!(s.isocurves.is_empty() && s.isocurve_lines().is_empty()); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc), "view state only: the design is untouched"); + // Hostile counts and picks. + for count in [json!(0), json!(-3), json!(2.5), json!(101), json!(1e300), json!("8"), json!([4])] { + assert!(s.execute("inspect.isocurve", &json!({"faces": [[0, 10, 20]], "count": count})).is_err(), "count {count}"); + } + assert!(s.execute("inspect.isocurve", &json!({"faces": [[500, 0, 0]]})).is_err(), "no face there"); + assert!(s.execute("inspect.isocurve", &json!({"faces": [["x", 0, 0]]})).is_err()); + assert!(s.execute("inspect.isocurve", &json!({"faces": vec![[0, 10, 20]; 101]})).is_err()); + assert!(s.isocurves.is_empty(), "a refused call shows nothing"); + } + + /// A sphere's face is closed by its seam and poles: its curves are the circles round it and + /// the meridians, each meridian from pole to pole. + #[test] + fn isocurves_of_a_sphere_meet_at_its_poles() { + let mut s = Session::default(); + s.execute("solid.sphere", &json!({"radius": 10})).unwrap(); + let r = s.execute("inspect.isocurve", &json!({"faces": [[10, 0, 0]], "count": 5})).unwrap(); + let face = &r["faces"][0]; + assert_eq!((face["u_curves"].as_u64(), face["v_curves"].as_u64()), (Some(5), Some(5)), "{face}"); + let curves = curve_points(&r); + let len = |q: &[f64; 3]| q[0].hypot(q[1]).hypot(q[2]); + assert!(curves.iter().flatten().all(|q| (len(q) - 10.0).abs() < 1e-6), "on the sphere"); + let pole = |q: &[f64; 3]| q[0].hypot(q[1]) < 1e-6 && (q[2].abs() - 10.0).abs() < 1e-6; + let meridians = curves.iter().filter(|c| pole(c.first().unwrap()) && pole(c.last().unwrap())).count(); + assert_eq!(meridians, 5, "the meridians run from pole to pole"); + } + + /// On a trimmed B-spline face (a spline profile's extruded side, with a hole through it: an + /// inner loop) the isocurves are the surface's own rows and columns and stay inside the face's + /// loops. + #[test] + fn isocurves_of_a_trimmed_spline_face_stay_inside_it() { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + s.execute("sketch.spline.fit_point", &json!({"points": [[0, 0], [20, 8], [40, 0]]})).unwrap(); + s.execute("sketch.line", &json!({"points": [[40, 0], [0, 0]]})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("solid.extrude", &json!({"distance": 30})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 3, "height": 30, "base": [28, -10, 15], "axis": "Y", "operation": "cut"})).unwrap(); + let r = s.execute("inspect.isocurve", &json!({"faces": [[28, 6.7, 5]], "count": 12})).unwrap(); + let face = &r["faces"][0]; + assert!(face["u_curves"].as_u64().unwrap() >= 12 && face["v_curves"].as_u64().unwrap() >= 12, "{face}"); + let st = s.model.state(); + let body = &st.bodies[0]; + let mesh = body.mesh(); + let tol = body.display_tol(); + let spline = face["face"].as_u64().unwrap() as u32; + for c in curve_points(&r) { + for q in &c { + let p = solidcore_record::Vec3::new(q[0], q[1], q[2]); + // On that face (within the display mesh's sag), within its extent, clear of the hole. + let d = mesh + .triangles + .iter() + .zip(&mesh.tri_face) + .filter(|(_, f)| **f == spline) + .filter_map(|(t, _)| mesh.tri(t)) + .map(|[a, b, c]| super::closest_on_triangle(p, a, b, c).dist(p)) + .fold(f64::INFINITY, f64::min); + assert!(d < 2.0 * tol, "on the spline face: {q:?} is {d} from it"); + assert!((-1e-6..=30.0 + 1e-6).contains(&q[2]) && q[1] > -1e-6, "{q:?}"); + assert!((q[0] - 28.0).hypot(q[2] - 15.0) > 3.0 - 1e-3, "not in the hole: {q:?}"); + } + } + } + /// #5246: the centre of mass of an assembly is the world's, like Measure's and Properties': /// a moved occurrence where it is, a copy counted and found by its world name. #[test] diff --git a/crates/engine/src/cmd/sketch_line_circle_tests.rs b/crates/engine/src/cmd/sketch_line_circle_tests.rs index df8ac2d24..513ecf226 100644 --- a/crates/engine/src/cmd/sketch_line_circle_tests.rs +++ b/crates/engine/src/cmd/sketch_line_circle_tests.rs @@ -3,7 +3,8 @@ //! line that cuts it), drives it, follows its parameter, and survives undo and reopening. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_model_plane_tests.rs b/crates/engine/src/cmd/sketch_model_plane_tests.rs index d70235848..b6c644738 100644 --- a/crates/engine/src/cmd/sketch_model_plane_tests.rs +++ b/crates/engine/src/cmd/sketch_model_plane_tests.rs @@ -4,7 +4,8 @@ //! the links follow when a parameter moves the plane. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 29b4ac42c..5ce6f355e 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -1,14 +1,15 @@ //! Sketch modify tools: trim, extend, break, fillet, chamfer, offset, mirror, circular and //! rectangular patterns, move/copy and scale. +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI, TAU}; use serde_json::{Value, json}; +use solidcore_record::{Plane, Vec2}; use solidcraft_doc::ProfileSel; -use solidcraft_geom::Vec2; -use solidcraft_sketch::{ConstraintKind, Curve, CurveKind, Shape, Sketch, intersections, intersections_within}; +use solidcraft_sketch::{ConstraintKind, Curve, CurveKind, Shape, Sketch, Wire, WireSpace, intersections, intersections_within}; -use super::sketch::{add_c, edit, ids_of, line_or_axis_ref, solve_current}; +use super::sketch::{add_c, coincident_points, edit, ids_of, line_or_axis_ref, solve_current}; use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec2_list}; @@ -24,31 +25,32 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "MODIFY") .icon("sketch_fillet") .enabled(in_sketch) - .params(concat!("point: corner shared by two curves (\"l1.end\") | points: [corners] (all rounded alike: one radius, the rest equal; a corner is a point reference or {a, b}, the two curves meeting there) | a, b: two lines or arcs meeting at a corner; radius: expr. A corner that dimensions or constraints measure to stays as a virtual sharp corner on both curves' extensions (`virtual_corners`; the moved ones in `moved_to_virtual_corner`)", created_doc!())), + .params(concat!("point: corner shared by two curves (\"l1.end\") | points: [corners] (all rounded alike: one radius, the rest equal; a corner is a point reference or {a, b}, the two curves meeting there) | a, b: two lines or arcs meeting at a corner (two lines that share no end are first brought to where they meet: the nearer end of a line that stops short moves there, and a line that runs past is cut there, losing its shorter piece); radius: expr. A corner that dimensions or constraints measure to stays as a virtual sharp corner on both curves' extensions (`virtual_corners`; the moved ones in `moved_to_virtual_corner`)", created_doc!())), CommandSpec::new("sketch.chamfer.equal_distance", "Equal Distance Chamfer", chamfer_equal) .at("SKETCH", "MODIFY") .icon("sketch_chamfer") .enabled(in_sketch) - .params(concat!("point | a, b: a corner of two lines; distance", created_doc!())), + .params(concat!("point | points: [corners] (every corner cut alike; a corner is a point reference or {a, b}) | a, b: a corner of two lines (two that share no end are first brought to where they meet, as in sketch.fillet); distance", created_doc!())), CommandSpec::new("sketch.chamfer.distance_angle", "Distance and Angle Chamfer", chamfer_dist_angle) .at("SKETCH", "MODIFY") .icon("sketch_chamfer_angle") .enabled(in_sketch) - .params(concat!("point | a, b: a corner of two lines; distance: along a, angle: deg from a", created_doc!())), + .params(concat!("point | points: [corners] (every corner cut alike; a corner is a point reference or {a, b}, and a point's `a` is the first of its two lines in curve order) | a, b: a corner of two lines (two that share no end are first brought to where they meet, as in sketch.fillet); distance: along a, angle: deg from a", created_doc!())), CommandSpec::new("sketch.chamfer.two_distance", "Two Distance Chamfer", chamfer_two) .at("SKETCH", "MODIFY") .icon("sketch_chamfer_two_distances") .enabled(in_sketch) - .params(concat!("point | a, b: a corner of two lines; distance: along a, distance2: along b", created_doc!())), + .params(concat!("point | points: [corners] (every corner cut alike; a corner is a point reference or {a, b}, and a point's `a` is the first of its two lines in curve order) | a, b: a corner of two lines (two that share no end are first brought to where they meet, as in sketch.fillet); distance: along a, distance2: along b", created_doc!())), CommandSpec::new("sketch.offset", "Offset", offset) .at("SKETCH", "MODIFY") .icon("offset") .key("O") .enabled(in_sketch) .params(concat!( - "curves: [ids], distance: number in mm or length expression (creates an editable dimension; positive = left of the chain, or toward `side`), side?: [x,y], chain?: bool (default true: the connected chain); ", + "curves: [ids], distance: number in mm or length expression (creates an editable dimension; positive = left of the chain, or toward `side`), side?: [x,y], chain?: bool (default true: the connected chain, including ends that only coincide). A corner is trimmed back to the crossing when the offset runs past it, and extended until the offset curves intersect when the corner falls short; ", "direction?: one_side|symmetric (default one_side) or symmetric?: bool (the same distance each way; no `side`, whose job it takes over), ", - "distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions", + "distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions; ", + "instances?: whole number or unitless expression, 1…100 (default 1): each instance after the first offsets the instance before it by the same distance again, so instance n stands n distances from the curves picked. Every instance of a side is driven by that side's own dimension, and each entry of `sides` names its `instance`; an instance the shape cannot take refuses the whole command", created_doc!() )), CommandSpec::new("sketch.offset.break", "Break Offset Association", break_offset).icon("sketch_break") @@ -59,7 +61,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("trim") .key("T") .enabled(in_sketch) - .params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it)", created_doc!())), + .params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it). Trimming a line source releases its dependent straight offsets' linked extents (offset_released: curve ids), retaining their driving normal-distance dimensions and parallel relations", created_doc!())), CommandSpec::new("sketch.trim.path", "Trim Along Path", trim_path) .icon("trim") .enabled(in_sketch) @@ -76,7 +78,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "MODIFY") .icon("sketch_break") .enabled(in_sketch) - .params(concat!("curve: id, at: [x,y] (split at intersections) | points: [[x,y]…] (1…1000 positions projected onto the curve; duplicates are merged)", created_doc!())), + .params(concat!("curve: id, at: [x,y] (split at intersections; at a point where the curve ends and another curve meets, the curve gets its own end there and the two are no longer joined) | points: [[x,y]…] (1…1000 positions projected onto the curve; duplicates are merged)", created_doc!())), CommandSpec::new("sketch.scale", "Sketch Scale", scale) .at("SKETCH", "MODIFY") .icon("sketch_scale") @@ -92,7 +94,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "MODIFY") .icon("sketch_move") .enabled(in_sketch) - .params(concat!("entities: [ids], translate?: [dx,dy], angle?: deg, center?: [x,y], copy?: bool, rotate_constraints?: bool (default true; false keeps constraints unchanged); a rotation turns the constraints tied to the sketch axes when all their geometry moves (horizontal and vertical relations and dimensions swap at odd quarter turns and stay at half turns, line angles turn with the line) and removes the horizontal and vertical ones that cannot hold at other angles; picking a text outline or linked point transforms its whole text source once, and copies remain editable text", created_doc!())), + .params(concat!("entities: [ids], translate?: [dx,dy], angle?: deg, center?: [x,y], copy?: bool, rotate_constraints?: bool (default true; false keeps constraints unchanged); a rotation turns the constraints tied to the sketch axes when all their geometry moves (horizontal and vertical relations and dimensions swap at odd quarter turns and stay at half turns, line angles turn with the line) and removes the horizontal and vertical ones that cannot hold at other angles; picking a text outline or linked point transforms its whole text source once, and copies remain editable text; copy also accepts drawn 3D curves, preserving exact arcs and height above the sketch plane", created_doc!())), CommandSpec::new("sketch.mirror", "Mirror", mirror) .at("SKETCH", "PATTERN") .icon("sketch_mirror") @@ -112,6 +114,10 @@ pub static COMMANDS: &[CommandSpec] = &[ const TOL: f64 = 1e-7; const MAX_COPIES: usize = 500; +/// The most offsets `sketch.offset` stacks one behind the other in a single run. Each instance +/// is its own association, so this stays below the sketch's own caps on analytic offset groups +/// and free-form associations (both 128). +const MAX_INSTANCES: usize = 100; fn curve_arg(sk: &Sketch, p: &Value, cmd: &str) -> Result { let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a curve id"))?; @@ -321,6 +327,54 @@ fn release_extent(sk: &mut Sketch, ci: usize) { }); } +/// Tangencies tied to one of the curve's ends, through a shared point or Coincident +/// constraints. Record them before splitting: keeping the curve ID alone would leave an +/// end tangent on the wrong piece and lose the solver's endpoint tangency equation. +fn endpoint_tangencies(sk: &Sketch, ci: usize) -> Vec<(usize, usize)> { + let Some((start, end)) = sk.curves.get(ci).and_then(|c| c.kind.ends()) else { return Vec::new() }; + let groups = coincident_points(sk); + let root = |p: usize| groups.get(p).copied().unwrap_or(p); + sk.constraints + .iter() + .enumerate() + .filter_map(|(i, k)| { + let ConstraintKind::Tangent { a, b } = k.kind else { return None }; + let other = if a == ci { + b + } else if b == ci { + a + } else { + return None; + }; + let (a, b) = sk.curves.get(other)?.kind.ends()?; + let joined = |p| root(p) == root(a) || root(p) == root(b); + match (joined(start), joined(end)) { + (true, false) => Some((i, start)), + (false, true) => Some((i, end)), + _ => None, + } + }) + .collect() +} + +/// Follow the original endpoints after the pieces have exchanged geometry to preserve the +/// original curve ID. A tangent on the removed piece goes with it in `remove_curves`. +fn rebind_endpoint_tangencies(sk: &mut Sketch, ci: usize, pieces: &[usize], tangencies: &[(usize, usize)]) { + for &(constraint, point) in tangencies { + let owner = pieces.iter().copied().find(|i| sk.curves.get(*i).and_then(|c| c.kind.ends()).is_some_and(|(a, b)| a == point || b == point)); + if let Some(owner) = owner + && let Some(k) = sk.constraints.get_mut(constraint) + && let ConstraintKind::Tangent { a, b } = &mut k.kind + { + if *a == ci { + *a = owner; + } else if *b == ci { + *b = owner; + } + } + } +} + /// The cut parameters bracketing `tq` on curve `ci`: (before, after) with their cutter curves. fn bracket(sk: &Sketch, ci: usize, tq: f64) -> (Vec<(f64, Vec2, usize)>, bool) { let Some(sh) = sk.shape(ci) else { return (Vec::new(), false) }; @@ -404,13 +458,103 @@ fn trim(s: &mut Session, p: &Value) -> Result { let at = req_vec2(cmd, p, "at")?; let (out, info) = edit(s, p, cmd, false, |sk, doc| { let ci = curve_arg(sk, p, cmd)?; - let (out, _) = remove_piece(sk, ci, at, cmd)?; + let released = release_source_line_offsets(sk, doc, ci, cmd)?; + let (mut out, _) = remove_piece(sk, ci, at, cmd)?; + if !released.is_empty() { + out["offset_released"] = json!(released); + } doc.prune_model_params(); Ok(out) })?; Ok(json!({"result": out, "sketch": info})) } +/// A source line's endpoints may change independently of its parallel offsets. Materialize +/// the affected line chains before Trim, retaining their original driving distance parameters +/// as point-line dimensions. Directly trimming an associated output remains a separate command policy. +fn release_source_line_offsets(sk: &mut Sketch, doc: &solidcraft_doc::Document, ci: usize, cmd: &str) -> Result> { + let Some(curve) = sk.curves.get(ci) else { return Ok(Vec::new()) }; + if curve.infinite || sk.is_linked_curve(ci) || !matches!(curve.kind, CurveKind::Line { .. }) { + return Ok(Vec::new()); + } + let id = curve.id.clone(); + let affected: Vec = sk + .offsets + .iter() + .enumerate() + .filter_map(|(i, offset)| { + (offset.topology.is_none() + && offset.sources.iter().any(|(source, _)| source == &id) + && offset.sources.len() == offset.outputs.len() + && offset.sources.iter().zip(&offset.outputs).all(|((source, _), output)| { + [source, output] + .iter() + .all(|id| sk.curve_index(id).and_then(|ci| sk.curves.get(ci)).is_some_and(|c| matches!(c.kind, CurveKind::Line { .. }))) + })) + .then_some(i) + }) + .collect(); + if affected.is_empty() { + return Ok(Vec::new()); + } + let report = solve_current(sk, doc)?; + if !report.keeps_orientation() { + return Err(bad(cmd, report.failure(|_| "cannot trim a source with conflicting offset dimensions".into()))); + } + let mut released = Vec::new(); + for index in affected.into_iter().rev() { + let record = sk.offsets.remove(index); + let dimension = sk + .constraints + .iter() + .find(|c| { + matches!(&c.kind, + ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output)) + }) + .cloned() + .ok_or_else(|| bad(cmd, "missing offset distance dimension"))?; + let value = match dimension.kind { + ConstraintKind::OffsetDistance { value, .. } => value, + _ => record.distance.abs(), + }; + sk.constraints.retain(|c| !matches!(&c.kind, ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output))); + for output in &record.outputs { + let target = sk.curve_index(output).ok_or_else(|| bad(cmd, "missing offset line"))?; + let points = sk.curves.get(target).map(|c| c.kind.point_ids()).unwrap_or_default(); + for i in points { + if i != 0 + && sk.curves.iter().all(|c| !c.kind.uses(i) || record.outputs.contains(&c.id)) + && let Some(point) = sk.points.get_mut(i) + { + point.fixed = false; + } + } + } + for (index, ((source, _), output)) in record.sources.iter().zip(&record.outputs).enumerate() { + let source = sk.curve_index(source).ok_or_else(|| bad(cmd, "missing offset source"))?; + let target = sk.curve_index(output).ok_or_else(|| bad(cmd, "missing offset line"))?; + if !sk.constraints.iter().any(|c| { + matches!(c.kind, + ConstraintKind::Parallel { a, b } if (a == source && b == target) || (a == target && b == source)) + }) { + add_c(sk, ConstraintKind::Parallel { a: source, b: target })?; + } + let p = sk.curves.get(target).and_then(|c| c.kind.ends()).map(|ends| ends.0).ok_or_else(|| bad(cmd, "missing offset line endpoint"))?; + let kind = ConstraintKind::PointLineDistance { p, l: source, value }; + let id = sk.add_constraint(kind.clone(), dimension.param.clone())?; + if let Some(added) = sk.constraints.iter_mut().find(|c| c.id == id) { + let mut kept = dimension.clone(); + kept.id = if index == 0 { dimension.id.clone() } else { id }; + kept.kind = kind; + *added = kept; + } + } + released.extend(record.outputs); + } + released.sort(); + Ok(released) +} + /// Remove the piece of curve `ci` around `at`: between the nearest intersections on either /// side, or the whole curve when nothing crosses it. Returns what `sketch.trim` reports and the /// removed piece as a polyline. @@ -438,7 +582,23 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu return Ok((json!({"deleted": id}), removed)); } refuse_offset_ends(sk, ci, "trim", cmd)?; + // For parallel lines, any point on the output measures the same normal distance. + // Move an endpoint witness to the surviving piece before removing its old endpoint. + let witnesses: Vec = sk + .constraints + .iter() + .filter_map(|dimension| { + let ConstraintKind::PointLineDistance { p, l, .. } = dimension.kind else { return None }; + let ends = sk.curves.get(ci).and_then(|c| c.kind.ends())?; + let line = matches!(sk.curves.get(ci)?.kind, CurveKind::Line { .. }); + (line + && (p == ends.0 || p == ends.1) + && sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Parallel { a, b } if (a == ci && b == l) || (a == l && b == ci)))) + .then(|| dimension.id.clone()) + }) + .collect(); release_extent(sk, ci); + let tangencies = endpoint_tangencies(sk, ci); let ts: Vec = cuts.iter().map(|c| c.0).collect(); let (pieces, pts) = split_at(sk, ci, &ts)?; // The piece containing tq. @@ -470,8 +630,18 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu } _ => gone, }; + rebind_endpoint_tangencies(sk, ci, &pieces, &tangencies); let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); tie(sk, &keep)?; + if let Some((a, _)) = sk.curves.get(ci).and_then(|c| c.kind.ends()) { + for dimension in &mut sk.constraints { + if witnesses.contains(&dimension.id) + && let ConstraintKind::PointLineDistance { p, .. } = &mut dimension.kind + { + *p = a; + } + } + } let removed = sk.polyline(gone); sk.remove_curves(&[gone]); Ok((json!({"trimmed": id}), removed)) @@ -570,7 +740,14 @@ fn trim_path(s: &mut Session, p: &Value) -> Result { after = (si, t); // A piece trim refuses (a closed spline crossed once) stays as it was. let before = sk.clone(); - match remove_piece(sk, ci, q, cmd) { + let cut = release_source_line_offsets(sk, doc, ci, cmd).and_then(|released| { + let (mut out, gone) = remove_piece(sk, ci, q, cmd)?; + if !released.is_empty() { + out["offset_released"] = json!(released); + } + Ok((out, gone)) + }); + match cut { Ok((out, gone)) => { trimmed.push(out); removed.push(json!(gone.iter().map(|v| [v.x, v.y]).collect::>())); @@ -593,11 +770,20 @@ fn trim_path(s: &mut Session, p: &Value) -> Result { Ok(json!({"trimmed": trimmed, "removed": removed, "skipped": skipped, "sketch": info})) } +/// Cuts closer than this to a curve's end or to each other are one place (mm). +const BREAK_GAP: f64 = 1e-6; + fn break_cmd(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.break"; let points = if p.get("points").is_some() { Some(vec2_list(cmd, p, "points", 1000)?) } else { None }; let (out, info) = edit(s, p, cmd, false, |sk, doc| { let ci = curve_arg(sk, p, cmd)?; + if points.is_none() + && let Some(end) = shared_end(sk, ci, req_vec2(cmd, p, "at")?) + { + separate_end(sk, ci, end)?; + return Ok(ids_of(sk, &[ci])); + } if sk.curves.get(ci).is_some_and(|c| c.kind.is_freeform()) { let r = if let Some(points) = &points { super::sketch_freeform::break_at_points(sk, ci, points, cmd)? @@ -608,6 +794,10 @@ fn break_cmd(s: &mut Session, p: &Value) -> Result { doc.prune_model_params(); return Ok(r["curves"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()); } + // Its new ends would follow the source curves as trim's and extend's would: a broken + // offset arc came out in three pieces that went the long way round, and the solve + // moved curves the break never touched. + refuse_offset_ends(sk, ci, "break", cmd)?; let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?; let (ts, cutters): (Vec, Vec>) = if let Some(list) = &points { let mut v: Vec = list.iter().map(|q| sh.param(sh.project(*q))).collect(); @@ -624,6 +814,23 @@ fn break_cmd(s: &mut Session, p: &Value) -> Result { if ts.is_empty() || (!sh.is_full() && ts.iter().any(|t| *t <= t0 || *t >= t1)) { return Err(bad(cmd, "nothing to break at there")); } + // A cut on (or a hair from) an end or another cut would make a piece of no length, and + // its ties: where a curve ends, or touches a tangent arc, it is already broken. + let ends = if sh.is_full() { Vec::new() } else { vec![sh.point(t0), sh.point(t1)] }; + let mut kept: Vec<(f64, Option)> = Vec::new(); + for (t, c) in ts.iter().zip(&cutters) { + let q = sh.point(*t); + if !ends.iter().chain(kept.iter().map(|k| sh.point(k.0)).collect::>().iter()).any(|e| e.dist(q) < BREAK_GAP) { + kept.push((*t, *c)); + } + } + if kept.is_empty() { + return Err(bad(cmd, "the curve is already broken there")); + } + let (ts, cutters): (Vec, Vec>) = kept.into_iter().unzip(); + // Its length (and its midpoint, an equal length) measured the whole curve: left on the + // first piece, it would stretch that piece back to the old size and skew the sketch. + release_extent(sk, ci); let (pieces, pts) = split_at(sk, ci, &ts)?; for (pi, c) in pts.iter().zip(&cutters) { if let Some(c) = c { @@ -636,6 +843,32 @@ fn break_cmd(s: &mut Session, p: &Value) -> Result { Ok(json!({"curves": out, "sketch": info})) } +/// The end of curve `ci` at `at` that another curve also ends at or passes through: Break there +/// separates the two (#7410). +fn shared_end(sk: &Sketch, ci: usize, at: Vec2) -> Option { + let (a, b) = sk.curves.get(ci)?.kind.ends()?; + let end = [a, b].into_iter().find(|&e| sk.point(e).is_some_and(|q| q.dist(at) <= 1e-6))?; + sk.curves.iter().enumerate().any(|(oi, c)| oi != ci && uses(c, end)).then_some(end) +} + +/// Give curve `ci` its own point in place of `end`, at the same place (`.start` or +/// `.end` when that id is free): the curves that met there stay where they are, no longer joined. +fn separate_end(sk: &mut Sketch, ci: usize, end: usize) -> Result<()> { + let pos = sk.point(end).ok_or_else(|| bad("sketch.break", "point"))?; + let curve = sk.curves.get(ci).ok_or_else(|| bad("sketch.break", "curve"))?; + let role = if curve.kind.ends().is_some_and(|(a, _)| a == end) { "start" } else { "end" }; + let name = format!("{}.{role}", curve.id); + let own = match sk.add_point(pos, Some(&name)) { + Ok(i) => i, + Err(solidcraft_sketch::SketchError::Duplicate(_)) => sk.add_point(pos, None)?, + Err(e) => return Err(e.into()), + }; + if let Some(c) = sk.curves.get_mut(ci) { + c.kind.map_points(&|q| if q == end { own } else { q }); + } + Ok(()) +} + /// How far a line with nothing in its way extends: the reach its preview draws, and the length /// `sketch.extend` adds, so clicking a preview that overhangs its target adds that line instead /// of nothing. @@ -947,11 +1180,19 @@ fn stop_point(sk: &Sketch, ci: usize, q: Vec2) -> Option { } /// Add the line an extension needs, from the growing end to the stop: the sketch's own point -/// when the stop already is one, a new point otherwise. -fn add_line_extension(sk: &mut Sketch, end: usize, q: Vec2, stop: Option) -> Result { +/// when the stop already is one, a new point otherwise. A new point stopped in the middle of a +/// curve is pinned onto it, as the free-end path pins its end, so the extension is attached to +/// the curve it stops on instead of lying loose over it. +fn add_line_extension(sk: &mut Sketch, end: usize, q: Vec2, stop: Option, cutter: Option) -> Result { let b = match stop { Some(p) => p, - None => sk.add_point(q, None)?, + None => { + let p = sk.add_point(q, None)?; + if let Some(cutter) = cutter { + pin(sk, p, cutter)?; + } + p + } }; sk.add_curve(CurveKind::Line { a: end, b }, None)?; Ok(sk.points.get(b).map(|x| x.id.clone()).unwrap_or_default()) @@ -1076,7 +1317,7 @@ fn grow_line(sk: &mut Sketch, ci: usize, aim: LineAim) -> Result { // The end joined to other geometry stays where it is: add a line from it. if !neighbors.is_empty() { - return add_line_extension(sk, end, q, stop); + return add_line_extension(sk, end, q, stop, cutter); } // An end held by a constraint, or lying on a circle or arc, stays where it is too: the @@ -1096,7 +1337,9 @@ fn grow_line(sk: &mut Sketch, ci: usize, aim: LineAim) -> Result { // Geometric check: does the endpoint lie on any circle or arc? let ep = sk.point(end).unwrap_or_default(); sk.curves.iter().any(|curve| match curve.kind { - CurveKind::Circle { c, r } => (ep - sk.point(c).unwrap_or_default()).len().abs() - r < 1e-6, + // On the circle means its distance to the centre equals the radius: a point merely + // *inside* the circle is not held by it. + CurveKind::Circle { c, r } => ((ep - sk.point(c).unwrap_or_default()).len() - r).abs() < TOL, // This is an arc's own start or end: it sits on that arc. CurveKind::Arc { a, b, .. } => ep.dist(sk.point(a).unwrap_or_default()) < 1e-6 || ep.dist(sk.point(b).unwrap_or_default()) < 1e-6, _ => false, @@ -1104,7 +1347,7 @@ fn grow_line(sk: &mut Sketch, ci: usize, aim: LineAim) -> Result { }; if end_is_held { - return add_line_extension(sk, end, q, stop); + return add_line_extension(sk, end, q, stop, cutter); } // A free end moves along instead, if the solver lets it. The attempt is made on a copy, @@ -1134,7 +1377,7 @@ fn grow_line(sk: &mut Sketch, ci: usize, aim: LineAim) -> Result { return Ok(sk.points.get(end).map(|x| x.id.clone()).unwrap_or_default()); } // The solve could not put the end where it belongs: add a new line instead. - add_line_extension(sk, end, q, stop) + add_line_extension(sk, end, q, stop, cutter) } /// The two-curve form of `sketch.extend`: `curves` names exactly two curves, `at` optionally one @@ -1395,21 +1638,31 @@ fn weld_corner(sk: &mut Sketch, p: &Value) { let Some(mut q) = q else { return }; // Each pass welds one partner; a pass removes a constraint, so this ends. for _ in 0..sk.constraints.len() { - let partner = sk.constraints.iter().enumerate().find_map(|(i, k)| { + let partner = sk.constraints.iter().find_map(|k| { let o = match k.kind { ConstraintKind::Coincident { p, q: r } if p == q && r != q => r, ConstraintKind::Coincident { p, q: r } if r == q && p != q => p, _ => return None, }; - let held_elsewhere = sk.constraints.iter().enumerate().any(|(j, k)| j != i && k.kind.refers_to_point(o)); + // What else holds the partner (a dimension measuring to the corner, #7507) holds + // the corner instead: the two are one place. Not where that would name the corner + // twice in one constraint (other than a repeat of this coincidence). + let twice = sk.constraints.iter().any(|other| { + let points = other.kind.indices().0; + !matches!(other.kind, ConstraintKind::Coincident { .. }) && points.contains(&o) && points.contains(&q) + }); let linked = (0..sk.curves.len()).any(|c| sk.is_linked_curve(c) && sk.curves.get(c).is_some_and(|x| x.kind.uses(o))); - (o != 0 && !held_elsewhere && !linked).then_some((i, o)) + (o != 0 && !twice && !linked).then_some(o) }); - let Some((i, o)) = partner else { return }; + let Some(o) = partner else { return }; for c in sk.curves.iter_mut() { c.kind.map_points(&|x| if x == o { q } else { x }); } - sk.constraints.remove(i); + for k in sk.constraints.iter_mut() { + k.kind.remap(&|x| Some(if x == o { q } else { x }), &Some); + } + // The coincidence, and any repeat of it, now joins the corner to itself. + sk.constraints.retain(|k| !matches!(k.kind, ConstraintKind::Coincident { p, q: r } if p == r)); sk.remove_points(&[o]); if o < q { q -= 1; @@ -1455,6 +1708,70 @@ fn refuse_offset_corner(sk: &Sketch, p: &Value, cmd: &str) -> Result<()> { } } +/// Two lines given as `a` and `b` that share no end are brought to where they meet, so they +/// make a corner to round or cut (#6912, #7759, #7985). Each line's end nearer that point moves +/// onto it: a line that stops short is extended, and one that runs past the other is cut there, +/// losing its shorter piece. Refused when the lines are parallel or meet too far away, and when +/// an end that would move is held by anything else (another curve, a constraint or dimension on +/// it, a fixed or driven position) or its line has a size of its own (a length, an equal or a +/// midpoint), which moving the end would change. +fn meet_lines(sk: &mut Sketch, p: &Value, cmd: &str) -> Result<()> { + if str_(p, "point").is_some() { + return Ok(()); + } + let line = |k: &str| str_(p, k).and_then(|i| sk.curve_index(i)); + let (Some(la), Some(lb)) = (line("a"), line("b")) else { return Ok(()) }; + let ends = |l: usize| match sk.curves.get(l).map(|c| &c.kind) { + Some(CurveKind::Line { a, b }) => Some((*a, *b)), + _ => None, + }; + let (Some((a0, a1)), Some((b0, b1))) = (ends(la), ends(lb)) else { return Ok(()) }; + if la == lb || [a0, a1].iter().any(|x| *x == b0 || *x == b1) { + return Ok(()); + } + let (Some(p0), Some(p1), Some(q0), Some(q1)) = (sk.point(a0), sk.point(a1), sk.point(b0), sk.point(b1)) else { return Ok(()) }; + let (da, db) = (p1 - p0, q1 - q0); + let den = da.cross(db); + if den.abs() <= 1e-9 * da.len() * db.len() { + return Err(bad(cmd, "the lines are parallel")); + } + // Where they meet, as a fraction along each line from its first end. + let (t, u) = ((q0 - p0).cross(db) / den, (q0 - p0).cross(da) / den); + let meet = p0 + da * t; + if !(meet.is_finite() && meet.len() < 1e7) { + return Err(bad(cmd, "the lines meet too far away")); + } + // The end on the shorter side of the meeting point moves (the nearer end, for a line that + // stops short of it). + let (na, nb) = (if t >= 0.5 { a1 } else { a0 }, if u >= 0.5 { b1 } else { b0 }); + for (l, e) in [(la, na), (lb, nb)] { + let id = sk.curves.get(l).map(|c| c.id.clone()).unwrap_or_default(); + let other_curve = sk.curves.iter().enumerate().any(|(i, c)| i != l && c.kind.uses(e)); + let positioned = sk.points.get(e).is_some_and(|q| q.fixed || q.exprs.is_some() || q.link.is_some()); + if e == 0 || other_curve || positioned || sk.is_linked_curve(l) || sk.constraints.iter().any(|k| k.kind.refers_to_point(e)) { + return Err(bad(cmd, format!("`{id}` doesn't reach the other line, and its end that would move there is held by other geometry"))); + } + let sized = sk.constraints.iter().any(|k| { + matches!(k.kind, ConstraintKind::Length { l: x, .. } | ConstraintKind::Midpoint { l: x, .. } if x == l) + || matches!(k.kind, ConstraintKind::Equal { a, b } if a == l || b == l) + }); + if sized { + return Err(bad(cmd, format!("`{id}` doesn't reach the other line, and its length is held: extending or cutting it would change that"))); + } + } + for e in [na, nb] { + if let Some(q) = sk.points.get_mut(e) { + q.pos = meet; + } + } + // One corner point: b's moved end becomes a's. + for c in sk.curves.iter_mut() { + c.kind.map_points(&|x| if x == nb { na } else { x }); + } + sk.remove_points(&[nb]); + Ok(()) +} + /// A corner of two lines: (line a, line b, corner point, far end of a, far end of b). fn corner(sk: &Sketch, p: &Value, cmd: &str) -> Result<(usize, usize, usize, usize, usize)> { let ends = |l: usize| match sk.curves.get(l).map(|c| &c.kind) { @@ -1634,34 +1951,40 @@ fn corner_arg(q: &Value) -> Value { } } +/// The corners a fillet or chamfer works on: several at once (`points`), each like a single +/// `point`, or the one corner `point` or `a`, `b` name. +fn corner_list(p: &Value, cmd: &str) -> Result> { + match p.get("points").and_then(Value::as_array) { + Some(a) if !a.is_empty() && a.len() <= 500 => Ok(a.iter().map(corner_arg).collect()), + Some(_) => Err(bad(cmd, "`points` must list 1…500 corners")), + None => Ok(vec![p.clone()]), + } +} + fn fillet(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.fillet"; let r_expr = req_expr(cmd, p, "radius")?; - // Several corners at once (`points`), each like a single `point`. - let corners: Vec = match p.get("points").and_then(Value::as_array) { - Some(a) if !a.is_empty() && a.len() <= 500 => a.iter().map(corner_arg).collect(), - Some(_) => return Err(bad(cmd, "`points` must list 1…500 corners")), - None => vec![p.clone()], - }; + let corners = corner_list(p, cmd)?; let (out, info) = edit(s, p, cmd, false, |sk, doc| { let r = doc.eval(&r_expr, solidcraft_doc::expr::Kind::Length).map_err(|e| bad(cmd, format!("radius: {e}")))?; if !(r > 1e-9 && r < 1e8) { return Err(bad(cmd, "radius must be positive")); } let pname = doc.new_model_param(&r_expr, "mm"); - let (mut arcs, mut cons, mut kept) = (Vec::new(), Vec::new(), Vec::new()); + // The arcs by id: a fillet that takes a whole line removes it, which renumbers the curves. + let (mut arcs, mut cons, mut kept): (Vec, _, _) = (Vec::new(), Vec::new(), Vec::new()); for q in &corners { let (arc, mut c, k) = fillet_corner(sk, q, r, cmd)?; kept.push(k); // One radius for them all: the first carries the dimension, the rest are equal to it. - match arcs.first() { + match arcs.first().and_then(|first| sk.curve_index(first)) { None => c.push(sk.add_constraint(ConstraintKind::Radius { c: arc, value: r }, Some(pname.clone()))?), - Some(first) => c.push(add_c(sk, ConstraintKind::Equal { a: *first, b: arc })?), + Some(first) => c.push(add_c(sk, ConstraintKind::Equal { a: first, b: arc })?), } cons.extend(c); - arcs.push(arc); + arcs.push(sk.curves.get(arc).map(|c| c.id.clone()).unwrap_or_default()); } - Ok((ids_of(sk, &arcs), cons, pname, kept_json(kept))) + Ok((arcs, cons, pname, kept_json(kept))) })?; let (vc, moved) = out.3; Ok(json!({"curves": out.0, "constraints": out.1, "param": out.2, "virtual_corners": vc, "moved_to_virtual_corner": moved, "sketch": info})) @@ -1686,6 +2009,7 @@ fn fillet_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result<(usize refuse_infinite_corner(sk, p, cmd)?; refuse_offset_corner(sk, p, cmd)?; weld_corner(sk, p); + meet_lines(sk, p, cmd)?; let (la, lb, c, fa, fb) = match corner(sk, p, cmd) { Ok(x) => x, // Not two lines: a corner with an arc. @@ -1699,12 +2023,21 @@ fn fillet_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result<(usize return Err(bad(cmd, "the lines are parallel")); } let d = r / half.tan(); - if d >= pa.dist(pc) - 1e-9 || d >= pb.dist(pc) - 1e-9 { + let (len_a, len_b) = (pa.dist(pc), pb.dist(pc)); + // A radius that needs all of a line (the second corner of a side filleted with half its + // length, #2500): the line goes, and the arc meets what was at its far end. + let tol = 1e-7 * (1.0 + len_a.max(len_b)); + if d > len_a + tol || d > len_b + tol { return Err(bad(cmd, format!("the radius is too large for that corner (it needs {d:.3} mm of each line)"))); } + let (spent_a, spent_b) = (d >= len_a - tol, d >= len_b - tol); + // A spent line is cut just short of its far end, and the stub is removed below. + let short = |len: f64| len - (len * 1e-6).max(1e-6); + let far_ids = [fa, fb].map(|i| sk.points.get(i).map(|p| p.id.clone()).unwrap_or_default()); let bis = (u + v).normalized().ok_or_else(|| bad(cmd, "the lines are parallel"))?; let center = pc + bis * (r / half.sin()); - let (ta, tb, _, kept) = cut_corner(sk, la, lb, c, fa, fb, d, d, cmd)?; + let (da, db) = (if spent_a { short(len_a) } else { d }, if spent_b { short(len_b) } else { d }); + let (ta, tb, _, kept) = cut_corner(sk, la, lb, c, fa, fb, da, db, cmd)?; let (qa, qb) = (sk.point(ta).unwrap_or_default(), sk.point(tb).unwrap_or_default()); let ccw = (qa - center).cross(qb - center) > 0.0; let arc = if ccw { @@ -1712,7 +2045,35 @@ fn fillet_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result<(usize } else { sk.add_arc(center, qb, qa, [None, Some(tb), Some(ta)], None)? }; - let cons = vec![add_c(sk, ConstraintKind::Tangent { a: la, b: arc })?, add_c(sk, ConstraintKind::Tangent { a: lb, b: arc })?]; + if !spent_a && !spent_b { + let cons = vec![add_c(sk, ConstraintKind::Tangent { a: la, b: arc })?, add_c(sk, ConstraintKind::Tangent { a: lb, b: arc })?]; + return Ok((arc, cons, kept)); + } + let id = |sk: &Sketch, i: usize| sk.curves.get(i).map(|c| c.id.clone()).unwrap_or_default(); + let arc_id = id(sk, arc); + let mut cons = Vec::new(); + let mut stubs = Vec::new(); + for ((line, t, spent), far_id) in [(la, ta, spent_a), (lb, tb, spent_b)].into_iter().zip(&far_ids) { + if !spent { + cons.push(add_c(sk, ConstraintKind::Tangent { a: line, b: arc })?); + continue; + } + let Some(far) = sk.point_index(far_id) else { return Err(bad(cmd, "the line's far end is gone")) }; + // The arc ends where the line did, tangent to the curve that goes on from there. + if let Some(cu) = sk.curves.get_mut(arc) { + cu.kind.map_points(&|i| if i == t { far } else { i }); + } + let next = (0..sk.curves.len()).find(|&i| { + i != line && i != arc && sk.curves.get(i).is_some_and(|cu| !cu.construction && cu.kind.ends().is_some_and(|(a, b)| a == far || b == far)) + }); + if let Some(n) = next { + cons.push(add_c(sk, ConstraintKind::Tangent { a: n, b: arc })?); + } + stubs.push(id(sk, line)); + } + let stubs: Vec = stubs.iter().filter_map(|s| sk.curve_index(s)).collect(); + sk.remove_curves(&stubs); + let arc = sk.curve_index(&arc_id).ok_or_else(|| bad(cmd, "the fillet arc is gone"))?; Ok((arc, cons, kept)) } @@ -1811,31 +2172,63 @@ fn round_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result Result<(f64, f64)>) -> Result { +fn chamfer(s: &mut Session, p: &Value, cmd: &str, dists: impl Fn(f64) -> Result<(f64, f64)>) -> Result { + let corners = corner_list(p, cmd)?; let (out, info) = edit(s, p, cmd, false, |sk, _| { - refuse_spatial_corner(sk, p, cmd)?; - refuse_infinite_corner(sk, p, cmd)?; - refuse_offset_corner(sk, p, cmd)?; - weld_corner(sk, p); - let (la, lb, c, fa, fb) = corner(sk, p, cmd)?; - let (pc, pa, pb) = (sk.point(c).unwrap_or_default(), sk.point(fa).unwrap_or_default(), sk.point(fb).unwrap_or_default()); - let (u, v) = ((pa - pc).normalized().unwrap_or(Vec2::X), (pb - pc).normalized().unwrap_or(Vec2::Y)); - let corner_angle = u.cross(v).atan2(u.dot(v)).abs(); - // Lines in line with each other, or lying on each other, have no corner to cut, as a - // fillet refuses them: on two lines lying on each other the chamfer was a line of no - // length between their cut-back ends. - if !(2e-6..=std::f64::consts::PI - 2e-9).contains(&corner_angle) { - return Err(bad(cmd, "the lines are parallel")); + // Every corner is cut alike, in one edit: a corner that can't be cut refuses them all. + // A corner named twice (its point, then its two lines, say) would be cut again where + // the first cut left a new corner, so it is refused. Two lines that share no end are + // brought to where they meet first, so that corner is found by its point too. + let mut seen = std::collections::BTreeSet::new(); + for q in &corners { + prepare_corner(sk, q, cmd)?; + if let Ok((la, lb, c, _, _)) = corner(sk, q, cmd) + && !seen.insert((c, la.min(lb), la.max(lb))) + { + return Err(bad(cmd, "a corner is listed twice")); + } } - let (da, db) = dists(corner_angle)?; - let (ta, tb, _, kept) = cut_corner(sk, la, lb, c, fa, fb, da, db, cmd)?; - let l = sk.add_line_pts(ta, tb, None)?; - Ok((ids_of(sk, &[l]), kept_json(vec![kept]))) + let (mut lines, mut kept) = (Vec::new(), Vec::new()); + for q in &corners { + let (l, k) = chamfer_corner(sk, q, cmd, &dists)?; + lines.push(l); + kept.push(k); + } + Ok((ids_of(sk, &lines), kept_json(kept))) })?; let (curves, (vc, moved)) = out; Ok(json!({"curves": curves, "virtual_corners": vc, "moved_to_virtual_corner": moved, "sketch": info})) } +/// Cut one corner (`point` or `a`, `b`) of two lines with a straight line, `dists` giving how +/// far back along each line from the corner's angle: the new line and what became of the corner. +fn chamfer_corner(sk: &mut Sketch, p: &Value, cmd: &str, dists: &impl Fn(f64) -> Result<(f64, f64)>) -> Result<(usize, CornerKept)> { + prepare_corner(sk, p, cmd)?; + let (la, lb, c, fa, fb) = corner(sk, p, cmd)?; + let (pc, pa, pb) = (sk.point(c).unwrap_or_default(), sk.point(fa).unwrap_or_default(), sk.point(fb).unwrap_or_default()); + let (u, v) = ((pa - pc).normalized().unwrap_or(Vec2::X), (pb - pc).normalized().unwrap_or(Vec2::Y)); + let corner_angle = u.cross(v).atan2(u.dot(v)).abs(); + // Lines in line with each other, or lying on each other, have no corner to cut, as a + // fillet refuses them: on two lines lying on each other the chamfer was a line of no + // length between their cut-back ends. + if !(2e-6..=std::f64::consts::PI - 2e-9).contains(&corner_angle) { + return Err(bad(cmd, "the lines are parallel")); + } + let (da, db) = dists(corner_angle)?; + let (ta, tb, _, kept) = cut_corner(sk, la, lb, c, fa, fb, da, db, cmd)?; + Ok((sk.add_line_pts(ta, tb, None)?, kept)) +} + +/// The checks and joins before a chamfer cuts a corner. Running them again on a corner already +/// prepared changes nothing. +fn prepare_corner(sk: &mut Sketch, p: &Value, cmd: &str) -> Result<()> { + refuse_spatial_corner(sk, p, cmd)?; + refuse_infinite_corner(sk, p, cmd)?; + refuse_offset_corner(sk, p, cmd)?; + weld_corner(sk, p); + meet_lines(sk, p, cmd) +} + fn chamfer_equal(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.chamfer.equal_distance"; let d = num(p, "distance").ok_or_else(|| bad(cmd, "`distance` must be a number"))?; @@ -1866,13 +2259,46 @@ fn chamfer_dist_angle(s: &mut Session, p: &Value) -> Result { // --------------------------------------------------------------------------------------------- // Offset +/// Ends this close are one corner. Profile finding joins ends at the same distance, so a loop +/// the sketch already treats as one profile offsets as one chain. +const ENDPOINT_JOIN: f64 = 1e-4; + /// Curves of the connected chain through `start` (joined where exactly two curves meet), in /// order, with whether each is walked from its stored start (`a`) to its end (`b`). +/// +/// A corner counts when the curves share the point, when a coincident constraint makes the two +/// ends one point, or when the ends simply lie on each other. The offset then trims a corner +/// that runs past the crossing and extends one that stops short, so the new curves intersect. fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool) { - let ends = |c: usize| sk.curves.get(c).and_then(|c| c.kind.ends()); + // Ends joined by a coincident constraint are one joint, as well as a shared point: lines drawn + // one by one meet at their own points, held together by constraints, and must chain the same + // (else each is offset on its own, to the left of the way it was drawn). + let groups = coincident_points(sk); + let root = |i: usize| groups.get(i).copied().unwrap_or(i); + let endpoints: Vec<_> = sk.curves.iter().map(|c| c.kind.ends().map(|(a, b)| (root(a), root(b)))).collect(); + let ends = |c: usize| endpoints.get(c).copied().flatten(); let Some((s0, s1)) = ends(start) else { return (vec![(start, true)], true) }; + let mut parent: Vec = (0..sk.points.len()).collect(); + for constraint in &sk.constraints { + if let ConstraintKind::Coincident { p, q } = constraint.kind { + union_points(&mut parent, p, q); + } + } + let group: Vec = (0..parent.len()).map(|i| find_point(&mut parent, i)).collect(); + let same = |a: usize, b: usize| -> bool { + if a == b { + return true; + } + if group.get(a).zip(group.get(b)).is_some_and(|(x, y)| x == y) { + return true; + } + match (sk.point(a), sk.point(b)) { + (Some(p), Some(q)) if p.is_finite() && q.is_finite() => p.dist(q) <= ENDPOINT_JOIN, + _ => false, + } + }; let next = |from: usize, at: usize, used: &[usize]| -> Option { - let users: Vec = pool.iter().copied().filter(|c| ends(*c).is_some_and(|(a, b)| a == at || b == at)).collect(); + let users: Vec = pool.iter().copied().filter(|c| ends(*c).is_some_and(|(a, b)| same(a, at) || same(b, at))).collect(); if users.len() != 2 { return None; } @@ -1884,7 +2310,7 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool let mut closed = false; while let Some(n) = next(cur, at, &used) { let Some((a, b)) = ends(n) else { break }; - let forward = a == at; + let forward = same(a, at); fwd.push((n, forward)); used.push(n); cur = n; @@ -1893,7 +2319,7 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool break; } } - if at == s0 && fwd.len() > 1 { + if fwd.len() > 1 && same(at, s0) { closed = true; } else { // Walk backwards from the start. @@ -1901,7 +2327,7 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool let mut back = Vec::new(); while let Some(n) = next(cur, at, &used) { let Some((a, b)) = ends(n) else { break }; - let forward = b == at; + let forward = same(b, at); back.push((n, forward)); used.push(n); cur = n; @@ -1917,6 +2343,33 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool (fwd, closed) } +fn find_point(parent: &mut [usize], mut i: usize) -> usize { + let mut top = i; + while parent.get(top).copied().unwrap_or(top) != top { + top = parent[top]; + } + while i != top { + let next = parent.get(i).copied().unwrap_or(top); + if let Some(slot) = parent.get_mut(i) { + *slot = top; + } + i = next; + } + top +} + +fn union_points(parent: &mut [usize], a: usize, b: usize) { + if a >= parent.len() || b >= parent.len() { + return; + } + let (a, b) = (find_point(parent, a), find_point(parent, b)); + if a != b + && let Some(slot) = parent.get_mut(b) + { + *slot = a; + } +} + /// An offset piece: shape walked in chain direction, offset by `d` to the left. #[derive(Clone)] enum Piece { @@ -2120,7 +2573,7 @@ fn offset_side(sk: &mut Sketch, cmd: &str, order: &[(usize, bool)], sources: &[( idx.push(pb); idx.dedup(); if idx.len() >= 2 { - made.push(sk.add_curve(CurveKind::Spline { pts: idx, control: false, degree: 3, periodic: false }, None)?); + made.push(sk.add_curve(CurveKind::Spline { pts: idx, control: false, degree: 3, periodic: false, nurbs: None }, None)?); } } Piece::Line(..) => { @@ -2162,6 +2615,24 @@ fn offset_length(s: &Session, p: &Value, key: &str, positive: bool) -> Result<(f Ok((value, expression)) } +/// `instances`: how many offsets stand one behind the other, each at the same distance from the +/// one before it. A number or a unitless expression; one (the offset by itself) by default. +fn offset_instances(s: &Session, p: &Value, cmd: &str) -> Result { + let message = format!("`instances` must be a whole number from 1 to {MAX_INSTANCES}, or an expression for one"); + let count = match p.get("instances") { + None | Some(Value::Null) => return Ok(1), + Some(Value::Number(_)) => num(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?, + Some(_) => { + let expression = expr(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?.into_string(); + s.doc.eval(&expression, solidcraft_doc::expr::Kind::Unitless).map_err(|error| bad(cmd, format!("`instances`: {error}")))? + } + }; + if !count.is_finite() || count.fract() != 0.0 || !(1.0..=MAX_INSTANCES as f64).contains(&count) { + return Err(bad(cmd, message)); + } + Ok(count as usize) +} + #[derive(Clone, Copy)] struct OffsetOptions { side: Option, @@ -2233,13 +2704,31 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha sel.clone() }; let (order, closed) = chain(sk, first, &pool); - // Side: toward `side` (compare both offsets' distance to it), else the sign. + // Side: toward `side`, else the sign. A positive distance offsets to the left of the walk. + // A line or an arc says directly which side `side` is on (the half-plane; inside or outside + // the circle, as for a circle above), so neither rounding of a tiny step nor an arc too small + // for the distance can turn it round; other curves compare both offsets' distance to it. let d = match side { Some(q) => { - let dist = |dd: f64| { - offset_piece(sk, first, order.iter().find(|x| x.0 == first).is_none_or(|x| x.1), dd).map(|pc| piece_dist(&pc, q)).unwrap_or(f64::MAX) + let forward = order.iter().find(|x| x.0 == first).is_none_or(|x| x.1); + let left = match sk.curves.get(first).map(|c| c.kind.clone()) { + Some(CurveKind::Line { a, b }) => { + let (a, b) = (sk.point(a).unwrap_or_default(), sk.point(b).unwrap_or_default()); + let (from, along) = if forward { (a, b - a) } else { (b, a - b) }; + Some(along.x * (q - from).y - along.y * (q - from).x >= 0.0) + } + Some(CurveKind::Arc { c, a, .. }) => { + let (c, a) = (sk.point(c).unwrap_or_default(), sk.point(a).unwrap_or_default()); + // Followed forward an arc turns anticlockwise, its centre on the left. + Some((q.dist(c) <= c.dist(a)) == forward) + } + _ => None, }; - if dist(d0.abs()) <= dist(-d0.abs()) { d0.abs() } else { -d0.abs() } + let toward = left.unwrap_or_else(|| { + let dist = |dd: f64| offset_piece(sk, first, forward, dd).map(|pc| piece_dist(&pc, q)).unwrap_or(f64::MAX); + dist(d0.abs()) <= dist(-d0.abs()) + }); + if toward { d0.abs() } else { -d0.abs() } } None => d0, }; @@ -2296,6 +2785,142 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha Ok(sides) } +/// One rung of an offset ladder: the offsets of `ids`, with the infinite flag carried over from +/// infinite sources (#1359) and a driving dimension on each side that is linked to its source. +/// `names` is the parameter each side is driven by, in side order, falling back to the first for +/// a side the rung before it had none for. The sources the rung consumed come back with it. +fn offset_rung( + sk: &mut Sketch, + cmd: &str, + ids: &[String], + eligible: &std::collections::HashSet, + options: OffsetOptions, + names: &[String], +) -> Result<(Vec, Vec)> { + let mut group = offset_group(sk, ids, eligible, options)?; + let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?; + let sources = sk + .offsets + .iter() + .find(|o| o.owns_output(output)) + .map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::>()) + .or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()])) + .or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone())) + .ok_or_else(|| bad(cmd, "offset association is missing"))?; + // An offset of infinite lines is infinite lines too (#1359). + let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite)); + if infinite { + for id in group.iter().flat_map(|side| side.curves.iter()) { + if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c)) + && matches!(cu.kind, CurveKind::Line { .. }) + { + cu.infinite = true; + cu.construction = true; + } + } + } + for (index, side) in group.iter_mut().enumerate() { + // A trimmed offset is not linked to its source: it has no distance to drive. + if side.unlinked_sources.is_some() { + continue; + } + let name = names.get(index).or_else(|| names.first()).ok_or_else(|| bad(cmd, "offset has no driving dimension"))?; + let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?; + side.constraints.push(sk.add_constraint( + ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 }, + Some(name.clone()), + )?); + side.param = Some(name.clone()); + } + Ok((group, sources)) +} + +/// Where the next instance of an offset belongs: one more step the way the rung already went. +/// The rung's own normal-distance annotation knows that, since its ends are the middle of its +/// first source curve and the point one signed distance away on the rung itself; the same step +/// again lands one distance past the rung. The side is taken from the geometry this way rather +/// than from the sign again, because an output's stored ends need not run the way the chain +/// through them is walked, and a reversed walk reads the same sign as the other side. A trimmed +/// offset has no annotation and is ordinary geometry: `None` leaves the sign to speak for it. +fn offset_beyond(sk: &Sketch, rung: &[String]) -> Option { + // A circle offsets concentrically: there is no chain to walk and so no walk direction to + // mistake, and its own side is read as "outside the current radius". A step past a ring + // smaller than the distance lands beyond the centre, which reads as outside and would turn + // an inward ladder round into a growing one instead of letting it run out of room. Its + // signed distance already says which way, so leave the side to it. + let index = sk.curve_index(rung.first()?)?; + let kind = &sk.curves.get(index)?.kind; + if matches!(kind, CurveKind::Circle { .. }) { + return None; + } + let (from, to) = sk.offset_dimension_points(rung.first()?)?; + if from.dist(to) <= TOL { + return None; + } + let step = to - from; + // An arc's side is inside or outside its circle, and the same trap as the ring's waits + // there: a whole step toward the centre past an arc smaller than the distance lands beyond + // the centre and reads as outside, so the ladder turned round onto an earlier instance. + // Stop halfway to the centre instead, still inside, and let the arc run out of room. + if let CurveKind::Arc { c, .. } = *kind + && let Some(centre) = sk.points.get(c).map(|p| p.pos) + { + let r = to.dist(centre); + if step.dot(centre - to) > 0.0 && step.len() >= r * 0.5 { + return Some(to + step.normalized()? * (r * 0.5)); + } + } + Some(to + step) +} + +/// What one side of a rung leaves for the next: the curves to offset again, its own signed +/// distance, and the dimension its whole ladder is driven by. +fn offset_leaves(side: &Side, fallback: &str) -> (Vec, f64, String) { + (side.curves.clone(), side.distance, side.param.clone().unwrap_or_else(|| fallback.to_string())) +} + +/// Every offset of one connected source group: the first rung at the distances asked for, then +/// one more rung per extra instance, each offsetting the rung before it the same way and the +/// same distance again, so instance n stands n distances from the curves picked. Each side comes +/// back paired with the instance it belongs to, and the first rung's sources come with them, so +/// the caller can take those out of the selection it is still working through. +fn offset_ladder( + sk: &mut Sketch, + cmd: &str, + ids: &[String], + eligible: &std::collections::HashSet, + options: OffsetOptions, + instances: usize, + names: &[String], +) -> Result<(Vec<(usize, Side)>, Vec)> { + let primary = names.first().cloned().ok_or_else(|| bad(cmd, "offset has no driving dimension"))?; + let (first, sources) = offset_rung(sk, cmd, ids, eligible, options, names)?; + let mut rung: Vec<(Vec, f64, String)> = first.iter().map(|side| offset_leaves(side, &primary)).collect(); + let mut sides: Vec<(usize, Side)> = first.into_iter().map(|side| (1, side)).collect(); + for instance in 2..=instances { + let mut next = Vec::new(); + for (curves, distance, name) in &rung { + // One side at a time from here: the side this rung follows is the whole of its + // direction, so `side`, `symmetric` and `distance2` had their say in the first rung. + let beyond = offset_beyond(sk, curves); + let step = OffsetOptions { side: beyond, chain: false, distance: *distance, symmetric: false, distance2: None }; + // Which instance ran out of room is the whole of the answer, so the refusal names it + // in front of the reason, rather than wrapping one "invalid parameters" in another. + let (made, _) = offset_rung(sk, cmd, curves, eligible, step, std::slice::from_ref(name)).map_err(|error| { + let reason = match &error { + crate::EngineError::BadParams { msg, .. } => msg.clone(), + other => other.to_string(), + }; + bad(cmd, format!("instance {instance} of {instances}: {reason}")) + })?; + next.extend(made.iter().map(|side| offset_leaves(side, name))); + sides.extend(made.into_iter().map(|side| (instance, side))); + } + rung = next; + } + Ok((sides, sources)) +} + fn offset(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.offset"; let ids = string_list(cmd, p, "curves")?; @@ -2326,6 +2951,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { if symmetric && side.is_some() { return Err(bad(cmd, "`symmetric` offsets both sides, so `side` has no side left to pick: drop one of them")); } + let instances = offset_instances(s, p, cmd)?; let ((sides, param, param2), info) = edit(s, p, cmd, true, |sk, doc| { sk.refresh_offsets()?; let rep = solve_current(sk, doc)?; @@ -2340,41 +2966,8 @@ fn offset(s: &mut Session, p: &Value) -> Result { let mut pending = ids.clone(); let mut sides = Vec::new(); while !pending.is_empty() { - let mut group = offset_group(sk, &pending, &eligible, OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 })?; - let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?; - let sources = sk - .offsets - .iter() - .find(|o| o.owns_output(output)) - .map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::>()) - .or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()])) - .or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone())) - .ok_or_else(|| bad(cmd, "offset association is missing"))?; - // An offset of infinite lines is infinite lines too (#1359). - let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite)); - if infinite { - for id in group.iter().flat_map(|side| side.curves.iter()) { - if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c)) - && matches!(cu.kind, CurveKind::Line { .. }) - { - cu.infinite = true; - cu.construction = true; - } - } - } - for (index, side) in group.iter_mut().enumerate() { - // A trimmed offset is not linked to its source: it has no distance to drive. - if side.unlinked_sources.is_some() { - continue; - } - let name = if index == 1 { param2.as_ref().unwrap_or(¶m) } else { ¶m }; - let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?; - side.constraints.push(sk.add_constraint( - ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 }, - Some(name.clone()), - )?); - side.param = Some(name.clone()); - } + let options = OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 }; + let (group, sources) = offset_ladder(sk, cmd, &pending, &eligible, options, instances, &made)?; let before = pending.len(); pending.retain(|id| !sources.contains(id)); if pending.len() == before { @@ -2383,31 +2976,31 @@ fn offset(s: &mut Session, p: &Value) -> Result { sides.extend(group); } // Parameters made for distances that only trimmed (unlinked) offsets used drive nothing. - let used = |name: &String| sides.iter().any(|side: &Side| side.param.as_ref() == Some(name)); + let used = |name: &String| sides.iter().any(|(_, side): &(usize, Side)| side.param.as_ref() == Some(name)); let param = used(¶m).then_some(param); let param2 = param2.filter(|name| used(name)); doc.params.retain(|p| !made.contains(&p.name) || param.as_ref() == Some(&p.name) || param2.as_ref() == Some(&p.name)); Ok((sides, param, param2)) })?; - let curves: Vec<&String> = sides.iter().flat_map(|side| side.curves.iter()).collect(); - let constraints: Vec<&String> = sides.iter().flat_map(|side| side.constraints.iter()).collect(); + let curves: Vec<&String> = sides.iter().flat_map(|(_, side)| side.curves.iter()).collect(); + let constraints: Vec<&String> = sides.iter().flat_map(|(_, side)| side.constraints.iter()).collect(); let each: Vec = sides .iter() - .map(|side| { - let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param}); + .map(|(instance, side)| { + let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param, "instance": instance}); if let Some(association) = &side.association { entry["association"] = json!(association); } entry }) .collect(); - let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param}); + let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param,"instances":instances}); if let Some(param2) = param2 { response["param2"] = json!(param2); } - // One side keeps the single `association` it always returned. Two sides have one each, in - // `sides`, so there is no single association left to name. - if let [only] = sides.as_slice() + // One side keeps the single `association` it always returned. Two sides, or an instance + // behind another, have one each in `sides`, so there is no single association left to name. + if let [(_, only)] = sides.as_slice() && let Some(association) = &only.association { response["association"] = json!(association); @@ -2853,20 +3446,52 @@ fn release_origin_holds(sk: &mut Sketch, pts: &[usize]) { ); } +/// Separate drawn wires from planar entities. Their fit points use either the owner's local +/// frame or the legacy world frame, so each must turn about the sketch plane in that frame. +fn drawn_copy_selection(s: &Session, p: &Value, ids: Vec) -> Result<(Vec, Vec<(Wire, Plane)>)> { + let cmd = "sketch.move"; + let id = sketch_store::target(s, p, cmd)?; + let sk = sketch_store::read(&s.doc, id)?; + let mut planar = Vec::new(); + let mut drawn: Vec<(Wire, Plane)> = Vec::new(); + for entity in ids { + let Some(wire) = sk.wires.iter().find(|w| w.id == entity) else { + planar.push(entity); + continue; + }; + if wire.link.is_some() || wire.fit.is_empty() { + return Err(bad(cmd, "Copy supports drawn 3D curves; reference wires cannot be copied")); + } + if drawn.iter().any(|(w, _)| w.id == entity) { + continue; + } + let plane = match wire.space { + WireSpace::Component => s.model.state().sketch(id).map(|sk| sk.plane), + WireSpace::World => s.world_state()?.sketch(id).map(|sk| sk.plane), + } + .ok_or_else(|| bad(cmd, "sketch plane is unavailable"))?; + drawn.push((wire.clone(), plane)); + } + Ok((planar, drawn)) +} + fn move_copy(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.move"; let t = if p.get("translate").is_some() { req_vec2(cmd, p, "translate")? } else { Vec2::ZERO }; let ang = if p.get("angle").is_some() { num(p, "angle").ok_or_else(|| bad(cmd, "`angle` must be finite"))? } else { 0.0 }.to_radians(); let copy = bool_(p, "copy").unwrap_or(false); let rotate_constraints = bool_(p, "rotate_constraints").unwrap_or(true); + let selection = string_list(cmd, p, "entities")?; + let (planar, drawn) = if copy { drawn_copy_selection(s, p, selection)? } else { (selection, Vec::new()) }; let (out, info) = edit(s, p, cmd, false, |sk, doc| { - let (mut cs, mut ps) = entities(sk, p, cmd)?; + let (mut cs, mut ps) = + if planar.is_empty() && !drawn.is_empty() { (Vec::new(), Vec::new()) } else { entities(sk, &json!({"entities": planar}), cmd)? }; let c = if p.get("center").is_some() { point_or_ref(sk, p, "center", cmd)? } else { Vec2::ZERO }; let rot = rotate(c, ang); let f = move |q: Vec2| rot(q) + t; let mut links = Vec::new(); - for entity in string_list(cmd, p, "entities")? { - if let Some(link) = super::sketch_create::text_link(sk, &entity) + for entity in &planar { + if let Some(link) = super::sketch_create::text_link(sk, entity) && !links.iter().any(|old| old == link) { links.push(link.to_owned()); @@ -2881,7 +3506,12 @@ fn move_copy(s: &mut Session, p: &Value) -> Result { if copy { let (mut m, _) = copy_through(sk, &cs, &ps, &f, false, &|_| false, 1.0)?; m.extend(text_curves); - return Ok(ids_of(sk, &m)); + let mut ids = ids_of(sk, &m); + for (wire, plane) in &drawn { + let fit: Vec<_> = wire.fit.iter().map(|&q| plane.to_world(f(plane.to_local(q))) + plane.normal() * plane.height(q)).collect(); + ids.push(if wire.arc.is_some() { sk.add_drawn_arc_in(&fit, wire.space)? } else { sk.add_drawn_wire_in(&fit, wire.space)? }); + } + return Ok(ids); } transform_in_place(sk, &cs, &ps, &f, 1.0, cmd)?; if rotate_constraints { @@ -2908,17 +3538,76 @@ fn transform(s: &mut Session, p: &Value) -> Result { None => 0.0, }; let t = if p.get("translate").is_some() { req_vec2(cmd, p, "translate")? } else { Vec2::ZERO }; - let (out, info) = edit(s, p, cmd, false, |sk, _| { + let (out, info) = edit(s, p, cmd, false, |sk, doc| { let (cs, ps) = entities(sk, p, cmd)?; let c = if p.get("center").is_some() { point_or_ref(sk, p, "center", cmd)? } else { Vec2::ZERO }; let rot = rotate(c, ang); let f = move |q: Vec2| rot(c + (q - c) * k) + t; transform_in_place(sk, &cs, &ps, &f, k, cmd)?; + let moved = involved_points(sk, &cs, &ps); + rotate_axis_constraints(sk, doc, &moved, ang)?; + scale_dimensions(sk, doc, &cs, &moved, k)?; Ok(ids_of(sk, &cs)) })?; + s.doc_mut().prune_model_params(); Ok(json!({"curves": out, "sketch": info})) } +/// The driving lengths wholly inside a transformed selection scale with it. Keep formulas +/// tied to their user parameters, and compensate references between scaled dimensions so a +/// dimension such as `d1 / 2` does not get the factor twice. +fn scale_dimensions(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, curves: &[usize], points: &[usize], factor: f64) -> Result<()> { + if factor == 1.0 { + return Ok(()); + } + let selected: Vec = sk + .constraints + .iter() + .enumerate() + .filter(|(_, c)| { + let pts = sk.constraint_points(&c.kind); + !c.driven + && c.kind.is_dimension() + && !c.kind.is_angle() + && !pts.is_empty() + && pts.iter().all(|p| points.contains(p)) + // A circle's centre may move with another curve while its radius stays put. + && c.kind.indices().1.iter().all(|i| { + curves.contains(i) + || !matches!(sk.curves.get(*i).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Ellipse { .. })) + }) + }) + .map(|(i, _)| i) + .collect(); + let mut expressions = std::collections::BTreeMap::new(); + for i in selected { + let Some(c) = sk.constraints.get_mut(i) else { continue }; + if let Some(value) = c.kind.value() { + c.kind.set_value(value * factor); + } + if let Some(name) = &c.param + && let Some(param) = doc.param(name) + { + let expression = if solidcraft_doc::expr::references(¶m.expr).is_empty() { + format!("{} mm", doc.eval(name, solidcraft_doc::expr::Kind::Length)? * factor) + } else { + let formula = param.expr.trim().strip_prefix('=').unwrap_or(¶m.expr); + format!("({formula}) * {factor}") + }; + expressions.insert(name.clone(), expression); + } + } + for (name, mut expression) in expressions.clone() { + for reference in solidcraft_doc::expr::references(&expression) { + if expressions.contains_key(&reference) { + expression = solidcraft_doc::expr::rename_reference(&expression, &reference, &format!("({reference} / {factor})")); + } + } + doc.set_param(&name, &expression, None, None)?; + } + Ok(()) +} + fn scale(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.scale"; let k = num(p, "factor").filter(|k| *k > 1e-9 && *k < 1e6).ok_or_else(|| bad(cmd, "`factor` must be a positive number"))?; diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 20ef7081e..6b67b6893 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, CurveKind}; use crate::Session; @@ -40,6 +41,66 @@ fn close(a: f64, b: f64) -> bool { (a - b).abs() < 1e-6 } +fn assert_closed_offset(sk: &solidcraft_sketch::Sketch, curves: &[String]) { + assert!(!curves.is_empty(), "an offset boundary must contain curves"); + let ends: Vec<_> = curves.iter().map(|id| sk.curves[sk.curve_index(id).unwrap()].kind.ends().unwrap()).collect(); + let mut adjacency = std::collections::BTreeMap::>::new(); + for (edge, &(a, b)) in ends.iter().enumerate() { + assert_ne!(a, b, "offset edge must have distinct endpoints"); + adjacency.entry(a).or_default().push(edge); + adjacency.entry(b).or_default().push(edge); + } + for (point, edges) in &adjacency { + assert_eq!(edges.len(), 2, "offset corner {point} must be shared by two curves"); + } + let mut visited = std::collections::BTreeSet::new(); + let mut pending = vec![0]; + while let Some(edge) = pending.pop() { + if visited.insert(edge) { + let (a, b) = ends[edge]; + pending.extend(&adjacency[&a]); + pending.extend(&adjacency[&b]); + } + } + assert_eq!(visited.len(), ends.len(), "all offset curves must belong to one connected loop"); +} + +#[test] +#[should_panic(expected = "all offset curves must belong to one connected loop")] +fn closed_offset_assertion_rejects_disconnected_loops() { + let mut sk = solidcraft_sketch::Sketch::new(); + let mut curves = Vec::new(); + for x in [0.0, 20.0] { + let a = sk.add_point(Vec2::new(x, 0.0), None).unwrap(); + let b = sk.add_point(Vec2::new(x + 10.0, 0.0), None).unwrap(); + let c = sk.add_point(Vec2::new(x, 10.0), None).unwrap(); + for (p, q) in [(a, b), (b, c), (c, a)] { + let edge = sk.add_line_pts(p, q, None).unwrap(); + curves.push(sk.curves[edge].id.clone()); + } + } + assert_closed_offset(&sk, &curves); +} + +#[test] +fn offset_chain_resolves_transitive_coincidence_and_stops_at_branches() { + let mut sk = solidcraft_sketch::Sketch::new(); + for xy in [[0., 0.], [10., 0.], [10., 0.], [20., 0.], [10., 0.], [10., 10.], [10., 0.]] { + sk.add_point(Vec2::new(xy[0], xy[1]), None).unwrap(); + } + let a = sk.add_line_pts(0, 1, None).unwrap(); + let b = sk.add_line_pts(2, 3, None).unwrap(); + let c = sk.add_line_pts(4, 5, None).unwrap(); + // Equal coordinates do not connect curves without shared points or constraints. + assert_eq!(super::chain(&sk, a, &[a, b]), (vec![(a, true)], false)); + sk.add_constraint(ConstraintKind::Coincident { p: 1, q: 6 }, None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: 2, q: 6 }, None).unwrap(); + assert_eq!(super::chain(&sk, a, &[a, b]), (vec![(a, true), (b, true)], false)); + sk.add_constraint(ConstraintKind::Coincident { p: 4, q: 6 }, None).unwrap(); + assert_eq!(super::chain(&sk, a, &[a, b, c]), (vec![(a, true)], false)); + assert_eq!(super::chain(&sk, a, &[a, b]), (vec![(a, true), (b, true)], false)); +} + #[test] fn explicit_freeform_break_preserves_exact_geometry_and_undo() { for (command, params) in [ @@ -136,6 +197,87 @@ fn analytic_trim_and_break_use_freeform_cutters() { assert!(sk.shape(ci).unwrap().dist(Vec2::new(-5.0, 0.0)) < 1e-6); } +/// #10851: an endpoint's tangent must stay with the arc piece that owns that endpoint, +/// including when the endpoints are separate points joined by a Coincident constraint. +#[test] +fn trim_keeps_endpoint_tangency_on_its_arc_piece() { + for path in [false, true] { + for separate in [false, true] { + for at_start in [false, true] { + for reverse in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.arc.center_point", json!({"center": [0,0], "start": [50,0], "end": [-50,0]})); + let endpoint = if at_start { "a1.start" } else { "a1.end" }; + let x = if at_start { 50 } else { -50 }; + let start = if separate { json!([x, 0]) } else { json!(endpoint) }; + run(&mut s, "sketch.line", json!({"points": [start, [x,-30]], "connect": false, "infer": false})); + if separate { + run(&mut s, "sketch.constraint.coincident", json!({"a": "l1.start", "b": endpoint})); + } + let (a, b) = if reverse { ("a1", "l1") } else { ("l1", "a1") }; + let tangent = run(&mut s, "sketch.constraint.tangent", json!({"a": a, "b": b}))["constraint"].as_str().unwrap().to_string(); + run(&mut s, "sketch.dimension", json!({"entities": ["a1"], "type": "radius", "value": "50"})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "30"})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["origin", "a1.start"], "mode": "horizontal"})); + for x in [-10, 10] { + run(&mut s, "sketch.line", json!({"points": [[x,40],[x,60]]})); + } + run(&mut s, "sketch.constraint.fix", json!({"entities": ["l2", "l3"]})); + assert_eq!(run(&mut s, "sketch.solve", json!({}))["dof"], 1); + let before = sketch(&s); + let undo = s.undo.len(); + let result = if path { + run(&mut s, "sketch.trim.path", json!({"points": [[0,45],[0,55]]})) + } else { + run(&mut s, "sketch.trim", json!({"curve": "a1", "at": [0,50]})) + }; + assert_eq!(result["sketch"]["dof"], 1, "path={path}, separate={separate}, at_start={at_start}, reverse={reverse}: {result}"); + assert_eq!(s.undo.len(), undo + 1); + let after = sketch(&s); + let ci = after.curve_index(if at_start { "a1" } else { "a3" }).unwrap(); + let li = after.curve_index("l1").unwrap(); + assert!(after.constraints.iter().any( + |k| k.id == tangent && matches!(k.kind, ConstraintKind::Tangent { a, b } if (a == ci && b == li) || (a == li && b == ci)) + )); + let at = |id: &str| after.point(after.resolve_point(id).unwrap()).unwrap(); + assert!(at(endpoint).dist(at("l1.start")) < 1e-8); + let radius = at("l1.start") - at("a1.center"); + let line = at("l1.end") - at("l1.start"); + assert!(radius.dot(line).abs() < 1e-6, "the line stays tangent to the circle"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(sketch(&s), after); + } + } + } + } +} + +#[test] +fn trim_keeps_or_removes_tangency_with_the_original_end() { + for remove_tangent_end in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.arc.center_point", json!({"center": [0,0], "start": [50,0], "end": [-50,0]})); + run(&mut s, "sketch.line", json!({"points": ["a1.end", [-50,-30]]})); + let tangent = run(&mut s, "sketch.constraint.tangent", json!({"a": "l1", "b": "a1"}))["constraint"].as_str().unwrap().to_string(); + run(&mut s, "sketch.line", json!({"points": [[0,40],[0,60]]})); + let before = sketch(&s); + let x = if remove_tangent_end { -40 } else { 40 }; + run(&mut s, "sketch.trim", json!({"curve": "a1", "at": [x,30]})); + let after = sketch(&s); + assert!(after.curve_index("a1").is_some(), "the original curve ID survives either end trim"); + assert_eq!(after.constraints.iter().any(|k| k.id == tangent), !remove_tangent_end); + if !remove_tangent_end { + let arc = after.curve_index("a1").unwrap(); + let line = after.curve_index("l1").unwrap(); + assert!(after.constraints.iter().any(|k| k.id == tangent && matches!(k.kind, ConstraintKind::Tangent { a, b } if a == line && b == arc))); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s), before); + } +} + #[test] fn trim_extend_break() { let mut s = new_sketch(); @@ -222,6 +364,43 @@ fn an_arc_extended_from_an_end_a_tangent_line_ends_on_adds_no_arc_of_no_length() } } +/// #7410: two lines drawn as one chain share their corner point. Break at that point gives the +/// picked line its own end there: both stay in place, and each can move without the other. +#[test] +fn break_at_a_shared_point_separates_the_curves_that_meet_there() { + let mut s = new_sketch(); + let chain = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 0], [20, 10]]}))["curves"]); + let (first, second) = (chain[0].clone(), chain[1].clone()); + let ends = |s: &Session, id: &str| { + let sk = sketch(s); + let (a, b) = sk.curves[sk.curve_index(id).unwrap()].kind.ends().unwrap(); + (a, b, sk.point(a).unwrap(), sk.point(b).unwrap()) + }; + let (_, shared, ..) = ends(&s, &first); + assert_eq!(ends(&s, &second).0, shared, "the chain shares its corner"); + let points = sketch(&s).points.len(); + + let out = run(&mut s, "sketch.break", json!({"curve": second, "at": [20, 0]})); + assert_eq!(ids(&out["curves"]), vec![second.clone()], "{out}"); + let (own, _, at, far) = ends(&s, &second); + let (_, kept, ..) = ends(&s, &first); + assert_eq!(kept, shared, "the first line keeps the point"); + assert_ne!(own, shared, "the second line has its own end"); + assert_eq!(sketch(&s).points.len(), points + 1); + assert!(at.dist(Vec2::new(20.0, 0.0)) < 1e-9 && far.dist(Vec2::new(20.0, 10.0)) < 1e-9, "the second line stays put: {at:?} {far:?}"); + let own_id = sketch(&s).points[own].id.clone(); + assert_eq!(own_id, format!("{second}.start")); + + // Moving the second line's new end leaves the first line where it was. + run(&mut s, "sketch.move_point", json!({"point": own_id, "to": [25, 0]})); + let (_, _, a, b) = ends(&s, &first); + assert!(a.dist(Vec2::new(0.0, 0.0)) < 1e-9 && b.dist(Vec2::new(20.0, 0.0)) < 1e-9, "{a:?} {b:?}"); + + // A point only one curve ends at has nothing to separate: Break there still refuses. + let lone = s.execute("sketch.break", &json!({"curve": second, "at": [20, 10]})); + assert!(lone.is_err(), "{lone:?}"); +} + #[test] fn trim_circle_makes_an_arc_and_a_profile() { let mut s = new_sketch(); @@ -578,6 +757,71 @@ fn exact_extend_takes_one_of_two_stops_at_the_same_distance() { assert!(end.dist(Vec2::new(10.0, 0.0)) < 1e-6, "{end:?}"); } +#[test] +fn extend_does_not_treat_a_line_end_inside_a_circle_as_lying_on_it() { + // #9731: the "lies on a circle" test was true for every end *inside* a circle, so a large + // construction circle around the drawing made Extend treat a free end as held and lay a + // loose new line instead of lengthening the line. Only an end on the circle is held. + let mut s = new_sketch(); + let l1 = ids(&run(&mut s, "sketch.line", json!({"points":[[0,5],[10,5]],"connect":false,"infer":false}))["curves"])[0].clone(); + let l2 = ids(&run(&mut s, "sketch.line", json!({"points":[[20,-10],[20,20]],"connect":false,"infer":false}))["curves"])[0].clone(); + run(&mut s, "sketch.circle.center", json!({"center":[5,5],"radius":60})); + run(&mut s, "sketch.extend", json!({"curve": l1, "at": [9,5]})); + let sk = sketch(&s); + assert_eq!(sk.curves.len(), 3, "the circle around the drawing must not add a line"); + let end = sk.resolve_point(&format!("{l1}.end")).expect("l1's end"); + assert!(sk.point(end).is_some_and(|p| p.dist(Vec2::new(20.0, 5.0)) < 1e-6), "l1 reaches l2: {:?}", sk.point(end)); + let l2i = sk.curve_index(&l2).expect("l2"); + assert!( + sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::PointOnCurve { p, c } if p == end && c == l2i)), + "the extended end is held on l2" + ); + + // The same end deep inside a far larger circle behaves the same way. + let mut s = new_sketch(); + let l1 = ids(&run(&mut s, "sketch.line", json!({"points":[[0,5],[10,5]],"connect":false,"infer":false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points":[[20,-10],[20,20]],"connect":false,"infer":false})); + run(&mut s, "sketch.circle.center", json!({"center":[100,100],"radius":200})); + run(&mut s, "sketch.extend", json!({"curve": l1, "at": [9,5]})); + let sk = sketch(&s); + assert_eq!(sk.curves.len(), 3, "an end inside a circle is not held by it"); + let end = sk.resolve_point(&format!("{l1}.end")).expect("l1's end"); + assert!(sk.point(end).is_some_and(|p| p.dist(Vec2::new(20.0, 5.0)) < 1e-6), "{:?}", sk.point(end)); + + // An end that lies ON the circle is still held: Extend adds a new line from it. + let mut s = new_sketch(); + let l1 = ids(&run(&mut s, "sketch.line", json!({"points":[[0,5],[10,5]],"connect":false,"infer":false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points":[[20,-10],[20,20]],"connect":false,"infer":false})); + run(&mut s, "sketch.circle.center", json!({"center":[5,5],"radius":5})); + run(&mut s, "sketch.extend", json!({"curve": l1, "at": [9,5]})); + let sk = sketch(&s); + assert_eq!(sk.curves.len(), 4, "an end on the circle stays put and gains a new line"); + let end = sk.resolve_point(&format!("{l1}.end")).expect("l1's end"); + assert!(sk.point(end).is_some_and(|p| p.dist(Vec2::new(10.0, 5.0)) < 1e-6), "l1 stays put: {:?}", sk.point(end)); +} + +#[test] +fn extend_from_a_held_end_is_pinned_to_the_curve_it_stops_on() { + // The end being extended carries geometry (another line meets it there), so the extension is + // a new line. It stops in the middle of a third curve: the new end point is held on that + // curve, as the free-end path holds its end, instead of lying loose over it. + let mut s = new_sketch(); + let both = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[10,0],[10,10]],"connect":false,"infer":false}))["curves"]); + let l1 = both[0].clone(); + let wall = ids(&run(&mut s, "sketch.line", json!({"points":[[20,-10],[20,10]],"connect":false,"infer":false}))["curves"])[0].clone(); + run(&mut s, "sketch.extend", json!({"curve": l1, "at": [10,0]})); + let sk = sketch(&s); + assert_eq!(sk.curves.len(), 4, "the held end stays and a new line is added"); + let new_line = sk.curves.last().expect("the new line"); + let CurveKind::Line { b, .. } = new_line.kind else { panic!("the new curve is a line: {new_line:?}") }; + assert!(sk.point(b).is_some_and(|p| p.dist(Vec2::new(20.0, 0.0)) < 1e-6), "the new line stops on the wall: {:?}", sk.point(b)); + let walli = sk.curve_index(&wall).expect("the wall"); + assert!( + sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::PointOnCurve { p, c } if p == b && c == walli)), + "the new end point is held on the curve it stops on" + ); +} + #[test] fn fillet_keeps_expression_corner_when_parameter_changes() { let mut s = new_sketch(); @@ -643,6 +887,133 @@ fn fillet_and_chamfers() { assert!(s.execute("sketch.fillet", &json!({"a": l[0], "b": l[2], "radius": 1})).is_err(), "no shared corner"); } +/// #2500, #5951, #7805: the second fillet of a side with a radius of half its length takes all +/// that is left of the line, so the line goes and the two arcs meet: a 20 × 10 rectangle with +/// r = 5 becomes a slot, a 10 × 10 square a circle. +#[test] +fn fillets_of_half_a_side_meet_and_the_side_goes() { + for (w, h, area) in [(20.0, 10.0, 10.0 * 10.0 + std::f64::consts::PI * 25.0), (10.0, 10.0, std::f64::consts::PI * 25.0)] { + let mut s = new_sketch(); + let l = ids(&run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [w, h]}))["curves"]); + let mut last = Value::Null; + for k in 0..4 { + last = run(&mut s, "sketch.fillet", json!({"a": l[k], "b": l[(k + 1) % 4], "radius": 5})); + } + assert_eq!(last["sketch"]["solved"], true, "{last}"); + let sk = sketch(&s); + let lines = sk.curves.iter().filter(|c| !c.construction && matches!(c.kind, CurveKind::Line { .. })).count(); + let arcs = sk.curves.iter().filter(|c| matches!(c.kind, CurveKind::Arc { .. })).count(); + assert_eq!((lines, arcs), (if w > h { 2 } else { 0 }, 4), "{w} x {h}"); + let a = profiles(&s); + assert_eq!(a.len(), 1, "{a:?}"); + assert!(close(a[0], area), "{w} x {h}: {a:?}"); + } + // All four corners in one call: the arcs keep one radius dimension and equal constraints + // although the short sides go in between. + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})); + let f = run(&mut s, "sketch.fillet", json!({"points": ["l1.start", "l1.end", "l2.end", "l3.end"], "radius": 5})); + assert_eq!(ids(&f["curves"]).len(), 4, "{f}"); + assert_eq!(f["sketch"]["solved"], true, "{f}"); + let a = profiles(&s); + assert!(a.len() == 1 && close(a[0], 100.0 + std::f64::consts::PI * 25.0), "{a:?}"); + let equal = sketch(&s).constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Equal { .. })).count(); + assert!(equal >= 3, "the arcs stay equal to the first: {equal}"); + // A radius past the line's length is still refused. + let mut s = new_sketch(); + let l = ids(&run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]}))["curves"]); + run(&mut s, "sketch.fillet", json!({"a": l[0], "b": l[1], "radius": 5})); + assert!(s.execute("sketch.fillet", &json!({"a": l[1], "b": l[2], "radius": 5.1})).is_err()); +} + +/// A rectangle drawn as four separate lines (each its own points, the corners held by +/// coincident constraints) offsets as one closed shape, every side the same way. Its lines used +/// to be offset one by one, each to the left of the way it was drawn: both horizontals moved up +/// and the corners came apart. +#[test] +fn offset_of_lines_drawn_one_by_one_stays_a_closed_shape() { + let mut s = new_sketch(); + for pts in [[[0, 0], [20, 0]], [[20, 0], [20, 10]], [[0, 10], [20, 10]], [[0, 0], [0, 10]]] { + run(&mut s, "sketch.line", json!({"points": pts})); + } + let r = run(&mut s, "sketch.offset", json!({"curves": ["l1", "l2", "l3", "l4"], "distance": 2})); + let made: Vec = r["curves"].as_array().unwrap().iter().map(|c| c.as_str().unwrap().to_string()).collect(); + assert_eq!(made.len(), 4, "{r}"); + let sk = sketch(&s); + let ends: Vec<(Vec2, Vec2)> = made + .iter() + .map(|id| match sk.curves[sk.curve_index(id).unwrap()].kind { + CurveKind::Line { a, b } => (sk.points[a].pos, sk.points[b].pos), + _ => panic!("{id} is not a line"), + }) + .collect(); + // Every side 2 in: the bottom up, the top down, the sides in. + let mut ys: Vec = ends.iter().filter(|e| (e.0.y - e.1.y).abs() < 1e-9).map(|e| e.0.y).collect(); + let mut xs: Vec = ends.iter().filter(|e| (e.0.x - e.1.x).abs() < 1e-9).map(|e| e.0.x).collect(); + ys.sort_by(f64::total_cmp); + xs.sort_by(f64::total_cmp); + assert!(ys.len() == 2 && (ys[0] - 2.0).abs() < 1e-9 && (ys[1] - 8.0).abs() < 1e-9, "{ys:?}"); + assert!(xs.len() == 2 && (xs[0] - 2.0).abs() < 1e-9 && (xs[1] - 18.0).abs() < 1e-9, "{xs:?}"); + assert_closed_offset(&sk, &made); +} + +#[test] +fn offset_of_trimmed_circle_and_fillet_chains_coincident_ends() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); + run(&mut s, "sketch.line", json!({"points": [[-20, 0], [20, 0]]})); + run(&mut s, "sketch.trim", json!({"curve": "c1", "at": [0, -10]})); + run(&mut s, "sketch.trim", json!({"curve": "l1", "at": [-15, 0]})); + run(&mut s, "sketch.trim", json!({"curve": "l1", "at": [15, 0]})); + // A point on the line alone is a different case: #5019 explicitly joins these ends + // with Coincident, while the fillet makes its own two shared ends. + run(&mut s, "sketch.constraint.coincident", json!({"a": "c1.end", "b": "l1.start"})); + let fillet = run(&mut s, "sketch.fillet", json!({"a": "c1", "b": "l1", "radius": 1})); + let arc = ids(&fillet["curves"])[0].clone(); + assert_eq!(profiles(&s).len(), 1); + let r = run(&mut s, "sketch.offset", json!({"curves": ["c1", "l1", arc], "distance": -0.5})); + assert_eq!(r["sides"].as_array().unwrap().len(), 1, "{r}"); + let made = ids(&r["curves"]); + assert_eq!(made.len(), 3, "{r}"); + let sk = sketch(&s); + assert_closed_offset(&sk, &made); + let mut radii: Vec<_> = made + .iter() + .filter_map(|id| match sk.curves[sk.curve_index(id).unwrap()].kind { + CurveKind::Arc { c, a, .. } => Some(sk.points[c].pos.dist(sk.points[a].pos)), + _ => None, + }) + .collect(); + radii.sort_by(f64::total_cmp); + assert!(radii.len() == 2 && close(radii[0], 1.5) && close(radii[1], 10.5), "{radii:?}"); +} + +#[test] +fn offset_of_separately_drawn_fillet_and_chamfer_stays_closed() { + let mut s = new_sketch(); + for points in [[[0, 0], [20, 0]], [[20, 0], [20, 10]], [[0, 10], [20, 10]], [[0, 0], [0, 10]]] { + run(&mut s, "sketch.line", json!({"points": points})); + } + run(&mut s, "sketch.fillet", json!({"a": "l1", "b": "l2", "radius": 2})); + run(&mut s, "sketch.chamfer.equal_distance", json!({"a": "l3", "b": "l4", "distance": 1})); + let sources: Vec<_> = sketch(&s).curves.iter().map(|c| c.id.clone()).collect(); + assert_eq!(profiles(&s).len(), 1); + let r = run(&mut s, "sketch.offset", json!({"curves": sources, "distance": 1})); + assert_eq!(r["sides"].as_array().unwrap().len(), 1, "{r}"); + let made = ids(&r["curves"]); + assert_eq!(made.len(), 6, "{r}"); + let sk = sketch(&s); + assert_closed_offset(&sk, &made); + let radii: Vec<_> = made + .iter() + .filter_map(|id| match sk.curves[sk.curve_index(id).unwrap()].kind { + CurveKind::Arc { c, a, .. } => Some(sk.points[c].pos.dist(sk.points[a].pos)), + _ => None, + }) + .collect(); + assert!(radii.len() == 1 && close(radii[0], 1.0), "{radii:?}"); +} + #[test] fn offset_chain_mirror_patterns_move_scale() { let mut s = new_sketch(); @@ -823,6 +1194,65 @@ fn transform_scales_turns_and_moves_in_one_step() { } } +/// Transform must leave a dimensioned rectangle where its preview put it, rather than letting +/// the old horizontal/vertical relations and size dimensions pull it back (#11617). +#[test] +fn transform_turns_and_scales_a_dimensioned_rectangle() { + for angle in [30.0_f64, 90.0, 180.0] { + let mut s = new_sketch(); + let drawn = run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [25, 12.5]})); + let curves = ids(&drawn["curves"]); + let width = run(&mut s, "sketch.dimension", json!({"entities": [curves[0]], "type": "length", "value": "50 mm"})); + let height = run(&mut s, "sketch.dimension", json!({"entities": [curves[1]], "type": "length", "value": "25 mm"})); + let before = sketch(&s); + let result = run(&mut s, "sketch.transform", json!({"entities": curves, "factor": 2, "angle": angle, "center": [0, 0]})); + assert_eq!(result["sketch"]["solved"], true); + let after = sketch(&s); + let (sin, cos) = angle.to_radians().sin_cos(); + for id in ["p1", "p2", "p3", "p4"] { + let p = before.point(before.resolve_point(id).unwrap()).unwrap(); + let expected = Vec2::new(p.x * cos - p.y * sin, p.x * sin + p.y * cos) * 2.0; + let actual = after.point(after.resolve_point(id).unwrap()).unwrap(); + assert!(actual.dist(expected) < 1e-6, "{angle} degrees, {id}: {actual:?}, expected {expected:?}"); + } + for (dimension, expected) in [(&width, 100.0), (&height, 50.0)] { + let name = dimension["param"].as_str().unwrap(); + assert!(close(s.doc.eval(name, solidcraft_doc::expr::Kind::Length).unwrap(), expected)); + } + assert!(close(profiles(&s)[0], 5000.0)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s).constraints, before.constraints); + assert!(close(profiles(&s)[0], 1250.0)); + run(&mut s, "edit.redo", json!({})); + assert!(close(profiles(&s)[0], 5000.0)); + } +} + +#[test] +fn transform_scales_dimension_formulas_once_and_keeps_unselected_dimensions() { + let mut s = new_sketch(); + run(&mut s, "parameters.add", json!({"name": "width", "expression": "50 mm"})); + let rectangle = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 10], "p1": [60, 35]})); + let curves = ids(&rectangle["curves"]); + let width = run(&mut s, "sketch.dimension", json!({"entities": [curves[0]], "type": "length", "value": "=width"})); + let width_param = width["param"].as_str().unwrap(); + let height = run(&mut s, "sketch.dimension", json!({"entities": [curves[1]], "type": "length", "value": format!("{width_param} / 2")})); + run(&mut s, "sketch.dimension", json!({"entities": [curves[2]], "type": "length", "driven": true})); + let circle = run(&mut s, "sketch.circle.center", json!({"center": [100, 100], "radius": 5})); + let radius = run(&mut s, "sketch.dimension", json!({"entities": [circle["curves"][0]], "type": "radius", "value": "5 mm"})); + let outside = s.doc.param(radius["param"].as_str().unwrap()).unwrap().clone(); + run(&mut s, "sketch.transform", json!({"entities": curves, "factor": 2, "angle": 90, "center": [35, 22.5]})); + let length = solidcraft_doc::expr::Kind::Length; + assert!(close(s.doc.eval("width", length).unwrap(), 50.0), "the user parameter stays unchanged"); + assert!(close(s.doc.eval(width_param, length).unwrap(), 100.0)); + assert!(close(s.doc.eval(height["param"].as_str().unwrap(), length).unwrap(), 50.0)); + assert_eq!(s.doc.param(&outside.name).unwrap(), &outside); + assert!(close(sketch(&s).radius(sketch(&s).curve_index(circle["curves"][0].as_str().unwrap()).unwrap()).unwrap(), 5.0)); + run(&mut s, "parameters.change", json!({"name": "width", "expression": "60 mm"})); + assert!(close(s.doc.eval(width_param, length).unwrap(), 120.0), "the formula still follows its user parameter"); + assert!(close(s.doc.eval(height["param"].as_str().unwrap(), length).unwrap(), 60.0), "dependent dimensions scale only once"); +} + /// #1485: after a circle is trimmed between two construction lines, clicking the trimmed end /// picks the construction line's end lying there, not the arc's own; the tangent arc still starts /// from the trimmed arc, tangent to it. @@ -1085,6 +1515,53 @@ fn centre_circle_through_a_point_keeps_it_on_the_circle() { assert!(!sketch(&s).constraints.iter().any(|k| matches!(k.kind, ConstraintKind::PointOnCurve { c, .. } if c == ci))); } +/// #9858: a 3-point circle drawn on snapped clicks keeps them. Drawn through a line's start, +/// its midpoint and another line's end, the circle stays on those points when the line is +/// dimensioned. +#[test] +fn three_point_circle_keeps_snapped_points() { + let mut s = new_sketch(); + let l = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}))["curves"])[0].clone(); + let v = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 5], [20, 30]]}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.circle.three_point", json!({"p0": format!("{l}.start"), "p1": format!("mid:{l}"), "p2": format!("{v}.end")})); + let c = ids(&r["curves"])[0].clone(); + assert_eq!(ids(&r["constraints"]).len(), 3, "{r}"); + let sk = sketch(&s); + let ci = sk.curve_index(&c).unwrap(); + let on_circle = + |sk: &solidcraft_sketch::Sketch, p: usize, c: usize| sk.constraints.iter().any(|k| k.kind == ConstraintKind::PointOnCurve { p, c }); + let (start, tip) = (sk.resolve_point(&format!("{l}.start")).unwrap(), sk.resolve_point(&format!("{v}.end")).unwrap()); + // The midpoint snap holds its point at the line's midpoint, and the circle keeps it too. + let mid = sk + .constraints + .iter() + .find_map(|k| match k.kind { + ConstraintKind::Midpoint { p, .. } => Some(p), + _ => None, + }) + .expect("midpoint snap point"); + for p in [start, mid, tip] { + assert!(on_circle(&sk, p, ci), "{:?} is not on the circle: {:?}", sk.points[p].id, sk.constraints); + } + // Seeded as the circumcircle of the three clicks. + let (o, rad) = (sk.center(ci).unwrap(), sk.radius(ci).unwrap()); + for p in [start, mid, tip] { + assert!(close(o.dist(sk.points[p].pos), rad), "the circle does not pass its click: {o:?} {rad}"); + } + // Dimensioning the line: the circle stays on the start, midpoint and end. + run(&mut s, "sketch.dimension", json!({"entities": [l], "value": 60})); + let sk = sketch(&s); + let (o, rad) = (sk.center(ci).unwrap(), sk.radius(ci).unwrap()); + for p in [start, mid, tip] { + assert!(close(o.dist(sk.points[p].pos), rad), "the circle left a snapped point: {:?}", sk.points); + } + // Plain positions: nothing to keep. + let r = run(&mut s, "sketch.circle.three_point", json!({"p0": [100, 0], "p1": [110, 0], "p2": [105, 8]})); + let ci = sketch(&s).curve_index(&ids(&r["curves"])[0]).unwrap(); + assert!(ids(&r["constraints"]).is_empty()); + assert!(!sketch(&s).constraints.iter().any(|k| matches!(k.kind, ConstraintKind::PointOnCurve { c, .. } if c == ci))); +} + #[test] fn ellipse_splines_conic() { let pi = std::f64::consts::PI; @@ -1154,7 +1631,7 @@ fn a_point_added_to_a_spline_keeps_its_constraints_and_undoes() { let fit: Vec = old.iter().map(|i| before.point(*i).unwrap()).collect(); let curve = before.exact_segs(si).unwrap(); let off = - |segs: &[solidcraft_geom::Seg2], q: Vec2| segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min); + |segs: &[solidcore_record::Seg2], q: Vec2| segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min); let out = run(&mut s, "sketch.spline.insert_point", json!({"curve": sid, "at": [15, 6]})); let after = sketch(&s); @@ -1193,13 +1670,71 @@ fn a_point_added_to_a_spline_keeps_its_constraints_and_undoes() { assert_eq!(sketch(&s), unchanged, "refusals change nothing"); } +/// Remove Spline Point (#10783): one fit point goes, with the dimension on it. The spline runs +/// through its other points, which stay where they were, and the line joined to its end stays. +/// Undo puts the point back. The end the line joins, a line and an unknown point are refused; a +/// control point spline gives up a point too. +#[test] +fn a_point_removed_from_a_spline_goes_with_its_dimension_and_undoes() { + let mut s = new_sketch(); + let sid = + ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [20, 0], [30, 6]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [format!("{sid}.end"), [40, 6]], "connect": false})); + let sk = sketch(&s); + let si = sk.curve_index(&sid).unwrap(); + let names: Vec = sk.curves[si].kind.point_ids().iter().map(|i| sk.points[*i].id.clone()).collect(); + run(&mut s, "sketch.dimension", json!({"entities": [names[1], names[2]], "value": 12.8})); + let before = sketch(&s); + let at = |sk: &solidcraft_sketch::Sketch, id: &str| sk.point(sk.point_index(id).unwrap()).unwrap(); + + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": sid, "point": names[1]})); + assert_eq!((r["curve"].as_str(), r["point"].as_str(), r["deleted"].as_bool()), (Some(sid.as_str()), Some(names[1].as_str()), Some(true)), "{r}"); + let after = sketch(&s); + assert!(after.point_index(&names[1]).is_none(), "the point went"); + let left: Vec = after.curves[si].kind.point_ids().iter().map(|i| after.points[*i].id.clone()).collect(); + assert_eq!(left, [names[0].clone(), names[2].clone(), names[3].clone()]); + let segs = after.exact_segs(si).unwrap(); + for id in &left { + let q = at(&after, id); + assert!(q.dist(at(&before, id)) < 1e-9, "{id} stays where it was"); + let off = segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min); + assert!(off < 1e-9, "the curve runs through {id}"); + } + assert!(after.constraints.iter().all(|c| c.kind.value().is_none()), "the dimension on the point went"); + let joined = after.curves.iter().any(|c| matches!(c.kind, CurveKind::Line { a, .. } if after.points[a].id == names[3])); + assert!(joined, "the line still starts at the spline's end"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s), before, "undo puts the point back"); + + let line = before.curves.iter().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone(); + for (p, why) in [ + (json!({"curve": sid, "point": format!("{sid}.end")}), "joined"), + (json!({"curve": line, "point": names[0]}), "spline"), + (json!({"curve": sid, "point": "nope"}), "unknown sketch point"), + (json!({"curve": sid}), "`point`"), + ] { + let e = s.execute("sketch.spline.remove_point", &p).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + } + assert_eq!(sketch(&s), before, "refusals change nothing"); + + let cv = + ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [[0, 20], [10, 30], [20, 20]], "connect": false}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": cv, "point": format!("{cv}.start")})); + assert_eq!(r["deleted"], json!(true), "{r}"); + let sk = sketch(&s); + let ci = sk.curve_index(&cv).unwrap(); + let left: Vec = sk.curves[ci].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect(); + assert_eq!(left, [Vec2::new(10.0, 30.0), Vec2::new(20.0, 20.0)]); +} + /// Reverse Spline Direction (#8224): a fit, a control point and a closed spline each run the /// other way along the same path, their ends swapped. Their points, the constraints on them and /// a line joined to an end stay, and undo restores the spline. A line and the source and output /// of an offset are refused. #[test] fn a_reversed_spline_runs_the_other_way_along_the_same_path() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; let mut s = new_sketch(); let fit = ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [25, 2], [30, 6]], "connect": false}))["curves"])[0].clone(); @@ -1428,8 +1963,12 @@ fn free_form_profiles_extrude_exactly() { run(&mut s, "solid.extrude", json!({"distance": 5})); let v = vol(&mut s); assert!((v - pi * 40.0 * 5.0).abs() / (pi * 200.0) < 2e-4, "{v}"); + // An exact ellipse: its side's area is h times the perimeter, 4a E(e), e² = 1 − b²/a² + // (by the Gauss–Kummer series, P = 46.026225), and only the top and bottom are planes. let m = run(&mut s, "inspect.measure", json!({})); - assert_eq!(m["bodies"][0]["faces"], 3, "an exact ellipse: top, bottom and one side ({m})"); + let area = m["bodies"][0]["area_mm2"].as_f64().unwrap_or(f64::NAN); + assert!((area - (2.0 * pi * 40.0 + 5.0 * 46.026_225_191_329_7)).abs() < 1e-4, "{area} ({m})"); + assert_eq!(m["bodies"][0]["face_types"]["plane"], 2, "{m}"); // A region closed by a fit spline and a line. let mut s = new_sketch(); let sp = ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [20, 0]]}))["curves"])[0].clone(); @@ -1439,8 +1978,9 @@ fn free_form_profiles_extrude_exactly() { run(&mut s, "solid.extrude", json!({"distance": 2})); let v = vol(&mut s); assert!((v - a * 2.0).abs() / (a * 2.0) < 2e-4, "{v} vs {}", a * 2.0); + // Exact: the spline's side is curved, the planes are the top, the bottom and the line's side. let m = run(&mut s, "inspect.measure", json!({})); - assert!(m["bodies"][0]["faces"].as_u64().unwrap() <= 5, "{m}"); + assert_eq!(m["bodies"][0]["face_types"]["plane"], 3, "{m}"); } #[test] @@ -1576,7 +2116,7 @@ fn fillet_a_line_and_an_arc() { fn fillet_a_line_and_an_arc_drawn_to_meet_at_a_point() { // #1208: the arc starts at the line's end by coordinates, so the corner is two points held // together by a Coincident constraint. By point and by naming the two curves. - for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"})] { + for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"}), json!({"a": "a1", "b": "l1"})] { let mut s = new_sketch(); run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]})); run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"})); @@ -1603,6 +2143,77 @@ fn fillet_a_line_and_an_arc_drawn_to_meet_at_a_point() { } } +/// #7507: a line drawn on from another line's end by coordinates meets it through a Coincident +/// constraint, and a dimension measures to the second line's own end at that corner. The corner +/// is still rounded, by point and by naming the two lines, and the dimension keeps measuring to +/// the sharp corner. +#[test] +fn fillet_a_coincident_corner_that_a_dimension_measures_to() { + for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "l2"})] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]})); + run(&mut s, "sketch.line", json!({"points": [[40, 0], [100, -30]]})); + run(&mut s, "sketch.dimension", json!({"entities": ["origin", "l2.start"], "type": "horizontal", "value": "40"})); + let mut p = how.clone(); + p["radius"] = json!(5); + let f = run(&mut s, "sketch.fillet", p); + let made = ids(&f["curves"]); + assert_eq!(made.len(), 1, "{how}: {f}"); + let sk = sketch(&s); + let ai = sk.curve_index(&made[0]).unwrap(); + assert!((sk.radius(ai).unwrap() - 5.0).abs() < 1e-7, "{how}"); + // Tangent to both lines: 5 below the first and 5 from the second's line. + let c = sk.center(ai).unwrap(); + let along = Vec2::new(60.0, -30.0).normalized().unwrap(); + assert!((c.y + 5.0).abs() < 1e-6 && ((c - Vec2::new(40.0, 0.0)).cross(along).abs() - 5.0).abs() < 1e-6, "{how}: {c:?}"); + // The dimension still measures 40 to the sharp corner, and the sketch solves. + let info = run(&mut s, "sketch.inspect", json!({})); + assert_eq!(info["status"], "solved", "{how}: {info}"); + let (p, q) = sk + .constraints + .iter() + .find_map(|k| match k.kind { + ConstraintKind::DistanceX { p, q, .. } => Some((p, q)), + _ => None, + }) + .unwrap(); + assert!((sk.point(q).unwrap().x - sk.point(p).unwrap().x - 40.0).abs() < 1e-6, "{how}"); + assert!(sk.point(q).unwrap().dist(Vec2::new(40.0, 0.0)) < 1e-6, "{how}"); + } +} + +#[test] +fn fillet_coincident_line_and_arc_selection_order() { + for held in ["l1.end", "a1.end"] { + for (a, b) in [("l1", "a1"), ("a1", "l1")] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"})); + // Keep the fixed sharp corner in place, whichever endpoint is fixed or picked + // first when rounding the same corner. + run(&mut s, "sketch.constraint.fix", json!({"entity": held})); + let before = serde_json::to_value(sketch(&s)).unwrap(); + let f = run(&mut s, "sketch.fillet", json!({"a": a, "b": b, "radius": 3})); + let sk = sketch(&s); + let ai = sk.curve_index(&ids(&f["curves"])[0]).unwrap(); + let want = Vec2::new(50.0 - 160f64.sqrt(), 3.0); + assert!((sk.radius(ai).unwrap() - 3.0).abs() < 1e-7, "{held}: {a}, {b}"); + assert!(sk.center(ai).unwrap().dist(want) < 1e-6, "{held}: {a}, {b}"); + let fixed = sk + .constraints + .iter() + .find_map(|c| match c.kind { + ConstraintKind::Fix { p } => Some(p), + _ => None, + }) + .unwrap(); + assert!(sk.point(fixed).unwrap().dist(Vec2::new(40.0, 0.0)) < 1e-6); + assert_eq!(run(&mut s, "sketch.inspect", json!({}))["status"], "solved"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before); + } + } +} #[test] fn chamfer_two_lines_drawn_to_meet_at_a_point() { let mut s = new_sketch(); @@ -1665,7 +2276,7 @@ fn irregular_closed_spline_offset_certificate_edits_undoes_and_reopens() { let parameter = result["param"].as_str().unwrap().to_string(); let point_ids = sketch(&s).curves[1].kind.point_ids(); let verify = |s: &Session, distance: f64| { - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; assert_eq!(sk.curves[0], original.curves[0]); assert_eq!(&sk.points[..original.points.len()], &original.points); @@ -1855,7 +2466,7 @@ fn periodic_closed_offset_chain_break_drag_reopen_and_material_volume() { let sketch_id = s.active_sketch.unwrap(); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch":sketch_id,"profiles":[selected.0],"distance":3,"operation":"new"})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let volume = solidcraft_kernel::measure(&state.bodies.last().unwrap().body).unwrap().volume; assert!((volume - expected).abs() < 0.05, "{volume} vs {expected}"); } @@ -1933,7 +2544,7 @@ fn periodic_offset_extrusion_survives_post_extrude_span_changes_and_cold_reopen( let initial_doc = s.doc.to_json(); for major in [12.0, 16.0, 20.0] { run(&mut s, "parameters.change", json!({"name":"d1","expression":major})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = state.sketch(sk_id).unwrap(); let ring = sk.profiles.iter().find(|p| p.whole_curve_boundaries().as_ref() == Some(&boundary)).unwrap(); assert_ne!(ring.outer_curves.len(), initial_count, "the repro must actually change graph span multiplicity"); @@ -1976,19 +2587,25 @@ fn periodic_offset_extrusion_survives_post_extrude_span_changes_and_cold_reopen( let body = &state.bodies[0].body; for (distance, material) in [(1.25, true), (0.5, false), (1.75, false)] { let point = ellipse + normal * distance; - assert_eq!(body.contains(solidcraft_geom::Vec3::new(point.x, point.y, 1.5)), material); + assert_eq!( + body.classify_point(solidcore_record::Vec3::new(point.x, point.y, 1.5)).unwrap() == solidcraft_kernel::PointClass::Inside, + material + ); } // Repeat at the exact major-axis seam as a physical material control. for (distance, material) in [(1.25, true), (0.5, false), (1.75, false)] { let point = centre + u * (major + distance); assert_eq!(ring.region.contains(point), material); - assert_eq!(body.contains(solidcraft_geom::Vec3::new(point.x, point.y, 1.5)), material); + assert_eq!( + body.classify_point(solidcore_record::Vec3::new(point.x, point.y, 1.5)).unwrap() == solidcraft_kernel::PointClass::Inside, + material + ); } let volume = solidcraft_kernel::measure(body).unwrap().volume; assert!((volume - expected).abs() < 0.05, "{major}: {volume} vs independent {expected}"); let mut cold = Session { doc: solidcraft_doc::format::read(&s.doc.to_json()).unwrap().into(), ..Default::default() }; cold.refresh(); - let cold_state = cold.world_state(); + let cold_state = cold.world_state().unwrap(); assert_eq!(cold_state.bodies.len(), 1); let cold_volume = solidcraft_kernel::measure(&cold_state.bodies[0].body).unwrap().volume; assert!((cold_volume - volume).abs() < 1e-8); @@ -2080,6 +2697,196 @@ fn offset_two_sides_of_one_curve_follows_the_sign_of_the_distance() { assert!(close(one.1.x - one.0.x, 40.0) && close(two.1.x - two.0.x, 40.0), "{one:?} {two:?}"); } +/// Each instance of an outward offset of a 40 by 30 rectangle, as a box one more step out. +fn offset_rings(sk: &solidcraft_sketch::Sketch, o: &Value, out: &[f64]) { + for (index, out) in out.iter().copied().enumerate() { + let curves = side_curves(o, index); + assert_eq!(curves.len(), 4, "{o}"); + assert!(box_is(sk, &curves, [-out, -out], [40.0 + out, 30.0 + out]), "instance {}: {:?}", index + 1, bounds(sk, &curves)); + } +} + +#[test] +fn offset_instances_stack_one_behind_another_at_the_same_distance() { + let mut s = new_sketch(); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let l = ids(&r["curves"]); + // Three instances outward by 5 from a 40 by 30 rectangle: rings 5, 10 and 15 out, each the + // offset of the one before it. + let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, -10], "instances": 3})); + assert_eq!(o["instances"], 3, "{o}"); + let sides = o["sides"].as_array().unwrap().clone(); + assert_eq!(sides.len(), 3, "{o}"); + assert_eq!(sides.iter().map(|side| side["instance"].as_u64()).collect::>(), vec![Some(1), Some(2), Some(3)], "{o}"); + assert_eq!(ids(&o["curves"]).len(), 12, "{o}"); + offset_rings(&sketch(&s), &o, &[5.0, 10.0, 15.0]); + // One dimension drives the whole ladder, so every ring moves together when it changes. + let param = o["param"].as_str().unwrap().to_string(); + assert!(sides.iter().all(|side| side["param"].as_str() == Some(param.as_str())), "{o}"); + assert_eq!(sketch(&s).constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::OffsetDistance { .. })).count(), 3); + run(&mut s, "parameters.change", json!({"name": param, "expression": "8 mm"})); + offset_rings(&sketch(&s), &o, &[8.0, 16.0, 24.0]); +} + +#[test] +fn offset_instances_go_the_way_the_first_one_went() { + let mut s = new_sketch(); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let l = ids(&r["curves"]); + // Inward by 5: rings at (5,5)-(35,25) and (10,10)-(30,20). A later instance reads its side + // from the ring it follows, so it never doubles back over the one before it. + let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, 15], "instances": 2})); + let sk = sketch(&s); + assert!(box_is(&sk, &side_curves(&o, 0), [5.0, 5.0], [35.0, 25.0]), "{:?}", bounds(&sk, &side_curves(&o, 0))); + assert!(box_is(&sk, &side_curves(&o, 1), [10.0, 10.0], [30.0, 20.0]), "{:?}", bounds(&sk, &side_curves(&o, 1))); +} + +#[test] +fn offset_instances_stop_where_the_shape_runs_out() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let before = s.doc.to_json(); + // Inward by 5 twice reaches a 20 by 10 ring; a third would have no height left, so the + // whole command is refused and names the instance that could not be made. + let error = s.execute("sketch.offset", &json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 3})).unwrap_err().to_string(); + assert!(error.contains("instance 3 of 3"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone"); + // Two of them still work on the same shape. + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 2})); + assert_eq!(o["sides"].as_array().map(Vec::len), Some(2), "{o}"); +} + +/// Instances picked from an arc keep going inward: a slot with r5 ends, stepped 2 mm in three +/// times from an end arc. The third step would pass that arc's centre, so the command is +/// refused there, where the third instance used to turn round onto the first (its side was +/// read past the centre, outside the arc). +#[test] +fn offset_instances_from_an_arc_stop_where_the_arc_runs_out() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[-10, -5], [10, -5]]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [10, 0], "start": [10, -5], "end": [10, 5]})); + run(&mut s, "sketch.line", json!({"points": [[10, 5], [-10, 5]]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [-10, 0], "start": [-10, 5], "end": [-10, -5]})); + let before = s.doc.to_json(); + let error = s.execute("sketch.offset", &json!({"curves": ["a1"], "distance": 2, "side": [10, 0], "instances": 3})).unwrap_err().to_string(); + assert!(error.contains("instance 3 of 3"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone"); + let o = run(&mut s, "sketch.offset", json!({"curves": ["a1"], "distance": 2, "side": [10, 0], "instances": 2})); + let sk = sketch(&s); + let radii: Vec = o["sides"] + .as_array() + .unwrap() + .iter() + .map(|side| { + let id = side["curves"].as_array().unwrap().iter().filter_map(|v| v.as_str()).find(|id| id.starts_with('a')).unwrap(); + let CurveKind::Arc { c, a, .. } = sk.curves[sk.curve_index(id).unwrap()].kind else { panic!("{id} is no arc") }; + sk.points[c].pos.dist(sk.points[a].pos) + }) + .collect(); + assert!(radii.len() == 2 && (radii[0] - 3.0).abs() < 1e-6 && (radii[1] - 1.0).abs() < 1e-6, "{radii:?}"); +} + +/// `side` is read off the picked curve itself: an arc's end of a slot left a hair of radius by +/// the first instance still makes the second go on inward, and run out of room, and a tiny +/// distance far from the origin still goes the way `side` says (a step a thousandth of it is +/// lost to rounding there). +#[test] +fn offset_side_is_read_off_the_picked_curve() { + let mut s = new_sketch(); + let r = 2.0005; + run(&mut s, "sketch.line", json!({"points": [[-10, -r], [10, -r]]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [10, 0], "start": [10, -r], "end": [10, r]})); + run(&mut s, "sketch.line", json!({"points": [[10, r], [-10, r]]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [-10, 0], "start": [-10, r], "end": [-10, -r]})); + let error = s.execute("sketch.offset", &json!({"curves": ["a1"], "distance": 2, "side": [10, 0], "instances": 2})).unwrap_err().to_string(); + assert!(error.contains("instance 2 of 2"), "{error}"); + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 1e8], [20, 1e8]]})); + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 0.000001, "side": [10, 99999999]})); + let sk = sketch(&s); + let out = o["curves"][0].as_str().unwrap(); + let CurveKind::Line { a, .. } = sk.curves[sk.curve_index(out).unwrap()].kind else { panic!("{out} is no line") }; + assert!(sk.points[a].pos.y < 1e8, "below, toward `side`: {:?}", sk.points[a].pos); +} + +#[test] +fn offset_instances_count_must_be_a_whole_number_within_the_cap() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + for count in [json!(0), json!(-1), json!(1.5), json!(101), json!("two"), json!(true)] { + let params = json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count.clone()}); + assert!(s.execute("sketch.offset", ¶ms).is_err(), "instances {count} must be refused"); + } + // No count, and a count of one, are the offset by itself. + for count in [json!(null), json!(1), json!("1")] { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count})); + assert_eq!(o["instances"], 1, "{o}"); + assert_eq!(o["sides"].as_array().map(Vec::len), Some(1), "{o}"); + assert_eq!(ids(&o["curves"]).len(), 4, "{o}"); + } +} + +#[test] +fn offset_instances_into_a_circle_run_out_at_the_centre() { + let mut s = new_sketch(); + let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"])[0].clone(); + let radii = |s: &Session, o: &Value| -> Vec { + let sk = sketch(s); + o["sides"] + .as_array() + .unwrap() + .iter() + .map(|side| match sk.curves.get(sk.curve_index(ids(&side["curves"])[0].as_str()).unwrap()).unwrap().kind { + CurveKind::Circle { r, .. } => r, + ref other => panic!("{other:?}"), + }) + .collect() + }; + // Inward by 3 from a 10 mm circle: rings at 7, 4 and 1 mm. + let o = run(&mut s, "sketch.offset", json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 3})); + let got = radii(&s, &o); + assert!(got.iter().zip([7.0, 4.0, 1.0]).all(|(a, b)| close(*a, b)), "{got:?}"); + let before = s.doc.to_json(); + // A fourth has nothing left to take. The ladder has to run out here: a step past a ring + // smaller than the distance lands beyond the centre, and reading that as the outward side + // turned the ladder round and grew it again (1, 4, 1, 4 ...) rather than refusing. + let error = s.execute("sketch.offset", &json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 4})).unwrap_err().to_string(); + assert!(error.contains("instance 4 of 4"), "{error}"); + assert!(error.contains("no size"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone"); + // Outward is unaffected: every ring is one distance larger than the last. + let out = run(&mut s, "sketch.offset", json!({"curves": [c], "distance": 3, "side": [40, 0], "instances": 3})); + let got = radii(&s, &out); + assert!(got.iter().zip([13.0, 16.0, 19.0]).all(|(a, b)| close(*a, b)), "{got:?}"); +} + +#[test] +fn offset_instances_follow_each_side_of_a_symmetric_offset() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + // Symmetric by 5, two instances: both ways get a second ring a further 5 out, so the four + // rings are 5 and 10 inside and 5 and 10 outside. + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "symmetric": true, "instances": 2})); + let sides = o["sides"].as_array().unwrap().clone(); + assert_eq!(sides.len(), 4, "{o}"); + assert_eq!(sides.iter().filter(|side| side["instance"] == 2).count(), 2, "{o}"); + let sk = sketch(&s); + let mut boxes: Vec<[f64; 4]> = sides + .iter() + .map(|side| { + let (lo, hi) = bounds(&sk, &ids(&side["curves"])); + [lo.x, lo.y, hi.x, hi.y] + }) + .collect(); + boxes.sort_by(|a, b| a[0].total_cmp(&b[0])); + let want = [[-10.0, -10.0, 50.0, 40.0], [-5.0, -5.0, 45.0, 35.0], [5.0, 5.0, 35.0, 25.0], [10.0, 10.0, 30.0, 20.0]]; + for (got, want) in boxes.iter().zip(&want) { + assert!(got.iter().zip(want).all(|(a, b)| close(*a, *b)), "{boxes:?}"); + } +} + #[test] fn offset_both_sides_of_a_rounded_boundary_keep_separate_associations() { let mut s = new_sketch(); @@ -2144,6 +2951,24 @@ fn offset_both_sides_of_a_circle_are_concentric() { assert!(s.execute("sketch.offset", &json!({"curves": [c], "distance": 10, "symmetric": true})).is_err()); } +#[test] +fn an_offset_circle_takes_its_radius_from_the_source() { + // #9264: the offset rebuilds a circle's radius from its source after the solve, but the + // solve still counted that radius as an unknown: a dimensioned circle and its offset + // reported 1 degree of freedom. + let mut s = new_sketch(); + let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": "origin", "radius": 25}))["curves"])[0].clone(); + let d = run(&mut s, "sketch.dimension", json!({"entities": [c], "type": "diameter", "value": "d = 50"})); + assert_eq!(d["sketch"]["dof"], 0, "{d}"); + let o = run(&mut s, "sketch.offset", json!({"curves": [c], "distance": 5, "side": [40, 0]})); + assert_eq!(o["sketch"]["dof"], 0, "the offset circle's radius follows its source: {o}"); + let out = ids(&o["curves"])[0].clone(); + run(&mut s, "parameters.change", json!({"name": "d", "expression": "60"})); + let sk = sketch(&s); + let CurveKind::Circle { r, .. } = sk.curves[sk.curve_index(&out).unwrap()].kind else { panic!("{out} is not a circle") }; + assert!(close(r, 35.0), "30 mm source plus 5 mm: {r}"); +} + #[test] fn offset_refuses_the_combinations_that_would_be_guesswork() { let mut s = new_sketch(); @@ -2193,7 +3018,7 @@ fn offset_driver_edits_reopens_and_undoes_without_moving_sources() { let param = result["param"].as_str().unwrap().to_string(); let outputs = ids(&result["curves"]); let check = |s: &Session, distance: f64| { - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; assert!((sk.offset_distance(&outputs[0]).unwrap().abs() - distance).abs() < 1e-8); let constraint = sk.constraints.iter().find(|c| c.param.as_deref() == Some(¶m)).unwrap(); @@ -2308,6 +3133,167 @@ fn an_offset_slot_still_moves_with_the_dimension_that_places_it() { } } +fn capped_line_offset(fixed_cap: bool) -> Session { + let mut s = Session::default(); + run( + &mut s, + "timeline.add", + json!({ + "feature": {"id":1,"name":"Capped offset","type":"sketch","plane":{"type":"origin","name":"XY"},"sketch":{ + "points":[ + {"id":"origin","pos":[0,0],"fixed":true}, + {"id":"end","pos":[0,50],"fixed":false}, + {"id":"oa","pos":[-2,0],"fixed":true}, + {"id":"ob","pos":[-2,50],"fixed":true}, + {"id":"center","pos":[-1,50],"fixed":false}, + {"id":"cap_end","pos":[-2,50],"fixed":fixed_cap} + ], + "curves":[ + {"id":"source","type":"line","a":0,"b":1}, + {"id":"offset","type":"line","a":2,"b":3}, + {"id":"cap","type":"arc","c":4,"a":1,"b":5} + ], + "constraints":[ + {"id":"vertical","type":"vertical","l":0}, + {"id":"length","type":"length","l":0,"value":50,"param":"height"}, + {"id":"source_tangent","type":"tangent","a":0,"b":2}, + {"id":"offset_tangent","type":"tangent","a":1,"b":2}, + {"id":"end_join","type":"coincident","p":3,"q":5} + ], + "offsets":[{"sources":[["source",true]],"outputs":["offset"],"distance":2,"closed":false}] + }}, + "params":[{"name":"height","expression":"50","unit":"mm"}] + }), + ); + run(&mut s, "sketch.edit", json!({"sketch":1})); + s +} + +#[test] +fn a_tangent_cap_follows_its_offset_when_the_source_length_changes() { + // #4823: the cap joins the source to the offset's held endpoint. Solving against the old + // endpoint first makes every length change look contradictory, before the offset can move. + let mut s = capped_line_offset(false); + let check = |s: &Session, height: f64| { + let world = s.world_state().unwrap(); + let solved = world.sketch(1).unwrap(); + assert!(solved.report.keeps_orientation(), "{:?}", solved.report); + assert!(solved.report.fully_constrained()); + let sk = &solved.sketch; + for (id, expected) in [ + ("origin", Vec2::ZERO), + ("end", Vec2::new(0.0, height)), + ("oa", Vec2::new(-2.0, 0.0)), + ("ob", Vec2::new(-2.0, height)), + ("center", Vec2::new(-1.0, height)), + ("cap_end", Vec2::new(-2.0, height)), + ] { + let point = sk.points.iter().find(|p| p.id == id).unwrap(); + assert!(point.pos.dist(expected) < 1e-6, "{id}: {:?}, expected {expected:?}", point.pos); + } + assert_eq!(sk.constraints.len(), 5); + assert_eq!(sk.offsets.len(), 1); + }; + check(&s, 50.0); + let mut previous = 50.0; + for height in [60.0, 40.0, 70.0] { + run(&mut s, "parameters.change", json!({"name":"height","expression":height.to_string()})); + check(&s, height); + run(&mut s, "edit.undo", json!({})); + check(&s, previous); + run(&mut s, "edit.redo", json!({})); + check(&s, height); + previous = height; + } + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + check(&reopened, 70.0); +} + +#[test] +fn an_offset_cap_fixed_at_the_old_height_still_refuses_a_length_change() { + let mut s = capped_line_offset(true); + let before = s.doc.to_json(); + let undo = s.undo.len(); + assert!(s.execute("parameters.change", &json!({"name":"height","expression":"60"})).is_err()); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); +} + +#[test] +fn a_cap_on_an_offset_arc_keeps_its_radius_through_large_length_edits() { + // Two externally tangent source arcs: radii 3 and 6, centres separated by (4, -sqrt(65)). + // Their inward/outward offsets share those centres; a radius-1 cap closes the 2 mm gap. + // The preliminary keep-start solve used to stretch that cap onto another tangency branch. + let dy = 65.0_f64.sqrt(); + let end_dy = 11.0_f64.sqrt(); + for batch in [false, true] { + let mut s = Session::default(); + run( + &mut s, + "timeline.add", + json!({ + "feature":{"id":1,"name":"Curved cap","type":"sketch","plane":{"type":"origin","name":"XY"},"sketch":{ + "points":[ + {"id":"origin","pos":[0,0],"fixed":true}, + {"id":"end","pos":[0,50]}, + {"id":"bend_center","pos":[3,50]}, + {"id":"bend_join","pos":[3.0+4.0/3.0,50.0-dy/3.0]}, + {"id":"tip_center","pos":[7,50.0-dy]}, + {"id":"tip_end","pos":[2,50.0-dy-end_dy]}, + {"id":"oa","pos":[-2,0],"fixed":true}, + {"id":"ob","pos":[-2,50],"fixed":true}, + {"id":"offset_join","pos":[3.0+20.0/9.0,50.0-dy*5.0/9.0],"fixed":true}, + {"id":"offset_end","pos":[7.0-10.0/3.0,50.0-dy-end_dy*2.0/3.0],"fixed":true}, + {"id":"cap_center","pos":[7.0-25.0/6.0,50.0-dy-end_dy*5.0/6.0]}, + {"id":"cap_end","pos":[7.0-10.0/3.0,50.0-dy-end_dy*2.0/3.0]} + ], + "curves":[ + {"id":"source","type":"line","a":0,"b":1}, + {"id":"bend","type":"arc","c":2,"a":3,"b":1}, + {"id":"tip","type":"arc","c":4,"a":3,"b":5}, + {"id":"offset","type":"line","a":6,"b":7}, + {"id":"bend_offset","type":"arc","c":2,"a":8,"b":7}, + {"id":"tip_offset","type":"arc","c":4,"a":8,"b":9}, + {"id":"cap","type":"arc","c":10,"a":5,"b":11} + ], + "constraints":[ + {"id":"vertical","type":"vertical","l":0}, + {"id":"length","type":"length","l":0,"value":50,"param":"height"}, + {"id":"bend_tangent","type":"tangent","a":0,"b":1}, + {"id":"tip_tangent","type":"tangent","a":1,"b":2}, + {"id":"tip_distance","type":"line_circle_distance","l":0,"c":2,"value":1}, + {"id":"bend_radius","type":"radius","c":1,"value":3}, + {"id":"tip_radius","type":"radius","c":2,"value":6}, + {"id":"end_distance","type":"point_line_distance","p":5,"l":0,"value":2}, + {"id":"cap_tangent","type":"tangent","a":2,"b":6}, + {"id":"end_join","type":"coincident","p":9,"q":11} + ], + "offsets":[{"sources":[["source",true],["bend",false],["tip",true]], + "outputs":["offset","bend_offset","tip_offset"],"distance":2,"closed":false}] + }}, + "params":[{"name":"height","expression":"50","unit":"mm"}] + }), + ); + run(&mut s, "sketch.edit", json!({"sketch":1})); + let initial = sketch(&s); + for height in [55.0, 60.0, 70.0, 40.0] { + let params = + if batch { json!({"changes":{"height":height.to_string()}}) } else { json!({"name":"height","expression":height.to_string()}) }; + run(&mut s, "parameters.change", params); + let world = s.world_state().unwrap(); + let solved = world.sketch(1).unwrap(); + assert!(solved.report.keeps_orientation() && solved.report.fully_constrained(), "{:?}", solved.report); + for (p, before) in solved.sketch.points.iter().zip(&initial.points) { + let shift = if matches!(p.id.as_str(), "origin" | "oa") { 0.0 } else { height - 50.0 }; + let expected = before.pos + Vec2::new(0.0, shift); + assert!(p.pos.dist(expected) < 1e-6, "batch={batch}, height={height}, {}: {:?}, expected {expected:?}", p.id, p.pos); + assert_eq!(p.fixed, before.fixed, "temporary source holds must not be saved"); + } + assert_eq!(solved.sketch.constraints.len(), 10); + } + } +} + #[test] fn offset_driver_covers_disconnected_selections_and_refuses_bad_values_atomically() { let mut s = new_sketch(); @@ -2369,7 +3355,7 @@ fn offset_driver_uses_design_units_and_dimension_delete_freezes_current_distance assert!((sketch(&s).offsets[0].distance - 5.08).abs() < 1e-8); assert!(s.doc.param(param).is_none()); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert!((reopened.world_state().sketch(1).unwrap().sketch.offsets[0].distance - 5.08).abs() < 1e-8); + assert!((reopened.world_state().unwrap().sketch(1).unwrap().sketch.offsets[0].distance - 5.08).abs() < 1e-8); } #[test] @@ -2396,7 +3382,7 @@ fn offset_driver_arc_first_retires_breaks_undoes_and_reopens() { assert!(sketch(&s).offsets.is_empty()); assert_eq!(sketch(&s).segs(sketch(&s).curve_index(&survivor).unwrap()), before); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert!(reopened.world_state().sketch(1).unwrap().sketch.offsets.is_empty()); + assert!(reopened.world_state().unwrap().sketch(1).unwrap().sketch.offsets.is_empty()); run(&mut s, "edit.undo", json!({})); assert!(s.doc.param(param).is_some()); run(&mut s, "edit.redo", json!({})); @@ -2644,7 +3630,7 @@ fn trim_piece_is_what_a_trim_there_takes_away() { /// refused (the trim used to report success and leave the curve whole). Trimming away a whole /// offset curve still works, and once the association is broken the trim cuts it. #[test] -fn trim_and_extend_refuse_an_offsets_ends_until_its_association_is_broken() { +fn trim_extend_and_break_refuse_an_offsets_ends_until_its_association_is_broken() { let mut s = new_sketch(); run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); let out = ids(&run(&mut s, "sketch.offset", json!({"curves": ["l1", "l2", "l3", "l4"], "distance": "2 mm", "side": [-5, -5]}))["curves"]); @@ -2655,6 +3641,10 @@ fn trim_and_extend_refuse_an_offsets_ends_until_its_association_is_broken() { assert!(e.contains("offset") && e.contains("break the offset association"), "{e}"); let e = s.execute("sketch.extend", &json!({"curve": "l5", "at": [42, -2]})).unwrap_err().to_string(); assert!(e.contains("offset"), "{e}"); + for params in [json!({"curve": "l5", "at": [30, -2]}), json!({"curve": "l5", "points": [[20, -2]]})] { + let e = s.execute("sketch.break", ¶ms).unwrap_err().to_string(); + assert!(e.contains("offset") && e.contains("break the offset association"), "{params}: {e}"); + } assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before, "a refused trim changes nothing"); run(&mut s, "sketch.offset.break", json!({"curve": "l5"})); @@ -3391,3 +4381,557 @@ fn corner_tools_refuse_all_spatial_curves_with_an_unsupported_message() { } } } + +/// #10653: a tangent arc started on a line between its ends (`on:l1:…`, which a click there +/// gives) is refused as no end to start from, not as an unknown point; `tangent_arc_starts_at` +/// tells a tool which points it can start at. +#[test] +fn a_tangent_arc_starts_only_at_a_curves_end() { + let mut s = new_sketch(); + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[5, 0], [15, 0]], "connect": false, "infer": false}))["curves"])[0].clone(); + let before = s.doc.to_json(); + let on = format!("on:{line}:10,0"); + for start in [on.clone(), format!("mid:{line}")] { + let err = s.execute("sketch.arc.tangent", &json!({"start": start, "end": [20, 10]})).map(|v| v.to_string()).unwrap_err().to_string(); + assert!(err.contains("`start` must be the end point of a line or arc") && !err.contains("unknown sketch point"), "{start}: {err}"); + assert_eq!(s.doc.to_json(), before); + } + let sk = sketch(&s); + assert!(crate::cmd::tangent_arc_starts_at(&sk, &format!("{line}.end"))); + assert!(crate::cmd::tangent_arc_starts_at(&sk, &format!("{line}.start"))); + assert!(!crate::cmd::tangent_arc_starts_at(&sk, &on)); + assert!(!crate::cmd::tangent_arc_starts_at(&sk, "origin"), "no curve ends at the origin here"); +} + +/// `sketch.arc.tangent` ends on an existing point when `end` names it, so a chain can close, and +/// makes a new point for coordinates as before (#9489). The preview is the arc the command draws. +#[test] +fn a_tangent_arc_can_end_on_an_existing_point() { + let mut s = new_sketch(); + let far = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 20], [40, 20]], "connect": false, "infer": false}))["curves"])[0].clone(); + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "connect": false, "infer": false}))["curves"])[0].clone(); + let start = format!("{line}.end"); + let target = format!("{far}.start"); + let sk = sketch(&s); + let preview = crate::cmd::tangent_arc_preview(&sk, &line, &start, Vec2::new(20.0, 20.0)).expect("an arc"); + assert_eq!(preview.curves.len(), 1); + assert!(preview.center(0).unwrap().dist(Vec2::new(10.0, 12.5)) < 1e-9, "{:?}", preview.center(0)); + assert!(crate::cmd::tangent_arc_preview(&sk, &line, &start, Vec2::new(30.0, 0.0)).is_none(), "straight ahead there is no arc"); + + let points = sk.points.len(); + let r = run(&mut s, "sketch.arc.tangent", json!({"start": start, "curve": line, "end": target})); + let arc = ids(&r["curves"])[0].clone(); + let sk = sketch(&s); + assert_eq!(sk.resolve_point(&format!("{arc}.end")), sk.resolve_point(&format!("{far}.start")), "the arc ends on that point"); + assert_eq!(sk.resolve_point(&format!("{arc}.start")), sk.resolve_point(&format!("{line}.end"))); + assert_eq!(sk.points.len(), points + 1, "only the arc's centre is new"); + let ai = sk.curve_index(&arc).unwrap(); + assert!(sk.center(ai).unwrap().dist(Vec2::new(10.0, 12.5)) < 1e-6, "{:?}", sk.center(ai)); + assert!(close(sk.radius(ai).unwrap(), 12.5)); + + // Clockwise: the arc is stored the other way round, and its end is still the named point. + let down = ids(&run(&mut s, "sketch.line", json!({"points": [[0, -50], [10, -50]], "connect": false, "infer": false}))["curves"])[0].clone(); + let mark = ids(&run(&mut s, "sketch.line", json!({"points": [[20, -70], [40, -70]], "connect": false, "infer": false}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.arc.tangent", json!({"start": format!("{down}.end"), "curve": down, "end": format!("{mark}.start")})); + let arc = ids(&r["curves"])[0].clone(); + let sk = sketch(&s); + assert_eq!(sk.resolve_point(&format!("{arc}.end")), sk.resolve_point(&format!("{mark}.start"))); + assert_eq!(sk.resolve_point(&format!("{arc}.start")), sk.resolve_point(&format!("{down}.end"))); + + // A name that is no point, and the arc's own start, are refused and change nothing. + let before = s.doc.to_json(); + assert!(s.execute("sketch.arc.tangent", &json!({"start": format!("{down}.end"), "curve": down, "end": "nowhere"})).is_err()); + assert!(s.execute("sketch.arc.tangent", &json!({"start": format!("{down}.end"), "curve": down, "end": format!("{down}.end")})).is_err()); + assert_eq!(s.doc.to_json(), before); +} + +/// Where a circle of radius `r1` at the origin meets a circle of radius `r2` at `(-d, 0)`, +/// then the same on the right. `(top-left, bottom-left, top-right, bottom-right)`. +fn lobe_corners(r1: f64, r2: f64, d: f64) -> (Vec2, Vec2, Vec2, Vec2) { + let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d); + let h = (r1 * r1 - a * a).sqrt(); + (Vec2::new(-a, h), Vec2::new(-a, -h), Vec2::new(a, h), Vec2::new(a, -h)) +} + +fn arc_ends(sk: &solidcraft_sketch::Sketch, id: &str) -> (usize, usize, Vec2, Vec2, Vec2) { + match sk.curves[sk.curve_index(id).unwrap()].kind { + CurveKind::Arc { c, a, b } => (a, b, sk.point(c).unwrap(), sk.point(a).unwrap(), sk.point(b).unwrap()), + ref other => panic!("{id} is {other:?}"), + } +} + +fn line_ends(sk: &solidcraft_sketch::Sketch, id: &str) -> (usize, Vec2, usize, Vec2) { + match sk.curves[sk.curve_index(id).unwrap()].kind { + CurveKind::Line { a, b } => (a, sk.point(a).unwrap(), b, sk.point(b).unwrap()), + ref other => panic!("{id} is {other:?}"), + } +} + +/// Midpoint of the counter-clockwise arc from `a` to `b` around `c`. +fn ccw_mid(c: Vec2, a: Vec2, b: Vec2) -> Vec2 { + let start = (a - c).angle(); + let mut sweep = (b - c).angle() - start; + if sweep <= 1e-12 { + sweep += std::f64::consts::TAU; + } + c + Vec2::from_angle(start + sweep * 0.5) * c.dist(a) +} + +/// Corners whose ends are separate points offset as one chain. An offset that runs past the +/// crossing is trimmed back to it; one that stops short is extended until the curves intersect. +#[test] +fn offset_corners_trim_the_overlap_and_extend_the_gap() { + let (big, small, apart) = (27.5, 12.5, 27.95); + let (tl, bl, tr, br) = lobe_corners(big, small, apart); + let mut s = new_sketch(); + let draw = |s: &mut Session, id: &str, center: [f64; 2], start: Vec2, end: Vec2| { + run( + s, + "sketch.arc.center_point", + json!({ + "id": id, "center": center, "start": [start.x, start.y], "end": [end.x, end.y], "connect": false, + }), + ); + }; + draw(&mut s, "top", [0.0, 0.0], tr, tl); + draw(&mut s, "left", [-apart, 0.0], tl, bl); + draw(&mut s, "bottom", [0.0, 0.0], bl, br); + draw(&mut s, "right", [apart, 0.0], br, tr); + let sk = sketch(&s); + let (top_end, left_start) = (sk.resolve_point("top.end").unwrap(), sk.resolve_point("left.start").unwrap()); + assert_ne!(top_end, left_start, "the corner is two points"); + assert!(sk.point(top_end).unwrap().dist(sk.point(left_start).unwrap()) < 1e-9); + assert!(!sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Coincident { p, q } if p == top_end || q == top_end))); + assert_eq!(profiles(&s).len(), 1, "the four arcs are one profile"); + + // Chain off copies the one arc, source angle and all, so the corner stays open. + let alone = run(&mut s, "sketch.offset", json!({"curves": ["top"], "distance": -3, "chain": false})); + assert_eq!(ids(&alone["curves"]).len(), 1); + let radial = tl.normalized().unwrap() * (big + 3.0); + let (_, _, _, _, open_end) = arc_ends(&sketch(&s), &ids(&alone["curves"])[0]); + assert!(open_end.dist(radial) < 1e-4, "untrimmed end {open_end:?}, radial {radial:?}"); + run(&mut s, "edit.undo", json!({})); + + let out = run(&mut s, "sketch.offset", json!({"curves": ["top"], "distance": -3})); + assert_eq!(ids(&out["curves"]).len(), 4, "{out}"); + assert_eq!(out["sides"].as_array().unwrap().len(), 1); + let sk = sketch(&s); + assert_eq!(sk.offsets.len(), 1); + let rec = &sk.offsets[0]; + assert!(rec.closed); + assert_eq!( + rec.sources.iter().map(|(id, forward)| (id.as_str(), *forward)).collect::>(), + vec![("top", true), ("left", true), ("bottom", true), ("right", true)] + ); + let (meet_tl, meet_bl, meet_tr, meet_br) = lobe_corners(big + 3.0, small + 3.0, apart); + let mut prev_end = arc_ends(&sk, rec.outputs.last().unwrap()).1; + for (id, radius, center) in [ + ("top", big + 3.0, Vec2::ZERO), + ("left", small + 3.0, Vec2::new(-apart, 0.0)), + ("bottom", big + 3.0, Vec2::ZERO), + ("right", small + 3.0, Vec2::new(apart, 0.0)), + ] { + let i = rec.sources.iter().position(|(source, _)| source == id).unwrap(); + let (a, b, c, start, _) = arc_ends(&sk, &rec.outputs[i]); + assert_eq!(prev_end, a, "{id} starts where the previous arc ends"); + assert!((c.dist(start) - radius).abs() < 1e-4 && c.dist(center) < 1e-6, "{id} at {c:?} radius {}", c.dist(start)); + prev_end = b; + } + let (_, _, _, _, trimmed) = arc_ends(&sk, &rec.outputs[0]); + assert!(trimmed.dist(meet_tl) < 1e-4, "top-left corner {trimmed:?}, intersection {meet_tl:?}"); + assert!(trimmed.dist(radial) > 1.0, "trimmed back from the untrimmed end {radial:?} to {trimmed:?}"); + let (_, _, c, a, b) = arc_ends(&sk, &rec.outputs[0]); + let mid = ccw_mid(c, a, b); + assert!(mid.dist(Vec2::new(0.0, big + 3.0)) < 1e-3, "the top arc stays the short one, mid {mid:?}"); + let left_i = rec.sources.iter().position(|(source, _)| source == "left").unwrap(); + let (_, _, c, a, b) = arc_ends(&sk, &rec.outputs[left_i]); + let mid = ccw_mid(c, a, b); + assert!(mid.dist(Vec2::new(-apart - (small + 3.0), 0.0)) < 1e-3, "the left arc stays the outer one, mid {mid:?}"); + // The other three crossings, so a closed chain joins the last corner as well. + let corners: Vec = rec + .outputs + .iter() + .map(|id| { + let (_, _, _, _, end) = arc_ends(&sk, id); + end + }) + .collect(); + for want in [meet_tl, meet_bl, meet_tr, meet_br] { + assert!(corners.iter().any(|q| q.dist(want) < 1e-4), "missing {want:?} in {corners:?}"); + } + + // Editing the distance keeps the corners on the new intersection. + let param = out["param"].as_str().unwrap(); + run(&mut s, "parameters.change", json!({"name": param, "expression": "4 mm"})); + let sk = sketch(&s); + assert!((sk.offsets[0].distance + 4.0).abs() < 1e-6, "distance {}", sk.offsets[0].distance); + let (grown, _, _, _) = lobe_corners(big + 4.0, small + 4.0, apart); + let top_i = sk.offsets[0].sources.iter().position(|(source, _)| source == "top").unwrap(); + let top_out = sk.offsets[0].outputs[top_i].clone(); + let (_, _, _, _, trimmed) = arc_ends(&sk, &top_out); + assert!(trimmed.dist(grown) < 1e-4, "after the edit {trimmed:?}, intersection {grown:?}"); + + // An L of two lines. Negative (outward) stops short of the corner and must be extended. + // Positive runs past it and must be trimmed back. The ends only share a position. + let corner_of = |distance: f64| -> Vec2 { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [20.0, 0.0]], "connect": false, "infer": false})); + run(&mut s, "sketch.line", json!({"points": [[20.0, 0.0], [20.0, 20.0]], "connect": false, "infer": false})); + let sk = sketch(&s); + assert_ne!(sk.resolve_point("l1.end").unwrap(), sk.resolve_point("l2.start").unwrap()); + let out = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": distance})); + assert_eq!(ids(&out["curves"]).len(), 2, "distance {distance}: {out}"); + let sk = sketch(&s); + let (first, second) = (&sk.offsets[0].outputs[0], &sk.offsets[0].outputs[1]); + let (_, _, end_i, end) = line_ends(&sk, first); + let (start_i, start, _, _) = line_ends(&sk, second); + assert_eq!(end_i, start_i, "one corner point"); + assert!(end.dist(start) < 1e-9); + end + }; + let extended = corner_of(-3.0); + assert!(extended.dist(Vec2::new(23.0, -3.0)) < 1e-6, "extended to {extended:?}"); + let trimmed = corner_of(3.0); + assert!(trimmed.dist(Vec2::new(17.0, 3.0)) < 1e-6, "trimmed to {trimmed:?}"); + + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [20.0, 0.0]], "connect": false, "infer": false})); + run(&mut s, "sketch.line", json!({"points": [[20.0, 0.0], [20.0, 20.0]], "connect": false, "infer": false})); + let alone = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": -3, "chain": false})); + assert_eq!(ids(&alone["curves"]).len(), 1); + let (_, _, _, end) = line_ends(&sketch(&s), &ids(&alone["curves"])[0]); + assert!(end.dist(Vec2::new(20.0, -3.0)) < 1e-6, "chain off leaves the gap, end {end:?}"); + + // The same L, joined only by a coincident constraint across a gap the tolerance would not. + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [20.0, 0.0]], "connect": false, "infer": false})); + run(&mut s, "sketch.line", json!({"points": [[20.5, 0.5], [20.5, 20.0]], "connect": false, "infer": false})); + let gap = { + let sk = sketch(&s); + sk.point(sk.resolve_point("l1.end").unwrap()).unwrap().dist(sk.point(sk.resolve_point("l2.start").unwrap()).unwrap()) + }; + assert!(gap > 0.4, "the ends start {gap} mm apart"); + run(&mut s, "sketch.constraint.fix", json!({"entity": "l1.start"})); + run(&mut s, "sketch.constraint.fix", json!({"entity": "l2.end"})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l1", "mode": "horizontal"})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l2", "mode": "vertical"})); + run(&mut s, "sketch.constraint.coincident", json!({"a": "l1.end", "b": "l2.start"})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": -3})); + assert_eq!(ids(&out["curves"]).len(), 2, "{out}"); + let sk = sketch(&s); + let (_, _, _, end) = line_ends(&sk, &sk.offsets[0].outputs[0]); + assert!(end.dist(Vec2::new(23.5, -3.0)) < 1e-4, "coincident corner extended to {end:?}"); +} + +#[test] +fn move_copy_drawn_arc_keeps_exact_geometry_and_original() { + use solidcore_record::Vec3; + let mut s = new_sketch(); + run(&mut s, "sketch.options", json!({"sketch_3d":true})); + let source = ids(&run(&mut s, "sketch.arc3d", json!({"start":[10,0,3],"through":[0,10,3],"end":[-10,0,3]}))["curves"])[0].clone(); + let id = s.active_sketch.unwrap(); + let original = s.doc.sketch(id).unwrap().wires[0].clone(); + let before = s.doc.to_json(); + let out = run(&mut s, "sketch.move", json!({"entities":[source],"translate":[1.6,0],"copy":true})); + let copied = ids(&out["curves"]); + assert_eq!(copied.len(), 1); + assert_ne!(copied[0], source); + let sk = s.doc.sketch(id).unwrap(); + assert_eq!(sk.wires.len(), 2); + assert_eq!(sk.wires[0], original); + let wire = &sk.wires[1]; + assert_eq!(wire.id, copied[0]); + assert_eq!(wire.space, original.space); + assert_eq!(wire.link, None); + let arc = wire.arc.unwrap(); + assert!(arc.center.dist(Vec3::new(1.6, 0.0, 3.0)) < 1e-9); + assert!(close(arc.radius, 10.0)); + assert!(close(solidcraft_sketch::arc_sweep(&arc), std::f64::consts::PI)); + for (p, q) in wire.fit.iter().zip(&original.fit) { + assert!(p.dist(*q + Vec3::new(1.6, 0.0, 0.0)) < 1e-9); + } + let after = s.doc.to_json(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.to_json(), after); + let reopened = solidcraft_doc::format::read(&after).unwrap(); + assert_eq!(reopened.sketch(id).unwrap().wires, s.doc.sketch(id).unwrap().wires); +} + +#[test] +fn move_copy_drawn_arc_turns_in_the_sketch_plane_without_flattening() { + use solidcore_record::Vec3; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"YZ"})); + run(&mut s, "sketch.options", json!({"sketch_3d":true})); + let source = ids(&run(&mut s, "sketch.arc3d", json!({"start":[5,12,3],"through":[5,2,13],"end":[5,-8,3]}))["curves"])[0].clone(); + run(&mut s, "sketch.move", json!({"entities":[source],"translate":[4,-1],"angle":90,"center":[2,3],"copy":true})); + let sk = s.doc.sketch(s.active_sketch.unwrap()).unwrap(); + let copy = &sk.wires[1]; + for (p, expected) in copy.fit.iter().zip([Vec3::new(5.0, 6.0, 12.0), Vec3::new(5.0, -4.0, 2.0), Vec3::new(5.0, 6.0, -8.0)]) { + assert!(p.dist(expected) < 1e-9, "{p:?} != {expected:?}"); + } + let arc = copy.arc.unwrap(); + assert!(arc.center.dist(Vec3::new(5.0, 6.0, 2.0)) < 1e-9); + assert!(arc.normal.dist(Vec3::X) < 1e-9); + assert!(close(arc.radius, 10.0)); +} + +#[test] +fn move_copy_drawn_wires_mix_with_planar_curves_and_deduplicate() { + use solidcore_record::Vec3; + let mut s = new_sketch(); + run(&mut s, "sketch.options", json!({"sketch_3d":true})); + let curve = ids(&run(&mut s, "sketch.line", json!({"points":[[1,2],[4,2]]}))["curves"])[0].clone(); + let wire = ids(&run(&mut s, "sketch.spline3d", json!({"points":[[1,2,3],[4,6,8],[10,8,9]]}))["curves"])[0].clone(); + let point = run(&mut s, "sketch.point3d", json!({"point":[2,3,4]}))["point"].as_str().unwrap().to_owned(); + let before = sketch(&s); + let out = run(&mut s, "sketch.move", json!({"entities":[wire,curve,point,wire],"translate":[3,-2],"copy":true})); + assert_eq!(ids(&out["curves"]).len(), 3); + let after = sketch(&s); + assert_eq!(after.curves.len(), before.curves.len() + 1); + assert_eq!(after.wires.len(), before.wires.len() + 2); + for (original, copy) in before.wires.iter().zip(after.wires.iter().skip(2)) { + assert_eq!(after.wires.iter().find(|w| w.id == original.id).unwrap(), original); + assert_eq!(copy.space, original.space); + assert_eq!(copy.arc, None); + for (p, q) in copy.fit.iter().zip(&original.fit) { + assert!(p.dist(*q + Vec3::new(3.0, -2.0, 0.0)) < 1e-9); + } + } + let copied = &after.curves[1]; + let CurveKind::Line { a, b } = copied.kind else { panic!("expected a copied line") }; + assert!(after.point(a).unwrap().dist(Vec2::new(4.0, 0.0)) < 1e-9); + assert!(after.point(b).unwrap().dist(Vec2::new(7.0, 0.0)) < 1e-9); +} + +#[test] +fn move_copy_drawn_wire_failures_leave_the_design_and_history_unchanged() { + let mut s = new_sketch(); + run(&mut s, "sketch.options", json!({"sketch_3d":true})); + let wire = ids(&run(&mut s, "sketch.arc3d", json!({"start":[10,0,0],"through":[0,10,0],"end":[-10,0,0]}))["curves"])[0].clone(); + let original = s.doc.to_json(); + let history = (s.undo.len(), s.redo.len()); + for params in [ + json!({"entities":[wire],"copy":true,"translate":[1e9,0]}), + json!({"entities":[wire,"missing"],"copy":true,"translate":[1,0]}), + json!({"entities":[],"copy":true}), + ] { + assert!(s.execute("sketch.move", ¶ms).is_err()); + assert_eq!(s.doc.to_json(), original); + assert_eq!((s.undo.len(), s.redo.len()), history); + } + // An unlinked reference wire has no editable fit points: Copy must not convert its + // samples to a fitted spline and silently change the curve's shape. + let id = s.active_sketch.unwrap(); + s.doc_mut().sketch_mut(id).unwrap().wires[0].fit.clear(); + s.doc_mut().sketch_mut(id).unwrap().wires[0].arc = None; + s.refresh(); + let original = s.doc.to_json(); + let error = s.execute("sketch.move", &json!({"entities":[wire],"copy":true})).unwrap_err().to_string(); + assert!(error.contains("drawn 3D"), "{error}"); + assert_eq!(s.doc.to_json(), original); + assert_eq!((s.undo.len(), s.redo.len()), history); +} + +/// A construction line and its two offsets each stop at their own crossing. Trimming one +/// must never shorten the others, whatever order the three curves are picked in. +#[test] +fn trim_source_then_two_offsets_independently_in_either_order() { + for order in [[0, 1, 2], [0, 2, 1]] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "construction": true, "connect": false, "infer": false, "ids": ["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false})); + let mut curves = vec!["source".to_string()]; + curves.extend(ids(&out["curves"])); + assert_eq!(curves.len(), 3); + run(&mut s, "sketch.line", json!({"points": [[-20,20],[60,20]], "connect": false, "infer": false})); + for picked in order { + let before = sketch(&s); + let geometry = |sk: &solidcraft_sketch::Sketch, id: &str| sk.shape(sk.curve_index(id).unwrap()).unwrap(); + let solidcraft_sketch::Shape::Line { a, b } = geometry(&before, &curves[picked]) else { panic!("line") }; + let r = run(&mut s, "sketch.trim", json!({"curve": curves[picked], "at": [a.x + 1.0, a.y + 1.0]})); + assert_eq!(r["sketch"]["solved"], true, "{order:?}: {r}"); + let after = sketch(&s); + let solidcraft_sketch::Shape::Line { a: start, b: end } = geometry(&after, &curves[picked]) else { panic!("line") }; + assert!((start.y - 20.0).abs() < 1e-6 && (start.x - (20.0 + a.x - a.y)).abs() < 1e-6, "{order:?}: {start:?}"); + assert!(end.dist(b) < 1e-6, "the far end stays put: {order:?}: {end:?} {b:?}"); + for (i, id) in curves.iter().enumerate().filter(|(i, _)| *i != picked) { + let solidcraft_sketch::Shape::Line { a: old_a, b: old_b } = geometry(&before, id) else { panic!("line") }; + let solidcraft_sketch::Shape::Line { a: new_a, b: new_b } = geometry(&after, id) else { panic!("line") }; + assert!(new_a.dist(old_a) < 1e-6 && new_b.dist(old_b) < 1e-6, "unpicked {i} changed in {order:?}: {old_a:?} -> {new_a:?}"); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!( + serde_json::to_value(sketch(&s)).unwrap(), + serde_json::to_value(before).unwrap(), + "one undo restores the complete association" + ); + run(&mut s, "edit.redo", json!({})); + assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), serde_json::to_value(after).unwrap()); + } + } +} + +#[test] +fn trim_path_cuts_source_and_two_offsets_at_their_own_crossings() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "construction": true, "connect": false, "infer": false, "ids": ["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false})); + let mut curves = vec!["source".to_string()]; + curves.extend(ids(&out["curves"])); + run(&mut s, "sketch.line", json!({"points": [[-20,20],[60,20]], "connect": false, "infer": false})); + let before = s.doc.to_json(); + let path = json!({"points": [[4,5],[15,5],[-10,5]], "dry_run": true}); + let preview = run(&mut s, "sketch.trim.path", path); + assert_eq!(preview["trimmed"].as_array().unwrap().len(), 3, "{preview}"); + assert_eq!(s.doc.to_json(), before, "preview releases no stored associations or parameters"); + let r = run(&mut s, "sketch.trim.path", json!({"points": [[4,5],[15,5],[-10,5]]})); + assert_eq!(r["trimmed"], preview["trimmed"]); + assert!(r["skipped"].as_array().unwrap().is_empty(), "{r}"); + let sk = sketch(&s); + assert!(sk.offsets.is_empty()); + for id in curves { + let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(&id).unwrap()).unwrap() else { panic!("line") }; + assert!((a.y - 20.0).abs() < 1e-6, "{id}: {a:?}"); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before, "one undo restores all three lines and their associations"); +} + +#[test] +fn trim_whole_source_keeps_its_offsets_and_unrelated_associations() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "connect": false, "infer": false, "ids": ["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false})); + let outputs = ids(&out["curves"]); + run(&mut s, "sketch.line", json!({"points": [[100,100],[120,100]], "connect": false, "infer": false, "ids": ["unrelated"]})); + let other = run(&mut s, "sketch.offset", json!({"curves": ["unrelated"], "distance": 3, "chain": false})); + let before = sketch(&s); + let doc_before = s.doc.to_json(); + let r = run(&mut s, "sketch.trim", json!({"curve": "source", "at": [10,10]})); + assert_eq!(r["result"]["deleted"], "source"); + assert_eq!(r["sketch"]["solved"], true); + let sk = sketch(&s); + assert!(sk.curve_index("source").is_none()); + assert_eq!(sk.offsets.len(), 1); + for id in outputs { + assert_eq!(sk.polyline(sk.curve_index(&id).unwrap()), before.polyline(before.curve_index(&id).unwrap()), "{id}"); + } + let other_output = other["curves"][0].as_str().unwrap(); + assert_eq!(sk.offset_distance(other_output), Some(3.0)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), doc_before); +} + +#[test] +fn trim_keeps_offset_distances_driving_after_trims_drag_and_reopen() { + let verify = |s: &Session, distance: f64, parameter: &str| { + let state = s.world_state().unwrap(); + let sk = &state.sketch(1).unwrap().sketch; + let solidcraft_sketch::Shape::Line { a, b } = sk.shape(sk.curve_index("source").unwrap()).unwrap() else { panic!("source line") }; + let dir = (b - a).normalized().unwrap(); + for (id, sign) in [("l1", 1.0), ("l2", -1.0)] { + let solidcraft_sketch::Shape::Line { a: p, b: q } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("offset line") }; + assert!(dir.cross((q - p).normalized().unwrap()).abs() < 1e-6, "{id} is parallel"); + for point in [p, q] { + assert!((dir.cross(point - a) - sign * distance).abs() < 1e-6, "{id}: {point:?}, distance {distance}"); + } + } + assert!(s.doc.param(parameter).is_some(), "the original driving offset parameter remains"); + assert_eq!(sk.constraints.iter().filter(|c| c.param.as_deref() == Some(parameter)).count(), 2, "both sides retain their dimensions"); + assert!(state.sketch(1).unwrap().report.ok()); + }; + for reverse_outputs in [true, false] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[40,40]],"construction":true,"connect":false,"infer":false,"ids":["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves":["source"],"distance":2,"symmetric":true,"chain":false})); + let parameter = out["param"].as_str().unwrap().to_string(); + let cutter = + run(&mut s, "sketch.line", json!({"points":[[-20,20],[60,20]],"connect":false,"infer":false}))["curves"][0].as_str().unwrap().to_string(); + let order = if reverse_outputs { ["source", "l2", "l1"] } else { ["source", "l1", "l2"] }; + for id in order { + let sk = sketch(&s); + let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("line") }; + run(&mut s, "sketch.trim", json!({"curve":id,"at":[a.x+1.0,a.y+1.0]})); + verify(&s, 2.0, ¶meter); + } + // A second end trim must reattach the existing distance witness to the retained line. + let second_cutter = + run(&mut s, "sketch.line", json!({"points":[[-20,25],[60,25]],"connect":false,"infer":false}))["curves"][0].as_str().unwrap().to_string(); + for id in order { + let sk = sketch(&s); + let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("line") }; + run(&mut s, "sketch.trim", json!({"curve":id,"at":[a.x+1.0,a.y+1.0]})); + verify(&s, 2.0, ¶meter); + } + run(&mut s, "sketch.constraint.fix", json!({"entities":["source",cutter,second_cutter]})); + run(&mut s, "sketch.move_point", json!({"point":"l1.end","to":[55,25]})); + verify(&s, 2.0, ¶meter); + run(&mut s, "parameters.change", json!({"name":parameter,"expression":"3 mm"})); + verify(&s, 3.0, ¶meter); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + verify(&reopened, 3.0, ¶meter); + run(&mut reopened, "parameters.change", json!({"name":parameter,"expression":"4 mm"})); + verify(&reopened, 4.0, ¶meter); + run(&mut reopened, "edit.undo", json!({})); + verify(&reopened, 3.0, ¶meter); + } +} + +/// Breaking a piece again where it was already broken adds nothing: no zero-length piece and +/// no new constraints, however often it is clicked. +#[test] +fn breaking_again_where_a_curve_was_broken_adds_nothing() { + let mut s = new_sketch(); + let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 0]]}))["curves"])[0].clone(); + // A circle tangent to A (as the slot's end arc is to its side): a tangent touch is a double + // root, found as two cuts a hair apart. + let x = 20.0 / 3.0 + 0.123_456_789; + run(&mut s, "sketch.circle.center", json!({"center": [x, 3.0], "radius": 3.0})); + run(&mut s, "sketch.dimension", json!({"entities": [a.clone()], "value": 20})); + run(&mut s, "sketch.break", json!({"curve": a, "at": [5, 0]})); + let count = |s: &Session| { + let k = sketch(s); + (k.curves.len(), k.constraints.len()) + }; + let first = count(&s); + let shown = |s: &Session| { + let k = sketch(s); + k.curves + .iter() + .map(|c| match c.kind { + CurveKind::Line { a, b } => format!("line {:?}-{:?}", k.point(a), k.point(b)), + _ => "other".into(), + }) + .collect::>() + }; + eprintln!("after the first break: {:?}", shown(&s)); + for _ in 0..5 { + let k = sketch(&s); + let left = k + .curves + .iter() + .find(|c| { + matches!(c.kind, CurveKind::Line { .. }) + && k.shape(k.curve_index(&c.id).unwrap()).is_some_and(|sh| sh.project(Vec2::new(5.0, 0.0)).dist(Vec2::new(5.0, 0.0)) < 1e-9) + }) + .map(|c| c.id.clone()); + let Some(left) = left else { panic!("no piece through (5, 0): {:?}", shown(&s)) }; + let _ = s.execute("sketch.break", &json!({"curve": left, "at": [5, 0]})); + let _ = s.execute("sketch.break", &json!({"curve": left, "at": [x - 1e-7, 0]})); + } + let k = sketch(&s); + eprintln!("first {first:?} now {:?}; constraints {:?}", count(&s), k.constraints.iter().map(|c| format!("{:?}", c.kind)).collect::>()); + assert_eq!(count(&s), first, "repeated breaks added curves or constraints"); + // The line stays where it was, 20 long: the length became the distance between its old ends. + let k = sketch(&s); + for c in &k.curves { + if let CurveKind::Line { a, b } = c.kind { + let (pa, pb) = (k.point(a).unwrap(), k.point(b).unwrap()); + assert!(pa.y.abs() < 1e-9 && pb.y.abs() < 1e-9 && pa.dist(pb) > 1e-3, "{:?}", shown(&s)); + } + } + assert!(k.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Distance { value, .. } if close(value, 20.0))), "{:?}", k.constraints); +} diff --git a/crates/engine/src/cmd/sketch_pattern_tests.rs b/crates/engine/src/cmd/sketch_pattern_tests.rs index 68d8a6cd4..633019aa5 100644 --- a/crates/engine/src/cmd/sketch_pattern_tests.rs +++ b/crates/engine/src/cmd/sketch_pattern_tests.rs @@ -698,7 +698,7 @@ fn rectangular_pattern_expressions_follow_parameters_and_survive_reopening() { s.refresh(); run(&mut s, "parameters.change", json!({"name":"pitch","expression":"40"})); run(&mut s, "parameters.change", json!({"name":"copies","expression":"4"})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; assert_eq!(sk.patterns[0].instances.len(), 7); assert_eq!(sk.patterns[0].instances[0].curves[0], first); @@ -706,7 +706,7 @@ fn rectangular_pattern_expressions_follow_parameters_and_survive_reopening() { let last = &sk.patterns[0].instances.last().unwrap().curves[0]; assert!(point(sk, &format!("{last}.center")).dist(Vec2::new(125., 25.)) < 1e-6); run(&mut s, "parameters.change", json!({"name":"copies","expression":"2"})); - assert_eq!(s.world_state().sketch(1).unwrap().sketch.patterns[0].instances.len(), 3); + assert_eq!(s.world_state().unwrap().sketch(1).unwrap().sketch.patterns[0].instances.len(), 3); run(&mut s, "parameters.change", json!({"name":"pitch","new_name":"step"})); assert_eq!(serde_json::to_value(&s.doc.sketch(1).unwrap().patterns[0]).unwrap()["expressions"]["spacing"], "step"); assert!(s.execute("parameters.change", &json!({"delete":"step"})).is_err()); @@ -749,7 +749,7 @@ fn circular_pattern_expressions_validate_inputs_and_keep_numeric_compatibility() let before = sketch(&s); let mut s = Session { doc: reopened.into(), ..Default::default() }; s.refresh(); - let state = s.world_state(); + let state = s.world_state().unwrap(); let after = &state.sketch(1).unwrap().sketch; for (a, b) in before.points.iter().zip(&after.points) { assert!(a.id == b.id && a.pos.dist(b.pos) < 1e-9, "{} moved", a.id); diff --git a/crates/engine/src/cmd/sketch_perf_tests.rs b/crates/engine/src/cmd/sketch_perf_tests.rs index 0f97b4acb..f76d83fa3 100644 --- a/crates/engine/src/cmd/sketch_perf_tests.rs +++ b/crates/engine/src/cmd/sketch_perf_tests.rs @@ -19,7 +19,7 @@ fn big(n: usize) -> Session { let id = s.active_sketch.unwrap(); let mut doc = (*s.doc).clone(); let sk = doc.sketch_mut(id).unwrap(); - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; use solidcraft_sketch::ConstraintKind::*; let side = (n as f64).sqrt().ceil() as usize; for k in 0..n { @@ -83,3 +83,78 @@ fn sketch_perf() { ); } } + +/// Fill sketch `id` with `n` constrained rectangles, each with a circle inside. +fn fill(doc: &mut solidcraft_doc::Document, id: u64, n: usize, x0: f64) { + use solidcore_record::Vec2; + use solidcraft_sketch::ConstraintKind::*; + let Ok(sk) = doc.sketch_mut(id) else { return }; + for k in 0..n { + let (x, y) = (x0 + k as f64 * 30.0, 0.0); + let p: Vec = [(0.0, 0.0), (20.0, 0.3), (20.2, 15.0), (-0.1, 15.1)] + .iter() + .map(|(dx, dy)| sk.add_point(Vec2::new(x + dx, y + dy), None).unwrap()) + .collect(); + let l: Vec = (0..4).map(|i| sk.add_line_pts(p[i], p[(i + 1) % 4], None).unwrap()).collect(); + sk.add_constraint(Horizontal { l: l[0] }, None).unwrap(); + sk.add_constraint(Horizontal { l: l[2] }, None).unwrap(); + sk.add_constraint(Vertical { l: l[1] }, None).unwrap(); + sk.add_constraint(Vertical { l: l[3] }, None).unwrap(); + sk.add_constraint(Length { l: l[0], value: 20.0 }, None).unwrap(); + sk.add_constraint(Length { l: l[1], value: 15.0 }, None).unwrap(); + sk.add_circle(Vec2::new(x + 10.0, y + 7.5), 3.0, None, None).unwrap(); + } +} + +/// A large design (`sketches` sketches of `rects` rectangles, `params` parameters), the first +/// sketch (`first` rectangles) open for editing; per live drag frame: execute time and the +/// time of one copy of the document. +#[test] +#[ignore] +fn sketch_drag_frame_perf() { + let cases: [(usize, usize, usize, usize); 3] = [(50, 10, 200, 2), (200, 20, 500, 2), (200, 20, 500, 50)]; + for (sketches, rects, params, first) in cases { + let mut s = Session::default(); + for i in 0..params { + s.execute("parameters.add", &json!({"name": format!("p{i}"), "expression": format!("{i} mm")})).unwrap(); + } + for k in 0..sketches { + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + let id = s.active_sketch.unwrap(); + let mut doc = (*s.doc).clone(); + fill(&mut doc, id, if k == 0 { first } else { rects }, 0.0); + *s.doc_mut() = doc; + s.execute("sketch.finish", &json!({})).unwrap(); + } + s.execute("sketch.edit", &json!({"sketch": "Sketch1"})).unwrap(); + let curves: usize = s.doc.features.iter().filter_map(|f| s.doc.sketch(f.id).ok()).map(|k| k.curves.len()).sum(); + let json_len = serde_json::to_string(&*s.doc).map(|j| j.len()).unwrap_or(0); + let frames = 60; + let mut frame_ms = Vec::new(); + for f in 0..frames { + let to = [1.0 + f as f64 * 0.05, 1.0 + f as f64 * 0.03]; + let t = Instant::now(); + s.execute("sketch.drag", &json!({"entity": "p1", "from": [0, 0], "to": to, "live": true})).unwrap(); + frame_ms.push(ms(t)); + } + s.execute("sketch.drag_end", &json!({})).ok(); + let digest = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + serde_json::to_string(&*s.doc).unwrap_or_default().hash(&mut h); + format!("{:016x}", h.finish()) + }; + frame_ms.sort_by(f64::total_cmp); + let t = Instant::now(); + for _ in 0..frames { + std::hint::black_box((*s.doc).clone()); + } + let copy = ms(t) / frames as f64; + let frame = frame_ms[frames / 2]; + eprintln!( + "DRAGPERF sketches={sketches} rects={rects} first={first} params={params} features={} curves={curves} json={json_len}B: frame median {frame:.3} ms, one copy {copy:.3} ms ({:.1} %), design {digest}", + s.doc.features.len(), + 100.0 * copy / frame + ); + } +} diff --git a/crates/engine/src/cmd/sketch_point_expr_tests.rs b/crates/engine/src/cmd/sketch_point_expr_tests.rs index 4a3d3c819..390ffb2f7 100644 --- a/crates/engine/src/cmd/sketch_point_expr_tests.rs +++ b/crates/engine/src/cmd/sketch_point_expr_tests.rs @@ -2,7 +2,8 @@ //! where it comes to, and the point follows the parameters without a dimension or a solve. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::Session; @@ -187,3 +188,263 @@ fn a_tangent_from_a_placed_point_keeps_the_side_it_was_drawn_on() { } assert!(flipped.is_empty(), "the tangent went over to the other side, without a word, at {flipped:?}"); } + +#[test] +fn a_rectangle_corner_typed_as_an_expression_follows_its_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let c = run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": ["W / 2", "W / 4"]})); + // A second one, from two corners, one of them mixing a number and an expression. + let t = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [100, 100], "p1": ["100 + W", 100 + 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10})); + no_trouble(&s); + let corner = |r: &Value, k: &str| r["corners"][k].as_str().unwrap_or_default().to_string(); + assert_eq!(solved(&s, &corner(&c, "top_right")), Vec2::new(20.0, 10.0)); + assert_eq!(solved(&s, &corner(&t, "top_right")), Vec2::new(140.0, 110.0)); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "80 mm"})); + no_trouble(&s); + assert_eq!(solved(&s, &corner(&c, "bottom_left")), Vec2::new(-40.0, -20.0)); + assert_eq!(solved(&s, &corner(&c, "top_right")), Vec2::new(40.0, 20.0)); + // The other corners are solved, not placed: equal within the solver's tolerance. + let br = solved(&s, &corner(&t, "bottom_right")); + assert!((br.x - 180.0).abs() < 1e-6 && (br.y - 100.0).abs() < 1e-6, "{br:?}"); + assert!((volume(&mut s) - (80.0 * 40.0 + 80.0 * 10.0) * 10.0).abs() < 1e-6); + // The design file keeps them. + let mut r = reopened(&s); + no_trouble(&r); + assert!((volume(&mut r) - (80.0 * 40.0 + 80.0 * 10.0) * 10.0).abs() < 1e-6); + // An expression that cannot be worked out is refused, and draws nothing. + run(&mut s, "sketch.edit", json!({"sketch": "S"})); + let points = s.doc.sketch(s.doc.find_feature("S").unwrap().id).unwrap().points.len(); + assert!(s.execute("sketch.rectangle.center", &json!({"center": [0, 0], "corner": ["nope", 5]})).is_err()); + assert!(s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, "nope"]})).is_err()); + assert_eq!(s.doc.sketch(s.doc.find_feature("S").unwrap().id).unwrap().points.len(), points); +} + +#[test] +fn a_circle_size_typed_as_an_expression_is_a_dimension_that_follows_its_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "X", "expression": "10 mm"})); + run(&mut s, "parameters.add", json!({"name": "R", "expression": "4 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.circle.center", json!({"center": ["X", 0], "radius": "R", "id": "a"})); + run(&mut s, "sketch.circle.center", json!({"center": [50, 0], "diameter": "R * 4", "id": "b"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10})); + no_trouble(&s); + let radius = |s: &Session, id: &str| { + let f = s.doc.find_feature("S").unwrap().id; + let st = s.model.state(); + let sk = &st.sketch(f).unwrap().sketch; + let c = sk.curves.iter().find(|c| c.id == id).unwrap(); + match c.kind { + solidcraft_sketch::CurveKind::Circle { r, .. } => r, + _ => f64::NAN, + } + }; + assert!((radius(&s, "a") - 4.0).abs() < 1e-9 && (radius(&s, "b") - 8.0).abs() < 1e-9); + let before = volume(&mut s); + run(&mut s, "parameters.change", json!({"name": "R", "expression": "9 mm"})); + no_trouble(&s); + assert!((radius(&s, "a") - 9.0).abs() < 1e-9 && (radius(&s, "b") - 18.0).abs() < 1e-9); + assert!(volume(&mut s) > before); + // A value that is no size is refused with its own message, not a missing one. + run(&mut s, "sketch.edit", json!({"sketch": "S"})); + for bad in [json!({"center": [0, 0], "radius": "nope"}), json!({"center": [0, 0], "radius": "0 mm"}), json!({"center": [0, 0], "radius": true})] { + let e = s.execute("sketch.circle.center", &bad).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(!e.is_empty() && !e.contains("needs `radius` or `diameter`"), "{bad}: {e}"); + } + // `radius` wins over `diameter` whatever its form: a bad one is refused, not passed over. + for bad in [json!({"center": [0, 0], "radius": true, "diameter": 10}), json!({"center": [0, 0], "radius": [1], "diameter": "R"})] { + let e = s.execute("sketch.circle.center", &bad).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("`radius` must be a number"), "{bad}: {e}"); + } + let e = s.execute("sketch.circle.center", &json!({"center": [0, 0]})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("needs `radius` or `diameter`"), "{e}"); + run(&mut s, "sketch.circle.center", json!({"center": [100, 0], "radius": "R", "diameter": 30, "id": "c"})); + run(&mut s, "sketch.circle.center", json!({"center": [150, 0], "radius": 5, "diameter": "R * 2", "id": "d"})); + run(&mut s, "sketch.finish", json!({})); + assert!((circle_radius(&s, "c") - 9.0).abs() < 1e-9 && (circle_radius(&s, "d") - 5.0).abs() < 1e-9); +} + +fn circle_radius(s: &Session, id: &str) -> f64 { + let f = s.doc.find_feature("S").unwrap().id; + let st = s.model.state(); + let sk = &st.sketch(f).unwrap().sketch; + match sk.curves.iter().find(|c| c.id == id).map(|c| &c.kind) { + Some(solidcraft_sketch::CurveKind::Circle { r, .. }) => *r, + _ => f64::NAN, + } +} + +fn corner_at(s: &Session, r: &Value, k: &str) -> Vec2 { + solved(s, r["corners"][k].as_str().unwrap_or_default()) +} + +#[test] +fn a_centre_rectangle_follows_its_parameters_from_any_quadrant_and_an_expression_centre() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let rects: Vec = [(1.0, 1.0), (-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)] + .iter() + .enumerate() + .map(|(i, (sx, sy))| { + let at = 200.0 * i as f64; + let corner = json!([format!("{at} + {sx} * W / 2"), format!("{sy} * W / 4")]); + run( + &mut s, + "sketch.rectangle.center", // The centre is held by an expression (a plain-number centre stays free: it moves with the solver). + json!({"center": [format!("{at} + 0 * W"), "0 * W"], "corner": corner}), + ) + }) + .collect(); + // An expression centre too, with a corner expressed from it. + let c = run(&mut s, "sketch.rectangle.center", json!({"center": [1000, "W"], "corner": [1010, "W + 5"]})); + let e = run(&mut s, "sketch.rectangle.center", json!({"center": ["W * 20", "-W"], "corner": ["W * 20 + 10", "-W - 5"]})); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "80 mm"})); + no_trouble(&s); + for (i, r) in rects.iter().enumerate() { + let at = 200.0 * i as f64; + let (bl, tr) = (corner_at(&s, r, "bottom_left"), corner_at(&s, r, "top_right")); + assert!((bl.x - (at - 40.0)).abs() < 1e-6 && (bl.y + 20.0).abs() < 1e-6, "{i}: {bl:?}"); + assert!((tr.x - (at + 40.0)).abs() < 1e-6 && (tr.y - 20.0).abs() < 1e-6, "{i}: {tr:?}"); + } + let (bl, tr) = (corner_at(&s, &c, "bottom_left"), corner_at(&s, &c, "top_right")); + assert!((bl.x - 990.0).abs() < 1e-6 && (bl.y - 75.0).abs() < 1e-6 && (tr.x - 1010.0).abs() < 1e-6 && (tr.y - 85.0).abs() < 1e-6, "{bl:?} {tr:?}"); + let (bl, tr) = (corner_at(&s, &e, "bottom_left"), corner_at(&s, &e, "top_right")); + assert!( + (bl.x - 1590.0).abs() < 1e-6 && (bl.y + 85.0).abs() < 1e-6 && (tr.x - 1610.0).abs() < 1e-6 && (tr.y + 75.0).abs() < 1e-6, + "{bl:?} {tr:?}" + ); +} + +#[test] +fn a_two_point_rectangle_drawn_from_swapped_corners_follows_its_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + // p0 is the top right, p1 the bottom left: each coordinate is kept with its corner. + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": ["W", "W / 2"], "p1": [0, 0]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "60 mm"})); + no_trouble(&s); + assert_eq!(corner_at(&s, &r, "top_right"), Vec2::new(60.0, 30.0)); + let bl = corner_at(&s, &r, "bottom_left"); + assert!(bl.x.abs() < 1e-9 && bl.y.abs() < 1e-9, "{bl:?}"); +} + +#[test] +fn a_size_expression_reads_in_the_design_unit_and_one_naming_no_parameter_is_a_number() { + let mut s = Session::default(); + run(&mut s, "document.units", json!({"units": "in"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let params = s.doc.params.len(); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": "1", "id": "a"})); + run(&mut s, "sketch.circle.center", json!({"center": [50, 0], "radius": "2 in", "id": "b"})); + run(&mut s, "sketch.circle.center", json!({"center": [100, 0], "diameter": "1", "id": "c"})); + // An expression naming no parameter is the number it comes to: no dimension behind it. + assert_eq!(s.doc.params.len(), params); + assert!( + (circle_radius(&s, "a") - 25.4).abs() < 1e-9 && (circle_radius(&s, "b") - 50.8).abs() < 1e-9 && (circle_radius(&s, "c") - 12.7).abs() < 1e-9 + ); + run(&mut s, "parameters.add", json!({"name": "R", "expression": "1 in"})); + run(&mut s, "sketch.circle.center", json!({"center": [150, 0], "radius": "R / 2", "id": "d"})); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); + assert!((circle_radius(&s, "d") - 12.7).abs() < 1e-9); + run(&mut s, "parameters.change", json!({"name": "R", "expression": "2 in"})); + no_trouble(&s); + assert!((circle_radius(&s, "d") - 25.4).abs() < 1e-9); + // The 2-tangent circle reads a bare number typed as text the same way. + run(&mut s, "sketch.edit", json!({"sketch": "S"})); + let x = run(&mut s, "sketch.line", json!({"points": [[200, 0], [300, 0]]})); + let y = run(&mut s, "sketch.line", json!({"points": [[200, 0], [200, 100]], "connect": false})); + let t = run(&mut s, "sketch.circle.two_tangent", json!({"curves": [x["curves"][0], y["curves"][0]], "radius": "1", "near": [225, 25]})); + let id = t["curves"][0].as_str().unwrap_or_default().to_string(); + assert!((circle_radius_live(&s, &id) - 25.4).abs() < 1e-6); +} + +/// The radius of circle `id` in the sketch being edited. +fn circle_radius_live(s: &Session, id: &str) -> f64 { + let f = s.doc.find_feature("S").unwrap().id; + match s.doc.sketch(f).ok().and_then(|sk| sk.curves.iter().find(|c| c.id == id).map(|c| c.kind.clone())) { + Some(solidcraft_sketch::CurveKind::Circle { r, .. }) => r, + _ => f64::NAN, + } +} + +#[test] +fn a_rejected_size_or_corner_expression_leaves_nothing_behind() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let f = s.doc.find_feature("S").unwrap().id; + let count = |s: &Session| { + let sk = s.doc.sketch(f).unwrap(); + (sk.points.len(), sk.curves.len(), sk.constraints.len(), s.doc.params.len()) + }; + let before = count(&s); + let tries = [ + ("sketch.circle.center", json!({"center": ["W", 0], "radius": "W - 40"})), + ("sketch.circle.center", json!({"center": ["W", 0], "radius": "nope"})), + ("sketch.circle.center", json!({"center": ["W", 0], "radius": "W", "id": "bad|id"})), + ("sketch.rectangle.center", json!({"center": ["W", 0], "corner": ["W", 5]})), + ("sketch.rectangle.two_point", json!({"p0": ["W", 0], "p1": ["W", 5]})), + ]; + for (cmd, p) in tries { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + assert_eq!(count(&s), before, "{cmd} {p}"); + } +} + +/// A corner typed as an expression that comes to 0 when drawn lands on the origin; it must not +/// be tied to it by the automatic Coincident a snapped click gets, or the next parameter change +/// conflicts with the tie (#10703). +#[test] +fn a_rectangle_corner_whose_expression_is_zero_when_drawn_is_not_tied_to_the_origin() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "x0", "expression": "0 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": ["x0", 0], "p1": [40, 30]})); + assert_eq!(r["constraints"].as_array().map(Vec::len), Some(4), "the four side constraints, no Coincident to the origin: {r}"); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10})); + no_trouble(&s); + assert!((volume(&mut s) - 40.0 * 30.0 * 10.0).abs() < 1e-6); + run(&mut s, "parameters.change", json!({"name": "x0", "expression": "15 mm"})); + no_trouble(&s); + assert!((volume(&mut s) - 25.0 * 30.0 * 10.0).abs() < 1e-6); +} + +/// The same for a lone `sketch.point`: an expression that comes to the origin at draw time +/// leaves the point free, and it follows the parameter from there (#10703). +#[test] +fn a_point_whose_expression_is_zero_when_drawn_is_not_tied_to_the_origin() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "x0", "expression": "0 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.point", json!({"point": ["x0", 0], "id": "p"})); + assert_eq!(r["constraints"].as_array().map(Vec::len), Some(0), "no Coincident to the origin: {r}"); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); + run(&mut s, "parameters.change", json!({"name": "x0", "expression": "15 mm"})); + no_trouble(&s); + assert_eq!(solved(&s, "p"), Vec2::new(15.0, 0.0)); +} + +/// A corner given as plain numbers on the origin still snaps to it, as a clicked point does: +/// only expression-placed points are exempt from the automatic Coincident. +#[test] +fn a_plain_corner_on_the_origin_still_snaps_to_it() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + assert_eq!(r["constraints"].as_array().map(Vec::len), Some(5), "the four side constraints plus the Coincident to the origin: {r}"); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); +} diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index 6bbdbad5e..915b596bd 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -4,10 +4,11 @@ //! normal geometry. use serde_json::{Value, json}; +use solidcore_record::{Plane, Vec2, Vec3}; use solidcraft_doc::project::resolve; use solidcraft_doc::{Document, FeatureKind}; -use solidcraft_geom::{Plane, Vec2, Vec3}; -use solidcraft_sketch::{ConstraintKind, LinkKind, LinkSource, Sketch, nearest_crossing}; +use solidcraft_geom::prelude::*; +use solidcraft_sketch::{ConstraintKind, LinkKind, LinkSource, Sketch}; use super::sketch_store; use super::{CommandSpec, in_sketch}; @@ -16,7 +17,7 @@ use crate::{EngineError, Result, Session}; macro_rules! refs_doc { () => { - "refs: [{edge: [x,y,z], body?} | {face: [x,y,z], body?} (its edge loops) | {body: name} (silhouette) | {vertex: [x,y,z], body?} | {sketch, curve} | {sketch, point} | \"origin\" | {axis: X|Y|Z} | {plane: XY|XZ|YZ|name}]" + "refs: [{edge: [x,y,z], body?} | {face: [x,y,z], body?} (its edge loops) | {body: name} (silhouette) | {vertex: [x,y,z], body?} | {sketch, curve} | {sketch, point} | \"origin\" | {axis: X|Y|Z|name} | {plane: XY|XZ|YZ|name}]" }; } @@ -110,7 +111,7 @@ fn source(s: &Session, v: &Value, cmd: &str) -> Result { return Ok(LinkSource::Body { body: b.to_string() }); } if let Some(a) = str_(v, "axis") { - return Ok(LinkSource::Axis { name: a.to_ascii_uppercase() }); + return axis_source(s, a, cmd); } if let Some(p) = str_(v, "plane") { return Ok(LinkSource::Plane { name: p.to_string() }); @@ -121,6 +122,17 @@ fn source(s: &Session, v: &Value, cmd: &str) -> Result { Err(bad(cmd, format!("cannot project {v}"))) } +/// An origin axis (`X`, `Y` or `Z`, in any case), or a construction axis by its name (#9324). +fn axis_source(s: &Session, name: &str, cmd: &str) -> Result { + if ["X", "Y", "Z"].iter().any(|axis| name.eq_ignore_ascii_case(axis)) { + return Ok(LinkSource::Axis { name: name.to_ascii_uppercase() }); + } + match s.doc.find_feature(name) { + Some(f) if matches!(f.kind, FeatureKind::ConstructionAxis { .. }) => Ok(LinkSource::Axis { name: f.name.clone() }), + _ => Err(bad(cmd, format!("unknown axis `{name}`: X, Y, Z or the name of a construction axis"))), + } +} + /// The plane of a sketch feature, resolved against `st`: the model before the sketch as its /// component sees it, which is what evaluation resolves it against. A construction plane built /// from the model (through a sketch line, three points, between two faces…) exists only there. @@ -147,7 +159,7 @@ fn state_for_sketch<'a>( }); match attachment { Some(anchor) => solidcraft_doc::state_in_face_anchor_frame(doc, st, anchor, comp), - None => Ok(solidcraft_doc::state_in_frame_at(doc, st, comp, owner_frame(s, doc, comp))), + None => solidcraft_doc::state_in_frame_at(doc, st, comp, owner_frame(s, doc, comp)), } } @@ -197,10 +209,16 @@ pub(super) fn refresh(s: &Session, doc: &Document, id: u64, sk: &mut Sketch) -> return vec!["lost face attachment; reattach explicitly".into()]; }; let Ok(plane) = sketch_plane(&doc, id, &st) else { return Vec::new() }; - let warnings = match attachment { + let refreshed = match attachment { Some(anchor) => solidcraft_doc::project::refresh_face_anchor_links(&doc, &vals, &st, &plane, sk, anchor), None => solidcraft_doc::project::refresh_links(&doc, &vals, &st, &plane, sk), }; + // A link whose named face or edge is gone fails the sketch when it is evaluated; while it is + // edited, that is what the refresh says. + let warnings = match refreshed { + Ok(warnings) => warnings, + Err(e) => return vec![e.in_feature(&doc.feature(id).map(|f| f.name.clone()).unwrap_or_default()).to_string()], + }; if let Ok(stored) = sketch_store::read(&doc, id) && sk.positions_in(stored).is_some() { @@ -296,6 +314,9 @@ fn add_link_unless_present( // The link is the edge that was picked, not whichever is nearest the picked point later. let edge_name = solidcraft_doc::project::resolved_edge_name(&st, &r); let link = sk.add_link_with_wires(kind, r.source, &r.geom, &r.wires)?; + // The wires' exact curves, as a refresh of the link gives them (an included edge's record + // curve): a link made now is the one its sketch would resolve. + sk.set_link_wire_curves(&link, &r.exact)?; if let Some(l) = sk.links.iter_mut().find(|l| l.id == link) { l.face_name = name; l.edge_name = edge_name; @@ -674,9 +695,9 @@ pub(super) fn snap_points(s: &mut Session, p: &Value, cmd: &str) -> Result Option { + let r = s.model.result(s.doc.find_feature("Top").unwrap().id).unwrap(); + r.error.as_deref().and_then(solidcraft_doc::reselect_parts).filter(|(feature, _)| *feature == "Top").map(|(_, reference)| reference.to_string()) +} + /// A slot cut through the plate from x = 80 to 120, y = 20 to 30 leaves the picked edge in two -/// pieces, y = 0..20 and y = 30..50. The link, picked at y = 10, gives the piece it was picked -/// on and says the edge was split; without the slot it is the whole edge again. +/// pieces, y = 0..20 and y = 30..50. Neither is the edge: the sketch fails, asking for it again +/// (never the piece nearest the pick); without the slot it is the whole edge again. #[test] -fn a_projected_edge_that_was_split_gives_its_nearest_piece_and_says_so() { +fn a_projected_edge_that_was_split_fails_its_sketch_asking_for_the_edge_again() { let mut s = Session::default(); plate(&mut s); run(&mut s, "sketch.create", json!({"plane": "XY", "name": "SlotSketch"})); @@ -133,31 +140,28 @@ fn a_projected_edge_that_was_split_gives_its_nearest_piece_and_says_so() { run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": true})); project_right_edge(&mut s, 10.0); assert_line(&s, 100.0, (0.0, 50.0), "drawn"); + let name = stored(&s).edge_name.unwrap(); run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": false})); - assert_line(&s, 100.0, (0.0, 20.0), "split"); - assert!(trouble(&s).contains("was split"), "{}", trouble(&s)); - assert!(!link(&s).lost); + assert_eq!(reselect(&s), Some(name), "{}", trouble(&s)); run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": true})); assert_line(&s, 100.0, (0.0, 50.0), "whole again"); assert_eq!(trouble(&s), ""); } /// A fillet of radius 4 takes the picked edge away. Its two tangent edges are 4 from the picked -/// point, the nearest edges there are now: the link is lost and keeps its line, it takes -/// neither of them. Without the fillet the link has its edge again. +/// point, the nearest edges there are now: the sketch takes neither of them, it fails, asking for +/// its edge again. Without the fillet the link has its edge again. #[test] -fn a_projected_edge_that_is_gone_is_lost_not_replaced() { +fn a_projected_edge_that_is_gone_fails_its_sketch_not_replaced() { let mut s = Session::default(); plate(&mut s); run(&mut s, "solid.fillet", json!({"edges": [[100, 25, 20]], "radius": "4 mm", "name": "Round"})); run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": true})); project_right_edge(&mut s, 25.0); assert_line(&s, 100.0, (0.0, 50.0), "drawn"); + let name = stored(&s).edge_name.unwrap(); run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": false})); - let said = trouble(&s); - assert!(said.contains("projected reference lost: edge") && said.contains("no longer exists"), "{said}"); - assert!(link(&s).lost); - assert_line(&s, 100.0, (0.0, 50.0), "the last geometry is kept"); + assert_eq!(reselect(&s), Some(name), "{}", trouble(&s)); run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": true})); assert_eq!(trouble(&s), ""); assert!(!link(&s).lost); diff --git a/crates/engine/src/cmd/sketch_project_side_tests.rs b/crates/engine/src/cmd/sketch_project_side_tests.rs index 9b43f1a21..2a3283432 100644 --- a/crates/engine/src/cmd/sketch_project_side_tests.rs +++ b/crates/engine/src/cmd/sketch_project_side_tests.rs @@ -3,7 +3,8 @@ //! line, also past the place the point is stored at. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::Session; @@ -86,6 +87,77 @@ fn a_distance_from_a_projected_line_keeps_its_side_when_the_source_moves_past() assert_p(&s, 15.0, "after an edit"); } +/// A label's sketch: three points brought in from sketch `A` (a 20 long vertical line whose start +/// the parameters `x` and `y` place, and its middle), a construction rectangle 5 wide on them +/// (its near side on the line's ends, its far side 5 from the middle) and a centred text on the +/// far side whose words the text parameter `Label` gives. Other words are other outlines: the text +/// is built anew in the evaluated sketch, so its entities are not the stored sketch's. Moved 280 +/// away afterwards (more than one jump can take: the solve walks there from the stored sketch), the +/// rectangle follows and keeps its side. +#[test] +fn a_label_follows_its_source_far_after_a_text_parameter_gave_it_other_words() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "x", "expression": "100 mm"})); + run(&mut s, "parameters.add", json!({"name": "y", "expression": "200 mm"})); + run(&mut s, "parameters.add", json!({"name": "Label", "expression": "A1", "unit": "text"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "A"})); + run(&mut s, "sketch.line", json!({"points": [[100, 200], [100, 180]], "ids": ["rail"]})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "rail", "mode": "vertical"})); + run(&mut s, "sketch.dimension", json!({"entities": ["origin", "rail.start"], "type": "horizontal", "value": "x"})); + run(&mut s, "sketch.dimension", json!({"entities": ["origin", "rail.start"], "type": "vertical", "value": "y"})); + run(&mut s, "sketch.dimension", json!({"entities": ["rail"], "value": "20 mm"})); + run(&mut s, "sketch.point", json!({"point": [100, 190], "id": "mid"})); + run(&mut s, "sketch.constraint.midpoint", json!({"point": "mid", "line": "rail"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let refs = ["rail.start", "rail.end", "mid"].map(|p| json!({"sketch": "A", "point": p})); + let r = run(&mut s, "sketch.project", json!({"refs": refs})); + let brought: Vec = (0..3).map(|i| r["links"][i]["points"][0].as_str().unwrap().to_string()).collect(); + let near = 100.0 - 5.0; + for (id, a, b) in [ + ("l1", [100.0, 200.0], [100.0, 180.0]), + ("l2", [near, 200.0], [near, 180.0]), + ("l3", [100.0, 200.0], [near, 200.0]), + ("l4", [100.0, 180.0], [near, 180.0]), + ] { + run(&mut s, "sketch.line", json!({"points": [a, b], "ids": [id], "construction": true, "connect": false})); + } + for (a, b) in [ + ("l1.start", brought[0].as_str()), + ("l1.end", &brought[1]), + ("l3.start", "l1.start"), + ("l3.end", "l2.start"), + ("l4.start", "l1.end"), + ("l4.end", "l2.end"), + ] { + run(&mut s, "sketch.constraint.coincident", json!({"a": a, "b": b})); + } + run(&mut s, "sketch.constraint.parallel", json!({"a": "l2", "b": "l1"})); + run(&mut s, "sketch.dimension", json!({"entities": [brought[2], "l2"], "type": "distance", "value": "5 mm"})); + run(&mut s, "sketch.constraint.perpendicular", json!({"a": "l3", "b": "l1"})); + run(&mut s, "sketch.constraint.perpendicular", json!({"a": "l4", "b": "l1"})); + run(&mut s, "sketch.text", json!({"text_expression": "Label + '-1'", "at": [0, 0], "height": 3, "align": "center", "path": "l2"})); + run(&mut s, "sketch.finish", json!({})); + let far_side = |s: &Session| { + let st = s.model.state(); + let sk = &st.sketch(s.doc.find_feature("S").unwrap().id).unwrap().sketch; + sk.point(sk.resolve_point("l2.start").unwrap()).unwrap() + }; + #[track_caller] + fn quiet(s: &Session, when: &str) { + let feature = s.model.result(s.doc.find_feature("S").unwrap().id).unwrap(); + assert_eq!((&feature.error, &feature.warning), (&None, &None), "{when}"); + } + quiet(&s, "drawn"); + run(&mut s, "parameters.change", json!({"name": "Label", "expression": "B2"})); + quiet(&s, "relabelled"); + for (x, y) in [(300.0, 400.0), (100.0, 200.0)] { + run(&mut s, "parameters.change", json!({"changes": {"x": format!("{x} mm"), "y": format!("{y} mm")}})); + quiet(&s, &format!("moved to ({x}, {y})")); + assert!(far_side(&s).dist(Vec2::new(x - 5.0, y)) < 1e-6, "({x}, {y}): {:?}", far_side(&s)); + } +} + /// The same from the other side: the point above the line, the source rising past it and /// coming back; and with the line brought in by Include 3D Geometry. #[test] diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index 2e36a214c..d2e5f8cec 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -1,4 +1,5 @@ use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -36,7 +37,7 @@ fn manual_projection_captures_the_requested_coincident_body_producer() { assert!(matches!(&sk.links[0].source,solidcraft_sketch::LinkSource::Face{body,at} if body=="Target" && (at.z-20.).abs()<1e-6)); assert!(sk.points.iter().any(|point| point.pos.x > 19.)); assert!(sk.points.iter().any(|point| point.pos.y > 19.)); - assert!((session.world_state().body("Control").unwrap().mesh().bounds().max.z - 10.).abs() < 1e-6); + assert!((session.world_state().unwrap().body("Control").unwrap().mesh().bounds().max.z - 10.).abs() < 1e-6); }; verify(&s); verify(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap())); @@ -48,12 +49,12 @@ fn initial_projection_retains_selected_face_when_closest_point_lands_on_shared_e run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10,"body_name":"Target"})); let state = s.model.state(); let body = state.body("Target").unwrap(); - let source = solidcraft_sketch::LinkSource::Face { body: "Target".into(), at: solidcraft_geom::Vec3::new(-0.1, 5., 10.5) }; + let source = solidcraft_sketch::LinkSource::Face { body: "Target".into(), at: solidcore_record::Vec3::new(-0.1, 5., 10.5) }; let resolved = solidcraft_doc::project::resolve( &s.doc, &std::collections::BTreeMap::new(), &state, - &solidcraft_geom::Plane::XY, + &solidcore_record::Plane::XY, solidcraft_sketch::LinkKind::Project, &source, ) @@ -216,6 +217,53 @@ fn project_edges_bodies_sketches_and_origin() { assert!(s.execute("sketch.project", &json!({"refs": [{"plane": "XY"}]})).is_err(), "parallel plane projects to nothing"); } +/// A construction axis projects as an origin axis does, as its line in the sketch plane, and stays +/// linked to it: the projection follows when the axis moves and when it is renamed. The report's +/// steps (#9324): the axis made after the sketch, then moved before it. +#[test] +fn a_construction_axis_projects_and_stays_linked() { + let mut s = Session::default(); + let sketch = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.finish", json!({})); + let axis = |x: f64| json!({"a": {"point": [x, 0, 0]}, "b": {"point": [x, 30, 0]}, "name": "Axis1"}); + run(&mut s, "construct.axis.two_points", axis(10.0)); + run(&mut s, "timeline.reorder", json!({"feature": "Axis1", "position": 0})); + run(&mut s, "sketch.edit", json!({"sketch": sketch})); + let r = run(&mut s, "sketch.project", json!({"refs": [{"axis": "Axis1"}]})); + let line = r["links"][0]["curves"][0].clone(); + // Where the projected line runs: its two ends' x, and its length along y. + let at = |s: &mut Session| { + run(s, "sketch.edit", json!({"sketch": sketch})); + let si = inspect(s); + let c = si["curves"].as_array().unwrap().iter().find(|c| c["id"] == line).cloned().unwrap(); + run(s, "sketch.finish", json!({})); + let n = |v: &Value| v.as_f64().unwrap(); + (n(&c["start_at"][0]), n(&c["end_at"][0]), (n(&c["end_at"][1]) - n(&c["start_at"][1])).abs()) + }; + run(&mut s, "sketch.finish", json!({})); + let (x0, x1, length) = at(&mut s); + assert!((x0 - 10.0).abs() < 1e-9 && (x1 - 10.0).abs() < 1e-9 && length > 30.0, "{x0} {x1} {length}"); + run(&mut s, "timeline.redefine", json!({"feature": "Axis1", "command": "construct.axis.two_points", "params": axis(25.0)})); + let (x0, x1, _) = at(&mut s); + assert!((x0 - 25.0).abs() < 1e-9 && (x1 - 25.0).abs() < 1e-9, "the projection follows the axis: {x0} {x1}"); + run(&mut s, "timeline.rename", json!({"feature": "Axis1", "name": "Hinge axis"})); + let state = s.model.state(); + let link = &state.sketch(sketch).unwrap().sketch.links[0]; + assert_eq!(link.source, solidcraft_sketch::LinkSource::Axis { name: "Hinge axis".into() }); + assert!(!link.lost, "renamed, the axis is still found"); + // A design with the axis after the sketch opens with the link lost, saying why. + run(&mut s, "timeline.reorder", json!({"feature": "Hinge axis", "position": 1})); + let opened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(opened.model.state().sketch(sketch).unwrap().sketch.links[0].lost); + let warnings = opened.model.result(sketch).and_then(|r| r.warning.clone()).unwrap_or_default(); + assert!(warnings.contains("it must come earlier in the timeline"), "{warnings}"); + run(&mut s, "timeline.reorder", json!({"feature": "Hinge axis", "position": 0})); + // An axis that is no origin axis and no construction axis is refused, by its name. + run(&mut s, "sketch.edit", json!({"sketch": sketch})); + let error = s.execute("sketch.project", &json!({"refs": [{"axis": "Axis9"}]})).unwrap_err().to_string(); + assert!(error.contains("unknown axis `Axis9`"), "{error}"); +} + #[test] fn project_whole_body_can_create_unlinked_geometry() { let mut s = Session::default(); @@ -333,21 +381,20 @@ fn deleting_one_edge_of_a_projected_face_keeps_the_others_as_they_were() { assert!(s.doc.sketch(id).unwrap().links.is_empty()); } +/// The edge a projection was made from goes with its body: the sketch fails, asking for the edge +/// again, instead of keeping a lost link. #[test] -fn lost_reference_keeps_geometry_with_a_warning() { +fn a_reference_whose_body_is_gone_fails_its_sketch_asking_for_it_again() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); let boxf = s.doc.features.last().unwrap().id; run(&mut s, "sketch.create", json!({"plane": "XY"})); run(&mut s, "sketch.project", json!({"refs": [{"edge": [5, 0, 10]}]})); run(&mut s, "sketch.finish", json!({})); + let name = s.doc.sketch(s.doc.features.last().unwrap().id).unwrap().links[0].edge_name.clone().unwrap(); run(&mut s, "timeline.suppress", json!({"feature": boxf, "suppressed": true})); - let st = s.model.state(); - let ss = st.sketches.last().unwrap(); - assert_eq!(ss.sketch.curves.len(), 1, "geometry kept"); - assert!(ss.sketch.links[0].lost); - let w = s.model.results.last().unwrap().warning.clone().unwrap_or_default(); - assert!(w.contains("lost"), "{w}"); + let r = s.model.results.last().unwrap(); + assert_eq!(r.error.as_deref().and_then(solidcraft_doc::reselect_parts), Some((r.name.as_str(), name.as_str())), "{r:?}"); } #[test] @@ -408,14 +455,28 @@ fn three_d_sketch_curves() { let src = s.doc.features.last().unwrap().id; run(&mut s, "sketch.create", json!({"plane": "XY"})); let r = run(&mut s, "sketch.project_to_surface", json!({"curves": [{"sketch": src, "curve": l}], "face": [0, 0, 20]})); + // The line's projection where it first meets the sphere: the arc of the great circle in y = 0 + // from x = -10 to 10 over the top (z = √(400 − x²)), one wire though SMLib splits it at the + // pole, and no curve on the far side. + assert_eq!(r["links"][0]["wires"].as_array().unwrap().len(), 1, "{r}"); let wid = r["links"][0]["wires"][0].as_str().unwrap().to_string(); let st = s.model.state(); let sk = &st.sketch(s.active_sketch.unwrap()).unwrap().sketch; let w = &sk.wires[sk.wire_index(&wid).unwrap()]; - assert!(w.pts.len() > 20); - for p in &w.pts { - assert!((p.len() - 20.0).abs() < 0.1, "{p:?}"); - assert!(p.z > 0.0); + assert!(!w.exact.is_empty()); + // SMLib makes projected curves to a millionth of the body's size (the sphere's 40 mm box). + let tol = 40.0 * 1e-6; + let ends = [*w.pts.first().unwrap(), *w.pts.last().unwrap()]; + let top = 300f64.sqrt(); + assert!(ends.iter().all(|e| (e.x.abs() - 10.0).abs() < tol && e.y.abs() < tol && (e.z - top).abs() < tol), "{ends:?}"); + assert!((ends[0].x + ends[1].x).abs() < tol, "{ends:?}"); + // Along its exact curves (the wire's points are its spans' polygon), on the sphere's top. + for c in &w.exact { + let eval = solidcraft_geom::brep::eval::CurveEval::new(&c.curve).unwrap(); + for k in 0..=32 { + let p = eval.point(c.interval[0] + (c.interval[1] - c.interval[0]) * f64::from(k) / 32.0).unwrap(); + assert!((p.len() - 20.0).abs() < tol && p.y.abs() < tol && p.z >= top - tol, "{p:?}"); + } } // Delete the wire. run(&mut s, "sketch.delete", json!({"entities": [wid]})); @@ -453,6 +514,77 @@ fn three_d_sketch_curves() { assert!((c["start_at"][0].as_f64().unwrap().abs() - 6.0).abs() < 1e-3, "{c}"); } +/// #9009: picked faces intersect as the viewport picks them, the whole surface patch, not just the +/// B-rep piece under the pick; a fit-point spline's wall is one face per span joined by hidden seams. +#[test] +fn intersection_curve_of_picked_faces_spans_the_whole_surface() { + use solidcore_record::Plane; + use solidcraft_doc::project::resolve; + use solidcraft_sketch::{LinkKind, LinkSource}; + use std::collections::BTreeMap; + + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "wall_h", "expression": "20 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Wave"})); + let wave = ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [9.5, 12], [30.5, 7], [52, 15]]}))["curves"])[0].clone(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "surface.extrude", json!({"sketch": "Wave", "curves": [wave], "distance": "wall_h", "body_name": "Wall"})); + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Roof"})); + // XZ sketch y is world -Z, so the arc peaks at world z = 15. + let arc = run(&mut s, "sketch.arc.three_point", json!({"start": [0, 0], "end": [50, 0], "through": [25, -15]}))["created"]["curves"][0] + .as_str() + .unwrap() + .to_string(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "surface.extrude", json!({"sketch": "Roof", "curves": [arc], "distance": 30, "body_name": "Roof"})); + + let st = s.model.state(); + let wall = st.body("Wall").unwrap(); + let m = wall.mesh(); + assert!(wall.body.face_count() > 1, "premise of #9009: one face per spline span"); + assert_eq!(m.surface_patch(m.tri_face[0] as usize).len(), wall.body.face_count(), "premise: the spans are one surface patch (hidden seams)"); + // A pick on the middle span, away from the joins at x = 9.5 and x = 30.5. + let pick = + *m.positions.iter().min_by(|a, b| ((a.x - 20.).abs() + (a.z - 10.).abs()).total_cmp(&((b.x - 20.).abs() + (b.z - 10.).abs()))).unwrap(); + + let check = |s: &Session, id: u64| { + let st = s.model.state(); + let sk = &st.sketch(id).unwrap().sketch; + assert!(sk.links.iter().all(|l| !l.lost), "no link lost"); + let pts: Vec<_> = sk.wires.iter().flat_map(|w| w.pts.iter().copied()).collect(); + assert!(!pts.is_empty()); + let (lo, hi) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), p| (l.min(p.x), h.max(p.x))); + assert!(lo < 1.0 && hi > 49.0, "the whole crossing, not one span: x {lo}..{hi}"); + for p in &pts { + assert!((((p.x - 25.).powi(2) + (p.z + 40. / 3.).powi(2)).sqrt() - 85. / 3.).abs() < 0.1, "{p:?}"); + assert!(p.y > -1e-6 && p.y < 30. + 1e-6, "{p:?}"); + } + }; + + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let id = s.active_sketch.unwrap(); + let r = run( + &mut s, + "sketch.intersection_curve", + json!({"a": {"face": [pick.x, pick.y, pick.z], "body": "Wall"}, "b": {"face": [25, 15, 15], "body": "Roof"}}), + ); + assert!(!r["wires"].as_array().unwrap().is_empty(), "{r}"); + check(&s, id); + + // The same as giving the two bodies. + let st = s.model.state(); + let body = |n: &str| Box::new(LinkSource::Body { body: n.to_string() }); + let whole = resolve(&s.doc, &BTreeMap::new(), &st, &Plane::XY, LinkKind::Include, &LinkSource::Intersection { a: body("Wall"), b: body("Roof") }) + .unwrap(); + let sk = &st.sketch(id).unwrap().sketch; + assert_eq!(sk.wires.len(), whole.wires.len()); + + // Editing the wall re-resolves the stored pick to the same patch. + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "parameters.change", json!({"name": "wall_h", "expression": "25 mm"})); + check(&s, id); +} + #[test] fn isoparametric_curves_of_a_cylinder() { let mut s = Session::default(); @@ -481,10 +613,11 @@ fn tilted_circles_project_to_exact_ellipses_and_splines_stay_splines() { run(&mut s, "sketch.create", json!({"plane": "XY", "offset": -10})); // The base circle (centred at the origin) seen from above. let r = run(&mut s, "sketch.project", json!({"refs": [{"edge": [0, 5, 0]}]})); - // One seam half: exact conics (rational quadratic arcs). + // The rim is one closed circle edge: an exact ellipse, x semi-axis 5·cos 45° (the tilt), y 5. let si = inspect(&mut s); let c = si["curves"].as_array().unwrap().iter().find(|c| c["id"] == r["links"][0]["curves"][0]).unwrap().clone(); - assert_eq!(c["type"], "conic", "{c}"); + assert_eq!(c["type"], "ellipse", "{c}"); + assert!((c["minor_radius"].as_f64().unwrap() - 5.0 * std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{c}"); let st = s.model.state(); let sk = &st.sketch(s.active_sketch.unwrap()).unwrap().sketch; for ci in sk.link_curves(r["links"][0]["link"].as_str().unwrap()) { @@ -494,7 +627,7 @@ fn tilted_circles_project_to_exact_ellipses_and_splines_stay_splines() { assert!((e - 1.0).abs() < 1e-9, "{q:?}"); } } - // The whole face (both halves of its rim, plus its seam) gives the full ellipse. + // The whole face (its rim, plus its seam) gives the full ellipse. let r = run(&mut s, "sketch.project", json!({"refs": [{"face": [0, 0, 0]}]})); let si = inspect(&mut s); let types: Vec = r["links"][0]["curves"] @@ -558,7 +691,7 @@ fn sweeps_and_pipes_follow_3d_sketch_curves() { // A sweep of a square profile drawn square to the curve at its start. let (a, b) = (pts[0], pts[1]); let t = (b - a).normalized().unwrap(); - let x = t.cross(solidcraft_geom::Vec3::Z).normalized().unwrap(); + let x = t.cross(solidcore_record::Vec3::Z).normalized().unwrap(); let y = t.cross(x); run(&mut s, "sketch.create", json!({"plane": {"origin": [a.x, a.y, a.z], "x_dir": [x.x, x.y, x.z], "y_dir": [y.x, y.y, y.z]}})); run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-1, -1], "p1": [1, 1]})); @@ -572,8 +705,8 @@ fn sweeps_and_pipes_follow_3d_sketch_curves() { } /// #47: references to other bodies: an edge, a face's loops and a silhouette of a second body -/// project into a sketch on the first; they follow an edit of that body (a parameter) and -/// are reported lost, not crashed on, when it goes away. +/// project into a sketch on the first; they follow an edit of that body (a parameter), and when +/// it goes away the sketch fails, asking for the named edge again, not crashed on. #[test] fn project_and_include_from_other_bodies() { let mut s = Session::default(); @@ -603,13 +736,17 @@ fn project_and_include_from_other_bodies() { let id = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap().id; let si = run(&mut s, "sketch.inspect", json!({"sketch": id})); assert!(xs(&si).iter().any(|x| (x - 70.0).abs() < 1e-6), "{:?}", xs(&si)); - // Remove the cylinder: its silhouette and edge are lost, with a warning and no error. + // Remove the cylinder: the edge included from it is gone, and the sketch asks for it again. let cyl = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Cylinder { .. })).unwrap().id; run(&mut s, "timeline.delete", json!({"feature": cyl})); let t = run(&mut s, "document.inspect", json!({})); let row = t["timeline"].as_array().unwrap().iter().find(|r| r["id"] == json!(id)).cloned().unwrap(); - assert!(row["error"].is_null(), "{row}"); - assert!(row["warning"].as_str().is_some_and(|w| w.contains("lost")), "{row}"); + let error = row["error"].as_str().unwrap_or_default(); + assert!( + solidcraft_doc::reselect_parts(error) + .is_some_and(|(feature, reference)| feature == row["name"] && reference.starts_with(&format!("F{cyl}:"))), + "{row}" + ); } /// A cylinder's wall and the torus of a rounded rim are drawn as one face but stored in halves @@ -691,7 +828,9 @@ fn a_rectangle_put_onto_a_projected_edge_stays_a_closed_profile() { // Picked by a point inside, it extrudes to a 20 x 15 x 10 block of its own. run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch": id, "profiles": [{"point": [15, 7.5]}], "distance": 10, "operation": "new", "body_name": "Pad"})); - let volume = |s: &Session, name: &str| s.model.state().body(name).unwrap().body.tessellate_with(1e-4, true).unwrap().measure().volume; + let volume = |s: &Session, name: &str| { + s.model.state().body(name).unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume + }; assert!((volume(&s, "Pad") - 3000.0).abs() < 1e-6, "{}", volume(&s, "Pad")); assert!((volume(&s, &block) - 24000.0).abs() < 1e-6, "{}", volume(&s, &block)); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); @@ -735,11 +874,18 @@ fn a_face_engraved_with_text_projects_its_letters_exactly_and_extrudes() { assert!(r.error.is_none(), "{r:?}"); let face = before - volume(&mut s); assert!((face - taken).abs() < 1e-6 * before, "{face} {taken}"); - // Its sketch got the letters as Bézier pieces. + // Its sketch got the letters as their exact pieces: the outline's quadratic Béziers, which are + // parabolic arcs, come in as conics (or as control-point splines). let st = s.model.state(); let sketch = &st.sketches.last().unwrap().sketch; - let pieces = - sketch.curves.iter().filter(|c| c.link.is_some() && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. })).count(); + let pieces = sketch + .curves + .iter() + .filter(|c| { + c.link.is_some() + && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. } | solidcraft_sketch::CurveKind::Conic { .. }) + }) + .count(); assert!(pieces > 100, "{pieces}"); } @@ -757,12 +903,23 @@ fn a_face_sketch_saved_with_fitted_letters_reopens_and_builds_the_same() { let r = s.model.result(id).unwrap(); assert!(r.error.is_none(), "{name}: {:?}", r.error); } - // The build that saved it measured 5916.018831 mm³. - assert!((volume - 5916.018830904924).abs() < 1e-3, "{volume}"); + // The 30 x 20 x 10 block less the "S" 1 deep (its profile's exact area, Sketch2's smaller + // region) and the r 2 circle 3 deep, clear of the letter: 5916.010767. (The build that saved + // it measured 5916.018831, 8e-3 off; SMLib's integral is within 1e-8 of the closed form.) + let letter = s.model.state().sketches.iter().find(|k| k.name == "Sketch2").unwrap().profiles.iter().map(|p| p.area).fold(f64::INFINITY, f64::min); + let want = 6000.0 - letter - 3.0 * std::f64::consts::PI * 4.0; + assert!((volume - want).abs() < 1e-8 * 6000.0, "{volume} vs {want}"); + // The letter's exact pieces in the face's link: its quadratic Béziers, as conics (or splines). let st = s.model.state(); let sketch = &st.sketches.last().unwrap().sketch; - let pieces = - sketch.curves.iter().filter(|c| c.link.is_some() && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. })).count(); + let pieces = sketch + .curves + .iter() + .filter(|c| { + c.link.is_some() + && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. } | solidcraft_sketch::CurveKind::Conic { .. }) + }) + .count(); assert!(pieces > 0, "{pieces}"); } @@ -814,9 +971,13 @@ fn projecting_what_the_face_sketch_already_shows_adds_no_second_copy() { let border = shown(&mut s); assert_eq!(border.0, 8, "four sides and four rounded corners"); let corner = 5.0 - 5.0 * std::f64::consts::FRAC_1_SQRT_2; - for refs in [json!([{"face":[20,15,10]}]), json!([{"edge":[20,0,10]}]), json!([{"edge":[corner,corner,10]}])] { + // These references name no body, so the refusal names the kind alone: it must not end in + // "face of " with nothing after the "of" (#4929). + let cases = [(json!([{"face":[20,15,10]}]), "face"), (json!([{"edge":[20,0,10]}]), "edge"), (json!([{"edge":[corner,corner,10]}]), "edge")]; + for (refs, what) in cases { let e = s.execute("sketch.project", &json!({"refs": refs})).unwrap_err().to_string(); assert!(e.contains("already projected"), "{refs}: {e}"); + assert!(e.ends_with(&format!("already projected into this sketch: {what}")), "{refs}: {e}"); assert_eq!(shown(&mut s), border, "{refs}"); } // Something new still projects, and alongside it a reference already shown is skipped. @@ -839,6 +1000,21 @@ fn intersect_curves(steps: &[(&str, Value)], plane: Value) -> std::result::Resul Ok(linked_curves(&inspect(&mut s))) } +/// The lines among `curves` as an outline: each line's ends rounded and the lower first, the lines +/// sorted. A section's chains are walked from either end (the mesh's triangle order picks which), +/// so a line's direction says nothing about the cut. +fn outline(curves: &[Value]) -> Vec<[f64; 4]> { + let mut ends: Vec<[f64; 4]> = line_ends(curves) + .into_iter() + .map(|e| { + let e = e.map(f64::round); + if [e[2], e[3]] < [e[0], e[1]] { [e[2], e[3], e[0], e[1]] } else { e } + }) + .collect(); + ends.sort_by(|a, b| a.partial_cmp(b).unwrap()); + ends +} + fn line_ends(curves: &[Value]) -> Vec<[f64; 4]> { let at = |c: &Value, k: &str, i: usize| c[k][i].as_f64().unwrap_or(f64::NAN); curves @@ -854,10 +1030,8 @@ fn line_ends(curves: &[Value]) -> Vec<[f64; 4]> { fn intersect_keeps_its_exact_cuts() { let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))]; for offset in [10, 0] { - let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": offset})).unwrap()); - ends.iter_mut().for_each(|e| *e = e.map(|v| v.round())); - ends.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]], "offset {offset}"); + let ends = outline(&intersect_curves(&block, json!({"plane": "XY", "offset": offset})).unwrap()); + assert_eq!(ends, vec![[0.0, 0.0, 0.0, 30.0], [0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 40.0, 30.0], [40.0, 0.0, 40.0, 30.0]], "offset {offset}"); } for (steps, plane, radius) in [ (vec![("solid.cylinder", json!({"base": [0, 0, 0], "radius": 7, "height": 30}))], json!({"plane": "XY", "offset": 12}), 7.0), @@ -866,11 +1040,25 @@ fn intersect_keeps_its_exact_cuts() { let c = intersect_curves(&steps, plane).unwrap(); assert!(c.len() == 1 && c[0]["type"] == "circle" && (c[0]["radius"].as_f64().unwrap() - radius).abs() < 1e-4, "{c:?}"); } + // The tilted cylinder's cut is an ellipse the section leaves as the mesh's segments, as many + // as the tessellation crosses (21 on truck's mesh, 20 on SMLib's): each end on the cylinder + // within the section's own reach of the surface, the display tolerance (a thousandth of the + // mesh's size, doc::project::fit_segments), which the old pin of one end to 1e-4 assumed of + // one mesh. let tilted = [("solid.cylinder", json!({"base": [0, 0, 0], "radius": 5, "height": 40, "axis": [1, 0, 1]}))]; - let ends = line_ends(&intersect_curves(&tilted, json!({"plane": "XY", "offset": 10})).unwrap()); - assert_eq!(ends.len(), 21); - let first = [2.941, -0.2891, 3.3932, -1.7819]; - assert!(ends[0].iter().zip(first).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", ends[0]); + let curves = intersect_curves(&tilted, json!({"plane": "XY", "offset": 10})).unwrap(); + let ends = line_ends(&curves); + assert!(ends.len() == curves.len() && ends.len() >= 16, "{curves:?}"); + let axis = solidcore_record::Vec3::new(1.0, 0.0, 1.0).normalized().unwrap(); + // The cylinder's box: its axis 40 along (1, 0, 1)/√2 and its ends' discs of radius 5 span + // (40 + 2·5)/√2 in x and z and 10 in y. + let span = 50.0 * std::f64::consts::FRAC_1_SQRT_2; + let reach = 1e-3 * (2.0 * span * span + 100.0).sqrt(); + for e in &ends { + for p in [solidcore_record::Vec3::new(e[0], e[1], 10.0), solidcore_record::Vec3::new(e[2], e[3], 10.0)] { + assert!(((p - axis * p.dot(axis)).len() - 5.0).abs() < reach, "{p:?}"); + } + } } /// A plane crossing a curved face's rim cuts it on the surface, not on the mesh's chord: a @@ -897,10 +1085,43 @@ fn intersect_crosses_a_curved_face_on_the_surface() { #[test] fn intersect_on_a_top_face_gives_its_outline() { let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))]; - let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": 20})).unwrap()); - ends.iter_mut().for_each(|e| *e = e.map(|v| v.round())); - ends.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]]); + let ends = outline(&intersect_curves(&block, json!({"plane": "XY", "offset": 20})).unwrap()); + assert_eq!(ends, vec![[0.0, 0.0, 0.0, 30.0], [0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 40.0, 30.0], [40.0, 0.0, 40.0, 30.0]]); +} + +/// A free-form edge projects as the one exact spline it is, its knots and weights its own: the +/// bottom face of a 40 x 20 x 10 box whose upright edges have G2 rounds (each round's bottom +/// edge a B-spline of several spans) comes into its sketch as four lines and four splines, one a +/// corner, each meeting the lines at their ends (#3604, where each span was a curve of its own). +/// The profile they bound, extruded the box's height, is the box: its sides are upright. +#[test] +fn a_free_form_edge_projects_as_one_spline_with_its_own_knots() { + use solidcraft_sketch::CurveKind; + let volume = |s: &Session, body: &str| solidcraft_kernel::measure(&s.world_state().unwrap().body(body).unwrap().body).unwrap().volume; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"corner":[0,0,0],"length":40,"width":20,"height":10,"body_name":"B"})); + run(&mut s, "solid.fillet", json!({"body":"B","edges":[[0,0,5],[40,0,5],[40,20,5],[0,20,5]],"radius":5,"type":"g2"})); + let id = run(&mut s, "sketch.create", json!({"plane":{"face":[20,10,0]},"project_edges":true,"name":"Bottom"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.finish", json!({})); + let st = s.model.state(); + let sketch = &st.sketch(id).unwrap().sketch; + let lines = sketch.curves.iter().filter(|c| matches!(c.kind, CurveKind::Line { .. })).count(); + let splines: Vec<_> = sketch.curves.iter().filter(|c| matches!(c.kind, CurveKind::Spline { .. })).collect(); + assert_eq!((lines, splines.len(), sketch.curves.len()), (4, 4, 8), "{:?}", sketch.curves); + for c in &splines { + let CurveKind::Spline { pts, control: true, nurbs: Some(nurbs), .. } = &c.kind else { panic!("{:?}", c.kind) }; + assert_eq!(nurbs.knots.len(), pts.len() + 4, "a cubic's knots"); + let (a, b) = c.kind.ends().unwrap(); + for end in [a, b] { + let meets = sketch.curves.iter().filter(|o| matches!(o.kind, CurveKind::Line { a, b } if a == end || b == end)).count(); + assert_eq!(meets, 1, "{} end {end}", c.id); + } + } + drop(st); + let rounded = volume(&s, "B"); + run(&mut s, "solid.extrude", json!({"sketch":"Bottom","distance":10,"operation":"new","body_name":"P"})); + let prism = volume(&s, "P"); + assert!((prism - rounded).abs() < rounded * 1e-6, "{prism} vs {rounded}"); } #[test] @@ -981,7 +1202,7 @@ fn whole_body_project_stays_on_the_body_outline_after_a_late_chamfer() { } for i in 0..=16 { let t = t0 + sweep * f64::from(i) / 16.0; - let q = solidcraft_geom::Vec2::new(c.x + r * t.cos(), c.y + r * t.sin()); + let q = solidcore_record::Vec2::new(c.x + r * t.cos(), c.y + r * t.sin()); worst = worst.max((x0 - q.x).max(q.x - x1).max(y0 - q.y).max(q.y - y1)); } assert!(sweep < std::f64::consts::PI + 0.01, "{plane} {chamfer:?}: arc sweeps {sweep} rad, not a rounded corner"); @@ -1039,6 +1260,106 @@ fn whole_body_project_of_a_filleted_plate_keeps_exact_lines_and_arcs() { } } +/// A U-slot cut into a plate's edge with its top rim rounded: the round meets the top face on a +/// circle of radius 6.5 + 1 about the slot's axis, but the kernel makes that edge a spline that +/// only follows the circle (within 2e-6 mm), and it projected as twenty spline pieces. The +/// edge is a circle (the selection readout says so): it projects as an arc of that circle. +#[test] +fn a_rounded_slot_rim_projects_as_an_arc_of_its_circle() { + use solidcraft_sketch::CurveKind; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"})); + run(&mut s, "solid.cylinder", json!({"radius": 6.5, "height": 20, "base": [20, 2, -5], "operation": "cut", "targets": ["Plate"]})); + run(&mut s, "solid.fillet", json!({"edges": [[20, 8.5, 10]], "radius": 1})); + let edge = run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 30, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Plate", "edge": [20, 9.5, 10]}]})); + run(&mut s, "sketch.finish", json!({})); + let face = run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 30, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Plate", "face": [5, 25, 10]}]})); + run(&mut s, "sketch.finish", json!({})); + + let state = s.model.state(); + let center = solidcore_record::Vec2::new(20., 2.); + for id in [edge, face] { + let sk = &state.sketch(id).unwrap().sketch; + let pos = |i: usize| sk.points[i].pos; + let mut arcs = 0; + for curve in &sk.curves { + match curve.kind { + CurveKind::Line { .. } => {} + CurveKind::Arc { c, a, b } => { + arcs += 1; + assert!(pos(c).dist(center) < 1e-5, "arc centre {:?}", pos(c)); + for end in [a, b] { + assert!((pos(end).dist(pos(c)) - 7.5).abs() < 1e-5, "arc end {:?} off the circle", pos(end)); + } + } + ref other => panic!("sketch {id}: the rim projects as {other:?}, not as lines and arcs"), + } + } + assert!(arcs >= 1, "sketch {id}: no arc in {:?}", sk.curves); + } + // The face's outline still closes: the plate's top less the slot's disc of radius 7.5 (its + // part above the front face, whose chord lies 2 below the centre). + let (r, d) = (7.5f64, 2f64); + let below = r * r * (d / r).acos() - d * (r * r - d * d).sqrt(); + let area = 40. * 30. - (std::f64::consts::PI * r * r - below); + let profiles = &state.sketch(face).unwrap().profiles; + assert!(profiles.iter().any(|p| (p.area - area).abs() < 1e-3), "{:?} vs {area}", profiles.iter().map(|p| p.area).collect::>()); +} + +/// A hook: a J of lines and two arcs about (-15, 0), of radii 7.5 and 15, extruded 20 with its +/// top edges chamfered. Seen along the extrusion its outline is the J again. The walls are seen +/// edge-on, but the triangles of a round wall join its two rims at slightly different angles +/// and each leans a hair towards the sketch or away: the outline ran zig-zag along the walls +/// and came in as 74 short lines. Faces that lie edge-on are edge-on in every triangle. +#[test] +fn whole_body_project_of_a_chamfered_hook_keeps_its_arcs() { + use solidcraft_sketch::CurveKind; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 60], [0, 0]]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [-15, 0], "start": [-30, 0], "end": [0, 0]})); + run(&mut s, "sketch.line", json!({"points": [[-30, 0], [-30, 10], [-22.5, 10], [-22.5, 0]]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [-15, 0], "start": [-22.5, 0], "end": [-7.5, 0]})); + run(&mut s, "sketch.line", json!({"points": [[-7.5, 0], [-7.5, 60], [0, 60]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 20, "body_name": "Hook"})); + run(&mut s, "solid.chamfer", json!({"edges": [[-15, -15, 20], [-15, -7.5, 20], [0, 30, 20], [-7.5, 30, 20]], "distance": 0.25})); + let sketch = run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 40, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Hook"}]})); + run(&mut s, "sketch.finish", json!({})); + + let state = s.model.state(); + let solved = state.sketch(sketch).unwrap(); + let sk = &solved.sketch; + let pos = |i: usize| sk.points[i].pos; + let mut radii = Vec::new(); + for curve in &sk.curves { + match curve.kind { + CurveKind::Line { .. } => {} + CurveKind::Arc { c, a, b } => { + assert!(pos(c).dist(solidcore_record::Vec2::new(-15., 0.)) < 1e-3, "arc centre {:?}", pos(c)); + assert!((pos(a).dist(pos(c)) - pos(b).dist(pos(c))).abs() < 1e-6); + radii.push(pos(a).dist(pos(c))); + } + ref other => panic!("the outline projects as {other:?}, not as lines and arcs"), + } + } + radii.sort_by(f64::total_cmp); + assert_eq!(radii.len(), 2, "{} curves, arcs of radii {radii:?}", sk.curves.len()); + assert!((radii[0] - 7.5).abs() < 1e-3 && (radii[1] - 15.).abs() < 1e-3, "{radii:?}"); + assert_eq!(sk.curves.len(), 8, "{:?}", sk.curves); + // One closed profile: the J's area, a rectangle 7.5 x 60 and a half ring 7.5 to 15 with its + // 7.5 x 10 tip. + let area = 7.5 * 60. + std::f64::consts::PI * (15. * 15. - 7.5 * 7.5) / 2. + 7.5 * 10.; + assert!( + solved.profiles.iter().any(|p| (p.area - area).abs() < 0.05), + "{:?} vs {area}", + solved.profiles.iter().map(|p| p.area).collect::>() + ); +} + #[test] fn whole_body_intersect_of_a_filleted_plate_keeps_exact_lines_and_arcs() { use solidcraft_sketch::CurveKind; @@ -1098,3 +1419,117 @@ fn a_rebuilt_projection_keeps_user_constraints_without_a_warning() { assert!(warning.is_none(), "{warning:?}"); } } + +/// #9001: an angle (an L profile, wall thickness `d1`, legs `d2`) with a sketch on its face and +/// a hole dimensioned to the inner wall's projected edge. Making the wall thicker moves the +/// inner corner by more than a tenth of the face; the projection follows it (it was kept as it +/// was, "boundary identity is ambiguous"), and the hole with it, as it already did for `d2`. +#[test] +fn a_thicker_angle_moves_the_projected_face_of_the_sketch_on_it() { + let mut s = Session::default(); + run(&mut s, "parameters.change", json!({"name": "d1", "expression": "20 mm"})); + run(&mut s, "parameters.change", json!({"name": "d2", "expression": "80 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let l = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [80, 0], [80, 20], [20, 20], [20, 80], [0, 80]], "closed": true}))["curves"]); + for (i, line) in l.iter().enumerate() { + let mode = if i % 2 == 0 { "horizontal" } else { "vertical" }; + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": line, "mode": mode})); + } + run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.start", l[0]), "b": "origin"})); + for (k, value) in [(0, "d2"), (1, "d1"), (4, "d1"), (5, "d2")] { + run(&mut s, "sketch.dimension", json!({"entities": [l[k]], "value": value})); + } + assert_eq!(inspect(&mut s)["dof"], 0); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 30})); + let sketch = run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 30]}}))["sketch"].as_u64().unwrap(); + let si = inspect(&mut s); + // The inner wall's edge, from (20, 20) to (20, 80) on the face. + let wall = linked_curves(&si) + .into_iter() + .find(|c| { + ["start_at", "end_at"].iter().all(|e| (c[e][0].as_f64().unwrap().abs() - 20.).abs() < 1e-6 && c[e][1].as_f64().unwrap().abs() > 19.) + }) + .unwrap_or_else(|| panic!("{si}")); + let hole = ids(&run(&mut s, "sketch.circle.center", json!({"center": [10, 50], "radius": 3}))["curves"])[0].clone(); + run(&mut s, "sketch.dimension", json!({"entities": [format!("{hole}.center"), wall["id"]], "value": 10})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "parameters.change", json!({"name": "d1", "expression": "30 mm"})); + let check = |s: &Session| { + let warning = s.model.result(sketch).and_then(|r| r.warning.clone()); + assert!(warning.is_none(), "{warning:?}"); + let st = s.model.state(); + let ss = st.sketch(sketch).unwrap(); + assert!(ss.sketch.links.iter().all(|l| !l.lost)); + let world = |p: solidcore_record::Vec2| ss.plane.to_world(p); + let at = |x: f64, y: f64| ss.sketch.points.iter().any(|p| world(p.pos).dist(solidcore_record::Vec3::new(x, y, 30.)) < 1e-6); + // The inner corner is at (30, 30) now, and the hole 10 from the wall that moved. + assert!(at(30., 30.) && !at(20., 20.)); + let center = ss.sketch.points.iter().find(|p| p.id == format!("{hole}.center")).unwrap(); + assert!((world(center.pos).x - 20.).abs() < 1e-6, "{:?}", world(center.pos)); + assert_eq!(ss.sketch.constraints.len(), 1); + }; + check(&s); + check(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap())); +} + +/// A sphere's outline from above is its equator: one circle and one profile. Flat triangles beside +/// the equator can tip the other way from the sphere, and their edges must not join the outline. +#[test] +fn a_spheres_silhouette_is_one_circle() { + let mut s = Session::default(); + run(&mut s, "solid.sphere", json!({"radius": 8, "body_name": "Ball"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": -10, "name": "Below"})); + let r = run(&mut s, "sketch.project", json!({"refs": [{"body": "Ball"}]})); + let curves = r["links"][0]["curves"].as_array().unwrap(); + assert_eq!(curves.len(), 1, "{r}"); + let inspected = run(&mut s, "sketch.inspect", json!({})); + let circle = inspected["curves"].as_array().unwrap().iter().find(|c| c["id"] == curves[0]).unwrap(); + assert_eq!(circle["type"], "circle", "{circle}"); + assert!((circle["radius"].as_f64().unwrap() - 8.0).abs() < 1e-6, "{circle}"); + let done = run(&mut s, "sketch.finish", json!({})); + assert_eq!(done["profiles"], 1, "{done}"); +} + +/// The silhouette of a square with a conic round at each corner (rho 0.19, 0.4, 0.5 and 0.7) is +/// one closed outline of the square's true area. Fitted arcs along a conic were snapped onto lines +/// that ended further along the outline, which left gaps of up to 3.6 mm: no profile. +#[test] +fn the_silhouette_of_conic_rounds_closes() { + let mut s = Session::default(); + let corners = [ + ([-75., 65.], [-75., 75.], [-65., 75.], 0.19), + ([65., 75.], [75., 75.], [75., 65.], 0.4), + ([75., -65.], [75., -75.], [65., -75.], 0.5), + ([-65., -75.], [-75., -75.], [-75., -65.], 0.7), + ]; + run(&mut s, "sketch.create", json!({"plane": "XZ"})); + for (i, (start, apex, end, rho)) in corners.iter().enumerate() { + run(&mut s, "sketch.conic", json!({"start": start, "apex": apex, "end": end, "rho": rho})); + let next = corners[(i + 1) % 4].0; + run(&mut s, "sketch.line", json!({"points": [end, next]})); + } + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 55, "body_name": "Part"})); + run(&mut s, "sketch.create", json!({"plane": "XZ", "offset": -10})); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Part"}]})); + // The true area: the outline through the four rational quadratic Béziers (apex weight + // rho / (1 - rho)), finely sampled, and the straight sides between them. + let mut outline: Vec<[f64; 2]> = Vec::new(); + for (start, apex, end, rho) in corners { + let w = rho / (1. - rho); + for k in 0..=2000 { + let t = f64::from(k) / 2000.; + let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t); + let sum = b0 + b1 + b2; + outline.push([(b0 * start[0] + b1 * apex[0] + b2 * end[0]) / sum, (b0 * start[1] + b1 * apex[1] + b2 * end[1]) / sum]); + } + } + let n = outline.len(); + let exact = (0..n).map(|i| outline[i][0] * outline[(i + 1) % n][1] - outline[(i + 1) % n][0] * outline[i][1]).sum::().abs() / 2.; + let si = inspect(&mut s); + let profiles = si["profiles"].as_array().unwrap(); + assert_eq!(profiles.len(), 1, "{}", si["profiles"]); + let area = profiles[0]["area_mm2"].as_f64().unwrap(); + assert!((area - exact).abs() < exact * 2e-4, "area {area}, exact {exact}"); +} diff --git a/crates/engine/src/cmd/sketch_rect_tests.rs b/crates/engine/src/cmd/sketch_rect_tests.rs index 82bb7b289..ec26a4fa0 100644 --- a/crates/engine/src/cmd/sketch_rect_tests.rs +++ b/crates/engine/src/cmd/sketch_rect_tests.rs @@ -2,6 +2,7 @@ //! over-constrained (dragging, dimensioning, pinning the centre, making them square). use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_redundant_tests.rs b/crates/engine/src/cmd/sketch_redundant_tests.rs index 78bcd7565..d14cb5820 100644 --- a/crates/engine/src/cmd/sketch_redundant_tests.rs +++ b/crates/engine/src/cmd/sketch_redundant_tests.rs @@ -4,7 +4,8 @@ //! with the sketch are refused. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_robust_tests.rs b/crates/engine/src/cmd/sketch_robust_tests.rs index 65559d89b..00d8cade7 100644 --- a/crates/engine/src/cmd/sketch_robust_tests.rs +++ b/crates/engine/src/cmd/sketch_robust_tests.rs @@ -3,6 +3,7 @@ //! degenerate is left behind). use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_rounded_rect_tests.rs b/crates/engine/src/cmd/sketch_rounded_rect_tests.rs index 023a6c136..9fa88f4ac 100644 --- a/crates/engine/src/cmd/sketch_rounded_rect_tests.rs +++ b/crates/engine/src/cmd/sketch_rounded_rect_tests.rs @@ -1,6 +1,7 @@ //! Rounded Rectangle (#891): a 2-point rectangle whose corners are filleted alike, in one step. use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::ConstraintKind; use crate::Session; @@ -146,3 +147,27 @@ fn typed_width_and_height_measure_the_whole_rounded_rectangle() { assert!((area - want).abs() < 1e-6, "area {area}, want {want}: {si}"); assert_eq!(si["dof"], 2, "only the position is free: {si}"); } + +/// The corners take expressions over the design's parameters, as a 2-point rectangle's do: the +/// rounded rectangle follows them, and the radius is checked against the sides they work out to. +#[test] +fn corners_typed_as_expressions_follow_their_parameters() { + let mut s = sketch(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "parameters.add", json!({"name": "H", "expression": "20 mm"})); + let r = run(&mut s, "sketch.rectangle.rounded", json!({"p0": ["-W / 2", "-H / 2"], "p1": ["W / 2", "H / 2"], "radius": 3})); + assert_eq!(ids(&r["arcs"]).len(), 4, "{r}"); + let area = |s: &mut Session| { + let si = run(s, "sketch.inspect", json!({})); + si["profiles"][0]["area_mm2"].as_f64().unwrap_or(f64::NAN) + }; + let corners = (4.0 - std::f64::consts::PI) * 9.0; + let a = area(&mut s); + assert!((a - (40.0 * 20.0 - corners)).abs() < 1e-6, "area {a}"); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "70 mm"})); + let a = area(&mut s); + assert!((a - (70.0 * 20.0 - corners)).abs() < 1e-6, "area after W = 70 mm: {a}"); + // A radius the worked-out sides cannot take is refused, as for numbers. + let too_big = s.execute("sketch.rectangle.rounded", &json!({"p0": [0, 0], "p1": ["W", "H / 4"], "radius": 3})); + assert!(too_big.is_err(), "radius 3 mm on a 5 mm side: {too_big:?}"); +} diff --git a/crates/engine/src/cmd/sketch_support.rs b/crates/engine/src/cmd/sketch_support.rs index 926f57777..636ec3706 100644 --- a/crates/engine/src/cmd/sketch_support.rs +++ b/crates/engine/src/cmd/sketch_support.rs @@ -1,6 +1,7 @@ //! Bounded roots on exact curve pieces against an infinite line or complete circle. //! Rational pieces are intersected in homogeneous coordinates, without sampled chords. -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{Shape, intersections}; use crate::{Result, params::bad}; @@ -205,7 +206,7 @@ mod tests { elevated.push(y[n - 1]); y = elevated; } - let mut points = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL]; + let mut points = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; for (i, p) in points.iter_mut().take(8).enumerate() { *p = Vec2::new(10.0 + i as f64 * 20.0 / 7.0, y[i]); } diff --git a/crates/engine/src/cmd/sketch_symmetry_point_tests.rs b/crates/engine/src/cmd/sketch_symmetry_point_tests.rs index 05077e113..71c138467 100644 --- a/crates/engine/src/cmd/sketch_symmetry_point_tests.rs +++ b/crates/engine/src/cmd/sketch_symmetry_point_tests.rs @@ -2,7 +2,8 @@ //! or given as `point`. Each pair is joined by a construction line the point is the midpoint of. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, Sketch}; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_text_expr_tests.rs b/crates/engine/src/cmd/sketch_text_expr_tests.rs index 5a8749d65..9250bc4b1 100644 --- a/crates/engine/src/cmd/sketch_text_expr_tests.rs +++ b/crates/engine/src/cmd/sketch_text_expr_tests.rs @@ -2,7 +2,8 @@ //! text keeps the expression, follows the parameters, and a number typed instead replaces it. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::LinkSource; use crate::Session; @@ -389,11 +390,55 @@ fn a_texts_words_follow_its_text_parameters_and_so_does_its_cut() { run(&mut s, "sketch.finish", json!({})); assert_eq!((words(&s, &link).as_str(), word_expr(&s, &link)), ("OK", Value::Null)); - // An expression naming no text parameter, or a number parameter, is refused. - run(&mut s, "parameters.add", json!({"name": "W", "expression": "10 mm"})); + // An expression naming an unknown parameter, or a text parameter in number(), is refused. run(&mut s, "sketch.edit", json!({"sketch": "S"})); - for (bad, says) in [("Nope + 'x'", "Nope"), ("W", "W"), ("Tag +", "")] { + for (bad, says) in [("Nope + 'x'", "Nope"), ("number(Tag)", "Tag"), ("Tag +", "")] { let e = s.execute("sketch.edit_text", &json!({"link": link, "text_expression": bad})).unwrap_err().to_string(); assert!(e.contains(says), "{bad}: {e}"); } } + +/// #9281: a number parameter in a text's words shows its value in the design's units +/// (`number()` without the unit, with chosen decimals); a parameter edit rewrites the words +/// and the cut follows in the same rebuild, also after a save; a rename reaches the words and +/// deleting the parameter is refused while the text shows it. +#[test] +fn a_texts_words_show_a_number_parameter_and_follow_it() { + let typed = |words: &str| { + let mut s = Session::default(); + block_with_text(&mut s, json!({"text": words})); + no_trouble(&s); + volume(&mut s) + }; + let same = |a: f64, b: f64, what: &str| assert!((a - b).abs() < 1e-6, "{what}: {a} against {b} typed"); + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "Width", "expression": "85 mm"})); + run(&mut s, "parameters.add", json!({"name": "Tilt", "expression": "30 deg"})); + let r = block_with_text(&mut s, json!({"text_expression": "'W' + number(Width)"})); + let link = r["link"].as_str().unwrap().to_string(); + no_trouble(&s); + assert_eq!(words(&s, &link), "W85"); + same(volume(&mut s), typed("W85"), "W85"); + + run(&mut s, "parameters.change", json!({"name": "Width", "expression": "90 mm"})); + no_trouble(&s); + assert_eq!(words(&s, &link), "W90"); + let wide = typed("W90"); + same(volume(&mut s), wide, "W90"); + let mut again = reopened(&s); + no_trouble(&again); + same(volume(&mut again), wide, "W90 reopened"); + + run(&mut s, "sketch.edit", json!({"sketch": "S"})); + run(&mut s, "sketch.edit_text", json!({"link": link, "text_expression": "number(Width, 1) + ' / ' + Tilt"})); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); + assert_eq!(words(&s, &link), "90.0 / 30°"); + + run(&mut s, "parameters.rename", json!({"name": "Width", "new_name": "Span"})); + assert_eq!(word_expr(&s, &link), json!("number(Span, 1) + ' / ' + Tilt")); + let e = s.execute("parameters.delete", &json!({"name": "Span"})).unwrap_err().to_string(); + assert!(e.contains("Text"), "{e}"); + no_trouble(&s); + assert_eq!(words(&s, &link), "90.0 / 30°"); +} diff --git a/crates/engine/src/cmd/sketch_text_move_tests.rs b/crates/engine/src/cmd/sketch_text_move_tests.rs index 188cb73fa..000bdd891 100644 --- a/crates/engine/src/cmd/sketch_text_move_tests.rs +++ b/crates/engine/src/cmd/sketch_text_move_tests.rs @@ -87,7 +87,7 @@ fn live_text_resize_follows_each_frame_and_rebuilds_downstream_on_release() { assert!((*angle + 10_f64.to_radians()).abs() < 1e-12); // Same letters, same outlines: what references them keeps working. assert_eq!(sk.link_curves(&link).len(), curves); - let shown = s.world_state(); + let shown = s.world_state().unwrap(); assert!(shown.sketch(1).unwrap().profiles.len() >= 2, "the sketch shown follows the frame"); } run(&mut s, "sketch.drag_end", json!({})); @@ -122,13 +122,13 @@ fn text_move_in_a_rotated_component_preserves_font_and_local_coordinates() { let sid = created["sketch"].as_u64().unwrap(); let result = run(&mut s, "sketch.text", json!({"text":"I","at":[0,0],"height":10,"font":solidcraft_sketch::DEFAULT_FONT_FAMILY})); let link = result["link"].as_str().unwrap(); - let before = s.world_state().sketch(sid).unwrap().plane; + let before = s.world_state().unwrap().sketch(sid).unwrap().plane; run(&mut s, "sketch.move", json!({"entities":[result["curves"][0]],"translate":[5,2]})); let sk = s.doc.sketch(sid).unwrap(); let LinkSource::Text { at, font, .. } = &sk.link(link).unwrap().source else { panic!() }; assert!(at.dist(Vec2::new(5.0, 2.0)) < 1e-9); assert_eq!(font.as_deref(), Some(solidcraft_sketch::DEFAULT_FONT_FAMILY)); - let state = s.world_state(); + let state = s.world_state().unwrap(); assert!(state.sketch(sid).unwrap().plane.to_world(*at).dist(before.to_world(Vec2::new(5.0, 2.0))) < 1e-9); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert_eq!(reopened.doc.sketch(sid).unwrap().link(link).unwrap().source, sk.link(link).unwrap().source); @@ -153,7 +153,7 @@ fn text_move_rejects_malformed_values_without_changing_history() { /// The box around the solved outlines of text `link` in sketch 1: (min, max). fn text_box(s: &Session, link: &str) -> (Vec2, Vec2) { - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; let pts: Vec = sk.link_curves(link).into_iter().flat_map(|ci| sk.polyline(ci)).collect(); let lo = pts.iter().fold(Vec2::new(f64::MAX, f64::MAX), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y))); @@ -384,7 +384,7 @@ fn a_text_on_a_spline_turns_its_path_into_a_guide() { let t = run(&mut s, "sketch.text", json!({"text":"Phago","at":[0,0],"height":10,"path":spline})); assert_eq!(t["guide"], json!(spline)); assert!(construction(&s)); - let state = s.world_state(); + let state = s.world_state().unwrap(); let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); for (i, p) in ss.profiles.iter().enumerate() { let alone = p.curve_ids().iter().all(|id| ss.sketch.curves.iter().any(|c| &c.id == id && c.link.is_some())); diff --git a/crates/engine/src/cmd/sketch_trim_path_tests.rs b/crates/engine/src/cmd/sketch_trim_path_tests.rs index 91e8b94bd..49842c13f 100644 --- a/crates/engine/src/cmd/sketch_trim_path_tests.rs +++ b/crates/engine/src/cmd/sketch_trim_path_tests.rs @@ -2,7 +2,8 @@ //! with `sketch.trim` would, in one undo step. use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::Shape; use crate::Session; diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs index 691dd6a37..ae40e4477 100644 --- a/crates/engine/src/cmd/sketch_ux_tests.rs +++ b/crates/engine/src/cmd/sketch_ux_tests.rs @@ -2,6 +2,7 @@ //! which entity moves when a two-entity constraint is applied. use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{DimFrame, Sketch, dim_frame, dim_layout}; use crate::Session; @@ -53,7 +54,7 @@ fn every_dimension_kind_has_a_drawable_frame() { let mut kinds = Vec::new(); for c in dims { let f = dim_frame(&sk, &c.kind).unwrap_or_else(|| panic!("no frame for {c:?}")); - let l = dim_layout(&f, None, 0.1, solidcraft_geom::Vec2::new(1.0, 0.5)); + let l = dim_layout(&f, None, 0.1, solidcore_record::Vec2::new(1.0, 0.5)); assert!(!l.lines.is_empty() && !l.arrows.is_empty(), "{c:?}"); assert!(l.text.is_finite()); kinds.push(std::mem::discriminant(&f)); @@ -80,10 +81,10 @@ fn dimension_text_is_stored_relative_to_the_dimension_and_follows_it() { let f = dim_frame(&sk, &c.kind).expect("frame"); dim_layout(&f, c.text, 0.1, Default::default()).text }; - assert!(text(&s).dist(solidcraft_geom::Vec2::new(20.0, -8.0)) < 1e-9); + assert!(text(&s).dist(solidcore_record::Vec2::new(20.0, -8.0)) < 1e-9); // Moved by the parameter name; then the line moves and the text goes with it. run(&mut s, "sketch.dimension_text", json!({"dimension": param, "at": [30, 12]})); - assert!(text(&s).dist(solidcraft_geom::Vec2::new(30.0, 12.0)) < 1e-9); + assert!(text(&s).dist(solidcore_record::Vec2::new(30.0, 12.0)) < 1e-9); run(&mut s, "sketch.move_point", json!({"point": "l1.start", "to": [0, 10]})); run(&mut s, "sketch.move_point", json!({"point": "l1.end", "to": [40, 10]})); // Still 10 along and 12 across from the middle of the (moved) line. @@ -114,7 +115,7 @@ fn deleting_a_dimension_frees_its_parameter() { // --------------------------------------------------------------------------------------------- // Fix / Unfix -fn pt(s: &Session, id: &str) -> solidcraft_geom::Vec2 { +fn pt(s: &Session, id: &str) -> solidcore_record::Vec2 { let sk = sketch(s); sk.resolve_point(id).and_then(|i| sk.point(i)).unwrap_or_else(|| panic!("no point {id}")) } @@ -163,7 +164,7 @@ fn fixing_curves_holds_their_points_and_radius() { assert!(si["curves"].as_array().is_some_and(|c| c.iter().all(|c| c["fixed"] == true)), "{si}"); // A fixed circle keeps centre and radius; a dimension on it conflicts. run(&mut s, "sketch.move_point", json!({"point": "c1.center", "to": [0, 0]})); - assert_eq!(pt(&s, "c1.center"), solidcraft_geom::Vec2::new(10.0, 10.0)); + assert_eq!(pt(&s, "c1.center"), solidcore_record::Vec2::new(10.0, 10.0)); assert!(s.execute("sketch.dimension", &json!({"entities": ["c1"], "value": 20})).is_err()); let r0 = sketch(&s).radius(0); assert_eq!(r0, Some(5.0)); @@ -296,7 +297,7 @@ fn projected_geometry_can_become_construction() { // Two-entity constraints: the first pick stays, the second moves /// Positions of an entity's points (and its radius). -fn snap(s: &Session, id: &str) -> (Vec, Option) { +fn snap(s: &Session, id: &str) -> (Vec, Option) { let sk = sketch(s); if let Some(i) = sk.curve_index(id) { let pts = sk.curves[i].kind.point_ids().into_iter().filter_map(|p| sk.point(p)).collect(); @@ -305,7 +306,7 @@ fn snap(s: &Session, id: &str) -> (Vec, Option) { (vec![pt(s, id)], None) } -fn same(a: &(Vec, Option), b: &(Vec, Option)) -> bool { +fn same(a: &(Vec, Option), b: &(Vec, Option)) -> bool { a.0.len() == b.0.len() && a.0.iter().zip(&b.0).all(|(p, q)| p.dist(*q) < 1e-9) && a.1.zip(b.1).is_none_or(|(x, y)| (x - y).abs() < 1e-9) } @@ -437,7 +438,7 @@ fn point_constraints_keep_the_first_pick() { let (a0, l0) = (snap(&s, "p1"), snap(&s, "l1")); run(&mut s, "sketch.constraint.symmetry", json!({"a": "p1", "b": "p2", "line": "l1"})); assert!(same(&snap(&s, "p1"), &a0) && same(&snap(&s, "l1"), &l0)); - assert!(pt(&s, "p2").dist(solidcraft_geom::Vec2::new(3.0, -7.0)) < 1e-6, "{:?}", pt(&s, "p2")); + assert!(pt(&s, "p2").dist(solidcore_record::Vec2::new(3.0, -7.0)) < 1e-6, "{:?}", pt(&s, "p2")); } #[test] @@ -570,12 +571,12 @@ fn drag(s: &mut Session, e: &str, from: [f64; 2], to: [f64; 2]) { run(s, "sketch.drag", json!({"entity": e, "from": from, "to": to})); } -fn v(x: f64, y: f64) -> solidcraft_geom::Vec2 { - solidcraft_geom::Vec2::new(x, y) +fn v(x: f64, y: f64) -> solidcore_record::Vec2 { + solidcore_record::Vec2::new(x, y) } /// The corners of the polygon drawn by `out`, in order, and its support circle's centre and radius. -fn polygon_shape(s: &Session, out: &Value) -> (Vec, solidcraft_geom::Vec2, f64) { +fn polygon_shape(s: &Session, out: &Value) -> (Vec, solidcore_record::Vec2, f64) { use solidcraft_sketch::CurveKind; let sk = sketch(s); let corners = out["curves"] @@ -593,7 +594,7 @@ fn polygon_shape(s: &Session, out: &Value) -> (Vec, solid } /// A regular polygon: corners equally far from `c`, sides equally long. -fn assert_regular(corners: &[solidcraft_geom::Vec2], c: solidcraft_geom::Vec2, what: &str) { +fn assert_regular(corners: &[solidcore_record::Vec2], c: solidcore_record::Vec2, what: &str) { let n = corners.len(); let reach: Vec = corners.iter().map(|q| q.dist(c)).collect(); let sides: Vec = (0..n).map(|i| corners[i].dist(corners[(i + 1) % n])).collect(); @@ -781,7 +782,7 @@ fn arm_drags(links: Links) -> (usize, usize) { let v3 = v2 + v(b * (th1 + bend).cos(), b * (th1 + bend).sin()); let (tr, tt) = (lo + rnd() * (hi - lo), rnd() * TAU); let to = o + v(tr * tt.cos(), tr * tt.sin()); - let clear = |p: solidcraft_geom::Vec2| (lo..=hi).contains(&p.dist(o)); + let clear = |p: solidcore_record::Vec2| (lo..=hi).contains(&p.dist(o)); if !(0..=100).all(|i| clear(v3 + (to - v3) * (i as f64 / 100.0))) { continue; } @@ -868,13 +869,13 @@ fn hanging_triangle_flips(n: usize) -> usize { let v3 = v2 + v(b * (th1 + bend).cos(), b * (th1 + bend).sin()); let (tr, tt) = (lo + rnd() * (hi - lo), rnd() * TAU); let to = o + v(tr * tt.cos(), tr * tt.sin()); - let clear = |p: solidcraft_geom::Vec2| (lo..=hi).contains(&p.dist(o)); + let clear = |p: solidcore_record::Vec2| (lo..=hi).contains(&p.dist(o)); if !(0..=100).all(|i| clear(v3 + (to - v3) * (i as f64 / 100.0))) { continue; } kept += 1; let turn = rnd() * TAU; - let u = solidcraft_geom::Vec2::from_angle(turn); + let u = solidcore_record::Vec2::from_angle(turn); let normal = u.perp() * if rnd() < 0.5 { 1.0 } else { -1.0 }; let (tq, tr) = (v3 + u * 3.9, v3 + u * 1.95 + normal * (4.0f64 - 1.95 * 1.95).sqrt()); { @@ -1068,7 +1069,7 @@ fn a_dragged_fillet_stays_in_its_corner() { let arc_id = sk0.curves[arc].id.clone(); let inside = |s: &Session| { let sk = sketch(s); - let side = |p: solidcraft_geom::Vec2, a: solidcraft_geom::Vec2, b: solidcraft_geom::Vec2| (b - a).cross(p - a).signum(); + let side = |p: solidcore_record::Vec2, a: solidcore_record::Vec2, b: solidcore_record::Vec2| (b - a).cross(p - a).signum(); let c = sk.center(arc).expect("centre"); let (p0, k1, k2, p3) = (pt(s, "l1.start"), pt(s, "l1.end"), pt(s, "l2.start"), pt(s, "l2.end")); let r = sk.radius(arc).unwrap_or(0.0); @@ -1379,8 +1380,8 @@ fn three_d_curves_need_the_option_and_move_joined() { let sk = sketch(&s); let w = &sk.wires[sk.wire_index(&sid).expect("spline")]; assert!(w.pts.len() > 10); - assert!(w.pts.first().expect("p").dist(solidcraft_geom::Vec3::new(10.0, 0.0, 10.0)) < 1e-12); - assert!(w.pts.last().expect("p").dist(solidcraft_geom::Vec3::new(20.0, 0.0, 20.0)) < 1e-12); + assert!(w.pts.first().expect("p").dist(solidcore_record::Vec3::new(10.0, 0.0, 10.0)) < 1e-12); + assert!(w.pts.last().expect("p").dist(solidcore_record::Vec3::new(20.0, 0.0, 20.0)) < 1e-12); // The shared corner moves for both lines (and the spline that starts there). let r = run(&mut s, "sketch.move3d", json!({"wire": ids[1], "index": 1, "by": [0, 0, 5]})); assert_eq!(r["moved"], 2); @@ -1538,7 +1539,7 @@ fn hung_elbow_side(s: &Session) -> f64 { } /// The hand of `hung_arm` swung by `angle` about the shoulder. -fn hung_hand_target(s: &Session, angle: f64, scale: f64) -> solidcraft_geom::Vec2 { +fn hung_hand_target(s: &Session, angle: f64, scale: f64) -> solidcore_record::Vec2 { let (b, h) = (pt(s, "ab.end"), pt(s, "eh.end")); let r = h - b; let (c, si) = (angle.cos(), angle.sin()); @@ -1717,8 +1718,17 @@ fn the_first_dimension_scales_shapes_joined_by_a_constraint() { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})); run(&mut s, "sketch.rectangle.two_point", json!({"p0": [30, 10], "p1": [45, 20]})); run(&mut s, "sketch.constraint.coincident", json!({"a": "l1.start", "b": "l5.start"})); + let before = sketch(&s); + let f = 40.0 / pt(&s, "l1.end").dist(pt(&s, "l1.start")); let out = run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "40 mm", "scale_sketch": true})); - assert!(out.get("scaled").is_some(), "{out}"); + assert!((out["scaled"].as_f64().unwrap() - f).abs() < 1e-6, "{out}"); + // l1 measures its value, and every point of both rectangles, the joined one too, scaled + // about the origin by the same factor: the joined rectangle keeps its shape at its scaled place. + assert!((pt(&s, "l1.end").dist(pt(&s, "l1.start")) - 40.0).abs() < 1e-6); + let after = sketch(&s); + for (p, q) in before.points.iter().zip(&after.points) { + assert!(q.pos.dist(p.pos * f) < 1e-6, "{} {:?} -> {:?}", p.id, p.pos, q.pos); + } } /// The cursor fallback shares the held solves' frame budget; a scripted drag can finish later. @@ -1800,6 +1810,55 @@ fn budget_limited_cursor_progress_requests_a_frame_with_the_same_target() { // --------------------------------------------------------------------------------------------- // Cancel Sketch (#3838) +fn sketch_below_a_solid() -> (Session, u64) { + let mut s = Session::default(); + let id = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5})); + (s, id) +} + +#[test] +fn finishing_a_temporary_sketch_edit_at_the_undo_limit_keeps_the_original_design() { + let (mut s, id) = sketch_below_a_solid(); + for i in 0..crate::MAX_UNDO { + run(&mut s, "browser.visibility", json!({"items": ["Body1"], "visible": i % 2 != 0})); + } + assert_eq!(s.undo.len(), crate::MAX_UNDO); + let before = s.doc.to_json(); + run(&mut s, "sketch.edit", json!({"sketch": id, "restore_marker": null})); + for y in [20, 30] { + run(&mut s, "sketch.line", json!({"points": [[0, y], [10, y]]})); + } + run(&mut s, "sketch.finish", json!({})); + assert!(s.undo.len() <= crate::MAX_UNDO); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.active_sketch, None); + assert_eq!(s.model.state().bodies.len(), 1); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.marker, None); + assert_eq!(s.doc.sketch(id).unwrap().curves.len(), 6); +} + +#[test] +fn undoing_cancel_then_finishing_restores_the_temporary_sketch_marker() { + let (mut s, id) = sketch_below_a_solid(); + run(&mut s, "sketch.edit", json!({"sketch": id, "restore_marker": null})); + run(&mut s, "sketch.line", json!({"points": [[0, 20], [10, 20]]})); + run(&mut s, "sketch.cancel", json!({})); + assert_eq!(s.doc.marker, None); + assert_eq!(s.doc.sketch(id).unwrap().curves.len(), 4); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.active_sketch, Some(id)); + run(&mut s, "sketch.finish", json!({})); + assert_eq!(s.doc.marker, None); + assert_eq!(s.active_sketch, None); + assert_eq!(s.doc.sketch(id).unwrap().curves.len(), 5); + assert_eq!(s.model.state().bodies.len(), 1); +} + #[test] fn cancel_removes_a_new_sketch_with_its_dimensions_and_undo_brings_it_back() { let mut s = Session::default(); @@ -1883,7 +1942,7 @@ fn dragging_an_end_of_a_tangent_line_leaves_its_other_end_still() { drag(&mut s, &format!("{l}.end"), [20.0, 10.0], [5.0, 12.0]); assert!(at(&s, &format!("{l}.start")).dist(start) < 1e-7, "the far end moved: {:?}", at(&s, &format!("{l}.start"))); assert!( - at(&s, &format!("{l}.end")).dist(solidcraft_geom::Vec2::new(5.0, 12.0)) < 1e-6, + at(&s, &format!("{l}.end")).dist(solidcore_record::Vec2::new(5.0, 12.0)) < 1e-6, "the end went where dragged: {:?}", at(&s, &format!("{l}.end")) ); @@ -1967,12 +2026,12 @@ fn a_changed_length_dimension_keeps_its_first_point() { let width = run(&mut s, "sketch.dimension", json!({"entities": [bottom]}))["param"].as_str().unwrap().to_string(); let height = run(&mut s, "sketch.dimension", json!({"entities": [right]}))["param"].as_str().unwrap().to_string(); run(&mut s, "parameters.change", json!({"name": width, "expression": "60 mm"})); - assert!(at(&s, "p1").dist(solidcraft_geom::Vec2::new(10.0, 10.0)) < 1e-6, "the first corner stays: {:?}", at(&s, "p1")); - assert!(at(&s, "p2").dist(solidcraft_geom::Vec2::new(70.0, 10.0)) < 1e-6, "the far corner moves: {:?}", at(&s, "p2")); + assert!(at(&s, "p1").dist(solidcore_record::Vec2::new(10.0, 10.0)) < 1e-6, "the first corner stays: {:?}", at(&s, "p1")); + assert!(at(&s, "p2").dist(solidcore_record::Vec2::new(70.0, 10.0)) < 1e-6, "the far corner moves: {:?}", at(&s, "p2")); // Several at once: the right side grows up from its start, the bottom-right corner. run(&mut s, "parameters.change", json!({"changes": {height: "25 mm"}})); - assert!(at(&s, "p2").dist(solidcraft_geom::Vec2::new(70.0, 10.0)) < 1e-6, "{:?}", at(&s, "p2")); - assert!(at(&s, "p3").dist(solidcraft_geom::Vec2::new(70.0, 35.0)) < 1e-6, "{:?}", at(&s, "p3")); + assert!(at(&s, "p2").dist(solidcore_record::Vec2::new(70.0, 10.0)) < 1e-6, "{:?}", at(&s, "p2")); + assert!(at(&s, "p3").dist(solidcore_record::Vec2::new(70.0, 35.0)) < 1e-6, "{:?}", at(&s, "p3")); // Centred on the Y axis: holding a corner can't keep it symmetric, so both ends move. let mut s = new_sketch(); diff --git a/crates/engine/src/cmd/solid_move_copy_tests.rs b/crates/engine/src/cmd/solid_move_copy_tests.rs index 793817540..c9f5da037 100644 --- a/crates/engine/src/cmd/solid_move_copy_tests.rs +++ b/crates/engine/src/cmd/solid_move_copy_tests.rs @@ -181,3 +181,160 @@ fn an_older_design_with_no_copy_key_at_all_still_loads_and_moves_in_place() { let moved = state.body("Cube").unwrap(); assert!(moved.mesh().bounds().min.dist(Vec3::new(5.0, 0.0, 0.0)) < 1e-6); } + +/// A component `Part` holding a 20 mm cube at the origin, placed once at the root. +fn part_with_cube(s: &mut Session) -> (u64, u64) { + let made = run(s, "component.create", json!({"name": "Part", "grounded": false})); + cube20(s, "Peg"); + run(s, "component.activate", json!({"component": "root"})); + (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap()) +} + +/// The component an occurrence is an instance of. +fn component_of(s: &Session, occurrence: u64) -> u64 { + s.doc.occurrences.iter().find(|o| o.id == occurrence).expect("the occurrence exists").component +} + +/// The lowest corner of the first body a placement shows, in the world. +fn world_min(s: &Session, path: &[u64]) -> Vec3 { + let names = s.occurrence_bodies(path, true).unwrap(); + s.world_state().unwrap().body(&names[0]).unwrap().mesh().bounds().min +} + +#[test] +fn copying_a_picked_component_makes_an_independent_component_at_the_moved_place() { + let mut s = Session::default(); + let (part, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let source = world_min(&s, &[occurrence]); + let reply = run(&mut s, "solid.move", json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]})); + let copy = reply["occurrences"][0].as_u64().expect("the move reports the copy it made"); + let copied = component_of(&s, copy); + assert_ne!(copied, part, "an independent copy of the component, not another instance of it"); + let name = &s.doc.components.iter().find(|c| c.id == copied).expect("the copy is a component").name; + assert_eq!(name, "Part (2)", "named the way Paste New names its copies"); + assert!(world_min(&s, &[copy]).dist(Vec3::new(source.x + 50.0, source.y, source.z)) < 1e-6, "the copy lands at the moved place"); + assert!(world_min(&s, &[occurrence]).dist(source) < 1e-6, "the original component stays where it was"); + assert_eq!(s.occurrence_bodies(&[occurrence], true).unwrap().len(), 1, "the original keeps its body"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before, "one undo removes the copy"); +} + +#[test] +fn a_copied_component_turns_with_the_move() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let reply = run( + &mut s, + "solid.move", + json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [0, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"}), + ); + let copy = reply["occurrences"][0].as_u64().unwrap(); + // A quarter turn about the origin takes the cube's x from 0..20 to -20..0 and y to 0..20. + assert!(world_min(&s, &[copy]).dist(Vec3::new(-20.0, 0.0, 0.0)) < 1e-6, "the copy turns with the move"); + assert!(world_min(&s, &[occurrence]).dist(Vec3::ZERO) < 1e-6, "the original does not turn"); +} + +#[test] +fn bodies_and_a_component_copied_together_are_one_undo_step() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + cube20_at(&mut s, "Top", [0, 0, 50]); + let before = s.doc.clone(); + let count = s.model.state().bodies.len(); + let reply = run(&mut s, "solid.move", json!({"bodies": ["Top"], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]})); + assert_eq!(reply["occurrences"].as_array().map(Vec::len), Some(1)); + assert!(reply.get("feature").is_some(), "the reply is a solid.move reply: the body feature's, with the copies alongside"); + assert_eq!(s.model.state().bodies.len(), count + 2, "a copy of the body and of the component"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before, "one undo removes both copies"); +} + +/// A copying move of a component and of bodies in differently turned frames (a block in the root +/// and a screw inserted lying down) is one move: the component's copy turns with it, the bodies +/// split into one feature per frame as a move of them alone does (#9660), in one undo step. +#[test] +fn a_copied_component_and_bodies_in_differently_turned_frames_are_one_undo_step() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 10, "center": [0, 0, 5], "body_name": "Block"})); + run( + &mut s, + "parts.insert", + json!({"family": "socket_head_cap_screw", "size": "M3", "length": 12, "point": [0, 0, 10], "direction": [1, 0, 0], "name": "screw"}), + ); + let before = s.doc.clone(); + let reply = run( + &mut s, + "solid.move", + json!({"bodies": ["Block", "Body1"], "occurrences": [[occurrence]], "copy": true, "axis": [0, 0, 1], "angle": "90 deg"}), + ); + assert_eq!(reply["features"].as_array().map(Vec::len), Some(2), "one Move feature per frame"); + let copy = reply["occurrences"][0].as_u64().expect("the move reports the copy it made"); + assert!(world_min(&s, &[copy]).dist(Vec3::new(-20.0, 0.0, 0.0)) < 1e-6, "the copy turns with the move"); + assert!(world_min(&s, &[occurrence]).dist(Vec3::ZERO) < 1e-6, "the original does not turn"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before, "one undo removes the copies of the component and of the bodies"); +} + +#[test] +fn a_component_picked_with_its_parent_is_copied_once_inside_the_parents_copy() { + let mut s = Session::default(); + // `Outer` at the root holds `Inner`, which holds a 20 mm cube. + let outer = run(&mut s, "component.create", json!({"name": "Outer", "grounded": false}))["occurrence"].as_u64().unwrap(); + let inner = run(&mut s, "component.create", json!({"name": "Inner", "parent": "Outer"}))["occurrence"].as_u64().unwrap(); + cube20(&mut s, "Peg"); + run(&mut s, "component.activate", json!({"component": "root"})); + let counts = |s: &Session| (s.doc.components.len(), s.doc.occurrences.len(), s.model.state().bodies.len()); + assert_eq!(counts(&s), (2, 2, 1), "components, occurrences and bodies before the move"); + let before = s.doc.clone(); + let source = world_min(&s, &[outer, inner]); + + // Both are picked, Inner inside Outer: Inner comes with its parent's copy, so one copy is made. + let reply = run(&mut s, "solid.move", json!({"bodies": [], "occurrences": [[outer], [outer, inner]], "copy": true, "translate": [50, 0, 0]})); + assert_eq!(reply["occurrences"].as_array().map(Vec::len), Some(1), "one copy: Inner is copied inside Outer's copy"); + let copy = reply["occurrences"][0].as_u64().unwrap(); + assert_eq!(counts(&s), (4, 4, 2), "the copy of Outer and its own Inner, with the cube copied once"); + assert!( + world_min(&s, &[copy]).dist(Vec3::new(source.x + 50.0, source.y, source.z)) < 1e-6, + "the copied cube sits 50 mm along X from the original" + ); + assert!(world_min(&s, &[outer, inner]).dist(source) < 1e-6, "the original cube stays where it was"); + + run(&mut s, "edit.undo", json!({})); + assert_eq!(counts(&s), (2, 2, 1), "one undo puts back the two components, two occurrences and one body"); + assert_eq!(s.doc, before, "one undo removes the whole copy"); +} + +#[test] +fn a_copy_that_fails_part_way_changes_nothing() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let undo = s.undo.len(); + // The first component copies; the second names no occurrence, so the whole move is refused. + let error = s.execute("solid.move", &json!({"bodies": [], "occurrences": [[occurrence], [999_999]], "copy": true, "translate": [50, 0, 0]})); + assert!(error.is_err()); + assert_eq!(s.doc, before, "the first copy is rolled back with the rest"); + assert_eq!(s.undo.len(), undo, "a refused move leaves no undo step"); +} + +#[test] +fn components_move_only_as_copies() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let error = s.execute("solid.move", &json!({"bodies": [], "occurrences": [[occurrence]], "translate": [50, 0, 0]})).unwrap_err(); + assert!(error.to_string().contains("copy"), "{error}"); + assert_eq!(s.doc, before, "a refused move changes nothing"); +} + +#[test] +fn bodies_that_are_not_a_list_are_refused_with_components() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let error = s.execute("solid.move", &json!({"bodies": "Peg", "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]})).unwrap_err(); + assert!(error.to_string().contains("bodies"), "{error}"); + assert_eq!(s.doc, before, "a refused move changes nothing"); +} diff --git a/crates/engine/src/cmd/stacked_face_tests.rs b/crates/engine/src/cmd/stacked_face_tests.rs index 673d62dad..79d67db7a 100644 --- a/crates/engine/src/cmd/stacked_face_tests.rs +++ b/crates/engine/src/cmd/stacked_face_tests.rs @@ -5,6 +5,7 @@ use crate::Session; use serde_json::{Value, json}; use solidcraft_doc::FaceAttachmentStatus; +use solidcraft_geom::prelude::*; fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap_or_else(|e| panic!("{command} {params}: {e}")) @@ -40,7 +41,7 @@ fn two_extrudes(circle: bool, full: bool, on_face: bool, operation: &str) -> Ses s } -fn healthy(s: &Session, sketch: &str) -> solidcraft_geom::Plane { +fn healthy(s: &Session, sketch: &str) -> solidcore_record::Plane { let id = s.doc.find_feature(sketch).map(|f| f.id).unwrap(); match s.placed_document().sketch_face_attachment(id, &s.model) { FaceAttachmentStatus::Healthy { plane, .. } => plane, diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 05d6942e4..1e812db8d 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -8,7 +8,8 @@ use solidcraft_doc::{ }; use solidcraft_doc::{BodyName, SketchId}; use solidcraft_doc::{Dir, FacePick, Position}; -use solidcraft_kernel::Continuity; +use solidcraft_geom::prelude::*; +use solidcraft_kernel::{Construction, Continuity}; use super::CommandSpec; use super::features::{add_feature, axis_param, check_expr, extent_param, feature_sketch, operation, plane_param, profiles, sketch_id}; @@ -19,7 +20,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.patch", "Patch", patch) .at("SURFACE", "CREATE") .icon("surface_patch") - .params("sketch?: id|name and profiles? (planar patches of sketch regions) | edges: [[x,y,z]] (points on a closed loop of a body's edges: one face on them, planar when the loop is, else a smooth B-spline surface) and body?; continuity?: g0|g1|g2 (edges only, default g0: how the patch meets the faces beside the loop — g1 their tangent planes, g2 also their curvature across the edges) or [{edge: [x,y,z], g: g0|g1|g2}] (those edges so, the rest g0) or {all, edges}; points?: [[x,y,z]] (edges only, up to 64: points the patch passes through); crown?: number −0.9…3 (default 0: only a fitted patch, whose middle becomes fuller by this many times the loop's size — the bump vanishes on the loop, so the face still meets the picked edges and the continuity across them; a loop that is planar and g0 is the exact plane whatever the crown; with points, crown needs a g1 or g2 edge); name?, body_name?"), + .params("sketch?: id|name and profiles? (planar patches of sketch regions) | edges: [[x,y,z]] (points on a closed loop of a body's edges: one face on them, planar when the loop is, else a smooth B-spline surface) and body?; continuity?: g0|g1|g2|g3|g4 (edges only, default g0: how the patch meets the faces beside the loop — g1 their tangent planes, g2 also their curvature across the edges, g3 also its rate of change, g4 the change of that rate) or [{edge: [x,y,z], g: g0|g1|g2|g3|g4}] (those edges so, the rest g0) or {all, edges}; points?: [[x,y,z]] (edges only, up to 64: points the patch passes through); crown?: number −0.9…3 (default 0: only a fitted patch, whose middle becomes fuller by this many times the loop's size — the bump vanishes on the loop, so the face still meets the picked edges and the continuity across them; a loop that is planar and g0 is the exact plane whatever the crown; with points, crown needs a g1 or higher edge); name?, body_name?"), CommandSpec::new("surface.stitch", "Stitch", stitch) .at("SURFACE", "MODIFY") .icon("surface_stitch") @@ -31,7 +32,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.extend", "Extend", extend) .at("SURFACE", "MODIFY") .icon("surface_extend") - .params("body: surface name; edges: [[x,y,z]] (points on boundary edges to push out); distance: expr (unless up_to); mode?: natural (the surface itself continued: exact for planes and surfaces of revolution, a B-spline's end spans continued; the default) | tangent (a ruled run-off face along each edge, G1) | curvature (a run-off face keeping the surface's curvature across the edge, G2); up_to?: plane (XY|XZ|YZ|plane name|{origin, normal}) | {body, point} (a face, its surface extended) | \"bounds\" (natural: back to the surface's own bounds, undoing a trim); neighbours?: bool (default true: the edges next to an extended edge are lengthened to meet it; false: the extension's sides run square to the edge)"), + .params("body: surface name; edges: [[x,y,z]] (points on boundary edges to push out); distance: expr (unless up_to); mode?: natural (the surface itself continued: a B-spline's end spans continued, which keeps planes and surfaces of revolution on themselves; the default) | tangent (the face continued tangent to its surface across the edge, G1) | curvature (continued keeping the surface's curvature across the edge too, G2); up_to?: plane (XY|XZ|YZ|plane name|{origin, normal}) | {body, point} (a face, its surface extended) | \"bounds\" (natural: back to the surface's own bounds, undoing a trim); neighbours?: bool (default true: the edges next to an extended edge are lengthened to meet it; false: the extension's sides run square to the edge)"), CommandSpec::new("surface.trim", "Trim", trim) .at("SURFACE", "MODIFY") .icon("surface_trim") @@ -39,7 +40,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.extrude", "Surface Extrude", surface_extrude) .at("SURFACE", "CREATE") .icon("surface_extrude") - .params("sketch?: id|name; curves?: [curve ids] (open or closed chains of curves meeting end to end) and/or profiles? (their boundaries; the default when no curves are given); distance: expr; direction?: positive|negative|symmetric; distance2?: expr; start_offset?: expr; name?, body_name? (a surface body: walls only, no caps)"), + .params("sketch?: id|name; curves?: [curve ids] (open or closed chains of curves meeting end to end) and/or profiles? (their boundaries; the default when no curves are given); distance: expr; direction?: positive|negative|symmetric (symmetric: distance is the total, split evenly around the start plane, as solid.extrude); convention?: total_distance|legacy_per_side (as solid.extrude; default total_distance; legacy_per_side: the distance on each side, as older symmetric surface extrudes keep); distance2?: expr; start_offset?: expr; name?, body_name? (a surface body: walls only, no caps)"), CommandSpec::new("surface.revolve", "Surface Revolve", surface_revolve) .at("SURFACE", "CREATE") .icon("surface_revolve") @@ -59,7 +60,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.ruled", "Ruled Surface", ruled) .at("SURFACE", "CREATE") .icon("surface_ruled") - .params("body; edges: [[x,y,z]] (points on a chain of its edges, open or closed); distance: expr (how far the strip reaches); mode?: normal|tangent|angle|direction (default normal: along the normal of the face beside each edge; tangent: continuing it); angle?: expr (angle mode: from `direction`, else from the face's normal, turned away from the face; 90 deg from the normal is tangent); direction?: [x,y,z] (direction mode: the rulings; angle mode: the reference, e.g. a pull direction for a draft); face?: [x,y,z] (a point on the face the directions come from; default: the face beside the most picked edges); flip?: bool (the other side); corners?: mitre|round (sharp corners of the chain; inside corners are always cut back). Lines and arcs give exact planes, cylinders and cones, other edges a fitted ruled B-spline. A new surface body"), + .params("body; edges: [[x,y,z]] (points on a chain of its edges, open or closed); distance: expr (how far the strip reaches); mode?: normal|tangent|angle|direction (default normal: along the normal of the face beside each edge; tangent: continuing it); angle?: expr (angle mode: from `direction`, else from the face's normal, turned away from the face; 90 deg from the normal is tangent); direction?: [x,y,z] (direction mode: the rulings; angle mode: the reference, e.g. a pull direction for a draft); face?: [x,y,z] (a point on the face the directions come from; default: the face beside the most picked edges); flip?: bool (the other side); corners?: mitre|round (sharp corners of the chain; inside corners are always cut back); far?: [null|[[x,y,z]]] (per chain edge, the interior control points of a free strip's far curve, as the default curve's handles list them; null: the default). A constant ruling, or one keeping its angle to an arc's axis, gives an exact plane, cylinder or cone; where the rulings turn freely along an edge, the strip is the exact ruled surface to a far curve of its own (from corner to corner, fair, near the rulings' ends). A new surface body"), CommandSpec::new("surface.blend", "Blend Surface", blend) .at("SURFACE", "CREATE") .icon("surface_blend") @@ -91,7 +92,8 @@ fn patch(s: &mut Session, p: &Value) -> Result { let crown = crown_param(p, cmd)?; let continuity = patch_continuity(p, cmd)?; let points: Vec = patch_points(p, cmd)?.into_iter().map(Position).collect(); - let edges: Vec = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + let edges: Vec = + p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); let mut v = if !edges.is_empty() { if edges.len() > 10_000 { return Err(bad(cmd, "too many edges")); @@ -134,12 +136,9 @@ fn patch(s: &mut Session, p: &Value) -> Result { Ok(v) } -/// A continuity word for a patch: g0, g1 or g2 (a patch does not hold g3). +/// A continuity word for a patch, within what a patch builds ([`Construction::Patch`]). fn patch_order(v: Option<&Value>, cmd: &str) -> Result { - match v.and_then(Value::as_str).and_then(Continuity::parse) { - Some(g) if g != Continuity::G3 => Ok(g), - _ => Err(bad(cmd, "a patch's continuity is g0, g1 or g2")), - } + crate::params::continuity(cmd, v, "a patch's continuity", Construction::Patch) } /// The patch's `continuity`: one word for every edge, a list of `{edge, g}` for some edges (the @@ -172,12 +171,15 @@ fn patch_continuity(p: &Value, cmd: &str) -> Result { }; Ok(PatchContinuity { all, edges }) } - Some(_) => Err(bad(cmd, "`continuity` must be g0, g1 or g2, or a list of {edge, g}")), + Some(_) => { + let (lowest, highest) = Construction::Patch.orders(); + Err(bad(cmd, format!("`continuity` must be {}, or a list of {{edge, g}}", Continuity::words(lowest, highest)))) + } } } /// The points a patch passes through (at most 64, each a finite point). -fn patch_points(p: &Value, cmd: &str) -> Result> { +fn patch_points(p: &Value, cmd: &str) -> Result> { let Some(v) = p.get("points") else { return Ok(Vec::new()) }; let list = v .as_array() @@ -202,7 +204,7 @@ fn crown_param(p: &Value, cmd: &str) -> Result { fn blend_side(p: &Value, cmd: &str, key: &str) -> Result { let side = p.get(key).ok_or_else(|| bad(cmd, format!("`{key}` must be {{body, edges}}")))?; let body = str_(side, "body").ok_or_else(|| bad(cmd, format!("`{key}.body` must name a body")))?; - let edges: Vec = + let edges: Vec = side.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if edges.is_empty() || edges.len() > 10_000 { return Err(bad(cmd, format!("`{key}.edges` must list 1 to 10000 points on the edges of a chain"))); @@ -219,9 +221,7 @@ fn blend(s: &mut Session, p: &Value) -> Result { None => [Continuity::G1, Continuity::G1], Some(v) => { let list = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, "`continuity` must be two words, one per end"))?; - let word = |x: Option<&Value>| -> Result { - x.and_then(Value::as_str).and_then(Continuity::parse).ok_or_else(|| bad(cmd, "`continuity` entries must be g0, g1, g2 or g3")) - }; + let word = |x: Option<&Value>| crate::params::continuity(cmd, x, "a `continuity` entry", Construction::Bridge); [word(list.first())?, word(list.get(1))?] } }; @@ -263,12 +263,13 @@ fn surface_extrude(s: &mut Session, p: &Value) -> Result { } /// A body by name, and points on some of its faces (none: all of them). -fn body_faces(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec)> { +fn body_faces(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec)> { let body = str_(p, "body").ok_or_else(|| bad(cmd, "`body` is required"))?.to_string(); if s.model.state().body(&body).is_none() { return Err(bad(cmd, format!("no body `{body}`"))); } - let faces: Vec = p.get("faces").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + let faces: Vec = + p.get("faces").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if faces.len() > 10_000 { return Err(bad(cmd, "too many faces")); } @@ -300,7 +301,7 @@ fn untrim(s: &mut Session, p: &Value) -> Result { if points.len() > 10_000 { return Err(bad(cmd, "too many holes")); } - let points: Option> = points.iter().map(vec3).collect(); + let points: Option> = points.iter().map(vec3).collect(); Some(points.ok_or_else(|| bad(cmd, "`holes` must list points [x, y, z] on the inner loops"))?) } Some(_) => return Err(bad(cmd, "`holes` must be \"all\" or a list of points [x, y, z] on the inner loops")), @@ -384,7 +385,7 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result { // A section is a chain of sketch curves, or an edge chain of a body whose face the end of // the loft repeats. if let Some(body) = str_(sec, "body") { - let edges: Vec = + let edges: Vec = sec.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if edges.is_empty() || edges.len() > 10_000 { return Err(bad(cmd, "`sections.edges` must list 1 to 10000 points on the edges of a chain")); @@ -413,9 +414,7 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result { None => [Continuity::G0, Continuity::G0], Some(v) => { let list = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, "`continuity` must be two words, one per end"))?; - let word = |x: Option<&Value>| -> Result { - x.and_then(Value::as_str).and_then(Continuity::parse).ok_or_else(|| bad(cmd, "`continuity` entries must be g0, g1, g2 or g3")) - }; + let word = |x: Option<&Value>| crate::params::continuity(cmd, x, "a `continuity` entry", Construction::Bridge); [word(list.first())?, word(list.get(1))?] } }; @@ -437,7 +436,8 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result { fn offset(s: &mut Session, p: &Value) -> Result { let cmd = "surface.offset"; - let faces: Vec = p.get("faces").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + let faces: Vec = + p.get("faces").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if faces.is_empty() || faces.len() > 10_000 { return Err(bad(cmd, "`faces` must list points on the faces to offset")); } @@ -463,7 +463,8 @@ fn ruled(s: &mut Session, p: &Value) -> Result { if s.model.state().body(&body).is_none() { return Err(bad(cmd, format!("no body `{body}`"))); } - let edges: Vec = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + let edges: Vec = + p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if edges.is_empty() || edges.len() > 10_000 { return Err(bad(cmd, "`edges` must list points on a chain of the body's edges")); } @@ -501,6 +502,26 @@ fn ruled(s: &mut Session, p: &Value) -> Result { Some(v) => Some(vec3(v).ok_or_else(|| bad(cmd, "`face` must be [x, y, z] on a face"))?), None => None, }; + // A free strip's far-curve handles, per chain edge: a list of points, or null for the default. + let far = match p.get("far").filter(|v| !v.is_null()) { + None => Vec::new(), + Some(v) => { + let lists = + v.as_array().filter(|a| a.len() <= 10_000).ok_or_else(|| bad(cmd, "`far` must be a list, per edge, of null or [[x, y, z], ...]"))?; + lists + .iter() + .map(|h| match h { + Value::Null => Ok(None), + Value::Array(pts) if pts.len() <= 100_000 => pts + .iter() + .map(|q| vec3(q).map(Position).ok_or_else(|| bad(cmd, "`far` handles must be [x, y, z]"))) + .collect::>>() + .map(Some), + _ => Err(bad(cmd, "`far` must be a list, per edge, of null or [[x, y, z], ...]")), + }) + .collect::>>()? + } + }; let kind = FeatureKind::SurfaceRuled { body: BodyName(body), edges: edges.into_iter().map(Position).collect(), @@ -511,6 +532,7 @@ fn ruled(s: &mut Session, p: &Value) -> Result { flip: bool_(p, "flip").unwrap_or(false), corners, face: face.map(FacePick), + far, }; add_feature(s, p, kind) } @@ -556,7 +578,8 @@ fn extend(s: &mut Session, p: &Value) -> Result { if s.model.state().body(&body).is_none() { return Err(bad(cmd, format!("no body `{body}`"))); } - let edges: Vec = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + let edges: Vec = + p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if edges.is_empty() || edges.len() > 10_000 { return Err(bad(cmd, "`edges` must list points on the edges to extend")); } @@ -597,7 +620,7 @@ fn extend(s: &mut Session, p: &Value) -> Result { } /// Points to keep: one `[x, y, z]`, or a list of them (at most 10 000). -fn keep_points(v: Option<&Value>, cmd: &str, key: &str) -> Result> { +fn keep_points(v: Option<&Value>, cmd: &str, key: &str) -> Result> { let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; if let Some(p) = vec3(v) { return Ok(vec![p]); @@ -752,12 +775,12 @@ mod tests { s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")) } fn volume(s: &Session, name: &str) -> f64 { - let st = s.world_state(); + let st = s.world_state().unwrap(); solidcraft_kernel::measure(&st.body(name).unwrap().body).unwrap().volume } fn area(s: &Session, name: &str) -> f64 { - solidcraft_kernel::measure(&s.world_state().body(name).unwrap().body).unwrap().area + solidcraft_kernel::measure(&s.world_state().unwrap().body(name).unwrap().body).unwrap().area } /// Surface Extrude of open curves: a line and an arc joined end to end (listed in either @@ -774,19 +797,20 @@ mod tests { .to_string(); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": [arc, "l1"], "distance": 4, "body_name": "Wall"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let wall = &st.body("Wall").unwrap().body; assert!(wall.is_surface() && wall.face_count() == 2); // The line's wall and the half circle's (radius 5): length × height. let want = (10.0 + std::f64::consts::PI * 5.0) * 4.0; assert!((area(&s, "Wall") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Wall")); - run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": ["l1"], "distance": 2, "direction": "symmetric", "body_name": "Both"})); - let bb = solidcraft_kernel::measure(&s.world_state().body("Both").unwrap().body).unwrap().bbox; + // Symmetric: the distance is the total, split evenly around the sketch plane. + run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": ["l1"], "distance": 4, "direction": "symmetric", "body_name": "Both"})); + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Both").unwrap().body).unwrap().bbox; assert!((bb.min.z + 2.0).abs() < 1e-9 && (bb.max.z - 2.0).abs() < 1e-9, "{bb:?}"); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Both").is_none()); + assert!(s.world_state().unwrap().body("Both").is_none()); run(&mut s, "edit.redo", json!({})); - assert!(s.world_state().body("Both").is_some()); + assert!(s.world_state().unwrap().body("Both").is_some()); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Wall") - area(&s, "Wall")).abs() < 1e-9); // Refused: no such curve, a zero distance, and an extent a sheet does not take yet. @@ -804,7 +828,7 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 6]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.extrude", json!({"sketch": "R", "distance": 3, "body_name": "Walls"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let walls = &st.body("Walls").unwrap().body; assert!(walls.is_surface() && walls.face_count() == 4); assert!((area(&s, "Walls") - 96.0).abs() < 1e-9); @@ -812,7 +836,7 @@ mod tests { run(&mut s, "surface.patch", json!({"edges": edges(0.0), "body": "Walls", "body_name": "Bottom"})); run(&mut s, "surface.patch", json!({"edges": edges(3.0), "body": "Walls", "body_name": "Top"})); run(&mut s, "surface.stitch", json!({"bodies": ["Walls", "Bottom", "Top"]})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(!st.body("Walls").unwrap().body.is_surface()); run(&mut s, "solid.extrude", json!({"sketch": "R", "distance": 3, "body_name": "Solid"})); assert!((volume(&s, "Walls") - volume(&s, "Solid")).abs() < 1e-9); @@ -828,7 +852,7 @@ mod tests { run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); let names_before: Vec = solidcraft_doc::naming::face_names(s.model.state().body("Box").unwrap()).to_vec(); run(&mut s, "surface.unstitch", json!({"body": "Box"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Box").is_none()); let pieces: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); assert_eq!(pieces.len(), 6); @@ -843,19 +867,19 @@ mod tests { b.sort(); assert_eq!(a, b, "the faces keep their names"); run(&mut s, "surface.stitch", json!({"bodies": pieces})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let back = st.bodies.first().unwrap(); assert!(!back.body.is_surface()); assert!((solidcraft_kernel::measure(&back.body).unwrap().volume - 1000.0).abs() < 1e-9); run(&mut s, "edit.undo", json!({})); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Box").is_some()); + assert!(s.world_state().unwrap().body("Box").is_some()); run(&mut s, "surface.unstitch", json!({"body": "Box", "faces": [[5, 5, 10], [5, 5, 0]]})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 3); assert_eq!(st.body("Box").unwrap().body.face_count(), 4); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert_eq!(cold.world_state().bodies.len(), 3); + assert_eq!(cold.world_state().unwrap().bodies.len(), 3); assert!(s.execute("surface.unstitch", &json!({"body": "Nope"})).is_err()); assert!(s.execute("surface.unstitch", &json!({})).is_err()); } @@ -869,11 +893,11 @@ mod tests { run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.patch", json!({"sketch": "S", "body_name": "Sheet"})); run(&mut s, "surface.thicken", json!({"bodies": ["Sheet"], "thickness": 2, "body_name": "Up"})); - let up = solidcraft_kernel::measure(&s.world_state().body("Up").unwrap().body).unwrap().bbox; + let up = solidcraft_kernel::measure(&s.world_state().unwrap().body("Up").unwrap().body).unwrap().bbox; run(&mut s, "edit.undo", json!({})); run(&mut s, "surface.reverse_normal", json!({"body": "Sheet"})); run(&mut s, "surface.thicken", json!({"bodies": ["Sheet"], "thickness": 2, "body_name": "Down"})); - let down = solidcraft_kernel::measure(&s.world_state().body("Down").unwrap().body).unwrap().bbox; + let down = solidcraft_kernel::measure(&s.world_state().unwrap().body("Down").unwrap().body).unwrap().bbox; assert!((up.max.z - down.max.z - 2.0).abs() < 1e-9 && (up.min.z - down.min.z - 2.0).abs() < 1e-9, "{up:?} vs {down:?}"); run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [20, 0, 0], "body_name": "Cube"})); assert!(s.execute("surface.reverse_normal", &json!({"body": "Cube"})).is_err()); @@ -887,20 +911,20 @@ mod tests { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); run(&mut s, "face.delete", json!({"faces": [[5, 5, 10]], "heal": false})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let open = &st.body("Box").unwrap().body; assert!(open.is_surface() && open.face_count() == 5); let rim = json!([[5, 0, 10], [10, 5, 10], [5, 10, 10], [0, 5, 10]]); run(&mut s, "surface.patch", json!({"edges": rim, "body": "Box", "body_name": "Lid"})); run(&mut s, "surface.stitch", json!({"bodies": ["Box", "Lid"]})); - assert!(!s.world_state().body("Box").unwrap().body.is_surface()); + assert!(!s.world_state().unwrap().body("Box").unwrap().body.is_surface()); assert!((volume(&s, "Box") - 1000.0).abs() < 1e-9); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((volume(&cold, "Box") - 1000.0).abs() < 1e-9); // By default the gap heals, and a box's sides can't close its top: refused, the box kept. run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "body_name": "Healed"})); assert!(s.execute("face.delete", &json!({"faces": [[25, 5, 10]], "body": "Healed"})).is_err()); - assert!(!s.world_state().body("Healed").unwrap().body.is_surface()); + assert!(!s.world_state().unwrap().body("Healed").unwrap().body.is_surface()); let all = json!([[25, 5, 10], [25, 5, 0], [25, 0, 5], [25, 10, 5], [20, 5, 5], [30, 5, 5]]); assert!(s.execute("face.delete", &json!({"faces": all, "body": "Healed", "heal": false})).is_err()); } @@ -926,14 +950,14 @@ mod tests { "surface.revolve", json!({"sketch": "S", "curves": ["side"], "axis": "y", "angle": "90 deg", "symmetric": true, "body_name": "Both"}), ); - let bb = solidcraft_kernel::measure(&s.world_state().body("Both").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Both").unwrap().body).unwrap().bbox; let z = 3.0 * (PI / 4.0).sin(); assert!((bb.min.z + z).abs() < 1e-3 && (bb.max.z - z).abs() < 1e-3, "{bb:?}"); run(&mut s, "surface.revolve", json!({"sketch": "S", "curves": ["slant"], "axis": "y", "body_name": "Cone"})); close(area(&s, "Cone"), PI * 3.0 * 5.0); - assert!(s.world_state().body("Cone").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Cone").unwrap().body.is_surface()); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Cone").is_none()); + assert!(s.world_state().unwrap().body("Cone").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Cone") - area(&s, "Cone")).abs() < 1e-9); @@ -943,7 +967,7 @@ mod tests { run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.revolve", json!({"sketch": "R", "axis": "y", "body_name": "Ring"})); run(&mut s, "solid.revolve", json!({"sketch": "R", "axis": "y", "body_name": "Solid"})); - assert!(!s.world_state().body("Ring").unwrap().body.is_surface()); + assert!(!s.world_state().unwrap().body("Ring").unwrap().body.is_surface()); close(volume(&s, "Ring"), volume(&s, "Solid")); // Refused: a curve across the axis, no axis, and a turn of more than 360°. assert!(s.execute("surface.revolve", &json!({"sketch": "S", "curves": ["side"], "axis": {"origin": [3, 2, 0], "dir": [1, 0, 0]}})).is_err()); @@ -975,7 +999,7 @@ mod tests { run(&mut s, "sketch.finish", json!({})); let close = |a: f64, want: f64| assert!((a - want).abs() < want * 2e-3, "{a} vs {want}"); // (measured on meshes) run(&mut s, "surface.sweep", json!({"sketch": "S", "curves": ["l"], "path_sketch": "P", "path": ["up", arc], "body_name": "Bend"})); - assert!(s.world_state().body("Bend").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Bend").unwrap().body.is_surface()); close(area(&s, "Bend"), 10.0 * (5.0 + 5.0 * FRAC_PI_2)); run(&mut s, "surface.sweep", json!({"sketch": "S", "curves": ["l"], "path_sketch": "P", "path": ["up", "over"], "body_name": "Corner"})); close(area(&s, "Corner"), 100.0); @@ -983,11 +1007,11 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-1, -1], "p1": [1, 2]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.sweep", json!({"sketch": "R", "path_sketch": "P", "path": ["up"], "body_name": "Walls"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Walls").unwrap().body.is_surface() && st.body("Walls").unwrap().body.face_count() == 4); close(area(&s, "Walls"), 10.0 * 5.0); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Walls").is_none()); + assert!(s.world_state().unwrap().body("Walls").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Bend") - area(&s, "Bend")).abs() < 1e-9); @@ -1013,15 +1037,15 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, 0], "p1": [30, 6]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.loft", json!({"sections": [{"sketch": "A", "curves": ["a"]}, {"sketch": "B", "curves": ["b"]}], "body_name": "Strip"})); - assert!(s.world_state().body("Strip").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Strip").unwrap().body.is_surface()); assert!((area(&s, "Strip") - 50.0).abs() < 1e-6, "{}", area(&s, "Strip")); run(&mut s, "surface.loft", json!({"sections": [{"sketch": "A", "profiles": [0]}, {"sketch": "B", "profiles": [0]}], "body_name": "Walls"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let walls = &st.body("Walls").unwrap().body; assert!(walls.is_surface() && walls.face_count() == 4); assert!((area(&s, "Walls") - 160.0).abs() < 1e-6, "{}", area(&s, "Walls")); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Walls").is_none()); + assert!(s.world_state().unwrap().body("Walls").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Walls") - area(&s, "Walls")).abs() < 1e-9); @@ -1073,23 +1097,23 @@ mod tests { } } - /// Offset Surface: a cylinder's side picked once with its chain (both halves) moved out to - /// radius 12; a box top moved up exactly; a zero distance copies; past the axis refused, the - /// design left as it was; undo, redo and reopening. + /// Offset Surface: a cylinder's side (one face, closed along its seam) picked with its chain + /// moved out to radius 12; a box top moved up exactly; a zero distance copies; past the axis + /// refused, the design left as it was; undo, redo and reopening. #[test] fn offset_surface_of_a_cylinder_and_a_box_top() { let mut s = Session::default(); run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20, "body_name": "Can"})); run(&mut s, "surface.offset", json!({"faces": [[10, 0, 10]], "chain": true, "distance": 2, "body": "Can", "body_name": "Sleeve"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let sleeve = &st.body("Sleeve").unwrap().body; - assert!(sleeve.is_surface() && sleeve.face_count() == 2); + assert!(sleeve.is_surface()); let want = 2.0 * std::f64::consts::PI * 12.0 * 20.0; assert!((area(&s, "Sleeve") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Sleeve")); // (measured on meshes) assert!(st.body("Can").is_some(), "the source body stays"); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0], "body_name": "Box"})); run(&mut s, "surface.offset", json!({"faces": [[35, 5, 10]], "distance": "5 mm", "body_name": "Lid"})); - let bb = solidcraft_kernel::measure(&s.world_state().body("Lid").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Lid").unwrap().body).unwrap().bbox; assert!((bb.min.z - 15.0).abs() < 1e-9 && (area(&s, "Lid") - 100.0).abs() < 1e-9); run(&mut s, "surface.offset", json!({"faces": [[35, 5, 10]], "distance": 0, "body_name": "Copy"})); assert!((area(&s, "Copy") - 100.0).abs() < 1e-9); @@ -1097,7 +1121,7 @@ mod tests { assert!(s.execute("surface.offset", &json!({"faces": [[10, 0, 10]], "chain": true, "distance": -11, "body": "Can"})).is_err()); assert_eq!(s.doc.features.len(), before); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Copy").is_none()); + assert!(s.world_state().unwrap().body("Copy").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Sleeve") - area(&s, "Sleeve")).abs() < 1e-9); @@ -1117,7 +1141,7 @@ mod tests { let top = json!([5, 5, 10]); run(&mut s, "surface.ruled", json!({"body": "Box", "edges": rim, "distance": "2 mm", "mode": "tangent", "face": top, "body_name": "Flange"})); assert!((area(&s, "Flange") - 96.0).abs() < 1e-9, "{}", area(&s, "Flange")); - assert!(s.world_state().body("Flange").unwrap().body.is_surface() && s.world_state().body("Box").is_some()); + assert!(s.world_state().unwrap().body("Flange").unwrap().body.is_surface() && s.world_state().unwrap().body("Box").is_some()); run(&mut s, "surface.ruled", json!({"body": "Box", "edges": rim, "distance": 2, "face": top, "body_name": "Wall"})); assert!((area(&s, "Wall") - 80.0).abs() < 1e-9); run( @@ -1132,9 +1156,9 @@ mod tests { "surface.ruled", json!({"body": "Box", "edges": [[5, 0, 10]], "distance": 2, "mode": "direction", "direction": [0, -1, 0], "body_name": "Lip"}), ); - let bb = solidcraft_kernel::measure(&s.world_state().body("Lip").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Lip").unwrap().body).unwrap().bbox; assert!((area(&s, "Lip") - 20.0).abs() < 1e-9 && (bb.min.y + 2.0).abs() < 1e-9); - let st = s.world_state(); + let st = s.world_state().unwrap(); let names = solidcraft_doc::naming::face_names(st.body("Flange").unwrap()); assert!(names.len() == 4 && names.iter().all(|n| !n.is_empty()), "{names:?}"); let before = s.doc.features.len(); @@ -1151,7 +1175,7 @@ mod tests { } assert_eq!(s.doc.features.len(), before); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Lip").is_none()); + assert!(s.world_state().unwrap().body("Lip").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Draft") - area(&s, "Draft")).abs() < 1e-9); @@ -1166,7 +1190,7 @@ mod tests { } fn edge_count(s: &Session, name: &str) -> usize { - s.world_state().body(name).unwrap().body.edge_count() + s.world_state().unwrap().body(name).unwrap().body.edge_count() } /// Untrim the plate's top: every hole taken away gives one face of the whole 40 × 20 @@ -1178,9 +1202,9 @@ mod tests { plate_with_three_holes(&mut s); let top = [5.0, 5.0, 2.0]; let name = - solidcraft_doc::naming::face_name_at_body(s.model.state().body("Plate").unwrap(), solidcraft_geom::Vec3::new(5.0, 5.0, 2.0)).unwrap(); + solidcraft_doc::naming::face_name_at_body(s.model.state().body("Plate").unwrap(), solidcore_record::Vec3::new(5.0, 5.0, 2.0)).unwrap(); run(&mut s, "surface.untrim", json!({"face": {"body": "Plate", "point": top}, "body_name": "Top"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let made = &st.body("Top").unwrap().body; assert!(made.is_surface() && made.face_count() == 1); assert_eq!(edge_count(&s, "Top"), 4, "the rectangle alone"); @@ -1188,7 +1212,7 @@ mod tests { assert_eq!(solidcraft_doc::naming::face_names(s.model.state().body("Top").unwrap()).first(), Some(&name), "the face keeps its name"); assert!(st.body("Plate").is_some(), "the solid stays"); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Top").is_none()); + assert!(s.world_state().unwrap().body("Top").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Top") - 800.0).abs() < 1e-9); @@ -1235,7 +1259,7 @@ mod tests { let on = [10.0 * 2.5f64.cos(), 10.0 * 2.5f64.sin(), 5.0]; assert!(s.execute("surface.untrim", &json!({"face": {"body": "Half", "point": on}})).is_err(), "no holes, outer kept"); run(&mut s, "surface.untrim", json!({"face": {"body": "Half", "point": on}, "outer": true, "in_place": true})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 1, "untrimmed where it is"); assert!((area(&s, "Half") - 150.0 * pi).abs() < 150.0 * pi * 1e-3, "{}", area(&s, "Half")); // (measured on meshes) let bb = solidcraft_kernel::measure(&st.body("Half").unwrap().body).unwrap().bbox; @@ -1249,13 +1273,13 @@ mod tests { fn untrim_an_imported_step_face() { let mut s = Session::default(); plate_with_three_holes(&mut s); - let step = solidcraft_kernel::step_export(&[&s.world_state().body("Plate").unwrap().body], "untrim test").unwrap(); + let step = solidcraft_kernel::step_export(&[&s.world_state().unwrap().body("Plate").unwrap().body], "untrim test").unwrap(); let path = std::env::temp_dir().join(format!("solidcraft-untrim-{}.step", std::process::id())); std::fs::write(&path, step).unwrap(); let mut s = Session::default(); run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy()})); let _ = std::fs::remove_file(&path); - let body = s.world_state().bodies.first().unwrap().name.clone(); + let body = s.world_state().unwrap().bodies.first().unwrap().name.clone(); run(&mut s, "surface.untrim", json!({"face": {"body": body, "point": [5, 5, 2]}, "holes": "all", "outer": true, "body_name": "Top"})); assert_eq!(edge_count(&s, "Top"), 4, "the rectangle alone"); assert!((area(&s, "Top") - 800.0).abs() < 1e-9, "{}", area(&s, "Top")); @@ -1275,9 +1299,11 @@ mod tests { /// Extend a cylinder strip: naturally 5 along its axis (10 · π/2 · 25, one face, still a /// cylinder), up to the plane z = 30 (10 · π/2 · 30), and by tangent and curvature run-offs - /// (a second face along a straight edge, 20 long: the tangent one a flat 5 × 20, the - /// curvature one the parabola s ↦ s·R + ½κs²·n with the cylinder's κ = 1/10, its section - /// ∫₀⁵ √(1 + κ²s²) ds long). Undo, redo and reopening; the default saves nothing new. + /// along a straight edge, 20 long: each SMLib's G1 or G2 extension of the surface, so the + /// strip stays one face. The distance is measured across the surface (the run-off's section + /// is 5 long, whatever its curvature) and the strip is its section swept 20 along z, so each + /// run-off adds 5 × 20: 10 · π/2 · 20 + 100 = 414.159265, exact to 1e-6. Areas are SMLib's, + /// integrated on the exact surfaces. Undo, redo and reopening; the default saves nothing new. #[test] fn extend_a_cylinder_strip_every_way() { let pi = std::f64::consts::PI; @@ -1286,8 +1312,8 @@ mod tests { let top = [10.0 * (pi / 4.0).cos(), 10.0 * (pi / 4.0).sin(), 20.0]; run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [top], "distance": "5 mm", "name": "Up"})); let want = 10.0 * pi / 2.0 * 25.0; - assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip")); // (measured on meshes) - assert_eq!(s.world_state().body("Strip").unwrap().body.face_count(), 1); + assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip")); + assert_eq!(s.world_state().unwrap().body("Strip").unwrap().body.face_count(), 1); let saved = s.doc.to_json(); assert!(!saved.contains("\"mode\"") && !saved.contains("\"up_to\"") && !saved.contains("\"neighbours\""), "the default saves as before"); run(&mut s, "edit.undo", json!({})); @@ -1299,18 +1325,15 @@ mod tests { run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [top], "up_to": {"origin": [0, 0, 30], "normal": [0, 0, 1]}})); let want = 10.0 * pi / 2.0 * 30.0; - assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip")); // (measured on meshes) + assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip")); run(&mut s, "edit.undo", json!({})); let side = [0.0, 10.0, 10.0]; - let k: f64 = 0.1; - let parabola = 2.5 * (1.0 + 25.0 * k * k).sqrt() + (5.0 * k).asinh() / (2.0 * k); - for (mode, run_off) in [("tangent", 5.0), ("curvature", parabola)] { + for mode in ["tangent", "curvature"] { run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [side], "distance": 5, "mode": mode})); - let st = s.world_state(); - assert_eq!(st.body("Strip").unwrap().body.face_count(), 2, "{mode}"); - let want = 10.0 * pi / 2.0 * 20.0 + run_off * 20.0; - assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{mode}: {} vs {want}", area(&s, "Strip")); // (measured on meshes) + let want = 10.0 * pi / 2.0 * 20.0 + 5.0 * 20.0; + // SMLib's area, integrated on the exact surface to 1e-8: the run-off is exactly 5 long. + assert!((area(&s, "Strip") - want).abs() < want * 1e-6, "{mode}: {} vs {want}", area(&s, "Strip")); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Strip") - area(&s, "Strip")).abs() < 1e-9, "{mode}"); run(&mut s, "edit.undo", json!({})); @@ -1411,7 +1434,7 @@ mod tests { // (A patch's face is named from geometry; its pieces inherit that, no surer.) let sure = exact(&s, "Floor", 0); run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [5, 5, 0], "with": "Wall", "keep_with": [0, 5, 5], "stitch": true})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Wall").is_none(), "sewn into the floor"); let l = &st.body("Floor").unwrap().body; assert!(l.is_surface()); @@ -1427,15 +1450,15 @@ mod tests { assert!(exact(&s, "Floor", 0) == sure && exact(&s, "Floor", 1) == sure); let saved = s.doc.to_json(); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Wall").is_some() && (area(&s, "Floor") - 200.0).abs() < 1e-9); + assert!(s.world_state().unwrap().body("Wall").is_some() && (area(&s, "Floor") - 200.0).abs() < 1e-9); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); - assert!((area(&cold, "Floor") - 200.0).abs() < 1e-9 && cold.world_state().body("Wall").is_none()); + assert!((area(&cold, "Floor") - 200.0).abs() < 1e-9 && cold.world_state().unwrap().body("Wall").is_none()); // Without stitching, each keeps its half under its own name. run(&mut s, "edit.undo", json!({})); run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [-5, 5, 0], "with": "Wall", "keep_with": [0, 5, -5]})); assert!((area(&s, "Floor") - 100.0).abs() < 1e-9 && (area(&s, "Wall") - 100.0).abs() < 1e-9); - let bb = solidcraft_kernel::measure(&s.world_state().body("Wall").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Wall").unwrap().body).unwrap().bbox; assert!((bb.max.z).abs() < 1e-9, "the wall's lower half: {bb:?}"); } @@ -1452,7 +1475,7 @@ mod tests { let mut asked = mutual.clone(); asked["extend"] = json!(true); run(&mut s, "surface.trim", asked); - let st = s.world_state(); + let st = s.world_state().unwrap(); let l = &st.body("Floor").unwrap().body; assert_eq!((l.face_count(), l.edge_count()), (2, 7)); assert!((area(&s, "Floor") - 200.0).abs() < 1e-6, "{}", area(&s, "Floor")); @@ -1597,7 +1620,7 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.patch", json!({"sketch": "S", "body_name": "Sheet"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Sheet").unwrap().body.is_surface()); run(&mut s, "surface.trim", json!({"body": "Sheet", "plane": {"origin": [3, 0, 0], "normal": [1, 0, 0]}, "keep": [8, 5, 0]})); run(&mut s, "surface.extend", json!({"body": "Sheet", "edges": [[10, 5, 0]], "distance": 5})); @@ -1607,7 +1630,7 @@ mod tests { // Stitch the patch of a box's open top back on. run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "body_name": "Cup"})); run(&mut s, "surface.patch", json!({"edges": [[25, 0, 10], [30, 5, 10], [25, 10, 10], [20, 5, 10]], "body": "Cup", "body_name": "Lid"})); - assert!(s.world_state().body("Lid").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Lid").unwrap().body.is_surface()); // A rim that is not planar: a box with its top cut away by a sideways cylinder. run(&mut s, "solid.box", json!({"length": 28, "width": 28, "height": 20, "corner": [-14, -14, 0], "body_name": "Saddle"})); run( @@ -1618,7 +1641,7 @@ mod tests { let z = |x: f64| 50.0 - (1600.0 - x * x).sqrt(); let rim = json!([[14, 0, z(14.0)], [0, 14, z(0.0)], [-14, 0, z(-14.0)], [0, -14, z(0.0)]]); run(&mut s, "surface.patch", json!({"edges": rim, "body": "Saddle", "body_name": "Cover"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let cover = &st.body("Cover").unwrap().body; assert!(cover.is_surface() && cover.face_count() == 1); // The cover is a smooth surface on the rim, close to the cylinder that cut it (its area @@ -1655,10 +1678,10 @@ mod tests { /// always was. Hostile crowns are refused. #[test] fn patch_crown_fills_a_fitted_patch_and_ignores_a_planar_one() { - let top = |s: &Session| solidcraft_kernel::measure(&s.world_state().body("Cover").unwrap().body).unwrap().bbox.max.z; + let top = |s: &Session| solidcraft_kernel::measure(&s.world_state().unwrap().body("Cover").unwrap().body).unwrap().bbox.max.z; let (plain, reply) = saddle_cover(None); assert_eq!(reply["crown"], json!(0.0), "the crown is reported, 0 by default: {reply}"); - let plain_cover = plain.world_state().body("Cover").unwrap().body.clone(); + let plain_cover = plain.world_state().unwrap().body("Cover").unwrap().body.clone(); // The middle of the loop's box (28 × 28 + 1%, so a 39.9 mm diagonal) rises by crown × 39.9. let (small, reply) = saddle_cover(Some(0.05)); assert_eq!(reply["crown"], json!(0.05), "{reply}"); @@ -1669,7 +1692,7 @@ mod tests { // Crown 0 is the body the default makes, and stitching still closes on the rim (the // crowned patch adds material, so the sealed cup holds more). let (zero, _) = saddle_cover(Some(0.0)); - let zero_area = solidcraft_kernel::measure(&zero.world_state().body("Cover").unwrap().body).unwrap().area; + let zero_area = solidcraft_kernel::measure(&zero.world_state().unwrap().body("Cover").unwrap().body).unwrap().area; assert_eq!(zero_area, solidcraft_kernel::measure(&plain_cover).unwrap().area, "crown 0 is the plain patch"); let sealed = |mut s: Session| { run(&mut s, "surface.stitch", json!({"bodies": ["Saddle", "Cover"], "body_name": "Sealed"})); @@ -1678,7 +1701,7 @@ mod tests { let (sealed_plain, sealed_small, sealed_big) = (sealed(plain), sealed(small), sealed(big)); // The stitch sews the cover onto the cup: one body is left, under the cup's name. let only = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 1, "the cover still meets the rim: {:?}", st.bodies.iter().map(|b| b.name.clone()).collect::>()); st.bodies.first().map(|b| b.name.clone()).unwrap_or_default() }; @@ -1696,7 +1719,7 @@ mod tests { "surface.patch", json!({"edges": [[25, 0, 10], [30, 5, 10], [25, 10, 10], [20, 5, 10]], "body": "Cup", "body_name": "Lid", "crown": 1.0}), ); - let lid = s.world_state().body("Lid").unwrap().body.clone(); + let lid = s.world_state().unwrap().body("Lid").unwrap().body.clone(); let bb = solidcraft_kernel::measure(&lid).unwrap().bbox; assert!((bb.max.z - 10.0).abs() < 1e-9, "a planar rim stays the plane: {bb:?}"); // Hostile crowns. @@ -1737,7 +1760,7 @@ mod tests { s }; let only = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 1, "the blend sews onto both boxes: {:?}", st.bodies.iter().map(|b| b.name.clone()).collect::>()); st.bodies.first().map(|b| b.name.clone()).unwrap_or_default() }; @@ -1753,7 +1776,7 @@ mod tests { // measurable effect in this fixture (the volumes agree to 2e-5 mm³) — the blend's crown // wiring is item 2/4's to check; this item only owns the patch's crown. for (bulge, s, name) in [(0.0, &plain, &plain_name), (0.6, &full, &full_name)] { - let bb = solidcraft_kernel::measure(&s.world_state().body(name).unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body(name).unwrap().body).unwrap().bbox; assert!(bb.min.z.abs() < 1e-9 && (bb.max.z - 15.0).abs() < 1e-9, "the rims stay the boxes' tops at bulge {bulge}: {bb:?}"); } } @@ -1778,12 +1801,12 @@ mod tests { assert_eq!(r["warning"], json!(null), "{r}"); // The flat sheet between the two top faces: 40 x 10, at z = 10. assert!((area(&s, "Bridge") - 400.0).abs() < 1e-6, "{}", area(&s, "Bridge")); - let bb = solidcraft_kernel::measure(&s.world_state().body("Bridge").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Bridge").unwrap().body).unwrap().bbox; assert!((bb.min.z - 10.0).abs() < 1e-9 && (bb.max.z - 10.0).abs() < 1e-9, "{bb:?}"); - assert!(s.world_state().body("Bridge").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Bridge").unwrap().body.is_surface()); // Undo, redo and a cold reopen keep it and its bodies. run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Bridge").is_none()); + assert!(s.world_state().unwrap().body("Bridge").is_none()); run(&mut s, "edit.redo", json!({})); assert!((area(&s, "Bridge") - 400.0).abs() < 1e-6); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); @@ -1794,7 +1817,7 @@ mod tests { sewn["body_name"] = json!("Seam"); let stitched = run(&mut s, "surface.blend", sewn); assert_eq!(stitched["removed_bodies"], json!(["A", "B"]), "{stitched}"); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("A").is_none() && st.body("B").is_none() && st.body("Seam").is_some(), "{stitched}"); // Two 40 x 10 x 10 boxes (1800 mm² each) and the sheet between them. let want = 2.0 * 1800.0 + 400.0; @@ -1830,7 +1853,7 @@ mod tests { let want = 2.0 * std::f64::consts::PI * 100.0; assert!((area(&s, "Neck") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Neck")); let turn = |s: &Session, name: &str| { - let grid = solidcraft_kernel::sample_grid(&s.world_state().body(name).unwrap().body, 17, 5).unwrap(); + let grid = solidcraft_kernel::sample_grid(&s.world_state().unwrap().body(name).unwrap().body, 17, 5).unwrap(); grid.iter() .map(|row| { let (a, b) = (row[0], row[row.len() - 1]); @@ -1876,7 +1899,8 @@ mod tests { fn patch_continuity_and_points_cap_a_tube() { // A coarse mesh is enough to tell the patches apart (measuring a fitted face's area // exactly tessellates it finely). - let mesh = |s: &Session, name: &str| s.world_state().body(name).unwrap().body.tessellate(0.05).unwrap(); + let mesh = + |s: &Session, name: &str| s.world_state().unwrap().body(name).unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap(); let (mut s, rim) = open_tube(); let reply = run(&mut s, "surface.patch", json!({"edges": rim, "body": "Tube", "continuity": "g1", "body_name": "Cap"})); assert_eq!(reply["continuity"], json!({"all": "g1"}), "{reply}"); @@ -1903,7 +1927,7 @@ mod tests { assert!(s.doc.to_json().contains("\"continuity\""), "the continuity is saved"); // Hostile and misplaced values. for (key, v) in [ - ("continuity", json!("g3")), + ("continuity", json!("g5")), ("continuity", json!("smooth")), ("continuity", json!(5)), ("continuity", json!([{"edge": "here", "g": "g1"}])), @@ -1936,30 +1960,39 @@ mod tests { (numbers[0], numbers[1]) } - /// Surface Fair on the fitted B-spline face of an offset sphere: the face is smoothed in - /// place, its edges do not move at all, the reply carries the energy before and after, undo, - /// redo and a cold reopen keep it, and hostile inputs are refused. + /// Surface Fair on the fitted B-spline face of a patch on a rim that is not planar (a box's + /// top cut away by a sideways cylinder): the face is smoothed in place, its edges do not move + /// at all, the reply carries the energy before and after, undo, redo and a cold reopen keep + /// it, and hostile inputs are refused. #[test] fn fairing_a_b_spline_face_keeps_its_edges_and_reports_its_energy() { let mut s = Session::default(); - run(&mut s, "solid.sphere", json!({"radius": 20, "body_name": "Ball"})); - // A sphere is neither a plane nor a cylinder, so its offset is a fitted B-spline face. - run(&mut s, "surface.offset", json!({"faces": [[0, 0, 20]], "body": "Ball", "distance": 2, "body_name": "Shell"})); - let st = s.world_state(); - assert!(st.body("Shell").unwrap().body.is_surface(), "an offset sphere face is a sheet"); - let before: Vec = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect(); + run(&mut s, "solid.box", json!({"length": 28, "width": 28, "height": 20, "corner": [-14, -14, 0], "body_name": "Saddle"})); + run( + &mut s, + "solid.cylinder", + json!({"radius": 40, "height": 120, "base": [0, -60, 50], "axis": "Y", "operation": "cut", "targets": ["Saddle"]}), + ); + let z = |x: f64| 50.0 - (1600.0 - x * x).sqrt(); + let rim = json!([[14, 0, z(14.0)], [0, 14, z(0.0)], [-14, 0, z(-14.0)], [0, -14, z(0.0)]]); + // The rim is not planar, so its patch is a fitted B-spline face. + run(&mut s, "surface.patch", json!({"edges": rim, "body": "Saddle", "body_name": "Shell"})); + let st = s.world_state().unwrap(); + assert!(st.body("Shell").unwrap().body.is_surface(), "a patch on a rim is a sheet"); + let before: Vec = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect(); assert!(!before.is_empty()); let area_before = area(&s, "Shell"); - // The fairing reports both energies, the second no larger than the first. + // The fairing reports both energies. The fit is not the fairest surface on its own rim, so + // the energy falls strictly and the face moves: its area changes. let reply = run(&mut s, "surface.fair", json!({"body": "Shell", "tolerance": 1.0, "iterations": 3})); let (energy_before, energy_after) = energies(&reply); let area_after = area(&s, "Shell"); - eprintln!("surface.fair: {reply}\nenergies {energy_before:e} → {energy_after:e}, area {area_before} → {area_after}"); - assert!(energy_before > 0.0 && energy_after <= energy_before, "{energy_before:e} → {energy_after:e}"); - // The face moved (the fit is not the flattest surface on its own rim), but not its edges: - // every boundary point of the body is where it was, bit for bit. - assert!((area_after - area_before).abs() > 0.0 || energy_after < energy_before); - let after: Vec = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect(); + assert!(energy_before > 0.0 && energy_after < energy_before, "{energy_before:e} → {energy_after:e}"); + assert_ne!(area_after, area_before, "the fairing did not move the face"); + // The edges do not move: every boundary point of the faired body is where it was, bit for + // bit, and the sheet is still the one face. + let st = s.world_state().unwrap(); + let after: Vec = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect(); assert_eq!(after, before, "fairing must not move the face's edges"); assert_eq!(st.body("Shell").unwrap().body.face_count(), 1); // Undo takes the fairing back, redo puts it back, and a cold reopen rebuilds the same. @@ -2005,7 +2038,7 @@ mod tests { "body_name": "Blend" }), ); - let body = s.world_state().body("Blend").unwrap().body.clone(); + let body = s.world_state().unwrap().body("Blend").unwrap().body.clone(); // A fine grid in the run direction: the seams sit at u = 0, 1/2 and 1, and the first step // off each one is the tangent there (a thousandth of the run, so it is the tangent). let grid = solidcraft_kernel::sample_grid(&body, 1001, 9).unwrap(); diff --git a/crates/engine/src/cmd/surface_analysis.rs b/crates/engine/src/cmd/surface_analysis.rs index cc73d98f3..2876808f1 100644 --- a/crates/engine/src/cmd/surface_analysis.rs +++ b/crates/engine/src/cmd/surface_analysis.rs @@ -1,70 +1,189 @@ //! Surface analyses: zebra stripes, draft angle and curvature map shading of the model's faces. -//! View state only: no geometry changes and no undo step. +//! View state only: no geometry changes and no undo step. The view analyses (these shadings, +//! continuity seams, isocurves and curvature combs) are one group: one at a time is on, and +//! `inspect.analysis` says which or turns it off. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::CommandSpec; use crate::params::{bad, bool_, num, str_, vec3}; +use crate::schema::{TypedContract, output_schema_for, surface_analysis as contract}; use crate::{ContinuitySeam, Result, Session, SurfaceAnalysis, kernel}; -/// Stations along each edge when the call does not say (`samples`). -const DEFAULT_SAMPLES: usize = 33; -/// Tolerances a seam is judged against when the call does not say: a micron of position gap, a -/// degree of normal angle, and a curvature jump of 1/100 mm. -const DEFAULT_GAP_MM: f64 = 1e-3; -const DEFAULT_ANGLE_DEG: f64 = 1.0; -const DEFAULT_CURVATURE_PER_MM: f64 = 0.01; +const ZEBRA: TypedContract = TypedContract::new(); +const DRAFT: TypedContract = TypedContract::new(); +const ENVIRONMENT: TypedContract = TypedContract::new(); +const ACCESSIBILITY: TypedContract = TypedContract::new(); +const CURVATURE: TypedContract = TypedContract::new(); +const CONTINUITY: TypedContract = TypedContract::new(); /// Most edges one call may pick, and most bodies one call may analyse at once. const MAX_PICKS: usize = 512; const MAX_BODIES: usize = 64; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("inspect.zebra", "Zebra Analysis", zebra) + CommandSpec::new("inspect.zebra", "Zebra Analysis", crate::checked!("inspect.zebra", zebra)) + .contract(&ZEBRA) + .output(output_schema_for::) .at("SKETCH", "INSPECT") .icon("zebra") .noundo() .params("stripes?: number across the view (default 12); clear?: true turns the analysis off"), - CommandSpec::new("inspect.draft", "Draft Analysis", draft) + CommandSpec::new("inspect.draft", "Draft Analysis", crate::checked!("inspect.draft", draft)) + .contract(&DRAFT) + .output(output_schema_for::) .at("SKETCH", "INSPECT") .icon("draft_analysis") .noundo() .params("pull?: [x,y,z] direction (default Z); angle?: degrees (default 1); clear?: true turns the analysis off"), - CommandSpec::new("inspect.environment_map", "Environment Map Analysis", |s, p| set(s, p, SurfaceAnalysis::Environment)) + CommandSpec::new("inspect.environment_map", "Environment Map Analysis", crate::checked!("inspect.environment_map", environment)) + .contract(&ENVIRONMENT) + .output(output_schema_for::) .at("SKETCH", "INSPECT") .icon("environment_map") .noundo() .params("clear?: true turns the analysis off"), - CommandSpec::new("inspect.accessibility", "Accessibility Analysis", accessibility) + CommandSpec::new("inspect.accessibility", "Accessibility Analysis", crate::checked!("inspect.accessibility", accessibility)) + .contract(&ACCESSIBILITY) + .output(output_schema_for::) .at("SKETCH", "INSPECT") .icon("accessibility") .noundo() .params("direction?: [x,y,z] the tool comes from (default Z, from above); clear?: true turns the analysis off"), - CommandSpec::new("inspect.curvature_map", "Curvature Map Analysis", curvature_map) + CommandSpec::new("inspect.curvature_map", "Curvature Map Analysis", crate::checked!("inspect.curvature_map", curvature_map)) + .contract(&CURVATURE) + .output(output_schema_for::) .at("SKETCH", "INSPECT") .icon("curvature_map") .noundo() .params("radius?: mm shown red (default: a tenth of the model's size); clear?: true turns the analysis off"), - CommandSpec::new("inspect.continuity", "Continuity Analysis", continuity).at("SURFACE", "INSPECT").icon("continuity").noundo().params( - "body?: name (default: the visible bodies); edges?: [x,y,z] points or {\"index\": i} (default: every edge of the body; \ + CommandSpec::new("inspect.analysis", "View Analysis", crate::checked!("inspect.analysis", analysis)) + .icon("zebra") + .noundo() + .doc_only() + .contract(&ANALYSIS_CONTRACT) + .output(crate::schema::output_schema_for::) + .params( + "off?: true turns the view analysis on now off. → active: the command id of the view analysis on (inspect.zebra, \ + inspect.draft, inspect.curvature_map, inspect.environment_map, inspect.accessibility, inspect.continuity, \ + inspect.isocurve or inspect.curvature_comb), or null. One is on at a time: turning one on turns the one on before \ + off. Read-only without `off`", + ), + CommandSpec::new("inspect.continuity", "Continuity Analysis", crate::checked!("inspect.continuity", continuity)) + .contract(&CONTINUITY) + .output(output_schema_for::) + .at("SURFACE", "INSPECT") + .icon("continuity") + .noundo() + .params( + "body?: name (default: the visible bodies); edges?: [x,y,z] points or {\"index\": i} (default: every edge of the body; \ a pick must match one body); samples?: 3…257 stations along each edge, ends included (default 33); \ - gap_tolerance_mm? (default 0.001), angle_tolerance_deg? (default 1), curvature_tolerance_per_mm? (default 0.01); \ + gap_tolerance_mm? (default 0.001), angle_tolerance_deg? (default 1), curvature_tolerance_per_mm? (default 0.01), \ + curvature_change_tolerance_per_mm2? (default 0.001), curvature_change_rate_tolerance_per_mm3? (default 0.0001); \ add?: true keeps the seams already shaded and adds these (measuring an edge again replaces it); \ - clear?: true turns the analysis off. → each edge's worst gap (G0), normal angle (G1) and curvature jump (G2) as \ - {value, at: [x,y,z], edge_fraction}, its verdict (smooth, curvature_jump, sharp or gap) and a summary; \ - the seams are shaded in the viewport", - ), + clear?: true turns the analysis off. → each edge's worst gap (G0), normal angle (G1), curvature jump (G2), \ + jump of the curvature's change across the seam dκ/ds (G3) and of that change's rate d²κ/ds² (G4), from the \ + faces' exact derivatives, as {value, at: [x,y,z], edge_fraction}; its order (g0…g4: the highest every station \ + meets within the tolerances, null where the faces do not meet), its verdict (smooth: g2 or better, \ + curvature_jump, sharp or gap) and a summary; the seams are shaded in the viewport", + ), ]; +const ANALYSIS_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +/// The view analyses, by the command that turns each on: the shadings, the continuity seams, the +/// isocurves and the curvature combs. One at a time is on. +impl Session { + /// The view analysis on now, by its command id, or `None`. + pub fn active_analysis(&self) -> Option<&'static str> { + if let Some(a) = self.analysis { + Some(a.command()) + } else if self.comb.is_some() { + Some("inspect.curvature_comb") + } else if !self.isocurves.is_empty() { + Some("inspect.isocurve") + } else if !self.continuity.is_empty() { + Some("inspect.continuity") + } else { + None + } + } + + /// Turn every view analysis off but the one command `keep` turns on (`None`: all of them). + /// Turning one on leaves the others on while the preference to show several is set + /// ([`Session::single_surface_analysis`]). + pub fn analyses_off(&mut self, keep: Option<&str>) { + if keep.is_some() && !self.single_surface_analysis() { + return; + } + if self.analysis.is_some_and(|a| Some(a.command()) != keep) { + self.analysis = None; + } + if keep != Some("inspect.curvature_comb") { + self.comb = None; + } + if keep != Some("inspect.isocurve") { + self.isocurves.clear(); + } + if keep != Some("inspect.continuity") { + self.continuity.clear(); + } + self.status_analysis_changed(None); + // Only what is shown: an open feature editor stays valid (#10687). + self.refresh_display(); + } +} + +impl SurfaceAnalysis { + /// The command that turns this analysis on. + pub fn command(self) -> &'static str { + match self { + SurfaceAnalysis::Zebra { .. } => "inspect.zebra", + SurfaceAnalysis::Draft { .. } => "inspect.draft", + SurfaceAnalysis::Curvature { .. } => "inspect.curvature_map", + SurfaceAnalysis::Environment => "inspect.environment_map", + SurfaceAnalysis::Access { .. } => "inspect.accessibility", + } + } +} + +/// `inspect.analysis`: which view analysis is on, and `off` turns it off. +fn analysis(s: &mut Session, p: &Value) -> Result { + let off = match p.get("off") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad("inspect.analysis", "`off` must be true or false")), + }; + if off { + s.analyses_off(None); + } + Ok(json!({"active": s.active_analysis()})) +} + +fn environment(s: &mut Session, p: &Value) -> Result { + set(s, p, SurfaceAnalysis::Environment) +} + fn set(s: &mut Session, p: &Value, a: SurfaceAnalysis) -> Result { if bool_(p, "clear").unwrap_or(false) { s.analysis = None; } else { + // In this order: a replaced analysis keeps its status slot. s.analysis = Some(a); + s.analyses_off(Some(a.command())); } s.status_analysis_changed((!bool_(p, "clear").unwrap_or(false)).then_some(crate::status_items::StatusId::SurfaceAnalysis)); - s.revision += 1; - Ok(json!({ "analysis": s.analysis })) + s.refresh_display(); + let vector = |v: Vec3| [v.x, v.y, v.z]; + let analysis = s.analysis.map(|a| match a { + SurfaceAnalysis::Zebra { stripes } => contract::Analysis::Zebra { stripes }, + SurfaceAnalysis::Draft { pull, angle } => contract::Analysis::Draft { pull: vector(pull), angle }, + SurfaceAnalysis::Curvature { radius } => contract::Analysis::Curvature { radius }, + SurfaceAnalysis::Environment => contract::Analysis::Environment, + SurfaceAnalysis::Access { dir } => contract::Analysis::Access { dir: vector(dir) }, + }); + serde_json::to_value(contract::AnalysisResult { analysis, param_warnings: Vec::new() }).map_err(|e| bad("surface analysis", e.to_string())) } fn zebra(s: &mut Session, p: &Value) -> Result { @@ -119,23 +238,31 @@ fn continuity(s: &mut Session, p: &Value) -> Result { if bool_(p, "clear").unwrap_or(false) { s.continuity.clear(); s.status_analysis_changed(None); - s.revision += 1; - return Ok(json!({ "analysis": "continuity", "cleared": true })); + s.refresh_display(); + return serde_json::to_value(contract::ContinuityResult::Cleared { + analysis: "continuity".into(), + cleared: true, + param_warnings: Vec::new(), + }) + .map_err(|e| bad(cmd, e.to_string())); } let samples = match p.get("samples") { - None => DEFAULT_SAMPLES, + None => kernel::DEFAULT_SAMPLES, Some(v) => match v.as_f64().filter(|n| n.is_finite() && n.fract() == 0.0 && (3.0..=257.0).contains(n)) { Some(n) => n as usize, None => return Err(bad(cmd, "`samples` must be 3…257 stations along each edge")), }, }; + let default = kernel::ContinuityTolerances::default(); let tolerances = kernel::ContinuityTolerances { - gap_mm: tolerance(p, "gap_tolerance_mm", DEFAULT_GAP_MM)?, - angle_deg: tolerance(p, "angle_tolerance_deg", DEFAULT_ANGLE_DEG)?, - curvature_per_mm: tolerance(p, "curvature_tolerance_per_mm", DEFAULT_CURVATURE_PER_MM)?, + gap_mm: tolerance(p, "gap_tolerance_mm", default.gap_mm)?, + angle_deg: tolerance(p, "angle_tolerance_deg", default.angle_deg)?, + curvature_per_mm: tolerance(p, "curvature_tolerance_per_mm", default.curvature_per_mm)?, + curvature_change_per_mm2: tolerance(p, "curvature_change_tolerance_per_mm2", default.curvature_change_per_mm2)?, + curvature_change_rate_per_mm3: tolerance(p, "curvature_change_rate_tolerance_per_mm3", default.curvature_change_rate_per_mm3)?, }; let picks = edge_picks(p)?; - let st = s.world_state(); + let st = s.world_state()?; let named = str_(p, "body"); let candidates: Vec<&solidcraft_doc::ModelBody> = match named { Some(name) => vec![st.body(name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?], @@ -179,26 +306,54 @@ fn continuity(s: &mut Session, p: &Value) -> Result { let report = kernel::seam_diagnostics(&body.body, edges, samples, tolerances)?; let mut rows = Vec::new(); for seam in &report.seams { - summary.count(seam.verdict); - seams.push(ContinuitySeam { body: body.name.clone(), edge: seam.edge, points: seam.points.clone(), verdict: seam.verdict }); - rows.push(json!({ - "edge": seam.edge, - "length_mm": seam.length, - "samples": seam.samples, - "gap_mm": seam.gap_mm, - "normal_angle_deg": seam.normal_angle_deg, - "curvature_jump_per_mm": seam.curvature_jump_per_mm, - "verdict": seam.verdict, - })); + summary.count(seam.verdict, seam.order); + seams.push(ContinuitySeam { + body: body.name.clone(), + edge: seam.edge, + points: seam.points.clone(), + verdict: seam.verdict, + order: seam.order, + details: crate::status_details::ContinuityDetail { + body: body.name.clone(), + edge: seam.edge, + samples: seam.samples, + gap_tolerance_mm: tolerances.gap_mm, + angle_tolerance_deg: tolerances.angle_deg, + curvature_tolerance_per_mm: tolerances.curvature_per_mm, + gap_mm: seam.gap_mm.value, + normal_angle_deg: seam.normal_angle_deg.value, + curvature_jump_per_mm: seam.curvature_jump_per_mm.value, + length_mm: seam.length, + verdict: seam.verdict.into(), + gap_at: [seam.gap_mm.at.x, seam.gap_mm.at.y, seam.gap_mm.at.z], + gap_fraction: seam.gap_mm.edge_fraction, + normal_angle_at: [seam.normal_angle_deg.at.x, seam.normal_angle_deg.at.y, seam.normal_angle_deg.at.z], + normal_angle_fraction: seam.normal_angle_deg.edge_fraction, + curvature_jump_at: [seam.curvature_jump_per_mm.at.x, seam.curvature_jump_per_mm.at.y, seam.curvature_jump_per_mm.at.z], + curvature_jump_fraction: seam.curvature_jump_per_mm.edge_fraction, + skipped: report.skipped, + unmeasured: report.unmeasured, + current: true, + geometry_key: body.geometry_key(), + feature: body.feature, + }, + }); + rows.push(contract::EdgeReport { + edge: seam.edge, + length_mm: seam.length, + samples: seam.samples, + gap_mm: metric(seam.gap_mm), + normal_angle_deg: metric(seam.normal_angle_deg), + curvature_jump_per_mm: metric(seam.curvature_jump_per_mm), + curvature_change_jump_per_mm2: metric(seam.curvature_change_jump_per_mm2), + curvature_change_rate_jump_per_mm3: metric(seam.curvature_change_rate_jump_per_mm3), + order: seam.order.map(|g| g.as_str().to_string()), + verdict: verdict(seam.verdict), + }); } summary.skipped += report.skipped; summary.unmeasured += report.unmeasured; - bodies.push(json!({ - "body": body.name, - "edges": rows, - "skipped": report.skipped, - "unmeasured": report.unmeasured, - })); + bodies.push(contract::BodyReport { body: body.name.clone(), edges: rows, skipped: report.skipped, unmeasured: report.unmeasured }); } if bool_(p, "add").unwrap_or(false) { // The seams shown stay; an edge measured again takes its new reading. @@ -207,28 +362,48 @@ fn continuity(s: &mut Session, p: &Value) -> Result { } else { s.continuity = seams; } + if !s.continuity.is_empty() { + s.analyses_off(Some("inspect.continuity")); + } s.status_analysis_changed(Some(crate::status_items::StatusId::Continuity)); - s.revision += 1; - Ok(json!({ - "analysis": "continuity", - "samples": samples, - "tolerances": { - "gap_mm": tolerances.gap_mm, - "angle_deg": tolerances.angle_deg, - "curvature_per_mm": tolerances.curvature_per_mm, + s.refresh_display(); + serde_json::to_value(contract::ContinuityResult::Measured { + analysis: "continuity".into(), + samples, + tolerances: contract::Tolerances { + gap_mm: tolerances.gap_mm, + angle_deg: tolerances.angle_deg, + curvature_per_mm: tolerances.curvature_per_mm, + curvature_change_per_mm2: tolerances.curvature_change_per_mm2, + curvature_change_rate_per_mm3: tolerances.curvature_change_rate_per_mm3, }, - "bodies": bodies, - "summary": { - "edges": summary.edges, - "smooth": summary.smooth, - "curvature_jump": summary.curvature_jump, - "sharp": summary.sharp, - "gap": summary.gap, - "skipped": summary.skipped, - "unmeasured": summary.unmeasured, - "worst": summary.worst(), + bodies, + summary: contract::Summary { + edges: summary.edges, + smooth: summary.smooth, + curvature_jump: summary.curvature_jump, + sharp: summary.sharp, + gap: summary.gap, + skipped: summary.skipped, + unmeasured: summary.unmeasured, + orders: summary.orders(), + worst: summary.worst().map(verdict), }, - })) + param_warnings: Vec::new(), + }) + .map_err(|e| bad(cmd, e.to_string())) +} + +fn verdict(value: kernel::SeamVerdict) -> contract::Verdict { + match value { + kernel::SeamVerdict::Smooth => contract::Verdict::Smooth, + kernel::SeamVerdict::CurvatureJump => contract::Verdict::CurvatureJump, + kernel::SeamVerdict::Sharp => contract::Verdict::Sharp, + kernel::SeamVerdict::Gap => contract::Verdict::Gap, + } +} +fn metric(value: kernel::SeamWorst) -> contract::Metric { + contract::Metric { value: value.value, at: [value.at.x, value.at.y, value.at.z], edge_fraction: value.edge_fraction } } /// A tolerance parameter. A value that is given but unusable (NaN, infinity, negative, a @@ -277,11 +452,16 @@ struct Summary { gap: usize, skipped: usize, unmeasured: usize, + /// Seams by the highest order they meet, indexed by [`kernel::Continuity::order`]. + by_order: [usize; 5], } impl Summary { - fn count(&mut self, verdict: kernel::SeamVerdict) { + fn count(&mut self, verdict: kernel::SeamVerdict, order: Option) { self.edges += 1; + if let Some(slot) = order.and_then(|g| self.by_order.get_mut(g.order())) { + *slot += 1; + } match verdict { kernel::SeamVerdict::Smooth => self.smooth += 1, kernel::SeamVerdict::CurvatureJump => self.curvature_jump += 1, @@ -290,6 +470,11 @@ impl Summary { } } + /// How many seams meet each order at best, by its word (`g0` … `g4`). + fn orders(&self) -> serde_json::Map { + kernel::Continuity::ALL.into_iter().zip(self.by_order).map(|(g, n)| (g.as_str().to_string(), json!(n))).collect() + } + /// The worst verdict over the edges measured (`None` when there was nothing to measure). /// [`kernel::SeamVerdict`] runs from the best continuity to the worst. fn worst(&self) -> Option { @@ -682,6 +867,59 @@ mod tests { assert!(s.status_order.is_empty(), "new design resets transient chronology"); } + #[test] + fn continuity_details_never_validate_old_matching_geometry_during_a_live_drag() { + use std::sync::Arc; + let mut s = Session::default(); + for (command, params) in [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.rectangle.two_point", json!({"p0":[5,5],"p1":[25,20]})), + ("sketch.dimension", json!({"entities":["l1"],"value":20})), + ("sketch.dimension", json!({"entities":["l2"],"value":15})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance":5})), + ("inspect.continuity", json!({"samples":5})), + ("sketch.edit", json!({"sketch":"Sketch1"})), + ] { + s.execute(command, ¶ms).unwrap(); + } + let records = s.continuity.clone(); + assert!(!records.is_empty()); + assert!(s.continuity_details().iter().all(|row| row.current)); + let before_drag = s.model.state(); + s.execute("sketch.drag", &json!({"entity":"l1.start","from":[5,5],"to":[4,5],"live":true})).unwrap(); + assert!(s.model.is_stale()); + // The live solver replaces ModelState to show the moved sketch, while retaining + // its old downstream B-rep body. That body/key, not the whole container Arc, + // is the misleading geometry the pure descriptor must refuse. + let retained_model = s.model.state(); + assert!(before_drag.body(&records[0].body).unwrap().body.same_shape(&retained_model.body(&records[0].body).unwrap().body)); + assert_eq!( + retained_model.body(&records[0].body).unwrap().geometry_key(), + records[0].details.geometry_key, + "this real pending edit retains exactly the misleading old matching geometry key" + ); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.is_dirty(), s.evaluations, s.status_order.clone()); + for _ in 0..3 { + let reply = s.execute("view.status_details", &json!({})).unwrap(); + assert!(reply["continuity"].as_array().unwrap().iter().all(|row| row["current"] == false)); + assert!(s.continuity_target_points(&records[0].body, records[0].edge).is_none()); + } + assert!(s.model.is_stale()); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert!(Arc::ptr_eq(&retained_model, &s.model.state())); + assert_eq!(s.continuity, records, "query does not clean or fabricate measurements"); + assert_eq!((s.revision, s.undo.len(), s.redo.len(), s.is_dirty(), s.evaluations, s.status_order.clone()), before); + s.execute("sketch.drag_end", &json!({})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("inspect.continuity", &json!({"samples":5})).unwrap(); + assert!(!s.model.is_stale()); + assert!(s.continuity_details().iter().all(|row| row.current)); + let fresh = &s.continuity[0]; + assert!(s.continuity_target_points(&fresh.body, fresh.edge).is_some(), "normal fresh evaluation/measurement restores valid targets"); + } + /// The edges of the first body of a continuity reply. fn edges(v: &Value) -> &Vec { v["bodies"][0]["edges"].as_array().unwrap_or_else(|| panic!("no edges in {v}")) @@ -706,7 +944,7 @@ mod tests { s.execute("inspect.environment_map", &json!({})).unwrap(); assert_eq!(s.analysis, Some(SurfaceAnalysis::Environment)); s.execute("inspect.accessibility", &json!({"direction": [0, 0, -3]})).unwrap(); - assert_eq!(s.analysis, Some(SurfaceAnalysis::Access { dir: solidcraft_geom::Vec3::new(0.0, 0.0, -1.0) })); + assert_eq!(s.analysis, Some(SurfaceAnalysis::Access { dir: solidcore_record::Vec3::new(0.0, 0.0, -1.0) })); s.execute("inspect.curvature_map", &json!({"clear": true})).unwrap(); assert_eq!(s.analysis, None); assert_eq!(s.undo.len(), undo, "no undo steps"); @@ -731,6 +969,7 @@ mod tests { assert!((angle - 90.0).abs() < 1e-9, "angle {angle} in {e}"); assert!(jump < 1e-9, "curvature jump {jump} in {e}"); assert_eq!(e["verdict"], json!("sharp"), "{e}"); + assert_eq!(e["order"], json!("g0"), "{e}"); assert_eq!(e["samples"], json!(33), "{e}"); assert!((e["length_mm"].as_f64().unwrap() - 20.0).abs() < 1e-9, "{e}"); assert_eq!(e["normal_angle_deg"]["at"].as_array().map(Vec::len), Some(3), "{e}"); @@ -739,7 +978,11 @@ mod tests { } assert_eq!(v["analysis"], json!("continuity")); assert_eq!(v["samples"], json!(33)); - assert_eq!(v["tolerances"], json!({"gap_mm": 1e-3, "angle_deg": 1.0, "curvature_per_mm": 0.01})); + assert_eq!( + v["tolerances"], + json!({"gap_mm": 1e-3, "angle_deg": 1.0, "curvature_per_mm": 0.01, "curvature_change_per_mm2": 1e-3, "curvature_change_rate_per_mm3": 1e-4}) + ); + assert_eq!(v["summary"]["orders"], json!({"g0": 12, "g1": 0, "g2": 0, "g3": 0, "g4": 0})); assert_eq!(v["summary"]["edges"], json!(12)); assert_eq!(v["summary"]["sharp"], json!(12)); assert_eq!(v["summary"]["worst"], json!("sharp")); @@ -764,7 +1007,12 @@ mod tests { let jump = e["curvature_jump_per_mm"]["value"].as_f64().unwrap(); assert!((jump - 0.25).abs() < 1e-6, "1 / radius 4: {e}"); assert_eq!(e["verdict"], json!("curvature_jump"), "{e}"); + assert_eq!(e["order"], json!("g1"), "a plane tangent to a cylinder is G1, not G2: {e}"); + assert!(e["curvature_change_jump_per_mm2"]["value"].as_f64().unwrap() < 1e-9, "{e}"); + assert!(e["curvature_change_rate_jump_per_mm3"]["value"].as_f64().unwrap() < 1e-9, "{e}"); } + assert_eq!(v["summary"]["orders"]["g1"], json!(2)); + assert_eq!(s.continuity.iter().filter(|seam| seam.order == Some(crate::kernel::Continuity::G1)).count(), 2); assert_eq!(v["summary"]["curvature_jump"], json!(2)); assert_eq!(v["summary"]["sharp"], json!(13)); assert_eq!(v["summary"]["smooth"], json!(0)); @@ -827,6 +1075,112 @@ mod tests { } /// Hostile parameters are refused with an error, never a panic. + #[test] + fn continuity_details_keep_successful_per_record_settings_and_query_is_pure() { + let mut s = Session::default(); + boxed(&mut s, 10.0); + let first = s + .execute( + "inspect.continuity", + &json!({"edges":[[5,0,0]],"samples":5,"gap_tolerance_mm":0.002,"angle_tolerance_deg":2,"curvature_tolerance_per_mm":0.03}), + ) + .unwrap(); + let old = s.continuity[0].clone(); + s.execute( + "inspect.continuity", + &json!({"edges":[[0,5,0]],"samples":9,"gap_tolerance_mm":0.007,"angle_tolerance_deg":4,"curvature_tolerance_per_mm":0.06,"add":true}), + ) + .unwrap(); + let rows = s.continuity_details(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].samples, 5); + assert_eq!(rows[0].gap_tolerance_mm, 0.002); + assert_eq!(rows[1].samples, 9); + assert_eq!(rows[1].angle_tolerance_deg, 4.0); + assert!(rows.iter().all(|row| row.current)); + assert_eq!(rows[0].gap_mm, first["bodies"][0]["edges"][0]["gap_mm"]["value"].as_f64().unwrap()); + assert_eq!(rows[0].gap_at, serde_json::from_value::<[f64; 3]>(first["bodies"][0]["edges"][0]["gap_mm"]["at"].clone()).unwrap()); + let before = (s.revision, s.doc.to_json(), s.undo.len(), s.status_activation.clone(), s.continuity.clone(), s.is_dirty()); + for _ in 0..3 { + let query = s.execute("view.status_details", &json!({})).unwrap(); + assert_eq!(query["continuity"][0]["samples"], 5); + assert_eq!(query["continuity"][1]["samples"], 9); + } + assert_eq!((s.revision, s.doc.to_json(), s.undo.len(), s.status_activation.clone(), s.continuity.clone(), s.is_dirty()), before); + assert!(s.execute("view.status_details", &json!({"extra":true})).is_err()); + assert!(s.execute("inspect.continuity", &json!({"body":old.body,"edges":[{"index":old.edge}],"samples":2,"add":true})).is_err()); + assert_eq!(s.continuity, before.4, "failed live update is atomic across mixed settings"); + s.execute("inspect.continuity",&json!({"body":old.body,"edges":[{"index":old.edge}],"samples":7,"gap_tolerance_mm":old.details.gap_tolerance_mm,"angle_tolerance_deg":old.details.angle_tolerance_deg,"curvature_tolerance_per_mm":old.details.curvature_tolerance_per_mm,"add":true})).unwrap(); + let remaining = s.continuity.iter().find(|row| row.edge != old.edge).unwrap(); + assert_eq!(remaining.details, rows[1]); + assert_eq!(s.continuity.iter().find(|row| row.edge == old.edge).unwrap().details.samples, 7); + } + + #[test] + fn continuity_targets_follow_geometry_identity_rather_than_view_revision() { + let mut s = Session::default(); + boxed(&mut s, 10.0); + s.execute("inspect.continuity", &json!({"edges":[[5,0,0]],"samples":5})).unwrap(); + let seam = s.continuity[0].clone(); + let revision = s.revision; + s.execute("view.apply", &json!({"camera":{"target":[1,2,3],"yaw":0,"pitch":0,"distance":40}})).unwrap(); + assert_eq!(s.camera.unwrap().target, solidcore_record::Vec3::new(1.0, 2.0, 3.0)); + // Camera apply is an echo; these real display changes advance Session's view revision. + s.execute("browser.visibility", &json!({"items":[seam.body],"visible":false})).unwrap(); + s.execute("browser.visibility", &json!({"items":[seam.body],"visible":true})).unwrap(); + assert!(s.revision > revision); + assert!(s.continuity_target_points(&seam.body, seam.edge).is_some()); + s.execute("body.rename", &json!({"body":seam.body,"name":"Renamed"})).unwrap(); + assert!(!s.continuity_details()[0].current); + assert!(s.continuity_target_points(&seam.body, seam.edge).is_none()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.continuity_details()[0].current, "restored matching geometry may be targeted again"); + let feature = s.doc.features[0].id; + s.execute("timeline.redefine", &json!({"feature":feature,"command":"solid.box","params":{"length":20,"width":10,"height":10}})).unwrap(); + assert!(!s.continuity_details()[0].current); + assert!(s.continuity_target_points(&seam.body, seam.edge).is_none()); + s.execute("edit.undo", &json!({})).unwrap(); + let restored_key = s.model.state().body(&seam.body).unwrap().geometry_key(); + assert_ne!( + restored_key, seam.details.geometry_key, + "feature redefinition undo produces a new evaluated generation, despite restoring dimensions" + ); + assert!(!s.continuity_details()[0].current); + assert!(s.continuity_target_points(&seam.body, seam.edge).is_none()); + s.execute("inspect.continuity",&json!({"body":seam.body,"edges":[{"index":seam.edge}],"samples":seam.details.samples, + "gap_tolerance_mm":seam.details.gap_tolerance_mm,"angle_tolerance_deg":seam.details.angle_tolerance_deg,"curvature_tolerance_per_mm":seam.details.curvature_tolerance_per_mm})).unwrap(); + assert!(s.continuity_details()[0].current, "a real fresh report validates the restored geometry generation"); + assert!(s.continuity_target_points(&seam.body, seam.edge).is_some()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!s.continuity_details()[0].current); + s.execute("inspect.continuity", &json!({"clear":true})).unwrap(); + assert!(s.continuity_details().is_empty()); + } + + #[test] + fn continuity_details_reject_changed_occurrence_placement_without_query_evaluation() { + let mut s = Session::default(); + let component = s.execute("component.create", &json!({"name":"Part","grounded":false})).unwrap(); + let occurrence = component["occurrence"].as_u64().unwrap(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"PartBody"})).unwrap(); + s.execute("component.activate", &json!({"component":0})).unwrap(); + s.execute("inspect.continuity", &json!({"body":"PartBody","edges":[[5,0,0]],"samples":5})).unwrap(); + let record = s.continuity[0].clone(); + assert!(s.continuity_details()[0].current); + s.execute("occurrence.move", &json!({"occurrence":occurrence,"translate":[0,20,0],"capture":false})).unwrap(); + assert!(s.pending_moves.contains_key(&occurrence), "this test intentionally exercises a pending, revertible placement"); + let revision = s.revision; + assert!(!s.continuity_details()[0].current); + assert_eq!(s.revision, revision, "descriptor does not prepare a stale world or mutate it"); + let _placed = s.world_state().unwrap(); + assert!(!s.continuity_details()[0].current, "a warmed moved occurrence is still different geometry placement"); + assert!(s.continuity_target_points(&record.body, record.edge).is_none()); + s.execute("component.revert_position", &json!({"occurrences":[occurrence]})).unwrap(); + assert!(!s.pending_moves.contains_key(&occurrence)); + let _restored = s.world_state().unwrap(); + assert!(s.continuity_details()[0].current, "matching restored placement is validated by real geometry identity"); + } + #[test] fn hostile_continuity_params_are_refused() { let mut s = Session::default(); @@ -842,6 +1196,8 @@ mod tests { json!({"gap_tolerance_mm": 1e12}), json!({"angle_tolerance_deg": f64::NAN}), json!({"curvature_tolerance_per_mm": "tight"}), + json!({"curvature_change_tolerance_per_mm2": -0.5}), + json!({"curvature_change_rate_tolerance_per_mm3": null}), json!({"edges": 3}), json!({"edges": [[1, 2]]}), json!({"edges": [[]]}), diff --git a/crates/engine/src/cmd/surface_boundary.rs b/crates/engine/src/cmd/surface_boundary.rs index df909f1ae..572e3e74b 100644 --- a/crates/engine/src/cmd/surface_boundary.rs +++ b/crates/engine/src/cmd/surface_boundary.rs @@ -6,29 +6,29 @@ use serde_json::Value; use solidcraft_doc::{BodyName, FeatureKind, NetworkCurve, Operation, Position, SketchId}; -use solidcraft_kernel::Continuity; +use solidcraft_geom::prelude::*; +use solidcraft_kernel::{Construction, Continuity}; use super::CommandSpec; use super::features::{add_feature, feature_sketch, sketch_id}; use crate::params::{bad, str_, string_list, vec3}; +use crate::schema::features::FeatureResult; +use crate::schema::surface_boundary::{BoundaryParams, MAX_NETWORK_CURVES, MAX_SAMPLES, MIN_SAMPLES}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; /// The stations a boundary carries by default (the patch's resolution along the loop). const DEFAULT_SAMPLES: usize = solidcraft_doc::BOUNDARY_SAMPLES; -/// The fewest stations a patch can hold the widest continuity pair with: a G3 side needs four rows -/// at each of two opposite sides, so eight. -const MIN_SAMPLES: usize = 8; -/// The most stations a boundary may carry (the kernel's own cap). -const MAX_SAMPLES: usize = 512; -/// The most curves one direction of a network may list (the kernel's own cap). -const MAX_NETWORK_CURVES: usize = solidcraft_geom::network::MAX_NETWORK_CURVES; +const CONTRACT: TypedContract = TypedContract::new(); /// The most sketch curves one network curve may chain, and points picking one chain of edges /// (the kernel's own caps). use solidcraft_kernel::{MAX_CHAIN_CURVES as MAX_CHAIN, MAX_EDGE_PICKS as MAX_PICKS}; -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("surface.boundary", "Boundary Surface", boundary) +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("surface.boundary", "Boundary Surface", crate::checked!("surface.boundary", boundary)) .at("SURFACE", "CREATE") .icon("surface_boundary") + .contract(&CONTRACT) + .output(output_schema_for::) .params( "Either a loop of one sketch's curves — sketch?: id|name (default: the sketch being edited); curves: [2 to 4 sketch curve ids in loop order] (each one ends where the next begins and the last where the first does; two: the patch spans between them and leaves each boundary along the tangent across it; three or four: the flat patch of the loop, three collapsing the side opposite the first curve to the corner there); continuity?: g0|g1|g2|g3 | [one per curve] (default g1: how much of the surface across each boundary the patch repeats — a sketch curve's own plane, so g1 and up hold exactly and g0 lets the middle bow); crown?: number -0.9…3 (default 0: how full the middle is, without touching a boundary; two curves only); samples?: 8…512 stations per boundary (default 25) — or a curve network — u: [curve] (two or more one way: the surface lofts through them), v?: [curve] (crossing every u-curve once: two each way give a Coons patch, more a Gordon surface through every curve; a curve that misses another by more than 0.01 mm is refused, naming the pair), each curve \"id\" (a curve of `sketch`) | {sketch?: id|name, curves: [ids meeting end to end]} (planar or 3D sketch curves) | {body: name, edges: [[x,y,z]] (points on a chain of its edges), continuity?: g0|g1|g2 (default g0; g1 the surface leaves tangent to the face beside a surface's open edges, g2 with its curvature too; on curves of one direction only)} | {point: [x,y,z]} (a side collapsed to a point: a three-sided patch); operation?: new|join (default new; join sews the surface into the body of its first edge curve, a solid when it closes the gap). name?, body_name? (a surface body)", )]; @@ -56,7 +56,7 @@ fn loop_patch(s: &mut Session, p: &Value) -> Result { // of each is the first of the next, and the last boundary's end is the first one's start. let state = s.model.state(); let sk = state.sketch(sketch).ok_or_else(|| bad(cmd, "the sketch has not been solved"))?; - let mut ends: Vec<(solidcraft_geom::Vec2, solidcraft_geom::Vec2)> = Vec::with_capacity(curves.len()); + let mut ends: Vec<(solidcore_record::Vec2, solidcore_record::Vec2)> = Vec::with_capacity(curves.len()); for id in &curves { let ci = sk.sketch.curve_index(id).ok_or_else(|| bad(cmd, format!("no sketch curve `{id}`")))?; let pieces = sk.sketch.exact_pieces(ci); @@ -88,15 +88,12 @@ fn loop_patch(s: &mut Session, p: &Value) -> Result { drop(state); let orders = match p.get("continuity") { None | Some(Value::Null) => vec![Continuity::G1; curves.len()], - Some(Value::String(w)) => { - let one = Continuity::parse(w).ok_or_else(|| bad(cmd, "`continuity` must be g0, g1, g2 or g3"))?; - vec![one; curves.len()] - } + Some(one @ Value::String(_)) => vec![crate::params::continuity(cmd, Some(one), "`continuity`", Construction::Bridge)?; curves.len()], Some(v) => { let list = v.as_array().filter(|a| a.len() == curves.len()).ok_or_else(|| bad(cmd, "`continuity` must be one word, or one per curve"))?; let mut out = Vec::with_capacity(list.len()); for x in list { - out.push(x.as_str().and_then(Continuity::parse).ok_or_else(|| bad(cmd, "`continuity` entries must be g0, g1, g2 or g3"))?); + out.push(crate::params::continuity(cmd, Some(x), "a `continuity` entry", Construction::Bridge)?); } out } @@ -205,10 +202,7 @@ fn network_curves(s: &Session, p: &Value, key: &str, default_sketch: &mut Option } } if let Some(g) = o.get("continuity").filter(|v| !v.is_null()) { - let g = g.as_str().and_then(Continuity::parse).ok_or_else(|| bad(cmd, format!("{name}.continuity must be g0, g1 or g2")))?; - if g == Continuity::G3 { - return Err(bad(cmd, format!("not supported yet: G3 on {name} (a curve network holds up to g2)"))); - } + let g = crate::params::continuity(cmd, Some(g), &format!("{name}.continuity"), Construction::Network)?; if g != Continuity::G0 && curve.body.is_none() { return Err(bad(cmd, format!("{name}: g1 and g2 apply to a curve on a body's edges (a surface's open edges)"))); } diff --git a/crates/engine/src/cmd/surface_boundary_tests.rs b/crates/engine/src/cmd/surface_boundary_tests.rs index fd9f0f81a..18d1ea907 100644 --- a/crates/engine/src/cmd/surface_boundary_tests.rs +++ b/crates/engine/src/cmd/surface_boundary_tests.rs @@ -114,8 +114,8 @@ fn a_network_of_3d_lines_is_a_hyperbolic_paraboloid() { // The face's own area comes from the coarse reference mesh (a chord of a fiftieth of a per // cent of the body); the measuring mesh is refined onto the surface. assert!((face - want).abs() < 1e-2 * want && (total - want).abs() < 1e-3 * want, "{face} / {total} vs {want}"); - let st = s.world_state(); - let mesh = st.body(&body).map(|b| b.body.tessellate(0.01)).and_then(Result::ok).unwrap_or_default(); + let st = s.world_state().unwrap(); + let mesh = st.body(&body).map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01))).and_then(Result::ok).unwrap_or_default(); assert!(!mesh.positions.is_empty()); for p in &mesh.positions { assert!((p.z - p.x * p.y / 10.0).abs() < 1e-6, "{p:?} is off the paraboloid"); @@ -194,13 +194,13 @@ fn hostile_networks_are_refused() { let mut s = Session::default(); let (sheet, top) = cylinder_and_line(&mut s); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 40, 0]})); - let boxed = s.world_state().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); + let boxed = s.world_state().unwrap().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Flat"})); let a = line(&mut s, [0.0, 0.0], [10.0, 0.0]); let b = line(&mut s, [0.0, 5.0], [10.0, 5.0]); let far = line(&mut s, [0.0, 20.0], [10.0, 20.0]); let ring = first(&run(&mut s, "sketch.circle.center", json!({"center": [50, 50], "radius": 3}))["created"]["curves"]); - let bodies = s.world_state().bodies.len(); + let bodies = s.world_state().unwrap().bodies.len(); let edge = |g: &str| json!({"body": sheet, "edges": [[5.0, 10.0, 0.0]], "continuity": g}); let many: Vec = (0..33).map(|_| json!(a)).collect(); let cases: Vec<(Value, &str)> = vec![ @@ -240,7 +240,7 @@ fn hostile_networks_are_refused() { assert!(!matches!(e, crate::EngineError::Internal(..)), "{params}: {e}"); assert!(e.to_string().contains(want), "{params}: {e}"); } - assert_eq!(s.world_state().bodies.len(), bodies, "a refused network left a body behind"); + assert_eq!(s.world_state().unwrap().bodies.len(), bodies, "a refused network left a body behind"); } /// An edit (`timeline.redefine`) may turn a loop of sketch curves into the network of the same @@ -259,7 +259,7 @@ fn an_edit_turns_a_loop_into_a_network_and_back() { run(&mut s, "timeline.redefine", json!({"feature": "Patch", "command": "surface.boundary", "params": network})); let kind = |s: &Session| s.doc.find_feature("Patch").map(|f| f.kind.clone()); assert!(matches!(kind(&s), Some(solidcraft_doc::FeatureKind::SurfaceNetwork { .. })), "{:?}", kind(&s)); - let body = s.world_state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let body = s.world_state().unwrap().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); assert!((areas(&mut s, &body).0 - 100.0).abs() < 1e-6); run(&mut s, "timeline.redefine", json!({"feature": "Patch", "command": "surface.boundary", "params": {"sketch": "Square", "curves": sides}})); assert!(matches!(kind(&s), Some(solidcraft_doc::FeatureKind::SurfaceBoundary { .. })), "{:?}", kind(&s)); diff --git a/crates/engine/src/cmd/surface_match.rs b/crates/engine/src/cmd/surface_match.rs index 78f5b8ec8..bb5e6f303 100644 --- a/crates/engine/src/cmd/surface_match.rs +++ b/crates/engine/src/cmd/surface_match.rs @@ -5,17 +5,24 @@ use serde_json::Value; use solidcraft_doc::{BodyName, FacePick, FeatureKind, Position}; -use solidcraft_kernel::Continuity; +use solidcraft_kernel::{Construction, Continuity}; use super::CommandSpec; use super::features::add_feature; use crate::params::{bad, str_, vec3}; +use crate::schema::features::FeatureResult; +use crate::schema::surface_match::MatchSurfaceParams; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; +const CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("surface.match", "Match Surface", match_surface) + CommandSpec::new("surface.match", "Match Surface", crate::checked!("surface.match", match_surface)) .at("SURFACE", "MODIFY") .icon("continuity") + .contract(&CONTRACT) + .output(output_schema_for::) .params( "body: surface name (the body whose face is rebuilt); faces?: [[x,y,z]] (points on that face, default: the body's first); target: body name (the body the seam must meet); edges: [[x,y,z]] (points on one edge chain of the target: the rebuilt boundary takes its place); order?: g1|g2|g3 (default g2: position and tangent plane, the curvature too, or how that curvature changes along the seam). The far boundary stays where it was and the body keeps its name", ), @@ -33,17 +40,19 @@ fn match_surface(s: &mut Session, p: &Value) -> Result { if s.model.state().body(&target).is_none() { return Err(bad(cmd, format!("no body `{target}`"))); } - let faces: Vec = p.get("faces").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + let faces: Vec = + p.get("faces").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if faces.len() > 64 { return Err(bad(cmd, "too many points on the face to rebuild")); } - let edges: Vec = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + let edges: Vec = + p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); if edges.is_empty() || edges.len() > 10_000 { return Err(bad(cmd, "`edges` must list 1 to 10000 points on the target's edge chain")); } let order = match p.get("order") { None => Continuity::G2, - Some(v) => v.as_str().and_then(Continuity::parse).filter(|o| *o != Continuity::G0).ok_or_else(|| bad(cmd, "`order` must be g1, g2 or g3"))?, + Some(v) => crate::params::continuity(cmd, Some(v), "`order`", Construction::Match)?, }; add_feature( s, @@ -63,7 +72,7 @@ mod tests { use super::*; use crate::Session; use serde_json::json; - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; fn run(s: &mut Session, c: &str, p: Value) -> Value { s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")) @@ -73,7 +82,7 @@ mod tests { /// at either end. The seam is where `solid.extrude` starts the circle, so it is read off the /// body rather than assumed. fn picks(s: &Session) -> Vec { - let boss = s.world_state().body("Boss").unwrap().body.clone(); + let boss = s.world_state().unwrap().body("Boss").unwrap().body.clone(); let e = boss .edges(boss.size() * 1e-2) .unwrap() @@ -109,7 +118,7 @@ mod tests { /// is from the picked seam line, the angle between the two surfaces' normals across it, and /// the continuity it holds. fn seam(s: &Session) -> (f64, f64, Continuity) { - let st = s.world_state(); + let st = s.world_state().unwrap(); let made = st.body("Skirt").unwrap().body.clone(); let target = st.body("Boss").unwrap().body.clone(); solidcraft_kernel::seam_continuity(&made, &target, &picks(s)).unwrap() @@ -127,7 +136,7 @@ mod tests { assert!((gap - 1.0).abs() < 0.05, "the skirt starts a millimetre off the seam: {gap}"); let chain = picks(&s); run(&mut s, "surface.match", json!({"body": "Skirt", "target": "Boss", "edges": chain, "order": "g2"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Skirt").is_some(), "the matched body keeps its name"); assert!(st.body("Boss").is_some(), "the body it was matched to stays too"); assert!(st.body("Skirt").unwrap().body.is_surface(), "a match stays a surface"); diff --git a/crates/engine/src/cmd/sweep_options_tests.rs b/crates/engine/src/cmd/sweep_options_tests.rs index 2d6b804bf..ceeb5f95c 100644 --- a/crates/engine/src/cmd/sweep_options_tests.rs +++ b/crates/engine/src/cmd/sweep_options_tests.rs @@ -31,7 +31,7 @@ fn setup() -> Session { } fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { - solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() + solidcraft_kernel::measure(&s.world_state().unwrap().body(body).unwrap().body).unwrap() } fn sweep(s: &mut Session, sketch: &str, body: &str, extra: Value) -> Result { @@ -92,7 +92,7 @@ fn twisted_sweep_faces_follow_the_profile_curves() { // The end cap turns with the twist: at 90 deg a square's corners are back where they were, // at 45 deg its top reaches out to the corner radius along the axes. let reach = |s: &Session| { - let mesh = s.world_state().body("Twisted").unwrap().body.tessellate(0.01).unwrap(); + let mesh = s.world_state().unwrap().body("Twisted").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); mesh.positions.iter().filter(|p| (p.z - 40.0).abs() < 1e-6).map(|p| p.x).fold(f64::MIN, f64::max) }; assert!((reach(&s) - 5.0).abs() < 1e-3, "{}", reach(&s)); @@ -161,3 +161,56 @@ fn hostile_sweep_options_are_refused() { assert_eq!(s.doc.features.len(), before, "{bad}"); } } + +/// #3345: a 4 x 3 profile drawn at the middle of the bottom line of a closed rounded rectangle +/// (60 x 40, corners r8), swept round all of it, path picked from that line's start. The path is +/// followed from the profile: the tube stays on the path (Pappus: A L), within 2 mm of it +/// sideways, instead of standing off it by the half line the path's start lies away. +#[test] +fn a_sweep_round_a_closed_path_starts_where_the_profile_is() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Path"})); + run(&mut s, "sketch.line", json!({"points": [[-22, -20], [22, -20]], "infer": false, "ids": ["l1"]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [22, -12], "start": [22, -20], "end": [30, -12], "id": "a1"})); + run(&mut s, "sketch.line", json!({"points": [[30, -12], [30, 12]], "infer": false, "ids": ["l2"]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [22, 12], "start": [30, 12], "end": [22, 20], "id": "a2"})); + run(&mut s, "sketch.line", json!({"points": [[22, 20], [-22, 20]], "infer": false, "ids": ["l3"]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [-22, 12], "start": [-22, 20], "end": [-30, 12], "id": "a3"})); + run(&mut s, "sketch.line", json!({"points": [[-30, 12], [-30, -12]], "infer": false, "ids": ["l4"]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [-22, -12], "start": [-30, -12], "end": [-22, -20], "id": "a4"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, -20, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}, "name": "Prof"})); + run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [2, 1.5]})); + run(&mut s, "sketch.finish", json!({})); + let path = json!(["l1", "a1", "l2", "a2", "l3", "a3", "l4", "a4"]); + run(&mut s, "solid.sweep", json!({"sketch": "Prof", "path_sketch": "Path", "path": path, "operation": "new", "body_name": "Tube"})); + let m = measure(&s, "Tube"); + let want = 12.0 * (2.0 * 44.0 + 2.0 * 24.0 + 4.0 * (PI / 2.0) * 8.0); + assert!((m.volume - want).abs() < want * 1e-3, "{} vs {want}", m.volume); + // Within the rig's 1e-3 of the box diagonal (the box is measured on a mesh). + for (got, want) in [(m.bbox.min.x, -32.0), (m.bbox.min.y, -22.0), (m.bbox.max.x, 32.0), (m.bbox.max.y, 22.0)] { + assert!((got - want).abs() < 0.08, "{:?}", m.bbox); + } +} + +/// #3604: a path whose first curve is a spline of several exact pieces, the next curve meeting +/// it at its start, follows the spline back from its end: a curve is turned round whole, not +/// piece by piece. A 2 x 2 profile at the spline's end (20, 0), swept along the spline through +/// (20, 0), (10, 0), (0, 0) and on along the line to (-15, 0): a 35 long bar. +#[test] +fn a_path_turns_a_spline_of_several_pieces_round_whole() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Path"})); + run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 0], [20, 0]], "ids": ["s1"]})); + run(&mut s, "sketch.line", json!({"points": [[-15, 0], [0, 0]], "infer": false, "ids": ["l1"]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": {"origin": [20, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}, "name": "Prof"})); + run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [1, 1]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.sweep", json!({"sketch": "Prof", "path_sketch": "Path", "path": ["s1", "l1"], "operation": "new", "body_name": "Bar"})); + let m = measure(&s, "Bar"); + assert!((m.volume - 140.0).abs() < 140.0 * 1e-6, "{}", m.volume); + for (got, want) in [(m.bbox.min.x, -15.0), (m.bbox.max.x, 20.0), (m.bbox.min.y, -1.0), (m.bbox.max.y, 1.0)] { + assert!((got - want).abs() < 0.04, "{:?}", m.bbox); + } +} diff --git a/crates/engine/src/cmd/sweep_rails_tests.rs b/crates/engine/src/cmd/sweep_rails_tests.rs index badeffc69..e6600633f 100644 --- a/crates/engine/src/cmd/sweep_rails_tests.rs +++ b/crates/engine/src/cmd/sweep_rails_tests.rs @@ -39,7 +39,7 @@ fn setup() -> Session { } fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { - solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() + solidcraft_kernel::measure(&s.world_state().unwrap().body(body).unwrap().body).unwrap() } fn sweep(s: &mut Session, body: &str, extra: Value) -> Result { diff --git a/crates/engine/src/cmd/thin_extrude_tests.rs b/crates/engine/src/cmd/thin_extrude_tests.rs index 86fd336e7..208e9a601 100644 --- a/crates/engine/src/cmd/thin_extrude_tests.rs +++ b/crates/engine/src/cmd/thin_extrude_tests.rs @@ -2,6 +2,7 @@ //! area times its height). use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -182,15 +183,15 @@ fn attachment(s: &Session, sketch: &str) -> solidcraft_doc::FaceAttachmentStatus s.placed_document().sketch_face_attachment(id, &s.model) } -fn attached(s: &Session, sketch: &str) -> (solidcraft_geom::Plane, Option) { +fn attached(s: &Session, sketch: &str) -> (solidcore_record::Plane, Option) { match attachment(s, sketch) { solidcraft_doc::FaceAttachmentStatus::Healthy { plane, target, .. } => (plane, target.certificate), other => panic!("{sketch}: {other:?}"), } } -fn same_plane(a: &solidcraft_geom::Plane, b: &solidcraft_geom::Plane) { - let near = |p: solidcraft_geom::Vec3, q: solidcraft_geom::Vec3| (p - q).len() < 1e-9; +fn same_plane(a: &solidcore_record::Plane, b: &solidcore_record::Plane) { + let near = |p: solidcore_record::Vec3, q: solidcore_record::Vec3| (p - q).len() < 1e-9; assert!(near(a.origin, b.origin) && near(a.x, b.x) && near(a.y, b.y), "{a:?} != {b:?}"); } @@ -284,7 +285,7 @@ fn no_errors(s: &Session, context: &str) { } /// How far a face's plane lies from the origin along its own normal. -fn plane_offset(plane: &solidcraft_geom::Plane) -> f64 { +fn plane_offset(plane: &solidcore_record::Plane) -> f64 { plane.normal().dot(plane.origin) } @@ -338,11 +339,11 @@ fn the_walls_of_an_open_thin_extrude_take_sketches_that_follow_their_thickness() /// A point inside each flat, vertical face of the first body: (what it is, point). fn flat_side_faces(s: &Session) -> Vec<(String, [f64; 3])> { - let world = s.world_state(); + let world = s.world_state().unwrap(); let mut out = Vec::new(); let Some(body) = world.bodies.first() else { return out }; let mesh = body.mesh(); - let mut best: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let mut best: std::collections::BTreeMap = std::collections::BTreeMap::new(); for (triangle, face) in mesh.triangles.iter().zip(&mesh.tri_face) { if let Some([a, b, c]) = mesh.tri(triangle) { let area = (b - a).cross(c - a).len(); @@ -369,12 +370,17 @@ fn the_round_sides_of_a_thin_ring_are_named_by_the_circle_they_run_beside() { run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch": "Outline", "thin": true, "thickness": 2, "distance": 5, "name": "Ring"})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let names = solidcraft_doc::naming::face_names(world.bodies.first().unwrap()); - // Each round side is two half cylinders, told apart by their numbers. + // Each round side is one cylinder, closed along its seam, so its name needs no number. let walls: Vec<_> = names.iter().filter(|name| name.contains(":wall:")).collect(); - assert_eq!(walls.len(), 4, "{names:?}"); - for side in ["left", "right"] { - assert_eq!(walls.iter().filter(|name| name.contains(&format!(":wall:c1:{side}#"))).count(), 2, "{walls:?}"); + assert_eq!(walls.len(), 2, "{names:?}"); + // The wall is 2 thick about the circle (radius 9 to 11). The circle runs counter-clockwise, + // so its left is the inner side; each name is found again at a point on its own wall. + for (side, radius) in [("left", 9.0), ("right", 11.0)] { + let name = format!("F2:wall:c1:{side}"); + assert!(walls.contains(&&name), "{walls:?}"); + let at = solidcore_record::Vec3::new(0.0, radius, 2.5); + assert_eq!(solidcraft_doc::naming::face_names_at(&s.model.state(), &[at]), vec![name.clone()]); } } diff --git a/crates/engine/src/cmd/urdf_tests.rs b/crates/engine/src/cmd/urdf_tests.rs index 84625a573..b67806a44 100644 --- a/crates/engine/src/cmd/urdf_tests.rs +++ b/crates/engine/src/cmd/urdf_tests.rs @@ -1,6 +1,7 @@ //! URDF export (#719, docs/urdf.md): files, names, limits, mass and forward kinematics against //! the joint solver. +use solidcraft_geom::prelude::*; use std::path::PathBuf; use serde_json::{Value, json}; @@ -111,7 +112,7 @@ fn stl_volume(bytes: &[u8]) -> Option { for (k, p) in t.iter().enumerate() { let n = mesh.positions.len() as u32; tri[k] = *index.entry(p.map(f32::to_bits)).or_insert_with(|| { - mesh.positions.push(solidcraft_geom::Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64)); + mesh.positions.push(solidcore_record::Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64)); n }); } @@ -375,7 +376,7 @@ fn urdf_inertial_is_mass_weighted() { } assert!(i.inertia[0][1].abs() < 1e-15); // The centre of mass is the cube's centre, in the link frame. - assert!(i.com.dist(solidcraft_doc::apply_point(&l.mesh_origin, solidcraft_geom::Vec3::new(105.0, 5.0, 5.0))) < 1e-9, "{:?}", i.com); + assert!(i.com.dist(solidcraft_doc::apply_point(&l.mesh_origin, solidcore_record::Vec3::new(105.0, 5.0, 5.0))) < 1e-9, "{:?}", i.com); } #[test] diff --git a/crates/engine/src/cmd/view_dxf.rs b/crates/engine/src/cmd/view_dxf.rs index 676d8049b..0f47a3288 100644 --- a/crates/engine/src/cmd/view_dxf.rs +++ b/crates/engine/src/cmd/view_dxf.rs @@ -8,7 +8,7 @@ pub(super) mod sketch; use std::collections::BTreeMap; use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_io::{DxfEntity, DxfLayer, DxfLinetype, DxfShape}; use solidcraft_render::Camera; diff --git a/crates/engine/src/cmd/view_dxf_sketch.rs b/crates/engine/src/cmd/view_dxf_sketch.rs index 66a1327d6..000e66b15 100644 --- a/crates/engine/src/cmd/view_dxf_sketch.rs +++ b/crates/engine/src/cmd/view_dxf_sketch.rs @@ -3,7 +3,8 @@ //! curves, text outlines and drawn 3D-sketch curves. Construction geometry, centerlines, //! projected references, points, dimensions and constraints are viewport overlays and are left //! out. The active sketch is drawn on top, as the viewport draws it. -use solidcraft_geom::{Plane, Vec3}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::Sketch; use crate::Session; @@ -24,7 +25,7 @@ fn has_profile(sk: &Sketch) -> bool { /// Does the current view have anything `file.export_view_dxf` draws: a visible body or a shown /// sketch with a profile curve? The export dialog asks this before choosing a file. pub fn exportable(s: &Session) -> bool { - let world = s.world_state(); + let Ok(world) = s.world_state() else { return false }; world.bodies.iter().any(|b| s.body_visible(&b.name)) || world.sketches.iter().any(|ss| sketch_shown(s, ss.feature) && has_profile(&ss.sketch)) } @@ -44,7 +45,7 @@ fn curve_parts(sk: &Sketch, i: usize, plane: &Plane, tolerance: f64) -> Vec Result, &'static str> { - let world = s.world_state(); + let world = s.world_state().map_err(|_| "the model cannot be placed")?; let shown: Vec<_> = world.sketches.iter().filter(|ss| sketch_shown(s, ss.feature)).collect(); let progress = Stage::new("dxf_projection", shown.len()); let mut result = Vec::new(); diff --git a/crates/engine/src/cmd/view_dxf_tests.rs b/crates/engine/src/cmd/view_dxf_tests.rs index 7fb116f76..2a9cd50f1 100644 --- a/crates/engine/src/cmd/view_dxf_tests.rs +++ b/crates/engine/src/cmd/view_dxf_tests.rs @@ -1,5 +1,6 @@ use super::*; -use solidcraft_geom::{Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; +use solidcraft_geom::prelude::*; use solidcraft_render::StandardView; fn run(s: &mut Session, id: &str, p: Value) -> Value { @@ -180,7 +181,7 @@ fn view_dxf_keeps_every_occurrence_while_sharing_geometry() { assert!(centers.len() >= 3, "{centers:?}"); assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); // The definition's first placement hidden: the others are still drawn from the shared mesh. - let first = s.world_state().bodies.first().map(|b| b.name.clone()).unwrap(); + let first = s.world_state().unwrap().bodies.first().map(|b| b.name.clone()).unwrap(); run(&mut s, "browser.visibility", json!({"items":[first],"visible":false})); let result = export(&mut s, camera(StandardView::Top), "dashed"); assert_eq!((result["stats"]["bodies"].clone(), result["stats"]["shared_meshes"].clone()), (json!(2), json!(1)), "{result}"); diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index 4e34336d1..71c4558c7 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -1,16 +1,21 @@ //! Stateless camera commands shared by the navigation cube and programmatic callers. use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use solidcraft_render::{Camera, StandardView}; use super::CommandSpec; use crate::params::{bad, num, req_vec2, req_vec3, vec3}; -use crate::schema::view_navigation::{RenderBrowser, RenderFocus, RenderSelect, TabStep, TabStepParams}; +use crate::schema::view_navigation::{ + CameraReply, NormalToParams, RenderBrowser, RenderFocus, RenderSelect, StandardViewParams, TabStep, TabStepParams, +}; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Sel, Session}; const FOCUS_CONTRACT: TypedContract = TypedContract::new(); const BROWSER_CONTRACT: TypedContract = TypedContract::new(); const TAB_STEP_CONTRACT: TypedContract = TypedContract::new(); +const STANDARD_VIEW_CONTRACT: TypedContract = TypedContract::new(); +const NORMAL_TO_CONTRACT: TypedContract = TypedContract::new(); // Both existing request forms share the Browser command and its published schema. #[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)] @@ -35,6 +40,10 @@ const RENDER_SELECT: TypedContract = TypedContract::new(); const STATUS_ITEMS_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ +CommandSpec::new("view.status_details", "Viewport Status Details", crate::checked!("view.status_details", status_details)) + .icon("list").noundo().doc_only() + .contract(&STATUS_ITEMS_CONTRACT).output(output_schema_for::) + .params("no parameters → current effect settings/detail capabilities and retained per-seam Continuity diagnostics, with current geometry validity; read-only, no evaluation"), CommandSpec::new("view.status_items", "Viewport Status Items", crate::checked!("view.status_items", status_items)) .icon("list").noundo().doc_only() .contract(&STATUS_ITEMS_CONTRACT).output(output_schema_for::) @@ -102,19 +111,21 @@ CommandSpec::new("view.navigate", "Navigate View", navigate) .icon("orbit") .noundo() .doc_only() - .params("camera: Camera; direction?: [x,y,z] in the camera's up-axis frame; or action: left|right|up|down|clockwise|counterclockwise|home|fit, degrees?: 0..180 (how far left|right|up|down turn; default 90); or motion: pan|orbit|zoom, delta?: [dx,dy] (pixels, each ±10000), free_orbit?: bool (orbit through poles, default false), viewport?: [width,height] (1..1000000, required for pan or pivot), pivot?: [x,y,z], factor?: 0.05..20 (required for zoom), anchor?: [x,y,z] → camera, fit, continuous?"), -CommandSpec::new("view.normal_to", "Normal to Selection", normal_to) + .params("camera: Camera; direction?: [x,y,z] in the camera's up-axis frame; or action: left|right|up|down|clockwise|counterclockwise|home|fit, degrees?: 0..180 (how far left|right|up|down turn; default 90), fit?: bool (frame the whole model from the new direction as well, as home does; default false); or motion: pan|orbit|zoom, delta?: [dx,dy] (pixels, each ±10000), free_orbit?: bool (orbit through poles, default false), viewport?: [width,height] (1..1000000, required for pan or pivot), pivot?: [x,y,z], factor?: 0.05..20 (required for zoom), anchor?: [x,y,z] → camera, fit, continuous?"), +CommandSpec::new("view.normal_to", "Normal to Selection", crate::checked!("view.normal_to", normal_to)) .icon("camera") .noundo() .enabled(|s| normal_target(s).map(|_| ()).ok_or_else(|| "select a planar face or plane".into())) + .contract(&NORMAL_TO_CONTRACT) + .output(output_schema_for::) .params("camera?: Camera (default: current session camera or home view) → camera; Look At the first selected planar face or plane, centered on the picked point; repeat while aligned to flip the side; preserves scale and projection"), -CommandSpec::new("view.front", "Front View", front).icon("camera").noundo().key("Ctrl+1").params(STANDARD_PARAMS), -CommandSpec::new("view.back", "Back View", back).icon("camera").noundo().key("Ctrl+2").params(STANDARD_PARAMS), -CommandSpec::new("view.left", "Left View", left).icon("camera").noundo().key("Ctrl+3").params(STANDARD_PARAMS), -CommandSpec::new("view.right", "Right View", right).icon("camera").noundo().key("Ctrl+4").params(STANDARD_PARAMS), -CommandSpec::new("view.top", "Top View", top).icon("camera").noundo().key("Ctrl+5").params(STANDARD_PARAMS), -CommandSpec::new("view.bottom", "Bottom View", bottom).icon("camera").noundo().key("Ctrl+6").params(STANDARD_PARAMS), -CommandSpec::new("view.isometric", "Isometric View", isometric).icon("camera").noundo().key("Ctrl+7").params(STANDARD_PARAMS), +CommandSpec::new("view.front", "Front View", crate::checked!("view.front", front)).icon("camera").noundo().key("Ctrl+1").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::).params(STANDARD_PARAMS), +CommandSpec::new("view.back", "Back View", crate::checked!("view.back", back)).icon("camera").noundo().key("Ctrl+2").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::).params(STANDARD_PARAMS), +CommandSpec::new("view.left", "Left View", crate::checked!("view.left", left)).icon("camera").noundo().key("Ctrl+3").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::).params(STANDARD_PARAMS), +CommandSpec::new("view.right", "Right View", crate::checked!("view.right", right)).icon("camera").noundo().key("Ctrl+4").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::).params(STANDARD_PARAMS), +CommandSpec::new("view.top", "Top View", crate::checked!("view.top", top)).icon("camera").noundo().key("Ctrl+5").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::).params(STANDARD_PARAMS), +CommandSpec::new("view.bottom", "Bottom View", crate::checked!("view.bottom", bottom)).icon("camera").noundo().key("Ctrl+6").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::).params(STANDARD_PARAMS), +CommandSpec::new("view.isometric", "Isometric View", crate::checked!("view.isometric", isometric)).icon("camera").noundo().key("Ctrl+7").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::).params(STANDARD_PARAMS), CommandSpec::new("view.next_tab", "Next Tab", crate::checked!("view.next_tab", next_tab)) .icon("chevron_right").noundo().doc_only().key("Ctrl+Tab").contract(&TAB_STEP_CONTRACT).output(output_schema_for::) .params("no parameters → step: 1; the window shows the design tab to the right of the shown one (after the last, the first); never edits the design or opens a dialog"), @@ -160,54 +171,83 @@ fn isometric(s: &mut Session, p: &Value) -> Result { turn_to(s, p, "view.isometric") } -fn turn_to(s: &mut Session, p: &Value, cmd: &str) -> Result { - let view = standard_view(cmd).ok_or_else(|| bad(cmd, "not a standard view"))?; - let mut cam: Camera = match p.get("camera") { - Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "invalid camera"))?, - None => s.camera.unwrap_or_else(|| crate::view::home_camera(s)), - }; - if !cam.is_valid() || !cam.fov.is_finite() || !(0.0..std::f64::consts::PI).contains(&cam.fov) { - return Err(bad(cmd, "invalid camera")); - } - cam.set_view(view); - s.camera = Some(cam); - Ok(json!({"camera": cam})) +/// A view command's `camera` as its handler reads it: a [`Camera`] with finite fields, a positive +/// distance and a field of view in [0, π). None for anything else, which the handlers refuse as +/// "invalid camera" (and `CameraParam`, its contract type, too). +pub(crate) fn camera_form(v: &Value) -> Option { + serde_json::from_value::(v.clone()).ok().filter(usable_camera) } -fn normal_target(s: &Session) -> Option<(solidcraft_geom::Vec3, solidcraft_geom::Vec3)> { - let state = s.world_state(); +fn usable_camera(cam: &Camera) -> bool { + cam.is_valid() && cam.fov.is_finite() && (0.0..std::f64::consts::PI).contains(&cam.fov) +} + +/// The camera a view command turns: the one given, else the session's, else the home view. +fn given_camera(s: &Session, p: &Value) -> Result> { + Ok(match p.get("camera") { + Some(value) => camera_form(value), + None => Some(match s.camera { + Some(c) => c, + None => crate::view::home_camera(s)?, + }) + .filter(usable_camera), + }) +} + +/// The reply of a view command that turned the camera to `camera`. +fn camera_reply(cmd: &str, camera: Camera) -> Result { + serde_json::to_value(CameraReply { camera, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string())) +} + +fn turn_to(s: &mut Session, p: &Value, cmd: &str) -> Result { + let view = standard_view(cmd).ok_or_else(|| bad(cmd, "not a standard view"))?; + let mut cam = given_camera(s, p)?.ok_or_else(|| bad(cmd, "invalid camera"))?; + cam.set_view(view); + s.camera = Some(cam); + camera_reply(cmd, cam) +} + +fn normal_target(s: &Session) -> Option<(solidcore_record::Vec3, solidcore_record::Vec3)> { + let state = s.world_state().ok()?; s.selection.iter().find_map(|selection| match selection { Sel::Face { body, index, point } if point.is_finite() => { let plane = state.body(body)?.body.planar_face(*index)?; Some((*point, plane.normal())) } - Sel::Plane { name } => solidcraft_geom::Plane::named(name).map(|plane| (plane.origin, plane.normal())), + Sel::Plane { name } => solidcore_record::Plane::named(name).map(|plane| (plane.origin, plane.normal())), _ => None, }) } +fn status_details(s: &mut Session, p: &Value) -> Result { + let p = if p.is_null() { json!({}) } else { p.clone() }; + if !p.as_object().is_some_and(|object| object.is_empty()) { + return Err(bad("view.status_details", "parameters must be an empty object")); + } + let _: crate::schema::view_navigation::StatusItemsParams = serde_json::from_value(p).map_err(|e| bad("view.status_details", e.to_string()))?; + let items = + s.status_items().into_iter().map(|source| crate::status_details::StatusDetailItem { has_details: source.has_details(), source }).collect(); + serde_json::to_value(crate::status_details::StatusDetails { + document_id: s.document_id.clone(), + items, + continuity: s.continuity_details(), + param_warnings: Vec::new(), + }) + .map_err(|e| bad("view.status_details", e.to_string())) +} + fn normal_to(s: &mut Session, p: &Value) -> Result { let cmd = "view.normal_to"; let (point, normal) = normal_target(s).ok_or_else(|| bad(cmd, "select a planar face or plane"))?; - let cam: Camera = match p.get("camera") { - Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "invalid camera"))?, - None => s.camera.unwrap_or_else(|| crate::view::home_camera(s)), - }; - if !cam.is_valid() - || !cam.fov.is_finite() - || !(0.0..std::f64::consts::PI).contains(&cam.fov) - || cam.yaw.abs() > 1e6 - || cam.roll.abs() > 1e6 - || cam.pitch.abs() > std::f64::consts::FRAC_PI_2 - { - return Err(bad(cmd, "invalid camera")); - } + let cam = given_camera(s, p)? + .filter(|cam| cam.yaw.abs() <= 1e6 && cam.roll.abs() <= 1e6 && cam.pitch.abs() <= std::f64::consts::FRAC_PI_2) + .ok_or_else(|| bad(cmd, "invalid camera"))?; // Promoted from viewport::look_at_selection: asking again from the normal side flips it. let direction = if cam.back().dot(normal) > 0.999 { -normal } else { normal }; let mut to = cam.looking_from(direction); to.target = point; s.camera = Some(to); - Ok(json!({"camera": to})) + camera_reply(cmd, to) } // UI-owned settings follow the layout command: validate here, apply in the UI adapter. @@ -294,7 +334,7 @@ fn render_select(s: &mut Session, p: &Value) -> Result { let result = serde_json::to_value(request).map_err(|e| bad("view.render_select", e.to_string()))?; if !s.selection.is_empty() { s.selection.clear(); - s.revision += 1; + s.refresh_display(); } Ok(result) } @@ -415,10 +455,19 @@ fn navigate(_s: &mut Session, p: &Value) -> Result { { return Err(bad(cmd, "invalid camera")); } + // A turn may ask the window to frame the whole model from the new direction, as `home` does + // (the navigators' Fit preference, #10091). + let framed = match p.get("fit") { + None => false, + Some(value) => value.as_bool().ok_or_else(|| bad(cmd, "fit must be a boolean"))?, + }; if p.get("motion").is_some() { + if framed { + return Err(bad(cmd, "fit does not apply to a motion")); + } return continuous(cam, p); } - let mut fit = false; + let mut fit = framed; if let Some(value) = p.get("direction") { let dir = vec3(value) .filter(|v| v.is_finite() && v.len() <= 2.0) @@ -442,7 +491,7 @@ fn navigate(_s: &mut Session, p: &Value) -> Result { .map(|d| if d == 90.0 { (1.0, 0.0) } else { d.to_radians().sin_cos() }) .ok_or_else(|| bad(cmd, "degrees must be a number above 0 and at most 180"))?, }; - let turn = |toward: solidcraft_geom::Vec3| cam.looking_from(b * cos + toward * sin); + let turn = |toward: solidcore_record::Vec3| cam.looking_from(b * cos + toward * sin); match p.get("action").and_then(Value::as_str) { Some("left") => cam = turn(-r), Some("right") => cam = turn(r), @@ -483,7 +532,7 @@ fn continuous(mut cam: Camera, p: &Value) -> Result { } let orbit = |cam: &mut Camera| { if free_orbit { - cam.rotate_in_view(solidcraft_geom::Vec3::new(-delta.y * 0.008, -delta.x * 0.008, 0.0)); + cam.rotate_in_view(solidcore_record::Vec3::new(-delta.y * 0.008, -delta.x * 0.008, 0.0)); } else { cam.orbit(delta.x, delta.y); } @@ -534,7 +583,7 @@ pub(crate) fn square_heading(yaw: f64) -> f64 { #[cfg(test)] mod tests { use super::*; - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; use solidcraft_render::UpAxis; #[test] @@ -600,7 +649,7 @@ mod tests { fn normal_to_selection_faces_each_planar_surface_without_editing_the_design() { let mut s = Session::default(); s.execute("solid.box", &json!({"length":40,"width":30,"height":20})).unwrap(); - let state = s.world_state(); + let state = s.world_state().unwrap(); let body = state.bodies.first().unwrap(); let faces = body.body.faces(0.01).unwrap(); let document = s.doc.to_json(); @@ -655,7 +704,7 @@ mod tests { fn normal_to_selection_rejects_curved_missing_and_invalid_inputs() { let mut s = Session::default(); s.execute("solid.cylinder", &json!({"diameter":20,"height":30})).unwrap(); - let state = s.world_state(); + let state = s.world_state().unwrap(); let body = state.bodies.first().unwrap(); let faces = body.body.faces(0.1).unwrap(); let flat = faces.iter().find(|f| f.plane_normal.is_some()).unwrap(); @@ -686,7 +735,7 @@ mod tests { s.execute("component.create", &json!({"name":"Part","grounded":false})).unwrap(); s.execute("solid.box", &json!({"length":40,"width":30,"height":20})).unwrap(); s.execute("occurrence.move", &json!({"occurrence":"Part:1","translate":[50,20,10],"axis":[1,2,3],"angle":"37 deg"})).unwrap(); - let state = s.world_state(); + let state = s.world_state().unwrap(); let body = state.bodies.first().unwrap(); let faces = body.body.faces(0.01).unwrap(); let cam = Camera { roll: 1.4, ..Default::default() }; @@ -731,6 +780,34 @@ mod tests { } } + /// #10091: a turn asked to frame the model reports `fit`, as home does; a motion can't. + #[test] + fn a_turn_with_fit_asks_the_window_to_frame_the_model() { + let mut s = Session::default(); + let before = s.doc.to_json(); + let cam = Camera { distance: 100.0, ..Default::default() }; + for params in + [json!({"camera": cam, "direction": [0, 0, 1]}), json!({"camera": cam, "action": "right"}), json!({"camera": cam, "action": "clockwise"})] + { + let plain = s.execute("view.navigate", ¶ms).unwrap(); + assert_eq!(plain["fit"], false, "{params}"); + let mut framed = params.clone(); + framed["fit"] = json!(true); + let result = s.execute("view.navigate", &framed).unwrap(); + assert_eq!(result["fit"], true, "{params}"); + assert_eq!(result["camera"], plain["camera"], "fit asks for the framing, the turn is the same"); + framed["fit"] = json!(false); + assert_eq!(s.execute("view.navigate", &framed).unwrap(), plain); + } + assert_eq!(s.execute("view.navigate", &json!({"camera": cam, "action": "home", "fit": false})).unwrap()["fit"], true, "home frames anyway"); + for value in [json!(1), json!("yes"), Value::Null, json!([true])] { + assert!(s.execute("view.navigate", &json!({"camera": cam, "action": "right", "fit": value})).is_err(), "{value}"); + } + assert!(s.execute("view.navigate", &json!({"camera": cam, "motion": "zoom", "factor": 2.0, "fit": true})).is_err()); + assert!(s.execute("view.navigate", &json!({"camera": cam, "motion": "zoom", "factor": 2.0, "fit": false})).is_ok()); + assert_eq!(s.doc.to_json(), before); + } + #[test] fn continuous_navigation_moves_the_camera_without_editing_the_design() { let mut s = Session::default(); diff --git a/crates/engine/src/computed_commands_tests.rs b/crates/engine/src/computed_commands_tests.rs index 5e6d6c0e1..9529499c1 100644 --- a/crates/engine/src/computed_commands_tests.rs +++ b/crates/engine/src/computed_commands_tests.rs @@ -16,15 +16,15 @@ fn acceptance_preserves_file_history_and_prepared_world_without_evaluation() { let checkpoint = session.checkpoint(); let history = session.undo.len(); let prepared = session.scratch().compute_commands(&commands(), None).unwrap(); - prepared.warm_meshes(|| true); - let world = prepared.computed.world_state(); + prepared.warm_meshes(|| true).unwrap(); + let world = prepared.computed.world_state().unwrap(); let before = session.evaluations; session.accept_commands(prepared).unwrap(); assert_eq!(session.evaluations, before); assert_eq!(session.path.as_deref(), Some("working.solidcraft")); assert!(Arc::ptr_eq(&saved, &session.saved)); assert_eq!(session.undo.len(), history + 1); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); session.restore_checkpoint(checkpoint).unwrap(); assert_eq!(session.undo.len(), history); assert_eq!(session.doc.features.len(), 1); @@ -65,14 +65,14 @@ fn revision_context_selection_and_replaced_document_reject_old_work() { fn editor_marker_restoration_reuses_the_pinned_model_with_an_empty_cache() { let mut session = Session::default(); session.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); let original = session.scratch(); session.execute("timeline.roll_to", &json!({"position":0})).unwrap(); let source = session.scratch(); *session.model.cache.lock().unwrap() = Default::default(); let prepared = session.scratch().compute_editor_commands(&[], &source, original).unwrap(); assert_eq!(prepared.computed.evaluations, 0, "restoring the marker must never evaluate the old suffix"); - assert!(Arc::ptr_eq(&world, &prepared.computed.world_state())); + assert!(Arc::ptr_eq(&world, &prepared.computed.world_state().unwrap())); session.accept_commands(prepared).unwrap(); assert_eq!(session.doc.marker, None); } @@ -149,6 +149,35 @@ fn editor_visibility_changes_allow_apply_and_preserve_separate_undo_steps() { } } +/// A section, an analysis or the selection changed while an editor is open changes only what is +/// shown: OK still applies the edit and Cancel puts the design back (#10687). +#[test] +fn editor_display_changes_allow_apply_and_cancel() { + let cases: [&[(&str, serde_json::Value)]; 5] = [ + &[("inspect.section", json!({"plane":"XZ","offset":1}))], + &[("inspect.section", json!({"plane":"XZ","offset":1})), ("inspect.section", json!({"clear":true}))], + &[("inspect.zebra", json!({"stripes":14.5}))], + &[("select.set", json!({"items":[{"type":"body","name":"Other"}]}))], + &[("select.clear", json!({}))], + ]; + for display in cases { + let (mut session, source, original, commands) = extrusion_editor(); + for (id, params) in display { + session.execute(id, params).unwrap(); + } + let prepared = + session.scratch().compute_editor_commands(&commands, &source, original).unwrap_or_else(|e| panic!("OK after {display:?}: {e}")); + session.accept_commands(prepared).unwrap(); + assert_editor_volume(&mut session, 12024.0); + let (mut session, source, original, _) = extrusion_editor(); + for (id, params) in display { + session.execute(id, params).unwrap(); + } + session.restore_editor(&source, original).unwrap_or_else(|e| panic!("Cancel after {display:?}: {e}")); + assert_editor_volume(&mut session, 6024.0); + } +} + #[test] fn editor_visibility_changes_allow_cancel_and_keep_undo_and_redo_at_the_original_marker() { for undo_hide in [false, true] { @@ -251,3 +280,41 @@ fn cancelling_an_editor_with_visibility_changes_restores_an_existing_history_mar assert_eq!(session.doc.marker, Some(1)); assert!(session.visibility.hidden_origin.is_empty()); } + +/// Rolling the marker back before a move of the body a joint seats on solves the joints again, +/// which puts the seated occurrence back where the body was: the editor's pinned model differs +/// from its source there, and only there, and the edit still goes through. +#[test] +fn an_editor_accepts_the_placements_rolling_the_marker_solves() { + let mut session = Session::default(); + for (name, x) in [("A", 0), ("B", 20)] { + session.execute("component.activate", &json!({"component": "root"})).unwrap(); + session.execute("component.create", &json!({"name": name})).unwrap(); + session.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})).unwrap(); + } + let component = |s: &Session, name: &str| s.doc.components.iter().find(|c| c.name == name).map(|c| c.id).unwrap(); + let occurrence = |s: &Session, name: &str| { + let component = component(s, name); + s.doc.occurrences.iter().find(|o| o.component == component).cloned().unwrap() + }; + session.execute("occurrence.ground", &json!({"occurrence": occurrence(&session, "A").id, "grounded": true})).unwrap(); + session + .execute("joint.create", &json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": 5, "name": "Seat"})) + .unwrap(); + let seated = occurrence(&session, "B").transform; + // A's box moves along, and B, seated on it, with it. + session.execute("component.activate", &json!({"component": "A"})).unwrap(); + let a = component(&session, "A"); + let body = session.model.state().bodies.iter().find(|b| b.component == a).map(|b| b.name.clone()).unwrap(); + session.execute("solid.move", &json!({"bodies": [body], "translate": [30, 0, 0]})).unwrap(); + let moved = occurrence(&session, "B").transform; + assert_ne!(moved, seated, "B follows the box it is seated on"); + let original = session.scratch(); + session.execute("timeline.roll_to", &json!({"position": 2})).unwrap(); + let source = session.scratch(); + assert_eq!(occurrence(&session, "B").transform, seated, "before the move, B sits where the box was"); + let prepared = session.scratch().compute_editor_commands(&[], &source, original).unwrap(); + session.accept_commands(prepared).unwrap(); + assert_eq!(session.doc.marker, None); + assert_eq!(occurrence(&session, "B").transform, moved); +} diff --git a/crates/engine/src/construct_tests.rs b/crates/engine/src/construct_tests.rs index e51afaed9..39b54ea08 100644 --- a/crates/engine/src/construct_tests.rs +++ b/crates/engine/src/construct_tests.rs @@ -2,7 +2,8 @@ //! 40 × 30 × 20 box at the origin, a cylinder, a sphere and a torus. use serde_json::{Value, json}; -use solidcraft_geom::{Plane, Vec3}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::prelude::*; use crate::Session; use crate::view::{construction_axes, construction_planes, construction_points}; @@ -43,6 +44,55 @@ fn plane(s: &Session, name: &str) -> Plane { construction_planes(s).into_iter().find(|p| p.1 == name).map(|p| p.2).unwrap_or_else(|| panic!("no plane {name}")) } +#[test] +fn construction_plane_names_cannot_be_reused_by_new_features() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "body_name": "Block"})); + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"})); + let before = s.doc.clone(); + for (command, params) in [ + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Mid"})), + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": " Mid "})), + ("sketch.create", json!({"plane": "XY", "name": "Mid"})), + ("solid.box", json!({"length": 1, "width": 1, "height": 1, "name": "Mid"})), + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Box1"})), + ] { + let error = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(error.contains("another feature is called"), "{command}: {error}"); + assert_eq!(s.doc, before, "{command}: a refused creation changes nothing"); + } + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Upper"})); + run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "Upper"})); + let measured = run(&mut s, "inspect.measure", json!({})); + let mirrored = measured["bodies"].as_array().unwrap().iter().find(|b| b["name"] == "Block (2)").unwrap(); + assert_eq!(mirrored["bbox"]["min"][2], 35.0); + assert_eq!(mirrored["bbox"]["max"][2], 40.0); +} + +#[test] +fn redefining_a_construction_plane_keeps_its_existing_name() { + let mut s = Session::default(); + let id = run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"}))["feature"].as_u64().unwrap(); + run(&mut s, "sketch.create", json!({"plane": "Mid", "name": "Profile"})); + run(&mut s, "sketch.finish", json!({})); + run( + &mut s, + "timeline.redefine", + json!({"feature": id, "command": "construct.plane.offset", "params": {"base": "XY", "offset": 20, "name": "Mid"}}), + ); + assert_eq!(s.doc.feature(id).unwrap().name, "Mid"); + assert_eq!(s.doc.features.len(), 2); + assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 20.0))); + run(&mut s, "edit.undo", json!({})); + assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 10.0))); + run(&mut s, "edit.redo", json!({})); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + reopened.refresh(); + assert_eq!(reopened.doc.feature(id).unwrap().name, "Mid"); + assert!(near(plane(&reopened, "Mid").origin, Vec3::new(0.0, 0.0, 20.0))); + assert!(reopened.model.results.iter().all(|r| r.error.is_none())); +} + #[test] fn renamed_construction_references_survive_edits_and_reopening() { let mut s = Session::default(); @@ -108,6 +158,88 @@ fn on_plane(pl: &Plane, p: Vec3) -> bool { (p - pl.origin).dot(pl.normal()).abs() < 1e-3 } +#[test] +fn plane_through_axis_and_point_contains_both_and_rejects_an_on_axis_point() { + let mut s = Session::default(); + run(&mut s, "construct.plane.axis_point", json!({"axis": {"axis": "Z"}, "point": {"point": [10, 20, 30]}, "name": "Fence"})); + let pl = plane(&s, "Fence"); + for p in [Vec3::ZERO, Vec3::Z * 100.0, Vec3::new(10.0, 20.0, 30.0)] { + assert!(on_plane(&pl, p), "{p:?} is on {pl:?}"); + } + assert!(parallel(pl.normal(), Vec3::new(-20.0, 10.0, 0.0))); + let before = s.doc.to_json(); + let error = s.execute("construct.plane.axis_point", &json!({"axis": {"axis": "Z"}, "point": {"point": [0, 0, 50]}})).unwrap_err(); + assert!(error.to_string().contains("point is on the axis"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a degenerate plane leaves the design unchanged"); +} + +#[test] +fn plane_through_axis_and_point_follows_renamed_sources_edits_undo_and_reopen() { + let mut s = Session::default(); + run(&mut s, "construct.axis.two_points", json!({"a":{"point":[5,6,7]},"b":{"point":[5,6,17]},"name":"Spine"})); + run(&mut s, "construct.point.vertex", json!({"point":{"point":[15,6,7]},"name":"Pin"})); + run(&mut s, "construct.plane.axis_point", json!({"axis":{"axis":"Spine"},"point":{"construct_point":"Pin"},"name":"Fence"})); + assert!(parallel(plane(&s, "Fence").normal(), Vec3::Y)); + run(&mut s, "timeline.rename", json!({"feature":"Spine","name":"Mast"})); + run(&mut s, "timeline.rename", json!({"feature":"Pin","name":"Peg"})); + let definition = run(&mut s, "timeline.inspect", json!({"feature":"Fence"})); + assert_eq!(definition["definition"]["plane"]["axis"]["name"], "Mast"); + assert_eq!(definition["definition"]["plane"]["point"]["name"], "Peg"); + run(&mut s, "timeline.edit", json!({"feature":"Peg","set":{"def.point":{"type":"point","p":[5,16,7]}}})); + assert!(parallel(plane(&s, "Fence").normal(), Vec3::X), "point edit rotates the dependent plane"); + run(&mut s, "edit.undo", json!({})); + assert!(parallel(plane(&s, "Fence").normal(), Vec3::Y)); + run(&mut s, "edit.redo", json!({})); + let reopened = solidcraft_doc::format::read(&s.doc.to_json()).unwrap(); + let mut cold = Session::new(reopened); + cold.refresh(); + assert!(cold.model.results.iter().all(|r| r.error.is_none()), "{:?}", cold.model.results); + let pl = plane(&cold, "Fence"); + assert!(parallel(pl.normal(), Vec3::X)); + assert!(on_plane(&pl, Vec3::new(5.0, 16.0, 7.0))); + run(&mut cold, "sketch.create", json!({"plane":"Fence"})); +} + +#[test] +fn plane_through_axis_and_point_accepts_straight_model_and_sketch_lines() { + let mut s = part(); + run(&mut s, "construct.plane.axis_point", json!({"axis":{"edge":[20,0,0]},"point":{"vertex":[40,30,0]},"name":"Base"})); + assert!(parallel(plane(&s, "Base").normal(), Vec3::Z)); + let sk = run(&mut s, "sketch.create", json!({"plane":"XY"}))["sketch"].as_u64().unwrap(); + let line = run(&mut s, "sketch.line", json!({"points":[[0,0],[10,0]]})); + let curve = line["curves"][0].as_str().unwrap(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "construct.plane.axis_point", json!({"axis":{"sketch":sk,"curve":curve},"point":{"point":[0,0,10]},"name":"Side"})); + assert!(parallel(plane(&s, "Side").normal(), Vec3::Y)); +} + +#[test] +fn plane_through_axis_and_point_in_a_moved_component_keeps_its_world_picks() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name":"Part","grounded":false})); + run(&mut s, "occurrence.move", json!({"occurrence":"Part:1","translate":[50,0,0]})); + run(&mut s, "construct.axis.two_points", json!({"a":{"point":[50,0,0]},"b":{"point":[50,0,10]},"name":"Mast"})); + run(&mut s, "construct.plane.axis_point", json!({"axis":{"axis":"Mast"},"point":{"point":[60,0,0]},"name":"Fence"})); + run(&mut s, "occurrence.move", json!({"occurrence":"Part:1","translate":[0,20,0]})); + let pl = plane(&s, "Fence"); + assert!(parallel(pl.normal(), Vec3::Y)); + for p in [Vec3::new(50.0, 20.0, 0.0), Vec3::new(50.0, 20.0, 10.0), Vec3::new(60.0, 20.0, 0.0)] { + assert!(on_plane(&pl, p), "{p:?} on {pl:?}"); + } + run(&mut s, "component.activate", json!({"component":0})); + run( + &mut s, + "timeline.redefine", + json!({"feature":"Fence","command":"construct.plane.axis_point","params":{"axis":{"axis":"Mast"},"point":{"point":[70,20,0]}}}), + ); + let definition = run(&mut s, "timeline.inspect", json!({"feature":"Fence"})); + assert_eq!( + definition["definition"]["plane"]["point"], + json!({"type":"point","p":[20.,0.,0.]}), + "redefine uses the feature's authoring frame, not the active root" + ); +} + #[test] fn axis_through_cylinder_cone_or_torus() { let mut s = part(); @@ -228,6 +360,24 @@ fn point_along_a_path() { run(&mut s, "construct.point.along_path", json!({"path": {"edge": [20, 0, 0]}, "t": 0.25, "name": "P"})); let p = point(&s, "P"); assert!(near(p, Vec3::new(10.0, 0.0, 0.0)) || near(p, Vec3::new(30.0, 0.0, 0.0)), "{p:?}"); + // On an arc it is the arc's own point by arc length, to rounding: a third of a quarter turn + // of radius 10 is 30° round. A t past either end is refused, not moved onto it. + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Round"})); + let arc = run(&mut s, "sketch.arc.center_point", json!({"center": [0, 0], "start": [10, 0], "end": [0, 10]}))["created"]["curves"][0] + .as_str() + .unwrap() + .to_string(); + run(&mut s, "sketch.finish", json!({})); + let path = json!({"sketch": "Round", "curve": arc}); + run(&mut s, "construct.point.along_path", json!({"path": path, "t": "1/3", "name": "Third"})); + let third = point(&s, "Third"); + let want = Vec3::new(10.0 * (std::f64::consts::PI / 6.0).cos(), 5.0, 0.0); + assert!(third.dist(want) < 1e-12, "{third:?} is {:e} off", third.dist(want)); + for t in [json!(1.5), json!(-0.25), json!("2")] { + let e = s.execute("construct.point.along_path", &json!({"path": path, "t": t})).unwrap_err(); + assert!(e.to_string().contains("0 (its start) to 1 (its end)"), "t {t}: {e}"); + assert!(s.execute("construct.plane.along_path", &json!({"path": path, "t": t})).is_err(), "plane at t {t}"); + } } #[test] @@ -276,6 +426,57 @@ fn plane_tangent_to_a_cylinder() { assert!(parallel(u.normal(), Vec3::Z) && on_plane(&u, Vec3::new(3.0, 3.0, 65.0)), "{u:?}"); } +/// #8822: with a reference plane or planar face, the plane touches where the face turns towards +/// the reference (parallel to it, on the side of the pick), turned by an angle about the axis, +/// and follows the reference when it moves. +#[test] +fn plane_tangent_lined_up_with_a_reference() { + let mut s = part(); + // Picked 60° round the cylinder (axis Z through (60, 0)); the XZ plane faces ±Y. + let pick = json!([62.5, 4.330127, 5]); + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"plane": "XZ"}, "name": "T"})); + let t = plane(&s, "T"); + assert!(parallel(t.normal(), Vec3::Y) && on_plane(&t, Vec3::new(60.0, 5.0, 9.0)), "{t:?}"); + // Turned 30° about the axis: still on the pick's side. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"plane": "XZ"}, "angle": "30 deg", "name": "A"})); + let a = plane(&s, "A"); + let d = Vec3::new(-0.5, 3f64.sqrt() / 2.0, 0.0); + assert!(parallel(a.normal(), d) && on_plane(&a, Vec3::new(60.0, 0.0, 2.0) + d * 5.0), "{a:?}"); + // A planar face of the box (x = 40, facing X) as the reference. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"face": [40, 15, 10]}, "name": "F"})); + let f = plane(&s, "F"); + assert!(parallel(f.normal(), Vec3::X) && on_plane(&f, Vec3::new(65.0, 1.0, 1.0)), "{f:?}"); + // The torus (axis Z through (0, 60)): on its outer equator. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": [0, 72, 0]}, "reference": {"plane": "XZ"}, "name": "R"})); + let r = plane(&s, "R"); + assert!(parallel(r.normal(), Vec3::Y) && on_plane(&r, Vec3::new(3.0, 72.0, 1.0)), "{r:?}"); + // The sphere (centre (0, 0, 60)), picked below its middle: under it, parallel to XY. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": [3, 0, 56]}, "reference": {"plane": "XY"}, "name": "U"})); + let u = plane(&s, "U"); + assert!(parallel(u.normal(), Vec3::Z) && on_plane(&u, Vec3::new(1.0, 1.0, 55.0)), "{u:?}"); + + // A reference built on a parameter: the tangent plane follows it. + run(&mut s, "parameters.add", json!({"name": "turn", "expression": "0 deg"})); + run(&mut s, "construct.plane.at_angle", json!({"base": "XZ", "axis": "Z", "angle": "turn", "name": "Ref"})); + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"plane": "Ref"}, "name": "M"})); + assert!(on_plane(&plane(&s, "M"), Vec3::new(60.0, 5.0, 1.0))); + run(&mut s, "parameters.change", json!({"name": "turn", "expression": "-90 deg"})); + let m = plane(&s, "M"); + assert!(parallel(m.normal(), Vec3::X) && on_plane(&m, Vec3::new(65.0, 2.0, 1.0)), "{m:?}"); + + // What has no answer is refused and adds nothing. + let count = construction_planes(&s).len(); + for (p, why) in [ + (json!({"face": {"face": pick}, "reference": {"plane": "XY"}}), "a reference square to the axis"), + (json!({"face": {"face": [3, 0, 56]}, "reference": {"plane": "XY"}, "angle": "10 deg"}), "an angle on a sphere"), + (json!({"face": {"face": pick}, "angle": "10 deg"}), "an angle without a reference"), + (json!({"face": {"face": pick}, "reference": {"plane": "XZ"}, "angle": "2 mm"}), "a length for the angle"), + ] { + assert!(s.execute("construct.plane.tangent", &p).is_err(), "{why}"); + } + assert_eq!(construction_planes(&s).len(), count); +} + #[test] fn plane_along_a_path() { let mut s = part(); @@ -600,3 +801,49 @@ fn offset_plane_through_a_point_follows_the_point() { // A distance and a point at once is refused. assert!(s.execute("construct.plane.offset", &json!({"base": "XY", "offset": 5, "through": {"vertex": [0, 0, 0]}})).is_err()); } + +/// Hiding the placement a component is shown at hides its construction geometry too, as it +/// hides its bodies and sketches. +#[test] +fn hiding_an_occurrence_hides_its_construction_geometry() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Part"})); + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": "5 mm", "name": "Shelf"})); + run(&mut s, "construct.axis.two_planes", json!({"a": "XZ", "b": "YZ", "name": "Spine"})); + run(&mut s, "construct.point.three_planes", json!({"a": "XY", "b": "XZ", "c": "YZ", "name": "Pin"})); + let component = s.doc.features.iter().find(|f| f.name == "Shelf").map(|f| f.component).unwrap(); + assert_ne!(component, 0); + let path = s.doc.first_path(component); + run(&mut s, "component.activate", json!({"component": 0})); + for name in ["Shelf", "Spine", "Pin"] { + assert!(s.construction_visible(name), "{name}"); + } + run(&mut s, "browser.visibility", json!({"paths": [path], "visible": false})); + for name in ["Shelf", "Spine", "Pin"] { + assert!(!s.construction_visible(name), "{name} shows in a hidden placement"); + } +} + +/// #10127: an axis and a point built on a component's cylinder turn with it when Move/Copy +/// turns the cylinder, as its faces do. One also pinned to a fixed point stays where it is. +#[test] +fn construction_on_a_moved_body_moves_with_it() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "body_name": "Pin"})); + run(&mut s, "component.create", json!({"name": "Part", "parent": "root", "activate": false})); + run(&mut s, "component.move_bodies", json!({"bodies": ["Pin"], "component": "Part"})); + run(&mut s, "construct.axis.through_cylinder", json!({"face": {"face": [5, 0, 10]}, "name": "PinAxis"})); + run(&mut s, "construct.point.center", json!({"of": {"edge": [5, 0, 20]}, "name": "PinTop"})); + run(&mut s, "construct.axis.two_points", json!({"a": {"construct_point": "PinTop"}, "b": {"point": [0, 50, 20]}, "name": "Tether"})); + let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap(); + // A quarter turn about Y through the origin, then 10 mm along X: the top centre (0, 0, 20) + // goes to (30, 0, 0), and the cylinder's axis lies along X. + run(&mut s, "solid.move", json!({"bodies": [body], "translate": [10, 0, 0], "axis": [0, 1, 0], "angle": "90 deg"})); + let errors: Vec = s.model.results.iter().filter_map(|r| r.error.clone()).collect(); + assert!(errors.is_empty(), "{errors:?}"); + let (o, d) = axis(&s, "PinAxis"); + assert!(parallel(d, Vec3::X) && on_line(o, d, Vec3::new(30.0, 0.0, 0.0)), "{o:?} {d:?}"); + assert!(near(point(&s, "PinTop"), Vec3::new(30.0, 0.0, 0.0)), "{:?}", point(&s, "PinTop")); + let (o, d) = axis(&s, "Tether"); + assert!(on_line(o, d, Vec3::new(0.0, 0.0, 20.0)) && on_line(o, d, Vec3::new(0.0, 50.0, 20.0)), "{o:?} {d:?}"); +} diff --git a/crates/engine/src/control_auth.rs b/crates/engine/src/control_auth.rs index c93541923..6645a1cfb 100644 --- a/crates/engine/src/control_auth.rs +++ b/crates/engine/src/control_auth.rs @@ -57,12 +57,17 @@ pub fn bind_with_fallback(first: u16, tries: u16) -> Result/control` (`SOLIDCRAFT_CONTROL_DIR` replaces it). fn control_dir() -> Option { - match solidcraft_geom::env::var_os("CONTROL_DIR").filter(|d| !d.is_empty()) { + match custom_control_dir() { Some(d) => Some(PathBuf::from(d)), None => Some(crate::recovery::data_dir()?.join("control")), } } +/// The folder `SOLIDCRAFT_CONTROL_DIR` names in place of the default one. +fn custom_control_dir() -> Option { + solidcraft_geom::env::var_os("CONTROL_DIR").filter(|d| !d.is_empty()) +} + /// The token file of the app listening on `port`: `/control/.token` /// (`SOLIDCRAFT_CONTROL_DIR` replaces the folder). pub fn token_path(port: u16) -> Option { @@ -276,9 +281,19 @@ pub fn tokens_match(a: &str, b: &str) -> bool { /// Write `token` to `path`, readable and writable only by the user: the folder is made `0700` /// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one -/// entry for the user (`icacls`) before the token goes in. A file left by an earlier launch is -/// replaced. The process file beside it ([`pid_path`]) records this process, best effort. +/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file +/// is removed and no token is written. A file left by an earlier launch is replaced. The process +/// file beside it ([`pid_path`]) records this process, best effort. pub fn write_token_file(path: &Path, token: &str) -> Result<()> { + #[cfg(windows)] + let restrict = restrict_to_user; + #[cfg(not(windows))] + let restrict = |_: &Path| Ok(()); + write_token_file_with(path, token, restrict) +} + +/// [`write_token_file`], with `restrict` limiting the new file to the user (Windows). +fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> { let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?; std::fs::create_dir_all(dir)?; let _ = std::fs::remove_file(path); @@ -291,8 +306,11 @@ pub fn write_token_file(path: &Path, token: &str) -> Result<()> { opts.mode(0o600); } let mut f = opts.open(path)?; - #[cfg(windows)] - restrict_to_user(path)?; + if let Err(e) = restrict(path) { + drop(f); + let _ = std::fs::remove_file(path); + return Err(e); + } f.write_all(token.as_bytes())?; f.write_all(b"\n")?; f.sync_all()?; @@ -332,9 +350,32 @@ fn held_by_another(path: &Path, token: &str) -> bool { #[cfg(windows)] const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5); +/// How a run of `icacls` ended. +#[cfg(any(windows, test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IcaclsEnd { + Succeeded, + Failed, + /// It didn't finish within [`ICACLS_LIMIT`] and was ended. + TimedOut, +} + +/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is +/// in the folder `SOLIDCRAFT_CONTROL_DIR` names. A timeout is accepted only in the default folder, +/// the user's own local app data, which other users can't read by default; nothing is known about +/// the permissions of any other folder. +#[cfg(any(windows, test))] +fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> { + match end { + IcaclsEnd::Succeeded => Ok(()), + IcaclsEnd::TimedOut if !custom_folder => Ok(()), + IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))), + IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))), + } +} + /// Windows: drop inherited entries and grant only the current user full access. An `icacls` -/// that doesn't finish in time is ended and the file kept as made: it is in the user's own -/// local app data folder, which other users can't read by default. +/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means. #[cfg(windows)] fn restrict_to_user(path: &Path) -> Result<()> { use std::os::windows::process::CommandExt; @@ -348,10 +389,12 @@ fn restrict_to_user(path: &Path) -> Result<()> { .stderr(std::process::Stdio::null()) .creation_flags(0x0800_0000) .spawn()?; - match wait_within(child, ICACLS_LIMIT)? { - Some(status) if !status.success() => Err(Error::other(format!("icacls failed to restrict {}", path.display()))), - _ => Ok(()), - } + let end = match wait_within(child, ICACLS_LIMIT)? { + Some(status) if status.success() => IcaclsEnd::Succeeded, + Some(_) => IcaclsEnd::Failed, + None => IcaclsEnd::TimedOut, + }; + restriction_result(end, custom_control_dir().is_some(), path) } /// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it @@ -400,6 +443,39 @@ mod tests { assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success())); } + /// #6145's freeze fix stays in the default folder, the user's own; a folder picked with + /// `SOLIDCRAFT_CONTROL_DIR` gets no token unless the file was really restricted. + #[test] + fn only_the_default_folder_accepts_an_icacls_that_timed_out() { + let path = Path::new("control/7878.token"); + for custom in [false, true] { + assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok()); + assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err()); + } + assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok()); + let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::TimedOut); + assert!(e.to_string().contains("7878.token"), "{e}"); + } + + /// A file that couldn't be restricted is removed, empty and with no process file beside it, and + /// the error goes to the caller. A restricted one gets its token. + #[test] + fn a_token_file_that_could_not_be_restricted_is_removed() { + let dir = std::env::temp_dir().join(format!("solidcraft-control-restrict-{}", std::process::id())); + let path = dir.join("7879.token"); + let e = write_token_file_with(&path, "secret-token", |p| { + assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in"); + restriction_result(IcaclsEnd::TimedOut, true, p) + }) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::TimedOut); + assert!(!path.exists() && !pid_path(&path).exists()); + write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap(); + assert_eq!(read_token(&path).as_deref(), Some("secret-token")); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn tokens_compare_whole() { assert!(tokens_match("abc123", "abc123")); diff --git a/crates/engine/src/cosmetic_threads.rs b/crates/engine/src/cosmetic_threads.rs index 4f35f6366..869bfaff1 100644 --- a/crates/engine/src/cosmetic_threads.rs +++ b/crates/engine/src/cosmetic_threads.rs @@ -1,9 +1,11 @@ //! Original schematic cylindrical hatching for evaluated cosmetic threads. The segments lie //! on the displayed triangles, so neither a separate cylinder nor a helical B-rep is needed. +use solidcraft_geom::prelude::*; use std::collections::HashMap; +use solidcore_record::Vec3; use solidcraft_doc::{ModelBody, ThreadInfo}; -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::Mesh; /// Shared upper bound for cosmetic strokes in one viewport/snapshot scene. pub const MAX_SCENE_SEGMENTS: usize = 65_536; @@ -201,9 +203,9 @@ mod tests { fn modeled_threads_do_not_receive_cosmetic_strokes() { let mut s = Session::default(); run(&mut s, "solid.cylinder", json!({"radius":3,"height":4})); - let before = s.world_state().bodies[0].mesh().triangles.len(); + let before = s.world_state().unwrap().bodies[0].mesh().triangles.len(); run(&mut s, "solid.thread", json!({"face":[3,0,3],"designation":"M6","length":2,"modeled":true})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.threads.is_empty()); assert_ne!(st.bodies[0].mesh().triangles.len(), before); assert!(segments(&st.bodies[0], &st.bodies[0].mesh(), &st.threads).is_empty()); @@ -215,7 +217,7 @@ mod tests { run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10})); run(&mut s, "solid.hole", json!({"position":[10,10,10],"direction":[0,0,-1],"thread":"M6"})); run(&mut s, "solid.hole", json!({"position":[10,10,10],"direction":[0,0,-1],"diameter":8,"depth":3})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let body = &st.bodies[0]; let lines = segments(body, &body.mesh(), &st.threads); assert!(!lines.is_empty()); @@ -233,7 +235,7 @@ mod tests { for i in 1..96 { run(&mut s, "occurrence.copy", json!({"component":c["component"],"translate":[i*8,0,0]})); } - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 96); assert_eq!(st.threads.len(), 96); let started = std::time::Instant::now(); @@ -277,7 +279,7 @@ mod tests { let saved = s.doc.to_json(); let reopened = solidcraft_doc::Document::from_json(&saved).unwrap(); let mut s = Session::new(reopened); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.threads.len(), 1); assert!(st.threads[0].axis.z.abs() < 1e-6); let body = &st.bodies[0]; @@ -305,10 +307,10 @@ mod tests { } else { run(&mut s, "solid.cylinder", json!({"radius":3,"height":10,"body_name":"Part"})); } - let before = s.world_state().bodies[0].mesh(); + let before = s.world_state().unwrap().bodies[0].mesh(); let face = if internal { json!([12.5, 10, 9]) } else { json!([3, 0, 9]) }; run(&mut s, "solid.thread", json!({"face":face,"designation":"M6","length":4,"modeled":false})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let body = &st.bodies[0]; assert_eq!(before.positions, body.mesh().positions); assert_eq!(before.triangles, body.mesh().triangles); @@ -336,7 +338,7 @@ mod tests { } } assert_eq!(s.doc.to_json(), saved); - let scene = crate::view::scene(&s, &crate::render::Camera::default()); + let scene = crate::view::scene(&s, &crate::render::Camera::default()).unwrap(); assert!(!scene.lines.iter().any(|l| l.width == 0.85), "ordinary snapshots preserve the default-off behavior"); for distance in [25.0, 60.0] { let cam = crate::render::Camera { @@ -353,7 +355,8 @@ mod tests { &crate::view::Palette::DEFAULT, Default::default(), true, - ); + ) + .unwrap(); assert!(scene.lines.iter().any(|l| l.width == 0.85 && !l.on_top)); let marked = crate::render::render(&scene, &cam, 320, 240).rgba; scene.lines.retain(|l| l.width != 0.85); @@ -363,7 +366,7 @@ mod tests { } } s.execute("edit.undo", &json!({})).unwrap(); - assert!(s.world_state().threads.is_empty()); + assert!(s.world_state().unwrap().threads.is_empty()); } } } diff --git a/crates/engine/src/crash.rs b/crates/engine/src/crash.rs index 18c426b9c..ce2de9480 100644 --- a/crates/engine/src/crash.rs +++ b/crates/engine/src/crash.rs @@ -71,20 +71,23 @@ pub struct Build { pub built: &'static str, } -/// One report, as listed. -#[derive(Clone, Debug, PartialEq, serde::Serialize)] +/// One report, as listed (and as `diagnostics.crash_reports` describes it, #10909). +#[derive(Clone, Debug, PartialEq, serde::Serialize, schemars::JsonSchema)] pub struct Summary { + /// The report's id, which `diagnostics.crash_report` reads. pub id: String, /// `command_panic`, `panic`, `kernel_panic_recovered` or `unclean_exit`. pub kind: String, /// When the report was first recorded (UTC). Unclean exits are recorded at a later launch, /// which may be days after the session ended, rather than at the exact exit time. pub time: String, + /// The internal error's message. pub message: String, /// The command running when it happened, if one was. pub command: Option, /// Times it happened. pub count: u64, + /// The version of SolidCraft it happened in. pub version: String, /// The report's folder. pub path: String, @@ -365,9 +368,22 @@ pub fn phase(step: &str) { j.write(&line); j.phase = Some(line); j.phase_step = Some(step.to_string()); + j.running |= step == RUNNING; } } +/// A step of getting a window's graphics up (egui-wgpu's `window surface`, `surface configure`, +/// …): the [`phase`] until the app is [`RUNNING`], ignored after. A window opened later (the +/// agent chat on its own, say) goes through the same steps, and must not make a crash an hour +/// later read as a crash during startup (#8776). +pub fn startup_step(step: &str) { + let Some(s) = STATE.get() else { return }; + if s.journal.lock().is_ok_and(|j| j.running) { + return; + } + phase(step); +} + /// Where a native crash handler writes what it caught for this run: a small JSON file /// (`code`, `name`, `address`, `module`, `offset`, `detail`, `thread`, and from macOS /// `thread_name` and `frames`) and a minidump. The next @@ -624,6 +640,8 @@ struct Journal { /// The latest startup step's line and name, and the renderer's line (kept across rebases). phase: Option, phase_step: Option, + /// The app reached [`RUNNING`] once: later startup steps are not startup ([`startup_step`]). + running: bool, environment: Option, } @@ -644,6 +662,7 @@ impl Journal { running_at: None, phase: None, phase_step: None, + running: false, environment: None, }; j.rebase(&json!("new"), 0, None); @@ -900,6 +919,7 @@ fn unclean_exit(dir: &Path, build: &Build, journal: &Path) { running_at: None, phase: None, phase_step: None, + running: false, environment: None, }), known: Mutex::new(list(dir).into_iter().filter_map(|s| sig_of(&s.id).map(|sig| (sig, (0, s.id)))).collect()), @@ -1025,6 +1045,9 @@ fn write_report(state: &State, kind: &str, p: Option<&Panic>, extra: Extra) -> O fs::create_dir_all(&folder).ok()?; let mut files = serde_json::Map::new(); let mut notes = extra.notes; + if let Some(call) = solidcraft_kernel::native_call_in_flight() { + notes.push(format!("native kernel call in flight: {call}")); + } if let Some(d) = &extra.design { if d.len() <= MAX_DESIGN_BYTES { let name = format!("design.{}", solidcraft_io::DESIGN_EXT); diff --git a/crates/engine/src/crash_tests.rs b/crates/engine/src/crash_tests.rs index 095ea0495..83ee4f999 100644 --- a/crates/engine/src/crash_tests.rs +++ b/crates/engine/src/crash_tests.rs @@ -50,6 +50,15 @@ fn child() { } std::process::abort(); } + // Up and running, then a second window's surface (the agent chat on its own), then dying. + if mode == "late_surface" { + startup_step("window surface"); + startup_step("surface configure"); + phase(RUNNING); + startup_step("window surface"); + startup_step("surface configure"); + std::process::abort(); + } set_environment("Renderer: test"); let mut s = Session { crash_journal: true, ..Default::default() }; // Where the session's ids stand at the journal's base, its first command. @@ -123,6 +132,29 @@ fn child() { assert_eq!(read_live_journal(state).base, json!({"file":path})); println!("PREPARED_JOURNAL_OK"); } + // Live sketch drag frames store the edited design without copying it again: each + // frame is journaled, and the next frame does not take the design for an outside edit. + "sketch_drag" => { + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + s.execute("sketch.rectangle.two_point", &json!({"p0": [5, 5], "p1": [25, 20]})).unwrap(); + for k in 1..=3 { + let (from, to) = ([6.0 - k as f64, 5.0], [5.0 - k as f64, 5.0]); + s.execute("sketch.drag", &json!({"entity": "l1.start", "from": from, "to": to, "live": true})).unwrap(); + } + s.execute("sketch.drag_end", &json!({})).unwrap(); + let journal = read_live_journal(STATE.get().unwrap()); + assert_eq!(journal.base, json!("new"), "the drag frames continue the replay"); + // The drag's end only evaluates the model: it changes nothing a replay needs. + let ids: Vec<&str> = journal.replay.iter().filter_map(|c| c["command"].as_str()).collect(); + assert_eq!(ids, ["solid.box", "sketch.create", "sketch.rectangle.two_point", "sketch.drag", "sketch.drag", "sketch.drag"]); + let mut replay = Session::default(); + for command in &journal.replay { + replay.execute(command["command"].as_str().unwrap(), &command["params"]).unwrap(); + } + let id = s.active_sketch.unwrap(); + assert_eq!(replay.doc.sketch(id).ok(), s.doc.sketch(id).ok(), "the replay drags the sketch to the same place"); + println!("SKETCH_DRAG_JOURNAL_OK"); + } "render" => { s.execute("render.settings.set", &json!({"name":"Studio","set":{"exposure_ev":2}})).unwrap(); s.execute("render.settings.get", &json!({"name":"Studio"})).unwrap(); @@ -146,8 +178,10 @@ fn child() { s.doc = std::sync::Arc::new(doc); assert!(s.execute("diagnostics.crash_test", &json!({"mode": "panic"})).is_err()); } + // A panic inside a solidcore call: caught there, an internal error of the command. "kernel" => { - assert!(s.execute("diagnostics.crash_test", &json!({"mode": "kernel"})).is_err()); + let r = s.execute("diagnostics.crash_test", &json!({"mode": "kernel"})); + assert!(matches!(&r, Err(crate::EngineError::Internal(id, _)) if id == "diagnostics.crash_test"), "{r:?}"); } // `thread_dies`: the panic ends the app, as one on the window's thread does. "thread" | "thread_dies" => { @@ -218,6 +252,14 @@ fn a_read_only_command_keeps_the_replay_after_body_names_are_pinned() { let _ = fs::remove_dir_all(directory); } +#[test] +fn live_sketch_drag_frames_keep_the_replay() { + let directory = fresh_dir("sketch-drag"); + let (output, ok) = run_child(&directory, "sketch_drag"); + assert!(ok && output.contains("SKETCH_DRAG_JOURNAL_OK"), "{output}"); + let _ = fs::remove_dir_all(directory); +} + fn only_report(dir: &Path) -> (Summary, Value) { let all = list(dir); assert_eq!(all.len(), 1, "{all:?}"); @@ -476,6 +518,21 @@ fn a_crash_signal_is_reported_with_its_thread_and_its_walk_up_the_stack() { let _ = fs::remove_dir_all(&d); } +#[test] +fn a_window_surface_after_startup_is_not_a_startup_crash() { + let d = fresh_dir("late_surface"); + let (_, ok) = run_child(&d, "late_surface"); + assert!(!ok, "the child aborted"); + let (_, ok) = run_child(&d, "none"); + assert!(ok); + let (s, v) = only_report(&d); + assert_eq!(s.kind, "unclean_exit"); + assert!(!s.message.contains("during startup"), "{}", s.message); + assert!(s.message.contains("between commands"), "{}", s.message); + assert!(v.get("startup_phase").is_none(), "{v}"); + let _ = fs::remove_dir_all(&d); +} + #[test] fn startup_steps_survive_a_rebase_and_running_ends_startup() { let d = fresh_dir("rebase"); diff --git a/crates/engine/src/display_mesh_tests.rs b/crates/engine/src/display_mesh_tests.rs index 25d717b72..0c4199a36 100644 --- a/crates/engine/src/display_mesh_tests.rs +++ b/crates/engine/src/display_mesh_tests.rs @@ -1,10 +1,12 @@ //! What the application draws of a large sheet with small bends and holes, and that what //! reads the same mesh (bounds, picks, inside tests) answers as before. +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, TAU}; use serde_json::{Value, json}; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use solidcraft_kernel::{DISPLAY_ANGLE, FaceSurface, face_surface}; use crate::Session; @@ -64,7 +66,7 @@ fn steps_around(m: &Mesh, face: usize, origin: Vec3, axis: Vec3) -> (usize, f64) #[test] fn a_large_sheet_shows_its_small_bends_and_holes_round() { let s = large_sheet(); - let st = s.world_state(); + let st = s.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); assert!(b.body.size() * 1e-3 > 3.0, "the chord tolerance is more than any radius here"); @@ -97,7 +99,7 @@ fn a_large_sheet_shows_its_small_bends_and_holes_round() { } } // And the scene the renderers take draws those same polylines. - let scene = crate::view::scene(&s, &crate::view::home_camera(&s)); + let scene = crate::view::scene(&s, &crate::view::home_camera(&s).unwrap()).unwrap(); let drawn: usize = scene.lines.iter().filter(|l| l.points.iter().all(|p| ((p.x - 30.0).hypot(p.y - 20.0) - 2.0).abs() < 1e-6)).map(|l| l.points.len() - 1).sum(); assert!(drawn >= 2 * (TAU / DISPLAY_ANGLE).ceil() as usize, "{drawn} rim segments in the scene"); @@ -106,10 +108,10 @@ fn a_large_sheet_shows_its_small_bends_and_holes_round() { #[test] fn what_reads_the_display_mesh_of_a_large_sheet_answers_as_before() { let s = large_sheet(); - let st = s.world_state(); + let st = s.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); - let coarse = b.body.display_mesh((b.body.size() * 1e-3).max(1e-3)).unwrap(); + let coarse = b.body.mesh(&solidcraft_kernel::MeshTolerance::chord((b.body.size() * 1e-3).max(1e-3))).unwrap(); // Bounds: the sheet's box is set by flat faces, so the rounder bends move nothing. let (now, before) = (m.bounds(), coarse.bounds()); assert!(now.min.dist(before.min) < 1e-9 && now.max.dist(before.max) < 1e-9, "{now:?} {before:?}"); diff --git a/crates/engine/src/drawing_dimension_paper.rs b/crates/engine/src/drawing_dimension_paper.rs index 7d486aa0b..219f56c43 100644 --- a/crates/engine/src/drawing_dimension_paper.rs +++ b/crates/engine/src/drawing_dimension_paper.rs @@ -8,12 +8,13 @@ use std::f64::consts::{FRAC_1_SQRT_2, PI, TAU}; +use solidcore_record::{Seg2, Vec2}; use solidcraft_doc::drawing::dimension::{Dimension, DimensionKind, Resolved, TextPlace}; use solidcraft_geom::drawing_measure::LinearDirection; use solidcraft_geom::drawing_view::ViewFrame; use solidcraft_geom::paper::annotate::{ArrowShape, Terminator}; use solidcraft_geom::paper::{Group, Item, ObjectKind}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{DimFrame, DimSizes, dim_layout_sized}; /// A dimension's sizes on paper, with its text above an unbroken line (ISO 129-1). diff --git a/crates/engine/src/drawing_dimension_paper_tests.rs b/crates/engine/src/drawing_dimension_paper_tests.rs index 2a7c057fe..6748920f6 100644 --- a/crates/engine/src/drawing_dimension_paper_tests.rs +++ b/crates/engine/src/drawing_dimension_paper_tests.rs @@ -1,8 +1,9 @@ +use solidcore_record::Vec3; use solidcraft_doc::drawing::dimension::{Member, ModelEdge, ModelFace, Silhouette, Status}; +use solidcraft_geom::Aabb2; use solidcraft_geom::drawing_measure::{Measured, Reading, SilhouetteSide}; use solidcraft_geom::drawing_view::{NamedView, Scale}; use solidcraft_geom::paper::Scene; -use solidcraft_geom::{Aabb2, Vec3}; use super::*; diff --git a/crates/engine/src/drawing_dimension_tests.rs b/crates/engine/src/drawing_dimension_tests.rs index db743ffda..024670d3d 100644 --- a/crates/engine/src/drawing_dimension_tests.rs +++ b/crates/engine/src/drawing_dimension_tests.rs @@ -5,6 +5,7 @@ use std::collections::BTreeSet; use std::sync::Arc; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::ModelBody; use solidcraft_doc::appearance::face_index_at; use solidcraft_doc::drawing::dimension::{ @@ -15,10 +16,10 @@ use solidcraft_doc::drawing::{Drawing, Source, Units}; use solidcraft_doc::drawing_view::{ViewDirection, ViewOverrides}; use solidcraft_doc::ids::IdSource; use solidcraft_doc::naming::{edge_names, face_names}; -use solidcraft_geom::Vec3; use solidcraft_geom::drawing_measure::{LinearDirection, Reading, SilhouetteSide}; use solidcraft_geom::drawing_sheet::{Orientation, PaperSize, Sheet}; use solidcraft_geom::drawing_view::{NamedView, ProjectedSide}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -504,7 +505,7 @@ fn flat_faces_are_measured_when_their_corners_are_gone() { assert!(spans(&r.points[..2], 0.0) && spans(&r.points[2..], 80.0), "{r:?}"); let along = f.add(f.front, kind(LinearDirection::Horizontal), None); assert_reads(&f.resolve(along), 80.0, false); - let diagonal = f.add(f.front, kind(LinearDirection::Along(solidcraft_geom::Vec2::new(1.0, 1.0))), None); + let diagonal = f.add(f.front, kind(LinearDirection::Along(solidcore_record::Vec2::new(1.0, 1.0))), None); assert!((f.resolve(diagonal).measured.unwrap().value - 80.0 * 2f64.sqrt()).abs() < 1e-9); let seen = f.add(f.right, kind(LinearDirection::Aligned), None); assert!(matches!(&f.resolve(seen).status, Status::Unmeasurable(why) if why.contains("edge-on")), "{:?}", f.resolve(seen)); @@ -546,14 +547,9 @@ fn a_flat_face_that_isnt_one_face_or_isnt_parallel_says_so() { assert_eq!(f.resolve(id).status, Status::Suppressed); } -fn radial(edge: &ModelEdge, diameter: bool) -> DimensionKind { - DimensionKind::Radial { edge: edge.clone(), diameter } -} - /// A boss of radius 5 along X on the box's right face reads Ø10 between its silhouettes in the front /// view, exactly, with its silhouettes 10 apart from one end of it to the other. A notch across its -/// top cuts its face into pieces, all on the one cylinder, so it still reads Ø10 (found through -/// pieces, so not exactly). The right view looks along its axis, so it can't be measured there; +/// top leaves it the one cylindrical face, so it still reads Ø10, exactly. The right view looks along its axis, so it can't be measured there; /// with the boss suppressed it is lost. #[test] fn a_cylinders_diameter_is_found_through_all_its_faces() { @@ -575,7 +571,7 @@ fn a_cylinders_diameter_is_found_through_all_its_faces() { run(&mut f.s, "solid.box", json!({"length": 2, "width": 50, "height": 3, "corner": [89, -1, 18], "operation": "cut", "targets": ["Box"]})); let r = f.resolve(front); assert_reads(&r, 10.0, false); - assert!(!r.exact, "found through pieces: {r:?}"); + assert!(r.exact, "the notch leaves one cylindrical face: {r:?}"); run(&mut f.s, "timeline.suppress", json!({"feature": boss, "suppressed": true})); let r = f.resolve(front); // The boss that made its face is suppressed, so the dimension says so: it isn't lost. diff --git a/crates/engine/src/drawing_picture_tests.rs b/crates/engine/src/drawing_picture_tests.rs index cb99e0d1e..bb353095c 100644 --- a/crates/engine/src/drawing_picture_tests.rs +++ b/crates/engine/src/drawing_picture_tests.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_render::VisualStyle::{Shaded, Visible, VisibleHidden}; use super::*; @@ -54,7 +55,7 @@ fn bodies_placed_through_a_reference_component_are_reference_parts() { run(&mut s, "component.activate", json!({"component": 0})); run(&mut s, "occurrence.copy", json!({"component": "Hinge", "translate": [0, 50, 0]})); let pin = s.doc.find_component("Pin").unwrap(); - let pins = |s: &Session| s.world_state().bodies.iter().map(|b| b.component == pin).collect::>(); + let pins = |s: &Session| s.world_state().unwrap().bodies.iter().map(|b| b.component == pin).collect::>(); assert_eq!(pins(&s).iter().filter(|p| **p).count(), 2, "{:?}", pins(&s)); assert_eq!(reference_flags(&s), vec![false; pins(&s).len()]); for reference in ["Hinge", "Pin"] { diff --git a/crates/engine/src/drawing_pictures.rs b/crates/engine/src/drawing_pictures.rs index bf02e8f1c..4daee0881 100644 --- a/crates/engine/src/drawing_pictures.rs +++ b/crates/engine/src/drawing_pictures.rs @@ -11,13 +11,14 @@ use std::cell::OnceCell; use std::collections::BTreeMap; +use solidcore_record::Vec2; use solidcraft_doc::canvas::base64_decode; use solidcraft_doc::drawing::Drawing; use solidcraft_doc::drawing::image::{ImageFile, SheetImage}; use solidcraft_doc::ids; +use solidcraft_geom::Aabb2; use solidcraft_geom::paper::{Group, Item, MAX_IMAGE_PIXELS, ObjectKind, Picture, Pictures}; use solidcraft_geom::pixel_grid::{GridWindow, PixelGrid}; -use solidcraft_geom::{Aabb2, Vec2}; use solidcraft_render::sheet_image; use crate::Session; diff --git a/crates/engine/src/drawing_scene.rs b/crates/engine/src/drawing_scene.rs index 2e62dcc36..5fbc5ea6f 100644 --- a/crates/engine/src/drawing_scene.rs +++ b/crates/engine/src/drawing_scene.rs @@ -30,6 +30,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; use solidcraft_doc::drawing::dimension::{self, Dimension}; use solidcraft_doc::drawing::view::{ResolvedView, View}; use solidcraft_doc::drawing::{Drawing, Sheet}; @@ -39,7 +40,8 @@ use solidcraft_geom::cell::Projection; use solidcraft_geom::drawing_view::ViewFrame; use solidcraft_geom::paper::text::TextRun; use solidcraft_geom::paper::{Group, Item, MAX_RECORDS, ObjectKind, Picture, Scene}; -use solidcraft_geom::{Aabb2, ArcMap, Loop2, Region2, Seg2, Vec2}; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Aabb2, ArcMap}; use crate::drawing_picture::{picture_items, view_parts}; use crate::drawing_view::{CHORD_MM, LineRequest, MIN_MODEL_CHORD_MM, ShownSet, Stats, Styles, Unmeasured, paper_group}; @@ -595,12 +597,12 @@ pub struct ViewStanding { /// is on. It reads the cache: nothing is drawn. A view that drew but didn't fit its sheet's scene is /// as the last assembly left it, while that is still its sheet's scene ([`Cache::assembled`]). pub fn standing(s: &Session, d: &Drawing) -> Vec { - let state = s.world_state(); + let state = s.world_state().ok(); let cache = &s.drawing_scenes; let assembled = cache.assembled(d).unwrap_or_default(); let in_assembly = |id: u64| assembled.binary_search_by_key(&id, |v| v.view).ok().and_then(|at| assembled.get(at)); let one = |view: &Arc| { - let fresh = d.resolve_view(view.id).is_ok_and(|resolved| cache.fresh(view.id, &state, &resolved)); + let fresh = d.resolve_view(view.id).is_ok_and(|resolved| state.as_ref().is_some_and(|state| cache.fresh(view.id, state, &resolved))); let (status, reason) = match cache.views.get(&view.id).filter(|_| fresh) { Some(entry) => { let status = in_assembly(view.id).map_or(&entry.drawn.status, |v| &v.status); @@ -618,7 +620,7 @@ pub fn standing(s: &Session, d: &Drawing) -> Vec { pub fn extract(s: &mut Session, sheet: u64) -> Result { forget_closed(s); let d = s.drawing(CMD)?.clone(); - let state = s.world_state(); + let state = s.world_state()?; let units = s.doc.drawing_units(&d).to_string(); let cache = &mut s.drawing_scenes; if let Some(last) = &cache.last @@ -665,7 +667,7 @@ pub fn step(s: &mut Session) -> bool { forget_closed(s); let (Ok(d), Some(sheet)) = (s.drawing(CMD).cloned(), s.drawing_scenes.sheet) else { return false }; let Ok(on) = views_on(&d, sheet) else { return false }; - let state = s.world_state(); + let Ok(state) = s.world_state() else { return false }; let units = s.doc.drawing_units(&d).to_string(); let waiting: Vec<(u64, ResolvedView)> = on.iter().filter(|(id, view, _)| !s.drawing_scenes.fresh(*id, &state, view)).map(|(id, view, _)| (*id, *view)).collect(); diff --git a/crates/engine/src/drawing_scene_tests.rs b/crates/engine/src/drawing_scene_tests.rs index 649c22193..47c52dd8a 100644 --- a/crates/engine/src/drawing_scene_tests.rs +++ b/crates/engine/src/drawing_scene_tests.rs @@ -1057,7 +1057,7 @@ fn a_dimension_past_the_scenes_limits_is_left_out_and_says_why() { status: Status::Drawn, stats: None, boundary: None, - frame: Some(ViewFrame::new(solidcraft_geom::Plane::XY, "1:1".parse().unwrap(), Vec2::ZERO, Vec2::ZERO).unwrap()), + frame: Some(ViewFrame::new(solidcore_record::Plane::XY, "1:1".parse().unwrap(), Vec2::ZERO, Vec2::ZERO).unwrap()), }; let mut assembly = assemble(record, Projection::Third, &[], std::iter::once((front, Vec2::new(100.0, 100.0), view))).unwrap(); let stroke = |to: Vec2| Item::Stroke { path: vec![Seg2::Line { a: Vec2::ZERO, b: to }], closed: false, width_mm: 0.25, pattern: None }; diff --git a/crates/engine/src/drawing_view.rs b/crates/engine/src/drawing_view.rs index 3e6ce9afb..87a953f96 100644 --- a/crates/engine/src/drawing_view.rs +++ b/crates/engine/src/drawing_view.rs @@ -11,11 +11,12 @@ use std::collections::{BTreeMap, HashSet}; use std::fmt; use std::sync::Arc; +use solidcore_record::{Plane, Vec2}; use solidcraft_doc::drawing::view::ResolvedView; use solidcraft_doc::drawing::{Drawing, Sheet}; use solidcraft_doc::{MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, ModelBody, ModelState, ids}; use solidcraft_geom::drawing_view::{Scale, ViewFrame}; -use solidcraft_geom::{Aabb2, EPS, Plane, Vec2}; +use solidcraft_geom::{Aabb2, EPS}; use solidcraft_render::VisualStyle; use crate::params::bad; @@ -48,6 +49,8 @@ pub enum Unmeasured { /// The assembly places more than a view walks, so a view of it would leave parts out. PastWalkLimit, NoBodies, + /// The bodies of the assembly can't be placed. + NotPlaced, } impl Unmeasured { @@ -56,6 +59,7 @@ impl Unmeasured { match self { Unmeasured::PastWalkLimit => "past_walk_limit", Unmeasured::NoBodies => "no_bodies", + Unmeasured::NotPlaced => "not_placed", } } } @@ -68,6 +72,7 @@ impl fmt::Display for Unmeasured { "the assembly is deeper than {MAX_PLACEMENT_DEPTH} levels or has more than {MAX_PLACEMENTS} placements: a view of it would leave parts out" ), Unmeasured::NoBodies => f.write_str("the view's source has no bodies"), + Unmeasured::NotPlaced => f.write_str("the assembly's bodies can't be placed"), } } } @@ -151,7 +156,7 @@ pub fn shown(s: &Session) -> std::result::Result { if !s.doc.placements_complete() { return Err(Unmeasured::PastWalkLimit); } - let state = s.world_state(); + let state = s.world_state().map_err(|_| Unmeasured::NotPlaced)?; // The world state names each placed body as this walk does, so its name finds its path. let mut placed: BTreeMap, String)> = s.doc.body_frames_with_source(&s.model.state()).into_iter().map(|(name, body, _, path, _)| (name, (path, body))).collect(); diff --git a/crates/engine/src/drawing_view_lines.rs b/crates/engine/src/drawing_view_lines.rs index 382bc95f4..797ae314c 100644 --- a/crates/engine/src/drawing_view_lines.rs +++ b/crates/engine/src/drawing_view_lines.rs @@ -7,12 +7,15 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; use solidcraft_doc::Mat; use solidcraft_geom::drawing_view::ViewFrame; use solidcraft_geom::hlr::{Source, Visibility}; use solidcraft_geom::paper::{Group, Item, MAX_RECORDS, ObjectKind}; +use solidcraft_geom::prelude::*; use solidcraft_geom::section::CurveAccuracy; -use solidcraft_geom::{Aabb2, EPS, Plane, Seg2, Similarity2, Vec2, Vec3}; +use solidcraft_geom::{Aabb2, EPS, Similarity2}; +use solidcraft_kernel::PlanarPiece; use super::ShownSet; use crate::mesh_lines::{self, Ask, Origin, Owner, Scene, View}; @@ -248,14 +251,7 @@ fn exact_arcs(shown: &ShownSet, scene: &Scene, basis: &Plane, runs: &[(Owner, Ve let Some(body) = shown.bodies.get(first as usize).and_then(|b| shown.body(b)) else { continue }; let edges: Vec = edges.into_iter().collect(); let exact = body.body.planar_edges(basis, &edges); - let arcs = edges - .iter() - .zip(exact) - .filter_map(|(edge, segs)| match segs.as_deref() { - Some([arc @ Seg2::Arc { .. }]) => Some((*edge, *arc)), - _ => None, - }) - .collect(); + let arcs = edges.iter().zip(exact).filter_map(|(edge, pieces)| one_arc(pieces.as_deref()?).map(|arc| (*edge, arc))).collect(); found.insert(key, (first, arcs)); } let mut out = HashMap::new(); @@ -273,6 +269,26 @@ fn exact_arcs(shown: &ShownSet, scene: &Scene, basis: &Plane, runs: &[(Owner, Ve out } +/// An edge's pieces as one arc: the kernel gives a whole circle as two half circles. `None` unless +/// every piece is an arc of one circle, each going on from where the last one ended. +fn one_arc(pieces: &[PlanarPiece]) -> Option { + let arcs = |piece: &PlanarPiece| match *piece { + PlanarPiece::Seg(Seg2::Arc { center, radius, start, sweep }) => Some((center, radius, start, sweep)), + _ => None, + }; + let (center, radius, start, mut sweep) = arcs(pieces.first()?)?; + for piece in pieces.get(1..)? { + let (c, r, s, turn) = arcs(piece)?; + let on_from_last = (start + sweep - s).rem_euclid(std::f64::consts::TAU); + let on_from_last = on_from_last.min(std::f64::consts::TAU - on_from_last); + if c.dist(center) > radius * 1e-9 || (r - radius).abs() > radius * 1e-9 || on_from_last > 1e-9 { + return None; + } + sweep += turn; + } + Some(Seg2::Arc { center, radius, start, sweep }) +} + /// A placement's turn: its matrix's rotation, bit for bit. fn turn(m: &Mat) -> [u64; 9] { [m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]].map(f64::to_bits) diff --git a/crates/engine/src/exact_tool_tests.rs b/crates/engine/src/exact_tool_tests.rs index dc29b3c4c..87cf2a4d1 100644 --- a/crates/engine/src/exact_tool_tests.rs +++ b/crates/engine/src/exact_tool_tests.rs @@ -4,7 +4,7 @@ //! (a cut) or material (a join) on the bodies' faces, not just at a few sample points. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -20,7 +20,10 @@ fn volume(s: &Session, body: &str) -> f64 { } fn has(s: &Session, body: &str, at: [f64; 3]) -> bool { - s.model.state().body(body).is_some_and(|b| b.body.contains(Vec3::new(at[0], at[1], at[2]))) + s.model + .state() + .body(body) + .is_some_and(|b| b.body.classify_point(Vec3::new(at[0], at[1], at[2])).unwrap() == solidcraft_kernel::PointClass::Inside) } fn bodies(s: &Session) -> Vec { diff --git a/crates/engine/src/extent_tests.rs b/crates/engine/src/extent_tests.rs index 852a271ef..8a836ce2d 100644 --- a/crates/engine/src/extent_tests.rs +++ b/crates/engine/src/extent_tests.rs @@ -181,3 +181,56 @@ fn extrude_to_a_cylinder_beside_another_body() { assert!((end + (2.75f64 * 2.75 - 1.5 * 1.5).sqrt()).abs() < 1e-3, "{b}"); assert!((b["bbox"]["min"][0].as_f64().unwrap_or(0.0) + 98.0).abs() < 1e-6, "{b}"); } + +/// A window cut To Object through the side of a tube (r 20 outside, 18 inside), up to the inside +/// face: it takes the wall under the profile and nothing else. Before, the tool ended in the +/// curved inner face: the tool less the tube kept only the air before the wall and cut nothing, +/// or the boolean failed on the coincident curved faces. Picking the outside face from inside +/// the wall cuts back to it. +#[test] +fn cut_to_the_far_side_of_a_curved_wall() { + let tube = || { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 20, "height": 20, "body_name": "Tube"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bore"})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 18})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Bore", "distance": 20, "operation": "cut"})); + s + }; + let volume = |s: &mut Session| body(s, "Tube")["volume_mm3"].as_f64().unwrap_or(0.0); + let wall = |x: f64, r: f64| (r * r - x * x).sqrt(); + let n = 2000; + let between = |r0: f64, r1: f64| -> f64 { + (0..n).map(|i| -3.0 + 6.0 * (i as f64 + 0.5) / n as f64).map(|x| (wall(x, r1) - wall(x, r0)) * 4.0 * 6.0 / n as f64).sum() + }; + // From outside the tube, through the wall, to its inside face. + let mut s = tube(); + let whole = volume(&mut s); + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, -30, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Window"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-3, 8], "p1": [3, 12]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Window", "to": [0, -18, 10], "operation": "cut"})); + let removed = whole - volume(&mut s); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + // The same window cut 20 mm, ending in the bore: the tube's own facets set its volume. + let mut plain = tube(); + run(&mut plain, "sketch.create", json!({"plane": {"origin": [0, -30, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Window"})); + run(&mut plain, "sketch.rectangle.two_point", json!({"p0": [-3, 8], "p1": [3, 12]})); + run(&mut plain, "sketch.finish", json!({})); + run(&mut plain, "solid.extrude", json!({"sketch": "Window", "distance": -20, "operation": "cut"})); + let reference = whole - volume(&mut plain); + assert!((removed - reference).abs() < reference * 1e-6, "removed {removed}, a 20 mm cut {reference}"); + let want = between(18.0, 20.0); + assert!((removed - want).abs() < want * 2e-2, "removed {removed}, want {want}"); + // From inside the wall (y = -19) back out to the outside face. + let mut s = tube(); + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, -19, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Window"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-3, 8], "p1": [3, 12]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Window", "to": [0, -20, 10], "operation": "cut"})); + let removed = whole - volume(&mut s); + let want: f64 = (0..n).map(|i| -3.0 + 6.0 * (i as f64 + 0.5) / n as f64).map(|x| (wall(x, 20.0) - 19.0) * 4.0 * 6.0 / n as f64).sum(); + assert!((removed - want).abs() < want * 2e-2, "removed {removed}, want {want}"); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); +} diff --git a/crates/engine/src/face_name_tests.rs b/crates/engine/src/face_name_tests.rs index e2e5b9b13..f7e1a18ee 100644 --- a/crates/engine/src/face_name_tests.rs +++ b/crates/engine/src/face_name_tests.rs @@ -4,7 +4,7 @@ use std::f64::consts::PI; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -43,8 +43,8 @@ fn top_and_hole_names(s: &mut Session) -> (String, Vec) { } /// A 60 x 40 x 10 plate with a hole of radius 5: its top face is a rectangle with a hole in it, -/// whose centroid (the plate's middle, (30, 20, 10)) is in the hole; the hole's wall is two half -/// cylinders, whose centroids are inside the cylinder, 2r/π from its axis. +/// whose centroid (the plate's middle, (30, 20, 10)) is in the hole; the hole's wall is one +/// whole cylinder (SMLib's, closed on its seam), whose centroid is on its axis, halfway up. #[test] fn model_faces_gives_a_point_on_each_face_and_the_hole_axis_and_radius() { let mut s = Session::default(); @@ -61,10 +61,10 @@ fn model_faces_gives_a_point_on_each_face_and_the_hole_axis_and_radius() { Some(c) => { let radial = (at.x - 30.0).hypot(at.y - 20.0); assert!((radial - 5.0).abs() < 1e-9 && at.z > 0.0 && at.z < 10.0, "{at:?}"); - // The centroid of a half cylinder's wall is 2r/π = 3.18 from the axis, not on the wall. + // The centroid of a whole cylinder's wall is on its axis, not on the wall. let centroid = vec(&f["centroid"]); let inside = (centroid.x - 30.0).hypot(centroid.y - 20.0); - assert!((2.5..4.0).contains(&inside), "the centroid of a half cylinder is inside it: {inside}"); + assert!(inside < 1e-9 && (centroid.z - 5.0).abs() < 1e-9, "the centroid of the hole's wall is on its axis: {centroid:?}"); // The hole's axis: the line through (30, 20) along z, its radius 5. let (origin, axis) = (vec(&c["origin"]), vec(&c["axis"])); assert!((origin.x - 30.0).abs() < 1e-9 && (origin.y - 20.0).abs() < 1e-9, "{origin:?}"); @@ -122,10 +122,11 @@ fn convert_to_sheet_metal_takes_the_plates_face_by_name() { let span = at.iter().cloned().fold(f64::MIN, f64::max) - at.iter().cloned().fold(f64::MAX, f64::min); assert!(span > 9.8 && span < 10.0 + 1e-6, "{span}"); } - // The plate is still 100 x 60 x 2.5 less the hole: 15000 - π·5²·2.5 = 14803.65 mm³ for a round hole, a little more - // (less than 2% of the hole's 196.35 mm³) for a polygon inside the circle. + // The plate is still 100 x 60 x 2.5 less the hole, which is round: 15000 - π·5²·2.5 = + // 14803.65 mm³, within the measure's accuracy (SMLib's mass properties come within 2e-7 of + // a closed form). let (v, round) = (volume(&mut s, "Plate"), 15000.0 - 25.0 * PI * 2.5); - assert!(v >= round - 1e-6 && v - round < 0.02 * 25.0 * PI * 2.5, "{v}"); + assert!((v - round).abs() < 2e-7 * round, "{v} vs {round}"); } /// Shell, draft and offset face share the parser of Delete Face. @@ -207,8 +208,8 @@ fn offset_face_takes_the_face_by_name() { assert!((volume(&mut s, "Tray") - 100.0 * 60.0 * 35.0).abs() < 1e-6, "{}", volume(&mut s, "Tray")); } -/// A cylinder of radius 10 and height 20 has a side of two half cylinders, each of which -/// `model.faces` describes (its axis and radius); drafting them 5 degrees from the base plane makes +/// A cylinder of radius 10 and height 20 has one side face (SMLib's, closed on its seam), which +/// `model.faces` describes (its axis and radius); drafting it 5 degrees from the base plane makes /// a frustum of radius 10 at the base and 10 - 20 tan 5 degrees at the top. #[test] fn draft_takes_a_cylinders_side_by_name() { @@ -216,7 +217,7 @@ fn draft_takes_a_cylinders_side_by_name() { run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20, "body_name": "Pin"})); let all = faces(&mut s, "Pin"); let sides: Vec<&Value> = all.iter().filter(|f| f.get("cylinder").is_some()).collect(); - assert_eq!(sides.len(), 2, "two half cylinders: {all:?}"); + assert_eq!(sides.len(), 1, "one side: {all:?}"); for side in &sides { assert!((side["cylinder"]["radius"].as_f64().unwrap_or(f64::NAN) - 10.0).abs() < 1e-9, "{side}"); } @@ -240,3 +241,81 @@ fn replace_face_takes_the_face_by_name() { // A's top moves up to B's, 15 high: 10 x 10 x 15. assert!((volume(&mut s, "A") - 1500.0).abs() < 1e-6, "{}", volume(&mut s, "A")); } + +/// A face name on two bodies, each with one such face (two bodies one extrude made, the pieces of +/// a split body), is not a split face: a hole placed on one of them gives no warning (#10699). +#[test] +fn a_face_name_on_two_bodies_is_no_split_face() { + let said = |s: &Session, feature: &str| { + let r = s.model.result(s.doc.find_feature(feature).unwrap().id).unwrap(); + format!("{}{}", r.error.clone().unwrap_or_default(), r.warning.clone().unwrap_or_default()) + }; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [14, 0], "p1": [24, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 10, "operation": "new"})); + run(&mut s, "solid.hole", json!({"position": [5, 5, 10], "diameter": 5, "depth": 5, "name": "Hole1"})); + assert_eq!(said(&s, "Hole1"), ""); + assert!((volume(&mut s, "Body1") - (1000.0 - PI * 2.5 * 2.5 * 5.0)).abs() < 0.1); + assert!((volume(&mut s, "Body2") - 1000.0).abs() < 1e-6); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10})); + run(&mut s, "solid.split_body", json!({"body": "Body1", "plane": {"origin": [20, 0, 0], "normal": [1, 0, 0]}})); + run(&mut s, "solid.hole", json!({"position": [30, 10, 10], "diameter": 5, "name": "Hole1", "targets": ["Body1"]})); + assert_eq!(said(&s, "Hole1"), ""); +} + +/// A plate with a round wall on each long side, and a tall tab with a curved notch joined to its +/// far end, 12 mm from those walls: this join reports no history, and the bigger body meshes the +/// walls differently. Returns the plate's and the tab's feature ids. +fn plate_and_notched_tab(s: &mut Session) -> (Option, Option) { + let reach = 57.0_f64.sqrt(); // Where a circle of radius 11 meets y = ±8. + run(s, "sketch.create", json!({"plane": "XY"})); + run(s, "sketch.rectangle.two_point", json!({"p0": [-20, -8], "p1": [20, 8]})); + run(s, "sketch.arc.three_point", json!({"start": [-reach, 8], "end": [reach, 8], "through": [0, 11]})); + run(s, "sketch.arc.three_point", json!({"start": [-reach, -8], "end": [reach, -8], "through": [0, -11]})); + run(s, "sketch.finish", json!({})); + let plate = run(s, "solid.extrude", json!({"distance": 10, "name": "Plate"}))["feature"].as_u64(); + run(s, "sketch.create", json!({"plane": {"face": [20, 0, 5]}, "project_edges": false})); + run(s, "sketch.line", json!({"points": [[-8, -5], [8, -5], [8, 23], [-8, 23], [-8, -5]]})); + run(s, "sketch.circle.center", json!({"center": [0, 23], "radius": 8.0667})); + run(s, "sketch.finish", json!({})); + let tab = + run(s, "solid.extrude", json!({"distance": 10, "operation": "join", "name": "Tab", "profiles": [{"point": [0, -3]}]}))["feature"].as_u64(); + (plate, tab) +} + +/// The round walls stay the plate's whole, and an edge picked on one stores no trace of the tab. +#[test] +fn a_join_that_makes_the_body_bigger_leaves_round_walls_it_never_touched_alone() { + let mut s = Session::default(); + let (plate, tab) = plate_and_notched_tab(&mut s); + let tab_name = format!("F{}", tab.unwrap_or_default()); + let made_by = |face: &Value| face["name"].as_str().and_then(solidcraft_doc::persistent_name::made_by); + let all = faces(&mut s, "Body1"); + let round: Vec<&Value> = all.iter().filter(|f| f.get("plane_normal").is_none_or(Value::is_null)).collect(); + let walls: Vec<&&Value> = round.iter().filter(|f| vec(&f["point"]).x < 15.0).collect(); + assert_eq!(walls.len(), 2, "{all:?}"); + for wall in walls { + assert_eq!(made_by(wall), plate, "{wall}"); + assert!(wall["name"].as_str().is_some_and(|name| !name.contains(&tab_name)), "{wall}"); + } + assert!(round.iter().filter(|f| vec(&f["point"]).x > 20.0).all(|notch| made_by(notch) == tab), "{all:?}"); + + let volume_before = volume(&mut s, "Body1"); + run(&mut s, "solid.fillet", json!({"edges": [[0, -11, 10]], "radius": 1, "name": "Round"})); + assert!(volume(&mut s, "Body1") < volume_before); + let filleted = volume(&mut s, "Body1"); + let round_id = s.doc.features.iter().position(|f| f.name == "Round").unwrap(); + assert!(s.doc.features[round_id].edge_names.iter().all(|name| !name.contains(&tab_name)), "{:?}", s.doc.features[round_id].edge_names); + + // A design saved while the wall was named after the tab still finds its edge. + let mut saved = (*s.doc).clone(); + saved.features[round_id].edge_names = vec![format!("F2:top|{tab_name}:side:l4#[F2:side:l1]")]; + let mut reopened = Session::opened_at(saved, None, None); + let result = reopened.model.result(reopened.doc.features[round_id].id).unwrap(); + assert!(!result.skipped && result.error.is_none(), "{:?}", result.error); + assert!((volume(&mut reopened, "Body1") - filleted).abs() < 1e-6); +} diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index 48b5b269b..5591dedec 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -10,8 +10,9 @@ //! without moved components). use serde_json::{Map, Value}; +use solidcore_record::Vec3; use solidcraft_doc::{Mat, apply_point, apply_vector, is_identity, map_point_expr, map_vector_expr, mat_inverse}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use crate::Session; @@ -61,7 +62,7 @@ fn table(id: &str) -> &'static [(&'static str, K)] { "solid.hole" => &[("position", Pick), ("direction", Dir), ("body", Body)], "solid.scale" => &[("origin", Make), ("bodies", Body)], "solid.offset_face" | "solid.shell" => &[("faces", Picks), ("body", Body)], - "solid.thread" => &[("face", Pick)], + "solid.thread" => &[("face", Pick), ("from", Pick), ("up_to", Plane)], "solid.emboss" => &[("face", Make)], "solid.draft" => &[("faces", Picks), ("neutral", Plane), ("pull", Dir), ("body", Body)], "solid.press_pull" => &[("face", Pick), ("edges", Picks)], @@ -90,7 +91,9 @@ fn table(id: &str) -> &'static [(&'static str, K)] { "sketch.project_to_surface" | "sketch.isoparametric_curve" => &[("face", Here)], "sketch.intersection_curve" => &[("a", Here), ("b", Here)], "inspect.curvature_comb" | "inspect.minimum_radius" | "inspect.isocurve" => &[("edges", Picks), ("faces", Picks)], - "parts.insert" | "parts.fastener" => &[("at", Pick), ("point", Make), ("direction", Dir)], + // A fastener's `at` picks locate host occurrences and feed joint.create in world + // coordinates. Only free placement belongs in the active component's frame. + "parts.insert" | "parts.fastener" => &[("point", Make), ("direction", Dir)], "appearance.assign" => &[("faces", Picks), ("bodies", Body), ("body", Body)], "solid.move" => &[("bodies", Body), ("translate", Delta), ("axis", Dir), ("origin", Moved)], "solid.combine" => &[("target", Body), ("tools", Body)], @@ -147,13 +150,12 @@ fn pt(p: Vec3) -> Value { /// The frame of the body a world point lies on (the nearest), or of the named body, with the /// bodies whose faces meet there: the first is the body under the point, and more than one /// means the pick is ambiguous. -fn frame_at(s: &Session, f: &Frames, p: Vec3, body: Option<&str>) -> Option<(Mat, Vec)> { +fn frame_at(s: &Session, world: &solidcraft_doc::ModelState, f: &Frames, p: Vec3, body: Option<&str>) -> Option<(Mat, Vec)> { if let Some(b) = body && let Some((_, own, m)) = f.bodies(s).iter().find(|(w, _, _)| w == b) { return Some((*m, vec![own.clone()])); } - let world = s.world_state(); let mut best: Option<(f64, Mat, Vec)> = None; for wb in &world.bodies { let Some((_, own, m)) = f.bodies(s).iter().find(|(w, _, _)| *w == wb.name) else { continue }; @@ -199,7 +201,10 @@ fn tri_dist(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 { } struct Mapper<'a> { + /// The session the body frames are read from (only when a pick needs them). s: &'a Session, + /// The placed model the picks are on. + world: &'a solidcraft_doc::ModelState, f: Frames, /// The frame of the command's first pick (its directions turn with it). first: Option, @@ -211,7 +216,7 @@ struct Mapper<'a> { impl Mapper<'_> { fn pick(&mut self, v: &Value, body: Option<&str>) -> Option { let p = vec3(v)?; - let under = if self.here { None } else { frame_at(self.s, &self.f, p, body) }; + let under = if self.here { None } else { frame_at(self.s, self.world, &self.f, p, body) }; let m = if self.here { self.f.sketch } else { under.as_ref().map(|(m, _)| *m).unwrap_or(self.f.active) }; self.first.get_or_insert(m); let out = self.local_point(&m, p); @@ -298,6 +303,10 @@ impl Mapper<'_> { } fn plane(&mut self, v: &Value) -> Option { + // A point where a plane may be given (a thread's `up_to`): a pick. + if v.is_array() { + return self.pick(v, None); + } let o = v.as_object()?; let mut m = o.clone(); if let Some(x) = o.get("face").and_then(|x| self.pick(x, None)) { @@ -339,6 +348,9 @@ thread_local! { static DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The outermost command's coordinates were mapped here (its table lists them). static MAPPED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The outermost command is `solid.move`, whose parameters stay in the world when its bodies + /// lie in differently turned frames (`split_move`). + static OUTER_MOVE: std::cell::Cell = const { std::cell::Cell::new(false) }; /// The picks of the running command: the point it sees and the bodies whose faces meet /// there (the first is the body under it; more than one means the pick is ambiguous). static PICKS: std::cell::RefCell)>> = const { std::cell::RefCell::new(Vec::new()) }; @@ -404,7 +416,8 @@ impl Nested { }); if outer { let inner = if id == "timeline.redefine" { None } else { Some(id) }; - MAPPED.with(|m| m.set(inner.is_none_or(|i| !table(i).is_empty()))); + MAPPED.with(|m| m.set(inner.is_none_or(|i| !table(i).is_empty() || i == "construct.plane.axis_point"))); + OUTER_MOVE.with(|m| m.set(id == "solid.move")); } (Nested, outer) } @@ -416,20 +429,91 @@ impl Drop for Nested { } } -/// `params` with world picks mapped into component frames (`None`: nothing to change). -pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { +/// `params` with world picks mapped into component frames (`None`: nothing to change). A model +/// that cannot be placed is the error. +pub fn to_local(s: &Session, id: &str, params: &Value) -> crate::Result> { + // A command with no world picks has nothing to map, and may not need the bodies placed. + let picks = !table(id).is_empty() || matches!(id, "library.apply" | "timeline.redefine" | "sketch.redefine"); + if !picks || !placed(s) { + return Ok(None); + } + // A move of bodies in differently turned frames keeps its world vectors: `solid.move` splits + // it by frame and maps each part itself (`split_move`). + if id == "solid.move" && split_move(s, params)?.is_some() { + return Ok(None); + } + let world = s.world_state()?; + Ok(map_local(s, &world, id, params)) +} + +/// A `solid.move` of bodies placed in different frames, as one move per frame (#9660). A Move +/// feature moves each of its bodies in the body's own frame, by one vector and one turn: given +/// in the world, they can be mapped into one frame only, so bodies in a frame turned otherwise +/// (a screw inserted lying down, moved with a block of the root) moved along their own axes. +/// Bodies whose frames turn alike share a move (and for a turn, frames that are also in the +/// same place, as its pivot is a point). `None`: the bodies share one frame, or are moved as +/// placements (`placements_moved`), or the move is not the outermost command (run by another, +/// such as Edit Feature, its parameters are already in component frames). `to_local` leaves the +/// parameters of a split move in the world, and `solid.move` asks for the parts. A model that +/// cannot be placed is the error. +pub(crate) fn split_move(s: &Session, params: &Value) -> crate::Result>> { + let outermost_move = DEPTH.with(std::cell::Cell::get) == 1 && OUTER_MOVE.with(std::cell::Cell::get); + if !outermost_move || !placed(s) || placements_moved(s, params).is_some() { + return Ok(None); + } + let Some(names) = params.get("bodies").and_then(Value::as_array) else { return Ok(None) }; + let turns = params.get("axis").is_some() || params.get("angle").is_some(); + let alike = |a: &Mat, b: &Mat| { + let columns = if turns { 4 } else { 3 }; + a.iter().zip(b).take(columns).all(|(x, y)| x.iter().zip(y).take(3).all(|(u, v)| (u - v).abs() <= 1e-9 * (1.0 + u.abs().max(v.abs())))) + }; + let frames = s.body_frames(); + let mut groups: Vec<(Mat, Vec)> = Vec::new(); + for name in names { + // An unknown body is the command's to refuse. + let Some(b) = name.as_str() else { return Ok(None) }; + let Some(m) = frames.iter().find(|(world, own, _)| world == b || own == b).map(|(.., m)| *m) else { return Ok(None) }; + match groups.iter_mut().find(|(g, _)| alike(g, &m)) { + Some((_, bodies)) => bodies.push(name.clone()), + None => groups.push((m, vec![name.clone()])), + } + } + if groups.len() < 2 { + return Ok(None); + } + let world = s.world_state()?; + let given = params.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + let moves = groups + .into_iter() + .enumerate() + .map(|(k, (_, bodies))| { + let mut p = params.clone(); + p["bodies"] = Value::Array(bodies); + // Each move is its own feature: a name given is numbered after the first. + if let Some(name) = given.filter(|_| k > 0) { + p["name"] = Value::String(format!("{name} ({})", k + 1)); + } + map_local(s, &world, "solid.move", &p).unwrap_or(p) + }) + .collect(); + Ok(Some(moves)) +} + +/// [`to_local`] on the placed model `world`. +fn map_local(s: &Session, world: &solidcraft_doc::ModelState, id: &str, params: &Value) -> Option { if id == "library.apply" { // Library targets are the same world selections as appearance.assign, // nested one level down. Convert at the outer boundary exactly once; // run_nested subsequently receives the component-local picks and names. - let targets = to_local(s, "appearance.assign", params.get("targets")?)?; + let targets = map_local(s, world, "appearance.assign", params.get("targets")?)?; let mut out = params.clone(); out["targets"] = targets; return Some(out); } // Several placements of one part moved together are moved as placements, in the world - // (`placements_moved`): their names and vectors stay as given. - if id == "solid.move" && placements_moved(s, params).is_some() { + // (`placements_moved`), and components copied (`occurrences`) likewise: their names and vectors + // stay as given. Bodies listed with them are mapped by `copy_components`. + if id == "solid.move" && (params.get("occurrences").is_some() || placements_moved(s, params).is_some()) { return None; } if id == "timeline.redefine" { @@ -443,7 +527,7 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { if let solidcraft_doc::FeatureKind::Emboss { face: Some(face), .. } = &feature.kind { context.active_occurrence_path = (!face.author_path.is_empty()).then(|| face.author_path.clone()); } - let mut inner = to_local(&context, cmd, params.get("params")?)?; + let mut inner = map_local(&context, world, cmd, params.get("params")?)?; // An untouched explicit axis is displayed in world coordinates by Edit // Feature. Keep its exact saved values instead of an affine round trip. if cmd == "solid.revolve" @@ -487,8 +571,22 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { { return None; } + if id == "construct.plane.axis_point" && placed(s) { + // Construction references include tagged saved forms as well as pick wrappers. + // Map the parsed definition once at the boundary, including a nested Edit Feature. + // The constructor can then name local model picks and retain their exact references. + let mut kind = crate::cmd::plane_axis_point_kind(s, params).ok()?; + kind.transform_geometry(&mat_inverse(&s.active_component_frame())?); + let solidcraft_doc::FeatureKind::ConstructionPlane { plane: solidcraft_doc::PlaneRef::AxisPoint { axis, point } } = kind else { + return None; + }; + let mut out = params.clone(); + out["axis"] = serde_json::to_value(axis).ok()?; + out["point"] = serde_json::to_value(point).ok()?; + return Some(out); + } let keys = table(id); - if keys.is_empty() || !placed(s) { + if keys.is_empty() { return None; } let obj = params.as_object()?; @@ -513,7 +611,7 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { obj.insert("origin".into(), serde_json::json!([0.0, 0.0, 0.0])); } let obj = &obj; - let mut m = Mapper { s, f: command_frames, first, changed: false, here: false }; + let mut m = Mapper { s, world, f: command_frames, first, changed: false, here: false }; let body = obj.get("body").or_else(|| obj.get("face_body")).and_then(Value::as_str).map(str::to_string); let mut out: Map = obj.clone(); // Picks first: their frame turns the directions. diff --git a/crates/engine/src/frames_tests.rs b/crates/engine/src/frames_tests.rs index b614f8e4a..fd8214030 100644 --- a/crates/engine/src/frames_tests.rs +++ b/crates/engine/src/frames_tests.rs @@ -2,7 +2,8 @@ //! world land in the component's own frame (user bug #4). use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::Session; @@ -18,7 +19,7 @@ fn near(a: Vec3, b: Vec3) -> bool { } fn world_bbox(s: &Session, body: &str) -> (Vec3, Vec3) { - let w = s.world_state(); + let w = s.world_state().unwrap(); let b = w.body(body).unwrap_or_else(|| panic!("no body {body}")).mesh().bounds(); (b.min, b.max) } @@ -72,9 +73,13 @@ fn sketches_and_planes_move_with_the_component() { fn world_picks_map_into_the_component() { let mut s = moved_part(); let v0 = volume(&mut s); + assert!((v0 - 6000.0).abs() < 1e-6, "{v0}"); // 30 x 20 x 10 // The edge along X at the top front: world (65, 0, 10). run(&mut s, "solid.fillet", json!({"edges": [[65, 0, 10]], "radius": 2})); - assert!(volume(&mut s) < v0 - 1.0, "the fillet cut material"); + let filleted = volume(&mut s); + // A round of radius 2 along the 30 mm edge removes r²(1 − π/4) of section along its length. + let round = 4.0 * (1.0 - std::f64::consts::PI / 4.0) * 30.0; + assert!((v0 - filleted - round).abs() < 4e-7 * v0, "the fillet cut {} against {round}", v0 - filleted); // The modified face has no certified lineage; explicitly freeze its picked plane. // Its world pick still maps into the moved component exactly once. run(&mut s, "sketch.create", json!({"plane": {"face": [70, 10, 10],"fixed":true}, "name": "Pad"})); @@ -88,7 +93,10 @@ fn world_picks_map_into_the_component() { assert!(near(pad, Vec3::new(70.0, 10.0, 10.0)), "{pad:?}"); let v1 = volume(&mut s); let h = run(&mut s, "solid.hole", json!({"position": [60, 10, 10], "diameter": 4, "depth": 5})); - assert!(volume(&mut s) < v1 - 1.0, "the hole cut material: {h}"); + // A simple (flat-bottomed) hole: a cylinder of radius 2, 5 deep, clear of the round at y < 2. + let bore = std::f64::consts::PI * 4.0 * 5.0; + let v2 = volume(&mut s); + assert!((v1 - v2 - bore).abs() < 4e-7 * v1, "the hole cut {} against {bore}: {h}", v1 - v2); // A box made at world (100, 0, 0) in the active (moved) component shows there. run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [100, 0, 0], "operation": "new"})); let last = s.model.state().bodies.last().map(|b| b.name.clone()).unwrap(); @@ -108,7 +116,11 @@ fn picks_on_an_instance_map_through_its_placement() { // An edge of the second instance only (world y = 40). run(&mut s, "solid.fillet", json!({"edges": [[5, 40, 10]], "radius": 2})); let v1 = volume(&mut s); - assert!(v1 < v0 - 1.0, "{v0} {v1}"); + // Two 10 mm cubes; the round of radius 2 along one 10 mm edge of the component removes + // r²(1 − π/4)·10 from every instance, the picked one and the other. + assert!((v0 - 2000.0).abs() < 1e-6, "{v0}"); + let round = 4.0 * (1.0 - std::f64::consts::PI / 4.0) * 10.0; + assert!((v0 - v1 - 2.0 * round).abs() < 4e-7 * v0, "{v0} {v1}"); } /// (c) Moving a body into a moved component keeps it where it is in the world. @@ -263,6 +275,65 @@ fn move_expression_distances_keep_parameters_through_rebuild_and_reopen() { } } +/// One `solid.move` of bodies placed in differently turned frames (a block in the root and a +/// screw inserted lying down) moves and turns each of them in the world, whichever is listed +/// first (#9660). +#[test] +fn one_move_of_bodies_in_differently_turned_frames_moves_each_in_the_world() { + let corners = |(lo, hi): (Vec3, Vec3)| { + let mut out = Vec::new(); + for x in [lo.x, hi.x] { + for y in [lo.y, hi.y] { + for z in [lo.z, hi.z] { + out.push(Vec3::new(x, y, z)); + } + } + } + out + }; + let bounds = |points: Vec| { + let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); + let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for p in points { + lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)); + hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z)); + } + (lo, hi) + }; + let close = |a: (Vec3, Vec3), b: (Vec3, Vec3)| a.0.dist(b.0) < 1e-4 && a.1.dist(b.1) < 1e-4; + // The quarter turn is about the world z axis, which passes through the screw's own origin + // (where it was inserted): a Move feature turns about that origin. + let moves: [(Value, &dyn Fn(Vec3) -> Vec3); 3] = [ + (json!({"translate": [0, 0, 3]}), &|p| p + Vec3::new(0.0, 0.0, 3.0)), + (json!({"translate": [0, "2 mm", 0]}), &|p| p + Vec3::new(0.0, 2.0, 0.0)), + (json!({"axis": [0, 0, 1], "angle": "90 deg"}), &|p| Vec3::new(-p.y, p.x, p.z)), + ]; + for direction in [[1, 0, 0], [0, 0, -1], [0, 1, 0]] { + for order in [["Block", "Body1"], ["Body1", "Block"]] { + for (params, expected) in &moves { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 10, "center": [0, 0, 5], "body_name": "Block"})); + let screw = json!({"family": "socket_head_cap_screw", "size": "M3", "length": 12, "point": [0, 0, 10], "direction": direction, "name": "screw"}); + run(&mut s, "parts.insert", screw); + let before: Vec<_> = order.iter().map(|b| world_bbox(&s, b)).collect(); + let mut p = params.clone(); + p["bodies"] = json!(order); + run(&mut s, "solid.move", p.clone()); + for (body, was) in order.iter().zip(&before) { + let want = bounds(corners(*was).into_iter().map(expected).collect()); + let got = world_bbox(&s, body); + assert!(close(got, want), "{body} after {p} (screw along {direction:?}): {got:?}, want {want:?}"); + } + // One step: a single undo puts both back. + run(&mut s, "edit.undo", json!({})); + for (body, was) in order.iter().zip(&before) { + assert!(close(world_bbox(&s, body), *was), "{body} after undoing {p}"); + } + } + } + } +} + /// Edit Feature passes a primitive's placement through as saved, so changing the radius of /// Leaf B's rod in the Hinge Assembly leaves the leaf where it was (#2926). #[test] @@ -416,3 +487,29 @@ fn an_explicit_sketch_plane_is_read_in_the_frame_asked_for() { assert!(e.contains(why), "{p}: {e}"); } } + +/// #3383: a root body joined into a body of a component turned a quarter turn about X stays where +/// it is in the world: the join overlaps the plate by 10 x 5 x 5 and is one solid. When the +/// component moves on, the join follows where both bodies are placed. +#[test] +fn a_combine_tool_stays_where_it_is_placed() { + let mut s = Session::default(); + // The design's first part is grounded when it is made (#2804); this one is moved. + run(&mut s, "component.create", json!({"name": "Part", "grounded": false})); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "body_name": "Plate"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "occurrence.move", json!({"occurrence": "Part:1", "axis": [1, 0, 0], "angle": "90 deg"})); + run(&mut s, "component.capture_position", json!({})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [-5, -5, -25], "operation": "new", "body_name": "Boss"})); + run(&mut s, "solid.combine", json!({"target": "Plate", "tools": ["Boss"]})); + let lumps = |s: &Session| s.model.state().body("Plate").map(|b| b.body.lumps().unwrap().len()); + assert_eq!(lumps(&s), Some(1), "the boss overlaps the plate where it is shown"); + assert!((volume(&mut s) - 16750.0).abs() < 1e-6, "{}", volume(&mut s)); + let (lo, hi) = world_bbox(&s, "Plate"); + assert!(near(lo, Vec3::new(-20.0, -10.0, -25.0)) && near(hi, Vec3::new(20.0, 5.0, 20.0)), "{lo:?} {hi:?}"); + // Raised 10 mm, the plate (z -10..30) clears the boss (z -25..-15). + run(&mut s, "occurrence.move", json!({"occurrence": "Part:1", "translate": [0, 0, 10]})); + run(&mut s, "component.capture_position", json!({})); + assert_eq!(lumps(&s), Some(2), "the boss stays where it is in the world"); + assert!((volume(&mut s) - 17000.0).abs() < 1e-6, "{}", volume(&mut s)); +} diff --git a/crates/engine/src/fuzz.rs b/crates/engine/src/fuzz.rs index 2219c5ed6..5d2a7bda0 100644 --- a/crates/engine/src/fuzz.rs +++ b/crates/engine/src/fuzz.rs @@ -8,7 +8,7 @@ use serde::Serialize; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_kernel::fuzz::Rng; pub use solidcraft_kernel::fuzz::{BoolCase, boolean_case, boolean_shapes}; @@ -64,8 +64,6 @@ pub struct Run { pub unsupported: Vec<(String, String)>, /// Steps whose generated parameters a command refused. pub rejected: usize, - pub boolean_fallbacks: std::collections::BTreeMap, - pub boolean_reports_truncated: bool, } impl Run { @@ -83,10 +81,13 @@ fn classify(e: &EngineError) -> Outcome { let msg = e.to_string(); match e { EngineError::Internal(..) => Outcome::new("panic", msg), - EngineError::BadParams { .. } | EngineError::Disabled(..) | EngineError::UnknownCommand(_) => Outcome::new("rejected", msg), - // A failed boolean is a failure even when it says "not supported" (the planar fallback on - // curved bodies): those are the cases to fix. Features the kernel doesn't do yet (a - // fillet between curved faces) are limitations. + EngineError::Panel(_) + | EngineError::BadParams { .. } + | EngineError::Disabled(..) + | EngineError::Refused { .. } + | EngineError::UnknownCommand(_) => Outcome::new("rejected", msg), + // A failed boolean is a failure even when it says "not supported": those are the cases + // to fix. Features the kernel doesn't do yet are limitations. // Picks the generator got wrong (a centroid off its face). EngineError::Other(_) if msg.starts_with("invalid input") => Outcome::new("rejected", msg), EngineError::Other(_) if msg.contains("boolean") => Outcome::new("failed", msg), @@ -294,55 +295,11 @@ pub fn run_with(seed: u64, max_steps: usize, on_step: &mut dyn FnMut(&Step)) -> run_session(seed, max_steps, on_step).0 } -/// What a seed builds, as recorded in the robustness goldens (`tests/robustness/goldens.json`): -/// the steps, how it ended (with the start of the message when it did not end ok) and, for the -/// design it left, its bodies' total volume and area and their face, edge and shell counts. -pub fn golden(seed: u64, max_steps: usize) -> Value { - let (run, s) = run_session(seed, max_steps, &mut |_| {}); - let st = s.model.state(); - let (mut volume, mut area, mut faces, mut edges, mut shells) = (0.0, 0.0, 0, 0, 0); - let mut measured = true; - for b in &st.bodies { - match solidcraft_kernel::measure(&b.body) { - Ok(m) => { - volume += m.volume; - area += m.area; - faces += m.faces; - edges += m.edges; - shells += m.shells; - } - Err(_) => measured = false, - } - } - let round = |x: f64| (x * 1e6).round() / 1e6; - json!({ - "steps": run.steps.iter().map(|st| st.kind).collect::>(), - "outcome": run.outcome.kind, - "error": (run.outcome.kind != "ok").then(|| gist(&run.outcome.detail)), - "unsupported": run.unsupported.len(), - "rejected": run.rejected, - "bodies": st.bodies.len(), - "volume": measured.then(|| round(volume)), - "area": measured.then(|| round(area)), - "faces": faces, - "edges": edges, - "shells": shells, - }) -} - /// [`run_with`], and the session the run left. fn run_session(seed: u64, max_steps: usize, on_step: &mut dyn FnMut(&Step)) -> (Run, Session) { let mut r = Rng::new(seed); let mut s = Session::default(); - let mut run = Run { - seed, - steps: Vec::new(), - outcome: Outcome::ok(), - unsupported: Vec::new(), - rejected: 0, - boolean_fallbacks: Default::default(), - boolean_reports_truncated: false, - }; + let mut run = Run { seed, steps: Vec::new(), outcome: Outcome::ok(), unsupported: Vec::new(), rejected: 0 }; let mut last_feature: Option = None; let n = 2 + r.below(max_steps.max(2) - 1); let mut tries = 0; @@ -367,12 +324,6 @@ fn run_session(seed: u64, max_steps: usize, on_step: &mut dyn FnMut(&Step)) -> ( continue; } let kind = st.kind; - for result in s.model.results.iter().skip(before).filter(|result| result.error.is_none()) { - run.boolean_reports_truncated |= result.boolean_diagnostics.truncated; - for event in &result.boolean_diagnostics.events { - *run.boolean_fallbacks.entry(event.strategy).or_default() += 1; - } - } run.steps.push(st); if out.kind != "ok" { run.outcome = out; @@ -388,19 +339,14 @@ fn run_session(seed: u64, max_steps: usize, on_step: &mut dyn FnMut(&Step)) -> ( /// Run fixed steps (a recorded or minimised design): the index and outcome of the first step /// that isn't ok (or the last step's, ok). pub fn replay(steps: &[Step]) -> (usize, Outcome) { - let (index, outcome, _) = replay_session(steps); - (index, outcome) -} - -fn replay_session(steps: &[Step]) -> (usize, Outcome, Session) { let mut s = Session::default(); for (i, st) in steps.iter().enumerate() { let out = apply(&mut s, st); if out.kind != "ok" { - return (i, out, s); + return (i, out); } } - (steps.len().saturating_sub(1), Outcome::ok(), s) + (steps.len().saturating_sub(1), Outcome::ok()) } /// The start of a message, to tell failures apart (numbers vary between versions of a case). @@ -431,16 +377,8 @@ pub fn minimise(run: &Run) -> Run { } } } - let (_, outcome, session) = replay_session(&steps); - let mut boolean_fallbacks = std::collections::BTreeMap::new(); - let mut boolean_reports_truncated = false; - for result in &session.model.results { - boolean_reports_truncated |= result.boolean_diagnostics.truncated; - for event in &result.boolean_diagnostics.events { - *boolean_fallbacks.entry(event.strategy).or_default() += 1; - } - } - Run { seed: run.seed, steps, outcome, unsupported: Vec::new(), rejected: 0, boolean_fallbacks, boolean_reports_truncated } + let (_, outcome) = replay(&steps); + Run { seed: run.seed, steps, outcome, unsupported: Vec::new(), rejected: 0 } } #[cfg(test)] diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rs index 6fe936d37..115bc8ca2 100644 --- a/crates/engine/src/hole_face_tests.rs +++ b/crates/engine/src/hole_face_tests.rs @@ -3,7 +3,7 @@ //! where it was put and says so instead of sliding to the face's nearest point. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -24,7 +24,7 @@ fn volume(s: &mut Session) -> f64 { /// Whether the model holds material at (x, y, z). fn solid_at(s: &Session, x: f64, y: f64, z: f64) -> bool { - s.model.state().bodies.iter().any(|b| b.body.contains(Vec3::new(x, y, z))) + s.model.state().bodies.iter().any(|b| b.body.classify_point(Vec3::new(x, y, z)).unwrap() == solidcraft_kernel::PointClass::Inside) } /// What the hole feature says (its error and its warning); empty when it is silent. @@ -343,7 +343,6 @@ fn drilled_sketch_points_break_through_a_sloping_back_face() { let id = s.doc.find_feature("H").unwrap().id; let result = s.model.result(id).unwrap(); assert!(result.error.is_none()); - assert!(result.boolean_diagnostics.unverified().is_none()); // The cylindrical bore and cone, less the oblique conical cap outside x = z/4. let r = 2.5; let k = 59f64.to_radians().tan(); @@ -450,3 +449,47 @@ fn a_hole_may_start_over_the_mouth_of_an_existing_bore() { let e = s.execute("solid.hole", &json!({"position": [-1, 15, 20], "diameter": 8})).unwrap_err().to_string(); assert!(e.contains("is not on a face of a body"), "{e}"); } + +/// A hole moved off the part cuts nothing and says so (#10701), as a pattern's copies do: by a +/// parameter of its position or a sketch point moved away. Back on the part it is silent. +#[test] +fn a_hole_moved_off_the_part_says_it_removes_no_material() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "hx", "expression": "10 mm"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": ["hx", "10 mm", "10 mm"], "diameter": 5, "name": "H1"})); + assert_eq!(said(&s, "H1"), ""); + change(&mut s, "hx", "100 mm"); + assert!((volume(&mut s) - 12_000.0).abs() < 1e-6, "nothing is cut"); + assert!(said(&s, "H1").contains("the hole removes no material"), "{}", said(&s, "H1")); + change(&mut s, "hx", "30 mm"); + assert_eq!(said(&s, "H1"), ""); + // Holes at two sketch points, one of them moved off the plate. + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 10, "name": "HP"})); + run(&mut s, "sketch.point", json!({"point": [10, 20], "id": "a"})); + run(&mut s, "sketch.point", json!({"point": [20, 20], "id": "b"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.hole", json!({"sketch": "HP", "points": ["a", "b"], "diameter": 4, "name": "H2"})); + assert_eq!(said(&s, "H2"), ""); + run(&mut s, "sketch.edit", json!({"sketch": "HP"})); + run(&mut s, "sketch.move_point", json!({"point": "a", "to": [100, 100]})); + run(&mut s, "sketch.finish", json!({})); + assert!(said(&s, "H2").contains("1 of 2 holes remove no material"), "{}", said(&s, "H2")); +} + +/// A hole wider than the part takes all of it away and says so (#10702): at creation, and when +/// a parameter widens it later. A hole across the part's width keeps the rest, silently. +#[test] +fn a_hole_wider_than_the_part_says_it_removes_all_of_it() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "hd", "expression": "40 mm"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": [10, 10, 10], "diameter": "hd", "name": "H1"})); + assert_eq!(said(&s, "H1"), ""); + assert_eq!(s.model.state().bodies.len(), 1); + change(&mut s, "hd", "100 mm"); + assert!(s.model.state().bodies.is_empty()); + assert!(said(&s, "H1").contains("the hole removes all of Body1"), "{}", said(&s, "H1")); + change(&mut s, "hd", "5 mm"); + assert_eq!(said(&s, "H1"), ""); +} diff --git a/crates/engine/src/hole_matrix_tests.rs b/crates/engine/src/hole_matrix_tests.rs index 5898647ee..123b2be85 100644 --- a/crates/engine/src/hole_matrix_tests.rs +++ b/crates/engine/src/hole_matrix_tests.rs @@ -13,10 +13,11 @@ //! case that passes fails the test (take it off the list), and so does an unlisted one that fails. //! `HOLE_MATRIX_BLESS=1 cargo test -p solidcraft-engine hole_matrix` rewrites the list. +use solidcraft_geom::prelude::*; use std::f64::consts::PI; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -34,7 +35,7 @@ fn measure(s: &mut Session) -> Result<(f64, i64), String> { } fn solid_at(s: &Session, p: Vec3) -> bool { - s.model.state().bodies.iter().any(|b| b.body.contains(p)) + s.model.state().bodies.iter().any(|b| b.body.classify_point(p).unwrap() == solidcraft_kernel::PointClass::Inside) } fn v3(a: [f64; 3]) -> Vec3 { @@ -802,6 +803,28 @@ fn hole_matrix() { ); } +/// #5041: a countersink cuts nothing outside its diameter above the face, so a wall standing +/// just past its rim keeps its face. +#[test] +fn a_countersink_next_to_a_wall_leaves_the_wall_whole() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 8, "corner": [0, 0, 0], "name": "Plate"})).unwrap(); + run(&mut s, "solid.box", json!({"length": 40, "width": 10, "height": 30, "corner": [0, 30, 8], "operation": "join", "name": "Wall"})).unwrap(); + let (before, _) = measure(&mut s).unwrap(); + // A Ø13.7 countersink whose rim ends 0.15 mm short of the wall. + let p = json!({"position": [20, 23, 8], "direction": [0, 0, -1], "diameter": 6.4, "depth": 8, "type": "countersink", "cs_diameter": 13.7, "cs_angle": 90}); + run(&mut s, "solid.hole", p).unwrap(); + assert!(solid_at(&s, Vec3::new(20.0, 30.05, 8.3)), "the wall above the plate is notched"); + assert!(solid_at(&s, Vec3::new(20.0, 30.05, 8.02))); + assert!(!solid_at(&s, Vec3::new(20.0, 29.0, 7.9)), "the countersink reaches its rim"); + // Exactly the countersink and the clearance hole are taken: the frustum from Ø13.7 to the + // hole, and the rest of the hole down through the plate. + let r = 3.2; + let (cs, h) = csink(13.7 / 2.0, r); + let (after, _) = measure(&mut s).unwrap(); + assert!(close(before - after, cs + cyl(r, 8.0 - h), cs), "{} taken, want {}", before - after, cs + cyl(r, 8.0 - h)); +} + #[test] fn recessed_drill_point_geometry_roundtrip_preview_and_undo() { for kind in ["counterbore", "countersink"] { @@ -826,7 +849,7 @@ fn recessed_drill_point_geometry_roundtrip_preview_and_undo() { p.as_object_mut().unwrap().remove("tip_angle"); let redefine = json!({"feature":hole,"command":"solid.hole","params":p}); let preview = s.preview(&[("timeline.redefine".into(), redefine.clone())]).unwrap(); - assert!(preview.after.bodies.iter().any(|b| b.body.contains(probe))); + assert!(preview.after.bodies.iter().any(|b| b.body.classify_point(probe).unwrap() == solidcraft_kernel::PointClass::Inside)); assert_eq!(s.doc.to_json(), saved, "preview cannot accept the bottom change"); run(&mut s, "timeline.redefine", redefine).unwrap(); assert!(solid_at(&s, probe)); @@ -856,3 +879,17 @@ fn recessed_drill_point_through_and_exact_shoulder_keep_the_existing_exit() { } } } + +/// A hole on the side of a cone, given no direction, drills along the cone's normal there, not +/// the nearest mesh facet's, which leaned it up to 2.6° sideways (#10698). +#[test] +fn a_hole_on_a_cones_side_drills_along_its_normal() { + let mut s = Session::default(); + run(&mut s, "solid.cone", json!({"radius": 15, "height": 20, "body_name": "Cone"})).unwrap(); + // The side is r = 15 (1 - z / 20): at (7.5, 0, 10) the outward normal is (0.8, 0, 0.6). + run(&mut s, "solid.hole", json!({"position": [7.5, 0, 10], "diameter": 4, "depth": 4, "name": "H"})).unwrap(); + let f = s.doc.find_feature("H").unwrap(); + let solidcraft_doc::FeatureKind::Hole { direction, .. } = &f.kind else { panic!("not a hole") }; + let d = direction.0; + assert!((d.x + 0.8).abs() < 1e-6 && d.y.abs() < 1e-6 && (d.z + 0.6).abs() < 1e-6, "{d:?}"); +} diff --git a/crates/engine/src/hole_reference_tests.rs b/crates/engine/src/hole_reference_tests.rs index 48d437e72..f504488ec 100644 --- a/crates/engine/src/hole_reference_tests.rs +++ b/crates/engine/src/hole_reference_tests.rs @@ -3,11 +3,12 @@ //! when the part changes (also after the design is saved and reopened), and a bad reference is //! refused with an error. A cylinder takes the same references for its base (#6380). +use solidcraft_geom::prelude::*; use std::f64::consts::PI; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_doc::FeatureKind; -use solidcraft_geom::Vec3; use crate::{EngineError, Session}; @@ -19,7 +20,7 @@ fn run(s: &mut Session, id: &str, p: Value) -> Value { } fn solid_at(s: &Session, p: Vec3) -> bool { - s.model.state().bodies.iter().any(|b| b.body.contains(p)) + s.model.state().bodies.iter().any(|b| b.body.classify_point(p).unwrap() == solidcraft_kernel::PointClass::Inside) } /// The bore (5 mm across, 4 mm deep, down from the top face at z = `top`) is about (x, y): @@ -105,6 +106,32 @@ fn a_hole_follows_its_edges_when_the_box_grows() { assert_eq!(hole(&t).1, hole(&s).1); } +#[test] +fn a_referenced_hole_can_be_patterned_and_mirrored() { + // #8055, #6754: a pattern or mirror places its copies from the hole's own spot, found again + // after the hole has been drilled. Through the plate, its centre is then in the opening, with + // no face under it. + let mut s = plate(); + let mut through = referenced(json!([{"edge": [0, 20, 10], "distance": 10}, {"edge": [25, 0, 10], "distance": 12}])); + through.as_object_mut().unwrap().remove("depth"); + run(&mut s, "solid.hole", through); + run( + &mut s, + "solid.pattern.rectangular", + json!({"features": ["H"], "dir1": [1, 0, 0], "count1": 2, "spacing1": 12, "dir2": [0, 1, 0], "count2": 2, "spacing2": 12, "name": "P"}), + ); + for (x, y) in [(10.0, 12.0), (22.0, 12.0), (10.0, 24.0), (22.0, 24.0)] { + bore_at(&s, x, y, 10.0); + } + run(&mut s, "solid.mirror", json!({"features": ["H"], "plane": {"origin": [25, 0, 0], "normal": [1, 0, 0]}, "name": "M"})); + bore_at(&s, 40.0, 12.0, 10.0); + // The copies still follow the hole's edges. + run(&mut s, "parameters.change", json!({"name": "len", "expression": "60 mm"})); + let p = s.doc.find_feature("P").unwrap().id; + assert!(s.model.result(p).is_some_and(|r| r.error.is_none()), "{:?}", s.model.result(p).map(|r| &r.error)); + bore_at(&s, 22.0, 24.0, 10.0); +} + #[test] fn a_bad_reference_is_refused() { let mut s = plate(); diff --git a/crates/engine/src/large_assembly_tests.rs b/crates/engine/src/large_assembly_tests.rs index cf256f5ce..ade58e30b 100644 --- a/crates/engine/src/large_assembly_tests.rs +++ b/crates/engine/src/large_assembly_tests.rs @@ -7,9 +7,9 @@ //! `SOLIDCRAFT_BENCH_PARTS=400 cargo test --release -p solidcraft-engine bench_generated_assembly -- --ignored --nocapture` use serde_json::json; +use solidcore_record::Vec3; use solidcraft_doc::BodyName; use solidcraft_doc::{Document, FeatureKind, Operation, mat_inverse, point_expr, rigid}; -use solidcraft_geom::Vec3; use crate::Session; @@ -70,7 +70,7 @@ fn generated_assembly_opens_with_every_body_in_place() { let doc = generated_assembly(parts); let mut s = Session::new(doc.clone()); assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results.iter().find(|r| r.error.is_some())); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), parts * 4); assert!(world.bodies.iter().all(|b| b.component != 0 && b.transferred)); world.warm_meshes(|| true); @@ -110,7 +110,7 @@ fn bench_generated_assembly() { let evaluate = ms(t); let features: f64 = s.model.results.iter().map(|r| r.ms).sum(); let t = std::time::Instant::now(); - let world = s.world_state(); + let world = s.world_state().unwrap(); world.warm_meshes(|| true); let mesh = ms(t); let t = std::time::Instant::now(); @@ -124,3 +124,23 @@ fn bench_generated_assembly() { "volume_mm3": m["total"]["volume_mm3"]}) ); } + +#[test] +fn names_only_lists_every_world_body_without_measuring() { + let mut s = Session::new(generated_assembly(3)); + let full = s.execute("inspect.measure", &json!({})).unwrap(); + let names = s.execute("inspect.measure", &json!({"names_only": true})).unwrap(); + assert_eq!(names["body_count"], full["body_count"]); + let world = s.world_state().unwrap(); + for ((n, f), b) in names["bodies"].as_array().unwrap().iter().zip(full["bodies"].as_array().unwrap()).zip(&world.bodies) { + assert_eq!(n["name"], f["name"]); + assert_eq!(n["definition"], json!(b.definition_name())); + assert!(n.get("volume_mm3").is_none(), "{n}"); + } + assert!(names.get("total").is_none()); + // The `bodies` filter holds, and an unknown name is still refused. + let first = names["bodies"][0]["name"].clone(); + let one = s.execute("inspect.measure", &json!({"names_only": true, "bodies": [first]})).unwrap(); + assert_eq!(one["body_count"], 1); + assert!(s.execute("inspect.measure", &json!({"names_only": true, "bodies": ["no such body"]})).is_err()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bb8827868..6efee1217 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,6 +27,7 @@ pub mod fuzz; pub mod licences; mod mesh_lines; pub mod occurrences; +pub mod panels; pub mod params; pub mod product_scene; pub mod recovery; @@ -39,27 +40,30 @@ pub mod slicer_files; mod slicer_icon; pub mod slicers; pub mod snap; +pub mod status_details; pub mod status_items; pub mod timing; pub mod view; +use solidcraft_geom::prelude::*; use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::Value; +use solidcore_record::Vec3; use solidcraft_doc::{Document, Model, ModelState}; -use solidcraft_geom::Vec3; pub use cmd::settings::{MAX_PROFILE_NAME, profile_name}; pub use cmd::{ - Addition, CommandInfo, CommandSpec, addition, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, resolve_design_links, - shown_scope, standard_view, + Addition, CommandInfo, CommandSpec, OpenSteps, addition, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, + resolve_design_links, shown_scope, standard_view, }; pub use solidcraft_doc as doc; pub use solidcraft_doc::Visibility; pub use solidcraft_geom as geom; pub use solidcraft_io as io; pub use solidcraft_kernel as kernel; +pub use solidcraft_profile as profile; pub use solidcraft_render as render; pub use solidcraft_sketch as sketch; @@ -69,6 +73,8 @@ pub const MAX_LINE: usize = 16 << 20; #[derive(Debug, thiserror::Error)] pub enum EngineError { + #[error("{text}", text = panels::commands::error_text(.0.clone()))] + Panel(#[from] panels::PanelError), #[error("unknown command `{0}`{hint}", hint = cmd::did_you_mean(.0))] UnknownCommand(String), #[error("`{0}` is not available right now: {1}")] @@ -77,6 +83,10 @@ pub enum EngineError { BadParams { cmd: String, msg: String }, #[error("{0}")] Other(String), + /// The host's pre-command check ([`Session::set_command_check`]) refused the command; the + /// message is the reason it gave. + #[error("{reason}")] + Refused { cmd: String, reason: String }, /// A command panicked; the document was kept as it was (a bug: please report it). #[error("internal error in `{0}` (the design was kept as it was): {1}")] Internal(String, String), @@ -84,7 +94,10 @@ pub enum EngineError { impl From for EngineError { fn from(e: solidcraft_doc::DocError) -> Self { - EngineError::Other(e.to_string()) + match e { + solidcraft_doc::DocError::Kernel(e) => e.into(), + e => EngineError::Other(e.to_string()), + } } } impl From for EngineError { @@ -94,7 +107,19 @@ impl From for EngineError { } impl From for EngineError { fn from(e: solidcraft_kernel::KernelError) -> Self { - EngineError::Other(e.to_string()) + match e { + // A panic the kernel caught: internal, as one in the command would be. The command's id + // is filled in where the command is run (`Session::execute`). + solidcraft_kernel::KernelError::Internal(m) => EngineError::Internal(String::new(), m), + e => EngineError::Other(e.to_string()), + } + } +} + +impl EngineError { + /// The error a failed feature's result reports: internal when the kernel caught a panic. + pub(crate) fn of_feature(r: &solidcraft_doc::FeatureResult, error: String) -> EngineError { + if r.internal { EngineError::Internal(String::new(), error) } else { EngineError::Other(error) } } } impl From for EngineError { @@ -188,6 +213,32 @@ pub enum Sel { }, } +impl Sel { + /// The body this item names, when it names one: the body itself, or the body a face, edge + /// or vertex belongs to. Session state that names a body has to follow its renames (#9737). + pub(crate) fn body_name(&self) -> Option<&str> { + match self { + Sel::Body { name } => Some(name), + Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => Some(body), + _ => None, + } + } +} + +/// Whether the document differs from the one its file holds, as last worked out for this pair +/// of documents at this revision. The window asks every frame for every tab (the tab strip, the +/// autosave), and a large design compared field by field cost more than the rest of an idle +/// frame. Holding both documents keeps their contents fixed and their addresses unused by +/// another document while the answer stands: shared, a document can't be edited in place (an +/// edit copies it to a new address), and [`Session::doc_mut`] lets the answer go first so an +/// edit stays in place. +struct DirtyAnswer { + revision: u64, + doc: Arc, + saved: Arc, + differs: bool, +} + /// A body rename between two designs (see `Session::body_renames`). #[derive(Clone)] struct BodyRename { @@ -198,13 +249,15 @@ struct BodyRename { names_only: bool, } -/// Bodies or component placements copied in one design, for pasting into another -/// (`component.paste_from_design`): that design's placed model as it was when they were copied, +/// Bodies, component placements or timeline features copied in one design, for pasting into another: +/// that design's model as it was when they were copied, /// so the copy is what was copied, whatever happens to that design (or its tab) after. #[derive(Clone, Debug)] pub struct ForeignCopy { /// The design's name (it names what the paste adds). pub design: String, + /// Timeline features, in their original order (`timeline.paste` with `from_design`). + pub features: Vec, /// Its placed model: what its Browser and view showed. pub world: Arc, /// The bodies copied, as its Browser names them (a body seen in another placement under the @@ -226,13 +279,14 @@ pub struct ForeignCopy { impl ForeignCopy { /// What `session` copies when `bodies` and `placements` are copied in it now. - pub fn of(session: &Session, bodies: Vec, placements: Vec>) -> ForeignCopy { + pub fn of(session: &Session, bodies: Vec, placements: Vec>) -> Result { let frames = session.placed_document().body_frames_with_source(&session.model.state()); let names = bodies.iter().map(|b| frames.iter().find(|f| f.0 == *b).map_or_else(|| b.clone(), |f| f.1.clone())).collect(); let placed = placements.iter().filter_map(|p| session.occurrence_placement(p).ok()).map(|p| (p.component, p.occurrence, p.world)).collect(); - ForeignCopy { + Ok(ForeignCopy { design: session.doc.name.clone(), - world: session.world_state(), + features: Vec::new(), + world: session.world_state()?, bodies, names, placements, @@ -240,6 +294,22 @@ impl ForeignCopy { doc: session.doc.clone(), model: session.model.clone(), pending_moves: session.pending_moves.clone(), + }) + } + + /// Timeline Copy's snapshot. No placed body geometry is needed to paste sketches. + pub fn of_features(session: &Session) -> ForeignCopy { + ForeignCopy { + design: session.doc.name.clone(), + features: session.clipboard.clone(), + world: session.model.state(), + bodies: Vec::new(), + names: Vec::new(), + placements: Vec::new(), + placed: Vec::new(), + doc: session.doc.clone(), + model: session.model.clone(), + pending_moves: session.pending_moves.clone(), } } } @@ -282,6 +352,10 @@ pub(crate) struct SketchEntry { pub(crate) doc: Arc, pub(crate) undo_len: usize, pub(crate) undo_top: Option>, + /// A temporary editor rollback, restored by the engine even without a window. + pub(crate) restore_marker: Option>, + pub(crate) pending_moves: std::collections::BTreeMap, + pub(crate) visibility: Visibility, } /// A copy of a session that evaluates commands ahead of it ([`Session::ahead`]). @@ -307,7 +381,7 @@ impl Ahead { /// front end can say how far a batch has got. pub fn evaluate_counting(self, commands: &[(String, Value)], step: &std::sync::atomic::AtomicUsize) -> Result { let (after, _) = self.0.preview_in_place(commands, Some(step))?; - after.world_state().warm_display(); + after.world_state()?.warm_display(); Ok(Evaluated(after.model)) } @@ -344,7 +418,9 @@ struct WorldCache { pending_moves: std::collections::BTreeMap, active_component: u64, active_occurrence_path: Option>, - world: Arc, + /// The placed model, or why it could not be placed (kept too, so a model that cannot be + /// placed is not placed again on every read). + world: std::result::Result, String>, /// The moved components' bodies as placed for `world`, reused by the next world state. placed: Arc>, /// Every placed body's world name, own name and frame for `world` ([`Session::body_frames`]), @@ -392,23 +468,33 @@ impl ComputedCommands { session.same_document_context(source) && session.selection == source.selection } - /// Prepare display tessellation before returning the transaction to the window. - pub fn warm_meshes(&self, keep_going: impl Fn() -> bool + Sync) { - self.warm_display(solidcraft_doc::display_quality::DisplayQuality::Normal, keep_going); + /// Prepare display tessellation before returning the transaction to the window; a model that + /// cannot be placed is the error. + pub fn warm_meshes(&self, keep_going: impl Fn() -> bool + Sync) -> Result<()> { + self.warm_display(solidcraft_doc::display_quality::DisplayQuality::Normal, keep_going) } /// Prepare both the reference picking mesh and the GPU plan/highlight mesh at the /// selected quality. Warming only the reference mesh leaves cold planning on the UI. - pub fn warm_display(&self, quality: solidcraft_doc::display_quality::DisplayQuality, keep_going: impl Fn() -> bool + Sync) { - self.computed.world_state().warm_display_at(quality, keep_going); + pub fn warm_display(&self, quality: solidcraft_doc::display_quality::DisplayQuality, keep_going: impl Fn() -> bool + Sync) -> Result<()> { + self.computed.world_state()?.warm_display_at(quality, keep_going); + Ok(()) } } +/// A check an app that embeds the engine runs before every command ([`Session::set_command_check`]): +/// it is shown the command's id, its parameters and the session (read only), and returns `Ok` to +/// let the command run or `Err(reason)` to refuse it. +pub type CommandCheck = Arc std::result::Result<(), String> + Send + Sync>; + /// An editing session on one design. /// Starts an upload of a file (its name, its bytes) to EasyPrint and returns at once; the host /// reports how it went and opens the answer itself. `Err`: it couldn't start. pub type EasyPrintUpload = Arc) -> std::result::Result<(), String> + Send + Sync>; +/// See [`Session::made_bodies`]. +type MadeBodies = std::collections::HashMap, Vec)>; + pub struct Session { pub doc: Arc, pub model: Model, @@ -439,6 +525,11 @@ pub struct Session { /// Opened read-only (`doc.open {read_only}`, the "open elsewhere" notice): saving to its own /// file is refused; Save As to another file is how its changes are kept. pub read_only: bool, + /// Whether the design's name is one its user chose for it (`file.new {name}`) rather than + /// one it borrowed — from a file's name, a sample's name, or a file that stored another + /// design's name. A borrowed name follows Save As to the new file's name (#4907); a name + /// the user chose is kept. + pub user_named: bool, /// One-shot display-only notification during doc.open, before authoritative evaluation. /// Interactive loaders may show it provisionally; it never becomes model state. pub open_preview: Option>, @@ -447,9 +538,12 @@ pub struct Session { pub log: Vec, /// Increments on every document change (views use it to refresh). pub revision: u64, - /// Revision increments caused only by visibility. Comparing both counters proves that - /// every intervening increment left an editor's document and model untouched. + /// Revision increments caused only by what is shown ([`Session::refresh_display`]). + /// Comparing both counters proves that every intervening increment left an editor's + /// document and model untouched. visibility_revision: u64, + /// [`Document::browser_stamp`] when the browser's groups and order were last checked. + browser_stamp: [u64; 6], /// This open design's id for programs that follow it (`document.revision`, #6646): kept /// while it stays open, through saves and renames; another for each design started or opened. pub document_id: String, @@ -473,14 +567,33 @@ pub struct Session { pub active_occurrence_path: Option>, /// Occurrence moves not captured yet (Capture Position keeps them, a recompute drops them). pub pending_moves: std::collections::BTreeMap, + /// The placements the exploded view (`explode.show`) put in `pending_moves` to be shown: + /// display only. An entry of `pending_moves` still equal to its one here is the exploded view's, + /// not a move of the design's, so the placements the design reports and Capture Position + /// keeps leave it out ([`Session::uncaptured_moves`]). + pub exploded: std::collections::BTreeMap, world_cache: std::sync::Mutex>, /// The design the joints were last solved for, as the solve left it, and the model it read /// (see [`Session::solve_joints`]). joints_settled: Option<(Arc, std::sync::Weak)>, occurrence_visibility_cache: std::sync::Mutex>, + /// The hidden joints, folders and bodies of the view, as sets: the browser asks about every + /// joint of the design on every frame (#3892), the viewport about every body, and an answer + /// that walked the hidden lists made a frame cost grow with the size of the design. + visibility_index_cache: std::sync::Mutex>, + /// The sketches a feature uses, with the design they were read from + /// ([`view::sketch_consumed`]): the viewport asks about every sketch several times a frame, + /// and walking the features for each made that cost grow with sketches times features. + /// Keyed on the design itself, so an edit of any kind builds the set again. + consumed_sketches_cache: std::sync::Mutex>, + /// The bodies each feature made, by name, with the state they were read from + /// ([`Session::pin_body_names`]). + made_bodies: MadeBodies, removed_later_cache: std::sync::Mutex>, occurrence_bodies_cache: std::sync::Mutex>, placement_index_cache: std::sync::Mutex>, + /// The last answer of [`Session::is_dirty`] on the document (see [`DirtyAnswer`]). + dirty_cache: std::sync::Mutex>, /// Pairs `inspect.clearance` measured, by the bodies' geometry where they stood (shared with /// scratch copies): a body that did not change or move is not measured again. clearance_cache: std::sync::Arc>, @@ -510,6 +623,12 @@ pub struct Session { /// The seams `inspect.continuity` last measured, for the viewport to shade. View state: not /// part of the design and not an undo step. pub continuity: Vec, + /// The faces Isocurve Analysis shows the isoparametric curves of, for the viewport to draw + /// ([`Session::isocurve_lines`]). View state: not part of the design and not an undo step. + pub isocurves: Vec, + /// The curvature combs `inspect.curvature_comb` shows, for the viewport to draw; `None` when + /// the analysis is off. View state: not part of the design and not an undo step. + pub comb: Option, /// Oldest active slot first; replacing an effect retains its row position. status_order: Vec, /// Successful source activations, independently of row order and sharing policy. @@ -540,6 +659,9 @@ pub struct Session { /// that did is no edit of the design before it, so [`Session::execute`] never takes it for a /// change of render intent or part properties alone. replacements: u64, + /// The host's pre-command check (none by default: every command may run). It belongs to the + /// host, not the design: opening or starting a design keeps it, and scratch copies carry it. + command_check: Option, /// Record this session's top-level commands in the crash journal (the app's own design; /// never previews or other scratch sessions). See [`crash`]. pub crash_journal: bool, @@ -606,6 +728,49 @@ pub struct ContinuitySeam { pub points: Vec, /// The seam's worst verdict along its length. pub verdict: kernel::SeamVerdict, + /// The highest continuity order it meets along its whole length (`None`: the faces do not + /// meet). + pub order: Option, + /// Successful measurement settings and diagnostics, owned by this particular seam. + pub details: status_details::ContinuityDetail, +} + +/// A face Isocurve Analysis shows: the body, the picked point on the face (its face is found +/// from it again whenever the body changes) and how many curves each way. View state only. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct IsoPick { + pub body: String, + pub at: Vec3, + pub count: usize, +} + +/// What Curvature Comb Analysis shows: the picks, the options every comb is drawn with, and +/// the teeth drawn, all at one scale so their lengths compare. View state only. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct CombView { + pub picks: Vec, + /// Teeth per curve. + pub density: usize, + /// The multiplier on the automatic scale. + pub length: f64, + /// A fixed comb length per unit curvature, in place of the automatic one. + pub fixed_scale: Option, + /// The comb length per unit curvature the teeth are drawn at, shared by every comb. + pub scale: f64, + /// Each comb's teeth as (foot, tip), in world coordinates. + pub teeth: Vec>, +} + +/// A curve Curvature Comb Analysis shows, as it was picked (found again whenever it is drawn). +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum CombPick { + /// A sketch curve. + Curve { sketch: u64, curve: String }, + /// The body edge whose exact curve passes nearest `at`. + Edge { at: Vec3 }, + /// The face at `at`, combed along `count` iso curves each way. + Face { at: Vec3, count: usize }, } impl SurfaceAnalysis { @@ -644,20 +809,36 @@ impl Session { /// `doc`'s evaluation ([`Model::adopt`]); otherwise the timeline is evaluated. /// Use [`Self::opened_at`] when the document's file location is known. /// `SOLIDCRAFT_NO_MODEL_CACHE` set always evaluates. - pub fn opened(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>) -> Self { + pub fn opened(doc: Document, saved: Option<&solidcraft_doc::SavedModel>) -> Self { + Self::opened_validating(doc, saved, solidcraft_kernel::Validation::default()) + } + + /// [`Self::opened`], its features evaluated under `validation` ([`Session::set_validation`]). + pub fn opened_validating(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>, validation: solidcraft_kernel::Validation) -> Self { // A design's font files are checked like its other paths before it is evaluated. solidcraft_io::vfs::install_checks(); // The session keeps what is hidden (an undo step of its own); the design file carries it. let visibility = std::mem::take(&mut doc.visibility); let doc = Arc::new(doc); - let adopted = saved - .filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none()) - .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()); - let model = adopted.unwrap_or_else(|| { + // A model saved under another check mode holds that mode's results: evaluated again. + let model = Self::saved_model(&doc, saved).filter(|model| model.validation() == validation).unwrap_or_else(|| { let mut model = Model::new(); + model.set_validation(validation); model.evaluate_shared(&doc); model }); + Self::with_model(doc, visibility, model) + } + + /// The model `doc`'s file kept, when it is `doc`'s evaluation and the cache is not turned off. + pub(crate) fn saved_model(doc: &Arc, saved: Option<&solidcraft_doc::SavedModel>) -> Option { + saved + .filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none()) + .and_then(|saved| Model::adopt(doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()) + } + + /// A session on `doc` evaluated as `model`, with what it hides. + pub(crate) fn with_model(doc: Arc, visibility: Visibility, model: Model) -> Self { Session { saved: doc.clone(), doc, @@ -674,10 +855,12 @@ impl Session { uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), disk: None, read_only: false, + user_named: false, open_preview: None, log: Vec::new(), revision: 1, visibility_revision: 0, + browser_stamp: [0; 6], document_id: cmd::inspect::new_document_id(), followed: None, auto_project: true, @@ -687,12 +870,17 @@ impl Session { active_component: 0, active_occurrence_path: None, pending_moves: Default::default(), + exploded: Default::default(), world_cache: Default::default(), joints_settled: None, occurrence_visibility_cache: Default::default(), + visibility_index_cache: Default::default(), + consumed_sketches_cache: Default::default(), + made_bodies: MadeBodies::new(), removed_later_cache: Default::default(), occurrence_bodies_cache: Default::default(), placement_index_cache: Default::default(), + dirty_cache: Default::default(), clearance_cache: Default::default(), body_renames: Vec::new(), contact_meshes: Default::default(), @@ -705,6 +893,8 @@ impl Session { colored_components: None, analysis: None, continuity: Vec::new(), + isocurves: Vec::new(), + comb: None, status_order: Vec::new(), status_activation: Vec::new(), single_surface_analysis: true, @@ -722,6 +912,7 @@ impl Session { #[cfg(test)] evaluations: 0, motion_traces: Default::default(), + command_check: None, crash_journal: false, } } @@ -734,6 +925,7 @@ impl Session { /// 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 validation = self.validation(); let single_surface_analysis = self.single_surface_analysis; let param_check = self.param_check; let easyprint_upload = self.easyprint_upload.take(); @@ -746,9 +938,14 @@ impl Session { // next frame, so commands sent right after `doc.open` or `file.new` are kept. let crash_journal = self.crash_journal; let replacements = self.replacements.wrapping_add(1); + let command_check = self.command_check.take(); *self = fresh; self.crash_journal = crash_journal; + self.command_check = command_check; self.auto_project = auto_project; + // The user's, like `auto_project`: the commands that open a design evaluate it under it + // already (`Session::opened_validating`). + self.set_validation(validation); self.set_single_surface_analysis(single_surface_analysis); self.param_check = param_check; self.easyprint_upload = easyprint_upload; @@ -766,11 +963,62 @@ impl Session { self.ids = solidcraft_doc::ids::IdSource::seeded(seed); } + /// Install (or with `None` remove) the check [`Session::execute`] runs before every command, + /// for an app that embeds the engine and decides which commands may run. A refusal comes back + /// as [`EngineError::Refused`] and leaves the session as it was. + pub fn set_command_check(&mut self, check: Option) { + self.command_check = check; + } + + /// The check installed with [`Session::set_command_check`], to hand on to another session. + pub fn command_check(&self) -> Option { + self.command_check.clone() + } + + /// Ask the host's check, if any, whether `spec` may run with `params`. A check that panics + /// refuses the command as an internal error instead of taking the session down. + fn check_command(&self, spec: &CommandSpec, params: &Value) -> Result<()> { + let Some(check) = &self.command_check else { return Ok(()) }; + // The check sees the parameters as the command will (no parameters: an empty object). + let empty = Value::Object(Default::default()); + let params = if params.is_null() { &empty } else { params }; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(spec.id, params, self))) { + Ok(Ok(())) => Ok(()), + Ok(Err(reason)) => Err(EngineError::Refused { cmd: spec.id.to_string(), reason }), + Err(_) => Err(EngineError::Internal(spec.id.to_string(), "the host's command check failed".into())), + } + } + /// The design has changes not in its file: in the document, or in what is hidden. pub fn is_dirty(&self) -> bool { - (!Arc::ptr_eq(&self.doc, &self.saved) && *self.doc != *self.saved) || self.visibility != self.saved_visibility + self.document_differs() || self.visibility != self.saved_visibility } + + /// The document is not the one its file holds: compared once per pair of documents and + /// revision ([`DirtyAnswer`]). + fn document_differs(&self) -> bool { + if Arc::ptr_eq(&self.doc, &self.saved) { + return false; + } + let Ok(mut answer) = self.dirty_cache.lock() else { return *self.doc != *self.saved }; + let same = |a: &DirtyAnswer| a.revision == self.revision && Arc::ptr_eq(&a.doc, &self.doc) && Arc::ptr_eq(&a.saved, &self.saved); + if let Some(a) = answer.as_ref().filter(|a| same(a)) { + return a.differs; + } + let differs = *self.doc != *self.saved; + *answer = Some(DirtyAnswer { revision: self.revision, doc: self.doc.clone(), saved: self.saved.clone(), differs }); + differs + } + + /// Let the unsaved-changes answer go, with the documents it holds. + fn forget_dirty_answer(&self) { + if let Ok(mut answer) = self.dirty_cache.lock() { + *answer = None; + } + } + pub fn mark_saved(&mut self) { + self.forget_dirty_answer(); self.saved = self.doc.clone(); self.saved_visibility = self.visibility.clone(); } @@ -869,15 +1117,51 @@ impl Session { } } + /// Let the used sketches' set go before an edit in place: it holds the document weakly, and + /// `Arc::make_mut` would move a weakly held document to a new address. + fn forget_consumed_sketches(&self) { + if let Ok(mut cache) = self.consumed_sketches_cache.lock() { + *cache = None; + } + } + + /// The marker an active temporary sketch edit returns to. `Some(None)` means the end of + /// the timeline; `None` means this sketch was opened without a temporary rollback. + pub fn sketch_restore_marker(&self) -> Option> { + self.sketch_entry.as_ref().filter(|entry| Some(entry.sketch) == self.active_sketch).and_then(|entry| entry.restore_marker) + } + /// Mutable document (copy-on-write). pub fn doc_mut(&mut self) -> &mut Document { - // The placement index keeps the document alive with its answers; let it go before an - // in-place edit, so the edit stays in place (a shared handle would clone the document - // to a new address behind the crash journal's back, #7502) and no stale lookup outlives it. + self.forget_document_caches(); + #[cfg(test)] + if Arc::strong_count(&self.doc) > 1 { + tests::doc_copies::record(); + } + Arc::make_mut(&mut self.doc) + } + + /// Make `doc` the design, as `*doc_mut() = doc` does, without first copying a shared + /// document only to overwrite the copy: a command's undo step still holds the design it + /// started from, so `doc_mut` would copy all of it (every feature and sketch) on each + /// sketch drag frame. The design lands at a new address either way, and the command's end + /// tells the crash journal that address (#7502). + pub(crate) fn set_doc(&mut self, doc: Document) { + self.forget_document_caches(); + self.doc = Arc::new(doc); + } + + /// Before the document changes: the placement index keeps the document alive with its + /// answers; let it go, so an in-place edit stays in place (a shared handle would clone the + /// document to a new address behind the crash journal's back, #7502) and no stale lookup + /// outlives it. + fn forget_document_caches(&mut self) { if let Ok(mut index) = self.placement_index_cache.lock() { *index = None; } - Arc::make_mut(&mut self.doc) + self.forget_consumed_sketches(); + self.forget_dirty_answer(); + self.model.forget_fingerprints(); } /// The drawing open, for `cmd`. @@ -922,29 +1206,30 @@ impl Session { if self.doc.occurrences.is_empty() { return Some(state); } - self.world_cache.lock().ok()?.as_ref().filter(|cache| cache.matches(self, &state)).map(|cache| cache.world.clone()) + self.world_cache.lock().ok()?.as_ref().filter(|cache| cache.matches(self, &state)).and_then(|cache| cache.world.clone().ok()) } /// Re-evaluate the model after a document change. /// The model placed in the world through component occurrences (and uncaptured moves): what /// to display, measure, pick and export. The same as `model.state()` without components. - pub fn world_state(&self) -> Arc { + /// An error when the model cannot be placed (see [`solidcraft_doc::world_state`]). + pub fn world_state(&self) -> Result> { let st = self.model.state(); if self.doc.occurrences.is_empty() { - return st; + return Ok(st); } if let Ok(c) = self.world_cache.lock() && let Some(cached) = c.as_ref() && cached.matches(self, &st) { - return cached.world.clone(); + return cached.world.clone().map_err(EngineError::Other); } // The bodies the last world state placed: unchanged ones are not transformed and meshed // again (a design built command by command changed one body at a time). let placed = self.world_cache.lock().ok().and_then(|c| c.as_ref().map(|c| c.placed.clone())).unwrap_or_default(); // Taken out while placing, so a scratch copy of the session sharing it never waits. let mut reuse = placed.lock().map(|mut p| std::mem::take(&mut *p)).unwrap_or_default(); - let mut w = { + let w = { if self.pending_moves.is_empty() { solidcraft_doc::world_state_reusing(&self.doc, &st, &mut reuse) } else { @@ -960,21 +1245,40 @@ impl Session { if let Ok(mut p) = placed.lock() { *p = reuse; } + let w = w.map_err(EngineError::from).and_then(|w| self.authored_sketches(w)).map(Arc::new); + if let Ok(mut c) = self.world_cache.lock() { + *c = Some(WorldCache { + doc: self.doc.clone(), + model: st, + pending_moves: self.pending_moves.clone(), + active_component: self.active_component, + active_occurrence_path: self.active_occurrence_path.clone(), + world: w.as_ref().map(Arc::clone).map_err(ToString::to_string), + placed, + frames: Arc::default(), + }); + } + w + } + + /// `w` with the active component's sketches shown at the placement being authored. + fn authored_sketches(&self, mut w: solidcraft_doc::ModelState) -> Result { // Sketch definitions are displayed once, at the placement currently being authored. if self.active_occurrence_path.is_some() && self.active_component != 0 { let first = self.occurrence_placement(&self.doc.first_path(self.active_component)).map(|p| p.world).unwrap_or(solidcraft_doc::IDENTITY); - if let Some(inverse) = solidcraft_doc::mat_inverse(&first) { + let inverse = solidcraft_doc::mat_inverse(&first) + .ok_or_else(|| EngineError::Other(format!("the placement of component {} cannot be inverted", self.active_component)))?; + { let delta = solidcraft_doc::mat_mul(&self.active_component_frame(), &inverse); for sketch in w.sketches.iter_mut().filter(|sk| self.doc.feature(sk.feature).is_some_and(|f| f.component == self.active_component)) { let sketch = Arc::make_mut(sketch); let plane = sketch.plane; - if let Some(mapped) = solidcraft_geom::Plane::new( + sketch.plane = solidcore_record::Plane::new( solidcraft_doc::apply_point(&delta, plane.origin), solidcraft_doc::apply_vector(&delta, plane.x), solidcraft_doc::apply_vector(&delta, plane.y), - ) { - sketch.plane = mapped; - } + ) + .ok_or_else(|| EngineError::Other("a sketch plane cannot be placed at the authored placement".into()))?; for wire in &mut sketch.sketch.wires { if wire.space == solidcraft_doc::sketch::WireSpace::Component { solidcraft_doc::map_wire(wire, &delta); @@ -983,20 +1287,7 @@ impl Session { } } } - let w = Arc::new(w); - if let Ok(mut c) = self.world_cache.lock() { - *c = Some(WorldCache { - doc: self.doc.clone(), - model: st, - pending_moves: self.pending_moves.clone(), - active_component: self.active_component, - active_occurrence_path: self.active_occurrence_path.clone(), - world: w.clone(), - placed, - frames: Arc::default(), - }); - } - w + Ok(w) } /// Every placed body's world name, own name and frame. Kept with the world state while it is @@ -1013,6 +1304,36 @@ impl Session { } } + /// When SMLib's check runs on the features evaluated: after every sweep, boolean and blend, + /// once on the bodies each feature keeps (the default), or not at all. A user's setting, + /// kept when another design is opened (`diagnostics.validation`, the app's preference). + pub fn validation(&self) -> solidcraft_kernel::Validation { + self.model.validation() + } + + /// Evaluate the features computed from now on under `validation` ([`Session::validation`]); + /// the results already there stand until their features are computed again + /// (`timeline.compute_all` computes every one). + pub fn set_validation(&mut self, validation: solidcraft_kernel::Validation) { + self.model.set_validation(validation); + } + + /// The model body a name means: one of the model's own bodies as it is named, else the body + /// a placed copy shows (`KB (K:2)`, the name `inspect.measure` lists), as `appearance.assign` + /// takes it (#9740). `None` when neither names it. + pub(crate) fn own_body_name(&self, name: &str) -> Option { + if self.model.state().body(name).is_some() { + return Some(name.to_string()); + } + self.body_frames().iter().find(|(world, ..)| world == name).map(|(_, own, _)| own.clone()) + } + + /// A component by its id or name, or by the name of one of its placements (`K:2`); never the + /// root. + pub(crate) fn component_or_placement(&self, key: &str) -> Option { + self.doc.find_component(key).or_else(|| self.doc.occurrences.iter().find(|o| o.name == key).map(|o| o.component)).filter(|id| *id != 0) + } + pub fn refresh(&mut self) { if self.model.evaluate_shared(&self.doc) { #[cfg(test)] @@ -1022,6 +1343,15 @@ impl Session { } self.revision += 1; self.prune_occurrence_state(); + // Looked at only when what the groups can name has changed, not on every refresh. + let stamp = self.doc.browser_stamp(); + if stamp != self.browser_stamp { + if let Some((groups, order)) = self.doc.browser_pruned() { + let d = self.doc_mut(); + (d.browser_groups, d.browser_order) = (groups, order); + } + self.browser_stamp = self.doc.browser_stamp(); + } // Joints follow the geometry their origins snap to. if !self.doc.assembly.joints.is_empty() { // A solve that moves parts changes what features reading where a part is placed @@ -1068,11 +1398,21 @@ impl Session { /// [`Session::refresh`] after the design changed from `previous`; a change that only renamed /// a body or a feature (or undid or redid such a rename) renames it in the model instead, /// which keeps every result and mesh (#3044). - fn refresh_from(&mut self, previous: &Arc) { - self.follow_plane_renames(previous); - self.follow_axis_point_renames(previous); + fn refresh_from(&mut self, previous: &Arc, visibility_restored: bool) { let rename = self.body_rename(previous); - self.remap_hidden_bodies(previous, &self.model.state(), rename.as_ref().map(|(old, new, _)| (old.as_str(), new.as_str()))); + // Undo/redo restored visibility in the target document's names already. Remapping + // those names again can transfer a deleted body's stale hide to the restored body. + if !visibility_restored { + self.follow_plane_renames(previous); + self.follow_axis_point_renames(previous); + self.remap_hidden_bodies(previous, &self.model.state(), rename.as_ref().map(|(old, new, _)| (old.as_str(), new.as_str()))); + // Locked bodies follow explicit renames and outside edits too (#9737). + if let Some((old, new, _)) = &rename { + for b in self.visibility.locked_bodies.iter_mut().filter(|b| **b == *old) { + *b = new.clone(); + } + } + } if let Some((old, new, names_only)) = rename && names_only && self.model.rename_body(&self.doc, &old, &new) @@ -1106,12 +1446,34 @@ impl Session { } let mut pins: Vec<(u64, Vec)> = Vec::new(); let mut reserve: Vec = Vec::new(); - for f in self.doc.features.iter().filter(|f| !matches!(f.kind, solidcraft_doc::FeatureKind::FrameMember { .. })) { - let Some(r) = self.model.result(f.id).filter(|r| r.error.is_none() && !r.skipped && !r.stale) else { continue }; - let made: Vec<&str> = r.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| b.name.as_str()).collect(); + // The names of the bodies each feature made, kept with the state they were read from: + // every command pins, and reading them again searched every result's bodies (features × + // bodies per command). A state is the same while it is the same allocation (the weak + // reference keeps that address from being reused), and its bodies never change in place. + let mut known = std::mem::take(&mut self.made_bodies); + let mut made_bodies = MadeBodies::with_capacity(known.len()); + for (i, f) in self.doc.features.iter().enumerate() { + if matches!(f.kind, solidcraft_doc::FeatureKind::FrameMember { .. }) { + continue; + } + // Results are in timeline order: the feature's own index first, the search only when not. + let r = self.model.results.get(i).filter(|r| r.id == f.id).or_else(|| self.model.result(f.id)); + let Some(r) = r.filter(|r| r.error.is_none() && !r.skipped && !r.stale) else { continue }; + let made = match known.remove(&f.id).filter(|(state, _)| std::sync::Weak::as_ptr(state) == Arc::as_ptr(&r.state)) { + Some(entry) => made_bodies.entry(f.id).or_insert(entry), + None => made_bodies.entry(f.id).or_insert_with(|| { + let names = r.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| b.name.clone()).collect(); + (Arc::downgrade(&r.state), names) + }), + }; + let made: Vec<&str> = made.1.iter().map(String::as_str).collect(); reserve.extend( made.iter().filter(|n| solidcraft_doc::is_counted_body_name(n) && !self.doc.reserved_body_names.contains(**n)).map(|n| n.to_string()), ); + // Nothing to pin when every slot the bodies take already holds a name. + if made.len() <= f.body_names.len() && f.body_names.iter().take(made.len()).all(|slot| !slot.trim().is_empty()) { + continue; + } let mut names = f.body_names.clone(); names.resize(names.len().max(made.len()), String::new()); for (slot, name) in names.iter_mut().zip(&made) { @@ -1123,9 +1485,13 @@ impl Session { pins.push((f.id, names)); } } + self.made_bodies = made_bodies; if pins.is_empty() && reserve.is_empty() { return; } + // The fingerprints that stand: taken before the pins change the design. + let renamed: Vec = pins.iter().map(|(id, _)| *id).collect(); + let keep = self.model.pinned_prefix(&self.doc, &renamed); let doc = self.doc_mut(); for (id, names) in pins { if let Some(f) = doc.feature_mut(id) { @@ -1134,7 +1500,7 @@ impl Session { } doc.reserved_body_names.extend(reserve); // The pinned names are the ones the bodies have: no result changes, so none is evaluated. - self.model.refingerprint_shared(&self.doc); + self.model.refingerprint_shared(&self.doc, keep); } /// A hidden construction plane stays hidden when the design renames it, or undo or redo @@ -1202,14 +1568,15 @@ impl Session { } } - /// Only persistent render intent, part properties, appearances or drawings changed. Never - /// evaluate or clear a stale model here. + /// Only persistent render intent, part properties, appearances, the browser's groups or drawings + /// changed. Never evaluate or clear a stale model here. fn render_only_change(&self, before: &Snapshot) -> bool { self.active_sketch == before.active_sketch && self.pending_moves == before.pending_moves && (self.doc.differs_only_in_render(&before.doc) || self.doc.differs_only_in_part_properties(&before.doc) || self.doc.differs_only_in_appearance(&before.doc) + || self.doc.differs_only_in_browser(&before.doc) || self.doc.differs_only_in_drawings(&before.doc)) } @@ -1231,8 +1598,9 @@ impl Session { } } - /// Only what is hidden or shown changed: the model is untouched, so only the view revision - /// moves (the visibility caches are keyed on it) and the viewport redraws. + /// Only what is shown changed (hidden or shown items, a section or analysis, the selection): + /// the design and model are untouched, so only the view revision moves and the viewport + /// redraws. An open feature editor stays valid across it (#10687). pub(crate) fn refresh_display(&mut self) { self.revision += 1; self.visibility_revision += 1; @@ -1268,6 +1636,10 @@ impl Session { /// as before. Otherwise store each sketch whose values changed as solved, so the next edit /// continues from it (see `Model::adopt_solved_sketches`). pub(crate) fn settle_value_edit(&mut self, solved_before: &SketchValues) -> Result<()> { + // The solved geometry each sketch had before the edit, for the shrink/fling checks + // after the refresh below (the same checks `settle` runs on an edit's own solve). + let solved_geometry: std::collections::BTreeMap = + self.model.results.iter().filter_map(|r| r.state.sketch(r.id).map(|k| (r.id, k.sketch.clone()))).collect(); // Quantity changes alter topology, so store the regenerated instances in the same // transaction as the parameter edit. Later picks and undo must see those same ids. let mut updated: Vec<_> = self @@ -1296,23 +1668,38 @@ impl Session { self.refresh(); for r in &self.model.results { let (Some(before), Some(k)) = (solved_before.get(&r.id), r.state.sketch(r.id)) else { continue }; - if !k.report.keeps_orientation() && own_values(&k.sketch) != *before { + if own_values(&k.sketch) == *before { + continue; + } + if !k.report.keeps_orientation() { let why = k.report.failure(|f| format!("its constraints would conflict ({f})")); return Err(EngineError::Other(format!("sketch `{}`: {why}; the values were not changed", r.name))); } + // The value changed this sketch and it still solves: refuse it the way `settle` + // refuses an edit's solve when the curve was squeezed away or points thrown far, + // so a zero (or wild) value is never stored as a sketch that can't be solved back. + if let Some(before_sketch) = solved_geometry.get(&r.id) + && let Some(why) = cmd::collapse_reason(before_sketch, &k.sketch) + { + return Err(EngineError::Other(format!("sketch `{}`: {why}; the values were not changed", r.name))); + } } // Checked first: storing makes the document unique (a copy when the undo step shares it). if self.model.edited_sketches(&self.doc).next().is_some() { if let Ok(mut index) = self.placement_index_cache.lock() { *index = None; } + self.forget_consumed_sketches(); + self.forget_dirty_answer(); self.model.adopt_solved_sketches(Arc::make_mut(&mut self.doc)); } Ok(()) } /// Run a command with JSON parameters (no dialogs). Undoable commands record an undo step - /// when they change the document; a failing or panicking command leaves it unchanged. + /// when they change the document; a failing or panicking command leaves it unchanged. The + /// host's check ([`Session::set_command_check`]) is asked first, on every call (commands that + /// a command runs through `execute` included). /// /// A command that takes `live` ([`CommandSpec::live`]) run with `live: true` is one frame of /// an interactive gesture: the model shows its sketch's new solution and keeps every later @@ -1322,6 +1709,14 @@ impl Session { /// the model up to date before anything reads it. pub fn execute(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if panels::commands::is_command(spec.id) { + // Layout is application state. Even a missing capability must not + // clear live links, map picks, snapshot, evaluate or refresh a design. + panels::commands::parse_command(spec.id, params)?; + return Err(EngineError::Panel(panels::error(panels::Rule::Capability, "application layout backend was not injected"))); + } + // The command, the evaluation it causes and the refresh after it: one profiler span. + let _span = solidcraft_profile::span("command", spec.id); let host_viewport = self.render_viewport.clone(); let host_jobs = self.render_jobs.host.clone(); let additional_jobs = self.render_jobs.additional.clone(); @@ -1333,6 +1728,8 @@ impl Session { } } spec.allowed(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?; + // Before anything changes: a refusal leaves the session exactly as it was. + self.check_command(spec, params)?; let open_drawing = self.open_drawing; let before = Snapshot { part: open_drawing.filter(|_| matches!(spec.part, cmd::Part::Drawing | cmd::Part::Open)), ..Snapshot::of(self, spec.label) }; @@ -1348,7 +1745,7 @@ impl Session { let (_nested, outermost) = frames::Nested::enter(spec.id); let mapped = if outermost { frames::forget_picks(); - frames::to_local(self, spec.id, params) + frames::to_local(self, spec.id, params)? } else { None }; @@ -1377,6 +1774,11 @@ impl Session { } r => r, }; + // The kernel's internal errors come up without the command's id. + let r = r.map_err(|e| match e { + EngineError::Internal(id, msg) if id.is_empty() => EngineError::Internal(spec.id.to_string(), msg), + e => e, + }); // A value typed as `name = expression` defines the user parameter `name` (#4071), in the // same undo step; a refused definition fails the command, which leaves the design as it was. let r = match r { @@ -1449,7 +1851,7 @@ impl Session { } None if render_only => self.refresh_render(&previous_doc), None if display_only => self.refresh_display(), - None => self.refresh_from(&previous_doc), + None => self.refresh_from(&previous_doc, matches!(spec.id, "edit.undo" | "edit.redo")), } // A row the change added takes its item number in the same undo step; numbers // draw nothing, so the model and the placed world stay. @@ -1548,8 +1950,13 @@ impl Session { /// Go back to checkpoint `id` as if nothing since had happened (the undo history too). It /// and later checkpoints are used up. pub fn restore_checkpoint(&mut self, id: u64) -> Result<()> { - let i = self.checkpoints.iter().position(|c| c.id == id).ok_or_else(|| EngineError::Other(format!("no checkpoint {id}")))?; - let Some(c) = self.checkpoints.drain(i..).next() else { return Err(EngineError::Other(format!("no checkpoint {id}"))) }; + let missing = || { + EngineError::Other(format!( + "no checkpoint {id} (used up by restoring or forgetting it or an earlier one, or dropped: only the last {MAX_CHECKPOINTS} are kept)" + )) + }; + let i = self.checkpoints.iter().position(|c| c.id == id).ok_or_else(missing)?; + let Some(c) = self.checkpoints.drain(i..).next() else { return Err(missing()) }; let before = Snapshot::of(self, ""); self.doc = c.doc; self.active_sketch = c.active_sketch; @@ -1594,11 +2001,13 @@ impl Session { uid: self.uid, disk: self.disk, read_only: self.read_only, + user_named: self.user_named, open_preview: None, saved: self.saved.clone(), log: Vec::new(), revision: self.revision, visibility_revision: self.visibility_revision, + browser_stamp: self.browser_stamp, document_id: self.document_id.clone(), followed: None, auto_project: self.auto_project, @@ -1608,12 +2017,19 @@ impl Session { active_component: self.active_component, active_occurrence_path: self.active_occurrence_path.clone(), pending_moves: self.pending_moves.clone(), + exploded: self.exploded.clone(), world_cache: std::sync::Mutex::new(self.world_cache.lock().ok().and_then(|cache| cache.clone())), joints_settled: self.joints_settled.clone(), + // Read again by the copy: handing it these references measured more peak memory on a + // large design (the rover, evaluated ahead) for no change in what it pins. + made_bodies: MadeBodies::new(), occurrence_visibility_cache: Default::default(), + visibility_index_cache: Default::default(), + consumed_sketches_cache: Default::default(), removed_later_cache: Default::default(), occurrence_bodies_cache: Default::default(), placement_index_cache: Default::default(), + dirty_cache: Default::default(), clearance_cache: self.clearance_cache.clone(), body_renames: self.body_renames.clone(), contact_meshes: self.contact_meshes.clone(), @@ -1626,6 +2042,8 @@ impl Session { colored_components: None, analysis: None, continuity: Vec::new(), + isocurves: Vec::new(), + comb: None, status_order: Vec::new(), status_activation: Vec::new(), single_surface_analysis: self.single_surface_analysis, @@ -1643,6 +2061,7 @@ impl Session { #[cfg(test)] evaluations: 0, motion_traces: self.motion_traces.clone(), + command_check: self.command_check.clone(), crash_journal: false, } } @@ -1662,6 +2081,23 @@ impl Session { } let mut expected = (*original.doc).clone(); expected.marker = source.doc.marker; + // Rolling the marker solves the joints again and stores where that puts each occurrence. + if expected.occurrences.len() == source.doc.occurrences.len() { + for (e, s) in expected.occurrences.iter_mut().zip(&source.doc.occurrences) { + if e.id == s.id { + e.transform = s.transform; + } + } + } + // ...and works out each coupled joint's ratio and lift from the faces at that marker. + if expected.assembly.links.len() == source.doc.assembly.links.len() { + for (e, s) in expected.assembly.links.iter_mut().zip(&source.doc.assembly.links) { + if (e.a, e.ia, e.b, e.ib) == (s.a, s.ia, s.b, s.ib) { + e.ratio = s.ratio; + e.lift = s.lift.clone(); + } + } + } if expected != *source.doc { return Err(EngineError::Other("the original editor model does not match its source design".into())); } @@ -1832,6 +2268,7 @@ impl Session { self.active_component = computed.active_component; self.active_occurrence_path = computed.active_occurrence_path; self.pending_moves = computed.pending_moves; + self.exploded = computed.exploded; // Joints the computation hid (an import's rigid group) stay hidden. for j in computed.visibility.hidden_joints { if !self.visibility.hidden_joints.contains(&j) { @@ -1857,22 +2294,20 @@ impl Session { /// The same evaluated preview in occurrence coordinates, including uncaptured moves. pub fn preview_world(&self, commands: &[(String, Value)]) -> Result { - self.scratch().preview_in_place(commands, None).map(|(after, replies)| Preview { - before: self.world_state(), - after: after.world_state(), - replies, - }) + let (after, replies) = self.scratch().preview_in_place(commands, None)?; + Ok(Preview { before: self.world_state()?, after: after.world_state()?, replies }) } /// World preview with each session's visibility applied, including new body placements. pub fn preview_visible_world(&self, commands: &[(String, Value)]) -> Result { - let visible = |session: &Session| { - let world = session.world_state(); + let visible = |session: &Session| -> Result> { + let world = session.world_state()?; let mut shown = (*world).clone(); shown.bodies.retain(|body| session.body_visible(&body.name)); - Arc::new(shown) + Ok(Arc::new(shown)) }; - self.scratch().preview_in_place(commands, None).map(|(after, replies)| Preview { before: visible(self), after: visible(&after), replies }) + let (after, replies) = self.scratch().preview_in_place(commands, None)?; + Ok(Preview { before: visible(self)?, after: visible(&after)?, replies }) } /// Run `commands` on a [`Session::scratch`] copy that keeps the undo and redo stacks: what @@ -1883,6 +2318,7 @@ impl Session { let mut copy = self.scratch(); copy.undo.clone_from(&self.undo); copy.redo.clone_from(&self.redo); + copy.sketch_entry.clone_from(&self.sketch_entry); copy.model.keep(Some(Arc::default())); Ahead(copy) } @@ -1905,8 +2341,10 @@ impl Session { { self.doc_mut().marker = Some(idx + 1); self.refresh(); - if let Some(e) = self.model.result(fid).and_then(|r| r.error.clone()) { - return Err(EngineError::Other(e)); + if let Some(r) = self.model.result(fid) + && let Some(e) = r.error.clone() + { + return Err(EngineError::of_feature(r, e)); } } } @@ -2114,6 +2552,7 @@ fn same_but_features(a: &Document, b: &Document) -> bool { point_clouds, param_comments, materials, + print_faces, user_materials, appearances, body_components, @@ -2150,6 +2589,7 @@ fn same_but_features(a: &Document, b: &Document) -> bool { && *point_clouds == b.point_clouds && *param_comments == b.param_comments && *materials == b.materials + && *print_faces == b.print_faces && *user_materials == b.user_materials && *appearances == b.appearances && *body_components == b.body_components diff --git a/crates/engine/src/licences.rs b/crates/engine/src/licences.rs index 5ff64b967..885f5a7c7 100644 --- a/crates/engine/src/licences.rs +++ b/crates/engine/src/licences.rs @@ -20,7 +20,7 @@ mod tests { #[test] fn the_licences_are_built_in() { assert!(super::LICENSE_MIT.contains("MIT License") && super::LICENSE_APACHE.contains("Apache License")); - assert!(super::THIRD_PARTY.contains("truck") && super::THIRD_PARTY.contains("egui")); + assert!(super::THIRD_PARTY.contains("wgpu") && super::THIRD_PARTY.contains("egui")); assert!(super::all().contains("NOTICE")); } } diff --git a/crates/engine/src/measure_centre_tests.rs b/crates/engine/src/measure_centre_tests.rs index 36e0eda92..ced252821 100644 --- a/crates/engine/src/measure_centre_tests.rs +++ b/crates/engine/src/measure_centre_tests.rs @@ -2,10 +2,11 @@ //! distances with the closest and farthest listed too, diameters and radii, slot sizes. Every //! expected value is worked out by hand from the part's dimensions. +use solidcraft_geom::prelude::*; use std::f64::consts::{PI, TAU}; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -336,6 +337,48 @@ fn a_cylinders_top_circle_is_as_long_as_its_circumference() { assert!(close(&r["items"][0]["length_mm"], TAU * 5.0, 1e-9), "{r}"); } +/// The first face whose analytic surface satisfies `want`, as a pick. +fn face_of(s: &Session, want: impl Fn(solidcraft_kernel::FaceSurface) -> bool) -> Value { + let st = s.model.state(); + let b = st.bodies.first().unwrap(); + let m = b.mesh(); + let n = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap(); + let f = (0..n).find(|&f| solidcraft_kernel::face_surface(&b.body, f).is_some_and(&want)).expect("face"); + let p = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf as usize == f).and_then(|(t, _)| m.tri(t)).unwrap()[0]; + json!({"type": "face", "body": b.name, "index": f, "point": p}) +} + +/// A fillet round the foot of a boss is a toroidal face: it measures its radius (the fillet's) +/// next to its area, and says it is a torus with its ring radius too. +#[test] +fn a_fillet_round_a_boss_reports_its_radius() { + use solidcraft_kernel::FaceSurface; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10})); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 12, "base": [20, 20, 10], "operation": "join"})); + run(&mut s, "solid.fillet", json!({"edges": [[25, 20, 10]], "radius": 3})); + let fillet = face_of(&s, |f| matches!(f, FaceSurface::Torus { minor, .. } if (minor - 3.0).abs() < 1e-6)); + let r = measure(&mut s, vec![fillet]); + assert!(close(&r["radius"], 3.0, 1e-6) && close(&r["diameter"], 6.0, 1e-6), "{r}"); + assert_eq!(r["items"][0]["surface"], "torus", "{r}"); + // The ring through the middle of the rolling ball: the boss's radius plus the fillet's. + assert!(close(&r["items"][0]["major_radius"], 8.0, 1e-6), "{r}"); + // The area is still there. + assert!(r["items"][0]["area_mm2"].as_f64().is_some_and(|a| a > 1.0), "{r}"); +} + +/// A ball's face reports its radius. +#[test] +fn a_sphere_face_reports_its_radius() { + use solidcraft_kernel::FaceSurface; + let mut s = Session::default(); + run(&mut s, "solid.sphere", json!({"radius": 7, "center": [0, 0, 0]})); + let ball = face_of(&s, |f| matches!(f, FaceSurface::Sphere { .. })); + let r = measure(&mut s, vec![ball]); + assert!(close(&r["radius"], 7.0, 1e-6) && close(&r["diameter"], 14.0, 1e-6), "{r}"); + assert_eq!(r["items"][0]["surface"], "sphere", "{r}"); +} + /// A plate with holes through STEP: the holes come back as cylinders, and measure the same. #[test] fn step_round_trip_of_a_plate_with_holes() { @@ -474,6 +517,7 @@ fn open_surface_measurements_have_no_volume_properties() { assert_eq!(props["total"]["open_bodies_skipped"], 1); assert!(props["bodies"][0]["mass_g"].is_null()); assert!(props["total"]["center_of_mass"].is_null()); + assert!(s.execute("inspect.center_of_mass", &json!({"bodies": ["OpenTube"]})).is_err(), "an open surface has no centre of mass"); } #[test] @@ -502,6 +546,43 @@ fn volume_totals_skip_open_surfaces_and_keep_closed_box_properties() { for key in ["volume_mm3", "mass_g", "center_of_mass"] { assert_eq!(props_before["total"][key], props_after["total"][key]); } + let com = run(&mut s, "inspect.center_of_mass", json!({})); + assert_eq!(com["skipped"].as_array().map(Vec::len), Some(1), "{com}"); + assert_eq!(com["bodies"].as_array().map(Vec::len), Some(1), "{com}"); + assert!(close(&com["volume"], 6000.0, 1e-9), "{com}"); + for (axis, expected) in [5.0, 10.0, 15.0].into_iter().enumerate() { + assert!(close(&com["center"][axis], expected, 1e-9), "{com}"); + } +} + +/// #6173: Center of Mass reports the volume and centre Measure does. It measured the display +/// mesh, whose flat facets cut curved faces short: a sphere of radius 10 came out 0.13 % small. +#[test] +fn center_of_mass_reports_the_same_volume_and_centre_as_measure() { + let mut s = Session::default(); + run(&mut s, "solid.sphere", json!({"radius": 10, "center": [0, 0, 0], "body_name": "Ball"})); + run(&mut s, "solid.cylinder", json!({"base": [50, 0, 0], "radius": 10, "height": 20, "body_name": "Cup"})); + run(&mut s, "solid.shell", json!({"faces": [[50, 0, 20]], "thickness": 2})); + let measured = run(&mut s, "inspect.measure", json!({})); + let com = run(&mut s, "inspect.center_of_mass", json!({})); + let entry = |list: &Value, key: &str, name: &str| -> Value { + list.as_array().and_then(|l| l.iter().find(|b| b[key] == name)).cloned().unwrap_or_else(|| panic!("{name} in {list}")) + }; + for name in ["Ball", "Cup"] { + let (m, c) = (entry(&measured["bodies"], "name", name), entry(&com["bodies"], "body", name)); + assert!(close(&c["volume"], m["volume_mm3"].as_f64().unwrap(), 1e-9), "{name}: {c} vs {m}"); + for axis in 0..3 { + assert!(close(&c["center"][axis], m["center_of_mass"][axis].as_f64().unwrap(), 1e-9), "{name}: {c} vs {m}"); + } + } + assert!(close(&com["volume"], measured["total"]["volume_mm3"].as_f64().unwrap(), 1e-6), "{com} vs {measured}"); + assert_eq!(com["skipped"].as_array().map(Vec::len), Some(0), "{com}"); + // Worked out by hand: the sphere is 4/3 pi r^3, the cup a cylinder less its 8 x 18 bore. + let ball = 4.0 / 3.0 * PI * 1000.0; + let cup = PI * (100.0 * 20.0 - 64.0 * 18.0); + let (b, c) = (entry(&com["bodies"], "body", "Ball"), entry(&com["bodies"], "body", "Cup")); + assert!(close(&b["volume"], ball, ball * 2e-4), "{b}: want {ball}"); + assert!(close(&c["volume"], cup, cup * 2e-4), "{c}: want {cup}"); } /// An ASCII STL of the tetrahedron (0,0,0), (10,0,0), (0,10,0), (0,0,10), outward facing; `open` diff --git a/crates/engine/src/mesh_lines/meshes.rs b/crates/engine/src/mesh_lines/meshes.rs index 6214246ee..d7eab9ddc 100644 --- a/crates/engine/src/mesh_lines/meshes.rs +++ b/crates/engine/src/mesh_lines/meshes.rs @@ -1,13 +1,15 @@ //! Export-only mesh instances. Keep one geometry buffer per unambiguous definition, while //! retaining the current placed body's edge choices (tangent classification can vary after //! placement). Never modify the document, fuse parts, or share across separate exports. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use std::mem::size_of; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use solidcore_record::Vec3; use solidcraft_doc::{IDENTITY, Mat, ModelBody, mat_inverse, mat_mul}; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcraft_geom::{Aabb3, Mesh}; use solidcraft_kernel::{KernelError, map_with_local_pools}; use super::progress::Stage; @@ -116,7 +118,7 @@ fn rigid(m: &Mat) -> bool { /// for. Errors about the placements name the command `cmd`; a body with no exportable surface, the /// memory budget and cancellation come back as the meshing stage's own errors. pub(crate) fn prepare(s: &Session, cmd: &str, tolerance: f64, ask: Ask, shown: impl Fn(&ModelBody) -> bool) -> Result { - let world = s.world_state(); + let world = s.world_state()?; let state = s.model.state(); let mut definitions = BTreeMap::new(); for body in &state.bodies { @@ -153,7 +155,7 @@ pub(crate) fn prepare(s: &Session, cmd: &str, tolerance: f64, ask: Ask, shown: i let bytes = AtomicUsize::new(0); let results = map_with_local_pools(&items, WORKERS, |item| { progress.check().map_err(|e| KernelError::Failed(e.into()))?; - let mut mesh = item.body.body.reference_display_mesh_angular(tolerance, solidcraft_kernel::DISPLAY_ANGLE)?; + let mut mesh = item.body.body.mesh(&solidcraft_kernel::MeshTolerance { chord: tolerance, angle: Some(solidcraft_kernel::DISPLAY_ANGLE) })?; if mesh.triangles.is_empty() { return Err(KernelError::Invalid(format!("{} has no exportable surface", item.body.name))); } diff --git a/crates/engine/src/mesh_lines/projection.rs b/crates/engine/src/mesh_lines/projection.rs index a7854723c..f7275111c 100644 --- a/crates/engine/src/mesh_lines/projection.rs +++ b/crates/engine/src/mesh_lines/projection.rs @@ -1,8 +1,10 @@ //! Vector hidden-line removal: intersect each projected edge with triangle half planes and //! its depth plane, then union occluded parameter intervals. A BVH bounds the candidate work. +use solidcore_record::{Plane, Vec2, Vec3}; +use solidcraft_geom::Aabb3; #[cfg(test)] use solidcraft_geom::Mesh; -use solidcraft_geom::{Aabb3, Plane, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use solidcraft_render::Camera; use std::collections::BTreeMap; diff --git a/crates/engine/src/mesh_lines/scene.rs b/crates/engine/src/mesh_lines/scene.rs index db47cc138..8476d4465 100644 --- a/crates/engine/src/mesh_lines/scene.rs +++ b/crates/engine/src/mesh_lines/scene.rs @@ -2,13 +2,15 @@ //! triangle hierarchy per shared mesh. Per-placement node bounds are small; projected //! triangle coordinates are evaluated only in visited leaves. Covered line intervals prune //! subsequent nodes and instances, including the entire query once coverage is complete. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use web_time::Instant; +use solidcore_record::Vec3; use solidcraft_doc::{apply_point, apply_vector}; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcraft_geom::{Aabb3, Mesh}; use super::meshes::{Placement, Scene, WORKERS, claim, transformed_bounds}; use super::progress::Stage; @@ -690,7 +692,7 @@ mod tests { } fn canonical(lines: Vec) -> Vec<([i64; 2], [i64; 2], bool)> { - let k = |p: solidcraft_geom::Vec2| [(p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64]; + let k = |p: solidcore_record::Vec2| [(p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64]; let mut result = lines .into_iter() .map(|l| { diff --git a/crates/engine/src/naming_history_tests.rs b/crates/engine/src/naming_history_tests.rs index 980c14fbc..bd7ea0f7b 100644 --- a/crates/engine/src/naming_history_tests.rs +++ b/crates/engine/src/naming_history_tests.rs @@ -4,7 +4,7 @@ //! names again by sampling geometry could do. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -27,14 +27,25 @@ fn error(s: &Session, name: &str) -> Option { s.model.result(id(s, name)).and_then(|r| r.error.clone()) } +/// The reference feature `name` failed on, asking for it to be picked again. +fn reselect(s: &Session, name: &str) -> Option { + let error = error(s, name)?; + solidcraft_doc::reselect_parts(&error).filter(|(feature, _)| *feature == name).map(|(_, reference)| reference.to_string()) +} + /// Whether any body holds `p`. fn solid_at(s: &Session, p: [f64; 3]) -> bool { - s.model.state().bodies.iter().any(|b| b.body.contains(Vec3::new(p[0], p[1], p[2]))) + s.model.state().bodies.iter().any(|b| b.body.classify_point(Vec3::new(p[0], p[1], p[2])).unwrap() == solidcraft_kernel::PointClass::Inside) } /// Which body holds `p`. fn body_at(s: &Session, p: [f64; 3]) -> Option { - s.model.state().bodies.iter().find(|b| b.body.contains(Vec3::new(p[0], p[1], p[2]))).map(|b| b.name.clone()) + s.model + .state() + .bodies + .iter() + .find(|b| b.body.classify_point(Vec3::new(p[0], p[1], p[2])).unwrap() == solidcraft_kernel::PointClass::Inside) + .map(|b| b.name.clone()) } fn names(s: &Session, body: &str) -> Vec<(String, bool)> { @@ -143,8 +154,8 @@ fn a_blend_follows_its_named_edge_to_a_moved_lid_instead_of_the_body_below() { let lid_volume = solidcraft_kernel::measure(&lid.body).unwrap().volume; assert!((base_volume - 24000.0).abs() < 0.01, "{command}: the base stays sharp: {base_volume}"); assert!((lid_volume - (6000.0 - removed)).abs() < 0.01, "{command}: the lid keeps its blend: {lid_volume}"); - assert!(base.body.contains(Vec3::new(39.9, 29.9, 12.5))); - assert!(!lid.body.contains(Vec3::new(39.9, 29.9, 22.5))); + assert_eq!(base.body.classify_point(Vec3::new(39.9, 29.9, 12.5)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(lid.body.classify_point(Vec3::new(39.9, 29.9, 22.5)).unwrap(), solidcraft_kernel::PointClass::Outside); } } @@ -171,14 +182,16 @@ fn a_piece_keeps_its_identity_when_the_cut_that_made_it_moves_or_shrinks() { change(&mut s, "slot_w", "0.05 mm"); assert_eq!(warning(&s, "Raise"), None); assert!(solid_at(&s, [39.0, 15.0, 11.0]) && !solid_at(&s, [27.0, 15.0, 11.0])); - // Gone altogether (suppressed), the piece is the whole top again: said, not guessed. + // Gone altogether (suppressed), the top is whole again, which is not the piece: the raise + // fails, asking for its face again, never guessed. run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": true})); - let w = warning(&s, "Raise").unwrap_or_default(); - assert!(w.contains("split") || w.contains("no longer exists"), "{w}"); + assert_eq!(reselect(&s, "Raise").as_ref(), raise.face_names.first()); } +/// A face merged into another is not the face that was picked: the feature on it fails, asking +/// for its face again; when the faces part again, the reference finds its face. #[test] -fn a_face_merged_into_another_answers_to_its_name_and_says_so() { +fn a_face_merged_into_another_asks_for_its_face_again() { let mut s = Session::default(); block(&mut s); run(&mut s, "parameters.add", json!({"name": "boss_h", "expression": "5 mm"})); @@ -191,13 +204,13 @@ fn a_face_merged_into_another_answers_to_its_name_and_says_so() { let raise = s.doc.find_feature("Raise").cloned().unwrap(); assert_eq!(raise.face_names, vec![format!("F{boss}:top")]); assert!(solid_at(&s, [50.0, 15.0, 5.5]) && !solid_at(&s, [50.0, 15.0, 6.5])); - // As tall as the block, the boss's top and the block's are one face: the reference finds - // it and says it was merged. + // As tall as the block, the boss's top and the block's are one face: not the boss's top. change(&mut s, "boss_h", "10 mm"); + assert_eq!(reselect(&s, "Raise").as_ref(), raise.face_names.first()); + assert!(!solid_at(&s, [50.0, 15.0, 10.5]) && !solid_at(&s, [20.0, 15.0, 10.5]), "nothing is raised"); + change(&mut s, "boss_h", "5 mm"); assert_eq!(error(&s, "Raise"), None); - let w = warning(&s, "Raise").unwrap_or_default(); - assert!(w.contains("merged"), "{w}"); - assert!(solid_at(&s, [50.0, 15.0, 10.5]) && solid_at(&s, [20.0, 15.0, 10.5]), "the merged top is raised as one"); + assert!(solid_at(&s, [50.0, 15.0, 5.5]) && !solid_at(&s, [20.0, 15.0, 10.5])); } #[test] @@ -251,6 +264,40 @@ fn pieces_of_a_cut_body_keep_their_body_names_when_the_cut_moves() { } } +/// A hole that cuts a body in three pieces names them as the design names them when it is +/// evaluated again from the names it pinned, as on opening it. Found by the model fuzzer: the two +/// smaller pieces swapped names there, so a later feature naming one of them met the other. +#[test] +fn pieces_of_a_cut_keep_their_names_when_the_design_is_evaluated_again() { + let mut s = Session::default(); + run(&mut s, "construct.plane.offset", json!({"base": "XZ", "name": "P8", "offset": 5})); + run(&mut s, "sketch.create", json!({"plane": "P8"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-7, -9], "p1": [5, -7]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "join"})); + run(&mut s, "sketch.create", json!({"plane": "XZ"})); + run(&mut s, "sketch.circle.center", json!({"center": [7, -3], "radius": 4})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "join"})); + run(&mut s, "solid.hole", json!({"depth": 14, "diameter": 5, "position": [-1, 10, 8]})); + // Each body by name, with where it is (two pieces have the same volume). + let pieces = |st: &solidcraft_doc::ModelState| -> Vec<(String, String)> { + st.bodies + .iter() + .map(|b| { + let m = solidcraft_kernel::measure(&b.body).unwrap(); + (b.name.clone(), format!("{:.3} {:.3} {:.3} {:.3}", m.volume, m.centroid.x, m.centroid.y, m.centroid.z)) + }) + .collect() + }; + let live = pieces(&s.model.state()); + assert_eq!(live.len(), 3, "{live:?}"); + let mut again = solidcraft_doc::Model::new(); + again.no_cache = true; + again.evaluate(&s.doc); + assert_eq!(pieces(&again.state()), live); +} + #[test] fn a_name_of_a_body_without_history_is_found_by_geometry_and_says_so_once_it_moves() { let mut s = Session::default(); @@ -337,6 +384,59 @@ fn a_sketch_on_a_certified_face_survives_a_fillet_and_a_cut_upstream_of_it() { assert!((top(&s) - 20.0).abs() < 1e-6, "{}", top(&s)); } +/// A blend's seams are those with the faces either side of the edge it replaced and with other +/// blends (a corner patch and its rounds); where a round runs into an end face is not one. +#[test] +fn blend_seams_are_a_rounds_contacts_and_the_blends_beside_it() { + use solidcraft_doc::naming::{BlendSeamKind, blend_seams}; + let mut s = Session::default(); + block(&mut s); + run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2, "tangent_chain": false})); + let state = s.model.state(); + let seams = blend_seams(&state.bodies[0]); + assert_eq!(seams.len(), 2, "the round's two tangent seams, not its two ends: {seams:?}"); + assert!(seams.iter().all(|x| x.kind == BlendSeamKind::Contact && !x.corner), "{seams:?}"); + + let mut s = Session::default(); + block(&mut s); + run(&mut s, "solid.fillet", json!({"edges": [[40, 15, 10], [20, 30, 10], [40, 30, 5]], "radius": 2, "tangent_chain": false})); + let state = s.model.state(); + let seams = blend_seams(&state.bodies[0]); + let contact = seams.iter().filter(|x| x.kind == BlendSeamKind::Contact).count(); + let corner: Vec<_> = seams.iter().filter(|x| x.corner).collect(); + assert_eq!(contact, 6, "each round's two faces: {seams:?}"); + assert_eq!(corner.len(), 3, "the corner patch's seams with the three rounds: {seams:?}"); + assert!(corner.iter().all(|x| x.kind == BlendSeamKind::Blend), "{seams:?}"); +} + +/// A round along a chain onto an earlier round's end has that round for one of its faces, and +/// that round's own faces are not its own: where it runs into the cylinder the earlier round +/// rolls on, its end face, is no seam of it (a block's arc at a cylinder rounded r2, then the +/// block's top edge with the round's end curve on its side face rounded r1; the earlier round's +/// name holds a `|` of its own, `F3:blend:F1:+z|F2:side`). +#[test] +fn a_round_of_a_round_s_end_has_no_seam_with_that_round_s_faces() { + use solidcraft_doc::naming::{blend_seams, face_names}; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 10, "height": 15, "corner": [0, -5, 0], "body_name": "Block"})); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 30, "base": [0, 0, 0], "operation": "join", "targets": ["Block"]})); + run(&mut s, "solid.fillet", json!({"edges": [[10, 0, 15]], "radius": 2})); + run(&mut s, "solid.fillet", json!({"edges": [[30, 5, 15]], "radius": 1})); + let state = s.model.state(); + let body = &state.bodies[0]; + let names = face_names(body); + let mesh = body.mesh(); + let sides = |edge: usize| -> Vec<&str> { mesh.edge_faces[edge].iter().filter_map(|f| names.get(*f as usize).map(String::as_str)).collect() }; + let seams = blend_seams(body); + assert!(!seams.is_empty()); + for seam in &seams { + let faces = sides(seam.edge); + if faces.iter().any(|n| n.starts_with("F2:side")) { + assert!(faces.iter().any(|n| n.starts_with("F3:blend:")), "a seam of the r2 round only: {faces:?}"); + } + } +} + /// A fillet of a shell's inner corners names those edges. Thinning the wall past the outer /// round removes them. The fillet must say the names are gone, not blend the seam nearest /// the old pick, which now sits on the axis of the inner round (#775). @@ -389,10 +489,10 @@ fn named_at(faces: &[(String, bool, [f64; 3])], at: [f64; 3]) -> String { } /// #1209: an arm with a boss at each end (each boss the radius of the arm's round end under it) -/// and a square cut through one. The second boss and the cut are prism booleans sewn slab by -/// slab, where the arm's round end and the boss over it are two pieces of one cylinder: every -/// face keeps exact history, so the cut's walls are its own four faces and the boss's outer -/// cylinder keeps its name, through the fillets on the bore's corners too. +/// and a square cut through one. The arm's round end and the boss over it lie on one cylinder, +/// which SMLib keeps one face, named for the arm's end it began as: every face keeps exact +/// history, so the cut's walls are its own four faces and the boss's outer cylinder keeps its +/// name, through the fillets on the bore's corners too. #[test] fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { let mut s = Session::default(); @@ -412,8 +512,10 @@ fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"distance": 16, "body_name": "Arm"})); run(&mut s, "solid.cylinder", json!({"diameter": 46.0, "height": 22, "base": [0, 0, 0], "operation": "join", "targets": ["Arm"]})); - let boss = named_at(&listed(&mut s, "Arm"), [19.98, -4.24, 19.0]); - assert!(boss.starts_with("F3:side"), "{boss}"); + // A point on the boss's outer wall, above the arm. + let wall = |s: &Session| solidcraft_doc::naming::face_names_at(&s.model.state(), &[Vec3::new(-23.0, 0.0, 19.0)]).pop().unwrap_or_default(); + let boss = wall(&s); + assert!(boss.starts_with("F2:side:a"), "{boss}"); run(&mut s, "solid.cylinder", json!({"diameter": 30.0, "height": 20, "base": [170.0, 0, 0], "operation": "join", "targets": ["Arm"]})); let joined = listed(&mut s, "Arm"); assert!(joined.iter().all(|(_, exact, _)| *exact), "{joined:?}"); @@ -428,47 +530,57 @@ fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { for (at, line) in [([0.0, -6.35, 11.0], "l1"), ([6.35, 0.0, 11.0], "l2"), ([0.0, 6.35, 11.0], "l3"), ([-6.35, 0.0, 11.0], "l4")] { assert_eq!(named_at(&cut, at), format!("F6:side:{line}")); } - assert_eq!(named_at(&cut, [19.98, -4.24, 19.0]), boss); + assert_eq!(wall(&s), boss); run(&mut s, "solid.fillet", json!({"edges": [[6.35, 6.35, 10], [-6.35, 6.35, 10], [-6.35, -6.35, 10], [6.35, -6.35, 10]], "radius": 1.5})); let filleted = listed(&mut s, "Arm"); let blends = filleted.iter().filter(|(n, _, _)| n.starts_with("F7:blend:")).count(); assert_eq!(blends, 4, "{filleted:?}"); - assert_eq!(named_at(&filleted, [19.98, -4.24, 19.0]), boss); + assert_eq!(wall(&s), boss); } -/// #3902: a torus with a closed, twisted square sweep cut inside it splits the sweep's walls into -/// pieces the kernel returns in a different order on each evaluation. The pieces are numbered by -/// where they lie, so every fresh evaluation gives each piece the same name. +/// A disc whose top a round groove along x splits into two pieces of one name, numbered by +/// place: `F1:top#1` on the -y side, `F1:top#2` on the +y side. +fn grooved_disc() -> Value { + json!([ + {"command": "solid.cylinder", "params": {"radius": 20, "height": 10, "body_name": "Disc"}}, + {"command": "solid.cylinder", "params": {"axis": [1, 0, 0], "base": [-25, 0, 10], "radius": 3, "height": 60, "operation": "cut"}} + ]) +} + +/// #3902: a torus with a closed, twisted square sweep cut inside it split the sweep's walls into +/// pieces truck returned in a different order on each evaluation (SMLib keeps those walls +/// whole), and a grooved disc's top is two pieces of one name. Pieces are numbered by where they +/// lie, so every fresh evaluation gives each face the same name. #[test] fn split_pieces_keep_their_numbers_across_evaluations() { - let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/closed_sweep_torus_cut.json")).unwrap(); - let mut s = Session::default(); - s.run_script(&script).unwrap(); - let body = s.model.state().bodies.first().map(|b| b.name.clone()).expect("a body"); - let named = |s: &mut Session| -> Vec<(String, [i64; 3])> { - let mut faces: Vec<(String, [i64; 3])> = listed(s, &body).into_iter().map(|(n, _, c)| (n, c.map(|x| x.round() as i64))).collect(); - faces.sort(); - faces - }; - let first = named(&mut s); - assert!(first.iter().any(|(n, _)| n.contains('#')), "no split pieces: {first:?}"); - for run in 0..10 { - let mut fresh = Session::new(solidcraft_doc::Document::clone(&s.doc)); - fresh.refresh(); - assert_eq!(named(&mut fresh), first, "evaluation {run}"); + let torus: Value = serde_json::from_str(include_str!("../../../examples/regressions/closed_sweep_torus_cut.json")).unwrap(); + for (script, pieces) in [(torus, false), (grooved_disc(), true)] { + let mut s = Session::default(); + s.run_script(&script).unwrap(); + let body = s.model.state().bodies.first().map(|b| b.name.clone()).expect("a body"); + let named = |s: &mut Session| -> Vec<(String, [i64; 3])> { + let mut faces: Vec<(String, [i64; 3])> = listed(s, &body).into_iter().map(|(n, _, c)| (n, c.map(|x| x.round() as i64))).collect(); + faces.sort(); + faces + }; + let first = named(&mut s); + assert_eq!(first.iter().any(|(n, _)| n.contains('#')), pieces, "split pieces: {first:?}"); + for run in 0..10 { + let mut fresh = Session::new(solidcraft_doc::Document::clone(&s.doc)); + fresh.refresh(); + assert_eq!(named(&mut fresh), first, "evaluation {run}"); + } } } -/// #3902: a design saved before the pieces of a face were numbered by place opens with the -/// numbers it was saved with, so a reference to `…#1` stays on the piece it was made on. The -/// block cut by the second block here has its side split in two, numbered the other way round -/// by place. +/// #3902: a design saved before the pieces of a face were numbered by place opens with its +/// features marked `kernel_piece_order`, and evaluates: its pieces are named alike every time it +/// is evaluated. (Which numbers they get is not promised to be the ones it was saved with.) #[test] -fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { - let script: Value = serde_json::from_str(include_str!("../../../tests/action_matrix/designs/multi-body-join-cut.json")).unwrap(); +fn a_design_saved_before_pieces_were_numbered_by_place_opens_marked_and_names_alike() { let mut s = Session::default(); - s.run_script(&script).unwrap(); - let by_place = listed(&mut s, "Block"); + s.run_script(&grooved_disc()).unwrap(); + let by_place = listed(&mut s, "Disc"); // As a build before the change saved it: its features carry no mark, and the file does not // list the change among those it has. let mut file: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); @@ -484,16 +596,14 @@ fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { assert!(old.features.iter().all(|f| f.kernel_piece_order), "the features of an older design keep the old numbering"); let mut reopened = Session::new(old); reopened.refresh(); - let kept = listed(&mut reopened, "Block"); - let at = |faces: &[(String, bool, [f64; 3])], name: &str| faces.iter().find(|(n, _, _)| n == name).map(|(_, _, c)| *c); - // The pieces are numbered differently by place, and the older design keeps its own numbers. - let (old1, new1) = (at(&kept, "F2:side#1").unwrap(), at(&by_place, "F2:side#1").unwrap()); - assert!((0..3).any(|k| (old1[k] - new1[k]).abs() > 1.0), "{kept:?} {by_place:?}"); + assert!(reopened.model.results.iter().all(|r| r.error.is_none()), "{:?}", reopened.model.results); + let kept = listed(&mut reopened, "Disc"); + assert_eq!(kept.len(), by_place.len()); let mut legacy = solidcraft_doc::Document::clone(&s.doc); legacy.features.iter_mut().for_each(|f| f.kernel_piece_order = true); let mut saved_with = Session::new(legacy); saved_with.refresh(); - assert_eq!(listed(&mut saved_with, "Block"), kept); + assert_eq!(listed(&mut saved_with, "Disc"), kept); } /// The volumes of the design's bodies, by name. @@ -593,9 +703,9 @@ fn one_fillet_over_two_bodies_of_one_extrude_rounds_each_body_s_own_edges() { /// One fillet over a vertical edge of each of two stacked boxes. A build before blends were split /// by body named the upper box's edge after the lower box's nearest edge (its top front edge), /// which was rounded instead. The pick (outside the box the name was recorded on) shows that name -/// is not the upper box's: the edge is found at its point, on the upper box. +/// is not the upper box's edge: the fillet fails, asking for that edge again, and rounds nothing. #[test] -fn one_fillet_over_stacked_boxes_rounds_the_upper_box_s_edge_even_when_saved_named_on_the_lower() { +fn one_fillet_over_stacked_boxes_saved_named_on_the_lower_asks_for_the_upper_edge_again() { let mut s = Session::default(); stacked_boxes(&mut s); run(&mut s, "solid.fillet", json!({"edges": [[25, -25, 20], [-25, -25, 45]], "radius": 2, "name": "Rounds"})); @@ -618,8 +728,62 @@ fn one_fillet_over_stacked_boxes_rounds_the_upper_box_s_edge_even_when_saved_nam let old_refs = solidcraft_doc::edge_refs(&before, &Some(lower.name.clone().into()), &[Vec3::new(25.0, -25.0, 20.0), Vec3::new(-25.0, -25.0, 45.0)]); let feature = s.doc_mut().feature_mut(f).unwrap(); - feature.edge_names = old_names; + feature.edge_names = old_names.clone(); feature.edge_refs = old_refs; s.refresh(); - check(&s, "saved by an older build"); + assert_eq!(reselect(&s, "Rounds").as_ref(), old_names.get(1)); + assert!(solid_at(&s, [24.8, -24.8, 20.0]) && solid_at(&s, [-24.8, -24.8, 45.0]), "nothing is rounded"); +} + +/// A shell opened by a point pick on a bar's end face keeps opening that face when a parameter +/// edit moves the bar so the stored point no longer lies on it (it now lies on the bottom face). +/// The point is moved onto the named face clear of its edges: the face's nearest point to the old +/// pick is on the edge it shares with the bottom face, where a pick finds both faces (#2531). +#[test] +fn a_shell_point_pick_moved_off_its_face_reopens_only_that_face() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "L", "expression": "100 mm", "unit": "mm"})); + run(&mut s, "parameters.add", json!({"name": "Y0", "expression": "5 mm", "unit": "mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 5], "p1": [100, 25]})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["origin", "l1.start"], "mode": "vertical"})); + run(&mut s, "sketch.dimension", json!({"entities": ["origin", "l1.start"], "type": "vertical", "value": "Y0"})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "type": "length", "value": "L"})); + run(&mut s, "sketch.dimension", json!({"entities": ["l4"], "type": "length", "value": "20 mm"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": "20 mm", "operation": "new", "body_name": "Bar"})); + run(&mut s, "solid.shell", json!({"faces": [[100, 15, 10]], "thickness": "2 mm", "direction": "inside", "body": "Bar", "name": "Shell"})); + change(&mut s, "L", "150 mm"); + change(&mut s, "Y0", "15 mm"); + assert_eq!(error(&s, "Shell"), None); + let state = s.model.state(); + let bar = state.body("Bar").expect("the shelled bar"); + let volume = solidcraft_kernel::measure(&bar.body).expect("measure").volume; + // 150 x 20 x 20 open at x = 150 only: 60000 - 148 * 16 * 16. + assert!((volume - 22112.0).abs() < 1e-3, "{volume}"); + assert_eq!(bar.body.face_count(), 11); + assert!(solid_at(&s, [100.0, 16.0, 10.0]), "the bottom face stays closed"); + assert!(!solid_at(&s, [149.0, 25.0, 10.0]), "the end at x = 150 is open"); +} + +/// A two-distance chamfer of a plate's bottom front edge running 220 up the front face, past the +/// 85 mm where the plate's sides start to taper (rig fillets/5181): the chamfer takes up the front +/// face's straight side edges too, and lies between their faces, but it is made from the picked +/// edge alone. Its one face has the picked edge's name everywhere on it (it was named after the +/// left side's edge, l6, the first edge it took up). +#[test] +fn a_chamfer_running_past_the_side_edges_it_takes_up_is_named_by_its_edge() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Bracket"})); + let taper = 30.675635228421154; + run(&mut s, "sketch.line", json!({"points": [[-50, 0], [50, 0], [50, 85], [taper, 222.5], [-taper, 222.5], [-50, 85]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Bracket", "distance": 23, "body_name": "Bracket"})); + run(&mut s, "solid.chamfer", json!({"edges": [[0, 0, 0]], "distance": 220, "distance2": 11})); + let blends: Vec = names(&s, "Bracket").into_iter().map(|(n, _)| n).filter(|n| n.starts_with("F3:blend:")).collect(); + assert_eq!(blends, vec!["F3:blend:F2:side:l1|F2:start".to_string()]); + // On the chamfer's plane, through (x, -11, 0) and (x, 0, 220): below and above z = 85. + let on = |z: f64| Vec3::new(0.0, -11.0 * (1.0 - z / 220.0), z); + let at = solidcraft_doc::naming::face_names_at(&s.model.state(), &[on(40.0), on(150.0)]); + assert_eq!(at, vec![blends[0].clone(), blends[0].clone()]); } diff --git a/crates/engine/src/occurrences.rs b/crates/engine/src/occurrences.rs index ec6a34d1b..8492aedae 100644 --- a/crates/engine/src/occurrences.rs +++ b/crates/engine/src/occurrences.rs @@ -1,5 +1,5 @@ //! Exact placement identity and session view/authoring state. -use crate::{EngineError, Result, Sel, Session}; +use crate::{EngineError, Result, Sel, Session, Visibility}; use solidcraft_doc::{FeatureKind, IDENTITY, Mat, PlaneRef, mat_mul}; #[derive(Clone, Debug)] @@ -32,6 +32,153 @@ pub(crate) struct VisibilityCache { bodies: std::collections::BTreeSet, } +/// The hidden joints, folders and bodies of the view, as sets: the browser asks about every +/// joint and every folder of the design on every frame, the viewport about every body several +/// times a frame, and an answer that walked the hidden lists made a frame cost grow with the +/// size of the design (#3892). The sets are built when the view changes and are kept until it +/// changes again. +pub(crate) struct VisibilityIndex { + /// The revision of the design the sets were built for. + revision: u64, + /// Where the hidden joints were when the sets were built: the list is replaced (the + /// whole view is replaced) or written in place (a joint is hidden or shown), and this + /// says whether the list the sets were built from is still the list of the view. + joints_at: ListId, + /// The hidden joint ids. + joint_ids: std::collections::HashSet, + /// Where the hidden folders were when the sets were built. + folders_at: ListId, + /// The hidden folder keys. + folder_keys: std::collections::HashSet, + /// Where the hidden bodies were when the sets were built. + bodies_at: ListId, + /// The names of the bodies hidden themselves. + body_names: std::collections::HashSet, + /// The hidden joints and folders, as they were when the sets were built: they are + /// compared with these to tell a change of the view from a change of the design alone + /// (the design changes far more often than the view does). + joints: Vec, + folders: Vec, + bodies: Vec, +} + +/// Where a list of hidden items was: the address of its buffer and how many items it held. +/// A list that is replaced gets a buffer of its own (the old one is still alive while the +/// new one is allocated, so the addresses differ), and a list that is written in place keeps +/// its buffer; the length then says how much of it is written. +#[derive(Clone, Copy, PartialEq, Eq)] +struct ListId { + address: usize, + length: usize, +} + +impl ListId { + fn of(list: &[T]) -> ListId { + ListId { address: list.as_ptr() as usize, length: list.len() } + } +} + +impl VisibilityIndex { + /// The sets of the hidden joints and folders of a view. + fn new(revision: u64, v: &Visibility) -> VisibilityIndex { + let joint_ids: std::collections::HashSet = v.hidden_joints.iter().copied().collect(); + let folder_keys: std::collections::HashSet = v.hidden_folders.iter().cloned().collect(); + let body_names: std::collections::HashSet = v.hidden_bodies.iter().cloned().collect(); + visibility_work::built(joint_ids.len() as u64 + folder_keys.len() as u64 + body_names.len() as u64); + VisibilityIndex { + revision, + joints_at: ListId::of(&v.hidden_joints), + joint_ids, + folders_at: ListId::of(&v.hidden_folders), + folder_keys, + bodies_at: ListId::of(&v.hidden_bodies), + body_names, + joints: v.hidden_joints.clone(), + folders: v.hidden_folders.clone(), + bodies: v.hidden_bodies.clone(), + } + } + + /// Do the sets still answer for this design and this view? The revision says the design + /// changed; the lists say the view changed under it (the view is replaced outside the + /// engine too, without a revision of its own). + /// + /// The first and last entries of each list are part of the answer: a buffer that was freed + /// and handed out again holds another list, and the entries say so. + fn matches(&self, revision: u64, v: &Visibility) -> bool { + self.revision == revision + && self.joints_at == ListId::of(&v.hidden_joints) + && self.folders_at == ListId::of(&v.hidden_folders) + && self.joints.first() == v.hidden_joints.first() + && self.joints.last() == v.hidden_joints.last() + && self.folders.first() == v.hidden_folders.first() + && self.folders.last() == v.hidden_folders.last() + && self.bodies_at == ListId::of(&v.hidden_bodies) + && self.bodies.first() == v.hidden_bodies.first() + && self.bodies.last() == v.hidden_bodies.last() + } + + /// Are the hidden joints and folders the ones the sets were built from? A design that + /// changed without touching the view leaves the sets alone. + fn same_lists(&self, v: &Visibility) -> bool { + self.joints == v.hidden_joints && self.folders == v.hidden_folders && self.bodies == v.hidden_bodies + } + + /// The lists are the ones the sets were built from, at another revision. + fn restamp(&mut self, revision: u64, v: &Visibility) { + self.revision = revision; + self.joints_at = ListId::of(&v.hidden_joints); + self.folders_at = ListId::of(&v.hidden_folders); + self.bodies_at = ListId::of(&v.hidden_bodies); + } +} + +/// How many entries of the hidden lists a visibility answer had to walk, and how many the +/// index was built from. The browser asks about every joint of the design on every frame, so +/// the answer must not cost more as the design grows (#3892); the counters make that cost +/// visible to a test. +pub(crate) mod visibility_work { + #[cfg(test)] + use std::cell::Cell; + + // The counter of the thread that asks: the tests run beside each other, and each counts + // its own work. + #[cfg(test)] + thread_local! { + static WALKED: Cell = const { Cell::new(0) }; + static BUILT: Cell = const { Cell::new(0) }; + } + + /// The entries the answers of this thread walked since the last [`take`]. + #[cfg(test)] + pub(crate) fn take() -> u64 { + WALKED.with(|walked| walked.replace(0)) + } + + /// Count the entries an answer walked. + pub(crate) fn add(walked: u64) { + #[cfg(test)] + WALKED.with(|count| count.set(count.get() + walked)); + #[cfg(not(test))] + let _ = walked; + } + + /// Count the entries the index was built from: the index is built once per change of the + /// view, not once per answer, so this work is apart from the answers' own. + pub(crate) fn built(built: u64) { + #[cfg(test)] + BUILT.with(|count| count.set(count.get() + built)); + #[cfg(not(test))] + let _ = built; + } + + /// The entries the index was built from since the last [`built_take`]. + #[cfg(test)] + pub(crate) fn built_take() -> u64 { + BUILT.with(|count| count.replace(0)) + } +} + /// [`Session::occurrence_bodies`] answers for one document, evaluated model and set of pending /// moves. The document and model are kept alive with the answers, so neither a new document nor /// a later allocation at the same address can reuse them. @@ -132,8 +279,10 @@ pub(crate) struct RemovedLaterCache { } impl Session { - /// Hidden names follow the same body and exact occurrence path through a rename. Undo - /// history restores visibility separately. Never parse display labels: + /// Hidden names and the bodies the selection names follow the same body and exact + /// occurrence path through a rename (#9737: a selected body stays selected under its new + /// name, so Delete hits the body the user actually selected, never one that later takes + /// the old name). Undo history restores visibility separately. Never parse display labels: /// ambiguous labels and names containing slashes use the document's canonical naming. pub(crate) fn remap_hidden_bodies( &mut self, @@ -141,7 +290,8 @@ impl Session { state: &solidcraft_doc::ModelState, rename: Option<(&str, &str)>, ) { - if self.visibility.hidden_bodies.is_empty() { + let selected: std::collections::BTreeSet<&str> = self.selection.iter().filter_map(|s| s.body_name()).collect(); + if self.visibility.hidden_bodies.is_empty() && selected.is_empty() { return; } if rename.is_none() { @@ -161,19 +311,39 @@ impl Session { } let hidden: std::collections::BTreeSet<_> = self.visibility.hidden_bodies.iter().map(String::as_str).collect(); let mut names = std::collections::BTreeMap::new(); + let mut destinations = std::collections::BTreeSet::new(); let (before, after) = (solidcraft_doc::WorldNames::new(previous, state), solidcraft_doc::WorldNames::new(&self.doc, &renamed)); for (component, path, _) in previous.placements() { for body in state.bodies.iter().filter(|body| previous.model_body_component(body) == component) { let old = before.name(&body.name, component, &path); - if hidden.contains(old.as_str()) { - let source = rename.filter(|(old, _)| *old == body.name).map_or(body.name.as_str(), |(_, new)| new); - names.insert(old, after.name(source, component, &path)); + let source = rename.filter(|(old, _)| *old == body.name).map_or(body.name.as_str(), |(_, new)| new); + let new = after.name(source, component, &path); + if old != new { + destinations.insert(new.clone()); + } + if hidden.contains(old.as_str()) || selected.contains(old.as_str()) { + names.insert(old, new); } } } - for hidden in &mut self.visibility.hidden_bodies { + self.visibility.hidden_bodies.retain_mut(|hidden| { if let Some(new) = names.get(hidden) { hidden.clone_from(new); + true + } else { + // A deleted body's hidden name can be reused (#10163). Only a current + // body's hide follows into that name; a stale entry must not hide it. + !destinations.contains(hidden) + } + }); + for sel in &mut self.selection { + let name = match sel { + Sel::Body { name } => name, + Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => body, + _ => continue, + }; + if let Some(new) = names.get(name.as_str()) { + name.clone_from(new); } } } @@ -211,13 +381,42 @@ impl Session { } std::borrow::Cow::Owned(doc) } - /// Resolve only the supplied path, never an exponentially expanded assembly. The placement - /// index answers from lookups; the plain walk stays as the fallback and the error reporter. - pub fn occurrence_placement(&self, path: &[u64]) -> Result { - if path.is_empty() || path.len() > 64 { - return Err(invalid("occurrence path must contain 1..64 ids")); + /// The occurrence moves of the design not captured yet: `pending_moves` without the + /// placements the exploded view shows ([`Session::exploded`]), which are display only. An + /// entry the exploded view put there and nothing has moved since is left out; one moved since + /// (dragged, played) is a move like any other. + pub fn uncaptured_moves(&self) -> std::borrow::Cow<'_, std::collections::BTreeMap> { + if !self.pending_moves.iter().any(|(id, m)| self.exploded.get(id) == Some(m)) { + return std::borrow::Cow::Borrowed(&self.pending_moves); } - if let Some(placement) = self.occurrence_placement_indexed(path) { + std::borrow::Cow::Owned(self.pending_moves.iter().filter(|(id, m)| self.exploded.get(id) != Some(*m)).map(|(id, m)| (*id, *m)).collect()) + } + + /// The document with the design's own uncaptured moves applied ([`Session::uncaptured_moves`]): + /// [`Session::placed_document`] without the exploded view, for what reports the design's + /// placements or works a new placement out from them. + pub fn design_document(&self) -> std::borrow::Cow<'_, solidcraft_doc::Document> { + let moves = self.uncaptured_moves(); + if moves.is_empty() { + return std::borrow::Cow::Borrowed(&self.doc); + } + let mut doc = (*self.doc).clone(); + for o in &mut doc.occurrences { + if let Some(transform) = moves.get(&o.id) { + o.transform = *transform; + } + } + std::borrow::Cow::Owned(doc) + } + + /// Resolve only the supplied path, never an exponentially expanded assembly: placed where + /// it is shown (uncaptured moves and the exploded view included). + /// The placement index answers from lookups; the plain walk stays as the fallback and the error reporter. + pub fn occurrence_placement(&self, path: &[u64]) -> Result { + if !path.is_empty() + && path.len() <= 64 + && let Some(placement) = self.occurrence_placement_indexed(path) + { return Ok(placement); } self.occurrence_placement_walk(path) @@ -277,6 +476,13 @@ impl Session { /// The plain walk over `doc.occurrences`, kept as the fallback for paths the index can't /// answer and as the reference the indexed answers are checked against (#7502). pub(crate) fn occurrence_placement_walk(&self, path: &[u64]) -> Result { + self.occurrence_placement_with(path, &self.pending_moves) + } + + /// [`Session::occurrence_placement`] with the occurrences moved by `moves` instead of + /// `pending_moves` (the design's own, [`Session::uncaptured_moves`], for what reports the + /// design's placements). The placement index holds `pending_moves`, so this walks the path. + pub fn occurrence_placement_with(&self, path: &[u64], moves: &std::collections::BTreeMap) -> Result { if path.is_empty() || path.len() > 64 { return Err(invalid("occurrence path must contain 1..64 ids")); } @@ -298,7 +504,7 @@ impl Session { return Err(invalid("occurrence path has a missing component")); } parent_world = world; - world = mat_mul(&world, self.pending_moves.get(id).unwrap_or(&o.transform)); + world = mat_mul(&world, moves.get(id).unwrap_or(&o.transform)); if world.iter().flatten().any(|x| !x.is_finite()) { return Err(invalid("occurrence path has a non-finite transform")); } @@ -319,7 +525,7 @@ impl Session { path: path.to_vec(), name: leaf.name.clone(), world, - local: self.pending_moves.get(&leaf.id).copied().unwrap_or(leaf.transform), + local: moves.get(&leaf.id).copied().unwrap_or(leaf.transform), parent_world, grounded: leaf.grounded, bodies, @@ -549,10 +755,36 @@ impl Session { Ok(count) } + /// The hidden joints, folders and bodies of the view, as sets: the browser asks about every + /// joint of the design on every frame, and an answer that walked the hidden lists made a + /// frame cost grow with the size of the design (#3892). The sets are built when the view + /// changes and are kept until it changes again. + fn visibility_index(&self) -> Option>> { + let mut cache = self.visibility_index_cache.lock().ok()?; + let v = &self.visibility; + if cache.as_ref().is_none_or(|c| !c.matches(self.revision, v)) { + // The design or the view changed. The sets are rebuilt only when the hidden lists + // themselves changed: a change of the design alone leaves them alone. + if cache.as_ref().is_some_and(|c| c.same_lists(v)) { + if let Some(c) = cache.as_mut() { + c.restamp(self.revision, v); + } + } else { + *cache = Some(VisibilityIndex::new(self.revision, v)); + } + } + Some(cache) + } + /// Whether a joint's glyph is drawn (`browser.visibility`). Hiding a joint only hides its /// drawing: it still constrains and drives the parts. /// Is the joint shown itself (its own eye; the Joints folder may still hide it)? pub fn joint_visible(&self, id: u64) -> bool { + if let Some(cache) = self.visibility_index() { + return cache.as_ref().is_none_or(|c| !c.joint_ids.contains(&id)); + } + // The lock is poisoned: answer from the list itself. + visibility_work::add(self.visibility.hidden_joints.len() as u64); !self.visibility.hidden_joints.contains(&id) } @@ -569,6 +801,11 @@ impl Session { /// Is a browser folder or group hidden itself (by tree key, see `Visibility::hidden_folders`)? pub fn folder_hidden(&self, key: &str) -> bool { + if let Some(cache) = self.visibility_index() { + return cache.as_ref().is_none_or(|c| c.folder_keys.contains(key)); + } + // The lock is poisoned: answer from the list itself. + visibility_work::add(self.visibility.hidden_folders.len() as u64); self.visibility.hidden_folders.iter().any(|k| k == key) } @@ -582,40 +819,57 @@ impl Session { || self.doc.browser_groups.iter().any(|g| { g.component == component && g.folder == folder - && g.items.iter().any(|i| i == item) - && self.folder_hidden(&format!("{scope}/g{}", g.id)) + && g.has_item(item) + // A hidden group hides the groups inside it. + && std::iter::successors(Some(g.id), |id| self.doc.browser_group(*id).and_then(|g| g.parent)) + .take(solidcraft_doc::MAX_GROUP_NESTING + 1) + .any(|id| self.folder_hidden(&format!("{scope}/g{id}"))) }) } + /// The placement a sketch or construction feature is drawn at: the active one while its + /// component is being edited, else the component's first (empty for the design's own). + fn feature_path(&self, component: u64) -> Vec { + match &self.active_occurrence_path { + _ if component == 0 => Vec::new(), + Some(p) if self.active_component == component => p.clone(), + _ => self.doc.first_path(component), + } + } + + /// Is the placement a sketch or construction feature is drawn at shown? + pub fn feature_placement_visible(&self, id: u64) -> bool { + if self.visibility.hidden_occurrences.is_empty() { + return true; + } + let component = self.doc.feature(id).map_or(0, |f| f.component); + component == 0 || self.occurrence_visible(&self.feature_path(component)) + } + /// Is a sketch or construction feature hidden by its folder or group, at the placement it - /// is drawn at (the active one while its component is being edited, else the first)? + /// is drawn at? pub fn feature_folder_hidden(&self, id: u64, folder: &str) -> bool { if self.visibility.hidden_folders.is_empty() { return false; } let component = self.doc.feature(id).map_or(0, |f| f.component); - let path = match &self.active_occurrence_path { - _ if component == 0 => Vec::new(), - Some(p) if self.active_component == component => p.clone(), - _ => self.doc.first_path(component), - }; - self.item_folder_hidden(&Self::folder_scope(&path), component, folder, &id.to_string()) + self.item_folder_hidden(&Self::folder_scope(&self.feature_path(component)), component, folder, &id.to_string()) } /// Is construction geometry or an origin item (by name) shown: not hidden itself, nor by - /// its folder or a group it is in? + /// its folder or a group it is in, nor by a hidden placement of its component? pub fn construction_visible(&self, name: &str) -> bool { if self.visibility.hidden_origin.iter().any(|h| h == name) { return false; } match self.doc.features.iter().find(|f| f.name == name) { - Some(f) => !self.feature_folder_hidden(f.id, "construction"), + Some(f) => self.feature_placement_visible(f.id) && !self.feature_folder_hidden(f.id, "construction"), None => true, } } pub fn body_visible(&self, name: &str) -> bool { - if self.visibility.hidden_bodies.iter().any(|n| n == name) || self.body_removed_later(name) { + if self.body_hidden_itself(name) || self.body_removed_later(name) { return false; } let v = &self.visibility; @@ -636,6 +890,16 @@ impl Session { !self.bodies_hidden_by_parents().contains(name) } + /// Is the body hidden itself (its own eye; a placement, folder or group may still hide it)? + fn body_hidden_itself(&self, name: &str) -> bool { + if let Some(cache) = self.visibility_index() { + return cache.as_ref().is_some_and(|c| c.body_names.contains(name)); + } + // The lock is poisoned: answer from the list itself. + visibility_work::add(self.visibility.hidden_bodies.len() as u64); + self.visibility.hidden_bodies.iter().any(|n| n == name) + } + /// World names of the bodies a hidden placement, folder or group above them hides (their /// own state aside). fn bodies_hidden_by_parents(&self) -> std::collections::BTreeSet { @@ -719,6 +983,7 @@ impl Session { pub(crate) fn prune_occurrence_state(&mut self) { self.pending_moves.retain(|id, _| self.doc.occurrences.iter().any(|o| o.id == *id)); + self.exploded.retain(|id, _| self.doc.occurrences.iter().any(|o| o.id == *id)); if self.active_component != 0 && !self.doc.components.iter().any(|c| c.id == self.active_component) { self.active_component = 0; self.active_occurrence_path = None; @@ -728,6 +993,16 @@ impl Session { } let selection = std::mem::take(&mut self.selection); self.selection = selection.into_iter().filter(|s| !matches!(s, Sel::Occurrence {path} if self.occurrence_placement(path).is_err())).collect(); + // A selected body that is gone cannot be deleted, measured or shown: drop it, so a + // later body taking its name is never deleted in its place (#9737). + if self.selection.iter().any(|s| s.body_name().is_some()) + && let Ok(world) = self.world_state() + { + self.selection.retain(|s| match s.body_name() { + Some(name) => world.body(name).is_some(), + None => true, + }); + } let hidden = std::mem::take(&mut self.visibility.hidden_occurrences); self.visibility.hidden_occurrences = hidden.into_iter().filter(|p| self.occurrence_placement(p).is_ok()).collect(); } diff --git a/crates/engine/src/panels/commands.rs b/crates/engine/src/panels/commands.rs new file mode 100644 index 000000000..486d23841 --- /dev/null +++ b/crates/engine/src/panels/commands.rs @@ -0,0 +1,946 @@ +//! Application-owned command execution shared by UI, control and headless MCP. +//! No Session, document, geometry, dialogs or camera are reachable here. +mod catalogue; + +use std::collections::BTreeMap; +use std::sync::Arc; + +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use super::*; +use crate::schema::panels as wire; + +pub const MAX_USER_PRESETS: usize = 64; +pub const MAX_WORKSPACES: usize = 64; +pub const MAX_CATALOGUE_BYTES: usize = 4 * 1024 * 1024; +pub const MAX_CATALOGUE_METADATA_BYTES: usize = 16 * 1024; +/// Framing is bounded separately from the aggregate payload/metadata budgets. +pub const MAX_CATALOGUE_SNAPSHOT_BYTES: usize = MAX_CATALOGUE_BYTES + MAX_CATALOGUE_METADATA_BYTES + 8192; +pub const MAX_COMMAND_BYTES: usize = 16 * 1024; + +/// Full envelope plus bounded rejected recovery intent. Arc makes catalogue +/// preparation bounded without copying each maximum-sized envelope 64 times. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredEnvelope { + bytes: Arc<[u8]>, + rejected: Option>, +} +impl StoredEnvelope { + pub fn new(envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult { + if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) { + return Err(error(Rule::CollectionLimit, "rejected recovery byte cap")); + } + Ok(Self { bytes: encode(envelope, registry)?.into(), rejected: rejected.map(Arc::from) }) + } + /// Exact retained inspection, including saved instances whose kinds are now + /// absent. This is not a live-layout admission check; stage with + /// `project_envelope` before submitting through the authoritative sink. + pub fn envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + decode_retained(&self.bytes, registry, workspace) + } + /// Explicitly stage current-registry quarantine before a guarded live use. + /// Exact inspection above deliberately keeps absent-kind saved instances. + pub fn project_envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + project_retained_record(&self.bytes, registry, workspace) + } + /// Hydration retains the original validated bytes. In particular, optional + /// order/projection metadata is not filled and recounted against the cap. + fn from_record(bytes: &[u8], rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult { + if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) { + return Err(error(Rule::CollectionLimit, "rejected recovery byte cap")); + } + decode_retained_record(bytes, registry)?; + Ok(Self { bytes: Arc::from(bytes), rejected: rejected.map(Arc::from) }) + } + pub fn rejected(&self) -> Option<&[u8]> { + self.rejected.as_deref() + } + pub fn bytes(&self) -> &[u8] { + &self.bytes + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorkspaceDescriptor { + pub id: WorkspaceId, + pub title_key: String, + pub default_preset: String, +} + +/// Fields are private: registrations and prepared updates must obey aggregate +/// bounds before cloning or publishing. There is no independently stored selection. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CatalogueState { + workspaces: BTreeMap, + builtins: BTreeMap, + users: BTreeMap, + remembered: BTreeMap, +} +impl CatalogueState { + pub fn summaries(&self) -> Vec { + self.workspaces + .values() + .map(|item| wire::WorkspaceSummary { + id: item.id.clone(), + title_key: item.title_key.clone(), + default_preset: item.default_preset.clone(), + has_remembered_layout: self.remembered.contains_key(&item.id), + }) + .collect() + } + pub fn user_count(&self) -> usize { + self.users.len() + } + pub fn user_presets(&self) -> impl Iterator { + self.users.iter().map(|(name, record)| (name.as_str(), record)) + } + pub fn remembered(&self, workspace: &WorkspaceId) -> Option<&StoredEnvelope> { + self.remembered.get(workspace) + } + pub fn preset(&self, name: &str) -> PanelResult<&StoredEnvelope> { + self.builtins.get(name).or_else(|| self.users.get(name)).ok_or_else(|| error(Rule::MissingTarget, "layout preset not registered")) + } + fn validate(&self) -> PanelResult<()> { + if self.users.keys().any(|name| self.builtins.contains_key(name)) { + return Err(error(Rule::DuplicateId, "user preset collides with immutable built-in")); + } + if self.users.len() > MAX_USER_PRESETS + || self.builtins.len() > MAX_USER_PRESETS + || self.workspaces.len() > MAX_WORKSPACES + || self.remembered.len() > MAX_WORKSPACES + { + return Err(error(Rule::CollectionLimit, "layout catalogue count cap")); + } + let mut metadata = 0_usize; + for (id, item) in &self.workspaces { + valid_id(&id.0)?; + valid_id(&item.title_key)?; + if item.id != *id || !self.builtins.contains_key(&item.default_preset) { + return Err(error(Rule::MissingTarget, "workspace requires a registered immutable default")); + } + metadata = metadata.saturating_add(id.0.len() + item.title_key.len() + item.default_preset.len()); + } + let mut bytes = 0_usize; + for (name, stored) in self.builtins.iter().chain(&self.users) { + if preset_name(name)? != *name { + return Err(error(Rule::Schema, "preset name must be normalised")); + } + metadata = metadata.saturating_add(name.len()); + bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len())); + } + for (id, stored) in &self.remembered { + valid_id(&id.0)?; + metadata = metadata.saturating_add(id.0.len()); + bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len())); + } + if metadata > MAX_CATALOGUE_METADATA_BYTES || bytes > MAX_CATALOGUE_BYTES { + return Err(error(Rule::CollectionLimit, "aggregate layout catalogue byte cap")); + } + Ok(()) + } +} + +pub struct PreparedCatalogue(CatalogueState); +impl PreparedCatalogue { + pub fn new(state: CatalogueState) -> PanelResult { + state.validate()?; + Ok(Self(state)) + } + pub fn state(&self) -> &CatalogueState { + &self.0 + } + pub fn into_state(self) -> CatalogueState { + self.0 + } +} + +/// Prepare MUST stage every fallible storage operation. Publish MUST be infallible. +/// The executor holds the exclusive catalogue borrow across guarded dispatch. +pub trait LayoutCatalogue { + fn state(&self) -> &CatalogueState; + fn prepare(&mut self, next: CatalogueState) -> PanelResult; + fn publish(&mut self, prepared: PreparedCatalogue); +} + +#[derive(Default)] +pub struct InMemoryCatalogue { + state: CatalogueState, + /// Failure-injectable storage staging; no state has been published on failure. + pub fail_stage: bool, +} +impl LayoutCatalogue for InMemoryCatalogue { + fn state(&self) -> &CatalogueState { + &self.state + } + fn prepare(&mut self, next: CatalogueState) -> PanelResult { + if self.fail_stage { + return Err(error(Rule::Capability, "layout storage staging unavailable")); + } + PreparedCatalogue::new(next) + } + fn publish(&mut self, prepared: PreparedCatalogue) { + self.state = prepared.into_state(); + } +} +impl InMemoryCatalogue { + /// Hydration builds a validated candidate, without live dispatch or changing + /// the mutability of saved user presets. Production storage remains external. + pub fn from_snapshot(bytes: &[u8], registry: &PanelRegistry) -> PanelResult { + Ok(Self { state: CatalogueState::hydrate(bytes, registry)?, fail_stage: false }) + } + /// Explicit fixture/peer registration, never populated with invented products. + pub fn register_builtin(&mut self, name: &str, envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> { + let name = preset_name(name)?; + if self.state.builtins.contains_key(&name) || self.state.users.contains_key(&name) { + return Err(error(Rule::DuplicateId, "preset already registered")); + } + let stored = StoredEnvelope::new(envelope, None, registry)?; + let mut next = self.state.clone(); + next.builtins.insert(name, stored); + let prepared = self.prepare(next)?; + self.publish(prepared); + Ok(()) + } + pub fn register_workspace(&mut self, descriptor: WorkspaceDescriptor) -> PanelResult<()> { + valid_id(&descriptor.id.0)?; + valid_id(&descriptor.title_key)?; + if self.state.workspaces.contains_key(&descriptor.id) { + return Err(error(Rule::DuplicateId, "workspace already registered")); + } + let mut next = self.state.clone(); + next.workspaces.insert(descriptor.id.clone(), descriptor); + let prepared = self.prepare(next)?; + self.publish(prepared); + Ok(()) + } + pub fn remember(&mut self, envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<()> { + let stored = StoredEnvelope::new(envelope, rejected, registry)?; + let mut next = self.state.clone(); + next.remembered.insert(envelope.layout.workspace.clone(), stored); + let prepared = self.prepare(next)?; + self.publish(prepared); + Ok(()) + } +} + +pub fn preset_name(raw: &str) -> PanelResult { + // Bound BEFORE trimming, allocating or iterating over scalars. + if raw.len() > 1024 { + return Err(error(Rule::CollectionLimit, "raw preset name byte cap")); + } + let name = raw.trim(); + if name.is_empty() || name.len() > 256 || name.chars().count() > 64 || raw.chars().any(char::is_control) { + return Err(error(Rule::Schema, "preset name requires 1..64 Unicode scalars without controls")); + } + Ok(name.into()) +} + +pub fn is_command(id: &str) -> bool { + crate::find_command(id).is_some_and(|spec| IDS.contains(&spec.id)) +} +pub const IDS: &[&str] = &[ + "layout.apply", + "layout.get", + "layout.reset", + "layout.save", + "layout.workspace.select", + "panel.activate", + "panel.close", + "panel.collapse", + "panel.dismiss", + "panel.float", + "panel.focus", + "panel.list", + "panel.move", + "panel.native_close", + "panel.open", + "panel.peek", + "panel.popout", + "panel.reset_pair", + "panel.resize", + "panel.resize_pair", +]; + +#[derive(Debug)] +pub enum PanelCommand { + List, + Get, + Open(wire::Open), + Select { operation: &'static str, params: wire::Select }, + Move { operation: &'static str, params: wire::Move }, + Resize(wire::Resize), + Collapse(wire::Collapse), + Dismiss(wire::Revision), + ResizePair(wire::ResizePair), + ResetPair(wire::ResetPair), + Save(wire::Save), + Apply(wire::Apply), + Reset(wire::Revision), + Workspace(wire::WorkspaceSelect), +} +fn read(value: &Value) -> PanelResult { + serde_json::from_value(value.clone()).map_err(|_| error(Rule::Schema, "invalid panel command fields or types")) +} +pub fn parse_command(id: &str, params: &Value) -> PanelResult { + // Keep the engine/control convention: absent/null params mean an empty form. + let empty = json!({}); + let params = if params.is_null() { &empty } else { params }; + if !params.is_object() { + return Err(error(Rule::Schema, "panel command parameters must be an object")); + } + bounded_json(params)?; + // Capped writer protects direct callers as well as transports, before clone. + struct Counter(usize); + impl std::io::Write for Counter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 = self.0.saturating_add(bytes.len()); + if self.0 > MAX_COMMAND_BYTES { + return Err(std::io::Error::other("command byte cap")); + } + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + serde_json::to_writer(Counter(0), params).map_err(|_| error(Rule::CollectionLimit, "panel command byte cap"))?; + let id = crate::find_command(id).map(|s| s.id).ok_or_else(|| error(Rule::MissingTarget, "unknown panel command"))?; + let command = match id { + "panel.list" => { + let _: wire::Empty = read(params)?; + PanelCommand::List + } + "layout.get" => { + let _: wire::Empty = read(params)?; + PanelCommand::Get + } + "panel.open" => PanelCommand::Open(read(params)?), + "panel.close" | "panel.activate" | "panel.focus" | "panel.peek" | "panel.native_close" => { + PanelCommand::Select { operation: id, params: read(params)? } + } + "panel.move" | "panel.float" | "panel.popout" => PanelCommand::Move { operation: id, params: read(params)? }, + "panel.resize" => PanelCommand::Resize(read(params)?), + "panel.collapse" => PanelCommand::Collapse(read(params)?), + "panel.dismiss" => PanelCommand::Dismiss(read(params)?), + "panel.resize_pair" => PanelCommand::ResizePair(read(params)?), + "panel.reset_pair" => PanelCommand::ResetPair(read(params)?), + "layout.save" => PanelCommand::Save(read(params)?), + "layout.apply" => PanelCommand::Apply(read(params)?), + "layout.reset" => PanelCommand::Reset(read(params)?), + "layout.workspace.select" => PanelCommand::Workspace(read(params)?), + _ => return Err(error(Rule::MissingTarget, "not an application layout command")), + }; + // Validate hostile values even when no application capability is injected. + validate_command(&command)?; + Ok(command) +} + +fn validate_selector(target: &Option, id: &Option) -> PanelResult<()> { + match (target, id) { + (Some(target), None) => match target { + wire::Target::Instance(id) => valid_id(&id.0), + wire::Target::Section(id) => valid_id(&id.0), + wire::Target::Workspace(id) => valid_id(&id.0), + wire::Target::NativeHost(id) => valid_id(&id.0), + }, + (None, Some(id)) => valid_id(id), + _ => Err(error(Rule::Schema, "supply exactly one typed target or legacy id")), + } +} +fn validate_destination(destination: Destination) -> PanelResult<()> { + match destination { + Destination::NewSection { section, index, location, size } => { + valid_id(§ion.0)?; + location.validate()?; + size.validate()?; + if index > MAX_SECTIONS { + return Err(error(Rule::Bounds, "section index cap")); + } + } + Destination::JoinTab { section, index } => { + valid_id(§ion.0)?; + if index >= MAX_TABS { + return Err(error(Rule::Bounds, "tab index cap")); + } + } + } + Ok(()) +} +fn validate_command(command: &PanelCommand) -> PanelResult<()> { + match command { + PanelCommand::Open(p) => { + valid_id(&p.kind.0)?; + valid_id(&p.instance.0)?; + if let Some(destination) = &p.destination { + validate_destination(destination.clone().into())?; + } + } + PanelCommand::Select { params, .. } => validate_selector(¶ms.target, ¶ms.id)?, + PanelCommand::Move { params, .. } => { + validate_selector(¶ms.target, ¶ms.id)?; + validate_destination(params.destination.clone().into())?; + } + PanelCommand::Resize(p) => { + validate_selector(&p.target, &p.id)?; + Size::from(p.size).validate()?; + } + PanelCommand::Collapse(p) => validate_selector(&p.target, &p.id)?, + PanelCommand::ResizePair(p) => { + valid_id(&p.first.0)?; + valid_id(&p.second.0)?; + Size::from(p.first_size).validate()?; + Size::from(p.second_size).validate()?; + } + PanelCommand::ResetPair(p) => { + valid_id(&p.first.0)?; + valid_id(&p.second.0)?; + } + PanelCommand::Save(p) => { + preset_name(&p.name)?; + } + PanelCommand::Apply(p) => { + preset_name(&p.name)?; + } + PanelCommand::Workspace(p) => valid_id(&p.workspace.0)?, + _ => {} + } + Ok(()) +} + +pub struct PanelCommandContext<'a> { + pub sink: &'a mut dyn ActionSink, + pub registry: &'a PanelRegistry, + pub catalogue: &'a mut dyn LayoutCatalogue, + /// Web popout is an explicit host policy, never inferred from no native support. + pub web: bool, +} + +fn target(target: Option, legacy: Option, layout: &Layout, registry: &PanelRegistry) -> PanelResult { + if let Some(target) = target { + return Ok(target.into()); + } + let id = legacy.ok_or_else(|| error(Rule::Schema, "target required"))?; + let instance = InstanceId::new(id.clone())?; + if layout.instance(&instance).is_ok() { + return Ok(LayoutTarget::Instance(instance)); + } + let kind = PanelKind::new(id)?; + let spec = registry.get(&kind)?; + if spec.features.multi_instance { + return Err(error(Rule::ExactlyOnce, "kind selector is ambiguous for multi-instance panels; supply typed instance")); + } + let matches: Vec<_> = layout.instances.iter().filter(|p| p.kind == kind).collect(); + if matches.len() != 1 { + return Err(error(Rule::MissingTarget, "kind requires one canonical retained instance")); + } + Ok(LayoutTarget::Instance(matches.first().ok_or_else(|| error(Rule::MissingTarget, "canonical instance absent"))?.id.clone())) +} +fn instance(target: LayoutTarget, layout: &Layout) -> PanelResult { + match target { + LayoutTarget::Instance(id) => { + layout.instance(&id)?; + Ok(id) + } + _ => Err(error(Rule::Schema, "operation requires instance target")), + } +} +fn section(target: LayoutTarget, layout: &Layout) -> PanelResult { + match target { + LayoutTarget::Section(id) => { + layout.section(&id)?; + Ok(id) + } + LayoutTarget::Instance(id) => Ok(layout.containing(&id)?.id.clone()), + _ => Err(error(Rule::Schema, "operation requires section or open instance target")), + } +} +fn revision(expected: Option, state: &LayoutReply) -> PanelResult<()> { + if expected.is_some_and(|r| r != state.revision) { + return Err(error(Rule::Revision, "stale layout revision")); + } + Ok(()) +} + +fn lower(command: PanelCommand, state: &LayoutReply, registry: &PanelRegistry, web: bool) -> PanelResult { + let layout = &state.layout; + Ok(match command { + PanelCommand::Open(p) => { + revision(p.expected_revision, state)?; + Mutation::Open { kind: p.kind, instance: p.instance, destination: p.destination.map(Into::into) } + } + PanelCommand::Select { operation, params: p } => { + revision(p.expected_revision, state)?; + let selected = target(p.target, p.id, layout, registry)?; + if operation == "panel.native_close" { + let LayoutTarget::NativeHost(host) = selected else { + return Err(error(Rule::Schema, "native close requires typed native_host target")); + }; + Mutation::NativeClose { host } + } else { + let instance = instance(selected, layout)?; + match operation { + "panel.close" => Mutation::Close { instance }, + "panel.focus" => Mutation::Focus { instance }, + "panel.activate" => Mutation::Activate { instance }, + "panel.peek" => Mutation::Peek { instance }, + _ => return Err(error(Rule::Schema, "unknown target operation")), + } + } + } + PanelCommand::Move { operation, params: p } => { + revision(p.expected_revision, state)?; + let instance = instance(target(p.target, p.id, layout, registry)?, layout)?; + let mut destination: Destination = p.destination.into(); + if operation == "panel.float" && !matches!(&destination, Destination::NewSection { location: SectionLocation::Floating { .. }, .. }) { + return Err(error(Rule::Placement, "panel.float requires new_section with floating location")); + } + if operation == "panel.popout" { + if !registry.get(&layout.instance(&instance)?.kind)?.features.popout { + return Err(error(Rule::FeatureDisabled, "panel cannot pop out")); + } + match &mut destination { + Destination::NewSection { location, .. } => match location { + SectionLocation::Window { origin, .. } => { + if web { + *location = SectionLocation::Floating { origin: *origin }; + } + } + _ => return Err(error(Rule::Placement, "panel.popout requires new_section with window location")), + }, + _ => return Err(error(Rule::Placement, "panel.popout requires a new section")), + } + } + Mutation::Move { instance, destination } + } + PanelCommand::Resize(p) => { + revision(p.expected_revision, state)?; + Mutation::SetSize { section: section(target(p.target, p.id, layout, registry)?, layout)?, size: p.size.into() } + } + PanelCommand::Collapse(p) => { + revision(p.expected_revision, state)?; + Mutation::Collapse { section: section(target(p.target, p.id, layout, registry)?, layout)?, collapsed: p.collapsed } + } + PanelCommand::Dismiss(p) => { + revision(p.expected_revision, state)?; + Mutation::DismissPeek + } + PanelCommand::ResizePair(p) => { + revision(p.expected_revision, state)?; + Mutation::ResizePair { first: p.first, second: p.second, first_size: p.first_size.into(), second_size: p.second_size.into() } + } + PanelCommand::ResetPair(p) => { + revision(p.expected_revision, state)?; + Mutation::ResetPair { first: p.first, second: p.second } + } + _ => return Err(error(Rule::Capability, "catalogue/query commands require individual transactions")), + }) +} + +fn current_envelope(catalogue: &CatalogueState, state: &LayoutReply, registry: &PanelRegistry) -> PanelResult<(LayoutEnvelope, Option>)> { + let workspace = &state.layout.workspace; + match catalogue.remembered.get(workspace) { + Some(stored) => { + Ok((with_live_layout(&stored.project_envelope(registry, workspace)?, state.layout.clone(), registry)?, stored.rejected.clone())) + } + None => Ok((LayoutEnvelope::new(state.layout.clone()), None)), + } +} + +/// Preserve all opaque sidecars. Reusing an identity with different opaque intent +/// is an error, never silently resolved by choosing one preset's value. +fn merge_envelopes(current: &LayoutEnvelope, mut next: LayoutEnvelope, registry: &PanelRegistry) -> PanelResult { + next.layout.workspace = current.layout.workspace.clone(); + for item in ¤t.quarantine { + if next.layout.instances.iter().any(|known| known.id == item.instance) { + return Err(error(Rule::DuplicateId, "preset collides with quarantined identity")); + } + match next.quarantine.iter().find(|q| q.instance == item.instance) { + Some(existing) if existing != item => return Err(error(Rule::DuplicateId, "quarantine sidecar collision")), + Some(_) => {} + None => next.quarantine.push(item.clone()), + } + } + for (id, data) in ¤t.retained_data { + if next.retained_data.get(id).is_some_and(|existing| existing != data) { + return Err(error(Rule::DuplicateId, "retained data collision")); + } + if let (Ok(old), Ok(new)) = (current.layout.instance(id), next.layout.instance(id)) + && old.kind != new.kind + { + return Err(error(Rule::DuplicateId, "retained instance kind collision")); + } + next.retained_data.insert(id.clone(), data.clone()); + } + for (id, snapshot) in ¤t.section_snapshots { + if next.section_snapshots.get(id).is_some_and(|existing| existing != snapshot) { + return Err(error(Rule::DuplicateId, "section sidecar collision")); + } + next.section_snapshots.insert(id.clone(), snapshot.clone()); + } + // Preserve dormant gaps from current; subsequent refresh overlays live order. + let dormant: std::collections::BTreeSet<_> = next.quarantine.iter().filter_map(|q| q.section.clone()).collect(); + let live: std::collections::BTreeSet<_> = next.layout.sections.iter().map(|s| s.id.clone()).collect(); + let mut order: Vec<_> = current.section_order.iter().filter(|id| dormant.contains(*id) || live.contains(*id)).cloned().collect(); + for id in &next.section_order { + if !order.contains(id) { + order.push(id.clone()); + } + } + next.section_order = order; + let layout = next.layout.clone(); + with_live_layout(&next, layout, registry) +} + +fn stage_current( + context: &mut PanelCommandContext<'_>, + state: &LayoutReply, + action: &LayoutAction, + envelope: &LayoutEnvelope, + recovery: Option>, + mut next: CatalogueState, +) -> PanelResult<(LayoutReply, CatalogueState)> { + let projected = context.sink.project(action.clone())?; + let envelope = with_live_layout(envelope, projected, context.registry)?; + let stored = StoredEnvelope::new(&envelope, recovery.as_deref(), context.registry)?; + next.remembered.insert(envelope.layout.workspace.clone(), stored); + let prepared = context.catalogue.prepare(next)?; + // Inspect can change through external adapters between planning and dispatch. + // Every action below includes the inspected revision; no stale catalogue publishes. + if context.sink.inspect().revision != state.revision { + return Err(error(Rule::Revision, "layout changed during storage staging")); + } + let committed = if *action == LayoutAction::Inspect { + let current = context.sink.inspect(); + revision(Some(state.revision), ¤t)?; + current + } else { + context.sink.dispatch(action.clone())? + }; + context.catalogue.publish(prepared); + Ok((committed, context.catalogue.state().clone())) +} + +pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<'_>) -> PanelResult { + validate_command(&command)?; + let state = context.sink.inspect(); + match command { + PanelCommand::List => return value(wire::ListReply { state, kinds: context.registry.specs().cloned().collect() }), + PanelCommand::Get => return value(wire::GetReply { state, workspaces: context.catalogue.state().summaries() }), + PanelCommand::Workspace(ref p) if p.workspace == state.layout.workspace => { + revision(p.expected_revision, &state)?; + return value(wire::WorkspaceReply { + previous_workspace: state.layout.workspace.clone(), + source: wire::WorkspaceSource::Unchanged, + state, + }); + } + _ => {} + } + let mut next = context.catalogue.state().clone(); + let (current, recovery) = current_envelope(&next, &state, context.registry)?; + match command { + PanelCommand::Save(p) => { + revision(p.expected_revision, &state)?; + let name = preset_name(&p.name)?; + if next.builtins.contains_key(&name) { + return Err(error(Rule::Capability, "built-in presets are immutable")); + } + let overwritten = next.users.contains_key(&name); + if overwritten && !p.overwrite { + return Err(error(Rule::DuplicateId, "preset exists; overwrite must be explicit")); + } + if !overwritten && next.users.len() >= MAX_USER_PRESETS { + return Err(error(Rule::CollectionLimit, "user preset count cap")); + } + next.users.insert(name.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?); + let action = LayoutAction::Inspect; + let (state, _) = stage_current(context, &state, &action, ¤t, recovery, next)?; + value(wire::SaveReply { name, overwritten, state }) + } + PanelCommand::Apply(p) => { + revision(p.expected_revision, &state)?; + let stored = next.preset(&preset_name(&p.name)?)?; + let mut envelope: LayoutEnvelope = + serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid registered envelope"))?; + // Decode using its original workspace before rebinding to the current one. + envelope = stored.project_envelope(context.registry, &envelope.layout.workspace)?; + let mut envelope = merge_envelopes(¤t, envelope, context.registry)?; + restore_quarantine(&mut envelope, context.registry)?; + let recovery = merge_recovery(recovery, stored.rejected.clone())?; + let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() }; + value(stage_current(context, &state, &action, &envelope, recovery, next)?.0) + } + PanelCommand::Reset(p) => { + revision(p.expected_revision, &state)?; + let descriptor = next + .workspaces + .get(&state.layout.workspace) + .ok_or_else(|| error(Rule::Capability, "selected workspace has no registered default"))?; + let stored = next.preset(&descriptor.default_preset)?; + let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid default envelope"))?; + let mut envelope = merge_envelopes(¤t, stored.project_envelope(context.registry, &raw.layout.workspace)?, context.registry)?; + restore_quarantine(&mut envelope, context.registry)?; + let recovery = merge_recovery(recovery, stored.rejected.clone())?; + let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() }; + value(stage_current(context, &state, &action, &envelope, recovery, next)?.0) + } + PanelCommand::Workspace(p) => { + revision(p.expected_revision, &state)?; + let previous_workspace = state.layout.workspace.clone(); + if p.workspace == previous_workspace { + return value(wire::WorkspaceReply { previous_workspace, source: wire::WorkspaceSource::Unchanged, state }); + } + let descriptor = next.workspaces.get(&p.workspace).ok_or_else(|| error(Rule::MissingTarget, "workspace not registered"))?; + let (stored, source) = match next.remembered.get(&p.workspace) { + Some(stored) => (stored, wire::WorkspaceSource::Remembered), + None => (next.preset(&descriptor.default_preset)?, wire::WorkspaceSource::DefaultPreset), + }; + let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid workspace envelope"))?; + let mut envelope = stored.project_envelope(context.registry, &raw.layout.workspace)?; + envelope.layout.workspace = p.workspace; + restore_quarantine(&mut envelope, context.registry)?; + let incoming_recovery = stored.rejected.clone(); + next.remembered.insert(previous_workspace.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?); + let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() }; + let (state, _) = stage_current(context, &state, &action, &envelope, incoming_recovery, next)?; + value(wire::WorkspaceReply { previous_workspace, source, state }) + } + command => { + let mutation = lower(command, &state, context.registry, context.web)?; + let action = LayoutAction::Apply { expected_revision: Some(state.revision), mutations: vec![mutation] }; + value(stage_current(context, &state, &action, ¤t, recovery, next)?.0) + } + } +} +fn merge_recovery(first: Option>, second: Option>) -> PanelResult>> { + if first.is_some() && second.is_some() && first != second { + return Err(error(Rule::DuplicateId, "rejected recovery intent collision")); + } + Ok(first.or(second)) +} +fn value(value: impl serde::Serialize) -> PanelResult { + serde_json::to_value(value).map_err(|_| error(Rule::Schema, "cannot encode committed layout reply")) +} +pub fn execute(id: &str, params: &Value, context: &mut PanelCommandContext<'_>) -> PanelResult { + execute_command(parse_command(id, params)?, context) +} + +/// A private transaction planner reuses the common executor and the LIVE sink's +/// pure projection. It owns no reducer or LayoutService and cannot publish live +/// effects. Only the final guarded action and prepared catalogue are published. +struct PlanningSink<'a> { + authoritative: &'a dyn ActionSink, + state: LayoutReply, + mutations: Vec, + replaced: bool, +} +impl ActionSink for PlanningSink<'_> { + fn inspect(&self) -> LayoutReply { + self.state.clone() + } + fn project(&self, action: LayoutAction) -> PanelResult { + match action { + LayoutAction::Inspect => Ok(self.state.layout.clone()), + LayoutAction::Replace { expected_revision, layout } => { + revision(expected_revision, &self.state)?; + if !self.mutations.is_empty() { + return Err(error( + Rule::Capability, + "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false", + )); + } + self.authoritative.project(LayoutAction::Replace { expected_revision: Some(self.state.revision), layout }) + } + LayoutAction::Apply { expected_revision, mutations } => { + revision(expected_revision, &self.state)?; + if self.replaced { + return Err(error( + Rule::Capability, + "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false", + )); + } + if self.mutations.len().saturating_add(mutations.len()) > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "layout batch mutation cap")); + } + let mut combined = self.mutations.clone(); + combined.extend(mutations); + self.authoritative.project(LayoutAction::Apply { expected_revision: Some(self.state.revision), mutations: combined }) + } + } + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + let layout = self.project(action.clone())?; + match action { + LayoutAction::Apply { mutations, .. } => self.mutations.extend(mutations), + LayoutAction::Replace { .. } => { + self.replaced = true; + self.state.interaction = InteractionState::default(); + } + LayoutAction::Inspect => {} + } + self.state.layout = layout; + Ok(self.state.clone()) + } +} + +/// Pure structural preflight, usable before application context publication. +/// Same-workspace selection remains a no-op and may accompany mutations. +pub fn preflight_batch(steps: &[Value], workspace: &WorkspaceId) -> PanelResult<()> { + if steps.is_empty() || steps.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps")); + } + let mut selected = workspace.clone(); + let mut replacement = false; + let mut mutation = false; + for step in steps { + let id = + step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?; + let empty = json!({}); + match parse_command(id, step.get("params").unwrap_or(&empty))? { + PanelCommand::List | PanelCommand::Get | PanelCommand::Save(_) => {} + PanelCommand::Apply(_) | PanelCommand::Reset(_) => replacement = true, + PanelCommand::Workspace(params) => { + replacement |= params.workspace != selected; + selected = params.workspace; + } + _ => mutation = true, + } + } + if replacement && mutation { + return Err(error(Rule::Capability, "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false")); + } + Ok(()) +} + +/// Atomic batches use one Apply or Replace and one catalogue/native/controller +/// preflight. Explicit lifecycle intent is never flattened into a replacement. +pub fn execute_batch(steps: &[Value], context: &mut PanelCommandContext<'_>) -> PanelResult { + if steps.is_empty() || steps.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps")); + } + let state = context.sink.inspect(); + preflight_batch(steps, &state.layout.workspace)?; + let mut planned = InMemoryCatalogue { state: context.catalogue.state().clone(), fail_stage: false }; + let mut sink = PlanningSink { authoritative: &*context.sink, state: state.clone(), mutations: Vec::new(), replaced: false }; + let mut rows = Vec::new(); + for step in steps { + let id = + step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?; + let id = crate::find_command(id).map(|spec| spec.id).ok_or_else(|| error(Rule::MissingTarget, "batch command not registered"))?; + let empty = json!({}); + let result = execute( + id, + step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty), + &mut PanelCommandContext { sink: &mut sink, registry: context.registry, catalogue: &mut planned, web: context.web }, + )?; + rows.push((id, result)); + } + let action = if sink.replaced { + LayoutAction::Replace { expected_revision: Some(state.revision), layout: sink.state.layout.clone() } + } else if !sink.mutations.is_empty() { + LayoutAction::Apply { expected_revision: Some(state.revision), mutations: sink.mutations.clone() } + } else { + LayoutAction::Inspect + }; + let planned_state = sink.state.clone(); + let changed = planned.state != *context.catalogue.state() || action != LayoutAction::Inspect; + // Release the immutable authoritative borrow before committing through it. + drop(sink); + let committed = if changed { + let (envelope, recovery) = current_envelope(&planned.state, &planned_state, context.registry)?; + stage_current(context, &state, &action, &envelope, recovery, planned.state)?.0 + } else { + context.sink.inspect() + }; + let mut results = Vec::new(); + for (id, mut result) in rows { + match id { + "panel.list" => result = value(wire::ListReply { state: committed.clone(), kinds: context.registry.specs().cloned().collect() })?, + "layout.get" => result = value(wire::GetReply { state: committed.clone(), workspaces: context.catalogue.state().summaries() })?, + "layout.save" | "layout.workspace.select" => result["state"] = value(committed.clone())?, + _ => result = value(committed.clone())?, + } + results.push(result); + } + Ok(json!({"completed":steps.len(),"results":results,"undone":0})) +} + +/// Transport-compatible error text retains the structured foundation identity. +/// Control/MCP also expose this as panel_error beside their usual error string. +pub fn error_text(reason: PanelError) -> String { + serde_json::to_string(&reason).unwrap_or_else(|_| "{\"rule\":\"schema\",\"detail\":\"layout error encoding failed\"}".into()) +} +pub fn structured_error(text: &str) -> Option { + if text.len() > 4096 { + return None; + } + serde_json::from_str::(text).ok().and_then(|reason| value(error(reason.rule, reason.detail)).ok()) +} + +pub fn sequential_failure(index: usize, command: Option<&str>, text: String, results: Vec) -> Value { + let mut failed = json!({"index":index,"command":command,"error":text}); + if let Some(reason) = structured_error(&text) { + failed["panel_error"] = reason; + } + json!({"completed":index,"results":results,"failed":failed,"undone":0,"rolled_back":false}) +} + +/// One owned, persistent in-memory headless backend, outside Session. No kinds, +/// presets or workspace descriptors are invented. Peers/fixtures may inject them. +pub struct InMemoryPanelBackend { + pub service: LayoutService, + pub catalogue: InMemoryCatalogue, +} + +/// In-process layout has no native realization. Even a supplied service with +/// native flags cannot make this adapter claim that it opened an OS window. +struct HeadlessSink<'a>(&'a mut LayoutService); +impl ActionSink for HeadlessSink<'_> { + fn inspect(&self) -> LayoutReply { + let mut state = self.0.inspect(); + state.capabilities.native_windows = false; + state.capabilities.max_native_hosts = 0; + state + } + fn project(&self, action: LayoutAction) -> PanelResult { + let prepared = self.0.prepare(action)?; + if prepared.effects().iter().any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. })) { + return Err(error(Rule::Capability, "headless has no native host adapter")); + } + Ok(prepared.layout().clone()) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + self.project(action.clone())?; + let mut state = self.0.dispatch(action)?; + state.capabilities.native_windows = false; + state.capabilities.max_native_hosts = 0; + Ok(state) + } +} +impl InMemoryPanelBackend { + pub fn new(service: LayoutService, catalogue: InMemoryCatalogue) -> Self { + Self { service, catalogue } + } + pub fn empty() -> PanelResult { + Ok(Self::new( + LayoutService::new(PanelRegistry::default(), Layout::empty(WorkspaceId::new("headless")?), HostCapabilities::default())?, + InMemoryCatalogue::default(), + )) + } + pub fn execute(&mut self, id: &str, params: &Value) -> PanelResult { + let registry = self.service.registry().clone(); + execute( + id, + params, + &mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: ®istry, catalogue: &mut self.catalogue, web: false }, + ) + } + pub fn batch(&mut self, steps: &[Value]) -> PanelResult { + let registry = self.service.registry().clone(); + execute_batch( + steps, + &mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: ®istry, catalogue: &mut self.catalogue, web: false }, + ) + } +} diff --git a/crates/engine/src/panels/commands/catalogue.rs b/crates/engine/src/panels/commands/catalogue.rs new file mode 100644 index 000000000..3c3e07dc6 --- /dev/null +++ b/crates/engine/src/panels/commands/catalogue.rs @@ -0,0 +1,158 @@ +//! Small versioned storage seam for application preferences, not design files. +//! Length-prefixed records keep arbitrary recovery bytes exact and bound every +//! allocation before copying. Envelopes retain their foundation JSON limits. +use super::*; + +const HEADER: &[u8] = b"SCPCAT01"; + +impl CatalogueState { + /// Export all immutable registrations, mutable users and remembered full + /// envelopes. No storage, live action, selection or Session is touched. + pub fn export(&self) -> PanelResult> { + self.validate()?; + let mut writer = Writer(Vec::new()); + writer.put(HEADER)?; + for presets in [&self.builtins, &self.users] { + writer.count(presets.len())?; + for (name, record) in presets { + writer.bytes(name.as_bytes())?; + writer.record(record)?; + } + } + writer.count(self.workspaces.len())?; + for descriptor in self.workspaces.values() { + writer.bytes(descriptor.id.0.as_bytes())?; + writer.bytes(descriptor.title_key.as_bytes())?; + writer.bytes(descriptor.default_preset.as_bytes())?; + } + writer.count(self.remembered.len())?; + for (workspace, record) in &self.remembered { + writer.bytes(workspace.0.as_bytes())?; + writer.record(record)?; + } + Ok(writer.0) + } + + /// Build a private validated candidate. Counts, duplicate identities, + /// names/IDs, envelope node/depth/byte bounds, rejected recovery and total + /// budgets are checked before the result can be published by any catalogue. + pub fn hydrate(bytes: &[u8], registry: &PanelRegistry) -> PanelResult { + if bytes.len() > MAX_CATALOGUE_SNAPSHOT_BYTES { + return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap")); + } + let mut reader = Reader { bytes, at: 0 }; + if reader.take(HEADER.len())? != HEADER { + return Err(error(Rule::Version, "unsupported catalogue snapshot")); + } + let mut next = Self::default(); + for builtin in [true, false] { + let count = reader.count(MAX_USER_PRESETS)?; + for _ in 0..count { + let name = reader.text(256)?; + if preset_name(&name)? != name { + return Err(error(Rule::Schema, "stored preset name is not normalised")); + } + if next.builtins.contains_key(&name) || next.users.contains_key(&name) { + return Err(error(Rule::DuplicateId, "duplicate stored preset identity")); + } + let record = reader.record(registry)?; + if builtin { + next.builtins.insert(name, record); + } else { + next.users.insert(name, record); + } + } + } + for _ in 0..reader.count(MAX_WORKSPACES)? { + let id = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?; + let title_key = reader.text(MAX_ID_BYTES)?; + valid_id(&title_key)?; + let default_preset = reader.text(256)?; + if next.workspaces.contains_key(&id) { + return Err(error(Rule::DuplicateId, "duplicate stored workspace identity")); + } + next.workspaces.insert(id.clone(), WorkspaceDescriptor { id, title_key, default_preset }); + } + for _ in 0..reader.count(MAX_WORKSPACES)? { + let workspace = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?; + if next.remembered.contains_key(&workspace) { + return Err(error(Rule::DuplicateId, "duplicate remembered workspace identity")); + } + let record = reader.record(registry)?; + // A remembered record belongs to its key, unlike a reusable preset. + record.envelope(registry, &workspace)?; + next.remembered.insert(workspace, record); + } + if reader.at != bytes.len() { + return Err(error(Rule::Schema, "trailing catalogue snapshot data")); + } + next.validate()?; + Ok(next) + } +} + +struct Writer(Vec); +impl Writer { + fn put(&mut self, bytes: &[u8]) -> PanelResult<()> { + if self.0.len().saturating_add(bytes.len()) > MAX_CATALOGUE_SNAPSHOT_BYTES { + return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap")); + } + self.0.extend_from_slice(bytes); + Ok(()) + } + fn count(&mut self, count: usize) -> PanelResult<()> { + let count = u32::try_from(count).map_err(|_| error(Rule::CollectionLimit, "catalogue framing cap"))?; + self.put(&count.to_le_bytes()) + } + fn bytes(&mut self, bytes: &[u8]) -> PanelResult<()> { + self.count(bytes.len())?; + self.put(bytes) + } + fn record(&mut self, record: &StoredEnvelope) -> PanelResult<()> { + self.bytes(record.bytes())?; + match record.rejected() { + Some(rejected) => { + self.put(&[1])?; + self.bytes(rejected) + } + None => self.put(&[0]), + } + } +} + +struct Reader<'a> { + bytes: &'a [u8], + at: usize, +} +impl<'a> Reader<'a> { + fn take(&mut self, count: usize) -> PanelResult<&'a [u8]> { + let end = self.at.checked_add(count).ok_or_else(|| error(Rule::CollectionLimit, "catalogue framing overflow"))?; + let bytes = self.bytes.get(self.at..end).ok_or_else(|| error(Rule::Schema, "truncated catalogue snapshot"))?; + self.at = end; + Ok(bytes) + } + fn count(&mut self, max: usize) -> PanelResult { + let raw = <[u8; 4]>::try_from(self.take(4)?).map_err(|_| error(Rule::Schema, "invalid catalogue length"))?; + let count = usize::try_from(u32::from_le_bytes(raw)).map_err(|_| error(Rule::CollectionLimit, "catalogue length overflow"))?; + if count > max { + return Err(error(Rule::CollectionLimit, "catalogue record/count cap")); + } + Ok(count) + } + fn bytes(&mut self, max: usize) -> PanelResult<&'a [u8]> { + let count = self.count(max)?; + self.take(count) + } + fn text(&mut self, max: usize) -> PanelResult { + std::str::from_utf8(self.bytes(max)?).map(str::to_owned).map_err(|_| error(Rule::Schema, "invalid catalogue UTF-8")) + } + fn record(&mut self, registry: &PanelRegistry) -> PanelResult { + let bytes = self.bytes(MAX_ENVELOPE_BYTES)?; + let rejected = match self.take(1)? { + [0] => None, + [1] => Some(self.bytes(MAX_ENVELOPE_BYTES)?), + _ => return Err(error(Rule::Schema, "invalid catalogue recovery tag")), + }; + StoredEnvelope::from_record(bytes, rejected, registry) + } +} diff --git a/crates/engine/src/panels/fixtures.rs b/crates/engine/src/panels/fixtures.rs new file mode 100644 index 000000000..e32888746 --- /dev/null +++ b/crates/engine/src/panels/fixtures.rs @@ -0,0 +1,110 @@ +//! Executable synthetic contracts for independent host/command/persistence work. +//! These identifiers are fixtures, never production registrations or UI strings. +use std::collections::BTreeMap; + +use super::*; + +pub const FIXTURE_LAYOUT_V1: &[u8] = include_bytes!("fixtures/layout-v1.json"); + +pub fn synthetic_registry() -> PanelResult { + let mut registry = PanelRegistry::default(); + for (kind, multi, pinned) in + [("fixture.application", false, false), ("fixture.editor", false, false), ("fixture.log", true, false), ("fixture.pin", true, true)] + { + let mut allowed_zones: std::collections::BTreeSet<_> = + [Zone::Left, Zone::Right, Zone::Bottom, Zone::Floating, Zone::Window].into_iter().collect(); + if pinned { + allowed_zones.remove(&Zone::Bottom); + } + registry.register(PanelSpec { + kind: PanelKind::new(kind)?, + title_key: "ui.panel".into(), + icon: "panel".into(), + allowed_zones, + default_zone: Zone::Left, + min_size: Size { width: 160.0, height: 120.0 }, + default_size: Size { width: 280.0, height: 240.0 }, + max_size: Size { width: 1200.0, height: 1200.0 }, + edge_rule: if pinned { EdgeRule::PinOuter } else { EdgeRule::None }, + surface: PanelSurface::FollowZone, + features: PanelFeatures { multi_instance: multi, ..PanelFeatures::default() }, + })?; + } + Ok(registry) +} + +pub fn fixture_open(kind: &str, instance: &str, section: &str, zone: Zone, index: usize) -> PanelResult { + Ok(Mutation::Open { + kind: PanelKind::new(kind)?, + instance: InstanceId::new(instance)?, + destination: Some(Destination::NewSection { + section: SectionId::new(section)?, + index, + location: if zone == Zone::Floating { + SectionLocation::Floating { origin: Point { x: 40.0, y: 40.0 } } + } else { + SectionLocation::Dock { zone } + }, + size: Size { width: 280.0, height: 240.0 }, + }), + }) +} + +pub fn fixture_service(native: bool) -> PanelResult { + LayoutService::new( + synthetic_registry()?, + Layout::empty(WorkspaceId::new("fixture.workspace")?), + HostCapabilities { native_windows: native, max_native_hosts: if native { 8 } else { 0 }, persistence: true }, + ) +} + +pub fn transaction(mutations: Vec) -> LayoutAction { + LayoutAction::Apply { expected_revision: None, mutations } +} + +/// Synthetic catalogue shared by command/control/MCP tests; never registered by +/// application startup. Two descriptors may deliberately share one default. +pub fn fixture_command_catalogue(registry: &PanelRegistry) -> PanelResult { + let mut catalogue = commands::InMemoryCatalogue::default(); + let empty = LayoutEnvelope::new(Layout::empty(WorkspaceId::new("fixture.workspace")?)); + catalogue.register_builtin("Fixture default", &empty, registry)?; + for id in ["fixture.workspace", "fixture.other"] { + catalogue.register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new(id)?, + title_key: "ui.panel".into(), + default_preset: "Fixture default".into(), + })?; + } + Ok(catalogue) +} + +pub fn fixture_command_backend() -> PanelResult { + let service = fixture_service(false)?; + let catalogue = fixture_command_catalogue(service.registry())?; + Ok(commands::InMemoryPanelBackend::new(service, catalogue)) +} + +#[derive(Default)] +pub struct FakePersistence { + /// Deliberately separate map demonstrates that layout writes own one key. + pub unrelated_preferences: BTreeMap, + pub layouts: BTreeMap>, + pub fail_save: bool, +} +impl LayoutPersistence for FakePersistence { + fn load(&mut self, workspace: &WorkspaceId) -> PanelResult>> { + valid_id(&workspace.0)?; + Ok(self.layouts.get(workspace).cloned()) + } + fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()> { + valid_id(&workspace.0)?; + if envelope.len() > MAX_ENVELOPE_BYTES || (!self.layouts.contains_key(workspace) && self.layouts.len() >= MAX_SECTIONS) { + return Err(error(Rule::CollectionLimit, "fake persistence capacity")); + } + if self.fail_save { + return Err(error(Rule::Capability, "synthetic atomic write failure")); + } + self.layouts.insert(workspace.clone(), envelope.to_vec()); + Ok(()) + } +} diff --git a/crates/engine/src/panels/fixtures/layout-v1.json b/crates/engine/src/panels/fixtures/layout-v1.json new file mode 100644 index 000000000..794c19ed2 --- /dev/null +++ b/crates/engine/src/panels/fixtures/layout-v1.json @@ -0,0 +1,37 @@ +{ + "format": "solidcraft.panel-layout", + "version": 1, + "layout": { + "version": 1, + "workspace": "fixture.workspace", + "instances": [ + { + "id": "editor", + "kind": "fixture.editor", + "requested_open": true, + "memory": { + "section": "editor-section", + "location": { "type": "dock", "zone": "left" }, + "section_index": 0, + "tab_index": 0, + "size": { "width": 280.0, "height": 240.0 }, + "collapsed": false + } + } + ], + "sections": [ + { + "id": "editor-section", + "location": { "type": "dock", "zone": "left" }, + "tabs": ["editor"], + "active": "editor", + "size": { "width": 280.0, "height": 240.0 }, + "collapsed": false + } + ] + }, + "quarantine": [], + "section_snapshots": {}, + "section_order": ["editor-section"], + "retained_data": {} +} diff --git a/crates/engine/src/panels/geometry.rs b/crates/engine/src/panels/geometry.rs new file mode 100644 index 000000000..475855a68 --- /dev/null +++ b/crates/engine/src/panels/geometry.rs @@ -0,0 +1,410 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::*; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Point { + pub x: f32, + pub y: f32, +} +impl Point { + pub fn validate(self) -> PanelResult<()> { + if !self.x.is_finite() || !self.y.is_finite() || self.x.abs() > MAX_LOGICAL || self.y.abs() > MAX_LOGICAL { + return Err(error(Rule::Bounds, "invalid logical position")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct LogicalRect { + pub origin: Point, + pub size: Size, +} +impl LogicalRect { + pub fn validate(self) -> PanelResult<()> { + self.origin.validate()?; + self.size.validate()?; + if (self.origin.x + self.size.width).abs() > MAX_LOGICAL || (self.origin.y + self.size.height).abs() > MAX_LOGICAL { + return Err(error(Rule::Bounds, "logical rectangle extent out of range")); + } + Ok(()) + } + pub fn contains(self, p: Point) -> bool { + p.x >= self.origin.x && p.y >= self.origin.y && p.x <= self.origin.x + self.size.width && p.y <= self.origin.y + self.size.height + } + pub fn contains_rect(self, other: Self) -> bool { + self.contains(other.origin) && self.contains(Point { x: other.origin.x + other.size.width, y: other.origin.y + other.size.height }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Flow { + Tall, + Wide, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum SizeClass { + Compact, + Regular, + Wide, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Direction { + Ltr, + Rtl, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PhysicalEdge { + Left, + Right, + Bottom, +} + +impl Direction { + pub fn edge(self, zone: Zone) -> PanelResult { + match (self, zone) { + (Self::Ltr, Zone::Left) | (Self::Rtl, Zone::Right) => Ok(PhysicalEdge::Left), + (Self::Ltr, Zone::Right) | (Self::Rtl, Zone::Left) => Ok(PhysicalEdge::Right), + (_, Zone::Bottom) => Ok(PhysicalEdge::Bottom), + _ => Err(error(Rule::Placement, "free host has no logical dock edge")), + } + } +} + +/// Usable logical units: egui applies scale exactly once, outside this contract. +/// Free/native flow starts at aspect 1, switches Tall->Wide above 1.1, Wide->Tall +/// below 0.9, and retains the previous flow inside that band. +pub fn responsive(zone: Zone, usable: Size, previous: Option) -> PanelResult<(Flow, SizeClass)> { + usable.validate()?; + let aspect = usable.width / usable.height; + let flow = match zone { + Zone::Left | Zone::Right => Flow::Tall, + Zone::Bottom => Flow::Wide, + Zone::Floating | Zone::Window => match previous { + Some(Flow::Tall) if aspect <= 1.1 => Flow::Tall, + Some(Flow::Wide) if aspect >= 0.9 => Flow::Wide, + _ if aspect >= 1.0 => Flow::Wide, + _ => Flow::Tall, + }, + }; + let shorter = usable.width.min(usable.height); + let class = if shorter < 240.0 { + SizeClass::Compact + } else if shorter <= 480.0 { + SizeClass::Regular + } else { + SizeClass::Wide + }; + Ok((flow, class)) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum InputRole { + Surface, + Header, + Tab, + Sash, + Action, + Rail, + Overlay, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct InputRegion { + pub control: ControlId, + pub role: InputRole, + pub bounds: LogicalRect, + pub keyboard_focusable: bool, + /// Translation key or a runtime title resolved by the host. + pub accessible_name: String, +} +impl InputRegion { + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.control.0)?; + self.bounds.validate()?; + if self.accessible_name.is_empty() || self.accessible_name.len() > 256 { + return Err(error(Rule::Bounds, "accessible name requires 1..256 bytes")); + } + Ok(()) + } +} + +/// Host-resolved geometry has separate outer, body, paint and input bounds. No +/// transparent/full-window input shield is implied by an overlay surface. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ResolvedPanel { + pub instance: InstanceId, + pub section: SectionId, + pub zone: Zone, + pub outer: LogicalRect, + pub body: LogicalRect, + pub painted: Vec, + pub input: Vec, +} +impl ResolvedPanel { + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.instance.0)?; + valid_id(&self.section.0)?; + self.outer.validate()?; + self.body.validate()?; + if !self.outer.contains_rect(self.body) { + return Err(error(Rule::Bounds, "usable body outside outer host")); + } + if self.painted.is_empty() || self.painted.len() > MAX_TABS || self.input.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "resolved region count")); + } + for rect in &self.painted { + rect.validate()?; + if !self.outer.contains_rect(*rect) { + return Err(error(Rule::Bounds, "paint outside host")); + } + } + let mut ids = std::collections::BTreeSet::new(); + for region in &self.input { + region.validate()?; + if !ids.insert(®ion.control) { + return Err(error(Rule::DuplicateId, "semantic control id repeated")); + } + if !self.painted.iter().any(|r| r.contains_rect(region.bounds)) { + return Err(error(Rule::Bounds, "input must be contained in painted area")); + } + } + Ok(()) + } + pub fn consumes_pointer(&self, at: Point) -> bool { + self.input.iter().any(|r| r.bounds.contains(at)) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum UnpresentedReason { + MinimumOverflow, + Unavailable, + NativeUnsupported, + Collapsed, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct UnpresentedSection { + pub section: SectionId, + pub reason: UnpresentedReason, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ResolvedLayout { + pub panels: Vec, + /// Accessible rail controls are chrome, never sub-minimum content bodies. + pub rails: Vec, + pub unpresented: Vec, +} +impl ResolvedLayout { + pub fn validate(&self) -> PanelResult<()> { + if self.panels.len() > MAX_SECTIONS || self.rails.len() > MAX_SECTIONS || self.unpresented.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "resolved layout cap")); + } + let mut instances = std::collections::BTreeSet::new(); + let mut sections = std::collections::BTreeSet::new(); + let mut rails = std::collections::BTreeSet::new(); + for panel in &self.panels { + panel.validate()?; + if !instances.insert(&panel.instance) || !sections.insert(&panel.section) { + return Err(error(Rule::ExactlyOnce, "duplicate resolved instance/section")); + } + } + for rail in &self.rails { + rail.validate()?; + if rail.role != InputRole::Rail || !rails.insert(&rail.control) { + return Err(error(Rule::DuplicateId, "invalid or duplicate rail control")); + } + } + for record in &self.unpresented { + valid_id(&record.section.0)?; + if !sections.insert(&record.section) { + return Err(error(Rule::ExactlyOnce, "section both presented/unpresented or duplicated")); + } + } + Ok(()) + } +} + +/// Reference geometry for synthetic mounts. Production docking owns its richer +/// resolver; both return the same meaningful geometry contract. No layout writes. +pub fn resolve_geometry(service: &LayoutService, capacity: LogicalRect, direction: Direction, chrome: f32) -> PanelResult { + capacity.validate()?; + if !chrome.is_finite() || chrome < 0.0 || chrome > 256.0 { + return Err(error(Rule::Bounds, "invalid header/footer chrome extent")); + } + let mut result = ResolvedLayout::default(); + let mut left = capacity.origin.x; + let mut right = capacity.origin.x + capacity.size.width; + let mut bottom = capacity.origin.y + capacity.size.height; + let mut left_y = capacity.origin.y; + let mut right_y = capacity.origin.y; + let mut bottom_x = capacity.origin.x; + let mut rail_y = capacity.origin.y; + let mut occupied: Vec = Vec::new(); + for section in &service.layout().sections { + let id = §ion.active; + let zone = section.location.zone(); + let peek = &service.interaction().peek; + let active = peek.as_ref().filter(|p| section.tabs.contains(p)).unwrap_or(id); + let available = service.availability(active) == Availability::Available; + let reason = if !available { + Some(UnpresentedReason::Unavailable) + } else if zone == Zone::Window && !service.capabilities().native_windows { + Some(UnpresentedReason::NativeUnsupported) + } else if section.collapsed && peek.as_ref() != Some(active) { + Some(UnpresentedReason::Collapsed) + } else { + None + }; + if let Some(reason) = reason { + result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: reason.clone() }); + if reason == UnpresentedReason::Collapsed { + append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?; + } + continue; + } + let size = section.size; + let origin = match §ion.location { + SectionLocation::Floating { origin } | SectionLocation::Window { origin, .. } => *origin, + SectionLocation::Dock { zone } => match direction.edge(*zone)? { + PhysicalEdge::Left => Point { x: left, y: left_y }, + PhysicalEdge::Right => Point { x: right - size.width, y: right_y }, + PhysicalEdge::Bottom => Point { x: bottom_x, y: bottom - size.height }, + }, + }; + let outer = LogicalRect { origin, size }; + let overlaps_dock = zone.docked() + && !section.collapsed + && occupied.iter().any(|r| { + r.origin.x < origin.x + size.width + && origin.x < r.origin.x + r.size.width + && r.origin.y < origin.y + size.height + && origin.y < r.origin.y + r.size.height + }); + if !capacity.contains_rect(outer) || size.height <= chrome || overlaps_dock { + result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: UnpresentedReason::MinimumOverflow }); + append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?; + continue; + } + if zone.docked() && !section.collapsed { + occupied.push(outer); + match direction.edge(zone)? { + PhysicalEdge::Left => { + left_y += size.height; + left = left.max(origin.x); + } + PhysicalEdge::Right => { + right_y += size.height; + right = right.min(origin.x + size.width); + } + PhysicalEdge::Bottom => { + bottom_x += size.width; + bottom = bottom.min(origin.y + size.height); + } + } + } + let body = + LogicalRect { origin: Point { x: origin.x, y: origin.y + chrome / 2.0 }, size: Size { width: size.width, height: size.height - chrome } }; + let panel = ResolvedPanel { + instance: active.clone(), + section: section.id.clone(), + zone, + outer, + body, + painted: vec![outer], + input: vec![InputRegion { + control: ControlId::new(format!("host.{}", section.id.0).chars().take(MAX_ID_BYTES).collect::())?, + role: InputRole::Surface, + bounds: outer, + keyboard_focusable: true, + accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(), + }], + }; + panel.validate()?; + result.panels.push(panel); + } + result.validate()?; + Ok(result) +} + +fn append_rail( + result: &mut ResolvedLayout, + service: &LayoutService, + active: &InstanceId, + capacity: LogicalRect, + direction: Direction, + zone: Zone, + rail_y: &mut f32, +) -> PanelResult<()> { + // Rails are bounded chrome, not below-minimum content bodies. If every entry + // cannot fit, the complete unpresented list remains available to a host's rail. + let width = 32.0_f32.min(capacity.size.width); + let height = 32.0_f32.min(capacity.size.height); + if *rail_y + height <= capacity.origin.y + capacity.size.height { + let right = direction.edge(if zone.docked() { zone } else { Zone::Left })? == PhysicalEdge::Right; + let x = if right { capacity.origin.x + capacity.size.width - width } else { capacity.origin.x }; + result.rails.push(InputRegion { + control: ControlId::new(format!("rail.{}", result.rails.len()))?, + role: InputRole::Rail, + bounds: LogicalRect { origin: Point { x, y: *rail_y }, size: Size { width, height } }, + keyboard_focusable: true, + accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(), + }); + *rail_y += height; + } + Ok(()) +} + +/// Surfaces child resolves theme tokens. Invalid authored pairs retain raw import +/// intent and last good tokens; they cannot be reported as accessible by recolouring. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum ContrastOutcome { + Readable { effective_background_alpha: f32 }, + RetainReadableFallback { reason: ContrastFailure }, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ContrastFailure { + InvalidTokens, + UnreadableAtFullOpacity, +} + +impl ContrastOutcome { + /// The surfaces adapter proves readability. This boundary enforces finite + /// alpha and the policy that effective background alpha may only increase. + pub fn validate(&self, requested_alpha: f32) -> PanelResult<()> { + if !requested_alpha.is_finite() || !(0.0..=1.0).contains(&requested_alpha) { + return Err(error(Rule::Bounds, "invalid requested background alpha")); + } + if let Self::Readable { effective_background_alpha } = self + && (!effective_background_alpha.is_finite() || *effective_background_alpha < requested_alpha || *effective_background_alpha > 1.0) + { + return Err(error(Rule::Bounds, "resolved background alpha must be finite and only raised")); + } + Ok(()) + } +} + +/// Shared surface precedence: Opaque wins, then explicit Translucent, then zone +/// default (bottom/native opaque, sides/free translucent). No colour implementation. +pub fn group_surface<'a>(zone: Zone, specs: impl IntoIterator) -> PanelSurface { + let mut translucent = false; + for spec in specs { + if spec.surface == PanelSurface::Opaque { + return PanelSurface::Opaque; + } + translucent |= spec.surface == PanelSurface::Translucent; + } + if translucent || !matches!(zone, Zone::Bottom | Zone::Window) { PanelSurface::Translucent } else { PanelSurface::Opaque } +} diff --git a/crates/engine/src/panels/mod.rs b/crates/engine/src/panels/mod.rs new file mode 100644 index 000000000..868041315 --- /dev/null +++ b/crates/engine/src/panels/mod.rs @@ -0,0 +1,18 @@ +//! Application/workspace layout, deliberately independent of Session and egui. +//! Consumers must use `LayoutService` (or its `ActionSink`) for committed mutations. +//! The serde values are wire data, not proof of validity; see `validate` and `decode`. +pub mod commands; +mod fixtures; +mod geometry; +mod model; +mod persistence; +mod reducer; + +pub use fixtures::*; +pub use geometry::*; +pub use model::*; +pub use persistence::*; +pub use reducer::*; + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/panels/model.rs b/crates/engine/src/panels/model.rs new file mode 100644 index 000000000..c9525b503 --- /dev/null +++ b/crates/engine/src/panels/model.rs @@ -0,0 +1,480 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use super::geometry::Point; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +pub const LAYOUT_VERSION: u32 = 1; +pub const PANEL_API_VERSION: u32 = 1; +pub const MAX_ID_BYTES: usize = 64; +pub const MAX_INSTANCES: usize = 128; +pub const MAX_SECTIONS: usize = 64; +pub const MAX_TABS: usize = 32; +pub const MAX_MUTATIONS: usize = 64; +pub const MAX_LOGICAL: f32 = 32_768.0; +pub const MAX_ENVELOPE_BYTES: usize = 262_144; + +/// Classic is a permanent compatibility contract; this foundation does not +/// select a new preset or migrate existing preferences. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum CompatibilityPreset { + Classic, +} + +/// Stable machine-readable rule names; presentation translates these in the adapter. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Rule { + Availability, + Bounds, + Capability, + CollectionLimit, + DuplicateId, + ExactlyOnce, + FeatureDisabled, + Id, + IncompatibleTabs, + Lifecycle, + MissingTarget, + PinConflict, + PinOrder, + Placement, + Revision, + Schema, + Version, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)] +#[error("{rule:?}: {detail}")] +pub struct PanelError { + pub rule: Rule, + pub detail: String, +} + +pub type PanelResult = std::result::Result; + +pub fn error(rule: Rule, detail: impl Into) -> PanelError { + // Error replies are bounded too; never echo a hostile payload in full. + PanelError { rule, detail: detail.into().chars().take(256).collect() } +} + +pub fn valid_id(value: &str) -> PanelResult<()> { + if value.is_empty() || value.len() > MAX_ID_BYTES || !value.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)) { + return Err(error(Rule::Id, "expected a nonempty bounded lowercase identifier")); + } + Ok(()) +} + +macro_rules! identity { + ($($name:ident),+ $(,)?) => {$ ( + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)] + #[serde(transparent)] + pub struct $name(pub String); + impl $name { + pub fn new(value: impl Into) -> PanelResult { + let value = value.into(); + valid_id(&value)?; + Ok(Self(value)) + } + } + )+}; +} +identity!(PanelKind, InstanceId, SectionId, WorkspaceId, DocumentId, ViewportId, HostId, ControlId); + +/// Leading/trailing logical sides, mirrored by a host for RTL. There is no Top zone. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Zone { + Left, + Right, + Bottom, + Floating, + Window, +} + +impl Zone { + pub fn docked(self) -> bool { + matches!(self, Self::Left | Self::Right | Self::Bottom) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum EdgeRule { + None, + PinOuter, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PanelSurface { + FollowZone, + Opaque, + Translucent, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Size { + pub width: f32, + pub height: f32, +} + +impl Size { + pub fn validate(self) -> PanelResult<()> { + if !self.width.is_finite() + || !self.height.is_finite() + || self.width <= 0.0 + || self.height <= 0.0 + || self.width > MAX_LOGICAL + || self.height > MAX_LOGICAL + { + return Err(error(Rule::Bounds, "outer size must be finite and in (0, 32768] logical units")); + } + Ok(()) + } + pub fn within(self, min: Self, max: Self) -> bool { + self.width >= min.width && self.height >= min.height && self.width <= max.width && self.height <= max.height + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct PanelFeatures { + pub collapsible: bool, + pub closable: bool, + pub popout: bool, + pub tabbable: bool, + pub multi_instance: bool, +} + +impl Default for PanelFeatures { + fn default() -> Self { + Self { collapsible: true, closable: true, popout: true, tabbable: true, multi_instance: false } + } +} + +/// Immutable registration metadata. No callbacks, content state or model references. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct PanelSpec { + pub kind: PanelKind, + pub title_key: String, + pub icon: String, + pub allowed_zones: BTreeSet, + pub default_zone: Zone, + pub min_size: Size, + pub default_size: Size, + pub max_size: Size, + pub edge_rule: EdgeRule, + pub surface: PanelSurface, + pub features: PanelFeatures, +} + +#[derive(Clone, Debug, Default)] +pub struct PanelRegistry { + specs: BTreeMap, +} + +impl PanelRegistry { + pub fn register(&mut self, spec: PanelSpec) -> PanelResult<()> { + valid_id(&spec.kind.0)?; + valid_id(&spec.title_key)?; + valid_id(&spec.icon)?; + spec.min_size.validate()?; + spec.max_size.validate()?; + spec.default_size.validate()?; + if !spec.default_size.within(spec.min_size, spec.max_size) { + return Err(error(Rule::Bounds, "min <= default <= max required in both dimensions")); + } + if !spec.allowed_zones.contains(&Zone::Floating) || !spec.allowed_zones.contains(&spec.default_zone) { + return Err(error(Rule::Placement, "Floating and default_zone must be allowed")); + } + if spec.edge_rule == EdgeRule::PinOuter && spec.allowed_zones.contains(&Zone::Bottom) { + return Err(error(Rule::Placement, "PinOuter must exclude Bottom")); + } + if self.specs.contains_key(&spec.kind) { + return Err(error(Rule::DuplicateId, "panel kind already registered")); + } + if self.specs.len() >= MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "registry full")); + } + self.specs.insert(spec.kind.clone(), spec); + Ok(()) + } + pub fn get(&self, kind: &PanelKind) -> PanelResult<&PanelSpec> { + self.specs.get(kind).ok_or_else(|| error(Rule::MissingTarget, "unregistered panel kind")) + } + pub fn specs(&self) -> impl Iterator { + self.specs.values() + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum SectionLocation { + Dock { zone: Zone }, + Floating { origin: Point }, + Window { host: HostId, origin: Point, return_to: DockReturn }, +} + +impl SectionLocation { + pub fn zone(&self) -> Zone { + match self { + Self::Dock { zone } => *zone, + Self::Floating { .. } => Zone::Floating, + Self::Window { .. } => Zone::Window, + } + } + pub fn validate(&self) -> PanelResult<()> { + match self { + Self::Dock { zone } if !zone.docked() => Err(error(Rule::Placement, "dock must name a docked zone")), + Self::Dock { .. } => Ok(()), + Self::Floating { origin } => origin.validate(), + Self::Window { host, origin, return_to } => { + valid_id(&host.0)?; + origin.validate()?; + return_to.validate() + } + } + } +} + +/// Native return destinations never recursively contain another native host. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct DockReturn { + pub zone: Zone, + pub index: usize, + pub size: Size, + pub collapsed: bool, + /// Restore a former tab group when it still occupies the recorded dock. + /// Missing/reparented groups use the nonrecursive dock fallback above. + #[serde(default)] + pub join: Option, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ReturnTab { + pub section: SectionId, + pub index: usize, +} +impl DockReturn { + pub fn validate(&self) -> PanelResult<()> { + if !self.zone.docked() || self.index > MAX_SECTIONS { + return Err(error(Rule::Placement, "invalid native return destination")); + } + self.size.validate()?; + if let Some(join) = &self.join { + valid_id(&join.section.0)?; + if join.index >= MAX_TABS { + return Err(error(Rule::Bounds, "native return tab index cap")); + } + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Section { + pub id: SectionId, + pub location: SectionLocation, + pub tabs: Vec, + pub active: InstanceId, + /// Desired outer dimensions; overflow resolution never modifies these. + pub size: Size, + pub collapsed: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct PlacementMemory { + pub section: SectionId, + pub location: SectionLocation, + pub section_index: usize, + pub tab_index: usize, + pub size: Size, + pub collapsed: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct PanelInstance { + pub id: InstanceId, + pub kind: PanelKind, + pub requested_open: bool, + pub memory: PlacementMemory, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Layout { + pub version: u32, + pub workspace: WorkspaceId, + pub instances: Vec, + /// Stable order, outermost first within each logical dock edge. + pub sections: Vec
, +} + +impl Layout { + pub fn empty(workspace: WorkspaceId) -> Self { + Self { version: LAYOUT_VERSION, workspace, instances: Vec::new(), sections: Vec::new() } + } + pub fn instance(&self, id: &InstanceId) -> PanelResult<&PanelInstance> { + self.instances.iter().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found")) + } + pub fn section(&self, id: &SectionId) -> PanelResult<&Section> { + self.sections.iter().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found")) + } + pub fn containing(&self, id: &InstanceId) -> PanelResult<&Section> { + self.sections.iter().find(|s| s.tabs.contains(id)).ok_or_else(|| error(Rule::MissingTarget, "instance has no open section")) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum Availability { + Available, + Unavailable { reason: String }, +} + +impl Availability { + pub fn require(&self) -> PanelResult<()> { + match self { + Self::Available => Ok(()), + Self::Unavailable { reason } => Err(error(Rule::Availability, reason)), + } + } +} + +/// Missing entries mean available. Availability is live context, never layout persistence. +pub type AvailabilityMap = BTreeMap; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct HostCapabilities { + pub native_windows: bool, + pub persistence: bool, + pub max_native_hosts: usize, +} + +pub fn tab_bounds(layout: &Layout, registry: &PanelRegistry, section: &Section) -> PanelResult<(Size, Size)> { + let mut min = Size { width: 0.0, height: 0.0 }; + let mut max = Size { width: MAX_LOGICAL, height: MAX_LOGICAL }; + for id in §ion.tabs { + let spec = registry.get(&layout.instance(id)?.kind)?; + min.width = min.width.max(spec.min_size.width); + min.height = min.height.max(spec.min_size.height); + max.width = max.width.min(spec.max_size.width); + max.height = max.height.min(spec.max_size.height); + } + if min.width > max.width || min.height > max.height { + return Err(error(Rule::IncompatibleTabs, "tab size constraints have no intersection")); + } + Ok((min, max)) +} + +/// Bounded semantic validation, also required after serde and every transaction. +pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> { + if layout.version != LAYOUT_VERSION { + return Err(error(Rule::Version, "unsupported layout version")); + } + valid_id(&layout.workspace.0)?; + if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "layout collection limit")); + } + let mut instances = BTreeSet::new(); + let mut kinds = BTreeSet::new(); + for p in &layout.instances { + valid_id(&p.id.0)?; + valid_id(&p.kind.0)?; + valid_id(&p.memory.section.0)?; + if !instances.insert(&p.id) { + return Err(error(Rule::DuplicateId, "duplicate instance")); + } + let spec = registry.get(&p.kind)?; + if !spec.features.multi_instance && !kinds.insert(&p.kind) { + return Err(error(Rule::ExactlyOnce, "single-instance kind repeated, including closed instances")); + } + p.memory.location.validate()?; + p.memory.size.validate()?; + if p.memory.tab_index >= MAX_TABS || p.memory.section_index > MAX_SECTIONS { + return Err(error(Rule::Bounds, "invalid placement memory")); + } + if !spec.allowed_zones.contains(&p.memory.location.zone()) { + return Err(error(Rule::Placement, "remembered zone forbidden")); + } + } + let mut sections = BTreeSet::new(); + let mut seen = BTreeSet::new(); + let mut hosts = BTreeSet::new(); + let mut pins = BTreeSet::new(); + let mut edges = BTreeSet::new(); + for s in &layout.sections { + valid_id(&s.id.0)?; + s.location.validate()?; + s.size.validate()?; + if !sections.insert(&s.id) { + return Err(error(Rule::DuplicateId, "duplicate section")); + } + if s.tabs.is_empty() || s.tabs.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "section requires 1..32 tabs")); + } + if !s.tabs.contains(&s.active) { + return Err(error(Rule::MissingTarget, "active tab outside section")); + } + if let SectionLocation::Window { host, .. } = &s.location + && !hosts.insert(host) + { + return Err(error(Rule::DuplicateId, "native host reused")); + } + let zone = s.location.zone(); + let first = edges.insert(zone); + for id in &s.tabs { + let instance = layout.instance(id)?; + let spec = registry.get(&instance.kind)?; + if !instance.requested_open || !seen.insert(id) { + return Err(error(Rule::ExactlyOnce, "closed or duplicate presented instance")); + } + if !spec.allowed_zones.contains(&zone) { + return Err(error(Rule::Placement, "panel zone forbidden")); + } + if s.tabs.len() > 1 && !spec.features.tabbable { + return Err(error(Rule::FeatureDisabled, "panel cannot join tabs")); + } + if s.collapsed && !spec.features.collapsible { + return Err(error(Rule::FeatureDisabled, "panel cannot collapse")); + } + if zone == Zone::Window && !spec.features.popout { + return Err(error(Rule::FeatureDisabled, "panel cannot pop out")); + } + if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) { + if !pins.insert(zone) { + return Err(error(Rule::PinConflict, "competing pins on logical edge, including same tab group")); + } + if !first { + return Err(error(Rule::PinOrder, "pinned section must be outermost")); + } + } + } + let (min, max) = tab_bounds(layout, registry, s)?; + if !s.size.within(min, max) { + return Err(error(Rule::Bounds, "section outside intersected tab bounds")); + } + if let SectionLocation::Window { return_to, .. } = &s.location { + for id in &s.tabs { + let spec = registry.get(&layout.instance(id)?.kind)?; + if !spec.allowed_zones.contains(&return_to.zone) + || !return_to.size.within(spec.min_size, spec.max_size) + || (return_to.collapsed && !spec.features.collapsible) + { + return Err(error(Rule::Placement, "native return violates member constraints")); + } + } + } + } + for p in &layout.instances { + // Diagnose impossible tab groups before their shared size can make an + // individual member's remembered size appear invalid. + let spec = registry.get(&p.kind)?; + if !p.memory.size.within(spec.min_size, spec.max_size) { + return Err(error(Rule::Bounds, "invalid placement memory")); + } + if p.requested_open != seen.contains(&p.id) { + return Err(error(Rule::ExactlyOnce, "open instance must appear exactly once")); + } + } + Ok(()) +} diff --git a/crates/engine/src/panels/persistence.rs b/crates/engine/src/panels/persistence.rs new file mode 100644 index 000000000..43446e9bc --- /dev/null +++ b/crates/engine/src/panels/persistence.rs @@ -0,0 +1,762 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::*; + +pub const ENVELOPE_FORMAT: &str = "solidcraft.panel-layout"; +pub const ENVELOPE_VERSION: u32 = 1; + +/// Unknown panel wire values are retained verbatim as JSON values, including +/// fields a future content adapter understands. Total encoded envelope is capped. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct QuarantinedPanel { + pub instance: InstanceId, + pub kind: PanelKind, + pub instance_data: serde_json::Value, + pub section: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct SectionSnapshot { + pub data: serde_json::Value, + /// Latest complete rank; also permits reading earlier v1 envelopes without + /// the envelope's explicit complete section_order list. + pub index: usize, + /// Last materialized section, so a live user edit can be distinguished from + /// the fallback active tab/order produced while some members are dormant. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub projected: Option
, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct LayoutEnvelope { + pub format: String, + pub version: u32, + pub layout: Layout, + pub quarantine: Vec, + /// Shared, lossless section order/activation/future fields, stored once even + /// when many unknown tabs refer to the same section. Retained after restore. + #[serde(default)] + pub section_snapshots: std::collections::BTreeMap, + /// Latest complete section ordering, including currently dormant sections. + /// Retained snapshots alone cannot rank surviving sections without this list. + #[serde(default)] + pub section_order: Vec, + /// Original unknown wire data remains available after registry reappearance. + /// A content/persistence adapter may explicitly consume it; restoring placement + /// alone must not erase a future field that this foundation cannot interpret. + #[serde(default)] + pub retained_data: std::collections::BTreeMap, +} +impl LayoutEnvelope { + pub fn new(layout: Layout) -> Self { + let section_order = layout.sections.iter().map(|section| section.id.clone()).collect(); + Self { + format: ENVELOPE_FORMAT.into(), + version: ENVELOPE_VERSION, + layout, + quarantine: Vec::new(), + section_snapshots: std::collections::BTreeMap::new(), + section_order, + retained_data: std::collections::BTreeMap::new(), + } + } +} + +#[derive(Clone, Debug)] +pub struct LoadOutcome { + pub envelope: LayoutEnvelope, + /// Adapter reports this once; fallback never blocks startup or touches other preferences. + pub notice: Option, + /// Bounded corrupt/future input, available to a recovery adapter before replacement. + pub rejected: Option>, +} + +/// Implementations read/write ONLY the workspace panel-layout preference key. +/// `save` must replace atomically, preserving unrelated preferences. Production +/// preference migration is intentionally outside the foundation. +pub trait LayoutPersistence { + fn load(&mut self, workspace: &WorkspaceId) -> PanelResult>>; + fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()>; +} + +pub fn encode(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult> { + validate_envelope(envelope, registry)?; + encode_record(envelope) +} + +fn encode_record(envelope: &LayoutEnvelope) -> PanelResult> { + let mut writer = BoundedEnvelopeWriter { bytes: Vec::new() }; + serde_json::to_writer(&mut writer, envelope).map_err(|_| error(Rule::CollectionLimit, "cannot encode panel envelope within byte cap"))?; + // Aggregated opaque entries must also fit the decoder's global node/depth + // budget. Never persist bytes that this same version would reject on reopen. + let value: serde_json::Value = serde_json::from_slice(&writer.bytes).map_err(|_| error(Rule::Schema, "invalid encoded panel envelope"))?; + bounded_json(&value)?; + Ok(writer.bytes) +} + +struct BoundedEnvelopeWriter { + bytes: Vec, +} +impl std::io::Write for BoundedEnvelopeWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if self.bytes.len().saturating_add(bytes.len()) > MAX_ENVELOPE_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "panel envelope byte cap")); + } + self.bytes.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +fn validate_envelope(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> { + if envelope.format != ENVELOPE_FORMAT { + return Err(error(Rule::Schema, "unknown panel envelope format")); + } + if envelope.version != ENVELOPE_VERSION { + return Err(error(Rule::Version, "unknown panel envelope version")); + } + validate(&envelope.layout, registry)?; + validate_envelope_metadata(envelope) +} + +fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> { + if envelope.quarantine.len() + envelope.layout.instances.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "quarantine instance cap")); + } + if envelope.retained_data.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "retained data cap")); + } + for (id, data) in &envelope.retained_data { + valid_id(&id.0)?; + bounded_json(data)?; + } + if envelope.section_snapshots.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "section snapshot cap")); + } + validate_section_order(&envelope.section_order)?; + for (id, snapshot) in &envelope.section_snapshots { + validate_snapshot(id, snapshot)?; + } + let mut ids = std::collections::BTreeSet::new(); + for item in &envelope.quarantine { + bounded_json(&item.instance_data)?; + valid_id(&item.instance.0)?; + valid_id(&item.kind.0)?; + if !ids.insert(&item.instance) || envelope.layout.instances.iter().any(|p| p.id == item.instance) { + return Err(error(Rule::DuplicateId, "quarantine identity or index invalid")); + } + let instance: PanelInstance = + serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?; + if instance.id != item.instance || instance.kind != item.kind { + return Err(error(Rule::Id, "quarantine identity mismatch")); + } + if instance.requested_open != item.section.is_some() { + return Err(error(Rule::ExactlyOnce, "quarantine open/section mismatch")); + } + valid_id(&instance.memory.section.0)?; + instance.memory.location.validate()?; + instance.memory.size.validate()?; + if instance.memory.section_index > MAX_SECTIONS || instance.memory.tab_index >= MAX_TABS { + return Err(error(Rule::CollectionLimit, "quarantine placement cap")); + } + if let Some(id) = &item.section { + let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "quarantined section snapshot absent"))?; + let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?; + if !section.tabs.contains(&item.instance) { + return Err(error(Rule::ExactlyOnce, "quarantined instance absent from section snapshot")); + } + } + } + Ok(()) +} + +fn validate_section_order(order: &[SectionId]) -> PanelResult<()> { + if order.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "complete section order cap")); + } + let mut seen = std::collections::BTreeSet::new(); + for id in order { + valid_id(&id.0)?; + if !seen.insert(id) { + return Err(error(Rule::DuplicateId, "duplicate complete section rank")); + } + } + Ok(()) +} + +fn validate_section_record(section: &Section) -> PanelResult<()> { + valid_id(§ion.id.0)?; + section.location.validate()?; + section.size.validate()?; + if section.tabs.is_empty() || section.tabs.len() > MAX_TABS || !section.tabs.contains(§ion.active) { + return Err(error(Rule::CollectionLimit, "section snapshot tabs/active bound")); + } + let mut seen = std::collections::BTreeSet::new(); + for id in §ion.tabs { + valid_id(&id.0)?; + if !seen.insert(id) { + return Err(error(Rule::ExactlyOnce, "section snapshot duplicate tab")); + } + } + Ok(()) +} + +fn validate_snapshot(id: &SectionId, snapshot: &SectionSnapshot) -> PanelResult<()> { + valid_id(&id.0)?; + bounded_json(&snapshot.data)?; + let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid shared section snapshot"))?; + if section.id != *id || snapshot.index > MAX_SECTIONS { + return Err(error(Rule::Id, "section snapshot identity/index mismatch")); + } + validate_section_record(§ion)?; + if let Some(projected) = &snapshot.projected { + if projected.id != *id { + return Err(error(Rule::Id, "projected section identity mismatch")); + } + validate_section_record(projected)?; + } + Ok(()) +} + +/// Overlay the live relative order on its previous slots, keeping dormant gaps. +/// New live entries attach before their next surviving live neighbour, rather +/// than consuming a dormant slot or reversing a run of newly added entries. +fn merge_visible_order(saved: &[T], live: &[T], dormant: &std::collections::BTreeSet) -> Vec { + let survivors: std::collections::BTreeSet<_> = saved.iter().filter(|id| live.contains(id)).cloned().collect(); + let mut live_survivors = live.iter().filter(|id| survivors.contains(*id)); + let mut merged = Vec::new(); + for id in saved { + if dormant.contains(id) && !live.contains(id) { + merged.push(id.clone()); + } else if survivors.contains(id) + && let Some(next) = live_survivors.next() + { + merged.push(next.clone()); + } + } + for (index, id) in live.iter().enumerate() { + if survivors.contains(id) { + continue; + } + let before = live.iter().skip(index + 1).find(|next| survivors.contains(*next)); + let at = before.and_then(|next| merged.iter().position(|old| old == next)).unwrap_or(merged.len()); + merged.insert(at, id.clone()); + } + merged +} + +/// Refresh live semantics before a new quarantine episode, or before a direct +/// restoration after the caller has edited the known layout. Opaque data stays +/// shared; only semantic fields supplied by the current layout are refreshed. +fn refresh_section_memory( + envelope: &mut LayoutEnvelope, + raw: Option<&serde_json::Value>, + capture: &std::collections::BTreeSet, +) -> PanelResult<()> { + if envelope.section_snapshots.len() > MAX_SECTIONS || envelope.quarantine.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "section memory collection cap")); + } + validate_section_order(&envelope.section_order)?; + for (id, snapshot) in &envelope.section_snapshots { + validate_snapshot(id, snapshot)?; + } + let dormant_sections: std::collections::BTreeSet<_> = envelope.quarantine.iter().filter_map(|item| item.section.clone()).collect(); + let live_order: Vec<_> = envelope.layout.sections.iter().map(|section| section.id.clone()).collect(); + let mut saved_order = envelope.section_order.clone(); + if saved_order.is_empty() { + // Read earlier v1 envelopes without the complete rank list. Sort missing + // ranks before insertion, never in instance/quarantine processing order. + saved_order = live_order.clone(); + let mut missing = Vec::new(); + for id in &dormant_sections { + let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "dormant section snapshot missing"))?; + if !saved_order.contains(id) { + missing.push((snapshot.index, id.clone())); + } + } + missing.sort(); + for (index, id) in missing { + saved_order.insert(index.min(saved_order.len()), id); + } + } else if dormant_sections.iter().any(|id| !saved_order.contains(id)) { + return Err(error(Rule::MissingTarget, "complete order omits a dormant section")); + } + envelope.section_order = merge_visible_order(&saved_order, &live_order, &dormant_sections); + validate_section_order(&envelope.section_order)?; + for (index, section) in envelope.layout.sections.iter().enumerate() { + let previous = envelope.section_snapshots.get(§ion.id); + if previous.is_none() && !capture.contains(§ion.id) { + continue; + } + let current = match raw { + Some(raw) => raw + .get("layout") + .and_then(|layout| layout.get("sections")) + .and_then(|sections| sections.get(index)) + .cloned() + .ok_or_else(|| error(Rule::Schema, "saved section raw data missing"))?, + None => serde_json::to_value(section).map_err(|_| error(Rule::Schema, "cannot encode live section semantics"))?, + }; + let (mut data, projected) = match previous { + Some(previous) => (previous.data.clone(), previous.projected.clone()), + None => (serde_json::json!({}), None), + }; + let dormant_tabs: std::collections::BTreeSet<_> = + envelope.quarantine.iter().filter(|item| item.section.as_ref() == Some(§ion.id)).map(|item| item.instance.clone()).collect(); + let previous_section: Option
= previous + .map(|snapshot| serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid section memory"))) + .transpose()?; + let tabs = match &previous_section { + Some(saved) if !dormant_tabs.is_empty() => merge_visible_order(&saved.tabs, §ion.tabs, &dormant_tabs), + _ => section.tabs.clone(), + }; + if tabs.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "complete tab order cap")); + } + let active = match &previous_section { + Some(saved) + if dormant_tabs.contains(&saved.active) + && !section.tabs.contains(&saved.active) + && !projected.as_ref().is_some_and(|last| last.active != section.active) => + { + saved.active.clone() + } + _ => section.active.clone(), + }; + // Overlay current fields, preserving opaque keys absent from the typed + // layout. A current raw value for the same key is the latest saved intent. + let object = data.as_object_mut().ok_or_else(|| error(Rule::Schema, "section memory must be an object"))?; + let current = current.as_object().ok_or_else(|| error(Rule::Schema, "saved section must be an object"))?; + for (key, value) in current { + object.insert(key.clone(), value.clone()); + } + object.insert("tabs".into(), serde_json::to_value(tabs).map_err(|_| error(Rule::Schema, "cannot encode complete tab order"))?); + object.insert("active".into(), serde_json::to_value(active).map_err(|_| error(Rule::Schema, "cannot encode complete activation"))?); + let rank = envelope + .section_order + .iter() + .position(|id| *id == section.id) + .ok_or_else(|| error(Rule::MissingTarget, "live section has no complete rank"))?; + envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index: rank, projected }); + } + for (id, snapshot) in &mut envelope.section_snapshots { + if let Some(rank) = envelope.section_order.iter().position(|known| known == id) { + snapshot.index = rank; + } + } + Ok(()) +} + +fn record_section_projections(envelope: &mut LayoutEnvelope) { + let layout = &envelope.layout; + for (id, snapshot) in &mut envelope.section_snapshots { + snapshot.projected = layout.sections.iter().find(|section| section.id == *id).cloned(); + } +} + +/// Stage live edits without losing dormant order, projected activation or opaque +/// fields. The caller publishes only after its guarded layout dispatch succeeds. +pub fn with_live_layout(envelope: &LayoutEnvelope, layout: Layout, registry: &PanelRegistry) -> PanelResult { + encode(envelope, registry)?; + validate(&layout, registry)?; + let mut next = envelope.clone(); + next.layout = layout; + refresh_section_memory(&mut next, None, &std::collections::BTreeSet::new())?; + record_section_projections(&mut next); + encode(&next, registry)?; + Ok(next) +} + +/// Iterative traversal also bounds caller-constructed JSON, which did not pass +/// through serde_json's parser/recursion limit. +pub fn bounded_json(value: &serde_json::Value) -> PanelResult<()> { + let mut stack = vec![(value, 0_usize)]; + let mut nodes = 0_usize; + let mut bytes = 0_usize; + while let Some((value, depth)) = stack.pop() { + nodes = nodes.saturating_add(1); + if nodes > 8192 || depth > 32 { + return Err(error(Rule::CollectionLimit, "JSON node/depth cap")); + } + match value { + serde_json::Value::String(s) => bytes = bytes.saturating_add(s.len()), + serde_json::Value::Array(values) => { + if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 { + return Err(error(Rule::CollectionLimit, "JSON array cap")); + } + stack.extend(values.iter().map(|value| (value, depth + 1))); + } + serde_json::Value::Object(values) => { + if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 { + return Err(error(Rule::CollectionLimit, "JSON object cap")); + } + for (key, value) in values { + bytes = bytes.saturating_add(key.len()); + stack.push((value, depth + 1)); + } + } + serde_json::Value::Number(n) if n.as_f64().is_some_and(|n| !n.is_finite()) => return Err(error(Rule::Bounds, "nonfinite JSON value")), + _ => {} + } + if bytes > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "JSON byte cap")); + } + } + Ok(()) +} + +/// Decode bounded bytes, quarantine unknown kinds, and retry retained panels when +/// registered again. Corrupt/future input returns a validated safe preset plus notice. +pub fn decode(bytes: &[u8], registry: &PanelRegistry, fallback: &Layout) -> PanelResult { + validate(fallback, registry)?; + match decode_inner(bytes, registry, &fallback.workspace, true) { + Ok(envelope) => Ok(LoadOutcome { envelope, notice: None, rejected: None }), + Err(reason) => Ok(LoadOutcome { + envelope: LayoutEnvelope::new(fallback.clone()), + notice: Some(reason), + rejected: if bytes.len() <= MAX_ENVELOPE_BYTES { Some(bytes.to_vec()) } else { None }, + }), + } +} + +/// Validate an already-retained record exactly, without generating section order, +/// projections or quarantine/restoration metadata. Missing registrations do not +/// invalidate saved intent. Structure and every applicable known-kind constraint +/// are still validated, but this retained layout is NOT permission to commit it +/// to a live sink. Use `project_retained_record` to stage registry migration. +pub fn decode_retained_record(bytes: &[u8], registry: &PanelRegistry) -> PanelResult { + if bytes.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap")); + } + let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; + bounded_json(&raw)?; + let envelope: LayoutEnvelope = serde_json::from_value(raw).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?; + if envelope.format != ENVELOPE_FORMAT { + return Err(error(Rule::Schema, "unknown panel envelope format")); + } + if envelope.version != ENVELOPE_VERSION { + return Err(error(Rule::Version, "unknown panel envelope version")); + } + validate_retained_layout(&envelope.layout, registry)?; + validate_envelope_metadata(&envelope)?; + // The same canonical encodability budget as admission, without filling any + // metadata or requiring absent peers. The caller retains the ORIGINAL bytes. + encode_record(&envelope)?; + Ok(envelope) +} + +/// Read a retained record in its workspace without consuming a reappearance +/// obligation or materializing absent order/projection metadata. +pub fn decode_retained(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + valid_id(&workspace.0)?; + let envelope = decode_retained_record(bytes, registry)?; + if envelope.layout.workspace != *workspace { + return Err(error(Rule::Schema, "panel envelope workspace mismatch")); + } + Ok(envelope) +} + +/// Stage a usable current-registry layout without consuming quarantined +/// reappearance obligations. Newly absent kinds move to the foundation's +/// lossless quarantine. Metadata expansion can fail at the existing caps; the +/// original record remains available for retry and no live state is published. +pub fn project_retained_record(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + let envelope = decode_retained(bytes, registry, workspace)?; + if envelope.layout.instances.iter().any(|instance| registry.get(&instance.kind).is_err()) { + decode_inner(bytes, registry, workspace, false) + } else { + Ok(envelope) + } +} + +fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, restore: bool) -> PanelResult { + if bytes.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap")); + } + // serde_json's recursion limit remains enabled. Parsing starts only after the + // byte bound, so oversized arrays/strings cannot allocate without a bound. + let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; + bounded_json(&raw)?; + let mut envelope: LayoutEnvelope = serde_json::from_value(raw.clone()).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?; + if envelope.version != ENVELOPE_VERSION || envelope.layout.version != LAYOUT_VERSION { + return Err(error(Rule::Version, "future or unsupported panel layout")); + } + if envelope.format != ENVELOPE_FORMAT || envelope.layout.workspace != *workspace { + return Err(error(Rule::Schema, "panel envelope format/workspace mismatch")); + } + if envelope.layout.instances.len() > MAX_INSTANCES + || envelope.layout.sections.len() > MAX_SECTIONS + || envelope.quarantine.len() > MAX_INSTANCES + || envelope.layout.sections.iter().any(|s| s.tabs.len() > MAX_TABS) + { + return Err(error(Rule::CollectionLimit, "panel collection limit")); + } + validate_retained_layout(&envelope.layout, registry)?; + validate_envelope_metadata(&envelope)?; + let unknown: Vec<_> = envelope.layout.instances.iter().filter(|p| registry.get(&p.kind).is_err()).cloned().collect(); + let capture: std::collections::BTreeSet<_> = envelope + .layout + .sections + .iter() + .filter(|section| unknown.iter().any(|p| section.tabs.contains(&p.id))) + .map(|section| section.id.clone()) + .collect(); + // Refresh from the saved live layout BEFORE newly unknown members are + // removed. A previous fully-restored snapshot is opaque metadata, not an + // authority that can overwrite intervening saved edits. + refresh_section_memory(&mut envelope, Some(&raw), &capture)?; + for instance in unknown { + let section_index = envelope.layout.sections.iter().position(|s| s.tabs.contains(&instance.id)); + let instance_data = raw + .get("layout") + .and_then(|l| l.get("instances")) + .and_then(|a| a.as_array()) + .and_then(|a| a.iter().find(|v| v.get("id").and_then(|s| s.as_str()) == Some(instance.id.0.as_str()))) + .cloned() + .ok_or_else(|| error(Rule::Schema, "unknown instance raw data missing"))?; + let section = if let Some(index) = section_index { + let id = envelope.layout.sections.get(index).ok_or_else(|| error(Rule::MissingTarget, "unknown section absent"))?.id.clone(); + Some(id) + } else { + None + }; + envelope.quarantine.push(QuarantinedPanel { instance: instance.id.clone(), kind: instance.kind, instance_data, section }); + envelope.layout.instances.retain(|p| p.id != instance.id); + } + let retained: std::collections::BTreeSet<_> = envelope.layout.instances.iter().map(|p| p.id.clone()).collect(); + for section in &mut envelope.layout.sections { + section.tabs.retain(|id| retained.contains(id)); + if !section.tabs.contains(§ion.active) + && let Some(first) = section.tabs.first() + { + section.active = first.clone(); + } + } + envelope.layout.sections.retain(|s| !s.tabs.is_empty()); + // Newly quarantining an active tab creates a fallback selection. That + // projection is produced by us, not an intervening user activation. + record_section_projections(&mut envelope); + validate_envelope(&envelope, registry)?; + if restore { + restore_quarantine(&mut envelope, registry)?; + } + // Success means the lossless transformed envelope is itself persistable, + // including its aggregate byte/node/depth budget. Otherwise retain recovery. + encode(&envelope, registry)?; + Ok(envelope) +} + +pub fn restore_quarantine(envelope: &mut LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> { + restore_quarantine_with_availability(envelope, registry, &AvailabilityMap::new()) +} + +pub fn restore_quarantine_with_availability( + envelope: &mut LayoutEnvelope, + registry: &PanelRegistry, + availability: &AvailabilityMap, +) -> PanelResult<()> { + validate_envelope(envelope, registry)?; + if availability.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "reappearance availability cap")); + } + for (id, state) in availability { + valid_id(&id.0)?; + if matches!(state, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) { + return Err(error(Rule::Availability, "invalid reappearance availability reason")); + } + } + let mut working = envelope.clone(); + // Direct consumers may have edited the live layout since the last decode or + // restore. Merge those edits before using saved ranks/activation again. + refresh_section_memory(&mut working, None, &std::collections::BTreeSet::new())?; + // Build a candidate for each entry. An incompatible reappearance stays in + // quarantine instead of invalidating the known layout or erasing its wire data. + let mut remaining = Vec::new(); + for item in &envelope.quarantine { + if registry.get(&item.kind).is_err() || availability.get(&item.instance).is_some_and(|state| *state != Availability::Available) { + remaining.push(item.clone()); + continue; + } + let mut candidate = working.layout.clone(); + let instance: PanelInstance = + serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?; + candidate.instances.push(instance.clone()); + if instance.requested_open { + let Some(section_id) = &item.section else { + remaining.push(item.clone()); + continue; + }; + let snapshot = working.section_snapshots.get(section_id).ok_or_else(|| error(Rule::MissingTarget, "shared snapshot missing"))?; + let mut saved: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?; + if let Some(section) = candidate.sections.iter_mut().find(|s| s.id == saved.id) { + let members: std::collections::BTreeSet<_> = section.tabs.iter().cloned().chain(std::iter::once(instance.id.clone())).collect(); + section.tabs = saved + .tabs + .iter() + .filter(|id| members.contains(*id)) + .cloned() + .chain(section.tabs.iter().filter(|id| !saved.tabs.contains(id)).cloned()) + .collect(); + if saved.active == instance.id { + section.active = saved.active.clone(); + } + } else { + saved.tabs = vec![instance.id.clone()]; + saved.active = instance.id.clone(); + candidate.sections.push(saved); + } + } + // Rank against the full saved order, not an index clamped into a partial + // list. Sorting also includes surviving sections with no snapshot. + candidate.sections.sort_by_key(|section| working.section_order.iter().position(|id| *id == section.id).unwrap_or(MAX_SECTIONS)); + if validate(&candidate, registry).is_ok() { + if working.retained_data.len() >= MAX_INSTANCES && !working.retained_data.contains_key(&item.instance) { + remaining.push(item.clone()); + continue; + } + working + .retained_data + .entry(item.instance.clone()) + .or_insert_with(|| serde_json::json!({"instance":item.instance_data,"section":item.section})); + working.layout = candidate; + } else { + remaining.push(item.clone()); + } + } + working.quarantine = remaining; + record_section_projections(&mut working); + encode(&working, registry)?; + *envelope = working; + Ok(()) +} + +/// Validate saved identities/ownership independently of optional peers, then use +/// the ordinary validator for known members. The temporary known-only view is +/// validation input only: it is never returned, encoded, or dispatched. +fn validate_retained_layout(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> { + validate_wire_structure(layout)?; + if layout.instances.iter().all(|instance| registry.get(&instance.kind).is_ok()) { + return validate(layout, registry); + } + let mut edges = std::collections::BTreeSet::new(); + for section in &layout.sections { + let zone = section.location.zone(); + let first = edges.insert(zone); + for id in §ion.tabs { + let instance = layout.instance(id)?; + if let Ok(spec) = registry.get(&instance.kind) { + // Filtering absent tabs/sections must not hide these constraints + // of a known member in the ORIGINAL full saved placement. + if section.tabs.len() > 1 && !spec.features.tabbable { + return Err(error(Rule::FeatureDisabled, "panel cannot join tabs")); + } + if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) && !first { + return Err(error(Rule::PinOrder, "pinned section must be outermost")); + } + } + } + } + let mut known = layout.clone(); + known.instances.retain(|instance| registry.get(&instance.kind).is_ok()); + let ids: std::collections::BTreeSet<_> = known.instances.iter().map(|instance| instance.id.clone()).collect(); + for section in &mut known.sections { + section.tabs.retain(|id| ids.contains(id)); + if !section.tabs.contains(§ion.active) + && let Some(first) = section.tabs.first() + { + section.active = first.clone(); + } + } + known.sections.retain(|section| !section.tabs.is_empty()); + validate(&known, registry) +} + +fn validate_wire_structure(layout: &Layout) -> PanelResult<()> { + if layout.version != LAYOUT_VERSION { + return Err(error(Rule::Version, "unsupported layout version")); + } + valid_id(&layout.workspace.0)?; + if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "layout collection limit")); + } + let mut instances = std::collections::BTreeSet::new(); + let mut sections = std::collections::BTreeSet::new(); + let mut seen = std::collections::BTreeSet::new(); + let mut hosts = std::collections::BTreeSet::new(); + for instance in &layout.instances { + valid_id(&instance.id.0)?; + valid_id(&instance.kind.0)?; + valid_id(&instance.memory.section.0)?; + instance.memory.location.validate()?; + instance.memory.size.validate()?; + if instance.memory.tab_index >= MAX_TABS || instance.memory.section_index > MAX_SECTIONS { + return Err(error(Rule::Bounds, "invalid placement memory")); + } + if !instances.insert(&instance.id) { + return Err(error(Rule::DuplicateId, "duplicate unknown/known instance")); + } + } + for section in &layout.sections { + valid_id(§ion.id.0)?; + section.location.validate()?; + section.size.validate()?; + if !sections.insert(§ion.id) { + return Err(error(Rule::DuplicateId, "duplicate unknown/known section")); + } + if section.tabs.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "section tab cap")); + } + if let SectionLocation::Window { host, .. } = §ion.location + && !hosts.insert(host) + { + return Err(error(Rule::DuplicateId, "native host reused")); + } + if section.tabs.is_empty() || !section.tabs.contains(§ion.active) { + return Err(error(Rule::ExactlyOnce, "invalid unknown/known active tab")); + } + for id in §ion.tabs { + if !instances.contains(id) || !seen.insert(id) { + return Err(error(Rule::ExactlyOnce, "unknown/known tab ownership invalid")); + } + } + } + for instance in &layout.instances { + if instance.requested_open != seen.contains(&instance.id) { + return Err(error(Rule::ExactlyOnce, "unknown/known open state invalid")); + } + } + Ok(()) +} + +/// JSON schema for the wire contract. Semantic constraints are enforced by decode +/// and the reducer; schema alone is never treated as a validation proof. +pub fn layout_action_schema() -> schemars::Schema { + schemars::schema_for!(LayoutAction) +} +pub fn layout_reply_schema() -> schemars::Schema { + schemars::schema_for!(LayoutReply) +} +pub fn layout_error_schema() -> schemars::Schema { + schemars::schema_for!(PanelError) +} +pub fn layout_envelope_schema() -> schemars::Schema { + schemars::schema_for!(LayoutEnvelope) +} + +pub fn decode_action(bytes: &[u8]) -> PanelResult { + if bytes.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "action byte cap")); + } + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid action JSON"))?; + bounded_json(&value)?; + let action: LayoutAction = serde_json::from_value(value).map_err(|_| error(Rule::Schema, "invalid action shape"))?; + if let LayoutAction::Apply { mutations, .. } = &action + && (mutations.is_empty() || mutations.len() > MAX_MUTATIONS) + { + return Err(error(Rule::CollectionLimit, "action mutation cap")); + } + Ok(action) +} diff --git a/crates/engine/src/panels/reducer.rs b/crates/engine/src/panels/reducer.rs new file mode 100644 index 000000000..5a8189162 --- /dev/null +++ b/crates/engine/src/panels/reducer.rs @@ -0,0 +1,732 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::*; + +/// Joining an existing tab group and creating a split are deliberately distinct. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Destination { + NewSection { section: SectionId, index: usize, location: SectionLocation, size: Size }, + JoinTab { section: SectionId, index: usize }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Mutation { + Open { + kind: PanelKind, + instance: InstanceId, + destination: Option, + }, + Close { + instance: InstanceId, + }, + /// Explicit owner cleanup, only after close. Hiding is never destruction. + Destroy { + instance: InstanceId, + }, + Move { + instance: InstanceId, + destination: Destination, + }, + Activate { + instance: InstanceId, + }, + Focus { + instance: InstanceId, + }, + Peek { + instance: InstanceId, + }, + DismissPeek, + Collapse { + section: SectionId, + collapsed: bool, + }, + SetSize { + section: SectionId, + size: Size, + }, + /// Both neighbours change together; their shared axis extent is conserved. + ResizePair { + first: SectionId, + second: SectionId, + first_size: Size, + second_size: Size, + }, + ResetPair { + first: SectionId, + second: SectionId, + }, + /// A native window's close button redocks its whole section. + NativeClose { + host: HostId, + }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum LayoutAction { + Inspect, + Apply { + expected_revision: Option, + mutations: Vec, + }, + /// Apply a complete saved layout/preset, including a workspace change. + /// Omission and requested_open=false hide content without lifecycle intent. + Replace { + expected_revision: Option, + layout: Layout, + }, +} + +/// Stable targets for a later command adapter; none are registered with Session yet. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", content = "id", rename_all = "snake_case")] +pub enum LayoutTarget { + Workspace(WorkspaceId), + Instance(InstanceId), + Section(SectionId), + NativeHost(HostId), +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum HostEffect { + Focus { instance: InstanceId }, + Peek { instance: InstanceId }, + DismissPeek, + CreateNative { host: HostId, section: SectionId }, + RebindNative { host: HostId, section: SectionId }, + ReleaseNative { host: HostId }, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct InteractionState { + pub focused: Option, + pub peek: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct LayoutReply { + pub api_version: u32, + pub revision: u64, + pub layout: Layout, + pub interaction: InteractionState, + pub effects: Vec, + pub capabilities: HostCapabilities, + pub availability: AvailabilityMap, +} + +/// Same boundary for GUI and programmatic callers. No mutable Session reference. +pub trait ActionSink { + fn dispatch(&mut self, action: LayoutAction) -> PanelResult; + fn inspect(&self) -> LayoutReply; + /// Pure projection on the authoritative service. Adapters stage bounded + /// envelope/storage changes from this before guarded dispatch publishes. + fn project(&self, _action: LayoutAction) -> PanelResult { + Err(error(Rule::Capability, "layout sink cannot stage commands")) + } +} + +#[derive(Debug)] +pub struct LayoutService { + identity: std::sync::Arc<()>, + registry: PanelRegistry, + layout: Layout, + revision: u64, + availability: AvailabilityMap, + interaction: InteractionState, + capabilities: HostCapabilities, + identities: std::collections::BTreeMap, +} + +/// An optimistic, fully validated candidate. Fields stay private so it cannot be forged. +pub struct PreparedLayout { + service_identity: std::sync::Arc<()>, + base_revision: u64, + next: Layout, + interaction: InteractionState, + effects: Vec, + changed: bool, + availability: AvailabilityMap, + identities: std::collections::BTreeMap, +} + +impl PreparedLayout { + pub fn layout(&self) -> &Layout { + &self.next + } + pub fn effects(&self) -> &[HostEffect] { + &self.effects + } + /// Runtime availability is staged with the same atomic layout commit. + pub fn set_availability(&mut self, availability: AvailabilityMap) -> PanelResult<()> { + validate_availability(&availability)?; + self.changed |= self.availability != availability; + self.availability = availability; + Ok(()) + } +} + +impl LayoutService { + pub fn new(registry: PanelRegistry, layout: Layout, capabilities: HostCapabilities) -> PanelResult { + validate(&layout, ®istry)?; + if capabilities.max_native_hosts > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "native capability exceeds section cap")); + } + // Restored native entries remain data even on web; resolve_geometry marks them + // unpresented. New native mutations still require a capable adapter. + Ok(Self { + identity: std::sync::Arc::new(()), + registry, + identities: layout.instances.iter().map(|p| (p.id.clone(), p.kind.clone())).collect(), + layout, + revision: 0, + availability: AvailabilityMap::new(), + interaction: InteractionState::default(), + capabilities, + }) + } + pub fn registry(&self) -> &PanelRegistry { + &self.registry + } + pub fn layout(&self) -> &Layout { + &self.layout + } + pub fn interaction(&self) -> &InteractionState { + &self.interaction + } + pub fn capabilities(&self) -> &HostCapabilities { + &self.capabilities + } + pub fn availability(&self, id: &InstanceId) -> Availability { + self.availability.get(id).cloned().unwrap_or(Availability::Available) + } + pub fn set_availability(&mut self, values: AvailabilityMap) -> PanelResult<()> { + validate_availability(&values)?; + if self.availability != values { + let revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?; + self.availability = values; + self.revision = revision; + self.reconcile_interaction(); + } + Ok(()) + } + fn reconcile_interaction(&mut self) { + let layout = &self.layout; + let availability = &self.availability; + let visible = |id: &InstanceId| { + layout.instance(id).is_ok_and(|p| p.requested_open) && availability.get(id).is_none_or(|state| *state == Availability::Available) + }; + if self.interaction.focused.as_ref().is_some_and(|id| !visible(id)) { + self.interaction.focused = None; + } + if self.interaction.peek.as_ref().is_some_and(|id| !visible(id)) { + self.interaction.peek = None; + } + } + pub fn prepare(&self, action: LayoutAction) -> PanelResult { + let mut next = self.layout.clone(); + let mut interaction = self.interaction.clone(); + let mut effects = Vec::new(); + let mut availability = self.availability.clone(); + let mut destroyed = std::collections::BTreeSet::new(); + if let LayoutAction::Replace { expected_revision, layout } = &action { + if expected_revision.is_some_and(|r| r != self.revision) { + return Err(error(Rule::Revision, "stale layout revision")); + } + validate(layout, &self.registry)?; + next = layout.clone(); + availability.clear(); + interaction = InteractionState::default(); + } + if let LayoutAction::Apply { expected_revision, mutations } = action { + if expected_revision.is_some_and(|r| r != self.revision) { + return Err(error(Rule::Revision, "stale layout revision")); + } + if mutations.is_empty() || mutations.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "transaction requires 1..64 mutations")); + } + validate_lifecycle_intents(&mutations)?; + for mutation in &mutations { + if let Mutation::Destroy { instance } = mutation { + destroyed.insert(instance.clone()); + } + } + for mutation in mutations { + apply(&mut next, &self.registry, &self.availability, &self.capabilities, &mut interaction, &mut effects, mutation)?; + // A bounded intermediate state cannot smuggle oversized collections into + // a later mutation. Semantic invariants are checked at atomic commit. + if next.instances.len() > MAX_INSTANCES || next.sections.len() > MAX_SECTIONS || next.sections.iter().any(|s| s.tabs.len() > MAX_TABS) + { + return Err(error(Rule::CollectionLimit, "transaction collection limit")); + } + } + validate(&next, &self.registry)?; + for before in &self.layout.instances { + if next.instances.iter().any(|after| after.id == before.id && after.kind != before.kind) { + return Err(error(Rule::DuplicateId, "transaction cannot reuse an instance for another kind")); + } + } + } + let mut identities = self.identities.clone(); + for id in destroyed { + identities.remove(&id); + } + for p in &next.instances { + if identities.get(&p.id).is_some_and(|kind| *kind != p.kind) { + return Err(error(Rule::DuplicateId, "instance identity cannot change kind across layouts/workspaces")); + } + identities.insert(p.id.clone(), p.kind.clone()); + } + if identities.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "retained instance identity cap")); + } + // Native effects describe the committed difference, never intermediate windows. + let old = native_hosts(&self.layout); + let new = native_hosts(&next); + for (host, section) in &new { + if !old.iter().any(|(h, _)| h == host) { + if !self.capabilities.native_windows || new.len() > self.capabilities.max_native_hosts { + return Err(error(Rule::Capability, "native hosts unavailable or at capacity")); + } + effects.push(HostEffect::CreateNative { host: host.clone(), section: section.clone() }); + } else if self.layout.workspace != next.workspace || old.iter().any(|(h, s)| h == host && s != section) { + if !self.capabilities.native_windows { + return Err(error(Rule::Capability, "cannot rebind unsupported native host")); + } + effects.push(HostEffect::RebindNative { host: host.clone(), section: section.clone() }); + } + } + for (host, _) in old { + if !new.iter().any(|(h, _)| *h == host) { + effects.push(HostEffect::ReleaseNative { host }); + } + } + if interaction.focused.as_ref().is_some_and(|id| !next.containing(id).is_ok_and(|s| !s.collapsed && s.active == *id)) { + interaction.focused = None; + } + if interaction + .peek + .as_ref() + .is_some_and(|id| !next.instance(id).is_ok_and(|p| p.requested_open) || !next.containing(id).is_ok_and(|s| s.collapsed)) + { + interaction.peek = None; + } + effects.retain(|effect| match effect { + HostEffect::Focus { instance } => interaction.focused.as_ref() == Some(instance), + HostEffect::Peek { instance } => interaction.peek.as_ref() == Some(instance), + _ => true, + }); + let changed = next != self.layout || interaction != self.interaction || availability != self.availability || !effects.is_empty(); + if changed && self.revision == u64::MAX { + return Err(error(Rule::Revision, "layout revision exhausted")); + } + Ok(PreparedLayout { + service_identity: self.identity.clone(), + base_revision: self.revision, + next, + interaction, + effects, + changed, + availability, + identities, + }) + } + pub fn commit(&mut self, prepared: PreparedLayout) -> PanelResult { + if !std::sync::Arc::ptr_eq(&prepared.service_identity, &self.identity) || prepared.base_revision != self.revision { + return Err(error(Rule::Revision, "candidate became stale")); + } + if prepared.changed { + self.revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?; + } + self.layout = prepared.next; + self.interaction = prepared.interaction; + self.availability = prepared.availability; + self.identities = prepared.identities; + self.reconcile_interaction(); + let mut reply = self.inspect(); + reply.effects = prepared.effects; + Ok(reply) + } +} + +fn validate_availability(values: &AvailabilityMap) -> PanelResult<()> { + if values.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "availability map full")); + } + for (id, state) in values { + valid_id(&id.0)?; + if let Availability::Unavailable { reason } = state + && (reason.is_empty() || reason.len() > 256) + { + return Err(error(Rule::Availability, "availability reason must contain 1..256 bytes")); + } + } + Ok(()) +} + +/// Close/Destroy are explicit, irreversible content intents. Do not infer them +/// solely from net layout differences, or permit later mutations to erase them. +pub fn validate_lifecycle_intents(mutations: &[Mutation]) -> PanelResult<()> { + if mutations.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "lifecycle intent batch cap")); + } + let mut counts = std::collections::BTreeMap::<&InstanceId, (usize, bool)>::new(); + for mutation in mutations { + let (id, terminal) = match mutation { + Mutation::Close { instance } | Mutation::Destroy { instance } => (instance, true), + Mutation::Open { instance, .. } + | Mutation::Move { instance, .. } + | Mutation::Activate { instance } + | Mutation::Focus { instance } + | Mutation::Peek { instance } => (instance, false), + _ => continue, + }; + let entry = counts.entry(id).or_default(); + entry.0 += 1; + entry.1 |= terminal; + if entry.1 && entry.0 > 1 { + return Err(error(Rule::Lifecycle, "Close/Destroy cannot share a batch with another operation on that instance")); + } + } + Ok(()) +} + +impl ActionSink for LayoutService { + fn project(&self, action: LayoutAction) -> PanelResult { + Ok(self.prepare(action)?.layout().clone()) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + let prepared = self.prepare(action)?; + self.commit(prepared) + } + fn inspect(&self) -> LayoutReply { + LayoutReply { + api_version: PANEL_API_VERSION, + revision: self.revision, + layout: self.layout.clone(), + interaction: self.interaction.clone(), + effects: Vec::new(), + capabilities: self.capabilities.clone(), + availability: self.availability.clone(), + } + } +} + +fn native_hosts(layout: &Layout) -> Vec<(HostId, SectionId)> { + layout + .sections + .iter() + .filter_map(|s| match &s.location { + SectionLocation::Window { host, .. } => Some((host.clone(), s.id.clone())), + _ => None, + }) + .collect() +} + +fn available(map: &AvailabilityMap, id: &InstanceId) -> PanelResult<()> { + if let Some(state) = map.get(id) { + state.require()?; + } + Ok(()) +} + +fn section_mut<'a>(layout: &'a mut Layout, id: &SectionId) -> PanelResult<&'a mut Section> { + layout.sections.iter_mut().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found")) +} + +fn remember(layout: &mut Layout, id: &InstanceId) -> PanelResult<()> { + let section = layout.containing(id)?.clone(); + let section_index = layout.sections.iter().position(|s| s.id == section.id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))?; + let tab_index = section.tabs.iter().position(|p| p == id).ok_or_else(|| error(Rule::MissingTarget, "tab not found"))?; + let p = layout.instances.iter_mut().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found"))?; + p.memory = PlacementMemory { + section: section.id, + location: section.location, + section_index, + tab_index, + size: section.size, + collapsed: section.collapsed, + }; + Ok(()) +} + +fn detach(layout: &mut Layout, id: &InstanceId) { + for s in &mut layout.sections { + s.tabs.retain(|p| p != id); + if s.active == *id + && let Some(first) = s.tabs.first() + { + s.active = first.clone(); + } + } + layout.sections.retain(|s| !s.tabs.is_empty()); +} + +fn place(layout: &mut Layout, id: &InstanceId, destination: Destination) -> PanelResult<()> { + match destination { + Destination::NewSection { section, index, location, size } => { + valid_id(§ion.0)?; + location.validate()?; + size.validate()?; + if layout.sections.iter().any(|s| s.id == section) { + return Err(error(Rule::DuplicateId, "new-section identity already exists")); + } + if index > layout.sections.len() { + return Err(error(Rule::Bounds, "section insertion index out of bounds")); + } + layout.sections.insert(index, Section { id: section, location, tabs: vec![id.clone()], active: id.clone(), size, collapsed: false }); + } + Destination::JoinTab { section, index } => { + let s = section_mut(layout, §ion)?; + if index > s.tabs.len() { + return Err(error(Rule::Bounds, "tab insertion index out of bounds")); + } + s.tabs.insert(index, id.clone()); + // Joining never steals active tab or resizes the group. + } + } + Ok(()) +} + +fn reopen_destination(layout: &Layout, p: &PanelInstance) -> Destination { + if let Ok(s) = layout.section(&p.memory.section) { + Destination::JoinTab { section: s.id.clone(), index: p.memory.tab_index.min(s.tabs.len()) } + } else { + Destination::NewSection { + section: p.memory.section.clone(), + index: p.memory.section_index.min(layout.sections.len()), + location: p.memory.location.clone(), + size: p.memory.size, + } + } +} + +fn apply( + layout: &mut Layout, + registry: &PanelRegistry, + availability: &AvailabilityMap, + caps: &HostCapabilities, + interaction: &mut InteractionState, + effects: &mut Vec, + mutation: Mutation, +) -> PanelResult<()> { + match mutation { + Mutation::Open { kind, instance, destination } => { + valid_id(&instance.0)?; + registry.get(&kind)?; + available(availability, &instance)?; + if let Ok(existing) = layout.instance(&instance) { + if existing.kind != kind { + return Err(error(Rule::DuplicateId, "instance belongs to another kind")); + } + if existing.requested_open { + if destination.is_some() { + return Err(error(Rule::Placement, "use Move for an open instance")); + } + return Ok(()); + } + let p = existing.clone(); + let restore_collapsed = destination.is_none() && layout.section(&p.memory.section).is_err(); + let destination = destination.unwrap_or_else(|| reopen_destination(layout, &p)); + place(layout, &instance, destination)?; + if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) { + entry.requested_open = true; + } + if restore_collapsed && let Some(s) = layout.sections.iter_mut().find(|s| s.id == p.memory.section) { + s.collapsed = p.memory.collapsed; + } + } else { + let destination = destination.ok_or_else(|| error(Rule::Placement, "new instance requires explicit destination"))?; + place(layout, &instance, destination)?; + let s = layout.containing(&instance)?.clone(); + layout.instances.push(PanelInstance { + id: instance.clone(), + kind, + requested_open: true, + memory: PlacementMemory { + section: s.id, + location: s.location, + section_index: 0, + tab_index: 0, + size: s.size, + collapsed: s.collapsed, + }, + }); + } + } + Mutation::Close { instance } => { + let p = layout.instance(&instance)?; + if !registry.get(&p.kind)?.features.closable { + return Err(error(Rule::FeatureDisabled, "panel is not closable")); + } + if p.requested_open { + remember(layout, &instance)?; + detach(layout, &instance); + if let Some(p) = layout.instances.iter_mut().find(|p| p.id == instance) { + p.requested_open = false; + } + } + } + Mutation::Destroy { instance } => { + if layout.instance(&instance)?.requested_open { + return Err(error(Rule::Lifecycle, "close before owner destruction")); + } + layout.instances.retain(|p| p.id != instance); + } + Mutation::Move { instance, destination } => { + if !layout.instance(&instance)?.requested_open { + return Err(error(Rule::Placement, "cannot move a closed instance")); + } + let collapsed = layout.containing(&instance)?.collapsed; + remember(layout, &instance)?; + detach(layout, &instance); + let new_section = match &destination { + Destination::NewSection { section, .. } => Some(section.clone()), + _ => None, + }; + place(layout, &instance, destination)?; + if let Some(id) = new_section { + section_mut(layout, &id)?.collapsed = collapsed; + } + } + Mutation::Activate { instance } => { + available(availability, &instance)?; + let section = layout.containing(&instance)?.id.clone(); + section_mut(layout, §ion)?.active = instance; + } + Mutation::Focus { instance } => { + available(availability, &instance)?; + let p = layout.instance(&instance)?.clone(); + if !p.requested_open { + let destination = reopen_destination(layout, &p); + place(layout, &instance, destination)?; + if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) { + entry.requested_open = true; + } + } + let section = layout.containing(&instance)?.id.clone(); + let s = section_mut(layout, §ion)?; + s.active = instance.clone(); + s.collapsed = false; + interaction.peek = None; + interaction.focused = Some(instance.clone()); + effects.push(HostEffect::Focus { instance }); + } + Mutation::Peek { instance } => { + available(availability, &instance)?; + let s = layout.containing(&instance)?; + if !s.collapsed { + return Err(error(Rule::Placement, "peek requires a collapsed section")); + } + interaction.peek = Some(instance.clone()); + effects.push(HostEffect::Peek { instance }); + } + Mutation::DismissPeek => { + interaction.peek = None; + effects.push(HostEffect::DismissPeek); + } + Mutation::Collapse { section, collapsed } => { + section_mut(layout, §ion)?.collapsed = collapsed; + } + Mutation::SetSize { section, size } => { + size.validate()?; + section_mut(layout, §ion)?.size = size; + } + Mutation::ResizePair { first, second, first_size, second_size } => { + first_size.validate()?; + second_size.validate()?; + let (a, b, zone) = pair(layout, &first, &second)?; + let sum = |a: Size, b: Size| if zone == Zone::Bottom { a.width + b.width } else { a.height + b.height }; + if (sum(a.size, b.size) - sum(first_size, second_size)).abs() > 0.01 { + return Err(error(Rule::Bounds, "paired sash must conserve shared extent")); + } + if zone == Zone::Bottom && (first_size.height != a.size.height || second_size.height != b.size.height) + || zone != Zone::Bottom && (first_size.width != a.size.width || second_size.width != b.size.width) + { + return Err(error(Rule::Bounds, "paired sash changes only split axis")); + } + section_mut(layout, &first)?.size = first_size; + section_mut(layout, &second)?.size = second_size; + } + Mutation::ResetPair { first, second } => { + let (a, b, zone) = pair(layout, &first, &second)?; + let mut a_size = a.size; + let mut b_size = b.size; + let (a_min, a_max) = tab_bounds(layout, registry, a)?; + let (b_min, b_max) = tab_bounds(layout, registry, b)?; + let axis = |s: Size| if zone == Zone::Bottom { s.width } else { s.height }; + let extent = axis(a_size) + axis(b_size); + let lo = axis(a_min).max(extent - axis(b_max)); + let hi = axis(a_max).min(extent - axis(b_min)); + if lo > hi { + return Err(error(Rule::Bounds, "pair cannot satisfy defaults within bounds")); + } + let a_default = registry.get(&layout.instance(&a.active)?.kind)?.default_size; + let b_default = registry.get(&layout.instance(&b.active)?.kind)?.default_size; + let preferred = extent * axis(a_default) / (axis(a_default) + axis(b_default)); + let split = preferred.clamp(lo, hi); + if zone == Zone::Bottom { + a_size.width = split; + b_size.width = extent - split; + } else { + a_size.height = split; + b_size.height = extent - split; + } + section_mut(layout, &first)?.size = a_size; + section_mut(layout, &second)?.size = b_size; + } + Mutation::NativeClose { host } => { + valid_id(&host.0)?; + let index = layout + .sections + .iter() + .position(|s| matches!(&s.location, SectionLocation::Window { host: h, .. } if *h == host)) + .ok_or_else(|| error(Rule::MissingTarget, "native host not found"))?; + let mut section = layout.sections.remove(index); + let SectionLocation::Window { return_to, .. } = section.location else { + return Err(error(Rule::Placement, "not a native section")); + }; + if let Some(join) = &return_to.join + && let Some(target) = layout.sections.iter_mut().find(|s| s.id == join.section && s.location.zone() == return_to.zone) + { + if target.tabs.len().saturating_add(section.tabs.len()) > MAX_TABS { + return Err(error(Rule::CollectionLimit, "native return tab capacity")); + } + let index = join.index.min(target.tabs.len()); + drop(target.tabs.splice(index..index, section.tabs)); + return Ok(()); + } + section.location = SectionLocation::Dock { zone: return_to.zone }; + section.size = return_to.size; + section.collapsed = return_to.collapsed; + layout.sections.insert(return_to.index.min(layout.sections.len()), section); + } + } + let windows = native_hosts(layout); + // Retained unsupported windows can be closed/redocked without native capability. + if caps.native_windows && windows.len() > caps.max_native_hosts { + return Err(error(Rule::Capability, "native host limit")); + } + Ok(()) +} + +fn pair<'a>(layout: &'a Layout, first: &SectionId, second: &SectionId) -> PanelResult<(&'a Section, &'a Section, Zone)> { + if first == second { + return Err(error(Rule::Placement, "sash requires two distinct neighbours")); + } + let a = layout.section(first)?; + let b = layout.section(second)?; + let zone = a.location.zone(); + let edge: Vec<_> = layout.sections.iter().filter(|s| s.location.zone() == zone).collect(); + if !zone.docked() + || b.location.zone() != zone + || !edge.windows(2).any(|p| p.first().is_some_and(|s| s.id == *first) && p.get(1).is_some_and(|s| s.id == *second)) + { + return Err(error(Rule::Placement, "sash requires ordered neighbours in one dock")); + } + Ok((a, b, zone)) +} diff --git a/crates/engine/src/panels/tests.rs b/crates/engine/src/panels/tests.rs new file mode 100644 index 000000000..2db660b99 --- /dev/null +++ b/crates/engine/src/panels/tests.rs @@ -0,0 +1,2476 @@ +use super::*; + +fn id(value: &str) -> InstanceId { + InstanceId::new(value).unwrap() +} +fn section(value: &str) -> SectionId { + SectionId::new(value).unwrap() +} +fn size(width: f32, height: f32) -> Size { + Size { width, height } +} +fn rect(width: f32, height: f32) -> LogicalRect { + LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: size(width, height) } +} +fn open(service: &mut LayoutService, instance: &str, group: &str) { + let index = service.layout().sections.len(); + service.dispatch(transaction(vec![fixture_open("fixture.log", instance, group, Zone::Left, index).unwrap()])).unwrap(); +} +fn reject(service: &mut LayoutService, mutations: Vec, rule: Rule) { + let before = service.inspect(); + assert_eq!(service.dispatch(transaction(mutations)).unwrap_err().rule, rule); + assert_eq!(service.inspect(), before, "failed action must preserve layout/revision/interaction"); +} + +#[test] +fn registry_constraints_and_identifiers_are_bounded() { + let base = synthetic_registry().unwrap().specs().next().unwrap().clone(); + for bad in ["", "UPPER", "two words", &"a".repeat(MAX_ID_BYTES + 1)] { + assert_eq!(PanelKind::new(bad).unwrap_err().rule, Rule::Id); + } + for bad in [f32::NAN, f32::INFINITY, -1.0, 0.0, MAX_LOGICAL + 1.0] { + let mut spec = base.clone(); + spec.min_size.width = bad; + assert_eq!(PanelRegistry::default().register(spec).unwrap_err().rule, Rule::Bounds); + } + let mut spec = base.clone(); + spec.edge_rule = EdgeRule::PinOuter; + assert_eq!(PanelRegistry::default().register(spec).unwrap_err().rule, Rule::Placement); + let mut spec = base.clone(); + spec.allowed_zones.remove(&Zone::Floating); + assert_eq!(PanelRegistry::default().register(spec).unwrap_err().rule, Rule::Placement); + let mut registry = PanelRegistry::default(); + registry.register(base.clone()).unwrap(); + assert_eq!(registry.register(base).unwrap_err().rule, Rule::DuplicateId); +} + +#[test] +fn single_instance_includes_closed_memory_but_multi_instances_coexist() { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.editor", "editor", "edit", Zone::Left, 0).unwrap()])).unwrap(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("editor") }])).unwrap(); + reject(&mut service, vec![fixture_open("fixture.editor", "editor-two", "edit-two", Zone::Left, 0).unwrap()], Rule::ExactlyOnce); + open(&mut service, "log-one", "logs-one"); + open(&mut service, "log-two", "logs-two"); + validate(service.layout(), service.registry()).unwrap(); +} + +#[test] +fn duplicate_missing_and_closed_instances_cannot_enter_sections() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let mut broken = service.layout().clone(); + broken.sections.first_mut().unwrap().tabs.push(id("one")); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::ExactlyOnce); + broken = service.layout().clone(); + broken.instances.first_mut().unwrap().requested_open = false; + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::ExactlyOnce); + broken = service.layout().clone(); + broken.sections.clear(); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::ExactlyOnce); + broken = service.layout().clone(); + broken.sections.first_mut().unwrap().tabs.clear(); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn multi_field_failure_is_atomic_and_inspection_reads_committed_state() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + reject( + &mut service, + vec![ + Mutation::SetSize { section: section("first"), size: size(400.0, 300.0) }, + Mutation::Move { instance: id("absent"), destination: Destination::JoinTab { section: section("first"), index: 0 } }, + ], + Rule::MissingTarget, + ); + let revision = service.inspect().revision; + assert_eq!( + service + .dispatch(LayoutAction::Apply { expected_revision: Some(revision + 1), mutations: vec![Mutation::Close { instance: id("one") }] }) + .unwrap_err() + .rule, + Rule::Revision + ); + let prepared = service.prepare(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + assert!(service.inspect().layout.instance(&id("one")).unwrap().requested_open); + service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + assert_eq!(service.commit(prepared).unwrap_err().rule, Rule::Revision); +} + +#[test] +fn pin_outer_conflicts_include_shared_groups_and_follow_logical_side() { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.pin", "pin-one", "pins", Zone::Left, 0).unwrap()])).unwrap(); + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.pin").unwrap(), + instance: id("pin-two"), + destination: Some(Destination::JoinTab { section: section("pins"), index: 1 }), + }], + Rule::PinConflict, + ); + reject(&mut service, vec![fixture_open("fixture.pin", "pin-two", "pins-two", Zone::Left, 1).unwrap()], Rule::PinConflict); + service.dispatch(transaction(vec![fixture_open("fixture.pin", "pin-two", "pins-two", Zone::Right, 1).unwrap()])).unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("pin-one"), + destination: Destination::NewSection { + section: section("free-pin"), + index: 1, + location: SectionLocation::Floating { origin: Point { x: 0.0, y: 0.0 } }, + size: size(280.0, 240.0), + }, + }])) + .unwrap(); + validate(service.layout(), service.registry()).unwrap(); +} + +#[test] +fn outermost_order_and_forbidden_bottom_are_declarative() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + reject(&mut service, vec![fixture_open("fixture.pin", "pin", "pins", Zone::Left, 1).unwrap()], Rule::PinOrder); + reject(&mut service, vec![fixture_open("fixture.pin", "pin", "pins", Zone::Bottom, 1).unwrap()], Rule::Placement); +} + +#[test] +fn joins_intersect_two_dimensional_constraints_without_changing_active_tab() { + let base = synthetic_registry().unwrap().get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + let mut registry = PanelRegistry::default(); + registry.register(base.clone()).unwrap(); + let mut narrow = base.clone(); + narrow.kind = PanelKind::new("fixture.narrow").unwrap(); + narrow.max_size.width = 250.0; + narrow.default_size.width = 200.0; + let mut wide = base; + wide.kind = PanelKind::new("fixture.wide").unwrap(); + wide.min_size.width = 300.0; + wide.default_size.width = 400.0; + registry.register(narrow).unwrap(); + registry.register(wide).unwrap(); + let mut service = LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture").unwrap()), HostCapabilities::default()).unwrap(); + open(&mut service, "one", "first"); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }])) + .unwrap(); + assert_eq!(service.layout().section(§ion("first")).unwrap().active, id("one")); + // Empty intersection is rejected before testing the group's current size. + let narrow_open = Mutation::Open { + kind: PanelKind::new("fixture.narrow").unwrap(), + instance: id("narrow"), + destination: Some(Destination::NewSection { + section: section("narrow-section"), + index: 1, + location: SectionLocation::Dock { zone: Zone::Right }, + size: size(200.0, 240.0), + }), + }; + service.dispatch(transaction(vec![narrow_open])).unwrap(); + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.wide").unwrap(), + instance: id("wide"), + destination: Some(Destination::JoinTab { section: section("narrow-section"), index: 1 }), + }], + Rule::IncompatibleTabs, + ); +} + +#[test] +fn tab_indices_and_new_section_targets_are_checked() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + reject( + &mut service, + vec![Mutation::Move { instance: id("two"), destination: Destination::JoinTab { section: section("first"), index: usize::MAX } }], + Rule::Bounds, + ); + reject(&mut service, vec![fixture_open("fixture.log", "three", "first", Zone::Left, 0).unwrap()], Rule::DuplicateId); + reject(&mut service, vec![fixture_open("fixture.log", "three", "third", Zone::Left, usize::MAX).unwrap()], Rule::Bounds); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("two"), + destination: Destination::JoinTab { section: section("first"), index: 1 }, + }])) + .unwrap(); + assert_eq!(service.layout().sections.len(), 1); + service.dispatch(transaction(vec![Mutation::Activate { instance: id("two") }])).unwrap(); + assert_eq!(service.layout().sections.first().unwrap().active, id("two")); +} + +#[test] +fn paired_sashes_conserve_axis_and_reset_both_neighbours() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service + .dispatch(transaction(vec![Mutation::ResizePair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 300.0), + }])) + .unwrap(); + reject( + &mut service, + vec![Mutation::ResizePair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 200.0), + second_size: size(280.0, 300.0), + }], + Rule::Bounds, + ); + reject( + &mut service, + vec![Mutation::ResizePair { + first: section("first"), + second: section("first"), + first_size: size(280.0, 200.0), + second_size: size(280.0, 300.0), + }], + Rule::Placement, + ); + service.dispatch(transaction(vec![Mutation::ResetPair { first: section("first"), second: section("second") }])).unwrap(); + assert_eq!(service.layout().section(§ion("first")).unwrap().size.height, 240.0); + assert_eq!(service.layout().section(§ion("second")).unwrap().size.height, 240.0); +} + +#[test] +fn unavailable_requests_fail_but_saved_open_layout_stays_dormant() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let layout = service.layout().clone(); + service.set_availability([(id("one"), Availability::Unavailable { reason: "context absent".into() })].into()).unwrap(); + reject(&mut service, vec![Mutation::Focus { instance: id("one") }], Rule::Availability); + reject( + &mut service, + vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: None }], + Rule::Availability, + ); + assert_eq!(*service.layout(), layout); + let dormant = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); + assert!(dormant.panels.is_empty()); + assert_eq!(dormant.unpresented.first().unwrap().reason, UnpresentedReason::Unavailable); + service.set_availability(AvailabilityMap::new()).unwrap(); + assert_eq!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.len(), 1); +} + +#[test] +fn closed_state_reopens_with_placement_size_and_collapse_memory() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + service + .dispatch(transaction(vec![ + Mutation::SetSize { section: section("first"), size: size(350.0, 300.0) }, + Mutation::Collapse { section: section("first"), collapsed: true }, + Mutation::Close { instance: id("one") }, + ])) + .unwrap(); + assert!(service.layout().sections.is_empty()); + service + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: None }])) + .unwrap(); + let restored = service.layout().section(§ion("first")).unwrap(); + assert_eq!(restored.size, size(350.0, 300.0)); + assert!(restored.collapsed); + service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + assert!(!service.layout().section(§ion("first")).unwrap().collapsed); +} + +#[test] +fn peek_never_rewrites_saved_collapse_or_sizes_and_focus_restores_content() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: true }])).unwrap(); + let layout = service.layout().clone(); + service.dispatch(transaction(vec![Mutation::Peek { instance: id("one") }])).unwrap(); + assert_eq!(*service.layout(), layout); + assert_eq!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.len(), 1); + service.dispatch(transaction(vec![Mutation::DismissPeek])).unwrap(); + assert!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.is_empty()); + service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + assert!(service.interaction().focused.is_none()); +} + +#[test] +fn overflow_is_transient_and_never_squeezes_or_rewrites_desired_dimensions() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let before = service.inspect(); + let small = resolve_geometry(&service, rect(80.0, 80.0), Direction::Ltr, 48.0).unwrap(); + assert!(small.panels.is_empty()); + assert_eq!(small.unpresented.first().unwrap().reason, UnpresentedReason::MinimumOverflow); + let large = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); + assert_eq!(large.panels.first().unwrap().outer.size, size(280.0, 240.0)); + assert_eq!(service.inspect(), before); +} + +#[test] +fn logical_rtl_flow_hysteresis_and_size_classes_use_usable_units() { + assert_eq!(Direction::Rtl.edge(Zone::Left).unwrap(), PhysicalEdge::Right); + for (width, expected) in [(239.0, SizeClass::Compact), (240.0, SizeClass::Regular), (480.0, SizeClass::Regular), (481.0, SizeClass::Wide)] { + assert_eq!(responsive(Zone::Floating, size(width, 600.0), None).unwrap().1, expected); + } + assert_eq!(responsive(Zone::Floating, size(105.0, 100.0), Some(Flow::Tall)).unwrap().0, Flow::Tall); + assert_eq!(responsive(Zone::Window, size(95.0, 100.0), Some(Flow::Wide)).unwrap().0, Flow::Wide); + assert_eq!(responsive(Zone::Window, size(89.0, 100.0), Some(Flow::Wide)).unwrap().0, Flow::Tall); + assert_eq!(responsive(Zone::Bottom, size(100.0, 400.0), None).unwrap().0, Flow::Wide); +} + +#[test] +fn pointer_regions_cannot_intercept_unpainted_viewport_space() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let mut panel = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.remove(0); + assert!(panel.consumes_pointer(Point { x: 20.0, y: 20.0 })); + assert!(!panel.consumes_pointer(Point { x: 500.0, y: 500.0 })); + panel.input.first_mut().unwrap().bounds = rect(1000.0, 800.0); + assert_eq!(panel.validate().unwrap_err().rule, Rule::Bounds); +} + +#[test] +fn native_capabilities_and_close_redock_are_atomic() { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + let native = Destination::NewSection { + section: section("native"), + index: 0, + location: SectionLocation::Window { + host: HostId::new("native-host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { zone: Zone::Left, index: 0, size: size(280.0, 240.0), collapsed: false, join: None }, + }, + size: size(300.0, 250.0), + }; + let reply = service.dispatch(transaction(vec![Mutation::Move { instance: id("one"), destination: native.clone() }])).unwrap(); + assert!(reply.effects.iter().any(|e| matches!(e, HostEffect::CreateNative { .. }))); + let reply = service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap(); + assert_eq!(service.layout().containing(&id("one")).unwrap().location.zone(), Zone::Left); + assert!(reply.effects.iter().any(|e| matches!(e, HostEffect::ReleaseNative { .. }))); + let mut web = fixture_service(false).unwrap(); + open(&mut web, "one", "first"); + reject(&mut web, vec![Mutation::Move { instance: id("one"), destination: native }], Rule::Capability); +} + +#[test] +fn envelope_schema_roundtrip_and_version_fallback_preserve_original_input() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let envelope = LayoutEnvelope::new(service.layout().clone()); + let bytes = encode(&envelope, service.registry()).unwrap(); + assert_eq!(decode(&bytes, service.registry(), service.layout()).unwrap().envelope, envelope); + for schema in [layout_action_schema(), layout_reply_schema(), layout_envelope_schema()] { + assert!(serde_json::to_value(schema).unwrap().is_object()); + } + let mut future = envelope; + future.version += 1; + let raw = serde_json::to_vec(&future).unwrap(); + let loaded = decode(&raw, service.registry(), service.layout()).unwrap(); + assert_eq!(loaded.notice.unwrap().rule, Rule::Version); + assert_eq!(loaded.rejected.unwrap(), raw); + assert_eq!(loaded.envelope.layout, *service.layout()); + assert!(decode(b"broken", service.registry(), service.layout()).unwrap().notice.is_some()); +} + +#[test] +fn unknown_panels_are_quarantined_losslessly_and_reappear_when_registered() { + let mut known = fixture_service(false).unwrap(); + open(&mut known, "one", "first"); + let mut envelope = serde_json::to_value(LayoutEnvelope::new(known.layout().clone())).unwrap(); + envelope["layout"]["instances"][0]["kind"] = serde_json::json!("extension.panel"); + envelope["layout"]["instances"][0]["future_content"] = serde_json::json!({"keep":"conversation"}); + let bytes = serde_json::to_vec(&envelope).unwrap(); + let fallback = Layout::empty(known.layout().workspace.clone()); + let mut loaded = decode(&bytes, known.registry(), &fallback).unwrap().envelope; + assert!(loaded.layout.instances.is_empty()); + assert_eq!(loaded.quarantine.len(), 1); + assert_eq!(loaded.quarantine.first().unwrap().instance_data["future_content"]["keep"], "conversation"); + let mut registry = known.registry().clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + registry.register(spec).unwrap(); + restore_quarantine(&mut loaded, ®istry).unwrap(); + assert!(loaded.quarantine.is_empty()); + assert_eq!(loaded.layout.instances.len(), 1); + assert_eq!(loaded.retained_data[&id("one")]["instance"]["future_content"]["keep"], "conversation"); + validate(&loaded.layout, ®istry).unwrap(); +} + +#[test] +fn persistence_failure_preserves_unrelated_preferences_and_old_layout() { + let mut persistence = FakePersistence::default(); + let service = fixture_service(false).unwrap(); + persistence.unrelated_preferences.insert("theme".into(), "raw authored intent".into()); + let bytes = encode(&LayoutEnvelope::new(service.layout().clone()), service.registry()).unwrap(); + persistence.save(&service.layout().workspace, &bytes).unwrap(); + persistence.fail_save = true; + assert!(persistence.save(&service.layout().workspace, b"replacement").is_err()); + assert_eq!(persistence.load(&service.layout().workspace).unwrap().unwrap(), bytes); + assert_eq!(persistence.unrelated_preferences.get("theme").unwrap(), "raw authored intent"); +} + +#[test] +fn collection_byte_and_depth_limits_reject_hostile_wire_values() { + let mut service = fixture_service(false).unwrap(); + reject(&mut service, Vec::new(), Rule::CollectionLimit); + reject(&mut service, vec![Mutation::DismissPeek; MAX_MUTATIONS + 1], Rule::CollectionLimit); + let oversized = vec![b' '; MAX_ENVELOPE_BYTES + 1]; + assert_eq!(decode_action(&oversized).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(decode(&oversized, service.registry(), service.layout()).unwrap().notice.unwrap().rule, Rule::CollectionLimit); + let mut nested = serde_json::Value::Null; + for _ in 0..34 { + nested = serde_json::json!([nested]); + } + assert_eq!(bounded_json(&nested).unwrap_err().rule, Rule::CollectionLimit); + let mut layout = service.layout().clone(); + open(&mut service, "one", "first"); + layout.instances = vec![service.layout().instances.first().unwrap().clone(); MAX_INSTANCES + 1]; + assert_eq!(validate(&layout, service.registry()).unwrap_err().rule, Rule::CollectionLimit); + layout = service.layout().clone(); + layout.sections = vec![layout.sections.first().unwrap().clone(); MAX_SECTIONS + 1]; + assert_eq!(validate(&layout, service.registry()).unwrap_err().rule, Rule::CollectionLimit); + layout = service.layout().clone(); + layout.sections.first_mut().unwrap().tabs = vec![id("one"); MAX_TABS + 1]; + assert_eq!(validate(&layout, service.registry()).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn deterministic_hostile_action_sequences_preserve_all_invariants() { + let mut service = fixture_service(true).unwrap(); + let mut state = 0x3141_5926_u64; + for step in 0..1024 { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1); + let target = id(&format!("instance-{}", state % 8)); + let group = section(&format!("section-{}", (state >> 8) % 8)); + let mutation = match (state >> 16) % 8 { + 0 => fixture_open("fixture.log", &target.0, &group.0, Zone::Left, 0).unwrap(), + 1 => Mutation::Close { instance: target }, + 2 => Mutation::Focus { instance: target }, + 3 => Mutation::SetSize { section: group, size: size(if step % 2 == 0 { f32::NAN } else { 280.0 }, 240.0) }, + 4 => Mutation::Collapse { section: group, collapsed: state.is_multiple_of(2) }, + 5 => Mutation::Move { instance: target, destination: Destination::JoinTab { section: group, index: (state % 40) as usize } }, + 6 => Mutation::Peek { instance: target }, + _ => Mutation::Destroy { instance: target }, + }; + let before = service.inspect(); + if service.dispatch(transaction(vec![mutation])).is_err() { + assert_eq!(service.inspect(), before); + } + validate(service.layout(), service.registry()).unwrap(); + } +} + +#[test] +fn layout_work_never_touches_document_dirty_revision_undo_geometry_or_tessellation() { + let mut session = crate::Session::default(); + session.execute("solid.box", &serde_json::json!({"length":10,"width":10,"height":10})).unwrap(); + session.mark_saved(); + let document = session.doc.clone(); + let model_state = session.model.state(); + let meshes: Vec<_> = model_state.bodies.iter().map(|b| b.cached_mesh()).collect(); + let revision = session.revision; + let undo = session.undo.len(); + let recomputed = session.model.recomputed; + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + for width in [280.0, 350.0, 500.0] { + service.dispatch(transaction(vec![Mutation::SetSize { section: section("first"), size: size(width, 240.0) }])).unwrap(); + resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); + } + assert!(!session.is_dirty()); + assert_eq!(session.revision, revision); + assert_eq!(session.undo.len(), undo); + assert_eq!(session.model.recomputed, recomputed); + assert!(std::sync::Arc::ptr_eq(&document, &session.doc)); + assert!(std::sync::Arc::ptr_eq(&model_state, &session.model.state())); + for (before, after) in meshes.iter().zip(session.model.state().bodies.iter().map(|b| b.cached_mesh())) { + match (before, after) { + (Some(a), Some(b)) => assert!(std::sync::Arc::ptr_eq(a, &b)), + (None, None) => {} + _ => panic!("layout touched tessellation cache"), + } + } +} + +#[test] +fn surface_precedence_and_truthful_contrast_fallback_have_wire_contracts() { + let registry = synthetic_registry().unwrap(); + let mut spec = registry.specs().next().unwrap().clone(); + assert_eq!(group_surface(Zone::Bottom, [&spec]), PanelSurface::Opaque); + spec.surface = PanelSurface::Translucent; + assert_eq!(group_surface(Zone::Bottom, [&spec]), PanelSurface::Translucent); + let mut opaque = spec.clone(); + opaque.surface = PanelSurface::Opaque; + assert_eq!(group_surface(Zone::Left, [&spec, &opaque]), PanelSurface::Opaque); + let outcome = ContrastOutcome::RetainReadableFallback { reason: ContrastFailure::UnreadableAtFullOpacity }; + let roundtrip: ContrastOutcome = serde_json::from_value(serde_json::to_value(&outcome).unwrap()).unwrap(); + assert_eq!(roundtrip, outcome); + assert!(ContrastOutcome::Readable { effective_background_alpha: 0.2 }.validate(0.3).is_err()); + assert!(ContrastOutcome::Readable { effective_background_alpha: f32::NAN }.validate(0.3).is_err()); + assert!(ContrastOutcome::Readable { effective_background_alpha: 0.8 }.validate(0.3).is_ok()); +} + +#[test] +fn versioned_fixture_and_action_schema_are_consumable_without_a_ui() { + let service = fixture_service(false).unwrap(); + let loaded = decode(FIXTURE_LAYOUT_V1, service.registry(), service.layout()).unwrap(); + assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.layout.instances.len(), 1); + let mut live = LayoutService::new(service.registry().clone(), loaded.envelope.layout, HostCapabilities::default()).unwrap(); + let action = decode_action(br#"{"type":"apply","expected_revision":0,"mutations":[{"type":"focus","instance":"editor"}]}"#).unwrap(); + let sink: &mut dyn ActionSink = &mut live; + assert_eq!(sink.dispatch(action).unwrap().interaction.focused, Some(id("editor"))); + assert_eq!(serde_json::to_value(CompatibilityPreset::Classic).unwrap(), "classic"); +} + +#[test] +fn instance_section_registry_and_tab_limits_allow_the_boundary_then_reject() { + let mut service = fixture_service(false).unwrap(); + for index in 0..MAX_TABS { + let mutation = if index == 0 { + fixture_open("fixture.log", "log-0", "logs", Zone::Left, 0).unwrap() + } else { + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(&format!("log-{index}")), + destination: Some(Destination::JoinTab { section: section("logs"), index }), + } + }; + service.dispatch(transaction(vec![mutation])).unwrap(); + } + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("excess"), + destination: Some(Destination::JoinTab { section: section("logs"), index: MAX_TABS }), + }], + Rule::CollectionLimit, + ); + let base = synthetic_registry().unwrap().specs().next().unwrap().clone(); + let mut registry = PanelRegistry::default(); + for i in 0..MAX_INSTANCES { + let mut spec = base.clone(); + spec.kind = PanelKind::new(format!("panel-{i}")).unwrap(); + registry.register(spec).unwrap(); + } + let mut excess = base; + excess.kind = PanelKind::new("excess").unwrap(); + assert_eq!(registry.register(excess).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn feature_constraints_and_height_bounds_are_enforced_for_every_member() { + let mut spec = synthetic_registry().unwrap().get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.features.closable = false; + spec.features.collapsible = false; + spec.features.tabbable = false; + spec.features.popout = false; + let mut registry = PanelRegistry::default(); + registry.register(spec).unwrap(); + let mut service = LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture").unwrap()), HostCapabilities::default()).unwrap(); + open(&mut service, "one", "first"); + reject(&mut service, vec![Mutation::Close { instance: id("one") }], Rule::FeatureDisabled); + reject(&mut service, vec![Mutation::Collapse { section: section("first"), collapsed: true }], Rule::FeatureDisabled); + reject(&mut service, vec![Mutation::SetSize { section: section("first"), size: size(280.0, 119.0) }], Rule::Bounds); + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }], + Rule::FeatureDisabled, + ); +} + +#[test] +fn prepared_candidates_cannot_commit_to_a_different_live_service() { + let mut first = fixture_service(false).unwrap(); + let mut other = fixture_service(false).unwrap(); + let candidate = first.prepare(transaction(vec![fixture_open("fixture.log", "one", "first", Zone::Left, 0).unwrap()])).unwrap(); + let before = other.inspect(); + assert_eq!(other.commit(candidate).unwrap_err().rule, Rule::Revision); + assert_eq!(other.inspect(), before); + open(&mut first, "one", "first"); +} + +#[test] +fn native_close_returns_to_a_stable_tab_group_without_stealing_activation() { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }])) + .unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("two"), + destination: Destination::NewSection { + section: section("native"), + index: 1, + location: SectionLocation::Window { + host: HostId::new("native-host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: Some(ReturnTab { section: section("first"), index: 1 }), + }, + }, + size: size(280.0, 240.0), + }, + }])) + .unwrap(); + service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap(); + let group = service.layout().section(§ion("first")).unwrap(); + assert_eq!(group.tabs, vec![id("one"), id("two")]); + assert_eq!(group.active, id("one")); + assert_eq!(service.layout().sections.len(), 1); +} + +#[test] +fn activation_preserves_collapse_and_does_not_request_focus_or_reopen() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: true }])).unwrap(); + let reply = service.dispatch(transaction(vec![Mutation::Activate { instance: id("one") }])).unwrap(); + assert!(reply.effects.is_empty()); + assert!(reply.interaction.focused.is_none()); + assert!(reply.layout.sections.first().unwrap().collapsed); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + reject(&mut service, vec![Mutation::Activate { instance: id("one") }], Rule::MissingTarget); + service.set_availability([(id("future"), Availability::Unavailable { reason: "context missing".into() })].into()).unwrap(); + reject(&mut service, vec![fixture_open("fixture.log", "future", "future-section", Zone::Left, 0).unwrap()], Rule::Availability); +} + +#[test] +fn complete_layout_application_keeps_one_revision_and_validates_workspace_identities() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let saved = service.layout().clone(); + let revision = service.inspect().revision; + let away = Layout::empty(WorkspaceId::new("other-workspace").unwrap()); + let reply = service.dispatch(LayoutAction::Replace { expected_revision: Some(revision), layout: away.clone() }).unwrap(); + assert_eq!(reply.layout, away); + assert_eq!(reply.revision, revision + 1); + let before = service.inspect(); + assert_eq!( + service.dispatch(LayoutAction::Replace { expected_revision: Some(revision), layout: saved.clone() }).unwrap_err().rule, + Rule::Revision + ); + assert_eq!(service.inspect(), before); + let mut changed_kind = saved.clone(); + changed_kind.instances.first_mut().unwrap().kind = PanelKind::new("fixture.editor").unwrap(); + assert_eq!(service.dispatch(LayoutAction::Replace { expected_revision: None, layout: changed_kind }).unwrap_err().rule, Rule::DuplicateId); + let mut unknown = saved.clone(); + unknown.instances.first_mut().unwrap().kind = PanelKind::new("not.registered").unwrap(); + assert_eq!(service.dispatch(LayoutAction::Replace { expected_revision: None, layout: unknown }).unwrap_err().rule, Rule::MissingTarget); + assert_eq!(service.inspect(), before); + service.dispatch(LayoutAction::Replace { expected_revision: Some(before.revision), layout: saved.clone() }).unwrap(); + assert_eq!(service.layout(), &saved); +} + +#[test] +fn lifecycle_intents_are_rejected_before_intermediate_mutations() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let reopen = Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: None }; + for batch in [ + vec![Mutation::Close { instance: id("one") }, reopen.clone()], + vec![ + Mutation::Close { instance: id("one") }, + Mutation::Move { instance: id("one"), destination: Destination::JoinTab { section: section("second"), index: 0 } }, + reopen.clone(), + ], + vec![Mutation::Destroy { instance: id("one") }, reopen], + ] { + reject(&mut service, batch, Rule::Lifecycle); + } + service + .dispatch(transaction(vec![ + Mutation::Close { instance: id("one") }, + Mutation::SetSize { section: section("second"), size: size(300.0, 260.0) }, + ])) + .unwrap(); + assert!(!service.layout().instance(&id("one")).unwrap().requested_open); + assert_eq!(service.layout().section(§ion("second")).unwrap().size, size(300.0, 260.0)); +} + +fn future_group() -> serde_json::Value { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "a", "group"); + for (index, name) in [(1, "b"), (2, "c")] { + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(name), + destination: Some(Destination::JoinTab { section: section("group"), index }), + }])) + .unwrap(); + } + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + for instance in raw["layout"]["instances"].as_array_mut().unwrap() { + let name = instance["id"].as_str().unwrap().to_owned(); + instance["kind"] = serde_json::json!(format!("extension.{name}")); + instance["future_draft"] = serde_json::json!(format!("draft-{name}")); + } + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["c", "b", "a"]); + raw["layout"]["sections"][0]["active"] = serde_json::json!("c"); + raw +} + +fn future_registry(names: &[&str]) -> PanelRegistry { + let mut registry = synthetic_registry().unwrap(); + let base = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + for name in names { + let mut spec = base.clone(); + spec.kind = PanelKind::new(format!("extension.{name}")).unwrap(); + registry.register(spec).unwrap(); + } + registry +} + +#[test] +fn shared_future_metadata_successfully_decodes_and_reencodes_without_duplication() { + let registry = future_registry(&["a"]); + let fallback = fixture_service(false).unwrap().layout().clone(); + let mut raw = future_group(); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!(vec![serde_json::Value::Null; 5000]); + let bytes = serde_json::to_vec(&raw).unwrap(); + bounded_json(&raw).unwrap(); + let loaded = decode(&bytes, ®istry, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.quarantine.len(), 2); + assert_eq!(loaded.envelope.section_snapshots.len(), 1); + let encoded = encode(&loaded.envelope, ®istry).unwrap(); + let reopened = decode(&encoded, ®istry, &fallback).unwrap(); + assert!(reopened.notice.is_none()); + assert_eq!(reopened.envelope, loaded.envelope); + assert_eq!(reopened.envelope.section_snapshots[§ion("group")].data["future_metadata"].as_array().unwrap().len(), 5000); +} + +#[test] +fn all_unknown_tabs_restore_original_order_and_activation_across_registry_stages() { + let fallback = fixture_service(false).unwrap().layout().clone(); + let raw = future_group(); + let bytes = serde_json::to_vec(&raw).unwrap(); + let mut envelope = decode(&bytes, &future_registry(&[]), &fallback).unwrap().envelope; + assert!(envelope.layout.sections.is_empty()); + restore_quarantine(&mut envelope, &future_registry(&["a"])).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("a")]); + restore_quarantine(&mut envelope, &future_registry(&["a", "b"])).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("b"), id("a")]); + restore_quarantine(&mut envelope, &future_registry(&["a", "b", "c"])).unwrap(); + let group = envelope.layout.sections.first().unwrap(); + assert_eq!(group.tabs, vec![id("c"), id("b"), id("a")]); + assert_eq!(group.active, id("c")); + assert!(envelope.quarantine.is_empty()); + for name in ["a", "b", "c"] { + assert_eq!(envelope.retained_data[&id(name)]["instance"]["future_draft"], format!("draft-{name}")); + } + assert_eq!(envelope.section_snapshots[§ion("group")].data["active"], "c"); + encode(&envelope, &future_registry(&["a", "b", "c"])).unwrap(); +} + +#[test] +fn mixed_tab_reappearance_retains_unavailable_or_invalid_entries_and_future_fields() { + let fallback = fixture_service(false).unwrap().layout().clone(); + let raw = future_group(); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &future_registry(&["a"]), &fallback).unwrap().envelope; + let mut registry = future_registry(&["a", "b"]); + let mut narrow = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + narrow.kind = PanelKind::new("extension.c").unwrap(); + narrow.default_size.width = 200.0; + narrow.max_size.width = 200.0; + registry.register(narrow).unwrap(); + let unavailable = [(id("b"), Availability::Unavailable { reason: "extension unavailable".into() })].into(); + restore_quarantine_with_availability(&mut envelope, ®istry, &unavailable).unwrap(); + assert_eq!(envelope.quarantine.len(), 2); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); + restore_quarantine(&mut envelope, &future_registry(&["a", "b", "c"])).unwrap(); + let group = envelope.layout.sections.first().unwrap(); + assert_eq!(group.tabs, vec![id("c"), id("b"), id("a")]); + assert_eq!(group.active, id("c")); + assert_eq!(envelope.retained_data[&id("b")]["instance"]["future_draft"], "draft-b"); +} + +#[test] +fn lossless_representation_over_budget_returns_recovery_instead_of_decode_success() { + let registry = future_registry(&[]); + let fallback = fixture_service(false).unwrap().layout().clone(); + let mut raw = future_group(); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!(""); + let base = serde_json::to_vec(&raw).unwrap().len(); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!("x".repeat(MAX_ENVELOPE_BYTES - base)); + let bytes = serde_json::to_vec(&raw).unwrap(); + assert_eq!(bytes.len(), MAX_ENVELOPE_BYTES); + let loaded = decode(&bytes, ®istry, &fallback).unwrap(); + assert_eq!(loaded.notice.unwrap().rule, Rule::CollectionLimit); + assert_eq!(loaded.rejected.unwrap(), bytes); + assert_eq!(loaded.envelope.layout, fallback); +} + +#[test] +fn restored_metadata_survives_unregister_register_and_known_survivor_activation() { + let fallback = fixture_service(false).unwrap().layout().clone(); + let raw = future_group(); + let all = future_registry(&["a", "b", "c"]); + let only_a = future_registry(&["a"]); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &only_a, &fallback).unwrap().envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + let bytes = encode(&envelope, &all).unwrap(); + let mut again = decode(&bytes, &only_a, &fallback).unwrap().envelope; + assert_eq!(again.quarantine.len(), 2); + restore_quarantine(&mut again, &all).unwrap(); + assert_eq!(again.layout.sections.first().unwrap().active, id("c")); + assert_eq!(again.retained_data[&id("c")]["instance"]["future_draft"], "draft-c"); + // A surviving known active tab is not displaced while some unrelated member + // reappears. The saved active member only reactivates when it itself returns. + let a_c = future_registry(&["a", "c"]); + let mut mixed = decode(&serde_json::to_vec(&raw).unwrap(), &a_c, &fallback).unwrap().envelope; + mixed.layout.sections.first_mut().unwrap().active = id("a"); + restore_quarantine(&mut mixed, &all).unwrap(); + assert_eq!(mixed.layout.sections.first().unwrap().active, id("a")); + assert_eq!(mixed.layout.sections.first().unwrap().tabs, vec![id("c"), id("b"), id("a")]); +} + +#[test] +fn complete_layout_wire_contract_checks_native_capacity_and_destroyed_identity_reuse() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let snapshot = service.layout().clone(); + let action = LayoutAction::Replace { expected_revision: Some(service.inspect().revision), layout: snapshot.clone() }; + let wire = serde_json::to_vec(&action).unwrap(); + assert_eq!(decode_action(&wire).unwrap(), action); + let mut native = snapshot.clone(); + native.sections.first_mut().unwrap().location = SectionLocation::Window { + host: HostId::new("native").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { zone: Zone::Left, index: 0, size: size(280.0, 240.0), collapsed: false, join: None }, + }; + let before = service.inspect(); + assert_eq!(service.dispatch(LayoutAction::Replace { expected_revision: None, layout: native }).unwrap_err().rule, Rule::Capability); + assert_eq!(service.inspect(), before); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + service.dispatch(transaction(vec![Mutation::Destroy { instance: id("one") }])).unwrap(); + let mut reused = snapshot; + reused.instances.first_mut().unwrap().kind = PanelKind::new("fixture.editor").unwrap(); + service.dispatch(LayoutAction::Replace { expected_revision: None, layout: reused }).unwrap(); + assert_eq!(service.layout().instance(&id("one")).unwrap().kind, PanelKind::new("fixture.editor").unwrap()); +} + +fn future_sections() -> serde_json::Value { + let mut service = fixture_service(false).unwrap(); + for (member, group) in [("a", "s0"), ("b", "s1"), ("c", "s2")] { + open(&mut service, member, group); + } + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + let instances = raw["layout"]["instances"].as_array_mut().unwrap(); + for instance in instances.iter_mut() { + let name = instance["id"].as_str().unwrap().to_owned(); + instance["kind"] = serde_json::json!(format!("extension.{name}")); + instance["future_draft"] = serde_json::json!(format!("draft-{name}")); + } + instances.reverse(); // Exact regression: member processing order s2, s1, s0. + for group in raw["layout"]["sections"].as_array_mut().unwrap() { + let name = group["id"].as_str().unwrap().to_owned(); + group["future_surface"] = serde_json::json!({"keep":name}); + } + raw +} + +fn section_ids(envelope: &LayoutEnvelope) -> Vec { + envelope.layout.sections.iter().map(|section| section.id.clone()).collect() +} + +fn persistence_fallback() -> Layout { + fixture_service(false).unwrap().layout().clone() +} + +#[test] +fn whole_section_order_restores_from_reverse_instance_order_in_one_or_many_stages() { + let fallback = persistence_fallback(); + let raw = future_sections(); + let bytes = serde_json::to_vec(&raw).unwrap(); + let all = future_registry(&["a", "b", "c"]); + let loaded = decode(&bytes, &future_registry(&[]), &fallback).unwrap(); + assert!(loaded.notice.is_none()); + let original = loaded.envelope; + assert!(original.layout.sections.is_empty()); + assert_eq!(original.section_order, vec![section("s0"), section("s1"), section("s2")]); + let mut together = original.clone(); + restore_quarantine(&mut together, &all).unwrap(); + assert_eq!(section_ids(&together), vec![section("s0"), section("s1"), section("s2")]); + let mut staged = original; + for (registry, expected) in [ + (future_registry(&["c"]), vec![section("s2")]), + (future_registry(&["b", "c"]), vec![section("s1"), section("s2")]), + (all, vec![section("s0"), section("s1"), section("s2")]), + ] { + restore_quarantine(&mut staged, ®istry).unwrap(); + assert_eq!(section_ids(&staged), expected); + let saved = encode(&staged, ®istry).unwrap(); + let reopened = decode(&saved, ®istry, &fallback).unwrap(); + assert!(reopened.notice.is_none()); + staged = reopened.envelope; + } + assert!(staged.quarantine.is_empty()); + for (index, name) in ["s0", "s1", "s2"].into_iter().enumerate() { + let snapshot = &staged.section_snapshots[§ion(name)]; + assert_eq!(snapshot.index, index); + assert_eq!(snapshot.data["future_surface"]["keep"], name); + } +} + +fn command_destination(group: &str, index: usize, zone: &str) -> serde_json::Value { + serde_json::json!({"type":"new_section","section":group,"index":index,"location":{"type":"dock","zone":zone},"size":{"width":280,"height":240}}) +} +fn command_target(instance: &str) -> serde_json::Value { + serde_json::json!({"type":"instance","id":instance}) +} +fn command_ready_backend() -> commands::InMemoryPanelBackend { + let mut backend = fixture_command_backend().unwrap(); + backend + .execute("panel.open", &serde_json::json!({"kind":"fixture.log","instance":"one","destination":command_destination("s-one",0,"left")})) + .unwrap(); + backend + .execute("panel.open", &serde_json::json!({"kind":"fixture.log","instance":"two","destination":command_destination("s-two",1,"left")})) + .unwrap(); + backend +} +fn command_inputs() -> Vec<(&'static str, serde_json::Value)> { + use serde_json::json; + let selected = json!({"target":command_target("one")}); + let mut floating = command_destination("free", 1, "left"); + floating["location"] = json!({"type":"floating","origin":{"x":20,"y":30}}); + let mut native = floating.clone(); + native["location"] = json!({"type":"window","host":"native","origin":{"x":20,"y":30},"return_to":{"zone":"left","index":0,"size":{"width":280,"height":240},"collapsed":false}}); + vec![ + ("layout.apply", json!({"name":"Fixture default"})), + ("layout.get", json!({})), + ("layout.reset", json!({})), + ("layout.save", json!({"name":"Saved"})), + ("layout.workspace.select", json!({"workspace":"fixture.other"})), + ("panel.activate", selected.clone()), + ("panel.close", selected.clone()), + ("panel.collapse", json!({"target":command_target("one"),"collapsed":true})), + ("panel.dismiss", json!({})), + ("panel.float", json!({"target":command_target("one"),"destination":floating})), + ("panel.focus", selected.clone()), + ("panel.list", json!({})), + ("panel.move", json!({"target":command_target("one"),"destination":command_destination("moved",1,"right")})), + ("panel.native_close", json!({"target":{"type":"native_host","id":"native"}})), + ( + "panel.open", + json!({"kind":"fixture.application","instance":"application","destination":command_destination("application-section",2,"right")}), + ), + ("panel.peek", selected), + ("panel.popout", json!({"target":command_target("one"),"destination":native})), + ("panel.reset_pair", json!({"first":"s-one","second":"s-two"})), + ("panel.resize", json!({"target":command_target("one"),"size":{"width":300,"height":300}})), + ( + "panel.resize_pair", + json!({"first":"s-one","second":"s-two","first_size":{"width":280,"height":260},"second_size":{"width":280,"height":220}}), + ), + ] +} + +#[test] +fn every_panel_command_has_strict_input_output_contracts_and_hostile_field_rejection() { + use commands::LayoutCatalogue; + let inputs = command_inputs(); + assert_eq!(inputs.len(), commands::IDS.len()); + for (id, input) in inputs { + let spec = crate::find_command(id).unwrap(); + assert!(!spec.undoable && !spec.reads_model, "{id}"); + let contract = spec.contract.unwrap(); + assert!(contract.check(&input).is_empty(), "{id}: {input}"); + assert_eq!(contract.input_schema().as_value()["additionalProperties"], false, "{id}"); + let output = (spec.output.unwrap())(); + assert!(output.as_value().is_object(), "{id}"); + assert_eq!(output.as_value()["additionalProperties"], false, "{id}"); + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + for junk in [serde_json::json!(false), serde_json::json!([]), serde_json::json!(["bad"]), serde_json::json!("bad"), { + let mut value = input.clone(); + value["unknown"] = serde_json::json!(true); + value + }] { + assert!(!contract.check(&junk).is_empty(), "{id}: {junk}"); + assert_eq!(commands::parse_command(id, &junk).unwrap_err().rule, Rule::Schema, "{id}"); + assert!(backend.execute(id, &junk).is_err(), "{id}"); + assert_eq!(backend.service.inspect(), before, "{id}"); + assert_eq!(backend.catalogue.state(), &catalogue, "{id}"); + } + for field in ["id", "instance", "kind", "first", "second", "workspace"] { + if input.get(field).is_some() { + let mut hostile = input.clone(); + hostile[field] = serde_json::json!("UPPER/invalid"); + assert!(commands::parse_command(id, &hostile).is_err(), "{id}/{field}"); + } + } + let mut oversized = input.clone(); + oversized["unknown"] = serde_json::json!("x".repeat(commands::MAX_COMMAND_BYTES + 1)); + assert_eq!(commands::parse_command(id, &oversized).unwrap_err().rule, Rule::CollectionLimit, "{id}"); + } +} + +#[test] +fn panel_command_success_replies_describe_committed_state_for_every_executable_operation() { + for (id, input) in command_inputs() { + let mut backend = command_ready_backend(); + if id == "panel.peek" { + backend.execute("panel.collapse", &serde_json::json!({"target":command_target("one"),"collapsed":true})).unwrap(); + } + let result = backend.execute(id, &input); + if matches!(id, "panel.popout" | "panel.native_close") { + assert!(result.is_err(), "{id}"); + continue; + } + let result = result.unwrap_or_else(|e| panic!("{id}: {e}")); + let reply: LayoutReply = serde_json::from_value(result.get("state").unwrap_or(&result).clone()).unwrap(); + let live = backend.service.inspect(); + assert_eq!(reply.layout, live.layout, "{id}"); + assert_eq!(reply.revision, live.revision, "{id}"); + assert_eq!(reply.interaction, live.interaction, "{id}"); + assert_eq!(reply.capabilities, live.capabilities, "{id}"); + assert_eq!(reply.availability, live.availability, "{id}"); + } +} + +#[test] +fn panel_commands_reject_nested_unknowns_sizes_indices_and_nonfinite_values_before_effects() { + let mut backend = command_ready_backend(); + for value in [ + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(32769), + serde_json::json!(1e100), + serde_json::Value::Null, + serde_json::json!("NaN"), + ] { + let before = backend.service.inspect(); + assert!(backend.execute("panel.resize", &serde_json::json!({"target":command_target("one"),"size":{"width":value,"height":240}})).is_err()); + assert_eq!(backend.service.inspect(), before); + } + for path in ["target", "destination", "location", "size"] { + let mut input = serde_json::json!({"target":command_target("one"),"destination":command_destination("moved",0,"right")}); + match path { + "target" => input["target"]["unknown"] = true.into(), + "destination" => input["destination"]["unknown"] = true.into(), + "location" => input["destination"]["location"]["unknown"] = true.into(), + _ => input["destination"]["size"]["unknown"] = true.into(), + } + assert_eq!(commands::parse_command("panel.move", &input).unwrap_err().rule, Rule::Schema, "{path}"); + } + for index in [serde_json::json!(-1), serde_json::json!(65), serde_json::json!(1e100)] { + let mut dest = command_destination("moved", 0, "left"); + dest["index"] = index; + assert!(commands::parse_command("panel.move", &serde_json::json!({"target":command_target("one"),"destination":dest})).is_err()); + } + for hostile in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mutation = Mutation::SetSize { section: section("s-one"), size: size(hostile, 240.0) }; + assert!(backend.service.project(transaction(vec![mutation])).is_err()); + } +} + +#[test] +fn command_target_resolution_never_guesses_a_multi_instance_or_mismatched_target() { + let mut backend = command_ready_backend(); + assert_eq!(backend.execute("panel.focus", &serde_json::json!({"id":"fixture.log"})).unwrap_err().rule, Rule::ExactlyOnce); + backend.execute("panel.focus", &serde_json::json!({"id":"one"})).unwrap(); + backend + .execute( + "panel.open", + &serde_json::json!({"kind":"fixture.application","instance":"app","destination":command_destination("app-section",2,"right")}), + ) + .unwrap(); + backend.execute("panel.focus", &serde_json::json!({"id":"fixture.application"})).unwrap(); + for target in [serde_json::json!({"type":"workspace","id":"fixture.workspace"}), serde_json::json!({"type":"section","id":"s-one"})] { + assert_eq!(backend.execute("panel.focus", &serde_json::json!({"target":target})).unwrap_err().rule, Rule::Schema); + } + assert!(backend.execute("panel.focus", &serde_json::json!({"target":command_target("one"),"id":"one"})).is_err()); + backend.execute("panel.close", &serde_json::json!({"target":command_target("one")})).unwrap(); + assert_eq!(backend.execute("panel.activate", &serde_json::json!({"target":command_target("one")})).unwrap_err().rule, Rule::MissingTarget); + backend.execute("panel.focus", &serde_json::json!({"target":command_target("one")})).unwrap(); + backend.service.set_availability([(id("one"), Availability::Unavailable { reason: "fixture unavailable".into() })].into()).unwrap(); + for command in ["panel.focus", "panel.activate", "panel.peek"] { + assert_eq!(backend.execute(command, &serde_json::json!({"target":command_target("one")})).unwrap_err().rule, Rule::Availability); + } +} + +#[test] +fn command_storage_native_stale_and_lifecycle_failures_preserve_layout_and_catalogue() { + use commands::LayoutCatalogue; + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + backend.catalogue.fail_stage = true; + assert_eq!(backend.execute("panel.close", &serde_json::json!({"target":command_target("one")})).unwrap_err().rule, Rule::Capability); + backend.catalogue.fail_stage = false; + assert_eq!( + backend.execute("panel.close", &serde_json::json!({"target":command_target("one"),"expected_revision":0})).unwrap_err().rule, + Rule::Revision + ); + let native = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + assert_eq!(backend.execute("panel.popout", &native).unwrap_err().rule, Rule::Capability); + let steps = vec![ + serde_json::json!({"command":"panel.close","params":{"target":command_target("one")}}), + serde_json::json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"one"}}), + ]; + assert_eq!(backend.batch(&steps).unwrap_err().rule, Rule::Lifecycle); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + let invalid = vec![ + serde_json::json!({"command":"panel.collapse","params":{"target":command_target("one"),"collapsed":true}}), + serde_json::json!({"command":"panel.resize","params":{"target":command_target("two"),"size":{"width":1,"height":1}}}), + ]; + assert!(backend.batch(&invalid).is_err()); + assert_eq!(backend.service.inspect(), before); +} + +#[test] +fn command_presets_enforce_unicode_names_overwrite_builtins_and_user_count() { + let mut backend = fixture_command_backend().unwrap(); + for invalid in ["".into(), " ".into(), "x\n".into(), "x\u{0000}".into(), "🦀".repeat(65), " ".repeat(1025)] { + assert!(backend.execute("layout.save", &serde_json::json!({"name":invalid})).is_err()); + } + let name = "🦀".repeat(64); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":format!(" {name} ")})).unwrap()["name"], name); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":name})).unwrap_err().rule, Rule::DuplicateId); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":name,"overwrite":true})).unwrap()["overwritten"], true); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":"Fixture default","overwrite":true})).unwrap_err().rule, Rule::Capability); + for i in 1..commands::MAX_USER_PRESETS { + backend.execute("layout.save", &serde_json::json!({"name":format!("user-{i}")})).unwrap(); + } + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":"overflow"})).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn command_apply_reset_and_workspace_roundtrip_never_select_implicitly() { + use serde_json::json; + let mut backend = command_ready_backend(); + let a = backend.service.layout().clone(); + backend.execute("layout.save", &json!({"name":"Saved"})).unwrap(); + backend.execute("layout.reset", &json!({})).unwrap(); + assert_eq!(backend.service.layout().workspace, a.workspace); + assert!(backend.service.layout().instances.is_empty()); + backend.execute("layout.apply", &json!({"name":"Saved"})).unwrap(); + assert_eq!(backend.service.layout(), &a); + let selected = backend.execute("layout.workspace.select", &json!({"workspace":"fixture.other"})).unwrap(); + assert_eq!(selected["source"], "default_preset"); + backend.execute("layout.apply", &json!({"name":"Saved"})).unwrap(); + assert_eq!(backend.service.layout().workspace.0, "fixture.other"); + backend.execute("panel.collapse", &json!({"target":command_target("one"),"collapsed":true})).unwrap(); + let b = backend.service.layout().clone(); + assert_eq!(backend.execute("layout.workspace.select", &json!({"workspace":"fixture.workspace"})).unwrap()["source"], "remembered"); + assert_eq!(backend.service.layout(), &a); + backend.execute("layout.workspace.select", &json!({"workspace":"fixture.other"})).unwrap(); + assert_eq!(backend.service.layout(), &b); + backend.execute("panel.peek", &json!({"target":command_target("one")})).unwrap(); + let before = backend.service.inspect(); + backend.catalogue.fail_stage = true; + assert_eq!(backend.execute("layout.workspace.select", &json!({"workspace":"fixture.other"})).unwrap()["source"], "unchanged"); + assert_eq!(backend.service.inspect(), before, "same workspace preserves revision/focus/peek even when storage is unavailable"); + backend.catalogue.fail_stage = false; + assert_eq!(backend.execute("layout.workspace.select", &json!({"workspace":"missing"})).unwrap_err().rule, Rule::MissingTarget); + let summaries = backend.execute("layout.get", &json!({})).unwrap(); + assert_eq!(summaries["workspaces"].as_array().unwrap().len(), 2); + backend.execute("layout.reset", &json!({})).unwrap(); + assert_eq!(backend.service.layout().workspace.0, "fixture.other"); + backend.execute("layout.apply", &json!({"name":"Saved"})).unwrap(); +} + +#[test] +fn command_save_apply_reset_preserve_full_unknown_envelopes_and_recovery() { + use commands::LayoutCatalogue; + let registry = synthetic_registry().unwrap(); + let fallback = persistence_fallback(); + let raw = future_sections(); + let envelope = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &fallback).unwrap().envelope; + let mut backend = fixture_command_backend().unwrap(); + backend.catalogue.remember(&envelope, Some(b"rejected future envelope"), ®istry).unwrap(); + backend.execute("layout.save", &serde_json::json!({"name":"Unknown"})).unwrap(); + backend.execute("layout.reset", &serde_json::json!({})).unwrap(); + backend.execute("layout.apply", &serde_json::json!({"name":"Unknown"})).unwrap(); + let stored = backend.catalogue.state().remembered(&fallback.workspace).unwrap(); + assert_eq!(stored.rejected(), Some(b"rejected future envelope".as_slice())); + let saved = stored.envelope(®istry, &fallback.workspace).unwrap(); + assert_eq!(saved.quarantine, envelope.quarantine); + assert_eq!(saved.section_order, envelope.section_order); + assert_eq!(saved.section_snapshots, envelope.section_snapshots); + let mut appeared = saved; + restore_quarantine(&mut appeared, &future_registry(&["a", "b", "c"])).unwrap(); + assert_eq!(section_ids(&appeared), vec![section("s0"), section("s1"), section("s2")]); + assert_eq!(appeared.retained_data[&id("a")]["instance"]["future_draft"], "draft-a"); +} + +#[test] +fn command_sidecar_collisions_and_aggregate_catalogue_growth_are_rejected_atomically() { + use commands::LayoutCatalogue; + let mut backend = fixture_command_backend().unwrap(); + let mut first = LayoutEnvelope::new(backend.service.layout().clone()); + first.retained_data.insert(id("future"), serde_json::json!({"draft":"first"})); + backend.catalogue.remember(&first, None, backend.service.registry()).unwrap(); + backend.execute("layout.save", &serde_json::json!({"name":"First"})).unwrap(); + let mut second = first.clone(); + second.retained_data.insert(id("future"), serde_json::json!({"draft":"second"})); + backend.catalogue.remember(&second, None, backend.service.registry()).unwrap(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + assert_eq!(backend.execute("layout.apply", &serde_json::json!({"name":"First"})).unwrap_err().rule, Rule::DuplicateId); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + let mut large = first; + large.retained_data.insert(id("large"), serde_json::json!({"opaque":"x".repeat(200_000)})); + backend.catalogue.remember(&large, None, backend.service.registry()).unwrap(); + let mut rejected = false; + for i in 0..commands::MAX_USER_PRESETS { + let before = backend.catalogue.state().clone(); + if let Err(reason) = backend.execute("layout.save", &serde_json::json!({"name":format!("large-{i}")})) { + assert_eq!(reason.rule, Rule::CollectionLimit); + assert_eq!(backend.catalogue.state(), &before); + rejected = true; + break; + } + } + assert!(rejected, "aggregate bytes reject before count cap"); +} + +#[test] +fn session_only_panel_commands_report_capability_without_touching_document_or_model() { + let mut session = crate::Session::default(); + let doc = session.doc.clone(); + let model = session.model.state(); + let revision = session.revision; + let dirty = session.is_dirty(); + let undo = session.undo.len(); + let evaluations = session.evaluations; + for level in crate::schema::ParamCheck::ALL { + session.param_check = level; + for (id, input) in command_inputs() { + let reason = session.execute(id, &input).unwrap_err(); + assert!(matches!(reason, crate::EngineError::Panel(PanelError { rule: Rule::Capability, .. })), "{id}: {reason}"); + assert!(commands::structured_error(&reason.to_string()).is_some()); + } + } + assert!(std::sync::Arc::ptr_eq(&doc, &session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &session.model.state())); + assert_eq!(session.revision, revision); + assert_eq!(session.undo.len(), undo); + assert_eq!(session.is_dirty(), dirty); + assert_eq!(session.evaluations, evaluations); +} + +#[test] +fn all_mutating_panel_commands_reject_stale_revisions_before_catalogue_publication() { + use commands::LayoutCatalogue; + for (id, mut input) in command_inputs() { + if matches!(id, "panel.list" | "layout.get") { + continue; + } + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + input["expected_revision"] = serde_json::json!(u64::MAX); + assert_eq!(backend.execute(id, &input).unwrap_err().rule, Rule::Revision, "{id}"); + assert_eq!(backend.service.inspect(), before, "{id}"); + assert_eq!(backend.catalogue.state(), &catalogue, "{id}"); + } +} + +#[test] +fn panel_command_pin_tab_intersections_and_paired_sashes_keep_foundation_rules() { + use serde_json::json; + let mut backend = command_ready_backend(); + backend + .execute("panel.open", &json!({"kind":"fixture.pin","instance":"pin","destination":command_destination("pin-section",0,"right")})) + .unwrap(); + let before = backend.service.inspect(); + assert_eq!( + backend + .execute("panel.open", &json!({"kind":"fixture.pin","instance":"pin-two","destination":command_destination("pin-two-section",1,"right")})) + .unwrap_err() + .rule, + Rule::PinConflict + ); + assert_eq!(backend.service.inspect(), before); + let bad_pair = json!({"first":"s-one","second":"s-two","first_size":{"width":281,"height":250},"second_size":{"width":280,"height":230}}); + assert_eq!(backend.execute("panel.resize_pair", &bad_pair).unwrap_err().rule, Rule::Bounds); + assert_eq!(backend.service.inspect(), before); + backend + .execute( + "panel.resize_pair", + &json!({"first":"s-one","second":"s-two","first_size":{"width":280,"height":260},"second_size":{"width":280,"height":220}}), + ) + .unwrap(); + let total: f32 = backend.service.layout().sections.iter().filter(|s| s.location.zone() == Zone::Left).map(|s| s.size.height).sum(); + assert_eq!(total, 480.0); + backend.execute("panel.reset_pair", &json!({"first":"s-one","second":"s-two"})).unwrap(); + assert_eq!(backend.service.layout().section(§ion("s-one")).unwrap().size.height, 240.0); + let mut registry = synthetic_registry().unwrap(); + let mut small = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + small.kind = PanelKind::new("fixture.small").unwrap(); + small.min_size = size(160.0, 120.0); + small.default_size = size(180.0, 140.0); + small.max_size = size(200.0, 180.0); + registry.register(small).unwrap(); + let mut large = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + large.kind = PanelKind::new("fixture.large").unwrap(); + large.min_size = size(400.0, 400.0); + large.default_size = size(450.0, 450.0); + large.max_size = size(500.0, 500.0); + registry.register(large).unwrap(); + let service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + let mut bounded = commands::InMemoryPanelBackend::new(service, fixture_command_catalogue(®istry).unwrap()); + bounded.execute("panel.open", &json!({"kind":"fixture.log","instance":"log","destination":command_destination("shared",0,"left")})).unwrap(); + let before = bounded.service.inspect(); + assert_eq!( + bounded + .execute("panel.open", &json!({"kind":"fixture.small","instance":"small","destination":{"type":"join_tab","section":"shared","index":1}})) + .unwrap_err() + .rule, + Rule::Bounds + ); + assert_eq!(bounded.service.inspect(), before); + bounded.execute("panel.resize", &json!({"target":command_target("log"),"size":{"width":180,"height":140}})).unwrap(); + bounded + .execute("panel.open", &json!({"kind":"fixture.small","instance":"small","destination":{"type":"join_tab","section":"shared","index":1}})) + .unwrap(); + let before = bounded.service.inspect(); + assert_eq!( + bounded + .execute("panel.open", &json!({"kind":"fixture.large","instance":"large","destination":{"type":"join_tab","section":"shared","index":2}})) + .unwrap_err() + .rule, + Rule::IncompatibleTabs + ); + assert_eq!(bounded.service.inspect(), before); +} + +#[test] +fn web_popout_explicitly_lowers_to_floating_while_desktop_requires_native_capability() { + let mut backend = command_ready_backend(); + let registry = backend.service.registry().clone(); + let input = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + let before = backend.service.inspect(); + assert_eq!(backend.execute("panel.popout", &input).unwrap_err().rule, Rule::Capability); + assert_eq!(backend.service.inspect(), before); + let result = commands::execute( + "panel.popout", + &input, + &mut commands::PanelCommandContext { sink: &mut backend.service, registry: ®istry, catalogue: &mut backend.catalogue, web: true }, + ) + .unwrap(); + assert_eq!(result["layout"]["sections"][1]["location"]["type"], "floating"); + assert!(result["effects"].as_array().unwrap().iter().all(|e| e["type"] != "create_native")); +} + +#[test] +fn catalogue_batch_stages_all_saves_and_replacements_once_and_rolls_back_failed_plans() { + use commands::LayoutCatalogue; + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let result = backend + .batch(&[ + serde_json::json!({"command":"layout.save","params":{"name":"Batch saved"}}), + serde_json::json!({"command":"layout.reset"}), + serde_json::json!({"command":"layout.apply","params":{"name":"Batch saved"}}), + serde_json::json!({"command":"layout.get"}), + ]) + .unwrap(); + assert_eq!(result["completed"], 4); + assert_eq!(backend.service.layout(), &before.layout); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + assert!( + backend + .batch(&[ + serde_json::json!({"command":"layout.save","params":{"name":"Not saved"}}), + serde_json::json!({"command":"layout.workspace.select","params":{"workspace":"missing"}}), + ]) + .is_err() + ); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + let mixed = backend + .batch(&[ + serde_json::json!({"command":"panel.close","params":{"target":command_target("one")}}), + serde_json::json!({"command":"layout.reset"}), + ]) + .unwrap_err(); + assert_eq!(mixed.rule, Rule::Capability); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); +} + +#[test] +fn catalogue_staging_cannot_publish_a_plan_after_an_external_revision_change() { + use commands::{CatalogueState, LayoutCatalogue, PreparedCatalogue}; + use std::cell::RefCell; + use std::rc::Rc; + struct SharedSink(Rc>); + impl ActionSink for SharedSink { + fn inspect(&self) -> LayoutReply { + self.0.borrow().inspect() + } + fn project(&self, action: LayoutAction) -> PanelResult { + self.0.borrow().project(action) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + self.0.borrow_mut().dispatch(action) + } + } + struct RacingCatalogue { + catalogue: commands::InMemoryCatalogue, + service: Rc>, + published: bool, + } + impl LayoutCatalogue for RacingCatalogue { + fn state(&self) -> &CatalogueState { + self.catalogue.state() + } + fn prepare(&mut self, next: CatalogueState) -> PanelResult { + self.service.borrow_mut().set_availability([(id("one"), Availability::Unavailable { reason: "external update".into() })].into())?; + PreparedCatalogue::new(next) + } + fn publish(&mut self, prepared: PreparedCatalogue) { + self.published = true; + self.catalogue.publish(prepared); + } + } + let backend = command_ready_backend(); + let registry = backend.service.registry().clone(); + let shared = Rc::new(RefCell::new(backend.service)); + let mut sink = SharedSink(shared.clone()); + let mut catalogue = RacingCatalogue { catalogue: backend.catalogue, service: shared, published: false }; + let before = catalogue.state().clone(); + let reason = commands::execute( + "panel.close", + &serde_json::json!({"target":command_target("one")}), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false }, + ) + .unwrap_err(); + assert_eq!(reason.rule, Rule::Revision); + assert!(!catalogue.published); + assert_eq!(catalogue.state(), &before); + assert!(sink.inspect().layout.instance(&id("one")).unwrap().requested_open); +} + +#[test] +fn catalogue_workspace_count_and_metadata_budgets_are_independent_and_atomic() { + use commands::LayoutCatalogue; + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(persistence_fallback()); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.register_builtin("Default", &envelope, ®istry).unwrap(); + for i in 0..commands::MAX_WORKSPACES { + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new(format!("workspace-{i}")).unwrap(), + title_key: "ui.panel".into(), + default_preset: "Default".into(), + }) + .unwrap(); + } + let before = catalogue.state().clone(); + assert_eq!( + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("overflow").unwrap(), + title_key: "ui.panel".into(), + default_preset: "Default".into() + }) + .unwrap_err() + .rule, + Rule::CollectionLimit + ); + assert_eq!(catalogue.state(), &before); + let mut metadata = commands::InMemoryCatalogue::default(); + for i in 0..64 { + metadata.register_builtin(&format!("{}{:02}", "🦀".repeat(62), i), &envelope, ®istry).unwrap(); + } + let name = format!("{}00", "🦀".repeat(62)); + metadata + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("first").unwrap(), + title_key: "ui.panel".into(), + default_preset: name.clone(), + }) + .unwrap(); + let before = metadata.state().clone(); + assert_eq!( + metadata + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("second").unwrap(), + title_key: "ui.panel".into(), + default_preset: name + }) + .unwrap_err() + .rule, + Rule::CollectionLimit + ); + assert_eq!(metadata.state(), &before); +} + +#[test] +fn headless_cannot_claim_native_support_even_when_an_injected_service_sets_native_flags() { + let service = fixture_service(true).unwrap(); + let catalogue = fixture_command_catalogue(service.registry()).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + backend + .execute("panel.open", &serde_json::json!({"kind":"fixture.log","instance":"one","destination":command_destination("s-one",0,"left")})) + .unwrap(); + assert_eq!(backend.execute("panel.list", &serde_json::json!({})).unwrap()["state"]["capabilities"]["native_windows"], false); + let mut input = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + input["destination"]["index"] = serde_json::json!(0); + let before = backend.service.inspect(); + assert_eq!(backend.execute("panel.popout", &input).unwrap_err().rule, Rule::Capability); + assert_eq!(backend.service.inspect(), before); +} + +#[test] +fn registry_growth_save_and_live_mutation_keep_uncommitted_reappearance_retryable() { + use commands::LayoutCatalogue; + let absent = future_registry(&["a"]); + let grown = future_registry(&["a", "b", "c"]); + let fallback = persistence_fallback(); + let raw = future_group(); + let dormant = decode(&serde_json::to_vec(&raw).unwrap(), &absent, &fallback).unwrap().envelope; + let service = LayoutService::new(grown.clone(), dormant.layout.clone(), HostCapabilities::default()).unwrap(); + let mut catalogue = fixture_command_catalogue(&grown).unwrap(); + catalogue.remember(&dormant, Some(b"recovery"), &grown).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let catalogue = commands::InMemoryCatalogue::from_snapshot(&snapshot, &grown).unwrap(); + let hydrated = catalogue.state().remembered(&fallback.workspace).unwrap().envelope(&grown, &fallback.workspace).unwrap(); + assert_eq!(hydrated.quarantine, dormant.quarantine); + assert_eq!(hydrated.section_order, dormant.section_order); + assert_eq!(hydrated.section_snapshots, dormant.section_snapshots, "including materialized projected sections"); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + backend.execute("layout.save", &serde_json::json!({"name":"Registry grew"})).unwrap(); + backend + .execute( + "panel.open", + &serde_json::json!({"kind":"fixture.application","instance":"app","destination":command_destination("app-section",1,"right")}), + ) + .unwrap(); + backend.execute("panel.resize", &serde_json::json!({"target":command_target("app"),"size":{"width":300,"height":280}})).unwrap(); + let remembered = backend.catalogue.state().remembered(&fallback.workspace).unwrap(); + let retained = remembered.envelope(&grown, &fallback.workspace).unwrap(); + assert_eq!(retained.quarantine.len(), 2, "temporary decode is not a committed restore"); + assert_eq!(retained.section_snapshots[§ion("group")].data["active"], "c"); + assert_eq!(retained.section_snapshots[§ion("group")].data["tabs"], serde_json::json!(["c", "b", "a"])); + assert_eq!(retained.quarantine.iter().find(|q| q.instance == id("b")).unwrap().instance_data["future_draft"], "draft-b"); + assert_eq!(remembered.rejected(), Some(b"recovery".as_slice())); + let restored = decode(remembered.bytes(), &grown, &fallback).unwrap().envelope; + assert_eq!(restored.layout.section(§ion("group")).unwrap().active, id("c")); + assert_eq!(restored.layout.section(§ion("group")).unwrap().tabs, vec![id("c"), id("b"), id("a")]); + let before = backend.catalogue.state().clone(); + let live = backend.service.inspect(); + backend.catalogue.fail_stage = true; + assert!(backend.execute("layout.apply", &serde_json::json!({"name":"Registry grew"})).is_err()); + assert_eq!(backend.catalogue.state(), &before); + assert_eq!(backend.service.inspect(), live); + backend.catalogue.fail_stage = false; + backend.execute("layout.apply", &serde_json::json!({"name":"Registry grew"})).unwrap(); + assert_eq!(backend.service.layout().section(§ion("group")).unwrap().active, id("c")); + let committed = backend.catalogue.state().remembered(&fallback.workspace).unwrap().envelope(&grown, &fallback.workspace).unwrap(); + assert!(committed.quarantine.is_empty()); + assert_eq!(committed.retained_data[&id("b")]["instance"]["future_draft"], "draft-b"); +} + +#[test] +fn disabled_popout_rejects_native_and_web_before_lowering_while_float_remains_allowed() { + use commands::LayoutCatalogue; + for web in [false, true] { + let mut registry = synthetic_registry().unwrap(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("fixture.no-popout").unwrap(); + spec.features.popout = false; + registry.register(spec).unwrap(); + let mut service = LayoutService::new( + registry.clone(), + persistence_fallback(), + HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: false }, + ) + .unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.no-popout", "one", "s-one", Zone::Left, 0).unwrap()])).unwrap(); + let mut catalogue = fixture_command_catalogue(®istry).unwrap(); + let before = service.inspect(); + let stored = catalogue.state().clone(); + let mut popout = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + popout["destination"]["index"] = serde_json::json!(0); + let reason = commands::execute( + "panel.popout", + &popout, + &mut commands::PanelCommandContext { sink: &mut service, registry: ®istry, catalogue: &mut catalogue, web }, + ) + .unwrap_err(); + assert_eq!(reason.rule, Rule::FeatureDisabled); + assert_eq!(service.inspect(), before); + assert_eq!(catalogue.state(), &stored); + popout["destination"]["location"] = serde_json::json!({"type":"floating","origin":{"x":20,"y":30}}); + commands::execute( + "panel.float", + &popout, + &mut commands::PanelCommandContext { sink: &mut service, registry: ®istry, catalogue: &mut catalogue, web }, + ) + .unwrap(); + assert_eq!(service.layout().containing(&id("one")).unwrap().location.zone(), Zone::Floating); + } +} + +// Deliberately uses only public consumer interfaces, as an independent storage +// crate would; user presets are never reconstructed by fake live commands. +mod catalogue_consumer { + use crate::panels::commands::{ + CatalogueState, InMemoryCatalogue, InMemoryPanelBackend, LayoutCatalogue, MAX_CATALOGUE_BYTES, MAX_CATALOGUE_SNAPSHOT_BYTES, + }; + use crate::panels::*; + + fn maximum_record(mut envelope: LayoutEnvelope, registry: &PanelRegistry, bytes: usize) -> LayoutEnvelope { + let padding = InstanceId::new("padding").unwrap(); + envelope.retained_data.insert(padding.clone(), serde_json::json!("")); + let overhead = encode(&envelope, registry).unwrap().len(); + let length = bytes.checked_sub(overhead).expect("test record has room for opaque padding"); + envelope.retained_data.insert(padding, serde_json::json!("x".repeat(length))); + assert_eq!(encode(&envelope, registry).unwrap().len(), bytes); + envelope + } + + fn unmaterialized_section_record(with_snapshot: bool) -> (PanelRegistry, LayoutEnvelope) { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "log", "logs", Zone::Left, 0).unwrap()])).unwrap(); + let registry = service.registry().clone(); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + envelope.section_order.clear(); // Encode-valid earlier-v1 intent, not missing content. + if with_snapshot { + let section = envelope.layout.sections.first().unwrap(); + let mut data = serde_json::to_value(section).unwrap(); + data["future_surface"] = serde_json::json!({"opaque":"preserve exactly"}); + envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index: 0, projected: None }); + } + (registry, envelope) + } + + fn without_kind(registry: &PanelRegistry, missing: &str) -> PanelRegistry { + let mut absent = PanelRegistry::default(); + for spec in registry.specs().filter(|spec| spec.kind.0 != missing) { + absent.register(spec.clone()).unwrap(); + } + absent + } + + fn assert_same_placement(actual: &Layout, expected: &Layout) { + assert_eq!(actual.version, expected.version); + assert_eq!(actual.workspace, expected.workspace); + assert_eq!(actual.sections, expected.sections, "complete section order, tab order and activation"); + assert_eq!(actual.instances.len(), expected.instances.len()); + for instance in &expected.instances { + assert_eq!(actual.instance(&instance.id).unwrap(), instance); + } + } + + fn registered_extension_record() -> (PanelRegistry, LayoutEnvelope) { + let mut registry = synthetic_registry().unwrap(); + let mut extension = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + extension.kind = PanelKind::new("extension.a").unwrap(); + registry.register(extension).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "ordinary", "group", Zone::Left, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("extension.a").unwrap(), + instance: InstanceId::new("extension").unwrap(), + destination: Some(Destination::JoinTab { section: SectionId::new("group").unwrap(), index: 0 }), + }, + fixture_open("fixture.application", "app", "app-section", Zone::Right, 1).unwrap(), + Mutation::Activate { instance: InstanceId::new("extension").unwrap() }, + ])) + .unwrap(); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + envelope.retained_data.insert(InstanceId::new("extension").unwrap(), serde_json::json!({"future_draft":{"text":"keep draft","cursor":7}})); + for (index, section) in envelope.layout.sections.iter().enumerate() { + let mut data = serde_json::to_value(section).unwrap(); + data["future_surface"] = serde_json::json!({"opaque":section.id.0}); + envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index, projected: Some(section.clone()) }); + } + (registry, envelope) + } + + #[test] + fn registry_shrink_hydrates_exact_users_builtins_and_memories_then_stages_reappearance() { + let (registry, envelope) = registered_extension_record(); + let absent = without_kind(®istry, "extension.a"); + let mut catalogue = fixture_command_catalogue(®istry).unwrap(); + catalogue.register_builtin("Extension default", &envelope, ®istry).unwrap(); + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("extension.workspace").unwrap(), + title_key: "ui.panel".into(), + default_preset: "Extension default".into(), + }) + .unwrap(); + let mut source = InMemoryPanelBackend::new(fixture_service(false).unwrap(), catalogue); + source.execute("layout.save", &serde_json::json!({"name":"Ordinary user"})).unwrap(); + // Use the real extended registry/service when creating the saved user. + source.service = LayoutService::new(registry.clone(), envelope.layout.clone(), HostCapabilities::default()).unwrap(); + let rejected = [0, 255, 128, 0, 17]; + source.catalogue.remember(&envelope, Some(&rejected), ®istry).unwrap(); + source.execute("layout.save", &serde_json::json!({"name":"Extension user"})).unwrap(); + let snapshot = source.catalogue.state().export().unwrap(); + let hydrated = InMemoryCatalogue::from_snapshot(&snapshot, &absent).unwrap(); + assert_eq!(hydrated.state(), source.catalogue.state()); + assert_eq!(hydrated.state().export().unwrap(), snapshot); + assert_eq!(hydrated.state().user_presets().map(|(name, _)| name).collect::>(), vec!["Extension user", "Ordinary user"]); + let record = hydrated.state().preset("Extension user").unwrap(); + let exact = record.envelope(&absent, &envelope.layout.workspace).unwrap(); + assert_eq!(exact.layout, envelope.layout, "inspection keeps the original requested-open instance and activation"); + assert_eq!(exact.retained_data, envelope.retained_data); + assert_eq!(record.rejected(), Some(rejected.as_slice())); + let mut staged = record.project_envelope(&absent, &envelope.layout.workspace).unwrap(); + validate(&staged.layout, &absent).unwrap(); + assert!(staged.layout.instances.iter().all(|instance| instance.kind.0 != "extension.a")); + assert_eq!(staged.quarantine.len(), 1); + assert_eq!(staged.section_snapshots[&SectionId::new("group").unwrap()].data["active"], "extension"); + let dormant = staged.clone(); + let availability = [(InstanceId::new("extension").unwrap(), Availability::Unavailable { reason: "temporarily absent provider".into() })] + .into_iter() + .collect(); + restore_quarantine_with_availability(&mut staged, ®istry, &availability).unwrap(); + assert_eq!(staged, dormant, "a refused reappearance preserves retryable intent"); + restore_quarantine(&mut staged, ®istry).unwrap(); + assert_same_placement(&staged.layout, &envelope.layout); + assert_eq!(staged.section_order, envelope.section_order); + assert!(staged.quarantine.is_empty()); + assert_eq!(staged.retained_data[&InstanceId::new("extension").unwrap()], envelope.retained_data[&InstanceId::new("extension").unwrap()]); + assert_eq!(staged.section_snapshots[&SectionId::new("group").unwrap()].data["future_surface"]["opaque"], "group"); + let mut absent_backend = InMemoryPanelBackend::new( + LayoutService::new(absent.clone(), Layout::empty(envelope.layout.workspace.clone()), HostCapabilities::default()).unwrap(), + hydrated, + ); + absent_backend.execute("layout.apply", &serde_json::json!({"name":"Ordinary user"})).unwrap(); + absent_backend.execute("layout.workspace.select", &serde_json::json!({"workspace":"fixture.other"})).unwrap(); + absent_backend.execute("layout.reset", &serde_json::json!({})).unwrap(); + absent_backend.execute("layout.workspace.select", &serde_json::json!({"workspace":"extension.workspace"})).unwrap(); + assert!(absent_backend.service.layout().instances.iter().all(|instance| instance.kind.0 != "extension.a")); + let remembered = absent_backend + .catalogue + .state() + .remembered(&WorkspaceId::new("extension.workspace").unwrap()) + .unwrap() + .envelope(&absent, &WorkspaceId::new("extension.workspace").unwrap()) + .unwrap(); + assert_eq!(remembered.quarantine.len(), 1, "selecting a missing peer stages quarantine, never an unknown live instance"); + absent_backend.execute("layout.save", &serde_json::json!({"name":"Still dormant"})).unwrap(); + let after_shrink = absent_backend.catalogue.state().export().unwrap(); + let grown = InMemoryCatalogue::from_snapshot(&after_shrink, ®istry).unwrap(); + assert_eq!(grown.state().export().unwrap(), after_shrink); + assert_eq!(grown.state().preset("Extension user").unwrap().bytes(), source.catalogue.state().preset("Extension user").unwrap().bytes()); + assert_eq!(grown.state().preset("Extension user").unwrap().rejected(), Some(rejected.as_slice())); + let service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("recovery.workspace").unwrap()), HostCapabilities::default()) + .unwrap(); + let mut grown_backend = InMemoryPanelBackend::new(service, grown); + grown_backend.execute("layout.apply", &serde_json::json!({"name":"Still dormant"})).unwrap(); + let mut expected = envelope.layout; + expected.workspace = WorkspaceId::new("recovery.workspace").unwrap(); + assert_same_placement(grown_backend.service.layout(), &expected); + } + + #[test] + fn registry_shrink_maximum_records_remain_exact_and_projection_failure_is_retryable() { + for with_snapshot in [false, true] { + let (registry, envelope) = unmaterialized_section_record(with_snapshot); + let absent = without_kind(®istry, "fixture.log"); + let envelope = maximum_record(envelope, ®istry, MAX_ENVELOPE_BYTES); + let original = encode(&envelope, ®istry).unwrap(); + let rejected = [0, 255, 128, 0]; + let mut catalogue = InMemoryCatalogue::default(); + catalogue.register_builtin("Maximum", &envelope, ®istry).unwrap(); + let ordinary = LayoutEnvelope::new(Layout::empty(WorkspaceId::new("unrelated.workspace").unwrap())); + catalogue.register_builtin("Ordinary", &ordinary, ®istry).unwrap(); + catalogue.remember(&envelope, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = InMemoryCatalogue::from_snapshot(&snapshot, &absent).unwrap(); + assert_eq!(hydrated.state(), catalogue.state()); + assert_eq!(hydrated.state().export().unwrap(), snapshot); + let stored = hydrated.state().remembered(&envelope.layout.workspace).unwrap(); + assert_eq!(stored.bytes(), original.as_slice()); + assert_eq!(stored.rejected(), Some(rejected.as_slice())); + assert_eq!(stored.envelope(&absent, &envelope.layout.workspace).unwrap(), envelope); + if with_snapshot { + let projected = stored.project_envelope(&absent, &envelope.layout.workspace).unwrap(); + validate(&projected.layout, &absent).unwrap(); + assert_eq!(projected.quarantine.len(), 1); + assert_eq!(projected.section_snapshots[&SectionId::new("logs").unwrap()].data["active"], "log"); + } else { + // Capturing a previously absent snapshot needs additional bytes. + assert_eq!(stored.project_envelope(&absent, &envelope.layout.workspace).unwrap_err().rule, Rule::CollectionLimit); + } + let mut backend = + InMemoryPanelBackend::new(LayoutService::new(absent.clone(), ordinary.layout, HostCapabilities::default()).unwrap(), hydrated); + backend.execute("layout.apply", &serde_json::json!({"name":"Ordinary"})).unwrap(); + let before = backend.catalogue.state().clone(); + let live = backend.service.inspect(); + if with_snapshot { + // Existing snapshot storage frees enough space when its absent + // live section is quarantined; no cap is raised to permit it. + backend.execute("layout.apply", &serde_json::json!({"name":"Maximum"})).unwrap(); + assert!(backend.service.layout().instances.is_empty()); + let remembered = + backend.catalogue.state().remembered(&live.layout.workspace).unwrap().envelope(&absent, &live.layout.workspace).unwrap(); + assert_eq!(remembered.quarantine.len(), 1); + assert_eq!(remembered.retained_data, envelope.retained_data); + } else { + assert_eq!(backend.execute("layout.apply", &serde_json::json!({"name":"Maximum"})).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(backend.catalogue.state(), &before); + assert_eq!(backend.service.inspect(), live); + } + let grown = CatalogueState::hydrate(&snapshot, ®istry).unwrap(); + assert_eq!(grown.export().unwrap(), snapshot); + assert_eq!( + grown.preset("Maximum").unwrap().project_envelope(®istry, &envelope.layout.workspace).unwrap(), + envelope, + "returning registration needs no read-time metadata expansion" + ); + } + } + + #[test] + fn registry_shrink_and_growth_preserve_exact_aggregate_budget_and_recovery() { + let (registry, base) = unmaterialized_section_record(true); + let absent = without_kind(®istry, "fixture.log"); + let full = maximum_record(base.clone(), ®istry, MAX_ENVELOPE_BYTES); + let ordinary = + maximum_record(LayoutEnvelope::new(Layout::empty(WorkspaceId::new("ordinary.workspace").unwrap())), ®istry, MAX_ENVELOPE_BYTES); + let rejected = [255, 0, 128, 0, 1]; + let tail = maximum_record(base, ®istry, MAX_ENVELOPE_BYTES - rejected.len()); + let mut catalogue = InMemoryCatalogue::default(); + for index in 0..14 { + catalogue.register_builtin(&format!("Missing-{index}"), &full, ®istry).unwrap(); + } + catalogue.register_builtin("Ordinary", &ordinary, ®istry).unwrap(); + catalogue.remember(&tail, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + assert_eq!( + 14 * encode(&full, ®istry).unwrap().len() + + encode(&ordinary, ®istry).unwrap().len() + + encode(&tail, ®istry).unwrap().len() + + rejected.len(), + MAX_CATALOGUE_BYTES + ); + let absent_state = CatalogueState::hydrate(&snapshot, &absent).unwrap(); + assert_eq!(absent_state, catalogue.state().clone()); + assert_eq!(absent_state.export().unwrap(), snapshot); + assert_eq!(absent_state.preset("Ordinary").unwrap().project_envelope(&absent, &ordinary.layout.workspace).unwrap(), ordinary); + assert_eq!(absent_state.remembered(&tail.layout.workspace).unwrap().rejected(), Some(rejected.as_slice())); + let grown = CatalogueState::hydrate(&absent_state.export().unwrap(), ®istry).unwrap(); + assert_eq!(grown.export().unwrap(), snapshot); + assert_eq!(grown.preset("Missing-0").unwrap().envelope(®istry, &full.layout.workspace).unwrap(), full); + let mut hydrated = InMemoryCatalogue::from_snapshot(&snapshot, &absent).unwrap(); + let before = hydrated.state().clone(); + assert_eq!( + hydrated.register_builtin("Overflow", &LayoutEnvelope::new(Layout::empty(ordinary.layout.workspace)), &absent).unwrap_err().rule, + Rule::CollectionLimit + ); + assert_eq!(hydrated.state(), &before); + } + + #[test] + fn optional_peer_raw_future_fields_survive_exact_hydration_quarantine_and_reappearance() { + let (registry, mut envelope) = registered_extension_record(); + // A future writer may also carry opaque keys in the saved typed records. + // Keep a separate existing opaque sidecar to exercise both storage paths. + let draft = envelope.retained_data.remove(&InstanceId::new("extension").unwrap()).unwrap(); + envelope.retained_data.insert(InstanceId::new("unrelated-opaque").unwrap(), draft); + let mut raw = serde_json::to_value(&envelope).unwrap(); + raw["layout"]["instances"][1]["future_editor"] = serde_json::json!({"draft":"original raw draft","selection":[3,9]}); + raw["layout"]["sections"][0]["future_surface"] = serde_json::json!({"raw":"keep raw section intent"}); + let bytes = serde_json::to_vec(&raw).unwrap(); + let rejected = [0, 255, 128, 0]; + let saved = snapshot( + &[("Builtin", &bytes, None)], + &[("User", &bytes, Some(&rejected))], + &[("fixture.workspace", "ui.panel", "Builtin")], + &[("fixture.workspace", &bytes, Some(&rejected))], + ); + let original = CatalogueState::hydrate(&saved, ®istry).unwrap().export().unwrap(); + let absent = without_kind(®istry, "extension.a"); + let hydrated = CatalogueState::hydrate(&original, &absent).unwrap(); + assert_eq!(hydrated.export().unwrap(), original); + for record in + [hydrated.preset("Builtin").unwrap(), hydrated.preset("User").unwrap(), hydrated.remembered(&envelope.layout.workspace).unwrap()] + { + assert_eq!(record.bytes(), bytes.as_slice()); + let mut staged = record.project_envelope(&absent, &envelope.layout.workspace).unwrap(); + assert_eq!(staged.quarantine[0].instance_data["future_editor"], raw["layout"]["instances"][1]["future_editor"]); + assert_eq!(staged.section_snapshots[&SectionId::new("group").unwrap()].data["future_surface"]["raw"], "keep raw section intent"); + restore_quarantine(&mut staged, ®istry).unwrap(); + assert_same_placement(&staged.layout, &envelope.layout); + assert_eq!( + staged.retained_data[&InstanceId::new("extension").unwrap()]["instance"]["future_editor"], + raw["layout"]["instances"][1]["future_editor"] + ); + assert_eq!( + staged.retained_data[&InstanceId::new("unrelated-opaque").unwrap()], + envelope.retained_data[&InstanceId::new("unrelated-opaque").unwrap()] + ); + } + let grown = CatalogueState::hydrate(&hydrated.export().unwrap(), ®istry).unwrap(); + assert_eq!(grown.export().unwrap(), original); + assert_eq!(grown.preset("User").unwrap().rejected(), Some(rejected.as_slice())); + } + + #[test] + fn missing_peer_does_not_hide_corrupt_structure_or_known_member_constraints() { + let (registry, envelope) = registered_extension_record(); + let absent = without_kind(®istry, "extension.a"); + let valid = serde_json::to_value(&envelope).unwrap(); + let mut hostile = Vec::new(); + let mut value = valid.clone(); + value["layout"]["instances"][1]["memory"]["size"]["width"] = serde_json::json!(0); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][1]["memory"]["tab_index"] = serde_json::json!(MAX_TABS); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["sections"][0]["active"] = serde_json::json!("ghost"); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][1]["id"] = serde_json::json!("ordinary"); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][0]["memory"]["size"]["width"] = serde_json::json!(1); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["sections"][0]["size"]["width"] = serde_json::json!(1); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][0]["kind"] = serde_json::json!("fixture.application"); + hostile.push(value); // Repeats known single-instance kind. + let mut value = valid.clone(); + value["layout"]["sections"][0]["tabs"] = serde_json::json!(vec!["ordinary"; MAX_TABS + 1]); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][0]["requested_open"] = serde_json::json!(false); + value["layout"]["sections"][0]["tabs"] = serde_json::json!(["extension"]); + for section in value["layout"]["sections"].as_array_mut().unwrap() { + section["location"] = serde_json::json!({"type":"window","host":"same-host","origin":{"x":0,"y":0}, + "return_to":{"zone":"left","index":0,"size":{"width":280,"height":240},"collapsed":false}}); + } + hostile.push(value); // Duplicate native host, including an entirely absent-kind section. + let mut deep = serde_json::json!(null); + for _ in 0..34 { + deep = serde_json::json!({"future":deep}); + } + let mut value = valid.clone(); + value["retained_data"]["future"] = deep; + hostile.push(value); + for value in hostile { + let bytes = serde_json::to_vec(&value).unwrap(); + let snapshot = snapshot(&[], &[("Saved", &bytes, None)], &[], &[]); + assert!(CatalogueState::hydrate(&snapshot, &absent).is_err()); + assert!(project_retained_record(&bytes, &absent, &envelope.layout.workspace).is_err()); + } + // A known member's no-tab flag applies even when its only peer is absent. + let mut no_tabs = PanelRegistry::default(); + for spec in absent.specs() { + let mut spec = spec.clone(); + if spec.kind.0 == "fixture.log" { + spec.features.tabbable = false; + } + no_tabs.register(spec).unwrap(); + } + let bytes = encode(&envelope, ®istry).unwrap(); + assert_eq!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", &bytes, None)], &[], &[]), &no_tabs).unwrap_err().rule, Rule::FeatureDisabled); + // An absent-only outer section still precedes a known pinned section. + let mut pin_service = + LayoutService::new(registry.clone(), Layout::empty(envelope.layout.workspace.clone()), HostCapabilities::default()).unwrap(); + pin_service + .dispatch(transaction(vec![ + fixture_open("fixture.pin", "pin", "pin-section", Zone::Left, 0).unwrap(), + fixture_open("extension.a", "missing", "missing-section", Zone::Right, 1).unwrap(), + ])) + .unwrap(); + let mut wire = serde_json::to_value(LayoutEnvelope::new(pin_service.layout().clone())).unwrap(); + wire["layout"]["sections"].as_array_mut().unwrap().reverse(); + wire["layout"]["sections"][0]["location"] = serde_json::json!({"type":"dock","zone":"left"}); + let bytes = serde_json::to_vec(&wire).unwrap(); + assert_eq!(CatalogueState::hydrate(&snapshot(&[], &[("Pinned", &bytes, None)], &[], &[]), &absent).unwrap_err().rule, Rule::PinOrder); + } + + #[test] + fn accepted_maximum_records_roundtrip_without_materializing_order_or_projection() { + for with_snapshot in [false, true] { + let (registry, envelope) = unmaterialized_section_record(with_snapshot); + let envelope = maximum_record(envelope, ®istry, MAX_ENVELOPE_BYTES); + let original = encode(&envelope, ®istry).unwrap(); + let rejected = [0, 255, 0, 127, 128, 42, 1]; + let mut catalogue = InMemoryCatalogue::default(); + catalogue.register_builtin("Maximum", &envelope, ®istry).unwrap(); + catalogue.remember(&envelope, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = InMemoryCatalogue::from_snapshot(&snapshot, ®istry).unwrap(); + assert_eq!(hydrated.state(), catalogue.state()); + assert_eq!(hydrated.state().export().unwrap(), snapshot, "same-registry hydration retains the original records byte for byte"); + for record in [hydrated.state().preset("Maximum").unwrap(), hydrated.state().remembered(&envelope.layout.workspace).unwrap()] { + assert_eq!(record.bytes(), original.as_slice()); + let loaded = record.envelope(®istry, &envelope.layout.workspace).unwrap(); + assert_eq!(loaded, envelope); + assert!(loaded.section_order.is_empty()); + assert!(loaded.section_snapshots.values().all(|snapshot| snapshot.projected.is_none())); + } + assert_eq!(hydrated.state().remembered(&envelope.layout.workspace).unwrap().rejected(), Some(rejected.as_slice())); + let mut oversized = envelope.clone(); + oversized.retained_data.insert( + InstanceId::new("padding").unwrap(), + serde_json::json!(format!("{}x", envelope.retained_data[&InstanceId::new("padding").unwrap()].as_str().unwrap())), + ); + let before = catalogue.state().clone(); + assert_eq!(catalogue.register_builtin("Oversized", &oversized, ®istry).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(catalogue.state(), &before); + let mut corrupt = snapshot; + corrupt.push(0); + assert_eq!(CatalogueState::hydrate(&corrupt, ®istry).unwrap_err().rule, Rule::Schema); + } + } + + #[test] + fn accepted_aggregate_limit_roundtrips_exact_records_and_rejected_binary_bytes() { + let (registry, base) = unmaterialized_section_record(true); + let full = maximum_record(base.clone(), ®istry, MAX_ENVELOPE_BYTES); + let full_bytes = encode(&full, ®istry).unwrap(); + let rejected = [0, 255, 0, 127, 128, 42, 1]; + let tail = maximum_record(base, ®istry, MAX_ENVELOPE_BYTES - rejected.len()); + let tail_bytes = encode(&tail, ®istry).unwrap(); + assert_eq!(15 * full_bytes.len() + tail_bytes.len() + rejected.len(), MAX_CATALOGUE_BYTES); + let mut catalogue = InMemoryCatalogue::default(); + for index in 0..15 { + catalogue.register_builtin(&format!("Maximum-{index}"), &full, ®istry).unwrap(); + } + catalogue.remember(&tail, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = CatalogueState::hydrate(&snapshot, ®istry).unwrap(); + assert_eq!(hydrated, catalogue.state().clone()); + assert_eq!(hydrated.export().unwrap(), snapshot, "no per-record expansion may silently exceed the aggregate cap"); + for index in 0..15 { + let record = hydrated.preset(&format!("Maximum-{index}")).unwrap(); + assert_eq!(record.bytes(), full_bytes.as_slice()); + assert_eq!(record.envelope(®istry, &full.layout.workspace).unwrap(), full); + } + let remembered = hydrated.remembered(&tail.layout.workspace).unwrap(); + assert_eq!(remembered.bytes(), tail_bytes.as_slice()); + assert_eq!(remembered.rejected(), Some(rejected.as_slice())); + let before = catalogue.state().clone(); + let empty = LayoutEnvelope::new(Layout::empty(full.layout.workspace.clone())); + assert_eq!(catalogue.register_builtin("One beyond aggregate budget", &empty, ®istry).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(catalogue.state(), &before); + } + + #[test] + fn maximum_retained_records_defer_live_refresh_and_reappearance_atomically() { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "future", "future-section", Zone::Left, 0).unwrap()])).unwrap(); + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + raw["layout"]["instances"][0]["kind"] = serde_json::json!("extension.future"); + raw["layout"]["instances"][0]["future_draft"] = serde_json::json!("pending conversation"); + let absent = synthetic_registry().unwrap(); + let fallback = Layout::empty(service.layout().workspace.clone()); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &absent, &fallback).unwrap().envelope; + envelope.section_order.clear(); + let mut grown = absent; + let mut spec = grown.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.future").unwrap(); + grown.register(spec).unwrap(); + let envelope = maximum_record(envelope, &grown, MAX_ENVELOPE_BYTES); + let rejected = [255, 0, 128, 0, 1]; + let mut catalogue = InMemoryCatalogue::default(); + catalogue.remember(&envelope, Some(&rejected), &grown).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = CatalogueState::hydrate(&snapshot, &grown).unwrap(); + let loaded = hydrated.remembered(&fallback.workspace).unwrap().envelope(&grown, &fallback.workspace).unwrap(); + assert_eq!(loaded, envelope, "registered quarantine is not a read-time restoration"); + assert_eq!(loaded.quarantine.first().unwrap().instance_data["future_draft"], "pending conversation"); + assert_eq!(with_live_layout(&loaded, loaded.layout.clone(), &grown).unwrap_err().rule, Rule::CollectionLimit); + let mut candidate = loaded.clone(); + assert_eq!(restore_quarantine(&mut candidate, &grown).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(candidate, loaded, "failed materialization keeps all retryable intent and opaque records"); + assert_eq!(hydrated.export().unwrap(), snapshot); + assert_eq!(hydrated.remembered(&fallback.workspace).unwrap().rejected(), Some(rejected.as_slice())); + } + + #[test] + fn external_storage_roundtrip_restores_mutable_users_full_records_and_workspaces() { + let mut backend = fixture_command_backend().unwrap(); + backend.service.dispatch(transaction(vec![fixture_open("fixture.log", "log", "logs", Zone::Left, 0).unwrap()])).unwrap(); + let mut envelope = LayoutEnvelope::new(backend.service.layout().clone()); + envelope.retained_data.insert(InstanceId::new("opaque").unwrap(), serde_json::json!({"future":{"draft":"keep"}})); + backend.catalogue.remember(&envelope, Some(&[0, 255, 1, 0]), backend.service.registry()).unwrap(); + backend.execute("layout.save", &serde_json::json!({"name":"User saved"})).unwrap(); + let snapshot = backend.catalogue.state().export().unwrap(); + let users: Vec<_> = backend.catalogue.state().user_presets().map(|(name, _)| name).collect(); + assert_eq!(users, vec!["User saved"]); + // No executor is called while the independent consumer reconstructs state. + let registry = synthetic_registry().unwrap(); + let state = CatalogueState::hydrate(&snapshot, ®istry).unwrap(); + assert_eq!(state.summaries(), backend.catalogue.state().summaries()); + assert_eq!(state.user_presets().map(|(name, _)| name).collect::>(), users); + let saved = state.preset("User saved").unwrap(); + assert_eq!(saved.rejected(), Some([0, 255, 1, 0].as_slice())); + let restored = saved.envelope(®istry, &envelope.layout.workspace).unwrap(); + assert_eq!(restored.retained_data, envelope.retained_data); + assert_eq!(state.remembered(&envelope.layout.workspace).unwrap().rejected(), Some([0, 255, 1, 0].as_slice())); + let catalogue = InMemoryCatalogue::from_snapshot(&snapshot, ®istry).unwrap(); + assert_eq!(catalogue.state().user_count(), 1); + let mut reloaded = InMemoryPanelBackend::new(fixture_service(false).unwrap(), catalogue); + assert_eq!(reloaded.execute("layout.save", &serde_json::json!({"name":"User saved"})).unwrap_err().rule, Rule::DuplicateId); + reloaded.execute("layout.save", &serde_json::json!({"name":"User saved","overwrite":true})).unwrap(); + assert_eq!(reloaded.catalogue.state().user_count(), 1); + assert_eq!( + reloaded.execute("layout.save", &serde_json::json!({"name":"Fixture default","overwrite":true})).unwrap_err().rule, + Rule::Capability + ); + } + + type Entry<'a> = (&'a str, &'a [u8], Option<&'a [u8]>); + fn length(out: &mut Vec, count: usize) { + out.extend_from_slice(&(count as u32).to_le_bytes()); + } + fn bytes(out: &mut Vec, value: &[u8]) { + length(out, value.len()); + out.extend_from_slice(value); + } + fn entries(out: &mut Vec, records: &[Entry<'_>]) { + length(out, records.len()); + for (name, envelope, rejected) in records { + bytes(out, name.as_bytes()); + bytes(out, envelope); + match rejected { + Some(rejected) => { + out.push(1); + bytes(out, rejected); + } + None => out.push(0), + } + } + } + fn snapshot(builtins: &[Entry<'_>], users: &[Entry<'_>], workspaces: &[(&str, &str, &str)], remembered: &[Entry<'_>]) -> Vec { + let mut out = b"SCPCAT01".to_vec(); + entries(&mut out, builtins); + entries(&mut out, users); + length(&mut out, workspaces.len()); + for (id, title, default) in workspaces { + bytes(&mut out, id.as_bytes()); + bytes(&mut out, title.as_bytes()); + bytes(&mut out, default.as_bytes()); + } + entries(&mut out, remembered); + out + } + + #[test] + fn catalogue_hydration_rejects_duplicate_names_workspaces_and_corrupt_framing_before_publication() { + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(fixture_service(false).unwrap().layout().clone()); + let raw = encode(&envelope, ®istry).unwrap(); + let record = ("Saved", raw.as_slice(), None); + for duplicate in [ + snapshot(&[], &[record, record], &[], &[]), + snapshot(&[record], &[record], &[], &[]), + snapshot(&[record], &[], &[("a", "ui.panel", "Saved"), ("a", "ui.panel", "Saved")], &[]), + snapshot(&[], &[], &[], &[("fixture.workspace", raw.as_slice(), None), ("fixture.workspace", raw.as_slice(), None)]), + ] { + assert_eq!(CatalogueState::hydrate(&duplicate, ®istry).unwrap_err().rule, Rule::DuplicateId); + } + let valid = snapshot(&[], &[record], &[], &[]); + for size in [0, 7, 12, valid.len() - 1] { + assert!(CatalogueState::hydrate(&valid[..size], ®istry).is_err()); + } + let mut trailing = valid.clone(); + trailing.push(0); + assert!(CatalogueState::hydrate(&trailing, ®istry).is_err()); + let mut future = valid; + future[7] = b'2'; + assert_eq!(CatalogueState::hydrate(&future, ®istry).unwrap_err().rule, Rule::Version); + assert!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", b"corrupt", None)], &[], &[]), ®istry).is_err()); + assert!(CatalogueState::hydrate(&snapshot(&[], &[], &[], &[("wrong-workspace", raw.as_slice(), None)]), ®istry).is_err()); + let live = fixture_command_backend().unwrap(); + let before = live.catalogue.state().clone(); + let layout = live.service.inspect(); + assert!(InMemoryCatalogue::from_snapshot(b"corrupt", ®istry).is_err()); + assert_eq!(live.catalogue.state(), &before); + assert_eq!(live.service.inspect(), layout); + } + + #[test] + fn catalogue_hydration_bounds_counts_strings_depth_nodes_recovery_and_total_bytes() { + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(fixture_service(false).unwrap().layout().clone()); + let raw = encode(&envelope, ®istry).unwrap(); + let mut count = b"SCPCAT01".to_vec(); + length(&mut count, 65); + assert_eq!(CatalogueState::hydrate(&count, ®istry).unwrap_err().rule, Rule::CollectionLimit); + for name in ["".to_string(), " not-normalised ".into(), "bad\n".into(), "x".repeat(257)] { + assert!(CatalogueState::hydrate(&snapshot(&[], &[(&name, &raw, None)], &[], &[]), ®istry).is_err()); + } + let rejected = vec![0; MAX_ENVELOPE_BYTES + 1]; + assert_eq!( + CatalogueState::hydrate(&snapshot(&[], &[("Saved", &raw, Some(&rejected))], &[], &[]), ®istry).unwrap_err().rule, + Rule::CollectionLimit + ); + let mut value = serde_json::to_value(&envelope).unwrap(); + let mut deep = serde_json::json!(null); + for _ in 0..34 { + deep = serde_json::json!({"future":deep}); + } + for hostile in [deep, serde_json::json!(vec![serde_json::Value::Null; 8193]), serde_json::json!("x".repeat(MAX_ENVELOPE_BYTES))] { + value["retained_data"]["future"] = hostile; + let hostile = serde_json::to_vec(&value).unwrap(); + assert!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", &hostile, None)], &[], &[]), ®istry).is_err()); + } + assert_eq!(CatalogueState::hydrate(&vec![0; MAX_CATALOGUE_SNAPSHOT_BYTES + 1], ®istry).unwrap_err().rule, Rule::CollectionLimit); + } + + #[test] + fn catalogue_hydration_rejects_aggregate_payload_metadata_and_duplicate_envelope_identities() { + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(fixture_service(false).unwrap().layout().clone()); + let raw = encode(&envelope, ®istry).unwrap(); + let mut large = envelope.clone(); + large.retained_data.insert(InstanceId::new("future").unwrap(), serde_json::json!({"opaque":"x".repeat(200_000)})); + let large = encode(&large, ®istry).unwrap(); + let names: Vec<_> = (0..21).map(|i| format!("user-{i}")).collect(); + let users: Vec<_> = names.iter().map(|name| (name.as_str(), large.as_slice(), None)).collect(); + let oversized = snapshot(&[], &users, &[], &[]); + assert!(oversized.len() < MAX_CATALOGUE_SNAPSHOT_BYTES, "payload cap is independent of framing cap"); + assert_eq!(CatalogueState::hydrate(&oversized, ®istry).unwrap_err().rule, Rule::CollectionLimit); + let names: Vec<_> = (0..64).map(|i| format!("{}{:02}", "🦀".repeat(62), i)).collect(); + let builtins: Vec<_> = names.iter().map(|name| (name.as_str(), raw.as_slice(), None)).collect(); + let default = names.first().unwrap().as_str(); + let oversized = snapshot(&builtins, &[], &[("first", "ui.panel", default), ("second", "ui.panel", default)], &[]); + assert_eq!(CatalogueState::hydrate(&oversized, ®istry).unwrap_err().rule, Rule::CollectionLimit); + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "same", "group", Zone::Left, 0).unwrap()])).unwrap(); + let mut duplicate = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + let repeated = duplicate["layout"]["instances"][0].clone(); + duplicate["layout"]["instances"].as_array_mut().unwrap().push(repeated); + let duplicate = serde_json::to_vec(&duplicate).unwrap(); + assert!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", &duplicate, None)], &[], &[]), ®istry).is_err()); + } +} + +#[test] +fn whole_section_ranks_include_known_survivors_and_preserve_intervening_live_order() { + let fallback = persistence_fallback(); + let raw = future_sections(); + let bytes = serde_json::to_vec(&raw).unwrap(); + let all = future_registry(&["a", "b", "c"]); + let mut mixed = decode(&bytes, &future_registry(&["b"]), &fallback).unwrap().envelope; + assert_eq!(section_ids(&mixed), vec![section("s1")]); + assert!(!mixed.section_snapshots.contains_key(§ion("s1"))); + restore_quarantine(&mut mixed, &future_registry(&["b", "c"])).unwrap(); + assert_eq!(section_ids(&mixed), vec![section("s1"), section("s2")]); + restore_quarantine(&mut mixed, &all).unwrap(); + assert_eq!(section_ids(&mixed), vec![section("s0"), section("s1"), section("s2")]); + let a_c = future_registry(&["a", "c"]); + let mut edited = decode(&bytes, &a_c, &fallback).unwrap().envelope; + edited.layout.sections.reverse(); // Visible saved user order is now s2, s0. + let reloaded = decode(&encode(&edited, &a_c).unwrap(), &a_c, &fallback).unwrap(); + assert!(reloaded.notice.is_none()); + edited = reloaded.envelope; + assert_eq!(edited.section_order, vec![section("s2"), section("s1"), section("s0")]); + restore_quarantine(&mut edited, &all).unwrap(); + assert_eq!(section_ids(&edited), vec![section("s2"), section("s1"), section("s0")]); +} + +#[test] +fn new_visible_sections_anchor_to_live_neighbours_while_old_sections_are_dormant() { + let fallback = persistence_fallback(); + let b = future_registry(&["b"]); + let all = future_registry(&["a", "b", "c"]); + let mut envelope = decode(&serde_json::to_vec(&future_sections()).unwrap(), &b, &fallback).unwrap().envelope; + let mut live = LayoutService::new(b, envelope.layout.clone(), HostCapabilities::default()).unwrap(); + live.dispatch(transaction(vec![fixture_open("fixture.log", "new", "new-section", Zone::Right, 0).unwrap()])).unwrap(); + envelope.layout = live.layout().clone(); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(section_ids(&envelope), vec![section("s0"), section("new-section"), section("s1"), section("s2")]); + assert!(envelope.quarantine.is_empty()); + encode(&envelope, &all).unwrap(); +} + +#[test] +fn a_new_whole_section_episode_uses_the_latest_saved_complete_section_order() { + let fallback = persistence_fallback(); + let all = future_registry(&["a", "b", "c"]); + let none = future_registry(&[]); + let mut envelope = decode(&serde_json::to_vec(&future_sections()).unwrap(), &none, &fallback).unwrap().envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + envelope.layout.sections.rotate_right(1); + assert_eq!(section_ids(&envelope), vec![section("s2"), section("s0"), section("s1")]); + let reloaded = decode(&encode(&envelope, &all).unwrap(), &none, &fallback).unwrap(); + assert!(reloaded.notice.is_none()); + envelope = reloaded.envelope; + assert_eq!(envelope.section_order, vec![section("s2"), section("s0"), section("s1")]); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(section_ids(&envelope), vec![section("s2"), section("s0"), section("s1")]); + assert_eq!(envelope.section_snapshots[§ion("s0")].data["future_surface"]["keep"], "s0"); +} + +fn future_pair(active: &str) -> serde_json::Value { + let mut raw = future_group(); + raw["layout"]["instances"].as_array_mut().unwrap().retain(|instance| instance["id"] != "c"); + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["a", "b"]); + raw["layout"]["sections"][0]["active"] = serde_json::json!(active); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!({"keep":"opaque section data"}); + raw +} + +#[test] +fn a_new_quarantine_episode_refreshes_saved_tab_order_activation_and_outer_semantics() { + let fallback = persistence_fallback(); + let a = future_registry(&["a"]); + let all = future_registry(&["a", "b"]); + for initial_active in ["a", "b"] { + let mut envelope = decode(&serde_json::to_vec(&future_pair(initial_active)).unwrap(), &a, &fallback).unwrap().envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + let group = envelope.layout.sections.first_mut().unwrap(); + group.tabs = vec![id("b"), id("a")]; + group.active = id("b"); + group.size = size(400.0, 300.0); + group.collapsed = true; + group.location = SectionLocation::Dock { zone: Zone::Right }; + let mut saved: serde_json::Value = serde_json::from_slice(&encode(&envelope, &all).unwrap()).unwrap(); + saved["layout"]["sections"][0]["new_future_field"] = serde_json::json!("latest opaque intent"); + let loaded = decode(&serde_json::to_vec(&saved).unwrap(), &a, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + let memory = &envelope.section_snapshots[§ion("group")]; + assert_eq!(memory.data["tabs"], serde_json::json!(["b", "a"])); + assert_eq!(memory.data["active"], "b"); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); // Generated fallback, not a user edit. + let loaded = decode(&encode(&envelope, &a).unwrap(), &a, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + let group = envelope.layout.sections.first().unwrap(); + assert_eq!(group.tabs, vec![id("b"), id("a")]); + assert_eq!(group.active, id("b")); + assert_eq!(group.size, size(400.0, 300.0)); + assert!(group.collapsed); + assert_eq!(group.location.zone(), Zone::Right); + let memory = &envelope.section_snapshots[§ion("group")]; + assert_eq!(memory.data["future_metadata"]["keep"], "opaque section data"); + assert_eq!(memory.data["new_future_field"], "latest opaque intent"); + assert_eq!(envelope.retained_data[&id("b")]["instance"]["future_draft"], "draft-b"); + encode(&envelope, &all).unwrap(); + } +} + +#[test] +fn mixed_partial_episodes_keep_dormant_members_and_latest_visible_user_choices() { + let fallback = persistence_fallback(); + let a = future_registry(&["a"]); + let a_b = future_registry(&["a", "b"]); + let all = future_registry(&["a", "b", "c"]); + let mut raw = future_group(); + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["a", "b", "c"]); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!({"opaque":true}); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &a_b, &fallback).unwrap().envelope; + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("a"), id("b")]); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); + let group = envelope.layout.sections.first_mut().unwrap(); + group.tabs.reverse(); + group.active = id("b"); + let saved = encode(&envelope, &a_b).unwrap(); + let loaded = decode(&saved, &a, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + assert_eq!(envelope.quarantine.len(), 2); + assert_eq!(envelope.section_snapshots[§ion("group")].data["tabs"], serde_json::json!(["b", "a", "c"])); + assert_eq!(envelope.section_snapshots[§ion("group")].data["active"], "b"); + restore_quarantine(&mut envelope, &a_b).unwrap(); + assert_eq!(envelope.quarantine.len(), 1); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("b"), id("a")]); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("b")); + let mut unchanged = envelope.clone(); + restore_quarantine(&mut unchanged, &all).unwrap(); + assert_eq!(unchanged.layout.sections.first().unwrap().tabs, vec![id("b"), id("a"), id("c")]); + assert_eq!(unchanged.layout.sections.first().unwrap().active, id("b")); + // A direct live edit between restoration stages is authoritative too. + let group = envelope.layout.sections.first_mut().unwrap(); + group.tabs.reverse(); + group.active = id("a"); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("a"), id("b"), id("c")]); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); + assert_eq!(envelope.section_snapshots[§ion("group")].data["future_metadata"]["opaque"], true); + encode(&envelope, &all).unwrap(); +} + +#[test] +fn unchanged_partial_save_does_not_replace_pending_activation_with_a_fallback() { + let fallback = persistence_fallback(); + let a_b = future_registry(&["a", "b"]); + let all = future_registry(&["a", "b", "c"]); + let mut raw = future_group(); + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["a", "b", "c"]); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &a_b, &fallback).unwrap().envelope; + for _ in 0..2 { + let loaded = decode(&encode(&envelope, &a_b).unwrap(), &a_b, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + } + assert_eq!(envelope.section_snapshots[§ion("group")].data["active"], "c"); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("c")); +} + +#[test] +fn earlier_v1_rank_metadata_and_new_order_projection_bounds_are_supported() { + let fallback = persistence_fallback(); + let none = future_registry(&[]); + let all = future_registry(&["a", "b", "c"]); + let envelope = decode(&serde_json::to_vec(&future_sections()).unwrap(), &none, &fallback).unwrap().envelope; + let mut earlier = serde_json::to_value(&envelope).unwrap(); + earlier.as_object_mut().unwrap().remove("section_order"); + for snapshot in earlier["section_snapshots"].as_object_mut().unwrap().values_mut() { + snapshot.as_object_mut().unwrap().remove("projected"); + } + let loaded = decode(&serde_json::to_vec(&earlier).unwrap(), &none, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + let mut restored = loaded.envelope; + restore_quarantine(&mut restored, &all).unwrap(); + assert_eq!(section_ids(&restored), vec![section("s0"), section("s1"), section("s2")]); + let mut duplicate = envelope.clone(); + duplicate.section_order = vec![section("s0"), section("s0")]; + assert_eq!(encode(&duplicate, &none).unwrap_err().rule, Rule::DuplicateId); + let mut excessive = envelope; + excessive.section_order = (0..=MAX_SECTIONS).map(|index| section(&format!("s-{index}"))).collect(); + assert_eq!(encode(&excessive, &none).unwrap_err().rule, Rule::CollectionLimit); + let snapshot = restored.section_snapshots.get_mut(§ion("s0")).unwrap(); + snapshot.projected.as_mut().unwrap().tabs = vec![id("a"); MAX_TABS + 1]; + assert_eq!(encode(&restored, &all).unwrap_err().rule, Rule::CollectionLimit); +} diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs index 10e6343a1..8de8f269f 100644 --- a/crates/engine/src/params.rs +++ b/crates/engine/src/params.rs @@ -1,10 +1,10 @@ //! Helpers to read hostile JSON parameters. use serde_json::Value; +use solidcore_record::{Vec2, Vec3}; use solidcraft_doc::Expr; -use solidcraft_geom::{Vec2, Vec3}; -use crate::{EngineError, Result}; +use crate::{EngineError, Result, kernel}; pub fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.to_string(), msg: msg.into() } @@ -146,21 +146,22 @@ pub fn string_list(cmd: &str, p: &Value, k: &str) -> Result> { /// named by its position as in [`string_list`]. The commands that take feature keys read them /// here, because their list is not a list of names (#6651). pub fn name_or_id_list(cmd: &str, p: &Value, k: &str) -> Result> { + Ok(name_or_id_values(cmd, p, k)?.iter().map(|v| v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string())).collect()) +} + +/// Keep the JSON types when a command distinguishes a numeric name from a numeric id. +pub(crate) fn name_or_id_values<'a>(cmd: &str, p: &'a Value, k: &str) -> Result<&'a [Value]> { match p.get(k) { - None | Some(Value::Null) => Ok(Vec::new()), - Some(Value::String(s)) => Ok(vec![s.clone()]), + None | Some(Value::Null) => Ok(&[]), + Some(v @ Value::String(_)) => Ok(std::slice::from_ref(v)), Some(Value::Array(a)) => { if a.len() > MAX_STRING_LIST { return Err(bad(cmd, format!("`{k}` must list at most {MAX_STRING_LIST} keys"))); } - a.iter() - .enumerate() - .map(|(i, v)| match v { - Value::String(s) => Ok(s.clone()), - Value::Number(n) if n.is_u64() => Ok(n.to_string()), - other => Err(bad(cmd, format!("`{k}` must list names or ids; the entry {} is {}", i + 1, json_brief(other)))), - }) - .collect() + if let Some((i, v)) = a.iter().enumerate().find(|(_, v)| !v.is_string() && !v.is_u64()) { + return Err(bad(cmd, format!("`{k}` must list names or ids; the entry {} is {}", i + 1, json_brief(v)))); + } + Ok(a) } Some(v) => Err(bad(cmd, format!("`{k}` must be a list of names or ids; it is {}", json_brief(v)))), } @@ -180,6 +181,21 @@ pub fn string_list_or_default(p: &Value, k: &str) -> Vec { } } +/// A continuity word (`g0` … `g4`, [`kernel::Continuity::parse`]) for `what` (the key or entry +/// it was given as), refused when it is not a word and when `by` does not build that order: the +/// kernel's [`kernel::Construction`] table says which orders it does. +pub fn continuity(cmd: &str, v: Option<&Value>, what: &str, by: kernel::Construction) -> Result { + let (lowest, highest) = by.orders(); + let g = v + .and_then(Value::as_str) + .and_then(kernel::Continuity::parse) + .ok_or_else(|| bad(cmd, format!("{what} must be {}", kernel::Continuity::words(lowest, highest))))?; + g.built_by(by).map_err(|e| match e { + kernel::KernelError::Invalid(why) => bad(cmd, format!("{what}: {why}")), + other => other.into(), + }) +} + /// Whether any text in `p` is shaped like a definition, `name = expression` (#4071), so the /// design may hold one to store once the command has run (`Document::define_inline`). Looks at /// most a bounded number of values deep into hostile input. diff --git a/crates/engine/src/pattern_suppress_tests.rs b/crates/engine/src/pattern_suppress_tests.rs index 89182fc82..d2bd7382d 100644 --- a/crates/engine/src/pattern_suppress_tests.rs +++ b/crates/engine/src/pattern_suppress_tests.rs @@ -2,6 +2,7 @@ //! pattern says so. use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use crate::Session; @@ -52,15 +53,15 @@ fn enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs() { s.doc.features.iter().find(|feature| feature.name == "USB" && matches!(feature.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap(); assert!((s.model.state().sketch(usb.id).unwrap().plane.origin.y + 35.5).abs() < 1e-6); let assert_material = |session: &Session| { - let state = session.world_state(); + let state = session.world_state().unwrap(); let case = state.body("Case").unwrap().mesh(); let lid = state.body("Lid").unwrap().mesh(); - assert!(case.contains(solidcraft_geom::Vec3::new(-24.5, -21.5, 7.))); - assert!(!case.contains(solidcraft_geom::Vec3::new(-26.5, -21.5, 7.))); - assert!(!case.contains(solidcraft_geom::Vec3::new(-10., -35.25, 11.35))); - assert!(case.contains(solidcraft_geom::Vec3::new(-10., -35.25, 15.))); + assert!(case.contains(solidcore_record::Vec3::new(-24.5, -21.5, 7.))); + assert!(!case.contains(solidcore_record::Vec3::new(-26.5, -21.5, 7.))); + assert!(!case.contains(solidcore_record::Vec3::new(-10., -35.25, 11.35))); + assert!(case.contains(solidcore_record::Vec3::new(-10., -35.25, 15.))); assert!( - lid.contains(solidcraft_geom::Vec3::new(0., 32.2, 29.)), + lid.contains(solidcore_record::Vec3::new(0., 32.2, 29.)), "lid bounds {:?}; lip {:?}; probes {:?}", lid.bounds(), session @@ -78,11 +79,11 @@ fn enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs() { .unwrap() .sketch .links, - (20..35).map(|y| (y, lid.contains(solidcraft_geom::Vec3::new(0., f64::from(y) + 0.2, 29.)))).collect::>() + (20..35).map(|y| (y, lid.contains(solidcore_record::Vec3::new(0., f64::from(y) + 0.2, 29.)))).collect::>() ); - assert!(!lid.contains(solidcraft_geom::Vec3::new(0., 32.9, 29.))); - assert!(!lid.contains(solidcraft_geom::Vec3::new(-33.5, -28.5, 32.))); - assert!(lid.contains(solidcraft_geom::Vec3::new(-31.5, -28.5, 32.))); + assert!(!lid.contains(solidcore_record::Vec3::new(0., 32.9, 29.))); + assert!(!lid.contains(solidcore_record::Vec3::new(-33.5, -28.5, 32.))); + assert!(lid.contains(solidcore_record::Vec3::new(-31.5, -28.5, 32.))); }; assert_material(&s); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); @@ -92,8 +93,8 @@ fn enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs() { #[test] fn enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen() { + use solidcore_record::{Vec2, Vec3}; use solidcraft_doc::FeatureKind; - use solidcraft_geom::{Vec2, Vec3}; use solidcraft_sketch::CurveKind; let mut s = Session::default(); @@ -144,7 +145,7 @@ fn enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen assert!((regions[0].area() - 332.570619298295).abs() < 1e-7, "area {}", regions[0].area()); let ring = solidcraft_kernel::extrude(&solved.plane, ®ions, 0., 2.).unwrap(); assert_eq!(ring.len(), 1); - let precise_ring = ring[0].tessellate(1e-6).unwrap(); + let precise_ring = ring[0].mesh(&solidcraft_kernel::MeshTolerance::chord(1e-6)).unwrap(); let bounds = precise_ring.bounds(); for (actual, expected) in [(bounds.min.x, -37.8), (bounds.max.x, 37.8), (bounds.min.y, -32.8), (bounds.max.y, 32.8), (bounds.min.z, 28.), (bounds.max.z, 30.)] @@ -160,14 +161,14 @@ fn enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen .segs .iter() .map(|segment| match segment { - solidcraft_geom::Seg2::Arc { radius, sweep, .. } => radius.abs() * sweep.abs(), - solidcraft_geom::Seg2::Line { .. } => 0., + solidcore_record::Seg2::Arc { radius, sweep, .. } => radius.abs() * sweep.abs(), + solidcore_record::Seg2::Line { .. } => 0., other => panic!("unexpected ring boundary {other:?}"), }) .sum::(); assert!((arc_perimeter - std::f64::consts::TAU * 0.8).abs() < 1e-8); assert_eq!(regions[0].holes.len(), 1); - assert!(regions[0].holes[0].segs.iter().all(|segment| matches!(segment, solidcraft_geom::Seg2::Line { .. }))); + assert!(regions[0].holes[0].segs.iter().all(|segment| matches!(segment, solidcore_record::Seg2::Line { .. }))); // Body::tessellate floors the requested sag tolerance at size * 1e-6. // Only the outer arcs incur chord error: their tolerance-wide boundary // strip bounds the volume error without changing CAD or export tolerances. @@ -178,7 +179,7 @@ fn enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen (measured - analytic_volume).abs() <= discretization_bound, "ring mesh volume {measured}, analytic {analytic_volume}, bound {discretization_bound}" ); - let lid = state.body("Lid").unwrap().body.tessellate(1e-4).unwrap(); + let lid = state.body("Lid").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap(); for (point, material) in [ (Vec3::new(0., 32.2, 29.), true), (Vec3::new(0., 32.9, 29.), false), diff --git a/crates/engine/src/product_scene.rs b/crates/engine/src/product_scene.rs index c3b763da2..8f53abf48 100644 --- a/crates/engine/src/product_scene.rs +++ b/crates/engine/src/product_scene.rs @@ -20,7 +20,7 @@ pub fn extract_where(s: &Session, keep: impl Fn(&ModelBody) -> bool) -> Result

= MAX_PRODUCT_BODIES { @@ -63,9 +63,9 @@ pub fn extract_where(s: &Session, keep: impl Fn(&ModelBody) -> bool) -> Result

Value { } fn volumes(s: &Session) -> Vec { - s.model.state().bodies.iter().map(|b| b.body.tessellate(1e-2).unwrap().measure().volume).collect() + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume).collect() } fn last_error(s: &Session) -> Option { @@ -68,7 +68,7 @@ fn a_profile_picked_by_curves_follows_a_parameter_change() { if let Some(f) = s.doc_mut().feature_mut(id) && let FeatureKind::Extrude { profiles, .. } = &mut f.kind { - *profiles = ProfileSel::Points { points: vec![solidcraft_geom::Vec2::new(25.0, 10.0)] }; + *profiles = ProfileSel::Points { points: vec![solidcore_record::Vec2::new(25.0, 10.0)] }; } s.refresh(); assert!((volumes(&s)[0] - 6000.0).abs() < 1.0); diff --git a/crates/engine/src/profile_fallback_tests.rs b/crates/engine/src/profile_fallback_tests.rs index 34d84db89..38642a1df 100644 --- a/crates/engine/src/profile_fallback_tests.rs +++ b/crates/engine/src/profile_fallback_tests.rs @@ -18,7 +18,7 @@ fn run(s: &mut Session, id: &str, p: Value) -> Value { } fn volume(s: &Session) -> f64 { - s.model.state().bodies.iter().map(|b| b.body.tessellate(1e-3).unwrap().measure().volume).sum() + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap().measure().volume).sum() } fn result(s: &Session, name: &str) -> (Option, Option) { diff --git a/crates/engine/src/profile_refs_tests.rs b/crates/engine/src/profile_refs_tests.rs index dd38479e6..8cbff001b 100644 --- a/crates/engine/src/profile_refs_tests.rs +++ b/crates/engine/src/profile_refs_tests.rs @@ -41,7 +41,12 @@ fn enclosure() -> Session { } fn bodies(s: &Session) -> Vec<(String, f64)> { - s.model.state().bodies.iter().map(|b| (b.name.clone(), b.body.tessellate(1e-2).unwrap().measure().volume)).collect() + s.model + .state() + .bodies + .iter() + .map(|b| (b.name.clone(), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume)) + .collect() } #[test] @@ -61,16 +66,16 @@ fn a_port_picked_by_index_stays_a_cut_after_a_width_change() { assert!(s.model.result(id).is_some_and(|r| r.error.is_none()), "{:?}", s.model.result(id)); let port = s.doc.find_feature("USB port").unwrap().id; assert!((s.model.state().sketch(port).unwrap().plane.origin.x - 50.).abs() < 1e-6); - let world = s.world_state(); + let world = s.world_state().unwrap(); let mesh = world.body("Enclosure").unwrap().mesh(); - assert!(!mesh.contains(solidcraft_geom::Vec3::new(49., 0., 12.))); - assert!(mesh.contains(solidcraft_geom::Vec3::new(49., 0., 20.))); + assert!(!mesh.contains(solidcore_record::Vec3::new(49., 0., 12.))); + assert!(mesh.contains(solidcore_record::Vec3::new(49., 0., 20.))); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!(reopened.model.result(id).unwrap().error.is_none()); - let world = reopened.world_state(); + let world = reopened.world_state().unwrap(); let mesh = world.body("Enclosure").unwrap().mesh(); - assert!(!mesh.contains(solidcraft_geom::Vec3::new(49., 0., 12.))); - assert!(mesh.contains(solidcraft_geom::Vec3::new(49., 0., 20.))); + assert!(!mesh.contains(solidcore_record::Vec3::new(49., 0., 12.))); + assert!(mesh.contains(solidcore_record::Vec3::new(49., 0., 20.))); } /// A pick the sketch no longer has is an error on the feature, never a different profile. diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index ad12d7c41..ddb65cbd3 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -281,6 +281,14 @@ impl Autosaver { Ok(true) } + /// Whether the last autosave holds `s` as it is now, with no write still running: what a + /// crash now would leave for the next launch to offer. A finished write counts once a + /// [`Self::tick`] has taken its outcome. + pub fn caught_up(&self, s: &Session) -> bool { + self.writing.is_none() + && self.last.as_ref().is_some_and(|(doc, visibility)| (Arc::ptr_eq(doc, &s.doc) || **doc == *s.doc) && *visibility == s.visibility) + } + /// Autosave when the interval has passed, or right away after a big operation. The design /// is written on a worker thread; true when this call started a write. pub fn tick(&mut self, s: &Session, big: bool) -> Result { @@ -464,6 +472,19 @@ mod tests { d } + /// Ticks (bounded) until the autosave a tick started has been written and taken up, as the + /// app's own frames would. A tick right after the one that started a write can find it still + /// running under load and take nothing up, so a test that then changes the session (marking + /// it saved) and checks the files would race the worker. + fn tick_until_caught_up(a: &mut Autosaver, s: &Session) { + let began = Instant::now(); + while !a.caught_up(s) { + assert!(began.elapsed() < Duration::from_secs(30), "the autosave never caught up"); + std::thread::sleep(Duration::from_millis(1)); + a.tick(s, false).unwrap(); + } + } + #[test] fn autosave_only_unsaved_changes_and_recover_after_a_crash() { let d = dir("crash"); @@ -686,6 +707,7 @@ mod tests { let mut a = Autosaver::new(&d, Duration::ZERO).unwrap(); s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); assert!(a.tick(&s, false).unwrap()); + tick_until_caught_up(&mut a, &s); s.mark_saved(); a.tick(&s, false).unwrap(); assert!(!file(&d, &a.id, solidcraft_io::DESIGN_EXT).exists()); diff --git a/crates/engine/src/render_jobs.rs b/crates/engine/src/render_jobs.rs index 7ea415311..b7d0d801a 100644 --- a/crates/engine/src/render_jobs.rs +++ b/crates/engine/src/render_jobs.rs @@ -36,6 +36,41 @@ pub(crate) struct Execution { pub executor: solidcraft_render::ExecutorId, pub options: solidcraft_render::job::JobOptions, pub environment: Option, + pub shot: Option, +} + +struct LiveJob { + handle: JobHandle, + shot: Option, +} + +/// Transient completed-image metadata. Neither pixels nor selection enter a design or undo. +#[derive(Clone, Debug, serde::Serialize)] +pub struct RetainedResult { + pub frame: solidcraft_render::job::FrameInfo, + pub shot: Option, + pub seconds: f64, + pub stale: bool, +} + +struct Completed { + handle: JobHandle, + info: RetainedResult, +} + +pub(crate) struct BatchShot { + pub name: String, + pub camera: solidcraft_render::Camera, + pub request: Arc, +} + +#[derive(Clone, Debug, serde::Serialize)] +pub struct RenderQueueState { + pub running: usize, + pub waiting: usize, + pub job: Option, + pub shot: Option, + pub error: Option, } pub(crate) struct Jobs { @@ -45,12 +80,14 @@ pub(crate) struct Jobs { pub(crate) host: Option, pub(crate) descriptor: Option, pub(crate) additional: Vec<(CpuHost, ExecutorDescriptor)>, - live: Vec, + live: Vec, history: VecDeque, - last_good: Option, - /// One explicitly displayed completed result, independent of a newer completion. - /// The existing frame Arc keeps its original host reservation accounted for. - pinned: Option, + completed: VecDeque, + selected: Option, + waiting: VecDeque, + batch_job: Option, + batch_error: Option, + comparison: Option<[Option; 2]>, } impl Default for Jobs { @@ -64,8 +101,12 @@ impl Default for Jobs { additional: Vec::new(), live: Vec::new(), history: VecDeque::new(), - last_good: None, - pinned: None, + completed: VecDeque::new(), + selected: None, + waiting: VecDeque::new(), + batch_job: None, + batch_error: None, + comparison: None, } } } @@ -73,12 +114,26 @@ impl Default for Jobs { impl Drop for Jobs { fn drop(&mut self) { for job in &self.live { - let _ = job.cancel(); + let _ = job.handle.cancel(); } } } impl Jobs { + pub(crate) fn set_comparison(&mut self, sides: Option<[Option; 2]>) { + self.comparison = sides; + if let Some([left, right]) = sides { + self.selected = right.or(left); + } + } + + fn valid_comparison(&self) -> Option<[Option; 2]> { + self.comparison.filter(|sides| sides.iter().flatten().all(|job| self.completed.iter().any(|result| result.handle.id() == *job))) + } + pub(crate) fn has_results(&self) -> bool { + !self.completed.is_empty() || self.live.iter().any(|job| job.handle.frame().ok().flatten().is_some()) + } + pub(crate) fn host_for(&self, executor: &solidcraft_render::ExecutorId) -> Option<&CpuHost> { if executor.as_str() == "cpu-raytrace" { return self @@ -103,14 +158,26 @@ impl Jobs { pub(crate) fn collect(&mut self) -> Result<(), JobError> { let mut i = 0; while i < self.live.len() { - let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.status()?; + let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.handle.status()?; if !status.progress.phase.terminal() { i += 1; continue; } - let handle = self.live.remove(i); - if status.progress.phase == Phase::Completed && self.last_good.as_ref().is_none_or(|old| old.id().serial < handle.id().serial) { - self.last_good = Some(handle); + let job = self.live.remove(i); + if let Some(frame) = status.frame.as_ref().filter(|_| status.progress.phase == Phase::Completed) { + let seconds = job.handle.completed_duration()?.map_or(0.0, |duration| duration.as_secs_f64()); + let completed_id = job.handle.id(); + self.completed.push_back(Completed { + handle: job.handle, + info: RetainedResult { frame: frame.clone(), shot: job.shot, seconds, stale: false }, + }); + while self.completed.len() > 8 { + self.completed.pop_front(); + } + if self.valid_comparison().is_none() { + self.comparison = None; + self.selected = Some(completed_id); + } } self.history.push_back(status); while self.history.len() > 4 { @@ -128,12 +195,19 @@ impl Jobs { replace: bool, execution: Execution, ) -> Result { - let Execution { executor, options, environment } = execution; + let Execution { executor, options, environment, shot } = execution; + if self.batch_job.is_some() { + if !replace { + return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before starting another render")); + } + self.waiting.clear(); + self.batch_job = None; + } self.collect()?; let host = self.host_for(&executor).ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))?.clone(); if replace { for job in self.live.drain(..) { - let mut status = job.cancel()?; + let mut status = job.handle.cancel()?; // Replaced handles are deliberately abandoned: keep a cancellation tombstone, // not a permanently "cancelling" snapshot. The token already prevents any // publication; the host can finish releasing its buffers asynchronously. @@ -165,7 +239,7 @@ impl Jobs { let status = handle.status()?; self.serial = serial; self.generation = generation; - self.live.push(handle); + self.live.push(LiveJob { handle, shot }); Ok(status) } @@ -174,6 +248,9 @@ impl Jobs { source_id: JobId, presentation: solidcraft_render::job::presentation::Presentation, ) -> Result { + if self.batch_job.is_some() { + return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before regrading")); + } self.collect()?; let source = self.handle(source_id)?; let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; @@ -194,7 +271,8 @@ impl Jobs { let status = handle.status()?; self.serial = serial; self.generation = generation; - self.live.push(handle); + let shot = self.completed.iter().find(|result| result.handle.id() == source_id).and_then(|result| result.info.shot.clone()); + self.live.push(LiveJob { handle, shot }); Ok(status) } @@ -209,8 +287,8 @@ impl Jobs { self.check_owner(id)?; self.live .iter() - .chain(self.last_good.iter()) - .chain(self.pinned.iter()) + .map(|job| &job.handle) + .chain(self.completed.iter().map(|result| &result.handle)) .find(|j| j.id() == id) .cloned() .ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) @@ -226,17 +304,35 @@ impl Jobs { } pub(crate) fn pin(&mut self, id: Option) -> Result, JobError> { + self.collect()?; let Some(id) = id else { - self.pinned = None; + self.selected = None; + self.comparison = None; return Ok(None); }; let handle = self.handle(id)?; let frame = handle.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "only a completed result can be pinned"))?; let info = frame.info.clone(); - self.pinned = Some(handle); + self.comparison = None; + self.selected = Some(id); Ok(Some(info)) } + pub(crate) fn result_index(&mut self, index: usize, discard: bool) -> Result<(), JobError> { + self.collect()?; + let id = self.completed.get(index).ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "retained result index is out of bounds"))?.handle.id(); + if discard { + self.completed.remove(index); + if self.selected == Some(id) { + self.selected = self.completed.back().map(|result| result.handle.id()); + } + } else { + self.comparison = None; + self.selected = Some(id); + } + Ok(()) + } + pub(crate) fn frame(&mut self, id: JobId) -> Result, JobError> { self.collect()?; self.handle(id)?.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "render has no completed image")) @@ -244,6 +340,126 @@ impl Jobs { } impl crate::Session { + pub fn render_comparison(&self) -> Option<[Option; 2]> { + self.render_jobs.valid_comparison() + } + + pub fn render_queue_state(&self) -> RenderQueueState { + let active = self.render_jobs.batch_job.and_then(|id| self.render_jobs.live.iter().find(|job| job.handle.id() == id)); + RenderQueueState { + running: self.render_jobs.live.iter().filter(|job| job.handle.status().is_ok_and(|status| !status.progress.phase.terminal())).count(), + waiting: self.render_jobs.waiting.len(), + job: self.render_jobs.batch_job, + shot: active.and_then(|job| job.shot.clone()), + error: self.render_jobs.batch_error.clone(), + } + } + + pub fn render_batch_ready(&self) -> std::result::Result<(), String> { + if self.doc.render.setups.is_empty() { + return Err("no saved shots to render".into()); + } + if self.doc.render.setups.len() > 32 { + return Err("render all shots is limited to 32 shots".into()); + } + if self.render_jobs.batch_job.is_some() || self.render_queue_state().running != 0 { + return Err("a render or shot queue is already active".into()); + } + Ok(()) + } + + pub(crate) fn start_render_batch(&mut self, shots: VecDeque) -> crate::Result { + self.render_batch_ready().map_err(crate::EngineError::Other)?; + if shots.is_empty() || shots.len() > 32 { + return Err(crate::EngineError::Other("shot queue must contain 1..32 shots".into())); + } + let queued = shots.len(); + self.render_jobs.waiting = shots; + self.render_jobs.batch_error = None; + self.start_next_batch_shot()?; + Ok(queued) + } + + fn start_next_batch_shot(&mut self) -> crate::Result<()> { + let Some(shot) = self.render_jobs.waiting.pop_front() else { return Ok(()) }; + let result: crate::Result<()> = (|| { + let mut params = (*shot.request).clone(); + let settings = params + .get_mut("settings") + .and_then(serde_json::Value::as_object_mut) + .ok_or_else(|| crate::EngineError::Other("queued render settings are missing".into()))?; + settings.insert("camera".into(), serde_json::json!(shot.camera)); + let reply = self.execute("render.start", ¶ms)?; + let job: JobId = serde_json::from_value(reply.get("job").cloned().unwrap_or_default()) + .map_err(|error| crate::EngineError::Other(format!("invalid queued render identity: {error}")))?; + self.label_render_job(job, &shot.name)?; + self.render_jobs.batch_job = Some(job); + Ok(()) + })(); + if let Err(error) = &result { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_error = Some(error.to_string()); + } + result + } + + /// Non-blocking queue scheduling. The existing host still owns all render work. + pub fn advance_render_batch(&mut self) -> crate::Result<()> { + let Some(job) = self.render_jobs.batch_job else { return Ok(()) }; + let status = self.render_jobs.status(job).map_err(job_error)?; + if !status.progress.phase.terminal() { + return Ok(()); + } + self.render_jobs.batch_job = None; + if status.progress.phase != Phase::Completed { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_error = status.error.map(|error| error.to_string()); + return Ok(()); + } + self.start_next_batch_shot() + } + + pub(crate) fn cancel_render_batch(&mut self, job: JobId) { + if self.render_jobs.batch_job == Some(job) { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_job = None; + } + } + + /// Capture the UI draft's label alongside an unnamed active request, never in the design. + pub fn label_render_job(&mut self, id: JobId, shot: &str) -> crate::Result<()> { + solidcraft_doc::render_settings::RenderSettings::validate_name(shot).map_err(|error| crate::EngineError::Other(error.to_string()))?; + let job = self + .render_jobs + .live + .iter_mut() + .find(|job| job.handle.id() == id) + .ok_or_else(|| job_error(JobError::new(ErrorCode::UnknownJob, "render job is no longer active")))?; + if job.shot.is_none() { + job.shot = Some(shot.to_owned()); + } + Ok(()) + } + + /// Oldest first, capped at eight. Staleness follows the current design revision. + pub fn render_retained_results(&mut self) -> crate::Result> { + self.render_jobs.collect().map_err(job_error)?; + Ok(self + .render_jobs + .completed + .iter() + .map(|result| { + let mut info = result.info.clone(); + info.stale = info.frame.scene_generation != self.revision; + info + }) + .collect()) + } + + pub fn render_selected_result(&self) -> Option { + self.render_jobs.selected + } + /// A host is installed by the application, never by document data or a command. pub fn set_render_job_host(&mut self, host: Option) -> crate::Result<()> { if self.render_jobs.host.as_ref().zip(host.as_ref()).is_some_and(|(a, b)| a.same_host(b)) { @@ -350,7 +566,7 @@ mod displayed_result_tests { panic!("bounded result fixture did not finish") } #[test] - fn explicit_display_pin_preserves_the_old_exact_frame_without_unbounded_history() { + fn explicit_display_pin_selects_exact_bytes_within_bounded_retention() { let mut s = crate::Session::default(); let host = CpuHost::cooperative(); s.set_render_job_host(Some(host.clone())).unwrap(); @@ -368,10 +584,11 @@ mod displayed_result_tests { let foreign = JobId { session: old.session + 1, ..old }; assert!(s.execute("render.result.pin", &json!({"job":foreign})).is_err()); assert_eq!(host.admitted_bytes(), retained); - assert!(s.execute("render.result.pin", &json!({})).is_err()); + assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(s.render_selected_result())); s.execute("render.result.pin", &json!({"job":null})).unwrap(); - assert!(s.render_job_handle(old).is_err()); - assert!(host.admitted_bytes() < retained); + assert!(s.render_selected_result().is_none()); + assert!(s.render_job_handle(old).is_ok(), "clearing selection does not discard retained results"); + assert_eq!(host.admitted_bytes(), retained); assert_eq!(s.doc.to_json(), before); assert_eq!(s.undo.len(), undo); let reply = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); diff --git a/crates/engine/src/render_lights.rs b/crates/engine/src/render_lights.rs index 2014637c5..fa48f4135 100644 --- a/crates/engine/src/render_lights.rs +++ b/crates/engine/src/render_lights.rs @@ -1,7 +1,8 @@ //! Shared light inspection and numerical adapters; no document or view-state mutation. use crate::schema::render_lights::{Geometry, Light}; +use solidcore_record::Vec3; use solidcraft_doc::render_settings::{RenderJob, RenderSetup}; -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_render::job::LightingPreset; use solidcraft_render::job::{AreaLight, AreaLights, DirectionalLightOptions, PunctualLightOptions, RectangleLightOptions, SpotConeOptions, Sun}; diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 1bec6eb25..877beb056 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -161,33 +161,56 @@ mod tests { assert!(session.model.results.iter().all(|result| result.error.is_none())); assert!((session.model.state().sketch(boss).unwrap().plane.origin.z - 12.).abs() < 1e-6); assert!((session.model.state().sketch(bore).unwrap().plane.origin.z - 26.).abs() < 1e-6); - let world = session.world_state(); + let world = session.world_state().unwrap(); let plate = world.body("Plate").unwrap().mesh(); assert!((plate.bounds().max.z - 26.).abs() < 1e-6); - assert!(plate.contains(solidcraft_geom::Vec3::new(5., 25., 10.))); - assert!(plate.contains(solidcraft_geom::Vec3::new(40., 35., 24.))); - assert!(!plate.contains(solidcraft_geom::Vec3::new(40., 25., 24.))); - assert!(!plate.contains(solidcraft_geom::Vec3::new(40., 25., 2.))); - assert!(plate.contains(solidcraft_geom::Vec3::new(40., 35., 2.))); + assert!(plate.contains(solidcore_record::Vec3::new(5., 25., 10.))); + assert!(plate.contains(solidcore_record::Vec3::new(40., 35., 24.))); + assert!(!plate.contains(solidcore_record::Vec3::new(40., 25., 24.))); + assert!(!plate.contains(solidcore_record::Vec3::new(40., 25., 2.))); + assert!(plate.contains(solidcore_record::Vec3::new(40., 35., 2.))); let reopened = crate::Session::new(solidcraft_doc::Document::from_json(&session.doc.to_json()).unwrap()); assert!((reopened.model.state().sketch(bore).unwrap().plane.origin.z - 26.).abs() < 1e-6); - let reopened_world = reopened.world_state(); + let reopened_world = reopened.world_state().unwrap(); let reopened_plate = reopened_world.body("Plate").unwrap().mesh(); - assert!(!reopened_plate.contains(solidcraft_geom::Vec3::new(40., 25., 2.))); - assert!(reopened_plate.contains(solidcraft_geom::Vec3::new(40., 35., 2.))); + assert!(!reopened_plate.contains(solidcore_record::Vec3::new(40., 25., 2.))); + assert!(reopened_plate.contains(solidcore_record::Vec3::new(40., 35., 2.))); } - /// Every built-in sample builds without a failing feature or joint. + /// Every built-in sample builds without a failing feature or joint, and without a panic on + /// the way: panics inside the kernel are caught natively, but abort the web build (wasm + /// can't unwind; the Plastic Enclosure's bosses used to panic 8 times). #[test] - fn samples_build_cleanly() { + fn samples_build_cleanly_without_panics() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + let me = std::thread::current().id(); + let count = Arc::new(AtomicUsize::new(0)); + let seen = count.clone(); + let prev = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |_| { + if std::thread::current().id() == me { + seen.fetch_add(1, Ordering::SeqCst); + } + })); + let mut failed = Vec::new(); for s in super::samples() { let mut session = crate::Session::default(); - if let Err(e) = session.run_script(&(s.script)()) { - panic!("{}: {e}", s.name); + let built = session.run_script(&(s.script)()); + let panics = count.swap(0, Ordering::SeqCst); + if panics > 0 { + failed.push(format!("{}: {panics} panic(s)", s.name)); + } + if let Err(e) = built { + failed.push(format!("{}: {e}", s.name)); + continue; + } + failed.extend(session.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| format!("{}: {}: {e}", s.name, r.name)))); + if session.model.state().bodies.is_empty() { + failed.push(format!("{}: no bodies", s.name)); } - let failed: Vec = session.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| format!("{}: {e}", r.name))).collect(); - assert!(failed.is_empty(), "{}: {failed:?}", s.name); - assert!(!session.model.state().bodies.is_empty(), "{}", s.name); } + std::panic::set_hook(prev); + assert!(failed.is_empty(), "{failed:?}"); } } diff --git a/crates/engine/src/schema/appearance.rs b/crates/engine/src/schema/appearance.rs new file mode 100644 index 000000000..ef18ad14f --- /dev/null +++ b/crates/engine/src/schema/appearance.rs @@ -0,0 +1,384 @@ +//! Contracts and result types for the appearance commands in `cmd/inspect.rs`: +//! `appearance.assign`, `appearance.library` and `appearance.list`. + +use std::borrow::Cow; +use std::collections::BTreeMap; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Value, json}; +use solidcraft_doc::appearance::Look; +use solidcraft_doc::pbr_appearance::PbrParameters; + +use super::check::whole; +use super::types::{Point3, StringList}; +use crate::params; + +/// Give bodies, faces or components a look, or clear theirs: a library appearance or a starter +/// recipe by `appearance`, or a `color`. With neither (or `color: null`) the targets' own looks +/// are cleared, so a face follows its body, a body its component and a component its material. +/// One undo step; no dialogs. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppearanceAssignParams { + /// Bodies, by name (a placed copy's name, `KB (K:2)`, means the body it shows). + #[serde(default)] + pub bodies: Option, + /// Faces, by a point on each, at most 10000. + #[serde(default)] + pub faces: Option, + /// The body the `faces` points are on, for points that don't name one. Default: the + /// nearest body with a face there. + #[serde(default)] + pub body: Option, + /// Components, by name or id, or a placement's name (`K:2`). + #[serde(default)] + pub components: Option, + /// A library appearance's name or a starter recipe's name or stable `starter.*` id (see + /// `appearance.library`). With `color` too, that colour under this name. A recipe that + /// needs refraction (the glass ones) is refused. + #[serde(default)] + pub appearance: Option, + /// The colour, `"#rrggbb"` or `[r, g, b]` (0–255); with `appearance`, it replaces the + /// recipe's colour. `null` (without `appearance`) clears the targets' looks. + #[serde(default)] + pub color: Option, + /// 0 (clear) to 1 (opaque). Default: 1, or the appearance's own. With `color` alone it + /// must be within 0–1; with `appearance` it is clamped there. + #[serde(default)] + pub opacity: Option, + /// A label for a copied look: needs `color`, not with `appearance`. + #[serde(default)] + pub name: Option, + /// The opaque PBR response (needs `color` or `appearance`, and opacity 1). Left out, a + /// recipe keeps its own; `null` clears it. + #[serde(default)] + pub pbr: Option, +} + +/// `appearance.assign`'s `faces`: at most 10000 points, each `[x, y, z]` (or `{x, y, z}`) or +/// `{"point": [x, y, z], "body": name}`, read as the handler reads them. +#[derive(Clone, Debug, PartialEq)] +pub struct FaceSpots(pub Vec); + +impl<'de> Deserialize<'de> for FaceSpots { + fn deserialize>(d: D) -> Result { + let fail = || D::Error::custom("must list points [x, y, z]"); + let list = match Value::deserialize(d)? { + Value::Array(list) if list.len() <= 10_000 => list, + _ => return Err(fail()), + }; + let point = |v: &Value| params::vec3(v).or_else(|| v.get("point").and_then(params::vec3)); + if list.iter().all(|v| point(v).is_some()) { Ok(FaceSpots(list)) } else { Err(fail()) } + } +} + +impl JsonSchema for FaceSpots { + fn schema_name() -> Cow<'static, str> { + "FaceSpots".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + let on_body = json!({ + "type": "object", + "properties": {"point": point, "body": {"type": "string"}}, + "required": ["point"] + }); + json_schema!({ + "description": "Points in mm, one on each face: [x, y, z], or {\"point\": [x, y, z], \"body\": name} to say which body.", + "type": "array", + "items": {"anyOf": [point, on_body]}, + "maxItems": 10000 + }) + } +} + +/// A colour, `"#rrggbb"` (the `#` optional) or `[r, g, b]` of numbers 0–255, as +/// `inspect::color_param` reads it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ColorParam(pub [u8; 3]); + +impl<'de> Deserialize<'de> for ColorParam { + fn deserialize>(d: D) -> Result { + crate::cmd::inspect::color_param(&Value::deserialize(d)?) + .map(ColorParam) + .ok_or_else(|| D::Error::custom("must be \"#rrggbb\" or [r, g, b] with values 0–255")) + } +} + +impl JsonSchema for ColorParam { + fn schema_name() -> Cow<'static, str> { + "Color".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let channel = json!({"type": "number", "minimum": 0, "maximum": 255}); + json_schema!({ + "description": "A colour: \"#rrggbb\" or [r, g, b] with values 0–255.", + "anyOf": [ + {"type": "string", "pattern": "^#?[0-9A-Fa-f]{6}$"}, + {"type": "array", "items": channel, "minItems": 3, "maxItems": 3} + ] + }) + } +} + +/// A copied look's label: 1 to 128 characters, none of them a control character. +#[derive(Clone, Debug, PartialEq)] +pub struct LookLabel(pub String); + +impl<'de> Deserialize<'de> for LookLabel { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) if !s.is_empty() && s.chars().count() <= 128 && !s.chars().any(char::is_control) => Ok(LookLabel(s)), + _ => Err(D::Error::custom("must be a nonempty label of at most 128 characters without controls")), + } + } +} + +impl JsonSchema for LookLabel { + fn schema_name() -> Cow<'static, str> { + "LookLabel".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A label for a copied look, without control characters.", + "type": "string", + "minLength": 1, + "maxLength": 128 + }) + } +} + +/// An opaque PBR response, exactly `metallic`, `roughness` and `dielectric_ior`, checked as +/// the handler checks it (`attach_pbr`), with its messages. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PbrParam(pub PbrParameters); + +impl<'de> Deserialize<'de> for PbrParam { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + let object = value + .as_object() + .filter(|o| o.len() == 3 && o.keys().all(|k| matches!(k.as_str(), "metallic" | "roughness" | "dielectric_ior"))) + .ok_or_else(|| D::Error::custom(whole("`pbr` requires exactly metallic, roughness and dielectric_ior")))?; + let number = |key: &str| { + object.get(key).and_then(Value::as_f64).ok_or_else(|| D::Error::custom(whole(format!("`pbr.{key}` must be a finite number")))) + }; + PbrParameters::new(number("metallic")?, number("roughness")?, number("dielectric_ior")?).map(PbrParam).map_err(|e| D::Error::custom(whole(e))) + } +} + +impl JsonSchema for PbrParam { + fn schema_name() -> Cow<'static, str> { + "PbrParameters".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "An opaque PBR response.", + "type": "object", + "properties": { + "metallic": {"type": "number", "minimum": 0, "maximum": 1}, + "roughness": {"type": "number", "minimum": 0.045, "maximum": 1}, + "dielectric_ior": {"type": "number", "minimum": 1, "maximum": 3} + }, + "required": ["metallic", "roughness", "dielectric_ior"], + "additionalProperties": false + }) + } +} + +/// A look's PBR response, as the appearance commands report it. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +pub struct PbrReply { + pub metallic: f64, + pub roughness: f64, + pub dielectric_ior: f64, +} + +impl From for PbrReply { + fn from(p: PbrParameters) -> Self { + PbrReply { metallic: p.metallic(), roughness: p.roughness(), dielectric_ior: p.dielectric_ior() } + } +} + +/// A look, as the appearance commands report it. +#[derive(Clone, Debug, Serialize, JsonSchema)] +pub struct LookReply { + /// The library appearance's or recipe's name, or the look's label (`Custom` for a plain + /// colour). + pub name: String, + /// `"#rrggbb"`. + pub color: String, + /// 0 (clear) to 1 (opaque). + pub opacity: f64, + /// Its opaque PBR response, when it has one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pbr: Option, +} + +impl From<&Look> for LookReply { + fn from(l: &Look) -> Self { + LookReply { name: l.name.clone(), color: l.hex(), opacity: l.opacity, pbr: l.pbr.map(PbrReply::from) } + } +} + +/// A face with a look of its own: its body and the point on it the look was given at. +#[derive(Clone, Debug, Serialize, JsonSchema)] +pub struct FaceSpot { + pub body: String, + /// `[x, y, z]` in mm. + pub point: [f64; 3], +} + +/// What `appearance.assign` returns: the targets, and the look they got (`null`: cleared). +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppearanceAssignResult { + pub bodies: Vec, + pub faces: Vec, + /// The components, by id. + pub components: Vec, + pub appearance: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// `appearance.library` takes no parameters. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppearanceLibraryParams {} + +/// What `appearance.library` returns: every appearance `appearance.assign` takes by name. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppearanceLibraryResult { + pub appearances: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One library entry: a plain appearance or finish, or a starter recipe. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum LibraryAppearance { + Plain(PlainAppearance), + Starter(StarterAppearance), +} + +/// A legacy scalar appearance, or an opaque PBR finish (which has `pbr`). +#[derive(Debug, Serialize, JsonSchema)] +pub struct PlainAppearance { + #[serde(flatten)] + pub look: LookReply, + /// The part of the name before ` - `, such as `Aluminum`. + pub category: String, +} + +/// A starter recipe: its look, where it comes from and what showing it needs. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StarterAppearance { + /// Its stable id, `starter.*`, which `appearance.assign` takes as `appearance`. + pub id: String, + pub name: String, + /// wood, metal, plastic, glass, solar or regolith. + pub category: Value, + pub revision: u32, + /// Its preview colour, `"#rrggbb"`. + pub color: String, + pub opacity: f64, + /// Its opaque PBR response; `null` for a recipe that has none (glass). + pub pbr: Option, + /// False for a recipe this build can't show (the glass ones need refraction). + pub available: bool, + /// What showing it needs: opaque_pbr, refraction, certified_thin_or_closed. + pub requirements: Value, + /// Who made it and under which licence: {author, license, source, kind}. + pub provenance: Value, + /// Its optical recipe: {kind: opaque, color, metallic, roughness, dielectric_ior} or + /// {kind: glass, dielectric_ior, transmission_linear_rgb, reference_path_mm, boundary}. + pub recipe: Value, + pub preview_note: String, + /// The texture it is meant to get later ({id, repeat_mm, grain_axis}), or `null`. + pub future_texture_recipe: Value, +} + +/// `appearance.list` takes one parameter, `body`, optional. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppearanceListParams { + /// A body (or a placed copy's name, `KB (K:2)`, for the body it shows): the reply adds + /// `body`, its resolved look and its faces' looks. + #[serde(default)] + pub body: Option, +} + +/// What `appearance.list` returns: the looks the design assigns, by look and by target. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppearanceListResult { + /// Each look the design uses, with where it is used. + pub in_design: Vec, + /// The bodies with a look of their own, by name. + pub bodies: BTreeMap, + /// The faces with a look of their own. + pub faces: Vec, + /// The components with a look of their own. + pub components: Vec, + /// With `body`: that body's resolved look and its faces'. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A look the design uses, and the bodies, faces and components it is given to. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LookInDesign { + #[serde(flatten)] + pub look: LookReply, + pub bodies: Vec, + pub faces: Vec, + /// Components, by id. + pub components: Vec, +} + +/// A face's own look. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FaceLookReply { + pub body: String, + /// `[x, y, z]` in mm: the point the look was given at. + pub point: [f64; 3], + pub appearance: LookReply, +} + +/// A component's own look. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ComponentLookReply { + /// The component's id. + pub component: u64, + pub appearance: LookReply, +} + +/// A body's resolved look and its faces' looks. +#[derive(Debug, Serialize, JsonSchema)] +pub struct BodyLooks { + pub name: String, + /// The look it shows (its own, else its component's, else its material's), or `null`. + pub appearance: Option, + /// The colour it is drawn in, `[r, g, b]` from 0 to 1, or `null` for the default. + pub color: Option<[f32; 3]>, + /// Its faces with a look (their own or imported), by face index. + pub faces: Vec, +} + +/// A face's look, by the face's index in `model.faces`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FaceIndexLook { + pub face: usize, + pub appearance: LookReply, +} + +#[cfg(test)] +#[path = "appearance_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/appearance_tests.rs b/crates/engine/src/schema/appearance_tests.rs new file mode 100644 index 000000000..c25e7aa12 --- /dev/null +++ b/crates/engine/src/schema/appearance_tests.rs @@ -0,0 +1,82 @@ +use serde_json::{Value, json}; + +use super::{ + AppearanceAssignParams, AppearanceAssignResult, AppearanceLibraryParams, AppearanceLibraryResult, AppearanceListParams, AppearanceListResult, +}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys( + input_schema_for::(), + &["appearance", "bodies", "body", "color", "components", "faces", "name", "opacity", "pbr"], + ); + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &["body"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("appearance.assign", json!({"faces": [[1, 2]]})), + ("appearance.assign", json!({"faces": [{"body": "Box1"}]})), + ("appearance.assign", json!({"color": "red"})), + ("appearance.assign", json!({"color": [0, 128, 300]})), + ("appearance.assign", json!({"color": "#ff0000", "name": ""})), + ("appearance.assign", json!({"color": "#ff0000", "pbr": {"metallic": 1}})), + ("appearance.assign", json!({"color": "#ff0000", "pbr": {"metallic": "1", "roughness": 0.5, "dielectric_ior": 1.5}})), + ("appearance.assign", json!({"color": "#ff0000", "pbr": {"metallic": 2, "roughness": 0.5, "dielectric_ior": 1.5}})), + ]); +} + +/// A library look, a starter recipe, a colour with PBR on a face, a cleared body, the library +/// and the list with and without `body`, in Warn: each reply matches its output schema and +/// carries no warning; a misspelt key's warning still matches. +#[test] +fn replies_match_the_output_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: schemars::Schema, id: &str, reply: &Value| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}"); + }; + let assigned = |reply: &Value| { + assert!(reply.get("param_warnings").is_none(), "{reply}"); + matches(output_schema_for::(), "appearance.assign", reply); + }; + let made = run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 0]})); + let body = made["created_bodies"][0].as_str().unwrap_or_default().to_string(); + let library = run("appearance.library", json!({})); + assert!(library.get("param_warnings").is_none(), "{library}"); + matches(output_schema_for::(), "appearance.library", &library); + let entries = library["appearances"].as_array().cloned().unwrap_or_default(); + let named = |pick: &dyn Fn(&Value) -> bool| entries.iter().find(|e| pick(e)).and_then(|e| e["name"].as_str()).unwrap_or_default().to_string(); + let plain = named(&|e| e.get("id").is_none() && e.get("pbr").is_none()); + let finish = named(&|e| e.get("id").is_none() && e.get("pbr").is_some()); + let starter = entries.iter().find(|e| e["available"] == true).and_then(|e| e["id"].as_str()).unwrap_or_default().to_string(); + assert!(!plain.is_empty() && !finish.is_empty() && !starter.is_empty(), "{library}"); + assigned(&run("appearance.assign", json!({"bodies": [body], "appearance": plain, "opacity": 0.5}))); + assigned(&run("appearance.assign", json!({"bodies": body, "appearance": finish}))); + assigned(&run("appearance.assign", json!({"bodies": [body], "appearance": starter}))); + let face = run( + "appearance.assign", + json!({"faces": [{"point": [5, 5, 10], "body": body}], "color": [200, 40, 40], "name": "Signal red", + "pbr": {"metallic": 0, "roughness": 0.4, "dielectric_ior": 1.5}}), + ); + assert_eq!(face["faces"][0]["point"], json!([5.0, 5.0, 10.0]), "{face}"); + assigned(&face); + let all = run("appearance.list", json!({})); + assert!(all.get("param_warnings").is_none() && all.get("body").is_none(), "{all}"); + matches(output_schema_for::(), "appearance.list", &all); + let one = run("appearance.list", json!({"body": body})); + assert_eq!(one["body"]["faces"].as_array().map(Vec::len), Some(1), "{one}"); + matches(output_schema_for::(), "appearance.list", &one); + let cleared = run("appearance.assign", json!({"bodies": [body]})); + assert!(cleared["appearance"].is_null(), "{cleared}"); + assigned(&cleared); + let warned = run("appearance.list", json!({"bodyy": body})); + assert!(warned["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{warned}"); + matches(output_schema_for::(), "appearance.list", &warned); +} diff --git a/crates/engine/src/schema/bom.rs b/crates/engine/src/schema/bom.rs index a5f190f91..59cc95111 100644 --- a/crates/engine/src/schema/bom.rs +++ b/crates/engine/src/schema/bom.rs @@ -1,12 +1,14 @@ -//! Contracts and result types for the commands in `cmd/bom.rs`. +//! Contracts and result types for the commands in `cmd/bom.rs` (#11075). use std::borrow::Cow; +use std::collections::BTreeMap; use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; -use serde::de::Error; +use serde::de::Error as _; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; use solidcraft_doc::BomType; +use solidcraft_doc::bom::View; use super::check::whole; use super::types::{IdOrName, present}; @@ -85,6 +87,227 @@ pub struct OccurrenceBomTypeResult { pub param_warnings: Vec, } +/// The bill of materials below a component: its parts, counted through subassemblies, by part +/// number. Each placement counts as its occurrence's bom type, else its component's: a phantom has +/// no row (what it holds counts where it is placed), a reference counts nowhere, and a purchased or +/// inseparable component is one row. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct BomParams { + /// The component, by id or name (default: the design). + #[serde(default, deserialize_with = "component")] + #[schemars(schema_with = "component_schema")] + pub component: Option, + /// `flat` (the default): every part at any depth, counted through its subassemblies; `top`: + /// the component's direct children, subassemblies as one row each; `all`: as top, each + /// subassembly's own rows listed after it, to any depth. + #[serde(default, deserialize_with = "levels")] + #[schemars(schema_with = "levels_schema")] + pub levels: Option, + /// In all levels, a purchased part's contents listed under it too (default false). + #[serde(default, deserialize_with = "show_purchased_contents")] + pub show_purchased_contents: Option, + #[serde(default)] + pub group_by: Option, + /// A component with a part number is one row, the parts placed inside it listed under it as + /// `children` rather than as rows of their own (default false). + #[serde(default, deserialize_with = "group_children")] + pub group_children: Option, + /// Measure each part: `mass_g` on its row, and `total_mass_g` (default false). + #[serde(default, deserialize_with = "mass")] + pub mass: Option, + /// Also write the bill of materials to this `.csv` or `.json` file (children as items 1.1, + /// 1.2…). + #[serde(default)] + pub path: Option, + /// With `path`: `csv` or `json`, in any case (default: from the path's extension). + #[serde(default)] + pub format: Option, +} + +/// A component's id or name, as the handler reads it, with its message; `null` is none. +fn component<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::Number(n) => Ok(Some(n.to_string())), + Value::String(s) => Ok(Some(s)), + _ => Err(D::Error::custom(whole("`component` must be a component id or name"))), + } +} + +fn component_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "string", "null"]}) +} + +/// A view's word, with the handler's message; `null` is the default view. +fn levels<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::String(l) if View::parse(&l).is_some() => Ok(Some(l)), + _ => Err(D::Error::custom(whole(format!("`levels` is {}", View::ALL.map(View::as_str).join(" or "))))), + } +} + +fn levels_schema(_: &mut SchemaGenerator) -> Schema { + let mut words: Vec = View::ALL.iter().map(|v| Value::from(v.as_str())).collect(); + words.push(Value::Null); + json_schema!({"enum": words}) +} + +/// `true` or `false`, with the handler's message; `null` is `false`. +fn flag<'de, D: Deserializer<'de>>(d: D, key: &str) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::Bool(b) => Ok(Some(b)), + _ => Err(D::Error::custom(whole(format!("`{key}` is true or false")))), + } +} + +fn group_children<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + flag(d, "group_children") +} + +fn mass<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + flag(d, "mass") +} + +fn show_purchased_contents<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + flag(d, "show_purchased_contents") +} + +/// What makes two components one row: `part_number` (the default; components without a part +/// number get a row per definition) or `definition`, as a word or a one-item list, with the +/// handler's messages. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BomGroupBy(pub String); + +impl<'de> Deserialize<'de> for BomGroupBy { + fn deserialize>(d: D) -> Result { + let key = |g: String| match g.as_str() { + "part_number" | "definition" => Ok(BomGroupBy(g)), + o => Err(D::Error::custom(whole(format!("can't group by `{o}` (part_number or definition)")))), + }; + let shape = || D::Error::custom(whole("`group_by` is [\"part_number\"] or [\"definition\"]")); + match Value::deserialize(d)? { + Value::String(g) => key(g), + Value::Array(a) => match <[Value; 1]>::try_from(a) { + Ok([Value::String(g)]) => key(g), + _ => Err(shape()), + }, + _ => Err(shape()), + } + } +} + +impl JsonSchema for BomGroupBy { + fn schema_name() -> Cow<'static, str> { + "BomGroupBy".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let key = serde_json::json!({"enum": ["part_number", "definition"]}); + json_schema!({ + "description": "What makes two components one row: part_number (the default; components without a part number get a row per definition) or definition, as a word or a one-item list.", + "anyOf": [key, {"type": "array", "items": key, "minItems": 1, "maxItems": 1}] + }) + } +} + +/// What `assembly.bom` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Bom { + /// The component listed, by id (0: the design). + pub component: u64, + /// `flat`, `top` or `all`. + pub levels: String, + /// `["part_number"]` or `["definition"]`. + pub group_by: Vec, + pub group_children: bool, + pub show_purchased_contents: bool, + pub mass: bool, + /// With `path`: the file written. + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + /// With `path`: `csv` or `json`. + #[serde(skip_serializing_if = "Option::is_none")] + pub format: Option, + /// The rows, by part number; rows without one after them, by name. In a numbered view each + /// level goes by item number; in all levels each row is followed by the rows under it. + pub rows: Vec, + /// How many occurrences the rows count, children included. + pub total_occurrences: u64, + /// With `mass`: what the assembly weighs, in grams; null when unknown. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_mass_g: Option>, + /// Whether the view's item numbers are saved. + pub numbered: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One row of a bill of materials. +#[derive(Debug, Serialize, JsonSchema)] +pub struct BomRow { + /// Its number: from 1 at the top level, and as text such as `2.1` under another row. + #[schemars(schema_with = "item_schema")] + pub item: Value, + pub part_number: String, + pub description: String, + pub revision: String, + /// `normal`, `phantom`, `purchased` or `inseparable`. + pub bom_type: String, + /// How many are placed. + pub count: u64, + /// The components' names, `; ` between them. + pub definition: String, + /// The physical materials of the definitions' own bodies, `; ` between them. + pub material: String, + /// Under another row: how many are in one of that row's component. + #[serde(skip_serializing_if = "Option::is_none")] + pub each: Option, + /// At the top level: the components' ids. + #[serde(skip_serializing_if = "Option::is_none")] + pub components: Option>, + /// At the top level: their free properties, by name. + #[serde(skip_serializing_if = "Option::is_none")] + pub properties: Option>, + /// With `mass`: what one of the row's parts weighs, in grams; null when unknown. + #[serde(skip_serializing_if = "Option::is_none")] + pub mass_g: Option>, + /// When its definitions have a `bom_quantity`: what its placements add up to; null with + /// `quantity_unknown`. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option>, + /// `pieces` or `mm`. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity_unit: Option, + /// `mixed` (pieces and a length) or `invalid` (a quantity that no longer evaluates). + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity_unknown: Option, + /// In a numbered view, its number isn't saved yet. + #[serde(skip_serializing_if = "Option::is_none")] + pub provisional: Option, + /// A renumber keeps its number. + #[serde(skip_serializing_if = "Option::is_none")] + pub locked: Option, + /// Another row at its level has its number. + #[serde(skip_serializing_if = "Option::is_none")] + pub duplicate: Option, + /// The values typed in for the component, shown in place of the worked-out ones. + #[serde(rename = "static", skip_serializing_if = "Option::is_none")] + pub statics: Option>, + /// The parts placed inside it, listed under it. + #[serde(skip_serializing_if = "Option::is_none")] + pub children: Option>, +} + +fn item_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["integer", "string"]}) +} + #[cfg(test)] #[path = "bom_tests.rs"] mod tests; diff --git a/crates/engine/src/schema/bom_tests.rs b/crates/engine/src/schema/bom_tests.rs index 2ec30c3e4..cc2232a2a 100644 --- a/crates/engine/src/schema/bom_tests.rs +++ b/crates/engine/src/schema/bom_tests.rs @@ -1,6 +1,6 @@ use serde_json::{Value, json}; -use super::{OccurrenceBomTypeParams, OccurrenceBomTypeResult}; +use super::{Bom, BomParams, OccurrenceBomTypeParams, OccurrenceBomTypeResult}; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; @@ -8,6 +8,10 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["bom_type", "occurrence", "path"]); + assert_keys( + input_schema_for::(), + &["component", "format", "group_by", "group_children", "levels", "mass", "path", "show_purchased_contents"], + ); } /// A design with one placed component, `Part:1`. @@ -70,3 +74,82 @@ fn replies_match_the_output_schema() { assert!(!conforms(schema, schema, &bad), "{bad}"); } } + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// As in the command's own tests: a plate placed three times, and a hinge subassembly placed +/// twice that holds one pin. Here the hinge has a part number too, so it can keep its pin. +fn assembly(s: &mut Session) { + run(s, "component.create", json!({"name": "Plate"})); + run(s, "solid.box", json!({"length": 40, "width": 20, "height": 3})); + run(s, "component.activate", json!({"component": 0})); + run(s, "component.create", json!({"name": "Hinge", "activate": false})); + run(s, "component.create", json!({"name": "Pin", "parent": "Hinge"})); + run(s, "solid.cylinder", json!({"diameter": 4, "height": 30})); + run(s, "component.activate", json!({"component": 0})); + for x in [50, 100] { + run(s, "occurrence.copy", json!({"component": "Plate", "translate": [x, 0, 0]})); + } + run(s, "occurrence.copy", json!({"component": "Hinge", "translate": [0, 50, 0]})); + run(s, "component.metadata.set", json!({"component": "Plate", "part_number": "PL-100", "description": "Plate, 3 mm", "revision": "B"})); + run(s, "component.metadata.set", json!({"component": "Pin", "part_number": "PN-040", "properties": {"finish": "zinc"}})); + run(s, "component.metadata.set", json!({"component": "Hinge", "part_number": "HG-1"})); +} + +#[test] +fn strict_keeps_todays_errors_of_a_bill_of_materials() { + let file = std::env::temp_dir().join(format!("solidcraft-bom-schema-{}.csv", std::process::id())); + let file = file.to_string_lossy(); + assert_strict_keeps_todays_errors(&[ + ("assembly.bom", json!({"component": true})), + ("assembly.bom", json!({"component": "Nope"})), + ("assembly.bom", json!({"levels": "deep"})), + ("assembly.bom", json!({"levels": 1})), + ("assembly.bom", json!({"group_by": "size"})), + ("assembly.bom", json!({"group_by": ["size"]})), + ("assembly.bom", json!({"group_by": ["part_number", "definition"]})), + ("assembly.bom", json!({"group_by": [5]})), + ("assembly.bom", json!({"group_by": 5})), + ("assembly.bom", json!({"group_children": "yes"})), + ("assembly.bom", json!({"mass": "yes"})), + ("assembly.bom", json!({"show_purchased_contents": 1})), + ("assembly.bom", json!({"path": file.replace(".csv", ".txt")})), + ("assembly.bom", json!({"path": file, "format": "xml"})), + ]); +} + +/// #11075: a bill of materials replies as its output schema says, in Warn without warnings for +/// good calls and with them for a misspelt key: flat and top, grouped by definition, with the +/// hinge keeping its pin as children, and written to a JSON and a CSV file. +#[test] +fn a_bill_of_materials_replies_with_its_schema() { + let schema = output_schema_for::(); + let matches = |r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + assembly(&mut s); + let r = run(&mut s, "assembly.bom", json!({})); + matches(&r, false); + assert!(r.get("path").is_none() && r["rows"].as_array().is_some_and(|rows| rows.iter().all(|row| row.get("children").is_none())), "{r}"); + matches(&run(&mut s, "assembly.bom", json!({"component": 0, "levels": "top", "group_by": "definition"})), false); + matches(&run(&mut s, "assembly.bom", json!({"levels": "all", "show_purchased_contents": true, "mass": true})), false); + matches(&run(&mut s, "assembly.bom", json!({"group_children": true, "mass": true})), false); + let r = run(&mut s, "assembly.bom", json!({"levels": "flat", "group_by": ["part_number"], "group_children": true})); + matches(&r, false); + let hinge = r["rows"].as_array().and_then(|rows| rows.iter().find(|row| row["part_number"] == "HG-1")).cloned().unwrap_or_default(); + assert_eq!((hinge["children"][0]["part_number"].as_str(), hinge["children"][0]["item"].is_string()), (Some("PN-040"), true), "{r}"); + let dir = std::env::temp_dir(); + for (name, format) in [("json", Value::Null), ("csv", json!("CSV"))] { + let path = dir.join(format!("solidcraft-bom-schema-{}.{name}", std::process::id())).to_string_lossy().into_owned(); + let r = run(&mut s, "assembly.bom", json!({"path": path, "format": format})); + matches(&r, false); + assert_eq!(r["format"], name, "{r}"); + let _ = std::fs::remove_file(&path); + } + matches(&run(&mut s, "assembly.bom", json!({"level": "top"})), true); +} diff --git a/crates/engine/src/schema/browser.rs b/crates/engine/src/schema/browser.rs new file mode 100644 index 000000000..9b76efcff --- /dev/null +++ b/crates/engine/src/schema/browser.rs @@ -0,0 +1,169 @@ +//! Contracts and result types for the commands in `cmd/browser.rs`. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use super::types::{FeatureCommon, LengthExpr, feature_common}; + +/// Repair a part the modelling kernel refuses, or an open part that should be a solid: faces +/// SMLib refuses on their own are rebuilt on their own surfaces (geometry unchanged), free edges +/// that pair up within `gap` are sewn (each sewn edge carries its own gap as its tolerance; the +/// body's and the other edges' stay), and with `patch_holes` the loops of free edges left (missing +/// faces) are patched and sewn in. One undoable feature; refused, with why, when nothing applies. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct RepairParams { + /// The part (body name). + pub body: String, + /// The widest gap between two free edges that is sewn, more than 0 and at most 1 mm. + /// Default: 0.2 mm. + #[serde(default)] + pub gap: Option, + /// Patch each loop of free edges no pair explains (a missing face) and sew the patch in: the + /// plane of the faces around it where they are all that plane, else a patch tangent to them + /// (G1). Default: false (the reply offers the patches). + #[serde(default)] + pub patch_holes: Option, + #[serde(flatten, deserialize_with = "feature_common")] + pub common: FeatureCommon, +} + +/// A face rebuilt on its own surface, or one SMLib still refuses. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairFace { + /// The face's index in the part's face order before the repair (from 0). + pub face: usize, + /// Its surface: plane, cylinder, cone, sphere, torus or freeform. + pub surface: String, + /// What SMLib said about it. + pub why: String, +} + +/// Two free edges sewn into one. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairSewn { + /// The faces on either side, by index before the repair. + pub faces: [usize; 2], + /// The widest distance between the two edges, mm. + pub gap: f64, + /// A point halfway along the gap, [x, y, z]. + pub at: [f64; 3], +} + +/// A loop of free edges no pair explains: a missing face. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairHole { + /// The faces around it, by index before the repair. + pub faces: Vec, + /// g0 (a patch in the plane of the faces around it) or g1 (tangent to curved neighbours). + pub continuity: String, + /// The patch was made and sewn in. + pub patched: bool, + /// Why it was not, when `patch_holes` asked for it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub why: Option, + /// The Patch that fills it: `{command: "surface.patch", params}`. + pub patch: Value, +} + +/// What the repair did, face by face. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairDone { + pub rebuilt: Vec, + /// Faces SMLib refuses that could not be rebuilt (the part may still be taken as a whole). + pub refused: Vec, + pub sewn: Vec, + pub holes: Vec, + /// Faces before and after. + pub faces: [usize; 2], + /// The largest edge tolerance before and after, mm. + pub largest_edge_tolerance: [f64; 2], + /// The part is a closed solid now. + pub closed: bool, + /// The modelling kernel takes the part now. + pub modelling: bool, + /// Its volume, mm³, when it is a closed solid. + pub volume: Option, +} + +/// What `body.repair` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairResult { + /// The new feature's id. + pub feature: u64, + /// The new feature's name. + pub name: String, + /// Every body after the feature. + pub bodies: Vec, + /// The bodies the feature made. + pub created_bodies: Vec, + /// Bodies that were there before and now have other geometry. + pub changed_bodies: Vec, + /// Bodies that are gone. + pub removed_bodies: Vec, + /// A warning from the evaluation (a hole left open), or `null`. + pub warning: Option, + /// How long the feature took to evaluate, in milliseconds. + pub ms: Option, + pub repair: RepairDone, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// The units a design can show lengths in. +pub const DESIGN_UNITS: [&str; 5] = ["mm", "cm", "m", "in", "ft"]; + +/// One of [`DESIGN_UNITS`], with `document.units`' message for anything else. +#[derive(Clone, Debug, PartialEq)] +pub struct DesignUnits(pub String); + +impl<'de> Deserialize<'de> for DesignUnits { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(u) if DESIGN_UNITS.contains(&u.as_str()) => Ok(DesignUnits(u)), + _ => Err(D::Error::custom("must be mm, cm, m, in or ft")), + } + } +} + +impl JsonSchema for DesignUnits { + fn schema_name() -> Cow<'static, str> { + "DesignUnits".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "The units the design shows lengths in.", "type": "string", "enum": DESIGN_UNITS}) + } +} + +/// Change the units the design shows lengths in, and reads a bare number in. Values keep their +/// meaning: a unit-less parameter holding a bare number that lengths read is written with the +/// old unit (`10` becomes `10 mm`) when that keeps those lengths where they were. One undo +/// step; the same units again changes nothing. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct DocumentUnitsParams { + /// The design's new units: mm, cm, m, in or ft. + pub units: DesignUnits, +} + +/// What `document.units` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct DocumentUnitsResult { + /// The design's units now. + pub units: String, + /// The unit-less parameters now written with the old unit, so the lengths that read them + /// stay where they were. Empty when nothing needed it, or the units didn't change. + pub kept: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "browser_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/browser_tests.rs b/crates/engine/src/schema/browser_tests.rs new file mode 100644 index 000000000..07ba23de7 --- /dev/null +++ b/crates/engine/src/schema/browser_tests.rs @@ -0,0 +1,68 @@ +use serde_json::{Value, json}; + +use super::{DocumentUnitsParams, DocumentUnitsResult, RepairParams, RepairResult}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["body", "body_name", "body_names", "gap", "name", "participants", "patch_holes"]); +} + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(!required.contains(&"param_warnings")); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})).unwrap(); + s.execute("surface.unstitch", &json!({"body": "Box", "faces": [[5, 5, 10]]})).unwrap(); + s.param_check = ParamCheck::Warn; + let r = s.execute("body.repair", &json!({"body": "Box", "gap": "0.1 mm", "patch_holes": true, "name": "Mend"})).unwrap(); + assert!(r.get("param_warnings").is_none(), "{r}"); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + let r = s.execute("body.repair", &json!({"body": "Box", "colour": "red"})); + assert!(r.is_err(), "nothing left to repair"); +} + +#[test] +fn units_schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["units"]); +} + +#[test] +fn units_strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[("document.units", json!({})), ("document.units", json!({"units": "furlong"}))]); +} + +/// A change that keeps a parameter's value with the old unit, one that keeps none, and the same +/// units again, in Warn: each reply matches the output schema and carries no warning. +#[test] +fn units_replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let mut run = |p: Value| s.execute("document.units", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + let mut check = |p: Value| { + let reply = run(p.clone()); + assert!(reply.get("param_warnings").is_none() && conforms(schema, schema, &reply), "{p}: {reply} doesn't match {schema}"); + reply + }; + check(json!({"units": "cm"})); + assert_eq!(check(json!({"units": "cm"}))["kept"], json!([])); + check(json!({"units": "in"})); +} + +/// A unit-less parameter a length reads is kept with the old unit, and the reply names it. +#[test] +fn the_reply_names_the_parameters_kept_in_the_old_unit() { + let mut s = Session::default(); + s.execute("parameters.add", &json!({"name": "w", "expression": "10", "unit": ""})).unwrap_or_else(|e| panic!("{e}")); + s.execute("solid.box", &json!({"length": "w", "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + let reply = s.execute("document.units", &json!({"units": "in"})).unwrap_or_else(|e| panic!("{e}")); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + assert_eq!(reply["kept"], json!(["w"]), "{reply}"); +} diff --git a/crates/engine/src/schema/clearance.rs b/crates/engine/src/schema/clearance.rs new file mode 100644 index 000000000..f5e8ca186 --- /dev/null +++ b/crates/engine/src/schema/clearance.rs @@ -0,0 +1,197 @@ +//! Contract and result types for `inspect.clearance` in `cmd/clearance.rs` (#11051). + +use std::borrow::Cow; +use std::collections::BTreeMap; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use super::check::whole; +use super::types::StringList; +use crate::params; + +/// Most neighbours a body's `nearest` list holds. +pub const MAX_NEAREST: usize = 1000; +/// Largest clearance (mm). +pub const MAX_CLEARANCE: f64 = 1e6; + +/// Find the solid bodies that overlap, and those closer than `clearance`, in world placement. +/// Distances are measured on the exact faces and edges; the meshes only rule pairs out. Mesh +/// bodies aren't measured: each is listed in `unchecked`. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ClearanceParams { + /// The bodies to check (default: every solid body but those in `against`). + #[serde(default)] + pub bodies: Option, + /// Only pairs with one body in `bodies` and the other here. + #[serde(default)] + pub against: Option, + /// Smaller overlaps count as contact, in mm³ (default 0.01). + #[serde(default, deserialize_with = "min_volume")] + #[schemars(schema_with = "min_volume_schema")] + pub min_volume: Option, + /// Report pairs closer than this, in mm: 0 to 1 000 000 (default 0). + #[serde(default, deserialize_with = "clearance")] + #[schemars(schema_with = "clearance_schema")] + pub clearance: Option, + /// A gap below this is contact, 0, in mm: 0 to 1 (default 1e-6). + #[serde(default, deserialize_with = "tolerance")] + #[schemars(schema_with = "tolerance_schema")] + pub tolerance: Option, + /// Each body of `bodies` gets its this many nearest others, 0 to 1000 (default 0); a + /// fraction is rounded down. + #[serde(default, deserialize_with = "nearest")] + #[schemars(schema_with = "nearest_schema")] + pub nearest: Option, + #[serde(default)] + pub skip_within: Option, +} + +/// A number from 0 to `max`, read as the handler reads it (`params::num`: finite, under 1e9 in +/// size), with its message; `null` is the default. +macro_rules! up_to { + ($read:ident, $schema:ident, $key:literal, $max:expr) => { + fn $read<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v + .as_f64() + .and_then(params::finite) + .filter(|x| (0.0..=$max).contains(x)) + .map(Some) + .ok_or_else(|| D::Error::custom(whole(format!("`{}` must be a number from 0 to {}", $key, $max)))), + } + } + + fn $schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "null"], "minimum": 0, "maximum": f64::min($max, 1e9), "exclusiveMaximum": 1e9}) + } + }; +} + +up_to!(min_volume, min_volume_schema, "min_volume", f64::MAX); +up_to!(clearance, clearance_schema, "clearance", MAX_CLEARANCE); +up_to!(tolerance, tolerance_schema, "tolerance", 1.0); +up_to!(nearest, nearest_schema, "nearest", MAX_NEAREST as f64); + +/// Pairs not to check: of bodies of one occurrence (`occurrence`), or inside one placed +/// component, its subcomponents included (`component`). `null` checks every pair. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SkipWithin { + Occurrence, + Component, +} + +impl<'de> Deserialize<'de> for SkipWithin { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)?.as_str() { + Some("occurrence") => Ok(SkipWithin::Occurrence), + Some("component") => Ok(SkipWithin::Component), + _ => Err(D::Error::custom(whole("`skip_within` must be \"occurrence\", \"component\" or null"))), + } + } +} + +impl JsonSchema for SkipWithin { + fn schema_name() -> Cow<'static, str> { + "SkipWithin".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "Pairs not to check: of bodies of one occurrence (`occurrence`), or inside one placed component, its subcomponents included (`component`). null checks every pair.", + "enum": ["occurrence", "component", null] + }) + } +} + +/// What `inspect.clearance` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Clearance { + /// Pairs that share at least `min_volume`. + pub overlaps: Vec, + /// Pairs closer than `clearance`, nearest first; a pair in contact is at 0. + pub near: Vec, + /// With `nearest`: each body of `bodies`, with its nearest others. + pub nearest: BTreeMap>, + /// Pairs whose overlap couldn't be worked out, and each mesh body, which isn't measured + /// (`b` is then `null`). + pub unchecked: Vec, + /// How many solid bodies were checked. + pub bodies: usize, + pub pairs_checked: usize, + /// Of those, the pairs measured by an earlier call: neither body changed or moved since. + pub pairs_reused: usize, + /// Pairs ruled out by their boxes. + pub pairs_pruned: usize, + /// Whether there were more pairs than one call measures. + pub truncated: bool, + /// How long it took (ms). + pub ms: f64, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Two bodies that overlap. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Overlap { + pub a: String, + pub b: String, + /// The volume they share (mm³). + pub volume_mm3: f64, + /// The area of the shared volume's surface (mm²). + pub area_mm2: f64, + pub bbox: OverlapBounds, + pub center: [f64; 3], +} + +/// A box, by its corners. +#[derive(Debug, Serialize, JsonSchema)] +pub struct OverlapBounds { + pub min: [f64; 3], + pub max: [f64; 3], +} + +/// Two bodies closer than `clearance`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct NearPair { + pub a: String, + pub b: String, + pub distance_mm: f64, + /// The nearest point on `a`. + pub from: [f64; 3], + /// The nearest point on `b`. + pub to: [f64; 3], + /// For a contact: the volume they share, below `min_volume` (mm³). + #[serde(skip_serializing_if = "Option::is_none")] + pub overlap_mm3: Option, + /// `false` when measured on the meshes; absent when measured on the exact faces and edges. + #[serde(skip_serializing_if = "Option::is_none")] + pub exact: Option, +} + +/// One of a body's nearest others. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Neighbour { + pub body: String, + pub distance_mm: f64, +} + +/// A pair, or a mesh body, that wasn't measured. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Unchecked { + pub a: String, + /// The other body; `null` for a mesh body. + pub b: Option, + pub reason: String, +} + +#[cfg(test)] +#[path = "clearance_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/clearance_tests.rs b/crates/engine/src/schema/clearance_tests.rs new file mode 100644 index 000000000..edce0c205 --- /dev/null +++ b/crates/engine/src/schema/clearance_tests.rs @@ -0,0 +1,62 @@ +use serde_json::{Value, json}; + +use super::{Clearance, ClearanceParams}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["against", "bodies", "clearance", "min_volume", "nearest", "skip_within", "tolerance"]); +} + +/// The handler reads the numbers and `skip_within` before the bodies, so each of these fails +/// the same way on a design with no bodies. +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("inspect.clearance", json!({"min_volume": -1})), + ("inspect.clearance", json!({"min_volume": "x"})), + ("inspect.clearance", json!({"min_volume": 2e9})), + ("inspect.clearance", json!({"clearance": 2e6})), + ("inspect.clearance", json!({"tolerance": 2})), + ("inspect.clearance", json!({"nearest": 1001})), + ("inspect.clearance", json!({"skip_within": "x"})), + ("inspect.clearance", json!({"skip_within": 5})), + ("inspect.clearance", json!({"bodies": ["Nope"]})), + ("inspect.clearance", json!({"against": "Nope"})), + ]); +} + +/// #11051: a clearance check replies as its output schema says, in Warn without warnings for +/// good calls and with them for a misspelt key: two overlapping boxes and a third 2 mm away, +/// checked with every key, and with `against` alone. +#[test] +fn a_clearance_check_replies_with_its_schema() { + let schema = output_schema_for::(); + let matches = |r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [5, 5, 5], "body_name": "B", "operation": "new"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [12, -20, 0], "body_name": "C", "operation": "new"})); + let r = run(&mut s, "inspect.clearance", json!({})); + matches(&r, false); + assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(1), "{r}"); + let r = run( + &mut s, + "inspect.clearance", + json!({"bodies": ["A", "B"], "against": "C", "min_volume": 0.01, "clearance": 30, "tolerance": 1e-6, "nearest": 2, "skip_within": "occurrence"}), + ); + matches(&r, false); + assert!(r["near"].as_array().is_some_and(|n| !n.is_empty()) && r["nearest"]["A"].is_array(), "{r}"); + matches(&run(&mut s, "inspect.clearance", json!({"against": ["A"], "skip_within": null})), false); + matches(&run(&mut s, "inspect.clearance", json!({"clearence": 3})), true); +} diff --git a/crates/engine/src/schema/compare.rs b/crates/engine/src/schema/compare.rs new file mode 100644 index 000000000..75ab197b2 --- /dev/null +++ b/crates/engine/src/schema/compare.rs @@ -0,0 +1,307 @@ +//! Contract and result types for `inspect.compare` in `cmd/compare.rs` (#10994). + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Map, Value}; + +use super::check::whole; + +/// Compare two bodies laid over each other, in world placement: measure both, sample each +/// surface's distance to the other, and find, measure and (with `color`) colour the places where +/// only one of them has material. It works from the two surfaces, without a boolean of the +/// bodies, so near-identical bodies compare too. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CompareParams { + /// The first body, by name. Give both `a` and `b`, or neither: then the two selected bodies, + /// or the design's only two. + #[serde(default, deserialize_with = "body_name")] + pub a: Option, + /// The second body, by name. + #[serde(default, deserialize_with = "body_name")] + pub b: Option, + /// Surfaces closer than this agree, in mm: 0.001 to 10 (default 0.01). + #[serde(default, deserialize_with = "tolerance")] + #[schemars(schema_with = "tolerance_schema")] + pub tolerance: Option, + /// The largest piece of a face sampled as one point, in mm: 0.01 to 1000 (default 0.5), + /// coarser for a body that would need more than `max_points` samples. + #[serde(default, deserialize_with = "spacing")] + #[schemars(schema_with = "spacing_schema")] + pub spacing: Option, + /// The most samples per body: 10 000 to 50 million (default 8 million). + #[serde(default, deserialize_with = "max_points")] + #[schemars(schema_with = "max_points_schema")] + pub max_points: Option, + /// The most regions measured: 1 to 1000 (default 50); more are counted in `unlisted_regions`. + #[serde(default, deserialize_with = "max_regions")] + #[schemars(schema_with = "max_regions_schema")] + pub max_regions: Option, + #[serde(default)] + pub color: Option, +} + +/// A body name, with the handler's message for anything else; `null` is none. +fn body_name<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::String(s) => Ok(Some(s)), + _ => Err(D::Error::custom("must be a body name")), + } +} + +/// A number in `lo..=hi` with the handler's message, `null` none, for each ranged key. +macro_rules! ranged { + ($read:ident, $schema:ident, $lo:literal, $hi:literal) => { + fn $read<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v + .as_f64() + .filter(|x| x.is_finite() && ($lo..=$hi).contains(x)) + .map(Some) + .ok_or_else(|| D::Error::custom(format!("must be a number from {} to {}", $lo, $hi))), + } + } + + fn $schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "null"], "minimum": $lo, "maximum": $hi}) + } + }; +} + +ranged!(tolerance, tolerance_schema, 0.001, 10.0); +ranged!(spacing, spacing_schema, 0.01, 1000.0); +ranged!(max_points, max_points_schema, 1e4, 5e7); +ranged!(max_regions, max_regions_schema, 1.0, 1000.0); + +/// Colour the faces that hold a region: `true` for red where only `a` has material and green +/// where only `b` has, or `{only_in_a?, only_in_b?}` to choose either colour (`"#rrggbb"` or +/// `[r, g, b]`, 0 to 255). `false` colours nothing. One undo step. +#[derive(Clone, Debug, PartialEq)] +pub struct CompareColor(pub Value); + +impl<'de> Deserialize<'de> for CompareColor { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + match &v { + Value::Bool(_) => {} + Value::Object(o) => { + if o.keys().any(|k| k != "only_in_a" && k != "only_in_b") { + return Err(D::Error::custom("must be true or {only_in_a, only_in_b}")); + } + for k in ["only_in_a", "only_in_b"] { + if o.get(k).is_some_and(|c| !c.is_null() && crate::cmd::color_param(c).is_none()) { + return Err(D::Error::custom(whole(format!("`color.{k}` must be \"#rrggbb\" or [r, g, b] with values 0–255")))); + } + } + } + _ => return Err(D::Error::custom("must be true or {only_in_a, only_in_b}")), + } + Ok(CompareColor(v)) + } +} + +impl JsonSchema for CompareColor { + fn schema_name() -> Cow<'static, str> { + "CompareColor".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let color = || { + serde_json::json!({ + "anyOf": [ + {"description": "\"#rrggbb\": six hex digits, the # optional.", "type": "string", "pattern": "^\\s*#?[0-9a-fA-F]{6}\\s*$"}, + {"type": "array", "items": {"type": "number", "minimum": 0, "maximum": 255}, "minItems": 3, "maxItems": 3}, + {"type": "null"} + ] + }) + }; + json_schema!({ + "description": "Colour the faces that hold a region: true for red where only `a` has material and green where only `b` has, or {only_in_a?, only_in_b?} to choose either colour (\"#rrggbb\" or [r, g, b], 0 to 255). false colours nothing.", + "anyOf": [ + {"type": "boolean"}, + {"type": "object", "properties": {"only_in_a": color(), "only_in_b": color()}, "additionalProperties": false} + ] + }) + } +} + +/// What `inspect.compare` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Comparison { + /// `a`'s measures, as `inspect.measure` gives a body's. + pub a: Map, + /// `b`'s measures, as `inspect.measure` gives a body's. + pub b: Map, + /// `b` less `a`. + pub difference: Difference, + /// The tolerance used (mm). + pub tolerance_mm: f64, + /// How far each surface is from the other. + pub deviation: Deviations, + /// Whether no region differs by more than the tolerance. + pub identical: bool, + /// The comparison in a sentence. + pub verdict: String, + /// The regions where only one body has material, largest first. + pub regions: Vec, + /// The regions with material only in `a`, and their volume together. + pub only_in_a: SideTotal, + /// The regions with material only in `b`, and their volume together. + pub only_in_b: SideTotal, + /// Regions beyond `max_regions`, counted but not measured. + pub unlisted_regions: usize, + /// What makes the comparison less certain: a body whose surface doesn't enclose what it + /// measures, a cut that couldn't be made, a body that encloses no volume. + pub warnings: Vec, + /// How the surfaces were sampled. + pub sampling: Sampling, + /// With `color`: how many faces were coloured. + #[serde(skip_serializing_if = "Option::is_none")] + pub colored_faces: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// `b` less `a`; `null` where either has no such measure. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Difference { + pub volume_mm3: Option, + /// The volume difference as a share of `a`'s (%). + pub volume_percent: Option, + pub area_mm2: Option, + pub center_of_mass: Option<[f64; 3]>, + pub center_of_mass_distance_mm: Option, + pub bbox_min: Option<[f64; 3]>, + pub bbox_max: Option<[f64; 3]>, +} + +/// How far each surface is from the other. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Deviations { + /// From `a`'s surface to `b`'s. + pub a_to_b: Deviation, + /// From `b`'s surface to `a`'s. + pub b_to_a: Deviation, + /// The larger of the two maxima (mm). + pub max_mm: f64, +} + +/// One surface's distance to the other, over its samples. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Deviation { + pub max_mm: f64, + pub mean_mm: f64, + /// Where the largest is. + pub at: [f64; 3], + /// The area further than the tolerance (mm²). + pub area_beyond_mm2: f64, + /// The area sampled (mm²). + pub area_mm2: f64, + /// How many samples. + pub points: usize, +} + +/// Which body alone has a region's material. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum CompareSide { + OnlyInA, + OnlyInB, +} + +/// A region where only one body has material. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Region { + /// Its number, from 1, largest first. + pub index: usize, + pub side: CompareSide, + /// The body that has the material. + pub material_of: String, + /// Its volume (mm³), measured exactly on the pieces of the cut on its side (a − b or b − a) + /// that lie there; `null` when it isn't measured, never an estimate. + pub volume_mm3: Option, + /// `boolean` when the volume, centre and box were measured on the cut, else `not measured`. + pub measured_by: MeasuredBy, + /// Why it isn't measured (the cut couldn't be made, a body encloses no volume, no piece fell + /// here); `null` when it is. + pub not_measured: Option, + /// Its surface on both bodies (mm²). + pub area_mm2: f64, + pub area_a_mm2: f64, + pub area_b_mm2: f64, + /// How far the surfaces are apart there at most (mm). + pub max_deviation_mm: f64, + /// Where that is. + pub at: [f64; 3], + /// Its centre of volume, measured with the volume; `null` when it isn't measured. + pub center: Option<[f64; 3]>, + /// The measured pieces' box, or the box the region was found in when it isn't measured. + pub bbox: Bounds, + /// The faces of `a` it lies on, by index, as `model.faces` lists them. + pub faces_a: Vec, + /// The faces of `b` it lies on. + pub faces_b: Vec, + /// The lines through it the surfaces were sampled along. + pub resolution: Resolution, +} + +/// How a region was measured. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +pub enum MeasuredBy { + /// Exactly, on the pieces of the cut that lie there. + #[serde(rename = "boolean")] + Boolean, + /// Not at all: see `not_measured`. + #[serde(rename = "not measured")] + NotMeasured, +} + +/// A box, by its corners. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Bounds { + pub min: [f64; 3], + pub max: [f64; 3], +} + +/// The lines through a region the surfaces were sampled along. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Resolution { + /// The axis they run along: `X`, `Y` or `Z`. + pub along: String, + /// Their spacing across the other two axes (mm). + pub line_spacing_mm: [f64; 2], + pub lines: usize, + /// Lines that crossed a gap in a surface and were left out. + pub skipped_lines: usize, +} + +/// The regions on one side, and their volume together. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SideTotal { + pub regions: usize, + /// Their volume together (mm³); `null` when one of them isn't measured. + pub volume_mm3: Option, +} + +/// How the surfaces were sampled. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Sampling { + /// The sample spacing used (mm). + pub spacing_mm: f64, + /// How closely the meshes follow the surfaces (mm): a quarter of the tolerance. + pub chord_mm: f64, + pub triangles_a: usize, + pub triangles_b: usize, +} + +#[cfg(test)] +#[path = "compare_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/compare_tests.rs b/crates/engine/src/schema/compare_tests.rs new file mode 100644 index 000000000..593e23961 --- /dev/null +++ b/crates/engine/src/schema/compare_tests.rs @@ -0,0 +1,74 @@ +use serde_json::{Value, json}; + +use super::{CompareParams, Comparison}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["a", "b", "color", "max_points", "max_regions", "spacing", "tolerance"]); +} + +/// The handler reads the numbers and the colours before it looks for the bodies, so each of +/// these fails the same way on a design with none. +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("inspect.compare", json!({"tolerance": 0})), + ("inspect.compare", json!({"tolerance": "x"})), + ("inspect.compare", json!({"spacing": 2000})), + ("inspect.compare", json!({"max_points": 1})), + ("inspect.compare", json!({"max_regions": 0})), + ("inspect.compare", json!({"color": 5})), + ("inspect.compare", json!({"color": "red"})), + ("inspect.compare", json!({"color": {"only_in_a": "#zz0000"}})), + ("inspect.compare", json!({"color": {"only_in_b": [1, 2]}})), + ("inspect.compare", json!({"a": 5})), + ("inspect.compare", json!({"a": "A"})), + ("inspect.compare", json!({})), + ("inspect.compare", json!({"a": "X", "b": "Y"})), + ]); +} + +/// #10994: a comparison replies as its output schema says, in Warn without warnings for good +/// calls and with them for a misspelt key: a box and its copy (identical, no regions), and the +/// copy with a boss, compared with every key and coloured both ways. +#[test] +fn a_comparison_replies_with_its_schema() { + let schema = output_schema_for::(); + let matches = |r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "A"})); + run(&mut s, "solid.move", json!({"bodies": ["A"], "translate": [0, 0, 0], "copy": true})); + let r = run(&mut s, "inspect.compare", json!({})); + matches(&r, false); + assert!(r["identical"] == true && r["regions"] == json!([]) && r.get("colored_faces").is_none(), "{r}"); + run(&mut s, "solid.box", json!({"length": 6, "width": 5, "height": 2, "corner": [5, 5, 10], "operation": "join", "targets": ["A (2)"]})); + let r = run( + &mut s, + "inspect.compare", + json!({"a": "A", "b": "A (2)", "tolerance": 0.01, "spacing": 0.5, "max_points": 1e6, "max_regions": 10, "color": true}), + ); + matches(&r, false); + assert_eq!((r["regions"][0]["side"].as_str(), r["identical"].as_bool()), (Some("only_in_b"), Some(false)), "{r}"); + assert!(r["colored_faces"].as_u64().is_some_and(|n| n > 0), "{r}"); + let r = run(&mut s, "inspect.compare", json!({"a": "A", "b": "A (2)", "color": {"only_in_b": "#123456", "only_in_a": null}})); + matches(&r, false); + matches(&run(&mut s, "inspect.compare", json!({"a": "A", "b": "A (2)", "color": false, "tolerence": 1})), true); +} + +/// A `color` string in the published schema carries the same pattern the handler checks. +#[test] +fn the_color_string_has_a_pattern() { + let schema = serde_json::to_string(&input_schema_for::()).unwrap(); + assert!(schema.contains(r"^\\s*#?[0-9a-fA-F]{6}\\s*$"), "{schema}"); +} diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rs index 53eace830..c84878fea 100644 --- a/crates/engine/src/schema/component.rs +++ b/crates/engine/src/schema/component.rs @@ -363,6 +363,54 @@ pub struct MoveFeaturesParams { pub component: Option, } +/// Move sketches to the part whose face they are drawn on (`component.move_sketches.to_parts`), +/// in one undo step. A sketch whose plane is an exactly attached face of a part's body goes to +/// that part, staying where it is on the face; the others stay where they are. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MoveSketchesToPartsParams { + /// The sketches to look at, by id or name. Default: every sketch in the design. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "Vec")] + pub sketches: Option>, +} + +/// A sketch `component.move_sketches.to_parts` moved. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct SketchMovedToPart { + pub sketch: u64, + pub name: String, + /// The part it went to: its component id and name. + pub component: u64, + pub part: String, +} + +/// A sketch `component.move_sketches.to_parts` left where it was, and why. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct SketchKeptInPlace { + pub sketch: u64, + pub name: String, + /// Why, as a code: `not_on_face`, `no_exact_attachment`, `design_body`, `part_missing` or + /// `already_in_part`; and in words. + pub code: String, + pub reason: String, +} + +/// What `component.move_sketches.to_parts` returns. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct MoveSketchesToPartsResult { + /// How many sketches moved, and how many stayed. + pub moved: usize, + pub stayed: usize, + /// The sketches that moved, each with the part it went to. + pub sketches: Vec, + /// The sketches that stayed, each with the reason. + pub kept: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + /// What `component.move_features` returns. #[derive(Debug, Default, Serialize, JsonSchema)] pub struct MoveFeaturesResult { diff --git a/crates/engine/src/schema/component_tests.rs b/crates/engine/src/schema/component_tests.rs index 3acbf2fef..983c8705b 100644 --- a/crates/engine/src/schema/component_tests.rs +++ b/crates/engine/src/schema/component_tests.rs @@ -1,8 +1,12 @@ +use solidcraft_geom::prelude::*; use std::sync::Arc; use serde_json::{Value, json}; -use super::{EditInPlaceParams, FinishEditParams, MoveFeaturesParams, OccurrenceAlignParams, OccurrenceAlignResult, ReparentItemsParams}; +use super::{ + EditInPlaceParams, FinishEditParams, MoveFeaturesParams, MoveSketchesToPartsParams, OccurrenceAlignParams, OccurrenceAlignResult, + ReparentItemsParams, +}; use crate::Session; use crate::schema::tests::{assert_keys, conforms}; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; @@ -30,6 +34,7 @@ fn schemas_and_the_key_check_agree() { ], ); assert_keys(input_schema_for::(), &["component", "features"]); + assert_keys(input_schema_for::(), &["sketches"]); assert_keys(input_schema_for::(), &["bodies", "component", "component_path", "features", "occurrences"]); } @@ -79,3 +84,53 @@ fn replies_match_the_output_schema() { assert!(r2.get("param_warnings").is_some(), "{r2}"); assert!(conforms(schema, schema, &r2), "{r2} doesn't match {schema}"); } + +fn sketch_square(s: &mut Session) { + let run = |s: &mut Session, c: &str, p: Value| s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + run(s, "sketch.rectangle.two_point", json!({"p0":[1,1],"p1":[3,3]})); + run(s, "sketch.finish", json!({})); +} + +/// `component.move_sketches.to_parts` (#10218): sketches drawn on a part's face while the design +/// was active go to that part and stay where they are on the face; the others stay and say why; +/// it is one undo step. +#[test] +fn sketches_move_to_the_part_whose_face_they_are_on() { + let mut s = Session::default(); + let run = |s: &mut Session, c: &str, p: Value| s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + let part = run(&mut s, "component.create", json!({"name":"Part","parent":0,"grounded":false})); + let (component, occurrence) = (part["component"].as_u64().unwrap(), part["occurrence"].as_u64().unwrap()); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Base"})); + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0]})); + run(&mut s, "component.activate", json!({"component":0})); + let world = s.world_state().unwrap(); + let base = world.body("Base").unwrap(); + let top = base.body.faces(0.01).unwrap().into_iter().max_by(|a, b| a.centroid.z.total_cmp(&b.centroid.z)).unwrap(); + let pick = json!({"body": base.name, "index": top.index, "face": [top.centroid.x, top.centroid.y, top.centroid.z], "path": [occurrence]}); + let on_face = run(&mut s, "sketch.create", json!({"name":"OnFace","plane":pick,"project_edges":false}))["sketch"].as_u64().unwrap(); + sketch_square(&mut s); + let on_xy = run(&mut s, "sketch.create", json!({"name":"OnXY","plane":"XY"}))["sketch"].as_u64().unwrap(); + sketch_square(&mut s); + let world_plane = |s: &Session| s.world_state().unwrap().sketch(on_face).unwrap().plane; + let before = world_plane(&s); + assert_eq!(s.doc.feature(on_face).unwrap().component, 0); + let doc_before = s.doc.to_json(); + + let out = run(&mut s, "component.move_sketches.to_parts", json!({})); + assert_eq!((out["moved"].as_u64(), out["stayed"].as_u64()), (Some(1), Some(1)), "{out}"); + assert_eq!(out["sketches"][0]["part"], "Part"); + assert_eq!(out["kept"][0]["name"], "OnXY"); + assert_eq!(out["kept"][0]["reason"], "not on a face"); + assert_eq!(s.doc.feature(on_face).unwrap().component, component); + assert_eq!(s.doc.feature(on_xy).unwrap().component, 0); + let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &s.doc.feature(on_face).unwrap().kind else { panic!("not sketch") }; + assert_eq!(solidcraft_doc::face_anchor::plane_face_anchor(plane).unwrap().author_path, vec![occurrence]); + assert!(s.model.result(on_face).unwrap().error.is_none()); + let after = world_plane(&s); + assert!((after.origin - before.origin).len() < 1e-6 && after.normal().dot(before.normal()) > 1. - 1e-9, "{before:?} {after:?}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), doc_before, "one undo step"); + run(&mut s, "component.move_sketches.to_parts", json!({})); + let again = run(&mut s, "component.move_sketches.to_parts", json!({"sketches":["OnFace"]})); + assert_eq!((again["moved"].as_u64(), again["kept"][0]["reason"].as_str()), (Some(0), Some("already in its part"))); +} diff --git a/crates/engine/src/schema/config.rs b/crates/engine/src/schema/config.rs new file mode 100644 index 000000000..876e6a963 --- /dev/null +++ b/crates/engine/src/schema/config.rs @@ -0,0 +1,116 @@ +//! Contracts and result types for the configuration commands in `cmd/config.rs` that read the +//! table and switch between its rows (#11059). + +use std::collections::BTreeMap; + +use schemars::JsonSchema; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use super::check::whole; + +/// The configuration table: its columns, rows and rules, the active row, and whether the design +/// still matches it. Read-only. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ConfigTableParams {} + +/// Switch to a configuration row: its parameter values, suppressions, materials and appearances +/// are set, and its rules run. Refused, with nothing changed, when a feature that builds now +/// would fail in it. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ConfigRowParams { + /// The row, by name. + #[serde(deserialize_with = "row")] + pub row: String, +} + +/// The row's name, with the handler's message for anything that isn't text. +fn row<'de, D: Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(D::Error::custom(whole("`row` is required"))), + } +} + +/// The configuration table, as `config.table` and `config.rules` return it and an activation +/// returns it after the switch. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ConfigTable { + /// Each column's key: `param:`, `suppress:`, or a material or appearance + /// column's. + pub columns: Vec, + /// Each column: its key, a label to show, and what it drives. + pub targets: Vec, + /// The rows, in order. + pub rows: Vec, + /// The rules, in the order they run: `{id, name, enabled, condition, effect}` each. + pub rules: Vec, + /// The active row's name, or `null`. + pub active: Option, + /// Whether the design still has the active row's values. + pub matches: bool, + /// Each style column's state, when it could be worked out. + pub style_status: Option>, + /// Why the style columns' state couldn't be worked out. + pub style_error: Option, +} + +/// One column of the table. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ConfigTarget { + pub key: String, + /// What to show for it, such as `Component: Bracket`. + pub label: String, + /// What it drives, as the design file saves it. + pub target: Value, +} + +/// One row of the table. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ConfigTableRow { + pub name: String, + /// Its cell for each column, by column key. + pub values: BTreeMap, +} + +/// What `config.table` and `config.rules` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ConfigTableReply { + #[serde(flatten)] + pub table: ConfigTable, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `config.activate` and `config.preview` return: the table after the switch, and what the +/// switch did. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ConfigActivation { + #[serde(flatten)] + pub table: ConfigTable, + /// The features that fail after the switch, `: ` each, those that failed + /// before included. + pub errors: Vec, + /// What each rule did. + pub trace: Vec, + /// Each style column's state after the switch. + pub styles: Vec, + /// For `config.preview`: always true. The design and its history are unchanged. + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + /// For `config.preview`: the parameters as the row would set them, as `parameters.list` + /// gives them. + #[serde(skip_serializing_if = "Option::is_none")] + pub parameters: Option>, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "config_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/config_tests.rs b/crates/engine/src/schema/config_tests.rs new file mode 100644 index 000000000..2adf132d9 --- /dev/null +++ b/crates/engine/src/schema/config_tests.rs @@ -0,0 +1,78 @@ +use serde_json::{Value, json}; + +use super::{ConfigActivation, ConfigRowParams, ConfigTableParams, ConfigTableReply}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// A box `W` long, with `W` and the box's suppression configured, a `Big` row and a +/// `Without` row that suppresses the box. +fn configured(s: &mut Session) { + run(s, "parameters.add", json!({"name": "W", "expression": "10 mm"})); + run(s, "solid.box", json!({"length": "W", "width": 10, "height": 10, "body_name": "A", "name": "Block"})); + run(s, "config.configure", json!({"params": ["W"], "features": ["Block"]})); + run(s, "config.row", json!({"name": "Big", "values": {"param:W": "20 mm"}})); + run(s, "config.row", json!({"name": "Without", "values": {"suppress:Block": true}})); +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &["row"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("config.activate", json!({})), + ("config.activate", json!({"row": 5})), + ("config.activate", json!({"row": "Nope"})), + ]); +} + +/// A preview runs the activation, whose messages name `config.activate`, where strict names +/// `config.preview`; the message after the name is the same. +#[test] +fn a_preview_keeps_the_activations_messages_in_strict() { + for p in [json!({}), json!({"row": 5}), json!({"row": "Nope"})] { + let message = |level: ParamCheck| { + let mut s = Session { param_check: level, ..Session::default() }; + s.execute("config.preview", &p).err().map(|e| e.to_string().split_once("`: ").map(|m| m.1.to_string())) + }; + let off = message(ParamCheck::Off); + assert!(off.as_ref().is_some_and(Option::is_some), "{p} should fail today"); + assert_eq!(message(ParamCheck::Strict), off, "{p}"); + } +} + +/// #11059: the table, the rules, an activation and a preview reply as their output schemas say, +/// in Warn without warnings for good calls and with them for a misspelt key. +#[test] +fn configuration_commands_reply_with_their_schemas() { + let (table, activation) = (output_schema_for::(), output_schema_for::()); + let matches = |schema: &schemars::Schema, r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + matches(&table, &run(&mut s, "config.table", json!({})), false); + configured(&mut s); + let r = run(&mut s, "config.table", json!({})); + matches(&table, &r, false); + assert_eq!((r["rows"].as_array().map(Vec::len), r["targets"].as_array().map(Vec::len)), (Some(3), Some(2)), "{r}"); + matches(&table, &run(&mut s, "config.rules", json!({})), false); + let r = run(&mut s, "config.activate", json!({"row": "Big"})); + matches(&activation, &r, false); + assert!(r["active"] == "Big" && r.get("preview").is_none(), "{r}"); + let r = run(&mut s, "config.preview", json!({"row": "Without"})); + matches(&activation, &r, false); + assert!(r["preview"] == true && r["parameters"].is_array() && r["active"] == "Without", "{r}"); + assert_eq!(s.doc.configs.active.as_deref(), Some("Big"), "a preview changes nothing"); + matches(&table, &run(&mut s, "config.table", json!({"row": "Big"})), true); + matches(&activation, &run(&mut s, "config.activate", json!({"row": "Default", "rows": 1})), true); +} diff --git a/crates/engine/src/schema/construct.rs b/crates/engine/src/schema/construct.rs index edd091735..a670fcf0e 100644 --- a/crates/engine/src/schema/construct.rs +++ b/crates/engine/src/schema/construct.rs @@ -8,7 +8,7 @@ use schemars::JsonSchema; use serde::Deserialize; -use super::types::{ConstructionCommon, GeoRefParam, NumberExpr, PlaneCommon, Point3, feature_common, present}; +use super::types::{AngleExpr, ConstructionCommon, GeoRefParam, NumberExpr, PlaneCommon, Point3, feature_common, present}; /// Add a construction axis along the axis of a cylinder, cone or torus face, or of a circular /// edge. @@ -175,6 +175,18 @@ pub struct PlaneTwoEdgesParams { pub common: PlaneCommon, } +/// Add a construction plane containing an axis and a point off that axis. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct PlaneAxisPointParams { + /// An origin axis, construction axis, straight edge or sketch line reference. + pub axis: GeoRefParam, + /// A vertex, sketch point, construction point or fixed point, not on the axis. + pub point: GeoRefParam, + #[serde(flatten, deserialize_with = "feature_common")] + pub common: PlaneCommon, +} + /// Add a construction plane through three points. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -202,6 +214,14 @@ pub struct PlaneTangentParams { /// otherwise. #[serde(default)] pub at: Option, + /// A plane or planar face to line the plane up with: it touches where the face turns + /// towards the reference, parallel to it, on the side of `at`. + #[serde(default)] + pub reference: Option, + /// With `reference`, how far the plane is turned from it about the face's axis. Not on a + /// sphere. Default: 0 deg. + #[serde(default)] + pub angle: Option, #[serde(flatten, deserialize_with = "feature_common")] pub common: PlaneCommon, } diff --git a/crates/engine/src/schema/construct_tests.rs b/crates/engine/src/schema/construct_tests.rs index f461b6ef6..f2d7a56ba 100644 --- a/crates/engine/src/schema/construct_tests.rs +++ b/crates/engine/src/schema/construct_tests.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use super::{ AxisEdgeParams, AxisNormalToFaceParams, AxisThroughCylinderParams, AxisTwoPlanesParams, AxisTwoPointsParams, MidplaneParams, - PlaneAlongPathParams, PlanePerpendicularParams, PlaneTangentParams, PlaneThreePointsParams, PlaneTwoEdgesParams, PointAlongPathParams, - PointCenterParams, PointEdgePlaneParams, PointThreePlanesParams, PointTwoEdgesParams, PointVertexParams, + PlaneAlongPathParams, PlaneAxisPointParams, PlanePerpendicularParams, PlaneTangentParams, PlaneThreePointsParams, PlaneTwoEdgesParams, + PointAlongPathParams, PointCenterParams, PointEdgePlaneParams, PointThreePlanesParams, PointTwoEdgesParams, PointVertexParams, }; use crate::Session; use crate::schema::features::FeatureResult; @@ -24,9 +24,10 @@ fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["edge", "name", "participants", "plane"]); assert_keys(input_schema_for::(), &["name", "participants", "path", "t"]); assert_keys(input_schema_for::(), &["a", "b", "name", "participants"]); + assert_keys(input_schema_for::(), &["axis", "name", "participants", "point"]); assert_keys(input_schema_for::(), &["a", "b", "name", "participants"]); assert_keys(input_schema_for::(), &["a", "b", "c", "name", "participants"]); - assert_keys(input_schema_for::(), &["at", "face", "name", "participants"]); + assert_keys(input_schema_for::(), &["angle", "at", "face", "name", "participants", "reference"]); assert_keys(input_schema_for::(), &["name", "participants", "path", "t"]); assert_keys(input_schema_for::(), &["line", "name", "participants", "plane"]); } @@ -88,6 +89,7 @@ fn construction_features_reply_with_feature_result() { run("construct.axis.two_points", json!({"a": {"type": "point", "p": [0, 0, 0]}, "b": {"point": {"x": 1, "y": 2, "z": 3}}})), run("construct.axis.edge", json!({"edge": {"edge": [5, 0, 0]}, "participants": []})), run("construct.plane.midplane", json!({"a": "XY", "b": {"face": [5, 5, 10]}, "name": "Middle"})), + run("construct.plane.axis_point", json!({"axis":{"axis":"Z"},"point":{"point":[10,20,30]}})), run("construct.plane.two_edges", json!({"a": {"edge": [5, 0, 0]}, "b": {"edge": [0, 5, 0]}})), run("construct.plane.three_points", json!({"a": {"point": [0, 0, 0]}, "b": {"vertex": [10, 0, 0]}, "c": {"sketch": sketch, "point": point}})), run("construct.plane.tangent", json!({"face": {"face": [35, 0, 5]}})), diff --git a/crates/engine/src/schema/diagnostics.rs b/crates/engine/src/schema/diagnostics.rs new file mode 100644 index 000000000..4c49049c6 --- /dev/null +++ b/crates/engine/src/schema/diagnostics.rs @@ -0,0 +1,357 @@ +//! Contracts and result types for the commands in `cmd/diagnostics.rs`: the crash reports on +//! this computer (#10909), the profiler and the validation mode. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Map, Value, json}; + +/// List this computer's crash reports, newest first. They stay on this computer and are never +/// sent anywhere. Read one with `diagnostics.crash_report`; reproduce one with +/// `solidcraft-cli crashes replay `. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashReportsParams { + /// How many reports to list, newest first. Default: 20; at most 1000 are listed, whatever + /// the limit. + #[serde(default)] + pub limit: Option, +} + +/// What `diagnostics.crash_reports` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CrashReportList { + /// The crash report folder on this computer. + pub dir: String, + /// The reports, newest first. + pub reports: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Read one crash report: the whole report as it was saved, with the paths of its files. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashReportParams { + /// The report's id, as `diagnostics.crash_reports` lists it. + pub id: String, +} + +/// What `diagnostics.crash_report` returns: the report as saved, with where its files are. A +/// report from an earlier release may lack some of these fields, and a report can carry more +/// (`startup_phase`, `native`). +#[derive(Debug, Serialize)] +pub struct CrashReport { + /// The report's fields. + #[serde(flatten)] + pub report: Map, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +impl JsonSchema for CrashReport { + fn schema_name() -> Cow<'static, str> { + "CrashReport".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let path = + |what: &str| json!({"description": format!("Where the report's {what} is on this computer; only when it has one."), "type": "string"}); + json_schema!({ + "description": "A crash report as saved, with where its files are. A report from an earlier release may lack some fields, and a report can carry more.", + "type": "object", + "properties": { + "id": {"description": "The report's id.", "type": "string"}, + "kind": {"description": "command_panic, panic, kernel_panic_recovered or unclean_exit.", "type": "string"}, + "signature": {"description": "What tells this crash apart from others, so a repeat counts against the same report."}, + "count": {"description": "How many times it happened.", "type": "integer", "minimum": 0}, + "first_seen": {"description": "When it was first recorded (UTC). An unclean exit is recorded at a later launch."}, + "last_seen": {"description": "When it was last recorded (UTC)."}, + "app": {"description": "The app's version, commit and build date."}, + "system": {"description": "The operating system, architecture and graphics environment."}, + "session": {"description": "How long the app had been running."}, + "message": {"description": "The internal error's message."}, + "location": {"description": "Where in the code it happened."}, + "thread": {"description": "The thread it happened on."}, + "backtrace": {"description": "The stack, one frame `symbol (file:line)` each."}, + "command": {"description": "The command running when it happened, with its parameters, if one was."}, + "base": {"description": "What the replay starts from."}, + "recent_commands": {"description": "The commands run before it."}, + "files": {"description": "The files saved with the report, by what they are."}, + "reproduce": {"description": "The command line that replays the crash, when it can be."}, + "notes": {"description": "What the report could not record, and why."}, + "path": {"description": "The report's folder on this computer.", "type": "string"}, + "design_path": path("design"), + "replay_path": path("replay (`solidcraft-cli run --in `)"), + "minidump_path": path("minidump"), + "param_warnings": {"description": "In the warn parameter-check mode: what the call's parameters got wrong.", "type": "array", "items": {"type": "string"}} + } + }) + } +} + +/// Delete one crash report, or all of them. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashReportsClearParams { + /// The report to delete, as `diagnostics.crash_reports` lists it. Default: every report. An + /// id that names no report deletes nothing. + #[serde(default)] + pub id: Option, +} + +/// What `diagnostics.crash_reports.clear` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CrashReportsCleared { + /// How many reports were deleted. + pub deleted: usize, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Check that crash reports work, by crashing on purpose. Only when the SOLIDCRAFT_CRASH_TEST +/// environment variable is set. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashTestParams { + /// What to break. + pub mode: CrashTestMode, +} + +/// What `diagnostics.crash_test` breaks. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum CrashTestMode { + /// An internal error in this command, caught: the design is unchanged. + Panic, + /// An internal error inside the geometry kernel, caught. + Kernel, + /// The app ends at once; the report is made at the next start. + Abort, +} + +impl<'de> Deserialize<'de> for CrashTestMode { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) if s == "panic" => Ok(CrashTestMode::Panic), + Value::String(s) if s == "kernel" => Ok(CrashTestMode::Kernel), + Value::String(s) if s == "abort" => Ok(CrashTestMode::Abort), + _ => Err(D::Error::custom("must be panic, kernel or abort")), + } + } +} + +/// What `diagnostics.crash_test` would return. It never succeeds: it ends in an internal error +/// that is caught and reported (`panic`, `kernel`), or it ends the app (`abort`). +#[derive(Debug, Serialize, JsonSchema)] +pub struct CrashTestResult {} + +/// `true`, `false` or null, with the handler's message for anything else. +fn flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::Bool(b) => Ok(Some(b)), + _ => Err(serde::de::Error::custom("must be true or false")), + } +} + +/// A row count, with the handler's message for anything else. +fn rows<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v.as_u64().map(Some).ok_or_else(|| serde::de::Error::custom("must be a whole number of rows (0: all)")), + } +} + +/// A file path, with the handler's message for anything else. +fn path<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::String(s) if !s.trim().is_empty() && s.len() < 4096 => Ok(Some(s)), + _ => Err(serde::de::Error::custom("must be a file path")), + } +} + +/// What `diagnostics.profile` should do besides reporting. +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ProfileParams { + /// Start (`true`) or stop (`false`) recording, after the report is taken. + #[serde(default, deserialize_with = "flag")] + pub enabled: Option, + /// Forget what was recorded, after the report is taken. + #[serde(default, deserialize_with = "flag")] + pub reset: Option, + /// How many rows to return, the most self time first (default 20; 0: all of them). + #[serde(default, deserialize_with = "rows")] + pub top: Option, + /// Write the recorded spans here as a Chrome trace-event file (chrome://tracing, Perfetto). + #[serde(default, deserialize_with = "path")] + pub trace: Option, +} + +/// One category's share of the recorded self time. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ProfileCategory { + /// `solidcore` (the kernel's own calls), `kernel`, `feature`, `doc`, `command`, `import`, `io`. + pub category: String, + pub self_ms: f64, + /// Of all recorded self time, 0–1. + pub share: f64, +} + +/// One span name's aggregate. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ProfileRow { + pub category: String, + pub name: String, + pub count: u64, + /// Its time, counting only its outermost occurrence on each thread's stack. + pub total_ms: f64, + /// Its time less the time of the spans inside it. + pub self_ms: f64, + /// Its longest single run. + pub max_ms: f64, +} + +/// What the profiler recorded: the reply of `diagnostics.profile`, and an import's `profile`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ProfileReport { + /// The profiler is compiled into this build (the apps' `profile` feature). + pub compiled: bool, + /// It is recording (after this call's `enabled`). + pub enabled: bool, + /// Wall time the report covers. + pub wall_ms: f64, + /// Spans recorded. + pub spans: u64, + /// Spans left out of the trace (past its cap); they are in the rows. + pub dropped: u64, + /// Self time per category, the most first. + pub by_category: Vec, + /// The span names with the most self time, the most first. + pub rows: Vec, + /// Span names recorded (rows lists `top` of them). + pub rows_total: usize, + /// Where the Chrome trace was written, when `trace` asked for one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trace: Option, +} + +fn ms(d: std::time::Duration) -> f64 { + (d.as_secs_f64() * 1e6).round() / 1e3 +} + +impl ProfileReport { + /// `report` with its `top` rows of most self time (0: all of them). + pub fn new(report: &solidcraft_profile::Report, top: usize) -> ProfileReport { + let sorted = report.sorted(); + let all: f64 = report.rows.iter().map(|r| r.self_time.as_secs_f64()).sum(); + let by_category = report + .by_category() + .into_iter() + .map(|(c, d)| ProfileCategory { + category: c.to_string(), + self_ms: ms(d), + share: if all > 0.0 { (d.as_secs_f64() / all * 1000.0).round() / 1000.0 } else { 0.0 }, + }) + .collect(); + let n = if top == 0 { sorted.len() } else { top.min(sorted.len()) }; + let rows = sorted + .iter() + .take(n) + .map(|r| ProfileRow { + category: r.category.to_string(), + name: r.name.to_string(), + count: r.count, + total_ms: ms(r.total), + self_ms: ms(r.self_time), + max_ms: ms(r.max), + }) + .collect(); + ProfileReport { + compiled: report.compiled, + enabled: report.enabled, + wall_ms: ms(report.wall), + spans: (report.events as u64).saturating_add(report.dropped), + dropped: report.dropped, + by_category, + rows, + rows_total: sorted.len(), + trace: None, + } + } +} + +/// A validation mode by name, with the handler's message for anything else. +fn validation_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::String(s) => ValidationMode::parse(&s).map(Some).ok_or_else(|| serde::de::Error::custom(VALIDATION_MODES)), + _ => Err(serde::de::Error::custom(VALIDATION_MODES)), + } +} + +/// What a `mode` that names no validation mode is told. +pub(crate) const VALIDATION_MODES: &str = "must be each_step, each_feature or off"; + +/// When SMLib's full check runs while features are computed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ValidationMode { + /// After every sweep, boolean and blend inside a feature: a step whose result fails the + /// check fails the feature there. + EachStep, + /// Once per feature (the default): each body the feature makes or changes is checked before + /// it is kept, and a body the check refuses fails the feature with the check's reason. + EachFeature, + /// Never (experimental): a body the check would refuse is kept. + Off, +} + +impl ValidationMode { + fn parse(id: &str) -> Option { + solidcraft_kernel::Validation::parse(id).map(ValidationMode::from) + } +} + +impl From for ValidationMode { + fn from(v: solidcraft_kernel::Validation) -> Self { + match v { + solidcraft_kernel::Validation::EachStep => ValidationMode::EachStep, + solidcraft_kernel::Validation::EachFeature => ValidationMode::EachFeature, + solidcraft_kernel::Validation::Off => ValidationMode::Off, + } + } +} + +/// Read, or set, when SMLib's full check runs on the features computed from now on. +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ValidationParams { + /// The mode to compute features under from now on. Default: leave it as it is. The results + /// already there stand until their features are computed again (`timeline.compute_all`). + #[serde(default, deserialize_with = "validation_mode")] + pub mode: Option, +} + +/// The reply of `diagnostics.validation`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ValidationReply { + /// The mode features are computed under now. + pub mode: ValidationMode, + /// The mode before this call. + pub previous: ValidationMode, +} + +/// Tests that switch the process-wide profiler on, off or reset it run one at a time. +#[cfg(test)] +pub(crate) static PROFILE_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[cfg(test)] +#[path = "diagnostics_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/diagnostics_tests.rs b/crates/engine/src/schema/diagnostics_tests.rs new file mode 100644 index 000000000..a16432ab7 --- /dev/null +++ b/crates/engine/src/schema/diagnostics_tests.rs @@ -0,0 +1,208 @@ +use serde_json::{Value, json}; + +use super::{ + CrashReport, CrashReportList, CrashReportParams, CrashReportsClearParams, CrashReportsCleared, CrashReportsParams, CrashTestMode, + CrashTestParams, ProfileParams, ValidationParams, +}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["limit"]); + assert_keys(input_schema_for::(), &["id"]); + assert_keys(input_schema_for::(), &["id"]); + assert_keys(input_schema_for::(), &["mode"]); + assert_keys(input_schema_for::(), &["enabled", "reset", "top", "trace"]); + assert_keys(input_schema_for::(), &["mode"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("diagnostics.crash_report", json!({"id": "no-such-report"})), + ("diagnostics.profile", json!({"enabled": "yes"})), + ("diagnostics.profile", json!({"reset": 1})), + ("diagnostics.profile", json!({"top": -1})), + ("diagnostics.profile", json!({"top": 2.5})), + ("diagnostics.profile", json!({"trace": 5})), + ("diagnostics.validation", json!({"mode": "each step"})), + ("diagnostics.validation", json!({"mode": true})), + ]); +} + +/// The crash test runs only with SOLIDCRAFT_CRASH_TEST set, so its mode is checked here: the +/// schema lists the three modes (one `const` each, with what it breaks), the type reads them, +/// and anything else gets the handler's message. +#[test] +fn the_crash_test_mode_is_one_of_three() { + let schema = input_schema_for::(); + let schema = schema.as_value(); + let listed: Vec<&str> = schema["$defs"]["CrashTestMode"]["oneOf"].as_array().into_iter().flatten().filter_map(|m| m["const"].as_str()).collect(); + assert_eq!(listed, ["panic", "kernel", "abort"], "{schema}"); + for (mode, want) in [("panic", CrashTestMode::Panic), ("kernel", CrashTestMode::Kernel), ("abort", CrashTestMode::Abort)] { + let p = json!({ "mode": mode }); + assert_eq!(serde_json::from_value::(p.clone()).ok().map(|p| p.mode), Some(want), "{mode}"); + assert!(conforms(schema, schema, &p), "{p}"); + } + for mode in [json!("Panic"), json!("explode"), json!(""), json!(1), json!(null)] { + let p = json!({ "mode": mode }); + let error = serde_json::from_value::(p.clone()).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("must be panic, kernel or abort"), "{p}: {error}"); + assert!(!mode.as_str().is_some_and(|m| listed.contains(&m)), "{p}"); + } +} + +/// A report in this test process's crash folder, as the app writes one, with a design and a +/// replay beside it. +fn write_report(id: &str) { + let dir = crate::crash::default_dir().unwrap_or_else(|| panic!("no crash folder")).join(id); + std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}")); + let report = json!({ + "format": 1, "id": id, "kind": "command_panic", "signature": "00000000deadbeef", "count": 2, + "first_seen": "2026-11-01T12:00:00Z", "last_seen": "2026-11-01T12:05:00Z", + "app": {"version": "0.29.0", "commit": "abc", "built": "2026-10-31"}, + "system": {"os": "windows", "arch": "x86_64", "environment": ""}, "session": {"uptime_s": 60}, + "message": "an internal error", "location": "here.rs:1", "thread": "main", "backtrace": ["f (here.rs:1)"], + "command": {"command": "solid.box", "params": {}}, "base": "new", "recent_commands": [], + "files": {"design": "design.sc", "replay": "replay.json"}, "reproduce": format!("solidcraft-cli crashes replay {id}"), "notes": [], + "startup_phase": "running" + }); + for (name, text) in [("report.json", report.to_string()), ("design.sc", "{}".into()), ("replay.json", "[]".into())] { + std::fs::write(dir.join(name), text).unwrap_or_else(|e| panic!("{e}")); + } +} + +/// #10909: listing, reading and deleting reports reply as their output schemas say, in Warn +/// without warnings for good calls and with them for a misspelt key; strict refuses an `id` +/// that isn't text, which the handler would read as no id and so delete every report. +#[test] +fn crash_report_commands_reply_with_their_schemas() { + let id = "20261101-120000-00000000deadbeef"; + write_report(id); + let (list_schema, report_schema, cleared_schema) = + (output_schema_for::(), output_schema_for::(), output_schema_for::()); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: &schemars::Schema, r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + for p in [json!({}), json!({"limit": 5}), json!({"limit": 0}), json!({"limit": 5000})] { + let r = run(&mut s, "diagnostics.crash_reports", p.clone()); + matches(&list_schema, &r, false); + let listed = r["reports"].as_array().is_some_and(|a| a.iter().any(|x| x["id"] == id)); + assert_eq!(listed, p["limit"] != json!(0), "{p}: {r}"); + } + matches(&list_schema, &run(&mut s, "diagnostics.crash_reports", json!({"limit": "5"})), true); + let r = run(&mut s, "diagnostics.crash_report", json!({"id": id})); + matches(&report_schema, &r, false); + assert_eq!((r["id"].as_str(), r["count"].as_u64(), r["startup_phase"].as_str()), (Some(id), Some(2), Some("running")), "{r}"); + assert!(r["design_path"].is_string() && r["replay_path"].is_string() && r["path"].is_string(), "{r}"); + matches(&report_schema, &run(&mut s, "diagnostics.crash_report", json!({"id": id, "ids": [id]})), true); + matches(&cleared_schema, &run(&mut s, "diagnostics.crash_reports.clear", json!({"id": "20261101-120000-0000000000000000"})), false); + let mut strict = Session { param_check: ParamCheck::Strict, ..Session::default() }; + let error = strict.execute("diagnostics.crash_reports.clear", &json!({"id": 5})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("`id`"), "{error}"); + let r = run(&mut s, "diagnostics.crash_reports.clear", json!({"id": id})); + matches(&cleared_schema, &r, false); + assert_eq!(r["deleted"], 1, "the report was still there to delete: {r}"); +} + +/// The profiler records commands, the features they compute and the kernel below them, and +/// reports, resets and writes a Chrome trace through the command. +#[test] +fn diagnostics_profile_reports_commands_features_and_the_kernel() { + let _serial = super::PROFILE_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut s = Session::default(); + s.execute("diagnostics.profile", &json!({"reset": true, "enabled": true})).unwrap(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let r = s.execute("diagnostics.profile", &json!({"top": 0})).unwrap(); + assert_eq!((r["compiled"].as_bool(), r["enabled"].as_bool()), (Some(true), Some(true)), "{r}"); + let rows = r["rows"].as_array().unwrap(); + let row = |cat: &str, name: &str| rows.iter().find(|x| x["category"] == cat && x["name"] == name); + let cmd = row("command", "solid.box").unwrap_or_else(|| panic!("{r}")); + assert!(row("feature", "BoxFeature").is_some() && row("doc", "evaluate").is_some(), "{r}"); + assert!(row("kernel", "box_solid").is_some(), "{r}"); + assert!(cmd["self_ms"].as_f64().unwrap() <= cmd["total_ms"].as_f64().unwrap(), "{r}"); + assert_eq!(r["rows_total"].as_u64(), Some(rows.len() as u64)); + // `top` keeps the rows with the most self time. + let one = s.execute("diagnostics.profile", &json!({"top": 1})).unwrap(); + assert_eq!(one["rows"].as_array().map(Vec::len), Some(1)); + // A trace file, then stop and forget. + let dir = std::env::temp_dir().join(format!("solidcraft-profile-trace-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("trace.json").to_string_lossy().to_string(); + let since_trace = std::time::Instant::now(); + let t = s.execute("diagnostics.profile", &json!({"trace": path, "enabled": false, "reset": true})).unwrap(); + assert_eq!((t["trace"].as_str(), t["enabled"].as_bool()), (Some(path.as_str()), Some(false))); + let trace: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(trace["traceEvents"].as_array().unwrap().iter().any(|e| e["ph"] == "X" && e["name"] == "solid.box"), "{trace}"); + // Other tests run commands (this one among them) while it records, so the rows after the + // reset can hold theirs too. The wall time shows the reset: it starts again at the call that + // reset it, whose own span ends after the reset and is the one row certain to be there. + let after = s.execute("diagnostics.profile", &json!({})).unwrap(); + assert!(after["wall_ms"].as_f64().unwrap() <= since_trace.elapsed().as_secs_f64() * 1000.0 + 0.001, "{after}"); + let rows = after["rows"].as_array().unwrap(); + assert!(rows.iter().any(|x| x["category"] == "command" && x["name"] == "diagnostics.profile"), "{after}"); + assert_eq!(after["enabled"], json!(false), "{after}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Features are checked once each by default; the command reads and sets the mode, and the mode +/// is the user's: it stays when another design is started and when everything is computed again. +#[test] +fn validation_defaults_to_each_feature_and_round_trips_through_the_command() { + use solidcraft_kernel::Validation; + let mut s = Session::default(); + assert_eq!(s.validation(), Validation::EachFeature); + assert_eq!(s.execute("diagnostics.validation", &json!({})).unwrap(), json!({"mode": "each_feature", "previous": "each_feature"})); + let r = s.execute("diagnostics.validation", &json!({"mode": "each_step"})).unwrap(); + assert_eq!(r, json!({"mode": "each_step", "previous": "each_feature"})); + assert_eq!(s.validation(), Validation::EachStep); + s.execute("file.new", &json!({})).unwrap(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); + s.execute("timeline.compute_all", &json!({})).unwrap(); + assert_eq!(s.execute("diagnostics.validation", &json!({"mode": "off"})).unwrap()["previous"], json!("each_step")); + assert_eq!(s.validation(), Validation::Off); + // A refused mode changes nothing. + assert!(s.execute("diagnostics.validation", &json!({"mode": "never"})).is_err()); + assert_eq!(s.validation(), Validation::Off); +} + +/// A feature whose body SMLib's check refuses fails under each_feature as under each_step (once +/// at its end instead of at the step), with the check's reason; off keeps the body. The bar's +/// top edge rounded into the boss's round (kernel case +/// fillets/1207-fillet-bar-top-edge-after-boss-arc-round-r0-5, refused by the check on this +/// SMLib); the same features without the last round build under every mode, to the same volume. +#[test] +fn a_body_the_check_refuses_still_fails_its_feature_once_per_feature() { + use solidcraft_kernel::Validation; + let build = |mode: Validation, last: bool| { + let mut s = Session::default(); + s.set_validation(mode); + s.execute("solid.box", &json!({"length": 100, "width": 30, "height": 10, "corner": [0, -15, 0], "body_name": "Arm"})).unwrap(); + s.execute("solid.cylinder", &json!({"diameter": 40, "height": 20, "base": [0, 0, 0], "operation": "join", "targets": ["Arm"]})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[16, 12, 10]], "radius": 2})).unwrap(); + let r = if last { s.execute("solid.fillet", &json!({"edges": [[60, -15, 10]], "radius": 0.5})).map(|_| ()) } else { Ok(()) }; + let volume = s.execute("inspect.measure", &json!({})).ok().and_then(|m| m["total"]["volume_mm3"].as_f64()); + (r.map_err(|e| e.to_string()), volume) + }; + let each_step = build(Validation::EachStep, false); + for mode in [Validation::EachFeature, Validation::Off] { + let (r, volume) = build(mode, false); + assert!(r.is_ok() && each_step.0.is_ok(), "{mode:?}: {r:?}"); + assert!(volume.zip(each_step.1).is_some_and(|(v, w)| (v - w).abs() <= 1e-9 * w), "{mode:?}: {volume:?} vs {:?}", each_step.1); + } + let (step, _) = build(Validation::EachStep, true); + let (feature, _) = build(Validation::EachFeature, true); + assert_eq!(step.is_err(), feature.is_err(), "each_step {step:?}, each_feature {feature:?}"); + if let Err(e) = &feature { + assert!(e.contains("SMLib's check refuses the result"), "{e}"); + assert!(step.as_ref().err().is_some_and(|e| e.contains("SMLib's check refuses the result")), "{step:?}"); + let (off, _) = build(Validation::Off, true); + assert!(off.is_ok(), "off keeps the body the check refuses: {off:?}"); + } +} diff --git a/crates/engine/src/schema/drawing_view.rs b/crates/engine/src/schema/drawing_view.rs index 3276463d7..6a0c29da0 100644 --- a/crates/engine/src/schema/drawing_view.rs +++ b/crates/engine/src/schema/drawing_view.rs @@ -11,8 +11,8 @@ use std::borrow::Cow; use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use solidcore_record::Seg2; use solidcraft_doc::drawing_view::{TangentEdges, ViewDirection, ViewSettings}; -use solidcraft_geom::Seg2; use solidcraft_geom::drawing_sheet::{Orientation, PaperSize, SheetSize}; use solidcraft_geom::drawing_view::{NamedView, ProjectedSide, Scale}; use solidcraft_geom::paper::ObjectKind; @@ -619,7 +619,7 @@ pub struct ExtentsResult { /// `approximate`: measured on the display mesh; `placeholder`: nothing to measure, so the box is /// the placeholder's. pub status: &'static str, - /// `display_mesh`; with a placeholder, why: `past_walk_limit` or `no_bodies`. + /// `display_mesh`; with a placeholder, why: `past_walk_limit`, `no_bodies` or `not_placed`. pub provenance: &'static str, } diff --git a/crates/engine/src/schema/edit.rs b/crates/engine/src/schema/edit.rs index 901f33381..cffdbac66 100644 --- a/crates/engine/src/schema/edit.rs +++ b/crates/engine/src/schema/edit.rs @@ -1,7 +1,20 @@ //! Contracts and result types for the commands in `cmd/edit.rs`. -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +/// Assistant visibility is UI-owned and takes no parameters. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AssistantParams {} + +/// Headless sessions refuse Assistant display requests and produce no result. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AssistantResult {} /// `edit.repeat` takes no parameters: it starts the last tool with its defaults. #[derive(Debug, Deserialize, JsonSchema)] @@ -37,14 +50,139 @@ pub struct TimelinePlayResult { pub action: PlaybackAction, } +/// `edit.undo` takes no parameters: it takes back the last step of the undo history. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct UndoParams {} + +/// What `edit.undo` returns. With nothing to undo it is refused. +#[derive(Debug, Serialize, JsonSchema)] +pub struct UndoResult { + /// The name of the step taken back, as the undo history labels it. + pub undone: String, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// `edit.redo` takes no parameters: it does again the last step undone. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct RedoParams {} + +/// What `edit.redo` returns. With nothing to redo it is refused. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RedoResult { + /// The name of the step done again, as the undo history labels it. + pub redone: String, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// `edit.checkpoint` takes no parameters: it remembers the design, the active sketch and the +/// undo history, to go back to with `edit.restore_checkpoint`. The last 16 are kept, the oldest +/// dropped first. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CheckpointParams {} + +/// What `edit.checkpoint` and `edit.restore_checkpoint` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CheckpointResult { + /// The checkpoint's id. + pub checkpoint: u64, + /// `edit.restore_checkpoint` only: true when the design went back to it, false when it was + /// dropped (`forget`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub restored: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A checkpoint's id, as `edit.checkpoint` returns it: a whole number of at least 0. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CheckpointId(pub u64); + +impl<'de> Deserialize<'de> for CheckpointId { + fn deserialize>(d: D) -> Result { + Value::deserialize(d)?.as_u64().map(CheckpointId).ok_or_else(|| D::Error::custom("must be an id from edit.checkpoint")) + } +} + +impl JsonSchema for CheckpointId { + fn schema_name() -> Cow<'static, str> { + "CheckpointId".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "A checkpoint's id, from edit.checkpoint.", "type": "integer", "minimum": 0}) + } +} + +/// Go back to a checkpoint, undo history included; or, with `forget`, drop it without going +/// back. Either uses it up and every later checkpoint with it: take a new one to go back again. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct RestoreCheckpointParams { + /// The checkpoint, by the id `edit.checkpoint` returned. + pub checkpoint: CheckpointId, + /// True to drop the checkpoint (and every later one) without going back. Default: false. + #[serde(default)] + pub forget: Option, +} + #[cfg(test)] mod tests { - use super::RepeatParams; - use crate::schema::input_schema_for; - use crate::schema::tests::assert_keys; + use serde_json::{Value, json}; + + use super::{ + AssistantParams, CheckpointParams, CheckpointResult, RedoParams, RedoResult, RepeatParams, RestoreCheckpointParams, UndoParams, UndoResult, + }; + use crate::Session; + use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; + use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &["checkpoint", "forget"]); + } + + #[test] + fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("edit.restore_checkpoint", json!({"checkpoint": "first"})), + ("edit.restore_checkpoint", json!({"checkpoint": -1})), + ]); + } + + /// Undo, redo, a checkpoint, going back to it and forgetting one, in Warn: each reply matches + /// its output schema and carries no warning. + #[test] + fn replies_match_the_output_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: schemars::Schema, id: &str, reply: &Value| { + let schema = schema.as_value(); + assert!(reply.get("param_warnings").is_none() && conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}"); + }; + run("solid.box", json!({"length": 10, "width": 10, "height": 10})); + matches(output_schema_for::(), "edit.undo", &run("edit.undo", json!({}))); + matches(output_schema_for::(), "edit.redo", &run("edit.redo", json!({}))); + let taken = run("edit.checkpoint", json!({})); + matches(output_schema_for::(), "edit.checkpoint", &taken); + run("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]})); + let back = run("edit.restore_checkpoint", json!({"checkpoint": taken["checkpoint"]})); + assert_eq!(back["restored"], true, "{back}"); + matches(output_schema_for::(), "edit.restore_checkpoint", &back); + let again = run("edit.checkpoint", json!({})); + let dropped = run("edit.restore_checkpoint", json!({"checkpoint": again["checkpoint"], "forget": true})); + assert_eq!(dropped["restored"], false, "{dropped}"); + matches(output_schema_for::(), "edit.restore_checkpoint", &dropped); } } diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rs index d524553d8..ee83f04a0 100644 --- a/crates/engine/src/schema/features.rs +++ b/crates/engine/src/schema/features.rs @@ -7,11 +7,13 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; +use serde_json::Value; use super::types::{ - AngleExpr, AxisDir, AxisLine, ConventionParam, DirectionParam, ExtentKeyword, ExtrudeOperation, FacesParam, FeatureCommon, FromPoint, - GeoRefParam, IdOrName, LengthExpr, NumberExpr, OperationParam, PlaneCommon, PlaneOrFace, Point3, PointExpr3, ProfilesParam, ScaleFactors, - SketchRef, StringList, ThinSideParam, ToPoint, feature_common, present, + AngleExpr, AxisDir, AxisLine, ConventionParam, DirectionParam, EdgeRefs, ExtentKeyword, ExtrudeOperation, FacesParam, FeatureCommon, + FilletCornerParam, FilletFitParam, FilletTurnParam, FilletTypeParam, FromPoint, GeoRefParam, IdOrName, LengthExpr, NumberExpr, OperationParam, + PlaneCommon, PlaneOrFace, Point3, PointExpr3, ProfilesParam, ScaleFactors, SketchRef, StringList, ThinSideParam, ToPoint, TouchingParam, + feature_common, present, }; /// Add a box primitive. @@ -41,6 +43,9 @@ pub struct BoxParams { /// `participants` lists bodies. #[serde(default)] pub targets: Option, + /// What a join makes of pieces that share no face. Default: separate. + #[serde(default)] + pub touching: Option, /// The bodies a join, cut or intersect works on, in place of `targets`. #[serde(default)] pub participants: Option, @@ -138,6 +143,9 @@ pub struct ExtrudeParams { /// that body. #[serde(default)] pub targets: Option, + /// What a join makes of pieces that share no face. Default: separate. + #[serde(default)] + pub touching: Option, /// The bodies taking part; overrides the default scope. #[serde(default)] pub participants: Option, @@ -169,6 +177,29 @@ pub struct ExtrudeParams { pub thickness2: Option, } +/// Something a feature's result tells the user without stopping them, with an action to take. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FeatureNotice { + /// The text to show. + pub message: String, + /// How the bodies split off touched the others: `along_edge`, `at_point` or `touching` (along + /// a line or at a point their boundaries don't hold). + pub contact: String, + /// The command that changes the feature as the notice offers. + pub action: NoticeAction, +} + +/// A command a notice offers to run. +#[derive(Debug, Serialize, JsonSchema)] +pub struct NoticeAction { + /// The action's label. + pub label: String, + /// The command's id. + pub command: String, + /// Its parameters. + pub params: Value, +} + /// Add a cylinder primitive. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -402,6 +433,92 @@ pub struct PlaneAtAngleParams { pub common: PlaneCommon, } +/// Round edges of a body: a constant radius by default, or a chord, a curvature-continuous +/// section or a radius varying along each edge (`type`). +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct FilletParams { + /// The edges to round: a point on each, or `{body, index}`. + pub edges: EdgeRefs, + /// The radius; the chord's width with `type: chord`, the equivalent circular setback with + /// `type: curvature`, the start radius with `type: variable` or `spline`. + pub radius: LengthExpr, + /// The body whose edges the points pick. Default: whichever body has an edge there. + #[serde(default)] + pub body: Option, + /// Round each picked edge's tangent chain with it. Default: true; false rounds exactly the + /// picked edges. + #[serde(default)] + pub tangent_chain: Option, + #[serde(default, rename = "type")] + pub kind: Option, + /// `type: variable`: the radius at the end away from `start`; it or `radius` may be 0, where + /// the round closes to the corner. + #[serde(default)] + pub radius2: Option, + /// `type: variable` or `spline`: a point near the end the radius starts from. + #[serde(default)] + pub start: Option, + /// `type: variable`: radii between the ends, each `[position, radius]`, the position between 0 + /// and 1 from the start end. At most 100 are read. + #[serde(default)] + pub mid: Option>, + /// `type: variable`: smooth instead of straight between the radii. Default: false. + #[serde(default)] + pub smooth: Option, + /// `type: spline`: the control radii after `radius`. At most 100 are read. + #[serde(default)] + pub radii: Option>, + /// `type: spline`: the knot vector from 0 to 1, as many knots as all control radii, the + /// degree (1 to 3) and one more. + #[serde(default)] + pub knots: Option>, + #[serde(default)] + pub fit: Option, + #[serde(default)] + pub corner: Option, + /// Corner setbacks: the corner at the vertex nearest each `vertex`, where every edge meeting it + /// is rounded, starts its patch `distance` along each of those edges from the vertex, past + /// where the rounds would meet. Constant-radius exact fillets only. + #[serde(default)] + pub setbacks: Option>, + #[serde(default)] + pub turn: Option, + #[serde(flatten, deserialize_with = "feature_common")] + pub common: FeatureCommon, +} + +/// A fillet corner set back. +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SetbackParam { + /// A point at the corner's vertex. + pub vertex: Point3, + /// How far along each edge there the corner's patch starts. + pub distance: LengthExpr, +} + +/// The radius `fit: reduce` gave one edge. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppliedRadius { + /// A point on the edge. + pub edge: [f64; 3], + /// The radius it was rounded at. + pub radius: f64, +} + +/// What `solid.fillet` returns: a feature command's reply, with the radii `fit: reduce` used. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FilletResult { + #[serde(flatten)] + pub feature: FeatureResult, + /// With `fit: reduce` where it reduced the radius: the smallest radius used. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub radius_applied: Option, + /// With `fit: reduce` where it reduced the radius: each edge's radius. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub radii_applied: Option>, +} + /// What a feature command returns. #[derive(Debug, Serialize, JsonSchema)] pub struct FeatureResult { @@ -420,6 +537,12 @@ pub struct FeatureResult { /// A warning from the evaluation (a Boolean that needed a retry, a reference found again /// elsewhere), or `null`. pub warning: Option, + /// A join that split pieces into bodies of their own because they touch the others only along + /// an edge or at a point (its `touching: separate`): what to tell the user, and the edit that + /// makes them one body instead. Left out otherwise, also when the join kept pieces that touch + /// nothing in one body. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub notice: Option, /// How long the feature took to evaluate, in milliseconds. pub ms: Option, /// In the warn parameter-check mode: what the call's parameters got wrong. diff --git a/crates/engine/src/schema/features_tests.rs b/crates/engine/src/schema/features_tests.rs index 09bfb432f..bc55cbddb 100644 --- a/crates/engine/src/schema/features_tests.rs +++ b/crates/engine/src/schema/features_tests.rs @@ -1,8 +1,8 @@ use serde_json::{Value, json}; use super::{ - BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, OffsetPlaneParams, PipeParams, PlaneAtAngleParams, - ScaleParams, SphereParams, TorusParams, + BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, FilletParams, FilletResult, OffsetPlaneParams, + PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams, }; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms, sketch_rectangle}; @@ -12,7 +12,7 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; fn schemas_and_the_key_check_agree() { assert_keys( input_schema_for::(), - &["body_name", "body_names", "center", "corner", "height", "length", "name", "operation", "participants", "targets", "width"], + &["body_name", "body_names", "center", "corner", "height", "length", "name", "operation", "participants", "targets", "touching", "width"], ); assert_keys( input_schema_for::(), @@ -46,6 +46,7 @@ fn schemas_and_the_key_check_agree() { "through_all", "to", "to_offset", + "touching", ], ); assert_keys( @@ -86,6 +87,30 @@ fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["bodies", "factor", "factors", "name", "origin", "participants"]); assert_keys(input_schema_for::(), &["base", "name", "offset", "participants", "through"]); assert_keys(input_schema_for::(), &["angle", "axis", "base", "name", "participants"]); + assert_keys( + input_schema_for::(), + &[ + "body", + "body_name", + "body_names", + "corner", + "edges", + "fit", + "knots", + "mid", + "name", + "participants", + "radii", + "radius", + "radius2", + "setbacks", + "smooth", + "start", + "tangent_chain", + "turn", + "type", + ], + ); } #[test] @@ -156,6 +181,13 @@ fn strict_keeps_todays_errors() { ("construct.plane.at_angle", json!({"base": "XY", "axis": {"face": "x", "point": [0, 0, 0]}, "angle": 30})), ("construct.plane.at_angle", json!({"base": "XY", "axis": {"face": "x"}, "angle": 30})), ("construct.plane.at_angle", json!({"base": "XY", "axis": "X", "angle": true})), + ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "turn": "round"})), + ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "turn": "ROUND"})), + ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "type": "bogus"})), + ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "fit": "bogus"})), + ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "corner": "round"})), + ("solid.fillet", json!({"edges": [], "radius": 1})), + ("solid.fillet", json!({"edges": 5, "radius": 1})), ]); } @@ -174,6 +206,7 @@ fn feature_result_serializes_like_the_old_reply() { warning: warning.clone(), ms, param_warnings: vec![], + notice: None, }; assert_eq!(serde_json::to_value(&new).ok(), Some(old)); } @@ -211,6 +244,47 @@ fn replies_match_the_output_schema() { assert!(!conforms(schema, schema, &bad), "{bad}"); } +/// `solid.fillet` replies with `FilletResult` in each of its forms, its contract taking each: a +/// boss's base rounded with each turn and its options spelled out, a reduced round (with the radii +/// it used), chord and curvature rounds, a smooth-patch corner with setbacks, and the variable and +/// spline forms. +#[test] +fn fillet_replies_match_its_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + // A 40 x 30 x 10 plate with a 10 x 10 x 5 boss on it, whose base edges `boss` are. + let run = |p: Value| { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 10, "body_name": "B"})).unwrap_or_else(|e| panic!("{e}")); + s.execute("solid.box", &json!({"corner": [15, 10, 10], "length": 10, "width": 10, "height": 5, "operation": "join"})) + .unwrap_or_else(|e| panic!("{e}")); + let r = s.execute("solid.fillet", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{p}: {r}"); + r + }; + let boss = json!([[20, 10, 10], [25, 15, 10], [20, 20, 10], [15, 15, 10]]); + run( + json!({"edges": boss, "radius": 1, "turn": "mitre", "type": "constant", "fit": "exact", "corner": "rolling", "tangent_chain": true, "body": "B", "name": "Round"}), + ); + run(json!({"edges": boss, "radius": "1 mm", "turn": "Swept"})); + run(json!({"edges": boss, "radius": 1, "turn": "swept", "fit": "reduce"})); + let reduced = run(json!({"edges": [[20, 0, 10]], "radius": 15, "fit": "reduce"})); + assert!(reduced.get("radius_applied").is_some_and(Value::is_number) && reduced.get("radii_applied").is_some_and(Value::is_array), "{reduced}"); + run(json!({"edges": [[20, 0, 10]], "radius": 1, "type": "chord"})); + run(json!({"edges": [{"body": "B", "index": 0}], "radius": 0.5, "tangent_chain": false})); + run(json!({"edges": [[20, 0, 10]], "radius": 1, "type": "curvature"})); + // Variable and spline radii: solidcore fails a variable round on a box edge at this pin (status + // 1001, as `variable_radius_on_a_box_edge`), so their forms are checked against the contract. + for p in [ + json!({"edges": [[20, 0, 10]], "radius": 1, "type": "variable", "radius2": 2, "start": [0, 0, 10], "mid": [[0.5, "1.5 mm"]], "smooth": true}), + json!({"edges": [[20, 0, 10]], "radius": 1, "type": "spline", "start": [0, 0, 10], "radii": [2], "knots": [0, 0, 1, 1]}), + ] { + assert!(crate::schema::Contract::check(&crate::schema::TypedContract::::new(), &p).is_empty(), "{p}"); + } + run(json!({"edges": [[20, 0, 10], [40, 15, 10], [40, 0, 5]], "radius": 2, "corner": "g2", "setbacks": [{"vertex": [40, 0, 10], "distance": 4}]})); +} + /// The feature commands converted after box and extrude answer with `FeatureResult` too, and /// their contracts take every form these calls use: in Warn, a contract that refused one would /// still run the command, so the replies are checked for warnings too. diff --git a/crates/engine/src/schema/file.rs b/crates/engine/src/schema/file.rs new file mode 100644 index 000000000..58754f627 --- /dev/null +++ b/crates/engine/src/schema/file.rs @@ -0,0 +1,135 @@ +//! Contracts and result types for the commands in `cmd/file.rs`: so far the export command of +//! each format (`file.export_step`, `file.export_stl`, `file.export_3mf`, `file.export_obj`, +//! `file.export_urdf`), which take what `file.export` takes for that format, without `format`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::types::StringList; + +/// How closely an exported mesh follows curved faces. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum MeshQualityParam { + /// A chord tolerance of 2e-4 of each body's size. + Standard, + /// 5e-5 of each body's size. + Fine, + /// 1e-5 of each body's size. + Finest, +} + +/// What each 3MF object holds. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum ObjectsParam { + /// One object per body. + Body, + /// One object for each placed component with two or more bodies, with those bodies as its + /// parts, so a slicer loads them as one object with parts; other bodies stay objects of their own. + Component, +} + +/// Export bodies as a STEP file. With no `bodies`, a design with components exports as a STEP +/// assembly, otherwise its bodies as placed. The file is STEP whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportStepParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, +} + +/// Export bodies as a mesh file: binary STL for `file.export_stl`, OBJ for `file.export_obj` +/// (the colours of the bodies go in a material library, `.mtl`, written next to it). The file +/// has that format whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportMeshParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, + /// How closely the mesh follows curved faces. Default: standard. + #[serde(default)] + pub quality: Option, +} + +/// Export bodies as a 3MF file, whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct Export3mfParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, + /// How closely the mesh follows curved faces. Default: standard. + #[serde(default)] + pub quality: Option, + /// What each object in the file holds. Default: body. + #[serde(default)] + pub objects: Option, +} + +/// Export the whole assembly as a robot description (URDF), with an STL mesh for each link +/// written next to it (docs/urdf.md). +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportUrdfParams { + /// The `.urdf` file to write; the meshes go in its folder. + pub path: String, + /// Put before each mesh file name in the URDF, such as `package://robot/meshes/`. Default: none. + #[serde(default)] + pub mesh_prefix: Option, + /// Each joint's effort limit, a positive number. Default: 1000. + #[serde(default)] + pub effort: Option, + /// Each joint's velocity limit, a positive number. Default: 10. + #[serde(default)] + pub velocity: Option, +} + +/// What `file.export_step`, `file.export_stl`, `file.export_3mf` and `file.export_obj` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ExportResult { + /// The file written. + pub path: String, + /// Its size in bytes. + pub bytes: usize, + /// The format written: Step, StlBinary, ThreeMf or Obj. + pub format: String, + /// OBJ only: every file written, the material library first and the mesh file last. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub files: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `file.export_urdf` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct UrdfExportResult { + /// The `.urdf` file written. + pub path: String, + /// Always Urdf. + pub format: String, + /// Every file written, the meshes first and the `.urdf` last. + pub files: Vec, + /// How many links the robot has. + pub links: usize, + /// How many joints the robot has. + pub joints: usize, + /// What the export could not carry over as it is in the design. + pub warnings: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "file_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/file_tests.rs b/crates/engine/src/schema/file_tests.rs new file mode 100644 index 000000000..f040637bf --- /dev/null +++ b/crates/engine/src/schema/file_tests.rs @@ -0,0 +1,38 @@ +use serde_json::json; + +use super::{Export3mfParams, ExportMeshParams, ExportStepParams, ExportUrdfParams}; +use crate::Session; +use crate::schema::tests::assert_keys; +use crate::schema::{ParamCheck, input_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["bodies", "path"]); + assert_keys(input_schema_for::(), &["bodies", "path", "quality"]); + assert_keys(input_schema_for::(), &["bodies", "objects", "path", "quality"]); + assert_keys(input_schema_for::(), &["effort", "mesh_prefix", "path", "velocity"]); +} + +#[test] +fn bad_calls_say_what_is_wrong_and_write_nothing() { + let dir = std::env::temp_dir().join(format!("solidcraft-export-schemas-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}")); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + for cmd in ["file.export_step", "file.export_stl", "file.export_3mf", "file.export_obj", "file.export_urdf"] { + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains(cmd) && e.contains("path"), "{cmd}: {e}"); + } + let at = dir.join("a.stl").to_string_lossy().to_string(); + let e = s.execute("file.export_stl", &json!({"path": at, "quality": "rough"})).unwrap_err().to_string(); + assert!(e.contains("quality"), "{e}"); + s.param_check = ParamCheck::Strict; + let e = s.execute("file.export_stl", &json!({"path": at, "objects": "component"})).unwrap_err().to_string(); + assert!(e.contains("objects"), "objects is for 3MF only: {e}"); + s.param_check = ParamCheck::Off; + let e = s.execute("file.export_urdf", &json!({"path": at, "effort": -1})).unwrap_err().to_string(); + assert!(e.contains("effort"), "{e}"); + assert_eq!(std::fs::read_dir(&dir).map(|d| d.count()).unwrap_or(0), 0, "nothing written"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/schema/inspect.rs b/crates/engine/src/schema/inspect.rs index fc732e4f0..cc674dcf0 100644 --- a/crates/engine/src/schema/inspect.rs +++ b/crates/engine/src/schema/inspect.rs @@ -37,6 +37,209 @@ pub struct DescribeResult { pub param_warnings: Vec, } +/// List a body's edges or faces, with what picks each one. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct BodyListParams { + /// The body, by name. + pub body: String, +} + +/// List the design's cosmetic threads. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ModelThreadsParams {} + +/// What `model.edges` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ModelEdges { + /// The body's name. + pub body: String, + /// Its edges, in the kernel's order. + pub edges: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One edge of a body. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ModelEdge { + /// Its index, which changes when the body is rebuilt differently. + pub index: usize, + /// Its name, `|` from the faces it joins (numbered when repeated); `null` + /// when it has none. + pub name: Option, + /// The point halfway along it, which picks it. + pub mid: [f64; 3], + /// Its length (mm). + pub length: f64, + /// Where it starts; `null` for an edge with no points. + pub start: Option<[f64; 3]>, + /// Where it ends; `null` for an edge with no points. + pub end: Option<[f64; 3]>, +} + +/// What `model.faces` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ModelFaces { + /// The body's name. + pub body: String, + /// Its faces, in the kernel's order. + pub faces: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One face of a body. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ModelFace { + /// Its index, which changes when the body is rebuilt differently. + pub index: usize, + /// Its name: what `face.delete`, `sheet.convert`'s `face`, `solid.shell` and others take in + /// place of a point. `null` when it has none. + pub name: Option, + /// Whether the name follows the face's exact history; `false` when it was worked out from + /// the geometry, which an edit earlier in the timeline can fool. + pub exact: bool, + /// Its area (mm²). + pub area: f64, + /// Its centroid, which isn't always on the face. + pub centroid: [f64; 3], + /// Its outward unit normal if it is planar, else `null`. + pub plane_normal: Option<[f64; 3]>, + /// A point on the face that picks it; `null` when none was found. + pub point: Option<[f64; 3]>, + /// For a cylindrical face: its axis and radius. + #[serde(skip_serializing_if = "Option::is_none")] + pub cylinder: Option, + /// For a folded sheet's face: `sheet:::`, where the panel is `base` or a + /// flange's tag `F.` and the side is `top`, `bottom`, `rim.`, `bend.inner` + /// or `bend.outer`. It is taken wherever a face name is, and holds while sizes change and + /// flanges come and go. + #[serde(skip_serializing_if = "Option::is_none")] + pub sheet_face: Option, +} + +/// A cylindrical face's axis and radius. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FaceCylinder { + /// A point on the axis. + pub origin: [f64; 3], + /// The axis direction, a unit vector. + pub axis: [f64; 3], + /// The radius (mm). + pub radius: f64, +} + +/// What `model.threads` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ModelThreads { + /// The cosmetic threads, in timeline order. + pub threads: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A cosmetic thread: on which cylinder, its size, and the threaded part of the axis. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ModelThread { + /// The id of the thread feature. + pub feature: u64, + /// The body it is on. + pub body: String, + /// Its size, such as `M6x1`. + pub designation: String, + /// Its major diameter (mm). + pub major_diameter: f64, + /// The radius of the cylindrical face it is on (mm). + pub radius: f64, + /// Its pitch (mm). + pub pitch: f64, + /// Whether it is cut into a hole rather than on a shaft. + pub internal: bool, + /// Its form. + pub form: ThreadForm, + /// Which way it turns. + pub hand: ThreadHand, + /// How many starts it has. + pub starts: u32, + /// A point on the axis, which `start` and `end` are measured from. + pub axis_point: [f64; 3], + /// The axis direction, a unit vector. + pub axis: [f64; 3], + /// Where the threaded part starts along the axis from `axis_point` (mm). + pub start: f64, + /// Where it ends (mm). + pub end: f64, +} + +/// Which way a thread turns. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ThreadHand { + Right, + Left, + /// A right- and a left-handed groove crossing on one face (a reversing screw). + Both, +} + +/// A thread form: ISO metric 60°, metric trapezoidal 30°, Acme 29°, metric buttress 3°/30°, +/// buttress inch 7°/45°, square, and the 55° and 60° pipe threads. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ThreadForm { + Metric, + Trapezoidal, + Acme, + Buttress, + ButtressAsme, + Square, + Bspp, + Rp, + Bspt, + Npt, +} + +impl From<&solidcraft_doc::ThreadInfo> for ModelThread { + fn from(t: &solidcraft_doc::ThreadInfo) -> Self { + use solidcraft_doc::thread_forms::{ThreadForm as Form, ThreadHand as Hand}; + ModelThread { + feature: t.feature, + body: t.body.clone(), + designation: t.designation.clone(), + major_diameter: t.major_diameter, + radius: t.radius, + pitch: t.pitch, + internal: t.internal, + form: match t.form { + Form::Metric => ThreadForm::Metric, + Form::Trapezoidal => ThreadForm::Trapezoidal, + Form::Acme => ThreadForm::Acme, + Form::Buttress => ThreadForm::Buttress, + Form::ButtressAsme => ThreadForm::ButtressAsme, + Form::Square => ThreadForm::Square, + Form::Bspp => ThreadForm::Bspp, + Form::Rp => ThreadForm::Rp, + Form::Bspt => ThreadForm::Bspt, + Form::Npt => ThreadForm::Npt, + }, + hand: match t.hand { + Hand::Right => ThreadHand::Right, + Hand::Left => ThreadHand::Left, + Hand::Both => ThreadHand::Both, + }, + starts: t.starts, + axis_point: t.axis_point.into(), + axis: solidcore_record::Vec3::from(t.axis).into(), + start: t.start, + end: t.end, + } + } +} + #[cfg(test)] #[path = "inspect_tests.rs"] mod tests; diff --git a/crates/engine/src/schema/inspect_tests.rs b/crates/engine/src/schema/inspect_tests.rs index 9c0ef91f9..0281835f2 100644 --- a/crates/engine/src/schema/inspect_tests.rs +++ b/crates/engine/src/schema/inspect_tests.rs @@ -1,13 +1,15 @@ -use serde_json::json; +use serde_json::{Value, json}; -use super::DescribeParams; +use super::{BodyListParams, DescribeParams, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams}; use crate::Session; -use crate::schema::input_schema_for; -use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["command"]); + assert_keys(input_schema_for::(), &["body"]); + assert_keys(input_schema_for::(), &[]); } #[test] @@ -16,9 +18,60 @@ fn strict_keeps_todays_errors() { ("engine.describe", json!({"command": 5})), ("engine.describe", json!({"command": null})), ("engine.describe", json!({"command": "solid.extrud"})), + ("model.edges", json!({})), + ("model.edges", json!({"body": "Nope"})), + ("model.faces", json!({})), + ("model.faces", json!({"body": "Nope"})), ]); } +/// #10942: a body's edges and faces and the design's threads reply as their output schemas say, +/// in Warn without warnings for good calls and with them for a misspelt key. A cylindrical face +/// carries `cylinder` and a folded sheet's face `sheet_face`; strict refuses a `body` that isn't +/// text, which the handlers read as no body. +#[test] +fn model_lists_reply_with_their_schemas() { + let (edges, faces, threads) = (output_schema_for::(), output_schema_for::(), output_schema_for::()); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: &schemars::Schema, r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "body_name": "Shaft"})); + run(&mut s, "solid.thread", json!({"face": [4, 0, 10], "designation": "M8"})); + run(&mut s, "sheet.manage_rules", json!({"name": "R1", "thickness": "1 mm", "bend_radius": "1 mm", "active": true})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, 0], "p1": [60, 30]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Base"})); + let sheet = s.model.state().bodies.iter().map(|b| b.name.clone()).find(|n| n != "Shaft").unwrap_or_default(); + + let r = run(&mut s, "model.edges", json!({"body": "Shaft"})); + matches(&edges, &r, false); + assert!(r["edges"].as_array().is_some_and(|e| !e.is_empty()), "{r}"); + let r = run(&mut s, "model.faces", json!({"body": "Shaft"})); + matches(&faces, &r, false); + assert!(r["faces"].as_array().into_iter().flatten().any(|f| f["cylinder"]["radius"].as_f64().is_some_and(|r| (r - 4.0).abs() < 1e-9)), "{r}"); + let r = run(&mut s, "model.faces", json!({"body": sheet})); + matches(&faces, &r, false); + assert!(r["faces"].as_array().into_iter().flatten().any(|f| f["sheet_face"].as_str().is_some_and(|n| n.starts_with("sheet:"))), "{r}"); + let r = run(&mut s, "model.threads", json!({})); + matches(&threads, &r, false); + assert_eq!((r["threads"][0]["designation"].as_str(), r["threads"][0]["hand"].as_str()), (Some("M8"), Some("right")), "{r}"); + + matches(&edges, &run(&mut s, "model.edges", json!({"body": "Shaft", "bdy": 1})), true); + matches(&faces, &run(&mut s, "model.faces", json!({"body": "Shaft", "bdy": 1})), true); + matches(&threads, &run(&mut s, "model.threads", json!({"body": "Shaft"})), true); + let mut strict = Session { param_check: ParamCheck::Strict, ..Session::default() }; + strict.execute("solid.cylinder", &json!({"radius": 4, "height": 20, "body_name": "Shaft"})).unwrap_or_else(|e| panic!("{e}")); + for id in ["model.edges", "model.faces"] { + let error = strict.execute(id, &json!({"body": 5})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("`body` must be text"), "{id}: {error}"); + } +} + #[test] fn describe_returns_both_schemas() { let mut s = Session::default(); diff --git a/crates/engine/src/schema/joints.rs b/crates/engine/src/schema/joints.rs new file mode 100644 index 000000000..81c0afd61 --- /dev/null +++ b/crates/engine/src/schema/joints.rs @@ -0,0 +1,113 @@ +//! Contracts and result types for the commands in `cmd/joints.rs`. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use super::types::{AngleExpr, IdOrName, LengthExpr, present}; + +/// A joint origin as joint.create takes it: a joint origin's name, or an object with the snap +/// (`occurrence`, then `face`, `circle`, `edge` or `point`, or a `frame`). Kept as given, for the +/// handler, which reads it as it reads joint.create's sides. +#[derive(Clone, Debug, PartialEq)] +pub struct JointOriginParam(pub Value); + +impl<'de> Deserialize<'de> for JointOriginParam { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + v @ (Value::String(_) | Value::Object(_)) => Ok(JointOriginParam(v)), + _ => Err(D::Error::custom("must be a joint origin's name or an object")), + } + } +} + +impl JsonSchema for JointOriginParam { + fn schema_name() -> Cow<'static, str> { + "JointOrigin".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A joint origin, as joint.create takes a side: a joint origin's name, or an object with occurrence and face, circle, edge or point (world coordinates, or a face's name), with z?, x?, end?, on?, corner?, or with a frame {origin, z, x?}.", + "anyOf": [ + {"type": "string", "minLength": 1}, + {"type": "object"} + ] + }) + } +} + +/// Edit a joint in place. The sides `a` and `b` take a joint origin as joint.create does; a side +/// left out keeps its place, and the two must stay on different occurrences. The joint re-solves +/// and keeps its limits, its drive and the expressions it follows; a relation's values start +/// again where its parts are when its sides, type, offset, angle or flip change. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct EditJointParams { + /// The joint, by id or name. + pub joint: IdOrName, + /// Side a: a joint origin, as joint.create takes it. Default: a keeps its place. + #[serde(default, deserialize_with = "present")] + pub a: Option, + /// Side b: a joint origin, as joint.create takes it. Default: b keeps its place. + #[serde(default, deserialize_with = "present")] + pub b: Option, + /// The joint's type, as joint.create takes it (rigid, revolute, slider, ...). + #[serde(default, rename = "type", deserialize_with = "present")] + pub kind: Option, + /// Whether b's z lies along a's instead of against it, as joint.create's `flip`. + #[serde(default, deserialize_with = "present")] + pub flip: Option, + /// The distance from a's frame to b's along z: a length, or an expression the joint follows. + #[serde(default, deserialize_with = "present")] + pub offset: Option, + /// The turn about that distance: an angle, or an expression the joint follows. + #[serde(default, deserialize_with = "present")] + pub angle: Option, + /// Suppress the joint (true) or bring it back (false). + #[serde(default, deserialize_with = "present")] + pub suppressed: Option, + /// The joint's new name. + #[serde(default, deserialize_with = "present")] + pub name: Option, + /// Leave out the degrees of freedom and the fixed occurrences in the reply. + #[serde(default, deserialize_with = "present")] + pub quiet: Option, +} + +/// A joint the solve reports: its id, name and why. +#[derive(Debug, Serialize, JsonSchema)] +pub struct JointProblem { + pub joint: u64, + pub name: String, + pub why: String, +} + +/// The degrees of freedom one occurrence keeps (6 free, 0 fixed). +#[derive(Debug, Serialize, JsonSchema)] +pub struct OccurrenceDof { + pub occurrence: u64, + pub dof: usize, +} + +/// What `joint.edit` returns: the joints that disagree with the solved placement, and those the +/// solve could not apply. Unless `quiet`, also each occurrence's degrees of freedom and the +/// occurrences fixed in place. +#[derive(Debug, Serialize, JsonSchema)] +pub struct EditJointResult { + pub conflicts: Vec, + pub errors: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dof: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fixed: Option>, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "joints_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/joints_tests.rs b/crates/engine/src/schema/joints_tests.rs new file mode 100644 index 000000000..5fc406abc --- /dev/null +++ b/crates/engine/src/schema/joints_tests.rs @@ -0,0 +1,27 @@ +use serde_json::json; + +use super::{EditJointParams, EditJointResult}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["a", "angle", "b", "flip", "joint", "name", "offset", "quiet", "suppressed", "type"]); +} + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + s.execute("component.create", &json!({"name": "B", "grounded": false})).unwrap_or_else(|e| panic!("{e}")); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0]})).unwrap_or_else(|e| panic!("{e}")); + s.execute("joint.create", &json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}})) + .unwrap_or_else(|e| panic!("{e}")); + let full = s.execute("joint.edit", &json!({"joint": "Stack", "flip": true})).unwrap_or_else(|e| panic!("{e}")); + assert!(conforms(schema, schema, &full), "{full} doesn't match {schema}"); + let quiet = s.execute("joint.edit", &json!({"joint": "Stack", "quiet": true})).unwrap_or_else(|e| panic!("{e}")); + assert!(quiet.get("dof").is_none() && conforms(schema, schema, &quiet), "{quiet}"); +} diff --git a/crates/engine/src/schema/libraries.rs b/crates/engine/src/schema/libraries.rs new file mode 100644 index 000000000..345ee1e3e --- /dev/null +++ b/crates/engine/src/schema/libraries.rs @@ -0,0 +1,270 @@ +//! Contracts and result types for the commands in `cmd/libraries.rs`: local material libraries +//! (#10938). The handlers read these same types, so the contract is exactly what they take; +//! like them, a contract refuses unknown keys. + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use solidcraft_io::catalog::{Catalog, FORMAT, Provenance, V1_FORMAT}; + +/// Read a local library file and check it, without changing the design. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryInspectParams { + /// The library file (`solidcraft-library/1` or `/2` JSON, at most 4 MiB). + pub path: String, +} + +/// Write the looks assigned in this design and its own physical materials to a library file. +/// The design is never changed. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryExportParams { + /// Where to write it: a `.json` file. + pub path: String, + /// The library's id, which qualifies each entry's id: lowercase letters, digits, `.`, `_` + /// and `-`, starting with a letter, at most 64. + #[serde(default = "default_id")] + pub id: String, + /// The library's name: 1 to 128 bytes, without surrounding spaces or control characters. + #[serde(default = "default_name")] + pub name: String, + /// Where the entries come from, saved with each entry. + #[serde(default)] + #[schemars(schema_with = "provenance_schema")] + pub provenance: Provenance, + /// Replace the file if it exists. Without it, an existing file is refused and left as it is. + #[serde(default)] + pub overwrite: bool, + /// The file format. `solidcraft-library/1` refuses a design whose looks or materials have + /// PBR or physical cards, before writing anything. + #[serde(default = "default_format")] + #[schemars(schema_with = "format_schema")] + pub format: String, +} + +fn default_id() -> String { + "user.local".into() +} + +fn default_name() -> String { + "My library".into() +} + +fn default_format() -> String { + FORMAT.into() +} + +/// Copy one library entry, at an exact revision, into this design in one undo step: an +/// appearance onto bodies, faces or components, or a physical material (assigned to bodies). +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryApplyParams { + /// The library file. + pub path: String, + /// The entry's qualified id, as `library.inspect` lists it (at most 129 bytes). + pub entry: String, + /// The entry's revision, as `library.inspect` lists it: the SHA-256 of its content, 64 hex + /// digits. An entry whose content has changed since is refused. + pub revision: String, + /// What to copy it onto. An appearance needs at least one target; a physical material takes + /// bodies only, and with none it is only added to the design. + #[serde(default)] + pub targets: LibraryTargets, + /// For a physical material: the name to give it in this design (1 to 128 bytes). Default: + /// the entry's name. A material of that name already in the design is reused if it is the + /// same, and refused if it differs. An appearance entry refuses it. + pub name: Option, +} + +/// What a library entry is copied onto: at most 1024 targets in all. +#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryTargets { + /// Bodies, by name. + #[serde(default)] + pub bodies: Vec, + /// Faces, each by its body and a point on it (each coordinate finite and under 1e9 in size). + #[serde(default)] + pub faces: Vec, + /// Components, by name. + #[serde(default)] + pub components: Vec, +} + +/// A face, by its body and a point on it. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryFace { + /// The body's name. + pub body: String, + /// A point on the face. + pub point: [f64; 3], +} + +/// What `library.inspect` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryInspected { + /// The library as read and checked. + #[schemars(schema_with = "catalog_schema")] + pub catalog: Catalog, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `library.export` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryExported { + /// The file written. + pub path: String, + /// How many entries it holds. + pub entries: usize, + /// Its size in bytes. + pub bytes: usize, + /// The library as written. + #[schemars(schema_with = "catalog_schema")] + pub catalog: Catalog, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `library.apply` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryApplied { + /// The entry copied. + pub entry: String, + /// Its revision. + pub revision: String, + /// Always true: the entry's values were copied into the design, which keeps no link to the + /// file. + pub copied: bool, + /// What was done with it. + #[schemars(schema_with = "applied_schema")] + pub result: Value, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +fn provenance_schema(_: &mut SchemaGenerator) -> Schema { + // `provenance()` is an object, which a schema always takes. + Schema::try_from(provenance()).unwrap_or_else(|_| Schema::from(true)) +} + +fn provenance() -> Value { + let text = |what: &str, max: u32| json!({"description": format!("{what}: 1 to {max} bytes, without surrounding spaces or control characters."), "type": "string"}); + json!({ + "description": "Where a library entry comes from. Information only: the source URL is never fetched.", + "type": "object", + "properties": { + "license": text("Its licence, such as an SPDX expression", 128), + "author": text("Who made it", 256), + "source_url": text("Where it was published", 2048) + }, + "required": ["license"], + "additionalProperties": false + }) +} + +fn format_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "enum": [FORMAT, V1_FORMAT]}) +} + +/// A look as a library saves it. +fn look() -> Value { + json!({ + "description": "A look: its name, colour and opacity, and a physically based response when it has one.", + "type": "object", + "properties": { + "name": {"type": "string"}, + "color": {"description": "Red, green and blue, 0 to 255.", "type": "array", "items": {"type": "integer", "minimum": 0, "maximum": 255}, "minItems": 3, "maxItems": 3}, + "opacity": {"type": "number", "minimum": 0, "maximum": 1}, + "pbr": {"description": "metallic (0 to 1), roughness (0.045 to 1) and dielectric_ior (1 to 3).", "type": "object"} + }, + "required": ["name", "color", "opacity"] + }) +} + +fn catalog_schema(_: &mut SchemaGenerator) -> Schema { + let definition = |kind: &str, value: Value| { + json!({ + "type": "object", + "properties": {"kind": {"type": "string", "enum": [kind]}, "value": value}, + "required": ["kind", "value"] + }) + }; + let material = json!({ + "description": "A physical material: its name and density, with its default look and a physical card when it has them.", + "type": "object", + "properties": { + "name": {"type": "string"}, + "density_g_cm3": {"type": "number", "exclusiveMinimum": 0}, + "appearance": look(), + "physical_card": {"description": "Its validated engineering data, as material.inspect shows it.", "type": "object"} + }, + "required": ["name", "density_g_cm3"] + }); + json_schema!({ + "description": "A local library: no network, external resources or links to a design.", + "type": "object", + "properties": { + "format": {"type": "string", "enum": [FORMAT, V1_FORMAT]}, + "id": {"description": "The library's id.", "type": "string"}, + "name": {"description": "The library's name.", "type": "string"}, + "entries": { + "type": "array", + "maxItems": 1024, + "items": { + "type": "object", + "properties": { + "id": {"description": "`/-`, as library.apply takes it.", "type": "string"}, + "revision": {"description": "The SHA-256 of the entry's content, 64 hex digits, as library.apply takes it.", "type": "string"}, + "provenance": provenance(), + "definition": {"anyOf": [definition("appearance", look()), definition("material", material)]} + }, + "required": ["id", "revision", "provenance", "definition"] + } + } + }, + "required": ["format", "id", "name", "entries"] + }) +} + +fn applied_schema(_: &mut SchemaGenerator) -> Schema { + let names = |what: &str| json!({"description": what, "type": "array", "items": {"type": "string"}}); + json_schema!({ + "anyOf": [ + { + "description": "An appearance: what appearance.assign assigned it to, and the look.", + "type": "object", + "properties": { + "bodies": names("The bodies."), + "faces": { + "description": "The faces, each by its body and the point given.", + "type": "array", + "items": {"type": "object", "properties": {"body": {"type": "string"}, "point": {"type": "array", "items": {"type": "number"}}}} + }, + "components": names("The components."), + "appearance": {"description": "The look assigned: name, colour (`#rrggbb`), opacity and pbr when it has one.", "type": ["object", "null"]} + }, + "required": ["bodies", "faces", "components", "appearance"] + }, + { + "description": "A physical material: its name in this design, whether one already there was reused, and the bodies it was assigned to.", + "type": "object", + "properties": { + "material": {"type": "string"}, + "reused": {"type": "boolean"}, + "bodies": names("The bodies.") + }, + "required": ["material", "reused", "bodies"] + } + ] + }) +} + +#[cfg(test)] +#[path = "libraries_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/libraries_tests.rs b/crates/engine/src/schema/libraries_tests.rs new file mode 100644 index 000000000..6d0478687 --- /dev/null +++ b/crates/engine/src/schema/libraries_tests.rs @@ -0,0 +1,99 @@ +use serde_json::{Value, json}; + +use super::{LibraryApplied, LibraryApplyParams, LibraryExportParams, LibraryExported, LibraryInspectParams, LibraryInspected}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +/// A library file in the temporary folder, removed when dropped. +struct File(String); + +impl File { + fn new(name: &str) -> Self { + let name = format!("solidcraft-library-schema-{}-{name}.json", std::process::id()); + File(solidcraft_io::vfs::temp_dir().join(name).to_string_lossy().into_owned()) + } +} + +impl Drop for File { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["path"]); + assert_keys(input_schema_for::(), &["format", "id", "name", "overwrite", "path", "provenance"]); + assert_keys(input_schema_for::(), &["entry", "name", "path", "revision", "targets"]); +} + +#[test] +fn strict_keeps_todays_errors() { + let file = File::new("strict"); + assert_strict_keeps_todays_errors(&[ + ("library.inspect", json!({"path": ""})), + ("library.inspect", json!({"path": file.0})), + ("library.export", json!({"path": file.0.replace(".json", ".txt")})), + ("library.export", json!({"path": file.0, "format": "solidcraft-library/3"})), + ("library.export", json!({"path": file.0, "id": "Not An Id"})), + ("library.export", json!({"path": file.0, "provenance": {"license": ""}})), + ("library.apply", json!({"path": file.0, "entry": "user.local/appearance-0", "revision": "0"})), + ("library.apply", json!({"path": file.0, "entry": "e", "revision": "0", "targets": {"faces": [{"body": "B", "point": [1e10, 0, 0]}]}})), + ]); +} + +/// #10938: exporting, reading and applying a library reply as their output schemas say, in Warn +/// without warnings; an appearance entry and a physical material entry each take their own +/// branch of the `result` schema. Like the handlers, warn and strict refuse an unknown key. +#[test] +fn library_commands_reply_with_their_schemas() { + let file = File::new("replies"); + let (inspected, exported, applied) = + (output_schema_for::(), output_schema_for::(), output_schema_for::()); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: &schemars::Schema, r: &Value| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + }; + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(&mut s, "appearance.assign", json!({"bodies": ["Body1"], "color": [180, 120, 70], "opacity": 0.8})); + run(&mut s, "material.create", json!({"name": "Timber", "density_g_cm3": 0.7, "color": "#b47846"})); + run(&mut s, "material.assign", json!({"bodies": ["Body1"], "material": "Timber"})); + let provenance = json!({"license": "CC0-1.0", "author": "A tester", "source_url": "https://example.com/library"}); + let r = run(&mut s, "library.export", json!({"path": file.0, "id": "user.test", "name": "Test", "provenance": provenance})); + matches(&exported, &r); + assert!(r["entries"].as_u64() >= Some(2), "{r}"); + let v1 = File::new("replies-v1"); + matches(&exported, &run(&mut s, "library.export", json!({"path": v1.0, "format": "solidcraft-library/1", "overwrite": true}))); + let r = run(&mut s, "library.inspect", json!({"path": file.0})); + matches(&inspected, &r); + let entries = r["catalog"]["entries"].as_array().cloned().unwrap_or_default(); + let entry = |kind: &str| { + entries + .iter() + .find(|e| e["definition"]["kind"] == kind) + .map(|e| (e["id"].clone(), e["revision"].clone())) + .unwrap_or_else(|| panic!("no {kind} in {r}")) + }; + let (look, look_revision) = entry("appearance"); + let targets = json!({"bodies": ["Body1"], "faces": [{"body": "Body1", "point": [10, 5, 5]}], "components": []}); + let r = run(&mut s, "library.apply", json!({"path": file.0, "entry": look, "revision": look_revision, "targets": targets})); + matches(&applied, &r); + assert!(r["result"]["appearance"].is_object(), "{r}"); + let (material, material_revision) = entry("material"); + let r = run( + &mut s, + "library.apply", + json!({"path": file.0, "entry": material, "revision": material_revision, "targets": {"bodies": ["Body1"]}, "name": null}), + ); + matches(&applied, &r); + assert_eq!((r["result"]["material"].as_str(), r["result"]["reused"].as_bool()), (Some("Timber"), Some(true)), "{r}"); + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = Session { param_check: level, ..Session::default() }; + let error = s.execute("library.inspect", &json!({"path": file.0, "pth": 1})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("pth"), "{level:?}: {error}"); + } +} diff --git a/crates/engine/src/schema/mass_properties.rs b/crates/engine/src/schema/mass_properties.rs new file mode 100644 index 000000000..4775ab50e --- /dev/null +++ b/crates/engine/src/schema/mass_properties.rs @@ -0,0 +1,114 @@ +//! Contracts and result types for the commands in `cmd/mass_properties.rs`. +//! +//! The reply types are also the Rust API a dynamics solver reads (`Session::mass_properties`): +//! units are kg, mm and kg·mm² throughout. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Mass, centre of mass and inertia tensor of every occurrence of the design and of every rigid +/// group (occurrences joined by rigid joints, which move as one body), from each body's material +/// density. Read-only. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AssemblyMassParams {} + +/// A placed coordinate frame in world coordinates (mm): its origin and its unit axes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct MassFrame { + pub origin: [f64; 3], + pub x: [f64; 3], + pub y: [f64; 3], + pub z: [f64; 3], +} + +/// Mass, centre of mass and inertia tensor of one rigid body (or of several taken as one). +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct RigidMass { + /// Mass in kg. + pub mass_kg: f64, + /// Centre of mass in world coordinates, mm. + pub center_of_mass_mm: [f64; 3], + /// Centre of mass in the frame's coordinates, mm. + pub center_of_mass_local_mm: [f64; 3], + /// Inertia tensor about the centre of mass, world axes, kg·mm², row by row: the moments on + /// the diagonal (Ixx = ∫ (y² + z²) dm …), the negated products of inertia off it + /// (−∫ x y dm …), as URDF and most dynamics libraries take it. `null` when a closed body's + /// mesh does not close (a warning names it). + pub inertia_world_kg_mm2: Option<[[f64; 3]; 3]>, + /// The same tensor in the frame's axes, kg·mm². `null` as above, or when the frame is + /// scaled (its axes are not a rotation). + pub inertia_local_kg_mm2: Option<[[f64; 3]; 3]>, +} + +/// One body of an occurrence. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct BodyMassEntry { + pub name: String, + /// Its physical material (the default material when none is assigned). + pub material: String, + pub density_g_cm3: f64, + /// A closed solid: an open body (a surface) has no volume and adds no mass. + pub closed: bool, + /// Volume in mm³ and mass in kg, for a closed body only. + pub volume_mm3: Option, + pub mass_kg: Option, +} + +/// One occurrence (0: the design's own bodies, which never move). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct OccurrenceMass { + pub occurrence: u64, + pub name: String, + /// The component it places. + pub component: u64, + /// Occurrence ids from the top of the assembly down (empty for 0). + pub path: Vec, + /// Index of its rigid group in `groups`. + pub group: usize, + /// Grounded, or the design itself. + pub fixed: bool, + /// The occurrence's frame (its component's origin and axes as placed). + pub frame: MassFrame, + pub bodies: Vec, + /// Bodies left out because they are not closed solids. + pub open_bodies_skipped: usize, + /// Its own bodies' totals in its frame; `null` when it holds no closed body. + pub mass: Option, +} + +/// Occurrences that move as one body. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct RigidGroupMass { + /// Its index in `groups`. + pub group: usize, + /// The occurrences it holds, ascending (0: the design's own bodies). + pub occurrences: Vec, + /// Holds the design itself or a grounded occurrence: it does not move. + pub fixed: bool, + /// The occurrence whose frame `frame` is: 0 (world) for a fixed group holding the design, + /// else the group's lowest occurrence id. + pub frame_occurrence: u64, + pub frame: MassFrame, + /// Totals of all its occurrences in `frame` (parallel-axis theorem); `null` when massless. + pub mass: Option, +} + +/// What `assembly.mass_properties` returns. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct AssemblyMassResult { + /// Every occurrence, the design's own bodies (0) first, then by occurrence id. + pub occurrences: Vec, + /// The rigid groups, in order of their lowest occurrence id. + pub groups: Vec, + /// Approximations made (open bodies, repeated subassemblies, scaled frames). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "mass_properties_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/mass_properties_tests.rs b/crates/engine/src/schema/mass_properties_tests.rs new file mode 100644 index 000000000..6f42ba965 --- /dev/null +++ b/crates/engine/src/schema/mass_properties_tests.rs @@ -0,0 +1,28 @@ +use serde_json::json; + +use super::{AssemblyMassParams, AssemblyMassResult}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &[]); +} + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let empty = s.execute("assembly.mass_properties", &json!({})).unwrap_or_else(|e| panic!("{e}")); + assert!(conforms(schema, schema, &empty), "{empty} doesn't match {schema}"); + assert!(empty.get("param_warnings").is_none(), "{empty}"); + s.execute("component.create", &json!({"name": "Block"})).unwrap_or_else(|e| panic!("{e}")); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + let r = s.execute("assembly.mass_properties", &json!({"unknown_extra": 1})).unwrap_or_else(|e| panic!("{e}")); + assert!(r.get("param_warnings").is_some(), "{r}"); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + s.param_check = ParamCheck::Strict; + assert!(s.execute("assembly.mass_properties", &json!({"unknown_extra": 1})).is_err()); +} diff --git a/crates/engine/src/schema/material_properties.rs b/crates/engine/src/schema/material_properties.rs new file mode 100644 index 000000000..b04e1e017 --- /dev/null +++ b/crates/engine/src/schema/material_properties.rs @@ -0,0 +1,184 @@ +//! Contracts and result types for the commands in `cmd/material_properties.rs`: checking an +//! engineering material card, and its elastic modulus in a direction (#11036). + +use std::borrow::Cow; +use std::collections::BTreeMap; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; +use solidcraft_doc::physical_material::{DirectionalModulus, IsotropicModuli, MaterialAxes, Validation}; + +use super::check::whole; + +/// Check an engineering material card: its numbers' consistency, the isotropic moduli they +/// imply, and the conditions and sources still to review. Read-only: nothing is assigned or +/// saved, and there is no analysis solver. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ValidateCardParams { + #[schemars(schema_with = "card_schema")] + pub card: Value, +} + +/// The Young modulus of an engineering material card in one direction, in the card's own +/// material axes. Read-only: no load case or structural solver. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct DirectionalModulusParams { + #[schemars(schema_with = "card_schema")] + pub card: Value, + pub direction: CardDirection, +} + +/// The card, checked by the handler (`admit_card`), with its messages. +fn card_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A schema_version 1 engineering material card in SI units (see docs/physical-material-cards.md).", + "type": "object" + }) +} + +/// A direction in the card's material axes: three numbers, not all zero, with the handler's +/// messages. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CardDirection(pub [f64; 3]); + +impl<'de> Deserialize<'de> for CardDirection { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + let a = + v.as_array().filter(|a| a.len() == 3).ok_or_else(|| D::Error::custom(whole("direction: expected exactly three numeric components")))?; + let c = |i: usize| a.get(i).and_then(Value::as_f64).ok_or_else(|| D::Error::custom(whole("direction: expected numeric components"))); + Ok(CardDirection([c(0)?, c(1)?, c(2)?])) + } +} + +impl JsonSchema for CardDirection { + fn schema_name() -> Cow<'static, str> { + "CardDirection".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A direction in the card's material axes: three numbers, not all zero.", + "type": "array", + "items": {"type": "number"}, + "minItems": 3, + "maxItems": 3 + }) + } +} + +/// What `material.properties.validate` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CardValidated { + /// Always true: a card that isn't valid is refused. + pub valid: bool, + pub validation: CardValidation, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `material.properties.directional` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CardModulus { + /// The direction, made a unit vector. + pub direction: [f64; 3], + /// The card's material axes, when it has directional properties. + pub axes: Option, + /// The Young modulus in that direction (Pa). + pub young_modulus_pa: f64, + pub validation: CardValidation, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +impl From for CardModulus { + fn from(m: DirectionalModulus) -> Self { + let DirectionalModulus { direction, axes, young_modulus_pa, validation } = m; + CardModulus { direction, axes: axes.map(CardAxes::from), young_modulus_pa, validation: validation.into(), param_warnings: Vec::new() } + } +} + +/// A card's material axes. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum CardAxes { + /// The material's own axes 1, 2 and 3. + Material123, + /// Wood's longitudinal, radial and tangential axes. + WoodLrt, +} + +impl From for CardAxes { + fn from(a: MaterialAxes) -> Self { + match a { + MaterialAxes::Material123 => CardAxes::Material123, + MaterialAxes::WoodLrt => CardAxes::WoodLrt, + } + } +} + +/// What checking a card found. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CardValidation { + pub schema_version: u32, + /// The kinds of property the card gives. + pub property_kinds: Vec, + /// The shear and bulk moduli an isotropic card's numbers imply. + pub isotropic_moduli: Option, + /// The property kinds given without every condition they hold at (temperature, state, and + /// moisture for wood or strain rate for polymers). + pub unspecified_conditions: Vec, + /// Per property kind: the condition fields it lacks. + pub missing_condition_fields: BTreeMap>, + /// The sources the card's properties cite, which still need review. + pub source_review_required: Vec, + /// Always false: there is no analysis solver. + pub analysis_solver_available: bool, + /// Always false: a card holds no rendering properties. + pub rendering_properties_available: bool, +} + +impl From for CardValidation { + fn from(v: Validation) -> Self { + // In full, so a field added to `Validation` fails here rather than going missing. + let Validation { + schema_version, + property_kinds, + isotropic_moduli, + unspecified_conditions, + missing_condition_fields, + source_review_required, + analysis_solver_available, + rendering_properties_available, + } = v; + CardValidation { + schema_version, + property_kinds, + isotropic_moduli: isotropic_moduli.map(|IsotropicModuli { shear_pa, bulk_pa }| CardModuli { shear_pa, bulk_pa }), + unspecified_conditions, + missing_condition_fields, + source_review_required, + analysis_solver_available, + rendering_properties_available, + } + } +} + +/// The isotropic moduli a card's numbers imply. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CardModuli { + pub shear_pa: f64, + pub bulk_pa: f64, +} + +#[cfg(test)] +#[path = "material_properties_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/material_properties_tests.rs b/crates/engine/src/schema/material_properties_tests.rs new file mode 100644 index 000000000..810460eb0 --- /dev/null +++ b/crates/engine/src/schema/material_properties_tests.rs @@ -0,0 +1,58 @@ +use serde_json::{Value, json}; + +use super::{CardModulus, CardValidated, DirectionalModulusParams, ValidateCardParams}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +/// An isotropic card, as the command's own tests write one. +fn card() -> Value { + json!({"schema_version":1,"designation":"Original synthetic card, not design data","family":"other", + "sources":[{"id":"fixture","title":"Original analytic constants","kind":"illustrative","license":"MIT OR Apache-2.0"}], + "properties":[{"source_id":"fixture","conditions":{"temperature_k":293.15,"state":"synthetic"}, + "data":{"kind":"density","kg_m3":700.0}}, + {"source_id":"fixture","data":{"kind":"elasticity","model":{ + "symmetry":"isotropic","young_modulus_pa":12.25e9,"poisson_ratio":0.25}}}]}) +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["card"]); + assert_keys(input_schema_for::(), &["card", "direction"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("material.properties.validate", json!({"card": {}})), + ("material.properties.validate", json!({"card": null})), + ("material.properties.directional", json!({"card": {}, "direction": [1, 0, 0]})), + ("material.properties.directional", json!({"card": card(), "direction": [1, 0]})), + ("material.properties.directional", json!({"card": card(), "direction": "x"})), + ("material.properties.directional", json!({"card": card(), "direction": [1, "a", 0]})), + ("material.properties.directional", json!({"card": card(), "direction": [0, 0, 0]})), + ]); +} + +/// #11036: both commands reply as their output schemas say, in Warn without warnings. Like the +/// handlers, warn and strict refuse a key they don't take, so no reply carries a warning. +#[test] +fn card_commands_reply_with_their_schemas() { + let (validated, modulus) = (output_schema_for::(), output_schema_for::()); + let matches = |schema: &schemars::Schema, r: &Value| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let r = s.execute("material.properties.validate", &json!({"card": card()})).unwrap_or_else(|e| panic!("{e}")); + matches(&validated, &r); + assert!(r["valid"] == true && r["validation"]["isotropic_moduli"]["shear_pa"].is_number(), "{r}"); + let r = s.execute("material.properties.directional", &json!({"card": card(), "direction": [1, 1, 0]})).unwrap_or_else(|e| panic!("{e}")); + matches(&modulus, &r); + assert!(r["axes"].is_null() && (r["young_modulus_pa"].as_f64().unwrap_or(0.0) - 12.25e9).abs() < 1.0, "{r}"); + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = Session { param_check: level, ..Session::default() }; + assert!(s.execute("material.properties.validate", &json!({"card": card(), "crd": 1})).is_err(), "{level:?}"); + } +} diff --git a/crates/engine/src/schema/metadata.rs b/crates/engine/src/schema/metadata.rs new file mode 100644 index 000000000..f30b02303 --- /dev/null +++ b/crates/engine/src/schema/metadata.rs @@ -0,0 +1,84 @@ +//! Contracts and result types for the commands in `cmd/metadata.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +/// Read the design's properties: its `metadata` object as saved, and SolidCraft's own design +/// properties (project, part number, revision…) as text. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MetadataParams {} + +/// What `document.metadata` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MetadataResult { + /// The design's metadata object as saved, other tools' keys included. + pub metadata: Map, + /// Each of SolidCraft's design properties, by key: its text, or null when it is absent or + /// not text. + pub properties: Map, +} + +/// Change design properties in one undo step: `key` and `value`, or `values` for several at +/// once (all or nothing). A change that sets what is already there makes no undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MetadataSetParams { + /// The property to set: one of SolidCraft's keys (the ones `document.metadata`'s + /// `properties` lists), which take text, or another tool's reverse-DNS key such as + /// `com.example.tool`, which takes an object. `bom_type` is a component's property and is + /// refused here. Needs `value`; not with `values`. + #[serde(default)] + pub key: Option, + /// The value for `key`: text for SolidCraft's keys, an object for another tool's. `""` or + /// null removes the key. Required with `key`. + #[serde(default)] + #[schemars(with = "Value")] + pub value: Option, + /// Several properties at once, `{key: value, …}`, at most 256 keys, each as `key` and + /// `value` take them. Not with `key`. + #[serde(default)] + pub values: Option>, +} + +/// What `document.metadata.set` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MetadataSetResult { + /// The design's metadata object after the change. + pub metadata: Map, + /// The keys whose value changed, in key order. + pub changed: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Remove design properties in one undo step: `key`, or `keys` for several. Any key can go, +/// also one another tool wrote; a key that isn't there is left out of `removed`. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MetadataRemoveParams { + /// The property to remove. Not with `keys`. + #[serde(default)] + pub key: Option, + /// The properties to remove, at most 256. Not with `key`. + #[serde(default)] + pub keys: Option>, +} + +/// What `document.metadata.remove` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MetadataRemoveResult { + /// The design's metadata object after the change. + pub metadata: Map, + /// The keys that were there and are removed, each once, in the order asked. + pub removed: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "metadata_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/metadata_tests.rs b/crates/engine/src/schema/metadata_tests.rs new file mode 100644 index 000000000..c4c7699c7 --- /dev/null +++ b/crates/engine/src/schema/metadata_tests.rs @@ -0,0 +1,54 @@ +use serde_json::{Value, json}; + +use super::{MetadataParams, MetadataRemoveParams, MetadataRemoveResult, MetadataResult, MetadataSetParams, MetadataSetResult}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &["key", "value", "values"]); + assert_keys(input_schema_for::(), &["key", "keys"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("document.metadata.set", json!({"key": 5, "value": "Gearbox"})), + ("document.metadata.remove", json!({"key": 5})), + ]); +} + +/// Every form of the three commands, in Warn: each reply matches its output schema and carries +/// no warning; a misspelt key's warning still matches. +#[test] +fn replies_match_the_output_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: schemars::Schema, reply: &Value| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, reply), "{reply} doesn't match {schema}"); + }; + let set = |reply: &Value| matches(output_schema_for::(), reply); + let remove = |reply: &Value| matches(output_schema_for::(), reply); + let calls = [ + ("document.metadata.set", json!({"values": {"author": "Jane Doe", "com.acme.shop": {"shop_id": 88123}}})), + ("document.metadata.set", json!({"key": "project", "value": "Gearbox"})), + ("document.metadata.set", json!({"key": "project", "value": null})), + ("document.metadata.remove", json!({"keys": ["author", "author", "not.there"]})), + ("document.metadata.remove", json!({"key": "com.acme.shop"})), + ]; + for (id, p) in calls { + let reply = run(id, p.clone()); + assert!(reply.get("param_warnings").is_none(), "{id} {p}: {reply}"); + if id == "document.metadata.set" { set(&reply) } else { remove(&reply) } + } + run("document.metadata.set", json!({"key": "part_number", "value": "ACME-1042"})); + let read = run("document.metadata", json!({})); + assert_eq!(read["properties"]["part_number"], "ACME-1042"); + matches(output_schema_for::(), &read); + let warned = run("document.metadata.set", json!({"key": "author", "value": "J", "valeu": 1})); + assert!(warned["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{warned}"); + set(&warned); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 7640cc077..88efba290 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -54,9 +54,15 @@ mod coverage_tests; pub(crate) mod tests; // The contracts, by command file. +pub mod appearance; pub mod bom; +pub mod browser; +pub mod clearance; +pub mod compare; pub mod component; +pub mod config; pub mod construct; +pub mod diagnostics; pub mod drawing; pub mod drawing_balloon; pub mod drawing_dimension; @@ -68,14 +74,32 @@ pub mod drawing_sheet; pub mod drawing_view; pub mod edit; pub mod features; +pub mod file; pub mod inspect; +pub mod joints; +pub mod libraries; +pub mod mass_properties; +pub mod material_properties; +pub mod metadata; +pub mod motion; +pub mod panels; +pub mod print_face; pub mod render; pub mod render_lights; +pub mod render_stage; pub mod render_ui; +pub mod section; pub mod sheet; +pub mod sketch; pub mod sketch_constraints; pub mod sketch_create; +pub mod sketch_ends; pub mod sketch_equation; +pub mod sketch_inspect; +pub mod surface_analysis; +pub mod surface_boundary; +pub mod surface_match; +pub mod ui_prefs; pub mod view_navigation; pub(crate) use check::read; diff --git a/crates/engine/src/schema/motion.rs b/crates/engine/src/schema/motion.rs new file mode 100644 index 000000000..87ad20186 --- /dev/null +++ b/crates/engine/src/schema/motion.rs @@ -0,0 +1,166 @@ +//! Contracts and result types for the commands in `cmd/motion.rs`. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +/// Find where each value of a joint can go before the parts it moves touch another body. The +/// design is not changed. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct FindLimitsParams { + pub joint: JointRef, + /// Which value (0 for a revolute's angle). Default: every value of the joint. + #[serde(default)] + pub index: Option, + /// mm: each stop is bisected until no part moves more than this between the last clear value + /// and the touching one (above 0, at most 1000). Default: 0.01. + #[serde(default)] + pub refine: Option, + /// Between samples, in the value's unit (degrees for angles, mm for distances; above 0). + /// Default: fine enough that no part passes through another between two. + #[serde(default)] + pub step: Option, + /// The parts checked against each other. Default: every occurrence. + #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Vec")] + pub occurrences: Option>, + /// The parts that stay: each of `occurrences` is checked only against these. + #[serde(default)] + pub against: Option>, + /// Check the pairs of the design's contact sets instead (not with `occurrences`). + #[serde(default)] + pub contact_sets: Option, +} + +/// A joint by its id (a number) or its name. +#[derive(Debug)] +pub struct JointRef; + +impl<'de> Deserialize<'de> for JointRef { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::Number(_) | Value::String(_) => Ok(JointRef), + _ => Err(D::Error::custom("must be an id or a name")), + } + } +} + +impl JsonSchema for JointRef { + fn schema_name() -> Cow<'static, str> { + "JointRef".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "A joint's id (a number) or its name.", "type": ["number", "string"]}) + } +} + +/// An occurrence by its id (a number) or its name. +#[derive(Debug)] +pub struct PartRef; + +impl<'de> Deserialize<'de> for PartRef { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::Number(_) | Value::String(_) => Ok(PartRef), + _ => Err(D::Error::custom("an occurrence must be an id or a name")), + } + } +} + +impl JsonSchema for PartRef { + fn schema_name() -> Cow<'static, str> { + "PartRef".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "An occurrence's id (a number) or its name.", "type": ["number", "string"]}) + } +} + +/// What stopped one side of a sweep. +#[derive(Clone, Debug, PartialEq, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum Stop { + /// Two parts touch. + Contact { + a: String, + b: String, + /// Where they touch (world, mm). + at: [f64; 3], + }, + /// `loop`: a closed loop can no longer close; `limit`: the limit of another of the joint's + /// values, or of another joint through a motion link; `turn`: no contact within one turn, so the side is a turn from the other; + /// `range`: no contact within the parts' reach (a distance), so the side has no limit. + Other(Why), +} + +/// Why a side stopped short of contact. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum Why { + Loop, + Limit, + Turn, + Range, +} + +/// One value's limits. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FoundLimits { + /// Which value of the joint. + pub index: usize, + /// Its name (angle, distance, …). + pub dof: String, + /// `deg` or `mm`. + pub unit: String, + /// Where it is now, which the search starts from. + pub value: f64, + /// The lowest value clear of contact, or `null` (`min_by` is `range`). + pub min: Option, + /// The highest value clear of contact, or `null` (`max_by` is `range`). + pub max: Option, + pub min_by: Stop, + pub max_by: Stop, + /// How far each way the search went: a turn (360) for an angle, the parts' reach for a + /// distance. + pub range: f64, +} + +/// Two parts already passing into each other where the search starts. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Overlap { + pub a: String, + pub b: String, + /// How deep (mm). + pub depth_mm: f64, +} + +/// What `joint.find_limits` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FindLimitsResult { + pub joint: u64, + pub name: String, + pub values: Vec, + pub refine_mm: f64, + /// `mesh`: distances between the parts' tessellations. + pub gap_method: String, + /// How far those can be off: 0 when every face is flat. + pub gap_tolerance_mm: f64, + /// How many pairs of parts are checked. + pub pairs: usize, + /// Pairs of parts touching where the search starts: they stop it only once they pass into + /// each other deeper than they start. + pub touching_at_start: Vec<[String; 2]>, + /// Pairs of those already passing into each other, deeper than a touch. + pub overlapping_at_start: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "motion_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/motion_tests.rs b/crates/engine/src/schema/motion_tests.rs new file mode 100644 index 000000000..e7135a8bc --- /dev/null +++ b/crates/engine/src/schema/motion_tests.rs @@ -0,0 +1,59 @@ +use serde_json::{Value, json}; + +use super::{FindLimitsParams, FindLimitsResult}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["against", "contact_sets", "index", "joint", "occurrences", "refine", "step"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("joint.find_limits", json!({"joint": true})), + ("joint.find_limits", json!({"joint": null})), + ("joint.find_limits", json!({"joint": "Hinge"})), + ]); +} + +/// A 100 × 4 × 50 door hinged about Z at the origin, a block in its way and a slider beside it. +fn door() -> Session { + let mut s = Session::default(); + for (name, corner, size) in [("Door", [0, 0, 0], [100, 4, 50]), ("Block", [60, 30, 0], [20, 20, 50]), ("Slide", [0, -40, 0], [10, 10, 10])] { + for (id, p) in [ + ("component.activate", json!({"component": "root"})), + ("component.create", json!({"name": name, "grounded": false})), + ("solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})), + ] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + } + } + for p in [ + json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}), + json!({"type": "slider", "a": {"occurrence": 0, "point": [0, -40, 0], "z": [1, 0, 0]}, "b": {"occurrence": "Slide", "point": [0, -40, 0], "z": [1, 0, 0]}, "flip": true, "name": "Rail"}), + ] { + s.execute("joint.create", &p).unwrap_or_else(|e| panic!("{e}")); + } + s +} + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = door(); + s.param_check = ParamCheck::Warn; + for p in [json!({"joint": "Hinge"}), json!({"joint": "Rail", "index": 0, "refine": 0.1, "occurrences": ["Slide", "Door"]})] { + let r = s.execute("joint.find_limits", &p).unwrap_or_else(|e| panic!("{e}")); + assert!(r.get("param_warnings").is_none(), "{r}"); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + } + // A misspelt key still runs in warn, and says so. + let r = s.execute("joint.find_limits", &json!({"joint": "Hinge", "refin": 0.1})).unwrap_or_else(|e| panic!("{e}")); + assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()) && conforms(schema, schema, &r), "{r}"); + let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(!required.contains(&"param_warnings")); +} diff --git a/crates/engine/src/schema/panels.rs b/crates/engine/src/schema/panels.rs new file mode 100644 index 000000000..9adf2f5d4 --- /dev/null +++ b/crates/engine/src/schema/panels.rs @@ -0,0 +1,298 @@ +//! Strict external application-layout contracts. These are command parameters, +//! not another persistent layout model. +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::panels::*; + +/// Discovery and ParamCheck use the exact parser the injected executor uses. +pub struct CommandContract

{ + id: &'static str, + typed: super::TypedContract

, +} +impl

CommandContract

{ + pub const fn new(id: &'static str) -> Self { + Self { id, typed: super::TypedContract::new() } + } +} +impl super::Contract for CommandContract

{ + fn input_schema(&self) -> schemars::Schema { + super::Contract::input_schema(&self.typed) + } + fn allowed_keys(&self) -> std::sync::Arc> { + super::Contract::allowed_keys(&self.typed) + } + fn check(&self, params: &serde_json::Value) -> Vec { + match crate::panels::commands::parse_command(self.id, params) { + Ok(_) => Vec::new(), + Err(reason) => { + // Keep the shared parser's bounds ahead of deserialization, but + // retain ordinary contract paths and unknown-key suggestions. + if reason.rule == Rule::Schema { + let issues = super::Contract::check(&self.typed, params); + if !issues.is_empty() { + return issues; + } + } + vec![super::Issue { path: String::new(), message: reason.to_string(), suggestion: None }] + } + } + } +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(tag = "type", content = "id", rename_all = "snake_case", deny_unknown_fields)] +pub enum Target { + Workspace(WorkspaceId), + Instance(InstanceId), + Section(SectionId), + NativeHost(HostId), +} +impl From for LayoutTarget { + fn from(value: Target) -> Self { + match value { + Target::Workspace(id) => Self::Workspace(id), + Target::Instance(id) => Self::Instance(id), + Target::Section(id) => Self::Section(id), + Target::NativeHost(id) => Self::NativeHost(id), + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct OuterSize { + pub width: f32, + pub height: f32, +} +impl From for Size { + fn from(value: OuterSize) -> Self { + Self { width: value.width, height: value.height } + } +} +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Origin { + pub x: f32, + pub y: f32, +} +impl From for Point { + fn from(value: Origin) -> Self { + Self { x: value.x, y: value.y } + } +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReturnJoin { + pub section: SectionId, + pub index: usize, +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReturnTo { + pub zone: Zone, + pub index: usize, + pub size: OuterSize, + pub collapsed: bool, + #[serde(default)] + pub join: Option, +} +impl From for DockReturn { + fn from(value: ReturnTo) -> Self { + Self { + zone: value.zone, + index: value.index, + size: value.size.into(), + collapsed: value.collapsed, + join: value.join.map(|join| ReturnTab { section: join.section, index: join.index }), + } + } +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum Location { + Dock { zone: Zone }, + Floating { origin: Origin }, + Window { host: HostId, origin: Origin, return_to: ReturnTo }, +} +impl From for SectionLocation { + fn from(value: Location) -> Self { + match value { + Location::Dock { zone } => Self::Dock { zone }, + Location::Floating { origin } => Self::Floating { origin: origin.into() }, + Location::Window { host, origin, return_to } => Self::Window { host, origin: origin.into(), return_to: return_to.into() }, + } + } +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum Placement { + NewSection { section: SectionId, index: usize, location: Location, size: OuterSize }, + JoinTab { section: SectionId, index: usize }, +} +impl From for Destination { + fn from(value: Placement) -> Self { + match value { + Placement::NewSection { section, index, location, size } => { + Self::NewSection { section, index, location: location.into(), size: size.into() } + } + Placement::JoinTab { section, index } => Self::JoinTab { section, index }, + } + } +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Empty {} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Open { + pub kind: PanelKind, + pub instance: InstanceId, + pub destination: Option, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Select { + pub target: Option, + /// Compatibility selector: exact instance, or a single-instance canonical kind. + pub id: Option, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Move { + pub target: Option, + pub id: Option, + pub destination: Placement, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Resize { + pub target: Option, + pub id: Option, + pub size: OuterSize, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Collapse { + pub target: Option, + pub id: Option, + pub collapsed: bool, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Revision { + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResizePair { + pub first: SectionId, + pub second: SectionId, + pub first_size: OuterSize, + pub second_size: OuterSize, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResetPair { + pub first: SectionId, + pub second: SectionId, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Save { + pub name: String, + #[serde(default)] + pub overwrite: bool, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Apply { + pub name: String, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceSelect { + pub workspace: WorkspaceId, + pub expected_revision: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceSummary { + pub id: WorkspaceId, + pub title_key: String, + pub default_preset: String, + pub has_remembered_layout: bool, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct GetReply { + pub state: LayoutReply, + pub workspaces: Vec, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ListReply { + pub state: LayoutReply, + pub kinds: Vec, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SaveReply { + pub name: String, + pub overwritten: bool, + pub state: LayoutReply, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum WorkspaceSource { + Remembered, + DefaultPreset, + Unchanged, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceReply { + pub previous_workspace: WorkspaceId, + pub source: WorkspaceSource, + pub state: LayoutReply, +} + +/// Successful wire replies have no extensible object fields. Maps (availability) +/// remain maps. Persistence schemas intentionally retain their own opaque fields. +pub fn strict_output() -> schemars::Schema { + let mut schema = super::output_schema_for::(); + fn seal(value: &mut serde_json::Value) { + match value { + serde_json::Value::Object(object) => { + if object.contains_key("properties") { + object.insert("additionalProperties".into(), false.into()); + } + for value in object.values_mut() { + seal(value); + } + } + serde_json::Value::Array(values) => values.iter_mut().for_each(seal), + _ => {} + } + } + if let Some(object) = schema.as_object_mut() { + if object.contains_key("properties") { + object.insert("additionalProperties".into(), false.into()); + } + for value in object.values_mut() { + seal(value); + } + } + schema +} diff --git a/crates/engine/src/schema/print_face.rs b/crates/engine/src/schema/print_face.rs new file mode 100644 index 000000000..88d10bc9d --- /dev/null +++ b/crates/engine/src/schema/print_face.rs @@ -0,0 +1,74 @@ +//! Contracts and result types for the commands in `cmd/print_face.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::types::Point3; + +/// Mark the flat face of a body at a point as the body's print face, or clear it. A slicer +/// export (`file.send_to_slicer`, `file.save_mesh` with `slicer`, `file.open_in_easyprint`) lays +/// the body on its print face: turned so the face points down and lies at Z = 0, the centre of +/// mass over the origin. A body has one print face at most; marking another replaces it. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct PrintFaceParams { + /// The body, by name. Solid bodies only: a mesh body can't have a print face yet. + pub body: String, + /// A point on the flat face to mark, in mm. Default: none, which clears the body's print face. + #[serde(default)] + pub point: Option, +} + +/// What `body.print_face` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PrintFaceResult { + /// The body. + pub body: String, + /// The persistent name of the face now marked. Absent when the print face was cleared. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub face: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::PrintFaceParams; + use crate::Session; + use crate::schema::input_schema_for; + use crate::schema::tests::assert_keys; + + #[test] + fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["body", "point"]); + } + + #[test] + fn bad_calls_say_what_is_wrong_and_change_nothing() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap_or_else(|e| panic!("{e}")); + let undo = s.undo.len(); + let e = s.execute("body.print_face", &json!({"point": [20, 5, 2.5]})).unwrap_err().to_string(); + assert!(e.contains("body"), "{e}"); + let e = s.execute("body.print_face", &json!({"body": "Bracket", "point": [20, 5, 2.5]})).unwrap_err().to_string(); + assert!(e.contains("Bracket"), "{e}"); + let e = s.execute("body.print_face", &json!({"body": "Block", "point": "top"})).unwrap_err().to_string(); + assert!(e.contains("point"), "{e}"); + assert!(s.doc.print_faces.is_empty() && s.undo.len() == undo); + } + + #[test] + fn the_reply_names_the_marked_face_and_leaves_it_out_when_cleared() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap_or_else(|e| panic!("{e}")); + let r = s.execute("body.print_face", &json!({"body": "Block", "point": [20, 5, 2.5]})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["body"], "Block"); + assert!(r["face"].as_str().is_some_and(|f| !f.is_empty()), "{r}"); + let r = s.execute("body.print_face", &json!({"body": "Block"})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["body"], "Block"); + assert!(r.get("face").is_none(), "{r}"); + } +} diff --git a/crates/engine/src/schema/render_stage.rs b/crates/engine/src/schema/render_stage.rs new file mode 100644 index 000000000..269382028 --- /dev/null +++ b/crates/engine/src/schema/render_stage.rs @@ -0,0 +1,145 @@ +//! Contracts and result type for the render stage commands in `cmd/render/staging.rs` (#11455). +//! A stage is a set of render-only panels saved with a render setup. The handlers read these +//! same parameter types, so each contract is exactly what its handler takes; like the handlers, +//! a contract refuses unknown keys. + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +fn patch() -> Value { + serde_json::json!({}) +} + +fn set_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "object", "maxProperties": 13, "default": {}}) +} + +fn margin() -> f64 { + 0.25 +} + +fn gap() -> f64 { + 0.1 +} + +fn reflectance() -> [f64; 3] { + [0.18; 3] +} + +/// Fit one ground panel under the visible product, a little below its lowest point, and save +/// it with a render setup in one undo step. The setup must render with the CPU raytracer or the +/// GPU path tracer. The product's clearance from the panel is checked again on every render. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct GroundParams { + /// The render setup, saved or new. + pub name: String, + /// Changes to the setup before the ground is fitted, as `render.settings.set` takes them: + /// an object of at most 13 setup fields. Default: none. + #[serde(default = "patch")] + #[schemars(schema_with = "set_schema")] + pub set: Value, + /// How far the ground reaches past the product on each side, as a share of the product's + /// largest size: 0 to 10. Default: 0.25. + #[serde(default = "margin")] + #[schemars(range(min = 0.0, max = 10.0))] + pub margin_fraction: f64, + /// The gap between the product's lowest point and the ground (mm): 0.0001 to 1000. + /// Default: 0.1. + #[serde(default = "gap")] + #[schemars(range(min = 0.0001, max = 1000.0))] + pub gap_mm: f64, + /// How much light the ground reflects, as linear red, green and blue: each 0 to 1. + /// Default: 0.18 each. + #[serde(default = "reflectance")] + pub reflectance_linear: [f64; 3], + /// Replace a stage the setup already has. Without it, such a setup is refused. + #[serde(default)] + pub replace_stage: bool, +} + +/// Fit a floor and a wall, or a curved cyclorama of 24 flat strips, behind the visible product, +/// facing the setup's camera, and save it with the render setup in one undo step. The setup +/// must render with the CPU raytracer or the GPU path tracer. World +Z is up. This is a finite +/// background, not an infinite floor or a smooth CAD face. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct BackdropParams { + /// The render setup, saved or new. + pub name: String, + /// Changes to the setup before the backdrop is fitted, as `render.settings.set` takes them: + /// an object of at most 13 setup fields. Default: none. + #[serde(default = "patch")] + #[schemars(schema_with = "set_schema")] + pub set: Value, + pub kind: BackdropKind, + /// How much light the panels reflect, as linear red, green and blue: each 0 to 1. + /// Default: 0.18 each. + #[serde(default = "reflectance")] + pub reflectance_linear: [f64; 3], + /// Replace a stage the setup already has. Without it, such a setup is refused. + #[serde(default)] + pub replace_stage: bool, + /// The design's revision when the caller last read it, as `document.inspect` gives it. If + /// the design changed since, the call is refused: read it again and retry. + pub expected_revision: u64, +} + +/// The backdrop's shape. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum BackdropKind { + /// A floor and a flat wall. + FloorWall, + /// A floor that curves up into the wall, in 24 flat strips. + Cyclorama, +} + +/// Remove the stage from a render setup in one undo step. The design's geometry and the +/// setup's lighting stay as they are. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ClearParams { + /// The render setup, saved or new. + pub name: String, + /// Changes to the setup made with the removal, as `render.settings.set` takes them: + /// an object of at most 13 setup fields. Default: none. + #[serde(default = "patch")] + #[schemars(schema_with = "set_schema")] + pub set: Value, +} + +/// What `render.stage.ground`, `render.stage.backdrop` and `render.stage.clear` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StageSaved { + /// The render setup. + pub name: String, + /// The setup as saved, as the render settings commands give it. + pub setup: Value, + /// Always true: the design's bodies don't change. + pub engineering_geometry_unchanged: bool, + /// Always true: the panels exist only in renders. + pub stage_only: bool, + /// How the product's clearance from the panels is checked. + pub clearance: String, + /// A backdrop's shape: `finite_floor_and_wall` or `24_segment_polygonal_cyclorama`. + #[serde(skip_serializing_if = "Option::is_none")] + pub geometry_kind: Option, + /// A backdrop's part in the lighting. + #[serde(skip_serializing_if = "Option::is_none")] + pub light_transport: Option, + /// A backdrop: always true, the setup's camera stays as it is. + #[serde(skip_serializing_if = "Option::is_none")] + pub camera_preserved: Option, + /// A backdrop's limits, in sentences. + #[serde(skip_serializing_if = "Option::is_none")] + pub limitations: Option>, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "render_stage_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/render_stage_tests.rs b/crates/engine/src/schema/render_stage_tests.rs new file mode 100644 index 000000000..db14853e6 --- /dev/null +++ b/crates/engine/src/schema/render_stage_tests.rs @@ -0,0 +1,99 @@ +use serde_json::{Value, json}; + +use super::{BackdropParams, ClearParams, GroundParams, StageSaved}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +/// A design with a box and a saved render setup, `Shot`, that renders with the GPU path tracer, +/// at the parameter-check level `level`. +fn with_a_shot(level: ParamCheck) -> Session { + let mut s = Session { param_check: level, ..Session::default() }; + for (id, p) in [ + ("solid.box", json!({"length": 20, "width": 15, "height": 10, "body_name": "Subject"})), + ("render.settings.set", json!({"name": "Shot", "set": {"width": 96, "height": 64, "job": {"method": "gpu_path", "options": {}}}})), + ] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + } + s +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["gap_mm", "margin_fraction", "name", "reflectance_linear", "replace_stage", "set"]); + assert_keys(input_schema_for::(), &["expected_revision", "kind", "name", "reflectance_linear", "replace_stage", "set"]); + assert_keys(input_schema_for::(), &["name", "set"]); +} + +/// The handlers refuse these calls after reading them; strict refuses them with their message. +/// They need a design with a body and a saved setup, and the design's revision, so the shared +/// helper, which has a sketch only, doesn't fit. +#[test] +fn strict_keeps_todays_errors() { + let cases: [(&str, fn(u64) -> Value); 12] = [ + ("render.stage.ground", |_| json!({"name": "Shot", "margin_fraction": 11})), + ("render.stage.ground", |_| json!({"name": "Shot", "gap_mm": 0})), + ("render.stage.ground", |_| json!({"name": "Shot", "reflectance_linear": [2, 0, 0]})), + ("render.stage.ground", |_| json!({"name": "Raster"})), + ("render.stage.ground", |_| json!({"name": " Shot"})), + ("render.stage.ground", |_| json!({"name": "Shot", "set": {"width": 0}})), + ("render.stage.backdrop", |_| json!({"name": "Shot", "kind": "cyclorama", "expected_revision": 999_999})), + ("render.stage.backdrop", |r| json!({"name": "Raster", "kind": "floor_wall", "expected_revision": r})), + ("render.stage.backdrop", |r| json!({"name": "Shot", "kind": "floor_wall", "reflectance_linear": [0, -1, 0], "expected_revision": r})), + ("render.stage.clear", |_| json!({"name": ""})), + ("render.stage.clear", |_| json!({"name": "Shot", "set": {"width": 0}})), + ("render.stage.clear", |_| json!({"name": "Shot", "set": 5})), + ]; + for (id, p) in cases { + let error = |level: ParamCheck| { + let mut s = with_a_shot(level); + let p = p(s.revision); + s.execute(id, &p).err().map(|e| e.to_string()) + }; + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{id} {} should fail today", p(0)); + assert_eq!(error(ParamCheck::Strict), off, "{id} {}", p(0)); + } + // A stage already there needs `replace_stage`, for a ground and a backdrop alike. + for level in [ParamCheck::Off, ParamCheck::Strict] { + let mut s = with_a_shot(level); + s.execute("render.stage.ground", &json!({"name": "Shot"})).unwrap_or_else(|e| panic!("{e}")); + let ground = s.execute("render.stage.ground", &json!({"name": "Shot"})).err().map(|e| e.to_string()); + let p = json!({"name": "Shot", "kind": "floor_wall", "expected_revision": s.revision}); + let backdrop = s.execute("render.stage.backdrop", &p).err().map(|e| e.to_string()); + for error in [ground, backdrop] { + assert!(error.as_deref().is_some_and(|e| e.contains("replace_stage: true")), "{level:?}: {error:?}"); + } + } +} + +/// #11455: a ground, both backdrops and a clear reply as the output schema says, in Warn +/// without warnings; only a backdrop carries its shape and limits. Like the handlers, warn and +/// strict refuse a misspelt key. +#[test] +fn stage_commands_reply_with_their_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = with_a_shot(ParamCheck::Warn); + let run = |s: &mut Session, id: &str, p: Value| { + let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + r + }; + let p = json!({"name": "Shot", "set": {}, "margin_fraction": 0.5, "gap_mm": 1, "reflectance_linear": [0.2, 0.2, 0.2], "replace_stage": false}); + let r = run(&mut s, "render.stage.ground", p); + assert!(r["setup"].is_object() && r.get("geometry_kind").is_none(), "{r}"); + for kind in ["floor_wall", "cyclorama"] { + let revision = s.revision; + let p = json!({"name": "Shot", "kind": kind, "replace_stage": true, "expected_revision": revision}); + let r = run(&mut s, "render.stage.backdrop", p); + assert!(r["geometry_kind"].is_string() && r["limitations"].is_array(), "{r}"); + } + run(&mut s, "render.stage.clear", json!({"name": "Shot", "set": {}})); + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = with_a_shot(level); + let error = s.execute("render.stage.clear", &json!({"nme": "Shot"})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("nme"), "{level:?}: {error}"); + } +} diff --git a/crates/engine/src/schema/render_ui.rs b/crates/engine/src/schema/render_ui.rs index eef51c954..be7551493 100644 --- a/crates/engine/src/schema/render_ui.rs +++ b/crates/engine/src/schema/render_ui.rs @@ -1,4 +1,4 @@ -//! Clipboard requests for the Render workspace; headless calls only echo validated text. +//! Contracts for transient Render workspace clipboard and retained-result requests. use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -9,3 +9,68 @@ pub struct CheckReport { #[schemars(length(min = 1, max = 65536))] pub text: String, } + +/// Select or discard a retained result without editing a design. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResultIndex { + /// Zero-based index, oldest first. The result must still be retained. + #[schemars(range(min = 0, max = 7))] + pub index: u32, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum LiveSide { + Live, +} + +/// A live product view or a retained result's zero-based index (oldest first). +#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)] +#[serde(untagged)] +pub enum CompareSide { + Live(LiveSide), + Result(#[schemars(range(min = 0, max = 7))] u32), +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ComparePair { + pub left: CompareSide, + pub right: CompareSide, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CompareOff { + /// Must be true. Leave comparison without changing retained results. + pub off: bool, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum CompareParams { + Off(CompareOff), + Pair(ComparePair), +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CompareDivider { + /// Finite fraction of the canvas width, clamped to 0.05..0.95. + pub position: f64, +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct BatchParams { + /// Optional render.start request. Its setup is shared, with each saved shot's camera. + /// Without a request, use the first saved shot's setup (name order). + pub request: Option>, +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct BatchResult { + /// Total accepted shots, including the first active job. At most 32. + pub queued: u32, +} diff --git a/crates/engine/src/schema/section.rs b/crates/engine/src/schema/section.rs new file mode 100644 index 000000000..a99e66b8b --- /dev/null +++ b/crates/engine/src/schema/section.rs @@ -0,0 +1,43 @@ +//! Section clipping contract. Explicit planes use numerical millimetre coordinates. +use super::{AxisDir, LengthExpr, Point3, present}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum Plane { + Name(String), + Id(u64), + Explicit { origin: Option, normal: AxisDir }, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SectionParams { + /// Required unless clearing. XY/XZ/YZ, construction name/id, or {origin?,normal}. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Plane")] + pub plane: Option, + /// Signed distance along the original plane normal, in design units or an expression. + pub offset: Option, + /// World coordinate on a named plane's normal axis; mutually exclusive with offset. + pub at: Option, + pub flip: Option, + pub hatch: Option, + pub clear: Option, +} +#[derive(Serialize, JsonSchema)] +pub struct Section { + pub origin: [f64; 3], + pub normal: [f64; 3], + pub hatch: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub axis: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub at: Option, +} +#[derive(Serialize, JsonSchema)] +pub struct SectionResult { + pub section: Option

, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} diff --git a/crates/engine/src/schema/sheet.rs b/crates/engine/src/schema/sheet.rs index 8e3cbf573..652ceccf7 100644 --- a/crates/engine/src/schema/sheet.rs +++ b/crates/engine/src/schema/sheet.rs @@ -1,5 +1,5 @@ -//! Contracts for the sheet metal feature commands in `cmd/sheet.rs`. They all return -//! [`FeatureResult`](super::features::FeatureResult). +//! Contracts for sheet metal feature and rule commands in `cmd/sheet.rs`. Feature commands +//! return [`FeatureResult`](super::features::FeatureResult); rule commands have their own replies. //! //! A sheet metal rule sets the sheet's thickness, K-factor, bend radius and reliefs: the //! commands refuse those keys with a pointer to `sheet.manage_rules`, so they are no keys of @@ -17,8 +17,8 @@ use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; use serde::de::Error as _; use serde::{Deserialize, Deserializer}; use serde_json::Value; +use solidcore_record::Vec3; use solidcraft_doc::FlangeEdge; -use solidcraft_geom::Vec3; use super::check::whole; use super::types::{AngleExpr, FaceRef, FeatureCommon, IdOrName, LengthExpr, Point3, ProfilesParam, SketchRef, StringList, feature_common, present}; @@ -417,9 +417,9 @@ pub struct FlangeParams { pub common: FeatureCommon, } -/// Add a field of round perforations over a whole flat sheet: holes in the flat pattern, the DXF -/// (layer PERFORATION) and the measured volume, not cut into the solid. `participants` changes -/// nothing. +/// Add a field of round perforations over a whole flat sheet, or inside a sketch's outline: holes +/// in the flat pattern, the DXF (layer PERFORATION) and the measured volume, not cut into the +/// solid. `participants` changes nothing. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct PerforateParams { @@ -427,8 +427,8 @@ pub struct PerforateParams { pub diameter: LengthExpr, /// The distance between hole centres, more than the diameter. pub pitch: LengthExpr, - /// How far the holes stay clear of the sheet's edges, cut-outs and bends, at least 0. - /// Default: the diameter. + /// How far the holes stay clear of the sheet's edges, cut-outs and bends, and of the outline, + /// at least 0. Default: the diameter. #[serde(default)] pub margin: Option, /// How the holes are laid out. Default: staggered. @@ -437,6 +437,18 @@ pub struct PerforateParams { /// The sheet metal body. Default: the newest sheet. #[serde(default)] pub body: Option, + /// The field's outline: a sketch, by id or name, on a face of the sheet (or on the flat sheet + /// while it is unfolded). Holes go only inside its closed profiles, out of their inner loops, + /// on a grid from the outline's lower-left corner; on a folded sheet only in the panels the + /// sketch lies on. Default: the whole sheet. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "IdOrName")] + pub sketch: Option, + /// Which of the outline sketch's profiles bound the field. Needs `sketch`. Default: all of + /// them. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "ProfilesParam")] + pub profiles: Option, #[serde(flatten, deserialize_with = "feature_common")] pub common: FeatureCommon, } @@ -545,6 +557,201 @@ pub struct ConvertParams { pub common: FeatureCommon, } +/// List the design's sheet metal rules (the built-in steel rule if none are saved). +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct RulesParams {} + +/// Create or edit a sheet metal rule, activate it, or delete it. Expressions may use design +/// parameters; `Thickness` inside a rule's other expressions is that rule's thickness. +/// The handler evaluates dimensions and ranges against the design after checking the contract. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ManageRulesParams { + /// The rule's name (trimmed, nonempty, at most 128 bytes). A new rule inherits the active + /// rule's fields; an existing rule keeps fields not given here. + pub name: RuleName, + /// Thickness, more than 0 and less than 10000 mm. Ignored when deleting. + pub thickness: Option, + /// Neutral-axis fraction, from 0 to 1. Ignored when deleting. + pub k_factor: Option, + /// Inner bend radius, nonnegative. Ignored when deleting. + pub bend_radius: Option, + /// Bend relief width. Ignored when deleting. + pub relief_width: Option, + /// Bend relief depth. Ignored when deleting. + pub relief_depth: Option, + /// Corner relief size across. Ignored when deleting. + pub corner_relief: Option, + /// Corner relief shape. Ignored when deleting. + pub corner_relief_shape: Option, + /// Inner radius of flat hems. Ignored when deleting. + pub hem_gap: Option, + /// Gap between meeting flanges. Ignored when deleting. + pub gap: Option, + /// How DXF bend notes show angles: bend or included, ignoring case and surrounding blanks. + /// Ignored when deleting. + pub angle_display: Option, + /// Make this the active rule. Default: true if there is no saved active rule, otherwise false. + /// False leaves the active choice unchanged; ignored when deleting. + pub active: Option, + /// Delete the named saved rule instead of editing it. Default: false. Deleting the active + /// rule clears that choice; listing then uses the first remaining rule, else built-in steel. + pub delete: Option, +} + +/// A rule name, checked by the handler's reader. +#[derive(Debug)] +pub struct RuleName(pub String); + +impl<'de> Deserialize<'de> for RuleName { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + crate::cmd::sheet_rule_name(&v).map(|n| RuleName(n.to_string())).map_err(|why| D::Error::custom(whole(why))) + } +} + +impl JsonSchema for RuleName { + fn schema_name() -> Cow<'static, str> { + "SheetRuleName".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "description": "Trimmed, nonempty rule name, at most 128 bytes after trimming."}) + } +} + +/// A rule's bend-note angle display, checked by the same parser as the handler. +#[derive(Debug)] +pub struct AngleDisplayParam(pub solidcraft_doc::sheet::AngleDisplay); + +impl<'de> Deserialize<'de> for AngleDisplayParam { + fn deserialize>(d: D) -> Result { + Value::deserialize(d)? + .as_str() + .and_then(solidcraft_doc::sheet::AngleDisplay::parse) + .map(AngleDisplayParam) + .ok_or_else(|| D::Error::custom("must be bend or included")) + } +} + +impl JsonSchema for AngleDisplayParam { + fn schema_name() -> Cow<'static, str> { + "SheetAngleDisplay".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "description": "bend or included, ignoring case and surrounding blanks.", + "pattern": format!("^{blank}([Bb][Ee][Nn][Dd]|[Ii][Nn][Cc][Ll][Uu][Dd][Ee][Dd]){blank}$", blank = blanks())}) + } +} + +/// A saved rule's expressions, including the default bend-angle display which the saved +/// design omits. These are expressions, not evaluated values. +#[derive(Debug, serde::Serialize, JsonSchema)] +pub struct RuleReply { + pub name: String, + pub thickness: String, + pub k_factor: String, + pub bend_radius: String, + pub relief_width: String, + pub relief_depth: String, + pub corner_relief: String, + pub corner_relief_shape: String, + pub hem_gap: String, + pub gap: String, + pub angle_display: String, +} + +impl From<&solidcraft_doc::sheet::SheetRule> for RuleReply { + fn from(r: &solidcraft_doc::sheet::SheetRule) -> Self { + Self { + name: r.name.clone(), + thickness: r.thickness.clone(), + k_factor: r.k_factor.clone(), + bend_radius: r.bend_radius.clone(), + relief_width: r.relief_width.clone(), + relief_depth: r.relief_depth.clone(), + corner_relief: r.corner_relief.clone(), + corner_relief_shape: r.corner_relief_shape.clone(), + hem_gap: r.hem_gap.clone(), + gap: r.gap.clone(), + angle_display: r.angle_display.clone(), + } + } +} + +/// Evaluated rule values: lengths in millimetres, dimensionless K-factor and canonical choices. +#[derive(Debug, serde::Serialize, JsonSchema)] +pub struct RuleValuesReply { + pub thickness: f64, + pub k_factor: f64, + pub bend_radius: f64, + pub relief_width: f64, + pub relief_depth: f64, + pub corner_relief: f64, + pub corner_relief_shape: String, + pub hem_gap: f64, + pub gap: f64, + pub angle_display: String, +} + +impl From for RuleValuesReply { + fn from(r: solidcraft_doc::sheet::RuleValues) -> Self { + Self { + thickness: r.thickness, + k_factor: r.k_factor, + bend_radius: r.bend_radius, + relief_width: r.relief_width, + relief_depth: r.relief_depth, + corner_relief: r.corner_relief, + corner_relief_shape: r.corner_relief_shape.name().into(), + hem_gap: r.hem_gap, + gap: r.gap, + angle_display: r.angle_display.name().into(), + } + } +} + +/// A rule and its evaluated values, or null values if its expressions no longer evaluate. +#[derive(Debug, serde::Serialize, JsonSchema)] +pub struct ListedRule { + pub rule: RuleReply, + pub values: Option, +} + +/// The rule list and effective active name. +#[derive(Debug, serde::Serialize, JsonSchema)] +pub struct RulesResult { + pub rules: Vec, + pub active: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A feature that failed to rebuild after a rule was edited. +#[derive(Debug, serde::Serialize, JsonSchema)] +pub struct RuleFeatureError { + pub feature: String, + pub error: String, +} + +/// A successful rule edit or deletion, preserving the existing reply alternatives. +#[derive(Debug, serde::Serialize, JsonSchema)] +#[serde(untagged)] +pub enum ManageRulesResult { + Changed { + rule: Box, + values: RuleValuesReply, + errors: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + param_warnings: Vec, + }, + Deleted { + deleted: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + param_warnings: Vec, + }, +} + #[cfg(test)] #[path = "sheet_tests.rs"] mod tests; diff --git a/crates/engine/src/schema/sheet_tests.rs b/crates/engine/src/schema/sheet_tests.rs index 069904a05..6a63080f2 100644 --- a/crates/engine/src/schema/sheet_tests.rs +++ b/crates/engine/src/schema/sheet_tests.rs @@ -64,7 +64,7 @@ fn schemas_and_the_key_check_agree() { "type", ]), ); - assert_keys(input_schema_for::(), &keys(&["body", "diameter", "margin", "pattern", "pitch"])); + assert_keys(input_schema_for::(), &keys(&["body", "diameter", "margin", "pattern", "pitch", "profiles", "sketch"])); assert_keys(input_schema_for::(), &keys(&["body", "edges", "flip", "gap", "length"])); assert_keys(input_schema_for::(), &keys(&["angle", "body", "curve", "fixed", "flip", "points", "position", "radius", "sketch"])); assert_keys(input_schema_for::(), &keys(&["body"])); @@ -355,3 +355,139 @@ fn replies_match_the_output_schema() { assert!(r.get("param_warnings").is_some(), "{r}"); check(r); } + +#[test] +fn rule_commands_publish_contracts_and_refuse_unknown_keys() { + for id in ["sheet.rules", "sheet.manage_rules"] { + let spec = crate::command_specs().into_iter().find(|c| c.id == id).unwrap(); + assert!(spec.contract.is_some() && spec.output.is_some(), "{id}: input schema missing"); + let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() }; + let p = if id == "sheet.rules" { json!({"unknown_key": true}) } else { json!({"name": "Test", "thikness": 1}) }; + assert!(s.execute(id, &p).is_err(), "{id}: unknown key accepted"); + assert!(s.doc.sheet.rules.is_empty()); + } +} + +#[test] +fn rule_contract_keys_and_readers_match() { + use super::{AngleDisplayParam, ManageRulesParams, RuleName, RulesParams}; + assert_keys(input_schema_for::(), &[]); + assert_keys( + input_schema_for::(), + &[ + "active", + "angle_display", + "bend_radius", + "corner_relief", + "corner_relief_shape", + "delete", + "gap", + "hem_gap", + "k_factor", + "name", + "relief_depth", + "relief_width", + "thickness", + ], + ); + for (text, valid) in [("bend", true), (" INCLUDED ", true), ("\u{2003}BeNd\u{2003}", true), ("outside", false)] { + assert_eq!(parse::(json!(text)).is_some(), valid); + } + assert!(parse::(json!(false)).is_none()); + for v in [json!(null), json!(false), json!(1), json!(""), json!(" \n "), json!("a".repeat(129)), json!("é".repeat(65))] { + assert!(parse::(v).is_none()); + } + assert_eq!(parse::(json!(" My rule ")).unwrap().0, "My rule"); + assert!(parse::(json!("é".repeat(64))).is_some()); + let pattern = input_schema_for::(); + assert!(pattern.as_value()["pattern"].as_str().unwrap().contains(&super::blanks())); + assert_strict_keeps_todays_errors(&[ + ("sheet.manage_rules", json!({"name": null})), + ("sheet.manage_rules", json!({"name": true})), + ("sheet.manage_rules", json!({"name": " "})), + ("sheet.manage_rules", json!({"name": "a".repeat(129)})), + ("sheet.manage_rules", json!({"name": "R", "angle_display": "outer"})), + ("sheet.manage_rules", json!({"name": "R", "angle_display": 5})), + ("sheet.manage_rules", json!({"name": "R", "corner_relief_shape": "oval"})), + ("sheet.manage_rules", json!({"name": "R", "thickness": -1})), + ("sheet.manage_rules", json!({"name": "R", "k_factor": 2})), + ("sheet.manage_rules", json!({"name": "Missing", "delete": true})), + ]); +} + +/// Run all rule forms in Warn, compare with Off, and pin the successful reply shapes. +#[test] +fn rule_replies_match_the_output_schemas_without_warnings() { + use super::{ManageRulesResult, RulesResult}; + let mut off = Session::default(); + let mut warn = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let calls = [ + ("sheet.rules", json!({})), + ( + "sheet.manage_rules", + json!({"name": " Metric ", "thickness": 2, "k_factor": "0.4", "bend_radius": "Thickness / 2", + "relief_width": 1, "relief_depth": "Thickness", "corner_relief": 3, "corner_relief_shape": " Round ", + "hem_gap": 0.1, "gap": "Thickness / 2", "angle_display": " INCLUDED ", "active": true}), + ), + ( + "sheet.manage_rules", + json!({"name": "Metric", "thickness": "3 mm", "k_factor": 0.5, "bend_radius": 1, + "relief_width": "1 mm", "relief_depth": 2, "corner_relief": "3 mm", "corner_relief_shape": "tear", + "hem_gap": "0.2 mm", "gap": 2, "angle_display": "BeNd", "active": false, "delete": false}), + ), + ("sheet.manage_rules", json!({"name": "Other"})), + ( + "sheet.manage_rules", + json!({"name": "Other", "thickness": null, "k_factor": null, "bend_radius": null, + "relief_width": null, "relief_depth": null, "corner_relief": null, "corner_relief_shape": null, + "hem_gap": null, "gap": null, "angle_display": null, "active": null, "delete": null}), + ), + ("sheet.rules", json!({})), + ("sheet.manage_rules", json!({"name": "Other", "active": true})), + ("sheet.manage_rules", json!({"name": "Metric", "delete": true})), + ("sheet.manage_rules", json!({"name": "Other", "delete": true})), + ("sheet.rules", json!({})), + ]; + for (id, p) in calls { + let a = off.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let b = warn.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + assert_eq!(a, b, "{id} {p}"); + assert!(b.get("param_warnings").is_none(), "{id} {p}: {b}"); + let schema = if id == "sheet.rules" { output_schema_for::() } else { output_schema_for::() }; + assert!(conforms(schema.as_value(), schema.as_value(), &b), "{id}: {b}"); + if let Some(rule) = b.get("rule") { + let saved = off.doc.sheet.rules.iter().find(|r| json!(r.name) == rule["name"]).unwrap(); + let mut old = json!(saved); + old["angle_display"] = json!(saved.angle_display); + assert_eq!(*rule, old); + let (vals, _) = off.doc.param_values(); + assert_eq!(b["values"], json!(off.doc.rule_values(&vals, saved).unwrap())); + assert_eq!(b["errors"], json!([])); + } + } + // Saved rules whose expressions no longer evaluate are still listed, with null values. + warn.doc_mut().sheet.rules.push(solidcraft_doc::sheet::SheetRule { + name: "Invalid".into(), + thickness: "Missing".into(), + ..solidcraft_doc::sheet::SheetRule::steel() + }); + let reply = warn.execute("sheet.rules", &json!({})).unwrap(); + assert_eq!(reply["rules"][0]["values"], Value::Null); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply)); +} + +#[test] +fn rule_warnings_match_the_output_schema_and_strict_does_not_mutate() { + use super::{ManageRulesResult, RulesResult}; + for (id, p) in [("sheet.rules", json!({"naem": "R"})), ("sheet.manage_rules", json!({"name": "R", "thikness": 1}))] { + let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() }; + assert!(s.execute(id, &p).is_err()); + assert!(s.doc.sheet.rules.is_empty()); + s.param_check = ParamCheck::Warn; + let reply = s.execute(id, &p).unwrap(); + assert!(!reply["param_warnings"].as_array().unwrap().is_empty()); + let schema = if id == "sheet.rules" { output_schema_for::() } else { output_schema_for::() }; + assert!(conforms(schema.as_value(), schema.as_value(), &reply)); + } +} diff --git a/crates/engine/src/schema/sketch.rs b/crates/engine/src/schema/sketch.rs new file mode 100644 index 000000000..c9e8df34c --- /dev/null +++ b/crates/engine/src/schema/sketch.rs @@ -0,0 +1,51 @@ +//! Contracts and result types for sketch editing and completion in `cmd/sketch.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::types::{IdOrName, present}; + +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct EditParams { + pub sketch: IdOrName, + /// When present, temporarily roll to this sketch and restore this position when the edit + /// ends. Null means the end of the timeline; omission leaves the timeline in place. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Option")] + pub restore_marker: Option>, +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExitParams { + /// Restore the temporary editor marker (default true). False transfers it directly to + /// another editor without rebuilding the intermediate timeline. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool")] + pub restore_marker: Option, +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct EditResult { + pub sketch: u64, + pub name: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct FinishResult { + pub sketch: Option, + pub profiles: usize, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct CancelResult { + pub sketch: u64, + pub removed: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs index 143069480..7c6d1971e 100644 --- a/crates/engine/src/schema/sketch_create.rs +++ b/crates/engine/src/schema/sketch_create.rs @@ -4,9 +4,9 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::Value; -use super::types::{AngleExpr, SketchRef, present}; +use super::types::{AngleExpr, LengthExpr, SketchRef, present}; -/// Create an infinite reference line in the active sketch. +/// Create a reference line in the active sketch: infinite, or a segment of a given length. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct ConstructionLineParams { @@ -16,7 +16,8 @@ pub struct ConstructionLineParams { pub at: Value, /// Second point of a two-point construction line. pub through: Option, - /// Point used to select the closest solution when several exist. + /// Point used to select the closest solution when several exist; for a line with a + /// `length`, the side of `at` it runs towards. pub near: Option<[f64; 2]>, /// Zero-based index in the deterministic list of solutions. pub solution: Option, @@ -28,6 +29,12 @@ pub struct ConstructionLineParams { pub alternate: Option, /// Direction measured counter-clockwise from sketch X, in degrees. pub angle: Option, + /// A segment of this length from `at` instead of an infinite line, held by a length + /// dimension. For the horizontal, vertical, angle, parallel and perpendicular methods. + pub length: Option, + /// `false` makes a line with a `length` a normal sketch line, ready for a profile, instead + /// of construction geometry (default `true`). An infinite line is always construction. + pub construction: Option, /// The sketch (default: the one being edited). pub sketch: Option, } @@ -73,6 +80,50 @@ pub struct SplineReverseParams { pub sketch: Option, } +/// Take one point out of a spline: it runs through (or over) its other points only, and the point +/// goes with the constraints on it unless another curve uses it. Takes fit point, control point +/// and closed splines; refused for a closed spline's closing point, for an end joined to other +/// geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed +/// spline), and for a projected, offset or patterned spline. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SplineRemovePointParams { + /// The spline's curve id. + #[serde(deserialize_with = "spline_id")] + pub curve: String, + /// One of the spline's points: a point id, or the curve's `start` or `end` (`s1.end`). + #[serde(deserialize_with = "point_ref")] + pub point: String, + /// The sketch (default: the one being edited). + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "SketchRef")] + pub sketch: Option, +} + +/// What `sketch.spline.remove_point` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SplineRemovePointResult { + /// The spline's curve id (unchanged). + pub curve: String, + /// The id the point had. + pub point: String, + /// Whether the point went too; `false` when another curve still uses it. + pub deleted: bool, + /// The sketch's solve: `{solved, dof}`. + pub sketch: Value, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A point reference, with the handler's message for anything else. +fn point_ref<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(serde::de::Error::custom("must be one of the spline's points")), + } +} + /// A curve id, with the handler's message for anything else. fn spline_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { match Value::deserialize(d)? { diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs index e9c69cf50..bea64f761 100644 --- a/crates/engine/src/schema/sketch_create_tests.rs +++ b/crates/engine/src/schema/sketch_create_tests.rs @@ -1,6 +1,6 @@ use serde_json::json; -use super::{SplineReverseParams, SplineReverseResult}; +use super::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult}; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; @@ -8,6 +8,7 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["curve", "sketch"]); + assert_keys(input_schema_for::(), &["curve", "point", "sketch"]); } #[test] @@ -17,9 +18,30 @@ fn strict_keeps_todays_errors() { ("sketch.spline.reverse", json!({"curve": null})), ("sketch.spline.reverse", json!({"curve": "nope"})), ("sketch.spline.reverse", json!({"curve": "l1"})), + ("sketch.spline.remove_point", json!({"curve": 5, "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "nope", "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "l1", "point": 3})), + ("sketch.spline.remove_point", json!({"curve": "l1"})), ]); } +#[test] +fn spline_remove_point_reply_matches_its_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: serde_json::Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let c = run(&mut s, "sketch.spline.fit_point", json!({"points": [[5, 0], [10, 5], [20, 0], [30, 5], [40, 0]]})); + let spline = c["curves"][0].as_str().unwrap_or_else(|| panic!("{c}")).to_string(); + let schema = output_schema_for::(); + let schema = schema.as_value(); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.start")})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.end"), "unknown": 1})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}"); +} + #[test] fn spline_reverse_reply_matches_its_schema() { let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; @@ -42,7 +64,7 @@ fn construction_line_contracts_and_replies_match() { use super::{ConstructionLineParams, ConstructionLineResult}; assert_keys( input_schema_for::(), - &["alternate", "angle", "at", "curve", "curve2", "mode", "near", "sketch", "solution", "through"], + &["alternate", "angle", "at", "construction", "curve", "curve2", "length", "mode", "near", "sketch", "solution", "through"], ); let schema = output_schema_for::(); let schema = schema.as_value(); @@ -52,6 +74,7 @@ fn construction_line_contracts_and_replies_match() { ("sketch.construction_line", json!({"at":[0,0],"through":[5,5]})), ("sketch.construction_line.horizontal", json!({"at":[0,10]})), ("sketch.construction_line.angle", json!({"at":[10,10],"angle":30})), + ("sketch.construction_line.vertical", json!({"at":[20,0],"length":"12 mm","near":[20,-5]})), ] { let r = s.execute(id, &p).unwrap(); assert!(conforms(schema, schema, &r), "{r}"); diff --git a/crates/engine/src/schema/sketch_ends.rs b/crates/engine/src/schema/sketch_ends.rs new file mode 100644 index 000000000..668098e77 --- /dev/null +++ b/crates/engine/src/schema/sketch_ends.rs @@ -0,0 +1,161 @@ +//! Contracts and result types for the commands in `cmd/sketch_ends.rs`: a sketch's loose ends, +//! and tying them (#10959). + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use super::check::whole; + +/// The most names `params::string_list` takes, which the tie command reads its points with. +const MAX_POINTS: usize = 10_000; + +/// A sketch, as `sketch_store::target` reads one: its feature id or its name, with its message. +/// Whether a sketch has that id or name is the handler's to check. +#[derive(Clone, Debug, PartialEq)] +pub struct SketchTarget(pub String); + +impl<'de> Deserialize<'de> for SketchTarget { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::Number(n) if n.is_u64() => Ok(SketchTarget(n.to_string())), + Value::String(s) => Ok(SketchTarget(s)), + _ => Err(D::Error::custom("must be an id or a name")), + } + } +} + +impl JsonSchema for SketchTarget { + fn schema_name() -> Cow<'static, str> { + "SketchTarget".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The sketch: its feature id or its name (default: the one being edited).", + "anyOf": [{"type": "integer", "minimum": 0}, {"type": "string"}] + }) + } +} + +/// Point ids, as the tie command reads them: a list of ids (a single id isn't taken), at most +/// 10 000, with its messages. +#[derive(Clone, Debug, PartialEq)] +pub struct PointIds(pub Vec); + +impl<'de> Deserialize<'de> for PointIds { + fn deserialize>(d: D) -> Result { + let fail = || D::Error::custom("must be a list of point ids"); + let Value::Array(a) = Value::deserialize(d)? else { + return Err(fail()); + }; + let ids = a.into_iter().map(|v| if let Value::String(s) = v { Some(s) } else { None }).collect::>>().ok_or_else(fail)?; + if ids.len() > MAX_POINTS { + return Err(D::Error::custom(whole(format!("`points` must list at most {} names", MAX_POINTS)))); + } + Ok(PointIds(ids)) + } +} + +impl JsonSchema for PointIds { + fn schema_name() -> Cow<'static, str> { + "PointIds".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "Point ids, such as `p3`.", + "type": "array", + "items": {"type": "string"}, + "maxItems": MAX_POINTS + }) + } +} + +/// The ends of a sketch's profile curves (not construction, projected or text curves) that can +/// make a profile fail. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct LooseEndsParams { + #[serde(default)] + pub sketch: Option, +} + +/// Tie each untied end to what it touches: coincident with another curve's end, or on another +/// curve. One undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct TieLooseEndsParams { + #[serde(default)] + pub sketch: Option, + /// The untied ends to tie, by point id (default: every untied end). An id that isn't an + /// untied end is left as it is. + #[serde(default)] + pub points: Option, +} + +/// What `sketch.loose_ends` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LooseEnds { + /// Ends that touch no other profile curve: no profile runs through them. + pub open: Vec, + /// Ends that touch another curve only by position: the profile closes now, but nothing keeps + /// it closed when a dimension changes. + pub untied: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// An end that touches nothing. +#[derive(Debug, Serialize, JsonSchema)] +pub struct OpenEnd { + /// The end's point id. + pub point: Option, + /// The profile curve it ends. + pub curve: Option, + /// Where it is, in sketch coordinates. + pub at: Option<[f64; 2]>, +} + +/// An end that touches another curve only by position. +#[derive(Debug, Serialize, JsonSchema)] +pub struct UntiedEnd { + /// The end's point id. + pub point: Option, + /// The curve it ends. + pub curve: Option, + /// Where it is, in sketch coordinates. + pub at: Option<[f64; 2]>, + /// What it touches: another curve's end, or a curve. + pub touches: Touches, +} + +/// What an untied end touches. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum Touches { + /// Another curve's end, by point id. + Point(Option), + /// A curve, by id. + Curve(Option), +} + +/// What `sketch.loose_ends.tie` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct TiedLooseEnds { + /// The ids of the constraints added, one per end tied. + pub constraints: Vec, + /// The sketch's solve: `{solved, dof}`. + pub sketch: Value, + /// The untied ends left. + pub untied: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "sketch_ends_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/sketch_ends_tests.rs b/crates/engine/src/schema/sketch_ends_tests.rs new file mode 100644 index 000000000..2eafcd74a --- /dev/null +++ b/crates/engine/src/schema/sketch_ends_tests.rs @@ -0,0 +1,91 @@ +use serde_json::{Value, json}; + +use super::{LooseEnds, LooseEndsParams, TieLooseEndsParams, TiedLooseEnds}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// A sketch being edited, as these commands need: a square of four separate lines, closed by +/// position only, so its four corners are untied. +fn loose_square(s: &mut Session) { + run(s, "sketch.create", json!({"plane": "XY", "name": "Square"})); + let c = [[0, 0], [10, 0], [10, 10], [0, 10]]; + for i in 0..4 { + run(s, "sketch.line", json!({"points": [c[i], c[(i + 1) % 4]], "infer": false, "connect": false})); + } +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["sketch"]); + assert_keys(input_schema_for::(), &["points", "sketch"]); +} + +/// A call that fails today gets the same message in strict. These commands run only while a +/// sketch is being edited, so each call runs in one (`assert_strict_keeps_todays_errors` runs +/// after a finished sketch). +#[test] +fn strict_keeps_todays_errors() { + let many = vec!["p1"; 10_001]; + for (id, p) in [ + ("sketch.loose_ends", json!({"sketch": true})), + ("sketch.loose_ends", json!({"sketch": -1})), + ("sketch.loose_ends", json!({"sketch": 1.5})), + ("sketch.loose_ends", json!({"sketch": "Nope"})), + ("sketch.loose_ends.tie", json!({"sketch": {}})), + ("sketch.loose_ends.tie", json!({"points": "p1"})), + ("sketch.loose_ends.tie", json!({"points": [1]})), + ("sketch.loose_ends.tie", json!({"points": ["nope"]})), + ("sketch.loose_ends.tie", json!({"points": many})), + ] { + let error = |level: ParamCheck| { + let mut s = Session { param_check: level, ..Session::default() }; + loose_square(&mut s); + s.execute(id, &p).err().map(|e| e.to_string()) + }; + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{id} {p} should fail today"); + assert_eq!(error(ParamCheck::Strict), off, "{id} {p}"); + } +} + +/// #10959: the report and the tie reply as their output schemas say, in Warn without warnings +/// for good calls and with them for a misspelt key, with open ends, untied ends touching a +/// point and a curve, and ties of some ends and then the rest. +#[test] +fn loose_end_commands_reply_with_their_schemas() { + let (report, tied) = (output_schema_for::(), output_schema_for::()); + let matches = |schema: &schemars::Schema, r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + loose_square(&mut s); + // A line from the middle of the top side: one end touches a curve, the other nothing. + run(&mut s, "sketch.line", json!({"points": [[5, 10], [5, 20]], "infer": false, "connect": false})); + let r = run(&mut s, "sketch.loose_ends", json!({})); + matches(&report, &r, false); + let untied = r["untied"].as_array().cloned().unwrap_or_default(); + assert_eq!(r["open"].as_array().map(Vec::len), Some(1), "{r}"); + assert!(untied.iter().any(|u| u["touches"]["point"].is_string()) && untied.iter().any(|u| u["touches"]["curve"].is_string()), "{r}"); + for u in &untied { + let touches = u["touches"].as_object().map(|t| t.keys().cloned().collect::>()); + assert!(matches!(touches.as_deref(), Some([k]) if k == "point" || k == "curve"), "{u}"); + } + matches(&report, &run(&mut s, "sketch.loose_ends", json!({"sketch": "Square"})), false); + matches(&report, &run(&mut s, "sketch.loose_ends", json!({"skech": "Square"})), true); + + let first = untied.first().map(|u| u["point"].clone()).unwrap_or_default(); + let r = run(&mut s, "sketch.loose_ends.tie", json!({"points": [first]})); + matches(&tied, &r, false); + assert_eq!(r["constraints"].as_array().map(Vec::len), Some(1), "{r}"); + let r = run(&mut s, "sketch.loose_ends.tie", json!({"point": []})); + matches(&tied, &r, true); + assert_eq!(r["untied"], json!([]), "every end is tied: {r}"); + matches(&tied, &run(&mut s, "sketch.loose_ends.tie", json!({"sketch": "Square", "points": null})), false); +} diff --git a/crates/engine/src/schema/sketch_equation.rs b/crates/engine/src/schema/sketch_equation.rs index 66b1b18dd..ee3b04f72 100644 --- a/crates/engine/src/schema/sketch_equation.rs +++ b/crates/engine/src/schema/sketch_equation.rs @@ -68,6 +68,33 @@ impl JsonSchema for Tolerance { } } +/// What the curve's variable is in its formulas. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VariableUnitParam(pub solidcraft_sketch::VariableUnit); + +impl<'de> Deserialize<'de> for VariableUnitParam { + fn deserialize>(d: D) -> Result { + Value::deserialize(d)? + .as_str() + .and_then(solidcraft_sketch::VariableUnit::parse) + .map(VariableUnitParam) + .ok_or_else(|| D::Error::custom("must be \"number\" or \"range\"")) + } +} + +impl JsonSchema for VariableUnitParam { + fn schema_name() -> Cow<'static, str> { + "EquationVariableUnit".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "What the variable is in the formulas. \"number\": a plain number. \"range\": a length, as the range is; start and end must then both be lengths, or one a length and the other a plain number, which is in the design's unit. Default \"number\".", + "type": "string", + "enum": ["number", "range"] + }) + } +} + /// An equation curve's id. #[derive(Clone, Debug, PartialEq)] pub struct CurveId(pub String); @@ -113,6 +140,9 @@ pub struct EquationCurveParams { /// How far (mm) the curve may stray from its formulas. Default 0.01. #[serde(default)] pub tolerance: Option, + /// What the variable is in the formulas. Default "number". + #[serde(default)] + pub variable_unit: Option, /// Make it construction geometry. Default false. #[serde(default)] pub construction: Option, @@ -147,6 +177,9 @@ pub struct EquationEditParams { /// How far (mm) the curve may stray from its formulas. Kept when left out. #[serde(default)] pub tolerance: Option, + /// What the variable is in the formulas. Kept when left out. + #[serde(default)] + pub variable_unit: Option, /// The sketch (default: the one being edited). #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] #[schemars(with = "SketchRef")] diff --git a/crates/engine/src/schema/sketch_equation_tests.rs b/crates/engine/src/schema/sketch_equation_tests.rs index ca3ff3968..3d7669125 100644 --- a/crates/engine/src/schema/sketch_equation_tests.rs +++ b/crates/engine/src/schema/sketch_equation_tests.rs @@ -7,8 +7,11 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { - assert_keys(input_schema_for::(), &["construction", "end", "explicit", "sketch", "start", "tolerance", "x", "y"]); - assert_keys(input_schema_for::(), &["curve", "end", "explicit", "sketch", "start", "tolerance", "x", "y"]); + assert_keys( + input_schema_for::(), + &["construction", "end", "explicit", "sketch", "start", "tolerance", "variable_unit", "x", "y"], + ); + assert_keys(input_schema_for::(), &["curve", "end", "explicit", "sketch", "start", "tolerance", "variable_unit", "x", "y"]); } #[test] @@ -21,6 +24,9 @@ fn strict_keeps_todays_errors() { ("sketch.equation_curve", json!({"x": "t", "y": "t", "start": 0, "end": 1, "explicit": 1})), ("sketch.equation_curve", json!({"x": "t", "y": "t", "start": 0, "end": 1e12})), ("sketch.equation_curve", json!({"y": "t", "start": 0, "end": 1})), + ("sketch.equation_curve", json!({"x": "t", "y": "t", "start": 0, "end": 1, "variable_unit": "mm"})), + ("sketch.equation_curve", json!({"x": "t", "y": "t", "start": 0, "end": 1, "variable_unit": true})), + ("sketch.equation_curve", json!({"x": "t", "y": "t", "start": 0, "end": 1, "variable_unit": "range"})), ("sketch.equation_curve.edit", json!({"curve": 7})), ("sketch.equation_curve.edit", json!({"curve": "nope", "y": "t"})), ]); @@ -43,4 +49,11 @@ fn replies_match_their_schemas() { let edited = edited.as_value(); let r = run(&mut s, "sketch.equation_curve.edit", json!({"curve": id, "end": "6 * pi"})); assert!(conforms(edited, edited, &r), "{r} doesn't match {edited}"); + // The variable in its range's unit, then back: both accepted in strict, nothing warned. + s.param_check = ParamCheck::Strict; + let r = run(&mut s, "sketch.equation_curve", json!({"x": "t", "y": "t / 2", "start": 0, "end": "10 mm", "variable_unit": "range"})); + assert!(conforms(created, created, &r), "{r} doesn't match {created}"); + let id = r["curve"].as_str().unwrap_or_else(|| panic!("{r}")).to_string(); + let r = run(&mut s, "sketch.equation_curve.edit", json!({"curve": id, "variable_unit": "number"})); + assert!(conforms(edited, edited, &r), "{r} doesn't match {edited}"); } diff --git a/crates/engine/src/schema/sketch_inspect.rs b/crates/engine/src/schema/sketch_inspect.rs new file mode 100644 index 000000000..3baded849 --- /dev/null +++ b/crates/engine/src/schema/sketch_inspect.rs @@ -0,0 +1,400 @@ +//! Contracts and result types for the commands in `cmd/sketch_inspect.rs`: curvature combs, +//! minimum radius and isocurves on sketch curves, model edges and faces, and the centre of mass +//! of bodies (#10949). + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; +use solidcore_record::Vec3; + +use super::check::whole; +use super::types::{Point3, SketchRef, StringList, present}; +use crate::params; + +/// Points that pick edges or faces, read as the handler reads them: a list whose first `$limit` +/// items are each a point `params::vec3` reads (the handler looks at no more), with its message +/// for anything else and, where it refuses one, for an empty list. +macro_rules! point_list { + ($(#[$doc:meta])* $name:ident, limit: $limit:literal, bad: $bad:literal, empty: $empty:expr) => { + $(#[$doc])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name(pub Vec); + + impl<'de> Deserialize<'de> for $name { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + let points = v.as_array().ok_or_else(|| D::Error::custom(whole($bad)))?; + let empty: Option<&str> = $empty; + if let (true, Some(message)) = (points.is_empty(), empty) { + return Err(D::Error::custom(whole(message))); + } + points.iter().take($limit).map(params::vec3).collect::>>().map($name).ok_or_else(|| D::Error::custom(whole($bad))) + } + } + + impl JsonSchema for $name { + fn schema_name() -> Cow<'static, str> { + stringify!($name).into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + let empty: Option<&str> = $empty; + json_schema!({"type": "array", "items": point, "minItems": u32::from(empty.is_some())}) + } + } + }; +} + +point_list!( + /// Points on model edges, each picking the nearest edge of any body (the first 1000 are used). + EdgePoints, + limit: 1000, + bad: "`edges` must be points [x,y,z]", + empty: None +); +point_list!( + /// Points on faces, for combs along each face's isoparametric curves (the first 100 are used). + CombFaces, + limit: 100, + bad: "`faces` must list points [x,y,z]", + empty: Some("`faces` must list points [x,y,z]") +); +point_list!( + /// Points on faces, each picking the nearest face of any body (the first 1000 are used). + RadiusFaces, + limit: 1000, + bad: "`faces` must be points [x,y,z]", + empty: None +); +/// The most faces one isocurve call shows. +pub const MAX_ISO_FACES: usize = 100; + +const ISO_FACES: &str = "`faces` must list points [x,y,z] on faces"; + +/// Points on faces, each picking the nearest face of any body: 1 to [`MAX_ISO_FACES`] of them, +/// with the handler's messages. +#[derive(Clone, Debug, PartialEq)] +pub struct IsoFaces(pub Vec); + +impl<'de> Deserialize<'de> for IsoFaces { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + let points = v.as_array().ok_or_else(|| D::Error::custom(whole(ISO_FACES)))?; + if points.is_empty() || points.len() > MAX_ISO_FACES { + return Err(D::Error::custom(whole(format!("`faces` must list 1…{MAX_ISO_FACES} points [x,y,z] on faces")))); + } + points.iter().map(params::vec3).collect::>>().map(IsoFaces).ok_or_else(|| D::Error::custom(whole(ISO_FACES))) + } +} + +impl JsonSchema for IsoFaces { + fn schema_name() -> Cow<'static, str> { + "IsoFaces".into() + } + + fn inline_schema() -> bool { + true + } + + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + json_schema!({"type": "array", "items": point, "minItems": 1, "maxItems": MAX_ISO_FACES}) + } +} + +/// `true`, `false` or null, with the handler's message for anything else. +fn flag<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::Bool(b) => Ok(Some(b)), + _ => Err(D::Error::custom("must be true or false")), + } +} + +/// The comb's length multiplier, 0.01 to 100, with the handler's message for anything else; +/// `null` is none. +fn multiplier<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v + .as_f64() + .filter(|x| (0.01..=100.0).contains(x)) + .map(Some) + .ok_or_else(|| D::Error::custom(whole("`length` must be a multiplier 0.01…100"))), + } +} + +fn multiplier_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "null"], "minimum": 0.01, "maximum": 100}) +} + +/// Isocurves each way, a whole number 1 to `MAX_ISO_COUNT`, with the handler's message for +/// anything else; `null` is none. +fn iso_count<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let max = crate::kernel::MAX_ISO_COUNT; + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v + .as_f64() + .filter(|c| c.fract() == 0.0 && (1.0..=max as f64).contains(c)) + .map(Some) + .ok_or_else(|| D::Error::custom(whole(format!("`count` must be a whole number of curves each way, 1…{max}")))), + } +} + +fn iso_count_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["integer", "null"], "minimum": 1, "maximum": crate::kernel::MAX_ISO_COUNT}) +} + +/// A number, as `params::num` reads one (finite, under 1e9 in size), with the curvature comb's +/// message for anything else; `null` is none. +fn number<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v.as_f64().and_then(params::finite).map(Some).ok_or_else(|| D::Error::custom("must be a number")), + } +} + +fn number_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "null"], "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9}) +} + +/// Curvature combs: teeth along each curve, edge or face isocurve, each as long as the curvature +/// there times `scale`, standing out on the convex side. Give `curves`, `edges` or `faces`, or +/// more than one. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CurvatureCombParams { + /// Sketch curve ids (the first 1000 are used). + #[serde(default)] + pub curves: Option, + /// The sketch the curves are in (default: the one being edited). Read only with `curves`. + #[serde(default)] + pub sketch: Option, + #[serde(default)] + pub edges: Option, + #[serde(default, deserialize_with = "present")] + #[schemars(with = "CombFaces")] + pub faces: Option, + /// With `faces`: how many isoparametric curves each way (default 4; 1 to 50). + #[serde(default, deserialize_with = "number")] + #[schemars(schema_with = "number_schema")] + pub count: Option, + /// Teeth per curve (default 40; 2 to 2000). + #[serde(default, deserialize_with = "number")] + #[schemars(schema_with = "number_schema")] + pub density: Option, + /// Tooth length per unit of curvature (mm²). Default, or when not above 0: the longest tooth + /// is a fifth of the size of everything combed. + #[serde(default, deserialize_with = "number")] + #[schemars(schema_with = "number_schema")] + pub scale: Option, + /// A multiplier on the automatic scale (default 1; 0.01 to 100). Ignored with `scale`. + #[serde(default, deserialize_with = "multiplier")] + #[schemars(schema_with = "multiplier_schema")] + pub length: Option, + /// Keep the combs shown and add these, every comb again at one scale. With nothing picked it + /// draws those shown again with this call's options. + #[serde(default, deserialize_with = "flag")] + pub add: Option, + /// Turn the analysis off. + #[serde(default, deserialize_with = "flag")] + pub clear: Option, +} + +/// The smallest radius of curvature of each sketch curve, edge or face, and where it is. With +/// none of `curves`, `edges` and `faces`: every face of every body. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MinimumRadiusParams { + /// Sketch curve ids (the first 1000 are used). + #[serde(default)] + pub curves: Option, + /// The sketch the curves are in (default: the one being edited). Read only with `curves`. + #[serde(default)] + pub sketch: Option, + #[serde(default)] + pub edges: Option, + #[serde(default)] + pub faces: Option, +} + +/// The isoparametric curves of faces, u = const and v = const of each face's surface, cut to its +/// trims; `faces` unless `clear`. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct IsocurveParams { + #[serde(default)] + pub faces: Option, + /// How many curves each way (default 8; 1 to 100). + #[serde(default, deserialize_with = "iso_count")] + #[schemars(schema_with = "iso_count_schema")] + pub count: Option, + /// Keep the faces already shown. + #[serde(default, deserialize_with = "flag")] + pub add: Option, + /// Turn the analysis off. + #[serde(default, deserialize_with = "flag")] + pub clear: Option, +} + +/// The centre of mass of bodies, at uniform density, each and all together, where the bodies +/// are placed in the assembly. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CenterOfMassParams { + /// The bodies, by name (default: all). A body whose volume can't be measured is left out. + #[serde(default)] + pub bodies: Option, +} + +/// What a view analysis's `clear` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AnalysisCleared { + /// The analysis turned off. + pub analysis: String, + pub cleared: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `inspect.curvature_comb` returns: the combs, or the analysis turned off. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum CurvatureCombReply { + Combs(CurvatureCombs), + Cleared(AnalysisCleared), +} + +/// The combs `inspect.curvature_comb` shows. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CurvatureCombs { + /// One comb per curve, edge and face isocurve (those shown, with `add`). + pub combs: Vec, + /// The tooth length per unit of curvature used for every comb (mm²). + pub scale: f64, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One curvature comb. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Comb { + /// What it combs: a sketch curve's id, `edge@x,y,z` or `face@x,y,z#k` (the point given, and + /// the face's isocurve). + pub curve: String, + /// Each tooth, from the curve out to its tip. + pub teeth: Vec<[[f64; 3]; 2]>, + /// The teeth's tips, in order. + pub envelope: Vec<[f64; 3]>, + /// The largest curvature along it (1/mm). + pub max_curvature: f64, + /// Its smallest radius of curvature (mm); `null` when it is straight. + pub min_radius: Option, +} + +/// What `inspect.minimum_radius` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MinimumRadii { + /// Each curve, edge or face looked at. + pub items: Vec, + /// The smallest of them all (mm); `null` when everything is straight or flat. + pub min_radius: Option, + /// Where that is; `null` with it. + pub at: Option<[f64; 3]>, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One curve, edge or face's smallest radius of curvature. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RadiusItem { + /// A sketch curve's id, `edge@x,y,z`, `face@x,y,z` (the point given) or `:face`. + pub item: String, + /// Its smallest radius of curvature (mm); `null` when it is straight or flat. + pub min_radius: Option, + /// Where that is; only with a radius. + #[serde(skip_serializing_if = "Option::is_none")] + pub at: Option<[f64; 3]>, +} + +/// What `inspect.isocurve` returns: the curves, or the analysis turned off. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum IsocurveReply { + Curves(Isocurves), + Cleared(AnalysisCleared), +} + +/// The isocurves of the faces `inspect.isocurve` picked. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Isocurves { + /// Each isoparametric curve as points along it, `count` each way per face. + pub curves: Vec>, + /// Each face picked. + pub faces: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One face whose isocurves are shown. +#[derive(Debug, Serialize, JsonSchema)] +pub struct IsoFace { + /// The body, by name. + pub body: String, + /// The face's index in the body. + pub face: usize, + /// Curves asked for each way. + pub count: usize, + /// Curves along u (v = const) and along v (u = const), as cut to the face. + pub u_curves: usize, + pub v_curves: usize, +} + +/// What `inspect.center_of_mass` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CentersOfMass { + /// The centre of mass of the bodies together. + pub center: [f64; 3], + /// Their volume together (mm³). + pub volume: f64, + /// Each body measured. + pub bodies: Vec, + /// The bodies left out: those that enclose no volume or could not be measured. + pub skipped: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One body's centre of mass. +#[derive(Debug, Serialize, JsonSchema)] +pub struct BodyCenter { + /// Its name, in the assembly. + pub body: String, + /// Its centre of mass. + pub center: [f64; 3], + /// Its volume (mm³). + pub volume: f64, +} + +/// A body the centre of mass leaves out, and why. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SkippedBody { + pub body: String, + pub reason: String, +} + +#[cfg(test)] +#[path = "sketch_inspect_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/sketch_inspect_tests.rs b/crates/engine/src/schema/sketch_inspect_tests.rs new file mode 100644 index 000000000..6f894c716 --- /dev/null +++ b/crates/engine/src/schema/sketch_inspect_tests.rs @@ -0,0 +1,104 @@ +use serde_json::{Value, json}; + +use super::{ + CenterOfMassParams, CentersOfMass, CurvatureCombParams, CurvatureCombReply, IsocurveParams, IsocurveReply, MinimumRadii, MinimumRadiusParams, +}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys( + input_schema_for::(), + &["add", "clear", "count", "curves", "density", "edges", "faces", "length", "scale", "sketch"], + ); + assert_keys(input_schema_for::(), &["curves", "edges", "faces", "sketch"]); + assert_keys(input_schema_for::(), &["add", "clear", "count", "faces"]); + assert_keys(input_schema_for::(), &["bodies"]); +} + +/// Each point list keeps its own command's messages: a bad point, an empty list, `null`. +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("inspect.curvature_comb", json!({})), + ("inspect.curvature_comb", json!({"faces": []})), + ("inspect.curvature_comb", json!({"faces": null})), + ("inspect.curvature_comb", json!({"faces": "x"})), + ("inspect.curvature_comb", json!({"faces": [[1, 2]]})), + ("inspect.curvature_comb", json!({"faces": [[0, 0, 0]], "count": "x"})), + ("inspect.curvature_comb", json!({"faces": [[0, 0, 0]], "count": 1e9})), + ("inspect.curvature_comb", json!({"edges": [[1, 2]]})), + ("inspect.curvature_comb", json!({"edges": [[0, 0, 1e9]]})), + ("inspect.minimum_radius", json!({"edges": ["x"]})), + ("inspect.minimum_radius", json!({"faces": [[1, 2]]})), + ("inspect.minimum_radius", json!({"faces": [[0, 0, 500]]})), + ("inspect.isocurve", json!({"faces": []})), + ("inspect.isocurve", json!({"faces": null})), + ("inspect.isocurve", json!({"faces": 5})), + ("inspect.isocurve", json!({"faces": [[1, 2]]})), + ("inspect.isocurve", json!({"faces": [{"x": 0, "y": 0, "z": 500}]})), + ("inspect.isocurve", json!({"faces": [[0, 0, 0]], "count": 0})), + ("inspect.isocurve", json!({"faces": [[0, 0, 0]], "count": 2.5})), + ("inspect.curvature_comb", json!({"edges": [[0, 0, 0]], "length": 0})), + ("inspect.center_of_mass", json!({})), + ("inspect.center_of_mass", json!({"bodies": ["nope"]})), + ]); +} + +/// #10949: the four analysis commands reply as their output schemas say, in Warn without +/// warnings for good calls and with them for a misspelt key, on sketch curves, a cylinder's +/// edge and face, and every face. A `density` that isn't a number, which the handler reads as +/// none, gets a warning, and strict refuses it. +#[test] +fn analysis_commands_reply_with_their_schemas() { + let (combs, radii, isocurves, centers) = ( + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + ); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: &schemars::Schema, r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Curves"})); + let circle = run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5}))["curves"][0].clone(); + let line = run(&mut s, "sketch.line", json!({"points": [[0, 20], [10, 20]]}))["curves"][0].clone(); + let r = run(&mut s, "inspect.curvature_comb", json!({"curves": [circle, line], "density": 20})); + matches(&combs, &r, false); + assert!(r["combs"][1]["min_radius"].is_null(), "a line is straight: {r}"); + let r = run(&mut s, "inspect.minimum_radius", json!({"curves": circle, "sketch": "Curves"})); + matches(&radii, &r, false); + assert!(r["items"][0]["at"].is_array() && r["at"].is_array(), "{r}"); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.cylinder", json!({"base": [50, 0, 0], "radius": 8, "height": 10, "body_name": "Can"})); + + matches(&combs, &run(&mut s, "inspect.curvature_comb", json!({"edges": [[58, 0, 10]]})), false); + let r = run(&mut s, "inspect.curvature_comb", json!({"faces": [{"x": 58, "y": 0, "z": 5}], "count": 3, "scale": 0.5})); + matches(&combs, &r, false); + assert_eq!(r["scale"], 0.5, "{r}"); + matches(&radii, &run(&mut s, "inspect.minimum_radius", json!({"faces": [[58, 0, 5]], "edges": [[58, 0, 10]]})), false); + // Every face: the flat ends have no radius, and so no `at`. + let r = run(&mut s, "inspect.minimum_radius", json!({})); + matches(&radii, &r, false); + assert!(r["items"].as_array().into_iter().flatten().any(|i| i["min_radius"].is_null() && i.get("at").is_none()), "{r}"); + matches(&isocurves, &run(&mut s, "inspect.isocurve", json!({"faces": [[58, 0, 5]], "count": 4})), false); + matches(¢ers, &run(&mut s, "inspect.center_of_mass", json!({})), false); + let r = run(&mut s, "inspect.center_of_mass", json!({"bodies": "Can"})); + matches(¢ers, &r, false); + assert_eq!(r["bodies"][0]["body"], "Can", "{r}"); + + matches(&combs, &run(&mut s, "inspect.curvature_comb", json!({"edges": [[58, 0, 10]], "dencity": 20})), true); + matches(&combs, &run(&mut s, "inspect.curvature_comb", json!({"edges": [[58, 0, 10]], "density": "20"})), true); + matches(&radii, &run(&mut s, "inspect.minimum_radius", json!({"face": [[58, 0, 5]]})), true); + matches(&isocurves, &run(&mut s, "inspect.isocurve", json!({"faces": [[58, 0, 5]], "cnt": 2})), true); + matches(¢ers, &run(&mut s, "inspect.center_of_mass", json!({"body": "Can"})), true); + s.param_check = ParamCheck::Strict; + let error = s.execute("inspect.curvature_comb", &json!({"edges": [[58, 0, 10]], "density": "20"})).err().map(|e| e.to_string()); + assert!(error.as_deref().is_some_and(|e| e.contains("`density` must be a number")), "{error:?}"); +} diff --git a/crates/engine/src/schema/surface_analysis.rs b/crates/engine/src/schema/surface_analysis.rs new file mode 100644 index 000000000..f6f75af27 --- /dev/null +++ b/crates/engine/src/schema/surface_analysis.rs @@ -0,0 +1,212 @@ +//! Contracts and result types for the view-only surface analyses, the commands in +//! `cmd/surface_analysis.rs`; the handlers validate domain ranges. +use super::{AxisDir, Point3, present}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// `true`, `false` or null, with the handler's message for anything else. +fn flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::Bool(b) => Ok(Some(b)), + _ => Err(serde::de::Error::custom("must be true or false")), + } +} + +/// Say which view analysis is on (zebra, draft, curvature map, environment map, accessibility, +/// continuity, isocurves or curvature combs: one at a time), or turn it off. +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AnalysisParams { + /// Turn the view analysis on now off. + #[serde(default, deserialize_with = "flag")] + pub off: Option, +} + +/// What `inspect.analysis` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AnalysisState { + /// The command id of the view analysis on (after `off`), or null when none is. + pub active: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ZebraParams { + /// Stripe frequency across the view, including fractional values. Default 12; 1…200. + pub stripes: Option, + pub clear: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct DraftParams { + /// Nonzero pull direction. Default +Z; normalised by the handler. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "AxisDir")] + pub pull: Option, + /// Threshold in degrees, 0 inclusive to 90 exclusive. Default 1. + pub angle: Option, + pub clear: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct EnvironmentParams { + pub clear: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AccessibilityParams { + /// Nonzero direction the tool comes from. Default +Z. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "AxisDir")] + pub direction: Option, + pub clear: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CurvatureParams { + /// Radius in mm shown red, greater than 1e-6 and less than 1e9. + /// Default a tenth of the largest model diagonal, or 10 mm for an empty model. + pub radius: Option, + pub clear: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum EdgePick { + Index { index: usize }, + Point(Point3), +} +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ContinuityParams { + /// Body name; otherwise visible bodies. At most 64 bodies in one call. + pub body: Option, + /// At most 512 edge indices or points. Empty/absent measures all seams. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Vec")] + pub edges: Option>, + /// Integer stations per edge, 3…257. Default 33. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub samples: Option, + /// Positional tolerance in mm, 0…1e9 exclusive. Default .001. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub gap_tolerance_mm: Option, + /// Normal angle tolerance in degrees. Default 1. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub angle_tolerance_deg: Option, + /// Curvature tolerance in inverse mm. Default .01. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub curvature_tolerance_per_mm: Option, + /// Tolerance on the jump of the curvature's change across the seam (G3) in inverse mm². + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub curvature_change_tolerance_per_mm2: Option, + /// Tolerance on the jump of that change's rate (G4) in inverse mm³. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub curvature_change_rate_tolerance_per_mm3: Option, + /// Preserve other measured seams, replacing only matching body/edge records. + pub add: Option, + pub clear: Option, +} + +#[derive(Serialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Analysis { + Zebra { stripes: f64 }, + Draft { pull: [f64; 3], angle: f64 }, + Curvature { radius: f64 }, + Environment, + Access { dir: [f64; 3] }, +} +#[derive(Serialize, JsonSchema)] +pub struct AnalysisResult { + pub analysis: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} +#[derive(Serialize, JsonSchema)] +pub struct Metric { + pub value: f64, + pub at: [f64; 3], + pub edge_fraction: f64, +} +#[derive(Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Verdict { + Smooth, + CurvatureJump, + Sharp, + Gap, +} +#[derive(Serialize, JsonSchema)] +pub struct EdgeReport { + pub edge: usize, + pub length_mm: f64, + pub samples: usize, + pub gap_mm: Metric, + pub normal_angle_deg: Metric, + pub curvature_jump_per_mm: Metric, + pub curvature_change_jump_per_mm2: Metric, + pub curvature_change_rate_jump_per_mm3: Metric, + /// The highest continuity order met along the whole edge (`g0`…`g4`), null where the faces do + /// not meet. + pub order: Option, + pub verdict: Verdict, +} +#[derive(Serialize, JsonSchema)] +pub struct BodyReport { + pub body: String, + pub edges: Vec, + pub skipped: usize, + pub unmeasured: usize, +} +#[derive(Serialize, JsonSchema)] +pub struct Tolerances { + pub gap_mm: f64, + pub angle_deg: f64, + pub curvature_per_mm: f64, + pub curvature_change_per_mm2: f64, + pub curvature_change_rate_per_mm3: f64, +} +#[derive(Serialize, JsonSchema)] +pub struct Summary { + pub edges: usize, + pub smooth: usize, + pub curvature_jump: usize, + pub sharp: usize, + pub gap: usize, + pub skipped: usize, + pub unmeasured: usize, + /// How many edges meet each order. + pub orders: serde_json::Map, + pub worst: Option, +} +#[derive(Serialize, JsonSchema)] +#[serde(untagged)] +pub enum ContinuityResult { + Cleared { + analysis: String, + cleared: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + param_warnings: Vec, + }, + Measured { + analysis: String, + samples: usize, + tolerances: Tolerances, + bodies: Vec, + summary: Summary, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + param_warnings: Vec, + }, +} + +#[cfg(test)] +#[path = "surface_analysis_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/surface_analysis_tests.rs b/crates/engine/src/schema/surface_analysis_tests.rs new file mode 100644 index 000000000..e2955ab4a --- /dev/null +++ b/crates/engine/src/schema/surface_analysis_tests.rs @@ -0,0 +1,45 @@ +use serde_json::json; + +use super::AnalysisParams; +use crate::Session; +use crate::schema::input_schema_for; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["off"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[("inspect.analysis", json!({"off": "yes"})), ("inspect.analysis", json!({"off": 1}))]); +} + +/// The view analyses are one group: turning one on turns the one on before off, and +/// `inspect.analysis` names the one on and turns it off. +#[test] +fn one_view_analysis_is_on_at_a_time() { + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius": 5, "height": 10})).unwrap(); + let active = |s: &mut Session| s.execute("inspect.analysis", &json!({})).unwrap()["active"].clone(); + assert_eq!(active(&mut s), json!(null)); + s.execute("inspect.zebra", &json!({})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.zebra")); + s.execute("inspect.curvature_comb", &json!({"edges": [[0, 5, 10]]})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.curvature_comb")); + assert!(s.analysis.is_none(), "the zebra stripes went off"); + s.execute("inspect.isocurve", &json!({"faces": [[0, 5, 5]]})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.isocurve")); + assert!(s.comb.is_none(), "the combs went off"); + s.execute("inspect.continuity", &json!({})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.continuity")); + assert!(s.isocurves.is_empty(), "the isocurves went off"); + s.execute("inspect.draft", &json!({})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.draft")); + assert!(s.continuity.is_empty(), "the seams went off"); + // Turning on the comb with nothing picked yet. + s.execute("inspect.curvature_comb", &json!({"add": true})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.curvature_comb")); + assert_eq!(s.execute("inspect.analysis", &json!({"off": true})).unwrap()["active"], json!(null)); + assert!(s.comb.is_none() && s.analysis.is_none()); +} diff --git a/crates/engine/src/schema/surface_boundary.rs b/crates/engine/src/schema/surface_boundary.rs new file mode 100644 index 000000000..e449b1ded --- /dev/null +++ b/crates/engine/src/schema/surface_boundary.rs @@ -0,0 +1,274 @@ +//! Contract for `surface.boundary` in `cmd/surface_boundary.rs` (#11083). It returns +//! `add_feature`'s reply, a [`super::features::FeatureResult`]. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer}; +use serde_json::{Value, json}; +use solidcraft_geom::fill::{MAX_CROWN, MIN_CROWN}; +use solidcraft_kernel::{Continuity, MAX_CHAIN_CURVES, MAX_EDGE_PICKS}; + +use super::check::whole; +use super::types::{FeatureCommon, IdOrName, OperationParam, Point3, feature_common, present}; +use crate::params; + +/// The fewest stations a patch can hold the widest continuity pair with: a G3 side needs four +/// rows at each of two opposite sides, so eight. +pub const MIN_SAMPLES: usize = 8; +/// The most stations a boundary may carry (the kernel's own cap). +pub const MAX_SAMPLES: usize = 512; +/// The most curves one direction of a network may list (the kernel's own cap). +pub const MAX_NETWORK_CURVES: usize = solidcraft_geom::network::MAX_NETWORK_CURVES; + +const CMD: &str = "surface.boundary"; + +/// A surface through curves: either one patch through a loop of two to four curves of one sketch +/// (`curves`, with `continuity`, `crown` and `samples`), or one surface through a curve network +/// (`u`, with `v` and `operation`). The keys of one form are refused with the other's. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct BoundaryParams { + /// The sketch the loop's curves, or a network's bare curve ids, are in (default: the one being + /// edited). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "IdOrName")] + pub sketch: Option, + /// The loop: 2 to 4 sketch curve ids in loop order, each ending where the next begins and the + /// last where the first does. Two: the patch spans between them, leaving each along the + /// tangent across it. Three or four: the flat patch of the loop, three collapsing the side + /// opposite the first curve to the corner there. + #[serde(default, deserialize_with = "curves")] + #[schemars(schema_with = "curves_schema")] + pub curves: Option>, + #[serde(default)] + pub continuity: Option, + /// With two curves: how full the middle is, without touching a boundary, -0.9 to 3 (default 0). + #[serde(default, deserialize_with = "crown")] + #[schemars(schema_with = "crown_schema")] + pub crown: Option, + /// Stations per boundary: a whole number from 8 to 512 (default 25). + #[serde(default, deserialize_with = "samples")] + #[schemars(schema_with = "samples_schema")] + pub samples: Option, + #[serde(default)] + pub u: Option, + #[serde(default)] + pub v: Option, + /// A network's: `new` (the default) or `join`, which sews the surface into the body of its + /// first edge curve, a solid when it closes the gap. + #[serde(default)] + pub operation: Option, + #[serde(flatten, deserialize_with = "feature_common")] + pub common: FeatureCommon, +} + +/// The message of a handler's parameter error, for a reader the contract shares. +fn message(e: crate::EngineError) -> String { + match e { + crate::EngineError::BadParams { msg, .. } => msg, + other => other.to_string(), + } +} + +/// The loop's curves, read by `params::string_list` itself, with its messages. +fn curves<'de, D: Deserializer<'de>>(d: D) -> Result>, D::Error> { + let v = Value::deserialize(d)?; + params::string_list(CMD, &json!({ "curves": v }), "curves").map(Some).map_err(|e| D::Error::custom(whole(message(e)))) +} + +fn curves_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": 10000}, {"type": "null"}]}) +} + +/// `crown`, with the handler's message; `null` is 0. +fn crown<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v + .as_f64() + .filter(|x| x.is_finite() && (MIN_CROWN..=MAX_CROWN).contains(x)) + .map(Some) + .ok_or_else(|| D::Error::custom(whole("`crown` must be a number between -0.9 and 3"))), + } +} + +fn crown_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "null"], "minimum": MIN_CROWN, "maximum": MAX_CROWN}) +} + +/// `samples`, with the handler's message; `null` is the default. +fn samples<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => { + v.as_f64().filter(|x| x.is_finite() && x.fract() == 0.0 && (MIN_SAMPLES as f64..=MAX_SAMPLES as f64).contains(x)).map(Some).ok_or_else( + || D::Error::custom(whole(format!("`samples` must be a whole number of stations between {MIN_SAMPLES} and {MAX_SAMPLES}"))), + ) + } + } +} + +fn samples_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "null"], "minimum": MIN_SAMPLES, "maximum": MAX_SAMPLES, "multipleOf": 1}) +} + +/// How much of the surface across each boundary the patch repeats: one of g0, g1, g2 or g3 for +/// every curve, or one per curve, with the handler's messages (default g1). A sketch curve's own +/// plane, so g1 and up hold exactly and g0 lets the middle bow. +#[derive(Clone, Debug, PartialEq)] +pub struct BoundaryContinuity(pub Vec); + +impl<'de> Deserialize<'de> for BoundaryContinuity { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(w) => Continuity::parse(&w) + .map(|c| BoundaryContinuity(vec![c])) + .ok_or_else(|| D::Error::custom(whole("`continuity` must be g0, g1, g2 or g3"))), + Value::Array(list) => list + .iter() + .map(|x| x.as_str().and_then(Continuity::parse)) + .collect::>>() + .map(BoundaryContinuity) + .ok_or_else(|| D::Error::custom(whole("a `continuity` entry must be g0, g1, g2 or g3"))), + _ => Err(D::Error::custom(whole("`continuity` must be one word, or one per curve"))), + } + } +} + +impl JsonSchema for BoundaryContinuity { + fn schema_name() -> Cow<'static, str> { + "BoundaryContinuity".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let word = json!({"type": "string", "pattern": "^[gG][0-3]$"}); + json_schema!({ + "description": "How much of the surface across each boundary the patch repeats: g0, g1 (the default), g2 or g3 for every curve, or one per curve. A sketch curve's own plane, so g1 and up hold exactly and g0 lets the middle bow.", + "anyOf": [word, {"type": "array", "items": word}] + }) + } +} + +/// One direction of a network (`key` is `u` or `v`), checked where the handler checks it without +/// the design, with its messages: each item a curve id, `{sketch?, curves}` (planar or 3D sketch +/// curves meeting end to end), `{body, edges}` (points on a chain of a body's edges) or `{point}` +/// (a side collapsed to a point), and a `continuity` (g0, g1 or g2) only on a body's edges. +fn network(key: &str, v: Value) -> Result<(), String> { + let list = match v { + Value::Array(a) => a, + _ => return Err(format!("`{key}` must list curves")), + }; + if list.len() > MAX_NETWORK_CURVES { + return Err(format!("`{key}` may list at most {MAX_NETWORK_CURVES} curves")); + } + for (k, item) in list.iter().enumerate() { + let name = format!("{key}[{k}]"); + let (mut curves, mut on_body, mut point) = (1, false, false); + if let Value::Object(o) = item { + let has = |k: &str| o.get(k).is_some_and(|v| !v.is_null()); + let kinds = [has("curves"), has("body") || has("edges"), has("point")]; + if kinds.iter().filter(|x| **x).count() != 1 { + return Err(format!("{name} must be one of {{sketch?, curves}}, {{body, edges}} or {{point}}")); + } + if has("point") { + o.get("point").and_then(params::vec3).ok_or_else(|| format!("{name}.point must be [x, y, z]"))?; + point = true; + } else if kinds[1] { + o.get("body").and_then(Value::as_str).ok_or_else(|| format!("{name}.body must name a body"))?; + let edges = o.get("edges").and_then(Value::as_array).ok_or_else(|| format!("{name}.edges must list points on the edges"))?; + if edges.is_empty() || edges.len() > MAX_EDGE_PICKS { + return Err(format!("{name}.edges must list 1 to {MAX_EDGE_PICKS} points on a chain of edges")); + } + if !edges.iter().all(|e| params::vec3(e).is_some()) { + return Err(format!("{name}.edges: a point must be [x, y, z]")); + } + on_body = true; + } else { + curves = params::string_list(CMD, item, "curves").map_err(message)?.len(); + } + if let Some(g) = o.get("continuity").filter(|v| !v.is_null()) { + let g = params::continuity(CMD, Some(g), &format!("{name}.continuity"), solidcraft_kernel::Construction::Network).map_err(message)?; + if g != Continuity::G0 && !on_body { + return Err(format!("{name}: g1 and g2 apply to a curve on a body's edges (a surface's open edges)")); + } + } + } else if !item.is_string() { + return Err(format!("{name} must be a curve id or {{sketch?, curves}}, {{body, edges}} or {{point}}")); + } + if !point && !on_body && (curves == 0 || curves > MAX_CHAIN_CURVES) { + return Err(format!("{name} must list 1 to {MAX_CHAIN_CURVES} sketch curves")); + } + } + Ok(()) +} + +/// The network's curves of one direction, checked by [`network`]. +macro_rules! network_direction { + ($(#[$doc:meta])* $name:ident, $key:literal) => { + $(#[$doc])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name(pub Value); + + impl<'de> Deserialize<'de> for $name { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + network($key, v.clone()).map_err(|m| D::Error::custom(whole(m)))?; + Ok($name(v)) + } + } + + impl JsonSchema for $name { + fn schema_name() -> Cow<'static, str> { + stringify!($name).into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + network_schema(generator) + } + } + }; +} + +network_direction!( + /// A network's curves one way: two or more, which the surface lofts through. + UCurves, + "u" +); +network_direction!( + /// A network's curves the other way, each crossing every `u` curve once: two each way give a + /// Coons patch, more a Gordon surface through every curve. A curve that misses another by + /// more than 0.01 mm is refused, naming the pair. + VCurves, + "v" +); + +fn network_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + let continuity = json!({"description": "g0 (the default), or on a body's edges g1 (tangent to the face beside a surface's open edge) or g2 (its curvature too).", "type": "string", "pattern": "^[gG][0-2]$"}); + json_schema!({ + "type": "array", + "maxItems": MAX_NETWORK_CURVES, + "items": { + "anyOf": [ + {"description": "A curve of `sketch`, by id.", "type": "string"}, + {"description": "Sketch curves meeting end to end (planar or 3D).", "type": "object", + "properties": {"sketch": {"type": ["number", "string"]}, "curves": {"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": MAX_CHAIN_CURVES}]}, "continuity": continuity.clone()}, + "required": ["curves"]}, + {"description": "Points on a chain of a body's edges.", "type": "object", + "properties": {"body": {"type": "string"}, "edges": {"type": "array", "items": point.clone(), "minItems": 1, "maxItems": MAX_EDGE_PICKS}, "continuity": continuity}, + "required": ["body", "edges"]}, + {"description": "A side collapsed to a point: a three-sided patch.", "type": "object", "properties": {"point": point}, "required": ["point"]} + ] + } + }) +} + +#[cfg(test)] +#[path = "surface_boundary_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/surface_boundary_tests.rs b/crates/engine/src/schema/surface_boundary_tests.rs new file mode 100644 index 000000000..4154a8220 --- /dev/null +++ b/crates/engine/src/schema/surface_boundary_tests.rs @@ -0,0 +1,105 @@ +use serde_json::{Value, json}; + +use super::BoundaryParams; +use crate::Session; +use crate::schema::features::FeatureResult; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// A box `Box`, then a sketch `Flat` being edited with a 10 mm square of four separate lines: +/// their ids, bottom, top, left, right. +fn square(s: &mut Session) -> [String; 4] { + run(s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [40, 40, 0], "body_name": "Box"})); + run(s, "sketch.create", json!({"plane": "XY", "name": "Flat"})); + let line = |s: &mut Session, a: [i32; 2], b: [i32; 2]| { + run(s, "sketch.line", json!({"points": [a, b], "infer": false, "connect": false}))["created"]["curves"][0] + .as_str() + .map(str::to_string) + .unwrap_or_default() + }; + [line(s, [0, 0], [10, 0]), line(s, [0, 10], [10, 10]), line(s, [0, 0], [0, 10]), line(s, [10, 0], [10, 10])] +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys( + input_schema_for::(), + &["body_name", "body_names", "continuity", "crown", "curves", "name", "operation", "participants", "samples", "sketch", "u", "v"], + ); +} + +/// A call that fails today gets the same message in strict. These need a sketch being edited +/// and its curves, so each runs on one (`assert_strict_keeps_todays_errors` runs after a finished +/// sketch, with no curves to name). +#[test] +fn strict_keeps_todays_errors() { + let mut s = Session::default(); + let [a, b, ..] = square(&mut s); + let many: Vec = (0..33).map(|_| json!(a)).collect(); + let point = json!([0, 0, 0]); + for p in [ + json!({"curves": [a]}), + json!({"curves": 5}), + json!({"curves": [a, 5]}), + json!({"curves": [a, b], "continuity": "g7"}), + json!({"curves": [a, b], "continuity": ["g1", 5]}), + json!({"curves": [a, b], "continuity": 5}), + json!({"curves": [a, b], "crown": 5}), + json!({"curves": [a, b], "samples": 7}), + json!({"curves": [a, b], "samples": 8.5}), + json!({"curves": [a, b], "sketch": null}), + json!({"curves": [a, b], "sketch": true}), + json!({"u": "l1"}), + json!({"u": [42, a]}), + json!({"u": [{}, a]}), + json!({"u": [{"curves": [], "sketch": "Flat"}, a]}), + json!({"u": [{"body": 5, "edges": [point]}, a]}), + json!({"u": [{"body": "Box", "edges": []}, a]}), + json!({"u": [{"body": "Box", "edges": [["x", 0, 0]]}, a]}), + json!({"u": [{"point": [0, 0]}, a]}), + json!({"u": [{"curves": [a], "body": "Box", "edges": [point]}, b]}), + json!({"u": [{"curves": [a], "continuity": "g1"}, b]}), + json!({"u": [{"body": "Box", "edges": [point], "continuity": "g3"}, a]}), + json!({"u": [{"body": "Box", "edges": [point], "continuity": "g9"}, a]}), + json!({"u": many}), + json!({"u": [a, b], "v": "x"}), + ] { + let error = |level: ParamCheck| { + let mut s = Session { param_check: level, ..Session::default() }; + square(&mut s); + s.execute("surface.boundary", &p).err().map(|e| e.to_string()) + }; + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{p} should fail today"); + assert_eq!(error(ParamCheck::Strict), off, "{p}"); + } +} + +/// #11083: both forms reply with `FeatureResult`, in Warn without warnings for good calls and +/// with them for a misspelt key: a patch between two sides of the square with every loop key, +/// and the square as a network. +#[test] +fn a_boundary_surface_replies_with_the_feature_result() { + let schema = output_schema_for::(); + let matches = |r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let [bottom, top, left, right] = square(&mut s); + let r = run( + &mut s, + "surface.boundary", + json!({"sketch": "Flat", "curves": [bottom, top], "continuity": ["g1", "G2"], "crown": 0.5, "samples": 16, "name": "Patch", "body_name": "Sheet"}), + ); + matches(&r, false); + assert_eq!(r["created_bodies"], json!(["Sheet"]), "{r}"); + let r = run(&mut s, "surface.boundary", json!({"u": [bottom, {"sketch": "Flat", "curves": [top]}], "v": [left, right], "operation": "new"})); + matches(&r, false); + matches(&run(&mut s, "surface.boundary", json!({"curves": [bottom, top], "crwn": 1})), true); +} diff --git a/crates/engine/src/schema/surface_match.rs b/crates/engine/src/schema/surface_match.rs new file mode 100644 index 000000000..c4dfdcbfc --- /dev/null +++ b/crates/engine/src/schema/surface_match.rs @@ -0,0 +1,165 @@ +//! Contract for `surface.match` in `cmd/surface_match.rs` (#10981). It returns `add_feature`'s +//! reply, a [`super::features::FeatureResult`]. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer}; +use serde_json::Value; +use solidcore_record::Vec3; +use solidcraft_kernel::{Construction, Continuity}; + +use super::check::whole; +use super::types::{Point3, StringList, present}; +use crate::params; + +/// Rebuild one face of a surface body so that its boundary nearest a picked edge chain of another +/// body lies on that chain and repeats that body's shape there up to `order`, while the opposite +/// boundary keeps its place. The body keeps its name: a match changes it rather than making one. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MatchSurfaceParams { + /// The surface body whose face is rebuilt, by name. + #[serde(deserialize_with = "body")] + pub body: String, + #[serde(default)] + pub faces: Option, + /// The body the seam must meet, by name. + #[serde(deserialize_with = "target")] + pub target: String, + pub edges: MatchEdges, + /// How closely the seam follows the target: `g1` (tangent), `g2` (curvature, the default) or + /// `g3`, in any case. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "MatchOrder")] + pub order: Option, + // Not `FeatureCommon`: a match makes no body, so `body_name` and `body_names` would do + // nothing. `participants` stays because `timeline.redefine` passes a feature's own back. + /// The feature's name in the timeline. + #[serde(default)] + pub name: Option, + /// The bodies taking part, which every feature records; each an existing body or `*`. A match + /// changes only `body`, whatever this lists. + #[serde(default)] + pub participants: Option, +} + +/// A body name, with the handler's message for anything that isn't text. +fn body<'de, D: Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(D::Error::custom(whole("`body` is required"))), + } +} + +/// The target's name, with the handler's message for anything that isn't text. +fn target<'de, D: Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(D::Error::custom(whole("`target` is required"))), + } +} + +/// Points `params::vec3` reads, or none if any isn't one. +fn points(v: &[Value]) -> Option> { + v.iter().map(params::vec3).collect() +} + +/// Points on the face to rebuild, at most 64 (default: the body's first face). +#[derive(Clone, Debug, PartialEq)] +pub struct MatchFaces(pub Vec); + +impl<'de> Deserialize<'de> for MatchFaces { + fn deserialize>(d: D) -> Result { + let faces = + Value::deserialize(d)?.as_array().and_then(|a| points(a)).ok_or_else(|| D::Error::custom("must be a list of points [x, y, z]"))?; + if faces.len() > 64 { + return Err(D::Error::custom(whole("too many points on the face to rebuild"))); + } + Ok(MatchFaces(faces)) + } +} + +impl JsonSchema for MatchFaces { + fn schema_name() -> Cow<'static, str> { + "MatchFaces".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + json_schema!({ + "description": "Points on the face to rebuild, at most 64 (default: the body's first face).", + "type": "array", + "items": point, + "maxItems": 64 + }) + } +} + +/// Points on one edge chain of the target: the rebuilt boundary takes its place. 1 to 10 000, +/// with the handler's message for anything else. +#[derive(Clone, Debug, PartialEq)] +pub struct MatchEdges(pub Vec); + +impl<'de> Deserialize<'de> for MatchEdges { + fn deserialize>(d: D) -> Result { + Value::deserialize(d)? + .as_array() + .and_then(|a| points(a)) + .filter(|edges| !edges.is_empty() && edges.len() <= 10_000) + .map(MatchEdges) + .ok_or_else(|| D::Error::custom(whole("`edges` must list 1 to 10000 points on the target's edge chain"))) + } +} + +impl JsonSchema for MatchEdges { + fn schema_name() -> Cow<'static, str> { + "MatchEdges".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + json_schema!({ + "description": "Points on one edge chain of the target: the rebuilt boundary takes its place.", + "type": "array", + "items": point, + "minItems": 1, + "maxItems": 10000 + }) + } +} + +/// A match's continuity, as `params::continuity` reads it for a match (g1 to g3), with its messages. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MatchOrder(pub Continuity); + +impl<'de> Deserialize<'de> for MatchOrder { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + params::continuity("surface.match", Some(&v), "`order`", Construction::Match).map(MatchOrder).map_err(|e| match e { + crate::EngineError::BadParams { msg, .. } => D::Error::custom(whole(msg)), + other => D::Error::custom(whole(other.to_string())), + }) + } +} + +impl JsonSchema for MatchOrder { + fn schema_name() -> Cow<'static, str> { + "MatchOrder".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "pattern": "^[gG][123]$"}) + } +} + +#[cfg(test)] +#[path = "surface_match_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/surface_match_tests.rs b/crates/engine/src/schema/surface_match_tests.rs new file mode 100644 index 000000000..47bedff2e --- /dev/null +++ b/crates/engine/src/schema/surface_match_tests.rs @@ -0,0 +1,121 @@ +use serde_json::{Value, json}; +use solidcore_record::Vec3; + +use super::MatchSurfaceParams; +use crate::Session; +use crate::schema::features::FeatureResult; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// Two points on the cylinder's straight vertical wall seam, as the command's own tests pick it. +fn picks(s: &Session) -> Vec { + let boss = s.world_state().ok().and_then(|st| st.body("Boss").map(|b| b.body.clone())).unwrap_or_else(|| panic!("no Boss")); + let e = boss + .edges(boss.size() * 1e-2) + .unwrap_or_default() + .into_iter() + .find(|e| e.length > 25.0 && (e.mid.x.hypot(e.mid.y) - 10.0).abs() < 0.05 && e.mid.z > 5.0 && e.mid.z < 25.0) + .unwrap_or_else(|| panic!("the cylinder has a straight vertical wall seam")); + let (a, b) = (e.points.first().copied().unwrap_or(e.mid), e.points.last().copied().unwrap_or(e.mid)); + vec![a + (b - a) * 0.25, a + (b - a) * 0.75] +} + +/// A cylinder `Boss` of radius 10, 30 high, and a cylindrical surface `Skirt` of radius 11 from +/// the cylinder's wall seam round 60 degrees, as in the command's own tests: a point on the skirt. +fn boss_and_skirt(s: &mut Session) -> [f64; 3] { + run(s, "sketch.create", json!({"plane": "XY", "name": "Round"})); + run(s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": "Round", "distance": 30, "body_name": "Boss"})); + let seam = picks(s)[0]; + let a = seam.y.atan2(seam.x); + let at = |t: f64| json!([11.0 * t.cos(), 11.0 * t.sin()]); + run(s, "sketch.create", json!({"plane": "XY", "name": "Skirt sketch"})); + let arc = run(s, "sketch.arc.three_point", json!({"start": at(a), "end": at(a + 60f64.to_radians()), "through": at(a + 30f64.to_radians())})) + ["created"]["curves"][0] + .clone(); + run(s, "sketch.finish", json!({})); + run(s, "surface.extrude", json!({"sketch": "Skirt sketch", "curves": [arc], "distance": 30, "body_name": "Skirt"})); + let mid = a + 30f64.to_radians(); + [11.0 * mid.cos(), 11.0 * mid.sin(), 15.0] +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["body", "edges", "faces", "name", "order", "participants", "target"]); +} + +/// A call that fails today gets the same message in strict. The handler looks both bodies up +/// before it reads the picks, so each call runs on a design with two (a missing `edges` is left +/// out: strict says it is required, the handler what it must list). +#[test] +fn strict_keeps_todays_errors() { + let many = vec![[0, 0, 0]; 10_001]; + let faces = vec![[0, 0, 0]; 65]; + let e = json!([[0, 0, 0]]); + for p in [ + json!({"target": "T", "edges": e}), + json!({"body": 5, "target": "T", "edges": e}), + json!({"body": "Nope", "target": "T", "edges": e}), + json!({"body": "B", "edges": e}), + json!({"body": "B", "target": [], "edges": e}), + json!({"body": "B", "target": "Nope", "edges": e}), + json!({"body": "B", "target": "T", "faces": faces, "edges": e}), + json!({"body": "B", "target": "T", "edges": []}), + json!({"body": "B", "target": "T", "edges": null}), + json!({"body": "B", "target": "T", "edges": 5}), + json!({"body": "B", "target": "T", "edges": [[1, 2]]}), + json!({"body": "B", "target": "T", "edges": many}), + json!({"body": "B", "target": "T", "edges": e, "order": "g5"}), + json!({"body": "B", "target": "T", "edges": e, "order": "g0"}), + json!({"body": "B", "target": "T", "edges": e, "order": null}), + json!({"body": "B", "target": "T", "edges": e, "order": 2}), + json!({"body": "B", "target": "T", "edges": e}), + ] { + let error = |level: ParamCheck| { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "body_name": "B"})); + run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [10, 0, 0], "body_name": "T"})); + s.param_check = level; + s.execute("surface.match", &p).err().map(|e| e.to_string()) + }; + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{p} should fail today"); + assert_eq!(error(ParamCheck::Strict), off, "{p}"); + } +} + +/// #10981: a match replies with `FeatureResult`, in Warn without warnings for good calls (the +/// body's first face, and a picked face with every other key) and with them for a misspelt key; +/// strict refuses a face point the handler would drop. +#[test] +fn a_match_replies_with_the_feature_result() { + let schema = output_schema_for::(); + let matches = |r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let on_skirt = boss_and_skirt(&mut s); + let chain = picks(&s); + let r = run(&mut s, "surface.match", json!({"body": "Skirt", "target": "Boss", "edges": chain, "order": "G2"})); + matches(&r, false); + assert_eq!(r["changed_bodies"], json!(["Skirt"]), "{r}"); + let r = run( + &mut s, + "surface.match", + json!({"body": "Skirt", "faces": [on_skirt], "target": "Boss", "edges": chain, "order": "g1", "name": "Seam", "participants": ["*"]}), + ); + matches(&r, false); + assert_eq!(r["name"], "Seam", "{r}"); + matches(&run(&mut s, "surface.match", json!({"body": "Skirt", "target": "Boss", "edges": chain, "ordr": "g3"})), true); + s.param_check = ParamCheck::Strict; + let error = s.execute("surface.match", &json!({"body": "Skirt", "faces": [on_skirt, [1, 2]], "target": "Boss", "edges": chain})); + let error = error.err().map(|e| e.to_string()); + assert!(error.as_deref().is_some_and(|e| e.contains("`faces` must be a list of points")), "{error:?}"); +} diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs index b45581837..48b987642 100644 --- a/crates/engine/src/schema/tests.rs +++ b/crates/engine/src/schema/tests.rs @@ -380,7 +380,7 @@ fn issues_are_read_from_the_commands_own_contract() { assert_eq!(messages(&issues), ["unknown key `operaton`; did you mean `operation`?"]); assert_eq!(issues, box_contract().check(&json!({"length": 1, "width": 1, "height": 1, "operaton": "cut"}))); // No contract, or no such command: nothing to say. - assert!(super::issues("solid.fillet", &json!({"nonsense": 1})).is_empty()); + assert!(super::issues("solid.chamfer", &json!({"nonsense": 1})).is_empty()); assert!(super::issues("no.such", &json!({"nonsense": 1})).is_empty()); } @@ -391,6 +391,93 @@ fn a_level_is_read_back_from_its_name() { } } +#[test] +fn ui_prefs_theme_options_input_schema_covers_updates_and_resets() { + use super::ui_prefs::PrefsParams; + let schema = input_schema_for::(); + let schema = schema.as_value(); + assert!(schema["properties"]["theme_options"].is_object()); + for value in [ + json!({}), + json!({"theme_options":{}}), + json!({"theme_options":{"a":{}}}), + json!({"theme_options":{"a":{"enabled":true,"amount":3.5,"style":"cool","reset":null}},"theme":"a"}), + ] { + assert!(serde_json::from_value::(value.clone()).is_ok(), "{value}"); + assert!(conforms(schema, schema, &value), "{value}"); + } + for value in [ + json!({"theme_options":null}), + json!({"theme_options":[]}), + json!({"theme_options":{"a":true}}), + json!({"theme_options":{"a":{"enabled":{}}}}), + json!({"theme_options":{"a":{"amount":[]}}}), + ] { + assert!(serde_json::from_value::(value.clone()).is_err(), "{value}"); + } +} + +#[test] +fn ui_prefs_theme_options_output_schema_matches_serialized_reply() { + use super::ui_prefs::*; + let options = ThemeOptionsReply { + theme_option_defs: vec![ + ThemeOptionDef { + id: "enabled".into(), + kind: ThemeOptionKind::Bool { default: false }, + label: "Enabled".into(), + help: String::new(), + parent: None, + advanced: false, + section: None, + standard: false, + available: true, + reason: None, + }, + ThemeOptionDef { + id: "blur".into(), + kind: ThemeOptionKind::Range { default: 0.0, min: 0.0, max: 100.0, step: 1.0, unit: Some("px".into()) }, + label: "blur".into(), + help: String::new(), + parent: None, + advanced: false, + section: None, + standard: true, + available: false, + reason: Some("not implemented".into()), + }, + ThemeOptionDef { + id: "style".into(), + kind: ThemeOptionKind::Choice { default: "warm".into(), values: vec![ThemeChoice { id: "warm".into(), label: "Warm".into() }] }, + label: "Style".into(), + help: String::new(), + parent: Some("enabled".into()), + advanced: true, + section: Some("Details".into()), + standard: false, + available: true, + reason: None, + }, + ], + theme_option_values: [ + ("enabled".into(), ThemeOptionValue::Bool(true)), + ("blur".into(), ThemeOptionValue::Num(0.0)), + ("style".into(), ThemeOptionValue::Choice("warm".into())), + ] + .into(), + theme_option_notices: vec![ThemeOptionNotice { id: "removed".into(), kind: ThemeOptionNoticeKind::UnknownOption }], + }; + let reply = PrefsReply { options, settings: [("theme".into(), json!("a")), ("theme_options".into(), json!({"a":{"enabled":true}}))].into() }; + let value = serde_json::to_value(&reply).unwrap(); + let schema = output_schema_for::(); + let schema = schema.as_value(); + for field in ["theme_option_defs", "theme_option_values", "theme_option_notices"] { + assert!(schema["properties"][field].is_object(), "{schema}"); + } + assert!(conforms(schema, schema, &value), "{schema}\n{value}"); + assert_eq!(serde_json::to_value(serde_json::from_value::(value.clone()).unwrap()).unwrap(), value); +} + /// Whether `v` conforms to `node` of the schema `root`, for the keywords these schemas use /// apart from `pattern`: `type`, `properties`, `required`, `additionalProperties: false`, /// `items`, `minItems`, `maxItems`, `uniqueItems`, `enum`, `minLength`, `maxLength`, `minimum`, @@ -700,7 +787,7 @@ fn face_and_edge_refs_match_the_pick_readers() { assert!(parse::(json!({"body": "A", "index": 1.0})).is_none()); assert_eq!(edge_schema["anyOf"][2]["properties"]["index"]["type"], "integer"); assert_eq!(parse::(json!({"body": "A", "index": 4})), Some(EdgeRef::Index { body: "A".into(), index: 4 })); - assert_eq!(parse::(json!({"point": [1, 2, 3]})), Some(FaceRef::Point(solidcraft_geom::Vec3::new(1.0, 2.0, 3.0)))); + assert_eq!(parse::(json!({"point": [1, 2, 3]})), Some(FaceRef::Point(solidcore_record::Vec3::new(1.0, 2.0, 3.0)))); } /// The pick lists take 1 to 1000 picks, as `face_points` and `edge_points` do, and so do their @@ -833,7 +920,8 @@ fn shared_types_keep_the_handlers_messages() { for (id, p, probe) in [ ("solid.shell", json!({"thickness": 1, "faces": 5}), json!({"faces": 5})), ("solid.shell", json!({"thickness": 1, "faces": null}), json!({"faces": null})), - ("solid.shell", json!({"thickness": 1, "faces": []}), json!({"faces": []})), + // `solid.shell` takes no faces (a closed hollow body); the draft refuses them. + ("solid.draft", json!({"angle": 1, "faces": []}), json!({"faces": []})), ("solid.shell", json!({"thickness": 1, "faces": [true]}), json!({"faces": [true]})), ("solid.shell", json!({"thickness": 1, "faces": [""]}), json!({"faces": [""]})), ("solid.fillet", json!({"radius": 1, "edges": {}}), json!({"edges": {}})), @@ -1056,3 +1144,38 @@ fn plane_names_match_check_plane_name() { } assert!(parse::(json!(5)).is_none()); } + +#[test] +fn sketch_edit_contracts_validate_markers_before_changing_the_session() { + use crate::schema::sketch::{CancelResult, EditParams, EditResult, ExitParams, FinishResult}; + use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + assert_keys(input_schema_for::(), &["restore_marker", "sketch"]); + assert_keys(input_schema_for::(), &["restore_marker"]); + let mut s = crate::Session::default(); + let run = |s: &mut crate::Session, id: &str, p: serde_json::Value| s.execute(id, &p).unwrap(); + let id = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5})); + s.param_check = ParamCheck::Strict; + let before = s.doc.to_json(); + for marker in [json!(-1), json!(3), json!(1.5), json!(true), json!([])] { + assert!(s.execute("sketch.edit", &json!({"sketch": id, "restore_marker": marker})).is_err()); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.active_sketch, None); + } + for exit in ["sketch.finish", "sketch.cancel"] { + let r = run(&mut s, "sketch.edit", json!({"sketch": id, "restore_marker": null})); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &r)); + for params in [json!({"restore_marker": "yes"}), json!({"unknown": true})] { + assert!(s.execute(exit, ¶ms).is_err()); + assert_eq!(s.active_sketch, Some(id)); + assert_eq!(s.doc.marker, Some(1)); + } + let r = run(&mut s, exit, json!({})); + let schema = if exit == "sketch.finish" { output_schema_for::() } else { output_schema_for::() }; + assert!(conforms(schema.as_value(), schema.as_value(), &r)); + assert_eq!(s.doc.to_json(), before); + } +} diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs index c73c67067..c3394ec9e 100644 --- a/crates/engine/src/schema/types.rs +++ b/crates/engine/src/schema/types.rs @@ -8,8 +8,8 @@ use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; use serde::de::Error as _; use serde::{Deserialize, Deserializer}; use serde_json::{Value, json}; -use solidcraft_doc::{Expr, Operation, ThinSide}; -use solidcraft_geom::{Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; +use solidcraft_doc::{Expr, Operation, ThinSide, Touching}; use super::check::{keyed, whole}; use crate::params; @@ -268,6 +268,40 @@ impl JsonSchema for AxisDir { } } +/// A camera, as the view commands read it (`cmd::view_navigation::camera_form`): the render +/// `Camera`, with finite fields, a positive distance and a field of view in [0, π), and the +/// handlers' message, "invalid camera", for anything else (#10898). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CameraParam(pub solidcraft_render::Camera); + +impl<'de> Deserialize<'de> for CameraParam { + fn deserialize>(d: D) -> Result { + crate::cmd::camera_form(&Value::deserialize(d)?).map(CameraParam).ok_or_else(|| D::Error::custom(whole("invalid camera"))) + } +} + +impl JsonSchema for CameraParam { + fn schema_name() -> Cow<'static, str> { + "Camera".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A camera orbiting a target point, as the view commands give it back. Angles are in radians, measured in the frame of the up axis.", + "type": "object", + "properties": { + "target": {"description": "The point the camera looks at, in mm: [x, y, z].", "type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + "yaw": {"description": "Turn about the up axis; 0 looks along +Y, from the front.", "type": "number"}, + "pitch": {"description": "Elevation above the ground plane, from -π/2 (looking up) to π/2 (looking down).", "type": "number"}, + "roll": {"description": "Turn about the viewing direction; 0 keeps the up axis upright. Default: 0.", "type": "number", "default": 0.0}, + "distance": {"description": "From the target to the eye, in mm.", "type": "number", "exclusiveMinimum": 0}, + "fov": {"description": "Vertical field of view; 0 is orthographic.", "type": "number", "minimum": 0, "exclusiveMaximum": std::f64::consts::PI}, + "up": {"description": "The world's up axis. Default: z.", "enum": ["z", "y"], "default": "z"} + }, + "required": ["target", "yaw", "pitch", "distance", "fov"] + }) + } +} + /// A sketch point in mm: `[x, y]` or `{x, y}` of finite numbers (read by `params::vec2`). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Point2(pub Vec2); @@ -430,6 +464,66 @@ fn enum_schema(values: &[&str], description: &str) -> Schema { json_schema!({"description": description, "type": "string", "enum": values}) } +/// A keyword a handler reads with `str_` and lowercases, refusing any other word with `unknown +/// `` ()`; the lowercased word is kept for the handler. +macro_rules! keyword_param { + ($(#[$doc:meta])* $name:ident, $what:literal, $values:expr, $expected:literal, $description:literal) => { + $(#[$doc])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name(pub String); + + impl<'de> Deserialize<'de> for $name { + fn deserialize>(d: D) -> Result { + let ok = |s: &str| $values.contains(&s.to_ascii_lowercase().as_str()); + let unknown = |s: &str| whole(format!(concat!("unknown ", $what, " `{}` (", $expected, ")"), s.to_ascii_lowercase())); + string_matching(d, ok, $expected, unknown).map(|s| $name(s.to_ascii_lowercase())) + } + } + + impl JsonSchema for $name { + fn schema_name() -> Cow<'static, str> { + stringify!($name).into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + enum_schema($values, $description) + } + } + }; +} + +keyword_param!( + /// `solid.fillet`'s `type`. + FilletTypeParam, + "fillet type", + &["constant", "rolling_ball", "chord", "chord_length", "curvature", "g2", "variable", "spline"], + "constant, chord, variable, spline or curvature", + "The round's section: constant (the default; rolling_ball is an alias), chord (`radius` is the width across; alias chord_length), curvature (alias g2: curvature-continuous between planar faces along straight edges, `radius` the equivalent circular setback), variable (`radius` at the end nearest `start`, `radius2` at the other) or spline (the radius a clamped B-spline from `start`: `radius`, then `radii`, over `knots`). Matching ignores case." +); +keyword_param!( + /// `solid.fillet`'s `fit`. + FilletFitParam, + "fit", + &["exact", "reduce", "taper"], + "exact, reduce or taper", + "What a radius too large for the geometry around the edges does: exact (the default) refuses it naming the largest that fits, reduce reduces it where it doesn't fit, taper follows the room along straight edges between planar faces. reduce and taper take type: constant. Matching ignores case." +); +keyword_param!( + /// `solid.fillet`'s `corner`. + FilletCornerParam, + "corner", + &["rolling", "g2"], + "rolling or g2", + "What fills a corner where three rounded edges meet: rolling (the default), the rolling ball's sphere, or g2, a set-back patch meeting the rounds to the second order (type: constant, fit: exact only). Matching ignores case." +); +keyword_param!( + /// `solid.fillet`'s `turn`. + FilletTurnParam, + "turn", + &["mitre", "swept"], + "mitre or swept", + "How two rounds turn round a sharp, straight, convex side edge square to both on a plane (the rounds along a boss's base, at its upright edges): mitre (the default) runs them on to meet in a mitre; swept ends them at the side edge and fills the corner with their section revolved about it, a torus. swept takes type: constant, corner: rolling, no setbacks and fit: exact or reduce, and is refused with the reason where the rounds are unequal or the side edge is concave, curved or tangent. Matching ignores case." +); + /// How a feature combines with existing bodies, as `features::operation` reads it. #[derive(Clone, Debug, PartialEq)] pub struct OperationParam(pub Operation); @@ -453,6 +547,34 @@ impl JsonSchema for OperationParam { } } +/// What a join makes of pieces that share no face, as `Touching::parse` reads it. +#[derive(Clone, Debug, PartialEq)] +pub struct TouchingParam(pub Touching); + +/// The feature commands' message for a `touching` they don't know. +const TOUCHING_MESSAGE: &str = "`touching` must be separate or one_body"; + +impl<'de> Deserialize<'de> for TouchingParam { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Touching::parse(&s).map(TouchingParam).ok_or_else(|| D::Error::custom(whole(TOUCHING_MESSAGE))), + _ => Err(D::Error::custom(whole(TOUCHING_MESSAGE))), + } + } +} + +impl JsonSchema for TouchingParam { + fn schema_name() -> Cow<'static, str> { + "Touching".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + enum_schema( + &["separate", "one_body"], + "What a join makes of pieces that share no face: separate (the default) makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body.", + ) + } +} + /// Extrude's operation: the above or `auto` (matched with `eq_ignore_ascii_case`, as the /// handler does). #[derive(Clone, Debug, PartialEq)] @@ -776,8 +898,8 @@ macro_rules! pick_list { pick_list!( /// The `faces` of `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face` and - /// `face.delete`, as `features::face_points` reads them. (Extrude's `faces` is a - /// [`FacesParam`].) + /// `face.delete`, as `features::face_points` reads them; `solid.shell` also takes an empty + /// list (a closed hollow body). (Extrude's `faces` is a [`FacesParam`].) FaceRefs, FaceRef, "`faces` must be a list of points or face names", diff --git a/crates/engine/src/schema/ui_prefs.rs b/crates/engine/src/schema/ui_prefs.rs new file mode 100644 index 000000000..c992dd855 --- /dev/null +++ b/crates/engine/src/schema/ui_prefs.rs @@ -0,0 +1,89 @@ +//! Theme-option contracts for the UI-owned `ui.prefs` control method. +//! Other preferences remain owned and validated by the UI preference table. + +use std::collections::BTreeMap; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum ThemeOptionValue { + Bool(bool), + Choice(String), + Num(f32), +} + +/// Null resets one option; an empty inner map resets that theme. +pub type ThemeOptionsUpdate = BTreeMap>>; + +#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] +pub struct PrefsParams { + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub theme_options: ThemeOptionsUpdate, + #[serde(flatten)] + pub settings: BTreeMap, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +pub struct ThemeChoice { + pub id: String, + pub label: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum ThemeOptionKind { + Bool { default: bool }, + Choice { default: String, values: Vec }, + Range { default: f32, min: f32, max: f32, step: f32, unit: Option }, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +pub struct ThemeOptionDef { + pub id: String, + #[serde(flatten)] + pub kind: ThemeOptionKind, + pub label: String, + pub help: String, + pub parent: Option, + pub advanced: bool, + pub section: Option, + pub standard: bool, + pub available: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ThemeOptionNoticeKind { + UnknownOption, + WrongType, + UnknownChoice, + NonFinite, + OutOfRange, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +pub struct ThemeOptionNotice { + pub id: String, + pub kind: ThemeOptionNoticeKind, +} + +#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] +pub struct ThemeOptionsReply { + pub theme_option_defs: Vec, + pub theme_option_values: BTreeMap, + pub theme_option_notices: Vec, +} + +/// Complete control reply: other preferences and dialog state share the outer object. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct PrefsReply { + #[serde(flatten)] + pub options: ThemeOptionsReply, + #[serde(flatten)] + pub settings: BTreeMap, +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index bc165ff77..1f61739dd 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -2,10 +2,6 @@ # (coverage_tests.rs). This list only shrinks: when you give a command its contract and output # type, remove its line. Never add one: a new command comes with both schemas. Sorted, one id # per line. -appearance.assign -appearance.library -appearance.list -assembly.bom body.rename browser.collapse_all browser.expand_all @@ -43,14 +39,10 @@ component.replace_with_link component.revert_position component.unlock component.update_links -config.activate config.column config.configure -config.preview config.row config.rule -config.rules -config.table contact.check contact.create contact.disable_all @@ -58,23 +50,11 @@ contact.edit contact.enable_all contact.enable_sets contact.list -diagnostics.crash_report -diagnostics.crash_reports -diagnostics.crash_reports.clear -diagnostics.crash_test doc.open doc.recover doc.recovery_discard doc.recovery_list document.inspect -document.metadata -document.metadata.remove -document.metadata.set -document.units -edit.checkpoint -edit.redo -edit.restore_checkpoint -edit.undo engine.commands explode.create explode.delete @@ -95,29 +75,15 @@ frame.member frame.profile.insert frame.profile.list frame.profile.properties -inspect.accessibility -inspect.center_of_mass -inspect.clearance -inspect.compare -inspect.continuity -inspect.curvature_comb -inspect.curvature_map -inspect.draft -inspect.environment_map inspect.interference -inspect.isocurve inspect.measure -inspect.minimum_radius inspect.parameter_sweep -inspect.section inspect.silhouette -inspect.zebra joint.as_built joint.cam joint.create joint.delete joint.drive -joint.edit joint.gear joint.inspect joint.limits @@ -130,21 +96,13 @@ joint.rigid_group joint.screw joint.solve joint.sweep -library.apply -library.export -library.inspect material.assign material.create material.delete material.edit material.inspect material.list -material.properties.directional -material.properties.validate mesh.convert -model.edges -model.faces -model.threads motion.delete motion.export motion.export_animation @@ -222,9 +180,6 @@ render.settings.set render.shot.duplicate render.shot.remove render.shot.rename -render.stage.backdrop -render.stage.clear -render.stage.ground render.start render.status select.clear @@ -233,9 +188,7 @@ selection.delete sheet.export_bend_table sheet.export_dxf sheet.flat_pattern -sheet.manage_rules sheet.path_flange -sheet.rules sketch.arc.center_point sketch.arc.tangent sketch.arc.three_point @@ -245,7 +198,6 @@ sketch.auto_project sketch.blend_curve sketch.break sketch.break_link -sketch.cancel sketch.centerline sketch.chain sketch.chamfer.distance_angle @@ -281,13 +233,11 @@ sketch.dimension_text sketch.drag sketch.drag_end sketch.draw.dimensioned -sketch.edit sketch.edit_text sketch.ellipse sketch.export_dxf sketch.extend sketch.fillet -sketch.finish sketch.finish_auto_constrain sketch.fit_curves_to_section sketch.glyphs @@ -302,8 +252,6 @@ sketch.isoparametric_curve sketch.line sketch.line.midpoint sketch.line3d -sketch.loose_ends -sketch.loose_ends.tie sketch.mirror sketch.move sketch.move3d @@ -350,7 +298,6 @@ solid.coil solid.combine solid.draft solid.emboss -solid.fillet solid.hole solid.loft solid.mirror @@ -371,12 +318,10 @@ solid.sweep solid.thread solid.web surface.blend -surface.boundary surface.extend surface.extrude surface.fair surface.loft -surface.match surface.offset surface.patch surface.reverse_normal @@ -411,19 +356,11 @@ timeline.suppress timeline.ungroup view.ambient_occlusion view.apply -view.back -view.bottom view.delete -view.front view.graphics_preset view.history_layout -view.isometric view.layout -view.left view.list view.navigate -view.normal_to view.rename -view.right view.save -view.top diff --git a/crates/engine/src/schema/view_navigation.rs b/crates/engine/src/schema/view_navigation.rs index 978e96760..599426030 100644 --- a/crates/engine/src/schema/view_navigation.rs +++ b/crates/engine/src/schema/view_navigation.rs @@ -4,6 +4,8 @@ use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; use std::borrow::Cow; +use super::types::{CameraParam, present}; + #[derive(Debug, Deserialize, Serialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct RenderDock { @@ -74,6 +76,44 @@ pub struct AngleReadoutResult { pub param_warnings: Vec, } +/// Turn the view to the command's standard orientation (front, back, left, right, top, bottom +/// or isometric), as the view cube does, keeping the camera's target, distance, projection and +/// up axis. Display only: the design isn't changed and nothing is added to undo. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct StandardViewParams { + /// The camera to turn. Default: the session's camera, or the home view when there is none. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "CameraParam")] + pub camera: Option, +} + +/// Look straight at the first selected planar face or plane, centred on the point it was picked +/// at (a plane: its origin); asked again while already facing it, look from the other side. +/// Keeps the camera's distance, projection and up axis. Needs a planar face or plane in the +/// selection. Display only: the design isn't changed and nothing is added to undo. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct NormalToParams { + /// The camera to turn. Default: the session's camera, or the home view when there is none. + /// Its yaw and roll must also be within ±1e6 and its pitch within ±π/2. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "CameraParam")] + pub camera: Option, +} + +/// What the standard views and `view.normal_to` return: the camera after the turn, which the +/// session keeps as its view. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CameraReply { + /// The camera now. + #[schemars(with = "CameraParam")] + pub camera: solidcraft_render::Camera, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + /// `view.next_tab` and `view.previous_tab` take no parameters (#8565). #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] diff --git a/crates/engine/src/schema/view_navigation_tests.rs b/crates/engine/src/schema/view_navigation_tests.rs index 7ef13a61c..63de8d4bf 100644 --- a/crates/engine/src/schema/view_navigation_tests.rs +++ b/crates/engine/src/schema/view_navigation_tests.rs @@ -1,13 +1,184 @@ use serde_json::{Value, json}; -use super::{AngleReadoutParams, TabStep, TabStepParams}; +use super::{AngleReadoutParams, CameraReply, NormalToParams, StandardViewParams, TabStep, TabStepParams}; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::types::CameraParam; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["enabled"]); + assert_keys(input_schema_for::(), &["camera"]); + assert_keys(input_schema_for::(), &["camera"]); +} + +const STANDARD_VIEWS: [&str; 7] = ["view.front", "view.back", "view.left", "view.right", "view.top", "view.bottom", "view.isometric"]; + +/// A camera the view commands take, with `change` merged into it. +fn camera(change: Value) -> Value { + let mut c = json!({"target": [1, 2, 3], "yaw": 0.3, "pitch": 0.4, "roll": 0, "distance": 150, "fov": 0, "up": "z"}); + if let (Some(c), Some(change)) = (c.as_object_mut(), change.as_object()) { + c.extend(change.clone()); + } + c +} + +/// #10898: the camera type takes what the view commands' own reader takes, and its schema says +/// the same. +#[test] +fn the_camera_type_matches_the_view_commands_reader() { + let schema = input_schema_for::(); + let schema = schema.as_value(); + let without = |key: &str| { + let mut c = camera(json!({})); + c.as_object_mut().map(|o| o.remove(key)); + c + }; + for v in [ + camera(json!({})), + camera(json!({"up": "y", "fov": 0.8})), + camera(json!({"pitch": -1.5, "yaw": 12.0, "roll": -3.0})), + camera(json!({"target": [0.5, -2, 1e6]})), + without("roll"), + without("up"), + camera(json!({"distance": 0})), + camera(json!({"distance": -5})), + camera(json!({"fov": std::f64::consts::PI})), + camera(json!({"fov": -0.1})), + camera(json!({"up": "x"})), + camera(json!({"up": "Z"})), + camera(json!({"target": [1, 2]})), + camera(json!({"target": {"x": 1, "y": 2, "z": 3}})), + camera(json!({"yaw": "0.3"})), + without("target"), + without("distance"), + without("fov"), + json!(null), + json!(5), + json!("front"), + json!([1, 2, 3]), + ] { + let read = crate::cmd::camera_form(&v).is_some(); + assert_eq!(serde_json::from_value::(v.clone()).is_ok(), read, "{v}"); + assert_eq!(conforms(schema, schema, &v), read, "{v}"); + } +} + +#[test] +fn standard_views_keep_todays_errors() { + let mut cases = Vec::new(); + for id in STANDARD_VIEWS { + for c in [json!(5), json!(null), json!("top"), camera(json!({"distance": 0})), camera(json!({"fov": 4})), camera(json!({"up": "x"}))] { + cases.push((id, json!({ "camera": c }))); + } + } + assert_strict_keeps_todays_errors(&cases); +} + +/// A box with its top face selected, for Normal To. +fn top_face_selected(check: ParamCheck) -> Session { + let mut s = Session { param_check: check, ..Session::default() }; + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap_or_else(|e| panic!("{e}")); + s.execute("select.set", &json!({"items": [{"type": "face", "body": "Body1", "index": 1, "point": [20, 15, 20]}]})) + .unwrap_or_else(|e| panic!("{e}")); + s +} + +/// #10898: every standard view and Normal To reply with the camera their output schema +/// describes, with or without a camera given, and refuse in strict what they refuse anyway. +#[test] +fn camera_commands_reply_with_the_camera_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let check = |id: &str, r: &Value, warned: bool| { + assert!(conforms(schema, schema, r), "{id}: {r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{id}: {r}"); + assert!(crate::cmd::camera_form(&r["camera"]).is_some(), "{id}: the reply's camera is one the commands take: {r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + for id in STANDARD_VIEWS { + for p in [json!({}), json!({"camera": camera(json!({}))}), json!({"camera": camera(json!({"up": "y", "fov": 0.6}))})] { + let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + check(id, &r, false); + if let Some(up) = p["camera"].get("up") { + assert_eq!(&r["camera"]["up"], up, "{id} keeps the up axis"); + } + } + let r = s.execute(id, &json!({"camera": camera(json!({})), "zoom": 2})).unwrap_or_else(|e| panic!("{id}: {e}")); + check(id, &r, true); + } + let mut s = top_face_selected(ParamCheck::Warn); + for p in [json!({}), json!({"camera": camera(json!({}))})] { + let r = s.execute("view.normal_to", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + check("view.normal_to", &r, false); + } + let r = s.execute("view.normal_to", &json!({"zoom": 2})).unwrap_or_else(|e| panic!("{e}")); + check("view.normal_to", &r, true); + // Strict refuses what the handler refuses, with its message: a camera of the wrong form, + // and (the handler's own check) one whose angles are out of Normal To's bounds. + for c in [json!(5), json!(null), camera(json!({"distance": 0})), camera(json!({"yaw": 2e6})), camera(json!({"pitch": 2.0}))] { + let p = json!({ "camera": c }); + let off = top_face_selected(ParamCheck::Off).execute("view.normal_to", &p).err().map(|e| e.to_string()); + assert!(off.as_deref().is_some_and(|e| e.contains("invalid camera")), "{p}: {off:?}"); + assert_eq!(top_face_selected(ParamCheck::Strict).execute("view.normal_to", &p).err().map(|e| e.to_string()), off, "{p}"); + } +} + +#[test] +fn status_details_has_checked_pure_query_and_current_typed_diagnostics() { + let schema = output_schema_for::(); + let root = schema.as_value(); + let mut s = Session::default(); + let spec = crate::find_command("view.status_details").unwrap(); + assert!(!spec.undoable && !spec.reads_model); + assert!(spec.contract.is_some() && spec.output.is_some()); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + s.execute("inspect.continuity", &json!({"edges":[[5,0,0]],"samples":5})).unwrap(); + for mode in [ParamCheck::Off, ParamCheck::Warn, ParamCheck::Strict] { + s.param_check = mode; + let before = (s.revision, s.doc.to_json(), s.undo.len(), s.continuity.clone()); + for params in [json!({}), Value::Null] { + let reply = s.execute("view.status_details", ¶ms).unwrap(); + assert!(conforms(root, root, &reply), "{reply} does not match {root}"); + assert_eq!(reply["continuity"][0]["samples"], 5); + assert_eq!(reply["continuity"][0]["current"], true); + assert_eq!(reply["continuity"][0]["verdict"], "sharp"); + assert_eq!(reply["items"][0]["source"]["command"], "inspect.continuity"); + assert_eq!(reply["items"][0]["has_details"], true); + } + for params in [json!({"clear":true}), json!([]), json!(false)] { + assert!(s.execute("view.status_details", ¶ms).is_err()); + } + assert_eq!((s.revision, s.doc.to_json(), s.undo.len(), s.continuity.clone()), before); + } +} + +#[test] +fn surface_and_section_contracts_match_successful_existing_reply_shapes() { + let mut s = Session { param_check: ParamCheck::Strict, ..Default::default() }; + s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + for (command, params) in [ + ("inspect.zebra", json!({"stripes":14.5})), + ("inspect.draft", json!({"pull":[-2,3,-4],"angle":12.75})), + ("inspect.environment_map", json!({})), + ("inspect.accessibility", json!({"direction":[0,0,-1]})), + ("inspect.curvature_map", json!({"radius":25.4})), + ("inspect.section", json!({"plane":{"origin":[4,5,6],"normal":[-1,2,-3]},"offset":"-2 mm","flip":true,"hatch":false})), + ( + "inspect.continuity", + json!({"edges":[[5,0,0]],"samples":5,"gap_tolerance_mm":0.002,"angle_tolerance_deg":2,"curvature_tolerance_per_mm":0.03}), + ), + ] { + let description = s.execute("engine.describe", &json!({"command":command})).unwrap(); + assert_eq!(description["input"]["additionalProperties"], false); + for params in [params, json!({"clear":true})] { + let reply = s.execute(command, ¶ms).unwrap(); + let root = &description["output"]; + assert!(conforms(root, root, &reply), "{command}: {reply} does not match {root}"); + } + assert!(s.execute(command, &json!({"unknown_setting":true})).is_err(), "checked registration for {command}"); + } } #[test] diff --git a/crates/engine/src/sketch_edit_removed_tests.rs b/crates/engine/src/sketch_edit_removed_tests.rs index 297331056..23293bb54 100644 --- a/crates/engine/src/sketch_edit_removed_tests.rs +++ b/crates/engine/src/sketch_edit_removed_tests.rs @@ -3,7 +3,8 @@ //! (#1167): the history is rolled back, the view of it is not. A body the sketch is built on stays. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_sketch::LinkSource; use crate::Session; @@ -110,7 +111,7 @@ fn a_body_the_sketch_sits_on_stays_shown() { let mut s = Session::default(); block(&mut s, "Gone", 0.0); let top = { - let world = s.world_state(); + let world = s.world_state().unwrap(); let face = world .body("Gone") .and_then(|body| body.body.faces(0.01).ok()) @@ -143,7 +144,7 @@ fn every_placement_of_a_component_body_is_left_out() { run(&mut s, "occurrence.copy", json!({"component": component, "translate": [50, 0, 0]})); run(&mut s, "timeline.roll_to", json!({"feature": "Edited"})); run(&mut s, "sketch.edit", json!({"sketch": "Edited"})); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), 2, "one body, placed twice"); for body in &world.bodies { assert!(!s.body_visible(&body.name), "{} is deleted later", body.name); diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 04e806016..b553d13e0 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -7,7 +7,9 @@ //! as the viewport shows the model. use serde::Serialize; -use solidcraft_geom::{UnitVec3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::UnitVec3; +use solidcraft_geom::prelude::*; use crate::cmd::Shape; use crate::{Sel, Session}; @@ -95,7 +97,7 @@ fn edge_points(s: &Session, sel: &Sel) -> Vec<(Vec3, SnapKind)> { /// same circle, in order: the whole arc when the kernel split it. fn whole_arc(s: &Session, sel: &Sel, center: Vec3, axis: UnitVec3, radius: f64) -> Option> { let Sel::Edge { body, index, .. } = sel else { return None }; - let st = s.world_state(); + let st = s.world_state().ok()?; let m = st.body(body)?.mesh(); let tol = (radius * 1e-6).max(1e-9); let on = |e: &Vec| e.iter().all(|p| (p.dist(center) - radius).abs() <= tol * 10.0 && (*p - center).dot(axis).abs() <= tol * 10.0); @@ -157,7 +159,7 @@ fn along(pts: &[Vec3], f: f64) -> Option { /// ends on the axis; a sphere or torus its centre. fn face_points(s: &Session, sel: &Sel) -> Vec<(Vec3, SnapKind)> { let Sel::Face { body, index, .. } = sel else { return Vec::new() }; - let st = s.world_state(); + let Ok(st) = s.world_state() else { return Vec::new() }; let Some(b) = st.body(body) else { return Vec::new() }; let Some((shape, _, tris)) = crate::cmd::shape_of(s, sel) else { return Vec::new() }; let verts: Vec = tris.iter().flat_map(|t| t.iter().copied()).collect(); diff --git a/crates/engine/src/snap_tests.rs b/crates/engine/src/snap_tests.rs index 50e31a42d..249e8f5d4 100644 --- a/crates/engine/src/snap_tests.rs +++ b/crates/engine/src/snap_tests.rs @@ -1,10 +1,11 @@ //! Snap points (#5881): the centres, middles and ends edges and faces offer. Every expected //! point is worked out by hand from the part's dimensions. +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_1_SQRT_2, PI}; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::snap::{SnapKind, SnapPoint, snap_points}; use crate::{Sel, Session}; diff --git a/crates/engine/src/status_details.rs b/crates/engine/src/status_details.rs new file mode 100644 index 000000000..d5d6267ed --- /dev/null +++ b/crates/engine/src/status_details.rs @@ -0,0 +1,93 @@ +//! Retained diagnostics for the existing Continuity effect. Queries never evaluate geometry. +use schemars::JsonSchema; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ContinuityVerdict { + Smooth, + CurvatureJump, + Sharp, + Gap, +} +impl From for ContinuityVerdict { + fn from(value: crate::kernel::SeamVerdict) -> Self { + match value { + crate::kernel::SeamVerdict::Smooth => Self::Smooth, + crate::kernel::SeamVerdict::CurvatureJump => Self::CurvatureJump, + crate::kernel::SeamVerdict::Sharp => Self::Sharp, + crate::kernel::SeamVerdict::Gap => Self::Gap, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, JsonSchema)] +pub struct ContinuityDetail { + pub body: String, + pub edge: usize, + pub samples: usize, + pub gap_tolerance_mm: f64, + pub angle_tolerance_deg: f64, + pub curvature_tolerance_per_mm: f64, + pub gap_mm: f64, + pub normal_angle_deg: f64, + pub curvature_jump_per_mm: f64, + pub length_mm: f64, + pub verdict: ContinuityVerdict, + pub gap_at: [f64; 3], + pub gap_fraction: f64, + pub normal_angle_at: [f64; 3], + pub normal_angle_fraction: f64, + pub curvature_jump_at: [f64; 3], + pub curvature_jump_fraction: f64, + pub skipped: usize, + pub unmeasured: usize, + /// True only while the exact evaluated geometry and occurrence placement still exist. + pub current: bool, + #[serde(skip)] + pub(crate) geometry_key: Option, + #[serde(skip)] + pub(crate) feature: u64, +} + +#[derive(Serialize, JsonSchema)] +pub struct StatusDetailItem { + pub source: crate::status_items::StatusItem, + pub has_details: bool, +} + +#[derive(Serialize, JsonSchema)] +pub struct StatusDetails { + pub document_id: String, + pub items: Vec, + pub continuity: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +impl crate::Session { + /// Cheap current-state lookup. A pending model evaluation or cold/stale assembly world + /// is conservatively unavailable, even if the old state's geometry keys still match. + pub fn continuity_details(&self) -> Vec { + let world = if self.model.is_stale() { None } else { self.cached_world_state() }; + self.continuity + .iter() + .map(|seam| { + let mut detail = seam.details.clone(); + detail.verdict = seam.verdict.into(); + detail.current = world.as_ref().and_then(|world| world.body(&seam.body)).is_some_and(|body| { + detail.geometry_key.is_some() && body.geometry_key() == detail.geometry_key && body.feature == detail.feature + }); + detail + }) + .collect() + } + + /// Validate again at activation; a button's earlier descriptor is never authority. + pub fn continuity_target_points(&self, body: &str, edge: usize) -> Option<&[solidcore_record::Vec3]> { + if !self.continuity_details().iter().any(|row| row.body == body && row.edge == edge && row.current) { + return None; + } + self.continuity.iter().find(|seam| seam.body == body && seam.edge == edge).map(|seam| seam.points.as_slice()) + } +} diff --git a/crates/engine/src/status_items.rs b/crates/engine/src/status_items.rs index a132303ec..d6e333edb 100644 --- a/crates/engine/src/status_items.rs +++ b/crates/engine/src/status_items.rs @@ -90,6 +90,14 @@ pub struct StatusItems { pub items: Vec, } +impl StatusItem { + /// Capability independent of a window's presentation preferences. `has_key` retains + /// the existing read-only legend contract; live details also include settings/findings. + pub fn has_details(&self) -> bool { + !matches!(self.setting, StatusSetting::Environment) + } +} + impl Session { /// Whether shading and Continuity share one slot (the default). This is session /// configuration, never design data; SDK clients may choose the legacy independent policy. @@ -136,7 +144,7 @@ impl Session { self.status_slot(id, active); } if self.status_items() != before { - self.revision += 1; + self.refresh_display(); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 977dec368..1b559f1d6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -26,6 +26,24 @@ impl Drop for Folder { mod mesh_convert; +/// Counts the copies `Session::doc_mut` makes of a shared document. +pub(crate) mod doc_copies { + use std::cell::Cell; + + thread_local! { + static COUNT: Cell = const { Cell::new(0) }; + } + + pub fn record() { + COUNT.with(|c| c.set(c.get() + 1)); + } + + /// The count since the last call. + pub fn take() -> usize { + COUNT.with(|c| c.replace(0)) + } +} + fn run(s: &mut Session, id: &str, p: Value) -> Value { match s.execute(id, &p) { Ok(v) => v, @@ -109,6 +127,47 @@ fn fillet_as_wide_as_a_face_rounds_it_off() { assert!(s.execute("solid.fillet", &json!({"edges": [[21, 0, 10]], "radius": 3.5})).is_err()); } +/// The owner's ruling of 2026-10-30: two edges of a 20 mm box rounded r2 in one fillet (they +/// meet in a mitre at the corner (20, 0, 20), the upright edge there sharp), then the upright edge +/// r3 in a second fillet, whose tangent chain takes the mitre's seam with it. The corner is the +/// one solidcore 8ddce9016 builds for three rounds of different radii there: one patch, 10 +/// faces, 7928.743041456134 mm³ (the fork's setback corner, 15 faces and 7928.142563938, waits +/// for solidcore#2310). The r2 rounds keep their names, and the r3 round and the corner's patch +/// are the second fillet's. +#[test] +fn a_later_round_at_a_mitred_corner_is_blended_with_the_rounds_there() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Box"})); + let first = run(&mut s, "solid.fillet", json!({"edges": [[20, 10, 20], [10, 0, 20]], "radius": 2}))["feature"].as_u64().unwrap(); + // A point halfway along each r2 round, at 45° between its faces. + let k = 2.0 - 2.0_f64.sqrt(); + let rounds = [solidcore_record::Vec3::new(20.0 - k, 10.0, 20.0 - k), solidcore_record::Vec3::new(10.0, k, 20.0 - k)]; + let named = |s: &mut Session, at: solidcore_record::Vec3| { + let st = s.model.state(); + let (d, index) = solidcraft_doc::appearance::nearest_face(st.body("Box").unwrap(), at).unwrap(); + // Found on the display mesh, whose facets lie within its chord of the faces. + assert!(d < 0.05, "{at:?} is {d} off the nearest face"); + let faces = run(s, "model.faces", json!({"body": "Box"}))["faces"].as_array().cloned().unwrap_or_default(); + faces.iter().find(|f| f["index"].as_u64() == Some(index as u64)).and_then(|f| f["name"].as_str()).unwrap_or_default().to_string() + }; + let before: Vec = rounds.iter().map(|p| named(&mut s, *p)).collect(); + assert!(before.iter().all(|n| n.starts_with(&format!("F{first}:blend:"))), "{before:?}"); + let second = run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 3}))["feature"].as_u64().unwrap(); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let v = volume(&mut s); + assert!((v - 7928.743041456134).abs() < 1e-6, "{v}"); + let faces = run(&mut s, "model.faces", json!({"body": "Box"}))["faces"].as_array().cloned().unwrap_or_default(); + assert_eq!(faces.len(), 10); + let after: Vec = rounds.iter().map(|p| named(&mut s, *p)).collect(); + assert_eq!(after, before); + // The r3 round (halfway up, at 45°) and the corner's patches: the faces the second fillet made. + let k3 = 3.0 - 4.5_f64.sqrt(); + assert!(named(&mut s, solidcore_record::Vec3::new(20.0 - k3, k3, 10.0)).starts_with(&format!("F{second}:blend:"))); + let made = faces.iter().filter(|f| f["name"].as_str().is_some_and(|n| n.starts_with(&format!("F{second}:")))).count(); + // the r3 round and the corner's patch + assert_eq!(made, 2, "{faces:?}"); +} + #[test] fn join_extrude_from_a_chamfered_top_face() { let mut s = Session::default(); @@ -153,10 +212,16 @@ fn join_extrude_from_a_chamfered_top_face() { assert!((solved.plane.origin.z - height).abs() < 1e-8); assert!(solved.sketch.links.iter().all(|link| link.auto_face && !link.lost)); let body = &state.bodies[0]; - assert!(body.body.contains(solidcraft_geom::Vec3::new(0., 0., height + 4.))); - assert!(!body.body.contains(solidcraft_geom::Vec3::new(0., 0., height + 6.))); - assert!(body.body.contains(solidcraft_geom::Vec3::new(10. - bevel - 0.5, 0., height + 4.))); - assert!(!body.body.contains(solidcraft_geom::Vec3::new(10. - bevel + 0.5, 0., height + 4.))); + assert_eq!(body.body.classify_point(solidcore_record::Vec3::new(0., 0., height + 4.)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.body.classify_point(solidcore_record::Vec3::new(0., 0., height + 6.)).unwrap(), solidcraft_kernel::PointClass::Outside); + assert_eq!( + body.body.classify_point(solidcore_record::Vec3::new(10. - bevel - 0.5, 0., height + 4.)).unwrap(), + solidcraft_kernel::PointClass::Inside + ); + assert_eq!( + body.body.classify_point(solidcore_record::Vec3::new(10. - bevel + 0.5, 0., height + 4.)).unwrap(), + solidcraft_kernel::PointClass::Outside + ); } } } @@ -223,18 +288,33 @@ fn join_merges_into_the_body_it_meets() { assert!(rel(volume(&mut s), 2064.0) < 1e-6); } -/// A join that meets no body still joins the first body, as a separate lump. +/// A join that meets no body still joins the first body, as a separate lump, and says nothing: +/// pieces that touch nothing stay one body. #[test] fn join_meeting_nothing_keeps_the_first_body() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); - run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [40, 0, 0], "operation": "join"})); + let r = run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [40, 0, 0], "operation": "join"})); + assert!(r.get("notice").is_none(), "{r}"); let st = s.model.state(); assert_eq!(st.bodies.len(), 1); assert_eq!(st.bodies[0].body.lumps().unwrap().len(), 2); assert!(rel(volume(&mut s), 1064.0) < 1e-6); } +/// A join of a box touching the first only along an edge keeps it a body of its own and says +/// so, with the edit that makes them one body. +#[test] +fn join_touching_along_an_edge_keeps_a_separate_body() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + let r = run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [10, 10, 0], "operation": "join"})); + assert_eq!(r["notice"]["contact"], "along_edge", "{r}"); + assert_eq!(r["notice"]["message"], "These bodies only touch along an edge, so they were kept as separate bodies.", "{r}"); + assert_eq!(r["notice"]["action"]["params"]["set"], json!({"touching": "one_body"}), "{r}"); + assert_eq!(s.model.state().bodies.len(), 2); +} + /// A 1 mm floor extruded into a through hole, from the sketch the plate was extruded from: the /// disc's wall lies on the hole's and its foot in the plate's bottom face. A wedge extruded /// sideways on top keeps the plate from being a prism along Z (the 2D route would take it @@ -343,15 +423,14 @@ fn join_of_a_lobed_disc_pattern_is_not_refused() { assert!(rel(got, want) < 1e-3, "{got} vs {want}"); } +mod barrel_join; mod blend_fit; -mod boolean_diagnostics; mod component_frames; mod curved_seam_round; mod flush_join_loft; mod gltf_import; mod import_component; mod large_step_import; -mod loft_cut; mod loft_ring; mod loft_spacing; mod mirror_placed; @@ -364,7 +443,6 @@ mod pleat_join; mod primitive_points; mod rim_cut; mod robustness; -mod robustness_goldens; mod rounded_loft_face; mod sphere_lens; mod spiral_join; @@ -434,6 +512,111 @@ fn fillet_the_edges_between_two_overlapping_cylinders() { assert!(rel(v, expect) < 2e-4, "{v} vs {expect}"); } +/// A bar 40 long, 16 wide and 10 tall whose far end is a half disc of radius 8 about (40, 8), +/// with a disc of radius 8 about the same centre sketched on its top (the top's outline +/// projected) and extruded 10 up, joined: the bar's sides run tangent into the cylinder. +/// V0 = 40·16·10 + π·8²·10/2 + π·8²·10. +fn peg(s: &mut Session) -> f64 { + run(s, "sketch.create", json!({"plane": "XY", "name": "Peg"})); + run(s, "sketch.line", json!({"points": [[0, 0], [40, 0]]})); + run(s, "sketch.arc.center_point", json!({"center": [40, 8], "start": [40, 0], "end": [40, 16]})); + run(s, "sketch.line", json!({"points": [[40, 16], [0, 16]]})); + run(s, "sketch.line", json!({"points": [[0, 16], [0, 0]]})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": "Peg", "distance": 10, "body_name": "Peg"})); + run(s, "sketch.create", json!({"plane": {"origin": [0, 0, 10], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Top"})); + run(s, "sketch.project", json!({"refs": [{"face": [2, 8, 10]}]})); + run(s, "sketch.circle.center", json!({"center": [40, 8], "radius": 8})); + run(s, "sketch.finish", json!({})); + run( + s, + "solid.extrude", + json!({"sketch": "Top", "distance": 10, "operation": "join", "targets": ["Peg"], "profiles": [{"point": [40, 8]}], "exact_regions": true}), + ); + 6400.0 + 960.0 * PI +} + +/// Simpson's rule over [a, b] with `n` (even) intervals. +fn simpson(f: impl Fn(f64) -> f64, a: f64, b: f64, n: usize) -> f64 { + let h = (b - a) / n as f64; + let inner: f64 = (1..n).map(|i| if i % 2 == 1 { 4.0 } else { 2.0 } * f(a + h * i as f64)).sum(); + (f(a) + f(b) + inner) * h / 3.0 +} + +/// The material an r2 round of the peg's front top edge (y = 0, z = 10) takes off: the spandrel +/// (height 2 - sqrt(4 - (2 - y)²) above the round at y) from x = `from` to where the cylinder's +/// wall, x = 40 - sqrt(64 - (8 - y)²), takes over (the round runs into the wall there). +fn peg_front_round(from: f64) -> f64 { + let spandrel = |y: f64| 2.0 - (4.0 - (2.0 - y) * (2.0 - y)).max(0.0).sqrt(); + let wall = |y: f64| 40.0 - (64.0 - (8.0 - y) * (8.0 - y)).max(0.0).sqrt(); + simpson(|y| spandrel(y) * (wall(y) - from), 0.0, 2.0, 20_000) +} + +/// The peg's front top edge rounded r2: SMLib's result holds the upper half of the cylinder's +/// wall as a rational spline whose parameter range runs more than a turn round, past the face's +/// trims (half a turn). Taken as a cylinder over the spline's range (past 360°) SMLib refused it +/// on the way back (SM_ERR_INVALID_INPUT), so the round seemed to build and the body could not +/// be measured or changed. It goes back as the cylinder over the face's own range: the body +/// measures, a round of the three edges at the bar's other top corner builds on it, and that +/// wall comes back from SMLib a cylinder of radius 8. +#[test] +fn rounds_on_a_bar_running_tangent_into_a_cylinder() { + let mut s = Session::default(); + let v0 = peg(&mut s); + run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2})); + let (v, expect) = (volume(&mut s), v0 - peg_front_round(0.0)); + assert!(rel(v, expect) < 1e-7, "{v} vs {expect}"); + // The vertical edge, the left top edge and the round's end arc on the left face: each + // spandrel (1 - π/4)·r² along the edge outside the corner cube of side 2, the cube less the + // rolling ball's eighth, 8 - 4π/3. + run(&mut s, "solid.fillet", json!({"edges": [[0, 0, 4], [0, 9, 10], [0, 0.5858, 9.4142]], "radius": 2})); + let strip = (1.0 - PI / 4.0) * 4.0; + let expect = v0 - peg_front_round(2.0) - strip * (8.0 + 14.0) - (8.0 - 4.0 * PI / 3.0); + let v = volume(&mut s); + assert!(rel(v, expect) < 1e-7, "{v} vs {expect}"); + for b in &s.model.state().bodies { + let bad = b.body.validity(); + assert!(bad.is_empty(), "{}: {bad:?}", b.name); + } + // The wall's upper half (x < 40, z in [10, 20], round (40, 8)): every face on the surface + // through (32, 8, 15) is a cylinder of radius 8. + let state = s.model.state(); + let rec = state.bodies[0].body.record(); + let p0 = solidcore_record::Vec3::new(32.0, 8.0, 15.0); + let on: Vec<&solidcore_record::brep::Surface> = rec + .faces + .iter() + .map(|f| &f.surface) + .filter(|s| { + let e = solidcraft_geom::brep::eval::SurfaceEval::new(s).ok(); + e.and_then(|e| e.project(p0, None, 1e-6).and_then(|uv| e.point(uv))).is_some_and(|q| q.dist(p0) < 1e-6) + }) + .collect(); + let kinds: Vec = on.iter().map(|s| format!("{s:?}").chars().take(48).collect()).collect(); + assert!( + !on.is_empty() && on.iter().all(|s| matches!(s, solidcore_record::brep::Surface::Cylinder { radius, .. } if (radius - 8.0).abs() < 1e-9)), + "{kinds:?}" + ); +} + +/// After the peg's front top round, the edge where that round runs into the cylinder's wall: its +/// faces are tangent at its lower end (40, 0, 8), where the round's contact with the front face +/// meets the wall's tangent line with it, and meet at a crease everywhere else. It is no smooth +/// edge (it was refused as one, judged at that end alone); the wall's seam with the front face, +/// tangent all along, still is. +#[test] +fn an_edge_tangent_at_one_end_only_is_not_smooth() { + let mut s = Session::default(); + peg(&mut s); + run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2})); + let fillet = |s: &mut Session, at: [f64; 3]| s.execute("solid.fillet", &json!({"edges": [at], "radius": 1, "tangent_chain": false})); + if let Err(e) = fillet(&mut s, [37.2641, 0.4827, 9.3025]) { + assert!(!e.to_string().contains("is smooth"), "{e}"); + } + let seam = fillet(&mut s, [40.0, 0.0, 4.0]).unwrap_err().to_string(); + assert!(seam.contains("is smooth: its faces meet tangentially"), "{seam}"); +} + /// The top outline of two overlapping cylinders whose concave edges were rounded: the walls of /// the rounds meet the cylinders along the rolling-ball contact lines, straight but not lines. #[test] @@ -634,7 +817,9 @@ fn extrude_of_adjacent_profiles_has_whole_edges() { assert_eq!(below.len(), 2, "{si}"); run(&mut s, "solid.extrude", json!({"sketch": "Holder", "profiles": below, "distance": 23, "body_name": "Holder"})); let topo = run(&mut s, "model.faces", json!({"body": "Holder"})); - assert_eq!(topo["faces"].as_array().unwrap().len(), 5, "a cut-off cylinder: {topo}"); + // The arc side (one face: SMLib keeps a cylinder's arc of more than half a turn whole), the + // chord's flat side and the two ends. + assert_eq!(topo["faces"].as_array().unwrap().len(), 4, "a cut-off cylinder: {topo}"); let lo = run(&mut s, "inspect.measure", json!({"bodies": ["Holder"]}))["bodies"][0]["bbox"]["min"][1].as_f64().unwrap(); run(&mut s, "solid.move", json!({"bodies": ["Holder"], "translate": [0, -5.0 - lo, 0]})); // The handle: r35 on the Y axis with a bevelled end. @@ -745,6 +930,36 @@ pub(crate) fn hostile_values() -> Vec { ] } +/// A copy of `s` as it stands: its design and model (sharing their bodies, as undo does), its +/// undo and redo, its open sketch and the design it was entered from, and its log. +fn copy_with_history(s: &Session) -> Session { + Session { undo: s.undo.clone(), redo: s.redo.clone(), sketch_entry: s.sketch_entry.clone(), log: s.log.clone(), ..s.scratch() } +} + +/// The hostile-parameter test's copy starts where a session built afresh stands: cancelling its +/// sketch and undoing step for step give the same designs, and the copied session is untouched. +#[test] +fn a_copy_with_history_undoes_like_the_session_it_copies() { + let start = |s: &mut Session| { + run(s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(s, "sketch.create", json!({"plane": "XY"})); + run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [5, 5]})); + }; + let mut fresh = Session::default(); + start(&mut fresh); + let mut original = Session::default(); + start(&mut original); + let before = original.doc.clone(); + let mut copy = copy_with_history(&original); + for (command, params) in [("sketch.cancel", json!({})), ("edit.undo", json!({})), ("edit.undo", json!({})), ("edit.redo", json!({}))] { + run(&mut fresh, command, params.clone()); + run(&mut copy, command, params); + assert_eq!(*fresh.doc, *copy.doc, "{command}"); + assert_eq!(fresh.active_sketch, copy.active_sketch, "{command}"); + } + assert!(std::sync::Arc::ptr_eq(&original.doc, &before) && original.active_sketch.is_some(), "the copied session is untouched"); +} + /// Every command, every parameter name it documents, every hostile value: no panic escapes and /// no command panics internally. #[test] @@ -897,16 +1112,27 @@ fn hostile_params_never_panic() { scope.spawn(|| { let mut internal = Vec::new(); while let Some(&id) = ids.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) { + // A model with a sketch, a body and an active sketch, so most commands get far. + // Built once per command and copied for each call: SMLib serialises every + // call behind one lock, so building the box for each of the ~3000 calls + // ran one after another on every thread (over half an hour in CI). + let mut start = Session::default(); + let _ = start.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})); + let _ = start.execute("sketch.create", &json!({"plane": "XY"})); + let _ = start.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]})); for v in hostile_values() { for k in keys { - if k == "path" && (id.starts_with("parameters.") || id == "timeline.export_script") { - continue; // parameter and script files: covered by their own tests (no stray files) + if k == "path" + && (id.starts_with("parameters.") + || id == "timeline.export_script" + || matches!( + id, + "file.export_3mf" | "file.export_obj" | "file.export_step" | "file.export_stl" | "file.export_urdf" + )) + { + continue; // parameter, script and export files: covered by their own tests (no stray files) } - let mut s = Session::default(); - // A model with a sketch, a body and an active sketch, so most commands get far. - let _ = s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})); - let _ = s.execute("sketch.create", &json!({"plane": "XY"})); - let _ = s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]})); + let mut s = copy_with_history(&start); let p = json!({ k: v.clone() }); if let Err(EngineError::Internal(id, msg)) = s.execute(id, &p) { internal.push(format!("{id} {p}: {msg}")); @@ -1109,7 +1335,7 @@ fn sample_edges_chain_and_faces() { let chain = m.tangent_chain(e, 2f64.to_radians()); // The plate's top outline: 4 lines and 4 corner arcs (a boolean may leave an edge twice, // once per face; count distinct ones). - let mut mids: Vec = Vec::new(); + let mut mids: Vec = Vec::new(); for i in &chain { let p = &m.edges[*i]; let mid = p[p.len() / 2]; @@ -1134,7 +1360,8 @@ fn timeline_inspect_shows_what_timeline_edit_changes() { run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Slab"})); run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2, "name": "Round"})); let i = run(&mut s, "timeline.inspect", json!({"feature": "Slab"})); - assert_eq!(i["type"], "ExtrudeFeature", "{i}"); + assert_eq!(i["type"], "extrude", "{i}"); + assert_eq!(i["type_name"], "ExtrudeFeature", "{i}"); assert_eq!(i["definition"]["extent"]["distance"], "10", "{i}"); assert_eq!(i["definition"]["operation"], "new_body", "{i}"); assert!(i["definition"].get("type").is_none() && i["definition"].get("param_names").is_none(), "{i}"); @@ -1446,14 +1673,14 @@ fn extrude_auto_operation() { run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); // A face pushed in (negative distance) cuts. let p = json!({"face": [20, 15, 20], "distance": -5, "operation": "auto"}); - assert_eq!(auto_operation(&s, &p), Some("cut")); + assert_eq!(auto_operation(&s, &p).unwrap(), Some("cut")); run(&mut s, "solid.extrude", p); assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0) < 1e-6); // Pulled out, it joins. - assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 5})), Some("join")); + assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 5})).unwrap(), Some("join")); // Pushed in far past the bottom (halfway is below the box), it still cuts (#1257). - assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": -50})), Some("cut")); - assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 50, "direction": "negative"})), Some("cut")); + assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": -50})).unwrap(), Some("cut")); + assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 50, "direction": "negative"})).unwrap(), Some("cut")); // A sketch on XY under the box: up goes into it (cut), down grows out of it (join), and a // profile beside the box still defaults to Join (New Body remains explicit). run(&mut s, "sketch.create", json!({"plane": "XY"})); @@ -1461,9 +1688,9 @@ fn extrude_auto_operation() { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [60, 5], "p1": [70, 15]})); run(&mut s, "sketch.finish", json!({})); let at = |x: f64, d: f64| json!({"profiles": [{"point": [x, 10]}], "distance": d}); - assert_eq!(auto_operation(&s, &at(10.0, 8.0)), Some("cut")); - assert_eq!(auto_operation(&s, &at(10.0, -8.0)), Some("join")); - assert_eq!(auto_operation(&s, &at(65.0, 8.0)), Some("join")); + assert_eq!(auto_operation(&s, &at(10.0, 8.0)).unwrap(), Some("cut")); + assert_eq!(auto_operation(&s, &at(10.0, -8.0)).unwrap(), Some("join")); + assert_eq!(auto_operation(&s, &at(65.0, 8.0)).unwrap(), Some("join")); run(&mut s, "solid.extrude", json!({"profiles": [{"point": [10, 10]}], "distance": 8, "operation": "auto"})); assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0 - 100.0 * 8.0) < 1e-6); } @@ -1479,17 +1706,17 @@ fn extrude_auto_operation_counts_from_the_start() { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]})); run(&mut s, "sketch.finish", json!({})); let down = json!({"profiles": [{"point": [10, 10]}], "distance": -5}); - assert_eq!(auto_operation(&s, &down), Some("cut")); + assert_eq!(auto_operation(&s, &down).unwrap(), Some("cut")); let mut from = down.clone(); from["from"] = json!([20, 15, 0]); - assert_eq!(auto_operation(&s, &from), Some("join")); + assert_eq!(auto_operation(&s, &from).unwrap(), Some("join")); let mut offset = down.clone(); offset["start_offset"] = json!("-15 mm"); - assert_eq!(auto_operation(&s, &offset), Some("join")); + assert_eq!(auto_operation(&s, &offset).unwrap(), Some("join")); // Up from the bottom face into the plate it cuts again. let mut up = from.clone(); up["distance"] = json!(5); - assert_eq!(auto_operation(&s, &up), Some("cut")); + assert_eq!(auto_operation(&s, &up).unwrap(), Some("cut")); } /// #1666: a loft between two 18-point polylines has twisted (bilinear) side faces. Each was @@ -1516,7 +1743,7 @@ fn twisted_ruled_faces_are_meshed_to_the_chord_tolerance() { let st = s.model.state(); let body = &st.bodies.first().unwrap().body; let exact = solidcraft_kernel::measure(body).unwrap().volume; - let mesh = body.tessellate(0.05).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap(); let volume: f64 = mesh .triangles .iter() @@ -1540,11 +1767,11 @@ fn extrude_auto_operation_follows_the_to_object() { // From the top face to the bottom face: through the body. let down = json!({"face": [20, 15, 20], "to": [10, 10, 0], "distance": 19, "direction": direction}); assert!(extrude_reach(&s, &down).is_some_and(|h| (h + 20.0).abs() < 1e-6), "{down}"); - assert_eq!(auto_operation(&s, &down), Some("cut"), "{down}"); + assert_eq!(auto_operation(&s, &down).unwrap(), Some("cut"), "{down}"); // From the top face up to the box above: out of the body. let up = json!({"face": [20, 15, 20], "to": [10, 10, 50], "distance": 19, "direction": direction}); assert!(extrude_reach(&s, &up).is_some_and(|h| (h - 30.0).abs() < 1e-6), "{up}"); - assert_eq!(auto_operation(&s, &up), Some("join"), "{up}"); + assert_eq!(auto_operation(&s, &up).unwrap(), Some("join"), "{up}"); } // Without a To object the direction still counts. assert_eq!(extrude_reach(&s, &json!({"face": [20, 15, 20], "distance": 5, "direction": "negative"})), Some(-5.0)); @@ -1597,7 +1824,7 @@ fn auto_extrude_joins_side_contact_elbow_and_keeps_new_body_explicit() { // The profile centre is outside the vertical arm. Contact is along its // y=10 side, not behind the centre along the extrusion's X direction. let p = json!({"distance": 10, "to": [0, 15, 25], "operation": operation}); - assert_eq!(auto_operation(&s, &p), Some("join")); + assert_eq!(auto_operation(&s, &p).unwrap(), Some("join")); run(&mut s, "solid.extrude", p); assert!((volume(&mut s) - 5000.0).abs() < 1e-6); let st = s.model.state(); @@ -1607,7 +1834,7 @@ fn auto_extrude_joins_side_contact_elbow_and_keeps_new_body_explicit() { assert!(body.validity().is_empty()); assert_eq!(body.lumps().unwrap().len(), 1); assert_eq!(body.face_count(), 8, "the two flat elbow sides must be single faces"); - assert!(body.contains(geom::Vec3::new(5.0, 10.0, 25.0))); + assert_eq!(body.classify_point(solidcore_record::Vec3::new(5.0, 10.0, 25.0)).unwrap(), solidcraft_kernel::PointClass::Inside); } } } @@ -1621,7 +1848,7 @@ fn auto_extrude_joins_corner_screw_boss() { run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 1})); run(&mut s, "sketch.finish", json!({})); let p = json!({"profiles": [{"point": [12, 10]}], "distance": 5, "operation": "auto"}); - assert_eq!(auto_operation(&s, &p), Some("join")); + assert_eq!(auto_operation(&s, &p).unwrap(), Some("join")); run(&mut s, "solid.extrude", p); assert!(rel(volume(&mut s), 3000.0 + PI * 15.0 * 5.0) < 1e-3); let st = s.model.state(); @@ -1629,7 +1856,11 @@ fn auto_extrude_joins_corner_screw_boss() { let body = &st.bodies.first().unwrap().body; assert_eq!(body.lumps().unwrap().len(), 1); assert!(body.validity().is_empty()); - assert!(!body.contains(geom::Vec3::new(10.0, 10.0, 32.0)), "the screw hole stays open"); + assert_eq!( + body.classify_point(solidcore_record::Vec3::new(10.0, 10.0, 32.0)).unwrap(), + solidcraft_kernel::PointClass::Outside, + "the screw hole stays open" + ); } #[test] @@ -1640,11 +1871,28 @@ fn auto_extrude_starts_new_body_in_empty_component() { run(&mut s, "sketch.create", json!({"plane": "XY"})); run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 2})); run(&mut s, "sketch.finish", json!({})); - assert_eq!(auto_operation(&s, &json!({"distance": 5})), Some("new")); - assert_eq!(auto_operation(&s, &json!({"distance": 5, "participants": ["missing"]})), Some("new")); + assert_eq!(auto_operation(&s, &json!({"distance": 5})).unwrap(), Some("new")); + assert_eq!(auto_operation(&s, &json!({"distance": 5, "participants": ["missing"]})).unwrap(), Some("new")); } /// Measuring picked geometry: distance between faces, angle, edge length. +#[test] +fn measure_origin_planes_axes_and_points() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + let at = |p: [f64; 3]| json!({"type": "vertex", "body": "Body1", "point": p}); + // A point 10 above the XY plane. + let r = run(&mut s, "inspect.measure", json!({"items": [{"type": "plane", "name": "XY"}, at([5.0, 5.0, 10.0])]})); + assert!((r["distance_mm"].as_f64().unwrap() - 10.0).abs() < 1e-9, "{r}"); + assert_eq!(r["from"], json!([5.0, 5.0, 0.0])); + // The point's distance from the Z axis. + let r = run(&mut s, "inspect.measure", json!({"items": [{"type": "axis", "name": "Z"}, at([3.0, 4.0, 7.0])]})); + assert!((r["distance_mm"].as_f64().unwrap() - 5.0).abs() < 1e-9, "{r}"); + // The XY plane and the Z axis meet: nothing between them. + let r = run(&mut s, "inspect.measure", json!({"items": [{"type": "plane", "name": "XY"}, {"type": "axis", "name": "Z"}]})); + assert!(r["distance_mm"].as_f64().unwrap().abs() < 1e-9, "{r}"); +} + #[test] fn measure_items() { let mut s = Session::default(); @@ -1716,8 +1964,10 @@ fn section_analysis() { assert_eq!(s.undo.len(), undo); } -/// A section index finds the same cut segments, in the same order, as cutting every triangle: -/// tilted and axis normals, cuts through vertices, at the ends and beyond the part. +/// A section index finds the same cut segments, in the same order and to the bit, as cutting +/// every triangle: one index for every normal (tilting a Section Analysis turns it every frame, +/// #10373), axis and tilted, cuts through vertices, at the ends and beyond the part, and a +/// triangle with a corner that is not a number. #[test] fn section_index_cuts_like_every_triangle() { let mut s = Session::default(); @@ -1725,18 +1975,30 @@ fn section_index_cuts_like_every_triangle() { run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 8, "operation": "join"})); let st = s.model.state(); let m = st.bodies.first().unwrap().mesh(); - assert!(m.triangles.len() > 64, "enough triangles for several slabs: {}", m.triangles.len()); - for n in [Vec3::Z, -Vec3::Y, Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(), Vec3::new(-0.3, 0.1, 0.9).normalized().unwrap()] { - let index = view::SectionIndex::new(&m, n); - let heights: Vec = m.positions.iter().map(|p| n.dot(*p)).collect(); - let (lo, hi) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(*h), b.max(*h))); - let mut cuts: Vec = (0..=40).map(|k| lo - 1.0 + (hi - lo + 2.0) * k as f64 / 40.0).collect(); - cuts.extend(heights.iter().step_by(7).copied()); - cuts.extend([lo, hi]); - for at in cuts { - let o = n * at; - let segments = view::section_segments(&m, o, n); - assert_eq!(index.segments(&m, o), segments, "{n:?} at {at}"); + assert!(m.triangles.len() > 64, "enough triangles for several cells: {}", m.triangles.len()); + let bits = |v: Vec<(Vec3, Vec3)>| v.iter().flat_map(|(a, b)| [a.x, a.y, a.z, b.x, b.y, b.z].map(f64::to_bits)).collect::>(); + let mut hostile = (*m).clone(); + hostile.positions.push(Vec3::new(f64::NAN, 0.0, 0.0)); + let nan = u32::try_from(hostile.positions.len() - 1).unwrap(); + hostile.triangles.extend([[0, 1, nan], [0, 1, u32::MAX]]); + for m in [&*m, &hostile] { + let index = view::SectionIndex::new(m); + let mut normals = vec![Vec3::Z, -Vec3::Y, Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(), Vec3::new(-0.3, 0.1, 0.9).normalized().unwrap()]; + // A tilt drag: the normal turns a little every frame. + normals.extend((0..30).map(|k| { + let a = (5.0 + 3.0 * k as f64).to_radians(); + Vec3::new(0.1, a.sin(), a.cos()).normalized().unwrap() + })); + for n in normals { + let heights: Vec = m.positions.iter().map(|p| n.dot(*p)).filter(|h| h.is_finite()).collect(); + let (lo, hi) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(*h), b.max(*h))); + let mut cuts: Vec = (0..=40).map(|k| lo - 1.0 + (hi - lo + 2.0) * k as f64 / 40.0).collect(); + cuts.extend(heights.iter().step_by(7).copied()); + cuts.extend([lo, hi]); + for at in cuts { + let o = n * at; + assert_eq!(bits(index.segments(m, o, n)), bits(view::section_segments(m, o, n)), "{n:?} at {at}"); + } } } } @@ -1850,7 +2112,7 @@ fn holes_at_sketch_points_threads_and_components() { assert_eq!(threads[0]["internal"], true); // A cosmetic thread on a shaft; designation from its size. run(&mut s, "solid.cylinder", json!({"base": [100, 0, 0], "radius": 4, "height": 20, "name": "Shaft", "body_name": "Shaft"})); - let th = run(&mut s, "solid.thread", json!({"face": [104, 0, 10], "length": 12})); + let th = run(&mut s, "solid.thread", json!({"face": [104, 0, 10], "length": 12, "from": [100, 0, 0]})); assert_eq!(th["thread"]["designation"], "M8", "{th}"); assert!((th["thread"]["end"].as_f64().unwrap() - th["thread"]["start"].as_f64().unwrap() - 12.0).abs() < 1e-6, "{th}"); assert!(s.execute("solid.thread", &json!({"face": [104, 0, 10], "designation": "M20"})).is_err()); @@ -1877,7 +2139,7 @@ fn holes_at_sketch_points_threads_and_components() { ); let reopened = Session::new(back); assert_eq!(reopened.model.state().body("Shaft").unwrap().component, assigned); - assert_eq!(reopened.world_state().threads.len(), s.world_state().threads.len()); + assert_eq!(reopened.world_state().unwrap().threads.len(), s.world_state().unwrap().threads.len()); } #[test] @@ -1958,6 +2220,24 @@ fn checkpoint_restores_with_a_full_undo_history() { assert!(s.execute("edit.restore_checkpoint", &json!({"checkpoint": id})).is_err()); } +/// Regression (#9746): a checkpoint restored already, or one of more than the 16 kept, was +/// refused with only "no checkpoint N", so a script that restores twice could not tell why. +#[test] +fn a_used_up_or_dropped_checkpoint_says_why() { + let mut s = Session::default(); + let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap(); + run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id})); + let used = s.execute("edit.restore_checkpoint", &json!({"checkpoint": id})).unwrap_err().to_string(); + assert!(used.contains("used up") && used.contains("16"), "{used}"); + let first = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap(); + for _ in 0..MAX_CHECKPOINTS { + run(&mut s, "edit.checkpoint", json!({})); + } + let dropped = s.execute("edit.restore_checkpoint", &json!({"checkpoint": first})).unwrap_err().to_string(); + assert!(dropped.contains("16"), "{dropped}"); + run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": first + 1})); +} + /// 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] @@ -1966,13 +2246,15 @@ fn a_checkpoint_survives_file_new() { 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"})); + // The volume as SMLib integrates it, to rounding (a unit box measures 1 + 2e-16). + let volume = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN); 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)); + assert!((volume(&mut s) - 8.0).abs() < 1e-12); 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)); + assert!((volume(&mut s) - 1.0).abs() < 1e-12); // 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)); + assert!(volume(&mut s).abs() < 1e-12); } #[test] @@ -1998,11 +2280,11 @@ fn components_occurrences_and_world_placement() { run(&mut s, "component.activate", json!({"component": 0})); // Instances share the contents; a copy is independent. run(&mut s, "occurrence.copy", json!({"component": cid, "translate": [0, 20, 0]})); - let w = s.world_state(); + let w = s.world_state().unwrap(); assert_eq!(w.bodies.len(), 3, "{:?}", w.bodies.iter().map(|b| &b.name).collect::>()); let pn = run(&mut s, "component.paste_new", json!({"component": cid, "translate": [0, -30, 0]})); assert_eq!(pn["features"].as_array().map(|a| a.len()), Some(2)); - assert_eq!(s.world_state().bodies.len(), 4); + assert_eq!(s.world_state().unwrap().bodies.len(), 4); // Ground stops moves; pending moves show until captured or reverted. run(&mut s, "occurrence.ground", json!({"occurrence": occ})); assert!(s.execute("occurrence.move", &json!({"occurrence": occ, "translate": [1, 0, 0]})).is_err()); @@ -2025,7 +2307,7 @@ fn components_occurrences_and_world_placement() { assert_eq!(s.pending_moves, pending); // Placed by the first placement, the body stays where it is in the world there. run(&mut s, "component.move_bodies", json!({"bodies": ["Base"], "component": "Arm", "component_path": [occ]})); - assert_eq!(s.world_state().body("Base").unwrap().component, cid); + assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, cid); assert_eq!(bbox(&mut s, "Base")["min"], json!([0.0, 0.0, 0.0])); run(&mut s, "edit.undo", json!({})); assert_eq!(s.doc.to_json(), document); @@ -2048,8 +2330,8 @@ fn components_occurrences_and_world_placement() { run(&mut s, "edit.redo", json!({})); run(&mut s, "timeline.roll_to", json!({"position": 1})); // The ownership boundary is later: before it Base remains the sole root body. - assert_eq!(s.world_state().bodies.len(), 1); - assert_eq!(s.world_state().body("Base").unwrap().component, 0); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, 0); run(&mut s, "timeline.roll_to", json!({})); // Saved and loaded; older designs get occurrences. let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); @@ -2131,7 +2413,7 @@ fn sample_plate_step_round_trip() { let mut s = Session::default(); s.run_script(&crate::sample::script()).unwrap(); let imp = step_round_trip(&mut s, "sample"); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(imp.bodies.len(), st.bodies.len()); for (a, b) in st.bodies.iter().zip(&imp.bodies) { assert_eq!(a.name, b.name); @@ -2221,7 +2503,7 @@ fn face_colours_and_opacity_export() { let mut s2 = Session::default(); run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()})); let _ = std::fs::remove_file(&p); - let st = s2.world_state(); + let st = s2.world_state().unwrap(); let looks = s2.doc.face_colors(&st.bodies[0]); assert_eq!(looks.len(), 1); assert_eq!(looks[0].1.color, [255, 0, 0]); @@ -2235,13 +2517,13 @@ fn iges_export_and_open() { run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "body_name": "Plate"})); run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "base": [10, 10, 5], "body_name": "Pin"})); run(&mut s, "appearance.assign", json!({"bodies": ["Pin"], "color": "#ff0000"})); - let want: Vec = s.world_state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); + let want: Vec = s.world_state().unwrap().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); let p = std::env::temp_dir().join(format!("solidcraft-iges-{}.igs", std::process::id())); run(&mut s, "file.export", json!({"path": p.to_string_lossy()})); let mut s2 = Session::default(); run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()})); let _ = std::fs::remove_file(&p); - let st = s2.world_state(); + let st = s2.world_state().unwrap(); let names: Vec<&str> = st.bodies.iter().map(|b| b.name.as_str()).collect(); assert_eq!(names, ["Plate", "Pin"]); for (b, v) in st.bodies.iter().zip(&want) { @@ -2258,7 +2540,7 @@ fn split_body_by_a_face() { run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"})); run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 40, "base": [5, 10, -5], "body_name": "Tool"})); run(&mut s, "solid.split_body", json!({"body": "Block", "tool": {"body": "Tool", "point": [9, 10, 10]}})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let mut v: Vec = st.bodies.iter().filter(|b| b.name.starts_with("Block")).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); v.sort_by(f64::total_cmp); @@ -2279,7 +2561,7 @@ fn split_body_by_a_sketch_line() { run(&mut s, "sketch.circle.center", json!({"center": [50, 50], "radius": 2, "id": "c"})); run(&mut s, "sketch.finish", json!({})); let volumes = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); let mut v: Vec = st.bodies.iter().filter(|b| b.name.starts_with("Block")).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); v.sort_by(f64::total_cmp); @@ -2316,12 +2598,12 @@ fn chord_and_variable_fillets() { run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"})); run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 4, "type": "chord"})); let r = 4.0 / 2f64.sqrt(); - let v = solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; assert!(rel(v, 6000.0 - (1.0 - PI / 4.0) * r * r * 20.0) < 1e-4, "{v}"); let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"})); run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable", "radius2": 5, "start": [10, 0, 30]})); - let v = solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; let removed = (1.0 - PI / 4.0) * 20.0 * (4.0 + 10.0 + 25.0) / 3.0; assert!(rel(v, 6000.0 - removed) < 1e-4, "{v}"); assert!(s.execute("solid.fillet", &json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable"})).is_err()); @@ -2329,7 +2611,7 @@ fn chord_and_variable_fillets() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"})); run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 4, "type": "variable", "radius2": 0, "start": [10, 0, 30]})); - let v = solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; assert!(rel(v, 6000.0 - (1.0 - PI / 4.0) * 20.0 * 16.0 / 3.0) < 1e-4, "{v}"); // A radius through a middle point (a user parameter), straight between: 2 → 4 → 2. let mut s = Session::default(); @@ -2340,7 +2622,7 @@ fn chord_and_variable_fillets() { "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable", "radius2": 2, "start": [10, 0, 30], "mid": [[0.5, "waist"]]}), ); - let vol = |s: &Session| solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let vol = |s: &Session| solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; let removed = 2.0 * (1.0 - PI / 4.0) * 10.0 * (4.0 + 8.0 + 16.0) / 3.0; assert!(rel(vol(&s), 6000.0 - removed) < 1e-4, "{}", vol(&s)); // The middle radius follows its parameter. @@ -2364,7 +2646,7 @@ fn components_export_as_step_assembly() { run(&mut s, "component.create", json!({"name": "Pin"})); run(&mut s, "solid.cylinder", json!({"radius": 2, "height": 10, "base": [5, 5, 5]})); run(&mut s, "occurrence.copy", json!({"component": "Pin", "translate": [20, 0, 0]})); - let want: f64 = s.world_state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); + let want: f64 = s.world_state().unwrap().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); let imp = step_round_trip(&mut s, "asm"); assert_eq!(imp.bodies.len(), 3, "{:?}", imp.bodies.iter().map(|b| &b.name).collect::>()); let got: f64 = imp.bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); @@ -2557,6 +2839,13 @@ mod naming { s.model.result(id).and_then(|r| r.warning.clone()) } + /// The reference feature `name` failed on, asking for it to be picked again. + fn reselect(s: &Session, name: &str) -> Option { + let id = s.doc.find_feature(name).map(|f| f.id)?; + let error = s.model.result(id).and_then(|r| r.error.clone())?; + solidcraft_doc::reselect_parts(&error).filter(|(feature, _)| *feature == name).map(|(_, reference)| reference.to_string()) + } + /// A 40 x 30 x 10 block (sketch S: l1…l4 counter-clockwise from the origin), a hole H, a /// fillet on the right top edge. fn block() -> Session { @@ -2622,25 +2911,21 @@ mod naming { run(s, "solid.extrude", json!({"sketch": "N", "distance": 10, "operation": "cut", "name": "Notch"})); } - /// Upstream of the fillet, a notch across the filleted edge at y 6 to 12 leaves two pieces of - /// it, 6 and 18 long: the fillet warns and rounds the one nearest its pick at y 15, the longer. + /// The notch leaves the filleted edge in two pieces: neither is the edge, so the fillet fails, + /// asking for its edge again, and never rounds the piece nearest the pick. #[test] - fn a_split_edge_warns_and_takes_the_nearest_piece() { + fn a_split_edge_fails_the_fillet_asking_for_the_edge_again() { let mut s = block(); run(&mut s, "timeline.roll_to", json!({"feature": "Hole"})); - notch(&mut s, [36.0, 6.0], [44.0, 12.0]); + notch(&mut s, [36.0, 12.0], [44.0, 18.0]); run(&mut s, "timeline.roll_to", json!({})); - let w = warning(&s, "Round").unwrap_or_default(); - assert!(w.contains("split"), "{w}"); - let rounded = 12000.0 - std::f64::consts::PI * 160.0 - 240.0 - STRIP * 18.0 / 30.0; - assert!((volume(&mut s) - rounded).abs() < 0.1, "{} {rounded}", volume(&mut s)); + assert_eq!(reselect(&s, "Round").as_deref(), Some("F2:side:l2|F2:top")); } - /// A fillet on a piece of a split edge, its notch then suppressed: the edge is whole again and - /// its piece's name matches it only through the face the piece was cut from, so the fillet - /// rounds all of it with a warning, not as the very edge it named. + /// A fillet on a piece of a split edge, its notch then suppressed: the edge is whole again, and + /// its piece's name doesn't stand for all of it, so the fillet fails, asking for its edge again. #[test] - fn a_pieces_name_on_the_whole_edge_again_warns() { + fn a_pieces_name_on_the_whole_edge_again_fails_asking_for_the_edge() { let mut s = block(); run(&mut s, "timeline.delete", json!({"features": ["Round"]})); notch(&mut s, [36.0, 12.0], [44.0, 18.0]); @@ -2649,14 +2934,15 @@ mod naming { assert!(!named.is_empty() && named.iter().all(|n| n.contains('#')), "a piece's name: {named:?}"); assert_eq!(warning(&s, "Piece"), None); run(&mut s, "timeline.suppress", json!({"feature": "Notch", "suppressed": true})); - let w = warning(&s, "Piece").unwrap_or_default(); - assert!(w.contains("split"), "{w}"); - let rounded = 12000.0 - std::f64::consts::PI * 160.0 - STRIP; - assert!((volume(&mut s) - rounded).abs() < 0.1, "{} {rounded}", volume(&mut s)); + assert!(reselect(&s, "Piece").is_some(), "{:?}", warning(&s, "Piece")); + let unrounded = 12000.0 - std::f64::consts::PI * 160.0; + assert!((volume(&mut s) - unrounded).abs() < 0.1, "{} {unrounded}", volume(&mut s)); } + /// The face the filleted edge bounded is gone with its sketch line: the fillet fails, asking + /// for its edge again. #[test] - fn a_removed_segment_warns() { + fn a_removed_segment_fails_the_fillet_asking_for_the_edge_again() { let mut s = block(); // Replace the right side (l2) of the rectangle with a new line: the face it made is gone. let sk = s.doc.find_feature("S").map(|f| f.id).unwrap(); @@ -2665,8 +2951,7 @@ mod naming { run(&mut s, "sketch.line", json!({"points": [[40, 0], [40, 30]], "ids": ["right"]})); let r: Result = s.execute("sketch.finish", &json!({})); assert!(r.is_ok() || r.is_err()); - let w = warning(&s, "Round").unwrap_or_default(); - assert!(w.contains("no longer exists"), "{w}"); + assert_eq!(reselect(&s, "Round").as_deref(), Some("F2:side:l2|F2:top")); } fn face_names(s: &mut Session, body: &str) -> Vec { @@ -2725,7 +3010,9 @@ mod naming { model.evaluate(&reopened); assert_eq!(model.state().sketch(reopened.find_feature("Top").unwrap().id).unwrap().plane.origin.z, 10.); assert!((model.state().bodies[0].mesh().bounds().max.z - 15.).abs() < 1e-6); - // A historical format-10 attachment uses its saved generic face name and no strong anchor. + // A format-10 attachment has only the face name that build worked out from geometry, and + // no strong anchor: that name finds no face today. The sketch fails, asking for its face + // again, and so does the peg on it; the block builds. let mut old = (*s.doc).clone(); let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, name, .. }, sketch } = &mut old.features.iter_mut().find(|f| f.name == "Top").unwrap().kind @@ -2733,6 +3020,7 @@ mod naming { panic!("fixture must contain a face sketch"); }; *anchor = None; + let saved = name.clone().unwrap(); for link in &mut sketch.links { if link.auto_face { link.auto_face = false; @@ -2740,30 +3028,20 @@ mod naming { } } old.format = "solidcraft/10".into(); - let mut legacy = Session::new(solidcraft_doc::Document::from_json(&old.to_json()).unwrap()); - assert_eq!(attached(&legacy), Some(10.)); - assert!((top(&mut legacy) - 15.).abs() < 1e-6); + let legacy = Session::new(solidcraft_doc::Document::from_json(&old.to_json()).unwrap()); + let error = |s: &Session, name: &str| s.model.results.iter().find(|r| r.id == s.doc.find_feature(name).unwrap().id).unwrap().error.clone(); + let reference = format!("{}{saved}", solidcraft_doc::naming::LEGACY_MARK); + assert_eq!(error(&legacy, "Top").as_deref().and_then(solidcraft_doc::reselect_parts), Some(("Top", reference.as_str()))); + assert!(error(&legacy, "Peg").is_some()); + assert!(error(&legacy, "Block").is_none()); // An upstream join that trims the certified face: the attachment stays on what is left // of it and never follows the substitute roof (see face_tests for a face covered whole). - for target in [&mut s, &mut legacy] { - run(target, "timeline.roll_to", json!({"feature": "Block"})); - run(target, "sketch.create", json!({"plane": "XY", "name": "B"})); - run(target, "sketch.rectangle.two_point", json!({"p0": [8, -5], "p1": [45, 35]})); - run(target, "sketch.finish", json!({})); - run(target, "solid.extrude", json!({"sketch": "B", "distance": 20, "operation": "join", "name": "Boss"})); - run(target, "timeline.roll_to", json!({})); - } - assert_eq!(attached(&legacy), Some(10.), "historical weak naming retains its saved geometry behavior"); - assert!((top(&mut legacy) - 20.).abs() < 1e-6); - let legacy_reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.doc.to_json()).unwrap()); - assert_eq!(attached(&legacy_reopened), Some(10.)); - assert!((legacy_reopened.model.state().bodies[0].mesh().bounds().max.z - 20.).abs() < 1e-6); - let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, .. }, .. } = - &legacy_reopened.doc.find_feature("Top").unwrap().kind - else { - panic!("saved historical face reference must remain present"); - }; - assert!(anchor.is_none(), "opening old face references must not infer a strict attachment"); + run(&mut s, "timeline.roll_to", json!({"feature": "Block"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "B"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [8, -5], "p1": [45, 35]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "B", "distance": 20, "operation": "join", "name": "Boss"})); + run(&mut s, "timeline.roll_to", json!({})); let failed = |s: &Session, name: &str| s.model.results.iter().find(|r| r.id == s.doc.find_feature(name).unwrap().id).unwrap().error.is_some(); assert!(!failed(&s, "Top")); assert!(!failed(&s, "Peg")); @@ -2860,17 +3138,74 @@ fn press_pull_on_curved_faces() { let v1 = volume(&mut s); assert!(rel(v1 - v0, PI * (25.0 - 16.0) * 20.0) < 1e-3, "{v0} {v1}"); // A shell's inner wall behind a fillet (`F3:inner:F2:blend:…`) only names the fillet: it is - // offset like any curved face, not taken for the shell's fillet. (The offset itself is - // refused: the wall is tangent to its neighbours.) + // offset like any curved face, not taken for the shell's fillet. Pulled 0.5 into the cavity + // (radius 3 to 2.5), the wall alone moves, stepping in from its tangent neighbours: the + // quarter ring between the radii, 18 high, is added. let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 20})); run(&mut s, "solid.fillet", json!({"edges": [[40, 40, 10]], "radius": 5})); run(&mut s, "solid.shell", json!({"faces": [[20, 20, 20]], "thickness": 2})); let on = Vec3::new(35.0, 35.0, 10.0) + Vec3::new(1.0, 1.0, 0.0).normalized().unwrap() * 3.0; - let err = - s.execute("solid.press_pull", &json!({"face": [on.x, on.y, on.z], "distance": 0.5})).map(|v| v.to_string()).unwrap_or_else(|e| e.to_string()); - assert!(!err.contains("not a fillet's or a chamfer's"), "{err}"); - assert!(err.contains("offset"), "{err}"); + let v0 = volume(&mut s); + let out = run(&mut s, "solid.press_pull", json!({"face": [on.x, on.y, on.z], "distance": 0.5})); + assert!(out["name"].as_str().is_some_and(|n| n.starts_with("OffsetFace")) && out.get("edited").is_none(), "{out}"); + let ring = PI / 4.0 * (3.0 * 3.0 - 2.5 * 2.5) * 18.0; + // Each volume to the measure's 2e-7. + assert!((volume(&mut s) - v0 - ring).abs() < 4e-7 * v0, "{} vs {ring}", volume(&mut s) - v0); +} + +/// #4986: Press Pull on a chamfer's flat face changes the chamfer's distance, as on a fillet's +/// face it changes the radius, rather than extruding the face. +#[test] +fn press_pull_on_a_chamfer_face_edits_the_chamfer() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut s, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"})); + let cut = |d: f64| d * d / 2.0 * 20.0; + assert!(rel(volume(&mut s), 24000.0 - cut(3.0)) < 1e-6); + // The chamfer's face runs from (37, 0) to (40, 3); its middle. + let out = run(&mut s, "solid.press_pull", json!({"face": [38.5, 1.5, 10], "distance": 2})); + assert_eq!(out["edited"], "Bevel", "{out}"); + assert_eq!(s.doc.features.len(), 2, "no extrude added"); + assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{}", volume(&mut s)); + // A point on the flat front face 0.02 mm from its edge with the chamfer (which now runs from + // (35, 0) to (40, 5)) is the front face's: it is extruded, the chamfer is left alone. + let mut t = Session::default(); + run(&mut t, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut t, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"})); + let out = run(&mut t, "solid.press_pull", json!({"face": [36.98, 0, 10], "distance": 1})); + assert!(out.get("edited").is_none(), "{out}"); + assert!(matches!(t.doc.features.last().map(|f| &f.kind), Some(solidcraft_doc::FeatureKind::Extrude { .. })), "an extrude added: {out}"); + assert!( + matches!(&t.doc.features[1].kind, solidcraft_doc::FeatureKind::Chamfer { distance, .. } if distance == "3"), + "{:?}", + t.doc.features[1].kind + ); + // Too far in (past zero) or too far out: an error, the chamfer as it was. + let on = [39.0, 1.0, 10.0]; + for d in [-10.0, 1e9] { + assert!(s.execute("solid.press_pull", &json!({"face": on, "distance": d})).is_err(), "{d}"); + assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{d}: {}", volume(&mut s)); + } + // An unequal chamfer's first distance changes and its second stays; an angle chamfer keeps + // its angle. + // Each chamfer's face crosses the corner's bisector at legs a, b: (40 - u, u), u = ab / (a + b). + let tan30 = (PI / 6.0).tan(); + for (extra, u) in [(json!({"distance2": 4}), 8.0 / 6.0), (json!({"angle": "30 deg"}), 2.0 * tan30 / (1.0 + tan30))] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + let mut p = json!({"edges": [[40, 0, 10]], "distance": 2, "name": "Bevel"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + run(&mut s, "solid.chamfer", p); + let v0 = volume(&mut s); + let out = run(&mut s, "solid.press_pull", json!({"face": [40.0 - u, u, 10.0], "distance": 1})); + assert_eq!(out["edited"], "Bevel", "{extra}: {out}"); + assert_eq!(s.doc.features.len(), 2, "{extra}"); + let Some(solidcraft_doc::FeatureKind::Chamfer { distance2, angle, .. }) = s.doc.features.last().map(|f| &f.kind) else { panic!("{extra}") }; + assert_eq!(distance2.as_ref().map(|e| e.to_string()), extra.get("distance2").map(|v| v.to_string()), "{extra}"); + assert_eq!(angle.as_ref().map(|e| e.to_string()), extra.get("angle").and_then(|v| v.as_str()).map(str::to_string), "{extra}"); + assert!(volume(&mut s) < v0 - 1.0, "{extra}: a bigger chamfer cuts more"); + } } /// A cut in one component leaves other components' bodies alone unless they are named as @@ -2889,7 +3224,7 @@ fn booleans_stay_in_their_component() { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [8, 2], "p1": [28, 8]})); run(&mut s, "sketch.finish", json!({})); let vol = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["total"]["volume_mm3"].as_f64().unwrap_or(0.0); - assert_eq!(auto_operation(&s, &json!({"sketch": "Slot", "distance": 10})), Some("cut")); + assert_eq!(auto_operation(&s, &json!({"sketch": "Slot", "distance": 10})).unwrap(), Some("cut")); run(&mut s, "solid.extrude", json!({"sketch": "Slot", "distance": 10, "operation": "cut", "name": "Cut"})); assert!((vol(&mut s, "ABox") - (2000.0 - 12.0 * 6.0 * 10.0)).abs() < 1e-6, "{}", vol(&mut s, "ABox")); assert!((vol(&mut s, "BBox") - 2000.0).abs() < 1e-6, "B untouched: {}", vol(&mut s, "BBox")); @@ -3005,6 +3340,16 @@ fn unequal_chamfers_on_circular_rims() { assert!(rel(full - volume(&mut s), flipped) < 5e-3, "{} vs {flipped}", full - volume(&mut s)); } +/// A solid box top is not a rim: Lip says to Shell first (#10437). +#[test] +fn lip_on_a_solid_box_says_to_shell_first() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10})); + let err = s.execute("plastic.lip", &json!({"face": [20, 15, 10], "width": 1, "height": 2})).unwrap_err().to_string(); + assert!(err.contains("Shell"), "{err}"); + assert!(err.contains("rim") || err.contains("opening"), "{err}"); +} + /// An enclosure built in the usual order: shell, bosses, then the lip on the rim. #[test] fn lip_after_boss() { @@ -3015,9 +3360,13 @@ fn lip_after_boss() { run(&mut s, "plastic.boss", json!({"position": [70, 40, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5})); let v0 = volume(&mut s); run(&mut s, "plastic.lip", json!({"face": [1, 25, 30], "width": 1, "height": 2})); - let v = volume(&mut s); - assert!(v > v0 + 1.0, "{v0} {v}"); - // Bosses up to the rim, with ribs, against a wall; lips, grooves and outside rims. + // The band inside the rim, 1 wide and 2 high: (78 × 48 − 76 × 46) × 2; the bosses stop + // at z = 14, well under it. + let inside = (78.0 * 48.0 - 76.0 * 46.0) * 2.0; + assert!(rel(volume(&mut s) - v0, inside) < 1e-6, "{}", volume(&mut s) - v0); + // Bosses up to the rim, with ribs, against a wall; lips, grooves and outside rims. None + // reaches the rim's bands, so each lip adds, and the groove (no gap) takes, its band: the + // inside one (78 × 48 − 76 × 46) × 2, the outside one (80 × 50 − 78 × 48) × 2. let bosses = [ json!({"position": [15, 15, 2], "diameter": 8, "height": 28, "hole_diameter": 3}), // Ribs out to the inner walls (15 − 4 − 9 = 2), and short of them. @@ -3026,13 +3375,14 @@ fn lip_after_boss() { json!({"position": [5.5, 25, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5}), json!({"position": [40, 25, 2], "diameter": 8, "height": 20, "draft": "1 deg", "fillet": 1}), ]; + let outside = (80.0 * 50.0 - 78.0 * 48.0) * 2.0; let lips = [ - json!({"face": [1, 25, 30], "width": 1, "height": 2}), - json!({"face": [1, 25, 30], "width": 1, "height": 2, "type": "groove"}), - json!({"face": [1, 25, 30], "width": 1, "height": 2, "side": "outside"}), + (json!({"face": [1, 25, 30], "width": 1, "height": 2}), inside), + (json!({"face": [1, 25, 30], "width": 1, "height": 2, "type": "groove"}), -inside), + (json!({"face": [1, 25, 30], "width": 1, "height": 2, "side": "outside"}), outside), ]; for (i, b) in bosses.iter().enumerate() { - for (j, l) in lips.iter().enumerate() { + for (j, (l, band)) in lips.iter().enumerate() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 30})); run(&mut s, "solid.shell", json!({"faces": [[40, 25, 30]], "thickness": 2})); @@ -3041,7 +3391,7 @@ fn lip_after_boss() { let v0 = volume(&mut s); let r = s.execute("plastic.lip", l); assert!(r.is_ok(), "boss {i} lip {j}: {r:?}"); - assert!((volume(&mut s) - v0).abs() > 1.0, "boss {i} lip {j}"); + assert!(rel(volume(&mut s) - v0, *band) < 1e-6, "boss {i} lip {j}: {} vs {band}", volume(&mut s) - v0); } } } @@ -3067,16 +3417,24 @@ fn hole_as_deep_as_the_plate() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 50, "width": 25, "height": 10})); let v0 = volume(&mut s); + // The depth is to the drill point's shoulder: the bore, radius 3, runs the plate's 10 and the + // point is in the air below it. run(&mut s, "solid.hole", json!({"position": [25, 12.5, 10], "diameter": 6, "depth": 10, "type": "drilled"})); let v = volume(&mut s); - assert!(v < v0 - PI * 9.0 * 9.0 && v > v0 - PI * 9.0 * 10.0 - 1.0, "{v0} {v}"); - // Other sizes and places, the defaults, and a tapped hole. - for (i, p) in [ - json!({"position": [10, 10, 10], "diameter": 5, "depth": 10, "type": "drilled"}), - json!({"position": [40, 15, 10], "diameter": 5, "depth": 10}), - json!({"position": [12, 6, 10], "diameter": 8.5, "depth": 10}), - json!({"position": [30, 7, 10], "thread": "M6", "depth": 10}), - json!({"position": [20, 18, 10], "diameter": 4, "depth": 10, "tip_angle": 90}), + assert!((v0 - v - PI * 9.0 * 10.0).abs() < 4e-7 * v0, "{v0} {v}"); + // Other sizes and places, the defaults, and a tapped hole: each a through bore of its drill, + // 10 long. The 8.5 at (12, 6) overlaps the 5 at (10, 10) (√20 apart, under 2.5 + 4.25), so + // it takes its bore less the lens they share, 10 long. + let (r, q, d) = (2.5f64, 4.25f64, 20f64.sqrt()); + let lens = r * r * ((d * d + r * r - q * q) / (2.0 * d * r)).acos() + q * q * ((d * d + q * q - r * r) / (2.0 * d * q)).acos() + - 0.5 * ((-d + r + q) * (d + r - q) * (d - r + q) * (d + r + q)).sqrt(); + for (i, (p, cut)) in [ + (json!({"position": [10, 10, 10], "diameter": 5, "depth": 10, "type": "drilled"}), PI * 6.25 * 10.0), + (json!({"position": [40, 15, 10], "diameter": 5, "depth": 10}), PI * 6.25 * 10.0), + (json!({"position": [12, 6, 10], "diameter": 8.5, "depth": 10}), (PI * q * q - lens) * 10.0), + // M6 × 1: the tap maker's 5.0 drill. + (json!({"position": [30, 7, 10], "thread": "M6", "depth": 10}), PI * 6.25 * 10.0), + (json!({"position": [20, 18, 10], "diameter": 4, "depth": 10, "tip_angle": 90}), PI * 4.0 * 10.0), ] .into_iter() .enumerate() @@ -3084,7 +3442,8 @@ fn hole_as_deep_as_the_plate() { let before = volume(&mut s); let r = s.execute("solid.hole", &p); assert!(r.is_ok(), "{i} {p}: {r:?}"); - assert!(volume(&mut s) < before - 1.0, "{i} {p}"); + let v = volume(&mut s); + assert!((before - v - cut).abs() < 4e-7 * before, "{i} {p}: {} vs {cut}", before - v); } } @@ -3300,7 +3659,12 @@ fn shell_tangent_chain_that_opens_every_face_explains_how_to_keep_walls() { assert_eq!(s.doc.to_json(), before, "a refused shell must preserve the design"); } run(&mut s, "solid.shell", json!({"faces": [[20,0,30]], "thickness": 2, "tangent_chain": false})); - assert!((volume(&mut s) - 15_305.28).abs() < 0.1); + // The rounded box (its 37 x 27 x 57 core grown by the 1.5 ball) less the cavity, which the + // 2 mm walls leave sharp, open through the front: 36 x 56 x 28. To the measure's 2e-7. + let (a, b, c, r) = (37.0, 27.0, 57.0, 1.5); + let rounded = a * b * c + 2.0 * r * (a * b + b * c + a * c) + PI * r * r * (a + b + c) + 4.0 / 3.0 * PI * r * r * r; + let want = rounded - 36.0 * 56.0 * 28.0; + assert!((volume(&mut s) - want).abs() < 2e-7 * rounded, "{} vs {want}", volume(&mut s)); assert_eq!(s.model.state().bodies.len(), 1); } @@ -3474,6 +3838,48 @@ fn computed_import_preserves_file_and_earlier_undo_history() { assert!(s.model.state().bodies.is_empty()); } +/// The unsaved-changes answer is worked out once per pair of documents and revision, and stays +/// right through every way the design changes: an edit in place (`doc_mut`, which stays in +/// place), one that bypasses it, a new document equal to the saved one, Save, a change of what +/// is hidden, and undo back to the saved design. Each answer is checked against the plain +/// comparison it stands for. +#[test] +fn the_unsaved_changes_answer_follows_every_change() { + let plain = |s: &Session| (!std::sync::Arc::ptr_eq(&s.doc, &s.saved) && *s.doc != *s.saved) || s.visibility != s.saved_visibility; + let check = |s: &Session, want: bool, why: &str| { + for _ in 0..2 { + assert_eq!(s.is_dirty(), want, "{why}"); + assert_eq!(plain(s), want, "{why}: the plain comparison"); + } + }; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + s.mark_saved(); + check(&s, false, "saved"); + // An edit in place: the cached answer holds the document, yet the edit is not a copy. + s.doc = std::sync::Arc::new((*s.doc).clone()); + check(&s, false, "an equal copy of the saved design"); + let at = std::sync::Arc::as_ptr(&s.doc); + s.doc_mut().name = "Renamed".into(); + assert_eq!(std::sync::Arc::as_ptr(&s.doc), at, "doc_mut edits in place"); + check(&s, true, "renamed in place, same revision"); + s.doc_mut().name = s.saved.name.clone(); + check(&s, false, "named back in place"); + // An edit that goes around doc_mut while the answer holds the document copies it. + std::sync::Arc::make_mut(&mut s.doc).name = "Elsewhere".into(); + check(&s, true, "edited past doc_mut"); + s.mark_saved(); + check(&s, false, "saved again"); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [30, 0, 0]})); + check(&s, true, "a command"); + run(&mut s, "edit.undo", json!({})); + check(&s, false, "undone back to the saved design"); + s.visibility.hidden_bodies.push("Body1".into()); + check(&s, true, "a body hidden"); + s.visibility.hidden_bodies.clear(); + check(&s, false, "shown again"); +} + /// Commands evaluated ahead (off the window thread) and then run for real take what was /// evaluated: on a design whose states are past the shared cache's budget the second run /// evaluated everything again, so an off-thread command cost twice its time. @@ -3514,14 +3920,14 @@ fn adopting_a_computed_component_keeps_its_warm_world_geometry() { run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10})); let mut computed = s.scratch(); run(&mut computed, "solid.box", json!({"length":5,"width":5,"height":5,"corner":[30,0,0]})); - let prepared = computed.world_state(); + let prepared = computed.world_state().unwrap(); for b in &prepared.bodies { let _ = b.mesh(); } s.accept_computed(computed); - assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state())); + assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state().unwrap())); s.invalidate_view(100); - assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state())); + assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state().unwrap())); } /// Every file command checked the size with the metadata and then read to the end. A character @@ -3656,14 +4062,14 @@ fn default_extrude_profiles_keep_even_depth_islands_and_separate_outlines() { /// The face of `body` whose normal points along +x, as a plane pick. fn side_face_pick(s: &Session, body: &str) -> Value { - let world = s.world_state(); + let world = s.world_state().unwrap(); let b = world.body(body).unwrap(); let face = b .body .faces(0.01) .unwrap() .into_iter() - .filter(|f| f.plane_normal.is_some_and(|n| n.dot(solidcraft_geom::Vec3::X) > 0.999)) + .filter(|f| f.plane_normal.is_some_and(|n| n.dot(solidcore_record::Vec3::X) > 0.999)) .max_by(|a, b| a.centroid.x.total_cmp(&b.centroid.x)) .unwrap(); json!({"body": b.name, "index": face.index, "face": [face.centroid.x, face.centroid.y, face.centroid.z]}) @@ -3683,7 +4089,7 @@ fn extruding_a_sketch_on_a_side_face_takes_the_whole_drawn_profile() { run(&mut s2, "solid.extrude", json!({"sketch": id, "distance": 5, "operation": "new", "body_name": "Rib", "profiles": selection.clone()})); let state = s2.model.state(); let rib = state.bodies.iter().find(|b| b.name == "Rib").unwrap(); - let v = rib.body.tessellate(1e-2).unwrap().measure().volume; + let v = rib.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume; assert!(rel(v, 500.0) < 1e-6, "{selection}: {v}"); } } @@ -3705,7 +4111,7 @@ fn a_pick_bounded_by_a_projected_rim_takes_only_that_region() { run(&mut s2, "solid.extrude", json!({"sketch": id, "distance": 5, "operation": "new", "body_name": "Pad", "profiles": [{"point": [12, 7]}]})); let state = s2.model.state(); let pad = state.bodies.iter().find(|b| b.name == "Pad").unwrap(); - let v = pad.body.tessellate(1e-2).unwrap().measure().volume; + let v = pad.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume; // The square with the hole's rim cut out of it, not the whole square. The mesh measures the // round rim as a polygon, so the volume is a little under the analytic one. let want = (400.0 - PI * 25.0) * 5.0; @@ -3735,7 +4141,7 @@ fn an_exact_pick_of_a_region_cut_by_the_face_outline_takes_only_that_region() { let state = s.model.state(); let ss = state.sketch(id).unwrap(); assert_eq!(ss.profiles.len(), 3, "the lens, the crescent past the face and the rest of the face"); - let at = |x: f64| ss.profiles.iter().position(|p| p.region.contains(solidcraft_geom::Vec2::new(x, 0.0))).unwrap(); + let at = |x: f64| ss.profiles.iter().position(|p| p.region.contains(solidcore_record::Vec2::new(x, 0.0))).unwrap(); let (on_face, past_face) = (at(7.0), at(14.0)); // The volume of the new body, and how many profiles its extrude is built from. let extrude = |extra: Value| -> (f64, usize) { @@ -3748,7 +4154,12 @@ fn an_exact_pick_of_a_region_cut_by_the_face_outline_takes_only_that_region() { let state = s2.model.state(); let Some(solidcraft_doc::FeatureKind::Extrude { profiles, .. }) = s2.doc.features.last().map(|f| &f.kind) else { panic!("an extrude") }; let count = solidcraft_doc::profile_selection_indices(state.sketch(id).unwrap(), profiles).unwrap().len(); - let v = state.bodies.iter().filter(|b| b.name.starts_with("Pad")).map(|b| b.body.tessellate(1e-2).unwrap().measure().volume).sum(); + let v = state + .bodies + .iter() + .filter(|b| b.name.starts_with("Pad")) + .map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume) + .sum(); (v, count) }; for (profiles, want, n) in [ @@ -4024,10 +4435,11 @@ fn extrude_reply_lists_the_bodies_it_created() { assert_eq!(r["created_bodies"], json!(["Ribs", "Ribs (2)", "Ribs (3)"]), "{r}"); } -/// A design saved before format 14 names the bodies past its stored names `BodyN`, as it did when -/// it was saved, so later features that name them still find them (#373). +/// A design saved before format 14 with fewer stored body names than bodies (#373) opens and +/// evaluates: the first body takes its stored name, and every body has a name of its own. (The +/// names the others had when it was saved are not promised.) #[test] -fn a_design_saved_before_format_14_keeps_generic_names_past_body_name() { +fn a_design_saved_before_format_14_with_fewer_body_names_opens_and_names_every_body() { let mut s = Session::default(); run(&mut s, "sketch.create", json!({"plane": "XY", "name": "R"})); for x in [0, 10, 20] { @@ -4045,11 +4457,33 @@ fn a_design_saved_before_format_14_keeps_generic_names_past_body_name() { std::fs::write(&design, legacy.to_string()).unwrap(); let mut old = Session::default(); run(&mut old, "doc.open", json!({"path": design.to_string_lossy()})); + assert!(old.model.results.iter().all(|r| r.error.is_none()), "{:?}", old.model.results); let names: Vec = old.model.state().bodies.iter().map(|b| b.name.clone()).collect(); - assert_eq!(names, ["Ribs", "Body1", "Body2"]); + assert_eq!((names.len(), names.first().map(String::as_str)), (3, Some("Ribs")), "{names:?}"); + assert_eq!(names.iter().collect::>().len(), 3, "{names:?}"); let _ = std::fs::remove_dir_all(&dir); } +/// R21 on the bottom front edge of a 50 x 50 x 20 block overflows the 20 mm front face (its circle +/// about (y, z) = (21, 21) reaches the top only at y = 21 - sqrt(440)) and goes first; the front +/// left upright, picked with it, lies wholly in what it removes (every (0, 0, z) is outside that +/// circle), so it is gone: not rounded, and the feature says so. The block is R21's alone: the +/// section loses 20 (21 - sqrt(440)) + int_0^sqrt(440) (21 - sqrt(441 - u^2)) du, along 50. +#[test] +fn fillet_edge_removed_by_a_larger_overflowing_round_is_noted() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 50, "width": 50, "height": 20})); + let out = run(&mut s, "solid.fillet", json!({"edges": [[25, 0, 0], [0, 0, 10]], "radius": 21, "tangent_chain": false, "name": "Round"})); + let w = 440f64.sqrt(); + let f = 0.5 * (w * (441.0 - w * w).sqrt() + 441.0 * (w / 21.0).asin()); + let lost = 20.0 * (21.0 - w) + 21.0 * w - f; + let want = 50.0 * 50.0 * 20.0 - 50.0 * lost; + assert!(rel(volume(&mut s), want) < 1e-9, "{} vs {want}", volume(&mut s)); + let id = out["feature"].as_u64().unwrap(); + let warning = s.model.result(id).and_then(|r| r.warning.clone()).unwrap_or_default(); + assert_eq!(warning, "the edge at (0, 0, 10) was removed by the larger round, so it is not rounded"); +} + #[test] fn fillet_fit_reduce_uses_the_largest_radius_that_fits() { // #293: 3.5 is too large for the 6 mm end faces of a 14 x 6 x 10 box; reduce gives 3 (a full @@ -4058,7 +4492,9 @@ fn fillet_fit_reduce_uses_the_largest_radius_that_fits() { run(&mut s, "parameters.add", json!({"name": "w", "expression": "6 mm"})); run(&mut s, "solid.box", json!({"length": 14, "width": "w", "height": 10, "corner": [14, 0, 0]})); let mids = json!([[14, 0, 5], [28, 0, 5], [14, 6, 5], [28, 6, 5]]); - assert!(s.execute("solid.fillet", &json!({"edges": mids, "radius": 3.5})).is_err()); + // The exact fit refuses it, naming the largest radius that fits. + let e = s.execute("solid.fillet", &json!({"edges": mids, "radius": 3.5})).unwrap_err().to_string(); + assert!(e.contains("the largest radius that fits is 3 mm"), "{e}"); let out = run(&mut s, "solid.fillet", json!({"edges": mids, "radius": 3.5, "fit": "reduce", "name": "Round"})); assert_eq!(out["radius_applied"].as_f64(), Some(3.0), "{out}"); let full = 840.0 - (4.0 - PI) * 9.0 * 10.0; @@ -4080,42 +4516,85 @@ fn fillet_fit_reduce_uses_the_largest_radius_that_fits() { assert!(s.execute("solid.fillet", &json!({"edges": mids, "radius": 1, "fit": "taper", "type": "chord"})).is_err()); } +/// A plate 15 high whose top narrows from 20 to `tip` mm along 40 mm (a wedge at 0), and, with +/// `wall`, a wall standing behind its slanted side from z = -15 to 30, which the plate's top and +/// bottom end on in concave edges: a blend of its front edges can't run past them. +fn tapering_plate(tip: f64, wall: bool) -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let pts = if tip > 0.0 { json!([[0, 0], [40, 0], [40, tip], [0, 20]]) } else { json!([[0, 0], [40, 0], [0, 20]]) }; + run(&mut s, "sketch.line", json!({"points": pts, "closed": true})); + run(&mut s, "solid.extrude", json!({"distance": 15})); + if wall { + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, -15], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})); + run(&mut s, "sketch.line", json!({"points": [[40, tip], [0, 20], [0, 30], [40, 30]], "closed": true})); + run(&mut s, "solid.extrude", json!({"distance": 45, "operation": "join"})); + assert_eq!(s.model.state().bodies.len(), 1); + } + s +} + +/// [`tapering_plate`]'s volume: the plate, and the wall's 20 (40 − tip) section along 45. +fn tapering_plate_volume(tip: f64, wall: bool) -> f64 { + (40.0 * (20.0 + tip) / 2.0) * 15.0 + if wall { 20.0 * (40.0 - tip) * 45.0 } else { 0.0 } +} + #[test] fn fillet_fit_taper_follows_the_room_along_the_edge() { - // #293: the top front edge of a plate whose top narrows from 20 to `tip` mm along 40 mm. - // At a 2 mm tip it can't take 3 mm; taper keeps 3 where it fits and comes down to 0.9 of the - // 2 mm there. With an 8 mm tip 3 fits and stays constant; a plate closing to a point - // tapers to 0. The warning says what was done. + // #293: the top front edge of a plate whose top narrows from 20 to `tip` mm along 40 mm, + // against a wall. At a 2 mm tip it can't take 3 mm; taper keeps 3 where it fits and comes + // down to 0.9 of the 2 mm there. With an 8 mm tip 3 fits and stays constant. The warning + // says what was done. let (k, edge) = (1.0 - PI / 4.0, json!([[20, 0, 15]])); - let plate = |tip: f64| { - let mut s = Session::default(); - run(&mut s, "sketch.create", json!({"plane": "XY"})); - let pts = if tip > 0.0 { json!([[0, 0], [40, 0], [40, tip], [0, 20]]) } else { json!([[0, 0], [40, 0], [0, 20]]) }; - run(&mut s, "sketch.line", json!({"points": pts, "closed": true})); - run(&mut s, "solid.extrude", json!({"distance": 15})); - s - }; let warning = |s: &Session, out: &Value| out["feature"].as_u64().and_then(|id| s.model.result(id)).and_then(|r| r.warning.clone()); - let mut s = plate(2.0); + let mut s = tapering_plate(2.0, true); assert!(s.execute("solid.fillet", &json!({"edges": edge, "radius": 3})).is_err()); let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"})); let w = warning(&s, &out).unwrap_or_default(); assert!(w.contains("tapers to the room on 1 of 1 edges, down to 1.8 mm"), "{w}"); // Between the material a constant 1.8 and a constant 3 would remove. - let (v, full) = (volume(&mut s), 40.0 * 22.0 / 2.0 * 15.0); + let (v, full) = (volume(&mut s), tapering_plate_volume(2.0, true)); assert!(v < full - k * 1.8 * 1.8 * 40.0 && v > full - k * 9.0 * 40.0, "{v}"); let json = serde_json::to_string(&s.doc.features).unwrap(); assert_eq!(json.matches("\"fit\":\"taper\"").count(), 1, "{json}"); - let mut s = plate(8.0); + let mut s = tapering_plate(8.0, true); let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"})); assert_eq!(warning(&s, &out), None); - assert!(rel(volume(&mut s), 40.0 * 28.0 / 2.0 * 15.0 - k * 9.0 * 40.0) < 2e-4); + assert!(rel(volume(&mut s), tapering_plate_volume(8.0, true) - k * 9.0 * 40.0) < 2e-4); - let mut s = plate(0.0); - let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 16, "fit": "taper"})); - let w = warning(&s, &out).unwrap_or_default(); + // Without the wall the 2 mm top's far edge is a cliff: R3 runs over it and is cut from the + // plate as if the top went on (the blend-overflow decision, 237f0ae74), so it fits and the + // taper leaves it constant. At x the plate's section is [0, w] × [0, 15], w = 20 − 0.45 x: + // the round takes its whole (1 − π/4)·9 where w >= 3, and where w < 3 the part of the + // 3 × 3 corner outside the circle about (3, 3) with s <= w, 3 w − (F(3) − F(3 − w)), + // F(v) = (v √(9 − v²) + 9 asin(v/3)) / 2. + let mut s = tapering_plate(2.0, false); + let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"})); + assert_eq!(warning(&s, &out), None); + let f = |v: f64| 0.5 * (v * (9.0 - v * v).max(0.0).sqrt() + 9.0 * (v / 3.0).asin()); + let n = 20000; + let taken: f64 = (0..n) + .map(|i| { + let w = 20.0 - 0.45 * 40.0 * (i as f64 + 0.5) / n as f64; + if w >= 3.0 { 9.0 * k } else { 3.0 * w - (f(3.0) - f(3.0 - w)) } + }) + .sum::() + * 40.0 + / n as f64; + let want = tapering_plate_volume(2.0, false) - taken; + assert!(rel(volume(&mut s), want) < 1e-6, "{} vs {want}", volume(&mut s)); +} + +#[test] +fn fillet_fit_taper_closes_to_a_point() { + // #293: a wedge against a wall, its top closing to a point at x = 40: no constant radius + // fits there, and taper comes down to 0 at the point. + let mut s = tapering_plate(0.0, true); + assert!(s.execute("solid.fillet", &json!({"edges": [[20, 0, 15]], "radius": 16})).is_err()); + let out = run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 15]], "radius": 16, "fit": "taper"})); + let w = out["feature"].as_u64().and_then(|id| s.model.result(id)).and_then(|r| r.warning.clone()).unwrap_or_default(); assert!(w.contains("on 1 of 1 edges, down to 0 mm"), "{w}"); } @@ -4123,10 +4602,7 @@ fn fillet_fit_taper_follows_the_room_along_the_edge() { fn spline_fillet_takes_over_a_taper() { // A tapered fillet keeps each edge's radius spline; given back as a `spline` fillet it makes // the same part, and its control radii are then the user's to change. - let mut s = Session::default(); - run(&mut s, "sketch.create", json!({"plane": "XY"})); - run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 2], [0, 20]], "closed": true})); - run(&mut s, "solid.extrude", json!({"distance": 15})); + let mut s = tapering_plate(2.0, true); let edge = json!([[20, 0, 15]]); let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"})); let id = out["feature"].as_u64().unwrap(); @@ -4152,29 +4628,54 @@ fn spline_fillet_takes_over_a_taper() { #[test] fn fillet_fit_reduce_keeps_the_radius_where_it_fits() { - // A 2 mm fin on a block: its top edge can't take 4, a corner of the block far from it can. - // Only the fin's edge is reduced; the reply gives each edge's radius. + // A 14 x 6 x 10 post on a block: its four vertical edges can't take 3.5 (two rounds on its + // 6 mm ends would cross), a corner of the block far from it can. Only the post's edges are + // reduced, to 3 (a full round); the reply gives each edge's radius. let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); - run(&mut s, "solid.box", json!({"length": 2, "width": 30, "height": 10, "corner": [19, 0, 20], "operation": "join"})); + run(&mut s, "solid.box", json!({"length": 14, "width": 6, "height": 10, "corner": [2, 2, 20], "operation": "join"})); assert_eq!(s.model.state().bodies.len(), 1); - let edges = json!([[21, 15, 30], [40, 0, 10]]); - let out = run(&mut s, "solid.fillet", json!({"edges": edges, "radius": 4, "fit": "reduce"})); - let fin = out["radius_applied"].as_f64().unwrap(); - assert!(fin < 4.0, "{out}"); + let post = [[2.0, 2.0, 25.0], [16.0, 2.0, 25.0], [2.0, 8.0, 25.0], [16.0, 8.0, 25.0]]; + let edges = json!([post[0], post[1], post[2], post[3], [40, 0, 10]]); + let out = run(&mut s, "solid.fillet", json!({"edges": edges, "radius": 3.5, "fit": "reduce"})); + assert_eq!(out["radius_applied"].as_f64(), Some(3.0), "{out}"); let each: Vec<(Vec, f64)> = out["radii_applied"] .as_array() .unwrap() .iter() .map(|x| (x["edge"].as_array().unwrap().iter().filter_map(Value::as_f64).collect(), x["radius"].as_f64().unwrap())) .collect(); - assert_eq!(each, [(vec![21.0, 15.0, 30.0], fin), (vec![40.0, 0.0, 10.0], 4.0)], "{out}"); - let removed = (1.0 - PI / 4.0) * (fin * fin * 30.0 + 16.0 * 20.0); - let want = 40.0 * 30.0 * 20.0 + 2.0 * 30.0 * 10.0 - removed; + let mut want_each: Vec<(Vec, f64)> = post.iter().map(|p| (p.to_vec(), 3.0)).collect(); + want_each.push((vec![40.0, 0.0, 10.0], 3.5)); + assert_eq!(each, want_each, "{out}"); + // The post's full round takes (4 − π)·9 of its section along its 10 mm height, the block's + // corner (1 − π/4)·3.5² along 20. + let removed = (4.0 - PI) * 9.0 * 10.0 + (1.0 - PI / 4.0) * 3.5 * 3.5 * 20.0; + let want = 40.0 * 30.0 * 20.0 + 14.0 * 6.0 * 10.0 - removed; assert!(rel(volume(&mut s), want) < 2e-4, "{} vs {want}", volume(&mut s)); let id = out["feature"].as_u64().unwrap(); let warning = s.model.result(id).and_then(|r| r.warning.clone()).unwrap_or_default(); - assert!(warning.contains("on 1 of 2 edges"), "{warning}"); + assert!(warning.contains("on 4 of 5 edges"), "{warning}"); +} + +/// A 2 mm fin's top edge at R4 runs over the fin's top, past its far edge (a cliff): it is cut +/// as if the top went on (the blend-overflow decision), so with `fit: reduce` nothing is reduced. +/// The fin's section loses the 4 x 4 square at its edge less the quarter disc about (17, 26) +/// inside the fin (x >= 19), as `fillet_max_each_reduces_only_where_the_radius_does_not_fit` +/// in the kernel finds it. +#[test] +fn fillet_fit_reduce_keeps_a_round_over_a_cliff() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut s, "solid.box", json!({"length": 2, "width": 30, "height": 10, "corner": [19, 0, 20], "operation": "join"})); + let out = run(&mut s, "solid.fillet", json!({"edges": [[21, 15, 30], [40, 0, 10]], "radius": 4, "fit": "reduce"})); + assert_eq!(out["radius_applied"].as_f64(), None, "{out}"); + let id = out["feature"].as_u64().unwrap(); + assert_eq!(s.model.result(id).and_then(|r| r.warning.clone()), None); + let disc = |a: f64| 0.5 * (a * (16.0 - a * a).max(0.0).sqrt() + 16.0 * (a / 4.0).asin()); + let removed = (2.0 * 4.0 - (disc(4.0) - disc(2.0))) * 30.0 + (1.0 - PI / 4.0) * 16.0 * 20.0; + let want = 40.0 * 30.0 * 20.0 + 2.0 * 30.0 * 10.0 - removed; + assert!(rel(volume(&mut s), want) < 1e-6, "{} vs {want}", volume(&mut s)); } #[test] @@ -4318,12 +4819,12 @@ fn a_side_drawn_in_two_collinear_pieces_extrudes_into_one_face() { assert_eq!(run(&mut s, "inspect.measure", json!({}))["bodies"][0]["kernel"]["faces"], 6); let names: Vec<&str> = f.iter().filter_map(|x| x["name"].as_str()).collect(); assert!(names.contains(&format!("F2:side:{}", pieces[0]).as_str()), "{names:?}"); - // The second piece's name answers for the same face, so a reference made when the side was - // two faces (an edge of the second piece) still finds its edge. + // The extrude made the side from both pieces: the second piece's role names that very face + // too, so an edge named after it is that edge. let st = s.model.state(); let body = st.body("Body1").unwrap(); let edge = format!("F2:side:{}|F2:top", pieces[1]); - let (at, _) = solidcraft_doc::naming::find_edge(body, &edge, geom::Vec3::new(15.0, 0.0, 5.0)).unwrap(); + let at = solidcraft_doc::naming::find_edge(body, &edge, solidcore_record::Vec3::new(15.0, 0.0, 5.0)).unwrap(); assert!(at.y.abs() < 1e-9 && (at.z - 5.0).abs() < 1e-9, "{edge} at {at:?}"); // A sketch attaches to the joined side as to any side. assert_eq!(run(&mut s, "sketch.create", json!({"plane": {"face": [15, 0, 2.5]}}))["attachment"], "exact_face"); @@ -4476,10 +4977,10 @@ fn renaming_a_body_later_features_change_evaluates_nothing() { assert_eq!(s.evaluations, 0, "nor do its undo and redo"); } -/// A body whose name later bodies' names are worked out from (`X` patterned into `X (2)`) is still -/// renamed by evaluating the design, so the copies follow it as they would on opening it. +/// A body whose name later bodies' names are worked out from (`X` patterned into `X (2)`) keeps +/// the same copies and face names as opening the renamed design. #[test] -fn renaming_a_body_whose_copies_take_its_name_evaluates_the_design() { +fn renaming_a_body_keeps_its_copies_consistent_with_rebuilding() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "X"})); run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["X"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20})); @@ -4489,6 +4990,9 @@ fn renaming_a_body_whose_copies_take_its_name_evaluates_the_design() { let mut fresh = Session::new((*s.doc).clone()); fresh.refresh(); assert_eq!(names(&fresh), names(&s)); + for (a, b) in fresh.model.state().bodies.iter().zip(&s.model.state().bodies) { + assert_eq!(solidcraft_doc::naming::face_names(a), solidcraft_doc::naming::face_names(b)); + } } /// #3044: on a design with thousands of bodies the cheap commands stay cheap: showing, hiding, @@ -4553,31 +5057,21 @@ fn creating_a_component_recomputes_nothing() { run(&mut s, "sketch.circle.center", json!({"center": [25, 25], "radius": 2})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch": "Post sketch", "to": [25, 25, 10], "operation": "new", "body_name": "Post"})); - // A plate whose top face loses its certificate: a patterned cut, a pad joined flush with - // the top, then one more cut. Extruding that face makes a sketch on a legacy face plane. + // A sketch on a face without a construction certificate: a face extrude on a plate, saved + // as a design from before face attachments were certified (no anchor), and reopened. run(&mut s, "solid.box", json!({"length": 100, "width": 100, "height": 10, "corner": [200, 0, 0], "operation": "new", "body_name": "Plate"})); - run( - &mut s, - "solid.cylinder", - json!({"diameter": 4, "height": 12, "base": [210, 10, -1], "operation": "cut", "targets": ["Plate"], "name": "Pilot"}), - ); - run( - &mut s, - "solid.pattern.rectangular", - json!({"features": ["Pilot"], "dir1": [1, 0, 0], "count1": 4, "spacing1": 20, "dir2": [0, 1, 0], "count2": 4, "spacing2": 20}), - ); - run(&mut s, "sketch.create", json!({"plane": "XY", "offset": "5 mm", "name": "Pad sketch"})); - run(&mut s, "sketch.rectangle.two_point", json!({"p0": [260, 60], "p1": [295, 95]})); - run(&mut s, "sketch.finish", json!({})); - run(&mut s, "solid.extrude", json!({"sketch": "Pad sketch", "distance": 5, "operation": "join", "targets": ["Plate"]})); - run(&mut s, "solid.box", json!({"length": 5, "width": 100, "height": 12, "corner": [199, 0, -1], "operation": "cut", "targets": ["Plate"]})); run(&mut s, "solid.extrude", json!({"face": [240, 40, 10], "distance": 1, "operation": "join", "name": "Face layer"})); - let legacy_face = s - .doc - .features - .iter() - .any(|f| matches!(&f.kind, solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: None, .. }, .. })); - assert!(legacy_face, "the face extrude's sketch is on a legacy face plane"); + let mut legacy = (*s.doc).clone(); + let mut legacy_face = false; + for f in &mut legacy.features { + if let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, .. }, .. } = &mut f.kind { + *anchor = None; + legacy_face = true; + } + } + assert!(legacy_face, "the face extrude's sketch is on a face plane"); + let mut s = Session::new(solidcraft_doc::Document::from_json(&legacy.to_json()).unwrap()); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "the legacy design evaluates"); for name in ["First", "Second"] { run(&mut s, "component.create", json!({"name": name})); assert_eq!(s.model.last_recomputed, 0, "creating {name} recomputed a feature"); @@ -4597,7 +5091,7 @@ fn parallel_pipe_large_nominals_support_shallow_and_thin_cylindrical_holes() { assert!(result.is_ok(), "{designation}, height={height}, depth={depth:?}: {result:?}"); let reopened = crate::Session::new(crate::doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!(reopened.model.results.iter().all(|r| r.error.is_none())); - let state = reopened.world_state(); + let state = reopened.world_state().unwrap(); assert_eq!(state.threads.len(), 1); assert_eq!(state.threads[0].designation, designation); assert!((state.threads[0].end - state.threads[0].start - depth.unwrap_or(height)).abs() < 1e-6); @@ -4623,7 +5117,7 @@ fn a_cut_leaves_hidden_bodies_alone() { run(&mut s, "solid.extrude", json!({"distance": 30, "direction": "negative", "operation": "cut"})); s }; - let vol = |s: &Session, name: &str| solidcraft_kernel::measure(&s.world_state().body(name).unwrap().body).unwrap().volume; + let vol = |s: &Session, name: &str| solidcraft_kernel::measure(&s.world_state().unwrap().body(name).unwrap().body).unwrap().volume; let full = 20.0 * 20.0 * 10.0; let mut hidden = setup(true); assert!((vol(&hidden, "Below") - full).abs() < 1e-6, "the hidden body is not cut"); @@ -4633,3 +5127,102 @@ fn a_cut_leaves_hidden_bodies_alone() { let shown = setup(false); assert!(vol(&shown, "Below") < full - 1.0 && vol(&shown, "Above") < full - 1.0, "with nothing hidden, both are cut"); } + +/// #2464: an extrude Join with no targets onto a plate with a hidden coincident copy changes the +/// shown plate only, and keeps the shown bodies as its participants. +#[test] +fn join_leaves_a_hidden_body_alone() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 5, "body_name": "Plate"})); + run(&mut s, "solid.move", json!({"bodies": ["Plate"], "copy": true})); + run(&mut s, "browser.visibility", json!({"items": ["Plate (2)"], "visible": false})); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 5, "name": "Rim"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [38, 38]})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [4, 4], "p1": [36, 36]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Rim", "profiles": [{"point": [3, 3]}], "distance": 3, "operation": "join"})); + let st = s.model.state(); + assert_eq!(st.bodies.len(), 2); + let v = |n: &str| solidcraft_kernel::measure(&st.body(n).unwrap().body).unwrap().volume; + assert!(rel(v("Plate"), 8816.0) < 1e-9 && rel(v("Plate (2)"), 8000.0) < 1e-9); + let f = s.doc.features.last().unwrap(); + assert_eq!(f.participants, vec!["Plate".to_string()]); + // Showing the copy again doesn't change the model. + run(&mut s, "browser.visibility", json!({"items": ["Plate (2)"], "visible": true})); + assert_eq!(s.model.state().bodies.len(), 2); +} + +/// A pre-command check that refuses one command id. +fn refusing(id: &'static str) -> CommandCheck { + std::sync::Arc::new(move |cmd: &str, _: &Value, _: &Session| if cmd == id { Err(format!("{cmd} is not allowed here")) } else { Ok(()) }) +} + +#[test] +fn without_a_command_check_every_command_runs() { + let mut s = Session::default(); + assert!(s.command_check().is_none()); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]})); + assert_eq!(s.doc.features.len(), 2); +} + +#[test] +fn a_command_check_refuses_a_command_and_leaves_the_design() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + s.set_command_check(Some(refusing("solid.box"))); + let doc = s.doc.clone(); + let (undo, revision) = (s.undo.len(), s.revision); + let r = s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]})); + match r { + Err(EngineError::Refused { cmd, reason }) => { + assert_eq!(cmd, "solid.box"); + assert_eq!(reason, "solid.box is not allowed here"); + } + other => panic!("expected a refusal, got {other:?}"), + } + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc), "the design is unchanged"); + assert_eq!((s.undo.len(), s.revision), (undo, revision)); + // Other commands still run, and the check stays with the session across new designs, + // scripts and previews. + run(&mut s, "file.new", json!({"name": "Next"})); + assert!(s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1})).is_err(), "kept by file.new"); + assert!(s.run_script(&json!([{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1}}])).is_err(), "scripts"); + assert!(s.preview(&[("solid.box".into(), json!({"length": 1, "width": 1, "height": 1}))]).is_err(), "previews"); + s.set_command_check(None); + run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1})); +} + +#[test] +fn a_command_check_can_count_the_features() { + const MAX: usize = 3; + let mut s = Session::default(); + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(String, Value)>::new())); + let log = seen.clone(); + s.set_command_check(Some(std::sync::Arc::new(move |cmd: &str, params: &Value, s: &Session| { + if let Ok(mut log) = log.lock() { + log.push((cmd.to_string(), params.clone())); + } + if cmd.starts_with("solid.") && s.doc.features.len() >= MAX { Err(format!("at most {MAX} features")) } else { Ok(()) } + }))); + for i in 0..MAX { + run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [i * 5, 0, 0]})); + } + let r = s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1, "corner": [50, 0, 0]})); + assert!(matches!(&r, Err(EngineError::Refused { .. })), "{r:?}"); + assert_eq!(r.err().map(|e| e.to_string()).as_deref(), Some("at most 3 features")); + assert_eq!(s.doc.features.len(), MAX); + // The check saw each command's id and parameters. + let seen = seen.lock().map(|l| l.clone()).unwrap_or_default(); + assert_eq!(seen.len(), MAX + 1); + assert!(seen.iter().all(|(id, p)| id == "solid.box" && p["length"] == 1)); +} + +#[test] +fn a_command_check_that_panics_refuses_the_command() { + let mut s = Session::default(); + s.set_command_check(Some(std::sync::Arc::new(|_: &str, _: &Value, _: &Session| -> std::result::Result<(), String> { panic!("host bug") }))); + let r = s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1})); + assert!(matches!(r, Err(EngineError::Internal(..))), "{r:?}"); + assert!(s.doc.features.is_empty()); +} diff --git a/crates/engine/src/tests/barrel_join.rs b/crates/engine/src/tests/barrel_join.rs new file mode 100644 index 000000000..a81aa6148 --- /dev/null +++ b/crates/engine/src/tests/barrel_join.rs @@ -0,0 +1,31 @@ +use super::*; + +/// A barrel joined under a plate's back edge, its ends flush with the sides of the leaf it hangs +/// from (#827 without its fillets): the join is exact, so the command's reply carries no warning, +/// and the barrel's ends stay in the leaf's sides. +#[test] +fn a_barrel_joined_between_the_sides_of_a_leaf_is_exact() { + let mut session = Session::default(); + run(&mut session, "solid.box", json!({"length": 40, "width": 20, "height": 6, "corner": [0, 0, 5], "body_name": "Plate"})); + run(&mut session, "solid.box", json!({"length": 14, "width": 10, "height": 6, "corner": [10, 10, 0], "operation": "join", "targets": ["Plate"]})); + let reply = run( + &mut session, + "solid.cylinder", + json!({"radius": 5, "height": 14, "axis": "X", "base": [10, 20, 0], "operation": "join", "targets": ["Plate"]}), + ); + assert!(reply["warning"].is_null(), "{reply}"); + let state = session.model.state(); + let plate = &state.body("Plate").unwrap().body; + assert_eq!(plate.shell_count(), 1); + assert!(plate.validity().is_empty(), "{:?}", plate.validity()); + // Every edge ends on a level along x of the plate, the leaf or the barrel. + for edge in plate.edges(1e-3).unwrap() { + for p in [edge.points.first(), edge.points.last()].into_iter().flatten() { + assert!([0., 10., 24., 40.].iter().any(|x| (p.x - x).abs() < 1e-9), "an edge ends at {p:?}"); + } + } + // A quarter of the barrel lies in the leaf. + let expected = 5500. + 0.75 * PI * 25. * 14.; + let actual = plate.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; + assert!(rel(actual, expected) < 1e-5, "{actual} vs {expected}"); +} diff --git a/crates/engine/src/tests/blend_fit.rs b/crates/engine/src/tests/blend_fit.rs index c3e682b0c..f8d570ad5 100644 --- a/crates/engine/src/tests/blend_fit.rs +++ b/crates/engine/src/tests/blend_fit.rs @@ -1,5 +1,6 @@ -//! #1080: a fillet or chamfer too large for the geometry beside its edge is refused, naming the -//! largest size that fits, and one that fits still builds. +//! #1080: a fillet or chamfer running past the faces beside its edge into an opening is built +//! as if the faces went on and cut by the opening (the blend-overflow decision, 237f0ae74), so it +//! never bridges it; one that stops short builds as it always did. use std::path::Path; @@ -21,15 +22,14 @@ fn chamfer_error(s: &Session) -> Option { /// The report's design: a 20 mm cube with a 10 mm square opening into each of three faces, /// then a 9 mm chamfer on the top edge over one side opening. The openings are 5 mm from the -/// edge, so the chamfer would cut through their rims. It is refused, naming 5 mm, and the part -/// is left as it was. +/// edge, so the chamfer runs over their rims: it is cut by them. Of its section, the triangle +/// y + (20 − z) <= 9 (area 40.5, along 20: 810), the two openings crossing it hold 80 each +/// (the rig's fillets/1080-chamfer-runs-into-openings-cut-by-them): 4000 − (810 − 160) = 3350. #[test] -fn chamfer_through_the_openings_is_refused() { +fn chamfer_through_the_openings_is_cut_by_them() { let mut s = open_fixture(); - let err = chamfer_error(&s).expect("the 9 mm chamfer cuts through two openings: it must be refused"); - assert!(err.contains("runs past the faces beside the edge"), "{err}"); - assert!(err.contains("the largest size that fits is 5 mm"), "{err}"); - assert!((volume(&mut s) - 4000.0).abs() < 1e-6, "the part stays as it was without the chamfer"); + assert_eq!(chamfer_error(&s), None); + assert!((volume(&mut s) - 3350.0).abs() < 1e-6, "{}", volume(&mut s)); } /// Sizes that stop short of the openings build, and take away exactly the chamfer's triangle @@ -44,3 +44,35 @@ fn chamfer_that_fits_still_builds() { assert!((volume(&mut s) - want).abs() < 1e-6, "{d} mm: {} (want {want})", volume(&mut s)); } } + +/// #199's bar, 14 x 6 x 10, its four upright edges rounded: past a full round of its 6 mm ends +/// the two rounds on each end would cross. Refused, naming 3 mm: the kernel's refusal carries a +/// size and the edge it was found for (`SolidError::FilletRefused`), and the message names the +/// edge. +#[test] +fn a_round_past_a_full_round_is_refused_naming_the_largest_that_fits_and_its_edge() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 14, "width": 6, "height": 10, "corner": [14, 0, 0]})); + let uprights = json!([[14, 0, 5], [28, 0, 5], [14, 6, 5], [28, 6, 5]]); + for r in [3.001, 3.5] { + let e = s.execute("solid.fillet", &json!({"edges": uprights, "radius": r})).unwrap_err().to_string(); + assert!(e.contains("the largest radius that fits is 3 mm"), "{r}: {e}"); + assert!(e.contains("allow, at the edge at ("), "{r}: {e}"); + assert_eq!(e.matches("that fits is").count(), 1, "{r}: {e}"); + } + assert!((volume(&mut s) - 840.0).abs() < 1e-6, "the part stays as it was"); +} + +/// A rib 4 mm wide: blends of its two top edges meet in its top's middle at 2 mm and past that +/// would cross each other. Refused as too large, naming the largest size that fits. +#[test] +fn blends_crossing_each_other_are_refused_naming_the_largest_that_fits() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 4, "height": 20})); + let edges = json!([[20, 0, 20], [20, 4, 20]]); + let e = s.execute("solid.chamfer", &json!({"edges": edges, "distance": 3})).unwrap_err().to_string(); + assert!(e.contains("the largest distance that fits is 2 mm"), "{e}"); + let e = s.execute("solid.fillet", &json!({"edges": edges, "radius": 3})).unwrap_err().to_string(); + assert!(e.contains("the largest radius that fits is 2 mm"), "{e}"); + assert!((volume(&mut s) - 3200.0).abs() < 1e-6, "the part stays as it was"); +} diff --git a/crates/engine/src/tests/boolean_diagnostics.rs b/crates/engine/src/tests/boolean_diagnostics.rs deleted file mode 100644 index 3d6435220..000000000 --- a/crates/engine/src/tests/boolean_diagnostics.rs +++ /dev/null @@ -1,84 +0,0 @@ -use super::*; -use solidcraft_kernel::BooleanStrategy; - -#[test] -fn boolean_retry_warning_and_details_survive_cache_undo_and_reopen() { - let slope = 1f64.to_radians().tan(); - let mut session = Session::default(); - run(&mut session, "sketch.create", json!({"plane":"XZ","name":"Floor section"})); - run(&mut session, "sketch.line", json!({"points":[[0,0],[100,0],[100,-10.-slope*100.],[0,-10.]],"closed":true})); - run(&mut session, "sketch.finish", json!({})); - run(&mut session, "solid.extrude", json!({"sketch":"Floor section","distance":80,"body_name":"Floor"})); - run(&mut session, "solid.cylinder", json!({"base":[50,40,-5],"radius":10,"height":30,"operation":"cut"})); - run(&mut session, "sketch.create", json!({"plane":"XY","name":"Ring section"})); - run(&mut session, "sketch.circle.center", json!({"center":[50,40],"radius":20})); - run(&mut session, "sketch.circle.center", json!({"center":[50,40],"radius":10})); - run(&mut session, "sketch.finish", json!({})); - run( - &mut session, - "solid.extrude", - json!({"sketch":"Ring section","profiles":[{"point":[65,40]}],"start_offset":-5,"distance":7,"body_name":"Ring"}), - ); - let id = run(&mut session, "solid.combine", json!({"target":"Floor","tools":["Ring"],"operation":"join"}))["feature"].as_u64().unwrap(); - let check = |session: &Session| { - let result = session.model.result(id).unwrap(); - assert!(result.error.is_none()); - assert!(result.warning.as_ref().is_some_and(|warning| warning.contains("Boolean retry:")), "{result:?}"); - assert!( - result.boolean_diagnostics.events.iter().any(|event| event.strategy == BooleanStrategy::CommonBore), - "{:?}", - result.boolean_diagnostics - ); - result.boolean_diagnostics.clone() - }; - let original = check(&session); - let expected = (10. + slope * 50.) * (8000. - PI * 100.) + PI * 300. * 5.; - assert!(rel(volume(&mut session), expected) < 2e-5); - let inspected = run(&mut session, "timeline.inspect", json!({"feature":id})); - assert_eq!(inspected["boolean_diagnostics"], serde_json::to_value(&original).unwrap()); - session.refresh(); - assert_eq!(check(&session), original); - run(&mut session, "edit.undo", json!({})); - run(&mut session, "edit.redo", json!({})); - assert_eq!(check(&session), original); - let reopened_doc = solidcraft_doc::Document::from_json(&session.doc.to_json()).unwrap(); - let reopened = Session::new(reopened_doc); - assert_eq!(check(&reopened), original); - // A later independent feature must not inherit the earlier retry's warning. - run(&mut session, "solid.box", json!({"corner":[200,0,0],"length":5,"width":5,"height":5})); - let last = session.model.results.last().unwrap(); - assert!(last.warning.is_none()); - assert!(last.boolean_diagnostics.events.is_empty()); -} - -/// A barrel joined under a plate's back edge, its ends flush with the sides of the leaf it hangs -/// from (#827 without its fillets): the join is exact, so the command's reply carries no Boolean -/// retry, and the barrel's ends stay in the leaf's sides (it is not nudged to make the join go). -#[test] -fn a_barrel_joined_between_the_sides_of_a_leaf_needs_no_retry() { - let mut session = Session::default(); - run(&mut session, "solid.box", json!({"length": 40, "width": 20, "height": 6, "corner": [0, 0, 5], "body_name": "Plate"})); - run(&mut session, "solid.box", json!({"length": 14, "width": 10, "height": 6, "corner": [10, 10, 0], "operation": "join", "targets": ["Plate"]})); - let reply = run( - &mut session, - "solid.cylinder", - json!({"radius": 5, "height": 14, "axis": "X", "base": [10, 20, 0], "operation": "join", "targets": ["Plate"]}), - ); - assert!(reply["warning"].is_null(), "{reply}"); - let result = session.model.result(reply["feature"].as_u64().unwrap()).unwrap(); - assert!(result.boolean_diagnostics.events.is_empty(), "{:?}", result.boolean_diagnostics); - let state = session.model.state(); - let plate = &state.body("Plate").unwrap().body; - assert_eq!(plate.shell_count(), 1); - assert!(plate.validity().is_empty(), "{:?}", plate.validity()); - // Every edge ends on a level along x of the plate, the leaf or the barrel. - for edge in plate.edges(1e-3).unwrap() { - for p in [edge.points.first(), edge.points.last()].into_iter().flatten() { - assert!([0., 10., 24., 40.].iter().any(|x| (p.x - x).abs() < 1e-9), "an edge ends at {p:?}"); - } - } - // A quarter of the barrel lies in the leaf. - let expected = 5500. + 0.75 * PI * 25. * 14.; - let actual = plate.tessellate(1e-4).unwrap().measure().volume; - assert!(rel(actual, expected) < 1e-5, "{actual} vs {expected}"); -} diff --git a/crates/engine/src/tests/component_frames.rs b/crates/engine/src/tests/component_frames.rs index 75d1d3794..88819dfc1 100644 --- a/crates/engine/src/tests/component_frames.rs +++ b/crates/engine/src/tests/component_frames.rs @@ -19,7 +19,7 @@ fn moved_component_picks_and_frames() { run(&mut s, "solid.box", json!({"corner": [20, 0, 0], "length": 10, "width": 4, "height": 4, "body_name": "ArmBody"})); run(&mut s, "component.activate", json!({"component": 0})); run(&mut s, "occurrence.move", json!({"occurrence": occ, "translate": [0, 50, 0]})); - let wbox = |s: &Session, b: &str| s.world_state().body(b).unwrap().mesh().bounds(); + let wbox = |s: &Session, b: &str| s.world_state().unwrap().body(b).unwrap().mesh().bounds(); let vol = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["total"]["volume_mm3"].as_f64().unwrap(); // Root active: a fillet picked at the moved edge in the world. run(&mut s, "solid.fillet", json!({"edges": [[25, 54, 4]], "radius": 1})); @@ -40,7 +40,7 @@ fn moved_component_picks_and_frames() { // A pasted instance: a pick on it lands on the shared definition. run(&mut s, "occurrence.copy", json!({"component": cid, "translate": [0, 20, 0]})); let v0 = vol(&mut s, "ArmBody"); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); let inst = names.iter().find(|n| n.starts_with("ArmBody (")).cloned().unwrap(); let ib = wbox(&s, &inst); // Its bottom edge along x at the far side (y max, z 0). @@ -71,7 +71,7 @@ fn extrude_in_a_moved_component_from_a_root_sketch() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "component.activate", json!({"component": jaw})); run(&mut s, "solid.extrude", json!({"sketch": "Tab", "distance": 10, "operation": "join", "targets": ["Jaw"]})); - let b = s.world_state().body("Jaw").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Jaw").unwrap().mesh().bounds(); let near = |a: f64, e: f64| (a - e).abs() < 1e-6; assert!(near(b.min.x, 0.0) && near(b.max.x, 40.0) && near(b.min.y, -5.0) && near(b.max.y, 7.0), "{b:?}"); let v = run(&mut s, "inspect.measure", json!({"bodies": ["Jaw"]}))["total"]["volume_mm3"].as_f64().unwrap(); @@ -101,7 +101,7 @@ fn extrude_to_a_face_in_a_moved_component() { run(&mut s, "component.activate", json!({"component": jaw})); // Up to the jaw's top face, picked in the world at its middle: the tab rises from z 0 to 15. run(&mut s, "solid.extrude", json!({"sketch": "Tab", "to": [20, 0, 15], "operation": "join", "targets": ["Jaw"]})); - let b = s.world_state().body("Jaw").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Jaw").unwrap().mesh().bounds(); let near = |a: f64, e: f64| (a - e).abs() < 1e-6; assert!( near(b.min.x, 0.0) && near(b.max.x, 40.0) && near(b.min.y, -5.0) && near(b.max.y, 7.0) && near(b.min.z, 0.0) && near(b.max.z, 15.0), @@ -175,7 +175,7 @@ fn extrude_from_a_slanted_face_in_another_moved_component() { "solid.extrude", json!({"sketch": "Pad", "from": [0, 5, -20], "distance": 4, "direction": "negative", "operation": "new", "body_name": "Leg"}), ); - let b = s.world_state().body("Leg").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Leg").unwrap().mesh().bounds(); assert!((b.max.z + 22.5).abs() < 1e-6 && (b.min.z + 26.5).abs() < 1e-6, "{b:?}"); } @@ -220,14 +220,14 @@ fn revolve_to_a_cylinder_in_another_moved_component() { "solid.revolve", json!({"sketch": "Profile", "axis": {"origin": [0, 0, 0], "dir": [0, 0, 1]}, "to": to, "operation": "new", "body_name": "Arc"}), ); - let world = s.world_state(); + let world = s.world_state().unwrap(); let arc = &world.body("Arc").unwrap().body; let post = &world.body("PostBody").unwrap().body; let overlap = solidcraft_kernel::boolean(arc, post, solidcraft_kernel::BoolOp::Intersect).unwrap(); assert!(overlap.is_none_or(|b| solidcraft_kernel::measure(&b).unwrap().volume < 1e-3), "the arc runs into the post"); // Past the picked point's angle (29°) on the inner side, where the post leaves room. let at = |r: f64, deg: f64| Vec3::new(r * deg.to_radians().cos(), r * deg.to_radians().sin(), -2.5); - assert!(arc.contains(at(10.2, 35.0)), "the arc is not cut back to the post's surface"); + assert_eq!(arc.classify_point(at(10.2, 35.0)).unwrap(), solidcraft_kernel::PointClass::Inside, "the arc is not cut back to the post's surface"); } /// A To Object pick is named after the face it is on, the nearest one, even when a face of a @@ -255,7 +255,7 @@ fn extrude_to_names_the_face_it_is_on() { "solid.extrude", json!({"sketch": "Pad", "distance": "1 mm", "direction": "negative", "to": [5, 5, -20], "operation": "new", "body_name": "Leg"}), ); - let b = s.world_state().body("Leg").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Leg").unwrap().mesh().bounds(); assert!((b.min.z + 20.0).abs() < 1e-9 && b.max.z.abs() < 1e-9, "moved {moved}: {b:?}"); } } diff --git a/crates/engine/src/tests/curved_seam_round.rs b/crates/engine/src/tests/curved_seam_round.rs index 5eda74568..107b5881f 100644 --- a/crates/engine/src/tests/curved_seam_round.rs +++ b/crates/engine/src/tests/curved_seam_round.rs @@ -8,7 +8,7 @@ use std::f64::consts::PI; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use super::*; @@ -52,7 +52,7 @@ fn core(p: Vec3) -> f64 { /// vertices were looked at and the worst error of that distance. fn off_the_ball(s: &Session, round: f64) -> (usize, f64) { let body = &s.model.state().bodies[0].body; - let mesh = body.tessellate(0.01).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); let centres: Vec = (0..720) .map(|i| { let a = 2.0 * PI * i as f64 / 720.0; diff --git a/crates/engine/src/tests/flush_join_loft.rs b/crates/engine/src/tests/flush_join_loft.rs index 18598e5da..eb38e00cf 100644 --- a/crates/engine/src/tests/flush_join_loft.rs +++ b/crates/engine/src/tests/flush_join_loft.rs @@ -93,7 +93,7 @@ fn a_flange_flush_with_the_end_of_a_bent_tapered_tube_joins() { assert!(body.validity().is_empty(), "{:?}", body.validity()); assert_eq!(body.lumps().unwrap().len(), 1); let (origin, normal) = (Vec3::new(BEND * TURN.sin(), BEND * (1.0 - TURN.cos()), 0.0), Vec3::new(TURN.cos(), TURN.sin(), 0.0)); - let mesh = body.tessellate(0.05).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap(); let beyond = mesh.positions.iter().map(|p| (*p - origin).dot(normal)).fold(f64::MIN, f64::max); assert!(beyond < 1e-3, "the join reaches {beyond} mm past the end plane"); } diff --git a/crates/engine/src/tests/gltf_import.rs b/crates/engine/src/tests/gltf_import.rs index 16c3ecc41..7951aa63a 100644 --- a/crates/engine/src/tests/gltf_import.rs +++ b/crates/engine/src/tests/gltf_import.rs @@ -62,6 +62,7 @@ impl Cube { fn shown_boxes(s: &Session) -> Vec<[i64; 6]> { let mut out: Vec<[i64; 6]> = s .world_state() + .unwrap() .bodies .iter() .map(|b| { diff --git a/crates/engine/src/tests/import_component.rs b/crates/engine/src/tests/import_component.rs index 826cb92fe..d35f6f61c 100644 --- a/crates/engine/src/tests/import_component.rs +++ b/crates/engine/src/tests/import_component.rs @@ -5,7 +5,8 @@ //! imports sit loose in a component open and rebuild as they did. use serde_json::{Value, json}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Aabb3; use solidcraft_kernel::{ExportBody, ExportProduct, StepHeader, box_solid, step_export_products}; use super::run; @@ -80,7 +81,7 @@ fn key(b: solidcraft_geom::Aabb3) -> [i64; 6] { /// Where the design shows its bodies, sorted. fn shown_boxes(s: &Session) -> Vec<[i64; 6]> { - let mut out: Vec<[i64; 6]> = s.world_state().bodies.iter().map(|b| key(solidcraft_kernel::measure(&b.body).unwrap().bbox)).collect(); + let mut out: Vec<[i64; 6]> = s.world_state().unwrap().bodies.iter().map(|b| key(solidcraft_kernel::measure(&b.body).unwrap().bbox)).collect(); out.sort(); out } @@ -112,7 +113,7 @@ fn corner_of(s: &Session, occurrence: &str) -> Vec3 { }; let names = s.occurrence_bodies(&path, true).unwrap(); assert!(!names.is_empty()); - let world = s.world_state(); + let world = s.world_state().unwrap(); world.bodies.iter().filter(|b| names.contains(&b.name)).fold(Aabb3::EMPTY, |a, b| a.union(&solidcraft_kernel::measure(&b.body).unwrap().bbox)).min } @@ -288,7 +289,7 @@ fn undo_takes_the_whole_import_away() { run(&mut s, "edit.undo", json!({})); assert!(s.doc.features.is_empty() && s.doc.components.is_empty() && s.doc.occurrences.is_empty(), "nothing left"); assert!(s.doc.assembly.joints.is_empty() && s.doc.body_components.is_empty() && s.doc.body_offsets.is_empty()); - assert!(s.world_state().bodies.is_empty()); + assert!(s.world_state().unwrap().bodies.is_empty()); run(&mut s, "edit.redo", json!({})); assert_eq!(shown_boxes(&s), file_boxes(&path)); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/tests/large_step_import.rs b/crates/engine/src/tests/large_step_import.rs index ce4b74bfc..3a9fb3d5f 100644 --- a/crates/engine/src/tests/large_step_import.rs +++ b/crates/engine/src/tests/large_step_import.rs @@ -11,8 +11,8 @@ use crate::*; fn step_file(name: &str, count: usize) -> String { let bodies: Vec<_> = (0..count) .map(|i| { - let at = solidcraft_geom::Vec3::new((i % 32) as f64 * 12.0, (i / 32) as f64 * 12.0, 0.0); - solidcraft_kernel::box_solid(at, at + solidcraft_geom::Vec3::new(10.0, 10.0, 10.0)).unwrap() + let at = solidcore_record::Vec3::new((i % 32) as f64 * 12.0, (i / 32) as f64 * 12.0, 0.0); + solidcraft_kernel::box_solid(at, at + solidcore_record::Vec3::new(10.0, 10.0, 10.0)).unwrap() }) .collect(); let text = solidcraft_kernel::step_export(&bodies.iter().collect::>(), name).unwrap(); diff --git a/crates/engine/src/tests/loft_cut.rs b/crates/engine/src/tests/loft_cut.rs deleted file mode 100644 index 7bb5dcf30..000000000 --- a/crates/engine/src/tests/loft_cut.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! A hollow elbow: a tube lofted from round sections along an arc, minus a narrower tube lofted the -//! same way (and running 5 mm past both ends, so the cut opens the ends). -//! -//! The boolean gave up with "no result" for some section counts and not for their neighbours: the -//! points of the intersection curves lie on the seam between the two halves of a loft's circle, -//! where truck's search for their parameters (from the previous point's) failed. - -use std::f64::consts::PI; - -use super::*; - -/// `sections` circles of radius `radius` centred on an arc of radius `path` turning `angle` -/// (radians), in planes normal to the arc, lofted into the body `body`; `over` extends the -/// sections past both ends along the tangent. -fn tube(s: &mut Session, body: &str, radius: f64, path: f64, angle: f64, sections: usize, over: f64) { - let mut stations: Vec<[f64; 4]> = (0..sections) - .map(|i| { - let t = angle * i as f64 / (sections - 1) as f64; - [path * t.cos(), path * t.sin(), -t.sin(), t.cos()] - }) - .collect(); - if over > 0.0 { - let (a, b) = (stations[0], stations[sections - 1]); - stations.insert(0, [a[0] - over * a[2], a[1] - over * a[3], a[2], a[3]]); - stations.push([b[0] + over * b[2], b[1] + over * b[3], b[2], b[3]]); - } - let mut list = Vec::new(); - for (i, [x, y, tx, ty]) in stations.iter().enumerate() { - let name = format!("{body}{i}"); - run(s, "sketch.create", json!({"plane": {"origin": [x, y, 0], "x_dir": [0, 0, 1], "y_dir": [ty, -tx, 0]}, "name": name})); - run(s, "sketch.circle.center", json!({"center": [0, 0], "radius": radius})); - run(s, "sketch.finish", json!({})); - list.push(json!({"sketch": name})); - } - run(s, "solid.loft", json!({"sections": list, "operation": "new", "name": format!("Loft{body}"), "body_name": body})); -} - -#[test] -fn a_hollow_elbow_cut_from_two_lofted_tubes() { - let (path, outer, inner) = (100.0, 30.0, 18.0); - // Each of these gave up in truck's `parameter boundary` step. - for (degrees, sections) in [(60.0, 5), (60.0, 7), (90.0, 10), (120.0, 7), (120.0, 13)] { - let angle = degrees * PI / 180.0; - let mut s = Session::default(); - tube(&mut s, "Outer", outer, path, angle, sections, 0.0); - tube(&mut s, "Inner", inner, path, angle, sections, 5.0); - run(&mut s, "solid.combine", json!({"target": "Outer", "tools": ["Inner"], "operation": "cut", "name": "Hollow"})); - assert_eq!(s.model.state().bodies.len(), 1, "{degrees} degrees, {sections} sections"); - let want = PI * (outer * outer - inner * inner) * path * angle; - let got = volume(&mut s); - assert!(rel(got, want) < 3e-3, "{degrees} degrees, {sections} sections: {got} vs {want}"); - } -} diff --git a/crates/engine/src/tests/loft_ring.rs b/crates/engine/src/tests/loft_ring.rs index 8438829da..9c2e2eac1 100644 --- a/crates/engine/src/tests/loft_ring.rs +++ b/crates/engine/src/tests/loft_ring.rs @@ -37,7 +37,7 @@ fn a_ring_section_keeps_its_hole_and_rejects_a_disc() { for face in 0..body.body.face_count() { assert!(solidcraft_doc::naming::face_name_exact(body, face), "face {face} lost its sketch-curve provenance"); } - assert!(!body.body.tessellate(0.001).unwrap().contains(solidcraft_geom::Vec3::new(0.0, 0.0, 10.0))); + assert!(!body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(solidcore_record::Vec3::new(0.0, 0.0, 10.0))); run(&mut s, "edit.undo", json!({})); assert!(s.model.state().bodies.is_empty()); run(&mut s, "edit.redo", json!({})); diff --git a/crates/engine/src/tests/mesh_convert.rs b/crates/engine/src/tests/mesh_convert.rs index 959d9ef81..d2ed9a884 100644 --- a/crates/engine/src/tests/mesh_convert.rs +++ b/crates/engine/src/tests/mesh_convert.rs @@ -1,10 +1,10 @@ use super::*; +use solidcore_record::Vec3; use solidcraft_doc::{Document, FeatureKind, MeshData}; -use solidcraft_geom::Vec3; fn imported_box() -> Session { let body = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); - let mesh = body.tessellate(0.01).unwrap(); + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); let mut doc = Document::default(); doc.add_feature( FeatureKind::MeshImport { @@ -141,7 +141,8 @@ fn exported_binary_stl_with_a_bore_reconstructs_analytic_faces() { assert!(!body.is_mesh()); assert!(body.validity().is_empty()); assert_eq!(solidcraft_kernel::measure(body).unwrap().merged.face_types.get("cylinder"), Some(&1)); - assert_eq!(body.faces(0.01).unwrap().len(), 10); + // The L's six sides, the two caps and the bore, one full-turn wall. + assert_eq!(body.faces(0.01).unwrap().len(), 9); std::fs::remove_file(path).unwrap(); } @@ -504,8 +505,31 @@ fn open_in_easyprint_hands_the_host_a_3mf_or_an_stl_that_reads_back() { let seen = seen.lock().unwrap(); assert_eq!((seen[0].0.ends_with(".3mf"), seen[1].0.ends_with(".stl")), (true, true), "{:?}", seen.iter().map(|u| &u.0).collect::>()); assert!(seen[0].1.starts_with(b"PK"), "a 3MF is a zip"); - // A binary STL: 80-byte header, a count, 50 bytes a triangle, and a box has 12. - assert_eq!(seen[1].1.len(), 84 + 50 * 12); + // The STL reads back as the imported mesh: its triangles, closed (every side shared by two + // triangles, each way once), enclosing the 10 × 20 × 30 box's 6000 mm³. + let imported = match &s.doc.features[0].kind { + FeatureKind::MeshImport { meshes, .. } => meshes[0].triangles.len() / 3, + other => panic!("{other:?}"), + }; + let tris = solidcraft_io::read_stl(&seen[1].1).unwrap(); + assert_eq!(tris.len(), imported); + let key = |p: [f32; 3]| p.map(f32::to_bits); + let mut sides = std::collections::HashMap::<_, i32>::new(); + for t in &tris { + for i in 0..3 { + let (a, b) = (key(t[i]), key(t[(i + 1) % 3])); + *sides.entry(if a < b { (a, b) } else { (b, a) }).or_default() += if a < b { 1 } else { -1 }; + } + } + assert!(sides.values().all(|n| *n == 0), "an open or inconsistently wound STL"); + let at = |p: [f32; 3]| Vec3::new(p[0].into(), p[1].into(), p[2].into()); + let volume: f64 = tris.iter().map(|t| at(t[0]).dot(at(t[1]).cross(at(t[2]))) / 6.0).sum(); + assert!((volume - 6000.0).abs() < 1e-6, "{volume}"); + let (lo, hi) = tris + .iter() + .flatten() + .fold(([f32::MAX; 3], [f32::MIN; 3]), |(lo, hi), p| (std::array::from_fn(|i| lo[i].min(p[i])), std::array::from_fn(|i| hi[i].max(p[i])))); + assert_eq!((lo, hi), ([0.0; 3], [10.0, 20.0, 30.0])); } #[test] diff --git a/crates/engine/src/tests/mirror_placed.rs b/crates/engine/src/tests/mirror_placed.rs index 68ee1a398..9b6f2ac41 100644 --- a/crates/engine/src/tests/mirror_placed.rs +++ b/crates/engine/src/tests/mirror_placed.rs @@ -3,13 +3,13 @@ //! geometry and put the copy in the active component, so the copy lost the placement. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use super::run; use crate::*; fn world_box(s: &Session, body: &str) -> (Vec3, Vec3) { - let b = s.world_state().body(body).unwrap_or_else(|| panic!("no body `{body}`")).mesh().bounds(); + let b = s.world_state().unwrap().body(body).unwrap_or_else(|| panic!("no body `{body}`")).mesh().bounds(); (b.min, b.max) } @@ -56,7 +56,7 @@ fn a_further_instance_is_mirrored_at_its_own_placement() { let mut s = Session::default(); let (component, _) = moved_arm(&mut s); run(&mut s, "occurrence.copy", json!({"component": component, "translate": [0, 0, 40]})); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); let instance = names.iter().find(|n| n.starts_with("ArmBody (")).cloned().unwrap(); let r = run(&mut s, "solid.mirror", json!({"bodies": ["ArmBody", instance], "plane": "YZ"})); let copies: Vec = r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect(); @@ -230,5 +230,173 @@ fn a_placement_leading_to_another_component_is_reported_lost() { s.refresh(); let e = s.model.result(mirror).and_then(|r| r.error.clone()).unwrap_or_else(|| panic!("mirrored at the wrong placement")); assert!(e.contains("no longer exists"), "{e}"); - assert!(s.world_state().body(©).is_none()); + assert!(s.world_state().unwrap().body(©).is_none()); +} + +/// A carriage-like part (a bored block and a ring) placed once, free to move: its occurrence and +/// body names. +fn curved_part(s: &mut Session) -> (u64, Vec) { + let c = run(s, "component.create", json!({"name": "Carriage", "grounded": false})); + run(s, "solid.box", json!({"length": 20, "width": 10, "height": 10, "corner": [10, 5, 0], "body_name": "Block"})); + run(s, "solid.cylinder", json!({"base": [20, 10, -1], "radius": 3, "height": 12, "operation": "cut", "targets": ["Block"]})); + run(s, "solid.torus", json!({"center": [20, 10, 20], "major": 6, "minor": 2, "operation": "new", "body_name": "Ring"})); + run(s, "component.activate", json!({"component": 0})); + run(s, "occurrence.move", json!({"occurrence": c["occurrence"], "translate": [0, 7, 3]})); + (c["occurrence"].as_u64().unwrap(), vec!["Block".into(), "Ring".into()]) +} + +/// The shown bodies drawn, as a viewport does, and the tessellation that took. +fn drawn(s: &Session) -> f64 { + let world = s.world_state().unwrap(); + let (_, work) = solidcraft_kernel::profile::capture(|| { + for b in &world.bodies { + b.mesh_in_place(); + b.display_plan(); + b.mesh(); + } + }); + work.tessellate_ms +} + +/// What the viewport shows is what a fresh evaluation of the design shows: where the triangles +/// are, which way they face and which faces and edges they belong to. +fn assert_as_evaluated_afresh(s: &Session) { + let mut fresh = solidcraft_doc::Model::new(); + fresh.no_cache = true; + fresh.evaluate(&s.doc); + assert!(fresh.results.iter().all(|r| r.error.is_none())); + let (shown, want) = (s.world_state().unwrap(), solidcraft_doc::world_state(&s.doc, &fresh.state()).unwrap()); + assert_eq!(shown.bodies.len(), want.bodies.len()); + for (a, b) in shown.bodies.iter().zip(&want.bodies) { + assert_eq!(a.name, b.name); + let (x, y) = (a.mesh(), b.mesh()); + assert_eq!(x.triangles, y.triangles, "{}", a.name); + assert_eq!(x.tri_face, y.tri_face, "{}", a.name); + assert_eq!(x.edge_faces, y.edge_faces, "{}", a.name); + assert_eq!(x.seams, y.seams, "{}", a.name); + assert_eq!(x.positions.len(), y.positions.len(), "{}", a.name); + assert!(x.edges.iter().flatten().zip(y.edges.iter().flatten()).all(|(p, q)| p.dist(*q) < 1e-7), "{}: edges", a.name); + assert_same_surface(&x, &y, &a.name); + // A plan's ties fall by the pose it was made at. + let (x, y) = (a.display_plan().unwrap().evaluate(), b.display_plan().unwrap().evaluate()); + assert_eq!(x.triangles.len(), y.triangles.len(), "{}: plan", a.name); + assert_same_surface(&x, &y, &a.name); + } +} + +/// Two meshes of one surface, facing the same way. Their points can differ: a revolved face is +/// turned by where it stands when it is made, which only moves where the surface is sampled. +fn assert_same_surface(x: &solidcraft_geom::Mesh, y: &solidcraft_geom::Mesh, name: &str) { + let enclosed = |m: &solidcraft_geom::Mesh| { + m.triangles.iter().fold((0.0, 0.0), |(v, s), t| { + let [a, b, c] = t.map(|i| m.positions[i as usize]); + (v + a.dot(b.cross(c)) / 6.0, s + (b - a).cross(c - a).len() / 2.0) + }) + }; + let ((v, s), (w, t)) = (enclosed(x), enclosed(y)); + assert!(v > 0.0 && (v - w).abs() < 1e-4 * w && (s - t).abs() < 1e-4 * t, "{name}: encloses {v}, {s} against {w}, {t}"); + let (a, b) = (x.bounds(), y.bounds()); + assert!(a.min.dist(b.min) < 0.05 && a.max.dist(b.max) < 0.05, "{name}: {a:?} against {b:?}"); +} + +/// Dragging a part with a mirrored copy moved the copy too, and every frame meshed the copy from +/// nothing: a design with a few dozen curved mirrored bodies dragged at a frame or two a second. +#[test] +fn dragging_a_mirrored_part_meshes_its_copies_once() { + let mut s = Session::default(); + let (occurrence, bodies) = curved_part(&mut s); + let first = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + // Mirrored again, as four carriages from one are: the source of these copies moves as well. + run(&mut s, "solid.mirror", json!({"bodies": first["created_bodies"], "plane": "YZ"})); + drawn(&s); + for k in 1..=4 { + let at = f64::from(k) * 3.5; + run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [1, at, 2], "continuous": true})); + assert!(s.model.last_recomputed > 0, "the copies follow the part"); + assert_eq!(drawn(&s), 0.0, "frame {k}: the copies are drawn from triangles already made"); + } + assert_as_evaluated_afresh(&s); + run(&mut s, "edit.undo", json!({})); + assert_as_evaluated_afresh(&s); +} + +/// What the viewport draws of a copy doesn't reach what the model reads: a later feature finds +/// the copy's own triangles, as it does in a design opened afresh. +#[test] +fn a_mirrored_copys_shared_triangles_are_display_only() { + let mut s = Session::default(); + let (occurrence, bodies) = curved_part(&mut s); + let r = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [0, 3, 0], "continuous": true})); + drawn(&s); + let (state, world) = (s.model.state(), s.world_state().unwrap()); + for copy in r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap()) { + assert!(world.body(copy).is_some_and(|b| b.cached_mesh().is_some()), "{copy} was drawn"); + assert!(state.body(copy).unwrap().cached_mesh().is_none(), "{copy}: the model's own mesh is its own"); + } +} + +/// A source changed is mirrored from what it is now, not from the triangles of what it was. +#[test] +fn a_changed_source_gives_its_copy_new_triangles() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "side", "expression": "10 mm"})); + let c = run(&mut s, "component.create", json!({"name": "Part", "grounded": false})); + run(&mut s, "solid.box", json!({"length": "side", "width": 10, "height": 10, "corner": [10, 0, 0], "body_name": "Block"})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "occurrence.move", json!({"occurrence": c["occurrence"], "translate": [0, 20, 0]})); + let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "XZ"}))); + assert_box(world_box(&s, ©), (Vec3::new(10.0, -30.0, 0.0), Vec3::new(20.0, -20.0, 10.0))); + run(&mut s, "parameters.change", json!({"name": "side", "expression": "15 mm"})); + assert_box(world_box(&s, ©), (Vec3::new(10.0, -30.0, 0.0), Vec3::new(25.0, -20.0, 10.0))); + assert_as_evaluated_afresh(&s); +} + +/// Copies nothing builds on skip the search that readies their revolved faces for a boolean. +/// A feature added later that does build on them gets them readied, as a design opened with that +/// feature has them, whether or not they were mirrored first. +#[test] +fn a_cut_added_after_a_mirror_finds_its_copies_readied() { + let cut = |s: &mut Session, copy: &str| { + run(s, "solid.cylinder", json!({"base": [20, -17, 15], "radius": 3, "height": 12, "operation": "cut", "targets": [copy]})); + }; + let mut s = Session::default(); + let (_, bodies) = curved_part(&mut s); + let copies = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + let ring = copies["created_bodies"][1].as_str().unwrap().to_string(); + let evaluated = s.model.recomputed; + cut(&mut s, &ring); + assert!(s.model.results.iter().all(|r| r.error.is_none())); + assert!(s.model.recomputed - evaluated >= 2, "the mirror is evaluated again with the cut"); + let measured = |s: &Session| { + let v = run(&mut s.scratch(), "inspect.measure", json!({"bodies": [ring]})); + v["total"]["volume_mm3"].as_f64().unwrap() + }; + let volume = measured(&s); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert_eq!(measured(&reopened), volume, "what evaluates here is what opens"); +} + +/// A part inserted after the mirror keeps its meshes while the mirror moves: evaluating the +/// insert again gives the same solids, and meshing them was as slow as meshing the copies. +#[test] +fn an_insert_after_a_mirror_keeps_its_meshes_through_a_drag() { + let dir = std::env::temp_dir().join(format!("solidcraft-mirror-insert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("insert.step").to_string_lossy().replace('\\', "/"); + let mut part = Session::default(); + run(&mut part, "solid.sphere", json!({"radius": 5})); + run(&mut part, "file.export", json!({"path": file})); + let mut s = Session::default(); + let (occurrence, bodies) = curved_part(&mut s); + run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + run(&mut s, "file.insert_step", json!({"path": file, "name": "After"})); + let _ = std::fs::remove_dir_all(&dir); + run(&mut s, "component.activate", json!({"component": 0})); + drawn(&s); + for k in 1..=3 { + run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [0, f64::from(k), 0], "continuous": true})); + assert_eq!(drawn(&s), 0.0, "frame {k}"); + } + assert_as_evaluated_afresh(&s); } diff --git a/crates/engine/src/tests/native_cad_import.rs b/crates/engine/src/tests/native_cad_import.rs index 0e0b2ce41..d313fccf1 100644 --- a/crates/engine/src/tests/native_cad_import.rs +++ b/crates/engine/src/tests/native_cad_import.rs @@ -19,7 +19,7 @@ fn file(tag: &str, name: &str, bytes: &[u8]) -> (std::path::PathBuf, String) { } fn extent(s: &Session) -> ([f64; 3], [f64; 3]) { - let b = crate::view::bounds(s); + let b = crate::view::bounds(s).unwrap(); ([b.min.x, b.min.y, b.min.z], [b.max.x, b.max.y, b.max.z]) } diff --git a/crates/engine/src/tests/primitive_points.rs b/crates/engine/src/tests/primitive_points.rs index b499b61ea..d37b5c353 100644 --- a/crates/engine/src/tests/primitive_points.rs +++ b/crates/engine/src/tests/primitive_points.rs @@ -112,7 +112,7 @@ fn point_expressions_in_a_moved_component() { run(&mut s, "occurrence.move", json!({"occurrence": occ, "translate": [0, 50, 0]})); run(&mut s, "component.activate", json!({"component": cid})); run(&mut s, "solid.cylinder", json!({"radius": 1, "height": 2, "base": ["x0", 60, 0], "body_name": "Pin"})); - let wlo = |s: &Session| s.world_state().body("Pin").unwrap().mesh().bounds().min; + let wlo = |s: &Session| s.world_state().unwrap().body("Pin").unwrap().mesh().bounds().min; let lo = wlo(&s); assert!((lo.x - 9.0).abs() < 1e-3 && (lo.y - 59.0).abs() < 1e-3, "{lo:?}"); run(&mut s, "parameters.change", json!({"name": "x0", "expression": "20 mm"})); diff --git a/crates/engine/src/tests/rim_cut.rs b/crates/engine/src/tests/rim_cut.rs index 2a5cda44d..1bbabb30c 100644 --- a/crates/engine/src/tests/rim_cut.rs +++ b/crates/engine/src/tests/rim_cut.rs @@ -48,7 +48,6 @@ fn rim_cut_after_the_round_on_the_other_end() { let id = cut_window(&mut after)["feature"].as_u64().unwrap(); let result = after.model.result(id).unwrap(); assert!(result.error.is_none() && result.warning.is_none(), "{result:?}"); - assert!(result.boolean_diagnostics.events.is_empty(), "{:?}", result.boolean_diagnostics); // The window's three faces (two sides and the top), at both points of the timeline. assert_eq!(faces(&before), f1 + 3); assert_eq!(faces(&after), f2 + 3); diff --git a/crates/engine/src/tests/robustness.rs b/crates/engine/src/tests/robustness.rs index 7e71d95cb..1114777fa 100644 --- a/crates/engine/src/tests/robustness.rs +++ b/crates/engine/src/tests/robustness.rs @@ -5,7 +5,7 @@ use std::f64::consts::PI; use serde_json::{Value, json}; -use super::{run, volume}; +use super::run; use crate::Session; use crate::fuzz; @@ -39,26 +39,15 @@ fn shell_with_a_shallow_arc_side() { ])); } -/// Shell of a plate with a hole whose wall meets the plate's arc side: the edge where the two -/// cylinders meet is neither a line nor an arc, and is rebuilt through its moved points. -#[test] -fn shell_with_a_hole_through_a_curved_side() { - script(json!([ - {"command": "sketch.create", "params": {"plane": "XY"}}, - {"command": "sketch.line", "params": {"points": [[0, 0], [42.5, 0], [42.5, 20.0], [0, 20.0]]}}, - {"command": "sketch.arc.three_point", "params": {"end": [0, 0], "start": [0, 20.0], "through": [-10.0, 10.0]}}, - {"command": "sketch.finish", "params": {}}, - {"command": "solid.extrude", "params": {"distance": 27.5}}, - {"command": "solid.cylinder", "params": {"axis": [1.0, 0.0, 0.0], "base": [-10.000000000000002, 12.5, 12.5], "height": 17.5, "operation": "cut", "radius": 5.0}}, - {"command": "solid.shell", "params": {"faces": [[42.5, 10.0, 13.75]], "thickness": 2.0}} - ])); -} - /// A cut whose end only touches the plate's arc side (#897, robustness seed 14): the end lies /// tangent to the arc at its apex, the direct boolean fails, and the last-resort nudge used to /// push the end into the arc, leaving a sliver of it a tenth of a millimetre wide that a shell -/// then couldn't offset. The nudge the other way parts them: the same faces as a cut clear of -/// the apex, and seed 14 shells and fillets again. +/// then couldn't offset. The touching cut must make the same part as a cut 0.1 clear of the +/// apex (x = −10.1 .. 7.4 instead of −10 .. 7.5), less the hole's last 0.1 mm: the arc (centre +/// (0, 10), r 10) reaches x = −10 only at y = 10, so both cuts open the same patch of it, and +/// the slice x = 7.4 .. 7.5 of the r 5 hole lies wholly inside the plate. The touching cut has +/// π 5² 0.1 less volume and 2π 5 0.1 more area (the longer hole wall; the floor disc is the +/// same); a sliver left on the arc adds about a square millimetre of faces. #[test] fn cut_whose_end_touches_an_arc_side_leaves_no_sliver() { let plate = |x: f64| { @@ -72,11 +61,27 @@ fn cut_whose_end_touches_an_arc_side_leaves_no_sliver() { ])) }; let (touching, clear) = (plate(-10.0), plate(-10.1)); - let faces = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.face_count()).sum::(); - assert_eq!(faces(&touching), faces(&clear), "a sliver face was left where the cut's end touches the arc"); - let r = fuzz::run(14, 8); - let kinds: Vec<&str> = r.steps.iter().map(|s| s.kind).collect(); - assert!(r.outcome.kind == "ok" && kinds.contains(&"shell"), "seed 14: {:?} {kinds:?}\n{}", r.outcome, r.script()); + let area = |s: &Session| s.model.state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).map(|m| m.area).unwrap_or(0.0)).sum::(); + let dv = total_volume(&clear) - total_volume(&touching); + assert!((dv - PI * 25.0 * 0.1).abs() < 1e-4, "volume: clear − touching = {dv}, not π 5² 0.1"); + let da = area(&touching) - area(&clear); + assert!((da - 2.0 * PI * 5.0 * 0.1).abs() < 1e-4, "area: touching − clear = {da}, not 2π 5 0.1: a sliver where the cut's end touches the arc"); + assert_eq!(touching.model.state().bodies.len(), 1); +} + +/// Robustness seed 14 (#897) as the generator made it: the touching cut above, then a shell +/// opening the plate's top face (y = 20). Every step builds and the body is a sound solid. +#[test] +fn shell_after_a_cut_whose_end_touches_an_arc_side() { + script(json!([ + {"command": "sketch.create", "params": {"plane": "XY"}}, + {"command": "sketch.line", "params": {"points": [[0, 0], [42.5, 0], [42.5, 20.0], [0, 20.0]]}}, + {"command": "sketch.arc.three_point", "params": {"end": [0, 0], "start": [0, 20.0], "through": [-10.0, 10.0]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.extrude", "params": {"distance": 27.5}}, + {"command": "solid.cylinder", "params": {"axis": [1.0, 0.0, 0.0], "base": [-10.000000000000002, 12.5, 12.5], "height": 17.5, "operation": "cut", "radius": 5.0}}, + {"command": "solid.shell", "params": {"faces": [[21.25, 19.999999999999993, 13.749999999999998]], "thickness": 2.0}} + ])); } /// #827: a hinge barrel joined to a laptop lid through its mounting leaf. The barrel's top lies @@ -169,37 +174,6 @@ fn shell_thicker_than_a_step_says_so() { assert!(e.to_string().contains("not supported yet"), "{e}"); } -/// Panics inside the kernel are caught natively, but abort the web build (wasm can't unwind). -/// Building the samples must not panic at all (the Plastic Enclosure's bosses used to, 8 times). -#[test] -fn samples_build_without_panics() { - use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; - let me = std::thread::current().id(); - let count = Arc::new(AtomicUsize::new(0)); - let c2 = count.clone(); - let prev = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |info| { - if std::thread::current().id() == me { - c2.fetch_add(1, Ordering::SeqCst); - } - let _ = info; - })); - let mut failed = Vec::new(); - for sample in crate::sample::samples() { - let mut s = Session::default(); - for c in (sample.script)()["commands"].as_array().into_iter().flatten() { - let _ = s.execute(c["command"].as_str().unwrap_or(""), &c["params"]); - } - let n = count.swap(0, Ordering::SeqCst); - if n > 0 { - failed.push(format!("{}: {n} panic(s)", sample.name)); - } - } - std::panic::set_hook(prev); - assert!(failed.is_empty(), "{failed:?}"); -} - fn total_volume(s: &Session) -> f64 { s.model.state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).map(|m| m.volume).unwrap_or(0.0)).sum() } @@ -272,46 +246,65 @@ fn shell_after_a_drilled_hole() { /// Rounding a box's edges one at a time: an edge running into an earlier round (of the same /// radius or another) takes off about what each round alone would (the corner where they meet -/// is small). +/// is small). The upright runs on tangentially into the first round's end arc, and that into +/// the top right edge: its tangent chain, which the default (`tangent_chain`) rounds too, taking +/// off about what a round of that edge (38 long, past the first round) would as well. #[test] fn fillet_into_an_earlier_round() { let box_ = json!({"command": "solid.box", "params": {"length": 60, "width": 40, "height": 15}}); + let lost = |r: f64, len: f64| (1.0 - PI / 4.0) * r * r * len; for r2 in [2.0, 3.0] { let s = script(json!([ box_, - {"command": "solid.fillet", "params": {"edges": [[30, 0, 15]], "radius": 2}}, - {"command": "solid.fillet", "params": {"edges": [[60, 0, 7]], "radius": r2}} + {"command": "solid.fillet", "params": {"edges": [[30, 0, 15]], "radius": 2, "tangent_chain": false}}, + {"command": "solid.fillet", "params": {"edges": [[60, 0, 7]], "radius": r2, "tangent_chain": false}} ])); - let lost = |r: f64, len: f64| (1.0 - PI / 4.0) * r * r * len; let want = 36000.0 - lost(2.0, 60.0) - lost(r2, 15.0); let v = total_volume(&s); assert!((v - want).abs() < 2.0, "r2 {r2}: {v} vs {want}"); } + let s = script(json!([ + box_, + {"command": "solid.fillet", "params": {"edges": [[30, 0, 15]], "radius": 2}}, + {"command": "solid.fillet", "params": {"edges": [[60, 0, 7]], "radius": 2}} + ])); + let want = 36000.0 - lost(2.0, 60.0) - lost(2.0, 15.0) - lost(2.0, 38.0); + let v = total_volume(&s); + assert!((v - want).abs() < 2.0, "the upright's tangent chain: {v} vs {want}"); } -/// Clean seeds (seed 16: a partial face contact, fused), and the original seed 5 edge contact, -/// now rejected without distortion. +/// Fixed seeds run without a panic and leave valid bodies (seed 16: a partial face contact, +/// fused), and the original seed 5 edge contact is kept as two bodies without distortion. What a +/// seed's steps come to is not compared with what the builds that chose the seeds made (truck's): +/// the kernel's reference is the ladder (`tests/kernel-cases/ladder`). #[test] fn fixed_seeds_run_clean() { + // A panic, a body that is not valid or a step that moved the volume the wrong way; a step the + // kernel refuses is not one. + let clean = |r: &fuzz::Run| !matches!(r.outcome.kind.as_str(), "panic" | "invalid" | "volume"); for seed in FIXED_SEEDS { if *seed == 5 { - // Seed 5 originally joined these boxes along only an edge. Accepting - // it required silently shifting the tool; that is now invalid input. + // Seed 5 originally joined these boxes along only an edge. Accepting it once required + // silently shifting the tool; since 94ee28d5c ("a join keeps solids that only touch as + // separate bodies") the join keeps the new box a body of its own and says why, as + // `join_touching_along_an_edge_keeps_a_separate_body` asserts in tests.rs. let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 25, "width": 15, "height": 10})); - let error = s - .execute( - "solid.box", - &json!({ - "corner": [25, 2.5, 10], "length": 17.5, "width": 17.5, - "height": 20, "operation": "join" - }), - ) - .unwrap_err(); - assert!(error.to_string().contains("zero-thickness edge contact"), "{error}"); - assert!((total_volume(&s) - 3750.0).abs() < 1e-6); - assert_eq!(s.model.state().bodies.len(), 1); - assert!(s.model.state().bodies.first().unwrap().body.validity().is_empty()); + let r = run( + &mut s, + "solid.box", + json!({ + "corner": [25, 2.5, 10], "length": 17.5, "width": 17.5, + "height": 20, "operation": "join" + }), + ); + assert_eq!(r["notice"]["contact"], "along_edge", "{r}"); + // 25 x 15 x 10 and 17.5 x 17.5 x 20, unmoved and sharing no volume. + assert!((total_volume(&s) - (3750.0 + 6125.0)).abs() < 1e-6, "{}", total_volume(&s)); + assert_eq!(s.model.state().bodies.len(), 2); + for b in &s.model.state().bodies { + assert!(b.body.validity().is_empty(), "{}: {:?}", b.name, b.body.validity()); + } continue; } if *seed == 16 { @@ -332,84 +325,16 @@ fn fixed_seeds_run_clean() { assert!((total_volume(&s) - want).abs() < 0.2, "{} vs {want}", total_volume(&s)); assert!(s.model.state().bodies.iter().all(|b| b.body.validity().is_empty())); let r = fuzz::run(*seed, 8); - assert!(!r.outcome.is_bug(), "seed {seed}: {:?}\n{}", r.outcome, r.script()); + assert!(clean(&r), "seed {seed}: {:?}\n{}", r.outcome, r.script()); continue; } let r = fuzz::run(*seed, 8); - assert!(!r.outcome.is_bug(), "seed {seed}: {:?}\n{}", r.outcome, r.script()); + assert!(clean(&r), "seed {seed}: {:?}\n{}", r.outcome, r.script()); } } const FIXED_SEEDS: &[u64] = &[3, 5, 11, 16, 21, 29, 33, 35]; -/// A drilled hole as deep as the plate: the drill point breaks through the bottom. -#[test] -fn hole_as_deep_as_the_plate() { - let mut s = Session::default(); - run(&mut s, "solid.box", json!({"length": 50, "width": 25, "height": 10})); - let v0 = volume(&mut s); - run(&mut s, "solid.hole", json!({"position": [25, 12.5, 10], "diameter": 6, "depth": 10, "type": "drilled"})); - let v = volume(&mut s); - assert!(v < v0 - PI * 9.0 * 9.0 && v > v0 - PI * 9.0 * 10.0 - 1.0, "{v0} {v}"); - // Other sizes and places, the defaults, and a tapped hole. - for (i, p) in [ - json!({"position": [10, 10, 10], "diameter": 5, "depth": 10, "type": "drilled"}), - json!({"position": [40, 15, 10], "diameter": 5, "depth": 10}), - json!({"position": [12, 6, 10], "diameter": 8.5, "depth": 10}), - json!({"position": [30, 7, 10], "thread": "M6", "depth": 10}), - json!({"position": [20, 18, 10], "diameter": 4, "depth": 10, "tip_angle": 90}), - ] - .into_iter() - .enumerate() - { - let before = volume(&mut s); - let r = s.execute("solid.hole", &p); - assert!(r.is_ok(), "{i} {p}: {r:?}"); - assert!(volume(&mut s) < before - 1.0, "{i} {p}"); - } -} - -/// An enclosure built in the usual order: shell, bosses, then the lip on the rim. -#[test] -fn lip_after_boss() { - let mut s = Session::default(); - run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 30})); - run(&mut s, "solid.shell", json!({"faces": [[40, 25, 30]], "thickness": 2})); - run(&mut s, "plastic.boss", json!({"position": [10, 10, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5})); - run(&mut s, "plastic.boss", json!({"position": [70, 40, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5})); - let v0 = volume(&mut s); - run(&mut s, "plastic.lip", json!({"face": [1, 25, 30], "width": 1, "height": 2})); - let v = volume(&mut s); - assert!(v > v0 + 1.0, "{v0} {v}"); - // Bosses up to the rim, with ribs, against a wall; lips, grooves and outside rims. - let bosses = [ - json!({"position": [15, 15, 2], "diameter": 8, "height": 28, "hole_diameter": 3}), - // Ribs out to the inner walls (15 − 4 − 9 = 2), and short of them. - json!({"position": [15, 15, 2], "diameter": 8, "height": 12, "ribs": 4, "rib_thickness": 1.5, "rib_length": 9}), - json!({"position": [15, 15, 2], "diameter": 8, "height": 12, "ribs": 4, "rib_thickness": 1.5, "rib_length": 6}), - json!({"position": [5.5, 25, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5}), - json!({"position": [40, 25, 2], "diameter": 8, "height": 20, "draft": "1 deg", "fillet": 1}), - ]; - let lips = [ - json!({"face": [1, 25, 30], "width": 1, "height": 2}), - json!({"face": [1, 25, 30], "width": 1, "height": 2, "type": "groove"}), - json!({"face": [1, 25, 30], "width": 1, "height": 2, "side": "outside"}), - ]; - for (i, b) in bosses.iter().enumerate() { - for (j, l) in lips.iter().enumerate() { - let mut s = Session::default(); - run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 30})); - run(&mut s, "solid.shell", json!({"faces": [[40, 25, 30]], "thickness": 2})); - let r = s.execute("plastic.boss", b); - assert!(r.is_ok(), "boss {i}: {r:?}"); - let v0 = volume(&mut s); - let r = s.execute("plastic.lip", l); - assert!(r.is_ok(), "boss {i} lip {j}: {r:?}"); - assert!((volume(&mut s) - v0).abs() > 1.0, "boss {i} lip {j}"); - } - } -} - /// A lip, a groove and an outside lip on the rim of a rounded, shelled enclosure (#29: the /// lip's walls continue the shell's walls, which a boolean join couldn't do). #[test] @@ -460,28 +385,7 @@ fn knife_edge_part() -> Session { /// The volume of the session's bodies through the display plan. fn planned_volume(s: &Session) -> f64 { - s.model.state().bodies.iter().map(|b| b.body.display_plan(2e-4).unwrap().evaluate().measure().volume).sum() -} - -/// #851: the knife edge where the wall runs out has opposite normals on its two faces. It rounds -/// to the ball that fits there and chamfers with the plane through that ball's contacts (the cusp -/// area less the wall's sector and the ball's, or the chord triangle less the wall's segment, -/// times the 10 mm height). -#[test] -fn blend_a_knife_edge_where_a_curved_wall_runs_out() { - let knife = json!([[62.1667, 0, 5]]); - for (command, params, removed) in - [("solid.fillet", json!({"edges": knife, "radius": 2}), 119.648_812), ("solid.chamfer", json!({"edges": knife, "distance": 2}), 159.236_451)] - { - let mut s = knife_edge_part(); - let before = planned_volume(&s); - s.execute(command, ¶ms).unwrap_or_else(|e| panic!("{command}: {e}")); - let after = planned_volume(&s); - assert!((before - after - removed).abs() < 0.5, "{command}: removed {}, expected {removed}", before - after); - for b in &s.model.state().bodies { - assert!(b.body.validity().is_empty(), "{command}: {:?}", b.body.validity()); - } - } + s.model.state().bodies.iter().map(|b| b.body.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(2e-4)).unwrap().evaluate().measure().volume).sum() } /// #851: the arc's top edge runs out tangent to the back face at the knife edge's top. The blend @@ -503,53 +407,6 @@ fn blend_an_arc_edge_that_runs_out_tangent_to_a_face() { } } -/// #851: every selection of the issue's table works, picked together or one after the other as -/// the issue lists them, on the part with the wall that meets the front face square and runs out -/// tangent into the back face (the top front edge, the arc's top edge, the front upright at the -/// arc, the front-left upright and the knife edge at the tip). Each makes a sound solid the -/// display plan can mesh, and takes less than its edges would one by one where they meet. -#[test] -fn blend_corners_where_edges_meet_on_a_curved_wall() { - let (tf, at, fu, fl, kn) = - (json!([20, -21, 10]), json!([47.3174, -6.1508, 10]), json!([41.1667, -21, 5]), json!([0, -21, 5]), json!([62.1667, 0, 5])); - let fillet = |edges: Value| json!({"command": "solid.fillet", "params": {"edges": edges, "radius": 2}}); - let chamfer = |edges: Value| json!({"command": "solid.chamfer", "params": {"edges": edges, "distance": 2}}); - let base = planned_volume(&knife_edge_part()); - let rows: Vec<(&str, Vec)> = vec![ - ("three at the corner", vec![fillet(json!([tf, at, fu]))]), - ("top front and arc", vec![fillet(json!([tf, at]))]), - ("arc and upright", vec![fillet(json!([at, fu]))]), - ("top front and upright", vec![fillet(json!([tf, fu]))]), - ("arc alone", vec![fillet(json!([at]))]), - ("top front, then the front-left upright", vec![fillet(json!([tf])), fillet(json!([fl]))]), - ("top front and front-left together", vec![fillet(json!([tf, fl]))]), - ("the knife edge", vec![fillet(json!([kn]))]), - ("chamfer: the knife edge", vec![chamfer(json!([kn]))]), - ("chamfer: the arc", vec![chamfer(json!([at]))]), - ("chamfer: the arc and the top front", vec![chamfer(json!([at, tf]))]), - ("arc, then top front", vec![fillet(json!([at])), fillet(json!([tf]))]), - ("top front, then upright", vec![fillet(json!([tf])), fillet(json!([fu]))]), - ]; - for (name, steps) in rows { - let mut s = knife_edge_part(); - for step in &steps { - let (c, p) = (step["command"].as_str().unwrap_or(""), &step["params"]); - s.execute(c, p).unwrap_or_else(|e| panic!("{name}: {c} {p}: {e}")); - } - for b in &s.model.state().bodies { - assert!(b.body.validity().is_empty(), "{name}: {:?}", b.body.validity()); - assert!(b.body.display_plan(2e-4).is_ok(), "{name}: the display plan refuses the body"); - } - let removed = base - planned_volume(&s); - assert!(removed > 0.0 && removed < 250.0, "{name}: removed {removed}"); - } - // The three edges end in a sphere: the volume of the rounds and the ball's corner. - let mut s = knife_edge_part(); - s.execute("solid.fillet", &fillet(json!([tf, at, fu]))["params"]).unwrap_or_else(|e| panic!("three at the corner: {e}")); - let removed = base - planned_volume(&s); - assert!((removed - 67.05).abs() < 0.15, "three at the corner: removed {removed}, expected 67.05"); -} - /// Seed 20 cuts a patterned cylinder's holes through a filleted plate. The lenient retry of a /// face's parameter boundary (#970) searched the whole cylinder for a point and found it across /// the seam, half a turn away; the face was divided wrongly and the cut failed. Such a boundary @@ -561,21 +418,6 @@ fn a_boundary_found_across_a_seam_is_not_used() { assert!(r.steps.iter().any(|s| s.kind == "circular pattern"), "the pattern must build, not be skipped as unsupported: {:?}", r.unsupported); } -/// Seed 33 ends in a fillet on its second body (#854's corner blends build it differently from -/// before). Its display plan and its measured volume agree for every body (on main before #854, -/// that body read 4439.42 through the display plan and 4443.51 measured). -#[test] -fn seed_33_display_plan_and_measure_agree() { - let r = fuzz::run(33, 8); - assert_eq!(r.outcome.kind, "ok", "seed 33: {:?}\n{}", r.outcome, r.script()); - let s = script(r.script()); - for b in &s.model.state().bodies { - let planned = b.body.display_plan(2e-4).unwrap().evaluate().measure().volume; - let measured = solidcraft_kernel::measure(&b.body).unwrap().volume; - assert!((planned - measured).abs() < 2e-5 * measured, "{}: planned {planned}, measured {measured}", b.name); - } -} - /// A chamfer on a concave edge fills the corner, so it adds material, as a fillet there does. The /// fuzzer expected every chamfer to shrink the body and reported these as a wrong volume (about /// 1 % of the designs of a 6,000-seed run; seed 7100465: a box, a shell, a chamfer of an inside diff --git a/crates/engine/src/tests/robustness_goldens.rs b/crates/engine/src/tests/robustness_goldens.rs deleted file mode 100644 index ad717c369..000000000 --- a/crates/engine/src/tests/robustness_goldens.rs +++ /dev/null @@ -1,465 +0,0 @@ -//! Seeded goldens: what every robustness seed builds (`tests/robustness/goldens.json`). -//! -//! Each seed's random design (`fuzz::run`) is recorded: its steps, how it ended (ok, or the -//! kind and start of the error it was refused with) and, for what it left, the bodies' total -//! volume and area (within a relative 1e-6) and their face, edge and shell counts (exact). Any -//! change fails, the better and the worse alike: a seed that used to be refused and now builds -//! is recorded on purpose, with the reason. To record: `ROBUSTNESS_GOLDENS_BLESS="why" cargo -//! test --profile ci -p solidcraft-engine --lib robustness_goldens::` (docs/robustness.md); run -//! it with `cargo test`, whose tests share one process and so one lock on the file, not with -//! nextest. The reason goes into the file's `notes` with the seeds it changed. -//! -//! Each seed is its own test (`seed_00` … `seed_95`), so the runner spreads them over the CI -//! shards and their cores: a few seeds take minutes, and grouped four ways they made one test -//! of half an hour. Pull requests that can change them run every seed but the slowest few -//! (`SLOW_SEEDS` in ci.yml); the merge queue, pushes to main and the nightly run every seed. - -use std::collections::BTreeMap; -use std::path::PathBuf; -use std::sync::Mutex; - -use serde_json::{Value, json}; - -use crate::fuzz; - -/// Seeds 0..SEEDS (about ten minutes for all of them on one core), each with up to this many steps (as `fixed_seeds_run_clean`). -const SEEDS: u64 = 96; -const MAX_STEPS: usize = 8; -const REL: f64 = 1e-6; - -/// Tests share the file when they record. -static FILE: Mutex<()> = Mutex::new(()); - -fn path() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/robustness/goldens.json") -} - -fn load() -> Value { - std::fs::read(path()).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_else(|| json!({})) -} - -/// How `got` differs from `want` (None when it matches within the tolerances). -fn differs(want: &Value, got: &Value) -> Option { - let mut out = Vec::new(); - for (k, g) in got.as_object().into_iter().flatten() { - let w = &want[k]; - let same = match (w.as_f64(), g.as_f64()) { - (Some(a), Some(b)) if matches!(k.as_str(), "volume" | "area") => (a - b).abs() <= REL * a.abs().max(b.abs()).max(1.0), - _ => w == g, - }; - if !same { - out.push(format!("{k}: {w} -> {g}")); - } - } - (!out.is_empty()).then(|| out.join("; ")) -} - -/// Only Windows needs an environment split; other OS policies remain compatible. -#[derive(Clone, Copy, Debug)] -struct Target<'a> { - os: &'a str, - env: &'a str, -} - -impl<'a> Target<'a> { - fn current() -> Self { - // cfg! describes the compilation target, including when cross-compiling. - let env = if cfg!(target_env = "msvc") { - "msvc" - } else if cfg!(target_env = "gnu") { - "gnu" - } else { - "other" - }; - Self { os: std::env::consts::OS, env } - } - - fn platform(self) -> Option<&'a str> { - match (self.os, self.env) { - ("windows", "msvc") => Some("windows"), // Existing MSVC-verified records. - ("windows", "gnu") => Some("windows-gnu"), - ("windows", _) => None, - (os, _) => Some(os), - } - } - - fn recording_platform(self, file: &Value) -> Result, String> { - let platform = self.platform(); - if self.os == "windows" { - return platform.map(Some).ok_or_else(|| format!("no recording policy for Windows target_env={}; define one before blessing", self.env)); - } - Ok(platform.filter(|p| file["platforms"][*p]["seeds"].is_object())) - } -} - -/// An override replaces the entire seed record, never individual fields. -/// The second return value identifies the selected reference in diagnostics. -fn expected<'a, 't>(file: &'a Value, seed: u64, target: Target<'t>) -> (&'a Value, &'t str) { - let key = seed.to_string(); - if let Some(platform) = target.platform() - && let Some(record) = file.get("platforms").and_then(|p| p.get(platform)).and_then(|p| p.get("seeds")).and_then(|s| s.get(&key)) - { - return (record, platform); - } - (&file["seeds"][key], "shared") -} - -fn difference(file: &Value, seed: u64, got: &Value, target: Target<'_>) -> Option { - let (want, group) = expected(file, seed, target); - let change = if want.is_null() { Some("new".to_string()) } else { differs(want, got) }; - change.map(|d| format!("seed {seed} [target_os={}, target_env={}, reference={group}]: {d}", target.os, target.env)) -} - -/// In-memory recording seam: regression tests never write the real reference file. -fn record(file: &mut Value, seed: u64, got: &Value, reason: &str, target: Target<'_>) -> Result { - if reason.trim().is_empty() { - return Err("ROBUSTNESS_GOLDENS_BLESS needs the reason for the change".to_string()); - } - let platform = target.recording_platform(file)?; - if difference(file, seed, got, target).is_none() { - return Ok(false); - } - if file.get("about").is_none() { - file["about"] = json!( - "What each robustness seed builds (crates/engine/src/tests/robustness_goldens.rs, docs/robustness.md). Record changes with ROBUSTNESS_GOLDENS_BLESS=\"why\"." - ); - } - if let Some(platform) = platform { - file["platforms"][platform]["seeds"][seed.to_string()] = got.clone(); - } else { - file["seeds"][seed.to_string()] = got.clone(); - } - let mut notes = file["notes"].as_array().cloned().unwrap_or_default(); - // Coalesce only the same reason AND destination, including shared vs platform. - // Windows destinations encode the environment, so GNU and MSVC cannot coalesce. - let destination = platform.map(|p| json!(p)); - match notes.last_mut() { - Some(last) if last["reason"] == json!(reason) && last.get("platform") == destination.as_ref() => { - let mut all: Vec = last["seeds"].as_array().into_iter().flatten().filter_map(Value::as_u64).chain([seed]).collect(); - all.sort_unstable(); - all.dedup(); - last["seeds"] = json!(all); - } - _ => { - let mut note = json!({"reason": reason, "seeds": [seed]}); - if let Some(platform) = platform { - note["platform"] = json!(platform); - } - notes.push(note); - } - } - file["notes"] = Value::Array(notes); - Ok(true) -} - -fn serialize(file: &Value) -> String { - // Seeds in order, one per line, so a change is a small diff. - let seeds: BTreeMap = - file["seeds"].as_object().into_iter().flatten().filter_map(|(k, v)| Some((k.parse::().ok()?, v.clone()))).collect(); - let mut s = format!("{{\n \"about\": {},\n \"seeds\": {{\n", file["about"]); - let n = seeds.len(); - for (i, (k, v)) in seeds.iter().enumerate() { - s += &format!(" \"{k}\": {}{}\n", v, if i + 1 < n { "," } else { "" }); - } - let notes: Vec = file["notes"].as_array().into_iter().flatten().map(|n| format!(" {n}")).collect(); - s += " },\n"; - if let Some(platforms) = file.get("platforms") { - s += &format!(" \"platforms\": {platforms},\n"); - } - s += &format!(" \"notes\": [\n{}\n ]\n}}\n", notes.join(",\n")); - s -} - -fn check(seed: u64) { - let got = fuzz::golden(seed, MAX_STEPS); - let _lock = FILE.lock().unwrap_or_else(|e| e.into_inner()); - let mut file = load(); - let target = Target::current(); - if let Ok(reason) = std::env::var("ROBUSTNESS_GOLDENS_BLESS") { - if record(&mut file, seed, &got, &reason, target).unwrap_or_else(|e| panic!("{e}")) { - std::fs::write(path(), serialize(&file)).unwrap_or_else(|e| panic!("{}: {e}", path().display())); - } - return; - } - let change = difference(&file, seed, &got, target); - assert!( - change.is_none(), - "build differs from tests/robustness/goldens.json (if that is intended, record it with ROBUSTNESS_GOLDENS_BLESS=\"why\" and say why in the pull request):\n{}", - change.unwrap_or_default() - ); -} - -const MSVC: Target<'_> = Target { os: "windows", env: "msvc" }; -const GNU: Target<'_> = Target { os: "windows", env: "gnu" }; -const LINUX: Target<'_> = Target { os: "linux", env: "gnu" }; - -fn policy_fixture() -> Value { - json!({ - "seeds": {"1": {"volume": 10, "faces": 2, "outcome": "ok"}, "2": {"volume": 20}}, - "platforms": { - "windows": {"seeds": {"1": {"volume": 11, "outcome": "failed"}}, "verification": "MSVC"}, - "macos": {"seeds": {"1": {"volume": 12}}} - }, - "notes": [{"platform": "windows", "reason": "same reason", "seeds": [1]}] - }) -} - -#[test] -fn policy_selects_msvc_and_gnu_overrides_with_shared_fallback() { - let mut file = policy_fixture(); - assert_eq!(expected(&file, 1, MSVC), (&file["platforms"]["windows"]["seeds"]["1"], "windows")); - assert_eq!(expected(&file, 1, GNU), (&file["seeds"]["1"], "shared")); - file["platforms"]["windows-gnu"]["seeds"]["1"] = json!({"volume": 13}); - assert_eq!(expected(&file, 1, GNU), (&file["platforms"]["windows-gnu"]["seeds"]["1"], "windows-gnu")); - for target in [MSVC, GNU] { - assert_eq!(expected(&file, 2, target), (&file["seeds"]["2"], "shared")); - } - // A platform record is whole, including failure outcomes and missing fields. - assert!(expected(&file, 1, MSVC).0.get("faces").is_none()); - assert_eq!(expected(&file, 1, MSVC).0["outcome"], "failed"); - assert!(differs(expected(&file, 1, MSVC).0, &file["seeds"]["1"]).is_some()); - assert!(expected(&file, 1, GNU).0.get("faces").is_none()); - assert!(expected(&file, 99, GNU).0.is_null()); -} - -#[test] -fn policy_preserves_non_windows_and_refuses_unknown_windows_recording() { - let mut file = policy_fixture(); - let macos = Target { os: "macos", env: "" }; - assert_eq!(expected(&file, 1, LINUX), (&file["seeds"]["1"], "shared")); - assert_eq!(expected(&file, 1, macos), (&file["platforms"]["macos"]["seeds"]["1"], "macos")); - assert_eq!(LINUX.recording_platform(&file), Ok(None)); - assert_eq!(macos.recording_platform(&file), Ok(Some("macos"))); - for env in ["", "other", "new-env"] { - let unknown = Target { os: "windows", env }; - let before = file.clone(); - assert_eq!(expected(&file, 1, unknown), (&file["seeds"]["1"], "shared")); - assert!(record(&mut file, 1, &json!({"volume": 30}), "why", unknown).is_err()); - assert_eq!(file, before); - } - assert_eq!(expected(&file, 1, Target { os: "future-os", env: "gnu" }).1, "shared"); -} - -#[test] -fn policy_records_only_changed_gnu_seeds_and_preserves_other_destinations_and_notes() { - let mut file = policy_fixture(); - let before = file.clone(); - let got = json!({"volume": 30, "outcome": "failed", "error": "known failure"}); - assert_eq!(record(&mut file, 2, &got, "same reason", GNU), Ok(true)); - assert_eq!(file["seeds"], before["seeds"]); - assert_eq!(file["platforms"]["windows"], before["platforms"]["windows"]); - assert_eq!(file["platforms"]["macos"], before["platforms"]["macos"]); - assert_eq!(file["notes"][0], before["notes"][0]); - assert_eq!(file["notes"][1], json!({"platform": "windows-gnu", "reason": "same reason", "seeds": [2]})); - assert_eq!(expected(&file, 2, GNU), (&got, "windows-gnu")); - assert!(file["platforms"]["windows-gnu"]["seeds"].get("1").is_none()); - assert_eq!(record(&mut file, 1, &got, "same reason", GNU), Ok(true)); - assert_eq!(file["notes"][1]["seeds"], json!([1, 2])); - let unchanged = file.clone(); - assert_eq!(record(&mut file, 1, &got, "same reason", GNU), Ok(false)); - assert_eq!(file, unchanged); - assert_eq!(record(&mut file, 1, &json!({"volume": 31}), "same reason", GNU), Ok(true)); - assert_eq!(file["notes"][1]["seeds"], json!([1, 2])); - assert!(expected(&file, 1, GNU).0.get("error").is_none()); - assert_eq!(serde_json::from_str::(&serialize(&file)).ok().as_ref(), Some(&file)); -} - -#[test] -fn policy_isolates_msvc_recording_even_without_a_namespace() { - for target in [MSVC, GNU] { - let mut file = json!({"seeds": {"1": {"volume": 10}}, "notes": []}); - let before = file.clone(); - assert_eq!(record(&mut file, 1, &json!({"volume": 10}), "why", target), Ok(false)); - assert_eq!(file, before); // No spurious namespace or note for a matching fallback. - assert_eq!(record(&mut file, 1, &json!({"volume": 11}), "why", target), Ok(true)); - assert_eq!(file["seeds"], before["seeds"]); - assert_eq!(expected(&file, 1, target).0["volume"], 11); - assert_eq!(file["notes"][0]["platform"], json!(target.platform())); - } -} - -#[test] -fn policy_notes_never_coalesce_across_destinations_in_either_direction() { - let mut file = policy_fixture(); - for target in [GNU, MSVC, LINUX, GNU, LINUX, MSVC] { - let previous_notes = file["notes"].as_array().cloned().unwrap_or_default(); - let got = json!({"volume": 100 + previous_notes.len()}); - assert_eq!(record(&mut file, 1, &got, "same reason", target), Ok(true)); - let notes = file["notes"].as_array().cloned().unwrap_or_default(); - assert_eq!(notes.len(), previous_notes.len() + 1); - assert_eq!(¬es[..previous_notes.len()], previous_notes); - } - let before = file["notes"].clone(); - assert_eq!(record(&mut file, 2, &json!({"volume": 50}), "different reason", MSVC), Ok(true)); - assert_eq!(file["notes"].as_array().map(Vec::len), before.as_array().map(|n| n.len() + 1)); - let before = file.clone(); - assert!(record(&mut file, 1, &json!({"volume": 99}), " ", GNU).is_err()); - assert_eq!(file, before); -} - -#[test] -fn policy_comparator_stays_strict_and_diagnostics_name_the_selected_reference() { - let want = json!({"volume": 100.0, "area": 10.0, "faces": 2, "outcome": "ok", "steps": ["box"], "error": null, "rejected": 0, "unsupported": 0}); - let mut got = want.clone(); - got["volume"] = json!(100.00005); - got["area"] = json!(10.000005); - assert_eq!(differs(&want, &got), None); - for (field, value) in [ - ("volume", json!(100.001)), - ("area", json!(10.001)), - ("faces", json!(3)), - ("outcome", json!("failed")), - ("steps", json!(["hole"])), - ("error", json!("refused")), - ("rejected", json!(1)), - ("unsupported", json!(1)), - ] { - let mut got = want.clone(); - got[field] = value; - assert!(differs(&want, &got).is_some(), "{field}"); - } - let file = policy_fixture(); - let diagnostic = difference(&file, 1, &json!({"volume": 100}), GNU).unwrap_or_default(); - assert!(diagnostic.contains("target_os=windows, target_env=gnu, reference=shared"), "{diagnostic}"); - let diagnostic = difference(&file, 1, &json!({"volume": 100}), MSVC).unwrap_or_default(); - assert!(diagnostic.contains("target_env=msvc, reference=windows"), "{diagnostic}"); -} - -#[test] -fn policy_non_windows_recording_keeps_existing_os_destination_and_shared_notes() { - let mut file = policy_fixture(); - let before = file.clone(); - let got = json!({"volume": 40}); - let macos = Target { os: "macos", env: "" }; - assert_eq!(record(&mut file, 1, &got, "same reason", macos), Ok(true)); - assert_eq!(file["seeds"], before["seeds"]); - assert_eq!(file["platforms"]["windows"], before["platforms"]["windows"]); - assert_eq!(expected(&file, 1, macos), (&got, "macos")); - let platforms = file["platforms"].clone(); - assert_eq!(record(&mut file, 1, &got, "same reason", LINUX), Ok(true)); - assert_eq!(file["platforms"], platforms); - assert_eq!(file["notes"][2], json!({"reason": "same reason", "seeds": [1]})); - assert_eq!(record(&mut file, 2, &got, "same reason", LINUX), Ok(true)); - assert_eq!(file["notes"][2]["seeds"], json!([1, 2])); -} - -/// One test per seed, and the list of them. -macro_rules! seeds { - ($($name:ident = $seed:literal),* $(,)?) => { - $( - #[test] - fn $name() { - check($seed); - } - )* - const LISTED: &[u64] = &[$($seed),*]; - }; -} - -seeds!( - seed_00 = 0, - seed_01 = 1, - seed_02 = 2, - seed_03 = 3, - seed_04 = 4, - seed_05 = 5, - seed_06 = 6, - seed_07 = 7, - seed_08 = 8, - seed_09 = 9, - seed_10 = 10, - seed_11 = 11, - seed_12 = 12, - seed_13 = 13, - seed_14 = 14, - seed_15 = 15, - seed_16 = 16, - seed_17 = 17, - seed_18 = 18, - seed_19 = 19, - seed_20 = 20, - seed_21 = 21, - seed_22 = 22, - seed_23 = 23, - seed_24 = 24, - seed_25 = 25, - seed_26 = 26, - seed_27 = 27, - seed_28 = 28, - seed_29 = 29, - seed_30 = 30, - seed_31 = 31, - seed_32 = 32, - seed_33 = 33, - seed_34 = 34, - seed_35 = 35, - seed_36 = 36, - seed_37 = 37, - seed_38 = 38, - seed_39 = 39, - seed_40 = 40, - seed_41 = 41, - seed_42 = 42, - seed_43 = 43, - seed_44 = 44, - seed_45 = 45, - seed_46 = 46, - seed_47 = 47, - seed_48 = 48, - seed_49 = 49, - seed_50 = 50, - seed_51 = 51, - seed_52 = 52, - seed_53 = 53, - seed_54 = 54, - seed_55 = 55, - seed_56 = 56, - seed_57 = 57, - seed_58 = 58, - seed_59 = 59, - seed_60 = 60, - seed_61 = 61, - seed_62 = 62, - seed_63 = 63, - seed_64 = 64, - seed_65 = 65, - seed_66 = 66, - seed_67 = 67, - seed_68 = 68, - seed_69 = 69, - seed_70 = 70, - seed_71 = 71, - seed_72 = 72, - seed_73 = 73, - seed_74 = 74, - seed_75 = 75, - seed_76 = 76, - seed_77 = 77, - seed_78 = 78, - seed_79 = 79, - seed_80 = 80, - seed_81 = 81, - seed_82 = 82, - seed_83 = 83, - seed_84 = 84, - seed_85 = 85, - seed_86 = 86, - seed_87 = 87, - seed_88 = 88, - seed_89 = 89, - seed_90 = 90, - seed_91 = 91, - seed_92 = 92, - seed_93 = 93, - seed_94 = 94, - seed_95 = 95, -); - -/// Every seed in 0..SEEDS has its test, once, and every recorded seed is one of them. -#[test] -fn every_seed_has_a_test() { - assert_eq!(LISTED, (0..SEEDS).collect::>().as_slice()); - let file = load(); - let recorded: Vec = file["seeds"].as_object().into_iter().flatten().filter_map(|(k, _)| k.parse().ok()).collect(); - assert!(recorded.iter().all(|s| *s < SEEDS), "{recorded:?}"); -} diff --git a/crates/engine/src/tests/rounded_loft_face.rs b/crates/engine/src/tests/rounded_loft_face.rs index 0029ae2f1..6e2f688e1 100644 --- a/crates/engine/src/tests/rounded_loft_face.rs +++ b/crates/engine/src/tests/rounded_loft_face.rs @@ -2,7 +2,7 @@ //! end a few 1e-5 mm short of the face's other edges, and where a round dies away at a corner the //! mesh keeps an edge from a point to itself; the face's outline still closes into one profile. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use super::*; @@ -27,7 +27,7 @@ fn a_sketch_on_either_end_of_a_rounded_loft_takes_the_whole_face() { let mut s = Session::default(); rounded_loft(&mut s); for up in [-1.0, 1.0] { - let world = s.world_state(); + let world = s.world_state().unwrap(); let loft = world.body("Loft").unwrap(); let face = loft.body.faces(0.01).unwrap().into_iter().find(|f| f.plane_normal.is_some_and(|n| n.dot(Vec3::Z * up) > 0.999)).unwrap(); let pick = json!({"body": "Loft", "index": face.index, "face": [face.centroid.x, face.centroid.y, face.centroid.z]}); @@ -37,7 +37,7 @@ fn a_sketch_on_either_end_of_a_rounded_loft_takes_the_whole_face() { run(&mut s2, "solid.extrude", json!({"sketch": id, "distance": 5, "operation": "new", "body_name": "Pad"})); let state = s2.model.state(); let pad = state.bodies.iter().find(|b| b.name == "Pad").unwrap(); - let v = pad.body.tessellate(1e-2).unwrap().measure().volume; + let v = pad.body.mesh(&crate::kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume; // The projected outline fits the round with splines, so it is close to the face, not exact. assert!(rel(v, face.area * 5.0) < 1e-2, "end {up}: {v} vs {}", face.area * 5.0); } diff --git a/crates/engine/src/tests/sphere_lens.rs b/crates/engine/src/tests/sphere_lens.rs index de06a19a9..394227fa7 100644 --- a/crates/engine/src/tests/sphere_lens.rs +++ b/crates/engine/src/tests/sphere_lens.rs @@ -28,8 +28,8 @@ fn negative_lens_extrude_cuts_a_partial_sphere_and_reopens() { let body = &state.bodies[0].body; assert!(body.validity().is_empty(), "{:?}", body.validity()); assert!(solidcraft_kernel::measure(body).unwrap().bbox.max.z < 20.01, "no lid across the opening"); - assert!(body.contains(Vec3::new(0., -10., 2.))); - assert!(!body.contains(Vec3::new(0., -10., 15.))); + assert_eq!(body.classify_point(Vec3::new(0., -10., 2.)).unwrap(), solidcraft_kernel::PointClass::Inside); + assert_eq!(body.classify_point(Vec3::new(0., -10., 15.)).unwrap(), solidcraft_kernel::PointClass::Outside); }; check(&mut s); let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); diff --git a/crates/engine/src/tests/step_import_options.rs b/crates/engine/src/tests/step_import_options.rs index fd8cbab47..52fbbc05f 100644 --- a/crates/engine/src/tests/step_import_options.rs +++ b/crates/engine/src/tests/step_import_options.rs @@ -2,7 +2,7 @@ //! on `file.insert_step` and `doc.open`. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_kernel::{ExportBody, ExportProduct, StepHeader, box_solid, step_export_products}; use super::run; @@ -44,7 +44,7 @@ fn frame_file(tag: &str) -> String { /// The lowest and highest corner of everything the design shows. fn extent(s: &Session) -> ([f64; 3], [f64; 3]) { - let b = crate::view::bounds(s); + let b = crate::view::bounds(s).unwrap(); ([b.min.x, b.min.y, b.min.z], [b.max.x, b.max.y, b.max.z]) } diff --git a/crates/engine/src/thread_tests.rs b/crates/engine/src/thread_tests.rs index e0424290a..9975f7f7e 100644 --- a/crates/engine/src/thread_tests.rs +++ b/crates/engine/src/thread_tests.rs @@ -1,10 +1,11 @@ //! Modelled threads: the ISO metric profile cut along a helix, inside and outside, //! including fine pitches on large shafts and the sample flange. +use solidcraft_geom::prelude::*; use std::f64::consts::PI; use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::Session; @@ -19,7 +20,7 @@ fn run(s: &mut Session, id: &str, p: Value) -> Value { /// measurement of its thousands of faces. fn volume(s: &mut Session, b: &str) -> f64 { let st = s.model.state(); - st.body(b).map(|mb| mb.body.tessellate(1e-3).unwrap().measure().volume).unwrap_or(0.0) + st.body(b).map(|mb| mb.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap().measure().volume).unwrap_or(0.0) } const SIZES: [(f64, f64); 9] = [(3.0, 0.5), (4.0, 0.7), (5.0, 0.8), (6.0, 1.0), (8.0, 1.25), (10.0, 1.5), (12.0, 1.75), (16.0, 2.0), (20.0, 2.5)]; @@ -54,7 +55,7 @@ fn tapped_thread_depth_keeps_reference_edge_placement_after_reopen() { }; assert_eq!(references.len(), 2); assert_eq!(thread_depth.as_ref().unwrap().to_string(), "3"); - assert!(!reopened.model.state().bodies[0].body.contains(Vec3::new(10.0, 12.0, 10.0))); + assert_eq!(reopened.model.state().bodies[0].body.classify_point(Vec3::new(10.0, 12.0, 10.0)).unwrap(), solidcraft_kernel::PointClass::Outside); } #[test] @@ -150,155 +151,12 @@ fn tapped_thread_depth_rejects_invalid_or_excessive_values_atomically() { assert_eq!(s.doc.to_json(), before); } -#[test] -fn thread_handedness_cosmetic_defaults_and_save_reopen_keep_axis_and_extent() { - use solidcraft_doc::{Document, FeatureKind, ThreadHandedness}; - for (hole, designation) in [(false, "M6"), (true, "M6"), (true, "G 1/4"), (true, "1/4-20 UNC")] { - let mut reference = None; - for hand in [None, Some("right"), Some("left")] { - let mut s = Session::default(); - let (command, mut params) = if hole { - run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10})); - ( - "solid.hole", - json!({"position":[10,10,10],"thread":designation,"depth":6,"thread_depth":3, - "references":[{"edge":[0,10,10],"distance":"7 mm"},{"edge":[10,0,10],"distance":"8 mm"}]}), - ) - } else { - run(&mut s, "solid.cylinder", json!({"radius":3,"height":6})); - ("solid.thread", json!({"face":[3,0,2],"designation":"M6","length":4})) - }; - if let Some(hand) = hand { - params["handedness"] = json!(hand); - } - run(&mut s, command, params); - let expected = if hand == Some("left") { ThreadHandedness::Left } else { ThreadHandedness::Right }; - let info = s.model.state().threads[0].clone(); - assert_eq!(info.handedness, expected); - if hole { - assert!((info.end - info.start - 3.0).abs() < 1e-8, "direction must retain the independent thread depth"); - } - let dimensions = (info.axis_point, info.axis, info.start, info.end, info.major_diameter, info.pitch); - assert_eq!(*reference.get_or_insert(dimensions), dimensions, "direction must not change axis, length or size"); - let mut kind = serde_json::to_value(&s.doc.features.last().unwrap().kind).unwrap(); - assert_eq!(kind.get("handedness"), (expected == ThreadHandedness::Left).then(|| json!("left")).as_ref()); - // An old feature with no field still deserializes to Right, for both feature types. - kind.as_object_mut().unwrap().remove("handedness"); - let old: FeatureKind = serde_json::from_value(kind).unwrap(); - assert!(matches!( - old, - FeatureKind::Hole { handedness: ThreadHandedness::Right, .. } | FeatureKind::Thread { handedness: ThreadHandedness::Right, .. } - )); - let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); - assert_eq!(reopened.model.state().threads[0], info); - } - } -} - -#[test] -fn thread_handedness_invalid_values_fail_without_changing_the_document() { - for hole in [false, true] { - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius":3,"height":6})); - let saved = s.doc.to_json(); - for hand in [json!("clockwise"), json!("LEFT"), json!(null), json!(true), json!(1)] { - let (command, params) = if hole { - ("solid.hole", json!({"position":[0,0,6],"thread":"M6","handedness":hand})) - } else { - ("solid.thread", json!({"face":[3,0,2],"designation":"M6","handedness":hand})) - }; - assert!(s.execute(command, ¶ms).unwrap_err().to_string().contains("handedness")); - assert_eq!(s.doc.to_json(), saved); - } - if hole { - assert!(s.execute("solid.hole", &json!({"position":[0,0,6],"diameter":2,"handedness":"left"})).is_err()); - assert_eq!(s.doc.to_json(), saved); - } - } -} - -#[test] -fn thread_handedness_modelled_internal_and_external_keep_chirality_and_bounded_volume() { - use solidcraft_doc::Document; - for internal in [false, true] { - let mut bodies = Vec::new(); - for hand in ["right", "left"] { - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius":if internal {6.0} else {3.0},"height":4,"body_name":"Stock"})); - if internal { - run(&mut s, "solid.hole", json!({"position":[0,0,4],"diameter":5})); - } - let face = json!([if internal { 2.5 } else { 3.0 }, 0, 3.5]); - run(&mut s, "solid.thread", json!({"face":face,"designation":"M6x1","length":3,"modeled":true,"handedness":hand})); - let state = s.model.state(); - let body = state.body("Stock").unwrap().body.clone(); - assert!(body.validity().is_empty(), "{internal}/{hand}: {:?}", body.validity()); - let before = volume(&mut s, "Stock"); - let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); - assert!((volume(&mut reopened, "Stock") - before).abs() < 1e-8); - let brep_volume = crate::kernel::measure(&body).unwrap().volume; - bodies.push((body, before, brep_volume)); - } - let [(right, vr, br), (left, vl, bl)] = bodies.as_slice() else { panic!("two directions") }; - eprintln!("handedness internal={internal}: mesh_mm3={vr}/{vl}, brep_mm3={br}/{bl}"); - for body in [right, left] { - let mesh = body.tessellate(0.001).unwrap(); - let low = mesh.positions.iter().map(|p| p.z).fold(f64::INFINITY, f64::min); - let high = mesh.positions.iter().map(|p| p.z).fold(f64::NEG_INFINITY, f64::max); - assert!(low.abs() < 1e-8 && (high - 4.0).abs() < 1e-8, "physical axial bounds: {low}/{high}"); - for z in [0.25, 1.5, 2.5, 3.75] { - assert_eq!(body.contains(Vec3::new(0.0, 0.0, z)), !internal, "axis stays solid in a shaft and open in a bore"); - if internal { - for i in 0..24 { - let a = 2.0 * PI * i as f64 / 24.0; - assert!(body.contains(Vec3::new(4.5 * a.cos(), 4.5 * a.sin(), z)), "the outer wall remains whole"); - } - } - } - } - let radius = if internal { 2.75 } else { 2.65 }; - let mut different = 0; - for z in [0.4, 1.1, 1.4, 1.8, 2.2, 2.6, 3.1, 3.5] { - for i in 0..24 { - let angle = 2.0 * PI * (i as f64 + 0.17) / 24.0; - let p = Vec3::new(radius * angle.cos(), radius * angle.sin(), z); - let reflected = Vec3::new(-p.x, p.y, p.z); - assert_eq!(right.contains(p), left.contains(reflected), "actual mirrored helix: {internal} at {p:?}"); - different += usize::from(right.contains(p) != left.contains(p)); - if z < 1.0 { - assert!(right.contains(p), "the 3 mm thread must leave the lower stub unchanged"); - } - } - } - assert!(different > 20, "Left must change real geometry, not just metadata: {internal}: {different}"); - // The sweep itself is an exact reflection (doc test). The existing Boolean first - // facets the curved stock within pitch * .005 mm. A nominal stock-faceting - // regression envelope uses radial annuli [r-d, r+d], with flat caps unchanged: - // pi*h*((r+d)^2-(r-d)^2) = 4*pi*h*r*d, summed over the outer and bore cylinders. - // Exact-set cutting would not enlarge the stock's symmetric difference. The BSP - // and rebuild also use numerical epsilons, so this conservative secondary ceiling - // is not a rigorous bound on every Boolean error, nor a precision/equal-volume proof. - let delta = 1.0 * 0.005; - let radii = if internal { 6.0 + 2.5 } else { 3.0 }; - let budget = 4.0 * PI * 4.0 * radii * delta; - eprintln!( - "handedness internal={internal}: post_boolean_delta_mm3={}, stock_faceting_budget_mm3={budget}, relative_delta={}", - (br - bl).abs(), - (br - bl).abs() / br - ); - assert!( - (br - bl).abs() <= budget, - "post-Boolean volume exceeds the configured stock faceting envelope: {internal}: {br}/{bl}, budget {budget}" - ); - } -} - /// Keep the original 48-station reproduction of the shell error even though new fine /// threads now use more stations. The same cut polygons must rebuild as a closed solid. #[test] fn faceted_flange_thread_preserves_thin_crest_boundaries() { - use crate::geom::{Plane, Vec2, Vec3}; use crate::kernel; + use solidcore_record::{Plane, Vec2, Vec3}; let mut s = Session::default(); let sample = crate::sample::samples().into_iter().find(|s| s.name == "Bolted Flange").unwrap(); @@ -319,8 +177,8 @@ fn faceted_flange_thread_preserves_thin_crest_boundaries() { let groove = kernel::sweep_helix_mesh(&plane, §ion, base, *cylinder.axis, pitch, (end - start) / pitch, 48).unwrap(); let cut = kernel::faceted_boolean(body, &groove, kernel::BoolOp::Cut, pitch * 0.005).unwrap().unwrap(); assert!(cut.validity().is_empty(), "{:?}", cut.validity()); - let before = body.tessellate(0.001).unwrap().measure().volume; - let after = cut.tessellate(0.001).unwrap().measure().volume; + let before = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().measure().volume; + let after = cut.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().measure().volume; assert!(before - after > 700.0 && before - after < 1800.0, "removed {}", before - after); } @@ -362,66 +220,25 @@ fn modelled_full_length_fine_threads_on_large_shafts() { } } -/// A modelled thread on a shaft thicker than it turns the shaft down to the major diameter -/// over the threaded length, then cuts the thread: an M6 over the top 8 mm of an 8 mm shaft -/// leaves a 6 mm threaded section on an 8 mm stub, its turned face named for later features. -/// A shaft of the thread's own size is cut as it is. +/// Issue 2705: an M14 over the top 10 mm of a 14.6 mm boss on a plate. A modelled thread never +/// changes the size of the shaft it is on (#1018, #2853): it is refused with the size to make +/// the shaft, and the part is unchanged (tests/kernel-cases/threads/2705). #[test] -fn a_shaft_thicker_than_a_modelled_thread_is_turned_down_to_it() { - let (p, len) = (1.0, 8.0); - let root = 3.0 - 5.0 * p * 3f64.sqrt() / 16.0; - let groove = per_turn(root, 3.0, |r| p / 4.0 + 2.0 * (r - root) * (PI / 6.0).tan()) * len / p; - for (shaft, turned) in [(8.0, true), (6.0, false)] { - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius": shaft / 2.0, "height": 12, "body_name": "Shaft"})); - run(&mut s, "solid.thread", json!({"face": [shaft / 2.0, 0, 11], "designation": "M6", "length": len, "modeled": true})); - let ring = PI * (shaft * shaft / 4.0 - 9.0) * len; - let want = PI * shaft * shaft / 4.0 * 12.0 - ring - groove; - let got = volume(&mut s, "Shaft"); - assert!((got - want).abs() < groove * 0.03, "M6 on {shaft} mm: {got} mm³, want {want}"); - let st = s.model.state(); - let Some(b) = st.body("Shaft") else { panic!("no shaft") }; - assert!(b.body.validity().is_empty(), "{shaft} mm: {:?}", b.body.validity()); - // Nothing past the major diameter over the threaded length; the stub keeps its size. - let round = |z: f64, r: f64| { - (0..24).filter(|i| b.body.contains(Vec3::new(r * (PI * *i as f64 / 12.0).cos(), r * (PI * *i as f64 / 12.0).sin(), z))).count() - }; - assert_eq!(round(8.0, 3.05), 0, "{shaft} mm: the threaded part is turned to 6 mm"); - assert_eq!(round(2.0, shaft / 2.0 - 0.05), 24, "{shaft} mm: the stub is whole"); - let names = solidcraft_doc::naming::face_names(b); - let fid = s.doc.features.last().map(|f| f.id).unwrap_or(0); - let named = |role: &str| names.iter().any(|n| n.starts_with(&format!("F{fid}:{role}"))); - assert_eq!(named("turned"), turned, "{shaft} mm: {names:?}"); - assert_eq!(named("shoulder:"), turned, "{shaft} mm: {names:?}"); - } - - // A 9 mm shaft is close enough to M8 to be offered it; it was refused as too thick (#2688). - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius": 4.5, "height": 10, "body_name": "Shaft"})); - run(&mut s, "solid.thread", json!({"face": [4.5, 0, 5], "designation": "M8", "modeled": true})); - let root = 4.0 - 5.0 * 1.25 * 3f64.sqrt() / 16.0; - let groove = per_turn(root, 4.0, |r| 1.25 / 4.0 + 2.0 * (r - root) * (PI / 6.0).tan()) * 10.0 / 1.25; - let (want, got) = (PI * 16.0 * 10.0 - groove, volume(&mut s, "Shaft")); - assert!((got - want).abs() < groove * 0.03, "M8 on 9 mm: {got} mm³, want {want}"); -} - -/// Issue 2705: an M14 over the top 10 mm of a 14.6 mm boss on a plate. Turned to 14 mm first: -/// 1600 + π 7.3² 15 − π (7.3² − 7²) 10 − 5 turns of 50.189 mm³ (tests/kernel-cases/threads/2705). -#[test] -fn an_m14_thread_on_a_14_6_mm_boss_turns_it_to_14_mm() { +fn an_m14_thread_on_a_14_6_mm_boss_is_refused_with_the_size_to_make_it() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"corner": [-10, -10, 0], "length": 20, "width": 20, "height": 4, "body_name": "Part"})); run(&mut s, "solid.cylinder", json!({"radius": 7.3, "height": 15, "base": [0, 0, 4], "operation": "join", "targets": ["Part"]})); - run(&mut s, "solid.thread", json!({"face": [7.3, 0, 17], "designation": "M14", "length": 10, "modeled": true})); - let got = volume(&mut s, "Part"); - assert!((got - 3725.5127).abs() < 3725.5127 * 0.01, "{got} mm³"); + let before = volume(&mut s, "Part"); + let thread = json!({"face": [7.3, 0, 17], "designation": "M14", "length": 10, "modeled": true}); + let e = s.execute("solid.thread", &thread).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("this 14.6 mm shaft is too thick for a modelled M14 thread; make the shaft 14 mm for M14"), "{e}"); + assert!((volume(&mut s, "Part") - before).abs() < 1e-9); } -/// A shaft thinner than the thread's minor diameter is still refused, and so is a cosmetic -/// thread on a shaft thicker than it (a note changes nothing to turn). A shaft the part goes on -/// round (standing against a wall) is not turned into the wall. +/// A shaft thinner than the thread's minor diameter is refused, and so is a thread on a shaft +/// far thicker than it. #[test] -fn a_thin_shaft_or_one_the_part_surrounds_is_refused() { +fn a_shaft_far_off_the_threads_size_is_refused() { let refused = |s: &mut Session, body: &str, p: Value| { let before = volume(s, body); let e = s.execute("solid.thread", &p).err().map(|e| e.to_string()).unwrap_or_default(); @@ -438,11 +255,8 @@ fn a_thin_shaft_or_one_the_part_surrounds_is_refused() { let e = refused(&mut s, "Shaft", json!({"face": [4, 0, 5], "designation": "M6"})); assert!(e.contains("an M6 thread does not fit a 8.00 mm shaft"), "{e}"); - let mut s = Session::default(); - run(&mut s, "solid.box", json!({"corner": [2, -10, 0], "length": 10, "width": 20, "height": 10, "body_name": "Part"})); - run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 10, "operation": "join", "targets": ["Part"]})); - let e = refused(&mut s, "Part", json!({"face": [-4, 0, 5], "designation": "M6", "modeled": true})); - assert!(e.contains("this 8 mm shaft is too thick for a modelled M6 thread") && e.contains("part around it"), "{e}"); + let e = refused(&mut s, "Shaft", json!({"face": [4, 0, 5], "designation": "M6", "modeled": true})); + assert!(e.contains("an M6 thread does not fit a 8.00 mm shaft"), "{e}"); } #[test] @@ -457,7 +271,8 @@ fn a_thread_without_a_coarse_pitch_suggests_explicit_pitches() { } for designation in ["MNaN", "Minf", "M-28", "M0", "M1e9", "M1e999", "M28x", "M28xNaN"] { let e = s.execute("solid.thread", &json!({"face": [14, 0, 5], "designation": designation})).unwrap_err().to_string(); - assert!(e.contains("unknown thread"), "{designation}: {e}"); + // Each thread form names itself in its refusal: `unknown metric thread`. + assert!(e.contains("unknown metric thread"), "{designation}: {e}"); assert_eq!(s.doc.to_json(), saved); } run(&mut s, "solid.thread", json!({"face": [14, 0, 5], "designation": "M28x2"})); @@ -533,7 +348,7 @@ fn modelled_internal_threads_m3_to_m20() { run(&mut s, "solid.cylinder", json!({"base": [0, 0, -1], "radius": d1 / 2.0, "height": len + 2.0, "body_name": "Bore"})); run(&mut s, "solid.combine", json!({"target": "Nut", "tools": ["Bore"], "operation": "cut"})); let before = volume(&mut s, "Nut"); - let th = run(&mut s, "solid.thread", json!({"face": [d1 / 2.0, 0, len / 2.0], "modeled": true})); + let th = run(&mut s, "solid.thread", json!({"face": [d1 / 2.0, 0, len / 2.0], "designation": format!("M{d}"), "modeled": true})); assert!(th["thread"].is_null(), "{th}"); // Bolt-shaped space: P/8 flat at the major diameter, widening towards the bore. let want = per_turn(d1 / 2.0, d / 2.0, |r| p / 8.0 + 2.0 * (d / 2.0 - r) * slope) * len / p; @@ -547,14 +362,16 @@ fn modelled_internal_threads_m3_to_m20() { /// that would cut next to nothing is refused, with the drill to use and the size that fits; /// a cosmetic one is still only a note. #[test] -fn a_modelled_thread_that_would_cut_nothing_is_refused() { +fn a_modelled_thread_that_would_cut_nothing_narrows_the_hole_instead() { + // #11609: the hole is narrowed to the thread's minor diameter, and the reply says so. let mut s = hex_nut(5.0); - let before = volume(&mut s, "Nut"); - let e = s.execute("solid.thread", &json!({"face": [2.5, 0, 2], "designation": "M5", "modeled": true})).err().map(|e| e.to_string()); - let e = e.unwrap_or_default(); - assert!(e.contains("this 5 mm hole") && e.contains("drill 4.2 mm for M5") && e.contains("thread this hole M6"), "{e}"); - assert!((volume(&mut s, "Nut") - before).abs() < 1e-9); run(&mut s, "solid.thread", json!({"face": [2.5, 0, 2], "designation": "M5"})); + let before = volume(&mut s, "Nut"); + let made = run(&mut s, "solid.thread", json!({"face": [2.5, 0, 2], "designation": "M5", "modeled": true})); + let warning = s.model.result(made["feature"].as_u64().unwrap()).and_then(|r| r.warning.clone()).unwrap_or_default(); + assert!(warning.contains("narrowed the 5 mm hole to 4.1") && warning.contains("M5"), "{warning}"); + assert_eq!(made["warning"], json!(warning), "the reply says so too"); + assert!(volume(&mut s, "Nut") > before + 1.0); // A shaft no thicker than the thread's root (17.29 mm for M20) is refused the same way. let mut s = Session::default(); @@ -566,43 +383,50 @@ fn a_modelled_thread_that_would_cut_nothing_is_refused() { /// Issue 2688: an M8 modelled thread in a 6 mm hole (narrower than its 6.65 mm minor diameter) /// was refused as "the face is too far from the thread's diameter". It says what is wrong and -/// what to drill, as a hole that is too wide does. (A shaft too thick is turned down.) +/// what to drill, as a hole that is too wide does; and the same for a shaft that is too thick. #[test] -fn a_hole_too_narrow_says_so_and_what_fits() { +fn a_hole_too_narrow_or_a_shaft_too_thick_says_which_and_what_fits() { let mut s = hex_nut(6.0); let before = volume(&mut s, "Nut"); let e = s.execute("solid.thread", &json!({"face": [3.0, 0, 2], "designation": "M8", "modeled": true})).err().map(|e| e.to_string()); let e = e.unwrap_or_default(); - assert!(e.contains("this 6 mm hole is too narrow for a modelled M8 thread") && e.contains("drill 6.75 mm for M8"), "{e}"); + assert!(e.contains("this 6 mm hole is too narrow for a modelled M8 thread") && e.contains("drill 6.8 mm for M8"), "{e}"); assert!(!e.contains("too far"), "{e}"); assert!((volume(&mut s, "Nut") - before).abs() < 1e-9); + + let mut s = Session::default(); + // 9 mm is close enough to M8 to be offered it, too thick to cut it. + run(&mut s, "solid.cylinder", json!({"radius": 4.5, "height": 10, "body_name": "Shaft"})); + let e = s.execute("solid.thread", &json!({"face": [4.5, 0, 5], "designation": "M8", "modeled": true})).err().map(|e| e.to_string()); + let e = e.unwrap_or_default(); + assert!(e.contains("this 9 mm shaft is too thick for a modelled M8 thread") && e.contains("make the shaft 8 mm for M8"), "{e}"); } /// The limit is a quarter of the basic depth 5H/8: a hole up to 4.78 mm for M5 (4.86 mm for -/// M5x0.5) still takes a modelled thread, a wider one is refused with that pitch's drill. +/// M5x0.5) is cut as drilled, a wider one is narrowed to the thread's minor diameter first. #[test] fn the_cut_nothing_limit_holds_for_coarse_and_fine_pitch() { for (m, hole, refused) in [ ("M5", 4.5, None), ("M5", 4.75, None), - ("M5", 4.8, Some("drill 4.2 mm for M5, or thread this hole M6")), + ("M5", 4.8, Some("narrowed the 4.8 mm hole")), ("M5x0.5", 4.5, None), ("M5x0.5", 4.85, None), - ("M5x0.5", 4.9, Some("drill 4.5 mm for M5x0.5, or thread this hole M6")), - ("M5x0.5", 5.0, Some("drill 4.5 mm for M5x0.5, or thread this hole M6")), + ("M5x0.5", 4.9, Some("narrowed the 4.9 mm hole")), + ("M5x0.5", 5.0, Some("narrowed the 5 mm hole")), ] { let mut s = hex_nut(hole); let before = volume(&mut s, "Nut"); let made = s.execute("solid.thread", &json!({"face": [hole / 2.0, 0, 2], "designation": m, "modeled": true})); let cut = before - volume(&mut s, "Nut"); - match (refused, made) { - (None, Ok(_)) => assert!(cut > 0.05, "{m} in {hole} mm: removed {cut}"), - (Some(want), Err(e)) => { - let e = e.to_string(); - assert!(e.contains(&format!("this {hole} mm hole")) && e.contains(want), "{m} in {hole} mm: {e}"); - assert!(cut.abs() < 1e-9, "{m} in {hole} mm: removed {cut}"); + let warning = made.ok().and_then(|v| v["feature"].as_u64()).and_then(|f| s.model.result(f)).and_then(|r| r.warning.clone()); + match (refused, warning) { + (None, None) => assert!(cut > 0.05, "{m} in {hole} mm: removed {cut}"), + (Some(want), Some(w)) => { + assert!(w.contains(want) && w.contains(m), "{m} in {hole} mm: {w}"); + assert!(cut < -0.05, "{m} in {hole} mm: the bore was filled in, removed {cut}"); } - (want, got) => panic!("{m} in {hole} mm: want refused {want:?}, got {:?}", got.map(|_| ())), + (want, got) => panic!("{m} in {hole} mm: want narrowed {want:?}, got {got:?}"), } } } @@ -622,11 +446,13 @@ fn hex_nut(hole: f64) -> Session { s } -/// A screw with a modeled M5 thread of `length` millimetres: the number of faces the thread left -/// on it, and how long the fillet of the boss's top edges took. The fillet is the work under test: -/// it healed the thread's facets and compared each of them with the whole old body, which froze -/// the app for minutes (#602). -fn fillet_beside_a_thread(length: f64) -> (usize, std::time::Duration) { +/// Issue 602: rounding the edges of a hex boss on a threaded shaft froze the app. The thread's +/// thousands of facets were healed pair by pair, once per feature after it, and the fillet's +/// preview then compared each of them with the whole old body. With SMLib the thread is exact (a +/// few dozen faces). The 4 mm thread starts at the shaft's free bottom end: the hex's corners +/// (2.31 mm out, past the M5 root at 2.07 mm) stand in the groove's way at the top end. +#[test] +fn fillet_beside_a_modelled_thread_finishes() { let mut s = Session::default(); for (id, p) in [ ("sketch.create", json!({"plane": "XY"})), @@ -637,11 +463,10 @@ fn fillet_beside_a_thread(length: f64) -> (usize, std::time::Duration) { ("sketch.polygon.circumscribed", json!({"center": [0, 0], "radius": 2, "sides": 6})), ("sketch.finish", json!({})), ("solid.extrude", json!({"distance": 3, "profiles": [{"point": [0, 0]}], "operation": "join", "targets": ["Screw"]})), - ("solid.thread", json!({"face": [2.5, 0, 5], "designation": "M5", "length": length, "modeled": true})), + ("solid.thread", json!({"face": [2.5, 0, 5], "designation": "M5", "length": 4, "modeled": true})), ] { run(&mut s, id, p); } - let faces = s.model.state().body("Screw").map(|b| b.body.face_count()).unwrap_or(0); let volume_before = volume(&mut s, "Screw"); let top: Vec = (0..6) .map(|i| { @@ -651,74 +476,1033 @@ fn fillet_beside_a_thread(length: f64) -> (usize, std::time::Duration) { .collect(); let started = std::time::Instant::now(); run(&mut s, "solid.fillet", json!({"edges": top, "radius": 0.3})); - let took = started.elapsed(); + assert!(started.elapsed().as_secs() < 30, "the fillet took {:?}", started.elapsed()); let volume_after = volume(&mut s, "Screw"); assert!(volume_after < volume_before && volume_after > volume_before * 0.99, "{volume_before} -> {volume_after}"); - (faces, took) } -/// Whether a job several times the size took at most about linear: `pair` times the small job, -/// then the big one. The quadratic that the bug cost grows with the square of the work, so eight -/// times the small time is the limit. The load of the other test binaries can rise between the two -/// runs, so a pair that misses is measured again, up to three times. Load only ever slows a run, -/// so each size keeps its fastest time and the ratio is taken of those: a retry cannot pass a -/// regression on a small run that a spike happened to slow, once an earlier small run was fast. -/// -/// `slack` is the room the noise of a busy machine gets, on top of the ratio. -fn scales_linearly(mut pair: impl FnMut() -> (std::time::Duration, std::time::Duration), slack: std::time::Duration) -> Result<(), String> { - let limit = |small: f64| 8.0 * small + slack.as_secs_f64(); - let (mut small, mut big) = (f64::INFINITY, f64::INFINITY); - let mut runs = Vec::new(); - for _ in 0..3 { - let (s, b) = pair(); - small = small.min(s.as_secs_f64()); - big = big.min(b.as_secs_f64()); - runs.push(format!("{s:?} then {b:?}")); - if big < limit(small) { - return Ok(()); +/// The SMLib volume of a body (exact surfaces), for closed-form checks. +fn exact_volume(s: &Session, b: &str) -> f64 { + let st = s.model.state(); + st.body(b).map(|mb| solidcraft_kernel::measure(&mb.body).unwrap().volume).unwrap_or(0.0) +} + +/// One turn of the ISO 68-1 external groove inside a shaft of radius `rs` (its section clipped at +/// the surface): 2π∫ r g(r) dr from the root, g = P/4 + 2 (r - root) tan 30°. +fn ext_turn(d: f64, p: f64, rs: f64) -> f64 { + let root = d / 2.0 - 5.0 * p * 3f64.sqrt() / 16.0; + let (a, b) = (p / 4.0 - 2.0 * root * (PI / 6.0).tan(), 2.0 * (PI / 6.0).tan()); + let f = |r: f64| a * r * r / 2.0 + b * r * r * r / 3.0; + 2.0 * PI * (f(rs) - f(root)) +} + +/// The groove's half width at its widest: for an external thread at the tool's outer edge, +/// 0.05 P past the crest (the section reaches past the surface so the cut leaves no skin). +fn ext_half_width(d: f64, p: f64) -> f64 { + let root = d / 2.0 - 5.0 * p * 3f64.sqrt() / 16.0; + (p / 4.0 + 2.0 * (d / 2.0 + 0.05 * p - root) * (PI / 6.0).tan()) / 2.0 +} + +/// A d10 shaft (z 10..35) on a d16 collar (z 0..10), as ladder 06/004. +fn shaft_on_collar() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 8, "height": 10, "body_name": "Part"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 10], "radius": 5, "height": 25, "operation": "join", "targets": ["Part"]})); + s +} + +/// Rig 602, ladder 06/004: a thread on a shaft ran a pitch past both ends of its face, into the +/// collar below as into the air above. It runs down to the shoulder and is trimmed at its plane +/// (#11610): the collar keeps its whole π 8² 10, and the groove takes 25/P turns, each slice of +/// the shaft along the axis losing the same. +#[test] +fn a_thread_runs_down_to_a_shoulder_and_leaves_it_whole() { + let mut s = shaft_on_collar(); + run(&mut s, "solid.thread", json!({"face": [5, 0, 25], "designation": "M10", "modeled": true})); + let want = PI * 64.0 * 10.0 + PI * 25.0 * 25.0 - 25.0 / 1.5 * ext_turn(10.0, 1.5, 5.0); + let got = exact_volume(&s, "Part"); + assert!((got - want).abs() < want * 2e-4, "{got} vs {want}"); +} + +/// The volume of a body's part between two heights along Z, within a quadrant of X and Y when +/// given (their signs). +fn volume_between(s: &Session, b: &str, (z0, z1): (f64, f64), quadrant: Option<(bool, bool)>) -> f64 { + let st = s.model.state(); + let mut part = st.body(b).unwrap().body.clone(); + let on = |origin: Vec3, normal: Vec3| solidcore_record::Plane::from_normal(origin, normal.normalized().unwrap()).unwrap(); + let z = Vec3::new(0.0, 0.0, 1.0); + let mut cuts = vec![(on(Vec3::new(0.0, 0.0, z0), z), true), (on(Vec3::new(0.0, 0.0, z1), z), false)]; + if let Some((x, y)) = quadrant { + cuts.push((on(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0)), x)); + cuts.push((on(Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0)), y)); + } + for (plane, positive) in cuts { + part = solidcraft_kernel::half_space(&part, &plane, positive).unwrap().0.unwrap(); + } + solidcraft_kernel::measure(&part).unwrap().volume +} + +/// #11610: a boss standing on a flat plate. The groove reaches the plate at every angle of the +/// last turn, wherever the helix lands on it (each height a different gap under a pitch): a thin +/// slice on the plate has lost as much as any slice of the thread, a pitch's slice as much in each +/// quadrant (the uncut block of the old stop sat in some of them), and the plate is whole. Before, +/// the last pitch kept up to a whole turn's groove uncut. +#[test] +fn a_thread_reaches_a_flat_shoulder_at_every_angle_and_leaves_it_whole() { + let (p, t, turn) = (1.5, 6.0, ext_turn(10.0, 1.5, 5.0)); + let per_mm = PI * 25.0 - turn / p; + for (h, extra) in [ + (16.0, json!({})), + (16.45, json!({})), + (16.6, json!({})), + (16.9, json!({})), + (17.4, json!({})), + (16.0, json!({"hand": "left"})), + (16.6, json!({"tip": "both"})), + ] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"corner": [-20, -20, 0], "length": 40, "width": 40, "height": t, "body_name": "Part"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, t], "radius": 5, "height": h, "operation": "join", "targets": ["Part"]})); + let mut ask = json!({"face": [5, 0, t + h / 2.0], "designation": "M10", "modeled": true}); + if let (Some(a), Value::Object(e)) = (ask.as_object_mut(), &extra) { + a.extend(e.clone()); + } + run(&mut s, "solid.thread", ask); + let name = format!("h {h} {extra}"); + assert!(s.model.state().body("Part").unwrap().body.validity().is_empty(), "{name}"); + let plate = volume_between(&s, "Part", (-1.0, t), None); + assert!((plate - 1600.0 * t).abs() < 1e-6 * 1600.0 * t, "{name}: the plate lost {} mm³", 1600.0 * t - plate); + let thin = volume_between(&s, "Part", (t, t + 0.1 * p), None); + let want = per_mm * 0.1 * p; + assert!((thin - want).abs() < want * 2e-3, "{name}: the slice on the plate is {thin}, not {want}"); + for quadrant in [(true, true), (true, false), (false, true), (false, false)] { + let got = volume_between(&s, "Part", (t, t + p), Some(quadrant)); + let want = per_mm * p / 4.0; + assert!((got - want).abs() < want * 2e-3, "{name}: {quadrant:?} of the last pitch is {got}, not {want}"); } } - Err(format!("{}; fastest {small:.3} s and {big:.3} s, limit {:.3} s", runs.join(", "), limit(small))) } +/// #11610: where a shoulder is not flat. A fillet or a chamfer at the shaft's base stays whole, the +/// groove trimmed where the face ends above it. A shoulder that rises back along the face (a +/// slanted plate, a boss on a round body) would be cut by a groove running to the plane of the +/// face's lowest point, so the groove keeps its square stop there. Nothing here fails. #[test] -fn scales_linearly_keeps_each_sizes_fastest_run() { - let pairs = |p: Vec<(u64, u64)>| { - let mut p = p.into_iter().map(|(s, b)| (std::time::Duration::from_millis(s), std::time::Duration::from_millis(b))); - move || p.next().unwrap_or((std::time::Duration::from_secs(1), std::time::Duration::from_secs(1))) +fn a_thread_at_a_shoulder_that_is_not_flat_still_builds() { + let (p, turn) = (1.5, ext_turn(10.0, 1.5, 5.0)); + let plate = |s: &mut Session| { + run(s, "solid.box", json!({"corner": [-20, -20, 0], "length": 40, "width": 40, "height": 6, "body_name": "Part"})); + run(s, "solid.cylinder", json!({"base": [0, 0, 6], "radius": 5, "height": 16, "operation": "join", "targets": ["Part"]})); }; - let slack = std::time::Duration::from_millis(0); - // Linear: four times the work, four times the time. - assert!(scales_linearly(pairs(vec![(5, 20)]), slack).is_ok()); - // A big run slowed by load, then a quiet pair. - assert!(scales_linearly(pairs(vec![(5, 80), (5, 20)]), slack).is_ok()); - // A quadratic cost (16x) whose later small runs a spike slowed: the fast first one still counts. - let r = scales_linearly(pairs(vec![(5, 80), (15, 80), (15, 80)]), slack); - assert!(r.as_ref().is_err_and(|e| e.contains("fastest 0.005 s and 0.080 s, limit 0.040 s")), "{r:?}"); + for finish in [("solid.fillet", json!({"edges": [[5, 0, 6]], "radius": 1})), ("solid.chamfer", json!({"edges": [[5, 0, 6]], "distance": 1}))] { + let mut s = Session::default(); + plate(&mut s); + run(&mut s, finish.0, finish.1); + let (base, shaft) = (volume_between(&s, "Part", (-1.0, 7.0), None), exact_volume(&s, "Part")); + run(&mut s, "solid.thread", json!({"face": [5, 0, 15], "designation": "M10", "modeled": true})); + assert!(s.model.state().body("Part").unwrap().body.validity().is_empty(), "{}", finish.0); + let left = volume_between(&s, "Part", (-1.0, 7.0), None); + assert!((left - base).abs() < 1e-6 * base, "{}: the base lost {} mm³", finish.0, base - left); + let (got, want) = (exact_volume(&s, "Part"), shaft - 15.0 / p * turn); + assert!((got - want).abs() < want * 2e-4, "{}: {got} vs {want}", finish.0); + } + let rising = [ + vec![("solid.cylinder", json!({"base": [0, 0, 0], "axis": [0.2, 0, 1], "radius": 20, "height": 6, "body_name": "Part"}))], + vec![("solid.cylinder", json!({"base": [0, -20, 0], "axis": [0, 1, 0], "radius": 10, "height": 40, "body_name": "Part"}))], + ]; + for cmds in rising { + let mut s = Session::default(); + for (c, ask) in cmds { + run(&mut s, c, ask); + } + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 2], "radius": 5, "height": 26, "operation": "join", "targets": ["Part"]})); + let before = exact_volume(&s, "Part"); + run(&mut s, "solid.thread", json!({"face": [5, 0, 20], "designation": "M10", "modeled": true})); + assert!(s.model.state().body("Part").unwrap().body.validity().is_empty()); + assert!(exact_volume(&s, "Part") < before); + } } -/// Issue 602: rounding the edges of a hex boss on a threaded shaft froze the app. The thread's -/// thousands of facets were healed pair by pair, once per feature after it, and the fillet's -/// preview then compared each of them with the whole old body. -/// -/// A ratio and not a limit: a test must not depend on wall-clock timing (CONTRIBUTING.md), the -/// machine is busy. The longer thread leaves about five times the facets, and the fillet healed -/// them in a time that grew with their square: linear is about 5x, the quadratic 25x or more. +/// #11610: the trim is for a thread that runs the whole face. A length stopping short of the +/// shoulder still stops there, however near. #[test] -fn fillet_beside_a_modelled_thread_finishes() { - /// The room the noise of a run on a busy machine gets, on top of the ratio. - const SLACK: std::time::Duration = std::time::Duration::from_millis(500); - let mut faces = 0; - if let Err(missed) = scales_linearly( - || { - let (_, small) = fillet_beside_a_thread(1.0); - let (facets, big) = fillet_beside_a_thread(8.0); - faces = facets; - (small, big) - }, - SLACK, - ) { - panic!("the fillet beside the thread does not scale linearly: {missed}"); - } - assert!(faces > 1000, "the thread is faceted: {faces} faces"); +fn a_thread_of_some_length_stops_where_it_is_told_short_of_a_shoulder() { + let (p, w) = (1.5, ext_half_width(10.0, 1.5)); + let mut s = shaft_on_collar(); + let before = exact_volume(&s, "Part"); + run(&mut s, "solid.thread", json!({"face": [5, 0, 25], "designation": "M10", "length": 24.6, "modeled": true})); + // Its end is within half a pitch of the shoulder: the stop stays clear of it. + let want = before - (24.6f64).min(25.0 - w) / p * ext_turn(10.0, p, 5.0); + let got = exact_volume(&s, "Part"); + assert!((got - want).abs() < want * 2e-4, "{got} vs {want}"); +} + +/// A d10 boss (z t..t+16) on a plate t thick, threaded M10: the plate's top is the shoulder. +/// The groove, with or without its runout, stays on the boss: the plate keeps all of itself +/// (what lies below z = t after the boss is cut away), and without a runout the boss loses +/// 16/P turns, as at a collar. The owner's bug: built as the app builds it (a rounded +/// plate, a circle sketched on its top face and extruded with Join), a plate thinner than 1.5 P +/// had no material where the free-end test looked (1 to 1.5 pitches past the face), so its top +/// was taken for a free end and the overrun cut a pitch into it. +#[test] +fn a_thread_on_a_boss_never_cuts_into_the_plate_below() { + let boss = |t: f64, extra: Value| { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.rounded", json!({"p0": [-20, -20], "p1": [20, 20], "radius": 5})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": t})); + run(&mut s, "sketch.create", json!({"plane": {"face": [0, 0, t]}})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 16, "operation": "join"})); + assert_eq!(s.model.state().bodies.len(), 1); + let mut p = json!({"face": [5, 0, t + 8.0], "modeled": true}); + if let (Some(p), Value::Object(e)) = (p.as_object_mut(), extra) { + p.extend(e); + } + run(&mut s, "solid.thread", p); + s + }; + let plate_left = |mut s: Session, t: f64| { + run( + &mut s, + "solid.box", + json!({"corner": [-30, -30, t], "length": 60, "width": 60, "height": 30, "body_name": "Above", "operation": "new_body"}), + ); + run(&mut s, "solid.combine", json!({"target": "Body1", "tools": ["Above"], "operation": "cut"})); + exact_volume(&s, "Body1") + }; + let plate = |t: f64| (40.0 * 40.0 - (4.0 - PI) * 25.0) * t; + let p = 1.5; + for t in [6.0, 1.0] { + let s = boss(t, json!({})); + let want = plate(t) + PI * 25.0 * 16.0 - 16.0 / p * ext_turn(10.0, p, 5.0); + let got = exact_volume(&s, "Body1"); + assert!((got - want).abs() < want * 2e-4, "plate {t}: {got} vs {want}"); + let left = plate_left(s, t); + assert!((left - plate(t)).abs() < 1e-6 * plate(t), "plate {t}: lost {} mm³", plate(t) - left); + } + for extra in [json!({"ease_out": "standard"}), json!({"ease_out": "short", "tip": "both"})] { + let s = boss(1.0, extra.clone()); + assert!(s.model.state().body("Body1").unwrap().body.validity().is_empty(), "{extra}"); + let left = plate_left(s, 1.0); + assert!((left - plate(1.0)).abs() < 1e-6 * plate(1.0), "{extra}: the plate below the boss lost {} mm³", plate(1.0) - left); + } +} + +/// Rig 602: "from the end nearest the pick" took the head end for a pick a little above the +/// middle. A thread of limited length starts at the face's only free end, wherever it is picked. +#[test] +fn a_thread_of_some_length_starts_at_the_only_free_end() { + let mut s = shaft_on_collar(); + let th = run(&mut s, "solid.thread", json!({"face": [5, 0, 15], "designation": "M10", "length": 6})); + let (a, b) = (th["thread"]["start"].as_f64().unwrap(), th["thread"]["end"].as_f64().unwrap()); + // The axis points up (+z) from the shaft's own axis point; the free end is the top, z = 35. + let k = th["thread"]["axis"][2].as_f64().unwrap(); + let z = |t: f64| th["thread"]["axis_point"][2].as_f64().unwrap() + k * t; + let (z0, z1) = (z(a).min(z(b)), z(a).max(z(b))); + assert!((z0 - 29.0).abs() < 1e-6 && (z1 - 35.0).abs() < 1e-6, "{th}"); +} + +/// Ladder 06/003: a pick in the middle of a face whose two ends are both free was a coin toss +/// (it fell to whichever end rounding favoured). It is refused, naming `from`; with `from` it runs +/// from that end, and a square stop inside the face takes exactly length / P turns. +#[test] +fn a_mid_face_pick_between_two_free_ends_needs_from() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 30, "body_name": "Part"})); + let e = s.execute("solid.thread", &json!({"face": [5, 0, 15], "designation": "M10", "length": 15, "modeled": true})); + let e = e.err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("both ends of the face are free") && e.contains("`from`"), "{e}"); + run(&mut s, "solid.thread", json!({"face": [5, 0, 15], "designation": "M10", "length": 15, "from": [0, 0, 30], "modeled": true})); + let want = PI * 25.0 * 30.0 - 10.0 * ext_turn(10.0, 1.5, 5.0); + let got = exact_volume(&s, "Part"); + assert!((got - want).abs() < want * 2e-4, "{got} vs {want}"); + // The groove is all in the top half: just under the surface, the bottom 15 mm (less the + // stop's half width) is whole and the top has the groove's turns. + let st = s.model.state(); + let body = &st.body("Part").unwrap().body; + let ring = |z: f64| (0..36).map(|i| (i as f64 * 10.0).to_radians()).map(move |a| Vec3::new(4.9 * a.cos(), 4.9 * a.sin(), z)); + let rings = |z0: f64, z1: f64| (0..=40).map(move |i| z0 + (z1 - z0) * i as f64 / 40.0).flat_map(ring); + assert!(rings(0.5, 14.0).all(|q| body.classify_point(q).unwrap() == solidcraft_kernel::PointClass::Inside), "the bottom half is cut"); + assert!( + rings(16.0, 29.5).filter(|q| body.classify_point(*q).unwrap() == solidcraft_kernel::PointClass::Outside).count() > 100, + "the top half is not threaded" + ); +} + +/// Up to a plane, or to a point's place along the axis, from the end given. +#[test] +fn a_thread_runs_up_to_a_plane_or_a_point() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "body_name": "Shaft"})); + let z = |th: &Value| { + let t = &th["thread"]; + let at = |u: &str| t["axis_point"][2].as_f64().unwrap() + t["axis"][2].as_f64().unwrap() * t[u].as_f64().unwrap(); + let (a, b) = (at("start"), at("end")); + (a.min(b), a.max(b)) + }; + let th = run(&mut s, "solid.thread", json!({"face": [4, 0, 10], "up_to": {"origin": [0, 0, 12], "normal": [0, 0, 1]}, "from": [0, 0, 0]})); + let (z0, z1) = z(&th); + assert!(z0.abs() < 1e-6 && (z1 - 12.0).abs() < 1e-6, "{th}"); + let th = run(&mut s, "solid.thread", json!({"face": [4, 0, 10], "extent": "up_to", "up_to": [4, 0, 5], "from": [0, 0, 20]})); + let (z0, z1) = z(&th); + assert!((z0 - 5.0).abs() < 1e-6 && (z1 - 20.0).abs() < 1e-6, "{th}"); + // An extent that contradicts the values given is refused. + let e = s.execute("solid.thread", &json!({"face": [4, 0, 10], "extent": "full", "length": 5})).err().map(|e| e.to_string()); + assert!(e.unwrap_or_default().contains("extent: full")); +} + +/// A blind tapped hole: the thread runs out of the entry and stops clear of the bottom, the +/// groove taking (depth - w)/P turns of 2π∫ r g(r) dr over the wall, w its widest half width (at +/// the tool's inner edge, 0.1 P inside the minor diameter). +#[test] +fn a_blind_tapped_hole_stops_clear_of_its_bottom() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"corner": [-10, -10, 0], "length": 20, "width": 20, "height": 20, "body_name": "Block"})); + run(&mut s, "solid.hole", json!({"position": [0, 0, 20], "diameter": 8.5, "depth": 12})); + let before = exact_volume(&s, "Block"); + run(&mut s, "solid.thread", json!({"face": [4.25, 0, 14], "designation": "M10", "modeled": true})); + let (d, p, rh) = (10.0, 1.5, 4.25); + let t = (PI / 6.0).tan(); + let minor = d / 2.0 - 5.0 * p * 3f64.sqrt() / 16.0; + let w = (p / 8.0 + 2.0 * (d / 2.0 - (minor - 0.1 * p)) * t) / 2.0; + // g(r) = P/8 + 2 (d/2 - r) tan 30°, over the wall r 4.25..5. + let f = |r: f64| (p / 8.0 + d * t) * r * r / 2.0 - 2.0 * t * r * r * r / 3.0; + let turn = 2.0 * PI * (f(d / 2.0) - f(rh)); + let want = before - (12.0 - w) / p * turn; + let got = exact_volume(&s, "Block"); + assert!((got - want).abs() < before * 1e-4, "{got} vs {want}"); +} + +/// A form's groove width at radius r between its root and crest: the pitch less the tooth, the +/// tooth `flat` wide at the crest radius `crest` and widening by tan a + tan b per unit of depth. +fn form_turn(p: f64, flat: f64, crest: f64, a: f64, b: f64, r0: f64, r1: f64, internal: bool) -> f64 { + let t = a.to_radians().tan() + b.to_radians().tan(); + let n = 2000; + let w = |r: f64| p - flat - (if internal { r - crest } else { crest - r }) * t; + (0..n).map(|i| r0 + (r1 - r0) * (i as f64 + 0.5) / n as f64).map(|r| 2.0 * PI * r * w(r) * (r1 - r0) / n as f64).sum() +} + +/// Every standard form cut into a shaft of its major diameter over six turns, right- and +/// left-handed: the groove takes 2π∫ r w(r) dr per turn (Pappus on the section, screw motion), +/// w from the standard's profile, from its external minor diameter to the shaft's surface. +#[test] +fn every_form_cuts_its_standard_profile() { + let inch = 25.4; + // (form, designation, d, P, crest flat, flanks, external minor radius) + let tr_ac = 0.25; + let acme_a = 0.020 * inch; + let t3 = 3f64.to_radians().tan() + 30f64.to_radians().tan(); + let t7 = 7f64.to_radians().tan() + 1.0; + let cases = [ + ("trapezoidal", "Tr20x4", 20.0, 4.0, 2.0 * (1.0 - 15f64.to_radians().tan()), (15.0, 15.0), 10.0 - 2.0 - tr_ac), + ( + "acme", + "3/4-6 ACME", + 0.75 * inch, + inch / 6.0, + inch / 12.0 * (1.0 - 14.5f64.to_radians().tan()), + (14.5, 14.5), + 0.375 * inch - inch / 12.0 - acme_a / 2.0, + ), + ("buttress", "S20x4", 20.0, 4.0, (4.0 - 3.0 * t3) / 2.0, (3.0, 30.0), 10.0 - 0.86777 * 4.0), + ( + "buttress_asme", + "1.5-8 BUTT", + 1.5 * inch, + inch / 8.0, + (inch / 8.0 - 0.6 * inch / 8.0 * t7) / 2.0, + (7.0, 45.0), + 0.75 * inch - 0.6 * inch / 8.0, + ), + ]; + for (form, designation, d, p, flat, (a, b), r3) in cases { + let mut volumes = Vec::new(); + for hand in ["right", "left"] { + let mut s = Session::default(); + let len = 6.0 * p; + run(&mut s, "solid.cylinder", json!({"radius": d / 2.0, "height": len, "body_name": "Shaft"})); + let before = exact_volume(&s, "Shaft"); + let th = run( + &mut s, + "solid.thread", + json!({"face": [d / 2.0, 0, len / 2.0], "form": form, "designation": designation, "hand": hand, "modeled": true}), + ); + assert!(th["thread"].is_null(), "{th}"); + let st = s.model.state(); + assert!(st.body("Shaft").unwrap().body.validity().is_empty(), "{designation} {hand}"); + let want = 6.0 * form_turn(p, flat, d / 2.0, a, b, r3, d / 2.0, false); + let got = before - exact_volume(&s, "Shaft"); + assert!((got - want).abs() < want * 1e-4, "{designation} {hand}: removed {got}, the standard's profile {want}"); + volumes.push(got); + } + assert!((volumes[0] - volumes[1]).abs() < volumes[0] * 1e-5, "{designation}: right {} left {}", volumes[0], volumes[1]); + } +} + +/// A left-handed groove turns the other way: on the helix z = P θ / 2π (right-handed) the shaft +/// is cut once a turn, on z = -P θ / 2π it is cut all along. Both: a right- and a left-handed +/// groove, crossing. +#[test] +fn a_left_handed_thread_turns_the_other_way() { + let (d, p, len) = (10.0, 1.5, 9.0); + let r = (d / 2.0 + d / 2.0 - 5.0 * p * 3f64.sqrt() / 16.0) / 2.0; + let on = |s: &Session, sign: f64| -> usize { + let st = s.model.state(); + let body = &st.body("Shaft").unwrap().body; + // Along each helix sense from every groove point on the z = 4.5 circle, count how often + // the line stays in the groove: a groove lies on one of them. + (0..36) + .filter(|i| { + let a0 = *i as f64 * 10f64.to_radians(); + let z0 = 4.5; + let probe = |a: f64| Vec3::new(r * (a0 + a).cos(), r * (a0 + a).sin(), z0 + sign * p * a / std::f64::consts::TAU); + body.classify_point(probe(0.0)).unwrap() == solidcraft_kernel::PointClass::Outside + && (1..12).all(|k| body.classify_point(probe(k as f64 * 0.5)).unwrap() == solidcraft_kernel::PointClass::Outside) + }) + .count() + }; + let mut volumes = Vec::new(); + for hand in ["right", "left", "both"] { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": d / 2.0, "height": len, "body_name": "Shaft"})); + let before = exact_volume(&s, "Shaft"); + run(&mut s, "solid.thread", json!({"face": [5, 0, 4.5], "designation": "M10", "hand": hand, "modeled": true})); + assert!(s.model.state().body("Shaft").unwrap().body.validity().is_empty(), "{hand}"); + let (right, left) = (on(&s, 1.0), on(&s, -1.0)); + match hand { + "right" => assert!(right > 0 && left == 0, "right: {right} {left}"), + "left" => assert!(left > 0 && right == 0, "left: {right} {left}"), + _ => assert!(left > 0 && right > 0, "both: {right} {left}"), + } + volumes.push(before - exact_volume(&s, "Shaft")); + } + let want = 6.0 * ext_turn(d, p, d / 2.0); + assert!((volumes[0] - want).abs() < want * 1e-4 && (volumes[1] - want).abs() < want * 1e-4, "{volumes:?} vs {want}"); + // Crossing, the two grooves share some of their volume. + assert!(volumes[2] > want * 1.2 && volumes[2] < 2.0 * want, "{volumes:?}"); +} + +/// A left-hand thread and tapped hole saved by v0.24.0 (format 39, `handedness: "left"`) open +/// left-handed; a tapped hole takes `hand` like a thread, never `both`, and only with a thread. +#[test] +fn a_format_39_left_hand_thread_and_tapped_hole_open_left_handed() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 60, "width": 60, "height": 12, "body_name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": [20, 30, 12], "thread": "M6", "depth": 8, "hand": "left"})); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 9, "base": [80, 0, 0], "body_name": "Shaft", "operation": "new"})); + run(&mut s, "solid.thread", json!({"face": [85, 0, 4.5], "designation": "M10", "hand": "left"})); + let hands = |s: &Session| -> Vec { s.model.state().threads.iter().map(|t| t.hand).collect() }; + let left = solidcraft_doc::thread_forms::ThreadHand::Left; + assert_eq!(hands(&s), [left, left]); + // What format 39 wrote: the direction as `handedness`, no pending changes. + let mut v: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + v["format"] = json!("solidcraft/39"); + v.as_object_mut().unwrap().remove("format_pending"); + for f in v["features"].as_array_mut().unwrap() { + if let Some(h) = f.as_object_mut().unwrap().remove("hand") { + f["handedness"] = h; + } + } + let reopened = Session::new(solidcraft_doc::Document::from_json(&v.to_string()).unwrap()); + assert_eq!(hands(&reopened), [left, left]); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 60, "width": 60, "height": 12})); + for (params, why) in [ + (json!({"position": [20, 30, 12], "thread": "M6", "depth": 8, "hand": "both"}), "unknown hand"), + (json!({"position": [20, 30, 12], "depth": 8, "hand": "left"}), "needs `thread`"), + ] { + let err = s.execute("solid.hole", ¶ms).unwrap_err().to_string(); + assert!(err.contains(why), "{err}"); + } +} + +/// A trapezoidal nut: the groove from the drilled minor diameter D1 = d - P out to the +/// internal root D4 = d + 2 ac (ISO 2904), 2π∫ r w(r) dr per turn. +#[test] +fn an_internal_trapezoidal_thread_cuts_out_to_its_root() { + let (d, p, ac) = (20.0, 4.0, 0.25); + let d1 = d - p; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"corner": [-20, -20, 0], "length": 40, "width": 40, "height": 6.0 * p, "body_name": "Nut"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, -1], "radius": d1 / 2.0, "height": 6.0 * p + 2.0, "body_name": "Bore"})); + run(&mut s, "solid.combine", json!({"target": "Nut", "tools": ["Bore"], "operation": "cut"})); + let before = exact_volume(&s, "Nut"); + run(&mut s, "solid.thread", json!({"face": [d1 / 2.0, 0, 3.0 * p], "designation": "Tr20x4", "modeled": true})); + let flat = p / 2.0 * (1.0 - 15f64.to_radians().tan()); + let want = 6.0 * form_turn(p, flat, d1 / 2.0, 15.0, 15.0, d1 / 2.0, d / 2.0 + ac, true); + let got = before - exact_volume(&s, "Nut"); + assert!((got - want).abs() < want * 1e-4, "{got} vs {want}"); +} + +/// No current standard defines a square thread: it is refused, saying what to use. +#[test] +fn a_square_thread_is_refused() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20})); + let e = s.execute("solid.thread", &json!({"face": [10, 0, 10], "form": "square", "designation": "20x4"})).err().map(|e| e.to_string()); + assert!(e.unwrap_or_default().contains("no current standard defines a square thread")); +} + +/// Ladder 06/008: n starts are n grooves of lead n P, each a turn's n-th further round: over the +/// same length they take n x L/(nP) turns, the volume of one start of that pitch, and do not +/// meet. A designation that gives the lead gives the starts. +#[test] +fn a_multi_start_thread_takes_the_volume_of_one_start() { + let (d, p, len) = (10.0, 1.5, 30.0); + let want = len / p * ext_turn(d, p, d / 2.0); + for (starts, designation) in [(2, "M10"), (3, "M10"), (1, "M10xPh3P1.5")] { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": len, "body_name": "Shaft"})); + let before = exact_volume(&s, "Shaft"); + run(&mut s, "solid.thread", json!({"face": [5, 0, 15], "designation": designation, "starts": starts, "modeled": true})); + let st = s.model.state(); + assert!(st.body("Shaft").unwrap().body.validity().is_empty(), "{designation} x{starts}"); + let got = before - exact_volume(&s, "Shaft"); + assert!((got - want).abs() < want * 1e-4, "{designation} x{starts}: removed {got}, one start {want}"); + } + // The cosmetic thread says it: two starts, lead 3. + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 20, "height": 40})); + let th = run(&mut s, "solid.thread", json!({"face": [20, 0, 20], "designation": "Tr40x14(P7)"})); + assert_eq!(th["thread"]["designation"], "Tr40x14(P7)", "{th}"); + assert_eq!(th["thread"]["starts"], 2, "{th}"); + let e = s.execute("solid.thread", &json!({"face": [20, 0, 20], "designation": "Tr40x14(P7)", "starts": 3})).err().map(|e| e.to_string()); + assert!(e.unwrap_or_default().contains("has 2 start(s), not 3")); +} + +/// The stock's volume after a modelled M10 thread, over sections z0..z1 whose outer radius is +/// `rmax(z)`: 2π∫∫ r m(r) dr dz, m the material fraction per pitch (1 under the root, 1 - w/P +/// in the groove's band). The groove's screw motion holds every meridian half-plane alike, and +/// an axisymmetric cut after it (a chamfer) only lowers rmax. +fn m10_stock(z0: f64, z1: f64, rmax: impl Fn(f64) -> f64) -> f64 { + let (d, p) = (10.0, 1.5); + let root = d / 2.0 - 5.0 * p * 3f64.sqrt() / 16.0; + let t = (PI / 6.0).tan(); + // ∫_0^R r m(r) dr in closed form: R²/2 to the root, then m = a + b r (1 - (P/4 + 2 (r - root) + // tan 30°)/P) beyond it. + let ring = |rr: f64| { + let inner = rr.min(root); + let mut v = inner * inner / 2.0; + if rr > root { + let (a, b) = (1.0 - 0.25 + 2.0 * root * t / p, -2.0 * t / p); + let f = |r: f64| a * r * r / 2.0 + b * r * r * r / 3.0; + v += f(rr) - f(root); + } + v + }; + let n = 20000; + (0..n).map(|i| z0 + (z1 - z0) * (i as f64 + 0.5) / n as f64).map(|z| 2.0 * PI * ring(rmax(z)) * (z1 - z0) / n as f64).sum() +} + +/// ISO 4753's chamfered end on both free ends of an M10 stud: a 45° cone down to the external +/// minor diameter d3 (ISO 724), cut after the groove; the volume as the stock's chamfered section +/// with the thread's material fraction (as ladder 06/006). d3 lies below the modelled root, so +/// each end face is the whole disk of d3, with the cone a whole ring around it, not pinched +/// where the groove reaches the end. +#[test] +fn a_chamfered_tip_tapers_the_last_teeth() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 30, "body_name": "Stud"})); + run(&mut s, "solid.thread", json!({"face": [5, 0, 15], "designation": "M10", "tip": "both", "modeled": true})); + let st = s.model.state(); + let stud = &st.body("Stud").unwrap().body; + assert!(stud.validity().is_empty()); + let rf = 5.0 - 17.0 / 24.0 * 1.5 * 3f64.sqrt() / 2.0; + let ends: Vec = + stud.faces(1e-4).unwrap().into_iter().filter(|f| f.plane_normal.is_some_and(|n| n.z.abs() > 0.999)).map(|f| f.area).collect(); + assert_eq!(ends.len(), 2); + for a in ends { + assert!((a - PI * rf * rf).abs() < 1e-3 * a, "each end is a whole disk of d3: {a} vs {}", PI * rf * rf); + } + let want = m10_stock(0.0, 30.0, |z| 5f64.min(rf + z).min(rf + 30.0 - z)); + let got = exact_volume(&s, "Stud"); + assert!((got - want).abs() < want * 1e-4, "{got} vs {want}"); + // 30° to the axis and 0.5 mm deep, at the one free end of a shaft on a collar. + let mut s = shaft_on_collar(); + run( + &mut s, + "solid.thread", + json!({"face": [5, 0, 25], "designation": "M10", "tip": "both", "chamfer_angle": "30 deg", "chamfer_depth": 0.5, "modeled": true}), + ); + let rf = 4.5; + let slope = 30f64.to_radians().tan(); + let want = PI * 64.0 * 10.0 + m10_stock(10.0, 35.0, |z| 5f64.min(rf + (35.0 - z) * slope)); + let got = exact_volume(&s, "Part"); + assert!((got - want).abs() < want * 1e-4, "{got} vs {want}"); + // Internal threads take a countersink instead. + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"corner": [-10, -10, 0], "length": 20, "width": 20, "height": 10, "body_name": "Nut"})); + run(&mut s, "solid.hole", json!({"position": [0, 0, 10], "diameter": 8.5})); + let e = + s.execute("solid.thread", &json!({"face": [4.25, 0, 5], "designation": "M10", "tip": "both", "modeled": true})).err().map(|e| e.to_string()); + assert!(e.unwrap_or_default().contains("countersink")); + // ISO 4753 is for ISO metric threads: another form names its chamfer depth. + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 40, "body_name": "Screw"})); + let e = s + .execute("solid.thread", &json!({"face": [10, 0, 20], "designation": "Tr20x4", "tip": "both", "modeled": true})) + .err() + .map(|e| e.to_string()); + assert!(e.unwrap_or_default().contains("chamfer depth")); + run(&mut s, "solid.thread", json!({"face": [10, 0, 20], "designation": "Tr20x4", "tip": "both", "chamfer_depth": 2.5, "modeled": true})); + assert!(s.model.state().body("Screw").unwrap().body.validity().is_empty()); +} + +/// `tip: start` chamfers only the end the thread starts from: on a stud started from its top, the +/// top is chamfered down to d3 and the bottom stays as cut. A start against a shoulder is no free +/// end and is refused; `both` there chamfers the one free end. +#[test] +fn a_tip_at_the_start_chamfers_only_that_end() { + let rf = 5.0 - 17.0 / 24.0 * 1.5 * 3f64.sqrt() / 2.0; + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 30, "body_name": "Stud"})); + run(&mut s, "solid.thread", json!({"face": [5, 0, 15], "designation": "M10", "tip": "start", "from": [5, 0, 30], "modeled": true})); + assert!(s.model.state().body("Stud").unwrap().body.validity().is_empty()); + let want = m10_stock(0.0, 30.0, |z| 5f64.min(rf + 30.0 - z)); + let got = exact_volume(&s, "Stud"); + assert!((got - want).abs() < want * 1e-4, "{got} vs {want}"); + let mut s = shaft_on_collar(); + let e = s.execute("solid.thread", &json!({"face": [5, 0, 25], "designation": "M10", "tip": "start", "from": [5, 0, 10], "modeled": true})); + assert!(e.err().map(|e| e.to_string()).unwrap_or_default().contains("not a free end")); + run(&mut s, "solid.thread", json!({"face": [5, 0, 25], "designation": "M10", "tip": "both", "from": [5, 0, 10], "modeled": true})); + let e = s.execute("solid.thread", &json!({"face": [5, 0, 25], "designation": "M10", "tip": "chamfer", "modeled": true})); + assert!(e.err().map(|e| e.to_string()).unwrap_or_default().contains("now `both`")); +} + +/// M10's groove section moved `d` out from the axis, clipped at the shaft's radius 5: the cut per +/// radian of turn, ∫ r w(r - d) dr from its moved root out to 5 (w the section's own width at +/// its radius, P/4 + 2 (ρ - root) tan 30°). A cubic in d until the root reaches the surface. +fn m10_cut_per_radian(d: f64) -> f64 { + let p = 1.5; + let root = 5.0 - 5.0 * p * 3f64.sqrt() / 16.0; + let q1 = 2.0 * (PI / 6.0).tan(); + let q0 = p / 4.0 - q1 * root - q1 * d; + let a = root + d; + if a >= 5.0 { + return 0.0; + } + let f = |r: f64| q0 * r * r / 2.0 + q1 * r * r * r / 3.0; + f(5.0) - f(a) +} + +/// The mean cut per radian over a runout whose offset runs linearly 0..h: Simpson on the cubic up +/// to where the root leaves the shaft (exact), nothing beyond. +fn m10_runout_mean(h: f64) -> f64 { + let p = 1.5; + let top = 5.0 * p * 3f64.sqrt() / 16.0; + let n = 64; + let step = top / n as f64; + let simpson: f64 = (0..n) + .map(|i| { + let (a, b) = (i as f64 * step, (i + 1) as f64 * step); + (m10_cut_per_radian(a) + 4.0 * m10_cut_per_radian((a + b) / 2.0) + m10_cut_per_radian(b)) * step / 6.0 + }) + .sum(); + simpson / h +} + +/// ISO 3508 runouts on a shaft between two collars: the thread starts at the lower collar and +/// its inner end fades out over 1.25 P (short) or 2.5 P (standard) before the upper one, its +/// section moving out past the surface as it turns, reaching nothing where its section clears the +/// collar. The cut is the integral over the turn of the clipped section's 2π∫ r dA (Pappus with +/// the section moving): full turns at f(0), the runout at the mean of f over the offsets it +/// passes. A fade shorter than a turn is cut too; the start never fades (`ease_in` is refused). +#[test] +fn a_runout_fades_the_groove_out_before_the_shoulder() { + let (p, w) = (1.5, ext_half_width(10.0, 1.5)); + let root = 5.0 - 5.0 * p * 3f64.sqrt() / 16.0; + let h = 5.0 - root + 0.05 * p; + // Trimmed at the bottom collar's plane, stopped clear of the top one for its runout. + let turns = (35.0 - 10.0 - w) / p; + for (ease, r_out) in [(json!("short"), 1.25), (json!("standard"), 2.5), (json!("1 mm"), 1.0 / 1.5)] { + let mut s = shaft_on_collar(); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 35], "radius": 8, "height": 10, "operation": "join", "targets": ["Part"]})); + let before = exact_volume(&s, "Part"); + run(&mut s, "solid.thread", json!({"face": [5, 0, 20], "designation": "M10", "ease_out": ease, "from": [0, 0, 10], "modeled": true})); + assert!(s.model.state().body("Part").unwrap().body.validity().is_empty(), "{ease}"); + let want = 2.0 * PI * (m10_cut_per_radian(0.0) * (turns - r_out) + r_out * m10_runout_mean(h)); + let got = before - exact_volume(&s, "Part"); + // Where the section moves, the sweep's walls lie within its tolerance (1e-4 P) of the + // true surfaces, not on them: up to that times the walls (about 64 mm² a turn) of the + // runout and of a turn more. Measured: 0.018 (short), 0.012 (standard), 0.011 mm³ (1 + // mm), not growing with the runout's length; full-depth turns are exact radially. + let bound = 1e-4 * p * 64.0 * (r_out + 1.0); + assert!((got - want).abs() < bound, "{ease}: {got} vs {want}"); + } + // Longer runouts than the thread are refused, and so is a runout at the start. + let mut s = shaft_on_collar(); + let e = s.execute("solid.thread", &json!({"face": [5, 0, 20], "designation": "M10", "ease_out": 30, "modeled": true})); + assert!(e.err().map(|e| e.to_string()).unwrap_or_default().contains("longer than the thread")); + let e = s.execute("solid.thread", &json!({"face": [5, 0, 20], "designation": "M10", "ease_in": "standard", "modeled": true})); + assert!(e.err().map(|e| e.to_string()).unwrap_or_default().contains("`ease_in` is gone")); +} + +/// A modelled M10 thread's flanks are several B-spline faces per turn (spans of one sweep); where +/// two of them meet with one tangent plane and one curvature the join is left out of the shaded +/// view (still pickable and in the wireframe), so the flank reads as one surface. The normal angle across each join is measured +/// independently (`seam_diagnostics`, projecting stations onto both surfaces). +#[test] +fn a_modelled_threads_flank_joins_are_not_drawn() { + use solidcore_record::brep::Surface; + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5.0, "height": 12, "body_name": "Shaft"})); + run(&mut s, "solid.thread", json!({"face": [5.0, 0, 6.0], "designation": "M10x1.5", "modeled": true})); + let st = s.model.state(); + let body = &st.body("Shaft").unwrap().body; + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); + let record = body.record(); + let free_form = |f: u32| { + record + .faces + .get(f as usize) + .is_some_and(|f| f.nurbs.is_none() && matches!(f.surface, Surface::Spline { .. } | Surface::RationalSpline { .. })) + }; + let tolerances = solidcraft_kernel::ContinuityTolerances { gap_mm: 1e-3, angle_deg: 0.5, curvature_per_mm: 1.0, ..Default::default() }; + let report = solidcraft_kernel::seam_diagnostics(body, &[], 33, tolerances).unwrap(); + let mut flank_joins = 0; + let mut worst: f64 = 0.0; + for seam in &report.seams { + let e = seam.edge; + let uses = &record.edges[e].uses; + if uses.len() != 2 || !uses.iter().all(|u| free_form(u.face)) { + continue; + } + let angle = seam.normal_angle_deg.value; + if angle < 0.5 { + flank_joins += 1; + worst = worst.max(angle); + assert!(mesh.smooth_edges[e] && !mesh.shaded_edge_visible(e), "join {e} at {angle} deg is drawn"); + assert!(mesh.edge_visible(e) && mesh.edge_pickable(e), "join {e} stays in the wireframe and pickable"); + } else { + assert!(mesh.shaded_edge_visible(e), "crease {e} at {angle} deg is hidden"); + } + } + // SMLib's flank pieces meet with normals about 1.5e-6 degrees apart (measured). + assert!(flank_joins >= 32 && worst < 1e-4, "{flank_joins} flank joins, the worst {worst} deg apart"); +} + +/// A pipe thread's profile for [`pipe_material`]: (flank half angle, thread height h, flat at crest +/// and root), each per the pitch: ISO 228-1/7-1 55° h 0.640327 P of H 0.960491 P (parallel) or +/// 0.960237 P (taper), ASME B1.20.1 60° h 0.8 P of H 0.866025 P. +fn pipe_profile(form: &str) -> (f64, f64, f64) { + let (a, big_h, h) = match form { + "bspp" | "rp" => (27.5f64, 0.960491, 0.640327), + "bspt" => (27.5, 0.960237, 0.640327), + _ => (30.0, 0.866025, 0.8), + }; + (a.to_radians(), h, (big_h - h) * a.to_radians().tan()) +} + +/// The material a pipe thread leaves, over z0..z1, as 2π∫∫ r m dr dz with m the material +/// fraction per pitch at height y over the external thread's root, 1 - (P - flat - 2 y tan a)/P +/// (the tooth's width over the pitch), its major radius `crest(z)` (a taper's grows 1/32 per mm) +/// and the stock between `inner` and `outer`. External: full material under the root, the +/// envelope's cone taking all above the crest. Internal: the nut's teeth, crest at crest(z) - h, +/// nothing inside that (the tap's minor cone). +fn pipe_material(form: &str, p: f64, internal: bool, (z0, z1): (f64, f64), inner: f64, outer: f64, crest: impl Fn(f64) -> f64) -> f64 { + let (a, h, flat) = pipe_profile(form); + let (h, flat) = (h * p, flat * p); + let tooth = |y: f64| ((p - flat) * p.recip() - 2.0 * y * a.tan() / p).clamp(0.0, 1.0); + let (nz, nr) = (4000, 400); + let mut v = 0.0; + for i in 0..nz { + let z = z0 + (z1 - z0) * (i as f64 + 0.5) / nz as f64; + let rc = crest(z); + let (root, top) = if internal { (rc, rc - h) } else { (rc - h, rc) }; + let mut ring = 0.0; + // Exactly the full annuli, the band in fine steps. + let (b0, b1) = (root.min(top).clamp(inner, outer), root.max(top).clamp(inner, outer)); + if internal { + ring += (outer * outer - b1 * b1) / 2.0; + } else { + ring += (b0 * b0 - inner * inner) / 2.0; + } + for j in 0..nr { + let r = b0 + (b1 - b0) * (j as f64 + 0.5) / nr as f64; + let y = if internal { root - r } else { r - root }; + ring += r * tooth(y) * (b1 - b0) / nr as f64; + } + v += 2.0 * PI * ring * (z1 - z0) / nz as f64; + } + v +} + +/// ISO 7-1 and ASME B1.20.1 taper threads, ISO 228-1 parallel: an R 1/2 and a 1/2-14 NPT on pipe +/// stubs of their pipes' outside diameters (21.3 mm, 0.840 in), an Rc 1/2 through a plate and a +/// G 1/2, each cut from the top across the whole face (a free end past each end, so every +/// meridian half-plane averages the same profile). The taper puts the external thread's gauge +/// diameter its gauge length in from the small end (R 1/2: 20.955 at 8.2 mm; NPT: E1 + h at L1) +/// and the internal one's at its face. +#[test] +fn pipe_threads_cut_their_standard_profiles_and_tapers() { + let inch = 25.4; + // (designation, form, internal, stock radius, crest radius at z for a 12 mm stock threaded from z = 12) + let r_half: f64 = 20.955 / 2.0 - 8.2 / 32.0; + let npt_half: f64 = ((0.75843 + 0.32 / 16.0) + 0.8 / 14.0) * inch / 2.0 - 0.32 * inch / 32.0; + // ISO 7-1's Rp, parallel and internal, in a hole drilled to its minor diameter. + let rp_minor = 20.955 / 2.0 - 0.640327 * inch / 14.0; + let cases: [(&str, &str, bool, f64, Box f64>); 5] = [ + ("R 1/2", "bspt", false, 10.65, Box::new(move |z| r_half + (12.0 - z) / 32.0)), + ("1/2-14 NPT", "npt", false, 0.42 * inch, Box::new(move |z| npt_half + (12.0 - z) / 32.0)), + ("G 1/2", "bspp", false, 20.955 / 2.0, Box::new(|_| 20.955 / 2.0)), + ("Rc 1/2", "bspt", true, 9.2, Box::new(|z| 20.955 / 2.0 - (12.0 - z) / 32.0)), + ("Rp 1/2", "rp", true, rp_minor + 1e-4, Box::new(|_| 20.955 / 2.0)), + ]; + for (designation, form, internal, rs, crest) in cases { + let stock = || { + let mut s = Session::default(); + if internal { + run(&mut s, "solid.box", json!({"corner": [-20, -20, 0], "length": 40, "width": 40, "height": 12, "body_name": "Part"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, -1], "radius": rs, "height": 14, "body_name": "Bore"})); + run(&mut s, "solid.combine", json!({"target": "Part", "tools": ["Bore"], "operation": "cut"})); + } else { + run(&mut s, "solid.cylinder", json!({"radius": rs, "height": 12, "body_name": "Part"})); + } + s + }; + let face = [rs, 0.0, 6.0]; + let (mut s, mut cosmetic) = (stock(), stock()); + let out = run(&mut cosmetic, "solid.thread", json!({"face": face, "designation": designation, "from": [rs, 0, 12], "length": 12})); + assert_eq!(out["thread"]["designation"], json!(designation)); + run(&mut s, "solid.thread", json!({"face": face, "designation": designation, "modeled": true, "from": [rs, 0, 12], "length": 12})); + let st = s.model.state(); + assert!(st.body("Part").unwrap().body.validity().is_empty(), "{designation}"); + let p = inch / 14.0; + let got = exact_volume(&s, "Part"); + let (want, stock) = if internal { + let plate = 40.0 * 40.0 * 12.0; + let hole = PI * rs * rs * 12.0; + (plate - hole - (PI * (30.0 * 30.0 - rs * rs) * 12.0 - pipe_material(form, p, true, (0.0, 12.0), rs, 30.0, &crest)), plate - hole) + } else { + (pipe_material(form, p, false, (0.0, 12.0), 0.0, rs, &crest), PI * rs * rs * 12.0) + }; + // A parallel thread's meridians are alike exactly. A taper's section moves off the axis + // as it turns, so the meridians differ; the averaged profile met the cut within 0.12 % of + // the removed volume here (R 1/2 0.06 %, NPT 0.12 %). + let tol = if matches!(form, "bspp" | "rp") { 1e-5 } else { 2e-3 }; + assert!((got - want).abs() < (stock - want).abs() * tol, "{designation}: {got} vs {want} (stock {stock})"); + } +} + +/// A taper pipe thread's rules: it starts at a free end (not at a shoulder), ISO 7-1 names the +/// internal taper Rc and the external R (and Rp is internal only), a pipe thread has one start and +/// turns one way, and its chamfered tip is cut from the small end's major diameter. +#[test] +fn a_taper_pipe_thread_starts_at_a_free_end_and_is_named_for_its_side() { + let part = || { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 16, "height": 10, "body_name": "Part"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 10], "radius": 10.65, "height": 25, "operation": "join", "targets": ["Part"]})); + s + }; + let mut s = part(); + let err = |s: &mut Session, p: Value| s.execute("solid.thread", &p).err().map(|e| e.to_string()).unwrap_or_default(); + let e = err(&mut s, json!({"face": [10.65, 0, 20], "designation": "R 1/2", "modeled": true, "from": [10.65, 0, 10]})); + assert!(e.contains("starts at a free end"), "{e}"); + let e = err(&mut s, json!({"face": [10.65, 0, 20], "designation": "Rc 1/2", "modeled": true, "from": [10.65, 0, 35]})); + assert!(e.contains("an external taper thread is R"), "{e}"); + let e = err(&mut s, json!({"face": [10.65, 0, 20], "designation": "R 1/2", "starts": 2, "modeled": true})); + assert!(e.contains("one start"), "{e}"); + let e = err(&mut s, json!({"face": [10.65, 0, 20], "designation": "R 1/2", "hand": "both", "modeled": true, "from": [10.65, 0, 35]})); + assert!(e.contains("turns one way"), "{e}"); + let e = err(&mut s, json!({"face": [10.65, 0, 20], "designation": "Rp 1/2", "modeled": true, "from": [10.65, 0, 35]})); + assert!(e.contains("Rp is an internal thread"), "{e}"); + // ISO 4753's chamfered end is metric: a pipe thread gives its depth. + let e = err(&mut s, json!({"face": [10.65, 0, 20], "designation": "R 1/2", "tip": "start", "modeled": true, "from": [10.65, 0, 35]})); + assert!(e.contains("chamfer depth"), "{e}"); + // From the free end it runs ISO 7-1's useful thread, 13.2 mm for R 1/2. + let out = run(&mut s, "solid.thread", json!({"face": [10.65, 0, 20], "designation": "R 1/2", "from": [10.65, 0, 35]})); + let t = &out["thread"]; + assert!((t["end"].as_f64().unwrap() - t["start"].as_f64().unwrap() - 13.2).abs() < 1e-9, "{t}"); + let mut plain = part(); + run(&mut plain, "solid.thread", json!({"face": [10.65, 0, 20], "designation": "R 1/2", "modeled": true, "from": [10.65, 0, 35]})); + assert!(plain.model.state().body("Part").unwrap().body.validity().is_empty()); + // The chamfered tip of a taper thread: the cone reaches the small end's major diameter less + // the depth, and cuts the first teeth. + let p = 25.4 / 14.0; + run( + &mut s, + "solid.thread", + json!({"face": [10.65, 0, 20], "designation": "R 1/2", "modeled": true, "from": [10.65, 0, 35], "tip": "start", "chamfer_depth": 0.640327 * p}), + ); + assert!(s.model.state().body("Part").unwrap().body.validity().is_empty()); + let (chamfered, threaded) = (exact_volume(&s, "Part"), exact_volume(&plain, "Part")); + assert!(chamfered < threaded - 1e-3, "the tip cuts the first teeth: {chamfered} vs {threaded}"); +} + +/// A tapped hole's thread cut into its wall (`modeled`), as the thread feature cuts one: an M8 +/// blind hole whose groove stops clear of the drill point's bottom, or fades out before it +/// (`ease_out`, ISO 3508), which leaves more of the wall than the full form there; an Rc 1/2 +/// through a plate, drilled with the tap maker's drill and cut to its taper; each a valid body +/// that reopens the same. An Rc size with no tabulated drill is refused. +#[test] +fn a_modelled_tapped_hole_stops_clear_of_its_bottom_or_fades_out_before_it() { + let blind = |extra: Value| { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":30,"width":30,"height":20,"body_name":"Plate"})); + let mut p = json!({"position":[15,15,20],"direction":[0,0,-1],"thread":"M8","depth":14,"type":"drilled"}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + run(&mut s, "solid.hole", p); + assert!(s.model.state().body("Plate").unwrap().body.validity().is_empty(), "{extra}"); + s + }; + let (drilled, square, fade) = (blind(json!({})), blind(json!({"modeled":true})), blind(json!({"modeled":true,"ease_out":"standard"}))); + let (v0, v1, v2) = (exact_volume(&drilled, "Plate"), exact_volume(&square, "Plate"), exact_volume(&fade, "Plate")); + assert!(v1 < v2 && v2 < v0, "drilled {v0}, square {v1}, fade {v2}"); + // The groove never reaches the drill point: the bottom's cone is the drilled one. + assert!(square.model.state().threads.is_empty(), "a modelled thread is cut, not listed"); + let reopened = Session::new(solidcraft_doc::Document::from_json(&fade.doc.to_json()).unwrap()); + assert!((exact_volume(&reopened, "Plate") - v2).abs() < 1e-6); + + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":40,"width":40,"height":12,"body_name":"Plate"})); + let out = run(&mut s, "solid.hole", json!({"position":[20,20,12],"direction":[0,0,-1],"thread":"Rc 1/2"})); + let drilled = exact_volume(&s, "Plate"); + // The tap maker's drill for a straight Rc 1/2 hole (Yamawa YEU23 p.709). + let drill: f64 = 17.6; + assert!((drilled - (40.0 * 40.0 * 12.0 - PI * (drill / 2.0).powi(2) * 12.0)).abs() < 1e-3, "{drilled}"); + let id = out["feature"].as_u64().unwrap(); + let redefine = json!({"position":[20,20,12],"direction":[0,0,-1],"thread":"Rc 1/2","modeled":true}); + run(&mut s, "timeline.redefine", json!({"feature":id,"command":"solid.hole","params":redefine})); + assert!(s.model.state().body("Plate").unwrap().body.validity().is_empty()); + assert!(exact_volume(&s, "Plate") < drilled - 1.0); + + let err = |p: Value| Session::default().execute("solid.hole", &p).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(err(json!({"position":[0,0,0],"diameter":5,"modeled":true})).contains("`modeled` needs `thread`")); + assert!(err(json!({"position":[0,0,0],"thread":"M8","ease_out":"standard"})).contains("modelled thread")); + assert!(err(json!({"position":[0,0,0],"thread":"Rc 5"})).contains("no tap drill is tabulated")); + // Another drill than the tap maker's (M8: 6.8 mm): from the minor diameter to 5% over it. + let drill = |d: f64| { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":30,"width":30,"height":20,"body_name":"Plate"})); + s.execute("solid.hole", &json!({"position":[15,15,20],"thread":"M8","diameter":d})).err().map(|e| e.to_string()).unwrap_or_default() + }; + let e = drill(7.5); + assert!(e.contains("from 6.647 to 7.14 mm") && e.contains("too little of the thread"), "{e}"); + assert!(drill(6.5).contains("the tap cannot cut")); + assert!(drill(7.1).is_empty() && drill(6.7).is_empty(), "inside the range"); +} + +/// A tapped hole given no `diameter` drills the tap maker's drill for its size (M8: 6.8 mm, 1/4-20 +/// UNC: 5.1054 mm); a given diameter is kept. +#[test] +fn a_tapped_hole_given_no_diameter_drills_the_tap_makers_drill() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":40,"width":20,"height":10,"body_name":"Plate"})); + let mut drilled = |p: Value| { + let id = run(&mut s, "solid.hole", p)["feature"].as_u64().unwrap(); + match &s.doc.feature(id).unwrap().kind { + solidcraft_doc::FeatureKind::Hole { diameter, .. } => diameter.to_string(), + k => panic!("{k:?}"), + } + }; + assert_eq!(drilled(json!({"position":[10,10,10],"thread":"M8"})), "6.8 mm"); + assert_eq!(drilled(json!({"position":[25,10,10],"thread":"1/4-20 UNC"})), "5.1054 mm"); + assert_eq!(drilled(json!({"position":[33,10,10],"thread":"M8","diameter":"6.9 mm"})), "6.9 mm"); +} + +/// A block with a bore of `dia` cut through it by a sketch circle. +fn block_with_bore(dia: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"corner": [-20, -20, 0], "length": 40, "width": 40, "height": 20, "body_name": "Blk"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "H"})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "diameter": dia})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "H", "through_all": true, "direction": "positive", "operation": "cut"})); + s +} + +/// #11609: a 12 mm hole took M14 (the size whose tap drill is 12 mm) and a modelled M12 in it was +/// refused. Automatic sizing now takes the size with the hole's nominal diameter first; a hole +/// near no nominal diameter is still matched by tap drill. +#[test] +fn a_hole_takes_the_size_of_its_nominal_diameter_first() { + for (dia, want) in [(12.0, "M12"), (12.1, "M12"), (10.0, "M10"), (8.0, "M8"), (14.0, "M14"), (10.2, "M12"), (13.0, "M14"), (11.0, "M12")] { + let mut s = block_with_bore(dia); + let th = run(&mut s, "solid.thread", json!({"face": [dia / 2.0, 0, 10]})); + assert_eq!(th["thread"]["designation"], json!(want), "a {dia} mm hole"); + } + // A shaft is still its major diameter. + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 6, "height": 30, "body_name": "Sh"})); + let th = run(&mut s, "solid.thread", json!({"face": [6, 0, 15]})); + assert_eq!(th["thread"]["designation"], json!("M12")); +} + +/// #11609: M12 modelled in a 12 mm hole narrows the bore to the thread's minor diameter and cuts +/// the thread there, and says so; the cosmetic M12 is the same size on the same bore. +#[test] +fn a_modelled_thread_in_a_hole_as_wide_as_it_narrows_the_bore() { + for (dia, d, p) in [(12.0, 12.0, 1.75), (14.0, 14.0, 2.0), (12.2, 12.0, 1.75), (13.0, 12.0, 1.75)] { + let mut s = block_with_bore(dia); + let before = volume(&mut s, "Blk"); + let made = run(&mut s, "solid.thread", json!({"face": [dia / 2.0, 0, 10], "designation": format!("M{d}"), "modeled": true})); + let warning = s.model.result(made["feature"].as_u64().unwrap()).and_then(|r| r.warning.clone()).unwrap_or_default(); + assert!(warning.contains("narrowed the") && warning.contains(&format!("M{d}")), "{warning}"); + // The bore is now the minor diameter's, so there is material where there was air, but + // less than a full sleeve (the groove cut into it). + let h = p * 3f64.sqrt() / 2.0; + let minor = d - 2.0 * 5.0 * h / 8.0; + let sleeve = PI * ((dia / 2.0).powi(2) - (minor / 2.0).powi(2)) * 20.0; + let added = volume(&mut s, "Blk") - before; + assert!(added > 0.2 * sleeve && added < sleeve, "M{d} in {dia}: added {added}, a full sleeve is {sleeve}"); + } + // Automatic and modelled, and cosmetic, on the 12 mm bore. + let mut s = block_with_bore(12.0); + let th = run(&mut s, "solid.thread", json!({"face": [6, 0, 10], "designation": "M12"})); + assert_eq!(th["thread"]["designation"], json!("M12")); + let mut s = block_with_bore(12.0); + let made = run(&mut s, "solid.thread", json!({"face": [6, 0, 10], "modeled": true})); + assert!(s.model.result(made["feature"].as_u64().unwrap()).and_then(|r| r.warning.clone()).unwrap_or_default().contains("M12")); +} + +/// A hole that already has the wall for the groove is not narrowed, and a size nowhere near the +/// hole is refused with the size it does take. +#[test] +fn a_hole_with_wall_for_the_groove_is_left_as_drilled() { + let mut s = block_with_bore(10.2); + let made = run(&mut s, "solid.thread", json!({"face": [5.1, 0, 10], "designation": "M12", "modeled": true})); + assert!(s.model.result(made["feature"].as_u64().unwrap()).and_then(|r| r.warning.clone()).is_none()); + let mut s = block_with_bore(20.0); + let e = s.execute("solid.thread", &json!({"face": [10, 0, 10], "designation": "M12", "modeled": true})).unwrap_err().to_string(); + assert!(e.contains("does not fit a 20.00 mm hole") && e.contains("takes M20"), "{e}"); +} + +/// #11609: a design saved with an automatic thread keeps the size it had (a 12 mm hole stays +/// M14), while the same thread made now takes M12. +#[test] +fn a_saved_automatic_thread_keeps_its_old_size() { + let mut s = block_with_bore(12.0); + run(&mut s, "solid.thread", json!({"face": [6, 0, 10]})); + let designations = |s: &Session| -> Vec { s.model.state().threads.iter().map(|t| t.designation.clone()).collect() }; + assert_eq!(designations(&s), ["M12"]); + // As the release before saved it: the last folded format, none of today's pending changes. + let mut v: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + v["format"] = json!("solidcraft/49"); + v.as_object_mut().unwrap().remove("format_pending"); + let reopened = Session::new(solidcraft_doc::Document::from_json(&v.to_string()).unwrap()); + assert_eq!(designations(&reopened), ["M14"]); + let saved: Value = serde_json::from_str(&reopened.doc.to_json()).unwrap(); + let thread = saved["features"].as_array().unwrap().iter().find(|f| f["type"] == json!("thread")).unwrap(); + assert_eq!(thread["old_auto_size"], json!(true)); +} + +/// Editing a saved automatic thread (which keeps its old size) does not change its size. +#[test] +fn editing_a_saved_automatic_thread_keeps_its_old_size() { + let mut s = block_with_bore(12.0); + let made = run(&mut s, "solid.thread", json!({"face": [6, 0, 10]})); + let mut v: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + v["format"] = json!("solidcraft/49"); + v.as_object_mut().unwrap().remove("format_pending"); + let mut s = Session::new(solidcraft_doc::Document::from_json(&v.to_string()).unwrap()); + let designations = |s: &Session| -> Vec { s.model.state().threads.iter().map(|t| t.designation.clone()).collect() }; + assert_eq!(designations(&s), ["M14"]); + run(&mut s, "timeline.redefine", json!({"feature": made["feature"], "command": "solid.thread", "params": {"face": [6, 0, 10], "hand": "left"}})); + assert_eq!(designations(&s), ["M14"]); } diff --git a/crates/engine/src/timing.rs b/crates/engine/src/timing.rs index 42e9e87f5..07bb2c945 100644 --- a/crates/engine/src/timing.rs +++ b/crates/engine/src/timing.rs @@ -40,6 +40,20 @@ pub fn time(profile: bool, f: impl FnOnce() -> T) -> (T, Step) { } } +/// `SOLIDCRAFT_PROFILE` asks for the profiler from the start: `1`, `true`, `on` or `yes`. +pub fn profile_env_on(value: Option<&str>) -> bool { + value.map(|v| v.trim().to_ascii_lowercase()).is_some_and(|v| matches!(v.as_str(), "1" | "true" | "on" | "yes")) +} + +/// Start the profiler when `SOLIDCRAFT_PROFILE` asks for it (the apps call this at start-up); +/// true when it is recording. +pub fn profile_from_env() -> bool { + if profile_env_on(solidcraft_geom::env::var("PROFILE").as_deref()) { + solidcraft_profile::set_enabled(true); + } + solidcraft_profile::enabled() +} + /// Milliseconds to the microsecond, so the JSON stays readable. pub fn round_ms(ms: f64) -> f64 { if ms.is_finite() { (ms * 1000.0).round() / 1000.0 } else { 0.0 } @@ -64,6 +78,16 @@ impl Step { mod tests { use super::*; + #[test] + fn the_profile_variable_takes_the_usual_yes_words() { + for v in ["1", "true", " ON ", "yes"] { + assert!(profile_env_on(Some(v)), "{v}"); + } + for v in [None, Some(""), Some("0"), Some("off"), Some("2")] { + assert!(!profile_env_on(v), "{v:?}"); + } + } + #[test] fn steps_report_their_time_and_profile_only_when_asked() { let (r, step) = time(false, || 7); diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 611151ba6..5712ae1a3 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -2,13 +2,15 @@ //! grid and the origin. Used by the headless snapshot renderer; the GPU viewport draws the same //! content. +use solidcraft_geom::prelude::*; use std::sync::Arc; -use solidcraft_geom::{Aabb3, Plane, Vec3}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::Aabb3; use solidcraft_render::{AnalysisColors, Camera, Rgb, Scene, SceneAnalysis, SceneLine, SceneMesh}; use solidcraft_sketch::Sketch; -use crate::{Sel, Session}; +use crate::{Result, Sel, Session}; /// Colours (shared with the GPU viewport). pub mod colors { @@ -23,6 +25,8 @@ pub mod colors { /// Fixed (locked) geometry. pub const SKETCH_LOCKED: Rgb = Rgb(0, 140, 60); pub const SKETCH_CENTERLINE: Rgb = Rgb(200, 110, 60); + /// Isocurve Analysis curves: the light theme's accent. + pub const ISOCURVE: Rgb = Rgb(38, 120, 218); /// Linked (projected) reference geometry. pub const SKETCH_PROJECTED: Rgb = Rgb(150, 60, 190); /// Linked geometry whose reference was lost. @@ -70,6 +74,10 @@ pub struct Palette { pub axes: [Rgb; 3], /// What the section cap is tinted toward. pub cap: Rgb, + /// The section hatch's other colours, after the cap's (`Scene::part_hatch`). + pub hatch: [Rgb; 2], + /// Isocurve Analysis: the faces' isoparametric curves. + pub isocurve: Rgb, /// The surface analysis colours. pub analysis: AnalysisColors, } @@ -93,6 +101,8 @@ impl Palette { sketch_centerline: colors::SKETCH_CENTERLINE, axes: [colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z], cap: colors::SECTION_CAP, + hatch: solidcraft_render::SECTION_HATCH, + isocurve: colors::ISOCURVE, analysis: AnalysisColors::DEFAULT, }; } @@ -105,8 +115,9 @@ impl Default for Palette { /// Bounds of everything visible now, in world space: shown bodies where their occurrences, /// joints and moves place them, and the sketches the view draws (not ones used by a feature, -/// hidden ones, or ones in hidden components). What Home, Fit and the orbit pivot frame. -pub fn bounds(s: &Session) -> Aabb3 { +/// hidden ones, or ones in hidden components). What Home, Fit and the orbit pivot frame. A model +/// that cannot be placed is the error. +pub fn bounds(s: &Session) -> Result { bounds_by(s, |body| body.mesh_bounds()) } @@ -122,12 +133,12 @@ pub fn shown_point_clouds(s: &Session) -> impl Iterator Aabb3 { +pub fn unmeshed_bounds(s: &Session) -> Result { bounds_by(s, |body| body.cached_mesh().map(|m| m.bounds()).unwrap_or_else(|| body.outline_bounds())) } -fn bounds_by(s: &Session, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> Aabb3 { - let st = s.world_state(); +fn bounds_by(s: &Session, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> Result { + let st = s.world_state()?; let mut b = Aabb3::EMPTY; for body in st.bodies.iter().filter(|x| s.body_visible(&x.name)) { b = b.union(&of(body)); @@ -135,7 +146,7 @@ fn bounds_by(s: &Session, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> A for ss in st.sketches.iter().filter(|x| sketch_shown(s, x.feature)) { // All four corners: on a tilted plane two opposite ones don't span the rectangle. if let Some((lo, hi)) = ss.sketch.bounds() { - for p in [lo, hi, solidcraft_geom::Vec2::new(lo.x, hi.y), solidcraft_geom::Vec2::new(hi.x, lo.y)] { + for p in [lo, hi, solidcore_record::Vec2::new(lo.x, hi.y), solidcore_record::Vec2::new(hi.x, lo.y)] { b.add(ss.plane.to_world(p)); } } @@ -150,7 +161,7 @@ fn bounds_by(s: &Session, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> A b.add(p); } } - b + Ok(b) } /// The origin plane a grid lies on. @@ -223,6 +234,183 @@ pub fn grid_step(half_height: f64) -> (f64, f64) { (minor, minor * 5.0) } +/// How wide the cross-fade between two grid levels is, in powers of ten of the view's height +/// (#9570): about 19% of zoom either side of the switch. The switches are at least +/// `log10(2)` apart, so two cross-fades never overlap. +const GRID_LEVEL_BLEND: f64 = 0.15; + +/// One level of the drawn grid: its spacing and how strongly it is drawn. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GridLevel { + pub minor: f64, + pub major: f64, + /// 0..1, the level's share of the cross-fade; the levels drawn at one zoom add up to 1. The + /// lines only this level has may be drawn weaker than its share ([`grid_lines`]). + pub weight: f32, +} + +/// Where the view is in a cross-fade between two grid levels (#9570). +#[derive(Clone, Copy, Debug)] +struct GridBlend { + /// The finer and the coarser level's minor steps. + lo: f64, + hi: f64, + /// 0..1 through the cross-fade; the switch of [`grid_step`] is at 0.5. + s: f64, + /// Whether the coarser step is a whole multiple of the finer one (1 to 2, 5 to 10), so that + /// every coarser line is also a finer one. From 2 to 5 it is not. + nested: bool, +} + +impl GridBlend { + /// The coarser level's share of the cross-fade: a smoothstep through it. + fn share_hi(&self) -> f32 { + smoothstep(self.s) as f32 + } + + /// How strongly the lines only one of the two levels has are drawn (finer, coarser). + /// + /// Nested levels cross-fade as their shares do. Levels that do not nest (2 and 5: lines at + /// 0, 2, 4, 5, 6, 8, 10 mm) look restless drawn together, so the finer level's own lines fade + /// out over the first half of the cross-fade and the coarser level's own lines fade in over + /// the second: the two are never seen at once. The lines both share (every 10 mm, the finer + /// level's major lines) stay at full strength throughout, so the grid never goes blank. + fn own(&self) -> (f32, f32) { + if self.nested { + let hi = self.share_hi(); + (1.0 - hi, hi) + } else { + (smoothstep(1.0 - 2.0 * self.s) as f32, smoothstep(2.0 * self.s - 1.0) as f32) + } + } +} + +fn smoothstep(x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} + +/// The cross-fade the view of the given half height is in, if any (#9570). +fn grid_blend(half_height: f64) -> Option { + let (minor, _) = grid_step(half_height); + let raw = half_height / 10.0; + // grid_step's floor: no finer level is ever drawn, so there is nothing to fade to. + if !raw.is_finite() || !minor.is_finite() || raw <= 1e-3 || minor <= 0.0 { + return None; + } + let p = 10f64.powf((minor.log10() + 1e-9).floor()); + let mantissa = (minor / p).round(); + // The neighbouring steps of the 1, 2, 5 sequence. + let (finer, coarser) = if mantissa < 1.5 { + (minor * 0.5, minor * 2.0) + } else if mantissa < 3.5 { + (minor * 0.5, minor * 2.5) + } else { + (minor * 0.4, minor * 2.0) + }; + let half = GRID_LEVEL_BLEND * 0.5; + let l = raw.log10(); + // Zooming out, the switch into the coarser level comes at `log10(coarser)`; zooming in, + // the switch into this level was at `log10(minor)`, below which the finer level returns. + let (lo, hi) = if coarser.log10() - l < half { + (minor, coarser) + } else if l - minor.log10() < half && finer >= 1e-3 * (1.0 - 1e-9) { + (finer, minor) + } else { + return None; + }; + let s = ((l - hi.log10()) / GRID_LEVEL_BLEND + 0.5).clamp(0.0, 1.0); + // The switch from 2 to 5 is the only one whose coarser step is not a whole multiple of the + // finer one. It takes the same zoom range as the others, so the grid is cross-fading at the + // same zooms as before; its two halves are each as long as half a nested cross-fade. + let nested = ((hi / lo) - (hi / lo).round()).abs() < 1e-6; + Some(GridBlend { lo, hi, s, nested }) +} + +/// The grid levels drawn for a view of the given half height (#9570). +/// +/// [`grid_step`] switches the spacing in a step (1, 2, 5 times a power of ten), so the whole grid +/// used to swap at once as the view zoomed through a switch, popping over and over while +/// scrolling. Near a switch the drawn grid now cross-fades: the outgoing and incoming levels are +/// both drawn, weighted by how far the zoom is through the switch (from 2 to 5 one after the +/// other, see [`grid_lines`]). Away from a switch only the level [`grid_step`] gives is drawn, at +/// full strength, so the grid looks as it did. The level with the larger weight is always +/// [`grid_step`]'s, which sketch snapping, dash lengths and the tools keep using unchanged: only +/// the drawing fades. +pub fn grid_levels(half_height: f64) -> Vec { + let Some(b) = grid_blend(half_height) else { + let (minor, major) = grid_step(half_height); + return vec![GridLevel { minor, major, weight: 1.0 }]; + }; + let w_hi = b.share_hi(); + [GridLevel { minor: b.lo, major: b.lo * 5.0, weight: 1.0 - w_hi }, GridLevel { minor: b.hi, major: b.hi * 5.0, weight: w_hi }] + .into_iter() + .filter(|g| g.weight > 0.0) + .collect() +} + +/// One line of the drawn grid (#9570), across one of the grid's axes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GridLineAt { + /// Where the line crosses the axis, measured from the grid's centre. + pub offset: f64, + /// How strongly it is drawn (0..1), before the fade with the distance ([`GridFade`]). + pub weight: f32, + /// How much of that weight is a major line (0..1): the line's colour and width blend from + /// the minor to the major ones by it. + pub major: f32, +} + +/// The lines of the grid across one axis, for a view of the given half height: every level of +/// [`grid_levels`], at the grid's own places on the plane (multiples of its step from the plane's +/// origin), so that a level fading in lies where it will stay once it is the only one. `at` is +/// the grid's centre on that axis, measured from the plane's origin; the lines reach `reach` +/// either side of it, at most `cap` steps of each level. A line two levels share is drawn once, +/// with their weights added; a line only one level has is drawn as strongly as that level's own +/// lines, which from 2 to 5 fade one after the other, never both at once. +pub fn grid_lines(half_height: f64, at: f64, reach: f64, cap: i64) -> Vec { + if !at.is_finite() { + return Vec::new(); + } + // (minor step, share of the cross-fade, strength of its own lines) per level. + let levels: Vec<(f64, f32, f32)> = match grid_blend(half_height) { + Some(b) => { + let (share_hi, (own_lo, own_hi)) = (b.share_hi(), b.own()); + vec![(b.lo, 1.0 - share_hi, own_lo), (b.hi, share_hi, own_hi)] + } + None => vec![(grid_step(half_height).0, 1.0, 1.0)], + }; + // (line, own strength, shared by two levels) + let mut out: Vec<(GridLineAt, f32, bool)> = Vec::new(); + for &(step, share, own) in &levels { + let k0 = (at / step).round(); + if !k0.is_finite() { + continue; + } + let n = ((reach / step) as i64).clamp(1, cap.max(1)); + for i in -n..=n { + let k = (k0 as i64).saturating_add(i); + let major = if k.rem_euclid(5) == 0 { 1.0 } else { 0.0 }; + out.push((GridLineAt { offset: k as f64 * step - at, weight: share, major }, own, false)); + } + } + out.sort_by(|a, b| a.0.offset.total_cmp(&b.0.offset)); + let tol = levels.iter().map(|l| l.0).fold(f64::INFINITY, f64::min) * 1e-6; + let mut merged: Vec<(GridLineAt, f32, bool)> = Vec::with_capacity(out.len()); + for (line, own, _) in out { + match merged.last_mut() { + Some((last, _, shared)) if (line.offset - last.offset).abs() <= tol => { + let weight = last.weight + line.weight; + last.major = if weight > 0.0 { (last.major * last.weight + line.major * line.weight) / weight } else { last.major }; + last.weight = weight.min(1.0); + *shared = true; + } + _ => merged.push((line, own, false)), + } + } + merged.into_iter().map(|(line, own, shared)| if shared { line } else { GridLineAt { weight: own, ..line } }).filter(|l| l.weight > 0.0).collect() +} + /// How the grid fades out with the distance from the middle of the view (#4214). /// /// The grid used to stop at a fixed distance, so its edge showed as a cut across the picture. It @@ -478,23 +666,24 @@ pub fn component_color(s: &Session, component: u64) -> Option<[u8; 3]> { Some(s.doc.component_identification_color(component)) } -/// The scene for a headless render, cut by the session's section. -pub fn scene(s: &Session, cam: &Camera) -> Scene { +/// The scene for a headless render, cut by the session's section. A model that cannot be placed +/// is the error. +pub fn scene(s: &Session, cam: &Camera) -> Result { scene_with_section(s, cam, s.section) } /// The scene for a headless render, cut by `section` (origin, normal) instead of the session's: /// the app passes the cut its viewport shows (an open Section Analysis dialog's preview, a /// sketch's Slice), so model renders match the window. -pub fn scene_with_section(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>) -> Scene { +pub fn scene_with_section(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>) -> Result { scene_with_guides(s, cam, section, Guides::default()) } /// The plane of the sketch that is open, if any: it always shows a grid, whatever the Grid switch /// says (outside a sketch the grid is the user's choice). -pub fn open_sketch_plane(s: &Session) -> Option { - let id = s.active_sketch?; - s.world_state().sketch(id).map(|ss| ss.plane) +pub fn open_sketch_plane(s: &Session) -> Result> { + let Some(id) = s.active_sketch else { return Ok(None) }; + Ok(s.world_state()?.sketch(id).map(|ss| ss.plane)) } /// The grid on a sketch plane: its centre (the view target's foot on the plane, snapped to the @@ -522,14 +711,14 @@ impl Default for Guides { } /// [`scene_with_section`] with the grid and the axes shown or left out. -pub fn scene_with_guides(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>, guides: Guides) -> Scene { +pub fn scene_with_guides(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>, guides: Guides) -> Result { scene_with_palette_and_guides(s, cam, section, world_curve_parts, &Palette::DEFAULT, guides) } /// A headless scene using supplied display paths for its visible sketch curves. /// Callers can use the same pixel sampler as a GPU viewport without changing the /// body, grid, appearance, section or sketch styling policies of [`scene`]. -pub fn scene_with_sketch_sampler(s: &Session, cam: &Camera, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>) -> Scene { +pub fn scene_with_sketch_sampler(s: &Session, cam: &Camera, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>) -> Result { scene_with_section_and_sketch_sampler(s, cam, s.section, sampler) } @@ -539,7 +728,7 @@ pub fn scene_with_section_and_sketch_sampler( cam: &Camera, section: Option<(Vec3, Vec3)>, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, -) -> Scene { +) -> Result { scene_with_palette(s, cam, section, sampler, &Palette::DEFAULT) } @@ -550,7 +739,7 @@ pub fn scene_with_palette( section: Option<(Vec3, Vec3)>, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, p: &Palette, -) -> Scene { +) -> Result { build_scene(s, cam, section, Guides::default(), sampler, p, false) } @@ -562,7 +751,7 @@ pub fn scene_with_palette_and_guides( sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, p: &Palette, guides: Guides, -) -> Scene { +) -> Result { build_scene(s, cam, section, guides, sampler, p, false) } @@ -576,7 +765,7 @@ pub fn scene_with_thread_markings( p: &Palette, guides: Guides, cosmetic_threads: bool, -) -> Scene { +) -> crate::Result { build_scene(s, cam, section, guides, sampler, p, cosmetic_threads) } @@ -588,25 +777,26 @@ fn build_scene( mut sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, p: &Palette, cosmetic_threads: bool, -) -> Scene { - let st = s.world_state(); +) -> Result { + let st = s.world_state()?; let section = section.filter(|(o, n)| o.is_finite() && n.is_finite() && n.len() > 1e-9); let mut sc = Scene { background: Some(p.background), clip: section.map(|(o, n)| (n, n.dot(o))), cap: Some(p.cap), plain_cap: !s.section_hatch, + part_hatch: Some([p.cap, p.hatch[0], p.hatch[1]]), analysis: s.analysis.map(|a| SceneAnalysis { mode: a.mode(), colors: p.analysis }), ..Default::default() }; - let b = bounds(s); + let b = bounds(s)?; sc.radius = (b.diagonal() * 0.5).max(cam.half_height()).max(10.0) + b.center().dist(cam.target); // Grid on the ground plane (XY with Z up, XZ with Y up), drawn under the model as in the viewport. if guides.grid { - let (minor, major) = grid_step(cam.half_height()); + let major = grid_step(cam.half_height()).1; // Headless pictures keep the grid on the ground, the viewport's default; an open sketch // has its own plane's grid (world coordinates, no camera frame). - let (c, u, v, slant, w): (Vec3, Vec3, Vec3, f64, Box Vec3>) = if let Some(pl) = open_sketch_plane(s) { + let (c, u, v, slant, w): (Vec3, Vec3, Vec3, f64, Box Vec3>) = if let Some(pl) = open_sketch_plane(s)? { let (c, u, v) = sketch_grid_frame(&pl, cam.target, major); let n = u.cross(v); (c, u, v, cam.back().dot(n), Box::new(|p| p)) @@ -624,23 +814,31 @@ fn build_scene( let ext = grid_ext(cam.half_height(), major, slant); let far_reach = grid_far_reach(cam, cam.clip(sc.radius).1, w(c), w(u.cross(v))); let fade = GridFade::new(cam.half_height(), slant, ext, far_reach); - let n = ((fade.end / minor) as i64).clamp(1, 400); - for i in -n..=n { - let t = i as f64 * minor; - let major_line = (t / major).fract().abs() < 1e-9; - let col = if major_line { p.grid_major } else { p.grid }; - // The viewport's widths (pixels). - let width = if major_line { 1.0 } else { 0.7 }; - // Two lines through the point `c + u * t`: one along v, one along u. - for (along, across) in [(v, u), (u, v)] { - for (s0, s1, alpha) in fade.pieces(t) { - sc.grid.push(SceneLine { - points: vec![w(c + across * t + along * s0), w(c + across * t + along * s1)], - color: col, - alpha, - width, - on_top: false, - }); + // The grid's centre on each axis, from the plane's origin (the world's, or the sketch + // plane's): a level fading in near a switch of the spacing lies on its own places (#9570). + let origin = open_sketch_plane(s)?.map_or(Vec3::ZERO, |pl| pl.origin); + let (at_u, at_v) = ((c - origin).dot(u), (c - origin).dot(v)); + // Two lines through the point `c + u * t`: one along v, one along u. + for (along, across, at) in [(v, u, at_u), (u, v, at_v)] { + for line in grid_lines(cam.half_height(), at, fade.end, 400) { + let t = line.offset; + // The viewport's widths (pixels). The headless picture keeps the palette's two + // grid colours: a line two levels share with different kinds is drawn as both, + // each as strong as its share. + let width = 0.7 + 0.3 * f64::from(line.major); + for (col, share) in [(p.grid_major, line.major), (p.grid, 1.0 - line.major)] { + if share <= 0.0 { + continue; + } + for (s0, s1, alpha) in fade.pieces(t) { + sc.grid.push(SceneLine { + points: vec![w(c + across * t + along * s0), w(c + across * t + along * s1)], + color: col, + alpha: alpha * line.weight * share, + width, + on_top: false, + }); + } } } } @@ -662,6 +860,8 @@ fn build_scene( .flatten() .collect(); let mut thread_budget = crate::cosmetic_threads::Budget::default(); + // Where the section cuts each closed solid body, by its mesh in `sc.meshes`: their hatches. + let mut cuts: Vec<(usize, u64, Vec<(Vec3, Vec3)>)> = Vec::new(); for body in st.bodies.iter().filter(|b| s.body_visible(&b.name)) { let selected = selected_occurrences.contains(&body.name) || s.selection.iter().any(|x| matches!(x, Sel::Body { name } if *name == body.name)); let mesh = body.mesh(); @@ -683,7 +883,9 @@ fn build_scene( // A see-through appearance is drawn see-through, as the viewport draws it; a selected // body is drawn solid, so the selection colour reads. let opacity = if selected { 1.0 } else { s.doc.model_body_opacity(body) as f32 }; - sc.meshes.push(SceneMesh { mesh: Arc::clone(&mesh), color, face_colors, opacity }); + let cut_solid = section.is_some() && body.is_closed() && opacity >= solidcraft_render::SEE_THROUGH; + sc.meshes.push(SceneMesh { mesh: Arc::clone(&mesh), color, face_colors, opacity, closed: body.is_closed(), hatch: Default::default() }); + let at = sc.meshes.len() - 1; if cosmetic_threads && thread_budget.available() && s.doc.model_body_opacity(body) >= 0.999 @@ -701,11 +903,28 @@ fn build_scene( } // The outline of the body where the section cuts it. if let Some((o, n)) = section { - for (a, b) in section_segments(&mesh, o, n) { - sc.lines.push(SceneLine { points: vec![a, b], color: p.edge, alpha: 1.0, width: 1.6, on_top: false }); + let segments = section_segments(&mesh, o, n); + for (a, b) in &segments { + sc.lines.push(SceneLine { points: vec![*a, *b], color: p.edge, alpha: 1.0, width: 1.6, on_top: false }); + } + if cut_solid && !segments.is_empty() { + cuts.push((at, solidcraft_render::hatch::seed(&body.name), segments)); } } } + if let Some((_, n)) = section { + let parts: Vec = + cuts.iter().map(|(_, seed, segments)| solidcraft_render::hatch::CutPart { seed: *seed, segments }).collect(); + for ((at, _, _), hatch) in cuts.iter().zip(solidcraft_render::hatch::hatches(&parts, n)) { + if let Some(m) = sc.meshes.get_mut(*at) { + m.hatch = hatch; + } + } + } + // Isocurve Analysis: the isoparametric curves of each face it shows, on the faces. + for line in s.isocurve_lines().iter().flat_map(|lines| lines.iter()) { + sc.lines.push(SceneLine { points: line.points.clone(), color: p.isocurve, alpha: 1.0, width: 1.4, on_top: false }); + } for ss in &st.sketches { let active = s.active_sketch == Some(ss.feature); if !sketch_shown(s, ss.feature) { @@ -715,7 +934,7 @@ fn build_scene( sc.lines.push(SceneLine { points: pts, color: col, alpha: 1.0, width: if cons { 1.0 } else { 1.6 }, on_top: active }); } } - sc + Ok(sc) } /// Where the plane through `o` with normal `n` cuts a mesh: one segment per crossed triangle, @@ -750,72 +969,143 @@ fn cut_triangle(m: &solidcraft_geom::Mesh, t: &[u32; 3], o: Vec3, n: Vec3, eps: } } -/// A mesh's triangles sorted into slabs along one normal, so cuts with that normal at any -/// height look only at the triangles of one slab: dragging a Section Analysis keeps the normal -/// and moves the cut, and an imported part can have millions of triangles. The same segments -/// as [`section_segments`]. +/// A mesh's triangles sorted into the cells of a grid by where their boxes sit, each cell +/// keeping the box around its triangles, so a cut with any plane looks only at the triangles of +/// the cells the plane crosses: an imported part can have millions of triangles, and dragging a +/// Section Analysis moves the cut and, when tilted, turns its normal every frame (#10373). The +/// same segments, in the same order, as [`section_segments`]. pub struct SectionIndex { - normal: Vec3, - /// The lowest height (`normal · p`) of the mesh, and the slab thickness. - start: f64, - step: f64, - /// Per slab, the triangles whose heights reach into it. - slabs: Vec>, + /// Per cell holding triangles, the centre and half size of the box around them, and where + /// they are in `tris` (in mesh order). + cells: Vec<(Vec3, Vec3, u32, u32)>, + tris: Vec, + /// Triangles with a corner that is not finite: cut on every plane, as `section_segments` + /// does. + always: Vec, + /// The largest coordinate of the mesh, for the cell test's rounding margin. + reach: f64, eps: f64, } -/// Slabs a [`SectionIndex`] makes, at most. -const SECTION_SLABS: usize = 4096; +/// How many mean triangle widths a [`SectionIndex`] cell is wide, and most cells of its grid. +const SECTION_CELL_WIDTHS: f64 = 4.0; +const SECTION_GRID: usize = 1 << 22; impl SectionIndex { - pub fn new(m: &solidcraft_geom::Mesh, normal: Vec3) -> SectionIndex { - let heights: Vec> = m + pub fn new(m: &solidcraft_geom::Mesh) -> SectionIndex { + let finite_tri = |t: &[u32; 3]| m.tri(t).filter(|p| p.iter().all(|q| q.is_finite())); + let mut always = Vec::new(); + let mut centres = Aabb3::EMPTY; + let (mut widths, mut count) = (0.0, 0usize); + for (i, t) in m.triangles.iter().enumerate() { + match finite_tri(t) { + Some([a, b, c]) => { + let (lo, hi) = (a.min(b).min(c), a.max(b).max(c)); + centres.add((lo + hi) * 0.5); + widths += (hi - lo).len(); + count += 1; + } + None if m.tri(t).is_some() => always.extend(u32::try_from(i)), + None => {} + } + } + // Cells as wide as a few triangles, on the axes the part spans: a part's triangles lie + // on its surface, so cells sized from the part's volume would hold far more. + let size = if centres.is_empty() { Vec3::ZERO } else { centres.size() }; + let ext = [size.x, size.y, size.z]; + let dims_for = |side: f64| ext.map(|e| if e > 0.0 && side > 0.0 { (e / side).ceil().clamp(1.0, SECTION_GRID as f64) as usize } else { 1 }); + let cells_of = |d: [usize; 3]| d.iter().fold(1usize, |p, k| p.saturating_mul(*k)); + let mut side = widths / count.max(1) as f64 * SECTION_CELL_WIDTHS; + while cells_of(dims_for(side)) > SECTION_GRID && side.is_finite() { + side *= 1.25; + } + let dims = dims_for(side); + let cells = cells_of(dims).min(SECTION_GRID); + let at = |v: f64, lo: f64, e: f64, d: usize| { + let k = if e > 0.0 { ((v - lo) / e * d as f64).floor() } else { 0.0 }; + if k.is_finite() { (k.max(0.0) as usize).min(d.saturating_sub(1)) } else { 0 } + }; + let of: Vec> = m .triangles .iter() .map(|t| { - let d = m.tri(t)?.map(|q| normal.dot(q)); - Some((d[0].min(d[1]).min(d[2]), d[0].max(d[1]).max(d[2]))) + let [a, b, c] = finite_tri(t)?; + let p = (a.min(b).min(c) + a.max(b).max(c)) * 0.5; + let [x, y, z] = + [at(p.x, centres.min.x, ext[0], dims[0]), at(p.y, centres.min.y, ext[1], dims[1]), at(p.z, centres.min.z, ext[2], dims[2])]; + Some(((z * dims[1] + y) * dims[0] + x).min(cells.saturating_sub(1))) }) .collect(); - let (lo, hi) = heights.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (l, h)| (a.min(*l), b.max(*h))); - let count = if lo.is_finite() && hi.is_finite() { (m.triangles.len() / 64).clamp(1, SECTION_SLABS) } else { 0 }; - let step = if count > 0 && hi > lo { (hi - lo) / count as f64 } else { 1.0 }; - let mut index = SectionIndex { normal, start: lo, step, slabs: vec![Vec::new(); count], eps: section_nudge(m) }; - for (i, h) in heights.iter().enumerate() { - let (Some((l, h)), Ok(i)) = (h, u32::try_from(i)) else { continue }; - for k in index.slab(*l)..=index.slab(*h) { - if let Some(slab) = index.slabs.get_mut(k) { - slab.push(i); - } + // Counted per cell, then each cell's first slot (the last entry: the total). + let mut starts = vec![0u32; cells + 1]; + for c in of.iter().flatten() { + if let Some(s) = starts.get_mut(*c) { + *s += 1; } } - index - } - - /// The normal this index was made for. - pub fn normal(&self) -> Vec3 { - self.normal - } - - fn slab(&self, height: f64) -> usize { - let k = ((height - self.start) / self.step).floor(); - if k.is_finite() { (k.max(0.0) as usize).min(self.slabs.len().saturating_sub(1)) } else { 0 } + let mut total = 0u32; + for s in &mut starts { + (*s, total) = (total, total.saturating_add(*s)); + } + let mut fill = starts.clone(); + let mut tris = vec![0u32; total as usize]; + for (i, c) in of.iter().enumerate() { + let (Some(c), Ok(i)) = (c, u32::try_from(i)) else { continue }; + if let Some(at) = fill.get_mut(*c) { + if let Some(slot) = tris.get_mut(*at as usize) { + *slot = i; + } + *at += 1; + } + } + let mut reach: f64 = 0.0; + let cells = starts + .windows(2) + .filter_map(|w| match *w { + [a, e] if e > a => { + let mut b = Aabb3::EMPTY; + for i in tris.get(a as usize..e as usize).unwrap_or(&[]) { + for p in m.triangles.get(*i as usize).and_then(|t| m.tri(t)).into_iter().flatten() { + b.add(p); + } + } + reach = reach.max(b.min.x.abs().max(b.min.y.abs()).max(b.min.z.abs()).max(b.max.x.abs()).max(b.max.y.abs()).max(b.max.z.abs())); + Some((b.center(), b.size() * 0.5, a, e)) + } + _ => None, + }) + .collect(); + SectionIndex { cells, tris, always, reach, eps: section_nudge(m) } } /// [`section_segments`] of `m` (the mesh this index was made from) at the plane through - /// `o` with this index's normal. - pub fn segments(&self, m: &solidcraft_geom::Mesh, o: Vec3) -> Vec<(Vec3, Vec3)> { - let mut out = Vec::new(); - let at = self.normal.dot(o); - if self.slabs.is_empty() || !at.is_finite() || at < self.start { - return out; + /// `o` with normal `n`; nothing for a plane that is not finite. + pub fn segments(&self, m: &solidcraft_geom::Mesh, o: Vec3, n: Vec3) -> Vec<(Vec3, Vec3)> { + if !(o.is_finite() && n.is_finite()) { + return Vec::new(); } - for i in self.slabs.get(self.slab(at)).into_iter().flatten() { - if let Some(t) = m.triangles.get(*i as usize) { - cut_triangle(m, t, o, self.normal, self.eps, &mut out); + let an = Vec3::new(n.x.abs(), n.y.abs(), n.z.abs()); + // Rounding in `cut_triangle`'s heights is far below this margin, so a cell left out + // holds no triangle it would cut. + let margin = 1e-9 * (an.x + an.y + an.z) * (self.reach + o.x.abs().max(o.y.abs()).max(o.z.abs()) + 1.0); + let at = n.dot(o); + // The cut triangles' segments, by triangle, then in mesh order. + let mut found: Vec<(u32, (Vec3, Vec3))> = Vec::new(); + let mut out = Vec::with_capacity(1); + let mut cut = |i: u32| { + if let Some(t) = m.triangles.get(i as usize) { + cut_triangle(m, t, o, n, self.eps, &mut out); + found.extend(out.pop().map(|seg| (i, seg))); + } + }; + self.always.iter().for_each(|i| cut(*i)); + for (centre, half, first, end) in &self.cells { + if (n.dot(*centre) - at).abs() <= an.dot(*half) + margin { + self.tris.get(*first as usize..*end as usize).unwrap_or(&[]).iter().for_each(|i| cut(*i)); } } - out + found.sort_unstable_by_key(|(i, _)| *i); + found.into_iter().map(|(_, seg)| seg).collect() } } @@ -828,7 +1118,7 @@ pub fn sketch_shown(s: &Session, id: u64) -> bool { if s.active_sketch == Some(id) || s.feature_edit_sketch == Some(id) { return true; } - if !sketch_component_visible(s, id) || s.feature_folder_hidden(id, "sketches") { + if !s.feature_placement_visible(id) || s.feature_folder_hidden(id, "sketches") { return false; } if s.doc @@ -845,48 +1135,79 @@ pub fn sketch_shown(s: &Session, id: u64) -> bool { v.shown_sketches.contains(&id) || !sketch_consumed(s, id) } -/// Is the placement a sketch is drawn at shown (the active one while its component is being -/// edited, else the component's first)? -fn sketch_component_visible(s: &Session, id: u64) -> bool { - if s.visibility.hidden_occurrences.is_empty() { - return true; +/// Is a sketch used by a later feature? A sheet metal base or contour flange, or a perforation's +/// outline, uses its sketch as an Extrude does: shown, its lines lie on the sheet's edges and +/// faces and take the clicks meant for them (#6804). So does a Hole at sketch points: shown, its +/// points are drawn in the holes (#9082). A Single hole snapped to one point (#2110) does not: it +/// was placed on a face, not built from the sketch, and hiding the sketch would take its other +/// points from the next Single hole's snap. +pub fn sketch_consumed(s: &Session, id: u64) -> bool { + if let Ok(mut cache) = s.consumed_sketches_cache.lock() { + if cache.as_ref().is_none_or(|c| !std::ptr::eq(c.doc.as_ptr(), Arc::as_ptr(&s.doc))) { + *cache = Some(ConsumedSketches { doc: Arc::downgrade(&s.doc), ids: consumed_sketches(&s.doc).collect() }); + } + return cache.as_ref().is_some_and(|c| c.ids.contains(&id)); } - let component = s.doc.feature(id).map_or(0, |f| f.component); - if component == 0 { - return true; - } - let path = match &s.active_occurrence_path { - Some(p) if s.active_component == component => p.clone(), - _ => s.doc.first_path(component), - }; - s.occurrence_visible(&path) + // The lock is poisoned: answer from the features themselves. + consumed_sketches(&s.doc).any(|sketch| sketch == id) } -/// Is a sketch used by a later feature? A sheet metal base or contour flange uses its sketch as -/// an Extrude does: shown, its lines lie on the sheet's edges and take the clicks meant for -/// them (#6804). So does a Hole at sketch points: shown, its points are drawn in the holes -/// (#9082). A Single hole snapped to one point (#2110) does not: it was placed on a face, not -/// built from the sketch, and hiding the sketch would take its other points from the next -/// Single hole's snap. -pub fn sketch_consumed(s: &Session, id: u64) -> bool { +/// The sketches [`sketch_consumed`] answers for, read from one design. The design is held +/// weakly: its allocation is not handed to another design while the set lives, and an edit in +/// place (`Arc::make_mut`) moves it to an allocation of its own, so a set is never asked about +/// a design it was not read from. +pub(crate) struct ConsumedSketches { + doc: std::sync::Weak, + ids: std::collections::HashSet, +} + +/// The sketches the features of a design use (see [`sketch_consumed`]), once per use. +fn consumed_sketches(doc: &solidcraft_doc::Document) -> impl Iterator + '_ { use solidcraft_doc::{FeatureKind, SketchPoints}; - s.doc.features.iter().any(|f| { - matches!(f.kind, FeatureKind::Extrude { sketch, .. } | FeatureKind::Revolve { sketch, .. } - | FeatureKind::SheetBase { sketch, .. } | FeatureKind::SheetContour { sketch, .. } - | FeatureKind::Hole { points: Some(SketchPoints { sketch, single: false, .. }), .. } if sketch == id) + sketch_work::add(doc.features.len() as u64); + doc.features.iter().filter_map(|f| match &f.kind { + FeatureKind::Extrude { sketch, .. } + | FeatureKind::Revolve { sketch, .. } + | FeatureKind::SheetBase { sketch, .. } + | FeatureKind::SheetContour { sketch, .. } + | FeatureKind::Hole { points: Some(SketchPoints { sketch, single: false, .. }), .. } + | FeatureKind::SheetPerforate { sketch: Some(sketch), .. } => Some(sketch.0), + _ => None, }) } +/// How many features [`sketch_consumed`] walked, for the tests that hold it to one walk per +/// design rather than one per question. +pub(crate) mod sketch_work { + #[cfg(test)] + thread_local! { + static WALKED: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The features the answers of this thread walked since the last call. + #[cfg(test)] + pub(crate) fn take() -> u64 { + WALKED.with(|walked| walked.replace(0)) + } + + pub(crate) fn add(walked: u64) { + #[cfg(test)] + WALKED.with(|count| count.set(count.get() + walked)); + #[cfg(not(test))] + let _ = walked; + } +} + /// Camera framing the model (iso view). -pub fn home_camera(s: &Session) -> Camera { +pub fn home_camera(s: &Session) -> Result { let mut c = Camera::default(); - let b = bounds(s); + let b = bounds(s)?; if !b.is_empty() { c.fit(&b); } else { c.distance = 150.0; } - c + Ok(c) } /// Construction planes of the timeline, as evaluated: (feature id, name, plane). @@ -960,8 +1281,8 @@ mod tests { s.execute("solid.cylinder", &json!({"diameter": 14, "height": 30, "base": [50, 15, 0], "operation": "new"})).unwrap(); s.execute("appearance.assign", &json!({"bodies": ["Body2"], "color": [220, 60, 40]})).unwrap(); s.execute("appearance.assign", &json!({"faces": [[20, 15, 20]], "body": "Body1", "color": [40, 170, 80]})).unwrap(); - let cam = home_camera(&s); - let sc = scene(&s, &cam); + let cam = home_camera(&s).unwrap(); + let sc = scene(&s, &cam).unwrap(); assert!(sc.meshes.iter().any(|m| m.color == Rgb(220, 60, 40))); assert!(sc.meshes.iter().any(|m| m.face_colors.iter().any(|(_, c)| *c == Rgb(40, 170, 80)))); } @@ -972,16 +1293,16 @@ mod tests { fn guides_leave_the_grid_and_the_axes_out() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20, "corner": [10, -15, -10]})).unwrap(); - let cam = home_camera(&s); + let cam = home_camera(&s).unwrap(); let grid = [colors::GRID, colors::GRID_MAJOR]; let axes = [colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z]; let count = |sc: &Scene, colours: &[Rgb]| sc.grid.iter().chain(&sc.lines).filter(|l| colours.contains(&l.color)).count(); - let all = scene(&s, &cam); + let all = scene(&s, &cam).unwrap(); let (grid_lines, edges) = (count(&all, &grid), count(&all, &[colors::EDGE])); assert!(grid_lines > 20 && edges >= 12, "{grid_lines} grid lines, {edges} edges"); assert_eq!(count(&all, &axes), 3); - assert_eq!(all.lines.len(), scene_with_guides(&s, &cam, s.section, Guides::default()).lines.len()); - let render = |g: Guides| scene_with_guides(&s, &cam, s.section, g); + assert_eq!(all.lines.len(), scene_with_guides(&s, &cam, s.section, Guides::default()).unwrap().lines.len()); + let render = |g: Guides| scene_with_guides(&s, &cam, s.section, g).unwrap(); let no_grid = render(Guides { grid: false, axes: true }); assert_eq!((count(&no_grid, &grid), count(&no_grid, &axes), count(&no_grid, &[colors::EDGE])), (0, 3, edges)); let no_axes = render(Guides { grid: true, axes: false }); @@ -996,10 +1317,10 @@ mod tests { fn hidden_origin_axes_stay_out_of_renders() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); + let cam = home_camera(&s).unwrap(); let axes = [colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z]; let shown = |s: &Session| -> Vec { - let sc = scene(s, &cam); + let sc = scene(s, &cam).unwrap(); axes.into_iter().filter(|c| sc.lines.iter().any(|l| l.color == *c)).collect() }; assert_eq!(shown(&s), axes); @@ -1007,7 +1328,7 @@ mod tests { assert_eq!(shown(&s), [colors::AXIS_X, colors::AXIS_Z]); s.execute("browser.visibility", &json!({"folder": "origin", "visible": false})).unwrap(); assert!(shown(&s).is_empty()); - let sc = scene_with_guides(&s, &cam, None, Guides { grid: true, axes: true }); + let sc = scene_with_guides(&s, &cam, None, Guides { grid: true, axes: true }).unwrap(); assert!(sc.grid.iter().any(|l| l.color == colors::GRID), "the grid is not part of the origin"); s.execute("browser.visibility", &json!({"folder": "origin", "visible": true})).unwrap(); assert_eq!(shown(&s), axes); @@ -1019,14 +1340,14 @@ mod tests { fn the_section_cuts_the_scene() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); - assert!(scene(&s, &cam).clip.is_none()); + let cam = home_camera(&s).unwrap(); + assert!(scene(&s, &cam).unwrap().clip.is_none()); s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); - let sc = scene(&s, &cam); + let sc = scene(&s, &cam).unwrap(); let (n, d) = sc.clip.unwrap(); assert!((n - Vec3::new(0.0, -1.0, 0.0)).len() < 1e-12 && (d + 15.0).abs() < 1e-12, "{n:?} {d}"); assert_eq!(sc.cap, Some(colors::SECTION_CAP)); - assert!(!section_segments(&s.world_state().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); + assert!(!section_segments(&s.world_state().unwrap().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); } /// The surface analysis shades the headless scene too, in the palette's colours. @@ -1034,10 +1355,10 @@ mod tests { fn the_surface_analysis_shades_the_scene() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); - assert!(scene(&s, &cam).analysis.is_none()); + let cam = home_camera(&s).unwrap(); + assert!(scene(&s, &cam).unwrap().analysis.is_none()); s.analysis = Some(crate::SurfaceAnalysis::Curvature { radius: 5.0 }); - let a = scene(&s, &cam).analysis.unwrap(); + let a = scene(&s, &cam).unwrap().analysis.unwrap(); assert_eq!((a.mode, a.colors), (solidcraft_render::AnalysisMode::Curvature { radius: 5.0 }, Palette::DEFAULT.analysis)); } @@ -1047,8 +1368,8 @@ mod tests { fn cpu_pictures_draw_silhouettes_on_curved_surfaces() { let mut s = Session::default(); s.execute("solid.sphere", &json!({"diameter": 20})).unwrap(); - let cam = home_camera(&s); - let img = solidcraft_render::render(&scene(&s, &cam), &cam, 400, 400); + let cam = home_camera(&s).unwrap(); + let img = solidcraft_render::render(&scene(&s, &cam).unwrap(), &cam, 400, 400); let dark = img.rgba.chunks(4).filter(|p| p[0] < 70 && p[1] < 70 && p[2] < 75).count(); assert!(dark > 40, "silhouette pixels: {dark}"); } @@ -1058,10 +1379,10 @@ mod tests { fn cpu_pictures_show_the_section() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); - let whole = solidcraft_render::render(&scene(&s, &cam), &cam, 200, 140).rgba; + let cam = home_camera(&s).unwrap(); + let whole = solidcraft_render::render(&scene(&s, &cam).unwrap(), &cam, 200, 140).rgba; s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); - let sc = scene(&s, &cam); + let sc = scene(&s, &cam).unwrap(); assert!(sc.clip.is_some()); let cut = solidcraft_render::render(&sc, &cam, 200, 140).rgba; let changed = whole.chunks(4).zip(cut.chunks(4)).filter(|(a, b)| a != b).count(); @@ -1078,10 +1399,12 @@ mod tests { // Cut away the front half (y < 15), so the iso camera looks into the cut. s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); for fov in [0.0, 0.6] { - let mut cam = home_camera(&s); + let mut cam = home_camera(&s).unwrap(); cam.fov = fov; - let mut sc = scene(&s, &cam); - assert!(!section_segments(&s.world_state().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); + let mut sc = scene(&s, &cam).unwrap(); + // The cap in the cap colour: a part's hatch colour is the one its name picks. + sc.part_hatch = None; + assert!(!section_segments(&s.world_state().unwrap().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); sc.lines.push(SceneLine { @@ -1108,11 +1431,11 @@ mod tests { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); s.execute("appearance.assign", &json!({"bodies": ["Body1"], "color": [40, 160, 90]})).unwrap(); - let cam = home_camera(&s); + let cam = home_camera(&s).unwrap(); let mut picture = |hatch: bool| { let plane = json!({"origin": [0, 15, 0], "normal": [0, -1, 0]}); s.execute("inspect.section", &json!({"plane": plane, "hatch": hatch})).unwrap(); - solidcraft_render::render(&scene(&s, &cam), &cam, 300, 220).rgba + solidcraft_render::render(&scene(&s, &cam).unwrap(), &cam, 300, 220).rgba }; // Pixels in the body's exact colour: only a plain cut has them (lit faces are shaded). let solid = |img: &[u8]| img.chunks(4).filter(|p| p[..3] == [40, 160, 90]).count(); @@ -1122,6 +1445,40 @@ mod tests { let shades = |img: &[u8]| img.chunks(4).map(|p| [p[0], p[1], p[2]]).collect::>().len(); assert!(shades(&hatched) > shades(&plain), "the hatch adds its stripes' shades"); } + + /// The viewport asks whether each sketch is used several times a frame: the features are + /// walked once per design, not once per sketch asked about, and the answers follow every + /// change of the design, a direct edit of it included. + #[test] + fn consumed_sketches_are_worked_out_once_per_design() { + let mut s = Session::default(); + let mut sketches = Vec::new(); + for i in 0..4 { + let at = 20 * i; + sketches.push(s.execute("sketch.create", &json!({"plane": "XY"})).unwrap()["sketch"].as_u64().unwrap()); + s.execute("sketch.rectangle.two_point", &json!({"p0": [at, 0], "p1": [at + 10, 10]})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + } + s.execute("solid.extrude", &json!({"sketch": sketches[0], "distance": 5})).unwrap(); + s.execute("solid.extrude", &json!({"sketch": sketches[2], "distance": 5, "operation": "new"})).unwrap(); + let shown = |s: &Session| sketches.iter().map(|id| sketch_shown(s, *id)).collect::>(); + sketch_work::take(); + for _ in 0..10 { + assert_eq!(shown(&s), [false, true, false, true]); + } + assert_eq!(sketch_work::take(), s.doc.features.len() as u64, "one walk of the features for 40 questions"); + s.execute("solid.extrude", &json!({"sketch": sketches[1], "distance": 5, "operation": "new"})).unwrap(); + assert_eq!(shown(&s), [false, false, false, true], "an Extrude added uses its sketch"); + let at = s.doc.features.iter().position(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Extrude { .. })).unwrap(); + Arc::make_mut(&mut s.doc).features.remove(at); + assert_eq!(shown(&s), [true, false, false, true], "a design edited in place is read again"); + // `doc_mut` edits in place (the crash journal follows the document's address, #7502): + // the set held on the design does not move it. + let address = Arc::as_ptr(&s.doc); + s.doc_mut().features.retain(|f| !matches!(f.kind, solidcraft_doc::FeatureKind::Extrude { .. })); + assert_eq!(Arc::as_ptr(&s.doc), address, "doc_mut still edits in place"); + assert_eq!(shown(&s), [true; 4], "an edit through doc_mut is read again"); + } } #[cfg(test)] diff --git a/crates/engine/src/view_bounds_tests.rs b/crates/engine/src/view_bounds_tests.rs index ccad6f97b..4d69169f0 100644 --- a/crates/engine/src/view_bounds_tests.rs +++ b/crates/engine/src/view_bounds_tests.rs @@ -1,7 +1,9 @@ // Home and Fit frame what is visible now: bodies where they are placed (occurrence moves, // joints, motion), sketches only while they are drawn, nothing hidden or consumed. use serde_json::{Value, json}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Aabb3; +use solidcraft_geom::prelude::*; use crate::Session; @@ -15,7 +17,7 @@ fn run(s: &mut Session, id: &str, p: Value) -> Value { /// What the viewport draws: visible bodies' meshes and the sketches it shows, from the scene. fn drawn(s: &Session) -> Aabb3 { let cam = solidcraft_render::Camera { distance: 1e5, ..Default::default() }; - let scene = crate::view::scene(s, &cam); + let scene = crate::view::scene(s, &cam).unwrap(); let mut b = Aabb3::EMPTY; for m in &scene.meshes { b = b.union(&m.mesh.bounds()); @@ -51,11 +53,11 @@ fn block(s: &mut Session) { fn moved_body_leaves_its_used_sketch_out() { let mut s = Session::default(); block(&mut s); - near(crate::view::bounds(&s), [0., 0., 0.], [10., 10., 5.]); - let body = s.world_state().bodies[0].name.clone(); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [10., 10., 5.]); + let body = s.world_state().unwrap().bodies[0].name.clone(); run(&mut s, "solid.move", json!({"bodies": [body], "translate": [500, 0, 0]})); - near(crate::view::bounds(&s), [500., 0., 0.], [510., 10., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [500., 0., 0.], [510., 10., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } #[test] @@ -68,14 +70,14 @@ fn moved_component_frames_where_it_is_now() { block(&mut s); run(&mut s, "component.activate", json!({"component": "root"})); run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [800, 0, 0]})); - near(crate::view::bounds(&s), [0., 0., 0.], [810., 10., 5.]); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [810., 10., 5.]); run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [-780, 0, 0]})); - near(crate::view::bounds(&s), [0., 0., 0.], [30., 10., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [30., 10., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); // Pending (not captured) moves too. run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [0, 300, 0], "capture": false})); - near(crate::view::bounds(&s), [0., 0., 0.], [30., 310., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [30., 310., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } #[test] @@ -83,11 +85,11 @@ fn body_consumed_by_a_join_or_cut_is_not_framed() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [200, 0, 0], "operation": "new"})); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); run(&mut s, "solid.move", json!({"bodies": [names[1].clone()], "translate": [-195, 0, 0]})); run(&mut s, "solid.combine", json!({"target": names[0].clone(), "tools": [names[1].clone()], "operation": "cut"})); - near(crate::view::bounds(&s), [0., 0., 0.], [5., 10., 10.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [5., 10., 10.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } #[test] @@ -107,11 +109,11 @@ fn hidden_component_is_not_framed() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "component.activate", json!({"component": "root"})); run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [400, 0, 0]})); - near(crate::view::bounds(&s), [0., 0., 0.], [440., 40., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [440., 40., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); run(&mut s, "browser.visibility", json!({"visible": false, "paths": [[b]]})); - near(crate::view::bounds(&s), [0., 0., 0.], [10., 10., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [10., 10., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } /// Two leaves joined by a hinge (as in the joint tests). @@ -147,16 +149,16 @@ fn block_leaf(s: &mut Session) { fn joint_and_drive_frame_the_joined_place() { let mut s = Session::default(); hinge(&mut s); - let b = crate::view::bounds(&s); + let b = crate::view::bounds(&s).unwrap(); assert!(b.max.x < 50.0, "the joint brought B onto A: {b:?}"); same(b, drawn(&s)); run(&mut s, "joint.drive", json!({"joint": "Hinge", "value": 90})); - let b = crate::view::bounds(&s); + let b = crate::view::bounds(&s).unwrap(); assert!(b.max.x < 50.0 && b.max.z > 30.0, "{b:?}"); same(b, drawn(&s)); run(&mut s, "motion.study", json!({"name": "Swing", "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [10, 180]]}]})); run(&mut s, "motion.play", json!({"study": "Swing", "step": 10})); - let b = crate::view::bounds(&s); + let b = crate::view::bounds(&s).unwrap(); assert!(b.max.x < 50.0 && b.max.y > 60.0, "{b:?}"); same(b, drawn(&s)); } diff --git a/crates/engine/src/view_display_tests.rs b/crates/engine/src/view_display_tests.rs index 118386b05..229dc905e 100644 --- a/crates/engine/src/view_display_tests.rs +++ b/crates/engine/src/view_display_tests.rs @@ -1,6 +1,6 @@ use super::*; use serde_json::json; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_sketch::{LinkGeom, LinkKind, LinkSource}; fn line(sk: &mut Sketch, y: f64) -> usize { @@ -154,8 +154,8 @@ fn scene_sampler_uses_exact_active_occurrence_plane_and_preserves_other_scene_co s.execute("sketch.circle.center", &json!({"center":[2,3],"radius":1})).unwrap(); s.section = Some((Vec3::new(0., 0., 3.), Vec3::Z)); let cam = Camera::default(); - let old = scene(&s, &cam); - let default = scene_with_sketch_sampler(&s, &cam, world_curve_parts); + let old = scene(&s, &cam).unwrap(); + let default = scene_with_sketch_sampler(&s, &cam, world_curve_parts).unwrap(); assert_eq!(old.lines.len(), default.lines.len()); for (a, b) in old.lines.iter().zip(&default.lines) { assert_eq!((&a.points, a.color, a.width, a.on_top), (&b.points, b.color, b.width, b.on_top)); @@ -165,7 +165,8 @@ fn scene_sampler_uses_exact_active_occurrence_plane_and_preserves_other_scene_co let sampled = scene_with_sketch_sampler(&s, &cam, |_, _, plane| { planes.push(*plane); parts.clone() - }); + }) + .unwrap(); assert_eq!(planes.len(), 1); assert!(planes[0].origin.dist(Vec3::new(20., 30., 40.)) < 1e-9); assert!(planes[0].x.dist(Vec3::X) < 1e-9); @@ -186,7 +187,7 @@ fn scene_sampler_uses_exact_active_occurrence_plane_and_preserves_other_scene_co let active = s.active_sketch.unwrap(); s.execute("sketch.finish", &json!({})).unwrap(); s.visibility.hidden_sketches.push(active); - let hidden = scene_with_sketch_sampler(&s, &cam, |_, _, _| panic!("hidden sketch sampled")); + let hidden = scene_with_sketch_sampler(&s, &cam, |_, _, _| panic!("hidden sketch sampled")).unwrap(); assert!(hidden.lines.iter().all(|line| !line.on_top)); } @@ -221,19 +222,19 @@ fn colored_components_override_appearances_and_restore_them() { } s.selection.clear(); let cam = Camera::default(); - let original = scene(&s, &cam); + let original = scene(&s, &cam).unwrap(); s.execute("inspect.colored_components", &json!({"enabled": true})).unwrap(); s.colored_components = Some(()); - let colored = scene(&s, &cam); + let colored = scene(&s, &cam).unwrap(); assert_eq!(colored.meshes.len(), 2); assert_ne!(colored.meshes[0].color, colored.meshes[1].color); - for (body, mesh) in s.world_state().bodies.iter().zip(&colored.meshes) { + for (body, mesh) in s.world_state().unwrap().bodies.iter().zip(&colored.meshes) { let [r, g, b] = component_color(&s, body.component).unwrap(); assert_eq!(mesh.color, Rgb(r, g, b)); assert!(mesh.face_colors.is_empty()); } s.execute("inspect.colored_components", &json!({"enabled": false})).unwrap(); - let restored = scene(&s, &cam); + let restored = scene(&s, &cam).unwrap(); for (a, b) in original.meshes.iter().zip(restored.meshes) { assert_eq!(a.color, b.color); assert_eq!(a.face_colors, b.face_colors); @@ -259,7 +260,7 @@ fn cycling_component_color_is_saved_undoable_and_shared_by_instances() { assert_eq!(s.doc.appearances, appearances); let loaded = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert_eq!(loaded.doc.component_identification_color(component), custom); - let copies: Vec<_> = s.world_state().bodies.iter().map(|b| b.component).collect(); + let copies: Vec<_> = s.world_state().unwrap().bodies.iter().map(|b| b.component).collect(); assert_eq!(copies, [component, component]); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(component_color(&s, component), Some(automatic)); diff --git a/crates/engine/src/view_palette_tests.rs b/crates/engine/src/view_palette_tests.rs index 4b991e325..970faec53 100644 --- a/crates/engine/src/view_palette_tests.rs +++ b/crates/engine/src/view_palette_tests.rs @@ -3,7 +3,7 @@ use super::*; use serde_json::json; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_sketch::{LinkGeom, LinkKind, LinkSource}; /// #4214: the grid's fade is at full strength in the middle of the view, and gone before the @@ -31,11 +31,11 @@ fn the_grid_fades_out_before_its_edge_and_before_the_far_plane() { #[test] fn the_headless_grid_fades_out_with_the_distance() { let s = Session::default(); - let mut cam = home_camera(&s); + let mut cam = home_camera(&s).unwrap(); // A top view: the ground is the XY plane and the grid is centred on the target. cam.pitch = std::f64::consts::FRAC_PI_2; cam.target = Vec3::ZERO; - let scene = scene(&s, &cam); + let scene = scene(&s, &cam).unwrap(); assert!(!scene.grid.is_empty(), "the grid is drawn"); // How far each piece of the grid is from the middle of the view, and the alpha it is drawn // with. @@ -75,6 +75,133 @@ fn the_grid_reaches_further_as_its_plane_is_seen_at_a_slant() { assert!(grid_ext(40.0, major, 0.0).is_finite()); } +/// #9570: zooming through a switch of the grid's spacing used to swap the whole grid at once, so +/// scrolling made it pop over and over. The drawn grid now cross-fades: zoomed in small steps +/// through a switch, no line's strength jumps from one step to the next, while away from a +/// switch only [`grid_step`]'s level is drawn, at full strength, as before. +#[test] +fn the_grid_cross_fades_between_levels_as_the_view_zooms() { + // Every 1, 2, 5 switch, zoomed by 1% a step from a half height of 8 to 1200. + let strengths = |hh: f64| { + let mut m = std::collections::BTreeMap::new(); + // The grid's centre off the origin, as when the view has panned: each level's lines + // stay on the plane's own places. + let at = 37.0; + for l in grid_lines(hh, at, 60.0 * hh, 4000) { + let world = l.offset + at; + // Weight and major share, keyed by the line's place on the plane (to 1e-6 mm). + m.insert((world * 1e6).round() as i64, (l.weight, l.major)); + } + m + }; + let mut hh = 8.0; + let mut prev = strengths(hh); + let mut faded = 0; + while hh < 1200.0 { + let next_hh = hh * 1.01; + let next = strengths(next_hh); + // Only lines both steps draw: compare within the smaller reach, short of its ends, where + // each level stops at a whole number of its steps. + let reach = ((60.0 * hh - hh / 4.0) * 1e6) as i64; + for key in prev.keys().chain(next.keys()).filter(|k| (**k - 37_000_000).abs() < reach) { + let (a, ma) = prev.get(key).copied().unwrap_or((0.0, 0.0)); + let (b, mb) = next.get(key).copied().unwrap_or((0.0, 0.0)); + assert!((a - b).abs() < 0.1, "the line at {} mm jumps from {a} to {b} zooming from {hh} to {next_hh}", *key as f64 * 1e-6); + if a > 0.05 && b > 0.05 { + assert!((ma - mb).abs() < 0.1, "the line at {} mm turns from major {ma} to {mb} zooming from {hh} to {next_hh}", *key as f64 * 1e-6); + } + } + let levels = grid_levels(next_hh); + let total: f32 = levels.iter().map(|g| g.weight).sum(); + assert!((total - 1.0).abs() < 1e-5, "the levels at {next_hh} add up to {total}"); + // The strongest level is the one snapping and the tools use. + let strongest = levels.iter().fold(levels[0], |a, g| if g.weight > a.weight { *g } else { a }); + assert_eq!((strongest.minor, strongest.major), grid_step(next_hh), "at {next_hh} the drawn grid's main level is grid_step's"); + faded += usize::from(levels.len() == 2); + prev = next; + hh = next_hh; + } + assert!(faded > 0, "some steps cross-fade"); + // Away from a switch (raw step 3 lies between the 2 and 5 switches), one level at full + // strength, as the grid always was. + assert_eq!(grid_levels(30.0), vec![GridLevel { minor: 2.0, major: 10.0, weight: 1.0 }]); + // grid_step's floor and hostile heights draw one level. + for hh in [0.0, 1e-9, -5.0, f64::NAN, f64::INFINITY] { + assert_eq!(grid_levels(hh).len(), 1, "{hh}"); + let _ = grid_lines(hh, f64::NAN, 10.0, 10); + let _ = grid_lines(hh, 1e300, 1e300, 10); + } +} + +/// #9570: the headless picture's grid cross-fades as the viewport's does: right at a nested +/// switch of the spacing (5 to 10), both levels are drawn, the finer one's own lines at half +/// strength, in the palette's grid colours only. Right at the switch from 2 to 5, which do not +/// nest, neither level's own lines are drawn, only the 10 mm lines both share. +#[test] +fn the_headless_grid_draws_both_levels_at_a_switch() { + let s = Session::default(); + let mut cam = home_camera(&s).unwrap(); + cam.pitch = std::f64::consts::FRAC_PI_2; + cam.target = Vec3::ZERO; + let strength = |hh: f64, x: f64| { + let mut cam = cam; + cam.distance *= hh / cam.half_height(); + assert!((cam.half_height() - hh).abs() < 1e-6); + let scene = scene(&s, &cam).unwrap(); + assert!(scene.grid.iter().all(|l| [Palette::DEFAULT.grid, Palette::DEFAULT.grid_major].contains(&l.color))); + // The strongest piece of the line in each grid colour, added: a line two levels share + // with different kinds is drawn in both. + let on = |l: &&SceneLine| (l.points[0].x - x).abs() < 1e-6 && (l.points[1].x - x).abs() < 1e-6; + [Palette::DEFAULT.grid, Palette::DEFAULT.grid_major] + .iter() + .map(|c| scene.grid.iter().filter(on).filter(|l| l.color == *c).map(|l| l.alpha).fold(0.0f32, f32::max)) + .sum::() + }; + // A half height where grid_step switches from 5 to 10: the 5 mm line (only the finer level) + // is drawn at half strength, the 10 mm line (both) at full. + let a = strength(100.0, 5.0); + assert!(a > 0.3 && a < 0.7, "the line at 5 mm is drawn at {a}, half strength while the levels cross-fade"); + assert!(strength(100.0, 10.0) > 0.9); + // A half height where grid_step switches from 2 to 5. + for x in [2.0, 5.0] { + let a = strength(50.0, x); + assert!(a < 1e-6, "the line at {x} mm is drawn at {a} while 2 and 5 swap"); + } + assert!(strength(50.0, 10.0) > 0.9); +} + +/// #9570: the levels 2 and 5 do not nest, and drawn together they gave lines at 0, 2, 4, 5, 6, +/// 8, 10 mm, which looked restless. Zooming through that switch the finer level's own lines are +/// gone before the coarser level's own lines appear, while the lines both share (every 10 mm) +/// stay at full strength, so the grid never goes blank. Checked in every decade drawn. +#[test] +fn the_grid_never_draws_two_levels_that_do_not_nest_at_once() { + for scale in [0.1, 1.0, 10.0, 100.0] { + // grid_step switches from 2 to 5 (times `scale`) at a half height of 50 times `scale`. + let (mut hh, end) = (30.0 * scale, 80.0 * scale); + let (mut saw_fine, mut saw_coarse) = (false, false); + while hh < end { + let lines = grid_lines(hh, 0.0, 60.0 * scale, 4000); + let at = |x: f64| lines.iter().filter(|l| (l.offset - x * scale).abs() < 1e-6 * scale).map(|l| l.weight).sum::(); + // 2, 4, 6, 8: only the finer level; 5, 15: only the coarser. + let fine = [2.0, 4.0, 6.0, 8.0].iter().map(|x| at(*x)).fold(0.0f32, f32::max); + let coarse = [5.0, 15.0].iter().map(|x| at(*x)).fold(0.0f32, f32::max); + assert!(fine == 0.0 || coarse == 0.0, "at {hh} the 2 and 5 levels are both drawn ({fine}, {coarse})"); + saw_fine |= fine > 0.0 && fine < 1.0; + saw_coarse |= coarse > 0.0 && coarse < 1.0; + for x in [0.0, 10.0, 20.0] { + assert!(at(x) > 0.999, "at {hh} the line at {x} mm both levels share is drawn at {}", at(x)); + } + hh *= 1.005; + } + assert!(saw_fine && saw_coarse, "both levels fade rather than swap (scale {scale})"); + } + // The nested switches still cross-fade both levels together: from 1 to 2 (half height 20). + let lines = grid_lines(20.0, 0.0, 20.0, 4000); + let at = |x: f64| lines.iter().filter(|l| (l.offset - x).abs() < 1e-6).map(|l| l.weight).sum::(); + assert!(at(1.0) > 0.3 && at(1.0) < 0.7 && at(2.0) > 0.999, "{} {}", at(1.0), at(2.0)); +} + /// No colour here is one of [`colors`] or an appearance below, and each field has its own. const MARK: Palette = Palette { background: (Rgb(1, 2, 3), Rgb(4, 5, 6)), @@ -93,6 +220,8 @@ const MARK: Palette = Palette { sketch_centerline: Rgb(43, 44, 45), axes: [Rgb(46, 47, 48), Rgb(49, 50, 51), Rgb(52, 53, 54)], cap: Rgb(55, 56, 57), + hatch: [Rgb(61, 62, 63), Rgb(64, 65, 66)], + isocurve: Rgb(58, 59, 60), analysis: solidcraft_render::AnalysisColors { draft: [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]], access: [[0.11, 0.12, 0.13], [0.14, 0.15, 0.16]], @@ -123,7 +252,7 @@ fn the_default_palette_is_the_colour_table() { (p.sketch_projected, p.sketch_lost, p.sketch_construction, p.sketch_centerline), (colors::SKETCH_PROJECTED, colors::SKETCH_LOST, colors::SKETCH_CONSTRUCTION, colors::SKETCH_CENTERLINE) ); - assert_eq!((p.axes, p.cap), ([colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z], colors::SECTION_CAP)); + assert_eq!((p.axes, p.cap, p.isocurve), ([colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z], colors::SECTION_CAP, colors::ISOCURVE)); assert_eq!(p.analysis, solidcraft_render::AnalysisColors::DEFAULT); } @@ -204,15 +333,17 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); s.execute("sketch.line", &json!({"points": [[0, -20], [30, -20]]})).unwrap(); s.execute("sketch.finish", &json!({})).unwrap(); + // Isocurve Analysis on Plain's side face. + s.execute("inspect.isocurve", &json!({"faces": [[45, 0, 5]], "count": 2})).unwrap(); s.selection = vec![Sel::Body { name: "Picked".into() }]; s.section = Some((Vec3::new(0., 0., 5.), Vec3::Z)); - let cam = home_camera(&s); - let names: Vec = s.world_state().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); + let cam = home_camera(&s).unwrap(); + let names: Vec = s.world_state().unwrap().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); let mesh = |sc: &Scene, name: &str| { names.iter().position(|n| n == name).and_then(|i| sc.meshes.get(i)).map(|m| (m.color, m.face_colors.clone())).unwrap() }; - let marked = scene_with_palette(&s, &cam, s.section, world_curve_parts, &MARK); + let marked = scene_with_palette(&s, &cam, s.section, world_curve_parts, &MARK).unwrap(); assert_eq!((marked.background, marked.cap), (Some(MARK.background), Some(MARK.cap))); let allowed = [ MARK.grid, @@ -229,11 +360,12 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { MARK.sketch_lost, MARK.sketch_construction, MARK.sketch_centerline, + MARK.isocurve, ]; let all_lines = || marked.grid.iter().chain(&marked.lines); let stray: Vec = all_lines().map(|l| l.color).filter(|c| !allowed.contains(c)).collect(); assert!(stray.is_empty(), "line colours not from the palette: {stray:?}"); - for want in [MARK.grid, MARK.grid_major, MARK.edge, MARK.axes[0], MARK.axes[1], MARK.axes[2], MARK.sketch_done] { + for want in [MARK.grid, MARK.grid_major, MARK.edge, MARK.axes[0], MARK.axes[1], MARK.axes[2], MARK.sketch_done, MARK.isocurve] { assert!(all_lines().any(|l| l.color == want), "no line in {want:?}"); } assert!(marked.grid.iter().all(|l| [MARK.grid, MARK.grid_major].contains(&l.color)), "only the grid is drawn under the model"); @@ -244,8 +376,8 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { assert!(!faces.is_empty() && faces.iter().all(|(_, c)| *c == Rgb(0, 255, 0)), "face colours are the design's: {faces:?}"); // The default palette is the scene everyone else gets, line for line. - let default = scene_with_palette(&s, &cam, s.section, world_curve_parts, &Palette::DEFAULT); - let plain_scene = scene(&s, &cam); + let default = scene_with_palette(&s, &cam, s.section, world_curve_parts, &Palette::DEFAULT).unwrap(); + let plain_scene = scene(&s, &cam).unwrap(); assert_eq!( (default.background, default.cap, default.clip, default.radius), (plain_scene.background, plain_scene.cap, plain_scene.clip, plain_scene.radius) @@ -274,9 +406,9 @@ fn a_see_through_appearance_reaches_the_scene() { s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3})).unwrap(); s.execute("appearance.assign", &json!({"bodies": ["Picked"], "color": "#b0bac6", "opacity": 0.3})).unwrap(); s.selection = vec![Sel::Body { name: "Picked".into() }]; - let cam = home_camera(&s); - let sc = scene(&s, &cam); - let names: Vec = s.world_state().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); + let cam = home_camera(&s).unwrap(); + let sc = scene(&s, &cam).unwrap(); + let names: Vec = s.world_state().unwrap().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); let opacity = |name: &str| names.iter().position(|n| n == name).and_then(|i| sc.meshes.get(i)).map(|m| (m.opacity, m.glass())).unwrap(); assert_eq!(opacity("Target"), (0.3, true), "the design's opacity is the one the renderers draw"); @@ -285,6 +417,6 @@ fn a_see_through_appearance_reaches_the_scene() { // Clearing the appearance makes it solid again. s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": null})).unwrap(); - let sc = scene(&s, &cam); + let sc = scene(&s, &cam).unwrap(); assert_eq!(sc.meshes.first().map(|m| m.opacity), Some(1.0)); } diff --git a/crates/engine/src/world_placement_cache_tests.rs b/crates/engine/src/world_placement_cache_tests.rs index 9fa268529..03124d8be 100644 --- a/crates/engine/src/world_placement_cache_tests.rs +++ b/crates/engine/src/world_placement_cache_tests.rs @@ -1,6 +1,8 @@ //! Placement-cache changes must retain physical picking, pending positions and named joints. -use crate::{Session, geom::Vec3}; +use crate::Session; use serde_json::{Value, json}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use std::sync::Arc; fn run(session: &mut Session, command: &str, params: Value) -> Value { @@ -17,7 +19,7 @@ fn geometry_independent_moves_do_not_evaluate_the_timeline() { let before = session.evaluations; run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":true})); assert_eq!(session.evaluations - before, 0, "a placement-independent model must not enter timeline evaluation"); - let world = session.world_state(); + let world = session.world_state().unwrap(); let block = world.bodies.iter().find(|b| b.source_name.as_deref() == Some("Block")).unwrap(); assert!(block.mesh().bounds().min.dist(Vec3::new(10., 0., 0.)) < 1e-9); assert!(Arc::ptr_eq(&definitions, &session.model.state())); @@ -34,7 +36,7 @@ fn geometry_independent_moves_do_not_evaluate_the_timeline() { assert_eq!(scratch.evaluations, 0); assert!(Arc::ptr_eq(&definitions, &scratch.model.state())); assert_fresh_world(&scratch); - assert!(session.world_state().bodies[0].mesh().bounds().min.dist(Vec3::new(10., 0., 0.)) < 1e-9); + assert!(session.world_state().unwrap().bodies[0].mesh().bounds().min.dist(Vec3::new(10., 0., 0.)) < 1e-9); } fn assert_fresh_world(session: &Session) { @@ -42,8 +44,8 @@ fn assert_fresh_world(session: &Session) { fresh.no_cache = true; fresh.evaluate(&session.doc); assert!(fresh.results.iter().all(|r| r.error.is_none())); - let expected = crate::doc::world_state(&session.doc, &fresh.state()); - let actual = session.world_state(); + let expected = crate::doc::world_state(&session.doc, &fresh.state()).unwrap(); + let actual = session.world_state().unwrap(); assert_eq!(actual.bodies.len(), expected.bodies.len()); for (a, b) in actual.bodies.iter().zip(&expected.bodies) { assert_eq!(a.name, b.name); @@ -192,8 +194,8 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let path = vec![second]; let placement = session.occurrence_placement(&path).unwrap(); let name = placement.bodies[0].world.clone(); - let world = session.world_state(); - assert!(Arc::ptr_eq(&world, &session.world_state())); + let world = session.world_state().unwrap(); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); let source_state = session.model.state(); let source = source_state.body("Block").unwrap(); let placed = world.body(&name).unwrap(); @@ -209,10 +211,10 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let top = placed.body.faces(0.001).unwrap().into_iter().find(|face| face.plane_normal.is_some_and(|n| n.z > 0.99)).unwrap().index; run(&mut session, "select.set", json!({"items":[{"type":"face","body":name,"index":top,"point":[pick.x,pick.y,pick.z]}]})); assert!(matches!(&session.selection[0], crate::Sel::Face { body, index, .. } if body == &name && *index == top)); - assert!(Arc::ptr_eq(&world, &session.world_state()), "selection changes must not discard prepared placements"); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap()), "selection changes must not discard prepared placements"); let scratch = session.scratch(); assert_eq!(scratch.pending_moves, pending); - let scratch_world = scratch.world_state(); + let scratch_world = scratch.world_state().unwrap(); assert!(Arc::ptr_eq(&world, &scratch_world)); let scratch_body = scratch_world.body(&name).unwrap(); assert!(scratch_body.mesh().bounds().min.dist(bounds.min) < 1e-9); @@ -224,7 +226,7 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let before_joint = crate::doc::mat_mul(&crate::doc::joints::occurrence_world(&session.doc, second), &local_frame); assert!(crate::doc::apply_point(&before_joint, Vec3::ZERO).dist(pick) < 1e-9); run(&mut session, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0],"capture":true})); - let moved = session.world_state(); + let moved = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&world, &moved), "a changed transform must invalidate placed meshes"); assert!(moved.body(&name).unwrap().mesh().bounds().min.dist(bounds.min + Vec3::new(5., 0., 0.)) < 1e-9); assert!(world.body(&name).unwrap().mesh().bounds().min.dist(bounds.min) < 1e-9, "prior snapshots must remain immutable"); @@ -233,7 +235,7 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let after_joint = crate::doc::mat_mul(&crate::doc::joints::occurrence_world(&session.doc, second), &local_frame); assert!(crate::doc::apply_point(&after_joint, Vec3::ZERO).dist(pick + Vec3::new(5., 0., 0.)) < 1e-9); let reopened = Session::new(crate::doc::Document::from_json(&session.doc.to_json()).unwrap()); - assert!(reopened.world_state().body(&name).unwrap().mesh().bounds().min.dist(bounds.min + Vec3::new(5., 0., 0.)) < 1e-9); + assert!(reopened.world_state().unwrap().body(&name).unwrap().mesh().bounds().min.dist(bounds.min + Vec3::new(5., 0., 0.)) < 1e-9); assert_eq!(reopened.model.results.iter().filter(|r| r.error.is_some()).count(), 0); } @@ -242,22 +244,22 @@ fn selection_visibility_section_and_view_revisions_reuse_world_geometry() { let mut session = Session::default(); run(&mut session, "component.create", json!({"name":"Part"})); run(&mut session, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Block","operation":"new"})); - let world = session.world_state(); + let world = session.world_state().unwrap(); let revision = session.revision; run(&mut session, "select.set", json!({"items":[{"type":"body","name":"Block"}]})); assert!(session.revision > revision); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); run(&mut session, "select.clear", json!({})); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); run(&mut session, "browser.visibility", json!({"items":["Block"],"visible":false})); assert!(!session.body_visible("Block")); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); run(&mut session, "inspect.section", json!({"plane":{"origin":[0,0,2],"normal":[0,0,1]}})); assert!(session.section.is_some()); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); session.invalidate_view(session.revision + 10); - assert!(Arc::ptr_eq(&world, &session.world_state())); - assert!(Arc::ptr_eq(&world, &session.scratch().world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); + assert!(Arc::ptr_eq(&world, &session.scratch().world_state().unwrap())); } #[test] @@ -270,50 +272,53 @@ fn world_cache_requires_exact_design_model_pending_and_author_context() { let sketch = run(&mut session, "sketch.create", json!({"plane":"XY"}))["sketch"].as_u64().unwrap(); run(&mut session, "sketch.finish", json!({})); let second = run(&mut session, "occurrence.copy", json!({"occurrence":first}))["occurrence"].as_u64().unwrap(); - let initial = session.world_state(); + let initial = session.world_state().unwrap(); run(&mut session, "occurrence.move", json!({"occurrence":second,"translate":[10,20,0],"capture":false})); - let pending = session.world_state(); + let pending = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&initial, &pending)); let name = session.occurrence_placement(&[second]).unwrap().bodies[0].world.clone(); assert!(pending.body(&name).unwrap().mesh().bounds().min.dist(Vec3::new(10., 20., 0.)) < 1e-9); run(&mut session, "component.activate", json!({"component":component,"occurrence":second,"path":[second]})); - let authored = session.world_state(); + let authored = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&pending, &authored)); assert!(authored.sketch(sketch).unwrap().plane.origin.dist(Vec3::new(10., 20., 0.)) < 1e-9); let mut scratch = session.scratch(); - assert!(Arc::ptr_eq(&authored, &scratch.world_state())); + assert!(Arc::ptr_eq(&authored, &scratch.world_state().unwrap())); scratch.active_occurrence_path = Some(vec![first]); - let scratch_world = scratch.world_state(); + let scratch_world = scratch.world_state().unwrap(); assert!(!Arc::ptr_eq(&authored, &scratch_world)); assert!(scratch_world.sketch(sketch).unwrap().plane.origin.dist(Vec3::ZERO) < 1e-9); - assert!(Arc::ptr_eq(&authored, &session.world_state()), "scratch context must not replace the source cache"); + assert!(Arc::ptr_eq(&authored, &session.world_state().unwrap()), "scratch context must not replace the source cache"); // Evaluation and placement never read appearances: an appearance edit, its undo and its redo // keep the evaluated model and the placed world (the cache follows the new document). let model = session.model.state(); run(&mut session, "appearance.assign", json!({"bodies":["Block"],"color":"#ff0000"})); - let painted = session.world_state(); + let painted = session.world_state().unwrap(); assert!(Arc::ptr_eq(&authored, &painted), "an appearance edit keeps the placed world"); assert!(Arc::ptr_eq(&model, &session.model.state()), "and the evaluated model"); assert_ne!(session.doc.model_body_look(painted.body("Block").unwrap()), None); run(&mut session, "edit.undo", json!({})); - let undone = session.world_state(); + let undone = session.world_state().unwrap(); assert!(Arc::ptr_eq(&painted, &undone), "undoing it too"); assert_eq!(session.doc.model_body_look(undone.body("Block").unwrap()), None); run(&mut session, "edit.redo", json!({})); - let redone = session.world_state(); + let redone = session.world_state().unwrap(); assert!(Arc::ptr_eq(&undone, &redone), "and redoing it"); assert!(session.doc.model_body_look(redone.body("Block").unwrap()).is_some()); - let before_edit = session.world_state(); + let before_edit = session.world_state().unwrap(); run(&mut session, "solid.box", json!({"length":5,"width":6,"height":7,"body_name":"Other","operation":"new"})); - let edited = session.world_state(); + let edited = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&before_edit, &edited)); assert!(edited.body("Other").is_some()); session.doc = Arc::new(crate::doc::Document::from_json(&session.doc.to_json()).unwrap()); - let replaced = session.world_state(); + let replaced = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&edited, &replaced), "equal contents in a different document cannot share the cache key"); session.model = crate::doc::Model::default(); session.model.evaluate(&session.doc); - assert!(!Arc::ptr_eq(&replaced, &session.world_state()), "a new evaluated model must invalidate even when the document Arc is unchanged"); + assert!( + !Arc::ptr_eq(&replaced, &session.world_state().unwrap()), + "a new evaluated model must invalidate even when the document Arc is unchanged" + ); } #[test] @@ -321,35 +326,35 @@ fn adopted_scratch_keeps_its_warm_geometry_and_history_stages_invalidate_it() { let mut session = Session::default(); run(&mut session, "component.create", json!({"name":"Part"})); run(&mut session, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Block","operation":"new"})); - let source = session.world_state(); + let source = session.world_state().unwrap(); let source_json = session.doc.to_json(); let mut scratch = session.scratch(); run(&mut scratch, "solid.box", json!({"length":5,"width":6,"height":7,"body_name":"Draft","operation":"new"})); - let warmed = scratch.world_state(); + let warmed = scratch.world_state().unwrap(); assert!(!Arc::ptr_eq(&source, &warmed)); assert_eq!(session.doc.to_json(), source_json); - assert!(Arc::ptr_eq(&source, &session.world_state())); + assert!(Arc::ptr_eq(&source, &session.world_state().unwrap())); assert!(source.body("Draft").is_none()); let feature = warmed.body("Draft").unwrap().feature; session.accept_computed(scratch); - assert!(Arc::ptr_eq(&warmed, &session.world_state()), "adoption/view revision must retain the worker's prepared geometry"); + assert!(Arc::ptr_eq(&warmed, &session.world_state().unwrap()), "adoption/view revision must retain the worker's prepared geometry"); session.invalidate_view(session.revision + 20); - assert!(Arc::ptr_eq(&warmed, &session.world_state())); + assert!(Arc::ptr_eq(&warmed, &session.world_state().unwrap())); run(&mut session, "timeline.rollback", json!({"position":1})); - let rolled = session.world_state(); + let rolled = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&warmed, &rolled)); assert!(rolled.body("Block").is_some()); assert!(rolled.body("Draft").is_none()); run(&mut session, "timeline.rollback", json!({})); - let restored = session.world_state(); + let restored = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&rolled, &restored)); assert!(restored.body("Draft").is_some()); run(&mut session, "timeline.suppress", json!({"feature":feature,"suppressed":true})); - let suppressed = session.world_state(); + let suppressed = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&restored, &suppressed)); assert!(suppressed.body("Draft").is_none()); run(&mut session, "timeline.suppress", json!({"feature":feature,"suppressed":false})); - assert!(session.world_state().body("Draft").is_some()); + assert!(session.world_state().unwrap().body("Draft").is_some()); } /// A moved component's bodies keep their placed geometry and display mesh while the design @@ -363,26 +368,26 @@ fn moved_component_bodies_are_not_placed_again_when_something_else_changes() { run(&mut session, "solid.box", json!({"length":60,"width":60,"height":5,"body_name":"Rim"})); run(&mut session, "component.activate", json!({"component":"root"})); run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[100,0,0]})); - let placed = session.world_state(); + let placed = session.world_state().unwrap(); let rim = placed.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap().clone(); let mesh = rim.mesh(); assert!(mesh.bounds().min.dist(Vec3::new(100., 0., 0.)) < 1e-6); // A body added elsewhere: the rim is the same placed body, already meshed. run(&mut session, "solid.box", json!({"length":5,"width":6,"height":7,"body_name":"Frame"})); - let after = session.world_state(); + let after = session.world_state().unwrap(); let again = after.body(&rim.name).unwrap(); assert!(Arc::ptr_eq(&mesh, &again.mesh()), "an unchanged placed body keeps its mesh"); assert!(again.body.same(&rim.body)); // The placement moves: new world coordinates, reusing the definition's triangulation. run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[0,50,0]})); - let moved = session.world_state(); + let moved = session.world_state().unwrap(); let moved_rim = moved.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap(); assert!(!Arc::ptr_eq(&mesh, &moved_rim.mesh())); assert!(moved_rim.mesh().bounds().min.dist(Vec3::new(100., 50., 0.)) < 1e-6); // The body itself changes: placed again too, and the old snapshot is untouched. run(&mut session, "body.rename", json!({"body":"Frame","name":"Frame tube"})); let source = session.model.state().body("Rim").unwrap().clone(); - let world = session.world_state(); + let world = session.world_state().unwrap(); let kept = world.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap(); assert!(Arc::ptr_eq(&moved_rim.mesh(), &kept.mesh())); assert_eq!(kept.source_transform, moved_rim.source_transform); @@ -404,14 +409,14 @@ fn joint_drive_reuses_reference_tessellation_across_rigid_poses() { json!({"type":"revolute","name":"Crank","a":0,"b":"Crank","at":{"occurrence":0,"point":[0,0,0],"z":[0,0,1]}}), ); let definitions = session.model.state(); - let original = session.world_state(); + let original = session.world_state().unwrap(); let local = original.body("Crank").unwrap().mesh(); let bounds = local.bounds(); for angle in [37., 91., 37., 0.] { let driven = run(&mut session, "joint.drive", json!({"joint":"Crank","value":angle})); assert_eq!(driven["moved"], true); assert!(Arc::ptr_eq(&definitions, &session.model.state())); - let world = session.world_state(); + let world = session.world_state().unwrap(); let body = world.body("Crank").unwrap(); let (mesh, work) = crate::kernel::profile::capture(|| body.mesh()); assert_eq!(work.tessellate_ms, 0., "a warm definition must not enter the kernel mesher at a new pose: {work:?}"); @@ -447,19 +452,19 @@ fn body_frames_are_kept_with_the_world_state() { let first = run(&mut session, "component.create", json!({"name":"Part"}))["occurrence"].as_u64().unwrap(); run(&mut session, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Block","operation":"new"})); let second = run(&mut session, "occurrence.copy", json!({"occurrence":first}))["occurrence"].as_u64().unwrap(); - let _ = session.world_state(); + let _ = session.world_state().unwrap(); let frames = session.body_frames(); assert!(Arc::ptr_eq(&frames, &session.body_frames()), "kept while the world state is current"); let copy = session.occurrence_placement(&[second]).unwrap().bodies[0].world.clone(); assert!(frames.iter().any(|(world, own, _)| *world == copy && own == "Block"), "a copy maps back to its definition"); run(&mut session, "occurrence.move", json!({"occurrence":second,"translate":[10,0,0],"capture":false})); - let _ = session.world_state(); + let _ = session.world_state().unwrap(); let moved = session.body_frames(); assert!(!Arc::ptr_eq(&frames, &moved), "a moved placement works them out again"); let at = |frames: &crate::BodyFrames| frames.iter().find(|(world, ..)| *world == copy).map(|(_, _, m)| m[3][0]); assert_eq!(at(&moved), Some(10.0), "with the placement's new frame"); assert_eq!(at(&frames), Some(0.0)); run(&mut session, "solid.box", json!({"length":1,"width":1,"height":1,"body_name":"Other","operation":"new"})); - let _ = session.world_state(); + let _ = session.world_state().unwrap(); assert!(session.body_frames().iter().any(|(world, ..)| world.starts_with("Other")), "a new body is in them"); } diff --git a/crates/engine/tests/save_as_cache.rs b/crates/engine/tests/save_as_cache.rs index 5bfd1f4e1..a8a28105b 100644 --- a/crates/engine/tests/save_as_cache.rs +++ b/crates/engine/tests/save_as_cache.rs @@ -13,7 +13,7 @@ fn assembly() -> Session { } fn warm(session: &Session) { - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } } diff --git a/crates/engine/tests/shell_regressions.rs b/crates/engine/tests/shell_regressions.rs index 5243877ff..3abd8b70c 100644 --- a/crates/engine/tests/shell_regressions.rs +++ b/crates/engine/tests/shell_regressions.rs @@ -1,4 +1,4 @@ -//! Shell regressions found by the robustness fuzzer (tests/robustness/goldens.json). +//! Shell regressions found by the robustness fuzzer (docs/robustness.md). //! //! The box-on-box designs below have a saddle corner: where the top box's left face meets the //! lower box's back face, four planar faces meet with convex and concave edges in turn (the @@ -46,6 +46,13 @@ fn shell_box_on_box_overhanging_saddle_corner() { let mut s = box_on_box(2.5); run(&mut s, "solid.shell", json!({"faces": [[7.5, 17.5, 38.75]], "thickness": 1.5})); sound(&s); + // The bottom closed and the top box's left face x = 7.5 open, so the cavity in the top box + // runs out to it: [1.5, 23.5] × [1.5, 16] × [1.5, 33.5] in the lower box, + // [7.5, 21] × [1.5, 16] × [33.5, 41] over it and [7.5, 21] × [16, 18.5] × [36.5, 41] in the + // overhang, out of the solid's 25 × 17.5 × 35 + 15 × 20 × 7.5. + let want = 25.0 * 17.5 * 35.0 + 15.0 * 20.0 * 7.5 - 22.0 * 14.5 * 32.0 - 13.5 * 14.5 * 7.5 - 13.5 * 2.5 * 4.5; + let got = volume(&s); + assert!((got - want).abs() < 1e-6 * want, "shell volume {got}, want {want}"); } /// The same saddle corner with the bottom open: every face round the corner moves, and the @@ -86,3 +93,22 @@ fn sound(s: &Session) { assert!(b.body.validity().is_empty(), "{:?}", b.body.validity()); } } + +/// A shell that opens no face (rig shell/4009): a closed hollow body, the void sealed inside. A +/// 40 × 30 × 12.5 box with a 2.5 wall inside leaves a 35 × 25 × 7.5 void; grown 2.5 outside, the +/// walls are a 45 × 35 × 17.5 box less the original. +#[test] +fn a_shell_that_opens_no_face_seals_its_void() { + for (direction, want, shells) in [("inside", 15000.0 - 35.0 * 25.0 * 7.5, 2), ("outside", 45.0 * 35.0 * 17.5 - 15000.0, 2)] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40.0, "width": 30.0, "height": 12.5})); + run(&mut s, "solid.shell", json!({"faces": [], "thickness": 2.5, "direction": direction})); + let errors: Vec<_> = s.model.results.iter().filter_map(|r| r.error.clone()).collect(); + assert!(errors.is_empty(), "{direction}: {errors:?}"); + let st = s.model.state(); + assert_eq!(st.bodies.len(), 1, "{direction}: one body"); + assert_eq!(st.bodies[0].body.shell_count(), shells, "{direction}: an outer and an inner shell"); + let got = volume(&s); + assert!((got - want).abs() < 1e-6 * want, "{direction}: volume {got}, want {want}"); + } +} diff --git a/crates/engine/tests/sketch_analysis.rs b/crates/engine/tests/sketch_analysis.rs index 337062c64..694e75e42 100644 --- a/crates/engine/tests/sketch_analysis.rs +++ b/crates/engine/tests/sketch_analysis.rs @@ -1,10 +1,11 @@ //! Command-level diagnostic work, including the report ultimately published to the model. +use solidcraft_geom::prelude::*; use std::sync::Arc; use serde_json::json; +use solidcore_record::Vec2; use solidcraft_engine::Session; -use solidcraft_geom::Vec2; use solidcraft_sketch::{Analysis, ConstraintKind, Sketch, profiling::capture}; fn session(horizontal: bool) -> (Session, u64, String) { diff --git a/crates/engine/tests/sketch_drag_target.rs b/crates/engine/tests/sketch_drag_target.rs index 883907e93..dc132f635 100644 --- a/crates/engine/tests/sketch_drag_target.rs +++ b/crates/engine/tests/sketch_drag_target.rs @@ -3,7 +3,8 @@ mod four_bar; use serde_json::json; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; #[test] fn angular_drag_keeps_the_horizontal_construction_line() { @@ -29,6 +30,52 @@ fn angular_drag_keeps_the_horizontal_construction_line() { } } +/// A line's end on a horizontal construction line through the origin, dragged up off it in +/// small frames (#9062): the end can only slide along the construction line, so it stays on it +/// and the construction line keeps its length. A line's horizontal row is `b.y - a.y`, which a +/// line a hair long meets at any tilt: the drag's solves shrank the construction line to 1e-5 mm +/// on the first frame and to 1e-7 mm by the tenth, so it vanished and the end went up. +#[test] +fn an_end_dragged_off_a_horizontal_construction_line_leaves_it_whole() { + let through_origin = [ + // Drawn from the origin (inferred horizontal). + vec![("sketch.line", json!({"points":["origin",[20,0]],"construction":true,"infer":true,"ids":["c"]}))], + // Drawn across the origin, then the origin made coincident with it. + vec![ + ("sketch.line", json!({"points":[[-10,0.2],[20,0.2]],"construction":true,"infer":true,"ids":["c"]})), + ("sketch.constraint.coincident", json!({"a":"origin","b":"c"})), + ], + ]; + for construction in through_origin { + for live in [false, true] { + let mut s = solidcraft_engine::Session::default(); + s.execute("sketch.create", &json!({"plane":"XY"})).unwrap(); + for (id, params) in construction.iter().cloned().chain([ + ("sketch.line", json!({"points":[[10,0],[10,10]],"ids":["l"],"infer":false})), + ("sketch.constraint.coincident", json!({"a":"l.start","b":"c"})), + ]) { + s.execute(id, ¶ms).unwrap(); + } + let point = |s: &solidcraft_engine::Session, id| four_bar::point(s, id).unwrap(); + let length = |s: &solidcraft_engine::Session| point(s, "c.start").dist(point(s, "c.end")); + let before = length(&s); + let mut at = point(&s, "l.start"); + for _ in 0..10 { + let to = Vec2::new(at.x, at.y + 0.1); + s.execute("sketch.drag", &json!({"entity":"l.start","from":[at.x,at.y],"to":[to.x,to.y],"live":live})).unwrap(); + assert!((length(&s) - before).abs() < 1e-6, "(live {live}) the construction line went from {before} mm to {} mm", length(&s)); + at = to; + } + if live { + s.execute("sketch.drag_end", &json!({})).unwrap(); + } + let end = point(&s, "l.start"); + assert!(end.y.abs() < 1e-6, "(live {live}) l.start left the construction line: {end:?}"); + assert!((length(&s) - before).abs() < 1e-6, "(live {live}) the construction line went to {} mm", length(&s)); + } + } +} + /// A line held at its midpoint, with an angle to a horizontal line from that point (#8944): /// dragging one of its ends off that angle slides the end along the line as far as it can go, /// and the horizontal line keeps its length. That line's far end is free only along it, which @@ -400,3 +447,53 @@ fn a_linkage_held_by_redundant_parallelograms_follows_the_cursor() { assert!(parallelogram_error(&s) < 1e-6); } } + +#[test] +fn a_drag_that_would_fling_points_far_away_leaves_them_near_the_sketch() { + let mut s = solidcraft_engine::Session::default(); + for (id, params) in [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.line", json!({"points":[[2,-27],[-2,22],[-10,-10],[2,13]]})), + ("sketch.rectangle.two_point", json!({"p0":[-12,1],"p1":[-18,28]})), + ("sketch.line", json!({"points":[[6,-21],[-12,-27],[-25,-29],[16,5]]})), + ("sketch.rectangle.two_point", json!({"p0":[-21,0],"p1":[-23,-3]})), + ("sketch.line", json!({"points":[[24,23],[-7,7],[0,29],[-6,-7]]})), + ("sketch.dimension", json!({"entities":["l16","l12"],"type":"angle","value":31})), + ] { + s.execute(id, ¶ms).unwrap(); + } + s.execute("sketch.drag", &json!({"entity":"p8","from":[-23.0,-0.534780330115472],"to":[23,-8]})).unwrap(); + for i in 0..30 { + let Ok(p) = four_bar::point(&s, &format!("p{i}")) else { continue }; + assert!(p.len() < 1000.0, "p{i} was thrown to {p:?}"); + } +} + +/// A line held at its midpoint, with an angle to a horizontal line from there: its end dragged +/// past the midpoint, where the line would have to turn over, pressed it to no length (the angle +/// then held no direction). The drag now stops just short of that, the line still pointing the +/// way the angle says. +#[test] +fn an_end_dragged_past_its_lines_midpoint_leaves_the_line_a_length() { + for live in [false, true] { + let mut s = solidcraft_engine::Session::default(); + for (id, params) in [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.line", json!({"points":[[-10,-6],[10,6]],"infer":false})), + ("sketch.constraint.midpoint", json!({"line":"l1","point":"origin"})), + ("sketch.line", json!({"points":["origin",[15,0]],"infer":false})), + ("sketch.constraint.horizontal_vertical", json!({"line":"l2"})), + ("sketch.dimension", json!({"entities":["l1","l2"],"type":"angle"})), + ("sketch.drag", json!({"entity":"l1.start","from":[-10,-6],"to":[12,4],"live":live})), + ] { + s.execute(id, ¶ms).unwrap(); + } + if live { + s.execute("sketch.drag_end", &json!({})).unwrap(); + } + let (a, b) = (four_bar::point(&s, "l1.start").unwrap(), four_bar::point(&s, "l1.end").unwrap()); + assert!(a.dist(b) > 1e-3, "l1 is left {} mm long (live {live})", a.dist(b)); + let d = b - a; + assert!((d.y.atan2(d.x) - 6f64.atan2(10.0)).abs() < 1e-6, "l1 turned to {d:?} (live {live})"); + } +} diff --git a/crates/engine/tests/support/four_bar.rs b/crates/engine/tests/support/four_bar.rs index 8ec6366f2..270883dac 100644 --- a/crates/engine/tests/support/four_bar.rs +++ b/crates/engine/tests/support/four_bar.rs @@ -1,7 +1,8 @@ //! Public-safe 10/40/20/42 mm linkage, matching the reported one-degree-of-freedom sketch. use serde_json::json; +use solidcore_record::Vec2; use solidcraft_engine::Session; -use solidcraft_geom::Vec2; +use solidcraft_geom::prelude::*; pub type Result = std::result::Result>; diff --git a/crates/geom/Cargo.toml b/crates/geom/Cargo.toml index 538cd41db..cd95c204b 100644 --- a/crates/geom/Cargo.toml +++ b/crates/geom/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] serde = { workspace = true } +solidcore-record = { workspace = true } thiserror = { workspace = true } [dev-dependencies] diff --git a/crates/geom/src/aabb2.rs b/crates/geom/src/aabb2.rs index 0a1e41e2b..dc8ec361e 100644 --- a/crates/geom/src/aabb2.rs +++ b/crates/geom/src/aabb2.rs @@ -2,7 +2,8 @@ use serde::{Deserialize, Serialize}; -use crate::Vec2; +use crate::prelude::*; +use solidcore_record::Vec2; /// Axis-aligned box in the plane; [`Aabb2::EMPTY`] (low +∞, high −∞) holds nothing. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/geom/src/arcfit.rs b/crates/geom/src/arcfit.rs index 332cee333..ea664fa80 100644 --- a/crates/geom/src/arcfit.rs +++ b/crates/geom/src/arcfit.rs @@ -5,9 +5,10 @@ //! keeps smooth curves this way with far fewer pieces than a chord polyline of the same //! tolerance: a biarc's error falls with the cube of its length, a chord's with the square. +use crate::prelude::*; use std::f64::consts::{PI, TAU}; -use crate::{Loop2, Region2, Seg2, Vec2}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; /// Most pieces one segment is fitted with. pub const MAX_FIT_PIECES: usize = 2048; @@ -16,163 +17,6 @@ const MAX_DEPTH: u32 = 30; /// Samples inside each candidate span that must lie within the tolerance. const SAMPLES: usize = 12; -impl Seg2 { - /// A straight line or a circular arc (what [`Seg2::fit_arcs`] produces). - pub fn is_line_or_arc(&self) -> bool { - matches!(self, Seg2::Line { .. } | Seg2::Arc { .. }) - } - - /// Lines and circular arcs that follow the segment within `tol` (mm), in order, the first - /// starting at the segment's start and the last ending at its end; consecutive pieces share - /// their end points and tangents. Lines and arcs come back unchanged. `None` when the - /// segment is not finite or would need more than [`MAX_FIT_PIECES`] pieces. - pub fn fit_arcs(&self, tol: f64) -> Option> { - if self.is_line_or_arc() { - return Some(vec![*self]); - } - if !(tol.is_finite() && tol > 0.0) { - return None; - } - let tol = tol.max(1e-9); - let mut out: Vec = Vec::new(); - // Spans still to fit; the last pushed is fitted first, so pushing the right half before - // the left one keeps the output in parameter order. - let mut todo = vec![(0.0f64, 1.0f64, 0u32)]; - let mut steps = 0usize; - while let Some((t0, t1, depth)) = todo.pop() { - steps += 1; - if steps > 4 * MAX_FIT_PIECES { - return None; - } - let (p0, p1) = (self.point_at(t0), self.point_at(t1)); - if !(p0.is_finite() && p1.is_finite()) { - return None; - } - if p0.dist(p1) < 1e-12 && self.span_extent(t0, t1) < tol { - continue; - } - let fit = match (self.tangent_out(t0, t1), self.tangent_in(t0, t1)) { - (Some(d0), Some(d1)) => biarc(p0, d0, p1, d1).filter(|arcs| self.within(arcs, t0, t1, tol)), - _ => None, - }; - match fit { - Some(arcs) => { - out.extend(arcs); - if out.len() > MAX_FIT_PIECES { - return None; - } - } - None if depth < MAX_DEPTH => { - let tm = 0.5 * (t0 + t1); - todo.push((tm, t1, depth + 1)); - todo.push((t0, tm, depth + 1)); - } - None => { - // Too fine to split further (a cusp): the chord is within the tolerance - // here or nothing is. - let chord = [Seg2::Line { a: p0, b: p1 }]; - if !self.within(&chord, t0, t1, tol) { - return None; - } - out.push(chord[0]); - } - } - } - // The pieces join where their spans meet; pin the outer ends to the segment's own. - if let Some(first) = out.first_mut() { - *first = with_start(*first, self.start()); - } - if let Some(last) = out.last_mut() { - *last = with_end(*last, self.end()); - } - Some(out) - } - - /// Unit direction of travel leaving `t` towards `t1`. - fn tangent_out(&self, t: f64, t1: f64) -> Option { - self.derivative(t).normalized().or_else(|| (self.point_at(t + (t1 - t) * 1e-4) - self.point_at(t)).normalized()) - } - - /// Unit direction of travel arriving at `t1` from `t0`. - fn tangent_in(&self, t0: f64, t1: f64) -> Option { - self.derivative(t1).normalized().or_else(|| (self.point_at(t1) - self.point_at(t1 - (t1 - t0) * 1e-4)).normalized()) - } - - /// Largest distance of the span's sample points from its start (a loop's size). - fn span_extent(&self, t0: f64, t1: f64) -> f64 { - let p0 = self.point_at(t0); - (1..=SAMPLES).map(|i| self.point_at(t0 + (t1 - t0) * i as f64 / (SAMPLES + 1) as f64).dist(p0)).fold(0.0, f64::max) - } - - /// Do `pieces` follow the span `t0..t1` within `tol` both ways? - fn within(&self, pieces: &[Seg2], t0: f64, t1: f64, tol: f64) -> bool { - if pieces.iter().any(|p| matches!(p, Seg2::Arc { sweep, .. } if sweep.abs() > PI)) { - return false; - } - let samples: Vec = (0..=SAMPLES + 1).map(|i| self.point_at(t0 + (t1 - t0) * i as f64 / (SAMPLES + 1) as f64)).collect(); - // The curve near the pieces... - if samples.iter().any(|p| pieces.iter().map(|s| dist_to(s, *p)).fold(f64::INFINITY, f64::min) > tol) { - return false; - } - // ...and the pieces near the curve (their quarter points against the curve's closest - // point on the span). - pieces.iter().all(|s| { - [0.25, 0.5, 0.75].iter().all(|f| { - let q = s.point_at(*f); - self.dist_on_span(q, t0, t1, &samples) <= tol - }) - }) - } - - /// Distance from `q` to the span `t0..t1` (closest sample, then Newton steps). - fn dist_on_span(&self, q: Vec2, t0: f64, t1: f64, samples: &[Vec2]) -> f64 { - let n = samples.len().saturating_sub(1).max(1); - let (k, mut best) = samples.iter().enumerate().map(|(i, p)| (i, p.dist(q))).fold((0, f64::INFINITY), |a, b| if b.1 < a.1 { b } else { a }); - let mut t = t0 + (t1 - t0) * k as f64 / n as f64; - for _ in 0..12 { - let (p, d) = (self.point_at(t), self.derivative(t)); - let dd = d.dot(d); - if !(dd > 1e-300) { - break; - } - let nt = (t - (p - q).dot(d) / dd).clamp(t0, t1); - best = best.min(self.point_at(nt).dist(q)); - if (nt - t).abs() < 1e-15 { - break; - } - t = nt; - } - best - } -} - -impl Loop2 { - /// The loop with every free-form segment fitted by lines and arcs (see - /// [`Seg2::fit_arcs`]). `None` when a segment cannot be fitted. - pub fn fit_arcs(&self, tol: f64) -> Option { - let mut segs = Vec::with_capacity(self.segs.len()); - for s in &self.segs { - segs.extend(s.fit_arcs(tol)?); - if segs.len() > MAX_FIT_PIECES * 8 { - return None; - } - } - Some(Loop2 { segs }) - } - - /// Only lines and arcs? - pub fn is_line_arc(&self) -> bool { - self.segs.iter().all(Seg2::is_line_or_arc) - } -} - -impl Region2 { - /// Only lines and arcs? - pub fn is_line_arc(&self) -> bool { - self.outer.is_line_arc() && self.holes.iter().all(Loop2::is_line_arc) - } -} - /// Distance from `p` to a line or arc segment (other segments: to their closest point). fn dist_to(s: &Seg2, p: Vec2) -> f64 { match *s { @@ -273,6 +117,185 @@ fn with_end(s: Seg2, p: Vec2) -> Seg2 { } } +/// Arcs and lines fitted to a profile segment ([`Seg2`]). +pub trait Seg2ArcFit { + /// A straight line or a circular arc (what [`Seg2::fit_arcs`] produces). + fn is_line_or_arc(&self) -> bool; + /// Lines and circular arcs that follow the segment within `tol` (mm), in order, the first + /// starting at the segment's start and the last ending at its end; consecutive pieces share + /// their end points and tangents. Lines and arcs come back unchanged. `None` when the + /// segment is not finite or would need more than [`MAX_FIT_PIECES`] pieces. + fn fit_arcs(&self, tol: f64) -> Option>; +} + +impl Seg2ArcFit for Seg2 { + fn is_line_or_arc(&self) -> bool { + matches!(self, Seg2::Line { .. } | Seg2::Arc { .. }) + } + fn fit_arcs(&self, tol: f64) -> Option> { + if self.is_line_or_arc() { + return Some(vec![*self]); + } + if !(tol.is_finite() && tol > 0.0) { + return None; + } + let tol = tol.max(1e-9); + let mut out: Vec = Vec::new(); + // Spans still to fit; the last pushed is fitted first, so pushing the right half before + // the left one keeps the output in parameter order. + let mut todo = vec![(0.0f64, 1.0f64, 0u32)]; + let mut steps = 0usize; + while let Some((t0, t1, depth)) = todo.pop() { + steps += 1; + if steps > 4 * MAX_FIT_PIECES { + return None; + } + let (p0, p1) = (self.point_at(t0), self.point_at(t1)); + if !(p0.is_finite() && p1.is_finite()) { + return None; + } + if p0.dist(p1) < 1e-12 && self.span_extent(t0, t1) < tol { + continue; + } + let fit = match (self.tangent_out(t0, t1), self.tangent_in(t0, t1)) { + (Some(d0), Some(d1)) => biarc(p0, d0, p1, d1).filter(|arcs| self.within(arcs, t0, t1, tol)), + _ => None, + }; + match fit { + Some(arcs) => { + out.extend(arcs); + if out.len() > MAX_FIT_PIECES { + return None; + } + } + None if depth < MAX_DEPTH => { + let tm = 0.5 * (t0 + t1); + todo.push((tm, t1, depth + 1)); + todo.push((t0, tm, depth + 1)); + } + None => { + // Too fine to split further (a cusp): the chord is within the tolerance + // here or nothing is. + let chord = [Seg2::Line { a: p0, b: p1 }]; + if !self.within(&chord, t0, t1, tol) { + return None; + } + out.push(chord[0]); + } + } + } + // The pieces join where their spans meet; pin the outer ends to the segment's own. + if let Some(first) = out.first_mut() { + *first = with_start(*first, self.start()); + } + if let Some(last) = out.last_mut() { + *last = with_end(*last, self.end()); + } + Some(out) + } +} + +/// What fitting a segment reads of a span of it. +trait Span { + /// Unit direction of travel leaving `t` towards `t1`. + fn tangent_out(&self, t: f64, t1: f64) -> Option; + /// Unit direction of travel arriving at `t1` from `t0`. + fn tangent_in(&self, t0: f64, t1: f64) -> Option; + /// Largest distance of the span's sample points from its start (a loop's size). + fn span_extent(&self, t0: f64, t1: f64) -> f64; + /// Do `pieces` follow the span `t0..t1` within `tol` both ways? + fn within(&self, pieces: &[Seg2], t0: f64, t1: f64, tol: f64) -> bool; + /// Distance from `q` to the span `t0..t1` (closest sample, then Newton steps). + fn dist_on_span(&self, q: Vec2, t0: f64, t1: f64, samples: &[Vec2]) -> f64; +} + +impl Span for Seg2 { + fn tangent_out(&self, t: f64, t1: f64) -> Option { + self.derivative(t).normalized().or_else(|| (self.point_at(t + (t1 - t) * 1e-4) - self.point_at(t)).normalized()) + } + fn tangent_in(&self, t0: f64, t1: f64) -> Option { + self.derivative(t1).normalized().or_else(|| (self.point_at(t1) - self.point_at(t1 - (t1 - t0) * 1e-4)).normalized()) + } + fn span_extent(&self, t0: f64, t1: f64) -> f64 { + let p0 = self.point_at(t0); + (1..=SAMPLES).map(|i| self.point_at(t0 + (t1 - t0) * i as f64 / (SAMPLES + 1) as f64).dist(p0)).fold(0.0, f64::max) + } + fn within(&self, pieces: &[Seg2], t0: f64, t1: f64, tol: f64) -> bool { + if pieces.iter().any(|p| matches!(p, Seg2::Arc { sweep, .. } if sweep.abs() > PI)) { + return false; + } + let samples: Vec = (0..=SAMPLES + 1).map(|i| self.point_at(t0 + (t1 - t0) * i as f64 / (SAMPLES + 1) as f64)).collect(); + // The curve near the pieces... + if samples.iter().any(|p| pieces.iter().map(|s| dist_to(s, *p)).fold(f64::INFINITY, f64::min) > tol) { + return false; + } + // ...and the pieces near the curve (their quarter points against the curve's closest + // point on the span). + pieces.iter().all(|s| { + [0.25, 0.5, 0.75].iter().all(|f| { + let q = s.point_at(*f); + self.dist_on_span(q, t0, t1, &samples) <= tol + }) + }) + } + fn dist_on_span(&self, q: Vec2, t0: f64, t1: f64, samples: &[Vec2]) -> f64 { + let n = samples.len().saturating_sub(1).max(1); + let (k, mut best) = samples.iter().enumerate().map(|(i, p)| (i, p.dist(q))).fold((0, f64::INFINITY), |a, b| if b.1 < a.1 { b } else { a }); + let mut t = t0 + (t1 - t0) * k as f64 / n as f64; + for _ in 0..12 { + let (p, d) = (self.point_at(t), self.derivative(t)); + let dd = d.dot(d); + if !(dd > 1e-300) { + break; + } + let nt = (t - (p - q).dot(d) / dd).clamp(t0, t1); + best = best.min(self.point_at(nt).dist(q)); + if (nt - t).abs() < 1e-15 { + break; + } + t = nt; + } + best + } +} + +/// Arcs and lines fitted to a profile loop ([`Loop2`]). +pub trait Loop2ArcFit { + /// The loop with every free-form segment fitted by lines and arcs (see + /// [`Seg2::fit_arcs`]). `None` when a segment cannot be fitted. + fn fit_arcs(&self, tol: f64) -> Option; + /// Only lines and arcs? + fn is_line_arc(&self) -> bool; +} + +impl Loop2ArcFit for Loop2 { + fn fit_arcs(&self, tol: f64) -> Option { + let mut segs = Vec::with_capacity(self.segs.len()); + for s in &self.segs { + segs.extend(s.fit_arcs(tol)?); + if segs.len() > MAX_FIT_PIECES * 8 { + return None; + } + } + Some(Loop2 { segs }) + } + fn is_line_arc(&self) -> bool { + self.segs.iter().all(Seg2::is_line_or_arc) + } +} + +/// Whether a profile region ([`Region2`]) is lines and arcs only. +pub trait Region2ArcFit { + /// Only lines and arcs? + fn is_line_arc(&self) -> bool; +} + +impl Region2ArcFit for Region2 { + fn is_line_arc(&self) -> bool { + self.outer.is_line_arc() && self.holes.iter().all(Loop2::is_line_arc) + } +} + #[cfg(test)] mod tests { use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2}; diff --git a/crates/geom/src/ball.rs b/crates/geom/src/ball.rs new file mode 100644 index 000000000..ac8848a9a --- /dev/null +++ b/crates/geom/src/ball.rs @@ -0,0 +1,233 @@ +//! The smallest ball holding a set of points (Welzl's algorithm): a measure of a point set's size +//! that does not move with the points, whatever rigid motion carries them. + +use crate::prelude::*; +use solidcore_record::Vec3; + +/// A ball: every point within `radius` of `center`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ball { + pub center: Vec3, + pub radius: f64, +} + +/// How much more than `radius` a point may lie from the centre and still count as inside: the +/// rounding of the centre's and radius' arithmetic, so a point the ball was made through is never +/// taken for one outside it. +const ROUNDING: f64 = 1e-12; + +impl Ball { + /// The smallest ball holding every finite point of `points` (points that are not finite are + /// skipped), or `None` when there are none. Welzl's algorithm in its incremental form, the + /// points taken in a fixed shuffled order: expected `O(n)`. The ball is unique, so the order + /// only changes the last bits of its centre and radius. + pub fn enclosing(points: &[Vec3]) -> Option { + let mut p: Vec = points.iter().copied().filter(|q| q.is_finite()).collect(); + shuffle(&mut p); + let mut ball = Ball { center: *p.first()?, radius: 0.0 }; + // Each loop keeps the smallest ball holding the points before it with the points of the + // loops outside it on its boundary (Welzl 1991): at most four are, in three dimensions. + for i in 1..p.len() { + if ball.holds(p[i]) { + continue; + } + ball = Ball { center: p[i], radius: 0.0 }; + for j in 0..i { + if ball.holds(p[j]) { + continue; + } + ball = through(&[p[i], p[j]]); + for k in 0..j { + if ball.holds(p[k]) { + continue; + } + ball = through(&[p[i], p[j], p[k]]); + for l in 0..k { + if !ball.holds(p[l]) { + ball = through(&[p[i], p[j], p[k], p[l]]); + } + } + } + } + } + Some(ball) + } + + pub fn diameter(&self) -> f64 { + 2.0 * self.radius + } + + /// Whether `p` lies in the ball, to the rounding of its arithmetic. + pub fn holds(&self, p: Vec3) -> bool { + p.dist(self.center) <= self.radius + ROUNDING * (self.radius + self.center.len()) + } +} + +/// The smallest ball with every one of `r` (two to four points) on its boundary; where they are +/// degenerate (three in a line, four in a plane, which exact arithmetic never asks for but +/// rounding can), the smallest ball through some of them that holds them all. +fn through(r: &[Vec3]) -> Ball { + let exact = match r { + [a, b] => Some((*a + *b) * 0.5), + [o, b, c] => circumcentre3(*o, *b, *c), + [o, b, c, d] => circumcentre4(*o, *b, *c, *d), + _ => None, + }; + match exact { + Some(center) => with_center(center, r), + None => smallest_holding(r), + } +} + +/// The ball about `center` reaching the farthest of `r`. +fn with_center(center: Vec3, r: &[Vec3]) -> Ball { + Ball { center, radius: r.iter().map(|q| q.dist(center)).fold(0.0, f64::max) } +} + +/// The centre of the circle through `o`, `b` and `c`, or `None` when they are (nearly) in a line. +fn circumcentre3(o: Vec3, b: Vec3, c: Vec3) -> Option { + let (a, b) = (b - o, c - o); + let n = a.cross(b); + let n2 = n.len2(); + if !(n2 > 1e-14 * a.len2() * b.len2()) { + return None; + } + Some(o + (b.cross(n) * a.len2() + n.cross(a) * b.len2()) / (2.0 * n2)) +} + +/// The centre of the sphere through `o`, `b`, `c` and `d`, or `None` when they are (nearly) in a +/// plane. +fn circumcentre4(o: Vec3, b: Vec3, c: Vec3, d: Vec3) -> Option { + let (a, b, c) = (b - o, c - o, d - o); + let det = a.dot(b.cross(c)); + if !(det.abs() > 1e-7 * a.len() * b.len() * c.len()) { + return None; + } + Some(o + (b.cross(c) * a.len2() + c.cross(a) * b.len2() + a.cross(b) * c.len2()) / (2.0 * det)) +} + +/// The smallest of the balls through two or three of `r` that holds all of them; a ball about +/// their mean where none does (never, for two to four points). +fn smallest_holding(r: &[Vec3]) -> Ball { + let mut best: Option = None; + let mut consider = |ball: Ball| { + if r.iter().all(|q| ball.holds(*q)) && best.is_none_or(|b| ball.radius < b.radius) { + best = Some(ball); + } + }; + for i in 0..r.len() { + for j in i + 1..r.len() { + consider(with_center((r[i] + r[j]) * 0.5, r)); + for k in j + 1..r.len() { + if let Some(c) = circumcentre3(r[i], r[j], r[k]) { + consider(with_center(c, r)); + } + } + } + } + best.unwrap_or_else(|| { + let mean = r.iter().fold(Vec3::ZERO, |s, q| s + *q) / (r.len().max(1) as f64); + with_center(mean, r) + }) +} + +/// A Fisher–Yates shuffle from a fixed seed (SplitMix64), so the same points give the same ball. +fn shuffle(p: &mut [Vec3]) { + let mut state: u64 = 0x9E37_79B9_7F4A_7C15; + for i in (1..p.len()).rev() { + state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + p.swap(i, (z % (i as u64 + 1)) as usize); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Points from a fixed generator in the cube [-1, 1]³. + fn cloud(n: usize, seed: u64) -> Vec { + let mut s = seed; + let mut next = || { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (s >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + }; + (0..n).map(|_| Vec3::new(next(), next(), next())).collect() + } + + /// The smallest ball by brute force: of the balls through two, three or four of the points, + /// the smallest that holds them all. + fn brute(p: &[Vec3]) -> f64 { + let mut best = f64::INFINITY; + let n = p.len(); + let mut try_ball = |b: Ball| { + if p.iter().all(|q| q.dist(b.center) <= b.radius * (1.0 + 1e-9)) { + best = best.min(b.radius); + } + }; + for i in 0..n { + for j in i + 1..n { + try_ball(through(&[p[i], p[j]])); + for k in j + 1..n { + try_ball(through(&[p[i], p[j], p[k]])); + for l in k + 1..n { + try_ball(through(&[p[i], p[j], p[k], p[l]])); + } + } + } + } + best + } + + #[test] + fn the_smallest_ball_holds_every_point_and_matches_brute_force() { + for seed in 1..40 { + let p = cloud(3 + seed as usize % 9, seed); + let ball = Ball::enclosing(&p).unwrap(); + assert!(p.iter().all(|q| ball.holds(*q)), "seed {seed}: a point outside"); + let want = brute(&p); + assert!((ball.radius - want).abs() <= 1e-12 * want, "seed {seed}: {} against {want}", ball.radius); + } + } + + #[test] + fn known_balls() { + let cube: Vec = (0..8).map(|i| Vec3::new((i & 1) as f64, (i >> 1 & 1) as f64, (i >> 2 & 1) as f64)).collect(); + let b = Ball::enclosing(&cube).unwrap(); + assert!(b.center.dist(Vec3::new(0.5, 0.5, 0.5)) < 1e-15 && (b.radius - 3f64.sqrt() / 2.0).abs() < 1e-15); + let s = 3f64.sqrt(); + let triangle = [Vec3::new(1.0, 0.0, 0.0), Vec3::new(-0.5, s / 2.0, 0.0), Vec3::new(-0.5, -s / 2.0, 0.0)]; + assert!((Ball::enclosing(&triangle).unwrap().radius - 1.0).abs() < 1e-15); + // An obtuse triangle's ball is its longest side's. + let obtuse = [Vec3::new(-1.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 0.0)]; + assert!((Ball::enclosing(&obtuse).unwrap().radius - 1.0).abs() < 1e-15); + let tetra = [Vec3::new(1.0, 1.0, 1.0), Vec3::new(1.0, -1.0, -1.0), Vec3::new(-1.0, 1.0, -1.0), Vec3::new(-1.0, -1.0, 1.0)]; + assert!((Ball::enclosing(&tetra).unwrap().radius - s).abs() < 1e-15); + // Points in a line and in a plane, repeated points, one point, none. + let line: Vec = (0..10).map(|i| Vec3::new(i as f64, 2.0 * i as f64, 0.0)).collect(); + assert!((Ball::enclosing(&line).unwrap().diameter() - 9.0 * 5f64.sqrt()).abs() < 1e-12); + let square: Vec = (0..4).flat_map(|i| [Vec3::new((i & 1) as f64, (i >> 1) as f64, 0.0); 3]).collect(); + assert!((Ball::enclosing(&square).unwrap().diameter() - 2f64.sqrt()).abs() < 1e-15); + assert_eq!(Ball::enclosing(&[Vec3::X]), Some(Ball { center: Vec3::X, radius: 0.0 })); + assert_eq!(Ball::enclosing(&[]), None); + assert_eq!(Ball::enclosing(&[Vec3::new(f64::NAN, 0.0, 0.0)]), None); + } + + /// The ball's size is the set's own: a rigid motion leaves it, and points crowding one end + /// do not stretch it (twice the farthest point's distance from the centroid would be nearly + /// twice the diameter here). + #[test] + fn the_size_does_not_move_with_the_points_or_their_crowding() { + let p = cloud(200, 7); + let d = Ball::enclosing(&p).unwrap().diameter(); + let (c, s) = (0.7f64.cos(), 0.7f64.sin()); + let moved: Vec = p.iter().map(|q| Vec3::new(c * q.x - s * q.y + 30.0, s * q.x + c * q.y - 12.0, q.z + 5.0)).collect(); + assert!((Ball::enclosing(&moved).unwrap().diameter() - d).abs() <= 1e-12 * d); + let mut crowded = vec![Vec3::ZERO; 99]; + crowded.push(Vec3::new(1.0, 0.0, 0.0)); + assert!((Ball::enclosing(&crowded).unwrap().diameter() - 1.0).abs() < 1e-15); + } +} diff --git a/crates/geom/src/blend.rs b/crates/geom/src/blend.rs index 6466ff987..15636d3fb 100644 --- a/crates/geom/src/blend.rs +++ b/crates/geom/src/blend.rs @@ -2,7 +2,8 @@ //! interpolation of each reference curve's position and derivatives at the joints. This is the //! geometry `sketch.blend_curve` builds; it knows nothing about sketches or the document. -use crate::{MAX_DERIVATIVE_ORDER, Vec2, profile::binom}; +use crate::{MAX_DERIVATIVE_ORDER, profile::binom}; +use solidcore_record::Vec2; /// Control points of the Bézier of degree `2k + 1`, `k = d0.len()`, that starts at `p0` with /// derivatives `d0` and ends at `p1` with derivatives `d1`, all with respect to its own parameter diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rs index aef024e53..225fbe0ca 100644 --- a/crates/geom/src/brep.rs +++ b/crates/geom/src/brep.rs @@ -1,567 +1,23 @@ -//! SolidCraft-owned portable B-rep data, independent of a modelling backend. -//! Millimetres, radians, right-handed Z-up. See docs/native-brep.md for semantics. -//! Validation checks structure and resource budgets, not geometric equivalence or trust. -use serde::{Deserialize, Serialize}; +//! The kernel's side of the portable B-rep record ([`solidcore_record::brep`]): what computes +//! from its coordinates. Evaluation ([`eval`]), exact NURBS forms of analytic geometry +//! ([`form`]), pcurves ([`pcurve`]), the record's geometric checks ([`check`]: frames, planes, +//! placements; [`geometry`]: that the geometry agrees with the topology), what its labels mean +//! in their own parameters ([`label`]), rigid motions ([`placement`]) and splitting edges +//! ([`split_edges`]). The record itself is data: see SolidCraft's docs/native-brep.md. -pub mod envelope; +// `eval` and `form` name the record's geometry through their parent (`super::Curve`). +use solidcore_record::brep::{Curve, Curve2, Frame, Surface}; -pub const VERSION: u32 = 3; -pub const MAX_ITEMS: usize = 1_000_000; -const MAX_DEPTH: usize = 16; -/// Most control points along one direction of a spline (a helical thread flank written as one -/// spline has thousands along the helix); the item budget bounds a surface's grid as a whole. -pub const MAX_SPLINE_CONTROLS: usize = 8192; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Brep { - pub version: u32, - pub shells: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Shell { - pub vertices: Vec<[f64; 3]>, - pub edges: Vec, - pub faces: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Edge { - pub vertices: [u32; 2], - pub curve: Curve, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Face { - pub loops: Vec>, - pub surface: Surface, - pub forward: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct EdgeUse { - pub edge: u32, - pub forward: bool, -} - -/// Right-handed orthonormal frame; z = x_axis cross y_axis. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Frame { - pub origin: [f64; 3], - pub x_axis: [f64; 3], - pub y_axis: [f64; 3], -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub enum Curve { - Line { - start: [f64; 3], - end: [f64; 3], - }, - CircleArc { - frame: Frame, - radius: f64, - angle: [f64; 2], - }, - EllipseArc { - frame: Frame, - radii: [f64; 2], - angle: [f64; 2], - }, - Polyline { - points: Vec<[f64; 3]>, - }, - Spline { - knots: Vec, - points: Vec<[f64; 3]>, - }, - RationalSpline { - knots: Vec, - homogeneous: Vec<[f64; 4]>, - }, - Intersection { - knots: Vec, - points: Vec<[f64; 3]>, - fitting_tolerance: f64, - faces: Option<[u32; 2]>, - }, - /// The intersection of two surfaces, traced from `leader` (a polyline or spline near it) - /// to within `tolerance`: the procedural curve itself, exactly as its producer holds it. - SurfaceIntersection { - surfaces: [Box; 2], - leader: Box, - tolerance: f64, - }, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub enum Surface { - Plane { - origin: [f64; 3], - u_axis: [f64; 3], - v_axis: [f64; 3], - }, - /// The plane through three points, parameter (1, 0) at `u_point` and (0, 1) at `v_point`: - /// the points themselves, as its producer holds them (axes worked out from them would round). - PlaneThrough { - origin: [f64; 3], - u_point: [f64; 3], - v_point: [f64; 3], - }, - Cylinder { - frame: Frame, - radius: f64, - angle: [f64; 2], - height: [f64; 2], - }, - Cone { - frame: Frame, - radius_at_origin: f64, - half_angle: f64, - angle: [f64; 2], - height: [f64; 2], - }, - Sphere { - frame: Frame, - radius: f64, - longitude: [f64; 2], - latitude: [f64; 2], - }, - Torus { - frame: Frame, - major_radius: f64, - minor_radius: f64, - longitude: [f64; 2], - meridian: [f64; 2], - }, - Spline { - u_knots: Vec, - v_knots: Vec, - points: Vec>, - }, - RationalSpline { - u_knots: Vec, - v_knots: Vec, - homogeneous: Vec>, - }, - Revolution { - profile: Box, - origin: [f64; 3], - axis: [f64; 3], - angle: [f64; 2], - }, - /// A full revolution of `profile` about `origin` and unit `axis`, then mapped by the - /// column-major affine `matrix`, with the normal reversed unless `forward`: the - /// revolution exactly as its producer holds it, nothing baked into the profile. - PlacedRevolution { - profile: Box, - origin: [f64; 3], - axis: [f64; 3], - matrix: [[f64; 4]; 4], - forward: bool, - }, -} - -#[derive(Clone, Debug, thiserror::Error)] -#[error("portable B-rep: {0}")] -pub struct Invalid(pub &'static str); - -type Result = std::result::Result; - -fn require(condition: bool, message: &'static str) -> Result<()> { - if condition { Ok(()) } else { Err(Invalid(message)) } -} - -struct Budget(usize); -impl Budget { - fn add(&mut self, n: usize) -> Result<()> { - self.0 = self.0.checked_add(n).ok_or(Invalid("item budget"))?; - require(self.0 <= MAX_ITEMS, "item budget") - } -} -fn numbers(values: impl IntoIterator) -> Result<()> { - require(values.into_iter().all(|v| v.is_finite() && v.abs() <= 1e12), "non-finite or excessive coordinate") -} -fn points(values: &[[f64; N]], budget: &mut Budget) -> Result<()> { - budget.add(values.len())?; - numbers(values.iter().flatten().copied()) -} -fn knots(values: &[f64], count: usize, budget: &mut Budget) -> Result<()> { - budget.add(values.len())?; - numbers(values.iter().copied())?; - let degree = values.len().checked_sub(count.saturating_add(1)).ok_or(Invalid("spline degree"))?; - require((2..=MAX_SPLINE_CONTROLS).contains(&count) && (1..=16).contains(°ree) && degree < count, "spline degree or size")?; - require(values.windows(2).all(|w| w.first() <= w.get(1)), "unordered knots")?; - require(values.get(degree) < values.get(count), "empty spline domain")?; - // No knot may have multiplicity greater than degree + 1. - let mut run = 1; - for pair in values.windows(2) { - run = if pair.first() == pair.get(1) { run + 1 } else { 1 }; - require(run <= degree + 1, "knot multiplicity")?; - } - Ok(()) -} -fn weights(values: &[[f64; 4]]) -> Result<()> { - require(values.iter().all(|p| p.get(3).is_some_and(|w| *w >= 1e-12)), "non-positive rational weight") -} -fn grid(u: &[f64], v: &[f64], rows: &[Vec<[f64; N]>], budget: &mut Budget) -> Result<()> { - let columns = rows.first().map_or(0, Vec::len); - knots(u, rows.len(), budget)?; - knots(v, columns, budget)?; - for row in rows { - require(row.len() == columns, "ragged surface")?; - points(row, budget)?; - } - Ok(()) -} -fn vector(p: [f64; 3]) -> crate::Vec3 { - crate::Vec3::new(p[0], p[1], p[2]) -} -fn frame(f: &Frame, budget: &mut Budget) -> Result<()> { - points(&[f.origin, f.x_axis, f.y_axis], budget)?; - let (x, y) = (vector(f.x_axis), vector(f.y_axis)); - require((x.len() - 1.).abs() <= 1e-8 && (y.len() - 1.).abs() <= 1e-8 && x.dot(y).abs() <= 1e-8, "nonorthonormal frame") -} -fn range(r: &[f64; 2]) -> Result<()> { - numbers(*r)?; - require(r[0] < r[1], "empty parameter range") -} -fn angle(r: &[f64; 2]) -> Result<()> { - range(r)?; - require(r[1] - r[0] <= std::f64::consts::TAU + 1e-12, "angular range exceeds one turn") -} -fn radius(r: f64) -> Result<()> { - require(r.is_finite() && (1e-12..=1e12).contains(&r), "radius") -} -fn curve(c: &Curve, depth: usize, budget: &mut Budget) -> Result<()> { - require(depth <= MAX_DEPTH, "geometry depth")?; - budget.add(1)?; - match c { - Curve::Line { start, end } => { - points(&[*start, *end], budget)?; - require(start != end, "collapsed line") - } - Curve::CircleArc { frame: f, radius: r, angle: a } => { - frame(f, budget)?; - radius(*r)?; - angle(a) - } - Curve::EllipseArc { frame: f, radii, angle: a } => { - frame(f, budget)?; - for r in radii { - radius(*r)?; - } - angle(a) - } - Curve::Polyline { points: p } => { - require(p.len() >= 2, "empty polyline")?; - points(p, budget)?; - require(p.windows(2).all(|p| p.first() != p.get(1)), "collapsed polyline segment") - } - Curve::Spline { knots: k, points: p } => { - knots(k, p.len(), budget)?; - points(p, budget) - } - Curve::RationalSpline { knots: k, homogeneous: p } => { - knots(k, p.len(), budget)?; - points(p, budget)?; - weights(p) - } - Curve::Intersection { knots: k, points: p, fitting_tolerance, .. } => { - require((1e-12..=1.0).contains(fitting_tolerance), "intersection fitting tolerance")?; - knots(k, p.len(), budget)?; - points(p, budget) - } - Curve::SurfaceIntersection { surfaces, leader, tolerance } => { - require(tolerance.is_finite() && (0.0..=1e3).contains(tolerance), "intersection tolerance")?; - for s in surfaces { - surface(s, depth + 1, budget)?; - } - // The leader is only a starting guess for the trace: its knots are the producer's, - // and a traced polyline may repeat a point. - require(depth < MAX_DEPTH, "geometry depth")?; - budget.add(1)?; - match &**leader { - Curve::Polyline { points: p } => { - require(p.len() >= 2, "empty intersection leader")?; - points(p, budget) - } - Curve::Spline { knots: k, points: p } => { - knots(k, p.len(), budget)?; - points(p, budget) - } - _ => Err(Invalid("intersection leader")), - } - } - } -} -fn surface(s: &Surface, depth: usize, budget: &mut Budget) -> Result<()> { - require(depth <= MAX_DEPTH, "geometry depth")?; - budget.add(1)?; - match s { - Surface::Plane { origin, u_axis, v_axis } => { - points(&[*origin, *u_axis, *v_axis], budget)?; - require(vector(*u_axis).cross(vector(*v_axis)).len() > 1e-12, "degenerate plane") - } - Surface::PlaneThrough { origin, u_point, v_point } => { - points(&[*origin, *u_point, *v_point], budget)?; - let o = vector(*origin); - require((vector(*u_point) - o).cross(vector(*v_point) - o).len() > 1e-12, "degenerate plane") - } - Surface::Cylinder { frame: f, radius: r, angle: a, height } => { - frame(f, budget)?; - radius(*r)?; - angle(a)?; - range(height) - } - Surface::Cone { frame: f, radius_at_origin, half_angle, angle: a, height } => { - frame(f, budget)?; - numbers([*radius_at_origin, *half_angle])?; - require(*radius_at_origin >= 0. && *half_angle > 0. && *half_angle < std::f64::consts::FRAC_PI_2, "cone dimensions")?; - angle(a)?; - range(height)?; - require(height.iter().all(|h| radius_at_origin + h * half_angle.tan() >= 0.), "negative cone radius") - } - Surface::Sphere { frame: f, radius: r, longitude, latitude } => { - frame(f, budget)?; - radius(*r)?; - angle(longitude)?; - range(latitude)?; - require(latitude[0] >= -std::f64::consts::FRAC_PI_2 && latitude[1] <= std::f64::consts::FRAC_PI_2, "sphere latitude") - } - Surface::Torus { frame: f, major_radius, minor_radius, longitude, meridian } => { - frame(f, budget)?; - radius(*major_radius)?; - radius(*minor_radius)?; - require(major_radius > minor_radius, "ring torus radii")?; - angle(longitude)?; - angle(meridian) - } - Surface::Spline { u_knots, v_knots, points: p } => grid(u_knots, v_knots, p, budget), - Surface::RationalSpline { u_knots, v_knots, homogeneous: p } => { - grid(u_knots, v_knots, p, budget)?; - for row in p { - weights(row)?; - } - Ok(()) - } - Surface::Revolution { profile, origin, axis, angle: a } => { - points(&[*origin, *axis], budget)?; - require((vector(*axis).len() - 1.0).abs() <= 1e-8, "revolution axis is not unit length")?; - angle(a)?; - curve(profile, depth + 1, budget) - } - Surface::PlacedRevolution { profile, origin, axis, matrix, .. } => { - points(&[*origin, *axis], budget)?; - require((vector(*axis).len() - 1.0).abs() <= 1e-8, "revolution axis is not unit length")?; - points(matrix, budget)?; - let [x, y, z, _] = matrix.map(|c| vector([c[0], c[1], c[2]])); - require(x.cross(y).dot(z).abs() > 1e-12, "singular revolution placement")?; - curve(profile, depth + 1, budget) - } - } -} - -impl Brep { - /// Validate portable structure without calling a kernel or evaluating geometry. - /// Does not certify watertightness, surface coincidence, or authoritative state. - pub fn validate(&self) -> Result<()> { - require(self.version == VERSION, "unsupported version")?; - require(!self.shells.is_empty() && self.shells.len() <= 1024, "shell count")?; - let mut budget = Budget(0); - for shell in &self.shells { - points(&shell.vertices, &mut budget)?; - budget.add(shell.edges.len())?; - budget.add(shell.faces.len())?; - require(!shell.faces.is_empty(), "empty shell")?; - for edge in &shell.edges { - require(edge.vertices.iter().all(|&v| (v as usize) < shell.vertices.len()), "edge vertices")?; - curve(&edge.curve, 0, &mut budget)?; - if let Curve::Intersection { faces: Some(hints), .. } = &edge.curve { - require(hints.iter().all(|&i| (i as usize) < shell.faces.len()), "intersection face hint")?; - } - } - for face in &shell.faces { - require(!face.loops.is_empty(), "face loops")?; - surface(&face.surface, 0, &mut budget)?; - for wire in &face.loops { - require(!wire.is_empty(), "empty wire")?; - budget.add(wire.len())?; - let mut first = None; - let mut last = None; - for use_ in wire { - let edge = shell.edges.get(use_.edge as usize).ok_or(Invalid("edge reference"))?; - let [a, b] = edge.vertices; - let (start, end) = if use_.forward { (a, b) } else { (b, a) }; - require(last.is_none_or(|v| v == start), "disconnected wire")?; - first.get_or_insert(start); - last = Some(end); - } - require(first == last, "open wire")?; - } - } - } - Ok(()) - } -} +pub mod check; +pub mod eval; +pub mod form; +pub mod geometry; +pub mod label; +pub mod normal_section; +pub mod pcurve; +pub mod placement; +mod split; +pub use split::split_edges; #[cfg(test)] -mod tests { - use super::*; - fn triangle() -> Brep { - let vertices = vec![[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]]; - let edges = (0..3) - .map(|i| Edge { vertices: [i as u32, ((i + 1) % 3) as u32], curve: Curve::Line { start: vertices[i], end: vertices[(i + 1) % 3] } }) - .collect(); - Brep { - version: VERSION, - shells: vec![Shell { - vertices, - edges, - faces: vec![Face { - loops: vec![(0..3).map(|edge| EdgeUse { edge, forward: true }).collect()], - surface: Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }, - forward: true, - }], - }], - } - } - #[test] - fn portable_open_face_round_trip_without_a_kernel() { - let body = triangle(); - body.validate().unwrap(); - let bytes = serde_json::to_vec(&body).unwrap(); - let restored: Brep = serde_json::from_slice(&bytes).unwrap(); - restored.validate().unwrap(); - assert_eq!(body, restored); - assert!(!String::from_utf8(bytes).unwrap().contains("truck")); - } - #[test] - fn topology_references_and_wire_orientation_are_checked() { - let mut b = triangle(); - b.shells[0].faces[0].loops[0][0].edge = u32::MAX; - assert!(b.validate().is_err()); - let mut b = triangle(); - b.shells[0].faces[0].loops[0][1].forward = false; - assert!(b.validate().is_err()); - let mut b = triangle(); - b.shells[0].edges[0].vertices[0] = u32::MAX; - assert!(b.validate().is_err()); - let mut b = triangle(); - b.version += 1; - assert!(b.validate().is_err()); - let mut b = triangle(); - b.shells[0].vertices[0][0] = f64::NAN; - assert!(b.validate().is_err()); - } - #[test] - fn closed_edge_can_share_its_endpoint_vertex() { - let mut body = triangle(); - body.shells[0].vertices.truncate(1); - body.shells[0].edges = - vec![Edge { vertices: [0, 0], curve: Curve::Polyline { points: vec![[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 0., 0.]] } }]; - body.shells[0].faces[0].loops = vec![vec![EdgeUse { edge: 0, forward: true }]]; - body.validate().unwrap(); - } - - #[test] - fn spline_domains_weights_and_nesting_are_bounded() { - let mut budget = Budget(0); - assert!(knots(&[0., 0., 1., 1.], 2, &mut budget).is_ok()); - for bad in [vec![0., 0., 0., 0.], vec![0., 1., 0., 1.], vec![0., 0., f64::INFINITY, 1.]] { - assert!(knots(&bad, 2, &mut Budget(0)).is_err()); - } - let c = Curve::RationalSpline { knots: vec![0., 0., 1., 1.], homogeneous: vec![[0., 0., 0., 0.], [1., 0., 0., 1.]] }; - assert!(curve(&c, 0, &mut Budget(0)).is_err()); - let p = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [2., 0., 0.] }; - assert!(surface(&p, 0, &mut Budget(0)).is_err()); - assert!(curve(&Curve::Line { start: [0.; 3], end: [1.; 3] }, MAX_DEPTH + 1, &mut Budget(0)).is_err()); - assert!(Budget(MAX_ITEMS).add(1).is_err()); - // Control points along one direction: up to the cap, not one more (a clamped cubic). - let clamped = |count: usize| { - let mut k = vec![0.0; 4]; - k.extend((1..count - 3).map(|i| i as f64)); - k.extend([(count - 3) as f64; 4]); - k - }; - assert!(knots(&clamped(MAX_SPLINE_CONTROLS), MAX_SPLINE_CONTROLS, &mut Budget(0)).is_ok()); - assert!(knots(&clamped(MAX_SPLINE_CONTROLS + 1), MAX_SPLINE_CONTROLS + 1, &mut Budget(0)).is_err()); - } - - #[test] - fn exact_procedural_records_are_validated_and_round_trip() { - let plane = |z: f64| Box::new(Surface::Plane { origin: [0., 0., z], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }); - let leader = Box::new(Curve::Polyline { points: vec![[0.; 3], [0.; 3], [1., 0., 0.]] }); - let c = Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: 1e-6 }; - curve(&c, 0, &mut Budget(0)).unwrap(); - assert_eq!(serde_json::from_str::(&serde_json::to_string(&c).unwrap()).unwrap(), c); - let line = Box::new(Curve::Line { start: [0.; 3], end: [1.; 3] }); - for bad in [ - Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: line.clone(), tolerance: 1e-6 }, - Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: f64::NAN }, - Curve::SurfaceIntersection { surfaces: [plane(f64::INFINITY), plane(1.)], leader, tolerance: 1e-6 }, - ] { - assert!(curve(&bad, 0, &mut Budget(0)).is_err()); - } - let identity = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; - let s = Surface::PlacedRevolution { profile: line.clone(), origin: [0.; 3], axis: [0., 0., 1.], matrix: identity, forward: false }; - surface(&s, 0, &mut Budget(0)).unwrap(); - assert_eq!(serde_json::from_str::(&serde_json::to_string(&s).unwrap()).unwrap(), s); - let mut flat = identity; - flat[2] = [0.; 4]; - let bad = Surface::PlacedRevolution { profile: line, origin: [0.; 3], axis: [0., 0., 1.], matrix: flat, forward: true }; - assert!(surface(&bad, 0, &mut Budget(0)).is_err()); - } - - #[test] - fn analytic_records_have_independent_frames_and_domains() { - use std::f64::consts::{FRAC_PI_2, TAU}; - let f = Frame { origin: [1., 2., 3.], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; - let surfaces = [ - Surface::Cylinder { frame: f.clone(), radius: 2., angle: [0., TAU], height: [-1., 3.] }, - Surface::Cone { frame: f.clone(), radius_at_origin: 2., half_angle: 0.2, angle: [0., TAU], height: [0., 3.] }, - Surface::Sphere { frame: f.clone(), radius: 2., longitude: [0., TAU], latitude: [-FRAC_PI_2, FRAC_PI_2] }, - Surface::Torus { frame: f.clone(), major_radius: 4., minor_radius: 1., longitude: [0., TAU], meridian: [0., TAU] }, - Surface::Revolution { - profile: Box::new(Curve::Line { start: [2., 0., 0.], end: [2., 0., 3.] }), - origin: [0.; 3], - axis: [0., 0., 1.], - angle: [0., TAU], - }, - ]; - for s in surfaces { - surface(&s, 0, &mut Budget(0)).unwrap(); - let encoded = serde_json::to_string(&s).unwrap(); - assert_eq!(serde_json::from_str::(&encoded).unwrap(), s); - assert!(!encoded.contains("columns") && !encoded.contains("forward")); - } - for c in [ - Curve::CircleArc { frame: f.clone(), radius: 2., angle: [0., FRAC_PI_2] }, - Curve::EllipseArc { frame: f.clone(), radii: [2., 3.], angle: [0., TAU] }, - Curve::Intersection { knots: vec![0., 0., 1., 1.], points: vec![[0.; 3], [1.; 3]], fitting_tolerance: 1e-6, faces: None }, - ] { - curve(&c, 0, &mut Budget(0)).unwrap(); - let encoded = serde_json::to_string(&c).unwrap(); - assert_eq!(serde_json::from_str::(&encoded).unwrap(), c); - assert!(!encoded.contains("leader") && !encoded.contains("surfaces")); - } - let mut bad = f; - bad.y_axis = bad.x_axis; - assert!(frame(&bad, &mut Budget(0)).is_err()); - assert!(angle(&[0., TAU + 0.1]).is_err()); - assert!(range(&[2., 1.]).is_err()); - assert!(radius(f64::NAN).is_err()); - let mut b = triangle(); - b.shells[0].edges[0].curve = - Curve::Intersection { knots: vec![0., 0., 1., 1.], points: vec![[0.; 3], [1., 0., 0.]], fitting_tolerance: 1e-6, faces: Some([0, 1]) }; - assert!(b.validate().is_err()); - } -} +mod tests; diff --git a/crates/geom/src/brep/check.rs b/crates/geom/src/brep/check.rs new file mode 100644 index 000000000..46687c592 --- /dev/null +++ b/crates/geom/src/brep/check.rs @@ -0,0 +1,81 @@ +//! The kernel's checks of a record's geometric records, which the record's own structural +//! validation ([`Brep::validate`]) leaves to the kernel because they compute: every frame is +//! orthonormal, every plane spans two directions, and every placed revolution turns about a unit +//! axis under a non-singular placement. [`validate`] and [`validate_built`] are the record's +//! validation and these together: what a record must pass before the kernel takes it. +use crate::prelude::*; +use solidcore_record::brep::{Brep, Curve, Frame, Result, Surface, require}; + +use solidcore_record::Vec3; + +/// [`Brep::validate`] (a record from outside the kernel), then [`geometry`]. +pub fn validate(b: &Brep) -> Result<()> { + b.validate()?; + geometry(b) +} + +/// [`Brep::validate_built`] (a record the kernel built), then [`geometry`]. +pub fn validate_built(b: &Brep) -> Result<()> { + b.validate_built()?; + geometry(b) +} + +/// Every edge's and face's geometric records: their frames, planes and placements ([`curve`], +/// [`surface`]). Call on a record its structural validation accepted. +pub fn geometry(b: &Brep) -> Result<()> { + for e in &b.edges { + curve(&e.curve)?; + if let Some(n) = &e.nurbs { + curve(n)?; + } + } + for f in &b.faces { + surface(&f.surface)?; + if let Some(n) = &f.nurbs { + surface(n)?; + } + } + Ok(()) +} + +fn vector(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// A frame's axes are unit and perpendicular, to 1e-8. +pub fn frame(f: &Frame) -> Result<()> { + let (x, y) = (vector(f.x_axis), vector(f.y_axis)); + require((x.len() - 1.).abs() <= 1e-8 && (y.len() - 1.).abs() <= 1e-8 && x.dot(y).abs() <= 1e-8, "nonorthonormal frame") +} + +/// A curve's geometric records, and those of the surfaces of an intersection curve. Call on a +/// curve its structural validation accepted. +pub fn curve(c: &Curve) -> Result<()> { + match c { + Curve::Circle { frame: f, .. } | Curve::Ellipse { frame: f, .. } => frame(f), + Curve::SurfaceIntersection { surfaces, .. } => surfaces.iter().try_for_each(|s| surface(s)), + Curve::Line { .. } | Curve::Polyline { .. } | Curve::Spline { .. } | Curve::RationalSpline { .. } => Ok(()), + } +} + +/// A surface's geometric records, and its profile's for a placed revolution. Call on a surface +/// its structural validation accepted. +pub fn surface(s: &Surface) -> Result<()> { + match s { + Surface::Plane { u_axis, v_axis, .. } => require(vector(*u_axis).cross(vector(*v_axis)).len() > 1e-12, "degenerate plane"), + Surface::PlaneThrough { origin, u_point, v_point } => { + let o = vector(*origin); + require((vector(*u_point) - o).cross(vector(*v_point) - o).len() > 1e-12, "degenerate plane") + } + Surface::Cylinder { frame: f, .. } | Surface::Sphere { frame: f, .. } | Surface::Cone { frame: f, .. } | Surface::Torus { frame: f, .. } => { + frame(f) + } + Surface::PlacedRevolution { profile, axis, matrix, .. } => { + require((vector(*axis).len() - 1.0).abs() <= 1e-8, "revolution axis is not unit length")?; + let [x, y, z, _] = matrix.map(|c| vector([c[0], c[1], c[2]])); + require(x.cross(y).dot(z).abs() > 1e-12, "singular revolution placement")?; + curve(profile) + } + Surface::BallPatch { .. } | Surface::Spline { .. } | Surface::RationalSpline { .. } => Ok(()), + } +} diff --git a/crates/geom/src/brep/envelope.rs b/crates/geom/src/brep/envelope.rs deleted file mode 100644 index 2483992ce..000000000 --- a/crates/geom/src/brep/envelope.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! Stable version-one body metadata records. Runtime model types never define this wire contract. -use serde::{Deserialize, Serialize}; - -pub const VERSION: u32 = 1; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Metadata { - pub version: u32, - pub color: Option<[f32; 3]>, - pub paint: Option, - pub boundaries: Option>>, - pub face_sources: Option>>, - pub history: Option, - pub preserve_boundaries: bool, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Plane { - pub origin: [f64; 3], - pub x_axis: [f64; 3], - pub y_axis: [f64; 3], -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub enum Segment { - Line { start: [f64; 2], end: [f64; 2] }, - Arc { center: [f64; 2], radius: f64, start: f64, sweep: f64 }, - Cubic { points: [[f64; 2]; 4] }, - Conic { points: [[f64; 2]; 3], middle_weight: f64 }, - Bezier { points: Vec<[f64; 2]> }, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Region { - pub outer: Vec, - pub holes: Vec>, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub enum FaceSource { - ExtrusionSide { segment: Segment, plane: Option, coalesced: bool }, - CertifiedExtrusionSide { producer: u64, sketch: u64, curve: String, plane: Option }, - ExtrusionCap { high: bool, region: Region, plane: Plane }, - CertifiedExtrusionCap { producer: u64, sketch: u64, high: bool, outer: Vec, holes: Vec>, plane: Plane }, - CylinderCap { producer: u64, high: bool, plane: Plane }, - BoxFace { producer: Option, axis: u8, high: bool, plane: Plane }, - PlanarShell { producer: Option, source: Box, inner: bool, plane: Plane }, - Imported { item: u64, face: u64, payload_sha256: Option, producer: Option }, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Paint { - pub opacity: f32, - pub faces: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct FacePaint { - pub face: u32, - pub color: [f32; 3], - pub opacity: f32, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct History { - pub operands: u32, - pub faces: Vec, - pub edges: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct FaceHistory { - pub origins: Vec, - pub change: Change, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct EdgeHistory { - pub faces: Vec, - pub origins: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub enum FaceOrigin { - Face { operand: u32, face: u32 }, - Profile { segment: u32 }, - Cap { end: bool }, - Edge { operand: u32, edge: u32 }, - Offset { operand: u32, face: u32 }, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub enum EdgeOrigin { - Edge { operand: u32, edge: u32 }, - Meeting { sides: [Vec; 2] }, -} - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Change { - Kept, - Modified, - Split, - Merged, - Generated, -} diff --git a/crates/geom/src/brep/eval.rs b/crates/geom/src/brep/eval.rs new file mode 100644 index 000000000..d2f8a712f --- /dev/null +++ b/crates/geom/src/brep/eval.rs @@ -0,0 +1,625 @@ +//! Points of curve and surface records, in the records' own parameters (docs/native-brep.md, +//! "Geometry"), and the parameters of a point on a surface. Planes, splines and revolutions go +//! through the display evaluator ([`EvalSurface`], [`EvalCurve`], [`uv`]), which parameterises +//! them as their producer does; cylinders, cones, spheres and tori are evaluated and inverted in +//! closed form, in angle and height. A `surface_intersection` is the point of both surfaces in +//! the plane through its leader's point normal to the leader there, which truck's `subs` +//! converges to (within its 10⁻⁶ mm), found by Newton's method on the three planes. +//! +//! Call on validated records. Evaluation of a well-formed record never panics: a point that +//! cannot be had (a vanishing weight, a Newton step that does not converge) is `None`. +use super::normal_section::normal_section; +use super::pcurve::Error; +use super::{Curve, Curve2, Frame, Surface}; +use crate::bspline::MAX_SPLINE_DEGREE; +use crate::prelude::*; +use crate::tess::partials::{Partials, tabulate, trig_derivative}; +use crate::tess::uv::{self, Domain}; +use crate::tess::{EvalCurve, EvalSurface, MAX_EVAL_KNOTS, MAX_EVAL_POINTS}; +use solidcore_record::Vec3; +use std::f64::consts::{FRAC_PI_2, TAU}; + +/// Newton steps of one intersection point. +const MAX_NEWTON: usize = 64; + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} +fn unsupported(what: impl std::fmt::Display) -> Error { + Error::Failed(format!("not supported yet: {what}")) +} + +/// A frame's origin and axes, z = x × y. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Axes { + pub(crate) o: Vec3, + pub(crate) x: Vec3, + pub(crate) y: Vec3, + pub(crate) z: Vec3, +} +impl Axes { + pub(crate) fn new(f: &Frame) -> Self { + let (x, y) = (v3(f.x_axis), v3(f.y_axis)); + Axes { o: v3(f.origin), x, y, z: x.cross(y) } + } + /// `p` in the frame: (x, y, z) coordinates. + pub(crate) fn local(&self, p: Vec3) -> [f64; 3] { + let q = p - self.o; + [q.dot(self.x), q.dot(self.y), q.dot(self.z)] + } + /// The radial direction at angle `u` and its derivative. + fn radial(&self, u: f64) -> (Vec3, Vec3) { + let (s, c) = u.sin_cos(); + (self.x * c + self.y * s, self.y * c - self.x * s) + } +} + +/// The angle of (a, b) in [0, 2π), `near`'s (or 0) on the axis, where it is undefined. +fn angle(a: f64, b: f64, near: Option) -> f64 { + if a == 0.0 && b == 0.0 { + return near.unwrap_or(0.0); + } + let u = b.atan2(a); + if u < 0.0 { u + TAU } else { u } +} + +/// A surface record ready to evaluate. +#[derive(Clone, Debug, PartialEq)] +pub enum SurfaceEval { + /// A plane, spline or revolution, on the display evaluator. + Eval(EvalSurface, Domain), + Cylinder { + axes: Axes, + radius: f64, + }, + Cone { + axes: Axes, + radius_at_origin: f64, + slope: f64, + }, + Sphere { + axes: Axes, + radius: f64, + }, + /// `tube`: the tube angle at v = 0 (`Surface::Torus::tube_start`). + Torus { + axes: Axes, + major: f64, + minor: f64, + tube: f64, + }, +} + +impl SurfaceEval { + pub fn new(s: &Surface) -> Result { + let eval = |e: EvalSurface| { + let dom = uv::domain(&e); + Ok(SurfaceEval::Eval(e, dom)) + }; + match s { + Surface::Plane { origin, u_axis, v_axis } => eval(EvalSurface::Plane { origin: v3(*origin), du: v3(*u_axis), dv: v3(*v_axis) }), + Surface::PlaneThrough { origin, u_point, v_point } => { + let o = v3(*origin); + eval(EvalSurface::Plane { origin: o, du: v3(*u_point) - o, dv: v3(*v_point) - o }) + } + Surface::Cylinder { frame, radius } => Ok(SurfaceEval::Cylinder { axes: Axes::new(frame), radius: *radius }), + Surface::Cone { frame, radius_at_origin, half_angle } => { + Ok(SurfaceEval::Cone { axes: Axes::new(frame), radius_at_origin: *radius_at_origin, slope: half_angle.tan() }) + } + Surface::Sphere { frame, radius } => Ok(SurfaceEval::Sphere { axes: Axes::new(frame), radius: *radius }), + Surface::Torus { frame, major_radius, minor_radius, tube_start } => { + Ok(SurfaceEval::Torus { axes: Axes::new(frame), major: *major_radius, minor: *minor_radius, tube: *tube_start }) + } + // A label with no (u, v) of its own: its face evaluates its NURBS form. + Surface::BallPatch { .. } => Err(unsupported("a ball patch's label (evaluate its NURBS form)")), + Surface::Spline { u_knots, v_knots, points } => { + let rows: Vec> = points.iter().map(|r| r.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect()).collect(); + eval(nurbs(u_knots, v_knots, &rows)?) + } + Surface::RationalSpline { u_knots, v_knots, homogeneous } => eval(nurbs(u_knots, v_knots, homogeneous)?), + Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => { + let profile = match CurveEval::new(profile)? { + CurveEval::Spline(c) => c, + CurveEval::Line { start, end } => EvalCurve { + degree: 1, + knots: vec![0.0, 0.0, 1.0, 1.0], + ctrl: vec![[start.x, start.y, start.z, 1.0], [end.x, end.y, end.z, 1.0]], + }, + _ => return Err(unsupported("a revolution of a conic, polyline or intersection profile")), + }; + let axis = v3(*axis).normalized().ok_or_else(|| Error::Invalid("revolution axis".into()))?; + // Column-major: matrix[column][row]. + let transform = [0, 1, 2].map(|r| [matrix[0][r], matrix[1][r], matrix[2][r], matrix[3][r]]); + eval(EvalSurface::Revolved { profile, origin: v3(*origin), axis, transform, swap: !forward }) + } + } + } + + /// The parameter box and periods. + pub fn domain(&self) -> Domain { + let turn = (Some((0.0, TAU)), Some(TAU)); + let open = (None, None); + let ((ru, pu), (rv, pv)) = match self { + SurfaceEval::Eval(_, dom) => return *dom, + SurfaceEval::Cylinder { .. } | SurfaceEval::Cone { .. } => (turn, open), + SurfaceEval::Sphere { .. } => (turn, (Some((-FRAC_PI_2, FRAC_PI_2)), None)), + SurfaceEval::Torus { .. } => (turn, turn), + }; + Domain { range: [ru, rv], period: [pu, pv] } + } + + /// Point and first partial derivatives at (u, v). + pub fn derivs(&self, u: f64, v: f64) -> Option<(Vec3, Vec3, Vec3)> { + if !(u.is_finite() && v.is_finite()) { + return None; + } + Some(match self { + SurfaceEval::Eval(e, _) => return e.derivs(u, v), + SurfaceEval::Cylinder { axes: a, radius } => { + let (r, dr) = a.radial(u); + (a.o + a.z * v + r * *radius, dr * *radius, a.z) + } + SurfaceEval::Cone { axes: a, radius_at_origin, slope } => { + let (r, dr) = a.radial(u); + let rv = radius_at_origin + v * slope; + (a.o + a.z * v + r * rv, dr * rv, a.z + r * *slope) + } + SurfaceEval::Sphere { axes: a, radius } => { + let (r, dr) = a.radial(u); + let (s, c) = v.sin_cos(); + (a.o + (r * c + a.z * s) * *radius, dr * (c * radius), (a.z * c - r * s) * *radius) + } + SurfaceEval::Torus { axes: a, major, minor, tube } => { + let (r, dr) = a.radial(u); + let (s, c) = (v + tube).sin_cos(); + let ring = major + minor * c; + (a.o + r * ring + a.z * (minor * s), dr * ring, (a.z * c - r * s) * *minor) + } + }) + } + + pub fn point(&self, uv: [f64; 2]) -> Option { + self.derivs(uv[0], uv[1]).map(|d| d.0) + } + + /// The second partial derivatives `(S_uu, S_uv, S_vv)` at (u, v): in closed form on the + /// analytic surfaces, from the basis functions' own second derivatives on a spline; `None` + /// for a revolution ([`EvalSurface::second`]). + pub fn second(&self, u: f64, v: f64) -> Option<(Vec3, Vec3, Vec3)> { + if !(u.is_finite() && v.is_finite()) { + return None; + } + Some(match self { + SurfaceEval::Eval(e, _) => return e.second(u, v), + SurfaceEval::Cylinder { axes: a, radius } => (a.radial(u).0 * -*radius, Vec3::ZERO, Vec3::ZERO), + SurfaceEval::Cone { axes: a, radius_at_origin, slope } => { + let (r, dr) = a.radial(u); + (r * -(radius_at_origin + v * slope), dr * *slope, Vec3::ZERO) + } + SurfaceEval::Sphere { axes: a, radius } => { + let (r, dr) = a.radial(u); + let (s, c) = v.sin_cos(); + (r * (-c * radius), dr * (-s * radius), (r * c + a.z * s) * -*radius) + } + SurfaceEval::Torus { axes: a, major, minor, tube } => { + let (r, dr) = a.radial(u); + let (s, c) = (v + tube).sin_cos(); + (r * -(major + minor * c), dr * (-s * minor), (r * c + a.z * s) * -*minor) + } + }) + } + + /// The partial derivatives at (u, v) up to the fourth order ([`Partials`]), exactly: in closed + /// form on the analytic surfaces (angles differentiate as `cos(t + kπ/2)`), on the display + /// evaluator otherwise ([`EvalSurface::partials`]). + pub fn partials(&self, u: f64, v: f64) -> Option { + if !(u.is_finite() && v.is_finite()) { + return None; + } + // The i-th derivative of the radial direction at angle u, and the k-th of cos and sin at v. + let radial = |a: &Axes, i: usize| { + let (c, s) = trig_derivative(u, i); + a.x * c + a.y * s + }; + let at_v = |k: usize| trig_derivative(v, k); + let lift = |a: &Axes, i: usize, j: usize, x: Vec3| if i == 0 && j == 0 { a.o + x } else { x }; + match self { + SurfaceEval::Eval(e, _) => e.partials(u, v), + SurfaceEval::Cylinder { axes: a, radius } => tabulate(|i, j| { + let height = match j { + 0 if i == 0 => a.z * v, + 1 if i == 0 => a.z, + _ => Vec3::ZERO, + }; + let ring = if j == 0 { radial(a, i) * *radius } else { Vec3::ZERO }; + Some(lift(a, i, j, ring + height)) + }), + SurfaceEval::Cone { axes: a, radius_at_origin, slope } => tabulate(|i, j| { + let (height, rv) = match j { + 0 => (if i == 0 { a.z * v } else { Vec3::ZERO }, radius_at_origin + v * slope), + 1 => (if i == 0 { a.z } else { Vec3::ZERO }, *slope), + _ => (Vec3::ZERO, 0.0), + }; + Some(lift(a, i, j, radial(a, i) * rv + height)) + }), + SurfaceEval::Sphere { axes: a, radius } => tabulate(|i, j| { + let (c, s) = at_v(j); + let pole = if i == 0 { a.z * s } else { Vec3::ZERO }; + Some(lift(a, i, j, (radial(a, i) * c + pole) * *radius)) + }), + SurfaceEval::Torus { axes: a, major, minor, tube } => tabulate(|i, j| { + let (c, s) = trig_derivative(v + tube, j); + let ring = if j == 0 { major + minor * c } else { minor * c }; + let tube = if i == 0 { a.z * (minor * s) } else { Vec3::ZERO }; + Some(lift(a, i, j, radial(a, i) * ring + tube)) + }), + } + } + + /// The parameters of `p`, a point within `accept` of the surface, from `near` when given + /// (not unwrapped to it). + pub fn project(&self, p: Vec3, near: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { + self.project_with(&uv::Starts::default(), p, near, accept) + } + + /// [`SurfaceEval::project`] with the search grid of a spline or revolution kept in `starts` + /// ([`uv::project_with`]), which must serve this surface only. + pub fn project_with(&self, starts: &uv::Starts, p: Vec3, near: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { + let q = match self { + SurfaceEval::Eval(e, dom) => return uv::project_with(e, dom, starts, p, near, accept), + SurfaceEval::Cylinder { axes, .. } => { + let [a, b, h] = axes.local(p); + [angle(a, b, near.map(|n| n[0])), h] + } + SurfaceEval::Cone { axes, radius_at_origin, slope } => { + // The nearest point of the generator line through p's half-plane. + let [a, b, h] = axes.local(p); + [angle(a, b, near.map(|n| n[0])), ((a.hypot(b) - radius_at_origin) * slope + h) / (1.0 + slope * slope)] + } + SurfaceEval::Sphere { axes, .. } => { + let [a, b, h] = axes.local(p); + [angle(a, b, near.map(|n| n[0])), h.atan2(a.hypot(b))] + } + SurfaceEval::Torus { axes, major, tube, .. } => { + let [a, b, h] = axes.local(p); + let v = (h.atan2(a.hypot(b) - major) - tube).rem_euclid(TAU); + [angle(a, b, near.map(|n| n[0])), v] + } + }; + (q[0].is_finite() && q[1].is_finite() && self.point(q).is_some_and(|s| s.dist(p) <= accept)).then_some(q) + } + + /// Whether moving along each direction at `uv` leaves the point where it is (a pole). + pub fn pole(&self, uv: [f64; 2]) -> [bool; 2] { + let Some((_, su, sv)) = self.derivs(uv[0], uv[1]) else { return [false; 2] }; + let (a, b) = (su.len(), sv.len()); + [a <= 1e-9 * b.max(1e-12), b <= 1e-9 * a.max(1e-12)] + } + + /// [`Self::pole`], or within `reach` mm of one: moving along a direction across half its + /// period (or its whole range) moves the point no more than `reach` (a boundary point that + /// lies at a pole to within a tolerance, where its periodic parameter is free). + pub fn pole_within(&self, uv: [f64; 2], reach: f64) -> [bool; 2] { + let Some((_, su, sv)) = self.derivs(uv[0], uv[1]) else { return [false; 2] }; + uv::collapsed([su.len(), sv.len()], &self.domain(), reach) + } +} + +/// A tensor spline's rows (`rows[i][j]`, i along u) as the evaluator's u-fastest array. +fn nurbs(u_knots: &[f64], v_knots: &[f64], rows: &[Vec<[f64; 4]>]) -> Result { + let (nu, nv) = (rows.len(), rows.first().map_or(0, Vec::len)); + let degree = |k: &[f64], n: usize| k.len().checked_sub(n + 1).ok_or_else(|| Error::Invalid("spline degree".into())); + let (pu, pv) = (degree(u_knots, nu)?, degree(v_knots, nv)?); + if pu.max(pv) > MAX_SPLINE_DEGREE || pu.min(pv) == 0 { + return Err(unsupported(format!("a spline surface of degree ({pu}, {pv})"))); + } + if u_knots.len().max(v_knots.len()) > MAX_EVAL_KNOTS || nu.saturating_mul(nv) > MAX_EVAL_POINTS { + return Err(Error::TooLarge(format!("a spline surface of {nu} × {nv} points"))); + } + let mut ctrl = Vec::with_capacity(nu * nv); + for j in 0..nv { + for row in rows { + ctrl.push(*row.get(j).ok_or_else(|| Error::Invalid("ragged surface".into()))?); + } + } + Ok(EvalSurface::nurbs([pu, pv], [u_knots.to_vec(), v_knots.to_vec()], [nu, nv], ctrl)) +} + +/// A curve record ready to evaluate. +#[derive(Clone, Debug, PartialEq)] +pub enum CurveEval { + Line { + start: Vec3, + end: Vec3, + }, + /// A circle or an ellipse. + Conic { + axes: Axes, + radii: [f64; 2], + }, + Polyline(Vec), + Spline(EvalCurve), + Intersection(Box), +} + +/// A curve's differential geometry at one parameter. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CurveJet { + pub point: Vec3, + /// The unit tangent, along the curve's parameter. + pub tangent: Vec3, + /// The curvature vector `κ N`, 1/mm: towards the centre of curvature, its length the + /// curvature; zero where the curve is straight. + pub curvature: Vec3, +} + +impl CurveJet { + fn is_finite(&self) -> bool { + self.point.is_finite() && self.tangent.is_finite() && self.curvature.is_finite() + } +} + +/// A `surface_intersection` ready to evaluate. +#[derive(Clone, Debug, PartialEq)] +pub struct Intersection { + surfaces: [SurfaceEval; 2], + leader: CurveEval, +} + +impl CurveEval { + pub fn new(c: &Curve) -> Result { + Ok(match c { + Curve::Line { start, end } => CurveEval::Line { start: v3(*start), end: v3(*end) }, + Curve::Circle { frame, radius } => CurveEval::Conic { axes: Axes::new(frame), radii: [*radius; 2] }, + Curve::Ellipse { frame, radii } => CurveEval::Conic { axes: Axes::new(frame), radii: *radii }, + Curve::Polyline { points } => CurveEval::Polyline(points.iter().copied().map(v3).collect()), + Curve::Spline { knots, points } => spline(knots, points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect())?, + Curve::RationalSpline { knots, homogeneous } => spline(knots, homogeneous.clone())?, + Curve::SurfaceIntersection { surfaces, leader, .. } => { + let leader = CurveEval::new(leader)?; + if !matches!(leader, CurveEval::Polyline(_) | CurveEval::Spline(_)) { + return Err(Error::Invalid("intersection leader".into())); + } + CurveEval::Intersection(Box::new(Intersection { + surfaces: [SurfaceEval::new(&surfaces[0])?, SurfaceEval::new(&surfaces[1])?], + leader, + })) + } + }) + } + + /// The point at `t`. + pub fn point(&self, t: f64) -> Option { + if !t.is_finite() { + return None; + } + match self { + CurveEval::Line { start, end } => Some(*start + (*end - *start) * t), + CurveEval::Conic { axes: a, radii } => { + let (s, c) = t.sin_cos(); + Some(a.o + a.x * (radii[0] * c) + a.y * (radii[1] * s)) + } + CurveEval::Polyline(_) | CurveEval::Spline(_) => self.leader(t).map(|d| d.0), + CurveEval::Intersection(x) => x.point(t), + } + } + + /// Point and derivative of a polyline (truck's: the segment from ⌊t⌋, the last one at the + /// end) or a spline. + /// The point and first derivative at `t`; `None` for a traced intersection (its tangent + /// is not held). + pub fn derivs(&self, t: f64) -> Option<(Vec3, Vec3)> { + if !t.is_finite() { + return None; + } + match self { + CurveEval::Line { start, end } => Some((*start + (*end - *start) * t, *end - *start)), + CurveEval::Conic { axes: a, radii } => { + let (s, c) = t.sin_cos(); + Some((a.o + a.x * (radii[0] * c) + a.y * (radii[1] * s), a.y * (radii[1] * c) - a.x * (radii[0] * s))) + } + CurveEval::Polyline(_) | CurveEval::Spline(_) => self.leader(t), + CurveEval::Intersection(_) => None, + } + } + + /// The point, unit tangent and curvature vector at `t` ([`CurveJet`]), exactly: from the + /// record's first two derivatives on a line, conic or spline (in closed form, or the basis + /// functions' own, weights divided out), straight on each segment of a polyline; on a traced + /// intersection from both surfaces' normal curvatures along its tangent + /// ([`Intersection::jet`]). `None` where the tangent vanishes, the two surfaces are tangent, + /// or a value is not finite. + pub fn jet(&self, t: f64) -> Option { + if !t.is_finite() { + return None; + } + let (point, d1, d2) = match self { + CurveEval::Line { start, end } => (*start + (*end - *start) * t, *end - *start, Vec3::ZERO), + CurveEval::Conic { axes: a, radii } => { + let (s, c) = t.sin_cos(); + let (x, y) = (a.x * (radii[0] * c), a.y * (radii[1] * s)); + (a.o + x + y, a.y * (radii[1] * c) - a.x * (radii[0] * s), -(x + y)) + } + CurveEval::Polyline(_) => { + let (p, d) = self.leader(t)?; + (p, d, Vec3::ZERO) + } + CurveEval::Spline(c) => match c.derivatives(t, 2)?.as_slice() { + [p, d1, d2] => (*p, *d1, *d2), + _ => return None, + }, + CurveEval::Intersection(x) => return x.jet(t), + }; + let speed2 = d1.len2(); + if !(speed2 > 0.0) { + return None; + } + let tangent = d1 * (1.0 / speed2.sqrt()); + // κ N = (r'' − (r''·T) T) / |r'|²: the part of the acceleration across the curve. + let curvature = (d2 - tangent * d2.dot(tangent)) * (1.0 / speed2); + let jet = CurveJet { point, tangent, curvature }; + jet.is_finite().then_some(jet) + } + + fn leader(&self, t: f64) -> Option<(Vec3, Vec3)> { + match self { + CurveEval::Polyline(p) => { + let n = p.len(); + let last = *p.last()?; + if t <= 0.0 { + return Some((*p.first()?, *p.get(1)? - *p.first()?)); + } + if t + 1.0 >= n as f64 { + return Some((last, last - *p.get(n.checked_sub(2)?)?)); + } + let i = t as usize; + let (a, b) = (*p.get(i)?, *p.get(i + 1)?); + Some((a + (b - a) * (t - i as f64), b - a)) + } + CurveEval::Spline(c) => c.eval(t), + _ => None, + } + } +} + +fn spline(knots: &[f64], ctrl: Vec<[f64; 4]>) -> Result { + let degree = knots.len().checked_sub(ctrl.len() + 1).ok_or_else(|| Error::Invalid("spline degree".into()))?; + if !(1..=MAX_SPLINE_DEGREE).contains(°ree) { + return Err(unsupported(format!("a spline curve of degree {degree}"))); + } + Ok(CurveEval::Spline(EvalCurve { degree, knots: knots.to_vec(), ctrl })) +} + +impl Intersection { + /// The point in the leader's normal plane at `t`, found from the leader's point: a function + /// of `t` alone, whatever was evaluated before (and so the same on every thread). + fn point(&self, t: f64) -> Option { + let (lead, along) = self.leader.leader(t)?; + if !(along.len2() > 0.0) { + return None; + } + self.solve(lead, along) + } + + /// The curve's [`CurveJet`] at `t`. The tangent is square to both surfaces' normals (along the + /// leader); the curvature vector lies in the plane of those normals, and its component along + /// each is that surface's normal curvature in the tangent's direction (Meusnier), from the + /// surface's exact partial derivatives ([`normal_section`]): two equations for its two + /// components. `None` where the surfaces are tangent (their normals do not span a plane). + fn jet(&self, t: f64) -> Option { + let (lead, along) = self.leader.leader(t)?; + if !(along.len2() > 0.0) { + return None; + } + let point = self.solve(lead, along)?; + let mut feet = [(Vec3::ZERO, None); 2]; + for (foot, s) in feet.iter_mut().zip(&self.surfaces) { + let q = s.project(point, None, f64::INFINITY)?; + let d = s.partials(q[0], q[1])?; + *foot = (d[1][0].cross(d[0][1]).normalized()?, Some(d)); + } + let [(n0, Some(d0)), (n1, Some(d1))] = feet else { return None }; + let mut tangent = n0.cross(n1).normalized()?; + if tangent.dot(along) < 0.0 { + tangent = -tangent; + } + let k0 = normal_section(&d0, n0, tangent)?.curvature; + let k1 = normal_section(&d1, n1, tangent)?.curvature; + // κN = a n0 + b n1 with κN·n0 = k0 and κN·n1 = k1. + let c = n0.dot(n1); + let det = 1.0 - c * c; + if !(det > 1e-12) { + return None; + } + let (a, b) = ((k0 - c * k1) / det, (k1 - c * k0) / det); + let jet = CurveJet { point, tangent, curvature: n0 * a + n1 * b }; + jet.is_finite().then_some(jet) + } + + /// Newton on the planes: each surface's tangent plane at the foot of the current point, and + /// the leader's normal plane, until the point stops moving. + fn solve(&self, lead: Vec3, along: Vec3) -> Option { + let mut x = lead; + let mut uv: Option<[[f64; 2]; 2]> = None; + for _ in 0..MAX_NEWTON { + let mut planes = [(Vec3::ZERO, 0.0); 2]; + let mut feet = [[0.0; 2]; 2]; + for (i, s) in self.surfaces.iter().enumerate() { + let q = s.project(x, uv.and_then(|h| h.get(i).copied()), f64::INFINITY)?; + let (f, su, sv) = s.derivs(q[0], q[1])?; + let n = su.cross(sv).normalized()?; + *planes.get_mut(i)? = (n, n.dot(f)); + *feet.get_mut(i)? = q; + } + uv = Some(feet); + let [(n0, d0), (n1, d1)] = planes; + let y = solve3([n0, n1, along], [d0, d1, along.dot(lead)])?; + let step = y.dist(x); + x = y; + if step <= 1e-12 * (1.0 + x.len()) { + return Some(x); + } + } + None + } +} + +/// The point on the three planes `rows[i] · x = rhs[i]` (Cramer's rule), `None` when they meet +/// in no single point (tangent surfaces). +fn solve3(rows: [Vec3; 3], rhs: [f64; 3]) -> Option { + let [a, b, c] = rows; + let (bc, ca, ab) = (b.cross(c), c.cross(a), a.cross(b)); + let det = a.dot(bc); + if !(det.abs() > 1e-12 * a.len() * b.len() * c.len()) { + return None; + } + let x = (bc * rhs[0] + ca * rhs[1] + ab * rhs[2]) * (1.0 / det); + x.is_finite().then_some(x) +} + +/// Four-point Gauss–Legendre nodes and weights on `[−1, 1]`. +const GAUSS4: [(f64, f64); 4] = [ + (-0.861_136_311_594_052_6, 0.347_854_845_137_453_8), + (-0.339_981_043_584_856_3, 0.652_145_154_862_546_2), + (0.339_981_043_584_856_3, 0.652_145_154_862_546_2), + (0.861_136_311_594_052_6, 0.347_854_845_137_453_8), +]; + +/// Pieces each pcurve is integrated in, and how many Gauss panels cover a v range. +const FLUX_PIECES: usize = 32; +const FLUX_PANELS: usize = 4; + +/// The flux of `field` through a face, `∫∫ field(S)·(S_u × S_v) du dv` over the (u, v) region its +/// loops (record convention, each use its pcurve and direction) bound, by Green's theorem: +/// `∮ −G du` with `G(u, v) = ∫ field·N ds` from `v0` to `v`. A quadrature for the sign of a +/// shell's volume (`field = p / 3`) or a winding number, which only has to be right to well +/// under a half: no geometry is made from it. Loops round a periodic direction need no seam +/// edge, as a seam's two runs at constant u add nothing to `∮ G du`. +pub fn face_flux(s: &SurfaceEval, v0: f64, loops: &[Vec<(&Curve2, bool)>], field: &dyn Fn(Vec3) -> Vec3) -> Option { + let g = |u: f64, v: f64| -> Option { + let (mut sum, h) = (0.0, (v - v0) / FLUX_PANELS as f64); + for panel in 0..FLUX_PANELS { + let a = v0 + h * panel as f64; + for (x, w) in GAUSS4 { + let t = a + 0.5 * h * (x + 1.0); + let (p, su, sv) = s.derivs(u, t)?; + sum += 0.5 * h * w * field(p).dot(su.cross(sv)); + } + } + sum.is_finite().then_some(sum) + }; + let mut total = 0.0; + for (c, forward) in loops.iter().flatten() { + let [t0, t1] = c.interval()?; + let at = |k: f64| { + let f = k / FLUX_PIECES as f64; + // Exactly the ends at f = 0 and 1, whatever the interval's rounding. + super::pcurve::eval(c, if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f }) + }; + for k in 0..FLUX_PIECES { + let (a, m, z) = (at(k as f64)?, at(k as f64 + 0.5)?, at(k as f64 + 1.0)?); + total -= g(m[0], m[1])? * (z[0] - a[0]); + } + } + total.is_finite().then_some(total) +} diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rs new file mode 100644 index 000000000..c1008f4d6 --- /dev/null +++ b/crates/geom/src/brep/form.rs @@ -0,0 +1,711 @@ +//! The NURBS forms of the record's analytic curves and surfaces: the exact B-spline each one is +//! (docs/native-brep.md, "Surfaces"), built the way SMLib holds its own, so that a circle and every +//! face it bounds share one parameterisation and their pcurves are exact by construction. +//! +//! Angles are on rational quadratic quarter arcs laid on their frame's quarter grid: quarter `q` +//! runs from `q·π/2` to `(q+1)·π/2` from the frame's x axis, and the form parameter of an angle +//! `θ` in it is `q + u`, `u` the arc's own parameter (closed form, [`quarter_u`]). Every form on one +//! frame therefore has the same parameter at the same angle, whatever quarters it spans: a circle +//! edge's form and its cylinder's form agree along it, so its pcurve is a straight line in (u, v). +//! A form spans the quarters its interval needs (at most five for one turn), so an arc across the +//! frame's x axis has a form like any other. A face of five would cover part of its surface twice: +//! its frame is turned about its axis first ([`turned`], [`turn_quarters`]), so that it starts on +//! a quarter line and its form spans four; a torus face's tube likewise starts from its tube start +//! ([`tube_turned`], [`tube_quarters`]). +//! +//! A circle or ellipse is the arcs (an ellipse scaled by its radii, which keeps it exact: its +//! parameter is the eccentric angle). A cylinder or cone is the arcs times a degree-1 line along the +//! axis; a sphere the arcs times arcs of latitude (from `−π/2` to `π/2`); a torus the arcs times +//! the arcs of its tube. A line is the degree-1 B-spline on its own parameter. + +use super::{Curve, Frame, Surface}; +use crate::prelude::*; +use solidcore_record::Vec3; +use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, FRAC_PI_8, TAU}; + +/// Rounding room on an angle at a quarter's end. +const SLACK: f64 = 1e-12; + +/// The quarter arc's parameter `u` in `[0, 1]` at angle `ψ` in `[0, π/2]` from its start: the +/// arc with ends `±π/4` from its bisector and middle weight `cos π/4` has +/// `tan((ψ − π/4)/2) = tan(π/8)(2u − 1)`. +fn quarter_u(psi: f64) -> f64 { + 0.5 * (1.0 + (0.5 * psi - FRAC_PI_8).tan() / FRAC_PI_8.tan()) +} + +fn quarter_psi(u: f64) -> f64 { + 2.0 * (((2.0 * u - 1.0) * FRAC_PI_8.tan()).atan() + FRAC_PI_8) +} + +/// The quarter an angle lies in (an angle on a quarter's end lies in the one after it). +fn quarter_of(theta: f64) -> f64 { + (theta / FRAC_PI_2 + SLACK).floor() +} + +/// The form parameter of angle `theta`: its quarter plus the arc's parameter there. +pub fn param(theta: f64) -> f64 { + let q = quarter_of(theta); + q + quarter_u((theta - q * FRAC_PI_2).clamp(0.0, FRAC_PI_2)) +} + +/// The angle at form parameter `s`. +pub fn angle(s: f64) -> f64 { + let q = s.floor(); + q * FRAC_PI_2 + quarter_psi(s - q) +} + +/// The quarters an angle interval needs: the first one and how many. An end within `reach` (an +/// angle) of a quarter's end is on it: a face whose boundary lies within its tolerance of a +/// quarter's end needs no part of the quarter past it. +fn quarters([a0, a1]: [f64; 2], reach: f64) -> Option<(f64, usize)> { + if !(a0.is_finite() && a1.is_finite() && a1 > a0 && a1 - a0 <= TAU * (1.0 + 1e-9)) { + return None; + } + let on_end = |a: f64| { + let end = (a / FRAC_PI_2).round() * FRAC_PI_2; + if (a - end).abs() <= reach { end } else { a } + }; + let (a0, a1) = (on_end(a0), on_end(a1)); + let q0 = quarter_of(a0); + let q1 = (a1 / FRAC_PI_2 - SLACK).ceil(); + let n = (q1 - q0).max(1.0) as usize; + (n <= 5).then_some((q0, n)) +} + +/// A face's quarters along an angle direction and its domain there: a whole turn is exactly +/// four quarters from the one it starts in (the form closes on itself, so it is periodic and the +/// face's seam uses lie a period apart), anything less the quarters it needs ([`quarters`], ends +/// within `reach` of a quarter's end on it). +fn face_quarters(a: [f64; 2], reach: f64) -> Option<((f64, usize), [f64; 2])> { + if a[1] - a[0] >= TAU * (1.0 - 1e-9) { + let q0 = quarter_of(a[0]); + return Some(((q0, 4), [q0, q0 + 4.0])); + } + let grid = quarters(a, reach)?; + Some((grid, params(a, grid))) +} + +/// The form parameters of an angle interval on the quarters `quarters` chose for it (its ends kept +/// on them: an end within rounding past a quarter's end stays in that quarter). +fn params([a0, a1]: [f64; 2], (q0, n): (f64, usize)) -> [f64; 2] { + let end = q0 + n as f64; + [param(a0).clamp(q0, end), param(a1).clamp(q0, end)] +} + +/// Equal arcs from angle `a0` to `a1` (less than a turn), as few as keep each within a quarter: +/// their knot vector (0 at `a0`, one more at each arc's end) and control points (as +/// [`arcs`]). A form on them is not on the quarter grid: for a face whose angle range needs the +/// four quarters of a turn (or five) without being a turn, which on the grid would be a form that +/// closes on itself (or overlaps itself) around a face that does not. +fn arcs_between(a0: f64, a1: f64) -> Option<(Vec, Vec<([f64; 2], f64)>)> { + let span = a1 - a0; + if !(a0.is_finite() && span > 0.0 && span < TAU) { + return None; + } + let n = ((span / FRAC_PI_2) - 1e-9).ceil().max(1.0) as usize; + let phi = span / n as f64; + let w = (0.5 * phi).cos(); + let at = |a: f64| [a.cos(), a.sin()]; + let mut pts = Vec::with_capacity(2 * n + 1); + let mut knots = vec![0.0; 3]; + for k in 0..n { + let start = a0 + phi * k as f64; + if k == 0 { + pts.push((at(start), 1.0)); + } + let mid = at(start + 0.5 * phi); + pts.push(([mid[0] / w, mid[1] / w], w)); + pts.push((at(start + phi), 1.0)); + let end = (k + 1) as f64; + knots.extend(if k + 1 < n { vec![end; 2] } else { vec![end; 3] }); + } + Some((knots, pts)) +} + +/// The arcs of a face's angle range `a` and its domain on them: the quarter grid's +/// ([`face_quarters`]), or with `own` and a range short of a turn, arcs of its own from its start +/// ([`arcs_between`], the domain all of them). +fn face_arcs(a: [f64; 2], reach: f64, own: bool) -> Option<((Vec, Vec<([f64; 2], f64)>), [f64; 2])> { + if own && a[1] - a[0] < TAU * (1.0 - 1e-9) { + // Past each end by `reach` (while that stays short of a turn): the face's boundary, which + // lies off the surface by as much, then stays on the form. + let pad = reach.max(0.0).min(0.25 * (TAU * (1.0 - 1e-9) - (a[1] - a[0]))); + let (a0, a1) = (a[0] - pad, a[1] + pad); + let made = arcs_between(a0, a1)?; + let n = made.0.last().copied()?; + let phi = (a1 - a0) / n; + // The form parameter at angle `t`: its arc, plus the arc's own parameter there (as + // `quarter_u`, for an arc of `phi`). + let at = |t: f64| { + let k = ((t - a0) / phi).floor().clamp(0.0, n - 1.0); + let psi = (t - a0 - k * phi).clamp(0.0, phi); + k + 0.5 * (1.0 + (0.5 * psi - 0.25 * phi).tan() / (0.25 * phi).tan()) + }; + return Some((made, [at(a[0]), at(a[1])])); + } + let (grid, d) = face_quarters(a, reach)?; + Some((arcs(grid.0, grid.1), d)) +} + +/// Quarter arcs from quarter `q0`, `n` of them: their knot vector (in form parameter) and their +/// control points (as `(cos, sin)` factors on the unit circle's plane) with weights. +fn arcs(q0: f64, n: usize) -> (Vec, Vec<([f64; 2], f64)>) { + let at = |a: f64| [a.cos(), a.sin()]; + let mut pts = Vec::with_capacity(2 * n + 1); + let mut knots = vec![q0; 3]; + for k in 0..n { + let q = q0 + k as f64; + let (p, r) = (at(q * FRAC_PI_2), at((q + 1.0) * FRAC_PI_2)); + if k == 0 { + pts.push((p, 1.0)); + } + pts.push(([p[0] + r[0], p[1] + r[1]], FRAC_1_SQRT_2)); + pts.push((r, 1.0)); + knots.extend(if k + 1 < n { vec![q + 1.0; 2] } else { vec![q + 1.0; 3] }); + } + (knots, pts) +} + +fn v3(a: [f64; 3]) -> Vec3 { + Vec3::new(a[0], a[1], a[2]) +} + +fn hom(p: Vec3, w: f64) -> [f64; 4] { + [p.x * w, p.y * w, p.z * w, w] +} + +/// The frame's origin and unit axes (z = x × y). +fn axes(f: &Frame) -> Option<(Vec3, Vec3, Vec3, Vec3)> { + let (x, y) = (v3(f.x_axis).normalized()?, v3(f.y_axis).normalized()?); + Some((v3(f.origin), x, y, x.cross(y).normalized()?)) +} + +/// The NURBS form of a line, circle or ellipse edge and its interval in the form's parameter; +/// `None` for another kind, or an arc of more than one turn. +pub fn curve(c: &Curve, [t0, t1]: [f64; 2]) -> Option<(Curve, [f64; 2])> { + match c { + Curve::Line { start, end } => { + let (a, d) = (v3(*start), v3(*end) - v3(*start)); + let (p0, p1) = (a + d * t0, a + d * t1); + Some((Curve::Spline { knots: vec![t0, t0, t1, t1], points: vec![[p0.x, p0.y, p0.z], [p1.x, p1.y, p1.z]] }, [t0, t1])) + } + Curve::Circle { frame, radius } => conic(frame, [*radius; 2], [t0, t1]), + Curve::Ellipse { frame, radii } => conic(frame, *radii, [t0, t1]), + _ => None, + } +} + +fn conic(frame: &Frame, [rx, ry]: [f64; 2], t: [f64; 2]) -> Option<(Curve, [f64; 2])> { + let (o, x, y, _) = axes(frame)?; + let grid = quarters(t, 0.0)?; + let (knots, pts) = arcs(grid.0, grid.1); + let homogeneous = pts.iter().map(|([c, s], w)| hom(o + x * (rx * c) + y * (ry * s), *w)).collect(); + Some((Curve::RationalSpline { knots, homogeneous }, params(t, grid))) +} + +/// The NURBS form of a cylinder, cone, sphere or torus face over `domain` (in the label's +/// parameters: angles, and the height along the axis of a cylinder or cone) and the domain in the +/// form's parameters; `None` for another kind, or a domain of more than one turn. +pub fn surface(s: &Surface, domain: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2]; 2])> { + surface_within(s, domain, 0.0) +} + +/// The angles `tolerance` (mm) makes along a face's two directions ([`surface_within`]): on the +/// widest circle of the face about the axis (over `v`, the height of a cylinder or cone), and on +/// a sphere's meridian or a torus's tube. +fn reaches(s: &Surface, v: [f64; 2], tolerance: f64) -> (f64, f64) { + // The angle `tolerance` makes on a circle of `radius`. + let reach = |radius: f64| if tolerance > 0.0 && radius > 0.0 && radius.is_finite() { tolerance / radius } else { 0.0 }; + match s { + Surface::Cylinder { radius, .. } => (reach(radius.abs()), 0.0), + Surface::Cone { radius_at_origin, half_angle, .. } => { + let slope = half_angle.tan(); + (reach(v.iter().map(|h| (radius_at_origin + h * slope).abs()).fold(0.0, f64::max)), 0.0) + } + Surface::Sphere { radius, .. } => (reach(radius.abs()), reach(radius.abs())), + Surface::Torus { major_radius, minor_radius, .. } => (reach(major_radius.abs() + minor_radius.abs()), reach(minor_radius.abs())), + _ => (0.0, 0.0), + } +} + +/// How many quarters a cylinder, cone, sphere or torus face over `[u, v]` (its box on the label, +/// as for [`surface_within`]) spans about the axis on its frame's quarter grid: five when the face +/// does not start on a quarter line and more than three quarters are left to it. A face of less +/// than one turn then has a form past one turn (a NURBS that covers part of its surface twice); a +/// whole turn has a form of four quarters from the one it starts in, which ends short of the +/// face's seam, so the seam's second use lies off the form. [`turned`] puts its start on a quarter +/// line. `None` for another surface. +pub fn turn_quarters(s: &Surface, [u, v]: [[f64; 2]; 2], tolerance: f64) -> Option { + if !matches!(s, Surface::Cylinder { .. } | Surface::Cone { .. } | Surface::Sphere { .. } | Surface::Torus { .. }) { + return None; + } + Some(quarters(u, reaches(s, v, tolerance).0)?.1) +} + +/// A cylinder, cone, sphere or torus with its frame turned by `angle` about its own axis (its x +/// and y axes turned right-handed about z): the same surface, its angle parameter `angle` less at +/// every point. `None` for another surface. +pub fn turned(s: &Surface, angle: f64) -> Option { + let turn = |f: &Frame| -> Option { + let (o, x, _, z) = axes(f)?; + let (sin, cos) = angle.sin_cos(); + let nx = x * cos + z.cross(x) * sin; + let ny = z.cross(nx); + Some(Frame { origin: [o.x, o.y, o.z], x_axis: [nx.x, nx.y, nx.z], y_axis: [ny.x, ny.y, ny.z] }) + }; + Some(match s { + Surface::Cylinder { frame, radius } => Surface::Cylinder { frame: turn(frame)?, radius: *radius }, + Surface::Cone { frame, radius_at_origin, half_angle } => { + Surface::Cone { frame: turn(frame)?, radius_at_origin: *radius_at_origin, half_angle: *half_angle } + } + Surface::Sphere { frame, radius } => Surface::Sphere { frame: turn(frame)?, radius: *radius }, + Surface::Torus { frame, major_radius, minor_radius, tube_start } => { + Surface::Torus { frame: turn(frame)?, major_radius: *major_radius, minor_radius: *minor_radius, tube_start: *tube_start } + } + _ => return None, + }) +} + +/// How many quarters a torus face over `[u, v]` (its box on the label, as for +/// [`surface_within`]) spans along its tube on the label's quarter grid ([`turn_quarters`] for +/// the tube angle): five when the face does not start on a quarter line of the tube and more +/// than three quarters are left to it. [`tube_turned`] puts its start on one. `None` for another +/// surface. +pub fn tube_quarters(s: &Surface, [_, v]: [[f64; 2]; 2], tolerance: f64) -> Option { + if !matches!(s, Surface::Torus { .. }) { + return None; + } + Some(face_quarters(v, reaches(s, v, tolerance).1)?.0.1) +} + +/// A torus with its tube start moved on by `angle`: the same surface, its tube angle parameter +/// `angle` less at every point. `None` for another surface. +pub fn tube_turned(s: &Surface, angle: f64) -> Option { + let Surface::Torus { frame, major_radius, minor_radius, tube_start } = s else { return None }; + // Kept within one turn either way, as a record's tube start is. + let start = tube_start + angle; + let start = if start.abs() > TAU { start % TAU } else { start }; + Some(Surface::Torus { frame: frame.clone(), major_radius: *major_radius, minor_radius: *minor_radius, tube_start: start }) +} + +/// [`surface`] for a face whose boundary lies within `tolerance` (mm) of its surface: where the +/// domain ends within `tolerance` of a quarter's end (the angle that far along the widest circle +/// of the face in that direction), the form ends there too. A face's box is the extent of its +/// boundary's points ([`extent`]), which may run past a quarter's end by as much as its edges lie +/// off the surface; the form then covers no quarter for that alone (a torus face of half a tube +/// would otherwise go round the whole tube). +pub fn surface_within(s: &Surface, domain: [[f64; 2]; 2], tolerance: f64) -> Option<(Surface, [[f64; 2]; 2])> { + surface_on(s, domain, tolerance, false) +} + +/// The NURBS form of a cylinder, cone, sphere or torus face over `domain` (as [`surface`]) whose +/// angles run on arcs of the face's own from where it starts, not on its frame's quarter grid, +/// wherever its range is short of a turn: the same surface, exactly, but a form that never +/// closes on itself around a face that does not (a torus face round 250° of its tube needs all +/// four quarters of the grid, a form SMLib does not take for a torus); each angle runs past the +/// face's ends by the angle `tolerance` (mm) makes, so a boundary that far off stays on the +/// form. Its circles' forms then no +/// longer share its parameter, so its pcurves are not lines: Repair Part rebuilds a refused face +/// on it and has SMLib make them. +pub fn surface_on_own_arcs(s: &Surface, domain: [[f64; 2]; 2], tolerance: f64) -> Option<(Surface, [[f64; 2]; 2])> { + match s { + Surface::Cylinder { .. } | Surface::Cone { .. } | Surface::Sphere { .. } | Surface::Torus { .. } => surface_on(s, domain, tolerance, true), + _ => None, + } +} + +fn surface_on(s: &Surface, [u, v]: [[f64; 2]; 2], tolerance: f64, own: bool) -> Option<(Surface, [[f64; 2]; 2])> { + let (reach_u, reach_v) = reaches(s, v, tolerance); + let ((u_knots, ring), fu) = face_arcs(u, reach_u, own)?; + // The ring of arcs times a profile `(control, weight)` mapped to (radial, axial) about the + // frame: a rational tensor product, its weights the products. + let net = |f: &Frame, profile: &[([f64; 2], f64)], at: &dyn Fn([f64; 2]) -> (f64, f64)| -> Option>> { + let (o, x, y, z) = axes(f)?; + Some( + ring.iter() + .map(|([c, s], wu)| { + let r = x * *c + y * *s; + profile + .iter() + .map(|(q, wv)| { + let (radial, axial) = at(*q); + hom(o + r * radial + z * axial, wu * wv) + }) + .collect() + }) + .collect(), + ) + }; + let line = [([v[0], 0.0], 1.0), ([v[1], 0.0], 1.0)]; + match s { + Surface::Cylinder { frame, radius } => { + let homogeneous = net(frame, &line, &|[h, _]| (*radius, h))?; + Some((Surface::RationalSpline { u_knots, v_knots: vec![v[0], v[0], v[1], v[1]], homogeneous }, [fu, v])) + } + Surface::Cone { frame, radius_at_origin, half_angle } => { + let slope = half_angle.tan(); + let homogeneous = net(frame, &line, &|[h, _]| (radius_at_origin + h * slope, h))?; + Some((Surface::RationalSpline { u_knots, v_knots: vec![v[0], v[0], v[1], v[1]], homogeneous }, [fu, v])) + } + Surface::Sphere { frame, radius } => { + let vgrid = quarters(v, reach_v)?; + let (v_knots, meridian) = arcs(vgrid.0, vgrid.1); + let homogeneous = net(frame, &meridian, &|[c, s]| (radius * c, radius * s))?; + Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, params(v, vgrid)])) + } + Surface::Torus { frame, major_radius, minor_radius, tube_start } => { + let ((v_knots, tube), fv) = face_arcs(v, reach_v, own)?; + // The tube's arcs turned on by its start (a rotation of the control points, exact). + let (ts, tc) = tube_start.sin_cos(); + let homogeneous = net(frame, &tube, &|[c, s]| (major_radius + minor_radius * (c * tc - s * ts), minor_radius * (s * tc + c * ts)))?; + Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, fv])) + } + Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => { + // The profile's control points turned about the axis on the quarter grid from angle + // zero (the profile): (a + ib)(c + is) for each point's radial (a, b) in the frame and + // each arc control point (c, s), weights multiplied; then the matrix. + let (angles, along) = if *forward { (v, u) } else { (u, v) }; + let (ring_grid, fa) = face_quarters(angles, 0.0)?; + let (a_knots, arcs_r) = arcs(ring_grid.0, ring_grid.1); + let (p_knots, h) = profile_nurbs(profile, Some(along))?; + let fp = match profile.as_ref() { + Curve::Circle { .. } | Curve::Ellipse { .. } => curve(profile, along)?.1, + _ => along, + }; + let (o, x, y, k) = revolution_frame(&h, *origin, *axis)?; + let net: Vec> = arcs_r + .iter() + .map(|([c, s], wu)| { + h.iter() + .map(|hp| { + let d = Vec3::new(hp[0] / hp[3], hp[1] / hp[3], hp[2] / hp[3]) - o; + let (a, b, z) = (d.dot(x), d.dot(y), d.dot(k)); + let q = o + k * z + x * (a * c - b * s) + y * (a * s + b * c); + hom(affine(matrix, q), wu * hp[3]) + }) + .collect() + }) + .collect(); + if *forward { + // u the profile, v the angle: the net turned over. + let n = net.first()?.len(); + let t: Vec> = (0..n).map(|j| net.iter().filter_map(|r| r.get(j).copied()).collect()).collect(); + Some((Surface::RationalSpline { u_knots: p_knots, v_knots: a_knots, homogeneous: t }, [fp, fa])) + } else { + Some((Surface::RationalSpline { u_knots: a_knots, v_knots: p_knots, homogeneous: net }, [fa, fp])) + } + } + _ => None, + } +} + +/// A circle edge labelled on another frame about the same axis: the same circle, its angle +/// measured from `frame`'s x axis (its y axis taken so the circle keeps its own direction), and +/// its interval shifted to match, so its form lies on `frame`'s quarter grid. `None` when the +/// circle is not about `frame`'s axis (centre on it, normal along it, within `tol`). +pub fn on_frame(c: &Curve, [t0, t1]: [f64; 2], frame: &Frame, tol: f64) -> Option<(Curve, [f64; 2])> { + let Curve::Circle { frame: own, radius } = c else { return None }; + let (o, x, _, z) = axes(own)?; + let (fo, fx, _, fz) = axes(frame)?; + let d = o - fo; + if !((d - fz * d.dot(fz)).len() <= tol && (z.dot(fz).abs() - 1.0).abs() <= 1e-9) { + return None; + } + let nx = (fx - z * fx.dot(z)).normalized()?; + let ny = z.cross(nx); + let shift = x.dot(ny).atan2(x.dot(nx)); + let relabel = Frame { origin: [o.x, o.y, o.z], x_axis: [nx.x, nx.y, nx.z], y_axis: [ny.x, ny.y, ny.z] }; + Some((Curve::Circle { frame: relabel, radius: *radius }, [t0 + shift, t1 + shift])) +} + +/// A circle edge round a torus's tube (in a plane through the axis, centred on the ring, of the +/// tube's radius, all within `tol`): the same circle, its angle measured from the tube direction +/// at the torus's tube start (its y axis taken so the circle keeps its own direction), and its +/// interval shifted to match, so its form lies on the torus's quarter grid along the tube. `None` +/// for another circle or surface. +pub fn on_tube(c: &Curve, [t0, t1]: [f64; 2], torus: &Surface, tol: f64) -> Option<(Curve, [f64; 2])> { + let (Curve::Circle { frame: own, radius }, Surface::Torus { frame, major_radius, minor_radius, tube_start }) = (c, torus) else { + return None; + }; + let (o, x, _, z) = axes(own)?; + let (fo, _, _, fz) = axes(frame)?; + // The ring's direction at the circle's centre, and the centre on the ring. + let d = o - fo; + let radial = (d - fz * d.dot(fz)).normalized()?; + let on_ring = (o - (fo + radial * *major_radius)).len() <= tol; + if !(on_ring && (radius - minor_radius).abs() <= tol && z.dot(fz).abs() <= 1e-9 && z.dot(radial).abs() <= 1e-9) { + return None; + } + let (s, cs) = tube_start.sin_cos(); + let nx = (radial * cs + fz * s).normalized()?; + let ny = z.cross(nx); + let shift = x.dot(ny).atan2(x.dot(nx)); + let relabel = Frame { origin: [o.x, o.y, o.z], x_axis: [nx.x, nx.y, nx.z], y_axis: [ny.x, ny.y, ny.z] }; + Some((Curve::Circle { frame: relabel, radius: *radius }, [t0 + shift, t1 + shift])) +} + +/// Whether a circle round a torus's tube that is about `frame`'s axis (within `tol`) has one +/// quarter grid on both: its angle from `frame` ([`on_frame`]) and from the tube start +/// ([`on_tube`]) differ by whole quarters to rounding, so its form and both faces' lie on one +/// grid. `None` when it is not such a circle. +pub fn tube_on_grid(c: &Curve, interval: [f64; 2], frame: &Frame, torus: &Surface, tol: f64) -> Option { + let (Curve::Circle { frame: a, .. }, _) = on_frame(c, interval, frame, tol)? else { return None }; + let (Curve::Circle { frame: b, .. }, _) = on_tube(c, interval, torus, tol)? else { return None }; + let (_, ax, _, _) = axes(&a)?; + let (_, bx, by, _) = axes(&b)?; + let turn = ax.dot(by).atan2(ax.dot(bx)); + let off = turn - (turn / FRAC_PI_2).round() * FRAC_PI_2; + Some(off.abs() <= 1e-9) +} + +/// The frame of a cylinder, cone, sphere or torus, or of a placed revolution (its axis, angle +/// zero at its profile: [`revolution_frame`]); `None` for another surface. +pub fn frame_of(s: &Surface) -> Option { + match s { + Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } | Surface::Sphere { frame, .. } | Surface::Torus { frame, .. } => { + Some(frame.clone()) + } + Surface::PlacedRevolution { profile, origin, axis, matrix, .. } => { + let (_, h) = profile_nurbs(profile, None)?; + let (o, x, y, _) = revolution_frame(&h, *origin, *axis)?; + let m = |p: Vec3| affine(matrix, p); + let (mo, mx, my) = (m(o), m(o + x) - m(o), m(o + y) - m(o)); + Some(Frame { origin: [mo.x, mo.y, mo.z], x_axis: [mx.x, mx.y, mx.z], y_axis: [my.x, my.y, my.z] }) + } + _ => None, + } +} + +/// `matrix` (column-major, `matrix[column][row]`) applied to `p`. +fn affine(matrix: &[[f64; 4]; 4], p: Vec3) -> Vec3 { + let row = |r: usize| matrix[0][r] * p.x + matrix[1][r] * p.y + matrix[2][r] * p.z + matrix[3][r]; + Vec3::new(row(0), row(1), row(2)) +} + +/// A revolution's profile as a NURBS: its knots and homogeneous control points (a B-spline or +/// NURBS as it is, a line or conic as its form over `range`; `None` without a range). +fn profile_nurbs(profile: &Curve, range: Option<[f64; 2]>) -> Option<(Vec, Vec<[f64; 4]>)> { + let formed; + let c = match profile { + Curve::Spline { .. } | Curve::RationalSpline { .. } => profile, + other => { + formed = curve(other, range?)?.0; + &formed + } + }; + match c { + Curve::Spline { knots, points } => Some((knots.clone(), points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect())), + Curve::RationalSpline { knots, homogeneous } => Some((knots.clone(), homogeneous.clone())), + _ => None, + } +} + +/// A revolution's frame: the origin and unit axis, x the radial direction of the profile's +/// first control point off the axis (angle zero), y = axis × x. +fn revolution_frame(h: &[[f64; 4]], origin: [f64; 3], axis: [f64; 3]) -> Option<(Vec3, Vec3, Vec3, Vec3)> { + let (o, k) = (v3(origin), v3(axis).normalized()?); + let x = h.iter().find_map(|h| { + let d = Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]) - o; + let r = d - k * d.dot(k); + if r.len() > 1e-12 * (1.0 + d.len()) { r.normalized() } else { None } + })?; + Some((o, x, k.cross(x), k)) +} + +/// An edge's label and NURBS form: a circle about the axis of one of `frames` (the cylinder, +/// cone, sphere and torus faces it bounds) is labelled on that frame ([`on_frame`]), so its form +/// lies on that face's quarter grid; a circle or ellipse then has its form ([`curve`]). The label +/// with its interval, and the form with its own; `None` for an arc of more than one turn. +pub fn edge<'a>( + c: &Curve, + interval: [f64; 2], + frames: impl IntoIterator, + tol: f64, +) -> Option<(Curve, [f64; 2], Option<(Curve, [f64; 2])>)> { + edge_on(c, interval, frames, &[], tol) +} + +/// [`edge`], with the torus faces the edge bounds: a circle round one of their tubes that is +/// about none of `frames`' axes is labelled from that torus's tube start ([`on_tube`]), so its +/// form lies on the face's quarter grid along the tube. +pub fn edge_on<'a>( + c: &Curve, + interval: [f64; 2], + frames: impl IntoIterator, + tori: &[Surface], + tol: f64, +) -> Option<(Curve, [f64; 2], Option<(Curve, [f64; 2])>)> { + let (label, iv) = frames + .into_iter() + .find_map(|f| on_frame(c, interval, f, tol)) + .or_else(|| tori.iter().find_map(|t| on_tube(c, interval, t, tol))) + .unwrap_or_else(|| (c.clone(), interval)); + let form = match label { + Curve::Circle { .. } | Curve::Ellipse { .. } => Some(curve(&label, iv)?), + _ => None, + }; + Some((label, iv, form)) +} + +/// Points per edge along a loop taken for a face's extent. +const EXTENT_POINTS: usize = 32; + +/// The largest value of `f` on `[a, b]`, where it rises to one peak and falls (golden section, to +/// rounding; the ends count). +fn golden_max(f: &dyn Fn(f64) -> f64, a: f64, b: f64) -> f64 { + const R: f64 = 0.618_033_988_749_894_8; + let (mut a, mut b) = (a, b); + let best = f(a).max(f(b)); + let (mut c, mut d) = (b - R * (b - a), a + R * (b - a)); + let (mut fc, mut fd) = (f(c), f(d)); + while b - a > 1e-15 * (1.0 + a.abs().max(b.abs())) { + if fc >= fd { + b = d; + d = c; + fd = fc; + c = b - R * (b - a); + fc = f(c); + } else { + a = c; + c = d; + fc = fd; + d = a + R * (b - a); + fd = f(d); + } + } + best.max(fc).max(fd) +} + +/// The parameter box of a face on `label` over its boundary: each loop's points (`loops`, in +/// order along each loop) projected onto the label, a periodic parameter unwrapped from one point +/// to the next, and each loop after the first a whole number of periods along where that keeps +/// the box smallest. What the face's NURBS form ([`surface`]) is built over; no pcurve is +/// involved. +pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Option<[[f64; 2]; 2]> { + let eval = super::eval::SurfaceEval::new(label).ok()?; + let period = eval.domain().period; + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for l in loops { + // A loop is unwrapped from its own first point, so it can come out whole periods away + // from the loops before it (a hole beside the seam projects to the seam's other side), + // and a box over both is more than a turn wide. + let (mut l_lo, mut l_hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + let mut prev: Option<[f64; 2]> = None; + // The loop's bounds in each direction, each with the number of poles the loop had passed + // through when it got there; and the first and last points off a pole. + let mut bounds: Vec<(usize, usize, f64)> = Vec::new(); + let (mut crossings, mut on_pole) = (0usize, false); + let mut first: Option<[f64; 2]> = None; + for (c, [t0, t1], forward) in l { + let curve = super::eval::CurveEval::new(c).ok()?; + // The point at `t` on the label, a periodic parameter unwrapped next to `near`. + let at = |t: f64, near: Option<[f64; 2]>| -> Option<[f64; 2]> { + let mut q = eval.project(curve.point(t)?, near, f64::INFINITY)?; + if let Some(p) = near { + for d in 0..2 { + if let Some(Some(per)) = period.get(d) { + q[d] += ((p[d] - q[d]) / per).round() * per; + } + } + } + Some(q) + }; + let mut samples: Vec<(f64, [f64; 2], [bool; 2], usize)> = Vec::with_capacity(EXTENT_POINTS + 1); + for k in 0..=EXTENT_POINTS { + let f = k as f64 / EXTENT_POINTS as f64; + let t = if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f }; + let q = at(t, prev)?; + // At a pole the collapsed parameter is anything: it bounds nothing. + let pole = eval.pole(q); + if pole.iter().any(|p| *p) { + on_pole = first.is_some(); + } else { + if on_pole { + crossings += 1; + on_pole = false; + } + first = first.or(Some(q)); + prev = Some(q); + } + for (d, x) in q.iter().enumerate() { + if !pole.get(d).copied().unwrap_or(false) { + bounds.push((crossings, d, *x)); + } + } + samples.push((t, q, pole, crossings)); + } + // A sample is a point of the boundary, not its extreme: each sample higher (or lower) + // than its neighbours brackets an extreme of the edge, which is found there. + for k in 0..samples.len() { + let (_, q, pole, passed) = samples[k]; + let (a, b) = (samples[k.saturating_sub(1)].0, samples[(k + 1).min(samples.len() - 1)].0); + for d in 0..2 { + // Next to a pole the parameter it collapses is no function of the point: a + // meridian's angle there is rounding, not an extreme. + let near_pole = |j: Option| j.and_then(|j| samples.get(j)).is_some_and(|s| s.2[d]); + if pole[d] || near_pole(k.checked_sub(1)) || near_pole(Some(k + 1)) { + continue; + } + let side = |j: usize| samples.get(j).map(|s| s.1[d]); + let (before, after) = (if k > 0 { side(k - 1) } else { None }, side(k + 1)); + for sign in [1.0, -1.0] { + // Not lower than either neighbour and higher than one (a level run, a + // seam's constant angle, has no extreme between its samples). + let higher = |x: Option| x.is_none_or(|x| sign * q[d] >= sign * x); + let above = |x: Option| x.is_some_and(|x| sign * q[d] > sign * x); + if !(higher(before) && higher(after) && (above(before) || above(after))) { + continue; + } + let f = |t: f64| at(t, Some(q)).map_or(f64::NEG_INFINITY, |p| sign * p[d]); + let x = sign * golden_max(&f, a.min(b), a.max(b)); + bounds.push((passed, d, x)); + } + } + } + } + // Through a pole the loop goes on from anywhere round the periodic direction it + // collapses, so continuing from the point before it is no measure of where: a loop + // through a pole closes in (u, v), the pole taking up its turn (a hemisphere bounded by its + // rim and its seam, down the seam to the pole and up it on the other side). Past the + // first pole, the loop is moved the whole periods that close it. + let last = prev; + for d in 0..2 { + let shift = match (period.get(d), first, last) { + (Some(Some(per)), Some(f), Some(e)) if crossings > 0 => -((e[d] - f[d]) / per).round() * per, + _ => 0.0, + }; + for &(passed, dd, x) in &bounds { + if dd == d { + let x = if passed > 0 { x + shift } else { x }; + l_lo[d] = l_lo[d].min(x); + l_hi[d] = l_hi[d].max(x); + } + } + } + for d in 0..2 { + if !(l_lo[d] <= l_hi[d]) { + continue; + } + let shift = match period.get(d) { + Some(Some(per)) if lo[d] <= hi[d] => { + // The whole periods around the ones that bring the loop's middle to the box's, + // the one giving the smallest box. + let k = ((lo[d] + hi[d] - l_lo[d] - l_hi[d]) / (2.0 * per)).round(); + let span = |k: f64| hi[d].max(l_hi[d] + k * per) - lo[d].min(l_lo[d] + k * per); + [k, k - 1.0, k + 1.0].into_iter().min_by(|a, b| span(*a).total_cmp(&span(*b))).unwrap_or(k) * per + } + _ => 0.0, + }; + lo[d] = lo[d].min(l_lo[d] + shift); + hi[d] = hi[d].max(l_hi[d] + shift); + } + } + // At most one turn round a periodic direction; a boundary that never goes round it (a face + // bounded by its seam alone) covers the whole turn from there. + for d in 0..2 { + if let Some(Some(per)) = period.get(d) { + hi[d] = if hi[d] - lo[d] <= 1e-9 * per { lo[d] + per } else { hi[d].min(lo[d] + per) }; + } + } + (lo[0] < hi[0] && lo[1] < hi[1]).then_some([[lo[0], hi[0]], [lo[1], hi[1]]]) +} diff --git a/crates/geom/src/brep/geometry.rs b/crates/geom/src/brep/geometry.rs new file mode 100644 index 000000000..da2cb58bc --- /dev/null +++ b/crates/geom/src/brep/geometry.rs @@ -0,0 +1,236 @@ +//! Geometric agreement of a record (docs/native-brep.md, "Validation and trust"): what a kernel +//! assumes when it builds topology from the records without checking them itself. Each edge's +//! curve meets its vertices at its interval's ends; each oriented edge's pcurve, lifted through +//! its face's surface, lies on the edge's curve at the interval's ends and middle, and continues +//! the use before it without jumping a period; each edge loop's pcurves enclose (u, v) area, +//! one loop of each face counter-clockwise about the natural normal (the outer) and the rest +//! clockwise; each vertex loop's vertex lies on its surface. +//! +//! A spot check, not a certificate: a fixed number of evaluations per record (three points of +//! each edge, [`AREA_SAMPLES`] of each use, one projection per vertex loop), so the work is +//! linear in the record. Every distance is held to the record's own tolerance: +//! an edge's for its pcurves, an edge's and its vertex's together where they meet, a vertex's on +//! its surface. A point that cannot be evaluated is an error, never a panic. +use super::eval::{CurveEval, SurfaceEval}; +use crate::prelude::*; +use solidcore_record::Vec3; +use solidcore_record::brep::{Brep, Curve2, Loop}; + +/// Where a record disagrees with itself. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Record { + /// `edges[edge]`. + Edge(u32), + /// `faces[face]`. + Face(u32), + /// `faces[face].loops[loop].edges[position]`. + Use { face: u32, r#loop: u32, position: u32 }, + /// `faces[face].loops[loop]`, a vertex loop. + VertexLoop { face: u32, r#loop: u32 }, + /// `faces[face].loops[loop]`, an edge loop. + Loop { face: u32, r#loop: u32 }, +} + +impl std::fmt::Display for Record { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Record::Edge(e) => write!(f, "edge {e}"), + Record::Face(i) => write!(f, "face {i}"), + Record::Use { face, r#loop, position } => write!(f, "face {face} loop {loop} use {position}"), + Record::VertexLoop { face, r#loop } | Record::Loop { face, r#loop } => write!(f, "face {face} loop {loop}"), + } + } +} + +/// What disagrees. +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +pub enum Problem { + /// Two points that should coincide are `gap` mm apart, more than `tolerance`. + #[error("{what} by {gap} mm (tolerance {tolerance} mm)")] + Off { what: &'static str, gap: f64, tolerance: f64 }, + /// A pcurve starts `gap` in a periodic parameter from where the use before it ends: on + /// another period. + #[error("pcurve starts {gap} from the end of the use before it, on another period (period {period})")] + Period { gap: f64, period: f64 }, + /// An edge loop's pcurves enclose no (u, v) area, within rounding of the loop's size: its + /// face has no surface to it (a seam's two uses on one parameter line). + #[error("loop encloses no (u, v) area (signed area {area})")] + Empty { area: f64 }, + /// An edge loop runs the wrong way round in (u, v), seen from the surface's natural normal: + /// no loop of the face runs counter-clockwise (`outer`: the largest runs clockwise), or a + /// second one does (an inner loop, the smaller of them). + #[error("{} loop runs {} in (u, v) (signed area {area})", if *outer { "outer" } else { "inner" }, if *outer { "clockwise" } else { "counter-clockwise" })] + Turn { outer: bool, area: f64 }, + /// A point of the record cannot be evaluated (an unsupported kind, a non-finite value). + #[error("{0}")] + Unevaluable(String), +} + +/// A record whose geometry disagrees with its topology, and where. +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[error("portable B-rep: {record}: {problem}")] +pub struct Mismatch { + pub record: Record, + pub problem: Problem, +} + +type Result = std::result::Result; + +fn index(i: usize) -> u32 { + u32::try_from(i).unwrap_or(u32::MAX) +} +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} +fn unevaluable(record: Record, what: impl std::fmt::Display) -> Mismatch { + Mismatch { record, problem: Problem::Unevaluable(what.to_string()) } +} +/// A use's pcurve at its edge's parameter `t`. The pcurve's interval is its edge's to within +/// rounding ([`Brep::validate`], `PCURVE_INTERVAL`), so an edge parameter just past it is read at +/// the pcurve's end. +fn on_pcurve(pc: &Curve2, t: f64) -> Option<[f64; 2]> { + let [a, b] = pc.interval()?; + super::pcurve::eval(pc, t.clamp(a.min(b), a.max(b))) +} + +/// `gap` within `tolerance` (a non-finite gap never is). +fn within(record: Record, what: &'static str, gap: f64, tolerance: f64) -> Result<()> { + if gap <= tolerance { Ok(()) } else { Err(Mismatch { record, problem: Problem::Off { what, gap, tolerance } }) } +} + +/// Points of each use's pcurve that its loop's (u, v) area is taken over. +pub const AREA_SAMPLES: usize = 16; +/// Signed area this small against the square of the loop's (u, v) extent is none. +const EMPTY_AREA: f64 = 1e-9; + +const PCURVE_POINTS: [&str; 3] = + ["pcurve start lifts off its edge's curve", "pcurve middle lifts off its edge's curve", "pcurve end lifts off its edge's curve"]; + +/// Check that the record's geometry agrees with its topology, within its tolerances (module +/// docs). Call on a record [`Brep::validate`] accepted: this checks geometry, not structure, +/// though a malformed record is refused, never a panic. +pub fn check(brep: &Brep) -> Result<()> { + // Each edge's curve at its interval's start, middle and end, shared by all its uses. + let mut points = Vec::with_capacity(brep.edges.len()); + for (i, e) in brep.edges.iter().enumerate() { + let at = Record::Edge(index(i)); + let curve = CurveEval::new(e.parameters()).map_err(|err| unevaluable(at, err))?; + let [t0, t1] = e.interval; + let p = [t0, 0.5 * (t0 + t1), t1].map(|t| curve.point(t).ok_or(t)); + let p = match p { + [Ok(a), Ok(m), Ok(z)] => [a, m, z], + [Err(t), ..] | [_, Err(t), _] | [.., Err(t)] => return Err(unevaluable(at, format!("the curve has no point at {t}"))), + }; + for (end, what) in [(0, "curve start misses its start vertex"), (1, "curve end misses its end vertex")] { + let v = e.vertices.get(end).and_then(|&v| brep.vertices.get(v as usize)).ok_or_else(|| unevaluable(at, "edge vertices"))?; + let q = if end == 0 { p[0] } else { p[2] }; + within(at, what, q.dist(v3(v.point)), v.tolerance + e.tolerance)?; + } + points.push(p); + } + for (fi, f) in brep.faces.iter().enumerate() { + let face = index(fi); + let surface = SurfaceEval::new(f.parameters()).map_err(|err| unevaluable(Record::Face(face), err))?; + let period = surface.domain().period; + // Each edge loop's signed (u, v) area. + let mut areas: Vec<(u32, f64)> = Vec::with_capacity(f.loops.len()); + for (li, l) in f.loops.iter().enumerate() { + let r#loop = index(li); + match l { + Loop::Vertex { vertex } => { + let at = Record::VertexLoop { face, r#loop }; + let v = brep.vertices.get(*vertex as usize).ok_or_else(|| unevaluable(at, "vertex reference"))?; + let p = v3(v.point); + let on = surface.project(p, None, f64::INFINITY).and_then(|q| surface.point(q)); + let gap = on.map_or(f64::INFINITY, |s| s.dist(p)); + within(at, "vertex lies off its face's surface", gap, v.tolerance)?; + } + Loop::Edges { edges } => { + // Where each use starts and ends in (u, v), in the loop's direction. + let mut ends: Vec<[[f64; 2]; 2]> = Vec::with_capacity(edges.len()); + for (position, u) in edges.iter().enumerate() { + let at = Record::Use { face, r#loop, position: index(position) }; + let i = u.edge as usize; + let (e, p) = brep.edges.get(i).zip(points.get(i)).ok_or_else(|| unevaluable(at, "edge reference"))?; + let [t0, t1] = e.interval; + let mut uv = [[0.0; 2]; 3]; + for (k, t) in [t0, 0.5 * (t0 + t1), t1].into_iter().enumerate() { + let q = on_pcurve(&u.pcurve, t).ok_or_else(|| unevaluable(at, format!("the pcurve has no point at {t}")))?; + let s = surface.point(q).ok_or_else(|| unevaluable(at, format!("the surface has no point at {q:?}")))?; + let (Some(c), Some(what), Some(slot)) = (p.get(k), PCURVE_POINTS.get(k), uv.get_mut(k)) else { + return Err(unevaluable(at, "pcurve sample")); + }; + within(at, what, s.dist(*c), e.tolerance)?; + *slot = q; + } + ends.push(if u.forward { [uv[0], uv[2]] } else { [uv[2], uv[0]] }); + } + // Each use continues the one before it (the last closes the loop), except + // along a direction that collapses there (a pole): at the vertex where + // they meet, to within the vertex's tolerance. + for (position, pair) in ends.iter().enumerate() { + let before = ends.get(position.checked_sub(1).unwrap_or(ends.len().saturating_sub(1))); + let (Some([_, end]), [start, _]) = (before, pair) else { continue }; + let reach = edges + .get(position) + .and_then(|u| brep.edges.get(u.edge as usize).map(|e| e.vertices[if u.forward { 0 } else { 1 }])) + .and_then(|v| brep.vertices.get(v as usize)) + .map_or(0.0, |v| v.tolerance); + let pole = surface.pole_within(*start, reach); + for d in 0..2 { + let (Some(Some(p)), Some(false)) = (period.get(d), pole.get(d)) else { continue }; + let gap = (start[d] - end[d]).abs(); + if !(gap < 0.5 * p) { + let record = Record::Use { face, r#loop, position: index(position) }; + return Err(Mismatch { record, problem: Problem::Period { gap, period: *p } }); + } + } + } + // The signed area the loop encloses (positive for the outer loop). Where + // uses meet at a pole the ring runs straight along the pole's line. + let at = Record::Loop { face, r#loop }; + let mut ring: Vec<[f64; 2]> = Vec::with_capacity(edges.len().saturating_mul(AREA_SAMPLES)); + for u in edges { + let [t0, t1] = brep.edges.get(u.edge as usize).ok_or_else(|| unevaluable(at, "edge reference"))?.interval; + for k in 0..AREA_SAMPLES { + let f = k as f64 / AREA_SAMPLES as f64; + let t = if u.forward { t0 + (t1 - t0) * f } else { t1 - (t1 - t0) * f }; + ring.push(on_pcurve(&u.pcurve, t).ok_or_else(|| unevaluable(at, format!("the pcurve has no point at {t}")))?); + } + } + let area = signed_area(&ring); + let extent = (0..2) + .map(|d| { + let (lo, hi) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d]))); + hi - lo + }) + .fold(0.0, f64::max); + if !(area.abs() > EMPTY_AREA * extent * extent) { + return Err(Mismatch { record: at, problem: Problem::Empty { area } }); + } + areas.push((r#loop, area)); + } + } + } + // One loop runs counter-clockwise, the outer; every other one clockwise. Which is + // which comes from the areas, not the loops' order: the truck adapter writes a face's + // wires in truck's order, which need not put the outer one first. + let by_size = |a: &(u32, f64), b: &(u32, f64)| a.1.abs().total_cmp(&b.1.abs()); + let ccw: Vec<(u32, f64)> = areas.iter().copied().filter(|a| a.1 > 0.0).collect(); + let wrong = match ccw.len() { + 0 => areas.into_iter().max_by(by_size).map(|(l, area)| (l, true, area)), + 1 => None, + _ => ccw.into_iter().min_by(by_size).map(|(l, area)| (l, false, area)), + }; + if let Some((r#loop, outer, area)) = wrong { + return Err(Mismatch { record: Record::Loop { face, r#loop }, problem: Problem::Turn { outer, area } }); + } + } + Ok(()) +} + +/// Signed area of a closed polygon in (u, v): positive counter-clockwise. +fn signed_area(ring: &[[f64; 2]]) -> f64 { + let n = ring.len(); + 0.5 * (0..n).filter_map(|i| Some((ring.get(i)?, ring.get((i + 1) % n)?))).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum::() +} diff --git a/crates/geom/src/brep/label.rs b/crates/geom/src/brep/label.rs new file mode 100644 index 000000000..5031ab8d4 --- /dev/null +++ b/crates/geom/src/brep/label.rs @@ -0,0 +1,94 @@ +//! What a record's labels mean in their own parameters, computed: the natural (u, v) ranges of +//! a surface as it is named (a cone's apex), an edge's interval on its circle or ellipse, and +//! whether a face's NURBS form turns its natural normal against its surface's. The record holds +//! these as data; working them out is the kernel's. +use crate::prelude::*; +use solidcore_record::brep::{Curve, Edge, Face, Frame, Natural, Surface, UNBOUNDED, knot_domain}; + +use super::eval; + +/// The ranges of u and v of `s` as it is named (its own (u, v), not its NURBS form's). Call on a +/// validated record. +pub fn surface_natural(s: &Surface) -> [Natural; 2] { + use std::f64::consts::FRAC_PI_2; + match s { + Surface::Plane { .. } | Surface::PlaneThrough { .. } => [UNBOUNDED; 2], + Surface::Cylinder { .. } => [Natural::Periodic, UNBOUNDED], + Surface::Cone { radius_at_origin, half_angle, .. } => { + let apex = -radius_at_origin / half_angle.tan(); + let v = if *half_angle > 0. { Natural::Range(apex, f64::INFINITY) } else { Natural::Range(f64::NEG_INFINITY, apex) }; + [Natural::Periodic, v] + } + Surface::Sphere { .. } => [Natural::Periodic, Natural::Range(-FRAC_PI_2, FRAC_PI_2)], + Surface::Torus { .. } => [Natural::Periodic; 2], + // A label: the face's (u, v) are its NURBS form's. + Surface::BallPatch { .. } => [UNBOUNDED; 2], + Surface::Spline { u_knots, v_knots, points } => { + [knot_domain(u_knots, points.len()), knot_domain(v_knots, points.first().map_or(0, Vec::len))] + } + Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + [knot_domain(u_knots, homogeneous.len()), knot_domain(v_knots, homogeneous.first().map_or(0, Vec::len))] + } + Surface::PlacedRevolution { profile, forward: true, .. } => [profile.natural(), Natural::Periodic], + Surface::PlacedRevolution { profile, forward: false, .. } => [Natural::Periodic, profile.natural()], + } +} + +/// The edge's interval on its `curve` itself, for code that reads what the edge is (a circle's +/// angles): its `interval` when it has no NURBS form; otherwise the angles of its ends on the +/// NURBS, unwrapped forward along the edge (a whole turn for a closed edge). A form's circle or +/// ellipse has its frame turned so its angle grows along the NURBS (the SMLib conversion makes +/// it so). `None` where the NURBS can't be evaluated. +pub fn edge_curve_interval(edge: &Edge) -> Option<[f64; 2]> { + curve_interval(&edge.curve, edge.nurbs.as_ref(), edge.interval) +} + +/// [`edge_curve_interval`] of an edge given by its parts: its `curve`, its NURBS form and its +/// interval on that form. +pub fn curve_interval(curve: &Curve, nurbs: Option<&Curve>, interval: [f64; 2]) -> Option<[f64; 2]> { + use std::f64::consts::TAU; + let Some(n) = nurbs else { return Some(interval) }; + let (frame, radii) = match curve { + Curve::Circle { frame, radius } => (frame, [*radius, *radius]), + Curve::Ellipse { frame, radii } => (frame, *radii), + _ => return Some(interval), + }; + let eval = eval::CurveEval::new(n).ok()?; + let [t0, t1] = interval; + let o = solidcore_record::Vec3::new(frame.origin[0], frame.origin[1], frame.origin[2]); + let (x, y) = (solidcore_record::Vec3::from(frame.x_axis), solidcore_record::Vec3::from(frame.y_axis)); + let angle = |t: f64| eval.point(t).map(|p| ((p - o).dot(y) / radii[1]).atan2((p - o).dot(x) / radii[0]).rem_euclid(TAU)); + let (a0, a1) = (angle(t0)?, angle(t1)?); + let sweep = (a1 - a0).rem_euclid(TAU); + Some([a0, a0 + if sweep <= 1e-12 { TAU } else { sweep }]) +} + +/// Whether the face's NURBS form turns its natural normal against `surface`'s (away from the +/// axis of a cylinder or cone, the centre of a sphere, the tube's centre circle of a torus), at +/// the middle of `domain`. A shell's `forward` is about [`Face::parameters`], so the side +/// `surface` is used on is `forward != form_turns(face)`. `Some(false)` without a form; `None` +/// where the form does not evaluate there. +pub fn form_turns(face: &Face) -> Option { + let Some(form) = &face.nurbs else { return Some(false) }; + let eval = eval::SurfaceEval::new(form).ok()?; + let [[u0, u1], [v0, v1]] = face.domain; + let (p, su, sv) = eval.derivs(0.5 * (u0 + u1), 0.5 * (v0 + v1))?; + let v3 = |a: [f64; 3]| solidcore_record::Vec3::new(a[0], a[1], a[2]); + let radial = |f: &Frame| { + let (o, z) = (v3(f.origin), v3(f.x_axis).cross(v3(f.y_axis))); + let d = p - o; + (o, d - z * (d.dot(z) / z.dot(z))) + }; + let outward = match &face.surface { + Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } => radial(frame).1, + Surface::Sphere { frame, .. } => p - v3(frame.origin), + Surface::BallPatch { center, .. } => p - v3(*center), + Surface::Torus { frame, major_radius, .. } => { + let (o, r) = radial(frame); + p - (o + r.normalized()? * *major_radius) + } + _ => return None, + }; + let along = su.cross(sv).dot(outward); + (along.abs() > 0.0).then_some(along < 0.0) +} diff --git a/crates/geom/src/brep/normal_section.rs b/crates/geom/src/brep/normal_section.rs new file mode 100644 index 000000000..d318b842e --- /dev/null +++ b/crates/geom/src/brep/normal_section.rs @@ -0,0 +1,188 @@ +//! The curvature of a surface's normal section and its first two derivatives by arc length, from +//! the surface's exact partial derivatives ([`Partials`]): what a seam's G2, G3 and G4 compare. +//! +//! At a point `p` with unit normal `n`, the normal section along a unit tangent direction `w` is +//! the curve the plane through `p` spanned by `n` and `w` cuts from the surface. Written as a +//! height over that plane's `w` axis, `h(x) = (r − p) · n` with `x = (r − p) · w`, it starts flat +//! (`h(0) = h′(0) = 0`), and its signed curvature `κ = h″ / (1 + h′²)^(3/2)` has, at `p`, +//! +//! - `κ = h″` (the normal curvature in direction `w`: `n · r″`), +//! - `dκ/ds = h‴` (a curvature that changes along `w`: the G3 quantity), +//! - `d²κ/ds² = h⁗ − 3 h″³` (the G4 quantity). +//! +//! The height's Taylor coefficients come from the surface's: the section is the curve +//! `(u(x), v(x))` on which `(r − p) · w = x` and `(r − p) · t = 0` (`t = w × n`, the cutting +//! plane's normal). Expanding `r` about `p` in its partials and solving those two conditions order +//! by order gives each coefficient of `u` and `v` from the 2 × 2 system of the first partials +//! (the lower orders' terms on the right), and the height's coefficient is the normal part of the +//! same expansion. Nothing is sampled: the answer is exact up to rounding. + +use crate::prelude::*; +use crate::tess::partials::{MAX_PARTIAL_ORDER, Partials, orders}; +use solidcore_record::Vec3; + +/// Taylor coefficients in `x` up to the fourth power (index = power). +type Series = [T; MAX_PARTIAL_ORDER + 1]; + +/// The normal section's curvature and its first two arc-length derivatives at a point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SectionJet { + /// `κ = n · r″`, 1/mm: negative where the surface bends away from `n`. + pub curvature: f64, + /// `dκ/ds` along the direction, 1/mm². + pub curvature_change: f64, + /// `d²κ/ds²` along the direction, 1/mm³. + pub curvature_change_rate: f64, +} + +impl SectionJet { + /// The three values in order: curvature, its change, the change's rate. + pub fn values(&self) -> [f64; 3] { + [self.curvature, self.curvature_change, self.curvature_change_rate] + } +} + +/// The normal section at the point of `d` (`d[0][0]`) with unit normal `normal`, along the unit +/// tangent `direction`. `None` where the first partials do not span the tangent plane across the +/// section (a pole, a degenerate point) or a value is not finite. +pub fn normal_section(d: &Partials, normal: Vec3, direction: Vec3) -> Option { + let cut = direction.cross(normal); + let (ru, rv) = (d[1][0], d[0][1]); + // [ru·w rv·w; ru·t rv·t] [a; b] = rhs, solved by Cramer's rule. + let (m11, m12, m21, m22) = (ru.dot(direction), rv.dot(direction), ru.dot(cut), rv.dot(cut)); + let det = m11 * m22 - m12 * m21; + let scale = ru.len() * rv.len(); + if !(det.abs() > 1e-12 * scale && scale.is_finite()) { + return None; + } + let mut du: Series = [0.0; MAX_PARTIAL_ORDER + 1]; + let mut dv: Series = [0.0; MAX_PARTIAL_ORDER + 1]; + let mut height: Series = [0.0; MAX_PARTIAL_ORDER + 1]; + for k in 1..=MAX_PARTIAL_ORDER { + // The terms of order two and up, which only reach x^k through the coefficients below k. + let rest = *nonlinear(d, &du, &dv).get(k)?; + let target = if k == 1 { 1.0 } else { 0.0 }; + let (r1, r2) = (target - rest.dot(direction), -rest.dot(cut)); + *du.get_mut(k)? = (r1 * m22 - m12 * r2) / det; + *dv.get_mut(k)? = (m11 * r2 - r1 * m21) / det; + *height.get_mut(k)? = rest.dot(normal); + } + let [_, _, h2, h3, h4] = height; + let (curvature, change) = (2.0 * h2, 6.0 * h3); + let rate = 24.0 * h4 - 3.0 * curvature.powi(3); + let jet = SectionJet { curvature, curvature_change: change, curvature_change_rate: rate }; + jet.values().iter().all(|x| x.is_finite()).then_some(jet) +} + +/// `Σ_{2 ≤ i+j ≤ 4} d[i][j] du^i dv^j / (i! j!)`, as a series in `x`. +fn nonlinear(d: &Partials, du: &Series, dv: &Series) -> Series { + let pu = powers(du); + let pv = powers(dv); + let mut out: Series = [Vec3::ZERO; MAX_PARTIAL_ORDER + 1]; + for (i, j) in orders().filter(|(i, j)| i + j >= 2) { + let term = times(&pu[i], &pv[j]); + let weight = 1.0 / (factorial(i) * factorial(j)); + for (o, t) in out.iter_mut().zip(term) { + *o += d[i][j] * (t * weight); + } + } + out +} + +/// `s^0 … s^4`, truncated to the fourth power of `x`. +fn powers(s: &Series) -> [Series; MAX_PARTIAL_ORDER + 1] { + let mut out = [[0.0; MAX_PARTIAL_ORDER + 1]; MAX_PARTIAL_ORDER + 1]; + out[0][0] = 1.0; + for k in 1..=MAX_PARTIAL_ORDER { + out[k] = times(&out[k - 1], s); + } + out +} + +/// The product of two series, truncated to the fourth power. +fn times(a: &Series, b: &Series) -> Series { + let mut out = [0.0; MAX_PARTIAL_ORDER + 1]; + for (i, x) in a.iter().enumerate() { + for (j, y) in b.iter().enumerate().take(MAX_PARTIAL_ORDER + 1 - i) { + out[i + j] += x * y; + } + } + out +} + +fn factorial(n: usize) -> f64 { + (1..=n).map(|k| k as f64).product() +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + use crate::brep::eval::SurfaceEval; + use solidcore_record::brep::{Frame, Surface}; + + fn frame() -> Frame { + Frame { origin: [1., 2., 3.], x_axis: [0., 1., 0.], y_axis: [0., 0., 1.] } + } + + fn jet(s: &Surface, uv: [f64; 2], along: impl Fn(Vec3, Vec3) -> Vec3) -> SectionJet { + let e = SurfaceEval::new(s).unwrap(); + let d = e.partials(uv[0], uv[1]).unwrap(); + let n = d[1][0].cross(d[0][1]).normalized().unwrap(); + let w = along(d[1][0].normalized().unwrap(), d[0][1].normalized().unwrap()); + normal_section(&d, n, w).unwrap() + } + + fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 * (1.0 + b.abs()) + } + + /// A sphere's normal sections are great circles: curvature 1/R (towards the centre, against + /// the outward normal), constant, in every direction. + #[test] + fn a_sphere_is_a_constant_curvature_every_way() { + let s = Surface::Sphere { frame: frame(), radius: 4.0 }; + for along in [|u: Vec3, _: Vec3| u, |_: Vec3, v: Vec3| v, |u: Vec3, v: Vec3| (u + v).normalized().unwrap_or(u)] { + let j = jet(&s, [0.7, 0.3], along); + assert!(near(j.curvature, -0.25) && near(j.curvature_change, 0.0) && near(j.curvature_change_rate, 0.0), "{j:?}"); + } + } + + /// A cylinder across its axis: a circle (-1/R, constant); along it: a straight line. + #[test] + fn a_cylinder_is_a_circle_across_and_a_line_along() { + let s = Surface::Cylinder { frame: frame(), radius: 5.0 }; + let across = jet(&s, [1.1, 2.0], |u, _| u); + assert!(near(across.curvature, -0.2) && near(across.curvature_change, 0.0) && near(across.curvature_change_rate, 0.0), "{across:?}"); + let along = jet(&s, [1.1, 2.0], |_, v| v); + assert!(along.values().iter().all(|x| x.abs() < 1e-12), "{along:?}"); + } + + /// The graph `z = x³/6 + x⁴/12`, an exact quartic Bézier in x and straight in y, has h″ = 0, + /// h‴ = 1 and h⁗ = 2 at the origin: curvature 0, its change 1 and the change's rate 2 along x. + #[test] + fn a_polynomial_graph_reads_its_own_derivatives() { + let z = |x: f64| x.powi(3) / 6.0 + x.powi(4) / 12.0; + // Monomial coefficients a0..a4 = [0, 0, 0, 1/6, 1/12]; Bézier b_i = Σ_k C(i,k)/C(4,k) a_k. + let a = [0.0, 0.0, 0.0, 1.0 / 6.0, 1.0 / 12.0]; + let c = |n: usize, k: usize| crate::bspline::binomial(n, k); + let b: Vec = (0..=4).map(|i| (0..=i).map(|k| c(i, k) / c(4, k) * a[k]).sum()).collect(); + let mut points = Vec::new(); + for (i, bi) in b.iter().enumerate() { + points.push(vec![[i as f64 / 4.0, 0.0, *bi], [i as f64 / 4.0, 1.0, *bi]]); + } + let s = Surface::Spline { u_knots: vec![0., 0., 0., 0., 0., 1., 1., 1., 1., 1.], v_knots: vec![0., 0., 1., 1.], points }; + let e = SurfaceEval::new(&s).unwrap(); + assert!(near(e.point([0.5, 0.5]).unwrap().z, z(0.5))); + let d = e.partials(0.0, 0.5).unwrap(); + let j = normal_section(&d, Vec3::Z, Vec3::X).unwrap(); + assert!(near(j.curvature, 0.0) && near(j.curvature_change, 1.0) && near(j.curvature_change_rate, 2.0), "{j:?}"); + } + + #[test] + fn a_degenerate_point_has_no_section() { + let mut d: Partials = [[Vec3::ZERO; 5]; 5]; + d[1][0] = Vec3::X; + assert!(normal_section(&d, Vec3::Z, Vec3::X).is_none(), "r_v is zero"); + } +} diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rs new file mode 100644 index 000000000..1b01c70d3 --- /dev/null +++ b/crates/geom/src/brep/pcurve.rs @@ -0,0 +1,728 @@ +//! Pcurves from plain records: each edge use's curve in its face's surface parameters, on the +//! edge's own interval and running in its curve's direction (docs/native-brep.md, "Pcurves"), +//! within a tolerance when lifted onto the surface. One routine for every backend: computed +//! from the 3D edge and our surface record, never taken from a kernel's own parameter space. +//! +//! Exact where the edge lies on its surface in closed form: a line, polyline or spline on a +//! plane (the plane's parameters are affine in space: the curve's knots and weights with its +//! control points mapped); a circle about the axis of a cylinder, cone, sphere or torus (v +//! constant, u the circle's angle plus a constant, or minus it where the circle turns the other +//! way); a line along a ruling of a cylinder or cone (u constant, v linear). Each exact pcurve is +//! checked by lifting it; anything else, and any exact one that misses, is a cubic B-spline fitted +//! within the tolerance, never a polyline. +//! +//! Periodic parameters are unwrapped along each curve, and each loop's uses are moved by whole +//! periods so every use starts where the one before it ends: a seam edge used twice gets two +//! pcurves a period apart. A spline closed on itself in a direction is periodic there, one knot +//! interval per period ([`uv`]). At a pole the parameter along the collapsed direction is +//! undefined; there it is taken from the nearest sample where it is defined, so a pcurve runs +//! straight into the pole, and where two uses meet at a pole the loop runs along the pole's line. +use super::eval::{CurveEval, SurfaceEval}; +use crate::bspline::{HPoint, segment}; +use crate::prelude::*; +use crate::tess::uv::{self, Domain}; +use solidcore_record::Vec3; +use solidcore_record::brep::{Budget, Curve, Curve2, Surface, check_curve, check_curve2, check_interval, check_surface}; + +/// Why no pcurves: the records are malformed or out of bounds (`Invalid`), no pcurve within +/// the tolerance was found or the geometry is not supported (`Failed`), or the fit would exceed +/// its caps (`TooLarge`). +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +pub enum Error { + #[error("{0}")] + Invalid(String), + #[error("{0}")] + Failed(String), + #[error("{0}")] + TooLarge(String), +} + +type Result = std::result::Result; + +/// One oriented edge of a loop, as [`pcurves`] reads it: the edge's index (a seam edge, used +/// twice, is fitted once), its curve record and interval, whether the loop runs along it, the +/// edge record's own tolerance (its pcurve is fitted to that, never closer than the face's), and +/// the use's exact pcurve where the producer holds one (`given`, on the use's interval in its +/// curve's direction: a kernel's own UV trim mapped exactly into the record's parameters). A +/// given pcurve is taken as it is, only moved by whole periods with its loop; it is never +/// checked against the edge or replaced here (`brep::geometry::check` checks it). +#[derive(Clone, Copy, Debug)] +pub struct EdgeUse<'a> { + pub edge: u32, + pub curve: &'a Curve, + pub interval: [f64; 2], + pub forward: bool, + pub tolerance: f64, + pub given: Option<&'a Curve2>, +} + +/// Knot spans a fitted pcurve may have (the schema takes 4096 control points). +const MAX_SPANS: usize = 4000; +/// Edge uses of one face. +const MAX_USES: usize = 100_000; +/// Lift checks of an exact pcurve: evenly spaced, plus one inside each of its spans up to this. +const CHECKS: usize = 16; +/// How close, against the geometry's size, a closed-form pcurve must lift onto its edge to be +/// taken as exact (rounding, well inside any tolerance). +const EXACT: f64 = 1e-9; +/// An edge's tolerance over its largest distance from a face's surface: a pcurve is accepted +/// within half its edge's tolerance ([`pcurves_within`]), as SMLib's zone tolerance is half the +/// record's, so a tolerance that covers a gap goes past twice it. +pub const SURFACE_GAP_MARGIN: f64 = 3.0; + +/// For each loop of a face on `surface`, the pcurve of each of its edge uses, in order, within +/// `tolerance` mm (or the use's own edge tolerance where larger) of the edge when lifted onto +/// the surface. Loops are as the record keeps them (relative to the surface's natural normal: outer counter-clockwise, inner clockwise); each +/// pcurve runs on its use's interval in its curve's direction, whatever `forward` says. +pub fn pcurves(surface_record: &Surface, loops: &[Vec>], tolerance: f64) -> Result>> { + pcurves_within(surface_record, loops, tolerance, None) +} + +/// [`pcurves`] for a face whose parameter box is known (`domain`, u then v, as its kernel +/// gives it): where two uses meet at a pole, the periodic parameter's jump there is free, and +/// the loop takes the jumps whose extent in that parameter is nearest the box's. Two meridians +/// a three-quarter turn apart bound a quarter of a sphere or three quarters of it; the loop alone +/// can't tell which, the box can. +pub fn pcurves_within( + surface_record: &Surface, + loops: &[Vec>], + tolerance: f64, + domain: Option<[[f64; 2]; 2]>, +) -> Result>> { + check_size(loops, tolerance)?; + let on = On::new(surface_record)?.within(domain); + let each = each_pcurve(surface_record, &on, loops, tolerance)?; + let mut out = Vec::with_capacity(loops.len()); + for (l, pcs) in loops.iter().zip(each) { + let mut fitted = Vec::with_capacity(l.len()); + for (u, pc) in l.iter().zip(pcs) { + fitted.push((pc?, u.forward)); + } + on.close(&mut fitted, tolerance)?; + out.push(fitted.into_iter().map(|(c, _)| c).collect()); + } + Ok(out) +} + +/// For each loop of a face on `surface`, each use's pcurve where it has a closed form (or is +/// given), else `None`: the uses whose pcurves the face's kernel makes ([`Trims`]). Not closed +/// into loops; [`pcurves_within`] does that once every use has its pcurve. +pub fn exact_pcurves( + surface_record: &Surface, + loops: &[Vec>], + tolerance: f64, + domain: Option<[[f64; 2]; 2]>, +) -> Result>>> { + check_size(loops, tolerance)?; + let on = On::new(surface_record)?.within(domain); + Ok(each_pcurve(surface_record, &on, loops, tolerance)?.into_iter().map(|l| l.into_iter().map(|pc| pc.ok()).collect()).collect()) +} + +fn check_size(loops: &[Vec>], tolerance: f64) -> Result<()> { + if !(tolerance.is_finite() && tolerance > 0.0 && tolerance <= 1e3) { + return Err(Error::Invalid(format!("pcurve tolerance {tolerance}"))); + } + let uses = loops.iter().map(Vec::len).fold(0usize, usize::saturating_add); + if uses > MAX_USES { + return Err(Error::TooLarge(format!("a face with {uses} edge uses"))); + } + Ok(()) +} + +/// Each use's pcurve: the given one, or its closed form; a use with neither is its `Failed` +/// error, any other error fails the face. +fn each_pcurve(surface_record: &Surface, on: &On, loops: &[Vec>], tolerance: f64) -> Result>>> { + let mut budget = Budget::input(); + check_surface(surface_record, &mut budget).and_then(|()| super::check::surface(surface_record)).map_err(|e| Error::Invalid(e.to_string()))?; + // A seam edge used twice is worked out once. + let mut done: Vec<(u32, Result)> = Vec::new(); + let mut out = Vec::with_capacity(loops.len()); + for (w, l) in loops.iter().enumerate() { + let mut pcs = Vec::with_capacity(l.len()); + for (i, u) in l.iter().enumerate() { + if let Some(given) = u.given { + pcs.push(Ok(own_pcurve(given, u.interval, &mut budget).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?)); + continue; + } + if let Some((_, pc)) = done.iter().find(|(e, _)| *e == u.edge) { + pcs.push(pc.clone()); + continue; + } + check_curve(u.curve, &mut budget) + .and_then(|()| super::check::curve(u.curve)) + .map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?; + check_interval(&u.interval, u.curve.natural()).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?; + let c = CurveEval::new(u.curve)?; + // An edge record that holds a looser tolerance than the face's (another kernel's + // approximated edge) is checked against its own, up to the same cap. + let own = if u.tolerance.is_finite() && u.tolerance <= 1e3 { tolerance.max(u.tolerance) } else { tolerance }; + let pc = on.pcurve(u.curve, &c, u.interval, own).map_err(|e| { + let at = |t: f64| c.point(t).map(|p| [p.x, p.y, p.z]); + let message = format!("pcurve of loop {w} use {i} ({:?} to {:?}): {e}", at(u.interval[0]), at(u.interval[1])); + match e { + Error::Invalid(_) => Error::Invalid(message), + Error::Failed(_) => Error::Failed(message), + Error::TooLarge(_) => Error::TooLarge(message), + } + }); + if let Err(e @ (Error::Invalid(_) | Error::TooLarge(_))) = pc { + return Err(e); + } + done.push((u.edge, pc.clone())); + pcs.push(pc); + } + out.push(pcs); + } + Ok(out) +} + +/// One edge of a face handed to a kernel for its pcurves ([`TrimFace`]). +#[derive(Clone, Debug)] +pub struct TrimEdge<'a> { + /// What the edge is, and the NURBS form it is parameterised on when it has one (as + /// [`super::Edge`]). + pub curve: &'a Curve, + pub nurbs: Option<&'a Curve>, + pub interval: [f64; 2], + /// Into [`TrimFace::vertices`]. + pub vertices: [u32; 2], + pub tolerance: f64, +} + +/// One edge use of a [`TrimFace`]'s loop: its edge (into [`TrimFace::edges`]), whether the loop +/// runs along it, and its exact pcurve where it has one. +#[derive(Clone, Debug)] +pub struct TrimUse { + pub edge: u32, + pub forward: bool, + pub pcurve: Option, +} + +/// A face whose pcurves are partly unknown, as a kernel takes it to make them: its surface as +/// [`super::Face`] holds it (what it is, the NURBS form it is parameterised on, the parameter +/// box), its edges and their vertices, and its loops (relative to the surface's natural normal). +#[derive(Clone, Debug)] +pub struct TrimFace<'a> { + pub surface: &'a Surface, + pub nurbs: Option<&'a Surface>, + pub domain: [[f64; 2]; 2], + pub edges: Vec>, + pub vertices: Vec<[f64; 3]>, + pub loops: Vec>, + pub tolerance: f64, +} + +/// A kernel that makes the pcurves of a face's uses that have no closed form, keeping the given +/// ones: for each loop, every use's pcurve on its edge's interval in its curve's direction. +pub trait Trims { + fn trims(&self, face: &TrimFace<'_>) -> std::result::Result>, String>; +} + +/// A producer's own pcurve, checked as a record: a valid 2D B-spline on the use's interval +/// (within 10⁻⁹ of its magnitude, the schema's slack for a linear remap's rounding). +fn own_pcurve(c: &Curve2, [t0, t1]: [f64; 2], budget: &mut Budget) -> Result { + check_curve2(c, budget).map_err(|e| Error::Invalid(format!("given pcurve: {e}")))?; + let [a, b] = c.interval().ok_or_else(|| Error::Invalid("given pcurve: no interval".into()))?; + let slack = 1e-9 * t0.abs().max(t1.abs()).max(1.0); + if (a - t0).abs() > slack || (b - t1).abs() > slack { + return Err(Error::Invalid(format!("given pcurve on [{a}, {b}], its edge on [{t0}, {t1}]"))); + } + Ok(c.clone()) +} + +/// `c` cut exactly to `[t0, t1]` where that is less than its knot interval. +fn cut(c: Curve2, [t0, t1]: [f64; 2]) -> Result { + let Some([a, b]) = c.interval() else { return Err(Error::Invalid("pcurve: no interval".into())) }; + if a == t0 && b == t1 { + return Ok(c); + } + let (knots, h): (&[f64], Vec) = match &c { + Curve2::Spline { knots, points } => (knots, points.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: 1.0 }).collect()), + Curve2::RationalSpline { knots, homogeneous } => (knots, homogeneous.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: p[2] }).collect()), + }; + let degree = knots.len().checked_sub(h.len() + 1).ok_or_else(|| Error::Invalid("pcurve degree".into()))?; + let (knots, h) = segment(degree, knots, &h, t0, t1).map_err(|e| Error::Invalid(format!("pcurve cut to [{t0}, {t1}]: {e:?}")))?; + Ok(match c { + Curve2::Spline { .. } => Curve2::Spline { knots, points: h.iter().map(|p| [p.x, p.y]).collect() }, + Curve2::RationalSpline { .. } => Curve2::RationalSpline { knots, homogeneous: h.iter().map(|p| [p.x, p.y, p.w]).collect() }, + }) +} + +/// A degree-1 patch of four control points on a parallelogram (a plane as a file's B-spline +/// writes it) as that plane: the patch is affine in (u, v), so it is the plane at every +/// parameter, and its pcurves have the plane's closed forms. +fn flat_patch(s: &Surface) -> Option { + let Surface::Spline { u_knots, v_knots, points } = s else { return None }; + let (&[a, a1, b, b1], &[c, c1, d, d1]) = (u_knots.as_slice(), v_knots.as_slice()) else { return None }; + let [row0, row1] = points.as_slice() else { return None }; + let (&[p00, p01], &[p10, p11]) = (row0.as_slice(), row1.as_slice()) else { return None }; + let [p00, p01, p10, p11] = [p00, p01, p10, p11].map(Vec3::from); + if a != a1 || b != b1 || c != c1 || d != d1 || !(a < b && c < d) { + return None; + } + let size = [p00, p01, p10, p11].iter().flat_map(|p| [p.x.abs(), p.y.abs(), p.z.abs()]).fold(1.0, f64::max); + if (p00 + p11 - p10 - p01).len() > EXACT * size { + return None; + } + let (du, dv) = ((p10 - p00) * (1.0 / (b - a)), (p01 - p00) * (1.0 / (d - c))); + if !(du.cross(dv).len() > EXACT * size * size) { + return None; + } + let origin = p00 - du * a - dv * c; + Some(Surface::Plane { origin: [origin.x, origin.y, origin.z], u_axis: [du.x, du.y, du.z], v_axis: [dv.x, dv.y, dv.z] }) +} + +/// What a curve record is, for a message. +fn curve_kind(c: &Curve) -> &'static str { + match c { + Curve::Line { .. } => "a line", + Curve::Circle { .. } => "a circle", + Curve::Ellipse { .. } => "an ellipse", + Curve::Polyline { .. } => "a polyline", + Curve::Spline { .. } => "a B-spline", + Curve::RationalSpline { .. } => "a NURBS", + _ => "a derived curve", + } +} + +/// A face's surface: its evaluator and parameter box, and the grid a point's parameters on it +/// are searched from, made once for all the face's points. +struct On { + surface: SurfaceEval, + starts: uv::Starts, + dom: Domain, + /// The face's own parameter box, where its kernel gives one. + face: Option<[[f64; 2]; 2]>, +} + +impl On { + fn new(s: &Surface) -> Result { + let flat = flat_patch(s); + let surface = SurfaceEval::new(flat.as_ref().unwrap_or(s))?; + let dom = surface.domain(); + Ok(On { surface, starts: uv::Starts::default(), dom, face: None }) + } + + /// What the surface is, for a message. + fn surface_kind(&self) -> &'static str { + match &self.surface { + SurfaceEval::Eval(crate::tess::EvalSurface::Plane { .. }, _) => "a plane", + SurfaceEval::Cylinder { .. } => "a cylinder", + SurfaceEval::Cone { .. } => "a cone", + SurfaceEval::Sphere { .. } => "a sphere", + SurfaceEval::Torus { .. } => "a torus", + _ => "a spline surface", + } + } + + fn within(self, face: Option<[[f64; 2]; 2]>) -> Self { + let face = face.filter(|f| f.iter().flatten().all(|x| x.is_finite())); + On { face, ..self } + } + + fn pcurve(&self, record: &Curve, curve: &CurveEval, range: [f64; 2], tol: f64) -> Result { + if let Some(pc) = self.exact(record, curve, range, tol)? + && self.lifts(&pc, curve, range, 0.5 * tol) + { + return Ok(pc); + } + Err(Error::Failed(format!("not supported yet: no exact pcurve of {} on {}", curve_kind(record), self.surface_kind()))) + } + + /// The closed-form pcurve where there is one (unchecked). + fn exact(&self, record: &Curve, curve: &CurveEval, [t0, t1]: [f64; 2], tol: f64) -> Result> { + let segment = |a: [f64; 2], b: [f64; 2]| Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![a, b] }; + let at = |t: f64| curve.point(t).ok_or_else(|| Error::Failed(format!("the curve has no point at {t}"))); + Ok(match (&self.surface, record) { + (SurfaceEval::Eval(plane @ crate::tess::EvalSurface::Plane { .. }, dom), _) => { + let map = |p: Vec3| uv::project(plane, dom, p, None, 0.0).ok_or_else(|| Error::Invalid("degenerate plane".into())); + match record { + // The line's own ends where the interval reaches them. + Curve::Line { start, end } => { + let end_at = |t: f64| { + if t == 0.0 { + Ok(Vec3::from(*start)) + } else if t == 1.0 { + Ok(Vec3::from(*end)) + } else { + at(t) + } + }; + Some(segment(map(end_at(t0)?)?, map(end_at(t1)?)?)) + } + Curve::Polyline { .. } => { + let mut ts = vec![t0]; + ts.extend((t0.floor() as i64 + 1..).map(|k| k as f64).take_while(|k| *k < t1).take(MAX_SPANS)); + ts.push(t1); + if ts.len() > 4096 { + return Ok(None); + } + let mut knots = vec![t0]; + knots.extend(ts.iter().copied()); + knots.push(t1); + Some(Curve2::Spline { knots, points: ts.iter().map(|t| map(at(*t)?)).collect::>()? }) + } + // The control points through the plane's affine parameters (exact), cut to the + // edge's interval where it covers part of its curve (a form). + Curve::Spline { knots, points } => { + let points = points.iter().map(|p| map(Vec3::from(*p))).collect::>()?; + Some(cut(Curve2::Spline { knots: knots.clone(), points }, [t0, t1])?) + } + Curve::RationalSpline { knots, homogeneous } => { + let homogeneous = homogeneous + .iter() + .map(|h| { + let [u, v] = map(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]))?; + Ok([u * h[3], v * h[3], h[3]]) + }) + .collect::>()?; + Some(cut(Curve2::RationalSpline { knots: knots.clone(), homogeneous }, [t0, t1])?) + } + _ => None, + } + } + ( + SurfaceEval::Cylinder { axes, .. } + | SurfaceEval::Cone { axes, .. } + | SurfaceEval::Sphere { axes, .. } + | SurfaceEval::Torus { axes, .. }, + Curve::Circle { frame, radius }, + ) => { + // About the axis: u the circle's angle from where its x axis points, v fixed. + let c = super::eval::Axes::new(frame); + let turn = c.z.dot(axes.z); + if (turn.abs() - 1.0).abs() > 1e-9 { + return Ok(self.meridian(axes, &c, *radius, curve, [t0, t1])); + } + let sign = turn.signum(); + let u0 = c.x.dot(axes.y).atan2(c.x.dot(axes.x)); + let h = axes.local(c.o)[2]; + let v = match &self.surface { + SurfaceEval::Sphere { .. } => h.atan2(*radius), + SurfaceEval::Torus { major, tube, .. } => (h.atan2(radius - major) - tube).rem_euclid(std::f64::consts::TAU), + _ => h, + }; + Some(segment([u0 + sign * t0, v], [u0 + sign * t1, v])) + } + (SurfaceEval::Cylinder { axes, .. } | SurfaceEval::Cone { axes, .. }, Curve::Line { .. }) => { + // Along a ruling: u where the line is, v its height. + let [a, b, _] = axes.local(at(0.5 * (t0 + t1))?); + let height = |t: f64| at(t).map(|p| axes.local(p)[2]); + let u = b.atan2(a); + Some(segment([u, height(t0)?], [u, height(t1)?])) + } + (SurfaceEval::Eval(..), _) => self.along(curve, [t0, t1], tol), + _ => None, + }) + } + + /// A meridian of a sphere or a tube circle of a torus (a circle in a plane through the axis, + /// centred on the sphere's centre or on the torus's ring): u fixed at the arc's azimuth, v its + /// angle from the outward radial toward the axis, `α + s·t` (`s` ±1 as the circle runs). + /// `None` for any other circle. + fn meridian(&self, axes: &super::eval::Axes, c: &super::eval::Axes, radius: f64, curve: &CurveEval, [t0, t1]: [f64; 2]) -> Option { + // The ring's radius, the circle's, and the tube angle at v = 0. + let (ring, tube) = match &self.surface { + SurfaceEval::Sphere { radius: r, .. } => ((0.0, *r), 0.0), + SurfaceEval::Torus { major, minor, tube, .. } => ((*major, *minor), *tube), + _ => return None, + }; + let size = 1.0 + ring.0 + ring.1; + if c.z.dot(axes.z).abs() > 1e-9 || (radius - ring.1).abs() > 1e-9 * size { + return None; + } + let tm = 0.5 * (t0 + t1); + let m = curve.point(tm)?; + let [mx, my, _] = axes.local(m); + let u0 = my.atan2(mx); + let radial = (axes.x * mx + axes.y * my).normalized()?; + // The circle's centre: the sphere's, or the torus's ring at that azimuth. + let centre = axes.o + radial * ring.0; + if c.o.dist(centre) > 1e-9 * size { + return None; + } + let s = c.z.dot(radial.cross(axes.z)).signum(); + let d = m - centre; + let vm = d.dot(axes.z).atan2(d.dot(radial)) - tube; + let alpha = vm - s * tm; + Some(Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![[u0, alpha + s * t0], [u0, alpha + s * t1]] }) + } + + /// On a spline face (a NURBS form, or another spline), the edge's pcurve where it runs along + /// the face's parameters at its own parameter's pace: a straight line in (u, v), between the + /// ends' parameters, or with u (or v) the edge's parameter itself (a rim of a revolved form on + /// the same quarter grid, whose two ends are one point on the seam). A candidate is taken only + /// where it lifts onto the edge within the record's tolerance, as the closed forms on analytic + /// surfaces must: the closed form the geometry has, never a fit. + fn along(&self, curve: &CurveEval, [t0, t1]: [f64; 2], tol: f64) -> Option { + let (p0, p1, pm) = (curve.point(t0)?, curve.point(t1)?, curve.point(0.5 * (t0 + t1))?); + let size = [p0, p1, pm].iter().flat_map(|p| [p.x.abs(), p.y.abs(), p.z.abs()]).fold(1.0, f64::max); + // Within the record's tolerance, as the closed forms on analytic surfaces are, and never + // looser than rounding. + let exact = (0.5 * tol).max(EXACT * size); + let line = |a: [f64; 2], b: [f64; 2]| Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![a, b] }; + let mut candidates = Vec::with_capacity(3); + let ends = (self.project_in(p0, exact), self.project_in(p1, exact)); + if let (Some(a), Some(b)) = ends { + candidates.push(line(a, b)); + } + // One parameter fixed where the edge's middle is (an end on a seam or at an apex may + // project anywhere along it), the other from the ends. + if let (Some(a), Some(b), Some(m)) = (ends.0, ends.1, self.project_in(pm, exact)) { + candidates.push(line([m[0], a[1]], [m[0], b[1]])); + candidates.push(line([a[0], m[1]], [b[0], m[1]])); + } + // u or v moving at a steady pace in the edge's own parameter, the other fixed (or both + // moving): a rim on the face's quarter grid, its knots scaled or turned over (a closed + // rim's two ends are one point on the seam, so its pace is read inside it, from a quarter + // to three quarters along, unwrapped from the middle). + if let Some(m) = self.project_in(pm, exact) { + let tm = 0.5 * (t0 + t1); + let (ta, tb) = (t0 + 0.25 * (t1 - t0), t0 + 0.75 * (t1 - t0)); + let near = |t: f64| curve.point(t).and_then(|p| self.project(p, Some(m), exact)); + if let (Some(a), Some(b)) = (near(ta), near(tb)) { + let pace = [(b[0] - a[0]) / (tb - ta), (b[1] - a[1]) / (tb - ta)]; + let at = |t: f64, moving: [bool; 2]| { + let d = t - tm; + [m[0] + if moving[0] { pace[0] * d } else { 0.0 }, m[1] + if moving[1] { pace[1] * d } else { 0.0 }] + }; + for moving in [[true, false], [false, true], [true, true]] { + candidates.push(line(at(t0, moving), at(t1, moving))); + } + } + } + candidates.into_iter().find(|pc| self.lifts(pc, curve, [t0, t1], exact)) + } + + /// Whether `pc` lifts onto `curve` within `target` along `range` (evenly, and inside its + /// spans). + fn lifts(&self, pc: &Curve2, curve: &CurveEval, [t0, t1]: [f64; 2], target: f64) -> bool { + let knots = match pc { + Curve2::Spline { knots, .. } | Curve2::RationalSpline { knots, .. } => knots, + }; + // The ends exactly: `t0 + (t1 − t0)·1` may round past `t1`, where the pcurve has no point. + let even = (0..=CHECKS).map(|k| if k == CHECKS { t1 } else { t0 + (t1 - t0) * k as f64 / CHECKS as f64 }); + let spans = knots.windows(2).filter_map(|k| Some((*k.first()?, *k.get(1)?))).filter(|(a, b)| a < b).take(1 << 12).map(|(a, b)| 0.5 * (a + b)); + even.chain(spans).all(|t| { + let lifted = eval(pc, t).and_then(|q| self.surface.point(q)); + matches!((lifted, curve.point(t)), (Some(a), Some(b)) if a.dist(b) <= target) + }) + } + + /// The parameters of `p` within `accept` inside the face's parameter box when it has one: a + /// spline extended past its knots, or a profile turned past where the face lies, has other + /// preimages outside it. The global search first, then from the box's centre. + fn project_in(&self, p: Vec3, accept: f64) -> Option<[f64; 2]> { + let Some(b) = self.face else { return self.project(p, None, accept) }; + let pad = |d: usize| 1e-9 * (1.0 + (b[d][1] - b[d][0]).abs()); + let inside = |q: [f64; 2]| (0..2).all(|d| q[d] >= b[d][0] - pad(d) && q[d] <= b[d][1] + pad(d)); + let centre = [0.5 * (b[0][0] + b[0][1]), 0.5 * (b[1][0] + b[1][1])]; + [None, Some(centre)].into_iter().filter_map(|near| self.project(p, near, accept)).find(|q| inside(*q)) + } + + /// The parameters of `p` within `accept`, from `near` (and unwrapped to it) when given. + fn project(&self, p: Vec3, near: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { + let mut q = self.surface.project_with(&self.starts, p, near, accept)?; + if let Some(n) = near { + for (d, x) in q.iter_mut().enumerate() { + *x = uv::unwrap(*x, n[d], self.dom.period.get(d).copied().flatten()); + } + } + Some(q) + } + + /// Whether `uv` is at a pole along each direction, or within `reach` of one: moving that + /// parameter by half its period (or across its range) moves the point by no more than `reach` + /// at its speed there. There the parameter is as free as at the pole itself. + fn pole(&self, uv: [f64; 2], reach: f64) -> [bool; 2] { + self.surface.pole_within(uv, reach) + } + + /// The loop's uses moved by whole periods so each starts where the one before it ends (in + /// loop order and direction), then all together into the surface's base period where the + /// loop's lowest point allows. Where uses meet at a pole (within `tol`) the periodic + /// parameter is free: there the offsets that turn the loop counter-clockwise in (u, v) (a + /// face boundary seen from the natural normal) by more than rounding are taken, else the + /// nearest. A seam used twice from pole to pole thus encloses its face, never nothing. + fn close(&self, uses: &mut [(Curve2, bool)], tol: f64) -> Result<()> { + let n = uses.len(); + let mut ends = Vec::with_capacity(n); + for (c, fwd) in uses.iter() { + let [a, b] = c.interval().ok_or_else(|| Error::Failed("pcurve interval".into()))?; + let (Some(s), Some(e)) = (eval(c, a), eval(c, b)) else { return Err(Error::Failed("pcurve ends".into())) }; + ends.push(if *fwd { (s, e) } else { (e, s) }); + } + for d in 0..2 { + let Some(period) = self.dom.period.get(d).copied().flatten().filter(|p| *p > 0.0) else { continue }; + // Start after a pole junction if there is one: from there continuity fixes the + // offsets up to the next pole. + let at_pole: Vec = ends.iter().map(|(s, _)| self.pole(*s, tol).get(d).copied().unwrap_or(false)).collect(); + let first = at_pole.iter().position(|&p| p).unwrap_or(0); + let order: Vec = (0..n).map(|k| (first + k) % n).collect(); + let mut shift = vec![0.0; n]; + let mut free: Vec = Vec::new(); + let mut prev: Option = None; + for (k, &i) in order.iter().enumerate() { + let (Some(&(s, e)), Some(slot)) = (ends.get(i), shift.get_mut(i)) else { continue }; + if k > 0 && at_pole.get(i).copied().unwrap_or(false) { + free.push(k); + } + *slot = prev.map_or(0.0, |p| ((p - s[d]) / period).round() * period); + prev = Some(e[d] + *slot); + } + // After each later pole one period less, none or more: the right turn, then the + // fewest moves. + if !free.is_empty() && free.len() <= 6 { + // Less than this is rounding: a loop that encloses nothing (a seam's two uses + // on one line) has no turn, whatever the sign of its area. + let other = uses.iter().flat_map(|(c, _)| points(c).into_iter().filter_map(|q| q.get(1 - d).copied())); + let (lo, hi) = other.fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), x| (a.min(x), b.max(x))); + let flat = if hi >= lo { 1e-9 * period * (hi - lo) } else { 0.0 }; + // With the face's box: how far the loop's extent along `d` is from the box's + // (in steps of a millionth of a period, so rounding doesn't decide). + let width = self.face.and_then(|f| f.get(d).copied()).map(|[a, b]| (b - a).abs()); + let misfit = |extra: &[f64]| -> u64 { + let Some(width) = width else { return 0 }; + let (mut a, mut b) = (f64::INFINITY, f64::NEG_INFINITY); + for ((c, _), s) in uses.iter().zip(extra) { + for q in points(c) { + if let Some(x) = q.get(d) { + a = a.min(x + s); + b = b.max(x + s); + } + } + } + if b < a { 0 } else { ((b - a - width).abs() / period * 1e6).round() as u64 } + }; + let mut best: Option<(u64, bool, usize, Vec)> = None; + for combo in 0..3usize.pow(free.len() as u32) { + let (mut code, mut moved, mut add) = (combo, 0, 0.0); + let mut extra = shift.clone(); + for (k, &i) in order.iter().enumerate() { + if free.contains(&k) { + let step = (code % 3) as f64 - 1.0; + code /= 3; + moved += usize::from(step != 0.0); + add += step * period; + } + if let Some(slot) = extra.get_mut(i) { + *slot += add; + } + } + let right = area(uses, &extra, d) > flat; + let fit = misfit(&extra); + if best.as_ref().is_none_or(|(f, r, m, _)| fit < *f || (fit == *f && ((right && !r) || (right == *r && moved < *m)))) { + best = Some((fit, right, moved, extra)); + } + } + if let Some((_, _, _, extra)) = best { + shift = extra; + } + } + let lo = self.dom.range.get(d).copied().flatten().map_or(0.0, |(a, b)| a.min(b)); + let low = uses.iter().zip(&shift).flat_map(|((c, _), s)| points(c).into_iter().map(move |q| q[d] + s)).fold(f64::INFINITY, f64::min); + let base = if low.is_finite() { ((low - lo) / period + 1e-9).floor() * period } else { 0.0 }; + for (((c, _), s), (st, en)) in uses.iter_mut().zip(&shift).zip(ends.iter_mut()) { + let by = s - base; + if by != 0.0 { + move_by(c, d, by); + st[d] += by; + en[d] += by; + } + } + } + Ok(()) + } +} + +/// Signed area in (u, v) of the loop with its uses moved by `shift` along `d`. +fn area(uses: &[(Curve2, bool)], shift: &[f64], d: usize) -> f64 { + let mut ring: Vec<[f64; 2]> = Vec::new(); + for ((c, fwd), s) in uses.iter().zip(shift) { + let Some([a, b]) = c.interval() else { continue }; + for k in 0..16 { + let f = k as f64 / 16.0; + let t = if *fwd { a + (b - a) * f } else { b - (b - a) * f }; + if let Some(mut q) = eval(c, t) { + if let Some(x) = q.get_mut(d) { + *x += s; + } + ring.push(q); + } + } + } + let n = ring.len(); + (0..n).filter_map(|i| Some((ring.get(i)?, ring.get((i + 1) % n)?))).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum::() * 0.5 +} + +/// The control points of `c` in (u, v). +fn points(c: &Curve2) -> Vec<[f64; 2]> { + match c { + Curve2::Spline { points, .. } => points.clone(), + Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().map(|h| [h[0] / h[2], h[1] / h[2]]).collect(), + } +} + +/// `c` moved by `by` along parameter `d`. +fn move_by(c: &mut Curve2, d: usize, by: f64) { + match c { + Curve2::Spline { points, .. } => points.iter_mut().filter_map(|p| p.get_mut(d)).for_each(|x| *x += by), + Curve2::RationalSpline { homogeneous, .. } => { + for h in homogeneous { + let w = h[2]; + if let Some(x) = h.get_mut(d) { + *x += by * w; + } + } + } + } +} + +/// The point of pcurve `c` at `t` (`None` outside its interval or for a malformed record). +pub fn eval(c: &Curve2, t: f64) -> Option<[f64; 2]> { + let (knots, h): (&[f64], Vec<[f64; 3]>) = match c { + Curve2::Spline { knots, points } => (knots, points.iter().map(|&[u, v]| [u, v, 1.0]).collect()), + Curve2::RationalSpline { knots, homogeneous } => (knots, homogeneous.clone()), + }; + let p = knots.len().checked_sub(h.len() + 1)?; + let span = crate::bspline::find_span(knots, p, h.len(), t)?; + let n = basis(knots, p, span, t)?; + let mut s = [0.0; 3]; + for (j, nj) in n.iter().enumerate() { + let q = h.get(span + j - p)?; + for (a, x) in s.iter_mut().zip(q) { + *a += nj * x; + } + } + (s[2].abs() > 0.0).then(|| [s[0] / s[2], s[1] / s[2]]) +} + +/// The `p + 1` basis functions non-zero on knot span `span` at `t`, of any degree (NURBS Book +/// A2.2). +fn basis(knots: &[f64], p: usize, span: usize, t: f64) -> Option> { + if span < p || span + p >= knots.len() { + return None; + } + let k = |i: usize| knots.get(i).copied().unwrap_or(0.0); + let mut n = vec![0.0; p + 1]; + let (mut left, mut right) = (vec![0.0; p + 1], vec![0.0; p + 1]); + *n.first_mut()? = 1.0; + for j in 1..=p { + *left.get_mut(j)? = t - k(span + 1 - j); + *right.get_mut(j)? = k(span + j) - t; + let mut saved = 0.0; + for r in 0..j { + let (rr, lj) = (*right.get(r + 1)?, *left.get(j - r)?); + let den = rr + lj; + let tmp = if den != 0.0 { n.get(r)? / den } else { 0.0 }; + *n.get_mut(r)? = saved + rr * tmp; + saved = lj * tmp; + } + *n.get_mut(j)? = saved; + } + Some(n) +} + +#[cfg(test)] +#[path = "pcurve_tests.rs"] +pub(super) mod tests; diff --git a/crates/geom/src/brep/pcurve_tests.rs b/crates/geom/src/brep/pcurve_tests.rs new file mode 100644 index 000000000..07dab842d --- /dev/null +++ b/crates/geom/src/brep/pcurve_tests.rs @@ -0,0 +1,671 @@ +use super::*; +use crate::brep::eval::{CurveEval, SurfaceEval}; +use solidcore_record::brep::Frame; +use std::f64::consts::{FRAC_PI_2, PI, TAU}; + +fn frame(origin: [f64; 3], x_axis: [f64; 3], y_axis: [f64; 3]) -> Frame { + Frame { origin, x_axis, y_axis } +} +/// A frame about the axis through `origin` along +z, or −z when `down` (x stays +x). +fn about_z(origin: [f64; 3], down: bool) -> Frame { + frame(origin, [1., 0., 0.], if down { [0., -1., 0.] } else { [0., 1., 0.] }) +} +fn one(curve: &Curve, interval: [f64; 2]) -> Vec>> { + vec![vec![EdgeUse { edge: 0, curve, interval, forward: true, tolerance: 0.0, given: None }]] +} +/// The largest distance between the lifted pcurve and the curve, at 65 points and each span's +/// middle. +fn lift_error(surface: &Surface, curve: &Curve, interval: [f64; 2], pc: &Curve2) -> f64 { + let (s, c) = (SurfaceEval::new(surface).unwrap(), CurveEval::new(curve).unwrap()); + let [t0, t1] = interval; + assert_eq!(pc.interval(), Some(interval), "on the edge's interval"); + let knots = match pc { + Curve2::Spline { knots, .. } | Curve2::RationalSpline { knots, .. } => knots, + }; + let mut ts: Vec = (0..=64).map(|k| if k == 64 { t1 } else { t0 + (t1 - t0) * k as f64 / 64. }).collect(); + ts.extend(knots.windows(2).filter(|k| k[0] < k[1]).map(|k| 0.5 * (k[0] + k[1]))); + ts.iter().map(|&t| s.point(eval(pc, t).unwrap()).unwrap().dist(c.point(t).unwrap())).fold(0., f64::max) +} +fn segment_points(pc: &Curve2) -> [[f64; 2]; 2] { + match pc { + Curve2::Spline { knots, points } if knots.len() == 4 && points.len() == 2 => [points[0], points[1]], + other => panic!("not a degree-1 segment: {other:?}"), + } +} + +#[test] +fn a_spline_on_a_plane_over_an_interval_whose_even_steps_round_past_its_end_is_mapped() { + // Poppy Humanoid's edge: t0 + (t1 − t0)·1 is 1.2985843833752289, one rounding past t1, where + // a pcurve on [t0, t1] has no point; the closed form was refused for it. + let (t0, t1) = (0.013209624271103393f64, 1.2985843833752286f64); + assert!(t0 + (t1 - t0) * 1.0 > t1, "the interval's even step rounds past its end"); + let plane = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }; + let curve = Curve::Spline { knots: vec![t0, t0, t0, t1, t1, t1], points: vec![[0., 0., 0.], [1., 2., 0.], [3., 1., 0.]] }; + let pc = &pcurves_within(&plane, &one(&curve, [t0, t1]), 1e-9, None).unwrap()[0][0]; + assert!(lift_error(&plane, &curve, [t0, t1], pc) < 1e-12); +} + +#[test] +fn lines_polylines_and_splines_on_planes_are_their_points_mapped() { + let plane = Surface::PlaneThrough { origin: [1., 2., 3.], u_point: [3., 2., 3.], v_point: [1., 2., 7.] }; + let line = Curve::Line { start: [2., 2., 4.], end: [5., 2., 11.] }; + let pc = &pcurves(&plane, &one(&line, [0., 1.]), 1e-9).unwrap()[0][0]; + // Bit for bit: the ends lift to the line's own ends. + let [a, b] = segment_points(pc); + assert_eq!((a, b), ([0.5, 0.25], [2., 2.])); + // On part of the line, extended past it. + let pc = &pcurves(&plane, &one(&line, [-1., 3.]), 1e-9).unwrap()[0][0]; + assert!(lift_error(&plane, &line, [-1., 3.], pc) <= 1e-12); + let poly = Curve::Polyline { points: vec![[1., 2., 3.], [3., 2., 3.], [3., 2., 7.], [5., 2., 9.]] }; + let pc = &pcurves(&plane, &one(&poly, [0.5, 3.]), 1e-9).unwrap()[0][0]; + let Curve2::Spline { knots, points } = pc else { panic!("a spline") }; + assert_eq!(knots, &[0.5, 0.5, 1., 2., 3., 3.]); + assert_eq!(points, &[[0.5, 0.], [1., 0.], [1., 1.], [2., 1.5]]); + assert!(lift_error(&plane, &poly, [0.5, 3.], pc) <= 1e-12); + let w = std::f64::consts::FRAC_1_SQRT_2; + let arc = Curve::RationalSpline { + knots: vec![0., 0., 0., 1., 1., 1.], + homogeneous: vec![[3., 2., 3., 1.], [3. * w, 2. * w, 5. * w, w], [1., 2., 5., 1.]], + }; + let pc = &pcurves(&plane, &one(&arc, [0., 1.]), 1e-9).unwrap()[0][0]; + assert!(matches!(pc, Curve2::RationalSpline { .. })); + assert!(lift_error(&plane, &arc, [0., 1.], pc) <= 1e-12); + let cubic = Curve::Spline { knots: vec![0., 0., 0., 0., 2., 2., 2., 2.], points: vec![[1., 2., 3.], [4., 2., 3.], [2., 2., 6.], [5., 2., 8.]] }; + let pc = &pcurves(&plane, &one(&cubic, [0., 2.]), 1e-9).unwrap()[0][0]; + assert_eq!(pc, &Curve2::Spline { knots: vec![0., 0., 0., 0., 2., 2., 2., 2.], points: vec![[0., 0.], [1.5, 0.], [0.5, 0.75], [2., 1.25]] }); + // A piece of the spline is fitted instead (its knots would need cutting). + let pc = &pcurves(&plane, &one(&cubic, [0.5, 1.5]), 1e-7).unwrap()[0][0]; + assert!(lift_error(&plane, &cubic, [0.5, 1.5], pc) <= 1e-7); +} + +/// A G4 blend curve is one Bézier of degree 9 (five conditions at each end): on its sketch's +/// plane its pcurve is its points mapped, and on the face extruded from it, of degree (9, 1), +/// the kernel's own iso-line trims close the loop and lift onto the edges. Degree 9 was past the +/// evaluator's old cap of 7, so both faces were refused ("a spline surface of degree (9, 1)"). +#[test] +fn a_g4_blend_of_degree_9_and_the_face_extruded_from_it_get_exact_pcurves() { + let bezier = |z: f64| -> Vec<[f64; 3]> { + let along_x = (0..5).map(|k| [10. + k as f64, 0., z]); + let along_y = (5..10).map(|k| [20., k as f64 + 1., z]); + along_x.chain(along_y).collect() + }; + let knots: Vec = [[0.; 10], [1.; 10]].concat(); + let low = Curve::Spline { knots: knots.clone(), points: bezier(0.) }; + let plane = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }; + let pc = &pcurves(&plane, &one(&low, [0., 1.]), 1e-9).unwrap()[0][0]; + let Curve2::Spline { knots: k, points } = pc else { panic!("a spline") }; + assert_eq!((k, points.len()), (&knots, 10), "the curve's own knots and points"); + assert!(lift_error(&plane, &low, [0., 1.], pc) <= 1e-12); + + let (low_pts, high_pts) = (bezier(0.), bezier(10.)); + let rows = low_pts.iter().zip(&high_pts).map(|(a, b)| vec![*a, *b]).collect(); + let wall = Surface::Spline { u_knots: knots.clone(), v_knots: vec![0., 0., 1., 1.], points: rows }; + let high = Curve::Spline { knots, points: high_pts }; + let right = Curve::Line { start: [20., 10., 0.], end: [20., 10., 10.] }; + let left = Curve::Line { start: [10., 0., 10.], end: [10., 0., 0.] }; + let seg = |a: [f64; 2], b: [f64; 2]| Curve2::Spline { knots: vec![0., 0., 1., 1.], points: vec![a, b] }; + let given = [seg([0., 0.], [1., 0.]), seg([1., 0.], [1., 1.]), seg([0., 1.], [1., 1.]), seg([0., 1.], [0., 0.])]; + let edges = [(&low, true), (&right, true), (&high, false), (&left, true)]; + let l: Vec> = edges + .iter() + .zip(&given) + .enumerate() + .map(|(e, ((curve, forward), g))| EdgeUse { edge: e as u32, curve, interval: [0., 1.], forward: *forward, tolerance: 0.0, given: Some(g) }) + .collect(); + let pcs = pcurves_within(&wall, &[l], 1e-7, Some([[0., 1.], [0., 1.]])).unwrap(); + for ((curve, _), pc) in edges.iter().zip(&pcs[0]) { + assert!(lift_error(&wall, curve, [0., 1.], pc) <= 1e-12, "{curve:?}"); + } +} + +/// A circle about the axis is a u-line: v fixed, u its angle plus a constant (minus where it +/// turns the other way), on cylinders, cones, spheres and tori, in either direction. +#[test] +fn circles_about_the_axis_are_u_lines() { + let o = [1., -2., 3.]; + let at = |h: f64| [1., -2., 3. + h]; + let tilt = 0.3f64; + let rotated = |origin: [f64; 3], down: bool| { + let (s, c) = tilt.sin_cos(); + frame(origin, [c, s, 0.], if down { [s, -c, 0.] } else { [-s, c, 0.] }) + }; + let half = 0.4f64; + let cases = [ + (Surface::Cylinder { frame: about_z(o, false), radius: 5. }, 7., 5., 7.), + (Surface::Cone { frame: about_z(o, false), radius_at_origin: 2., half_angle: half }, 4., 2. + 4. * half.tan(), 4.), + (Surface::Sphere { frame: about_z(o, false), radius: 5. }, 3., 4., 3f64.atan2(4.)), + (Surface::Sphere { frame: about_z(o, false), radius: 5. }, -3., 4., (-3f64).atan2(4.)), + ( + Surface::Torus { frame: about_z(o, false), major_radius: 10., minor_radius: 2., tube_start: 0.0 }, + 2f64.sqrt(), + 10. - 2f64.sqrt(), + 0.75 * PI, + ), + ]; + for (surface, h, r, v) in cases { + for down in [false, true] { + let circle = Curve::Circle { frame: rotated(at(h), down), radius: r }; + for interval in [[0., TAU], [-1., 2.5], [4., 5.]] { + let pc = &pcurves(&surface, &one(&circle, interval), 1e-9).unwrap()[0][0]; + let [a, b] = segment_points(pc); + let sign = if down { -1. } else { 1. }; + // The u-line itself: the only freedom is the period the loop is moved by. + let shift = a[0] - (tilt + sign * interval[0]); + assert!((shift / TAU - (shift / TAU).round()).abs() < 1e-14, "{surface:?} {down}: {a:?}"); + assert!((b[0] - a[0] - sign * (interval[1] - interval[0])).abs() < 1e-13); + assert!(a[1] == b[1] && (a[1] - v).abs() < 1e-14, "{surface:?}: v {a:?} {v}"); + let e = lift_error(&surface, &circle, interval, pc); + assert!(e <= 1e-12, "{surface:?} {down} {interval:?}: {e}"); + } + } + } +} + +/// A line along a ruling of a cylinder or a cone is a v-line: u fixed, v its height. +#[test] +fn rulings_are_v_lines() { + let half = 0.3f64; + let cylinder = Surface::Cylinder { frame: about_z([0.; 3], false), radius: 4. }; + let cone = Surface::Cone { frame: about_z([0., 0., 1.], false), radius_at_origin: 3., half_angle: half }; + let (s, c) = 2f64.sin_cos(); + let up = Curve::Line { start: [4. * c, 4. * s, -1.], end: [4. * c, 4. * s, 6.] }; + let down = Curve::Line { start: [4. * c, 4. * s, 6.], end: [4. * c, 4. * s, -1.] }; + let r = |z: f64| 3. + (z - 1.) * half.tan(); + let slant = Curve::Line { start: [r(2.) * c, r(2.) * s, 2.], end: [r(5.) * c, r(5.) * s, 5.] }; + for (surface, line, heights) in [(&cylinder, &up, [-1., 6.]), (&cylinder, &down, [6., -1.]), (&cone, &slant, [1., 4.])] { + for interval in [[0., 1.], [0.25, 2.]] { + let pc = &pcurves(surface, &one(line, interval), 1e-9).unwrap()[0][0]; + let [a, b] = segment_points(pc); + assert_eq!(a[0], b[0]); + assert!((a[0] - 2.).abs() < 1e-14); + let height = |t: f64| heights[0] + (heights[1] - heights[0]) * t; + assert!((a[1] - height(interval[0])).abs() < 1e-13 && (b[1] - height(interval[1])).abs() < 1e-13, "{a:?} {b:?}"); + assert!(lift_error(surface, line, interval, pc) <= 1e-12); + } + } +} + +/// Curves with no closed form on their face are refused, never fitted: a tilted circle on a +/// sphere, a plane's ellipse on a cylinder, a circle off the axis on a plane. +#[test] +fn curves_without_a_closed_form_are_refused() { + let (s, c) = 0.5f64.sin_cos(); + let sphere = Surface::Sphere { frame: about_z([0.; 3], false), radius: 6. }; + let great = Curve::Circle { frame: frame([0.; 3], [1., 0., 0.], [0., c, s]), radius: 6. }; + let cylinder = Surface::Cylinder { frame: about_z([0.; 3], false), radius: 2. }; + let ellipse = Curve::Ellipse { + frame: frame([0., 0., 1.], [1. / (1f64 + 0.25).sqrt(), 0., 0.5 / (1f64 + 0.25).sqrt()], [0., 1., 0.]), + radii: [2. * (1.25f64).sqrt(), 2.], + }; + let plane = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }; + let circle = Curve::Circle { frame: about_z([3., 1., 0.], false), radius: 2. }; + for (surface, curve, interval) in [(&sphere, &great, [0., TAU]), (&cylinder, &ellipse, [0.2, 6.]), (&plane, &circle, [0., 3.])] { + let r = pcurves(surface, &one(curve, interval), 1e-6); + assert!(matches!(&r, Err(Error::Failed(m)) if m.contains("not supported yet: no exact pcurve")), "{curve:?}: {r:?}"); + } +} +/// The ends of each use in loop order and the loop's signed area in (u, v). +fn walk(l: &[EdgeUse<'_>], pcs: &[Curve2]) -> (Vec<([f64; 2], [f64; 2])>, f64) { + let mut ring = Vec::new(); + let mut ends = Vec::new(); + for (u, pc) in l.iter().zip(pcs) { + let [a, b] = u.interval; + let ts: Vec = (0..=16).map(|k| if u.forward { a + (b - a) * k as f64 / 16. } else { b - (b - a) * k as f64 / 16. }).collect(); + let pts: Vec<[f64; 2]> = ts.iter().map(|t| eval(pc, *t).unwrap()).collect(); + ends.push((pts[0], pts[16])); + ring.extend_from_slice(&pts[..16]); + } + let n = ring.len(); + let area = (0..n).map(|i| ring[i][0] * ring[(i + 1) % n][1] - ring[(i + 1) % n][0] * ring[i][1]).sum::() * 0.5; + (ends, area) +} + +/// A cylinder's wall between two full circles, with its seam line used twice: the seam's uses +/// are one period apart, the loop closes and turns counter-clockwise, all in the base period. +#[test] +fn a_seam_used_twice_gets_pcurves_a_period_apart() { + let cylinder = Surface::Cylinder { frame: about_z([0.; 3], false), radius: 3. }; + let seam = Curve::Line { start: [3., 0., 0.], end: [3., 0., 4.] }; + let low = Curve::Circle { frame: about_z([0.; 3], false), radius: 3. }; + let high = Curve::Circle { frame: about_z([0., 0., 4.], false), radius: 3. }; + let full = [0., TAU]; + let l = vec![ + EdgeUse { edge: 0, curve: &low, interval: full, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &seam, interval: [0., 1.], forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 2, curve: &high, interval: full, forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &seam, interval: [0., 1.], forward: false, tolerance: 0.0, given: None }, + ]; + let pcs = &pcurves(&cylinder, std::slice::from_ref(&l), 1e-9).unwrap()[0]; + let (ends, area) = walk(&l, pcs); + for k in 0..4 { + let (end, start) = (ends[k].1, ends[(k + 1) % 4].0); + assert!((end[0] - start[0]).abs() < 1e-12 && (end[1] - start[1]).abs() < 1e-12, "{k}: {end:?} {start:?}"); + } + assert!(area > 0., "counter-clockwise: {area}"); + let (a, b) = (segment_points(&pcs[1]), segment_points(&pcs[3])); + assert!(((a[0][0] - b[0][0]).abs() - TAU).abs() < 1e-12 && a[0][1] == b[0][1]); + for pc in pcs { + for p in segment_points(pc) { + assert!((-1e-12..=TAU + 1e-12).contains(&p[0]), "base period: {p:?}"); + } + } +} + +/// A sphere bounded by one meridian used twice from pole to pole: each use runs straight into +/// the poles, the two a period apart, and the loop runs along the poles' lines. +#[test] +fn meridians_run_straight_into_the_poles() { + let sphere = Surface::Sphere { frame: about_z([0.; 3], false), radius: 6. }; + let meridian = Curve::Circle { frame: frame([0.; 3], [1., 0., 0.], [0., 0., 1.]), radius: 6. }; + let half = [-FRAC_PI_2, FRAC_PI_2]; + let l = vec![ + EdgeUse { edge: 0, curve: &meridian, interval: half, forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 0, curve: &meridian, interval: half, forward: true, tolerance: 0.0, given: None }, + ]; + for tol in [1e-3, 1e-6] { + let pcs = &pcurves(&sphere, std::slice::from_ref(&l), tol).unwrap()[0]; + for pc in pcs { + assert!(lift_error(&sphere, &meridian, half, pc) <= tol); + for k in 0..=16 { + let q = eval(pc, -FRAC_PI_2 + PI * k as f64 / 16.).unwrap(); + let u = eval(&pcs[0], 0.).unwrap()[0]; + assert!((q[0] - u).abs() < 1e-9 || ((q[0] - u).abs() - TAU).abs() < 1e-9, "straight: {q:?}"); + } + } + let (a, b) = (eval(&pcs[0], 0.).unwrap(), eval(&pcs[1], 0.).unwrap()); + assert!(((a[0] - b[0]).abs() - TAU).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-12, "{a:?} {b:?}"); + let (_, area) = walk(&l, pcs); + assert!(area > 0., "counter-clockwise: {area}"); + } +} + +/// Two meridians a three-quarter turn apart bound a quarter of a sphere or three quarters of +/// it; the loop alone can't tell which. Given the face's box, the loop spans it: three quarters +/// of a turn in u (a ball revolved 270°), or a quarter where the box says so. +#[test] +fn meridians_at_a_pole_span_the_face_box() { + let sphere = Surface::Sphere { frame: about_z([0.; 3], false), radius: 6. }; + let at = |a: f64| Curve::Circle { frame: frame([0.; 3], [a.cos(), a.sin(), 0.], [0., 0., 1.]), radius: 6. }; + let (first, last) = (at(0.), at(1.5 * PI)); + let half = [-FRAC_PI_2, FRAC_PI_2]; + for (box_u, span) in [([0., 1.5 * PI], 1.5 * PI), ([-FRAC_PI_2, 0.], FRAC_PI_2)] { + for flip in [false, true] { + let l = vec![ + EdgeUse { edge: 0, curve: &first, interval: half, forward: !flip, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &last, interval: half, forward: flip, tolerance: 0.0, given: None }, + ]; + let pcs = &pcurves_within(&sphere, std::slice::from_ref(&l), 1e-7, Some([box_u, [-FRAC_PI_2, FRAC_PI_2]])).unwrap()[0]; + let (a, b) = (eval(&pcs[0], 0.).unwrap()[0], eval(&pcs[1], 0.).unwrap()[0]); + assert!(((a - b).abs() - span).abs() < 1e-9, "box {box_u:?}, flip {flip}: u {a} and {b}"); + } + } +} + +/// A whole sphere bounded only by its seam (one meridian from pole to pole, used twice), in +/// frames where rounding leaves the loop with the uses on one line a tiny positive area: the +/// two uses come out a period apart and the loop turns counter-clockwise around the whole +/// (u, v) box, in either loop order, for a circle or a NURBS meridian, with its ends at the +/// poles or within a tenth of the tolerance of them. +#[test] +fn a_seam_from_pole_to_pole_encloses_the_whole_sphere() { + let w = std::f64::consts::FRAC_1_SQRT_2; + let tol = 1e-7; + let frames = [ + about_z([0.; 3], false), + about_z([1., -2., 3.], true), + frame([1., 2., 3.], [0., 0.6, 0.8], [0., -0.8, 0.6]), + frame([-4., 0.5, 2.], [0.36, 0.48, 0.8], [-0.8, 0.6, 0.]), + ]; + for sf in frames { + let sphere = Surface::Sphere { frame: sf.clone(), radius: 6. }; + let ax = crate::brep::eval::Axes::new(&sf); + for turn in [0f64, 2.1, -0.7] { + let x = ax.x * turn.cos() + ax.y * turn.sin(); + let p = |v: Vec3| [v.x, v.y, v.z]; + let (o, r, z) = (ax.o, x * 6., ax.z * 6.); + let circle = Curve::Circle { frame: Frame { origin: p(o), x_axis: p(x), y_axis: p(ax.z) }, radius: 6. }; + for off in [0., 0.1 * tol] { + // South pole to north pole through the equator, as two rational quarter arcs, + // the ends `off` to the side of the poles. + let h = |v: Vec3, wt: f64| [v.x * wt, v.y * wt, v.z * wt, wt]; + let side = ax.y * off; + let nurbs = Curve::RationalSpline { + knots: vec![0., 0., 0., 0.5, 0.5, 1., 1., 1.], + homogeneous: vec![h(o - z + side, 1.), h(o - z + r, w), h(o + r, 1.), h(o + z + r, w), h(o + z - side, 1.)], + }; + // The circle on the sphere as it is; the NURBS meridian, on a parameter of its own, + // on the sphere's NURBS form (one turn is four quarters there, the latitude two). + let (form, _) = crate::brep::form::surface(&sphere, [[0., TAU], [-FRAC_PI_2, FRAC_PI_2]]).unwrap(); + for (seam, iv, on, period, height) in [(&circle, [-FRAC_PI_2, FRAC_PI_2], &sphere, TAU, PI), (&nurbs, [0., 1.], &form, 4., 2.)] { + for order in [[true, false], [false, true]] { + let l: Vec = order + .iter() + .map(|&forward| EdgeUse { edge: 0, curve: seam, interval: iv, forward, tolerance: 0.0, given: None }) + .collect(); + let pcs = &pcurves(on, std::slice::from_ref(&l), tol).unwrap()[0]; + let what = format!("{sf:?} {turn} {off} {seam:?} {order:?}"); + for pc in pcs { + assert!(lift_error(on, seam, iv, pc) <= tol, "{what}"); + } + let mid = 0.5 * (iv[0] + iv[1]); + let (a, b) = (eval(&pcs[0], mid).unwrap(), eval(&pcs[1], mid).unwrap()); + assert!(((a[0] - b[0]).abs() - period).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-12, "a period apart: {a:?} {b:?} {what}"); + let (ends, area) = walk(&l, pcs); + for k in 0..2 { + assert!((ends[k].1[1] - ends[(k + 1) % 2].0[1]).abs() < 1e-6, "closed in v: {ends:?} {what}"); + } + // The box less the corners `walk` cuts (it joins each use's 16th + // sample to the next use's start): about 15/16 of it. + assert!((area / (period * height * 15. / 16.) - 1.).abs() < 1e-2, "counter-clockwise around the box: {area} {what}"); + } + } + } + } + } +} + +/// A whole torus bounded only by its two seams (a circle about the axis and a circle around +/// the tube, each used twice): no pole, continuity alone puts each seam's uses a period apart +/// and the loop around the whole (u, v) box. +#[test] +fn a_torus_bounded_by_its_seams_spans_both_periods() { + let frames = [about_z([0.; 3], false), frame([1., 2., 3.], [0., 0.6, 0.8], [0., -0.8, 0.6])]; + for sf in frames { + let torus = Surface::Torus { frame: sf.clone(), major_radius: 10., minor_radius: 2., tube_start: 0.0 }; + let ax = crate::brep::eval::Axes::new(&sf); + let p = |v: Vec3| [v.x, v.y, v.z]; + // The outer equator (v = 0, u from 0) and the tube circle at u = 0 (v from 0, upwards). + let around = Curve::Circle { frame: sf.clone(), radius: 12. }; + let tube = Curve::Circle { frame: Frame { origin: p(ax.o + ax.x * 10.), x_axis: p(ax.x), y_axis: p(ax.z) }, radius: 2. }; + let full = [0., TAU]; + let l = vec![ + EdgeUse { edge: 0, curve: &around, interval: full, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &tube, interval: full, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 0, curve: &around, interval: full, forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &tube, interval: full, forward: false, tolerance: 0.0, given: None }, + ]; + let pcs = &pcurves(&torus, std::slice::from_ref(&l), 1e-9).unwrap()[0]; + let (ends, area) = walk(&l, pcs); + for k in 0..4 { + let (end, start) = (ends[k].1, ends[(k + 1) % 4].0); + assert!((end[0] - start[0]).abs() < 1e-12 && (end[1] - start[1]).abs() < 1e-12, "{k}: {end:?} {start:?}"); + } + assert!((area / (TAU * TAU) - 1.).abs() < 1e-12, "counter-clockwise around the box: {area}"); + } +} + +/// The pcurves of a loop on a spline closed in u (period 1): each lifts within `tol`, the +/// seam's two uses (`seam`: their positions) lie one period apart, the loop closes (in v alone +/// where it meets a pole) and turns counter-clockwise once around the whole (u, v) box, all in +/// the base period. +fn closes_around_the_box(surface: &Surface, l: &[EdgeUse<'_>], seam: [usize; 2], pole: Option, tol: f64, what: &str) { + let pcs = &pcurves(surface, &[l.to_vec()], tol).unwrap_or_else(|e| panic!("{what}: {e}"))[0]; + for (u, pc) in l.iter().zip(pcs) { + assert!(lift_error(surface, u.curve, u.interval, pc) <= tol, "{what}: lifts"); + } + let iv = l[seam[0]].interval; + let mid = 0.5 * (iv[0] + iv[1]); + let (a, b) = (eval(&pcs[seam[0]], mid).unwrap(), eval(&pcs[seam[1]], mid).unwrap()); + let dom = SurfaceEval::new(surface).unwrap().domain(); + let period = dom.period[0].unwrap(); + assert!(((a[0] - b[0]).abs() - period).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "{what}: seam uses a period apart: {a:?} {b:?}"); + let (ends, area) = walk(l, pcs); + let n = l.len(); + for k in 0..n { + let (end, start) = (ends[k].1, ends[(k + 1) % n].0); + let free_u = pole == Some((k + 1) % n); + assert!((free_u || (end[0] - start[0]).abs() < 1e-9) && (end[1] - start[1]).abs() < 1e-9, "{what}: closes at {k}: {end:?} {start:?}"); + } + // At a pole `walk` cuts the corner (it joins each use's 16th sample to the next use's + // start, across the pole's line): a sliver of the box less. + let [u, v] = dom.range.map(|r| r.unwrap()); + let area = area / ((u.1 - u.0) * (v.1 - v.0)); + let least = if pole.is_some() { 0.9 } else { 1. - 1e-6 }; + assert!(area >= least && area < 1. + 1e-6, "{what}: counter-clockwise around the box: {area}"); + for pc in pcs { + let (Curve2::Spline { knots, .. } | Curve2::RationalSpline { knots, .. }) = pc; + for k in 0..=32 { + let t = knots[0] + (knots[knots.len() - 1] - knots[0]) * k as f64 / 32.; + let q = eval(pc, t).unwrap(); + assert!((u.0 - 1e-9..=u.1 + 1e-9).contains(&q[0]), "{what}: base period: {q:?}"); + } + } +} + +/// Splines closed on themselves in u (their first and last control rows the same) are periodic +/// there, one knot interval per period: a ring of a torus bounded by two circles and a seam used +/// twice (SMLib's fillet round a hole's rim), a NURBS cylinder, and a NURBS dome whose seam runs +/// into its pole. Each seam's uses come out a period apart, never both on u = 0. +#[test] +fn a_seam_on_a_spline_closed_in_u_gets_pcurves_a_period_apart() { + let full = [0., TAU]; + let (big, small) = (5., 1.); + // Each surface and circle on its NURBS form (`form`), as SolidCraft's builders give them. + let on = |c: &Curve, iv: [f64; 2]| crate::brep::form::curve(c, iv).unwrap(); + // The torus band: the tube's quarter from its outer equator to its top. + let torus = Surface::Torus { frame: about_z([0.; 3], false), major_radius: big, minor_radius: small, tube_start: 0.0 }; + let (band, _) = crate::brep::form::surface(&torus, [full, [0., FRAC_PI_2]]).unwrap(); + let outer = on(&Curve::Circle { frame: about_z([0.; 3], false), radius: big + small }, full); + let top = on(&Curve::Circle { frame: about_z([0., 0., small], false), radius: big }, full); + let quarter = on(&Curve::Circle { frame: frame([big, 0., 0.], [1., 0., 0.], [0., 0., 1.]), radius: small }, [0., FRAC_PI_2]); + let l = vec![ + EdgeUse { edge: 0, curve: &outer.0, interval: outer.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &quarter.0, interval: quarter.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 2, curve: &top.0, interval: top.1, forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &quarter.0, interval: quarter.1, forward: false, tolerance: 0.0, given: None }, + ]; + for tol in [1e-4, 1e-7] { + closes_around_the_box(&band, &l, [1, 3], None, tol, &format!("torus band, tol {tol}")); + } + // The cylinder: radius 3 from z = 0 to z = 4, its seam a line. + let (cylinder, _) = crate::brep::form::surface(&Surface::Cylinder { frame: about_z([0.; 3], false), radius: 3. }, [full, [0., 4.]]).unwrap(); + let low = on(&Curve::Circle { frame: about_z([0.; 3], false), radius: 3. }, full); + let high = on(&Curve::Circle { frame: about_z([0., 0., 4.], false), radius: 3. }, full); + let line = Curve::Line { start: [3., 0., 0.], end: [3., 0., 4.] }; + let l = vec![ + EdgeUse { edge: 0, curve: &low.0, interval: low.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &line, interval: [0., 1.], forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 2, curve: &high.0, interval: high.1, forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &line, interval: [0., 1.], forward: false, tolerance: 0.0, given: None }, + ]; + closes_around_the_box(&cylinder, &l, [1, 3], None, 1e-7, "cylinder"); + // The dome: radius 6 from its equator to its pole, the seam a meridian. + let (dome, _) = crate::brep::form::surface(&Surface::Sphere { frame: about_z([0.; 3], false), radius: 6. }, [full, [0., FRAC_PI_2]]).unwrap(); + let equator = on(&Curve::Circle { frame: about_z([0.; 3], false), radius: 6. }, full); + let meridian = on(&Curve::Circle { frame: frame([0.; 3], [1., 0., 0.], [0., 0., 1.]), radius: 6. }, [0., FRAC_PI_2]); + let l = vec![ + EdgeUse { edge: 0, curve: &equator.0, interval: equator.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &meridian.0, interval: meridian.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &meridian.0, interval: meridian.1, forward: false, tolerance: 0.0, given: None }, + ]; + closes_around_the_box(&dome, &l, [1, 2], Some(2), 1e-7, "dome"); + // A spline whose ends merely come near each other stays open: no period, so the seam's + // second use cannot be moved and the loop does not close around the box. + let Surface::RationalSpline { u_knots, v_knots, homogeneous } = &cylinder else { panic!("a rational spline") }; + let mut open = homogeneous.clone(); + open[8][0][1] += 1e-3; + let open = Surface::RationalSpline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), homogeneous: open }; + assert_eq!(SurfaceEval::new(&open).unwrap().domain().period, [None, None]); + assert_eq!(SurfaceEval::new(&cylinder).unwrap().domain().period, [Some(4.), None]); +} + +/// An intersection record evaluates to the point of both surfaces in the leader's normal +/// plane; it has no exact pcurve on either. +#[test] +fn intersection_curves_lie_on_both_surfaces() { + // The cylinder x² + y² = 25 cut by the plane z = 20 + x tan 0.4: an ellipse. + let cylinder = Surface::Cylinder { frame: about_z([0.; 3], false), radius: 5. }; + let k = 0.4f64.tan(); + let plane = Surface::Plane { origin: [0., 0., 20.], u_axis: [1., 0., k], v_axis: [0., 1., 0.] }; + // A coarse leader through points of the curve, its chords up to 0.03 mm off it. + let leader: Vec<[f64; 3]> = (0..=12) + .map(|i| { + let a = 0.2 + 2.5 * i as f64 / 12.; + [5. * a.cos(), 5. * a.sin(), 20. + 5. * a.cos() * k] + }) + .collect(); + let curve = Curve::SurfaceIntersection { + surfaces: [Box::new(cylinder.clone()), Box::new(plane.clone())], + leader: Box::new(Curve::Polyline { points: leader }), + tolerance: 0.2, + }; + let eval = CurveEval::new(&curve).unwrap(); + for i in 0..=48 { + let p = eval.point(12. * i as f64 / 48.).unwrap(); + assert!((p.x.hypot(p.y) - 5.).abs() < 1e-11 && (p.z - 20. - p.x * k).abs() < 1e-11, "{i}: {p:?}"); + } + // It has no closed-form pcurve on either surface (an intersection record is a construction, + // not a NURBS): refused, never fitted. + for surface in [&cylinder, &plane] { + assert!(matches!(pcurves(surface, &one(&curve, [0., 12.]), 1e-6), Err(Error::Failed(m)) if m.contains("no exact pcurve"))); + } +} + +/// A thread flank as a screw sweep leaves it: a spline strip winding twenty-two turns of pitch 1 about +/// z, rising from radius 3 to radius 4 by half the pitch, so one turn lies 0.89 mm from the next, +/// and its v = ½ line (its rows' midpoints on its u knots, so it lies on the strip). +fn thread_flank() -> (Surface, Curve) { + helical_strip([3., 4.], 0.5, 0.5) +} + +/// A spline strip winding twenty-two turns of pitch 1 about z from radius `r[0]` (v = 0) to `r[1]` +/// (v = 1), rising by `rise` across, and its line at v = `at` (its rows' points there on its u +/// knots, so it lies on the strip). +fn helical_strip(r: [f64; 2], rise: f64, at: f64) -> (Surface, Curve) { + // Control points 7.3 to a turn (161 over 22 turns), so the knots fall at other angles on + // each turn. + const PER_TURN: f64 = 7.3; + let n = 161; + let helix = |r: f64, rise: f64| -> Vec<[f64; 3]> { + (0..n) + .map(|i| { + let a = TAU * i as f64 / PER_TURN; + [r * a.cos(), r * a.sin(), a / TAU + rise] + }) + .collect() + }; + let (inner, outer) = (helix(r[0], 0.), helix(r[1], rise)); + let mut u_knots = vec![0.; 4]; + u_knots.extend((1..n - 3).map(|k| k as f64 / (n - 3) as f64)); + u_knots.extend([1.; 4]); + let surface = Surface::Spline { + u_knots: u_knots.clone(), + v_knots: vec![0., 0., 1., 1.], + points: inner.iter().zip(&outer).map(|(a, b)| vec![*a, *b]).collect(), + }; + let middle = + Curve::Spline { knots: u_knots, points: inner.iter().zip(&outer).map(|(a, b)| [0, 1, 2].map(|k| (1. - at) * a[k] + at * b[k])).collect() }; + (surface, middle) +} + +/// Edges along a surface winding several turns (the flank's middle line, from mid-turn to +/// mid-turn, and a short run of it) get pcurves on their own turn, never the next one. +#[test] +fn edges_on_a_spline_winding_several_turns_stay_on_their_turn() { + let (surface, middle) = thread_flank(); + for interval in [[0., 1.], [0.0625, 0.9375], [0.40625, 0.4375]] { + for tol in [1e-3, 1e-6] { + let pc = &pcurves(&surface, &one(&middle, interval), tol).unwrap()[0][0]; + let e = lift_error(&surface, &middle, interval, pc); + assert!(e <= tol, "{interval:?} at {tol}: {e}"); + } + } +} + +/// A thread's root band, 0.93 of the pitch tall, its turns 0.07 mm apart: an edge along its lower +/// rim (as where the root meets a shoulder) gets a pcurve on its own turn, though the rim of the +/// turn below passes nearer some of the search's starts than its own turn does. +#[test] +fn an_edge_along_the_rim_of_a_band_winding_close_to_itself_stays_on_its_turn() { + let (surface, rim) = helical_strip([5., 5.], 0.93, 0.); + // Short edges starting every 1/64 of a turn round one turn. + for k in 0..64 { + let t0 = 0.5 + f64::from(k) / (64. * 22.); + let interval = [t0, t0 + 1. / 64.]; + let pc = &pcurves(&surface, &one(&rim, interval), 2e-4).unwrap()[0][0]; + let e = lift_error(&surface, &rim, interval, pc); + assert!(e <= 2e-4, "{interval:?}: {e}"); + } +} + +/// A curve weaving across a thread flank, smooth through a knot of full multiplicity (one smooth +/// curve with the knot inserted three times, as SMLib's intersection curves come), has no +/// closed-form pcurve on the flank: it is refused, never fitted (SMLib gives its own trims). +#[test] +fn a_curve_weaving_across_a_thread_flank_is_refused() { + let (surface, _) = thread_flank(); + let s = SurfaceEval::new(&surface).unwrap(); + // Along the flank as it winds, a third of a turn (u = t), weaving a little across it. + let [a, b] = [0.40625, 0.4234375]; + let ts: Vec = (0..=12).map(|i| a + (b - a) * i as f64 / 12.).collect(); + let v = |t: f64| 0.5 + 0.02 * (3. * TAU * (t - a) / (b - a)).sin(); + let on: Vec<[f64; 3]> = ts.iter().map(|&t| s.point([t, v(t)]).unwrap()).map(|p| [p.x, p.y, p.z]).collect(); + let c = crate::bspline::CurveN::interpolate(&ts, &on, 3).unwrap(); + let k = 0.4167; + let (mut knots, mut ctrl) = (c.knots, c.ctrl.iter().map(|p| crate::bspline::HPoint::weighted(Vec3::from(*p), 1.)).collect::>()); + for _ in 0..3 { + (knots, ctrl) = crate::bspline::insert_knot(3, &knots, &ctrl, k).unwrap(); + } + let weave = Curve::Spline { knots, points: ctrl.iter().map(|h| h.project().unwrap()).map(|p| [p.x, p.y, p.z]).collect() }; + // A curve weaving across the flank has no closed-form pcurve there: refused, never fitted. + assert!(matches!(pcurves(&surface, &one(&weave, [a, b]), 1e-3), Err(Error::Failed(m)) if m.contains("no exact pcurve"))); +} + +/// Hostile records give errors, never a panic. +#[test] +fn hostile_records_give_errors() { + let plane = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }; + let line = Curve::Line { start: [0.; 3], end: [1., 0., 0.] }; + for tol in [0., -1., f64::NAN, f64::INFINITY, 1e9] { + assert!(matches!(pcurves(&plane, &one(&line, [0., 1.]), tol), Err(Error::Invalid(_))), "{tol}"); + } + for interval in [[1., 1.], [2., 1.], [f64::NAN, 1.], [0., f64::INFINITY], [0., 1e13]] { + assert!(matches!(pcurves(&plane, &one(&line, interval), 1e-6), Err(Error::Invalid(_))), "{interval:?}"); + } + let nan = Curve::Line { start: [f64::NAN, 0., 0.], end: [1., 0., 0.] }; + assert!(matches!(pcurves(&plane, &one(&nan, [0., 1.]), 1e-6), Err(Error::Invalid(_)))); + let skew = Surface::Cylinder { frame: frame([0.; 3], [1., 0., 0.], [0.5, 1., 0.]), radius: 1. }; + assert!(matches!(pcurves(&skew, &one(&line, [0., 1.]), 1e-6), Err(Error::Invalid(_)))); + let flat = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [2., 0., 0.] }; + assert!(matches!(pcurves(&flat, &one(&line, [0., 1.]), 1e-6), Err(Error::Invalid(_)))); + let collapsed = Curve::Circle { frame: about_z([0.; 3], false), radius: 0. }; + assert!(matches!(pcurves(&plane, &one(&collapsed, [0., 1.]), 1e-6), Err(Error::Invalid(_)))); + // Too many uses, refused before any work. + let many = vec![vec![EdgeUse { edge: 0, curve: &line, interval: [0., 1.], forward: true, tolerance: 0.0, given: None }; MAX_USES + 1]]; + assert!(matches!(pcurves(&plane, &many, 1e-6), Err(Error::TooLarge(_)))); + // A polyline of many points across a curved surface: it has no exact pcurve there, and is + // refused as such (nothing is fitted). + let cylinder = Surface::Cylinder { frame: about_z([0.; 3], false), radius: 1. }; + let n = 5000; + let zigzag = Curve::Polyline { points: (0..n).map(|i| [(i as f64 * 0.01).cos(), (i as f64 * 0.01).sin(), (i % 2) as f64]).collect() }; + assert!(matches!(pcurves(&cylinder, &one(&zigzag, [0., (n - 1) as f64]), 1e-6), Err(Error::Failed(m)) if m.contains("no exact pcurve"))); + // A degree the evaluators do not take. + let high = Curve::Spline { knots: [vec![0.; 10], vec![1.; 10]].concat(), points: (0..10).map(|i| [i as f64, 0., 0.]).collect() }; + assert!(matches!(pcurves(&cylinder, &one(&high, [0., 1.]), 1e-6), Err(Error::Failed(_)))); + // Off the surface, and a curve on two tangent surfaces (no single point). + assert!(matches!(pcurves(&cylinder, &one(&line, [0., 1.]), 1e-6), Err(Error::Failed(_)))); + let touching = Curve::SurfaceIntersection { + surfaces: [Box::new(cylinder.clone()), Box::new(Surface::Plane { origin: [1., 0., 0.], u_axis: [0., 1., 0.], v_axis: [0., 0., 1.] })], + leader: Box::new(Curve::Polyline { points: vec![[1., 0., 0.], [1., 0., 1.]] }), + tolerance: 1e-3, + }; + assert!(pcurves(&cylinder, &one(&touching, [0., 1.]), 1e-6).is_err()); + // Extreme but valid: a torus as wide as the schema allows and thin as it allows. + let torus = Surface::Torus { frame: about_z([0.; 3], false), major_radius: 1e12, minor_radius: 1e-12, tube_start: 0.0 }; + let far = Curve::Circle { frame: about_z([0.; 3], false), radius: 1e12 }; + let _ = pcurves(&torus, &one(&far, [0., 1.]), 1e-6); +} + +/// An edge that lies up to 7.5e-5 mm off its plane (another kernel's approximation) gets no +/// pcurve at the face's 1e-5 mm, and one within its own record tolerance of 2e-4 mm when the +/// use carries it. +#[test] +fn an_edge_is_fitted_to_its_own_tolerance() { + let plane = Surface::PlaneThrough { origin: [1., 2., 3.], u_point: [3., 2., 3.], v_point: [1., 2., 7.] }; + let off = + Curve::Spline { knots: vec![0., 0., 0., 0., 1., 1., 1., 1.], points: vec![[1., 2., 3.], [2., 2.0001, 4.], [3., 2.0001, 5.], [4., 2., 6.]] }; + assert!(pcurves(&plane, &one(&off, [0., 1.]), 1e-5).is_err()); + let own = vec![vec![EdgeUse { edge: 0, curve: &off, interval: [0., 1.], forward: true, tolerance: 2e-4, given: None }]]; + let pc = &pcurves(&plane, &own, 1e-5).unwrap()[0][0]; + assert!(lift_error(&plane, &off, [0., 1.], pc) <= 2e-4); +} diff --git a/crates/geom/src/brep/placement.rs b/crates/geom/src/brep/placement.rs new file mode 100644 index 000000000..52f4befe0 --- /dev/null +++ b/crates/geom/src/brep/placement.rs @@ -0,0 +1,152 @@ +//! A record moved by a rigid motion: a rotation and a translation. Every point, axis and control +//! point moves; every parameter, pcurve, tolerance, orientation and the canonical order stay as +//! they are, because a rigid motion keeps distances, angles and handedness. The moved record is +//! the same B-rep in other coordinates, exactly. Reflections and scalings change parameters or +//! geometry kinds; they are a kernel operation, not this. +use solidcore_record::brep::{Brep, Curve, Frame, Surface}; + +/// A rotation (rows of an orthonormal matrix with determinant +1) and a translation: +/// `p ↦ rotation · p + translation`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Rigid { + pub rotation: [[f64; 3]; 3], + pub translation: [f64; 3], +} + +/// How far the rotation may be from orthonormal (per entry of RᵀR − I) and its determinant from 1. +const ORTHONORMAL: f64 = 1e-9; + +impl Rigid { + /// The rigid motion of a column-major affine matrix (columns 0–2 the images of x, y and z, + /// column 3 the translation), or `None` when its linear part scales, shears or reflects. + pub fn of_matrix(m: &[[f64; 4]; 4]) -> Option { + if m.iter().flatten().any(|x| !x.is_finite()) || m[0][3] != 0.0 || m[1][3] != 0.0 || m[2][3] != 0.0 || m[3][3] != 1.0 { + return None; + } + let rotation = [[m[0][0], m[1][0], m[2][0]], [m[0][1], m[1][1], m[2][1]], [m[0][2], m[1][2], m[2][2]]]; + let column = |j: usize| [rotation[0][j], rotation[1][j], rotation[2][j]]; + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + for i in 0..3 { + for j in 0..3 { + let want = if i == j { 1.0 } else { 0.0 }; + if (dot(column(i), column(j)) - want).abs() > ORTHONORMAL { + return None; + } + } + } + let [a, b, c] = rotation; + let det = a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]); + ((det - 1.0).abs() <= ORTHONORMAL).then_some(Rigid { rotation, translation: [m[3][0], m[3][1], m[3][2]] }) + } + + fn direction(&self, d: [f64; 3]) -> [f64; 3] { + self.rotation.map(|row| row[0] * d[0] + row[1] * d[1] + row[2] * d[2]) + } + + fn point(&self, p: [f64; 3]) -> [f64; 3] { + let r = self.direction(p); + [r[0] + self.translation[0], r[1] + self.translation[1], r[2] + self.translation[2]] + } + + /// A homogeneous control point `[x w, y w, z w, w]`: the point moves, its weight stays. + fn homogeneous(&self, h: [f64; 4]) -> [f64; 4] { + let r = self.direction([h[0], h[1], h[2]]); + let w = h[3]; + [r[0] + w * self.translation[0], r[1] + w * self.translation[1], r[2] + w * self.translation[2], w] + } + + /// The column-major affine matrix of this motion. + fn matrix(&self) -> [[f64; 4]; 4] { + let (r, t) = (self.rotation, self.translation); + [[r[0][0], r[1][0], r[2][0], 0.0], [r[0][1], r[1][1], r[2][1], 0.0], [r[0][2], r[1][2], r[2][2], 0.0], [t[0], t[1], t[2], 1.0]] + } + + fn frame(&self, f: &Frame) -> Frame { + Frame { origin: self.point(f.origin), x_axis: self.direction(f.x_axis), y_axis: self.direction(f.y_axis) } + } + + fn curve(&self, c: &Curve) -> Curve { + match c { + Curve::Line { start, end } => Curve::Line { start: self.point(*start), end: self.point(*end) }, + Curve::Circle { frame, radius } => Curve::Circle { frame: self.frame(frame), radius: *radius }, + Curve::Ellipse { frame, radii } => Curve::Ellipse { frame: self.frame(frame), radii: *radii }, + Curve::Polyline { points } => Curve::Polyline { points: points.iter().map(|p| self.point(*p)).collect() }, + Curve::Spline { knots, points } => Curve::Spline { knots: knots.clone(), points: points.iter().map(|p| self.point(*p)).collect() }, + Curve::RationalSpline { knots, homogeneous } => { + Curve::RationalSpline { knots: knots.clone(), homogeneous: homogeneous.iter().map(|h| self.homogeneous(*h)).collect() } + } + Curve::SurfaceIntersection { surfaces, leader, tolerance } => Curve::SurfaceIntersection { + surfaces: [Box::new(self.surface(&surfaces[0])), Box::new(self.surface(&surfaces[1]))], + leader: Box::new(self.curve(leader)), + tolerance: *tolerance, + }, + } + } + + fn surface(&self, s: &Surface) -> Surface { + match s { + Surface::Plane { origin, u_axis, v_axis } => { + Surface::Plane { origin: self.point(*origin), u_axis: self.direction(*u_axis), v_axis: self.direction(*v_axis) } + } + Surface::PlaneThrough { origin, u_point, v_point } => { + Surface::PlaneThrough { origin: self.point(*origin), u_point: self.point(*u_point), v_point: self.point(*v_point) } + } + Surface::Cylinder { frame, radius } => Surface::Cylinder { frame: self.frame(frame), radius: *radius }, + Surface::Cone { frame, radius_at_origin, half_angle } => { + Surface::Cone { frame: self.frame(frame), radius_at_origin: *radius_at_origin, half_angle: *half_angle } + } + Surface::Sphere { frame, radius } => Surface::Sphere { frame: self.frame(frame), radius: *radius }, + Surface::BallPatch { center, radius } => Surface::BallPatch { center: self.point(*center), radius: *radius }, + Surface::Torus { frame, major_radius, minor_radius, tube_start } => { + Surface::Torus { frame: self.frame(frame), major_radius: *major_radius, minor_radius: *minor_radius, tube_start: *tube_start } + } + Surface::Spline { u_knots, v_knots, points } => Surface::Spline { + u_knots: u_knots.clone(), + v_knots: v_knots.clone(), + points: points.iter().map(|row| row.iter().map(|p| self.point(*p)).collect()).collect(), + }, + Surface::RationalSpline { u_knots, v_knots, homogeneous } => Surface::RationalSpline { + u_knots: u_knots.clone(), + v_knots: v_knots.clone(), + homogeneous: homogeneous.iter().map(|row| row.iter().map(|h| self.homogeneous(*h)).collect()).collect(), + }, + // The revolution's own placement is composed with the motion; profile and axis stay + // where the producer put them. + Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => Surface::PlacedRevolution { + profile: profile.clone(), + origin: *origin, + axis: *axis, + matrix: compose(&self.matrix(), matrix), + forward: *forward, + }, + } + } +} + +/// `a · b` of column-major 4×4 matrices. +fn compose(a: &[[f64; 4]; 4], b: &[[f64; 4]; 4]) -> [[f64; 4]; 4] { + let mut out = [[0.0; 4]; 4]; + for (col, out_col) in out.iter_mut().enumerate() { + for (row, cell) in out_col.iter_mut().enumerate() { + *cell = (0..4).map(|k| a[k][row] * b[col][k]).sum(); + } + } + out +} + +/// This record moved by `motion` (module docs): topology, parameters and pcurves unchanged. +pub fn moved(brep: &Brep, motion: &Rigid) -> Brep { + let mut out = brep.clone(); + for f in &mut out.faces { + f.surface = motion.surface(&f.surface); + f.nurbs = f.nurbs.as_ref().map(|n| motion.surface(n)); + } + for e in &mut out.edges { + e.curve = motion.curve(&e.curve); + e.nurbs = e.nurbs.as_ref().map(|n| motion.curve(n)); + } + for v in &mut out.vertices { + v.point = motion.point(v.point); + } + out +} diff --git a/crates/geom/src/brep/split.rs b/crates/geom/src/brep/split.rs new file mode 100644 index 000000000..6cab60ad3 --- /dev/null +++ b/crates/geom/src/brep/split.rs @@ -0,0 +1,116 @@ +//! Splitting a record's edges at parameters inside them, exactly: each piece keeps the edge's +//! curve on a sub-interval, a new vertex sits on the curve at each split, and every use of the +//! edge becomes uses of its pieces with the use's pcurve cut at the same parameters +//! ([`crate::bspline::segment`]: the same points at the same parameters). What a sheet needs so +//! that another sheet's vertex on one of its edges is a vertex of both (no T-junction). +use super::eval::CurveEval; +use crate::bspline::{HPoint, segment}; +use solidcore_record::brep::part::Part; +use solidcore_record::brep::{Brep, Curve2, Edge, Invalid, Loop, OrientedEdge, Result, Shell, Vertex}; + +/// The record with edge `e` split at each `t` of `at` (`(e, t)`, `t` strictly inside the edge's +/// interval), in canonical order. The part's `edges` name, for each edge, the source edge it is +/// (a piece of); its `vertices` the source vertex, or for a vertex made at a split +/// `brep.vertices.len()` plus its number among the splits (sorted by edge, then parameter). +pub fn split_edges(brep: &Brep, at: &[(u32, f64)]) -> Result { + let mut cuts: Vec> = vec![Vec::new(); brep.edges.len()]; + for &(e, t) in at { + let edge = brep.edges.get(e as usize).ok_or(Invalid("split edge reference"))?; + let [a, b] = edge.interval; + if !(t > a && t < b) { + return Err(Invalid("a split parameter is not inside its edge")); + } + cuts.get_mut(e as usize).ok_or(Invalid("split edge reference"))?.push(t); + } + // Each source edge's pieces: (new edge index, interval), and the new vertices. + let mut vertices: Vec = brep.vertices.clone(); + let mut edges: Vec = Vec::with_capacity(brep.edges.len() + at.len()); + let mut source: Vec = Vec::with_capacity(brep.edges.len() + at.len()); + let mut pieces: Vec> = Vec::with_capacity(brep.edges.len()); + for (e, (edge, ts)) in brep.edges.iter().zip(cuts.iter_mut()).enumerate() { + ts.sort_by(f64::total_cmp); + ts.dedup(); + let curve = if ts.is_empty() { None } else { Some(CurveEval::new(edge.parameters()).map_err(|_| Invalid("a split edge's curve"))?) }; + let [a, b] = edge.interval; + let mut ends = vec![edge.vertices[0]]; + for &t in ts.iter() { + let p = curve.as_ref().and_then(|c| c.point(t)).ok_or(Invalid("a split edge has no point there"))?; + ends.push(index(vertices.len())?); + vertices.push(Vertex { point: [p.x, p.y, p.z], tolerance: edge.tolerance }); + } + ends.push(edge.vertices[1]); + let bounds: Vec = std::iter::once(a).chain(ts.iter().copied()).chain(std::iter::once(b)).collect(); + let mut list = Vec::with_capacity(bounds.len() - 1); + for (k, w) in bounds.windows(2).enumerate() { + let interval = [w[0], w[1]]; + let (Some(&from), Some(&to)) = (ends.get(k), ends.get(k + 1)) else { return Err(Invalid("split ends")) }; + list.push((index(edges.len())?, interval)); + edges.push(Edge { interval, vertices: [from, to], uses: Vec::new(), ..edge.clone() }); + source.push(index(e)?); + } + pieces.push(list); + } + let piece_list = |e: u32| pieces.get(e as usize).ok_or(Invalid("split edge reference")); + let mut faces = brep.faces.clone(); + for face in &mut faces { + for l in &mut face.loops { + let Loop::Edges { edges: uses } = l else { continue }; + let mut out = Vec::with_capacity(uses.len()); + for u in uses.iter() { + let list = piece_list(u.edge)?; + let cut = |&(edge, [t0, t1]): &(u32, [f64; 2])| -> Result { + let pcurve = if list.len() == 1 { u.pcurve.clone() } else { cut_pcurve(&u.pcurve, t0, t1)? }; + Ok(OrientedEdge { edge, forward: u.forward, pcurve }) + }; + if u.forward { + for p in list { + out.push(cut(p)?); + } + } else { + for p in list.iter().rev() { + out.push(cut(p)?); + } + } + } + *uses = out; + } + } + let pieces_of = |wires: &[u32]| -> Result> { + Ok(wires.iter().map(|e| piece_list(*e)).collect::>>()?.into_iter().flatten().map(|p| p.0).collect()) + }; + let shells = brep + .shells + .iter() + .map(|s| { + Ok(match s { + Shell::Faces { faces, wires } => Shell::Faces { faces: faces.clone(), wires: pieces_of(wires)? }, + Shell::Wire { edges } => Shell::Wire { edges: pieces_of(edges)? }, + Shell::Vertex { vertex } => Shell::Vertex { vertex: *vertex }, + }) + }) + .collect::>>()?; + let loose = Brep { version: brep.version, tolerance: brep.tolerance, regions: brep.regions.clone(), shells, faces, edges, vertices }; + let mut part = loose.canonical()?; + for e in &mut part.edges { + *e = source.get(*e as usize).copied().ok_or(Invalid("split edge reference"))?; + } + Ok(part) +} + +/// A pcurve's piece on `[t0, t1]`, a sub-interval of its own. +fn cut_pcurve(c: &Curve2, t0: f64, t1: f64) -> Result { + let (knots, h): (&[f64], Vec) = match c { + Curve2::Spline { knots, points } => (knots, points.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: 1.0 }).collect()), + Curve2::RationalSpline { knots, homogeneous } => (knots, homogeneous.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: p[2] }).collect()), + }; + let degree = knots.len().checked_sub(h.len() + 1).ok_or(Invalid("pcurve degree"))?; + let (knots, h) = segment(degree, knots, &h, t0, t1).map_err(|_| Invalid("a pcurve cannot be cut there"))?; + Ok(match c { + Curve2::Spline { .. } => Curve2::Spline { knots, points: h.iter().map(|p| [p.x, p.y]).collect() }, + Curve2::RationalSpline { .. } => Curve2::RationalSpline { knots, homogeneous: h.iter().map(|p| [p.x, p.y, p.w]).collect() }, + }) +} + +fn index(i: usize) -> Result { + u32::try_from(i).map_err(|_| Invalid("split index")) +} diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs new file mode 100644 index 000000000..1cbbdb065 --- /dev/null +++ b/crates/geom/src/brep/tests.rs @@ -0,0 +1,747 @@ +use super::*; +use crate::prelude::*; +use solidcore_record::brep::*; +use std::f64::consts::{FRAC_PI_2, TAU}; + +fn segment(a: f64, b: f64) -> Curve2 { + Curve2::Spline { knots: vec![a, a, b, b], points: vec![[a, 0.], [b, 1.]] } +} +fn a_frame() -> Frame { + Frame { origin: [1., 2., 3.], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] } +} + +/// Every edge's uses as the canonical walk meets them (faces are all forward here). +fn list_uses(b: &mut Brep) { + for e in &mut b.edges { + e.uses.clear(); + } + for (fi, f) in b.faces.iter().enumerate() { + for (li, l) in f.loops.iter().enumerate() { + if let Loop::Edges { edges } = l { + for (p, u) in edges.iter().enumerate() { + let at = EdgeUseRef { face: fi as u32, r#loop: li as u32, position: p as u32, upper: !u.forward }; + b.edges[u.edge as usize].uses.push(at); + } + } + } + } +} + +/// Every analytic face and conic edge on its NURBS form, as producers make them: a face's form +/// over its stated domain, a circle about a face's axis labelled on its frame (`form::edge`). +fn on_forms(b: &mut Brep) { + let frames: Vec = b.faces.iter().filter(|f| f.nurbs.is_none()).filter_map(|f| form::frame_of(&f.surface)).collect(); + for f in &mut b.faces { + if f.nurbs.is_none() + && let Some((n, d)) = form::surface(&f.surface, f.domain) + { + (f.nurbs, f.domain) = (Some(n), d); + } + } + for e in &mut b.edges { + if e.nurbs.is_none() + && let Some((label, _, Some((n, iv)))) = form::edge(&e.curve, e.interval, &frames, b.tolerance) + { + (e.curve, e.nurbs, e.interval) = (label, Some(n), iv); + } + } +} + +/// Every oriented edge's pcurve from its face's surface and its edge (`pcurve::pcurves`). +fn fit_pcurves(b: &mut Brep) { + for f in &mut b.faces { + let loops: Vec>> = f + .loops + .iter() + .map(|l| match l { + Loop::Edges { edges } => edges + .iter() + .map(|u| { + let e = &b.edges[u.edge as usize]; + pcurve::EdgeUse { + edge: u.edge, + curve: e.parameters(), + interval: e.interval, + forward: u.forward, + tolerance: e.tolerance, + given: None, + } + }) + .collect(), + Loop::Vertex { .. } => vec![], + }) + .collect(); + let fitted = pcurve::pcurves_within(f.parameters(), &loops, 1e-7, Some(f.domain)).unwrap(); + for (l, pcs) in f.loops.iter_mut().zip(fitted) { + if let Loop::Edges { edges } = l { + for (u, pc) in edges.iter_mut().zip(pcs) { + u.pcurve = pc; + } + } + } + } +} + +/// Planar faces, one per vertex cycle, grouped into shells; edges and vertices numbered in +/// canonical order as the cycles first meet them. +fn faceted(points: &[[f64; 3]], shells: &[&[&[usize]]], regions: Vec) -> Brep { + let mut b = Brep { version: VERSION, tolerance: 1e-7, regions, shells: Vec::new(), faces: Vec::new(), edges: Vec::new(), vertices: Vec::new() }; + let mut vertex_of = vec![None; points.len()]; + let mut vertex = |b: &mut Brep, p: usize| -> u32 { + *vertex_of[p].get_or_insert_with(|| { + b.vertices.push(Vertex { point: points[p], tolerance: 1e-7 }); + b.vertices.len() as u32 - 1 + }) + }; + let mut by_pair = std::collections::HashMap::new(); + for cycles in shells { + let mut uses = Vec::new(); + for cycle in cycles.iter() { + let mut loop_ = Vec::new(); + for k in 0..cycle.len() { + let (a, z) = (cycle[k], cycle[(k + 1) % cycle.len()]); + let (edge, forward) = match by_pair.get(&(z, a)) { + Some(&e) => (e, false), + None => { + let vs = [vertex(&mut b, a), vertex(&mut b, z)]; + b.edges.push(Edge { + nurbs: None, + curve: Curve::Line { start: points[a], end: points[z] }, + interval: [0., 1.], + vertices: vs, + tolerance: 1e-7, + uses: vec![], + }); + let e = b.edges.len() as u32 - 1; + by_pair.insert((a, z), e); + (e, true) + } + }; + loop_.push(OrientedEdge { edge, forward, pcurve: segment(0., 1.) }); + } + uses.push(OrientedFace { face: b.faces.len() as u32, forward: true }); + // The plane through the cycle's first three points: its natural normal is the cycle's. + let [o, p, q] = [0, 1, 2].map(|k| points[cycle[k]]); + let axis = |a: [f64; 3]| [a[0] - o[0], a[1] - o[1], a[2] - o[2]]; + let surface = Surface::Plane { origin: o, u_axis: axis(p), v_axis: axis(q) }; + b.faces.push(Face { nurbs: None, surface, domain: [[-10., 10.], [-10., 10.]], loops: vec![Loop::Edges { edges: loop_ }] }); + } + b.shells.push(Shell::Faces { faces: uses, wires: vec![] }); + } + list_uses(&mut b); + fit_pcurves(&mut b); + b +} + +fn infinite(shells: Vec) -> Region { + Region { shells, void: false } +} +const SQUARE: [[f64; 3]; 4] = [[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.]]; +fn sheet() -> Brep { + faceted(&SQUARE, &[&[&[0, 1, 2, 3]]], vec![infinite(vec![0])]) +} +const TETRA: [[f64; 3]; 4] = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]; +const TETRA_FACES: [&[usize]; 4] = [&[0, 2, 1], &[0, 1, 3], &[1, 2, 3], &[0, 3, 2]]; +fn tetra() -> Brep { + faceted(&TETRA, &[&TETRA_FACES], vec![infinite(vec![0]), Region { shells: vec![0], void: false }]) +} +/// A tetrahedron with a tetrahedral void inside it. +fn hollow() -> Brep { + let mut points = TETRA.to_vec(); + points.extend(TETRA.map(|p| p.map(|x| 0.2 + 0.1 * x))); + let inner: Vec> = TETRA_FACES.iter().map(|c| c.iter().rev().map(|i| i + 4).collect()).collect(); + let inner: Vec<&[usize]> = inner.iter().map(Vec::as_slice).collect(); + faceted( + &points, + &[&TETRA_FACES, &inner], + vec![infinite(vec![0]), Region { shells: vec![0, 1], void: false }, Region { shells: vec![1], void: true }], + ) +} +/// The side of a cylinder: one face bounded by two circles and a seam edge used twice. +fn tube() -> Brep { + let f = a_frame(); + let circle = |z: f64| Curve::Circle { frame: Frame { origin: [1., 2., 3. + z], ..f.clone() }, radius: 2. }; + let edge = |curve, interval, vertices| Edge { nurbs: None, curve, interval, vertices, tolerance: 1e-7, uses: vec![] }; + let mut b = Brep { + version: VERSION, + tolerance: 1e-7, + regions: vec![infinite(vec![0])], + shells: vec![Shell::Faces { faces: vec![OrientedFace { face: 0, forward: true }], wires: vec![] }], + faces: vec![Face { + nurbs: None, + surface: Surface::Cylinder { frame: f.clone(), radius: 2. }, + domain: [[0., TAU], [0., 5.]], + loops: vec![Loop::Edges { + edges: vec![ + OrientedEdge { edge: 0, forward: true, pcurve: segment(0., TAU) }, + OrientedEdge { edge: 1, forward: true, pcurve: segment(0., 1.) }, + OrientedEdge { edge: 2, forward: false, pcurve: segment(0., TAU) }, + OrientedEdge { edge: 1, forward: false, pcurve: segment(0., 1.) }, + ], + }], + }], + edges: vec![ + edge(circle(0.), [0., TAU], [0, 0]), + edge(Curve::Line { start: [3., 2., 3.], end: [3., 2., 8.] }, [0., 1.], [0, 1]), + edge(circle(5.), [0., TAU], [1, 1]), + ], + vertices: vec![Vertex { point: [3., 2., 3.], tolerance: 1e-7 }, Vertex { point: [3., 2., 8.], tolerance: 1e-7 }], + }; + list_uses(&mut b); + on_forms(&mut b); + fit_pcurves(&mut b); + b +} +/// One face on `surface` bounded by one loop of `uses` (edge index, forward), each edge's +/// pcurves fitted, as an open sheet. +fn one_face(surface: Surface, domain: [[f64; 2]; 2], edges: Vec<(Curve, [f64; 2], [u32; 2])>, vertices: &[[f64; 3]], uses: &[(u32, bool)]) -> Brep { + let mut b = Brep { + version: VERSION, + tolerance: 1e-7, + regions: vec![infinite(vec![0])], + shells: vec![Shell::Faces { faces: vec![OrientedFace { face: 0, forward: true }], wires: vec![] }], + faces: vec![Face { + nurbs: None, + surface, + domain, + loops: vec![Loop::Edges { edges: uses.iter().map(|&(edge, forward)| OrientedEdge { edge, forward, pcurve: segment(0., 1.) }).collect() }], + }], + edges: edges + .into_iter() + .map(|(curve, interval, vertices)| Edge { nurbs: None, curve, interval, vertices, tolerance: 1e-7, uses: vec![] }) + .collect(), + vertices: vertices.iter().map(|&point| Vertex { point, tolerance: 1e-7 }).collect(), + }; + list_uses(&mut b); + on_forms(&mut b); + fit_pcurves(&mut b); + b +} +/// A ring of a torus on its NURBS form, closed in u (first and last control rows the same), as +/// SMLib holds the fillet round a hole's rim: bounded by its two circles and the tube's quarter +/// at u = 0, a seam used twice, each on its form. +fn closed_band() -> Brep { + let (big, small) = (5., 1.); + let torus = Surface::Torus { + frame: Frame { origin: [0., 0., 0.], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, + major_radius: big, + minor_radius: small, + tube_start: 0.0, + }; + let about = |z: f64| Frame { origin: [0., 0., z], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; + let quarter = Curve::Circle { frame: Frame { origin: [big, 0., 0.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, radius: small }; + one_face( + torus, + [[0., TAU], [0., FRAC_PI_2]], + vec![ + (Curve::Circle { frame: about(0.), radius: big + small }, [0., TAU], [0, 0]), + (quarter, [0., FRAC_PI_2], [0, 1]), + (Curve::Circle { frame: about(small), radius: big }, [0., TAU], [1, 1]), + ], + &[[big + small, 0., 0.], [big, 0., small]], + &[(0, true), (1, true), (2, false), (1, false)], + ) +} +/// A whole sphere bounded by one meridian from pole to pole, used twice: a closed shell. +fn ball() -> Brep { + let meridian = Curve::Circle { frame: Frame { origin: [1., 2., 3.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, radius: 2. }; + let mut b = one_face( + Surface::Sphere { frame: a_frame(), radius: 2. }, + [[0., TAU], [-FRAC_PI_2, FRAC_PI_2]], + vec![(meridian, [-FRAC_PI_2, FRAC_PI_2], [0, 1])], + &[[1., 2., 1.], [1., 2., 5.]], + &[(0, true), (0, false)], + ); + b.regions.push(Region { shells: vec![0], void: false }); + b +} +/// The sheet with a vertex loop inside it, a wire shell and a vertex shell beside it. +fn sheet_with_lower_forms() -> Brep { + let mut b = sheet(); + let n = b.vertices.len() as u32; + // Vertex order: edge vertices first (the wire edge's), then the vertex loop's, then the shell's. + b.vertices.extend([[2., 0., 0.], [3., 0., 0.], [0.5, 0.5, 0.], [5., 5., 5.]].map(|point| Vertex { point, tolerance: 1e-7 })); + b.edges.push(Edge { + nurbs: None, + curve: Curve::Line { start: [2., 0., 0.], end: [3., 0., 0.] }, + interval: [0., 1.], + vertices: [n, n + 1], + tolerance: 1e-7, + uses: vec![], + }); + b.faces[0].loops.push(Loop::Vertex { vertex: n + 2 }); + b.shells.push(Shell::Wire { edges: vec![4] }); + b.shells.push(Shell::Vertex { vertex: n + 3 }); + b.regions[0].shells.extend([1, 2]); + b +} + +#[test] +fn every_form_validates_and_round_trips_without_a_kernel() { + for (name, body) in [ + ("sheet", sheet()), + ("closed", tetra()), + ("void", hollow()), + ("seam", tube()), + ("seam on a closed spline", closed_band()), + ("seam from pole to pole", ball()), + ("lower forms", sheet_with_lower_forms()), + ] { + check::validate(&body).unwrap_or_else(|e| panic!("{name}: {e}")); + geometry::check(&body).unwrap_or_else(|e| panic!("{name}: {e}")); + let bytes = serde_json::to_vec(&body).unwrap(); + let restored: Brep = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body, restored, "{name}"); + assert!(!String::from_utf8(bytes).unwrap().contains("truck")); + } +} + +/// One defect each on a record with NURBS forms; every one is refused (the rest are the +/// record's own tests). +#[test] +fn one_defect_fixtures_on_forms_are_refused() { + let cases: Vec<(&str, &str, Brep)> = vec![ + ("pcurve interval", "pcurve interval differs from its edge's", { + let mut b = tube(); + if let Loop::Edges { edges } = &mut b.faces[0].loops[0] { + edges[0].pcurve = segment(0., TAU - 1e-3); + } + b + }), + ("edge interval past its form", "parameter interval outside the natural domain", { + let mut b = tube(); + b.edges[0].interval = [0., 4.1]; + b + }), + ("face domain outside the sphere", "parameter interval outside the natural domain", { + let mut b = sheet(); + formed(&mut b, Surface::Sphere { frame: a_frame(), radius: 2. }, [[0., TAU], [-FRAC_PI_2, FRAC_PI_2]]); + b.faces[0].domain[1][0] -= 0.1; + b + }), + ("face domain past its form", "parameter interval outside the natural domain", { + let mut b = tube(); + b.faces[0].domain[0] = [0., 4.1]; + b + }), + ("cone domain past its apex", "parameter interval outside the natural domain", { + let mut b = sheet(); + formed(&mut b, Surface::Cone { frame: a_frame(), radius_at_origin: 1., half_angle: 0.25 * std::f64::consts::PI }, [[0., 1.], [-1., 1.]]); + b.faces[0].domain[1][0] = -2.; + b + }), + ]; + for (name, expected, body) in cases { + let error = check::validate(&body).err().unwrap_or_else(|| panic!("{name} was accepted")); + assert_eq!(error.0, expected, "{name}"); + } +} + +/// Face 0 relabelled `surface` on its NURBS form over `domain` (its loops left as they were). +fn formed(b: &mut Brep, surface: Surface, domain: [[f64; 2]; 2]) { + let (nurbs, domain) = form::surface(&surface, domain).expect("a form"); + let f = &mut b.faces[0]; + (f.surface, f.nurbs, f.domain) = (surface, Some(nurbs), domain); +} +fn pcurve_of(b: &mut Brep, face: usize, position: usize) -> &mut Curve2 { + let Loop::Edges { edges } = &mut b.faces[face].loops[0] else { panic!("an edge loop") }; + &mut edges[position].pcurve +} +fn shift(c: &mut Curve2, by: [f64; 2]) { + match c { + Curve2::Spline { points, .. } => points.iter_mut().for_each(|p| *p = [p[0] + by[0], p[1] + by[1]]), + Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter_mut().for_each(|h| *h = [h[0] + by[0] * h[2], h[1] + by[1] * h[2], h[2]]), + } +} + +/// A pcurve whose interval ends a rounding short of its edge's (as a kernel that snaps an edge's +/// end to its knot hands it back) is read at its end: the record validates and checks. +#[test] +fn a_pcurve_a_rounding_short_of_its_edge_is_read_at_its_end() { + let mut b = sheet(); + let Curve2::Spline { knots, .. } = pcurve_of(&mut b, 0, 0) else { panic!("a spline pcurve") }; + let end = *knots.last().unwrap(); + let short = end - 1e-11 * end.abs().max(1.0); + for k in knots.iter_mut().filter(|k| **k == end) { + *k = short; + } + check::validate(&b).unwrap(); + geometry::check(&b).unwrap(); +} + +/// One geometric defect each, structurally valid: every one is refused, naming the record. +#[test] +fn geometric_defects_are_refused_by_record() { + use geometry::{Problem, Record}; + let off = |what| move |p: &Problem| matches!(p, Problem::Off { what: w, .. } if *w == what); + let cases: Vec<(&str, Record, Box bool>, Brep)> = vec![ + ("vertex off its curve's start", Record::Edge(0), Box::new(off("curve start misses its start vertex")), { + let mut b = sheet(); + b.vertices[0].point = [0., 0., 0.01]; + b + }), + ("vertex off its curve's end", Record::Edge(0), Box::new(off("curve end misses its end vertex")), { + let mut b = sheet(); + b.edges[0].curve = Curve::Line { start: SQUARE[0], end: [1., 0., 0.01] }; + b + }), + ("pcurve shifted off its edge", Record::Use { face: 0, r#loop: 0, position: 1 }, Box::new(off("pcurve start lifts off its edge's curve")), { + let mut b = sheet(); + shift(pcurve_of(&mut b, 0, 1), [0., 0.1]); + b + }), + ("pcurve bowed off its edge", Record::Use { face: 0, r#loop: 0, position: 0 }, Box::new(off("pcurve middle lifts off its edge's curve")), { + let mut b = sheet(); + let pc = pcurve_of(&mut b, 0, 0); + let (a, z) = (pcurve::eval(pc, 0.).unwrap(), pcurve::eval(pc, 1.).unwrap()); + let middle = [0.5 * (a[0] + z[0]), 0.5 * (a[1] + z[1]) + 0.1]; + *pc = Curve2::Spline { knots: vec![0., 0., 0., 1., 1., 1.], points: vec![a, middle, z] }; + b + }), + ( + "seam pcurve on the wrong period", + Record::Use { face: 0, r#loop: 0, position: 1 }, + Box::new(|p: &Problem| matches!(p, Problem::Period { .. })), + { + // One turn of the tube's NURBS form is four quarters. + let mut b = tube(); + shift(pcurve_of(&mut b, 0, 1), [4., 0.]); + b + }, + ), + ("vertex loop off its surface", Record::VertexLoop { face: 0, r#loop: 1 }, Box::new(off("vertex lies off its face's surface")), { + let mut b = sheet_with_lower_forms(); + b.vertices[6].point[2] = 0.01; + b + }), + ( + "seam uses of a closed spline on one line", + Record::Use { face: 0, r#loop: 0, position: 1 }, + // On the ring's NURBS form one turn is four quarters. + Box::new(|p: &Problem| *p == Problem::Period { gap: 4., period: 4. }), + { + let mut b = closed_band(); + shift(pcurve_of(&mut b, 0, 1), [-4., 0.]); + b + }, + ), + ( + "seam from pole to pole on one line", + Record::Loop { face: 0, r#loop: 0 }, + Box::new(|p: &Problem| { + matches!(p, Problem::Empty { area } if area.abs() < 1e-9) && p.to_string().starts_with("loop encloses no (u, v) area (signed area ") + }), + { + let mut b = ball(); + let mid = |b: &mut Brep, k: usize| pcurve::eval(pcurve_of(b, 0, k), 0.).unwrap()[0]; + let by = mid(&mut b, 0) - mid(&mut b, 1); + // On the sphere's NURBS form one turn is four quarters. + assert!((by.abs() - 4.).abs() < 1e-9, "a period apart: {by}"); + shift(pcurve_of(&mut b, 0, 1), [by, 0.]); + b + }, + ), + ( + "outer loop clockwise", + Record::Loop { face: 0, r#loop: 0 }, + Box::new(|p: &Problem| { + matches!(p, Problem::Turn { outer: true, area } if (*area + 1.).abs() < 1e-12) + && p.to_string() == "outer loop runs clockwise in (u, v) (signed area -1)" + }), + { + // The plane's axes swapped turn its natural normal over: the loop, unchanged in + // space, runs clockwise about it. + let mut b = sheet(); + if let Surface::Plane { u_axis, v_axis, .. } = &mut b.faces[0].surface { + std::mem::swap(u_axis, v_axis); + } + fit_pcurves(&mut b); + b + }, + ), + ]; + for (name, record, problem, body) in cases { + check::validate(&body).unwrap_or_else(|e| panic!("{name}: structurally valid: {e}")); + let error = geometry::check(&body).err().unwrap_or_else(|| panic!("{name} was accepted")); + assert_eq!(error.record, record, "{name}: {error}"); + assert!(problem(&error.problem), "{name}: {error}"); + } +} + +/// Records `validate` would refuse, checked anyway: errors, never panics. +#[test] +fn hostile_records_never_panic_the_geometry_check() { + let mut cases: Vec = Vec::new(); + let mut b = sheet(); + b.vertices[0].point = [f64::NAN; 3]; + cases.push(b); + let mut b = sheet(); + b.edges[0].vertices = [u32::MAX; 2]; + cases.push(b); + let mut b = sheet(); + if let Loop::Edges { edges } = &mut b.faces[0].loops[0] { + edges[2].edge = u32::MAX; + } + cases.push(b); + let mut b = sheet(); + shift(pcurve_of(&mut b, 0, 0), [f64::NAN, 0.]); + cases.push(b); + let mut b = sheet(); + *pcurve_of(&mut b, 0, 3) = Curve2::Spline { knots: vec![], points: vec![] }; + cases.push(b); + let mut b = sheet(); + b.edges[1].interval = [f64::NEG_INFINITY, f64::INFINITY]; + cases.push(b); + let mut b = sheet_with_lower_forms(); + b.faces[0].loops[1] = Loop::Vertex { vertex: u32::MAX }; + cases.push(b); + let mut b = tube(); + if let Some(Surface::RationalSpline { homogeneous, .. }) = &mut b.faces[0].nurbs { + homogeneous[0][0][0] = f64::NAN; + } + cases.push(b); + let mut b = tube(); + b.edges[0].tolerance = f64::NAN; + cases.push(b); + let mut b = sheet(); + let circle = Box::new(Curve::Circle { frame: a_frame(), radius: 1. }); + let identity = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; + b.faces[0].surface = Surface::PlacedRevolution { profile: circle, origin: [0.; 3], axis: [0., 0., 1.], matrix: identity, forward: true }; + cases.push(b); + for (i, b) in cases.iter().enumerate() { + let checked = std::panic::catch_unwind(|| geometry::check(b)); + assert!(matches!(checked, Ok(Err(_))), "case {i}: {checked:?}"); + } +} + +/// The record's geometric records the kernel checks, which the record's structural validation +/// leaves alone: frames, planes, placements and a cone's apex. +#[test] +fn frames_planes_placements_and_apexes_are_the_kernels() { + let f = a_frame(); + let mut skewed = f.clone(); + skewed.y_axis = skewed.x_axis; + assert!(check::frame(&f).is_ok()); + assert_eq!(check::frame(&skewed).map_err(|e| e.0), Err("nonorthonormal frame")); + let p = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [2., 0., 0.] }; + assert_eq!(check::surface(&p).map_err(|e| e.0), Err("degenerate plane")); + let line = Box::new(Curve::Line { start: [0.; 3], end: [1.; 3] }); + let identity = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; + let s = Surface::PlacedRevolution { profile: line.clone(), origin: [0.; 3], axis: [0., 0., 1.], matrix: identity, forward: false }; + check::surface(&s).unwrap(); + assert_eq!(label::surface_natural(&s), [Natural::Periodic, UNBOUNDED]); + let mut flat = identity; + flat[2] = [0.; 4]; + let bad = Surface::PlacedRevolution { profile: line, origin: [0.; 3], axis: [0., 0., 1.], matrix: flat, forward: true }; + assert_eq!(check::surface(&bad).map_err(|e| e.0), Err("singular revolution placement")); + // A cone narrowing along z (a negative half angle, as SMLib makes them) lies below its apex. + let apex = 2. / 0.2f64.tan(); + let narrowing = Surface::Cone { frame: f, radius_at_origin: 2., half_angle: -0.2 }; + assert_eq!(label::surface_natural(&narrowing)[1], Natural::Range(f64::NEG_INFINITY, apex)); + // A record with a skewed frame is structurally valid, and refused by the kernel's check. + let mut b = tube(); + let Surface::Cylinder { frame, .. } = &mut b.faces[0].surface else { panic!("a cylinder") }; + frame.y_axis = frame.x_axis; + b.validate().unwrap(); + assert_eq!(check::validate(&b).map_err(|e| e.0), Err("nonorthonormal frame")); +} + +/// A cylinder face round its axis with a hole beside its seam: the seam at 350 degrees (so its +/// loop projects from 350 degrees on), the hole at 15..25 degrees (which on its own projects a +/// turn below). The face's box is the outer loop's turn with the hole in it; the hole's own +/// placement made a box from 15 degrees that cut the turn short and left the seam outside it +/// (#4598: a bored rod read back with its bore's pcurve a period off its face). +#[test] +fn a_hole_beside_the_seam_lies_in_its_face_turn() { + let (r, h) = (20.0f64, 60.0); + let cylinder = Surface::Cylinder { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; + let s = -10f64.to_radians(); + let at = |a: f64, z: f64| [r * a.cos(), r * a.sin(), z]; + let ring = + |z: f64| Curve::Circle { frame: Frame { origin: [0., 0., z], x_axis: [s.cos(), s.sin(), 0.], y_axis: [-s.sin(), s.cos(), 0.] }, radius: r }; + let (bottom, top) = (ring(0.), ring(h)); + let seam = Curve::Line { start: at(s, 0.), end: at(s, h) }; + let (a0, a1) = (15f64.to_radians(), 25f64.to_radians()); + let hole = + Curve::Spline { knots: vec![0., 0., 1., 2., 3., 4., 4.], points: vec![at(a0, 25.), at(a1, 25.), at(a1, 35.), at(a0, 35.), at(a0, 25.)] }; + let outer = vec![(&bottom, [0., TAU], true), (&seam, [0., 1.], true), (&top, [0., TAU], false), (&seam, [0., 1.], false)]; + let inner = vec![(&hole, [0., 4.], true)]; + let [u, v] = form::extent(&cylinder, &[outer, inner]).expect("an extent"); + assert!((u[1] - u[0] - TAU).abs() < 1e-9, "one turn: {u:?}"); + assert!((u[0].rem_euclid(TAU) - s.rem_euclid(TAU)).abs() < 1e-9, "from the seam: {u:?}"); + let hole_u = a0 + ((u[0] - a0) / TAU).ceil() * TAU; + assert!(hole_u > u[0] && hole_u + (a1 - a0) < u[1], "the hole in the turn: {u:?}"); + assert!(v[0].abs() < 1e-9 && (v[1] - h).abs() < 1e-9, "{v:?}"); +} + +/// A hemisphere bounded by its rim and its seam, its loop starting a quarter turn along the rim +/// (the order a re-imported dimple's loop came in): along the rim to the seam, down the seam to +/// the pole, up it on the other side and round the rest of the rim. Through the pole the loop goes +/// on a turn away; continuing from the point before the pole put the seam's second use on the +/// first and the box a quarter turn off the seam (oracle 14: the re-imported face's form over +/// -270..90 degrees, its pcurves over 0..360, and its area a quarter short). +#[test] +fn a_loop_through_a_pole_closes_its_turn_from_the_seam() { + let r = 15.0f64; + let sphere = Surface::Sphere { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; + let rim = Curve::Circle { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; + let seam = Curve::Circle { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 0., -1.] }, radius: r }; + let outer = + vec![(&rim, [0., FRAC_PI_2], false), (&seam, [0., FRAC_PI_2], true), (&seam, [0., FRAC_PI_2], false), (&rim, [FRAC_PI_2, TAU], false)]; + let [u, v] = form::extent(&sphere, &[outer]).expect("an extent"); + assert!((u[1] - u[0] - TAU).abs() < 1e-9, "one turn: {u:?}"); + let from = u[0].rem_euclid(TAU); + assert!(from.min(TAU - from) < 1e-9, "from the seam: {u:?}"); + assert!((v[0] + FRAC_PI_2).abs() < 1e-9 && v[1].abs() < 1e-9, "{v:?}"); +} + +/// A face's box reaches its boundary's extremes, not its samples' nearest ones: an ellipse cut +/// from a cylinder of radius 20 by a plane at 45 degrees rises 20 above its centre, at an angle +/// between the points the box is sampled at. Short of it, the face's NURBS form stopped below the +/// edge (#4598: the bore of a re-imported rod ended 2.3e-4 short of where it meets the rod). +#[test] +fn a_face_box_reaches_its_boundary_extremes() { + let r = 20.0f64; + let cylinder = Surface::Cylinder { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; + let c = std::f64::consts::FRAC_1_SQRT_2; + let cut = Curve::Ellipse { frame: Frame { origin: [0., 0., 30.], x_axis: [c, 0., c], y_axis: [0., 1., 0.] }, radii: [r * 2f64.sqrt(), r] }; + let [_, v] = form::extent(&cylinder, &[vec![(&cut, [0.1, 0.1 + TAU], true)]]).expect("an extent"); + assert!((v[0] - 10.0).abs() < 1e-9 && (v[1] - 50.0).abs() < 1e-9, "{v:?}"); +} + +/// A point next to a sphere's pole is a pole to within the reach it is given: crossing half a +/// turn of longitude there moves it about π times its distance from the axis, and no further. +#[test] +fn a_point_beside_a_pole_is_one_within_its_reach() { + let sphere = eval::SurfaceEval::new(&Surface::Sphere { frame: a_frame(), radius: 2. }).unwrap(); + let near = [0.3, FRAC_PI_2 - 1e-7]; + // 2e-7 mm from the axis: half a turn moves it 2π·1e-7. + assert_eq!(sphere.pole(near), [false, false]); + assert_eq!(sphere.pole_within(near, 1e-6), [true, false]); + assert_eq!(sphere.pole_within(near, 1e-7), [false, false]); + assert_eq!(sphere.pole_within([0.3, 0.2], 1e-3), [false, false]); +} + +/// The analytic surfaces' partials up to the fourth order agree with their first and second +/// derivatives and are each the derivative of the order below (central differences). +#[test] +fn analytic_partials_are_the_derivatives_of_the_order_below() { + use crate::tess::partials::MAX_PARTIAL_ORDER; + let f = Frame { origin: [1., 2., 3.], x_axis: [0.6, 0.8, 0.], y_axis: [0., 0., 1.] }; + let surfaces = [ + Surface::Cylinder { frame: f.clone(), radius: 3. }, + Surface::Cone { frame: f.clone(), radius_at_origin: 2., half_angle: 0.3 }, + Surface::Sphere { frame: f.clone(), radius: 4. }, + Surface::Torus { frame: f.clone(), major_radius: 5., minor_radius: 1.5, tube_start: 0.0 }, + ]; + let (u, v, h) = (0.8, 0.4, 1e-4); + let close = |a: solidcore_record::Vec3, b: solidcore_record::Vec3, tol: f64| a.dist(b) <= tol * (1.0 + a.len().max(b.len())); + for s in &surfaces { + let e = eval::SurfaceEval::new(s).unwrap(); + let d = e.partials(u, v).unwrap(); + let (p, su, sv) = e.derivs(u, v).unwrap(); + let (suu, suv, svv) = e.second(u, v).unwrap(); + for (a, b) in [(d[0][0], p), (d[1][0], su), (d[0][1], sv), (d[2][0], suu), (d[1][1], suv), (d[0][2], svv)] { + assert!(close(a, b, 1e-12), "{s:?}: {a:?} vs {b:?}"); + } + let (up, um, vp, vm) = + (e.partials(u + h, v).unwrap(), e.partials(u - h, v).unwrap(), e.partials(u, v + h).unwrap(), e.partials(u, v - h).unwrap()); + for i in 0..MAX_PARTIAL_ORDER { + for j in 0..MAX_PARTIAL_ORDER - i { + assert!(close((up[i][j] - um[i][j]) * (0.5 / h), d[i + 1][j], 1e-6), "{s:?} d/du ({i},{j})"); + assert!(close((vp[i][j] - vm[i][j]) * (0.5 / h), d[i][j + 1], 1e-6), "{s:?} d/dv ({i},{j})"); + } + } + } +} + +/// A curve's curvature vector, exactly, on every kind of record: a circle's is 1/R towards its +/// centre (as a conic and as SMLib's rational quadratic B-spline of it); an ellipse's at its +/// vertices is a/b² and b/a²; a line is straight; and the circle where a plane z = 3 cuts a +/// sphere of radius 5 about the origin, traced from a rough leader, has radius 4. +#[test] +fn curve_jets_are_exact_on_every_record() { + use solidcore_record::Vec3; + let near = |a: Vec3, b: Vec3| a.dist(b) <= 1e-9 * (1.0 + b.len()); + let jet = |c: &Curve, t: f64| eval::CurveEval::new(c).unwrap().jet(t).unwrap(); + let flat = Frame { origin: [1., 2., 3.], x_axis: [0.6, 0.8, 0.], y_axis: [-0.8, 0.6, 0.] }; + let o = Vec3::new(1., 2., 3.); + for t in [0.0, 0.7, 2.5, 5.9] { + let j = jet(&Curve::Circle { frame: flat.clone(), radius: 4. }, t); + assert!(near(j.curvature, (o - j.point) * (1.0 / 16.0)), "{j:?}"); + assert!(j.tangent.dot(j.curvature).abs() < 1e-12); + } + // A quarter circle of radius 2 as a rational quadratic. + let w = std::f64::consts::FRAC_1_SQRT_2; + let quarter = + Curve::RationalSpline { knots: vec![0., 0., 0., 1., 1., 1.], homogeneous: vec![[2., 0., 0., 1.], [2. * w, 2. * w, 0., w], [0., 2., 0., 1.]] }; + for t in [0.0, 0.3, 0.5, 1.0] { + let j = jet(&quarter, t); + assert!(near(j.curvature, j.point * -0.25), "{t}: {j:?}"); + } + let (a, b) = (10.0, 4.0); + let ellipse = Curve::Ellipse { frame: flat.clone(), radii: [a, b] }; + assert!((jet(&ellipse, 0.0).curvature.len() - a / (b * b)).abs() < 1e-12); + assert!((jet(&ellipse, FRAC_PI_2).curvature.len() - b / (a * a)).abs() < 1e-12); + assert_eq!(jet(&Curve::Line { start: [0.; 3], end: [1., 2., 3.] }, 0.4).curvature, Vec3::ZERO); + // The plane z = 3 and a sphere of radius 5: a circle of radius 4 about (0, 0, 3). + let z = Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; + let leader = Curve::Polyline { points: (0..=12).map(|k| (k as f64 * TAU / 12.0).sin_cos()).map(|(s, c)| [4.1 * c, 4.1 * s, 3.2]).collect() }; + let cut = Curve::SurfaceIntersection { + surfaces: [ + Box::new(Surface::Plane { origin: [0., 0., 3.], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }), + Box::new(Surface::Sphere { frame: z, radius: 5. }), + ], + leader: Box::new(leader), + tolerance: 1e-6, + }; + for t in [0.0, 1.5, 4.25, 11.0] { + let j = jet(&cut, t); + let centre = Vec3::new(0., 0., 3.); + assert!((j.point.dist(centre) - 4.0).abs() < 1e-9 && (j.point.z - 3.0).abs() < 1e-12, "{j:?}"); + assert!(near(j.curvature, (centre - j.point) * (1.0 / 16.0)), "{t}: {j:?}"); + assert!(j.tangent.dot(j.point - centre).abs() < 1e-9); + } +} + +#[test] +fn a_form_on_arcs_of_its_own_is_the_surface_and_does_not_close_around_an_open_face() { + // A torus face round 280° of its tube: on the quarter grid it needs all four quarters, a form + // that closes on itself; on arcs of its own it starts where the face does and stops past + // where it ends. + let torus = Surface::Torus { frame: a_frame(), major_radius: 5., minor_radius: 1.5, tube_start: 0. }; + let label = [[0.3, 1.2], [-2.9, 2.0]]; + let tube = |s: &Surface| match s { + Surface::RationalSpline { v_knots, .. } => (v_knots.first().copied().unwrap(), v_knots.last().copied().unwrap()), + _ => panic!("not a NURBS: {s:?}"), + }; + let (grid, _) = form::surface(&torus, label).unwrap(); + assert_eq!(tube(&grid), (-2.0, 2.0), "the grid's form is the whole tube"); + let tol = 1e-3; + let (own, domain) = form::surface_on_own_arcs(&torus, label, tol).unwrap(); + let (v0, v1) = tube(&own); + assert_eq!((v0, v1), (0.0, 4.0)); + let (label_at, own_at) = (eval::SurfaceEval::new(&torus).unwrap(), eval::SurfaceEval::new(&own).unwrap()); + let u = domain[0][0]; + assert!(own_at.point([u, v0]).unwrap().dist(own_at.point([u, v1]).unwrap()) > 0.1, "the form does not close"); + // Every point of the form is on the torus: (√(x² + y²) − R)² + z² = r² in its frame. + for i in 0..=8 { + for j in 0..=12 { + let uv = [domain[0][0] + (domain[0][1] - domain[0][0]) * i as f64 / 8., v0 + (v1 - v0) * j as f64 / 12.]; + let p = own_at.point(uv).unwrap() - solidcore_record::Vec3::new(1., 2., 3.); + let off = ((p.x.hypot(p.y) - 5.).powi(2) + p.z.powi(2)).sqrt() - 1.5; + assert!(off.abs() < 1e-12, "{uv:?}: {off}"); + } + } + // Its domain is the face's: the corners land where the label's do, the form past them by the + // angle the tolerance makes. + for (a, b) in [(0, 0), (0, 1), (1, 0), (1, 1)] { + let (p, q) = (label_at.point([label[0][a], label[1][b]]).unwrap(), own_at.point([domain[0][a], domain[1][b]]).unwrap()); + assert!(p.dist(q) < 1e-9, "corner {a}{b}: {p:?} vs {q:?}"); + } + assert!(domain[1][0] > v0 && domain[1][1] < v1, "{domain:?}"); + // A whole turn stays on the grid (periodic), and a plane has no form. + let (whole, _) = form::surface_on_own_arcs(&torus, [[0.3, 1.2], [-FRAC_PI_2, -FRAC_PI_2 + TAU]], tol).unwrap(); + assert_eq!(tube(&whole), (-1.0, 3.0)); + assert!(form::surface_on_own_arcs(&Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }, label, tol).is_none()); +} diff --git a/crates/geom/src/bspline.rs b/crates/geom/src/bspline.rs index 8b2cf84f8..8e1dba073 100644 --- a/crates/geom/src/bspline.rs +++ b/crates/geom/src/bspline.rs @@ -13,10 +13,12 @@ use std::ops::{Add, AddAssign, Mul, Sub}; -use crate::Vec3; +use solidcore_record::Vec3; -/// Highest polynomial degree accepted in either direction. -pub const MAX_SPLINE_DEGREE: usize = 7; +/// Highest polynomial degree accepted in either direction: the B-rep record's own bound +/// (`Brep::validate`), so every spline a record may hold can be evaluated. A G4 blend is of +/// degree 9 (five conditions at each end). +pub const MAX_SPLINE_DEGREE: usize = solidcore_record::brep::MAX_SPLINE_DEGREE; /// Most knots accepted in one knot vector. pub const MAX_KNOTS: usize = 1 << 14; /// Most control points accepted in one tensor surface. @@ -161,6 +163,22 @@ pub fn local_basis(knots: &[f64], u: f64, side: Side, n: usize) -> Vec { out } +/// The `degree + 1` basis functions of a B-spline with `knots` and `count` control points alive +/// at `t`, with their derivatives up to `order`: the index of the first of them and, for each, +/// its value and derivatives (element `k` the `k`-th). Each comes from its own local knots +/// ([`local_basis`]), on the span used at `t` (the last non-empty span starting at or before it, +/// the domain's last span at its end, from the left). +pub fn basis_derivatives(knots: &[f64], degree: usize, count: usize, t: f64, order: usize) -> Option<(usize, Vec>)> { + if degree == 0 || count <= degree || knots.len() != count + degree + 1 || !t.is_finite() { + return None; + } + let span = crate::tess::span_of(knots, degree, count, t); + let side = if t >= *knots.get(count)? { Side::Left } else { Side::Right }; + let first = span.checked_sub(degree)?; + let ders = (first..=span).map(|i| Some(local_basis(knots.get(i..=i + degree + 1)?, t, side, order))).collect::>>()?; + Some((first, ders)) +} + /// [`local_basis`] into a fixed array (no allocation): element `k` is the `k`-th derivative, /// for `k ≤ min(n, MAX_SPLINE_DEGREE)`, the rest zero. pub(crate) fn local_basis_array(knots: &[f64], u: f64, side: Side, n: usize) -> [f64; MAX_SPLINE_DEGREE + 1] { @@ -287,16 +305,24 @@ pub fn basis_bezier(knots: &[f64], a: f64, b: f64) -> SplineResult> { Ok(out) } +/// Ulps of the domain's magnitude a parameter may lie past a spline's domain end and still be +/// that end ([`find_span`]): the rounding of an affine step, `a + (b − a)·s`, a few ulps at most. +pub const DOMAIN_ROUNDING: f64 = 8.0; + /// The span index `k` with `knots[k] ≤ u < knots[k+1]` among the valid spans `p ≤ k < n` -/// (`n` control points), the last span closed at the domain end (NURBS Book A2.1). +/// (`n` control points), the last span closed at the domain end (NURBS Book A2.1). A parameter +/// past an end of the domain by floating-point rounding only ([`DOMAIN_ROUNDING`]) is at that +/// end: `a + (b − a)·1`, the last of a range's even steps, may round one step past `b`. pub fn find_span(knots: &[f64], p: usize, n: usize, u: f64) -> Option { if n <= p || knots.len() != n + p + 1 || !u.is_finite() { return None; } let (lo, hi) = (*knots.get(p)?, *knots.get(n)?); - if u < lo || u > hi { + let slack = DOMAIN_ROUNDING * f64::EPSILON * lo.abs().max(hi.abs()).max(1.0); + if u < lo - slack || u > hi + slack { return None; } + let u = u.clamp(lo, hi); // The last non-empty span in [p, n−1] that starts at or before u: by bisection (the knots // are sorted), and at the domain end the last non-empty span. let mut k = if u >= hi { @@ -343,6 +369,46 @@ pub fn insert_knot(p: usize, knots: &[f64], ctrl: &[HPoint], u: f64) -> SplineRe Ok((nk, q)) } +/// The piece of a B-spline (degree `p`, knots, homogeneous control points) on `[a, b]`, a +/// sub-interval of its domain, as a clamped B-spline of its own whose domain is exactly +/// `[a, b]`: the same points at the same parameters. Exact up to rounding: Boehm insertion of +/// `a` and `b` until each has multiplicity `p` (NURBS Book §5.3, curve splitting), then the +/// knots and control points between them. +pub fn segment(p: usize, knots: &[f64], ctrl: &[HPoint], a: f64, b: f64) -> SplineResult<(Vec, Vec)> { + let n = ctrl.len(); + if n <= p || knots.len() != n + p + 1 { + return invalid("knot and control point counts do not match the degree"); + } + let (lo, hi) = (knots.get(p).copied().unwrap_or(f64::NAN), knots.get(n).copied().unwrap_or(f64::NAN)); + if !(lo <= a && a < b && b <= hi) { + return invalid(format!("[{a}, {b}] is not a piece of the domain [{lo}, {hi}]")); + } + let (mut k, mut c) = (knots.to_vec(), ctrl.to_vec()); + for t in [a, b] { + // At most p insertions each. + for _ in 0..p { + if k.iter().filter(|&&x| x == t).count() >= p { + break; + } + (k, c) = insert_knot(p, &k, &c, t)?; + } + } + // The curve at a (from the right) is control point j0 − p, j0 the last knot equal to a; + // at b (from the left) control point j1 − 1, j1 the first knot equal to b. + let j0 = k.iter().rposition(|&x| x == a).filter(|&j| j >= p).ok_or_else(|| SplineError::Invalid("segment start".into()))?; + let j1 = k.iter().position(|&x| x == b).filter(|&j| j > j0).ok_or_else(|| SplineError::Invalid("segment end".into()))?; + let points = c.get(j0 - p..j1).ok_or_else(|| SplineError::Invalid("segment control points".into()))?.to_vec(); + let inner = k.get(j0 + 1..j1).ok_or_else(|| SplineError::Invalid("segment knots".into()))?; + let mut out = Vec::with_capacity(inner.len() + 2 * p + 2); + out.extend(std::iter::repeat_n(a, p + 1)); + out.extend_from_slice(inner); + out.extend(std::iter::repeat_n(b, p + 1)); + if out.len() != points.len() + p + 1 { + return invalid("segment counts"); + } + Ok((out, points)) +} + /// The binomial coefficient `(n k)` (zero for `k > n`). pub(crate) fn binomial(n: usize, k: usize) -> f64 { if k > n { @@ -641,6 +707,7 @@ impl NurbsSurface { #[cfg(test)] pub(crate) mod tests { use super::*; + use crate::prelude::*; /// A small deterministic generator for test data. pub(crate) struct Lcg(pub(crate) u64); @@ -714,6 +781,49 @@ pub(crate) mod tests { assert_eq!(find_span(&knots, p, n, f64::NAN), None); } + #[test] + fn a_parameter_a_rounding_past_the_domain_end_is_the_end() { + // Poppy Humanoid's interval: the last even step, t0 + (t1 − t0)·1, rounds one ulp past t1. + let (t0, t1) = (0.013209624271103393f64, 1.2985843833752286f64); + let past = t0 + (t1 - t0) * 1.0; + assert!(past > t1); + let knots = [t0, t0, t0, t1, t1, t1]; + assert_eq!(find_span(&knots, 2, 3, past), find_span(&knots, 2, 3, t1)); + assert_eq!(find_span(&knots, 2, 3, t0 - f64::EPSILON), find_span(&knots, 2, 3, t0)); + // A parameter outside the domain by more than rounding is still none. + assert_eq!(find_span(&knots, 2, 3, t1 + 1e-9), None); + } + + #[test] + fn a_segment_is_the_same_curve_on_its_interval() { + use crate::brep::eval::CurveEval; + use solidcore_record::brep::Curve; + let p = 3; + let mut rng = Lcg(11); + let ctrl: Vec = (0..KNOTS.len() - p - 1) + .map(|_| HPoint::weighted(Vec3::new(rng.unit() * 10.0, rng.unit() * 10.0, rng.unit() * 10.0), 0.5 + rng.unit())) + .collect(); + let record = + |k: &[f64], c: &[HPoint]| Curve::RationalSpline { knots: k.to_vec(), homogeneous: c.iter().map(|h| [h.x, h.y, h.z, h.w]).collect() }; + let whole = CurveEval::new(&record(&KNOTS, &ctrl)).unwrap(); + // Inside one span, across knots (a double one included), from or to a domain end, and + // from one existing knot to another. + for (a, b) in [(0.1, 0.2), (0.12, 0.95), (0.0, 0.42), (0.3, 1.0), (0.3, 0.5), (0.0, 1.0)] { + let (k, c) = segment(p, &KNOTS, &ctrl, a, b).unwrap(); + assert_eq!((k.first(), k.last()), (Some(&a), Some(&b)), "[{a}, {b}]: clamped on the interval"); + assert_eq!(k.len(), c.len() + p + 1); + let piece = CurveEval::new(&record(&k, &c)).unwrap(); + for x in samples() { + let t = a + (b - a) * x; + let (q, r) = (whole.point(t).unwrap(), piece.point(t).unwrap()); + assert!(q.dist(r) < 1e-12, "[{a}, {b}] at {t}: {q:?} vs {r:?}"); + } + } + assert!(segment(p, &KNOTS, &ctrl, 0.5, 0.5).is_err()); + assert!(segment(p, &KNOTS, &ctrl, -0.1, 0.5).is_err()); + assert!(segment(p, &KNOTS, &ctrl, 0.2, f64::NAN).is_err()); + } + #[test] fn single_function_knot_insertion_is_exact() { let mut rng = Lcg(7); @@ -952,6 +1062,103 @@ impl CurveN { } Some((x, dx)) } + + /// The speed in space (the length of the first three coordinates' derivative) at `t`. + fn speed(&self, t: f64) -> Option { + let (_, d) = self.eval(t)?; + Some(d.iter().take(3).map(|x| x * x).sum::().sqrt()) + } + + /// The length in space (the first three coordinates) from `a` to `b`: 8-point Gauss–Legendre. + fn length_between(&self, a: f64, b: f64) -> Option { + let (mid, half) = (0.5 * (a + b), 0.5 * (b - a)); + GAUSS_8.iter().try_fold(0.0, |sum, (x, w)| Some(sum + w * half * self.speed(mid + half * x)?)) + } +} + +/// Nodes and weights of the 8-point Gauss–Legendre rule on [-1, 1]. +pub const GAUSS_8: [(f64, f64); 8] = [ + (-0.960_289_856_497_536_2, 0.101_228_536_290_376_26), + (-0.796_666_477_413_626_7, 0.222_381_034_453_374_47), + (-0.525_532_409_916_329, 0.313_706_645_877_887_3), + (-0.183_434_642_495_649_8, 0.362_683_783_378_362), + (0.183_434_642_495_649_8, 0.362_683_783_378_362), + (0.525_532_409_916_329, 0.313_706_645_877_887_3), + (0.796_666_477_413_626_7, 0.222_381_034_453_374_47), + (0.960_289_856_497_536_2, 0.101_228_536_290_376_26), +]; + +/// Pieces of each knot span that [`ArcLength`] integrates over. +const ARC_PIECES_PER_SPAN: usize = 8; + +/// Length in space along a [`CurveN`] (its first three coordinates), for points evenly spaced +/// by length: each knot span split into [`ARC_PIECES_PER_SPAN`] pieces, each integrated with +/// 8-point Gauss–Legendre (a polynomial curve's speed is smooth within a span, so this is exact +/// to rounding for the cubics it is used on). +#[derive(Clone, Debug, PartialEq)] +pub struct ArcLength { + /// Each piece's start and end parameter and the length before it. + pieces: Vec<[f64; 3]>, + total: f64, +} + +impl ArcLength { + /// The table of `c` (`None` for a curve that does not evaluate or has no finite length). + pub fn of(c: &CurveN) -> Option { + let (p, n) = (c.degree, c.ctrl.len()); + if n <= p || c.knots.len() != n + p + 1 || n > MAX_KNOTS { + return None; + } + let mut pieces = Vec::new(); + let mut total = 0.0; + for w in c.knots.get(p..=n)?.windows(2) { + let (a, b) = (w[0], w[1]); + if !(b > a) { + continue; + } + for i in 0..ARC_PIECES_PER_SPAN { + let (s, e) = (a + (b - a) * i as f64 / ARC_PIECES_PER_SPAN as f64, a + (b - a) * (i + 1) as f64 / ARC_PIECES_PER_SPAN as f64); + pieces.push([s, e, total]); + total += c.length_between(s, e)?; + } + } + (total.is_finite() && !pieces.is_empty()).then_some(ArcLength { pieces, total }) + } + + /// The whole length. + pub fn total(&self) -> f64 { + self.total + } + + /// The parameter of `c` (the curve the table is of) at length `s` along it (clamped to the + /// curve): Newton's method within the piece holding it, kept inside that piece by bisection. + pub fn param_at(&self, c: &CurveN, s: f64) -> Option { + if !s.is_finite() { + return None; + } + let s = s.clamp(0.0, self.total); + let k = self.pieces.partition_point(|q| q[2] <= s).saturating_sub(1); + let [a, b, before] = *self.pieces.get(k)?; + let tol = 1e-13 * (1.0 + self.total); + let (mut lo, mut hi) = (a, b); + let piece = self.pieces.get(k + 1).map_or(self.total, |q| q[2]) - before; + let mut u = if piece > 0.0 { a + (b - a) * ((s - before) / piece).clamp(0.0, 1.0) } else { a }; + for _ in 0..60 { + let f = before + c.length_between(a, u)? - s; + if f.abs() <= tol { + break; + } + if f > 0.0 { + hi = u; + } else { + lo = u; + } + let v = c.speed(u)?; + let next = if v > 0.0 { u - f / v } else { f64::NAN }; + u = if next.is_finite() && next > lo && next < hi { next } else { 0.5 * (lo + hi) }; + } + Some(u) + } } #[cfg(test)] diff --git a/crates/geom/src/bvh.rs b/crates/geom/src/bvh.rs index 816fa5adf..46c7b130e 100644 --- a/crates/geom/src/bvh.rs +++ b/crates/geom/src/bvh.rs @@ -3,7 +3,9 @@ //! the box centres, a few items per leaf) and only read afterwards. [`MeshIndex`] holds one over //! a mesh's triangles and one over its edge segments, for picking. -use crate::{Aabb3, Mesh, Vec3}; +use crate::prelude::*; +use crate::{Aabb3, Mesh}; +use solidcore_record::Vec3; /// Most items in a leaf. const LEAF: usize = 4; diff --git a/crates/geom/src/catmull_rom.rs b/crates/geom/src/catmull_rom.rs new file mode 100644 index 000000000..67b6a5f9d --- /dev/null +++ b/crates/geom/src/catmull_rom.rs @@ -0,0 +1,114 @@ +//! The centripetal Catmull–Rom spline through fit points: the smooth curve a 3D sketch draws +//! through the points picked for it (no overshoot loops, no cusps). +//! +//! Between fit points `P1` and `P2` the curve is the cubic of the Barry–Goldman pyramid over the +//! four points `P0…P3` around them, at the knots `t0 = 0`, `t(i+1) = t(i) + |P(i+1) - P(i)|^½`, +//! run from `t1` to `t2` (Barry and Goldman, "A recursive evaluation algorithm for a class of +//! Catmull–Rom splines", SIGGRAPH 1988; the centripetal exponent ½ after Yuksel, Schaefer and +//! Keyser, "Parameterization and applications of Catmull–Rom curves", CAD 43(7), 2011). Its +//! derivative at `P1`, +//! +//! `m1 = (P1 - P0)/(t1 - t0) - (P2 - P0)/(t2 - t0) + (P2 - P1)/(t2 - t1)`, +//! +//! depends only on `P1`, its two neighbours and the two knot intervals between them, so the spans +//! on either side of a fit point leave it with the same derivative: in the parameter that runs on +//! from span to span by each span's knot interval, the spline is C1, exactly one cubic Bézier per +//! span ([`beziers`]). [`samples`] is the polyline through [`SPAN_SAMPLES`] points per span of the +//! same curve. +//! +//! Ends: an open spline mirrors its end points (`P(-1) = 2 P(0) - P(1)`, and so at the far end), +//! which leaves it leaving each end straight towards the next fit point. A spline of more than +//! three points whose last point is its first (within 1e-9) is closed: its neighbours wrap round, +//! so it is as smooth where it closes as anywhere else. + +use crate::prelude::*; +use solidcore_record::Vec3; + +/// Samples per span of [`samples`]. +pub const SPAN_SAMPLES: usize = 24; + +/// One span: the four points around it and their knots (`p[1]` to `p[2]` is the span). +struct Span { + p: [Vec3; 4], + t: [f64; 4], +} + +/// Whether the spline through `fit` closes on itself (see the module notes). +pub fn is_closed(fit: &[Vec3]) -> bool { + let n = fit.len(); + n > 3 && fit.first().zip(fit.last()).is_some_and(|(a, b)| a.dist(*b) < 1e-9) +} + +/// The spans of the spline through `fit` (three or more points), in order. +fn spans(fit: &[Vec3]) -> Vec { + let n = fit.len(); + let (Some(&first), Some(&second), Some(&last), Some(&before_last)) = (fit.first(), fit.get(1), fit.last(), fit.get(n.wrapping_sub(2))) else { + return Vec::new(); + }; + let closed = is_closed(fit); + let at = |i: isize| -> Vec3 { + match usize::try_from(i) { + Ok(i) if i < n => fit.get(i).copied().unwrap_or(last), + Ok(_) if closed => second, + Err(_) if closed => before_last, + // Mirrored end tangents. + Ok(_) => last * 2.0 - before_last, + Err(_) => first * 2.0 - second, + } + }; + let tj = |a: Vec3, b: Vec3| a.dist(b).sqrt().max(1e-9); + (0..n.saturating_sub(1)) + .map(|k| { + let k = k as isize; + let (p0, p1, p2, p3) = (at(k - 1), at(k), at(k + 1), at(k + 2)); + let t0 = 0.0; + let t1 = t0 + tj(p0, p1); + let t2 = t1 + tj(p1, p2); + let t3 = t2 + tj(p2, p3); + Span { p: [p0, p1, p2, p3], t: [t0, t1, t2, t3] } + }) + .collect() +} + +/// The polyline of the spline through `fit`: the point itself (one point), the line (two), or +/// [`SPAN_SAMPLES`] points per span after the first point, the last at the last fit point. +pub fn samples(fit: &[Vec3]) -> Vec { + if fit.len() <= 2 { + return fit.to_vec(); + } + let mut out = fit.first().copied().into_iter().collect::>(); + for Span { p: [p0, p1, p2, p3], t: [t0, t1, t2, t3] } in spans(fit) { + for s in 1..=SPAN_SAMPLES { + let t = t1 + (t2 - t1) * s as f64 / SPAN_SAMPLES as f64; + let a1 = p0 * ((t1 - t) / (t1 - t0)) + p1 * ((t - t0) / (t1 - t0)); + let a2 = p1 * ((t2 - t) / (t2 - t1)) + p2 * ((t - t1) / (t2 - t1)); + let a3 = p2 * ((t3 - t) / (t3 - t2)) + p3 * ((t - t2) / (t3 - t2)); + let b1 = a1 * ((t2 - t) / (t2 - t0)) + a2 * ((t - t0) / (t2 - t0)); + let b2 = a2 * ((t3 - t) / (t3 - t1)) + a3 * ((t - t1) / (t3 - t1)); + out.push(b1 * ((t2 - t) / (t2 - t1)) + b2 * ((t - t1) / (t2 - t1))); + } + } + out +} + +/// The spline through `fit` (three or more points) exactly, as one cubic Bézier per span (from +/// fit point to fit point): `P1`, `P1 + m1 h/3`, `P2 - m2 h/3`, `P2` (`h = t2 - t1`, `m` the +/// derivatives in the module notes), its parameter `(t - t1) / h`. Neighbouring spans meet with +/// the same derivative in `t`, so the spans make a C1 cubic B-spline with double interior knots. +/// Empty for fewer than three points (a point or a line); `None` for a spline that does not come +/// out finite. +pub fn beziers(fit: &[Vec3]) -> Option> { + if fit.len() < 3 { + return Some(Vec::new()); + } + let out: Vec<[Vec3; 4]> = spans(fit) + .into_iter() + .map(|Span { p: [p0, p1, p2, p3], t: [t0, t1, t2, t3] }| { + let h = t2 - t1; + let m1 = (p1 - p0) * (1.0 / (t1 - t0)) - (p2 - p0) * (1.0 / (t2 - t0)) + (p2 - p1) * (1.0 / h); + let m2 = (p2 - p1) * (1.0 / h) - (p3 - p1) * (1.0 / (t3 - t1)) + (p3 - p2) * (1.0 / (t3 - t2)); + [p1, p1 + m1 * (h / 3.0), p2 - m2 * (h / 3.0), p2] + }) + .collect(); + out.iter().flatten().all(|p| p.is_finite()).then_some(out) +} diff --git a/crates/geom/src/cell.rs b/crates/geom/src/cell.rs index 50858c65f..60d3c224b 100644 --- a/crates/geom/src/cell.rs +++ b/crates/geom/src/cell.rs @@ -30,7 +30,8 @@ use serde::{Deserialize, Serialize}; use crate::paper::MAX_COORDINATE_MM; -use crate::{Aabb2, EPS, Vec2}; +use crate::{Aabb2, EPS}; +use solidcore_record::Vec2; /// The most parts a cell's content may have. pub const MAX_PARTS: usize = 64; diff --git a/crates/geom/src/chain.rs b/crates/geom/src/chain.rs index 87795a33b..b6f1023d5 100644 --- a/crates/geom/src/chain.rs +++ b/crates/geom/src/chain.rs @@ -3,10 +3,12 @@ //! a chain is lives in its type, so code that walks its edges never wraps an index by hand, and //! what only a closed chain has (an area, an inside) is only asked of a ring. +use crate::prelude::*; use std::marker::PhantomData; use std::ops::Deref; -use crate::{Aabb2, Vec2, Vec3}; +use crate::Aabb2; +use solidcore_record::{Vec2, Vec3}; /// Whether a chain's last item joins its first. pub trait Ends: sealed::Sealed { @@ -142,7 +144,7 @@ impl Ring { } /// [`Ring::edges`] of items held elsewhere, for a type that keeps a closed ring in a field of its -/// own ([`crate::Loop2::joints`]). +/// own ([`solidcore_record::Loop2::joints`]). pub(crate) fn around(items: &[T]) -> impl Iterator + Clone { items.iter().zip(items.iter().cycle().skip(1)) } diff --git a/crates/geom/src/compare.rs b/crates/geom/src/compare.rs index 74e4b20fd..1b8b5dabc 100644 --- a/crates/geom/src/compare.rs +++ b/crates/geom/src/compare.rs @@ -12,10 +12,12 @@ //! intersects the two surfaces, so bodies that share almost every face (two versions of one //! part) compare as well as any others. +use crate::prelude::*; use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; -use crate::{Aabb3, Mesh, Vec3}; +use crate::{Aabb3, Mesh}; +use solidcore_record::Vec3; /// Runs a job for every index below `n`: the jobs are independent, so any order and any number /// of threads will do. [`serial`] runs them one after another; a caller with threads passes one diff --git a/crates/geom/src/drawing_measure.rs b/crates/geom/src/drawing_measure.rs index 8e372b7d3..52175128a 100644 --- a/crates/geom/src/drawing_measure.rs +++ b/crates/geom/src/drawing_measure.rs @@ -8,9 +8,11 @@ use serde::{Deserialize, Serialize}; +use crate::EPS; use crate::drawing_view::{Invalid, PARALLEL, require}; +use crate::prelude::*; use crate::section::{MAX_NUMBER, validate_plane}; -use crate::{EPS, Plane, Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; type Result = std::result::Result; diff --git a/crates/geom/src/drawing_sheet.rs b/crates/geom/src/drawing_sheet.rs index 485b01305..2b3b02a47 100644 --- a/crates/geom/src/drawing_sheet.rs +++ b/crates/geom/src/drawing_sheet.rs @@ -32,10 +32,11 @@ use serde::{Deserialize, Serialize}; +use crate::Aabb2; /// The longest side a custom sheet may have, in millimetres: the paper scene's limit. pub use crate::paper::MAX_SIDE_MM; use crate::paper::{Group, Item, MAX_LINE_MM, ObjectKind}; -use crate::{Aabb2, Loop2, Region2, Seg2, Vec2}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; /// The most fields an equal division may cut each way. pub const MAX_EQUAL_FIELDS: u32 = 200; diff --git a/crates/geom/src/drawing_sheet_tests.rs b/crates/geom/src/drawing_sheet_tests.rs index be4cc3834..66bf41710 100644 --- a/crates/geom/src/drawing_sheet_tests.rs +++ b/crates/geom/src/drawing_sheet_tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::prelude::*; const EPS: f64 = 1e-9; diff --git a/crates/geom/src/drawing_view.rs b/crates/geom/src/drawing_view.rs index 426123f58..73f7ef53a 100644 --- a/crates/geom/src/drawing_view.rs +++ b/crates/geom/src/drawing_view.rs @@ -14,8 +14,9 @@ //! scales at which a view fits a space. //! - A **[`ViewFrame`]** places a view on paper: the point of the view's plane at `centre` lands at //! `position_mm`, everything scaled by the scale. Its [`ViewFrame::paper_map`] moves the view's -//! curves ([`Seg2::similar`]) and their accuracy ([`CurveAccuracy::scaled`]) onto paper. +//! curves ([`Seg2Geom::similar`]) and their accuracy ([`CurveAccuracy::scaled`]) onto paper. +use crate::prelude::*; use std::fmt; use std::str::FromStr; @@ -24,7 +25,8 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::cell::Projection; use crate::paper::MAX_SIDE_MM; use crate::section::{CurveAccuracy, MAX_NUMBER, validate_plane}; -use crate::{Aabb2, Plane, Seg2, Similarity2, Vec2, Vec3}; +use crate::{Aabb2, Similarity2}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; /// The smallest scale: one paper millimetre for 100 m of model. pub const MIN_SCALE: f64 = 1e-5; diff --git a/crates/geom/src/fill.rs b/crates/geom/src/fill.rs index 4d911ad18..09a21bb37 100644 --- a/crates/geom/src/fill.rs +++ b/crates/geom/src/fill.rs @@ -10,13 +10,14 @@ //! B-spline curve, eq. 3.4: control values at the knot averages reproduce a linear function), //! A2.1 (span search). -use crate::Vec3; use crate::bspline::{Dir, HPoint, NurbsSurface, Side, SplineError, SplineResult, find_span, invalid, local_basis_array}; +use crate::prelude::*; +use solidcore_record::Vec3; /// Most loop points a fill takes. pub const MAX_LOOP_POINTS: usize = 8192; /// Most spans of the height field in each direction. -pub const MAX_FILL_SPANS: usize = 32; +pub const MAX_FILL_SPANS: usize = 64; /// How full a patch's middle may be made (`crown`): 0 the least-bending fill, positive fuller, /// negative flatter, in fractions of the loop's size. Outside this range the value is refused. pub const MIN_CROWN: f64 = -0.9; @@ -89,7 +90,7 @@ pub struct LoopFill { /// is free to turn at the rim (it is not the surface that made the rim). It does not depend /// on the grid's directions. `λ = 10⁻⁷ ·` (fitted points) `/` (control points): just enough /// to fix the inside, small enough not to pull the surface off the loop. -/// - Grids of 4, 8, 16, 32 spans across the box's longer side are tried, with as many across +/// - Grids of 4, 8, 16, 32, 64 spans across the box's longer side are tried, with as many across /// the shorter side as keep the cells about square; a grid whose cells are under twice the /// fitted points' largest step in a direction (cells between points would be left to the /// energy alone) waits for denser sampling. The first grid within `tol` of every sampled @@ -166,10 +167,25 @@ enum Fit { Exhausted(f64), } -/// One round of [`fill_loop`]: fit the points `fit`, check every point of `all` (the loop in -/// order, `fit` among them). -fn fit_once(fit: &[Vec3], all: &[Vec3], tol: f64, crown: f64) -> SplineResult { +/// The plane a loop's height field stands on (see [`fill_loop`]): through the fitted points' +/// centroid `o`, normal `n` by Newell's method turned so that its largest component is positive, +/// first axis `x` towards the fitted point farthest from the centroid in the plane, `y = n × x`; +/// and whether the points run counter-clockwise about `n`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct LoopFrame { + pub(crate) o: Vec3, + pub(crate) x: Vec3, + pub(crate) y: Vec3, + pub(crate) n: Vec3, + pub(crate) counter_clockwise: bool, +} + +/// The [`LoopFrame`] of the loop of points `fit`. +pub(crate) fn loop_frame(fit: &[Vec3]) -> SplineResult { let m = fit.len(); + if m < 3 { + return invalid("a loop needs three points"); + } let o = fit.iter().fold(Vec3::ZERO, |a, p| a + *p) / m as f64; let at = |k: usize| fit.get(k % m).copied().unwrap_or(Vec3::ZERO); let area = (0..m).fold(Vec3::ZERO, |a, k| a + (at(k) - o).cross(at(k + 1) - o)); @@ -206,6 +222,14 @@ fn fit_once(fit: &[Vec3], all: &[Vec3], tol: f64, crown: f64) -> SplineResult SplineResult { + let m = fit.len(); + let LoopFrame { o, x, y, n, counter_clockwise } = loop_frame(fit)?; let project = |pts: &[Vec3]| -> (Vec<[f64; 2]>, Vec) { (pts.iter().map(|p| [(*p - o).dot(x), (*p - o).dot(y)]).collect(), pts.iter().map(|p| (*p - o).dot(n)).collect()) }; @@ -284,8 +308,11 @@ fn fit_once(fit: &[Vec3], all: &[Vec3], tol: f64, crown: f64) -> SplineResult SplineResult<(NurbsSurface, usize, f64)> { @@ -314,7 +341,7 @@ pub(crate) fn crown_fill_along( let gap = loop_gap(uv); let mut base = surface; loop { - if let Some((crowned, points)) = crown_net(&base, uv, gap, crown, along)? { + if let Some((crowned, points)) = crown_net(&base, uv, gap, crown, along)?.filter(|c| c.2).map(|(c, n, _)| (c, n)) { let mut drift = 0.0f64; for q in uv { if let (Ok(a), Ok(b)) = (base.eval(q[0], q[1]), crowned.eval(q[0], q[1])) { @@ -342,14 +369,15 @@ pub(crate) fn crown_fill_along( /// The crown's bump in the net `base`: a control point whose support rectangle keeps clear of the /// loop takes `crown · size · B(ξ, η)`, `B` the bubble's blossom at the point's knots (so the /// surface between the perturbed points is exactly the bubble, not a fit of it) and `size` the -/// box's diagonal. `None` when the net has no such point. +/// box's diagonal. `None` when the net has no such point; with it, whether every point +/// supporting the box's middle took the bump (or the middle is outside the loop). fn crown_net( base: &NurbsSurface, uv: &[[f64; 2]], gap: [f64; 2], crown: f64, along: &dyn Fn([f64; 2]) -> Option, -) -> SplineResult> { +) -> SplineResult> { let [cu, cv] = base.count(); let degree = base.degree(); let knots = base.knots(); @@ -368,10 +396,16 @@ fn crown_net( let (Some(knots_u), Some(knots_v)) = (knots.first(), knots.get(1)) else { return invalid("the surface has no knot vectors") }; let mut ctrl = base.homogeneous().to_vec(); let mut points = 0usize; + let middle = [0.5 * (domain[0][0] + domain[0][1]), 0.5 * (domain[1][0] + domain[1][1])]; + // The points whose basis is not zero at the middle, and those of them that took the bump. + let (mut at_middle, mut raised_middle) = (0usize, 0usize); + let holds = |span: [f64; 2], x: f64| span[0] < x && x < span[1]; for j in 0..cv { let Some((v_span, v_knots)) = support(knots_v, degree[1], j) else { continue }; for i in 0..cu { let Some((u_span, u_knots)) = support(knots_u, degree[0], i) else { continue }; + let supports = holds(u_span, middle[0]) && holds(v_span, middle[1]); + at_middle += usize::from(supports); if !clear_of_loop(u_span, v_span, uv, gap) { continue; } @@ -383,12 +417,14 @@ fn crown_net( let Some(p) = h.project() else { continue }; *slot = HPoint::weighted(p + normal * bump, h.w); points += 1; + raised_middle += usize::from(supports); } } if points == 0 { return Ok(None); } - Ok(Some((NurbsSurface::from_homogeneous(degree, knots.clone(), ctrl)?, points))) + let middle_held = raised_middle == at_middle || !inside_loop(middle, uv); + Ok(Some((NurbsSurface::from_homogeneous(degree, knots.clone(), ctrl)?, points, middle_held))) } /// The same surface with a knot inserted in the middle of every span of direction `d` (0 = u): @@ -495,7 +531,7 @@ fn segment_meets_rect(p: [f64; 2], q: [f64; 2], lo: [f64; 2], hi: [f64; 2]) -> b } /// Refuse a loop that does not bound a height field over its plane (see [`fill_loop`]). -fn check_projectable(points: &[Vec3], uv: &[[f64; 2]]) -> SplineResult<()> { +pub(crate) fn check_projectable(points: &[Vec3], uv: &[[f64; 2]]) -> SplineResult<()> { let m = uv.len(); let q = |k: usize| uv.get(k % m).copied().unwrap_or([0.0; 2]); let p = |k: usize| points.get(k % m).copied().unwrap_or(Vec3::ZERO); @@ -707,7 +743,7 @@ impl Grid { /// The surface of the net `heights` over the plane `o`, `x`, `y`, `n`: control point `(i, j)` /// at the knot averages `(ξᵢ, ηⱼ)` in the plane, `heights[j·count[0] + i]` along `n`. - fn surface(&self, heights: &[f64], o: Vec3, x: Vec3, y: Vec3, n: Vec3) -> SplineResult { + pub(crate) fn surface(&self, heights: &[f64], o: Vec3, x: Vec3, y: Vec3, n: Vec3) -> SplineResult { let [cu, cv] = self.count; let mut ctrl = Vec::with_capacity(cu * cv); for j in 0..cv { @@ -755,7 +791,7 @@ impl Band { } /// Solve `A·x = b` by banded Cholesky factorisation `A = Uᵀ·U`; an error when `A` is not /// positive definite. - fn solve(self, b: Vec) -> SplineResult> { + pub(crate) fn solve(self, b: Vec) -> SplineResult> { self.factor()?.substitute(b) } diff --git a/crates/geom/src/fill_general.rs b/crates/geom/src/fill_general.rs index e6f5da582..203cd0e1f 100644 --- a/crates/geom/src/fill_general.rs +++ b/crates/geom/src/fill_general.rs @@ -52,9 +52,10 @@ //! - **A crown** fills the middle out along the surface's own normals, on control points clear of //! the loop, so it moves neither the loop nor the conditions across it. -use crate::Vec3; use crate::bspline::{HPoint, NurbsSurface, SplineError, SplineResult, invalid}; use crate::fill::{Band, Grid, MAX_LOOP_POINTS, SMOOTHNESS, inside_loop, segments_meet}; +use crate::prelude::*; +use solidcore_record::Vec3; /// Most spans of the surface along the domain's longer side. pub const MAX_GENERAL_SPANS: usize = 64; @@ -91,6 +92,10 @@ pub struct Across { pub normal: Vec3, /// G2: the neighbour's curvature vector along `leave` (unit speed). pub bend: Option, + /// G2 and up: the neighbour as a height over its tangent plane to the order asked + /// ([`crate::linkage::Jet`], on the frame `normal × leave`, `leave`), which the conditions of + /// [`crate::fill_iso`] read. `None` where only `bend` is known. + pub jet: Option, } /// One sample of the loop. @@ -226,7 +231,9 @@ pub fn fill_general( fn finite_station(s: &Station) -> bool { s.p.is_finite() && s.up.is_finite() - && s.across.is_none_or(|a| a.leave.is_finite() && a.normal.is_finite() && a.bend.is_none_or(|b| b.is_finite())) + && s.across.is_none_or(|a| { + a.leave.is_finite() && a.normal.is_finite() && a.bend.is_none_or(|b| b.is_finite()) && a.jet.is_none_or(|j| j.is_finite()) + }) } /// How close a grid came: what [`fill_general`] reports when none is close enough. @@ -1085,7 +1092,7 @@ fn crown(surface: NurbsSurface, net: &Net, st: &[Station], dev: &Developed, crow if crown == 0.0 { return Ok(surface); } - // The side the neighbours' normals face, by the patch's normals at the G1/G2 stations. + // The side the neighbours' normals face, by the patch's normals at the stations of G1 and up. let mut side = 0.0; for (s, q) in st.iter().zip(&dev.d) { if let (Some(a), Some((n, _, _))) = (s.across, net.frame(*q)) { @@ -1093,7 +1100,7 @@ fn crown(surface: NurbsSurface, net: &Net, st: &[Station], dev: &Developed, crow } } if side == 0.0 { - return Err(SplineError::Unsupported("crowning a patch with no g1 or g2 edge to say which side is out".into())); + return Err(SplineError::Unsupported("crowning a patch with no g1 or higher edge to say which side is out".into())); } let sign = side.signum(); let along = |g: [f64; 2]| net.frame(g).map(|(n, _, _)| n * sign); diff --git a/crates/geom/src/fill_general_tests.rs b/crates/geom/src/fill_general_tests.rs index 35ff6b6cd..41f2b4d43 100644 --- a/crates/geom/src/fill_general_tests.rs +++ b/crates/geom/src/fill_general_tests.rs @@ -30,7 +30,7 @@ fn tube_end(r: f64, g2: bool) -> impl FnMut(usize, &[f64]) -> Result impl FnMut(usize, &[f64]) -> Result, + pub points: Vec, + /// One positive weight per point; `None` for a polynomial edge. + pub weights: Option>, +} + +impl IsoEdge { + /// The edge's parameter interval. + pub fn domain(&self) -> [f64; 2] { + [self.knots.get(self.degree).copied().unwrap_or(0.0), self.knots.get(self.points.len()).copied().unwrap_or(0.0)] + } + + /// The middle of the edge's parameter interval. + pub fn middle(&self) -> f64 { + let [a, b] = self.domain(); + 0.5 * (a + b) + } + + /// The unit tangent at parameter `t` (the loop's way), `None` where the edge stops. + pub fn tangent(&self, t: f64) -> Option { + let space = Space::new(self.degree, self.knots.clone()).ok()?; + let h = self.homogeneous(); + let (a, da) = (space.eval(&h, t, 0).ok()?, space.eval(&h, t, 1).ok()?); + let p = a.project()?; + ((da.xyz() - p * da.w) * (1.0 / a.w)).normalized() + } + + /// The homogeneous control points. + fn homogeneous(&self) -> Vec { + let w = |i: usize| self.weights.as_ref().and_then(|w| w.get(i)).copied().unwrap_or(1.0); + self.points.iter().enumerate().map(|(i, p)| HPoint::weighted(*p, w(i))).collect() + } +} + +/// What the fill is asked for besides its boundary. +#[derive(Clone, Copy, Debug)] +pub struct IsoSpec<'a> { + /// How far a point may be from the fill. + pub tol: f64, + /// How far (radians) the fill's normal may turn from a G1/G2 neighbour's. + pub angle_tol: f64, + /// How full the middle is made (as [`crate::fill::fill_loop`]'s crown). + pub crown: f64, + /// How far (radians) the loop may turn at a vertex for it not to be a corner of the region + /// (the edges either side are then one side of the fill). + pub corner_turn: f64, + /// Points the fill passes through. + pub points: &'a [Vec3], +} + +/// What a side of a patch is, running the patch's loop counter-clockwise in (u, v) from `uv[0]` +/// to `uv[1]` (a straight line, affine in the curve's parameter). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum IsoSide { + /// The piece `[from, to]` of loop edge `edge` (its own parameter, running the loop's way). + Edge { edge: usize, from: f64, to: f64, uv: [[f64; 2]; 2] }, + /// Spoke `spoke` over its parameter `[0, 1]` (from its edge's midpoint to the centre), + /// run that way (`forward`) or back. + Spoke { spoke: usize, forward: bool, uv: [[f64; 2]; 2] }, +} + +/// One patch of the fill and its sides (three around a pole, else four). +#[derive(Clone, Debug, PartialEq)] +pub struct IsoPatch { + pub surface: NurbsSurface, + pub sides: Vec, +} + +/// The fill and what it achieved. +#[derive(Clone, Debug, PartialEq)] +pub struct IsoFill { + pub patches: Vec, + /// Each spoke (a curve inside the fill two patches share) as a curve (degree, knots on + /// `[0, 1]`, control points and, on a rational fill, weights), from its first end to its + /// second. Empty for a fill of one patch. + pub spokes: Vec, + /// Where each spoke starts and ends. + pub ends: Vec<[SpokeEnd; 2]>, + /// The fill's vertices inside the loop (the centre, or the inner patch's corners), where + /// spokes end ([`SpokeEnd::Inner`]). + pub inner: Vec, + pub achieved: Achieved, +} + +/// Where a spoke ends. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum SpokeEnd { + /// On loop edge `edge` at its parameter `t`. + Loop { edge: usize, t: f64 }, + /// At the fill's inner vertex `.0` ([`IsoFill::inner`]). + Inner(usize), +} + +/// What a fill achieves at its stations and points (its boundary is exact). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Achieved { + /// The largest angle (radians) between the fill's normal and a G1/G2 neighbour's (or, across + /// a spoke, between the two patches') at a station held to the tolerance, and at any station. + pub normal_deviation: f64, + pub normal_deviation_all: f64, + /// The largest angle (radians) by which the fill's normal at a station held to the tolerance + /// misses the neighbour's beyond the edge's own lean out of the neighbour's tangent plane + /// there (the fill holds the edge, so it can come no nearer): what the angle tolerance is + /// held to. + pub normal_excess: f64, + /// `jumps[k]`, k = 2 … 4: the largest jump, clear of the loop's corners, of the k-th + /// derivative of the linkage curves' height above the neighbour per unit length of their + /// foot (`(n·c⁽ᵏ⁾ − target) / |x₁|ᵏ`, 1/lengthᵏ⁻¹) across the edges asked for order k or more: + /// the normal curvature (k = 2), its rate of change (3) and that rate's (4). Zero below 2. + pub jumps: [f64; MAX_CONTINUITY + 1], + /// The farthest point from the fill. + pub point_deviation: f64, +} + +/// A curve on `[0, 1]`, on homogeneous control points. +#[derive(Clone, Debug)] +struct Curve { + space: Space, + points: Vec, +} + +/// The piece `[a, b]` of `edge` (homogeneous points scaled by `scale`), on `[0, 1]` (run +/// backwards when `reverse`). +fn on_unit(edge: &IsoEdge, scale: f64, [a, b]: [f64; 2], reverse: bool) -> SplineResult { + let h: Vec = edge.homogeneous().into_iter().map(|q| q * scale).collect(); + piece_on_unit(edge.degree, &edge.knots, &h, [a, b], reverse) +} + +/// The piece `[a, b]` of the curve of degree `p` on `knots` and homogeneous points `h`, on +/// `[0, 1]` (run backwards when `reverse`). +fn piece_on_unit(p: usize, knots: &[f64], h: &[HPoint], [a, b]: [f64; 2], reverse: bool) -> SplineResult { + let (knots, mut points) = segment(p, knots, h, a, b)?; + let map = |k: f64| if reverse { (b - k) / (b - a) } else { (k - a) / (b - a) }; + let mut knots: Vec = knots.iter().map(|k| map(*k)).collect(); + if reverse { + knots.reverse(); + points.reverse(); + } + // The ends exactly on the unit interval (the map's rounding). + for k in knots.iter_mut().take(p + 1) { + *k = 0.0; + } + let n = knots.len(); + for k in knots.iter_mut().skip(n - p - 1) { + *k = 1.0; + } + Ok(Curve { space: Space::new(p, knots)?, points }) +} + +/// The straight line from `a` to `b` on `[0, 1]`, homogeneous (a spoke's start, or a pole when +/// the points are one). +fn line(a: HPoint, b: HPoint) -> SplineResult { + Ok(Curve { space: Space::polynomial(1, 0.0, 1.0)?, points: vec![a, b] }) +} + +/// The breaks of a space: its distinct knots. +fn breaks(s: &Space) -> Vec { + let mut out: Vec = s.knots().to_vec(); + out.dedup(); + out +} + +/// Breaks of different sides closer than this (on `[0, 1]`) are one break: the rounding of +/// mapping each side's parameter onto the unit interval. +const BREAK_TOL: f64 = 1e-12; + +/// The knots of `s` with each one within [`BREAK_TOL`] of one of `breaks` moved onto it. +fn snapped(s: &Space, breaks: &[f64]) -> SplineResult { + let knots = s.knots().iter().map(|k| breaks.iter().copied().find(|b| (b - k).abs() <= BREAK_TOL).unwrap_or(*k)).collect(); + Space::new(s.degree(), knots) +} + +/// One space holding every curve, of degree `q` (at least each curve's), and each curve's +/// control points there. Each break of a curve keeps that curve's continuity there: a knot of +/// multiplicity `m` in a curve of degree `p` is one of multiplicity `m + q − p` in the space (as +/// raising the degree needs, NURBS Book §5.5), the most any curve asks (breaks of different +/// curves within [`BREAK_TOL`] made one); the breaks `extra` adds are simple knots. Exact: the +/// space contains every curve, which is carried into it by [`carried`]. +fn compatible(curves: &[&Curve], extra: &[f64], q: usize) -> SplineResult<(Space, Vec>)> { + let q = curves.iter().map(|s| s.space.degree()).max().unwrap_or(1).max(q); + let mut need: Vec<(f64, usize)> = Vec::new(); + for c in curves { + let p = c.space.degree(); + for (x, m) in interior_knots(&c.space) { + let k = (m + q - p).min(q); + match need.iter_mut().find(|(y, _)| (*y - x).abs() <= BREAK_TOL) { + Some((_, have)) => *have = (*have).max(k), + None => need.push((x, k)), + } + } + } + need.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut knots = vec![0.0; q + 1]; + for &(x, k) in &need { + knots.extend(std::iter::repeat_n(x, k)); + } + knots.extend(std::iter::repeat_n(1.0, q + 1)); + let target = Space::new(q, knots)?.refined(extra)?; + let canonical: Vec = need.iter().map(|(x, _)| *x).collect(); + let mut out = Vec::with_capacity(curves.len()); + for c in curves { + out.push(carried(&snapped(&c.space, &canonical)?, &c.points, &target)?); + } + Ok((target, out)) +} + +/// The distinct interior knots of a space and how often each is repeated. +fn interior_knots(s: &Space) -> Vec<(f64, usize)> { + let [a, b] = s.domain(); + let mut out: Vec<(f64, usize)> = Vec::new(); + for &k in s.knots().iter().filter(|k| **k > a && **k < b) { + match out.last_mut() { + Some((x, m)) if *x == k => *m += 1, + _ => out.push((k, 1)), + } + } + out +} + +/// The control points in `to` of the curve with control points `ctrl` in `from`, which `to` +/// contains: the curve interpolated at `to`'s Greville abscissae (where the interpolation +/// problem is uniquely solvable, Schoenberg–Whitney), which is the curve itself since it lies in +/// the space; its end points are the curve's own. +fn carried(from: &Space, ctrl: &[HPoint], to: &Space) -> SplineResult> { + let conds: Vec = greville(to).into_iter().map(|t| Cond { t, der: 0 }).collect(); + let data = conds.iter().map(|c| from.eval(ctrl, c.t, 0)).collect::>>()?; + let mut points = Interpolant::new(to.clone(), conds)?.fit(&data)?; + if let (Some(f), Some(first)) = (points.first_mut(), ctrl.first()) { + *f = *first; + } + if let (Some(l), Some(last)) = (points.last_mut(), ctrl.last()) { + *l = *last; + } + Ok(points) +} + +/// The Greville abscissae of a space (where its splines reproduce a linear function). +fn greville(s: &Space) -> Vec { + let (p, k) = (s.degree(), s.knots()); + (0..s.count()).map(|i| (1..=p).map(|r| k.get(i + r).copied().unwrap_or(0.0)).sum::() / p as f64).collect() +} + +/// A stretch of a loop edge on one side of the region: edge `edge` over its parameters +/// `range` (the loop's way), on the fraction `at` of the side. +#[derive(Clone, Copy, Debug, PartialEq)] +struct SidePiece { + edge: usize, + range: [f64; 2], + at: [f64; 2], +} + +/// The region's sides (module docs): the chains of edges between the loop's corners, the first +/// starting at a corner; each edge its own side when the loop has fewer than three corners. And +/// whether it has three or more. +fn loop_sides(edges: &[IsoEdge], corner_turn: f64) -> (Vec>, bool) { + let n = edges.len(); + let whole = |k: usize| SidePiece { edge: k, range: edges.get(k).map_or([0.0, 1.0], IsoEdge::domain), at: [0.0, 1.0] }; + // A corner where edge k starts: the tangents either side differ by more than the turn. + let corner: Vec = (0..n) + .map(|k| { + let (Some(a), Some(b)) = (edges.get((k + n - 1) % n), edges.get(k)) else { return true }; + match (a.tangent(a.domain()[1]), b.tangent(b.domain()[0])) { + (Some(x), Some(y)) => x.dot(y) < corner_turn.cos(), + _ => true, + } + }) + .collect(); + let corners: Vec = (0..n).filter(|k| corner.get(*k).copied().unwrap_or(true)).collect(); + if corners.len() < 3 { + return ((0..n).map(|k| vec![whole(k)]).collect(), false); + } + // Each edge's share of its side: its control polygon's length (any positive measure keeps the + // side exact; this one keeps its speed near the edges' own). + let length = |k: usize| edges.get(k).map_or(0.0, |e| e.points.windows(2).map(|w| w[0].dist(w[1])).sum::()).max(f64::MIN_POSITIVE); + let mut sides = Vec::with_capacity(corners.len()); + for (c, &first) in corners.iter().enumerate() { + let next = corners.get((c + 1) % corners.len()).copied().unwrap_or(first); + let count = (next + n - first - 1) % n + 1; + let chain: Vec = (0..count).map(|i| (first + i) % n).collect(); + let total: f64 = chain.iter().map(|k| length(*k)).sum(); + let mut from = 0.0; + let mut side = Vec::with_capacity(chain.len()); + for (i, &k) in chain.iter().enumerate() { + let to = if i + 1 == chain.len() { 1.0 } else { from + length(k) / total }; + side.push(SidePiece { at: [from, to], ..whole(k) }); + from = to; + } + sides.push(side); + } + (sides, true) +} + +/// A side as one curve on `[0, 1]` (module docs): its edges (homogeneous points scaled by +/// `scales`) each carried exactly into the side's degree and laid on its stretch, joined at +/// knots of full multiplicity. +fn side_curve(edges: &[IsoEdge], scales: &[f64], side: &[SidePiece]) -> SplineResult { + let mut parts = Vec::with_capacity(side.len()); + for sp in side { + let e = edges.get(sp.edge).ok_or_else(|| SplineError::Invalid("a side's edge".into()))?; + parts.push(on_unit(e, scales.get(sp.edge).copied().unwrap_or(1.0), sp.range, false)?); + } + let q = parts.iter().map(|c| c.space.degree()).max().unwrap_or(1); + let mut knots = vec![0.0; q + 1]; + let mut points: Vec = Vec::new(); + for (i, (part, sp)) in parts.iter().zip(side).enumerate() { + let (space, rows) = compatible(&[part], &[], q)?; + let [a, b] = sp.at; + let interior = space.knots().iter().skip(q + 1).take(space.count().saturating_sub(q + 1)); + knots.extend(interior.map(|x| a + (b - a) * x)); + let row = rows.into_iter().next().ok_or_else(|| SplineError::Invalid("a side's piece".into()))?; + // The joint's point is the previous piece's last. + points.extend(row.into_iter().skip(usize::from(i > 0))); + knots.extend(std::iter::repeat_n(b, if i + 1 == side.len() { q + 1 } else { q })); + } + Ok(Curve { space: Space::new(q, knots)?, points }) +} + +/// A piece of a loop edge on a patch's side: `piece` (fraction `piece.at` of loop side `side_of`), +/// on patch `patch`'s side `side` over the fraction `along` of it. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Piece { + piece: SidePiece, + side_of: usize, + patch: usize, + side: usize, + along: [f64; 2], +} + +impl Piece { + /// The edge's parameter at fraction `x` of the piece. + fn param(&self, x: f64) -> f64 { + let [a, b] = self.piece.range; + if x == 0.0 { + a + } else if x == 1.0 { + b + } else { + a + (b - a) * x + } + } +} + +/// The edges' pieces on the loop side `side_of` between its fractions `lo` and `hi`, on patch +/// `patch`'s side `side`, the fraction `lo` of the loop side at the patch side's start and `hi` +/// at its end. +fn pieces_between(side: &[SidePiece], side_of: usize, [lo, hi]: [f64; 2], patch: usize, s: usize) -> Vec { + let mut out = Vec::new(); + for sp in side { + let [g0, g1] = sp.at; + let (a, b) = (g0.max(lo), g1.min(hi)); + if !(a < b) { + continue; + } + let at = |g: f64| { + if g == g0 { + sp.range[0] + } else if g == g1 { + sp.range[1] + } else { + sp.range[0] + (sp.range[1] - sp.range[0]) * (g - g0) / (g1 - g0) + } + }; + let piece = SidePiece { edge: sp.edge, range: [at(a), at(b)], at: [a, b] }; + out.push(Piece { piece, side_of, patch, side: s, along: [(a - lo) / (hi - lo), (b - lo) / (hi - lo)] }); + } + out +} + +/// Where on the loop the fraction `g` of a side is: (edge, its parameter). +fn on_side(side: &[SidePiece], g: f64) -> Option<(usize, f64)> { + let sp = side.iter().find(|sp| sp.at[0] <= g && g <= sp.at[1])?; + let [g0, g1] = sp.at; + let t = if g == g0 { + sp.range[0] + } else if g == g1 { + sp.range[1] + } else { + sp.range[0] + (sp.range[1] - sp.range[0]) * (g - g0) / (g1 - g0) + }; + Some((sp.edge, t)) +} + +/// A tensor patch in the fill's spaces along u and v, control point `(i, j)` (i along u) at +/// `i + c·j`, `c` the u space's count, with its fixed weights. +#[derive(Clone, Debug)] +struct Patch { + spaces: [Space; 2], + net: Vec, + weights: Vec, + /// Whether any weight differs from one (else the polynomial basis is used as it is). + rational: bool, + /// The patch collapses along `u = 0` (a three-sided patch). + pole: bool, +} + +impl Patch { + /// The control points along u and along v. + fn counts(&self) -> [usize; 2] { + [self.spaces[0].count(), self.spaces[1].count()] + } + + fn flat(&self, i: usize, j: usize) -> usize { + i + self.spaces[0].count() * j + } + + fn at(&self, i: usize, j: usize) -> Vec3 { + self.net.get(self.flat(i, j)).copied().unwrap_or(Vec3::ZERO) + } + + fn weight(&self, i: usize, j: usize) -> f64 { + self.weights.get(self.flat(i, j)).copied().unwrap_or(1.0) + } + + /// The coefficients of `∂^(du+dv) S / ∂u^du ∂v^dv` at (u, v) on each control point it + /// depends on: `(i, j, coefficient)`. On a rational patch these are the derivatives of the + /// rational basis `R_ij = w_ij N_i N_j / W`, by the Leibniz rule for `w_ij N_i N_j = R_ij W`: + /// `R^(a,b) = (f^(a,b) − Σ_{(k,l) ≠ (0,0)} C(a,k) C(b,l) W^(k,l) R^(a−k,b−l)) / W`. + fn row(&self, u: f64, v: f64, du: usize, dv: usize) -> SplineResult> { + self.row_sided(u, v, du, dv, [false; 2]) + } + + /// The basis of the space along `d` at `t`, from the left of a knot when `left`. + fn basis(&self, d: usize, t: f64, r: usize, left: bool) -> SplineResult<(usize, Vec)> { + let space = self.spaces.get(d).ok_or_else(|| SplineError::Invalid("a patch has two directions".into()))?; + if left { space.basis_left(t, r) } else { space.basis(t, r) } + } + + /// [`Patch::row`] with each direction's basis taken from the left of a knot where `left` + /// says so: the derivative of the piece ending there. + fn row_sided(&self, u: f64, v: f64, du: usize, dv: usize, left: [bool; 2]) -> SplineResult> { + if !self.rational { + let (iu, bu) = self.basis(0, u, du, left[0])?; + let (iv, bv) = self.basis(1, v, dv, left[1])?; + let mut out = Vec::with_capacity(bu.len() * bv.len()); + for (b, nv) in bv.iter().enumerate() { + for (a, nu) in bu.iter().enumerate() { + out.push((iu + a, iv + b, nu * nv)); + } + } + return Ok(out); + } + // The basis and its derivatives up to the orders asked, each way. + let ders = |d: usize, t: f64, top: usize| -> SplineResult<(usize, Vec>)> { + let mut first = 0; + let mut out = Vec::with_capacity(top + 1); + for r in 0..=top { + let (f, b) = self.basis(d, t, r, left.get(d).copied().unwrap_or(false))?; + first = f; + out.push(b); + } + Ok((first, out)) + }; + let (iu, bu) = ders(0, u, du)?; + let (iv, bv) = ders(1, v, dv)?; + let width = (bu.first().map_or(0, Vec::len), bv.first().map_or(0, Vec::len)); + let basis = |d: &[Vec], r: usize, a: usize| d.get(r).and_then(|x| x.get(a)).copied().unwrap_or(0.0); + // W^(k,l) at the point. + let mut wd = vec![vec![0.0; dv + 1]; du + 1]; + for b in 0..width.1 { + for a in 0..width.0 { + let w = self.weight(iu + a, iv + b); + for (k, row) in wd.iter_mut().enumerate() { + for (l, x) in row.iter_mut().enumerate() { + *x += w * basis(&bu, k, a) * basis(&bv, l, b); + } + } + } + } + let w0 = wd.first().and_then(|r| r.first()).copied().unwrap_or(0.0); + if !(w0 > 0.0) { + return invalid("a patch's weights vanish"); + } + let binom = |n: usize, k: usize| (0..k).fold(1.0, |c, i| c * (n - i) as f64 / (i + 1) as f64); + let mut out = Vec::with_capacity(width.0 * width.1); + let mut r = vec![vec![0.0; dv + 1]; du + 1]; + for b in 0..width.1 { + for a in 0..width.0 { + let w = self.weight(iu + a, iv + b); + for total in 0..=du + dv { + for k in 0..=du.min(total) { + let l = total - k; + if l > dv { + continue; + } + let mut x = w * basis(&bu, k, a) * basis(&bv, l, b); + for i in 0..=k { + for j in 0..=l { + if i == 0 && j == 0 { + continue; + } + let wij = wd.get(i).and_then(|x| x.get(j)).copied().unwrap_or(0.0); + let rr = r.get(k - i).and_then(|x| x.get(l - j)).copied().unwrap_or(0.0); + x -= binom(k, i) * binom(l, j) * wij * rr; + } + } + if let Some(slot) = r.get_mut(k).and_then(|x| x.get_mut(l)) { + *slot = x / w0; + } + } + } + out.push((iu + a, iv + b, r.get(du).and_then(|x| x.get(dv)).copied().unwrap_or(0.0))); + } + } + Ok(out) + } + + fn eval(&self, u: f64, v: f64, du: usize, dv: usize) -> SplineResult { + Ok(self.row(u, v, du, dv)?.iter().fold(Vec3::ZERO, |s, (i, j, c)| s + self.at(*i, *j) * *c)) + } + + fn normal(&self, u: f64, v: f64) -> Option { + let (su, sv) = (self.eval(u, v, 1, 0).ok()?, self.eval(u, v, 0, 1).ok()?); + su.cross(sv).normalized() + } + + fn surface(&self) -> SplineResult { + let [cu, cv] = self.counts(); + let ctrl: Vec = + (0..cv).flat_map(|j| (0..cu).map(move |i| (i, j))).map(|(i, j)| HPoint::weighted(self.at(i, j), self.weight(i, j))).collect(); + let [su, sv] = &self.spaces; + NurbsSurface::from_homogeneous([su.degree(), sv.degree()], [su.knots().to_vec(), sv.knots().to_vec()], ctrl) + } +} + +/// Where side `s` of a patch runs on the unit square: (u, v) at its start and end. +fn side_uv(s: usize) -> [[f64; 2]; 2] { + match s { + 0 => [[0.0, 0.0], [1.0, 0.0]], + 1 => [[1.0, 0.0], [1.0, 1.0]], + 2 => [[1.0, 1.0], [0.0, 1.0]], + _ => [[0.0, 1.0], [0.0, 0.0]], + } +} + +/// At fraction `t` of side `s`: (u, v), and the derivative across into the patch +/// (`(du, dv, sign)`: the order taken along u or v, and its sign). +fn station_on(s: usize, t: f64) -> ([f64; 2], (usize, usize, f64)) { + let [a, b] = side_uv(s); + let uv = [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; + let across = match s { + 0 => (0, 1, 1.0), + 1 => (1, 0, -1.0), + 2 => (0, 1, -1.0), + _ => (1, 0, 1.0), + }; + (uv, across) +} + +/// The fill's control points: the patches, and which of their points are free (each free point +/// one unknown, a spoke's or the centre's shared by the patches it bounds). +struct Quilt { + patches: Vec, + /// Per patch, per control point: its unknown, `None` where the loop holds it. + slots: Vec>>, + unknowns: usize, + /// The loop edges' pieces on the patches' sides. + pieces: Vec, + /// The curves inside the fill two patches share, each joined G1 across. + spokes: Vec, + /// The fill's vertices inside the loop: a patch and its control point there. + inner: Vec<(usize, usize, usize)>, + /// How the fill's middle is crowned. + layout: Layout, +} + +/// How the region is laid out in patches (module docs). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Layout { + /// One patch on three or four sides. + One, + /// N patches about a centre. + Centre, + /// Four patches round the loop and one inside them. + Ring, +} + +/// A curve inside the fill shared by two patches: it runs along side `a.1` of patch `a.0` in that +/// side's direction (`t` from 0 to 1) and back along side `b.1` of patch `b.0`. Across it, with +/// `D_a`, `D_b` each patch's derivative across it away from itself and `L` the derivative along it, +/// `D_a + β(t)·D_b = α(t)·L`: the linear gluing of a G1 join, `α` and `β` linear between their +/// values at the ends (module docs). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Seam { + a: (usize, usize), + b: (usize, usize), + alpha: [f64; 2], + beta: [f64; 2], + ends: [SpokeEnd; 2], +} + +impl Seam { + /// Where on each patch's side the seam is at its parameter `t`. + fn at(&self, t: f64) -> ([f64; 2], [f64; 2]) { + (station_on(self.a.1, t).0, station_on(self.b.1, 1.0 - t).0) + } + + /// The gluing functions at `t`. + fn gluing(&self, t: f64) -> (f64, f64) { + let lerp = |x: [f64; 2]| x[0] + (x[1] - x[0]) * t; + (lerp(self.alpha), lerp(self.beta)) + } + + /// Whether `t` is within `share` of an end inside the loop (an inner vertex). + fn near_inner(&self, t: f64, share: f64) -> bool { + (matches!(self.ends[0], SpokeEnd::Inner(_)) && t < share) || (matches!(self.ends[1], SpokeEnd::Inner(_)) && t > 1.0 - share) + } +} + +/// The gluing at a spoke's foot on the loop: `(β, α)` with `D_a + β·D_b = α·L` for the two +/// patches' derivatives across it away from themselves (there, the loop's two sides' tangents, run +/// apart) and the spoke's own `L`, least squares in their plane. Where the loop runs straight on, +/// `α = 0` and `β` is the ratio of the sides' speeds. +fn foot_gluing(da: Vec3, db: Vec3, l: Vec3) -> (f64, f64) { + // [db, −l]·(β, α) = −da. + let (a11, a12, a22) = (db.dot(db), -db.dot(l), l.dot(l)); + let (r1, r2) = (-db.dot(da), l.dot(da)); + let det = a11 * a22 - a12 * a12; + if !(det.abs() > 1e-300) { + return (1.0, 0.0); + } + ((r1 * a22 - a12 * r2) / det, (a11 * r2 - a12 * r1) / det) +} + +/// The derivative of order one along side `s` of the unit square, in its running direction: +/// `(du, dv, sign)`. +fn along_side(s: usize) -> (usize, usize, f64) { + match s { + 0 => (1, 0, 1.0), + 1 => (0, 1, 1.0), + 2 => (1, 0, -1.0), + _ => (0, 1, -1.0), + } +} + +/// The gluing function `α` at an end of a seam at an inner vertex of `valence` patches: the value +/// the regular characteristic map meets there, `2·cos(2π/m)` with the seam's parameter running +/// towards the vertex (`towards`), its opposite running away (module docs). +fn characteristic(valence: usize, towards: bool) -> f64 { + let a = 2.0 * (std::f64::consts::TAU / valence.max(1) as f64).cos(); + if towards { a } else { -a } +} + +/// The constants each edge's homogeneous points are scaled by so that the weights at every +/// corner of the loop agree (module docs); refused when no such constants exist. +fn corner_scales(edges: &[IsoEdge]) -> SplineResult> { + let ends = |e: &IsoEdge| { + let w = e.weights.as_ref(); + (w.and_then(|w| w.first()).copied().unwrap_or(1.0), w.and_then(|w| w.last()).copied().unwrap_or(1.0)) + }; + let mut scales = Vec::with_capacity(edges.len()); + let mut c = 1.0 / edges.first().map_or(1.0, |e| ends(e).0); + for (k, e) in edges.iter().enumerate() { + if k > 0 { + let (_, before) = edges.get(k - 1).map(ends).unwrap_or((1.0, 1.0)); + c *= before / ends(e).0; + } + scales.push(c); + } + let closing = edges.last().map_or(1.0, |e| ends(e).1) * scales.last().copied().unwrap_or(1.0); + if !(closing.is_finite() && (closing - 1.0).abs() <= WEIGHT_TOL) { + return Err(SplineError::Unsupported( + "a patch on rational edges whose weights at the loop's corners cannot be made to agree (their end-to-start ratios round the loop multiply to more or less than one)".into(), + )); + } + Ok(scales) +} + +impl Quilt { + /// The fill's patches over the loop's sides at degree `degree` (at least) in spaces refined + /// by `extra` breaks (along u and v). One patch has a space each way, each holding the two + /// sides that run that way; about a centre, the space along each spoke is the two patches' + /// either side of it (one's along v, the other's along u), holding the spoke and the two edge + /// halves it meets those patches beside. + fn new(edges: &[IsoEdge], loop_sides: &[Vec], ring: bool, extra: &[Vec; 2], degree: usize) -> SplineResult { + let n = loop_sides.len(); + let scales = corner_scales(edges)?; + let whole: Vec = loop_sides.iter().map(|side| side_curve(edges, &scales, side)).collect::>()?; + let part = |k: usize, range: [f64; 2], reverse: bool| -> SplineResult { + let c = whole.get(k).ok_or_else(|| SplineError::Invalid("sides".into()))?; + piece_on_unit(c.space.degree(), c.space.knots(), &c.points, range, reverse) + }; + if ring { + return Quilt::ring(loop_sides, &whole, extra, degree); + } + if n <= 4 { + // One patch: the loop's sides are its sides (side 2 and 3 run back along their rows). + let mut sides: Vec = (0..n).map(|k| part(k, [0.0, 1.0], k >= 2)).collect::>()?; + if n == 3 { + let pole = whole.first().and_then(|c| c.points.first().copied()).unwrap_or(HPoint::ZERO); + sides.push(line(pole, pole)?); + } + let (Some(s0), Some(s1), Some(s2), Some(s3)) = (sides.first(), sides.get(1), sides.get(2), sides.get(3)) else { return invalid("sides") }; + let (su, along_u) = compatible(&[s0, s2], &extra[0], degree)?; + let (sv, along_v) = compatible(&[s3, s1], &extra[1], degree)?; + let (Some(c0), Some(c2), Some(c3), Some(c1)) = (along_u.first(), along_u.get(1), along_v.first(), along_v.get(1)) else { + return invalid("sides"); + }; + let patch = coons([su, sv], c0, c2, c3, c1, n == 3)?; + // The free points numbered with the shorter direction fastest, which keeps the + // normal equations' band narrow. + let [cu, cv] = patch.counts(); + let mut slots = vec![None; cu * cv]; + let (inner_u, inner_v) = (cu.saturating_sub(2), cv.saturating_sub(2)); + for j in 1..cv - 1 { + for i in 1..cu - 1 { + let id = if inner_u <= inner_v { (i - 1) + inner_u * (j - 1) } else { (j - 1) + inner_v * (i - 1) }; + if let Some(s) = slots.get_mut(i + cu * j) { + *s = Some(id); + } + } + } + let unknowns = inner_u * inner_v; + let pieces = loop_sides.iter().enumerate().flat_map(|(k, side)| pieces_between(side, k, [0.0, 1.0], 0, k)).collect(); + return Ok(Quilt { + patches: vec![patch], + slots: vec![slots], + unknowns, + pieces, + spokes: Vec::new(), + inner: Vec::new(), + layout: Layout::One, + }); + } + // N patches about the centre: halves of each side, and straight spokes to start. + let middle: Vec = whole.iter().map(|c| c.space.eval(&c.points, 0.5, 0)).collect::>()?; + let centre = middle.iter().filter_map(|h| h.project()).fold(Vec3::ZERO, |s, p| s + p) * (1.0 / n as f64); + let mut curves: Vec = Vec::with_capacity(3 * n); + for k in 0..n { + curves.push(part(k, [0.0, 0.5], false)?); + // The second half runs up u = 0 of the next patch: from V (v = 0) back to M. + curves.push(part(k, [0.5, 1.0], true)?); + } + for m in &middle { + curves.push(line(*m, HPoint::weighted(centre, 1.0))?); + } + // Space k runs along spoke k: it is patch k's along v (its sides edge k − 1's second half + // and spoke k) and patch k + 1's along u (edge k + 1's first half and spoke k), so it + // holds those three curves' breaks only, not every edge's. + let mut spaces: Vec = Vec::with_capacity(n); + // Each curve carried into the space it runs in: [first half, second half] per edge, and + // each spoke. + let mut first_half: Vec>> = vec![None; n]; + let mut second_half: Vec>> = vec![None; n]; + let mut spoke_rows: Vec> = Vec::with_capacity(n); + for k in 0..n { + let (prev, next) = ((k + n - 1) % n, (k + 1) % n); + let refs = [ + curves.get(2 * prev + 1).ok_or_else(|| SplineError::Invalid("curves".into()))?, + curves.get(2 * next).ok_or_else(|| SplineError::Invalid("curves".into()))?, + curves.get(2 * n + k).ok_or_else(|| SplineError::Invalid("curves".into()))?, + ]; + let (space, mut rows) = compatible(&refs, &extra[0], degree)?; + let spoke = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?; + let first = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?; + let second = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?; + second_half[prev] = Some(second); + first_half[next] = Some(first); + spoke_rows.push(spoke); + spaces.push(space); + } + let got = |v: &[Option>], k: usize| v.get(k).cloned().flatten().ok_or_else(|| SplineError::Invalid("rows".into())); + let space = |k: usize| spaces.get(k).cloned().ok_or_else(|| SplineError::Invalid("spaces".into())); + let spoke_row = |k: usize| spoke_rows.get(k).cloned().ok_or_else(|| SplineError::Invalid("rows".into())); + let mut patches = Vec::with_capacity(n); + for k in 0..n { + let prev = (k + n - 1) % n; + // Along u, space k − 1: v = 0 edge k's first half, v = 1 spoke k − 1 (from M_{k−1} to + // C); along v, space k: u = 0 edge k − 1's second half (from V_k up to M_{k−1}), + // u = 1 spoke k. + patches.push(coons( + [space(prev)?, space(k)?], + &got(&first_half, k)?, + &spoke_row(prev)?, + &got(&second_half, prev)?, + &spoke_row(k)?, + false, + )?); + } + // The spokes are shared rows: their weights the same in both patches (the Coons blends + // agree on them), and so are their points once solved. + // Unknowns: each spoke's points past its midpoint, the centre once, each patch's + // interior. + let mut unknowns = 0usize; + let mut next = || { + unknowns += 1; + unknowns - 1 + }; + let centre_id = next(); + let spoke_ids: Vec> = spaces.iter().map(|sp| (1..sp.count().saturating_sub(1)).map(|_| next()).collect()).collect(); + let mut slots = Vec::with_capacity(n); + for k in 0..n { + let prev = (k + n - 1) % n; + let [cu, cv] = patches.get(k).map(Patch::counts).ok_or_else(|| SplineError::Invalid("patch".into()))?; + let mut s = vec![None; cu * cv]; + for j in 1..cv { + for i in 1..cu { + let id = match (i == cu - 1, j == cv - 1) { + (true, true) => centre_id, + (true, false) => *spoke_ids.get(k).and_then(|x| x.get(j - 1)).ok_or_else(|| SplineError::Invalid("spoke".into()))?, + (false, true) => *spoke_ids.get(prev).and_then(|x| x.get(i - 1)).ok_or_else(|| SplineError::Invalid("spoke".into()))?, + (false, false) => next(), + }; + if let Some(slot) = s.get_mut(i + cu * j) { + *slot = Some(id); + } + } + } + slots.push(s); + } + let mut pieces = Vec::with_capacity(2 * n); + let mut spokes = Vec::with_capacity(n); + for (k, side) in loop_sides.iter().enumerate() { + pieces.extend(pieces_between(side, k, [0.0, 0.5], k, 0)); + pieces.extend(pieces_between(side, k, [0.5, 1.0], (k + 1) % n, 3)); + let (edge, t) = on_side(side, 0.5).ok_or_else(|| SplineError::Invalid("a side's middle".into()))?; + // Spoke k up patch k's u = 1 (from the midpoint to the centre), back along patch + // k + 1's v = 1; at the midpoint the edge's halves leave it at the same speed. + spokes.push(Seam { + a: (k, 1), + b: ((k + 1) % n, 2), + alpha: [0.0, characteristic(n, true)], + beta: [1.0, 1.0], + ends: [SpokeEnd::Loop { edge, t }, SpokeEnd::Inner(0)], + }); + } + let [cu, cv] = patches.first().map(Patch::counts).ok_or_else(|| SplineError::Invalid("patch".into()))?; + Ok(Quilt { patches, slots, unknowns, pieces, spokes, inner: vec![(0, cu - 1, cv - 1)], layout: Layout::Centre }) + } + + /// The ring (module docs): on four sides `P_k → P_{k+1}` of a loop with fewer than three + /// corners, ring patch `k` has the side along `v = 0`, spoke `r_{k+1}` (from `P_{k+1}` to the + /// inner corner `Q_{k+1}`) up `u = 1`, the inner patch's side `i_k` (from `Q_k` to `Q_{k+1}`) + /// along `v = 1` and spoke `r_k` down `u = 0`; the inner patch (patch 4) has the corners + /// `Q_0 … Q_3` and `i_k` as its side `k`. Every point of the loop is on two patches' sides, so + /// no patch has a corner where the loop runs straight on. The spaces: one along the loop and + /// the inner sides (holding each side and its reversal, so the inner patch holds `i_2` and + /// `i_3` run back), one along the spokes; `Q_k` starts half way from `P_k` to the centre. + fn ring(loop_sides: &[Vec], whole: &[Curve], extra: &[Vec; 2], degree: usize) -> SplineResult { + let bad = || SplineError::Invalid("a ring of four sides".into()); + if whole.len() != 4 || loop_sides.len() != 4 { + return Err(bad()); + } + let start = |k: usize| whole.get(k).and_then(|c| c.points.first().copied()).unwrap_or(HPoint::ZERO); + let middle: Vec = whole + .iter() + .map(|c| c.space.eval(&c.points, 0.5, 0)) + .collect::>>()? + .into_iter() + .filter_map(HPoint::project) + .collect(); + let centre = middle.iter().fold(Vec3::ZERO, |s, p| s + *p) * (1.0 / middle.len().max(1) as f64); + let q: Vec = (0..4).map(|k| start(k).project().map_or(HPoint::ZERO, |p| HPoint::weighted(p + (centre - p) * 0.5, 1.0))).collect(); + let at = |v: &[HPoint], k: usize| v.get(k % 4).copied().unwrap_or(HPoint::ZERO); + let radial: Vec = (0..4).map(|k| line(start(k), at(&q, k))).collect::>()?; + let inner: Vec = (0..4).map(|k| line(at(&q, k), at(&q, k + 1))).collect::>()?; + let reversed = |c: &Curve| piece_on_unit(c.space.degree(), c.space.knots(), &c.points, [0.0, 1.0], true); + let backs: Vec = whole.iter().map(reversed).collect::>()?; + let along: Vec<&Curve> = whole.iter().chain(&backs).chain(&inner).collect(); + let (ring_space, rows) = compatible(&along, &extra[0], degree)?; + let (spoke_space, spoke_rows) = compatible(&radial.iter().collect::>(), &extra[0], degree)?; + let row = |v: &[Vec], k: usize| v.get(k).cloned().ok_or_else(bad); + let back = |mut r: Vec| { + r.reverse(); + r + }; + let mut patches = Vec::with_capacity(5); + for k in 0..4 { + patches.push(coons( + [ring_space.clone(), spoke_space.clone()], + &row(&rows, k)?, + &row(&rows, 8 + k)?, + &row(&spoke_rows, k)?, + &row(&spoke_rows, (k + 1) % 4)?, + false, + )?); + } + patches.push(coons( + [ring_space.clone(), ring_space.clone()], + &row(&rows, 8)?, + &back(row(&rows, 10)?), + &back(row(&rows, 11)?), + &row(&rows, 9)?, + false, + )?); + let (cu, cv) = (ring_space.count(), spoke_space.count()); + let mut unknowns = 0usize; + let mut next = || { + unknowns += 1; + unknowns - 1 + }; + let q_id: Vec = (0..4).map(|_| next()).collect(); + let spoke_ids: Vec> = (0..4).map(|_| (1..cv.saturating_sub(1)).map(|_| next()).collect()).collect(); + let side_ids: Vec> = (0..4).map(|_| (1..cu.saturating_sub(1)).map(|_| next()).collect()).collect(); + // Point m (from Q_k) of the inner side i_k, and point j (from P_k) of the spoke r_k. + let on_side = |k: usize, m: usize| -> Option { + if m == 0 { + q_id.get(k % 4).copied() + } else if m + 1 == cu { + q_id.get((k + 1) % 4).copied() + } else { + side_ids.get(k % 4).and_then(|s| s.get(m - 1)).copied() + } + }; + let on_spoke = |k: usize, j: usize| -> Option { + if j + 1 == cv { q_id.get(k % 4).copied() } else { spoke_ids.get(k % 4).and_then(|s| s.get(j - 1)).copied() } + }; + let mut slots = Vec::with_capacity(5); + for k in 0..4 { + let mut s = vec![None; cu * cv]; + for j in 1..cv { + for i in 0..cu { + let id = if i == 0 { + on_spoke(k, j) + } else if i + 1 == cu { + on_spoke(k + 1, j) + } else if j + 1 == cv { + on_side(k, i) + } else { + Some(next()) + }; + if let Some(slot) = s.get_mut(i + cu * j) { + *slot = Some(id.ok_or_else(bad)?); + } + } + } + slots.push(s); + } + let mut s = vec![None; cu * cu]; + for j in 0..cu { + for i in 0..cu { + let id = if j == 0 { + on_side(0, i) + } else if i + 1 == cu { + on_side(1, j) + } else if j + 1 == cu { + on_side(2, cu - 1 - i) + } else if i == 0 { + on_side(3, cu - 1 - j) + } else { + Some(next()) + }; + if let Some(slot) = s.get_mut(i + cu * j) { + *slot = Some(id.ok_or_else(bad)?); + } + } + } + slots.push(s); + let pieces = loop_sides.iter().enumerate().flat_map(|(k, side)| pieces_between(side, k, [0.0, 1.0], k, 0)).collect(); + // The seams: spoke r_k between ring patches k − 1 (its u = 1) and k (its u = 0), glued at + // P_k by what the loop's two sides there ask (their derivatives against each other, and + // the spoke's), at Q_k by the valence-3 characteristic; side i_k between ring patch k + // (its v = 1, from Q_{k+1} to Q_k) and the inner patch (its side k). + let mut spokes = Vec::with_capacity(8); + for k in 0..4 { + let prev = (k + 3) % 4; + let (Some(a), Some(b)) = (patches.get(prev), patches.get(k)) else { return Err(bad()) }; + let (da, db) = (a.eval(1.0, 0.0, 1, 0)?, b.eval(0.0, 0.0, 1, 0)? * -1.0); + let l = b.eval(0.0, 0.0, 0, 1)?; + let (beta, alpha) = foot_gluing(da, db, l); + let foot = loop_sides.get(k).and_then(|s| s.first()).map(|sp| SpokeEnd::Loop { edge: sp.edge, t: sp.range[0] }).ok_or_else(bad)?; + spokes.push(Seam { + a: (prev, 1), + b: (k, 3), + alpha: [alpha, characteristic(3, true)], + beta: [beta, 1.0], + ends: [foot, SpokeEnd::Inner(k)], + }); + } + for k in 0..4 { + let towards = characteristic(3, true); + spokes.push(Seam { + a: (k, 2), + b: (4, k), + alpha: [-towards, towards], + beta: [1.0, 1.0], + ends: [SpokeEnd::Inner((k + 1) % 4), SpokeEnd::Inner(k)], + }); + } + let last = cu - 1; + Ok(Quilt { + patches, + slots, + unknowns, + pieces, + spokes, + inner: vec![(4, 0, 0), (4, last, 0), (4, last, last), (4, 0, last)], + layout: Layout::Ring, + }) + } + + /// Most free control points one solve takes, one patch or several about a centre. + fn most_unknowns(shared: bool) -> usize { + let _ = shared; + MAX_BANDED_POINTS + } + + /// Write the unknowns' values into every patch that holds them. + fn set(&mut self, values: &[Vec3]) { + for (patch, slots) in self.patches.iter_mut().zip(&self.slots) { + for (p, s) in patch.net.iter_mut().zip(slots) { + if let Some(v) = s.and_then(|s| values.get(s)) { + *p = *v; + } + } + } + } +} + +/// The bilinearly blended Coons patch of homogeneous sides: `c0`, `c1` along u at v = 0 and 1, +/// `d0`, `d1` along v at u = 0 and 1, all running with their parameter. Points and weights are +/// blended alike, so the boundary rows are the sides' own and the weights inside are the blend +/// of theirs (refused where one is not positive). +fn coons(spaces: [Space; 2], c0: &[HPoint], c1: &[HPoint], d0: &[HPoint], d1: &[HPoint], pole: bool) -> SplineResult { + let (gu, gv) = (greville(&spaces[0]), greville(&spaces[1])); + let (cu, cv) = (gu.len(), gv.len()); + let (Some(p00), Some(p10), Some(p01), Some(p11)) = (c0.first().copied(), c0.last().copied(), c1.first().copied(), c1.last().copied()) else { + return invalid("a side has no points"); + }; + let get = |a: &[HPoint], k: usize| a.get(k).copied().unwrap_or(HPoint::ZERO); + let mut net = Vec::with_capacity(cu * cv); + let mut weights = Vec::with_capacity(cu * cv); + for (j, &y) in gv.iter().enumerate() { + for (i, &x) in gu.iter().enumerate() { + let ruled_v = get(c0, i) * (1.0 - y) + get(c1, i) * y; + let ruled_u = get(d0, j) * (1.0 - x) + get(d1, j) * x; + let bilinear = (p00 * (1.0 - x) + p10 * x) * (1.0 - y) + (p01 * (1.0 - x) + p11 * x) * y; + // The boundary rows exactly the sides' own points. + let h = match (i, j) { + (_, 0) => get(c0, i), + (_, j) if j + 1 == cv => get(c1, i), + (0, _) => get(d0, j), + (i, _) if i + 1 == cu => get(d1, j), + _ => ruled_v + ruled_u - bilinear, + }; + let p = h + .project() + .filter(|_| h.w > 0.0) + .ok_or_else(|| SplineError::Unsupported("a rational patch whose blended weights are not positive".into()))?; + net.push(p); + weights.push(h.w); + } + } + let rational = weights.iter().any(|w| *w != 1.0); + Ok(Patch { spaces, net, weights, rational, pole }) +} + +/// One condition row: `Σ along·P = value` over its terms' control points, and its weight. +#[derive(Clone)] +struct Row { + terms: Vec, + value: f64, + weight: f64, +} + +/// A control point `(i, j)` of patch `patch` in a row, its coefficient a vector (dotted with +/// the point). +#[derive(Clone, Copy)] +struct Term { + patch: usize, + i: usize, + j: usize, + along: Vec3, +} + +/// The terms of a patch's derivative coefficients `(i, j, c)` taken along `dir`. +fn along(patch: usize, coefficients: &[(usize, usize, f64)], dir: Vec3) -> Vec { + coefficients.iter().map(|&(i, j, c)| Term { patch, i, j, along: dir * c }).collect() +} + +/// The three rows `Σ terms·P = value` on each coordinate. +fn on_each_axis(rows: &mut Vec, patch_terms: &[(usize, Vec<(usize, usize, f64)>)], value: Vec3, weight: f64) { + for (axis, v) in [(Vec3::X, value.x), (Vec3::Y, value.y), (Vec3::Z, value.z)] { + let terms = patch_terms.iter().flat_map(|(p, c)| along(*p, c, axis)).collect(); + rows.push(Row { terms, value: v, weight }); + } +} + +/// A station of a loop edge: its patch, side and fraction there, its condition, whether it is +/// held to the angle tolerance, whether it is clear of the loop's corners (its curvature and +/// curvature change are reported), and how fast the fill should leave there. +struct Station { + patch: usize, + side: usize, + t: f64, + across: Across, + /// The continuity order asked here: the neighbour's, or less near a corner whose neighbours + /// do not agree to it ([`Asked`]): orders up to `full` at their full weight, those above it + /// up to `order` at `fade` of it. + order: usize, + full: usize, + fade: f64, + /// How far (radians) the edge itself leans out of the neighbour's tangent plane here: the + /// fill holds the edge, so its normal can come no nearer the neighbour's than that. + tilt: f64, + held: bool, + clear: bool, + /// The weak rows' target for the cross derivative `c′` ([`stations`]): `w·c′ = speed`, + /// `t·c′ = slide`. + speed: f64, + slide: f64, +} + +impl Station { + /// The continuity order its conditions ask: 1 (G1) … 4 (G4). + fn order(&self) -> usize { + self.order + } +} + +/// What a station asks, by how near it is to corners whose neighbours agree to less (see +/// [`corner_orders`]): within [`CLASH_SHARE`] of such a corner the orders above the corner's +/// agreement (at least G1) are not asked, and over the next [`CLASH_SHARE`] they come back +/// smoothly (`fade` from 0 to 1, a smoothstep), so the fill is not strained where they start; +/// where the corner's tangent planes disagree the station is not held to the angle tolerance. +struct Asked { + asked: usize, + full: usize, + fade: f64, + held: bool, +} + +impl Asked { + /// For a station asking `asked`, at fraction `distance` of its side from each of the side's + /// two corners, whose neighbours agree to `agreement` (`None`: no cap). + fn near(asked: usize, ends: [(Option, f64); 2]) -> Asked { + let mut a = Asked { asked, full: asked, fade: 1.0, held: true }; + for (agreement, distance) in ends { + let Some(agreed) = agreement.filter(|g| *g < asked) else { continue }; + if distance >= 2.0 * CLASH_SHARE { + continue; + } + a.full = a.full.min(agreed.max(1)); + let x = ((distance - CLASH_SHARE) / CLASH_SHARE).clamp(0.0, 1.0); + a.fade = a.fade.min(x * x * (3.0 - 2.0 * x)); + if agreed == 0 && distance < CLASH_SHARE { + a.held = false; + } + } + a + } + + /// The highest order asked at all. + fn order(&self) -> usize { + if self.fade > 0.0 { self.asked } else { self.full } + } +} + +/// The derivatives `[c′, c″, …, c⁽ⁿ⁾]` (n = `order`) of the linkage curve `c` leaving a station +/// across its edge into the patch: the iso-parameter curve, σ growing into the patch. +fn linkage(patch: &Patch, s: &Station, order: usize) -> SplineResult> { + let (uv, (du, dv, sign)) = station_on(s.side, s.t); + (1..=order).map(|k| Ok(patch.eval(uv[0], uv[1], k * du, k * dv)? * sign.powi(k as i32))).collect() +} + +/// What orders 2 … n ask of `n·c⁽ᵏ⁾` at a station ([`crate::linkage::Jet::targets`]), read +/// from the linkage curve's last derivatives `c` (element k − 2 is order k's); empty for G1. +fn targets(s: &Station, c: &[Vec3]) -> Vec { + let Some(jet) = s.across.jet else { return Vec::new() }; + let (t, w) = (s.across.normal.cross(s.across.leave), s.across.leave); + let x: Vec<[f64; 2]> = c.iter().map(|d| [d.dot(t), d.dot(w)]).collect(); + let mut out = jet.targets(&x).unwrap_or_default(); + out.truncate(s.order().saturating_sub(1)); + out +} + +/// To what order the neighbours agree at each corner of the region (`[k]`: where side `k` +/// starts), from their conditions at its two edges' ends ([`corner_agreement`]); no cap +/// (`usize::MAX`) where either edge asks only G0. +fn corner_orders( + edges: &[IsoEdge], + sides: &[Vec], + across: &mut dyn FnMut(usize, &[f64]) -> Result>, String>, + size: f64, + angle_tol: f64, +) -> SplineResult> { + let n = sides.len(); + let mut out = vec![usize::MAX; n]; + for (k, slot) in out.iter_mut().enumerate() { + // The corner where side k starts: the end of the side before's last edge, the start of + // its own first. + let (Some(last), Some(first)) = (sides.get((k + n - 1) % n).and_then(|s| s.last()), sides.get(k).and_then(|s| s.first())) else { continue }; + let (prev, k) = (last.edge, first.edge); + let (Some(ea), Some(eb)) = (edges.get(prev), edges.get(k)) else { continue }; + let (end, start) = (last.range[1], first.range[0]); + let before = across(prev, &[end]).map_err(SplineError::Invalid)?.into_iter().next().flatten(); + let after = across(k, &[start]).map_err(SplineError::Invalid)?.into_iter().next().flatten(); + if let (Some(x), Some(y), Some(d0), Some(d1)) = (before, after, ea.tangent(end), eb.tangent(start)) { + *slot = corner_agreement(&x, &y, [d0, d1], size, angle_tol); + } + } + Ok(out) +} + +/// To what order the neighbours `before` and `after` the loop's corner agree there (where no +/// surface can meet both with more): 0 when no surface can be within `angle_tol` of both +/// tangent planes there, or (with both neighbours' jets) their twists between the two edges +/// differ (at a corner the fill's normal is the loop's own, `d₀ × d₁` of the +/// edges' tangents `directions`, so each neighbour's must be within the tolerance of it; at a +/// corner where the loop runs straight on, the two must be within twice the tolerance of each +/// other); else the highest order k up to both jets' such that their forms `H_2 … H_k` agree +/// along the two tangents once carried over half the loop's `size` ([`turn`]), as the fill's +/// own jumps are held. A corner whose neighbours agree to the order asked caps nothing. +pub fn corner_agreement(before: &Across, after: &Across, directions: [Vec3; 2], size: f64, angle_tol: f64) -> usize { + let cos = before.normal.dot(after.normal); + let tangent = match directions[0].cross(directions[1]).normalized() { + Some(corner) if directions[0].dot(directions[1]) < (2.0 * angle_tol).cos() => { + [before.normal, after.normal].iter().all(|n| n.dot(corner).abs() >= angle_tol.cos()) + } + _ => cos.abs() >= (2.0 * angle_tol).cos(), + }; + if !tangent { + return 0; + } + let (Some(a), Some(b)) = (before.jet, after.jet) else { return 1 }; + // Heights along each one's own normal; along the other's they change sign with the order. + let sign = cos.signum(); + let form = |x: &Across, jet: &crate::linkage::Jet, m: usize, d: Vec3| { + let (t, w) = (x.normal.cross(x.leave), x.leave); + jet.form(m, [d.dot(t), d.dot(w)]) + }; + // G1 along both edges fixes the fill's twist `n·S_uv` at the corner twice, from each + // neighbour's second form between the two edges' directions, `H₂(d₀, d₁)` + // (`(H₂(d₀ + d₁) − H₂(d₀ − d₁)) / 4`): where those differ, not even G1 holds there. + let [d0, d1] = directions; + let twist = |x: &Across, jet: &crate::linkage::Jet| Some(0.25 * (form(x, jet, 2, d0 + d1)? - form(x, jet, 2, d0 - d1)?)); + match (twist(before, &a), twist(after, &b)) { + (Some(x), Some(y)) if turn((x - sign * y).abs(), 2, size) <= angle_tol => {} + _ => return 0, + } + let mut agreed = 1; + for m in 2..=a.order.min(b.order) { + let same = directions.iter().all(|d| match (form(before, &a, m, *d), form(after, &b, m, *d)) { + (Some(x), Some(y)) => turn((x - sign * y).abs(), m, size) <= angle_tol, + _ => false, + }); + if !same { + return agreed; + } + agreed = m; + } + agreed +} + +/// Fill the loop `edges` (three to [`MAX_ISO_EDGES`], each ending where the next starts) with +/// patches on them (module docs). `across(k, ts)` gives the neighbour's conditions at the +/// parameters `ts` of edge `k` (its own parameter; `None`: G0 there). Where the neighbours at a +/// corner agree to a lower order than asked ([`corner_orders`]), the stations within +/// [`CLASH_SHARE`] of it ask no more than that (at least G1), and where their tangent planes +/// disagree they are not held to the angle tolerance either: no surface can meet both better. +pub fn iso_fill( + edges: &[IsoEdge], + across: &mut dyn FnMut(usize, &[f64]) -> Result>, String>, + spec: &IsoSpec, +) -> SplineResult { + let n = edges.len(); + if !(3..=MAX_ISO_EDGES).contains(&n) { + return Err(SplineError::Unsupported(format!("a patch on a loop of {n} edges (three to {MAX_ISO_EDGES})"))); + } + if !(spec.tol.is_finite() && spec.tol > 0.0 && spec.angle_tol.is_finite() && spec.angle_tol > 0.0) { + return invalid("tolerances must be positive"); + } + if !(crate::fill::MIN_CROWN..=crate::fill::MAX_CROWN).contains(&spec.crown) { + return invalid("a crown must be between -0.9 and 3"); + } + if spec.points.len() > crate::fill_general::MAX_FILL_POINTS || spec.points.iter().any(|p| !p.is_finite()) { + return invalid("too many points, or a point that is not finite"); + } + for (k, e) in edges.iter().enumerate() { + let p = e.degree; + if p == 0 || p > MAX_SPLINE_DEGREE || e.points.len() <= p || e.knots.len() != e.points.len() + p + 1 { + return invalid(format!("edge {k}'s degree, knots and control points do not fit")); + } + check_knots(&e.knots)?; + let [a, b] = e.domain(); + if !(a < b) || e.points.iter().any(|q| !q.is_finite()) { + return invalid(format!("edge {k} has an empty domain or a control point that is not finite")); + } + if let Some(w) = &e.weights + && (w.len() != e.points.len() || w.iter().any(|x| !(x.is_finite() && *x > 0.0))) + { + return invalid(format!("edge {k}'s weights must be positive, one per control point")); + } + } + let mut all = edges.iter().flat_map(|e| e.points.iter().copied()); + let first = all.next().ok_or_else(|| SplineError::Invalid("an edge has no control points".into()))?; + let (lo, hi) = all.fold((first, first), |(lo, hi), p| (lo.min(p), hi.max(p))); + let size = lo.dist(hi); + for k in 0..n { + let end = edges.get(k).and_then(|e| e.points.last()).copied().unwrap_or(Vec3::ZERO); + let next = edges.get((k + 1) % n).and_then(|e| e.points.first()).copied().unwrap_or(Vec3::ZERO); + if end.dist(next) > 1e-9 * size.max(1.0) { + return invalid(format!("edge {k} does not end where edge {} starts", (k + 1) % n)); + } + } + // The highest continuity asked anywhere, from the conditions at each edge's middle (an + // edge's continuity is one along it). + let mut order = 0usize; + for k in 0..n { + let Some(e) = edges.get(k) else { continue }; + let found = across(k, &[e.middle()]).map_err(SplineError::Invalid)?; + for c in found.into_iter().flatten() { + order = order.max(c.jet.map_or(1, |j| j.order)); + } + } + if order > MAX_CONTINUITY { + return invalid(format!("a patch's continuity is at most G{MAX_CONTINUITY}")); + } + let degree = if order == 0 { 1 } else { (order + 1).min(MAX_SPLINE_DEGREE) }; + if !(spec.corner_turn.is_finite() && spec.corner_turn >= 0.0) { + return invalid("the corner turn must be a finite angle"); + } + let (sides, cornered) = loop_sides(edges, spec.corner_turn); + if !cornered && sides.len() != 4 { + return Err(SplineError::Unsupported(format!( + "a patch on a loop of {} edges with fewer than three corners (such a loop is filled in four pieces)", + sides.len() + ))); + } + let corners = corner_orders(edges, &sides, &mut *across, size, spec.angle_tol)?; + let mut extra: [Vec; 2] = [Vec::new(), Vec::new()]; + let mut spans = [1usize; 2]; + loop { + let quilt = Quilt::new(edges, &sides, !cornered, &extra, degree)?; + let stations = stations(edges, &quilt, &mut *across, &corners)?; + let spaces = quilt.patches.first().map(|p| p.spaces.clone()).ok_or_else(|| SplineError::Invalid("no patch".into()))?; + let shared = !quilt.spokes.is_empty(); + // Rows enough for the conditions from opposite sides not to share control points, in + // every patch. + let fewest = |d: usize| quilt.patches.iter().filter_map(|p| p.spaces.get(d).map(Space::count)).min().unwrap_or(0); + let cramped = [fewest(0), fewest(1)].map(|c| c < 2 * (order + 1)); + if cramped.iter().any(|c| *c) && refinable(&spans, cramped, shared, quilt.unknowns) { + halve(&mut extra, &mut spans, &spaces, cramped, shared); + continue; + } + let (quilt, report, along) = solve(quilt, &stations, spec)?; + let folded = quilt.patches.iter().any(folds); + let mut wanted = along.missing(order, size, spec.angle_tol); + if folded || report.point_deviation > spec.tol { + wanted = [true; 2]; + } + // The tangent plane, the points and an unfolded fill are what a patch must have; the + // orders above G1 are held as tightly as the finest space allows, and reported. + let must = !folded && report.point_deviation <= spec.tol && along.angle.iter().all(|a| *a <= spec.angle_tol); + let refine = refinable(&spans, wanted, shared, quilt.unknowns); + if !wanted.iter().any(|w| *w) || (must && !refine) { + let quilt = crowned(quilt, &stations, spec.crown, size)?; + return finished(quilt, report); + } + if !refine { + let jumps = + report.jumps.get(2..=order).filter(|_| order >= 2).map(|j| format!(", jumps of orders 2 to {order} {j:?}")).unwrap_or_default(); + let folded = if folded { ", and it folds" } else { "" }; + return Err(SplineError::Unsupported(format!( + "a patch on these edges within the tolerances: normals within {:.4}° of the neighbours' beyond the edges' own lean{jumps}, points within {:.2e}{folded}", + report.normal_excess.to_degrees(), + report.point_deviation + ))); + } + halve(&mut extra, &mut spans, &spaces, wanted, shared); + } +} + +/// Whether the spans may be halved in the `wanted` directions (both when the patches share one +/// space, about a centre): within [`MAX_ISO_SPANS`] each way, and the free points, doubling for +/// each direction, within what one solve takes ([`Quilt::most_unknowns`]). +fn refinable(spans: &[usize; 2], wanted: [bool; 2], shared: bool, unknowns: usize) -> bool { + let wanted = if shared { [true; 2] } else { wanted }; + let grows = wanted.iter().filter(|w| **w).count() as u32; + let spans_ok = spans.iter().zip(wanted).all(|(s, w)| !w || s * 2 <= MAX_ISO_SPANS); + spans_ok && unknowns.saturating_mul(2usize.pow(grows)) <= Quilt::most_unknowns(shared) +} + +/// Halve every span of the spaces in the `wanted` directions: the breaks that do it added to +/// `extra`. About a centre, every spoke's space takes the middles of a uniform grid as fine as +/// the refinement has reached. +fn halve(extra: &mut [Vec; 2], spans: &mut [usize; 2], spaces: &[Space; 2], wanted: [bool; 2], shared: bool) { + if shared { + // Each spoke's space has the breaks of its own sides: every one of them gets the same + // further breaks, the middles of the uniform grid at the level reached so far. + let n = spans[0]; + extra[0].extend((0..n).map(|i| (2 * i + 1) as f64 / (2 * n) as f64)); + spans[0] *= 2; + spans[1] *= 2; + return; + } + for (((e, n), s), w) in extra.iter_mut().zip(spans.iter_mut()).zip(spaces).zip(wanted) { + if w { + e.extend(breaks(s).windows(2).map(|w| 0.5 * (w[0] + w[1]))); + *n *= 2; + } + } +} + +/// Whether every jump of order 2 … `order` is within the angle tolerance once carried into the +/// fill: by Taylor's theorem a jump `j` of order k (1/lengthᵏ⁻¹) turns the normal by +/// `j·dᵏ⁻¹/(k − 1)!` at a distance `d` from the edge, and no point of the fill is farther from +/// the loop than half its `size`. So each order is held as tightly as the tangent plane is. +pub fn within_order(jumps: &[f64; MAX_CONTINUITY + 1], order: usize, size: f64, angle_tol: f64) -> bool { + (2..=order).all(|k| jumps.get(k).is_some_and(|j| turn(*j, k, size) <= angle_tol)) +} + +/// How far (radians) a jump `jump` of order `k` turns the normal over half of `size` +/// ([`within_order`]). +pub fn turn(jump: f64, k: usize, size: f64) -> f64 { + let factorial: f64 = (1..k).map(|i| i as f64).product(); + jump * (0.5 * size).powi(k as i32 - 1) / factorial +} + +/// The patches, their sides and the spokes. +fn finished(quilt: Quilt, achieved: Achieved) -> SplineResult { + let n = quilt.patches.len(); + let mut patches = Vec::with_capacity(n); + for (k, patch) in quilt.patches.iter().enumerate() { + // Each side with where it starts round the patch: its side of the square, and how far + // along it. + let mut sides: Vec<((usize, f64), IsoSide)> = Vec::with_capacity(4); + for pc in quilt.pieces.iter().filter(|pc| pc.patch == k) { + let [a, b] = side_uv(pc.side); + let lerp = |x: f64| [a[0] + (b[0] - a[0]) * x, a[1] + (b[1] - a[1]) * x]; + let [from, to] = pc.piece.range; + sides.push(((pc.side, pc.along[0]), IsoSide::Edge { edge: pc.piece.edge, from, to, uv: [lerp(pc.along[0]), lerp(pc.along[1])] })); + } + for (i, seam) in quilt.spokes.iter().enumerate() { + if seam.a.0 == k { + sides.push(((seam.a.1, 0.0), IsoSide::Spoke { spoke: i, forward: true, uv: side_uv(seam.a.1) })); + } + if seam.b.0 == k { + sides.push(((seam.b.1, 0.0), IsoSide::Spoke { spoke: i, forward: false, uv: side_uv(seam.b.1) })); + } + } + // The loop's order round the patch. + sides.sort_by(|a, b| a.0.0.cmp(&b.0.0).then(a.0.1.total_cmp(&b.0.1))); + patches.push(IsoPatch { surface: patch.surface()?, sides: sides.into_iter().map(|(_, s)| s).collect() }); + } + let spokes = quilt.spokes.iter().map(|seam| boundary_row(&quilt, seam.a)).collect::>()?; + let inner = quilt.inner.iter().map(|&(p, i, j)| quilt.patches.get(p).map(|x| x.at(i, j)).unwrap_or(Vec3::ZERO)).collect(); + Ok(IsoFill { patches, spokes, ends: quilt.spokes.iter().map(|s| s.ends).collect(), inner, achieved }) +} + +/// The boundary row of side `s` of patch `p` as a curve in the side's running direction. +fn boundary_row(quilt: &Quilt, (p, s): (usize, usize)) -> SplineResult { + let patch = quilt.patches.get(p).ok_or_else(|| SplineError::Invalid("patch".into()))?; + let [cu, cv] = patch.counts(); + let space = patch.spaces.get(s % 2).ok_or_else(|| SplineError::Invalid("space".into()))?; + let cells: Vec<(usize, usize)> = match s { + 0 => (0..cu).map(|i| (i, 0)).collect(), + 1 => (0..cv).map(|j| (cu - 1, j)).collect(), + 2 => (0..cu).rev().map(|i| (i, cv - 1)).collect(), + _ => (0..cv).rev().map(|j| (0, j)).collect(), + }; + let mut knots = space.knots().to_vec(); + if s >= 2 { + knots = knots.iter().rev().map(|k| 1.0 - k).collect(); + } + let weights = patch.rational.then(|| cells.iter().map(|&(i, j)| patch.weight(i, j)).collect()); + Ok(IsoEdge { degree: space.degree(), knots, points: cells.iter().map(|&(i, j)| patch.at(i, j)).collect(), weights }) +} + +/// Stations along a side: [`STATIONS_PER_SPAN`] a span and [`STATIONS_PER_POINT`] per control +/// point of a row (each order of continuity holds one row of them, so the stations must outnumber +/// a row's points well for the conditions to hold between them too), at least [`MIN_STATIONS`]. +fn station_count(space: &Space) -> usize { + (breaks(space).len().saturating_sub(1) * STATIONS_PER_SPAN).max(STATIONS_PER_POINT * space.count()).max(MIN_STATIONS) +} + +/// The stations of every loop edge with a condition: enough of them for the space's spans. +fn stations( + edges: &[IsoEdge], + quilt: &Quilt, + across: &mut dyn FnMut(usize, &[f64]) -> Result>, String>, + corners: &[usize], +) -> SplineResult> { + let n = corners.len(); + let mut out = Vec::new(); + for pc in &quilt.pieces { + let (k, patch, side) = (pc.piece.edge, pc.patch, pc.side); + // The space the side runs in: u for sides 0 and 2, v for 1 and 3. + let Some(space) = quilt.patches.get(patch).and_then(|p| p.spaces.get(side % 2)) else { continue }; + // As many as the side's space asks, for the piece's share of the side. + let count = ((station_count(space) as f64) * (pc.along[1] - pc.along[0])).ceil().max(2.0) as usize; + // Stations inside the piece (its corners are its neighbours' corners); every side runs + // the loop's way round its patch, as the edge does. + let xs: Vec = (0..count).map(|i| (i as f64 + 0.5) / count as f64).collect(); + let params: Vec = xs.iter().map(|x| pc.param(*x)).collect(); + let found = across(k, ¶ms).map_err(SplineError::Invalid)?; + let Some(p) = quilt.patches.get(patch) else { continue }; + for ((&x, ¶m), c) in xs.iter().zip(¶ms).zip(found) { + let Some(c) = c else { continue }; + // Along the patch's side, and along the region's side (from its corner). + let t = pc.along[0] + (pc.along[1] - pc.along[0]) * x; + let f = pc.piece.at[0] + (pc.piece.at[1] - pc.piece.at[0]) * x; + let asked = c.jet.map_or(1, |j| j.order); + let ends = [(corners.get(pc.side_of).copied(), f), (corners.get((pc.side_of + 1) % n.max(1)).copied(), 1.0 - f)]; + let ask = Asked::near(asked, ends); + let clear = f > CORNER_SHARE && f < 1.0 - CORNER_SHARE && ask.full == asked; + let (uv, (du, dv, sign)) = station_on(side, t); + // The Coons start's cross derivative turned about the edge into the neighbour's + // tangent plane: its part along the edge kept, the rest laid along the leave + // direction at its own length. At a corner it is the next side's tangent, which the + // patch's cross derivative is there whatever its inside (module docs). + let d = p.eval(uv[0], uv[1], du, dv)? * sign; + let slide = d.dot(c.normal.cross(c.leave)); + let speed = (d.dot(d) - slide * slide).max(0.0).sqrt(); + let tilt = edges.get(k).and_then(|e| e.tangent(param)).map_or(0.0, |d| d.dot(c.normal).abs().clamp(0.0, 1.0).asin()); + out.push(Station { + patch, + side, + t, + across: c, + order: ask.order(), + full: ask.full, + fade: ask.fade, + tilt, + held: ask.held, + clear, + speed, + slide, + }); + } + } + Ok(out) +} + +/// The fill's free control points by least squares (module docs), and what they achieve. +fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult<(Quilt, Achieved, Along)> { + if quilt.unknowns == 0 { + return Ok((quilt, Achieved::default(), Along::default())); + } + let most = Quilt::most_unknowns(!quilt.spokes.is_empty()); + if quilt.unknowns > most { + return Err(SplineError::TooLarge(format!("{} free control points (at most {most})", quilt.unknowns))); + } + let fairing = stations.iter().map(Station::order).max().unwrap_or(1).max(1) + 1; + let energy: Vec> = quilt.patches.iter().map(|p| energy(p, fairing)).collect::>()?; + let mut located: Vec<(usize, [f64; 2])> = Vec::new(); + let mut report = Achieved::default(); + let mut along = Along::default(); + let spoke_count = quilt.patches.iter().map(|p| station_count(&p.spaces[0])).max().unwrap_or(0); + let top = stations.iter().map(Station::order).max().unwrap_or(1); + // The mean span of each space of a patch. + let span = |p: &Patch| p.spaces.clone().map(|s| 1.0 / breaks(&s).len().saturating_sub(1).max(1) as f64); + let rounds = if top >= 2 { ROUNDS_PER_ORDER * top } else { ROUNDS }; + let smooth = knot_line_rows(&quilt, spec.angle_tol)?; + for round in 0..rounds { + let mut rows: Vec = smooth.clone(); + for s in stations { + let Some(patch) = quilt.patches.get(s.patch) else { continue }; + // The span across the side: of v for sides 0 and 2, of u for 1 and 3. + linkage_rows(&mut rows, patch, s, span(patch).get(1 - s.side % 2).copied().unwrap_or(1.0))?; + } + // Across each spoke the two patches' derivatives away from it are opposed, up to the + // gluing functions (module docs). + for seam in &quilt.spokes { + let ((pa, sa), (pb, sb)) = (seam.a, seam.b); + let (Some(a), Some(b)) = (quilt.patches.get(pa), quilt.patches.get(pb)) else { continue }; + for i in 0..spoke_count { + let t = (i as f64 + 0.5) / spoke_count as f64; + let (ua, ub) = seam.at(t); + let (alpha, beta) = seam.gluing(t); + // Away from each patch: against its derivative into it. + let ((_, (da, ea, ga)), (_, (db, eb, gb))) = (station_on(sa, t), station_on(sb, 1.0 - t)); + let (la, ma, ha) = along_side(sa); + let scaled = |row: Vec<(usize, usize, f64)>, c: f64| row.into_iter().map(|(i, j, x)| (i, j, c * x)).collect::>(); + on_each_axis( + &mut rows, + &[ + (pa, scaled(a.row(ua[0], ua[1], da, ea)?, -ga)), + (pb, scaled(b.row(ub[0], ub[1], db, eb)?, -gb * beta)), + (pa, scaled(a.row(ua[0], ua[1], la, ma)?, -alpha * ha)), + ], + Vec3::ZERO, + 1.0, + ); + } + } + for (p, (patch, uv)) in spec.points.iter().zip(&located) { + let Some(on) = quilt.patches.get(*patch) else { continue }; + on_each_axis(&mut rows, &[(*patch, on.row(uv[0], uv[1], 0, 0)?)], *p, 1.0); + } + let solved = least_squares(&quilt, &rows, &energy)?; + quilt.set(&solved); + located = spec.points.iter().map(|p| nearest(&quilt, *p)).collect(); + (report, along) = measure(&quilt, stations, spec.points, &located, spoke_count)?; + let relinearise = top >= 2 || !spec.points.is_empty(); + if !relinearise && round == 0 { + break; + } + } + Ok((quilt, report, along)) +} + +/// Rows that keep a patch tangent continuous across its own C0 knot lines (a break where a +/// side is only C0 in its parameter, such as a circle's quarter joint once in homogeneous form): +/// along the line `u = x` (or `v = x`), at stations, the derivative across it from the right is +/// the one from the left times `r`, the ratio the two sides crossing the line have there (they +/// are tangent continuous, their speeds may differ), blended linearly between them; at the sides +/// the rows hold by construction. A line where a crossing side turns a corner is left alone: no +/// surface is tangent across it there. A three-sided patch's pole takes the other side's ratio. +fn knot_line_rows(quilt: &Quilt, angle_tol: f64) -> SplineResult> { + let mut rows = Vec::new(); + for (k, patch) in quilt.patches.iter().enumerate() { + for d in 0..2 { + let (Some(space), Some(other)) = (patch.spaces.get(d), patch.spaces.get(1 - d)) else { continue }; + let count = station_count(other); + for (x, m) in interior_knots(space) { + if m < space.degree() { + continue; + } + // The point (x, t) in the patch's (u, v), and its one-sided derivatives across. + let at = |t: f64| if d == 0 { [x, t] } else { [t, x] }; + let across = |t: f64, left: bool| -> SplineResult> { + let [u, v] = at(t); + let (du, dv) = if d == 0 { (1, 0) } else { (0, 1) }; + patch.row_sided(u, v, du, dv, if d == 0 { [left, false] } else { [false, left] }) + }; + let speed = |row: &[(usize, usize, f64)]| row.iter().fold(Vec3::ZERO, |s, (i, j, c)| s + patch.at(*i, *j) * *c); + let ratio = |t: f64| -> SplineResult> { + let (a, b) = (speed(&across(t, true)?), speed(&across(t, false)?)); + let (la, lb) = (a.len(), b.len()); + if !(la > 0.0 && lb > 0.0) { + return Ok(None); + } + Ok((a.dot(b) / (la * lb) >= angle_tol.cos()).then_some(lb / la)) + }; + let ends = [ratio(0.0)?, ratio(1.0)?]; + let (r0, r1) = match ends { + [Some(a), Some(b)] => (a, b), + [Some(a), None] | [None, Some(a)] if patch.pole && d == 1 => (a, a), + _ => continue, + }; + for i in 0..count { + let t = (i as f64 + 0.5) / count as f64; + let r = r0 * (1.0 - t) + r1 * t; + let mut terms = across(t, false)?; + terms.extend(across(t, true)?.into_iter().map(|(i, j, c)| (i, j, -r * c))); + on_each_axis(&mut rows, &[(k, terms)], Vec3::ZERO, 1.0); + } + } + } + } + Ok(rows) +} + +/// A station's rows (module docs), linearised about the patch as it stands: +/// - G1: `n·c′ = 0`, and the weak Hermite rows `w·c′ = s`, `t·c′ = a` in the neighbour's tangent +/// plane only (`t = n × w`), so they never pull against the G1 row; +/// - orders k = 2 … n: `n·c⁽ᵏ⁾ = T_k(x₁ … x_{k−1})` ([`crate::linkage::Jet::linearised`]) by +/// Newton's method: `T_k` is replaced by its tangent at the last solution's `x⁰`, so the row is +/// `n·c⁽ᵏ⁾ − Σ_j ∇_j T_k · x_j = T_k(x⁰) − Σ_j ∇_j T_k · x_j⁰`, with `x_j = (t·c⁽ʲ⁾, w·c⁽ʲ⁾)` +/// and `c⁽ʲ⁾ = signʲ ∂ʲS` across. Each is weighed by `hᵏ⁻¹` against the G1 row (`h` the span), +/// so every order says how far it misses over one span and none swamps the others as the +/// spans shrink. +fn linkage_rows(rows: &mut Vec, patch: &Patch, s: &Station, span: f64) -> SplineResult<()> { + let (uv, (du, dv, sign)) = station_on(s.side, s.t); + let (n, w) = (s.across.normal, s.across.leave); + let t = n.cross(w); + let order = s.order(); + // The coefficients of c′ … c⁽ⁿ⁾ on the control points. + let derivative: Vec> = (1..=order) + .map(|k| { + let sign_k = sign.powi(k as i32); + Ok(patch.row(uv[0], uv[1], k * du, k * dv)?.into_iter().map(|(i, j, c)| (i, j, c * sign_k)).collect()) + }) + .collect::>()?; + let Some(first) = derivative.first() else { return Ok(()) }; + rows.push(Row { terms: along(s.patch, first, n), value: 0.0, weight: 1.0 }); + for (dir, value) in [(w, s.speed), (t, s.slide)] { + rows.push(Row { terms: along(s.patch, first, dir), value, weight: HERMITE_WEIGHT }); + } + let Some(jet) = s.across.jet else { return Ok(()) }; + let c = linkage(patch, s, jet.order)?; + let x0: Vec<[f64; 2]> = c.iter().map(|d| [d.dot(t), d.dot(w)]).collect(); + let Some(targets) = jet.linearised(&x0) else { return Ok(()) }; + for (k, target) in (2..=order).zip(targets) { + let Some(top) = derivative.get(k - 1) else { continue }; + let mut terms = along(s.patch, top, n); + let mut value = target.value; + for (j, (g, x)) in target.gradient.iter().zip(&x0).enumerate().take(k - 1) { + let Some(cj) = derivative.get(j) else { continue }; + terms.extend(along(s.patch, cj, (t * g[0] + w * g[1]) * -1.0)); + value -= g[0] * x[0] + g[1] * x[1]; + } + let fade = if k <= s.full { 1.0 } else { s.fade }; + rows.push(Row { terms, value, weight: fade * span.powi(k as i32 - 1) }); + } + Ok(()) +} + +/// A patch's fairing energy for a fill asked G^n, between its control points (flat indices): the +/// thin plate (order 2) plus, for n ≥ 2, the energy of order `m = n + 1`, each scaled to unit +/// trace ([`energy_of`]). The higher order leaves the change the conditions ask (of curvature, +/// of its rate…) spread over the fill rather than squeezed into the first span along its edges; +/// the thin plate, whose null space (the planes) the loop pins, keeps the system definite where +/// the higher order's (polynomials of degree below m) is not. +fn energy(patch: &Patch, m: usize) -> SplineResult> { + let thin = energy_of(patch, 2)?; + if m <= 2 { + return Ok(thin); + } + let high = energy_of(patch, m)?; + let trace = |e: &[(usize, usize, f64)]| e.iter().filter(|(a, b, _)| a == b).map(|(_, _, x)| *x).sum::(); + let (t2, tm) = (trace(&thin), trace(&high)); + if !(t2 > 0.0 && tm > 0.0) { + return Ok(thin); + } + Ok(thin.into_iter().map(|(a, b, x)| (a, b, x / t2)).chain(high.into_iter().map(|(a, b, x)| (a, b, x / tm))).collect()) +} + +/// A patch's fairing energy of order `m` between its control points (flat indices): +/// `∫∫ Σ_r C(m, r) |∂ᵘʳ ∂ᵥᵐ⁻ʳ S|²`, the terms `G⁽ʳ⁾ ⊗ G⁽ᵐ⁻ʳ⁾` of the spaces' Gram matrices (order 2 +/// is the thin plate `∫∫ |S_uu|² + 2|S_uv|² + |S_vv|²`). +fn energy_of(patch: &Patch, m: usize) -> SplineResult> { + let (gu, gv) = (gram(&patch.spaces[0], m)?, gram(&patch.spaces[1], m)?); + let at = |g: &[Vec>], r: usize, a: usize, b: usize| g.get(r).and_then(|x| x.get(a)).and_then(|x| x.get(b)).copied().unwrap_or(0.0); + let binom = |n: usize, k: usize| (0..k).fold(1.0, |c, i| c * (n - i) as f64 / (i + 1) as f64); + let [cu, cv] = patch.counts(); + let mut out = Vec::new(); + for j in 0..cv { + for l in 0..cv { + for i in 0..cu { + for k in 0..cu { + let e: f64 = (0..=m).map(|r| binom(m, r) * at(&gu, r, i, k) * at(&gv, m - r, j, l)).sum(); + if e != 0.0 { + out.push((i + cu * j, k + cu * l, e)); + } + } + } + } + } + Ok(out) +} + +/// The Gram matrices `∫ N_a⁽ʳ⁾ N_b⁽ʳ⁾` of a space's basis for r = 0 … m (Gauss–Legendre on +/// each span, exact for the degrees used). +fn gram(s: &Space, m: usize) -> SplineResult>>> { + let n = s.count(); + let mut g: Vec>> = vec![vec![vec![0.0; n]; n]; m + 1]; + for w in breaks(s).windows(2) { + let (lo, hi) = (w[0], w[1]); + for (x, wt) in GAUSS6 { + let t = 0.5 * (lo + hi) + 0.5 * (hi - lo) * x; + let weight = 0.5 * (hi - lo) * wt; + for (r, gr) in g.iter_mut().enumerate() { + let (first, vals) = s.basis(t, r)?; + for (a, va) in vals.iter().enumerate() { + for (c, vc) in vals.iter().enumerate() { + if let Some(cell) = gr.get_mut(first + a).and_then(|row| row.get_mut(first + c)) { + *cell += weight * va * vc; + } + } + } + } + } + } + Ok(g) +} + +/// The free points minimising the weighted rows' squares plus a vanishing multiple of the +/// patches' energy, the loop's rows held: the normal equations, solved by Cholesky. +fn least_squares(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)>]) -> SplineResult> { + let dim = 3 * quilt.unknowns; + let slot = |p: usize, flat: usize| quilt.slots.get(p).and_then(|s| s.get(flat)).copied().flatten(); + let mut a = if quilt.spokes.is_empty() { Normal::new(dim, bandwidth(quilt, rows, energy)) } else { Normal::Blocks(BlockNormal::new(quilt)) }; + let mut b = vec![0.0; dim]; + let value = |p: usize, flat: usize| quilt.patches.get(p).and_then(|x| x.net.get(flat)).copied().unwrap_or(Vec3::ZERO); + let mut condition_trace = 0.0; + for r in rows { + let mut unknown: Vec<(usize, f64)> = Vec::new(); + let mut known = 0.0; + for t in &r.terms { + let flat = quilt.patches.get(t.patch).map_or(0, |p| p.flat(t.i, t.j)); + let v = value(t.patch, flat); + for (k, (f, x)) in [t.along.x, t.along.y, t.along.z].into_iter().zip([v.x, v.y, v.z]).enumerate() { + if f == 0.0 { + continue; + } + match slot(t.patch, flat) { + Some(id) => unknown.push((3 * id + k, f)), + None => known += f * x, + } + } + } + let rhs = r.value - known; + let w2 = r.weight * r.weight; + for &(x, cx) in &unknown { + for &(y, cy) in &unknown { + a.add(x, y, w2 * cx * cy); + } + if let Some(cell) = b.get_mut(x) { + *cell += w2 * cx * rhs; + } + condition_trace += w2 * cx * cx; + } + } + // The energy decides what the rows leave free; with no rows it is all there is. + let energy_trace: f64 = + energy.iter().enumerate().flat_map(|(p, e)| e.iter().filter(move |(x, y, _)| x == y && slot(p, *x).is_some())).map(|(_, _, e)| 3.0 * e).sum(); + let lambda = if condition_trace > 0.0 && energy_trace > 0.0 { 1e-7 * condition_trace / energy_trace } else { 1.0 }; + for (p, entries) in energy.iter().enumerate() { + for &(f, g, e) in entries { + let Some(x) = slot(p, f) else { continue }; + match slot(p, g) { + Some(y) => { + for k in 0..3 { + a.add(3 * x + k, 3 * y + k, lambda * e); + } + } + None => { + let fixed = value(p, g); + for (k, v) in [fixed.x, fixed.y, fixed.z].into_iter().enumerate() { + if let Some(cell) = b.get_mut(3 * x + k) { + *cell -= lambda * e * v; + } + } + } + } + } + } + let x = a.solve(b)?; + Ok((0..quilt.unknowns) + .map(|i| Vec3::new(x.get(3 * i).copied().unwrap_or(0.0), x.get(3 * i + 1).copied().unwrap_or(0.0), x.get(3 * i + 2).copied().unwrap_or(0.0))) + .collect()) +} + +/// The widest coupling between two unknowns (coordinates) in any row or energy term: the +/// normal equations' half bandwidth. +fn bandwidth(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)>]) -> usize { + let slot = |p: usize, i: usize, j: usize| quilt.patches.get(p).and_then(|x| quilt.slots.get(p)?.get(x.flat(i, j)).copied().flatten()); + let mut bw = 0usize; + for r in rows { + let ids = r.terms.iter().filter_map(|t| slot(t.patch, t.i, t.j)); + let (lo, hi) = ids.fold((usize::MAX, 0usize), |(lo, hi), x| (lo.min(x), hi.max(x))); + if lo <= hi { + bw = bw.max(3 * (hi - lo) + 2); + } + } + for (p, entries) in energy.iter().enumerate() { + let Some(slots) = quilt.slots.get(p) else { continue }; + for &(f, g, _) in entries { + if let (Some(Some(x)), Some(Some(y))) = (slots.get(f), slots.get(g)) { + bw = bw.max(3 * x.abs_diff(*y) + 2); + } + } + } + bw +} + +/// The normal equations' matrix: banded where the band is narrow against the size, else dense. +enum Normal { + Band(crate::fill::Band), + Dense(Vec, usize), + Blocks(BlockNormal), +} + +impl Normal { + fn new(n: usize, bw: usize) -> Normal { + if 4 * bw < n { Normal::Band(crate::fill::Band::new(n, bw)) } else { Normal::Dense(vec![0.0; n * n], n) } + } + + /// Add `v` at `(r, s)` (callers add both halves of a symmetric matrix). + fn add(&mut self, r: usize, s: usize, v: f64) { + match self { + Normal::Band(b) => b.add(r, s, v), + Normal::Dense(a, n) => { + if let Some(x) = a.get_mut(r * *n + s) { + *x += v; + } + } + Normal::Blocks(m) => m.add(r, s, v), + } + } + + fn solve(self, b: Vec) -> SplineResult> { + match self { + Normal::Band(m) => m.factor_rows()?.substitute(b), + Normal::Dense(a, n) => cholesky(a, b, n), + Normal::Blocks(m) => m.solve(b), + } + } +} + +/// The normal equations of patches about a centre, solved by blocks: each patch's interior +/// unknowns (coordinates of control points only that patch holds, coupled to no other patch's) +/// form a banded block, eliminated exactly onto the shared unknowns (the spokes', the centre's, +/// and any a row couples across patches) by their Schur complement, which is solved dense; the +/// interiors then follow by back substitution. Entries are kept sparse until the blocks are +/// known (callers add both halves of the symmetric matrix), in ordered maps: the eliminations +/// sum them in their order, so a hashed map's order (another each run) would make the fill +/// differ in its last bits from one run to the next, and a design read back another surface. +struct BlockNormal { + /// Each coordinate's patch when only one patch holds its point, else `None`. + owner: Vec>, + entries: std::collections::BTreeMap<(usize, usize), f64>, +} + +impl BlockNormal { + fn new(quilt: &Quilt) -> BlockNormal { + let mut holders: Vec> = vec![Vec::new(); quilt.unknowns]; + for (p, slots) in quilt.slots.iter().enumerate() { + for id in slots.iter().flatten() { + if let Some(h) = holders.get_mut(*id) + && !h.contains(&p) + { + h.push(p); + } + } + } + let owner = holders.iter().flat_map(|h| { + let o = if let [p] = h.as_slice() { Some(*p) } else { None }; + [o; 3] + }); + BlockNormal { owner: owner.collect(), entries: std::collections::BTreeMap::new() } + } + + fn add(&mut self, r: usize, s: usize, v: f64) { + if v != 0.0 { + *self.entries.entry((r, s)).or_insert(0.0) += v; + } + } + + fn solve(mut self, b: Vec) -> SplineResult> { + let n = b.len(); + // A coordinate coupled to another patch's interior is shared too. + let coupled: Vec = self + .entries + .keys() + .filter(|(r, c)| matches!((self.owner.get(*r).copied().flatten(), self.owner.get(*c).copied().flatten()), (Some(a), Some(b)) if a != b)) + .flat_map(|(r, c)| [*r, *c]) + .collect(); + for x in coupled { + if let Some(o) = self.owner.get_mut(x) { + *o = None; + } + } + let shared: Vec = (0..n).filter(|x| self.owner.get(*x).copied().flatten().is_none()).collect(); + if shared.len() > MAX_SHARED_UNKNOWNS { + return Err(SplineError::TooLarge(format!( + "{} unknowns shared by the patches about the centre (at most {MAX_SHARED_UNKNOWNS})", + shared.len() + ))); + } + let mut place = vec![usize::MAX; n]; + for (i, x) in shared.iter().enumerate() { + if let Some(slot) = place.get_mut(*x) { + *slot = i; + } + } + let patches = self.owner.iter().flatten().copied().max().map_or(0, |m| m + 1); + let mut interior: Vec> = vec![Vec::new(); patches]; + for (x, o) in self.owner.iter().enumerate() { + if let Some(p) = o + && let Some(list) = interior.get_mut(*p) + { + if let Some(slot) = place.get_mut(x) { + *slot = list.len(); + } + list.push(x); + } + } + let m = shared.len(); + // The shared block, and per patch its block, its coupling to the shared unknowns. + let mut s_mat = vec![0.0; m * m]; + let mut blocks: Vec> = vec![std::collections::BTreeMap::new(); patches]; + let mut couple: Vec> = vec![std::collections::BTreeMap::new(); patches]; + for ((r, c), v) in std::mem::take(&mut self.entries) { + let (or, oc) = (self.owner.get(r).copied().flatten(), self.owner.get(c).copied().flatten()); + let (pr, pc) = (place.get(r).copied().unwrap_or(0), place.get(c).copied().unwrap_or(0)); + match (or, oc) { + (None, None) => { + if let Some(x) = s_mat.get_mut(pr * m + pc) { + *x += v; + } + } + (Some(p), Some(_)) => { + if let Some(blk) = blocks.get_mut(p) { + *blk.entry((pr, pc)).or_insert(0.0) += v; + } + } + // Interior row, shared column (the transposed entry is its mirror). + (Some(p), None) => { + if let Some(cp) = couple.get_mut(p) { + *cp.entry((pr, pc)).or_insert(0.0) += v; + } + } + (None, Some(_)) => {} + } + } + let mut rhs: Vec = shared.iter().map(|x| b.get(*x).copied().unwrap_or(0.0)).collect(); + let mut solved_parts: Vec<(crate::fill::Band, Vec, Vec<(usize, Vec)>)> = Vec::with_capacity(patches); + for p in 0..patches { + let ids = interior.get(p).map(Vec::as_slice).unwrap_or(&[]); + let k = ids.len(); + let blk = blocks.get(p).cloned().unwrap_or_default(); + let bw = blk.keys().map(|(r, c)| r.abs_diff(*c)).max().unwrap_or(0); + let mut band = crate::fill::Band::new(k.max(1), bw); + for (&(r, c), &v) in &blk { + band.add(r, c, v); + } + if k == 0 { + solved_parts.push((band, Vec::new(), Vec::new())); + continue; + } + let band = band.factor_rows()?; + // g = A_kk⁻¹ b_k; per shared column j coupled to this patch, z_j = A_kk⁻¹ A_k,j. + let bk: Vec = ids.iter().map(|x| b.get(*x).copied().unwrap_or(0.0)).collect(); + let g = band.substitute(bk)?; + let mut columns: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (&(r, j), &v) in couple.get(p).into_iter().flatten() { + if let Some(cell) = columns.entry(j).or_insert_with(|| vec![0.0; k]).get_mut(r) { + *cell += v; + } + } + let mut z: Vec<(usize, Vec)> = Vec::with_capacity(columns.len()); + for (j, col) in columns { + z.push((j, band.substitute(col)?)); + } + // S −= A_Bk·Z, rhs −= A_Bk·g, A_Bk the transpose of the coupling. + let coupling = couple.get(p).cloned().unwrap_or_default(); + let mut by_column: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (&(r, j), &v) in &coupling { + by_column.entry(j).or_default().push((r, v)); + } + for (i, entries) in &by_column { + let dot = |w: &[f64]| entries.iter().map(|(r, v)| v * w.get(*r).copied().unwrap_or(0.0)).sum::(); + if let Some(x) = rhs.get_mut(*i) { + *x -= dot(&g); + } + for (j, zj) in &z { + if let Some(x) = s_mat.get_mut(i * m + j) { + *x -= dot(zj); + } + } + } + solved_parts.push((band, g, z)); + } + let xs = if m > 0 { cholesky(s_mat, rhs, m)? } else { Vec::new() }; + let mut x = vec![0.0; n]; + for (i, id) in shared.iter().enumerate() { + if let Some(slot) = x.get_mut(*id) { + *slot = xs.get(i).copied().unwrap_or(0.0); + } + } + for (p, (_, g, z)) in solved_parts.iter().enumerate() { + let ids = interior.get(p).map(Vec::as_slice).unwrap_or(&[]); + for (r, id) in ids.iter().enumerate() { + let mut v = g.get(r).copied().unwrap_or(0.0); + for (j, zj) in z { + v -= zj.get(r).copied().unwrap_or(0.0) * xs.get(*j).copied().unwrap_or(0.0); + } + if let Some(slot) = x.get_mut(*id) { + *slot = v; + } + } + } + if x.iter().any(|v| !v.is_finite()) { + return invalid("the patches' equations have no finite solution"); + } + Ok(x) + } +} + +/// Solve the symmetric positive definite `a·x = b` (dense, `n × n`). +fn cholesky(mut a: Vec, mut b: Vec, n: usize) -> SplineResult> { + let at = |a: &[f64], r: usize, c: usize| a.get(r * n + c).copied().unwrap_or(0.0); + for c in 0..n { + let mut d = at(&a, c, c); + for k in 0..c { + d -= at(&a, c, k).powi(2); + } + if !(d > 0.0) || !d.is_finite() { + return invalid("the patch's equations are singular"); + } + let d = d.sqrt(); + if let Some(x) = a.get_mut(c * n + c) { + *x = d; + } + for r in c + 1..n { + let mut v = at(&a, r, c); + for k in 0..c { + v -= at(&a, r, k) * at(&a, c, k); + } + if let Some(x) = a.get_mut(r * n + c) { + *x = v / d; + } + } + } + for r in 0..n { + let mut v = b.get(r).copied().unwrap_or(0.0); + for k in 0..r { + v -= at(&a, r, k) * b.get(k).copied().unwrap_or(0.0); + } + if let Some(x) = b.get_mut(r) { + *x = v / at(&a, r, r); + } + } + for r in (0..n).rev() { + let mut v = b.get(r).copied().unwrap_or(0.0); + for k in r + 1..n { + v -= at(&a, k, r) * b.get(k).copied().unwrap_or(0.0); + } + if let Some(x) = b.get_mut(r) { + *x = v / at(&a, r, r); + } + } + if b.iter().any(|x| !x.is_finite()) { + return invalid("the patch's equations have no finite solution"); + } + Ok(b) +} + +/// What the fill achieves at the stations, across the spokes and at the points. +fn measure( + quilt: &Quilt, + stations: &[Station], + points: &[Vec3], + located: &[(usize, [f64; 2])], + spoke_count: usize, +) -> SplineResult<(Achieved, Along)> { + let mut r = Achieved::default(); + let mut along = Along::default(); + let mut jumps = [0.0f64; MAX_CONTINUITY + 1]; + for s in stations { + let Some(patch) = quilt.patches.get(s.patch) else { continue }; + let (uv, _) = station_on(s.side, s.t); + let Some(normal) = patch.normal(uv[0], uv[1]) else { continue }; + let a = normal.dot(s.across.normal).abs().clamp(0.0, 1.0).acos(); + r.normal_deviation_all = r.normal_deviation_all.max(a); + let d = s.side % 2; + if s.held { + r.normal_deviation = r.normal_deviation.max(a); + r.normal_excess = r.normal_excess.max(a - s.tilt); + if let Some(x) = along.angle.get_mut(d) { + *x = x.max(a - s.tilt); + } + } + if s.order() < 2 || !s.clear { + continue; + } + // The linkage curve's height above the neighbour, per unit length along its foot. + let c = linkage(patch, s, s.across.jet.map_or(1, |j| j.order))?; + let n = s.across.normal; + let Some(first) = c.first() else { continue }; + let foot = (*first - n * first.dot(n)).len().max(1e-300); + for (k, want) in (2..).zip(targets(s, &c)) { + let (Some(ck), Some(jump)) = (c.get(k - 1), jumps.get_mut(k)) else { continue }; + let here = ((n.dot(*ck) - want) / foot.powi(k as i32)).abs(); + *jump = jump.max(here); + if let Some(x) = along.jumps.get_mut(d).and_then(|j| j.get_mut(k)) { + *x = x.max(here); + } + } + } + // Across the spokes, clear of the vertices inside the loop. + for seam in &quilt.spokes { + let (Some(a), Some(b)) = (quilt.patches.get(seam.a.0), quilt.patches.get(seam.b.0)) else { continue }; + for i in 0..spoke_count { + let t = (i as f64 + 0.5) / spoke_count as f64; + let (ua, ub) = seam.at(t); + if let (Some(na), Some(nb)) = (a.normal(ua[0], ua[1]), b.normal(ub[0], ub[1])) { + let a = na.dot(nb).clamp(-1.0, 1.0).acos(); + r.normal_deviation_all = r.normal_deviation_all.max(a); + if !seam.near_inner(t, CLASH_SHARE) { + r.normal_deviation = r.normal_deviation.max(a); + r.normal_excess = r.normal_excess.max(a); + along.angle = along.angle.map(|x| x.max(a)); + } + } + } + } + r.jumps = jumps; + for (p, (patch, uv)) in points.iter().zip(located) { + if let Some(on) = quilt.patches.get(*patch) { + r.point_deviation = r.point_deviation.max(on.eval(uv[0], uv[1], 0, 0)?.dist(*p)); + } + } + Ok((r, along)) +} + +/// What a fit achieves at the stations of the sides running along u (`[0]`) and along v (`[1]`): +/// where it falls short, the spans that way are halved. +#[derive(Clone, Copy, Debug, Default)] +struct Along { + angle: [f64; 2], + jumps: [[f64; MAX_CONTINUITY + 1]; 2], +} + +impl Along { + /// The directions whose sides miss the angle tolerance, or an order's ([`within_order`]). + fn missing(&self, order: usize, size: f64, angle_tol: f64) -> [bool; 2] { + [0, 1] + .map(|d| self.angle.get(d).is_some_and(|a| *a > angle_tol) || self.jumps.get(d).is_some_and(|j| !within_order(j, order, size, angle_tol))) + } +} + +/// The patch and parameters of the fill's point nearest `p`: the nearest of a grid of samples +/// on every patch, then Gauss–Newton inside that patch's square. +fn nearest(quilt: &Quilt, p: Vec3) -> (usize, [f64; 2]) { + const GRID: usize = 24; + let mut best = (f64::INFINITY, 0usize, [0.5, 0.5]); + for (k, patch) in quilt.patches.iter().enumerate() { + for i in 0..=GRID { + for j in 0..=GRID { + let uv = [i as f64 / GRID as f64, j as f64 / GRID as f64]; + if let Ok(q) = patch.eval(uv[0], uv[1], 0, 0) { + let d = q.dist(p); + if d < best.0 { + best = (d, k, uv); + } + } + } + } + } + let (_, k, [mut u, mut v]) = best; + let Some(patch) = quilt.patches.get(k) else { return (k, [u, v]) }; + for _ in 0..30 { + let (Ok(q), Ok(a), Ok(b)) = (patch.eval(u, v, 0, 0), patch.eval(u, v, 1, 0), patch.eval(u, v, 0, 1)) else { break }; + let r = q - p; + let (aa, ab, bb) = (a.dot(a), a.dot(b), b.dot(b)); + let det = aa * bb - ab * ab; + if !(det.abs() > 1e-300) { + break; + } + let (ga, gb) = (a.dot(r), b.dot(r)); + u = (u - (bb * ga - ab * gb) / det).clamp(0.0, 1.0); + v = (v - (aa * gb - ab * ga) / det).clamp(0.0, 1.0); + } + (k, [u, v]) +} + +/// Whether a patch folds back on itself: on a grid of its parameters, its normal reverses between +/// neighbouring points (the surface turns back over itself), or vanishes inside it. A patch may +/// turn its normal through more than a right angle overall (a dome meeting a tube's wall, a +/// window round more than half a cylinder): only a reversal between neighbours is a fold. The +/// normal may vanish at a corner (where two sides run on straight, as on a closed loop's pieces) +/// and on a three-sided patch's pole at u = 0. +fn folds(patch: &Patch) -> bool { + let n = FOLD_SAMPLES; + if patch.normal(0.5, 0.5).is_none() { + return true; + } + let at = |i: usize, j: usize| patch.normal(i as f64 / n as f64, j as f64 / n as f64); + let mut grid: Vec> = Vec::with_capacity((n + 1) * (n + 1)); + for i in 0..=n { + for j in 0..=n { + let normal = at(i, j); + let excused = (patch.pole && i == 0) || ((i == 0 || i == n) && (j == 0 || j == n)); + if normal.is_none() && !excused { + return true; + } + grid.push(normal); + } + } + let get = |i: usize, j: usize| grid.get(i * (n + 1) + j).copied().flatten(); + for i in 0..=n { + for j in 0..=n { + let Some(a) = get(i, j) else { continue }; + for (k, l) in [(i + 1, j), (i, j + 1)] { + if k <= n && l <= n && get(k, l).is_some_and(|b| a.dot(b) <= 0.0) { + return true; + } + } + } + } + false +} + +/// The fill with its middle filled out by `crown` times the loop's `size` along the normals (to +/// the side the neighbours' normals face), on +/// control points clear of the rows the conditions hold (n + 1 rows from a G^n edge), so the loop and the conditions across it do not move. One patch +/// rises by `16·u(1−u)·v(1−v)`; patches about a centre by `u(2−u)·v(2−v)`, nought on the loop and +/// one at the centre, the same on a spoke from either side. +fn crowned(mut quilt: Quilt, stations: &[Station], crown: f64, size: f64) -> SplineResult { + if crown == 0.0 { + return Ok(quilt); + } + let held = 1 + stations.iter().map(Station::order).max().unwrap_or(0); + // Out to the side the neighbours' normals face (the patches all turn one way). + let mut facing = 0.0; + for s in stations { + let (uv, _) = station_on(s.side, s.t); + if let Some(n) = quilt.patches.get(s.patch).and_then(|p| p.normal(uv[0], uv[1])) { + facing += n.dot(s.across.normal); + } + } + let out = if facing < 0.0 { -1.0 } else { 1.0 }; + let layout = quilt.layout; + let about_centre = layout != Layout::One; + let bump = |k: usize, x: f64, y: f64| match layout { + Layout::One => 16.0 * x * (1.0 - x) * y * (1.0 - y), + Layout::Centre => x * (2.0 - x) * y * (2.0 - y), + // The ring's patches rise from the loop (v = 0) to one at the inner patch, which is one. + Layout::Ring if k < 4 => y * (2.0 - y), + Layout::Ring => 1.0, + }; + let mut moved = std::collections::HashMap::new(); + for (k, patch) in quilt.patches.iter().enumerate() { + let [cu, cv] = patch.counts(); + let (gu, gv) = (greville(&patch.spaces[0]), greville(&patch.spaces[1])); + // The rows clear of those the conditions hold: from the loop's sides of each patch (a + // ring patch's sides across the loop are spokes, the inner patch has none). + let (ring, inside) = (layout == Layout::Ring && k < 4, layout == Layout::Ring && k >= 4); + let first = |across_loop: bool| if inside || (ring && across_loop) { 0 } else { held }; + let far = |c: usize| if about_centre { c } else { c.saturating_sub(held) }; + for j in first(false)..far(cv) { + for i in first(true)..far(cu) { + let Some(Some(id)) = quilt.slots.get(k).and_then(|s| s.get(patch.flat(i, j))) else { continue }; + let (x, y) = (gu.get(i).copied().unwrap_or(0.5), gv.get(j).copied().unwrap_or(0.5)); + let Some(n) = patch.normal(x, y) else { continue }; + moved.entry(*id).or_insert_with(|| patch.at(i, j) + n * (out * crown * size * bump(k, x, y))); + } + } + } + if moved.is_empty() { + return Err(SplineError::Unsupported("a crown on a fill with no room inside its held rows".into())); + } + for (patch, slots) in quilt.patches.iter_mut().zip(&quilt.slots) { + for (p, s) in patch.net.iter_mut().zip(slots) { + if let Some(v) = s.and_then(|s| moved.get(&s)) { + *p = *v; + } + } + } + Ok(quilt) +} + +#[cfg(test)] +#[path = "fill_iso_tests.rs"] +mod tests; diff --git a/crates/geom/src/fill_iso_tests.rs b/crates/geom/src/fill_iso_tests.rs new file mode 100644 index 000000000..6770ed0d3 --- /dev/null +++ b/crates/geom/src/fill_iso_tests.rs @@ -0,0 +1,430 @@ +use super::*; +use crate::brep::eval::SurfaceEval; +use crate::linkage::surface_jet; +use solidcore_record::brep::{Curve, Frame, Surface}; + +/// A homogeneous point of an edge. +fn eval_edge_h(e: &IsoEdge, t: f64) -> SplineResult { + Space::new(e.degree, e.knots.clone())?.eval(&e.homogeneous(), t, 0) +} + +const R: f64 = 10.0; +/// The window's half-widths in longitude and latitude. +const ALPHA: f64 = 0.5; +const BETA: f64 = 0.35; + +fn spec() -> IsoSpec<'static> { + IsoSpec { tol: 1e-6, angle_tol: 0.05f64.to_radians(), crown: 0.0, corner_turn: 1f64.to_radians(), points: &[] } +} + +/// The arc of the circle about `frame`'s z of radius `r` from angle `a0` to `a1`, on its NURBS +/// form (rational quadratic quarter arcs, as SMLib holds circles); run backwards when `reverse`. +fn arc(frame: Frame, r: f64, [a0, a1]: [f64; 2], reverse: bool) -> IsoEdge { + let (form, [t0, t1]) = crate::brep::form::curve(&Curve::Circle { frame, radius: r }, [a0, a1]).unwrap(); + let Curve::RationalSpline { knots, homogeneous } = form else { panic!("a circle's form is rational") }; + let h: Vec = homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(); + let p = knots.len() - h.len() - 1; + let (mut knots, mut h) = segment(p, &knots, &h, t0, t1).unwrap(); + if reverse { + knots = knots.iter().rev().map(|k| t0 + t1 - k).collect(); + h.reverse(); + } + IsoEdge { degree: p, knots, points: h.iter().map(|q| q.project().unwrap()).collect(), weights: Some(h.iter().map(|q| q.w).collect()) } +} + +fn frame(origin: Vec3, x: Vec3, y: Vec3) -> Frame { + Frame { origin: [origin.x, origin.y, origin.z], x_axis: [x.x, x.y, x.z], y_axis: [y.x, y.y, y.z] } +} + +/// A window in a sphere of radius `R` about the origin: longitudes `±ALPHA`, latitudes `±BETA`; +/// the bottom latitude east, the east meridian up, the top latitude west, the west meridian down. +fn window() -> Vec { + let radial = |u: f64| Vec3::new(u.cos(), u.sin(), 0.0); + let latitude = |v: f64| frame(Vec3::Z * (R * v.sin()), Vec3::X, Vec3::Y); + let meridian = |u: f64| frame(Vec3::ZERO, radial(u), Vec3::Z); + vec![ + arc(latitude(-BETA), R * BETA.cos(), [-ALPHA, ALPHA], false), + arc(meridian(ALPHA), R, [-BETA, BETA], false), + arc(latitude(BETA), R * BETA.cos(), [-ALPHA, ALPHA], true), + arc(meridian(-ALPHA), R, [-BETA, BETA], true), + ] +} + +/// The sphere round the window, met with continuity `order` (1 … 4): its outward normal, the way +/// it leaves into the window, and its jet. +fn sphere_beside(edges: &[IsoEdge], order: usize) -> impl FnMut(usize, &[f64]) -> Result>, String> + '_ { + let sphere = SurfaceEval::new(&Surface::Sphere { frame: frame(Vec3::ZERO, Vec3::X, Vec3::Y), radius: R }).unwrap(); + move |k, ts| { + let e = &edges[k]; + ts.iter() + .map(|t| { + let p = eval_edge_h(e, *t).unwrap().project().unwrap(); + let uv = [p.y.atan2(p.x), (p.z / R).clamp(-1.0, 1.0).asin()]; + let (_, su, sv) = sphere.derivs(uv[0], uv[1]).unwrap(); + let normal = su.cross(sv).normalized().unwrap(); + let leave = match k { + 0 => sv.normalized().unwrap(), + 1 => su.normalized().unwrap() * -1.0, + 2 => sv.normalized().unwrap() * -1.0, + _ => su.normalized().unwrap(), + }; + let jet = (order >= 2).then(|| surface_jet(&sphere, uv, normal, leave, order).unwrap()); + Ok(Some(Across { leave, normal, bend: None, jet })) + }) + .collect() + } +} + +/// How far the fill strays from the sphere, over a grid of each patch. +fn off_sphere(fill: &IsoFill) -> f64 { + let mut worst = 0.0f64; + for p in &fill.patches { + for i in 0..=16 { + for j in 0..=16 { + let q = p.surface.eval(i as f64 / 16.0, j as f64 / 16.0).unwrap(); + worst = worst.max((q.len() - R).abs()); + } + } + } + worst +} + +/// The fill's one patch as a surface record, to be evaluated independently of the fill. +fn record(fill: &IsoFill) -> SurfaceEval { + let s = &fill.patches[0].surface; + let [nu, nv] = s.count(); + let homogeneous = (0..nu).map(|i| (0..nv).map(|j| s.point(i, j)).map(|h| [h.x, h.y, h.z, h.w]).collect()).collect(); + let [u_knots, v_knots] = s.knots().clone(); + SurfaceEval::new(&Surface::RationalSpline { u_knots, v_knots, homogeneous }).unwrap() +} + +/// The largest jump of order `k` (2 … 4) across the window's edges, clear of the corners: the +/// fill's linkage curves (its exact partials across each edge) against the sphere's jet of order +/// `k`, per unit length of their foot, as `crate::linkage` defines it. +fn jump(fill: &IsoFill, edges: &[IsoEdge], k: usize) -> f64 { + let surface = record(fill); + let mut beside = sphere_beside(edges, k); + let mut worst = 0.0f64; + for (side, edge) in edges.iter().enumerate() { + let [a, b] = edge.domain(); + for i in 1..40 { + let f = i as f64 / 40.0; + if !(CORNER_SHARE..=1.0 - CORNER_SHARE).contains(&f) { + continue; + } + let across = beside(side, &[a + (b - a) * f]).unwrap()[0].unwrap(); + let (uv, (du, dv, sign)) = station_on(side, f); + let d = surface.partials(uv[0], uv[1]).unwrap(); + let c: Vec = (1..=k).map(|m| d[m * du][m * dv] * sign.powi(m as i32)).collect(); + let (n, t, w) = (across.normal, across.normal.cross(across.leave), across.leave); + let x: Vec<[f64; 2]> = c.iter().map(|d| [d.dot(t), d.dot(w)]).collect(); + let want = across.jet.unwrap().targets(&x).unwrap()[k - 2]; + let foot = (c[0] - n * c[0].dot(n)).len(); + worst = worst.max(((n.dot(c[k - 1]) - want) / foot.powi(k as i32)).abs()); + } + } + worst +} + +/// A window in a sphere, bounded by four circular arcs (rational edges), filled G1 … G4. Each +/// fill of order n holds its jumps of orders 2 … n, by its own report and by an independent +/// reading of its record; the jump of order n + 1 it leaves to its energy is many times larger. +/// (The sphere itself is not in the fill's space, whose weights are a Coons blend and the +/// sphere's a product, so the orders a fill is not asked for do leave jumps.) +#[test] +fn a_sphere_window_on_rational_arcs_holds_each_order_asked_and_not_the_next() { + let edges = window(); + for order in 1..=4 { + let fill = iso_fill(&edges, &mut sphere_beside(&edges, order), &spec()).unwrap(); + let a = fill.achieved; + let measured: Vec = (2..=4).map(|k| jump(&fill, &edges, k)).collect(); + eprintln!( + "G{order}: degree {}, {} control points a side, normals within {:.2e}°, reported jumps {:?}, read off the record (G2, G3, G4) {measured:?}, off the sphere {:.2e}", + fill.patches[0].surface.degree()[0], + fill.patches[0].surface.count()[0], + a.normal_deviation.to_degrees(), + a.jumps, + off_sphere(&fill) + ); + assert!(a.normal_deviation <= spec().angle_tol); + // Each order held within the angle tolerance over the window's size, by the fill's own + // report and by the independent reading of its record (at other stations, so within + // twice that). + let size = { + let mut all = edges.iter().flat_map(|e| e.points.iter().copied()); + let first = all.next().unwrap(); + let (lo, hi) = all.fold((first, first), |(lo, hi), p| (lo.min(p), hi.max(p))); + lo.dist(hi) + }; + for k in 2..=order { + let (reported, read) = (turn(a.jumps[k], k, size), turn(measured[k - 2], k, size)); + assert!(reported <= spec().angle_tol, "G{order}: order {k} reported {reported:e}"); + assert!(read <= 2.0 * spec().angle_tol, "G{order}: order {k} read {read:e}"); + } + if (2..4).contains(&order) { + let (held, next) = (measured[order - 2], measured[order - 1]); + assert!(next > 10.0 * held.max(1e-12), "G{order} leaves order {} to the energy: {next:e} vs {held:e}", order + 1); + } + // Not the sphere (nothing asks for it), but a cap over the window, not a dent. + assert!(off_sphere(&fill) < 0.05 * R, "G{order} near the sphere: {}", off_sphere(&fill)); + } +} + +#[test] +fn hostile_edges_are_refused() { + let edges = window(); + let ok = |e: &[IsoEdge]| iso_fill(e, &mut sphere_beside(e, 2), &spec()); + let mut bad = edges.clone(); + bad[1].weights = Some(vec![-1.0; bad[1].points.len()]); + assert!(ok(&bad).is_err(), "a negative weight"); + let mut bad = edges.clone(); + bad[1].weights = Some(vec![1.0]); + assert!(ok(&bad).is_err(), "a weight count that does not match"); + let mut bad = edges.clone(); + if let Some(w) = bad[0].weights.as_mut() { + w[0] = f64::NAN; + } + assert!(ok(&bad).is_err(), "a weight that is not a number"); + // One edge's start weight doubled alone (its curve changes, and its corner disagrees). + let mut bad = edges.clone(); + if let Some(w) = bad[0].weights.as_mut() { + w[0] *= 2.0; + } + assert!(matches!(ok(&bad), Err(SplineError::Unsupported(_))), "corner weights that cannot agree"); + // A jet above G4. + let mut beside = sphere_beside(&edges, 4); + let mut too_high = |k: usize, ts: &[f64]| -> Result>, String> { + let mut got = beside(k, ts)?; + for a in got.iter_mut().flatten() { + if let Some(j) = a.jet.as_mut() { + j.order = 5; + } + } + Ok(got) + }; + assert!(iso_fill(&edges, &mut too_high, &spec()).is_err()); +} + +/// The rational basis's derivatives (the Leibniz rule on `w N N = R W`) against central +/// differences of the derivative one order lower, on the sphere window's patch. +#[test] +fn a_rational_patch_s_derivatives_are_its_differences() { + let edges = window(); + let q = Quilt::new(&edges, &loop_sides(&edges, spec().corner_turn).0, false, &[Vec::new(), Vec::new()], 3).unwrap(); + let p = &q.patches[0]; + assert!(p.rational); + let (u, v, h) = (0.3, 0.6, 1e-5); + for (du, dv) in [(1, 0), (0, 1), (2, 0), (0, 2), (1, 1), (3, 0), (0, 3)] { + let exact = p.eval(u, v, du, dv).unwrap(); + let (lu, lv) = if du > 0 { (du - 1, dv) } else { (du, dv - 1) }; + let (a, b) = if du > 0 { ((u + h, v), (u - h, v)) } else { ((u, v + h), (u, v - h)) }; + let differences = (p.eval(a.0, a.1, lu, lv).unwrap() - p.eval(b.0, b.1, lu, lv).unwrap()) * (0.5 / h); + assert!(exact.dist(differences) < 1e-5 * exact.len().max(1.0), "∂({du}, {dv}): {exact:?} vs {differences:?}"); + } +} + +/// The four quarter arcs of the circle of radius `r` about z at height `z`, on their NURBS form. +fn circle_quarters(z: f64, r: f64) -> Vec { + let f = frame(Vec3::Z * z, Vec3::X, Vec3::Y); + let q = std::f64::consts::FRAC_PI_2; + (0..4).map(|k| arc(f.clone(), r, [k as f64 * q, (k + 1) as f64 * q], false)).collect() +} + +/// Neighbours given by a normal and a leave direction at each point of the loop. +fn beside_by<'a>( + edges: &'a [IsoEdge], + frame_at: impl Fn(Vec3) -> (Vec3, Vec3) + 'a, +) -> impl FnMut(usize, &[f64]) -> Result>, String> + 'a { + move |k, ts| { + ts.iter() + .map(|t| { + let p = eval_edge_h(&edges[k], *t).map_err(|e| e.to_string())?.project().ok_or("a point at infinity")?; + let (normal, leave) = frame_at(p); + Ok(Some(Across { leave, normal, bend: None, jet: None })) + }) + .collect() + } +} + +/// Whether any patch of the fill folds (its normal reverses between neighbouring samples). +fn any_fold(fill: &IsoFill) -> bool { + fill.patches.iter().any(|p| { + let s = SurfaceEval::new(&Surface::RationalSpline { + u_knots: p.surface.knots()[0].clone(), + v_knots: p.surface.knots()[1].clone(), + homogeneous: (0..p.surface.count()[0]) + .map(|i| (0..p.surface.count()[1]).map(|j| p.surface.point(i, j)).map(|h| [h.x, h.y, h.z, h.w]).collect()) + .collect(), + }) + .unwrap(); + let n = 48; + let normal = |i: usize, j: usize| { + let (_, su, sv) = s.derivs(i as f64 / n as f64, j as f64 / n as f64).unwrap(); + su.cross(sv).normalized() + }; + (0..=n).any(|i| { + (0..=n).any(|j| { + let Some(a) = normal(i, j) else { return false }; + [(i + 1, j), (i, j + 1)].iter().any(|&(k, l)| k <= n && l <= n && normal(k, l).is_some_and(|b| a.dot(b) <= 0.0)) + }) + }) + }) +} + +/// A tube's end: the circle in four quarter arcs, G1 to the tube's wall (its normal radial, the +/// wall going on upwards). Every vertex of the loop is smooth: the cross derivative of a side +/// there is the next side's tangent, along the edge itself. +#[test] +fn a_tube_end_capped_g1_holds_the_wall_and_does_not_fold() { + let edges = circle_quarters(30.0, 10.0); + let radial = |p: Vec3| (Vec3::new(p.x, p.y, 0.0).normalized().unwrap(), Vec3::Z); + let s = IsoSpec { tol: 2e-5, ..spec() }; + let fill = iso_fill(&edges, &mut beside_by(&edges, radial), &s).unwrap(); + eprintln!("tube end g1: {} patches, {:?}", fill.patches.len(), fill.achieved); + assert!(fill.achieved.normal_excess <= s.angle_tol); + assert!(!any_fold(&fill), "the cap folds"); + // No corner of the loop: four patches round it and one inside, none with a flat corner + // (two derivatives parallel), which a patch on the circle's own quarters would have. + assert_eq!(fill.patches.len(), 5, "the ring and the inner patch"); + for (k, p) in fill.patches.iter().enumerate() { + for c in [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]] { + let (angle, ..) = corner_angle(p, c); + assert!(angle > 0.5 && angle < 179.5, "patch {k}: a flat corner at {c:?}: {angle}°"); + } + } + // A crown fills the middle out of the tube, the inner patch whole. + let crowned = iso_fill(&edges, &mut beside_by(&edges, radial), &IsoSpec { crown: 0.1, ..s }).unwrap(); + let top = |f: &IsoFill| f.patches[4].surface.eval(0.5, 0.5).unwrap().z; + assert!(top(&crowned) > top(&fill) + 0.5, "{} {}", top(&crowned), top(&fill)); +} + +/// The angle (degrees) between a patch's two derivatives at a corner of its square, and their +/// lengths. +fn corner_angle(p: &IsoPatch, uv: [f64; 2]) -> (f64, f64, f64) { + let s = SurfaceEval::new(&Surface::RationalSpline { + u_knots: p.surface.knots()[0].clone(), + v_knots: p.surface.knots()[1].clone(), + homogeneous: (0..p.surface.count()[0]) + .map(|i| (0..p.surface.count()[1]).map(|j| p.surface.point(i, j)).map(|h| [h.x, h.y, h.z, h.w]).collect()) + .collect(), + }) + .unwrap(); + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + let cos = su.dot(sv) / (su.len() * sv.len()); + (cos.clamp(-1.0, 1.0).acos().to_degrees(), su.len(), sv.len()) +} + +/// Loops of five to eight sides about a centre on a wavy rim: at the centre every +/// patch has a proper corner (its two derivatives neither vanishing nor parallel). Parametric C1 +/// across the spokes cannot give that for N other than a multiple of four: it asks the spokes' +/// tangents at the centre `d_{k−1} + d_{k+1} = 0`, which only `d = 0` meets. +#[test] +fn patches_about_a_centre_have_proper_corners_there() { + for n in 5..=8usize { + let corners: Vec = (0..n) + .map(|k| { + let a = 0.3 + k as f64 * std::f64::consts::TAU / n as f64; + Vec3::new(20.0 * a.cos(), 20.0 * a.sin(), 3.0 * (2.0 * a).sin()) + }) + .collect(); + // Quadratic edges bowed up out of the rim's surface. + let edges: Vec = (0..n) + .map(|k| { + let (a, b) = (corners[k], corners[(k + 1) % n]); + IsoEdge { degree: 2, knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points: vec![a, (a + b) * 0.5 + Vec3::Z * 2.0, b], weights: None } + }) + .collect(); + let mut g0 = |_k: usize, ts: &[f64]| -> Result>, String> { Ok(vec![None; ts.len()]) }; + let fill = iso_fill(&edges, &mut g0, &IsoSpec { tol: 2e-5, ..spec() }).unwrap(); + let worst = fill + .patches + .iter() + .map(|p| corner_angle(p, [1.0, 1.0])) + .fold((180.0f64, f64::MAX), |(a, l), (b, x, y)| (a.min(b).min(180.0 - b), l.min(x).min(y))); + eprintln!("{n} sides: at the centre the patches' corners are at least {:.2}° from flat, derivatives at least {:.3e} long", worst.0, worst.1); + assert!(worst.0 > 0.5 && worst.1 > 1e-3, "{n} sides: a flat corner at the centre {worst:?}"); + } +} + +/// Half a round post's side, as SMLib holds it: its half circles are each two arcs, split at the +/// cylinder's seam (35.12° round), so the loop has six edges but four corners. The seam vertices, +/// where the loop runs straight on, are not corners of the region: one patch on four sides, each +/// edge a straight line on its stretch of a side, and no flat corner. +#[test] +fn a_loop_whose_edges_run_straight_on_at_seams_is_one_patch_on_its_corners() { + let seam = 35.12f64.to_radians(); + let h = std::f64::consts::FRAC_PI_2; + let (bottom, top) = (frame(Vec3::ZERO, Vec3::X, Vec3::Y), frame(Vec3::Z * 20.0, Vec3::X, Vec3::Y)); + let line = |a: Vec3, b: Vec3| IsoEdge { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![a, b], weights: None }; + let edges = vec![ + arc(bottom.clone(), 10.0, [seam, h], false), + line(Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 10.0, 20.0)), + arc(top.clone(), 10.0, [seam, h], true), + arc(top, 10.0, [-h, seam], true), + line(Vec3::new(0.0, -10.0, 20.0), Vec3::new(0.0, -10.0, 0.0)), + arc(bottom, 10.0, [-h, seam], false), + ]; + let mut g0 = |_k: usize, ts: &[f64]| -> Result>, String> { Ok(vec![None; ts.len()]) }; + let fill = iso_fill(&edges, &mut g0, &IsoSpec { tol: 2e-5, ..spec() }).unwrap(); + assert_eq!(fill.patches.len(), 1, "four corners, one patch"); + let sides = &fill.patches[0].sides; + assert_eq!(sides.len(), 6, "every edge on the patch's boundary"); + // Round the square, each edge from where the one before it ends. + let uv = |s: &IsoSide| match s { + IsoSide::Edge { uv, .. } | IsoSide::Spoke { uv, .. } => *uv, + }; + for (a, b) in sides.iter().zip(sides.iter().cycle().skip(1)) { + assert_eq!(uv(a)[1], uv(b)[0], "{sides:?}"); + } + assert!(!any_fold(&fill), "the patch folds"); + // Its corners are the loop's four, none flat. + for c in [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]] { + let (angle, ..) = corner_angle(&fill.patches[0], c); + assert!(angle > 0.5 && angle < 179.5, "a flat corner at {c:?}: {angle}°"); + } +} + +/// A crown fills the middle out to the side the neighbours' normals face, whichever way the +/// patch itself is parameterised: the sphere window, its neighbours' normals outward, rises away +/// from the centre; given them inward, it sinks. +#[test] +fn a_crown_fills_out_to_the_side_the_neighbours_face() { + let edges = window(); + let middle = |f: &IsoFill| f.patches[0].surface.eval(0.5, 0.5).unwrap().len(); + let plain = middle(&iso_fill(&edges, &mut sphere_beside(&edges, 1), &spec()).unwrap()); + let crowned = IsoSpec { crown: 0.1, ..spec() }; + let out = middle(&iso_fill(&edges, &mut sphere_beside(&edges, 1), &crowned).unwrap()); + let mut inward = { + let mut beside = sphere_beside(&edges, 1); + move |k: usize, ts: &[f64]| -> Result>, String> { + Ok(beside(k, ts)?.into_iter().map(|a| a.map(|a| Across { normal: a.normal * -1.0, ..a })).collect()) + } + }; + let sunk = middle(&iso_fill(&edges, &mut inward, &crowned).unwrap()); + eprintln!("the window's middle {plain:.4} from the centre, crowned {out:.4}, crowned to inward neighbours {sunk:.4}"); + assert!(out > plain + 0.1 && sunk < plain - 0.1, "{plain} {out} {sunk}"); +} + +/// The same loop fills to the same bits every time, about a centre and in a ring (a design is +/// rebuilt on reading it back, and must come back the same surface). +#[test] +fn a_fill_is_the_same_to_the_last_bit_every_time() { + let tube = circle_quarters(30.0, 10.0); + let radial = |p: Vec3| (Vec3::new(p.x, p.y, 0.0).normalized().unwrap(), Vec3::Z); + let s = IsoSpec { tol: 2e-5, ..spec() }; + let ring = |_: usize| iso_fill(&tube, &mut beside_by(&tube, radial), &s).unwrap(); + let corners: Vec = + (0..6).map(|k| Vec3::new((k as f64 * 1.047).cos(), (k as f64 * 1.047).sin(), 0.0) * 20.0 + Vec3::Z * (k % 2) as f64).collect(); + let hexagon: Vec = (0..6) + .map(|k| { + let (a, b) = (corners[k], corners[(k + 1) % 6]); + IsoEdge { degree: 2, knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points: vec![a, (a + b) * 0.5 + Vec3::Z * 2.0, b], weights: None } + }) + .collect(); + let mut g0 = |_k: usize, ts: &[f64]| -> Result>, String> { Ok(vec![None; ts.len()]) }; + let centre = |g0: &mut dyn FnMut(usize, &[f64]) -> Result>, String>| iso_fill(&hexagon, g0, &s).unwrap(); + let (a, b) = (ring(0), ring(1)); + assert_eq!(a.patches, b.patches, "the ring"); + let (a, b) = (centre(&mut g0), centre(&mut g0)); + assert_eq!(a.patches, b.patches, "about a centre"); +} diff --git a/crates/geom/src/fill_matched.rs b/crates/geom/src/fill_matched.rs new file mode 100644 index 000000000..9857cfb95 --- /dev/null +++ b/crates/geom/src/fill_matched.rs @@ -0,0 +1,505 @@ +//! Filling a closed loop with one height field that meets the faces beside the loop with G1 or +//! G2: the surface of [`crate::fill::fill_loop`] (a bicubic B-spline height field over the loop's +//! plane, so its parameters are plane coordinates and every edge's pcurve is the edge projected +//! onto that plane, exactly), fitted to the faces' derivatives as well as to the loop. +//! +//! The formulation (Piegl & Tiller, *The NURBS Book*, §9.4.1 least squares; do Carmo, +//! *Differential Geometry of Curves and Surfaces*, §3-3 for the second fundamental form of a +//! graph): +//! +//! - **The plane and grid** are [`crate::fill::fill_loop`]'s: the surface is +//! `S(u, v) = o + u·x + v·y + h(u, v)·n` with `h` a bicubic B-spline on a uniform grid over the +//! projected loop's box, the heights its unknowns. +//! - **The conditions** at each station (a point of the loop with the face beside it) are linear +//! in the heights, since every quantity of a graph is a derivative of `h`: +//! - G0: `h(u, v)` is the station's height. +//! - G1: the face's unit normal `N` (turned to `n`'s side) is the graph's when +//! `h_u = −N·x / N·n` and `h_v = −N·y / N·n`. +//! - G2: with G1, the surfaces share the curve and its tangent plane, so they agree to the +//! second order exactly when their normal curvatures across the curve agree: along the +//! direction `w` the face leaves the loop in (`a = w·x`, `b = w·y`), +//! `(a² h_uu + 2ab h_uv + b² h_vv) · N·n = κ`, `κ` the face's normal curvature along `w` +//! (its curvature vector `bend` against `N`). +//! +//! Each row is weighed to a length on the grid's scale (the G1 rows times a cell, the G2 rows +//! times a cell squared), and the heights minimise their squared misfit plus a small multiple +//! of the thin-plate energy ([`FAIRNESS`]), which decides what the conditions leave free. +//! - **At a corner** of the loop the two faces' conditions meet, and where their curvatures +//! across the corner differ (a round ending on a plane: the round's section has the round's +//! curvature where it reaches the plane, which is flat across its own curve) no surface is G2 +//! to both there: the surface's curvature is continuous, and has to pass from one face's to the +//! other's. A plane's G2 with G1 makes the surface flat to the second order all along its +//! curve, so the passage is a stiff one, and asked over a few cells it pulls the surface off +//! the loop along the whole side. The corner's own station holds the position only; the G2 +//! rows fade in over [`FADE_SHARE`] of the run from each corner to the next (a smoothstep of +//! the distance along the loop), a stretch of the loop's own, which finer grids then resolve, +//! and hold everywhere else. G1 rows fade likewise from a corner whose faces' tangent planes +//! disagree (`clash`), where no surface is G1 to both. +//! - **Grids** of 4 to [`MAX_MATCHED_SPANS`] spans across the box's longer side are tried in turn, +//! with denser sampling when a grid's cells are finer than twice the stations' step: the first +//! whose surface is within `tol` of every station, whose normal is within `angle_tol` of the +//! face's at every G1/G2 station clear of clashing corners, and whose normal curvature across +//! the loop is within `curvature_tol` of the face's at every G2 station clear of the corners' +//! fades, is the fill. Otherwise "not supported yet", with how close the best grid came. +//! +//! A loop that is not the boundary of a height field over its plane, or a face beside it that +//! stands along the plane's normal, is refused, never filled with wrong geometry. Input is +//! hostile: sizes are capped and every evaluation checked; nothing here panics. + +use crate::bspline::{SplineError, SplineResult, invalid}; +use crate::fill::{Band, Grid, LoopFill, LoopFrame, MAX_LOOP_POINTS, SMOOTHNESS, check_projectable, loop_frame}; +use crate::fill_general::Station; +use crate::prelude::*; +use solidcore_record::Vec3; + +/// Most spans of the height field across the box's longer side. +pub const MAX_MATCHED_SPANS: usize = 128; +/// Fewest spans (the first grid tried). +const MIN_SPANS: usize = 4; +/// The share of the run from a corner to the next over which the conditions the corner cannot +/// hold fade in. +pub const FADE_SHARE: f64 = 0.15; +/// The thin-plate energy's weight per fitted station: a thousand times +/// [`crate::fill::fill_loop`]'s. Its fill only passes through points, which leave the inside to +/// the energy alone; here the slope and curvature rows also act a little way inside the loop, +/// and with the weaker energy they pull the surface up past a plane it is G2 to, a millimetre or +/// two in from the plane's curve (by 0.06 at a box corner's r5 rounds set back 8). This weight +/// keeps it under the plane but where it passes from a round's curvature to the plane's, and +/// costs the loop little (2e-5 mm, 0.025° and 4e-4 per mm there). +const FAIRNESS: f64 = 1e3 * SMOOTHNESS; +/// A face beside the loop whose normal is closer than this cosine to square with the plane's +/// stands along the plane's normal: the height field cannot be tangent to it. +const MIN_NORMAL_COS: f64 = 0.05; + +/// What [`fill_matched`] is asked for. +#[derive(Clone, Copy, Debug)] +pub struct MatchedSpec { + /// How far the surface may be from the loop. + pub tol: f64, + /// How far (radians) its normal may turn from a G1/G2 neighbour's. + pub angle_tol: f64, + /// How far (1/length) its normal curvature across the loop may be from a G2 neighbour's, + /// clear of the corners' fades. + pub curvature_tol: f64, +} + +/// The fill and what it achieved. +#[derive(Clone, Debug, PartialEq)] +pub struct MatchedFill { + /// The height field, its plane and its deviation from the loop (no crown). + pub fill: LoopFill, + /// The largest angle (radians) between the surface's normal and a neighbour's at the G1/G2 + /// stations held to the angle tolerance, and at any G1/G2 station. + pub normal_deviation: f64, + pub normal_deviation_all: f64, + /// The largest difference (1/length) between the surface's normal curvature across the + /// loop and the neighbour's, at the G2 stations clear of the corners' fades, and at any G2 + /// station. + pub curvature_mismatch: f64, + pub curvature_mismatch_all: f64, + /// Spans of the grid each way, and stations sampled. + pub spans: [usize; 2], + pub stations: usize, +} + +/// Fill the closed loop of `sides` sides with one height field meeting each station's face as +/// its `across` asks (see the module documentation). `stations(k, ts)` samples side `k` at the +/// parameters `ts` (0 at its start, which is where side `k − 1` ends, towards 1 at its end); a +/// station at `t = 0` marked `corner` is a corner of the loop. +pub fn fill_matched( + sides: usize, + stations: &mut dyn FnMut(usize, &[f64]) -> Result, String>, + spec: &MatchedSpec, +) -> SplineResult { + if sides == 0 || sides.saturating_mul(16) > MAX_LOOP_POINTS / 2 { + return Err(SplineError::TooLarge(format!("a loop of {sides} sides (at most {})", MAX_LOOP_POINTS / 32))); + } + let positive = |x: f64| x.is_finite() && x > 0.0; + if !(positive(spec.tol) && positive(spec.angle_tol) && positive(spec.curvature_tol)) { + return invalid("the fill tolerances must be positive"); + } + let mut sample = |ts: &[f64]| -> SplineResult>> { + (0..sides) + .map(|k| { + let got = stations(k, ts).map_err(SplineError::Invalid)?; + if got.len() == ts.len() && got.iter().all(finite_station) { + Ok(got) + } else { + Err(SplineError::Invalid(format!("side {k} has no finite stations"))) + } + }) + .collect() + }; + let mut per = 16usize; + let mut fit = sample(&(0..per).map(|i| i as f64 / per as f64).collect::>())?; + let mut best = Shortfall::default(); + let mut level = MIN_SPANS; + loop { + let check = sample(&(0..per).map(|i| (i as f64 + 0.5) / per as f64).collect::>())?; + // The loop in order: fitted and checked stations alternating, side by side. + let mut all: Vec<(Station, bool)> = Vec::with_capacity(2 * per * sides); + for (f, c) in fit.iter().zip(&check) { + for (a, b) in f.iter().zip(c) { + all.push((*a, true)); + all.push((*b, false)); + } + } + match fit_round(&all, spec, level)? { + Round::Done(fill) => return Ok(*fill), + Round::Denser(s, at) => { + best = best.min(s); + level = at; + } + Round::Exhausted(s) => { + best = best.min(s); + break; + } + } + if all.len() * 2 > MAX_LOOP_POINTS { + break; + } + fit = fit.iter().zip(&check).map(|(f, c)| f.iter().zip(c).flat_map(|(a, b)| [*a, *b]).collect()).collect(); + per *= 2; + } + Err(SplineError::Unsupported(format!( + "filling this loop with one surface meeting its neighbours: the closest fit stays {:e} off the loop (tolerance {:e}), turns {:.4}° from \ + its neighbours (tolerance {:.4}°) and misses their curvature by {:e} (tolerance {:e})", + best.deviation, + spec.tol, + best.angle.to_degrees(), + spec.angle_tol.to_degrees(), + best.curvature, + spec.curvature_tol + ))) +} + +fn finite_station(s: &Station) -> bool { + s.p.is_finite() && s.across.is_none_or(|a| a.leave.is_finite() && a.normal.is_finite() && a.bend.is_none_or(|b| b.is_finite())) +} + +/// How close a grid came. +#[derive(Clone, Copy, Debug)] +struct Shortfall { + deviation: f64, + angle: f64, + curvature: f64, +} + +impl Default for Shortfall { + fn default() -> Shortfall { + Shortfall { deviation: f64::INFINITY, angle: f64::INFINITY, curvature: f64::INFINITY } + } +} + +impl Shortfall { + /// The closer of two, by how many times its tolerance each misses. + fn min(self, other: Shortfall) -> Shortfall { + let worst = |s: &Shortfall| s.deviation + s.angle + s.curvature; + if worst(&other) < worst(&self) { other } else { self } + } +} + +enum Round { + Done(Box), + /// Denser sampling is needed for the grid of this level (the coarser ones fell short). + Denser(Shortfall, usize), + Exhausted(Shortfall), +} + +/// A station as the fit takes it: its place over the plane, its height, and what the face beside +/// it asks there, in the plane's terms. +struct Row { + q: [f64; 2], + h: f64, + fitted: bool, + /// G1: the height field's gradient there, and the face's unit normal on `n`'s side. + gradient: Option<([f64; 2], Vec3)>, + /// G2: the leave direction's plane components `(a, b)` and the second derivative of `h` + /// along them, `κ / N·n`, with `κ` itself. + curvature: Option<([f64; 2], f64, f64)>, + /// How near the station is to a corner, and to a clashing corner: its distance along the + /// loop to the nearer of the two around it, as a share of the run between them (0 at a + /// corner, ½ midway; 1 with no corner). + to_corner: f64, + to_clash: f64, + corner: bool, +} + +/// The stations in the plane `f`'s terms, with their distances to the corners along the loop. +fn rows(all: &[(Station, bool)], f: &LoopFrame) -> SplineResult> { + let m = all.len(); + // Arc length along the loop (chords), and where its corners are. + let mut s = vec![0.0f64; m + 1]; + for k in 0..m { + let (Some((a, _)), Some((b, _))) = (all.get(k), all.get((k + 1) % m)) else { return invalid("stations") }; + let next = s.get(k).copied().unwrap_or(0.0) + a.p.dist(b.p); + if let Some(slot) = s.get_mut(k + 1) { + *slot = next; + } + } + let total = s.get(m).copied().unwrap_or(0.0); + if !(total > 0.0 && total.is_finite()) { + return invalid("the loop has no length"); + } + let at = |k: usize| s.get(k).copied().unwrap_or(0.0); + let corners: Vec = (0..m).filter(|&k| all.get(k).is_some_and(|(st, _)| st.corner)).map(at).collect(); + let clashes: Vec = (0..m).filter(|&k| all.get(k).is_some_and(|(st, _)| st.clash)).map(at).collect(); + let share = |list: &[f64], x: f64| { + if list.is_empty() { + return 1.0; + } + let back = list.iter().map(|c| (x - c).rem_euclid(total)).fold(f64::INFINITY, f64::min); + let ahead = list.iter().map(|c| (c - x).rem_euclid(total)).filter(|d| *d > 0.0).fold(total, f64::min); + let run = back + ahead; + if run > 0.0 { back.min(ahead) / run } else { 0.0 } + }; + let mut out = Vec::with_capacity(m); + for (k, (st, fitted)) in all.iter().enumerate() { + let d = st.p - f.o; + let q = [d.dot(f.x), d.dot(f.y)]; + let mut gradient = None; + let mut curvature = None; + if let Some(a) = st.across { + let normal = a.normal.normalized().ok_or_else(|| SplineError::Invalid("a neighbour's normal has no direction".into()))?; + let side = if normal.dot(f.n) >= 0.0 { 1.0 } else { -1.0 }; + let nn = normal * side; + let c = nn.dot(f.n); + if !(c > MIN_NORMAL_COS) { + return Err(SplineError::Unsupported("filling a loop beside a face that stands along the fill's normal".into())); + } + gradient = Some(([-nn.dot(f.x) / c, -nn.dot(f.y) / c], nn)); + if let Some(bend) = a.bend { + let kappa = bend.dot(nn); + let w = a.leave; + curvature = Some(([w.dot(f.x), w.dot(f.y)], kappa / c, kappa)); + } + } + out.push(Row { + q, + h: d.dot(f.n), + fitted: *fitted, + gradient, + curvature, + to_corner: share(&corners, at(k)), + to_clash: share(&clashes, at(k)), + corner: st.corner, + }); + } + Ok(out) +} + +/// The smoothstep `3t² − 2t³` of `share / FADE_SHARE` (1 from [`FADE_SHARE`] on). +fn fade(share: f64) -> f64 { + let t = (share / FADE_SHARE).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// The height field's derivatives at `q`: `[h, h_u, h_v, h_uu, h_uv, h_vv]`. +fn derivatives(grid: &Grid, heights: &[f64], q: [f64; 2]) -> Option<[f64; 6]> { + let cu = *grid.count.first()?; + let mut out = [0.0; 6]; + for (slot, (ru, rv)) in out.iter_mut().zip([(0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2)]) { + let (i0, bu) = grid.basis_derivative(0, q[0], ru)?; + let (j0, bv) = grid.basis_derivative(1, q[1], rv)?; + let mut s = 0.0; + for (b, wv) in bv.iter().enumerate() { + for (a, wu) in bu.iter().enumerate() { + s += wu * wv * heights.get((j0 + b) * cu + i0 + a)?; + } + } + *slot = s; + } + out.iter().all(|x| x.is_finite()).then_some(out) +} + +/// One grid's fit of the rows: the normal equations of the weighed rows and the energy. +fn solve(grid: &Grid, rows: &[Row], cell: f64) -> SplineResult> { + let [cu, cv] = grid.count; + let n = cu * cv; + let mut band = Band::new(n, 3 * cu + 3); + let mut rhs = vec![0.0; n]; + let add = |terms: &[(usize, f64)], value: f64, weight: f64, band: &mut Band, rhs: &mut Vec| { + let w2 = weight * weight; + for &(r, cr) in terms { + if let Some(slot) = rhs.get_mut(r) { + *slot += w2 * cr * value; + } + for &(s, cs) in terms { + band.add(r, s, w2 * cr * cs); + } + } + }; + let mut fitted = 0usize; + for row in rows.iter().filter(|r| r.fitted) { + let basis = |r: [usize; 2]| -> SplineResult<(usize, [f64; 4], usize, [f64; 4])> { + let (Some((i0, bu)), Some((j0, bv))) = (grid.basis_derivative(0, row.q[0], r[0]), grid.basis_derivative(1, row.q[1], r[1])) else { + return invalid("a loop point is off the grid"); + }; + Ok((i0, bu, j0, bv)) + }; + // The 16 control heights a derivative of order `r` at the station draws on, scaled. + let terms = |r: [usize; 2], scale: f64| -> SplineResult> { + let (i0, bu, j0, bv) = basis(r)?; + let mut t = Vec::with_capacity(16); + for (b, wv) in bv.iter().enumerate() { + for (a, wu) in bu.iter().enumerate() { + t.push(((j0 + b) * cu + i0 + a, wu * wv * scale)); + } + } + Ok(t) + }; + add(&terms([0, 0], 1.0)?, row.h, 1.0, &mut band, &mut rhs); + fitted += 1; + if row.corner { + continue; + } + if let Some((g, _)) = row.gradient { + let w = cell * fade(row.to_clash); + if w > 0.0 { + add(&terms([1, 0], 1.0)?, g[0], w, &mut band, &mut rhs); + add(&terms([0, 1], 1.0)?, g[1], w, &mut band, &mut rhs); + } + } + if let Some(([a, b], second, _)) = row.curvature { + let w = cell * cell * fade(row.to_corner) * fade(row.to_clash); + if w > 0.0 { + // a² h_uu + 2ab h_uv + b² h_vv, the three derivatives' terms summed per control + // height. + let mut sum: Vec<(usize, f64)> = Vec::with_capacity(48); + for (r, s) in [([2, 0], a * a), ([1, 1], 2.0 * a * b), ([0, 2], b * b)] { + for (idx, v) in terms(r, s)? { + match sum.iter_mut().find(|(i, _)| *i == idx) { + Some(slot) => slot.1 += v, + None => sum.push((idx, v)), + } + } + } + add(&sum, second, w, &mut band, &mut rhs); + } + } + } + let lambda = FAIRNESS * fitted as f64 / n as f64 * grid.cell(0) * grid.cell(1); + grid.add_energy(&mut band, lambda); + band.solve(rhs) +} + +/// What a fitted grid achieves at the rows: the deviation from the loop, the normal's angle to +/// the neighbours' (held stations, all), the curvature mismatch (held stations, all). +fn achieved(grid: &Grid, heights: &[f64], rows: &[Row], f: &LoopFrame) -> SplineResult<[f64; 5]> { + let reach = FADE_SHARE; + let (mut dev, mut ang, mut ang_all, mut cur, mut cur_all) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 0.0f64); + for row in rows { + let Some([h, hu, hv, huu, huv, hvv]) = derivatives(grid, heights, row.q) else { return invalid("the fit is not finite") }; + dev = dev.max((h - row.h).abs()); + if row.corner { + continue; + } + let up = (1.0 + hu * hu + hv * hv).sqrt(); + let normal = (f.n - f.x * hu - f.y * hv) * (1.0 / up); + if let Some((_, nn)) = row.gradient { + let a = normal.dot(nn).clamp(-1.0, 1.0).acos(); + ang_all = ang_all.max(a); + if row.to_clash >= reach { + ang = ang.max(a); + } + } + if let Some(([a, b], _, kappa)) = row.curvature { + // The normal curvature along the unit tangent of the surface over (a, b): the second + // fundamental form over the first. + let t = f.x * a + f.y * b + f.n * (a * hu + b * hv); + let ii = (a * a * huu + 2.0 * a * b * huv + b * b * hvv) / up; + let k = ii / t.len2().max(1e-300); + let miss = (k - kappa).abs(); + cur_all = cur_all.max(miss); + if row.to_corner >= reach && row.to_clash >= reach { + cur = cur.max(miss); + } + } + } + Ok([dev, ang, ang_all, cur, cur_all]) +} + +/// One round: the grids from `level` up, on these stations. +fn fit_round(all: &[(Station, bool)], spec: &MatchedSpec, level: usize) -> SplineResult { + let fitted: Vec = all.iter().filter(|(_, f)| *f).map(|(s, _)| s.p).collect(); + let frame = loop_frame(&fitted)?; + let points: Vec = all.iter().map(|(s, _)| s.p).collect(); + let rows = rows(all, &frame)?; + let uv: Vec<[f64; 2]> = rows.iter().map(|r| r.q).collect(); + check_projectable(&points, &uv)?; + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for q in &uv { + for d in 0..2 { + lo[d] = lo[d].min(q[d]); + hi[d] = hi[d].max(q[d]); + } + } + for d in 0..2 { + let pad = 0.01 * (hi[d] - lo[d]); + lo[d] -= pad; + hi[d] += pad; + } + if !(lo[0] < hi[0] && lo[1] < hi[1] && (hi[0] - lo[0]).is_finite() && (hi[1] - lo[1]).is_finite()) { + return invalid("the loop's extent is not finite"); + } + // The fitted stations' largest step each way: a grid finer than half of it waits for denser + // sampling. + let fq: Vec<[f64; 2]> = rows.iter().filter(|r| r.fitted).map(|r| r.q).collect(); + let mut step = [0.0f64; 2]; + for k in 0..fq.len() { + let (p, q) = (fq.get(k).copied().unwrap_or([0.0; 2]), fq.get((k + 1) % fq.len()).copied().unwrap_or([0.0; 2])); + for d in 0..2 { + step[d] = step[d].max((q[d] - p[d]).abs()); + } + } + let extent = [hi[0] - lo[0], hi[1] - lo[1]]; + let longer = extent[0].max(extent[1]); + let mut best = Shortfall::default(); + let mut level = level; + while level <= MAX_MATCHED_SPANS { + let spans = [0, 1].map(|d| ((extent[d] / longer * level as f64).ceil() as usize).clamp(1, level)); + let holds = (0..2).all(|d| extent[d] / spans[d] as f64 >= 2.0 * step[d]); + if !holds && level > MIN_SPANS { + return Ok(Round::Denser(best, level)); + } + let grid = Grid::new(spans, lo, hi); + let cell = grid.cell(0).max(grid.cell(1)); + let heights = solve(&grid, &rows, cell)?; + let [dev, ang, ang_all, cur, cur_all] = achieved(&grid, &heights, &rows, &frame)?; + let s = Shortfall { deviation: dev, angle: ang, curvature: cur }; + best = best.min(s); + if dev <= spec.tol && ang <= spec.angle_tol && cur <= spec.curvature_tol && holds { + let surface = grid.surface(&heights, frame.o, frame.x, frame.y, frame.n)?; + let fill = LoopFill { + surface, + origin: frame.o, + axes: [frame.x, frame.y], + normal: frame.n, + counter_clockwise: frame.counter_clockwise, + deviation: dev, + evaluations: all.len(), + crown: 0.0, + crowned: 0, + crown_drift: 0.0, + }; + return Ok(Round::Done(Box::new(MatchedFill { + fill, + normal_deviation: ang, + normal_deviation_all: ang_all, + curvature_mismatch: cur, + curvature_mismatch_all: cur_all, + spans, + stations: all.len(), + }))); + } + if !holds { + return Ok(Round::Denser(best, level)); + } + level *= 2; + } + Ok(Round::Exhausted(best)) +} + +#[cfg(test)] +#[path = "fill_matched_tests.rs"] +mod tests; diff --git a/crates/geom/src/fill_matched_tests.rs b/crates/geom/src/fill_matched_tests.rs new file mode 100644 index 000000000..ab942bc7d --- /dev/null +++ b/crates/geom/src/fill_matched_tests.rs @@ -0,0 +1,187 @@ +use super::*; +use crate::fill_general::Across; +use std::f64::consts::FRAC_PI_2; + +/// The face tolerance of the 60 x 40 x 20 box the corner is cut from (10⁻⁶ of its size). +const TOL: f64 = 7.5e-5; +const ANGLE: f64 = 0.05 * std::f64::consts::PI / 180.0; +/// Half a percent of the 1/5 per mm a rolling ball of radius 5 jumps by across its seams. +const CURVATURE: f64 = 1e-3; + +fn spec() -> MatchedSpec { + MatchedSpec { tol: TOL, angle_tol: ANGLE, curvature_tol: CURVATURE } +} + +/// The hole a setback leaves at the corner of three rounds of radius `r` set back `s` (> r) +/// along each edge of a corner at the origin, the solid below it in every axis: three sections +/// of the rounds (quarter circles on the cylinders about the three edges) and three curves on the +/// faces between their ends, each a quarter circle about the point `s` back along both edges +/// (radius `s − r`), meeting the rounds' contact lines tangentially. Each side is G2 to its face: +/// a round leaves its section along its axis, where it is straight, a face anywhere; both have no +/// curvature across the hole. +fn setback_hole(r: f64, s: f64, g2: bool) -> impl FnMut(usize, &[f64]) -> Result, String> { + let rho = s - r; + move |k, ts| { + ts.iter() + .map(|t| { + let a = t * FRAC_PI_2; + let (sin, cos) = a.sin_cos(); + let (p, normal, leave) = match k { + 0 => (Vec3::new(-s, -r + r * sin, -r + r * cos), Vec3::new(0.0, sin, cos), Vec3::X), + 1 => (Vec3::new(-s + rho * sin, 0.0, -s + rho * cos), Vec3::Y, Vec3::new(sin, 0.0, cos)), + 2 => (Vec3::new(-r + r * sin, -r + r * cos, -s), Vec3::new(sin, cos, 0.0), Vec3::Z), + 3 => (Vec3::new(0.0, -s + rho * cos, -s + rho * sin), Vec3::X, Vec3::new(0.0, cos, sin)), + 4 => (Vec3::new(-r + r * cos, -s, -r + r * sin), Vec3::new(cos, 0.0, sin), Vec3::Y), + 5 => (Vec3::new(-s + rho * cos, -s + rho * sin, 0.0), Vec3::Z, Vec3::new(cos, sin, 0.0)), + _ => return Err(format!("no side {k}")), + }; + let up = Vec3::new(1.0, 1.0, 1.0).normalized().unwrap_or(Vec3::Z); + Ok(Station { + p, + up, + across: Some(Across { leave, normal, bend: g2.then_some(Vec3::ZERO), jet: None }), + corner: *t == 0.0, + clash: false, + }) + }) + .collect() + } +} + +#[test] +fn a_setback_corner_hole_is_filled_g2_to_its_rounds_and_faces() { + let f = fill_matched(6, &mut setback_hole(5.0, 8.0, true), &spec()).unwrap(); + eprintln!( + "setback hole: spans {:?}, {} stations, deviation {:e}, normal {:.5}° (all {:.5}°), curvature {:e} (all {:e})", + f.spans, + f.stations, + f.fill.deviation, + f.normal_deviation.to_degrees(), + f.normal_deviation_all.to_degrees(), + f.curvature_mismatch, + f.curvature_mismatch_all + ); + assert!(f.fill.deviation <= TOL && f.normal_deviation <= ANGLE && f.curvature_mismatch <= CURVATURE); + // The plane is the corner's diagonal one, by symmetry. + let d = Vec3::new(1.0, 1.0, 1.0).normalized().unwrap(); + assert!(f.fill.normal.dot(d) > 1.0 - 1e-9, "{:?}", f.fill.normal); + // The patch is the corner's cap: inside the corner cube's octant and within the hull of the + // three rounds' tangent planes at 45° (the box's corner cut back by the rounds). + let [du, dv] = f.fill.surface.domain(); + let mut highest = f64::NEG_INFINITY; + for i in 0..=40 { + for j in 0..=40 { + let u = (du[0] + (du[1] - du[0]) * i as f64 / 40.0).min(du[1]); + let v = (dv[0] + (dv[1] - dv[0]) * j as f64 / 40.0).min(dv[1]); + let p = f.fill.surface.eval(u, v).unwrap(); + // Over the loop only: the box's corners outside the hole are not the patch. + if p.x > -8.0 && p.y > -8.0 && p.z > -8.0 && p.x < 0.0 && p.y < 0.0 && p.z < 0.0 { + highest = highest.max(p.dot(d)); + } + } + } + eprintln!("setback hole: highest point along the diagonal {highest:.6}"); + assert!(highest < 0.0); +} + +#[test] +fn a_setback_corner_hole_is_filled_g1_on_a_coarser_grid() { + let f = fill_matched(6, &mut setback_hole(5.0, 8.0, false), &spec()).unwrap(); + eprintln!("setback hole G1: spans {:?}, deviation {:e}, normal {:.5}°", f.spans, f.fill.deviation, f.normal_deviation.to_degrees()); + assert!(f.fill.deviation <= TOL && f.normal_deviation <= ANGLE); + // Flat to the second order along a curved plane's curve is what makes G2 the harder fill. + let g2 = fill_matched(6, &mut setback_hole(5.0, 8.0, true), &spec()).unwrap(); + assert!(f.spans[0] < g2.spans[0], "{:?} {:?}", f.spans, g2.spans); +} + +/// A hole in a cylinder of radius 5 about the x axis (its top line through the origin), the rim +/// over the circle of radius 2 about the z axis, G2 all round: the loop has no corner, and the +/// fill repeats the cylinder there. +#[test] +fn a_hole_in_a_cylinder_is_filled_with_the_cylinder_to_the_second_order() { + let r = 5.0; + let mut rim = move |_: usize, ts: &[f64]| -> Result, String> { + ts.iter() + .map(|t| { + let a = t * std::f64::consts::TAU; + let (x, y) = (2.0 * a.cos(), 2.0 * a.sin()); + let z = (r * r - y * y).sqrt() - r; + let p = Vec3::new(x, y, z); + let normal = Vec3::new(0.0, y, z + r).normalized().ok_or("normal")?; + let tangent = Vec3::new(-a.sin(), a.cos(), -a.cos() * y / (z + r)).normalized().ok_or("tangent")?; + // Into the hole, square to the rim in the cylinder. + let leave = tangent.cross(normal).normalized().ok_or("leave")?; + let leave = if leave.dot(Vec3::new(-x, -y, 0.0)) > 0.0 { leave } else { leave * -1.0 }; + // The cylinder's normal curvature along `leave`: its part across the axis, squared, + // over the radius, bending away from the normal. + let across = leave - Vec3::X * leave.x; + let bend = normal * (-across.len2() / r); + Ok(Station { p, up: normal, across: Some(Across { leave, normal, bend: Some(bend), jet: None }), corner: false, clash: false }) + }) + .collect() + }; + let f = fill_matched(1, &mut rim, &spec()).unwrap(); + eprintln!("cylinder hole: spans {:?}, deviation {:e}, curvature {:e}", f.spans, f.fill.deviation, f.curvature_mismatch_all); + assert!(f.fill.deviation <= TOL && f.normal_deviation_all <= ANGLE && f.curvature_mismatch_all <= CURVATURE); +} + +#[test] +fn hostile_matched_fills_are_refused() { + let bad = MatchedSpec { tol: 0.0, ..spec() }; + assert!(fill_matched(6, &mut setback_hole(5.0, 8.0, true), &bad).is_err()); + assert!(fill_matched(0, &mut setback_hole(5.0, 8.0, true), &spec()).is_err()); + // A face beside the loop standing along the fill's normal. + let mut wall = |_: usize, ts: &[f64]| -> Result, String> { + Ok(ts + .iter() + .map(|t| { + let a = t * std::f64::consts::TAU / 3.0; + let p = Vec3::new(a.cos(), a.sin(), 0.0); + Station { p, up: Vec3::Z, across: Some(Across { leave: Vec3::Z, normal: p, bend: None, jet: None }), corner: false, clash: false } + }) + .collect()) + }; + assert!(matches!(fill_matched(3, &mut wall, &spec()), Err(SplineError::Unsupported(_)))); +} + +/// How far the fill of `setback_hole(r, s)` rises past the planes it is G2 to, over the loop +/// (the corner is convex: all of it should lie under them), sampled. +fn over_the_planes(f: &MatchedFill, r: f64, s: f64) -> f64 { + let mut st = setback_hole(r, s, true); + let ts: Vec = (0..256).map(|i| i as f64 / 256.0).collect(); + let poly: Vec<[f64; 2]> = (0..6) + .flat_map(|k| st(k, &ts).unwrap()) + .map(|q| { + let d = q.p - f.fill.origin; + [d.dot(f.fill.axes[0]), d.dot(f.fill.axes[1])] + }) + .collect(); + let [du, dv] = f.fill.surface.domain(); + let n = 200; + let mut over = f64::NEG_INFINITY; + for i in 0..=n { + for j in 0..=n { + let u = (du[0] + (du[1] - du[0]) * i as f64 / n as f64).min(du[1]); + let v = (dv[0] + (dv[1] - dv[0]) * j as f64 / n as f64).min(dv[1]); + if crate::fill::inside_loop([u, v], &poly) { + let p = f.fill.surface.eval(u, v).unwrap(); + over = over.max(p.x).max(p.y).max(p.z); + } + } + } + over +} + +/// Set back from 1.5 to 3 times the radius the G2 fill stays under the planes it meets, but by +/// under a thousandth where it passes from a round's curvature to the plane's at the hole's +/// corners (SMLib's own setback patch rises past them beyond about twice the radius, by 0.002 at +/// 2.2 r and 0.25 at 3 r). +#[test] +fn a_setback_g2_fill_stays_under_its_planes() { + for s in [7.5, 8.0, 10.0, 12.0, 15.0] { + let f = fill_matched(6, &mut setback_hole(5.0, s, true), &spec()).unwrap(); + let over = over_the_planes(&f, 5.0, s); + eprintln!("set back {s}: spans {:?}, curvature {:.2e}, over the planes {over:.2e}", f.spans, f.curvature_mismatch); + assert!(over < 1e-3, "set back {s}: {over}"); + } +} diff --git a/crates/geom/src/hlr/curve.rs b/crates/geom/src/hlr/curve.rs index 2da8e2e8f..1b1b74d51 100644 --- a/crates/geom/src/hlr/curve.rs +++ b/crates/geom/src/hlr/curve.rs @@ -1,10 +1,14 @@ -//! Evaluation of portable B-rep curves: lines, circle and ellipse arcs, polynomial and rational -//! splines (fitted intersection records are ordinary splines with a stated fitting tolerance). +//! Evaluation of portable B-rep edges: lines, circle and ellipse arcs, polynomial and rational +//! splines (a traced intersection whose leader is a spline is that spline, within its tolerance). +//! Records' curves are unbounded: every curve here is cut to its edge's interval, so `domain` and +//! `breaks` are the edge's. use super::HlrError; -use crate::Vec3; -use crate::brep::{Curve, Frame}; +use crate::brep::eval::{CurveEval, SurfaceEval}; +use crate::prelude::*; use crate::section::CurveAccuracy; +use solidcore_record::Vec3; +use solidcore_record::brep::{Curve, Edge, Frame}; #[derive(Clone, Debug)] pub(crate) enum C3 { @@ -41,30 +45,108 @@ pub(crate) fn frame_axes(f: &Frame) -> (Vec3, Vec3, Vec3) { (v3(f.origin), x, y) } +/// Whether every sample of `c`, a few to each of its breaks, lies within `tolerance` of both +/// `surfaces`. +fn on_both_surfaces(c: &C3, surfaces: &[Box; 2], tolerance: f64) -> bool { + /// Most samples checked; a longer curve's are spread evenly over it. + const MAX_SAMPLES: usize = 512; + let [Ok(a), Ok(b)] = [SurfaceEval::new(&surfaces[0]), SurfaceEval::new(&surfaces[1])] else { return false }; + let breaks = c.breaks(); + let samples: Vec = + breaks.windows(2).flat_map(|w| (0..4).map(move |i| w[0] + (w[1] - w[0]) * f64::from(i) / 4.0)).chain(breaks.last().copied()).collect(); + let stride = (samples.len() / MAX_SAMPLES).max(1); + samples.iter().step_by(stride).all(|t| { + let p = c.at(*t); + // A plane's `project` answers with the foot of a point however far off, so the distance + // is measured here. + let on = |s: &SurfaceEval| s.project(p, None, tolerance).and_then(|uv| s.point(uv)).is_some_and(|q| q.dist(p) <= tolerance); + p.is_finite() && on(&a) && on(&b) + }) +} + impl C3 { - pub fn new(c: &Curve) -> Result<(C3, CurveAccuracy), HlrError> { + /// The bounded curve of an edge. A line, circle or ellipse with a NURBS form has its bounds + /// on the form ([`Edge::parameters`]): a line's ends are evaluated there, a conic's angles come + /// from [`crate::brep::label::edge_curve_interval`]. + pub fn of_edge(e: &Edge) -> Result<(C3, CurveAccuracy), HlrError> { + let exact = |c: C3| (c, CurveAccuracy::Analytic); + match (&e.curve, &e.nurbs) { + (Curve::SurfaceIntersection { surfaces, leader, tolerance }, form) => { + // Procedural: traced on demand from its leader. A spline to follow (its form, or + // the leader itself) is a fitted curve, good to the record's tolerance; a polyline + // leader carries no such curve. + let fitted = match (form, leader.as_ref()) { + (Some(n @ (Curve::Spline { .. } | Curve::RationalSpline { .. })), _) | (None, n @ Curve::Spline { .. }) => n, + _ => return Err(HlrError::Unsupported("surface intersection curve")), + }; + let c = C3::bounded(fitted, e.interval)?; + // What is drawn is that spline: it has to lie on both surfaces, or the tolerance + // the record claims says nothing and the drawing would show a wrong line. + if !on_both_surfaces(&c, surfaces, *tolerance) { + return Err(HlrError::Unsupported("surface intersection curve")); + } + Ok((c, CurveAccuracy::Bounded { max_deviation_mm: *tolerance })) + } + (Curve::Line { .. }, Some(form)) => { + let eval = CurveEval::new(form).map_err(|_| HlrError::Invalid("edge form"))?; + let end = |t: f64| eval.point(t).filter(|p| p.is_finite()).ok_or(HlrError::Invalid("edge form")); + Ok(exact(C3::Line { a: end(e.interval[0])?, b: end(e.interval[1])? })) + } + (Curve::Circle { .. } | Curve::Ellipse { .. }, _) => { + let angles = crate::brep::label::edge_curve_interval(e).ok_or(HlrError::Invalid("edge form"))?; + Ok(exact(C3::bounded(&e.curve, angles)?)) + } + (curve, _) => Ok(exact(C3::bounded(curve, e.interval)?)), + } + } + + /// `c` between the parameters `t` on its own parameter (a line then runs over [0, 1], a + /// polyline over [0, its segments]). + pub fn bounded(c: &Curve, t: [f64; 2]) -> Result { + if !(t[0].is_finite() && t[1].is_finite() && t[0] < t[1]) { + return Err(HlrError::Invalid("curve interval")); + } Ok(match c { - Curve::Line { start, end } => (C3::Line { a: v3(*start), b: v3(*end) }, CurveAccuracy::Analytic), - Curve::CircleArc { frame, radius, angle } => { - let (o, x, y) = frame_axes(frame); - (C3::Arc { o, x, y, r: [*radius, *radius], range: *angle }, CurveAccuracy::Analytic) + Curve::Line { start, end } => { + let (a, d) = (v3(*start), v3(*end) - v3(*start)); + let (p, q) = (a + d * t[0], a + d * t[1]); + if !(p.is_finite() && q.is_finite()) { + return Err(HlrError::Invalid("curve interval")); + } + C3::Line { a: p, b: q } } - Curve::EllipseArc { frame, radii, angle } => { + Curve::Circle { frame, radius } => { let (o, x, y) = frame_axes(frame); - (C3::Arc { o, x, y, r: *radii, range: *angle }, CurveAccuracy::Analytic) + C3::Arc { o, x, y, r: [*radius, *radius], range: t } } - Curve::Polyline { points } => (C3::Polyline(points.iter().copied().map(v3).collect()), CurveAccuracy::Analytic), - Curve::Spline { knots, points } => (spline(knots, points.iter().map(|p| [p[0], p[1], p[2], 1.]).collect())?, CurveAccuracy::Analytic), - Curve::RationalSpline { knots, homogeneous } => (spline(knots, homogeneous.clone())?, CurveAccuracy::Analytic), - Curve::Intersection { knots, points, fitting_tolerance, .. } => ( - spline(knots, points.iter().map(|p| [p[0], p[1], p[2], 1.]).collect())?, - CurveAccuracy::Bounded { max_deviation_mm: *fitting_tolerance }, - ), - // Procedural: the curve is traced on demand from its leader, which carries no bound. + Curve::Ellipse { frame, radii } => { + let (o, x, y) = frame_axes(frame); + C3::Arc { o, x, y, r: *radii, range: t } + } + Curve::Polyline { points } => C3::Polyline(polyline_part(points, t)?), + Curve::Spline { knots, points } => part(knots, points.iter().map(|p| [p[0], p[1], p[2], 1.]).collect(), t)?, + Curve::RationalSpline { knots, homogeneous } => part(knots, homogeneous.clone(), t)?, Curve::SurfaceIntersection { .. } => return Err(HlrError::Unsupported("surface intersection curve")), }) } + /// The curve under a placement: `point` maps positions, `direction` directions (a rigid motion, + /// which keeps the arcs' parameter and a spline's weights). + pub fn placed(&self, point: &dyn Fn(Vec3) -> Vec3, direction: &dyn Fn(Vec3) -> Vec3) -> Result { + Ok(match self { + C3::Line { a, b } => C3::Line { a: point(*a), b: point(*b) }, + C3::Arc { o, x, y, r, range } => C3::Arc { o: point(*o), x: direction(*x), y: direction(*y), r: *r, range: *range }, + C3::Polyline(p) => C3::Polyline(p.iter().map(|q| point(*q)).collect()), + C3::Spline { knots, points, .. } => { + let moved = points.iter().map(|h| { + let q = point(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])); + [q.x * h[3], q.y * h[3], q.z * h[3], h[3]] + }); + spline(knots, moved.collect())? + } + }) + } + pub fn domain(&self) -> [f64; 2] { match self { C3::Line { .. } => [0., 1.], @@ -139,6 +221,57 @@ fn spline(knots: &[f64], points: Vec<[f64; 4]>) -> Result { Ok(C3::Spline { degree, knots: knots.to_vec(), points, pieces }) } +/// The polyline's points between the parameters `t` (segment i spans [i, i + 1]). +fn polyline_part(points: &[[f64; 3]], t: [f64; 2]) -> Result, HlrError> { + let last = points.len().saturating_sub(1) as f64; + let t = [t[0].clamp(0., last), t[1].clamp(0., last)]; + let at = |x: f64| { + let i = (x.floor().max(0.) as usize).min(points.len().saturating_sub(2)); + match (points.get(i), points.get(i + 1)) { + (Some(a), Some(b)) => Ok(v3(*a).lerp(v3(*b), x - i as f64)), + _ => Err(HlrError::Invalid("polyline")), + } + }; + let inner = (t[0].floor() as i64 + 1..t[1].ceil() as i64).filter_map(|i| usize::try_from(i).ok()).filter_map(|i| points.get(i).copied()).map(v3); + Ok(std::iter::once(at(t[0])?).chain(inner).chain(std::iter::once(at(t[1])?)).collect()) +} + +/// The spline's part between the parameters `t`, itself a clamped spline on them: the whole +/// spline as it stands when `t` is its whole active interval. +fn part(knots: &[f64], points: Vec<[f64; 4]>, t: [f64; 2]) -> Result { + use crate::bspline::{HPoint, clamp_row, insert_knot}; + let refused = HlrError::Unsupported("spline edge interval"); + let p = knots.len().checked_sub(points.len() + 1).ok_or(HlrError::Unsupported("spline knot count"))?; + let (Some(&lo), Some(&hi)) = (knots.get(p), knots.get(points.len())) else { return Err(HlrError::Unsupported("spline knot count")) }; + if t[0] <= lo && hi <= t[1] { + return spline(knots, points); + } + let row: Vec = points.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(); + let Ok((mut k, mut c)) = clamp_row(p, knots, &row) else { return Err(refused) }; + let t = [t[0].max(lo), t[1].min(hi)]; + if !(t[0] < t[1]) { + return Err(refused); + } + for u in t { + if u > lo && u < hi { + // Each end a knot of full multiplicity: the control net splits there. + for _ in k.iter().filter(|x| **x == u).count()..p { + let Ok((nk, nc)) = insert_knot(p, &k, &c, u) else { return Err(refused) }; + (k, c) = (nk, nc); + } + } + } + let last_at_start = k.partition_point(|x| *x <= t[0]).checked_sub(1).ok_or(HlrError::Unsupported("spline edge interval"))?; + let first_at_end = k.partition_point(|x| *x < t[1]); + let (Some(inner), Some(net)) = (k.get(last_at_start + 1..first_at_end), last_at_start.checked_sub(p).and_then(|s| c.get(s..first_at_end))) else { + return Err(refused); + }; + let mut cut = vec![t[0]; p + 1]; + cut.extend_from_slice(inner); + cut.extend(std::iter::repeat_n(t[1], p + 1)); + spline(&cut, net.iter().map(|h| [h.x, h.y, h.z, h.w]).collect()) +} + /// A spline split into Bézier pieces: clamped, then every inner knot raised to the degree /// (NURBS Book §5.2); empty when that fails. fn bezier_pieces(p: usize, knots: &[f64], points: &[[f64; 4]]) -> Vec<([f64; 2], Vec<[f64; 4]>)> { diff --git a/crates/geom/src/hlr/mod.rs b/crates/geom/src/hlr/mod.rs index 8023c914f..764fc524b 100644 --- a/crates/geom/src/hlr/mod.rs +++ b/crates/geom/src/hlr/mod.rs @@ -4,8 +4,9 @@ //! trimmed faces. Every piece is visible, hidden or explicitly uncertain; nothing is guessed. //! //! Supported: planes, and cylinders, cones, spheres and tori whether stored as analytic records, -//! revolutions of lines and circles or spline patches (recognised to 1e-9 relative and then -//! trimmed and intersected in their own chart). Other spline and revolution faces are freeform: +//! rigidly placed revolutions of lines and circles or spline patches (recognised to 1e-9 relative +//! and then trimmed and intersected in their own chart). Other spline and rigidly placed revolution +//! faces are freeform: //! unless [`Options::freeform`] is set they are listed in [`Drawing::unsupported`], their //! silhouettes are not drawn and anything they could hide is reported uncertain. //! @@ -18,12 +19,13 @@ mod silhouette; pub(crate) mod surface; mod trim; +use crate::prelude::*; use serde::Serialize; -use crate::brep::Brep; use crate::section::CurveAccuracy; -use crate::{Seg2, Vec2, Vec3}; use curve::{C3, as_circle}; +use solidcore_record::brep::Brep; +use solidcore_record::{Seg2, Vec2, Vec3}; use surface::{Analytic, Hit, S3}; use trim::Trim; @@ -191,7 +193,7 @@ pub fn prepare_cancellable(b: &Brep, opts: &Options, cancel: &dyn Fn() -> bool) if !(1..=MAX_TRIM_SAMPLES).contains(&opts.trim_samples) { return Err(HlrError::Invalid("trim samples")); } - b.validate().map_err(|_| HlrError::Invalid("portable B-rep"))?; + crate::brep::check::validate(b).map_err(|_| HlrError::Invalid("portable B-rep"))?; // Work on the body moved to its own centre: rounding in ray and inversion formulas grows // with the coordinates, and a part may be modelled far from the origin (W05a finding 7). let offset = anchor(b); @@ -200,149 +202,147 @@ pub fn prepare_cancellable(b: &Brep, opts: &Options, cancel: &dyn Fn() -> bool) let mut edges = Vec::new(); let mut faces = Vec::new(); let mut report = PrepareReport::default(); - for shell in &b.shells { - let base_face = faces.len(); - let mut curves = Vec::with_capacity(shell.edges.len()); - for (ei, e) in shell.edges.iter().enumerate() { - if ei % 256 == 0 && cancel() { - return Err(HlrError::Cancelled); - } - let (c, acc) = C3::new(&e.curve)?; - let record = match &e.curve { - crate::brep::Curve::Line { .. } => "line", - crate::brep::Curve::CircleArc { .. } => "circle_arc", - crate::brep::Curve::EllipseArc { .. } => "ellipse_arc", - crate::brep::Curve::Polyline { .. } => "polyline", - crate::brep::Curve::Spline { .. } => "spline", - crate::brep::Curve::RationalSpline { .. } => "rational_spline", - crate::brep::Curve::Intersection { .. } => "intersection", - crate::brep::Curve::SurfaceIntersection { .. } => "surface_intersection", - }; - let shape = if matches!(c, C3::Line { .. }) { - "line" - } else if as_circle(&c, 1e-9).is_some() { - "circle" - } else { - "other" - }; - *report.curves.entry(format!("{record}/{shape}")).or_insert(0) += 1; - curves.push((c, acc)); + let mut curves = Vec::with_capacity(b.edges.len()); + for (ei, e) in b.edges.iter().enumerate() { + if ei % 256 == 0 && cancel() { + return Err(HlrError::Cancelled); } - let local_curves: Vec = curves.iter().map(|(c, _)| c.clone()).collect(); - let mut users: Vec> = vec![Vec::new(); shell.edges.len()]; - for (fi, f) in shell.faces.iter().enumerate() { - if cancel() { - return Err(HlrError::Cancelled); - } - let mut surface = S3::new(&f.surface)?; - // A flat spline patch is a plane: trimmed and intersected as one. - if let Some(plane) = surface.flat(1e-9) { - surface = plane; - } - let analytic = surface.analytic(1e-9); - // Trim and intersect recognised spline surfaces in their own analytic chart. - if matches!(surface, S3::Nurbs(_)) { - let axis = match analytic { - Analytic::Cylinder { p, a, .. } => Some((p, a)), - Analytic::Cone { apex, a, .. } => Some((apex, a)), - _ => None, - }; - let mut h = [0., 0.]; - if let Some((p, a)) = axis { - let along = f.loops.iter().flatten().filter_map(|u| local_curves.get(u.edge as usize)).flat_map(|c| { - let [t0, t1] = c.domain(); - (0..=64).map(move |i| c.at(t0 + (t1 - t0) * i as f64 / 64.)) - }); - let (lo, hi) = along.fold((f64::MAX, f64::MIN), |(lo, hi), q| ((q - p).dot(a).min(lo), (q - p).dot(a).max(hi))); - // Generous: the chart only has to contain the face; the trim bounds it exactly. - let pad = 0.01 * (hi - lo).abs() + 1e-6; - h = [lo - pad, hi + pad]; - } - let toward = match analytic { - Analytic::Sphere { c, .. } => { - let pts: Vec = f - .loops - .iter() - .flatten() - .filter_map(|u| local_curves.get(u.edge as usize)) - .map(|c| c.at(0.5 * (c.domain()[0] + c.domain()[1]))) - .collect(); - let n = pts.len().max(1) as f64; - pts.iter().fold(Vec3::ZERO, |acc, p| acc + *p) / n - c - } - _ => Vec3::ZERO, - }; - if let Some(chart) = S3::from_analytic(&analytic, h, toward) { - surface = chart; - } - } - *report.surfaces.entry(analytic_name(&analytic).to_string()).or_insert(0) += 1; - let trim = trim::build(f, &local_curves, &surface, opts.trim_samples); - if let Some(why) = trim.unsupported { - report.unsupported_trims.push((base_face + fi, why.to_string())); - } - report.max_trim_chord = report.max_trim_chord.max(trim.chord_error); - let (mut lo, mut hi) = (trim.lo, trim.hi); - // Curved faces can bulge past their boundary: bound them by the whole surface's - // guaranteed box (spline hull, turned profile), clipped to nothing tighter. - if !matches!(surface, S3::Plane { .. }) - && let Some((blo, bhi)) = surface.bound() - { - lo = lo.min(blo); - hi = hi.max(bhi); - } - // Every face is padded, planes too: a plane record and its edges may disagree by - // rounding, and a box flat along the normal would cull the plane's own hit. Rounding - // grows with where the body was modelled (its offset), not with the face's size. - let pad = (hi - lo).len() * 1e-6 + 1e-12 * offset.x.abs().max(offset.y.abs()).max(offset.z.abs()); - lo -= Vec3::new(pad, pad, pad); - hi += Vec3::new(pad, pad, pad); - for u in f.loops.iter().flatten() { - if let Some(list) = users.get_mut(u.edge as usize) { - list.push(base_face + fi); - } - } - let freeform = matches!(analytic, Analytic::Other); - if freeform { - report.freeform_faces.push(base_face + fi); - } - faces.push(FaceData { surface, analytic, group: Vec::new(), trim, lo, hi, freeform }); + let (c, acc) = C3::of_edge(e)?; + let record = match &e.curve { + solidcore_record::brep::Curve::Line { .. } => "line", + solidcore_record::brep::Curve::Circle { .. } => "circle_arc", + solidcore_record::brep::Curve::Ellipse { .. } => "ellipse_arc", + solidcore_record::brep::Curve::Polyline { .. } => "polyline", + solidcore_record::brep::Curve::Spline { .. } => "spline", + solidcore_record::brep::Curve::RationalSpline { .. } => "rational_spline", + // Only one with a spline to follow gets here: what was an `intersection` record. + solidcore_record::brep::Curve::SurfaceIntersection { .. } => "intersection", + }; + let shape = if matches!(c, C3::Line { .. }) { + "line" + } else if as_circle(&c, 1e-9).is_some() { + "circle" + } else { + "other" + }; + *report.curves.entry(format!("{record}/{shape}")).or_insert(0) += 1; + curves.push((c, acc)); + } + let local_curves: Vec = curves.iter().map(|(c, _)| c.clone()).collect(); + let mut users: Vec> = vec![Vec::new(); b.edges.len()]; + // Faces and edges by their numbers in the record. Validation puts every face in a shell; its + // loops are stored the same whichever side a shell uses, and hidden lines look at both, so the + // shells' orientation does not come into it (a face two shells share is one face). An edge no + // face uses (a wire) is drawn like any other. + for (fi, f) in b.faces.iter().enumerate() { + if cancel() { + return Err(HlrError::Cancelled); } - for (ei, (c, acc)) in curves.into_iter().enumerate() { - let list = users.get(ei).cloned().unwrap_or_default(); - let mut distinct = list.clone(); - distinct.sort_unstable(); - distinct.dedup(); - let kind = if list.len() >= 2 && distinct.len() == 1 { - EdgeKind::Seam - } else if let [f1, f2] = distinct.as_slice() { - let [t0, t1] = c.domain(); - let normals_parallel = [0.25, 0.5, 0.75].iter().all(|k| { - let m = c.at(t0 + (t1 - t0) * k); - let n = |f: usize| faces.get(f).and_then(|fd: &FaceData| fd.surface.inverse(m, None).and_then(|uv| fd.surface.normal(uv))); - n(*f1).zip(n(*f2)).is_some_and(|(a, b)| a.cross(b).len() < 1e-6) + let mut surface = S3::of_face(f)?; + // A flat spline patch is a plane: trimmed and intersected as one. + if let Some(plane) = surface.flat(1e-9) { + surface = plane; + } + let analytic = surface.analytic(1e-9); + // Trim and intersect recognised spline surfaces in their own analytic chart. + if matches!(surface, S3::Nurbs(_)) { + let axis = match analytic { + Analytic::Cylinder { p, a, .. } => Some((p, a)), + Analytic::Cone { apex, a, .. } => Some((apex, a)), + _ => None, + }; + let mut h = [0., 0.]; + if let Some((p, a)) = axis { + let along = trim::uses(f).filter_map(|u| local_curves.get(u.edge as usize)).flat_map(|c| { + let [t0, t1] = c.domain(); + (0..=64).map(move |i| c.at(t0 + (t1 - t0) * i as f64 / 64.)) }); - let same_surface = match (faces.get(*f1).map(|f: &FaceData| f.analytic), faces.get(*f2).map(|f: &FaceData| f.analytic)) { - (Some(a), Some(b)) => same_analytic(&a, &b, 1e-9), - _ => false, - }; - if same_surface { - EdgeKind::Seam - } else if normals_parallel { - EdgeKind::Tangent - } else { - EdgeKind::Sharp + let (lo, hi) = along.fold((f64::MAX, f64::MIN), |(lo, hi), q| ((q - p).dot(a).min(lo), (q - p).dot(a).max(hi))); + // Generous: the chart only has to contain the face; the trim bounds it exactly. + let pad = 0.01 * (hi - lo).abs() + 1e-6; + h = [lo - pad, hi + pad]; + } + let toward = match analytic { + Analytic::Sphere { c, .. } => { + let pts: Vec = trim::uses(f) + .filter_map(|u| local_curves.get(u.edge as usize)) + .map(|c| c.at(0.5 * (c.domain()[0] + c.domain()[1]))) + .collect(); + let n = pts.len().max(1) as f64; + pts.iter().fold(Vec3::ZERO, |acc, p| acc + *p) / n - c } + _ => Vec3::ZERO, + }; + if let Some(chart) = S3::from_analytic(&analytic, h, toward) { + surface = chart; + } + } + *report.surfaces.entry(analytic_name(&analytic).to_string()).or_insert(0) += 1; + let trim = trim::build(f, &local_curves, &surface, opts.trim_samples); + if let Some(why) = trim.unsupported { + report.unsupported_trims.push((fi, why.to_string())); + } + report.max_trim_chord = report.max_trim_chord.max(trim.chord_error); + let (mut lo, mut hi) = (trim.lo, trim.hi); + // Curved faces can bulge past their boundary: bound them by the whole surface's + // guaranteed box (spline hull, turned profile), clipped to nothing tighter. + if !matches!(surface, S3::Plane { .. }) + && let Some((blo, bhi)) = surface.bound() + { + lo = lo.min(blo); + hi = hi.max(bhi); + } + // Every face is padded, planes too: a plane record and its edges may disagree by + // rounding, and a box flat along the normal would cull the plane's own hit. Rounding + // grows with where the body was modelled (its offset), not with the face's size. + let pad = (hi - lo).len() * 1e-6 + 1e-12 * offset.x.abs().max(offset.y.abs()).max(offset.z.abs()); + lo -= Vec3::new(pad, pad, pad); + hi += Vec3::new(pad, pad, pad); + for u in trim::uses(f) { + if let Some(list) = users.get_mut(u.edge as usize) { + list.push(fi); + } + } + let freeform = matches!(analytic, Analytic::Other); + if freeform { + report.freeform_faces.push(fi); + } + faces.push(FaceData { surface, analytic, group: Vec::new(), trim, lo, hi, freeform }); + } + for (ei, (c, acc)) in curves.into_iter().enumerate() { + let list = users.get(ei).cloned().unwrap_or_default(); + let mut distinct = list.clone(); + distinct.sort_unstable(); + distinct.dedup(); + let kind = if list.len() >= 2 && distinct.len() == 1 { + EdgeKind::Seam + } else if let [f1, f2] = distinct.as_slice() { + let [t0, t1] = c.domain(); + let normals_parallel = [0.25, 0.5, 0.75].iter().all(|k| { + let m = c.at(t0 + (t1 - t0) * k); + let n = |f: usize| faces.get(f).and_then(|fd: &FaceData| fd.surface.inverse(m, None).and_then(|uv| fd.surface.normal(uv))); + n(*f1).zip(n(*f2)).is_some_and(|(a, b)| a.cross(b).len() < 1e-6) + }); + let same_surface = match (faces.get(*f1).map(|f: &FaceData| f.analytic), faces.get(*f2).map(|f: &FaceData| f.analytic)) { + (Some(a), Some(b)) => same_analytic(&a, &b, 1e-9), + _ => false, + }; + if same_surface { + EdgeKind::Seam + } else if normals_parallel { + EdgeKind::Tangent } else { EdgeKind::Sharp - }; - match kind { - EdgeKind::Tangent => report.tangent_edges += 1, - EdgeKind::Seam => report.seam_edges += 1, - EdgeKind::Sharp => {} } - edges.push(EdgeData { curve: c, acc, faces: list, kind }); + } else { + EdgeKind::Sharp + }; + match kind { + EdgeKind::Tangent => report.tangent_edges += 1, + EdgeKind::Seam => report.seam_edges += 1, + EdgeKind::Sharp => {} } + edges.push(EdgeData { curve: c, acc, faces: list, kind }); } // Faces on one quadric or torus. Only surfaces of one kind whose size (radius, half angle, // major radius) agrees to the tolerance can match, so each face is compared with the faces @@ -394,93 +394,23 @@ pub fn prepare_cancellable(b: &Brep, opts: &Options, cancel: &dyn Fn() -> bool) Ok(Prepared { edges, faces, offset, lo, hi, report }) } -/// The centre of the body's vertices' box (of its faces' reference points when it has no -/// vertices, a sphere without edges say). +/// The centre of the body's vertices' box (a validated body has vertices: every face has an edge +/// loop, every other shell an edge or a vertex). fn anchor(b: &Brep) -> Vec3 { - use crate::brep::Surface; - let v3 = |p: &[f64; 3]| Vec3::new(p[0], p[1], p[2]); - let mut pts: Vec = b.shells.iter().flat_map(|s| s.vertices.iter().map(v3)).collect(); - if pts.is_empty() { - pts = b - .shells - .iter() - .flat_map(|s| s.faces.iter()) - .filter_map(|f| match &f.surface { - Surface::Plane { origin, .. } | Surface::PlaneThrough { origin, .. } | Surface::Revolution { origin, .. } => Some(v3(origin)), - Surface::PlacedRevolution { origin, matrix: [x, y, z, w], .. } => { - let column = |c: &[f64; 4]| Vec3::new(c[0], c[1], c[2]); - Some(column(x) * origin[0] + column(y) * origin[1] + column(z) * origin[2] + column(w)) - } - Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } | Surface::Sphere { frame, .. } | Surface::Torus { frame, .. } => { - Some(v3(&frame.origin)) - } - Surface::Spline { points, .. } => points.first().and_then(|r| r.first()).map(v3), - Surface::RationalSpline { homogeneous, .. } => { - homogeneous.first().and_then(|r| r.first()).filter(|h| h[3] != 0.).map(|h| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])) - } - }) - .collect(); - } - let Some(first) = pts.first().copied() else { return Vec3::ZERO }; - let (lo, hi) = pts.iter().fold((first, first), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + let mut pts = b.vertices.iter().map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])); + let Some(first) = pts.next() else { return Vec3::ZERO }; + let (lo, hi) = pts.fold((first, first), |(lo, hi), p| (lo.min(p), hi.max(p))); let c = (lo + hi) * 0.5; if c.is_finite() { c } else { Vec3::ZERO } } -/// The body's records with every position moved by `-d`. +/// The body's records with every position moved by `-d`: points, control points and NURBS forms, +/// a placed revolution through its matrix; regions, parameters and pcurves as they are. fn shifted(b: &Brep, d: Vec3) -> Brep { - use crate::brep::{Curve, Surface}; - fn point(p: &mut [f64; 3], d: Vec3) { - p[0] -= d.x; - p[1] -= d.y; - p[2] -= d.z; - } - fn weighted(h: &mut [f64; 4], d: Vec3) { - h[0] -= d.x * h[3]; - h[1] -= d.y * h[3]; - h[2] -= d.z * h[3]; - } - fn curve(c: &mut Curve, d: Vec3) { - match c { - Curve::Line { start, end } => { - point(start, d); - point(end, d); - } - Curve::CircleArc { frame, .. } | Curve::EllipseArc { frame, .. } => point(&mut frame.origin, d), - Curve::Polyline { points } | Curve::Spline { points, .. } | Curve::Intersection { points, .. } => { - points.iter_mut().for_each(|p| point(p, d)) - } - Curve::RationalSpline { homogeneous, .. } => homogeneous.iter_mut().for_each(|h| weighted(h, d)), - Curve::SurfaceIntersection { surfaces, leader, .. } => { - surfaces.iter_mut().for_each(|s| surface(s, d)); - curve(leader, d); - } - } - } - fn surface(s: &mut Surface, d: Vec3) { - match s { - Surface::Plane { origin, .. } => point(origin, d), - Surface::PlaneThrough { origin, u_point, v_point } => [origin, u_point, v_point].into_iter().for_each(|p| point(p, d)), - Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } | Surface::Sphere { frame, .. } | Surface::Torus { frame, .. } => { - point(&mut frame.origin, d) - } - Surface::Spline { points, .. } => points.iter_mut().flatten().for_each(|p| point(p, d)), - Surface::RationalSpline { homogeneous, .. } => homogeneous.iter_mut().flatten().for_each(|h| weighted(h, d)), - Surface::Revolution { profile, origin, .. } => { - curve(profile, d); - point(origin, d); - } - // The placement's last column carries its translation (and the homogeneous weight). - Surface::PlacedRevolution { matrix: [.., w], .. } => weighted(w, d), - } - } - let mut out = b.clone(); - for s in &mut out.shells { - s.vertices.iter_mut().for_each(|p| point(p, d)); - s.edges.iter_mut().for_each(|e| curve(&mut e.curve, d)); - s.faces.iter_mut().for_each(|f| surface(&mut f.surface, d)); - } - out + crate::brep::placement::moved( + b, + &crate::brep::placement::Rigid { rotation: [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], translation: [-d.x, -d.y, -d.z] }, + ) } #[derive(Clone, Copy, Debug)] diff --git a/crates/geom/src/hlr/silhouette.rs b/crates/geom/src/hlr/silhouette.rs index af14e1332..9b60866b7 100644 --- a/crates/geom/src/hlr/silhouette.rs +++ b/crates/geom/src/hlr/silhouette.rs @@ -6,8 +6,9 @@ use super::curve::C3; use super::surface::{Analytic, S3}; use super::trim::Trim; -use crate::Vec3; +use crate::prelude::*; use crate::section::CurveAccuracy; +use solidcore_record::Vec3; const TAU: f64 = std::f64::consts::TAU; diff --git a/crates/geom/src/hlr/surface.rs b/crates/geom/src/hlr/surface.rs index d8c3dfc76..574952e1b 100644 --- a/crates/geom/src/hlr/surface.rs +++ b/crates/geom/src/hlr/surface.rs @@ -1,12 +1,16 @@ //! Surfaces of portable B-rep faces with a parameter chart, inversion, ray intersection and //! analytic recognition. Planes are closed form; revolutions are reduced to their 2D profile; -//! spline surfaces use Newton iterations seeded from a sample grid. +//! spline surfaces use Newton iterations seeded from a sample grid. Records' surfaces are unbounded: +//! a cylinder, cone, sphere, torus or revolution gets its chart's bounds from its face. use super::HlrError; use super::curve::{C3, as_circle, frame_axes, v3}; -use crate::Vec3; -use crate::brep::{Frame, Surface}; +use crate::brep::eval::SurfaceEval; +use crate::brep::{form, placement::Rigid}; use crate::bspline::{HPoint, NurbsSurface}; +use crate::prelude::*; +use solidcore_record::Vec3; +use solidcore_record::brep::{Curve, Face, Frame, Surface}; const TAU: f64 = std::f64::consts::TAU; @@ -116,8 +120,11 @@ fn perp(a: Vec3) -> Vec3 { } impl S3 { - pub fn new(s: &Surface) -> Result { - Ok(match s { + /// The chart of a face: its surface, in its own parameters where it is a plane or a spline + /// and in angle and height (angle and angle) where it is a cylinder, cone, sphere or torus, + /// over the part its NURBS form spans ([`Face::domain`]). + pub fn of_face(face: &Face) -> Result { + Ok(match &face.surface { Surface::Plane { origin, u_axis, v_axis } => { let (u, v) = (v3(*u_axis), v3(*v_axis)); let n = u.cross(v).normalized().ok_or(HlrError::Unsupported("degenerate plane"))?; @@ -130,39 +137,45 @@ impl S3 { let n = u.cross(v).normalized().ok_or(HlrError::Unsupported("degenerate plane"))?; S3::Plane { o, u, v, n } } - // A revolution mapped by an affine placement, which may scale it unevenly. - Surface::PlacedRevolution { .. } => return Err(HlrError::Unsupported("placed revolution surface")), Surface::Spline { u_knots, v_knots, points } => { let h = points.iter().map(|r| r.iter().map(|p| [p[0], p[1], p[2], 1.]).collect()).collect::>>(); S3::Nurbs(Box::new(Nurbs::new(u_knots, v_knots, &h)?)) } Surface::RationalSpline { u_knots, v_knots, homogeneous } => S3::Nurbs(Box::new(Nurbs::new(u_knots, v_knots, homogeneous)?)), - Surface::Revolution { profile, origin, axis, angle } => { - let (c, _) = C3::new(profile)?; - S3::Rev(Box::new(Rev::new(v3(*origin), v3(*axis), None, c, *angle)?)) - } - Surface::Cylinder { frame, radius, angle, height } => { + Surface::PlacedRevolution { .. } => placed_revolution(face)?, + label => S3::bounded(label, form_box(face, label)?)?, + }) + } + + /// A cylinder, cone, sphere or torus over `[angle, along]`: `along` the height on the frame's + /// axis of a cylinder or cone, the latitude of a sphere, a torus's tube angle from the frame + /// (its tube start counted in). + pub fn bounded(s: &Surface, [angle, along]: [[f64; 2]; 2]) -> Result { + let rev = match s { + Surface::Cylinder { frame, radius } => { let (o, x, _, z) = axes(frame); - let line = C3::Line { a: o + x * *radius + z * height[0], b: o + x * *radius + z * height[1] }; - S3::Rev(Box::new(Rev::new(o, z, Some(x), line, *angle)?)) + let line = C3::Line { a: o + x * *radius + z * along[0], b: o + x * *radius + z * along[1] }; + Rev::new(o, z, Some(x), line, angle)? } - Surface::Cone { frame, radius_at_origin, half_angle, angle, height } => { + Surface::Cone { frame, radius_at_origin, half_angle } => { let (o, x, _, z) = axes(frame); let r = |h: f64| radius_at_origin + h * half_angle.tan(); - let line = C3::Line { a: o + x * r(height[0]) + z * height[0], b: o + x * r(height[1]) + z * height[1] }; - S3::Rev(Box::new(Rev::new(o, z, Some(x), line, *angle)?)) + let line = C3::Line { a: o + x * r(along[0]) + z * along[0], b: o + x * r(along[1]) + z * along[1] }; + Rev::new(o, z, Some(x), line, angle)? } - Surface::Sphere { frame, radius, longitude, latitude } => { + Surface::Sphere { frame, radius } => { let (o, x, _, z) = axes(frame); - let arc = C3::Arc { o, x, y: z, r: [*radius, *radius], range: *latitude }; - S3::Rev(Box::new(Rev::new(o, z, Some(x), arc, *longitude)?)) + let arc = C3::Arc { o, x, y: z, r: [*radius, *radius], range: along }; + Rev::new(o, z, Some(x), arc, angle)? } - Surface::Torus { frame, major_radius, minor_radius, longitude, meridian } => { + Surface::Torus { frame, major_radius, minor_radius, .. } => { let (o, x, _, z) = axes(frame); - let arc = C3::Arc { o: o + x * *major_radius, x, y: z, r: [*minor_radius, *minor_radius], range: *meridian }; - S3::Rev(Box::new(Rev::new(o, z, Some(x), arc, *longitude)?)) + let arc = C3::Arc { o: o + x * *major_radius, x, y: z, r: [*minor_radius, *minor_radius], range: along }; + Rev::new(o, z, Some(x), arc, angle)? } - }) + _ => return Err(HlrError::Unsupported("surface chart")), + }; + Ok(S3::Rev(Box::new(rev))) } /// The recognised quadric or torus as a revolution chart: closed-form inversion and exact @@ -525,6 +538,123 @@ pub(crate) fn torus_roots(w: Vec3, d: Vec3, a: Vec3, big: f64, small: f64, range out } +/// Steps per direction when a face's NURBS form is read back onto its label: along a direction +/// that turns (at most a turn, in rational quarter arcs) each step stays well within half a turn. +const FORM_STEPS: usize = 16; + +/// The angle `x` on the turn nearest `near`. +fn unwrapped(x: f64, near: f64) -> f64 { + x + TAU * ((near - x) / TAU).round() +} + +/// A cylinder, cone, sphere or torus face's box on its label ([`S3::bounded`]): where its form's +/// points over its domain lie on the label's frame, whichever way round the form runs. +fn form_box(face: &Face, label: &Surface) -> Result<[[f64; 2]; 2], HlrError> { + let frame = match label { + Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } | Surface::Sphere { frame, .. } | Surface::Torus { frame, .. } => frame, + _ => return Err(HlrError::Unsupported("surface chart")), + }; + let (o, x, y, z) = axes(frame); + let along = |w: Vec3, rho: f64| match label { + Surface::Sphere { .. } => w.dot(z).atan2(rho), + Surface::Torus { major_radius, .. } => w.dot(z).atan2(rho - major_radius), + _ => w.dot(z), + }; + let turns = matches!(label, Surface::Torus { .. }); + let (angle, mut second) = sampled_box(face, turns, &|p| { + let w = p - o; + let (a, b) = (w.dot(x), w.dot(y)); + let rho = a.hypot(b); + [rho, b.atan2(a), along(w, rho)] + })?; + if !(second[0] < second[1]) { + return Err(HlrError::Invalid("surface form domain")); + } + if turns && second[1] - second[0] >= TAU - 1e-9 { + second[1] = second[0] + TAU; + } + Ok([angle, second]) +} + +/// The range of the angle about the axis and of a second coordinate over a form's points on a grid +/// of the face's domain; `at` gives a point's distance from the axis, angle and second coordinate, +/// the second an angle too when `turns`. Angles are unwrapped from point to point, row after row, so +/// a face that goes round comes to one turn. On the axis (a pole, an apex) there is no angle. +fn sampled_box(face: &Face, turns: bool, at: &dyn Fn(Vec3) -> [f64; 3]) -> Result<([f64; 2], [f64; 2]), HlrError> { + let form = face.nurbs.as_ref().ok_or(HlrError::Invalid("analytic surface without its form"))?; + let eval = SurfaceEval::new(form).map_err(|_| HlrError::Invalid("surface form"))?; + let [[u0, u1], [v0, v1]] = face.domain; + let step = |a: f64, b: f64, k: usize| a + (b - a) * k as f64 / FORM_STEPS as f64; + let mut samples = Vec::with_capacity((FORM_STEPS + 1) * (FORM_STEPS + 1)); + for j in 0..=FORM_STEPS { + for i in 0..=FORM_STEPS { + let p = eval.point([step(u0, u1, i), step(v0, v1, j)]).filter(|p| p.is_finite()).ok_or(HlrError::Invalid("surface form"))?; + samples.push(at(p)); + } + } + let widest = samples.iter().fold(0f64, |m, s| m.max(s[0])); + let (mut angle, mut second) = ([f64::INFINITY, f64::NEG_INFINITY], [f64::INFINITY, f64::NEG_INFINITY]); + // Each row starts next to the start of the one before. + let (mut row_a, mut row_s): (Option, Option) = (None, None); + for row in samples.chunks(FORM_STEPS + 1) { + let (mut last_a, mut last_s) = (row_a, row_s); + for (i, &[rho, a, s]) in row.iter().enumerate() { + if rho > 1e-6 * widest { + let a = last_a.map_or(a, |l| unwrapped(a, l)); + angle = [angle[0].min(a), angle[1].max(a)]; + last_a = Some(a); + if i == 0 || row_a.is_none() { + row_a = Some(a); + } + } + let s = if turns { last_s.map_or(s, |l| unwrapped(s, l)) } else { s }; + second = [second[0].min(s), second[1].max(s)]; + last_s = Some(s); + if i == 0 { + row_s = Some(s); + } + } + } + if !(angle[0] < angle[1]) { + return Err(HlrError::Invalid("surface form domain")); + } + Ok((angle, second)) +} + +/// A placed revolution's chart. Its placement must be rigid: then it is a revolution of the placed +/// profile about the placed axis. Any other (which may scale it unevenly) is refused. The profile's +/// range is `domain` along it: its own parameter, a conic's on its form's quarter grid. +fn placed_revolution(face: &Face) -> Result { + let Surface::PlacedRevolution { profile, origin, axis, matrix, forward } = &face.surface else { + return Err(HlrError::Unsupported("surface chart")); + }; + let Some(rigid) = Rigid::of_matrix(matrix) else { return Err(HlrError::Unsupported("placed revolution surface")) }; + let along = if *forward { face.domain[0] } else { face.domain[1] }; + let range = match profile.as_ref() { + Curve::Circle { .. } | Curve::Ellipse { .. } => [form::angle(along[0]), form::angle(along[1])], + _ => along, + }; + if matches!(profile.as_ref(), Curve::Circle { .. } | Curve::Ellipse { .. }) && !(range[1] - range[0] <= TAU * (1. + 1e-9)) { + return Err(HlrError::Invalid("revolution profile range")); + } + let rows = rigid.rotation.map(v3); + let direction = |d: Vec3| Vec3::new(rows[0].dot(d), rows[1].dot(d), rows[2].dot(d)); + let point = |p: Vec3| direction(p) + v3(rigid.translation); + let curve = C3::bounded(profile, range)?.placed(&point, &direction)?; + let (o, a) = (point(v3(*origin)), direction(v3(*axis)).normalized().ok_or(HlrError::Unsupported("zero revolution axis"))?); + let [t0, _] = curve.domain(); + let start = curve.at(t0) - o; + let e1 = (start - a * start.dot(a)).normalized().unwrap_or_else(|| perp(a)); + let e2 = a.cross(e1); + let (angle, _) = sampled_box(face, false, &|p| { + let w = p - o; + let h = w.dot(a); + let radial = w - a * h; + [radial.len(), radial.dot(e2).atan2(radial.dot(e1)), h] + })?; + Ok(S3::Rev(Box::new(Rev::new(o, a, Some(e1), curve, angle)?))) +} + fn axes(f: &Frame) -> (Vec3, Vec3, Vec3, Vec3) { let (o, x, y) = frame_axes(f); (o, x, y, x.cross(y)) @@ -828,12 +958,9 @@ impl Rev { let r = radial.len(); let theta = if r > 1e-12 * (1. + self.rmax) { radial.dot(self.e2).atan2(radial.dot(self.e1)) } else { hint.map_or(0., |u| u[0]) }; let (s, _) = self.closest([r, h]); - let mut t = theta; - if self.theta[1] - self.theta[0] >= TAU - 1e-9 { - t = t.rem_euclid(TAU); - } else if t < self.theta[0] { - t += TAU; - } + // Of a part of a turn, the copy nearest its middle: an end rounds either way. + let t = + if self.theta[1] - self.theta[0] >= TAU - 1e-9 { theta.rem_euclid(TAU) } else { unwrapped(theta, 0.5 * (self.theta[0] + self.theta[1])) }; Some([t, s]) } diff --git a/crates/geom/src/hlr/trim.rs b/crates/geom/src/hlr/trim.rs index c416d3319..a67667d76 100644 --- a/crates/geom/src/hlr/trim.rs +++ b/crates/geom/src/hlr/trim.rs @@ -5,8 +5,10 @@ use super::curve::C3; use super::surface::S3; -use crate::Vec3; -use crate::brep::Face; +use crate::brep::eval::SurfaceEval; +use crate::prelude::*; +use solidcore_record::Vec3; +use solidcore_record::brep::{Face, Loop, OrientedEdge}; #[derive(Clone, Debug)] pub(crate) struct Trim { @@ -159,6 +161,27 @@ fn index(segs: &[([f64; 2], [f64; 2])], period: [Option; 2], r: [f64; 2]) - Index { copies, vcross, buckets, v0, dv } } +/// Every use of an edge in a face's loops. +pub(crate) fn uses(face: &Face) -> impl Iterator { + face.loops.iter().flat_map(|l| match l { + Loop::Edges { edges } => edges.as_slice(), + Loop::Vertex { .. } => &[], + }) +} + +/// +1 where the chart's normal is the natural normal of the face's parameters, which its loops +/// are stored against, and -1 where it is the other side (a form turned against its label, a +/// recognised patch's own chart): the side the face is on, walking its loops in the chart. +fn loops_left(face: &Face, surface: &S3) -> f64 { + let [[u0, u1], [v0, v1]] = face.domain; + let natural = SurfaceEval::new(face.parameters()).ok().and_then(|s| s.derivs(0.5 * (u0 + u1), 0.5 * (v0 + v1))); + let along = natural.and_then(|(p, su, sv)| { + let chart = surface.inverse(p, None).and_then(|uv| surface.normal(uv))?; + Some(su.cross(sv).dot(chart)) + }); + if along.is_some_and(|a| a < 0.) { -1. } else { 1. } +} + fn lift(x: f64, near: f64, p: Option) -> f64 { match p { Some(p) if p > 0. => x + p * ((near - x) / p).round(), @@ -173,15 +196,17 @@ pub(crate) fn build(face: &Face, edges: &[C3], surface: &S3, per_break: usize) - let mut chords = Vec::new(); let mut chord_error = 0f64; let (mut lo, mut hi) = (Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)); - let mut uses = std::collections::BTreeMap::new(); - for u in face.loops.iter().flatten() { - *uses.entry(u.edge).or_insert(0usize) += 1; + let mut counts = std::collections::BTreeMap::new(); + for u in self::uses(face) { + *counts.entry(u.edge).or_insert(0usize) += 1; } let mut area_u = 0.; // -loop integral of v du let mut area_v = 0.; // loop integral of u dv let mut wraps = [false; 2]; let mut unsupported = None; for lp in &face.loops { + // A vertex loop (a pole) bounds nothing in the chart. + let Loop::Edges { edges: lp } = lp else { continue }; let mut pts: Vec<([f64; 2], bool)> = Vec::new(); let mut hint: Option<[f64; 2]> = None; for u in lp { @@ -189,7 +214,7 @@ pub(crate) fn build(face: &Face, edges: &[C3], surface: &S3, per_break: usize) - unsupported = Some("edge reference"); continue; }; - let is_seam = uses.get(&u.edge).copied().unwrap_or(0) > 1; + let is_seam = counts.get(&u.edge).copied().unwrap_or(0) > 1; let mut ts = Vec::new(); let b = c.breaks(); for w in b.windows(2) { @@ -253,11 +278,11 @@ pub(crate) fn build(face: &Face, edges: &[C3], surface: &S3, per_break: usize) - }; // Loops that wind once around a periodic direction without coming back (a hemisphere's // equator) close against the chart's own edge, so their area depends on where the chart - // starts: there the face is taken on the loops' left (the B-rep convention), and below the - // side within the surface's domain wins either way. + // starts: there the face is taken on the loops' left seen from the natural normal (the B-rep + // convention), and below the side within the surface's domain wins either way. let net = segs.iter().fold([0f64; 2], |n, (a, b)| [n[0] + b[0] - a[0], n[1] + b[1] - a[1]]); let open = (0..2).any(|k| period[k].is_some_and(|p| net[k].abs() > 0.5 * p)); - let sigma = if open { 1. } else { area.signum() }; + let sigma = if open { loops_left(face, surface) } else { area.signum() }; let dom = surface.domain(); // Inside point: beside the longest non-seam segment, on the face's side. let mut inside = None; diff --git a/crates/geom/src/hlr_tests.rs b/crates/geom/src/hlr_tests.rs index d56729e3d..e04ab6631 100644 --- a/crates/geom/src/hlr_tests.rs +++ b/crates/geom/src/hlr_tests.rs @@ -1,5 +1,358 @@ use super::*; -use crate::brep::{Brep, Curve, Edge, EdgeUse, Face, Shell, Surface}; +use crate::brep; +use solidcore_record::brep as rec; + +// The fixtures below write a body as data: shells each with their own vertices, edges and faces, +// curves and surfaces carrying their bounds, edges numbered as the fixture likes. `Brep::record` +// makes the portable record of it, which `prepare` here hands to the real one. + +#[derive(Clone)] +struct Brep { + version: u32, + shells: Vec, +} + +#[derive(Clone)] +struct Shell { + vertices: Vec<[f64; 3]>, + edges: Vec, + faces: Vec, +} + +#[derive(Clone)] +struct Edge { + vertices: [u32; 2], + curve: Curve, +} + +#[derive(Clone)] +struct Face { + loops: Vec>, + surface: Surface, + forward: bool, +} + +#[derive(Clone, Copy)] +struct EdgeUse { + edge: u32, + forward: bool, +} + +#[derive(Clone)] +enum Curve { + Line { start: [f64; 3], end: [f64; 3] }, + CircleArc { frame: rec::Frame, radius: f64, angle: [f64; 2] }, + Polyline { points: Vec<[f64; 3]> }, + Spline { knots: Vec, points: Vec<[f64; 3]> }, + RationalSpline { knots: Vec, homogeneous: Vec<[f64; 4]> }, + SurfaceIntersection { surfaces: [Box; 2], leader: Box, tolerance: f64 }, +} + +#[derive(Clone)] +enum Surface { + Plane { + origin: [f64; 3], + u_axis: [f64; 3], + v_axis: [f64; 3], + }, + PlaneThrough { + origin: [f64; 3], + u_point: [f64; 3], + v_point: [f64; 3], + }, + Cylinder { + frame: rec::Frame, + radius: f64, + angle: [f64; 2], + height: [f64; 2], + }, + Cone { + frame: rec::Frame, + radius_at_origin: f64, + half_angle: f64, + angle: [f64; 2], + height: [f64; 2], + }, + Sphere { + frame: rec::Frame, + radius: f64, + longitude: [f64; 2], + latitude: [f64; 2], + }, + Torus { + frame: rec::Frame, + major_radius: f64, + minor_radius: f64, + longitude: [f64; 2], + meridian: [f64; 2], + }, + Spline { + u_knots: Vec, + v_knots: Vec, + points: Vec>, + }, + RationalSpline { + u_knots: Vec, + v_knots: Vec, + homogeneous: Vec>, + }, + /// A revolution as far as `angle`, its profile where it stands. + Revolution { + profile: Box, + origin: [f64; 3], + axis: [f64; 3], + angle: [f64; 2], + }, + /// A whole revolution. + PlacedRevolution { + profile: Box, + origin: [f64; 3], + axis: [f64; 3], + matrix: [[f64; 4]; 4], + forward: bool, + }, +} + +const IDENTITY: [[f64; 4]; 4] = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; + +fn range(natural: rec::Natural) -> [f64; 2] { + match natural { + rec::Natural::Range(a, b) => [a, b], + rec::Natural::Periodic => [0., std::f64::consts::TAU], + } +} + +impl Curve { + /// What the curve is, unbounded. + fn label(&self) -> rec::Curve { + match self { + Curve::Line { start, end } => rec::Curve::Line { start: *start, end: *end }, + Curve::CircleArc { frame, radius, .. } => rec::Curve::Circle { frame: frame.clone(), radius: *radius }, + Curve::Polyline { points } => rec::Curve::Polyline { points: points.clone() }, + Curve::Spline { knots, points } => rec::Curve::Spline { knots: knots.clone(), points: points.clone() }, + Curve::RationalSpline { knots, homogeneous } => rec::Curve::RationalSpline { knots: knots.clone(), homogeneous: homogeneous.clone() }, + Curve::SurfaceIntersection { surfaces, leader, tolerance } => rec::Curve::SurfaceIntersection { + surfaces: [Box::new(surfaces[0].label()), Box::new(surfaces[1].label())], + leader: Box::new(leader.label()), + tolerance: *tolerance, + }, + } + } + + /// The curve's parameter range, the whole of it for a profile (a line from `start` to `end`). + fn extent(&self) -> [f64; 2] { + match self { + Curve::Line { .. } => [0., 1.], + Curve::CircleArc { angle, .. } => *angle, + _ => range(self.label().natural()), + } + } + + /// The label, its NURBS form and the interval the edge's parameter runs over. + fn parts(&self) -> (rec::Curve, Option, [f64; 2]) { + let label = self.label(); + match self { + Curve::CircleArc { angle, .. } => { + let (form, interval) = brep::form::curve(&label, *angle).expect("a circle's form"); + (label, Some(form), interval) + } + _ => (label, None, self.extent()), + } + } +} + +impl Surface { + /// What the surface is, unbounded. + fn label(&self) -> rec::Surface { + match self { + Surface::Plane { origin, u_axis, v_axis } => rec::Surface::Plane { origin: *origin, u_axis: *u_axis, v_axis: *v_axis }, + Surface::PlaneThrough { origin, u_point, v_point } => { + rec::Surface::PlaneThrough { origin: *origin, u_point: *u_point, v_point: *v_point } + } + Surface::Cylinder { frame, radius, .. } => rec::Surface::Cylinder { frame: frame.clone(), radius: *radius }, + Surface::Cone { frame, radius_at_origin, half_angle, .. } => { + rec::Surface::Cone { frame: frame.clone(), radius_at_origin: *radius_at_origin, half_angle: *half_angle } + } + Surface::Sphere { frame, radius, .. } => rec::Surface::Sphere { frame: frame.clone(), radius: *radius }, + Surface::Torus { frame, major_radius, minor_radius, .. } => { + rec::Surface::Torus { frame: frame.clone(), major_radius: *major_radius, minor_radius: *minor_radius, tube_start: 0. } + } + Surface::Spline { u_knots, v_knots, points } => { + rec::Surface::Spline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), points: points.clone() } + } + Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + rec::Surface::RationalSpline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), homogeneous: homogeneous.clone() } + } + // A revolution from its profile, u the angle and v along the profile. + Surface::Revolution { profile, origin, axis, .. } => { + rec::Surface::PlacedRevolution { profile: Box::new(profile.label()), origin: *origin, axis: *axis, matrix: IDENTITY, forward: false } + } + Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => rec::Surface::PlacedRevolution { + profile: Box::new(profile.label()), + origin: *origin, + axis: *axis, + matrix: *matrix, + forward: *forward, + }, + } + } + + /// The bounds it carries, on its label. + fn bounds(&self) -> [[f64; 2]; 2] { + let turn = [0., std::f64::consts::TAU]; + match self { + Surface::Cylinder { angle, height, .. } | Surface::Cone { angle, height, .. } => [*angle, *height], + Surface::Sphere { longitude, latitude, .. } => [*longitude, *latitude], + Surface::Torus { longitude, meridian, .. } => [*longitude, *meridian], + Surface::Revolution { profile, angle, .. } => [*angle, profile.extent()], + Surface::PlacedRevolution { profile, forward: true, .. } => [profile.extent(), turn], + Surface::PlacedRevolution { profile, forward: false, .. } => [turn, profile.extent()], + Surface::Spline { .. } | Surface::RationalSpline { .. } => brep::label::surface_natural(&self.label()).map(range), + // Nothing reads a plane's domain; this is around anything a fixture draws on one. + Surface::Plane { .. } | Surface::PlaneThrough { .. } => [[-1e12, 1e12]; 2], + } + } + + /// The label, its NURBS form and the face's domain. + fn parts(&self) -> (rec::Surface, Option, [[f64; 2]; 2]) { + let (label, bounds) = (self.label(), self.bounds()); + match self { + Surface::Plane { .. } | Surface::PlaneThrough { .. } | Surface::Spline { .. } | Surface::RationalSpline { .. } => (label, None, bounds), + _ => { + let (form, domain) = brep::form::surface(&label, bounds).expect("a surface's form"); + (label, Some(form), domain) + } + } + } +} + +impl Brep { + /// The portable record of the fixture, and the fixture's number of each of its edges. Shells, + /// and faces within them, keep their order, so a face keeps its number; edges and vertices come + /// in canonical order, first appearance walking faces, loops and uses. Pcurves carry the edge's + /// interval, which `Brep::validate` checks; neither it nor hidden lines read their points, as + /// hidden lines trace trims from the edges in 3D, so these are not on the surface. + fn record(&self) -> (rec::Brep, Vec) { + let (mut points, mut edges, mut faces, mut spans) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for s in &self.shells { + let (base_edge, base_vertex) = (edges.len() as u32, points.len() as u32); + spans.push((faces.len()..faces.len() + s.faces.len(), edges.len()..edges.len() + s.edges.len())); + points.extend_from_slice(&s.vertices); + edges.extend(s.edges.iter().map(|e| Edge { vertices: e.vertices.map(|v| v + base_vertex), curve: e.curve.clone() })); + faces.extend(s.faces.iter().cloned().map(|mut f| { + f.loops.iter_mut().flatten().for_each(|u| u.edge += base_edge); + f + })); + } + let mut order: Vec> = vec![None; edges.len()]; + let mut numbers: Vec = Vec::new(); + let mut walked: Vec> = vec![Vec::new(); edges.len()]; + let mut visit = |e: usize, order: &mut Vec>| { + if order[e].is_none() { + order[e] = Some(numbers.len() as u32); + numbers.push(e); + } + }; + for (fi, f) in faces.iter().enumerate() { + for (li, l) in f.loops.iter().enumerate() { + for k in 0..l.len() { + let position = if f.forward { k } else { l.len() - 1 - k }; + let u = l[position]; + visit(u.edge as usize, &mut order); + let at = rec::EdgeUseRef { face: fi as u32, r#loop: li as u32, position: position as u32, upper: !u.forward }; + walked[u.edge as usize].push(at); + } + } + } + // Edges no face uses, shell by shell: its wires. + let wires: Vec> = spans + .iter() + .map(|(_, shell_edges)| { + shell_edges + .clone() + .filter(|e| walked[*e].is_empty()) + .map(|e| { + visit(e, &mut order); + order[e].expect("just numbered") + }) + .collect() + }) + .collect(); + let number = |e: u32| order[e as usize].expect("every edge is numbered"); + let mut vertex_order: Vec> = vec![None; points.len()]; + let mut vertices = Vec::new(); + let mut edge_records = Vec::new(); + for &e in &numbers { + let (label, nurbs, interval) = edges[e].curve.parts(); + let ends = edges[e].vertices.map(|v| { + *vertex_order[v as usize].get_or_insert_with(|| { + vertices.push(rec::Vertex { point: points[v as usize], tolerance: 1e-6 }); + vertices.len() as u32 - 1 + }) + }); + edge_records.push(rec::Edge { curve: label, nurbs, interval, vertices: ends, tolerance: 1e-6, uses: walked[e].clone() }); + } + let pcurve = |edge: u32| { + let [t0, t1] = edge_records[number(edge) as usize].interval; + rec::Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![[0., 0.], [1., 0.]] } + }; + let face_records = faces + .iter() + .map(|f| { + let (surface, nurbs, domain) = f.surface.parts(); + let loops = f + .loops + .iter() + .map(|l| rec::Loop::Edges { + edges: l.iter().map(|u| rec::OrientedEdge { edge: number(u.edge), forward: u.forward, pcurve: pcurve(u.edge) }).collect(), + }) + .collect(); + rec::Face { surface, nurbs, domain, loops } + }) + .collect(); + let mut regions = vec![rec::Region { shells: (0..self.shells.len() as u32).collect(), void: false }]; + let mut shells = Vec::new(); + for (s, (shell_faces, _)) in spans.iter().enumerate() { + // A closed shell (each edge on its faces used twice among them) also bounds a region. + let used = |e: u32| faces[shell_faces.clone()].iter().flat_map(|f| f.loops.iter().flatten()).filter(|u| u.edge == e).count(); + if faces[shell_faces.clone()].iter().flat_map(|f| f.loops.iter().flatten()).all(|u| used(u.edge) >= 2) { + regions.push(rec::Region { shells: vec![s as u32], void: false }); + } + let oriented = shell_faces.clone().map(|f| rec::OrientedFace { face: f as u32, forward: faces[f].forward }).collect(); + shells.push(rec::Shell::Faces { faces: oriented, wires: wires[s].clone() }); + } + let record = rec::Brep { version: self.version, tolerance: 1e-6, regions, shells, faces: face_records, edges: edge_records, vertices }; + (record, numbers) + } +} + +/// The real `prepare_cancellable` on the fixture's record, its edges then back in the fixture's +/// numbering and its arcs on the angles the fixture counted them from (the record's are within a +/// turn of zero: `label::edge_curve_interval`), which is what the assertions below speak of. +fn prepare_cancellable(b: &Brep, opts: &Options, cancel: &dyn Fn() -> bool) -> Result { + let (record, numbers) = b.record(); + let mut def = super::prepare_cancellable(&record, opts, cancel)?; + let curves: Vec<&Curve> = b.shells.iter().flat_map(|s| s.edges.iter().map(|e| &e.curve)).collect(); + let mut ordered: Vec<(usize, EdgeData)> = numbers.into_iter().zip(std::mem::take(&mut def.edges)).collect(); + ordered.sort_by_key(|(n, _)| *n); + for (n, e) in &mut ordered { + if let (Curve::CircleArc { angle, .. }, C3::Arc { range, .. }) = (curves[*n], &mut e.curve) { + let turns = ((angle[0] - range[0]) / std::f64::consts::TAU).round() * std::f64::consts::TAU; + *range = [range[0] + turns, range[1] + turns]; + } + } + def.edges = ordered.into_iter().map(|(_, e)| e).collect(); + Ok(def) +} + +fn prepare(b: &Brep, opts: &Options) -> Result { + prepare_cancellable(b, opts, &|| false) +} + +/// A surface's chart over the bounds it carries. +fn chart(s: &Surface) -> S3 { + S3::bounded(&s.label(), s.bounds()).unwrap() +} /// An axis-aligned box with line edges and plane faces. fn cuboid(lo: [f64; 3], hi: [f64; 3]) -> Brep { @@ -33,7 +386,7 @@ fn cuboid(lo: [f64; 3], hi: [f64; 3]) -> Brep { Face { loops: vec![cycle([0, 4, 6, 2])], surface: plane(0, 4, 2), forward: true }, Face { loops: vec![cycle([1, 3, 7, 5])], surface: plane(1, 3, 5), forward: true }, ]; - Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices, edges, faces }] } + Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices, edges, faces }] } } fn identity(body: usize, t: [f64; 3]) -> Placement { @@ -93,9 +446,9 @@ fn quadratic_roots_with_no_linear_term() { #[test] fn a_torus_seen_along_its_axis_has_both_equator_silhouettes() { // A whole-meridian torus record: the outer equator sits where the closed profile's ends meet. - let frame = crate::brep::Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; + let frame = solidcore_record::brep::Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; let tau = std::f64::consts::TAU; - let s = surface::S3::new(&Surface::Torus { frame, major_radius: 20., minor_radius: 5., longitude: [0., tau], meridian: [0., tau] }).unwrap(); + let s = chart(&Surface::Torus { frame, major_radius: 20., minor_radius: 5., longitude: [0., tau], meridian: [0., tau] }); let mut radii: Vec = s .rev_silhouette(Vec3::new(0., 0., -1.)) .iter() @@ -164,12 +517,10 @@ fn a_ray_from_the_hole_crosses_a_thin_large_torus() { fn a_torus_seen_nearly_along_its_axis_keeps_its_silhouettes() { // Meridian starting off the equator and a view 1e-4 rad from the axis: the silhouette lives // in narrow profile intervals around the equators, which must not fall between samples. - let frame = crate::brep::Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; + let frame = solidcore_record::brep::Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; let tau = std::f64::consts::TAU; let shift = std::f64::consts::PI / 720.; - let s = - surface::S3::new(&Surface::Torus { frame, major_radius: 1000., minor_radius: 500., longitude: [0., tau], meridian: [shift, shift + tau] }) - .unwrap(); + let s = chart(&Surface::Torus { frame, major_radius: 1000., minor_radius: 500., longitude: [0., tau], meridian: [shift, shift + tau] }); let d = Vec3::new(1e-4, 0., -1.).normalized().unwrap(); let curves = s.rev_silhouette(d); // Both the outer (radius about 1500) and the inner (about 500) silhouettes are there. @@ -194,8 +545,8 @@ fn a_shallow_cut_through_a_torus_tube_is_found() { } /// A frame at `o` with x along +X and y along +Y (z along +Z). -fn frame_at(o: [f64; 3]) -> crate::brep::Frame { - crate::brep::Frame { origin: o, x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] } +fn frame_at(o: [f64; 3]) -> solidcore_record::brep::Frame { + solidcore_record::brep::Frame { origin: o, x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] } } /// A full circle about Z through vertex `v`. @@ -236,7 +587,7 @@ fn turned(r0: f64, r1: f64, h: f64) -> Brep { forward: true, }, ]; - Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: vec![[r0, 0., 0.], [r1, 0., h]], edges, faces }] } + Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[r0, 0., 0.], [r1, 0., h]], edges, faces }] } } /// A sphere of radius `r` at the origin: two hemispheres meeting at the equator. @@ -248,7 +599,7 @@ fn sphere(r: f64) -> Brep { forward: true, }; let faces = vec![hemisphere([0., half], true), hemisphere([-half, 0.], false)]; - Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: vec![[r, 0., 0.]], edges: vec![circle([0.; 3], r, 0)], faces }] } + Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[r, 0., 0.]], edges: vec![circle([0.; 3], r, 0)], faces }] } } /// A torus about Z (major radius `big`, minor `small`): top and bottom halves meeting at the @@ -262,7 +613,10 @@ fn torus(big: f64, small: f64) -> Brep { }; let edges = vec![circle([0.; 3], big + small, 0), circle([0.; 3], big - small, 1)]; let faces = vec![half([0., pi], true), half([pi, tau], false)]; - Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: vec![[big + small, 0., 0.], [big - small, 0., 0.]], edges, faces }] } + Brep { + version: solidcore_record::brep::VERSION, + shells: vec![Shell { vertices: vec![[big + small, 0., 0.], [big - small, 0., 0.]], edges, faces }], + } } /// A bilinear (twisted) spline patch over x, y in [-5, 5] with z between 0 and 1. @@ -275,7 +629,7 @@ fn twisted_patch() -> Brep { surface: Surface::Spline { u_knots: vec![0., 0., 1., 1.], v_knots: vec![0., 0., 1., 1.], points: vec![vec![p[0], p[3]], vec![p[1], p[2]]] }, forward: true, }; - Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] } + Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] } } fn pieces(d: &Drawing) -> impl Iterator { @@ -477,9 +831,11 @@ fn a_flat_spline_patch_is_a_plane_that_hides_for_certain() { surface: Surface::Spline { u_knots: vec![0., 0., 1., 1.], v_knots: vec![0., 0., 1., 1.], points: vec![vec![p[0], p[3]], vec![p[1], p[2]]] }, forward: true, }; - let patch = - prepare(&Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] }, &Options::default()) - .unwrap(); + let patch = prepare( + &Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] }, + &Options::default(), + ) + .unwrap(); assert!(patch.report.freeform_faces.is_empty()); let bar = prepare(&cuboid([-2., -1., -3.], [2., 1., -1.]), &Options::default()).unwrap(); let view = View::new(Vec3::new(0.1, 0.05, -1.), Vec3::new(0., 1., 0.)).unwrap(); @@ -520,7 +876,7 @@ fn a_circle_racing_through_its_first_turn_is_drawn_whole_edge_on() { let homogeneous: Vec<[f64; 4]> = num.iter().zip(&w).map(|((re, im), w)| [10. * re, 10. * im, 0., *w]).collect(); let start = [10., 0., 0.]; let disc = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![start], edges: vec![Edge { vertices: [0, 0], curve: Curve::RationalSpline { knots: [[0.; 7], [1.; 7]].concat(), homogeneous } }], @@ -559,7 +915,7 @@ fn an_arc_racing_through_almost_a_full_turn_is_drawn_whole() { let sweep_want = 4. * phi; let end = [10. * sweep_want.cos(), 10. * sweep_want.sin(), 0.]; let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[10., 0., 0.], end], edges: vec![ @@ -606,7 +962,7 @@ fn a_short_piece_of_a_fast_arc_turns_its_own_way() { let homogeneous: Vec<[f64; 4]> = first.iter().chain(second.iter().skip(1)).copied().collect(); let end = [10. * 5.8f64.cos(), 10. * 5.8f64.sin(), 0.]; let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[10., 0., 0.], end], edges: vec![ @@ -656,7 +1012,7 @@ fn an_arc_whose_whole_domain_is_8_roundings_wide_is_not_guessed() { let k = 0.25 + 2f64.powi(-51); let end = [10. * 3.75f64.cos(), 10. * 3.75f64.sin(), 0.]; let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[10., 0., 0.], end], edges: vec![ @@ -699,7 +1055,7 @@ fn a_piece_in_a_knot_span_of_1e_11_turns_its_own_way() { let k = 0.25 + 1e-11; let end = [10. * 4.5f64.cos(), 10. * 4.5f64.sin(), 0.]; let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[10., 0., 0.], end], edges: vec![ @@ -751,7 +1107,7 @@ fn a_curve_that_swerves_where_its_weight_is_near_zero_is_not_taken_for_a_circle( }) .collect(); let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[0., -10., 0.], [0., 10., 0.]], edges: vec![ @@ -785,9 +1141,11 @@ fn an_edge_leaving_a_left_out_faces_box_in_front_stays_visible() { surface: Surface::Plane { origin: c[0], u_axis: [10., 0., 6.], v_axis: [0., 0.2, 0.] }, forward: true, }; - let strip = - prepare(&Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: c.to_vec(), edges, faces: vec![face] }] }, &Options::default()) - .unwrap(); + let strip = prepare( + &Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: c.to_vec(), edges, faces: vec![face] }] }, + &Options::default(), + ) + .unwrap(); let view = View::new(Vec3::new(0., 0., -1.), Vec3::new(0., 1., 0.)).unwrap(); let d = hidden_lines(&[patch, strip], &[identity(0, [0.; 3]), identity(1, [0.; 3])], &view, &Options::default(), &never).unwrap(); let states: Vec<([f64; 2], Visibility)> = edge_line(&d, 1, 0).pieces.iter().map(|p| (p.t, p.visibility)).collect(); @@ -800,7 +1158,7 @@ fn a_nearly_straight_cubic_is_not_taken_for_a_huge_circle() { // about 1e7, which is 2e-10 of that radius but 2e-6 of the curve. Drawn as chords. let pts = [[0., 0., 0.], [1000. / 3., 0.071 / 3., 0.], [2000. / 3., 0.071 * 2. / 3. - 0.113 / 3., 0.], [1000., 0., 0.]]; let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[0.; 3], [1000., 0., 0.]], edges: vec![ @@ -835,15 +1193,17 @@ fn an_edge_dipping_behind_a_left_out_face_between_samples_is_uncertain() { surface: Surface::Spline { u_knots: vec![0., 0., 1., 1.], v_knots: vec![0., 0., 1., 1.], points: vec![vec![p[0], p[3]], vec![p[1], p[2]]] }, forward: true, }; - let patch = - prepare(&Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] }, &Options::default()) - .unwrap(); + let patch = prepare( + &Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] }, + &Options::default(), + ) + .unwrap(); assert_eq!(patch.report.freeform_faces, vec![0]); // z = 20 t^2 - 0.625 t + 0.0035625 as a quadratic Bezier. let z = [0.0035625, 0.0035625 - 0.3125, 20. - 0.625 + 0.0035625]; let c = [[0., 0.5, z[0]], [5., 0.5, z[1]], [10., 0.5, z[2]]]; let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![c[0], c[2]], edges: vec![ @@ -878,7 +1238,7 @@ fn an_arc_that_turns_back_is_drawn_as_chords() { let th = 2. * u3[3].atan(); let end = [10. * th.cos(), 10. * th.sin(), 0.]; let shape = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[10., 0., 0.], end], edges: vec![ @@ -907,7 +1267,7 @@ fn a_cone_tip_trimmed_near_the_apex_is_only_its_tip() { // tip below it: a box edge at x = 40, z = 50 to 150, seen along +X, is in front of nothing. let tau = std::f64::consts::TAU; let tip = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[0.25, 0., 1.]], edges: vec![circle([0., 0., 1.], 0.25, 0)], @@ -944,7 +1304,7 @@ fn an_edge_behind_a_left_out_freeform_face_is_uncertain_there() { let tau = std::f64::consts::TAU; let profile = Curve::Spline { knots: vec![0., 0., 0., 1., 1., 1.], points: vec![[12.5, 0., 0.], [13., 0., 5.], [12.5, 0., 10.]] }; let tube = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[12.5, 0., 0.], [12.5, 0., 10.]], edges: vec![circle([10., 0., 0.], 2.5, 0), circle([10., 0., 10.], 2.5, 1), Edge { vertices: [0, 1], curve: profile.clone() }], @@ -986,9 +1346,11 @@ fn a_sloping_edge_that_runs_behind_a_left_out_face_is_uncertain() { surface: Surface::Plane { origin: c[0], u_axis: [8., 0., -1.6], v_axis: [0., 0.2, 0.] }, forward: true, }; - let strip = - prepare(&Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: c.to_vec(), edges, faces: vec![face] }] }, &Options::default()) - .unwrap(); + let strip = prepare( + &Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: c.to_vec(), edges, faces: vec![face] }] }, + &Options::default(), + ) + .unwrap(); let view = View::new(Vec3::new(0., 0., -1.), Vec3::new(0., 1., 0.)).unwrap(); let d = hidden_lines(&[patch, strip], &[identity(0, [0.; 3]), identity(1, [0.; 3])], &view, &Options::default(), &never).unwrap(); for p in &edge_line(&d, 1, 0).pieces { @@ -1020,8 +1382,9 @@ fn a_torus_stored_as_a_rational_spline_patch_is_recognised() { }) .collect(); let at = |t: f64, f: f64| [(big + small * f.cos()) * t.cos(), (big + small * f.cos()) * t.sin(), small * f.sin()]; - let parallel = |f: f64| crate::brep::Frame { origin: [0., 0., small * f.sin()], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; - let meridian = |t: f64| crate::brep::Frame { origin: [big * t.cos(), big * t.sin(), 0.], x_axis: [t.cos(), t.sin(), 0.], y_axis: [0., 0., 1.] }; + let parallel = |f: f64| solidcore_record::brep::Frame { origin: [0., 0., small * f.sin()], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; + let meridian = + |t: f64| solidcore_record::brep::Frame { origin: [big * t.cos(), big * t.sin(), 0.], x_axis: [t.cos(), t.sin(), 0.], y_axis: [0., 0., 1.] }; let edges = vec![ Edge { vertices: [0, 1], curve: Curve::CircleArc { frame: parallel(-q), radius: big + small * q.cos(), angle: [-q, q] } }, Edge { vertices: [1, 2], curve: Curve::CircleArc { frame: meridian(q), radius: small, angle: [-q, q] } }, @@ -1034,7 +1397,7 @@ fn a_torus_stored_as_a_rational_spline_patch_is_recognised() { forward: true, }; let patch = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![at(-q, -q), at(q, -q), at(q, q), at(-q, q)], edges, faces: vec![face] }], }; let def = prepare(&patch, &Options::default()).unwrap(); @@ -1086,8 +1449,9 @@ fn a_torus_patch_with_a_bump_in_a_narrow_knot_span_is_not_taken_for_a_torus() { }) .collect(); let at = |t: f64, f: f64| [(big + small * f.cos()) * t.cos(), (big + small * f.cos()) * t.sin(), small * f.sin()]; - let parallel = |f: f64| crate::brep::Frame { origin: [0., 0., small * f.sin()], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; - let meridian = |t: f64| crate::brep::Frame { origin: [big * t.cos(), big * t.sin(), 0.], x_axis: [t.cos(), t.sin(), 0.], y_axis: [0., 0., 1.] }; + let parallel = |f: f64| solidcore_record::brep::Frame { origin: [0., 0., small * f.sin()], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; + let meridian = + |t: f64| solidcore_record::brep::Frame { origin: [big * t.cos(), big * t.sin(), 0.], x_axis: [t.cos(), t.sin(), 0.], y_axis: [0., 0., 1.] }; let edges = vec![ Edge { vertices: [0, 1], curve: Curve::CircleArc { frame: parallel(-q), radius: big + small * q.cos(), angle: [-q, q] } }, Edge { vertices: [1, 2], curve: Curve::CircleArc { frame: meridian(q), radius: small, angle: [-q, q] } }, @@ -1104,7 +1468,7 @@ fn a_torus_patch_with_a_bump_in_a_narrow_knot_span_is_not_taken_for_a_torus() { forward: true, }; let patch = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![at(-q, -q), at(q, -q), at(q, q), at(-q, q)], edges, faces: vec![face] }], }; let def = prepare(&patch, &Options::default()).unwrap(); @@ -1120,9 +1484,9 @@ fn a_big_circle_passing_behind_a_thin_left_out_face_is_uncertain_there() { let tau = std::f64::consts::TAU; let turn = 8.5 * std::f64::consts::PI / 256.; let (c, sn) = (turn.cos(), turn.sin()); - let frame = crate::brep::Frame { origin: [0.; 3], x_axis: [-c, -sn, 0.], y_axis: [sn, -c, 0.] }; + let frame = solidcore_record::brep::Frame { origin: [0.; 3], x_axis: [-c, -sn, 0.], y_axis: [sn, -c, 0.] }; let disc = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[-5000. * c, -5000. * sn, 0.]], edges: vec![Edge { vertices: [0, 0], curve: Curve::CircleArc { frame, radius: 5000., angle: [0., tau] } }], @@ -1140,13 +1504,13 @@ fn a_big_circle_passing_behind_a_thin_left_out_face_is_uncertain_there() { let end = |y: f64, v: u32| Edge { vertices: [v, v], curve: Curve::CircleArc { - frame: crate::brep::Frame { origin: [5000., y, 1.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, + frame: solidcore_record::brep::Frame { origin: [5000., y, 1.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, radius: 0.01, angle: [0., tau], }, }; let tube = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[5000.01, -100., 1.], [5000.01, 100., 1.]], edges: vec![end(-100., 0), end(100., 1), Edge { vertices: [0, 1], curve: profile.clone() }], @@ -1200,11 +1564,11 @@ fn an_arc_folding_back_under_a_left_out_face_seen_edge_on_is_uncertain_there() { fn folding_arc_under_a_patch(offset: f64) { let step = std::f64::consts::PI / 256.; let ta = -step / 4. + offset; - let frame = crate::brep::Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }; + let frame = solidcore_record::brep::Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }; let at = |t: f64| [10000. * t.cos(), 0., 10000. * t.sin()]; let (start, end) = (at(ta), at(ta + std::f64::consts::PI / 8.)); let arc = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![start, end], edges: vec![ @@ -1227,7 +1591,7 @@ fn folding_arc_under_a_patch(offset: f64) { surface: Surface::Spline { u_knots: vec![0., 0., 1., 1.], v_knots: vec![0., 0., 1., 1.], points: vec![vec![p[0], p[3]], vec![p[1], p[2]]] }, forward: true, }; - let patch = Brep { version: crate::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] }; + let patch = Brep { version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: p.to_vec(), edges, faces: vec![face] }] }; let defs = [prepare(&patch, &Options::default()).unwrap(), prepare(&arc, &Options::default()).unwrap()]; assert_eq!(defs[0].report.freeform_faces, vec![0]); let view = View::new(Vec3::new(0., 0., -1.), Vec3::new(0., 1., 0.)).unwrap(); @@ -1263,7 +1627,7 @@ fn a_left_out_face_curling_over_its_own_edge_makes_it_uncertain() { forward: true, }; let sheet = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![at(a, 0.), at(c, 0.), at(c, 8000.), at(a, 8000.)], edges, faces: vec![face] }], }; let def = prepare(&sheet, &Options::default()).unwrap(); @@ -1334,7 +1698,7 @@ fn a_sphere_with_a_spline_band_between_record_caps_is_one_sphere() { forward: true, }; let body = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[rho, 0., -z], [rho, 0., z]], edges: vec![circle([0., 0., -z], rho, 0), circle([0., 0., z], rho, 1)], @@ -1369,7 +1733,7 @@ fn chords_of_a_racing_circle_stay_within_their_stated_deviation() { let w = bernstein_product(&bernstein_product(&q, &q), &q); let homogeneous: Vec<[f64; 4]> = num.iter().zip(&w).map(|((re, im), w)| [*re, *im, 0., *w]).collect(); let disc = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[1., 0., 0.]], edges: vec![Edge { vertices: [0, 0], curve: Curve::RationalSpline { knots: [[0.; 7], [1.; 7]].concat(), homogeneous } }], @@ -1411,7 +1775,7 @@ fn a_big_arc_is_cut_where_it_meets_a_left_out_faces_box() { let a0 = -std::f64::consts::PI / 8.; let (start, end) = ([10000. * a0.cos(), 10000. * a0.sin(), 0.], [10000., 0., 0.]); let arc = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![start, end], edges: vec![ @@ -1433,13 +1797,13 @@ fn a_big_arc_is_cut_where_it_meets_a_left_out_faces_box() { let end_circle = |y: f64, v: u32| Edge { vertices: [v, v], curve: Curve::CircleArc { - frame: crate::brep::Frame { origin: [x, y, 1.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, + frame: solidcore_record::brep::Frame { origin: [x, y, 1.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, radius: 2.5, angle: [0., tau], }, }; let tube = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[x + 2.5, -4000., 1.], [x + 2.5, 3000., 1.]], edges: vec![end_circle(-4000., 0), end_circle(3000., 1), Edge { vertices: [0, 1], curve: profile.clone() }], @@ -1482,7 +1846,7 @@ fn narrow_torus_strips_keep_their_outline() { }; let phis: [f64; 3] = [0.3002, 0.3005, 0.3008]; let body = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: phis.iter().map(|p| [20. + 10. * p.cos(), 0., 10. * p.sin()]).collect(), edges: vec![ring(phis[0], 0), ring(phis[1], 1), ring(phis[2], 2)], @@ -1623,7 +1987,7 @@ fn disc(r: f64, pts: [[f64; 2]; 9], knots: Vec) -> Brep { let s = std::f64::consts::FRAC_1_SQRT_2; let homogeneous = pts.iter().enumerate().map(|(i, p)| if i % 2 == 1 { [p[0] * s, p[1] * s, 0., s] } else { [p[0], p[1], 0., 1.] }).collect(); Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![[r, 0., 0.]], edges: vec![Edge { vertices: [0, 0], curve: Curve::RationalSpline { knots, homogeneous } }], @@ -1715,7 +2079,7 @@ fn nearly_coaxial_cones_far_out_keep_their_own_silhouettes() { // 1e7 mm out, and 1 km ones 0.4 mm apart 1e9 mm out. for (x, r, gap) in [(1e7, 5., 0.005), (1e9, 1e6, 0.4)] { let shells = vec![frustum([x, 0., 0.], r, 0.25, [0., 10.]), frustum([x + gap, 0., 0.], r, 0.25, [20., 30.])]; - check_two_cone_outlines(&Brep { version: crate::brep::VERSION, shells }); + check_two_cone_outlines(&Brep { version: solidcore_record::brep::VERSION, shells }); } } @@ -1748,7 +2112,7 @@ fn nearly_coincident_cone_sectors_both_draw_their_outline() { cone_sector([x, 0., 0.], 1000., 0.25, [0., 1000.], [0., 0.02]), cone_sector([x + 3e-6, 0., 0.], 1000., 0.25, [2000., 3000.], [0., 0.02]), ]; - let def = prepare(&Brep { version: crate::brep::VERSION, shells }, &Options::default()).unwrap(); + let def = prepare(&Brep { version: solidcore_record::brep::VERSION, shells }, &Options::default()).unwrap(); let view = View::new(Vec3::new(-(0.01f64.sin()), 0.01f64.cos(), 0.), Vec3::new(0., 0., 1.)).unwrap(); let d = hidden_lines(&[def], &[identity(0, [0.; 3])], &view, &Options::default(), &never).unwrap(); for (z0, z1) in [(0., 1000.), (2000., 3000.)] { @@ -1791,7 +2155,7 @@ fn spherical_caps_through_one_circle_keep_their_own_outlines() { cap([0.; 3], r, lat(0.), edge(), [ring, 0., z]), cap([0., 0., dz], (ring * ring + (z - dz).powi(2)).sqrt(), lat(dz), edge(), [ring, 0., z]), ]; - let def = prepare(&Brep { version: crate::brep::VERSION, shells }, &Options::default()).unwrap(); + let def = prepare(&Brep { version: solidcore_record::brep::VERSION, shells }, &Options::default()).unwrap(); let view = View::new(Vec3::new(0., 1., 0.), Vec3::new(0., 0., 1.)).unwrap(); let d = hidden_lines(&[def], &[identity(0, [0.; 3])], &view, &Options::default(), &never).unwrap(); // Above the ring the outline is a half circle of about pi * 1000 * 0.41 mm on each side. @@ -1811,7 +2175,7 @@ fn spherical_caps_through_one_circle_keep_their_own_outlines() { fn tilted_cone(tilt: f64, h: [f64; 2]) -> Shell { let (x, y, z) = (Vec3::new(tilt.cos(), 0., -tilt.sin()), Vec3::new(0., 1., 0.), Vec3::new(tilt.sin(), 0., tilt.cos())); let arr = |v: Vec3| [v.x, v.y, v.z]; - let frame = |o: Vec3| crate::brep::Frame { origin: arr(o), x_axis: arr(x), y_axis: arr(y) }; + let frame = |o: Vec3| solidcore_record::brep::Frame { origin: arr(o), x_axis: arr(x), y_axis: arr(y) }; let at = |hh: f64| x * (0.25 * hh) + z * hh; let ring = |hh: f64, v: u32| Edge { vertices: [v, v], @@ -1837,7 +2201,7 @@ fn cones_with_slightly_turned_axes_keep_their_own_outlines() { // One apex, axes 3e-7 rad apart, heights 1000 to 3000 and 6000 to 8000: each frustum draws // both rulings of its own outline. let shells = vec![tilted_cone(0., [1000., 3000.]), tilted_cone(3e-7, [6000., 8000.])]; - let def = prepare(&Brep { version: crate::brep::VERSION, shells }, &Options::default()).unwrap(); + let def = prepare(&Brep { version: solidcore_record::brep::VERSION, shells }, &Options::default()).unwrap(); let view = View::new(Vec3::new(0., 1., 0.), Vec3::new(0., 0., 1.)).unwrap(); let d = hidden_lines(&[def], &[identity(0, [0.; 3])], &view, &Options::default(), &never).unwrap(); for (z0, z1) in [(1000., 3000.), (6000., 8000.)] { @@ -1889,7 +2253,7 @@ fn a_high_degree_spline_through_points_of_a_circle_is_not_taken_for_one() { let knots: Vec = std::iter::repeat_n(0., n + 1).chain(std::iter::repeat_n(1., n + 1)).collect(); let start = points[0]; let disc = Brep { - version: crate::brep::VERSION, + version: solidcore_record::brep::VERSION, shells: vec![Shell { vertices: vec![start], edges: vec![Edge { vertices: [0, 0], curve: Curve::Spline { knots, points } }], @@ -1971,10 +2335,12 @@ fn a_plane_through_three_points_draws_as_a_plane() { #[test] fn procedural_and_placed_records_are_not_supported_yet() { let o = Options::default(); - // A cylinder side stored as a placed revolution of its seam line. + // A cylinder side stored as a placed revolution of its seam line, under a placement that is + // not rigid. (The B-rep model now has this one record for main's drawn `Revolution` too, so a + // rigid placement is drawn: `a_placement_that_is_not_rigid_is_refused` and the tube fixtures.) let mut placed = cylinder(4., 10.); - let profile = Box::new(Curve::Line { start: [4., 0., 0.], end: [4., 0., 10.] }); - let matrix = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; + let profile = Box::new(Curve::Line { start: [2., 0., 0.], end: [2., 0., 10.] }); + let matrix = [[2., 0., 0., 0.], [0., 2., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; placed.shells[0].faces[0].surface = Surface::PlacedRevolution { profile, origin: [0.; 3], axis: [0., 0., 1.], matrix, forward: true }; assert!(matches!(prepare(&placed, &o), Err(HlrError::Unsupported("placed revolution surface")))); // A box edge stored as the meeting of the planes y = 0 and z = 0, traced from a leader. @@ -2211,3 +2577,296 @@ fn chords_only_near_each_other_still_meet_their_crossings() { assert_eq!(crossings(&mut tracks, &ctx).unwrap(), 2); assert!(tracks.iter().all(|t| t.splits.len() == 2), "{:?}", tracks.iter().map(|t| &t.splits).collect::>()); } + +/// Whether two drawings of one view agree: the same lines with the same states, in the same places. +fn assert_same_drawing(a: &Drawing, b: &Drawing, tol: f64) { + let states = |d: &Drawing| -> Vec<(Visibility, bool, usize)> { pieces(d).map(|p| (p.visibility, p.covered, p.geometry.len())).collect() }; + assert_eq!(states(a), states(b)); + for (p, q) in pieces(a).zip(pieces(b)) { + for (g, h) in p.geometry.iter().zip(&q.geometry) { + for s in [0., 0.5, 1.] { + assert!(g.point_at(s).dist(h.point_at(s)) < tol, "{g:?} vs {h:?}"); + } + } + } +} + +#[test] +fn a_rigidly_placed_revolution_draws_as_the_cylinder_it_is() { + // The side of `cylinder` stored as a revolution of its seam, u along it or u the angle, in + // place and with the profile and axis 5 mm off, the placement bringing them back. + let o = Options::default(); + let view = View::new(Vec3::new(1., 0.3, -0.3), Vec3::new(0., 0., 1.)).unwrap(); + let draw = |b: &Brep| { + let def = prepare(b, &o).unwrap(); + assert_eq!(def.report.surfaces.get("cylinder"), Some(&1), "{:?}", def.report); + hidden_lines(&[def], &[identity(0, [0.; 3])], &view, &o, &never).unwrap() + }; + let want = draw(&cylinder(4., 10.)); + let moved = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [5., 0., 0., 1.]]; + for (x, matrix) in [(0., IDENTITY), (-5., moved)] { + for forward in [true, false] { + let mut placed = cylinder(4., 10.); + let profile = Box::new(Curve::Line { start: [4. + x, 0., 0.], end: [4. + x, 0., 10.] }); + placed.shells[0].faces[0].surface = Surface::PlacedRevolution { profile, origin: [x, 0., 0.], axis: [0., 0., 1.], matrix, forward }; + assert_same_drawing(&want, &draw(&placed), 1e-9); + } + } +} + +#[test] +fn a_placement_that_is_not_rigid_is_refused() { + let mut placed = cylinder(4., 10.); + let profile = Box::new(Curve::Line { start: [2., 0., 0.], end: [2., 0., 10.] }); + let matrix = [[2., 0., 0., 0.], [0., 2., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; + placed.shells[0].faces[0].surface = Surface::PlacedRevolution { profile, origin: [0.; 3], axis: [0., 0., 1.], matrix, forward: true }; + assert!(matches!(prepare(&placed, &Options::default()), Err(HlrError::Unsupported("placed revolution surface")))); +} + +#[test] +fn a_revolved_circle_is_a_torus_drawn_at_both_equators() { + // The halves of `torus` stored as revolutions of half circles. + let half = |a: [f64; 2]| Curve::CircleArc { + frame: solidcore_record::brep::Frame { origin: [20., 0., 0.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, + radius: 5., + angle: a, + }; + let mut body = torus(20., 5.); + let (pi, tau) = (std::f64::consts::PI, std::f64::consts::TAU); + for (f, a) in body.shells[0].faces.iter_mut().zip([[0., pi], [pi, tau]]) { + f.surface = Surface::Revolution { profile: Box::new(half(a)), origin: [0.; 3], axis: [0., 0., 1.], angle: [0., tau] }; + } + let def = prepare(&body, &Options::default()).unwrap(); + assert_eq!(def.report.surfaces.get("torus"), Some(&2), "{:?}", def.report); + let view = View::new(Vec3::new(0., 0., -1.), Vec3::new(0., 1., 0.)).unwrap(); + let d = hidden_lines(&[def], &[identity(0, [0.; 3])], &view, &Options::default(), &never).unwrap(); + assert_eq!(d.stats.silhouettes, 2, "{:?}", d.stats); + assert_eq!(d.stats.uncertain_uncovered, 0, "{:?}", d.stats); +} + +/// A record's edge on `curve` over `interval`, its form `nurbs`. +fn bounded_edge(curve: rec::Curve, nurbs: Option, interval: [f64; 2]) -> rec::Edge { + rec::Edge { curve, nurbs, interval, vertices: [0, 1], tolerance: 1e-6, uses: Vec::new() } +} + +#[test] +fn an_edge_is_cut_to_its_interval_on_its_unbounded_curve() { + let close = |a: Vec3, b: [f64; 3]| a.dist(Vec3::new(b[0], b[1], b[2])) < 1e-12; + // A line through two points, from t = 2 to 3, without and with a form. + let line = rec::Curve::Line { start: [0.; 3], end: [1., 0., 0.] }; + let (c, acc) = C3::of_edge(&bounded_edge(line.clone(), None, [2., 3.])).unwrap(); + assert_eq!(acc, CurveAccuracy::Analytic); + assert!(close(c.at(0.), [2., 0., 0.]) && close(c.at(1.), [3., 0., 0.]), "{c:?}"); + let (form, interval) = brep::form::curve(&line, [2., 3.]).unwrap(); + let (c, _) = C3::of_edge(&bounded_edge(line, Some(form), interval)).unwrap(); + assert_eq!(c.domain(), [0., 1.]); + assert!(close(c.at(0.), [2., 0., 0.]) && close(c.at(1.), [3., 0., 0.]), "{c:?}"); + // An ellipse's angles come back from its form's parameter. + let frame = frame_at([1., 2., 3.]); + let ellipse = rec::Curve::Ellipse { frame, radii: [4., 2.] }; + let (form, interval) = brep::form::curve(&ellipse, [0.5, 2.5]).unwrap(); + let (c, _) = C3::of_edge(&bounded_edge(ellipse, Some(form), interval)).unwrap(); + let [a0, a1] = c.domain(); + assert!((a0 - 0.5).abs() < 1e-12 && (a1 - 2.5).abs() < 1e-12, "{c:?}"); + assert!(close(c.at(a0), [1. + 4. * 0.5f64.cos(), 2. + 2. * 0.5f64.sin(), 3.]), "{c:?}"); + // A polyline between its second and fourth points' middles. + let points = vec![[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [1., 1., 1.]]; + let (c, _) = C3::of_edge(&bounded_edge(rec::Curve::Polyline { points }, None, [0.5, 2.5])).unwrap(); + assert_eq!(c.domain(), [0., 3.]); + assert!( + close(c.at(0.), [0.5, 0., 0.]) && close(c.at(1.), [1., 0., 0.]) && close(c.at(2.), [1., 1., 0.]) && close(c.at(3.), [1., 1., 0.5]), + "{c:?}" + ); + // A cubic spline of two spans, cut across its inner knot: the same points, on its own domain + // and breaks, its hull and Bezier pieces of the part alone. + let (knots, points) = (vec![0., 0., 0., 0., 0.5, 1., 1., 1., 1.], vec![[0., 0., 0.], [1., 3., 0.], [2., -3., 1.], [3., 3., 0.], [4., 0., 2.]]); + let spline = rec::Curve::Spline { knots, points }; + let (whole, _) = C3::of_edge(&bounded_edge(spline.clone(), None, [0., 1.])).unwrap(); + let (part, _) = C3::of_edge(&bounded_edge(spline.clone(), None, [0.25, 0.75])).unwrap(); + assert_eq!(part.domain(), [0.25, 0.75]); + assert_eq!(part.breaks(), vec![0.25, 0.5, 0.75]); + for k in 0..=20 { + let t = 0.25 + 0.5 * k as f64 / 20.; + assert!(part.at(t).dist(whole.at(t)) < 1e-12, "at {t}"); + } + let hull = part.hull([0.25, 0.75]).unwrap(); + let (first, last) = (hull.first().unwrap(), hull.last().unwrap()); + assert!(first.dist(whole.at(0.25)) < 1e-12 && last.dist(whole.at(0.75)) < 1e-12, "{hull:?}"); + // Inside one span. + let (part, _) = C3::of_edge(&bounded_edge(spline.clone(), None, [0.1, 0.2])).unwrap(); + assert_eq!(part.breaks(), vec![0.1, 0.2]); + assert!(part.at(0.15).dist(whole.at(0.15)) < 1e-12); + // A traced intersection with a spline leader on its surfaces is that spline, good to its + // tolerance; with a polyline leader there is no curve to follow. + let plane = Box::new(rec::Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }); + let traced = + |leader: rec::Curve| rec::Curve::SurfaceIntersection { surfaces: [plane.clone(), plane.clone()], leader: Box::new(leader), tolerance: 1e-4 }; + let flat = rec::Curve::Spline { + knots: vec![0., 0., 0., 0., 0.5, 1., 1., 1., 1.], + points: vec![[0., 0., 0.], [1., 3., 0.], [2., -3., 0.], [3., 3., 0.], [4., 0., 0.]], + }; + let (whole, _) = C3::of_edge(&bounded_edge(flat.clone(), None, [0., 1.])).unwrap(); + let (c, acc) = C3::of_edge(&bounded_edge(traced(flat), None, [0.25, 0.75])).unwrap(); + assert_eq!(acc, CurveAccuracy::Bounded { max_deviation_mm: 1e-4 }); + assert!(c.at(0.5).dist(whole.at(0.5)) < 1e-12); + // That spline leaves the plane: it is not their intersection. + assert!(matches!(C3::of_edge(&bounded_edge(traced(spline), None, [0.25, 0.75])), Err(HlrError::Unsupported("surface intersection curve")))); + let leader = rec::Curve::Polyline { points: vec![[0.; 3], [1., 0., 0.]] }; + assert!(matches!(C3::of_edge(&bounded_edge(traced(leader), None, [0., 1.])), Err(HlrError::Unsupported("surface intersection curve")))); +} + +#[test] +fn a_faces_chart_is_where_its_form_lies_on_its_label() { + // A torus face from a tube start of 0.3: the chart's second coordinate is the tube angle, a + // third of the way up the tube from there, whichever way round the frame's angle counts. + let frame = frame_at([1., 0., 0.]); + let label = rec::Surface::Torus { frame, major_radius: 20., minor_radius: 5., tube_start: 0.3 }; + let (form, domain) = brep::form::surface(&label, [[-0.5, 1.], [0.2, 2.]]).unwrap(); + let face = rec::Face { surface: label, nurbs: Some(form.clone()), domain, loops: Vec::new() }; + let s = S3::of_face(&face).unwrap(); + let [angle, tube] = s.domain(); + assert!((angle[0] + 0.5).abs() < 1e-12 && (angle[1] - 1.).abs() < 1e-12, "{angle:?}"); + assert!((tube[0] - 0.5).abs() < 1e-12 && (tube[1] - 2.3).abs() < 1e-12, "{tube:?}"); + let eval = brep::eval::SurfaceEval::new(&form).unwrap(); + let p = eval.point([0.5 * (domain[0][0] + domain[0][1]), 0.5 * (domain[1][0] + domain[1][1])]).unwrap(); + let uv = s.inverse(p, None).unwrap(); + assert!(s.point(uv).dist(p) < 1e-9, "{uv:?}"); + // A whole turn comes to the periodic chart. + let label = rec::Surface::Cylinder { frame: frame_at([0.; 3]), radius: 2. }; + let (form, domain) = brep::form::surface(&label, [[1., 1. + std::f64::consts::TAU], [-1., 3.]]).unwrap(); + let s = S3::of_face(&rec::Face { surface: label, nurbs: Some(form), domain, loops: Vec::new() }).unwrap(); + assert_eq!(s.periods()[0], Some(std::f64::consts::TAU)); + assert!(s.point([0., 0.]).dist(Vec3::new(2., 0., -1.)) < 1e-12); + assert!(s.point([0., 1.]).dist(Vec3::new(2., 0., 3.)) < 1e-12); +} + +#[test] +fn a_form_turned_against_its_label_keeps_the_face_on_the_loops_side() { + // The north hemisphere, its form with u and v swapped so its natural normal points in: its + // loop, stored about that normal, runs the other way round the equator, and in a chart with + // both hemispheres (a recognised patch's would be) the face must still be the north one. The + // same loop on the unturned form is the south hemisphere's. + let tau = std::f64::consts::TAU; + let half = std::f64::consts::FRAC_PI_2; + let label = rec::Surface::Sphere { frame: frame_at([0.; 3]), radius: 10. }; + let chart = S3::bounded(&label, [[0., tau], [-half, half]]).unwrap(); + let circle = rec::Curve::Circle { frame: frame_at([0.; 3]), radius: 10. }; + let (edge_form, interval) = brep::form::curve(&circle, [0., tau]).unwrap(); + let edge = bounded_edge(circle, Some(edge_form), interval); + let curves = vec![C3::of_edge(&edge).unwrap().0]; + let backward = rec::Loop::Edges { + edges: vec![rec::OrientedEdge { + edge: 0, + forward: false, + pcurve: rec::Curve2::Spline { knots: vec![interval[0], interval[0], interval[1], interval[1]], points: vec![[0., 0.], [1., 0.]] }, + }], + }; + let (form, domain) = brep::form::surface(&label, [[0., tau], [0., half]]).unwrap(); + let rec::Surface::RationalSpline { u_knots, v_knots, homogeneous } = form.clone() else { panic!("a sphere's form is rational") }; + let columns = homogeneous[0].len(); + let swapped = (0..columns).map(|j| homogeneous.iter().map(|row| row[j]).collect()).collect(); + let turned = rec::Face { + surface: label.clone(), + nurbs: Some(rec::Surface::RationalSpline { u_knots: v_knots, v_knots: u_knots, homogeneous: swapped }), + domain: [domain[1], domain[0]], + loops: vec![backward.clone()], + }; + assert_eq!(brep::label::form_turns(&turned), Some(true)); + let north = trim::build(&turned, &curves, &chart, 64); + assert_eq!((north.contains([1., 1.]), north.contains([1., -1.])), (Some(true), Some(false))); + let (form, domain) = brep::form::surface(&label, [[0., tau], [-half, 0.]]).unwrap(); + let plain = rec::Face { surface: label, nurbs: Some(form), domain, loops: vec![backward] }; + assert_eq!(brep::label::form_turns(&plain), Some(false)); + let south = trim::build(&plain, &curves, &chart, 64); + assert_eq!((south.contains([1., 1.]), south.contains([1., -1.])), (Some(false), Some(true))); +} + +#[test] +fn an_edge_no_face_uses_is_drawn_like_any_other() { + // A wire beside a box, in the box's shell. + let mut b = cuboid([0.; 3], [1.; 3]); + let v = b.shells[0].vertices.len() as u32; + b.shells[0].vertices.extend([[3., 0., 0.], [3., 0., 1.]]); + b.shells[0].edges.push(Edge { vertices: [v, v + 1], curve: Curve::Line { start: [3., 0., 0.], end: [3., 0., 1.] } }); + let def = prepare(&b, &Options::default()).unwrap(); + assert_eq!(def.report.edges, 13); + let view = View::new(Vec3::new(0., 1., 0.), Vec3::new(0., 0., 1.)).unwrap(); + let d = hidden_lines(&[def], &[identity(0, [0.; 3])], &view, &Options::default(), &never).unwrap(); + assert!(edge_line(&d, 0, 12).pieces.iter().all(|p| p.visibility == Visibility::Visible), "{d:?}"); +} + +/// A traced intersection is drawn from its spline leader only where that spline lies on both +/// surfaces, so the drawn line is the true intersection to the record's tolerance. The top rim of +/// a cylinder of radius 10 and height 10, stored as the meeting of its side and the plane z = 10, +/// its leader four cubic quarter circles (2.8e-3 from the circle at most): seen from above the +/// drawn rim is that circle, and from the side the plane, within the tolerance. The same leader +/// 1 mm off the plane is refused: it would draw a wrong line. +#[test] +fn a_traced_rim_is_drawn_on_the_true_intersection_or_refused() { + let tolerance = 5e-3; + let k = 10. * 4. / 3. * (std::f64::consts::FRAC_PI_8).tan(); + let knots = vec![0., 0., 0., 0., 1., 1., 1., 2., 2., 2., 3., 3., 3., 4., 4., 4., 4.]; + let quarter = [ + [10., 0.], + [10., k], + [k, 10.], + [0., 10.], + [-k, 10.], + [-10., k], + [-10., 0.], + [-10., -k], + [-k, -10.], + [0., -10.], + [k, -10.], + [10., -k], + [10., 0.], + ]; + let traced = |z: f64| { + let mut body = cylinder(10., 10.); + let side = Box::new(body.shells[0].faces[0].surface.clone()); + let top = Box::new(Surface::Plane { origin: [0., 0., 10.], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }); + let points = quarter.iter().map(|[x, y]| [*x, *y, z]).collect(); + let leader = Box::new(Curve::Spline { knots: knots.clone(), points }); + body.shells[0].edges[1].curve = Curve::SurfaceIntersection { surfaces: [side, top], leader, tolerance }; + body + }; + let o = Options::default(); + let def = prepare(&traced(10.), &o).unwrap(); + let rim_points = |view: &View| -> Vec<[f64; 2]> { + let d = hidden_lines(std::slice::from_ref(&def), &[identity(0, [0.; 3])], view, &o, &never).unwrap(); + let rim: Vec<_> = d + .lines + .iter() + .filter(|l| matches!(l.source, Source::Edge { edge: 1, .. })) + .flat_map(|l| &l.pieces) + .flat_map(|p| p.points.iter().copied()) + .collect(); + assert!(rim.len() > 16, "{rim:?}"); + rim + }; + let above = rim_points(&View::new(Vec3::new(0., 0., -1.), Vec3::new(0., 1., 0.)).unwrap()); + assert!(above.iter().all(|p| (p[0].hypot(p[1]) - 10.).abs() <= tolerance), "{above:?}"); + let spread = |at: usize| above.iter().map(|p| p[at]).fold(f64::MIN, f64::max) - above.iter().map(|p| p[at]).fold(f64::MAX, f64::min); + assert!(spread(0) > 19.9 && spread(1) > 19.9, "the whole circle"); + let side = rim_points(&View::new(Vec3::new(0., 1., 0.), Vec3::new(0., 0., 1.)).unwrap()); + let height = side.first().map_or(f64::NAN, |p| p[1]); + let lowest = hidden_lines( + std::slice::from_ref(&def), + &[identity(0, [0.; 3])], + &View::new(Vec3::new(0., 1., 0.), Vec3::new(0., 0., 1.)).unwrap(), + &o, + &never, + ) + .unwrap(); + let bottom = lowest + .lines + .iter() + .filter(|l| matches!(l.source, Source::Edge { edge: 0, .. })) + .flat_map(|l| &l.pieces) + .flat_map(|p| p.points.iter()) + .next() + .map_or(f64::NAN, |p| p[1]); + assert!(side.iter().all(|p| (p[1] - height).abs() <= tolerance) && ((height - bottom) - 10.).abs() <= tolerance, "{side:?} over {bottom}"); + let off = prepare(&traced(11.), &o).err(); + assert!(matches!(off, Some(HlrError::Unsupported("surface intersection curve"))), "{off:?}"); +} diff --git a/crates/geom/src/inertia.rs b/crates/geom/src/inertia.rs index 3ff6db48d..8a0ebcb65 100644 --- a/crates/geom/src/inertia.rs +++ b/crates/geom/src/inertia.rs @@ -1,7 +1,9 @@ //! Inertia tensors (#8095): built from how a body's volume spreads about its centre of mass, //! taken about another point (parallel axes), and their principal moments and axes. -use crate::{MassProperties, Vec3}; +use crate::MassProperties; +use crate::prelude::*; +use solidcore_record::Vec3; /// A symmetric 3 × 3 tensor, row by row. pub type Tensor3 = [[f64; 3]; 3]; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index b114b0ebf..c01afc213 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,10 +11,12 @@ mod aabb2; mod arcfit; +mod ball; pub mod blend; pub mod brep; pub mod bspline; mod bvh; +pub mod catmull_rom; pub mod cell; mod chain; pub mod compare; @@ -24,10 +26,13 @@ pub mod drawing_view; pub mod env; pub mod fill; pub mod fill_general; +pub mod fill_iso; +pub mod fill_matched; mod grid; pub mod hlr; pub mod ids; pub mod inertia; +pub mod linkage; mod mesh; pub mod mesh_distance; pub mod network; @@ -48,16 +53,26 @@ mod unit_vec3; mod vec; pub use aabb2::Aabb2; -pub use arcfit::MAX_FIT_PIECES; +pub use arcfit::{Loop2ArcFit, MAX_FIT_PIECES, Region2ArcFit, Seg2ArcFit}; +pub use ball::Ball; pub use blend::hermite_bezier; pub use bvh::{Bvh, MeshIndex}; pub use chain::{Chain, Closed, Ends, Open, Path, Planar, Ring}; pub use grid::Grid; pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair}; -pub use plane::Plane; -pub use profile::{ArcMap, Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, MAX_DERIVATIVE_ORDER, Region2, Seg2, Similarity2, bezier, regions_apart}; +pub use plane::PlaneGeom; +pub use profile::{ArcMap, Loop2Geom, MAX_DERIVATIVE_ORDER, Region2Geom, Seg2Geom, Similarity2, bezier, regions_apart}; pub use unit_vec3::UnitVec3; -pub use vec::{Vec2, Vec3}; +pub use vec::{Vec2Geom, Vec3Geom}; + +/// The geometry traits of the record's plain data ([`solidcore_record::Vec3`], +/// [`solidcore_record::Plane`], the profile types), in scope with `use solidcraft_geom::prelude::*`. +pub mod prelude { + pub use crate::{ + Loop2ArcFit as _, Loop2Geom as _, PlaneGeom as _, Region2ArcFit as _, Region2Geom as _, Seg2ArcFit as _, Seg2Geom as _, Vec2Geom as _, + Vec3Geom as _, + }; +} /// Geometric tolerance for coincidence tests (mm). pub const EPS: f64 = 1e-9; diff --git a/crates/geom/src/linkage.rs b/crates/geom/src/linkage.rs new file mode 100644 index 000000000..17e388778 --- /dev/null +++ b/crates/geom/src/linkage.rs @@ -0,0 +1,335 @@ +//! Geometric continuity of order `n` (G0 … G4) between two surfaces that share a curve, in the +//! linkage-curve formulation, as the fill imposes it and as a seam is measured. +//! +//! **The criterion.** Two surfaces meeting along a curve are G^n there exactly when the +//! *linkage curves* crossing it — a curve on one surface continued by a curve on the other — are +//! G^n curves (Pegna & Wolter, "Geometrical criteria to guarantee curvature continuity of blend +//! surfaces", J. Mech. Des. 114, 1992, for n = 2; Hermann, Lukács & Wolter, "Geometrical +//! criteria on the higher order smoothness of composite surfaces", CAGD 16, 1999, for any n). +//! In a form that needs no reparameterisation: write the neighbour, near a point `p` of the +//! curve, as a height `H` over its tangent plane along its unit normal `n`, +//! `q = p + x + H(x)·n` for `x` in the tangent plane, so that `H(0) = 0` and `∇H(0) = 0`. A +//! curve `c(σ)` from `p` lies on a surface meeting the neighbour with G^n exactly when its height +//! above the neighbour, `n·(c(σ) − p) − H(x(σ))` with `x(σ)` the part of `c(σ) − p` in the +//! tangent plane, vanishes to order `n` in σ. With `H(x) = Σ_{m ≥ 2} H_m(x) / m!` (`H_m` the +//! m-th derivative of `H` at `p`, a form of degree m) and `x(σ) = Σ_j x_j σʲ / j!` +//! (`x_j` the tangent-plane part of `c⁽ʲ⁾`), the condition of order `k` is +//! +//! `n·c⁽ᵏ⁾ = k! · [σᵏ] Σ_{m=2}^{k} H_m(x(σ)) / m!`, +//! +//! whose right-hand side reads `c′ … c⁽ᵏ⁻¹⁾` only: order 1 is `n·c′ = 0` (the tangent plane), +//! order 2 `n·c″ = H₂(x₁)` (the normal curvature in the curve's direction), order 3 +//! `n·c‴ = 3·H₂(x₁, x₂) + H₃(x₁)` (the rate of change of that curvature), and order 4 its rate of +//! change in turn. For a unit `a`, `H₂(a)` is the curvature of the normal section along `a` and +//! `H₃(a)`, `H₄(a)` are its first and second derivatives by arc length. +//! +//! **The jet.** [`surface_jet`] reads `H₂ … H_n` off a surface record's exact partial +//! derivatives: along a tangent vector `a`, the curve on the surface whose foot in the tangent +//! plane runs straight along `a` at unit rate has `n·γ⁽ᵐ⁾(0) = H_m(a)`; its parameter series +//! `(u(τ), v(τ))` is found order by order (the part of each coefficient of `S(u(τ), v(τ))` in the +//! tangent plane is `a`, then zero), and `H_m` as a binary form from its values along +//! `t + λ·w` at `m + 1` values of λ (a polynomial of degree m in λ, so exactly). +//! +//! Input is hostile: orders are capped at [`MAX_CONTINUITY`], and every evaluation is checked. + +use crate::brep::eval::SurfaceEval; +use crate::prelude::*; +use crate::tess::partials::{MAX_PARTIAL_ORDER, Partials}; +use solidcore_record::Vec3; + +/// The highest continuity order handled: G4, the highest order of the surfaces' exact partials. +pub const MAX_CONTINUITY: usize = MAX_PARTIAL_ORDER; + +/// A surface near a point as a height over its tangent plane, to order `order` (2 … 4): the +/// forms `H_m` for `m = 2 ..= order` on the frame `t = n × w`, `w` (both unit, in the tangent +/// plane; `w` the direction the surface leaves the shared curve in). `forms[m − 2][j]` is the +/// coefficient of `x_t^(m−j)·x_w^j` in `H_m(x)`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Jet { + pub order: usize, + pub forms: [[f64; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1], +} + +impl Jet { + /// `H_m(a)` for a tangent vector given by its components `(a_t, a_w)`. + pub fn form(&self, m: usize, a: [f64; 2]) -> Option { + let coefficients = self.forms.get(m.checked_sub(2)?).filter(|_| (2..=self.order).contains(&m))?; + Some((0..=m).map(|j| coefficients.get(j).copied().unwrap_or(0.0) * a[0].powi((m - j) as i32) * a[1].powi(j as i32)).sum()) + } + + /// Whether every coefficient is finite. + pub fn is_finite(&self) -> bool { + self.forms.iter().flatten().all(|x| x.is_finite()) + } + + /// What orders `2 ..= self.order` ask of `n·c⁽ᵏ⁾` (module docs), for a curve whose first + /// derivatives have the tangent-plane components `x[j − 1] = (x_j·t, x_j·w)`: element + /// `k − 2` is order k's (it reads `x[0 .. k − 1]`). `None` when too few derivatives are given. + pub fn targets(&self, x: &[[f64; 2]]) -> Option> { + Some(self.linearised(x)?.into_iter().map(|t| t.value).collect()) + } + + /// [`Jet::targets`] with their exact gradients: element `k − 2` is order k's target and its + /// derivative with respect to each component of each `x_j` (`gradient[j − 1]`), so that the + /// condition `n·c⁽ᵏ⁾ = target(x)` can be linearised about a curve (Newton's method). + pub fn linearised(&self, x: &[[f64; 2]]) -> Option> { + let top = self.order; + if x.len() + 1 < top || top > MAX_CONTINUITY { + return None; + } + // x(σ) as truncated Taylor series in each component (no constant term), each coefficient + // a dual number seeded with its own component. + let mut series = [vec![Dual::ZERO; top + 1], vec![Dual::ZERO; top + 1]]; + for (j, xj) in x.iter().enumerate().take(top.saturating_sub(1)) { + for (c, (s, value)) in series.iter_mut().zip(xj).enumerate() { + if let Some(slot) = s.get_mut(j + 1) { + *slot = Dual::seed(*value, 2 * j + c).scale(1.0 / factorial(j + 1)); + } + } + } + let mut height = vec![Dual::ZERO; top + 1]; + for m in 2..=top { + let coefficients = self.forms.get(m - 2)?; + for (j, c) in coefficients.iter().enumerate().take(m + 1) { + let monomial = mul(&power(&series[0], m - j, top), &power(&series[1], j, top), top); + for (h, x) in height.iter_mut().zip(&monomial) { + *h = *h + x.scale(c / factorial(m)); + } + } + } + Some( + (2..=top) + .map(|k| { + let d = height.get(k).copied().unwrap_or(Dual::ZERO).scale(factorial(k)); + let mut gradient = [[0.0; 2]; MAX_CONTINUITY - 1]; + for (j, g) in gradient.iter_mut().enumerate() { + *g = [d.grad[2 * j], d.grad[2 * j + 1]]; + } + Target { value: d.value, gradient } + }) + .collect(), + ) + } +} + +/// One order's target and its gradient (see [`Jet::linearised`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Target { + pub value: f64, + /// `gradient[j − 1]`: the derivative with respect to `(x_j·t, x_j·w)`. + pub gradient: [[f64; 2]; MAX_CONTINUITY - 1], +} + +/// Gradients carried: two components of each of `x₁ … x₃`. +const SEEDS: usize = 2 * (MAX_CONTINUITY - 1); + +/// A number with its gradient with respect to the [`SEEDS`] components (forward differentiation: +/// the targets are polynomials in them, so the gradient is exact). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Dual { + value: f64, + grad: [f64; SEEDS], +} + +impl Dual { + const ZERO: Dual = Dual { value: 0.0, grad: [0.0; SEEDS] }; + const ONE: Dual = Dual { value: 1.0, grad: [0.0; SEEDS] }; + + fn seed(value: f64, at: usize) -> Dual { + let mut grad = [0.0; SEEDS]; + if let Some(g) = grad.get_mut(at) { + *g = 1.0; + } + Dual { value, grad } + } + + fn scale(self, k: f64) -> Dual { + Dual { value: self.value * k, grad: self.grad.map(|g| g * k) } + } +} + +impl std::ops::Add for Dual { + type Output = Dual; + fn add(self, o: Dual) -> Dual { + let mut grad = self.grad; + for (g, h) in grad.iter_mut().zip(o.grad) { + *g += h; + } + Dual { value: self.value + o.value, grad } + } +} + +impl std::ops::Mul for Dual { + type Output = Dual; + fn mul(self, o: Dual) -> Dual { + let mut grad = [0.0; SEEDS]; + for ((g, a), b) in grad.iter_mut().zip(self.grad).zip(o.grad) { + *g = a * o.value + self.value * b; + } + Dual { value: self.value * o.value, grad } + } +} + +/// `k!` as a float (small k). +fn factorial(k: usize) -> f64 { + (1..=k).map(|i| i as f64).product() +} + +/// The numbers the series below are over: plain floats and [`Dual`]s. +trait Coefficient: Copy + std::ops::Add + std::ops::Mul { + const ZERO: Self; + const ONE: Self; +} + +impl Coefficient for f64 { + const ZERO: f64 = 0.0; + const ONE: f64 = 1.0; +} + +impl Coefficient for Dual { + const ZERO: Dual = Dual::ZERO; + const ONE: Dual = Dual::ONE; +} + +/// The product of two truncated series (coefficients of `σ⁰ … σ^top`). +fn mul(a: &[T], b: &[T], top: usize) -> Vec { + let mut out = vec![T::ZERO; top + 1]; + for (i, x) in a.iter().enumerate().take(top + 1) { + for (j, y) in b.iter().enumerate().take(top + 1 - i) { + if let Some(slot) = out.get_mut(i + j) { + *slot = *slot + *x * *y; + } + } + } + out +} + +/// A truncated series to the power `e`. +fn power(a: &[T], e: usize, top: usize) -> Vec { + let mut one = vec![T::ZERO; top + 1]; + if let Some(c) = one.first_mut() { + *c = T::ONE; + } + (0..e).fold(one, |acc, _| mul(&acc, a, top)) +} + +/// The surface `s` near `uv` as a height along its unit normal `n` (either sign) over its tangent +/// plane, to order `order` (2 ..= [`MAX_CONTINUITY`]), on the frame `t = n × w`, `w` (`w` a unit +/// tangent vector): see [`Jet`] and the module docs. `None` where the surface has no tangent +/// plane (a pole) or cannot be evaluated. +pub fn surface_jet(s: &SurfaceEval, uv: [f64; 2], n: Vec3, w: Vec3, order: usize) -> Option { + if !(2..=MAX_CONTINUITY).contains(&order) { + return None; + } + let d = s.partials(uv[0], uv[1])?; + let t = n.cross(w); + let mut forms = [[0.0; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1]; + // H_m(t + λ w) is a polynomial of degree m in λ: its coefficients are the form's. + const NODES: [f64; MAX_CONTINUITY + 1] = [0.0, 1.0, -1.0, 2.0, -2.0]; + let along: Vec> = NODES.iter().map(|l| heights(&d, n, t + w * *l, order)).collect::>()?; + for m in 2..=order { + let values: Vec = along.iter().take(m + 1).map(|h| h.get(m).copied().unwrap_or(f64::NAN)).collect(); + let coefficients = polynomial_through(NODES.get(..=m)?, &values)?; + let slot = forms.get_mut(m - 2)?; + for (x, c) in slot.iter_mut().zip(coefficients) { + *x = c; + } + } + let jet = Jet { order, forms }; + jet.is_finite().then_some(jet) +} + +/// `H_m(a)` for `m = 0 ..= order` from the partials `d` (`d[i][j] = S^(i,j)`): the curve on +/// the surface whose foot runs straight along `a` (module docs), its parameter series solved +/// order by order. `None` where the tangent plane degenerates. +fn heights(d: &Partials, n: Vec3, a: Vec3, order: usize) -> Option> { + let at = |i: usize, j: usize| d.get(i).and_then(|r| r.get(j)).copied(); + let (su, sv) = (at(1, 0)?, at(0, 1)?); + let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv)); + let det = e * g - f * f; + // A pole: one parameter direction collapses against the other (or the two run together). + if !(e.min(g) > 1e-20 * e.max(g) && det > 1e-12 * e * g) { + return None; + } + // The rates (du, dv) whose image S_u du + S_v dv has tangent-plane part `b`. + let rates = |b: Vec3| { + let (bu, bv) = (b.dot(su), b.dot(sv)); + ((g * bu - f * bv) / det, (e * bv - f * bu) / det) + }; + let tangential = |x: Vec3| x - n * x.dot(n); + let mut du = vec![0.0; order + 1]; + let mut dv = vec![0.0; order + 1]; + for k in 1..=order { + // The coefficient of τᵏ with this order's rates still nought, then the rates that make + // its tangent-plane part `a` (k = 1) or zero. + let have = composed(d, &du, &dv, order)?.get(k).copied()?; + let want = if k == 1 { tangential(a) } else { Vec3::ZERO }; + let (x, y) = rates(want - tangential(have)); + *du.get_mut(k)? = x; + *dv.get_mut(k)? = y; + } + let c = composed(d, &du, &dv, order)?; + Some(c.iter().enumerate().map(|(k, x)| factorial(k) * n.dot(*x)).collect()) +} + +/// The Taylor coefficients of `S(u₀ + δu(τ), v₀ + δv(τ)) − S(u₀, v₀)` to order `order`, for the +/// series `δu`, `δv` (no constant term) and the partials `d`. +fn composed(d: &Partials, du: &[f64], dv: &[f64], order: usize) -> Option> { + let mut out = vec![Vec3::ZERO; order + 1]; + for (i, row) in d.iter().enumerate() { + for (j, partial) in row.iter().enumerate() { + if i + j == 0 || i + j > order { + continue; + } + let term = mul(&power(du, i, order), &power(dv, j, order), order); + let scale = 1.0 / (factorial(i) * factorial(j)); + for (o, x) in out.iter_mut().zip(&term) { + *o += *partial * (x * scale); + } + } + } + out.iter().all(|p| p.is_finite()).then_some(out) +} + +/// The coefficients `c₀ … c_m` of the polynomial of degree `m = nodes.len() − 1` through +/// `(nodes[i], values[i])` (Newton's divided differences, expanded). +fn polynomial_through(nodes: &[f64], values: &[f64]) -> Option> { + let m = nodes.len(); + if values.len() != m || m == 0 { + return None; + } + let mut dd = values.to_vec(); + for level in 1..m { + for i in (level..m).rev() { + let span = nodes.get(i)? - nodes.get(i - level)?; + if span == 0.0 { + return None; + } + *dd.get_mut(i)? = (dd.get(i)? - dd.get(i - 1)?) / span; + } + } + // Horner on the Newton form: p(λ) = dd₀ + (λ − x₀)(dd₁ + (λ − x₁)(…)). + let mut c = vec![0.0; m]; + for i in (0..m).rev() { + // c ← c·(λ − x_i) + dd_i. + let x = *nodes.get(i)?; + let mut next = vec![0.0; m]; + for (k, ck) in c.iter().enumerate() { + if let Some(slot) = next.get_mut(k + 1) { + *slot += ck; + } + if let Some(slot) = next.get_mut(k) { + *slot -= ck * x; + } + } + if let Some(slot) = next.get_mut(0) { + *slot += dd.get(i)?; + } + c = next; + } + c.iter().all(|x| x.is_finite()).then_some(c) +} + +#[cfg(test)] +#[path = "linkage_tests.rs"] +mod tests; diff --git a/crates/geom/src/linkage_tests.rs b/crates/geom/src/linkage_tests.rs new file mode 100644 index 000000000..3bcbfae26 --- /dev/null +++ b/crates/geom/src/linkage_tests.rs @@ -0,0 +1,95 @@ +use super::*; +use solidcore_record::brep::{Frame, Surface}; + +fn frame() -> Frame { + Frame { origin: [1.0, -2.0, 0.5], x_axis: [1.0, 0.0, 0.0], y_axis: [0.0, 1.0, 0.0] } +} + +/// A sphere of radius `r` as a height over its tangent plane along the outward normal: +/// `H(x) = √(r² − |x|²) − r`, so `H₂(a) = −|a|²/r`, `H₃ = 0`, `H₄(a) = −3|a|⁴/r³`. +#[test] +fn a_sphere_is_a_height_whose_forms_are_its_radius_s() { + let r = 7.0; + let s = SurfaceEval::new(&Surface::Sphere { frame: frame(), radius: r }).unwrap(); + for uv in [[0.3, 0.2], [2.0, -0.9], [4.5, 1.1]] { + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + let n = su.cross(sv).normalized().unwrap(); + let w = (su + sv * 0.5).normalized().unwrap(); + let jet = surface_jet(&s, uv, n, w, 4).unwrap(); + for (a, len2) in [([1.0, 0.0], 1.0), ([0.0, 1.0], 1.0), ([1.0, 1.0], 2.0), ([0.6, -0.8], 1.0)] { + assert!((jet.form(2, a).unwrap() + len2 / r).abs() < 1e-12, "H2 at {uv:?} along {a:?}"); + assert!(jet.form(3, a).unwrap().abs() < 1e-11, "H3 at {uv:?} along {a:?}"); + assert!((jet.form(4, a).unwrap() + 3.0 * len2 * len2 / r.powi(3)).abs() < 1e-11, "H4 at {uv:?} along {a:?}"); + } + } +} + +/// A cylinder bends across its axis only: the height depends on the component round it, as the +/// circle's `√(r² − x²) − r` does; along its axis it is straight. +#[test] +fn a_cylinder_bends_round_its_axis_and_not_along_it() { + let r = 4.0; + let s = SurfaceEval::new(&Surface::Cylinder { frame: frame(), radius: r }).unwrap(); + let uv = [0.7, 3.0]; + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + let n = su.cross(sv).normalized().unwrap(); + // w along the axis: t = n × w runs round the cylinder. + let jet = surface_jet(&s, uv, n, sv.normalized().unwrap(), 4).unwrap(); + let around = [1.0, 0.0]; + assert!((jet.form(2, around).unwrap().abs() - 1.0 / r).abs() < 1e-12); + assert!((jet.form(4, around).unwrap().abs() - 3.0 / r.powi(3)).abs() < 1e-11); + for m in 2..=4 { + assert!(jet.form(m, [0.0, 1.0]).unwrap().abs() < 1e-12, "straight along the axis: H{m}"); + } +} + +/// The same cylinder on its NURBS form (rational quadratic arcs, as SMLib holds it) has the same +/// jet: the height is the surface's, whatever its parameterisation. +#[test] +fn a_cylinder_and_its_nurbs_form_have_one_jet() { + let label = Surface::Cylinder { frame: frame(), radius: 4.0 }; + let (form, _) = crate::brep::form::surface(&label, [[0.0, 2.0], [-1.0, 5.0]]).unwrap(); + let (a, b) = (SurfaceEval::new(&label).unwrap(), SurfaceEval::new(&form).unwrap()); + let p = a.point([0.9, 2.0]).unwrap(); + let uv = b.project(p, None, 1e-9).unwrap(); + let (_, su, sv) = a.derivs(0.9, 2.0).unwrap(); + let n = su.cross(sv).normalized().unwrap(); + let w = (su.normalized().unwrap() * 0.6 + sv * 0.8).normalized().unwrap(); + let (ja, jb) = (surface_jet(&a, [0.9, 2.0], n, w, 4).unwrap(), surface_jet(&b, uv, n, w, 4).unwrap()); + for m in 2..=4 { + for x in [[1.0, 0.0], [0.0, 1.0], [0.3, 0.7]] { + let (fa, fb) = (ja.form(m, x).unwrap(), jb.form(m, x).unwrap()); + assert!((fa - fb).abs() < 1e-9 * fa.abs().max(1.0), "H{m}({x:?}): {fa} vs {fb}"); + } + } +} + +/// The targets are the linkage conditions: order 2 the form in the curve's direction, order 3 +/// `3·H₂(x₁, x₂) + H₃(x₁)`. +#[test] +fn the_targets_are_the_height_s_taylor_terms_along_the_curve() { + let mut forms = [[0.0; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1]; + forms[0] = [2.0, 0.5, -1.0, 0.0, 0.0]; + forms[1] = [0.3, -0.2, 0.1, 0.7, 0.0]; + let jet = Jet { order: 3, forms }; + let (x1, x2) = ([0.8, 0.4], [0.1, -0.5]); + let got = jet.targets(&[x1, x2]).unwrap(); + let h2 = |a: [f64; 2], b: [f64; 2]| 2.0 * a[0] * b[0] + 0.25 * (a[0] * b[1] + a[1] * b[0]) - a[1] * b[1]; + assert!((got[0] - h2(x1, x1)).abs() < 1e-14); + assert!((got[1] - (3.0 * h2(x1, x2) + jet.form(3, x1).unwrap())).abs() < 1e-14); + assert!(jet.targets(&[x1]).is_none(), "order 3 reads c″"); +} + +#[test] +fn hostile_orders_and_degenerate_points_are_refused() { + let s = SurfaceEval::new(&Surface::Sphere { frame: frame(), radius: 2.0 }).unwrap(); + let (n, w) = (Vec3::Z, Vec3::X); + assert!(surface_jet(&s, [0.0, 0.0], Vec3::X, Vec3::Y, 5).is_none()); + assert!(surface_jet(&s, [0.0, 0.0], Vec3::X, Vec3::Y, 1).is_none()); + // At the pole the latitude's parameterisation has no tangent plane. + assert!(surface_jet(&s, [0.0, std::f64::consts::FRAC_PI_2], n, w, 2).is_none()); + assert!(surface_jet(&s, [f64::NAN, 0.0], n, w, 2).is_none()); + let jet = Jet { order: 2, forms: [[f64::NAN; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1] }; + assert!(!jet.is_finite()); + assert!(jet.form(3, [1.0, 0.0]).is_none(), "beyond its order"); +} diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 3a0bd9509..c28294fad 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -1,6 +1,7 @@ +use crate::prelude::*; use serde::{Deserialize, Serialize}; -use crate::Vec3; +use solidcore_record::Vec3; /// Axis-aligned bounding box. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] @@ -600,33 +601,10 @@ impl Mesh { self.edges.extend(o.edges.iter().cloned()); } - /// Number of triangles a ray crosses (for inside/outside tests on closed meshes). + /// Number of triangles a ray crosses (for inside/outside tests on closed meshes), each + /// crossing counted once ([`ray_crosses`]). pub fn ray_crossings(&self, o: Vec3, dir: Vec3) -> usize { - let mut n = 0; - for t in &self.triangles { - let Some([a, b, c]) = self.tri(t) else { continue }; - let (e1, e2) = (b - a, c - a); - let p = dir.cross(e2); - let det = e1.dot(p); - if det.abs() < 1e-14 { - continue; - } - let inv = 1.0 / det; - let s = o - a; - let u = s.dot(p) * inv; - if !(0.0..1.0).contains(&u) { - continue; - } - let q = s.cross(e1); - let v = dir.dot(q) * inv; - if v < 0.0 || u + v >= 1.0 { - continue; - } - if e2.dot(q) * inv > 0.0 { - n += 1; - } - } - n + self.triangles.iter().filter_map(|t| self.tri(t)).filter(|&[a, b, c]| ray_crosses(a, b, c, o, dir)).count() } /// Point inside a closed mesh (majority vote of three skewed rays). @@ -854,33 +832,11 @@ impl InsideIndex<'_> { return 0; } let Some(list) = g.cells.get(gx * g.n.1 + gy) else { return 0 }; - let dir = g.dir; - let mut n = 0; - for &i in list { - let Some(t) = self.mesh.triangles.get(i as usize) else { continue }; - let Some([a, b, c]) = self.mesh.tri(t) else { continue }; - let (e1, e2) = (b - a, c - a); - let p = dir.cross(e2); - let det = e1.dot(p); - if det.abs() < 1e-14 { - continue; - } - let inv = 1.0 / det; - let s = o - a; - let u = s.dot(p) * inv; - if !(0.0..1.0).contains(&u) { - continue; - } - let q = s.cross(e1); - let v = dir.dot(q) * inv; - if v < 0.0 || u + v >= 1.0 { - continue; - } - if e2.dot(q) * inv > 0.0 { - n += 1; - } - } - n + list.iter() + .filter_map(|&i| self.mesh.triangles.get(i as usize)) + .filter_map(|t| self.mesh.tri(t)) + .filter(|&[a, b, c]| ray_crosses(a, b, c, o, g.dir)) + .count() } /// Same answer as `Mesh::contains`. @@ -888,3 +844,23 @@ impl InsideIndex<'_> { self.rays.iter().filter(|g| self.crossings(g, p) % 2 == 1).count() >= 2 } } + +/// Whether the ray from `o` along `dir` crosses the triangle `a b c` in front of `o`. Watertight: +/// a ray through an edge two triangles share crosses exactly one of them. Each edge's side of the +/// ray is the signed volume `dir · ((p - o) × (q - o))`, exactly antisymmetric in floating point +/// (swapping `p` and `q` negates every rounded term), so both triangles see one value with +/// opposite signs; a ray exactly on the edge's line is put on one side by the edge's endpoints +/// in lexicographic order, the same for both. A triangle the ray runs along is not crossed. +fn ray_crosses(a: Vec3, b: Vec3, c: Vec3, o: Vec3, dir: Vec3) -> bool { + let side = |p: Vec3, q: Vec3| { + let v = dir.dot((p - o).cross(q - o)); + if v != 0.0 { v > 0.0 } else { (p.x, p.y, p.z) < (q.x, q.y, q.z) } + }; + let normal = (b - a).cross(c - a); + let along = dir.dot(normal); + if along == 0.0 || !along.is_finite() { + return false; + } + let s = side(a, b); + side(b, c) == s && side(c, a) == s && (a - o).dot(normal) / along > 0.0 +} diff --git a/crates/geom/src/mesh_distance.rs b/crates/geom/src/mesh_distance.rs index 31653917a..c125add85 100644 --- a/crates/geom/src/mesh_distance.rs +++ b/crates/geom/src/mesh_distance.rs @@ -4,7 +4,9 @@ //! rather than the product of the triangle counts. use crate::compare::closest_on_triangle; -use crate::{Aabb3, Bvh, Mesh, Vec3}; +use crate::prelude::*; +use crate::{Aabb3, Bvh, Mesh}; +use solidcore_record::Vec3; /// A mesh's triangles with their B-rep faces, indexed for distance queries. #[derive(Clone, Debug, Default)] diff --git a/crates/geom/src/network.rs b/crates/geom/src/network.rs index 06ecd688f..d9359479d 100644 --- a/crates/geom/src/network.rs +++ b/crates/geom/src/network.rs @@ -50,9 +50,10 @@ //! Input is hostile: sizes are capped, every evaluation is checked, and failures are //! [`SplineError`]s naming the curves; nothing here panics. -use crate::Vec3; use crate::bspline::{NurbsSurface, SplineError, SplineResult, invalid}; +use crate::prelude::*; use crate::spline_space::{Cond, Interpolant, Linear, Monotone, Space, embed}; +use solidcore_record::Vec3; /// Most curves in one direction of a network. pub const MAX_NETWORK_CURVES: usize = 32; diff --git a/crates/geom/src/paper.rs b/crates/geom/src/paper.rs index 44d10a3ec..b54c89a5e 100644 --- a/crates/geom/src/paper.rs +++ b/crates/geom/src/paper.rs @@ -55,6 +55,7 @@ //! number finite and at most 1e5 mm in size. A fill is kept or dropped whole: one crossing its //! clip's edge isn't supported yet. +use crate::prelude::*; use serde::{Deserialize, Serialize}; use std::borrow::Cow; @@ -62,7 +63,8 @@ use std::collections::BTreeMap; use std::f64::consts::FRAC_PI_2; use crate::pixel_grid::{GridWindow, PixelGrid, PixelGridError}; -use crate::{Aabb2, EPS, Region2, Seg2, Vec2}; +use crate::{Aabb2, EPS}; +use solidcore_record::{Region2, Seg2, Vec2}; pub mod annotate; pub mod clip; diff --git a/crates/geom/src/paper/annotate.rs b/crates/geom/src/paper/annotate.rs index 2175038b8..f39f19a95 100644 --- a/crates/geom/src/paper/annotate.rs +++ b/crates/geom/src/paper/annotate.rs @@ -15,7 +15,8 @@ use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI}; use std::ops::RangeInclusive; use super::{Invalid, Item, MAX_COORDINATE_MM, MAX_SIDE_MM, Result, require}; -use crate::{Loop2, Region2, Seg2, Vec2}; +use crate::prelude::*; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; /// A leader's dot on a surface, in line widths across (ISO 128-2 clause 9). pub const DOT_PER_LINE_WIDTH: f64 = 5.0; diff --git a/crates/geom/src/paper/clip.rs b/crates/geom/src/paper/clip.rs index 447c57cad..f6c7b89a8 100644 --- a/crates/geom/src/paper/clip.rs +++ b/crates/geom/src/paper/clip.rs @@ -26,7 +26,9 @@ use std::f64::consts::TAU; use super::{Clip, Dashes, Group, Invalid, Item, Result, meet}; -use crate::{Aabb2, EPS, Region2, Seg2, Vec2}; +use crate::prelude::*; +use crate::{Aabb2, EPS}; +use solidcore_record::{Region2, Seg2, Vec2}; /// How closely a curve's crossing of a clip's edge is found: the span of its last part's control /// points, in millimetres. diff --git a/crates/geom/src/paper/clip_tests.rs b/crates/geom/src/paper/clip_tests.rs index d32ae8994..0637b4f18 100644 --- a/crates/geom/src/paper/clip_tests.rs +++ b/crates/geom/src/paper/clip_tests.rs @@ -2,7 +2,8 @@ use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI}; use super::super::{Clip, Dashes, Group, Invalid, Item, ObjectKind, Scene}; use crate::bspline::tests::Lcg; -use crate::{Seg2, Vec2}; +use crate::prelude::*; +use solidcore_record::{Seg2, Vec2}; fn p(x: f64, y: f64) -> Vec2 { Vec2::new(x, y) @@ -204,8 +205,8 @@ fn what_cant_be_clipped_is_refused() { /// clip, isn't cut yet. #[test] fn a_fill_is_kept_or_dropped_whole() { - let square = |x0: f64, y0: f64, x1: f64, y1: f64| crate::Loop2::polygon(&[p(x0, y0), p(x1, y0), p(x1, y1), p(x0, y1)]); - let fill = |outer, holes| Item::Fill { region: crate::Region2 { outer, holes } }; + let square = |x0: f64, y0: f64, x1: f64, y1: f64| solidcore_record::Loop2::polygon(&[p(x0, y0), p(x1, y0), p(x1, y1), p(x0, y1)]); + let fill = |outer, holes| Item::Fill { region: solidcore_record::Region2 { outer, holes } }; let crossing = "not supported yet: a fill crossing a clip's edge (#4890 A8)"; for clip in [rect(0.0, 0.0, 10.0, 10.0), Clip::Circle { center: p(5.0, 5.0), radius: 7.5 }] { for (item, kept) in [ @@ -213,7 +214,7 @@ fn a_fill_is_kept_or_dropped_whole() { (fill(square(20.0, 20.0, 30.0, 30.0), vec![]), Some(false)), // Round the clip, its hole round it too: wholly outside. (fill(square(-20.0, -20.0, 30.0, 30.0), vec![square(-15.0, -15.0, 25.0, 25.0)]), Some(false)), - (fill(crate::Loop2::polygon(&[p(8.0, 5.0), p(30.0, 0.0), p(30.0, 10.0)]), vec![]), None), + (fill(solidcore_record::Loop2::polygon(&[p(8.0, 5.0), p(30.0, 0.0), p(30.0, 10.0)]), vec![]), None), (fill(square(-20.0, -20.0, 30.0, 30.0), vec![]), None), ] { let scene = Scene::new(p(420.0, 297.0), vec![Group { object: 1, kind: ObjectKind::View, items: vec![item.clone()] }]); @@ -466,7 +467,8 @@ fn shapes_at_the_clips_edge_keep_exactly_what_lies_inside() { // outside, where it crosses and is refused by name; one below it, touching, is dropped whole, // unless its top edge is two EPS inside. A fill that is the clip's own rectangle is kept. let scene = |item: &Item| Scene::new(p(420.0, 297.0), vec![Group { object: 1, kind: ObjectKind::View, items: vec![item.clone()] }]); - let fill = |corners: &[Vec2]| Item::Fill { region: crate::Region2 { outer: crate::Loop2::polygon(corners), holes: vec![] } }; + let fill = + |corners: &[Vec2]| Item::Fill { region: solidcore_record::Region2 { outer: solidcore_record::Loop2::polygon(corners), holes: vec![] } }; let own = fill(&[p(10.0, 10.0), p(60.0, 10.0), p(60.0, 40.0), p(10.0, 40.0)]); assert_eq!(groups_cut(&scene(&own), &[(1, rect_clip)]).ok().map(|groups| groups[0].items.clone()), Some(vec![own.clone()])); for s in offsets { diff --git a/crates/geom/src/paper/cubic_pieces.rs b/crates/geom/src/paper/cubic_pieces.rs index 0dfd8430b..852e5c8a5 100644 --- a/crates/geom/src/paper/cubic_pieces.rs +++ b/crates/geom/src/paper/cubic_pieces.rs @@ -19,7 +19,8 @@ //! to [`MAX_CUBICS`] pieces: past that the curve is refused, never drawn coarser. use super::{Invalid, Result, require}; -use crate::{Seg2, Vec2}; +use crate::prelude::*; +use solidcore_record::{Seg2, Vec2}; /// The most cubics one curve may become. pub const MAX_CUBICS: usize = 4096; diff --git a/crates/geom/src/paper/cubic_pieces_tests.rs b/crates/geom/src/paper/cubic_pieces_tests.rs index b4199bcd7..66a8c836c 100644 --- a/crates/geom/src/paper/cubic_pieces_tests.rs +++ b/crates/geom/src/paper/cubic_pieces_tests.rs @@ -4,7 +4,7 @@ use std::f64::consts::FRAC_1_SQRT_2; use super::*; -use crate::MAX_BEZIER_CTRL; +use solidcore_record::MAX_BEZIER_CTRL; fn p(x: f64, y: f64) -> Vec2 { Vec2::new(x, y) diff --git a/crates/geom/src/paper/flatten.rs b/crates/geom/src/paper/flatten.rs index ddf2aae64..8a7c1f6ff 100644 --- a/crates/geom/src/paper/flatten.rs +++ b/crates/geom/src/paper/flatten.rs @@ -10,7 +10,8 @@ //! conditioned up to the walk's quarter turns). use super::{GridPath, GridPoint, Invalid, Piece, Result}; -use crate::{Seg2, Vec2}; +use crate::prelude::*; +use solidcore_record::{Seg2, Vec2}; /// The most points one path may flatten to. pub const MAX_POINTS: usize = 1 << 20; @@ -68,8 +69,8 @@ mod tests { use std::f64::consts::{FRAC_PI_2, PI, TAU}; use super::*; - use crate::Seg2; use crate::paper::{Grid, GridItem, Group, Item, ObjectKind, Scene}; + use solidcore_record::Seg2; /// The scene's one stroke along `seg` on the nanometre grid. fn on_grid(seg: Seg2) -> GridPath { diff --git a/crates/geom/src/paper/grid.rs b/crates/geom/src/paper/grid.rs index a87905725..cb7b7a1dd 100644 --- a/crates/geom/src/paper/grid.rs +++ b/crates/geom/src/paper/grid.rs @@ -22,7 +22,9 @@ use super::cubic_pieces::cubic_pieces; use super::{Clip, Invalid, Item, ObjectKind, Picture, Prepared, Result, arc_pieces, require}; -use crate::{Aabb2, Seg2, Vec2}; +use crate::Aabb2; +use crate::prelude::*; +use solidcore_record::{Seg2, Vec2}; /// The largest number put on a grid, in millimetres either way: far past any scene's 2e5. const MAX_NUMBER_MM: f64 = 9e9; diff --git a/crates/geom/src/paper/text.rs b/crates/geom/src/paper/text.rs index 07f0590b3..12d2cadba 100644 --- a/crates/geom/src/paper/text.rs +++ b/crates/geom/src/paper/text.rs @@ -36,7 +36,9 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use super::{Budget, Invalid, MAX_COORDINATE_MM, Result, Scene, pieces, require}; -use crate::{EPS, Loop2, Seg2, Vec2}; +use crate::EPS; +use crate::prelude::*; +use solidcore_record::{Loop2, Seg2, Vec2}; /// The most glyphs a run may place: sketch text's 1000 characters, four glyphs each. pub const MAX_RUN_GLYPHS: usize = 4000; diff --git a/crates/geom/src/paper_tests.rs b/crates/geom/src/paper_tests.rs index 34079863e..c2ae6f6b1 100644 --- a/crates/geom/src/paper_tests.rs +++ b/crates/geom/src/paper_tests.rs @@ -3,7 +3,7 @@ use std::f64::consts::{FRAC_PI_2, PI, TAU}; use serde_json::json; use super::*; -use crate::{Loop2, MAX_BEZIER_CTRL}; +use solidcore_record::{Loop2, MAX_BEZIER_CTRL}; fn p(x: f64, y: f64) -> Vec2 { Vec2::new(x, y) diff --git a/crates/geom/src/pixel_grid.rs b/crates/geom/src/pixel_grid.rs index 8132f6927..309636145 100644 --- a/crates/geom/src/pixel_grid.rs +++ b/crates/geom/src/pixel_grid.rs @@ -16,7 +16,8 @@ //! image of the sheet is drawn, and a picture on the sheet is drawn into its window of that grid //! ([`PixelGrid::window`]), so placing it is a copy of whole pixels. -use crate::{Aabb2, Vec2}; +use crate::Aabb2; +use solidcore_record::Vec2; /// The longest side a grid may have, in pixels. pub const MAX_SIDE_PX: u32 = 65_536; diff --git a/crates/geom/src/plane.rs b/crates/geom/src/plane.rs index a668e5ae0..af4d1f6a8 100644 --- a/crates/geom/src/plane.rs +++ b/crates/geom/src/plane.rs @@ -1,83 +1,68 @@ -use serde::{Deserialize, Serialize}; +use solidcore_record::{Plane, Vec2, Vec3}; -use crate::{Vec2, Vec3}; +use crate::Vec3Geom; -/// A sketch plane: an origin and two orthonormal in-plane axes. The normal is `x × y`. -/// -/// World point of sketch point `(u, v)` = `origin + u·x + v·y`. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct Plane { - pub origin: Vec3, - #[serde(rename = "x_dir")] - pub x: Vec3, - #[serde(rename = "y_dir")] - pub y: Vec3, +/// The geometry of a sketch plane ([`Plane`]): made from directions, and mapping points to and +/// from it. +// `new` makes a plane, or none from degenerate axes. +#[allow(clippy::new_ret_no_self)] +pub trait PlaneGeom { + /// Plane through `origin` with the given axes, re-orthonormalised. `None` if degenerate. + fn new(origin: Vec3, x: Vec3, y: Vec3) -> Option; + /// Plane through `origin` with normal `n` (in-plane axes chosen deterministically). + fn from_normal(origin: Vec3, n: impl Into) -> Option; + /// The same plane seen from its other side: a half turn about the sketch x axis (y + /// reversed), or about the y axis (x reversed) when `about_y`. Still right-handed. + fn flipped(&self, about_y: bool) -> Plane; + fn normal(&self) -> Vec3; + fn to_world(&self, p: Vec2) -> Vec3; + fn dir_to_world(&self, d: Vec2) -> Vec3; + fn to_local(&self, p: Vec3) -> Vec2; + /// Signed distance of `p` above the plane (along the normal). + fn height(&self, p: Vec3) -> f64; + /// The plane moved along its normal by `d`. + fn offset(&self, d: f64) -> Plane; + /// Intersection of the ray `o + t·dir` with the plane (t may be negative). + fn intersect_ray(&self, o: Vec3, dir: Vec3) -> Option; } -impl Plane { - /// Top: sketch x = +X, y = +Y, normal +Z. - pub const XY: Plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Y }; - /// Front: sketch x = +X, y = −Z, normal +Y. - pub const XZ: Plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::new(0.0, 0.0, -1.0) }; - /// Right: sketch x = +Y, y = +Z, normal +X. - pub const YZ: Plane = Plane { origin: Vec3::ZERO, x: Vec3::Y, y: Vec3::Z }; - - /// Plane through `origin` with the given axes, re-orthonormalised. `None` if degenerate. - pub fn new(origin: Vec3, x: Vec3, y: Vec3) -> Option { +impl PlaneGeom for Plane { + fn new(origin: Vec3, x: Vec3, y: Vec3) -> Option { let x = x.normalized()?; let n = x.cross(y).normalized()?; let y = n.cross(x).normalized()?; origin.is_finite().then_some(Plane { origin, x, y }) } - - /// Plane through `origin` with normal `n` (in-plane axes chosen deterministically). - pub fn from_normal(origin: Vec3, n: impl Into) -> Option { + fn from_normal(origin: Vec3, n: impl Into) -> Option { let n = n.into().normalized()?; // Horizontal planes keep world X as sketch x; others use the horizontal direction Z × n. let cand = if n.dot(Vec3::Z).abs() > 0.9 { Vec3::X } else { Vec3::Z.cross(n) }; let x = (cand - n * cand.dot(n)).normalized()?; Plane::new(origin, x, n.cross(x)) } - - /// The same plane seen from its other side: a half turn about the sketch x axis (y - /// reversed), or about the y axis (x reversed) when `about_y`. Still right-handed. - pub fn flipped(&self, about_y: bool) -> Plane { + fn flipped(&self, about_y: bool) -> Plane { if about_y { Plane { x: -self.x, ..*self } } else { Plane { y: -self.y, ..*self } } } - - /// Named origin plane: `XY`, `XZ`, `YZ` (case-insensitive). - pub fn named(name: &str) -> Option { - match name.to_ascii_uppercase().as_str() { - "XY" | "TOP" => Some(Plane::XY), - "XZ" | "FRONT" => Some(Plane::XZ), - "YZ" | "RIGHT" => Some(Plane::YZ), - _ => None, - } - } - - pub fn normal(&self) -> Vec3 { + fn normal(&self) -> Vec3 { self.x.cross(self.y) } - pub fn to_world(&self, p: Vec2) -> Vec3 { + fn to_world(&self, p: Vec2) -> Vec3 { self.origin + self.x * p.x + self.y * p.y } - pub fn dir_to_world(&self, d: Vec2) -> Vec3 { + fn dir_to_world(&self, d: Vec2) -> Vec3 { self.x * d.x + self.y * d.y } - pub fn to_local(&self, p: Vec3) -> Vec2 { + fn to_local(&self, p: Vec3) -> Vec2 { let d = p - self.origin; Vec2::new(d.dot(self.x), d.dot(self.y)) } - /// Signed distance of `p` above the plane (along the normal). - pub fn height(&self, p: Vec3) -> f64 { + fn height(&self, p: Vec3) -> f64 { (p - self.origin).dot(self.normal()) } - /// The plane moved along its normal by `d`. - pub fn offset(&self, d: f64) -> Plane { + fn offset(&self, d: f64) -> Plane { Plane { origin: self.origin + self.normal() * d, ..*self } } - /// Intersection of the ray `o + t·dir` with the plane (t may be negative). - pub fn intersect_ray(&self, o: Vec3, dir: Vec3) -> Option { + fn intersect_ray(&self, o: Vec3, dir: Vec3) -> Option { let n = self.normal(); let den = dir.dot(n); if den.abs() < 1e-12 { diff --git a/crates/geom/src/profile.rs b/crates/geom/src/profile.rs index 420ca106a..0e6d03f2f 100644 --- a/crates/geom/src/profile.rs +++ b/crates/geom/src/profile.rs @@ -1,60 +1,15 @@ -//! Planar profiles: closed loops of lines, circular arcs, cubic Béziers and conics (rational -//! quadratic Béziers), and regions (an outer loop minus holes). Sketches produce them; the -//! kernel turns them into faces. +//! The geometry of planar profiles ([`Seg2`], [`Loop2`], [`Region2`]: plain data in the +//! record): evaluation, derivatives, lengths, areas, containment, polylines and triangles. +//! Sketches produce profiles; the kernel turns them into faces. use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use serde::{Deserialize, Serialize}; +use solidcore_record::{Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, Region2, Seg2, Vec2}; -use crate::{Aabb2, Ring, Vec2}; +use crate::prelude::*; +use crate::{Aabb2, Ring}; -/// One boundary segment in sketch coordinates. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum Seg2 { - Line { - a: Vec2, - b: Vec2, - }, - /// Arc from `start` angle sweeping `sweep` radians (positive = counter-clockwise). - Arc { - center: Vec2, - radius: f64, - start: f64, - sweep: f64, - }, - /// Cubic Bézier. - Cubic { - p0: Vec2, - p1: Vec2, - p2: Vec2, - p3: Vec2, - }, - /// Rational quadratic Bézier from `a` to `b` with control `apex` of weight `w` (end - /// weights 1): exact conic arcs (ellipses, parabolas, hyperbolas). - Conic { - a: Vec2, - apex: Vec2, - b: Vec2, - w: f64, - }, - /// Bézier of degree `n` (4…[`MAX_BEZIER_DEGREE`]) over `p[0..=n]` (the rest unused): pieces of - /// higher-degree splines. - Bezier { - n: u8, - p: [Vec2; MAX_BEZIER_CTRL], - }, -} - -/// Highest degree of [`Seg2::Bezier`]: a degree-9 piece is the single Bézier a G4 blend curve -/// (`sketch.blend_curve` with `continuity: "g4"`) is made of. -pub const MAX_BEZIER_DEGREE: usize = 9; - -/// Control points a [`Seg2::Bezier`] carries: its highest degree plus one (the unused tail is -/// zero). -pub const MAX_BEZIER_CTRL: usize = MAX_BEZIER_DEGREE + 1; - -/// Highest derivative order [`Seg2::derivatives`] hands out, and therefore the highest +/// Highest derivative order [`Seg2Geom::derivatives`] hands out, and therefore the highest /// continuity order a blend curve can be built for (4 = G4). pub const MAX_DERIVATIVE_ORDER: usize = 4; @@ -85,7 +40,7 @@ impl ArcMap { /// A similarity of the plane: a point is scaled by `scale` (above 0) about the origin, turned /// `angle` radians counter-clockwise, then moved by `shift`. It keeps shapes and the direction -/// curves turn in, so an arc stays an arc ([`Seg2::similar`]). +/// curves turn in, so an arc stays an arc ([`Seg2Geom::similar`]). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Similarity2 { scale: f64, @@ -137,18 +92,18 @@ pub fn bezier(pts: &[Vec2]) -> Option { }) } -/// Smallest radius, conic weight and absolute arc sweep [`Seg2::check`] accepts. +/// Smallest radius, conic weight and absolute arc sweep [`Seg2Geom::check`] accepts. const MIN_POSITIVE: f64 = 1e-12; -/// Largest conic weight [`Seg2::check`] accepts. +/// Largest conic weight [`Seg2Geom::check`] accepts. const MAX_WEIGHT: f64 = 1e12; -/// Largest arc start angle either way, in radians, [`Seg2::check`] accepts. +/// Largest arc start angle either way, in radians, [`Seg2Geom::check`] accepts. const MAX_START_ANGLE: f64 = 1e6; fn require(condition: bool, message: &'static str) -> Result<(), &'static str> { if condition { Ok(()) } else { Err(message) } } -/// Every value finite and at most `max_abs` in size: [`Seg2::check`]'s rule for coordinates, which +/// Every value finite and at most `max_abs` in size: [`Seg2Geom::check`]'s rule for coordinates, which /// `section` applies to its planes and contacts too. pub(crate) fn coordinates(values: impl IntoIterator, max_abs: f64) -> Result<(), &'static str> { require(values.into_iter().all(|v| v.is_finite() && v.abs() <= max_abs), "non-finite or excessive coordinate") @@ -160,39 +115,6 @@ fn controls(points: &[Vec2], max_abs: f64) -> Result<(), &'static str> { require(rest.iter().any(|p| p != first), "collapsed curve") } -impl Seg2 { - /// Checks a segment read from outside before anything evaluates it: every stored coordinate - /// finite and at most `max_abs` in size (a Bézier's unused slots too, as they are serialized), - /// a radius in 1e-12..=`max_abs`, an arc's start within ±1e6 radians and its absolute sweep - /// 1e-12 to one turn (with 1e-12 radians of allowance), a conic weight in 1e-12..=1e12, a - /// Bézier degree of 4 to [`MAX_BEZIER_DEGREE`], controls not all at one point, and finite - /// ends. The limits keep evaluation finite; they promise no accuracy. The caller wraps the - /// message in its own error. - pub(crate) fn check(&self, max_abs: f64) -> Result<(), &'static str> { - match *self { - Seg2::Line { a, b } => controls(&[a, b], max_abs)?, - Seg2::Arc { center, radius, start, sweep } => { - coordinates([center.x, center.y], max_abs)?; - require(radius.is_finite() && (MIN_POSITIVE..=max_abs).contains(&radius), "arc radius")?; - require(start.is_finite() && start.abs() <= MAX_START_ANGLE, "arc start angle")?; - require(sweep.is_finite() && (MIN_POSITIVE..=TAU + 1e-12).contains(&sweep.abs()), "arc sweep")?; - } - Seg2::Cubic { p0, p1, p2, p3 } => controls(&[p0, p1, p2, p3], max_abs)?, - Seg2::Conic { a, apex, b, w } => { - controls(&[a, apex, b], max_abs)?; - require(w.is_finite() && (MIN_POSITIVE..=MAX_WEIGHT).contains(&w), "conic weight")?; - } - Seg2::Bezier { n, ref p } => { - require((4..=MAX_BEZIER_DEGREE).contains(&usize::from(n)), "Bezier degree")?; - // The unused slots are serialized too: reject hidden non-finite/excessive values. - coordinates(p.iter().flat_map(|q| [q.x, q.y]), max_abs)?; - controls(p.get(..=usize::from(n)).ok_or("Bezier degree")?, max_abs)?; - } - } - require(self.start().is_finite() && self.end().is_finite(), "non-finite curve endpoint") - } -} - /// de Casteljau: the point at `t` and the two halves' control points. fn casteljau(c: &[Vec2], t: f64) -> (Vec2, Vec, Vec) { let mut w = c.to_vec(); @@ -253,589 +175,6 @@ const GL5: [(f64, f64); 5] = [ (0.953_089_922_969_332, 0.118_463_442_528_095), ]; -impl Seg2 { - fn bez(n: u8, p: &[Vec2; MAX_BEZIER_CTRL]) -> &[Vec2] { - &p[..(n as usize).clamp(1, MAX_BEZIER_DEGREE) + 1] - } - /// Derivative with respect to the parameter at `t` (Béziers and conics; lines and arcs too). - pub fn derivative(&self, t: f64) -> Vec2 { - match *self { - Seg2::Line { a, b } => b - a, - Seg2::Arc { radius, start, sweep, .. } => Vec2::from_angle(start + sweep * t).perp() * (radius * sweep), - Seg2::Cubic { p0, p1, p2, p3 } => { - let u = 1.0 - t; - (p1 - p0) * (3.0 * u * u) + (p2 - p1) * (6.0 * u * t) + (p3 - p2) * (3.0 * t * t) - } - Seg2::Conic { a, apex, b, w } => { - let u = 1.0 - t; - let (n, d) = (a * (u * u) + apex * (2.0 * w * u * t) + b * (t * t), u * u + 2.0 * w * u * t + t * t); - let (dn, dd) = (a * (-2.0 * u) + apex * (2.0 * w * (1.0 - 2.0 * t)) + b * (2.0 * t), -2.0 * u + 2.0 * w * (1.0 - 2.0 * t) + 2.0 * t); - (dn * d - n * dd) / (d * d).max(1e-300) - } - Seg2::Bezier { n, ref p } => { - let c = Self::bez(n, p); - let diffs: Vec = c.windows(2).map(|w| (w[1] - w[0]) * (c.len() - 1) as f64).collect(); - casteljau(&diffs, t).0 - } - } - } - /// Derivatives 1…`order` with respect to the segment's own parameter at `t`, exactly: a line - /// and an arc from their analytic form (an arc's are the circular-motion recurrence, zero - /// curvature terms included), a cubic and a higher-degree piece from the forward differences - /// of their controls, a conic through the quotient rule of its rational form. A blend curve - /// reads a reference curve's derivatives here to build a Hermite interpolation, so this is - /// exact at both ends (`t` = 0 and 1) and `None` — never a wrong number — when `order` is - /// above [`MAX_DERIVATIVE_ORDER`], `t` is not finite or a value is not finite, as with a - /// degenerate rational piece. - pub fn derivatives(&self, t: f64, order: usize) -> Option> { - if !t.is_finite() || order > MAX_DERIVATIVE_ORDER { - return None; - } - let mut d = match *self { - Seg2::Line { a, b } => { - if !a.is_finite() || !b.is_finite() { - return None; - } - let mut d = vec![b - a]; - d.resize(MAX_DERIVATIVE_ORDER, Vec2::ZERO); - d - } - Seg2::Arc { center, radius, start, sweep } => { - if !center.is_finite() || !radius.is_finite() || !start.is_finite() || !sweep.is_finite() { - return None; - } - // Differentiating the radial direction twice returns its negative, so the - // directions of the successive derivatives are tangential, radial, tangential… - // with alternating signs, each order picking up one more factor of the sweep. - let mut v = Vec2::from_angle(start + sweep * t).perp(); - let mut d = Vec::with_capacity(MAX_DERIVATIVE_ORDER); - for j in 1..=MAX_DERIVATIVE_ORDER { - d.push(v * (radius * sweep.powi(j as i32))); - v = v.perp(); - } - d - } - Seg2::Cubic { p0, p1, p2, p3 } => bezier_derivatives(&[p0, p1, p2, p3], t, MAX_DERIVATIVE_ORDER)?, - Seg2::Bezier { n, ref p } => bezier_derivatives(Self::bez(n, p), t, MAX_DERIVATIVE_ORDER)?, - Seg2::Conic { a, apex, b, w } => { - if !a.is_finite() || !apex.is_finite() || !b.is_finite() || !w.is_finite() { - return None; - } - // The conic is `N(t) / d(t)` with `N` the quadratic through `a`, `w·apex`, `b` and - // `d` its weight polynomial; both are evaluated here in the power basis (at the - // ends `d` = 1, so a join is never singular). The quotient rule in its - // derivative-of-a-product form gives the higher derivatives: the numerator of - // `x⁽ʲ⁾` is `N⁽ʲ⁾` minus the terms that already use `d` and a lower `x`. - let (n0, n1, n2) = (a, apex * (2.0 * w) - a * 2.0, a - apex * (2.0 * w) + b); - let (e1, e2) = (2.0 * (w - 1.0), 2.0 * (1.0 - w)); - let quotient = |j: usize| match j { - 0 => n0 + n1 * t + n2 * (t * t), - 1 => n1 + n2 * (2.0 * t), - 2 => n2 * 2.0, - _ => Vec2::ZERO, - }; - let weight = |j: usize| match j { - 0 => 1.0 + e1 * t + e2 * (t * t), - 1 => e1 + e2 * (2.0 * t), - 2 => e2 * 2.0, - _ => 0.0, - }; - let den = weight(0); - if !(den.abs() > 1e-300) { - return None; - } - let mut x = vec![quotient(0) / den]; - for j in 1..=MAX_DERIVATIVE_ORDER { - let mut v = quotient(j); - for i in 1..=j { - v -= x[j - i] * (weight(i) * binom(j, i)); - } - x.push(v / den); - } - x.remove(0); - x - } - }; - d.truncate(order); - d.iter().all(|q| q.is_finite()).then_some(d) - } - pub fn start(&self) -> Vec2 { - match *self { - Seg2::Line { a, .. } | Seg2::Conic { a, .. } => a, - Seg2::Cubic { p0, .. } => p0, - Seg2::Bezier { p, .. } => p[0], - Seg2::Arc { center, radius, start, .. } => center + Vec2::from_angle(start) * radius, - } - } - pub fn end(&self) -> Vec2 { - match *self { - Seg2::Line { b, .. } | Seg2::Conic { b, .. } => b, - Seg2::Cubic { p3, .. } => p3, - Seg2::Bezier { n, ref p } => Self::bez(n, p).last().copied().unwrap_or(p[0]), - Seg2::Arc { center, radius, start, sweep } => center + Vec2::from_angle(start + sweep) * radius, - } - } - pub fn point_at(&self, t: f64) -> Vec2 { - match *self { - Seg2::Line { a, b } => a.lerp(b, t), - Seg2::Arc { center, radius, start, sweep } => center + Vec2::from_angle(start + sweep * t) * radius, - Seg2::Cubic { p0, p1, p2, p3 } => { - let u = 1.0 - t; - p0 * (u * u * u) + p1 * (3.0 * u * u * t) + p2 * (3.0 * u * t * t) + p3 * (t * t * t) - } - Seg2::Conic { a, apex, b, w } => { - let u = 1.0 - t; - let d = u * u + 2.0 * w * u * t + t * t; - (a * (u * u) + apex * (2.0 * w * u * t) + b * (t * t)) / d.max(1e-300) - } - Seg2::Bezier { n, ref p } => casteljau(Self::bez(n, p), t).0, - } - } - pub fn mid(&self) -> Vec2 { - self.point_at(0.5) - } - /// Unit tangent at the start (direction of travel). - pub fn start_tangent(&self) -> Vec2 { - match *self { - Seg2::Line { a, b } => (b - a).normalized().unwrap_or(Vec2::X), - Seg2::Arc { start, sweep, .. } => Vec2::from_angle(start).perp() * sweep.signum(), - Seg2::Cubic { p0, p1, p2, .. } => (p1 - p0).normalized().or_else(|| (p2 - p0).normalized()).unwrap_or(Vec2::X), - Seg2::Conic { a, apex, b, .. } => (apex - a).normalized().or_else(|| (b - a).normalized()).unwrap_or(Vec2::X), - Seg2::Bezier { n, ref p } => { - let c = Self::bez(n, p); - c.iter().skip(1).find_map(|q| (*q - c[0]).normalized()).unwrap_or(Vec2::X) - } - } - } - /// Unit tangent at the end (direction of travel). - pub fn end_tangent(&self) -> Vec2 { - match *self { - Seg2::Line { a, b } => (b - a).normalized().unwrap_or(Vec2::X), - Seg2::Arc { start, sweep, .. } => Vec2::from_angle(start + sweep).perp() * sweep.signum(), - Seg2::Cubic { p1, p2, p3, .. } => (p3 - p2).normalized().or_else(|| (p3 - p1).normalized()).unwrap_or(Vec2::X), - Seg2::Conic { a, apex, b, .. } => (b - apex).normalized().or_else(|| (b - a).normalized()).unwrap_or(Vec2::X), - Seg2::Bezier { n, ref p } => { - let c = Self::bez(n, p); - let last = c.last().copied().unwrap_or(p[0]); - c.iter().rev().skip(1).find_map(|q| (last - *q).normalized()).unwrap_or(Vec2::X) - } - } - } - pub fn reversed(&self) -> Seg2 { - match *self { - Seg2::Line { a, b } => Seg2::Line { a: b, b: a }, - Seg2::Arc { center, radius, start, sweep } => Seg2::Arc { center, radius, start: start + sweep, sweep: -sweep }, - Seg2::Cubic { p0, p1, p2, p3 } => Seg2::Cubic { p0: p3, p1: p2, p2: p1, p3: p0 }, - Seg2::Conic { a, apex, b, w } => Seg2::Conic { a: b, apex, b: a, w }, - Seg2::Bezier { n, ref p } => { - let mut q = *p; - let k = (n as usize).clamp(1, MAX_BEZIER_DEGREE); - q[..=k].reverse(); - Seg2::Bezier { n, p: q } - } - } - } - /// The segment with each control point mapped by `f`: exact for any affine map of lines, - /// Béziers and conics. An arc is returned as it is, so callers go through [`Seg2::mapped`]; only - /// a segment that holds no arc, such as a glyph's outline, takes a map that doesn't keep shapes. - pub(crate) fn map_controls(&self, f: impl Fn(Vec2) -> Vec2) -> Seg2 { - match *self { - Seg2::Line { a, b } => Seg2::Line { a: f(a), b: f(b) }, - Seg2::Cubic { p0, p1, p2, p3 } => Seg2::Cubic { p0: f(p0), p1: f(p1), p2: f(p2), p3: f(p3) }, - Seg2::Conic { a, apex, b, w } => Seg2::Conic { a: f(a), apex: f(apex), b: f(b), w }, - Seg2::Bezier { n, mut p } => { - p.iter_mut().take(usize::from(n) + 1).for_each(|q| *q = f(*q)); - Seg2::Bezier { n, p } - } - arc @ Seg2::Arc { .. } => arc, - } - } - /// The segment moved by the similarity `m`, exactly ([`Seg2::mapped`]). - pub fn similar(&self, m: &Similarity2) -> Seg2 { - self.mapped(|p| m.apply(p), ArcMap { angle: m.angle(), mirrored: false, scale: m.scale() }) - } - /// The segment under a map of the plane that keeps shapes: `f` moves its points (an arc's centre - /// and every control point), and `arc` says how it turns an arc (start `angle - start` and the - /// sweep reversed when mirrored, `angle + start` otherwise; the radius scaled). Points go - /// through `f` itself, so a map exact on points stays exact. - pub fn mapped(&self, f: impl Fn(Vec2) -> Vec2, arc: ArcMap) -> Seg2 { - let ArcMap { angle, mirrored, scale } = arc; - match *self { - Seg2::Arc { center, radius, start, sweep } => { - let (start, sweep) = if mirrored { (angle - start, -sweep) } else { (angle + start, sweep) }; - Seg2::Arc { center: f(center), radius: radius * scale, start, sweep } - } - _ => self.map_controls(f), - } - } - /// The smallest box round the piece: exact for a line and an arc, and for a curve within a - /// thousandth of a unit, read off its polyline. - pub fn bounds(&self) -> Aabb2 { - match *self { - Seg2::Line { a, b } => [a, b].into_iter().collect(), - Seg2::Arc { center, radius, start, sweep } => { - let mut bounds: Aabb2 = [self.start(), self.end()].into_iter().collect(); - let quarters = [ - (0.0, Vec2::new(1.0, 0.0)), - (FRAC_PI_2, Vec2::new(0.0, 1.0)), - (PI, Vec2::new(-1.0, 0.0)), - (3.0 * FRAC_PI_2, Vec2::new(0.0, -1.0)), - ]; - for (at, way) in quarters { - let along = if sweep >= 0.0 { at - start } else { start - at }; - if along.rem_euclid(TAU) <= sweep.abs() { - bounds.add(center + way * radius); - } - } - bounds - } - _ => self.polyline(1e-3).into_iter().collect(), - } - } - pub fn length(&self) -> f64 { - match *self { - Seg2::Line { a, b } => a.dist(b), - Seg2::Arc { radius, sweep, .. } => (radius * sweep).abs(), - Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => self.integrate(|s, t| s.derivative(t).len()), - } - } - /// The nearest to either end, in parameter, that [`Seg2::split_at`] splits a segment. - pub const MIN_SPLIT: f64 = 1e-9; - /// The segment split at parameter `t` in (0, 1), at least [`Seg2::MIN_SPLIT`] from either end - /// (same kind, exact; conic halves are re-normalised so their end weights stay 1). - pub fn split_at(&self, t: f64) -> (Seg2, Seg2) { - let t = t.clamp(Self::MIN_SPLIT, 1.0 - Self::MIN_SPLIT); - match *self { - Seg2::Line { a, b } => { - let m = a.lerp(b, t); - (Seg2::Line { a, b: m }, Seg2::Line { a: m, b }) - } - Seg2::Arc { center, radius, start, sweep } => ( - Seg2::Arc { center, radius, start, sweep: sweep * t }, - Seg2::Arc { center, radius, start: start + sweep * t, sweep: sweep * (1.0 - t) }, - ), - Seg2::Cubic { p0, p1, p2, p3 } => { - let (a, b, c) = (p0.lerp(p1, t), p1.lerp(p2, t), p2.lerp(p3, t)); - let (d, e) = (a.lerp(b, t), b.lerp(c, t)); - let m = d.lerp(e, t); - (Seg2::Cubic { p0, p1: a, p2: d, p3: m }, Seg2::Cubic { p0: m, p1: e, p2: c, p3 }) - } - Seg2::Conic { a, apex, b, w } => { - // Homogeneous de Casteljau: (a, 1), (w·apex, w), (b, 1). - let h = |p: Vec2, wt: f64| (p * wt, wt); - let lerp = |x: (Vec2, f64), y: (Vec2, f64)| (x.0 * (1.0 - t) + y.0 * t, x.1 * (1.0 - t) + y.1 * t); - let (p0, p1, p2) = (h(a, 1.0), h(apex, w), h(b, 1.0)); - let (q0, q1) = (lerp(p0, p1), lerp(p1, p2)); - let r = lerp(q0, q1); - let pt = |x: (Vec2, f64)| x.0 / x.1.max(1e-300); - let m = pt(r); - ( - Seg2::Conic { a, apex: pt(q0), b: m, w: q0.1 / r.1.max(1e-300).sqrt() }, - Seg2::Conic { a: m, apex: pt(q1), b, w: q1.1 / r.1.max(1e-300).sqrt() }, - ) - } - Seg2::Bezier { n, ref p } => { - let (_, l, r) = casteljau(Self::bez(n, p), t); - let mk = |c: &[Vec2]| bezier(c).unwrap_or(*self); - (mk(&l), mk(&r)) - } - } - } - /// The part of the segment from parameter `t0` to `t1` (0 <= t0 < t1 <= 1), the same kind: it - /// starts at `point_at(t0)` and ends at `point_at(t1)`, exactly as [`Seg2::split_at`] there puts - /// them. A conic's tail after the first split is re-normalised, which moves its parameter: `t1` - /// is carried into it (its end weights scaled to 1 by the factor `c`, a point at `u` of the - /// tail is at `u / (u + c (1 - u))`). - pub fn part(&self, t0: f64, t1: f64) -> Seg2 { - let tail = if t0 > 0.0 { self.split_at(t0).1 } else { *self }; - if t1 >= 1.0 { - return tail; - } - let u = (t1 - t0) / (1.0 - t0); - let s = match *self { - Seg2::Conic { w, .. } if t0 > 0.0 => { - let c = ((1.0 - t0) * (1.0 - t0) + 2.0 * w * t0 * (1.0 - t0) + t0 * t0).sqrt(); - u / (u + c * (1.0 - u)) - } - _ => u, - }; - tail.split_at(s).0 - } - /// Parameter of the closest point: exact projection for lines, - /// sampling followed by Newton for the remaining curves. - pub fn closest_param(&self, p: Vec2) -> f64 { - let finite = |p: Vec2| p.x.is_finite() && p.y.is_finite(); - match *self { - Seg2::Line { a, b } if finite(a) && finite(b) && finite(p) => { - let d = b - a; - if a == b { - return 0.0; - } - let denominator = d.len2(); - let t = (p - a).dot(d) / denominator; - if denominator > 0.0 && denominator.is_finite() && t.is_finite() { - return t.clamp(0.0, 1.0); - } - } - _ => {} - } - let n = 64; - let mut t = - (0..=n).map(|i| i as f64 / n as f64).min_by(|x, y| self.point_at(*x).dist(p).total_cmp(&self.point_at(*y).dist(p))).unwrap_or(0.0); - for _ in 0..30 { - let (q, d) = (self.point_at(t), self.derivative(t)); - let (d2, h) = ((self.derivative((t + 1e-6).min(1.0)) - self.derivative((t - 1e-6).max(0.0))) / 2e-6, q - p); - let f = h.dot(d); - let df = d.dot(d) + h.dot(d2); - if df.abs() < 1e-300 { - break; - } - let nt = (t - f / df).clamp(0.0, 1.0); - if (nt - t).abs() < 1e-14 { - t = nt; - break; - } - t = nt; - } - t - } - /// The two halves of the segment (same kind, exact). - pub fn split_half(&self) -> (Seg2, Seg2) { - match *self { - Seg2::Line { a, b } => { - let m = a.lerp(b, 0.5); - (Seg2::Line { a, b: m }, Seg2::Line { a: m, b }) - } - Seg2::Arc { center, radius, start, sweep } => ( - Seg2::Arc { center, radius, start, sweep: sweep / 2.0 }, - Seg2::Arc { center, radius, start: start + sweep / 2.0, sweep: sweep / 2.0 }, - ), - Seg2::Cubic { p0, p1, p2, p3 } => { - let (a, b, c) = (p0.lerp(p1, 0.5), p1.lerp(p2, 0.5), p2.lerp(p3, 0.5)); - let (d, e) = (a.lerp(b, 0.5), b.lerp(c, 0.5)); - let m = d.lerp(e, 0.5); - (Seg2::Cubic { p0, p1: a, p2: d, p3: m }, Seg2::Cubic { p0: m, p1: e, p2: c, p3 }) - } - Seg2::Conic { a, apex, b, w } => { - // Rational de Casteljau at the middle, weights normalised to 1 at the ends. - let m = self.point_at(0.5); - let w2 = ((1.0 + w) / 2.0).max(0.0).sqrt(); - let (l, r) = ((a + apex * w) / (1.0 + w), (apex * w + b) / (1.0 + w)); - (Seg2::Conic { a, apex: l, b: m, w: w2 }, Seg2::Conic { a: m, apex: r, b, w: w2 }) - } - Seg2::Bezier { .. } => self.split_at(0.5), - } - } - /// ∫₀¹ f(t) dt by composite Gauss–Legendre (16 pieces of 5 points). - fn integrate(&self, f: impl Fn(&Seg2, f64) -> f64) -> f64 { - let n = 16; - let mut sum = 0.0; - for k in 0..n { - let (t0, h) = (k as f64 / n as f64, 1.0 / n as f64); - for (x, w) in GL5 { - sum += w * h * f(self, t0 + x * h); - } - } - sum - } - /// Contribution to the loop's signed area (shoelace integral ½∮(x dy − y dx)). - pub fn area_term(&self) -> f64 { - match *self { - Seg2::Line { a, b } => 0.5 * a.cross(b), - Seg2::Arc { radius, sweep, .. } => { - let (a, b) = (self.start(), self.end()); - // Chord term plus the circular segment between chord and arc. - 0.5 * a.cross(b) + 0.5 * radius * radius * (sweep - sweep.sin()) - } - Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => self.integrate(|s, t| 0.5 * s.point_at(t).cross(s.derivative(t))), - } - } - /// How many equal steps of `t` keep every chord within `tol` (above 0) of the segment, unrounded - /// and with no floor or cap: an arc by its chord's bulge, the others by the largest second - /// difference of their controls (Wang's bound). - pub fn chords(&self, tol: f64) -> f64 { - // A chord over 1/k of t strays at most an eighth of the second derivative's bound over k². - let bound = |d2: f64| (d2 / (8.0 * tol)).sqrt(); - match *self { - Seg2::Line { .. } => 1.0, - Seg2::Arc { radius, sweep, .. } => { - sweep.abs() / if tol < radius { 2.0 * (1.0 - tol / radius).clamp(-1.0, 1.0).acos() } else { TAU / 8.0 } - } - Seg2::Cubic { p0, p1, p2, p3 } => bound((p0 - p1 * 2.0 + p2).len().max((p1 - p2 * 2.0 + p3).len()) * 6.0), - Seg2::Conic { a, apex, b, w } => bound((a - apex * 2.0 + b).len() * 2.0 * w.max(1.0)), - Seg2::Bezier { n, ref p } => { - // Second derivative ≤ n(n−1) × the largest second difference of the controls. - let c = Self::bez(n, p); - bound(c.windows(3).map(|w| (w[0] - w[1] * 2.0 + w[2]).len()).fold(0.0, f64::max) * (n as f64) * (n as f64 - 1.0)) - } - } - } - /// Polyline approximation (including both end points) with at most `tol` chord error - /// ([`Seg2::chords`]) in 2 to 4096 pieces, an arc's tolerance at least a millionth of its radius. - pub fn polyline(&self, tol: f64) -> Vec { - if let Seg2::Line { a, b } = *self { - return vec![a, b]; - } - let tol = if let Seg2::Arc { radius, .. } = *self { tol.max(radius.abs() * 1e-6) } else { tol }.max(1e-9); - let n = (self.chords(tol).ceil() as usize).clamp(2, 4096); - (0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect() - } -} - -/// A closed loop of segments, each starting where the previous one ends. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Loop2 { - pub segs: Vec, -} - -impl Loop2 { - /// The radius of the largest circle inside the loop, to about `tol` ([`Region2::inradius`]). - pub fn inradius(&self, tol: f64) -> f64 { - max_clearance(&[self.polyline(tol)]) - } - /// Full circle as two half arcs (counter-clockwise). - pub fn circle(center: Vec2, radius: f64) -> Loop2 { - Loop2 { - segs: vec![ - Seg2::Arc { center, radius, start: 0.0, sweep: std::f64::consts::PI }, - Seg2::Arc { center, radius, start: std::f64::consts::PI, sweep: std::f64::consts::PI }, - ], - } - } - /// Full circle starting (and split) at angle `start`. - pub fn circle_from(center: Vec2, radius: f64, start: f64) -> Loop2 { - use std::f64::consts::PI; - Loop2 { segs: vec![Seg2::Arc { center, radius, start, sweep: PI }, Seg2::Arc { center, radius, start: start + PI, sweep: PI }] } - } - pub fn polygon(pts: &[Vec2]) -> Loop2 { - let n = pts.len(); - Loop2 { segs: (0..n).filter_map(|i| Some(Seg2::Line { a: *pts.get(i)?, b: *pts.get((i + 1) % n)? })).collect() } - } - /// Signed area: positive when counter-clockwise. - pub fn signed_area(&self) -> f64 { - self.segs.iter().map(Seg2::area_term).sum() - } - pub fn reversed(&self) -> Loop2 { - Loop2 { segs: self.segs.iter().rev().map(Seg2::reversed).collect() } - } - /// Whether the loop runs counter-clockwise ([`Loop2::ccw`] keeps it as it is). - pub fn is_ccw(&self) -> bool { - self.signed_area() >= 0.0 - } - /// Counter-clockwise copy. - pub fn ccw(&self) -> Loop2 { - if self.is_ccw() { self.clone() } else { self.reversed() } - } - /// Each segment with the next and the last with the first: the loop's joints, where one - /// segment should end on the start of the next. - pub fn joints(&self) -> impl Iterator + Clone { - crate::chain::around(&self.segs) - } - /// The loop as a polyline within `tol`: each segment's points but its last, which the next - /// segment starts on. - pub fn polyline(&self, tol: f64) -> Ring { - self.segs - .iter() - .flat_map(|s| { - let p = s.polyline(tol); - let n = p.len().saturating_sub(1); - p.into_iter().take(n) - }) - .collect() - } - /// Even-odd point containment against the polyline approximation. - pub fn contains(&self, p: Vec2) -> bool { - self.polyline(1e-3).contains(p) - } - /// Area-weighted centroid (of the polyline approximation). - pub fn centroid(&self) -> Vec2 { - let poly = self.polyline(1e-3); - let n = poly.len(); - let (mut a2, mut c) = (0.0, Vec2::ZERO); - for i in 0..n { - let (Some(p), Some(q)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - let k = p.cross(*q); - a2 += k; - c += (*p + *q) * k; - } - if a2.abs() < 1e-15 { poly.first().copied().unwrap_or_default() } else { c / (3.0 * a2) } - } - /// Closed within `tol`? - pub fn is_closed(&self, tol: f64) -> bool { - let n = self.segs.len(); - n > 0 - && (0..n).all(|i| match (self.segs.get(i), self.segs.get((i + 1) % n)) { - (Some(a), Some(b)) => a.end().dist(b.start()) <= tol, - _ => false, - }) - } -} - -/// A planar region: outer loop (counter-clockwise) minus holes (clockwise). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Region2 { - pub outer: Loop2, - pub holes: Vec, -} - -impl Region2 { - pub fn area(&self) -> f64 { - self.outer.signed_area().abs() - self.holes.iter().map(|h| h.signed_area().abs()).sum::() - } - /// The outer loop, then the holes. - pub fn loops(&self) -> impl Iterator + Clone { - std::iter::once(&self.outer).chain(&self.holes) - } - /// A point strictly inside the region (for picking and labels). - pub fn interior_point(&self) -> Vec2 { - let c = self.centroid(); - if self.contains(c) { - return c; - } - // Scan a few horizontal lines for the midpoint of the widest inside span. - let poly = self.outer.polyline(1e-2); - let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); - for p in &poly { - y0 = y0.min(p.y); - y1 = y1.max(p.y); - } - for k in 1..16 { - let y = y0 + (y1 - y0) * k as f64 / 16.0; - let mut xs: Vec = Vec::new(); - for l in std::iter::once(&self.outer).chain(&self.holes) { - let pl = l.polyline(1e-2); - let n = pl.len(); - for i in 0..n { - let (Some(a), Some(b)) = (pl.get(i), pl.get((i + 1) % n)) else { continue }; - if (a.y > y) != (b.y > y) { - xs.push(a.x + (y - a.y) / (b.y - a.y) * (b.x - a.x)); - } - } - } - xs.sort_by(f64::total_cmp); - for w in xs.chunks(2) { - if let [a, b] = w { - let p = Vec2::new((a + b) * 0.5, y); - if self.contains(p) { - return p; - } - } - } - } - c - } - pub fn contains(&self, p: Vec2) -> bool { - self.outer.contains(p) && !self.holes.iter().any(|h| h.contains(p)) - } - /// The radius of the largest circle inside the region: how far its sides can move inwards - /// before they meet (a taper going in closes it there). Found by a grid search refined - /// around the best point, to about `tol`. - pub fn inradius(&self, tol: f64) -> f64 { - let loops: Vec> = std::iter::once(&self.outer).chain(&self.holes).map(|l| l.polyline(tol)).collect(); - max_clearance(&loops) - } -} - /// The largest distance from a point inside `loops` (even-odd) to their sides, by a grid search /// over their box refined around the best point. Zero for an empty or degenerate outline. fn max_clearance(loops: &[Ring]) -> f64 { @@ -894,70 +233,6 @@ fn max_clearance(loops: &[Ring]) -> f64 { best.0 } -impl Region2 { - /// Triangles covering the region (for filled display), by slabs between the vertex - /// heights: inside each slab the boundary edges don't cross, so consecutive crossings pair - /// up into trapezoids. - pub fn triangulate(&self, tol: f64) -> Vec<[Vec2; 3]> { - let mut edges: Vec<(Vec2, Vec2)> = Vec::new(); - for l in std::iter::once(&self.outer).chain(&self.holes) { - let pl = l.polyline(tol); - let n = pl.len(); - for i in 0..n { - let (Some(a), Some(b)) = (pl.get(i), pl.get((i + 1) % n)) else { continue }; - if (a.y - b.y).abs() > 1e-12 { - edges.push(if a.y < b.y { (*a, *b) } else { (*b, *a) }); - } - } - } - if edges.len() > 20_000 { - return Vec::new(); - } - let mut ys: Vec = edges.iter().flat_map(|(a, b)| [a.y, b.y]).collect(); - ys.sort_by(f64::total_cmp); - ys.dedup_by(|a, b| (*a - *b).abs() < 1e-12); - let x_at = |e: &(Vec2, Vec2), y: f64| e.0.x + (y - e.0.y) / (e.1.y - e.0.y) * (e.1.x - e.0.x); - // Sweep upward: an edge joins the slabs once its lower end is passed and leaves after - // its upper end, so each slab sorts only the edges crossing it (a finely sampled ring - // has hundreds of slabs and edges, but four edges in each slab). - edges.sort_by(|a, b| a.0.y.total_cmp(&b.0.y)); - let mut next = 0; - let mut span: Vec<&(Vec2, Vec2)> = Vec::new(); - let mut out = Vec::new(); - for w in ys.windows(2) { - let (y0, y1) = (w[0], w[1]); - let ym = (y0 + y1) * 0.5; - while let Some(e) = edges.get(next) - && e.0.y <= ym - { - span.push(e); - next += 1; - } - span.retain(|e| e.1.y >= ym); - span.sort_by(|a, b| x_at(a, ym).total_cmp(&x_at(b, ym))); - for pair in span.chunks(2) { - let [l, r] = pair else { continue }; - let (a, b) = (Vec2::new(x_at(l, y0), y0), Vec2::new(x_at(r, y0), y0)); - let (c, d) = (Vec2::new(x_at(r, y1), y1), Vec2::new(x_at(l, y1), y1)); - out.push([a, b, c]); - out.push([a, c, d]); - } - } - out - } - pub fn centroid(&self) -> Vec2 { - let ao = self.outer.signed_area().abs(); - let mut c = self.outer.centroid() * ao; - let mut a = ao; - for h in &self.holes { - let ah = h.signed_area().abs(); - c -= h.centroid() * ah; - a -= ah; - } - if a.abs() < 1e-15 { self.outer.centroid() } else { c / a } - } -} - /// Most boundary segment pairs [`regions_apart`] compares before it gives up (and says no). const APART_BUDGET: usize = 50_000_000; @@ -1049,6 +324,714 @@ fn segment_distance(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> f64 { to(a, c, d).min(to(b, c, d)).min(to(c, a, b)).min(to(d, a, b)) } +/// The geometry of a profile segment ([`Seg2`]): evaluation, derivatives, lengths, splits and +/// closest points. +pub trait Seg2Geom { + /// Checks a segment read from outside before anything evaluates it: every stored coordinate + /// finite and at most `max_abs` in size (a Bézier's unused slots too, as they are serialized), + /// a radius in 1e-12..=`max_abs`, an arc's start within ±1e6 radians and its absolute sweep + /// 1e-12 to one turn (with 1e-12 radians of allowance), a conic weight in 1e-12..=1e12, a + /// Bézier degree of 4 to [`MAX_BEZIER_DEGREE`], controls not all at one point, and finite + /// ends. The limits keep evaluation finite; they promise no accuracy. The caller wraps the + /// message in its own error. + fn check(&self, max_abs: f64) -> Result<(), &'static str>; + /// Derivative with respect to the parameter at `t` (Béziers and conics; lines and arcs too). + fn derivative(&self, t: f64) -> Vec2; + /// Derivatives 1…`order` with respect to the segment's own parameter at `t`, exactly: a line + /// and an arc from their analytic form (an arc's are the circular-motion recurrence, zero + /// curvature terms included), a cubic and a higher-degree piece from the forward differences + /// of their controls, a conic through the quotient rule of its rational form. A blend curve + /// reads a reference curve's derivatives here to build a Hermite interpolation, so this is + /// exact at both ends (`t` = 0 and 1) and `None` — never a wrong number — when `order` is + /// above [`MAX_DERIVATIVE_ORDER`], `t` is not finite or a value is not finite, as with a + /// degenerate rational piece. + fn derivatives(&self, t: f64, order: usize) -> Option>; + fn start(&self) -> Vec2; + fn end(&self) -> Vec2; + fn point_at(&self, t: f64) -> Vec2; + fn mid(&self) -> Vec2; + /// Unit tangent at the start (direction of travel). + fn start_tangent(&self) -> Vec2; + /// Unit tangent at the end (direction of travel). + fn end_tangent(&self) -> Vec2; + fn reversed(&self) -> Seg2; + /// The segment with each control point mapped by `f`: exact for any affine map of lines, + /// Béziers and conics. An arc is returned as it is, so callers go through [`Seg2Geom::mapped`]; + /// only a segment that holds no arc, such as a glyph's outline, takes a map that doesn't keep + /// shapes. + fn map_controls(&self, f: impl Fn(Vec2) -> Vec2) -> Seg2; + /// The segment moved by the similarity `m`, exactly ([`Seg2Geom::mapped`]). + fn similar(&self, m: &Similarity2) -> Seg2; + /// The segment under a map of the plane that keeps shapes: `f` moves its points (an arc's centre + /// and every control point), and `arc` says how it turns an arc (start `angle - start` and the + /// sweep reversed when mirrored, `angle + start` otherwise; the radius scaled). Points go + /// through `f` itself, so a map exact on points stays exact. + fn mapped(&self, f: impl Fn(Vec2) -> Vec2, arc: ArcMap) -> Seg2; + /// The smallest box round the piece: exact for a line and an arc, and for a curve within a + /// thousandth of a unit, read off its polyline. + fn bounds(&self) -> Aabb2; + fn length(&self) -> f64; + /// The nearest to either end, in parameter, that [`Seg2Geom::split_at`] splits a segment. + const MIN_SPLIT: f64; + /// The segment split at parameter `t` in (0, 1), at least [`Seg2Geom::MIN_SPLIT`] from either + /// end (same kind, exact; conic halves are re-normalised so their end weights stay 1). + fn split_at(&self, t: f64) -> (Seg2, Seg2); + /// The part of the segment from parameter `t0` to `t1` (0 <= t0 < t1 <= 1), the same kind: it + /// starts at `point_at(t0)` and ends at `point_at(t1)`, exactly as [`Seg2Geom::split_at`] there + /// puts them. A conic's tail after the first split is re-normalised, which moves its parameter: + /// `t1` is carried into it (its end weights scaled to 1 by the factor `c`, a point at `u` of the + /// tail is at `u / (u + c (1 - u))`). + fn part(&self, t0: f64, t1: f64) -> Seg2; + /// Parameter of the closest point: exact projection for lines, + /// sampling followed by Newton for the remaining curves. + fn closest_param(&self, p: Vec2) -> f64; + /// The two halves of the segment (same kind, exact). + fn split_half(&self) -> (Seg2, Seg2); + /// Contribution to the loop's signed area (shoelace integral ½∮(x dy − y dx)). + fn area_term(&self) -> f64; + /// How many equal steps of `t` keep every chord within `tol` (above 0) of the segment, unrounded + /// and with no floor or cap: an arc by its chord's bulge, the others by the largest second + /// difference of their controls (Wang's bound). + fn chords(&self, tol: f64) -> f64; + /// Polyline approximation (including both end points) with at most `tol` chord error + /// ([`Seg2Geom::chords`]) in 2 to 4096 pieces, an arc's tolerance at least a millionth of its radius. + fn polyline(&self, tol: f64) -> Vec; +} + +impl Seg2Geom for Seg2 { + fn check(&self, max_abs: f64) -> Result<(), &'static str> { + match *self { + Seg2::Line { a, b } => controls(&[a, b], max_abs)?, + Seg2::Arc { center, radius, start, sweep } => { + coordinates([center.x, center.y], max_abs)?; + require(radius.is_finite() && (MIN_POSITIVE..=max_abs).contains(&radius), "arc radius")?; + require(start.is_finite() && start.abs() <= MAX_START_ANGLE, "arc start angle")?; + require(sweep.is_finite() && (MIN_POSITIVE..=TAU + 1e-12).contains(&sweep.abs()), "arc sweep")?; + } + Seg2::Cubic { p0, p1, p2, p3 } => controls(&[p0, p1, p2, p3], max_abs)?, + Seg2::Conic { a, apex, b, w } => { + controls(&[a, apex, b], max_abs)?; + require(w.is_finite() && (MIN_POSITIVE..=MAX_WEIGHT).contains(&w), "conic weight")?; + } + Seg2::Bezier { n, ref p } => { + require((4..=MAX_BEZIER_DEGREE).contains(&usize::from(n)), "Bezier degree")?; + // The unused slots are serialized too: reject hidden non-finite/excessive values. + coordinates(p.iter().flat_map(|q| [q.x, q.y]), max_abs)?; + controls(p.get(..=usize::from(n)).ok_or("Bezier degree")?, max_abs)?; + } + } + require(self.start().is_finite() && self.end().is_finite(), "non-finite curve endpoint") + } + fn derivative(&self, t: f64) -> Vec2 { + match *self { + Seg2::Line { a, b } => b - a, + Seg2::Arc { radius, start, sweep, .. } => Vec2::from_angle(start + sweep * t).perp() * (radius * sweep), + Seg2::Cubic { p0, p1, p2, p3 } => { + let u = 1.0 - t; + (p1 - p0) * (3.0 * u * u) + (p2 - p1) * (6.0 * u * t) + (p3 - p2) * (3.0 * t * t) + } + Seg2::Conic { a, apex, b, w } => { + let u = 1.0 - t; + let (n, d) = (a * (u * u) + apex * (2.0 * w * u * t) + b * (t * t), u * u + 2.0 * w * u * t + t * t); + let (dn, dd) = (a * (-2.0 * u) + apex * (2.0 * w * (1.0 - 2.0 * t)) + b * (2.0 * t), -2.0 * u + 2.0 * w * (1.0 - 2.0 * t) + 2.0 * t); + (dn * d - n * dd) / (d * d).max(1e-300) + } + Seg2::Bezier { n, ref p } => { + let c = bez(n, p); + let diffs: Vec = c.windows(2).map(|w| (w[1] - w[0]) * (c.len() - 1) as f64).collect(); + casteljau(&diffs, t).0 + } + } + } + fn derivatives(&self, t: f64, order: usize) -> Option> { + if !t.is_finite() || order > MAX_DERIVATIVE_ORDER { + return None; + } + let mut d = match *self { + Seg2::Line { a, b } => { + if !a.is_finite() || !b.is_finite() { + return None; + } + let mut d = vec![b - a]; + d.resize(MAX_DERIVATIVE_ORDER, Vec2::ZERO); + d + } + Seg2::Arc { center, radius, start, sweep } => { + if !center.is_finite() || !radius.is_finite() || !start.is_finite() || !sweep.is_finite() { + return None; + } + // Differentiating the radial direction twice returns its negative, so the + // directions of the successive derivatives are tangential, radial, tangential… + // with alternating signs, each order picking up one more factor of the sweep. + let mut v = Vec2::from_angle(start + sweep * t).perp(); + let mut d = Vec::with_capacity(MAX_DERIVATIVE_ORDER); + for j in 1..=MAX_DERIVATIVE_ORDER { + d.push(v * (radius * sweep.powi(j as i32))); + v = v.perp(); + } + d + } + Seg2::Cubic { p0, p1, p2, p3 } => bezier_derivatives(&[p0, p1, p2, p3], t, MAX_DERIVATIVE_ORDER)?, + Seg2::Bezier { n, ref p } => bezier_derivatives(bez(n, p), t, MAX_DERIVATIVE_ORDER)?, + Seg2::Conic { a, apex, b, w } => { + if !a.is_finite() || !apex.is_finite() || !b.is_finite() || !w.is_finite() { + return None; + } + // The conic is `N(t) / d(t)` with `N` the quadratic through `a`, `w·apex`, `b` and + // `d` its weight polynomial; both are evaluated here in the power basis (at the + // ends `d` = 1, so a join is never singular). The quotient rule in its + // derivative-of-a-product form gives the higher derivatives: the numerator of + // `x⁽ʲ⁾` is `N⁽ʲ⁾` minus the terms that already use `d` and a lower `x`. + let (n0, n1, n2) = (a, apex * (2.0 * w) - a * 2.0, a - apex * (2.0 * w) + b); + let (e1, e2) = (2.0 * (w - 1.0), 2.0 * (1.0 - w)); + let quotient = |j: usize| match j { + 0 => n0 + n1 * t + n2 * (t * t), + 1 => n1 + n2 * (2.0 * t), + 2 => n2 * 2.0, + _ => Vec2::ZERO, + }; + let weight = |j: usize| match j { + 0 => 1.0 + e1 * t + e2 * (t * t), + 1 => e1 + e2 * (2.0 * t), + 2 => e2 * 2.0, + _ => 0.0, + }; + let den = weight(0); + if !(den.abs() > 1e-300) { + return None; + } + let mut x = vec![quotient(0) / den]; + for j in 1..=MAX_DERIVATIVE_ORDER { + let mut v = quotient(j); + for i in 1..=j { + v -= x[j - i] * (weight(i) * binom(j, i)); + } + x.push(v / den); + } + x.remove(0); + x + } + }; + d.truncate(order); + d.iter().all(|q| q.is_finite()).then_some(d) + } + fn start(&self) -> Vec2 { + match *self { + Seg2::Line { a, .. } | Seg2::Conic { a, .. } => a, + Seg2::Cubic { p0, .. } => p0, + Seg2::Bezier { p, .. } => p[0], + Seg2::Arc { center, radius, start, .. } => center + Vec2::from_angle(start) * radius, + } + } + fn end(&self) -> Vec2 { + match *self { + Seg2::Line { b, .. } | Seg2::Conic { b, .. } => b, + Seg2::Cubic { p3, .. } => p3, + Seg2::Bezier { n, ref p } => bez(n, p).last().copied().unwrap_or(p[0]), + Seg2::Arc { center, radius, start, sweep } => center + Vec2::from_angle(start + sweep) * radius, + } + } + fn point_at(&self, t: f64) -> Vec2 { + match *self { + Seg2::Line { a, b } => a.lerp(b, t), + Seg2::Arc { center, radius, start, sweep } => center + Vec2::from_angle(start + sweep * t) * radius, + Seg2::Cubic { p0, p1, p2, p3 } => { + let u = 1.0 - t; + p0 * (u * u * u) + p1 * (3.0 * u * u * t) + p2 * (3.0 * u * t * t) + p3 * (t * t * t) + } + Seg2::Conic { a, apex, b, w } => { + let u = 1.0 - t; + let d = u * u + 2.0 * w * u * t + t * t; + (a * (u * u) + apex * (2.0 * w * u * t) + b * (t * t)) / d.max(1e-300) + } + Seg2::Bezier { n, ref p } => casteljau(bez(n, p), t).0, + } + } + fn mid(&self) -> Vec2 { + self.point_at(0.5) + } + fn start_tangent(&self) -> Vec2 { + match *self { + Seg2::Line { a, b } => (b - a).normalized().unwrap_or(Vec2::X), + Seg2::Arc { start, sweep, .. } => Vec2::from_angle(start).perp() * sweep.signum(), + Seg2::Cubic { p0, p1, p2, .. } => (p1 - p0).normalized().or_else(|| (p2 - p0).normalized()).unwrap_or(Vec2::X), + Seg2::Conic { a, apex, b, .. } => (apex - a).normalized().or_else(|| (b - a).normalized()).unwrap_or(Vec2::X), + Seg2::Bezier { n, ref p } => { + let c = bez(n, p); + c.iter().skip(1).find_map(|q| (*q - c[0]).normalized()).unwrap_or(Vec2::X) + } + } + } + fn end_tangent(&self) -> Vec2 { + match *self { + Seg2::Line { a, b } => (b - a).normalized().unwrap_or(Vec2::X), + Seg2::Arc { start, sweep, .. } => Vec2::from_angle(start + sweep).perp() * sweep.signum(), + Seg2::Cubic { p1, p2, p3, .. } => (p3 - p2).normalized().or_else(|| (p3 - p1).normalized()).unwrap_or(Vec2::X), + Seg2::Conic { a, apex, b, .. } => (b - apex).normalized().or_else(|| (b - a).normalized()).unwrap_or(Vec2::X), + Seg2::Bezier { n, ref p } => { + let c = bez(n, p); + let last = c.last().copied().unwrap_or(p[0]); + c.iter().rev().skip(1).find_map(|q| (last - *q).normalized()).unwrap_or(Vec2::X) + } + } + } + fn reversed(&self) -> Seg2 { + match *self { + Seg2::Line { a, b } => Seg2::Line { a: b, b: a }, + Seg2::Arc { center, radius, start, sweep } => Seg2::Arc { center, radius, start: start + sweep, sweep: -sweep }, + Seg2::Cubic { p0, p1, p2, p3 } => Seg2::Cubic { p0: p3, p1: p2, p2: p1, p3: p0 }, + Seg2::Conic { a, apex, b, w } => Seg2::Conic { a: b, apex, b: a, w }, + Seg2::Bezier { n, ref p } => { + let mut q = *p; + let k = (n as usize).clamp(1, MAX_BEZIER_DEGREE); + q[..=k].reverse(); + Seg2::Bezier { n, p: q } + } + } + } + fn map_controls(&self, f: impl Fn(Vec2) -> Vec2) -> Seg2 { + match *self { + Seg2::Line { a, b } => Seg2::Line { a: f(a), b: f(b) }, + Seg2::Cubic { p0, p1, p2, p3 } => Seg2::Cubic { p0: f(p0), p1: f(p1), p2: f(p2), p3: f(p3) }, + Seg2::Conic { a, apex, b, w } => Seg2::Conic { a: f(a), apex: f(apex), b: f(b), w }, + Seg2::Bezier { n, mut p } => { + p.iter_mut().take(usize::from(n) + 1).for_each(|q| *q = f(*q)); + Seg2::Bezier { n, p } + } + arc @ Seg2::Arc { .. } => arc, + } + } + fn similar(&self, m: &Similarity2) -> Seg2 { + self.mapped(|p| m.apply(p), ArcMap { angle: m.angle(), mirrored: false, scale: m.scale() }) + } + fn mapped(&self, f: impl Fn(Vec2) -> Vec2, arc: ArcMap) -> Seg2 { + let ArcMap { angle, mirrored, scale } = arc; + match *self { + Seg2::Arc { center, radius, start, sweep } => { + let (start, sweep) = if mirrored { (angle - start, -sweep) } else { (angle + start, sweep) }; + Seg2::Arc { center: f(center), radius: radius * scale, start, sweep } + } + _ => self.map_controls(f), + } + } + fn bounds(&self) -> Aabb2 { + match *self { + Seg2::Line { a, b } => [a, b].into_iter().collect(), + Seg2::Arc { center, radius, start, sweep } => { + let mut bounds: Aabb2 = [self.start(), self.end()].into_iter().collect(); + let quarters = [ + (0.0, Vec2::new(1.0, 0.0)), + (FRAC_PI_2, Vec2::new(0.0, 1.0)), + (PI, Vec2::new(-1.0, 0.0)), + (3.0 * FRAC_PI_2, Vec2::new(0.0, -1.0)), + ]; + for (at, way) in quarters { + let along = if sweep >= 0.0 { at - start } else { start - at }; + if along.rem_euclid(TAU) <= sweep.abs() { + bounds.add(center + way * radius); + } + } + bounds + } + _ => self.polyline(1e-3).into_iter().collect(), + } + } + fn length(&self) -> f64 { + match *self { + Seg2::Line { a, b } => a.dist(b), + Seg2::Arc { radius, sweep, .. } => (radius * sweep).abs(), + Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => integrate(self, |s, t| s.derivative(t).len()), + } + } + const MIN_SPLIT: f64 = 1e-9; + fn split_at(&self, t: f64) -> (Seg2, Seg2) { + let t = t.clamp(Self::MIN_SPLIT, 1.0 - Self::MIN_SPLIT); + match *self { + Seg2::Line { a, b } => { + let m = a.lerp(b, t); + (Seg2::Line { a, b: m }, Seg2::Line { a: m, b }) + } + Seg2::Arc { center, radius, start, sweep } => ( + Seg2::Arc { center, radius, start, sweep: sweep * t }, + Seg2::Arc { center, radius, start: start + sweep * t, sweep: sweep * (1.0 - t) }, + ), + Seg2::Cubic { p0, p1, p2, p3 } => { + let (a, b, c) = (p0.lerp(p1, t), p1.lerp(p2, t), p2.lerp(p3, t)); + let (d, e) = (a.lerp(b, t), b.lerp(c, t)); + let m = d.lerp(e, t); + (Seg2::Cubic { p0, p1: a, p2: d, p3: m }, Seg2::Cubic { p0: m, p1: e, p2: c, p3 }) + } + Seg2::Conic { a, apex, b, w } => { + // Homogeneous de Casteljau: (a, 1), (w·apex, w), (b, 1). + let h = |p: Vec2, wt: f64| (p * wt, wt); + let lerp = |x: (Vec2, f64), y: (Vec2, f64)| (x.0 * (1.0 - t) + y.0 * t, x.1 * (1.0 - t) + y.1 * t); + let (p0, p1, p2) = (h(a, 1.0), h(apex, w), h(b, 1.0)); + let (q0, q1) = (lerp(p0, p1), lerp(p1, p2)); + let r = lerp(q0, q1); + let pt = |x: (Vec2, f64)| x.0 / x.1.max(1e-300); + let m = pt(r); + ( + Seg2::Conic { a, apex: pt(q0), b: m, w: q0.1 / r.1.max(1e-300).sqrt() }, + Seg2::Conic { a: m, apex: pt(q1), b, w: q1.1 / r.1.max(1e-300).sqrt() }, + ) + } + Seg2::Bezier { n, ref p } => { + let (_, l, r) = casteljau(bez(n, p), t); + let mk = |c: &[Vec2]| bezier(c).unwrap_or(*self); + (mk(&l), mk(&r)) + } + } + } + fn part(&self, t0: f64, t1: f64) -> Seg2 { + let tail = if t0 > 0.0 { self.split_at(t0).1 } else { *self }; + if t1 >= 1.0 { + return tail; + } + let u = (t1 - t0) / (1.0 - t0); + let s = match *self { + Seg2::Conic { w, .. } if t0 > 0.0 => { + let c = ((1.0 - t0) * (1.0 - t0) + 2.0 * w * t0 * (1.0 - t0) + t0 * t0).sqrt(); + u / (u + c * (1.0 - u)) + } + _ => u, + }; + tail.split_at(s).0 + } + fn closest_param(&self, p: Vec2) -> f64 { + let finite = |p: Vec2| p.x.is_finite() && p.y.is_finite(); + match *self { + Seg2::Line { a, b } if finite(a) && finite(b) && finite(p) => { + let d = b - a; + if a == b { + return 0.0; + } + let denominator = d.len2(); + let t = (p - a).dot(d) / denominator; + if denominator > 0.0 && denominator.is_finite() && t.is_finite() { + return t.clamp(0.0, 1.0); + } + } + _ => {} + } + let n = 64; + let t = (0..=n).map(|i| i as f64 / n as f64).min_by(|x, y| self.point_at(*x).dist(p).total_cmp(&self.point_at(*y).dist(p))).unwrap_or(0.0); + let t = newton_closest(self, p, t); + // A closed segment (a full circle) starts where it ends: a point just before its start is + // nearest just before its end, which Newton from the start (held there by the clamp) + // never reaches. Try from the other end too. + let (a, b) = (self.point_at(0.0), self.point_at(1.0)); + if (t == 0.0 || t == 1.0) && a.dist(b) <= 1e-12 * (1.0 + a.len()) { + let other = newton_closest(self, p, 1.0 - t); + if self.point_at(other).dist(p) < self.point_at(t).dist(p) { + return other; + } + } + t + } + fn split_half(&self) -> (Seg2, Seg2) { + match *self { + Seg2::Line { a, b } => { + let m = a.lerp(b, 0.5); + (Seg2::Line { a, b: m }, Seg2::Line { a: m, b }) + } + Seg2::Arc { center, radius, start, sweep } => ( + Seg2::Arc { center, radius, start, sweep: sweep / 2.0 }, + Seg2::Arc { center, radius, start: start + sweep / 2.0, sweep: sweep / 2.0 }, + ), + Seg2::Cubic { p0, p1, p2, p3 } => { + let (a, b, c) = (p0.lerp(p1, 0.5), p1.lerp(p2, 0.5), p2.lerp(p3, 0.5)); + let (d, e) = (a.lerp(b, 0.5), b.lerp(c, 0.5)); + let m = d.lerp(e, 0.5); + (Seg2::Cubic { p0, p1: a, p2: d, p3: m }, Seg2::Cubic { p0: m, p1: e, p2: c, p3 }) + } + Seg2::Conic { a, apex, b, w } => { + // Rational de Casteljau at the middle, weights normalised to 1 at the ends. + let m = self.point_at(0.5); + let w2 = ((1.0 + w) / 2.0).max(0.0).sqrt(); + let (l, r) = ((a + apex * w) / (1.0 + w), (apex * w + b) / (1.0 + w)); + (Seg2::Conic { a, apex: l, b: m, w: w2 }, Seg2::Conic { a: m, apex: r, b, w: w2 }) + } + Seg2::Bezier { .. } => self.split_at(0.5), + } + } + fn area_term(&self) -> f64 { + match *self { + Seg2::Line { a, b } => 0.5 * a.cross(b), + Seg2::Arc { radius, sweep, .. } => { + let (a, b) = (self.start(), self.end()); + // Chord term plus the circular segment between chord and arc. + 0.5 * a.cross(b) + 0.5 * radius * radius * (sweep - sweep.sin()) + } + Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => integrate(self, |s, t| 0.5 * s.point_at(t).cross(s.derivative(t))), + } + } + fn chords(&self, tol: f64) -> f64 { + // A chord over 1/k of t strays at most an eighth of the second derivative's bound over k². + let bound = |d2: f64| (d2 / (8.0 * tol)).sqrt(); + match *self { + Seg2::Line { .. } => 1.0, + Seg2::Arc { radius, sweep, .. } => { + sweep.abs() / if tol < radius { 2.0 * (1.0 - tol / radius).clamp(-1.0, 1.0).acos() } else { TAU / 8.0 } + } + Seg2::Cubic { p0, p1, p2, p3 } => bound((p0 - p1 * 2.0 + p2).len().max((p1 - p2 * 2.0 + p3).len()) * 6.0), + Seg2::Conic { a, apex, b, w } => bound((a - apex * 2.0 + b).len() * 2.0 * w.max(1.0)), + Seg2::Bezier { n, ref p } => { + // Second derivative ≤ n(n−1) × the largest second difference of the controls. + let c = bez(n, p); + bound(c.windows(3).map(|w| (w[0] - w[1] * 2.0 + w[2]).len()).fold(0.0, f64::max) * (n as f64) * (n as f64 - 1.0)) + } + } + } + fn polyline(&self, tol: f64) -> Vec { + if let Seg2::Line { a, b } = *self { + return vec![a, b]; + } + let tol = if let Seg2::Arc { radius, .. } = *self { tol.max(radius.abs() * 1e-6) } else { tol }.max(1e-9); + let n = (self.chords(tol).ceil() as usize).clamp(2, 4096); + (0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect() + } +} + +/// The geometry of a profile loop ([`Loop2`]): area, orientation, containment and polylines. +pub trait Loop2Geom { + /// The radius of the largest circle inside the loop, to about `tol` ([`Region2Geom::inradius`]). + fn inradius(&self, tol: f64) -> f64; + /// Signed area: positive when counter-clockwise. + fn signed_area(&self) -> f64; + fn reversed(&self) -> Loop2; + /// Whether the loop runs counter-clockwise ([`Loop2::ccw`] keeps it as it is). + fn is_ccw(&self) -> bool; + /// Counter-clockwise copy. + fn ccw(&self) -> Loop2; + /// Each segment with the next and the last with the first: the loop's joints, where one + /// segment should end on the start of the next. + fn joints(&self) -> impl Iterator + Clone; + /// The loop as a polyline within `tol`: each segment's points but its last, which the next + /// segment starts on. + fn polyline(&self, tol: f64) -> Ring; + /// Even-odd point containment against the polyline approximation. + fn contains(&self, p: Vec2) -> bool; + /// Area-weighted centroid (of the polyline approximation). + fn centroid(&self) -> Vec2; + /// Closed within `tol`? + fn is_closed(&self, tol: f64) -> bool; +} + +impl Loop2Geom for Loop2 { + fn inradius(&self, tol: f64) -> f64 { + max_clearance(&[self.polyline(tol)]) + } + fn signed_area(&self) -> f64 { + self.segs.iter().map(Seg2::area_term).sum() + } + fn reversed(&self) -> Loop2 { + Loop2 { segs: self.segs.iter().rev().map(Seg2::reversed).collect() } + } + fn is_ccw(&self) -> bool { + self.signed_area() >= 0.0 + } + fn ccw(&self) -> Loop2 { + if self.is_ccw() { self.clone() } else { self.reversed() } + } + fn joints(&self) -> impl Iterator + Clone { + crate::chain::around(&self.segs) + } + fn polyline(&self, tol: f64) -> Ring { + self.segs + .iter() + .flat_map(|s| { + let p = s.polyline(tol); + let n = p.len().saturating_sub(1); + p.into_iter().take(n) + }) + .collect() + } + fn contains(&self, p: Vec2) -> bool { + self.polyline(1e-3).contains(p) + } + fn centroid(&self) -> Vec2 { + let poly = self.polyline(1e-3); + let n = poly.len(); + let (mut a2, mut c) = (0.0, Vec2::ZERO); + for i in 0..n { + let (Some(p), Some(q)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; + let k = p.cross(*q); + a2 += k; + c += (*p + *q) * k; + } + if a2.abs() < 1e-15 { poly.first().copied().unwrap_or_default() } else { c / (3.0 * a2) } + } + fn is_closed(&self, tol: f64) -> bool { + let n = self.segs.len(); + n > 0 + && (0..n).all(|i| match (self.segs.get(i), self.segs.get((i + 1) % n)) { + (Some(a), Some(b)) => a.end().dist(b.start()) <= tol, + _ => false, + }) + } +} + +/// The geometry of a profile region ([`Region2`]): area, containment, inradius and triangles. +pub trait Region2Geom { + fn area(&self) -> f64; + /// A point strictly inside the region (for picking and labels). + fn interior_point(&self) -> Vec2; + fn contains(&self, p: Vec2) -> bool; + /// The radius of the largest circle inside the region: how far its sides can move inwards + /// before they meet (a taper going in closes it there). Found by a grid search refined + /// around the best point, to about `tol`. + fn inradius(&self, tol: f64) -> f64; + /// Triangles covering the region (for filled display), by slabs between the vertex + /// heights: inside each slab the boundary edges don't cross, so consecutive crossings pair + /// up into trapezoids. + fn triangulate(&self, tol: f64) -> Vec<[Vec2; 3]>; + fn centroid(&self) -> Vec2; +} + +impl Region2Geom for Region2 { + fn area(&self) -> f64 { + self.outer.signed_area().abs() - self.holes.iter().map(|h| h.signed_area().abs()).sum::() + } + fn interior_point(&self) -> Vec2 { + let c = self.centroid(); + if self.contains(c) { + return c; + } + // Scan a few horizontal lines for the midpoint of the widest inside span. + let poly = self.outer.polyline(1e-2); + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for p in &poly { + y0 = y0.min(p.y); + y1 = y1.max(p.y); + } + for k in 1..16 { + let y = y0 + (y1 - y0) * k as f64 / 16.0; + let mut xs: Vec = Vec::new(); + for l in std::iter::once(&self.outer).chain(&self.holes) { + let pl = l.polyline(1e-2); + let n = pl.len(); + for i in 0..n { + let (Some(a), Some(b)) = (pl.get(i), pl.get((i + 1) % n)) else { continue }; + if (a.y > y) != (b.y > y) { + xs.push(a.x + (y - a.y) / (b.y - a.y) * (b.x - a.x)); + } + } + } + xs.sort_by(f64::total_cmp); + for w in xs.chunks(2) { + if let [a, b] = w { + let p = Vec2::new((a + b) * 0.5, y); + if self.contains(p) { + return p; + } + } + } + } + c + } + fn contains(&self, p: Vec2) -> bool { + self.outer.contains(p) && !self.holes.iter().any(|h| h.contains(p)) + } + fn inradius(&self, tol: f64) -> f64 { + let loops: Vec> = std::iter::once(&self.outer).chain(&self.holes).map(|l| l.polyline(tol)).collect(); + max_clearance(&loops) + } + fn triangulate(&self, tol: f64) -> Vec<[Vec2; 3]> { + let mut edges: Vec<(Vec2, Vec2)> = Vec::new(); + for l in std::iter::once(&self.outer).chain(&self.holes) { + let pl = l.polyline(tol); + let n = pl.len(); + for i in 0..n { + let (Some(a), Some(b)) = (pl.get(i), pl.get((i + 1) % n)) else { continue }; + if (a.y - b.y).abs() > 1e-12 { + edges.push(if a.y < b.y { (*a, *b) } else { (*b, *a) }); + } + } + } + if edges.len() > 20_000 { + return Vec::new(); + } + let mut ys: Vec = edges.iter().flat_map(|(a, b)| [a.y, b.y]).collect(); + ys.sort_by(f64::total_cmp); + ys.dedup_by(|a, b| (*a - *b).abs() < 1e-12); + let x_at = |e: &(Vec2, Vec2), y: f64| e.0.x + (y - e.0.y) / (e.1.y - e.0.y) * (e.1.x - e.0.x); + // Sweep upward: an edge joins the slabs once its lower end is passed and leaves after + // its upper end, so each slab sorts only the edges crossing it (a finely sampled ring + // has hundreds of slabs and edges, but four edges in each slab). + edges.sort_by(|a, b| a.0.y.total_cmp(&b.0.y)); + let mut next = 0; + let mut span: Vec<&(Vec2, Vec2)> = Vec::new(); + let mut out = Vec::new(); + for w in ys.windows(2) { + let (y0, y1) = (w[0], w[1]); + let ym = (y0 + y1) * 0.5; + while let Some(e) = edges.get(next) + && e.0.y <= ym + { + span.push(e); + next += 1; + } + span.retain(|e| e.1.y >= ym); + span.sort_by(|a, b| x_at(a, ym).total_cmp(&x_at(b, ym))); + for pair in span.chunks(2) { + let [l, r] = pair else { continue }; + let (a, b) = (Vec2::new(x_at(l, y0), y0), Vec2::new(x_at(r, y0), y0)); + let (c, d) = (Vec2::new(x_at(r, y1), y1), Vec2::new(x_at(l, y1), y1)); + out.push([a, b, c]); + out.push([a, c, d]); + } + } + out + } + fn centroid(&self) -> Vec2 { + let ao = self.outer.signed_area().abs(); + let mut c = self.outer.centroid() * ao; + let mut a = ao; + for h in &self.holes { + let ah = h.signed_area().abs(); + c -= h.centroid() * ah; + a -= ah; + } + if a.abs() < 1e-15 { self.outer.centroid() } else { c / a } + } +} + +// Helpers of Seg2Geom. +fn bez(n: u8, p: &[Vec2; MAX_BEZIER_CTRL]) -> &[Vec2] { + &p[..(n as usize).clamp(1, MAX_BEZIER_DEGREE) + 1] +} +/// Newton's method for the parameter of the point nearest `p`, from `t`, within [0, 1]. +fn newton_closest(seg: &Seg2, p: Vec2, mut t: f64) -> f64 { + for _ in 0..30 { + let (q, d) = (seg.point_at(t), seg.derivative(t)); + let (d2, h) = ((seg.derivative((t + 1e-6).min(1.0)) - seg.derivative((t - 1e-6).max(0.0))) / 2e-6, q - p); + let f = h.dot(d); + let df = d.dot(d) + h.dot(d2); + if df.abs() < 1e-300 { + break; + } + let nt = (t - f / df).clamp(0.0, 1.0); + if (nt - t).abs() < 1e-14 { + t = nt; + break; + } + t = nt; + } + t +} +/// ∫₀¹ f(t) dt by composite Gauss–Legendre (16 pieces of 5 points). +fn integrate(seg: &Seg2, f: impl Fn(&Seg2, f64) -> f64) -> f64 { + let n = 16; + let mut sum = 0.0; + for k in 0..n { + let (t0, h) = (k as f64 / n as f64, 1.0 / n as f64); + for (x, w) in GL5 { + sum += w * h * f(seg, t0 + x * h); + } + } + sum +} + #[cfg(test)] mod tests { use super::*; @@ -1195,6 +1178,16 @@ mod tests { assert!(s.point_at(s.closest_param(on_curve)).dist(on_curve) < 1e-9); } } + // A full circle's points just before its start, either way round: nearest just before + // its end, not at its start (Newton from the start stays held there). + for sweep in [TAU, -TAU] { + let circle = Seg2::Arc { center: Vec2::new(1.0, 2.0), radius: 5.0, start: 0.6131, sweep }; + for delta in [1e-4, 0.01, 0.04] { + let before = 0.6131 - delta * sweep.signum(); + let p = Vec2::new(1.0, 2.0) + Vec2::from_angle(before) * 4.99; + assert!((circle.point_at(circle.closest_param(p)).dist(p) - 0.01).abs() < 1e-9, "sweep {sweep}, {delta}"); + } + } } /// The sweep visits only the edges crossing each slab; it must give the triangles that diff --git a/crates/geom/src/revision_tests.rs b/crates/geom/src/revision_tests.rs index a8a0e7024..fb46b8cac 100644 --- a/crates/geom/src/revision_tests.rs +++ b/crates/geom/src/revision_tests.rs @@ -1,7 +1,7 @@ use serde_json::json; use super::*; -use crate::Vec2; +use solidcore_record::Vec2; /// A fresh id, as the design's random ids are: never one handed out before in this run. fn fresh() -> u64 { diff --git a/crates/geom/src/section.rs b/crates/geom/src/section.rs index ba3dcf665..2c9d36f1b 100644 --- a/crates/geom/src/section.rs +++ b/crates/geom/src/section.rs @@ -21,10 +21,11 @@ //! exact or certified measures for conics and freeform curves. Profile values contain geometry //! only: callers retain the original result's accuracy declarations and local identities. +use crate::prelude::*; use serde::{Deserialize, Serialize}; use crate::profile::coordinates; -use crate::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; /// Aggregate input records/references, and the selected conversion's output items, at most. /// Input counts curves, wires, regions, contacts, curve uses and hole references together. diff --git a/crates/geom/src/section_tests.rs b/crates/geom/src/section_tests.rs index 7feb71c72..2e02b95b7 100644 --- a/crates/geom/src/section_tests.rs +++ b/crates/geom/src/section_tests.rs @@ -1,7 +1,8 @@ use std::f64::consts::{PI, TAU}; use super::*; -use crate::{MAX_BEZIER_CTRL, bezier}; +use crate::bezier; +use solidcore_record::MAX_BEZIER_CTRL; const TOL: f64 = 1e-6; diff --git a/crates/geom/src/simplify.rs b/crates/geom/src/simplify.rs index 7a4c0f3fb..f3a834efe 100644 --- a/crates/geom/src/simplify.rs +++ b/crates/geom/src/simplify.rs @@ -14,10 +14,11 @@ //! triangle count, with its error measured: how far its vertices and the centres of its triangles //! lie from the original surface, at most. +use crate::prelude::*; use std::cmp::Ordering; use std::collections::BinaryHeap; -use crate::Vec3; +use solidcore_record::Vec3; /// Most triangles [`levels`] simplifies (more: no levels). pub const MAX_TRIANGLES: usize = 50_000_000; diff --git a/crates/geom/src/spline_space.rs b/crates/geom/src/spline_space.rs index 6456ee8c2..5378dcaca 100644 --- a/crates/geom/src/spline_space.rs +++ b/crates/geom/src/spline_space.rs @@ -17,8 +17,8 @@ //! Input is hostile: constructors check sizes and finiteness and return [`SplineError`]; no //! function here panics. -use crate::Vec3; use crate::bspline::{HPoint, MAX_SPLINE_DEGREE, Side, SplineError, SplineResult, check_knots, find_span, insert_knot, invalid, local_basis}; +use solidcore_record::Vec3; /// Most basis functions a space used for interpolation may have (its systems are solved densely). pub const MAX_SPACE_DIMENSION: usize = 2048; @@ -76,6 +76,30 @@ impl Linear for Vec3 { } } +/// Homogeneous points as they are: a rational spline's control values `(x·w, y·w, z·w, w)` +/// combine linearly, so carrying one into a larger space (degree elevation, knot insertion) is +/// exact on them. +impl Linear for HPoint { + fn zero() -> Self { + HPoint::ZERO + } + fn plus(self, o: Self) -> Self { + self + o + } + fn times(self, s: f64) -> Self { + self * s + } + fn to_h(self) -> HPoint { + self + } + fn from_h(h: HPoint) -> Self { + h + } + fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite() + } +} + /// A clamped B-spline space: a degree and a knot vector whose first and last `degree + 1` knots /// are the domain's ends, interior knots repeated at most `degree` times (the space's splines /// are continuous). @@ -168,6 +192,27 @@ impl Space { Ok((first, values.collect())) } + /// [`Space::basis`] from the left of `t`: at an interior knot, the derivatives of the + /// polynomial piece that ends there (elsewhere the same as from the right). + pub fn basis_left(&self, t: f64, der: usize) -> SplineResult<(usize, Vec)> { + let [a, b] = self.domain(); + if !t.is_finite() { + return invalid("a parameter is not a finite number"); + } + let t = t.clamp(a, b); + if t <= a { + return self.basis(t, der); + } + let p = self.degree; + // The span [k_s, k_{s+1}) with k_s < t ≤ k_{s+1}. + let below = self.knots.partition_point(|&x| x < t); + let span = below.checked_sub(1).filter(|s| *s >= p).ok_or_else(|| SplineError::Invalid(format!("{t} is outside the domain")))?; + let first = span - p; + let values = + (first..=span).map(|i| self.knots.get(i..i + p + 2).map_or(0.0, |k| local_basis(k, t, Side::Left, der).get(der).copied().unwrap_or(0.0))); + Ok((first, values.collect())) + } + /// The `der`-th derivative at `t` of the spline with control values `ctrl`. pub fn eval(&self, ctrl: &[T], t: f64, der: usize) -> SplineResult { if ctrl.len() != self.count() { @@ -475,6 +520,7 @@ impl Monotone { #[cfg(test)] mod tests { use super::*; + use crate::prelude::*; fn close(a: f64, b: f64) -> bool { (a - b).abs() < 1e-10 diff --git a/crates/geom/src/table.rs b/crates/geom/src/table.rs index 6fc428eb7..a04be85d0 100644 --- a/crates/geom/src/table.rs +++ b/crates/geom/src/table.rs @@ -25,9 +25,10 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use serde::{Deserialize, Serialize}; +use crate::Aabb2; use crate::cell::{self, Content, HAlign, PADDING_MM, Part, Source, Warning, check_text, is_snake_case}; use crate::paper::{Group, Item, MAX_COORDINATE_MM, MAX_LINE_MM, MAX_SIDE_MM, ObjectKind}; -use crate::{Aabb2, Loop2, Seg2, Vec2}; +use solidcore_record::{Loop2, Seg2, Vec2}; /// The most rows a table may list, and the most overrides it may keep. pub const MAX_ROWS: usize = 10_000; diff --git a/crates/geom/src/table_tests.rs b/crates/geom/src/table_tests.rs index 65e9e4ab0..e6623c332 100644 --- a/crates/geom/src/table_tests.rs +++ b/crates/geom/src/table_tests.rs @@ -1,3 +1,4 @@ +use crate::prelude::*; use serde_json::json; use super::*; diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rs index 036b32079..9fce1ad68 100644 --- a/crates/geom/src/tess.rs +++ b/crates/geom/src/tess.rs @@ -9,10 +9,16 @@ //! [`EvalSurface`] forms defined here, so the two cannot drift apart. //! //! References: Piegl & Tiller, *The NURBS Book* (2nd ed.), A2.1 (span), A2.3 (basis -//! functions and derivatives), §4.5 (derivatives of a rational surface). +//! functions and derivatives), §4.5 (derivatives of a rational surface). [`uv`] finds the +//! parameters of a point on an evaluator surface. +use crate::Mesh; use crate::bspline::MAX_SPLINE_DEGREE; -use crate::{Mesh, Vec3}; +use crate::prelude::*; +use solidcore_record::Vec3; + +pub mod partials; +pub mod uv; /// Most knots in one evaluable knot vector (bounds the shader's span search). pub const MAX_EVAL_KNOTS: usize = 1 << 12; @@ -35,10 +41,10 @@ pub struct EvalCurve { pub enum EvalSurface { /// `origin + u·du + v·dv`. Plane { origin: Vec3, du: Vec3, dv: Vec3 }, - /// A rational tensor B-spline; control point `(i, j)` is `ctrl[j·count[0] + i]`. - /// `closed[d]`: the surface joins itself along direction `d` (a B-spline tube's way round). - /// Such a direction is periodic: a parameter outside the knot range is moved by whole - /// ranges back into it, so a face whose boundary runs across the join still evaluates. + /// A rational tensor B-spline; control point `(i, j)` is `ctrl[j·count[0] + i]`. `closed`: + /// whether it closes on itself along each direction ([`uv::closed`]), worked out once by + /// [`EvalSurface::nurbs`] (every evaluation outside the knot interval asks, and the test + /// walks the whole control net). Nurbs { degree: [usize; 2], knots: [Vec; 2], count: [usize; 2], ctrl: Vec<[f64; 4]>, closed: [bool; 2] }, /// `profile(u)` turned by the angle `v` (right-handed) about the axis through `origin` /// along the unit `axis`, then mapped by the affine `transform` (row-major 3×4); with @@ -66,6 +72,13 @@ pub struct FacePlan { pub triangles: Vec<[u32; 3]>, } +impl FacePlan { + /// Triangle `t` is on this face's own nodes (the evaluated mesh keeps only those). + fn has_nodes(&self, t: &[u32; 3]) -> bool { + t.iter().all(|&i| (i as usize) < self.uv.len()) + } +} + /// A body's display tessellation, ready to evaluate. #[derive(Clone, Debug, Default, PartialEq)] pub struct TessPlan { @@ -94,9 +107,8 @@ impl TessPlan { out.positions.push(p); out.normals.push(if f.flip { -n } else { n }); } - let n = f.uv.len(); for t in &f.triangles { - if t.iter().all(|&i| (i as usize) < n) { + if f.has_nodes(t) { let at = |i: u32| u32::try_from(base + i as usize).unwrap_or(u32::MAX); out.triangles.push([at(t[0]), at(t[1]), at(t[2])]); out.tri_face.push(f.face); @@ -108,6 +120,20 @@ impl TessPlan { out } + /// Which of the body's `faces` faces have triangles in [`TessPlan::evaluate`]'s mesh, + /// without evaluating it. + pub fn faces_with_triangles(&self, faces: usize) -> Vec { + let mut has = vec![false; faces]; + for f in &self.faces { + if f.triangles.iter().any(|t| f.has_nodes(t)) + && let Some(h) = has.get_mut(f.face as usize) + { + *h = true; + } + } + has + } + /// Vertices across all faces. pub fn vertex_count(&self) -> usize { self.faces.iter().map(|f| f.uv.len()).sum() @@ -133,6 +159,8 @@ impl TessPlan { EvalSurface::Plane { origin, du, dv } => EvalSurface::Plane { origin: point(*origin), du: vector(*du), dv: vector(*dv) }, EvalSurface::Nurbs { degree, knots, count, ctrl, closed } => EvalSurface::Nurbs { degree: *degree, + // An affine map keeps a surface closed or open. + closed: *closed, knots: knots.clone(), count: *count, // Homogeneous: the translation scales with the weight. @@ -143,9 +171,6 @@ impl TessPlan { [q.x, q.y, q.z, c[3]] }) .collect(), - // Which directions the surface joins itself along is a property of its - // parameters: moving the surface does not change it. - closed: *closed, }, EvalSurface::Revolved { profile, origin, axis, transform, swap } => { // `m` (as rows) after the surface's own affine map. @@ -190,7 +215,31 @@ impl EvalCurve { if p == 0 || p > MAX_SPLINE_DEGREE || n <= p || self.knots.len() != n + p + 1 || !t.is_finite() { return None; } - let span = span_of(&self.knots, p, n, t); + self.eval_on(span_of(&self.knots, p, n, t), t) + } + + /// The first derivative at `t` from either side: on the knot spans that end and start + /// there where `t` is a knot (the polynomials either side of it), else the derivative twice. + pub fn sides(&self, t: f64) -> Option<(Vec3, Vec3)> { + let p = self.degree; + let n = self.ctrl.len(); + if p == 0 || p > MAX_SPLINE_DEGREE || n <= p || self.knots.len() != n + p + 1 || !t.is_finite() { + return None; + } + let right = span_of(&self.knots, p, n, t); + // The last non-empty span before `t`'s, when `t` is where it starts. + let left = match self.knots.get(right) { + Some(&k) if k == t => { + (p..right).rev().find(|&i| matches!((self.knots.get(i), self.knots.get(i + 1)), (Some(a), Some(b)) if a < b)).unwrap_or(right) + } + _ => right, + }; + Some((self.eval_on(left, t)?.1, self.eval_on(right, t)?.1)) + } + + /// Point and first derivative at `t` of the polynomial on knot span `span`. + fn eval_on(&self, span: usize, t: f64) -> Option<(Vec3, Vec3)> { + let p = self.degree; let ders = basis_ders(&self.knots, span, p, t)?; let (mut a, mut da) = ([0.0; 4], [0.0; 4]); for (k, (n0, n1)) in ders[0].iter().zip(&ders[1]).take(p + 1).enumerate() { @@ -205,6 +254,12 @@ impl EvalCurve { } impl EvalSurface { + /// The rational tensor B-spline [`EvalSurface::Nurbs`], with whether it closes on itself. + pub fn nurbs(degree: [usize; 2], knots: [Vec; 2], count: [usize; 2], ctrl: Vec<[f64; 4]>) -> EvalSurface { + let closed = uv::closed(degree, &knots, count, &ctrl); + EvalSurface::Nurbs { degree, knots, count, ctrl, closed } + } + /// Point and unit normal (`S_u × S_v`, oriented as the surface) at `(u, v)`. A degenerate /// point (a cone's apex, a sphere's pole) takes its normal from a step inside; anything /// that still fails gives the origin and +Z rather than a NaN. @@ -214,10 +269,15 @@ impl EvalSurface { if let Some(n) = n.normalized().filter(|_| n.len2() > 1e-20 * (du.len2() * dv.len2()).max(1e-300)) { return (p, n); } - // Step into the parameter domain around the degenerate point. + // Step into the parameter domain around the degenerate point: never past the end of an + // interval, where the extrapolated surface folds back over the pole and its normal + // points the other way. let h = 1e-6 * (1.0 + u.abs().max(v.abs())); + let inside = |d: usize, t: f64, s: f64| self.interval(d).is_none_or(|(lo, hi)| (lo..=hi).contains(&(t + s * h))); for (su, sv) in [(1.0, 1.0), (-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)] { - if let Some((_, a, b)) = self.derivs(u + su * h, v + sv * h) + if inside(0, u, su) + && inside(1, v, sv) + && let Some((_, a, b)) = self.derivs(u + su * h, v + sv * h) && let Some(n) = self.oriented(a.cross(b)).normalized() { return (p, n); @@ -226,6 +286,18 @@ impl EvalSurface { (p, Vec3::Z) } + /// The active parameter interval along `d` (0: u, 1: v) of a spline, or of a revolution's + /// profile; `None` where the parameter is unbounded (a plane, a revolution's angle). + fn interval(&self, d: usize) -> Option<(f64, f64)> { + match self { + EvalSurface::Plane { .. } => None, + EvalSurface::Nurbs { degree, knots, count, .. } => Some((*knots.get(d)?.get(*degree.get(d)?)?, *knots.get(d)?.get(*count.get(d)?)?)), + EvalSurface::Revolved { profile, swap, .. } => { + (d == usize::from(*swap)).then(|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?))).flatten() + } + } + } + /// Mirror transforms reverse the cross product of the mapped derivatives. fn oriented(&self, n: Vec3) -> Vec3 { match self { @@ -234,28 +306,49 @@ impl EvalSurface { } } - /// Point and first partial derivatives. + /// `uv` with each parameter along which a spline closes on itself (or a revolution's + /// profile does) moved by whole periods into the active knot interval (unchanged inside it, + /// and for any other surface): the parameters both evaluators take for a point of a closed + /// spline found a period away. + pub fn wrap(&self, uv: [f64; 2]) -> [f64; 2] { + if let EvalSurface::Revolved { profile, swap, .. } = self { + let d = usize::from(*swap); + let range = self.interval(d); + let mut out = uv; + if let (Some(r), Some(x)) = (range, out.get_mut(d)) + && !(r.0..=r.1).contains(x) + && uv::closed_curve(profile) + { + *x = uv::wrap_into(*x, r); + } + return out; + } + let EvalSurface::Nurbs { closed, .. } = self else { return uv }; + let mut out = uv; + for d in 0..2 { + if let (true, Some(r)) = (closed[d], self.interval(d)) + && !(r.0..=r.1).contains(&uv[d]) + { + out[d] = uv::wrap_into(uv[d], r); + } + } + out + } + + /// Point and first partial derivatives (a closed spline's parameters wrapped into its + /// active interval first, [`EvalSurface::wrap`]). pub fn derivs(&self, u: f64, v: f64) -> Option<(Vec3, Vec3, Vec3)> { if !(u.is_finite() && v.is_finite()) { return None; } match self { EvalSurface::Plane { origin, du, dv } => Some((*origin + *du * u + *dv * v, *du, *dv)), - EvalSurface::Nurbs { degree, knots, count, ctrl, closed } => { - // The knot range of direction `d`: the parameters the surface is defined over. - let range = |d: usize| -> Option<(f64, f64)> { - let k = knots.get(d)?; - Some((*k.get(*degree.get(d)?)?, *k.get(*count.get(d)?)?)) - }; - // A direction the surface joins itself along repeats, so a parameter outside the - // range is moved by whole ranges back into it. Any other direction is left alone. - let wrap = |d: usize, t: f64| match range(d) { - Some((a, b)) if closed.get(d).copied().unwrap_or(false) && b > a && !(a..=b).contains(&t) => a + (t - a).rem_euclid(b - a), - _ => t, - }; - nurbs_derivs(*degree, knots, *count, ctrl, wrap(0, u), wrap(1, v)) + EvalSurface::Nurbs { degree, knots, count, ctrl, .. } => { + let [u, v] = self.wrap([u, v]); + nurbs_derivs(*degree, knots, *count, ctrl, u, v) } EvalSurface::Revolved { profile, origin, axis, transform, swap } => { + let [u, v] = self.wrap([u, v]); let (s, a) = if *swap { (v, u) } else { (u, v) }; let (c, dc) = profile.eval(s)?; let (sin, cos) = a.sin_cos(); @@ -272,6 +365,89 @@ impl EvalSurface { } } +impl EvalSurface { + /// The second partial derivatives `(S_uu, S_uv, S_vv)` at (u, v) of a plane or spline (zero + /// on a plane); `None` for a revolution (its profile carries first derivatives only) and + /// where the spline cannot be evaluated. + pub fn second(&self, u: f64, v: f64) -> Option<(Vec3, Vec3, Vec3)> { + if !(u.is_finite() && v.is_finite()) { + return None; + } + match self { + EvalSurface::Plane { .. } => Some((Vec3::ZERO, Vec3::ZERO, Vec3::ZERO)), + EvalSurface::Nurbs { degree, knots, count, ctrl, .. } => { + let [u, v] = self.wrap([u, v]); + nurbs_second(*degree, knots, *count, ctrl, u, v) + } + EvalSurface::Revolved { .. } => None, + } + } +} + +/// The values and first two derivatives of the `p + 1` basis functions of degree `p` alive at +/// `t` ([`crate::bspline::basis_derivatives`]), and the span they live on. A `t` past an end of +/// the knot range by no more than rounding (a boundary point carried off by a pcurve's +/// evaluation, which [`nurbs_derivs`] takes as it is) is that end: the basis functions are zero +/// outside their supports, so the derivatives there would not exist. +fn basis_second(knots: &[f64], p: usize, n: usize, t: f64) -> Option<(usize, Vec<[f64; 3]>)> { + let (first, ders) = crate::bspline::basis_derivatives(knots, p, n, onto_knots(knots, p, n, t)?, 2)?; + Some((first + p, ders.iter().map(|d| Some([*d.first()?, *d.get(1)?, *d.get(2)?])).collect::>()?)) +} + +/// `t`, or the end of the knot range of a spline of degree `p` over `n` points when `t` is past +/// it by no more than rounding ([`basis_second`]). +pub(crate) fn onto_knots(knots: &[f64], p: usize, n: usize, t: f64) -> Option { + let (&lo, &hi) = (knots.get(p)?, knots.get(n)?); + let slack = BOUNDARY_ROUNDING * (hi - lo).abs().max(lo.abs()).max(hi.abs()).max(1.0); + Some(if t < lo && t >= lo - slack { + lo + } else if t > hi && t <= hi + slack { + hi + } else { + t + }) +} + +/// How far past its knot range, relative to the range's magnitude, a parameter is still the range's +/// end: the room a pcurve's interval has for rounding (`brep::topology::PCURVE_INTERVAL`). +const BOUNDARY_ROUNDING: f64 = 1e-9; + +fn nurbs_second(degree: [usize; 2], knots: &[Vec; 2], count: [usize; 2], ctrl: &[[f64; 4]], u: f64, v: f64) -> Option<(Vec3, Vec3, Vec3)> { + let [pu, pv] = degree; + let [nu, nv] = count; + let ok = |p: usize, n: usize, k: &[f64]| (1..=MAX_SPLINE_DEGREE).contains(&p) && n > p && k.len() == n + p + 1; + if !ok(pu, nu, &knots[0]) || !ok(pv, nv, &knots[1]) || nu.checked_mul(nv)? != ctrl.len() { + return None; + } + let ((su, bu), (sv, bv)) = (basis_second(&knots[0], pu, nu, u)?, basis_second(&knots[1], pv, nv, v)?); + // Homogeneous sums: [A, A_u, A_v, A_uu, A_uv, A_vv]. + let mut a = [[0.0f64; 4]; 6]; + for (j, bj) in bv.iter().enumerate() { + for (i, bi) in bu.iter().enumerate() { + let c = ctrl.get((sv + j - pv) * nu + su + i - pu)?; + let w = [bi[0] * bj[0], bi[1] * bj[0], bi[0] * bj[1], bi[2] * bj[0], bi[1] * bj[1], bi[0] * bj[2]]; + for (sum, w) in a.iter_mut().zip(w) { + for d in 0..4 { + sum[d] += w * c[d]; + } + } + } + } + let w = a[0][3]; + if !(w.abs() > 1e-300) { + return None; + } + let xyz = |h: &[f64; 4]| Vec3::new(h[0], h[1], h[2]); + // S = A / w, differentiated by the quotient rule. + let s = xyz(&a[0]) * (1.0 / w); + let su_ = (xyz(&a[1]) - s * a[1][3]) * (1.0 / w); + let sv_ = (xyz(&a[2]) - s * a[2][3]) * (1.0 / w); + let suu = (xyz(&a[3]) - su_ * (2.0 * a[1][3]) - s * a[3][3]) * (1.0 / w); + let suv = (xyz(&a[4]) - su_ * a[2][3] - sv_ * a[1][3] - s * a[4][3]) * (1.0 / w); + let svv = (xyz(&a[5]) - sv_ * (2.0 * a[2][3]) - s * a[5][3]) * (1.0 / w); + (suu.is_finite() && suv.is_finite() && svv.is_finite()).then_some((suu, suv, svv)) +} + fn affine(m: &[[f64; 4]; 3], p: Vec3) -> Vec3 { linear(m, p) + Vec3::new(m[0][3], m[1][3], m[2][3]) } @@ -305,7 +481,9 @@ fn nurbs_derivs(degree: [usize; 2], knots: &[Vec; 2], count: [usize; 2], ct return None; } let (su, sv) = (span_of(&knots[0], pu, nu, u), span_of(&knots[1], pv, nv, v)); - let (bu, bv) = (basis_ders(&knots[0], su, pu, u)?, basis_ders(&knots[1], sv, pv, v)?); + let (mut bu, mut bv) = ([[0.0f64; W]; 2], [[0.0f64; W]; 2]); + basis_ders_into(&knots[0], su, pu, u, &mut bu)?; + basis_ders_into(&knots[1], sv, pv, v, &mut bv)?; let (mut s, mut s_u, mut s_v) = ([0.0; 4], [0.0; 4], [0.0; 4]); for (b, (nv0, nv1)) in bv[0].iter().zip(&bv[1]).take(pv + 1).enumerate() { for (a, (nu0, nu1)) in bu[0].iter().zip(&bu[1]).take(pu + 1).enumerate() { @@ -340,51 +518,71 @@ pub(crate) fn span_of(knots: &[f64], p: usize, n: usize, t: f64) -> usize { k } +/// The non-zero basis functions of degree `p` on span `span` (NURBS Book A2.2): element `j` is +/// `N_{span−p+j}`. +fn basis_funs(knots: &[f64], span: usize, p: usize, t: f64, n: &mut [f64; W]) -> Option<()> { + if p >= W { + return None; + } + let kn = |i: usize| knots.get(i).copied(); + n.fill(0.0); + n[0] = 1.0; + for j in 1..=p { + let mut saved = 0.0; + for (r, nr) in n.iter_mut().enumerate().take(j) { + // right[r + 1] and left[j − r] of A2.2. + let right = kn(span + r + 1)? - t; + let left = t - kn((span + 1 + r).checked_sub(j)?)?; + let den = right + left; + let temp = if den != 0.0 { *nr / den } else { 0.0 }; + *nr = saved + right * temp; + saved = left * temp; + } + n[j] = saved; + } + Some(()) +} + /// Non-zero basis functions of degree `p` on span `span` and their first derivatives -/// (NURBS Book A2.3 with n = 1). `ders[0][j]` is `N_{span−p+j}`, `ders[1][j]` its derivative. +/// (NURBS Book eq. 2.7, from the degree p − 1 functions on the same span). `ders[0][j]` is +/// `N_{span−p+j}`, `ders[1][j]` its derivative. One-dimensional tables, as the GPU twin keeps +/// them, so a high degree costs its own work only. pub(crate) fn basis_ders(knots: &[f64], span: usize, p: usize, t: f64) -> Option<[[f64; W]; 2]> { + let mut ders = [[0.0f64; W]; 2]; + basis_ders_into(knots, span, p, t, &mut ders)?; + Some(ders) +} + +/// [`basis_ders`] into a table the caller keeps: surface evaluation runs this for every point, +/// and moving the tables by value took about a quarter of the time of meshing a curved face. +fn basis_ders_into(knots: &[f64], span: usize, p: usize, t: f64, ders: &mut [[f64; W]; 2]) -> Option<()> { if p == 0 || p >= W { return None; } let kn = |i: usize| knots.get(i).copied(); - // ndu[j][r]: basis values (upper triangle incl. diagonal), knot differences (lower). - let mut ndu = [[0.0f64; W]; W]; - let (mut left, mut right) = ([0.0f64; W], [0.0f64; W]); - ndu[0][0] = 1.0; - for j in 1..=p { - left[j] = t - kn((span + 1).checked_sub(j)?)?; - right[j] = kn(span + j)? - t; - let mut saved = 0.0; - for r in 0..j { - ndu[j][r] = right[r + 1] + left[j - r]; - let temp = if ndu[j][r] != 0.0 { ndu[r][j - 1] / ndu[j][r] } else { 0.0 }; - ndu[r][j] = saved + right[r + 1] * temp; - saved = left[j - r] * temp; - } - ndu[j][j] = saved; - } - let mut ders = [[0.0f64; W]; 2]; - for j in 0..=p { - ders[0][j] = ndu[j][p]; - } - // First derivative: p·(N_{r,p−1}/(u_{r+p}−u_r) − N_{r+1,p−1}/(u_{r+p+1}−u_{r+1})). - for r in 0..=p { + let [values, slopes] = ders; + // The degree p − 1 functions first, kept in the derivative row: walked from the top down, so + // each slot still holds them when it and the slot above it are read. + basis_funs(knots, span, p - 1, t, slopes)?; + basis_funs(knots, span, p, t, values)?; + // N'_{i,p} = p·(N_{i,p−1}/(u_{i+p}−u_i) − N_{i+1,p−1}/(u_{i+p+1}−u_{i+1})), i = span − p + r. + for r in (0..=p).rev() { let mut d = 0.0; if r >= 1 { - let den = ndu[p][r - 1]; + let den = kn(span + r)? - kn((span + r).checked_sub(p)?)?; if den != 0.0 { - d += ndu[r - 1][p - 1] / den; + d += slopes[r - 1] / den; } } if r < p { - let den = ndu[p][r]; + let den = kn(span + r + 1)? - kn((span + r + 1).checked_sub(p)?)?; if den != 0.0 { - d -= ndu[r][p - 1] / den; + d -= slopes[r] / den; } } - ders[1][r] = d * p as f64; + slopes[r] = d * p as f64; } - Some(ders) + Some(()) } #[cfg(test)] @@ -404,13 +602,12 @@ mod tests { let m = [[c, s, 0.0, 0.0], [-s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [5.0, -2.0, 7.0, 1.0]]; let apply = |p: Vec3| Vec3::new(c * p.x - s * p.y + 5.0, s * p.x + c * p.y - 2.0, p.z + 7.0); let w = std::f64::consts::FRAC_1_SQRT_2; - let nurbs = EvalSurface::Nurbs { - degree: [2, 1], - knots: [vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], - count: [3, 2], - ctrl: vec![[1.0, 0.0, 0.0, 1.0], [w, w, 0.0, w], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 2.0, 1.0], [w, w, 2.0 * w, w], [0.0, 1.0, 2.0, 1.0]], - closed: [false, false], - }; + let nurbs = EvalSurface::nurbs( + [2, 1], + [vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], + [3, 2], + vec![[1.0, 0.0, 0.0, 1.0], [w, w, 0.0, w], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 2.0, 1.0], [w, w, 2.0 * w, w], [0.0, 1.0, 2.0, 1.0]], + ); let revolved = EvalSurface::Revolved { profile: line(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 1.0)), origin: Vec3::ZERO, @@ -521,8 +718,10 @@ mod tests { let (u, v) = (i as f64 / 10.0, j as f64); let (p, n) = s.eval(u, v); assert!((p.len() - 3.0).abs() < 1e-12, "{p:?}"); - // At the pole (u = 1) the normal comes from a step inside: within ~1e-6 rad. - assert!(n.cross(p).len() < 3e-5, "normal {n:?} not radial at {p:?}"); + // S_u × S_v points into this sphere. At the pole (u = 1) the normal comes from + // a step inside: within ~1e-6 rad, and the same way (a step past the pole would + // turn it over). + assert!(n.cross(p).len() < 3e-5 && n.dot(p) < 0.0, "normal {n:?} not inward at {p:?}"); } } } @@ -531,13 +730,7 @@ mod tests { fn bilinear_nurbs_patch_and_derivatives() { // Degree (1, 1) over [0, 2] × [0, 1] with corners lifted: a hyperbolic paraboloid. let ctrl = vec![[0.0, 0.0, 0.0, 1.0], [2.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [2.0, 1.0, 1.0, 1.0]]; - let s = EvalSurface::Nurbs { - degree: [1, 1], - knots: [vec![0.0, 0.0, 2.0, 2.0], vec![0.0, 0.0, 1.0, 1.0]], - count: [2, 2], - ctrl, - closed: [false, false], - }; + let s = EvalSurface::nurbs([1, 1], [vec![0.0, 0.0, 2.0, 2.0], vec![0.0, 0.0, 1.0, 1.0]], [2, 2], ctrl); let Some((p, du, dv)) = s.derivs(1.0, 0.5) else { panic!("evaluates") }; assert!(close(p, Vec3::new(1.0, 0.5, 0.25), 1e-12), "{p:?}"); assert!(close(du, Vec3::new(1.0, 0.0, 0.25), 1e-12), "{du:?}"); @@ -559,7 +752,7 @@ mod tests { } let Ok(reference) = crate::bspline::NurbsSurface::new([3, 2], knots.clone(), &pts, &wts) else { panic!("valid surface") }; let ctrl = reference.homogeneous().iter().map(|h| [h.x, h.y, h.z, h.w]).collect(); - let s = EvalSurface::Nurbs { degree: [3, 2], knots, count: [nu, nv], ctrl, closed: [false, false] }; + let s = EvalSurface::nurbs([3, 2], knots, [nu, nv], ctrl); for i in 0..=8 { for j in 0..=8 { let (u, v) = (i as f64 / 8.0, j as f64 / 4.0); @@ -583,14 +776,8 @@ mod tests { #[test] fn hostile_surfaces_do_not_panic() { let bad = [ - EvalSurface::Nurbs { degree: [9, 1], knots: [vec![0.0; 3], vec![0.0; 3]], count: [1, 1], ctrl: vec![], closed: [false, false] }, - EvalSurface::Nurbs { - degree: [1, 1], - knots: [vec![0.0, 0.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], - count: [2, 2], - ctrl: vec![[0.0; 4]; 4], - closed: [false, false], - }, + EvalSurface::nurbs([9, 1], [vec![0.0; 3], vec![0.0; 3]], [1, 1], vec![]), + EvalSurface::nurbs([1, 1], [vec![0.0, 0.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], [2, 2], vec![[0.0; 4]; 4]), EvalSurface::Revolved { profile: EvalCurve { degree: 0, knots: vec![], ctrl: vec![] }, origin: Vec3::ZERO, @@ -629,5 +816,19 @@ mod tests { assert_eq!(m.triangles, vec![[0, 1, 2]]); assert_eq!(m.tri_face, vec![3]); assert!(m.normals.iter().all(|n| close(*n, -Vec3::Z, 1e-12))); + // Faces with triangles, counted without evaluating, are the faces the mesh has: not a + // face whose only triangle is off its nodes, nor one with none, nor one out of range. + let mut plan = plan; + let only = |face: u32, triangles: Vec<[u32; 3]>| FacePlan { face, uv: vec![[0.0, 0.0]; 3], triangles, ..Default::default() }; + plan.faces.extend([only(0, vec![[0, 1, 9]]), only(1, vec![]), only(2, vec![[2, 1, 0]]), only(7, vec![[0, 1, 2]])]); + let has = plan.faces_with_triangles(5); + let mut evaluated = vec![false; 5]; + for f in plan.evaluate().tri_face { + if let Some(h) = evaluated.get_mut(f as usize) { + *h = true; + } + } + assert_eq!(has, evaluated); + assert_eq!(has, vec![false, false, true, true, false]); } } diff --git a/crates/geom/src/tess/partials.rs b/crates/geom/src/tess/partials.rs new file mode 100644 index 000000000..64f390a50 --- /dev/null +++ b/crates/geom/src/tess/partials.rs @@ -0,0 +1,269 @@ +//! Exact partial derivatives of the display evaluator's surfaces up to the fourth order, and the +//! derivatives of a rational spline curve: what a seam's change of curvature (G3) and the change +//! of that change (G4) are read from. Splines differentiate their basis functions +//! ([`crate::bspline::basis_derivatives`]) and divide out the weight by Leibniz's rule (NURBS +//! Book eq. 4.8 and 4.20); a revolution turns its profile's derivatives by the rotation's own. + +use super::{EvalCurve, EvalSurface, affine, linear, onto_knots}; +use crate::bspline::{MAX_SPLINE_DEGREE, basis_derivatives, binomial}; +use crate::prelude::*; +use solidcore_record::Vec3; + +/// The highest total order of [`Partials`]. +pub const MAX_PARTIAL_ORDER: usize = 4; + +/// A surface's partial derivatives at a point: `d[i][j]` is `∂^(i+j) S / ∂u^i ∂v^j`, filled for +/// `i + j ≤` [`MAX_PARTIAL_ORDER`] (`d[0][0]` the point itself) and zero past it. +pub type Partials = [[Vec3; MAX_PARTIAL_ORDER + 1]; MAX_PARTIAL_ORDER + 1]; + +/// The pairs `(i, j)` with `i + j ≤ MAX_PARTIAL_ORDER`. +pub(crate) fn orders() -> impl Iterator { + (0..=MAX_PARTIAL_ORDER).flat_map(|i| (0..=MAX_PARTIAL_ORDER - i).map(move |j| (i, j))) +} + +/// A table of partials from `f(i, j)`; `None` when one is missing or not finite. +pub(crate) fn tabulate(mut f: impl FnMut(usize, usize) -> Option) -> Option { + let mut d = [[Vec3::ZERO; MAX_PARTIAL_ORDER + 1]; MAX_PARTIAL_ORDER + 1]; + for (i, j) in orders() { + let x = f(i, j).filter(|x| x.is_finite())?; + *d.get_mut(i)?.get_mut(j)? = x; + } + Some(d) +} + +impl EvalSurface { + /// The partial derivatives at (u, v) up to the fourth order ([`Partials`]), exactly: a closed + /// spline's parameters wrapped first as in [`EvalSurface::derivs`]. `None` where the surface + /// cannot be evaluated (a malformed spline, a vanishing weight). + pub fn partials(&self, u: f64, v: f64) -> Option { + if !(u.is_finite() && v.is_finite()) { + return None; + } + match self { + EvalSurface::Plane { origin, du, dv } => tabulate(|i, j| { + Some(match (i, j) { + (0, 0) => *origin + *du * u + *dv * v, + (1, 0) => *du, + (0, 1) => *dv, + _ => Vec3::ZERO, + }) + }), + EvalSurface::Nurbs { degree, knots, count, ctrl, .. } => { + let [u, v] = self.wrap([u, v]); + nurbs_partials(*degree, knots, *count, ctrl, u, v) + } + EvalSurface::Revolved { profile, origin, axis, transform, swap } => { + let [u, v] = self.wrap([u, v]); + let (s, a) = if *swap { (v, u) } else { (u, v) }; + let c = profile.derivatives(s, MAX_PARTIAL_ORDER)?; + let turned = |i: usize, j: usize| -> Option { + // The profile's i-th derivative (its point taken about the axis), turned by + // the j-th derivative of the rotation. + let x = if i == 0 { *c.first()? - *origin } else { *c.get(i)? }; + let r = rotation_derivative(*axis, x, a, j); + Some(if i == 0 && j == 0 { affine(transform, *origin + r) } else { linear(transform, r) }) + }; + tabulate(|i, j| if *swap { turned(j, i) } else { turned(i, j) }) + } + } + } +} + +/// The `j`-th derivative by the angle `a` of `x` turned by `a` about the unit `axis` (Rodrigues: +/// `x cos a + (axis × x) sin a + axis (axis · x)(1 − cos a)`). +fn rotation_derivative(axis: Vec3, x: Vec3, a: f64, j: usize) -> Vec3 { + let (cos, sin) = trig_derivative(a, j); + let along = axis * axis.dot(x); + let constant = if j == 0 { along } else { Vec3::ZERO }; + x * cos + axis.cross(x) * sin - along * cos + constant +} + +/// The `k`-th derivatives of cos and sin at `t`: `cos(t + kπ/2)` and `sin(t + kπ/2)`. +pub(crate) fn trig_derivative(t: f64, k: usize) -> (f64, f64) { + let (sin, cos) = t.sin_cos(); + match k % 4 { + 0 => (cos, sin), + 1 => (-sin, cos), + 2 => (-cos, -sin), + _ => (sin, -cos), + } +} + +/// The basis functions alive at `t` and their derivatives up to `order`: the index of the first +/// and, for each, element `k` its `k`-th derivative (a `t` past an end by rounding is that end). +fn basis(knots: &[f64], p: usize, n: usize, t: f64, order: usize) -> Option<(usize, Vec>)> { + basis_derivatives(knots, p, n, onto_knots(knots, p, n, t)?, order) +} + +fn valid(p: usize, n: usize, knots: &[f64]) -> bool { + (1..=MAX_SPLINE_DEGREE).contains(&p) && n > p && knots.len() == n + p + 1 +} + +fn xyz(h: [f64; 4]) -> Vec3 { + Vec3::new(h[0], h[1], h[2]) +} + +fn nurbs_partials(degree: [usize; 2], knots: &[Vec; 2], count: [usize; 2], ctrl: &[[f64; 4]], u: f64, v: f64) -> Option { + let [pu, pv] = degree; + let [nu, nv] = count; + if !valid(pu, nu, &knots[0]) || !valid(pv, nv, &knots[1]) || nu.checked_mul(nv)? != ctrl.len() { + return None; + } + let ((fu, bu), (fv, bv)) = (basis(&knots[0], pu, nu, u, MAX_PARTIAL_ORDER)?, basis(&knots[1], pv, nv, v, MAX_PARTIAL_ORDER)?); + // The homogeneous partials A_ij = Σ N_a^(i) N_b^(j) P_ab (weights in the fourth place). + let mut a = [[[0.0f64; 4]; MAX_PARTIAL_ORDER + 1]; MAX_PARTIAL_ORDER + 1]; + for (jb, nb) in bv.iter().enumerate() { + for (ia, na) in bu.iter().enumerate() { + let c = ctrl.get((fv + jb) * nu + fu + ia)?; + for (i, j) in orders() { + let w = na.get(i)? * nb.get(j)?; + let sum = a.get_mut(i)?.get_mut(j)?; + for (s, c) in sum.iter_mut().zip(c) { + *s += w * c; + } + } + } + } + let w = a[0][0][3]; + if !(w.abs() > 1e-300) { + return None; + } + // S_kl = (A_kl − Σ_{(i,j) ≠ (0,0)} C(k,i) C(l,j) w_ij S_(k−i)(l−j)) / w, lower orders first. + let mut d = [[Vec3::ZERO; MAX_PARTIAL_ORDER + 1]; MAX_PARTIAL_ORDER + 1]; + for total in 0..=MAX_PARTIAL_ORDER { + for k in 0..=total { + let l = total - k; + let mut x = xyz(a[k][l]); + for (i, j) in (0..=k).flat_map(|i| (0..=l).map(move |j| (i, j))).filter(|ij| *ij != (0, 0)) { + x -= d[k - i][l - j] * (binomial(k, i) * binomial(l, j) * a[i][j][3]); + } + d[k][l] = x * (1.0 / w); + } + } + tabulate(|i, j| d.get(i)?.get(j).copied()) +} + +impl EvalCurve { + /// The point and derivatives up to `order` at `t` (element `k` the `k`-th), exactly: the + /// weight divided out by Leibniz's rule. `None` if the curve is malformed or its weight + /// vanishes there. + pub fn derivatives(&self, t: f64, order: usize) -> Option> { + let (p, n) = (self.degree, self.ctrl.len()); + if !valid(p, n, &self.knots) || !t.is_finite() || order > MAX_PARTIAL_ORDER { + return None; + } + let (first, b) = basis(&self.knots, p, n, t, order)?; + let mut a = vec![[0.0f64; 4]; order + 1]; + for (k, nk) in b.iter().enumerate() { + let c = self.ctrl.get(first + k)?; + for (ak, w) in a.iter_mut().zip(nk) { + for (s, c) in ak.iter_mut().zip(c) { + *s += w * c; + } + } + } + let w = a.first()?[3]; + if !(w.abs() > 1e-300) { + return None; + } + let mut d: Vec = Vec::with_capacity(order + 1); + for k in 0..=order { + let mut x = xyz(*a.get(k)?); + for i in 1..=k { + x -= *d.get(k - i)? * (binomial(k, i) * a.get(i)?[3]); + } + d.push(x * (1.0 / w)); + } + d.iter().all(|x| x.is_finite()).then_some(d) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + /// Within `tol`, relative to the larger length (at least 1). + fn close(a: Vec3, b: Vec3, tol: f64) -> bool { + a.dist(b) <= tol * (1.0 + a.len().max(b.len())) + } + + fn quarter_cylinder() -> EvalSurface { + // A rational quadratic quarter circle of radius 2 in u, a line 3 long in v: exact. + let w = std::f64::consts::FRAC_1_SQRT_2; + EvalSurface::nurbs( + [2, 1], + [vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], + [3, 2], + vec![ + [2.0, 0.0, 0.0, 1.0], + [2.0 * w, 2.0 * w, 0.0, w], + [0.0, 2.0, 0.0, 1.0], + [2.0, 0.0, 3.0, 1.0], + [2.0 * w, 2.0 * w, 3.0 * w, w], + [0.0, 2.0, 3.0, 1.0], + ], + ) + } + + #[test] + fn every_partial_is_the_derivative_of_the_order_below() { + let line = EvalCurve { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], ctrl: vec![[2.0, 0.0, 0.0, 1.0], [3.0, 0.0, 1.0, 1.0]] }; + let cubic = EvalSurface::nurbs( + [3, 2], + [vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]], + [4, 3], + (0..12).map(|k| [k as f64 * 0.7, (k * k) as f64 * 0.1, (k % 5) as f64, 1.0 + 0.1 * (k % 3) as f64]).collect(), + ); + let surfaces = [ + quarter_cylinder(), + cubic, + EvalSurface::Revolved { + profile: line, + origin: Vec3::ZERO, + axis: Vec3::Z, + transform: [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, -1.0, 2.0], [0.0, 1.0, 0.0, 3.0]], + swap: true, + }, + ]; + let h = 1e-4; + for s in &surfaces { + let (u, v) = (0.37, 0.61); + let d = s.partials(u, v).unwrap(); + let (p, su, sv) = s.derivs(u, v).unwrap(); + assert!(close(d[0][0], p, 1e-12) && close(d[1][0], su, 1e-12) && close(d[0][1], sv, 1e-12), "{s:?}"); + let (up, um) = (s.partials(u + h, v).unwrap(), s.partials(u - h, v).unwrap()); + let (vp, vm) = (s.partials(u, v + h).unwrap(), s.partials(u, v - h).unwrap()); + for (i, j) in orders().filter(|(i, j)| i + j < MAX_PARTIAL_ORDER) { + let du = (up[i][j] - um[i][j]) * (0.5 / h); + let dv = (vp[i][j] - vm[i][j]) * (0.5 / h); + assert!(close(du, d[i + 1][j], 1e-5), "d/du of ({i},{j}): {du:?} vs {:?}", d[i + 1][j]); + assert!(close(dv, d[i][j + 1], 1e-5), "d/dv of ({i},{j}): {dv:?} vs {:?}", d[i][j + 1]); + } + } + } + + #[test] + fn a_rational_quarter_circle_has_the_circles_derivatives() { + // On the circle of radius 2, the speed varies, but |r'| r'' and the curvature 1/2 do not: + // check the curvature (|r' × r''| / |r'|³) and its derivative (zero) from the table. + let s = quarter_cylinder(); + for u in [0.0, 0.2, 0.5, 0.9, 1.0] { + let d = s.partials(u, 0.4).unwrap(); + assert!((d[0][0].x.hypot(d[0][0].y) - 2.0).abs() < 1e-12); + let (r1, r2) = (d[1][0], d[2][0]); + let k = r1.cross(r2).len() / r1.len().powi(3); + assert!((k - 0.5).abs() < 1e-12, "{k}"); + assert!(d[0][2].len() < 1e-12 && d[1][1].z.abs() < 1e-12); + } + } + + #[test] + fn hostile_parameters_give_none() { + let s = quarter_cylinder(); + assert!(s.partials(f64::NAN, 0.0).is_none()); + assert!(s.partials(0.0, f64::INFINITY).is_none()); + let c = EvalCurve { degree: 2, knots: vec![0.0; 3], ctrl: vec![[0.0; 4]; 3] }; + assert!(c.derivatives(0.5, 2).is_none()); + } +} diff --git a/crates/geom/src/tess/uv.rs b/crates/geom/src/tess/uv.rs new file mode 100644 index 000000000..7fe8a9c3a --- /dev/null +++ b/crates/geom/src/tess/uv.rs @@ -0,0 +1,497 @@ +//! Parameters of points on an [`EvalSurface`], on the evaluator's own surface form: a +//! surface's parameter box and periods, the parameters of a point on it (closed form on a plane, +//! damped Gauss–Newton elsewhere), unwrapping across a period, and its poles. +//! +//! A spline that closes on itself along a direction (its first and last control rows coincide, +//! weights included, and its knots are clamped there: a NURBS cylinder, a fillet ring round a +//! hole's rim) is periodic along it, one active knot interval per period: the record stays as it +//! is, and parameters outside the interval are evaluated a whole number of periods back inside +//! it ([`EvalSurface::derivs`]). So is a revolution along a profile closed on itself (a torus's +//! whole circle). + +use super::EvalSurface; +use crate::prelude::*; +use solidcore_record::Vec3; + +/// The parameter box of a surface and its periods. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Domain { + /// Bounded ranges (`None`: unbounded, as a plane's). + pub range: [Option<(f64, f64)>; 2], + pub period: [Option; 2], +} + +/// The parameter box and periods of `s`. +pub fn domain(s: &EvalSurface) -> Domain { + let tau = std::f64::consts::TAU; + match s { + EvalSurface::Plane { .. } => Domain { range: [None, None], period: [None, None] }, + EvalSurface::Nurbs { degree, knots, count, closed: shut, .. } => { + let r = |d: usize| Some((*knots[d].get(degree[d])?, *knots[d].get(count[d])?)); + let range = [r(0), r(1)]; + let period = [0, 1].map(|d| range[d].filter(|_| shut[d]).map(|(a, b)| b - a).filter(|p| *p > 0.0)); + Domain { range, period } + } + EvalSurface::Revolved { profile, swap, .. } => { + let r = (|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?)))(); + // A profile closed on itself (a whole circle: a torus as another kernel writes it) + // is periodic along the profile too. + let along = r.filter(|_| closed_curve(profile)).map(|(a, b)| b - a).filter(|p| *p > 0.0); + let (a, b) = ((r, along), (Some((0.0, tau)), Some(tau))); + let (u, v) = if *swap { (b, a) } else { (a, b) }; + Domain { range: [u.0, v.0], period: [u.1, v.1] } + } + } +} + +/// Relative closeness of a spline's first and last control rows that makes it closed: control +/// points within this fraction of the control net's extent, weights within this fraction of +/// their size. Rows written as one (a producer's exact copy) pass; a surface whose ends merely +/// come near each other does not. +const CLOSED: f64 = 1e-9; + +/// Whether a spline curve closes on itself: its knots clamped at both ends and its first and +/// last control points the same, weights included ([`closed`] for a curve). +pub fn closed_curve(c: &super::EvalCurve) -> bool { + let Some(extent) = net_extent(&c.ctrl) else { return false }; + c.ctrl.len() >= 2 && clamped(c.degree, c.ctrl.len(), &c.knots) && same_point(c.ctrl.first(), c.ctrl.last(), extent) +} + +/// Whether the tensor spline closes on itself along each direction: its knots clamped at both +/// ends of that direction (so its boundary rows are its edges) and its first and last control +/// rows the same points with the same weights. Control point `(i, j)` is `ctrl[j·count[0] + i]`. +pub fn closed(degree: [usize; 2], knots: &[Vec; 2], count: [usize; 2], ctrl: &[[f64; 4]]) -> [bool; 2] { + let [nu, nv] = count; + if nu.checked_mul(nv) != Some(ctrl.len()) || nu < 2 || nv < 2 { + return [false; 2]; + } + let Some(extent) = net_extent(ctrl) else { return [false; 2] }; + let same = |a, b| same_point(ctrl.get(a), ctrl.get(b), extent); + let u = clamped(degree[0], nu, &knots[0]) && (0..nv).all(|j| same(j * nu, j * nu + nu - 1)); + let v = clamped(degree[1], nv, &knots[1]) && (0..nu).all(|i| same(i, (nv - 1) * nu + i)); + [u, v] +} + +fn cartesian(c: &[f64; 4]) -> Option { + (c[3] != 0.0).then(|| Vec3::new(c[0] / c[3], c[1] / c[3], c[2] / c[3])) +} + +/// The diagonal of a control net's box; `None` when a weight vanishes or the net is a point. +fn net_extent(ctrl: &[[f64; 4]]) -> Option { + let (mut lo, mut hi) = + (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY)); + for c in ctrl { + let p = cartesian(c)?; + lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)); + hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z)); + } + let extent = hi.dist(lo); + (extent.is_finite() && extent > 0.0).then_some(extent) +} + +/// Two control points the same within [`CLOSED`] of the net's extent, weights included. +fn same_point(a: Option<&[f64; 4]>, b: Option<&[f64; 4]>, extent: f64) -> bool { + match (a, b) { + (Some(a), Some(b)) => { + matches!((cartesian(a), cartesian(b)), (Some(p), Some(q)) if p.dist(q) <= CLOSED * extent) + && (a[3] - b[3]).abs() <= CLOSED * a[3].abs().max(b[3].abs()) + } + _ => false, + } +} + +/// Knots of degree `p` over `n` control points, clamped at both ends: the spline starts at its +/// first control point and ends at its last, its interval `[k[p], k[n]]` ending on knots of +/// multiplicity `p` within it. The outermost knots (`k[0]`, `k[n + p]`) take no part in the +/// spline over its interval, so they need not repeat: a periodic quadratic circle written with +/// knot multiplicities `1, 2, …, 2, 1` (as OpenCascade writes one) is clamped. +fn clamped(p: usize, n: usize, k: &[f64]) -> bool { + let ends = |r: std::ops::RangeInclusive| k.get(r).is_some_and(|s| s.windows(2).all(|w| w.first() == w.get(1))); + p >= 1 && k.len() == n + p + 1 && ends(1..=p) && ends(n..=n + p - 1) +} + +/// How far past an end of the interval, relative to its size, a parameter is still that end: +/// rounding, not a period away. +const WRAP_SLACK: f64 = 1e-12; + +/// `x` moved by whole periods `b − a` into `[a, b]` when it lies outside. A parameter a rounding +/// past an end (a pcurve ending on the seam one ulp beyond it) is that end, not moved a period +/// to the other one: a plan's node there would put its triangles across the whole period. +pub(crate) fn wrap_into(x: f64, (a, b): (f64, f64)) -> f64 { + let period = b - a; + if (a..=b).contains(&x) || !(period > 0.0) { + return x; + } + let slack = WRAP_SLACK * period.max(a.abs()).max(b.abs()); + if x > b && x - b <= slack { + return b; + } + if x < a && a - x <= slack { + return a; + } + let w = x - ((x - a) / period).floor() * period; + w.clamp(a, b) +} + +impl Domain { + pub fn clamp(&self, uv: [f64; 2]) -> [f64; 2] { + let mut out = uv; + for (d, x) in out.iter_mut().enumerate() { + if let (Some((a, b)), None) = (self.range[d], self.period[d]) { + *x = x.clamp(a.min(b), a.max(b)); + } + } + out + } +} + +/// Damped Gauss–Newton (Levenberg–Marquardt) for the parameters nearest to `p`, from `start`. +/// Returns the parameters and their distance to `p`. +fn newton(s: &EvalSurface, dom: &Domain, p: Vec3, start: [f64; 2]) -> Option<([f64; 2], f64)> { + let mut uv = dom.clamp(start); + let (mut q, mut su, mut sv) = s.derivs(uv[0], uv[1])?; + let mut dist = q.dist(p); + let mut lambda = 1e-6; + for _ in 0..60 { + let r = p - q; + let (a, b, c) = (su.len2(), su.dot(sv), sv.len2()); + let (g0, g1) = (su.dot(r), sv.dot(r)); + let scale = a + c; + if !(scale > 0.0) || !scale.is_finite() { + break; + } + let (a2, c2) = (a + lambda * scale, c + lambda * scale); + let det = a2 * c2 - b * b; + if !(det.abs() > 0.0) { + break; + } + let step = [(c2 * g0 - b * g1) / det, (a2 * g1 - b * g0) / det]; + let next = dom.clamp([uv[0] + step[0], uv[1] + step[1]]); + let Some((nq, nsu, nsv)) = s.derivs(next[0], next[1]) else { break }; + let nd = nq.dist(p); + if nd <= dist { + let moved = (next[0] - uv[0]).abs() + (next[1] - uv[1]).abs(); + (uv, q, su, sv, dist) = (next, nq, nsu, nsv, nd); + lambda = (lambda * 0.1).max(1e-12); + if moved <= 1e-15 * (1.0 + uv[0].abs() + uv[1].abs()) { + break; + } + } else { + lambda *= 10.0; + if lambda > 1e8 { + break; + } + } + } + Some((uv, dist)) +} + +/// The grid of surface points [`project`] searches from when it has no hint that converges: up to +/// [`MAX_STARTS`] evaluations of the surface, the same for every point, so a caller projecting +/// many points onto one surface (a face's pcurves, its boundary) keeps one `Starts` for it and +/// the grid is evaluated once, on first use ([`project_with`]). +#[derive(Clone, Debug, Default)] +pub struct Starts(std::sync::OnceLock>); + +/// A cache of the surface's own points: any two are alike. +impl PartialEq for Starts { + fn eq(&self, _: &Starts) -> bool { + true + } +} + +impl Starts { + /// The grid over `dom` ([`starts_along`] in each direction, thinned to [`MAX_STARTS`]): + /// each start's point and parameters. Empty where a direction is unbounded. + fn of(&self, s: &EvalSurface, dom: &Domain) -> &[(Vec3, [f64; 2])] { + self.0.get_or_init(|| { + let (Some(ru), Some(rv)) = (dom.range[0], dom.range[1]) else { return Vec::new() }; + let (mut us, mut vs) = (starts_along(s, 0, ru), starts_along(s, 1, rv)); + // Thin the longer list (every other start, its ends kept) until the grid fits. + while us.len().saturating_mul(vs.len()) > MAX_STARTS { + let longer = if us.len() >= vs.len() { &mut us } else { &mut vs }; + let last = longer.last().copied(); + *longer = longer.iter().step_by(2).copied().chain(last).collect(); + longer.dedup(); + } + let mut grid = Vec::with_capacity(us.len() * vs.len()); + for &u in &us { + for &v in &vs { + if let Some((q, _, _)) = s.derivs(u, v) { + grid.push((q, [u, v])); + } + } + } + grid + }) + } +} + +/// Parameters of `p` (a point on the surface within `accept`), from `hint` when that +/// converges, else from the best starts of a grid over the surface's domain, as fine as its +/// knot spans ([`starts_along`]). +pub fn project(s: &EvalSurface, dom: &Domain, p: Vec3, hint: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { + project_with(s, dom, &Starts::default(), p, hint, accept) +} + +/// [`project`] with the grid kept in `starts`, which must have been used with this surface and +/// domain only. +pub fn project_with(s: &EvalSurface, dom: &Domain, starts: &Starts, p: Vec3, hint: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { + if let EvalSurface::Plane { origin, du, dv } = s { + let r = p - *origin; + let (a, b, c) = (du.len2(), du.dot(*dv), dv.len2()); + let det = a * c - b * b; + if !(det.abs() > 0.0) { + return None; + } + let (g0, g1) = (du.dot(r), dv.dot(r)); + let uv = [(c * g0 - b * g1) / det, (a * g1 - b * g0) / det]; + return (uv[0].is_finite() && uv[1].is_finite()).then_some(uv); + } + let mut best: Option<([f64; 2], f64)> = None; + if let Some(h) = hint + && let Some((uv, d)) = newton(s, dom, p, h) + { + if d <= accept { + return Some(uv); + } + best = Some((uv, d)); + } + if dom.range.iter().any(Option::is_none) { + return None; + } + let grid = starts.of(s, dom); + // The nearest starts first (in grid order where equally near), until one converges within + // `accept`: where turns of a surface pass close to each other (a thread's root band a tenth + // of a millimetre from the next turn's), the nearest few can all lie on the wrong turn. + let mut near: Vec<(f64, usize)> = grid.iter().enumerate().map(|(i, (q, _))| ((*q - p).len2(), i)).collect(); + let by_distance = |a: &(f64, usize), b: &(f64, usize)| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)); + if near.len() > NEWTON_STARTS { + near.select_nth_unstable_by(NEWTON_STARTS, by_distance); + near.truncate(NEWTON_STARTS); + } + near.sort_by(by_distance); + for start in near.iter().filter_map(|(_, i)| grid.get(*i).map(|(_, uv)| uv)) { + if let Some((uv, d)) = newton(s, dom, p, *start) + && best.is_none_or(|(_, bd)| d < bd) + { + best = Some((uv, d)); + } + if accept.is_finite() && best.is_some_and(|(_, d)| d <= accept) { + break; + } + } + best.filter(|(_, d)| *d <= accept).map(|(uv, _)| uv) +} + +/// Evenly spaced starts along each direction of [`project`]'s search of the whole surface. +const EVEN_STARTS: usize = 16; +/// Starts per knot span of a direction where the surface has its own knots. +const SPAN_STARTS: usize = 2; +/// Most points of the surface the search measures. +const MAX_STARTS: usize = 1 << 14; +/// Most of them it runs Gauss–Newton from. +const NEWTON_STARTS: usize = 32; + +/// The parameters along direction `d` (over `range`) that [`project`] starts from when it has no +/// hint: even steps across the range, and where the surface has its own knots along `d` (a +/// spline's, a revolution's profile's) each span's start and points inside it, so a surface that +/// winds several turns along `d` (a thread's flank, one turn every few spans) is searched on +/// every turn and a point is never taken to the turn beside its own. +fn starts_along(s: &EvalSurface, d: usize, (a, b): (f64, f64)) -> Vec { + let knots = match s { + EvalSurface::Plane { .. } => None, + EvalSurface::Nurbs { knots, .. } => knots.get(d), + EvalSurface::Revolved { profile, swap, .. } => (usize::from(*swap) == d).then_some(&profile.knots), + }; + let (lo, hi) = (a.min(b), a.max(b)); + let mut out: Vec = (0..=EVEN_STARTS).map(|k| a + (b - a) * k as f64 / EVEN_STARTS as f64).collect(); + if let Some(knots) = knots { + let inside = knots.iter().copied().filter(|k| *k > lo && *k < hi); + let mut ends: Vec = std::iter::once(lo).chain(inside).chain(std::iter::once(hi)).collect(); + ends.dedup(); + for w in ends.windows(2).take(MAX_STARTS) { + let (Some(&k0), Some(&k1)) = (w.first(), w.get(1)) else { continue }; + out.extend((0..SPAN_STARTS).map(|j| k0 + (k1 - k0) * (j as f64 + 0.5) / SPAN_STARTS as f64)); + out.push(k0); + } + } + out.retain(|x| x.is_finite()); + out.sort_by(f64::total_cmp); + out.dedup(); + out +} + +/// `x` moved by whole periods to lie within half a period of `near`. +pub fn unwrap(x: f64, near: f64, period: Option) -> f64 { + match period { + Some(p) if p > 0.0 => x - ((x - near) / p).round() * p, + _ => x, + } +} + +/// Is the surface degenerate along direction `d` at `uv` (a pole: moving along `d` does not +/// move the point)? +pub fn degenerate(s: &EvalSurface, uv: [f64; 2], d: usize) -> bool { + let Some((_, su, sv)) = s.derivs(uv[0], uv[1]) else { return false }; + let (this, other) = if d == 0 { (su, sv) } else { (sv, su) }; + this.len() <= 1e-9 * other.len().max(1e-12) +} + +/// [`degenerate`], or within `reach` mm of a pole (see [`collapsed`]): a boundary point on a +/// patch side collapsed to within a tolerance, not to a point, where its parameter along `d` is +/// as free as at a pole. +pub fn degenerate_within(s: &EvalSurface, dom: &Domain, uv: [f64; 2], d: usize, reach: f64) -> bool { + let Some((_, su, sv)) = s.derivs(uv[0], uv[1]) else { return false }; + let speed = [su.len(), sv.len()]; + collapsed(speed, dom, reach).get(d).copied().unwrap_or(false) +} + +/// Along each direction, whether a point whose parameter speeds (mm per unit) are `speed` is a +/// pole, or within `reach` mm of one: moving along the direction there not at all (to 1e-9 of +/// the other's speed), or across half its period (or its whole range) by no more than `reach`. +pub fn collapsed(speed: [f64; 2], dom: &Domain, reach: f64) -> [bool; 2] { + let [a, b] = speed; + let mut out = [a <= 1e-9 * b.max(1e-12), b <= 1e-9 * a.max(1e-12)]; + for (d, flag) in out.iter_mut().enumerate() { + let span = match (dom.period[d], dom.range[d]) { + (Some(period), _) => 0.5 * period, + (None, Some((lo, hi))) => (hi - lo).abs(), + (None, None) => continue, + }; + *flag |= speed[d] * span <= reach; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tess::EvalCurve; + + fn cylinder() -> EvalSurface { + EvalSurface::Revolved { + profile: EvalCurve { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], ctrl: vec![[3.0, 0.0, 0.0, 1.0], [3.0, 0.0, 4.0, 1.0]] }, + origin: Vec3::ZERO, + axis: Vec3::Z, + transform: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], + swap: false, + } + } + + #[test] + fn projects_points_back_to_their_parameters() { + let s = cylinder(); + let dom = domain(&s); + for &(u, v) in &[(0.1, 0.2), (0.5, 3.0), (0.9, 6.0), (0.0, 1.0)] { + let (p, _) = s.eval(u, v); + let Some(uv) = project(&s, &dom, p, None, 1e-9) else { panic!("projects") }; + let (q, _) = s.eval(uv[0], uv[1]); + assert!(q.dist(p) < 1e-9); + assert!((uv[0] - u).abs() < 1e-9); + } + // Off the surface by more than `accept`: no parameters. + assert!(project(&s, &dom, Vec3::new(5.0, 0.0, 1.0), None, 1e-3).is_none()); + } + + /// A quadratic spline round a square in u (first and last columns the same), straight + /// up in v, `last` moving its last u column. + fn ring(last: [f64; 4], u_knots: Vec) -> EvalSurface { + let around = + [[2.0, 0.0, 0.0, 1.0], [2.0, 2.0, 0.0, 1.0], [-2.0, 2.0, 0.0, 1.0], [-2.0, -2.0, 0.0, 1.0], [2.0, -2.0, 0.0, 1.0], [2.0, 0.0, 0.0, 1.0]]; + let mut ctrl = Vec::new(); + for z in [0.0, 3.0] { + for (i, c) in around.iter().enumerate() { + let c = if i == around.len() - 1 { [c[0] + last[0], c[1] + last[1], c[2] + last[2], c[3] + last[3]] } else { *c }; + ctrl.push([c[0] * c[3], c[1] * c[3], (c[2] + z) * c[3], c[3]]); + } + } + EvalSurface::nurbs([2, 1], [u_knots, vec![0.0, 0.0, 1.0, 1.0]], [6, 2], ctrl) + } + + #[test] + fn a_spline_closed_on_itself_is_periodic_over_its_knot_interval() { + let clamped = || vec![0.0, 0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0, 1.0]; + let s = ring([0.0; 4], clamped()); + let EvalSurface::Nurbs { degree, knots, count, ctrl, closed: kept } = &s else { panic!("a spline") }; + assert_eq!(closed(*degree, knots, *count, ctrl), [true, false]); + assert_eq!(*kept, [true, false], "the constructor keeps what the test finds"); + assert_eq!(domain(&s).period, [Some(1.0), None]); + // A period away is the same point; inside the interval nothing moves. + for (u, inside) in [(1.25, 0.25), (-0.25, 0.75), (3.6, 0.6)] { + let (Some(a), Some(b)) = (s.derivs(u, 0.4), s.derivs(inside, 0.4)) else { panic!("evaluates") }; + assert!(a.0.dist(b.0) < 1e-12 && a.1.dist(b.1) < 1e-12, "{u}: {a:?} {b:?}"); + } + assert_eq!(s.wrap([1.0, 0.5]), [1.0, 0.5]); + assert_eq!(s.wrap([1.25, 2.0]), [0.25, 2.0]); + // A rounding past an end is that end, not the other one a period away. + assert_eq!(s.wrap([1.0 + f64::EPSILON, 0.5]), [1.0, 0.5]); + assert_eq!(s.wrap([-1e-17, 0.5]), [0.0, 0.5]); + // Projection finds a point near the seam from either side. + let p = s.derivs(0.02, 0.5).map(|d| d.0).unwrap_or(Vec3::ZERO); + let dom = domain(&s); + let Some(q) = project(&s, &dom, p, Some([0.98, 0.5]), 1e-9) else { panic!("projects") }; + assert!((unwrap(q[0], 0.98, dom.period[0]) - 1.02).abs() < 1e-9, "{q:?}"); + // Knots whose outermost values do not repeat, as OpenCascade writes a periodic circle: + // the interval still ends on knots of multiplicity 2, so the spline is closed there. + let outer_once = ring([0.0; 4], vec![-0.25, 0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0, 1.25]); + assert_eq!(domain(&outer_once).period, [Some(1.0), None]); + // Ends that only come near each other, a weight that differs, or unclamped knots: open, + // and evaluated past the interval as before (the end span continued). + for (what, open) in [ + ("ends apart", ring([0.0, 1e-6, 0.0, 0.0], clamped())), + ("weights differ", ring([0.0, 0.0, 0.0, 1e-6], clamped())), + ("unclamped", ring([0.0; 4], vec![-0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5])), + ] { + assert_eq!(domain(&open).period, [None, None], "{what}"); + assert_eq!(open.wrap([1.25, 0.5]), [1.25, 0.5], "{what}"); + } + } + + /// A revolution of a whole circle (a torus, the profile a rational quadratic closed on + /// itself) is periodic along the profile too, over its knot interval; a cylinder's line + /// profile is not. + #[test] + fn a_revolution_of_a_closed_profile_is_periodic_along_it() { + let w = std::f64::consts::FRAC_1_SQRT_2; + // The circle of radius 1 about (3, 0, 0) in the xz plane, four quarter arcs. + let pts = [[4.0, 0.0], [4.0, 1.0], [3.0, 1.0], [2.0, 1.0], [2.0, 0.0], [2.0, -1.0], [3.0, -1.0], [4.0, -1.0], [4.0, 0.0]]; + let ctrl: Vec<[f64; 4]> = pts + .iter() + .enumerate() + .map(|(i, [x, z])| { + let wt = if i % 2 == 1 { w } else { 1.0 }; + [x * wt, 0.0, z * wt, wt] + }) + .collect(); + let knots = vec![0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0]; + for swap in [false, true] { + let s = EvalSurface::Revolved { + profile: EvalCurve { degree: 2, knots: knots.clone(), ctrl: ctrl.clone() }, + origin: Vec3::ZERO, + axis: Vec3::Z, + transform: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], + swap, + }; + let (along, around) = if swap { (1, 0) } else { (0, 1) }; + let dom = domain(&s); + assert_eq!((dom.period[along], dom.period[around]), (Some(1.0), Some(std::f64::consts::TAU)), "swap {swap}"); + let at = |t: f64, a: f64| if swap { [a, t] } else { [t, a] }; + let wrapped = s.wrap(at(1.3, 0.4)); + assert!((wrapped[along] - 0.3).abs() < 1e-12 && wrapped[around] == 0.4, "swap {swap}: {wrapped:?}"); + assert_eq!(s.wrap(at(0.3, 7.0)), at(0.3, 7.0), "the angle is left alone"); + let (Some(p), Some(q)) = (s.derivs(at(1.3, 0.4)[0], at(1.3, 0.4)[1]), s.derivs(at(0.3, 0.4)[0], at(0.3, 0.4)[1])) else { + panic!("evaluates") + }; + assert!(p.0.dist(q.0) < 1e-12, "swap {swap}: {p:?} {q:?}"); + } + assert_eq!(domain(&cylinder()).period, [None, Some(std::f64::consts::TAU)]); + } + + #[test] + fn unwraps_across_the_period() { + let tau = std::f64::consts::TAU; + assert!((unwrap(0.1, tau - 0.1, Some(tau)) - (tau + 0.1)).abs() < 1e-12); + assert_eq!(unwrap(0.1, 6.0, None), 0.1); + } +} diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index e99cdba5b..20a5bfe0a 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -1,4 +1,5 @@ use crate::*; +use solidcore_record::{MAX_BEZIER_CTRL, Plane, Seg2, Vec2, Vec3}; fn cube_mesh(s: f64) -> Mesh { let p = |x: f64, y: f64, z: f64| Vec3::new(x * s, y * s, z * s); @@ -97,6 +98,44 @@ fn raycast_never_slips_between_triangles() { } } +/// A ray through an edge that two triangles share crosses exactly one of them: the same grid, +/// crossed at every inner edge's midpoint (and the middle of each cell, on its diagonal), straight +/// down and obliquely. The bracket example's hole centre fell on such an edge of the base's top +/// and was counted once for two faces. +#[test] +fn ray_crossings_count_a_shared_edge_once() { + let n = 6; + let positions: Vec = + (0..=n).flat_map(|j| (0..=n).map(move |i| Vec3::new(f64::from(i) * 40.0 / 6.0 + 100.0, f64::from(j) * 5.0, 20.0))).collect(); + let id = |i: u32, j: u32| j * (n + 1) + i; + let mut triangles = Vec::new(); + for j in 0..n { + for i in 0..n { + triangles.push([id(i, j), id(i + 1, j), id(i + 1, j + 1)]); + triangles.push([id(i, j), id(i + 1, j + 1), id(i, j + 1)]); + } + } + let tri_face = vec![0; triangles.len()]; + let m = Mesh { positions, triangles, tri_face, ..Default::default() }; + let dirs = [Vec3::new(-0.57735, 0.57735, -0.57735), Vec3::new(0.3, -0.7, -0.648), Vec3::new(-0.123456789, -0.2, -1.0), Vec3::new(0.0, 0.0, -1.0)]; + for d in dirs { + for j in 1..2 * n { + for i in 1..2 * n { + if i % 2 == 0 && j % 2 == 0 { + continue; + } + let p = Vec3::new(f64::from(i) * 20.0 / 6.0 + 100.0, f64::from(j) * 2.5, 20.0); + assert_eq!(m.ray_crossings(p - d * 50.0, d), 1, "{p:?} along {d:?}"); + assert_eq!(m.ray_crossings(p + d * 50.0, d), 0, "{p:?} along {d:?}, from beyond"); + } + } + } + // A closed cube: a ray through its top's diagonal crosses the top and the bottom. + let cube = cube_mesh(2.0); + assert_eq!(cube.ray_crossings(Vec3::new(0.5, 0.5, 5.0), Vec3::new(0.0, 0.0, -1.0)), 2); + assert_eq!(cube.ray_crossings(Vec3::new(0.5, 0.5, 1.0), Vec3::new(0.0, 0.0, -1.0)), 1); +} + #[test] fn planes() { assert_eq!(Plane::XY.normal(), Vec3::Z); @@ -296,7 +335,7 @@ fn surface_patches_cross_only_hidden_seams() { #[test] fn cubic_and_conic_segments_measure_exactly() { - use crate::{Loop2, Seg2, Vec2}; + use solidcore_record::{Loop2, Seg2, Vec2}; // An ellipse (a = 5, b = 3) as four quarter conics: area π a b. let w = std::f64::consts::FRAC_1_SQRT_2; let (a, b) = (5.0, 3.0); @@ -351,7 +390,7 @@ fn cubic_and_conic_segments_measure_exactly() { #[test] fn split_at_and_closest_param() { - use crate::{Seg2, Vec2}; + use solidcore_record::{Seg2, Vec2}; let w = std::f64::consts::FRAC_1_SQRT_2; let quarter = Seg2::Conic { a: Vec2::new(10.0, 0.0), apex: Vec2::new(10.0, 10.0), b: Vec2::new(0.0, 10.0), w }; for t in [0.2, 0.5, 0.8] { diff --git a/crates/geom/src/title_block.rs b/crates/geom/src/title_block.rs index 7d1906a95..d99fbd014 100644 --- a/crates/geom/src/title_block.rs +++ b/crates/geom/src/title_block.rs @@ -20,10 +20,11 @@ use serde::{Deserialize, Serialize}; +use crate::Aabb2; use crate::cell::{self, Content, Fit, Format, HAlign, Part, Projection, Source, is_snake_case}; use crate::drawing_sheet::SheetLayout; use crate::paper::{Group, Item, MAX_LINE_MM, ObjectKind}; -use crate::{Aabb2, Loop2, Seg2, Vec2}; +use solidcore_record::{Loop2, Seg2, Vec2}; /// The most cells a block may have. pub const MAX_CELLS: usize = 64; @@ -159,7 +160,12 @@ pub fn projection_symbol(projection: Projection, h: f64, centre: Vec2) -> [Item; let cone = Loop2::polygon(&cone.map(|(x, y)| Vec2::new(x, y))); let circles = Vec2::new(circles_at, y); let stroke = |path: Loop2| Item::Stroke { path: path.segs, closed: true, width_mm: h / 10.0, pattern: None }; - [stroke(cone), stroke(Loop2::circle(circles, h)), stroke(Loop2::circle(circles, h / 2.0))] + // Two half circles, as the symbol has always been drawn: `Loop2::circle` is one whole arc now. + let circle = |radius: f64| { + let half = |start: f64| Seg2::Arc { center: circles, radius, start, sweep: std::f64::consts::PI }; + Loop2 { segs: vec![half(0.0), half(std::f64::consts::PI)] } + }; + [stroke(cone), stroke(circle(h)), stroke(circle(h / 2.0))] } /// The built-in block, 180 x 49 mm: the twelve cells of the layout approved on #3875, each under a diff --git a/crates/geom/src/title_block_tests.rs b/crates/geom/src/title_block_tests.rs index de2fad227..d0a2be711 100644 --- a/crates/geom/src/title_block_tests.rs +++ b/crates/geom/src/title_block_tests.rs @@ -1,3 +1,4 @@ +use crate::prelude::*; use serde_json::json; use super::*; diff --git a/crates/geom/src/tspline/mod.rs b/crates/geom/src/tspline/mod.rs index 531f13b5f..5affc08be 100644 --- a/crates/geom/src/tspline/mod.rs +++ b/crates/geom/src/tspline/mod.rs @@ -25,8 +25,9 @@ pub use crate::bspline::Dir; pub use mesh::{Extension, IndexRect, MAX_GRID_POINTS, MAX_INDEX_LINES, Segment, TMesh}; pub use refine::Cut; -use crate::Vec3; use crate::bspline::{HPoint, MAX_SPLINE_DEGREE, Side, SplineError, SplineResult, invalid, local_basis, weighted_points}; +use crate::prelude::*; +use solidcore_record::Vec3; /// A blending function: its anchor's local knot vectors as line indices and as values, and /// its support. diff --git a/crates/geom/src/unit_vec3.rs b/crates/geom/src/unit_vec3.rs index 450e5e1a8..a5db0206a 100644 --- a/crates/geom/src/unit_vec3.rs +++ b/crates/geom/src/unit_vec3.rs @@ -1,15 +1,16 @@ //! A unit vector: a 3D vector of length 1. +use crate::prelude::*; use std::ops::{Add, Deref, Mul, Neg, Sub}; use serde::{Deserialize, Serialize}; -use crate::Vec3; +use solidcore_record::Vec3; /// A unit vector: length 1 up to rounding. Made only from a vector with a length -/// ([`UnitVec3::new`], [`Vec3::unit`]), so a function taking one need not normalise it or +/// ([`UnitVec3::new`], [`Vec3Geom::unit`]), so a function taking one need not normalise it or /// handle a zero vector again. It reads as the [`Vec3`] it holds (`d.dot(v)`, `*d`), and -/// [`Vec3::dot`] and [`Vec3::cross`] take one. +/// [`Vec3Geom::dot`] and [`Vec3Geom::cross`] take one. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(into = "Vec3", try_from = "Vec3")] pub struct UnitVec3(Vec3); @@ -28,13 +29,6 @@ impl UnitVec3 { } } -impl Vec3 { - /// This vector scaled to length 1 ([`UnitVec3::new`]). - pub fn unit(self) -> Option { - UnitVec3::new(self) - } -} - impl Deref for UnitVec3 { type Target = Vec3; fn deref(&self) -> &Vec3 { diff --git a/crates/geom/src/vec.rs b/crates/geom/src/vec.rs index 87c3ec294..1550b0b11 100644 --- a/crates/geom/src/vec.rs +++ b/crates/geom/src/vec.rs @@ -1,163 +1,126 @@ -use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign}; +//! The geometry of vectors and points ([`Vec2`], [`Vec3`], plain data in the record): dot and +//! cross products, lengths, distances, directions and interpolation. +use solidcore_record::{Vec2, Vec3}; -use serde::{Deserialize, Serialize}; +use crate::UnitVec3; -/// 2D vector / point (sketch space). -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(from = "[f64; 2]", into = "[f64; 2]")] -pub struct Vec2 { - pub x: f64, - pub y: f64, +/// The geometry of a 2D vector or point. +// `len` is the vector's length, not a count. +#[allow(clippy::len_without_is_empty)] +pub trait Vec2Geom { + fn dot(self, o: Vec2) -> f64; + /// z component of the 3D cross product. + fn cross(self, o: Vec2) -> f64; + fn len(self) -> f64; + fn len2(self) -> f64; + fn dist(self, o: Vec2) -> f64; + fn normalized(self) -> Option; + /// Rotated +90°. + fn perp(self) -> Vec2; + fn angle(self) -> f64; + fn from_angle(a: f64) -> Vec2; + fn lerp(self, o: Vec2, t: f64) -> Vec2; } -/// 3D vector / point (model space, Z up). -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(from = "[f64; 3]", into = "[f64; 3]")] -pub struct Vec3 { - pub x: f64, - pub y: f64, - pub z: f64, -} - -impl From<[f64; 2]> for Vec2 { - fn from(a: [f64; 2]) -> Self { - Vec2::new(a[0], a[1]) - } -} -impl From for [f64; 2] { - fn from(v: Vec2) -> Self { - [v.x, v.y] - } -} -impl From<[f64; 3]> for Vec3 { - fn from(a: [f64; 3]) -> Self { - Vec3::new(a[0], a[1], a[2]) - } -} -impl From for [f64; 3] { - fn from(v: Vec3) -> Self { - [v.x, v.y, v.z] - } -} - -impl Vec2 { - pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 }; - pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 }; - pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 }; - pub const fn new(x: f64, y: f64) -> Self { - Vec2 { x, y } - } - pub fn dot(self, o: Vec2) -> f64 { +impl Vec2Geom for Vec2 { + fn dot(self, o: Vec2) -> f64 { self.x * o.x + self.y * o.y } - /// z component of the 3D cross product. - pub fn cross(self, o: Vec2) -> f64 { + fn cross(self, o: Vec2) -> f64 { self.x * o.y - self.y * o.x } - pub fn len(self) -> f64 { + fn len(self) -> f64 { self.x.hypot(self.y) } - pub fn len2(self) -> f64 { + fn len2(self) -> f64 { self.dot(self) } - pub fn dist(self, o: Vec2) -> f64 { + fn dist(self, o: Vec2) -> f64 { (self - o).len() } - pub fn normalized(self) -> Option { + fn normalized(self) -> Option { let l = self.len(); (l > crate::EPS && l.is_finite()).then(|| self / l) } - /// Rotated +90°. - pub fn perp(self) -> Vec2 { + fn perp(self) -> Vec2 { Vec2::new(-self.y, self.x) } - pub fn angle(self) -> f64 { + fn angle(self) -> f64 { self.y.atan2(self.x) } - pub fn from_angle(a: f64) -> Vec2 { + fn from_angle(a: f64) -> Vec2 { Vec2::new(a.cos(), a.sin()) } - pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { + fn lerp(self, o: Vec2, t: f64) -> Vec2 { self + (o - self) * t } - pub fn is_finite(self) -> bool { - self.x.is_finite() && self.y.is_finite() - } - pub fn extend(self, z: f64) -> Vec3 { - Vec3::new(self.x, self.y, z) - } } -impl Vec3 { - pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; - pub const X: Vec3 = Vec3 { x: 1.0, y: 0.0, z: 0.0 }; - pub const Y: Vec3 = Vec3 { x: 0.0, y: 1.0, z: 0.0 }; - pub const Z: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 1.0 }; - pub const fn new(x: f64, y: f64, z: f64) -> Self { - Vec3 { x, y, z } - } +/// The geometry of a 3D vector or point. +// `len` is the vector's length, not a count. +#[allow(clippy::len_without_is_empty)] +pub trait Vec3Geom { /// Takes a [`Vec3`] or a [`UnitVec3`](crate::UnitVec3). - pub fn dot(self, o: impl Into) -> f64 { + fn dot(self, o: impl Into) -> f64; + /// Takes a [`Vec3`] or a [`UnitVec3`](crate::UnitVec3). + fn cross(self, o: impl Into) -> Vec3; + fn len(self) -> f64; + fn len2(self) -> f64; + fn dist(self, o: Vec3) -> f64; + fn normalized(self) -> Option; + fn lerp(self, o: Vec3, t: f64) -> Vec3; + fn min(self, o: Vec3) -> Vec3; + fn max(self, o: Vec3) -> Vec3; + /// Any unit vector perpendicular to `self` (which should be non-zero). + fn any_perp(self) -> Vec3; + /// Distance from this point to the segment `a`–`b`. + fn dist_to_segment(self, a: Vec3, b: Vec3) -> f64; + /// This vector scaled to length 1 ([`UnitVec3::new`]). + fn unit(self) -> Option; +} + +impl Vec3Geom for Vec3 { + fn dot(self, o: impl Into) -> f64 { let o = o.into(); self.x * o.x + self.y * o.y + self.z * o.z } - /// Takes a [`Vec3`] or a [`UnitVec3`](crate::UnitVec3). - pub fn cross(self, o: impl Into) -> Vec3 { + fn cross(self, o: impl Into) -> Vec3 { let o = o.into(); Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x) } - pub fn len(self) -> f64 { + fn len(self) -> f64 { self.len2().sqrt() } - pub fn len2(self) -> f64 { + fn len2(self) -> f64 { self.dot(self) } - pub fn dist(self, o: Vec3) -> f64 { + fn dist(self, o: Vec3) -> f64 { (self - o).len() } - pub fn normalized(self) -> Option { + fn normalized(self) -> Option { let l = self.len(); (l > crate::EPS && l.is_finite()).then(|| self / l) } - pub fn lerp(self, o: Vec3, t: f64) -> Vec3 { + fn lerp(self, o: Vec3, t: f64) -> Vec3 { self + (o - self) * t } - pub fn is_finite(self) -> bool { - self.x.is_finite() && self.y.is_finite() && self.z.is_finite() - } - pub fn min(self, o: Vec3) -> Vec3 { + fn min(self, o: Vec3) -> Vec3 { Vec3::new(self.x.min(o.x), self.y.min(o.y), self.z.min(o.z)) } - pub fn max(self, o: Vec3) -> Vec3 { + fn max(self, o: Vec3) -> Vec3 { Vec3::new(self.x.max(o.x), self.y.max(o.y), self.z.max(o.z)) } - /// Any unit vector perpendicular to `self` (which should be non-zero). - pub fn any_perp(self) -> Vec3 { + fn any_perp(self) -> Vec3 { let a = if self.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }; self.cross(a).normalized().unwrap_or(Vec3::Z) } - pub fn to_f32(self) -> [f32; 3] { - [self.x as f32, self.y as f32, self.z as f32] - } - /// Distance from this point to the segment `a`–`b`. - pub fn dist_to_segment(self, a: Vec3, b: Vec3) -> f64 { + fn dist_to_segment(self, a: Vec3, b: Vec3) -> f64 { let ab = b - a; let l2 = ab.len2(); let t = if l2 > 0.0 { ((self - a).dot(ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; self.dist(a + ab * t) } + fn unit(self) -> Option { + UnitVec3::new(self) + } } - -macro_rules! ops { - ($t:ident, $($f:ident),+) => { - impl Add for $t { type Output = $t; fn add(self, o: $t) -> $t { $t { $($f: self.$f + o.$f),+ } } } - impl Sub for $t { type Output = $t; fn sub(self, o: $t) -> $t { $t { $($f: self.$f - o.$f),+ } } } - impl Mul for $t { type Output = $t; fn mul(self, k: f64) -> $t { $t { $($f: self.$f * k),+ } } } - impl Div for $t { type Output = $t; fn div(self, k: f64) -> $t { $t { $($f: self.$f / k),+ } } } - impl Neg for $t { type Output = $t; fn neg(self) -> $t { $t { $($f: -self.$f),+ } } } - impl AddAssign for $t { fn add_assign(&mut self, o: $t) { $(self.$f += o.$f;)+ } } - impl SubAssign for $t { fn sub_assign(&mut self, o: $t) { $(self.$f -= o.$f;)+ } } - }; -} -ops!(Vec2, x, y); -ops!(Vec3, x, y, z); diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index f3c8d2a3f..de261ed00 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +solidcore-record = { workspace = true } robust = "1.2" solidcraft-geom = { workspace = true } solidcraft-render = { workspace = true } @@ -26,7 +27,8 @@ wgpu = { workspace = true, features = ["metal", "vulkan", "dx12", "gles"] } [dev-dependencies] image = { workspace = true } solidcraft-kernel = { workspace = true } -# Headless pictures of real designs (capture tests). +# Headless pictures of real designs (capture tests), built by the real kernel, solidcore, as in the +# apps. solidcraft-engine = { workspace = true, features = ["bundled-render-library"] } solidcraft-io = { workspace = true } serde_json = { workspace = true } diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index c67cfd299..14ba8ce62 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -7,15 +7,17 @@ //! renderer that drew it (`gpu`, `gpu-software` or `cpu`); `hardware` and `software` fail with an //! error that names the policy. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use solidcraft_geom::Vec3; -use solidcraft_render::{AnalysisMode, Camera, Rgb, SECTION_CAP, Scene}; +use solidcore_record::Vec3; +use solidcraft_render::hatch::Hatch; +use solidcraft_render::{AnalysisMode, Camera, Rgb, SECTION_CAP, Scene, SceneMesh}; use wgpu::util::DeviceExt; -use crate::view::{AccessMap, DrawStats, Frame, GpuScene, GpuTarget, Renderer, analysis_colors, analysis_uniform}; +use crate::view::{AccessMap, DrawStats, Frame, GpuScene, GpuTarget, Palette, PaletteIndex, Renderer, analysis_colors, analysis_uniform}; use crate::{GpuError, Result, caught, error_scopes}; /// The colour format pictures are drawn in: sRGB bytes as they are, like the viewport's usual @@ -106,13 +108,17 @@ impl Capturer { self.lost.load(Ordering::Acquire) } - /// [`Capturer::is_lost`], asking the driver first: an empty submission meets a loss the - /// driver reports and marks it, where the picture's first upload would panic inside wgpu. + /// [`Capturer::is_lost`], asking the driver first: a submission that opens a command list + /// meets a loss the driver reports and marks it, where the picture's first upload would + /// panic inside wgpu. As `egui_wgpu::DeviceLost::probe`: an empty submission only signals a + /// fence, which a reset D3D12 device let through (#6528). fn probe_lost(&self) -> bool { if self.is_lost() { return true; } - self.queue.submit([]); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("device lost probe") }); + encoder.insert_debug_marker("device lost probe"); + self.queue.submit([encoder.finish()]); self.is_lost() } @@ -397,7 +403,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces clip: scene.clip.map_or([0.0; 4], |(n, d)| [n.x as f32, n.y as f32, n.z as f32, d as f32]), cap: [f32::from(cap.0) / 255.0, f32::from(cap.1) / 255.0, f32::from(cap.2) / 255.0, if scene.plain_cap { 0.0 } else { 1.0 }], images: Vec::new(), - points: Vec::new(), + clouds: Vec::new(), analysis: analysis_uniform(mode, access.as_ref()), analysis_colors: scene.analysis.map_or([0.0; 36], |a| analysis_colors(&a.colors)), access, @@ -405,9 +411,11 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces eye: [eye[0], eye[1], eye[2], if cam.fov > 0.0 { 1.0 } else { 0.0 }], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], + hatch: scene.part_hatch.map_or_else(Default::default, |c| c.map(|Rgb(r, g, b)| [r, g, b].map(|x| f32::from(x) / 255.0))), } } @@ -415,24 +423,54 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces /// normals; a face normal where a vertex has none), lines as wide lines (over everything when /// `on_top`), the grid under everything. A body whose appearance is see-through /// ([`solidcraft_render::SceneMesh::glass`]) goes into the scene's glass, drawn as the viewport -/// draws glass: far sides first, then near sides, so what lies inside it shows through. +/// draws glass: far sides first, then near sides, so what lies inside it shows through. When the +/// scene hatches its cut by part ([`Scene::part_hatch`]), each body's colours are palette entries +/// of its own, carrying its hatch. pub fn scene_geometry(scene: &Scene) -> GpuScene { - let mut sc = GpuScene::default(); - for m in &scene.meshes { - let alpha = (m.alpha() * 255.0).round().clamp(0.0, 255.0) as u8; - let c4 = |c: Rgb| [c.0, c.1, c.2, alpha]; + let by_part = scene.part_hatch.is_some() && scene.clip.is_some(); + // Per body, its colours' stable entries (by part), and the stable palette they make. + let mut own: Vec> = Vec::new(); + let mut stable: Vec<[u8; 4]> = Vec::new(); + let mut hatches: Vec<(PaletteIndex, Hatch)> = Vec::new(); + let c4 = |m: &SceneMesh, c: Rgb| [c.0, c.1, c.2, (m.alpha() * 255.0).round().clamp(0.0, 255.0) as u8]; + if by_part { + for m in &scene.meshes { + let mut map = HashMap::new(); + for c in std::iter::once(m.color).chain(m.face_colors.iter().map(|(_, c)| *c)) { + map.entry(c4(m, c)).or_insert_with(|| { + let i = PaletteIndex(u32::try_from(stable.len()).unwrap_or(0)); + stable.push(c4(m, c)); + hatches.push((i, m.hatch)); + i + }); + } + own.push(map); + } + } + let mut palette = Palette::with_stable(stable); + for (i, h) in hatches { + palette.set_hatch(i, h); + } + let mut sc = GpuScene::with_palette(palette); + for (mi, m) in scene.meshes.iter().enumerate() { let faces: HashMap = m.face_colors.iter().copied().collect(); let mesh = &m.mesh; for (ti, t) in mesh.triangles.iter().enumerate() { - let col = sc.color(c4(mesh.tri_face.get(ti).and_then(|f| faces.get(f)).copied().unwrap_or(m.color))); + let rgba = c4(m, mesh.tri_face.get(ti).and_then(|f| faces.get(f)).copied().unwrap_or(m.color)); + let col = match own.get(mi).and_then(|o| o.get(&rgba)) { + Some(i) => *i, + None => sc.color(rgba), + }; let [Some(a), Some(b), Some(c)] = t.map(|k| mesh.positions.get(k as usize).copied()) else { continue }; let flat = (b - a).cross(c - a).normalized().unwrap_or(Vec3::Z); for (k, p) in t.iter().zip([a, b, c]) { let n = mesh.normals.get(*k as usize).copied().filter(|n| n.is_finite() && n.len() > 0.5).unwrap_or(flat); if m.glass() { sc.glass_tri(p.to_f32(), n.to_f32(), col); - } else { + } else if m.closed { sc.tri(p.to_f32(), n.to_f32(), col); + } else { + sc.open_tri(p.to_f32(), n.to_f32(), col); } } } @@ -559,7 +597,6 @@ mod tests { use super::*; use crate::view::TRI_SIZE; use solidcraft_geom::Mesh; - use solidcraft_render::SceneMesh; use std::sync::Arc; /// One triangle facing the camera. @@ -584,7 +621,14 @@ mod tests { /// headless picture of a translucent target shows the tool inside it. #[test] fn a_see_through_body_is_glass_at_its_own_alpha_and_a_solid_one_is_not() { - let mesh = |opacity: f32| SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: Vec::new(), opacity }; + let mesh = |opacity: f32| SceneMesh { + mesh: sheet(), + color: Rgb(200, 30, 30), + face_colors: Vec::new(), + opacity, + closed: true, + hatch: Default::default(), + }; let geometry = |opacity: f32| scene_geometry(&Scene { meshes: vec![mesh(opacity)], ..Default::default() }); let solid = geometry(1.0); @@ -608,7 +652,14 @@ mod tests { /// painting one face does not make the body solid again. #[test] fn a_painted_face_keeps_its_bodys_opacity() { - let mesh = SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: vec![(0, Rgb(0, 255, 0))], opacity: 0.5 }; + let mesh = SceneMesh { + mesh: sheet(), + color: Rgb(200, 30, 30), + face_colors: vec![(0, Rgb(0, 255, 0))], + opacity: 0.5, + closed: true, + hatch: Default::default(), + }; let sc = scene_geometry(&Scene { meshes: vec![mesh], ..Default::default() }); assert_eq!(sc.tris.len(), 0); assert_eq!(color(&sc, &sc.glass), Some([0, 255, 0, 128]), "the face's own colour at the body's alpha"); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 84d2588aa..5b45d6d59 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -13,9 +13,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +use solidcore_record::Vec3; #[cfg(not(target_arch = "wasm32"))] use solidcraft_geom::Mesh; -use solidcraft_geom::Vec3; use solidcraft_geom::tess::{EvalCurve, EvalSurface, TessPlan}; use wgpu::util::DeviceExt; diff --git a/crates/gpu/src/path/denoise_tests.rs b/crates/gpu/src/path/denoise_tests.rs index 12bc5f2ab..71c49ab34 100644 --- a/crates/gpu/src/path/denoise_tests.rs +++ b/crates/gpu/src/path/denoise_tests.rs @@ -1,6 +1,7 @@ use super::super::{Executor, JobOptions, Task, open_headless}; use super::*; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use solidcraft_render::{ Camera, ProductMesh, ProductScene, StandardView, job::{CancelToken, ImageRequest, ImageWork, TaskPoll}, diff --git a/crates/gpu/src/path/media_hierarchy.rs b/crates/gpu/src/path/media_hierarchy.rs index c7a2bbcf4..8cd351cd3 100644 --- a/crates/gpu/src/path/media_hierarchy.rs +++ b/crates/gpu/src/path/media_hierarchy.rs @@ -2,7 +2,8 @@ //! only a candidate; parent convexity and child vertices are checked against //! every outward parent half-space. Intersections and touching boundaries refuse. use super::scene::{Triangle, reserved}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_render::job::{CancelToken, ErrorCode, JobError, Result}; use std::ops::Range; diff --git a/crates/gpu/src/path/mod.rs b/crates/gpu/src/path/mod.rs index 3b08b4626..41d19e3cf 100644 --- a/crates/gpu/src/path/mod.rs +++ b/crates/gpu/src/path/mod.rs @@ -1,6 +1,6 @@ //! Native progressive product rendering. Software BVH traversal needs no ray-query //! features. Small measured quanta adapt to the device, then check cancellation. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; #[cfg(test)] use solidcraft_render::job::ToneMap; use solidcraft_render::{ @@ -217,6 +217,7 @@ impl Executor { lost.store(false, Ordering::Release); log::warn!("gpu-path device lost ({reason:?}); executor unavailable: {message}"); }); + let compiling = one_compile_at_a_time(); let scopes = scopes(&device); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("gpu-path"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); @@ -251,11 +252,21 @@ impl Executor { cache: None, }); checked(scopes)?; + drop(compiling); warm_up(&device, &queue, &pipeline, &placeholder_bind(&device, &layout, 7)?, &healthy)?; Ok(Self { context: Arc::new(Context { healthy, device, queue, pipeline, layout, denoise: std::sync::OnceLock::new() }) }) } } +/// Native drivers compile the path pipeline for minutes and gigabytes on a cold shader cache. +/// Executors opened side by side (parallel tests, each on its own device) compiled it together +/// until memory ran out (#6706). One compile at a time per process: the first fills the driver's +/// cache, and the waiting ones then get it from there. +fn one_compile_at_a_time() -> std::sync::MutexGuard<'static, ()> { + static COMPILE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + COMPILE.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + // Small zeroed bindings: binding 0 is a uniform whose zero work count makes every // invocation return at once; the others are storage buffers. fn placeholder_bind(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, count: u32) -> Result { diff --git a/crates/gpu/src/path/path.wgsl b/crates/gpu/src/path/path.wgsl index 7c6aa05f5..35e3f081d 100644 --- a/crates/gpu/src/path/path.wgsl +++ b/crates/gpu/src/path/path.wgsl @@ -574,17 +574,22 @@ fn dominant_vertex(bary: vec3) -> u32 { if bary.z>bary[anchor] { anchor=2u; } return anchor; } +// The vertex after `a`, as (a+1)%3. Not written with `%`: NVIDIA's Vulkan compiler crashes on +// that index after a BVH walk (#6705). +fn next_vertex(a: u32) -> u32 { + return select(a+1u,0u,a>=2u); +} fn surface_point(t: Triangle, bary: vec3) -> vec3 { // Anchor near the hit, retaining the two other directly computed weights. // A tiny weight on a distant vertex can encode an entire corner clearance. // Do not recover that weight by subtracting the other two from one. let p=array,3>(t.p0.xyz,t.p1.xyz,t.p2.xyz); - let a=dominant_vertex(bary); let b=(a+1u)%3u; let c=(a+2u)%3u; + let a=dominant_vertex(bary); let b=next_vertex(a); let c=next_vertex(b); return p[a]+((p[b]-p[a])*bary[b]+(p[c]-p[a])*bary[c]); } fn surface_point_precise(t: Triangle, bary: vec3) -> PrecisePoint { let p=array,3>(t.p0.xyz,t.p1.xyz,t.p2.xyz); - let a=dominant_vertex(bary); let b=(a+1u)%3u; let c=(a+2u)%3u; + let a=dominant_vertex(bary); let b=next_vertex(a); let c=next_vertex(b); // Keep the world anchor separate from its local displacement. return PrecisePoint(p[a],(p[b]-p[a])*bary[b]+(p[c]-p[a])*bary[c]); } @@ -595,7 +600,7 @@ fn surface_ray_depth_precise(t: Triangle, bary: vec3, origin: vec3, or } fn surface_ray_depth(t: Triangle, bary: vec3, origin: vec3, axis: u32) -> f32 { let p=array,3>(t.p0.xyz,t.p1.xyz,t.p2.xyz); - let a=dominant_vertex(bary); let b=(a+1u)%3u; let c=(a+2u)%3u; + let a=dominant_vertex(bary); let b=next_vertex(a); let c=next_vertex(b); // Original vertex differences avoid subtracting two rounded ray-relative // coordinates; adding the anchor last preserves distant thin-hit ordering. return (p[a][axis]-origin[axis])+((p[b][axis]-p[a][axis])*bary[b]+(p[c][axis]-p[a][axis])*bary[c]); @@ -660,16 +665,6 @@ fn area_pdf(light: AreaLight, delta: vec3) -> f32 { if cosine<=0.0 { return 0.0; } return dot(delta,delta)/(light.center.w*cosine); } -fn visible(o: vec3, d: vec3, distance: f32) -> ShadowResult { - if emitter_hit(o,d).distance0.0 { - let attenuation=volume_transmittance(o,d,distance); - visibility.transmittance*=attenuation; - visibility.branch_pdf*=attenuation; - } - return visibility; -} struct EnvironmentSample { direction: vec3, radiance: vec3, pdf: f32 }; fn environment_to_world(d: vec3) -> vec3 { return vec3(u.environment_map.x*d.x-u.environment_map.y*d.y,u.environment_map.y*d.x+u.environment_map.x*d.y,d.z); @@ -723,43 +718,67 @@ fn sun_sample(rng:ptr)->EnvironmentSample { let direction=from_local(vec3(radius*cos(phi),radius*sin(phi),z),u.sun_direction.xyz); return EnvironmentSample(direction,u.sun_radiance.xyz,u.sun_radiance.w); } -fn direct_studio(t: Triangle, position: vec3, o: vec3, n: vec3, geometric: vec3, v: vec3, remaining: u32, rng: ptr) -> vec3 { +// The three fixed lights of the preview without studio lighting: direction and intensity. +const FIXED_LIGHTS = array,3>(vec4(0.6,0.0,0.8,3.0),vec4(-0.8,0.0,0.6,1.0),vec4(0.0,-0.6,0.8,1.5)); +// Next-event estimation for every light source family through ONE shadow-ray call site, like +// volume_direct. Native compilers inline each call of the BVH walk; one walk per source family +// made `main` too large for NVIDIA's Vulkan compiler (#6705). Studio lighting visits every area +// light, then the environment, then the sun, drawing random numbers in that order; without it +// the three fixed lights are used. +fn direct_light(t: Triangle, position: vec3, o: vec3, n: vec3, geometric: vec3, v: vec3, remaining: u32, rng: ptr) -> vec3 { var result = vec3(0.0); let opaque = 1.0-t.base.w; - if opaque<=0.0 { return result; } - for (var i=0u; i=remaining); - result += visibility.transmittance*brdf(t,n,v,direction)*light.radiance.xyz*(opaque*nl*weight/pdf); - } - if u.environment_map.w>0.0 || any(u.environment.xyz>vec3(0.0)) { - let sample=env_sample(rng); - let nl=dot(n,sample.direction); - if sample.pdf>0.0 && nl>0.0 && dot(geometric,sample.direction)>0.0 { - let visibility=visible(o,sample.direction,FAR); - let competing=opaque*surface_pdf(t,n,v,sample.direction)*visibility.branch_pdf; - let weight=select(power_weight(sample.pdf,competing),1.0,visibility.solid || visibility.crossings>=remaining); - result+=visibility.transmittance*brdf(t,n,v,sample.direction)*sample.radiance*(opaque*nl*weight/sample.pdf); + let studio = u.environment.w > 0.0; + if studio && opaque<=0.0 { return result; } + let area_count = u32(u.light_count.w); + let count = select(3u, area_count+2u, studio); + for (var source=0u; source(0.0,0.0,1.0),vec3(0.0),0.0); + var shadow_direction = vec3(0.0,0.0,1.0); + var shadow_distance = FAR; + if !studio { + let light = FIXED_LIGHTS[source]; + if u.lighting.z <= 0.0 || dot(geometric,light.xyz)<=0.0 || dot(n,light.xyz)<=0.0 { continue; } + sample = EnvironmentSample(light.xyz,vec3(light.w*u.lighting.z*u.studio_weights[source]),1.0); + shadow_direction = light.xyz; + } else { + if sourcevec3(0.0)) { continue; } + sample = env_sample(rng); + shadow_direction = sample.direction; + } else { + if u.sun_radiance.w<=0.0 { continue; } + sample = sun_sample(rng); + shadow_direction = sample.direction; + } + if sample.pdf<=0.0 || dot(n,sample.direction)<=0.0 || dot(geometric,sample.direction)<=0.0 { continue; } } - } - if u.sun_radiance.w>0.0 { - let sample=sun_sample(rng); - let nl=dot(n,sample.direction); - if nl>0.0 && dot(geometric,sample.direction)>0.0 { - let visibility=visible(o,sample.direction,FAR); - let competing=opaque*surface_pdf(t,n,v,sample.direction)*visibility.branch_pdf; - let weight=select(power_weight(sample.pdf,competing),1.0,visibility.solid || visibility.crossings>=remaining); - result+=visibility.transmittance*brdf(t,n,v,sample.direction)*sample.radiance*(opaque*nl*weight/sample.pdf); + // Studio emitters block a connection that passes them; studio volumes attenuate it. + var visibility = blocked_shadow(); + if !studio || emitter_hit(o,shadow_direction).distance>=shadow_distance-u.lighting.x*2.0 { + visibility = shadow_transmittance(o,shadow_direction,shadow_distance); + if studio && u.volume_min.w>0.0 { + let attenuation=volume_transmittance(o,shadow_direction,shadow_distance); + visibility.transmittance*=attenuation; + visibility.branch_pdf*=attenuation; + } } + let nl = dot(n,sample.direction); + if !studio { + result += visibility.transmittance * brdf(t,n,v,sample.direction) * (opaque*nl*sample.radiance); + continue; + } + let competing=opaque*surface_pdf(t,n,v,sample.direction)*visibility.branch_pdf; + let weight=select(power_weight(sample.pdf,competing),1.0,visibility.solid || visibility.crossings>=remaining); + result += visibility.transmittance*brdf(t,n,v,sample.direction)*sample.radiance*(opaque*nl*weight/sample.pdf); } return result; } @@ -816,7 +835,6 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4 { var previous_delta = true; var media: array; var medium_count = 0u; - let lights = array,3>(vec4(0.6,0.0,0.8,3.0),vec4(-0.8,0.0,0.6,1.0),vec4(0.0,-0.6,0.8,1.5)); for (var bounce = 0u; bounce < u.sampling.y; bounce += 1u) { // Closed-glass continuations set an excluded producing triangle; every // other launch (camera, opaque or thin-sheet surface) does not. @@ -947,16 +965,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4 { } previous_position = position; previous_position_low=position_low; o = position + geometric*(u.lighting.x*2.0); o_low=vec3(0.0); - if u.environment.w > 0.0 { - radiance += throughput*direct_studio(t,position,o,n,geometric,v,u.sampling.y-bounce-1u,&rng); - } - for (var i=0u; i<3u && u.environment.w==0.0; i+=1u) { - let light = lights[i]; - if u.lighting.z > 0.0 && dot(geometric,light.xyz)>0.0 && dot(n,light.xyz)>0.0 { - let visibility=shadow_transmittance(o,light.xyz,FAR); - radiance += visibility.transmittance * throughput * brdf(t,n,v,light.xyz) * ((1.0-t.base.w)*light.w*dot(n,light.xyz)*u.lighting.z*u.studio_weights[i]); - } - } + radiance += throughput*direct_light(t,position,o,n,geometric,v,u.sampling.y-bounce-1u,&rng); if t.base.w > 0.0 && random(&rng) < t.base.w { var nt = t.parameters.z; if t.parameters.w < 0.0 && entering && medium_count > 0u && u.lighting.w==0.0 { @@ -1105,14 +1114,22 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let pilots = u.adaptive_budget.x; let strata = max(1u,u.adaptive_budget.z); let lane = u32(u.adaptive_error.w); + // Settle first whether this invocation samples at all, then take the path sample at one call + // site: every call is inlined, and three copies of the integrator were more than NVIDIA's + // Vulkan compiler could build (#6705). + var budget_count = 0u; + if pilots > 0u && u.image.z >= pilots { + budget_count = u32(accumulation[2u*pixels+pixel].x); + if u.image.z-pilots >= budget_count { return; } + } + let value = sample_path(pixel); if pilots == 0u { - let sample = sample_path(pixel)/f32(strata); + let sample = value/f32(strata); if u.image.z == 0u && lane == 0u { accumulation[pixel] = sample; } else { accumulation[pixel] += sample; } return; } if u.image.z < pilots { - let value = sample_path(pixel); var mean = accumulation[pixels+pixel]; var m2 = accumulation[2u*pixels+pixel]; if u.image.z == 0u { mean=vec4(0.0); m2=vec4(0.0); } @@ -1127,10 +1144,8 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } return; } - let budget_count=u32(accumulation[2u*pixels+pixel].x); let ordinal=u.image.z-pilots; - if ordinal>=budget_count { return; } - accumulation[pixel] += sample_path(pixel)/f32(strata); + accumulation[pixel] += value/f32(strata); // Per-pixel production means enter both raw EXR and denoising. Pilots do not. if ordinal+1u == budget_count && lane+1u == strata { accumulation[pixel] /= f32(budget_count); } } diff --git a/crates/gpu/src/path/planar_patches.rs b/crates/gpu/src/path/planar_patches.rs index bfd7e8cf4..0c81b2fa5 100644 --- a/crates/gpu/src/path/planar_patches.rs +++ b/crates/gpu/src/path/planar_patches.rs @@ -113,7 +113,7 @@ pub(super) fn ids(triangles: &[Triangle], cancel: &CancelToken) -> Result Triangle { diff --git a/crates/gpu/src/path/scene.rs b/crates/gpu/src/path/scene.rs index 068b23ac7..b5cf39245 100644 --- a/crates/gpu/src/path/scene.rs +++ b/crates/gpu/src/path/scene.rs @@ -1,9 +1,10 @@ //! Original median-split BVH. World geometry is rebased around the camera target for f32. #[path = "planar_patches.rs"] mod planar_patches; +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_render::{ ProductScene, job::{CancelToken, ErrorCode, JobError, Result}, diff --git a/crates/gpu/src/path/scene_bvh_tests.rs b/crates/gpu/src/path/scene_bvh_tests.rs index 50151a72a..68793295e 100644 --- a/crates/gpu/src/path/scene_bvh_tests.rs +++ b/crates/gpu/src/path/scene_bvh_tests.rs @@ -1,5 +1,5 @@ use super::{MAX_BVH_DEPTH, Node, Triangle, build}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_render::{job::CancelToken, surface::OpaqueSurface}; // Triangle centres spread over 60 decades: a sixteen-bin SAH split on the diff --git a/crates/gpu/src/path/scene_weld_tests.rs b/crates/gpu/src/path/scene_weld_tests.rs index 0b9b2bbaa..360781c5d 100644 --- a/crates/gpu/src/path/scene_weld_tests.rs +++ b/crates/gpu/src/path/scene_weld_tests.rs @@ -1,7 +1,9 @@ +use solidcraft_geom::prelude::*; use std::sync::Arc; use super::{MediumWeld, Triangle, flatten, medium_preparation_bytes}; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use solidcraft_render::{ProductMesh, ProductScene, job::CancelToken, surface::OpaqueSurface, transmission::Transmission}; fn seam_tetra(offset: Vec3) -> ProductScene { diff --git a/crates/gpu/src/path/tests.rs b/crates/gpu/src/path/tests.rs index b41046635..3932c92d2 100644 --- a/crates/gpu/src/path/tests.rs +++ b/crates/gpu/src/path/tests.rs @@ -1,4 +1,5 @@ use super::*; +use solidcraft_geom::prelude::*; use solidcraft_geom::{Aabb3, Mesh}; use solidcraft_render::{Camera, ProductMesh, StandardView, surface::OpaqueSurface}; @@ -531,6 +532,48 @@ fn shader_validates_without_a_device() { naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap(); } +/// #6705: native compilers inline every call. With 33 inlined BVH walks in `main` (three path +/// samples, a shadow walk per light source family) NVIDIA's Vulkan compiler crashed or ran out +/// of memory and never built the pipeline. Count the walks `main` inlines, so another call site +/// is a deliberate choice, checked on such a driver. +#[test] +fn main_inlines_few_bvh_walks() { + fn callees(block: &naga::Block, out: &mut Vec>) { + for statement in block.iter() { + match statement { + naga::Statement::Call { function, .. } => out.push(*function), + naga::Statement::Block(inner) => callees(inner, out), + naga::Statement::If { accept, reject, .. } => { + callees(accept, out); + callees(reject, out); + } + naga::Statement::Switch { cases, .. } => cases.iter().for_each(|case| callees(&case.body, out)), + naga::Statement::Loop { body, continuing, .. } => { + callees(body, out); + callees(continuing, out); + } + _ => {} + } + } + } + fn walks(module: &naga::Module, function: &naga::Function) -> usize { + let mut called = Vec::new(); + callees(&function.body, &mut called); + called + .into_iter() + .map(|handle| { + let callee = &module.functions[handle]; + let walk = matches!(callee.name.as_deref(), Some("trace_precise_within" | "trace_ordered_within")); + usize::from(walk) + walks(module, callee) + }) + .sum() + } + let module = naga::front::wgsl::parse_str(SHADER).unwrap(); + let main = module.entry_points.iter().find(|entry| entry.name == "main").unwrap(); + let inlined = walks(&module, &main.function); + assert!(inlined <= 5, "`main` inlines {inlined} BVH walks"); +} + #[test] fn render_lights_path_visibility_uniform_keeps_the_shader_contract() { shader_validates_without_a_device(); @@ -550,6 +593,25 @@ fn path_devices_are_vulkan_or_metal_only() { } } +/// #6706: executors opened side by side never compile the path pipeline at the same time. +#[test] +fn path_pipelines_compile_one_at_a_time() { + use std::sync::atomic::AtomicUsize; + let inside = AtomicUsize::new(0); + let most = AtomicUsize::new(0); + std::thread::scope(|scope| { + for _ in 0..8 { + scope.spawn(|| { + let _compiling = one_compile_at_a_time(); + most.fetch_max(inside.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(5)); + inside.fetch_sub(1, Ordering::SeqCst); + }); + } + }); + assert_eq!(most.load(Ordering::SeqCst), 1); +} + #[test] fn viewport_path_backends_keep_windows_on_its_selected_backend() { for backend in [wgpu::Backend::Dx12, wgpu::Backend::Gl, wgpu::Backend::Vulkan] { diff --git a/crates/gpu/src/path/textures.rs b/crates/gpu/src/path/textures.rs index 135aa340c..4e6fd9761 100644 --- a/crates/gpu/src/path/textures.rs +++ b/crates/gpu/src/path/textures.rs @@ -1,5 +1,6 @@ //! One read-only storage buffer: body lookup, planar records and linear RGBA pixels. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_render::job::{ CancelToken, ErrorCode, JobError, Result, textures::{BaseColorMode, RuntimeTextures, TextureMap}, diff --git a/crates/gpu/src/select.rs b/crates/gpu/src/select.rs index 388f189c3..7a2fcb596 100644 --- a/crates/gpu/src/select.rs +++ b/crates/gpu/src/select.rs @@ -139,7 +139,7 @@ pub fn native_backends() -> wgpu::Backends { } } -pub(crate) fn tier_of(t: wgpu::DeviceType) -> Tier { +pub fn tier_of(t: wgpu::DeviceType) -> Tier { match t { wgpu::DeviceType::Cpu => Tier::Software, wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu | wgpu::DeviceType::VirtualGpu | wgpu::DeviceType::Other => Tier::Hardware, diff --git a/crates/gpu/src/tess.wgsl b/crates/gpu/src/tess.wgsl index 3e350a6b1..f8f551f13 100644 --- a/crates/gpu/src/tess.wgsl +++ b/crates/gpu/src/tess.wgsl @@ -7,8 +7,8 @@ const PLANE: u32 = 0u; const NURBS: u32 = 1u; const REVOLVED: u32 = 2u; -// Basis slots for the highest degree (MAX_SPLINE_DEGREE = 7). -const W: u32 = 8u; +// Basis slots for the highest degree (MAX_SPLINE_DEGREE = 16). +const W: u32 = 17u; struct Surface { kind: u32, diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 9492fe908..0530bbc00 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1,4 +1,5 @@ -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_kernel::{Body, BoolOp}; use super::*; @@ -57,7 +58,7 @@ fn a_pipeline_the_device_rejects_is_an_error_not_a_crash() { // The same device then builds the real pipeline and evaluates on it. let gpu = ok(TessGpu::new(name, device, queue)); let body = ok(solidcraft_kernel::torus(Vec3::ZERO, 6.0, 1.5)); - let plan = ok(body.display_plan(0.01)); + let plan = ok(body.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(0.01))); assert_eq!(ok(gpu.evaluate(&plan)).positions.len(), plan.evaluate().positions.len()); } @@ -96,6 +97,106 @@ fn the_hlsl_for_fxc_has_no_arrays_fxc_must_unroll_loops_for() { } } +/// The shader's basis slots hold the highest degree the CPU evaluator takes, so every surface +/// the CPU evaluates the GPU evaluates too. +#[test] +fn the_shader_takes_every_degree_the_cpu_evaluator_does() { + let slots = format!("const W: u32 = {}u;", solidcraft_geom::bspline::MAX_SPLINE_DEGREE + 1); + assert!(SHADER.contains(&slots), "tess.wgsl must declare `{slots}`"); +} + +/// Browsers compile WGSL with Tint, which keeps a rule of the WGSL grammar that naga doesn't: a +/// shift, `&`, `|` and `^` don't mix in one expression without parentheses (`a << 3u | b` is +/// refused, `(a << 3u) | b` isn't). A shader that breaks it runs on the desktop and leaves the +/// web app's 3D view black (#11080). Every shader in the repository keeps to it. +#[test] +fn no_shader_mixes_shifts_and_bitwise_operators_without_parentheses() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut shaders = Vec::new(); + let mut dirs = vec![root.join("assets"), root.join("crates"), root.join("vendor")]; + while let Some(dir) = dirs.pop() { + for entry in ok(std::fs::read_dir(&dir)) { + let path = ok(entry).path(); + if path.is_dir() { + if !path.ends_with("target") { + dirs.push(path); + } + } else if path.extension().is_some_and(|e| e == "wgsl") { + shaders.push(path); + } + } + } + assert!(shaders.iter().any(|p| p.ends_with("assets/shaders/viewport.wgsl")), "{shaders:?}"); + let mut found = Vec::new(); + for path in &shaders { + for (n, line) in ok(std::fs::read_to_string(path)).lines().enumerate() { + if let Some(ops) = mixed_bitwise(line) { + found.push(format!("{}:{}: {ops}: {}", path.display(), n + 1, line.trim())); + } + } + } + assert!(found.is_empty(), "{}", found.join("\n")); + // The check finds the line #11080 reported, and takes it parenthesized. + assert_eq!(mixed_bitwise("let v = ((x ^ y) & 1u) << 3u | (y & 1u) << 2u;").as_deref(), Some("shift and |")); + assert_eq!(mixed_bitwise("let v = (((x ^ y) & 1u) << 3u) | ((y & 1u) << 2u);"), None); + assert_eq!(mixed_bitwise("let a = f(&p, x & 1u, y | 2u) && b || c; // x << 1u | y"), None); + assert_eq!(mixed_bitwise("var m: array>; let b = a & 1u ^ c;").as_deref(), Some("& and ^")); +} + +/// The bitwise operators (a shift, `&`, `|`, `^`) that one parenthesized group of a WGSL line +/// mixes, when it mixes more than one: what WGSL needs parentheses for. `&&`, `||`, an +/// address-of `&` and a `>>` closing two generic brackets (`vec2>`) aren't counted. +fn mixed_bitwise(line: &str) -> Option { + let chars: Vec = line.split("//").next().unwrap_or("").chars().collect(); + let at = |i: usize| chars.get(i).copied().unwrap_or(' '); + let mixed = |g: &Vec<&str>| (g.len() > 1).then(|| g.join(" and ")); + let mut groups: Vec> = vec![Vec::new()]; + let (mut i, mut prev) = (0, ' '); + while i < chars.len() { + let (c, next) = (at(i), at(i + 1)); + let mut op = None; + match c { + '(' | '[' => groups.push(Vec::new()), + ')' | ']' | ',' | ';' | '{' | '}' => { + if let Some(m) = groups.last().and_then(mixed) { + return Some(m); + } + if matches!(c, ')' | ']') && groups.len() > 1 { + groups.pop(); + } else if let Some(g) = groups.last_mut() { + g.clear(); + } + } + '<' if next == '<' => { + op = Some("shift"); + i += 1; + } + '>' if next == '>' => { + let after = at(i + 2); + if after == ' ' || after == '_' || after.is_alphanumeric() { + op = Some("shift"); + } + i += 1; + } + '&' | '|' if next == c => i += 1, + '&' if prev == '_' || prev == ')' || prev == ']' || prev.is_alphanumeric() => op = Some("&"), + '|' => op = Some("|"), + '^' => op = Some("^"), + _ => {} + } + if let (Some(op), Some(g)) = (op, groups.last_mut()) + && !g.contains(&op) + { + g.push(op); + } + if !at(i).is_whitespace() { + prev = at(i); + } + i += 1; + } + groups.iter().find_map(mixed) +} + fn ok(r: std::result::Result) -> T { match r { Ok(v) => v, @@ -125,7 +226,7 @@ fn bodies() -> Vec<(&'static str, Body)> { fn gpu_evaluation_matches_the_cpu() { let Some(gpu) = gpu() else { return }; for (name, body) in bodies() { - let plan = ok(body.display_plan(0.01)); + let plan = ok(body.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(0.01))); let cpu = plan.evaluate(); let got = ok(gpu.evaluate(&plan)); assert_eq!(got.triangles, cpu.triangles, "{name}"); @@ -155,7 +256,7 @@ fn gpu_evaluation_matches_the_cpu() { fn a_resident_mesh_matches_the_cpu() { let Some(gpu) = gpu() else { return }; for (name, body) in bodies() { - let plan = ok(body.display_plan_angular(0.01, std::f64::consts::PI / 9.0)); + let plan = ok(body.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: 0.01, angle: Some(std::f64::consts::PI / 9.0) })); let cpu = plan.evaluate(); let mesh = ok(gpu.prepare(&plan)); assert_eq!(mesh.vertex_count as usize, cpu.positions.len(), "{name}"); @@ -196,7 +297,10 @@ fn a_resident_mesh_matches_the_cpu() { #[test] fn a_scene_in_one_dispatch_matches_each_body_on_the_cpu() { let Some(gpu) = gpu() else { return }; - let plans: Vec = bodies().iter().map(|(_, b)| ok(b.display_plan_angular(0.01, std::f64::consts::PI / 9.0))).collect(); + let plans: Vec = bodies() + .iter() + .map(|(_, b)| ok(b.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: 0.01, angle: Some(std::f64::consts::PI / 9.0) }))) + .collect(); let refs: Vec<&TessPlan> = plans.iter().collect(); let mesh = ok(gpu.prepare_many(&refs)); assert_eq!(mesh.parts.len(), plans.len()); @@ -271,7 +375,7 @@ fn tessellation_without_surfaces_does_not_dispatch() { #[test] #[ignore] fn bench_plate() { - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; let rect = |w: f64| Loop2 { segs: vec![ Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(w, 0.0) }, @@ -300,11 +404,11 @@ fn bench_plate() { let (mut nr, mut np) = (0, 0); for _ in 0..5 { let t = std::time::Instant::now(); - let m = ok(plate.tessellate(tol)); + let m = ok(plate.mesh(&solidcraft_kernel::MeshTolerance::chord(tol))); r.push(ms(t)); nr = m.triangles.len(); let t = std::time::Instant::now(); - let plan = ok(plate.display_plan(tol)); + let plan = ok(plate.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(tol))); p.push(ms(t)); let t = std::time::Instant::now(); let m = plan.evaluate(); diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index edfbf4cdb..7ad8aba7f 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -9,14 +9,17 @@ //! evaluated on the GPU into the vertex buffer the pass draws (see [`PlannedBody`]), with nothing //! built or read back on the CPU. +use solidcraft_geom::prelude::*; use std::sync::{Arc, Mutex}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::pbr; use wgpu::util::DeviceExt; mod ao; +mod clouds; +pub use clouds::{CloudFilter, CloudStyle, ColorMode, DOT_SIZE, Dot, FILTERS, GpuCloud, cloud_dot}; #[cfg(not(target_arch = "wasm32"))] mod msaa_check; mod oit; @@ -41,7 +44,7 @@ pub struct PaletteIndex(pub u32); /// How many palette entries fit on one texel row: the shader reads `x = i & 2047`, /// `y = i >> 11`. A power of two keeps the lookup a shift and a mask. pub const PALETTE_WIDTH: u32 = 2048; -/// Most palette entries a scene may carry (2048 × 512): the palette is an `R32Uint` texture +/// Most palette entries a scene may carry (2048 × 512): the palette is an `Rg32Uint` texture /// (`downlevel_defaults`/WebGL2 have no storage buffers in the vertex stage). pub const MAX_PALETTE: usize = 1 << 20; @@ -50,17 +53,22 @@ pub const MAX_PALETTE: usize = 1 << 20; /// The first [`Palette::stable_len`] entries are stable for a scene: cached block bytes keep /// referring to them, so appearance edits only change their values. Entries after that are /// interned per build for ephemeral geometry (grids, highlights, sketch, previews). +/// +/// A stable entry also carries the section hatch of the body it colours +/// (`solidcraft_render::hatch`): none, the cap's own hatch, unless the scene hatches by part. #[derive(Clone, Debug, Default)] pub struct Palette { entries: Vec<[u8; 4]>, lookup: std::collections::HashMap<[u8; 4], u32>, stable_len: usize, + /// Per entry, 1 + its body's hatch, or 0 for the cap's own (empty: 0 for every entry). + hatches: Vec, } impl Palette { /// A palette whose entries are all stable (the model scene's body/face slots). pub fn with_stable(entries: Vec<[u8; 4]>) -> Palette { - Palette { stable_len: entries.len(), entries, lookup: std::collections::HashMap::new() } + Palette { stable_len: entries.len(), entries, lookup: std::collections::HashMap::new(), hatches: Vec::new() } } /// Where the stable entries end and the per-build interned ones begin. @@ -116,9 +124,35 @@ impl Palette { PaletteIndex(i) } - /// The palette as the shader's `R32Uint` texels (rgba bytes packed little-endian). - pub fn texels(&self) -> Vec { - self.entries.iter().map(|[r, g, b, a]| u32::from_le_bytes([*r, *g, *b, *a])).collect() + /// Give stable entry `i` (a body's colour) that body's section hatch; `false` when `i` is not + /// a stable entry. + pub fn set_hatch(&mut self, i: PaletteIndex, hatch: solidcraft_render::hatch::Hatch) -> bool { + let at = i.0 as usize; + if at >= self.stable_len { + return false; + } + if self.hatches.len() < self.stable_len { + self.hatches.resize(self.stable_len, 0); + } + match self.hatches.get_mut(at) { + Some(slot) => { + *slot = hatch.0.saturating_add(1); + true + } + None => false, + } + } + + /// The section hatch entry `i` was given ([`Palette::set_hatch`]), if any. + pub fn hatch(&self, i: PaletteIndex) -> Option { + self.hatches.get(i.0 as usize).and_then(|h| h.checked_sub(1)).map(solidcraft_render::hatch::Hatch) + } + + /// Entry `i` as the shader's `Rg32Uint` texel: the rgba bytes packed little-endian, then + /// 1 + its hatch (0: the cap's own). + fn texel(&self, i: usize) -> [u32; 2] { + let colour = self.entries.get(i).map_or(0, |[r, g, b, a]| u32::from_le_bytes([*r, *g, *b, *a])); + [colour, u32::from(self.hatches.get(i).copied().unwrap_or(0))] } } @@ -151,8 +185,8 @@ fn octahedral6(n: [f32; 3]) -> u32 { } /// The shader's `U`: the view-projection matrix, 10 `vec4`s (the tenth carries the ambient /// occlusion radius), the 8 analysis colours, their flags, the depth direction and the two -/// whole-body highlight colours (`uniform_bytes`). -const UNIFORM_SIZE: u64 = 416 + 16 + 21 * 64; +/// whole-body highlight colours, then the section hatch colours, the product lights, and the sky (`uniform_bytes`). +const UNIFORM_SIZE: u64 = 416 + 16 * solidcraft_render::hatch::HATCH_COLOURS as u64 + 16 + 21 * 64 + 16; /// A body drawn from its display plan, evaluated on the GPU: the plan, and a palette index per /// face (the plan's face numbering; faces past the end take the last index). @@ -163,11 +197,15 @@ pub struct PlannedBody { /// How the whole body is drawn: opaque with the model, or faded or see-through blended /// order-independently (only on a renderer that does that: [`GpuTarget::oit`]). pub class: TriClass, + /// The body encloses a volume (a solid, a closed mesh). Only closed bodies take part in a + /// section's crossing count ([`Cut`]): an open one has no inside, so it neither gets a cap + /// nor takes one from the body it lies in. + pub closed: bool, } /// What the viewport's last frame drew, counted as it was drawn (the performance overlay, #2548). /// Triangles and line segments count every pass that draws them, so a section's stencil passes -/// count twice; that is the work the GPU did. +/// count once each; that is the work the GPU did. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct DrawStats { pub draw_calls: u32, @@ -412,6 +450,8 @@ pub struct InstancedMesh { /// in the part's frame): a placement small on screen is drawn from the coarsest whose error /// stays under [`LOD_PX`] there ([`Batches::cull`]). pub levels: Vec<(Arc, f32)>, + /// The triangles enclose a volume (see [`PlannedBody::closed`]). + pub closed: bool, } impl InstancedMesh { @@ -456,6 +496,9 @@ pub struct GpuScene { pub palette: Arc, /// Opaque triangles. A zero normal draws the colour flat (unlit). pub tris: Vec, + /// Opaque triangles of open bodies, drawn as `tris` but left out of a section's crossing + /// count (see [`PlannedBody::closed`]). + pub open_tris: Vec, /// Opaque product PBR vertices; linear base color and explicit optical parameters. pub pbr: Vec, /// Translucent triangles (alpha from the colour), drawn after the opaque ones without @@ -547,6 +590,7 @@ impl GpuScene { } } out.tris.append(&mut self.tris); + out.tris.append(&mut self.open_tris); out.trans.append(&mut self.trans); out.lines.append(&mut self.lines); out.hidden.append(&mut self.hidden); @@ -615,6 +659,9 @@ pub struct BlockBytes { /// out of the draws ([`Batches::cull`]). Vertices outside every span are always drawn. pub bodies: Arc>, pub opaque: Arc>>, + /// The opaque runs of closed bodies: what a section's crossing count draws (see + /// [`PlannedBody::closed`]). + pub closed: Arc>>, pub glass: Arc>>, pub faded: Arc>>, pub lines: Arc>, @@ -683,13 +730,16 @@ pub fn extend_runs(runs: &mut Vec>, at: u32) { pub struct BlockBuilder { vertices: Vec, opaque: Vec>, + closed: Vec>, + /// The triangles being added belong to an open body ([`BlockBuilder::open_body`]). + open: bool, glass: Vec>, faded: Vec>, lines: Vec, hidden: Vec, bodies: Vec, /// The body being written: its first vertex and the box so far. - open: Option<(u32, [[f32; 3]; 2])>, + spanning: Option<(u32, [[f32; 3]; 2])>, } impl BlockBuilder { @@ -697,12 +747,12 @@ impl BlockBuilder { /// it can be left out of a view it is not in). pub fn begin_body(&mut self) { let at = u32::try_from(self.vertices.len() / TRI_SIZE).unwrap_or(u32::MAX); - self.open = Some((at, [[f32::INFINITY; 3], [f32::NEG_INFINITY; 3]])); + self.spanning = Some((at, [[f32::INFINITY; 3], [f32::NEG_INFINITY; 3]])); } /// End the body [`BlockBuilder::begin_body`] began. pub fn end_body(&mut self) { - let Some((start, bounds)) = self.open.take() else { return }; + let Some((start, bounds)) = self.spanning.take() else { return }; let end = u32::try_from(self.vertices.len() / TRI_SIZE).unwrap_or(u32::MAX); if end > start && bounds.iter().flatten().all(|x| x.is_finite()) { self.bodies.push(BodySpan { vertices: start..end, bounds }); @@ -726,7 +776,7 @@ impl BlockBuilder { } } self.vertices.extend_from_slice(&record); - if let Some((_, [lo, hi])) = &mut self.open { + if let Some((_, [lo, hi])) = &mut self.spanning { for v in p { for k in 0..3 { lo[k] = lo[k].min(v[k]); @@ -740,6 +790,16 @@ impl BlockBuilder { TriClass::Faded => &mut self.faded, }; extend_runs(runs, at); + if class == TriClass::Opaque && !self.open { + extend_runs(&mut self.closed, at); + } + } + + /// Whether the triangles added from now on belong to an open body (a surface body, a mesh + /// that does not close): those are left out of a section's crossing count. Closed until + /// said otherwise. + pub fn open_body(&mut self, open: bool) { + self.open = open; } /// The runs of `class` that fall within `vertices` (a body's share of the block). @@ -781,6 +841,7 @@ impl BlockBuilder { vertices: Arc::new(self.vertices), bodies: Arc::new(self.bodies), opaque: Arc::new(self.opaque), + closed: Arc::new(self.closed), glass: Arc::new(self.glass), faded: Arc::new(self.faded), lines: Arc::new(self.lines), @@ -803,6 +864,13 @@ impl GpuScene { } self.tris.extend_from_slice(&c.0.to_le_bytes()); } + /// A vertex of an open body's opaque triangle (see [`GpuScene::open_tris`]). + pub fn open_tri(&mut self, p: [f32; 3], n: [f32; 3], c: PaletteIndex) { + for v in p.iter().chain(&n) { + self.open_tris.extend_from_slice(&v.to_le_bytes()); + } + self.open_tris.extend_from_slice(&c.0.to_le_bytes()); + } /// A vertex of the ground-plane shadow (see [`GpuScene::shadow`]). pub fn shadow_tri(&mut self, p: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&[0.0; 3]) { @@ -921,34 +989,6 @@ pub struct GpuImage { /// Image vertex: position (3 × f32), uv (2 × f32), opacity (f32). const IMG_SIZE: usize = 24; -/// A point cloud: round dots of a size on screen, depth-tested and written like the model's -/// faces. -#[derive(Clone)] -pub struct GpuPoints { - pub id: u64, - /// Changes when the points change (they are uploaded again). - pub version: u64, - /// [`CLOUD_POINT_SIZE`] bytes per point: position (3 × f32, in the design), colour (RGBA8, - /// the alpha the dot's size in eighths of a pixel, see [`cloud_point`]). - pub bytes: Arc>, -} - -/// Bytes per point of a [`GpuPoints`]. -pub const CLOUD_POINT_SIZE: usize = 16; - -/// A point of a [`GpuPoints`]: where it is, its colour and its size on screen (pixels, up to 31). -pub fn cloud_point(out: &mut Vec, p: [f32; 3], rgb: [u8; 3], size: f32) { - for v in p { - out.extend_from_slice(&v.to_le_bytes()); - } - out.extend_from_slice(&rgb); - out.push((size * 8.0).round().clamp(8.0, 255.0) as u8); -} - -fn point_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Unorm8x4]; - wgpu::VertexBufferLayout { array_stride: CLOUD_POINT_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } -} /// Ambient occlusion samples per shaded pixel in a still picture (the shader's most). pub const AO_SAMPLES: u32 = 32; @@ -990,7 +1030,7 @@ pub struct Frame { /// Canvases and decals. pub images: Vec, /// Point clouds. - pub points: Vec, + pub clouds: Vec, /// Surface analysis: (mode: 0 none, 1 zebra, 2 draft, 3 curvature, 4 environment, /// 5 accessibility; parameter; scale; size) and the pull / access direction. pub analysis: [f32; 8], @@ -1016,6 +1056,12 @@ pub struct Frame { pub hover_tint: [f32; 3], /// Whole-body selection highlight: a selected body's colour before lighting (sRGB 0..1). pub selection_tint: [f32; 3], + /// The section hatch colours by part (straight sRGB, 0..1; the first the cap's own): what a + /// cut body whose palette entries carry a hatch ([`Palette::set_hatch`]) is tinted toward. + pub hatch: [[f32; 3]; solidcraft_render::hatch::HATCH_COLOURS], + /// The world's up direction and 1 to shade in linear light with a sky fill that follows it + /// (#7974); 0 shades as before. + pub sky: [f32; 4], } /// Heights of the model seen from a direction (an orthographic depth map): a point is reachable @@ -1139,8 +1185,10 @@ struct Batch { struct PlannedDraw { mesh: Arc, colors: wgpu::Buffer, - /// Its bodies' class: a chunk holds bodies of one class. + /// Its bodies' class and whether they are closed: a chunk holds bodies of one class, all + /// closed or all open. class: TriClass, + closed: bool, /// The address of each plan in the chunk, in `mesh.parts` order: a whole-body highlight /// finds the evaluated triangles of the body it lights. plans: Vec, @@ -1275,6 +1323,8 @@ struct LevelDraw { /// while they come back), and the placements in view, each drawn from its level. struct InstancedDraw { look: InstanceLook, + /// Its triangles enclose a volume ([`InstancedMesh::closed`]). + closed: bool, /// The full triangles first, then coarser ones. levels: Vec, bounds: [[f32; 3]; 2], @@ -1340,6 +1390,9 @@ struct BlockGpu { bytes: Arc, vertices: Option, opaque: Option, + /// The opaque runs of closed bodies ([`BlockBytes::closed`]): `opaque`'s own when they are + /// all of them. + closed: Option, glass: Option, faded: Option, lines: Option, @@ -1409,6 +1462,12 @@ impl BlockGpu { class_gpu(device, fits, &bytes.vertices, bytes.runs(class), old_pair, same_vertices, uploaded) }; let (opaque, glass, faded) = (class(TriClass::Opaque), class(TriClass::Glass), class(TriClass::Faded)); + let closed = if bytes.closed == bytes.opaque { + opaque.clone() + } else { + let old_pair = old.as_ref().and_then(|o| o.closed.as_ref().map(|c| (c, &o.bytes.closed))); + class_gpu(device, fits, &bytes.vertices, &bytes.closed, old_pair, same_vertices, uploaded) + }; let keep = |old: Option<&BlockGpu>, pick: fn(&BlockBytes) -> &Arc>, old_lines: fn(&BlockGpu) -> Option<&Batch>| { old.filter(|o| Arc::ptr_eq(pick(&o.bytes), pick(&bytes))).and_then(old_lines).cloned() }; @@ -1418,7 +1477,7 @@ impl BlockGpu { }; let lines = keep(old.as_ref(), |b| &b.lines, |b| b.lines.as_ref()).or_else(|| fresh(&bytes.lines, "sc_block_lines")); let hidden = keep(old.as_ref(), |b| &b.hidden, |b| b.hidden.as_ref()).or_else(|| fresh(&bytes.hidden, "sc_block_hidden")); - BlockGpu { bytes, vertices, opaque, glass, faded, lines, hidden, culled: None } + BlockGpu { bytes, vertices, opaque, closed, glass, faded, lines, hidden, culled: None } } fn class(&self, class: TriClass) -> Option<&ClassGpu> { @@ -1431,11 +1490,20 @@ impl BlockGpu { /// Draw `class`'s triangles with the pipeline already set (`tally`: what is counted). fn draw(&self, pass: &mut wgpu::RenderPass<'_>, class: TriClass, tally: &Tally) { - match self.class(class) { + self.draw_runs(pass, self.class(class), self.culled.as_ref().and_then(|c| c.get(class as usize)), tally); + } + + /// Draw the closed bodies' opaque triangles ([`BlockBytes::closed`]), as [`BlockGpu::draw`]. + fn draw_closed(&self, pass: &mut wgpu::RenderPass<'_>, tally: &Tally) { + self.draw_runs(pass, self.closed.as_ref(), None, tally); + } + + fn draw_runs(&self, pass: &mut wgpu::RenderPass<'_>, runs: Option<&ClassGpu>, culled: Option<&Vec>>, tally: &Tally) { + match runs { Some(ClassGpu::Runs(runs)) => { let Some(vertices) = &self.vertices else { return }; pass.set_vertex_buffer(0, vertices.slice(..)); - let runs = self.culled.as_ref().map_or(&runs[..], |c| &c[class as usize][..]); + let runs = culled.map_or(&runs[..], |c| &c[..]); for r in runs.iter() { pass.draw(r.clone(), 0..1); tally.triangles(r.len() as u32, 1); @@ -1475,16 +1543,19 @@ fn joined<'a>(blocks: impl Iterator>, own: Option, /// Held for the bind group, which views it. _texture: wgpu::Texture, bind: wgpu::BindGroup, rows: u32, - entries: Vec<[u8; 4]>, } +/// Bytes of one palette texel. +const PALETTE_TEXEL: u32 = 8; + fn palette_texture(device: &wgpu::Device, rows: u32) -> wgpu::Texture { device.create_texture(&wgpu::TextureDescriptor { label: Some("sc_palette"), @@ -1492,28 +1563,28 @@ fn palette_texture(device: &wgpu::Device, rows: u32) -> wgpu::Texture { mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::R32Uint, + format: wgpu::TextureFormat::Rg32Uint, usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, view_formats: &[], }) } -/// Rows `first..last` of `entries` as the texture's texels (zero past the end). -fn palette_bytes(entries: &[[u8; 4]], first: u32, last: u32) -> Vec { +/// Rows `first..last` of `palette` as the texture's texels (zero past the end). +fn palette_bytes(palette: &Palette, first: u32, last: u32) -> Vec { let width = PALETTE_WIDTH as usize; - let mut out = Vec::with_capacity((last - first) as usize * width * 4); + let mut out = Vec::with_capacity((last - first) as usize * width * PALETTE_TEXEL as usize); for row in first..last { for col in 0..PALETTE_WIDTH { - let i = row as usize * width + col as usize; - let texel = entries.get(i).map_or(0, |[r, g, b, a]| u32::from_le_bytes([*r, *g, *b, *a])); - out.extend_from_slice(&texel.to_le_bytes()); + for word in palette.texel(row as usize * width + col as usize) { + out.extend_from_slice(&word.to_le_bytes()); + } } } out } -fn palette_rows(entries: &[[u8; 4]]) -> u32 { - u32::try_from(entries.len().div_ceil(PALETTE_WIDTH as usize)).unwrap_or(1).max(1) +fn palette_rows(palette: &Palette) -> u32 { + u32::try_from(palette.len().div_ceil(PALETTE_WIDTH as usize)).unwrap_or(1).max(1) } impl PaletteGpu { @@ -1525,15 +1596,14 @@ impl PaletteGpu { palette: Arc, written: &mut u64, ) -> PaletteGpu { - let entries = palette.entries().to_vec(); - let rows = palette_rows(&entries); + let rows = palette_rows(&palette); let texture = palette_texture(device, rows); - let bytes = palette_bytes(&entries, 0, rows); + let bytes = palette_bytes(&palette, 0, rows); *written += bytes.len() as u64; queue.write_texture( wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(PALETTE_WIDTH * 4), rows_per_image: Some(rows) }, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(PALETTE_WIDTH * PALETTE_TEXEL), rows_per_image: Some(rows) }, wgpu::Extent3d { width: PALETTE_WIDTH, height: rows, depth_or_array_layers: 1 }, ); let view = texture.create_view(&Default::default()); @@ -1545,7 +1615,7 @@ impl PaletteGpu { wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&view) }, ], }); - PaletteGpu { palette, _texture: texture, bind, rows, entries } + PaletteGpu { palette, _texture: texture, bind, rows } } /// Bring the texture up to `palette`, writing only the rows whose entries changed (or the @@ -1562,8 +1632,7 @@ impl PaletteGpu { if Arc::ptr_eq(&self.palette, &palette) { return; } - let entries = palette.entries().to_vec(); - let rows = palette_rows(&entries); + let rows = palette_rows(&palette); if rows != self.rows { *self = PaletteGpu::new(device, queue, uniform, bgl, palette, written); return; @@ -1571,7 +1640,7 @@ impl PaletteGpu { let width = PALETTE_WIDTH as usize; let same = |row: u32| { let base = row as usize * width; - (0..width).all(|c| self.entries.get(base + c).copied().unwrap_or_default() == entries.get(base + c).copied().unwrap_or_default()) + (0..width).all(|c| self.palette.texel(base + c) == palette.texel(base + c)) }; let mut row = 0u32; while row < rows { @@ -1583,7 +1652,7 @@ impl PaletteGpu { while row < rows && !same(row) { row += 1; } - let bytes = palette_bytes(&entries, first, row); + let bytes = palette_bytes(&palette, first, row); *written += bytes.len() as u64; queue.write_texture( wgpu::TexelCopyTextureInfo { @@ -1593,11 +1662,10 @@ impl PaletteGpu { aspect: wgpu::TextureAspect::All, }, &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(PALETTE_WIDTH * 4), rows_per_image: Some(row - first) }, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(PALETTE_WIDTH * PALETTE_TEXEL), rows_per_image: Some(row - first) }, wgpu::Extent3d { width: PALETTE_WIDTH, height: row - first, depth_or_array_layers: 1 }, ); } - self.entries = entries; self.palette = palette; } } @@ -1630,6 +1698,8 @@ struct Batches { block_order: Vec, key: Option, tris: Option, + /// [`GpuScene::open_tris`]. + open_tris: Option, pbr: Option, trans: Option, shadow: Option, @@ -1723,6 +1793,7 @@ impl Batches { upload(device, label, data, stride) }; self.tris = own("sc_tris", &sc.tris, TRI_SIZE); + self.open_tris = own("sc_open_tris", &sc.open_tris, TRI_SIZE); self.pbr = own("sc_pbr", &sc.pbr, PBR_SIZE); self.trans = own("sc_trans", &sc.trans, TRI_SIZE); self.shadow = own("sc_shadow", &sc.shadow, TRI_SIZE); @@ -1812,7 +1883,7 @@ impl Batches { self.instanced_tris.insert(key, gpu); } if !levels.is_empty() { - out.push(InstancedDraw { look: m.look, levels, bounds: m.tris.bounds, placements, shown: None }); + out.push(InstancedDraw { look: m.look, closed: m.closed, levels, bounds: m.tris.bounds, placements, shown: None }); } } out @@ -1913,7 +1984,9 @@ impl Batches { for b in bodies { let n = b.plan.vertex_count(); match chunks.last_mut() { - Some(c) if open && filled + n <= crate::MAX_BATCH && c.first().is_some_and(|f| f.class == b.class) => c.push(b), + Some(c) if open && filled + n <= crate::MAX_BATCH && c.first().is_some_and(|f| (f.class, f.closed) == (b.class, b.closed)) => { + c.push(b) + } _ => { chunks.push(vec![b]); filled = 0; @@ -1957,26 +2030,42 @@ impl Batches { } self.uploads.planned += bytes.len() as u64; if let Some((colors, _)) = upload(device, "sc_planned_colors", &bytes, 4).and_then(|c| c.parts.into_iter().next()) { - let class = chunk.first().map_or(TriClass::Opaque, |b| b.class); - out.push(PlannedDraw { mesh, colors, class, plans: key(chunk) }); + let (class, closed) = chunk.first().map_or((TriClass::Opaque, true), |b| (b.class, b.closed)); + out.push(PlannedDraw { mesh, colors, class, closed, plans: key(chunk) }); } } out } } -/// The section's pipelines (see `Renderer::tri_cut`). +/// Where a section's crossing count starts (`Cut::count`): half the stencil's range, so a count +/// that goes below it (more faces entered than left: an open sheet's front) stays apart from one +/// above it. +const STENCIL_BASE: u32 = 128; + +/// The section's pipelines (see `Renderer::tri_cut`), drawn in this order. The cap shows where +/// the section plane lies inside a body: where the faces behind the plane, on the view ray +/// through the pixel, are left by the ray more often than entered. The stencil counts them, so +/// no depth is compared where bodies touch: a cut body's far wall and the face of the body it +/// rests on lie at one depth, and settling that by depth let the other body show through the +/// cap in specks, stripes and triangles. The display meshes are watertight, so the count is +/// exact for closed bodies; an open one (a surface body, a solid with faces left out) gets no +/// cap. struct Cut { - /// Draws the faces and marks the stencil by their true depth: 1 where a back face (the cap) - /// is the visible surface. Unpushed: `FACE_BIAS`'s slope part would let a front face win a - /// band along its edge with a back face seen through the cut, and the cap would skip it (#6328). - mark: wgpu::RenderPipeline, - /// The faces' depth again, pushed back by `FACE_BIAS` as unsectioned faces are (after - /// `Renderer::section_reset`), so their edges draw over them (#1434). No colour, no stencil. - push: wgpu::RenderPipeline, - /// The cap again, only where marked, at the section plane's depth: depth only, as the mark - /// drew the cap's colour (#6728). + /// Counts the crossings in the stencil from [`STENCIL_BASE`]: a back face behind the plane + /// adds one, a front face takes one away. No colour, no depth. Above the base, the plane is + /// inside a body; at or below it, outside (an open sheet seen from its front counts below). + count: wgpu::RenderPipeline, + /// Where the count is above the base, the nearest back face, by its true depth, in its body's cut + /// colour (the body the plane lies inside: the ray leaves it there). + fill: wgpu::RenderPipeline, + /// The cap again, only there, at the section plane's depth (pushed as faces are), so what + /// lies on the cut face draws over it: depth only, as `fill` drew its colour (#6728). cap: wgpu::RenderPipeline, + /// Elsewhere, the faces as they are drawn without a section, pushed back by + /// `FACE_BIAS` so their edges draw over them (#1434); a back face there is an open body's + /// inside, lit, not hatched. + rest: wgpu::RenderPipeline, } /// The viewport's pipelines and the scenes uploaded to one device, for one kind of target. @@ -2011,8 +2100,8 @@ pub struct Renderer { #[cfg(not(target_arch = "wasm32"))] tess_later: Option, /// While a section is shown (when the depth buffer has a stencil), in place of `tri`: the - /// faces marking where the cap shows, their depth pushed back, then the cap again at the - /// section plane's depth, so it hides the inside ([`Cut`]). + /// faces behind the plane counted where the cap shows, the cap in its colour and at the + /// section plane's depth, so it hides the inside, then the other faces ([`Cut`]). tri_cut: Option, /// Highlight triangles over the model (depth test ≤, no depth write). tri_hl: wgpu::RenderPipeline, @@ -2060,10 +2149,8 @@ pub struct Renderer { textures: std::collections::HashMap, /// This frame's quads: (image id, vertices). quads: Vec<(u64, Batch)>, - /// Point clouds' dots. - point: wgpu::RenderPipeline, - /// Point clouds by id: (version, points). - clouds: std::collections::HashMap, + cloud_pipes: clouds::CloudPipes, + clouds: clouds::CloudDraws, access_bgl: wgpu::BindGroupLayout, /// The accessibility depth map (a 1 × 1 stand-in when there is none) and its version. access_bind: wgpu::BindGroup, @@ -2111,9 +2198,9 @@ pub struct Renderer { /// Reversed depth drawn into the window's pass: egui clears its depth to 1, which is the near /// plane then, so the viewport first sets its rectangle to the far plane (0). depth_reset: Option, - /// The scene target's depth back to the far plane between the section's marking and push - /// passes ([`Cut`]); stencil and colour untouched. - section_reset: Option, + /// The scene target's stencil set to [`STENCIL_BASE`] before a section's crossing count + /// ([`Cut`]); depth and colour untouched. + section_stencil: Option, /// The new resolve textures [`clear_resolve_targets`] has cleared (tests count them). #[cfg(test)] resolve_clears: u32, @@ -2689,49 +2776,54 @@ impl Renderer { let solid = |label: &str, fs: &str, cull: Option, ds: Option, source: TriSource| { solid_writes(label, fs, cull, ds, source, true) }; - // While a section is shown, the depth states of the stencil marking and of the cap (see - // `Renderer::tri_cut`), where the depth buffer has a stencil. + // While a section is shown, the depth states of the crossing count and the cap (see `Cut`, + // drawn with the stencil reference `STENCIL_BASE`), where the depth buffer has a stencil. let cut_states = t.depth.filter(|f| f.has_stencil_aspect()).map(|format| { - // The visible surface, by its true depth, marks the stencil: 1 where it is a back face (the cap). - use wgpu::StencilOperation::{Keep, Replace, Zero}; - let face = |pass_op| wgpu::StencilFaceState { compare: wgpu::CompareFunction::Always, fail_op: Keep, depth_fail_op: Keep, pass_op }; - let mark = wgpu::DepthStencilState { + use wgpu::CompareFunction::{Always, GreaterEqual, Less}; + use wgpu::StencilOperation::{DecrementWrap, IncrementWrap, Keep}; + let face = |compare, pass_op| wgpu::StencilFaceState { compare, fail_op: Keep, depth_fail_op: Keep, pass_op }; + let stencil = |front, back, write_mask| wgpu::StencilState { front, back, read_mask: 0xff, write_mask }; + let count = wgpu::DepthStencilState { format, + depth_write_enabled: Some(false), + depth_compare: Some(Always), + stencil: stencil(face(Always, DecrementWrap), face(Always, IncrementWrap), 0xff), + bias: Default::default(), + }; + // The reference (`STENCIL_BASE`) below the count: the plane is inside a body. + let inside = stencil(face(Less, Keep), face(Less, Keep), 0); + let fill = wgpu::DepthStencilState { depth_write_enabled: Some(true), depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)), - stencil: wgpu::StencilState { front: face(Zero), back: face(Replace), read_mask: 0xff, write_mask: 0xff }, - bias: Default::default(), + stencil: inside.clone(), + ..count.clone() }; - // Then the cap's back faces again, only there, at the section plane's depth. - let only = wgpu::StencilFaceState { compare: wgpu::CompareFunction::Equal, ..face(Keep) }; - let cap = wgpu::DepthStencilState { - format, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::Always), - stencil: wgpu::StencilState { front: only, back: only, read_mask: 0xff, write_mask: 0 }, - bias: Default::default(), - }; - (mark, cap) + let cap = wgpu::DepthStencilState { depth_write_enabled: Some(true), stencil: inside, ..count.clone() }; + let outside = stencil(face(GreaterEqual, Keep), face(GreaterEqual, Keep), 0); + let rest = pushed(wgpu::CompareFunction::Less, true, FACE_BIAS).map(|d| wgpu::DepthStencilState { stencil: outside, ..d }); + (count, fill, rest, cap) }); - // `Cut::mark` and `Cut::push` use `tri`'s fragment shader; `Cut::cap` has its own. + // `Cut::count`, `Cut::fill` and `Cut::rest`; `Cut::cap` has a fragment shader of its own. let marks = |source: TriSource| { - cut_states.as_ref().map(|(mark, _)| { + cut_states.as_ref().map(|(count, fill, rest, _)| { ( - solid("sc_tris_mark", "fs_solid", None, Some(mark.clone()), source), - solid_writes("sc_tris_push", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), source, false), + solid_writes("sc_tris_count", "fs_clip", None, Some(count.clone()), source, false), + solid("sc_tris_fill", "fs_solid", Some(wgpu::Face::Front), Some(fill.clone()), source), + solid("sc_tris_rest", "fs_solid_open", None, rest.clone(), source), ) }) }; - // Depth only: every back face behind a marked pixel draws here, so writing colour let the - // last one drawn paint the cut, other bodies behind it included (their colours and - // outlines showed through it, #6328). The marking pass already drew the nearest back - // face's colour. + // Depth only: every back face behind a cap pixel draws here, so writing colour let the last + // one drawn paint the cut, other bodies behind it included (their colours and outlines + // showed through it, #6328). let cap = |source: TriSource| { - cut_states.as_ref().map(|(_, cap)| solid_writes("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap.clone()), source, false)) - }; - let cut = |marks: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, cap: Option| { - marks.zip(cap).map(|((mark, push), cap)| Cut { mark, push, cap }) + cut_states + .as_ref() + .map(|(_, _, _, cap)| solid_writes("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap.clone()), source, false)) }; + type Marks = (wgpu::RenderPipeline, wgpu::RenderPipeline, wgpu::RenderPipeline); + let cut = + |marks: Option, cap: Option| marks.zip(cap).map(|((count, fill, rest), cap)| Cut { count, fill, cap, rest }); let access_bind = access_texture(device, None, &access_bgl, 1, &[]); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("sc_image"), @@ -2801,12 +2893,7 @@ impl Renderer { ) }; let oit = || oit::Pipelines::new(device, &module, &layout, t.format, t.depth, t.samples); - let resets = || { - ( - window.reversed_depth().then(|| depth_reset_pipeline(device, window)).flatten(), - t.depth.filter(|f| f.has_stencil_aspect()).and_then(|_| depth_reset_pipeline(device, t)), - ) - }; + let resets = || (window.reversed_depth().then(|| depth_reset_pipeline(device, window)).flatten(), stencil_set_pipeline(device, t)); let opaque = || pushed(wgpu::CompareFunction::Less, true, FACE_BIAS); // One job per fragment shader, the costly part: wgpu compiles a shader for the first // pipeline that uses it and reuses it for the next, so each is still compiled once. A @@ -2875,7 +2962,7 @@ impl Renderer { pipeline("sc_guide_lines", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), ) }; - let point = || pipeline("sc_points", "vs_point", "fs_point", point_layout(), depth(wgpu::CompareFunction::Less, true), None); + let cloud_pipes = || clouds::CloudPipes::new(device, &module, &bgl, t, depth(wgpu::CompareFunction::Less, true)); let guide_trans = || pipeline("sc_guide_trans", "vs_tri", "fs_tri_all", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha); // Each job on a thread of its own where the device allows it: D3D12 compiles every shader // as its pipeline is made, which took seconds one after another (#4860). @@ -2892,7 +2979,7 @@ impl Renderer { let lines = jobs.spawn(lines); let lines_all = jobs.spawn(lines_all); let guide_trans = jobs.spawn(guide_trans); - let point = jobs.spawn(point); + let cloud_pipes = jobs.spawn(cloud_pipes); let image = jobs.spawn(image); let ao = jobs.spawn(ao); let oit = jobs.spawn(oit); @@ -2909,12 +2996,12 @@ impl Renderer { let (line, line_hidden) = lines.join(); let (overlay, guide_line) = lines_all.join(); let (ss_blit, copy_blit, ss_filter) = blits.join(); - let (depth_reset, section_reset) = resets.join(); + let (depth_reset, section_stencil) = resets.join(); let oit = oit.join(); Renderer { ao: ao.join(), depth_reset, - section_reset, + section_stencil, #[cfg(test)] resolve_clears: 0, target: GpuTarget { oit: oit.is_some(), ..t }, @@ -2941,7 +3028,7 @@ impl Renderer { sampler, textures: Default::default(), quads: Vec::new(), - point: point.join(), + cloud_pipes: cloud_pipes.join(), clouds: Default::default(), tri, tri_cut: cut(tri_marks, tri_cap), @@ -3037,25 +3124,51 @@ const GHOST_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: 2 * FA /// leaving colour and stencil as they are. None without a depth buffer. fn depth_reset_pipeline(device: &wgpu::Device, t: GpuTarget) -> Option { let format = t.depth?; + let reset = wgpu::DepthStencilState { + format, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }; + Some(viewport_pipeline(device, t, "sc_depth_reset", reset)) +} + +/// A pipeline that sets the stencil of the viewport in a pass of `t`'s kind to the reference, +/// leaving colour and depth as they are: a section's crossing count starts from it ([`Cut`]). +/// None without a stencil. +fn stencil_set_pipeline(device: &wgpu::Device, t: GpuTarget) -> Option { + let format = t.depth.filter(|f| f.has_stencil_aspect())?; + let replace = wgpu::StencilFaceState { + compare: wgpu::CompareFunction::Always, + fail_op: wgpu::StencilOperation::Keep, + depth_fail_op: wgpu::StencilOperation::Keep, + pass_op: wgpu::StencilOperation::Replace, + }; + let set = wgpu::DepthStencilState { + format, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: wgpu::StencilState { front: replace, back: replace, read_mask: 0xff, write_mask: 0xff }, + bias: Default::default(), + }; + Some(viewport_pipeline(device, t, "sc_stencil_set", set)) +} + +/// A triangle over the whole viewport in a pass of `t`'s kind, writing no colour, with `ds`. +fn viewport_pipeline(device: &wgpu::Device, t: GpuTarget, label: &str, ds: wgpu::DepthStencilState) -> wgpu::RenderPipeline { let far = if t.reversed_depth() { "0.0" } else { "1.0" }; let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("sc_depth_reset"), + label: Some(label), source: wgpu::ShaderSource::Wgsl(DEPTH_RESET_SHADER.replace("FAR", far).into()), }); - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("sc_depth_reset"), bind_group_layouts: &[], immediate_size: 0 }); - Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("sc_depth_reset"), + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: &[], immediate_size: 0 }); + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), layout: Some(&layout), vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, - depth_stencil: Some(wgpu::DepthStencilState { - format, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::Always), - stencil: Default::default(), - bias: Default::default(), - }), + depth_stencil: Some(ds), multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, fragment: Some(wgpu::FragmentState { module: &module, @@ -3065,7 +3178,7 @@ fn depth_reset_pipeline(device: &wgpu::Device, t: GpuTarget) -> Option Option { @@ -3244,7 +3357,7 @@ fn can_reuse(ss_ready: bool, cached: Option, key: u64) -> bool { /// section, images, analysis, accessibility map, ambient occlusion and the theme's hover and /// selection tints. The same key draws the same picture (pipelines and shaders are fixed for the /// renderer). -fn frame_key(cb: &Frame) -> u64 { +pub fn frame_key(cb: &Frame) -> u64 { use std::hash::Hash as _; let mut h = std::collections::hash_map::DefaultHasher::new(); cb.product.hash(&mut h); @@ -3266,6 +3379,8 @@ fn frame_key(cb: &Frame) -> u64 { // picture cached under the previous theme's colours is not shown (#5802). cb.hover_tint.map(f32::to_bits).hash(&mut h); cb.selection_tint.map(f32::to_bits).hash(&mut h); + cb.hatch.iter().flatten().for_each(|v| v.to_bits().hash(&mut h)); + cb.sky.map(f32::to_bits).hash(&mut h); cb.outline.hash(&mut h); cb.ao_radius.to_bits().hash(&mut h); cb.ao_samples.hash(&mut h); @@ -3277,10 +3392,7 @@ fn frame_key(cb: &Frame) -> u64 { img.corners.iter().flatten().for_each(|v| v.to_bits().hash(&mut h)); img.opacity.to_bits().hash(&mut h); } - for cloud in &cb.points { - cloud.id.hash(&mut h); - cloud.version.hash(&mut h); - } + clouds::hash_clouds(&cb.clouds, &mut h); match &cb.access { Some(a) => { true.hash(&mut h); @@ -3430,20 +3542,7 @@ impl Renderer { res.quads.push((img.id, b)); } } - // Point clouds: upload new or changed ones, drop removed ones. - res.clouds.retain(|id, _| cb.points.iter().any(|c| c.id == *id)); - for c in &cb.points { - if res.clouds.get(&c.id).is_none_or(|(v, _)| *v != c.version) { - match upload(device, "sc_points", &c.bytes, CLOUD_POINT_SIZE) { - Some(b) => { - res.clouds.insert(c.id, (c.version, b)); - } - None => { - res.clouds.remove(&c.id); - } - } - } - } + res.clouds.prepare(device, queue, &res.cloud_pipes, &cb.clouds); res.ss_ready = (cb.ssaa != 1.0 || see_through || res.window_differs()) && res.supersample(device, encoder, cb, see_through); res.ss_key = res.ss_ready.then_some(key); } @@ -3568,7 +3667,7 @@ impl Renderer { }; if phase == Phase::AfterSeeThrough { pass.set_bind_group(1, &res.access_bind, &[]); - pass.set_bind_group(2, &res.ao.bind, &[]); + pass.set_bind_group(2, &res.ao.maps.bind, &[]); Self::draw_over(res, pass, sk, h, pv, m, &tris, &lines); return; } @@ -3577,10 +3676,11 @@ impl Renderer { pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); lines(pass, &res.overlay, &sk.under); pass.set_bind_group(1, &res.access_bind, &[]); - pass.set_bind_group(2, &res.ao.bind, &[]); + pass.set_bind_group(2, &res.ao.maps.bind, &[]); pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); - let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline| { - for d in m.planned.iter().filter(|d| d.class == TriClass::Opaque) { + // `counting`: only closed bodies, for a section's crossing count ([`Cut::count`]). + let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, counting: bool| { + for d in m.planned.iter().filter(|d| d.class == TriClass::Opaque && (d.closed || !counting)) { pass.set_pipeline(p); pass.set_vertex_buffer(0, d.mesh.vertices.slice(..)); pass.set_vertex_buffer(1, d.colors.slice(..)); @@ -3590,8 +3690,8 @@ impl Renderer { } }; // Instanced meshes, with the pipeline for smooth and for flat triangles. - let instanced = |pass: &mut wgpu::RenderPass<'static>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline| { - for d in m.instanced.iter().filter(|d| d.look == InstanceLook::Opaque) { + let instanced = |pass: &mut wgpu::RenderPass<'static>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline, counting: bool| { + for d in m.instanced.iter().filter(|d| d.look == InstanceLook::Opaque && (d.closed || !counting)) { d.draw(pass, smooth, flat, tally); } }; @@ -3638,49 +3738,57 @@ impl Renderer { res.tri_cut_planned.as_ref(), res.tri_cut_instanced.as_ref(), res.tri_cut_instanced_flat.as_ref(), - res.section_reset.as_ref(), + res.section_stencil.as_ref(), ) { - (Some(cut), Some(cut_planned), Some(cut_instanced), Some(cut_flat), Some(reset)) => { + (Some(cut), Some(cut_planned), Some(cut_instanced), Some(cut_flat), Some(base)) => { // The model's own triangles, blocks, plans and instances with its palette, then the // preview's with its own. - let all = |pass: &mut wgpu::RenderPass<'static>, pick: fn(&Cut) -> &wgpu::RenderPipeline| { + // `counting`: the crossing count, which leaves open bodies out. + let all = |pass: &mut wgpu::RenderPass<'static>, pick: fn(&Cut) -> &wgpu::RenderPipeline, counting: bool| { pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); tris(pass, pick(cut), &m.tris); - block_class(pass, pick(cut), TriClass::Opaque); - planned(pass, pick(cut_planned)); - instanced(pass, pick(cut_instanced), pick(cut_flat)); + if counting { + for block in m.block_order.iter().filter_map(|k| m.blocks.get(k)).filter(|b| b.closed.is_some()) { + pass.set_pipeline(pick(cut)); + block.draw_closed(pass, tally); + } + } else { + tris(pass, pick(cut), &m.open_tris); + block_class(pass, pick(cut), TriClass::Opaque); + } + planned(pass, pick(cut_planned), counting); + instanced(pass, pick(cut_instanced), pick(cut_flat), counting); pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); tris(pass, pick(cut), &pv.tris); + if !counting { + tris(pass, pick(cut), &pv.open_tris); + } }; - pass.set_stencil_reference(1); - all(pass, |c| &c.mark); - pass.set_pipeline(reset); + pass.set_stencil_reference(STENCIL_BASE); + pass.set_pipeline(base); pass.draw(0..3, 0..1); tally.call(); - all(pass, |c| &c.push); - all(pass, |c| &c.cap); + all(pass, |c| &c.count, true); + all(pass, |c| &c.fill, false); + all(pass, |c| &c.cap, false); + all(pass, |c| &c.rest, false); } _ => { pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); tris(pass, &res.tri, &m.tris); + tris(pass, &res.tri, &m.open_tris); block_class(pass, &res.tri, TriClass::Opaque); - planned(pass, &res.tri_planned); - instanced(pass, &res.tri_instanced, &res.tri_instanced_flat); + planned(pass, &res.tri_planned, false); + instanced(pass, &res.tri_instanced, &res.tri_instanced_flat, false); pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); tris(pass, &res.tri, &pv.tris); + tris(pass, &res.tri, &pv.open_tris); } } pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); tris(pass, &res.pbr, &m.pbr); if !cb.product { - for (_, b) in res.clouds.values() { - pass.set_pipeline(&res.point); - for (buffer, count) in &b.parts { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(0..6, 0..*count); - tally.triangles(6, *count); - } - } + res.clouds.paint(pass, &res.cloud_pipes, tally); } // Whole-body tints first, so a face or an edge highlighted over the body (in `h.tris` // and `h.lines`) keeps its own colour, as it did when the body's triangles were built @@ -3712,14 +3820,19 @@ impl Renderer { } } tris(pass, &res.tri_hl, &h.tris); - pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); - lines(pass, &res.line, &m.lines); - pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); - lines(pass, &res.line, &sk.lines); + // Hidden edges before the visible ones, so a visible edge is drawn over them. An edge + // within a pixel of a nearer face's outline (a face seen edge on beside it) is hidden + // under part of its own width; drawn after, its light hidden copy covered the visible + // edge beside it there with a light line. pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); lines(pass, &res.line_hidden, &m.hidden); pass.set_bind_group(0, scene_bind(h, &res.bind), &[]); lines(pass, &res.line_hidden, &h.hidden); + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); + lines(pass, &res.line, &m.lines); + pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); + lines(pass, &res.line, &sk.lines); + pass.set_bind_group(0, scene_bind(h, &res.bind), &[]); lines(pass, &res.line, &h.lines); lines(pass, &res.guide_line, &h.guide_lines); pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); @@ -4131,6 +4244,9 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) - v.extend([if reversed { 1.0 } else { 0.0 }, FACE_STEPS as f32, FACE_SLOPE, 0.0]); v.extend([cb.hover_tint[0], cb.hover_tint[1], cb.hover_tint[2], 0.0]); v.extend([cb.selection_tint[0], cb.selection_tint[1], cb.selection_tint[2], 0.0]); + for [r, g, b] in cb.hatch { + v.extend([r, g, b, 1.0]); + } v.extend([ if cb.product_lights.is_some() { 1.0 } else { 0.0 }, cb.product_lights.as_ref().map_or(0, |lights| lights.len().min(21)) as f32, @@ -4141,6 +4257,7 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) - let light = cb.product_lights.as_ref().and_then(|lights| lights.get(index)).copied().unwrap_or([0.0; 16]); v.extend(light.map(|value| if value.is_finite() { value } else { 0.0 })); } + v.extend(cb.sky.map(|value| if value.is_finite() { value } else { 0.0 })); v.iter().flat_map(|x| x.to_le_bytes()).collect() } @@ -4229,7 +4346,8 @@ mod tests { #[test] fn shared_tris_share_each_vertex_once() { use super::{SHARED_SIZE, SharedTris}; - use solidcraft_geom::{Mesh, Vec3}; + use solidcore_record::Vec3; + use solidcraft_geom::Mesh; let p = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)]; // Two triangles of a square, each corner its own vertex (as an STL is read). let mut flat = Mesh::default(); @@ -4336,6 +4454,28 @@ mod tests { assert_eq!(samples_sent(1000), 32.0, "at most the shader's 32"); } + /// The sky (#7974) is the uniform's last `vec4`: the world's up direction and the switch, with + /// anything not finite sent as zero (shaded as before). + #[test] + fn the_sky_rides_at_the_end_of_the_uniform() { + let last = |sky: [f32; 4]| { + let mut f = cached_frame(); + f.sky = sky; + let bytes = super::uniform_bytes(&f, 64.0, 64.0, false, false); + assert_eq!(bytes.len() as u64, super::UNIFORM_SIZE); + let v: Vec = bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); + v[v.len() - 4..].to_vec() + }; + assert_eq!(last([0.0, 0.0, 1.0, 1.0]), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(last([0.0; 4]), [0.0; 4]); + assert_eq!(last([f32::NAN, 1.0, f32::INFINITY, 1.0]), [0.0, 1.0, 0.0, 1.0]); + // Turning it on draws the frame again. + let mut f = cached_frame(); + let off = super::frame_key(&f); + f.sky = [0.0, 0.0, 1.0, 1.0]; + assert_ne!(super::frame_key(&f), off); + } + #[test] fn render_lights_preview_shader_uniform_and_frame_cache_include_light_state() { let source = format!("{}\n{}", super::SHADER, crate::pbr::SOURCE); @@ -4377,16 +4517,18 @@ mod tests { clip: [0.0; 4], cap: [0.0; 4], images: Vec::new(), - points: Vec::new(), + clouds: Vec::new(), analysis: [0.0; 8], analysis_colors: [0.0; 36], access: None, hover_tint: [0.0; 3], selection_tint: [0.0; 3], + hatch: Default::default(), outline: false, eye: [0.0; 4], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, } } @@ -4539,6 +4681,55 @@ mod tests { mod glass_tests { use super::*; + /// Intel UHD 620 OpenGL collapsed long line quads or expanded short ones across the + /// viewport with vector/scalar direction division (#8053). Exercise the actual + /// OpenGL shader rather than the native headless selector, which skips GL on Windows. + #[test] + fn opengl_draws_grid_lines_in_every_direction_and_at_a_point() { + let mut descriptor = crate::instance_descriptor_from_env(); + descriptor.backends = wgpu::Backends::GL; + let instance = wgpu::Instance::new(descriptor); + let policy = crate::select::Policy::from_env().expect("a valid GPU test policy"); + let Some((adapter, _)) = crate::select::pick_among(pollster::block_on(instance.enumerate_adapters(wgpu::Backends::GL)), policy) else { + eprintln!("skipped: no OpenGL adapter qualifies under {}", policy.name()); + return; + }; + eprintln!("OpenGL regression adapter: {:?}", adapter.get_info()); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + required_limits: wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter.limits()), + ..Default::default() + })) + .expect("the OpenGL adapter opens a device"); + let window = GpuTarget { format: wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }; + // Ten world units span 32 pixels here; a four-pixel line covers over 100 pixels. + // A point or a very short line stays a small cap, never a fill over the viewport. + let cases = [ + ([-5.0, 0.0, 0.0], [5.0, 0.0, 0.0], 100..=256), + ([5.0, 0.0, 0.0], [-5.0, 0.0, 0.0], 100..=256), + ([0.0, -5.0, 0.0], [0.0, 5.0, 0.0], 100..=256), + ([0.0, 5.0, 0.0], [0.0, -5.0, 0.0], 100..=256), + ([-5.0, -5.0, 0.0], [5.0, 5.0, 0.0], 120..=256), + ([5.0, 5.0, 0.0], [-5.0, -5.0, 0.0], 120..=256), + ([-5.0, 5.0, 0.0], [5.0, -5.0, 0.0], 120..=256), + ([0.0; 3], [0.0; 3], 10..=64), + ([0.0; 3], [0.0001, 0.0001, 0.0], 10..=64), + ]; + for offscreen in [false, true] { + let target = if offscreen { GpuTarget { depth: Some(wgpu::TextureFormat::Depth24PlusStencil8), ..window } } else { window }; + let mut renderer = Renderer::with_window_target(&device, target, window, None); + for (index, (a, b, expected)) in cases.iter().enumerate() { + let mut scene = GpuScene::default(); + let red = scene.color([255, 0, 0, 255]); + scene.under_line(*a, *b, red, 4.0); + let mut frame = test_frame(scene, 1.0); + frame.key = index as u64 + 1; + let pixels = render_frame(&mut renderer, &device, &queue, &frame, false); + let coloured = pixels.as_chunks::<4>().0.iter().filter(|p| p[0] > 240 && p[1] < 30 && p[2] < 30).count(); + assert!(expected.contains(&coloured), "{a:?} to {b:?}, offscreen {offscreen}: {coloured} line pixels, expected {expected:?}"); + } + } + } + #[test] fn ground_shadow_does_not_require_order_independent_transparency() { let batch = || Some(Batch { parts: Vec::new(), chunk: TRI_SIZE * 6 }); @@ -4764,7 +4955,7 @@ mod glass_tests { clip: [0.0; 4], cap: [0.0; 4], images: Vec::new(), - points: Vec::new(), + clouds: Vec::new(), analysis: [0.0; 8], analysis_colors: [0.0; 36], access: None, @@ -4772,9 +4963,11 @@ mod glass_tests { eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], + hatch: Default::default(), }; let texture = |format, usage, sample_count| { device.create_texture(&wgpu::TextureDescriptor { @@ -4939,16 +5132,18 @@ mod glass_tests { clip: [0.0; 4], cap: [0.0; 4], images: Vec::new(), - points: Vec::new(), + clouds: Vec::new(), analysis: [0.0; 8], analysis_colors: [0.0; 36], access: None, hover_tint: [0.0; 3], selection_tint: [0.0; 3], + hatch: Default::default(), outline: false, eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa, } } @@ -4964,28 +5159,39 @@ mod glass_tests { } #[test] - fn a_cached_point_cloud_picture_updates_after_recoloring_and_hiding() { + fn a_cached_cloud_picture_follows_its_style_without_uploading_again() { let Some((_, device, queue)) = crate::open_headless().ok() else { return }; let depth = crate::depth_format(&device, true); let format = wgpu::TextureFormat::Rgba8Unorm; let mut renderer = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples: 1, tess: false, oit: false }, None); let mut frame = test_frame(GpuScene::default(), 2.0); - let mut bytes = Vec::new(); - cloud_point(&mut bytes, [0.0; 3], [255, 0, 0], 20.0); - frame.points.push(GpuPoints { id: 1, version: 1, bytes: Arc::new(bytes) }); - let red = render_frame(&mut renderer, &device, &queue, &frame, true); - assert!(red.as_chunks::<4>().0.iter().any(|p| p[0] > 200 && p[1] < 30 && p[2] < 30), "the cloud is drawn"); - render_frame(&mut renderer, &device, &queue, &frame, true); - assert!(renderer.cached.is_some()); - let mut bytes = Vec::new(); - cloud_point(&mut bytes, [0.0; 3], [0, 0, 255], 20.0); - frame.points = vec![GpuPoints { id: 1, version: 2, bytes: Arc::new(bytes) }]; - let blue = render_frame(&mut renderer, &device, &queue, &frame, true); - assert!(blue.as_chunks::<4>().0.iter().any(|p| p[0] < 30 && p[1] < 30 && p[2] > 200), "the edited cloud replaces the cached picture"); - assert_ne!(red, blue); - frame.points.clear(); + // A dot labelled 2 (red in the palette) and a dot filtered by 5 (a range) and the label + // 2 (a set). + let mut dots = Vec::new(); + cloud_dot(&mut dots, &Dot { at: [5.0, 5.0, 0.0], rgb: [0, 0, 255], value: 2.0, has: 16, ..Default::default() }); + let filtered = Dot { at: [-3.0, -3.0, 0.0], value: 1.0, filtered: [5.0, 2.0, 0.0, 0.0], rgb: [0, 255, 0], has: 0b10011 }; + cloud_dot(&mut dots, &filtered); + let style = CloudStyle { mode: ColorMode::Own, range: [0.0, 1.0], filters: Default::default(), point_size: 20.0 }; + frame.clouds.push(GpuCloud { id: 1, version: 1, dots: Arc::new(dots), style }); + let has = |img: &[u8], f: &dyn Fn(&[u8; 4]) -> bool| img.as_chunks::<4>().0.iter().any(f); + let green = |p: &[u8; 4]| p[1] > 120 && p[0] < 30 && p[2] < 30; + let own = render_frame(&mut renderer, &device, &queue, &frame, true); + assert!(has(&own, &|p| p[2] > 200 && p[0] < 30), "a dot in its own colour"); + assert!(has(&own, &green), "the other in its own colour"); + // Values from -1: bit 3 is the label 2, bit 2 the label 1. + frame.clouds[0].style.filters[1] = CloudFilter::Values { offset: -1, mask: 0b1000 }; + assert!(has(&render_frame(&mut renderer, &device, &queue, &frame, true), &green), "label 2 kept"); + frame.clouds[0].style.filters[1] = CloudFilter::Values { offset: -1, mask: 0b0100 }; + assert!(!has(&render_frame(&mut renderer, &device, &queue, &frame, true), &green), "label 2 left out"); + frame.clouds[0].style.filters[1] = CloudFilter::Off; + frame.clouds[0].style.filters[0] = CloudFilter::Range([0.0, 4.0]); + frame.clouds[0].style.mode = ColorMode::Palette; + let filtered = render_frame(&mut renderer, &device, &queue, &frame, true); + assert!(!has(&filtered, &green), "its 5 lies outside the range"); + assert!(has(&filtered, &|p| p[0] > 200 && p[1] < 90 && p[2] < 90), "the first, without that value, in the palette's red"); + frame.clouds.clear(); let hidden = render_frame(&mut renderer, &device, &queue, &frame, true); - assert!(!hidden.as_chunks::<4>().0.iter().any(|p| p[0] < 30 && p[1] < 30 && p[2] > 200), "hiding the cloud removes its dots"); + assert!(!has(&hidden, &|p| p[0] > 200 && p[1] < 90 && p[2] < 90), "hiding the cloud removes it"); } /// A still view shows the picture it drew last: a reused frame (whose filtered picture is diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rs index 850b0fac5..2449e6e58 100644 --- a/crates/gpu/src/view/ao.rs +++ b/crates/gpu/src/view/ao.rs @@ -1,68 +1,134 @@ -//! The optional AO depth prepass. Only opaque model and preview triangles participate: their -//! depth is drawn once into a single-sample depth map the lit fragment samples for occlusion. -//! The map is independent of the window's MSAA, and the depth runs the same way as the -//! viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]). +//! The optional AO passes. Only opaque model and preview triangles participate: their depth is +//! drawn once into a single-sample depth map, and the occlusion term of the surface that depth +//! holds is drawn into a texture of the same size and blurred by depth (#9327), which the lit +//! fragment reads. The maps are independent of the window's MSAA, and the depth runs the same way +//! as the viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]). //! Depth testing chooses the nearest surface; an R32Uint colour attachment stores that depth's //! bits for portable integer texel reads. GLSL cannot load from a depth texture, and float //! colour attachments are not available on every GL adapter. use super::{Batches, TriSource, color_layout, depth_compare, far_depth, instance_layout, planned_layout, shared_layout, tri_layout}; -pub(super) struct Resources { - pub layout: wgpu::BindGroupLayout, - pub bind: wgpu::BindGroup, - depth: wgpu::TextureView, - values: wgpu::TextureView, - size: [u32; 2], - pipeline: wgpu::RenderPipeline, - planned_pipeline: wgpu::RenderPipeline, - instanced_pipeline: wgpu::RenderPipeline, - instanced_flat_pipeline: wgpu::RenderPipeline, +const TERM_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Unorm; + +/// What the opaque triangles are drawn with in one pass, by where they come from. +struct OpaquePipelines { + built: wgpu::RenderPipeline, + planned: wgpu::RenderPipeline, + instanced: wgpu::RenderPipeline, + instanced_flat: wgpu::RenderPipeline, } -fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> (wgpu::TextureView, wgpu::TextureView, wgpu::BindGroup) { - let texture = |label, format, usage| { - device.create_texture(&wgpu::TextureDescriptor { +/// The maps at their current size. Group 2 of the shader is the depth map and a term: `bind` has +/// the blurred one for the lit pass, `blur_bind` the raw one for the blur. +pub(super) struct Maps { + pub bind: wgpu::BindGroup, + blur_bind: wgpu::BindGroup, + depth: wgpu::TextureView, + values: wgpu::TextureView, + raw: wgpu::TextureView, + smooth: wgpu::TextureView, +} + +pub(super) struct Resources { + pub layout: wgpu::BindGroupLayout, + pub maps: Maps, + size: [u32; 2], + prepass: OpaquePipelines, + term: OpaquePipelines, + blur: wgpu::RenderPipeline, +} + +fn maps(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> Maps { + let view = |label, format, usage| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let drawn_and_read = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; + let depth = view("sc_ao_depth", wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT); + let values = view("sc_ao_values", wgpu::TextureFormat::R32Uint, drawn_and_read); + let raw = view("sc_ao_raw", TERM_FORMAT, drawn_and_read); + let smooth = view("sc_ao_smooth", TERM_FORMAT, drawn_and_read); + let group = |label, term| { + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(label), - size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage, - view_formats: &[], + layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(term) }, + ], }) }; - let depth = texture("sc_ao_depth", wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT).create_view(&Default::default()); - let values = texture("sc_ao_values", wgpu::TextureFormat::R32Uint, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING) - .create_view(&Default::default()); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("sc_ao_depth"), - layout, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) }], - }); - (depth, values, bind) + Maps { bind: group("sc_ao_lit", &smooth), blur_bind: group("sc_ao_blur", &raw), depth, values, raw, smooth } +} + +/// A term map as a pass's target, cleared to no occlusion. +fn term_target(view: &wgpu::TextureView) -> Option> { + Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), store: wgpu::StoreOp::Store }, + }) +} + +/// The opaque triangles of `batches`, as neither pass counts them in the performance overlay. +fn draw_opaque(pass: &mut wgpu::RenderPass<'_>, pipelines: &OpaquePipelines, binds: [&wgpu::BindGroup; 2], batches: [&Batches; 2]) { + for (batch, bind) in batches.into_iter().zip(binds) { + pass.set_bind_group(0, bind, &[]); + pass.set_pipeline(&pipelines.built); + for tris in [&batch.tris, &batch.open_tris].into_iter().flatten() { + for (buffer, count) in &tris.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*count, 0..1); + } + } + let uncounted = super::Tally::default(); + // The blocks' opaque triangles, for the same depth. + for key in &batch.block_order { + if let Some(block) = batch.blocks.get(key) { + block.draw(pass, super::TriClass::Opaque, &uncounted); + } + } + pass.set_pipeline(&pipelines.planned); + for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) { + pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..)); + pass.set_vertex_buffer(1, draw.colors.slice(..)); + pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1); + } + for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) { + draw.draw(pass, &pipelines.instanced, &pipelines.instanced_flat, &uncounted); + } + } } impl Resources { - /// The layout of the depth map's bind group, which the lit pipelines' layout includes. + /// The layout of the maps' bind groups, which the lit pipelines' layout includes. pub fn layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { + let entry = |binding, sample_type| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, + count: None, + }; device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("sc_ao_depth"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Uint, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }], + label: Some("sc_ao_maps"), + entries: &[entry(0, wgpu::TextureSampleType::Uint), entry(1, wgpu::TextureSampleType::Float { filterable: false })], }) } - /// The prepass's pipelines and a 1 x 1 stand-in map, bound with `layout` ([`Resources::layout`]). + /// The passes' pipelines and 1 x 1 stand-in maps, bound with `layout` ([`Resources::layout`]). pub fn new( device: &wgpu::Device, layout: &wgpu::BindGroupLayout, @@ -71,57 +137,82 @@ impl Resources { reversed: bool, ) -> Self { let layout = layout.clone(); - let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + let prepass_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("sc_ao_prepass"), bind_group_layouts: &[Some(uniform)], immediate_size: 0, }); + let term_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_ao_term"), + bind_group_layouts: &[Some(uniform), None, Some(&layout)], + immediate_size: 0, + }); let built = [Some(tri_layout())]; let evaluated = [Some(planned_layout()), Some(color_layout())]; let placed = [Some(shared_layout()), Some(instance_layout())]; - let pipeline = |source: TriSource| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("sc_ao_prepass"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module, - entry_point: Some(source.entry()), - buffers: match source { - TriSource::Built => &built[..], - TriSource::Planned => &evaluated[..], - TriSource::Instanced | TriSource::InstancedFlat => &placed[..], + let target = |format| [Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::RED })]; + let opaque = |label, layout: &wgpu::PipelineLayout, fragment: &str, format, depth_write_enabled, compare| { + let pipeline = |source: TriSource| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { + module, + entry_point: Some(source.entry()), + buffers: match source { + TriSource::Built => &built[..], + TriSource::Planned => &evaluated[..], + TriSource::Instanced | TriSource::InstancedFlat => &placed[..], + }, + compilation_options: Default::default(), }, - compilation_options: Default::default(), - }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(true), - depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)), - stencil: Default::default(), - bias: Default::default(), - }), - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module, - entry_point: Some(&source.fragment("fs_ao_depth")), - targets: &[Some(wgpu::ColorTargetState { - format: wgpu::TextureFormat::R32Uint, - blend: None, - write_mask: wgpu::ColorWrites::RED, - })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }) + primitive: wgpu::PrimitiveState::default(), + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(depth_write_enabled), + depth_compare: Some(depth_compare(reversed, compare)), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(&source.fragment(fragment)), + targets: &target(format), + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + OpaquePipelines { + built: pipeline(TriSource::Built), + planned: pipeline(TriSource::Planned), + instanced: pipeline(TriSource::Instanced), + instanced_flat: pipeline(TriSource::InstancedFlat), + } }; - let planned_pipeline = pipeline(TriSource::Planned); - let instanced_pipeline = pipeline(TriSource::Instanced); - let instanced_flat_pipeline = pipeline(TriSource::InstancedFlat); - let pipeline = pipeline(TriSource::Built); - let (depth, values, bind) = texture(device, &layout, [1, 1]); - Self { layout, bind, depth, values, size: [1, 1], pipeline, planned_pipeline, instanced_pipeline, instanced_flat_pipeline } + let prepass = opaque("sc_ao_prepass", &prepass_layout, "fs_ao_depth", wgpu::TextureFormat::R32Uint, true, wgpu::CompareFunction::Less); + // The term only where the prepass's depth is, so each pixel's term is worked out once. + let term = opaque("sc_ao_term", &term_layout, "fs_ao_term", TERM_FORMAT, false, wgpu::CompareFunction::LessEqual); + let blur = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_ao_blur"), + layout: Some(&term_layout), + vertex: wgpu::VertexState { module, entry_point: Some("vs_ao_blur"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some("fs_ao_blur"), + targets: &target(TERM_FORMAT), + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + let maps = maps(device, &layout, [1, 1]); + Self { layout, maps, size: [1, 1], prepass, term, blur } } pub fn prepare( @@ -138,7 +229,7 @@ impl Resources { // Bound memory at large window sizes; normalized coordinates also handle downsampling. let size = target_size(enabled, size_px, device.limits().max_texture_dimension_2d); if size != self.size { - (self.depth, self.values, self.bind) = texture(device, &self.layout, size); + self.maps = maps(device, &self.layout, size); self.size = size; } if !enabled { @@ -147,7 +238,7 @@ impl Resources { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("sc_ao_prepass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &self.values, + view: &self.maps.values, depth_slice: None, resolve_target: None, ops: wgpu::Operations { @@ -156,7 +247,7 @@ impl Resources { }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth, + view: &self.maps.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(far_depth(reversed)), store: wgpu::StoreOp::Store }), stencil_ops: None, }), @@ -164,34 +255,35 @@ impl Resources { occlusion_query_set: None, multiview_mask: None, }); - for (batch, bind) in batches.into_iter().zip(binds) { - pass.set_bind_group(0, bind, &[]); - pass.set_pipeline(&self.pipeline); - if let Some(tris) = &batch.tris { - for (buffer, count) in &tris.parts { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(0..*count, 0..1); - } - } - // The depth prepass is left out of the performance overlay's counts, as before. - let uncounted = super::Tally::default(); - // The blocks' opaque triangles, for the same depth. - for key in &batch.block_order { - if let Some(block) = batch.blocks.get(key) { - block.draw(&mut pass, super::TriClass::Opaque, &uncounted); - } - } - pass.set_pipeline(&self.planned_pipeline); - for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) { - pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..)); - pass.set_vertex_buffer(1, draw.colors.slice(..)); - pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1); - } - for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) { - draw.draw(&mut pass, &self.instanced_pipeline, &self.instanced_flat_pipeline, &uncounted); - } - } + draw_opaque(&mut pass, &self.prepass, binds, batches); + drop(pass); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_ao_term"), + color_attachments: &[term_target(&self.maps.raw)], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.maps.depth, + depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Discard }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_bind_group(2, &self.maps.bind, &[]); + draw_opaque(&mut pass, &self.term, binds, batches); + drop(pass); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_ao_blur"), + color_attachments: &[term_target(&self.maps.smooth)], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.blur); + pass.set_bind_group(0, binds[0], &[]); + pass.set_bind_group(2, &self.maps.blur_bind, &[]); + pass.draw(0..3, 0..1); } } diff --git a/crates/gpu/src/view/clouds.rs b/crates/gpu/src/view/clouds.rs new file mode 100644 index 000000000..52c0f05a7 --- /dev/null +++ b/crates/gpu/src/view/clouds.rs @@ -0,0 +1,227 @@ +//! Point clouds: each point a round dot a few pixels across, facing the screen, depth-tested and +//! written like the model's faces. Every point is uploaded once, with the values it is coloured +//! and filtered by; how they are coloured and which are shown is a [`CloudStyle`] of a few +//! numbers the shaders read, so a new colour range or filter range draws again at once without +//! uploading anything. + +use std::sync::Arc; + +use super::{Batch, Tally, upload}; + +/// A point cloud as the GPU draws it. +#[derive(Clone)] +pub struct GpuCloud { + pub id: u64, + /// Changes when the records change (they are uploaded again). + pub version: u64, + /// [`DOT_SIZE`] bytes per point, written by [`cloud_dot`]. + pub dots: Arc>, + pub style: CloudStyle, +} + +/// How a cloud is coloured and which of its points are shown. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CloudStyle { + pub mode: ColorMode, + /// The ramp's range of values. + pub range: [f32; 2], + /// A point is shown where every filter keeps its filtered value. + pub filters: [CloudFilter; FILTERS], + /// A dot's size on screen, in pixels. + pub point_size: f32, +} + +/// Filters the GPU applies at once. +pub const FILTERS: usize = 4; + +/// The values a filter keeps. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum CloudFilter { + /// All of them. + #[default] + Off, + /// Those within a range, ends included. + Range([f32; 2]), + /// Whole values `offset + i` for each bit `i` set in `mask`. + Values { offset: i32, mask: u32 }, +} + +/// Where a point's colour comes from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ColorMode { + /// Its own colour ([`Dot::rgb`]). + #[default] + Own, + /// The ramp over [`CloudStyle::range`] at its value. + Ramp, + /// The palette at its whole value. + Palette, +} + +/// One point: where it is, the coloured value and the four filtered values, its own colour, and +/// which of the four filters and the value it has (bits 0 to 3, and 4, of `has`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Dot { + pub at: [f32; 3], + pub value: f32, + pub filtered: [f32; FILTERS], + pub rgb: [u8; 3], + pub has: u8, +} + +/// Bytes per [`Dot`]. +pub const DOT_SIZE: usize = 36; + +/// Append a dot's record. +pub fn cloud_dot(out: &mut Vec, d: &Dot) { + for v in d.at.iter().chain([&d.value]).chain(&d.filtered) { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&d.rgb); + out.push(d.has); +} + +fn dot_layout() -> wgpu::VertexBufferLayout<'static> { + const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32, 2 => Float32x4, 3 => Unorm8x4]; + wgpu::VertexBufferLayout { array_stride: DOT_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } +} + +/// The uniform a cloud's style is written to, bytes: the colouring, then a `vec4` per filter. +const STYLE_SIZE: u64 = 16 + 16 * FILTERS as u64; + +fn style_bytes(s: &CloudStyle) -> [u8; STYLE_SIZE as usize] { + let mode = match s.mode { + ColorMode::Own => 0.0f32, + ColorMode::Ramp => 1.0, + ColorMode::Palette => 2.0, + }; + let mut words = vec![mode.to_bits(), s.point_size.to_bits(), s.range[0].to_bits(), s.range[1].to_bits()]; + for f in &s.filters { + // Kind, then a range's ends, or the first value and the mask of those kept. + words.extend(match *f { + CloudFilter::Off => [0.0f32.to_bits(), 0, 0, 0], + CloudFilter::Range([lo, hi]) => [1.0f32.to_bits(), lo.to_bits(), hi.to_bits(), 0], + CloudFilter::Values { offset, mask } => [2.0f32.to_bits(), (offset as f32).to_bits(), 0, mask], + }); + } + let mut out = [0u8; STYLE_SIZE as usize]; + for (o, w) in out.as_chunks_mut::<4>().0.iter_mut().zip(words) { + *o = w.to_le_bytes(); + } + out +} + +/// The pipeline that draws clouds' dots, and the layout of their styles. +pub(super) struct CloudPipes { + layout: wgpu::BindGroupLayout, + dots: wgpu::RenderPipeline, +} + +impl CloudPipes { + pub(super) fn new( + device: &wgpu::Device, + module: &wgpu::ShaderModule, + viewport: &wgpu::BindGroupLayout, + target: super::GpuTarget, + depth: Option, + ) -> CloudPipes { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sc_cloud"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_cloud"), + bind_group_layouts: &[Some(viewport), Some(&layout)], + immediate_size: 0, + }); + let dots = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("vs_cloud_dot"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module, + entry_point: Some("vs_cloud_dot"), + buffers: &[Some(dot_layout())], + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, + depth_stencil: depth, + multisample: wgpu::MultisampleState { count: target.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some("fs_cloud"), + targets: &[Some(wgpu::ColorTargetState { format: target.format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + CloudPipes { layout, dots } + } +} + +/// A cloud on the GPU: its dots and its style's uniform. +struct Uploaded { + version: u64, + dots: Option, + style: wgpu::Buffer, + bind: wgpu::BindGroup, +} + +/// The clouds on the GPU, by id. +#[derive(Default)] +pub(super) struct CloudDraws(std::collections::HashMap); + +impl CloudDraws { + /// Upload new or changed clouds, drop removed ones, and write every style. + pub(super) fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pipes: &CloudPipes, clouds: &[GpuCloud]) { + self.0.retain(|id, _| clouds.iter().any(|c| c.id == *id)); + for c in clouds { + if self.0.get(&c.id).is_none_or(|u| u.version != c.version) { + let style = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sc_cloud_style"), + size: STYLE_SIZE, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_cloud_style"), + layout: &pipes.layout, + entries: &[wgpu::BindGroupEntry { binding: 3, resource: style.as_entire_binding() }], + }); + let dots = upload(device, "sc_cloud", &c.dots, DOT_SIZE); + self.0.insert(c.id, Uploaded { version: c.version, dots, style, bind }); + } + if let Some(u) = self.0.get(&c.id) { + queue.write_buffer(&u.style, 0, &style_bytes(&c.style)); + } + } + } + + pub(super) fn paint(&self, pass: &mut wgpu::RenderPass<'_>, pipes: &CloudPipes, tally: &Tally) { + for u in self.0.values() { + let Some(batch) = &u.dots else { continue }; + pass.set_bind_group(1, &u.bind, &[]); + pass.set_pipeline(&pipes.dots); + for (buffer, count) in &batch.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..6, 0..*count); + tally.triangles(6, *count); + } + } + } +} + +/// What a frame's clouds add to its picture's key. +pub(super) fn hash_clouds(clouds: &[GpuCloud], h: &mut impl std::hash::Hasher) { + use std::hash::Hash as _; + for c in clouds { + c.id.hash(h); + c.version.hash(h); + style_bytes(&c.style).hash(h); + } +} diff --git a/crates/gpu/src/view/msaa_check.rs b/crates/gpu/src/view/msaa_check.rs index 0afcc6d46..755541b98 100644 --- a/crates/gpu/src/view/msaa_check.rs +++ b/crates/gpu/src/view/msaa_check.rs @@ -113,7 +113,7 @@ impl Renderer { clip: [0.0; 4], cap: [0.0; 4], images: Vec::new(), - points: Vec::new(), + clouds: Vec::new(), analysis: [0.0; 8], analysis_colors: [0.0; 36], access: None, @@ -121,9 +121,11 @@ impl Renderer { eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], + hatch: Default::default(), }; let size = wgpu::Extent3d { width: SIZE, height: SIZE, depth_or_array_layers: 1 }; let color = device.create_texture(&wgpu::TextureDescriptor { diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rs index 03927f4ba..b3fee839d 100644 --- a/crates/gpu/tests/capture.rs +++ b/crates/gpu/tests/capture.rs @@ -5,8 +5,8 @@ //! (`SOLIDCRAFT_REQUIRE_GPU=1` makes that a failure). use serde_json::json; +use solidcore_record::Vec3; use solidcraft_engine::Session; -use solidcraft_engine::geom::Vec3; use solidcraft_engine::render::{Camera, Rgb, Scene, SceneLine}; use solidcraft_engine::view::{self, Guides, colors}; use solidcraft_gpu::GpuError; @@ -70,8 +70,8 @@ fn opengl_viewport_pipelines_render_a_model() { .unwrap(); let c = Capturer::new(&adapter, device, queue).unwrap(); let s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]); - let cam = view::home_camera(&s); - let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }), &cam, 160, 100).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }).unwrap(), &cam, 160, 100).unwrap(); let empty = c.rgba(&Default::default(), &cam, 160, 100).unwrap(); let changed = pixels(&img).zip(pixels(&empty)).filter(|(a, b)| a != b).count(); assert!(changed > 500, "the model covers only {changed} pixels"); @@ -87,8 +87,8 @@ fn pictures_show_appearances() { ("appearance.assign", json!({"bodies": ["Body2"], "color": [220, 60, 40]})), ("appearance.assign", json!({"faces": [[20, 15, 20]], "body": "Body1", "color": [40, 170, 80]})), ]); - let cam = view::home_camera(&s); - let img = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let img = c.rgba(&view::scene(&s, &cam).unwrap(), &cam, 200, 140).unwrap(); assert_eq!(img.len(), 200 * 140 * 4); let green = pixels(&img).filter(|p| p[1] > 120 && p[0] < 90 && p[2] < 110).count(); let red = pixels(&img).filter(|p| p[0] > 150 && p[1] < 90 && p[2] < 80).count(); @@ -102,8 +102,8 @@ fn pictures_show_appearances() { fn the_renderer_counts_what_it_draws() { let Some(c) = capturer() else { return }; let drawn = |s: &Session| { - let cam = view::home_camera(s); - let scene = view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }); + let cam = view::home_camera(s).unwrap(); + let scene = view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }).unwrap(); let triangles: usize = scene.meshes.iter().map(|m| m.mesh.triangles.len()).sum(); let (_, stats) = c.rgba_with_stats(&scene, &cam, 160, 100).unwrap(); (stats, triangles as u64) @@ -129,8 +129,8 @@ fn the_renderer_counts_what_it_draws() { fn pictures_drawn_at_once_each_count_their_own() { let Some(c) = capturer() else { return }; let scene = |s: &Session| { - let cam = view::home_camera(s); - (view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }), cam) + let cam = view::home_camera(s).unwrap(); + (view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }).unwrap(), cam) }; let empty = scene(&Session::default()); let solid = scene(&session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))])); @@ -152,8 +152,8 @@ fn pictures_drawn_at_once_each_count_their_own() { fn guides_change_the_picture() { let Some(c) = capturer() else { return }; let s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20, "corner": [10, -15, -10]}))]); - let cam = view::home_camera(&s); - let picture = |grid, axes| c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid, axes }), &cam, 160, 100).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let picture = |grid, axes| c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid, axes }).unwrap(), &cam, 160, 100).unwrap(); let (all, no_grid, no_axes, bare) = (picture(true, true), picture(false, true), picture(true, false), picture(false, false)); assert!(all != no_grid && all != no_axes && no_grid != bare && no_axes != bare); } @@ -163,8 +163,8 @@ fn guides_change_the_picture() { fn pictures_draw_silhouettes_on_curved_surfaces() { let Some(c) = capturer() else { return }; let s = session(&[("solid.sphere", json!({"diameter": 20}))]); - let cam = view::home_camera(&s); - let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }), &cam, 400, 400).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }).unwrap(), &cam, 400, 400).unwrap(); let dark = pixels(&img).filter(|p| p[0] < 90 && p[1] < 90 && p[2] < 95).count(); assert!(dark > 40, "silhouette pixels: {dark}"); } @@ -175,17 +175,19 @@ fn pictures_draw_silhouettes_on_curved_surfaces() { fn pictures_show_the_section_and_its_cap() { let Some(c) = capturer() else { return }; let mut s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]); - let cam = view::home_camera(&s); - let whole = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let whole = c.rgba(&view::scene(&s, &cam).unwrap(), &cam, 200, 140).unwrap(); // Cut away the front half (y < 15), so the iso camera looks into the cut. s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); - let cut = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + let cut = c.rgba(&view::scene(&s, &cam).unwrap(), &cam, 200, 140).unwrap(); let changed = pixels(&whole).zip(pixels(&cut)).filter(|(a, b)| a != b).count(); assert!(changed > 500, "{changed} pixels changed"); for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&s); + let mut cam = view::home_camera(&s).unwrap(); cam.fov = fov; - let mut sc = view::scene(&s, &cam); + let mut sc = view::scene(&s, &cam).unwrap(); + // The cap in the cap colour: a part's hatch colour is the one its name picks (#8529). + sc.part_hatch = None; // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); sc.lines.push(SceneLine { @@ -213,10 +215,10 @@ fn pictures_show_a_plain_cut_without_the_hatch() { ("solid.box", json!({"length": 40, "width": 30, "height": 20})), ("appearance.assign", json!({"bodies": ["Body1"], "color": [40, 160, 90]})), ]); - let cam = view::home_camera(&s); + let cam = view::home_camera(&s).unwrap(); let mut picture = |hatch: bool| { s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}, "hatch": hatch})).unwrap(); - c.rgba(&view::scene(&s, &cam), &cam, 300, 220).unwrap() + c.rgba(&view::scene(&s, &cam).unwrap(), &cam, 300, 220).unwrap() }; let solid = |img: &[u8]| pixels(img).filter(|p| p[..3].iter().zip([40u8, 160, 90]).all(|(a, b)| a.abs_diff(b) <= 3)).count(); let (hatched, plain) = (picture(true), picture(false)); @@ -248,9 +250,9 @@ fn a_body_behind_the_cut_does_not_colour_the_cap() { s.execute("inspect.section", &json!({"plane": {"origin": [0, 6, 0], "normal": [0, -1, 0]}, "hatch": hatch})).unwrap(); } for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&alone); + let mut cam = view::home_camera(&alone).unwrap(); cam.fov = fov; - let picture = |s: &Session| c.rgba(&view::scene(s, &cam), &cam, 300, 220).unwrap(); + let picture = |s: &Session| c.rgba(&view::scene(s, &cam).unwrap(), &cam, 300, 220).unwrap(); let (a, b) = (picture(&alone), picture(&with)); let differ = pixels(&a).zip(pixels(&b)).filter(|(p, q)| p.iter().zip(q).any(|(x, y)| x.abs_diff(*y) > 8)).count(); assert_eq!(differ, 0, "hatch {hatch}, fov {fov}: the inner body shows through the cap in {differ} pixels"); @@ -292,8 +294,9 @@ fn pictures_show_the_surface_analysis() { ("solid.box", json!({"length": 60, "width": 40, "height": 20})), ("solid.hole", json!({"position": [30, 20, 20], "diameter": 10, "depth": 20})), ]); - let cam = view::home_camera(&s); - let picture = |s: &Session| c.rgba(&view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }), &cam, 320, 200).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let picture = + |s: &Session| c.rgba(&view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }).unwrap(), &cam, 320, 200).unwrap(); let plain = picture(&s); s.execute("inspect.curvature_map", &json!({})).unwrap(); let curvature = picture(&s); @@ -319,6 +322,28 @@ fn pictures_show_the_surface_analysis() { assert!(reachable > 1000 && under > 1000, "accessibility: {reachable} reachable, {under} blocked pixels"); } +/// A flat face of a box keeps its zebra colour while the view turns a little at a time (#2153): +/// a horizontal face reflected straight ahead, on the edge between a black and a white stripe, +/// and rounding flipped it from one step to the next. +#[test] +fn zebra_on_flat_faces_holds_still_while_the_view_turns() { + let Some(c) = capturer() else { return }; + let mut s = session(&[("solid.box", json!({"length": 60, "width": 40, "height": 20}))]); + s.execute("inspect.zebra", &json!({})).unwrap(); + let home = view::home_camera(&s).unwrap(); + let whites: Vec = (0..24) + .map(|step| { + let mut cam = home; + cam.yaw += f64::from(step) * 0.11_f64.to_radians(); + let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }).unwrap(), &cam, 320, 200).unwrap(); + pixels(&img).filter(|p| p[0] > 225 && p[1] > 225 && p[2] > 225).count() + }) + .collect(); + let (least, most) = (whites.iter().min().copied().unwrap_or(0), whites.iter().max().copied().unwrap_or(0)); + assert!(most > 1000, "white stripes: {whites:?}"); + assert!((most - least) * 10 < most, "white pixels jump while the view turns by 0.11 degree steps: {whites:?}"); +} + fn colors_of(c: [[f32; 3]; 2]) -> [[u8; 3]; 2] { c.map(|rgb| rgb.map(|x| (x * 255.0).round() as u8)) } diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rs index 255536fb4..3a83305cb 100644 --- a/crates/gpu/tests/depth.rs +++ b/crates/gpu/tests/depth.rs @@ -7,10 +7,12 @@ //! makes that a failure). use serde_json::json; +use solidcore_record::Vec3; use solidcraft_engine::Session; -use solidcraft_engine::geom::{Mesh, Vec3}; +use solidcraft_engine::geom::Mesh; use solidcraft_engine::render::{Camera, Rgb, Scene, SceneLine, SceneMesh, StandardView}; use solidcraft_engine::view::{self, Guides}; +use solidcraft_geom::prelude::*; use solidcraft_gpu::GpuError; use solidcraft_gpu::capture::{self, Capturer}; use std::sync::{Arc, OnceLock}; @@ -59,7 +61,7 @@ fn session(script: &[(&str, serde_json::Value)]) -> Session { } fn picture(c: &Capturer, s: &Session, cam: &Camera, w: u32, h: u32) -> Vec { - c.rgba(&view::scene_with_guides(s, cam, None, Guides { grid: false, axes: false }), cam, w, h).unwrap() + c.rgba(&view::scene_with_guides(s, cam, None, Guides { grid: false, axes: false }).unwrap(), cam, w, h).unwrap() } fn differing(a: &[u8], b: &[u8]) -> usize { @@ -114,7 +116,7 @@ fn at_ten_metres_a_thin_label_is_whole_and_a_washer_behind_stays_hidden() { continue; } // The label's front face (y = -0.3), sampled inside its outline. - let radius = view::scene(&with, &cam).radius; + let radius = view::scene(&with, &cam).unwrap().radius; let mut grey = Vec::new(); for i in 1..20 { for j in 1..20 { @@ -294,12 +296,12 @@ fn an_edge_on_the_cut_face_draws_over_the_cap() { s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); for (mode, c) in capturers() { for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&s); + let mut cam = view::home_camera(&s).unwrap(); cam.fov = fov; let count = |on_top: bool| { // The session's section (`scene_with_guides` takes its own). The line is 2 µm on // the kept side: exactly on the plane, rounding cuts parts of it away with the rest. - let mut sc = view::scene(&s, &cam); + let mut sc = view::scene(&s, &cam).unwrap(); sc.lines.push(red_line(Vec3::new(5.0, 15.002, 10.0), Vec3::new(35.0, 15.002, 10.0), on_top)); pixels(&c.rgba(&sc, &cam, 300, 220).unwrap()).filter(|p| red(*p)).count() }; @@ -310,11 +312,65 @@ fn an_edge_on_the_cut_face_draws_over_the_cap() { } } +/// A cut body's cap covers the body it touches behind the cut. A block whose far face (y = 30) +/// lies on a larger plate's front face, cut at y = 15: through the cut the block's far wall and +/// the plate's face are at one depth. When the cap went to the nearer of the two by depth, the +/// plate showed through 2721 of its 4350 px here (an engine's sleeves in their bores, pins in +/// their bosses); counted by crossings, the cap is the same with the plate as without it. An +/// open body behind it (a box without its far face, whose near face alone the ray crosses) +/// takes nothing from the cap either: only closed bodies are counted. +#[test] +fn a_cap_covers_the_body_its_cut_body_touches() { + let block = ("solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "block"})); + let plate = ("solid.box", json!({"length": 70, "width": 10, "height": 50, "corner": [-15, 30, -15], "operation": "new", "body_name": "plate"})); + let shell = ("solid.box", json!({"length": 70, "width": 10, "height": 50, "corner": [-15, 35, -15], "operation": "new", "body_name": "shell"})); + let far_face = ("face.delete", json!({"faces": [[20, 45, 10]], "heal": false})); + let cut = ("inspect.section", json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})); + let alone = session(&[block.clone(), cut.clone()]); + let touching = session(&[block.clone(), plate, cut.clone()]); + let open = session(&[block, shell, far_face, cut]); + assert!(open.world_state().unwrap().body("shell").unwrap().body.is_surface()); + let (w, h) = (360, 280); + for (mode, c) in capturers() { + for (what, other) in [("the touching plate", &touching), ("an open shell behind", &open)] { + for fov in [0.0, 0.6] { + let mut cam = view::home_camera(&touching).unwrap(); + (cam.fov, cam.yaw, cam.pitch) = (fov, -0.3, 0.2); + let radius = view::scene(&touching, &cam).unwrap().radius; + let shot = |s: &Session| { + c.rgba(&Scene { grid: Vec::new(), lines: Vec::new(), radius, ..view::scene(s, &cam).unwrap() }, &cam, w, h).unwrap() + }; + let (a, b) = (shot(&alone), shot(other)); + // The cap on screen: the cut's rectangle (x 0..40, z 0..20 at y = 15), 2 px in. + let corner = |x: f64, z: f64| cam.to_screen(Vec3::new(x, 15.0, z), f64::from(w), f64::from(h), radius).map(|(x, y, _)| (x, y)); + let cap: Vec<(f64, f64)> = [(0.0, 0.0), (40.0, 0.0), (40.0, 20.0), (0.0, 20.0)].iter().filter_map(|(x, z)| corner(*x, *z)).collect(); + assert_eq!(cap.len(), 4, "fov {fov}: the cut is on screen"); + let turn = (0..4).map(|i| cap[i].0 * cap[(i + 1) % 4].1 - cap[(i + 1) % 4].0 * cap[i].1).sum::().signum(); + let inside = |x: f64, y: f64| { + (0..4).all(|i| { + let ((ax, ay), (bx, by)) = (cap[i], cap[(i + 1) % 4]); + ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) / (bx - ax).hypot(by - ay) * turn >= 2.0 + }) + }; + let (mut shown, mut all) = (0, 0); + for (i, (p, q)) in pixels(&a).zip(pixels(&b)).enumerate() { + if inside((i % w as usize) as f64 + 0.5, (i / w as usize) as f64 + 0.5) { + all += 1; + shown += usize::from(p.iter().zip(q).any(|(u, v)| u.abs_diff(v) > 24)); + } + } + assert!(all > 3000, "{mode}, fov {fov}: the cap ({all} px)"); + assert_eq!(shown, 0, "{mode} depth, fov {fov}: {what} shows through {shown} of {all} cap px"); + } + } + } +} + /// Pixels of the model's edges lying behind the section plane (recoloured red) that draw over /// the cap: the cap's pixels are where the picture without lines shows the hatch (warm, with /// warm pixels 3 px around, so the cut's outline doesn't count). fn edges_through_the_cap(c: &Capturer, s: &Session, cam: &Camera, (origin, normal): (Vec3, Vec3), (w, h): (u32, u32)) -> usize { - let mut sc = view::scene(s, cam); + let mut sc = view::scene(s, cam).unwrap(); let behind = |p: &Vec3| (*p - origin).dot(normal) < -0.5; let segments = sc .lines @@ -358,7 +414,7 @@ fn edges_of_a_pocket_behind_the_cut_stay_under_the_cap() { s.execute("inspect.section", &json!({"plane": {"origin": [0, -16, 0], "normal": [0, -1, 0]}})).unwrap(); for (mode, c) in capturers() { for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&s); + let mut cam = view::home_camera(&s).unwrap(); cam.fov = fov; let n = edges_through_the_cap(c, &s, &cam, plane, (360, 300)); assert!(n <= 2, "{mode} depth, fov {fov}: the pocket's edges show through the cap in {n} px"); @@ -384,7 +440,7 @@ fn edges_of_a_cut_hub_stay_under_the_cap_as_the_view_turns() { for fov in [0.0, 0.6] { let mut shown = Vec::new(); for i in 0..12 { - let mut cam = view::home_camera(&s); + let mut cam = view::home_camera(&s).unwrap(); (cam.fov, cam.yaw, cam.pitch) = (fov, -1.2 + 0.075 * f64::from(i), 0.35); shown.push(edges_through_the_cap(c, &s, &cam, plane, (900, 760))); } @@ -427,9 +483,9 @@ fn a_cut_hides_the_edges_behind_it() { let (w, h) = (400, 300); for (mode, c) in capturers() { for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&plain); + let mut cam = view::home_camera(&plain).unwrap(); cam.fov = fov; - let radius = view::scene(&plain, &cam).radius; + let radius = view::scene(&plain, &cam).unwrap().radius; // The cap on screen: the cut's rectangle, its outline left out (2 px in). let corner = |x: f64, z: f64| cam.to_screen(Vec3::new(x, -16.0, z), f64::from(w), f64::from(h), radius).map(|(x, y, _)| (x, y)); let cap: Vec<(f64, f64)> = [(-20.0, 0.0), (20.0, 0.0), (20.0, 30.0), (-20.0, 30.0)].iter().filter_map(|(x, z)| corner(*x, *z)).collect(); @@ -445,7 +501,7 @@ fn a_cut_hides_the_edges_behind_it() { }; let inside = |x: f64, y: f64| inside_by(x, y, 2.0); // Without the ground grid, whose extent follows the design. - let shot = |s: &Session| c.rgba(&Scene { grid: Vec::new(), ..view::scene(s, &cam) }, &cam, w, h).unwrap(); + let shot = |s: &Session| c.rgba(&Scene { grid: Vec::new(), ..view::scene(s, &cam).unwrap() }, &cam, w, h).unwrap(); let (a, b) = (shot(&plain), shot(&cut_through)); let (mut shown, mut all) = (0, 0); for (i, (p, q)) in pixels(&a).zip(pixels(&b)).enumerate() { @@ -471,3 +527,222 @@ fn a_cut_hides_the_edges_behind_it() { } } } + +/// The hatch a picture shows over the pixels `at`: the colour most of them have (the fill, +/// rounded to 8 levels a channel), and whether the darker lines through it run at 135 degrees +/// (down to the right on screen) rather than 45. +fn hatch_seen(img: &[u8], w: u32, at: &[(i64, i64)]) -> ([u8; 3], bool) { + let px = |x: i64, y: i64| { + let i = (y * i64::from(w) + x) as usize * 4; + img.get(i..i + 3).map(|p| [p[0], p[1], p[2]]) + }; + let mut counts = std::collections::HashMap::new(); + for (x, y) in at { + if let Some(p) = px(*x, *y) { + *counts.entry(p.map(|c| c / 8)).or_insert(0usize) += 1; + } + } + let fill = counts.into_iter().max_by_key(|(_, n)| *n).map_or([0; 3], |(c, _)| c); + let line = |x: i64, y: i64| { + px(x, y).is_some_and(|p| p.iter().map(|c| u32::from(*c)).sum::() * 8 < fill.iter().map(|c| u32::from(*c) * 8 + 4).sum::() * 7) + }; + // Along a 45 degree line (x + y the same) the pixels agree; across it they alternate. + let agree = |dy: i64| at.iter().filter(|(x, y)| line(*x, *y) && line(x + 1, y + dy)).count(); + (fill, agree(1) > agree(-1)) +} + +/// Section hatch by part: two blocks side by side, cut through both, touch along the cut, so they +/// get different hatches (in angle or colour) and the picture shows them apart; the next frame +/// and a plane moved a little keep each block's hatch. With one hatch for every body (the +/// preference's old behaviour) both caps are the cap colour at 45 degrees. +#[test] +fn touching_caps_are_hatched_apart_and_keep_their_hatch() { + let left = ("solid.box", json!({"length": 20, "width": 30, "height": 20, "body_name": "left"})); + let right = ("solid.box", json!({"length": 20, "width": 30, "height": 20, "corner": [20, 0, 0], "operation": "new", "body_name": "right"})); + let cut = |y: f64| ("inspect.section", json!({"plane": {"origin": [0, y, 0], "normal": [0, -1, 0]}})); + let s = session(&[left.clone(), right.clone(), cut(15.0)]); + let moved = session(&[left, right, cut(15.5)]); + let mut cam = view::home_camera(&s).unwrap(); + (cam.fov, cam.yaw, cam.pitch) = (0.0, -0.3, 0.2); + let hatches = |s: &Session| view::scene(s, &cam).unwrap().meshes.iter().map(|m| m.hatch).collect::>(); + let first = hatches(&s); + assert_eq!(first.len(), 2); + assert_ne!(first[0], first[1], "touching caps share a hatch"); + assert_eq!(hatches(&s), first, "the next frame keeps them"); + assert_eq!(hatches(&moved), first, "a plane moved a little keeps them"); + let (w, h) = (360, 280); + // Each block's cap on screen, 4 px in: x 0..20 and 20..40, z 0..20 at y = 15. + let radius = view::scene(&s, &cam).unwrap().radius; + let cap_pixels = |x0: f64| -> Vec<(i64, i64)> { + let corner = |x: f64, z: f64| cam.to_screen(Vec3::new(x, 15.0, z), f64::from(w), f64::from(h), radius).map(|(x, y, _)| (x, y)); + let q: Vec<(f64, f64)> = [(x0, 0.0), (x0 + 20.0, 0.0), (x0 + 20.0, 20.0), (x0, 20.0)].iter().filter_map(|(x, z)| corner(*x, *z)).collect(); + assert_eq!(q.len(), 4, "the cut is on screen"); + let turn = (0..4).map(|i| q[i].0 * q[(i + 1) % 4].1 - q[(i + 1) % 4].0 * q[i].1).sum::().signum(); + let inside = |x: f64, y: f64| { + (0..4).all(|i| { + let ((ax, ay), (bx, by)) = (q[i], q[(i + 1) % 4]); + ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) / (bx - ax).hypot(by - ay) * turn >= 4.0 + }) + }; + (0..i64::from(h)).flat_map(|y| (0..i64::from(w)).map(move |x| (x, y))).filter(|(x, y)| inside(*x as f64 + 0.5, *y as f64 + 0.5)).collect() + }; + let (a, b) = (cap_pixels(0.0), cap_pixels(20.0)); + assert!(a.len() > 1500 && b.len() > 1500, "the caps ({} and {} px)", a.len(), b.len()); + for (mode, c) in capturers() { + let by_part = c.rgba(&Scene { grid: Vec::new(), ..view::scene(&s, &cam).unwrap() }, &cam, w, h).unwrap(); + let (la, lb) = (hatch_seen(&by_part, w, &a), hatch_seen(&by_part, w, &b)); + assert_ne!(la, lb, "{mode} depth: the touching caps look alike"); + let expect = |hatch: solidcraft_engine::render::hatch::Hatch| hatch.turned(); + assert_eq!((la.1, lb.1), (expect(first[0]), expect(first[1])), "{mode} depth: the caps' angles"); + let one = c.rgba(&Scene { grid: Vec::new(), part_hatch: None, ..view::scene(&s, &cam).unwrap() }, &cam, w, h).unwrap(); + let (oa, ob) = (hatch_seen(&one, w, &a), hatch_seen(&one, w, &b)); + assert_eq!(oa, ob, "{mode} depth: one hatch for every body"); + assert!(!oa.1, "{mode} depth: one hatch runs at 45 degrees"); + } +} + +/// A 40 × 20 × 30 mm box centred on the origin, a flat-shaded face per side, and its 12 edges +/// with the outward normals of the two faces beside each. +fn shaded_box() -> (Mesh, Vec<(Vec3, Vec3, [Vec3; 2])>) { + let h = Vec3::new(20.0, 10.0, 15.0); + let corner = |i: usize| Vec3::new(if i & 1 == 0 { -h.x } else { h.x }, if i & 2 == 0 { -h.y } else { h.y }, if i & 4 == 0 { -h.z } else { h.z }); + // Each side: its normal and its corners, counter-clockwise seen from outside. + let sides = [ + (Vec3::new(-1.0, 0.0, 0.0), [0, 4, 6, 2]), + (Vec3::new(1.0, 0.0, 0.0), [1, 3, 7, 5]), + (Vec3::new(0.0, -1.0, 0.0), [0, 1, 5, 4]), + (Vec3::new(0.0, 1.0, 0.0), [2, 6, 7, 3]), + (Vec3::new(0.0, 0.0, -1.0), [0, 2, 3, 1]), + (Vec3::new(0.0, 0.0, 1.0), [4, 5, 7, 6]), + ]; + let mut mesh = Mesh::default(); + for (f, (n, c)) in sides.iter().enumerate() { + let base = mesh.positions.len() as u32; + mesh.positions.extend(c.iter().map(|i| corner(*i))); + mesh.normals.extend([*n; 4]); + mesh.triangles.extend([[base, base + 1, base + 2], [base, base + 2, base + 3]]); + mesh.tri_face.extend([f as u32; 2]); + } + let mut edges = Vec::new(); + for (i, (n, c)) in sides.iter().enumerate() { + for k in 0..4 { + let (a, b) = (c[k], c[(k + 1) % 4]); + // Each edge once: from the side that runs it from the lower corner. + if a > b { + continue; + } + let other = sides.iter().enumerate().find(|(j, (_, d))| *j != i && (0..4).any(|m| d[m] == b && d[(m + 1) % 4] == a)); + if let Some((_, (m, _))) = other { + edges.push((corner(a), corner(b), [*n, *m])); + } + } + } + (mesh, edges) +} + +/// The shaded-with-hidden-edges style: every edge drawn depth-tested and, in a light colour, +/// where the model hides it (`GpuScene::hidden_line`). A box turned so one side is seen almost +/// edge on (yaw 1.565): the side is under a pixel wide, so the edges along it lie within a pixel +/// of the nearer face beside it, which hides part of their width. Their hidden copy shows nowhere: +/// drawn after the visible edges, it covered the visible edge of that nearer face with a light +/// line along some 100 px. The box's back edges, which are hidden, still show. +#[test] +fn a_visible_edge_beside_a_face_seen_edge_on_has_no_hidden_copy() { + let (mesh, edges) = shaded_box(); + let (w, h) = (400, 300); + for (mode, c) in capturers() { + for fov in [0.0, 0.6] { + for yaw in [1.565_f64, 0.35] { + let cam = Camera { yaw, distance: 120.0, fov, ..Default::default() }; + let toward = |p: Vec3| if fov > 0.0 { cam.eye() - p } else { cam.back() }; + let back = |(a, b, n): &(Vec3, Vec3, [Vec3; 2])| n.iter().all(|n| n.dot(toward((*a + *b) * 0.5)) < 0.0); + let lines = edges + .iter() + .map(|(a, b, _)| SceneLine { points: vec![*a, *b], color: Rgb(20, 20, 20), alpha: 1.0, width: 1.3, on_top: false }) + .collect(); + let scene = + Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh.clone()), Rgb(160, 165, 175))], lines, radius: 40.0, ..Default::default() }; + let hidden = |keep: &dyn Fn(&(Vec3, Vec3, [Vec3; 2])) -> bool| { + let mut sc = solidcraft_gpu::view::GpuScene::default(); + let col = sc.color([0, 255, 0, 255]); + for e in edges.iter().filter(|e| keep(e)) { + sc.hidden_line(e.0.to_f32(), e.1.to_f32(), col, 1.0); + } + c.rgba_highlighted(&scene, Some(sc), &cam, w, h).unwrap() + }; + let green = |p: [u8; 4]| p[1] > 150 && p[0] < 120 && p[2] < 120; + let (all, back_only, none) = (hidden(&|_| true), hidden(&back), hidden(&|_| false)); + let doubled = differing(&all, &back_only); + assert_eq!(doubled, 0, "{mode} depth, fov {fov}, yaw {yaw}: a visible edge's hidden copy shows in {doubled} px"); + let behind = pixels(&back_only).filter(|p| green(*p)).count(); + assert!(behind > 100, "{mode} depth, fov {fov}, yaw {yaw}: the back edges show in {behind} px"); + assert_eq!(pixels(&none).filter(|p| green(*p)).count(), 0); + } + } + } +} + +/// #9407: a shaft in a bore it fits exactly, cut along its axis. Seen through the hub's cut, the +/// bore's wall (a back face: the hub's cap) and the shaft's side (a front face) are the same +/// cylinder, each faceted its own way, so neither is always in front: the shaft's side showed +/// through the hub's cap in streaks along the axis, changing as the view turned. The hub's cap is +/// the same as without the shaft, from several directions, in orthographic and perspective. +#[test] +fn a_shaft_in_its_bore_leaves_the_hubs_cap_whole() { + let hub = [ + ("solid.cylinder", json!({"radius": 20, "height": 40, "body_name": "Hub"})), + ("solid.cylinder", json!({"radius": 8, "height": 40, "operation": "cut"})), + ]; + let shaft = ("solid.cylinder", json!({"radius": 8, "height": 60, "base": [0, 0, -10], "body_name": "Shaft", "operation": "new"})); + let cut = ("inspect.section", json!({"plane": {"origin": [0, 0, 0], "normal": [0, -1, 0]}})); + let alone = session(&[&hub[..], std::slice::from_ref(&cut)].concat()); + let fitted = session(&[&hub[..], &[shaft, cut]].concat()); + let (w, h) = (480, 400); + for (mode, c) in capturers() { + for fov in [0.0, 0.6] { + let mut shown = Vec::new(); + for i in 0..6 { + let mut cam = view::home_camera(&fitted).unwrap(); + (cam.fov, cam.yaw, cam.pitch) = (fov, -1.1 + 0.3 * f64::from(i), 0.3); + let with = view::scene(&fitted, &cam).unwrap(); + let radius = with.radius; + // The hub alone, framed as the design with the shaft. + let without = Scene { radius, ..view::scene(&alone, &cam).unwrap() }; + let shot = |sc: Scene| c.rgba(&Scene { grid: Vec::new(), ..sc }, &cam, w, h).unwrap(); + let (a, b) = (shot(without), shot(with)); + // The hub's cut on screen: a rectangle each side of the bore, its outline left out. + let rects: Vec> = [(8.0, 20.0), (-20.0, -8.0)] + .iter() + .map(|(x0, x1)| { + [(*x0, 0.0), (*x1, 0.0), (*x1, 40.0), (*x0, 40.0)] + .iter() + .filter_map(|(x, z)| cam.to_screen(Vec3::new(*x, 0.0, *z), f64::from(w), f64::from(h), radius).map(|(x, y, _)| (x, y))) + .collect() + }) + .collect(); + let inside = |x: f64, y: f64| { + rects.iter().any(|q| { + q.len() == 4 && { + let turn = (0..4).map(|i| q[i].0 * q[(i + 1) % 4].1 - q[(i + 1) % 4].0 * q[i].1).sum::().signum(); + (0..4).all(|i| { + let ((ax, ay), (bx, by)) = (q[i], q[(i + 1) % 4]); + ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) / (bx - ax).hypot(by - ay) * turn >= 2.0 + }) + } + }) + }; + let (mut differ, mut all) = (0, 0); + for (i, (p, q)) in pixels(&a).zip(pixels(&b)).enumerate() { + if inside((i % w as usize) as f64 + 0.5, (i / w as usize) as f64 + 0.5) { + all += 1; + differ += usize::from(p.iter().zip(q).any(|(u, v)| u.abs_diff(v) > 24)); + } + } + assert!(all > 3000, "{mode}, fov {fov}, view {i}: the hub's cap ({all} px)"); + shown.push(differ); + } + let total: usize = shown.iter().sum(); + assert!(total <= 12, "{mode} depth, fov {fov}: the shaft shows through the hub's cap, px per view {shown:?}"); + } + } +} diff --git a/crates/gpu/tests/thin_lines.rs b/crates/gpu/tests/thin_lines.rs index e9b6583f2..9ec5e4bed 100644 --- a/crates/gpu/tests/thin_lines.rs +++ b/crates/gpu/tests/thin_lines.rs @@ -3,7 +3,7 @@ //! falls between two rows, so such lines came and went as the view zoomed. Skipped, with the //! reason printed, without a GPU adapter (`SOLIDCRAFT_REQUIRE_GPU=1` makes that a failure). -use solidcraft_engine::geom::Vec3; +use solidcore_record::Vec3; use solidcraft_engine::render::{Camera, Rgb, Scene, SceneLine, StandardView}; use solidcraft_gpu::GpuError; use solidcraft_gpu::capture::Capturer; diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 5ba521aca..1e2fc5bb2 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -13,9 +13,11 @@ workspace = true trust-unknown-source = [] [dependencies] +solidcore-record = { workspace = true } solidcraft-geom = { workspace = true } solidcraft-kernel = { workspace = true } solidcraft-doc = { workspace = true } +solidcraft-profile = { workspace = true } thiserror = { workspace = true } log = { workspace = true } zip = { workspace = true } @@ -34,6 +36,10 @@ cadmpeg-registry = { workspace = true } png = { workspace = true } tiny-skia = { workspace = true } +# The model cache's key (build.rs). +[build-dependencies] +sha2 = { workspace = true } + # A plain fsync where a network share refuses Apple's full flush (src/safe_write.rs); already in # the tree through tempfile. [target.'cfg(target_vendor = "apple")'.dependencies] @@ -45,3 +51,4 @@ gethostname = { workspace = true } [dev-dependencies] solidcraft-sketch = { workspace = true } +solidcraft-testkit = { workspace = true } diff --git a/crates/io/build.rs b/crates/io/build.rs index 45c77eed4..8174edbc5 100644 --- a/crates/io/build.rs +++ b/crates/io/build.rs @@ -1,20 +1,89 @@ -//! The commit the model cache is keyed by (`SOLIDCRAFT_SOURCE_COMMIT`): a cache is only the -//! result of evaluating its design when the same source computed it. "unknown" without git (a -//! source tarball), which never trusts a cache. +//! What the model cache is keyed by. `SOLIDCRAFT_EVALUATION_SOURCE`: the digest of the committed +//! source a design's model is computed from: the `doc` crate and every workspace crate it is +//! built from, the patched dependencies, the locked versions of all others, the workspace's build +//! settings and the cache's own reader. A cache is only the result of evaluating its design when +//! that source computed it, and an update that changed none of it (only the interface, the +//! commands or the other file formats, or the version number) computes the same model. +//! `SOLIDCRAFT_SOURCE_COMMIT`: the commit, recorded with the cache. Both are "unknown" without git +//! (a source tarball), which never trusts a cache. +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; use std::process::Command; -fn git(args: &[&str]) -> Option { - let out = Command::new("git").args(args).output().ok()?; - out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) +/// The workspace crates a design's model is computed from: `doc` and every workspace crate it +/// depends on (a test checks the list against their manifests). +const EVALUATION_CRATES: [&str; 9] = ["geom", "profile", "smlib", "step", "sketch", "kernel", "render", "derive", "doc"]; +/// The other files the saved model depends on, relative to the workspace root. +const EVALUATION_FILES: [&str; 3] = ["crates/io/build.rs", "crates/io/src/design/native_cache.rs", ".cargo/config.toml"]; +/// What under `vendor/` does not compute models: notes, and the interface's renderer. +const VENDOR_OUTSIDE: [&str; 2] = ["README.md", "egui-wgpu"]; + +fn git(root: &Path, args: &[&str]) -> Option { + let out = Command::new("git").arg("-C").arg(root).args(args).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned()).filter(|s| !s.trim().is_empty()) +} + +/// The committed `Cargo.lock` without the workspace's own packages: their version is the +/// application's, which every release changes; the source they are built from is hashed itself. +fn locked_dependencies(lock: &str) -> String { + lock.split("\n[[package]]").filter(|block| block.lines().any(|l| l.starts_with("source = "))).collect::>().join("\n[[package]]") +} + +/// The committed workspace `Cargo.toml` without the application's version. +fn workspace_settings(manifest: &str) -> String { + let mut section = ""; + let mut kept = Vec::new(); + for line in manifest.lines() { + if line.starts_with('[') { + section = line.trim(); + } + if !(section == "[workspace.package]" && line.trim_start().starts_with("version")) { + kept.push(line); + } + } + kept.join("\n") +} + +/// The digest of the committed source of the saved model (see the module notes), or `None` when +/// a part of it is not in the commit. +fn evaluation_source(root: &Path) -> Option { + let mut paths: Vec = EVALUATION_CRATES.iter().map(|c| format!("crates/{c}")).collect(); + paths.extend(EVALUATION_FILES.iter().map(|f| f.to_string())); + let specs: Vec = paths.iter().map(|p| format!("HEAD:./{p}")).collect(); + let mut args = vec!["rev-parse"]; + args.extend(specs.iter().map(String::as_str)); + let ids = git(root, &args)?; + if ids.lines().count() != paths.len() { + return None; + } + let mut digest = Sha256::new(); + for (path, id) in paths.iter().zip(ids.lines()) { + digest.update(format!("{path} {id}\n")); + } + // `vendor/`: one line per entry, " \t". + for entry in git(root, &["ls-tree", "HEAD", "./vendor/"])?.lines() { + let name = entry.rsplit(['\t', '/']).next().unwrap_or(entry); + if !VENDOR_OUTSIDE.contains(&name) { + digest.update(format!("vendor {entry}\n")); + } + } + digest.update(locked_dependencies(&git(root, &["show", "HEAD:./Cargo.lock"])?)); + digest.update(workspace_settings(&git(root, &["show", "HEAD:./Cargo.toml"])?)); + Some(digest.finalize().iter().map(|b| format!("{b:02x}")).collect()) } fn main() { - let commit = git(&["rev-parse", "HEAD"]).unwrap_or_else(|| "unknown".into()); + let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); + let root = crate_dir.join("../.."); + let commit = git(&crate_dir, &["rev-parse", "HEAD"]).map(|s| s.trim().to_string()).unwrap_or_else(|| "unknown".into()); println!("cargo:rustc-env=SOLIDCRAFT_SOURCE_COMMIT={commit}"); + let source = evaluation_source(&root).unwrap_or_else(|| "unknown".into()); + println!("cargo:rustc-env=SOLIDCRAFT_EVALUATION_SOURCE={source}"); + println!("cargo:rustc-env=SOLIDCRAFT_EVALUATION_CRATES={}", EVALUATION_CRATES.join(",")); // A new commit in this checkout (or worktree) restamps the build. - if let Some(dir) = git(&["rev-parse", "--git-dir"]) { - println!("cargo:rerun-if-changed={dir}/logs/HEAD"); + if let Some(dir) = git(&crate_dir, &["rev-parse", "--git-dir"]) { + println!("cargo:rerun-if-changed={}/logs/HEAD", dir.trim()); } println!("cargo:rerun-if-changed=build.rs"); } diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 17290bbd0..0111559e9 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -258,6 +258,7 @@ pub fn write_design_container_with_thumbnail( geometry: Option<&solidcraft_doc::SavedModel>, thumbnail: Option<&[u8]>, ) -> Result> { + let _span = solidcraft_profile::span("io", "write_design_container_with_thumbnail"); write_container(doc, compression, preview, geometry, thumbnail, max_design()) } @@ -739,6 +740,12 @@ impl DesignContainerReader { pub fn read_document(mut self) -> Result { read_document(&mut self.reader) } + + /// [`Self::geometry`] when [`Self::read_document`] follows: it validates the document. + fn geometry_before_document(&mut self) -> Option { + let document = self.reader.document(16 << 20).ok()?; + native_cache::read_geometry_before_document(&mut self.reader, &document).ok() + } } pub(super) fn read(bytes: &[u8]) -> Result { @@ -751,11 +758,12 @@ pub(super) fn read(bytes: &[u8]) -> Result { /// keeps one seekable file handle instead of buffering the complete archive. JSON continues /// through the normal migrations. pub fn read_design_file(path: &str, notify: Option) -> Result<(Document, Option)> { + let _span = solidcraft_profile::span("io", "read_design_file"); let mut source = open_regular_file(path)?; if is_container_source(&mut source)? { let mut reader = DesignContainerReader::new(source)?; // A design with its model opens without a picture first: the model is the session. - let model = reader.geometry(); + let model = reader.geometry_before_document(); if let Some(notify) = notify && model.is_none() && let Ok(preview) = read_preview(&mut reader.reader) @@ -866,7 +874,7 @@ fn read_document(reader: &mut PackageReader) -> Result solidcraft_doc::canvas::MAX_CANVAS_BYTES { return Err(invalid("canvas too large")); } - canvas.data = solidcraft_doc::canvas::base64_encode(bytes); + canvas.data = solidcraft_doc::canvas::base64_encode(bytes).into(); } for (index, cloud) in doc.point_clouds.iter_mut().enumerate() { if !cloud.points.is_empty() || !cloud.colors.is_empty() { @@ -997,7 +1005,7 @@ fn hydrate_hdr_resources(metadata: &mut Value, reader: &mut Pack #[cfg(test)] mod tests { use super::*; - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; struct CountingReader { source: Cursor>, @@ -1089,27 +1097,28 @@ mod tests { assert!(result.is_err_and(|e| e.to_string().contains("not a regular file"))); } - /// A saved model of one state holding `bodies` (no document evaluated it: enough for the - /// container, which stores whatever model it is given). + /// A saved model of one state holding `bodies`, none made by rounds (no document evaluated + /// it: enough for the container, which stores whatever model it is given). fn saved_model(bodies: Vec) -> solidcraft_doc::SavedModel { let records: Vec = (0..bodies.len()) .map(|i| json!({"name": format!("Body{i}"), "feature": 1, "component": 0, "key": "0000000000000001", "names": 0, "body": i})) .collect(); let state = json!({ "bodies": [[0, bodies.len()]], "sketches": [], "body_counter": 7, "sheets": [], "construct": [], "threads": [], - "sketch_keys": [], "blend_edges": {}, "fitted": {}, "tapered": {}, + "sketch_key_set": 0, "blend_edges": {}, "fitted": {}, "tapered": {}, }); solidcraft_doc::SavedModel { records: json!({ "features": [{"id": 1, "fingerprint": "0000000000000000", "ms": 0.0, "skipped": false, "state": 0}], "states": [state], "model_bodies": records, "names": [{"faces": [], "info": []}], "sketches": [], "sheets": [], + "rounds": [], "sketch_key_sets": [{"set": [], "drop": []}], }), bodies, } } fn native_geometry() -> solidcraft_doc::SavedModel { - saved_model(vec![solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap()]) + saved_model(vec![solidcraft_kernel::box_solid(solidcore_record::Vec3::ZERO, solidcore_record::Vec3::new(10., 20., 30.)).unwrap()]) } #[test] @@ -1119,6 +1128,38 @@ mod tests { assert!(native_cache::source_trusted("0123abc", false)); } + /// The model cache is keyed by the source of the crates a model is computed from (#7168): + /// each one `doc` is built from must be in it, or an update that changed one would open + /// designs with the model the code before it computed. + #[test] + fn the_cache_key_covers_every_crate_the_model_is_computed_from() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let read = |p: std::path::PathBuf| std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("{}: {e}", p.display())); + let workspace = read(root.join("Cargo.toml")); + // `solidcraft-geom = { path = "crates/geom" }`: a workspace crate's folder. + let folder = |name: &str| { + let prefix = format!("{name} = {{ path = \"crates/"); + workspace.lines().find_map(|l| l.strip_prefix(prefix.as_str())?.split('"').next().map(str::to_string)) + }; + let keyed: Vec<&str> = env!("SOLIDCRAFT_EVALUATION_CRATES").split(',').collect(); + let (mut todo, mut seen) = (vec!["doc".to_string()], BTreeSet::new()); + while let Some(krate) = todo.pop() { + if !seen.insert(krate.clone()) { + continue; + } + assert!(keyed.contains(&krate.as_str()), "crates/{krate} computes models: add it to EVALUATION_CRATES in crates/io/build.rs"); + let mut built_with = false; + for line in read(root.join("crates").join(&krate).join("Cargo.toml")).lines() { + if line.starts_with('[') { + built_with = line.ends_with("dependencies]") && !line.contains("dev-dependencies"); + } else if built_with && let Some(dir) = line.split(" = ").next().filter(|n| n.starts_with("solidcraft-")).and_then(folder) { + todo.push(dir); + } + } + } + assert_eq!(seen.len(), keyed.len(), "{seen:?} computed from, {keyed:?} keyed"); + } + #[test] fn native_cache_round_trip_and_preview_defer_original_sources() { let mut doc = Document::new("Native cache"); @@ -1142,7 +1183,7 @@ mod tests { #[test] fn model_cache_stores_repeated_parts_once_and_keeps_placed_copies() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let part = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); let share = solidcraft_kernel::DisplayShare::new(part.clone()); let mut bodies = vec![part.clone(), part.clone()]; @@ -1168,6 +1209,82 @@ mod tests { } } + /// The model cache's manifest, written straight from the model's records (not copied into a + /// JSON tree first), is byte for byte what writing it as a tree wrote: the same keys in the + /// same (sorted) order, the same numbers. + #[test] + fn the_model_cache_manifest_is_what_a_json_tree_writes() { + use solidcore_record::Vec3; + let part = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); + let share = solidcraft_kernel::DisplayShare::new(part.clone()); + let t = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [50.5, -0.25, 1e-7, 1.]]; + let moved = solidcraft_kernel::transform(&part, Vec3::new(50.5, -0.25, 1e-7), Vec3::ZERO, Vec3::Z, 0.).unwrap(); + let model = saved_model(vec![part.clone(), moved.with_display_share(&share, t)]); + let bytes = write_design_container_with_cache(&document(), DesignCompression::Fast, None, Some(&model)).unwrap(); + let manifest = &parts(&bytes)["cache/model.json"]; + let tree: Value = serde_json::from_slice(manifest).unwrap(); + assert_eq!(serde_json::to_vec(&tree).unwrap(), *manifest); + assert_eq!(tree["model"], model.records); + assert_eq!(tree.as_object().unwrap().len(), 12, "{:?}", tree.as_object().unwrap().keys().collect::>()); + } + + /// #9170: a mesh body (an imported STL) is kept in the model cache with the rest of the + /// model, as its own triangles, colour and paint. One mesh body left the whole cache out, so + /// opening the design evaluated every feature again. + #[test] + fn model_cache_keeps_mesh_bodies_with_the_rest_of_the_model() { + use solidcore_record::Vec3; + let corners = [Vec3::ZERO, Vec3::new(10., 0., 0.), Vec3::new(0., 10., 0.), Vec3::new(0., 0., 10.)]; + let tetra = solidcraft_kernel::mesh_body(&corners, &[[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]]) + .unwrap() + .with_color(Some([0.25, 0.5, 0.75])) + .with_paint(Some(solidcraft_kernel::Paint { opacity: 0.5, faces: Vec::new() })); + let block = solidcraft_kernel::box_solid(Vec3::new(40., 0., 0.), Vec3::new(60., 20., 20.)).unwrap(); + let model = saved_model(vec![block, tetra.clone()]); + let doc = document(); + let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&model)).unwrap(); + let entries = parts(&bytes); + let manifest: Value = serde_json::from_slice(&entries["cache/model.json"]).expect("the cache is written"); + assert_eq!(manifest["slices"].as_array().unwrap().len(), 2); + let read = DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().unwrap(); + assert_eq!(read.records, model.records); + assert_eq!(solidcraft_kernel::encode_native_body(&read.bodies[0]).unwrap(), solidcraft_kernel::encode_native_body(&model.bodies[0]).unwrap()); + let mesh = &read.bodies[1]; + assert_eq!(mesh.triangle_mesh(), tetra.triangle_mesh()); + assert_eq!((mesh.color(), mesh.paint()), (tetra.color(), tetra.paint())); + // The picture shown while opening draws the mesh body with its own triangles. + let preview = read_design_preview(&bytes).unwrap(); + assert_eq!(preview.meshes.len(), 2); + let (positions, triangles) = tetra.triangle_mesh().unwrap(); + assert_eq!(&*preview.meshes[1].positions, &positions.iter().flat_map(|p| [p.x, p.y, p.z]).collect::>()[..]); + assert_eq!(&*preview.meshes[1].triangles, &triangles.iter().flatten().copied().collect::>()[..]); + assert_eq!(preview.meshes[1].color, tetra.color()); + + // A changed or cut-short mesh slice (signed again, so it reaches the slice's reader) is a + // cache miss or another mesh, never a crash. + let range = |i: usize| manifest["slices"][1][i].as_u64().unwrap() as usize; + let (start, length) = (range(0), range(1)); + let payload = entries["cache/bodies.bin"].clone(); + assert_eq!(payload.len(), start + length, "the mesh slice is the last"); + let with = |payload: &[u8], length: usize| { + let mut entries = entries.clone(); + let mut manifest = manifest.clone(); + manifest["payload"] = json!(digest(payload)); + manifest["slices"][1][1] = json!(length); + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); + entries.insert("cache/bodies.bin".into(), payload.to_vec()); + package(&entries) + }; + assert!(read_design_geometry(&with(&payload, length)).is_some(), "signed again as it was, it reads"); + for n in (start..start + length).step_by(5) { + let mut changed = payload.clone(); + changed[n] ^= 0xff; + let changed = with(&changed, length); + assert!(std::panic::catch_unwind(|| (read_design_geometry(&changed), read_design_preview(&changed))).is_ok(), "byte {n}"); + assert!(read_design_geometry(&with(&payload[..n], n - start)).is_none(), "cut short at {n}"); + } + } + /// A model cache that does not fit the design file is left out: the save succeeds, and the /// design reads back as saved. #[test] @@ -1182,12 +1299,51 @@ mod tests { assert!(read_design_geometry(&bytes).is_some()); } + /// Opening a design with its model validates its document once, where the document is read + /// (`read_document`); reading the model first validated it a second time, a whole parse and + /// validation of a large design. A broken document still fails the open, as it did. + #[test] + fn opening_with_a_model_cache_validates_the_document_once() { + let validated = || native_cache::VALIDATED.with(std::cell::Cell::get); + let doc = document(); + let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&native_geometry())).unwrap(); + let before = validated(); + let alone = DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().unwrap(); + assert_eq!(validated(), before + 1, "the model alone checks its document"); + let mut reader = DesignContainerReader::new(Cursor::new(&bytes)).unwrap(); + let model = reader.geometry_before_document().unwrap(); + assert_eq!(validated(), before + 1, "opening leaves it to read_document"); + assert_eq!(reader.read_document().unwrap().to_json(), doc.to_json()); + assert_eq!(model.records, alone.records); + assert_eq!(model.bodies.len(), alone.bodies.len()); + + // A broken document whose cache is signed for it: the open fails with read_document's + // error, as when the model was read with the document validated (and so missed). + let entries = parts(&bytes); + let mut manifest: Value = serde_json::from_slice(&entries["cache/model.json"]).unwrap(); + let mut metadata: Value = serde_json::from_slice(&entries["document.json"]).unwrap(); + metadata["features"] = json!(5); + let truncated = entries["document.json"][..entries["document.json"].len() / 2].to_vec(); + for broken in [serde_json::to_vec(&metadata).unwrap(), truncated] { + let mut entries = entries.clone(); + manifest["document"] = json!(digest(&broken)); + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); + entries.insert("document.json".into(), broken); + let bytes = package(&entries); + assert!(DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().is_none()); + let expected = read(&bytes).unwrap_err().to_string(); + let mut reader = DesignContainerReader::new(Cursor::new(&bytes)).unwrap(); + let _ = reader.geometry_before_document(); + assert_eq!(reader.read_document().unwrap_err().to_string(), expected); + } + } + /// A saved model of four features (5, 50, 20 and 1 ms) whose states each hold the eight /// bodies all of them share and eight of their own (a body each feature replaces). No /// document evaluated it. fn timeline_model() -> solidcraft_doc::SavedModel { let bodies: Vec<_> = (0..40) - .map(|i| solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10. + f64::from(i), 20., 30.)).unwrap()) + .map(|i| solidcraft_kernel::box_solid(solidcore_record::Vec3::ZERO, solidcore_record::Vec3::new(10. + f64::from(i), 20., 30.)).unwrap()) .collect(); let records: Vec = (0..40) .map(|i| json!({"name": format!("Body{i}"), "feature": 1 + i / 8, "component": 0, "key": "0000000000000001", "names": 0, "body": i})) @@ -1198,7 +1354,7 @@ mod tests { let bodies = if i == 0 { json!([[0, 16]]) } else { json!([[0, 8], [8 * (i + 1), 8]]) }; json!({ "bodies": bodies, "sketches": [], "body_counter": 7, "sheets": [], "construct": [], "threads": [], - "sketch_keys": [], "blend_edges": {}, "fitted": {}, "tapered": {}, + "sketch_key_set": 0, "blend_edges": {}, "fitted": {}, "tapered": {}, }) }) .collect(); @@ -1208,7 +1364,10 @@ mod tests { .map(|(i, ms)| json!({"id": i + 1, "fingerprint": "0000000000000000", "ms": ms, "skipped": false, "state": i})) .collect(); solidcraft_doc::SavedModel { - records: json!({"features": features, "states": states, "model_bodies": records, "names": [{"faces": [], "info": []}], "sketches": [], "sheets": []}), + records: json!({ + "features": features, "states": states, "model_bodies": records, "names": [{"faces": [], "info": []}], "sketches": [], + "sheets": [], "validation": "each_feature", "rounds": [], "sketch_key_sets": [{"set": [], "drop": []}], + }), bodies, } } @@ -1234,6 +1393,7 @@ mod tests { let (states, kept, all, within) = thinned(40); assert_eq!((states, kept.len(), within), (vec![true; 4], 40, true)); assert_eq!(all.records, model.records); + assert_eq!(thinned(16).2.records["validation"], "each_feature", "the check mode it was evaluated under"); // The final state and the slowest other (50 ms): the shared bodies count once, else // these two states would need 32 bodies' room. for bodies in [24, 31] { @@ -1258,7 +1418,7 @@ mod tests { one.records["states"], json!([{ "bodies": [[0, 16]], "sketches": [], "body_counter": 7, "sheets": [], "construct": [], "threads": [], - "sketch_keys": [], "blend_edges": {}, "fitted": {}, "tapered": {}, + "sketch_key_set": 0, "blend_edges": {}, "fitted": {}, "tapered": {}, }]) ); } @@ -1324,7 +1484,7 @@ mod tests { let doc = document(); let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&native_geometry())).unwrap(); let original = parts(&bytes); - for key in ["format", "producer", "app", "build", "document", "payload"] { + for key in ["format", "producer", "evaluation", "kernel", "document", "payload"] { let mut entries = original.clone(); let mut manifest: Value = serde_json::from_slice(&entries["cache/model.json"]).unwrap(); manifest[key] = json!("unsupported-or-stale"); @@ -1334,6 +1494,24 @@ mod tests { assert!(read_design_preview(&bytes).is_none()); assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); } + // A cache of the format before sketch-key sets (/4) is a miss, and so are records of + // that shape (each state's keys inline) under the current format: never misread. + let manifest: Value = serde_json::from_slice(&original["cache/model.json"]).unwrap(); + let mut older = manifest.clone(); + older["format"] = json!("solidcraft-model-cache/4"); + let mut inline = manifest.clone(); + let model = inline["model"].as_object_mut().unwrap(); + model.remove("sketch_key_sets"); + let state = model["states"][0].as_object_mut().unwrap(); + state.remove("sketch_key_set"); + state.insert("sketch_keys".into(), json!([])); + for manifest in [older, inline] { + let mut entries = original.clone(); + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); + let bytes = package(&entries); + assert!(read_design_geometry(&bytes).is_none(), "{}", manifest["format"]); + assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); + } let mut entries = original; entries.get_mut("cache/bodies.bin").unwrap()[0] ^= 1; let bytes = package(&entries); @@ -1341,6 +1519,58 @@ mod tests { assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); } + /// #7168: a design saved by another version of SolidCraft (another version number and commit) + /// whose model was computed by the same evaluation source opens from its model cache, so an + /// update that changed only the interface or the commands does not evaluate every design again. + /// One computed by other evaluation source (a kernel or codec change) is evaluated again. + #[test] + fn a_cache_of_another_version_with_the_same_evaluation_source_is_read() { + let doc = document(); + let geometry = native_geometry(); + let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&geometry)).unwrap(); + let written = |entries: &BTreeMap>| serde_json::from_slice::(&entries["cache/model.json"]).unwrap(); + let original = parts(&bytes); + let evaluation = written(&original)["evaluation"].as_str().unwrap().to_string(); + assert!(evaluation.ends_with(&format!("/{}-{}", std::env::consts::ARCH, std::env::consts::OS)), "{evaluation}"); + let with = |changes: &[(&str, &str)]| { + let mut entries = original.clone(); + let mut manifest = written(&entries); + for (key, value) in changes { + manifest[*key] = json!(value); + } + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); + package(&entries) + }; + let older = with(&[("app", "0.0.1"), ("build", "0123456789abcdef0123456789abcdef01234567/other-platform")]); + let state = read_design_geometry(&older).expect("another version's cache of the same evaluation source"); + assert_eq!(state.bodies[0].body.face_count(), geometry.bodies[0].face_count()); + assert_eq!(crate::read_design(&older).unwrap().to_json(), doc.to_json()); + // The same version with other evaluation source, or on another platform, evaluates again. + let other_source = format!("{}/{}", "0".repeat(64), evaluation.rsplit('/').next().unwrap()); + for changed in [other_source.as_str(), &format!("{}/other-platform", evaluation.rsplit_once('/').unwrap().0)] { + let bytes = with(&[("evaluation", changed)]); + assert!(read_design_geometry(&bytes).is_none(), "{changed}"); + assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); + } + // An older build's cache (no evaluation source recorded) is evaluated again. + let mut entries = original.clone(); + let mut manifest = written(&entries); + manifest.as_object_mut().unwrap().remove("evaluation"); + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); + assert!(read_design_geometry(&package(&entries)).is_none()); + // The kernel that computed it is recorded, and a model the C++ kernel computed (an earlier + // build's) is evaluated again (a cache without one is a miss too). + assert_eq!(written(&original)["kernel"], json!(native_cache::KERNEL)); + let bytes = with(&[("kernel", "smlib")]); + assert!(read_design_geometry(&bytes).is_none(), "the C++ kernel's cache"); + assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); + let mut entries = original.clone(); + let mut manifest = written(&entries); + manifest.as_object_mut().unwrap().remove("kernel"); + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); + assert!(read_design_geometry(&package(&entries)).is_none()); + } + #[test] fn metadata_snapshot_survives_in_place_changes_after_preview() { use std::{cell::RefCell, rc::Rc}; @@ -1434,7 +1664,7 @@ mod tests { id, name: "Reference".into(), format: "png".into(), - data: solidcraft_doc::canvas::base64_encode(b"original image bytes"), + data: solidcraft_doc::canvas::base64_encode(b"original image bytes").into(), pixels: [1, 1], plane: solidcraft_doc::PlaneRef::Origin { name: "XY".into() }, center: Vec2::new(0.0, 0.0), @@ -1693,7 +1923,7 @@ mod tests { /// A valid STEP cube, padded with a comment to `length` bytes. `noisy` padding barely /// compresses; otherwise it is repetitive like the text of a real large export. fn padded_step(length: usize, noisy: bool) -> String { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let cube = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); let step = solidcraft_kernel::step_export(&[&cube], "padded").unwrap(); let (head, tail) = step.split_at(step.find("DATA;").unwrap() + 5); @@ -2092,7 +2322,7 @@ mod tests { #[test] #[ignore = "manual IO performance measurement"] fn benchmark_step_storage() { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let bodies: Vec<_> = (0..512) .map(|i| { let corner = Vec3::new((i % 32) as f64 * 12.0, (i / 32) as f64 * 12.0, 0.0); diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs index 9876d4f49..413300a54 100644 --- a/crates/io/src/design/native_cache.rs +++ b/crates/io/src/design/native_cache.rs @@ -1,12 +1,13 @@ //! The model cache: a design's evaluated timeline (every feature's result and the state after //! it, [`SavedModel`]), saved with it so opening need not evaluate it again. Bodies use -//! SolidCraft's exact native B-rep encoding; the key ties the cache to the exact document, build -//! and platform that computed it (docs/design-container.md). +//! SolidCraft's exact native B-rep encoding (a mesh body, its own triangles); the key ties the +//! cache to the exact document, and to the source, platform and geometry kernel that computed it +//! (docs/design-container.md). use super::*; use solidcraft_doc::{ModelState, SavedModel}; -const FORMAT: &str = "solidcraft-model-cache/4"; -const PRODUCER: &str = "solidcraft-truck-adapter/3"; +const FORMAT: &str = "solidcraft-model-cache/8"; +const PRODUCER: &str = "solidcraft-truck-adapter/4"; const MANIFEST: &str = "cache/model.json"; const PAYLOAD: &str = "cache/bodies.bin"; /// Body records (a placed copy is one record; its part is stored once). @@ -15,12 +16,24 @@ const MAX_RECORDS: usize = 200_000; const MAX_UNIQUE: usize = 100_000; const MAX_MANIFEST: usize = 32 << 20; -/// The build that computed a cache: the same source, compiled for the same platform, computes the -/// same numbers, so only its own caches are its results. +/// The build that wrote a cache (recorded; earlier builds read only their own caches). fn build() -> String { format!("{}/{}-{}", env!("SOLIDCRAFT_SOURCE_COMMIT"), std::env::consts::ARCH, std::env::consts::OS) } +/// What computed a cache: the same evaluation source (build.rs), compiled for the same platform, +/// computes the same numbers, so only caches of that source are its results. An update that left +/// that source as it was (only the interface or the commands changed) reads the caches of the +/// build before it; one that changed it (a kernel fix, the codec) evaluates the design again. +fn evaluation() -> String { + format!("{}/{}-{}", env!("SOLIDCRAFT_EVALUATION_SOURCE"), std::env::consts::ARCH, std::env::consts::OS) +} + +/// The geometry kernel that computed a cache. A cache another kernel wrote (the C++ SMLib, which +/// earlier builds could run on) is not this build's result: the kernels differ in tolerances and in +/// what they refuse, so a design opened from it evaluates again. +pub(super) const KERNEL: &str = "solidcore"; + /// A 4 x 4 matrix as its 16 numbers, in storage order. fn matrix(t: &[[f64; 4]; 4]) -> Vec { t.iter().flatten().copied().collect() @@ -107,6 +120,90 @@ fn same_topology(a: &solidcraft_kernel::Body, b: &solidcraft_kernel::Body) -> bo counts(a) == counts(b) } +/// The start of a mesh body's slice. A mesh body (an imported STL or 3MF) has no B-rep for the +/// native encoding: its slice is its triangles as they are, with its colour and paint, which is +/// all a mesh body holds. A B-rep slice starts with the native encoding's own tag. +const MESH_TAG: &[u8; 8] = b"SCMESH01"; +/// Most bytes of a mesh slice's header (its counts, colour and paint). +const MAX_MESH_HEADER: usize = 16 << 20; + +/// A mesh body's slice: the tag, the header's length (u32) and the header (JSON: the counts, +/// colour and paint), then each vertex as three f64 and each triangle as three u32, little-endian. +fn encode_mesh_body(body: &solidcraft_kernel::Body) -> Option> { + let (positions, triangles) = body.triangle_mesh()?; + let header = + serde_json::to_vec(&json!({"positions": positions.len(), "triangles": triangles.len(), "color": body.color(), "paint": body.paint()})) + .ok()?; + if header.len() > MAX_MESH_HEADER { + return None; + } + let size = positions.len().checked_mul(24)?.checked_add(triangles.len().checked_mul(12)?)?.checked_add(12 + header.len())?; + let mut out = Vec::with_capacity(size); + out.extend_from_slice(MESH_TAG); + out.extend_from_slice(&u32::try_from(header.len()).ok()?.to_le_bytes()); + out.extend_from_slice(&header); + for p in positions { + for x in [p.x, p.y, p.z] { + out.extend_from_slice(&x.to_le_bytes()); + } + } + for t in triangles { + for i in t { + out.extend_from_slice(&i.to_le_bytes()); + } + } + Some(out) +} + +/// The mesh body of a slice [`encode_mesh_body`] wrote; `None` for anything else. +fn decode_mesh_body(bytes: &[u8]) -> Option { + let rest = bytes.strip_prefix(MESH_TAG.as_slice())?; + let (length, rest) = rest.split_first_chunk::<4>()?; + let length = usize::try_from(u32::from_le_bytes(*length)).ok().filter(|n| *n <= MAX_MESH_HEADER)?; + let (header, data) = rest.split_at_checked(length)?; + let header: Value = serde_json::from_slice(header).ok()?; + let count = |key: &str| header.get(key).and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()); + let (vertices, triangles) = (count("positions")?, count("triangles")?); + if triangles > solidcraft_kernel::MAX_TRIANGLES { + return None; + } + // The counts must account for every byte, so nothing is allocated for data that is not there. + let split = vertices.checked_mul(24)?; + if split.checked_add(triangles.checked_mul(12)?)? != data.len() { + return None; + } + let (coordinates, corners) = data.split_at_checked(split)?; + let f64_at = |c: &[u8], at: usize| c.get(at..at + 8)?.try_into().ok().map(f64::from_le_bytes); + let u32_at = |c: &[u8], at: usize| c.get(at..at + 4)?.try_into().ok().map(u32::from_le_bytes); + let positions: Vec = coordinates + .as_chunks::<24>() + .0 + .iter() + .map(|c| Some(solidcore_record::Vec3::new(f64_at(c, 0)?, f64_at(c, 8)?, f64_at(c, 16)?))) + .collect::>()?; + let triangles: Vec<[u32; 3]> = + corners.as_chunks::<12>().0.iter().map(|c| Some([u32_at(c, 0)?, u32_at(c, 4)?, u32_at(c, 8)?])).collect::>()?; + let color: Option<[f32; 3]> = serde_json::from_value(header.get("color").cloned().unwrap_or(Value::Null)).ok()?; + let paint: Option = serde_json::from_value(header.get("paint").cloned().unwrap_or(Value::Null)).ok()?; + if color.is_some_and(|c| c.iter().any(|x| !x.is_finite())) { + return None; + } + Some(solidcraft_kernel::mesh_body(&positions, &triangles).ok()?.with_color(color).with_paint(paint)) +} + +/// A mesh body decoded is the one encoded: the same vertices, bit for bit, the same triangles, +/// colour and paint. +fn same_mesh(a: &solidcraft_kernel::Body, b: &solidcraft_kernel::Body) -> bool { + let (Some((pa, ta)), Some((pb, tb))) = (a.triangle_mesh(), b.triangle_mesh()) else { return false }; + let bits = |p: &[solidcore_record::Vec3]| p.iter().map(|v| [v.x.to_bits(), v.y.to_bits(), v.z.to_bits()]).collect::>(); + ta == tb && bits(pa) == bits(pb) && a.color() == b.color() && a.paint() == b.paint() +} + +/// A body of the cache's payload, mesh or B-rep by the slice's tag. +fn decode_cached_body(bytes: &[u8]) -> Option { + if bytes.starts_with(MESH_TAG) { decode_mesh_body(bytes) } else { solidcraft_kernel::decode_native_body(bytes).ok() } +} + impl Encoded { fn of(model: &SavedModel) -> Result { // What to encode: every body, and the part every placed copy shows. @@ -127,6 +224,10 @@ impl Encoded { // topology (two loose vertices more on a pattern copy cut by an extrude) would open as // another body. Then the model isn't kept, and opening the design evaluates it. let encoded = solidcraft_kernel::map_on_threads(&bodies, 16, |b| { + if b.is_mesh() { + let bytes = encode_mesh_body(b)?; + return decode_mesh_body(&bytes).is_some_and(|back| same_mesh(b, &back)).then_some(bytes); + } let bytes = solidcraft_kernel::encode_native_body(b).ok()?; let back = solidcraft_kernel::decode_native_body(&bytes).ok()?; same_topology(b, &back).then_some(bytes) @@ -193,18 +294,48 @@ impl Encoded { slices.push(json!([data.len(), bytes.len()])); data.extend_from_slice(bytes); } - let manifest = serde_json::to_vec(&json!({ - "format": FORMAT, "producer": PRODUCER, "app": env!("CARGO_PKG_VERSION"), "build": build(), - "document": digest(document), "payload": digest(&data), - "slices": slices, "shares": shares, "bodies": table, "model": records, - })) + let manifest = serde_json::to_vec(&Manifest { + app: env!("CARGO_PKG_VERSION"), + bodies: table, + build: build(), + document: digest(document), + evaluation: evaluation(), + format: FORMAT, + kernel: KERNEL, + model: records, + payload: digest(&data), + producer: PRODUCER, + shares, + slices, + }) .map_err(invalid)?; Ok((manifest, data)) } } -/// The final state of the model a design keeps, when this build computed it for exactly this -/// document. Any failure is a miss, never a document error. +/// A model cache's manifest as written: the model's records are written where they are, not +/// copied into a JSON tree first (copying a large model's records took as long as writing them, +/// and a cache too big for the file is written again for each try at fewer states). The fields +/// are in the order a JSON object keeps its keys (sorted), so the manifest is the one a tree +/// wrote, byte for byte. +#[derive(serde::Serialize)] +struct Manifest<'a> { + app: &'a str, + bodies: Vec, + build: String, + document: String, + evaluation: String, + format: &'a str, + kernel: &'a str, + model: &'a Value, + payload: String, + producer: &'a str, + shares: Vec, + slices: Vec, +} + +/// The final state of the model a design keeps, when this build's evaluation source computed it +/// for exactly this document. Any failure is a miss, never a document error. pub fn read_design_geometry(bytes: &[u8]) -> Option> { if bytes.len() > max_design() || !is_design_container(bytes) { return None; @@ -212,15 +343,23 @@ pub fn read_design_geometry(bytes: &[u8]) -> Option> DesignContainerReader::new(Cursor::new(bytes)).ok()?.geometry()?.final_state().ok() } -/// Whether `manifest` is a model cache this build wrote for `document`. +/// Whether `manifest` is a model cache of this build's evaluation source and kernel for `document`. +/// The application version and commit that wrote it are not asked: another version of the same +/// evaluation source computed the same model. fn current(manifest: &Value, document: &[u8]) -> bool { let is = |key: &str, value: &str| manifest.get(key).and_then(Value::as_str) == Some(value); is("format", FORMAT) && is("producer", PRODUCER) - && is("app", env!("CARGO_PKG_VERSION")) - && is("build", &build()) + && is("evaluation", &evaluation()) + && is("kernel", KERNEL) && is("document", &digest(document)) - && source_trusted(env!("SOLIDCRAFT_SOURCE_COMMIT"), cfg!(any(test, feature = "trust-unknown-source"))) + && source_trusted(env!("SOLIDCRAFT_EVALUATION_SOURCE"), cfg!(any(test, feature = "trust-unknown-source"))) +} + +#[cfg(test)] +thread_local! { + /// How often reading a model cache validated its document (tests count it). + pub(super) static VALIDATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// A build of unknown source (no git) never trusts a cache, unless `in_tests`: test builds @@ -231,6 +370,17 @@ pub(super) fn source_trusted(commit: &str, in_tests: bool) -> bool { } pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result { + read_geometry(reader, document, true) +} + +/// [`read_geometry_with`] for a reader whose document is read next: reading it runs the same +/// migrations and validation and fails the open when they fail, so validating it here as well +/// parsed and validated a large design twice (the model is dropped with the failed open). +pub(super) fn read_geometry_before_document(reader: &mut PackageReader, document: &[u8]) -> Result { + read_geometry(reader, document, false) +} + +fn read_geometry(reader: &mut PackageReader, document: &[u8], validate: bool) -> Result { let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?; if container.get("format").and_then(Value::as_str) != Some(VERSION) { return Err(invalid("container version")); @@ -240,7 +390,11 @@ pub(super) fn read_geometry_with(reader: &mut PackageReader, return Err(invalid("model cache key")); } // Validate the small parametric metadata before decoding any geometry. - Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; + if validate { + #[cfg(test)] + VALIDATED.with(|n| n.set(n.get() + 1)); + Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; + } let data = reader.limited_part(PAYLOAD, max_design())?; if manifest.get("payload").and_then(Value::as_str) != Some(digest(&data).as_str()) { return Err(invalid("model cache payload key")); @@ -264,7 +418,7 @@ pub(super) fn read_geometry_with(reader: &mut PackageReader, if end != data.len() { return Err(invalid("trailing cached data")); } - let decoded = solidcraft_kernel::map_on_threads(&parts, 16, |bytes| solidcraft_kernel::decode_native_body(bytes).ok()); + let decoded = solidcraft_kernel::map_on_threads(&parts, 16, |bytes| decode_cached_body(bytes)); let unique = decoded.into_iter().map(Option::flatten).collect::>>().ok_or_else(|| invalid("cached body"))?; let body = |v: Option<&Value>| unique.get(count(v)?).ok_or_else(|| invalid("cached body index")); let shares = manifest @@ -308,7 +462,7 @@ fn matrix_of(numbers: &[f64]) -> Result<[[f64; 4]; 4]> { pub(super) fn geometry_preview(document: &[u8], model: &SavedModel) -> Result { let doc = Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; - let world = solidcraft_doc::world_state(&doc, &*model.final_state()?); + let world = solidcraft_doc::world_state(&doc, &*model.final_state()?)?; let mut preview = DesignPreview::default(); let mut triangles = 0usize; let mut display_bytes = 0usize; @@ -322,16 +476,24 @@ pub(super) fn geometry_preview(document: &[u8], model: &SavedModel) -> Result own, + None => { + made = solidcraft_kernel::native_preview_mesh(&entry.body, detail, &mut work).map_err(invalid)?; + (made.positions.as_slice(), made.triangles.as_slice()) + } + }; + triangles = triangles.saturating_add(faces.len()); + display_bytes = display_bytes.saturating_add(positions.len().saturating_mul(24)).saturating_add(faces.len().saturating_mul(12)); if triangles > 1_000_000 || display_bytes > 128 << 20 { return Err(invalid("regenerated display budget")); } let displayed = MeshData { name: entry.name.clone(), - positions: mesh.positions.iter().flat_map(|p| [p.x, p.y, p.z]).collect(), - triangles: mesh.triangles.iter().flatten().copied().collect(), + positions: positions.iter().flat_map(|p| [p.x, p.y, p.z]).collect(), + triangles: faces.iter().flatten().copied().collect(), color: entry.body.color(), }; validate_mesh(&displayed)?; diff --git a/crates/io/src/design_lock.rs b/crates/io/src/design_lock.rs index 6a4daf361..f8376d308 100644 --- a/crates/io/src/design_lock.rs +++ b/crates/io/src/design_lock.rs @@ -15,6 +15,7 @@ //! The browser build keeps neither: it has no shared folders, and no clock in `std`. use serde::{Deserialize, Serialize}; +use std::io::Read; use std::path::{Path, PathBuf}; /// How often an open design's lock is written again. @@ -109,16 +110,29 @@ fn user_name() -> String { ["USER", "USERNAME", "LOGNAME"].iter().find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty())).unwrap_or_default() } -/// The lock next to the design at `path`, if there is a readable one. +/// The lock next to the design at `path`, if there is a readable one. Anything at the lock's path +/// but a regular file (a symbolic link, a device, a FIFO) is no lock and is not opened, and no +/// more than a lock's size is ever read. pub fn read(path: &Path) -> Option { if cfg!(target_arch = "wasm32") { return None; } let file = lock_path(path); - if std::fs::metadata(&file).ok()?.len() > MAX_LOCK_BYTES { + let meta = std::fs::symlink_metadata(&file).ok().filter(std::fs::Metadata::is_file)?; + if meta.len() > MAX_LOCK_BYTES { return None; } - serde_json::from_slice(&std::fs::read(&file).ok()?).ok() + let opened = std::fs::File::open(&file).ok()?; + // The path may have been swapped between the two calls; the handle decides. + if !opened.metadata().ok()?.is_file() { + return None; + } + let mut bytes = Vec::new(); + opened.take(MAX_LOCK_BYTES + 1).read_to_end(&mut bytes).ok()?; + if bytes.len() as u64 > MAX_LOCK_BYTES { + return None; + } + serde_json::from_slice(&bytes).ok() } /// Another app's fresh lock on the design at `path` at `now`: it is open elsewhere. @@ -126,10 +140,12 @@ pub fn held_elsewhere(path: &Path, now: u64) -> Option { read(path).filter(|l| !l.is_mine() && !l.is_stale(now)) } -/// Write `lock` next to the design at `path` (replacing whatever lock is there). +/// Write `lock` next to the design at `path`, replacing whatever lock is there. A symbolic link +/// at the lock's path is refused and never followed, unlike a save, which follows a link to where +/// the design really lives: the file a link there points to is not this app's to replace. pub fn write(path: &Path, lock: &Lock) -> std::io::Result<()> { let bytes = serde_json::to_vec_pretty(lock).map_err(std::io::Error::other)?; - crate::safe_write::write_atomic(&lock_path(path), &bytes, false) + crate::safe_write::write_atomic_no_follow(&lock_path(path), &bytes) } /// Remove this process's lock on the design at `path`; another app's lock is left alone. diff --git a/crates/io/src/dxf.rs b/crates/io/src/dxf.rs index 7defb594c..d04603529 100644 --- a/crates/io/src/dxf.rs +++ b/crates/io/src/dxf.rs @@ -5,9 +5,10 @@ //! arcs and points (free-form curves as polylines); the flat pattern's drawing, with ELLIPSE and SPLINE, is //! [`crate::write_dxf_drawing`]. +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use solidcraft_geom::{MAX_BEZIER_DEGREE, Vec2}; +use solidcore_record::{MAX_BEZIER_DEGREE, Vec2}; use crate::sketch2d::{Geom2, MAX_DRAWING_BYTES, MAX_ENTITIES, bulge_arc}; use crate::{IoError, Result}; diff --git a/crates/io/src/dxf_out.rs b/crates/io/src/dxf_out.rs index 7881672e6..56d12dbcd 100644 --- a/crates/io/src/dxf_out.rs +++ b/crates/io/src/dxf_out.rs @@ -4,16 +4,18 @@ //! Curves stay exact: a circle is a CIRCLE, a circular arc an ARC, a whole ellipse one ELLIPSE //! and a conic arc of weight below 1 an elliptical ELLIPSE arc; Béziers (TrueType glyph //! outlines, spline pieces) and the other conics are SPLINEs of their own degree. The file holds -//! what the entities refer to and what release 2000 needs to read them: the version, the -//! handle seed, the units and the extents; the linetype, layer and block-record tables; the -//! model and paper space blocks; handles, owners and the subclass markers of each entity; the -//! root dictionary. Layers can be dashed and a drawing can carry TEXT (for annotations). Group +//! what the entities refer to and what release 2000 needs to read them: the version, code page, +//! handle seed, units and extents; the (empty) CLASSES section; all nine symbol tables, with the +//! active viewport, the linetypes, layers, text style, the ACAD application id, the dimension +//! style and the block records; the model and paper space blocks; handles, owners and the +//! subclass markers of each entity; the root dictionary and its group dictionary. Layers can be dashed and a drawing can carry TEXT (for annotations). Group //! codes follow Autodesk's public DXF reference. +use solidcraft_geom::prelude::*; use std::f64::consts::TAU; use std::fmt::Write as _; -use solidcraft_geom::{Loop2, MAX_BEZIER_DEGREE, Seg2, Vec2}; +use solidcore_record::{Loop2, MAX_BEZIER_DEGREE, Seg2, Vec2}; use crate::{IoError, Result}; @@ -267,6 +269,11 @@ impl Out { self.num(c + 10, p.y); self.num(c + 20, 0.0); } + /// A 2D point: codes `c` and `c + 10`. + fn point2(&mut self, c: i32, p: Vec2) { + self.num(c, p.x); + self.num(c + 10, p.y); + } fn handle(&mut self) -> String { let h = format!("{:X}", self.next); self.next += 1; @@ -366,10 +373,48 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result< let (model, paper) = (o.handle(), o.handle()); let root = o.handle(); + // Release 2000 readers expect the CLASSES section, even empty, between HEADER and TABLES. + o.code(0, "SECTION"); + o.code(2, "CLASSES"); + o.code(0, "ENDSEC"); + + // All nine symbol tables, in the reference's order, even those with nothing to hold: a + // strict reader (AutoCAD among them, #9144) refuses a file that leaves one out. o.code(0, "SECTION"); o.code(2, "TABLES"); - // The three every drawing has, and DASHED, which the dashed layers name: dash and gap lengths - // (a gap is negative) after the pattern's total. + // The active viewport, looking down on the whole drawing so it opens zoomed to fit. + let t = o.table("VPORT", 1); + o.record("VPORT", "AcDbViewportTableRecord", &t); + o.code(2, "*Active"); + o.code(70, 0); + o.point2(10, Vec2::ZERO); + o.point2(11, Vec2::new(1.0, 1.0)); + o.point2(12, (lo + hi) * 0.5); + o.point2(13, Vec2::ZERO); + o.point2(14, Vec2::new(10.0, 10.0)); + o.point2(15, Vec2::new(10.0, 10.0)); + o.num(16, 0.0); + o.num(26, 0.0); + o.num(36, 1.0); + o.num(17, 0.0); + o.num(27, 0.0); + o.num(37, 0.0); + const ASPECT: f64 = 1.5; + let size = hi - lo; + let height = (size.y.max(size.x / ASPECT) * 1.1).max(1.0); + o.num(40, if height.is_finite() { height } else { 1.0 }); + o.num(41, ASPECT); + o.num(42, 50.0); + o.num(43, 0.0); + o.num(44, 0.0); + o.num(50, 0.0); + o.num(51, 0.0); + for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] { + o.code(code, value); + } + o.code(0, "ENDTAB"); + // The three linetypes every drawing has, and DASHED, which the dashed layers name: dash and + // gap lengths (a gap is negative) after the pattern's total. let mut linetypes: Vec<(&str, &str, &[f64])> = vec![ ("ByBlock", "", &[]), ("ByLayer", "", &[]), @@ -416,6 +461,29 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result< o.code(3, "txt"); o.code(4, ""); o.code(0, "ENDTAB"); + for name in ["VIEW", "UCS"] { + o.table(name, 0); + o.code(0, "ENDTAB"); + } + // The application id every drawing registers. + let t = o.table("APPID", 1); + o.record("APPID", "AcDbRegAppTableRecord", &t); + o.code(2, "ACAD"); + o.code(70, 0); + o.code(0, "ENDTAB"); + // The one dimension style, with the default settings. The table has a subclass of its own + // and its records keep their handle under 105, not 5. + let t = o.table("DIMSTYLE", 1); + o.code(100, "AcDbDimStyleTable"); + let h = o.handle(); + o.code(0, "DIMSTYLE"); + o.code(105, h); + o.code(330, &t); + o.code(100, "AcDbSymbolTableRecord"); + o.code(100, "AcDbDimStyleTableRecord"); + o.code(2, "Standard"); + o.code(70, 0); + o.code(0, "ENDTAB"); let t = o.table("BLOCK_RECORD", 2); for (h, name) in [(&model, "*Model_Space"), (&paper, "*Paper_Space")] { o.code(0, "BLOCK_RECORD"); @@ -535,11 +603,20 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result< o.code(0, "SECTION"); o.code(2, "OBJECTS"); + // The root dictionary, which must name the group dictionary (empty: no groups). + let groups = o.handle(); o.code(0, "DICTIONARY"); o.code(5, root.as_str()); o.code(330, 0); o.code(100, "AcDbDictionary"); o.code(281, 1); + o.code(3, "ACAD_GROUP"); + o.code(350, &groups); + o.code(0, "DICTIONARY"); + o.code(5, &groups); + o.code(330, &root); + o.code(100, "AcDbDictionary"); + o.code(281, 1); o.code(0, "ENDSEC"); o.code(0, "EOF"); @@ -548,6 +625,10 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result< head.code(2, "HEADER"); head.code(9, "$ACADVER"); head.code(1, "AC1015"); + // Every character in the file is ASCII (other letters are `\U+XXXX`), which this code page + // reads as itself. + head.code(9, "$DWGCODEPAGE"); + head.code(3, "ANSI_1252"); head.code(9, "$HANDSEED"); head.code(5, format!("{:X}", o.next)); head.code(9, "$INSUNITS"); @@ -683,7 +764,7 @@ mod tests { assert!(degree_2(&conic(2.0), Some(vec![1.0, 2.0, 1.0]))); assert!(degree_2(&conic(1.0 - 1e-9), Some(vec![1.0, 1.0 - 1e-9, 1.0]))); // A quintic piece: six control points and twelve knots. - let mut q = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL]; + let mut q = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; for (i, s) in q.iter_mut().enumerate() { *s = Vec2::new(i as f64, (i * i) as f64); } @@ -694,13 +775,13 @@ mod tests { #[test] fn a_bezier_is_a_spline_of_its_own_degree_over_all_its_control_points() { - let mut q = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL]; + let mut q = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; for (i, s) in q.iter_mut().enumerate() { *s = Vec2::new(i as f64, (i * i) as f64); } // Every degree a Bézier piece can have, up to a G4 blend's 9: n + 1 control points, all of // them, and 2(n + 1) clamped knots. - for n in 4..=solidcraft_geom::MAX_BEZIER_DEGREE as u8 { + for n in 4..=solidcore_record::MAX_BEZIER_DEGREE as u8 { let k = usize::from(n) + 1; let DxfShape::Spline { degree, knots, ctrl, weights } = seg_shape(&Seg2::Bezier { n, p: q }) else { panic!("degree {n}") }; assert_eq!((degree, knots.len(), weights), (n, 2 * k, None), "degree {n}"); @@ -795,7 +876,7 @@ mod tests { let Geom2::Spline { pts, control: true, degree: 3 } = &back[5] else { panic!("{:?}", back[5]) }; assert!(pts.iter().zip(&cubic).all(|(a, b)| a.dist(*b) < 1e-9) && pts.len() == 4); // A degree-9 Bézier (a G4 blend) comes back at its own degree over all ten points. - let mut q = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL]; + let mut q = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; for (i, s) in q.iter_mut().enumerate() { *s = Vec2::new(i as f64, (i % 3) as f64); } @@ -966,6 +1047,76 @@ mod tests { } } + #[test] + fn a_strict_reader_finds_every_section_table_and_the_group_dictionary() { + // #9144: AutoCAD refused the exported view. A release 2000 file has the CLASSES section, + // all nine symbol tables with their standard records, and a root dictionary naming + // ACAD_GROUP. + let ents = [ + DxfEntity { layer: "VISIBLE".into(), shape: DxfShape::Line(Vec2::new(0.0, 0.0), Vec2::new(30.0, 0.0)) }, + DxfEntity { layer: "VISIBLE".into(), shape: DxfShape::Circle { c: Vec2::new(15.0, 5.0), r: 5.0 } }, + ]; + let dxf = write_dxf_drawing(&[DxfLayer::new("VISIBLE", 7)], &ents).unwrap(); + let p = pairs(&dxf); + let sections: Vec<&str> = p.windows(2).filter(|w| w[0] == (0, "SECTION".into())).map(|w| w[1].1.as_str()).collect(); + assert_eq!(sections, ["HEADER", "CLASSES", "TABLES", "BLOCKS", "ENTITIES", "OBJECTS"]); + let tables: Vec<&str> = p.windows(2).filter(|w| w[0] == (0, "TABLE".into())).map(|w| w[1].1.as_str()).collect(); + assert_eq!(tables, ["VPORT", "LTYPE", "LAYER", "STYLE", "VIEW", "UCS", "APPID", "DIMSTYLE", "BLOCK_RECORD"]); + // Each table says how many records it holds, and holds them. + for table in tables { + let at = p.iter().position(|(c, v)| (*c, v.as_str()) == (2, table)).unwrap(); + let count: usize = p[at..].iter().find(|(c, _)| *c == 70).unwrap().1.parse().unwrap(); + assert_eq!(table_records(&p, table).len(), count, "{table}"); + } + assert_eq!(table_records(&p, "APPID").iter().map(|r| field(r, 2)).collect::>(), ["ACAD"]); + let dimstyles = table_records(&p, "DIMSTYLE"); + // (The DIMSTYLE table's own subclass comes before its record.) + let [standard] = dimstyles.as_slice() else { panic!("{dimstyles:?}") }; + assert_eq!(field(standard, 2), "Standard"); + assert!(!field(standard, 105).is_empty() && field(standard, 5).is_empty(), "{standard:?}"); + // The active viewport looks down on the middle of the drawing (0, 0)..(30, 10), all of it in view. + let vports = table_records(&p, "VPORT"); + let [active] = vports.as_slice() else { panic!("{vports:?}") }; + assert_eq!(field(active, 2), "*Active"); + assert_eq!((field(active, 12), field(active, 22), field(active, 36)), ("15.0", "5.0", "1.0")); + let (height, aspect): (f64, f64) = (field(active, 40).parse().unwrap(), field(active, 41).parse().unwrap()); + assert!(height >= 10.0 && height * aspect >= 30.0, "{height} {aspect}"); + // The root dictionary names the group dictionary, which it owns. + let objects = p.iter().position(|(c, v)| (*c, v.as_str()) == (2, "OBJECTS")).unwrap(); + let mut dictionaries: Vec> = Vec::new(); + for (c, v) in p[objects + 1..].iter().take_while(|(c, v)| (*c, v.as_str()) != (0, "ENDSEC")) { + match c { + 0 => dictionaries.push(Vec::new()), + _ => dictionaries.last_mut().unwrap().push((*c, v.clone())), + } + } + let [root, groups] = dictionaries.as_slice() else { panic!("{dictionaries:?}") }; + assert_eq!((field(root, 330), field(root, 3)), ("0", "ACAD_GROUP")); + assert_eq!(field(root, 350), field(groups, 5)); + assert_eq!(field(groups, 330), field(root, 5)); + // Handles, under 5 and the DIMSTYLE's 105, are unique and below the seed. + let seed_at = p.iter().position(|(c, v)| (*c, v.as_str()) == (9, "$HANDSEED")).unwrap() + 1; + let seed = u64::from_str_radix(&p[seed_at].1, 16).unwrap(); + let mut handles: Vec = p + .iter() + .enumerate() + .filter(|(i, (c, _))| *i != seed_at && (*c == 5 || *c == 105)) + .map(|(_, (_, v))| u64::from_str_radix(v, 16).unwrap()) + .collect(); + let n = handles.len(); + handles.sort_unstable(); + handles.dedup(); + assert_eq!(handles.len(), n); + assert!(handles.iter().all(|h| *h < seed)); + // Every owner (330) is 0 or a handle in the file. + for (_, v) in p.iter().filter(|(c, _)| *c == 330) { + let h = u64::from_str_radix(v, 16).unwrap(); + assert!(h == 0 || handles.binary_search(&h).is_ok(), "owner {v}"); + } + // SolidCraft's own reader still reads it. + assert_eq!(read_dxf(&dxf).unwrap().len(), 2); + } + #[test] fn the_extents_hold_the_text() { // Five letters of 3 mm, turned to read upwards: 0.8 × 3 × 5 = 12 mm long around y = 12, and diff --git a/crates/io/src/gltf_in.rs b/crates/io/src/gltf_in.rs index 1b6bd32c8..a822747b2 100644 --- a/crates/io/src/gltf_in.rs +++ b/crates/io/src/gltf_in.rs @@ -17,14 +17,15 @@ //! sRGB here), alpha (blended materials only) and metallic/roughness factors give the body's //! look. Textures are not read. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use gltf::accessor::{DataType, Dimensions}; use gltf::mesh::Mode; +use solidcore_record::Vec3; use solidcraft_doc::appearance::Look; use solidcraft_doc::{Mat, MeshData, mat_mul}; -use solidcraft_geom::Vec3; use crate::{IoError, MAX_3MF_BYTES, MeshFeature, Result}; diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 5ebd90fd0..02126b3a0 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -27,6 +27,7 @@ mod native_cad; pub use native_cad::{NATIVE_CAD_EXTS, is_native_cad_path, native_cad_to_step}; pub mod paper; mod ply; +mod ply_complex; pub use ply::{ply_counts, read_ply_mesh}; mod point_cloud; pub use point_cloud::{CloudFile, DEFAULT_MAX_POINTS, MAX_POINT_CLOUD_BYTES, is_ply_path, is_point_cloud_path, read_point_cloud}; @@ -42,7 +43,7 @@ pub use dxf_out::{DxfEntity, DxfLayer, DxfLinetype, DxfShape, loop_shapes, seg_s pub use legacy_dir::{APP_ID, LEGACY_APP_ID, PREVIOUS_APP_IDS, adopt_legacy_dir, legacy_flatpak_paths}; pub use safe_write::{backup_path, write_atomic}; pub use sketch2d::{Geom2, MAX_DRAWING_BYTES}; -pub use svg::read_svg; +pub use svg::{decode_svg, read_svg, svg_nothing_to_import}; mod gltf_in; pub use gltf_in::{GltfImport, Loader, MAX_GLTF_BYTES, MeshPlan, PlanPlace, glb_container, is_gltf_path, read_gltf}; mod obj; @@ -52,8 +53,10 @@ pub use threemf::{ }; pub use urdf::{UrdfOptions, UrdfPackage, urdf}; +use solidcore_record::Vec3; use solidcraft_doc::{Document, Metadata, ModelState}; -use solidcraft_geom::{MassProperties, Mesh, Vec3}; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{MassProperties, Mesh}; /// Design file extension: new designs, autosaves and recovery files are written as `.sc`. pub const DESIGN_EXT: &str = "sc"; @@ -224,6 +227,7 @@ pub fn step_import_feature(bytes: &[u8], file: &str) -> Result { /// [`step_import_feature`], with the bodies named after `names`. pub fn step_import_feature_named(bytes: &[u8], file: &str, names: StepNames) -> Result { + let _span = solidcraft_profile::span("import", "step_import_feature_named"); limits::check(limits::Kind::Step, bytes.len() as u64).map_err(IoError::Invalid)?; // STEP is 7-bit text with escapes; tolerate stray 8-bit bytes. IGES and the cadmpeg formats // are restated as STEP (the feature keeps that STEP text). @@ -279,6 +283,7 @@ pub struct MeshFeature { /// feature. A glTF file's bodies are all built where they are (see [`read_gltf`] for its node /// tree), and it can't read buffers in other files. pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result { + let _span = solidcraft_profile::span("import", "mesh_import_feature"); if is_gltf_path(file) { let mut no_files = |name: &str| Err(format!("`{name}` can't be read here")); let mut g = read_gltf(bytes, file, &mut no_files)?; @@ -408,12 +413,17 @@ pub fn export_mesh(b: &solidcraft_kernel::Body) -> Result { /// [`export_mesh`] at `quality` (never finer than 1 µm). pub fn export_mesh_at(b: &solidcraft_kernel::Body, quality: MeshQuality) -> Result { - Ok(b.tessellate((b.size() * quality.share()).max(1e-3))?) + Ok(b.mesh(&solidcraft_kernel::MeshTolerance::chord((b.size() * quality.share()).max(1e-3)))?) } -/// Distance within which an exported mesh's vertices are welded (STL and 3MF alike). +/// Distance within which an exported mesh's vertices are welded (STL, 3MF and OBJ alike). fn weld_eps(b: &solidcraft_kernel::Body) -> f64 { - (b.size() * 1e-6).max(1e-7) + weld_distance(b.size()) +} + +/// [`weld_eps`] for a body of characteristic size (bounding box diagonal) `size`. +fn weld_distance(size: f64) -> f64 { + (size * 1e-6).max(1e-7) } /// Unit-density [`MassProperties`] of a body from its welded [`export_mesh`], the mesh URDF links @@ -528,49 +538,81 @@ pub fn obj_files(bodies: &[ObjBody<'_>], mtl_name: &str) -> ObjFiles { ObjFiles { obj, mtl } } -/// The mesh of a body: its vertices and normals, each written once per distinct value, and the -/// faces that use them. Returns the text and the bases the next body carries on from. +/// The mesh of a body, welded as STL and 3MF are ([`weld`]: vertices closer than +/// [`weld_distance`] merged, and sides split where another face's vertex lies on them), so +/// neighbouring faces share their edge points and the file opens again as a closed solid +/// (#9074). Each corner keeps the normal it had ([`corner_normals`]), so edges between faces +/// stay sharp. Vertices and normals are each written once per distinct value. Returns the text +/// and the bases the next body carries on from. fn mesh_text(mesh: &Mesh, vbase: usize, nbase: usize) -> (String, usize, usize) { use std::collections::HashMap; - let mut s = String::new(); - // `+ 0.0` turns -0 into 0, so both merge. - let key = |x: f64, y: f64, z: f64| [x + 0.0, y + 0.0, z + 0.0].map(f64::to_bits); - let mut vmap: HashMap<[u64; 3], usize> = HashMap::new(); - let mut nmap: HashMap<[u64; 3], usize> = HashMap::new(); - let vi: Vec = mesh - .positions - .iter() - .map(|p| { - let next = vmap.len(); - *vmap.entry(key(p.x, p.y, p.z)).or_insert_with(|| { - s += &format!("v {} {} {}\n", p.x, p.y, p.z); - next - }) - }) - .collect(); - let ni: Vec = mesh - .normals - .iter() - .map(|n| { - let next = nmap.len(); - *nmap.entry(key(n.x, n.y, n.z)).or_insert_with(|| { - s += &format!("vn {} {} {}\n", n.x, n.y, n.z); - next - }) - }) - .collect(); - for t in &mesh.triangles { - let (Some(a), Some(b), Some(c)) = (vi.get(t[0] as usize), vi.get(t[1] as usize), vi.get(t[2] as usize)) else { continue }; - let (a, b, c) = (a + vbase, b + vbase, c + vbase); - match (ni.get(t[0] as usize), ni.get(t[1] as usize), ni.get(t[2] as usize)) { - (Some(na), Some(nb), Some(nc)) => { - let (na, nb, nc) = (na + nbase, nb + nbase, nc + nbase); - s += &format!("f {a}//{na} {b}//{nb} {c}//{nc}\n"); - } - _ => s += &format!("f {a} {b} {c}\n"), - } + let mut bounds = solidcraft_geom::Aabb3::EMPTY; + for p in &mesh.positions { + bounds.add(*p); } - (s, vbase + vmap.len(), nbase + nmap.len()) + let eps = weld_distance(bounds.diagonal()); + // Each welded triangle is tagged with the triangle it came from, for its normals. + let source: Vec = (0..mesh.triangles.len()).map(|k| u32::try_from(k).unwrap_or(u32::MAX)).collect(); + let (positions, triangles, from) = threemf::weld_tagged(&mesh.positions, &mesh.triangles, &source, eps); + let mut s = String::new(); + for p in &positions { + s += &format!("v {} {} {}\n", p.x, p.y, p.z); + } + // `+ 0.0` turns -0 into 0, so both merge. + let key = |n: Vec3| [n.x + 0.0, n.y + 0.0, n.z + 0.0].map(f64::to_bits); + let mut nmap: HashMap<[u64; 3], usize> = HashMap::new(); + let mut faces = String::new(); + for (t, k) in triangles.iter().zip(&from) { + let (a, b, c) = (t[0] as usize + vbase, t[1] as usize + vbase, t[2] as usize + vbase); + let at = t.map(|i| positions.get(i as usize).copied()); + let normals = match (mesh.triangles.get(*k as usize), at) { + (Some(o), [Some(pa), Some(pb), Some(pc)]) => corner_normals(mesh, *o, [pa, pb, pc], eps), + _ => None, + }; + let Some(normals) = normals else { + faces += &format!("f {a} {b} {c}\n"); + continue; + }; + let [na, nb, nc] = normals.map(|n| { + let next = nmap.len(); + nbase + + *nmap.entry(key(n)).or_insert_with(|| { + s += &format!("vn {} {} {}\n", n.x, n.y, n.z); + next + }) + }); + faces += &format!("f {a}//{na} {b}//{nb} {c}//{nc}\n"); + } + s += &faces; + (s, vbase + positions.len(), nbase + nmap.len()) +} + +/// The normals at the corners `at` of a welded piece of triangle `t` of `mesh` (the whole +/// triangle, or a piece of it split where another face's vertex lies on a side): a corner +/// within `eps` of one of `t`'s own corners takes that corner's normal; a point a side was split +/// at takes the normal between the side's ends. `None` when the mesh has no normals there. +fn corner_normals(mesh: &Mesh, t: [u32; 3], at: [Vec3; 3], eps: f64) -> Option<[Vec3; 3]> { + let p = t.map(|i| mesh.positions.get(i as usize).copied()); + let n = t.map(|i| mesh.normals.get(i as usize).copied()); + let ([Some(p0), Some(p1), Some(p2)], [Some(n0), Some(n1), Some(n2)]) = (p, n) else { return None }; + let (p, n) = ([p0, p1, p2], [n0, n1, n2]); + Some(at.map(|q| p.iter().zip(n).find(|(c, _)| c.dist(q) <= eps).map_or_else(|| normal_at(p, n, q), |(_, n)| n))) +} + +/// The normal at `q` on the triangle with corners `p` and corner normals `n`: the corners' +/// normals weighted by where `q` lies (barycentric), of unit length. The first corner's when +/// the triangle has no area. +fn normal_at(p: [Vec3; 3], n: [Vec3; 3], q: Vec3) -> Vec3 { + let [p0, p1, p2] = p; + let [n0, n1, n2] = n; + let (e1, e2, d) = (p1 - p0, p2 - p0, q - p0); + let (d11, d12, d22, d1, d2) = (e1.dot(e1), e1.dot(e2), e2.dot(e2), d.dot(e1), d.dot(e2)); + let den = d11 * d22 - d12 * d12; + if !(den.abs() > 0.0) { + return n0; + } + let (v, w) = ((d22 * d1 - d12 * d2) / den, (d11 * d2 - d12 * d1) / den); + (n0 * (1.0 - v - w) + n1 * v + n2 * w).normalized().unwrap_or(n0) } /// The material of each body: its name, safe to write in a material library and unique among @@ -684,6 +726,7 @@ pub fn export_with_quality( meta: &Metadata, quality: MeshQuality, ) -> Result> { + let _span = solidcraft_profile::span("io", "export_with_quality"); export_with_parts(state, bodies, &[], format, name, meta, quality) } @@ -779,6 +822,7 @@ fn mesh_object(b: &solidcraft_doc::ModelBody, tagged: bool, quality: MeshQuality /// part, built where the file placed it) is taken into its component's frame by that offset, /// as the world placement does, so the occurrences above it place it only once. pub fn step_assembly(doc: &Document, local: &ModelState, name: &str) -> Result> { + let _span = solidcraft_profile::span("io", "step_assembly"); use solidcraft_kernel::{ExportBody, ExportProduct}; let mut index: std::collections::HashMap = std::collections::HashMap::new(); index.insert(0, 0); @@ -811,10 +855,17 @@ pub fn step_assembly(doc: &Document, local: &ModelState, name: &str) -> Result Result { + let _span = solidcraft_profile::span("io", "read_design"); limits::check(limits::Kind::Design, bytes.len() as u64).map_err(|e| IoError::Invalid(format!("design {e}")))?; if is_design_container(bytes) { return design::read(bytes); } + // Every DWG starts with its version (`AC1032`), whatever the file is called (#9328). + if bytes.starts_with(b"AC1") { + return Err(IoError::Invalid( + "this is a DWG file, which SolidCraft can't read: export the model as STEP and open that, or the drawing as DXF and use Insert DXF in a sketch".into(), + )); + } let s = std::str::from_utf8(bytes).map_err(|_| IoError::Invalid("design file is not UTF-8 JSON".into()))?; Ok(Document::from_json(s)?) } @@ -893,8 +944,8 @@ pub const MAX_STL_TRIANGLES: usize = 20_000_000; #[cfg(test)] mod tests { use super::*; + use solidcore_record::Vec3; use solidcraft_doc::{FeatureKind, Model, Operation, point_expr}; - use solidcraft_geom::Vec3; fn model() -> (Document, Model) { let mut doc = Document::new("t"); @@ -990,8 +1041,12 @@ mod tests { assert!(o.contains("o Body1") && o.contains("\nf ")); } - /// OBJ shares a face's vertices (a cube: 8 positions, 6 normals, not 36 of each) and keeps - /// the body name as written, spaces included. + /// OBJ shares the vertices faces meet at and keeps the body name as written, spaces included. + /// The 10 × 20 × 30 box meshes as the planner's grids, no side longer than a fifth of its + /// extent (the 37.4 mm diagonal): its edges in 2, 3 and 5 pieces, so its faces are grids of + /// 2 × 3, 2 × 5 and 3 × 5 cells, 2 · (6 + 10 + 15) · 2 = 124 triangles. Welded, their + /// corners are the 3 · 4 · 6 = 72 nodes of the box's lattice less the 1 · 2 · 4 inside it: 64 + /// positions (unwelded, 372), and one normal per face. #[test] fn obj_export_is_welded_and_keeps_names() { let (_, m) = model(); @@ -1002,10 +1057,10 @@ mod tests { let o = String::from_utf8(export(&st, &[], Format::Obj, "t").unwrap()).unwrap(); let count = |p: &str| o.lines().filter(|l| l.starts_with(p)).count(); assert!(o.contains("\no Red Block\n"), "{o}"); - assert_eq!((count("v "), count("vn "), count("f ")), (8, 6, 12), "{o}"); + assert_eq!((count("v "), count("vn "), count("f ")), (64, 6, 124), "{o}"); let ids: Vec = o.lines().filter(|l| l.starts_with("f ")).flat_map(|l| l.split([' ', '/']).skip(1)).filter_map(|x| x.parse().ok()).collect(); - assert!(ids.iter().all(|i| (1..=8).contains(i) || (1..=6).contains(i))); + assert!(ids.iter().all(|i| (1..=64).contains(i))); } /// The OBJ export carries the colours of the bodies: the mesh file names the material @@ -1096,6 +1151,8 @@ mod tests { let back = read_design(&write_design(&doc)).unwrap(); assert_eq!(back, doc); assert!(read_design(b"\xff\xfe").is_err()); + let dwg = read_design(b"AC1032\0\0\0\0\0\xff\xfe").unwrap_err().to_string(); + assert!(dwg.contains("this is a DWG file") && dwg.contains("STEP") && dwg.contains("DXF"), "{dwg}"); assert!(matches!(export(&m.state(), &["nope".into()], Format::Step, "t"), Err(IoError::Empty))); assert_eq!(Format::from_name("a.STP").unwrap(), Format::Step); assert!(is_step_path("/x/Part.STEP") && is_step_path("a.stp") && !is_step_path("a.step.json") && !is_step_path("step")); @@ -1203,9 +1260,8 @@ mod tests { .sum() } - /// Build → export 3MF → import → the same volume as the STL export, closed meshes, names. - #[test] - fn threemf_round_trip() { + /// A filleted box, a cylinder and a torus: bodies whose faces are curved and meshed apart. + fn curved_bodies() -> Model { let mut doc = Document::new("t"); doc.add_feature( FeatureKind::Box { @@ -1226,6 +1282,9 @@ mod tests { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), + turn: Default::default(), + tangent_chain: true, }, None, ) @@ -1254,6 +1313,40 @@ mod tests { .unwrap(); let mut m = Model::new(); m.evaluate(&doc); + m + } + + /// OBJ is welded as STL and 3MF are: a filleted box, a cylinder and a torus written as OBJ + /// open again closed, with their STL export's volume, every face keeping its normals + /// (#9074). Before, each face wrote its edge points again, a few ulps apart, and the file + /// opened as an open mesh with no volume. + #[test] + fn obj_round_trip_of_curved_bodies_is_closed() { + let m = curved_bodies(); + let st = m.state(); + let bytes = export(&st, &[], Format::Obj, "t").unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(text.lines().filter(|l| l.starts_with("f ")).all(|l| l.matches("//").count() == 3), "every corner has a normal"); + let f = mesh_import_feature(&bytes, "parts.obj").unwrap(); + let mut d2 = Document::new("m"); + let id = d2.add_feature(f.kind, Some(&f.name)).unwrap(); + let mut m2 = Model::new(); + m2.evaluate(&d2); + assert!(m2.result(id).unwrap().error.is_none()); + let st2 = m2.state(); + assert_eq!(st2.bodies.len(), 3); + for (a, b) in st.bodies.iter().zip(&st2.bodies) { + assert!(b.body.is_mesh() && b.body.is_closed_mesh(), "{} is not watertight", a.name); + let v_stl = stl_volume(&export(&st, std::slice::from_ref(&a.name), Format::StlBinary, "t").unwrap()); + let v = solidcraft_kernel::measure(&b.body).unwrap().volume; + assert!((v - v_stl).abs() <= 1e-6 * v_stl.abs(), "{}: {v} vs {v_stl}", a.name); + } + } + + /// Build → export 3MF → import → the same volume as the STL export, closed meshes, names. + #[test] + fn threemf_round_trip() { + let m = curved_bodies(); let st = m.state(); assert_eq!(st.bodies.len(), 3); let bytes = export(&st, &[], Format::ThreeMf, "t").unwrap(); @@ -1312,6 +1405,9 @@ mod tests { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), + turn: Default::default(), + tangent_chain: true, }, None, ) diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index 191060f87..a7ebf7f00 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -1,323 +1,41 @@ -//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of -//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten -//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and -//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an -//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a -//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any -//! panic, so a caught one on the desktop is a crash there. -//! -//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces. -//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and -//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a -//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino -//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests. +//! Every reader of bytes the user didn't write, run over mutations of a valid file (#469): each +//! case gives an error or a result, never a panic, within the time budget and the reader's own +//! caps. The mutations and the check are `solidcraft_testkit`'s. -use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::time::{Duration, Instant}; +use solidcore_record::{Vec2, Vec3}; +use solidcraft_geom::Mesh; +use solidcraft_testkit::{mutations, survives}; -/// A deterministic xorshift64 stream. -pub(crate) struct Rng(u64); - -impl Rng { - pub(crate) fn new(seed: u64) -> Rng { - Rng(seed | 1) - } - - pub(crate) fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - - /// A value in `0..n` (0 when `n` is 0). - pub(crate) fn below(&mut self, n: usize) -> usize { - if n == 0 { 0 } else { (self.next() % n as u64) as usize } - } +fn cube() -> Mesh { + let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect(); + let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]]; + Mesh { positions, triangles: t.to_vec(), ..Default::default() } } -/// Numbers a hostile file might hold in place of a real one. -const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"]; - -/// Most truncations of one file (every length up to this, evenly spaced beyond). -const MAX_TRUNCATIONS: usize = 1024; - -/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number -/// mutations (the file is UTF-8 text). -pub(crate) fn mutations(good: &[u8], text: bool, seed: u64) -> Vec> { - let mut out: Vec> = Vec::new(); - let n = good.len(); - let mut rng = Rng::new(seed); - // Truncations: every length of a short file; of a long one, its first and last 64 lengths - // (headers, final records) and evenly spaced ones between. - if n <= MAX_TRUNCATIONS { - out.extend((0..n).map(|k| good[..k].to_vec())); - } else { - let mut cuts: Vec = (0..64).chain(n - 64..n).collect(); - cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128))); - cuts.sort_unstable(); - cuts.dedup(); - out.extend(cuts.into_iter().map(|k| good[..k].to_vec())); - } - if n == 0 { - return out; - } - // Bytes flipped, zeroed and saturated at seeded places. - for i in 0..384 { - let at = rng.below(n); - let mut b = good.to_vec(); - b[at] = match i % 3 { - 0 => b[at] ^ ((rng.next() >> 32) as u8 | 1), - 1 => 0x00, - _ => 0xff, - }; - out.push(b); - } - // Runs of bytes dropped, repeated and swapped with their neighbour. - for _ in 0..96 { - let at = rng.below(n); - let len = 1 + rng.below(64.min(n - at)); - let end = at + len; - let mut dropped = good[..at].to_vec(); - dropped.extend_from_slice(&good[end..]); - out.push(dropped); - let mut repeated = good[..end].to_vec(); - repeated.extend_from_slice(&good[at..]); - out.push(repeated); - if end + len <= n { - let mut swapped = good[..at].to_vec(); - swapped.extend_from_slice(&good[end..end + len]); - swapped.extend_from_slice(&good[at..end]); - swapped.extend_from_slice(&good[end + len..]); - out.push(swapped); - } - } - // The whole file: with garbage after it, twice over, reversed. - let mut tail = good.to_vec(); - tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8)); - out.push(tail); - out.push([good, good].concat()); - out.push(good.iter().rev().copied().collect()); - if text && let Ok(s) = std::str::from_utf8(good) { - out.extend(text_mutations(s, &mut rng)); - } - out +#[test] +fn stl_survives_mutation() { + let mesh = cube(); + let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz"); + let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes(); + assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12)); + assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12)); + let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len()); + survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read); + survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read); } -/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies. -fn text_mutations(s: &str, rng: &mut Rng) -> Vec> { - let mut out = Vec::new(); - let lines: Vec<&str> = s.split_inclusive('\n').collect(); - let join = |v: &[&str]| v.concat().into_bytes(); - let picked: Vec = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() }; - for &i in &picked { - let mut v = lines.clone(); - v.remove(i); - out.push(join(&v)); - let mut v = lines.clone(); - v.insert(i, lines[i]); - out.push(join(&v)); - if i + 1 < lines.len() { - let mut v = lines.clone(); - v.swap(i, i + 1); - out.push(join(&v)); - } - } - // A line in place of another (a block that inserts itself, a count where a coordinate was). - for _ in 0..200.min(lines.len() * lines.len()) { - let (i, j) = (rng.below(lines.len()), rng.below(lines.len())); - let mut v = lines.clone(); - v[i] = lines[j]; - out.push(join(&v)); - } - // A word in place of another of the file's own words: a renamed block, a swapped keyword, a - // block that now inserts itself. Every pair in a small file, a sample in a large one. - let words = word_spans(s); - let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect(); - vocab.sort_unstable(); - vocab.dedup(); - let pairs = words.len().saturating_mul(vocab.len()); - let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes(); - if pairs <= 3000 { - for &span in &words { - for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) { - out.push(swap(span, w)); - } - } - } else { - for _ in 0..400 { - out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())])); - } - } - // Numbers: each of up to 200 of them, in turn, becomes one of the liars. - let numbers = number_spans(s); - let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() }; - for (k, (a, b)) in chosen.into_iter().enumerate() { - let liar = LIARS[k % LIARS.len()]; - out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes()); - } - // Every number lying at once (two counts that are only harmless one at a time). - let all = number_spans(s); - for liar in LIARS { - let mut t = String::with_capacity(s.len()); - let mut at = 0; - for &(a, b) in &all { - t.push_str(&s[at..a]); - t.push_str(liar); - at = b; - } - t.push_str(&s[at..]); - out.push(t.into_bytes()); - } - out -} - -/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a -/// letter). -fn word_spans(s: &str) -> Vec<(usize, usize)> { - let b = s.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < b.len() { - if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) { - i += 1; - continue; - } - let a = i; - while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { - i += 1; - } - out.push((a, i)); - } - out -} - -/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent). -fn number_spans(s: &str) -> Vec<(usize, usize)> { - let b = s.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < b.len() { - let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit)); - let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); - if !starts || after_word { - i += 1; - continue; - } - let a = i; - i += 1; - while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) { - if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') { - i += 1; - } - i += 1; - } - out.push((a, i)); - } - out -} - -thread_local! { - /// Panics on this thread so far, caught or not ([`count_panics`]). - static PANICS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Count every panic per thread (tests run on several), then run the hook that was there. -fn count_panics() { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - let previous = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |info| { - PANICS.with(|p| p.set(p.get() + 1)); - previous(info); - })); +#[test] +fn obj_survives_mutation() { + let good = crate::obj(&[("Cube".into(), cube())]).into_bytes(); + assert!(crate::read_obj(&good, "fuzz").is_ok()); + survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| { + crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); } -/// The time any one reader call may take on a mutated file (a debug build on a loaded machine: -/// generous, but far below what unbounded work on a lying count would take). -pub(crate) const BUDGET: Duration = Duration::from_secs(2); - -/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles, -/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming -/// the first case that breaks a rule. -pub(crate) fn survives(what: &str, inputs: &[Vec], cap: usize, mut read: impl FnMut(&[u8]) -> Option) { - count_panics(); - let mut slowest = (Duration::ZERO, 0); - let mut read_ok = 0; - for (i, input) in inputs.iter().enumerate() { - let before = PANICS.with(std::cell::Cell::get); - let t = Instant::now(); - let r = catch_unwind(AssertUnwindSafe(|| read(input))); - let took = t.elapsed(); - let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned(); - let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) }; - let caught = PANICS.with(std::cell::Cell::get) - before; - assert!( - caught == 0, - "{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}", - input.len() - ); - assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len()); - if let Some(count) = r { - assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})"); - read_ok += 1; - } - slowest = slowest.max((took, i)); - } - eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0); -} - -#[cfg(test)] -mod tests { - use super::*; - use solidcraft_geom::{Mesh, Vec2, Vec3}; - - fn cube() -> Mesh { - let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect(); - let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]]; - Mesh { positions, triangles: t.to_vec(), ..Default::default() } - } - - #[test] - fn mutations_are_deterministic_and_cover_the_file() { - let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n"; - let a = mutations(good, true, 7); - assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases"); - assert_ne!(a, mutations(good, true, 8)); - assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing"); - assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar"); - assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]); - // A long file: bounded truncations, kept to the first and last bytes and spaced between. - let long = vec![b'a'; 100_000]; - let m = mutations(&long, false, 1); - assert!(m.len() < 3000, "{} cases", m.len()); - } - - #[test] - fn stl_survives_mutation() { - let mesh = cube(); - let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz"); - let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes(); - assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12)); - assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12)); - let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len()); - survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read); - survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read); - } - - #[test] - fn obj_survives_mutation() { - let good = crate::obj(&[("Cube".into(), cube())]).into_bytes(); - assert!(crate::read_obj(&good, "fuzz").is_ok()); - survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| { - crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - } - - #[test] - fn svg_survives_mutation() { - let good = br##" +#[test] +fn svg_survives_mutation() { + let good = br##" @@ -328,351 +46,352 @@ mod tests { "##; - assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok()); - survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); - } + assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok()); + survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); +} - #[test] - fn dxf_survives_mutation() { - let geom = [ - crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), - crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5), - crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) }, - crate::Geom2::Point(Vec2::new(1.0, 1.0)), - ]; - let written = crate::write_dxf(&geom).into_bytes(); - assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3)); - survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - // Blocks inside blocks, an array insert and a bulged polyline: what the block recursion, - // the array cells and the work budget guard. - let pairs: &[(&str, &str)] = &[ - ("0", "SECTION"), - ("2", "BLOCKS"), - ("0", "BLOCK"), - ("2", "inner"), - ("10", "0"), - ("20", "0"), - ("0", "LINE"), - ("10", "0"), - ("20", "0"), - ("11", "1"), - ("21", "1"), - ("0", "ENDBLK"), - ("0", "BLOCK"), - ("2", "outer"), - ("10", "0"), - ("20", "0"), - ("0", "INSERT"), - ("2", "inner"), - ("10", "2"), - ("20", "2"), - ("0", "CIRCLE"), - ("10", "0"), - ("20", "0"), - ("40", "1"), - ("0", "ENDBLK"), - ("0", "ENDSEC"), - ("0", "SECTION"), - ("2", "ENTITIES"), - ("0", "INSERT"), - ("2", "outer"), - ("10", "5"), - ("20", "5"), - ("41", "2"), - ("42", "2"), - ("50", "30"), - ("70", "3"), - ("71", "2"), - ("44", "10"), - ("45", "10"), - ("0", "LWPOLYLINE"), - ("90", "3"), - ("70", "1"), - ("10", "0"), - ("20", "0"), - ("42", "0.5"), - ("10", "5"), - ("20", "0"), - ("10", "5"), - ("20", "5"), - ("0", "ENDSEC"), - ("0", "EOF"), - ]; - let blocks: String = pairs - .iter() - .map(|(c, v)| { - format!( - "{c} +#[test] +fn dxf_survives_mutation() { + let geom = [ + crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), + crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5), + crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) }, + crate::Geom2::Point(Vec2::new(1.0, 1.0)), + ]; + let written = crate::write_dxf(&geom).into_bytes(); + assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3)); + survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); + // Blocks inside blocks, an array insert and a bulged polyline: what the block recursion, + // the array cells and the work budget guard. + let pairs: &[(&str, &str)] = &[ + ("0", "SECTION"), + ("2", "BLOCKS"), + ("0", "BLOCK"), + ("2", "inner"), + ("10", "0"), + ("20", "0"), + ("0", "LINE"), + ("10", "0"), + ("20", "0"), + ("11", "1"), + ("21", "1"), + ("0", "ENDBLK"), + ("0", "BLOCK"), + ("2", "outer"), + ("10", "0"), + ("20", "0"), + ("0", "INSERT"), + ("2", "inner"), + ("10", "2"), + ("20", "2"), + ("0", "CIRCLE"), + ("10", "0"), + ("20", "0"), + ("40", "1"), + ("0", "ENDBLK"), + ("0", "ENDSEC"), + ("0", "SECTION"), + ("2", "ENTITIES"), + ("0", "INSERT"), + ("2", "outer"), + ("10", "5"), + ("20", "5"), + ("41", "2"), + ("42", "2"), + ("50", "30"), + ("70", "3"), + ("71", "2"), + ("44", "10"), + ("45", "10"), + ("0", "LWPOLYLINE"), + ("90", "3"), + ("70", "1"), + ("10", "0"), + ("20", "0"), + ("42", "0.5"), + ("10", "5"), + ("20", "0"), + ("10", "5"), + ("20", "5"), + ("0", "ENDSEC"), + ("0", "EOF"), + ]; + let blocks: String = pairs + .iter() + .map(|(c, v)| { + format!( + "{c} {v} " - ) - }) - .collect(); - let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0); - assert!(n >= 12, "the array insert expands its nested blocks: {n} entities"); - survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - // The two lies that need each other, written out: a block that inserts itself (the - // depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets). - let looped = blocks.replacen( - "2 + ) + }) + .collect(); + let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0); + assert!(n >= 12, "the array insert expands its nested blocks: {n} entities"); + survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| { + crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) + }); + // The two lies that need each other, written out: a block that inserts itself (the + // depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets). + let looped = blocks.replacen( + "2 inner 10 2", - "2 + "2 outer 10 2", - 1, - ); - assert_ne!(looped, blocks, "the outer block now inserts itself"); - let huge = blocks.replacen( - "70 + 1, + ); + assert_ne!(looped, blocks, "the outer block now inserts itself"); + let huge = blocks.replacen( + "70 3 71 2", - "70 + "70 10000 71 10000", - 1, - ); - assert_ne!(huge, blocks); - survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - } + 1, + ); + assert_ne!(huge, blocks); + survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| { + crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) + }); +} - #[test] - fn threemf_survives_mutation() { - let mesh = cube(); - let object = crate::MeshObject { - name: "Cube".into(), - positions: mesh.positions, - triangles: mesh.triangles, - color: Some([0.8, 0.2, 0.1]), - ..Default::default() - }; - let good = crate::write_3mf(&[object]).unwrap(); - assert!(crate::read_3mf(&good).is_ok()); - survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| { +#[test] +fn threemf_survives_mutation() { + let mesh = cube(); + let object = crate::MeshObject { + name: "Cube".into(), + positions: mesh.positions, + triangles: mesh.triangles, + color: Some([0.8, 0.2, 0.1]), + ..Default::default() + }; + let good = crate::write_3mf(&[object]).unwrap(); + assert!(crate::read_3mf(&good).is_ok()); + survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); + // Objects in another model part (production extension), as slicers save projects. + let production = crate::threemf::tests::production_package(); + assert!(crate::read_3mf(&production).is_ok()); + survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); + // Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its + // checksums, these reach the `p:path` and `objectid` handling. + let parts = crate::threemf::tests::production_parts(); + for (k, (name, xml)) in parts.iter().enumerate() { + let rezipped: Vec> = mutations(xml.as_bytes(), true, 0x2089 + k as u64) + .iter() + .map(|m| { + let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect(); + crate::threemf::tests::package_bytes(&entries) + }) + .collect(); + survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| { crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); - // Objects in another model part (production extension), as slicers save projects. - let production = crate::threemf::tests::production_package(); - assert!(crate::read_3mf(&production).is_ok()); - survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { - crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - // Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its - // checksums, these reach the `p:path` and `objectid` handling. - let parts = crate::threemf::tests::production_parts(); - for (k, (name, xml)) in parts.iter().enumerate() { - let rezipped: Vec> = mutations(xml.as_bytes(), true, 0x2089 + k as u64) - .iter() - .map(|m| { - let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect(); - crate::threemf::tests::package_bytes(&entries) - }) - .collect(); - survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| { - crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - } } +} - #[test] - fn gltf_survives_mutation() { - let mut f = crate::gltf_in::tests::Fixture::default(); - let m = f.cube_mesh("Cube", 0.01); - let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]})); - let n = f.node(serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]})); - f.roots = vec![n]; - let mut no_files = |name: &str| -> std::result::Result, String> { Err(format!("no file `{name}`")) }; - let glb = f.glb(); - assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok()); - survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1)); - // The JSON form, its buffer embedded as a data URI. - let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin)); - let gltf = f.json(Some(&uri)).to_string().into_bytes(); - assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok()); - survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1)); +#[test] +fn gltf_survives_mutation() { + let mut f = crate::gltf_in::tests::Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]})); + let n = f.node( + serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]}), + ); + f.roots = vec![n]; + let mut no_files = |name: &str| -> std::result::Result, String> { Err(format!("no file `{name}`")) }; + let glb = f.glb(); + assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok()); + survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1)); + // The JSON form, its buffer embedded as a data URI. + let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin)); + let gltf = f.json(Some(&uri)).to_string().into_bytes(); + assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok()); + survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1)); +} + +#[test] +fn designs_survive_mutation() { + let mut doc = solidcraft_doc::Document::new("Fuzz"); + doc.set_param("width", "40", Some("mm"), None).unwrap(); + let mesh = solidcraft_doc::MeshData { + name: "Preview".into(), + positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(), + triangles: vec![0, 1, 2].into(), + color: None, + }; + let preview = crate::DesignPreview { meshes: vec![mesh] }; + let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap(); + assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some()); + survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| { + let _ = crate::read_design_preview(b); + let _ = crate::read_design_thumbnail(b); + crate::read_design(b).ok().map(|d| d.features.len()) + }); + let json = crate::write_design(&doc); + assert!(crate::read_design(&json).is_ok()); + survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); +} + +/// A design with two drawings, as a container and as plain JSON: every mutation gives an error +/// or a design, never a panic, and never more drawings than a design may hold. +#[test] +fn designs_with_drawings_survive_mutation() { + use solidcraft_doc::drawing::{Drawing, MAX_DRAWINGS, Source}; + use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; + let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); + let mut doc = solidcraft_doc::Document::new("Fuzz"); + for name in ["Assembly", "Details"] { + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let taken = doc.drawings.iter().map(|d| d.id).collect(); + let mut drawing = Drawing::new(name, "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut ids).unwrap(); + let id = drawing.allocate_id(&mut ids).unwrap(); + drawing.sources.push(Source { id }); + doc.drawings.push(drawing.into()); } + let container = crate::write_design_container(&doc).unwrap(); + assert_eq!(crate::read_design(&container).unwrap().drawings, doc.drawings); + survives("design container with drawings", &mutations(&container, false, 0xd4b), MAX_DRAWINGS, |b| { + crate::read_design(b).ok().map(|d| d.drawings.len()) + }); + let json = crate::write_design(&doc); + assert_eq!(crate::read_design(&json).unwrap().drawings, doc.drawings); + survives("design JSON with drawings", &mutations(&json, true, 0xd4c), MAX_DRAWINGS, |b| crate::read_design(b).ok().map(|d| d.drawings.len())); +} - #[test] - fn designs_survive_mutation() { - let mut doc = solidcraft_doc::Document::new("Fuzz"); - doc.set_param("width", "40", Some("mm"), None).unwrap(); - let mesh = solidcraft_doc::MeshData { - name: "Preview".into(), - positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(), - triangles: vec![0, 1, 2].into(), - color: None, - }; - let preview = crate::DesignPreview { meshes: vec![mesh] }; - let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap(); - assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some()); - survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| { - let _ = crate::read_design_preview(b); - let _ = crate::read_design_thumbnail(b); - crate::read_design(b).ok().map(|d| d.features.len()) - }); - let json = crate::write_design(&doc); - assert!(crate::read_design(&json).is_ok()); - survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); +/// Mid grey at half alpha, the size asked for: the paper fuzz cases' pictures. +struct Grey; + +impl solidcraft_geom::paper::Pictures for Grey { + fn rows( + &self, + _: u64, + _: &solidcraft_geom::pixel_grid::PixelGrid, + w: solidcraft_geom::pixel_grid::GridWindow, + ) -> std::result::Result, String> { + Ok([128, 128, 128, 128].repeat(w.x1.saturating_sub(w.x0) as usize * w.y1.saturating_sub(w.y0) as usize)) } +} - /// A design with two drawings, as a container and as plain JSON: every mutation gives an error - /// or a design, never a panic, and never more drawings than a design may hold. - #[test] - fn designs_with_drawings_survive_mutation() { - use solidcraft_doc::drawing::{Drawing, MAX_DRAWINGS, Source}; - use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; - let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); - let mut doc = solidcraft_doc::Document::new("Fuzz"); - for name in ["Assembly", "Details"] { - let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); - let taken = doc.drawings.iter().map(|d| d.id).collect(); - let mut drawing = Drawing::new(name, "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut ids).unwrap(); - let id = drawing.allocate_id(&mut ids).unwrap(); - drawing.sources.push(Source { id }); - doc.drawings.push(drawing.into()); - } - let container = crate::write_design_container(&doc).unwrap(); - assert_eq!(crate::read_design(&container).unwrap().drawings, doc.drawings); - survives("design container with drawings", &mutations(&container, false, 0xd4b), MAX_DRAWINGS, |b| { - crate::read_design(b).ok().map(|d| d.drawings.len()) - }); - let json = crate::write_design(&doc); - assert_eq!(crate::read_design(&json).unwrap().drawings, doc.drawings); - survives("design JSON with drawings", &mutations(&json, true, 0xd4c), MAX_DRAWINGS, |b| crate::read_design(b).ok().map(|d| d.drawings.len())); - } +/// A paper scene's JSON with a picture, mutated, read, prepared and written as SVG with its +/// pictures at 25 dpi: an error or a document, never a panic. +#[test] +fn paper_scenes_survive_mutation_into_svg() { + use solidcore_record::{Loop2, Region2, Seg2, Vec2}; + use solidcraft_geom::Aabb2; + use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Picture, Scene}; + let p = Vec2::new; + let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); + let dashes = || Dashes { lengths_mm: vec![4.2, 1.05, 0.5, 1.05], phase_mm: 0.5 }; + let items = vec![ + Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7, pattern: None }, + Item::Stroke { + path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], + closed: false, + width_mm: 0.35, + pattern: Some(dashes()), + }, + Item::Fill { region: Region2 { outer: border, holes: vec![] } }, + Item::Picture(Picture { source: 3, rect: Aabb2 { min: p(150.0, 100.0), max: p(250.0, 150.0) }, opacity: 0.8 }), + ]; + let scene = Scene::new(p(420.0, 297.0), vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }]); + let json = serde_json::to_vec(&scene).unwrap(); + let write = |b: &[u8]| -> Option { + let scene: Scene = serde_json::from_slice(b).ok()?; + let prepared = scene.prepare().ok()?; + crate::paper::paper_svg(&prepared, &Grey, 25.0).ok().map(|(bytes, _)| bytes.len()) + }; + assert!(write(&json).is_some()); + survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write); +} - /// Mid grey at half alpha, the size asked for: the paper fuzz cases' pictures. - struct Grey; - - impl solidcraft_geom::paper::Pictures for Grey { - fn rows( - &self, - _: u64, - _: &solidcraft_geom::pixel_grid::PixelGrid, - w: solidcraft_geom::pixel_grid::GridWindow, - ) -> std::result::Result, String> { - Ok([128, 128, 128, 128].repeat(w.x1.saturating_sub(w.x0) as usize * w.y1.saturating_sub(w.y0) as usize)) - } - } - - /// A paper scene's JSON with a picture, mutated, read, prepared and written as SVG with its - /// pictures at 25 dpi: an error or a document, never a panic. - #[test] - fn paper_scenes_survive_mutation_into_svg() { - use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Picture, Scene}; - use solidcraft_geom::{Aabb2, Loop2, Region2, Seg2, Vec2}; - let p = Vec2::new; - let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); - let dashes = || Dashes { lengths_mm: vec![4.2, 1.05, 0.5, 1.05], phase_mm: 0.5 }; +/// A clipped object's JSON, a line and a picture crossing its rectangle or circle, mutated, read, +/// prepared and written by both writers: an error or a file, never a panic. +#[test] +fn paper_scenes_with_clips_survive_mutation() { + use solidcore_record::{Seg2, Vec2}; + use solidcraft_geom::Aabb2; + use solidcraft_geom::paper::{Clip, Group, Item, ObjectKind, Picture, Scene}; + let p = Vec2::new; + let clips = [(0x5a5, Clip::Rect { min: p(180.0, 90.0), max: p(220.0, 130.0) }), (0x5a6, Clip::Circle { center: p(200.0, 110.0), radius: 25.0 })]; + for (seed, clip) in clips { let items = vec![ - Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7, pattern: None }, - Item::Stroke { - path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], - closed: false, - width_mm: 0.35, - pattern: Some(dashes()), - }, - Item::Fill { region: Region2 { outer: border, holes: vec![] } }, + Item::Stroke { path: vec![Seg2::Line { a: p(150.0, 110.0), b: p(250.0, 110.0) }], closed: false, width_mm: 0.35, pattern: None }, Item::Picture(Picture { source: 3, rect: Aabb2 { min: p(150.0, 100.0), max: p(250.0, 150.0) }, opacity: 0.8 }), ]; - let scene = Scene::new(p(420.0, 297.0), vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }]); - let json = serde_json::to_vec(&scene).unwrap(); - let write = |b: &[u8]| -> Option { - let scene: Scene = serde_json::from_slice(b).ok()?; - let prepared = scene.prepare().ok()?; - crate::paper::paper_svg(&prepared, &Grey, 25.0).ok().map(|(bytes, _)| bytes.len()) - }; - assert!(write(&json).is_some()); - survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write); - } - - /// A clipped object's JSON, a line and a picture crossing its rectangle or circle, mutated, read, - /// prepared and written by both writers: an error or a file, never a panic. - #[test] - fn paper_scenes_with_clips_survive_mutation() { - use solidcraft_geom::paper::{Clip, Group, Item, ObjectKind, Picture, Scene}; - use solidcraft_geom::{Aabb2, Seg2, Vec2}; - let p = Vec2::new; - let clips = - [(0x5a5, Clip::Rect { min: p(180.0, 90.0), max: p(220.0, 130.0) }), (0x5a6, Clip::Circle { center: p(200.0, 110.0), radius: 25.0 })]; - for (seed, clip) in clips { - let items = vec![ - Item::Stroke { path: vec![Seg2::Line { a: p(150.0, 110.0), b: p(250.0, 110.0) }], closed: false, width_mm: 0.35, pattern: None }, - Item::Picture(Picture { source: 3, rect: Aabb2 { min: p(150.0, 100.0), max: p(250.0, 150.0) }, opacity: 0.8 }), - ]; - let scene = Scene { clips: vec![(7, clip)], ..Scene::new(p(420.0, 297.0), vec![Group { object: 7, kind: ObjectKind::View, items }]) }; - let json = serde_json::to_vec(&scene).unwrap(); - let options = crate::paper::PngOptions { dpi: 25.0, colour: crate::paper::PngColour::Grey }; - let write = |b: &[u8]| -> Option { - let scene: Scene = serde_json::from_slice(b).ok()?; - let prepared = scene.prepare().ok()?; - let svg = crate::paper::paper_svg(&prepared, &Grey, 25.0).ok()?.0.len(); - let mut out = Vec::new(); - crate::paper::paper_png(&prepared, options, &Grey, &mut out).ok()?; - Some(svg + out.len()) - }; - assert!(write(&json).is_some()); - survives("clipped paper scene", &mutations(&json, true, seed), usize::MAX, write); - } - } - - /// The same scene's JSON with a picture, mutated, read, prepared and written as a 25 dpi sheet - /// PNG: an error or an image, never a panic. - #[test] - fn paper_scenes_survive_mutation_into_png() { - use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Picture, Scene}; - use solidcraft_geom::{Aabb2, Loop2, Region2, Seg2, Vec2}; - let p = Vec2::new; - let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); - let dashes = || Dashes { lengths_mm: vec![4.2, 1.05, 0.5, 1.05], phase_mm: 0.5 }; - let items = vec![ - Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7, pattern: None }, - Item::Stroke { - path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], - closed: false, - width_mm: 0.35, - pattern: Some(dashes()), - }, - Item::Fill { region: Region2 { outer: border, holes: vec![Loop2::circle(p(100.0, 100.0), 20.0)] } }, - Item::Picture(Picture { source: 3, rect: Aabb2 { min: p(150.0, 100.0), max: p(250.0, 150.0) }, opacity: 0.8 }), - ]; - let scene = Scene::new(p(420.0, 297.0), vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }]); + let scene = Scene { clips: vec![(7, clip)], ..Scene::new(p(420.0, 297.0), vec![Group { object: 7, kind: ObjectKind::View, items }]) }; let json = serde_json::to_vec(&scene).unwrap(); let options = crate::paper::PngOptions { dpi: 25.0, colour: crate::paper::PngColour::Grey }; let write = |b: &[u8]| -> Option { let scene: Scene = serde_json::from_slice(b).ok()?; let prepared = scene.prepare().ok()?; + let svg = crate::paper::paper_svg(&prepared, &Grey, 25.0).ok()?.0.len(); let mut out = Vec::new(); - crate::paper::paper_png(&prepared, options, &Grey, &mut out).ok().map(|_| out.len()) + crate::paper::paper_png(&prepared, options, &Grey, &mut out).ok()?; + Some(svg + out.len()) }; assert!(write(&json).is_some()); - survives("paper scene to PNG", &mutations(&json, true, 0x5a4), usize::MAX, write); - } - - /// Standard base64 (RFC 4648) of `bytes`, for a data URI. - fn base64(bytes: &[u8]) -> String { - const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut s = String::new(); - for c in bytes.chunks(3) { - let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); - for k in 0..4 { - if k <= c.len() { - s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63])); - } else { - s.push('='); - } - } - } - s + survives("clipped paper scene", &mutations(&json, true, seed), usize::MAX, write); } } + +/// The same scene's JSON with a picture, mutated, read, prepared and written as a 25 dpi sheet +/// PNG: an error or an image, never a panic. +#[test] +fn paper_scenes_survive_mutation_into_png() { + use solidcore_record::{Loop2, Region2, Seg2, Vec2}; + use solidcraft_geom::Aabb2; + use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Picture, Scene}; + let p = Vec2::new; + let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); + let dashes = || Dashes { lengths_mm: vec![4.2, 1.05, 0.5, 1.05], phase_mm: 0.5 }; + let items = vec![ + Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7, pattern: None }, + Item::Stroke { + path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], + closed: false, + width_mm: 0.35, + pattern: Some(dashes()), + }, + Item::Fill { region: Region2 { outer: border, holes: vec![Loop2::circle(p(100.0, 100.0), 20.0)] } }, + Item::Picture(Picture { source: 3, rect: Aabb2 { min: p(150.0, 100.0), max: p(250.0, 150.0) }, opacity: 0.8 }), + ]; + let scene = Scene::new(p(420.0, 297.0), vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }]); + let json = serde_json::to_vec(&scene).unwrap(); + let options = crate::paper::PngOptions { dpi: 25.0, colour: crate::paper::PngColour::Grey }; + let write = |b: &[u8]| -> Option { + let scene: Scene = serde_json::from_slice(b).ok()?; + let prepared = scene.prepare().ok()?; + let mut out = Vec::new(); + crate::paper::paper_png(&prepared, options, &Grey, &mut out).ok().map(|_| out.len()) + }; + assert!(write(&json).is_some()); + survives("paper scene to PNG", &mutations(&json, true, 0x5a4), usize::MAX, write); +} + +/// Standard base64 (RFC 4648) of `bytes`, for a data URI. +fn base64(bytes: &[u8]) -> String { + const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut s = String::new(); + for c in bytes.chunks(3) { + let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); + for k in 0..4 { + if k <= c.len() { + s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63])); + } else { + s.push('='); + } + } + } + s +} diff --git a/crates/io/src/obj.rs b/crates/io/src/obj.rs index f09e4e8b0..bcf426efd 100644 --- a/crates/io/src/obj.rs +++ b/crates/io/src/obj.rs @@ -3,7 +3,7 @@ //! are split into fans. Texture coordinates, normals and materials are ignored. The file is //! untrusted: counts are capped and bad lines become warnings. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::threemf::MeshObject; use crate::{IoError, Result}; diff --git a/crates/io/src/paper/png.rs b/crates/io/src/paper/png.rs index 64d9ff6db..a7a8ce5e0 100644 --- a/crates/io/src/paper/png.rs +++ b/crates/io/src/paper/png.rs @@ -25,7 +25,7 @@ use std::io::Write; use std::ops::RangeInclusive; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_geom::paper::{self, Clip, Grid, GridDashes, GridItem, GridPath, GridReport, Picture, Pictures, Prepared}; use solidcraft_geom::pixel_grid::{GridWindow, MAX_SIDE_PX, PixelGrid, PixelGridError}; use tiny_skia::{Color, FillRule, LineCap, LineJoin, Paint, Path, PathBuilder, Pixmap, PremultipliedColorU8, Stroke, StrokeDash, Transform}; diff --git a/crates/io/src/paper/png_tests.rs b/crates/io/src/paper/png_tests.rs index 8f35435ea..281f8b24b 100644 --- a/crates/io/src/paper/png_tests.rs +++ b/crates/io/src/paper/png_tests.rs @@ -1,8 +1,10 @@ use std::cell::RefCell; use std::f64::consts::{FRAC_PI_2, TAU}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; +use solidcraft_geom::Aabb2; use solidcraft_geom::paper::{Dashes, Group, Item, NoPictures, ObjectKind, Scene}; -use solidcraft_geom::{Aabb2, Loop2, Region2, Seg2, Vec2}; +use solidcraft_geom::prelude::*; use super::*; diff --git a/crates/io/src/paper/svg.rs b/crates/io/src/paper/svg.rs index b27220c69..6177bbf39 100644 --- a/crates/io/src/paper/svg.rs +++ b/crates/io/src/paper/svg.rs @@ -25,8 +25,9 @@ use std::fmt::Write; +use solidcore_record::Vec2; +use solidcraft_geom::Aabb2; use solidcraft_geom::paper::{Clip, FillRule, Grid, GridDashes, GridItem, GridPath, GridPoint, GridReport, Picture, Pictures, Piece, Prepared}; -use solidcraft_geom::{Aabb2, Vec2}; use super::png::{PICTURE_DPI, picture_png}; use crate::{IoError, MAX_DRAWING_BYTES, Result}; diff --git a/crates/io/src/paper/svg_tests.rs b/crates/io/src/paper/svg_tests.rs index b5dc090d3..efb49e49a 100644 --- a/crates/io/src/paper/svg_tests.rs +++ b/crates/io/src/paper/svg_tests.rs @@ -1,9 +1,11 @@ +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI, TAU}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; use solidcraft_doc::canvas::base64_decode; +use solidcraft_geom::Aabb2; use solidcraft_geom::paper::{Clip, Dashes, Group, Item, NoPictures, ObjectKind, Picture, Pictures, Scene}; use solidcraft_geom::pixel_grid::GridWindow; -use solidcraft_geom::{Aabb2, Loop2, Region2, Seg2, Vec2}; use super::*; use crate::paper::png::tests::{Image, Provider, read}; @@ -96,7 +98,7 @@ fn cubics_and_parabolas_are_written_and_other_curves_as_cubics() { assert_eq!(first_d(&sheet(vec![stroke(vec![cubic], false, 0.25)])), "M0 297C10 277 30 277 40 297"); let parabola = Seg2::Conic { a: p(0.0, 0.0), apex: p(10.0, 10.0), b: p(20.0, 0.0), w: 1.0 }; assert_eq!(first_d(&sheet(vec![stroke(vec![parabola], false, 0.25)])), "M0 297Q10 287 20 297"); - let mut controls = [p(0.0, 0.0); solidcraft_geom::MAX_BEZIER_CTRL]; + let mut controls = [p(0.0, 0.0); solidcore_record::MAX_BEZIER_CTRL]; controls[..5].copy_from_slice(&[p(0.0, 0.0), p(5.0, 10.0), p(10.0, 0.0), p(15.0, 10.0), p(20.0, 0.0)]); let quartic = Seg2::Bezier { n: 4, p: controls }; for curve in [0.5, 2.0].map(|w| Seg2::Conic { a: p(0.0, 0.0), apex: p(10.0, 10.0), b: p(20.0, 0.0), w }).into_iter().chain([quartic]) { diff --git a/crates/io/src/ply.rs b/crates/io/src/ply.rs index fc6c8fca5..83990961d 100644 --- a/crates/io/src/ply.rs +++ b/crates/io/src/ply.rs @@ -5,7 +5,7 @@ //! and property (normals, intensity, edges, …) is passed over. The file is untrusted: counts are //! checked against its size and capped. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::threemf::MeshObject; use crate::{IoError, Result}; @@ -25,7 +25,7 @@ fn invalid(m: impl std::fmt::Display) -> IoError { } #[derive(Clone, Copy, Debug, PartialEq)] -enum Scalar { +pub(crate) enum Scalar { I8, U8, I16, @@ -50,7 +50,7 @@ impl Scalar { _ => return None, }) } - fn size(self) -> usize { + pub(crate) fn size(self) -> usize { match self { Scalar::I8 | Scalar::U8 => 1, Scalar::I16 | Scalar::U16 => 2, @@ -79,7 +79,7 @@ impl Scalar { }) } /// A colour channel of this type as a byte: integers by their range, floats from 0..1. - fn channel(self, v: f64) -> u8 { + pub(crate) fn channel(self, v: f64) -> u8 { let v = match self { Scalar::F32 | Scalar::F64 => v * 255.0, Scalar::U16 | Scalar::I16 => v / 257.0, @@ -91,23 +91,23 @@ impl Scalar { } #[derive(Clone, Copy, Debug, PartialEq)] -enum Kind { +pub(crate) enum Kind { Scalar(Scalar), /// The count's type and the items' type. List(Scalar, Scalar), } #[derive(Clone, Debug)] -struct Property { - name: String, - kind: Kind, +pub(crate) struct Property { + pub(crate) name: String, + pub(crate) kind: Kind, } #[derive(Clone, Debug)] -struct Element { - name: String, - count: u64, - properties: Vec, +pub(crate) struct Element { + pub(crate) name: String, + pub(crate) count: u64, + pub(crate) properties: Vec, } impl Element { @@ -124,7 +124,7 @@ impl Element { } #[derive(Clone, Copy, Debug, PartialEq)] -enum Encoding { +pub(crate) enum Encoding { Ascii, Little, Big, @@ -132,10 +132,12 @@ enum Encoding { /// What the header says, and where the rows start. #[derive(Debug)] -struct Header { - encoding: Encoding, - elements: Vec, - body: usize, +pub(crate) struct Header { + pub(crate) encoding: Encoding, + pub(crate) elements: Vec, + pub(crate) body: usize, + /// The text of the `comment` lines. + pub(crate) comments: Vec, } /// Does `bytes` start like a PLY file? @@ -143,7 +145,7 @@ pub fn is_ply(bytes: &[u8]) -> bool { bytes.starts_with(b"ply") && bytes.get(3).is_some_and(|b| matches!(b, b'\n' | b'\r')) } -fn header(bytes: &[u8]) -> Result
{ +pub(crate) fn header(bytes: &[u8]) -> Result
{ if !is_ply(bytes) { return Err(invalid("not a PLY file (it must start with `ply`)")); } @@ -163,7 +165,12 @@ fn header(bytes: &[u8]) -> Result
{ let text = String::from_utf8_lossy(head.get(..end).unwrap_or_default()); let mut encoding = None; let mut elements: Vec = Vec::new(); + let mut comments = Vec::new(); for line in text.split(['\n', '\r']).skip(1) { + if let Some(c) = line.strip_prefix("comment ") { + comments.push(c.trim().to_string()); + continue; + } let mut it = line.split_whitespace(); match it.next() { Some("format") => { @@ -206,11 +213,11 @@ fn header(bytes: &[u8]) -> Result
{ } } let encoding = encoding.ok_or_else(|| invalid("no `format` line"))?; - Ok(Header { encoding, elements, body }) + Ok(Header { encoding, elements, body, comments }) } /// A row's values, read one after another. -enum Rows<'a> { +pub(crate) enum Rows<'a> { Binary { b: &'a [u8], pos: usize, big: bool }, Ascii { tokens: std::slice::Split<'a, u8, fn(&u8) -> bool> }, } @@ -220,7 +227,7 @@ fn space(b: &u8) -> bool { } impl<'a> Rows<'a> { - fn new(h: &Header, bytes: &'a [u8]) -> Rows<'a> { + pub(crate) fn new(h: &Header, bytes: &'a [u8]) -> Rows<'a> { let b = bytes.get(h.body..).unwrap_or_default(); match h.encoding { Encoding::Ascii => Rows::Ascii { tokens: b.split(space as fn(&u8) -> bool) }, @@ -228,7 +235,7 @@ impl<'a> Rows<'a> { Encoding::Big => Rows::Binary { b, pos: 0, big: true }, } } - fn value(&mut self, t: Scalar) -> Result { + pub(crate) fn value(&mut self, t: Scalar) -> Result { match self { Rows::Binary { b, pos, big } => { let v = b.get(*pos..).and_then(|r| t.read(r, *big)).ok_or_else(|| invalid("the file ends early"))?; @@ -265,7 +272,7 @@ impl<'a> Rows<'a> { } } } - fn count(&mut self, t: Scalar) -> Result { + pub(crate) fn count(&mut self, t: Scalar) -> Result { let n = self.value(t)?; if !(n >= 0.0 && n <= MAX_FACE as f64 && n.fract() == 0.0) { return Err(invalid("a list is longer than SolidCraft reads")); @@ -316,7 +323,6 @@ pub(crate) type Vertex = ([f64; 3], Option<[u8; 3]>); /// into `faces` (a fan of triangles per face) when given. struct Read { vertices: u64, - colored: bool, bad_faces: usize, } @@ -327,7 +333,7 @@ fn walk(bytes: &[u8], keep: &mut dyn FnMut(u64) -> bool, on_vertex: &mut dyn FnM if w.xyz.is_none() { return Err(invalid("the vertices have no `x`, `y` and `z`")); } - let mut out = Read { vertices: vertex.count, colored: w.rgb.is_some(), bad_faces: 0 }; + let mut out = Read { vertices: vertex.count, bad_faces: 0 }; let body = bytes.len().saturating_sub(h.body) as u64; let mut rows = Rows::new(&h, bytes); let mut slots = vec![0.0f64; MAX_PROPERTIES]; @@ -447,14 +453,6 @@ fn walk(bytes: &[u8], keep: &mut dyn FnMut(u64) -> bool, on_vertex: &mut dyn FnM Ok(out) } -/// The vertices of a PLY file, every `stride`th one (`1`: all), and how many the file has. -/// The colour of each is `Some` when the file has colours. -pub(crate) fn read_vertices(bytes: &[u8], stride: u64, on_vertex: &mut dyn FnMut(Vertex)) -> Result<(u64, bool)> { - let stride = stride.max(1); - let r = walk(bytes, &mut |i| i.is_multiple_of(stride), on_vertex, None)?; - Ok((r.vertices, r.colored)) -} - /// How many vertices and faces a PLY file says it has (from its header alone). pub fn ply_counts(bytes: &[u8]) -> Result<(u64, u64)> { let h = header(bytes)?; @@ -501,10 +499,12 @@ pub fn read_ply_mesh(bytes: &[u8], name: &str) -> Result<(Vec, Vec
Result<(Vec, u64, bool)> { - let mut out = Vec::new(); - let (n, c) = read_vertices(bytes, stride, &mut |v| out.push(v))?; - Ok((out, n, c)) + /// The vertices kept from at most `max` of them, how many the file has, and whether it has colours. + fn vertices(bytes: &[u8], max: usize) -> Result<(Vec, u64, bool)> { + let r = crate::ply_complex::read_ply_cloud(bytes, max)?; + let colors = r.colors.as_ref(); + let out = r.positions.iter().enumerate().map(|(i, p)| (*p, colors.and_then(|c| c.get(i).copied()))).collect(); + Ok((out, r.vertices, colors.is_some())) } fn binary(big: bool) -> Vec { @@ -532,7 +532,7 @@ mod tests { #[test] fn binary_little_and_big_endian_with_colours_and_other_elements() { for big in [false, true] { - let (v, n, colored) = vertices(&binary(big), 1).unwrap(); + let (v, n, colored) = vertices(&binary(big), 3).unwrap(); assert_eq!((n, colored), (3, true)); assert_eq!(v[1], ([1.5, 0.0, 0.0], Some([10, 20, 255]))); assert_eq!(v[2].0, [0.0, 2.5, -3.0]); @@ -551,7 +551,7 @@ mod tests { let src = "ply\nformat ascii 1.0\nelement vertex 4\nproperty double x\nproperty double y\nproperty double z\nproperty float red\nproperty float green\nproperty float blue\n\ element face 1\nproperty list uchar uint vertex_index\nend_header\n\ 0 0 0 1 0 0\n1 0 0 0 1 0\n1 1 0 0 0 1\n0 1 0 0.5 0.5 0.5\n4 0 1 2 3\n"; - let (v, n, colored) = vertices(src.as_bytes(), 1).unwrap(); + let (v, n, colored) = vertices(src.as_bytes(), 4).unwrap(); assert_eq!((n, colored, v.len()), (4, true, 4)); assert_eq!(v[0].1, Some([255, 0, 0])); assert_eq!(v[3], ([0.0, 1.0, 0.0], Some([128, 128, 128]))); @@ -560,7 +560,7 @@ mod tests { // Only points (as the glim maps are written): no colours, no faces. let points = "ply\nformat ascii 1.0\nelement vertex 2\nproperty float32 x\nproperty float32 y\nproperty float32 z\nend_header\n1 2 3\n4 5 6\n"; - let (v, n, colored) = vertices(points.as_bytes(), 1).unwrap(); + let (v, n, colored) = vertices(points.as_bytes(), 2).unwrap(); assert_eq!((v.len(), n, colored), (2, 2, false)); assert_eq!(v[1], ([4.0, 5.0, 6.0], None)); assert!(read_ply_mesh(points.as_bytes(), "x").is_err(), "a point cloud is not a mesh"); @@ -589,13 +589,13 @@ mod tests { for c in &cases { let r = std::panic::catch_unwind(|| { let _ = vertices(c, 1); - let _ = vertices(c, 3); + let _ = vertices(c, 1000); let _ = read_ply_mesh(c, "x"); let _ = ply_counts(c); }); assert!(r.is_ok(), "{:?}", String::from_utf8_lossy(c)); } - assert!(vertices(&good[..good.len() - 30], 1).is_err(), "a cut-off file is refused"); + assert!(vertices(&good[..good.len() - 30], 1000).is_err(), "a cut-off file is refused"); // A face naming a vertex that isn't there is left out, with a warning. let tri = "ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 2\nproperty list uchar int vertex_indices\nend_header\n0 0 0 1 0 0 0 1 0\n3 0 1 2\n3 0 1 99\n"; let (mesh, warnings) = read_ply_mesh(tri.as_bytes(), "x").unwrap(); diff --git a/crates/io/src/ply_complex.rs b/crates/io/src/ply_complex.rs new file mode 100644 index 000000000..ff8c4c290 --- /dev/null +++ b/crates/io/src/ply_complex.rs @@ -0,0 +1,147 @@ +//! A PLY file read with everything a point cloud can hold: its vertices with all their +//! properties. Positions are `x`, `y`, `z` and colours `red`, `green`, `blue`; every other scalar +//! property becomes a column named as in the file, whole-numbered when its type is an integer. A +//! comment `property: 0 name, 1 name` names the values of a whole-numbered property. Every +//! `stride`th vertex is kept. + +use solidcraft_doc::point_cloud::{Column, Complex, Floats, MAX_COLUMNS, Names}; + +use crate::ply::{Element, Kind, Rows, Scalar, header}; +use crate::{IoError, Result}; + +fn invalid(m: impl std::fmt::Display) -> IoError { + IoError::Invalid(format!("PLY: {m}")) +} + +/// What a PLY file holds, positions in the file's units. +pub(crate) struct PlyCloud { + pub positions: Vec<[f64; 3]>, + pub colors: Option>, + pub complex: Complex, + /// Vertices in the file. + pub vertices: u64, +} + +fn integer(s: Scalar) -> bool { + !matches!(s, Scalar::F32 | Scalar::F64) +} + +fn named(e: &Element, names: &[&str]) -> Option { + names.iter().find_map(|n| e.properties.iter().position(|p| p.name.eq_ignore_ascii_case(n) && matches!(p.kind, Kind::Scalar(_)))) +} + +/// The columns an element's scalar properties fill, leaving out those at `taken`. +fn columns_of(e: &Element, taken: &[usize]) -> Vec<(usize, Column)> { + e.properties + .iter() + .enumerate() + .filter(|(i, _)| !taken.contains(i)) + .filter_map(|(i, p)| match p.kind { + Kind::Scalar(s) => Some((i, Column { name: p.name.clone(), integer: integer(s), values: Floats::default() })), + Kind::List(..) => None, + }) + .collect() +} + +/// Read a PLY file's vertices, every `stride`th one of those beyond `max_points`. +pub(crate) fn read_ply_cloud(bytes: &[u8], max_points: usize) -> Result { + let h = header(bytes)?; + let vertex = h.elements.iter().find(|e| e.name == "vertex").ok_or_else(|| invalid("no `vertex` element"))?; + let stride = vertex.count.div_ceil(max_points.max(1) as u64).max(1); + let xyz = [named(vertex, &["x"]), named(vertex, &["y"]), named(vertex, &["z"])]; + let [Some(x), Some(y), Some(z)] = xyz else { return Err(invalid("the vertices have no `x`, `y` and `z`")) }; + let rgb = + [named(vertex, &["red", "r", "diffuse_red"]), named(vertex, &["green", "g", "diffuse_green"]), named(vertex, &["blue", "b", "diffuse_blue"])]; + let rgb = match rgb { + [Some(r), Some(g), Some(b)] => Some([r, g, b]), + _ => None, + }; + let mut taken = vec![x, y, z]; + taken.extend(rgb.into_iter().flatten()); + let mine = columns_of(vertex, &taken); + if mine.len() > MAX_COLUMNS { + return Err(invalid(format!("more than {MAX_COLUMNS} properties"))); + } + let body = bytes.len().saturating_sub(h.body) as u64; + let mut rows = Rows::new(&h, bytes); + let mut out = PlyCloud { positions: Vec::new(), colors: rgb.map(|_| Vec::new()), complex: Complex::default(), vertices: vertex.count }; + let mut columns: Vec<(usize, Vec, Column)> = mine.into_iter().map(|(i, c)| (i, Vec::new(), c)).collect(); + let mut row = vec![0.0f64; vertex.properties.len()]; + // The elements before the vertices are read past. + for e in h.elements.iter().take_while(|e| e.name != "vertex").chain([vertex]) { + if e.count > body { + return Err(invalid(format!("the file is too short for its {} {}", e.count, e.name))); + } + let vertices = std::ptr::eq(e, vertex); + for r in 0..e.count { + for (i, p) in e.properties.iter().enumerate() { + match p.kind { + Kind::Scalar(t) => { + let v = rows.value(t)?; + if let Some(s) = row.get_mut(i).filter(|_| vertices) { + *s = v; + } + } + Kind::List(c, t) => { + for _ in 0..rows.count(c)? { + rows.value(t)?; + } + } + } + } + if !vertices || !r.is_multiple_of(stride) { + continue; + } + let v = |i: usize| row.get(i).copied().unwrap_or(0.0); + out.positions.push([v(x), v(y), v(z)]); + if let (Some(c), Some(ks)) = (out.colors.as_mut(), rgb) { + let t = |i: usize| match vertex.properties.get(i).map(|p| p.kind) { + Some(Kind::Scalar(s)) => s.channel(v(i)), + _ => 0, + }; + c.push(ks.map(t)); + } + for (slot, values, _) in &mut columns { + values.push(v(*slot) as f32); + } + } + } + let columns: Vec = columns.into_iter().map(|(_, values, c)| Column { values: Floats(values.into()), ..c }).collect(); + // Names only for whole-numbered properties the file has, the first comment for each. + let mut names: Vec = Vec::new(); + for n in h.comments.iter().filter_map(|c| Names::parse(c)) { + let label = columns.iter().any(|c| c.name == n.property && c.integer); + if label && !names.iter().any(|m| m.property == n.property) && names.len() < MAX_COLUMNS { + names.push(n); + } + } + out.complex = Complex { columns, names }; + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_vertex_property_is_kept() { + let text = "ply\nformat ascii 1.0\ncomment role: 7 wall, -1 none\ncomment t: seconds since the start\ncomment width: 0 thin\n\ + element vertex 4\nproperty float x\nproperty float y\nproperty float z\nproperty double t\nproperty int role\nproperty float width\n\ + element face 1\nproperty list uchar int vertex_indices\nend_header\n\ + 0 0 0 0.5 7 1\n1 0 0 1.5 7 1\n1 1 0 2.5 -1 2\n0 1 0 3.5 -1 2\n4 0 1 2 3\n"; + let r = read_ply_cloud(text.as_bytes(), 10).unwrap(); + assert_eq!(r.positions.len(), 4); + let col = |n: &str| r.complex.column(n).unwrap(); + assert_eq!(&*col("t").values.0, &[0.5, 1.5, 2.5, 3.5]); + assert!(col("role").integer && !col("width").integer); + assert_eq!(&*col("role").values.0, &[7.0, 7.0, -1.0, -1.0]); + r.complex.check(4).unwrap(); + // Names for the whole-numbered `role` only: `t` is no list and `width` is not whole. + assert_eq!(r.complex.names.len(), 1); + assert_eq!(r.complex.names("role").and_then(|n| n.name(-1)), Some("none")); + // Every second vertex, with its numbers. + let half = read_ply_cloud(text.as_bytes(), 2).unwrap(); + assert_eq!((half.positions.len(), &*half.complex.column("t").unwrap().values.0), (2, &[0.5f32, 2.5][..])); + half.complex.check(2).unwrap(); + } +} diff --git a/crates/io/src/point_cloud.rs b/crates/io/src/point_cloud.rs index 3790fa9b8..90b00a46c 100644 --- a/crates/io/src/point_cloud.rs +++ b/crates/io/src/point_cloud.rs @@ -4,8 +4,8 @@ //! points than asked for is thinned evenly (every n-th point). The points are kept relative to //! the first one, in single precision. +use solidcore_record::Vec3; use solidcraft_doc::point_cloud::{MAX_COORD, MAX_POINTS}; -use solidcraft_geom::Vec3; use crate::{IoError, Result}; @@ -34,6 +34,8 @@ pub struct CloudFile { pub colors: Vec, /// Points in the file. pub source_points: u64, + /// The file's other properties of the points (PLY). + pub complex: solidcraft_doc::point_cloud::Complex, pub warnings: Vec, } @@ -77,20 +79,19 @@ pub fn read_point_cloud(bytes: &[u8], file: &str, scale: f64, max_points: usize) let ply = crate::ply::is_ply(bytes) || (is_ply_path(file) && !bytes.is_empty()); let stride; if ply { - let (count, _) = crate::ply::ply_counts(bytes)?; - stride = count.div_ceil(max as u64).max(1); - keep.out.points.reserve(count.div_ceil(stride).min(max as u64) as usize * 3); - // Colours are known once the header is read: the first vertex says. - let mut first = true; - let (count, colored) = crate::ply::read_vertices(bytes, stride, &mut |(p, rgb)| { - if first { - keep.colored = rgb.is_some(); - first = false; - } - keep.push(p, rgb); - })?; - keep.out.source_points = count; - keep.colored &= colored; + let r = crate::ply_complex::read_ply_cloud(bytes, max)?; + stride = r.vertices.div_ceil(r.positions.len().max(1) as u64).max(1); + keep.colored = r.colors.is_some(); + let colors = r.colors.unwrap_or_default(); + for (i, p) in r.positions.iter().enumerate() { + keep.push(*p, colors.get(i).copied()); + } + // A point left out would shift every number after it. + if keep.bad > 0 && !r.complex.is_empty() { + return Err(IoError::Invalid(format!("{} point(s) are not finite numbers within range", keep.bad))); + } + keep.out.source_points = r.vertices; + keep.out.complex = r.complex; } else { stride = read_xyz(bytes, &mut keep)?; } diff --git a/crates/io/src/safe_write.rs b/crates/io/src/safe_write.rs index 71f890fb1..baf309ea0 100644 --- a/crates/io/src/safe_write.rs +++ b/crates/io/src/safe_write.rs @@ -1,7 +1,8 @@ //! Crash-safe file writes: the new content goes to a temporary file next to the target, is //! flushed to disk, and replaces the target in one rename. A crash or power cut at any moment //! leaves the old file or the new one, never a torn mix. The previous version can be kept as -//! `.bak` (itself written the same way). +//! `.bak`: the old file itself under that name (a hard link) where the file system allows, +//! else a copy written the same way. use std::fs::{self, OpenOptions}; use std::io::Write; @@ -145,6 +146,45 @@ fn rename_with_retry( result } +/// Keep the file a save is about to replace as its backup without copying it: a second name for +/// the same file (a hard link) under a temporary name beside it, renamed over the old backup in +/// one step. The target keeps its name at every moment, and a save never writes into a file it +/// replaces (it renames a new one over it), so the backup stays the version it was. `Ok(false)`: +/// this file system refuses links (FAT and exFAT drives, many network shares and synced cloud +/// folders) or the old file could not be flushed first; the caller copies it then, as before. A +/// refused rename fails the save, as it does for a copy. +/// +/// What differs from a copy: the backup is the old file itself, so it keeps that file's +/// modification time (the previous save's, where a copy has the time of this save), its owner +/// and its permissions (a copy is given the same permissions), and until the target is replaced +/// the two names share one file. +fn link_backup(path: &Path) -> std::io::Result { + #[cfg(test)] + if tests::LINKS_REFUSED.with(std::cell::Cell::get) { + return Ok(false); + } + // Flushed first, as a copy is: data still only in memory would be lost with it in a power cut. + if open_to_flush(path).and_then(|f| flush(&f)).is_err() { + return Ok(false); + } + let bak_tmp = temp_beside(path, "bak"); + if fs::hard_link(path, &bak_tmp).is_err() { + return Ok(false); + } + if let Err(e) = replace_synced(&bak_tmp, &backup_path(path)) { + // Only the second name this call just made: the old file keeps its own. + let _ = fs::remove_file(&bak_tmp); + return Err(e); + } + Ok(true) +} + +/// Open the file a save replaces so it can be flushed. Windows flushes only a file opened for +/// writing (nothing is written, and it is not truncated); elsewhere reading is enough. +fn open_to_flush(path: &Path) -> std::io::Result { + OpenOptions::new().read(true).write(cfg!(windows)).open(path) +} + fn write_steps(path: &Path, bytes: &[u8], backup: bool, stop: Option) -> std::io::Result<()> { let permissions = fs::metadata(path).ok().filter(|m| m.is_file()).map(|m| m.permissions()); let tmp = temp_beside(path, "new"); @@ -156,7 +196,15 @@ fn write_steps(path: &Path, bytes: &[u8], backup: bool, stop: Option) -> s if stop == Some(Step::TempWritten) { return Ok(()); } - if backup && path.is_file() { + let linked = if backup && path.is_file() { link_backup(path) } else { Ok(false) }; + let linked = match linked { + Ok(linked) => linked, + Err(e) => { + let _ = fs::remove_file(&tmp); + return Err(e); + } + }; + if backup && !linked && path.is_file() { // Copy (not move) the old file, so the target exists at every moment. let old = fs::read(path); let bak_tmp = temp_beside(path, "bak"); @@ -178,13 +226,17 @@ fn write_steps(path: &Path, bytes: &[u8], backup: bool, stop: Option) -> s return Err(e); } sync_dir(path); - // Temporary files of saves that crashed part way (a minute old or more) go. - for t in stale_temps(path) { - if fs::metadata(&t).and_then(|m| m.modified()).ok().and_then(|m| m.elapsed().ok()).is_some_and(|age| age.as_secs() >= 60) { + remove_old_temps(path); + Ok(()) +} + +/// Temporary files of saves that crashed part way (a minute old or more) go. +fn remove_old_temps(path: &Path) { + for t in temps_beside(path) { + if fs::symlink_metadata(&t).and_then(|m| m.modified()).ok().and_then(|m| m.elapsed().ok()).is_some_and(|age| age.as_secs() >= 60) { let _ = fs::remove_file(t); } } - Ok(()) } /// Write `bytes` to `path` atomically; with `backup`, the file being replaced is kept as @@ -201,6 +253,34 @@ pub fn write_atomic(path: &Path, bytes: &[u8], backup: bool) -> std::io::Result< write_steps(&resolve_links(path)?, bytes, backup, None) } +/// Write `bytes` to the file named `path` itself, atomically: a link at `path` is never followed, +/// and what it points to is never touched. Anything there that isn't a regular file is refused. For +/// the app's own small files beside a design, which never live anywhere else. +pub fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if cfg!(target_arch = "wasm32") { + return crate::vfs::write(&path.to_string_lossy(), bytes); + } + let there = fs::symlink_metadata(path).ok(); + if there.as_ref().is_some_and(|m| !m.is_file()) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{}: not a regular file", path.display()))); + } + let tmp = temp_beside(path, "new"); + if let Err(e) = write_synced(&tmp, bytes) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + keep_permissions(&there.map(|m| m.permissions()), &tmp); + // A rename replaces the name itself, so a link put there since the check above goes, and the + // file it pointed to stays as it was. + if let Err(e) = replace_synced(&tmp, path) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + sync_dir(path); + remove_old_temps(path); + Ok(()) +} + /// Publish a complete new file without replacing an existing destination, even if another /// writer creates it after this call starts. Unsupported filesystems return an error. pub fn create_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { @@ -227,8 +307,11 @@ pub fn create_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { /// Leftover temporary files of saves that never finished (a crash part way), next to `path` /// (next to the file a link at `path` points to, where a save puts them). pub fn stale_temps(path: &Path) -> Vec { - let resolved = resolve_links(path).unwrap_or_else(|_| path.to_path_buf()); - let path = resolved.as_path(); + temps_beside(&resolve_links(path).unwrap_or_else(|_| path.to_path_buf())) +} + +/// The leftover temporary files of the file named `path` itself. +fn temps_beside(path: &Path) -> Vec { let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { return Vec::new() }; let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); let prefix = format!(".{name}."); @@ -245,6 +328,86 @@ pub fn stale_temps(path: &Path) -> Vec { mod tests { use super::*; + thread_local! { + /// This thread's saves find hard links refused ([`link_backup`]), as on a FAT drive: the + /// backup is copied, exactly as it is there. + pub(super) static LINKS_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// A new, empty folder of its own for one test (nothing in it is removed). + fn fresh_dir(tag: &str) -> PathBuf { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let d = std::env::temp_dir().join(format!("solidcraft-safe-write-{tag}-{}-{nanos}", std::process::id())); + fs::create_dir_all(&d).unwrap(); + d + } + + /// The time of a save with its backup, the backup linked against the backup copied (links + /// refused, as before hard links were used), taking turns. The file saved is + /// `SOLIDCRAFT_SAVE_BENCH_FILE` (a design), in a new folder in `SOLIDCRAFT_SAVE_BENCH_DIR` + /// (on the drive to measure; else the temporary folder). Run with `--ignored --nocapture`. + #[test] + #[ignore = "manual save measurement"] + fn save_time_with_the_backup_linked_or_copied() { + let Some(file) = std::env::var_os("SOLIDCRAFT_SAVE_BENCH_FILE") else { return }; + let bytes = fs::read(file).unwrap(); + let base = std::env::var_os("SOLIDCRAFT_SAVE_BENCH_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let d = base.join(format!("save-bench-{}-{nanos}", std::process::id())); + fs::create_dir_all(&d).unwrap(); + let p = d.join("design.solidcraft"); + write_atomic(&p, &bytes, true).unwrap(); + let rounds: usize = std::env::var("SOLIDCRAFT_SAVE_BENCH_ROUNDS").ok().and_then(|n| n.parse().ok()).unwrap_or(11); + let mut times = [Vec::new(), Vec::new()]; + for round in 0..2 * rounds { + let refused = round % 2 == 1; + LINKS_REFUSED.with(|r| r.set(refused)); + let t = std::time::Instant::now(); + write_atomic(&p, &bytes, true).unwrap(); + times[usize::from(refused)].push(t.elapsed().as_secs_f64() * 1000.0); + } + LINKS_REFUSED.with(|r| r.set(false)); + for (name, mut t) in ["linked", "copied"].into_iter().zip(times) { + t.sort_by(f64::total_cmp); + println!( + "SAVEBENCH bytes={} backup={name} median_ms={:.2} min_ms={:.2} max_ms={:.2} n={}", + bytes.len(), + t[t.len() / 2], + t[0], + t[t.len() - 1], + t.len() + ); + } + } + + /// Saves keep the previous version as the backup, stopped after any step or not, whether the + /// file system links the old file as the backup or refuses links (a FAT drive, a share) so it + /// is copied: the design file is the old version or the new one, whole, and the backup is + /// the version before it, never the one being written. + #[test] + fn the_backup_is_the_previous_version_linked_or_copied_and_a_stopped_save_keeps_both() { + for refused in [false, true] { + LINKS_REFUSED.with(|r| r.set(refused)); + let d = fresh_dir(if refused { "bak-copied" } else { "bak-linked" }); + let p = d.join("a.solidcraft"); + write_atomic(&p, b"one", true).unwrap(); + write_atomic(&p, b"two", true).unwrap(); + assert_eq!((fs::read(&p).unwrap(), fs::read(backup_path(&p)).unwrap()), (b"two".to_vec(), b"one".to_vec()), "refused {refused}"); + for stop in [Step::TempWritten, Step::BackupWritten] { + write_steps(&p, b"three", true, Some(stop)).unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"two", "{stop:?}, refused {refused}"); + let bak = fs::read(backup_path(&p)).unwrap(); + let want: &[u8] = if stop == Step::TempWritten { b"one" } else { b"two" }; + assert_eq!(bak, want, "{stop:?}, refused {refused}"); + assert!(!stale_temps(&p).is_empty(), "the stopped save's temporary file is left over"); + } + write_atomic(&p, b"four", true).unwrap(); + write_atomic(&p, b"five", true).unwrap(); + assert_eq!((fs::read(&p).unwrap(), fs::read(backup_path(&p)).unwrap()), (b"five".to_vec(), b"four".to_vec()), "refused {refused}"); + } + LINKS_REFUSED.with(|r| r.set(false)); + } + /// #5467: a lock is someone else's while it is refreshed; one left by a crash goes stale, and /// this app's own lock never counts as the design being open elsewhere. Writing a design's /// file changes its stamp. @@ -279,6 +442,104 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A link at the lock's path is neither written through nor read through, and closing the + /// design leaves it alone. A save still follows a link at the design's own path. + #[cfg(unix)] + #[test] + fn a_link_at_the_lock_path_is_never_followed() { + use crate::design_lock as lock; + use std::os::unix::fs::symlink; + let d = dir("design-lock-link"); + let design = d.join("Bracket.solidcraft"); + std::fs::write(&design, b"one").unwrap(); + let lock_file = lock::lock_path(&design); + let now = lock::now_secs(); + let mine = lock::Lock::mine(now); + + let victim = d.join("victim.txt"); + std::fs::write(&victim, b"keep me").unwrap(); + symlink(&victim, &lock_file).unwrap(); + assert!(lock::write(&design, &mine).is_err()); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep me"); + assert!(std::fs::symlink_metadata(&lock_file).unwrap().file_type().is_symlink(), "the link is refused, not replaced"); + std::fs::remove_file(&lock_file).unwrap(); + + // A link to a place with nothing there doesn't make the file either. + let missing = d.join("made-by-the-link.txt"); + symlink(&missing, &lock_file).unwrap(); + assert!(lock::write(&design, &mine).is_err()); + assert!(!missing.exists()); + std::fs::remove_file(&lock_file).unwrap(); + + // A link to a real lock is no lock: nothing is read through it, and closing leaves it. + let elsewhere = d.join("elsewhere.lock"); + std::fs::write(&elsewhere, serde_json::to_vec(&mine).unwrap()).unwrap(); + symlink(&elsewhere, &lock_file).unwrap(); + assert!(lock::read(&design).is_none()); + lock::remove(&design); + assert!(std::fs::symlink_metadata(&lock_file).is_ok() && elsewhere.exists()); + std::fs::remove_file(&lock_file).unwrap(); + + // A hard link is a regular file: its name is replaced, the other name keeps its content. + let other_name = d.join("other-name.txt"); + std::fs::write(&other_name, b"keep me too").unwrap(); + std::fs::hard_link(&other_name, &lock_file).unwrap(); + lock::write(&design, &mine).unwrap(); + assert_eq!(std::fs::read(&other_name).unwrap(), b"keep me too"); + assert!(lock::read(&design).is_some_and(|l| l.is_mine())); + std::fs::remove_file(&lock_file).unwrap(); + + // Nothing there, and no temporary file left: a plain lock is still written. + lock::write(&design, &mine).unwrap(); + assert_eq!(lock::read(&design), Some(mine)); + assert!(stale_temps(&lock_file).is_empty()); + + // The design's own link is still followed by a save. + let real = d.join("real.solidcraft"); + std::fs::write(&real, b"old").unwrap(); + let linked = d.join("linked.solidcraft"); + symlink(&real, &linked).unwrap(); + write_atomic(&linked, b"new", false).unwrap(); + assert_eq!(std::fs::read(&real).unwrap(), b"new"); + assert!(std::fs::symlink_metadata(&linked).unwrap().file_type().is_symlink()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A lock path that isn't a regular file is ignored at once. Read on a thread, so a regression + /// fails here rather than holding up the test run. + #[cfg(unix)] + #[test] + fn a_lock_path_that_is_not_a_regular_file_is_ignored_at_once() { + use crate::design_lock as lock; + use std::os::unix::fs::symlink; + let d = dir("design-lock-special"); + let design = d.join("Bracket.solidcraft"); + let lock_file = lock::lock_path(&design); + let read_soon = |design: &Path| { + let (tx, rx) = std::sync::mpsc::channel(); + let design = design.to_path_buf(); + std::thread::spawn(move || { + let _ = tx.send(lock::read(&design)); + }); + rx.recv_timeout(std::time::Duration::from_secs(10)).expect("read returned") + }; + let cases: [&dyn Fn(&Path); 3] = [&|p| symlink("/dev/zero", p).unwrap(), &|p| std::fs::create_dir(p).unwrap(), &|p| { + assert!(std::process::Command::new("mkfifo").arg(p).status().unwrap().success()) + }]; + for make in cases { + make(&lock_file); + assert!(read_soon(&design).is_none()); + assert!(lock::held_elsewhere(&design, lock::now_secs()).is_none()); + assert!(lock::write(&design, &lock::Lock::mine(lock::now_secs())).is_err()); + assert!(std::fs::symlink_metadata(&lock_file).is_ok(), "left where it is"); + let _ = std::fs::remove_file(&lock_file).or_else(|_| std::fs::remove_dir(&lock_file)); + } + // A regular file too large to be a lock is not read either. + std::fs::write(&lock_file, vec![b' '; 4097]).unwrap(); + assert!(read_soon(&design).is_none()); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn create_does_not_replace_an_existing_destination() { let d = dir("create"); @@ -471,6 +732,34 @@ mod tests { let _ = fs::remove_dir_all(&d); } + /// Where links work the backup is the old file itself, not a copy: its inode, its + /// modification time and its permissions, with one name again once the save is done; + /// where they are refused it is a copy with the old file's permissions. + #[test] + fn the_backup_is_the_old_file_linked_or_a_copy_where_links_are_refused() { + use std::os::unix::fs::MetadataExt; + for refused in [false, true] { + LINKS_REFUSED.with(|r| r.set(refused)); + let d = fresh_dir(if refused { "inode-copied" } else { "inode-linked" }); + let p = d.join("a.solidcraft"); + write_atomic(&p, b"one", true).unwrap(); + fs::set_permissions(&p, fs::Permissions::from_mode(0o640)).unwrap(); + let old = fs::metadata(&p).unwrap(); + write_atomic(&p, b"two", true).unwrap(); + let bak = fs::metadata(backup_path(&p)).unwrap(); + let new = fs::metadata(&p).unwrap(); + assert_ne!(new.ino(), old.ino(), "the design file is a new file"); + assert_eq!(bak.ino() == old.ino(), !refused, "linked: the backup is the old file"); + if !refused { + assert_eq!(bak.modified().unwrap(), old.modified().unwrap(), "it keeps the old file's time"); + } + assert_eq!((bak.nlink(), new.nlink()), (1, 1), "one name each once the save is done"); + assert_eq!((mode(&p), mode(&backup_path(&p))), (0o640, 0o640), "refused {refused}"); + assert_eq!(fs::read(backup_path(&p)).unwrap(), b"one"); + } + LINKS_REFUSED.with(|r| r.set(false)); + } + #[test] fn a_save_through_a_link_keeps_the_targets_permissions() { let d = dir("linkmode"); diff --git a/crates/io/src/sketch2d.rs b/crates/io/src/sketch2d.rs index df0e58717..9792e6f36 100644 --- a/crates/io/src/sketch2d.rs +++ b/crates/io/src/sketch2d.rs @@ -1,7 +1,8 @@ //! 2D drawing exchange for sketches: DXF (ASCII, read and write) and SVG (read). Readers produce //! plain 2D geometry in millimetres; the engine turns it into sketch curves. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; /// One imported 2D entity (millimetres, y up). #[derive(Clone, Debug, PartialEq)] diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index f76b4e752..9e474e7c0 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -5,7 +5,8 @@ use quick_xml::Reader; use quick_xml::events::{BytesStart, Event}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::sketch2d::{Geom2, MAX_DRAWING_BYTES, MAX_ENTITIES}; use crate::{IoError, Result}; @@ -525,6 +526,84 @@ pub fn read_svg(text: &str) -> Result> { Ok(out.g) } +/// The text of an SVG file's bytes: a UTF-8 byte-order mark is dropped and UTF-16 files (with +/// their mark, as some Windows tools write them) are decoded. A gzip-compressed file (`.svgz` +/// under any name) is refused with a clear error instead of being read as text (#9641). +pub fn decode_svg(bytes: &[u8]) -> Result { + if bytes.len() > MAX_DRAWING_BYTES { + return Err(IoError::Invalid("the SVG file is too large".into())); + } + if bytes.starts_with(&[0x1f, 0x8b]) { + return Err(IoError::Invalid( + "this SVG is gzip-compressed (an .svgz file); SolidCraft reads plain SVG only: save it as plain (uncompressed) SVG in a vector editor first" + .into(), + )); + } + let utf16 = |rest: &[u8], le: bool| -> String { + let units = rest.as_chunks::<2>().0.iter().map(|&pair| if le { u16::from_le_bytes(pair) } else { u16::from_be_bytes(pair) }); + char::decode_utf16(units).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)).collect() + }; + Ok(match bytes { + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + [0xFF, 0xFE, rest @ ..] => utf16(rest, true), + [0xFE, 0xFF, rest @ ..] => utf16(rest, false), + _ => String::from_utf8_lossy(bytes).into_owned(), + }) +} + +/// Why [`read_svg`] found nothing to import in `text`, in words for the person inserting it +/// (#9641): a picture embedded in an SVG, shapes drawn only from another file, or a file that is +/// not an SVG drawing at all, rather than a bare "no geometry". +pub fn svg_nothing_to_import(text: &str) -> String { + let mut rd = Reader::from_reader(text.as_bytes()); + rd.config_mut().trim_text(true); + let mut buf = Vec::new(); + let (mut svg, mut images, mut external_uses, mut elements) = (false, 0usize, 0usize, 0usize); + let mut broken = None; + while elements < MAX_ENTITIES { + match rd.read_event_into(&mut buf) { + Ok(Event::Start(e) | Event::Empty(e)) => { + elements += 1; + match e.local_name().as_ref() { + b"svg" => svg = true, + b"image" => images += 1, + b"use" => { + let a = attrs(&e); + if attr(&a, "href").is_some_and(|h| !h.trim_start().starts_with('#')) { + external_uses += 1; + } + } + _ => {} + } + } + Ok(Event::Eof) => break, + Ok(_) => {} + Err(e) => { + broken = Some(e.to_string()); + break; + } + } + buf.clear(); + } + if !svg { + return match broken { + Some(e) => format!("the file is not a readable SVG drawing ({e})"), + None => "the file is not an SVG drawing: it has no element (it may be a picture or a web page saved with an .svg name)".into(), + }; + } + if images > 0 { + return format!( + "the SVG holds only {} embedded picture{} (), not outlines, so there is nothing to draw in the sketch; trace the picture into paths in a vector editor, or save it as PNG/JPEG and use Insert > Canvas, then Canvas to Sketch", + if images == 1 { "an" } else { "several" }, + if images == 1 { "" } else { "s" } + ); + } + if external_uses > 0 { + return "the SVG's shapes are drawn with from another file, which SolidCraft does not follow; save the drawing as a single self-contained SVG first".into(); + } + "the SVG has no shapes SolidCraft reads (path, line, rect, circle, ellipse, polyline, polygon or text)".into() +} + #[cfg(test)] mod tests { use super::*; @@ -589,6 +668,36 @@ mod tests { assert!(matches!(g[0], Geom2::Line(a, b) if (a.dist(b) - 25.4).abs() < 1e-9)); } + /// #9641: a file with nothing to import says why (an embedded picture, shapes from another + /// file, not an SVG at all), and SVG files saved as UTF-16 or with a byte-order mark read. + #[test] + fn a_drawing_with_nothing_to_import_says_why() { + let picture = r##" + + "##; + assert!(read_svg(picture).unwrap().is_empty()); + let why = svg_nothing_to_import(picture); + assert!(why.contains("embedded picture") && why.contains("Canvas"), "{why}"); + let external = r#""#; + assert!(svg_nothing_to_import(external).contains("another file"), "{}", svg_nothing_to_import(external)); + assert!(svg_nothing_to_import("Not found").contains("not an SVG drawing")); + assert!(svg_nothing_to_import("").contains("no shapes")); + + let square = r#""#; + let le: Vec = [0xFF, 0xFE].into_iter().chain(square.encode_utf16().flat_map(u16::to_le_bytes)).collect(); + let be: Vec = [0xFE, 0xFF].into_iter().chain(square.encode_utf16().flat_map(u16::to_be_bytes)).collect(); + let bom: Vec = [0xEF, 0xBB, 0xBF].into_iter().chain(square.bytes()).collect(); + for bytes in [le, be, bom, square.as_bytes().to_vec()] { + let text = decode_svg(&bytes).unwrap(); + assert_eq!(read_svg(&text).unwrap().len(), 4, "{bytes:?}"); + } + let gz = decode_svg(&[0x1f, 0x8b, 8, 0, 0, 0]).unwrap_err().to_string(); + assert!(gz.contains("gzip"), "{gz}"); + for bytes in [&[0xFF, 0xFE, 0x3C][..], &[0xFE, 0xFF, 0xD8, 0x00][..], &[][..]] { + assert!(decode_svg(bytes).is_ok()); + } + } + /// A transform that scales a shape past the range of `f64` is refused with a clear error /// instead of handing the sketch an infinite curve (solidcraft#5020). #[test] diff --git a/crates/io/src/threemf.rs b/crates/io/src/threemf.rs index c2c768baf..02a7bc9b8 100644 --- a/crates/io/src/threemf.rs +++ b/crates/io/src/threemf.rs @@ -15,13 +15,14 @@ //! `Metadata/model_settings.config`), and those names are used. Packages are untrusted: sizes, //! entry counts, model parts, mesh sizes and component nesting are capped. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, HashMap}; use std::fmt::Write as _; use std::io::{Cursor, Read, Write}; use quick_xml::Reader; use quick_xml::events::{BytesStart, Event}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::{IoError, Result}; diff --git a/crates/io/src/urdf.rs b/crates/io/src/urdf.rs index c1ad07b9a..a5c56e8c8 100644 --- a/crates/io/src/urdf.rs +++ b/crates/io/src/urdf.rs @@ -9,11 +9,13 @@ //! `L = T_A · F_a` and the parent-side joint frame `L · M(q)`, the chain inverted (reversed, axes //! negated, so each URDF value still equals SolidCraft's). +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque}; +use solidcore_record::Vec3; use solidcraft_doc::joints::{self, Joint, JointKind}; use solidcraft_doc::{Document, IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, ModelState, Occurrence, apply_point, mat_inverse, mat_mul}; -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::Mesh; use crate::{IoError, Result, export_mesh, stl_binary, weld, weld_eps}; diff --git a/crates/io/src/vfs.rs b/crates/io/src/vfs.rs index 2c6f6c760..ac21126dd 100644 --- a/crates/io/src/vfs.rs +++ b/crates/io/src/vfs.rs @@ -46,6 +46,13 @@ mod imp { touched(); std::fs::metadata(path).map(|m| m.len()) } + /// The file's modification time and size (`None`: not there, or the platform keeps no times). + pub fn stamp(path: &str) -> Option<(std::time::SystemTime, u64)> { + check(path).ok()?; + touched(); + let meta = std::fs::metadata(path).ok()?; + Some((meta.modified().ok()?, meta.len())) + } pub fn exists(path: &str) -> bool { check(path).is_ok() && { touched(); @@ -108,6 +115,10 @@ mod imp { pub fn len(path: &str) -> Result { FILES.with(|f| f.borrow().get(path).map(|b| b.len() as u64)).ok_or_else(|| missing(path)) } + /// Browser storage keeps no modification times. + pub fn stamp(_path: &str) -> Option<(std::time::SystemTime, u64)> { + None + } pub fn exists(path: &str) -> bool { FILES.with(|f| f.borrow().contains_key(path)) } @@ -566,6 +577,12 @@ pub fn design_path_is_file(path: &str, design: Option<&str>) -> Option { design_path_refusal(path, design).is_none().then(|| is_file(path)) } +/// [`stamp`] of a path a design names; `None` when [`check_design_path`] refuses it, which asks +/// nothing of the disk or the network. +pub fn design_path_stamp(path: &str, design: Option<&str>) -> Option<(std::time::SystemTime, u64)> { + design_path_refusal(path, design).is_none().then(|| stamp(path)).flatten() +} + /// The checks the layers below ask before reading a file a design names (sketch text's font /// files). Done once; every session and agent scope does it. pub fn install_checks() { diff --git a/crates/kernel/Cargo.toml b/crates/kernel/Cargo.toml index 764db89f6..bf07fc5b8 100644 --- a/crates/kernel/Cargo.toml +++ b/crates/kernel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "solidcraft-kernel" -description = "SolidCraft B-rep kernel boundary: solids, extrude/revolve/booleans/fillets, tessellation, measures and STEP, behind our own API (implemented with truck)" +description = "SolidCraft B-rep kernel boundary: solids, extrude/revolve/booleans/fillets, meshes, measures and STEP, behind our own API (implemented with solidcore)" version.workspace = true edition.workspace = true license.workspace = true @@ -9,16 +9,15 @@ license.workspace = true workspace = true [dependencies] +solidcore-record = { workspace = true } solidcraft-geom = { workspace = true } +solidcraft-smlib = { workspace = true } +solidcraft-profile = { workspace = true } +solidcraft-step = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } -truck-modeling = { workspace = true } -truck-shapeops = { workspace = true } -truck-meshalgo = { workspace = true } -truck-stepio = { workspace = true } -truck-topology = { workspace = true } spade = { workspace = true } web-time = { workspace = true } @@ -26,7 +25,5 @@ web-time = { workspace = true } rayon = { workspace = true } [dev-dependencies] -# The vendored crate tests never build in CI, so its equivalence checks run from kernel tests. -# Resolver 3 keeps this dev-only feature out of shipped builds. -truck-meshalgo = { workspace = true, features = ["test-hooks"] } +solidcraft-profile = { workspace = true, features = ["enabled"] } proptest = { version = "1", default-features = false, features = ["std"] } diff --git a/crates/kernel/examples/step_board_fixture.rs b/crates/kernel/examples/step_board_fixture.rs new file mode 100644 index 000000000..95bb6f38e --- /dev/null +++ b/crates/kernel/examples/step_board_fixture.rs @@ -0,0 +1,82 @@ +//! A board-like assembly for issue #883, the worst case for a large STEP import: every +//! component is its own product with a package body and its own pins (nothing shared). +//! +//! ```sh +//! SOLIDCRAFT_STEP_PCB_COMPONENTS=600 SOLIDCRAFT_STEP_PCB_PINS=15 \ +//! cargo run --release -p solidcraft-kernel --example step_board_fixture -- board.step +//! ``` +//! +//! 600 components of 15 pins give 52 MB. The defaults are 500 and 16; the path defaults to +//! `board.step`. + +fn main() { + if let Err(e) = run::main() { + eprintln!("step_board_fixture: {e}"); + std::process::exit(1); + } +} + +mod run { + use solidcore_record::Vec3; + use solidcraft_kernel::{Body, ExportBody, ExportProduct, StepHeader, box_solid, cylinder, fillet, step_export_products}; + + /// A count from `SOLIDCRAFT_`, or `default` when it is unset. + fn count(name: &str, default: usize) -> Result { + solidcraft_geom::env::var(name).map_or(Ok(default), |s| s.parse().map_err(|e| format!("SOLIDCRAFT_{name}: {e}"))) + } + + /// A package: a box with its vertical edges and then its top edges rounded (left sharp where + /// a round does not build). + fn package(w: f64, d: f64, h: f64) -> Result { + let b = box_solid(Vec3::ZERO, Vec3::new(w, d, h)).map_err(|e| e.to_string())?; + let vertical = [Vec3::new(0.0, 0.0, h / 2.0), Vec3::new(w, 0.0, h / 2.0), Vec3::new(w, d, h / 2.0), Vec3::new(0.0, d, h / 2.0)]; + let top = [Vec3::new(w / 2.0, 0.0, h), Vec3::new(w, d / 2.0, h), Vec3::new(w / 2.0, d, h), Vec3::new(0.0, d / 2.0, h)]; + let b = fillet(&b, &vertical, 0.3).unwrap_or(b); + Ok(fillet(&b, &top, 0.1).unwrap_or(b)) + } + + pub fn main() -> Result<(), String> { + let components = count("STEP_PCB_COMPONENTS", 500)?; + let pins = count("STEP_PCB_PINS", 16)?; + let path = std::env::args().nth(1).unwrap_or_else(|| "board.step".into()); + let mut owned: Vec> = Vec::new(); + for c in 0..components { + let w = 4.0 + (c % 7) as f64 * 0.37; + let d = 3.0 + (c % 5) as f64 * 0.29; + let mut bodies = vec![package(w, d, 1.2 + (c % 3) as f64 * 0.1)?]; + for p in 0..pins { + let side = if p % 2 == 0 { -0.6 } else { d + 0.6 }; + let x = 0.3 + (p / 2) as f64 * (w - 0.6) / (pins / 2).max(1) as f64 + c as f64 * 1e-4; + bodies.push(cylinder(Vec3::new(x, side, -1.5), Vec3::Z, 0.25, 2.0 + (p % 3) as f64 * 0.01).map_err(|e| e.to_string())?); + } + owned.push(bodies); + } + let mut products: Vec = owned + .iter() + .enumerate() + .map(|(c, bodies)| ExportProduct { + name: format!("U{c}"), + bodies: bodies + .iter() + .enumerate() + .map(|(k, b)| ExportBody { name: format!("U{c}_{k}"), body: b, color: Some([0.2, 0.2, 0.2]) }) + .collect(), + children: Vec::new(), + }) + .collect(); + let side = (components as f64).sqrt().ceil() as usize; + let children = (0..components) + .map(|c| { + let (x, y) = ((c % side) as f64 * 12.0, (c / side) as f64 * 10.0); + (c, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [x, y, 1.6, 1.0]], format!("U{c}")) + }) + .collect(); + products.push(ExportProduct { name: "Board".into(), bodies: Vec::new(), children }); + let root = products.len() - 1; + let header = StepHeader { file_name: "board.step".into(), ..Default::default() }; + let text = step_export_products(&products, root, &header).map_err(|e| e.to_string())?; + std::fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?; + println!("wrote {path}: {} bytes, {components} components", text.len()); + Ok(()) + } +} diff --git a/crates/kernel/src/assemble.rs b/crates/kernel/src/assemble.rs new file mode 100644 index 000000000..4ae6b5014 --- /dev/null +++ b/crates/kernel/src/assemble.rs @@ -0,0 +1,482 @@ +//! Bodies built face by face on the schema 4 record: an operation that rebuilds part of a body +//! from its own topology (an emboss on a cylinder, a raised band, a deleted face healed by its +//! neighbours) starts from the body's record, takes faces away, adds faces bounded by new or +//! existing edges, and finishes into a record in canonical order (docs/native-brep.md): pcurves +//! from the record's one routine ([`solidcraft_geom::brep::pcurve`]) for every new use, the +//! record's own for every use kept, edge uses, regions and shells. The body is that record. +//! +//! Faces keep the record's convention as the operation gives them: each face's loops are seen +//! from the side the material is not on (the outward side), the outer loop counter-clockwise +//! and holes clockwise there; [`Assembly::finish`] stores them relative to the surface's natural +//! normal, as the record does. + +use solidcore_record::Vec3; +use solidcore_record::brep::{ + Brep, Curve, Curve2, Edge, Face, Frame, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell, Surface, VERSION, Vertex, +}; +use solidcraft_geom::brep::form; +use solidcraft_geom::brep::pcurve::{EdgeUse, pcurves_within}; +use solidcraft_geom::prelude::*; + +use crate::body::Body; +use crate::history::{EdgeOrigin, FaceProv}; +use crate::{KernelError, Result}; + +fn invalid(m: impl std::fmt::Display) -> KernelError { + KernelError::Failed(format!("rebuilding the B-rep: {m}")) +} + +/// One edge of the assembly: its curve on `interval`, from `vertices[0]` to `vertices[1]`. +#[derive(Clone, Debug)] +pub(crate) struct AEdge { + pub curve: Curve, + /// The NURBS form the edge's parameter is on, as the record's `Edge::nurbs`. + pub nurbs: Option, + pub interval: [f64; 2], + pub vertices: [u32; 2], + pub tolerance: f64, + /// The source record's edge this edge is, kept as it was. + pub source: Option, + /// The source record's edges this new edge is (a piece of, or the moved) edge of. + pub of: Vec, +} + +/// One use of an edge in a face's loop: the loop runs along it from its start (`forward`) or +/// from its end, with the source record's pcurve where the use is one the record had. +#[derive(Clone, Debug)] +pub(crate) struct AUse { + pub edge: u32, + pub forward: bool, + pub given: Option, +} + +/// One face of the assembly: its surface, whether its natural normal points out of the +/// material, its loops (outer first) seen from outside, and the shell it belongs to (a shell of +/// the source record, by index). +#[derive(Clone, Debug)] +pub(crate) struct AFace { + pub surface: Surface, + /// The NURBS form the face's parameters are on, as the record's `Face::nurbs`: its domain, + /// pcurves and `natural_out` are about this surface when it is given. + pub nurbs: Option, + pub natural_out: bool, + pub loops: Vec>, + pub shell: usize, + /// The source record's face whose surface and parameter box this face keeps. + pub domain: Option<[[f64; 2]; 2]>, +} + +/// A body taken apart: vertices, edges and faces that [`Assembly::finish`] builds into a record. +#[derive(Clone, Debug)] +pub(crate) struct Assembly { + pub tolerance: f64, + pub vertices: Vec, + pub edges: Vec, + /// `None`: a face taken away. + pub faces: Vec>, + /// The source's regions, by shell index (shells keep their indices; a shell left with no + /// face is dropped). + regions: Vec, + shells: usize, +} + +/// A finished record, with where each face of the assembly went in it (`None`: taken away). +pub(crate) struct Finished { + pub record: Brep, + pub faces: Vec>, + /// For each edge of the record, the assembly edge it is. + pub edges: Vec, +} + +impl Assembly { + /// The record `b` taken apart, every face and edge as it is (face i and edge i of the + /// assembly are the record's). Only face shells: a record with wire or vertex shells is not + /// rebuilt here. + pub(crate) fn from_record(b: &Brep) -> Result { + let mut faces: Vec> = vec![None; b.faces.len()]; + for (s, shell) in b.shells.iter().enumerate() { + let Shell::Faces { faces: uses, wires } = shell else { return Err(invalid("a wire or vertex shell")) }; + if !wires.is_empty() { + return Err(invalid("wire edges inside a shell")); + } + for of in uses { + let f = b.faces.get(of.face as usize).ok_or_else(|| invalid("face reference"))?; + let mut loops = Vec::with_capacity(f.loops.len()); + for l in &f.loops { + let Loop::Edges { edges } = l else { return Err(invalid("a vertex loop")) }; + let mut lp: Vec = edges.iter().map(|u| AUse { edge: u.edge, forward: u.forward, given: Some(u.pcurve.clone()) }).collect(); + // Stored about the natural normal; the assembly sees loops from outside. + if !of.forward { + reverse(&mut lp); + } + loops.push(lp); + } + let slot = faces.get_mut(of.face as usize).ok_or_else(|| invalid("face reference"))?; + if slot.is_some() { + return Err(invalid("a face used by two shells")); + } + *slot = Some(AFace { + surface: f.surface.clone(), + nurbs: f.nurbs.clone(), + natural_out: of.forward, + loops, + shell: s, + domain: Some(f.domain), + }); + } + } + if faces.iter().any(Option::is_none) { + return Err(invalid("a face no shell uses")); + } + let edges = b + .edges + .iter() + .enumerate() + .map(|(i, e)| AEdge { + curve: e.curve.clone(), + nurbs: e.nurbs.clone(), + interval: e.interval, + vertices: e.vertices, + tolerance: e.tolerance, + source: Some(i), + of: Vec::new(), + }) + .collect(); + Ok(Assembly { tolerance: b.tolerance, vertices: b.vertices.clone(), edges, faces, regions: b.regions.clone(), shells: b.shells.len() }) + } + + /// A new vertex at `p`. + pub(crate) fn vertex(&mut self, p: Vec3) -> Result { + if !p.is_finite() { + return Err(invalid("a vertex off the finite range")); + } + self.vertices.push(Vertex { point: [p.x, p.y, p.z], tolerance: self.tolerance }); + index(self.vertices.len() - 1) + } + + /// A vertex's point. + pub(crate) fn point(&self, v: u32) -> Option { + self.vertices.get(v as usize).map(|v| Vec3::from(v.point)) + } + + /// A new edge on `curve` over `interval`, from `a` to `b`. + pub(crate) fn edge(&mut self, curve: Curve, interval: [f64; 2], a: u32, b: u32) -> Result { + self.edges.push(AEdge { curve, nurbs: None, interval, vertices: [a, b], tolerance: self.tolerance, source: None, of: Vec::new() }); + index(self.edges.len() - 1) + } + + /// A new straight edge from vertex `a` to vertex `b` (t from 0 to 1). + pub(crate) fn line(&mut self, a: u32, b: u32) -> Result { + let (Some(p), Some(q)) = (self.point(a), self.point(b)) else { return Err(invalid("vertex reference")) }; + if p.dist(q) <= self.tolerance { + return Err(invalid("a line of no length")); + } + self.edge(Curve::Line { start: [p.x, p.y, p.z], end: [q.x, q.y, q.z] }, [0.0, 1.0], a, b) + } + + /// Record that edge `e` is (a piece of, or the moved) edge `of` of the assembly: the source + /// edges under `of` are under `e`. + pub(crate) fn piece(&mut self, e: u32, of: u32) { + let roots: Vec = match self.edges.get(of as usize) { + Some(x) => x.source.map(|s| vec![s]).unwrap_or_else(|| x.of.clone()), + None => Vec::new(), + }; + if let Some(x) = self.edges.get_mut(e as usize) { + for r in roots { + if !x.of.contains(&r) { + x.of.push(r); + } + } + } + } + + /// A new face. + pub(crate) fn face(&mut self, face: AFace) { + self.faces.push(Some(face)); + } + + /// Where an edge use starts and ends (in the loop's direction). + pub(crate) fn ends(&self, u: &AUse) -> Option<(u32, u32)> { + let e = self.edges.get(u.edge as usize)?; + let [a, b] = e.vertices; + Some(if u.forward { (a, b) } else { (b, a) }) + } + + /// The record of the faces left and added, in canonical order (`Brep::canonical`), checked: + /// each face's loops stored relative to its surface's natural normal with their pcurves and + /// parameter box, shells and regions as the source's (a region whose outer shell lost every + /// face is gone). + pub(crate) fn finish(&self) -> Result { + // The faces left and added, in assembly order, each in its shell. + let kept: Vec = self.faces.iter().enumerate().filter(|(_, f)| f.is_some()).map(|(i, _)| i).collect(); + let mut by_shell: Vec> = vec![Vec::new(); self.shells]; + let mut faces: Vec = Vec::with_capacity(kept.len()); + let mut sides: Vec = Vec::with_capacity(kept.len()); + let formed = self.formed()?; + for (k, &i) in kept.iter().enumerate() { + let f = self.faces.get(i).and_then(Option::as_ref).ok_or_else(|| invalid("face reference"))?; + by_shell.get_mut(f.shell).ok_or_else(|| invalid("shell reference"))?.push(index(k)?); + faces.push(self.stored(i, f, &formed)?); + sides.push(f.natural_out); + } + let shells = by_shell + .iter() + .map(|members| { + let faces = + members.iter().map(|&k| Ok(OrientedFace { face: k, forward: *sides.get(k as usize).ok_or_else(|| invalid("face reference"))? })); + Ok(Shell::Faces { faces: faces.collect::>()?, wires: Vec::new() }) + }) + .collect::>>()?; + let used = |s: u32| by_shell.get(s as usize).is_some_and(|f| !f.is_empty()); + let mut regions: Vec = Vec::new(); + for region in &self.regions { + // A bounded region whose outer shell went is gone (its faces were all taken away). + if regions.is_empty() || region.shells.first().is_some_and(|s| used(*s)) { + regions.push(Region { shells: region.shells.iter().copied().filter(|s| used(*s)).collect(), void: region.void }); + } + } + let edges = self.edges.iter().zip(&formed.edges).map(|(a, f)| Edge { + nurbs: f.nurbs.clone(), + curve: f.label.clone(), + interval: f.interval, + vertices: a.vertices, + tolerance: a.tolerance, + uses: Vec::new(), + }); + let loose = + Brep { version: VERSION, tolerance: self.tolerance, regions, shells, faces, edges: edges.collect(), vertices: self.vertices.clone() }; + let part = loose.canonical().map_err(invalid)?; + solidcraft_geom::brep::geometry::check(&part.brep).map_err(invalid)?; + let mut face_map: Vec> = vec![None; self.faces.len()]; + for (c, &k) in part.faces.iter().enumerate() { + if let Some(slot) = kept.get(k as usize).and_then(|i| face_map.get_mut(*i)) { + *slot = Some(c); + } + } + Ok(Finished { record: part.brep, faces: face_map, edges: part.edges.iter().map(|e| *e as usize).collect() }) + } + + /// Which faces and edges go on a NURBS form, and theirs. A cylinder, cone, sphere, torus or + /// revolution face without one takes one where none of its uses brings its own pcurve (those + /// are on its label's parameters); an edge without one takes one (a circle about such a + /// face's axis labelled on its frame, `form::edge`) where none of its uses brings a pcurve + /// and every face it bounds is a plane, a spline or on a form. + fn formed(&self) -> Result { + let takes: Vec = self + .faces + .iter() + .map(|f| { + f.as_ref() + .is_some_and(|f| f.nurbs.is_none() && form::frame_of(&f.surface).is_some() && f.loops.iter().flatten().all(|u| u.given.is_none())) + }) + .collect(); + let n = self.edges.len(); + let (mut frames, mut open, mut given): (Vec>, Vec, Vec) = (vec![Vec::new(); n], vec![true; n], vec![false; n]); + for (f, takes) in self.faces.iter().zip(&takes) { + let Some(f) = f else { continue }; + let on_form = f.nurbs.is_some() + || *takes + || matches!( + f.surface, + Surface::Plane { .. } | Surface::PlaneThrough { .. } | Surface::Spline { .. } | Surface::RationalSpline { .. } + ); + let frame = if *takes { form::frame_of(&f.surface) } else { None }; + for u in f.loops.iter().flatten() { + let e = u.edge as usize; + if u.given.is_some() + && let Some(g) = given.get_mut(e) + { + *g = true; + } + if !on_form && let Some(o) = open.get_mut(e) { + *o = false; + } + if let (Some(fr), Some(slot)) = (&frame, frames.get_mut(e)) { + slot.push(fr.clone()); + } + } + } + let mut edges = Vec::with_capacity(n); + for (i, a) in self.edges.iter().enumerate() { + let free = a.nurbs.is_none() && !given.get(i).copied().unwrap_or(true) && open.get(i).copied().unwrap_or(false); + let fr = frames.get(i).map(Vec::as_slice).unwrap_or(&[]); + edges.push(match (free, form::edge(&a.curve, a.interval, fr, self.tolerance)) { + (true, Some((label, iv, Some((nurbs, interval))))) => { + FormedEdge { label: label.clone(), label_interval: iv, nurbs: Some(nurbs), interval } + } + _ => FormedEdge { label: a.curve.clone(), label_interval: a.interval, nurbs: a.nurbs.clone(), interval: a.interval }, + }); + } + Ok(Formed { faces: takes, edges }) + } + + /// Face `i` as the record stores it: its loops relative to its surface's natural normal, each + /// use with its pcurve (the record's own where the use kept one), on its NURBS form (its own, + /// or the one [`Assembly::formed`] gives it, over its boundary's extent), and its parameter box. + fn stored(&self, i: usize, f: &AFace, formed: &Formed) -> Result { + let loops: Vec> = f + .loops + .iter() + .map(|l| { + let mut l = l.clone(); + if !f.natural_out { + reverse(&mut l); + } + l + }) + .collect(); + let uses: Vec>> = loops + .iter() + .map(|l| { + l.iter() + .map(|u| { + let e = self.edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; + let fe = formed.edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; + Ok(EdgeUse { + edge: u.edge, + curve: fe.nurbs.as_ref().unwrap_or(&fe.label), + interval: fe.interval, + forward: u.forward, + tolerance: e.tolerance, + given: u.given.as_ref(), + }) + }) + .collect::>>() + }) + .collect::>()?; + // A face taking a form: its form over its boundary's extent on its label. + let (nurbs, kept) = if formed.faces.get(i).copied().unwrap_or(false) { + let boundary: Vec> = loops + .iter() + .map(|l| l.iter().filter_map(|u| formed.edges.get(u.edge as usize).map(|e| (&e.label, e.label_interval, u.forward))).collect()) + .collect(); + let extent = form::extent(&f.surface, &boundary).ok_or_else(|| invalid(format!("face {i}: its boundary is not on its surface")))?; + let (n, d) = form::surface(&f.surface, extent).ok_or_else(|| invalid(format!("face {i}: more than one turn")))?; + (Some(n), Some(d)) + } else { + (f.nurbs.clone(), f.domain) + }; + let on = nurbs.as_ref().unwrap_or(&f.surface); + let pcurves = pcurves_within(on, &uses, self.tolerance, kept).map_err(|e| invalid(format!("face {i}: {e}")))?; + let domain = domain_of(on, &pcurves, kept).ok_or_else(|| invalid(format!("face {i}: no parameter box")))?; + let stored = loops + .iter() + .zip(&pcurves) + .map(|(l, pc)| Loop::Edges { + edges: l.iter().zip(pc).map(|(u, pcurve)| OrientedEdge { edge: u.edge, forward: u.forward, pcurve: pcurve.clone() }).collect(), + }) + .collect(); + Ok(Face { nurbs, surface: f.surface.clone(), domain, loops: stored }) + } +} + +/// What [`Assembly::formed`] decides: which faces take a NURBS form, and each edge's label (a +/// circle relabelled on a face's frame), its interval there, and its form with its interval. +struct Formed { + faces: Vec, + edges: Vec, +} + +struct FormedEdge { + label: Curve, + label_interval: [f64; 2], + nurbs: Option, + interval: [f64; 2], +} + +/// Reverse a loop: the same edges, the other way round. +fn reverse(l: &mut [AUse]) { + l.reverse(); + for u in l { + u.forward = !u.forward; + } +} + +fn index(i: usize) -> Result { + u32::try_from(i).map_err(|_| invalid("too many items")) +} + +/// A face's parameter box: the source face's where it kept it, else the box of its pcurves' +/// control points (which holds the curves), inside the surface's natural domain. +fn domain_of(surface: &Surface, pcurves: &[Vec], kept: Option<[[f64; 2]; 2]>) -> Option<[[f64; 2]; 2]> { + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for c in pcurves.iter().flatten() { + let points: Vec<[f64; 2]> = match c { + Curve2::Spline { points, .. } => points.clone(), + Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().map(|h| [h[0] / h[2], h[1] / h[2]]).collect(), + }; + for p in points { + for d in 0..2 { + if let (Some(l), Some(h), Some(x)) = (lo.get_mut(d), hi.get_mut(d), p.get(d)) { + *l = l.min(*x); + *h = h.max(*x); + } + } + } + } + if let Some(k) = kept { + // The source's box, grown to hold any loop the face has now. + for d in 0..2 { + if let (Some(l), Some(h), Some(r)) = (lo.get_mut(d), hi.get_mut(d), k.get(d)) { + *l = l.min(r[0]); + *h = h.max(r[1]); + } + } + } + let natural = solidcraft_geom::brep::label::surface_natural(surface); + let mut out = [[0.0; 2]; 2]; + for d in 0..2 { + let (mut a, mut b) = (*lo.get(d)?, *hi.get(d)?); + if !(a.is_finite() && b.is_finite()) { + return None; + } + match natural.get(d)? { + Natural::Periodic => b = b.min(a + std::f64::consts::TAU), + Natural::Range(x, y) => { + a = a.max(*x); + b = b.min(*y); + } + } + if !(a < b) { + return None; + } + *out.get_mut(d)? = [a, b]; + } + Some(out) +} + +/// The body of `finished`, built from the one operand `from`, with the history whose faces are +/// `faces` (in the assembly's face order, taken-away faces skipped): each kept edge the operand +/// edge it is, each re-made one the operand edges it is a piece of, each new one where its two +/// faces meet ([`crate::record::of_faces`]). The body is the finished record, so its faces and +/// edges are numbered as the record's. +pub(crate) fn body_with_history(finished: Finished, assembly: &Assembly, from: &Body, faces: Vec) -> Result { + // The provenance of each record face, from the assembly's face order. + let mut provs: Vec> = vec![None; finished.record.faces.len()]; + let mut given = faces.into_iter(); + for k in finished.faces.iter().flatten() { + let p = given.next().ok_or_else(|| invalid("history: fewer faces than the body"))?; + *provs.get_mut(*k).ok_or_else(|| invalid("history: face"))? = Some(p); + } + let faces: Option> = provs.into_iter().collect(); + let edges: Vec> = finished + .edges + .iter() + .map(|a| match assembly.edges.get(*a) { + Some(AEdge { source: Some(edge), .. }) => crate::record::pieces_of(0, [*edge]), + Some(AEdge { of, .. }) => crate::record::pieces_of(0, of.iter().copied()), + None => Vec::new(), + }) + .collect(); + let body = Body::from_record(finished.record)?; + Ok(crate::record::attach(body, &crate::record::counts(&[from]), faces, &edges)) +} + +/// Whether the face `face` of `b` has its natural normal out of the material. +pub(crate) fn natural_out(b: &Brep, face: usize) -> Option { + b.shells.iter().find_map(|s| match s { + Shell::Faces { faces, .. } => faces.iter().find(|f| f.face as usize == face).map(|f| f.forward), + _ => None, + }) +} diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 1f9c30cea..0cb99e70d 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -1,28 +1,21 @@ -//! Edge fillets and chamfers as a local B-rep operation. +//! Edge fillets and chamfers. SMLib blends exactly the picked edges in one call +//! ([`crate::blend_smlib`]): the blend faces, the corners where blends meet (a sphere, a patch, a +//! bevel or a mitre, as its fillet corners choose) and the end faces rebuilt round them. A blend +//! whose contact lines would leave the faces it rolls on is SMLib's refusal, reported as +//! [`KernelError::TooLarge`]. A tangent chain is the caller's to select ([`tangent_chain`]). //! -//! Supported locally: a straight edge between two planar faces whose two end vertices each -//! touch exactly one more planar face. The offset rails intersect the end planes, including -//! sloped walls. The end faces get an arc (round fillet), a quintic (G2 fillet) or a line -//! (chamfer) at the corner, and a cylindrical, quintic or planar face is inserted. -//! The result is exact. Edges meeting at an already blended corner, curved edges and other -//! configurations are reported as not supported yet. +//! The helpers here read a body's schema 4 record: planar faces' outward normals, the direction +//! into a face across an edge, an edge's tangent at its ends. -use std::collections::HashMap; +use solidcraft_geom::prelude::*; +use std::collections::BTreeSet; -use solidcraft_geom::{Aabb3, Vec3}; -use truck_modeling::{self as mt, builder}; +use solidcore_record::Vec3; +use solidcore_record::brep::{Brep, Curve, Loop, OrientedEdge, Shell, Surface}; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; -use crate::body::{Body, Solid, from_p3, p3, v3}; -use crate::history::{FaceOrigin, History}; -use crate::record::{self, Rebuild}; -use crate::{KernelError, Result, guard}; - -#[derive(Clone, Copy, PartialEq)] -enum Shape { - Round, - Flat, - Curvature, -} +use crate::body::Body; +use crate::{KernelError, Result}; pub(crate) fn unsupported(msg: &str) -> KernelError { KernelError::Failed(format!("not supported yet: {msg}")) @@ -33,1084 +26,183 @@ pub(crate) fn too_large(msg: &str) -> KernelError { KernelError::TooLarge(msg.into()) } -pub(crate) fn vtx(v: &mt::Vertex) -> Vec3 { - from_p3(v.point()) +/// The note on a blend's refusal as too large that names the largest `size` (radius, distance) +/// that fits: "the largest radius that fits is 3 mm". The kernel's own sized refusals and a fillet +/// feature's search for the size ([`fillet_max`]) word it alike. +pub fn largest_fit_note(size: &str, largest: f64) -> String { + format!("the largest {size} that fits is {} mm", trimmed_mm(largest)) } -/// Outward unit normal of a planar face (from its oriented surface), if planar. -pub(crate) fn plane_normal(f: &mt::Face) -> Option { - match f.oriented_surface() { - mt::Surface::Plane(p) => { - let n = p.normal(); - Vec3::new(n.x, n.y, n.z).normalized() - } - _ => None, - } +/// Whether a refusal already names the largest size that fits ([`largest_fit_note`]). +pub fn names_largest_fit(why: &str) -> bool { + why.contains("that fits is ") } -/// Replace edges in a face's oriented boundary (by id, keeping orientation), and insert extra -/// edges where consecutive edges no longer connect. -pub(crate) fn rebuild_face(f: &mt::Face, subst: &HashMap, connectors: &[mt::Edge]) -> Result { - rebuild_face_dropping(f, subst, &[], connectors) +/// `why` with the largest size that fits it names ([`largest_fit_note`]) replaced by `largest`: +/// solidcore names the size less a margin (34.99 where 35 builds), a feature's search the +/// largest it built. `why` itself where it names none. +pub fn with_fit_note(why: &str, size: &str, largest: f64) -> String { + let Some(start) = why.find("the largest ") else { return why.to_owned() }; + let Some(len) = why.get(start..).and_then(|rest| rest.find(" mm")) else { return why.to_owned() }; + let (head, tail) = (why.get(..start).unwrap_or_default(), why.get(start + len + 3..).unwrap_or_default()); + format!("{head}{}{tail}", largest_fit_note(size, largest)) } -/// [`rebuild_face`], also leaving out the `dropped` edges (consumed by a blend). -fn rebuild_face_dropping(f: &mt::Face, subst: &HashMap, dropped: &[mt::EdgeID], connectors: &[mt::Edge]) -> Result { - let mut wires = Vec::new(); - for w in f.absolute_boundaries() { - let mut edges: Vec = Vec::new(); - for e in w.edge_iter().filter(|e| !dropped.contains(&e.id())) { - let ne = match subst.get(&e.id()) { - Some(n) => { - // `n` was built in the orientation of the stored edge; match this use. - let stored_forward = e.front() == e.absolute_front(); - if stored_forward { n.clone() } else { n.inverse() } +/// `v` to the micrometre, without trailing zeros. +pub(crate) fn trimmed_mm(v: f64) -> String { + let s = format!("{v:.6}"); + s.trim_end_matches('0').trim_end_matches('.').to_string() +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// A body's record as the blends' checks read it: the record and each face's side in its shell. +pub(crate) struct Faces { + pub(crate) rec: Brep, + /// Whether each face's outward normal is its surface's natural normal (`None`: in no face shell). + forward: Vec>, +} + +impl Faces { + pub(crate) fn of(body: &Body) -> Result { + let rec = crate::native::brep_record(body)?; + let mut forward = vec![None; rec.faces.len()]; + for sh in &rec.shells { + if let Shell::Faces { faces, .. } = sh { + for f in faces { + if let Some(slot) = forward.get_mut(f.face as usize) { + *slot = Some(f.forward); + } } - None => e.clone(), - }; - edges.push(ne); - } - // Close gaps with connector edges. - let n = edges.len(); - let mut out: Vec = Vec::new(); - for i in 0..n { - let (Some(cur), Some(next)) = (edges.get(i), edges.get((i + 1) % n)) else { continue }; - out.push(cur.clone()); - if cur.back() != next.front() { - out.extend( - connect(cur.back(), next.front(), connectors) - .ok_or_else(|| KernelError::Failed("blend: could not close a face boundary".into()))?, - ); } } - wires.push(mt::Wire::from(out)); + Ok(Faces { rec, forward }) } - // A face on a periodic surface running along its seam edge twice (as a STEP file gives it) - // keeps doing so: such a wire isn't simple, which is valid there. - let seam_twice = |ws: &[mt::Wire]| { - ws.iter().any(|w| { - let ids: Vec = w.edge_iter().map(|e| e.id()).collect(); - ids.iter().enumerate().any(|(k, x)| ids.iter().skip(k + 1).any(|y| y == x)) - }) - }; - let had_seam = seam_twice(f.absolute_boundaries()); - let closed = wires.iter().all(|w| w.is_closed()); - if had_seam && closed && seam_twice(&wires) && mt::Face::try_new(wires.clone(), f.surface()).is_err() { - let mut nf = mt::Face::new_unchecked(wires, f.surface()); - if !f.orientation() { - nf.invert(); - } - return Ok(nf); - } - crate::heal::absolute_face(f, wires).ok_or_else(|| KernelError::Failed("blend: a face could not be rebuilt".into())) -} -/// A loop blend's refusal that is about its size: too large, or using up only some of the walls. -fn size_refusal(e: &KernelError) -> bool { - match e { - KernelError::TooLarge(_) => true, - KernelError::Failed(m) => m.contains("uses up"), - _ => false, + pub(crate) fn point(&self, v: u32) -> Option { + self.rec.vertices.get(v as usize).map(|v| v3(v.point)).filter(|p| p.is_finite()) } -} -/// The shortest run of `connectors` (each used either way, at most four) from `a` to `b`. -fn connect(a: &mt::Vertex, b: &mt::Vertex, connectors: &[mt::Edge]) -> Option> { - let mut paths: Vec<(mt::Vertex, Vec, Vec)> = vec![(a.clone(), Vec::new(), Vec::new())]; - for _ in 0..4 { - let mut next = Vec::new(); - for (at, path, used) in &paths { - for (i, c) in connectors.iter().enumerate().filter(|(i, _)| !used.contains(i)) { - let step = if c.front() == at { - c.clone() - } else if c.back() == at { - c.inverse() - } else { - continue; - }; - let to = step.back().clone(); - let mut p = path.clone(); - p.push(step); - if &to == b { - return Some(p); - } - let mut u = used.clone(); - u.push(i); - next.push((to, p, u)); - } - } - paths = next; + /// The points of the edge's start and end vertices. + pub(crate) fn ends(&self, e: usize) -> Option<(Vec3, Vec3)> { + let [a, b] = self.rec.edges.get(e)?.vertices; + Some((self.point(a)?, self.point(b)?)) } - None -} -/// Blend one edge of `solid`, with what was built from it (see [`Rebuild`]). -fn blend_one(solid: &Solid, edge: &mt::Edge, size: f64, r: f64, shape: Shape) -> Result<(Solid, Rebuild)> { - if !matches!(edge.curve(), mt::Curve::Line(_)) { - return Err(unsupported("only straight edges can be blended")); + /// Whether the edge's curve is a straight line. + pub(crate) fn straight(&self, e: usize) -> bool { + self.rec.edges.get(e).is_some_and(|x| matches!(x.curve, Curve::Line { .. })) } - let shells = solid.boundaries(); - let (si, shell) = shells - .iter() - .enumerate() - .find(|(_, sh)| sh.edge_iter().any(|e| e.id() == edge.id())) - .ok_or_else(|| KernelError::Failed("edge not found".into()))?; - let faces: Vec<&mt::Face> = shell.face_iter().collect(); - let on_edge: Vec = (0..faces.len()).filter(|i| faces.get(*i).is_some_and(|f| f.edge_iter().any(|e| e.id() == edge.id()))).collect(); - let [i1, i2] = on_edge[..] else { return Err(unsupported("the edge is not between two faces")) }; - let (Some(f1), Some(f2)) = (faces.get(i1), faces.get(i2)) else { return Err(KernelError::Failed("faces".into())) }; - let (Some(n1), Some(n2)) = (plane_normal(f1), plane_normal(f2)) else { return Err(unsupported("both faces next to the edge must be planar")) }; - let (v0, v1) = (edge.absolute_front().clone(), edge.absolute_back().clone()); - let (p0, p1) = (vtx(&v0), vtx(&v1)); - let d = (p1 - p0).normalized().ok_or_else(|| KernelError::Failed("zero-length edge".into()))?; - // In-face directions perpendicular to the edge, into each face: a face's boundary runs - // counter-clockwise about its outward normal, so its interior is to the left. - let into = |f: &mt::Face, n: Vec3| -> Option { - let e = f.boundary_iters().into_iter().flatten().find(|e| e.id() == edge.id())?; - let dir = (vtx(e.back()) - vtx(e.front())).normalized()?; - n.cross(dir).normalized() - }; - let (Some(t1), Some(t2)) = (into(f1, n1), into(f2, n2)) else { return Err(KernelError::Failed("blend: edge direction".into())) }; - // Convex edge: each face's outward normal points away from the other face; concave: toward. - let cos_phi = t1.dot(t2).clamp(-1.0, 1.0); - let phi = cos_phi.acos(); - let convex = n1.dot(t2) < -1e-9 && n2.dot(t1) < -1e-9; - let concave = n1.dot(t2) > 1e-9 && n2.dot(t1) > 1e-9; - if !(phi > 1e-3 && phi < std::f64::consts::PI - 1e-3) || !(convex || concave) { - return Err(unsupported("the faces at the edge are tangent or the edge is ambiguous")); - } - // The blend's centre line is inside the material for a convex edge, outside for a concave one. - let side = if convex { -1.0 } else { 1.0 }; - blend_geometry(solid, si, &faces, (i1, i2), edge, (v0, v1), (p0, p1, d), (n1, t1, t2, phi, side), size, r, shape) -} -/// Distance along each face from the edge to the blend boundary. -fn setback(r: f64, phi: f64, shape: Shape) -> f64 { - match shape { - Shape::Round | Shape::Curvature => r / (phi / 2.0).tan(), - Shape::Flat => r, - } -} - -/// An extended corner edge must stay in the trimmed side face, not just its infinite -/// supporting plane. Reject crossings and contact with any boundary after the old corner, -/// including holes. Curved boundaries are sampled more finely than the clearance tolerance. -pub(crate) fn extension_fits(face: &mt::Face, p: Vec3, q: Vec3, tol: f64) -> bool { - use mt::{BoundedCurve, ParameterDivision1D}; - // truck requires a curve sampling tolerance of at least 1e-6. Keep the - // boundary clearance four times larger than the chord approximation error. - let tol = tol.max(4e-6); - let (Some(x), Some(n)) = ((q - p).normalized(), plane_normal(face)) else { return false }; - let y = n.cross(x); - let len = p.dist(q); - if !len.is_finite() || len <= tol { - return false; - } - let mut inside = false; - for edge in face.edge_iter() { - let points = if matches!(edge.curve(), mt::Curve::Line(_)) { - vec![edge.front().point(), edge.back().point()] - } else { - let curve = edge.curve(); - curve.parameter_division(curve.range_tuple(), tol * 0.25).1 + /// The unit natural normal of a planar face's surface. + fn natural_plane_normal(&self, f: usize) -> Option { + let (du, dv) = match &self.rec.faces.get(f)?.surface { + Surface::Plane { u_axis, v_axis, .. } => (v3(*u_axis), v3(*v_axis)), + Surface::PlaneThrough { origin, u_point, v_point } => (v3(*u_point) - v3(*origin), v3(*v_point) - v3(*origin)), + _ => return None, }; - if points.len() < 2 || points.len() > 100_000 { - return false; - } - for pair in points.windows(2) { - let [a, b] = pair else { return false }; - let a = from_p3(*a) - p; - let b = from_p3(*b) - p; - let (ax, ay, bx, by) = (a.dot(x), a.dot(y), b.dot(x), b.dot(y)); - if ![ax, ay, bx, by].iter().all(|v| v.is_finite()) { - return false; - } - // Contact/overlap with the extension, except its original endpoint. - if (ay.abs() <= tol && by.abs() <= tol && ax.max(bx) > tol && ax.min(bx) <= len + tol) - || [(ax, ay), (bx, by)].iter().any(|(u, v)| *u > tol && *u <= len + tol && v.abs() <= tol) - { - return false; - } - // Curve endpoints may round to opposite sides of a ray that follows a - // straight boundary into the face. Treat points within its clearance as - // on the ray, so a shared endpoint contributes one crossing. - let ay = if ay.abs() <= tol { 0.0 } else { ay }; - let by = if by.abs() <= tol { 0.0 } else { by }; - if (ay > 0.0) != (by > 0.0) { - let hit = ax - ay * (bx - ax) / (by - ay); - if hit > tol && hit <= len + tol { - return false; - } - // Even-odd containment of q over all loops (outer boundary and holes). - if hit > len { - inside = !inside; - } - } - } + du.cross(dv).normalized().filter(|n| n.is_finite()) } - inside -} -/// Parameters along `x + λ d` where the line meets `surf`, within `reach` of `x` (Newton on -/// (u, v, λ) from several starts; nearest first). -fn line_surface_hits(surf: &mt::Surface, x: Vec3, d: Vec3, reach: f64, tol: f64) -> Vec { - use mt::{ParametricSurface, SearchNearestParameter}; - let mut out: Vec = Vec::new(); - for k in [0i32, 1, -1, 2, -2, 4, -4] { - let mut l = reach * f64::from(k) / 4.0; - let Some((mut u, mut v)) = surf.search_nearest_parameter(p3(x + d * l), None, 100) else { continue }; - for _ in 0..60 { - let f = from_p3(surf.subs(u, v)) - (x + d * l); - if !f.is_finite() { - break; - } - if f.len() <= tol { - if l.abs() <= reach && !out.iter().any(|o| (o - l).abs() <= tol * 10.0) { - out.push(l); - } - break; - } - let (su, sv) = (surf.uder(u, v), surf.vder(u, v)); - let m = [[su.x, sv.x, -d.x], [su.y, sv.y, -d.y], [su.z, sv.z, -d.z]]; - let Some([du, dv, dl]) = crate::polyhedron::solve3_pub(m, [-f.x, -f.y, -f.z]) else { break }; - if ![du, dv, dl].iter().all(|z| z.is_finite()) { - break; - } - // Damp long steps: the start may be far from the root. - let step = (Vec3::new(su.x, su.y, su.z) * du + Vec3::new(sv.x, sv.y, sv.z) * dv).len().max(dl.abs()); - let k = if step > reach { reach / step } else { 1.0 }; - u += du * k; - v += dv * k; - l += dl * k; - } + /// The side of the face in its shell: 1 where its outward normal is its surface's natural one. + fn side(&self, f: usize) -> Option { + self.forward.get(f).copied().flatten().map(|fw| if fw { 1.0 } else { -1.0 }) } - out.sort_by(|a, b| a.abs().total_cmp(&b.abs())); - out -} -/// Whether the faces `ids` are curved pieces of one surface: every piece's boundary lies on the -/// first one's surface (a cylinder a boolean left in pieces). -fn same_surface(faces: &[&mt::Face], ids: &[usize], tol: f64) -> bool { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface, SearchNearestParameter}; - let Some(first) = ids.first().and_then(|i| faces.get(*i)) else { return false }; - if ids.iter().any(|i| faces.get(*i).is_none_or(|f| plane_normal(f).is_some())) { - return false; + /// The outward unit normal of a planar face, if planar. + pub(crate) fn plane_normal(&self, f: usize) -> Option { + Some(self.natural_plane_normal(f)? * self.side(f)?) } - let surf = first.surface(); - let on = |q: Vec3| { - // From the nearest of a few starts: a periodic surface has more than one local minimum. - surf.search_nearest_parameter(p3(q), None, 100).is_some_and(|(u, v)| from_p3(surf.subs(u, v)).dist(q) <= tol) - }; - ids.iter().skip(1).filter_map(|i| faces.get(*i)).all(|f| { - f.edge_iter().all(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - [0.0, 0.3, 0.7, 1.0].iter().all(|k| on(from_p3(c.subs(t0 + (t1 - t0) * k)))) + + /// The outward unit normal of face `f` at `p` (a point within `accept` of its surface). + pub(crate) fn normal_at(&self, f: usize, p: Vec3, accept: f64) -> Option { + let s = SurfaceEval::new(self.rec.faces.get(f)?.parameters()).ok()?; + let uv = s.project(p, None, accept)?; + let (_, su, sv) = s.derivs(uv[0], uv[1])?; + Some(su.cross(sv).normalized()? * self.side(f)?) + } + + /// Every edge use in the face's loops. + pub(crate) fn uses(&self, f: usize) -> impl Iterator { + self.rec.faces.get(f).into_iter().flat_map(|face| face.loops.iter()).flat_map(|l| match l { + Loop::Edges { edges } => edges.as_slice(), + Loop::Vertex { .. } => &[], }) - }) + } + + /// The faces that use the edge, each once. + pub(crate) fn faces_of(&self, e: usize) -> BTreeSet { + self.rec.edges.get(e).map(|x| x.uses.iter().map(|u| u.face).collect()).unwrap_or_default() + } + + /// The unit direction into planar face `f` across the straight edge of `u`, square to the + /// edge: the face lies to the left of its loop seen from its surface's natural normal. + pub(crate) fn direction_into_face(&self, f: usize, u: &OrientedEdge) -> Option { + let (a, b) = self.ends(u.edge as usize)?; + let dir = if u.forward { b - a } else { a - b }; + self.natural_plane_normal(f)?.cross(dir.normalized()?).normalized() + } + + /// The edge's unit tangent along its interval (start to end vertex) at its start or end. + pub(crate) fn tangent(&self, e: usize, at_end: bool) -> Option { + let edge = self.rec.edges.get(e)?; + curve_tangent(edge.parameters(), if at_end { edge.interval[1] } else { edge.interval[0] }) + } } -/// A circle through the curve of `e` (centre, axis, radius), when it is one. -fn edge_circle(e: &mt::Edge, tol: f64) -> Option<(Vec3, Vec3, f64)> { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (lo, hi) = c.range_tuple(); - let at = |f: f64| from_p3(c.subs(lo + (hi - lo) * f)); - let (a, b, m) = (at(0.0), at(1.0), at(0.5)); - let (u, w) = (b - a, m - a); - let n = u.cross(w); - let n2 = n.len2(); - if !(n2 > 1e-30) { +/// The unit tangent of a record curve at `t`, along increasing `t`. +pub(crate) fn curve_tangent(c: &Curve, t: f64) -> Option { + curve_derivative(c, t)?.normalized().filter(|d| d.is_finite()) +} + +/// The first derivative of a record curve at `t` (of an intersection curve: its unit tangent). +pub(crate) fn curve_derivative(c: &Curve, t: f64) -> Option { + if !t.is_finite() { return None; } - // Circumcentre of a, b, m. - let centre = a + (n.cross(u) * w.len2() + w.cross(n) * u.len2()) / (2.0 * n2); - let radius = centre.dist(a); - let axis = n.normalized()?; - let ok = (1..16).all(|i| { - let q = at(f64::from(i) / 16.0); - (q.dist(centre) - radius).abs() <= tol && (q - centre).dot(axis).abs() <= tol - }); - (ok && radius.is_finite()).then_some((centre, axis, radius)) -} - -/// Where `q` lies on the edge's curve: its parameter, if within `tol` of the curve and inside -/// the edge's range. -pub(crate) fn on_edge(e: &mt::Edge, q: Vec3, tol: f64) -> Option { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - let c = e.curve(); - let (lo, hi) = c.range_tuple(); - let hint = - (0..=32).map(|i| lo + (hi - lo) * f64::from(i) / 32.0).min_by(|x, y| from_p3(c.subs(*x)).dist(q).total_cmp(&from_p3(c.subs(*y)).dist(q)))?; - let t = c.search_nearest_parameter(p3(q), hint, 100)?; - let margin = (hi - lo) * 1e-9; - (t.is_finite() && t >= lo - margin && t <= hi + margin && from_p3(c.subs(t)).dist(q) <= tol).then_some(t.clamp(lo, hi)) -} - -/// Whether `q` lies on the edge's curve continued past its ends (a line or a circle). -pub(crate) fn on_extension(e: &mt::Edge, q: Vec3, tol: f64) -> bool { - match e.curve() { - mt::Curve::Line(_) => { - let (a, b) = (vtx(e.absolute_front()), vtx(e.absolute_back())); - (b - a).normalized().is_some_and(|u| (q - a - u * (q - a).dot(u)).len() <= tol) + let d = match c { + Curve::Line { start, end } => v3(*end) - v3(*start), + Curve::Circle { frame, radius } => { + let (s, co) = t.sin_cos(); + (v3(frame.y_axis) * co - v3(frame.x_axis) * s) * *radius } - _ => edge_circle(e, tol).is_some_and(|(c, n, r)| ((q - c).dot(n)).abs() <= tol && ((q - c - n * (q - c).dot(n)).len() - r).abs() <= tol), - } -} - -/// The edge `e` with its end at `v` moved to `nv`, along its own curve: shortened (any curve), -/// or continued past `v` (a line or a circle). In the stored orientation of `e`. -pub(crate) fn retarget(e: &mt::Edge, v: &mt::Vertex, nv: &mt::Vertex, tol: f64) -> Result { - let (f, bk) = (e.absolute_front(), e.absolute_back()); - if f == bk { - return Err(unsupported("a closed edge where the blend ends")); - } - if matches!(e.curve(), mt::Curve::Line(_)) { - return Ok(if f == v { builder::line(nv, bk) } else { builder::line(f, nv) }); - } - use mt::Cut; - let q = vtx(nv); - if let Some(t) = on_edge(e, q, tol) { - use mt::BoundedCurve; - let mut c = e.curve(); - // The piece kept must not shrink to nothing. - let (lo, hi) = c.range_tuple(); - let margin = (hi - lo) * 1e-6; - if (f == v && t >= hi - margin) || (f != v && t <= lo + margin) { - return Err(too_large("the blend is larger than the neighbouring faces")); + Curve::Ellipse { frame, radii } => { + let (s, co) = t.sin_cos(); + v3(frame.y_axis) * (radii[1] * co) - v3(frame.x_axis) * (radii[0] * s) } - let rest = c.cut(t); - let (piece, a, b) = if f == v { (rest, nv, bk) } else { (c, f, nv) }; - return mt::Edge::try_new(a, b, piece).map_err(|err| KernelError::Failed(format!("blend: corner edge: {err}"))); - } - // Continued past v: the arc from the new end through v to the far end. - if edge_circle(e, tol).is_some() && on_extension(e, q, tol) { - let through = p3(vtx(v)); - return Ok(if f == v { builder::circle_arc(nv, bk, through) } else { builder::circle_arc(f, nv, through) }); - } - Err(too_large("the blend is larger than the neighbouring faces")) -} - -#[allow(clippy::too_many_arguments)] -fn blend_geometry( - solid: &Solid, - si: usize, - faces: &[&mt::Face], - (i1, i2): (usize, usize), - edge: &mt::Edge, - (v0, v1): (mt::Vertex, mt::Vertex), - (p0, p1, d): (Vec3, Vec3, Vec3), - (n1, t1, t2, phi, side): (Vec3, Vec3, Vec3, f64, f64), - size: f64, - r: f64, - shape: Shape, -) -> Result<(Solid, Rebuild)> { - let s = setback(r, phi, shape); - let tol = (size * 1e-7).max(1e-9); - // The arc centre is r from both faces (inside the material for a convex edge, outside for a - // concave one), in the cross-section through `p`. - let centre = |p: Vec3| p + t1 * s + n1 * (r * side); - // Each end of the blend lies in one more face (the end face, square to the edge or at an - // angle) or, for a fillet, in two that meet at the edge's end (Vida, Martin and Várady 1994: - // trimlines joined across existing faces): the blend then crosses the edge between them, - // which is cut back to the crossing. The rails run parallel to the edge, set back by s in - // their side faces, and end in the end plane they reach (`ga` from f1, `gb` from f2). A side - // edge that the setback uses up exactly is consumed: the rail ends at its far vertex (`ca`, - // `cb`; one end face only). - struct End { - v: mt::Vertex, - g: Vec, - e1: mt::Edge, - e2: mt::Edge, - /// The edge between two end faces, and where the blend crosses it. - e3: Option<(mt::Edge, Vec3)>, - a: Vec3, - b: Vec3, - /// The end's section of the blend, from A to B (across both faces when two). - planes: Vec<(Vec3, Vec3)>, - ca: Option, - cb: Option, - /// Points of the end's section on a curved end face, from A to B: one run per face it - /// crosses (an end surface in pieces), split where it crosses their seams. - cap: Option>>, - /// The seams between pieces of the end surface at the vertex, where the section crosses - /// them (in its order from A to B). - seams: Vec<(mt::Edge, Vec3)>, - /// The section lies where the end surface was missing round the vertex: the side edge - /// `e2` is split at B, its piece from B to the vertex a seam of the end surface. - concave: bool, - /// How far along the edge the section reaches from the end vertex. - reach: f64, - } - let mut ends: Vec = Vec::new(); - for (v, p) in [(&v0, p0), (&v1, p1)] { - let at_v: Vec = (0..faces.len()).filter(|i| faces.get(*i).is_some_and(|f| f.vertex_iter().any(|x| &x == v))).collect(); - let others: Vec = at_v.iter().copied().filter(|i| *i != i1 && *i != i2).collect(); - // The edge at v that face `fi` shares with face `g`, other than the blended edge. - let shared = |fi: usize, g: usize| -> Option { - let (f, gf) = (faces.get(fi)?, faces.get(g)?); - f.edge_iter().find(|e| e.id() != edge.id() && (e.front() == v || e.back() == v) && gf.edge_iter().any(|x| x.id() == e.id())) - }; - // One curved surface in several faces round the vertex (a cylinder a boolean left in - // pieces meeting there): the end face is that surface, its pieces' seams cut back. - let one_surface = others.len() >= 2 && same_surface(faces, &others, (size * 1e-5).max(1e-6)); - let (ga, gb) = match others[..] { - [g] => (g, g), - _ if one_surface => { - let x = others.iter().copied().find(|g| shared(i1, *g).is_some()); - let y = others.iter().copied().find(|g| shared(i2, *g).is_some()); - match (x, y) { - (Some(x), Some(y)) => (x, y), - _ => return Err(unsupported("each end of the edge must touch exactly one more face")), - } - } - [x, y] if shared(i1, x).is_some() && shared(i2, y).is_some() => (x, y), - [x, y] if shared(i1, y).is_some() && shared(i2, x).is_some() => (y, x), - _ => return Err(unsupported("each end of the edge must touch exactly one more face")), - }; - if shape == Shape::Curvature && (others.len() != 1 || faces.get(ga).and_then(|f| plane_normal(f)).is_none()) { - return Err(unsupported("G2 fillets require one planar end face at each end")); + Curve::Polyline { points } => { + let last = points.len().checked_sub(2)?; + let i = (t.max(0.0).floor() as usize).min(last); + v3(*points.get(i + 1)?) - v3(*points.get(i)?) } - // An end face that is not a plane, or meets the side faces in curves: the rails end where - // they reach its surface, and the blend's end is where its surface meets the end face - // (the cross-section through `p` slid along d onto it, point by point). - let is_line = |e: &mt::Edge| matches!(e.curve(), mt::Curve::Line(_)); - // Two end faces, not both planes meeting the sides and each other in lines (a sheet metal - // rim edge ending where a bend meets the next panel): the same, each face taking the - // section's points on it, cut where it crosses the edge between them. - let two_curved = !one_surface && ga != gb && { - let curved = |g: usize| faces.get(g).is_none_or(|f| plane_normal(f).is_none()); - let e3 = shared(ga, gb); - curved(ga) || curved(gb) || [shared(i1, ga), shared(i2, gb), e3].iter().any(|e| e.as_ref().is_none_or(|e| !is_line(e))) - }; - // Not where an end face runs on smoothly from a side (an earlier round): the corner build - // takes those ends. - let tangent = others.iter().any(|g| { - let n = |i: usize| faces.get(i).and_then(|f| crate::curveblend::project(f, p, None)).map(|x| x.1); - n(*g).is_some_and(|ng| [i1, i2].iter().filter_map(|i| n(*i)).any(|ns| ns.dot(ng) > 1.0 - 1e-6)) - }); - let multi = (one_surface || two_curved) && !tangent; - if (ga == gb || multi) - && let (Some(e1), Some(e2)) = (shared(i1, ga), shared(i2, gb)) - && (multi || faces.get(ga).and_then(|f| plane_normal(f)).is_none() || !is_line(&e1) || !is_line(&e2)) - { - if shape == Shape::Curvature { - return Err(unsupported("G2 fillets require straight edges around each planar end face")); - } - let g = faces.get(ga).ok_or_else(|| KernelError::Failed("face".into()))?; - // An end face running on smoothly from a side, an earlier round of this radius (its - // end an arc of it): the blend ends in that round, which takes a corner of its own - // (`curveblend::corner_blend`), the same as rounding both together. - let normal = |f: &mt::Face| crate::curveblend::project(f, p, None).map(|x| x.1); - let of_radius = |e: &mt::Edge| crate::curveblend::circle_of(e, r * 1e-4).is_some_and(|c| (c.1 - r).abs() <= r * 1e-4); - if let Some(ng) = normal(g) - && [i1, i2].iter().filter_map(|i| faces.get(*i)).filter_map(|f| normal(f)).any(|ns| ns.dot(ng) > 1.0 - 1e-6) - && shape == Shape::Round - && (of_radius(&e1) || of_radius(&e2)) - { - return Err(unsupported("a blend ending in an earlier round")); - } - let surf = g.surface(); - let surf_b = faces.get(gb).ok_or_else(|| KernelError::Failed("face".into()))?.surface(); - let on_tol = (size * 1e-5).max(1e-6); - let reach = 3.0 * (s + r); - let (sa, sb) = (p + t1 * s, p + t2 * s); - let c0 = centre(p); - let theta = std::f64::consts::PI - phi; - let profile = |f: f64| -> Vec3 { - match shape { - Shape::Flat => sa + (sb - sa) * f, - // G2 rejects curved end faces before entering this branch. - Shape::Round | Shape::Curvature => c0 + ((sa - c0) * ((1.0 - f) * theta).sin() + (sb - c0) * (f * theta).sin()) / theta.sin(), - } + Curve::Spline { .. } | Curve::RationalSpline { .. } => match CurveEval::new(c).ok()? { + CurveEval::Spline(s) => s.eval(t)?.1, + _ => return None, + }, + Curve::SurfaceIntersection { surfaces, leader, .. } => { + // Along both surfaces: square to both normals, on the leader's side. + let p = CurveEval::new(c).ok()?.point(t)?; + let normal = |s: &Surface| -> Option { + let e = SurfaceEval::new(s).ok()?; + let uv = e.project(p, None, f64::INFINITY)?; + let (_, su, sv) = e.derivs(uv[0], uv[1])?; + Some(su.cross(sv)) }; - // A rail's end: on the side edge, else on its continuation within the side face. - let rail_end = |x: Vec3, e: &mt::Edge, fi: usize, surf: &mt::Surface| -> Result<(Vec3, f64)> { - let hits = line_surface_hits(surf, x, d, reach, tol); - if let Some(l) = hits.iter().find(|l| on_edge(e, x + d * **l, on_tol).is_some()) { - return Ok((x + d * *l, *l)); - } - let side = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?; - hits.iter() - .find(|l| on_extension(e, x + d * **l, on_tol) && extension_fits(side, p, x + d * **l, tol)) - .map(|l| (x + d * *l, *l)) - .ok_or_else(|| too_large("the blend is larger than the neighbouring faces")) - }; - let ((a, la), (b, lb)) = (rail_end(sa, &e1, i1, &surf)?, rail_end(sb, &e2, i2, &surf_b)?); - let flat_plane = shape == Shape::Flat && plane_normal(g).is_some() && !multi; - // Where a point of the section lies across it: 0 at A's side, 1 at B's. - let perp = |x: Vec3| x - d * (x - p).dot(d); - let theta_ab = { - let (u, w) = (sa - c0, sb - c0); - (u.dot(w) / (u.len() * w.len()).max(1e-300)).clamp(-1.0, 1.0).acos() - }; - let fraction = |x: Vec3| -> f64 { - let x = perp(x); - match shape { - Shape::Flat => (x - sa).dot(sb - sa) / (sb - sa).len2().max(1e-300), - Shape::Round | Shape::Curvature => { - let (u, w) = (sa - c0, x - c0); - let ang = (u.dot(w) / (u.len() * w.len()).max(1e-300)).clamp(-1.0, 1.0).acos(); - ang / theta_ab.max(1e-300) - } - } - }; - // The seams between the end surface's pieces at the vertex, and where the blend's - // surface crosses each (walking out from the vertex to the first crossing). - let mut seams: Vec<(mt::Edge, Vec3, f64)> = Vec::new(); - let mut concave = false; - if multi { - let gap = |x: Vec3| -> f64 { - match shape { - Shape::Round | Shape::Curvature => (perp(x) - c0).len() - r, - Shape::Flat => (sb - sa).cross(d).normalized().map_or(f64::NAN, |m| (x - sa).dot(m)), - } - }; - let mut seen: Vec = vec![edge.id(), e1.id(), e2.id()]; - let mut uncrossed = 0usize; - for gi in &others { - let Some(gf) = faces.get(*gi) else { continue }; - for e in gf.edge_iter() { - if seen.contains(&e.id()) || !(e.front() == v || e.back() == v) { - continue; - } - seen.push(e.id()); - let owners: Vec = - (0..faces.len()).filter(|k| faces.get(*k).is_some_and(|f| f.edge_iter().any(|x| x.id() == e.id()))).collect(); - if !owners.iter().all(|k| others.contains(k)) { - return Err(unsupported("each end of the edge must touch exactly one more face")); - } - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let from_front = e.absolute_front() == v; - let at = |k: f64| from_p3(c.subs(if from_front { t0 + (t1 - t0) * k } else { t1 - (t1 - t0) * k })); - let mut prev = (0.0, gap(at(0.0))); - let mut hit = None; - for i in 1..=400 { - let k = f64::from(i) / 400.0; - let x = at(k); - let gk = gap(x); - if !gk.is_finite() || x.dist(p) > 2.0 * reach { - break; - } - if (gk > 0.0) != (prev.1 > 0.0) { - let (mut lo, mut hi) = (prev.0, k); - for _ in 0..60 { - let mid = 0.5 * (lo + hi); - if (gap(at(mid)) > 0.0) == (prev.1 > 0.0) { - lo = mid; - } else { - hi = mid; - } - } - hit = Some(at(0.5 * (lo + hi))); - break; - } - prev = (k, gk); - } - let Some(q) = hit else { - uncrossed += 1; - continue; - }; - let f = fraction(q); - if !(f > 1e-6 && f < 1.0 - 1e-6) { - return Err(unsupported("the blend's end across the end face's seams")); - } - seams.push((e.absolute_clone(), q, f)); - } - } - seams.sort_by(|x, y| x.2.total_cmp(&y.2)); - // No seam crossed: the surface turns back round the vertex (a boss joined beside - // the edge, its wall missing where the other body was). The section lies where - // that wall was, now laid bare: one piece takes it, and the rest of the edge - // from B to the vertex is a seam between them. - if uncrossed > 0 && (!seams.is_empty() || ga == gb || !one_surface) { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - concave = uncrossed > 0; - } - // Runs of the section between A, the seam crossings and B, each on the end surface. - let mut stops: Vec<(f64, Vec3, f64)> = vec![(0.0, a, la)]; - stops.extend(seams.iter().map(|(_, q, f)| (*f, *q, (*q - p).dot(d)))); - stops.push((1.0, b, lb)); - let mut far = la.abs().max(lb.abs()); - // The face each run lies in: the one holding the edges at both its ends. - let bounds: Vec = std::iter::once(e1.id()).chain(seams.iter().map(|x| x.0.id())).chain(std::iter::once(e2.id())).collect(); - let mut run_surfaces: Vec = Vec::new(); - for w in bounds.windows(2) { - let [x, y] = w else { continue }; - let fi = if one_surface || ga == gb { - Some(ga) - } else { - others - .iter() - .copied() - .find(|g| faces.get(*g).is_some_and(|f| f.edge_iter().any(|e| e.id() == *x) && f.edge_iter().any(|e| e.id() == *y))) - }; - run_surfaces.push(fi.and_then(|g| faces.get(g)).ok_or_else(|| unsupported("the blend's end across the end faces"))?.surface()); - } - let mut runs: Vec> = Vec::new(); - for (pair, surf) in stops.windows(2).zip(&run_surfaces) { - let [(f0, x0, l0), (f1, x1, _)] = pair else { continue }; - if flat_plane { - runs.push(vec![*x0, *x1]); - continue; - } - let mut found = None; - for n in [16usize, 32, 64] { - // The section's points on the end face, each continuing from the last. - let mut pts = vec![*x0]; - let mut last = *l0; - let mut ok = true; - for i in 1..n { - let x = profile(f0 + (f1 - f0) * i as f64 / n as f64); - match line_surface_hits(surf, x, d, reach, tol).into_iter().min_by(|u, v| (u - last).abs().total_cmp(&(v - last).abs())) { - Some(l) => { - pts.push(x + d * l); - last = l; - far = far.max(l.abs()); - } - None => { - ok = false; - break; - } - } - } - if !ok { - break; - } - pts.push(*x1); - // The fitted curve must stay on both surfaces between the points. - let Some(bs) = crate::build::interpolate_cubic(&pts) else { break }; - let fits = (0..n).all(|i| { - use mt::{ParametricCurve, ParametricSurface, SearchNearestParameter}; - let q = from_p3(bs.subs((i as f64 + 0.5) / n as f64)); - let on_g = surf.search_nearest_parameter(p3(q), None, 100).is_some_and(|(u, v)| from_p3(surf.subs(u, v)).dist(q) <= on_tol); - let on_blend = match shape { - Shape::Round | Shape::Curvature => { - let w = q - c0; - ((w - d * w.dot(d)).len() - r).abs() <= on_tol - } - Shape::Flat => (sb - sa).cross(d).normalized().is_some_and(|m| (q - sa).dot(m).abs() <= on_tol), - }; - on_g && on_blend - }); - if fits { - found = Some(pts); - break; - } - } - runs.push(found.ok_or_else(|| unsupported("the blend's end on a curved face"))?); - } - // A rail that ends at the far end of its side edge uses that edge up (an earlier round's - // end arc, when the new blend meets it exactly where that round meets the next face). - let far_end = |e: &mt::Edge, q: Vec3| { - let f = if e.front() == v { e.back() } else { e.front() }; - (!multi && vtx(f).dist(q) <= on_tol).then(|| f.clone()) - }; - let (ca, cb) = (far_end(&e1, a), far_end(&e2, b)); - ends.push(End { - v: v.clone(), - g: if multi { others.clone() } else { vec![ga] }, - e1, - e2, - e3: None, - a, - b, - planes: Vec::new(), - ca, - cb, - cap: Some(runs), - seams: seams.into_iter().map(|(e, q, _)| (e, q)).collect(), - concave, - reach: far, - }); - continue; - } - let normal = |g: usize| -> Result { - let n = faces.get(g).and_then(|f| plane_normal(f)).ok_or_else(|| unsupported("the faces at the edge ends must be planar"))?; - if n.dot(d).abs() < 1e-9 { - return Err(unsupported("an end face parallel to the edge")); - } - Ok(n) - }; - let (na, nb) = (normal(ga)?, normal(gb)?); - // Slide a point of the cross-section through `p` along d onto the end plane through p. - let slide = |x: Vec3, n: Vec3| x - d * (n.dot(x - p) / n.dot(d)); - let (a, b) = (slide(p + t1 * s, na), slide(p + t2 * s, nb)); - let (e1, e2) = ( - shared(i1, ga).ok_or_else(|| unsupported("unexpected corner topology"))?, - shared(i2, gb).ok_or_else(|| unsupported("unexpected corner topology"))?, - ); - let mut consumed: [Option; 2] = [None, None]; - for (k, (e, q, fi)) in [(&e1, a, i1), (&e2, b, i2)].into_iter().enumerate() { - if !matches!(e.curve(), mt::Curve::Line(_)) { - return Err(unsupported("the edges at the corners must be straight")); - } - let far = if e.front() == v { e.back().clone() } else { e.front().clone() }; - let delta = vtx(&far) - p; - let len = delta.len(); - let dir = delta.normalized().ok_or_else(|| unsupported("zero-length corner edge"))?; - let along = (q - p).dot(dir); - if (q - p - dir * along).len() > tol * 100.0 + 1e-7 { - return Err(unsupported("the blend is larger than the neighbouring faces")); - } - // A fillet's setback that uses up the side edge exactly consumes it. - if shape == Shape::Round && ga == gb && (along - len).abs() <= tol { - if let Some(slot) = consumed.get_mut(k) { - *slot = Some(far); - } - continue; - } - // A rail ending before the old corner extends the neighbouring rim edge away from its - // other vertex: valid only within the trimmed side face. - if along >= len - tol || (along < 0.0 && !faces.get(fi).is_some_and(|f| extension_fits(f, p, q, tol))) { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - } - // Across two end faces: where the blend's cylinder crosses the edge between them, on the - // blend's side of the axis (between its two rails). - let e3 = if ga == gb { - None - } else { - let (Some(fa), Some(fb)) = (faces.get(ga), faces.get(gb)) else { return Err(KernelError::Failed("face".into())) }; - let e3 = fa - .edge_iter() - .find(|e| (e.front() == v || e.back() == v) && fb.edge_iter().any(|x| x.id() == e.id())) - .ok_or_else(|| unsupported("unexpected corner topology"))?; - if !matches!(e3.curve(), mt::Curve::Line(_)) { - return Err(unsupported("the edges at the corners must be straight")); - } - let far = if e3.front() == v { vtx(e3.back()) } else { vtx(e3.front()) }; - let (len3, u) = (far.dist(p), (far - p).normalized().ok_or_else(|| unsupported("zero-length corner edge"))?); - let c0 = centre(p); - let perp = |x: Vec3| x - d * x.dot(d); - if shape == Shape::Flat { - // The chamfer plane through both rails crosses the edge between them. - let (sa, sb) = (p + t1 * s, p + t2 * s); - let m = (sb - sa).cross(d).normalized().ok_or_else(|| KernelError::Failed("chamfer plane".into()))?; - let den = m.dot(u); - let root = if den.abs() > 1e-12 { m.dot(sa - p) / den } else { f64::NAN }; - let x = perp(p + u * root - sa); - let along = x.dot(sb - sa) / (sb - sa).len2(); - if !(root > tol && root < len3 - tol && along > 1e-9 && along < 1.0 - 1e-9) { - return Err(unsupported("the blend does not cross the edge between the end faces")); - } - ends.push(End { - v: v.clone(), - g: vec![ga, gb], - e1: e1.clone(), - e2: e2.clone(), - e3: Some((e3.clone(), p + u * root)), - a, - b, - planes: vec![(p, na), (p, nb)], - ca: None, - cb: None, - cap: None, - seams: Vec::new(), - concave: false, - reach: 0.0, - }); - continue; - } - let (w, up) = (perp(p - c0), perp(u)); - // |w + λ up|² = r² - let (qa, qb, qc) = (up.len2(), 2.0 * w.dot(up), w.len2() - r * r); - let disc = qb * qb - 4.0 * qa * qc; - if qa < 1e-18 || disc < 0.0 { - return Err(unsupported("the blend does not cross the edge between the end faces")); - } - let (ra, rb) = (perp(p + t1 * s - c0), perp(p + t2 * s - c0)); - let angle = |x: Vec3, y: Vec3| (x.dot(y) / (x.len() * y.len()).max(1e-300)).clamp(-1.0, 1.0).acos(); - let between = |x: Vec3| (angle(ra, x) + angle(x, rb) - angle(ra, rb)).abs() < 1e-6; - let root = [(-qb - disc.sqrt()) / (2.0 * qa), (-qb + disc.sqrt()) / (2.0 * qa)] - .into_iter() - .filter(|l| *l > tol && *l < len3 - tol) - .find(|l| between(w + up * *l)) - .ok_or_else(|| unsupported("the blend does not cross the edge between the end faces"))?; - Some((e3.clone(), p + u * root)) - }; - let planes = if ga == gb { vec![(p, na)] } else { vec![(p, na), (p, nb)] }; - let [ca, cb] = consumed; - ends.push(End { - v: v.clone(), - g: if ga == gb { vec![ga] } else { vec![ga, gb] }, - e1, - e2, - e3, - a, - b, - planes, - ca, - cb, - cap: None, - seams: Vec::new(), - concave: false, - reach: 0.0, - }); - } - let [end0, end1] = &ends[..] else { return Err(KernelError::Failed("ends".into())) }; - if end0.g.iter().any(|g| end1.g.contains(g)) { - return Err(unsupported("both ends touch the same face")); - } - if (end1.a - end0.a).dot(d) <= tol || (end1.b - end0.b).dot(d) <= tol { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - // A side face whose corner edges are consumed at both ends is used up: its remaining edge, - // parallel to the old edge at the setback, becomes the rail and the face is removed. - let used_up = |fi: usize, c0: &Option, c1: &Option| -> Result> { - // Used up only where it is consumed at both ends; consumed at one, the face stays and - // loses that edge. - let (Some(x0), Some(x1)) = (c0, c1) else { return Ok(None) }; - let f = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?; - if f.boundaries().len() != 1 || f.edge_iter().count() != 4 { - return Err(unsupported("the blend uses up a neighbouring face with more edges")); - } - let rail = f - .edge_iter() - .find(|e| matches!(e.curve(), mt::Curve::Line(_)) && ((e.front() == x0 && e.back() == x1) || (e.front() == x1 && e.back() == x0))) - .ok_or_else(|| unsupported("the blend uses up a neighbouring face with more edges"))?; - Ok(Some(if rail.front() == x0 { rail.clone() } else { rail.inverse() })) - }; - let rail_a = used_up(i1, &end0.ca, &end1.ca)?; - let rail_b = used_up(i2, &end0.cb, &end1.cb)?; - let vertex = |c: &Option, p: Vec3| c.clone().unwrap_or_else(|| builder::vertex(p3(p))); - // Projection along the edge is affine, so projecting the six controls gives - // the exact quintic on an oblique end plane. The end-plane check above has - // already refused planes parallel to d. Use these same controls for the - // surface below, including where an outward slope extends past the old edge. - let g2_section = |p: Vec3, (o, n): (Vec3, Vec3)| g2_controls(p, t1, t2, s).map(|q| q - d * ((q - o).dot(n) / d.dot(n))); - // Corner curves on the end faces (A → B): the blend's cross-section through the end vertex, - // slid along the edge onto each end plane (an ellipse arc; the circle itself on a square - // end face). - let section = |p: Vec3, va: &mt::Vertex, vb: &mt::Vertex, from: Vec3, to: Vec3, plane: (Vec3, Vec3)| -> Result { - if shape == Shape::Flat { - return Ok(builder::line(va, vb)); - } - if shape == Shape::Curvature { - let controls = g2_section(p, plane); - return Ok(builder::bezier(va, vb, controls.into_iter().skip(1).take(4).map(p3).collect())); - } - let c = centre(p); - let mid = c + ((from - c) + (to - c)).normalized().unwrap_or(-n1) * r; - let (o, n) = plane; - if n.dot(d).abs() >= 1.0 - 1e-12 { - return Ok(builder::circle_arc(va, vb, p3(mid))); - } - let arc = builder::circle_arc(&builder::vertex(p3(from)), &builder::vertex(p3(to)), p3(mid)); - let den = d.dot(n); - // x ↦ x − d ((x − o)·n) / (d·n), column-major. - let col = |j: usize| { - let ej = [Vec3::X, Vec3::Y, Vec3::Z][j]; - ej - d * (ej.dot(n) / den) - }; - let (c0, c1, c2) = (col(0), col(1), col(2)); - let tr = d * (o.dot(n) / den); - let mat = mt::Matrix4::new(c0.x, c0.y, c0.z, 0.0, c1.x, c1.y, c1.z, 0.0, c2.x, c2.y, c2.z, 0.0, tr.x, tr.y, tr.z, 1.0); - let mut curve = arc.curve(); - mt::Transformed::transform_by(&mut curve, mat); - Ok(mt::Edge::new(va, vb, curve)) - }; - #[allow(clippy::type_complexity)] - let mut corners: Vec<(mt::Vertex, mt::Vertex, Vec, Option, Vec, Vec)> = Vec::new(); - let on_tol = (size * 1e-5).max(1e-6); - for (end, p) in [(end0, p0), (end1, p1)] { - let (va, vb) = (vertex(&end.ca, end.a), vertex(&end.cb, end.b)); - let (sa, sb) = (p + t1 * s, p + t2 * s); - let mut seam_vs: Vec = Vec::new(); - let (chain, vq) = match (&end.e3, &end.planes[..]) { - _ if end.cap.is_some() => { - // A run from each stop to the next: A, the seam crossings, B. - seam_vs = end.seams.iter().map(|(_, q)| builder::vertex(p3(*q))).collect(); - let stops: Vec<&mt::Vertex> = std::iter::once(&va).chain(seam_vs.iter()).chain(std::iter::once(&vb)).collect(); - let runs = end.cap.as_deref().unwrap_or_default(); - if runs.len() + 1 != stops.len() { - return Err(KernelError::Failed("blend end".into())); - } - let mut chain = Vec::with_capacity(runs.len()); - for (k, pts) in runs.iter().enumerate() { - let (Some(x), Some(y)) = (stops.get(k), stops.get(k + 1)) else { return Err(KernelError::Failed("blend end".into())) }; - chain.push(if pts.len() == 2 { - builder::line(x, y) - } else { - let bs = crate::build::interpolate_cubic(pts).ok_or_else(|| unsupported("the blend's end on a curved face"))?; - mt::Edge::try_new(x, y, mt::Curve::BSplineCurve(bs)).map_err(|e| KernelError::Failed(format!("blend end: {e}")))? - }); - } - (chain, None) - } - (None, [plane]) => (vec![section(p, &va, &vb, sa, sb, *plane)?], None), - (Some((_, q)), [pa, pb]) => { - let vq = builder::vertex(p3(*q)); - let sq = *q - d * (*q - p).dot(d); - (vec![section(p, &va, &vq, sa, sq, *pa)?, section(p, &vq, &vb, sq, sb, *pb)?], Some(vq)) - } - _ => return Err(KernelError::Failed("blend end".into())), - }; - // The rest of e2, from B to the vertex: a seam between the end surface's pieces. - let mut extra = Vec::new(); - if end.concave { - let far = if end.e2.absolute_front() == &end.v { end.e2.absolute_back().clone() } else { end.e2.absolute_front().clone() }; - extra.push(retarget(&end.e2, &far, &vb, on_tol)?); - } - corners.push((va, vb, chain, vq, seam_vs, extra)); - } - let [(a0, b0, c0, q0, s0, x0), (a1, b1, c1, q1, s1, x1)] = &corners[..] else { return Err(KernelError::Failed("ends".into())) }; - let link0: Vec = c0.iter().chain(x0).cloned().collect(); - let link1: Vec = c1.iter().chain(x1).cloned().collect(); - let la = rail_a.clone().unwrap_or_else(|| builder::line(a0, a1)); - let lb = rail_b.clone().unwrap_or_else(|| builder::line(b0, b1)); - - // Substitutions: side edges at the ends now stop at A/B (consumed ones are dropped), an edge - // between two end faces stops where the blend crosses it; the blended edge moves to A or B. - let mut subst: HashMap = HashMap::new(); - let mut dropped: Vec = Vec::new(); - let shorten = |e: &mt::Edge, v: &mt::Vertex, nv: &mt::Vertex| retarget(e, v, nv, on_tol); - for (end, a, b, q, sv) in [(end0, a0, b0, q0, s0), (end1, a1, b1, q1, s1)] { - // Seams between the end surface's pieces stop where the blend's end crosses them. - for ((e, _), nv) in end.seams.iter().zip(sv) { - subst.insert(e.id(), shorten(e, &end.v, nv)?); - } - for (e, nv, used) in [(&end.e1, a, &end.ca), (&end.e2, b, &end.cb)] { - if used.is_some() { - dropped.push(e.id()); - continue; - } - subst.insert(e.id(), shorten(e, &end.v, nv)?); - } - if let (Some((e3, _)), Some(q)) = (&end.e3, q) { - subst.insert(e3.id(), shorten(e3, &end.v, q)?); - } - } - // The side edges at the ends are pieces of themselves; the rails and corner curves are new. - let mut rec = Rebuild::default(); - rec.pieces(&subst); - let mut new_faces: Vec = Vec::with_capacity(faces.len() + 1); - for (i, f) in faces.iter().enumerate() { - if (i == i1 && rail_a.is_some()) || (i == i2 && rail_b.is_some()) { - continue; - } - let nf = if i == i1 { - let mut m = subst.clone(); - m.insert(edge.id(), la.clone()); - rebuild_face_dropping(f, &m, &dropped, &[])? - } else if i == i2 { - let mut m = subst.clone(); - m.insert(edge.id(), lb.clone()); - rebuild_face_dropping(f, &m, &dropped, &[])? - } else if end0.g.contains(&i) { - rebuild_face_dropping(f, &subst, &dropped, &link0)? - } else if end1.g.contains(&i) { - rebuild_face_dropping(f, &subst, &dropped, &link1)? - } else if f.edge_iter().any(|e| subst.contains_key(&e.id())) { - rebuild_face(f, &subst, &[])? - } else { - (*f).clone() - }; - rec.face(&nf, f); - new_faces.push(nf); - } - // The blend face uses each new edge opposite to its neighbour. - let f1_forward = faces.get(i1).is_some_and(|f| f.boundaries().iter().any(|w| w.edge_iter().any(|e| e.id() == edge.id() && e.front() == &v0))); - let reversed = |chain: &[mt::Edge]| chain.iter().rev().map(|e| e.inverse()).collect::>(); - let mut edges_out: Vec = Vec::new(); - if f1_forward { - edges_out.extend(c0.iter().cloned()); - edges_out.push(lb.clone()); - edges_out.extend(reversed(c1)); - edges_out.push(la.inverse()); - } else { - edges_out.push(la.clone()); - edges_out.extend(c1.iter().cloned()); - edges_out.push(lb.inverse()); - edges_out.extend(reversed(c0)); - } - let wire: mt::Wire = edges_out.into(); - let blend_face = match shape { - Shape::Flat => builder::try_attach_plane(&[wire]).map_err(|e| KernelError::Failed(format!("chamfer face: {e}")))?, - Shape::Curvature => { - let ([plane0], [plane1]) = (&end0.planes[..], &end1.planes[..]) else { - return Err(unsupported("G2 fillets require one planar end face at each end")); - }; - let (start, end) = (g2_section(p0, *plane0), g2_section(p1, *plane1)); - // A ruled patch between the two sections stays on the quintic's - // extrusion: corresponding controls differ only along d. Positive - // spans throughout their convex hull keep the surface from folding. - if start.iter().zip(&end).any(|(a, b)| !a.is_finite() || !b.is_finite() || (*b - *a).dot(d) <= tol) { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - let ctrl = start.into_iter().zip(end).map(|(a, b)| vec![p3(a), p3(b)]).collect(); - let bsp = mt::BSplineSurface::new((mt::KnotVec::bezier_knot(5), mt::KnotVec::bezier_knot(1)), ctrl); - let mut surf = mt::Surface::BSplineSurface(bsp); - use mt::ParametricSurface3D; - let nn = surf.normal(0.5, 0.5); - let outward = (t1 + t2) * side; - if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); - } - mt::Face::try_new(vec![wire], surf).map_err(|e| KernelError::Failed(format!("G2 fillet face: {e}")))? - } - Shape::Round => { - // The cylinder, from a cross-section before the first end to one past the second, so - // it holds the end sections wherever the end planes slide them. - let reach = ends - .iter() - .flat_map(|e| e.planes.iter().map(|(_, n)| (s + r) * (1.0 - n.dot(d).powi(2)).max(0.0).sqrt() / n.dot(d).abs())) - .chain(ends.iter().map(|e| e.reach)) - .fold(0.0, f64::max) - + r; - let start = p0 - d * reach; - let (sa, sb) = (start + t1 * s, start + t2 * s); - let c = centre(start); - let mid = c + ((sa - c) + (sb - c)).normalized().unwrap_or(-n1) * r; - let base = builder::circle_arc(&builder::vertex(p3(sa)), &builder::vertex(p3(sb)), p3(mid)); - let swept: mt::Face = builder::tsweep(&base, v3(p1 - p0 + d * (2.0 * reach))); - let mut surf = swept.oriented_surface(); - // Outward normal at the arc middle: away from the centre on a convex edge (the - // centre is in the material), toward it on a concave one. - let outward = (mid - c) * (-side); - use mt::{ParametricSurface3D, SearchParameter}; - if let Some((u, v)) = surf.search_parameter(p3(mid), None, 100) { - let nn = surf.normal(u, v); - if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); - } - } - mt::Face::try_new(vec![wire], surf).map_err(|e| KernelError::Failed(format!("fillet face: {e}")))? + let along = normal(&surfaces[0])?.cross(normal(&surfaces[1])?); + let along = along.normalized()?; + if along.dot(curve_tangent(leader, t)?) < 0.0 { along * -1.0 } else { along } } }; - rec.blend(&blend_face, [edge.id()]); - new_faces.push(blend_face); - let mut shells = solid.boundaries().clone(); - let new_shell: mt::Shell = new_faces.into(); - if let Some(sh) = shells.get_mut(si) { - *sh = new_shell; - } - let solid = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("blend produced an invalid solid: {e}")))?; - Ok((solid, rec)) + d.is_finite().then_some(d) } -/// Quintic Bezier cross-section. The first/last three controls are collinear and -/// equally spaced, so both endpoint second derivatives vanish. Sweeping along a -/// straight edge therefore gives zero normal curvature at both planar side faces. -fn g2_controls(p: Vec3, t1: Vec3, t2: Vec3, setback: f64) -> [Vec3; 6] { - [ - p + t1 * setback, - p + t1 * (setback * 2.0 / 3.0), - p + t1 * (setback / 3.0), - p + t2 * (setback / 3.0), - p + t2 * (setback * 2.0 / 3.0), - p + t2 * setback, - ] -} - -/// Curvature-continuous (G2) fillets between planar faces along straight edges. -/// `radius` sets the same setback as a circular fillet; the profile is not circular. -/// Each end must meet one planar face, which may be oblique to the edge. Unsupported -/// configurations are refused, never replaced with a G1 circular fillet. +/// Curvature-continuous (G2) fillets: each section is SMLib's G2 blend curve between the contact +/// lines the round of `radius` has (zero curvature at the contacts on planar faces), not a +/// circle. A configuration SMLib cannot blend so is refused, never given a circular round. pub fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_g2"); body.require_brep("G2 fillet")?; if !(radius.is_finite() && radius > 1e-6 && radius < 1e6) { return Err(KernelError::Invalid("G2 fillet size must be positive and finite".into())); @@ -1118,707 +210,8 @@ pub fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result { if edges.is_empty() || edges.len() > 1000 || edges.iter().any(|p| ![p.x, p.y, p.z].into_iter().all(f64::is_finite)) { return Err(KernelError::Invalid("G2 fillet needs 1 to 1000 finite edge points".into())); } - let counts = record::counts(&[body]); - let mut cur = crate::boolean_record::healed(body)?; - for p in edges { - let size = cur.size(); - let Some((idx, dist)) = cur.nearest_edge(*p, (size * 2e-3).max(1e-3))? else { - return Err(KernelError::Invalid("the body has no edges".into())); - }; - if dist > size * 0.05 + 1e-3 { - return Err(KernelError::Invalid("no edge near the G2 fillet pick".into())); - } - let solid = cur.deep_copy(); - let edge = Body::unique_edges(&solid).into_iter().nth(idx).ok_or_else(|| KernelError::Invalid("edge index".into()))?; - let (made, rec) = guard("G2 fillet", || blend_one(&solid, &edge, size, radius, Shape::Curvature))?; - cur = record::after(record::rebuilt(made, &[&solid], &rec)?, &cur, &counts); - } - closed(body, cur) -} - -/// Most edges whose other orders are tried when the order given is refused. -const MAX_REORDERED: usize = 4; - -/// All orders of `items` (the given one first). -fn orders(items: &[T]) -> Vec> { - if items.len() <= 1 { - return vec![items.to_vec()]; - } - let mut out = Vec::new(); - for i in 0..items.len() { - let mut rest = items.to_vec(); - let head = rest.remove(i); - for mut tail in orders(&rest) { - tail.insert(0, head.clone()); - out.push(tail); - } - } - out -} - -/// Blend the edges nearest the points, one at a time in an order that works. A blend ends in an -/// earlier round where they meet, which not every order allows (a blend over a round that an -/// edge it runs into left, or past a crease). So when the order given is refused for a reason -/// that is not the size, the other orders are tried too, and when its result has a face whose -/// boundary leaves its surface (a blend that ran on past the end of a round's surface, which a -/// round of a curved edge does not have) another order that has none is preferred. -fn blend(body: &Body, edges: &[Vec3], r: f64, shape: Shape, what: &str) -> Result { - blend_with(body, edges, r, shape, what, false) -} - -/// [`blend`]; `curved_ends`: also roll a ball along a straight edge between planes that ends at -/// a curved face (the last resort, after the corner build for an earlier round there). -fn blend_with(body: &Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, curved_ends: bool) -> Result { - let sound = |b: &Body| crate::tess::boundaries_on_surfaces(&b.solid, (b.size() * 1e-4).max(1e-6)); - let first = blend_in_order(body, edges, r, shape, what, curved_ends); - let reorder = (2..=MAX_REORDERED).contains(&edges.len()) - && match &first { - Ok(b) => !sound(b), - Err(KernelError::Failed(_)) => true, - Err(_) => false, - }; - if !reorder { - return first; - } - let mut fallback: Option = None; - for order in orders(edges).into_iter().skip(1) { - if let Ok(done) = blend_in_order(body, &order, r, shape, what, curved_ends) { - if sound(&done) { - return Ok(done); - } - fallback.get_or_insert(done); - } - } - match (first, fallback) { - (Ok(b), _) => Ok(b), - (Err(e), Some(done)) => { - let _ = e; - Ok(done) - } - (Err(e), None) => Err(e), - } -} - -fn blend_in_order(body: &Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, curved_ends: bool) -> Result { - if !(r.is_finite() && r > 1e-6 && r < 1e6) { - return Err(KernelError::Invalid(format!("{what} size must be positive"))); - } - if edges.is_empty() { - return Err(KernelError::Invalid("no edges selected".into())); - } - if edges.len() > 1000 { - return Err(KernelError::Invalid("too many edges".into())); - } - // Each step's result carries its history over `[body]`. - let counts = record::counts(&[body]); - // Coplanar neighbours as one face (as after a join), so corners look as they should. - let mut cur = crate::boolean_record::healed(body)?; - // The last resort only for edges it treats otherwise: else it repeats the refusal. - if curved_ends { - let solid = cur.deep_copy(); - let ids = edge_ids(&cur, &solid, edges)?; - let other = - Body::unique_edges(&solid).iter().any(|e| ids.contains(&e.id()) && !curved_case(&solid, e, false) && curved_case(&solid, e, true)); - if !other { - return Err(unsupported("no edge ending at a curved face")); - } - } - // Every edge of a convex planar body: rounded as a whole (sphere corners). - if shape == Shape::Round && edges.len() >= 6 { - let solid = cur.deep_copy(); - let all = Body::unique_edges(&solid); - if all.len() == edges.len() { - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let mut hit = std::collections::HashSet::new(); - for p in edges { - if let Some((idx, _)) = cur.nearest_edge(*p, tol)? { - hit.insert(idx); - } - } - if hit.len() == all.len() - && let Ok(b) = crate::polyhedron::round_all_edges(&cur, r) - { - return Ok(record::after(b, &cur, &counts)); - } - } - } - // Whole smooth loops of planar faces are blended in one go, loop by loop. - // Loops and other edges together (every edge of an extruded part): the other edges - // first, which leaves the loops smooth, then the loops. - if let Some((groups, rest)) = loop_split(&cur, edges)? - && !rest.is_empty() - && rest.len() < edges.len() - { - let _ = groups; - let loop_pts: Vec = edges.iter().filter(|p| !rest.iter().any(|q| q.dist(**p) < 1e-12)).copied().collect(); - cur = record::after(blend_in_order(&cur, &rest, r, shape, what, curved_ends)?, &cur, &counts); - return Ok(record::after(blend_in_order(&cur, &loop_pts, r, shape, what, curved_ends)?, &cur, &counts)); - } - // A loop the loop blend refuses for its shape (seams that aren't straight, walls it can't - // trim) is blended edge by edge below instead: a ball rolls along its smooth chain. - if let Some(groups) = loop_groups(&cur, edges)? { - let whole = || -> Result { - let mut lc = cur.clone(); - for g in groups { - let size = lc.size(); - let solid = lc.deep_copy(); - let ids = edge_ids(&lc, &solid, &g)?; - match crate::loopblend::loop_blend(&solid, &ids, size, r, shape == Shape::Round) { - Some(res) => { - let (made, rec) = guard(what, || res)?; - lc = record::after(record::rebuilt(made, &[&solid], &rec)?, &lc, &counts); - } - None => return Err(unsupported("the edges are not a whole loop of a planar face")), - } - } - Ok(lc) - }; - match whole() { - Ok(b) => return Ok(b), - // Too large for the loop (or using up some of its walls) is so edge by edge too. - Err(e) if size_refusal(&e) => return Err(e), - Err(_) => {} - } - } - blend_each(cur, edges, r, shape, what, &counts, curved_ends) -} - -/// The edges blended one at a time (see [`blend`]), `cur` being the healed body. -fn blend_each(mut cur: Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, counts: &[(usize, usize)], curved_ends: bool) -> Result { - let counts = counts.to_vec(); - // One at a time, in whatever order works: a run along a planar face's loop (bridging arcs - // that earlier blends left between selected edges, so corners round off), a single edge, - // or a chain of curved edges. - let mut todo: Vec = edges.to_vec(); - // Edges refused since the last blend that could have changed them: (pick, the box around the - // edge, the refusal). A blend only changes the body near the edges it rounds, so an edge - // refused away from every later blend would be refused the same way again: it is not tried - // again (a refusal costs a rolling-ball attempt, seconds each on a long curved edge). - let mut refused: Vec<(Vec3, Aabb3, KernelError)> = Vec::new(); - // A chain runs on along the edges smooth with a selected one in the body as given, not along - // a round this blend has made meanwhile (which would take in edges nobody selected, or not, - // by the order the edges come in). - let along: Vec = { - let solid = cur.deep_copy(); - let all = Body::unique_edges(&solid); - let tol = (cur.size() * 2e-3).max(1e-3); - let mut list: Vec = Vec::new(); - for p in edges { - if let Some((idx, _)) = cur.nearest_edge(*p, tol)? - && let Some(e) = all.get(idx) - { - let ids = smooth_chain(&solid, e).unwrap_or_else(|| vec![e.id()]); - for x in all.iter().filter(|x| ids.contains(&x.id())) { - if !list.iter().any(|y| y.id() == x.id()) { - list.push(x.clone()); - } - } - } - } - list - }; - let near_chain = (cur.size() * 1e-6).max(1e-7); - let on_chains = |e: &mt::Edge| lies_on(e, &along, near_chain); - for _ in 0..(2 * edges.len() + 4) { - if todo.is_empty() { - return Ok(cur); - } - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let solid = cur.deep_copy(); - if todo.len() >= 2 - && let Some((ids, covered)) = run_on_loop(&cur, &solid, &todo)? - && let Some(Ok((res, rec))) = crate::loopblend::loop_blend(&solid, &ids, size, r, shape == Shape::Round) - && let Ok(b) = guard(what, || Ok(res)).and_then(|res| record::rebuilt(res, &[&solid], &rec)) - { - let near = edges_box(&solid, &ids, r + tol); - refused.retain(|(_, b, _)| !boxes_meet(b, &near)); - cur = record::after(b, &cur, &counts); - todo.retain(|p| !covered.iter().any(|q| q.dist(*p) < 1e-12)); - continue; - } - let mut first_err: Option = None; - let mut done: Option<(Body, Vec, Aabb3)> = None; - for (j, p) in todo.iter().enumerate() { - if let Some((_, _, e)) = refused.iter().find(|(q, _, _)| q.dist(*p) < 1e-12) { - if first_err.is_none() || (matches!(e, KernelError::TooLarge(_)) && !matches!(first_err, Some(KernelError::TooLarge(_)))) { - first_err = Some(e.clone()); - } - continue; - } - let Some((idx, dist)) = cur.nearest_edge(*p, tol)? else { return Err(KernelError::Invalid("the body has no edges".into())) }; - if dist > size * 0.05 + 1e-3 { - return Err(KernelError::Invalid(format!("no edge near {:?}", [p.x, p.y, p.z]))); - } - let edge = Body::unique_edges(&solid).into_iter().nth(idx).ok_or_else(|| KernelError::Invalid("edge index".into()))?; - // Faces that meet smoothly (a round's seam with the face it runs into) leave no - // corner to blend: say so rather than that blending it isn't supported. - if tangent_faces(&solid, &edge) { - if first_err.is_none() { - first_err = Some(KernelError::Invalid(format!( - "the edge at [{:.3}, {:.3}, {:.3}] is smooth: the faces on either side meet tangentially there, so there is no corner to {what}; pick the sharp edges", - p.x, p.y, p.z - ))); - } - continue; - } - // Roll a ball along the edge's smooth chain (the points of `todo` on it go with it). - let roll = |ids: &[mt::EdgeID]| { - let on_chain: Vec = todo - .iter() - .enumerate() - .filter(|(_, q)| { - cur.nearest_edge(**q, tol) - .ok() - .flatten() - .and_then(|(i, _)| Body::unique_edges(&solid).into_iter().nth(i)) - .is_some_and(|x| ids.contains(&x.id())) - }) - .map(|(i, _)| i) - .collect(); - #[cfg(test)] - ROLLS.with(|n| n.set(n.get() + 1)); - guard(what, || crate::curveblend::curve_blend(&solid, ids, size, r, shape == Shape::Round)) - .map(|o| (o, if on_chain.is_empty() { vec![j] } else { on_chain })) - }; - // A straight edge running on smoothly into curved ones (a flange into its bend, a - // side into a rounded corner): the blend follows the whole smooth chain, as the - // rolling ball would. A fillet doesn't run on into an earlier round's arc of its - // radius: it ends in that round (as if both were rounded together). - let chain = smooth_chain_within(&solid, &edge, &on_chains); - let into_round = |ids: &[mt::EdgeID]| { - Body::unique_edges(&solid).iter().any(|x| { - ids.contains(&x.id()) - && x.id() != edge.id() - && [edge.front(), edge.back()].iter().any(|v| x.front() == *v || x.back() == *v) - && crate::curveblend::circle_of(x, size * 1e-6).is_some_and(|c| (c.1 - r).abs() <= r * 1e-4) - }) - }; - let own = edge.id(); - let runs_on = !curved_case(&solid, &edge, false) - && chain.as_ref().is_some_and(|ids| { - ids.len() > 1 - && Body::unique_edges(&solid).iter().any(|x| ids.contains(&x.id()) && !matches!(x.curve(), mt::Curve::Line(_))) - && !(shape == Shape::Round && into_round(ids)) - }); - let local = || guard(what, || blend_one(&solid, &edge, size, r, shape)); - let attempt = match chain.as_deref().filter(|_| runs_on).map(roll) { - Some(Ok(o)) => Ok(o), - // The chain cannot be rolled: the edge alone, locally or as a ball rolled along it - // (ending in the round the chain ran into). - Some(Err(e2)) => local() - .map(|o| (o, vec![j])) - .or_else(|_| if chain.as_ref().is_some_and(|c| c.len() > 1) { roll(&[edge.id()]) } else { Err(e2.clone()) }) - .map_err(|_| e2), - None => match local() { - Ok(o) => Ok((o, vec![j])), - // A curved edge, or one between curved faces: roll a ball along its smooth chain. - Err(e) if !curved_case(&solid, &edge, curved_ends) => Err(e), - Err(e) => match chain.as_deref() { - // The chain that cannot be rolled (it runs on into the edge an earlier round - // left where it met another face): the edge alone, ending on that round. A - // straight edge into an earlier round of this radius: on its own. - Some(ids) => { - let ids = if shape == Shape::Round && !curved_case(&solid, &edge, false) && into_round(ids) { - std::slice::from_ref(&own) - } else { - ids - }; - roll(ids).or_else(|first| if ids.len() > 1 { roll(&[edge.id()]).map_err(|_| first) } else { Err(first) }).map_err(|e2| { - match e2 { - KernelError::TooLarge(m) => KernelError::TooLarge(format!("{m} ({e})")), - e2 => KernelError::Failed(format!("{e2} ({e})")), - } - }) - } - None => Err(e), - }, - }, - }; - // What this attempt could change: the edge and its smooth chain, with room for the blend. - let reach = edges_box(&solid, chain.as_deref().unwrap_or(&[edge.id()]), r + tol); - match attempt.and_then(|((o, rec), js)| record::rebuilt(o, &[&solid], &rec).map(|b| (b, js))) { - Ok((b, js)) => { - done = Some((b, js, reach)); - break; - } - // Reported: the first refusal, unless a later one is a size a smaller radius may - // fit (the others may be refused only until that edge is blended). - Err(e) => { - if first_err.is_none() || (matches!(e, KernelError::TooLarge(_)) && !matches!(first_err, Some(KernelError::TooLarge(_)))) { - first_err = Some(e.clone()); - } - refused.push((*p, reach, e)); - } - } - } - match done { - Some((b, js, near)) => { - refused.retain(|(_, b2, _)| !boxes_meet(b2, &near)); - cur = record::after(b, &cur, &counts); - let mut k = 0; - todo.retain(|_| { - let keep = !js.contains(&k); - k += 1; - keep - }); - } - None => return Err(first_err.unwrap_or_else(|| unsupported("these edges"))), - } - } - if todo.is_empty() { Ok(cur) } else { Err(unsupported("blending these edges together")) } -} - -#[cfg(test)] -thread_local! { - /// Rolling-ball attempts made by [`blend`] on this thread (tests count them). - pub(crate) static ROLLS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// The box around these edges of `solid` (their ends and middles), grown by `margin`. -fn edges_box(solid: &Solid, ids: &[mt::EdgeID], margin: f64) -> Aabb3 { - use mt::{BoundedCurve, ParametricCurve}; - let points = Body::unique_edges(solid).into_iter().filter(|e| ids.contains(&e.id())).flat_map(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=8).map(move |k| from_p3(c.subs(t0 + (t1 - t0) * f64::from(k) / 8.0))) - }); - points.collect::().inflated(margin) -} - -/// Whether two boxes overlap (an empty box meets every box: nothing is known about it). -fn boxes_meet(a: &Aabb3, b: &Aabb3) -> bool { - a.is_empty() || b.is_empty() || a.meets(b) -} - -/// Neighbouring edges along one boundary loop of a planar face that between them hold at least -/// two of the points' edges, joined by arcs that meet them smoothly (left by earlier blends): -/// the run's edge ids and the points it covers. -#[allow(clippy::type_complexity)] -fn run_on_loop(cur: &Body, solid: &Solid, pts: &[Vec3]) -> Result, Vec)>> { - use mt::{BoundedCurve, ParametricCurve}; - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let all = Body::unique_edges(solid); - let mut per: Vec<(Vec3, mt::EdgeID)> = Vec::new(); - for p in pts { - if let Some((idx, dist)) = cur.nearest_edge(*p, tol)? - && dist <= size * 0.05 + 1e-3 - && let Some(e) = all.get(idx) - { - per.push((*p, e.id())); - } - } - let dir = |e: &mt::Edge, at_end: bool| -> Option { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let d = c.der(if at_end { t1 } else { t0 }); - Vec3::new(d.x, d.y, d.z).normalized() - }; - let mut best: Option<(Vec, Vec)> = None; - for f in solid.face_iter() { - if !matches!(f.oriented_surface(), mt::Surface::Plane(_)) { - continue; - } - for w in f.boundaries() { - let es: Vec = w.edge_iter().cloned().collect(); - let m = es.len(); - let sel = |i: usize| es.get(i % m).is_some_and(|e| per.iter().any(|(_, id)| *id == e.id())); - // A filler: an unselected arc meeting both neighbours smoothly. - let smooth = |a: &mt::Edge, b: &mt::Edge| match (dir(a, true), dir(b, false)) { - (Some(x), Some(y)) => x.dot(y) > 1.0 - 1e-6, - _ => false, - }; - let filler = |i: usize| { - let (Some(prev), Some(e), Some(next)) = (es.get((i + m - 1) % m), es.get(i % m), es.get((i + 1) % m)) else { return false }; - !matches!(e.curve(), mt::Curve::Line(_)) && smooth(prev, e) && smooth(e, next) - }; - let usable = |i: usize| sel(i) || filler(i); - if (0..m).all(usable) { - // The whole loop. - if (0..m).filter(|i| sel(*i)).count() >= 2 { - let ids: Vec = es.iter().map(|e| e.id()).collect(); - let covered: Vec = per.iter().filter(|(_, id)| ids.contains(id)).map(|(p, _)| *p).collect(); - if best.as_ref().is_none_or(|b| covered.len() > b.1.len()) { - best = Some((ids, covered)); - } - } - continue; - } - // Runs: start after an unusable edge; trim fillers off both ends. - for s0 in 0..m { - if usable(s0) && !usable(s0 + m - 1) { - let mut idx: Vec = (0..m).map(|j| s0 + j).take_while(|i| usable(*i)).collect(); - while idx.first().is_some_and(|i| !sel(*i)) { - idx.remove(0); - } - while idx.last().is_some_and(|i| !sel(*i)) { - idx.pop(); - } - if idx.iter().filter(|i| sel(**i)).count() < 2 { - continue; - } - let ids: Vec = idx.iter().filter_map(|i| es.get(i % m).map(|e| e.id())).collect(); - // Not yet when another selected edge meets one of the run's inner corners: - // that edge goes first, and the run then rounds the corner. - let inner: Vec = idx.iter().skip(1).filter_map(|i| es.get(i % m).map(|e| e.front().clone())).collect(); - let blocked = per - .iter() - .filter(|(_, id)| !ids.contains(id)) - .any(|(_, id)| all.iter().find(|e| e.id() == *id).is_some_and(|e| inner.iter().any(|v| v == e.front() || v == e.back()))); - if blocked { - continue; - } - let covered: Vec = per.iter().filter(|(_, id)| ids.contains(id)).map(|(p, _)| *p).collect(); - if best.as_ref().is_none_or(|b| covered.len() > b.1.len()) { - best = Some((ids, covered)); - } - } - } - } - } - Ok(best) -} - -/// Is the edge curved, or does it lie between faces that aren't both planar (or, with -/// `curved_ends`, end at one)? -fn curved_case(solid: &Solid, edge: &mt::Edge, curved_ends: bool) -> bool { - if !matches!(edge.curve(), mt::Curve::Line(_)) { - return true; - } - // Between curved faces, or (when asked) ending at one: a straight edge running into a wall. - let curved = |f: &mt::Face| !matches!(f.oriented_surface(), mt::Surface::Plane(_)); - solid.face_iter().filter(|f| f.edge_iter().any(|e| e.id() == edge.id())).any(curved) - || (curved_ends && solid.face_iter().filter(|f| f.vertex_iter().any(|v| v == *edge.front() || v == *edge.back())).any(curved)) -} - -/// Whether the two faces of `edge` meet tangentially along it (sampled at a quarter, the -/// middle and three quarters of the edge): a seam, not a corner. -fn tangent_faces(solid: &Solid, edge: &mt::Edge) -> bool { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchParameter}; - let faces: Vec<&mt::Face> = solid.face_iter().filter(|f| f.edge_iter().any(|e| e.id() == edge.id())).take(3).collect(); - let [f1, f2] = faces[..] else { return false }; - let c = edge.curve(); - let (t0, t1) = c.range_tuple(); - let normal = |f: &mt::Face, q: mt::Point3| -> Option { - let s = f.oriented_surface(); - let (u, v) = s.search_parameter(q, None, 100)?; - let n = s.normal(u, v); - Vec3::new(n.x, n.y, n.z).normalized() - }; - [0.25, 0.5, 0.75].iter().all(|k| { - let q = c.subs(t0 + (t1 - t0) * k); - matches!((normal(f1, q), normal(f2, q)), (Some(a), Some(b)) if a.dot(b) > 1.0 - 1e-6) - }) -} - -/// The chain of edges continuing `edge` smoothly at its ends (its ids): closed, or open where -/// the next edge turns sharply. -pub(crate) fn smooth_chain(solid: &Solid, edge: &mt::Edge) -> Option> { - smooth_chain_within(solid, edge, &|_| true) -} - -/// Whether edge `e` runs along one of `along` (is a piece of it): points through it lie on one. -fn lies_on(e: &mt::Edge, along: &[mt::Edge], tol: f64) -> bool { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - if along.iter().any(|a| a.id() == e.id()) { - return true; - } - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - [0.25, 0.5, 0.75].iter().all(|f| { - let p = c.subs(t0 + (t1 - t0) * f); - along.iter().any(|a| { - let ac = a.curve(); - let (a0, a1) = ac.range_tuple(); - let d = |t: f64| crate::body::from_p3(ac.subs(t)).dist(crate::body::from_p3(p)); - let Some(hint) = (0..=16).map(|i| a0 + (a1 - a0) * i as f64 / 16.0).min_by(|x, y| d(*x).total_cmp(&d(*y))) else { return false }; - let t = ac.search_nearest_parameter(p, hint, 50).unwrap_or(hint).clamp(a0, a1); - d(t).min(d(hint)) <= tol - }) - }) -} - -/// [`smooth_chain`], walking on only over edges `keep` allows. -pub(crate) fn smooth_chain_within(solid: &Solid, edge: &mt::Edge, keep: &dyn Fn(&mt::Edge) -> bool) -> Option> { - use mt::{BoundedCurve, ParametricCurve}; - let all = Body::unique_edges(solid); - // Along the edge as it runs from its front to its back (an edge may run against its curve). - let dir = |e: &mt::Edge, at_end: bool| -> Option { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let d = c.der(if at_end { t1 } else { t0 }); - Vec3::new(d.x, d.y, d.z).normalized() - }; - let mut ids = vec![edge.id()]; - // Walk on from one end of the edge (leaving vertex `v` in direction `d`). - let walk = |mut v: mt::Vertex, mut d: Vec3, ids: &mut Vec, stop: &mt::Vertex| -> Option { - for _ in 0..200 { - if v == *stop { - return Some(true); - } - let next = all.iter().filter(|e| !ids.contains(&e.id()) && (*e.front() == v || *e.back() == v)).find_map(|e| { - let fwd = *e.front() == v; - let t = if fwd { dir(e, false)? } else { -dir(e, true)? }; - (t.dot(d) > 1.0 - 1e-4 && !smooth_seam(solid, e) && keep(e)).then(|| (e.clone(), fwd)) - }); - let Some((e, fwd)) = next else { return Some(false) }; - ids.push(e.id()); - if fwd { - v = e.back().clone(); - d = dir(&e, true)?; - } else { - v = e.front().clone(); - d = -dir(&e, false)?; - } - } - None - }; - let closed = walk(edge.back().clone(), dir(edge, true)?, &mut ids, edge.front())?; - if !closed { - walk(edge.front().clone(), -dir(edge, false)?, &mut ids, edge.back())?; - } - Some(ids) -} - -/// Whether the faces on either side of `e` meet smoothly there (a seam between pieces of one -/// surface, or a round's tangent edge): nothing to blend, so a chain stops before it. -fn smooth_seam(solid: &Solid, e: &mt::Edge) -> bool { - let Some(m) = edge_mid(e) else { return false }; - let normals: Vec = solid - .face_iter() - .filter(|f| f.edge_iter().any(|x| x.id() == e.id())) - .filter_map(|f| crate::curveblend::project(f, m, None).map(|x| x.1)) - .collect(); - matches!(normals[..], [a, b] if a.dot(b) > 1.0 - 1e-6) -} - -pub(crate) fn edge_mid(e: &mt::Edge) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - Some(from_p3(c.subs((t0 + t1) * 0.5))) -} - -/// Do the loop's edges meet tangentially everywhere? -fn smooth_loop(w: &mt::Wire) -> bool { - use mt::{BoundedCurve, ParametricCurve}; - let es: Vec = w.edge_iter().cloned().collect(); - let n = es.len(); - let dir = |e: &mt::Edge, at_end: bool| -> Option { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let t = if at_end { t1 } else { t0 }; - let d = c.der(t); - Vec3::new(d.x, d.y, d.z).normalized() - }; - (0..n).all(|i| match (es.get(i), es.get((i + 1) % n)) { - (Some(a), Some(b)) => match (dir(a, true), dir(b, false)) { - (Some(x), Some(y)) => x.dot(y) > 1.0 - 1e-6, - _ => false, - }, - _ => false, - }) -} - -/// The B-rep edges nearest the points (each once). -fn edge_ids(cur: &Body, solid: &Solid, pts: &[Vec3]) -> Result> { - let all = Body::unique_edges(solid); - let mut ids = Vec::new(); - for p in pts { - if let Some(id) = nearest_edge_id(cur, &all, *p)? - && !ids.contains(&id) - { - ids.push(id); - } - } - Ok(ids) -} - -/// The edge of `all` (`cur`'s edges, in their order) a point picks: the nearest, if near enough. -fn nearest_edge_id(cur: &Body, all: &[mt::Edge], p: Vec3) -> Result> { - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - Ok(match cur.nearest_edge(p, tol)? { - Some((idx, dist)) if dist <= size * 0.05 + 1e-3 => all.get(idx).map(|e| e.id()), - _ => None, - }) -} - -/// When the edges make up whole boundary loops of planar faces: the edge points per loop. -fn loop_groups(cur: &Body, pts: &[Vec3]) -> Result>>> { - Ok(loop_split(cur, pts)?.and_then(|(g, rest)| rest.is_empty().then_some(g))) -} - -/// Edges in whole loops of planar faces (points per loop), and the other edges' points. -fn loop_split(cur: &Body, pts: &[Vec3]) -> Result>, Vec)>> { - let solid = cur.deep_copy(); - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let all = Body::unique_edges(&solid); - // Each point's edge. A point on a vertex is as near to the edges meeting there (a circle - // and a cylinder's seam line): prefer one on a planar face's boundary. - let polys = cur.edges(tol)?; - // Only break actual distance ties. The tessellation tolerance can exceed half a short - // rim edge's length: using it here would pick a nearby wall seam instead (#2498). - let tie_tol = (size * 1e-7).max(1e-9); - let planar_edge: std::collections::HashSet = solid - .face_iter() - .filter(|f| matches!(f.oriented_surface(), mt::Surface::Plane(_))) - .flat_map(|f| f.edge_iter().map(|e| e.id()).collect::>()) - .collect(); - let mut per: Vec<(Vec3, mt::EdgeID)> = Vec::new(); - for p in pts { - let dists: Vec<(usize, f64)> = - polys.iter().map(|e| (e.index, e.points.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min))).collect(); - let best = dists.iter().map(|x| x.1).fold(f64::INFINITY, f64::min); - if best > size * 0.05 + 1e-3 { - return Ok(None); - } - let near: Vec<&mt::Edge> = dists.iter().filter(|x| x.1 <= best + tie_tol).filter_map(|x| all.get(x.0)).collect(); - let Some(e) = near.iter().find(|e| planar_edge.contains(&e.id())).or(near.first()) else { return Ok(None) }; - per.push((*p, e.id())); - } - // Fillets follow tangent chains in the original body. Include those edges before - // recognising a whole loop, too: two picks across a sharp arc/line joint can cover - // the entire rim once each pick's smooth chain is included. - let ids = guard("loop tangent chains", || { - let mut ids: std::collections::HashSet = per.iter().map(|x| x.1).collect(); - for (_, id) in &per { - if let Some(edge) = all.iter().find(|e| e.id() == *id) - && let Some(chain) = smooth_chain(&solid, edge) - { - ids.extend(chain); - } - } - Ok(ids) - })?; - let mut covered: Vec = Vec::new(); - let mut groups = Vec::new(); - for f in solid.face_iter() { - if !matches!(f.oriented_surface(), mt::Surface::Plane(_)) { - continue; - } - for w in f.boundaries() { - let wids: Vec = w.edge_iter().map(|e| e.id()).collect(); - if wids.iter().any(|x| covered.contains(x)) { - continue; - } - // The whole loop is selected, or one of its edges and the loop is smooth (tangent - // chain, which also covers a circle that a boolean left in pieces). - let all_sel = wids.iter().all(|x| ids.contains(x)); - let some_sel = wids.iter().any(|x| ids.contains(x)); - if all_sel || (some_sel && smooth_loop(&w)) { - covered.extend(wids.iter().copied()); - // One point per loop edge, on it. - let pts: Vec = w.edge_iter().filter_map(edge_mid).collect(); - groups.push(pts); - } - } - } - let rest: Vec = per.iter().filter(|(_, id)| !covered.contains(id)).map(|(p, _)| *p).collect(); - Ok((!groups.is_empty()).then_some((groups, rest))) + let out = crate::blend_smlib::fillet_g2(body, edges, radius)?; + closed(body, out) } /// A fillet's result, refused when a face's boundary crosses itself (#871): rounds that @@ -1841,87 +234,292 @@ fn closed(input: &Body, b: Body) -> Result { } } +/// How two constant rounds of one radius turn round a sharp, straight, convex side edge square to +/// both on a plane, such as the rounds along a boss's base at its upright edges. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum FilletTurn { + /// The rounds run on to where they cross and meet in a mitre. + #[default] + Mitre, + /// The rounds end at the side edge and the corner is their section revolved about it, a + /// torus tangent to both. Refused where it is not built (unequal or variable rounds, a + /// concave, curved or tangent side edge, a corner of four edges), with the reason. + Swept, +} + /// Constant-radius fillet of the edges nearest to the given points. A radius too large for the /// faces around the edges is refused with [`KernelError::TooLarge`] ([`fillet_max`] finds the /// largest that works). pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result { + fillet_turning(body, edges, radius, FilletTurn::Mitre) +} + +/// [`fillet`], its rounds turning at side edges as `turn` says. +fn fillet_turning(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet"); body.require_brep("fillet")?; - // A round that would run past its faces into other geometry or another round (#1080). - // Checked once built, so a refusal of the build itself stands as it is. - let size = crate::blend_fit::Size::Round(radius); - match fillet_built(body, edges, radius) { - Ok(b) => crate::blend_fit::accept(body, b, edges, size), - Err(e) => Err(crate::blend_fit::explain(body, edges, size, e)), + crate::blend_smlib::fillet(body, edges, radius, turn).and_then(|b| closed(body, b)) +} + +/// [`fillet`], its rounds turning at side edges as `turn` says, with the picks whose edges are +/// gone: where some of the rounds overflow their faces, those are built first, and a picked edge +/// one of them removes whole is not rounded (the others round what is left of their edges). +pub fn fillet_removing(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<(Body, Vec)> { + let _span = solidcraft_profile::span("kernel", "fillet"); + body.require_brep("fillet")?; + let (b, gone) = crate::blend_smlib::fillet_removing(body, edges, radius, turn)?; + Ok((closed(body, b)?, gone)) +} + +/// What a refusal of a setback too short for its corner says before the least that builds (in +/// mm): SMLib certifies the corner's fill convex only from that setback on ([`fillet_setback`]). +pub const SETBACK_AT_LEAST: &str = "the smallest setback that builds is "; + +/// [`fillet`] with corner setbacks: each `(at, distance)` sets back the corner at the vertex +/// nearest `at`, a vertex where every edge is rounded, so its patch starts `distance` along +/// each of its edges from the vertex (one distance for all of a corner's edges: SMLib keeps one +/// per corner). The rounds run whole up to their sections there, and the patch between them +/// meets each face in a curve from one round's contact line to the next. The distance must reach +/// past where the rounds would meet without it (past the radius at a square corner); a corner +/// where some edge is not rounded is refused as not supported, a setback as long as an edge at +/// its corner as too large. +pub fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_setback"); + body.require_brep("fillet")?; + setbacks_reach(body, edges, radius, setbacks)?; + crate::blend_smlib::fillet_setback(body, edges, radius, setbacks).and_then(|b| closed(body, b)) +} + +/// Refuses a setback that does not reach past where its corner's rounds meet without one +/// ([`setback_minimum`]), naming the least it must exceed, at a corner where every edge is one +/// of `edges` (the others are SMLib's to refuse). SMLib fails there with its own status +/// (smlib_blend_setback): its patch does not join contact lines that already cross. +fn setbacks_reach(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result<()> { + let faces = Faces::of(body)?; + let (picked, _) = crate::blend_smlib::picked_edges(body, edges)?; + let picked: BTreeSet = picked.into_iter().collect(); + for (at, distance) in setbacks { + let Some(v) = corner_vertex(body, &faces, *at) else { continue }; + let all_rounded = (0..faces.rec.edges.len()) + .filter(|e| faces.rec.edges.get(*e).is_some_and(|x| !x.uses.is_empty() && x.vertices.contains(&v))) + .all(|e| picked.contains(&e)); + if !all_rounded { + continue; + } + let Some(least) = setback_minimum(&faces, v, radius) else { continue }; + if *distance <= least * (1.0 + 1e-9) { + let p = faces.point(v).unwrap_or(*at); + let shown = format!("{:.4}", least).trim_end_matches('0').trim_end_matches('.').to_string(); + let why = + if (least - radius).abs() <= radius * 1e-9 { format!("more than the radius ({shown} mm)") } else { format!("more than {shown} mm") }; + return Err(KernelError::Invalid(format!( + "the setback must be {why} at the corner ({:.3}, {:.3}, {:.3}): the rounds' contact lines meet {shown} mm from it along its edges, \ + and the corner's patch starts past that", + p.x, p.y, p.z + ))); + } } + Ok(()) } -/// [`fillet`], once the radius is known to fit. -fn fillet_built(body: &Body, edges: &[Vec3], radius: f64) -> Result { - // Corners the local blends refuse (an earlier round at an edge's end): radius per edge. - blend(body, edges, radius, Shape::Round, "fillet") - .and_then(|b| closed(body, b)) - .or_else(|e| { - let sel: Vec<(Vec3, f64)> = edges.iter().map(|p| (*p, radius)).collect(); - // The local blend's refusal, unless only the corner build found the radius too large. - crate::blend_corner::fillet_radii(body, &sel) - .and_then(|b| closed(body, b)) - .map_err(|e2| keep_size(e, e2)) - // Three edges at a vertex of any faces end in a sphere. - .or_else(|e| { - if edges.len() >= 3 { - crate::blend_vertex::fillet_ball_vertices(body, edges, radius).and_then(|b| closed(body, b)).map_err(|_| e) - } else { - Err(e) - } - }) - }) - // Straight edges ending at a curved face that isn't an earlier round's: a rolling ball - // trimmed by the face. Refused, the refusal above stands. - .or_else(|e| blend_with(body, edges, radius, Shape::Round, "fillet", true).and_then(|b| closed(body, b)).map_err(|_| e)) - // Blends meeting at corners on curved faces: all at once. - .or_else(|e| corners(body, edges, radius, Shape::Round, "fillet", false).and_then(|b| closed(body, b)).map_err(|e2| keep_size(e, e2))) +/// The least setback the corner at the vertex nearest `at` takes with rounds of `radius` +/// ([`setback_minimum`]): a setback there must be more than this, or [`fillet_setback`] and +/// [`fillet_g2_corners`] refuse it. `None` where no vertex is near `at`, or at a corner whose +/// least SMLib decides (one with a curved face or edge). +pub fn fillet_least_setback(body: &Body, at: Vec3, radius: f64) -> Result> { + body.require_brep("fillet")?; + let faces = Faces::of(body)?; + Ok(corner_vertex(body, &faces, at).and_then(|v| setback_minimum(&faces, v, radius))) } -/// The first refusal, unless only the second found the blend too large (a smaller one may fit). -fn keep_size(e: KernelError, e2: KernelError) -> KernelError { - match (&e, e2) { - (KernelError::TooLarge(_), _) => e, - (_, e2 @ KernelError::TooLarge(_)) => e2, - _ => e, +/// The vertex a setback at `at` names: the nearest, within the reach the setbacks take. +fn corner_vertex(body: &Body, faces: &Faces, at: Vec3) -> Option { + let reach = body.size() * 0.05 + 1e-3; + (0..faces.rec.vertices.len()) + .filter_map(|v| u32::try_from(v).ok()) + .filter_map(|v| faces.point(v).map(|p| (p.dist(at), v))) + .filter(|(d, _)| *d <= reach) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, v)| v) +} + +/// The least setback a corner of rounds of `radius` at `vertex` takes: on each face at the +/// corner, the contact lines (rails) of the two rounded edges beside it cross, and a setback +/// must reach past that crossing along both edges (smlib_blend_setback). A rail lies +/// r tan(psi / 2) from its edge, psi the angle between the outward normals of the edge's two +/// faces (r on faces square to each other); the rails of edges at angle alpha on a face, d1 and +/// d2 from them, cross (d2 + d1 cos alpha) / sin alpha along the first edge from the vertex. +/// Exact for planar faces and straight edges; `None` for a corner with any other (left to SMLib) +/// or one it cannot read. +fn setback_minimum(faces: &Faces, vertex: u32, radius: f64) -> Option { + let at: Vec = + (0..faces.rec.edges.len()).filter(|e| faces.rec.edges.get(*e).is_some_and(|x| !x.uses.is_empty() && x.vertices.contains(&vertex))).collect(); + if at.len() < 3 { + return None; } -} - -/// Blend the edges together, rebuilding the corners where they meet on faces of any surface -/// (see [`crate::curveblend::corner_blend`]); with `g2`, the corners where three blends meet are -/// G2 patches ([`crate::corner_g2`]) instead of pieces of the ball's sphere. -fn corners(body: &Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, g2: bool) -> Result { - let counts = record::counts(&[body]); - let cur = crate::boolean_record::healed(body)?; - let size = cur.size(); - let solid = cur.deep_copy(); - let ids = edge_ids(&cur, &solid, edges)?; - if ids.len() != edges.len() { - return Err(KernelError::Invalid("no edge near a selected point".into())); + // Each edge's direction away from the vertex and its rail's distance from it. + let mut away = Vec::with_capacity(at.len()); + let mut rail = Vec::with_capacity(at.len()); + for e in &at { + let [a, b] = faces.rec.edges.get(*e)?.vertices; + if a == b || !faces.straight(*e) { + return None; + } + let (pa, pb) = faces.ends(*e)?; + away.push(if a == vertex { (pb - pa).normalized()? } else { (pa - pb).normalized()? }); + let [f, g]: [u32; 2] = faces.faces_of(*e).into_iter().collect::>().try_into().ok()?; + let cos = faces.plane_normal(f as usize)?.dot(faces.plane_normal(g as usize)?).clamp(-1.0, 1.0); + rail.push(radius * (cos.acos() / 2.0).tan()); } - let (made, rec) = guard(what, || match g2 { - // The corner blend as it always was, bit for bit. - false => crate::curveblend::corner_blend(&solid, &ids, size, r, shape == Shape::Round), - true => crate::curveblend::corner_blend_style(&solid, &ids, size, r, shape == Shape::Round, true), - })?; - Ok(record::after(record::rebuilt(made, &[&solid], &rec)?, &cur, &counts)) + let mut least: f64 = 0.0; + let around: BTreeSet = at.iter().flat_map(|e| faces.faces_of(*e)).collect(); + for f in around { + let beside: Vec = (0..at.len()).filter(|i| at.get(*i).is_some_and(|e| faces.faces_of(*e).contains(&f))).collect(); + let [i, j] = beside[..] else { return None }; + let cos = away.get(i)?.dot(*away.get(j)?).clamp(-1.0, 1.0); + let sin = (1.0 - cos * cos).sqrt(); + if sin <= 1e-9 { + return None; + } + let (di, dj) = (*rail.get(i)?, *rail.get(j)?); + least = least.max((dj + di * cos) / sin).max((di + dj * cos) / sin); + } + (least.is_finite() && least > 0.0).then_some(least) } -/// [`fillet`] whose corners where three blended edges meet are G2 patches: the corner repeats each -/// blend's surface up to the second order (see [`crate::corner_g2`]) instead of the rolling ball's -/// sphere. The corner construction is the all-at-once corner blend, so a configuration it cannot -/// hold is refused rather than quietly given the ball's sphere; [`fillet`] (the default) is -/// unchanged. -pub fn fillet_g2_corners(body: &Body, edges: &[Vec3], radius: f64) -> Result { +/// [`fillet`] whose corners where three or more rounded edges meet are G2 patches +/// ([`crate::corner_g2`]): each such corner is set back, `setbacks` naming a corner by a point at +/// its vertex and the distance its patch starts along each edge there (the others take +/// [`crate::DEFAULT_SETBACK_FACTOR`] times the radius), SMLib leaves it open, and a patch that +/// meets the rounds and the faces round it to the second order fills it. The faces are sewn +/// into one solid, convex corners and concave ones alike. Without such a corner this is +/// [`fillet`]. Refused: a corner where an edge is not rounded, or whose edges are not all of one +/// convexity (SMLib sets back only corners where all are rounded, alike), a setback that does not reach past +/// where the rounds would meet, a hole that is no height field over its plane or a patch that +/// does not meet its neighbours within the tolerances. +pub fn fillet_g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { + g2_corners(body, edges, radius, setbacks, false) +} + +/// [`fillet_g2`] (curvature-continuous sections) whose corners where three or more rounded edges +/// meet are G2 patches, as [`fillet_g2_corners`] builds them: SMLib's own patch at such a corner +/// is only tangent to the rounds (its curvature jumps across their seams), which no +/// curvature-continuous fillet may leave. Without such a corner this is [`fillet_g2`]. Refused +/// as [`fillet_g2_corners`] is. +pub fn fillet_g2_with_g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { + g2_corners(body, edges, radius, setbacks, true) +} + +/// [`fillet_g2_corners`] (circular sections) or [`fillet_g2_with_g2_corners`] (`curvature`). +fn g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)], curvature: bool) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_g2_corners"); body.require_brep("fillet")?; if !(radius.is_finite() && radius > 0.0) { return Err(KernelError::Invalid("the blend radius must be finite and positive".into())); } - corners(body, edges, radius, Shape::Round, "fillet", true).and_then(|b| closed(body, b)) + let (picked, _) = crate::blend_smlib::picked_edges(body, edges)?; + let rec = body.record(); + let picked: BTreeSet = picked.into_iter().collect(); + // Each vertex's edges (a closed edge's one vertex once). + let mut at: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (i, e) in rec.edges.iter().enumerate() { + if e.uses.is_empty() { + continue; + } + for v in e.vertices { + at.entry(v).or_default().insert(i); + } + } + let point = |v: u32| rec.vertices.get(v as usize).map(|x| v3(x.point)); + let mut corners: Vec = Vec::new(); + for (v, around) in &at { + let rounded = around.iter().filter(|e| picked.contains(e)).count(); + if rounded < 3 { + continue; + } + let p = point(*v).ok_or_else(|| KernelError::Failed("fillet: a vertex reference".into()))?; + if rounded < around.len() { + return Err(unsupported(&format!( + "a G2 corner at ({:.3}, {:.3}, {:.3}) where an edge is not rounded (the corner is set back, and SMLib sets back only a corner where every edge is)", + p.x, p.y, p.z + ))); + } + corners.push(p); + } + if corners.is_empty() { + return if curvature { fillet_g2(body, edges, radius) } else { fillet(body, edges, radius) }; + } + // Each corner's setback: the one given at its vertex, else the default. + let reach = body.size() * 0.05 + 1e-3; + let mut distance = vec![crate::corner_g2::DEFAULT_SETBACK_FACTOR * radius; corners.len()]; + for (p, d) in setbacks { + let k = corners + .iter() + .enumerate() + .map(|(k, c)| (c.dist(*p), k)) + .filter(|(d, _)| *d <= reach) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, k)| k) + .ok_or_else(|| { + KernelError::Invalid(format!( + "the setback at ({:.3}, {:.3}, {:.3}) names no G2 corner (a vertex where three or more rounded edges meet)", + p.x, p.y, p.z + )) + })?; + if let Some(slot) = distance.get_mut(k) { + *slot = *d; + } + } + let set_back: Vec<(Vec3, f64)> = corners.iter().copied().zip(distance).collect(); + setbacks_reach(body, edges, radius, &set_back)?; + let open = crate::blend_smlib::fillet_setback_open(body, edges, radius, &set_back, curvature)?; + let mut patches = Vec::with_capacity(open.holes.len()); + for hole in &open.holes { + let (patch, _) = crate::corner_g2::corner_patch(&open.sheet, hole, radius)?; + patches.push(patch); + } + let mut parts: Vec<&Body> = vec![&open.sheet]; + parts.extend(patches.iter()); + let sewn = crate::stitch(&parts, 0.0)?; + let open_shells = sewn.validity(); + if !open_shells.is_empty() { + return Err(KernelError::Failed(format!("fillet: the G2 corners do not close the body: {}", open_shells.join("; ")))); + } + let history = corner_history(&sewn, body, &open.sheet, &patches); + closed(body, sewn.with_checked_history(history, &crate::record::counts(&[body]))) +} + +/// The history of the sewn G2-cornered fillet over `[body]`: the sewing's history (over the +/// sheet and the patches) carried through the sheet's (over the body); each patch face made from +/// the edges whose rounds meet at its corner, as SMLib's own corner patch is, each of its edges +/// the sheet's. +fn corner_history(sewn: &Body, body: &Body, sheet: &Body, patches: &[Body]) -> Option { + use crate::history::{EdgeOrigin, FaceOrigin}; + let outer = sewn.history()?.clone(); + let inner = sheet.history()?; + let mut parts = vec![inner.clone()]; + for patch in patches { + let own = patch.history()?; + // The patch's face comes from the rounded edges the sheet's faces beside it come from. + let mut origins: BTreeSet = BTreeSet::new(); + for e in &own.edges { + for o in &e.origins { + let EdgeOrigin::Edge { edge, .. } = o else { continue }; + for f in inner.edges.get(*edge).map(|x| x.faces.as_slice()).unwrap_or_default() { + let beside = inner.faces.get(*f).map(|x| x.origins.as_slice()).unwrap_or_default(); + origins.extend(beside.iter().copied().filter(|g| matches!(g, FaceOrigin::Edge { .. }))); + } + } + } + let mut h = own.clone().substituted(0, inner).ok()?; + for f in &mut h.faces { + *f = crate::record::generated(origins.iter().copied().collect()); + } + parts.push(h); + } + let h = outer.over(&parts.iter().collect::>()).ok()?; + h.check_counts((sewn.face_count(), sewn.edge_count()), &crate::record::counts(&[body])).ok()?; + Some(h) } /// The step of the radius search: three significant digits of the requested radius. @@ -1930,16 +528,34 @@ fn radius_step(radius: f64) -> f64 { } /// The largest radius below `radius` (to three significant digits) at which the fillet of -/// these edges works, with its result; `None` when none does. Each candidate is a real fillet +/// these edges works, with its result; `Ok(None)` when none does. Each candidate is a real fillet /// of the edges, so the radius returned is one that was built; the search runs up to 16 of -/// them, so it is for an explicit request, not every refusal. -pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64) -> Option<(f64, Body)> { - if !(radius.is_finite() && radius > 1e-6) { - return None; +/// them (a refusal of a fillet feature's exact fit runs it to name the largest that fits, and +/// so does `fit: reduce`). Only a refusal as too large +/// ([`KernelError::TooLarge`]) narrows the search: any other failure of a candidate is the +/// search's error, since a smaller radius would not be the largest that fits. The rounds turn at +/// side edges as `turn` says. +pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result> { + let _span = solidcraft_profile::span("kernel", "fillet_max"); + largest_that_fits(radius, |r| fillet_turning(body, edges, r, turn)) +} + +/// [`fillet_max`] for an equal-distance chamfer of these edges: the largest distance below +/// `distance` (to three significant digits) at which it works, with its result. +pub fn chamfer_max(body: &Body, edges: &[Vec3], distance: f64) -> Result> { + let _span = solidcraft_profile::span("kernel", "chamfer_max"); + largest_that_fits(distance, |d| chamfer(body, edges, d)) +} + +/// The largest size n·q below `size` (q: three significant digits of it) at which `blend` works, +/// by bisection over at most 16 blends; only [`KernelError::TooLarge`] narrows the search. +fn largest_that_fits(size: f64, blend: impl Fn(f64) -> Result) -> Result> { + if !(size.is_finite() && size > 1e-6) { + return Ok(None); } - let q = radius_step(radius); - // Radii n·q for n in [0, hi): hi fails (it is the request, or above it), lo works. - let mut hi = (radius / q).ceil() as u64; + let q = radius_step(size); + // Sizes n·q for n in [0, hi): hi is too large (it is the request, or above it), lo works. + let mut hi = (size / q).ceil() as u64; let mut lo = 0u64; let mut best: Option = None; // log2(10⁴) steps reach the step size; the cap keeps a slow body from stalling. @@ -1948,42 +564,48 @@ pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64) -> Option<(f64, Body break; } let mid = lo + (hi - lo) / 2; - match fillet(body, edges, mid as f64 * q) { + // A candidate fits only as a body SMLib's check accepts: each is checked as it is built, + // whatever the evaluation's validation mode (`crate::validation`). + match crate::validation::validating(crate::Validation::EachStep, || blend(mid as f64 * q)).0 { Ok(b) => { lo = mid; best = Some(b); } - Err(_) => hi = mid, + Err(KernelError::TooLarge(_)) => hi = mid, + Err(e) => return Err(e), } } - best.map(|b| (lo as f64 * q, b)) + Ok(best.map(|b| (lo as f64 * q, b))) } /// [`fillet_max`] for each group of the edges that may limit each other's radius (sharing a /// face or a vertex, directly or through other edges in the group), so a round that fits isn't -/// reduced for a tight edge elsewhere. The radius per edge (in `edges`' order) and the result; -/// one radius for all (as [`fillet_max`]) when a group is refused for another reason than its -/// size, the groups don't build together, or there are too many to search (each search is up -/// to 16 fillets, and this runs in the live preview). -pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Option<(Vec, Body)> { +/// reduced for a tight edge elsewhere. The radius per edge (in `edges`' order) and the result, +/// `Ok(None)` when no radius fits. One radius for all (as [`fillet_max`]) when the groups, +/// each reduced to fit, are too large together, or there are too many to search (each search is +/// up to 16 fillets, and this runs in the live preview). Any failure other than a refusal as too +/// large is the error. +pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result, Body)>> { + let _span = solidcraft_profile::span("kernel", "fillet_max_each"); const MAX_GROUPS: usize = 8; const MAX_SEARCHES: usize = 2; - let one = || fillet_max(body, edges, radius).map(|(r, b)| (vec![r; edges.len()], b)); + let one = || -> Result, Body)>> { Ok(fillet_max(body, edges, radius, turn)?.map(|(r, b)| (vec![r; edges.len()], b))) }; let Some(groups) = interacting_groups(body, edges).filter(|g| g.len() > 1 && g.len() <= MAX_GROUPS) else { return one() }; let mut radii = vec![radius; edges.len()]; let mut searches = 0; for g in &groups { let pts: Vec = g.iter().filter_map(|i| edges.get(*i).copied()).collect(); - let r = match fillet(body, &pts, radius) { + let r = match fillet_turning(body, &pts, radius, turn) { Ok(_) => continue, Err(KernelError::TooLarge(_)) if searches < MAX_SEARCHES => { searches += 1; - match fillet_max(body, &pts, radius) { + match fillet_max(body, &pts, radius, turn)? { Some((r, _)) => r, None => return one(), } } - Err(_) => return one(), + Err(KernelError::TooLarge(_)) => return one(), + Err(e) => return Err(e), }; for i in g { if let Some(x) = radii.get_mut(*i) { @@ -1991,76 +613,44 @@ pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Option<(Vec< } } } - match fillet_each(body, edges, &radii) { - Ok(b) => Some((radii, b)), - Err(_) => one(), + match fillet_each(body, edges, &radii, turn) { + Ok(b) => Ok(Some((radii, b))), + Err(KernelError::TooLarge(_)) => one(), + Err(e) => Err(e), } } -/// The fillet of each edge at its own radius (`radii` in `edges`' order): built together where -/// the corner build takes it, else the edges of each radius together, the largest first. -pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result { +/// The fillet of each edge at its own radius (`radii` in `edges`' order), all in one SMLib +/// blend. +pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64], turn: FilletTurn) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_each"); if radii.len() != edges.len() { return Err(KernelError::Invalid("one radius per edge".into())); } if let Some(r) = radii.first().filter(|r| radii.iter().all(|x| x.to_bits() == r.to_bits())) { - return fillet(body, edges, *r); + return fillet_turning(body, edges, *r, turn); } - let sel: Vec<(Vec3, f64)> = edges.iter().copied().zip(radii.iter().copied()).collect(); - // Each round must fit beside its own edge (#1080); the edges of each radius are checked - // together below. - let fit = |b: Body| -> Result { - for (p, r) in &sel { - crate::blend_fit::check(body, std::slice::from_ref(p), crate::blend_fit::Size::Round(*r))?; - } - Ok(b) - }; - if let Ok(b) = crate::blend_corner::fillet_radii(body, &sel).and_then(|b| closed(body, b)).and_then(fit) { - return Ok(b); - } - let mut by_radius: Vec<(f64, Vec)> = Vec::new(); - for (p, r) in sel { - match by_radius.iter_mut().find(|(x, _)| x.to_bits() == r.to_bits()) { - Some((_, pts)) => pts.push(p), - None => by_radius.push((r, vec![p])), - } - } - by_radius.sort_by(|a, b| b.0.total_cmp(&a.0)); - let mut cur = body.clone(); - for (r, pts) in &by_radius { - cur = fillet(&cur, pts, *r)?; - } - Ok(cur) + body.require_brep("fillet")?; + crate::blend_smlib::fillet_each(body, edges, radii, turn).and_then(|b| closed(body, b)) } -/// The points' edges (found as [`edge_ids`] finds them, on the body as the blends see it) grouped -/// where they share a face or a vertex, directly or through other points' edges: indices into -/// `pts`. `None` when a point has no edge near it. +/// The points' edges (each the edge a blend's pick there takes) grouped where they share a face +/// or a vertex, directly or through other points' edges: indices into `pts`. `None` when a point +/// has no edge near it. fn interacting_groups(body: &Body, pts: &[Vec3]) -> Option>> { - let cur = crate::boolean_record::healed(body).ok()?; - let all = Body::unique_edges(&cur.solid); + let rec = Faces::of(body).ok()?; + let (picked, _) = crate::blend_smlib::picked_edges(body, pts).ok()?; // What each point's edge touches: its faces and its ends. - let mut groups: Vec<(Vec, Vec, Vec)> = Vec::new(); - for (i, p) in pts.iter().enumerate() { - let id = nearest_edge_id(&cur, &all, *p).ok()??; - let edge = all.iter().find(|e| e.id() == id)?; - let mut faces: Vec = cur.solid.face_iter().filter(|f| f.edge_iter().any(|e| e.id() == id)).map(|f| f.id()).collect(); - let mut ends = vec![edge.front().id(), edge.back().id()]; + let mut groups: Vec<(BTreeSet, BTreeSet, Vec)> = Vec::new(); + for (i, idx) in picked.into_iter().enumerate() { + let mut faces = rec.faces_of(idx); + let mut ends: BTreeSet = rec.rec.edges.get(idx)?.vertices.into_iter().collect(); let mut members = vec![i]; // Join every group touching one of these faces or ends. - let (meet, rest): (Vec<_>, Vec<_>) = - groups.into_iter().partition(|(fs, vs, _)| fs.iter().any(|f| faces.contains(f)) || vs.iter().any(|v| ends.contains(v))); + let (meet, rest): (Vec<_>, Vec<_>) = groups.into_iter().partition(|(fs, vs, _)| !fs.is_disjoint(&faces) || !vs.is_disjoint(&ends)); for (fs, vs, ms) in meet { - for f in fs { - if !faces.contains(&f) { - faces.push(f); - } - } - for v in vs { - if !ends.contains(&v) { - ends.push(v); - } - } + faces.extend(fs); + ends.extend(vs); members.extend(ms); } groups = rest; @@ -2077,10 +667,10 @@ fn interacting_groups(body: &Body, pts: &[Vec3]) -> Option>> { ) } -/// Equal-distance chamfer of the edges nearest to the given points. Each edge is cut with a -/// prism whose only face inside the body is the chamfer plane (so neighbouring chamfers meet in -/// a mitre); the local operation is the fallback. +/// Equal-distance chamfer of the edges nearest to the given points, `distance` back along each +/// face, neighbouring chamfers meeting in a mitre. pub fn chamfer(body: &Body, edges: &[Vec3], distance: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "chamfer"); body.require_brep("chamfer")?; if !(distance.is_finite() && distance > 1e-6 && distance < 1e6) { return Err(KernelError::Invalid("chamfer size must be positive".into())); @@ -2088,217 +678,9 @@ pub fn chamfer(body: &Body, edges: &[Vec3], distance: f64) -> Result { if edges.is_empty() || edges.len() > 1000 { return Err(KernelError::Invalid("select 1…1000 edges".into())); } - // A chamfer that would run past its faces into other geometry or another chamfer, or whose - // result changes more than the chamfers can (#1080). - let size = crate::blend_fit::Size::Chamfer(distance); - match chamfer_built(body, edges, distance) { - Ok(b) => crate::blend_fit::accept(body, b, edges, size), - Err(e) => Err(crate::blend_fit::explain(body, edges, size, e)), - } + crate::blend_smlib::chamfer(body, edges, distance) } -/// [`chamfer`], once the size is known to fit. -fn chamfer_built(body: &Body, edges: &[Vec3], distance: f64) -> Result { - // Each step's result carries its history over `[body]`. - let counts = record::counts(&[body]); - // All cutters at once (their union mitres the corners), else one edge at a time. - // A hole corner's mitre extension runs into the wall, and the union of those cutters - // notches it. Those edges take the local blend below, which is one bevel (#814). - let tools: Result> = edges.iter().enumerate().map(|(i, p)| chamfer_tool(body, *p, distance, i)).collect(); - let notch = tools.as_ref().ok().is_some_and(|ts| ts.iter().any(|t| t.extension_inside)); - // The union of the cutters, cut from the body they were built on. - let batch = |tools: &[Cutter]| -> Option { - let mut acc: Option<(Body, Option)> = None; - for t in tools { - let next = match &acc { - None => Some((t.body.clone(), Some(History::identity(&t.body)))), - Some((a, h)) => crate::ops::boolean(a, &t.body, crate::BoolOp::Union).ok().flatten().map(|u| { - let h = crate::boolean_record::through(&u, 0, h.as_ref()); - (u, h) - }), - }; - next.as_ref()?; - acc = next; - } - let (tool, h) = acc?; - let r = crate::ops::boolean(body, &tool, crate::BoolOp::Cut).ok().flatten()?; - let h = cut_history(crate::boolean_record::through(&r, 1, h.as_ref()), body, tools); - Some(r.with_checked_history(h, &counts)) - }; - if !notch - && let Ok(tools) = &tools - && let Some(r) = batch(tools) - { - return Ok(r); - } - // At a pocket rim the cutters cannot extend beyond the selected edges. Rebuild - // the corners locally, allowing adjacent chamfers to reach different depths - // on their common wall seam. - if !notch - && edges.len() > 1 - && let Ok(result) = crate::blend_corner::chamfer(body, edges, distance) - { - return Ok(result); - } - // Coplanar neighbours as one face (as after a join), so corners look as they should. - let cur = crate::boolean_record::healed(body)?; - if let Some(groups) = loop_groups(&cur, edges)? { - let whole = || -> Result { - let mut lc = cur.clone(); - for g in groups { - let size = lc.size(); - let solid = lc.deep_copy(); - let ids = edge_ids(&lc, &solid, &g)?; - match crate::loopblend::loop_blend(&solid, &ids, size, distance, false) { - Some(res) => { - let (made, rec) = guard("chamfer", || res)?; - lc = record::after(record::rebuilt(made, &[&solid], &rec)?, &lc, &counts); - } - None => return Err(unsupported("the edges are not a whole loop of a planar face")), - } - } - Ok(lc) - }; - // Refused for its shape, the loop is chamfered edge by edge below ([`blend`] falls back - // the same way); too large stays too large. - match whole() { - Ok(b) => return Ok(b), - Err(e) if size_refusal(&e) => return Err(e), - Err(_) => {} - } - } - // A curved blend follows the whole tangent chain. Give it all picks together so - // picks on that chain are consumed once, rather than chamfering its new rails again. - if tools.is_err() && edges.len() > 1 { - let solid = cur.deep_copy(); - let ids = edge_ids(&cur, &solid, edges)?; - let all = Body::unique_edges(&solid); - let same_chain = ids - .first() - .and_then(|id| all.iter().find(|e| e.id() == *id)) - .and_then(|e| smooth_chain(&solid, e)) - .is_some_and(|chain| ids.len() > 1 && ids.iter().all(|id| chain.contains(id))); - if same_chain && let Ok(result) = blend(&cur, edges, distance, Shape::Flat, "chamfer") { - return Ok(result); - } - } - let start = cur.clone(); - let one_by_one = || -> Result { - let mut cur = start.clone(); - // Set once a step has changed the body, so a later miss cannot restart from the cutters. - let mut progressed = false; - // A chain running on into curved faces, or an edge ending at one: as for fillets. - let blend_or_curved = |cur: &Body, p: &Vec3| -> Result { - blend(cur, std::slice::from_ref(p), distance, Shape::Flat, "chamfer") - .or_else(|e| blend_with(cur, std::slice::from_ref(p), distance, Shape::Flat, "chamfer", true).map_err(|_| e)) - .or_else(|e| { - chamfer_tool_curved(cur, *p, distance) - .and_then(|tool| cut_one(cur, &tool)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))) - .map_err(|_| e) - }) - }; - for p in edges { - let tool = chamfer_tool(&cur, *p, distance, 0); - // The extension is inside the wall. The local blend is one bevel on a hole corner. - // Where that blend cannot build the edge, the cutter is what used to succeed (#814). - let inside = tool.as_ref().ok().is_some_and(|t| t.extension_inside); - let step = if inside { - match blend(&cur, std::slice::from_ref(p), distance, Shape::Flat, "chamfer") { - Ok(b) => b, - Err(miss) => match tool.and_then(|t| cut_one(&cur, &t)) { - Ok(Some(b)) => b, - // Healing can leave an edge the blend cannot end, and a cutter rebuilt on - // the healed body cannot cut it. Nothing has been applied yet, so the - // cutters built on the original body are what used to succeed - // (oracle/69-sm-tray). A hole corner does not get here: its bevel builds. - _ if !progressed => { - if let Ok(tools) = &tools - && let Some(r) = batch(tools) - { - return Ok(r); - } - blend_or_curved(&cur, p).map_err(|_| miss)? - } - _ => blend_or_curved(&cur, p).map_err(|_| miss)?, - }, - } - } else { - match tool.and_then(|t| cut_one(&cur, &t)) { - Ok(Some(b)) => b, - _ => blend_or_curved(&cur, p)?, - } - }; - progressed = true; - cur = record::after(step, &cur, &counts); - } - Ok(cur) - }; - // Chamfers meeting at corners on curved faces: all at once. - one_by_one().or_else(|e| corners(body, edges, distance, Shape::Flat, "chamfer", false).map_err(|e2| keep_size(e, e2))) -} - -/// `cur` cut by one cutter, with its history over `[cur]` (`None`: nothing left). -fn cut_one(cur: &Body, t: &Cutter) -> Result> { - let counts = record::counts(&[cur]); - Ok(crate::ops::boolean(cur, &t.body, crate::BoolOp::Cut)?.map(|r| { - let h = cut_history(r.history().cloned(), cur, std::slice::from_ref(t)); - r.with_checked_history(h, &counts) - })) -} - -/// A cut of `cur` by cutters (their union), from its history `h` over `[cur, cutter 0, …]`, as -/// over `[cur]`: each cutter's chamfer face is made in place of its edge, and nothing else of a -/// cutter may be left (`None` where something is). -fn cut_history(h: Option, cur: &Body, tools: &[Cutter]) -> Option { - let parts: Vec = std::iter::once(History::identity(cur)).chain(tools.iter().map(Cutter::history)).collect(); - crate::boolean_record::composed(h?.over(&parts.iter().collect::>())) -} - -/// Geometry of a straight convex edge between two planar faces. -struct EdgeFrame { - p0: Vec3, - p1: Vec3, - d: Vec3, - n1: Vec3, - n2: Vec3, - t1: Vec3, - t2: Vec3, -} - -/// The edge nearest `p` (its index in `cur`'s edge order) and its frame. -fn edge_frame(cur: &Body, p: Vec3) -> Result<(usize, EdgeFrame)> { - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let Some((idx, dist)) = cur.nearest_edge(p, tol)? else { return Err(KernelError::Invalid("the body has no edges".into())) }; - if dist > size * 0.05 + 1e-3 { - return Err(KernelError::Invalid(format!("no edge near {:?}", [p.x, p.y, p.z]))); - } - let solid = &*cur.solid; - let edge = Body::unique_edges(solid).into_iter().nth(idx).ok_or_else(|| KernelError::Invalid("edge index".into()))?; - if !matches!(edge.curve(), mt::Curve::Line(_)) { - return Err(unsupported("only straight edges")); - } - let faces: Vec<&mt::Face> = solid.face_iter().filter(|f| f.edge_iter().any(|e| e.id() == edge.id())).collect(); - let [f1, f2] = faces[..] else { return Err(unsupported("the edge is not between two faces")) }; - let (Some(n1), Some(n2)) = (plane_normal(f1), plane_normal(f2)) else { return Err(unsupported("both faces next to the edge must be planar")) }; - let (p0, p1) = (vtx(edge.absolute_front()), vtx(edge.absolute_back())); - let d = (p1 - p0).normalized().ok_or_else(|| KernelError::Failed("zero-length edge".into()))?; - let mut t1 = n1.cross(d); - if t1.dot(n2) > 0.0 { - t1 = -t1; - } - let mut t2 = n2.cross(d); - if t2.dot(n1) > 0.0 { - t2 = -t2; - } - if n1.dot(t2) > 1e-9 || n2.dot(t1) > 1e-9 || t1.dot(t2) < -1.0 + 1e-6 { - return Err(unsupported("only convex edges")); - } - Ok((idx, EdgeFrame { p0, p1, d, n1, n2, t1, t2 })) -} - -/// The prism that cuts a chamfer of size `s` on the edge nearest `p`. `k` varies the parts that -/// stay outside the body so that neighbouring cutters don't share edges. /// The second side of an unequal chamfer: a distance along the other face, or the angle the /// chamfer makes with the first face. #[derive(Clone, Copy, Debug, PartialEq)] @@ -2309,10 +691,8 @@ pub enum ChamferSide { /// A chamfer with different setbacks on the two faces of each edge: `d1` along the first face /// (the one facing up most, the other with `flip`), the second side by distance or angle. -/// Straight edges between planar faces are cut by prisms; curved edges where a planar face meets -/// a wall (a circular rim between a plane and a cylinder or cone, convex or concave, and loops of -/// lines and arcs) are chamfered along that face's loop. pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool) -> Result { + let _span = solidcraft_profile::span("kernel", "chamfer_sides"); body.require_brep("chamfer")?; let ok = |x: f64| x.is_finite() && x > 1e-6 && x < 1e6; let valid = ok(d1) @@ -2326,344 +706,534 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl if edges.is_empty() || edges.len() > 1000 { return Err(KernelError::Invalid("select 1…1000 edges".into())); } - let size = crate::blend_fit::Size::Sides(d1, side, flip); - let counts = record::counts(&[body]); - let cut = || -> Result { - let mut cur = crate::boolean_record::operand(body, 0, &counts); - for (k, p) in edges.iter().enumerate() { - let t = chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k)?; - let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?; - cur = record::after(step, &cur, &counts); - } - Ok(cur) - }; - // A curved edge picked: the prisms cannot cut it, and cutting the others first moves what - // its pick lands on. - let picks_curved = { - let solid = body.deep_copy(); - let ids = edge_ids(body, &solid, edges)?; - guard("chamfer", || Ok(Body::unique_edges(&solid).iter().any(|x| ids.contains(&x.id()) && curved_case(&solid, x, false))))? - }; - let cur = match picks_curved { - true => chamfer_sides_curved(body, edges, d1, side, flip, None)?, - false => match cut() { - Ok(cur) => cur, - Err(e) => chamfer_sides_curved(body, edges, d1, side, flip, Some(e))?, - }, - }; - crate::blend_fit::accept(body, cur, edges, size) + crate::blend_smlib::chamfer_sides(body, edges, d1, side, flip) } -/// [`chamfer_sides`] of a selection with curved edges, or one the prisms could not cut (`e`: -/// why) with edges running on smoothly into curved ones: whole loops of planar faces and runs of -/// one are chamfered along the loop ([`crate::loopblend::loop_chamfer_sides`]), other edges still -/// by a prism. A selection of straight edges only keeps the prisms' refusal. -fn chamfer_sides_curved(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool, e: Option) -> Result { - let counts = record::counts(&[body]); - let mut cur = crate::boolean_record::healed(body)?; - let curved = { - let solid = cur.deep_copy(); - let ids = edge_ids(&cur, &solid, edges)?; - guard("chamfer", || { - let all = Body::unique_edges(&solid); - let curved = |x: &mt::Edge| curved_case(&solid, x, false); - Ok(all - .iter() - .filter(|x| ids.contains(&x.id())) - .any(|x| curved(x) || smooth_chain(&solid, x).is_some_and(|chain| all.iter().any(|y| chain.contains(&y.id()) && curved(y))))) - })? - }; - if !curved { - return Err(e.unwrap_or_else(|| unsupported("these edges"))); +/// The edge each pick takes, as a blend takes it (an index in the body's edge order, the order +/// of its mesh's edges): the nearest, and at a vertex where a seam or a smooth join meets a sharp +/// edge (a cylinder's seam at its rim), the sharp edge. Picks that find no edge are refused. +pub fn blend_edges(body: &Body, picks: &[Vec3]) -> Result> { + crate::blend_smlib::picked_edges(body, picks).map(|(edges, _)| edges) +} + +/// The picked edges' tangent chains, for a blend that is to run along them: `picks` (each the +/// nearest edge of `body` to it), then a point on every other edge that continues one of them +/// tangentially (within 0.5° at a shared vertex), until no more do. Each pick takes its edge as a +/// blend does (a pick at a vertex where a seam meets a rim takes the rim). An edge only one face +/// uses ends a chain, and so do a seam and a smooth edge (its two faces meet tangentially, within +/// 0.5°, all along it): they have no corner to round. A chain does not run on into an edge of the +/// other convexity (a boss's concave base running on tangentially as the convex rim of its +/// overhang): a round cannot pass from one side of the faces to the other, so it ends at that +/// vertex. +/// Picks that find no edge are refused. +pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { + if picks.is_empty() || picks.len() > 1000 || picks.iter().any(|p| !p.is_finite()) { + return Err(KernelError::Invalid("select 1…1000 edges by finite points".into())); } - // The loop chamfer of the edges nearest `pts`, all on one planar face's loop. - let along_loop = |cur: &Body, pts: &[Vec3]| -> Result { - let size = cur.size(); - let solid = cur.deep_copy(); - let ids = edge_ids(cur, &solid, pts)?; - match crate::loopblend::loop_chamfer_sides(&solid, &ids, size, d1, side, flip) { - Some(res) => { - let (made, rec) = guard("chamfer", || res)?; - Ok(record::after(record::rebuilt(made, &[&solid], &rec)?, cur, &counts)) - } - None => Err(unsupported( - "a two-distance or distance-angle chamfer of a curved edge that is not on the boundary of a planar face (an equal-distance chamfer may work there)", - )), + let rec = Faces::of(body)?; + let (seeds, hidden) = crate::blend_smlib::picked_edges(body, picks)?; + let mut picked: Vec = Vec::new(); + for e in seeds { + if !picked.contains(&e) { + picked.push(e); } - }; - let (groups, rest) = loop_split(&cur, edges)?.unwrap_or_else(|| (Vec::new(), edges.to_vec())); - for g in &groups { - cur = along_loop(&cur, g)?; } - for (k, p) in rest.iter().enumerate() { - cur = match chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k) { - Ok(t) => { - let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?; - record::after(step, &cur, &counts) - } - Err(_) => along_loop(&cur, std::slice::from_ref(p))?, + let chain = chain_of(&rec, &picked, &hidden)?; + let mut out = picks.to_vec(); + for e in chain.into_iter().skip(picked.len()) { + out.push(edge_middle(&rec, e).ok_or_else(|| KernelError::Failed("a point on a chain edge".into()))?); + } + Ok(out) +} + +/// Edges meeting at an angle (radians) below this continue one another; faces meeting at an +/// angle below it meet tangentially, a smooth edge with nothing to round. One value for smooth +/// everywhere: the shaded view's ([`crate::smooth_edges::ANGLE`], half a degree), so an edge +/// the view draws can be rounded and one it hides is smooth. +const TANGENT: f64 = crate::smooth_edges::ANGLE; + +/// The point halfway along edge `e`. +fn edge_middle(rec: &Faces, e: usize) -> Option { + let edge = rec.rec.edges.get(e)?; + CurveEval::new(edge.parameters()).ok().and_then(|c| c.point(0.5 * (edge.interval[0] + edge.interval[1]))) +} + +/// How far from a face's surface a point may lie for its normal there. +fn normal_reach(rec: &Faces) -> f64 { + rec.rec.tolerance.max(1e-7) * 10.0 +} + +/// Whether edge `e`'s two uses meet tangentially (within [`TANGENT`]) all along it: a +/// smooth edge, with no corner to blend (a seam a face meets itself across is one). An edge +/// whose faces are tangent at one end only (a round running into a wall it is tangent to where +/// the wall meets its face) is a crease everywhere else, which is not smooth; nor is a cusp, its +/// faces folded back on each other (outward normals opposite), which SMLib rounds like any other +/// edge. Decided exactly from the faces' surfaces and the uses' pcurves +/// ([`crate::tangent_edge`]). +fn smooth_join(rec: &Faces, e: usize) -> Result { + crate::tangent_edge::tangent_all_along(&rec.rec, |f| rec.side(f), e, TANGENT) +} + +/// `seeds` (edges in the record's order, each once), then every other edge that continues one +/// of them tangentially, as [`tangent_chain`] follows them; `hidden` marks the edges a pick +/// passes over. +fn chain_of(rec: &Faces, seeds: &[usize], hidden: &[bool]) -> Result> { + let mut chain = seeds.to_vec(); + // Each edge's smoothness, decided once. + let mut smooth: Vec> = vec![None; rec.rec.edges.len()]; + let mut smooth_at = |f: usize| -> Result { + if let Some(known) = smooth.get(f).copied().flatten() { + return Ok(known); + } + let s = smooth_join(rec, f)?; + if let Some(slot) = smooth.get_mut(f) { + *slot = Some(s); + } + Ok(s) + }; + // The unit direction edge `e` leaves its end `v` in. + let leaving = |e: usize, v: u32| -> Option { + let [a, b] = rec.rec.edges.get(e)?.vertices; + if a == b { + return None; + } + if a == v { rec.tangent(e, false) } else { rec.tangent(e, true).map(|t| t * -1.0) } + }; + let cos = TANGENT.cos(); + let accept = normal_reach(rec); + // Whether edge `e` is convex at its end `v` (its faces meet at less than 180° inside the + // body): the direction into its second face, square to it, points against its first face's + // outward normal. A face lies to the left of its loop seen from its surface's natural normal. + // None for an edge without exactly two uses, or where a normal cannot be found. + let convex = |e: usize, v: u32| -> Option { + let edge = rec.rec.edges.get(e)?; + let [ua, ub] = edge.uses.as_slice() else { return None }; + let forward_b = match rec.rec.faces.get(ub.face as usize)?.loops.get(ub.r#loop as usize)? { + Loop::Edges { edges } => edges.get(ub.position as usize)?.forward, + Loop::Vertex { .. } => return None, }; - } - Ok(cur) -} - -/// The prism that cuts a chamfer: the body, which of its faces is the chamfer plane, and the -/// edge (of the body it chamfers, in its edge order) that face is made in place of. -pub(crate) struct Cutter { - body: Body, - face: Option, - edge: usize, - /// The mitre extension at mid-edge lies in the body. On a convex edge it stays outside. - /// On a hole corner it runs into the walls, and the cutter bites them (#814). - extension_inside: bool, -} - -impl Cutter { - /// The cutter as made from the body it chamfers: its chamfer face in place of the edge, its - /// other faces (all outside that body) from nothing of it. - fn history(&self) -> History { - let faces = (0..self.body.face_count()) - .map(|i| record::generated(if Some(i) == self.face { vec![FaceOrigin::Edge { operand: 0, edge: self.edge }] } else { Vec::new() })) - .collect(); - record::from_faces(&self.body.solid, 1, faces) - } -} - -pub(crate) fn chamfer_tool(cur: &Body, p: Vec3, s: f64, k: usize) -> Result { - let tool = chamfer_tool_sides(cur, p, s, None, k)?; - // A straight edge that runs on into a curved one (a slot's side into its end arc) is one - // tangent chain: the cutter would chamfer the straight part only, and whether its overshoot - // reaches the next edge's material depends on the size of the part (#2672). The blend - // follows the whole chain, as it does for a fillet. - let all = Body::unique_edges(&cur.solid); - let curved_chain = all - .get(tool.edge) - .and_then(|e| smooth_chain(&cur.solid, e)) - .is_some_and(|ids| all.iter().any(|e| ids.contains(&e.id()) && !matches!(e.curve(), mt::Curve::Line(_)))); - if curved_chain { - return Err(unsupported("a straight edge continued by a curved one is chamfered with its chain")); - } - Ok(tool) -} - -/// A straight plane/cylinder edge has one constant chamfer section. Sweep its cutter -/// through the ends and let the boolean trim it against the actual end faces. In particular, -/// a small planar seam left by a tangent cut need not be extended into a rounded end (#2408). -fn chamfer_tool_curved(cur: &Body, pick: Vec3, distance: f64) -> Result { - guard("straight curved chamfer", || { - let size = cur.size(); - let tolerance = (size * 1e-7).max(1e-9); - let (index, gap) = cur.nearest_edge(pick, (size * 2e-3).max(1e-3))?.ok_or_else(|| unsupported("no chamfer edge"))?; - if gap > size * 0.05 + 1e-3 { - return Err(unsupported("no nearby chamfer edge")); - } - let edge = Body::unique_edges(&cur.solid).into_iter().nth(index).ok_or_else(|| unsupported("chamfer edge"))?; - if !crate::curveblend::straight(&edge, tolerance * 10.0) { - return Err(unsupported("a straight plane/cylinder edge is required")); - } - let (p0, p1) = (vtx(edge.absolute_front()), vtx(edge.absolute_back())); - let along = (p1 - p0).normalized().ok_or_else(|| unsupported("zero-length chamfer edge"))?; - let faces: Vec<_> = cur.solid.face_iter().filter(|f| f.edge_iter().any(|e| e.id() == edge.id())).collect(); - let [f1, f2] = faces.as_slice() else { return Err(unsupported("the edge must have two faces")) }; - let kinds = (crate::surface_kind::surface_of(f1, size), crate::surface_kind::surface_of(f2, size)); - let (normal, axis) = match kinds { - (Some(crate::FaceSurface::Plane { normal, .. }), Some(crate::FaceSurface::Cylinder { axis, .. })) - | (Some(crate::FaceSurface::Cylinder { axis, .. }), Some(crate::FaceSurface::Plane { normal, .. })) => (normal, axis), - _ => return Err(unsupported("a straight plane/cylinder edge is required")), - }; - // A boolean intersection can carry slightly displaced ends and supporting surfaces. - // Check angular alignment here, then the swept contacts against the actual surfaces. - if normal.dot(axis).abs() > 1e-5 || axis.cross(along).len() > 1e-5 { - return Err(unsupported("the cylinder must run along the chamfer edge")); - } - let d = if axis.dot(along) < 0.0 { -axis } else { axis }; - let mid = (p0 + p1) * 0.5; - let (n1, n2) = ( - crate::curveblend::project(f1, mid, None).map(|p| p.1).ok_or_else(|| unsupported("chamfer normal"))?, - crate::curveblend::project(f2, mid, None).map(|p| p.1).ok_or_else(|| unsupported("chamfer normal"))?, - ); - let used = f1.boundary_iters().into_iter().flatten().find(|e| e.id() == edge.id()).ok_or_else(|| unsupported("chamfer edge use"))?; - let tangent = (vtx(used.back()) - vtx(used.front())).normalized().ok_or_else(|| unsupported("chamfer tangent"))?; - if tangent.dot(n1.cross(n2)) <= 1e-9 { - return Err(unsupported("a convex chamfer edge is required")); - } - let (a, b) = crate::curveblend::straight_chamfer_contacts(f1, f2, mid, *d, distance, tolerance) - .ok_or_else(|| unsupported("the chamfer section does not fit"))?; - let fit_tolerance = (size * 1e-5).clamp(1e-5, 0.001); - for (face, point) in [(*f1, a), (*f2, b)] { - for along in [-0.5, -0.25, 0.0, 0.25, 0.5] { - let swept = point + d * (along * p0.dist(p1)); - if crate::curveblend::project(face, swept, None).is_none_or(|(q, _, _)| q.dist(swept) > fit_tolerance) { - return Err(unsupported("the chamfer section varies along the edge")); + let p = rec.point(v)?; + let along = rec.tangent(e, edge.vertices[0] != v)?; + let natural_b = rec.normal_at(ub.face as usize, p, accept)? * rec.side(ub.face as usize)?; + let into_b = natural_b.cross(if forward_b { along } else { along * -1.0 }); + Some(into_b.dot(rec.normal_at(ua.face as usize, p, accept)?) < 0.0) + }; + let mut k = 0; + while k < chain.len() { + let Some(&e) = chain.get(k) else { break }; + k += 1; + let Some(edge) = rec.rec.edges.get(e) else { continue }; + for v in edge.vertices { + let Some(d) = leaving(e, v) else { continue }; + for (f, other) in rec.rec.edges.iter().enumerate() { + let passed_over = hidden.get(f).copied().unwrap_or(false); + if passed_over || chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) || smooth_at(f)? { + continue; + } + let turns_over = matches!((convex(e, v), convex(f, v)), (Some(a), Some(b)) if a != b); + if !turns_over && leaving(f, v).is_some_and(|g| d.dot(g) < -cos) { + chain.push(f); } } } - // Contacts must lie on the trimmed faces, not merely their infinite supports. A - // fine mesh and an inward probe larger than its chord error also reject a bevel that - // has already used up the top face. Reuse that mesh for all cutter clearance probes. - let mesh = cur.tessellate_with(tolerance * 10.0, true)?; - let inset = (tolerance * 100.0).min(distance * 0.01); - for (face, point) in [(*f1, a), (*f2, b)] { - let (_, normal, _) = crate::curveblend::project(face, point, None).ok_or_else(|| unsupported("chamfer contact"))?; - if !mesh.contains(point - normal * inset) { - return Err(too_large("the chamfer runs past a neighbouring face")); - } - } - let outward = (n1 + n2).normalized().ok_or_else(|| unsupported("chamfer direction"))?; - let across = (a - b).normalized().ok_or_else(|| unsupported("chamfer section"))?; - let reach = distance * 4.0 + size * 0.02; - let center = (a + b + mid) / 3.0; - let a = a + across * reach; - let b = b - across * reach; - if mesh.contains(a) || mesh.contains(b) { - return Err(unsupported("the chamfer cutter crosses a neighbouring face")); - } - let extension = (distance * 2.0).max(size * 0.01); - let half = p0.dist(p1) * 0.5; - if [-1.0, 1.0].into_iter().any(|side| mesh.contains(center + d * (side * (half + extension * 0.5)))) { - return Err(unsupported("chamfers ending at a concave corner")); - } - let plane = solidcraft_geom::Plane::from_normal(mid - d * (p0.dist(p1) * 0.5 + extension), d).ok_or_else(|| unsupported("chamfer plane"))?; - let points = [a, b, mid + outward * reach].map(|q| plane.to_local(q)); - let mut profile = solidcraft_geom::Loop2::polygon(&points); - let mut segment = 0; - if profile.signed_area() < 0.0 { - profile = profile.reversed(); - segment = profile.segs.len().saturating_sub(1); - } - let region = solidcraft_geom::Region2 { outer: profile, holes: vec![] }; - let body = - crate::build::extrude(&plane, &[region], 0.0, p0.dist(p1) + 2.0 * extension)?.pop().ok_or_else(|| unsupported("chamfer cutter"))?; - let face = body.history().and_then(|h| h.faces.iter().position(|f| f.origins == [FaceOrigin::Profile { segment }])); - Ok(Cutter { body, face, edge: index, extension_inside: false }) - }) + } + Ok(chain) } -fn chamfer_tool_sides(cur: &Body, p: Vec3, s: f64, sides: Option<(ChamferSide, bool)>, k: usize) -> Result { - let (edge, mut f) = edge_frame(cur, p)?; - // Setbacks along each face: equal, or by the second side's rule. - let (s1, s2) = match sides { - None => (s, s), - Some((side, flip)) => { - // Side 1: the face facing up most (then +y, +x), unless flipped. - let up = Vec3::new(1e-6, 1e-3, 1.0); - if (f.n2.dot(up) > f.n1.dot(up)) != flip { - std::mem::swap(&mut f.n1, &mut f.n2); - std::mem::swap(&mut f.t1, &mut f.t2); +/// Before blending exactly `edges` (the record's edges `picks` took, in order): refuses an edge +/// whose faces meet tangentially (a smooth edge, nothing to round), and names the first edge a +/// picked one runs on into tangentially without being blended with it, if any (tangent +/// propagation off). SMLib blends the picked edges alone where it can end a blend there (a round +/// ending on the round it runs into); where it can't, [`with_continuation`] says why. +pub(crate) fn unfinished_chain(body: &Body, picks: &[Vec3], edges: &[usize], hidden: &[bool]) -> Result> { + let rec = Faces::of(body)?; + let at = |i: usize| picks.get(i).map(|p| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)).unwrap_or_default(); + for (i, &e) in edges.iter().enumerate() { + if smooth_join(&rec, e)? { + return Err(KernelError::Invalid(format!("the edge at {} is smooth: its faces meet tangentially, so there is nothing to round", at(i)))); + } + } + let mut seeds: Vec = Vec::new(); + for &e in edges { + if !seeds.contains(&e) { + seeds.push(e); + } + } + Ok(chain_of(&rec, &seeds, hidden)?.get(seeds.len()).and_then(|&next| edge_middle(&rec, next))) +} + +/// Before rounding exactly `edges` (the record's edges `picks` took, in order), edge i at radius +/// `radii[i]`: refuses a round too small to change the part. Across a crease whose faces' normals +/// turn by δ, a round of radius r lies r·(sec(δ/2) − 1) (≈ r·δ²/8) inside the sharp edge at its +/// middle, the farthest it moves the part; below the edge's tolerance the round is the edge +/// itself to the model's accuracy (SMLib refuses to build it). δ is the least turn along the edge +/// ([`crate::tangent_edge::least_angle_along`]); the message names the smallest radius that +/// rounds it, tolerance / (sec(δ/2) − 1), rounded up to the micrometre. +pub(crate) fn rounds_too_small(body: &Body, picks: &[Vec3], edges: &[usize], radii: &[f64]) -> Result<()> { + let rec = Faces::of(body)?; + for (i, (&e, &r)) in edges.iter().zip(radii).enumerate() { + let Some(edge) = rec.rec.edges.get(e) else { continue }; + let tolerance = edge.tolerance.max(rec.rec.tolerance); + let Some(turn) = crate::tangent_edge::least_angle_along(&rec.rec, |f| rec.side(f), e)? else { continue }; + let reach = 1.0 / (0.5 * turn).cos() - 1.0; + if !(turn > TANGENT && reach.is_finite() && reach > 0.0) || r * reach >= tolerance { + continue; + } + let at = picks.get(i).map(|p| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)).unwrap_or_default(); + let smallest = (tolerance / reach * 1e3).ceil() / 1e3; + return Err(KernelError::Invalid(format!( + "a round of radius {r} mm on the edge at {at} is too small: its faces turn only {:.2}° across the edge, so the round stays within the model's tolerance ({tolerance} mm) of it and changes nothing; the smallest radius that rounds this edge is {smallest:.3} mm", + turn.to_degrees() + ))); + } + Ok(()) +} + +/// Refuses a round whose section would cut through the material into a hollow behind its edge, +/// opening the part (a slit into the hollow, or a cut through the part): the owner's rule of +/// 2026-10-30, as [`KernelError::TooLarge`], so a fillet feature names the largest radius that +/// fits. A round running past a rim of its faces into open air is left to the blend (tangent +/// where it has room, cut where it runs out). +/// +/// Decided exactly in the section square to a picked straight edge between two planar faces +/// (A and B, convex): the round's circle of radius r has its centre at E + r k, the point at +/// depth r below both planes (k = −(n_A + n_B)/(1 + n_A·n_B)), and removes the region between the +/// edge E and its arc. That region grows with r. Material behind the faces first opens into a +/// hollow where the arc, moving away from E, uncovers a point q of the body's boundary strictly +/// inside the wedge with no material just beyond it (toward the centre): q lies on the circle, +/// |q − E − r k| = r, whose larger root in r is where it opens ([`opening_radius`]). Where the +/// strips of faces A and B themselves leave their faces, the round runs out past a rim into the +/// air, which is not a point of this kind (it lies on a face's plane, not inside the wedge). +/// +/// The boundary points looked at run along the edge, so their section is the same all along the +/// stretch they share with it: straight edges parallel to it (a hollow's corner), cylindrical +/// faces about axes parallel to it (a hollow's rounded corner), and a picked concave edge parallel +/// to it, rounded in the same fillet (the arc of its round, which fills the hollow's corner). +/// Whether the point uncovered is material is the body's exact point classification. +pub(crate) fn rounds_into_hollow(body: &Body, picks: &[Vec3], edges: &[usize], radii: &[f64]) -> Result<()> { + let rec = Faces::of(body)?; + for (i, (&e, &r)) in edges.iter().zip(radii).enumerate() { + let Some(section) = Section::of(&rec, e) else { continue }; + let Some((opens, at)) = section.opening(body, &rec, edges, radii)? else { continue }; + if r <= opens + section.tolerance { + continue; + } + let pick = picks.get(i).map(|p| format!(" at ({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)).unwrap_or_default(); + return Err(KernelError::TooLarge(format!( + "the round of radius {r} mm on the edge{pick} would cut through the material behind it into the hollow at ({:.3}, {:.3}, \ + {:.3}) and open the part", + at.x, at.y, at.z + ))); + } + Ok(()) +} + +/// The section of a round of a straight, convex edge between two planar faces, as +/// [`rounds_into_hollow`] reads it. +struct Section { + /// The edge's start, its unit direction and its length. + start: Vec3, + dir: Vec3, + length: f64, + /// The faces' outward unit normals. + na: Vec3, + nb: Vec3, + /// The centre of the round of radius r is at `start + r k` in the section through `start`. + k: Vec3, + tolerance: f64, +} + +impl Section { + fn of(rec: &Faces, e: usize) -> Option
{ + if !rec.straight(e) { + return None; + } + let [fa, fb] = <[u32; 2]>::try_from(rec.faces_of(e).into_iter().collect::>()).ok()?; + let (na, nb) = (rec.plane_normal(fa as usize)?, rec.plane_normal(fb as usize)?); + let (start, end) = rec.ends(e)?; + let length = start.dist(end); + let dir = (end - start).normalized()?; + let g = na.dot(nb); + if !(g.is_finite() && g.abs() < 1.0 - 1e-9) { + return None; + } + // Convex: going into face A from the edge goes below face B's plane. + let use_a = rec.uses(fa as usize).find(|u| u.edge as usize == e)?; + let into_a = rec.direction_into_face(fa as usize, use_a)?; + if into_a.dot(nb) >= 0.0 { + return None; + } + let tolerance = rec.rec.edges.get(e)?.tolerance.max(rec.rec.tolerance).max(1e-9); + let k = (na + nb) * (-1.0 / (1.0 + g)); + Some(Section { start, dir, length, na, nb, k, tolerance }) + } + + /// `p − start` without its part along the edge: its place in the section. + fn flat(&self, p: Vec3) -> Vec3 { + let w = p - self.start; + w - self.dir * w.dot(self.dir) + } + + /// Whether `p` (in the section) runs along the edge: a direction parallel to it. + fn parallel(&self, d: Vec3) -> bool { + d.normalized().is_some_and(|d| d.cross(self.dir).len() <= 1e-9) + } + + /// The stretch `[lo, hi]` along the edge (from its start) that `[a, b]` (points' places along + /// it) shares with it, its middle; `None` where they share none. + fn shared(&self, a: f64, b: f64) -> Option { + let (lo, hi) = (a.min(b).max(0.0), a.max(b).min(self.length)); + (hi - lo > self.tolerance).then_some(0.5 * (lo + hi)) + } + + /// The smallest radius at which the round opens into a hollow behind it and the point where it + /// does (at the middle of the stretch the opening runs along); `None` where it never does + /// through the boundary looked at ([`rounds_into_hollow`]). `edges` and `radii`: the fillet's. + fn opening(&self, body: &Body, rec: &Faces, edges: &[usize], radii: &[f64]) -> Result> { + let mut best: Option<(f64, Vec3)> = None; + let mut keep = |found: Option<(f64, Vec3)>| { + if let Some((r, p)) = found + && best.is_none_or(|(b, _)| r < b) + { + best = Some((r, p)); } - let s2 = match side { - ChamferSide::Distance(d) => d, - ChamferSide::Angle(a) => { - // The triangle edge–A–B: angle φ at the edge, `a` at A (on face 1). - let phi = f.t1.dot(f.t2).clamp(-1.0, 1.0).acos(); - let den = (phi + a).sin(); - if den <= 1e-9 { - return Err(KernelError::Invalid("that chamfer angle runs past the other face".into())); - } - s * a.sin() / den - } + }; + // Straight edges parallel to the round's: a hollow's corner, or a picked concave edge whose + // round of its own fills it. + for (j, edge) in rec.rec.edges.iter().enumerate() { + if !matches!(edge.curve, Curve::Line { .. }) { + continue; + } + let Some((a, b)) = rec.ends(j) else { continue }; + if !self.parallel(b - a) { + continue; + } + let Some(middle) = self.shared((a - self.start).dot(self.dir), (b - self.start).dot(self.dir)) else { continue }; + // The round's own edge, and edges on its line, lie at the section's origin. + let q = self.flat(a); + if q.len() <= self.tolerance { + continue; + } + let found = match edges.iter().position(|&p| p == j) { + Some(at) => match (concave_round_centre(rec, j, radii.get(at).copied()), radii.get(at)) { + (Some((o, arc)), Some(&rho)) => self.through_circle(body, self.flat(o), rho, middle, Some(arc))?, + _ => None, + }, + None => self.through_point(body, q, middle)?, }; - (s, s2) + keep(found); } - }; - let s = s1.max(s2); - let size = cur.size(); - let len = f.p0.dist(f.p1); - let ext = (s * 2.0).max(size * 0.01) * (1.0 + 0.093 * (k % 5) as f64); - // Cross-section at p0 - d*ext, in a plane with normal d. - let base = f.p0 - f.d * ext; - let plane = solidcraft_geom::Plane::from_normal(base, f.d).ok_or_else(|| KernelError::Failed("chamfer plane".into()))?; - let a = base + f.t1 * s1; - let b = base + f.t2 * s2; - let ab = (a - b).normalized().ok_or_else(|| KernelError::Failed("chamfer".into()))?; - let out = (f.n1 + f.n2).normalized().ok_or_else(|| KernelError::Failed("chamfer".into()))?; - let vary = 1.0 + 0.137 * (k % 7) as f64; - let reach = (s * 4.0 + size * 0.02) * vary; - let a_ext = a + ab * (s * 0.5 + reach * 0.05); - let b_ext = b - ab * (s * 0.5 + reach * 0.07); - let e_far = base + out * reach; - // The cross-section sits past the edge ends, so test the offset at mid-edge. The cutter - // is still built: a caller that cannot blend the edge keeps it (#814). - let mid_edge = (f.p0 + f.p1) * 0.5; - let extension_inside = cur.contains(mid_edge + (a_ext - base)) || cur.contains(mid_edge + (b_ext - base)); - // The material beyond both ends must be empty (the cutter runs past them). - let mid = (a + b + base) / 3.0; - for probe in [mid + f.d * (ext * 0.5), mid + f.d * (len + ext * 1.5)] { - if cur.contains(probe) { - return Err(unsupported("chamfers ending at a concave corner")); + // Cylindrical faces about axes parallel to the edge: a hollow's rounded corner. + for (f, face) in rec.rec.faces.iter().enumerate() { + let Surface::Cylinder { frame, radius } = &face.surface else { continue }; + if !self.parallel(v3(frame.x_axis).cross(v3(frame.y_axis))) { + continue; + } + let along: Vec = + rec.uses(f).filter_map(|u| rec.ends(u.edge as usize)).flat_map(|(a, b)| [a, b]).map(|p| (p - self.start).dot(self.dir)).collect(); + let (lo, hi) = along.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(*t), hi.max(*t))); + let Some(middle) = self.shared(lo, hi) else { continue }; + keep(self.through_circle(body, self.flat(v3(frame.origin)), *radius, middle, None)?); + } + Ok(best) + } + + /// Where the round opens through the section point `q` (a boundary point running along the + /// edge): its larger radius on the circle through `q`, when `q` then lies on the round's arc + /// strictly inside the wedge and no material lies just beyond it, toward the centre. + fn through_point(&self, body: &Body, q: Vec3, middle: f64) -> Result> { + // |q − r k|² = r²: (|k|² − 1) r² − 2 (q·k) r + |q|² = 0. + let Some(r) = larger_root(self.k.len2() - 1.0, q.dot(self.k), q.len2()) else { return Ok(None) }; + self.opens_at(body, r, q, middle) + } + + /// Where the round opens through a circle of the section, centre `o`, radius `rho`, with the + /// hollow inside it: where the circle's far point from the round's centre reaches the round's + /// arc (|o − r k| + rho = r). `arc`: the directions from `o` the circle is the boundary + /// along, when it is a picked concave edge's round, not yet built. + fn through_circle(&self, body: &Body, o: Vec3, rho: f64, middle: f64, arc: Option<(Vec3, Vec3)>) -> Result> { + // |o − r k|² = (r − rho)²: (|k|² − 1) r² − 2 (o·k − rho) r + |o|² − rho² = 0. + let Some(r) = larger_root(self.k.len2() - 1.0, o.dot(self.k) - rho, o.len2() - rho * rho) else { return Ok(None) }; + let Some(out) = (o - self.k * r).normalized() else { return Ok(None) }; + let q = o + out * rho; + match arc { + Some((m1, m2)) => { + // On the concave round's own arc: between its two contacts, seen from its centre. + if !within(out, m1, m2, self.tolerance / rho.max(1.0)) { + return Ok(None); + } + self.opens_at(body, r, q, middle) + } + None => { + // On the face itself. + if body.classify_point(self.place(q, middle))? != crate::body::PointClass::OnBoundary { + return Ok(None); + } + self.opens_at(body, r, q, middle) + } } } - // So must its far side: it reaches several times the chamfer's size out from the edge, and - // beside a wall (a pin standing in a socket) that is inside the wall, which the cut would - // take a bite out of. - if [0.0, ext + len * 0.5, len + 2.0 * ext].iter().any(|t| cur.contains(e_far + f.d * *t)) { - return Err(unsupported("the chamfer cutter reaches other material")); + + /// The section point `q` at `middle` along the edge. + fn place(&self, q: Vec3, middle: f64) -> Vec3 { + self.start + self.dir * middle + q } - let loc: Vec = [a_ext, b_ext, e_far].iter().map(|q| plane.to_local(*q)).collect(); - let mut lp = solidcraft_geom::Loop2::polygon(&loc); - // The chamfer plane is swept from the segment a → b: first, or last once turned round. - let mut chamfer_segment = 0; - if lp.signed_area() < 0.0 { - lp = lp.reversed(); - chamfer_segment = lp.segs.len().saturating_sub(1); + + /// `Some((r, q placed))` when, at radius `r`, `q` lies on the round's arc strictly inside the + /// wedge and the body has no material just beyond it toward the centre. + fn opens_at(&self, body: &Body, r: f64, q: Vec3, middle: f64) -> Result> { + if !(r.is_finite() && r > self.tolerance) { + return Ok(None); + } + let centre = self.k * r; + // q − centre = α n_A + β n_B with α, β > 0: on the arc between the contacts. + if !within(q - centre, self.na, self.nb, self.tolerance) { + return Ok(None); + } + let Some(inward) = (centre - q).normalized() else { return Ok(None) }; + let step = (r * 1e-3).max(self.tolerance * 10.0); + let at = self.place(q, middle); + Ok((body.classify_point(at + inward * step)? == crate::body::PointClass::Outside).then_some((r, at))) + } +} + +/// Whether `w` = α a + β b with α, β > `margin` (a, b unit, not parallel). +fn within(w: Vec3, a: Vec3, b: Vec3, margin: f64) -> bool { + let g = a.dot(b); + let det = 1.0 - g * g; + if !(det > 1e-12) { + return false; + } + let (wa, wb) = (w.dot(a), w.dot(b)); + let alpha = (wa - g * wb) / det; + let beta = (wb - g * wa) / det; + alpha > margin && beta > margin +} + +/// The larger root of a x² − 2 b x + c = 0 (a > 0). +fn larger_root(a: f64, b: f64, c: f64) -> Option { + let disc = b * b - a * c; + (a > 1e-12 && disc >= 0.0).then(|| (b + disc.sqrt()) / a).filter(|r| r.is_finite()) +} + +/// The centre of the round of radius `r` of concave straight edge `e` between planar faces, and +/// the directions from it to the round's two contacts: the circle tangent to both faces' planes +/// on the side away from the material. +fn concave_round_centre(rec: &Faces, e: usize, r: Option) -> Option<(Vec3, (Vec3, Vec3))> { + let r = r?; + let [f1, f2] = <[u32; 2]>::try_from(rec.faces_of(e).into_iter().collect::>()).ok()?; + let (n1, n2) = (rec.plane_normal(f1 as usize)?, rec.plane_normal(f2 as usize)?); + let use1 = rec.uses(f1 as usize).find(|u| u.edge as usize == e)?; + // Concave: going into face 1 from the edge goes above face 2's plane. + if rec.direction_into_face(f1 as usize, use1)?.dot(n2) <= 0.0 { + return None; + } + let g = n1.dot(n2); + if !(g.is_finite() && g.abs() < 1.0 - 1e-9) { + return None; + } + let (a, _) = rec.ends(e)?; + Some((a + (n1 + n2) * (r / (1.0 + g)), (-n1, -n2))) +} + +/// A blend's failure where a picked edge continues tangentially into `next`, an edge left out +/// ([`unfinished_chain`]): SMLib rounds a tangent chain as one sequence and could not end the +/// blend there, so the reason and the way out are named. +pub(crate) fn with_continuation(e: KernelError, next: Option) -> KernelError { + let Some(p) = next else { return e }; + let why = format!( + " (a picked edge continues tangentially into the edge at ({:.3}, {:.3}, {:.3}), which is not blended with it, and the blend \ + cannot end there: with tangent propagation on, tangent_chain: true, its tangent chain is blended as one)", + p.x, p.y, p.z + ); + match e { + KernelError::Invalid(m) => KernelError::Invalid(m + &why), + KernelError::Failed(m) => KernelError::Failed(m + &why), + KernelError::TooLarge(m) => KernelError::TooLarge(m + &why), + e => e, } - let region = solidcraft_geom::Region2 { outer: lp, holes: vec![] }; - let body = crate::build::extrude(&plane, &[region], 0.0, len + 2.0 * ext)?.pop().ok_or_else(|| KernelError::Failed("chamfer tool".into()))?; - let face = body.history().and_then(|h| h.faces.iter().position(|f| f.origins == [FaceOrigin::Profile { segment: chamfer_segment }])); - Ok(Cutter { body, face, edge, extension_inside }) } #[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; + + /// A round (`round`) or an equal-distance chamfer of the edges nearest `pts`. + fn blend(body: &Body, pts: &[Vec3], size: f64, round: bool) -> Result { + if round { fillet(body, pts, size) } else { chamfer(body, pts, size) } + } + + fn vol(b: &Body) -> f64 { + b.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume + } + + /// Whether a vertex of `b` lies within `tol` of `p`. + fn has_vertex(b: &Body, p: Vec3, tol: f64) -> bool { + crate::native::brep_record(b).unwrap().vertices.iter().any(|v| v3(v.point).dist(p) < tol) + } + + /// The ladder's 08-chamfers/008: a boss on a block, rounded where it meets the block, picked + /// at the top of its seam. The pick takes the top rim, and the chain keeps to it: it never + /// runs down the seam into the round's own seam, which continues it tangentially. + #[test] + fn a_chain_picked_where_a_seam_meets_a_rim_keeps_to_the_rim() { + let block = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); + let boss = crate::build::cylinder(Vec3::new(15.0, 15.0, 20.0), Vec3::Z, 8.0, 10.0).unwrap(); + let joined = crate::boolean(&block, &boss, crate::BoolOp::Union).unwrap().unwrap(); + let rec = joined.record(); + // The seam: the edge both of whose uses lie on the boss's side. + let seam = rec.edges.iter().find(|e| e.uses.len() == 2 && e.uses[0].face == e.uses[1].face).unwrap(); + let ends = seam.vertices.map(|v| v3(rec.vertices[v as usize].point)); + let (foot, top) = if ends[0].z < ends[1].z { (ends[0], ends[1]) } else { (ends[1], ends[0]) }; + let rounded = fillet(&joined, &[foot], 1.0).unwrap(); + let chain = tangent_chain(&rounded, &[top]).unwrap(); + assert_eq!(chain, vec![top], "the chain left the top rim"); + assert!(chamfer(&rounded, &chain, 1.0).is_ok()); + // Even from a pick on the seam itself, the chain takes no seam: the round's continues + // the boss's tangentially but has no corner to blend. + let side = (top + Vec3::new(top.x, top.y, 21.0)) * 0.5; + assert_eq!(tangent_chain(&rounded, &[side]).unwrap(), vec![side], "the chain ran into the round's seam"); + } + + /// Smoothness is decided all along an edge. A bar 40 × 16 × 10 whose front face runs tangent + /// into a cylinder R8 at its far end, its front top edge rounded r2: the round's contact with + /// the front face and the front face's tangent line with the wall are smooth (plane against + /// cylinder, tangent all along); the round's edge with the wall is tangent at its lower end + /// (40, 0, 8) only, a crease everywhere else; a box edge is a crease. A knife edge (a wall of + /// radius 21 running out into a plane, #851: its faces tangent all along but folded back on + /// each other) is a cusp, which is not smooth. + #[test] + fn an_edge_is_smooth_only_where_its_faces_are_tangent_all_along_it() { + let bar = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 16.0, 10.0)).unwrap(); + let post = crate::build::cylinder(Vec3::new(40.0, 8.0, 0.0), Vec3::Z, 8.0, 20.0).unwrap(); + let peg = crate::boolean(&bar, &post, crate::BoolOp::Union).unwrap().unwrap(); + let rounded = fillet(&peg, &[Vec3::new(20.0, 0.0, 10.0)], 2.0).unwrap(); + let rec = Faces::of(&rounded).unwrap(); + let smooth = |p: Vec3| smooth_join(&rec, blend_edges(&rounded, &[p]).unwrap()[0]).unwrap(); + assert!(smooth(Vec3::new(20.0, 0.0, 8.0)), "the round's contact with the front face"); + assert!(smooth(Vec3::new(40.0, 0.0, 4.0)), "the front face's tangent line with the wall"); + assert!(!smooth(Vec3::new(37.2641, 0.4827, 9.3025)), "the round's edge with the wall"); + assert!(!smooth(Vec3::new(20.0, 0.0, 0.0)), "the bar's front bottom edge"); + let tip = 62.0 + 1.0 / 6.0; + let slab = crate::build::box_solid(Vec3::new(0.0, -21.0, 0.0), Vec3::new(tip, 0.0, 10.0)).unwrap(); + let disc = crate::build::cylinder(Vec3::new(tip, -21.0, 0.0), Vec3::Z, 21.0, 10.0).unwrap(); + let knife = crate::boolean(&slab, &disc, crate::BoolOp::Cut).unwrap().unwrap(); + let rec = Faces::of(&knife).unwrap(); + assert!(!smooth_join(&rec, blend_edges(&knife, &[Vec3::new(tip, 0.0, 5.0)]).unwrap()[0]).unwrap(), "the knife edge"); + } #[test] - fn g2_fillet_has_zero_curvature_at_both_planar_rails() { - use mt::{InnerSpace, ParametricCurve, ParametricSurface}; + fn g2_fillet_takes_off_what_the_round_does() { let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); let out = fillet_g2(&body, &[Vec3::new(20.0, 0.0, 10.0)], 2.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.face_count(), body.face_count() + 1); - let solid = out.deep_copy(); - let face = solid.boundaries().iter().flat_map(|s| s.face_iter()).find(|f| matches!(f.surface(), mt::Surface::BSplineSurface(_))).unwrap(); - let surf = face.surface(); - // Inversion may swap the surface parameters. At each rail, curvature - // must vanish in *every* direction, while the two tangent vectors stay regular. - let mut rails = 0; - for (u, v) in [(0.0, 0.5), (1.0, 0.5), (0.5, 0.0), (0.5, 1.0)] { - let p = from_p3(surf.subs(u, v)); - if (p.x - 20.0).abs() > 1e-8 && p.y.abs() > 1e-8 { - continue; - } - let (du, dv) = (surf.uder(u, v), surf.vder(u, v)); - let n = du.cross(dv); - assert!(n.magnitude2() > 1e-8); - let expected = if p.y.abs() < 1e-8 { mt::Vector3::unit_y() } else { mt::Vector3::unit_x() }; - assert!(n.cross(expected).magnitude2() < 1e-12); - for second in [surf.uuder(u, v), surf.uvder(u, v), surf.vvder(u, v)] { - assert!(second.dot(n).abs() < 1e-8); - } - rails += 1; - } - assert_eq!(rails, 2); - // End sections are exact quintics, with regular tangents and zero endpoint curvature. - let mut sections = 0; - for edge in face.edge_iter() { - if let mt::Curve::BSplineCurve(c) = edge.curve() { - for t in [0.0, 1.0] { - let d = c.der(t); - assert!(d.magnitude2() > 1e-8); - assert!(d.cross(c.der2(t)).magnitude2() < 1e-12); - } - sections += 1; - } - } - assert_eq!(sections, 2); - // Independent analytic area: integrating x(t) y'(t) for the quintic - // gives 113/756 times setback² for a right-angle corner. - let volume = out.tessellate(0.0001).unwrap().measure().volume; - let expected = 8000.0 - (113.0 / 756.0) * 4.0 * 20.0; + // The curvature section's default thumbweight is equal area: on the round's rails it takes + // off what the round does, (1 - pi/4) setback² at a right-angle corner. + let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; + let expected = 8000.0 - (1.0 - std::f64::consts::FRAC_PI_4) * 4.0 * 20.0; assert!((volume - expected).abs() < 0.02, "{volume} vs {expected}"); } @@ -2680,8 +1250,8 @@ mod tests { let body = crate::build::extrude(&Plane::XY, &[Region2 { outer: lp, holes: vec![] }], 0.0, 20.0).unwrap().remove(0); let out = fillet_g2(&body, &[Vec3::new(10.0, 10.0, 10.0)], 2.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); - let volume = out.tessellate(0.0001).unwrap().measure().volume; - let expected = 6000.0 + (113.0 / 756.0) * 4.0 * 20.0; + let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; + let expected = 6000.0 + (1.0 - std::f64::consts::FRAC_PI_4) * 4.0 * 20.0; assert!((volume - expected).abs() < 0.02, "{volume} vs {expected}"); let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); let out = fillet_g2(&body, &[Vec3::new(20.0, 0.0, 10.0), Vec3::new(0.0, 20.0, 10.0)], 2.0).unwrap(); @@ -2692,8 +1262,6 @@ mod tests { #[test] fn g2_fillet_refuses_sections_crossing_a_cap_hole() { // The hole lies inside the setback without touching either side face. - // The larger quintic crosses its loop on both perpendicular end faces, - // even though the rebuilt shell is closed according to topology alone. let region = Region2 { outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(20.0, 0.0), Vec2::new(20.0, 20.0), Vec2::new(0.0, 20.0)]), holes: vec![Loop2::circle(Vec2::new(0.5, 0.5), 0.15)], @@ -2706,22 +1274,13 @@ mod tests { assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.crossed_face_loops().unwrap(), 0); assert_eq!(out.face_count(), body.face_count() + 1); - let result = fillet_g2(&body, &[pick], 2.0); - if let Ok(out) = &result { - eprintln!("accepted G2 result: validity={:?}, crossed_faces={}", out.validity(), out.crossed_face_loops().unwrap()); - } - assert!(matches!( - result, - Err(KernelError::Failed(message)) if message.contains("rounds would leave openings") - )); + assert!(fillet_g2(&body, &[pick], 2.0).is_err()); } } #[test] - fn g2_fillet_meets_sloped_planar_ends_with_zero_rail_curvature() { - use mt::{InnerSpace, ParametricCurve, ParametricSurface, SearchParameter}; - // Inward and outward sloping ends, and one square end, in two orientations. - // Outward slopes need end curves beyond the old edge's axial range (#2708). + fn g2_fillet_meets_sloped_planar_ends() { + // Inward and outward sloping ends, and one square end, in two orientations (#2708). for plane in [Plane::XY, Plane::XZ] { for (left, right) in [(-0.5, -0.5), (0.5, 0.5), (0.0, 0.5), (-0.25, 0.5)] { let region = Region2 { @@ -2734,53 +1293,12 @@ mod tests { assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.crossed_face_loops().unwrap(), 0); assert_eq!(out.face_count(), 7); - let solid = out.deep_copy(); - let face = solid.face_iter().find(|f| matches!(f.surface(), mt::Surface::BSplineSurface(_))).unwrap(); - let surf = face.surface(); - let mut sections = 0; - for edge in face.edge_iter() { - if let mt::Curve::BSplineCurve(c) = edge.curve() { - for k in 0..=20 { - let q = c.subs(f64::from(k) / 20.0); - let uv = plane.to_local(from_p3(q)); - assert!((uv.x - left * uv.y).abs() < 1e-8 || (uv.x + right * uv.y - 40.0).abs() < 1e-8); - let (u, v) = surf.search_parameter(q, None, 100).expect("end curve on the G2 surface"); - assert!((surf.subs(u, v) - q).magnitude() < 1e-8); - } - sections += 1; - } - } - assert_eq!(sections, 2); - // A parameter swap on inversion is allowed; identify the rails by - // the original side planes and check the whole second fundamental form. - for along in [0.1, 0.5, 0.9] { - let mut rails = 0; - for (u, v) in [(0.0, along), (1.0, along), (along, 0.0), (along, 1.0)] { - let q = from_p3(surf.subs(u, v)); - let y = plane.to_local(q).y; - let z = (q - plane.origin).dot(plane.normal()); - let expected = if y.abs() < 1e-8 { - plane.y - } else if (z - 20.0).abs() < 1e-8 { - plane.normal() - } else { - continue; - }; - let n = surf.uder(u, v).cross(surf.vder(u, v)).normalize(); - assert!(n.cross(v3(expected)).magnitude() < 1e-8); - for second in [surf.uuder(u, v), surf.uvder(u, v), surf.vvder(u, v)] { - assert!(second.dot(n).abs() < 1e-8); - } - rails += 1; - } - assert_eq!(rails, 2); - } - // Analytic volume: the removed section has area 113 r² / 756 - // and first moment ∫y dA = 13711 r³ / 486486, obtained by integrating - // the quintic's x(t)y'(t) and x(t)y(t)y'(t). Axial length is 40−(left+right)y. - let removed = 40.0 * 113.0 / 756.0 * 25.0 - (left + right) * 13711.0 / 486486.0 * 125.0; + // Analytic volume: the equal-area section removes (1 - pi/4) r², and its first + // moment ∫y dA is 0.0474559669443 r³ (Green's theorem on the section at the + // square corner's equal-area thumbweight). Axial length is 40−(left+right)y. + let removed = 40.0 * (1.0 - std::f64::consts::FRAC_PI_4) * 25.0 - (left + right) * 0.0474559669443 * 125.0; let expected = 16000.0 - 4000.0 * (left + right) - removed; - let volume = out.tessellate(0.0001).unwrap().measure().volume; + let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; assert!((volume - expected).abs() < 0.05, "{volume} vs {expected}"); } } @@ -2788,7 +1306,6 @@ mod tests { #[test] fn g2_fillet_on_concave_edge_meets_caps_sloped_in_both_directions() { - use mt::{ParametricCurve, ParametricSurface, SearchParameter}; let region = Region2 { outer: Loop2::polygon(&[ Vec2::ZERO, @@ -2807,27 +1324,13 @@ mod tests { let out = fillet_g2(&body, &[Vec3::new(10.0, 10.0, 17.0)], 2.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.crossed_face_loops().unwrap(), 0); - let solid = out.deep_copy(); - let face = solid.face_iter().find(|f| matches!(f.surface(), mt::Surface::BSplineSurface(_))).unwrap(); - let surf = face.surface(); - for edge in face.edge_iter() { - if let mt::Curve::BSplineCurve(c) = edge.curve() { - for k in 0..=20 { - let q = c.subs(f64::from(k) / 20.0); - let height = q.z - 0.3 * q.x - 0.4 * q.y; - assert!(height.abs() < 1e-8 || (height - 20.0).abs() < 1e-8); - let (u, v) = surf.search_parameter(q, None, 100).unwrap(); - assert!(from_p3(surf.subs(u, v)).dist(from_p3(q)) < 1e-8); - } - } - } - let volume = out.tessellate(0.0001).unwrap().measure().volume; - let expected = 6000.0 + 113.0 / 756.0 * 4.0 * 20.0; + let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; + let expected = 6000.0 + (1.0 - std::f64::consts::FRAC_PI_4) * 4.0 * 20.0; assert!((volume - expected).abs() < 0.02, "{volume} vs {expected}"); } #[test] - fn g2_fillet_refuses_invalid_and_unsupported_geometry() { + fn g2_fillet_refuses_invalid_geometry() { let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); let edge = [Vec3::new(20.0, 0.0, 10.0)]; for radius in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e7] { @@ -2836,32 +1339,14 @@ mod tests { assert!(fillet_g2(&body, &[], 2.0).is_err()); assert!(fillet_g2(&body, &[Vec3::new(f64::NAN, 0.0, 0.0)], 2.0).is_err()); assert!(fillet_g2(&body, &[Vec3::new(1000.0, 0.0, 0.0)], 2.0).is_err()); - assert!(fillet_g2(&body, &edge, 25.0).is_err()); - let rounded = fillet(&body, &edge, 2.0).unwrap(); - assert!(fillet_g2(&rounded, &[Vec3::new(20.0, 2.0, 10.0)], 1.0).is_err()); - let boss = box_and_boss(); - assert!(fillet_g2(&boss, &[Vec3::new(40.0, 4.0, 0.0)], 0.5).is_err()); - // The ordinary blend supports the boss's pieced end wall; G2 must still refuse it. - assert!(matches!( - fillet_g2(&boss, &[Vec3::new(40.0, 4.0, 20.0)], 0.8), - Err(KernelError::Failed(message)) if message.contains("G2 fillets require one planar end face") - )); - } - - #[test] - fn chamfer_extension_cannot_cross_a_hole_and_reenter_the_face() { - let rectangle = |a, b, c, d| Loop2::polygon(&[Vec2::new(a, b), Vec2::new(c, b), Vec2::new(c, d), Vec2::new(a, d)]); - let region = - Region2 { outer: rectangle(0.0, 0.0, 10.0, 10.0), holes: vec![rectangle(4.0, 4.0, 6.0, 6.0), Loop2::circle(Vec2::new(4.0, 1.5), 0.25)] }; - for plane in [Plane::XY, Plane::XZ] { - let face = crate::build::face(&plane, ®ion).unwrap(); - let p = plane.to_world(Vec2::new(4.0, 4.0)); - let fits = |y| extension_fits(&face, p, plane.to_world(Vec2::new(4.0, y)), 1e-6); - assert!(fits(2.0)); - assert!(!fits(1.5)); // endpoint in the circular hole - assert!(!fits(0.5)); // endpoint in material, but the extension crossed the hole - assert!(!fits(-1e8)); // an arbitrarily long slide cannot escape the face - } + // Wider than the faces (20), over their far edges, cliffs: cut as if they went on. The + // section is the equal-area one from 25 out on each face; it takes the region between it + // and the corner inside the 20 x 20 section (the area under the curve clipped to the + // square, 2e4 strips on a 4e5-piece polygon of the curve), along 20. + let wide = fillet_g2(&body, &edge, 25.0).unwrap(); + let v = crate::measure(&wide).unwrap().volume; + assert!((v - 5329.0618943703).abs() < 1e-5 * 5329.0618943703, "{v}"); + assert!(wide.validity().is_empty()); } /// A box with a cylinder joined across one side (#556): the bottom edge of that side runs @@ -2875,12 +1360,11 @@ mod tests { #[test] fn a_blend_runs_into_a_cylinder_at_its_end() { let body = box_and_boss(); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; let v0 = vol(&body); // The edge (40, 0..8, 0) ends in the cylinder wall at y = 8. let len = 20.0 - (144.0f64 - 0.0).sqrt(); - for (shape, size, area) in [(Shape::Round, 0.5, (1.0 - std::f64::consts::PI / 4.0) * 0.25), (Shape::Flat, 0.5, 0.125)] { - let out = blend(&body, &[Vec3::new(40.0, 4.0, 0.0)], size, shape, "blend").unwrap(); + for (round, size, area) in [(true, 0.5, (1.0 - std::f64::consts::PI / 4.0) * 0.25), (false, 0.5, 0.125)] { + let out = blend(&body, &[Vec3::new(40.0, 4.0, 0.0)], size, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); let removed = v0 - vol(&out); // The section runs on a little past y = 8 under the cylinder wall. @@ -2896,10 +1380,9 @@ mod tests { let plate = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 20.0, 10.0)).unwrap(); let hole = crate::build::cylinder(Vec3::new(20.0, 0.0, -1.0), Vec3::Z, 5.0, 12.0).unwrap(); let body = crate::ops::boolean(&plate, &hole, crate::BoolOp::Cut).unwrap().unwrap(); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; let v0 = vol(&body); - for (shape, area) in [(Shape::Round, (1.0 - std::f64::consts::PI / 4.0)), (Shape::Flat, 0.5)] { - let out = blend(&body, &[Vec3::new(5.0, 0.0, 10.0)], 1.0, shape, "blend").unwrap(); + for (round, area) in [(true, (1.0 - std::f64::consts::PI / 4.0)), (false, 0.5)] { + let out = blend(&body, &[Vec3::new(5.0, 0.0, 10.0)], 1.0, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); let removed = v0 - vol(&out); assert!(removed > area * 14.0 && removed < area * 15.2, "{removed}"); @@ -2911,7 +1394,6 @@ mod tests { let plate = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 10.0)).unwrap(); let pocket = crate::build::box_solid(Vec3::new(10.0, 10.0, -1.0), Vec3::new(30.0, 30.0, 12.0)).unwrap(); let body = crate::ops::boolean(&plate, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; let v0 = vol(&body); let one = chamfer(&body, &[Vec3::new(10.0, 10.0, 5.0)], 2.0).unwrap(); assert!(one.validity().is_empty(), "{:?}", one.validity()); @@ -2936,11 +1418,10 @@ mod tests { let b = crate::build::box_solid(Vec3::ZERO, Vec3::new(100.0, 50.0, 20.0)).unwrap(); let outline = [Vec3::new(50.0, 0.0, 20.0), Vec3::new(100.0, 25.0, 20.0), Vec3::new(50.0, 50.0, 20.0), Vec3::new(0.0, 25.0, 20.0)]; let c = chamfer(&b, &outline, k).unwrap(); - let out = blend(&c, &[Vec3::new(k / 2.0, k / 2.0, 20.0 - k / 2.0)], 1.0, Shape::Flat, "chamfer").unwrap(); + let out = chamfer(&c, &[Vec3::new(k / 2.0, k / 2.0, 20.0 - k / 2.0)], 1.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.lumps().unwrap().len(), 1); assert_eq!(out.face_count(), c.face_count() + 1); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; // About the triangle (sides 1 and 1 at 120°) along the mitre; its ends slant. let removed = vol(&c) - vol(&out); let along = 0.5 * 120f64.to_radians().sin() * k * 3f64.sqrt(); @@ -2954,15 +1435,12 @@ mod tests { let b = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 20.0, 20.0)).unwrap(); let c = crate::build::cylinder(Vec3::new(20.0, -1.0, 16.0), Vec3::Y, 8.0, 22.0).unwrap(); let body = crate::ops::boolean(&b, &c, crate::BoolOp::Cut).unwrap().unwrap(); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; let v0 = vol(&body); - for shape in [Shape::Round, Shape::Flat] { - let out = blend(&body, &[Vec3::new(20.0, 0.0, 8.0)], 0.5, shape, "blend").unwrap(); + for round in [true, false] { + let out = blend(&body, &[Vec3::new(20.0, 0.0, 8.0)], 0.5, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); - // One blend face per piece of the arc (the groove's surface is in two faces). - assert_eq!(out.face_count(), body.face_count() + 2); // About the section along the arc (240°, at the section's distance from the axis). - let area = if shape == Shape::Round { (1.0 - std::f64::consts::PI / 4.0) * 0.25 } else { 0.125 }; + let area = if round { (1.0 - std::f64::consts::PI / 4.0) * 0.25 } else { 0.125 }; let along = 8.2 * 240f64.to_radians(); let removed = v0 - vol(&out); assert!(removed > area * along * 0.9 && removed < area * along * 1.1, "{removed} vs {}", area * along); @@ -2972,55 +1450,31 @@ mod tests { #[test] fn a_blend_of_an_edge_running_into_a_rounded_corner_follows_it() { // A box with one vertical edge rounded: a top edge meeting that round smoothly is blended - // with the round's top arc and the next top edge, as one smooth chain. + // with the round's top arc and the next top edge, as one smooth chain (its tangent chain, + // as the Fillet and Chamfer features ask for it). let b = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); - let rounded = blend(&b, &[Vec3::new(40.0, 30.0, 10.0)], 5.0, Shape::Round, "fillet").unwrap(); - for shape in [Shape::Round, Shape::Flat] { - let out = blend(&rounded, &[Vec3::new(20.0, 30.0, 20.0)], 1.0, shape, "blend").unwrap(); + let rounded = fillet(&b, &[Vec3::new(40.0, 30.0, 10.0)], 5.0).unwrap(); + let chain = tangent_chain(&rounded, &[Vec3::new(20.0, 30.0, 20.0)]).unwrap(); + assert_eq!(chain.len(), 3, "the top edge, the round's top arc and the next top edge"); + for round in [true, false] { + let out = blend(&rounded, &chain, 1.0, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.face_count(), rounded.face_count() + 3); } } - #[test] - fn a_blend_ends_where_a_joined_boss_turns_back_round_its_end() { - // The box's top right edge runs into the cylinder at (40, 8, 20), where the cylinder's - // wall is in pieces (inside the box it is gone): the blend's end lies on the cylinder - // where the box was, now laid bare. - let body = box_and_boss(); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; - let v0 = vol(&body); - for (shape, area) in [(Shape::Round, (1.0 - std::f64::consts::PI / 4.0) * 0.64), (Shape::Flat, 0.32)] { - let out = blend(&body, &[Vec3::new(40.0, 4.0, 20.0)], 0.8, shape, "blend").unwrap(); - assert!(out.validity().is_empty(), "{:?}", out.validity()); - assert_eq!(out.lumps().unwrap().len(), 1); - // Along y = 0 … 8 (and on a hair's breadth, to the cylinder's wall: y − 8 < 0.03). - let removed = v0 - vol(&out); - assert!((removed - area * 8.0).abs() < area * 8.0 * 1e-3, "{removed} vs {}", area * 8.0); - } - } - #[test] fn a_blend_along_a_boss_ends_on_the_box_side_beside_it() { // The boss's bottom edge outside the box (a half circle) ends at the box's side, square to - // it: the side face takes the end section, its bottom edge running on to the blend. + // it: the side face takes the end section. let body = box_and_boss(); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; let v0 = vol(&body); - for (shape, area, c) in [ - ( - Shape::Round, - (1.0 - std::f64::consts::PI / 4.0) * 0.64, - 0.8 * (10.0 - 3.0 * std::f64::consts::PI) / (3.0 * (4.0 - std::f64::consts::PI)), - ), - (Shape::Flat, 0.32, 0.8 / 3.0), + for (round, area, c) in [ + (true, (1.0 - std::f64::consts::PI / 4.0) * 0.64, 0.8 * (10.0 - 3.0 * std::f64::consts::PI) / (3.0 * (4.0 - std::f64::consts::PI))), + (false, 0.32, 0.8 / 3.0), ] { - let picks = [Vec3::new(52.0, 20.0, 0.0)]; - let out = match shape { - Shape::Round => fillet(&body, &picks, 0.8), - _ => chamfer(&body, &picks, 0.8), - } - .unwrap(); + // The half circle's tangent chain, as the Fillet and Chamfer features ask for it. + let out = blend(&body, &tangent_chain(&body, &[Vec3::new(52.0, 20.0, 0.0)]).unwrap(), 0.8, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); // Pappus: the section turned half round the axis at its centroid's radius. let want = area * std::f64::consts::PI * (12.0 - c); @@ -3035,8 +1489,7 @@ mod tests { #[test] fn a_blend_ends_on_a_face_running_along_its_seam_twice() { // #691: a pocket's floor edge along its straight wall ends on a boss's cylinder, which a - // STEP file gives as one face running along its seam edge twice. The rebuilt face keeps - // doing so. + // STEP file gives as one face running along its seam edge twice. let b = crate::build::box_solid(Vec3::new(-55.0, -20.0, -30.0), Vec3::new(55.0, 50.0, 0.0)).unwrap(); let boss = crate::build::cylinder(Vec3::new(55.0, 15.0, -50.0), Vec3::Z, 25.0, 50.0).unwrap(); let b = crate::ops::boolean(&b, &boss, crate::BoolOp::Union).unwrap().unwrap(); @@ -3045,19 +1498,17 @@ mod tests { let pocket = crate::ops::boolean(&pocket, &wall, crate::BoolOp::Cut).unwrap().unwrap(); let made = crate::ops::boolean(&b, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); let body = crate::step_import(&crate::step_export(&[&made], "test").unwrap()).unwrap().bodies.remove(0).body; - let seam_twice = body.solid.face_iter().any(|f| { - f.absolute_boundaries().iter().any(|w| { - let ids: Vec = w.edge_iter().map(|e| e.id()).collect(); - ids.iter().enumerate().any(|(k, x)| ids.iter().skip(k + 1).any(|y| y == x)) - }) + let rec = crate::native::brep_record(&body).unwrap(); + let seam_twice = rec.faces.iter().flat_map(|f| f.loops.iter()).any(|l| match l { + Loop::Edges { edges } => edges.iter().enumerate().any(|(k, x)| edges.iter().skip(k + 1).any(|y| y.edge == x.edge)), + Loop::Vertex { .. } => false, }); assert!(seam_twice); - let vol = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; let v0 = vol(&body); // The edge runs from x = −45 to where the wall meets the cylinder, x = 55 − √(25² − 5²). let len = 45.0 + 55.0 - (600f64).sqrt(); - for (shape, area) in [(Shape::Round, 1.0 - std::f64::consts::PI / 4.0), (Shape::Flat, 0.5)] { - let out = blend(&body, &[Vec3::new(0.0, 10.0, -15.0)], 1.0, shape, "blend").unwrap(); + for (round, area) in [(true, 1.0 - std::f64::consts::PI / 4.0), (false, 0.5)] { + let out = blend(&body, &[Vec3::new(0.0, 10.0, -15.0)], 1.0, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); // A concave edge: the blend adds material. let added = vol(&out) - v0; @@ -3066,7 +1517,7 @@ mod tests { } #[test] - fn local_chamfer_intersects_sloped_end_planes() { + fn a_chamfer_meets_sloped_end_planes() { for slope in [-0.5, 0.5] { let region = Region2 { outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(40.0, 0.0), Vec2::new(40.0 - slope * 20.0, 20.0), Vec2::new(slope * 20.0, 20.0)]), @@ -3074,29 +1525,131 @@ mod tests { }; let body = crate::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap(); let pick = [Vec3::new(20.0, 0.0, 20.0)]; - let result = blend(&body, &pick, 2.0, Shape::Flat, "chamfer").unwrap(); + let result = chamfer(&body, &pick, 2.0).unwrap(); let removed = 2.0 * (40.0 - 2.0 * slope * 2.0 / 3.0); let actual = crate::measure(&body).unwrap().volume - crate::measure(&result).unwrap().volume; assert!((actual - removed).abs() < 1e-6, "{actual} vs {removed}"); assert!(result.validity().is_empty()); // The new corner vertices lie on both original end planes. for point in [Vec3::new(slope * 2.0, 2.0, 20.0), Vec3::new(40.0 - slope * 2.0, 2.0, 20.0)] { - assert!(result.solid.vertex_iter().any(|v| vtx(&v).dist(point) < 1e-8)); + assert!(has_vertex(&result, point, 1e-8)); } - assert!(blend(&body, &pick, 25.0, Shape::Flat, "chamfer").is_err()); + // Past the faces (20 deep, 20 high), over their far edges, cliffs: cut as if the + // faces and the sloped end planes went on. The plane 25 back on each face takes, of + // the section, z >= y - 5 (y, z in [0, 20]), each line of it 40 - 2 slope y long + // between the end planes: 11500 - 4625 slope. + let past = chamfer(&body, &pick, 25.0).unwrap(); + let removed = 11500.0 - 4625.0 * slope; + let actual = crate::measure(&body).unwrap().volume - crate::measure(&past).unwrap().volume; + assert!((actual - removed).abs() < 1e-6 * removed, "{actual} vs {removed}"); + assert!(past.validity().is_empty()); // A fillet ends in each sloped end plane along an ellipse: the removed section's // length is taken at its centroid, c from the edge. - let rounded = blend(&body, &pick, 2.0, Shape::Round, "fillet").unwrap(); + let rounded = fillet(&body, &pick, 2.0).unwrap(); let (area, c) = ((1.0 - std::f64::consts::PI / 4.0) * 4.0, 2.0 * (10.0 - 3.0 * std::f64::consts::PI) / (3.0 * (4.0 - std::f64::consts::PI))); let removed = area * (40.0 - 2.0 * slope * c); let actual = crate::measure(&body).unwrap().volume - crate::measure(&rounded).unwrap().volume; - // `measure` reads a round about 6e-4 heavy, square ends too. assert!((actual - removed).abs() < 1e-3 * removed, "{actual} vs {removed}"); assert!(rounded.validity().is_empty()); } } + /// A block 40 wide and 20 deep (z 0…20) whose top rises from y = 20 at its sides to a + /// crease along z at x = 20, each half sloping `slope` degrees, so the faces turn by twice + /// that across the crease; and a point on the crease. + fn roof(slope: f64) -> (Body, Vec3) { + let h = 20.0 * slope.to_radians().tan(); + let outline = [Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), Vec2::new(40.0, 20.0), Vec2::new(20.0, 20.0 + h), Vec2::new(0.0, 20.0)]; + let region = Region2 { outer: Loop2::polygon(&outline), holes: vec![] }; + let body = crate::build::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().remove(0); + (body, Vec3::new(20.0, 20.0 + h, 10.0)) + } + + /// A round lies r·(sec(δ/2) − 1) inside the crease it replaces (δ the faces' turn): below the + /// edge's tolerance it changes nothing and is refused as too small, naming the smallest + /// radius that rounds. The block's edges are held to 2e-5 mm (SMLib's intersection tolerance + /// for a part this size, twice its zone tolerance of 1e-5). At 1° an R0.4 round would lie + /// 0.4 · (sec 0.5° − 1) = 0.015 µm in, under it: the smallest is 2e-5 / (sec 0.5° − 1) = + /// 0.52523 mm, named rounded up. At 3° the R2 round is 0.685 µm in and builds: one face more, + /// the top that much lower, removing 20 · r²(tan(δ/2) − δ/2) = 4.786e-4 mm³. + #[test] + fn a_round_too_small_to_change_the_part_is_refused_naming_the_smallest_that_rounds() { + let (gentle, crease) = roof(0.5); + let rec = Faces::of(&gentle).unwrap().rec; + assert!(rec.tolerance == 2e-5 && rec.edges.iter().all(|e| e.tolerance == 2e-5), "{}", rec.tolerance); + let turn = 1f64.to_radians(); + let smallest = 2e-5 / (1.0 / (0.5 * turn).cos() - 1.0); + assert!((smallest - 0.52523).abs() < 1e-5, "{smallest}"); + let e = fillet(&gentle, &[crease], 0.4).unwrap_err().to_string(); + assert!( + e.contains("is too small") && e.contains("turn only 1.00°") && e.contains("the smallest radius that rounds this edge is 0.526 mm"), + "{e}" + ); + + let (steeper, crease) = roof(1.5); + let (r, turn) = (2.0, 3f64.to_radians()); + let rounded = fillet(&steeper, &[crease], r).unwrap(); + assert!(rounded.validity().is_empty(), "{:?}", rounded.validity()); + assert_eq!(rounded.face_count(), steeper.face_count() + 1); + let (before, after) = (crate::measure(&steeper).unwrap(), crate::measure(&rounded).unwrap()); + let sag = r * (1.0 / (0.5 * turn).cos() - 1.0); + assert!(((before.bbox.max.y - after.bbox.max.y) - sag).abs() < 1e-9, "{} vs {sag}", before.bbox.max.y - after.bbox.max.y); + let removed = 20.0 * r * r * ((0.5 * turn).tan() - 0.5 * turn); + assert!(((before.volume - after.volume) - removed).abs() < 1e-6, "{} vs {removed}", before.volume - after.volume); + } + + /// At 1° the crease rounds from 0.526 mm: R2 lies 0.076 µm in and R20 0.76 µm, and each + /// builds, removing 20 · r²(tan(δ/2) − δ/2). + /// A box 104 x 64 x 42 hollowed 2 mm from the inside, open at the bottom: 1668's thin wall. + fn thin_walled_case() -> Body { + let outer = crate::build::box_solid(Vec3::new(-52.0, -32.0, 0.0), Vec3::new(52.0, 32.0, 42.0)).unwrap(); + let hollow = crate::build::box_solid(Vec3::new(-50.0, -30.0, -1.0), Vec3::new(50.0, 30.0, 40.0)).unwrap(); + crate::ops::boolean(&outer, &hollow, crate::BoolOp::Cut).unwrap().unwrap() + } + + #[test] + fn a_round_cutting_through_a_thin_wall_into_the_hollow_is_refused_naming_the_largest_that_fits() { + let case = thin_walled_case(); + let top = Vec3::new(0.0, 32.0, 42.0); + // The round's centre is at (32 - r, 42 - r); the hollow's corner (30, 40) leaves its circle + // where sqrt2 (r - 2) = r: r = 4 + 2 sqrt2 = 6.8284. + let e = fillet(&case, &[top], 7.0).unwrap_err(); + assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); + let e = e.to_string(); + assert!(e.contains("into the hollow at (0.000, 30.000, 40.000) and open the part"), "{e}"); + let (largest, _) = fillet_max(&case, &[top], 7.0, FilletTurn::Mitre).unwrap().unwrap(); + assert!((largest - 6.828).abs() < 1e-9, "{largest}"); + + // Just short of the corner it rounds, its whole section along the 104. + let r = 6.8; + let rounded = fillet(&case, &[top], r).unwrap(); + let want = 104.0 * 64.0 * 42.0 - 100.0 * 60.0 * 40.0 - (1.0 - std::f64::consts::FRAC_PI_4) * r * r * 104.0; + let got = crate::measure(&rounded).unwrap().volume; + assert!((got - want).abs() < 1e-6 * want, "{got} vs {want}"); + + // The inside edge rounded with it fills the hollow's corner: the outer round reaches the + // inner R7's arc (centre (23, 33)) only at sqrt2 (r - 9) + 7 = r, r = 13.83. + let inside = Vec3::new(0.0, 30.0, 40.0); + assert!(fillet(&case, &[top, inside], 7.0).is_ok()); + assert!(fillet_each(&case, &[top, inside], &[13.8, 7.0], FilletTurn::Mitre).is_ok()); + let e = fillet_each(&case, &[top, inside], &[13.9, 7.0], FilletTurn::Mitre).unwrap_err().to_string(); + assert!(e.contains("into the hollow at"), "{e}"); + } + + #[test] + fn a_one_degree_crease_rounds_from_the_smallest_radius_named() { + let (gentle, crease) = roof(0.5); + let turn = 1f64.to_radians(); + for r in [2.0, 20.0] { + let rounded = fillet(&gentle, &[crease], r).unwrap(); + assert!(rounded.validity().is_empty(), "r={r}: {:?}", rounded.validity()); + let removed = 20.0 * r * r * ((0.5 * turn).tan() - 0.5 * turn); + let (before, after) = (crate::measure(&gentle).unwrap().volume, crate::measure(&rounded).unwrap().volume); + assert!(((before - after) - removed).abs() < 1e-6, "r={r}: {} vs {removed}", before - after); + } + } + /// A pin standing in a socket, 3.5 mm from two of its walls, in a large block. The cutters /// for its tip reach several times the chamfer's size past each edge (more on a larger part), /// into the walls, and their union took bites out of them: 7.2 mm³ instead of the tip's. @@ -3119,3 +1672,7 @@ mod tests { assert!(out.validity().is_empty(), "{:?}", out.validity()); } } + +#[cfg(test)] +#[path = "curvecorner_tests.rs"] +mod corner_tests; diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs index 3def4625b..d7b72a052 100644 --- a/crates/kernel/src/blend_corner.rs +++ b/crates/kernel/src/blend_corner.rs @@ -1,28 +1,255 @@ -//! Fillets with a radius per edge, and the corners where filleted edges meet. +//! Fillets with a radius per edge. SMLib rounds every picked edge at its own radius in one +//! blend, with the corners where the rounds meet: an end in the face beyond, two rounds trimming +//! each other, or a corner patch where three meet. //! -//! The edges are straight and convex, and every face at their end vertices is planar with three -//! edges meeting at each such vertex, including reflex corners of pocket rims. The faces there are rebuilt around the -//! blends, faces away from them are kept. At a vertex: -//! - one filleted edge ends on the third face: the blend ends in that face's section of the -//! cylinder (an exact arc or ellipse); -//! - two filleted edges, the third sharp: the cylinders trim each other (rolling ball); the -//! crease runs from where their contact lines cross to the third edge (equal radii) or to the -//! smaller blend's contact line on the face that ends the larger one; -//! - three filleted edges: each cylinder stops at a plane section through the points where its -//! contact lines meet the others', and a corner patch spans the three sections (a sphere for -//! equal radii, else a rational patch through the exact sections). -//! -//! A fillet that ends on an earlier round (of any radius) takes the round off -//! ([`crate::delete_faces`]) and blends both edges together. +//! A later round at a corner where earlier rounds already meet in a mitre (the owner's ruling of +//! 2026-10-30) makes the corner all of them would have made rounded at once: one smooth patch, +//! the mitre gone. A body made by constant-radius rounds keeps what they were made on and which +//! edges they rounded at which radius ([`Rounds`]); a later round reaching such a corner +//! ([`later_corners`]) blends the earlier rounds' edges, from the earliest of the rounds that +//! meet there on, with the new edges in one SMLib blend of the body before them, and the result's +//! history is put over the body the later round was given ([`rebase`]): an earlier round's face +//! is that face, trimmed anew; the corner patch, and every face the new edges make, is the later +//! round's. The mitre's seam is no edge to round on its own: picked (a tangent chain reaches it +//! from the new edge), it only says the corner is blended again. -use std::collections::{HashMap, HashSet}; +use std::collections::BTreeSet; -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, builder}; +use solidcore_record::Vec3; -use crate::blend::{plane_normal, too_large, unsupported, vtx}; -use crate::body::{Body, Solid, p3, v3}; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History}; +use crate::{KernelError, Result}; + +/// The constant-radius rounds that made a body ([`crate::fillet`], [`fillet_radii`]): the body +/// they were made on, and each edge they rounded (its index in that body's edge order) with its +/// radius. The body's history is over `before`. +#[derive(Clone, Debug)] +pub(crate) struct Rounds { + pub(crate) before: Body, + pub(crate) edges: Vec<(usize, f64)>, +} + +/// A later round at corners where earlier rounds meet ([`later_corners`]): what is blended in +/// one go, and what puts its history over the body the later round was given. +pub(crate) struct Later { + /// The body before the earliest of the rounds that meet at the new edges' corners. + pub(crate) base: Body, + /// The edges blended on `base` (its edge order) with their radii: the edges of every round + /// from that earliest on, and the new edges. + pub(crate) edges: Vec<(usize, f64)>, + /// The body over `base`: the histories of those rounds composed. + chain: History, + /// The new edges: each one's index in the body, and in `base`. + new: Vec<(usize, usize)>, + /// The body's mitre seams at the new edges' corners, which the corner patches replace. + seams: Vec, +} + +impl Later { + /// How many of `edges`, the last ones, are the new edges. + pub(crate) fn new_count(&self) -> usize { + self.new.len() + } +} + +/// The history of `body` over the body `levels` rounds back ([`Rounds::before`] taken that many +/// times), composed; `None` when a step has no record or history, or for no levels. +fn down(body: &Body, levels: usize) -> Option { + let mut at = body.clone(); + let mut composed: Option = None; + for _ in 0..levels { + let rounds = at.rounds.clone()?; + let step = at.history().filter(|h| h.operands == 1)?.clone(); + composed = Some(match composed { + None => step, + Some(h) => h.substituted(0, &step).ok()?, + }); + at = rounds.before.clone(); + } + composed +} + +/// The operand edge `edge` of a result comes from, through `h`, when it is (a piece of) one. +fn edge_origin(h: &History, edge: usize) -> Option { + match h.edges.get(edge).map(|e| e.origins.as_slice()) { + Some([EdgeOrigin::Edge { operand: 0, edge }]) => Some(*edge), + _ => None, + } +} + +/// Faces a blend made in place of edges (rounds, their corner patches), through `h`. +fn rounds_of(h: &History) -> Vec { + h.faces + .iter() + .map(|f| f.change == Change::Generated && !f.origins.is_empty() && f.origins.iter().all(|o| matches!(o, FaceOrigin::Edge { .. }))) + .collect() +} + +/// Is `edge` (its faces through `h`) where the rounds of different edges meet: between two of +/// `rounds` made in place of edges none of which both are (a mitre, or rounds running on into +/// each other), not between a round and its own end cap or a corner patch it is part of? +fn between_rounds(h: &History, rounds: &[bool], edge: usize) -> bool { + let round = |f: usize| rounds.get(f).copied().unwrap_or(false).then(|| h.faces.get(f)).flatten(); + match h.edges.get(edge).map(|e| e.faces.as_slice()) { + Some([f, g]) if f != g => match (round(*f), round(*g)) { + (Some(a), Some(b)) => a.origins.iter().all(|o| !b.origins.contains(o)), + _ => false, + }, + _ => false, + } +} + +/// The later rounds of `picked` (the body's edges, `sizes` their radii, as the blend resolved +/// them) when one of them reaches a corner where rounds that made the body meet: the blend to +/// make in their place, and the new edges (in the body's edge order, with their radii) the +/// body's record of rounds takes. `Ok(None)` when none does, or when the rounds are not on record +/// down to that corner. A picked seam between earlier rounds is refused unless a new edge of +/// the same radius meets it: it has no round of its own. +pub(crate) fn later_corners(body: &Body, picked: &[usize], sizes: &[f64]) -> Result)>> { + // The rounds on record, latest first: each one's body before it and the body over that. + let mut levels: Vec<(Rounds, History)> = Vec::new(); + while let Some(h) = down(body, levels.len() + 1) { + let Some(r) = (match levels.last() { + None => body.rounds.as_deref().cloned(), + Some((r, _)) => r.before.rounds.as_deref().cloned(), + }) else { + break; + }; + levels.push((r, h)); + } + let Some((_, deepest)) = levels.last() else { return Ok(None) }; + let rounds = rounds_of(deepest); + let record = body.record(); + let ends = |e: usize| record.edges.get(e).map(|e| e.vertices).unwrap_or([u32::MAX; 2]); + let (seam_picks, new): (Vec<(usize, f64)>, Vec<(usize, f64)>) = + picked.iter().copied().zip(sizes.iter().copied()).partition(|(e, _)| between_rounds(deepest, &rounds, *e)); + let corners: BTreeSet = new.iter().flat_map(|(e, _)| ends(*e)).collect(); + let seams: Vec = + (0..record.edges.len()).filter(|e| between_rounds(deepest, &rounds, *e) && ends(*e).iter().any(|v| corners.contains(v))).collect(); + for (seam, size) in &seam_picks { + let meets = new.iter().any(|(e, r)| r.to_bits() == size.to_bits() && ends(*e).iter().any(|v| ends(*seam).contains(v))); + if !meets { + return Err(KernelError::Invalid( + "fillet: a picked edge is where earlier rounds meet (a mitre), which has no round of its own: pick the edge that runs \ + into that corner, at its radius, and the corner is rounded again with it" + .into(), + )); + } + } + if seams.is_empty() { + return Ok(None); + } + // The latest round from which on every seam is between rounds on record. + let Some(level) = levels.iter().position(|(_, h)| { + let rounds = rounds_of(h); + seams.iter().all(|s| between_rounds(h, &rounds, *s)) + }) else { + return Ok(None); + }; + let Some((base, chain)) = levels.get(level).map(|(r, h)| (r.before.clone(), h.clone())) else { return Ok(None) }; + // Every round's edges from that level on, in `base`'s edge order. + let mut edges: Vec<(usize, f64)> = Vec::new(); + for (step, (r, _)) in levels.iter().enumerate().take(level + 1) { + let inner = down(&r.before, level - step); + for (e, radius) in &r.edges { + let at = match &inner { + None => Some(*e), + Some(h) => edge_origin(h, *e), + }; + let Some(at) = at else { return Ok(None) }; + edges.push((at, *radius)); + } + } + let mut mapped = Vec::with_capacity(new.len()); + for (e, radius) in &new { + let Some(at) = edge_origin(&chain, *e) else { return Ok(None) }; + mapped.push((*e, at)); + edges.push((at, *radius)); + } + Ok(Some((Later { base, edges, chain, new: mapped, seams }, new))) +} + +/// The history of `result`, the blend `later` made of its base (`h`, over the base), over the +/// body the later round was given (`body`, `later.chain` over the base): a face of the base's +/// faces is the body's face of them, kept where both kept it, else trimmed anew (split or joined +/// where they are several); an earlier round's face is that round's face in the body; a face +/// made in place of a new edge (its round, and a corner patch where it meets earlier rounds) is +/// new, made in place of the new edges and of the body's seams between the rounds it joins. +/// Each edge is the body's edge between the faces it lies between there, else where its faces +/// meet. `None` where a face has no counterpart. +pub(crate) fn rebase(h: &History, later: &Later, body: &Body) -> Option { + let chain = &later.chain; + let set = |p: &FaceProv| p.origins.iter().copied().collect::>(); + let mut faces = Vec::with_capacity(h.faces.len()); + for p in &h.faces { + let origins = set(p); + let new_edges: Vec = later + .new + .iter() + .filter(|(_, at)| origins.contains(&FaceOrigin::Edge { operand: 0, edge: *at })) + .map(|(e, _)| FaceOrigin::Edge { operand: 0, edge: *e }) + .collect(); + if !new_edges.is_empty() { + // The seams between rounds all of whose origins this face takes up. + let replaced = later.seams.iter().filter(|s| { + chain.edges.get(**s).is_some_and(|e| e.faces.iter().all(|f| chain.faces.get(*f).is_some_and(|f| set(f).is_subset(&origins)))) + }); + let mut all = new_edges; + all.extend(replaced.map(|s| FaceOrigin::Edge { operand: 0, edge: *s })); + faces.push(crate::record::generated(all)); + continue; + } + let candidates: Vec = if p.change == Change::Generated { + (0..chain.faces.len()).filter(|f| chain.faces.get(*f).is_some_and(|c| c.change == Change::Generated && set(c) == origins)).collect() + } else { + (0..chain.faces.len()) + .filter(|f| chain.faces.get(*f).is_some_and(|c| c.change != Change::Generated && c.origins.iter().any(|o| origins.contains(o)))) + .collect() + }; + let change = match candidates[..] { + [] => return None, + [f] if p.change == Change::Kept && chain.faces.get(f).is_some_and(|c| c.change == Change::Kept) => Change::Kept, + [_] => Change::Modified, + _ => Change::Merged, + }; + faces.push(FaceProv { origins: candidates.into_iter().map(|face| FaceOrigin::Face { operand: 0, face }).collect(), change }); + } + crate::record::mark_shared_split(&mut faces); + // The body's faces under each result face, and the body's edges by the faces they separate. + let under = |f: usize| -> BTreeSet { + faces + .get(f) + .filter(|p| p.change != Change::Generated) + .map(|p| p.origins.iter().filter_map(|o| if let FaceOrigin::Face { face, .. } = o { Some(*face) } else { None }).collect()) + .unwrap_or_default() + }; + let body_edges = crate::history::edge_faces(body.record()); + let edges = h + .edges + .iter() + .map(|e| { + let sides: Vec> = e.faces.iter().map(|f| under(*f)).collect(); + let same: Vec = if sides.iter().all(|s| !s.is_empty()) { + body_edges + .iter() + .enumerate() + .filter(|(_, between)| { + between.len() == sides.len() + && (between.iter().zip(&sides).all(|(f, s)| s.contains(f)) + || between.iter().rev().zip(&sides).all(|(f, s)| s.contains(f))) + }) + .map(|(edge, _)| EdgeOrigin::Edge { operand: 0, edge }) + .collect() + } else { + Vec::new() + }; + let origins = if same.is_empty() { crate::record::meeting(&e.faces, &faces) } else { same }; + EdgeProv { faces: e.faces.clone(), origins } + }) + .collect(); + Some(History { operands: 1, faces, edges }) +} /// Fillet each edge nearest a point with its own radius. pub fn fillet_radii(body: &Body, edges: &[(Vec3, f64)]) -> Result { @@ -33,1222 +260,18 @@ pub fn fillet_radii(body: &Body, edges: &[(Vec3, f64)]) -> Result { if edges.iter().any(|(p, r)| !(p.is_finite() && r.is_finite() && *r > 1e-6 && *r < 1e6)) { return Err(KernelError::Invalid("fillet size must be positive".into())); } - // Each step's result carries its history over `[body]`. - let counts = crate::record::counts(&[body]); - let mut cur = crate::boolean_record::healed(body)?; - let mut sel = edges.to_vec(); - let mut first: Option = None; - // Earlier rounds at the edges' ends come off and are blended again with the new edges. - for _ in 0..4 { - let err = match build(&cur, &sel, true) { - Ok(b) => return Ok(crate::record::after(b, &cur, &counts)), - Err(e) => e, - }; - let rounds = guard("recognise earlier rounds", || rounds_at(&cur, &sel))?; - if rounds.is_empty() { - return Err(first.unwrap_or(err)); - } - first.get_or_insert(err); - let idx: Vec = rounds.iter().map(|r| r.0).collect(); - sel = guard("map picks across earlier rounds", || surviving_picks(&cur, &sel, &idx))?; - cur = crate::record::after(crate::delete_faces(&cur, &idx)?, &cur, &counts); - sel.extend(rounds.iter().map(|r| (r.1, r.2))); - } - Err(first.unwrap_or_else(|| unsupported("these fillets"))) -} - -/// Local equal-distance chamfers, including pocket rims where adjacent walls have -/// different slopes. The planar strips trim each other at each selected corner. -pub(crate) fn chamfer(body: &Body, edges: &[Vec3], distance: f64) -> Result { - let cur = crate::boolean_record::healed(body)?; - let selected: Vec<_> = edges.iter().map(|p| (*p, distance)).collect(); - Ok(crate::record::after(build(&cur, &selected, false)?, &cur, &crate::record::counts(&[body]))) -} - -/// A face of the shell being rebuilt, or a new face. -#[derive(Clone, Copy, PartialEq)] -enum Owner { - Face(usize), - Cyl(mt::EdgeID), - Patch, -} - -/// A filleted edge. -struct Sel { - r: f64, - /// Setback: distance along each face from the edge to the contact line. - s: f64, - /// Middle weight of the cross-section arc, sin(α/2) for the faces' interior angle α. - w: f64, - fa: usize, - fb: usize, - na: Vec3, - nb: Vec3, - /// In-face directions away from the edge. - ta: Vec3, - tb: Vec3, - p0: Vec3, - d: Vec3, - surf: mt::Surface, -} - -impl Sel { - fn t(&self, f: usize) -> Vec3 { - if f == self.fa { self.ta } else { self.tb } - } - fn axis_point(&self) -> Vec3 { - self.p0 + self.ta * self.s - self.na * self.r - } -} - -/// The edges at a vertex: id, the edge, unit direction away from the vertex. -struct Around { - edges: Vec<(mt::EdgeID, Vec3)>, -} - -fn h(p: Vec3, w: f64) -> mt::Vector4 { - mt::Vector4::new(p.x * w, p.y * w, p.z * w, w) -} - -/// Rational quadratic from `a` to `b` with middle control point `m` of weight `w`. -fn conic(a: Vec3, m: Vec3, b: Vec3, w: f64) -> mt::NurbsCurve { - mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![h(a, 1.0), h(m, w), h(b, 1.0)])) -} - -fn edge(a: &mt::Vertex, b: &mt::Vertex, c: mt::Curve) -> Result { - mt::Edge::try_new(a, b, c).map_err(|e| KernelError::Failed(format!("corner edge: {e}"))) -} - -/// Point where the contact line at setback `s` (in-face direction `t`) crosses the line from `v` -/// along `u`. -fn hit(v: Vec3, u: Vec3, t: Vec3, s: f64) -> Result { - let k = u.dot(t); - if k.abs() < 1e-6 { - return Err(unsupported("a fillet that runs along its neighbouring edge")); - } - Ok(v + u * (s / k)) -} - -/// Unit direction in which a (curved) edge leaves its end vertex `v`. -fn leaving(e: &mt::Edge, v: &mt::Vertex) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let at_front = e.absolute_front() == v; - let d = c.der(if at_front { t0 } else { t1 }); - let d = Vec3::new(d.x, d.y, d.z); - (if at_front { d } else { d * -1.0 }).normalized() -} - -/// Point where the contact line at setback `s` (in-face direction `t`) crosses a curved edge -/// leaving `v`: the first along it from `v`. -fn crossing(e: &mt::Edge, v: Vec3, t: Vec3, s: f64) -> Result { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let from_front = crate::body::from_p3(e.absolute_front().point()).dist(v) <= crate::body::from_p3(e.absolute_back().point()).dist(v); - let at = |f: f64| crate::body::from_p3(c.subs(if from_front { t0 + (t1 - t0) * f } else { t1 - (t1 - t0) * f })); - let g = |f: f64| (at(f) - v).dot(t) - s; - let steps = 256; - let mut lo = 0.0; - for i in 1..=steps { - let hi = i as f64 / steps as f64; - if g(hi) >= 0.0 { - let (mut a, mut b) = (lo, hi); - for _ in 0..60 { - let m = (a + b) * 0.5; - if g(m) >= 0.0 { - b = m; - } else { - a = m; - } - } - return Ok(at((a + b) * 0.5)); - } - lo = hi; - } - Err(too_large("a fillet larger than the faces next to it")) -} - -/// The cylinder's (a chamfer's plane's) section by a curved end face `g`, from `a` (on the -/// contact line with in-face direction `ta`) to `b` (`tb`) round the edge's end `v` (its other -/// end `far`): points of the blend's cross-sections on the face, interpolated; within tolerance -/// of both. -#[allow(clippy::too_many_arguments)] -fn curved_section( - sel: &Sel, - g: &mt::Face, - (a, ta): (Vec3, Vec3), - (b, tb): (Vec3, Vec3), - v: Vec3, - far: Vec3, - round: bool, - size: f64, -) -> Result { - use mt::ParametricCurve; - let tolerance = (size * 1e-5).clamp(1e-5, 0.001); - let fail = || too_large("a fillet larger than the faces next to it"); - // Position along the edge, and the cross-section there (fraction 0 on `ta`'s side). - let along = |x: Vec3| (x - sel.p0).dot(sel.d); - let point = |f: f64, l: f64| -> Vec3 { - let apex = sel.p0 + sel.d * l; - let (pa, pb) = (apex + ta * sel.s, apex + tb * sel.s); - if round { crate::body::from_p3(conic(pa, apex, pb, sel.w).subs(f)) } else { pa + (pb - pa) * f } - }; - // The face's surface, each search started from the last one's answer (the points come in - // small steps). - let surface = g.oriented_surface(); - let last = std::cell::Cell::new(None::<(f64, f64)>); - let side = |x: Vec3| -> f64 { - use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let found = last - .get() - .and_then(|hint| surface.search_nearest_parameter(p3(x), Some(hint), 20)) - .or_else(|| surface.search_nearest_parameter(p3(x), None, 100)); - found.map_or(f64::NAN, |(u, w)| { - last.set(Some((u, w))); - let n = surface.normal(u, w); - (x - crate::body::from_p3(surface.subs(u, w))).dot(Vec3::new(n.x, n.y, n.z)) - }) - }; - let (la, lb) = (along(a), along(b)); - // Out of the material: toward the edge's end. - let outward = if along(v) >= along(far) { 1.0 } else { -1.0 }; - let step = ((lb - la).abs().max(sel.s * 0.05)) / 16.0; - let root = |f: f64| -> Option { - let guess = la + (lb - la) * f; - let gv = side(point(f, guess)); - if !gv.is_finite() { - return None; - } - let dir = if gv < 0.0 { outward } else { -outward }; - let mut prev = (guess, gv); - for i in 1..=4096 { - let l = guess + dir * step * i as f64; - let cur = (l, side(point(f, l))); - if !cur.1.is_finite() { - return None; - } - if (prev.1 < 0.0) != (cur.1 < 0.0) { - let (mut x, mut y) = (prev, cur); - for _ in 0..60 { - let m = (x.0 + y.0) * 0.5; - let gm = side(point(f, m)); - if (gm < 0.0) == (x.1 < 0.0) { - x = (m, gm); - } else { - y = (m, gm); - } - } - return Some((x.0 + y.0) * 0.5); - } - prev = cur; - } - None - }; - // Closer together toward the ends, where the face may only touch the blend. - let across = |t: f64| (1.0 - (std::f64::consts::PI * t).cos()) * 0.5; - let mut m = 8; - loop { - let mut pts = vec![a]; - for i in 1..m { - let f = across(i as f64 / m as f64); - pts.push(point(f, root(f).ok_or_else(fail)?)); - } - pts.push(b); - let curve = crate::build::interpolate_cubic(&pts).ok_or_else(|| KernelError::Failed("fillet: end curve".into()))?; - let accurate = (0..m).all(|i| { - let t = (i as f64 + 0.5) / m as f64; - let f = across(t); - let x = crate::body::from_p3(curve.subs(t)); - root(f).is_some_and(|l| point(f, l).dist(x) <= tolerance) && side(x).abs() <= tolerance - }); - if accurate { - return Ok(mt::Curve::BSplineCurve(curve)); - } - if m >= 128 { - return Err(KernelError::Failed("fillet: could not fit the blend's end in a curved face".into())); - } - m *= 2; - } -} - -/// Point in a face where the contact lines of two edges from `v` (directions `u1`, `u2`, in-face -/// directions `t1`, `t2`, setbacks `s1`, `s2`) cross. -fn meet(v: Vec3, (u1, t1, s1): (Vec3, Vec3, f64), (u2, t2, s2): (Vec3, Vec3, f64)) -> Result { - let (k1, k2) = (u1.dot(t2), u2.dot(t1)); - if k1.abs() < 1e-6 || k2.abs() < 1e-6 { - return Err(unsupported("fillets of nearly parallel edges at a corner")); - } - Ok(v + u1 * (s2 / k1) + u2 * (s1 / k2)) -} - -/// Intersection of the three planes n·x = n·p. -fn planes3(a: (Vec3, Vec3), b: (Vec3, Vec3), c: (Vec3, Vec3)) -> Result { - let row = |n: Vec3| [n.x, n.y, n.z]; - crate::polyhedron::solve3_pub([row(a.0), row(b.0), row(c.0)], [a.0.dot(a.1), b.0.dot(b.1), c.0.dot(c.1)]) - .map(|x| Vec3::new(x[0], x[1], x[2])) - .ok_or_else(|| unsupported("a corner whose planes do not meet in a point")) -} - -/// Flip a surface so that its normal near `at` points along `outward`. -fn orient(mut surf: mt::Surface, at: Vec3, outward: Vec3) -> mt::Surface { - use mt::{ParametricSurface3D, SearchNearestParameter}; - if let Some((u, v)) = surf.search_nearest_parameter(p3(at), None, 100) { - let n = surf.normal(u, v); - if Vec3::new(n.x, n.y, n.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); - } - } - surf -} - -/// Edges from `from` to `to` through the pool edges of `owner`. -fn connect(from: &mt::Vertex, to: &mt::Vertex, pool: &[(mt::Edge, Vec)], owner: Owner) -> Result> { - let mut out = Vec::new(); - let mut used: HashSet = HashSet::new(); - let mut cur = from.clone(); - for _ in 0..=pool.len() { - if &cur == to { - return Ok(out); - } - let next = pool.iter().filter(|(e, o)| o.contains(&owner) && !used.contains(&e.id())).find_map(|(e, _)| { - if e.front() == &cur { - Some(e.clone()) - } else if e.back() == &cur { - Some(e.inverse()) - } else { - None - } - }); - let Some(e) = next else { break }; - used.insert(e.id()); - cur = e.back().clone(); - out.push(e); - } - Err(KernelError::Failed("fillet corner: a boundary does not close".into())) -} - -fn build(cur: &Body, sel_pts: &[(Vec3, f64)], round: bool) -> Result { - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let solid = cur.deep_copy(); - let all = Body::unique_edges(&solid); - let mut radius: HashMap = HashMap::new(); - let mut order: Vec = Vec::new(); - for (p, r) in sel_pts { - let Some((idx, dist)) = cur.nearest_edge(*p, tol)? else { return Err(KernelError::Invalid("the body has no edges".into())) }; - if dist > size * 0.05 + 1e-3 { - return Err(KernelError::Invalid(format!("no edge near {:?}", [p.x, p.y, p.z]))); - } - let e = all.get(idx).ok_or_else(|| KernelError::Invalid("edge index".into()))?; - if radius.insert(e.id(), *r).is_none() { - order.push(e.id()); - } - } - let shells = solid.boundaries(); - let Some(first) = order.first() else { return Err(KernelError::Invalid("no edges selected".into())) }; - let si = shells.iter().position(|sh| sh.edge_iter().any(|e| e.id() == *first)).ok_or_else(|| KernelError::Failed("edge not found".into()))?; - let shell = shells.get(si).ok_or_else(|| KernelError::Failed("shell".into()))?; - if order.iter().any(|id| !shell.edge_iter().any(|e| e.id() == *id)) { - return Err(unsupported("fillets on separate lumps in one go")); - } - let faces: Vec = shell.face_iter().cloned().collect(); - let edges: HashMap = shell.edge_iter().map(|e| (e.id(), e)).collect(); - // Faces on each edge, and the faces and edges at each vertex. - let mut on_edge: HashMap> = HashMap::new(); - let mut at_vertex: HashMap, Vec)> = HashMap::new(); - for (fi, f) in faces.iter().enumerate() { - for e in f.edge_iter() { - let ids = on_edge.entry(e.id()).or_default(); - if !ids.contains(&fi) { - ids.push(fi); - } - for v in [e.front(), e.back()] { - let a = at_vertex.entry(v.id()).or_default(); - a.0.insert(e.id()); - if !a.1.contains(&fi) { - a.1.push(fi); - } - } - } - } - let planes: Vec> = faces.iter().map(plane_normal).collect(); - let normal = |fi: usize| planes.get(fi).copied().flatten(); - - // The filleted edges. - let mut sels: HashMap = HashMap::new(); - let mut touched: HashMap = HashMap::new(); - for id in &order { - let e = edges.get(id).ok_or_else(|| KernelError::Failed("edge".into()))?; - if !matches!(e.curve(), mt::Curve::Line(_)) { - return Err(unsupported("only straight edges")); - } - let fs = on_edge.get(id).cloned().unwrap_or_default(); - let [fa, fb] = fs[..] else { return Err(unsupported("the edge is not between two faces")) }; - let (Some(na), Some(nb)) = (normal(fa), normal(fb)) else { return Err(unsupported("both faces next to the edge must be planar")) }; - let (v0, v1) = (e.absolute_front().clone(), e.absolute_back().clone()); - let (p0, p1) = (vtx(&v0), vtx(&v1)); - let d = (p1 - p0).normalized().ok_or_else(|| KernelError::Failed("zero-length edge".into()))?; - let ta = (nb - na * nb.dot(na)) * -1.0; - let tb = (na - nb * na.dot(nb)) * -1.0; - let (Some(ta), Some(tb)) = (ta.normalized(), tb.normalized()) else { return Err(unsupported("the faces at the edge are tangent")) }; - // Convex: each face lies away from the other's outward side (its loop's left side). - let inward = |fi: usize, n: Vec3| -> Option { - let fe = faces.get(fi)?.boundaries().into_iter().flat_map(|w| w.edge_iter().cloned().collect::>()).find(|x| x.id() == *id)?; - n.cross(vtx(fe.back()) - vtx(fe.front())).normalized() - }; - let (Some(ia), Some(ib)) = (inward(fa, na), inward(fb, nb)) else { return Err(KernelError::Failed("fillet: edge direction".into())) }; - if ia.dot(ta) < 1e-6 || ib.dot(tb) < 1e-6 { - return Err(unsupported("fillets of concave edges with other radii")); - } - let alpha = ta.dot(tb).clamp(-1.0, 1.0).acos(); - if !(alpha > 1e-3 && alpha < std::f64::consts::PI - 1e-3) { - return Err(unsupported("the faces at the edge are tangent")); - } - let r = radius.get(id).copied().unwrap_or(1.0); - let s = if round { r / (alpha / 2.0).tan() } else { r }; - let w = (alpha / 2.0).sin(); - // The cylinder, well past both ends (sections on oblique end faces reach beyond them). - let m = 4.0 * (s + r); - let (q0, q1) = (p0 - d * m, p1 + d * m); - let ctrl = vec![vec![h(q0 + ta * s, 1.0), h(q1 + ta * s, 1.0)], vec![h(q0, w), h(q1, w)], vec![h(q0 + tb * s, 1.0), h(q1 + tb * s, 1.0)]]; - let surf = if round { - mt::Surface::NurbsSurface(mt::NurbsSurface::new(mt::BSplineSurface::new( - (mt::KnotVec::bezier_knot(2), mt::KnotVec::bezier_knot(1)), - ctrl, - ))) - } else { - mt::Surface::Plane(mt::Plane::new(p3(q0 + ta * s), p3(q1 + ta * s), p3(q0 + tb * s))) - }; - let mid = (p0 + p1) * 0.5; - let axis = mid + ta * s - na * r; - let out = ((ta + tb) * -1.0).normalized().unwrap_or(na); - let surf = orient(surf, axis + (mid - axis).normalized().unwrap_or(out) * r, mid - axis); - touched.insert(v0.id(), v0); - touched.insert(v1.id(), v1); - sels.insert(*id, Sel { r, s, w, fa, fb, na, nb, ta, tb, p0, d, surf }); - } - - // The vertices at the ends of filleted edges: three planar faces, three straight edges. - let mut around: HashMap = HashMap::new(); - for (vid, v) in &touched { - let (eids, fids) = at_vertex.get(vid).ok_or_else(|| KernelError::Failed("vertex".into()))?; - if eids.len() != 3 || fids.len() != 3 { - return Err(unsupported("fillets ending where more than three edges meet")); - } - // Where one fillet ends, the face it ends on may be curved (and the edges it shares - // with the others): the blend ends in that face's section of the cylinder. - let chosen = eids.iter().filter(|id| sels.contains_key(id)).count(); - let sides: Vec = eids.iter().filter_map(|id| sels.get(id)).flat_map(|s| [s.fa, s.fb]).collect(); - if fids.iter().any(|f| normal(*f).is_none() && (chosen != 1 || sides.contains(f))) { - return Err(unsupported("fillets ending on curved faces")); - } - let pv = vtx(v); - let mut list = Vec::new(); - for id in eids { - let e = edges.get(id).ok_or_else(|| KernelError::Failed("edge".into()))?; - let u = if matches!(e.curve(), mt::Curve::Line(_)) { - let other = if e.absolute_front() == v { e.absolute_back() } else { e.absolute_front() }; - (vtx(other) - pv).normalized() - } else if chosen == 1 && !sels.contains_key(id) { - leaving(e, v) - } else { - return Err(unsupported("fillets ending next to curved edges")); - } - .ok_or_else(|| KernelError::Failed("zero-length edge".into()))?; - list.push((*id, u)); - } - around.insert(*vid, Around { edges: list }); - } - - guard("fillet corners", || { - // New end points: (edge, vertex, face for a filleted edge's contact line). - let mut endpt: HashMap<(mt::EdgeID, mt::VertexID, Option), mt::Vertex> = HashMap::new(); - let mut pool: HashMap)>> = HashMap::new(); - // Corner patches, with the edges meeting at their corner. - let mut patches: Vec<(mt::Face, [mt::EdgeID; 3])> = Vec::new(); - let face_with = |a: mt::EdgeID, b: mt::EdgeID| -> Result { - let fa = on_edge.get(&a).cloned().unwrap_or_default(); - let fb = on_edge.get(&b).cloned().unwrap_or_default(); - fa.into_iter().find(|f| fb.contains(f)).ok_or_else(|| KernelError::Failed("fillet corner: faces".into())) - }; - for (vid, ar) in &around { - let v = vtx(touched.get(vid).ok_or_else(|| KernelError::Failed("vertex".into()))?); - let mut chosen: Vec<(mt::EdgeID, Vec3)> = ar.edges.iter().filter(|(id, _)| sels.contains_key(id)).copied().collect(); - let rest: Vec<(mt::EdgeID, Vec3)> = ar.edges.iter().filter(|(id, _)| !sels.contains_key(id)).copied().collect(); - chosen.sort_by_key(|(id, _)| order.iter().position(|x| x == id)); - let sel = |id: mt::EdgeID| sels.get(&id).ok_or_else(|| KernelError::Failed("fillet".into())); - // At an inner rim a contact line can extend the next edge backwards. - // Its new endpoint must remain in the trimmed face, including its holes. - let check_extension = |q: Vec3, fi: usize| -> Result { - let face = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?; - if !crate::blend::extension_fits(face, v, q, size * 1e-7) { - return Err(too_large("a fillet larger than the faces next to it")); - } - Ok(q) - }; - let hit = |u: Vec3, t: Vec3, s: f64, fi: usize| -> Result { - let q = hit(v, u, t, s)?; - if u.dot(t) < 0.0 { check_extension(q, fi) } else { Ok(q) } - }; - let list = pool.entry(*vid).or_default(); - match (&chosen[..], &rest[..]) { - ([(e1, _)], [(e2, u2), (e3, u3)]) => { - let s1 = sel(*e1)?; - let (f12, f31) = (face_with(*e1, *e2)?, face_with(*e1, *e3)?); - let f23 = face_with(*e2, *e3)?; - // Along a curved neighbouring edge: where it crosses the contact line. - let reach = |e: mt::EdgeID, u: Vec3, f: usize| -> Result { - match edges.get(&e) { - Some(x) if !matches!(x.curve(), mt::Curve::Line(_)) => crossing(x, v, s1.t(f), s1.s), - _ => hit(u, s1.t(f), s1.s, f), - } - }; - let p2 = reach(*e2, *u2, f12)?; - let p3_ = reach(*e3, *u3, f31)?; - let (a, b) = (builder::vertex(p3(p2)), builder::vertex(p3(p3_))); - endpt.insert((*e2, *vid, None), a.clone()); - endpt.insert((*e1, *vid, Some(f12)), a.clone()); - endpt.insert((*e3, *vid, None), b.clone()); - endpt.insert((*e1, *vid, Some(f31)), b.clone()); - let c = match faces.get(f23) { - Some(g) if normal(f23).is_none() => { - let e1v = edges.get(e1).ok_or_else(|| KernelError::Failed("edge".into()))?; - let far = if e1v.absolute_front().id() == *vid { vtx(e1v.absolute_back()) } else { vtx(e1v.absolute_front()) }; - edge(&a, &b, curved_section(s1, g, (p2, s1.t(f12)), (p3_, s1.t(f31)), v, far, round, size)?)? - } - _ if round => edge(&a, &b, mt::Curve::NurbsCurve(conic(p2, v, p3_, s1.w)))?, - _ => builder::line(&a, &b), - }; - list.push((c, vec![Owner::Face(f23), Owner::Cyl(*e1)])); - } - ([(ea, ua), (eb, ub)], [(e3, u3)]) => { - let (sa, sb) = (sel(*ea)?, sel(*eb)?); - let fab = face_with(*ea, *eb)?; - let (fb3, fa3) = (face_with(*eb, *e3)?, face_with(*ea, *e3)?); - let q = meet(v, (*ua, sa.t(fab), sa.s), (*ub, sb.t(fab), sb.s))?; - if ua.dot(sb.t(fab)) < 0.0 || ub.dot(sa.t(fab)) < 0.0 { - check_extension(q, fab)?; - } - // Where each cylinder touches the third edge. - let xb = hit(*u3, sb.t(fb3), sb.s, fb3)?; - let xa = hit(*u3, sa.t(fa3), sa.s, fa3)?; - let qv = builder::vertex(p3(q)); - endpt.insert((*ea, *vid, Some(fab)), qv.clone()); - endpt.insert((*eb, *vid, Some(fab)), qv.clone()); - let (la, lb) = ((xa - v).len(), (xb - v).len()); - let crease_to = |end: Vec3| -> Result { - if round { crease(sa, sb, q, end, size) } else { Ok(mt::Curve::Line(mt::Line(p3(q), p3(end)))) } - }; - if (la - lb).abs() <= size * 1e-9 { - let xv = builder::vertex(p3(xb)); - endpt.insert((*e3, *vid, None), xv.clone()); - endpt.insert((*ea, *vid, Some(fa3)), xv.clone()); - endpt.insert((*eb, *vid, Some(fb3)), xv.clone()); - let c = edge(&qv, &xv, crease_to(xb)?)?; - list.push((c, vec![Owner::Cyl(*ea), Owner::Cyl(*eb)])); - } else { - // The larger blend (reaching further down the third edge) ends on the - // face it shares with the smaller one's other side. - let (big, small, us, fbig3, fsmall3, eb_, es, x) = - if lb > la { (sb, sa, *ua, fb3, fa3, *eb, *ea, xb) } else { (sa, sb, *ub, fa3, fb3, *ea, *eb, xa) }; - // The big cylinder's section by the small one's end face: from the third - // edge to the small edge's line, where it crosses the small contact line. - let z = hit(us, big.t(fab), big.s, fab)?; - let mut sec = conic(x, v, z, big.w); - let tt = small.t(fsmall3); - let c0 = (x - v).dot(tt) - small.s; - let c1 = big.w * (0.0 - small.s); - let c2 = (z - v).dot(tt) - small.s; - // A chamfer section is a line, not the cylinder's conic. - // Where it meets the other strip's contact line is also - // where the crease ends; the remainder trims that wall. - let t = if round { bernstein_root(c0, c1, c2) } else { Some(c0 / (c0 - c2)).filter(|t| *t > 0.0 && *t < 1.0) } - .ok_or_else(|| unsupported("blends this different in size at one corner"))?; - let y = if round { - use mt::ParametricCurve; - crate::body::from_p3(sec.subs(t)) - } else { - x + (z - x) * t - }; - { - use mt::Cut; - let _ = sec.cut(t); - } - let xv = builder::vertex(p3(x)); - let yv = builder::vertex(p3(y)); - endpt.insert((*e3, *vid, None), xv.clone()); - endpt.insert((eb_, *vid, Some(fbig3)), xv.clone()); - endpt.insert((es, *vid, Some(fsmall3)), yv.clone()); - let piece = if round { edge(&xv, &yv, mt::Curve::NurbsCurve(sec))? } else { builder::line(&xv, &yv) }; - list.push((piece, vec![Owner::Face(fsmall3), Owner::Cyl(eb_)])); - let c = edge(&qv, &yv, crease_to(y)?)?; - list.push((c, vec![Owner::Cyl(*ea), Owner::Cyl(*eb)])); - } - } - ([(e1, u1), (e2, u2), (e3, u3)], []) => { - if !round { - return Err(unsupported("three chamfers at one corner in the local blend")); - } - let (s1, s2, s3) = (sel(*e1)?, sel(*e2)?, sel(*e3)?); - let (f12, f23, f31) = (face_with(*e1, *e2)?, face_with(*e2, *e3)?, face_with(*e3, *e1)?); - let q12 = meet(v, (*u1, s1.t(f12), s1.s), (*u2, s2.t(f12), s2.s))?; - let q23 = meet(v, (*u2, s2.t(f23), s2.s), (*u3, s3.t(f23), s3.s))?; - let q31 = meet(v, (*u3, s3.t(f31), s3.s), (*u1, s1.t(f31), s1.s))?; - let (v12, v23, v31) = (builder::vertex(p3(q12)), builder::vertex(p3(q23)), builder::vertex(p3(q31))); - for (e, f, x) in [(e1, f12, &v12), (e2, f12, &v12), (e2, f23, &v23), (e3, f23, &v23), (e3, f31, &v31), (e1, f31, &v31)] { - endpt.insert((*e, *vid, Some(f)), x.clone()); - } - let out = (normal(f12).unwrap_or(Vec3::Z) + normal(f23).unwrap_or(Vec3::Z) + normal(f31).unwrap_or(Vec3::Z)) - .normalized() - .unwrap_or(Vec3::Z); - let n = |f: usize| normal(f).unwrap_or(Vec3::Z); - let cp = corner_patch([s1, s2, s3], [f12, f23, f31], [q12, q23, q31], [n(f12), n(f23), n(f31)], out, size)?; - let [t1, t2, t3] = cp.sections; - let c1 = edge(&v12, &v31, mt::Curve::NurbsCurve(t1))?; - let c2 = edge(&v12, &v23, mt::Curve::NurbsCurve(t2))?; - let c3 = edge(&v23, &v31, mt::Curve::NurbsCurve(t3))?; - let surf = cp.surf; - let wire: mt::Wire = vec![c2.clone(), c3.clone(), c1.inverse()].into(); - patches - .push((mt::Face::try_new(vec![wire], surf).map_err(|e| KernelError::Failed(format!("corner patch: {e}")))?, [*e1, *e2, *e3])); - list.push((c1, vec![Owner::Cyl(*e1), Owner::Patch])); - list.push((c2, vec![Owner::Cyl(*e2), Owner::Patch])); - list.push((c3, vec![Owner::Cyl(*e3), Owner::Patch])); - } - _ => return Err(unsupported("this corner")), - } - } - - // Rebuilt edges: contact lines per (edge, face), shortened edges per edge. - let end_of = - |id: mt::EdgeID, v: &mt::Vertex, f: Option| -> mt::Vertex { endpt.get(&(id, v.id(), f)).cloned().unwrap_or_else(|| v.clone()) }; - let mut lines: HashMap<(mt::EdgeID, Option), mt::Edge> = HashMap::new(); - let mut line_of = |e: &mt::Edge, f: Option| -> Result { - if let Some(x) = lines.get(&(e.id(), f)) { - return Ok(x.clone()); - } - let (a, b) = (end_of(e.id(), e.absolute_front(), f), end_of(e.id(), e.absolute_back(), f)); - let (pa, pb) = (vtx(&a), vtx(&b)); - let orig = vtx(e.absolute_back()) - vtx(e.absolute_front()); - if (pb - pa).dot(orig) <= size * 1e-9 * orig.len() { - return Err(too_large("a fillet larger than the faces next to it")); - } - let x = if matches!(e.curve(), mt::Curve::Line(_)) { - builder::line(&a, &b) - } else { - // A curved edge next to a fillet's end, shortened along its own curve. - let moved = |n: &mt::Vertex, o: &mt::Vertex| (n != o).then(|| n.clone()); - crate::curveblend::trim_curved_seam(&e.absolute_clone(), moved(&a, e.absolute_front()), moved(&b, e.absolute_back()), size)? - }; - lines.insert((e.id(), f), x.clone()); - Ok(x) - }; - let moved = |e: &mt::Edge| touched.contains_key(&e.absolute_front().id()) || touched.contains_key(&e.absolute_back().id()); - let mut rec = crate::record::Rebuild::default(); - let mut new_faces: Vec = Vec::with_capacity(faces.len() + sels.len() + patches.len()); - for (fi, f) in faces.iter().enumerate() { - if !f.vertex_iter().any(|v| touched.contains_key(&v.id())) { - new_faces.push(f.clone()); - continue; - } - let mut wires = Vec::new(); - for w in f.boundaries() { - let olds: Vec = w.edge_iter().cloned().collect(); - let mut news = Vec::with_capacity(olds.len()); - for e in &olds { - let ne = if sels.contains_key(&e.id()) { - line_of(e, Some(fi))? - } else if moved(e) { - // The edge itself, shortened at the corner. - let piece = line_of(e, None)?; - rec.piece(&piece, e); - piece - } else { - news.push(e.clone()); - continue; - }; - news.push(if e.front() == e.absolute_front() { ne } else { ne.inverse() }); - } - let n = news.len(); - let mut out = Vec::new(); - for i in 0..n { - let (Some(a), Some(b), Some(old)) = (news.get(i), news.get((i + 1) % n), olds.get(i)) else { continue }; - out.push(a.clone()); - if a.back() != b.front() { - let p = pool.get(&old.back().id()).map(|x| &x[..]).unwrap_or(&[]); - out.extend(connect(a.back(), b.front(), p, Owner::Face(fi))?); - } - } - wires.push(mt::Wire::from(out)); - } - let rebuilt = mt::Face::try_new(wires, f.oriented_surface()).map_err(|e| KernelError::Failed(format!("fillet: face: {e}")))?; - rec.face(&rebuilt, f); - new_faces.push(rebuilt); - } - // The blends: back along the first face's contact line, round the corner, along the - // second's, round the other corner. - for id in &order { - let (Some(s), Some(e)) = (sels.get(id), edges.get(id)) else { continue }; - let (va, vb) = (e.absolute_front(), e.absolute_back()); - let a_forward = faces.get(s.fa).is_some_and(|f| f.boundaries().iter().any(|w| w.edge_iter().any(|x| x.id() == *id && x.front() == va))); - let la = line_of(e, Some(s.fa))?; - let lb = line_of(e, Some(s.fb))?; - let (first, second, c1, c2) = if a_forward { (la.inverse(), lb, va, vb) } else { (lb.inverse(), la, va, vb) }; - let p1 = pool.get(&c1.id()).map(|x| &x[..]).unwrap_or(&[]); - let p2 = pool.get(&c2.id()).map(|x| &x[..]).unwrap_or(&[]); - let mut w = vec![first.clone()]; - w.extend(connect(first.back(), second.front(), p1, Owner::Cyl(*id))?); - w.push(second.clone()); - w.extend(connect(second.back(), first.front(), p2, Owner::Cyl(*id))?); - let blend = mt::Face::try_new(vec![w.into()], s.surf.clone()).map_err(|e| KernelError::Failed(format!("fillet face: {e}")))?; - rec.blend(&blend, [*id]); - new_faces.push(blend); - } - // Corner patches run each section opposite to its blend; each is made in place of the - // edges meeting at its corner. - for (mut p, corner) in patches { - let uses = |f: &mt::Face, id: mt::EdgeID| { - f.boundaries().iter().flat_map(|w| w.edge_iter().cloned().collect::>()).find(|x| x.id() == id).map(|x| x.front().id()) - }; - let flip = p - .boundaries() - .first() - .and_then(|w| w.edge_iter().next()) - .and_then(|pe| new_faces.iter().find_map(|f| uses(f, pe.id())).map(|front| front == pe.front().id())); - if flip == Some(true) { - let surf = p.oriented_surface(); - let wires: Vec = p.boundaries().iter().map(|w| w.inverse()).collect(); - p = mt::Face::try_new(wires, surf).map_err(|e| KernelError::Failed(format!("corner patch: {e}")))?; - } - rec.blend(&p, corner); - new_faces.push(p); - } - let mut shells = solid.boundaries().clone(); - if let Some(sh) = shells.get_mut(si) { - *sh = new_faces.into(); - } - let out = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("fillet produced an invalid solid: {e}")))?; - crate::record::rebuilt(out, &[&solid], &rec) - }) -} - -/// The root in (0, 1) of the quadratic with Bernstein coefficients c0, c1, c2. -fn bernstein_root(c0: f64, c1: f64, c2: f64) -> Option { - let (a, b, c) = (c0 - 2.0 * c1 + c2, 2.0 * (c1 - c0), c0); - let roots: Vec = if a.abs() < 1e-14 { - if b.abs() < 1e-14 { vec![] } else { vec![-c / b] } - } else { - let disc = b * b - 4.0 * a * c; - if disc < 0.0 { - vec![] - } else { - let sq = disc.sqrt(); - vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)] - } - }; - roots.into_iter().filter(|t| *t > 1e-9 && *t < 1.0 - 1e-9).min_by(|x, y| x.total_cmp(y)) -} - -/// The crease where the blends of two edges cross, from `q` (their contact lines' crossing) to -/// `end`: rulings of the first cylinder cut by the second, through a cubic. -fn crease(a: &Sel, b: &Sel, q: Vec3, end: Vec3, size: f64) -> Result { - let (ca, da) = (a.axis_point(), a.d); - let (cb, db) = (b.axis_point(), b.d); - let g = a.na; - let hh = (a.nb - g * a.nb.dot(g)).normalized().ok_or_else(|| unsupported("the faces at the edge are tangent"))?; - let angle = |p: Vec3| { - let x = p - ca; - x.dot(hh).atan2(x.dot(g)) - }; - let (th0, th1) = (angle(q), angle(end)); - let (l0, l1) = ((q - ca).dot(da), (end - ca).dot(da)); - let dd = da - db * da.dot(db); - let k2 = dd.dot(dd); - if k2 < 1e-12 { - return Err(unsupported("fillets of parallel edges meeting")); - } - let n = 48; - let mut pts = vec![p3(q)]; - for i in 1..n { - let f = i as f64 / n as f64; - let th = th0 + (th1 - th0) * f; - let target = l0 + (l1 - l0) * f; - let base = ca + (g * th.cos() + hh * th.sin()) * a.r; - let b0 = (base - cb) - db * (base - cb).dot(db); - let (k1, k0) = (b0.dot(dd), b0.dot(b0) - b.r * b.r); - let disc = (k1 * k1 - k2 * k0).max(0.0); - let sq = disc.sqrt(); - let (r1, r2) = ((-k1 - sq) / k2, (-k1 + sq) / k2); - let lam = if (r1 - target).abs() < (r2 - target).abs() { r1 } else { r2 }; - let p = base + da * lam; - // Still on both cylinders. - let off = (p - cb) - db * (p - cb).dot(db); - if (off.len() - b.r).abs() > size * 1e-6 + b.r * 1e-6 { - return Err(unsupported("fillets this different in size at one corner")); - } - pts.push(p3(p)); - } - pts.push(p3(end)); - let mut curve = crate::splitface::fit(&pts, size)?; - // The last chord tilts away from the cylinders' intersection tangent. At an equal-radius - // mitre that tangent continues the sharp third edge; losing it breaks the smooth chain - // used to map picks when a later fillet rebuilds these rounds (#2422). - let radial = |c: Vec3, d: Vec3| (end - c) - d * (end - c).dot(d); - if (a.r - b.r).abs() <= size * 1e-9 - && let Some(tangent) = radial(ca, da).cross(radial(cb, db)).normalized() - && let mt::Curve::BSplineCurve(ref mut spline) = curve - && let Some(index) = spline.control_points().len().checked_sub(2) - && let Some(control) = spline.control_points_mut().nth(index) - { - let toward_end = end - crate::body::from_p3(*control); - let tangent = if tangent.dot(toward_end) < 0.0 { -tangent } else { tangent }; - *control = p3(end - tangent * toward_end.len()); - } - Ok(curve) -} - -/// Keep selected sharp edges while consuming a selected mitre that is on the same smooth -/// chain as one of them. After removing the rounds, that mitre no longer exists; using its -/// old point would silently choose a different nearby edge, possibly with a different radius. -fn surviving_picks(cur: &Body, sel: &[(Vec3, f64)], removed: &[usize]) -> Result> { - let solid = &*cur.solid; - let edges = Body::unique_edges(solid); - let faces: Vec<_> = solid.face_iter().collect(); - let mut selected = Vec::new(); - for (p, r) in sel { - let (idx, _) = cur.nearest_edge(*p, (cur.size() * 2e-3).max(1e-3))?.ok_or_else(|| unsupported("no edge at a fillet pick"))?; - let e = edges.get(idx).ok_or_else(|| unsupported("no edge at a fillet pick"))?; - let count = removed.iter().filter_map(|i| faces.get(*i)).filter(|f| f.edge_iter().any(|x| x.id() == e.id())).count(); - selected.push((e, *p, *r, count)); - } - for (e, _, r, count) in &selected { - if *count == 0 { - continue; - } - let chain = crate::blend::smooth_chain(solid, e).unwrap_or_default(); - if *count != 2 || !selected.iter().any(|(other, _, rr, n)| *n == 0 && (r - rr).abs() <= r * 1e-9 && chain.contains(&other.id())) { - return Err(unsupported("a selected earlier-round boundary cannot be mapped to a sharp edge")); - } - } - Ok(selected.into_iter().filter(|(_, _, _, n)| *n == 0).map(|(_, p, r, _)| (p, r)).collect()) -} - -/// Connected faces at the filleted edges' ends that are rounds of straight edges between planar faces: -/// (face index, a point on the sharp edge it replaced, its radius). -fn rounds_at(cur: &Body, sel: &[(Vec3, f64)]) -> Result> { - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let solid = &*cur.solid; - let all = Body::unique_edges(solid); - let mut ends: Vec = Vec::new(); - for (p, _) in sel { - if let Ok(Some((idx, _))) = cur.nearest_edge(*p, tol) - && let Some(e) = all.get(idx) - { - ends.push(vtx(e.absolute_front())); - ends.push(vtx(e.absolute_back())); - } - } - let faces: Vec<&mt::Face> = solid.face_iter().collect(); - let mut neighbours: HashMap> = HashMap::new(); - for (fi, f) in faces.iter().enumerate() { - for e in f.edge_iter() { - neighbours.entry(e.id()).or_default().push(fi); - } - } - let mut pending: Vec = faces - .iter() - .enumerate() - .filter(|(_, f)| f.vertex_iter().any(|v| ends.iter().any(|p| p.dist(vtx(&v)) <= size * 1e-9))) - .map(|(fi, _)| fi) - .collect(); - let mut visited = HashSet::new(); - let mut out = Vec::new(); - while let Some(fi) = pending.pop() { - if !visited.insert(fi) { - continue; - } - let Some(f) = faces.get(fi) else { continue }; - if plane_normal(f).is_some() { - continue; - } - if let Some((p, r)) = round_of(&faces, f, size) { - if out.len() + sel.len() >= 1000 { - return Err(unsupported("too many connected earlier rounds to rebuild")); - } - out.push((fi, p, r)); - // Healing requires planar neighbours. Include the other recognised rounds - // sharing this one's mitres, rather than leaving a curved neighbour across - // the gap. A closed ring must be restored and reblended as a whole (#1557). - for e in f.edge_iter() { - pending.extend(neighbours.get(&e.id()).into_iter().flatten().copied().filter(|i| !visited.contains(i))); - } - } - } - out.sort_by_key(|r| r.0); - Ok(out) -} - -/// A round between two planes: two parallel straight boundary edges on planar faces, the -/// surface a cylinder tangent to both. The sharp edge's midpoint and the radius. -fn round_of(faces: &[&mt::Face], f: &mt::Face, size: f64) -> Option<(Vec3, f64)> { - use mt::{ParametricSurface, SearchNearestParameter}; - let mut lines: Vec<(Vec3, Vec3, Vec3)> = Vec::new(); - for e in f.edge_iter() { - if !matches!(e.curve(), mt::Curve::Line(_)) { - continue; - } - let other = faces.iter().find(|g| !std::ptr::eq(**g, f) && g.edge_iter().any(|x| x.id() == e.id()))?; - let n = plane_normal(other)?; - lines.push((vtx(e.absolute_front()), vtx(e.absolute_back()), n)); - } - for (i, (a0, a1, na)) in lines.iter().enumerate() { - for (b0, b1, nb) in lines.iter().skip(i + 1) { - let d = (*a1 - *a0).normalized()?; - if (*b1 - *b0).normalized()?.cross(d).len() > 1e-9 || na.cross(*nb).len() < 1e-6 { - continue; - } - // The cross-section through a's midpoint. - let a = (*a0 + *a1) * 0.5; - let b = *b0 + d * (a - *b0).dot(d); - let dn = *nb - *na; - let r = (b - a).len() / dn.len(); - if (b - a - dn * r).len() > size * 1e-6 { - continue; - } - // The surface is the cylinder about a − r·na. - let c = a - *na * r; - let mid = c + (*na + *nb).normalized()? * r; - let surf = f.surface(); - let (u, v) = surf.search_nearest_parameter(p3(mid), None, 100)?; - if crate::body::from_p3(surf.subs(u, v)).dist(mid) > size * 1e-6 { - continue; - } - let p = planes3((*na, a), (*nb, b), (d, a)).ok()?; - return Some((p, r)); - } - } - None -} - -struct CornerPatch { - /// Sections of the first blend (q12 → q31), the second (q12 → q23), the third (q23 → q31). - sections: [mt::NurbsCurve; 3], - surf: mt::Surface, -} - -/// Plane section of a blend's cylinder from `a` to `b` (points on its contact lines): the plane -/// holds the chord and the faces' bisector turned by `psi` about the chord. Its middle control -/// point and the curve. -fn section(s: &Sel, a: Vec3, b: Vec3, psi: f64) -> Result<(Vec3, mt::NurbsCurve)> { - let c = (b - a).normalized().ok_or_else(|| unsupported("a corner this small"))?; - let bis = s.na + s.nb; - let bis = (bis - c * bis.dot(c)).normalized().ok_or_else(|| unsupported("the faces at the edge are tangent"))?; - let dir = bis * psi.cos() + c.cross(bis) * psi.sin(); - let cut_n = c.cross(dir).normalized().ok_or_else(|| unsupported("a corner this small"))?; - let m = planes3((s.na, s.p0), (s.nb, s.p0), (cut_n, a))?; - if m.dist(a) > 10.0 * (s.s + s.r) { - return Err(unsupported("a corner this skewed")); - } - Ok((m, conic(a, m, b, s.w))) -} - -/// The corner where three blends meet. Equal radii: a sphere through cross-sections of the -/// cylinders. Else the sections are turned so that the blends' curvatures agree where two of -/// them meet on a face (else no smooth patch can meet both there), and a rational patch of -/// degree 4 through them, closed at q31, is fitted tangent to the three cylinders and to the -/// face at q31. -fn corner_patch(s: [&Sel; 3], f: [usize; 3], q: [Vec3; 3], n: [Vec3; 3], out: Vec3, size: f64) -> Result { - let [s1, s2, s3] = s; - let [f12, f23, _] = f; - let [q12, q23, q31] = q; - let [n12, n23, n31] = n; - let equal = (s1.r - s2.r).abs() <= size * 1e-9 && (s1.r - s3.r).abs() <= size * 1e-9; - let mk = |psi: [f64; 3]| -> Result<[(Vec3, mt::NurbsCurve); 3]> { - Ok([section(s1, q12, q31, psi[0])?, section(s2, q12, q23, psi[1])?, section(s3, q23, q31, psi[2])?]) - }; - if equal { - // A sphere about the point a radius inside all three faces, its poles and seam away - // from the patch. - let [(_, t1), (_, t2), (_, t3)] = mk([0.0; 3])?; - let r = s1.r; - let c = planes3((n12, q12 - n12 * r), (n23, q23 - n23 * r), (n31, q31 - n31 * r))?; - let side = out.any_perp(); - let (np, sp, back) = (c + side * r, c - side * r, c - out * r); - let meridian = builder::circle_arc(&builder::vertex(p3(np)), &builder::vertex(p3(sp)), p3(back)); - let surf = mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(meridian.oriented_curve(), p3(c), v3(side)))); - return Ok(CornerPatch { sections: [t1, t2, t3], surf: orient(surf, c + out * r, out) }); - } - // Curvature agreement at q12 (blends 1, 2) and q23 (blends 2, 3): along unit tangents x, y - // the normal curvatures (x·e)(y·e)/r of the two cylinders match (e: in the face, square to - // the cylinder's axis). - let rmin = s1.r.min(s2.r).min(s3.r); - let resid = |psi: [f64; 3]| -> Option<[f64; 5]> { - let [(m1, _), (m2, _), (m3, _)] = mk(psi).ok()?; - let ii = |x: Vec3, y: Vec3, e: Vec3, r: f64| x.dot(e) * y.dot(e) / r; - let (a, b) = ((m1 - q12).normalized()?, (m2 - q12).normalized()?); - let c12 = ii(a, b, s1.t(f12), s1.r) - ii(a, b, s2.t(f12), s2.r); - let (a, b) = ((m2 - q23).normalized()?, (m3 - q23).normalized()?); - let c23 = ii(a, b, s2.t(f23), s2.r) - ii(a, b, s3.t(f23), s3.r); - let mu = 1e-2; - Some([c12 * rmin, c23 * rmin, psi[0] * mu, psi[1] * mu, psi[2] * mu]) - }; - let cost = |p: [f64; 3]| resid(p).map(|r| r.iter().map(|x| x * x).sum::()).unwrap_or(f64::INFINITY); - let mut best = [0.0; 3]; - for start in [[0.0; 3], [0.3, 0.3, 0.3], [-0.3, -0.3, -0.3], [0.3, -0.3, 0.3], [-0.3, 0.3, -0.3]] { - let mut p = start; - let mut lambda = 1e-3; - for _ in 0..100 { - let Some(r0) = resid(p) else { break }; - // Gauss-Newton with damping on the 3 unknowns. - let mut jac = [[0.0; 3]; 5]; - for k in 0..3 { - let mut q = p; - if let Some(x) = q.get_mut(k) { - *x += 1e-7; - } - let Some(rk) = resid(q) else { continue }; - for (i, row) in jac.iter_mut().enumerate() { - if let (Some(slot), Some(a), Some(b)) = (row.get_mut(k), rk.get(i), r0.get(i)) { - *slot = (a - b) / 1e-7; - } - } - } - let mut m = [[0.0; 3]; 3]; - let mut g = [0.0; 3]; - for (i, row) in jac.iter().enumerate() { - for a in 0..3 { - if let (Some(ga), Some(ja), Some(ri)) = (g.get_mut(a), row.get(a), r0.get(i)) { - *ga -= ja * ri; - } - for b in 0..3 { - if let (Some(mab), Some(ja), Some(jb)) = (m.get_mut(a).and_then(|x| x.get_mut(b)), row.get(a), row.get(b)) { - *mab += ja * jb; - } - } - } - } - for (a, row) in m.iter_mut().enumerate() { - if let Some(x) = row.get_mut(a) { - *x *= 1.0 + lambda; - } - } - let Some(dp) = crate::polyhedron::solve3_pub(m, g) else { break }; - let next = [p[0] + dp[0], p[1] + dp[1], p[2] + dp[2]]; - if cost(next) < cost(p) { - p = next; - lambda *= 0.3; - } else { - lambda *= 10.0; - } - if dp.iter().all(|x| x.abs() < 1e-12) { - break; - } - } - if cost(p) < cost(best) { - best = p; - } - } - let [(m1, t1), (m2, t2), (m3, t3)] = mk(best)?; - // Degree-2 patch through the sections (rows along the second section, columns along the - // first and third), raised to degree 4. - let w11 = s2.w * (s1.w + s3.w) * 0.5; - let p11 = ((m1 + m2 + m3) * 2.0 - (q12 + q23 + q31)) * (1.0 / 3.0); - let c2: [[mt::Vector4; 3]; 3] = - [[h(q12, 1.0), h(m1, s1.w), h(q31, 1.0)], [h(m2, s2.w), h(p11, w11), h(q31, s2.w)], [h(q23, 1.0), h(m3, s3.w), h(q31, 1.0)]]; - const RAISE: [[f64; 3]; 5] = [[1.0, 0.0, 0.0], [0.5, 0.5, 0.0], [1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0], [0.0, 0.5, 0.5], [0.0, 0.0, 1.0]]; - let zero = mt::Vector4::new(0.0, 0.0, 0.0, 0.0); - let mut hp = [[zero; 5]; 5]; - for (i, ri) in RAISE.iter().enumerate() { - for (j, rj) in RAISE.iter().enumerate() { - let mut acc = zero; - for (a, ca) in ri.iter().enumerate() { - for (b, cb) in rj.iter().enumerate() { - if let Some(x) = c2.get(a).and_then(|r| r.get(b)) { - acc += *x * (ca * cb); - } - } - } - if let Some(slot) = hp.get_mut(i).and_then(|r| r.get_mut(j)) { - *slot = acc; - } - } - } - fit_tangent(&mut hp, [s1, s2, s3], q31, n31)?; - let ctrl: Vec> = hp.iter().map(|r| r.to_vec()).collect(); - let surf = - mt::Surface::NurbsSurface(mt::NurbsSurface::new(mt::BSplineSurface::new((mt::KnotVec::bezier_knot(4), mt::KnotVec::bezier_knot(4)), ctrl))); - let rs = s1.r + s2.r + s3.r; - let surf = orient(surf, (q12 + q23 + q31) * (1.0 / 3.0) + out * rs * 0.05, out); - Ok(CornerPatch { sections: [t1, t2, t3], surf }) -} - -fn bern4(i: usize, t: f64) -> f64 { - let c = [1.0, 4.0, 6.0, 4.0, 1.0]; - c.get(i).copied().unwrap_or(0.0) * t.powi(i as i32) * (1.0 - t).powi(4 - i as i32) -} - -/// Move the inner control points of the degree-4 patch (boundary rows fixed) as little as -/// possible so that across each boundary the patch is tangent to that blend's cylinder, and at -/// the closed corner q31 to the face there (normal `n31`): conditions linear in the homogeneous -/// points, sampled along each boundary and solved by least squares. -fn fit_tangent(hp: &mut [[mt::Vector4; 5]; 5], s: [&Sel; 3], q31: Vec3, n31: Vec3) -> Result<()> { - const N: usize = 36; - let unknown = |i: usize, j: usize| -> Option { ((1..4).contains(&i) && (1..4).contains(&j)).then(|| ((i - 1) * 3 + (j - 1)) * 4) }; - let at = - |hp: &[[mt::Vector4; 5]; 5], i: usize, j: usize| hp.get(i).and_then(|r| r.get(j)).copied().unwrap_or(mt::Vector4::new(0.0, 0.0, 0.0, 1.0)); - let eval = |hp: &[[mt::Vector4; 5]; 5], u: f64, v: f64| -> Vec3 { - let mut acc = mt::Vector4::new(0.0, 0.0, 0.0, 0.0); - for i in 0..5 { - for j in 0..5 { - acc += at(hp, i, j) * (bern4(i, u) * bern4(j, v)); - } - } - if acc.w.abs() < 1e-300 { Vec3::ZERO } else { Vec3::new(acc.x / acc.w, acc.y / acc.w, acc.z / acc.w) } - }; - let cyl_normal = |s: &Sel, p: Vec3| -> Vec3 { - let x = p - s.axis_point(); - (x - s.d * x.dot(s.d)).normalized().unwrap_or(Vec3::Z) - }; - let mut rows: Vec<([f64; N], f64)> = Vec::new(); - let big = 1e3; - let samples = 13; - for k in 1..=samples { - let t = k as f64 / (samples + 1) as f64; - // Boundary u = 0 (first blend), v = 0 (second), u = 1 (third): the row next to it. - for bd in 0..3 { - let mut row = [0.0; N]; - let mut cst = 0.0; - let (p, sel) = match bd { - 0 => (eval(hp, 0.0, t), s[0]), - 1 => (eval(hp, t, 0.0), s[1]), - _ => (eval(hp, 1.0, t), s[2]), - }; - let n = cyl_normal(sel, p); - for m in 0..5 { - let (i, j) = match bd { - 0 => (1, m), - 1 => (m, 1), - _ => (3, m), - }; - let b = bern4(m, t); - let coef = [n.x * b, n.y * b, n.z * b, -p.dot(n) * b]; - match unknown(i, j) { - Some(o) => { - for (c, x) in coef.iter().enumerate() { - if let Some(slot) = row.get_mut(o + c) { - *slot += x * big; - } - } - } - None => { - let hv = at(hp, i, j); - cst += coef[0] * hv.x + coef[1] * hv.y + coef[2] * hv.z + coef[3] * hv.w; - } - } - } - rows.push((row, -cst * big)); - } - } - // At the closed corner every direction leaving it lies in the face's plane. - for i in 1..4 { - let mut row = [0.0; N]; - if let Some(o) = unknown(i, 3) { - for (c, x) in [n31.x, n31.y, n31.z, -q31.dot(n31)].iter().enumerate() { - if let Some(slot) = row.get_mut(o + c) { - *slot = x * big; - } - } - } - rows.push((row, 0.0)); - } - // Stay near the raised patch. - for i in 1..4 { - for j in 1..4 { - let hv = at(hp, i, j); - if let Some(o) = unknown(i, j) { - for (c, x) in [hv.x, hv.y, hv.z, hv.w].iter().enumerate() { - let mut row = [0.0; N]; - if let Some(slot) = row.get_mut(o + c) { - *slot = 1.0; - } - rows.push((row, *x)); - } - } - } - } - // Normal equations, Gaussian elimination with partial pivoting. - let mut a = vec![[0.0; N]; N]; - let mut y = [0.0; N]; - for (row, rhs) in &rows { - for (p, rp) in row.iter().enumerate() { - if *rp == 0.0 { - continue; - } - if let Some(yp) = y.get_mut(p) { - *yp += rp * rhs; - } - if let Some(ap) = a.get_mut(p) { - for (q, rq) in row.iter().enumerate() { - if let Some(x) = ap.get_mut(q) { - *x += rp * rq; - } - } - } - } - } - for c in 0..N { - let piv = (c..N).max_by(|x, z| { - let g = |r: usize| a.get(r).and_then(|row| row.get(c)).map(|v| v.abs()).unwrap_or(0.0); - g(*x).total_cmp(&g(*z)) - }); - let Some(piv) = piv else { return Err(KernelError::Failed("corner patch".into())) }; - a.swap(c, piv); - y.swap(c, piv); - let (Some(arow), Some(&yc)) = (a.get(c).copied(), y.get(c)) else { continue }; - let d = arow.get(c).copied().unwrap_or(0.0); - if d.abs() < 1e-300 { - return Err(unsupported("this corner patch")); - } - for r in 0..N { - if r == c { - continue; - } - let Some(row) = a.get_mut(r) else { continue }; - let f = row.get(c).copied().unwrap_or(0.0) / d; - if f == 0.0 { - continue; - } - for (x, ac) in row.iter_mut().zip(arow.iter()) { - *x -= f * ac; - } - if let Some(yr) = y.get_mut(r) { - *yr -= f * yc; - } - } - } - for i in 1..4 { - for j in 1..4 { - let Some(o) = unknown(i, j) else { continue }; - let val = |k: usize| y.get(o + k).copied().unwrap_or(0.0) / a.get(o + k).and_then(|r| r.get(o + k)).copied().unwrap_or(1.0); - let v = mt::Vector4::new(val(0), val(1), val(2), val(3)); - if !(v.w > 1e-6 && v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) { - return Err(unsupported("this corner patch")); - } - if let Some(slot) = hp.get_mut(i).and_then(|r| r.get_mut(j)) { - *slot = v; - } - } - } - Ok(()) + let (points, radii): (Vec, Vec) = edges.iter().copied().unzip(); + crate::blend_smlib::fillet_each(body, &points, &radii, crate::FilletTurn::Mitre) } #[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; + use crate::blend::Faces; use crate::{box_solid, fillet, measure}; + use solidcraft_geom::brep::eval::CurveEval; + use solidcraft_geom::prelude::*; /// The 20 mm box and the three edges at its corner (20, 0, 20): `a` along y, `b` along x, /// `c` up. @@ -1285,32 +308,30 @@ mod tests { /// Largest angle (degrees) between the two faces' normals along edges between curved faces. fn kink(b: &Body) -> f64 { - use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; - let faces: Vec<&mt::Face> = b.solid.face_iter().collect(); + let rec = Faces::of(b).unwrap(); let mut worst: f64 = 0.0; - for (i, f) in faces.iter().enumerate() { - for g in faces.iter().skip(i + 1) { - if plane_normal(f).is_some() || plane_normal(g).is_some() { - continue; - } - for e in f.edge_iter().filter(|e| g.edge_iter().any(|x| x.id() == e.id())) { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - for k in 1..10 { - let p = c.subs(t0 + (t1 - t0) * k as f64 / 10.0); - let n = |s: mt::Surface| { - let (u, v) = s.search_nearest_parameter(p, None, 100).unwrap(); - s.normal(u, v) - }; - let (a, bb) = (n(f.oriented_surface()), n(g.oriented_surface())); - worst = worst.max(a.dot(bb).abs().min(1.0).acos().to_degrees()); - } - } + for (i, e) in rec.rec.edges.iter().enumerate() { + let faces: Vec = rec.faces_of(i).into_iter().map(|f| f as usize).collect(); + let [f, g] = faces[..] else { continue }; + if rec.plane_normal(f).is_some() || rec.plane_normal(g).is_some() { + continue; + } + let c = CurveEval::new(e.parameters()).unwrap(); + let [t0, t1] = e.interval; + for k in 1..10 { + let p = c.point(t0 + (t1 - t0) * k as f64 / 10.0).unwrap(); + let (a, bb) = (rec.normal_at(f, p, 1e-3).unwrap(), rec.normal_at(g, p, 1e-3).unwrap()); + worst = worst.max(a.dot(bb).abs().min(1.0).acos().to_degrees()); } } worst } + /// The body's vertex points. + fn vertices(b: &Body) -> Vec { + crate::native::brep_record(b).unwrap().vertices.iter().map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])).collect() + } + #[test] fn analytic_volumes_of_the_reference() { // One round and the sphere corner of three equal ones. @@ -1325,8 +346,7 @@ mod tests { fn a_round_next_to_a_round_of_another_radius() { let (bx, a, b, _) = setup(); let ra = fillet(&bx, &[a], 2.0).unwrap(); - // Today's local blend refuses the edge that ends on the round; the corner path - // takes the round off and blends both edges: their cylinders trim each other. + // The round of b ends on the round of a: their cylinders trim each other. let r = fillet(&ra, &[b], 3.0).unwrap(); assert_eq!(r.face_count(), 8); assert_eq!(r.unmeshed_faces(), 0); @@ -1338,7 +358,7 @@ mod tests { } let s = fillet_radii(&bx, &[(a, 3.0), (b, 2.0)]).unwrap(); assert!((vol(&s) - strips(3.0, 2.0, 0.0)).abs() < 0.05); - // Equal radii: the mitre, as the local blend makes it. + // Equal radii: the mitre. let e = fillet(&ra, &[b], 2.0).unwrap(); assert!((vol(&e) - strips(2.0, 2.0, 0.0)).abs() < 0.05); } @@ -1353,14 +373,16 @@ mod tests { let mut together = bottom.to_vec(); together.push(vertical); let reference = fillet(&b, &together, 2.0).unwrap(); + // The vertical edge, alone or with the seam, with its tangent chain (as the Fillet feature + // asks for it): every pick gives the same body. for picks in [vec![vertical], vec![vertical, seam], vec![seam, vertical]] { - let result = fillet(&rounded, &picks, 2.0).unwrap(); + let result = fillet(&rounded, &crate::tangent_chain(&rounded, &picks).unwrap(), 2.0).unwrap(); assert_eq!(result.face_count(), reference.face_count()); assert_eq!(result.unmeshed_faces(), 0); assert!(result.validity().is_empty(), "{:?}", result.validity()); assert!((vol(&result) - vol(&reference)).abs() < 0.05); - assert!(!result.contains(Vec3::new(24.9, 0.1, 5.0))); - assert!(result.contains(Vec3::new(24.0, 1.0, 5.0))); + assert_eq!(result.classify_point(Vec3::new(24.9, 0.1, 5.0)).unwrap(), crate::PointClass::Outside); + assert_eq!(result.classify_point(Vec3::new(24.0, 1.0, 5.0)).unwrap(), crate::PointClass::Inside); } } @@ -1379,8 +401,8 @@ mod tests { assert!(result.validity().is_empty(), "{:?}", result.validity()); assert!((vol(&result) - vol(&reference)).abs() < 0.05, "radius {radius}"); // The old bottom radius is still 2, away from the newly rounded corner. - assert!(!result.contains(Vec3::new(12.5, 0.5, 0.5))); - assert!(result.contains(Vec3::new(12.5, 1.0, 1.0))); + assert_eq!(result.classify_point(Vec3::new(12.5, 0.5, 0.5)).unwrap(), crate::PointClass::Outside); + assert_eq!(result.classify_point(Vec3::new(12.5, 1.0, 1.0)).unwrap(), crate::PointClass::Inside); } // A tangent boundary of an earlier round is not a sharp edge, and cannot be // reinterpreted as the sharp edge exposed when that round is taken off. @@ -1391,28 +413,42 @@ mod tests { assert!(fillet_radii(&rounded, &[(seam, 2.0)]).is_err()); } + /// A 40 x 80 x 27 box (and the same shelled 1 mm, open at the top) with its bottom edges + /// rounded R2 as four separate fillets (mitred at the bottom corners), then one vertical + /// edge R2: the same solid whichever of its picks comes first. Horizontal sections: below + /// z = r above the bottom, s up, the rectangle moved in by d = r − ρ, ρ = √(r² − (r − s)²), + /// with the rounded corner a quarter disc of radius ρ less than its square (the sphere octant + /// where the three rounds meet); above, the rectangle less that corner at r. With + /// ∫ ρ = π r² / 4, ∫ ρ² = 2 r³ / 3, ∫ d = r² (1 − π/4) and ∫ d² = r³ (5/3 − π/2) over the + /// bottom r. The shell's cavity, 38 x 78 x 26, lies clear of both rounds (the bottom round's + /// arc passes 2 − √2 from the outer corner along the diagonal, the cavity's corner 1). #[test] fn issue2422_vertical_after_separate_bottom_rounds() { + use std::f64::consts::{FRAC_PI_2, FRAC_PI_4}; let origin = Vec3::new(-5.0, 7.2, -2.0); - let b = box_solid(origin, origin + Vec3::new(40.0, 80.0, 27.0)).unwrap(); + let (l, w, h, r) = (40.0, 80.0, 27.0, 2.0); + let b = box_solid(origin, origin + Vec3::new(l, w, h)).unwrap(); let bottom = [Vec3::new(15.0, 7.2, -2.0), Vec3::new(35.0, 47.2, -2.0), Vec3::new(15.0, 87.2, -2.0), Vec3::new(-5.0, 47.2, -2.0)]; + let spandrel = 1.0 - FRAC_PI_4; + let solid = l * w * r - 2.0 * (l + w) * r * r * spandrel + 4.0 * r * r * r * (5.0 / 3.0 - FRAC_PI_2) - spandrel * 2.0 * r * r * r / 3.0 + + (h - r) * (l * w - spandrel * r * r); + let cavity = (l - 2.0) * (w - 2.0) * (h - 1.0); // The issue has no design attached. Reconstruct its outside corner and bottom mitre, // using the reported picks, with and without the open cavity visible in the screenshot. let picks = [Vec3::new(-5.0, 87.2, 12.5), Vec3::new(-4.283446394180081, 86.48344639418008, -1.5001085324947512)]; - for base in [b.clone(), crate::shell(&b, &[Vec3::new(15.0, 47.2, 25.0)], 1.0).unwrap()] { + for (base, want) in [(b.clone(), solid), (crate::shell(&b, &[Vec3::new(15.0, 47.2, 25.0)], 1.0).unwrap(), solid - cavity)] { + // Each fillet with its tangent chain, as the Fillet feature asks for it by default + // (tangent propagation). let mut rounded = base; for edge in bottom { - rounded = fillet(&rounded, &[edge], 2.0).unwrap(); + rounded = fillet(&rounded, &crate::tangent_chain(&rounded, &[edge]).unwrap(), 2.0).unwrap(); } - let reference = fillet(&rounded, &picks[..1], 2.0).unwrap(); - for selection in [picks, [picks[1], picks[0]]] { - let result = fillet(&rounded, &selection, 2.0).unwrap(); - assert_eq!(result.face_count(), reference.face_count()); - assert_eq!(result.unmeshed_faces(), 0); + for selection in [&picks[..1], &picks[..], &[picks[1], picks[0]][..]] { + let result = fillet(&rounded, &crate::tangent_chain(&rounded, selection).unwrap(), 2.0).unwrap(); assert!(result.validity().is_empty(), "{:?}", result.validity()); - assert!((vol(&result) - vol(&reference)).abs() < 0.05); - assert!(!result.contains(Vec3::new(-4.9, 87.1, 10.0))); - assert!(result.contains(Vec3::new(-4.1, 86.3, 10.0))); + assert!((vol(&result) - want).abs() < 1e-6 * want, "{selection:?}: {} vs {want}", vol(&result)); + assert_eq!(result.classify_point(Vec3::new(-4.9, 87.1, 10.0)).unwrap(), crate::PointClass::Outside); + assert_eq!(result.classify_point(Vec3::new(-4.1, 86.3, 10.0)).unwrap(), crate::PointClass::Inside); } } } @@ -1426,7 +462,9 @@ mod tests { let vertical = [Vec3::new(0.0, 0.0, 6.0), Vec3::new(25.0, 0.0, 6.0), Vec3::new(25.0, 25.0, 6.0), Vec3::new(0.0, 25.0, 6.0)].map(|p| p + origin); let rounded = fillet(&b, &bottom, 2.0).unwrap(); - let result = fillet(&rounded, &vertical, 2.0).unwrap(); + // Each vertical edge with its tangent chain (on through the bottom rounds' corners), as + // the Fillet feature asks for it. + let result = fillet(&rounded, &crate::tangent_chain(&rounded, &vertical).unwrap(), 2.0).unwrap(); assert!(result.validity().is_empty(), "{:?}", result.validity()); assert!(kink(&result) < 0.05); // Integrate rounded-square horizontal sections. Above z=r the area is @@ -1442,45 +480,79 @@ mod tests { #[test] fn three_rounds_at_a_corner() { let (bx, a, b, c) = setup(); - // Two rounds meeting in a mitre, then the third edge: a sphere octant. + // Two rounds meeting in a mitre, then the third edge with its tangent chain, as the Fillet + // feature asks for it (84bd2daad): the mitre's seam leaves c's end along c, so the chain + // is c and the seam, and the corner is a sphere octant. The cube less its three rounds + // (each (1 − π/4) r² over its 18 mm straight part) and the corner's 2 mm cube less the + // octant (r³ (1 − π/6)). let ab = fillet(&bx, &[a, b], 2.0).unwrap(); - let r = fillet(&ab, &[c], 2.0).unwrap(); + let r = fillet(&ab, &crate::tangent_chain(&ab, &[c]).unwrap(), 2.0).unwrap(); let sphere = 8000.0 - 3.0 * (1.0 - std::f64::consts::FRAC_PI_4) * 4.0 * 18.0 - 8.0 * (1.0 - std::f64::consts::PI / 6.0); assert_eq!(r.face_count(), 10); - assert!((vol(&r) - sphere).abs() < 0.05, "{} vs {sphere}", vol(&r)); + assert!(r.validity().is_empty(), "{:?}", r.validity()); + assert!((vol(&r) - sphere).abs() < 1e-11 * sphere, "{} vs {sphere}", vol(&r)); assert!(kink(&r) < 0.01); - // Different radii: a smooth patch over the corner, slightly more than the strips take. + // Different radii: SMLib's setback corner (SmBlendSetback.h). Each round runs whole up to + // its section square to its edge at its setback, the owner's rule's (at least 1.5 r, more + // where the rails beside it cross later, scaled to the least at which the corner's G1 fill + // is certified convex), and the hole between the three sections is filled by the setback + // split: one setback patch per round and the triangle between them in three + // quadrilaterals, so 6 planes, 3 rounds and 6 patches (15 faces), G1 across every seam. + // Outside the box the sections span ([20 - d_b, 20] x [0, d_a] x [20 - d_c, 20], d each + // edge's setback) the body is the three strips', so its volume is theirs within that box's. + // The rounds a and b of one radius lie mirrored about the plane x + y = 20 with c: one + // setback. (2, 2, 3): 3.6155, 3.6155, 4.6485; (2, 3, 4): 4.7745, 5.03975, 6.366 (a, b, c). for (rs, sel) in [((2.0, 2.0, 3.0), fillet(&ab, &[c], 3.0)), ((2.0, 3.0, 4.0), fillet_radii(&bx, &[(a, 2.0), (b, 3.0), (c, 4.0)]))] { let r = sel.unwrap(); - assert_eq!(r.face_count(), 10); + assert_eq!(r.face_count(), 15); assert_eq!(r.unmeshed_faces(), 0); + assert!(r.validity().is_empty(), "{:?}", r.validity()); let k = kink(&r); - assert!(k < 0.05, "kink {k}°"); - let (v, s) = (vol(&r), strips(rs.0, rs.1, rs.2)); - assert!(v < s + 0.05 && v > s - 3.0, "{v} vs {s}"); + assert!(k < 0.01, "kink {k}°"); + let (ra, rb, rc) = rs; + let vs = vertices(&r); + // An edge's setback: where its round's section meets both faces, at two vertices. + let setback = |at: &dyn Fn(f64) -> [Vec3; 2], r: f64| -> Option { + vs.iter() + .flat_map(|p| [p.y, 20.0 - p.x, 20.0 - p.z]) + .find(|d| *d >= 1.5 * r - 1e-9 && *d < 20.0 && at(*d).iter().all(|q| vs.iter().any(|p| p.dist(*q) < 1e-9))) + }; + let da = setback(&|d| [Vec3::new(20.0 - ra, d, 20.0), Vec3::new(20.0, d, 20.0 - ra)], ra); + let db = setback(&|d| [Vec3::new(20.0 - d, 0.0, 20.0 - rb), Vec3::new(20.0 - d, rb, 20.0)], rb); + let dc = setback(&|d| [Vec3::new(20.0 - rc, 0.0, 20.0 - d), Vec3::new(20.0, rc, 20.0 - d)], rc); + eprintln!("{rs:?}: setbacks {da:?} {db:?} {dc:?}"); + let (Some(da), Some(db), Some(dc)) = (da, db, dc) else { panic!("{rs:?}: a round's setback section is missing: {da:?} {db:?} {dc:?}") }; + if ra == rb { + assert!((da - db).abs() < 1e-9, "{da} vs {db}"); + } + let (v, s) = (vol(&r), strips(ra, rb, rc)); + assert!((v - s).abs() < db * da * dc, "{v} vs {s}"); } } #[test] fn corners_refuse_what_they_cannot_build() { - let (bx, a, b, c) = setup(); - // Larger than the faces, or not a size: errors, no panic. Large but fitting is fine. + let (bx, a, b, _) = setup(); + // Not a size: errors, no panic. Large but fitting is fine. assert!(fillet_radii(&bx, &[(a, 15.0), (b, 2.0)]).is_ok_and(|r| r.unmeshed_faces() == 0)); - assert!(fillet_radii(&bx, &[(a, 25.0), (b, 2.0)]).is_err()); + // R25 on a overflows both its faces and goes first: its circle about (x, z) = (-5, -5) + // takes all of the top, and with it b, which is gone. What is left is R25's alone: the + // square [0, 20]² inside that circle, with t = x + 5, ∫₅^√600 √(625 − t²) dt − 5 (√600 − 5), + // along 20. + let g = |t: f64| 0.5 * (t * (625.0 - t * t).sqrt() + 625.0 * (t / 25.0).asin()); + let w = 600f64.sqrt(); + let want = 20.0 * (g(w) - g(5.0) - 5.0 * (w - 5.0)); + let r = fillet_radii(&bx, &[(a, 25.0), (b, 2.0)]).unwrap(); + assert!((vol(&r) - want).abs() < 1e-9 * want, "{} vs {want}", vol(&r)); assert!(fillet_radii(&bx, &[(a, f64::NAN)]).is_err()); assert!(fillet_radii(&bx, &[(a, 0.0)]).is_err()); assert!(fillet_radii(&bx, &[]).is_err()); assert!(fillet_radii(&bx, &[(Vec3::new(500.0, 0.0, 0.0), 1.0)]).is_err()); - // A concave edge is left to the other blends. - let l = crate::ops::boolean(&bx, &box_solid(Vec3::new(10.0, -1.0, 10.0), Vec3::new(21.0, 21.0, 21.0)).unwrap(), crate::BoolOp::Cut) - .unwrap() - .unwrap(); - assert!(fillet_radii(&l, &[(Vec3::new(10.0, 10.0, 10.0), 1.0), (c, 2.0)]).is_err()); } #[test] fn sloped_basin_rim_fillets() { - use solidcraft_geom::{Loop2, Plane, Vec2}; + use solidcore_record::{Loop2, Plane, Vec2}; let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); let pocket = @@ -1493,81 +565,31 @@ mod tests { assert!(result.validity().is_empty()); assert_eq!(result.unmeshed_faces(), 0); assert!(vol(&result) < vol(&basin)); - let mesh = result.tessellate(0.01).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!(mesh.contains(Vec3::new(50.0, 2.0, 27.0))); assert!(!mesh.contains(Vec3::new(50.0, 3.9, 29.99))); // The small blend removes only a strip at the rim, and never escapes // the slab. Topology checks alone do not catch crossed faces. assert!(vol(&basin) - vol(&result) < 2.0_f64.powi(2) * (60.0 + 46.0) * 2.0); - for v in result.solid.vertex_iter() { - let p = vtx(&v); + for p in vertices(&result) { assert!(p.x >= 0.0 && p.x <= 100.0 && p.y >= 0.0 && p.y <= 60.0 && p.z >= 0.0 && p.z <= 30.0 + 1e-8); } } } + /// A chamfer 2 of a basin's rim loop (walls all sloping 10 over 20, the front rim 1 mm wide) + /// whose front leg runs off the rim over the slab's front edge builds, cut by the front face + /// (the owner's ruling of 2026-10-30, d7: a chamfer that reaches or runs past a rim builds). + /// Sliced at depth t below the top, each chamfer's strip beside its wall is + /// w(t) = d (1 − t/δ) wide, δ = d / √(1 + k²) with k = 1/2 the walls' run over drop; the four + /// meet in mitres at the rim's corners, so the section removed is the pocket's rectangle at t, + /// [20 + t/2, 80 − t/2] × [1 + t/2, 50 − t/2], grown by w(t) on every side and clipped to the + /// slab's front face y >= 0, less that rectangle. Its area is quadratic in t between δ and + /// where the front strip's edge 1 + t/2 − w(t) crosses y = 0, so Simpson's rule is exact on + /// each piece: 375.673069 taken from V0 = 140333.333333 (the prismatoid), 139957.660264. #[test] - fn sloped_rim_fillets_cannot_extend_outside_the_material() { - use solidcraft_geom::{Loop2, Plane, Vec2}; - for margin in [0.5, 1.0] { - let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); - let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); - let pocket = crate::loft(&[ - (Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)), - (Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0)), - ]) - .unwrap(); - let basin = crate::boolean(&slab, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); - let picks = [Vec3::new(50.0, margin, 30.0), Vec3::new(80.0, 27.0, 30.0), Vec3::new(50.0, 50.0, 30.0), Vec3::new(20.0, 27.0, 30.0)]; - for count in [1, 2, 4] { - assert!(fillet(&basin, &picks[..count], 4.0).is_err()); - assert!(fillet(&basin, &picks[..count], margin * 0.5).is_ok()); - } - } - } - - #[test] - fn chamfers_meet_on_unequal_sloped_rim_walls() { - use solidcraft_geom::{Loop2, Plane, Vec2}; - for margin in [1.0, 4.0] { - let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); - let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); - let pocket = crate::loft(&[ - (Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)), - (Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0)), - ]) - .unwrap(); - let basin = crate::boolean(&slab, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); - let picks = [Vec3::new(50.0, margin, 30.0), Vec3::new(80.0, 27.0, 30.0), Vec3::new(50.0, 50.0, 30.0), Vec3::new(20.0, 27.0, 30.0)]; - for count in [2, 3, 4] { - if margin == 1.0 { - assert!(crate::chamfer(&basin, &picks[..count], 2.0).is_err()); - assert!(crate::chamfer(&basin, &picks[..count], 1.0).is_err()); - } - let distance = if margin == 1.0 { 0.5 } else { 2.0 }; - let result = crate::chamfer(&basin, &picks[..count], distance).unwrap(); - assert!(result.validity().is_empty()); - assert_eq!(result.unmeshed_faces(), 0); - assert!(vol(&result) < vol(&basin)); - assert!(vol(&basin) - vol(&result) < distance.powi(2) * (60.0 + 50.0 - margin)); - let reverse: Vec<_> = picks[..count].iter().copied().rev().collect(); - let reversed = crate::chamfer(&basin, &reverse, distance).unwrap(); - assert!((vol(&result) - vol(&reversed)).abs() < 1e-6); - // These are exact planes, with every boundary on its owning face. - for f in result.solid.face_iter() { - let Some(n) = plane_normal(f) else { continue }; - let origin = vtx(&f.vertex_iter().next().unwrap()); - for v in f.vertex_iter() { - assert!((vtx(&v) - origin).dot(n).abs() < 1e-7); - } - } - } - } - } - - #[test] - fn equal_slope_rim_loops_cannot_escape_the_face() { - use solidcraft_geom::{Loop2, Plane, Vec2}; + fn a_rim_loop_chamfer_running_off_its_rim_builds() { + use solidcore_record::{Loop2, Plane, Vec2}; let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); let pocket = @@ -1575,9 +597,23 @@ mod tests { .unwrap(); let basin = crate::boolean(&slab, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); let picks = [Vec3::new(50.0, 1.0, 30.0), Vec3::new(80.0, 27.0, 30.0), Vec3::new(50.0, 50.0, 30.0), Vec3::new(20.0, 27.0, 30.0)]; - assert!(crate::chamfer(&basin, &picks, 2.0).is_err()); - assert!(fillet(&basin, &picks, 4.0).is_err()); - assert!(crate::chamfer(&basin, &picks, 0.5).is_ok()); - assert!(fillet(&basin, &picks, 0.5).is_ok()); + let (d, k) = (2.0_f64, 0.5_f64); + let delta = d / (1.0 + k * k).sqrt(); + let area = |t: f64| { + let w = d * (1.0 - t / delta); + let (x0, x1, y0, y1) = (20.0 + k * t, 80.0 - k * t, 1.0 + k * t, 50.0 - k * t); + (x1 - x0 + 2.0 * w) * (y1 + w - (y0 - w).max(0.0)) - (x1 - x0) * (y1 - y0) + }; + // 1 + k t − d (1 − t/δ) = 0. + let crossing = (d - 1.0) / (k + d / delta); + let removed: f64 = + [(0.0, crossing), (crossing, delta)].iter().map(|&(a, b)| (b - a) / 6.0 * (area(a) + 4.0 * area(0.5 * (a + b)) + area(b))).sum(); + assert!((removed - 375.673069).abs() < 1e-6, "{removed}"); + let before = crate::measure(&basin).unwrap().volume; + assert!((before - 140333.333333).abs() < 1e-5, "{before}"); + let result = crate::chamfer(&basin, &picks, d).unwrap_or_else(|e| panic!("{e}")); + assert!(result.validity().is_empty(), "{:?}", result.validity()); + let v = crate::measure(&result).unwrap().volume; + assert!((v - (before - removed)).abs() < 1e-6 * before, "{v} vs {}", before - removed); } } diff --git a/crates/kernel/src/blend_fit.rs b/crates/kernel/src/blend_fit.rs deleted file mode 100644 index 3cb6a4a5d..000000000 --- a/crates/kernel/src/blend_fit.rs +++ /dev/null @@ -1,652 +0,0 @@ -//! Does a fillet or chamfer fit where it is asked for (#1080)? A blend of a straight edge -//! between two planar faces takes away (or, on a concave edge, fills) at most the wedge between -//! the edge and its two setback lines. Any other face of the body inside that wedge means the -//! blend runs past a neighbouring face's boundary into other geometry (a hole, a pocket, an -//! earlier round), and two such wedges overlapping mean two blends cross. Either way the result -//! the operations build is not a blend of those edges, so it is refused with the largest size -//! that does fit. After the build, the volume taken away is checked against the wedges too. - -use solidcraft_geom::Vec3; -use truck_modeling as mt; - -use crate::blend::{ChamferSide, plane_normal, vtx}; -use crate::body::Body; -use crate::{KernelError, Result}; - -/// What is asked for on every edge. -#[derive(Clone, Copy, Debug)] -pub(crate) enum Size { - /// A round of this radius. - Round(f64), - /// An equal-distance chamfer. - Chamfer(f64), - /// A chamfer with a second distance or an angle (see [`crate::chamfer_sides`]). - Sides(f64, ChamferSide, bool), -} - -impl Size { - fn scaled(self, k: f64) -> Size { - match self { - Size::Round(r) => Size::Round(r * k), - Size::Chamfer(s) => Size::Chamfer(s * k), - Size::Sides(d, ChamferSide::Distance(d2), f) => Size::Sides(d * k, ChamferSide::Distance(d2 * k), f), - Size::Sides(d, a, f) => Size::Sides(d * k, a, f), - } - } - - fn value(self) -> f64 { - match self { - Size::Round(v) | Size::Chamfer(v) | Size::Sides(v, _, _) => v, - } - } - - fn what(self) -> &'static str { - match self { - Size::Round(_) => "fillet", - _ => "chamfer", - } - } -} - -/// A straight edge between two planar faces: its ends, the unit directions into each face -/// (perpendicular to the edge) and the faces' outward normals. -struct Frame { - p0: Vec3, - p1: Vec3, - /// Into face a and face b, from the edge. - ta: Vec3, - tb: Vec3, - na: Vec3, - nb: Vec3, - /// The faces (indices in the body's face order) the blend may meet: the two beside the - /// edge and every face at its ends. - allowed: Vec, - ends: [mt::VertexID; 2], - /// Another edge of the two faces runs on from an end tangentially: the blend runs on along - /// that chain past this edge. - chained: bool, -} - -/// One edge's region: the triangle edge, setback on face a, setback on face b, swept along the -/// edge, as half-spaces `n·x <= c` and as its five boundary polygons. -struct Wedge { - planes: [(Vec3, f64); 5], - faces: Vec>, - /// Cross-section area times length: the most a blend of the edge takes away or fills. - volume: f64, -} - -impl Frame { - /// The setbacks along face a and face b for `size`; `None` where the faces are (nearly) - /// tangent or the size doesn't make a blend. - fn setbacks(&self, size: Size) -> Option<(f64, f64)> { - let cos = self.ta.dot(self.tb).clamp(-1.0, 1.0); - let phi = cos.acos(); - if !(1e-3..std::f64::consts::PI - 1e-3).contains(&phi) { - return None; - } - match size { - // The round touches each face at r / tan(φ/2) from the edge. - Size::Round(r) => { - let t = r / (phi * 0.5).tan(); - Some((t, t)) - } - Size::Chamfer(s) => Some((s, s)), - Size::Sides(d1, side, flip) => { - // As `chamfer_tool_sides`: side 1 is the face facing up most, unless flipped. - let up = Vec3::new(1e-6, 1e-3, 1.0); - let a_is_first = (self.na.dot(up) >= self.nb.dot(up)) != flip; - let d2 = match side { - ChamferSide::Distance(d) => d, - ChamferSide::Angle(a) => { - let den = (phi + a).sin(); - if den <= 1e-9 { - return None; - } - d1 * a.sin() / den - } - }; - Some(if a_is_first { (d1, d2) } else { (d2, d1) }) - } - } - } - - fn wedge(&self, size: Size) -> Option { - let (sa, sb) = self.setbacks(size)?; - if !(sa.is_finite() && sb.is_finite() && sa > 0.0 && sb > 0.0) { - return None; - } - self.prism(self.ta * sa, self.tb * sb) - } - - /// For a round, the arc of its cross-section from the setback on face a to the one on face - /// b, in [`ARC_PIECES`] pieces, as offsets from the edge; `None` for a chamfer. - fn arc(&self, size: Size) -> Option> { - let Size::Round(r) = size else { return None }; - let (sa, sb) = self.setbacks(size)?; - let half = 0.5 * self.ta.dot(self.tb).clamp(-1.0, 1.0).acos(); - // The ball's centre, on the bisector, `r` from both faces. - let centre = (self.ta + self.tb).normalized()? * (r / half.sin()); - let (a, b) = (self.ta * sa - centre, self.tb * sb - centre); - (0..=ARC_PIECES).map(|k| Some(centre + (a + (b - a) * (k as f64 / ARC_PIECES as f64)).normalized()? * r)).collect() - } - - /// What a blend of the edge at `size` changes, within the wedge: for a round, the fan of - /// prisms from the edge to the pieces of its arc (between the edge and the arc lies all it - /// takes away or fills; the ball's side of the arc is left as it is), for a chamfer the - /// wedge itself. - fn pieces(&self, size: Size) -> Option> { - match self.arc(size) { - Some(arc) => arc.windows(2).map(|w| self.prism(*w.first()?, *w.get(1)?)).collect(), - None => Some(vec![self.wedge(size)?]), - } - } - - /// The blend's own surface at `size`, as polygons: the strips between its arc's pieces, or - /// the chamfer's face. - fn surface(&self, size: Size) -> Option>> { - match self.arc(size) { - Some(arc) => arc - .windows(2) - .map(|w| { - let (u, v) = (*w.first()?, *w.get(1)?); - Some(vec![self.p0 + u, self.p0 + v, self.p1 + v, self.p1 + u]) - }) - .collect(), - None => Some(vec![self.wedge(size)?.faces.get(2)?.clone()]), - } - } - - /// The triangle between the edge and the offsets `u` and `w` across it, swept along the edge. - fn prism(&self, u: Vec3, w: Vec3) -> Option { - let d = (self.p1 - self.p0).normalized()?; - let (a0, b0) = (self.p0 + u, self.p0 + w); - let (a1, b1) = (self.p1 + u, self.p1 + w); - // Each side's plane, facing away from the triangle's third corner. - let side = |p: Vec3, q: Vec3, opposite: Vec3| -> Option<(Vec3, f64)> { - let mut n = d.cross(q - p).normalized()?; - if n.dot(opposite - p) > 0.0 { - n = -n; - } - Some((n, n.dot(p))) - }; - let planes = [side(self.p0, a0, b0)?, side(self.p0, b0, a0)?, side(a0, b0, self.p0)?, (-d, -d.dot(self.p0)), (d, d.dot(self.p1))]; - let faces = - vec![vec![self.p0, a0, a1, self.p1], vec![self.p0, b0, b1, self.p1], vec![a0, b0, b1, a1], vec![self.p0, a0, b0], vec![self.p1, a1, b1]]; - let area = 0.5 * u.cross(w).len(); - Some(Wedge { planes, faces, volume: area * self.p0.dist(self.p1) }) - } -} - -/// Pieces a round's arc is divided into for [`Frame::pieces`] and [`Frame::surface`]: each -/// chord sags under 0.5 % of the radius. -const ARC_PIECES: usize = 8; - -/// `poly` clipped to the half-spaces `n·x <= c`, each moved `eps` inwards (empty when nothing -/// is left). -fn clip(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> Vec { - let mut cur: Vec = poly.to_vec(); - for (n, c) in planes { - let c = c - eps; - let mut next = Vec::with_capacity(cur.len() + 2); - for (i, p) in cur.iter().enumerate() { - let Some(q) = cur.get((i + 1) % cur.len()) else { continue }; - let (dp, dq) = (n.dot(*p) - c, n.dot(*q) - c); - if dp <= 0.0 { - next.push(*p); - } - if (dp < 0.0 && dq > 0.0) || (dp > 0.0 && dq < 0.0) { - next.push(*p + (*q - *p) * (dp / (dp - dq))); - } - } - if next.is_empty() { - return next; - } - cur = next; - } - cur -} - -/// `poly` clipped to the half-spaces, each moved `eps` inwards: is anything left? -fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool { - !clip(poly, planes, eps).is_empty() -} - -/// Most polygons [`reaches_inside_beyond`] clips before it gives up and answers yes. -const MAX_CLIPS: usize = 4096; - -/// Whether the part of `poly` outside every one of the wedges `trimmed` (by more than `out`) -/// reaches inside `planes` (by `eps`). A face beside or at the end of another edge the same -/// feature blends is trimmed back to that blend, so its part inside that edge's wedge is gone -/// (#1668). -fn reaches_inside_beyond(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64, trimmed: &[&Wedge], out: f64) -> bool { - let mut parts = vec![poly.to_vec()]; - for w in trimmed { - // Outside a convex wedge is outside one of its planes (pieces may overlap: only - // whether anything is left counts). - let mut next = Vec::new(); - for part in &parts { - for (n, c) in &w.planes { - let piece = clip(part, &[(-*n, -*c)], out); - if !piece.is_empty() { - next.push(piece); - } - } - if next.len() > MAX_CLIPS { - return true; - } - } - parts = next; - } - parts.iter().any(|p| reaches_inside(p, planes, eps)) -} - -/// Whether two sets of convex prisms overlap (by more than `eps`): a face of one reaches -/// inside the other. -fn overlap(a: &[Wedge], b: &[Wedge], eps: f64) -> bool { - a.iter().any(|x| { - b.iter().any(|y| y.faces.iter().any(|p| reaches_inside(p, &x.planes, eps)) || x.faces.iter().any(|p| reaches_inside(p, &y.planes, eps))) - }) -} - -/// The body's straight edges between planar faces nearest the points (each once; `None` for a -/// point whose edge is something else, which the check leaves alone). -struct Selection { - frames: Vec>, - /// The body's triangles, with their face and whether that face is planar. - tris: Vec<([Vec3; 3], usize)>, - planar: Vec, - size: f64, - chord: f64, - /// The body's volume and area from that mesh. - coarse: (f64, f64), -} - -fn select(body: &Body, pts: &[Vec3]) -> Result { - // As the blends take it: coplanar neighbours as one face, collinear pieces as one edge. - let healed = crate::boolean_record::healed(body)?; - crate::guard("blend fit", || select_in(&healed, pts)) -} - -fn select_in(body: &Body, pts: &[Vec3]) -> Result { - let size = body.size(); - let chord = (size * 1e-3).max(1e-4); - let mesh = body.tessellate(chord)?; - let solid = &*body.solid; - let faces: Vec<&mt::Face> = solid.face_iter().collect(); - let planar: Vec = faces.iter().map(|f| plane_normal(f).is_some()).collect(); - let all = Body::unique_edges(solid); - let mut taken: Vec = Vec::new(); - let mut frames = Vec::new(); - for p in pts { - // The edge nearest the point, as the blends pick it. - let best = mesh - .edges - .iter() - .enumerate() - .map(|(i, poly)| (i, poly.windows(2).filter_map(|w| Some(p.dist_to_segment(*w.first()?, *w.get(1)?))).fold(f64::INFINITY, f64::min))) - .min_by(|a, b| a.1.total_cmp(&b.1)); - // Points on the same edge (pieces healed into one) count once. - let frame = match best.and_then(|(i, dist)| all.get(i).filter(|_| dist <= size * 0.05 + 1e-3)) { - Some(e) if taken.contains(&e.id()) => continue, - Some(e) => { - taken.push(e.id()); - frame(&faces, e) - } - None => None, - }; - frames.push(frame); - } - let m = mesh.measure(); - let coarse = (m.volume, m.area); - let tris = mesh.triangles.iter().zip(&mesh.tri_face).filter_map(|(t, f)| Some((mesh.tri(t)?, *f as usize))).collect(); - Ok(Selection { frames, tris, planar, size, chord, coarse }) -} - -fn frame(faces: &[&mt::Face], e: &mt::Edge) -> Option { - if !matches!(e.curve(), mt::Curve::Line(_)) { - return None; - } - let id = e.id(); - let ends = [e.front().id(), e.back().id()]; - let (p0, p1) = (vtx(e.absolute_front()), vtx(e.absolute_back())); - let d = (p1 - p0).normalized()?; - // Each face along the edge: its outward normal and the direction into it (its boundary runs - // counter-clockwise about the normal, so the face lies to the left of the edge's use). - let mut beside = Vec::new(); - let mut allowed = Vec::new(); - let mut chained = false; - for (i, f) in faces.iter().enumerate() { - let mut uses: Vec = f.boundaries().iter().flat_map(|w| w.edge_iter()).filter(|x| x.id() == id).cloned().collect(); - let at_end = f.boundaries().iter().flat_map(|w| w.edge_iter()).any(|x| ends.contains(&x.front().id()) || ends.contains(&x.back().id())); - if at_end { - allowed.push(i); - } - if uses.is_empty() { - continue; - } - let n = plane_normal(f)?; - let u = uses.pop()?; - if !uses.is_empty() { - return None; - } - let dir = (vtx(u.back()) - vtx(u.front())).normalized()?; - beside.push((n, n.cross(dir).normalized()?)); - chained |= f.boundaries().iter().flat_map(|w| w.edge_iter()).filter(|x| x.id() != id).any(|x| { - ends.iter().any(|v| *v == x.front().id() && tangent_at(x, false).is_some_and(|t| t.dot(d).abs() > 1.0 - 1e-6)) - || ends.iter().any(|v| *v == x.back().id() && tangent_at(x, true).is_some_and(|t| t.dot(d).abs() > 1.0 - 1e-6)) - }); - } - let [(na, ta), (nb, tb)] = beside[..] else { return None }; - // Both directions perpendicular to the edge, within their faces. - if ta.dot(d).abs() > 1e-6 || tb.dot(d).abs() > 1e-6 { - return None; - } - Some(Frame { p0, p1, ta, tb, na, nb, allowed, ends, chained }) -} - -/// The unit tangent of an edge (as used) at its start or end. -fn tangent_at(e: &mt::Edge, at_end: bool) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let d = c.der(if at_end { t1 } else { t0 }); - Vec3::new(d.x, d.y, d.z).normalized() -} - -/// What a blend that doesn't fit runs into. -enum Clash { - Face, - Blend, -} - -/// What a blend at `size` runs into first, if anything. Curved faces are meshed to within the -/// chord: they count when their mesh reaches into a wedge by more than twice the chord, or, when -/// `strict`, when it comes within the chord of one (the surface may then be inside it). -fn first_clash(sel: &Selection, size: Size, strict: bool) -> Option { - let wedges: Vec> = sel.frames.iter().map(|f| f.as_ref().and_then(|f| f.wedge(size))).collect(); - // What each blend changes: for a round only the fan between its edge and its arc, a part of - // the wedge. A face inside the wedge but beyond the arc (the inside round of a wall, when the - // outside one is a concentric round) is on the ball's side, left as it is. - let changes: Vec>> = sel.frames.iter().map(|f| f.as_ref().and_then(|f| f.pieces(size))).collect(); - // Planar faces are exact in the mesh; curved ones are within the chord. - let flat = (sel.size * 1e-7).max(1e-9); - let curved = if strict { -sel.chord } else { sel.chord * 2.0 }; - // Planar faces beside an edge lie in its wedge's side planes: outside it means further. - let out = (sel.size * 1e-6).max(1e-8); - for (i, ((f, w), changed)) in sel.frames.iter().zip(&wedges).zip(&changes).enumerate() { - let (Some(f), Some(w)) = (f, w) else { continue }; - // Without its pieces (or for a chamfer, whose one piece is the wedge) the wedge counts. - let changed = changed.as_deref().unwrap_or_default(); - let hit = sel.tris.iter().filter(|(_, face)| !f.allowed.contains(face)).any(|(t, face)| { - let eps = if sel.planar.get(*face).copied().unwrap_or(false) { flat } else { curved }; - // The other blended edges this face runs along or ends them trim it back. - let trimmed: Vec<&Wedge> = sel - .frames - .iter() - .zip(&wedges) - .enumerate() - .filter(|(j, (fj, _))| *j != i && fj.as_ref().is_some_and(|fj| fj.allowed.contains(face))) - .filter_map(|(_, (_, wj))| wj.as_ref()) - .collect(); - // The pieces near the arc's ends are thin: a curved face only goes clear of them - // when its mesh stays a chord outside, or a sliver into the round is missed (#324). - let fan = if sel.planar.get(*face).copied().unwrap_or(false) { flat } else { -sel.chord }; - reaches_inside_beyond(t, &w.planes, eps, &trimmed, out) - && (changed.len() <= 1 || changed.iter().any(|p| reaches_inside_beyond(t, &p.planes, fan, &trimmed, out))) - }); - if hit { - return Some(Clash::Face); - } - } - // Two blends whose edges don't meet must not overlap (those meeting at a vertex mitre). - let eps = (sel.size * 1e-7).max(1e-9); - for (i, (fi, wi)) in sel.frames.iter().zip(&wedges).enumerate() { - let (Some(fi), Some(wi)) = (fi, wi) else { continue }; - for (fj, wj) in sel.frames.iter().zip(&wedges).skip(i + 1) { - let (Some(fj), Some(wj)) = (fj, wj) else { continue }; - if fi.ends.iter().any(|v| fj.ends.contains(v)) { - continue; - } - let meet = wj.faces.iter().any(|p| reaches_inside(p, &wi.planes, eps)) || wi.faces.iter().any(|p| reaches_inside(p, &wj.planes, eps)); - if meet && blends_cross(fi, wi, fj, wj, size, eps) { - return Some(Clash::Blend); - } - } - } - None -} - -/// Two blends whose wedges overlap: do they cross? Rounds on both sides of a wall (the outside -/// round's wedge reaches past the inside corner, which the inside round fills) need not: they -/// cross only where what one changes (between its edge and its arc) overlaps what the other -/// does, or where either's surface runs into the other's wedge (#1668). -fn blends_cross(fi: &Frame, wi: &Wedge, fj: &Frame, wj: &Wedge, size: Size, eps: f64) -> bool { - let (Some(pi), Some(pj), Some(si), Some(sj)) = (fi.pieces(size), fj.pieces(size), fi.surface(size), fj.surface(size)) else { return true }; - overlap(&pi, &pj, eps) || sj.iter().any(|p| reaches_inside(p, &wi.planes, eps)) || si.iter().any(|p| reaches_inside(p, &wj.planes, eps)) -} - -/// The step the largest fitting size is given to: three significant digits. -fn step(v: f64) -> f64 { - 10f64.powf(v.log10().floor() - 3.0) -} - -/// Why a blend of `edges` at `size` doesn't fit `body` and the largest size that does (to -/// three significant digits; `None` when not even the smallest step fits), or `None` when it -/// fits or the check can't tell (edges other than straight ones between planar faces). -fn misfit(body: &Body, edges: &[Vec3], size: Size) -> Result)>> { - if body.is_mesh() || edges.is_empty() || !size.value().is_finite() || size.value() <= 0.0 { - return Ok(None); - } - misfit_in(&select(body, edges)?, size) -} - -/// [`misfit`] on the selection. -fn misfit_in(sel: &Selection, size: Size) -> Result)>> { - if sel.frames.iter().all(Option::is_none) || !size.value().is_finite() || size.value() <= 0.0 { - return Ok(None); - } - let Some(clash) = first_clash(sel, size, false) else { return Ok(None) }; - // Bisection on the size's steps: `hi` doesn't fit, `lo` does (or is 0). Strictly: a size - // offered as fitting must fit, though a curved face that only touches the wedge at it would - // not be refused (a hole whose rim the round's band just reaches, #324). - let asked = size.value(); - let q = step(asked); - let (mut lo, mut hi) = (0u64, (asked / q).ceil() as u64); - for _ in 0..20 { - if hi.saturating_sub(lo) <= 1 { - break; - } - let mid = lo + (hi - lo) / 2; - if first_clash(sel, size.scaled(mid as f64 * q / asked), true).is_none() { - lo = mid; - } else { - hi = mid; - } - } - Ok(Some((clash, (lo > 0).then_some(lo as f64 * q)))) -} - -/// "; the largest radius that fits is 5 mm", or nothing. -fn fits_note(size: Size, largest: Option) -> String { - let unit = if matches!(size, Size::Round(_)) { "radius" } else { "size" }; - largest.map(|v| format!("; the largest {unit} that fits is {} mm", show(v))).unwrap_or_default() -} - -/// Refuse a blend of `edges` at `size` that runs into other faces of `body` or into another of -/// the blends, with [`KernelError::TooLarge`] naming the largest size that fits. -pub(crate) fn check(body: &Body, edges: &[Vec3], size: Size) -> Result<()> { - if body.is_mesh() || edges.is_empty() { - return Ok(()); - } - check_in(&select(body, edges)?, size) -} - -/// [`check`] on the selection. -fn check_in(sel: &Selection, size: Size) -> Result<()> { - let Some((clash, largest)) = misfit_in(sel, size)? else { return Ok(()) }; - let what = size.what(); - let into = match clash { - Clash::Face => "it runs past the faces beside the edge into other geometry".to_string(), - Clash::Blend => format!("the {what}s on these edges would cross each other"), - }; - Err(KernelError::TooLarge(format!("{} mm is too large for this {what}: {into}{}", show(size.value()), fits_note(size, largest)))) -} - -/// A blend's refusal `e`, with the largest size that fits added when the size is why. -pub(crate) fn explain(body: &Body, edges: &[Vec3], size: Size, e: KernelError) -> KernelError { - let note = match misfit(body, edges, size) { - Ok(Some((_, largest @ Some(_)))) => fits_note(size, largest), - _ => return e, - }; - match e { - KernelError::TooLarge(m) => KernelError::TooLarge(format!("{m}{note}")), - KernelError::Failed(m) => KernelError::Failed(format!("{m}{note}")), - other => other, - } -} - -/// A blend of `edges` at `size` that turned `input` into `out`, if it fits ([`check`]) and -/// changes no more than it can ([`check_volume`]). -pub(crate) fn accept(input: &Body, out: Body, edges: &[Vec3], size: Size) -> Result { - if input.is_mesh() || out.is_mesh() || edges.is_empty() { - return Ok(out); - } - let sel = select(input, edges)?; - check_in(&sel, size)?; - let out = volume_in(&sel, input, out, size)?; - right_way(input, out, edges, size) -} - -/// Whether the edge of `body` nearest `p` is convex (`Some(true)`: a chamfer takes material -/// away) or concave (`Some(false)`: it fills), from the two faces' outward normals and the -/// directions into each face across the edge at `p`. `None` unless that is clear-cut: faces -/// meeting at a few degrees of tangent or of a knife edge, an edge not between two faces. -fn convex_at(body: &Body, p: Vec3) -> Option { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - let tol = (body.size() * 1e-4).max(1e-4); - let (i, _) = body.nearest_edge(p, tol).ok()??; - let edge = Body::unique_edges(&body.solid).into_iter().nth(i)?; - let mut sides = Vec::new(); - for f in body.solid.face_iter() { - for e in f.boundary_iters().into_iter().flatten().filter(|e| e.id() == edge.id()) { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let t = c.search_nearest_parameter(crate::body::p3(p), None, 100)?.clamp(t0.min(t1), t0.max(t1)); - let d = c.der(t); - let dir = Vec3::new(d.x, d.y, d.z).normalized()?; - let (_, n, _) = crate::curveblend::project(f, p, None)?; - // A face's boundary runs counter-clockwise about its outward normal: its inside is - // to the left of the edge. - sides.push((n, n.cross(dir).normalized()?)); - } - } - let [(n1, t1), (n2, t2)] = sides[..] else { return None }; - // About 3°: the faces neither nearly tangent nor folded onto each other. - const CLEAR: f64 = 0.05; - if t1.dot(t2) > 1.0 - CLEAR || t1.dot(t2) < -1.0 + CLEAR { - return None; - } - let (a, b) = (n1.dot(t2), n2.dot(t1)); - if a < -CLEAR && b < -CLEAR { - Some(true) - } else if a > CLEAR && b > CLEAR { - Some(false) - } else { - None - } -} - -/// A chamfer of convex edges takes material away and one of concave edges fills it: a result -/// that went the other way (a chamfer on a curved edge running off a face it skims, which the -/// wedges can't bound) is refused rather than kept. Rounds are left to the wedges: a round -/// rolled along a smooth chain may run on round convex and concave stretches alike. -fn right_way(input: &Body, out: Body, edges: &[Vec3], size: Size) -> Result { - if matches!(size, Size::Round(_)) { - return Ok(out); - } - let ways: Option> = edges.iter().map(|p| convex_at(input, *p)).collect(); - let Some(ways) = ways else { return Ok(out) }; - let (convex, concave) = (ways.iter().all(|w| *w), ways.iter().all(|w| !*w)); - if !(convex || concave) { - return Ok(out); - } - let (Ok(a), Ok(b)) = (crate::measure(input), crate::measure(&out)) else { return Ok(out) }; - let slack = a.volume.abs() * 1e-5 + 1e-6; - let grew = b.volume - a.volume; - if (convex && grew > slack) || (concave && grew < -slack) { - return Err(KernelError::TooLarge(format!( - "{} mm is too large for this {}: on {} edge it would {} the part by {} mm³ instead (it runs off a face next to the edge)", - show(size.value()), - size.what(), - if convex { "a convex" } else { "a concave" }, - if convex { "grow" } else { "shrink" }, - // A fraction of a mm³ is typical here: to the hundredth. - show((grew.abs() * 100.0).round() / 100.0) - ))); - } - Ok(out) -} - -/// After a blend of `edges` at `size` turned `input` into `out`: refused when the volume taken -/// away (or added) is more than the blends' wedges hold, which only a result that ran into -/// other geometry does (#871's shelled box lost 240 mm³ more than any round could take). -#[cfg(test)] -pub(crate) fn check_volume(input: &Body, out: Body, edges: &[Vec3], size: Size) -> Result { - if input.is_mesh() || out.is_mesh() || edges.is_empty() { - return Ok(out); - } - let Ok(sel) = select(input, edges) else { return Ok(out) }; - volume_in(&sel, input, out, size) -} - -/// [`check_volume`] on the selection. -fn volume_in(sel: &Selection, input: &Body, out: Body, size: Size) -> Result { - if sel.frames.is_empty() { - return Ok(out); - } - let mut bound = 0.0; - for f in &sel.frames { - // An edge the wedges can't describe: no bound. - let Some(w) = f.as_ref().and_then(|f| f.wedge(size)) else { return Ok(out) }; - let Some(f) = f.as_ref().filter(|f| !f.chained) else { return Ok(out) }; - // Past an edge's ends a chamfer may still cut under a sloping end face. - let (sa, sb) = f.setbacks(size).unwrap_or((0.0, 0.0)); - let len = f.p0.dist(f.p1); - bound += w.volume * (len + 2.0 * sa.max(sb)) / len.max(1e-12); - } - // Well within the bound on the meshes the check made anyway: accepted. Otherwise measured - // finely, as a coarse mesh of a cone or a blend is off by more than a small blend. - if let Ok(m) = out.tessellate(sel.chord).map(|m| m.measure()) { - let (va, aa) = sel.coarse; - // A chord's sag over every face bounds what the meshes miss. - let slack = (aa + m.area) * sel.chord; - if (va - m.volume).abs() + slack <= bound * 1.02 { - return Ok(out); - } - } - let (Ok(ma), Ok(mb)) = (crate::measure(input), crate::measure(&out)) else { return Ok(out) }; - let slack = ma.volume.abs() * 1e-4 + (ma.area + mb.area) * sel.size * 1e-5; - let changed = (ma.volume - mb.volume).abs(); - if changed > bound * 1.02 + slack { - return Err(KernelError::TooLarge(format!( - "{} mm is too large for this {}: the result changes {} mm³ of the part, more than the {} can (at most {} mm³)", - show(size.value()), - size.what(), - show_rounded(changed), - size.what(), - show_rounded(bound) - ))); - } - Ok(out) -} - -/// A length in mm, without trailing zeros. -fn show(v: f64) -> String { - let s = format!("{v:.4}"); - s.trim_end_matches('0').trim_end_matches('.').to_string() -} - -fn show_rounded(v: f64) -> String { - format!("{v:.0}") -} diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs new file mode 100644 index 000000000..bbfbe8a5a --- /dev/null +++ b/crates/kernel/src/blend_smlib.rs @@ -0,0 +1,811 @@ +//! Fillets and chamfers through SMLib. +//! +//! Each kernel entry point ([`crate::fillet`], [`crate::chamfer`], …) hands its arguments here +//! unchanged: the body goes into SMLib as its schema 4 record (healed where SMLib's check refuses +//! it as given), tagged as operand 0; each point picks the body's nearest edge in its own edge +//! order, and SMLib is given that edge's midpoint, which no other edge is as near to (a point at +//! a vertex between two edges would leave SMLib to choose); SMLib blends exactly those edges and +//! the corners where they meet (a pick's tangent chain is the caller's to ask for, +//! [`crate::tangent_chain`]), its check must pass, and the result comes +//! back decoded with its geometry checked. An option SMLib has no construction for is refused as +//! "not supported yet". +//! +//! The history is SMLib's tags, renumbered into the body's orders; a blend face, which SMLib +//! leaves untagged, comes from the edge it replaces ([`solidcraft_smlib::history::blends`]). + +use solidcore_record::Vec3; + +use crate::blend_variable::RadiusSpline; +use crate::body::Body; +use crate::{FilletTurn, KernelError, Result}; + +/// What SMLib cannot build yet. +pub(crate) fn unsupported(what: &str) -> KernelError { + KernelError::Invalid(format!("not supported yet: {what} with the SMLib kernel")) +} + +/// A constant-radius round of the edges nearest `edges` ([`crate::fillet`]). +/// The rounds turn at side edges as `turn` says. +pub(crate) fn fillet(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result { + imp::blend(body, "fillet", Kind::Round(turn), edges, &vec![radius; edges.len()]) +} + +/// [`fillet`], with the picks whose edges a larger, overflowing round removed whole. +pub(crate) fn fillet_removing(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<(Body, Vec)> { + let (b, dropped) = imp::blend_dropping(body, "fillet", Kind::Round(turn), edges, &vec![radius; edges.len()])?; + Ok((b, edges.iter().zip(dropped).filter(|(_, d)| *d).map(|(p, _)| *p).collect())) +} + +/// Each edge rounded at its own radius ([`crate::fillet_each`]), turning at side edges as `turn` +/// says. +pub(crate) fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64], turn: FilletTurn) -> Result { + if radii.len() != edges.len() { + return Err(KernelError::Invalid("one radius per edge".into())); + } + imp::blend(body, "fillet", Kind::Round(turn), edges, radii) +} + +/// A constant-radius round whose corners at `setbacks` (a point at each corner's vertex, and the +/// distance its patch starts along each edge there) are set back ([`crate::fillet_setback`]). +pub(crate) fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { + imp::blend_setback(body, edges, &vec![radius; edges.len()], setbacks) +} + +/// A set-back blend whose corners SMLib leaves open ([`fillet_setback_open`]): the sheet, its +/// history over the body it was made from, and per corner the edges round its hole in order, +/// each its index in the sheet's edge order with whether the face beside it runs it forwards +/// (counter-clockwise about the solid's outward normal). +pub(crate) struct OpenCorners { + pub(crate) sheet: Body, + pub(crate) holes: Vec>, +} + +/// [`fillet_setback`] with each set-back corner left open: SMLib builds the rounds up to the +/// corners' setback sections and the curves on the faces between them, and leaves out the patch +/// that would fill each corner, for the caller to fill. +/// `curvature`: the rounds' sections are curvature-continuous ([`fillet_g2`]), else circular. +pub(crate) fn fillet_setback_open(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)], curvature: bool) -> Result { + let kind = if curvature { Kind::Curvature } else { Kind::Round(FilletTurn::Mitre) }; + imp::blend_setback_open(body, kind, edges, &vec![radius; edges.len()], setbacks) +} + +/// Curvature-continuous rounds with the setback of a round of `radius` ([`crate::fillet_g2`]). +pub(crate) fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result { + imp::blend(body, "G2 fillet", Kind::Curvature, edges, &vec![radius; edges.len()]) +} + +/// Rounds `chord` wide from contact to contact ([`crate::fillet_chord`]). +pub(crate) fn fillet_chord(body: &Body, edges: &[Vec3], chord: f64) -> Result { + imp::blend(body, "chord fillet", Kind::Chord, edges, &vec![chord; edges.len()]) +} + +/// An equal-distance chamfer ([`crate::chamfer`]). +pub(crate) fn chamfer(body: &Body, edges: &[Vec3], distance: f64) -> Result { + imp::blend(body, "chamfer", Kind::Chamfer, edges, &vec![distance; edges.len()]) +} + +/// A chamfer `d1` back along the face facing up most (down most with `flip`), the other side by +/// `side` ([`crate::chamfer_sides`]). +pub(crate) fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: crate::ChamferSide, flip: bool) -> Result { + imp::sides(body, edges, d1, side, flip) +} + +/// One edge rounded with the radius `spline` (checked by the caller) along it from the end +/// nearest `start` ([`crate::fillet_variable_spline`]). +pub(crate) fn fillet_variable(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result { + imp::variable(body, edge_at, start, spline) +} + +/// The edges `picks` select, in the body's edge order, as a blend resolves them, and per edge +/// whether a pick passes it over (a seam or a smooth join: never a blend's edge), for a caller +/// that selects edges to blend ([`crate::tangent_chain`]). +pub(crate) fn picked_edges(body: &Body, picks: &[Vec3]) -> Result<(Vec, Vec)> { + let picked = imp::resolve(body, picks)?; + Ok((picked.edges, picked.hidden)) +} + +#[derive(Clone, Copy)] +enum Kind { + /// Constant-radius rounds, turning at side edges as the [`FilletTurn`] says. + Round(FilletTurn), + Curvature, + Chord, + Chamfer, +} + +mod imp { + use solidcraft_geom::prelude::*; + use std::collections::BTreeSet; + + use solidcore_record::Vec3; + use solidcraft_smlib::{Blend, Brep, ChamferSecond, CheckLevel, Error as SmError, Turn}; + + use super::Kind; + use crate::blend_variable::RadiusSpline; + use crate::body::Body; + use crate::history::{BodyHistory, Change, EdgeOrigin, FaceOrigin, History}; + use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; + use crate::{KernelError, Result, guard, record}; + + fn failed(what: &str, step: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {what}: {step}"), e) + } + + /// How far a pick may lie from its edge. + fn pick_tolerance(body: &Body) -> f64 { + body.size() * 0.05 + 1e-3 + } + + /// The edges `picks` select: each one's index in the body's edge order and the point halfway + /// along it, for SMLib to pick. A pick as near to a smooth join (a seam where a face meets + /// itself, or faces meeting tangentially: never a blend's edge) as to a sharp edge, such as + /// one at the vertex where a cylinder's seam meets its rim, takes the sharp edge. + pub(super) fn resolve(body: &Body, picks: &[Vec3]) -> Result { + if picks.iter().any(|p| !p.is_finite()) { + return Err(KernelError::Invalid("edge picks must be finite points".into())); + } + let chord = (body.size() * 2e-3).max(1e-3); + let mesh = body.mesh(&crate::MeshTolerance::chord(chord))?; + let seams = crate::topo::seam_flags(body, &mesh); + let (smooth, _) = crate::smooth_edges::flags(body, &mesh); + let hidden: Vec = + (0..mesh.edges.len()).map(|i| seams.get(i).copied().unwrap_or(false) || smooth.get(i).copied().unwrap_or(false)).collect(); + let reach = pick_tolerance(body); + let tie = (body.size() * 1e-6).max(1e-6); + let mut out = Picked { edges: Vec::with_capacity(picks.len()), points: Vec::with_capacity(picks.len()), hidden: Vec::new() }; + for p in picks { + // A polyline is up to `chord` off its edge, which may be more than the edges are + // apart: those that close are measured on their curves. + let polyline = |line: &[Vec3]| { + line.windows(2).filter_map(|w| if let [a, b] = w { Some(p.dist_to_segment(*a, *b)) } else { None }).fold(f64::INFINITY, f64::min) + }; + let near: Vec = mesh.edges.iter().map(|line| polyline(line)).collect(); + let nearest = near.iter().copied().fold(f64::INFINITY, f64::min); + // The nearest edge, and the nearest that is no seam. + let (mut any, mut edge): (Option<(f64, usize)>, Option<(f64, usize)>) = (None, None); + for (i, d) in near.iter().copied().enumerate() { + let d = if d <= nearest + 2.0 * chord { exact_distance(body, i, *p).unwrap_or(d) } else { d }; + let seam = hidden.get(i).copied().unwrap_or(false); + for (slot, take) in [(&mut any, true), (&mut edge, !seam)] { + if take && slot.is_none_or(|(bd, _)| d < bd) { + *slot = Some((d, i)); + } + } + } + let chosen = match (any, edge) { + (Some((d, _)), Some(e)) if e.0 <= d + tie => Some(e), + (a, _) => a, + }; + let Some((_, i)) = chosen.filter(|(d, _)| *d <= reach) else { + return Err(KernelError::Invalid(format!("no edge near the pick at ({:.3}, {:.3}, {:.3})", p.x, p.y, p.z))); + }; + let (mid, _) = crate::body::polyline_mid(mesh.edges.get(i).map(Vec::as_slice).unwrap_or(&[])); + out.edges.push(i); + out.points.push([mid.x, mid.y, mid.z]); + } + out.hidden = hidden; + Ok(out) + } + + /// How far `p` is from edge `i` itself, sampled along its curve; `None` for an edge with no + /// curve to sample. + fn exact_distance(body: &Body, i: usize, p: Vec3) -> Option { + const SAMPLES: usize = 512; + let record = body.record(); + let e = record.edges.get(i)?; + let eval = solidcraft_geom::brep::eval::CurveEval::new(e.nurbs.as_ref().unwrap_or(&e.curve)).ok()?; + let [t0, t1] = e.interval; + let at = |k: usize| eval.point(t0 + (t1 - t0) * k as f64 / SAMPLES as f64); + let mut best = f64::INFINITY; + let mut last = at(0)?; + for k in 1..=SAMPLES { + let next = at(k)?; + best = best.min(p.dist_to_segment(last, next)); + last = next; + } + Some(best) + } + + pub(super) struct Picked { + /// Each pick's edge in the body's edge order. + pub(super) edges: Vec, + /// A point halfway along each. + pub(super) points: Vec<[f64; 3]>, + /// Per edge of the body: does a pick pass it over (a seam or a smooth join)? + pub(super) hidden: Vec, + } + + fn sizes_ok(what: &str, sizes: &[f64]) -> Result<()> { + if sizes.is_empty() || sizes.len() > solidcraft_smlib::MAX_POINTS { + return Err(KernelError::Invalid(format!("{what}: select 1…{} edges", solidcraft_smlib::MAX_POINTS))); + } + if sizes.iter().any(|s| !(s.is_finite() && *s > 1e-6 && *s < 1e6)) { + return Err(KernelError::Invalid(format!("{what}: the size must be positive and finite"))); + } + Ok(()) + } + + /// SMLib's blend of each kind. + fn blend_kind(kind: Kind) -> Blend { + match kind { + Kind::Round(_) => Blend::Round, + Kind::Curvature => Blend::Curvature, + Kind::Chord => Blend::Chord, + Kind::Chamfer => Blend::Chamfer, + } + } + + /// SMLib's turn of each kind of turn. + fn smlib_turn(turn: crate::FilletTurn) -> Turn { + match turn { + crate::FilletTurn::Mitre => Turn::Mitre, + crate::FilletTurn::Swept => Turn::Swept, + } + } + + pub(super) fn blend(body: &Body, what: &str, kind: Kind, edges: &[Vec3], sizes: &[f64]) -> Result { + blend_dropping(body, what, kind, edges, sizes).map(|(b, _)| b) + } + + /// [`blend`], with whether each of `edges` picked an edge a larger round removed whole: a + /// round overflowing its faces is built first, and an edge it takes away is gone. + pub(super) fn blend_dropping(body: &Body, what: &str, kind: Kind, edges: &[Vec3], sizes: &[f64]) -> Result<(Body, Vec)> { + body.require_brep(what)?; + sizes_ok(what, sizes)?; + let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; + if matches!(kind, Kind::Round(_)) { + crate::blend::rounds_too_small(body, edges, &picked.edges, sizes)?; + crate::blend::rounds_into_hollow(body, edges, &picked.edges, sizes)?; + } + let tol = pick_tolerance(body); + let Kind::Round(turn) = kind else { + let kind = blend_kind(kind); + return run_with(body, what, &picked.edges, &[], |b| b.blend_dropping(kind, Turn::Mitre, &picked.points, sizes, tol)) + .map(|(out, dropped, _)| (out, dropped)) + .map_err(|e| crate::blend::with_continuation(e, next)); + }; + // Constant-radius rounds: the body keeps what they were made on, and a later round at a + // corner where they meet blends them again with it (crate::blend_corner). + let turn = smlib_turn(turn); + let out = match crate::blend_corner::later_corners(body, &picked.edges, sizes)? { + Some((later, new)) => reblend(body, what, &later, turn).map(|(b, dropped_new)| { + // A picked seam has no round of its own: only the new edges can be removed. + let dropped = picked + .edges + .iter() + .map(|e| new.iter().position(|(n, _)| n == e).is_some_and(|j| dropped_new.get(j).copied().unwrap_or(false))) + .collect(); + (b.with_rounds(body, new), dropped) + }), + None => run_with(body, what, &picked.edges, &[], |b| b.blend_dropping(Blend::Round, turn, &picked.points, sizes, tol)) + .map(|(out, dropped, _)| (out.with_rounds(body, picked.edges.iter().copied().zip(sizes.iter().copied()).collect()), dropped)), + }; + out.map_err(|e| crate::blend::with_continuation(e, next)) + } + + /// The blend `later` makes of its base, every round from the earliest meeting the new edges' + /// corners on and the new edges in one, with its history over `body`, the body the later + /// round was given ([`crate::blend_corner::rebase`]), and whether each new edge (in + /// `later`'s order) was removed whole by a larger, overflowing round. The rounds turn at side + /// edges as `turn` says. + fn reblend(body: &Body, what: &str, later: &crate::blend_corner::Later, turn: Turn) -> Result<(Body, Vec)> { + let base = &later.base; + let mesh = base.mesh(&crate::MeshTolerance::chord((base.size() * 2e-3).max(1e-3)))?; + let mut indices = Vec::with_capacity(later.edges.len()); + let mut points = Vec::with_capacity(later.edges.len()); + let mut radii = Vec::with_capacity(later.edges.len()); + for (e, r) in &later.edges { + let line = mesh.edges.get(*e).ok_or_else(|| failed(what, "corner", "an earlier round's edge is not in the body it was made on"))?; + let (mid, _) = crate::body::polyline_mid(line); + indices.push(*e); + points.push([mid.x, mid.y, mid.z]); + radii.push(*r); + } + sizes_ok(what, &radii)?; + let tol = pick_tolerance(base); + let (out, dropped, _) = run_with(base, what, &indices, &[], |b| b.blend_dropping(Blend::Round, turn, &points, &radii, tol))?; + // The new edges are the last of `later.edges`. + let dropped_new = dropped.get(dropped.len().saturating_sub(later.new_count())..).map(<[bool]>::to_vec).unwrap_or_default(); + let history = out.history().and_then(|h| crate::blend_corner::rebase(h, later, body)); + Ok((out.with_checked_history(history, &record::counts(&[body])).inherit_regularization_protection(body), dropped_new)) + } + + /// Rounds with corner setbacks: each corner point picks the body's nearest vertex (within + /// the pick tolerance), handed to SMLib at that vertex's own position. + pub(super) fn blend_setback(body: &Body, edges: &[Vec3], sizes: &[f64], setbacks: &[(Vec3, f64)]) -> Result { + let what = "fillet with corner setbacks"; + body.require_brep(what)?; + sizes_ok(what, sizes)?; + if setbacks.is_empty() || setbacks.len() > solidcraft_smlib::MAX_POINTS { + return Err(KernelError::Invalid(format!("{what}: give 1…{} corners", solidcraft_smlib::MAX_POINTS))); + } + if setbacks.iter().any(|(p, d)| !p.is_finite() || !(d.is_finite() && *d > 1e-6 && *d < 1e6)) { + return Err(KernelError::Invalid(format!("{what}: each corner is a finite point with a positive, finite setback"))); + } + let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; + crate::blend::rounds_too_small(body, edges, &picked.edges, sizes)?; + crate::blend::rounds_into_hollow(body, edges, &picked.edges, sizes)?; + let corners = corner_vertices(body, setbacks.iter().map(|(p, _)| *p))?; + let distances: Vec = setbacks.iter().map(|(_, d)| *d).collect(); + let tol = pick_tolerance(body); + let at: Vec = setbacks.iter().map(|(p, _)| *p).collect(); + run_with(body, what, &picked.edges, &at, |b| b.blend_setback(Blend::Round, &picked.points, sizes, &corners, &distances, tol).map(|r| (r, ()))) + .map(|(out, (), _)| out) + .map_err(|e| crate::blend::with_continuation(e, next)) + } + + /// [`blend_setback`] with the set-back corners left open (`super::OpenCorners`). + pub(super) fn blend_setback_open(body: &Body, kind: Kind, edges: &[Vec3], sizes: &[f64], setbacks: &[(Vec3, f64)]) -> Result { + let what = "fillet with open setback corners"; + body.require_brep(what)?; + sizes_ok(what, sizes)?; + if setbacks.is_empty() || setbacks.len() > solidcraft_smlib::MAX_POINTS { + return Err(KernelError::Invalid(format!("{what}: give 1…{} corners", solidcraft_smlib::MAX_POINTS))); + } + if setbacks.iter().any(|(p, d)| !p.is_finite() || !(d.is_finite() && *d > 1e-6 && *d < 1e6)) { + return Err(KernelError::Invalid(format!("{what}: each corner is a finite point with a positive, finite setback"))); + } + let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; + let corners = corner_vertices(body, setbacks.iter().map(|(p, _)| *p))?; + let distances: Vec = setbacks.iter().map(|(_, d)| *d).collect(); + let at: Vec = setbacks.iter().map(|(p, _)| *p).collect(); + let tol = pick_tolerance(body); + let (sheet, holes, order) = + run_with(body, what, &picked.edges, &at, |b| b.blend_setback_open(blend_kind(kind), &picked.points, sizes, &corners, &distances, tol)) + .map_err(|e| crate::blend::with_continuation(e, next))?; + // SMLib's indices in the sheet's own orders. + let place = |list: &[usize], i: usize| if list.is_empty() { Some(i) } else { list.get(i).copied() }; + let renumber = |hole: &solidcraft_smlib::Hole| -> Result> { + hole.edges + .iter() + .map(|h| { + let edge = match &order { + Some(o) => place(&o.edges, h.edge), + None => Some(h.edge), + }; + edge.filter(|e| *e < sheet.edge_count()) + .map(|e| (e, h.forward)) + .ok_or_else(|| failed(what, "hole", "an edge SMLib names is not in the sheet")) + }) + .collect() + }; + let holes = holes.iter().map(renumber).collect::>>()?; + Ok(super::OpenCorners { sheet, holes }) + } + + /// The body's vertex nearest each point, within the pick tolerance: the ends of its edges. + fn corner_vertices(body: &Body, picks: impl Iterator) -> Result> { + let mesh = body.mesh(&crate::MeshTolerance::chord((body.size() * 2e-3).max(1e-3)))?; + let ends: Vec = mesh.edges.iter().flat_map(|l| l.first().into_iter().chain(l.last())).copied().collect(); + let reach = pick_tolerance(body); + picks + .map(|p| { + ends.iter() + .map(|v| (v.dist(p), *v)) + .filter(|(d, _)| *d <= reach) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, v)| [v.x, v.y, v.z]) + .ok_or_else(|| KernelError::Invalid(format!("no corner near the setback point ({:.3}, {:.3}, {:.3})", p.x, p.y, p.z))) + }) + .collect() + } + + pub(super) fn sides(body: &Body, edges: &[Vec3], d1: f64, side: crate::ChamferSide, flip: bool) -> Result { + body.require_brep("chamfer")?; + sizes_ok("chamfer", &vec![d1; edges.len()])?; + let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; + let second = match side { + crate::ChamferSide::Distance(d) => ChamferSecond::Distance(d), + crate::ChamferSide::Angle(a) => ChamferSecond::Angle(a), + }; + let up = if flip { [0.0, 0.0, -1.0] } else { [0.0, 0.0, 1.0] }; + let tol = pick_tolerance(body); + run(body, "chamfer", &picked.edges, |b| b.chamfer_sides(&picked.points, tol, d1, second, up)) + .map_err(|e| crate::blend::with_continuation(e, next)) + } + + pub(super) fn variable(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result { + body.require_brep("fillet")?; + if !start.is_finite() { + return Err(KernelError::Invalid("the start point must be finite".into())); + } + let picked = resolve(body, &[edge_at])?; + let next = crate::blend::unfinished_chain(body, &[edge_at], &picked.edges, &picked.hidden)?; + let [at] = picked.points[..] else { return Err(KernelError::Invalid("one edge".into())) }; + let tol = pick_tolerance(body); + run(body, "variable fillet", &picked.edges, |b| { + b.fillet_variable(at, tol, [start.x, start.y, start.z], spline.degree, &spline.knots, &spline.radii) + }) + .map_err(|e| crate::blend::with_continuation(e, next)) + } + + /// `op` on `body` in SMLib, tagged as operand 0, checked, decoded, with its history. + fn run(body: &Body, what: &str, edges: &[usize], op: impl FnOnce(&Brep) -> solidcraft_smlib::Result) -> Result { + run_with(body, what, edges, &[], |b| op(b).map(|r| (r, ()))).map(|(out, (), _)| out) + } + + /// [`run`] for an `op` that also gives something of its own, with where SMLib's faces and + /// edges of the result are in the body's orders. + /// `corners`: the corner points of a blend with setbacks, in the order `op` gives them to + /// SMLib, so a refused corner is named by its place. + fn run_with( + body: &Body, + what: &str, + edges: &[usize], + corners: &[Vec3], + op: impl FnOnce(&Brep) -> solidcraft_smlib::Result<(Brep, T)>, + ) -> Result<(Body, T, Option)> { + guard(what, || { + let (sb, order) = smlib_body_ordered(body)?; + let tagged = sb.tagged(0).map_err(|e| failed(what, "tag", e))?; + let (r, extra) = op(&tagged).map_err(|e| match e { + SmError::Unsupported => super::unsupported(&format!("this {what}, which SMLib cannot build exactly")), + SmError::CornerRefused { corner } => match corners.get(corner) { + // The same words as `super::unsupported`, the reason after them. + Some(p) => KernelError::Invalid(format!( + "not supported yet: setting back the corner at ({:.3}, {:.3}, {:.3}) with the SMLib kernel (a G2 corner is set \ + back): SMLib sets back a corner only where every edge meeting it is rounded and they are all convex or all concave", + p.x, p.y, p.z + )), + None => failed(what, "operation", SmError::CornerRefused { corner }), + }, + SmError::NoEffect => KernelError::Failed(format!("SMLib made no change: the {what} reported success but built no face")), + SmError::CornerUnsupported => KernelError::Invalid(format!( + "not supported yet: the {what} meets a corner of this kind, which SMLib's blends do not handle yet (where its edges \ + run on tangentially into each other, or meet in a way no blend corner builds)" + )), + SmError::NoRoom => KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow")), + // Not a size a smaller radius fixes: solidcore builds no swept turn there. + SmError::TurnRefused { why, at, .. } => { + let at = at.map(|[x, y, z]| format!(" at ({x:.3}, {y:.3}, {z:.3})")).unwrap_or_default(); + KernelError::Invalid(format!("the {what}'s swept corner{at} is not built: {why}")) + } + SmError::TooLarge { size, kind, at, why } => { + let mut beside = match at { + Some([x, y, z]) => format!(", at the edge at ({x:.3}, {y:.3}, {z:.3})"), + None => String::new(), + }; + if let Some(why) = why { + beside = format!("{beside}: {}", why.words()); + } + let fits = match kind { + solidcraft_smlib::FitKind::Scale => { + format!("the largest that fits is {} times the distances given", crate::blend::trimmed_mm(size)) + } + kind => crate::blend::largest_fit_note(kind.word(), size), + }; + KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow{beside}; {fits}")) + } + SmError::Unported(why) => KernelError::Invalid(format!("not supported yet: {why}")), + e => failed(what, "operation", e), + })?; + // Checked here unless the evaluation's validation mode leaves it to the feature's end + // (`crate::validation`). + let step = crate::validation::step(); + if step == crate::validation::Step::Check { + let check = r.check(CheckLevel::All).map_err(|e| failed(what, "check", e))?; + if !check.is_valid() { + let input_fails = sb.check(CheckLevel::All).is_ok_and(|c| !c.is_valid()); + let step = if input_fails { + "SMLib's check refuses the result (the input already fails it)" + } else { + "SMLib's check refuses the result" + }; + return Err(failed(what, step, check)); + } + } + let (out, result_order) = body_from_smlib_ordered(&r)?; + let history = match (order, &result_order) { + (Some(o), Some(ro)) => match r.history().map_err(|e| failed(what, "history", e))?.history(&[o], ro) { + Ok(mut h) => { + let operand = History::identity(body).edges; + let taken_up = taken_up(body, edges, &h); + solidcraft_smlib::history::blends(&mut h, &operand, edges, &taken_up); + Some(with_corners(h)) + } + Err(e) => { + log::debug!(target: "smlib", "{what} history: {e}"); + None + } + }, + _ => None, + }; + let out = out.with_checked_history(history, &record::counts(&[body])).inherit_regularization_protection(body); + let out = if step == crate::validation::Step::Defer { + out.left_unchecked(&format!("SMLib {what}"), crate::validation::Checked::AsIs, r) + } else { + out + }; + Ok((out, extra, result_order)) + }) + } + + /// `h` with each blend face still without origin (a corner patch where blends meet) made in + /// place of all the edges of the blend faces next to it, and every + /// edge of a face new to the blend recorded as where its faces meet (two chamfers' mitre is + /// where the two chamfers meet). + fn with_corners(mut h: History) -> History { + let mut corners: Vec<(usize, BTreeSet)> = Vec::new(); + for (i, f) in h.faces.iter().enumerate() { + if f.change != Change::Generated || !f.origins.is_empty() { + continue; + } + let around: BTreeSet = h + .edges + .iter() + .filter(|e| e.faces.contains(&i)) + .flat_map(|e| e.faces.iter().filter(|g| **g != i)) + .filter_map(|g| h.faces.get(*g)) + .flat_map(|g| g.origins.iter().copied()) + .filter(|o| matches!(o, FaceOrigin::Edge { .. })) + .collect(); + if !around.is_empty() { + corners.push((i, around)); + } + } + for (i, origins) in corners { + if let Some(f) = h.faces.get_mut(i) { + *f = record::generated(origins.into_iter().collect()); + } + } + let faces = h.faces.clone(); + for e in &mut h.edges { + if e.faces.iter().any(|f| faces.get(*f).is_some_and(|f| f.change == Change::Generated)) { + e.origins = record::meeting(&e.faces, &faces); + } + } + h + } + + /// The operand's edges the blend took up besides the picked ones: every edge no result edge + /// comes from (one the blend's corners took up, or one it ran over), in the operand's edge + /// order. + fn taken_up(body: &Body, picked: &[usize], h: &History) -> Vec { + let kept: BTreeSet = h + .edges + .iter() + .flat_map(|e| e.origins.iter()) + .filter_map(|o| match o { + EdgeOrigin::Edge { operand: 0, edge } => Some(*edge), + _ => None, + }) + .collect(); + (0..body.edge_count()).filter(|e| !kept.contains(e) && !picked.contains(e)).collect() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use solidcore_record::Vec3; + + use super::*; + use crate::history::{Change, FaceOrigin}; + use crate::{box_solid, measure}; + + const QUARTER: f64 = 1.0 - std::f64::consts::FRAC_PI_4; + + fn cube() -> Body { + box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(20.0, 20.0, 20.0)).unwrap() + } + + fn volume(b: &Body) -> f64 { + measure(b).unwrap().volume + } + + /// Within the kernel measure's accuracy on a curved face (a few 1e-6 of the volume; SMLib's + /// own exact volumes match to 1e-3 mm³ in the C API's tests). + fn near(got: f64, want: f64) -> bool { + (got - want).abs() <= 5e-6 * want.abs() + } + + /// The edge of `b` nearest `p`, in its edge order. + fn edge_at(b: &Body, p: Vec3) -> usize { + b.nearest_edge(p, 1e-3).unwrap().unwrap().0 + } + + #[test] + fn a_round_loses_its_corner_and_its_face_comes_from_the_edge() { + let b = cube(); + let at = Vec3::new(10.0, 20.0, 20.0); + let r = imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[at], &[2.0]).unwrap(); + assert!(near(volume(&r), 8000.0 - QUARTER * 4.0 * 20.0), "{}", volume(&r)); + assert_eq!(r.face_count(), 7); + let h = r.history().expect("a history"); + let blends: Vec<_> = h.faces.iter().filter(|f| f.change == Change::Generated).collect(); + assert_eq!(blends.len(), 1); + assert_eq!(blends[0].origins, vec![FaceOrigin::Edge { operand: 0, edge: edge_at(&b, at) }]); + } + + #[test] + fn a_pick_at_a_vertex_takes_the_nearest_edge_by_its_midpoint() { + // (20, 20, 10) is on the vertical edge only; (20, 20, 20) is a corner of three edges, which + // the body's own order resolves, never left to SMLib. + let b = cube(); + assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(20.0, 20.0, 20.0)], &[1.0]).is_ok()); + assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(60.0, 60.0, 60.0)], &[1.0]).is_err()); + } + + /// A ball's rim on a block's back face, tangent to the back face's bottom edge at (2.5, 22.5, 0). + /// Near there the two are closer than the mesh's chord, which can't tell them apart. + #[test] + fn a_pick_on_a_rim_tangent_to_a_straight_edge_takes_the_rim() { + let block = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(30.0, 22.5, 17.5)).unwrap(); + let ball = crate::sphere(Vec3::new(2.5, 22.5, 5.0), 5.0).unwrap(); + let b = crate::boolean(&block, &ball, crate::BoolOp::Cut).unwrap().unwrap(); + let on_rim = |[x, y, z]: [f64; 3]| (y - 22.5).abs() < 1e-6 && ((x - 2.5).hypot(z - 5.0) - 5.0).abs() < 1e-3; + for degrees in [2.0f64, 5.0, 10.0, 20.0, 45.0] { + let a = degrees.to_radians(); + let pick = Vec3::new(2.5 + 5.0 * a.sin(), 22.5, 5.0 - 5.0 * a.cos()); + let picked = imp::resolve(&b, &[pick]).unwrap(); + assert!(on_rim(picked.points[0]), "{degrees} degrees from the tangent point: took the edge through {:?}", picked.points[0]); + let beside = imp::resolve(&b, &[Vec3::new(pick.x, 22.5, 0.0)]).unwrap(); + assert!(beside.points[0][2].abs() < 1e-9, "the straight edge under it: took the edge through {:?}", beside.points[0]); + } + } + + #[test] + fn a_pick_where_a_seam_meets_a_rim_takes_the_rim() { + // Every point of the top rim's circle, the seam's top end among them, is on the rim. + let c = crate::cylinder(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 8.0, 10.0).unwrap(); + assert!(c.edge_count() > 2, "the cylinder has a seam"); + for k in 0..8 { + let a = k as f64 * std::f64::consts::FRAC_PI_4; + let picked = imp::resolve(&c, &[Vec3::new(8.0 * a.cos(), 8.0 * a.sin(), 10.0)]).unwrap(); + let [_, _, z] = picked.points[0]; + assert!((z - 10.0).abs() < 1e-9, "the pick at {a} took an edge through z = {z}"); + } + } + + #[test] + fn a_pick_where_a_bosss_seam_meets_its_base_takes_the_base_circle() { + // A boss joined onto a block, as the ladder's running part has (07-fillets/017 picks + // its base circle where the seam starts): its side lies on both sides of its seam. + let block = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 30.0, 20.0)).unwrap(); + let boss = crate::cylinder(Vec3::new(15.0, 15.0, 20.0), Vec3::new(0.0, 0.0, 1.0), 8.0, 10.0).unwrap(); + let b = crate::boolean(&block, &boss, crate::BoolOp::Union).unwrap().unwrap(); + let mesh = b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); + let seams = crate::topo::seam_flags(&b, &mesh); + let record = b.record(); + let one_face: Vec = crate::history::edge_faces(record) + .iter() + .zip(&record.edges) + .enumerate() + .filter(|(_, (faces, e))| faces.len() == 1 && e.uses.len() == 2) + .map(|(i, _)| i) + .collect(); + assert_eq!(one_face.len(), 1, "the boss's side meets itself along its seam"); + for &i in &one_face { + assert!(seams[i], "edge {i}, the boss's side on both of its sides, is a seam"); + assert!(!mesh.edge_pickable(i), "edge {i} is drawn and picked as a seam"); + // Its end on the base circle, where a pick takes the circle. + let line = &mesh.edges[i]; + let foot = [line[0], line[line.len() - 1]].into_iter().find(|p| (p.z - 20.0).abs() < 1e-6).unwrap(); + let picked = imp::resolve(&b, &[foot]).unwrap(); + let [_, _, z] = picked.points[0]; + assert!((z - 20.0).abs() < 1e-9, "the pick at {foot:?} took an edge through z = {z}"); + } + } + + #[test] + fn each_edge_takes_its_own_size() { + let b = cube(); + let picks = [Vec3::new(10.0, 20.0, 20.0), Vec3::new(10.0, 0.0, 20.0)]; + let r = imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &picks, &[2.0, 3.0]).unwrap(); + assert!(near(volume(&r), 8000.0 - QUARTER * 13.0 * 20.0), "{}", volume(&r)); + let c = imp::blend(&b, "chamfer", Kind::Chamfer, &picks, &[2.0, 3.0]).unwrap(); + assert!(near(volume(&c), 8000.0 - 0.5 * 13.0 * 20.0), "{}", volume(&c)); + assert_eq!(c.history().map(|h| h.faces.iter().filter(|f| matches!(f.origins[..], [FaceOrigin::Edge { .. }])).count()), Some(2)); + } + + #[test] + fn a_linear_radius_runs_from_the_start_end() { + // 3 at x = 0 to 1 at x = 20: the balls' union, a cone, takes 18.5377834 (their great + // circles, (1 - pi/4) L (r0^2 + r0 r1 + r1^2) / 3, would take 18.5988), from either end + // given as the start with the law reversed. + let b = cube(); + let at = Vec3::new(10.0, 20.0, 20.0); + let law = RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], radii: vec![3.0, 1.0] }; + let r = imp::variable(&b, at, Vec3::new(0.0, 20.0, 20.0), &law).unwrap(); + let want = 8000.0 - 18.5377834; + assert!((volume(&r) - want).abs() < 0.01, "{}", volume(&r)); + let back = imp::variable(&b, at, Vec3::new(20.0, 20.0, 20.0), &law.reversed()).unwrap(); + assert!((volume(&back) - volume(&r)).abs() < 1e-6 * 8000.0); + } + + /// A chamfer 5 back along the top and 2 down the side of the cube's edge y = 20, z = 20 (or + /// 2 along the top and 5 down with `flip`): a 5 × 2 / 2 triangle along the 20 mm edge, its + /// face coming from the edge. + #[test] + fn a_chamfer_takes_its_two_setbacks() { + let b = cube(); + let at = Vec3::new(10.0, 20.0, 20.0); + for flip in [false, true] { + let r = imp::sides(&b, &[at], 5.0, crate::ChamferSide::Distance(2.0), flip).unwrap(); + assert!(near(volume(&r), 8000.0 - 100.0), "{}", volume(&r)); + let top = if flip { 18.0 } else { 15.0 }; + assert!( + r.edges(0.01).unwrap().iter().any(|e| e.points.iter().all(|p| (p.y - top).abs() < 1e-6 && (p.z - 20.0).abs() < 1e-6)), + "flip {flip}" + ); + let h = r.history().unwrap(); + assert!(h.faces.iter().any(|f| f.origins == [crate::history::FaceOrigin::Edge { operand: 0, edge: edge_at(&b, at) }])); + } + let r = imp::sides(&b, &[at], 5.0, crate::ChamferSide::Angle(45f64.to_radians()), false).unwrap(); + assert!(near(volume(&r), 8000.0 - 12.5 * 20.0), "{}", volume(&r)); + } + + /// The ladder's 08/006: a 2 mm chamfer of a cylinder's top rim. SMLib's cone and rail lie some + /// 2e-5 mm off the faces they bound, more than the kernel's working tolerance; the body keeps + /// the tolerances SMLib's record gave them, so its own record (and the saved body's) is valid + /// and SMLib's check takes it back. + #[test] + fn an_smlib_blend_keeps_its_record_valid() { + let c = crate::cylinder(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0, 20.0).unwrap(); + let r = imp::blend(&c, "chamfer", Kind::Chamfer, &[Vec3::new(10.0, 0.0, 20.0)], &[2.0]).unwrap(); + let v = crate::validity(&r); + assert!(v.record.is_ok(), "{:?}", v.record); + assert!(matches!(v.smlib, Some(crate::SmlibCheck::Valid)), "{:?}", v.smlib); + let saved = crate::decode_native_body(&crate::encode_native_body(&r).unwrap()).unwrap(); + assert!(crate::validity(&saved).record.is_ok()); + assert!( + crate::validity( + &crate::transform_matrix(&saved, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [5.0, 0.0, 0.0, 1.0]]).unwrap() + ) + .record + .is_ok() + ); + } + + #[test] + fn options_smlib_cannot_build_are_refused() { + assert!(unsupported("x").to_string().contains("not supported yet")); + let b = cube(); + // A radius law down to zero inside the edge would pinch the round to a point. + let pinch = RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 0.5, 1.0, 1.0], radii: vec![4.0, 0.0, 4.0] }; + assert!(imp::variable(&b, Vec3::new(10.0, 20.0, 20.0), Vec3::new(0.0, 20.0, 20.0), &pinch).is_err()); + assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(10.0, 20.0, 20.0)], &[f64::NAN]).is_err()); + assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(f64::NAN, 20.0, 20.0)], &[1.0]).is_err()); + assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[], &[]).is_err()); + } + + /// A smooth edge (a round's seam with the face it runs into) has nothing to round: refused + /// before SMLib, saying so. An edge that runs on tangentially into one left out is SMLib's to + /// end: the end face's top edge into the round's end arc builds, its round run on through the + /// arc's round until it leaves the material (rig fillets/1207-fillet-box-end-edge-into- + /// unblended-round), and with its tangent chain the edge builds too; a vertical edge run on + /// up a top round's end arc into the corner (ladder 07-fillets/018) builds. + #[test] + fn smooth_edges_and_unfinished_tangent_chains_are_refused_saying_why() { + let b = cube(); + let rounded = fillet(&b, &[Vec3::new(10.0, 20.0, 20.0)], 3.0, FilletTurn::Mitre).unwrap(); + // the seam where the r3 round meets the top, 3 in from the old edge + let seam = imp::blend(&rounded, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(10.0, 17.0, 20.0)], &[1.0]).unwrap_err().to_string(); + assert!(seam.contains("is smooth: its faces meet tangentially, so there is nothing to round"), "{seam}"); + // the end face's top edge runs on tangentially into the round's end arc: its r1 round + // goes on along y through the r3 round until that drops below it, at y = 17 + sqrt(5) + // (the rig case's closed form: 8000 - 20 (9 - 9 pi/4) - 17 (1 - pi/4) - 0.218236) + let top = Vec3::new(0.0, 8.0, 20.0); + let alone = fillet(&rounded, &[top], 1.0, FilletTurn::Mitre).unwrap(); + assert!((volume(&alone) - 7957.505202).abs() < 1e-3, "{}", volume(&alone)); + let chain = crate::tangent_chain(&rounded, &[top]).unwrap(); + assert!(chain.len() > 1, "{chain:?}"); + let whole = fillet(&rounded, &chain, 1.0, FilletTurn::Mitre).unwrap(); + assert!(volume(&whole) < volume(&rounded)); + + // r5 and r3 on two top edges at a corner, then r2 on the vertical edge under them: it + // runs on up the r5 round's end arc, and SMLib ends it there + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let b = fillet(&b, &[Vec3::new(30.0, 40.0, 20.0)], 5.0, FilletTurn::Mitre).unwrap(); + let b = fillet(&b, &[Vec3::new(60.0, 20.0, 20.0)], 3.0, FilletTurn::Mitre).unwrap(); + let vertical = Vec3::new(60.0, 40.0, 8.0); + let chain = crate::tangent_chain(&b, &[vertical]).unwrap(); + assert!(chain.len() > 1, "{chain:?}"); + let run_on = fillet(&b, &[vertical], 2.0, FilletTurn::Mitre).unwrap(); + assert!(volume(&run_on) < volume(&b)); + } +} diff --git a/crates/kernel/src/blend_variable.rs b/crates/kernel/src/blend_variable.rs index 337408aa5..3c6da7a7e 100644 --- a/crates/kernel/src/blend_variable.rs +++ b/crates/kernel/src/blend_variable.rs @@ -1,62 +1,55 @@ //! Fillets beyond a constant radius: a radius that varies along the edge (from one end to the //! other) and chord-length fillets (the width across the blend given instead of the radius). -//! -//! Variable radius: a straight, convex or concave edge between two planar faces whose ends each -//! touch one more planar face square to the edge (the configuration of `blend`). Every section -//! square to the edge is a circular arc tangent to both faces, its radius running linearly from -//! one end to the other; the arcs' control points move linearly, so the blend is exactly a -//! rational B-spline of degree 2 across and 1 along. The radius may run down to zero at one end: -//! there the blend closes to the edge's end point, a three-sided face, and the end face is kept. +//! SMLib builds both ([`crate::blend_smlib`]): a variable round as its variable-radius solver on a +//! B-spline radius law, a chord fillet as its constant-chord solver. On a straight edge between +//! two planar faces the band a radius law takes from the faces is checked against the faces +//! first, which also gives a [`taper`] its room along the edge. -use std::collections::HashMap; +use solidcore_record::Vec3; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::prelude::*; -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, builder}; - -use crate::blend::{plane_normal, rebuild_face, too_large, unsupported, vtx}; -use crate::body::{Body, Solid, p3}; +use crate::blend::{Faces, too_large, unsupported}; +use crate::body::Body; use crate::{KernelError, Result, guard}; -/// The radius of a chord-length fillet between faces whose in-face directions (away from the -/// edge) make the angle `phi`: the arc spans π − φ, so the chord is 2 r cos(φ/2). -fn chord_radius(chord: f64, phi: f64) -> f64 { - chord / (2.0 * (phi / 2.0).cos()) -} - /// The two planar faces at an edge, the in-face directions away from it (`t1`, `t2`), the -/// first face's normal, the angle between the directions and the side of the material. +/// angle between the directions. struct EdgeFrame { i1: usize, i2: usize, - n1: Vec3, t1: Vec3, t2: Vec3, phi: f64, - side: f64, } -fn edge_frame(faces: &[&mt::Face], edge: &mt::Edge) -> Result { - let on_edge: Vec = (0..faces.len()).filter(|i| faces.get(*i).is_some_and(|f| f.edge_iter().any(|e| e.id() == edge.id()))).collect(); - let [i1, i2] = on_edge[..] else { return Err(unsupported("the edge is not between two faces")) }; - let (Some(f1), Some(f2)) = (faces.get(i1), faces.get(i2)) else { return Err(KernelError::Failed("faces".into())) }; - let (Some(n1), Some(n2)) = (plane_normal(f1), plane_normal(f2)) else { return Err(unsupported("both faces next to the edge must be planar")) }; - let into = |f: &mt::Face, n: Vec3| -> Option { - let e = f.boundary_iters().into_iter().flatten().find(|e| e.id() == edge.id())?; - let dir = (vtx(e.back()) - vtx(e.front())).normalized()?; - n.cross(dir).normalized() +fn edge_frame(rec: &Faces, e: usize) -> Result { + let faces: Vec = rec.faces_of(e).into_iter().map(|f| f as usize).collect(); + let [i1, i2] = faces[..] else { return Err(unsupported("the edge is not between two faces")) }; + let (Some(n1), Some(n2)) = (rec.plane_normal(i1), rec.plane_normal(i2)) else { + return Err(unsupported("both faces next to the edge must be planar")); }; - let (Some(t1), Some(t2)) = (into(f1, n1), into(f2, n2)) else { return Err(KernelError::Failed("blend: edge direction".into())) }; + let into = |f: usize| -> Option { + let mut uses = rec.uses(f).filter(|u| u.edge as usize == e); + let u = uses.next()?; + if uses.next().is_some() { + return None; + } + rec.direction_into_face(f, u) + }; + let (Some(t1), Some(t2)) = (into(i1), into(i2)) else { return Err(KernelError::Failed("blend: edge direction".into())) }; let phi = t1.dot(t2).clamp(-1.0, 1.0).acos(); let convex = n1.dot(t2) < -1e-9 && n2.dot(t1) < -1e-9; let concave = n1.dot(t2) > 1e-9 && n2.dot(t1) > 1e-9; if !(phi > 1e-3 && phi < std::f64::consts::PI - 1e-3) || !(convex || concave) { return Err(unsupported("the faces at the edge are tangent or the edge is ambiguous")); } - Ok(EdgeFrame { i1, i2, n1, t1, t2, phi, side: if convex { -1.0 } else { 1.0 } }) + Ok(EdgeFrame { i1, i2, t1, t2, phi }) } /// Fillet one straight edge with radius `r0` at its end nearest `start` and `r1` at the other. pub fn fillet_variable(body: &Body, edge_at: Vec3, start: Vec3, r0: f64, r1: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_variable"); fillet_variable_points(body, edge_at, start, &[(0.0, r0), (1.0, r1)], false) } @@ -104,9 +97,11 @@ impl RadiusSpline { /// The radius at position `t`. pub fn eval(&self, t: f64) -> f64 { - let kv = mt::KnotVec::from(self.knots.clone()); - let b = kv.try_bspline_basis_functions(self.degree, t.clamp(0.0, 1.0)).unwrap_or_default(); - b.iter().zip(&self.radii).map(|(x, r)| x * r).sum() + use solidcraft_geom::bspline::{Side, local_basis}; + let t = t.clamp(0.0, 1.0); + // At the end of the domain the closing span's left limit holds. + let side = if t >= 1.0 { Side::Left } else { Side::Right }; + self.radii.iter().enumerate().filter_map(|(j, r)| Some(local_basis(self.knots.get(j..=j + self.degree + 1)?, t, side, 0).first()? * r)).sum() } /// The same radius with its positions taken from the other end. @@ -189,6 +184,7 @@ impl RadiusSpline { /// positions 0 (the end nearest `start`) to 1 (the other end) and any between, the radius /// straight between them or `smooth`. One end's radius may be zero. pub fn fillet_variable_points(body: &Body, edge_at: Vec3, start: Vec3, points: &[(f64, f64)], smooth: bool) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_variable_points"); if points.len() < 2 || points.len() > 100 { return Err(KernelError::Invalid("a variable radius needs 2…100 points".into())); } @@ -204,69 +200,47 @@ pub fn fillet_variable_points(body: &Body, edge_at: Vec3, start: Vec3, points: & fillet_variable_spline(body, edge_at, start, &RadiusSpline::through(&pts, smooth)) } -/// Fillet one straight edge with the radius `spline` along it, its positions from the end -/// nearest `start`. One end's radius may be zero. A curved edge, or one between curved faces, is -/// rolled by a ball of the law's radius instead ([`curved_variable`]). +/// Fillet one edge with the radius `spline` along it, its positions from the end nearest +/// `start`. One end's radius may be zero. A law whose round would leave the faces beside the +/// edge is SMLib's refusal ([`KernelError::TooLarge`]). pub fn fillet_variable_spline(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_variable_spline"); body.require_brep("fillet")?; spline.check()?; - let edge = crate::surfaces::edge_near(body, edge_at).ok_or_else(|| KernelError::Invalid(format!("no edge at {edge_at:?}")))?; - guard("variable fillet", || { - let Ok(s) = EdgeSetup::new(body, &edge) else { - return curved_variable(body, &edge, start, spline); - }; - // Positions from the end nearest `start` (the edge keeps its own direction). - let law = if s.p1.dist(start) < s.p0.dist(start) { spline.reversed() } else { spline.clone() }; - build(body, &s, &edge, &law) - }) + if !(edge_at.is_finite() && start.is_finite()) { + return Err(KernelError::Invalid("the edge pick and the start point must be finite".into())); + } + crate::blend_smlib::fillet_variable(body, edge_at, start, spline) } -/// The radius law along a curved edge: a ball whose radius is the law's at each station rolls -/// along the edge's smooth chain (the same sections, contacts and trims as the straight-edge case, -/// sized by the law there). A law that has run to zero at an end closes the blend to the edge's -/// end point, as the straight-edge fillet does. -fn curved_variable(body: &Body, edge: &mt::Edge, start: Vec3, law: &RadiusSpline) -> Result { - // Positions from the end nearest `start` (the chain runs along the edge's own direction). - let (p0, p1) = (vtx(edge.absolute_front()), vtx(edge.absolute_back())); - let law = if p1.dist(start) < p0.dist(start) { law.reversed() } else { law.clone() }; - let chain = crate::blend::smooth_chain(&body.solid, edge).unwrap_or_else(|| vec![edge.id()]); - let (made, rec) = guard("variable fillet", || crate::curveblend::curve_blend_law(&body.solid, &chain, body.size(), &law, true))?; - crate::record::rebuilt(made, &[&body.solid], &rec) -} - -/// A straight edge between two planar faces as the variable blend sees it: the shell it is in -/// and that shell's faces, the frame at the edge, and its ends (front first). -struct EdgeSetup<'a> { - si: usize, - faces: Vec<&'a mt::Face>, +/// A straight edge between two planar faces as the variable blend sees it: the body's record, +/// the frame at the edge, and its ends (start first). +struct EdgeSetup { + rec: Faces, fr: EdgeFrame, - edge: mt::EdgeID, - v0: mt::Vertex, - v1: mt::Vertex, + edge: usize, + v0: u32, + v1: u32, p0: Vec3, p1: Vec3, d: Vec3, tol: f64, } -impl<'a> EdgeSetup<'a> { - fn new(body: &'a Body, edge: &mt::Edge) -> Result> { - if !matches!(edge.curve(), mt::Curve::Line(_)) { +impl EdgeSetup { + /// The edge of `body` a pick at `at` takes, as the blend takes it. + fn new(body: &Body, at: Vec3) -> Result { + let (picked, _) = crate::blend_smlib::picked_edges(body, &[at])?; + let edge = *picked.first().ok_or_else(|| KernelError::Invalid(format!("no edge at {at:?}")))?; + let rec = Faces::of(body)?; + if !rec.straight(edge) { return Err(unsupported("only straight edges take a variable radius")); } - let (si, shell) = body - .solid - .boundaries() - .iter() - .enumerate() - .find(|(_, sh)| sh.edge_iter().any(|e| e.id() == edge.id())) - .ok_or_else(|| KernelError::Failed("edge not found".into()))?; - let faces: Vec<&mt::Face> = shell.face_iter().collect(); - let fr = edge_frame(&faces, edge)?; - let (v0, v1) = (edge.absolute_front().clone(), edge.absolute_back().clone()); - let (p0, p1) = (vtx(&v0), vtx(&v1)); + let fr = edge_frame(&rec, edge)?; + let [v0, v1] = rec.rec.edges.get(edge).ok_or_else(|| KernelError::Failed("edge not found".into()))?.vertices; + let (p0, p1) = rec.ends(edge).ok_or_else(|| KernelError::Failed("edge not found".into()))?; let d = (p1 - p0).normalized().ok_or_else(|| KernelError::Failed("zero-length edge".into()))?; - Ok(EdgeSetup { si, faces, fr, edge: edge.id(), v0, v1, p0, p1, d, tol: (body.size() * 1e-7).max(1e-9) }) + Ok(EdgeSetup { rec, fr, edge, v0, v1, p0, p1, d, tol: (body.size() * 1e-7).max(1e-9) }) } /// How far a blend of radius `r` reaches into each face from the edge. @@ -279,9 +253,7 @@ impl<'a> EdgeSetup<'a> { fn band_fits(&self, u: f64, r: f64) -> bool { let p = self.p0 + (self.p1 - self.p0) * u; let s = self.back(r); - [(self.fr.i1, self.fr.t1), (self.fr.i2, self.fr.t2)] - .into_iter() - .all(|(i, t)| self.faces.get(i).is_some_and(|f| crate::blend::extension_fits(f, p, p + t * s, self.tol))) + [(self.fr.i1, self.fr.t1), (self.fr.i2, self.fr.t2)].into_iter().all(|(i, t)| extension_fits(&self.rec, i, p, p + t * s, self.tol)) } /// The largest radius up to `cap` whose band fits at position `u`. @@ -300,199 +272,115 @@ impl<'a> EdgeSetup<'a> { /// The room at the end `v` (`out` pointing away from the edge there), as a radius: zero /// where a face closes to a point (its next side runs back along the edge), the reach of the /// sides along the faces where they are square to the edge, None where a side leans outward. - fn end_room(&self, v: &mt::Vertex, out: Vec3) -> Option { + fn end_room(&self, v: u32, out: Vec3) -> Option { let mut room = f64::INFINITY; for (i, t) in [(self.fr.i1, self.fr.t1), (self.fr.i2, self.fr.t2)] { - let side = self.faces.get(i)?.edge_iter().find(|e| e.id() != self.edge && (e.front() == v || e.back() == v))?; - let dir = leaving(&side, v, self.tol)?; + let side = self + .rec + .uses(i) + .map(|u| u.edge as usize) + .find(|e| *e != self.edge && self.rec.rec.edges.get(*e).is_some_and(|x| x.vertices.contains(&v)))?; + let [a, b] = self.rec.rec.edges.get(side)?.vertices; + // The direction the side leaves `v` in. + let dir = if a == v { self.rec.tangent(side, false)? } else { self.rec.tangent(side, true)? * -1.0 }; let lean = dir.dot(out); if lean < -1e-9 { return Some(0.0); } - if lean > 1e-9 || !matches!(side.curve(), mt::Curve::Line(_)) { + if lean > 1e-9 || !self.rec.straight(side) { return None; } - let other = if side.front() == v { side.back() } else { side.front() }; - room = room.min((vtx(other) - vtx(v)).dot(t) * (self.fr.phi / 2.0).tan()); + let other = if a == v { b } else { a }; + room = room.min((self.rec.point(other)? - self.rec.point(v)?).dot(t) * (self.fr.phi / 2.0).tan()); } Some(room) } } -/// The direction `edge` leaves its end `v` in (along its first piece within `tol`). -fn leaving(edge: &mt::Edge, v: &mt::Vertex, tol: f64) -> Option { - use mt::{BoundedCurve, ParameterDivision1D}; - let curve = edge.curve(); - let pts = curve.parameter_division(curve.range_tuple(), tol.max(1e-6)).1; - let p = vtx(v); - let near = if crate::body::from_p3(*pts.first()?).dist(p) <= crate::body::from_p3(*pts.last()?).dist(p) { - pts.get(1)? - } else { - pts.get(pts.len().checked_sub(2)?)? - }; - (crate::body::from_p3(*near) - p).normalized() -} - -/// Build the blend of the edge of `s` with the radius `law` (its positions from the edge's front). -fn build(body: &Body, s: &EdgeSetup, edge: &mt::Edge, law: &RadiusSpline) -> Result { - let (faces, fr, tol) = (&s.faces, &s.fr, s.tol); - let (v0, v1, p0, p1, d) = (&s.v0, &s.v1, s.p0, s.p1, s.d); - // The end radii are the first and last control radii (exact: a zero end closes the blend). - let (ra, rb) = (law.radii.first().copied().unwrap_or(0.0), law.radii.last().copied().unwrap_or(0.0)); - let back = |r: f64| s.back(r); - let arc_mid = |p: Vec3, sb: f64, r: f64| { - let c = p + fr.t1 * sb + fr.n1 * (r * fr.side); - c + (p - c).normalized().unwrap_or(-fr.n1) * r - }; - // Each end: the blend's corners on the two faces and, with a radius, the arc between them, - // the end face and its edges along the two faces. At a zero radius the blend closes to the - // end vertex, and the faces around it stay as they are. - struct Arc { - v: mt::Vertex, - g: usize, - e1: mt::Edge, - e2: mt::Edge, - edge: mt::Edge, +/// The points of edge `e` from start to end: its ends for a line, else its curve divided until +/// each chord lies within `tol` of the curve at its middle (at most `MAX_POINTS`). +fn edge_points(rec: &Faces, e: usize, tol: f64) -> Option> { + const MAX_POINTS: usize = 100_000; + let (a, b) = rec.ends(e)?; + if rec.straight(e) { + return Some(vec![a, b]); } - struct End { - a: mt::Vertex, - b: mt::Vertex, - arc: Option, + let edge = rec.rec.edges.get(e)?; + let c = CurveEval::new(edge.parameters()).ok()?; + let [t0, t1] = edge.interval; + // Start from 8 pieces (a closed or turning curve's chord says nothing of its middle). + let mut out = vec![a]; + let mut stack: Vec<(f64, Vec3, f64, Vec3, usize)> = Vec::new(); + let pieces = 8; + let at = |k: usize| t0 + (t1 - t0) * k as f64 / pieces as f64; + for k in (0..pieces).rev() { + stack.push((at(k), c.point(at(k))?, at(k + 1), c.point(at(k + 1))?, 0)); } - let mut ends = Vec::new(); - for (v, p, r) in [(v0, p0, ra), (v1, p1, rb)] { - if r == 0.0 { - ends.push(End { a: v.clone(), b: v.clone(), arc: None }); + while let Some((ta, pa, tb, pb, depth)) = stack.pop() { + let tm = (ta + tb) / 2.0; + let pm = c.point(tm)?; + if depth < 24 && pm.dist_to_segment(pa, pb) > tol { + stack.push((tm, pm, tb, pb, depth + 1)); + stack.push((ta, pa, tm, pm, depth + 1)); continue; } - let at_v: Vec = (0..faces.len()).filter(|i| faces.get(*i).is_some_and(|f| f.vertex_iter().any(|x| &x == v))).collect(); - let others: Vec = at_v.iter().copied().filter(|i| *i != fr.i1 && *i != fr.i2).collect(); - let [g] = others[..] else { return Err(unsupported("each end of the edge must touch exactly one more face")) }; - let gf = faces.get(g).ok_or_else(|| KernelError::Failed("face".into()))?; - let ng = plane_normal(gf).ok_or_else(|| unsupported("the faces at the edge ends must be planar"))?; - if ng.dot(d).abs() < 1.0 - 1e-9 { - return Err(unsupported("the faces at the edge ends must be perpendicular to the edge")); + out.push(pb); + if out.len() > MAX_POINTS { + return None; } - let shared = |fi: usize| -> Result { - let f = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?; - f.edge_iter() - .find(|e| e.id() != edge.id() && (e.front() == v || e.back() == v) && gf.edge_iter().any(|x| x.id() == e.id())) - .ok_or_else(|| unsupported("unexpected corner topology")) - }; - let (e1, e2) = (shared(fr.i1)?, shared(fr.i2)?); - for (e, t) in [(&e1, fr.t1), (&e2, fr.t2)] { - if !matches!(e.curve(), mt::Curve::Line(_)) { - return Err(unsupported("the edges at the corners must be straight")); + } + Some(out) +} + +/// An extended corner edge must stay in the trimmed planar face `f`, not just its infinite +/// plane: the segment from `p` (on its boundary) to `q` crosses or touches no boundary after +/// `p`, holes included, and `q` is inside. Curved boundaries are divided more finely than the +/// clearance. +fn extension_fits(rec: &Faces, f: usize, p: Vec3, q: Vec3, tol: f64) -> bool { + let tol = tol.max(4e-6); + let (Some(x), Some(n)) = ((q - p).normalized(), rec.plane_normal(f)) else { return false }; + let y = n.cross(x); + let len = p.dist(q); + if !len.is_finite() || len <= tol { + return false; + } + let mut inside = false; + for u in rec.uses(f) { + let Some(points) = edge_points(rec, u.edge as usize, tol * 0.25) else { return false }; + if points.len() < 2 { + return false; + } + for pair in points.windows(2) { + let [a, b] = pair else { return false }; + let a = *a - p; + let b = *b - p; + let (ax, ay, bx, by) = (a.dot(x), a.dot(y), b.dot(x), b.dot(y)); + if ![ax, ay, bx, by].iter().all(|v| v.is_finite()) { + return false; } - let other = if e.front() == v { vtx(e.back()) } else { vtx(e.front()) }; - let along = (other - p).dot(t); - if (other - p - t * along).len() > tol * 100.0 + 1e-7 { - return Err(unsupported("the faces at the edge ends must be perpendicular to the edge")); + // Contact/overlap with the extension, except its original endpoint. + if (ay.abs() <= tol && by.abs() <= tol && ax.max(bx) > tol && ax.min(bx) <= len + tol) + || [(ax, ay), (bx, by)].iter().any(|(u, v)| *u > tol && *u <= len + tol && v.abs() <= tol) + { + return false; } - if along <= back(r) + tol { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - } - let sb = back(r); - let (a, b) = (builder::vertex(p3(p + fr.t1 * sb)), builder::vertex(p3(p + fr.t2 * sb))); - let arc = builder::circle_arc(&a, &b, p3(arc_mid(p, sb, r))); - ends.push(End { a, b, arc: Some(Arc { v: v.clone(), g, e1, e2, edge: arc }) }); - } - let [end0, end1] = &ends[..] else { return Err(KernelError::Failed("ends".into())) }; - if let (Some(x), Some(y)) = (&end0.arc, &end1.arc) - && x.g == y.g - { - return Err(unsupported("both ends touch the same face")); - } - // Along the edge the band the blend takes from each face stays inside it. - const STATIONS: usize = 256; - if (1..STATIONS).any(|k| !s.band_fits(k as f64 / STATIONS as f64, law.eval(k as f64 / STATIONS as f64))) { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - // Contact curves: the edge moved along each face by the setback of the radius there. - let g = law.greville(); - let contact = |t: Vec3, a: &mt::Vertex, b: &mt::Vertex| -> Result { - if law.degree == 1 && law.radii.len() == 2 { - return Ok(builder::line(a, b)); - } - let ctrl: Vec = g.iter().zip(&law.radii).map(|(gj, rj)| p3(p0 + (p1 - p0) * *gj + t * back(*rj))).collect(); - let c = mt::BSplineCurve::try_new(mt::KnotVec::from(law.knots.clone()), ctrl).map_err(|e| KernelError::Failed(format!("fillet: {e}")))?; - mt::Edge::try_new(a, b, mt::Curve::BSplineCurve(c)).map_err(|e| KernelError::Failed(format!("fillet: {e}"))) - }; - let la = contact(fr.t1, &end0.a, &end1.a)?; - let lb = contact(fr.t2, &end0.b, &end1.b)?; - let arcs = || [end0, end1].into_iter().filter_map(|end| end.arc.as_ref().map(|arc| (end, arc))); - let mut subst: HashMap = HashMap::new(); - for (end, arc) in arcs() { - for (e, nv) in [(&arc.e1, &end.a), (&arc.e2, &end.b)] { - let (f, bk) = (e.absolute_front(), e.absolute_back()); - let ne = if f == &arc.v { builder::line(nv, bk) } else { builder::line(f, nv) }; - subst.insert(e.id(), ne); - } - } - // The side edges at the ends are pieces of themselves; the contacts and end arcs are new. - let mut rec = crate::record::Rebuild::default(); - rec.pieces(&subst); - let mut new_faces: Vec = Vec::with_capacity(faces.len() + 1); - for (i, f) in faces.iter().enumerate() { - let nf = if i == fr.i1 { - let mut m = subst.clone(); - m.insert(edge.id(), la.clone()); - rebuild_face(f, &m, &[])? - } else if i == fr.i2 { - let mut m = subst.clone(); - m.insert(edge.id(), lb.clone()); - rebuild_face(f, &m, &[])? - } else if let Some((_, arc)) = arcs().find(|(_, arc)| arc.g == i) { - rebuild_face(f, &subst, std::slice::from_ref(&arc.edge))? - } else { - (*f).clone() - }; - rec.face(&nf, f); - new_faces.push(nf); - } - // The blend surface: rational quadratic arcs (tangent points and the edge point, middle - // weight sin(φ/2)) at each end, joined along the radius spline. - let w = (fr.phi / 2.0).sin(); - let h = |p: Vec3, wt: f64| mt::Vector4::new(p.x * wt, p.y * wt, p.z * wt, wt); - let row = |t: Vec3, wt: f64, off: bool| -> Vec { - g.iter().zip(&law.radii).map(|(gj, rj)| h(p0 + (p1 - p0) * *gj + if off { t * back(*rj) } else { Vec3::ZERO }, wt)).collect() - }; - let ctrl = vec![row(fr.t1, 1.0, true), row(fr.t1, w, false), row(fr.t2, 1.0, true)]; - let bsp = mt::BSplineSurface::new((mt::KnotVec::bezier_knot(2), mt::KnotVec::from(law.knots.clone())), ctrl); - let mut surf = mt::Surface::NurbsSurface(mt::NurbsSurface::new(bsp)); - // Outward: away from the arc centre on a convex edge, toward it on a concave one (at an - // end with a radius). - let (p, r) = if end0.arc.is_none() { (p1, rb) } else { (p0, ra) }; - let (c, mid) = (p + fr.t1 * back(r) + fr.n1 * (r * fr.side), arc_mid(p, back(r), r)); - let outward = (mid - c) * (-fr.side); - { - use mt::{ParametricSurface3D, SearchParameter}; - if let Some((u, v)) = surf.search_parameter(p3(mid), None, 100) { - let nn = surf.normal(u, v); - if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); + // Points within the clearance of the ray count as on it, so a shared endpoint + // contributes one crossing. + let ay = if ay.abs() <= tol { 0.0 } else { ay }; + let by = if by.abs() <= tol { 0.0 } else { by }; + if (ay > 0.0) != (by > 0.0) { + let hit = ax - ay * (bx - ax) / (by - ay); + if hit > tol && hit <= len + tol { + return false; + } + // Even-odd containment of q over all loops (outer boundary and holes). + if hit > len { + inside = !inside; + } } } } - // The blend face uses each new edge opposite to its neighbour; a closed end has no arc. - let arc_of = |end: &End| end.arc.as_ref().map(|a| a.edge.clone()); - let f1_forward = faces.get(fr.i1).is_some_and(|f| f.boundaries().iter().any(|w| w.edge_iter().any(|e| e.id() == edge.id() && e.front() == v0))); - let wire: mt::Wire = if f1_forward { - [arc_of(end0), Some(lb.clone()), arc_of(end1).map(|a| a.inverse()), Some(la.inverse())].into_iter().flatten().collect() - } else { - [Some(la.clone()), arc_of(end1), Some(lb.inverse()), arc_of(end0).map(|a| a.inverse())].into_iter().flatten().collect() - }; - let blend = mt::Face::try_new(vec![wire], surf).map_err(|e| KernelError::Failed(format!("fillet face: {e}")))?; - rec.blend(&blend, [edge.id()]); - new_faces.push(blend); - let solid: &Solid = &body.solid; - let mut shells = solid.boundaries().clone(); - if let Some(sh) = shells.get_mut(s.si) { - *sh = new_faces.into(); - } - let out = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("variable fillet produced an invalid solid: {e}")))?; - crate::record::rebuilt(out, &[solid], &rec) + inside } /// How much of the room along an edge a taper takes: its band stays within this fraction of each @@ -519,12 +407,11 @@ pub fn taper(body: &Body, edge_at: Vec3, radius: f64) -> Result { if !(radius.is_finite() && radius > 1e-6 && radius < 1e6) { return Err(KernelError::Invalid("fillet radii must be positive".into())); } - let edge = crate::surfaces::edge_near(body, edge_at).ok_or_else(|| KernelError::Invalid(format!("no edge at {edge_at:?}")))?; guard("taper", || { - let s = EdgeSetup::new(body, &edge)?; + let s = EdgeSetup::new(body, edge_at)?; let leans = || unsupported("a taper needs each end of the edge square to it or closing to a point"); - let room0 = s.end_room(&s.v0, -s.d).ok_or_else(leans)?; - let room1 = s.end_room(&s.v1, s.d).ok_or_else(leans)?; + let room0 = s.end_room(s.v0, s.d * -1.0).ok_or_else(leans)?; + let room1 = s.end_room(s.v1, s.d).ok_or_else(leans)?; if room0 == 0.0 && room1 == 0.0 { return Err(too_large("the faces close to a point at both ends of the edge")); } @@ -555,6 +442,7 @@ pub fn taper(body: &Body, edge_at: Vec3, radius: f64) -> Result { /// on alone gets a [`taper`], and the rest the constant radius. The result and the taper of each /// edge (in `edges`' order; None where the radius is constant). pub fn fillet_tapered(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body, Vec>)> { + let _span = solidcraft_profile::span("kernel", "fillet_tapered"); let why = match crate::fillet(body, edges, radius) { Err(KernelError::TooLarge(why)) => why, other => return other.map(|b| (b, vec![None; edges.len()])), @@ -587,11 +475,10 @@ pub fn fillet_tapered(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body, } /// Chord-length fillet: each edge rounded so that the blend is `chord` wide across, from contact -/// to contact at every station. A straight edge between planar faces is built exactly, the radius -/// `chord / (2 cos(φ/2))` from its face angle and edges sharing that angle blended together; a -/// curved edge, or one between curved faces (or a chain of selected edges running on into one), -/// is rolled by a ball whose radius gives the same width, which follows the face angle along it. +/// to contact at every station (SMLib's constant-chord round), its radius following the face +/// angle along the edge. pub fn fillet_chord(body: &Body, edges: &[Vec3], chord: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "fillet_chord"); body.require_brep("fillet")?; if !(chord.is_finite() && chord > 1e-6 && chord < 1e6) { return Err(KernelError::Invalid("the chord length must be positive".into())); @@ -599,70 +486,34 @@ pub fn fillet_chord(body: &Body, edges: &[Vec3], chord: f64) -> Result { if edges.is_empty() || edges.len() > 1000 { return Err(KernelError::Invalid("select 1…1000 edges".into())); } - let found: Vec = edges - .iter() - .map(|p| crate::surfaces::edge_near(body, *p).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))) - .collect::>()?; - // The exact radius of a straight edge between planar faces; None where the rolling ball has to - // take the edge (a curved edge, or one between curved faces). - let exact_radius = |e: &mt::Edge| -> Option { - if !matches!(e.curve(), mt::Curve::Line(_)) { - return None; - } - let shell = body.solid.boundaries().iter().find(|sh| sh.edge_iter().any(|x| x.id() == e.id()))?; - let faces: Vec<&mt::Face> = shell.face_iter().collect(); - Some(chord_radius(chord, edge_frame(&faces, e).ok()?.phi)) - }; - // A straight edge running on smoothly into a selected curved one goes with it: the ball rolls - // along the chain, so blending the parts apart would leave a step at their joint. - let meets = |a: &mt::Edge, b: &mt::Edge| [a.front(), a.back()].into_iter().any(|v| v == b.front() || v == b.back()); - let mixed = |e: &mt::Edge| found.iter().any(|f| f.id() != e.id() && exact_radius(f).is_none() && meets(e, f)); - // Radius per edge from its face angle; the rest roll a ball along their chain. - let mut groups: Vec<(f64, Vec)> = Vec::new(); - let mut rolled: Vec> = Vec::new(); - let mut done: Vec = Vec::new(); - for (p, e) in edges.iter().zip(&found) { - if let Some(r) = exact_radius(e).filter(|_| !mixed(e)) { - match groups.iter_mut().find(|(gr, _)| (gr - r).abs() <= 1e-9 * r) { - Some((_, v)) => v.push(*p), - None => groups.push((r, vec![*p])), - } - continue; - } - if done.contains(&e.id()) { - continue; - } - // The whole smooth chain (as the constant-radius path rolls it): a ball cannot stop - // where the edge runs on, so the chain's other edges are blended with it. - let chain = crate::blend::smooth_chain(&body.solid, e).unwrap_or_else(|| vec![e.id()]); - done.extend(chain.iter().copied()); - rolled.push(edges.iter().zip(&found).filter(|(_, f)| chain.contains(&f.id())).map(|(p, _)| *p).collect()); - } - // Each step's result carries its history over `[body]`. - let counts = crate::record::counts(&[body]); - let mut cur = crate::boolean_record::operand(body, 0, &counts); - for (r, pts) in groups { - cur = crate::record::after(crate::fillet(&cur, &pts, r)?, &cur, &counts); - } - for picks in rolled { - // The chain as the current body has it: the blends before it rebuilt the faces it runs - // through, and a rebuilt face carries its edges again. - let edges: Vec = picks.iter().filter_map(|p| crate::surfaces::edge_near(&cur, *p)).collect(); - let Some(first) = edges.first() else { continue }; - let keep = |x: &mt::Edge| edges.iter().any(|e| e.id() == x.id()); - let chain = crate::blend::smooth_chain_within(&cur.solid, first, &keep).unwrap_or_else(|| vec![first.id()]); - let (made, rec) = crate::guard("chord fillet", || crate::curveblend::curve_blend_chord(&cur.solid, &chain, cur.size(), chord, true))?; - let step = crate::record::rebuilt(made, &[&cur.solid], &rec)?; - cur = crate::record::after(step, &cur, &counts); - } - Ok(cur) + crate::blend_smlib::fillet_chord(body, edges, chord) } #[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; use crate::{box_solid, measure}; + /// The number of edge uses of each face of `b`, and its vertex points. + fn faces_and_vertices(b: &Body) -> (Vec, Vec) { + let rec = crate::native::brep_record(b).unwrap(); + let sides = rec + .faces + .iter() + .map(|f| { + f.loops + .iter() + .map(|l| match l { + solidcore_record::brep::Loop::Edges { edges } => edges.len(), + solidcore_record::brep::Loop::Vertex { .. } => 0, + }) + .sum() + }) + .collect(); + (sides, rec.vertices.iter().map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])).collect()) + } + fn rel(a: f64, b: f64) -> f64 { (a - b).abs() / b.abs().max(1e-9) } @@ -695,16 +546,17 @@ mod tests { assert_eq!((less.eval(0.0), less.eval(1.0)), (2.0, 3.0)); } - /// The material a variable fillet removes from a right-angled edge of length L, radius - /// running r0 → r1: ∫ (1 − π/4) r(t)² dt = (1 − π/4) L (r0² + r0 r1 + r1²) / 3. + /// The material a variable fillet removes from a right-angled edge, radius running r0 → r1: + /// its balls' union (`removed_by_balls`; the balls' great circles, (1 − π/4) L (r0² + r0 r1 + + /// r1²) / 3, take more), to 1e-4 of itself. #[test] fn variable_radius_on_a_box_edge() { let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); // The edge along y at x = 10, z = 30; radius 2 at y = 0, 5 at y = 20. let f = fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), 2.0, 5.0).unwrap(); - let removed = (1.0 - std::f64::consts::FRAC_PI_4) * 20.0 * (4.0 + 10.0 + 25.0) / 3.0; + let removed = removed_by_balls(20.0, &|u| 2.0 + 3.0 * u, &open, &[]); let v = measure(&f).unwrap().volume; - assert!(rel(v, 6000.0 - removed) < 1e-4, "{v} vs {}", 6000.0 - removed); + assert!(rel(6000.0 - v, removed) < 1e-4, "{} removed vs {removed}", 6000.0 - v); // Started from the other end: the same solid. let h = fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 20.0, 30.0), 5.0, 2.0).unwrap(); assert!(rel(measure(&h).unwrap().volume, v) < 1e-9); @@ -712,30 +564,44 @@ mod tests { let g = fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), 3.0, 3.0).unwrap(); let k = crate::fillet(&b, &[Vec3::new(10.0, 10.0, 30.0)], 3.0).unwrap(); assert!(rel(measure(&g).unwrap().volume, measure(&k).unwrap().volume) < 1e-6); - // Too big for the faces: refused. - assert!(fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), 2.0, 50.0).is_err()); + // Wider than the faces: past r = 10 the contact on the top leaves it across its far edge + // x = 0 (past r = 30 the one on the side across its bottom), cliffs. The round is built as + // if the faces went on, and what it removes is cut from the box: the balls' union inside + // the box's section, 10 along the top and 30 down the side (the great circles' would take + // 2453.81, near twice as much). + let w = fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), 2.0, 50.0).unwrap(); + let removed_w = removed_by_balls(20.0, &|u| 2.0 + 48.0 * u, &slab, &[20.0 * 8.0 / 48.0, 20.0 * 28.0 / 48.0]); + let vw = measure(&w).unwrap().volume; + assert!(rel(6000.0 - vw, removed_w) < 1e-4, "{} removed vs {removed_w}", 6000.0 - vw); } - /// A radius through a middle point: straight pieces (exact: each piece removes - /// (1 − π/4) L (a² + ab + b²) / 3), and smooth (the removed volume integrates the law). + /// A radius through a middle point, straight pieces 2 → 4 → 2: a corner in the law, where the + /// two sides' rounds cross and each ends where they do; the balls' union takes 39.541034 + /// (the halves' great circles would take 40.0590). + #[test] + fn variable_radius_with_a_corner_through_a_middle_point() { + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); + let (at, start) = (Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0)); + let f = fillet_variable_points(&b, at, start, &[(0.0, 2.0), (0.5, 4.0), (1.0, 2.0)], false).unwrap(); + let removed = removed_by_balls(20.0, &|u| 4.0 - 4.0 * (u - 0.5).abs(), &open, &[10.0]); + assert!((removed - 39.541034).abs() < 1e-5, "{removed}"); + let v = measure(&f).unwrap().volume; + assert!(rel(6000.0 - v, removed) < 1e-4, "{} removed vs {removed}", 6000.0 - v); + assert_eq!(f.unmeshed_faces(), 0); + } + + /// A radius through a middle point, smooth: the removed volume is the balls' union. #[test] fn variable_radius_through_a_middle_point() { let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); let (at, start) = (Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0)); - let k = 1.0 - std::f64::consts::FRAC_PI_4; let pts = [(0.0, 2.0), (0.5, 4.0), (1.0, 2.0)]; - let f = fillet_variable_points(&b, at, start, &pts, false).unwrap(); - let removed = 2.0 * k * 10.0 * (4.0 + 8.0 + 16.0) / 3.0; - let v = measure(&f).unwrap().volume; - assert!(rel(v, 6000.0 - removed) < 1e-4, "{v} vs {}", 6000.0 - removed); - assert_eq!(f.unmeshed_faces(), 0); let s = fillet_variable_points(&b, at, start, &pts, true).unwrap(); let law = RadiusSpline::through(&pts, true); - let n = 20000; - let integral: f64 = (0..n).map(|i| law.eval((i as f64 + 0.5) / n as f64).powi(2)).sum::() / n as f64 * 20.0; assert!((law.eval(0.5) - 4.0).abs() < 1e-12 && (law.eval(0.0) - 2.0).abs() < 1e-12); + let removed = removed(&law, 20.0); let v = measure(&s).unwrap().volume; - assert!(rel(v, 6000.0 - k * integral) < 1e-4, "{v} vs {}", 6000.0 - k * integral); + assert!(rel(6000.0 - v, removed) < 1e-4, "{} removed vs {removed}", 6000.0 - v); // Unsorted, from the other end: the same. let r = fillet_variable_points(&b, at, Vec3::new(10.0, 20.0, 30.0), &[(1.0, 2.0), (0.0, 2.0), (0.5, 4.0)], true).unwrap(); assert!(rel(measure(&r).unwrap().volume, v) < 1e-9); @@ -747,32 +613,33 @@ mod tests { } /// The radius running down to zero at one end: the blend closes to the corner, a three-sided - /// face, and the end face there is untouched. Removed (1 − π/4) L r0² / 3 when linear. + /// face, and the end face there is untouched. Removed: the balls' union (a cone to its apex + /// when linear, 22.594877; the great circles' (1 − π/4) L r0² / 3 would take 22.8945). #[test] fn variable_radius_down_to_zero_at_one_end() { let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); let (at, start, end) = (Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), Vec3::new(10.0, 20.0, 30.0)); - let k = 1.0 - std::f64::consts::FRAC_PI_4; + let cone = removed_by_balls(20.0, &|u| 4.0 - 4.0 * u, &open, &[]); + assert!((cone - 22.594877).abs() < 1e-5, "{cone}"); for (r0, r1) in [(4.0, 0.0), (0.0, 4.0)] { let f = fillet_variable(&b, at, start, r0, r1).unwrap(); let v = measure(&f).unwrap().volume; - assert!(rel(v, 6000.0 - k * 20.0 * 16.0 / 3.0) < 1e-4, "{r0} → {r1}: {v}"); + assert!(rel(6000.0 - v, cone) < 1e-4, "{r0} → {r1}: {} removed vs {cone}", 6000.0 - v); assert_eq!(f.unmeshed_faces(), 0); - let faces: Vec<&mt::Face> = f.solid.boundaries().iter().flat_map(|sh| sh.face_iter()).collect(); + let (faces, vertices) = faces_and_vertices(&f); assert_eq!(faces.len(), 7); // The blend is three-sided; the closed end's corner is still a box corner. - assert!(faces.iter().any(|fc| fc.edge_iter().count() == 3)); + assert!(faces.contains(&3)); let corner = if r1 == 0.0 { end } else { start }; - assert!(faces.iter().flat_map(|fc| fc.vertex_iter()).any(|x| vtx(&x).dist(corner) < 1e-9)); + assert!(vertices.iter().any(|x| x.dist(corner) < 1e-9)); } // Through a middle point, smooth, closing at the far end. let pts = [(0.0, 3.0), (0.5, 4.0), (1.0, 0.0)]; let s = fillet_variable_points(&b, at, start, &pts, true).unwrap(); let law = RadiusSpline::through(&pts, true); - let n = 20000; - let integral: f64 = (0..n).map(|i| law.eval((i as f64 + 0.5) / n as f64).powi(2)).sum::() / n as f64 * 20.0; + let removed = removed(&law, 20.0); let v = measure(&s).unwrap().volume; - assert!(rel(v, 6000.0 - k * integral) < 1e-4, "{v} vs {}", 6000.0 - k * integral); + assert!(rel(6000.0 - v, removed) < 1e-4, "{} removed vs {removed}", 6000.0 - v); // Zero at both ends, zero in the middle, a smooth radius dipping below zero, or a radius // too small to build: refused. assert!(fillet_variable(&b, at, start, 0.0, 0.0).is_err()); @@ -783,38 +650,186 @@ mod tests { assert!(fillet_variable(&b, at, start, 4.0, 1e-9).is_err()); } - /// A prism of the polygon `pts` (in xy) from z = 0 to `h`. - fn prism(pts: &[(f64, f64)], h: f64) -> Body { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + /// A prism of the polygon `pts` (in xy) from z = `z0` to `z1`. + fn prism_between(pts: &[(f64, f64)], z0: f64, z1: f64) -> Body { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; let outer = Loop2::polygon(&pts.iter().map(|(x, y)| Vec2::new(*x, *y)).collect::>()); - crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0.0, h).unwrap().pop().unwrap() + crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], z0, z1).unwrap().pop().unwrap() } - /// The material a right-angled blend with the radius `law` removes along an edge of length L: - /// ∫ (1 − π/4) r² over the edge. + /// A prism of the polygon `pts` (in xy) from z = 0 to `h`. + fn prism(pts: &[(f64, f64)], h: f64) -> Body { + prism_between(pts, 0.0, h) + } + + /// A plate 15 high whose top narrows from 20 to 2 mm along 40 mm (the trapezoid (0, 0), + /// (40, 0), (40, 2), (0, 20)), against a wall standing behind its slanted side from z = -15 + /// to 30: the plate's top and bottom end on the wall in concave edges, so a blend of its + /// front edges can't run past them (no cliff to cut over). 6600 + 20 · 38 · 45. + fn ledge() -> Body { + let plate = prism(&[(0.0, 0.0), (40.0, 0.0), (40.0, 2.0), (0.0, 20.0)], 15.0); + let wall = prism_between(&[(40.0, 2.0), (0.0, 20.0), (0.0, 30.0), (40.0, 30.0)], -15.0, 30.0); + crate::boolean(&plate, &wall, crate::BoolOp::Union).unwrap().unwrap() + } + + /// Simpson's rule for `f` on [a, b] in `n` (even) panels. + fn simpson(f: impl Fn(f64) -> f64, a: f64, b: f64, n: usize) -> f64 { + let h = (b - a) / n as f64; + (0..=n) + .map(|i| { + f(a + i as f64 * h) + * if i == 0 || i == n { + 1.0 + } else if i % 2 == 1 { + 4.0 + } else { + 2.0 + } + }) + .sum::() + * h + / 3.0 + } + + /// The material a variable round removes from a right-angled edge of length `len`: what no + /// ball reaches, the round being the union of its balls (their envelope; each ball touches it + /// along the circle square to the line of centres, not its great circle, as the radius + /// varies). The ball at s along the edge has radius `law(s / len)` (the law going on past the + /// ends along its end slopes) and its centre that far from both faces. In each plane square + /// to the edge at x, the ray from the edge at angle θ from the first face meets the union + /// first at the least entry over the balls, and the corner up to there is taken, as far as + /// `room(x, θ)` (the body's section along the ray; ∞ where it does not end): ∫ ρ²/2 dθ, + /// integrated over x, both by Simpson's rule, split at `kinks` (where the law turns). + pub(crate) fn removed_by_balls(len: f64, law: &dyn Fn(f64) -> f64, room: &dyn Fn(f64, f64) -> f64, kinks: &[f64]) -> f64 { + let h = 1e-7; + let (k0, k1) = ((law(h) - law(0.0)) / (h * len), (law(1.0) - law(1.0 - h)) / (h * len)); + let r = |s: f64| { + if s < 0.0 { + law(0.0) + k0 * s + } else if s > len { + law(1.0) + k1 * (s - len) + } else { + law(s / len) + } + }; + let big = (0..=1000).map(|i| law(i as f64 / 1000.0)).fold(0.0f64, f64::max); + let entry = |x: f64, c: f64, sn: f64, s: f64| { + let rr = r(s); + let p = rr * (c + sn); + let disc = p * p - (x - s) * (x - s) - rr * rr; + if rr > 0.0 && disc >= 0.0 { p - disc.sqrt() } else { f64::INFINITY } + }; + let rho = |x: f64, t: f64| { + let (c, sn) = (t.cos(), t.sin()); + let (lo, hi, scan) = (x - 1.5 * big, x + 1.5 * big, 400); + let step = (hi - lo) / scan as f64; + let (mut best, mut at) = (f64::INFINITY, x); + for i in 0..=scan { + let s = lo + i as f64 * step; + let e = entry(x, c, sn, s); + if e < best { + (best, at) = (e, s); + } + } + let (mut a, mut b, g) = (at - step, at + step, (5f64.sqrt() - 1.0) / 2.0); + for _ in 0..80 { + let (m1, m2) = (b - g * (b - a), a + g * (b - a)); + if entry(x, c, sn, m1) < entry(x, c, sn, m2) { + b = m2; + } else { + a = m1; + } + } + best.min(entry(x, c, sn, 0.5 * (a + b))) + }; + // The rays meet the union tangentially at the faces (ρ goes as the root of the angle + // there): θ = π/4 (1 − cos(π q)) makes the integrand smooth in q. + let area = |x: f64| { + let q = std::f64::consts::PI; + simpson( + |u: f64| { + let t = q / 4.0 * (1.0 - (q * u).cos()); + let p = rho(x, t).min(room(x, t)); + let p = if p.is_finite() { p } else { 0.0 }; + 0.5 * p * p * q * q / 4.0 * (q * u).sin() + }, + 0.0, + 1.0, + 128, + ) + }; + let mut ends = vec![0.0]; + ends.extend(kinks.iter().copied().filter(|k| *k > 0.0 && *k < len)); + ends.push(len); + ends.windows(2).map(|w| simpson(area, w[0], w[1], 2 * ((64.0 * (w[1] - w[0]) / len).ceil() as usize).max(1))).sum() + } + + /// No end to the body's section: the faces go on past the round. + fn open(_x: f64, _t: f64) -> f64 { + f64::INFINITY + } + + /// The 10 x 20 x 30 box's section about its edge x = 10, z = 30: 10 along the top, 30 down + /// the side. + fn slab(_x: f64, t: f64) -> f64 { + (10.0 / t.cos().max(1e-300)).min(30.0 / t.sin().max(1e-300)) + } + + /// The material a right-angled blend with the radius `law` removes along an edge of length L + /// where the faces go on past it: the union of its balls. fn removed(law: &RadiusSpline, len: f64) -> f64 { - let n = 20000; - (1.0 - std::f64::consts::FRAC_PI_4) * (0..n).map(|i| law.eval((i as f64 + 0.5) / n as f64).powi(2)).sum::() / n as f64 * len + removed_by_balls(len, &|u| law.eval(u), &open, &[]) } /// The volume of a fine tessellation: at a blend closed to a point `measure` takes a /// coarser mesh of the blend, a few mm³ off on these parts. fn fine_volume(b: &Body) -> f64 { - b.tessellate_with(5e-4, true).unwrap().measure().volume + b.mesh(&crate::MeshTolerance::chord(5e-4)).unwrap().measure().volume } /// A taper on the top front edge of a wedge, whose top face narrows to a point, and of a - /// trapezoid, whose top face narrows to 2 mm: the radius asked for where it fits, below - /// 0.9 of the room everywhere, down to zero at the wedge's tip and to 1.8 mm at the - /// trapezoid's narrow end; the volume integrates the spline. + /// plate against a wall, whose top face narrows to 2 mm: the radius asked for where it fits, + /// below 0.9 of the room everywhere, down to zero at the wedge's tip and to 1.8 mm at the + /// plate's narrow end; the volume integrates the spline. On the free-standing wedge R16 runs + /// over the top's far edge and the front's bottom edge (cliffs), so it is built as if those + /// faces went on and cut from the wedge (the blend-overflow decision, 237f0ae74), and a + /// tapered fillet keeps it; against the wall the plate's R3 has no room at the narrow end + /// and tapers. #[test] fn taper_follows_the_room_along_the_edge() { let (at, start) = (Vec3::new(20.0, 0.0, 15.0), Vec3::new(0.0, 0.0, 15.0)); + let plate = ledge(); + let full = 6600.0 + 20.0 * 38.0 * 45.0; + assert!(matches!(crate::fillet(&plate, &[at], 3.0), Err(KernelError::TooLarge(_)))); + let (f, tapers) = fillet_tapered(&plate, &[at], 3.0).unwrap(); + let t = tapers.into_iter().flatten().next().unwrap(); + let law = if t.start.dist(start) < 1e-9 { t.spline } else { t.spline.reversed() }; + assert!((law.eval(0.0) - 3.0).abs() < 1e-9 && (law.eval(1.0) - 1.8).abs() < 1e-9); + let v = fine_volume(&f); + assert!(rel(v, full - removed(&law, 40.0)) < 1e-4, "{v} vs {}", full - removed(&law, 40.0)); + // A radius that fits stays constant. + let (g, tapers) = fillet_tapered(&plate, &[at], 1.0).unwrap(); + assert_eq!(tapers, vec![None]); + assert!(rel(measure(&g).unwrap().volume, measure(&crate::fillet(&plate, &[at], 1.0).unwrap()).unwrap().volume) < 1e-12); + let wedge = prism(&[(0.0, 0.0), (40.0, 0.0), (0.0, 20.0)], 15.0); - assert!(matches!(crate::fillet(&wedge, &[at], 16.0), Err(KernelError::TooLarge(_)))); + // At x the section is the rectangle [0, w] × [0, 15], w = 20 (1 − x/40), less the part + // of the 16 × 16 square at the edge outside the circle about (16, 16): integrated along x. + let cut = |w: f64| { + let (r, s, t) = (16.0f64, 16.0f64.min(w), 15.0); + let f = |v: f64| 0.5 * (v * (r * r - v * v).max(0.0).sqrt() + r * r * (v / r).clamp(-1.0, 1.0).asin()); + let s1 = (r - (r * r - (r - t) * (r - t)).sqrt()).min(s); + t * s1 + r * (s - s1) - (f(r - s1) - f(r - s)) + }; + let n = 20000; + let removed16: f64 = (0..n).map(|i| cut(20.0 * (1.0 - (i as f64 + 0.5) / n as f64))).sum::() * 40.0 / n as f64; + let (f, tapers) = fillet_tapered(&wedge, &[at], 16.0).unwrap(); + assert_eq!(tapers, vec![None]); + let v = measure(&f).unwrap().volume; + assert!(rel(v, 6000.0 - removed16) < 1e-6, "{v} vs {}", 6000.0 - removed16); + // The taper the room gives: the top face is 20 (1 − u) wide, the front 15 high. let t = taper(&wedge, at, 16.0).unwrap(); let law = if t.start.dist(start) < 1e-9 { t.spline.clone() } else { t.spline.reversed() }; - // The room: the top face is 20 (1 − u) wide, the front 15 high. for i in 0..=100 { let u = i as f64 / 100.0; let r = law.eval(u); @@ -822,26 +837,10 @@ mod tests { } assert_eq!(law.eval(1.0), 0.0); assert!((law.eval(0.0) - 13.5).abs() < 1e-9); - let (f, tapers) = fillet_tapered(&wedge, &[at], 16.0).unwrap(); - assert_eq!(tapers, vec![Some(t)]); + let f = fillet_variable_spline(&wedge, at, t.start, &t.spline).unwrap(); let v = fine_volume(&f); assert!(rel(v, 6000.0 - removed(&law, 40.0)) < 1e-4, "{v} vs {}", 6000.0 - removed(&law, 40.0)); - assert_eq!(f.unmeshed_faces(), 0); - let faces: Vec<&mt::Face> = f.solid.boundaries().iter().flat_map(|sh| sh.face_iter()).collect(); - assert!(faces.iter().any(|fc| fc.edge_iter().count() == 3)); - - let trap = prism(&[(0.0, 0.0), (40.0, 0.0), (40.0, 2.0), (0.0, 20.0)], 15.0); - assert!(matches!(crate::fillet(&trap, &[at], 3.0), Err(KernelError::TooLarge(_)))); - let (f, tapers) = fillet_tapered(&trap, &[at], 3.0).unwrap(); - let t = tapers.into_iter().flatten().next().unwrap(); - let law = if t.start.dist(start) < 1e-9 { t.spline } else { t.spline.reversed() }; - assert!((law.eval(0.0) - 3.0).abs() < 1e-9 && (law.eval(1.0) - 1.8).abs() < 1e-9); - let v = fine_volume(&f); - assert!(rel(v, 6600.0 - removed(&law, 40.0)) < 1e-4, "{v} vs {}", 6600.0 - removed(&law, 40.0)); - // A radius that fits stays constant. - let (g, tapers) = fillet_tapered(&trap, &[at], 1.0).unwrap(); - assert_eq!(tapers, vec![None]); - assert!(rel(measure(&g).unwrap().volume, measure(&crate::fillet(&trap, &[at], 1.0).unwrap()).unwrap().volume) < 1e-12); + assert!(f.validity().is_empty(), "{:?}", f.validity()); } /// A radius spline given directly: a cubic with its control radii pulling the radius up in @@ -860,7 +859,11 @@ mod tests { assert!(fillet_variable_spline(&b, at, start, &unclamped).is_err()); let dips = RadiusSpline { radii: vec![2.0, 0.0, 0.0, 3.0, 2.0], ..law.clone() }; assert!(fillet_variable_spline(&b, at, start, &dips).is_err()); - // A middle radius beyond the faces: too large. + // A middle radius up to 21.25 (on the top 10 wide), rising and falling so fast that the + // balls' envelope folds over itself at the peak: for the balls' family + // F(y, p) = |p - c(y)|² - r(y)² the touch arc there has F_yy down to -8.88 (where the touch + // circles move back along the edge). Refused, never built folded (the balls' great + // circles, which never fold, built it to 726.53 removed against the union's 332.2). let big = RadiusSpline { radii: vec![2.0, 2.0, 40.0, 3.0, 2.0], ..law }; assert!(matches!(fillet_variable_spline(&b, at, start, &big), Err(KernelError::TooLarge(_)))); } diff --git a/crates/kernel/src/blend_vertex.rs b/crates/kernel/src/blend_vertex.rs deleted file mode 100644 index 018cf5c92..000000000 --- a/crates/kernel/src/blend_vertex.rs +++ /dev/null @@ -1,404 +0,0 @@ -//! Fillets of the three edges at a convex vertex of any smooth faces, of one radius: the rounds -//! end in a piece of sphere, as they do at the corner of a box. -//! -//! The ball of the fillets' radius that touches the three faces there (its centre `c`, its -//! contacts `q`) ends each round: round `k` stops at the circle where the ball meets the plane -//! through `c` and the contacts of its two faces, and the sphere's patch joins the three circles. -//! The construction uses only what a round with a plane end does already: -//! 1. cut off the corner beyond the three planes (a skewed box whose three faces are those -//! planes), so each of the three edges ends square on a plane face; -//! 2. round the three edges one after another, each ending in its plane face, which a round's -//! end arc and the sides it uses up reduce to a quarter disc of the ball's section; -//! 3. replace the three quarter discs, which meet along radii at `c`, by the sphere's patch, -//! which has the three end arcs for its boundary. - -use std::collections::{HashMap, HashSet}; - -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt}; - -use crate::blend::{edge_mid, too_large, unsupported, vtx}; -use crate::body::{Body, Solid, from_p3, p3, v3}; -use crate::curveblend::project; -use crate::record; -use crate::{BoolOp, KernelError, Result}; - -/// Round the edges nearest the points, `radius` each. The three edges meeting at a vertex that -/// all lie among them end in a sphere; the others are rounded as they would be alone. -pub(crate) fn fillet_ball_vertices(body: &Body, edges: &[Vec3], radius: f64) -> Result { - body.require_brep("fillet")?; - if !(radius.is_finite() && radius > 1e-6 && radius < 1e6) { - return Err(KernelError::Invalid("fillet size must be positive".into())); - } - if edges.len() < 3 { - return Err(unsupported("a vertex with three rounded edges")); - } - let counts = record::counts(&[body]); - let mut cur = crate::boolean_record::healed(body)?; - let mut todo: Vec = edges.to_vec(); - let mut done = false; - while let Some((at, picks)) = find_vertex(&cur, &todo)? { - let next = round_vertex(&cur, at, radius)?; - cur = record::after(next, &cur, &counts); - todo.retain(|p| !picks.iter().any(|q| q.dist(*p) < 1e-12)); - done = true; - } - if !done { - return Err(unsupported("a vertex with three rounded edges")); - } - if todo.is_empty() { Ok(cur) } else { crate::blend::fillet(&cur, &todo, radius) } -} - -/// A vertex of three edges all among the picked ones (its position) and their picks. -fn find_vertex(cur: &Body, picks: &[Vec3]) -> Result)>> { - let size = cur.size(); - let tol = (size * 2e-3).max(1e-3); - let solid = cur.deep_copy(); - let all = Body::unique_edges(&solid); - // The picked edges, by identity, with the pick each came from. - let mut picked: Vec<(mt::EdgeID, Vec3)> = Vec::new(); - for p in picks { - let Some((idx, dist)) = cur.nearest_edge(*p, tol)? else { return Ok(None) }; - if dist > size * 0.05 + 1e-3 { - return Err(KernelError::Invalid(format!("no edge near {:?}", [p.x, p.y, p.z]))); - } - if let Some(e) = all.get(idx) - && !picked.iter().any(|(id, _)| *id == e.id()) - { - picked.push((e.id(), *p)); - } - } - let mut at_vertex: HashMap> = HashMap::new(); - for e in &all { - let Some((_, p)) = picked.iter().find(|(id, _)| *id == e.id()) else { continue }; - for v in [e.absolute_front(), e.absolute_back()] { - at_vertex.entry(v.id()).or_default().push((e.id(), *p)); - } - } - for (vid, list) in at_vertex { - let degree = all.iter().filter(|e| e.absolute_front().id() == vid || e.absolute_back().id() == vid).count(); - if list.len() == 3 && degree == 3 { - let v = all.iter().find_map(|e| [e.absolute_front(), e.absolute_back()].into_iter().find(|v| v.id() == vid)); - if let Some(v) = v { - return Ok(Some((vtx(v), list.iter().map(|(_, p)| *p).collect()))); - } - } - } - Ok(None) -} - -/// The ball touching three faces from inside, near the corner `v`: its centre and contacts. -struct Ball { - c: Vec3, - /// Contact with each face, and the face's outward normal there. - q: [Vec3; 3], -} - -fn ball_at(faces: &[&mt::Face; 3], v: Vec3, r: f64, tol: f64) -> Result { - let rows = |n: [Vec3; 3]| [[n[0].x, n[0].y, n[0].z], [n[1].x, n[1].y, n[1].z], [n[2].x, n[2].y, n[2].z]]; - let near = |p: Vec3, hint: &mut [Option<(f64, f64)>; 3]| -> Option<([Vec3; 3], [Vec3; 3])> { - let mut q = [Vec3::ZERO; 3]; - let mut n = [Vec3::ZERO; 3]; - for (i, f) in faces.iter().enumerate() { - let (qi, ni, uv) = project(f, p, hint[i])?; - (q[i], n[i], hint[i]) = (qi, ni, Some(uv)); - } - Some((q, n)) - }; - let mut hint = [None; 3]; - let (_, n0) = near(v, &mut hint).ok_or_else(|| unsupported("the faces at the vertex"))?; - // The planes' ball first: each face r inside its tangent plane at the vertex. - let x = crate::polyhedron::solve3_pub(rows(n0), [-r, -r, -r]).ok_or_else(|| unsupported("a vertex whose faces do not meet in a corner"))?; - let mut c = v + Vec3::new(x[0], x[1], x[2]); - for _ in 0..60 { - let (q, n) = near(c, &mut hint).ok_or_else(|| unsupported("the ball at the vertex"))?; - let g = [(c - q[0]).dot(n[0]) + r, (c - q[1]).dot(n[1]) + r, (c - q[2]).dot(n[2]) + r]; - let d = crate::polyhedron::solve3_pub(rows(n), [-g[0], -g[1], -g[2]]) - .ok_or_else(|| unsupported("a vertex whose faces do not meet in a corner"))?; - let dc = Vec3::new(d[0], d[1], d[2]); - c += dc; - if !c.is_finite() { - break; - } - if dc.len() < tol * 1e-3 && g.iter().all(|x| x.abs() < tol) { - let (q, n) = near(c, &mut hint).ok_or_else(|| unsupported("the ball at the vertex"))?; - // A convex corner: the vertex lies out from every face the ball touches. - if n.iter().any(|ni| (v - c).dot(*ni) < 0.25 * r) { - return Err(unsupported("rounds at a corner that is not convex")); - } - return Ok(Ball { c, q }); - } - } - Err(unsupported("the ball does not fit at the vertex")) -} - -/// Round the three edges at the vertex at `at`, ending in a sphere. -fn round_vertex(cur: &Body, at: Vec3, r: f64) -> Result { - let size = cur.size(); - let tol = (size * 1e-7).max(1e-9); - let solid = cur.deep_copy(); - let all = Body::unique_edges(&solid); - let face_list: Vec<&mt::Face> = solid.face_iter().collect(); - // The vertex, its three edges and the faces between them. - let v = all - .iter() - .flat_map(|e| [e.absolute_front().clone(), e.absolute_back().clone()]) - .find(|v| vtx(v).dist(at) <= size * 1e-9 + 1e-12) - .ok_or_else(|| KernelError::Failed("fillet vertex".into()))?; - let edges: Vec = all.iter().filter(|e| *e.absolute_front() == v || *e.absolute_back() == v).cloned().collect(); - let faces_of = |e: &mt::Edge| -> Vec { - (0..face_list.len()).filter(|i| face_list.get(*i).is_some_and(|f| f.edge_iter().any(|x| x.id() == e.id()))).collect() - }; - let mut around: Vec = Vec::new(); - for e in &edges { - for f in faces_of(e) { - if !around.contains(&f) { - around.push(f); - } - } - } - let [fa, fb, fc] = around[..] else { return Err(unsupported("a vertex of three faces")) }; - let (Some(a), Some(b), Some(c)) = (face_list.get(fa), face_list.get(fb), face_list.get(fc)) else { - return Err(KernelError::Failed("faces".into())); - }; - let faces = [*a, *b, *c]; - let ball = ball_at(&faces, vtx(&v), r, tol * 100.0)?; - // The plane of each edge's end: through the centre and the contacts of the edge's two faces, - // its normal out toward the vertex. - let mut normals: Vec = Vec::with_capacity(3); - for e in &edges { - let sides: Vec = faces_of(e).iter().filter_map(|f| around.iter().position(|x| x == f)).collect(); - let [i, j] = sides[..] else { return Err(unsupported("an edge not between two faces")) }; - let (Some(qi), Some(qj)) = (ball.q.get(i), ball.q.get(j)) else { return Err(KernelError::Failed("contacts".into())) }; - let m = (*qi - ball.c).cross(*qj - ball.c).normalized().ok_or_else(|| unsupported("a ball that touches an edge's faces at one point"))?; - normals.push(if m.dot(vtx(&v) - ball.c) < 0.0 { -m } else { m }); - } - let [m0, m1, m2] = normals[..] else { return Err(KernelError::Failed("planes".into())) }; - // The corner beyond the three planes, a skewed box from the centre along the three lines - // where two of the planes meet, long enough to hold the corner of the body. - let gen_ = |x: Vec3, y: Vec3, toward: Vec3| -> Result { - let g = x.cross(y).normalized().ok_or_else(|| unsupported("planes that do not meet in a corner"))?; - Ok(if g.dot(toward) < 0.0 { -g } else { g }) - }; - let reach = 3.0 * (vtx(&v).dist(ball.c) + r); - let (g0, g1, g2) = (gen_(m1, m2, m0)? * reach, gen_(m2, m0, m1)? * reach, gen_(m0, m1, m2)? * reach); - let unit = crate::build::box_solid(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0))?; - let m = [[g0.x, g0.y, g0.z, 0.0], [g1.x, g1.y, g1.z, 0.0], [g2.x, g2.y, g2.z, 0.0], [ball.c.x, ball.c.y, ball.c.z, 1.0]]; - let cutter = crate::ops::transform_matrix(&unit, m)?; - let notched = crate::ops::boolean(cur, &cutter, BoolOp::Cut)?.ok_or_else(|| unsupported("a corner this small"))?; - // The cut splits a curved face along the trace of its plane (the whole way across, not just - // where the plane cuts): the pieces are one face again. - let notched = crate::guard("merge split faces", || merge_split_faces(¬ched, cur, size))?; - // A point on what is left of each edge, half way from where its plane crosses it to its far end. - let mut picks: Vec = Vec::with_capacity(3); - for (e, m) in edges.iter().zip(&normals) { - picks.push(remaining_pick(e, &v, ball.c, *m)?); - } - // Round them one after another, in an order that works. - let mut last: Option = None; - for order in [[0usize, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] { - let mut step = notched.clone(); - let mut ok = true; - for k in order { - let Some(p) = picks.get(k) else { return Err(KernelError::Failed("pick".into())) }; - match crate::blend::fillet(&step, &[*p], r) { - Ok(b) => step = b, - Err(e) => { - last = Some(e); - ok = false; - break; - } - } - } - if ok { - return close_with_sphere(&step, &ball, [m0, m1, m2], r, vtx(&v)); - } - } - Err(last.unwrap_or_else(|| unsupported("the three rounds at a vertex"))) -} - -/// A point on edge `e` between where the plane (through `c`, normal `m`) crosses it and its far -/// end (the end that is not `v`). -fn remaining_pick(e: &mt::Edge, v: &mt::Vertex, c: Vec3, m: Vec3) -> Result { - use mt::{BoundedCurve, ParametricCurve}; - let curve = e.curve(); - let (lo, hi) = curve.range_tuple(); - // From the end at the vertex (outside the plane's far side) to the far end. - let (near, far) = if e.absolute_front() == v { (lo, hi) } else { (hi, lo) }; - let side = |t: f64| (from_p3(curve.subs(t)) - c).dot(m); - let (mut a, mut b) = (near, far); - if !(side(a) > 0.0 && side(b) < 0.0) { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - for _ in 0..80 { - let mid = 0.5 * (a + b); - if side(mid) > 0.0 { a = mid } else { b = mid } - } - Ok(from_p3(curve.subs(0.5 * (0.5 * (a + b) + far)))) -} - -/// `step` has the three rounds ending in three quarter discs; the sphere's patch takes their place. -fn close_with_sphere(step: &Body, ball: &Ball, planes: [Vec3; 3], r: f64, v: Vec3) -> Result { - let size = step.size(); - let on_tol = (size * 1e-6).max(1e-9); - let solid = step.deep_copy(); - let faces: Vec = solid.face_iter().cloned().collect(); - // The face in each plane: a plane face through the centre. - let mut discs: Vec = Vec::new(); - for m in planes { - let found = faces.iter().position(|f| { - crate::blend::plane_normal(f).is_some_and(|n| n.dot(m).abs() > 1.0 - 1e-9) - && f.vertex_iter().next().is_some_and(|p| (vtx(&p) - ball.c).dot(m).abs() <= on_tol * 10.0) - && f.vertex_iter().any(|p| vtx(&p).dist(ball.c) <= on_tol * 10.0) - }); - let Some(i) = found else { return Err(unsupported("the ends of the three rounds")) }; - discs.push(i); - } - // The arc of each: its one edge that is not a straight line. - let mut arcs: Vec = Vec::with_capacity(3); - for i in &discs { - let f = faces.get(*i).ok_or_else(|| KernelError::Failed("face".into()))?; - let curved: Vec = f.edge_iter().filter(|e| !matches!(e.curve(), mt::Curve::Line(_))).collect(); - let [arc] = &curved[..] else { return Err(unsupported("the ends of the three rounds")) }; - arcs.push(arc.absolute_clone()); - } - // The three arcs in a loop. - let first_arc = arcs.first().cloned().ok_or_else(|| KernelError::Failed("arc".into()))?; - let mut used: HashSet = HashSet::from([first_arc.id()]); - let mut wire: Vec = vec![first_arc]; - for _ in 0..2 { - let end = wire.last().map(|e| e.back().clone()).ok_or_else(|| KernelError::Failed("arc".into()))?; - let next = arcs - .iter() - .find(|a| !used.contains(&a.id()) && (*a.front() == end || *a.back() == end)) - .ok_or_else(|| unsupported("the ends of the three rounds"))?; - used.insert(next.id()); - wire.push(if *next.front() == end { next.clone() } else { next.inverse() }); - } - if wire.last().map(|e| e.back().clone()) != wire.first().map(|e| e.front().clone()) { - return Err(unsupported("the ends of the three rounds")); - } - // A sphere about the centre, its poles and seam away from the patch. - let out = (v - ball.c).normalized().ok_or_else(|| KernelError::Failed("sphere".into()))?; - let side = out.any_perp(); - let (np, sp, back) = (ball.c + side * r, ball.c - side * r, ball.c - out * r); - let meridian = mt::builder::circle_arc(&mt::builder::vertex(p3(np)), &mt::builder::vertex(p3(sp)), p3(back)); - let mut surf = - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(meridian.oriented_curve(), p3(ball.c), v3(side)))); - { - use mt::{ParametricSurface3D, SearchNearestParameter}; - if let Some((u, w)) = surf.search_nearest_parameter(p3(ball.c + out * r), None, 100) { - let n = surf.normal(u, w); - if Vec3::new(n.x, n.y, n.z).dot(out) < 0.0 { - surf = mt::Invertible::inverse(&surf); - } - } - } - // The patch runs each arc opposite to the round that ends on it. - let rest: Vec<&mt::Face> = faces.iter().enumerate().filter(|(i, _)| !discs.contains(i)).map(|(_, f)| f).collect(); - let uses = |id: mt::EdgeID| { - rest.iter().find_map(|f| { - f.boundaries().iter().flat_map(|w| w.edge_iter().cloned().collect::>()).find(|x| x.id() == id).map(|x| x.front().id()) - }) - }; - if let (Some(first), Some(front)) = (wire.first(), wire.first().and_then(|e| uses(e.id()))) - && front == first.front().id() - { - wire = wire.iter().rev().map(|e| e.inverse()).collect(); - } - let patch = mt::Face::try_new(vec![mt::Wire::from(wire)], surf).map_err(|e| KernelError::Failed(format!("sphere patch: {e}")))?; - let mut new_faces: Vec = rest.into_iter().cloned().collect(); - new_faces.push(patch); - let mut shells = solid.boundaries().clone(); - let si = shells.iter().position(|sh| sh.face_iter().any(|f| discs.iter().any(|i| faces.get(*i).is_some_and(|d| d.id() == f.id())))).unwrap_or(0); - if let Some(sh) = shells.get_mut(si) { - *sh = new_faces.into(); - } - let out: Solid = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("rounds ending in a sphere: {e}")))?; - record::rebuilt(out, &[&step.solid], &record::Rebuild::default()) -} - -/// `body` with the curved faces that are pieces of one input face (as the cut that made `body` -/// recorded them) joined again: the edges two pieces share go, the rest make the one boundary. -fn merge_split_faces(body: &Body, source: &Body, size: f64) -> Result { - let tol = (size * 1e-6).max(1e-9); - let Some(history) = body.history() else { return Ok(body.clone()) }; - let solid = body.deep_copy(); - let faces: Vec = solid.face_iter().cloned().collect(); - if history.faces.len() != faces.len() { - return Ok(body.clone()); - } - let on = |a: &mt::Face, p: Vec3| project(a, p, None).is_some_and(|(q, _, uv)| crate::curveblend::in_range(a, uv) && q.dist(p) <= tol * 10.0); - // Pieces by the input face they come from. - let mut groups: Vec> = Vec::new(); - for (i, f) in history.faces.iter().enumerate() { - let curved = faces.get(i).is_some_and(|x| crate::blend::plane_normal(x).is_none()); - if !(curved && f.change == crate::history::Change::Split && f.origins.len() == 1) { - continue; - } - match groups.iter_mut().find(|g| g.first().and_then(|k| history.faces.get(*k)).is_some_and(|o| o.origins == f.origins)) { - Some(g) => g.push(i), - None => groups.push(vec![i]), - } - } - let mut out: Vec> = faces.iter().cloned().map(Some).collect(); - let mut merged_any = false; - for group in groups.iter().filter(|g| g.len() >= 2) { - let pieces: Vec<&mt::Face> = group.iter().filter_map(|i| faces.get(*i)).collect(); - if pieces.iter().any(|f| f.boundaries().len() != 1) { - continue; - } - // Edges used once, as the pieces walk them. - let all: Vec = - pieces.iter().flat_map(|f| f.boundaries().iter().flat_map(|w| w.edge_iter().cloned().collect::>()).collect::>()).collect(); - let mut uses: HashMap = HashMap::new(); - for e in &all { - *uses.entry(e.id()).or_default() += 1; - } - let mut left: Vec = all.into_iter().filter(|e| uses.get(&e.id()) == Some(&1)).collect(); - let Some(start) = left.pop() else { continue }; - let mut wire = vec![start]; - while let Some(end) = wire.last().map(|e| e.back().clone()) { - if wire.first().is_some_and(|e| *e.front() == end) { - break; - } - let Some(at) = left.iter().position(|e| *e.front() == end) else { break }; - wire.push(left.swap_remove(at)); - } - // One closed boundary, all of it used. - if !left.is_empty() || wire.first().map(|e| e.front().clone()) != wire.last().map(|e| e.back().clone()) { - continue; - } - // A boolean may restrict a piece's surface to its own parameter box. The - // joined boundary needs the original face's full patch, not an extrapolation - // of one piece (which the bounded display planner correctly refuses). - let all_on = |f: &mt::Face| { - pieces.iter().all(|p| p.vertex_iter().all(|v| on(f, vtx(&v))) && p.edge_iter().all(|e| edge_mid(&e).is_none_or(|m| on(f, m)))) - }; - let original = group.first().and_then(|i| history.faces.get(*i)).and_then(|h| match h.origins.as_slice() { - [crate::history::FaceOrigin::Face { operand: 0, face }] => source.solid.face_iter().nth(*face), - _ => None, - }); - let Some(like) = original.filter(|f| all_on(f)).or_else(|| pieces.iter().copied().find(|f| all_on(f))) else { continue }; - let Ok(joined) = mt::Face::try_new(vec![mt::Wire::from(wire)], like.oriented_surface()) else { continue }; - let Some(first) = group.first() else { continue }; - for i in group { - if let Some(slot) = out.get_mut(*i) { - *slot = None; - } - } - if let Some(slot) = out.get_mut(*first) { - *slot = Some(joined); - } - merged_any = true; - } - if !merged_any { - return Ok(body.clone()); - } - let mut shells = solid.boundaries().clone(); - if let Some(sh) = shells.first_mut() { - *sh = out.into_iter().flatten().collect::>().into(); - } - let rebuilt = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("a corner cut: {e}")))?; - record::rebuilt(rebuilt, &[&body.solid], &record::Rebuild::default()) -} diff --git a/crates/kernel/src/blend_wrong_way_tests.rs b/crates/kernel/src/blend_wrong_way_tests.rs index 9d927c16c..c450929d2 100644 --- a/crates/kernel/src/blend_wrong_way_tests.rs +++ b/crates/kernel/src/blend_wrong_way_tests.rs @@ -1,4 +1,5 @@ -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use crate::*; @@ -27,13 +28,14 @@ fn block_with_ball_cut() -> Body { /// The ball's rim on the back face dips to 0.04 mm above the bottom: a 0.5 mm chamfer of it /// would run off the back face, and what was built grew the part (by 0.65 mm³, more with other -/// edge orders). On a convex edge a chamfer takes material away, so it is refused. +/// edge orders). On a convex edge a chamfer takes material away, so it is refused, as too large +/// (SMLib's NO_ROOM). #[test] fn a_chamfer_that_would_grow_the_part_on_a_convex_edge_is_refused() { let body = block_with_ball_cut(); let rim = Vec3::new(3.1526309873924174, 22.5, 0.04277569594852188); let e = chamfer(&body, &[rim], 0.5).expect_err("refused"); - assert!(matches!(e, KernelError::TooLarge(_)) && e.to_string().contains("convex"), "{e}"); + assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); } /// Curved convex edges that a chamfer does take material from still build: a hole's rim in a diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 9ea0627e7..4459d3dd0 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -1,8 +1,10 @@ use serde::Serialize; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; -use truck_meshalgo::prelude::*; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self, Brep, Curve, Loop, Shell, Surface}; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Aabb3, Mesh}; +use crate::history::BodyHistory; use crate::{KernelError, Result, guard}; #[path = "planar_regularize.rs"] @@ -12,34 +14,26 @@ mod planar_sources; #[path = "shell_groups.rs"] pub(crate) mod shell_groups; -pub(crate) type Solid = mt::Solid; - /// A solid body (one or more closed shells), or a mesh body (triangles only, like an imported /// 3MF or STL: it renders, measures and exports, but B-rep features cannot use it). Cheap to /// clone; never mutated in place. +/// +/// A solid body is its schema 4 record ([`solidcraft_geom::brep`]): faces, edges and vertices +/// in the record's canonical order are the body's own, everywhere (history, naming, meshes). +/// SMLib works on the same body built from that record, made once and shared by clones. #[derive(Clone, Debug)] pub struct Body { - pub(crate) solid: std::sync::Arc, - /// Bounding-box diagonal, measured by [`Body::new`] while it read the vertices anyway; 0 - /// means "not measured, walk the geometry". Every kernel tolerance is a fraction of it. + pub(crate) record: std::sync::Arc, + /// The body in SMLib, built from `record` on first use (or kept from the operation that + /// made it), shared by clones because they share the record. + pub(crate) smlib: std::sync::Arc>>, + /// Bounding-box diagonal of the vertices, measured when the body was made; 0 means "not + /// measured, walk the geometry". Every kernel tolerance is a fraction of it. pub(crate) size: f64, - /// How far this body's face boundaries may lie off their surfaces (mm) and still be taken as - /// lying on them. `Some` for a body read from a file that declares its own numeric - /// uncertainty (a STEP file's `GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT`, see - /// `crate::step_in::Units::tol`); `None` for a body this kernel built, which has no such - /// declaration. - /// - /// A band face's ring edges are held to it when the importer splits the band (see - /// `crate::step_in::split`). The display planner takes it only where it is more than its own - /// bound, a hundredth of the body (see `accept` in [`crate::tess::plan_face`]). - pub(crate) boundary_tol: Option, - /// The last volume measured for this solid and the tolerance it was measured at, shared by - /// clones because they share the solid. A boolean measures its operands, and a later boolean - /// takes the result as an operand again, so the same body is measured twice otherwise. + /// The last volume measured for this record and the tolerance it was measured at, shared by + /// clones because they share the record. pub(crate) volume: Option>>>, - /// Missing-face check from the orientation mesh, reusable at exactly its tolerance. - pub(crate) coarse_missing: Option<(f64, usize)>, - /// Set for mesh bodies (`solid` is then empty). + /// Set for mesh bodies (`record` is then empty). pub(crate) mesh: Option>, /// Display colour (linear RGB 0..1) from an imported file; operations drop it. pub(crate) color: Option<[f32; 3]>, @@ -55,44 +49,72 @@ pub struct Body { /// Exact history of the operation that made this body, relative to that operation's /// operands; `None` when the operation does not report one. pub(crate) history: Option>, - /// A placed copy of a solid that another body shows already (an instance of a part a STEP + /// A placed copy of a body that another body shows already (an instance of a part a STEP /// assembly lists many times): its display mesh is that body's, placed by the matrix, so the - /// part is tessellated once rather than once per instance. Dropped by anything that changes - /// what the body shows (its geometry is never changed in place). + /// part is meshed once rather than once per instance. Dropped by anything that changes what + /// the body shows (its geometry is never changed in place). pub(crate) display_of: Option, [[f64; 4]; 4])>>, - /// Meshes of this solid kept for reuse, set by [`Body::keeping_meshes`]: a check that + /// Meshes of this record kept for reuse, set by [`Body::keeping_meshes`]: a check that /// intersects one large body with many small ones meshes it at the same tolerance each time. pub(crate) meshes: Option>, - /// Its revolved faces were turned away from their seams (see `rephase_revolved`), so a - /// placed copy, which keeps them where they are, need not turn them again: searching every - /// revolved face of every placed occurrence was most of the time moving an assembly took. - pub(crate) phased: bool, + /// The SMLib result this body was decoded from, when the step that made it left SMLib's + /// check to the end of its feature ([`crate::validation`]): checked there as the step's own + /// check would have, then let go. Answers only for this record. + pub(crate) unchecked: Option>, + /// The constant-radius rounds that made this body from another, when they did + /// ([`crate::blend_corner::Rounds`]): a later round at a corner where they meet blends them + /// again with it. Anything else that makes a body leaves it out, and so does every new + /// history: the rounds are over the body its history is over. + pub(crate) rounds: Option>, } -/// The meshes made of one solid (see [`Body::keeping_meshes`]), by tolerance, angle and -/// refinement. They answer only for that solid: a copy whose solid was replaced makes its own. +/// The meshes made of one record (see [`Body::keeping_meshes`]), by tolerance and angle. They +/// answer only for that record: a copy whose record was replaced makes its own. #[derive(Debug)] pub(crate) struct MeshMemo { - solid: std::sync::Arc, - made: std::sync::Mutex)>>, - /// The meshes a boolean makes of the solid's shells, by tolerance. - shells: std::sync::Mutex>)>>, + record: std::sync::Arc, + made: Remembered, } /// Meshes a [`MeshMemo`] keeps at most (the oldest goes first). const MEMO_MESHES: usize = 4; +/// Meshes (or their plans) kept for reuse, by tolerance (see [`remembered`]). +type Remembered = std::sync::Mutex)>>; + +/// The mesh (or plan) at `t` from `kept`, made by `make` and kept (at most [`MEMO_MESHES`]) if +/// it isn't there. The lock is held while meshing: threads asking for the same mesh wait for it +/// rather than make it too. +fn remembered(kept: &Remembered, t: &MeshTolerance, make: impl FnOnce() -> Result) -> Result> { + let Ok(mut made) = kept.lock() else { return make().map(std::sync::Arc::new) }; + let key = t.key(); + if let Some((_, m)) = made.iter().find(|(k, _)| *k == key) { + return Ok(m.clone()); + } + let m = std::sync::Arc::new(make()?); + if made.len() >= MEMO_MESHES { + made.remove(0); + } + made.push((key, m.clone())); + Ok(m) +} + /// The display mesh of a body that several placed copies show (see `Body::display_of`): the -/// body, and its mesh once made. +/// body, and its mesh and plan once made. #[derive(Debug)] pub(crate) struct SharedDisplay { pub(crate) original: Body, - mesh: std::sync::OnceLock>, + meshes: Remembered, + plans: Remembered, } impl SharedDisplay { pub(crate) fn new(original: Body) -> Self { - SharedDisplay { original: Body { display_of: None, meshes: None, ..original }, mesh: std::sync::OnceLock::new() } + SharedDisplay { + original: Body { display_of: None, meshes: None, ..original }, + meshes: std::sync::Mutex::new(Vec::new()), + plans: std::sync::Mutex::new(Vec::new()), + } } } @@ -127,11 +149,7 @@ fn placed_mesh(m: &Mesh, t: &[[f64; 4]; 4]) -> Option { t[0][2] * v.x + t[1][2] * v.y + t[2][2] * v.z + w * t[3][2], ) }; - let det = t[0][0] * (t[1][1] * t[2][2] - t[1][2] * t[2][1]) - t[0][1] * (t[1][0] * t[2][2] - t[1][2] * t[2][0]) - + t[0][2] * (t[1][0] * t[2][1] - t[1][1] * t[2][0]); - if !(det > 0.0 && (det - 1.0).abs() < 1e-6) || t.iter().flatten().any(|x| !x.is_finite()) { - return None; - } + solidcraft_geom::brep::placement::Rigid::of_matrix(t)?; Some(Mesh { positions: m.positions.iter().map(|p| r(*p, 1.0)).collect(), normals: m.normals.iter().map(|n| r(*n, 0.0)).collect(), @@ -143,20 +161,20 @@ fn placed_mesh(m: &Mesh, t: &[[f64; 4]; 4]) -> Option { #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum FaceSource { ExtrudeSide { - segment: solidcraft_geom::Seg2, - plane: Option, + segment: solidcore_record::Seg2, + plane: Option, coalesced: bool, }, CertifiedExtrudeSide { producer: u64, sketch: u64, curve: String, - plane: Option, + plane: Option, }, ExtrudeCap { high: bool, - region: solidcraft_geom::Region2, - plane: solidcraft_geom::Plane, + region: solidcore_record::Region2, + plane: solidcore_record::Plane, }, CertifiedExtrudeCap { producer: u64, @@ -164,25 +182,25 @@ pub enum FaceSource { high: bool, outer: Vec, holes: Vec>, - plane: solidcraft_geom::Plane, + plane: solidcore_record::Plane, }, Box { producer: Option, axis: u8, high: bool, - plane: solidcraft_geom::Plane, + plane: solidcore_record::Plane, }, /// A cylinder primitive's cap: `high` at the far end (its `top`), else at the base. CylinderCap { producer: u64, high: bool, - plane: solidcraft_geom::Plane, + plane: solidcore_record::Plane, }, ShellPlanar { producer: Option, source: Box, inner: bool, - plane: solidcraft_geom::Plane, + plane: solidcore_record::Plane, }, Imported { item: u64, @@ -196,7 +214,7 @@ pub type CapSignature = (Vec, Vec>); type FaceSources = std::sync::Arc>>; impl FaceSource { - fn plane_mut(&mut self) -> Option<&mut solidcraft_geom::Plane> { + fn plane_mut(&mut self) -> Option<&mut solidcore_record::Plane> { match self { Self::ExtrudeSide { plane, .. } | Self::CertifiedExtrudeSide { plane, .. } => plane.as_mut(), Self::ExtrudeCap { plane, .. } @@ -246,8 +264,6 @@ pub struct FaceInfo { pub plane_normal: Option, } -type MeshedShell = truck_topology::Shell, Option>; - /// The most one facet of the display mesh turns (radians): a curved face or edge is divided /// until no facet spans more of it than this, however small its radius is beside the body. /// 20 degrees: a quarter turn is drawn with at least five facets, a full circle with at least 18. @@ -262,273 +278,63 @@ const DISPLAY_ANGLE_FLOOR: f64 = 1e-3; /// The finest angle a display mesh is divided by (one degree). const MIN_DISPLAY_ANGLE: f64 = std::f64::consts::PI / 180.0; -/// Triangulate each shell (not the solid: truck's solid constructor panics on the open or -/// non-manifold shells an import can produce). Boundaries that lie on their surface only within -/// tolerance (imports, boolean results) are projected onto it. -fn mesh_shells(solid: &Solid, tol: f64) -> Vec { - mesh_shells_within(solid, Deflection { display: true, ..Deflection::chord(tol) }) +/// How closely [`Body::mesh`] follows the exact surfaces. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshTolerance { + /// The farthest a facet or an edge segment may stand off the surface or curve it stands for + /// (mm). Not finite or not positive: 0.05 mm. Never finer than a millionth of the body. + pub chord: f64, + /// The most a facet may turn (radians, at least one degree) where its sag is above a + /// thousandth of `chord`; `None`: `chord` alone. + pub angle: Option, } -/// [`mesh_shells`] divided by a chord tolerance and, when it has one, a bound on the angle a -/// facet spans. Each edge is divided once for both its faces, so the faces still share its -/// points. -fn mesh_shells_within(solid: &Solid, deflection: Deflection) -> Vec { - solid - .boundaries() - .iter() - // The robust search tries the exact one first, so exact geometry costs nothing extra; a - // face can also come back as an empty mesh rather than none (boolean results with - // approximate intersection curves), so always use it. - .map(|sh| sh.robust_triangulation_within(deflection)) - .collect() -} +impl MeshTolerance { + /// `chord` alone. + pub const fn chord(chord: f64) -> Self { + MeshTolerance { chord, angle: None } + } -/// A face's triangles (corner positions and normals, in the mesh's winding) with every edge -/// whose middle sags more than `tol` from the surface split there, found through the mesh's -/// surface parameters. A split depends on the edge alone, so neighbours stay conforming. -/// `None` when nothing needs splitting or the parameters don't match the surface. -#[allow(clippy::type_complexity)] -fn refined(pm: &PolygonMesh, surf: &mt::Surface, tol: f64) -> Option> { - refined_with_cache(pm, surf, tol, true) -} + /// What the viewport draws: `chord`, and no facet turning more than [`DISPLAY_ANGLE`], so + /// small radii on a large body look round too. + pub const fn display(chord: f64) -> Self { + MeshTolerance { chord, angle: Some(DISPLAY_ANGLE) } + } -#[allow(clippy::type_complexity)] -fn refined_with_cache(pm: &PolygonMesh, surf: &mt::Surface, tol: f64, memoize: bool) -> Option> { - use mt::{ParametricSurface, ParametricSurface3D}; - let (pos, uvs, nor) = (pm.positions(), pm.uv_coords(), pm.normals()); - if uvs.is_empty() { - return None; + /// The application's display mesh of a body of size `size` (its box diagonal): 1/1000 of + /// it, at least 1 µm, at [`DISPLAY_ANGLE`]. + pub fn display_of(size: f64) -> Self { + MeshTolerance::display((size * 1e-3).max(1e-3)) } - type V = (Vec3, (f64, f64), Vec3); - let mut tris: Vec<[V; 3]> = Vec::new(); - for tri in pm.faces().triangle_iter() { - let mut t = [(Vec3::ZERO, (0.0, 0.0), Vec3::Z); 3]; - for (slot, v) in t.iter_mut().zip(tri.iter()) { - let p = pos.get(v.pos)?; - let uv = uvs.get(v.uv?)?; - let n = v.nor.and_then(|i| nor.get(i)).map(|n| Vec3::new(n.x, n.y, n.z)).unwrap_or(Vec3::Z); - *slot = (Vec3::new(p.x, p.y, p.z), (uv.x, uv.y), n); - } - tris.push(t); - } - // The parameters must be the surface's own. - let check = tris.iter().take(8).flat_map(|t| t.iter()).all(|(p, (u, v), _)| from_p3(surf.subs(*u, *v)).dist(*p) < tol * 4.0 + 1e-9); - // Bounded work: a face may grow to a few times its triangles (wild surfaces sag - // everywhere and are left as meshed). - let cap = (tris.len() * 8).clamp(2_000, 60_000); - if !check || tris.len() > 50_000 { - return None; - } - // Edges on the face's boundary are shared with the next face: never split them. - let k = |x: &V| ((x.1.0 * 1e9).round() as i64, (x.1.1 * 1e9).round() as i64); - let ek = |a: &V, b: &V| if k(a) < k(b) { (k(a), k(b)) } else { (k(b), k(a)) }; - // Only exact finite values identify reusable evaluations. In particular, - // the rounded UV keys used for boundary incidence cannot identify a point - // whose derivatives or midpoint may be reused. - let vertex_key = |v: &V| { - let values = [v.0.x, v.0.y, v.0.z, v.1.0, v.1.1, v.2.x, v.2.y, v.2.z]; - values.iter().all(|x| x.is_finite()).then(|| values.map(f64::to_bits)) - }; - let cache_limit = cap * 3; - let mut singular_cache = std::collections::HashMap::<(u64, u64), bool>::new(); - let mut changed = false; - for _ in 0..4 { - let mut uses: std::collections::HashMap<((i64, i64), (i64, i64)), u32> = std::collections::HashMap::new(); - for [a, b, c] in &tris { - for e in [ek(a, b), ek(b, c), ek(c, a)] { - *uses.entry(e).or_default() += 1; - } - } - let mut edge_cache = std::collections::HashMap::<([u64; 8], [u64; 8]), Option>::new(); - let mut at = |a: &V, b: &V| -> Option { - let key = if memoize { vertex_key(a).zip(vertex_key(b)).map(|(a, b)| if a < b { (a, b) } else { (b, a) }) } else { None }; - if let Some(key) = key - && let Some(value) = edge_cache.get(&key) - { - return *value; - } - let mut calculate = || -> Option { - if uses.get(&ek(a, b)).copied().unwrap_or(0) < 2 { - return None; - } - // Not at a degenerate point (a cone's apex: its parameters there are arbitrary). - let mut singular = |x: &V| { - let key = (x.1.0.to_bits(), x.1.1.to_bits()); - let cacheable = memoize && x.1.0.is_finite() && x.1.1.is_finite(); - if cacheable && let Some(value) = singular_cache.get(&key) { - return *value; - } - let (du, dv) = (surf.uder(x.1.0, x.1.1), surf.vder(x.1.0, x.1.1)); - let c = du.cross(dv); - let value = c.x * c.x + c.y * c.y + c.z * c.z - <= 1e-12 * (du.x * du.x + du.y * du.y + du.z * du.z + dv.x * dv.x + dv.y * dv.y + dv.z * dv.z).powi(2) + 1e-300; - if cacheable && singular_cache.len() < cache_limit { - singular_cache.insert(key, value); - } - value - }; - if singular(a) || singular(b) { - return None; - } - let (u, v) = ((a.1.0 + b.1.0) / 2.0, (a.1.1 + b.1.1) / 2.0); - let q = from_p3(surf.subs(u, v)); - // Within tolerance, or so far off that the parameters wrapped (a seam). - let sag = q.dist((a.0 + b.0) * 0.5); - if sag <= tol || sag >= 0.5 * a.0.dist(b.0) { - return None; - } - let n = surf.normal(u, v); - let mut n = Vec3::new(n.x, n.y, n.z); - // Keep the mesh's normal side. - if n.dot(a.2 + b.2) < 0.0 { - n = -n; - } - Some((q, (u, v), n)) - }; - let value = calculate(); - if let Some(key) = key - && edge_cache.len() < cache_limit - && value.is_none_or(|v| vertex_key(&v).is_some()) - { - edge_cache.insert(key, value); - } - value - }; - let mut next = Vec::with_capacity(tris.len()); - let mut any = false; - for t in &tris { - let [a, b, c] = t; - let m = [at(a, b), at(b, c), at(c, a)]; - any |= m.iter().any(Option::is_some); - match m { - [None, None, None] => next.push(*t), - [Some(x), Some(y), Some(z)] => { - next.extend([[*a, x, z], [x, *b, y], [z, y, *c], [x, y, z]]); - } - [Some(x), None, None] => next.extend([[*a, x, *c], [x, *b, *c]]), - [None, Some(y), None] => next.extend([[*a, *b, y], [*a, y, *c]]), - [None, None, Some(z)] => next.extend([[*a, *b, z], [z, *b, *c]]), - [Some(x), Some(y), None] => next.extend([[*a, x, *c], [x, *b, y], [x, y, *c]]), - [None, Some(y), Some(z)] => next.extend([[*a, *b, z], [z, *b, y], [z, y, *c]]), - [Some(x), None, Some(z)] => next.extend([[*a, x, z], [x, *b, *c], [x, *c, z]]), - } - } - tris = next; - changed |= any; - if !any || tris.len() > cap { - break; - } - } - changed.then(|| tris.into_iter().map(|t| t.map(|(p, _, n)| (p, n))).collect()) -} -/// Revolved surfaces are periodic in their angle; a face whose angles start at 0 is found at 0 -/// or 2π, which confuses the boolean's loop projection. Each revolved face's surface is turned -/// (same geometry) so the face sits around angle π, well away from the wrap. -fn rephase_revolved(solid: Solid) -> Solid { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - #[cfg(test)] - REPHASED.with(|n| n.set(n.get() + 1)); - let r = guard("rephase", || { - let mut changed = false; - let mut shells = Vec::new(); - for sh in solid.boundaries() { - let mut faces = Vec::new(); - for f in sh.face_iter() { - let mt::Surface::RevolutedCurve(proc_) = f.surface() else { - faces.push(f.clone()); - continue; - }; - let surf = f.surface(); - // The face's middle angle. - let mut acc = Vec3::ZERO; - let mut n = 0.0f64; - for w in f.absolute_boundaries() { - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..4 { - acc += from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 4.0)); - n += 1.0; - } - } - } - let Some((_, v)) = surf.search_nearest_parameter(p3(acc / n.max(1.0)), None, 100) else { - faces.push(f.clone()); - continue; - }; - let phi = v.rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; - if phi.abs() < 0.3 { - faces.push(f.clone()); - continue; - } - let new_proc = proc_.map_ref(|rc| { - let (o, a) = (rc.origin(), rc.axis()); - let rot = mt::Matrix4::from_translation(mt::EuclideanSpace::to_vec(o)) - * mt::Matrix4::from_axis_angle(a, mt::Rad(phi)) - * mt::Matrix4::from_translation(-mt::EuclideanSpace::to_vec(o)); - mt::RevolutedCurve::by_revolution(mt::Transformed::transformed(rc.entity_curve(), rot), o, a) - }); - match mt::Face::try_new(f.absolute_boundaries().clone(), mt::Surface::RevolutedCurve(new_proc)) { - Ok(mut nf) => { - if !f.orientation() { - nf.invert(); - } - faces.push(nf); - changed = true; - } - Err(_) => faces.push(f.clone()), - } - } - shells.push(mt::Shell::from(faces)); - } - if !changed { - return Ok(None); - } - Ok(Solid::try_new(shells).ok()) - }); - match r { - Ok(Some(s)) => s, - _ => solid, + /// For export to a mesh format (STL, 3MF, OBJ) of a body of size `size`: 1/5000 of it, at + /// least 1 µm, the chord alone. + pub fn export_of(size: f64) -> Self { + MeshTolerance::chord((size * 2e-4).max(1e-3)) + } + + /// The planner's chord tolerance and facet angle for a body of size `size`. + pub(crate) fn rules(&self, size: f64) -> (f64, Option) { + let tol = if self.chord.is_finite() && self.chord > 0.0 { self.chord } else { 0.05 }; + let tol = tol.max(size * 1e-6); + let turn = self + .angle + .filter(|a| a.is_finite() && *a > 0.0) + .map(|a| crate::tess::size::Turn { angle: a.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR }); + (tol, turn) + } + + /// The key a kept mesh is found by. + fn key(&self) -> (u64, u64) { + (self.chord.to_bits(), self.angle.map_or(u64::MAX, f64::to_bits)) } } -pub(crate) fn p3(v: Vec3) -> mt::Point3 { - mt::Point3::new(v.x, v.y, v.z) -} -pub(crate) fn v3(v: Vec3) -> mt::Vector3 { - mt::Vector3::new(v.x, v.y, v.z) -} -pub(crate) fn from_p3(p: mt::Point3) -> Vec3 { - Vec3::new(p.x, p.y, p.z) +pub(crate) fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) } -/// The distinct edges of `faces` in order of first use, and the faces (by position) each one -/// bounds: the one edge order of a body, used by [`Body::edges`], tessellations and -/// [`crate::history`]. -pub(crate) fn edge_order<'a, P: 'a, C: 'a, S: 'a>( - faces: impl IntoIterator>, -) -> (Vec>, Vec>) { - let mut index = std::collections::HashMap::new(); - let (mut edges, mut bounds): (Vec>, Vec>) = (Vec::new(), Vec::new()); - for (fi, f) in faces.into_iter().enumerate() { - for e in f.edge_iter() { - let i = *index.entry(e.id()).or_insert_with(|| { - edges.push(e.clone()); - bounds.push(Vec::new()); - edges.len() - 1 - }); - if let Some(slot) = bounds.get_mut(i) - && !slot.contains(&fi) - { - slot.push(fi); - } - } - } - (edges, bounds) -} - -fn polyline_mid(pts: &[Vec3]) -> (Vec3, f64) { +pub(crate) fn polyline_mid(pts: &[Vec3]) -> (Vec3, f64) { let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum(); let mut acc = 0.0; for w in pts.windows(2) { @@ -543,66 +349,33 @@ fn polyline_mid(pts: &[Vec3]) -> (Vec3, f64) { (pts.first().copied().unwrap_or_default(), len) } -#[cfg(test)] -thread_local! { - /// Solids [`Body::new`] meshed on this thread to orient them (tests count the work an import does). - pub(crate) static ORIENTED: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Solids `rephase_revolved` searched on this thread. - pub(crate) static REPHASED: std::cell::Cell = 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 { - 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) -} - -/// A solid's volume off a mesh at `tol`, negative when it faces inwards, and how many faces that -/// mesh left out. -fn signed_volume(solid: &Solid, tol: f64) -> Result<(f64, usize)> { - let orient = |tol: f64| { - guard("orient", || { - let shells = mesh_shells(solid, tol); - let volume = shells.iter().map(|s| s.to_polygon().volume()).sum::(); - let missing = - shells.iter().flat_map(|s| s.face_iter()).filter(|f| f.surface().is_none_or(|m| m.faces().triangle_iter().next().is_none())).count(); - Ok((volume, missing)) - }) - }; - let (mut v, missing) = orient(tol)?; - // A long thin round part (a through hole's tool: a cylinder whose vertices all lie on - // its seam, so they span its length only) meshed that coarsely can come out with a - // negative volume when it is outward already: check finely before turning it inside out. - let fine = (tol * 0.02).max(1e-4); - if v < 0.0 && fine < tol { - (v, _) = orient(fine)?; - } - Ok((v, missing)) -} - -/// Whether a closed shell faces inwards (a void), by the check [`Body::new`] orients a solid by. -/// Unlike [`shell_volume`], a negative coarse volume is checked again on a finer mesh. -pub(crate) fn faces_inward(shell: &mt::Shell) -> Result { - let solid = guard("shell", || Solid::try_new(vec![shell.clone()]).map_err(|e| KernelError::Failed(format!("shell: {e}"))))?; - Ok(signed_volume(&solid, orientation_tolerance(span_of(&solid)))?.0 < 0.0) -} - -/// 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. -fn orientation_tolerance(span: f64) -> f64 { +/// Deflection of the coarse mesh `unmeshed_faces` counts on: coarse enough for a large body, +/// fine enough that a small one still meshes. +fn coarse_tolerance(span: f64) -> f64 { (span * 0.01).clamp(1e-3, 1.0) } -/// Bounding-box diagonal of a solid's vertices (1 when it has no finite extent). -fn span_of(solid: &Solid) -> f64 { - let bounds: Aabb3 = solid.vertex_iter().map(|v| from_p3(v.point())).collect(); - if bounds.is_empty() { 1.0 } else { bounds.diagonal() } +/// Box diagonal of a record's vertices and points along its edges (0 when it has none or no +/// finite extent). The edges count: SMLib closes a sphere, a cylinder or a torus along seams, so +/// its vertices alone can be two poles or a single point (a torus came out 1 mm across, and its +/// display mesh at a hundredth of that took 214 720 triangles). Points on the edges, not their +/// control hulls: a rational edge's control points can lie far off it. +fn span_of(record: &Brep) -> f64 { + let mut bounds: Aabb3 = record.vertices.iter().map(|v| v3(v.point)).collect(); + for e in &record.edges { + if let Ok(c) = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()) { + let [t0, t1] = e.interval; + for i in 1..4 { + if let Some(p) = c.point(t0 + (t1 - t0) * f64::from(i) / 4.0) + && p.is_finite() + { + bounds.add(p); + } + } + } + } + let d = if bounds.is_empty() { 0.0 } else { bounds.diagonal() }; + if d.is_finite() && d > 0.0 { d } else { 0.0 } } /// Equal shared values: the same allocation (a clone of the body), else equal contents. @@ -614,7 +387,189 @@ fn same_shared(a: &Option>, b: &Option Result { + solidcraft_geom::brep::check::validate_built(&record).map_err(|e| KernelError::Invalid(e.to_string()))?; + if record.faces.is_empty() { + return Err(KernelError::Failed("empty result".into())); + } + Ok(record) +} + +/// The record of no solid: only the infinite region. +pub(crate) fn empty_record() -> Brep { + Brep { + version: brep::VERSION, + tolerance: 1e-6, + regions: vec![brep::Region { shells: Vec::new(), void: false }], + shells: Vec::new(), + faces: Vec::new(), + edges: Vec::new(), + vertices: Vec::new(), + } +} + +/// Why SMLib refuses a body, and the face it refuses on its own when one does: SMLib's import +/// says only that it refuses the body, so each face is then sent on its own to find which. +#[derive(Clone, Debug, PartialEq)] +pub struct Refusal { + /// The first face (in the body's face order) SMLib refuses on its own; `None` when it takes + /// each face alone (the faces do not fit together) or the body has too many to try. + pub face: Option, + /// That face's surface. + pub surface: Option, + /// SMLib's reason for the whole body, as the log words it. + pub why: String, + /// The reason is a panic the wrapper caught, not a refusal ([`KernelError::Internal`]). + pub internal: bool, +} + +/// Where a point lies against a body ([`Body::classify_point`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PointClass { + /// In the body's material. + Inside, + /// Outside the material, or in a cavity. + Outside, + /// Within the body's tolerance of a face, an edge or a vertex. + OnBoundary, +} + +/// The kind of surface a face lies on, as a person modelling would name it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SurfaceKind { + Plane, + Cylinder, + Cone, + Sphere, + Torus, + /// A B-spline or NURBS surface, or a revolution of a spline. + Freeform, +} + +/// Most faces sent into SMLib one by one to find the one it refuses. +const MAX_REFUSAL_PROBES: usize = 20_000; + +impl Refusal { + /// The refusal of `record` for `error`, with the face SMLib refuses on its own. + fn of(record: &Brep, error: &solidcraft_smlib::Error) -> Refusal { + if let solidcraft_smlib::Error::Internal(why) = error { + return Refusal { face: None, surface: None, why: why.clone(), internal: true }; + } + let _span = solidcraft_profile::span("kernel", "smlib_refusal_face"); + let alone = |f: usize| crate::surfaces::Parts::of(record, &[(f, false)]).and_then(|p| p.canonical()).map(|c| c.brep); + let face = (record.faces.len() <= MAX_REFUSAL_PROBES) + .then(|| (0..record.faces.len()).find(|&f| alone(f).is_ok_and(|r| solidcraft_smlib::Brep::from_record(&r, true).is_err()))) + .flatten(); + let surface = face.and_then(|f| record.faces.get(f)).map(|f| SurfaceKind::of(&f.surface)); + Refusal { face, surface, why: error.to_string(), internal: false } + } +} + +impl SurfaceKind { + pub(crate) fn of(surface: &solidcore_record::brep::Surface) -> SurfaceKind { + use solidcore_record::brep::Surface as S; + match surface { + S::Plane { .. } | S::PlaneThrough { .. } => SurfaceKind::Plane, + S::Cylinder { .. } => SurfaceKind::Cylinder, + S::Cone { .. } => SurfaceKind::Cone, + S::Sphere { .. } | S::BallPatch { .. } => SurfaceKind::Sphere, + S::Torus { .. } => SurfaceKind::Torus, + S::Spline { .. } | S::RationalSpline { .. } | S::PlacedRevolution { .. } => SurfaceKind::Freeform, + } + } +} + impl Body { + /// A body with `record` and nothing else set. + fn bare(record: Brep, mesh: Option>) -> Body { + let size = span_of(&record); + Body { + record: std::sync::Arc::new(record), + smlib: std::sync::Arc::new(std::sync::OnceLock::new()), + size, + volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), + mesh, + color: None, + paint: None, + splits: None, + face_sources: None, + regularization_protected: false, + history: None, + display_of: None, + meshes: None, + unchecked: None, + rounds: None, + } + } + + /// This body with `result`, the SMLib result of the step `what` it was decoded from, whose + /// check that step left to the end of its feature ([`crate::validation::check_kept`]). + pub(crate) fn left_unchecked(self, what: &str, how: crate::validation::Checked, result: solidcraft_smlib::Brep) -> Body { + let unchecked = crate::validation::Unchecked::new(&self.record, what, how, result); + Body { unchecked: Some(std::sync::Arc::new(unchecked)), ..self } + } + + /// The body of a schema 4 record (a solid, or a surface body of open shells): checked for + /// structure (references, loops, regions, canonical order; a record from a file is checked + /// against the file budgets where it is read). Its faces face as the + /// record says. + pub(crate) fn from_record(record: Brep) -> Result { + Ok(Body::bare(solid_record(record)?, None)) + } + + /// The body of SMLib's export of a B-rep (its record, in canonical order). The SMLib body + /// the export came from is not kept: the export is not exact to the bit (its parameters, + /// radians, pcurves), so that body measures and operates a little differently from the + /// record's import, and a body evaluated afresh would then differ from the same body read + /// back from a file. Every operation starts from the record's import ([`Body::smlib`]). + pub(crate) fn from_smlib_record(record: Brep) -> Result { + Ok(Body::bare(solid_record(record)?, None)) + } + + /// A mesh body of `mesh`. + pub(crate) fn of_mesh(mesh: crate::meshbody::TriMesh) -> Body { + Body::bare(empty_record(), Some(std::sync::Arc::new(mesh))) + } + + /// The body's record: faces, edges and vertices in the body's own order. Empty for a mesh body. + pub fn record(&self) -> &Brep { + &self.record + } + + /// The body in SMLib, built from its record the first time it is asked for. The record is + /// SMLib's own form (`SmBrepData`), imported as given: a record SMLib refuses is an error that + /// names why, never repaired here. + pub fn smlib(&self) -> Result<&solidcraft_smlib::Brep> { + self.require_brep("an SMLib operation")?; + self.smlib + .get_or_init(|| solidcraft_smlib::Brep::from_record(&self.record, true).map_err(|e| Refusal::of(&self.record, &e))) + .as_ref() + .map_err( + |r| if r.internal { KernelError::Internal(format!("SMLib: {}", r.why)) } else { KernelError::Failed(format!("SMLib: {}", r.why)) }, + ) + } + + /// Why SMLib refuses the body, if it does: the body is sent into SMLib as an operation + /// would send it (and kept there for the operations to come). `None` for a body SMLib takes, + /// and for a mesh body (no operation sends one). + pub fn smlib_refusal(&self) -> Option<&Refusal> { + if self.is_mesh() { + return None; + } + let _ = self.smlib(); + self.smlib_refused() + } + + /// Why SMLib refused the body when it was last sent there (by an operation, or by + /// [`Self::smlib_refusal`]); `None` when it took it or the body was not sent yet. Sends + /// nothing. + pub fn smlib_refused(&self) -> Option<&Refusal> { + self.smlib.get().and_then(|r| r.as_ref().err()) + } + /// The very same body (shared data), not just an equal-looking one. Its history (how an /// operation made it) is not part of it: an operation that leaves a body as it is (a cut by /// a tool clear of it) gives the same body, with that operation's history. @@ -627,9 +582,9 @@ impl Body { && self.regularization_protected == other.regularization_protected } - /// The very same shape (shared solid or mesh), whatever its colour, paint or face splits. + /// The very same shape (shared record or mesh), whatever its colour, paint or face splits. pub fn same_shape(&self, other: &Body) -> bool { - std::sync::Arc::ptr_eq(&self.solid, &other.solid) + std::sync::Arc::ptr_eq(&self.record, &other.record) && match (&self.mesh, &other.mesh) { (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b), (None, None) => true, @@ -637,104 +592,19 @@ impl Body { } } - pub(crate) fn new(solid: Solid) -> Result { - if solid.boundaries().is_empty() { - return Err(KernelError::Failed("empty result".into())); - } - let mut solid = rephase_revolved(solid); - // Orient outward: a closed solid must have positive volume (meshed finely enough that - // every face comes out: a face missing from a coarse mesh can flip the sign). - let span = span_of(&solid); - let tol = orientation_tolerance(span); - #[cfg(test)] - ORIENTED.with(|n| n.set(n.get() + 1)); - // The faces missing from the coarse mesh are the same whichever way the solid turns out - // to face, so the count is kept for `unmeshed_faces` either way. - let (v, missing) = signed_volume(&solid, tol)?; - if v < 0.0 { - solid.not(); - } - Ok(Body { - solid: std::sync::Arc::new(solid), - size: if span.is_finite() && span > 0.0 { span } else { 0.0 }, - boundary_tol: None, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: Some((tol, missing)), - mesh: None, - color: None, - paint: None, - splits: None, - face_sources: None, - regularization_protected: false, - history: None, - display_of: None, - meshes: None, - phased: true, - }) - } - - /// Like [`Body::new`], for a solid made by placing an already-oriented body (see - /// [`crate::ops::transform_matrix`]): a placement keeps the faces pointing the way they did - /// unless it mirrors them, so its orientation is read from the matrix rather than meshed - /// again. Only for closed solids; `coarse` is the input's cached missing-face count, which a - /// rigid placement preserves exactly. - /// `phased`: the solid was placed from a body whose revolved faces are turned already. - pub(crate) fn new_placed(solid: Solid, flip: bool, coarse: Option<(f64, usize)>, phased: bool) -> Result { - if solid.boundaries().is_empty() { - return Err(KernelError::Failed("empty result".into())); - } - Body::placed_as_is(if phased { solid } else { rephase_revolved(solid) }, flip, coarse) - } - - /// [`Body::new_placed`] for a solid whose revolved faces were already turned away from - /// their seam (a placement of an oriented body keeps them where they were). - fn placed_as_is(mut solid: Solid, flip: bool, coarse: Option<(f64, usize)>) -> Result { - if solid.boundaries().is_empty() { - return Err(KernelError::Failed("empty result".into())); - } - let span = span_of(&solid); - if flip { - solid.not(); - } - Ok(Body { - solid: std::sync::Arc::new(solid), - size: if span.is_finite() && span > 0.0 { span } else { 0.0 }, - boundary_tol: None, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: coarse, - mesh: None, - color: None, - paint: None, - splits: None, - face_sources: None, - regularization_protected: false, - history: None, - display_of: None, - meshes: None, - phased: true, - }) - } - - /// This oriented body's solid moved by `m` (an affine placement), as [`Body::new_placed`] - /// makes it: the orientation comes from the matrix, so a part placed many times (assembly - /// instances) is meshed to orient it only once. Topology only; appearance is the caller's. - pub(crate) fn placed(&self, m: &mt::Matrix4) -> Result { - use mt::SquareMatrix as _; - if *m == mt::Matrix4::from_scale(1.0) { - return Ok(self.clone()); - } - let a = [[m.x.x, m.x.y, m.x.z, m.x.w], [m.y.x, m.y.y, m.y.z, m.y.w], [m.z.x, m.z.y, m.z.z, m.z.w], [m.w.x, m.w.y, m.w.z, m.w.w]]; - let det = m.determinant(); - if !det.is_finite() || det.abs() < 1e-12 { - return Err(KernelError::Invalid("degenerate placement".into())); - } - let rigid = crate::ops::rigid_placement(&a); - let out = Body::placed_as_is(mt::builder::transformed(&*self.solid, *m), det < 0.0, rigid.then_some(self.coarse_missing).flatten())?; - // A placement that does not change distances leaves the boundaries exactly as far off - // their surfaces as they were, so the file's own figure still describes them (see - // [`Body::boundary_tol`]); one that scales the part does not, and the copy declares - // nothing. The same rule as the mesh count above. - Ok(if rigid { out.with_boundary_tol(self.boundary_tol) } else { out }) + /// Whether face `index`'s normal in its body is its surface's natural normal (its first + /// oriented face's `forward`, the side the record walks it by). + pub(crate) fn face_forward(&self, index: usize) -> bool { + self.record + .shells + .iter() + .filter_map(|s| match s { + Shell::Faces { faces, .. } => Some(faces), + _ => None, + }) + .flatten() + .find(|f| f.face as usize == index) + .is_none_or(|f| f.forward) } pub(crate) fn inherit_regularization_protection(mut self, input: &Body) -> Self { @@ -742,6 +612,22 @@ impl Body { self } + /// This body with the lines `inputs`' faces were split along on purpose added to its own: + /// an operation combining bodies keeps their authored splits (each line once), as it keeps + /// their regularization protection. + pub(crate) fn inherit_split_lines(self, inputs: &[&Body]) -> Self { + let mut lines: Vec> = self.split_keep().to_vec(); + for line in inputs.iter().flat_map(|input| input.split_keep()) { + if !lines.contains(line) { + lines.push(line.clone()); + } + } + if lines.len() == self.split_keep().len() { + return self; + } + self.with_split_lines(Some(std::sync::Arc::new(lines))) + } + /// Exact history of the operation that made this body, relative to that operation's /// operands (see [`crate::history`]); `None` when the operation does not report one. pub fn history(&self) -> Option<&crate::history::History> { @@ -753,6 +639,7 @@ impl Body { pub(crate) fn with_history(mut self, history: crate::history::History, operands: &[&Body]) -> Result { history.check(&self, operands)?; self.history = Some(std::sync::Arc::new(history)); + self.rounds = None; Ok(self) } @@ -760,6 +647,7 @@ impl Body { pub(crate) fn with_history_counts(mut self, history: crate::history::History, operands: &[(usize, usize)]) -> Result { history.check_counts((self.face_count(), self.edge_count()), operands)?; self.history = Some(std::sync::Arc::new(history)); + self.rounds = None; Ok(self) } @@ -775,12 +663,45 @@ impl Body { None } }); + self.rounds = None; self } + /// This body as the rounds of `edges` (each an edge of `before`, in its edge order, with its + /// radius) made it from `before` ([`crate::blend_corner::Rounds`]). + pub(crate) fn with_rounds(mut self, before: &Body, edges: Vec<(usize, f64)>) -> Self { + self.rounds = Some(std::sync::Arc::new(crate::blend_corner::Rounds { before: before.clone(), edges })); + self + } + + /// The constant-radius rounds that made this body, when they did: the body they were made + /// on, and each edge they rounded (its index in that body's edge order) with its radius. A + /// later round at a corner where they meet blends them again with it, so a saved model + /// keeps this with the body ([`Body::with_rounds_of`]). + pub fn rounds(&self) -> Option<(&Body, &[(usize, f64)])> { + self.rounds.as_deref().map(|r| (&r.before, r.edges.as_slice())) + } + + /// This body as the rounds of `edges` made it from `before`, as [`Body::rounds`] gave them + /// (read back from a saved model). Refused unless every edge is one of `before`'s, every + /// radius a fillet's, and this body's history is over `before`. + pub fn with_rounds_of(self, before: &Body, edges: Vec<(usize, f64)>) -> Result { + let bad = |what: &str| KernelError::Invalid(format!("rounds: {what}")); + if edges.is_empty() || edges.len() > before.edge_count() { + return Err(bad("no edges, or more than the body has")); + } + if edges.iter().any(|(e, r)| *e >= before.edge_count() || !(r.is_finite() && *r > 1e-6 && *r < 1e6)) { + return Err(bad("an edge the body before them does not have, or a radius no fillet takes")); + } + let history = self.history().filter(|h| h.operands == 1).ok_or_else(|| bad("the body has no history over the body before them"))?; + history.check_counts((self.face_count(), self.edge_count()), &[(before.face_count(), before.edge_count())])?; + Ok(self.with_rounds(before, edges)) + } + /// This body with no history: an operation whose history is not known. pub(crate) fn without_history(mut self) -> Self { self.history = None; + self.rounds = None; self } @@ -795,7 +716,7 @@ impl Body { } /// An exact construction/import plane; never inferred from tessellation. - pub fn face_plane(&self, index: usize) -> Option { + pub fn face_plane(&self, index: usize) -> Option { if index >= 50_000 { return None; } @@ -811,24 +732,20 @@ impl Body { } } - /// Exact current planar surface for an explicitly fixed snapshot, without source lineage. - pub fn planar_face(&self, index: usize) -> Option { - if index >= 50_000 { - return None; - } - guard("exact planar face", || { - let plane = self.solid.face_iter().nth(index).and_then(|face| match face.oriented_surface() { - mt::Surface::Plane(plane) => { - let u = plane.u_axis(); - let v = plane.v_axis(); - solidcraft_geom::Plane::new(from_p3(plane.origin()), Vec3::new(u.x, u.y, u.z), Vec3::new(v.x, v.y, v.z)) - } - _ => None, - }); - Ok(plane) - }) - .ok() - .flatten() + /// Exact current planar surface for an explicitly fixed snapshot, without source lineage: the + /// face's plane as the face faces (out of the material in a closed shell). + pub fn planar_face(&self, index: usize) -> Option { + let face = self.record.faces.get(index)?; + let (o, u, v) = match &face.surface { + Surface::Plane { origin, u_axis, v_axis } => (v3(*origin), v3(*u_axis), v3(*v_axis)), + Surface::PlaneThrough { origin, u_point, v_point } => { + let o = v3(*origin); + (o, v3(*u_point) - o, v3(*v_point) - o) + } + _ => return None, + }; + let v = if self.face_forward(index) { v } else { -v }; + solidcore_record::Plane::new(o, u, v) } /// Certify the two caps of a body built by [`crate::cylinder`]. Its wall stays uncertified. @@ -938,7 +855,7 @@ impl Body { let mut sources = sources.as_ref().clone(); for source in sources.iter_mut().flatten() { if let Some(plane) = source.plane_mut() { - *plane = solidcraft_geom::Plane::new( + *plane = solidcore_record::Plane::new( vector(plane.origin) + translation, vector(plane.x), vector(plane.y) * if reflected { -1. } else { 1. }, @@ -996,11 +913,6 @@ impl Body { self } - /// A deep copy of the solid that can be mutated without affecting other bodies. - pub(crate) fn deep_copy(&self) -> Solid { - mt::builder::clone(&*self.solid) - } - /// Is this a mesh body (no B-rep)? pub fn is_mesh(&self) -> bool { self.mesh.is_some() @@ -1020,14 +932,6 @@ impl Body { self.color } - /// The same body, with how far its boundaries may lie off their surfaces (mm) as the file it - /// was read from declares (see [`Body::boundary_tol`]). A value that is not finite and above - /// zero clears the declaration, which puts the body back on the kernel's own bound. - pub(crate) fn with_boundary_tol(mut self, tol: Option) -> Body { - self.boundary_tol = tol.filter(|t| t.is_finite() && *t > 0.0); - self - } - /// The same body with a display colour. pub fn with_color(mut self, c: Option<[f32; 3]>) -> Body { self.color = c.filter(|c| c.iter().all(|x| x.is_finite())).map(|c| c.map(|x| x.clamp(0.0, 1.0))); @@ -1066,7 +970,7 @@ impl Body { /// Identity of the solid: clones of a body (and bodies a feature passed through unchanged) /// share it. pub fn solid_id(&self) -> usize { - std::sync::Arc::as_ptr(&self.solid) as usize + std::sync::Arc::as_ptr(&self.record) as usize } pub fn with_split_lines(mut self, s: Option>>>) -> Body { @@ -1104,21 +1008,20 @@ impl Body { self } - /// Characteristic size (bounding box diagonal) for tolerances. [`Body::new`] measured it - /// while it read the vertices anyway, and a mesh body when it was made, so the answer is - /// cached; a body built by hand carries 0 and is walked here. + /// Characteristic size (bounding box diagonal of its vertices) for tolerances, measured + /// when the body was made; mesh bodies measure their triangles. pub fn size(&self) -> f64 { if self.size > 0.0 { return self.size; } - let mut b = solidcraft_geom::Aabb3::EMPTY; + let mut b = Aabb3::EMPTY; if let Some(m) = &self.mesh { for p in &m.positions { b.add(*p); } } - for v in self.solid.vertex_iter() { - b.add(from_p3(v.point())); + for v in &self.record.vertices { + b.add(v3(v.point)); } let d = b.diagonal(); if d.is_finite() && d > 0.0 { d } else { 1.0 } @@ -1128,51 +1031,38 @@ impl Body { /// points (a spline lies in the hull of its controls; a face's surface does not count, as an /// imported face is often trimmed from a far larger one). A face curving out beyond all of /// its edges (a dome on a circle) can reach past it, so it frames a view while the body is - /// still being meshed; [`Mesh::bounds`] is the exact one. - /// A mesh body's box is its triangles'. - pub fn outline_bounds(&self) -> solidcraft_geom::Aabb3 { - crate::guard("outline bounds", || Ok(self.outline_bounds_unguarded())).unwrap_or(solidcraft_geom::Aabb3::EMPTY) - } - - fn outline_bounds_unguarded(&self) -> solidcraft_geom::Aabb3 { - use mt::BoundedCurve; - let mut b = solidcraft_geom::Aabb3::EMPTY; + /// still being meshed; [`Body::exact_bounds`] is the exact one. A mesh body's box is its + /// triangles'. + pub fn outline_bounds(&self) -> Aabb3 { + let mut b = Aabb3::EMPTY; if let Some(m) = &self.mesh { for p in &m.positions { b.add(*p); } return b; } - let homogeneous = |b: &mut solidcraft_geom::Aabb3, v: mt::Vector4| { - if v.w > 0.0 { - b.add(Vec3::new(v.x / v.w, v.y / v.w, v.z / v.w)); - } - }; - for v in self.solid.vertex_iter() { - b.add(from_p3(v.point())); + for v in &self.record.vertices { + b.add(v3(v.point)); } - for e in self.solid.edge_iter() { - match e.curve() { - mt::Curve::Line(l) => { - b.add(from_p3(l.0)); - b.add(from_p3(l.1)); - } - mt::Curve::BSplineCurve(c) => c.control_points().iter().for_each(|p| b.add(from_p3(*p))), - mt::Curve::NurbsCurve(c) => c.control_points().iter().for_each(|p| homogeneous(&mut b, *p)), - mt::Curve::IntersectionCurve(c) => { - let (t0, t1) = c.range_tuple(); - for i in 0..=8 { - b.add(from_p3(mt::ParametricCurve::subs(&e.curve(), t0 + (t1 - t0) * f64::from(i) / 8.0))); - } - } - } + for e in &self.record.edges { + curve_hull(e.parameters(), e.interval, &mut b); } b } - /// The body's volume from a mesh at `tol`, measured once per (solid, tolerance): clones of - /// a body share the measurement, so an operand a later boolean takes again is not meshed - /// twice for the same number. `None` when the body cannot be meshed. + /// The exact box of the body's faces, edges and vertices (SMLib's tight box); a mesh body's + /// is its triangles'. + pub fn exact_bounds(&self) -> Result { + if self.is_mesh() { + return Ok(self.outline_bounds()); + } + let (lo, hi) = self.smlib()?.bounds().map_err(|e| KernelError::smlib("SMLib bounds", e))?; + Ok(Aabb3 { min: v3(lo), max: v3(hi) }) + } + + /// The body's volume from a mesh at `tol`, measured once per (record, tolerance): clones of + /// a body share the measurement. `None` when the body cannot be meshed, or a face of it was + /// left out of the mesh (an open mesh has no volume). pub fn volume_at(&self, tol: f64) -> Option { let key = if tol.is_finite() && tol > 0.0 { tol } else { 0.05 }; let key = key.to_bits(); @@ -1183,7 +1073,11 @@ impl Body { { return Some(volume); } - let volume = self.tessellate(f64::from_bits(key)).ok()?.measure().volume; + let mesh = self.mesh(&MeshTolerance::chord(f64::from_bits(key))).ok()?; + if self.faces_without_triangles(&mesh) > 0 { + return None; + } + let volume = mesh.measure().volume; if let Some(cell) = &self.volume && let Ok(mut slot) = cell.lock() { @@ -1198,207 +1092,84 @@ impl Body { if let Some(m) = &self.mesh { return m.positions.len() * 24 + m.triangles.len() * 12; } - // Counted on the borrowed boundaries: `Solid::edge_iter` and `vertex_iter` clone every - // face's wires to walk them, which made this estimate (taken after every feature, over - // every body) cost more than evaluating most features. Each edge use is one edge and - // one vertex in those iterators, so the counts are the same. - let (mut faces, mut uses) = (0usize, 0usize); - for face in self.solid.face_iter() { - faces += 1; - uses += face.absolute_boundaries().iter().map(|w| w.len()).sum::(); + let uses: usize = self.record.faces.iter().flat_map(|f| &f.loops).map(|l| if let Loop::Edges { edges } = l { edges.len() } else { 1 }).sum(); + self.record.faces.len() * 2048 + uses * (512 + 96) + } + + /// The body's triangles, `t` from its exact surfaces: SolidCraft's one mesher (the planner, + /// [`crate::tess`]), evaluated on the CPU, with its edges flagged for display (seams, tangent + /// joins, protected creases). Triangles carry their face index and the edges their polylines, + /// in the record's order; neighbouring faces share every boundary node, so the mesh is + /// watertight wherever the B-rep is. A mesh body gives its own triangles. A face the planner + /// cannot mesh is left out (logged with why; [`Body::unmeshed_faces`] counts it) and the rest + /// meshed; a body none of whose faces mesh is an error that names the first and why. + pub fn mesh(&self, t: &MeshTolerance) -> Result { + crate::profile::timed(crate::profile::Kind::Tessellate, "mesh", || self.mesh_untimed(t)) + } + + fn mesh_untimed(&self, t: &MeshTolerance) -> Result { + if let Some(m) = &self.mesh { + return Ok(m.to_mesh()); } - faces * 2048 + uses * (512 + 96) - } - - /// Distinct edges in a stable order (the order of `edges()` and `tessellate().edges`). - pub(crate) fn unique_edges(solid: &Solid) -> Vec { - let mut seen = std::collections::HashSet::new(); - solid.edge_iter().filter(|e| seen.insert(e.id())).collect() - } - - /// Triangulate with chord tolerance `tol` (mm). Triangles carry their face index. - pub fn tessellate(&self, tol: f64) -> Result { - self.tessellate_with(tol, false) - } - - /// Like [`Body::tessellate`]; with `refine`, triangles that cut through curved faces are - /// split until within `tol` of the surface (for measuring). - pub fn tessellate_with(&self, tol: f64, refine: bool) -> Result { - self.tessellate_within(tol, f64::INFINITY, refine) - } - - /// [`Body::tessellate_with`] in which no facet turns more than `angle` radians either - /// (infinite: the chord tolerance alone). - fn tessellate_within(&self, tol: f64, angle: f64, refine: bool) -> Result { - let mesh = || crate::profile::timed(crate::profile::Kind::Tessellate, || self.tessellate_within_untimed(tol, angle, refine)); - let memo = self.meshes.as_ref().filter(|m| std::sync::Arc::ptr_eq(&m.solid, &self.solid)); - // Held while meshing: threads asking for the same mesh wait for it rather than make it too. - let Some(Ok(mut made)) = memo.map(|m| m.made.lock()) else { return mesh() }; - let key = (tol.to_bits(), angle.to_bits(), refine); - if let Some((_, m)) = made.iter().find(|(k, _)| *k == key) { - return Ok(Mesh::clone(m)); + // A placed copy shows its original's mesh, moved: the part is meshed once for every copy. + if let Some((shared, m)) = self.display_of.as_deref() { + let made = remembered(&shared.meshes, t, || shared.original.mesh_untimed(t))?; + if let Some(placed) = placed_mesh(&made, m) { + return Ok(placed); + } } - let m = mesh()?; - if made.len() >= MEMO_MESHES { - made.remove(0); + match self.meshes.as_ref().filter(|m| std::sync::Arc::ptr_eq(&m.record, &self.record)) { + Some(memo) => { + let kept: std::sync::Arc = remembered(&memo.made, t, || self.mesh_of(&self.mesh_plan_untimed(t)?))?; + Ok(Mesh::clone(&kept)) + } + None => self.mesh_of(&self.mesh_plan_untimed(t)?), } - made.push((key, std::sync::Arc::new(m.clone()))); - Ok(m) + } + + /// The plan [`Body::mesh`] evaluates: every face's triangulation in its own parameters, each + /// edge sampled once so faces meet exactly. For an evaluator of its own (the GPU viewport); + /// [`Body::mesh_of`] gives its mesh without planning again. + pub fn mesh_plan(&self, t: &MeshTolerance) -> Result { + crate::profile::timed(crate::profile::Kind::Tessellate, "mesh_plan", || self.mesh_plan_untimed(t)) + } + + fn mesh_plan_untimed(&self, t: &MeshTolerance) -> Result { + if self.is_mesh() { + return Err(KernelError::Invalid("a mesh body has no surfaces to mesh".into())); + } + // A placed copy is planned as its original, moved (as `Body::mesh` shows the original's + // mesh): the part is planned once for every copy. + if let Some((shared, m)) = self.display_of.as_deref() + && solidcraft_geom::brep::placement::Rigid::of_matrix(m).is_some() + { + return Ok(remembered(&shared.plans, t, || shared.original.mesh_plan_untimed(t))?.transformed(m)); + } + let (tol, turn) = t.rules(self.size()); + let (plan, stats) = guard("mesh", || crate::tess::plan(&self.record, tol, turn))?; + // A face filled leniently has no hole on screen, but its pcurves or seams are still wrong: + // it is reported, never silent. + for f in &stats.lenient { + log::warn!("display plan: face {} filled leniently in (u, v), a defect in its pcurves or seams: {}", f.face, f.reason); + } + // A face no method plans is left out (no triangles; `unmeshed_faces` counts it) and named. + for f in &stats.unmeshed { + log::warn!("display plan: face {} left out of the mesh: {}", f.face, f.reason); + } + Ok(plan) + } + + /// The mesh of `plan`, a plan [`Body::mesh_plan`] made of this body: what [`Body::mesh`] + /// gives at the plan's tolerance. + pub fn mesh_of(&self, plan: &solidcraft_geom::tess::TessPlan) -> Result { + self.flagged(plan.evaluate()) } /// A copy of this body that keeps the meshes made of it for reuse, for as long as the copy /// (or a clone of it) lives: for many operations on one large body at the same tolerance, /// such as cutting it down to the region of each of many contacts. pub fn keeping_meshes(&self) -> Body { - let (made, shells) = (std::sync::Mutex::new(Vec::new()), std::sync::Mutex::new(Vec::new())); - Body { meshes: Some(std::sync::Arc::new(MeshMemo { solid: self.solid.clone(), made, shells })), ..self.clone() } - } - - /// The meshes of this body's shells a boolean at `tol` makes, when the body keeps its meshes - /// ([`Body::keeping_meshes`]); `None` otherwise. - pub(crate) fn boolean_meshes(&self, tol: f64) -> Option>> { - let memo = self.meshes.as_ref().filter(|m| std::sync::Arc::ptr_eq(&m.solid, &self.solid))?; - // Held while meshing, as in `tessellate_within`. - let mut shells = memo.shells.lock().ok()?; - if let Some((_, m)) = shells.iter().find(|(k, _)| *k == tol.to_bits()) { - return Some(m.clone()); - } - let made = std::sync::Arc::new(guard("boolean meshes", || Ok(truck_shapeops::meshes(&*self.solid, tol))).ok()?); - if shells.len() >= MEMO_MESHES { - shells.remove(0); - } - shells.push((tol.to_bits(), made.clone())); - Some(made) - } - - fn tessellate_within_untimed(&self, tol: f64, angle: f64, refine: bool) -> Result { - let tol = if tol.is_finite() && tol > 0.0 { tol } else { 0.05 }; - let tol = tol.max(self.size() * 1e-6); - if let Some(m) = &self.mesh { - return Ok(m.to_mesh()); - } - // Two kinds of face truck cannot mesh in its surface's parameters: one trimmed by a - // helix, which turns more than once around its cylinder and comes out with triangles - // across the solid (#1289), and one that runs across the join of a B-spline surface that - // closes on itself, which comes out folded over itself or with a hole in it. - // Such a body is meshed from its display plan, which cuts and unwraps those faces. - let planned = - guard("tessellate", || Ok(crate::tess::seam::turns_more_than_once(&self.solid) || crate::tess::seam::closes_on_itself(&self.solid))); - if planned.unwrap_or(false) { - let turn = (angle.is_finite() && angle > 0.0) - .then(|| crate::tess::size::Turn { angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR }); - match guard("tessellate", || crate::tess::plan(&self.solid, tol, turn, self.boundary_tol)) { - Ok((plan, _)) => return Ok(plan.evaluate()), - Err(e) => log::debug!("no display plan ({e}); meshing the reference way"), - } - } - let deflection = if angle.is_finite() && angle > 0.0 { - Deflection { chord: tol, angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR, display: true } - } else { - Deflection { display: true, ..Deflection::chord(tol) } - }; - guard("tessellate", || { - let meshed = mesh_shells_within(&self.solid, deflection); - let mut out = Mesh::default(); - let solid_faces: Vec<&mt::Face> = self.solid.face_iter().collect(); - for (fi, face) in meshed.iter().flat_map(|s| s.face_iter()).enumerate() { - let Some(pm) = face.surface() else { continue }; - let flip = !face.orientation(); - let base = u32::try_from(out.positions.len()).unwrap_or(u32::MAX); - // Curved faces: split triangles that cut through the surface. - let refinement = if refine { - solid_faces.get(fi).and_then(|sf| { - let surface = sf.surface(); - if matches!(surface, mt::Surface::Plane(_)) { None } else { refined(&pm, &surface, tol) } - }) - } else { - None - }; - if let Some(tris) = refinement { - let fid = u32::try_from(fi).unwrap_or(u32::MAX); - for t in tris { - let mut idx = [0u32; 3]; - for (slot, (p, n)) in idx.iter_mut().zip(t) { - out.positions.push(p); - out.normals.push(if flip { -n } else { n }); - *slot = u32::try_from(out.positions.len() - 1).unwrap_or(0); - } - out.triangles.push(if flip { [idx[0], idx[2], idx[1]] } else { idx }); - out.tri_face.push(fid); - } - continue; - } - let pos = pm.positions(); - let nor = pm.normals(); - // Expand to per-corner vertices so normals stay per face (crisp edges). - for tri in pm.faces().triangle_iter() { - let mut idx = [0u32; 3]; - for (k, v) in tri.iter().enumerate() { - let Some(p) = pos.get(v.pos) else { continue }; - let n = v.nor.and_then(|ni| nor.get(ni)).map(|n| Vec3::new(n.x, n.y, n.z)).unwrap_or(Vec3::Z); - let n = if flip { -n } else { n }; - out.positions.push(Vec3::new(p.x, p.y, p.z)); - out.normals.push(n); - if let Some(slot) = idx.get_mut(k) { - *slot = u32::try_from(out.positions.len() - 1).unwrap_or(0); - } - } - let t = if flip { [idx[0], idx[2], idx[1]] } else { idx }; - out.triangles.push(t); - out.tri_face.push(u32::try_from(fi).unwrap_or(u32::MAX)); - } - let _ = base; - } - // Fill missing normals from geometry. - for t in &out.triangles { - let (Some(a), Some(b), Some(c)) = - (out.positions.get(t[0] as usize), out.positions.get(t[1] as usize), out.positions.get(t[2] as usize)) - else { - continue; - }; - let fnrm = (b - a).cross(c - a).normalized().unwrap_or(Vec3::Z); - for k in t { - if let Some(n) = out.normals.get_mut(*k as usize) - && (n.dot(fnrm) < -0.2 || n.len() < 0.5) - { - *n = fnrm; - } - } - } - let (edges, faces) = edge_order(meshed.iter().flat_map(|s| s.face_iter())); - out.edges = edges.iter().map(|e| e.oriented_curve().0.iter().map(|p| Vec3::new(p.x, p.y, p.z)).collect()).collect(); - out.edge_faces = faces.into_iter().map(|fs| fs.into_iter().map(|f| u32::try_from(f).unwrap_or(u32::MAX)).collect()).collect(); - Ok(out) - }) - } - - /// The display tessellation as a plan for the CPU or GPU evaluator: every face's - /// triangulation in its own parameters, with each edge sampled once (chord tolerance - /// `tol`, mm) so faces meet exactly. - pub fn display_plan(&self, tol: f64) -> Result { - self.plan_within(tol, None) - } - - /// Like [`Body::display_plan`], and no facet turns more than `angle` radians (see - /// [`Body::display_mesh_angular`]). - pub fn display_plan_angular(&self, tol: f64, angle: f64) -> Result { - self.plan_within(tol, Some(angle)) - } - - fn plan_within(&self, tol: f64, angle: Option) -> Result { - crate::profile::timed(crate::profile::Kind::Tessellate, || self.plan_within_untimed(tol, angle)) - } - - fn plan_within_untimed(&self, tol: f64, angle: Option) -> Result { - if self.is_mesh() { - return Err(KernelError::Invalid("a mesh body has no surfaces to tessellate".into())); - } - let tol = if tol.is_finite() && tol > 0.0 { tol } else { 0.05 }; - let tol = tol.max(self.size() * 1e-6); - // The same angle and floor as the reference mesher's angular display mesh. - let turn = - angle.filter(|a| a.is_finite()).map(|a| crate::tess::size::Turn { angle: a.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR }); - guard("tessellate", || crate::tess::plan(&self.solid, tol, turn, self.boundary_tol).map(|(plan, _)| plan)) + Body { meshes: Some(std::sync::Arc::new(MeshMemo { record: self.record.clone(), made: std::sync::Mutex::new(Vec::new()) })), ..self.clone() } } /// Planar faces whose boundary crosses itself: two of its loops crossing each other, or a @@ -1413,7 +1184,6 @@ impl Body { /// The faces [`Body::crossed_face_loops`] counts, each as the mean of its boundary's /// points: the same for a face an operation carried over unchanged. pub fn crossed_faces(&self) -> Result> { - use mt::{BoundedCurve, ParameterDivision1D}; if self.is_mesh() { return Ok(Vec::new()); } @@ -1422,32 +1192,22 @@ impl Body { let tol = (size * 1e-6).max(1e-9); let chord = (size * 1e-3).max(1e-4); let mut crossed = Vec::new(); - for f in self.solid.face_iter() { - let mt::Surface::Plane(pl) = f.oriented_surface() else { continue }; - let o = from_p3(pl.origin()); - let (Some(u), Some(n)) = ( - Vec3::new(pl.u_axis().x, pl.u_axis().y, pl.u_axis().z).normalized(), - Vec3::new(pl.normal().x, pl.normal().y, pl.normal().z).normalized(), - ) else { - continue; - }; - let v = n.cross(u); - let flat = |p: mt::Point3| { - let d = from_p3(p) - o; + for (fi, f) in self.record.faces.iter().enumerate() { + let Some(plane) = self.planar_face(fi) else { continue }; + let (o, u, v) = (plane.origin, plane.x, plane.y); + let flat = |p: Vec3| { + let d = p - o; (d.dot(u), d.dot(v)) }; // Each loop's segments, in the face's plane. let mut loops: Vec> = Vec::new(); let mut total = 0usize; - for w in f.boundaries() { + for l in &f.loops { + let Loop::Edges { edges } = l else { continue }; let mut segs = Vec::new(); - for e in w.edge_iter() { - let pts = guard("face loops", || { - Ok(match e.curve() { - mt::Curve::Line(_) => vec![e.front().point(), e.back().point()], - c => c.parameter_division(c.range_tuple(), chord).1, - }) - })?; + for u in edges { + let e = self.record.edges.get(u.edge as usize).ok_or_else(|| KernelError::Invalid("edge reference".into()))?; + let pts = edge_points(e, chord)?; segs.extend(pts.windows(2).filter_map(|q| Some((flat(*q.first()?), flat(*q.get(1)?))))); } total = total.saturating_add(segs.len()); @@ -1470,137 +1230,42 @@ impl Body { let (d3, d4) = (side(t.0, t.1, s.0), side(t.0, t.1, s.1)); ((d1 > tol && d2 < -tol) || (d1 < -tol && d2 > tol)) && ((d3 > tol && d4 < -tol) || (d3 < -tol && d4 > tol)) }; - let all: Vec<(usize, &((f64, f64), (f64, f64)))> = - loops.iter().enumerate().flat_map(|(l, segs)| segs.iter().map(move |s| (l, s))).collect(); - let bad = all.iter().enumerate().any(|(i, (_, s))| all.iter().skip(i + 1).any(|(_, t)| cross(s, t))); + let all: Vec<&((f64, f64), (f64, f64))> = loops.iter().flatten().collect(); + let bad = all.iter().enumerate().any(|(i, s)| all.iter().skip(i + 1).any(|t| cross(s, t))); if bad { - let ends: Vec<(f64, f64)> = all.iter().map(|(_, s)| s.0).collect(); - let k = ends.len().max(1) as f64; - let (su, sv) = ends.iter().fold((0.0, 0.0), |acc, p| (acc.0 + p.0, acc.1 + p.1)); + let k = all.len().max(1) as f64; + let (su, sv) = all.iter().fold((0.0, 0.0), |acc, s| (acc.0 + s.0.0, acc.1 + s.0.1)); crossed.push(o + u * (su / k) + v * (sv / k)); } } Ok(crossed) } - /// Faces with no triangles of their own, and so not shown: none in a coarse tessellation, - /// and none in the display plan either (the plan is what the viewport draws, and it meshes - /// faces the reference mesher gives up on). Only faces the coarse tessellation misses are - /// looked for in the plan, so a sound body costs no planning. + /// Faces with no triangles in a coarse mesh (the mesher failed or gave up), counted on the + /// mesh's plan: the mesh itself is not made. pub fn unmeshed_faces(&self) -> usize { if self.is_mesh() { return 0; } - let tol = orientation_tolerance(self.size()); - // The count [`Body::new`] already took at this tolerance, else the same count made now. - let missing = match self.coarse_missing { - Some((cached_tol, missing)) if cached_tol == tol => missing, - _ => { - let Ok(m) = self.tessellate(tol) else { return self.face_count() }; - let mut has = vec![false; self.face_count()]; - for f in &m.tri_face { - if let Some(h) = has.get_mut(*f as usize) { - *h = true; - } - } - has.iter().filter(|h| !**h).count() - } - }; - // A body the coarse mesh covers whole is shown whole: no plan is made for it, whether the - // count came from the cache or from the mesh above. - if missing == 0 { - return 0; - } - self.unmeshed_in_plan(tol).unwrap_or(missing) + let Ok(plan) = self.mesh_plan(&MeshTolerance::chord(coarse_tolerance(self.size()))) else { return self.face_count() }; + plan.faces_with_triangles(self.face_count()).iter().filter(|h| !**h).count() } - /// Faces the display plan leaves without triangles; `None` when the body has no plan. - fn unmeshed_in_plan(&self, tol: f64) -> Option { - let plan = self.display_plan(tol).ok()?; + /// Faces of the body with no triangles in its mesh `m` (left out by the mesher). + fn faces_without_triangles(&self, m: &Mesh) -> usize { + if self.is_mesh() { + return 0; + } let mut has = vec![false; self.face_count()]; - for f in &plan.faces { - if !f.triangles.is_empty() - && let Some(h) = has.get_mut(f.face as usize) - { + for f in &m.tri_face { + if let Some(h) = has.get_mut(*f as usize) { *h = true; } } - Some(has.iter().filter(|h| !**h).count()) + has.iter().filter(|h| !**h).count() } - /// Display mesh: like [`Body::tessellate`], with seam edges flagged. Meshed from the - /// body's [`Body::display_plan`] (shared edge nodes, structured grids), or the way - /// [`Body::tessellate`] meshes when no plan can be made. - pub fn display_mesh(&self, tol: f64) -> Result { - crate::profile::timed(crate::profile::Kind::Tessellate, || self.display_mesh_untimed(tol)) - } - - fn display_mesh_untimed(&self, tol: f64) -> Result { - if self.is_mesh() { - return self.flagged(self.tessellate(tol)?); - } - let m = match self.display_plan(tol) { - Ok(plan) => plan.evaluate(), - Err(e) => { - log::debug!("display mesh: {e}; meshing the reference way"); - self.tessellate(tol)? - } - }; - self.flagged(m) - } - - /// Display mesh whose curved faces and edges look curved whatever the body's size: like - /// [`Body::display_mesh`], and no facet turns more than `angle` radians (see - /// [`DISPLAY_ANGLE`]). A chord tolerance that follows the body's size is larger than the - /// sagitta of a small radius on a large body (a sheet-metal bend, a small hole), which the - /// tolerance alone leaves as one flat facet. - pub fn display_mesh_angular(&self, tol: f64, angle: f64) -> Result { - crate::profile::timed(crate::profile::Kind::Tessellate, || self.display_mesh_angular_untimed(tol, angle)) - } - - fn display_mesh_angular_untimed(&self, tol: f64, angle: f64) -> Result { - if self.is_mesh() { - return self.flagged(self.tessellate(tol)?); - } - match self.display_plan_angular(tol, angle) { - Ok(plan) => self.display_mesh_of(&plan), - Err(e) => { - log::debug!("display mesh: {e}; meshing the reference way"); - self.reference_display_mesh_angular(tol, angle) - } - } - } - - /// The display mesh of a plan made from this body ([`Body::display_plan`], - /// [`Body::display_plan_angular`]): evaluated on the CPU, with its edges flagged. - pub fn display_mesh_of(&self, plan: &solidcraft_geom::tess::TessPlan) -> Result { - crate::profile::timed(crate::profile::Kind::Tessellate, || self.display_mesh_of_untimed(plan)) - } - - fn display_mesh_of_untimed(&self, plan: &solidcraft_geom::tess::TessPlan) -> Result { - self.flagged(plan.evaluate()) - } - - /// The reference mesher's angular display mesh: what [`Body::display_mesh_angular`] falls - /// back to when no plan can be made. - pub fn reference_display_mesh_angular(&self, tol: f64, angle: f64) -> Result { - crate::profile::timed(crate::profile::Kind::Tessellate, || self.reference_display_mesh_angular_untimed(tol, angle)) - } - - fn reference_display_mesh_angular_untimed(&self, tol: f64, angle: f64) -> Result { - if let Some((shared, t)) = self.display_of.as_deref() - && let Some(placed) = - shared.mesh.get_or_init(|| shared.original.reference_display_mesh_angular(tol, angle).ok()).as_ref().and_then(|m| placed_mesh(m, t)) - { - return Ok(placed); - } - if self.is_mesh() { - return self.flagged(self.tessellate(tol)?); - } - self.flagged(self.tessellate_within(tol, angle, false)?) - } - - /// A tessellation with its edges flagged for display (seams, tangent joins, protected creases). + /// A mesh with its edges flagged for display (seams, tangent joins, protected creases). fn flagged(&self, mut m: Mesh) -> Result { if self.is_mesh() { return Ok(m); @@ -1610,9 +1275,9 @@ impl Body { Ok(m) } - /// Edges with polylines (index = position in [`Body::tessellate`]'s `edges`). + /// Edges with polylines (index = the record's edge index). pub fn edges(&self, tol: f64) -> Result> { - let m = self.tessellate(tol)?; + let m = self.mesh(&MeshTolerance::chord(tol))?; Ok(m.edges .into_iter() .enumerate() @@ -1623,32 +1288,35 @@ impl Body { .collect()) } - /// Edges `indices` (as in [`Body::tessellate`]'s `edges`) in `plane`'s coordinates, - /// exactly: lines, circular arcs, and free-form curves as the Bézier spans they are, for a - /// sketch to project them. `None` for an edge that doesn't lie in a plane parallel to - /// `plane`, isn't read exactly or isn't there, and for every edge of a mesh body. - pub fn planar_edges(&self, plane: &solidcraft_geom::Plane, indices: &[usize]) -> Vec>> { - let none = || vec![None; indices.len()]; + /// How far [`Body::planar_edges`] lets a piece it reads as a line or an arc lie from the + /// edge's curve (a NURBS within this of a circle is that arc), so how far a piece's ends may + /// lie from the edge's vertices. + pub fn planar_edges_tolerance(&self) -> f64 { + (self.size() * 1e-7).max(1e-9) * 10.0 + } + + /// Edges `indices` (record edge indices) in `plane`'s coordinates, exactly: lines, circular + /// arcs, single free-form segments, and a free-form curve of several spans as the one + /// B-spline it is, for a sketch to project them. `None` for an edge that doesn't lie in a + /// plane parallel to `plane`, isn't read exactly or isn't there, and for every edge of a mesh + /// body. + pub fn planar_edges(&self, plane: &solidcore_record::Plane, indices: &[usize]) -> Vec>> { if self.is_mesh() { - return none(); + return vec![None; indices.len()]; } - let tol = (self.size() * 1e-7).max(1e-9) * 10.0; - guard("planar edges", || { - let edges = Self::unique_edges(&self.solid); - Ok(indices - .iter() - .map(|i| { - let mut work = 262_144usize; - edges.get(*i).and_then(|e| crate::prism_curve::projected(e, plane, tol, &mut work)) - }) - .collect()) - }) - .unwrap_or_else(|_| none()) + let tol = self.planar_edges_tolerance(); + indices + .iter() + .map(|i| { + let mut work = 262_144usize; + crate::prism_curve::Run::of(&self.record, *i, true).and_then(|run| crate::prism_curve::projected_curves(&run, plane, tol, &mut work)) + }) + .collect() } /// Faces with area and centroid. pub fn faces(&self, tol: f64) -> Result> { - let m = self.tessellate(tol)?; + let m = self.mesh(&MeshTolerance::chord(tol))?; let nf = self.face_count(); let mut acc: Vec<(f64, Vec3, Vec3, bool)> = vec![(0.0, Vec3::ZERO, Vec3::ZERO, true); nf]; for (t, f) in m.triangles.iter().zip(&m.tri_face) { @@ -1696,44 +1364,64 @@ impl Body { Ok(best) } - /// Is the point inside the solid? - pub fn contains(&self, p: Vec3) -> bool { - self.tessellate(self.size() * 2e-3).map(|m| m.contains(p)).unwrap_or(false) + /// Where `p` lies against the body, decided exactly on its faces' surfaces and edges' curves + /// (SMLib's point classification at the body's own tolerance, no mesh): on the boundary when + /// within that tolerance of a face, an edge or a vertex, else inside its material or outside + /// (a cavity is outside). A mesh body's triangles are its exact shape: on its boundary + /// within the record's tolerance of a triangle, else inside when rays from the point cross + /// it an odd number of times. + pub fn classify_point(&self, p: Vec3) -> Result { + if !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite()) { + return Err(KernelError::Invalid(format!("point classification: the point {p:?} is not finite"))); + } + if let Some(m) = &self.mesh { + let mesh = m.to_mesh(); + let near = mesh + .triangles + .iter() + .filter_map(|t| mesh.tri(t)) + .any(|[a, b, c]| solidcraft_geom::compare::closest_on_triangle(p, a, b, c).dist(p) <= self.record.tolerance); + return Ok(if near { + PointClass::OnBoundary + } else if mesh.contains(p) { + PointClass::Inside + } else { + PointClass::Outside + }); + } + let class = self.smlib()?.classify_point([p.x, p.y, p.z]).map_err(|e| KernelError::smlib("SMLib point classification", e))?; + Ok(match class { + solidcraft_smlib::PointClass::Inside => PointClass::Inside, + solidcraft_smlib::PointClass::Outside => PointClass::Outside, + solidcraft_smlib::PointClass::OnBoundary => PointClass::OnBoundary, + }) } /// B-rep faces (a mesh body is one face; [`crate::measure`] counts its triangles). pub fn face_count(&self) -> usize { - match &self.mesh { - Some(_) => 1, - None => self.solid.face_iter().count(), - } + if self.mesh.is_some() { 1 } else { self.record.faces.len() } } /// B-rep edges (none for a mesh body). pub fn edge_count(&self) -> usize { - match &self.mesh { - Some(_) => 0, - None => Self::unique_edges(&self.solid).len(), - } + self.record.edges.len() } /// B-rep vertices (none for a mesh body). pub fn vertex_count(&self) -> usize { - if self.mesh.is_some() { - return 0; - } - let mut seen = std::collections::HashSet::new(); - self.solid.vertex_iter().filter(|v| seen.insert(v.id())).count() + self.record.vertices.len() } - /// What is wrong with the body as a solid: shells that aren't closed and consistently - /// oriented, faces that don't mesh, a volume that isn't positive. Empty when it is sound. + + /// What is wrong with the body as a solid: face shells that aren't closed, faces that don't + /// mesh, a volume that isn't positive. Empty when it is sound. pub fn validity(&self) -> Vec { if let Some(m) = &self.mesh { return if crate::meshbody::is_closed(m) { Vec::new() } else { vec!["the mesh is not closed".into()] }; } let mut out = Vec::new(); - for (i, sh) in self.solid.boundaries().iter().enumerate() { - let c = sh.shell_condition(); - if c != truck_topology::shell::ShellCondition::Closed { - out.push(format!("shell {i} is {c:?}, not closed")); + for (i, shell) in self.record.shells.iter().enumerate() { + if let Shell::Faces { .. } = shell + && !self.record.regions.iter().skip(1).any(|r| r.shells.first() == Some(&(i as u32))) + { + out.push(format!("shell {i} is open, not closed")); } } let missing = self.unmeshed_faces(); @@ -1748,26 +1436,60 @@ impl Body { out } + /// Face shells (a mesh body is one). pub fn shell_count(&self) -> usize { - match &self.mesh { - Some(_) => 1, - None => self.solid.boundaries().len(), - } + if self.mesh.is_some() { 1 } else { self.record.shells.iter().filter(|s| matches!(s, Shell::Faces { .. })).count() } } -} -impl Body { - /// The separate pieces of a body: each outer shell with the voids inside it. A body in one - /// piece comes back as itself. Pieces of a body in several carry their history over - /// `[self]` (their faces and edges are its own), so whoever names them can follow it. + /// The separate pieces of a body: each material region with the voids inside it, read from + /// the record's regions. A body in one piece comes back as itself. Pieces of a body in + /// several carry their history over `[self]` (their faces and edges are its own), so + /// whoever names them can follow it. pub fn lumps(&self) -> Result> { - let pieces = self.lumps_with_clearance(0.0)?; - if pieces.len() < 2 { - return Ok(pieces); + let regions = self.record.material_regions(); + if self.is_mesh() || regions.len() < 2 { + return Ok(vec![self.clone()]); } + self.parts(&(0..regions.len()).map(|k| vec![k]).collect::>()) + } + + /// How the body's lumps meet (positions as in [`Body::lumps`]): each pair that shares a face, + /// an edge or a vertex, with the most it shares, read from the record. Pairs not listed are + /// apart. Empty for a mesh body or a body in one piece. + pub fn region_contacts(&self) -> Result> { + if self.is_mesh() { + return Ok(Vec::new()); + } + self.record.region_contacts().map_err(|e| KernelError::Invalid(format!("region contacts: {e}"))) + } + + /// The body cut into parts: one per group of its lumps (positions as in [`Body::lumps`]), + /// each the lumps listed with the voids inside them. The parts carry their history over + /// `[self]`, as lumps do. + pub fn parts(&self, groups: &[Vec]) -> Result> { + let regions = self.record.material_regions(); let counts = [(self.face_count(), self.edge_count())]; - let histories = crate::boolean_record::parts_of(&pieces, self); - Ok(pieces.into_iter().zip(histories).map(|(piece, history)| piece.with_checked_history(history, &counts)).collect()) + // Sources are by face position: a table of another length belongs to another body. + if self.face_sources.as_ref().is_some_and(|all| all.len() != self.face_count()) { + return Err(KernelError::Invalid("lumps: face source table does not match the body".into())); + } + groups + .iter() + .map(|group| { + let picked = group + .iter() + .map(|&k| regions.get(k).copied().ok_or_else(|| KernelError::Invalid(format!("no lump {k}")))) + .collect::>>()?; + let part = self.record.part(&picked).map_err(|e| KernelError::Failed(format!("lump: {e}")))?; + let sources = self + .face_sources + .as_ref() + .map(|all| std::sync::Arc::new(part.faces.iter().map(|&f| all.get(f as usize).cloned().flatten()).collect::>())); + let history = crate::history::of_part(&part, &counts); + let piece = Body::from_record(part.brep)?.with_face_sources(sources).inherit_regularization_protection(self); + Ok(piece.with_checked_history(Some(history), &counts)) + }) + .collect() } /// Whether this body and `other` share material or touch (within a fine mesh tolerance). @@ -1775,7 +1497,7 @@ impl Body { self.require_brep("contact test")?; other.require_brep("contact test")?; let tol = (self.size().max(other.size()) * 1e-4).max(1e-6); - let (a, b) = (self.tessellate(tol)?, other.tessellate(tol)?); + let (a, b) = (self.mesh(&MeshTolerance::chord(tol))?, other.mesh(&MeshTolerance::chord(tol))?); shell_groups::meshes_meet(&a, &b, 2.0 * tol) } @@ -1798,134 +1520,65 @@ impl Body { if meshes.len() == 16 { meshes.clear(); } - meshes.insert(key, self.tessellate(tol)?); + meshes.insert(key, self.mesh(&MeshTolerance::chord(tol))?); } let mesh = meshes.get(&key).ok_or_else(|| KernelError::Internal("contact mesh disappeared".into()))?; - contacts.push(shell_groups::meshes_meet(mesh, &other.tessellate(tol)?, 2.0 * tol)?); + contacts.push(shell_groups::meshes_meet(mesh, &other.mesh(&MeshTolerance::chord(tol))?, 2.0 * tol)?); } Ok(contacts) } +} - /// A boolean shortcut needs clearance larger than both shell mesh deflections. - pub(crate) fn separated_lumps(&self) -> Result> { - self.lumps_with_clearance(4.0 * (self.size() * 1e-3).max(1e-3)) +/// Points of an edge's curve over its interval, within `chord` of it: lines by their ends, the +/// rest at the evaluator's points (capped). +fn edge_points(e: &brep::Edge, chord: f64) -> Result> { + const MAX_POINTS: usize = 4096; + let curve = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).map_err(|err| KernelError::Invalid(err.to_string()))?; + let [t0, t1] = e.interval; + let at = |t: f64| curve.point(t).ok_or_else(|| KernelError::Invalid(format!("edge curve has no point at {t}"))); + if let Curve::Line { .. } = e.curve { + return Ok(vec![at(t0)?, at(t1)?]); } - - /// A union's pieces must be clear of each other by the contact distance of [`Body::meets`]; - /// closer shells are touching material that was never fused (#396). - pub(crate) fn union_lumps(&self) -> Result> { - self.lumps_with_clearance(2.0 * (self.size() * 1e-4).max(1e-6)) - } - - fn lumps_with_clearance(&self, clearance: f64) -> Result> { - if self.mesh.is_some() || self.solid.boundaries().len() < 2 { - return Ok(vec![self.clone()]); + // Halve until every chord's midpoint is within `chord` of the curve. + let mut ts = vec![t0, t1]; + let mut k = 0; + while k + 1 < ts.len() && ts.len() < MAX_POINTS { + let (a, b) = (ts[k], ts[k + 1]); + let m = 0.5 * (a + b); + let (pa, pb, pm) = (at(a)?, at(b)?, at(m)?); + if pm.dist(pa.lerp(pb, 0.5)) > chord { + ts.insert(k + 1, m); + } else { + k += 1; } - let tol = (self.size() * 1e-3).max(1e-3); - guard("lumps", || { - let shells: Vec = self.solid.boundaries().clone(); - if shells.len() > shell_groups::MAX_SHELLS - || shells.iter().flat_map(mt::Shell::vertex_iter).take(shell_groups::MAX_POINTS + 1).count() > shell_groups::MAX_POINTS - || shells.iter().flat_map(mt::Shell::face_iter).take(shell_groups::MAX_TRIANGLES + 1).count() > shell_groups::MAX_TRIANGLES - { - return Err(KernelError::Failed("lumps: topology exceeds the shell grouping limit".into())); - } - let (mut point_count, mut triangle_count) = (0usize, 0usize); - let data: Vec<(f64, Mesh)> = shells - .iter() - .map(|sh| { - let meshed = sh.robust_triangulation(tol); - if meshed.face_iter().any(|f| f.surface().is_none_or(|m| m.faces().triangle_iter().next().is_none())) { - return Err(KernelError::Failed("lumps: cannot mesh a complete shell boundary".into())); - } - let pm = meshed.to_polygon(); - point_count = point_count - .checked_add(pm.positions().len()) - .ok_or_else(|| KernelError::Failed("lumps: mesh exceeds the shell grouping limit".into()))?; - triangle_count = triangle_count - .checked_add(pm.faces().triangle_iter().take(shell_groups::MAX_TRIANGLES + 1).count()) - .ok_or_else(|| KernelError::Failed("lumps: mesh exceeds the shell grouping limit".into()))?; - if point_count > shell_groups::MAX_POINTS || triangle_count > shell_groups::MAX_TRIANGLES { - return Err(KernelError::Failed("lumps: mesh exceeds the shell grouping limit".into())); - } - let mut m = Mesh::default(); - for p in pm.positions() { - m.positions.push(Vec3::new(p.x, p.y, p.z)); - } - for t in pm.faces().triangle_iter() { - let idx = |k: usize| { - t.get(k).and_then(|x| u32::try_from(x.pos).ok()).ok_or_else(|| KernelError::Failed("lumps: invalid mesh index".into())) - }; - let indices = [idx(0)?, idx(1)?, idx(2)?]; - let [a, b, c] = m.tri(&indices).ok_or_else(|| KernelError::Failed("lumps: invalid mesh triangle".into()))?; - // STEP sphere poles can produce zero-area duplicate triangles. - // They have no boundary area or volume and are not ray crossings. - if (b - a).cross(c - a) == Vec3::ZERO { - continue; - } - m.triangles.push(indices); - m.tri_face.push(0); - } - let origin = m.positions.first().copied().ok_or_else(|| KernelError::Failed("lumps: empty mesh".into()))?; - let v = m - .triangles - .iter() - .map(|t| { - m.tri(t) - .map(|[a, b, c]| (a - origin).dot((b - origin).cross(c - origin)) / 6.0) - .ok_or_else(|| KernelError::Failed("lumps: invalid mesh triangle".into())) - }) - .collect::>>()? - .into_iter() - .sum(); - Ok((v, m)) - }) - .collect::>()?; - let (volumes, meshes): (Vec<_>, Vec<_>) = data.into_iter().unzip(); - let groups = shell_groups::groups(&meshes, &volumes, (self.size() * 1e-8).max(1e-9).max(clearance))?; - if groups.len() == 1 { - return Ok(vec![self.clone()]); - } - // Grouping keeps existing shells; certificates belong to their - // exact face identities, not the new lump's positional face index. - // This is not propagation through a geometry-changing operation. - let sources_by_face = if let Some(sources) = &self.face_sources { - if sources.len() != self.solid.face_iter().count() { - return Err(KernelError::Invalid("lumps: face source table does not match the body".into())); - } - let mut by_id = std::collections::HashMap::new(); - for (face, source) in self.solid.face_iter().zip(sources.iter()) { - if by_id.insert(face.id(), Some((face.orientation(), source))).is_some() { - // A repeated identity has no unique source association. - by_id.insert(face.id(), None); + } + ts.into_iter().map(at).collect() +} + +/// Grow `b` by a curve's hull over `interval`: its control points for splines, its points for +/// lines, circles and ellipses (their exact extreme points), the leader's hull for an +/// intersection curve. +fn curve_hull(c: &Curve, interval: [f64; 2], b: &mut Aabb3) { + match c { + Curve::Line { .. } | Curve::Circle { .. } | Curve::Ellipse { .. } => { + if let Ok(e) = solidcraft_geom::brep::eval::CurveEval::new(c) { + let [t0, t1] = interval; + for i in 0..=16 { + if let Some(p) = e.point(t0 + (t1 - t0) * f64::from(i) / 16.0) { + b.add(p); } } - Some(by_id) - } else { - None - }; - groups - .into_iter() - .map(|g| { - let shells = g - .into_iter() - .map(|i| shells.get(i).cloned().ok_or_else(|| KernelError::Failed("lumps: missing shell".into()))) - .collect::>>()?; - let result = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("lump: {e}"))).and_then(Body::new)?; - let sources = sources_by_face.as_ref().map(|old| { - result - .solid - .face_iter() - .map(|face| match old.get(&face.id()) { - Some(Some((orientation, source))) if *orientation == face.orientation() => (*source).clone(), - _ => None, - }) - .collect() - }); - Ok(result.with_face_sources(sources.map(std::sync::Arc::new)).inherit_regularization_protection(self)) - }) - .collect() - }) + } + } + Curve::Polyline { points } | Curve::Spline { points, .. } => points.iter().for_each(|p| b.add(v3(*p))), + Curve::RationalSpline { homogeneous, .. } => { + for h in homogeneous { + if h[3] > 0.0 { + b.add(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])); + } + } + } + Curve::SurfaceIntersection { leader, .. } => curve_hull(leader, interval, b), } } @@ -1937,10 +1590,6 @@ mod lump_tests; #[path = "mesh_memo_tests.rs"] mod mesh_memo_tests; -#[cfg(test)] -#[path = "refine_cache_tests.rs"] -mod refine_cache_tests; - #[cfg(test)] #[path = "display_mesh_tests.rs"] mod display_mesh_tests; diff --git a/crates/kernel/src/body_lump_tests.rs b/crates/kernel/src/body_lump_tests.rs index 89aa73ada..47e8ca864 100644 --- a/crates/kernel/src/body_lump_tests.rs +++ b/crates/kernel/src/body_lump_tests.rs @@ -14,7 +14,7 @@ fn nested_island() -> Body { fn assert_material(body: &Body, expected: f64, probes: &[(Vec3, bool)]) { assert!(body.validity().is_empty(), "{:?}", body.validity()); - let mesh = body.tessellate_with(0.01, true).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!((mesh.measure().volume - expected).abs() < expected * 1e-6, "{} vs {expected}", mesh.measure().volume); for (p, want) in probes { assert_eq!(mesh.contains(*p), *want, "material at {p:?}"); @@ -31,7 +31,7 @@ fn check_nested(body: &Body) { for (got, want) in volumes.iter().zip([56_000.0, 488_000.0]) { assert!((got - want).abs() < 1e-6, "{volumes:?}"); } - let meshes: Vec<_> = lumps.iter().map(|b| b.tessellate_with(0.01, true).unwrap()).collect(); + let meshes: Vec<_> = lumps.iter().map(|b| b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap()).collect(); for (p, want) in probes { assert_eq!(meshes.iter().filter(|m| m.contains(p)).count(), usize::from(want), "lump material at {p:?}"); } @@ -46,44 +46,26 @@ fn sphere_cut_far_from_a_void_keeps_the_void() { let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 40.0)).unwrap(); let cavity = box_solid(Vec3::new(25.0, 25.0, 25.0), Vec3::new(30.0, 30.0, 30.0)).unwrap(); let hollow = boolean(&block, &cavity, BoolOp::Cut).unwrap().unwrap(); - assert_eq!(hollow.solid.boundaries().len(), 2, "the cavity is a second shell"); + assert_eq!(hollow.shell_count(), 2, "the cavity is a second shell"); let ball = sphere(Vec3::new(0.0, 0.0, 40.0), 8.0).unwrap(); let cut = boolean(&hollow, &ball, BoolOp::Cut).unwrap().unwrap(); // The block, less the cavity, less the eighth of the ball inside the corner. let want = 64_000.0 - 125.0 - std::f64::consts::PI * 512.0 / 6.0; let got = measure(&cut).unwrap().volume; assert!((got - want).abs() < want * 1e-3, "volume {got}, want {want}"); - assert_eq!(cut.solid.boundaries().len(), 2, "the cavity stays a sealed second shell"); - let mesh = cut.tessellate_with(0.01, true).unwrap(); + assert_eq!(cut.shell_count(), 2, "the cavity stays a sealed second shell"); + let mesh = cut.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); for (p, material) in [(Vec3::new(27.5, 27.5, 27.5), false), (Vec3::new(1.0, 1.0, 39.0), false), (Vec3::new(20.0, 20.0, 20.0), true)] { assert_eq!(mesh.contains(p), material, "material at {p:?}"); } } #[test] -fn nested_cavities_stay_with_their_material_islands_for_every_shell_order() { +fn nested_cavities_stay_with_their_material_islands() { let body = nested_island(); check_nested(&body); let before = step_export(&[&body], "nested cavities").unwrap(); - let shells = body.deep_copy().boundaries().clone(); - assert_eq!(shells.len(), 4); - for a in 0..4 { - for b in 0..4 { - for c in 0..4 { - for d in 0..4 { - let order = [a, b, c, d]; - if order.iter().enumerate().any(|(i, x)| order.iter().skip(i + 1).any(|y| x == y)) { - continue; - } - let permuted = guard("permuted cavity shells", || { - Body::new(Solid::try_new(order.into_iter().map(|i| shells[i].clone()).collect()).unwrap()) - }) - .unwrap(); - check_nested(&permuted); - } - } - } - } + assert_eq!(body.shell_count(), 4); assert_eq!(step_export(&[&body], "nested cavities").unwrap(), before); } @@ -108,7 +90,7 @@ fn nested_voids_survive_step_round_trip_and_further_cuts() { for lump in &lumps { if let Some(cut) = boolean(lump, &opening, BoolOp::Cut).unwrap() { cut_volume += measure(&cut).unwrap().volume; - assert!(!cut.tessellate_with(0.01, true).unwrap().contains(Vec3::X * 15.0)); + assert!(!cut.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().contains(Vec3::X * 15.0)); } } // Only x=10..20 is material along this 4×4 opening: 160 mm³ removed. @@ -132,7 +114,7 @@ fn curved_internal_void_and_disconnected_material_keep_analytic_volume() { for (got, want) in volumes.iter().zip(want) { assert!((got - want).abs() < want * 0.002, "{got} vs {want}"); } - let meshes: Vec<_> = lumps.iter().map(|b| b.tessellate_with(0.01, true).unwrap()).collect(); + let meshes: Vec<_> = lumps.iter().map(|b| b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap()).collect(); for (p, want) in [(Vec3::ZERO, 0), (Vec3::X * 3.0, 1), (Vec3::X * 7.0, 0), (Vec3::X * 15.0, 1)] { assert_eq!(meshes.iter().filter(|m| m.contains(p)).count(), want); } @@ -142,74 +124,12 @@ fn curved_internal_void_and_disconnected_material_keep_analytic_volume() { // two bodies. let imported: Vec<_> = imported.bodies.into_iter().map(|b| b.body).collect(); assert_eq!(imported.len(), 2); - let imported_meshes: Vec<_> = imported.iter().map(|b| b.tessellate_with(0.01, true).unwrap()).collect(); + let imported_meshes: Vec<_> = imported.iter().map(|b| b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap()).collect(); for (p, want) in [(Vec3::ZERO, 0), (Vec3::X * 3.0, 1), (Vec3::X * 7.0, 0), (Vec3::X * 15.0, 1)] { assert_eq!(imported_meshes.iter().filter(|m| m.contains(p)).count(), want); } } -fn joined_shells(shells: Vec) -> Body { - guard("invalid ownership fixture", || Body::new(Solid::try_new(shells).unwrap())).unwrap() -} - -#[test] -fn unowned_overlapping_and_touching_cavities_are_errors_not_dropped_geometry() { - let outer = cube(50.0); - for (min, max) in [ - (Vec3::new(60.0, 60.0, 60.0), Vec3::new(70.0, 70.0, 70.0)), - (Vec3::new(45.0, -5.0, -5.0), Vec3::new(55.0, 5.0, 5.0)), - (Vec3::new(40.0, -5.0, -5.0), Vec3::new(50.0, 5.0, 5.0)), - ] { - let mut inner = box_solid(min, max).unwrap().deep_copy(); - inner.not(); - let body = joined_shells(outer.deep_copy().boundaries().iter().chain(inner.boundaries()).cloned().collect()); - let before = step_export(&[&body], "invalid ownership").unwrap(); - assert!(body.lumps().is_err()); - assert_eq!(step_export(&[&body], "invalid ownership").unwrap(), before); - } - let mut a = box_solid(Vec3::new(-10.0, -10.0, -10.0), Vec3::new(10.0, 10.0, 10.0)).unwrap().deep_copy(); - a.not(); - let mut b = box_solid(Vec3::new(0.0, -10.0, -10.0), Vec3::new(20.0, 10.0, 10.0)).unwrap().deep_copy(); - b.not(); - let body = joined_shells(outer.deep_copy().boundaries().iter().chain(a.boundaries()).chain(b.boundaries()).cloned().collect()); - assert!(body.lumps().is_err()); -} - -#[test] -fn shell_grouping_preserves_large_disconnected_patterns_and_bounds_hostile_work() { - let mesh = cube(1.0).tessellate_with(0.01, true).unwrap(); - let copies: Vec<_> = (0..512) - .map(|i| { - let mut m = mesh.clone(); - for p in &mut m.positions { - p.x += f64::from(i) * 4.0; - } - m - }) - .collect(); - assert_eq!(shell_groups::groups(&copies, &vec![8.0; 512], 1e-8).unwrap().len(), 512); - let excessive = vec![Mesh::default(); shell_groups::MAX_SHELLS + 1]; - assert!(shell_groups::groups(&excessive, &vec![1.0; excessive.len()], 1e-8).unwrap_err().to_string().contains("shell count")); - let mut oversized = mesh.clone(); - oversized.positions.resize(shell_groups::MAX_POINTS + 1, Vec3::ZERO); - assert!(shell_groups::groups(&[oversized], &[8.0], 1e-8).unwrap_err().to_string().contains("grouping limit")); - // Two stacks of one slanted triangle, in parallel planes 1 µm apart: every pair's boxes - // overlap but none touch, so all 7000² pairs need testing. - let slanted = |dz: f64| Mesh { - positions: vec![Vec3::new(0.0, 0.0, dz), Vec3::new(1.0, 0.0, 1.0 + dz), Vec3::new(0.0, 1.0, 1.0 + dz)], - triangles: vec![[0, 1, 2]; 7000], - ..Mesh::default() - }; - let (repeated, lifted) = (slanted(0.0), slanted(1e-3)); - assert!(shell_groups::groups(&[repeated, lifted], &[8.0, 8.0], 1e-8).unwrap_err().to_string().contains("boundary work")); - let mut outer = cube(2.0).tessellate_with(0.01, true).unwrap(); - let mut inner = mesh; - outer.triangles = outer.triangles.iter().copied().cycle().take(4000).collect(); - inner.triangles = inner.triangles.iter().copied().cycle().take(4000).collect(); - inner.positions.resize(4000, Vec3::ZERO); - assert!(shell_groups::groups(&[outer, inner], &[64.0, -8.0], 1e-8).unwrap_err().to_string().contains("containment work")); -} - #[test] fn translated_and_scaled_nested_voids_keep_material_membership() { let body = nested_island(); @@ -222,9 +142,9 @@ fn translated_and_scaled_nested_voids_keep_material_membership() { .unwrap(); let lumps = transformed .lumps() - .unwrap_or_else(|e| panic!("scale={scale}: {e}; bounds={:?}", transformed.tessellate_with(1e-4, true).unwrap().bounds())); + .unwrap_or_else(|e| panic!("scale={scale}: {e}; bounds={:?}", transformed.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().bounds())); assert_eq!(lumps.len(), 2); - let meshes: Vec<_> = lumps.iter().map(|b| b.tessellate_with((scale * 0.01).max(1e-5), true).unwrap()).collect(); + let meshes: Vec<_> = lumps.iter().map(|b| b.mesh(&crate::MeshTolerance::chord((scale * 0.01).max(1e-5))).unwrap()).collect(); for (x, want) in [(0.0, 0), (15.0, 1), (30.0, 0), (45.0, 1)] { assert_eq!(meshes.iter().filter(|m| m.contains(origin + Vec3::X * (x * scale))).count(), want); } @@ -232,30 +152,16 @@ fn translated_and_scaled_nested_voids_keep_material_membership() { } #[test] -fn shortcut_clearance_refuses_curved_contact_hidden_between_mesh_vertices() { +fn spheres_apart_join_as_two_lumps() { let direction = Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(); let a = sphere(Vec3::ZERO, 10.0).unwrap(); - for distance in [19.999, 20.001] { - let b = sphere(direction * distance, 10.0).unwrap(); - for shells in [ - a.deep_copy().boundaries().iter().chain(b.deep_copy().boundaries()).cloned().collect(), - b.deep_copy().boundaries().iter().chain(a.deep_copy().boundaries()).cloned().collect(), - ] { - assert!(joined_shells(shells).separated_lumps().is_err(), "distance {distance}"); - } - } let far = sphere(direction * 21.0, 10.0).unwrap(); let safe = crate::ops::join_pieces(vec![a, far]).unwrap().unwrap(); - assert_eq!(safe.separated_lumps().unwrap().len(), 2); - let outer = sphere(Vec3::ZERO, 10.0).unwrap(); - let mut protruding = sphere(direction * 9.001, 1.0).unwrap().deep_copy(); - protruding.not(); - let invalid = joined_shells(outer.deep_copy().boundaries().iter().chain(protruding.boundaries()).cloned().collect()); - assert!(invalid.separated_lumps().is_err()); + assert_eq!(safe.lumps().unwrap().len(), 2); } fn certified_lump_witness() -> Body { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; // The current trimmed lower prism: a rectangular tool with a circular stop // removed. Its cap footprint differs materially from the original sketch. let region = Region2 { @@ -265,23 +171,28 @@ fn certified_lump_witness() -> Body { let lower = crate::extrude(&Plane::XY, &[region], 0., 1.).unwrap().pop().unwrap(); let named = box_solid(Vec3::new(40., 20., 5.), Vec3::new(42., 23., 7.)).unwrap().with_box_certificate(202).unwrap(); let unknown = box_solid(Vec3::new(50., 20., 5.), Vec3::new(51., 21., 6.)).unwrap().with_face_sources(None); - let sources: std::collections::HashMap<_, _> = [&lower, &named] - .into_iter() - .flat_map(|body| body.solid.face_iter().zip(body.face_sources().unwrap()).map(|(face, source)| (face.id(), source.clone()))) - .collect(); // Deliberately put the larger named box first, then the trimmed tool. An // index-based copy of the source table would attach certificates wrongly. - let shells = [&named, &unknown, &lower].into_iter().flat_map(|b| b.solid.boundaries().iter().cloned()).collect(); - let body = Body::new(Solid::try_new(shells).unwrap()).unwrap(); - let table = body.solid.face_iter().map(|f| sources.get(&f.id()).cloned().flatten()).collect(); + let inputs = [&named, &unknown, &lower]; + let sources: Vec> = + inputs.iter().flat_map(|b| b.face_sources().map_or_else(|| vec![None; b.face_count()], |s| s.to_vec())).collect(); + let records: Vec<&solidcore_record::brep::Brep> = inputs.iter().map(|b| b.record()).collect(); + let part = solidcore_record::brep::part::compound(&records).unwrap(); + let body = Body::from_record(part.brep).unwrap(); + let table = part.faces.iter().map(|f| sources.get(*f as usize).cloned().flatten()).collect(); body.with_face_sources(Some(std::sync::Arc::new(table))) } #[test] fn grouping_lumps_preserves_only_unchanged_face_certificates_and_trimmed_caps() { let body = certified_lump_witness(); + // A face is known by its surface and parameter box (no two faces here share both). + let key = |b: &Body, i: usize| { + let f = &b.record().faces[i]; + format!("{:?} {:?}", f.surface, f.domain) + }; let expected: std::collections::HashMap<_, _> = - body.solid.face_iter().zip(body.face_sources().unwrap()).map(|(f, source)| (f.id(), (f.orientation(), source.clone()))).collect(); + (0..body.face_count()).zip(body.face_sources().unwrap()).map(|(i, source)| (key(&body, i), (body.face_forward(i), source.clone()))).collect(); let before = step_export(&[&body], "source").unwrap(); let lumps = body.lumps().unwrap(); assert_eq!(lumps.len(), 3); @@ -291,9 +202,9 @@ fn grouping_lumps_preserves_only_unchanged_face_certificates_and_trimmed_caps() let mut unknown_faces = 0; for lump in &lumps { assert_eq!(lump.face_sources().unwrap().len(), lump.face_count()); - for (f, source) in lump.solid.face_iter().zip(lump.face_sources().unwrap()) { - let (orientation, original) = expected.get(&f.id()).expect("grouping must retain original face IDs"); - assert_eq!(*orientation, f.orientation()); + for (i, source) in lump.face_sources().unwrap().iter().enumerate() { + let (orientation, original) = expected.get(&key(lump, i)).expect("grouping must retain the original faces"); + assert_eq!(*orientation, lump.face_forward(i)); assert_eq!(source, original); match source { Some(FaceSource::ExtrudeCap { region, high, plane }) => { @@ -311,7 +222,7 @@ fn grouping_lumps_preserves_only_unchanged_face_certificates_and_trimmed_caps() } total_faces += 1; } - let mesh = lump.tessellate(1e-5).unwrap(); + let mesh = lump.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap(); if mesh.contains(Vec3::new(21., 21., 0.5)) { assert!(!mesh.contains(Vec3::new(25., 25., 0.5)), "trimmed stop hole must not refill"); assert!((mesh.measure().volume - (100. - 4. * std::f64::consts::PI)).abs() < 0.002); @@ -338,13 +249,62 @@ fn grouping_lumps_does_not_infer_absent_or_misaligned_sources() { /// It must still come out outward, or a Cut with it removes the wrong side (#559). #[test] fn a_long_thin_cylinder_comes_out_outward() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; + use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; let plane = Plane::from_normal(Vec3::new(0., 24., 30.), Vec3::Z).unwrap(); for (lo, seam) in [(-181.0, 0.613), (-100.0, 0.613), (-10.0, 0.613), (-181.0, 0.0)] { let disc = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 0.5, seam), holes: vec![] }; let tool = crate::extrude(&plane, &[disc], lo, 0.9).unwrap().pop().unwrap(); - let volume = tool.tessellate(0.01).unwrap().measure().volume; + let volume = tool.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().volume; let want = std::f64::consts::PI * 0.25 * (0.9 - lo); assert!((volume - want).abs() < want * 0.02, "{lo} {seam}: {volume} vs {want}"); } } + +/// Exact point classification: a box's inside, outside, faces, edges and corners; a cylinder's +/// curved wall within its tolerance (on it), 5 µm inside it (inside: the old mesh test, at a +/// chord of 2e-3 of the size, missed this band) and just beyond; a cavity is outside. +#[test] +fn points_classify_exactly_against_the_body() { + use crate::{PointClass::*, cylinder}; + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); + for (p, want) in [ + (Vec3::new(5.0, 10.0, 15.0), Inside), + (Vec3::new(5.0, 10.0, 31.0), Outside), + (Vec3::new(5.0, 10.0, 30.0 + 1e-4), Outside), + (Vec3::new(5.0, 10.0, 30.0 - 1e-4), Inside), + (Vec3::new(5.0, 10.0, 30.0), OnBoundary), + (Vec3::new(10.0, 10.0, 30.0), OnBoundary), + (Vec3::new(10.0, 20.0, 30.0), OnBoundary), + (Vec3::ZERO, OnBoundary), + ] { + assert_eq!(b.classify_point(p).unwrap(), want, "{p:?}"); + } + assert!(b.classify_point(Vec3::new(f64::NAN, 0.0, 0.0)).is_err()); + + let c = cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap(); + let tol = c.record().tolerance; + let at = |r: f64| Vec3::new(r * std::f64::consts::FRAC_1_SQRT_2, r * std::f64::consts::FRAC_1_SQRT_2, 5.0); + assert_eq!(c.classify_point(at(5.0 + 0.5 * tol)).unwrap(), OnBoundary); + assert_eq!(c.classify_point(at(5.0 - 0.5 * tol)).unwrap(), OnBoundary); + assert_eq!(c.classify_point(at(5.0 - 5e-3)).unwrap(), Inside); + assert_eq!(c.classify_point(at(5.0 + 1e-4)).unwrap(), Outside); + assert_eq!(c.classify_point(Vec3::new(0.0, 0.0, 10.0)).unwrap(), OnBoundary); + + let hollow = boolean(&cube(50.0), &cube(40.0), BoolOp::Cut).unwrap().unwrap(); + assert_eq!(hollow.classify_point(Vec3::ZERO).unwrap(), Outside, "the cavity"); + assert_eq!(hollow.classify_point(Vec3::X * 45.0).unwrap(), Inside); + assert_eq!(hollow.classify_point(Vec3::X * 40.0).unwrap(), OnBoundary, "the cavity's wall"); +} + +/// A mesh body's triangles are its shape: on them within the record's tolerance, else inside or +/// outside by the rays' crossings. +#[test] +fn points_classify_against_a_mesh_body() { + use crate::PointClass::*; + let p = [Vec3::ZERO, Vec3::X * 10.0, Vec3::Y * 10.0, Vec3::Z * 10.0]; + let m = crate::mesh_body(&p, &[[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]]).unwrap(); + assert_eq!(m.classify_point(Vec3::new(1.0, 1.0, 1.0)).unwrap(), Inside); + assert_eq!(m.classify_point(Vec3::new(5.0, 5.0, 5.0)).unwrap(), Outside); + assert_eq!(m.classify_point(Vec3::new(1.0, 1.0, 0.0)).unwrap(), OnBoundary); + assert_eq!(m.classify_point(Vec3::X * 10.0).unwrap(), OnBoundary); +} diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rs deleted file mode 100644 index e2a4b79cc..000000000 --- a/crates/kernel/src/boolean_diagnostics.rs +++ /dev/null @@ -1,307 +0,0 @@ -//! Scoped reports for successful Boolean retries. Discarded attempts never enter -//! their caller's report, and independent evaluations cannot inherit old events. - -use std::cell::RefCell; - -use serde::{Deserialize, Serialize}; - -const MAX_EVENTS: usize = 1024; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum BooleanStrategy { - RefinedTolerance, - ShiftedOperands, - CoplanarSeparation, - CommonBore, - /// A boss in the other body's bore, grown into the material around it (nothing recut). - GrownBoss, - PlanarFallback, - ToolNudge, - /// A rotationally symmetric tool turned about its own axis; its volume is unchanged. - ToolReseam, - Piecewise, - /// No retry gave a result, and the answer from sample points was kept although the bodies' - /// facetings disagree with it. - UnverifiedShortcut, -} - -/// Numerical adjustments used by a successful retry, in millimetres/radians. -/// Operand shifts are reversed on the result; face shifts are temporary working -/// offsets. A tool nudge, in contrast, changes the relative operand placement. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct BooleanFallback { - pub strategy: BooleanStrategy, - pub translation_mm: f64, - pub rotation_rad: f64, - pub face_shift_mm: f64, - pub tolerance_mm: f64, -} - -impl BooleanStrategy { - /// Whether a result made this way can differ from the exact one: the tool was moved - /// against the other body, or part of where they meet was ignored. The other retries work - /// on temporary geometry or tolerances only, and their results are the exact ones. - pub fn alters_result(self) -> bool { - matches!(self, BooleanStrategy::ToolNudge | BooleanStrategy::UnverifiedShortcut) - } -} - -impl BooleanFallback { - pub(crate) fn new(strategy: BooleanStrategy) -> Self { - Self { strategy, translation_mm: 0., rotation_rad: 0., face_shift_mm: 0., tolerance_mm: 0. } - } - - fn description(&self) -> String { - match self.strategy { - BooleanStrategy::RefinedTolerance => format!("refined tolerance {:.6e} mm", self.tolerance_mm), - BooleanStrategy::ShiftedOperands => { - format!("shifted operands {:.6e} mm (result shifted back), tolerance {:.6e} mm", self.translation_mm, self.tolerance_mm) - } - BooleanStrategy::CoplanarSeparation => format!("temporary coincident-face separation up to {:.6e} mm per face", self.face_shift_mm), - BooleanStrategy::CommonBore => format!("temporary bore offset {:.6e} mm, followed by recutting the original bore", self.face_shift_mm), - BooleanStrategy::GrownBoss => format!("boss grown {:.6e} mm into the material around the bore it fills", self.face_shift_mm), - BooleanStrategy::PlanarFallback => "exact planar fallback (no displacement)".into(), - BooleanStrategy::ToolNudge => format!("tool displacement {:.6e} mm, rotation {:.6e} rad", self.translation_mm, self.rotation_rad), - BooleanStrategy::ToolReseam => format!("axisymmetric tool reseamed by {:.6e} rad (no displacement)", self.rotation_rad), - BooleanStrategy::Piecewise => "piecewise retry (no displacement)".into(), - BooleanStrategy::UnverifiedShortcut => format!( - "not verified: the bodies' facets pass through each other by more than {:.6e} mm, but they could not be intersected there; that part is ignored", - self.tolerance_mm - ), - } - } -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct BooleanDiagnostics { - pub events: Vec, - pub truncated: bool, - /// Why candidates of the retries that led to the result were discarded before they were - /// measured (#3020: a coarse candidate whose edges run far outside the operands, which - /// meshing never finished). Left out of the report when there are none. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub rejected: Vec, -} - -impl BooleanDiagnostics { - pub(crate) fn push(&mut self, event: BooleanFallback) { - if self.events.len() < MAX_EVENTS { - self.events.push(event); - } else { - self.truncated = true; - } - } - - fn push_rejected(&mut self, reason: String) { - // A candidate checked twice (picked, then taken) is noted once. - if self.rejected.contains(&reason) { - return; - } - if self.rejected.len() < MAX_EVENTS { - self.rejected.push(reason); - } else { - self.truncated = true; - } - } - - /// Why the result is not verified, when it ignores a place where the bodies seem to pass - /// through each other ([`BooleanStrategy::UnverifiedShortcut`]). - pub fn unverified(&self) -> Option { - self.events.iter().find(|event| event.strategy == BooleanStrategy::UnverifiedShortcut).map(BooleanFallback::description) - } - - /// Every retry the result took, for a message about the boolean (one that failed its - /// checks lists what was tried). - pub fn summary(&self) -> Option { - self.described(&self.events.iter().collect::>()) - } - - /// The note a feature carries: the retries that can make its result differ from the exact - /// one ([`BooleanStrategy::alters_result`]). Exact retries are in `events` all the same - /// (`timeline.inspect`), but they leave the result as it should be: no reason to warn. - pub fn warning(&self) -> Option { - self.described(&self.events.iter().filter(|e| e.strategy.alters_result()).collect::>()) - } - - fn described(&self, events: &[&BooleanFallback]) -> Option { - if events.is_empty() && !self.truncated { - return None; - } - let mut descriptions: Vec = events.iter().take(4).map(|e| e.description()).collect(); - if events.len() > 4 { - descriptions.push(format!("{} additional retries", events.len() - 4)); - } - if self.truncated { - descriptions.push(format!("report capped at {MAX_EVENTS} retries")); - } - Some(format!("Boolean retry: {}", descriptions.join("; "))) - } -} - -thread_local! { - static REPORT: RefCell> = const { RefCell::new(None) }; -} - -struct Scope { - previous: Option>, -} - -impl Drop for Scope { - fn drop(&mut self) { - if let Some(previous) = self.previous.take() { - REPORT.with(|cell| { - if let Ok(mut report) = cell.try_borrow_mut() { - *report = previous; - } - }); - } - } -} - -/// Capture only the events produced by this call. Nested callers explicitly merge -/// an accepted attempt; dropping a scope restores its parent even during unwinding. -pub fn capture_boolean_diagnostics(run: impl FnOnce() -> T) -> (T, BooleanDiagnostics) { - let previous = REPORT.with(|cell| cell.try_borrow_mut().ok().map(|mut report| report.replace(BooleanDiagnostics::default()))); - let scope = Scope { previous }; - let result = run(); - let report = REPORT.with(|cell| cell.try_borrow_mut().ok().and_then(|mut report| report.take())).unwrap_or_default(); - drop(scope); - (result, report) -} - -pub(crate) fn record(event: BooleanFallback) { - REPORT.with(|cell| { - if let Ok(mut report) = cell.try_borrow_mut() - && let Some(report) = report.as_mut() - { - report.push(event); - } - }); -} - -/// Note a candidate discarded before it was measured, and why. -pub(crate) fn reject(reason: String) { - REPORT.with(|cell| { - if let Ok(mut report) = cell.try_borrow_mut() - && let Some(report) = report.as_mut() - { - report.push_rejected(reason); - } - }); -} - -pub(crate) fn merge(report: BooleanDiagnostics) { - for event in report.events { - record(event); - } - for reason in report.rejected { - reject(reason); - } - if report.truncated { - REPORT.with(|cell| { - if let Ok(mut report) = cell.try_borrow_mut() - && let Some(report) = report.as_mut() - { - report.truncated = true; - } - }); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn nested_attempts_are_committed_explicitly_and_do_not_leak() { - let (_, report) = capture_boolean_diagnostics(|| { - let (_, discarded) = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge))); - assert_eq!(discarded.events.len(), 1); - let (_, accepted) = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::PlanarFallback))); - merge(accepted); - }); - assert_eq!(report.events.len(), 1); - assert_eq!(report.events[0].strategy, BooleanStrategy::PlanarFallback); - assert!(capture_boolean_diagnostics(|| {}).1.events.is_empty()); - record(BooleanFallback::new(BooleanStrategy::ToolNudge)); - assert!(capture_boolean_diagnostics(|| {}).1.events.is_empty()); - } - - /// Candidates discarded unmeasured (#3020) are reported with the attempt that led to the - /// result, once each, and not at all when there are none. - #[test] - fn rejected_candidates_follow_the_accepted_attempt() { - let (_, report) = capture_boolean_diagnostics(|| { - let (_, discarded) = capture_boolean_diagnostics(|| reject("from a discarded attempt".into())); - assert_eq!(discarded.rejected.len(), 1); - let (_, accepted) = capture_boolean_diagnostics(|| { - reject("runaway edge".into()); - reject("runaway edge".into()); - record(BooleanFallback::new(BooleanStrategy::ToolNudge)); - }); - merge(accepted); - }); - assert_eq!(report.rejected, vec!["runaway edge".to_string()]); - assert!(serde_json::to_string(&report).unwrap().contains("\"rejected\":[\"runaway edge\"]")); - let plain = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge))).1; - assert!(!serde_json::to_string(&plain).unwrap().contains("rejected")); - } - - /// Only retries whose result can differ from the exact one make a warning; the summary - /// lists every retry. - #[test] - fn only_retries_that_alter_the_result_warn() { - let report = |strategies: &[BooleanStrategy]| { - capture_boolean_diagnostics(|| { - for s in strategies { - record(BooleanFallback::new(*s)); - } - }) - .1 - }; - let exact = report(&[BooleanStrategy::ShiftedOperands, BooleanStrategy::GrownBoss, BooleanStrategy::CoplanarSeparation]); - assert!(exact.warning().is_none(), "{exact:?}"); - assert!(exact.summary().is_some_and(|s| s.contains("shifted operands") && s.contains("boss grown"))); - let nudged = report(&[BooleanStrategy::GrownBoss, BooleanStrategy::ToolNudge]); - let warning = nudged.warning().unwrap(); - assert!(warning.contains("tool displacement") && !warning.contains("boss grown"), "{warning}"); - } - - #[test] - fn exact_operations_and_failed_calls_have_no_retry_report() { - use solidcraft_geom::Vec3; - let body = crate::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap(); - let other = crate::box_solid(Vec3::new(5., 0., 0.), Vec3::new(15., 10., 10.)).unwrap(); - let (result, diagnostics) = capture_boolean_diagnostics(|| crate::boolean(&body, &other, crate::BoolOp::Union)); - assert!(result.unwrap().is_some()); - assert!(diagnostics.warning().is_none(), "{diagnostics:?}"); - let mesh = crate::mesh_body(&[Vec3::ZERO, Vec3::X, Vec3::Y], &[[0, 1, 2]]).unwrap(); - let (result, diagnostics) = capture_boolean_diagnostics(|| crate::boolean(&body, &mesh, crate::BoolOp::Cut)); - assert!(result.is_err()); - assert!(diagnostics.warning().is_none(), "{diagnostics:?}"); - } - - #[test] - fn unwinding_restores_parent_and_reports_are_thread_local_and_bounded() { - let (_, report) = capture_boolean_diagnostics(|| { - let failed = crate::guard("diagnostic test", || { - capture_boolean_diagnostics(|| -> crate::Result<()> { - record(BooleanFallback::new(BooleanStrategy::ToolNudge)); - panic!("discard this attempt"); - }) - .0 - }); - assert!(failed.is_err()); - let separate = std::thread::spawn(|| capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge))).1); - assert_eq!(separate.join().unwrap().events.len(), 1); - for _ in 0..MAX_EVENTS + 1 { - record(BooleanFallback::new(BooleanStrategy::PlanarFallback)); - } - }); - assert_eq!(report.events.len(), MAX_EVENTS); - assert!(report.truncated); - assert!(report.events.iter().all(|event| event.strategy == BooleanStrategy::PlanarFallback)); - assert!(report.warning().unwrap().contains("capped")); - } -} diff --git a/crates/kernel/src/boolean_guard.rs b/crates/kernel/src/boolean_guard.rs deleted file mode 100644 index aafcadd42..000000000 --- a/crates/kernel/src/boolean_guard.rs +++ /dev/null @@ -1,218 +0,0 @@ -//! The check every Boolean retry's result must pass before it is returned (issue #616). -//! -//! A retry moves things about (the tool nudged, faces pushed apart, pieces cut off and glued -//! back), so its result is held to what a join or a cut can do at all: -//! - it is closed; -//! - a join never loses volume and a cut never gains any; -//! - outside the tool's box nothing changes: there, the result's surface is the target's and -//! the target's surface is the result's. A join or a cut can only change the target where the -//! tool is, so geometry anywhere else (a slit through a wall, a face moved) is wrong. -//! -//! A result that fails is refused with an error: a wrong result that looks right is worse. - -use solidcraft_geom::{Aabb3, Mesh, Vec3}; - -use crate::body::Body; -use crate::{BoolOp, KernelError, Result}; - -/// Most triangles sampled from each surface (evenly spaced through the mesh). -const MAX_SAMPLES: usize = 20_000; - -/// Distance from `p` to the triangle `abc`. -pub(crate) fn point_triangle_dist(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 { - let n = (b - a).cross(c - a); - let Some(nn) = n.normalized() else { - return [(a, b), (b, c), (c, a)].iter().map(|(u, v)| p.dist_to_segment(*u, *v)).fold(f64::INFINITY, f64::min); - }; - let h = (p - a).dot(nn); - let q = p - nn * h; - let inside = [(a, b), (b, c), (c, a)].iter().all(|(u, v)| (*v - *u).cross(q - *u).dot(n) >= 0.0); - if inside { h.abs() } else { [(a, b), (b, c), (c, a)].iter().map(|(u, v)| p.dist_to_segment(*u, *v)).fold(f64::INFINITY, f64::min) } -} - -/// The triangles of a mesh in a uniform grid of cells, each listing the triangles within `reach` -/// of it, to answer "is this point within `reach` of the surface?". -struct Near<'a> { - mesh: &'a Mesh, - min: Vec3, - cell: f64, - dims: [usize; 3], - cells: Vec>, - reach: f64, -} - -impl<'a> Near<'a> { - fn new(mesh: &'a Mesh, reach: f64) -> Option { - let bounds = mesh.bounds(); - if bounds.is_empty() { - return None; - } - let min = bounds.min - Vec3::new(reach, reach, reach); - let size = bounds.size() + Vec3::new(2.0 * reach, 2.0 * reach, 2.0 * reach); - // About a few triangles a cell, at most 64^3 cells. - let n = (mesh.triangles.len().max(1) as f64).cbrt().clamp(1.0, 64.0); - let cell = (size.x.max(size.y).max(size.z) / n).max(reach * 2.0).max(1e-9); - let dims = [size.x, size.y, size.z].map(|s| ((s / cell).ceil() as usize).clamp(1, 256)); - let mut cells = vec![Vec::new(); dims[0] * dims[1] * dims[2]]; - for (i, t) in mesh.triangles.iter().enumerate() { - let Some(tri) = mesh.tri(t) else { continue }; - let mut bx = Aabb3::EMPTY; - for p in tri { - bx.add(p); - } - let lo = Self::index(min, cell, dims, bx.min - Vec3::new(reach, reach, reach)); - let hi = Self::index(min, cell, dims, bx.max + Vec3::new(reach, reach, reach)); - for x in lo[0]..=hi[0] { - for y in lo[1]..=hi[1] { - for z in lo[2]..=hi[2] { - if let Some(c) = cells.get_mut((x * dims[1] + y) * dims[2] + z) { - c.push(i as u32); - } - } - } - } - } - Some(Near { mesh, min, cell, dims, cells, reach }) - } - - fn index(min: Vec3, cell: f64, dims: [usize; 3], p: Vec3) -> [usize; 3] { - let d = p - min; - let f = |v: f64, n: usize| ((v / cell).floor().max(0.0) as usize).min(n - 1); - [f(d.x, dims[0]), f(d.y, dims[1]), f(d.z, dims[2])] - } - - fn close(&self, p: Vec3) -> bool { - let d = p - self.min; - let s = [d.x, d.y, d.z]; - if s.iter().zip(self.dims).any(|(v, n)| *v < 0.0 || *v > self.cell * n as f64) { - return false; - } - let [x, y, z] = Self::index(self.min, self.cell, self.dims, p); - let Some(list) = self.cells.get((x * self.dims[1] + y) * self.dims[2] + z) else { return false }; - list.iter().any(|&t| { - self.mesh.triangles.get(t as usize).and_then(|t| self.mesh.tri(t)).is_some_and(|[a, b, c]| point_triangle_dist(p, a, b, c) <= self.reach) - }) - } -} - -/// A point of `from`'s surface outside `region` that is not on `onto`'s surface (within -/// `reach`), if there is one. -fn stray_point(from: &Mesh, onto: &Near, region: &Aabb3) -> Option { - let step = from.triangles.len().div_ceil(MAX_SAMPLES).max(1); - from.triangles.iter().step_by(step).filter_map(|t| from.tri(t)).find_map(|[a, b, c]| { - let p = (a + b + c) / 3.0; - let outside = - p.x < region.min.x || p.y < region.min.y || p.z < region.min.z || p.x > region.max.x || p.y > region.max.y || p.z > region.max.z; - (outside && !onto.close(p)).then_some(p) - }) -} - -/// The smallest radius of a body's cylinders, spheres and tori (their tubes). -fn smallest_radius(body: &Body) -> Option { - use crate::surface_kind::{FaceSurface, face_surface}; - (0..body.face_count()) - .filter_map(|i| match face_surface(body, i)? { - FaceSurface::Cylinder { radius, .. } | FaceSurface::Sphere { radius, .. } => Some(radius), - FaceSurface::Torus { minor, .. } => Some(minor), - _ => None, - }) - .filter(|r| r.is_finite() && *r > 0.0) - .min_by(f64::total_cmp) -} - -fn bad(op: BoolOp, what: String) -> KernelError { - let verb = match op { - BoolOp::Union => "join", - BoolOp::Cut => "cut", - BoolOp::Intersect => "intersect", - }; - KernelError::Failed(format!( - "the {verb} could not be computed reliably: {what}. The result was refused rather than kept wrong; \ - where the bodies only touch (faces flush with each other), overlapping them slightly usually helps" - )) -} - -/// Check the result of a Boolean that needed a retry (see the module docs). `result` is `None` -/// for an empty result. -pub(crate) fn check_retry(a: &Body, b: &Body, op: BoolOp, result: Option<&Body>) -> Result<()> { - if op == BoolOp::Intersect || a.is_mesh() || b.is_mesh() { - return Ok(()); - } - let Some(r) = result else { - // Nothing left: only a cut whose tool covers the whole target (to within the meshes' - // chords: a tool touching a round side of the target). - let chord = a.size().max(b.size()) * 1e-3; - let (Ok(ma), Ok(mb)) = (a.tessellate(chord), b.tessellate(chord)) else { return Ok(()) }; - let (ba, bb) = (ma.bounds(), mb.bounds()); - let tol = 2.0 * chord; - let within = ba.min.x >= bb.min.x - tol - && ba.min.y >= bb.min.y - tol - && ba.min.z >= bb.min.z - tol - && ba.max.x <= bb.max.x + tol - && ba.max.y <= bb.max.y + tol - && ba.max.z <= bb.max.z + tol; - return if op == BoolOp::Cut && within { Ok(()) } else { Err(bad(op, "it came out empty".into())) }; - }; - if r.solid.boundaries().iter().any(|s| s.shell_condition() != truck_modeling::ShellCondition::Closed) { - return Err(bad(op, "the result is not closed".into())); - } - let size = a.size().max(b.size()); - let t = (size * 2e-4).max(1e-5); - let (Ok(ma), Ok(mb), Ok(mr)) = (a.tessellate_with(t, true), b.tessellate_with(t, true), r.tessellate_with(t, true)) else { - return Err(bad(op, "the result could not be checked".into())); - }; - // A mesh as coarse as `t` on a round smaller than it has no inside to speak of (a through - // hole 0.13 mm across in a 900 mm slab measured −30272 mm³, #1255): the volumes are measured - // at a tenth of the bodies' smallest radius, where that is finer. All three at the same - // tolerance, so the chords' error on the faces they share cancels. `scale` refines it all. - let finest = [a, b, r].iter().filter_map(|x| smallest_radius(x)).fold(f64::INFINITY, f64::min); - let fine = if finest * 0.1 < t { (finest * 0.1).max(t * 1e-2) } else { t }; - let volume = |body: &Body, mesh: &Mesh, scale: f64| -> Result { - if fine == t && scale == 1.0 { - return Ok(mesh.measure().volume); - } - body.tessellate_with(fine * scale, true).map(|m| m.measure().volume).map_err(|_| bad(op, "the result could not be checked".into())) - }; - let judge = |scale: f64| -> Result<(bool, f64, f64, f64)> { - let (va, vb, vr) = (volume(a, &ma, scale)?, volume(b, &mb, scale)?, volume(r, &mr, scale)?); - let slack = 2e-4 * (va.abs() + vb.abs()) + 1e-9; - let ok = vr.is_finite() - && match op { - BoolOp::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack, - BoolOp::Cut => vr <= va + slack && vr >= va - vb - slack, - BoolOp::Intersect => true, - }; - Ok((ok, va, vb, vr)) - }; - // A volume out of bounds is measured again ten times finer before it refuses the result: - // the coarse meshes of a part with many rounds can be off by more than the slack (a 0.8 mm - // hole through a plastic part's wall measured 6.8 mm³ more than the part, #1255). - let (mut volume_ok, mut va, mut vb, mut vr) = judge(1.0)?; - if !volume_ok { - (volume_ok, va, vb, vr) = judge(0.1)?; - } - if !volume_ok { - let what = match op { - BoolOp::Union => format!("the joined body's volume would be {vr:.4} mm³ (the target is {va:.4} mm³, the tool {vb:.4} mm³)"), - _ => format!("the cut body's volume would be {vr:.4} mm³ (the target is {va:.4} mm³, the tool {vb:.4} mm³)"), - }; - return Err(bad(op, what)); - } - // Outside the tool's box (with room for the meshes' chords and a nudge) the result's - // surface and the target's must be the same. - let reach = 3.0 * t + size * 1e-5; - let mut region = mb.bounds(); - region.min -= Vec3::new(reach, reach, reach) * 2.0; - region.max += Vec3::new(reach, reach, reach) * 2.0; - let (Some(near_a), Some(near_r)) = (Near::new(&ma, reach), Near::new(&mr, reach)) else { - return Err(bad(op, "the result could not be checked".into())); - }; - let at = |p: Vec3| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z); - if let Some(p) = stray_point(&mr, &near_a, ®ion) { - return Err(bad(op, format!("it would change the body away from the tool, at {} (outside the tool's region)", at(p)))); - } - if let Some(p) = stray_point(&ma, &near_r, ®ion) { - return Err(bad(op, format!("it would remove part of the body away from the tool, at {} (outside the tool's region)", at(p)))); - } - Ok(()) -} diff --git a/crates/kernel/src/boolean_history_tests.rs b/crates/kernel/src/boolean_history_tests.rs index 826466036..ac40c4540 100644 --- a/crates/kernel/src/boolean_history_tests.rs +++ b/crates/kernel/src/boolean_history_tests.rs @@ -2,11 +2,14 @@ //! of the operands (in tests only: the history itself is recorded, never sampled), and the exact //! origins asserted where the outcome is known. +use solidcraft_geom::prelude::*; use std::collections::BTreeSet; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use crate::body::Body; +use crate::history::BodyHistory; use crate::history::{Change, EdgeOrigin, FaceOrigin, History, Side}; use crate::{BoolOp, boolean, box_solid}; @@ -89,8 +92,8 @@ fn verified<'a>(r: &'a Body, operands: &[&Body], tol: f64) -> &'a History { pub(crate) fn checked<'a>(r: &'a Body, operands: &[&Body], tol: f64, at: Reach, generated: &dyn Fn(usize) -> bool) -> &'a History { let h = r.history().expect("the operation reports its history"); h.check(r, operands).unwrap(); - let rm = r.tessellate(tol).unwrap(); - let ms: Vec = operands.iter().map(|b| b.tessellate(tol).unwrap()).collect(); + let rm = r.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); + let ms: Vec = operands.iter().map(|b| b.mesh(&crate::MeshTolerance::chord(tol)).unwrap()).collect(); let near = 4.0 * tol + r.size() * 1e-6; let on = |o: &FaceOrigin, p: Vec3| match *o { FaceOrigin::Face { operand, face } => to_face(&ms[operand], face, p) < near.max(at.moved), @@ -186,16 +189,17 @@ fn faces_of(h: &History) -> Vec<(Change, Vec)> { h.faces.iter().map(|f| (f.change, f.origins.clone())).collect() } -/// Truck's boolean with a sphere (no prism, no coincident faces): a box with a corner taken -/// off by a sphere. The three faces at the corner get a notch, the sphere's patches inside the -/// box bound it, meeting the box's faces along new edges. +/// A boolean with a sphere (no prism, no coincident faces): a box with a corner taken +/// off by a sphere. The three faces at the corner get a notch, the sphere's one face (SMLib's +/// sphere is one periodic face) bounds it inside the box, meeting each notched face along a new +/// edge. #[test] -fn box_minus_sphere_through_truck() { +fn box_minus_sphere() { let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap(); let r = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&a, &b], 0.02); - assert_eq!(changes(h), [3, 6, 0, 0, 0], "{}", show(h)); + assert_eq!(changes(h), [3, 4, 0, 0, 0], "{}", show(h)); let from_b: BTreeSet = h .faces .iter() @@ -205,36 +209,12 @@ fn box_minus_sphere_through_truck() { _ => None, }) .collect(); - assert_eq!(from_b.len(), 3); - // Each notched box face meets two of the sphere's patches. - assert_eq!(meets(h).len(), 6, "{}", show(h)); + assert_eq!(from_b.len(), 1); + // Each notched box face meets the sphere. + assert_eq!(meets(h).len(), 3, "{}", show(h)); assert!(meets(h).iter().all(|(x, y)| matches!((x, y), (FaceOrigin::Face { operand: 0, .. }, FaceOrigin::Face { operand: 1, .. })))); } -/// The jitter retries move both operands and the result back: the history holds for the -/// operands themselves, the same faces coming from the same operand faces. -#[test] -fn shifted_truck_attempt_keeps_the_history() { - let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); - let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap(); - let counts = crate::record::counts(&[&a, &b]); - let mut compared = 0; - for op in [BoolOp::Cut, BoolOp::Union, BoolOp::Intersect] { - let Ok((_, Some((plain, _)))) = crate::ops::truck_boolean(&a, &b, op, None, 0.035) else { continue }; - // The shifts the retries use (a hundredth of the size along each). - for j in [[0.1373, 0.2719, 0.3911], [-0.5127, 0.0833, 0.2291], [0.6911, -0.3337, -0.6127]] { - let shift = truck_modeling::Vector3::new(j[0], j[1], j[2]) * 0.17; - let Ok((s, h)) = crate::ops::truck_boolean(&a, &b, op, Some(shift), 0.035) else { continue }; - let faces = h.as_ref().map(|(f, _)| f.clone()); - assert_eq!(faces, Some(plain.clone()), "{op:?}"); - let r = crate::boolean_record::truck_result(s, h, 17.4, &[], &counts).unwrap(); - verified(&r, &[&a, &b], 0.02); - compared += 1; - } - } - assert!(compared > 0); -} - /// Two prisms along x, the tool's section inside the target's, overlapping in part: sewn slab by /// slab, then healed. The target's face at x = 10 gets the tool's outline as a hole, which the /// tool's sides meet; the tool's sides and far end stand out of it. @@ -254,9 +234,10 @@ fn box_union_box_prism() { }) .collect(); origins.sort(); - // All of a's faces, and b's but the end inside a. + // All of a's faces, and b's but the end inside a (its face at x = 5). let mut want: Vec = (0..6).map(|i| face(0, i)).chain((0..6).map(|i| face(1, i))).collect(); - let inside = face(1, 4); + let inside = + face(1, b.faces(1e-3).unwrap().iter().position(|f| (f.centroid.x - 5.0).abs() < 1e-6 && f.plane_normal.is_some_and(|n| n.x < -0.9)).unwrap()); want.retain(|o| *o != inside); assert_eq!(origins, want, "{}", show(h)); // b's four sides meet a's face at x = 10. @@ -266,22 +247,22 @@ fn box_union_box_prism() { assert!(h.edges.iter().all(|e| e.origins.len() == 1)); } -/// A through hole: the box's sides are kept, top and bottom get the hole, the cylinder's two -/// half walls line it, meeting top and bottom along its rims, and meet each other along the -/// cylinder's own seams. +/// A through hole: the box's sides are kept, top and bottom get the hole, the cylinder's wall +/// (one periodic face) lines it, meeting top and bottom along its rims, and closes on itself +/// along the cylinder's own seam. #[test] fn box_minus_cylinder_prism() { let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); let b = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 12.0).unwrap(); let r = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&a, &b], 0.01); - assert_eq!(changes(h), [4, 4, 0, 0, 0], "{}", show(h)); - let walls = from(h, face(1, 1)).len() + from(h, face(1, 2)).len(); - assert_eq!(walls, 2, "{}", show(h)); - // Rims: each wall meets top and bottom. - assert_eq!(meets(h).len(), 4, "{}", show(h)); + assert_eq!(changes(h), [4, 3, 0, 0, 0], "{}", show(h)); + let side = (0..b.face_count()).find(|i| b.planar_face(*i).is_none()).unwrap(); + assert_eq!(from(h, face(1, side)).len(), 1, "{}", show(h)); + // Rims: the wall meets top and bottom. + assert_eq!(meets(h).len(), 2, "{}", show(h)); let seams = h.edges.iter().filter(|e| matches!(e.origins.as_slice(), [EdgeOrigin::Edge { operand: 1, .. }])).count(); - assert_eq!(seams, 2); + assert_eq!(seams, 1); // Every other edge is one of the box's twelve. let boxed_edges: BTreeSet<_> = h.edges.iter().flat_map(|e| &e.origins).filter(|o| matches!(o, EdgeOrigin::Edge { operand: 0, .. })).collect(); assert_eq!(boxed_edges.len(), 12); @@ -333,87 +314,28 @@ fn trivial_paths() { assert!(h.faces.iter().all(|f| f.change == Change::Kept)); } -/// A body in two pieces, cut a piece at a time: each piece's faces are the body's own. +/// A body in two pieces, cut: each piece's faces are the body's own. #[test] -fn by_lumps_composes_the_pieces() { +fn a_cut_of_two_pieces_composes_the_pieces() { let left = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); let right = boxed(20.0, 0.0, 0.0, 30.0, 10.0, 10.0); let a = boolean(&left, &right, BoolOp::Union).unwrap().unwrap(); assert_eq!(a.shell_count(), 2); let b = crate::sphere(Vec3::new(15.0, 5.0, 10.0), 7.0).unwrap(); - let r = crate::ops::by_lumps(&a, &b, a.lumps().unwrap(), b.lumps().unwrap(), BoolOp::Cut).unwrap().unwrap(); + let r = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&a, &b], 0.02); - // Both pieces are bitten: the sphere's patches inside each line its bite. - let bites: BTreeSet<_> = h.faces.iter().flat_map(|f| &f.origins).filter(|o| matches!(o, FaceOrigin::Face { operand: 1, .. })).collect(); - assert!(bites.len() >= 2, "{}", show(h)); + // Both pieces are bitten: a piece of the sphere's face lines each bite. + let bites = h.faces.iter().filter(|f| matches!(f.origins.as_slice(), [FaceOrigin::Face { operand: 1, .. }])).count(); + assert!(bites >= 2, "{}", show(h)); let targets: BTreeSet<_> = h.faces.iter().flat_map(|f| &f.origins).filter(|o| matches!(o, FaceOrigin::Face { operand: 0, .. })).collect(); assert_eq!(targets.len(), 12); } -/// Two bodies touching along one whole face, back to back: glued, the two faces gone, the -/// coplanar sides each side of the seam merged. -#[test] -fn glue_merges_across_the_seam() { - let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); - let b = boxed(10.0, 0.0, 0.0, 20.0, 10.0, 10.0); - let r = crate::coplanar::glue(&a, &b).unwrap().unwrap(); - let h = verified(&r, &[&a, &b], 0.02); - assert_eq!(changes(h), [2, 0, 0, 4, 0], "{}", show(h)); - // The four seam edges went with the merged faces; the ends' edges are each box's. - assert_eq!(h.edges.len(), 12); - assert!(h.edges.iter().all(|e| !e.origins.is_empty())); -} - -/// Coincident faces pushed apart: a cut flush with the target's top, and a union of bodies -/// standing on one floor (the floor that is cut back is both operands' floors). -#[test] -fn faces_pushed_apart() { - let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); - let tool = boxed(2.0, 2.0, 5.0, 8.0, 8.0, 10.0); - let r = crate::coplanar::boolean_apart(&a, &tool, BoolOp::Cut).unwrap().unwrap().unwrap(); - let h = verified(&r, &[&a, &tool], 0.02); - // The pocket: its floor and four sides are the tool's. - let tool_faces: BTreeSet<_> = h.faces.iter().flat_map(|f| &f.origins).filter(|o| matches!(o, FaceOrigin::Face { operand: 1, .. })).collect(); - assert_eq!(tool_faces.len(), 5, "{}", show(h)); - let left = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); - let right = boxed(5.0, 3.0, 0.0, 15.0, 7.0, 4.0); - let r = crate::coplanar::boolean_apart(&left, &right, BoolOp::Union).unwrap().unwrap().unwrap(); - let h = verified(&r, &[&left, &right], 0.02); - assert!(h.faces.iter().any(|f| f.change == Change::Merged && f.origins.len() == 2), "{}", show(h)); -} - -/// The exact polygon boolean: pieces of planar faces joined back into faces. -#[test] -fn planar_fallback() { - let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); - let b = boxed(5.0, 5.0, 5.0, 15.0, 15.0, 15.0); - for (op, count) in [(BoolOp::Cut, 9), (BoolOp::Union, 12), (BoolOp::Intersect, 6)] { - let r = crate::polybool::planar_boolean(&a, &b, op).unwrap().unwrap(); - let h = verified(&r, &[&a, &b], 0.02); - assert_eq!(h.faces.len(), count, "{op:?}\n{}", show(h)); - assert!(h.faces.iter().all(|f| f.origins.len() == 1)); - // Three faces of each meet three of the other's. - assert_eq!(meets(h).len(), 6, "{op:?}\n{}", show(h)); - assert!(h.edges.iter().all(|e| e.origins.len() == 1), "{op:?}\n{}", show(h)); - } -} - -/// The nudged retry: a boolean with the tool moved a hair, composed with the move. -#[test] -fn nudged_tool_composes() { - let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); - let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap(); - let nb = crate::transform(&b, Vec3::new(1e-5, 0.0, 0.0), Vec3::ZERO, Vec3::Z, 0.0).unwrap(); - let r = boolean(&a, &nb, BoolOp::Cut).unwrap().unwrap(); - let r = crate::ops::nudged(r, &nb, &crate::record::counts(&[&a, &b])); - verified(&r, &[&a, &b], 0.02); -} - /// A boolean with a triangle mesh: the mesh's faces are its triangles (and it has no edges). #[test] fn faceted_tool() { let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); - let tool = boxed(5.0, 5.0, 5.0, 15.0, 15.0, 15.0).tessellate(0.1).unwrap(); + let tool = boxed(5.0, 5.0, 5.0, 15.0, 15.0, 15.0).mesh(&crate::MeshTolerance::chord(0.1)).unwrap(); let r = crate::faceted_boolean(&a, &tool, BoolOp::Cut, 0.01).unwrap().unwrap(); let h = r.history().expect("the faceted boolean reports its history"); h.check_counts((r.face_count(), r.edge_count()), &[(a.face_count(), a.edge_count()), (tool.triangles.len(), 0)]).unwrap(); @@ -423,11 +345,11 @@ fn faceted_tool() { assert_eq!(h.faces.iter().filter(|f| matches!(f.origins.first(), Some(FaceOrigin::Face { operand: 1, .. }))).count(), 3); } -/// A partial-depth cut of stepped prisms: walls over one segment through successive slabs are -/// sewn as one face (coalesced), which comes from the operand walls under it in every slab. +/// A partial-depth cut of a prism by a narrower one: the stock's walls run whole from 0 to 20, +/// one face each past the cutter's floor, untouched (Kept). #[test] -fn coalesced_stepped_walls() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; +fn stepped_cut_keeps_the_stock_walls_whole() { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; for curved in [true, false] { let (outer, inner) = if curved { (Loop2::circle(Vec2::ZERO, 10.0), Loop2::circle(Vec2::ZERO, 5.0)) @@ -439,20 +361,19 @@ fn coalesced_stepped_walls() { let cutter = crate::extrude(&Plane::XY, &[Region2 { outer: inner, holes: vec![] }], 2.0, 22.0).unwrap().pop().unwrap(); let r = boolean(&stock, &cutter, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&stock, &cutter], 0.01); - // The stock's walls run whole from 0 to 20, one face each, past the cutter's floor. - let walls: Vec = (0..r.face_count()).filter(|i| r.face_was_coalesced(*i)).collect(); - assert_eq!(walls.len(), if curved { 2 } else { 4 }, "{}", show(h)); + let walls: Vec = + stock.faces(1e-3).unwrap().iter().enumerate().filter(|(_, f)| f.plane_normal.is_none_or(|n| n.z.abs() < 0.5)).map(|(i, _)| i).collect(); + assert_eq!(walls.len(), if curved { 1 } else { 4 }); for i in walls { - assert!(matches!(h.faces[i].origins.as_slice(), [FaceOrigin::Face { operand: 0, .. }]), "{}", show(h)); - assert_eq!(h.faces[i].change, Change::Modified, "{}", show(h)); + let pieces = from(h, face(0, i)); + assert_eq!(pieces.len(), 1, "{}", show(h)); + assert_eq!(h.faces[pieces[0]].change, Change::Kept, "{}", show(h)); } } } -/// A step cut into a box: the stepped prism path sews the box's face 3 in pieces at the -/// slab stations, and the joining of generated walls on their common supports makes it one face -/// again; the joined body keeps the sewn body's history composed through the join. A certified -/// box (whose planar regularization would join the same pieces) gets the same history. +/// A step cut into a box: the box's top (z = 7.5) loses the step's corner, one face still +/// (Modified). A certified box gets the same history as a plain one. #[test] fn regularized_step_cut() { let (pa, pb) = (boxed(0.0, 0.0, 0.0, 30.0, 35.0, 7.5), boxed(0.0, 30.0, 2.5, 22.5, 50.0, 25.0)); @@ -461,30 +382,13 @@ fn regularized_step_cut() { let h = verified(&r, &[&a, &b], 0.01); let plain = boolean(&pa, &pb, BoolOp::Cut).unwrap().unwrap(); let ph = verified(&plain, &[&pa, &pb], 0.01); - let joined = from(ph, face(0, 3)); + let top = pa.faces(1e-3).unwrap().iter().position(|f| (f.centroid.z - 7.5).abs() < 1e-9).unwrap(); + let joined = from(ph, face(0, top)); assert_eq!(joined.len(), 1, "{}", show(ph)); - assert_eq!(faces_of(ph)[joined[0]], (Change::Modified, vec![face(0, 3)])); + assert_eq!(faces_of(ph)[joined[0]], (Change::Modified, vec![face(0, top)])); assert_eq!(faces_of(h), faces_of(ph), "{}", show(h)); } -/// A ring joined under a floor, its bore on the floor's hole (coincident cylinders): the ring's -/// bore is narrowed, the bodies joined, and the bore cut out again. The ring's bore is a circle -/// built in two arcs, and the recut wall is split where the cutting cylinder's own construction -/// splits it, so which arc each piece of it restores is not known: no history. -#[test] -fn bore_union_of_a_bore_in_two_arcs_has_no_history() { - let hole = crate::cylinder(Vec3::new(50.0, 40.0, -5.0), Vec3::Z, 10.0, 30.0).unwrap(); - let floor = boolean(&boxed(0.0, 0.0, 0.0, 100.0, 80.0, 10.0), &hole, BoolOp::Cut).unwrap().unwrap(); - let centre = solidcraft_geom::Vec2::new(50.0, 40.0); - let annulus = solidcraft_geom::Region2 { - outer: solidcraft_geom::Loop2::circle(centre, 20.0), - holes: vec![solidcraft_geom::Loop2::circle(centre, 10.0).reversed()], - }; - let ring = crate::extrude(&solidcraft_geom::Plane::XY, &[annulus], -5.0, 2.0).unwrap().remove(0); - let r = crate::coplanar::bore_union(&floor, &ring, &|_| true).expect("the bores are recut"); - assert!(r.history().is_none()); -} - /// Bodies clearly apart, joined as one body of several pieces (`union_apart`): every face and /// edge is its piece's own, kept. #[test] @@ -524,3 +428,99 @@ fn stacked_pieces_of_one_cylinder_keep_their_walls() { } } } + +/// The same booleans through SMLib: its tags, renumbered into the operands' and the result's +/// face and edge order, give a history that holds against the geometry. +mod smlib { + use super::*; + use crate::smlib_boolean::smlib_boolean; + + fn through_smlib(a: &Body, b: &Body, op: BoolOp) -> Body { + smlib_boolean(a, b, op).unwrap().expect("a result") + } + + #[test] + fn operands_number_as_their_records() { + let bodies = [ + boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0), + crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 12.0).unwrap(), + crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap(), + crate::torus(Vec3::new(0.0, 0.0, 0.0), 10.0, 2.0).unwrap(), + ]; + // SMLib imports a record's faces and edges in the record's order, and the record is + // already canonical: SMLib's face and edge i are the record's i (the order is the + // identity, or empty, which says the same), with no edge split into pieces. + for (i, b) in bodies.iter().enumerate() { + let (_, order) = crate::native::smlib_body_ordered(b).unwrap(); + let order = order.unwrap_or_else(|| panic!("body {i}: no order")); + let identity = |to: &[usize], n: usize| to.is_empty() || to.iter().copied().eq(0..n); + assert!(identity(&order.faces, b.face_count()), "body {i}: faces {:?}", order.faces); + assert!(identity(&order.edges, b.edge_count()), "body {i}: edges {:?}", order.edges); + assert!(order.pieces.is_empty(), "body {i}: {:?}", order.pieces); + } + } + + /// Cubes sharing an edge, and cubes sharing a vertex: SMLib's union touches itself there; + /// it comes back as two closed shells, the shared edge and vertices split into one copy per + /// cube, each copy with its edge's history (verified against the geometry). The copies say + /// how the two meet. + #[test] + fn cubes_touching_along_an_edge_or_at_a_vertex_unite_into_two_solids() { + use solidcore_record::brep::part::{Contact, RegionContact}; + let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); + for (name, b, contact) in [ + ("edge", boxed(10.0, 10.0, 0.0, 20.0, 20.0, 10.0), Contact::Edge), + ("vertex", boxed(10.0, 10.0, 10.0, 20.0, 20.0, 20.0), Contact::Vertex), + ] { + let r = through_smlib(&a, &b, BoolOp::Union); + assert_eq!(r.shell_count(), 2, "{name}"); + assert_eq!(r.region_contacts().unwrap(), vec![RegionContact { regions: [0, 1], contact }], "{name}"); + assert_eq!((r.face_count(), r.edge_count()), (12, 24), "{name}"); + let v = crate::measure(&r).unwrap().volume; + assert!((v - 2000.0).abs() < 1e-6 * 2000.0, "{name}: {v}"); + let h = verified(&r, &[&a, &b], 0.02); + assert!(h.faces.iter().all(|f| f.origins.len() == 1), "{name}: {}", show(h)); + } + } + + /// Pieces of a cut meeting along a line (two opposite quarters of a slab cut away) come + /// back as separate solids rather than a refusal. + #[test] + fn a_cut_leaving_pieces_along_a_line_gives_two_solids() { + let a = boxed(0.0, 0.0, 0.0, 20.0, 20.0, 10.0); + let once = through_smlib(&a, &boxed(10.0, -1.0, -1.0, 21.0, 10.0, 11.0), BoolOp::Cut); + let r = through_smlib(&once, &boxed(-1.0, 10.0, -1.0, 10.0, 21.0, 11.0), BoolOp::Cut); + assert_eq!(r.shell_count(), 2); + let v = crate::measure(&r).unwrap().volume; + assert!((v - 2000.0).abs() < 1e-6 * 2000.0, "{v}"); + } + + /// A block touching itself along a line: a through hole tangent to its side from inside, and + /// a blind hole tangent to its side (the side then on both sides of the line). SMLib's + /// result uses the tangent line four times; it comes back as one solid whose edges each bound + /// two faces, of the block's volume less the hole's, every face and edge's history verified + /// against the geometry. + #[test] + fn holes_tangent_to_the_side_come_back_as_one_solid() { + let a = boxed(0.0, 0.0, 0.0, 30.0, 20.0, 10.0); + for (name, z0, depth) in [("through", -1.0, 12.0), ("blind", 2.0, 9.0)] { + let b = crate::cylinder(Vec3::new(10.0, 15.0, z0), Vec3::Z, 5.0, depth).unwrap(); + let r = through_smlib(&a, &b, BoolOp::Cut); + assert_eq!(r.shell_count(), 1, "{name}"); + let record = crate::brep_record(&r).unwrap(); + assert!(record.edges.iter().all(|e| e.uses.len() == 2), "{name}"); + let hole = std::f64::consts::PI * 25.0 * (10.0 - z0.max(0.0)); + let v = crate::measure(&r).unwrap().volume; + assert!((v - (6000.0 - hole)).abs() < 1e-4 * 6000.0, "{name}: {v}"); + assert!(r.validity().is_empty(), "{name}: {:?}", r.validity()); + verified(&r, &[&a, &b], 0.02); + } + } + + #[test] + fn disjoint_intersection_is_empty() { + let a = boxed(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + let b = boxed(5.0, 5.0, 5.0, 6.0, 6.0, 6.0); + assert!(smlib_boolean(&a, &b, BoolOp::Intersect).unwrap().is_none()); + } +} diff --git a/crates/kernel/src/boolean_record.rs b/crates/kernel/src/boolean_record.rs index e52383bfa..6a7ae3246 100644 --- a/crates/kernel/src/boolean_record.rs +++ b/crates/kernel/src/boolean_record.rs @@ -1,22 +1,16 @@ -//! Recording the exact history of a boolean's result, whichever path made it (see -//! [`crate::ops::boolean`]): for each result face, the operand faces it is a region of; for each -//! result edge, the operand edges it lies along or the operand faces whose meeting it is. The -//! operands are `[a, b]`: the target, then the tool. Paths compose the histories of the steps -//! they take ([`History::over`], [`History::substitute`]); a path that cannot leaves the result -//! without history. - -use std::collections::HashMap; - -use solidcraft_geom::Vec3; -use truck_modeling as mt; +//! Composing the exact history of a multi-step operation (a boolean through several steps, a +//! local modifier on a healed body): each step's history over its own operands is placed among +//! the operation's operands ([`placed`], [`kept`]) and substituted into the next +//! ([`through`], [`crate::record::after`]). The operands of a boolean are `[a, b]`: +//! the target, then the tool. A step that cannot report its history leaves the result without +//! one. use crate::Result; -use crate::body::{Body, Solid, edge_order}; -use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv, History}; -use crate::record; +use crate::body::Body; +use crate::history::{BodyHistory, History}; /// A composition step's history, or none (logged) where the lineage can't be expressed. -pub(crate) fn composed(h: Result) -> Option { +pub(crate) fn composed(h: std::result::Result) -> Option { h.map_err(|e| log::debug!("no history: {e}")).ok() } @@ -43,191 +37,14 @@ pub(crate) fn operand(body: &Body, operand: usize, counts: &[(usize, usize)]) -> body.clone().with_checked_history(kept(body, operand, counts.len()), counts) } -/// The histories of `parts`, each made of shells of `whole` (its lumps), over `[whole]`: their -/// faces and edges are the whole's own (by identity). -pub(crate) fn parts_of(parts: &[Body], whole: &Body) -> Vec> { - let (faces, edges) = (record::face_index(&whole.solid), record::edge_origins(&whole.solid, 0)); - parts - .iter() - .map(|part| { - let faces = part.solid.face_iter().map(|f| Some(record::from_face(0, *faces.get(&f.id())?, Change::Kept))).collect::>>()?; - Some(History { operands: 1, faces, edges: record::edge_provs(part, &edges)? }) - }) - .collect() -} - -/// A body with its history over the operation's operands (`None`: not known). -pub(crate) type Traced = (Body, Option); - -/// The history over the operation's operands of `result`, made from `x` and `y` (in that order) -/// whose histories over them are given. -pub(crate) fn of_pair(result: &Body, x: &Option, y: &Option) -> Option { - composed(result.history()?.clone().over(&[x.as_ref()?, y.as_ref()?])) -} - -/// Bodies apart from each other, each with its history over the operation's operands (with -/// `counts` faces and edges), as one body of several pieces whose history is theirs side by side. -pub(crate) fn join(pieces: Vec, counts: &[(usize, usize)]) -> Result> { - if pieces.len() < 2 { - return Ok(pieces.into_iter().next().map(|(b, h)| b.with_checked_history(h, counts))); - } - // The pieces' shells in order: their faces in order, their edges themselves. - let mut faces = Some(Vec::new()); - let mut edges = HashMap::new(); - for (p, h) in &pieces { - let (Some(h), Some(all)) = (h, faces.as_mut()) else { - faces = None; - break; - }; - all.extend(h.faces.iter().cloned()); - edges.extend(record::edges_by_identity(p, h)); - } - if let Some(faces) = faces.as_mut() { - record::mark_shared_split(faces); - } - let joined = crate::ops::join_pieces(pieces.into_iter().map(|(p, _)| p).collect())?; - Ok(joined.map(|body| record::traced(body, counts, faces, Some(&edges)))) -} - -/// A truck boolean's history in our terms, in the order of the solid it made: each face a -/// region of one operand face (Kept when that very face), each edge's origins. -pub(crate) type Shapeops = (Vec, Vec>); - -/// A truck boolean's history in our terms ([`Shapeops`]). `tool` is the -/// tool as passed (after a cut turned it inside out, which keeps its faces' order but walks each -/// face's edges the other way, so its edge order changes) and `tool_edges` its edges by identity -/// in its own order (before turning). -pub(crate) fn shapeops(h: &truck_shapeops::History, tool: &Solid, tool_edges: Option<&HashMap>>) -> Option { - let face = |f: truck_shapeops::FaceIndex| FaceOrigin::Face { operand: f.operand, face: f.face }; - let faces = - h.faces.iter().map(|o| record::from_face(o.source.operand, o.source.face, if o.kept { Change::Kept } else { Change::Modified })).collect(); - let passed: Vec = edge_order(tool.face_iter()).0.iter().map(|e| e.id()).collect(); - let edges = h - .edges - .iter() - .map(|o| match *o { - truck_shapeops::EdgeOrigin::Edge { operand: 1, edge } if tool_edges.is_some() => { - tool_edges.and_then(|t| t.get(passed.get(edge)?)).cloned() - } - truck_shapeops::EdgeOrigin::Edge { operand, edge } => Some(vec![EdgeOrigin::Edge { operand, edge }]), - truck_shapeops::EdgeOrigin::Meet { a, b } => Some(vec![EdgeOrigin::meet(face(a), face(b))]), - }) - .collect::>>()?; - Some((faces, edges)) -} - -/// Samples along each edge when checking that its curve evaluates. -const EVALUATION_SAMPLES: usize = 32; - -/// Whether every edge of `solid` evaluates along its whole range. An intersection curve projects -/// its leader's point onto both surfaces, which fails to converge where a boolean made the edge -/// from an approximation that strayed (#1252). Such a result is no solid to keep: the mesher, -/// healing and measuring all sample the edge and stumble over the gap. -pub(crate) fn edges_evaluate(solid: &Solid) -> bool { - use truck_meshalgo::prelude::TrySubs; - use truck_modeling::BoundedCurve; - solid.boundaries().iter().flat_map(|shell| shell.edge_iter()).all(|edge| { - let curve = edge.curve(); - let (t0, t1) = curve.range_tuple(); - (0..=EVALUATION_SAMPLES).all(|k| { - let t = t0 + (t1 - t0) * k as f64 / EVALUATION_SAMPLES as f64; - curve.try_subs(t).is_some_and(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()) - }) - }) -} - -/// The body made of `solid` healed (keeping faces apart along `keep`), with the history whose -/// faces and edges (in `solid`'s orders) are given before healing, carried through it. -/// Operands with `counts` faces and edges. A result with an edge that does not evaluate is -/// refused (see [`edges_evaluate`]). -pub(crate) fn heal_build( - solid: Solid, - size: f64, - keep: &[Vec], - faces: Option>, - edges: Option>>, - counts: &[(usize, usize)], -) -> Result { - let (healed, map) = crate::heal::heal_traced(solid, size, keep); - if !edges_evaluate(&healed) { - return Err(crate::KernelError::Failed("an edge of the result does not evaluate".into())); - } - let carried = faces.zip(edges).zip(map).and_then(|((f, e), m)| m.carry(&f, &e)); - let (faces, edges) = carried.unzip(); - record::build(healed, counts, faces, edges.as_ref()) -} - -/// The body truck's result `s` makes, healed (see [`heal_build`]), with its history `h`. -pub(crate) fn truck_result(s: Solid, h: Option, size: f64, keep: &[Vec], counts: &[(usize, usize)]) -> Result { - let (faces, edges) = h.unzip(); - heal_build(s, size, keep, faces, edges, counts) -} - -/// `body` healed (see [`heal_build`]), its history carried through: `solid` is `body`'s solid -/// or a copy of it (`Body::deep_copy`, which keeps its order). -pub(crate) fn heal_body(body: &Body, solid: Solid, size: f64, keep: &[Vec], counts: &[(usize, usize)]) -> Result { - let (faces, edges) = body.history().map(|h| (h.faces.clone(), h.edges.iter().map(|e| e.origins.clone()).collect())).unzip(); - heal_build(solid, size, keep, faces, edges, counts) -} - -/// A prism boolean's result `body` with the coplanar pieces its slabs leave merged (nothing -/// else healed: its edges are exact as they are), its history carried through, and what else it carries kept: each face's -/// construction source where every piece merged into it had that same one, its Split Face -/// lines and its regularization protection. -pub(crate) fn heal_prism_result(body: &Body, size: f64, keep: &[Vec], counts: &[(usize, usize)]) -> Result { - let (faces, edges): (Option>, Option>>) = - body.history().map(|h| (h.faces.clone(), h.edges.iter().map(|e| e.origins.clone()).collect())).unzip(); - let (healed, map) = crate::heal::merge_faces_traced((*body.solid).clone(), size, keep); - let sources = match (body.face_sources(), &map) { - (Some(sources), Some(m)) => Some( - m.faces - .iter() - .map(|under| { - let mut each = under.iter().map(|i| sources.get(*i).cloned().flatten()); - let first = each.next().flatten()?; - each.all(|s| s.as_ref() == Some(&first)).then_some(first) - }) - .collect::>(), - ), - _ => None, - }; - let carried = faces.zip(edges).zip(map).and_then(|((f, e), m)| m.carry(&f, &e)); - let (faces, edges) = carried.unzip(); - let mut out = record::build(healed, counts, faces, edges.as_ref())?; - out = out.with_face_sources(sources.map(std::sync::Arc::new)).inherit_regularization_protection(body); - out.splits = body.splits.clone(); - Ok(out) -} - -/// `body` healed as the local modifiers take it (coplanar neighbours as one face, as after a -/// join; faces split on purpose kept apart), with its history over `[body]`. +/// `body` healed as the local modifiers take it (faces on one surface as one face, as after a +/// join; faces split on purpose kept apart), with its history over `[body]` +/// ([`crate::heal::heal`]), each face keeping the construction source its faces shared and the +/// body its regularization protection. pub(crate) fn healed(body: &Body) -> Result { - let counts = record::counts(&[body]); - heal_body(&operand(body, 0, &counts), body.deep_copy(), body.size(), body.split_keep(), &counts) -} - -/// `body` copied as it is, unhealed (`Body::deep_copy`, which keeps its face and edge order), -/// with its history over `[body]`: every face and edge kept. -pub(crate) fn copied(body: &Body) -> Result { - let copy = Body::new(body.deep_copy())?; - Ok(operand(©, 0, &record::counts(&[body]))) -} - -/// The faces and edges of `a`, then of the tool `b` turned inside out as a void (`inner`, a -/// copy of `b`, with `inner_edges` its edges by identity before turning): the history of -/// `a` with `b`'s inside taken out where `b` lies wholly within it. -pub(crate) fn void( - a: &Body, - inner_edges: HashMap>, - b_faces: usize, -) -> (Vec, HashMap>) { - let faces = (0..a.face_count()) - .map(|i| record::from_face(0, i, Change::Kept)) - .chain((0..b_faces).map(|i| record::from_face(1, i, Change::Kept))) - .collect(); - let mut edges = record::edge_origins(&a.solid, 0); - edges.extend(inner_edges); - (faces, edges) + let healed = crate::heal::heal(body, body.split_keep())?; + let sources = healed.history().map(|h| std::sync::Arc::new(h.face_sources(&[body]))); + Ok(healed.with_face_sources(sources).inherit_regularization_protection(body)) } #[cfg(test)] diff --git a/crates/kernel/src/bore_guard.rs b/crates/kernel/src/bore_guard.rs deleted file mode 100644 index 2b6651f9e..000000000 --- a/crates/kernel/src/bore_guard.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! Necessary boundary safety check for the narrowed-bore fallback. -//! This is not a certificate of general Boolean equivalence. It prevents a -//! cylinder recut from silently removing an additional material boundary that -//! the fallback's coarse material samples do not see. -use crate::body::{Body, from_p3}; -use solidcraft_geom::{Plane, Seg2, UnitVec3, Vec3}; -use std::collections::HashSet; -use truck_modeling as mt; - -pub(super) fn boundaries_clear( - body: &Body, - bore_faces: &[usize], - origin: Vec3, - axis: UnitVec3, - radius: f64, - lo: f64, - hi: f64, - tol: f64, -) -> Option<()> { - let plane = Plane::from_normal(origin, axis)?; - if !origin.is_finite() - || ![radius, lo, hi, tol].iter().all(|v| v.is_finite()) - || radius <= tol - || hi <= lo - || tol <= 0. - || bore_faces.len() > 16_384 - { - return None; - } - let mut remaining_faces = 16_384usize; - let mut remaining_uses = 65_536usize; - for face in body.solid.face_iter() { - remaining_faces = remaining_faces.checked_sub(1)?; - for wire in face.absolute_boundaries() { - for _ in wire.edge_iter() { - remaining_uses = remaining_uses.checked_sub(1)?; - } - } - } - // Exempt only existing coincident bore boundaries, never newly inferred - // edges or every edge of a planar face adjoining a cylinder. - let bore_faces: HashSet = bore_faces.iter().copied().collect(); - let mut bore_edges = HashSet::new(); - for (i, face) in body.solid.face_iter().enumerate() { - if bore_faces.contains(&i) { - for edge in face.edge_iter() { - bore_edges.insert(edge.id()); - } - } - } - let mut seen = HashSet::new(); - let mut work = 2_000_000usize; - for edge in body.solid.edge_iter() { - if !seen.insert(edge.id()) { - continue; - } - let common_bore = bore_edges.contains(&edge.id()); - work = work.checked_sub(1)?; - let curve = edge.curve(); - // Original matched-cylinder trims retain the legacy fallback policy. - // Boolean-produced rational trims need not be exact analytic circles. - // This exemption follows existing face/edge identity only; additional - // trims must pass the whole-boundary proof below. It is deliberately - // not a general proof that the cylinder contains no material. - if common_bore && matches!(curve, mt::Curve::IntersectionCurve(_) | mt::Curve::BSplineCurve(_) | mt::Curve::NurbsCurve(_)) { - continue; - } - if let mt::Curve::Line(line) = curve { - let (a, b) = (from_p3(line.0), from_p3(line.1)); - if !a.is_finite() || !b.is_finite() { - return None; - } - let ha = plane.height(a); - let hb = plane.height(b); - let error = tol + 512. * f64::EPSILON * (1. + a.len() + b.len() + origin.len()); - if common_bore { - let pa = plane.to_local(a); - let pb = plane.to_local(b); - if pa.dist(pb) <= error && (pa.len() - radius).abs() + (pb.len() - radius).abs() <= error * 2. { - continue; - } - return None; - } - let (mut t0, mut t1): (f64, f64) = (0., 1.); - let dh = hb - ha; - if dh.abs() <= error { - if ha.min(hb) > hi + error || ha.max(hb) < lo - error { - continue; - } - } else { - let x = (lo - error - ha) / dh; - let y = (hi + error - ha) / dh; - t0 = t0.max(x.min(y)); - t1 = t1.min(x.max(y)); - if t0 > t1 { - continue; - } - } - let pa = plane.to_local(a + (b - a) * t0); - let pb = plane.to_local(a + (b - a) * t1); - let d = pb - pa; - let t = if d.len2() > 0. { (-pa.dot(d) / d.len2()).clamp(0., 1.) } else { 0. }; - if (pa + d * t).len() <= radius + error { - return None; - } - continue; - } - // Positive rational controls enclose the entire axial extent. Project - // the current curve onto the axis plane; the existing whole-span - // certificate proves its Line/Arc image, without point sampling. - let (knots, controls): (mt::KnotVec, Vec) = match curve { - mt::Curve::BSplineCurve(c) => { - if c.control_points().len() > 4096 || c.knot_vec().len() > 8192 { - return None; - } - work = work.checked_sub(c.control_points().len().checked_add(c.knot_vec().len())?)?; - (c.knot_vec().clone(), c.control_points().iter().map(|p| mt::Vector4::new(p.x, p.y, p.z, 1.)).collect()) - } - mt::Curve::NurbsCurve(c) => { - if c.control_points().len() > 4096 || c.knot_vec().len() > 8192 { - return None; - } - work = work.checked_sub(c.control_points().len().checked_add(c.knot_vec().len())?)?; - (c.knot_vec().clone(), c.control_points().clone()) - } - _ => return None, - }; - let mut heights = (f64::INFINITY, f64::NEG_INFINITY); - let mut projection_error: f64 = 0.; - let mut projected_origin = None; - let mut projected_spread: f64 = 0.; - let mut projected = Vec::with_capacity(controls.len()); - for p in controls { - if ![p.x, p.y, p.z, p.w].iter().all(|v| v.is_finite()) || p.w <= 0. { - return None; - } - let point = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w); - if !point.is_finite() { - return None; - } - let error = tol + 512. * f64::EPSILON * (1. + point.len() + origin.len()); - projection_error = projection_error.max(error); - let h = plane.height(point); - heights.0 = heights.0.min(h - error); - heights.1 = heights.1.max(h + error); - let q = plane.to_local(point); - let first = *projected_origin.get_or_insert(q); - projected_spread = projected_spread.max(q.dist(first)); - projected.push(mt::Vector4::new(q.x * p.w, q.y * p.w, 0., p.w)); - } - if heights.0 > hi || heights.1 < lo { - continue; - } - // A swept seam may be represented as a rational straight edge. Its - // positive control hull proves a point-sized radial projection even - // though a nondegenerate planar Line/Arc recognizer cannot accept it. - if let Some(q) = projected_origin { - if common_bore && projected_spread + projection_error + (q.len() - radius).abs() <= tol * 8. { - continue; - } - if !common_bore && q.len() - projected_spread - projection_error > radius + tol * 4. { - continue; - } - } - use mt::{BoundedCurve, ParametricCurve}; - let projected = mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::try_new(knots, projected).ok()?)); - let (a, b) = projected.range_tuple(); - let projected_edge = mt::Edge::new(&mt::Vertex::new(projected.subs(a)), &mt::Vertex::new(projected.subs(b)), projected); - let segments = crate::prism_curve::segment(&projected_edge, &Plane::XY, tol, &mut work)?; - for segment in segments { - if common_bore { - if let Seg2::Arc { center, radius: r, .. } = segment - && center.len() + (r - radius).abs() + projection_error <= tol * 8. - { - continue; - } - return None; - } - let clearance = match segment { - Seg2::Line { a, b } => { - let d = b - a; - let t = if d.len2() > 0. { (-a.dot(d) / d.len2()).clamp(0., 1.) } else { 0. }; - (a + d * t).len() - } - Seg2::Arc { center, radius, .. } => radius - center.len(), - _ => return None, - }; - if clearance <= radius + tol * 4. + projection_error { - return None; - } - } - } - Some(()) -} diff --git a/crates/kernel/src/bore_union_tests.rs b/crates/kernel/src/bore_union_tests.rs deleted file mode 100644 index 7dd91a1ee..000000000 --- a/crates/kernel/src/bore_union_tests.rs +++ /dev/null @@ -1,135 +0,0 @@ -#![allow(clippy::unwrap_used, clippy::panic)] -use crate::*; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; - -fn fixture() -> (Body, Body, Vec3, f64) { - let slope = 1f64.to_radians().tan(); - let hs = |normal: Vec3, point: Vec3| { - let n = normal.normalized().unwrap(); - HalfSpace { n, d: n.dot(point) } - }; - let stock = convex_polyhedron(&[ - hs(Vec3::X, Vec3::new(40., 0., 0.)), - hs(-Vec3::X, Vec3::ZERO), - hs(Vec3::Y, Vec3::new(0., 30., 0.)), - hs(-Vec3::Y, Vec3::ZERO), - hs(-Vec3::Z, Vec3::ZERO), - hs(Vec3::new(-slope, 0., 1.), Vec3::new(0., 0., 20.)), - ]) - .unwrap(); - let cutter = cylinder(Vec3::new(20., 15., -5.), Vec3::Z, 5., 40.).unwrap(); - let bored = boolean(&stock, &cutter, BoolOp::Cut).unwrap().unwrap(); - let web = box_solid(Vec3::new(14., 14., 16.05), Vec3::new(26., 16., 16.07)).unwrap(); - let target = boolean(&bored, &web, BoolOp::Union).unwrap().unwrap(); - let region = Region2 { outer: Loop2::circle(Vec2::new(20., 15.), 8.), holes: vec![Loop2::circle(Vec2::new(20., 15.), 5.).reversed()] }; - let ring = extrude(&Plane::XY, &[region], 14., 24.).unwrap().remove(0); - let web_volume = 0.02 * 2. * (24f64.sqrt() + 25. * 0.2f64.asin()); - let fine_target = target.tessellate_with(1e-4, true).unwrap(); - let added = fine_target.measure().volume - bored.tessellate_with(1e-4, true).unwrap().measure().volume; - assert!((added - web_volume).abs() < 0.005, "actual connected web adds {added}, expected {web_volume}"); - for x in [16., 20., 24.] { - for y in [14.2, 15., 15.8] { - assert!(fine_target.contains(Vec3::new(x, y, 16.06)), "source web must exist at {x},{y}"); - } - } - assert!(!fine_target.contains(Vec3::new(20., 12., 16.06))); - let floor_volume = (20. + slope * 20.) * (1200. - 25. * std::f64::consts::PI); - let ring_added = std::f64::consts::PI * (64. - 25.) * (24. - (20. + slope * 20.)); - (target, ring, Vec3::new(20., 15., 16.06), floor_volume + web_volume + ring_added) -} - -#[test] -fn thin_connected_web_between_bore_stations_survives_union() { - let (target, ring, probe, expected) = fixture(); - let target_before = step_export(&[&target], "source").unwrap(); - let ring_before = step_export(&[&ring], "ring").unwrap(); - let size = target.size().max(ring.size()); - let tol = (size * 5e-4).max(size * 1e-5); - let ma = target.tessellate_with(tol, true).unwrap(); - let mb = ring.tessellate_with(tol, true).unwrap(); - assert!(ma.contains(probe), "fixture must contain the real connected web"); - assert!(!mb.contains(probe)); - let va = ma.measure().volume; - let vb = mb.measure().volume; - let slack = 2e-3 * (va + vb) + 1e-9; - let accept = |body: &Body| { - let mr = body.tessellate_with(tol, true).unwrap(); - let v = mr.measure().volume; - let mismatch = super::mismatch(&ma, &mb, &mr, BoolOp::Union); - eprintln!("fallback candidate V={v}, expected={expected}, web={}, mismatch={mismatch:?}", mr.contains(probe)); - v > 0. && v >= va.max(vb) - slack && v <= va + vb + slack && mismatch.is_none_or(|f| f < 0.004) - }; - let direct = crate::coplanar::bore_union(&target, &ring, &accept); - eprintln!("direct fallback result={}", direct.is_some()); - let public = boolean(&target, &ring, BoolOp::Union); - if let Ok(dir) = solidcraft_geom::env::var("BORE_AUDIT_DIR").ok_or(()) { - let dir = std::path::Path::new(&dir); - std::fs::create_dir_all(dir).unwrap(); - std::fs::write(dir.join("target-with-web.step"), step_export(&[&target], "target with web").unwrap()).unwrap(); - if let Some(result) = &direct { - std::fs::write(dir.join("direct-union.step"), step_export(&[result], "direct union").unwrap()).unwrap(); - } - if let Ok(Some(result)) = &public { - std::fs::write(dir.join("public-union.step"), step_export(&[result], "public union").unwrap()).unwrap(); - } - } - let direct_keeps_web = direct.as_ref().is_none_or(|result| result.tessellate_with(1e-3, true).unwrap().contains(probe)); - let public_keeps_web = match &public { - Ok(Some(result)) => { - let keep = result.tessellate_with(1e-3, true).unwrap().contains(probe); - eprintln!("public Union result web={keep}"); - keep - } - result => { - eprintln!("public Union honestly refused: {result:?}"); - true - } - }; - assert!(direct_keeps_web, "accepted fallback removed real web material"); - assert!(public_keeps_web, "public Union removed real web material"); - assert_eq!(step_export(&[&target], "source").unwrap(), target_before); - assert_eq!(step_export(&[&ring], "ring").unwrap(), ring_before); -} - -#[test] -fn unproved_curved_boundary_between_clear_endpoints_refuses_recut() { - let a = Vec2::new(6., -1.); - let b = Vec2::new(6., 1.); - let c = Vec2::new(8., 1.); - let d = Vec2::new(8., -1.); - let region = Region2 { - outer: Loop2 { - segs: vec![ - Seg2::Cubic { p0: a, p1: Vec2::new(3., -0.5), p2: Vec2::new(3., 0.5), p3: b }, - Seg2::Line { a: b, b: c }, - Seg2::Line { a: c, b: d }, - Seg2::Line { a: d, b: a }, - ], - } - .reversed(), - holes: vec![], - }; - let body = extrude(&Plane::XY, &[region], 16.05, 16.07).unwrap().remove(0); - assert!(a.len() > 5. && b.len() > 5., "endpoint samples miss the interior excursion"); - assert!(body.tessellate_with(1e-4, true).unwrap().contains(Vec3::new(4.5, 0., 16.06))); - let before = step_export(&[&body], "curved source").unwrap(); - assert!(crate::bore_guard::boundaries_clear(&body, &[], Vec3::ZERO, UnitVec3::Z, 5., 14., 24., 1e-6).is_none()); - assert_eq!(step_export(&[&body], "curved source").unwrap(), before); -} - -/// Posts sunk into one floor have their tops in a common plane but apart: they don't -/// coincide, so joining another post doesn't go through pushing faces apart (#261). -#[test] -fn coplanar_faces_apart_from_each_other_do_not_coincide() { - let floor = box_solid(Vec3::new(0., 0., 0.), Vec3::new(80., 60., 2.)).unwrap(); - let post = |x: f64| cylinder(Vec3::new(x, 30., 1.), Vec3::Z, 3., 6.).unwrap(); - let with_one = boolean(&floor, &post(10.), BoolOp::Union).unwrap().unwrap(); - assert!(crate::coplanar::coincident_planes(&with_one, &post(60.)).is_empty()); - assert!(crate::coplanar::boolean_apart(&with_one, &post(60.), BoolOp::Union).is_none()); - // A post over the first one's top does meet it there. - assert!(!crate::coplanar::coincident_planes(&with_one, &cylinder(Vec3::new(12., 30., 7.), Vec3::Z, 3., 6.).unwrap()).is_empty()); - let joined = boolean(&with_one, &post(60.), BoolOp::Union).unwrap().unwrap(); - let v = joined.tessellate_with(1e-3, true).unwrap().measure().volume; - let expected = 80. * 60. * 2. + 2. * std::f64::consts::PI * 9. * 5.; - assert!((v - expected).abs() < 0.5, "volume {v}, expected {expected}"); -} diff --git a/crates/kernel/src/boundary.rs b/crates/kernel/src/boundary.rs index 0a63df1b5..b8aa5bd35 100644 --- a/crates/kernel/src/boundary.rs +++ b/crates/kernel/src/boundary.rs @@ -17,7 +17,8 @@ //! exactly; the network there refuses G1/G2 on two sides that meet at a corner for the same //! reason. Everything this module refuses is an error, never a quietly worse surface. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::body::Body; use crate::bridge::{Continuity, Frame, bridge}; diff --git a/crates/kernel/src/boundary_network.rs b/crates/kernel/src/boundary_network.rs index ea109e4ad..3291bbc12 100644 --- a/crates/kernel/src/boundary_network.rs +++ b/crates/kernel/src/boundary_network.rs @@ -11,19 +11,17 @@ //! The two-curve bridge with G0–G3 against a sketch's plane is [`crate::boundary`]; this is the //! general case: three or four sides, interior curves, 3D curves and edges. -use std::collections::HashSet; - -use mt::{BoundedCurve, Cut, InnerSpace, ParametricCurve, ParametricSurface, SearchNearestParameter}; +use solidcore_record::brep::Brep; +use solidcore_record::{Plane, Seg2, Vec3}; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; use solidcraft_geom::bspline::{CurveN, NurbsSurface, SplineError}; use solidcraft_geom::network::{self, CrossFace, FaceFrame, NetCurve, NetworkCurve, PointCurve, Tolerances}; -use solidcraft_geom::{Plane, Seg2, Vec3}; -use truck_modeling as mt; +use solidcraft_geom::prelude::*; -use crate::body::{Body, from_p3, p3}; -use crate::bridge::Continuity; -use crate::plane_fit::EdgeSampler; -use crate::record::Rebuild; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::continuity_order::{Construction, Continuity}; +use crate::surfaces::{Chain, Parts, spline_curve, spline_surface, surface_body, uv_line}; +use crate::{KernelError, Result}; /// How far apart curves of the two directions may pass and still cross (mm). pub const CROSS_TOLERANCE: f64 = 0.01; @@ -36,13 +34,18 @@ pub const MAX_EDGE_PICKS: usize = 10_000; /// Most sketch curves one curve of a boundary surface chains. pub const MAX_CHAIN_CURVES: usize = 1000; -/// The network's continuity for a curve's: G3 is refused (a network holds up to G2). +/// The network's continuity for a curve's, refused past what a network builds +/// ([`Construction::Network`]). fn net_order(c: &BoundaryCurve) -> Result { - match c.continuity { + let named = |e: KernelError| match e { + KernelError::Invalid(why) => KernelError::Invalid(format!("{}: {why}", c.label)), + other => other, + }; + match c.continuity.built_by(Construction::Network).map_err(named)? { Continuity::G0 => Ok(network::Continuity::G0), Continuity::G1 => Ok(network::Continuity::G1), Continuity::G2 => Ok(network::Continuity::G2), - Continuity::G3 => Err(KernelError::Invalid(format!("not supported yet: G3 continuity on {} (a curve network holds up to G2)", c.label))), + higher => Err(KernelError::Failed(format!("a curve network has no {} condition yet", higher.code()))), } } @@ -79,7 +82,7 @@ pub fn boundary_surface(u: &[BoundaryCurve], v: &[BoundaryCurve]) -> Result = Vec::new(); let mut to_net = |c: &BoundaryCurve| -> Result> { let (curve, face): (Box, Option) = match &c.source { @@ -101,12 +104,18 @@ pub fn boundary_surface(u: &[BoundaryCurve], v: &[BoundaryCurve]) -> Result None, _ => Some(EdgeFaces::new(&c.label, body, &chain)?), }; - (Box::new(EdgeChain::new(&c.label, &chain)?), face) + (Box::new(EdgeChain::new(&c.label, r, &chain)?), face) } }; if c.continuity != Continuity::G0 && face.is_none() { @@ -122,20 +131,16 @@ pub fn boundary_surface(u: &[BoundaryCurve], v: &[BoundaryCurve]) -> Result KernelError::TooLarge(m), SplineError::Invalid(m) => KernelError::Invalid(m), })?; - let face = face_of(&surface, &corners)?; - let mut rec = Rebuild::default(); - rec.made(&face, Vec::new()); - crate::surfaces::body_of(vec![face], &[], &rec) - }) + face_of(&surface, &corners) + } } /// `made` (a boundary surface) sewn into `target` along the edges they share: one body, a solid /// when it closes the gap. Refused when they share no edge. pub fn boundary_join(target: &Body, made: &Body) -> Result { target.require_brep("join")?; - let edges = |b: &Body| b.solid.edge_iter().map(|e| e.id()).collect::>().len(); let joined = crate::surfaces::stitch(&[target, made], CROSS_TOLERANCE)?; - if edges(&joined) == edges(target) + edges(made) { + if joined.edge_count() == target.edge_count() + made.edge_count() { return Err(KernelError::Invalid("the surface shares no edge with the body it joins".into())); } Ok(joined) @@ -245,32 +250,42 @@ fn resample(pts: &[Vec3], max: usize) -> Vec { .collect() } -/// A chain of edges (each turned to run along it), by their lengths. +/// A chain of a body's edges (each walked the way the chain runs along it), by their lengths; +/// a point a fraction of the way along an edge is at that fraction of its parameter interval. struct EdgeChain { - edges: Vec, + edges: Vec<(CurveEval, [f64; 2])>, starts: Vec, total: f64, } +/// The curves of `chain` (edges of `r`), each with its interval in the chain's direction. +fn chain_curves(label: &str, r: &Brep, chain: &Chain) -> Result> { + chain + .iter() + .map(|&(e, forward)| { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge reference")))?; + let c = CurveEval::new(edge.parameters()).map_err(|err| KernelError::Invalid(format!("{label}: {err}")))?; + let [t0, t1] = edge.interval; + Ok((c, if forward { [t0, t1] } else { [t1, t0] })) + }) + .collect() +} + +/// The point `f` (0…1) of the way along a directed interval of a curve. +fn along((c, [a, z]): &(CurveEval, [f64; 2]), f: f64) -> Option { + c.point(a + (z - a) * f.clamp(0.0, 1.0)) +} + impl EdgeChain { - fn new(label: &str, chain: &[mt::Edge]) -> Result { - let mut edges = Vec::with_capacity(chain.len()); - let mut starts = Vec::with_capacity(chain.len()); + fn new(label: &str, r: &Brep, chain: &Chain) -> Result { + let edges = chain_curves(label, r, chain)?; + let mut starts = Vec::with_capacity(edges.len()); let mut total = 0.0; - for e in chain { - let mut s = EdgeSampler::new(e).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge has no parameter range")))?; - let mut len = 0.0; - let mut last: Option = None; - for k in 0..=16 { - let p = s.at(k as f64 / 16.0).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge can't be evaluated")))?; - if let Some(q) = last { - len += p.dist(q); - } - last = Some(p); - } + for e in &edges { + let pts = (0..=16).map(|k| along(e, k as f64 / 16.0)).collect::>>(); + let pts = pts.ok_or_else(|| KernelError::Invalid(format!("{label}: an edge can't be evaluated")))?; starts.push(total); - total += len; - edges.push(s); + total += pts.windows(2).map(|w| w[0].dist(w[1])).sum::(); } if !(total > 0.0 && total.is_finite()) { return Err(KernelError::Invalid(format!("{label} has no length"))); @@ -286,7 +301,7 @@ impl NetCurve for EdgeChain { let start = *self.starts.get(k)?; let end = self.starts.get(k + 1).copied().unwrap_or(self.total); let local = if end > start { ((at - start) / (end - start)).clamp(0.0, 1.0) } else { 0.0 }; - self.edges.get_mut(k)?.at(local) + along(self.edges.get(k)?, local) } } @@ -302,29 +317,34 @@ pub(crate) struct EdgeFaces { /// parameters found last (the next search starts there). struct EdgeSide { pts: Vec, - surface: mt::Surface, + surface: SurfaceEval, along: bool, - hint: Option<(f64, f64)>, + hint: Option<[f64; 2]>, } impl EdgeFaces { - pub(crate) fn new(label: &str, body: &Body, chain: &[mt::Edge]) -> Result { + pub(crate) fn new(label: &str, body: &Body, chain: &Chain) -> Result { + let r = body.record(); + let curves = chain_curves(label, r, chain)?; let mut sides = Vec::with_capacity(chain.len()); - for e in chain { - let mut faces = body.solid.face_iter().filter(|f| f.boundaries().iter().flatten().any(|x| x.id() == e.id())); - let (Some(face), None) = (faces.next(), faces.next()) else { + for (&(e, forward), curve) in chain.iter().zip(&curves) { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge reference")))?; + let [u] = edge.uses.as_slice() else { return Err(KernelError::Invalid(format!( "{label}: G1 and G2 need an open edge of a surface (an edge with a face on one side only)" ))); }; - // How the face's own (absolute) boundary runs this edge. - let in_wire = face.absolute_boundaries().iter().flatten().find(|x| x.id() == e.id()).cloned(); - let in_wire = in_wire.ok_or_else(|| KernelError::Failed("boundary surface: an edge's face".into()))?; - let along = in_wire.front().id() == e.front().id(); - let mut sampler = EdgeSampler::new(e).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge has no parameter range")))?; - let pts = (0..=16).map(|k| sampler.at(k as f64 / 16.0)).collect::>>(); + // How the face's loop (counter-clockwise about its surface's natural normal) runs the edge. + let face = r.faces.get(u.face as usize).ok_or_else(|| KernelError::Failed("boundary surface: an edge's face".into()))?; + let in_loop = match face.loops.get(u.r#loop as usize) { + Some(solidcore_record::brep::Loop::Edges { edges }) => edges.get(u.position as usize).map(|x| x.forward), + _ => None, + }; + let in_loop = in_loop.ok_or_else(|| KernelError::Failed("boundary surface: an edge's face".into()))?; + let pts = (0..=16).map(|k| along(curve, k as f64 / 16.0)).collect::>>(); let pts = pts.ok_or_else(|| KernelError::Invalid(format!("{label}: an edge can't be evaluated")))?; - sides.push(EdgeSide { pts, surface: face.surface(), along, hint: None }); + let surface = SurfaceEval::new(face.parameters()).map_err(|err| KernelError::Failed(format!("boundary surface: {err}")))?; + sides.push(EdgeSide { pts, surface, along: in_loop == forward, hint: None }); } Ok(EdgeFaces { sides }) } @@ -339,17 +359,12 @@ impl CrossFace for EdgeFaces { let seg = side.pts.windows(2).min_by(|a, b| at.dist_to_segment(a[0], a[1]).total_cmp(&at.dist_to_segment(b[0], b[1])))?; let chain_dir = seg[1] - seg[0]; let s = &side.surface; - let (u, v) = s.search_nearest_parameter(p3(at), side.hint, 100).or_else(|| s.search_nearest_parameter(p3(at), None, 100))?; - side.hint = Some((u, v)); - let (su, sv) = (s.uder(u, v), s.vder(u, v)); - let n = su.cross(sv); - if !(n.magnitude2() > 0.0) { - return None; - } - let n = n.normalize(); - let normal = Vec3::new(n.x, n.y, n.z); - // The face's boundary runs counter-clockwise about its surface's normal, so the face lies - // to the left of it: outward is the boundary's direction × the normal. + let [u, v] = s.project(at, side.hint, f64::INFINITY).or_else(|| s.project(at, None, f64::INFINITY))?; + side.hint = Some([u, v]); + let (_, su, sv) = s.derivs(u, v)?; + let normal = su.cross(sv).normalized()?; + // The face's loop runs counter-clockwise about its surface's normal, so the face lies to + // the left of it: outward is the loop's direction × the normal. let wire = if side.along { chain_dir } else { -chain_dir }; let outward = wire.cross(normal).normalized()?; // The second fundamental form, in the basis of the tangent asked about and outward. @@ -363,11 +378,10 @@ impl CrossFace for EdgeFaces { // II(w, w) = L·α² + 2M·αβ + N·β² for w = α·S_u + β·S_v, with L, M, N the surface's // second derivatives along its unit normal (do Carmo, §3-3): exact, rational surfaces // included, and with nothing sampled beyond the edge, where the face's domain ends. - let nv = mt::Vector3::new(normal.x, normal.y, normal.z); - let (l, m, nn) = (s.uuder(u, v).dot(nv), s.uvder(u, v).dot(nv), s.vvder(u, v).dot(nv)); + let (suu, suv, svv) = s.second(u, v)?; + let (l, m, nn) = (suu.dot(normal), suv.dot(normal), svv.dot(normal)); let ii = |w: Vec3| -> Option { - let wv = mt::Vector3::new(w.x, w.y, w.z); - let (p, q) = (wv.dot(su), wv.dot(sv)); + let (p, q) = (w.dot(su), w.dot(sv)); let (alpha, beta) = ((p * g - q * f) / det, (q * e - p * f) / det); let out = l * alpha * alpha + 2.0 * m * alpha * beta + nn * beta * beta; out.is_finite().then_some(out) @@ -380,99 +394,127 @@ impl CrossFace for EdgeFaces { } /// The face of a network surface: its four sides from the surface's boundary rows, each split -/// at the `corners` that lie on it (inner vertices of edge chains). Refused when a side shrinks to -/// a point. -fn face_of(s: &NurbsSurface, corners: &[Vec3]) -> Result { +/// at the `corners` that lie on it (inner vertices of edge chains), the pieces edges on the side's +/// own curve over parts of its interval. A side collapsed to a point (a three-sided patch) is left +/// out: the two sides beside it meet at one vertex there. Refused when more than one side +/// shrinks to a point. +fn face_of(s: &NurbsSurface, corners: &[Vec3]) -> Result { let fail = |m: &str| KernelError::Failed(format!("boundary surface: {m}")); let [nu, nv] = s.count(); - let [ku, kv] = s.knots(); - let rows: Vec> = (0..nu).map(|i| (0..nv).map(|j| p3(s.point(i, j).xyz())).collect()).collect(); - let (uk, vk) = (mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone())); - let surface = mt::BSplineSurface::try_new((uk.clone(), vk.clone()), rows.clone()).map_err(|e| fail(&e.to_string()))?; - let row = |pts: Vec, k: &mt::KnotVec| mt::BSplineCurve::try_new(k.clone(), pts).map_err(|e| fail(&e.to_string())); - let (Some(first), Some(last)) = (rows.first(), rows.last()) else { return Err(fail("control net")) }; - let bottom = row(rows.iter().filter_map(|r| r.first().copied()).collect(), &uk)?; - let top = row(rows.iter().filter_map(|r| r.last().copied()).collect(), &uk)?; - let left = row(first.clone(), &vk)?; - let right = row(last.clone(), &vk)?; - let corner = |c: &mt::BSplineCurve, end: bool| { - let (t0, t1) = c.range_tuple(); - c.subs(if end { t1 } else { t0 }) + if nu < 2 || nv < 2 { + return Err(fail("control net")); + } + let [ku, kv] = s.knots().clone(); + let [[u0, u1], [v0, v1]] = s.domain(); + let corner = |i: usize, j: usize| s.point(i, j).project().ok_or_else(|| fail("a corner has no position")); + let c = [corner(0, 0)?, corner(nu - 1, 0)?, corner(nu - 1, nv - 1)?, corner(0, nv - 1)?]; + let size = c.iter().map(|p| p.dist(c[0])).fold(0.0, f64::max).max(1.0); + let row = |j: usize| (0..nu).map(|i| s.point(i, j)).collect::>(); + let column = |i: usize| (0..nv).map(|j| s.point(i, j)).collect::>(); + // Bottom (v0) and top (v1) along u, left (u0) and right (u1) along v, each from its first + // corner to its second; the loop runs bottom, right, top backwards, left backwards. + let sides = [ + (row(0), ku.clone(), [0, 1], true, [None, Some(v0)]), + (column(nu - 1), kv.clone(), [1, 2], true, [Some(u1), None]), + (row(nv - 1), ku, [3, 2], false, [None, Some(v1)]), + (column(0), kv, [0, 3], false, [Some(u0), None]), + ]; + let collapsed: Vec = sides.iter().map(|(_, _, [a, z], ..)| c[*a].dist(c[*z]) <= size * 1e-9).collect(); + if collapsed.iter().filter(|x| **x).count() > 1 { + return Err(KernelError::Invalid("not supported yet: a boundary surface with more than one side shrunk to a point".into())); + } + // Vertices: the corners, a collapsed side's two ends one vertex. + let mut vertex_of = [0usize, 1, 2, 3]; + for (k, (_, _, [a, z], ..)) in sides.iter().enumerate() { + if collapsed.get(k).copied().unwrap_or(false) { + vertex_of[*z] = vertex_of[*a]; + } + } + let tolerance = (size * 1e-6).max(1e-5); + let mut parts = Parts { tolerance, ..Parts::default() }; + parts.vertices = c.iter().map(|p| solidcore_record::brep::Vertex { point: [p.x, p.y, p.z], tolerance }).collect(); + let mut uses = Vec::new(); + for (k, (ctrl, knots, [a, z], forward, fixed)) in sides.into_iter().enumerate() { + if collapsed.get(k).copied().unwrap_or(false) { + continue; + } + let (curve, [t0, t1]) = spline_curve(&ctrl, knots)?; + let eval = CurveEval::new(&curve).map_err(|e| fail(&e.to_string()))?; + let cuts = cuts_on(&eval, [t0, t1], corners); + let mut breaks = vec![t0]; + breaks.extend(cuts.iter().map(|(t, _)| *t)); + breaks.push(t1); + let mut ends = vec![vertex_of[a]]; + for (_, p) in &cuts { + ends.push(parts.vertices.len()); + parts.vertices.push(solidcore_record::brep::Vertex { point: [p.x, p.y, p.z], tolerance }); + } + ends.push(vertex_of[z]); + let uv = |t: f64| [fixed[0].unwrap_or(t), fixed[1].unwrap_or(t)]; + let mut pieces = Vec::with_capacity(breaks.len()); + for (w, e) in breaks.windows(2).zip(ends.windows(2)) { + let interval = [w[0], w[1]]; + let edge = index(parts.edges.len())?; + let vertices = [index(e[0])?, index(e[1])?]; + parts.edges.push(solidcore_record::brep::Edge { nurbs: None, curve: curve.clone(), interval, vertices, tolerance, uses: Vec::new() }); + pieces.push(solidcore_record::brep::OrientedEdge { edge, forward, pcurve: uv_line(uv(w[0]), uv(w[1]), interval) }); + } + if !forward { + pieces.reverse(); + } + uses.extend(pieces); + } + let face = solidcore_record::brep::Face { + nurbs: None, + surface: spline_surface(s), + domain: s.domain(), + loops: vec![solidcore_record::brep::Loop::Edges { edges: uses }], }; - let (c00, c10, c11, c01) = (corner(&bottom, false), corner(&bottom, true), corner(&top, true), corner(&top, false)); - let size = [c00, c10, c11, c01].iter().map(|p| from_p3(*p).dist(from_p3(c00))).fold(0.0, f64::max).max(1.0); - // A side collapsed to a point (a three-sided patch) is left out of the loop: the two sides - // beside it meet at one vertex there. - let sides = [(c00, c10), (c10, c11), (c01, c11), (c00, c01)]; - let collapsed: Vec = sides.iter().map(|(a, b)| from_p3(*a).dist(from_p3(*b)) <= size * 1e-9).collect(); - match collapsed.iter().filter(|c| **c).count() { - 0 | 1 => {} - _ => return Err(KernelError::Invalid("not supported yet: a boundary surface with more than one side shrunk to a point".into())), - } - let mut verts: Vec = Vec::with_capacity(4); - for c in [c00, c10, c11, c01] { - let same = verts.iter().find(|v| from_p3(v.point()).dist(from_p3(c)) <= size * 1e-9).cloned(); - verts.push(same.unwrap_or_else(|| mt::Vertex::new(c))); - } - let (Some(v00), Some(v10), Some(v11), Some(v01)) = (verts.first(), verts.get(1), verts.get(2), verts.get(3)) else { - return Err(fail("corners")); - }; - let is = |k: usize| collapsed.get(k).copied().unwrap_or(false); - let mut wire: Vec = Vec::new(); - if !is(0) { - wire.extend(side_edges(bottom, v00, v10, corners)); - } - if !is(1) { - wire.extend(side_edges(right, v10, v11, corners)); - } - if !is(2) { - wire.extend(side_edges(top, v01, v11, corners).into_iter().rev().map(|e| e.inverse())); - } - if !is(3) { - wire.extend(side_edges(left, v00, v01, corners).into_iter().rev().map(|e| e.inverse())); - } - // u along the bottom, v up the left: counter-clockwise in (u, v). - mt::Face::try_new(vec![wire.into()], mt::Surface::BSplineSurface(surface)).map_err(|e| fail(&e.to_string())) + parts.faces.push((face, true)); + let body = surface_body(&parts.canonical()?.brep)?; + crate::surfaces::all_new(body, &[]) } -/// The edges of one side from `a` to `b`, split at the points of `corners` that lie on it -/// (within [`CROSS_TOLERANCE`]) strictly between its ends. -fn side_edges(mut curve: mt::BSplineCurve, a: &mt::Vertex, b: &mt::Vertex, corners: &[Vec3]) -> Vec { - let (t0, t1) = curve.range_tuple(); +/// The points of `corners` on a side's curve (within [`CROSS_TOLERANCE`]) strictly between its +/// ends, with their parameters, in order: each found from its nearest of 256 samples by +/// golden-section search. +fn cuts_on(c: &CurveEval, [t0, t1]: [f64; 2], corners: &[Vec3]) -> Vec<(f64, Vec3)> { + const SAMPLES: usize = 256; let margin = (t1 - t0) * 1e-6; - let mut cuts: Vec = corners + let mut cuts: Vec<(f64, Vec3)> = corners .iter() - .filter_map(|c| { - let t = curve.search_nearest_parameter(p3(*c), None, 100)?; - (t > t0 + margin && t < t1 - margin && from_p3(curve.subs(t)).dist(*c) <= CROSS_TOLERANCE).then_some(t) + .filter_map(|p| { + let d = |t: f64| c.point(t).map_or(f64::INFINITY, |q| q.dist(*p)); + let at = |i: usize| t0 + (t1 - t0) * i as f64 / SAMPLES as f64; + let i = (0..=SAMPLES).min_by(|a, b| d(at(*a)).total_cmp(&d(at(*b))))?; + let (mut lo, mut hi) = (at(i.saturating_sub(1)), at((i + 1).min(SAMPLES))); + let g = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..80 { + let (x, y) = (hi - g * (hi - lo), lo + g * (hi - lo)); + if d(x) < d(y) { + hi = y; + } else { + lo = x; + } + } + let t = 0.5 * (lo + hi); + (t > t0 + margin && t < t1 - margin && d(t) <= CROSS_TOLERANCE).then(|| (t, c.point(t).unwrap_or(*p))) }) .collect(); - cuts.sort_by(f64::total_cmp); - cuts.dedup_by(|x, y| (*x - *y).abs() <= margin); - let mut edges = Vec::with_capacity(cuts.len() + 1); - let mut from = a.clone(); - // Cut from the far end back, so the earlier parameters stay on the part kept. - let mut tails = Vec::with_capacity(cuts.len()); - for &t in cuts.iter().rev() { - tails.push(curve.cut(t)); - } - let mut pieces = vec![curve]; - pieces.extend(tails.into_iter().rev()); - let count = pieces.len(); - for (k, piece) in pieces.into_iter().enumerate() { - let to = if k + 1 == count { b.clone() } else { mt::Vertex::new(piece.subs(piece.range_tuple().1)) }; - edges.push(mt::Edge::new(&from, &to, mt::Curve::BSplineCurve(piece))); - from = to; - } - edges + cuts.sort_by(|a, b| a.0.total_cmp(&b.0)); + cuts.dedup_by(|x, y| (x.0 - y.0).abs() <= margin); + cuts +} + +fn index(i: usize) -> Result { + u32::try_from(i).map_err(|_| KernelError::TooLarge("boundary surface: too many edges".into())) } #[cfg(test)] mod tests { use super::*; use crate::patch_region; - use mt::ParametricSurface3D; - use solidcraft_geom::{Loop2, Region2, Vec2}; + use solidcore_record::{Loop2, Region2, Vec2}; fn sketch(label: &str, plane: Plane, segs: Vec) -> BoundaryCurve<'static> { BoundaryCurve { label: label.into(), source: CurveSource::Sketch { plane, segs }, continuity: Continuity::G0 } @@ -482,8 +524,8 @@ mod tests { BoundaryCurve { label: label.into(), source: CurveSource::Points(vec![a, b]), continuity: Continuity::G0 } } - fn face_surface(b: &Body) -> mt::Surface { - b.solid.face_iter().next().unwrap().surface() + fn face_surface(b: &Body) -> SurfaceEval { + SurfaceEval::new(&b.record().faces[0].surface).unwrap() } /// The flat sheet y ∈ [−10, 0], x ∈ [0, 10] in z = 0, its edge along y = 0 open. @@ -506,7 +548,7 @@ mod tests { let s = face_surface(&body); for i in 0..=10 { for j in 0..=10 { - let q = from_p3(s.subs(i as f64 / 10.0, j as f64 / 10.0)); + let q = s.point([i as f64 / 10.0, j as f64 / 10.0]).unwrap(); assert!((q.z - q.x * q.y / 10.0).abs() < 1e-9, "{q:?}"); } } @@ -530,7 +572,7 @@ mod tests { let s = face_surface(&body); for i in 0..=8 { for j in 0..=8 { - assert!((s.subs(i as f64 / 8.0, j as f64 / 8.0).z - 3.0).abs() < 1e-9); + assert!((s.point([i as f64 / 8.0, j as f64 / 8.0]).unwrap().z - 3.0).abs() < 1e-9); } } } @@ -560,9 +602,9 @@ mod tests { let near = |a: f64| (a - want).abs() < 0.25; let faces = body.faces(0.01).unwrap(); assert!(faces.len() == 1 && near(faces[0].area), "faces: {faces:?}"); - let tess = body.tessellate(0.01).unwrap().measure().area; + let tess = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().area; assert!(near(tess), "measuring mesh: {tess}"); - let display = body.display_mesh(0.01).unwrap().measure().area; + let display = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().area; assert!(near(display), "display mesh: {display}"); } @@ -580,15 +622,14 @@ mod tests { let apex = BoundaryCurve { label: "centre".into(), source: CurveSource::Point(Vec3::ZERO), continuity: Continuity::G0 }; let body = boundary_surface(&[sketch("arc", pl, vec![arc]), apex], &[sketch("x", pl, vec![x]), sketch("y", pl, vec![y])]).unwrap(); assert!(body.is_surface() && body.face_count() == 1); - let edges: std::collections::HashSet<_> = body.solid.edge_iter().map(|e| e.id()).collect(); - assert_eq!(edges.len(), 3, "the collapsed side is no edge"); + assert_eq!(body.edge_count(), 3, "the collapsed side is no edge"); let want = PI * r * r / 4.0; let near = |a: f64| (a - want).abs() < 0.2; let faces = body.faces(0.01).unwrap(); assert!(near(faces[0].area), "faces: {faces:?}"); - let tess = body.tessellate(0.01).unwrap().measure().area; + let tess = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().area; assert!(near(tess), "measuring mesh: {tess}"); - let display = body.display_mesh(0.01).unwrap().measure().area; + let display = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().area; assert!(near(display), "display mesh: {display}"); // Two collapsed sides are no patch. let p = |l: &str, q: Vec3| BoundaryCurve { label: l.into(), source: CurveSource::Point(q), continuity: Continuity::G0 }; @@ -600,11 +641,11 @@ mod tests { } /// The angle between the two faces' normals across the edge at `p`. - fn normal_angle(a: &mt::Surface, b: &mt::Surface, p: Vec3) -> f64 { - let n = |s: &mt::Surface| { - let (u, v) = s.search_nearest_parameter(p3(p), None, 100).unwrap(); - let n = s.normal(u, v); - Vec3::new(n.x, n.y, n.z) + fn normal_angle(a: &SurfaceEval, b: &SurfaceEval, p: Vec3) -> f64 { + let n = |s: &SurfaceEval| { + let [u, v] = s.project(p, None, f64::INFINITY).unwrap(); + let (_, su, sv) = s.derivs(u, v).unwrap(); + su.cross(sv).normalized().unwrap() }; n(a).dot(n(b)).abs().clamp(0.0, 1.0).acos().to_degrees() } @@ -650,11 +691,10 @@ mod tests { /// Normal curvature of `s` at the point nearest `p` in the direction `w` (projected into the /// tangent plane), signed against the unit normal `n`. - fn normal_curvature(s: &mt::Surface, p: Vec3, w: Vec3, n: Vec3) -> f64 { - let (u, v) = s.search_nearest_parameter(p3(p), None, 100).unwrap(); - let v3 = |x: mt::Vector3| Vec3::new(x.x, x.y, x.z); - let (su, sv) = (v3(s.uder(u, v)), v3(s.vder(u, v))); - let (suu, suv, svv) = (v3(s.uuder(u, v)), v3(s.uvder(u, v)), v3(s.vvder(u, v))); + fn normal_curvature(s: &SurfaceEval, p: Vec3, w: Vec3, n: Vec3) -> f64 { + let [u, v] = s.project(p, None, f64::INFINITY).unwrap(); + let (_, su, sv) = s.derivs(u, v).unwrap(); + let (suu, suv, svv) = s.second(u, v).unwrap(); let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv)); let (l, m, nn) = (suu.dot(n), suv.dot(n), svv.dot(n)); let (p1, q1) = (w.dot(su), w.dot(sv)); @@ -698,17 +738,16 @@ mod tests { assert!((k1 + 1.0 / r).abs() > 0.1 / r, "G1 alone does not carry the curvature: {k1}"); } - /// G3 is more than a network holds: refused, never a panic. + /// G3 and G4 are more than a network holds: refused, naming the curve, never a panic. #[test] fn g3_is_not_supported() { let base = sheet(); - let edge = BoundaryCurve { - label: "edge".into(), - source: CurveSource::Edges { body: &base, at: vec![Vec3::new(5.0, 0.0, 0.0)] }, - continuity: Continuity::G3, - }; - let e = boundary_surface(&[edge, line3("far", Vec3::new(0.0, 10.0, 5.0), Vec3::new(10.0, 10.0, 5.0))], &[]).unwrap_err(); - assert!(e.to_string().contains("not supported yet"), "{e}"); + for g in [Continuity::G3, Continuity::G4] { + let edge = + BoundaryCurve { label: "edge".into(), source: CurveSource::Edges { body: &base, at: vec![Vec3::new(5.0, 0.0, 0.0)] }, continuity: g }; + let e = boundary_surface(&[edge, line3("far", Vec3::new(0.0, 10.0, 5.0), Vec3::new(10.0, 10.0, 5.0))], &[]).unwrap_err(); + assert!(e.to_string().contains("not supported yet") && e.to_string().contains("edge") && e.to_string().contains(g.as_str()), "{e}"); + } } /// Refusals: G1 on a sketch curve, on an edge between two faces, curves that miss. diff --git a/crates/kernel/src/boundary_tests.rs b/crates/kernel/src/boundary_tests.rs index ce7abfcb0..f1091173d 100644 --- a/crates/kernel/src/boundary_tests.rs +++ b/crates/kernel/src/boundary_tests.rs @@ -3,8 +3,6 @@ //! approximation. use super::*; -use crate::body::from_p3; -use truck_modeling::ParametricSurface; /// The angle between two vectors, in degrees. fn angle_deg(a: Vec3, b: Vec3) -> f64 { @@ -28,9 +26,8 @@ fn shape_of(d1: Vec3, d2: Vec3, d3: Vec3) -> (Vec3, Vec3, Vec3) { /// read back as the position, the unit tangent, the curvature vector and the change of curvature /// along that inward direction. fn across(body: &Body, uv: (f64, f64), into: (f64, f64), h: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let q: Vec = (0..5).map(|k| from_p3(surf.subs(uv.0 + k as f64 * h * into.0, uv.1 + k as f64 * h * into.1))).collect(); + let (surf, _) = crate::bridge::the_face(body).unwrap(); + let q: Vec = (0..5).map(|k| surf.point([uv.0 + k as f64 * h * into.0, uv.1 + k as f64 * h * into.1]).unwrap()).collect(); let (f0, f1, f2, f3, f4) = (q[0], q[1], q[2], q[3], q[4]); let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (1.0 / (12.0 * h)); let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * h * h)); diff --git a/crates/kernel/src/bridge.rs b/crates/kernel/src/bridge.rs index d13685cfb..781a3568a 100644 --- a/crates/kernel/src/bridge.rs +++ b/crates/kernel/src/bridge.rs @@ -1,5 +1,5 @@ //! Continuity-driven bridging surfaces: one B-spline face that leaves one surface and arrives at -//! another with a requested continuity (G0 up to G3). This is the core the Blend, Boundary and +//! another with a requested continuity (G0 up to G3, [`Construction::Bridge`]). This is the core the Blend, Boundary and //! Match surfaces are built on. //! //! A bridge is a tensor product. Across it (v) every station's cross-section is a Bézier whose @@ -16,62 +16,17 @@ //! speed) by finite differences: the second derivative of a surface curve with a unit tangent is //! its curvature vector, and the third is the arclength derivative of that curvature vector. -use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcore_record::brep::Brep; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; use solidcraft_geom::bspline::{CurveN, HPoint, NurbsSurface}; -use truck_modeling as mt; +use solidcraft_geom::prelude::*; -use crate::body::{Body, from_p3, p3}; -use crate::surfaces::surface_body; -use crate::{KernelError, Result, guard}; - -/// How much of a support surface a bridge repeats along its boundary. -#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum Continuity { - /// The boundary curve alone: the surfaces meet, nothing else. - G0, - /// Position and tangent plane. - #[default] - G1, - /// Position, tangent plane and curvature vector. - G2, - /// Position, tangent plane, curvature vector and its change along the leave direction. - G3, -} - -impl Continuity { - /// Conditions a side carries: 1 (G0) up to 4 (G3). - pub fn conditions(self) -> usize { - match self { - Continuity::G0 => 1, - Continuity::G1 => 2, - Continuity::G2 => 3, - Continuity::G3 => 4, - } - } - - /// The word a command parameter uses. - pub fn as_str(self) -> &'static str { - match self { - Continuity::G0 => "g0", - Continuity::G1 => "g1", - Continuity::G2 => "g2", - Continuity::G3 => "g3", - } - } - - /// Parse `g0`…`g3` (upper case accepted), `None` for anything else. - pub fn parse(s: &str) -> Option { - match s.to_ascii_lowercase().as_str() { - "g0" => Some(Continuity::G0), - "g1" => Some(Continuity::G1), - "g2" => Some(Continuity::G2), - "g3" => Some(Continuity::G3), - _ => None, - } - } -} +use crate::body::Body; +use crate::continuity_order::Construction; +pub use crate::continuity_order::Continuity; +use crate::surfaces::Chain; +use crate::{KernelError, Result}; /// One station of a boundary: where the bridge starts, the direction it leaves in, and what the /// support surface does there along that direction. @@ -89,41 +44,40 @@ pub struct Frame { } /// The edges of `body` picked by points on them, chained: each runs on from the last, and the -/// chain may close. Used with [`frames`], whose chain must be a chain of one face's own edges. -pub fn chain(body: &Body, at: &[Vec3]) -> Result> { +/// chain may close. Each is an edge of the body's record (its index) with whether the chain runs +/// along it. Used with [`frames`], whose chain must be a chain of one face's own edges. +pub fn chain(body: &Body, at: &[Vec3]) -> Result { body.require_brep("blend")?; if at.is_empty() || at.len() > 10_000 || at.iter().any(|p| !p.is_finite()) { return Err(KernelError::Invalid("pick 1 to 10000 points on the edges of a chain".into())); } - let mut pool: Vec = Vec::new(); + let r = body.record(); + let mut pool: Vec = Vec::new(); for p in at { let e = crate::surfaces::edge_near(body, *p).ok_or_else(|| KernelError::Invalid("no edge near a picked point".to_string()))?; - if !pool.iter().any(|x| x.id() == e.id()) { + if !pool.contains(&e) { pool.push(e); } } + let ends = |e: usize| r.edges.get(e).map(|x| x.vertices).ok_or_else(|| KernelError::Invalid("an edge reference".into())); let first = pool.remove(0); - let mut chain = vec![first]; + let mut chain = vec![(first, true)]; // The picks need not be given in order: run forward from the first edge, then backwards. - let mut end = match chain.first() { - Some(e) => e.back().clone(), - None => return Err(KernelError::Invalid("pick at least one edge".into())), - }; - while let Some(k) = pool.iter().position(|e| e.front().id() == end.id() || e.back().id() == end.id()) { + let mut end = ends(first)?[1]; + while let Some(k) = pool.iter().position(|e| ends(*e).is_ok_and(|v| v.contains(&end))) { let e = pool.remove(k); - let e = if e.front().id() == end.id() { e } else { e.inverse() }; - end = e.back().clone(); - chain.push(e); + let [a, z] = ends(e)?; + let forward = a == end; + end = if forward { z } else { a }; + chain.push((e, forward)); } - let mut start = match chain.first() { - Some(e) => e.front().clone(), - None => return Err(KernelError::Invalid("pick at least one edge".into())), - }; - while let Some(k) = pool.iter().position(|e| e.front().id() == start.id() || e.back().id() == start.id()) { + let mut start = ends(first)?[0]; + while let Some(k) = pool.iter().position(|e| ends(*e).is_ok_and(|v| v.contains(&start))) { let e = pool.remove(k); - let e = if e.back().id() == start.id() { e } else { e.inverse() }; - start = e.front().clone(); - chain.insert(0, e); + let [a, z] = ends(e)?; + let forward = z == start; + start = if forward { a } else { z }; + chain.insert(0, (e, forward)); } if !pool.is_empty() { return Err(KernelError::Invalid("the picked edges do not run on from one another".into())); @@ -131,14 +85,20 @@ pub fn chain(body: &Body, at: &[Vec3]) -> Result> { Ok(chain) } -/// Whether a chain of edges closes back on itself. -pub fn chain_closes(chain: &[mt::Edge]) -> bool { +/// Whether a chain of `body`'s edges closes back on itself. +pub fn chain_closes(body: &Body, chain: &Chain) -> bool { + closes(body.record(), chain) +} + +fn closes(r: &Brep, chain: &Chain) -> bool { + let end = |(e, forward): (usize, bool), head: bool| r.edges.get(e).map(|x| if forward == head { x.vertices[1] } else { x.vertices[0] }); let (Some(first), Some(last)) = (chain.first(), chain.last()) else { return false }; - first.front().id() == last.back().id() + end(*first, false).is_some() && end(*first, false) == end(*last, true) } /// A point of a [`ChainLine`]'s polyline: where it is, its arclength along the chain, the chain -/// edge (its index) the segment from it runs along, and that edge's curve parameter there. +/// edge (its index in the chain) the segment from it runs along, and that edge's curve parameter +/// there. #[derive(Clone, Copy)] struct Sample { p: Vec3, @@ -148,40 +108,42 @@ struct Sample { } /// A chain of edges measured by arclength through a fine polyline on it, so that a station is read -/// on the edge's own curve, not on a chord. A chain that closes ends back on its first point. +/// on the edge's own curve, not on a chord. A chain that closes ends back on its first point. Each +/// edge's curve is walked the way the chain runs along it. struct ChainLine { - curves: Vec, + curves: Vec<(CurveEval, [f64; 2])>, samples: Vec, closed: bool, } impl ChainLine { - fn of(edges: &[mt::Edge]) -> Result { + fn of(body: &Body, chain: &Chain) -> Result { /// Samples per edge used for the length table. const PER_EDGE: usize = 64; - let mut samples: Vec = Vec::with_capacity(edges.len() * (PER_EDGE + 1) + 1); - let mut curves = Vec::with_capacity(edges.len()); + let r = body.record(); + let mut samples: Vec = Vec::with_capacity(chain.len() * (PER_EDGE + 1) + 1); + let mut curves = Vec::with_capacity(chain.len()); let push = |samples: &mut Vec, p: Vec3, edge: usize, t: f64| { let s = samples.last().map_or(0.0, |last| last.s + last.p.dist(p)); samples.push(Sample { p, s, edge, t }); }; - for (i, e) in edges.iter().enumerate() { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - if !(t1 > t0) || ![t0, t1].into_iter().all(f64::is_finite) { - return Err(KernelError::Invalid("an edge has no parameter range".into())); - } + let fail = || KernelError::Failed("bridge: an edge has no point".into()); + for (i, &(e, forward)) in chain.iter().enumerate() { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid("an edge reference".into()))?; + let c = CurveEval::new(edge.parameters()).map_err(|err| KernelError::Failed(format!("bridge: {err}")))?; + let [t0, t1] = edge.interval; + let (a, z) = if forward { (t0, t1) } else { (t1, t0) }; for k in 0..=PER_EDGE { // The segment that starts at this point: along this edge, or the zero-length join // to the next edge. - let t = t0 + (t1 - t0) * k as f64 / PER_EDGE as f64; - push(&mut samples, from_p3(c.subs(t)), i, t); + let t = a + (z - a) * k as f64 / PER_EDGE as f64; + push(&mut samples, c.point(t).ok_or_else(fail)?, i, t); } - curves.push(c); + curves.push((c, [a, z])); } - let closed = chain_closes(edges); + let closed = closes(r, chain); if closed && let Some(first) = samples.first().copied() { - push(&mut samples, first.p, edges.len().saturating_sub(1), first.t); + push(&mut samples, first.p, chain.len().saturating_sub(1), first.t); } let line = ChainLine { curves, samples, closed }; let total = line.length(); @@ -195,6 +157,10 @@ impl ChainLine { self.samples.last().map_or(0.0, |x| x.s) } + fn point(&self, edge: usize, t: f64) -> Result { + self.curves.get(edge).and_then(|(c, _)| c.point(t)).ok_or_else(|| KernelError::Failed("bridge: sample".into())) + } + /// The point at arclength `s` (wrapped round a closed chain, clamped on an open one), on its /// edge's own curve, and the chain edge it is on. fn at(&self, s: f64) -> Result<(Vec3, usize)> { @@ -203,14 +169,13 @@ impl ChainLine { let hi = self.samples.partition_point(|x| x.s < s).clamp(1, self.samples.len().saturating_sub(1)); let fail = || KernelError::Failed("bridge: sample".into()); let (lo, hi) = (self.samples.get(hi - 1).ok_or_else(fail)?, self.samples.get(hi).ok_or_else(fail)?); - let curve = self.curves.get(lo.edge).ok_or_else(fail)?; let span = hi.s - lo.s; if !(span > 1e-12) { // The zero-length join between two edges: the end of the edge it belongs to. - return Ok((from_p3(curve.subs(lo.t)), lo.edge)); + return Ok((self.point(lo.edge, lo.t)?, lo.edge)); } let f = ((s - lo.s) / span).clamp(0.0, 1.0); - Ok((from_p3(curve.subs(lo.t + (hi.t - lo.t) * f)), lo.edge)) + Ok((self.point(lo.edge, lo.t + (hi.t - lo.t) * f)?, lo.edge)) } /// `count` stations evenly along the chain, from arclength `start` (a closed chain's seam; an @@ -234,11 +199,10 @@ impl ChainLine { fn edges_at(&self, p: Vec3, edge: usize) -> [Option; 3] { let count = self.curves.len(); let tol = self.length() * 1e-9 + 1e-12; - let Some(curve) = self.curves.get(edge) else { return [Some(edge), None, None] }; - let (t0, t1) = curve.range_tuple(); - let at = |t: f64| from_p3(curve.subs(t)).dist(p) <= tol; - let before = at(t0).then(|| edge.checked_sub(1).or(self.closed.then(|| count.saturating_sub(1)))).flatten(); - let after = at(t1).then(|| Some(edge + 1).filter(|e| *e < count).or(self.closed.then_some(0))).flatten(); + let Some((curve, [a, z])) = self.curves.get(edge) else { return [Some(edge), None, None] }; + let at = |t: f64| curve.point(t).is_some_and(|q| q.dist(p) <= tol); + let before = at(*a).then(|| edge.checked_sub(1).or(self.closed.then(|| count.saturating_sub(1)))).flatten(); + let after = at(*z).then(|| Some(edge + 1).filter(|e| *e < count).or(self.closed.then_some(0))).flatten(); [Some(edge), before, after] } @@ -250,23 +214,33 @@ impl ChainLine { } /// The arclength of the chain's point nearest `p`, and how far `p` is from the chain: the - /// nearest point of the fine polyline, then refined on that edge's own curve. + /// nearest point of the fine polyline, then refined on that edge's own curve between the + /// samples either side (golden-section search). fn nearest_with_distance(&self, p: Vec3) -> (f64, f64) { - let mut best = (f64::INFINITY, 0.0, 0usize, 0.0); + let mut best = (f64::INFINITY, 0.0, 0usize, 0.0, 0.0); for w in self.samples.windows(2) { let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; let len = a.p.dist(b.p); let f = if len > 1e-12 { ((p - a.p).dot(b.p - a.p) / (len * len)).clamp(0.0, 1.0) } else { 0.0 }; let d = p.dist(a.p + (b.p - a.p) * f); - if d < best.0 { - best = (d, a.s + len * f, a.edge, a.t + (b.t - a.t) * f); + if d < best.0 && a.edge == b.edge { + best = (d, a.s + len * f, a.edge, a.t, b.t); } } - let (chord, s, edge, hint) = best; - let on_curve = self.curves.get(edge).and_then(|c| { - let (t0, t1) = c.range_tuple(); - let t = c.search_nearest_parameter(p3(p), Some(hint), 100)?; - (t0..=t1).contains(&t).then(|| from_p3(c.subs(t)).dist(p)) + let (chord, s, edge, ta, tb) = best; + let on_curve = self.curves.get(edge).and_then(|(c, _)| { + let d = |t: f64| c.point(t).map_or(f64::INFINITY, |q| q.dist(p)); + let (mut lo, mut hi) = (ta.min(tb), ta.max(tb)); + let g = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..80 { + let (x, y) = (hi - g * (hi - lo), lo + g * (hi - lo)); + if d(x) < d(y) { + hi = y; + } else { + lo = x; + } + } + Some(d(0.5 * (lo + hi))).filter(|x| x.is_finite()) }); (s, on_curve.map_or(chord, |d| d.min(chord))) } @@ -294,24 +268,25 @@ impl ChainLine { } } -/// The support surface's frames along `edges` (a chain of its own edges), for a bridge that -/// leaves in direction `leave` (projected into the tangent plane at each station). -pub fn frames(face: &mt::Face, edges: &[mt::Edge], leave: Vec3, count: usize) -> Result> { +/// The support surface's frames along `chain` (a chain of edges of `body`'s face `face`), for a +/// bridge that leaves in direction `leave` (projected into the tangent plane at each station). +pub fn frames(body: &Body, face: usize, chain: &Chain, leave: Vec3, count: usize) -> Result> { if !(2..=4097).contains(&count) { return Err(KernelError::Invalid("a bridge needs 2 to 4097 stations".into())); } - let line = ChainLine::of(edges)?; + let line = ChainLine::of(body, chain)?; let stations = line.stations(count, 0.0, false)?; - frames_on(&vec![face.clone(); edges.len()], &stations, &line, leave) + let r = body.record(); + frames_on(r, &vec![face; chain.len()], &stations, &line, leave) } /// The frames at `stations` (points on `line`, each with the index of the chain edge it is on), -/// each read on the support face of its own edge (`faces`, one per chain edge): a chain may run -/// along the boundaries of several faces, a tube's rim along the halves of its wall. A station on -/// the vertex where two of those faces meet sits at a corner of one face's parameters, where the -/// shape may not be readable along the leave direction; it is then read on the other face, which -/// holds the same point. -fn frames_on(faces: &[mt::Face], stations: &[(Vec3, usize)], line: &ChainLine, leave: Vec3) -> Result> { +/// each read on the support face of its own edge (`faces`, faces of `r`, one per chain edge): a +/// chain may run along the boundaries of several faces, a tube's rim along the halves of its wall. +/// A station on the vertex where two of those faces meet sits at a corner of one face's +/// parameters, where the shape may not be readable along the leave direction; it is then read on +/// the other face, which holds the same point. +fn frames_on(r: &Brep, faces: &[usize], stations: &[(Vec3, usize)], line: &ChainLine, leave: Vec3) -> Result> { let leave = leave.normalized().filter(|l| l.is_finite()).ok_or_else(|| KernelError::Invalid("the leave direction must be a finite vector".into()))?; let along = |n: Vec3| -> Result { @@ -322,22 +297,21 @@ fn frames_on(faces: &[mt::Face], stations: &[(Vec3, usize)], line: &ChainLine, l let length = line.length(); // One support per distinct face, each with its own walk (a parameter hint means nothing on // another surface). - let mut supports: Vec<(mt::FaceID, Support, Walk)> = Vec::new(); + let mut supports: Vec<(usize, Support, Walk)> = Vec::new(); let mut out = Vec::with_capacity(stations.len()); 'stations: for (p, edge) in stations { - let mut tried: Vec = Vec::with_capacity(2); + let mut tried: Vec = Vec::with_capacity(2); let mut refusal: Option = None; for e in line.edges_at(*p, *edge).into_iter().flatten() { - let Some(face) = faces.get(e) else { continue }; - let id = face.id(); - if tried.contains(&id) { + let Some(&face) = faces.get(e) else { continue }; + if tried.contains(&face) { continue; } - tried.push(id); - let k = match supports.iter().position(|(f, _, _)| *f == id) { + tried.push(face); + let k = match supports.iter().position(|(f, _, _)| *f == face) { Some(k) => k, None => { - supports.push((id, Support::of(face, length)?, Walk::new(length))); + supports.push((face, Support::of(r, face, length)?, Walk::new(length))); supports.len() - 1 } }; @@ -359,21 +333,22 @@ fn frames_on(faces: &[mt::Face], stations: &[(Vec3, usize)], line: &ChainLine, l Ok(out) } -/// The frames of `face` at stations on its own boundary, each leaving the face straight across -/// that boundary: `stations` are points on the boundary with the boundary's direction there *as -/// the face's own boundary runs* (its wires as [`mt::Face::boundaries`] gives them), and the leave -/// direction is that direction × the face's outward normal — in the face's tangent plane, at -/// right angles to the boundary, away from the face. `length` is the size of the boundary the -/// stations are on (it sets how closely a station must lie on the surface and the step the shape -/// is read with). Each frame comes with the face's unit normal there (as the face is oriented). -/// With `shape` false only the leave direction and the normal are read (`bend` and -/// `bend_change` are zero), which needs no room on the surface beside the station. -pub fn frames_across(face: &mt::Face, stations: &[(Vec3, Vec3)], length: f64, shape: bool) -> Result> { +/// The frames of `body`'s face `face` at stations on its own boundary, each leaving the face +/// straight across that boundary: `stations` are points on the boundary with the boundary's +/// direction there *as the face's own boundary runs* (counter-clockwise about its outward normal), +/// and the leave direction is that direction × the face's outward normal — in the face's tangent +/// plane, at right angles to the boundary, away from the face. `length` is the size of the boundary +/// the stations are on (it sets how closely a station must lie on the surface and the step the +/// shape is read with). Each frame comes with the face's outward unit normal there. With `shape` +/// false only the leave direction and the normal are read (`bend` and `bend_change` are zero), +/// which needs no room on the surface beside the station. +pub fn frames_across(body: &Body, face: usize, stations: &[(Vec3, Vec3)], length: f64, shape: bool) -> Result> { if stations.len() > 1 << 16 || !(length.is_finite() && length > 0.0) { return Err(KernelError::Invalid("frames across a boundary need at most 65536 stations on a boundary of finite size".into())); } - let support = Support::of(face, length)?; - let outward = if face.orientation() { 1.0 } else { -1.0 }; + let r = body.record(); + let support = Support::of(r, face, length)?; + let outward = if support.forward { 1.0 } else { -1.0 }; let mut walk = Walk::new(length); let mut out = Vec::with_capacity(stations.len()); for (p, tangent) in stations { @@ -389,12 +364,13 @@ pub fn frames_across(face: &mt::Face, stations: &[(Vec3, Vec3)], length: f64, sh Ok(out) } -/// A support surface read at stations: the surface, its parameter box, and how close a station -/// must lie to it. +/// A support surface read at stations: the surface, where its parameters run (a periodic +/// direction without bound), whether its face is used along its natural normal, and how close a +/// station must lie to it. struct Support { - surf: mt::Surface, - range_u: (f64, f64), - range_v: (f64, f64), + surf: SurfaceEval, + range: [(f64, f64); 2], + forward: bool, tol: f64, } @@ -402,7 +378,7 @@ struct Support { /// next projection, which keeps the search on the same side of a periodic or split surface) and /// the finite-difference step that worked. struct Walk { - hint: Option<(f64, f64)>, + hint: Option<[f64; 2]>, step: f64, } @@ -415,45 +391,46 @@ impl Walk { } impl Support { - fn of(face: &mt::Face, length: f64) -> Result { - let surf = face.surface(); - let (Some(range_u), Some(range_v)) = surf.try_range_tuple() else { - return Err(KernelError::Failed("bridge: the support surface is unbounded".into())); - }; - // A face's own edges may sit a fit tolerance off its surface (a cylinder's wall as a NURBS - // next to its exact ring), so the projection is only asked to be close, not exact. + fn of(r: &Brep, face: usize, length: f64) -> Result { + let f = r.faces.get(face).ok_or_else(|| KernelError::Invalid("no such face".into()))?; + let surf = SurfaceEval::new(f.parameters()).map_err(|e| KernelError::Failed(format!("bridge: {e}")))?; + let dom = surf.domain(); + let range = [0, 1].map(|d| match (dom.period[d], dom.range[d]) { + (None, Some(r)) => r, + _ => (f64::NEG_INFINITY, f64::INFINITY), + }); + let forward = r + .shells + .iter() + .find_map(|s| match s { + solidcore_record::brep::Shell::Faces { faces, .. } => faces.iter().find(|o| o.face as usize == face).map(|o| o.forward), + _ => None, + }) + .unwrap_or(true); + // A face's own edges may sit a fit tolerance off its surface, so the projection is only + // asked to be close, not exact. let tol = (length * 1e-4).max(1e-6); - Ok(Support { surf, range_u, range_v, tol }) + Ok(Support { surf, range, forward, tol }) } - /// The frame at `p`, leaving in `leave(n)` (`n` the surface's unit normal there), and that - /// normal. Without `read_shape`, the frame's shape is left at zero. + /// The frame at `p`, leaving in `leave(n)` (`n` the surface's natural unit normal there), and + /// that normal. Without `read_shape`, the frame's shape is left at zero. fn station(&self, p: Vec3, leave: &dyn Fn(Vec3) -> Result, walk: &mut Walk, read_shape: bool) -> Result<(Frame, Vec3)> { - let (surf, range_u, range_v, tol) = (&self.surf, self.range_u, self.range_v, self.tol); - let project = |hint: Option<(f64, f64)>| surf.search_nearest_parameter(p3(p), hint, 100); - let close = |uv: (f64, f64)| from_p3(surf.subs(uv.0, uv.1)).dist(p) <= tol; + let (surf, [range_u, range_v], tol) = (&self.surf, self.range, self.tol); // The station before this one is the hint where it lands close; a chain that wraps the // surface (or a periodic one) falls back to a free search. - let (u, v) = match project(walk.hint).filter(|uv| close(*uv)).or_else(|| project(None).filter(|uv| close(*uv))) { - Some(uv) => uv, - None => return Err(KernelError::Invalid("a picked edge is not on the support surface".into())), - }; - walk.hint = Some((u, v)); - let at = from_p3(surf.subs(u, v)); - if at.dist(p) > tol { + let Some([u, v]) = surf.project(p, walk.hint, tol).or_else(|| surf.project(p, None, tol)) else { return Err(KernelError::Invalid("a picked edge is not on the support surface".into())); - } - let normal = surf.normal(u, v); - let n = Vec3::new(normal.x, normal.y, normal.z) - .normalized() - .ok_or_else(|| KernelError::Failed("bridge: the support surface has no normal".into()))?; + }; + walk.hint = Some([u, v]); + let fail = || KernelError::Failed("bridge: the support surface has no point there".into()); + let (_, su, sv) = surf.derivs(u, v).ok_or_else(fail)?; + let n = su.cross(sv).normalized().ok_or_else(|| KernelError::Failed("bridge: the support surface has no normal".into()))?; let w = leave(n)?; if !read_shape { return Ok((Frame { p, leave: w, bend: Vec3::ZERO, bend_change: Vec3::ZERO }, n)); } // Parameter-space direction that leaves in `w` at unit 3D speed: S_u·du + S_v·dv = w. - let su = tangent(surf, u, v, range_u, true); - let sv = tangent(surf, u, v, range_v, false); let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv)); let det = a * c - b * b; let scale = a.max(c).max(1e-30); @@ -463,8 +440,8 @@ impl Support { let du = (c * w.dot(su) - b * w.dot(sv)) / det; let dv = (a * w.dot(sv) - b * w.dot(su)) / det; // The samples of the parameter line. A station sits on the support surface's own - // boundary, so the line usually leaves the surface: the shape is then read from the - // samples of the one side that is still on it, which is the surface's own extension past + // boundary, so the line usually leaves the face: the shape is then read from the samples + // of the one side that is still on the surface, which is the surface's own extension past // that boundary (exact for a plane and a cylinder, what a blend continues from). let slack = 1e-9; let on = |t: f64, h: f64| { @@ -497,7 +474,7 @@ impl Support { let Some(offsets) = chosen else { return Err(KernelError::Invalid("the support surface is too small around a picked edge to read its shape".into())); }; - let q: Vec = offsets.iter().map(|t| from_p3(surf.subs(u + t * h * du, v + t * h * dv))).collect(); + let q: Vec = offsets.iter().map(|t| surf.point([u + t * h * du, v + t * h * dv]).ok_or_else(fail)).collect::>()?; let (Some(&f0), Some(&f1), Some(&f2), Some(&f3), Some(&f4)) = (q.first(), q.get(1), q.get(2), q.get(3), q.get(4)) else { return Err(KernelError::Failed("bridge: samples".into())); }; @@ -514,8 +491,9 @@ impl Support { let d3 = (f0 * -5.0 + f1 * 18.0 + f2 * -24.0 + f3 * 14.0 + f4 * -3.0) * (1.0 / (2.0 * h * h * h)); (d1, d2, d3) } else { - let d1 = (f0 * -1.0 + f1 * 8.0 + f3 * -8.0 + f4) * (1.0 / (12.0 * h)); - let d2 = (f0 + f1 * -16.0 + f2 * 30.0 + f3 * -16.0 + f4) * (1.0 / (12.0 * h * h)); + // Five-point central differences at the middle sample f2. + let d1 = (f0 + f1 * -8.0 + f3 * 8.0 + f4 * -1.0) * (1.0 / (12.0 * h)); + let d2 = (f0 * -1.0 + f1 * 16.0 + f2 * -30.0 + f3 * 16.0 + f4 * -1.0) * (1.0 / (12.0 * h * h)); let d3 = (f0 * -1.0 + f1 * 2.0 + f3 * -2.0 + f4) * (1.0 / (2.0 * h * h * h)); (d1, d2, d3) }; @@ -529,22 +507,6 @@ impl Support { } } -/// A first derivative of the surface in one parameter, by central differences (one-sided where -/// the parameter is at the edge of the domain). -fn tangent(surf: &mt::Surface, u: f64, v: f64, range: (f64, f64), along_u: bool) -> Vec3 { - let span = (range.1 - range.0).max(1e-12); - let h = (span * 1e-5).max(1e-12); - let at = |x: f64| if along_u { from_p3(surf.subs(x, v)) } else { from_p3(surf.subs(u, x)) }; - let x = if along_u { u } else { v }; - if x - h >= range.0 && x + h <= range.1 { - (at(x + h) - at(x - h)) * (0.5 / h) - } else if x + h <= range.1 { - (at(x + h) - at(x)) * (1.0 / h) - } else { - (at(x.min(range.1)) - at((x - h).max(range.0))) * (1.0 / h) - } -} - /// The geometric shape of a surface curve at a point from its first three derivatives along the /// curve: the unit tangent, the curvature vector and the arclength derivative of that curvature /// vector. All three are what a surface-to-surface continuity condition is stated with. @@ -678,6 +640,9 @@ pub fn bridge(a: &[Frame], b: &[Frame], orders: [Continuity; 2], crown: [f64; 2] return Err(KernelError::Invalid("a bridge's crown must be between -0.9 and 3".into())); } } + for g in orders { + g.built_by(Construction::Bridge)?; + } let stations = a.len(); let n = orders[0].conditions() + orders[1].conditions() - 1; if n == 0 || n > solidcraft_geom::bspline::MAX_SPLINE_DEGREE { @@ -721,71 +686,68 @@ pub fn bridge(a: &[Frame], b: &[Frame], orders: [Continuity; 2], crown: [f64; 2] knots_v.extend(std::iter::repeat_n(1.0, n + 1)); let points: Vec = ctrl.iter().map(|p| HPoint::weighted(*p, 1.0)).collect(); let nurbs = NurbsSurface::from_homogeneous([degree, n], [knots_u, knots_v], points).map_err(|e| KernelError::Failed(format!("bridge: {e}")))?; - guard("bridge surface", || crate::spline_conv::tensor_face(&nurbs).map(|f| surface_body(vec![f]))) + crate::surfaces::tensor_sheet(&nurbs) } -/// The surface of a bridge face as a grid of points, for callers that measure the result. +/// The one face of a bridge body: its surface and its parameter box. +pub(crate) fn the_face(body: &Body) -> Result<(SurfaceEval, [[f64; 2]; 2])> { + let r = body.record(); + let face = r.faces.first().ok_or_else(|| KernelError::Failed("bridge: no face".into()))?; + let surf = SurfaceEval::new(face.parameters()).map_err(|e| KernelError::Failed(format!("bridge: {e}")))?; + Ok((surf, face.domain)) +} + +/// The surface of a bridge face as a grid of points over its parameter box, for callers that +/// measure the result. pub fn sample_grid(body: &Body, along: usize, across: usize) -> Result>> { if !(2..=1025).contains(&along) || !(2..=1025).contains(&across) { return Err(KernelError::Invalid("a grid needs 2 to 1025 samples each way".into())); } - let face = body.solid.face_iter().next().ok_or_else(|| KernelError::Failed("bridge: no face".into()))?; - let surf = face.surface(); - let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { - return Err(KernelError::Failed("bridge: the surface is unbounded".into())); - }; - let mut out = Vec::with_capacity(along); - for i in 0..along { - let u = u0 + (u1 - u0) * i as f64 / (along - 1) as f64; - let mut row = Vec::with_capacity(across); - for j in 0..across { - let v = v0 + (v1 - v0) * j as f64 / (across - 1) as f64; - row.push(from_p3(surf.subs(u, v))); - } - out.push(row); - } - Ok(out) + let (surf, [[u0, u1], [v0, v1]]) = the_face(body)?; + let fail = || KernelError::Failed("bridge: the surface has no point there".into()); + (0..along) + .map(|i| { + let u = u0 + (u1 - u0) * i as f64 / (along - 1) as f64; + (0..across).map(|j| surf.point([u, v0 + (v1 - v0) * j as f64 / (across - 1) as f64]).ok_or_else(fail)).collect() + }) + .collect() } /// The most any point of a bridge's boundary row is from the chain it was built on — the row at /// `v0` for the first boundary, at `v1` for the second: what a stitch would have to close up. fn boundary_gap(made: &Body, line: &ChainLine, at_end: bool) -> Result { - let face = made.solid.face_iter().next().ok_or_else(|| KernelError::Failed("bridge: no face".into()))?; - let surf = face.surface(); - let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { - return Err(KernelError::Failed("bridge: the surface is unbounded".into())); - }; + let (surf, [[u0, u1], [v0, v1]]) = the_face(made)?; let v = if at_end { v1 } else { v0 }; let mut worst: f64 = 0.0; for i in 0..=256 { - let u = u0 + (u1 - u0) * i as f64 / 256.0; - worst = worst.max(line.nearest_with_distance(from_p3(surf.subs(u, v))).1); + let q = + surf.point([u0 + (u1 - u0) * i as f64 / 256.0, v]).ok_or_else(|| KernelError::Failed("bridge: the surface has no point there".into()))?; + worst = worst.max(line.nearest_with_distance(q).1); } Ok(worst) } /// Which face of `body` the blend continues from along each edge of a chain (one per edge, in -/// chain order): of the faces each edge bounds, the one whose tangent plane holds as much of -/// `leave` as possible there. A chain may run along several faces (a tube's rim along the halves -/// of its wall). -fn support_faces(body: &Body, chain: &[mt::Edge], leave: Vec3) -> Result> { +/// chain order, by its index in the body's record): of the faces each edge bounds, the one whose +/// tangent plane holds as much of `leave` as possible there. A chain may run along several faces +/// (a tube's rim along the halves of its wall). +fn support_faces(r: &Brep, chain: &Chain, leave: Vec3, size: f64) -> Result> { let mut out = Vec::with_capacity(chain.len()); - for edge in chain { - let curve = edge.curve(); - let (t0, t1) = curve.range_tuple(); - let mid = from_p3(curve.subs(0.5 * (t0 + t1))); - let mut best: Option<(f64, mt::Face)> = None; - for face in body.solid.face_iter() { - if !face.edge_iter().any(|f| f.id() == edge.id()) { - continue; - } - let Some((q, n, _)) = crate::curveblend::project(face, mid, None) else { continue }; - if q.dist(mid) > body.size() * 1e-6 + 1e-9 { - continue; - } + for &(e, _) in chain { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid("an edge reference".into()))?; + let mid = CurveEval::new(edge.parameters()) + .ok() + .and_then(|c| c.point(0.5 * (edge.interval[0] + edge.interval[1]))) + .ok_or_else(|| KernelError::Failed("bridge: an edge has no point".into()))?; + let mut best: Option<(f64, usize)> = None; + for u in &edge.uses { + let face = u.face as usize; + let Some(surf) = r.faces.get(face).and_then(|f| SurfaceEval::new(f.parameters()).ok()) else { continue }; + let Some(uv) = surf.project(mid, None, size * 1e-6 + 1e-9) else { continue }; + let Some(n) = surf.derivs(uv[0], uv[1]).and_then(|(_, su, sv)| su.cross(sv).normalized()) else { continue }; let score = (leave - n * leave.dot(n)).len(); - if best.as_ref().is_none_or(|(b, _)| score > *b) { - best = Some((score, face.clone())); + if best.is_none_or(|(b, _)| score > b) { + best = Some((score, face)); } } let (score, face) = best.ok_or_else(|| KernelError::Invalid("no face of the body holds a picked edge".into()))?; @@ -898,7 +860,8 @@ pub fn blend_between( } let chain_a = chain(a, picks_a)?; let chain_b = chain(b, picks_b)?; - let (line_a, line_b) = (ChainLine::of(&chain_a)?, ChainLine::of(&chain_b)?); + let (line_a, line_b) = (ChainLine::of(a, &chain_a)?, ChainLine::of(b, &chain_b)?); + let (record_a, record_b) = (a.record(), b.record()); if line_a.closed != line_b.closed { return Err(KernelError::Invalid("a closed chain blends only to a closed chain, and an open one only to an open one".into())); } @@ -913,21 +876,17 @@ pub fn blend_between( (mid_a - mid_b).normalized().ok_or_else(|| KernelError::Invalid("the two boundaries coincide: there is nothing to blend".into()))?, ), }; - let faces_a = support_faces(a, &chain_a, leave_a)?; - let faces_b = support_faces(b, &chain_b, leave_b)?; + let faces_a = support_faces(record_a, &chain_a, leave_a, a.size())?; + let faces_b = support_faces(record_b, &chain_b, leave_b, b.size())?; let (start_a, backwards_a) = seam.map_or((0.0, false), |[p, _]| line_a.start_at_seam(p)); let stations_a = line_a.stations(samples, start_a, backwards_a)?; let stations_b = pair_with(&stations_a, &line_b, seam.map(|[_, q]| q))?; - let frames_a = frames_on(&faces_a, &stations_a, &line_a, leave_a)?; - let frames_b = frames_on(&faces_b, &stations_b, &line_b, leave_b)?; + let frames_a = frames_on(record_a, &faces_a, &stations_a, &line_a, leave_a)?; + let frames_b = frames_on(record_b, &faces_b, &stations_b, &line_b, leave_b)?; let made = bridge(&frames_a, &frames_b, orders, crown)?; let gap = boundary_gap(&made, &line_a, false)?.max(boundary_gap(&made, &line_b, true)?); - let faces: Vec = made.solid.face_iter().cloned().collect(); - let mut rec = crate::record::Rebuild::default(); - for f in &faces { - rec.made(f, Vec::new()); - } - let blend = crate::record::rebuilt_body(surface_body(faces), &[&a.solid, &b.solid], &rec); + // The blend's face is new to the operation over `[a, b]`. + let blend = crate::surfaces::all_new(made, &[a, b])?; if !stitch { return Ok((blend, gap)); } diff --git a/crates/kernel/src/bridge_tests.rs b/crates/kernel/src/bridge_tests.rs index 82966612b..052795ec0 100644 --- a/crates/kernel/src/bridge_tests.rs +++ b/crates/kernel/src/bridge_tests.rs @@ -9,11 +9,9 @@ use crate::{box_solid, cylinder}; /// of that curvature vector at the start of the cross-section. The samples run inwards from the /// boundary, so nothing is asked of the surface outside its own domain. fn section_at(body: &Body, u: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let (Some(_), Some((v0, _))) = surf.try_range_tuple() else { panic!("unbounded") }; + let (surf, [_, [v0, _]]) = the_face(body).unwrap(); let h = 1e-3; - let q: Vec = (0..5).map(|k| from_p3(surf.subs(u, v0 + k as f64 * h))).collect(); + let q: Vec = (0..5).map(|k| surf.point([u, v0 + k as f64 * h]).unwrap()).collect(); let (f0, f1, f2, f3, f4) = (q[0], q[1], q[2], q[3], q[4]); let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (1.0 / (12.0 * h)); let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * h * h)); @@ -25,11 +23,9 @@ fn section_at(body: &Body, u: f64) -> (Vec3, Vec3, Vec3, Vec3) { /// The same at the end of the cross-section (`v = v1`), with the samples running back inwards and /// the odd derivatives turned round. fn section_end_at(body: &Body, u: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let (Some(_), Some((_, v1))) = surf.try_range_tuple() else { panic!("unbounded") }; + let (surf, [_, [_, v1]]) = the_face(body).unwrap(); let h = 1e-3; - let q: Vec = (0..5).map(|k| from_p3(surf.subs(u, v1 - k as f64 * h))).collect(); + let q: Vec = (0..5).map(|k| surf.point([u, v1 - k as f64 * h]).unwrap()).collect(); let (f0, f1, f2, f3, f4) = (q[0], q[1], q[2], q[3], q[4]); let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (-1.0 / (12.0 * h)); let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * h * h)); @@ -81,28 +77,17 @@ fn valley_between_cylinders(count: usize, r: f64) -> (Vec, Vec) { (a, b) } -/// The edges of `face` chained into one loop. -fn loop_of(face: &mt::Face) -> Vec { - let mut pool: Vec = face.edge_iter().collect(); - let mut out = vec![pool.remove(0)]; - let mut end = out[0].back().clone(); - while !pool.is_empty() { - let k = pool.iter().position(|e| e.front().id() == end.id() || e.back().id() == end.id()).unwrap(); - let e = pool.remove(k); - let e = if e.front().id() == end.id() { e } else { e.inverse() }; - end = e.back().clone(); - out.push(e); - } - out +/// The edges of `body`'s face `face` chained into one loop (its outer loop, as it runs). +fn loop_of(body: &Body, face: usize) -> Chain { + let r = body.record(); + let solidcore_record::brep::Loop::Edges { edges } = &r.faces[face].loops[0] else { panic!("a vertex loop") }; + edges.iter().map(|u| (u.edge as usize, u.forward)).collect() } -/// The face of `body` that contains `at`. -fn face_at(body: &Body, at: Vec3) -> mt::Face { - body.solid - .face_iter() - .find(|f| f.surface().search_nearest_parameter(p3(at), None, 100).is_some_and(|(u, v)| from_p3(f.surface().subs(u, v)).dist(at) < 1e-6)) - .unwrap() - .clone() +/// The face of `body` (its index) whose surface contains `at`. +fn face_at(body: &Body, at: Vec3) -> usize { + let r = body.record(); + r.faces.iter().position(|f| SurfaceEval::new(&f.surface).unwrap().project(at, None, 1e-6).is_some()).unwrap() } #[test] @@ -110,9 +95,9 @@ fn frames_read_a_plane_and_a_cylinder_wall() { // A 40 x 30 x 20 box: the top face's rim leaves along +x, a plane with no curvature. let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); let top = face_at(&b, Vec3::new(20.0, 15.0, 20.0)); - let rim = loop_of(&top); - assert!(chain_closes(&rim)); - let f = frames(&top, &rim, Vec3::new(1.0, 0.0, 0.0), 9).unwrap(); + let rim = loop_of(&b, top); + assert!(chain_closes(&b, &rim)); + let f = frames(&b, top, &rim, Vec3::new(1.0, 0.0, 0.0), 9).unwrap(); assert_eq!(f.len(), 9); for s in &f { assert!((s.p.z - 20.0).abs() < 1e-9, "{s:?}"); @@ -127,15 +112,15 @@ fn frames_read_a_plane_and_a_cylinder_wall() { // has no tangent plane to work in. let c = cylinder(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), 10.0, 30.0).unwrap(); let wall = face_at(&c, Vec3::new(10.0, 0.0, 15.0)); - let ring = loop_of(&wall); - let f = frames(&wall, &ring, Vec3::new(0.0, 0.0, 1.0), 5).unwrap(); + let ring = loop_of(&c, wall); + let f = frames(&c, wall, &ring, Vec3::new(0.0, 0.0, 1.0), 5).unwrap(); for s in &f { assert!(s.bend.len() < 1e-6, "the axis direction is straight: {s:?}"); } // A leave direction that is normal to the support surface has no tangent plane to work in. - assert!(frames(&top, &rim, Vec3::new(0.0, 0.0, 1.0), 9).is_err(), "a face's own normal is no direction to leave in"); + assert!(frames(&b, top, &rim, Vec3::new(0.0, 0.0, 1.0), 9).is_err(), "a face's own normal is no direction to leave in"); // On the cylinder's wall only a direction with a tangential part is usable. - assert!(frames(&wall, &ring, Vec3::new(1.0, 0.0, 0.0), 5).is_ok()); + assert!(frames(&c, wall, &ring, Vec3::new(1.0, 0.0, 0.0), 5).is_ok()); } #[test] @@ -224,6 +209,9 @@ fn the_bridge_refuses_what_it_cannot_hold() { assert!(bridge(&bad, &b, [Continuity::G1, Continuity::G1], [0.0, 0.0]).is_err()); // Fewer than two stations. assert!(bridge(&a[..1], &b[..1], [Continuity::G1, Continuity::G1], [0.0, 0.0]).is_err()); + // G4 is past the bridge's Hermite rows: refused by the one check, not built as G3. + let e = bridge(&a, &b, [Continuity::G4, Continuity::G1], [0.0, 0.0]).unwrap_err().to_string(); + assert!(e.contains("not supported yet") && e.contains("g4"), "{e}"); // Every order from G0 to G3 builds. for (x, y) in [(Continuity::G0, Continuity::G0), (Continuity::G1, Continuity::G0), (Continuity::G3, Continuity::G1)] { let body = bridge(&a, &b, [x, y], [0.0, 0.0]).unwrap(); @@ -234,15 +222,6 @@ fn the_bridge_refuses_what_it_cannot_hold() { } } -#[test] -fn continuity_parses_its_words() { - assert_eq!(Continuity::parse("g0"), Some(Continuity::G0)); - assert_eq!(Continuity::parse("G3"), Some(Continuity::G3)); - assert_eq!(Continuity::parse("g9"), None); - assert_eq!(Continuity::parse(""), None); - assert_eq!([Continuity::G0, Continuity::G1, Continuity::G2, Continuity::G3].map(Continuity::conditions), [1, 2, 3, 4]); -} - /// A radius-10 tube along z from `z0` to `z0 + 30`, turned `turn` radians about its axis (which /// moves where its rim's seam sits), with the end face at `open_at` taken off: a surface body /// whose rim there is a closed chain. @@ -332,13 +311,12 @@ fn a_blend_between_offset_strips_is_the_cubic_hermite_strip() { } } // G1 at both seams: the blend's normal is the top faces' (±z) all along each rim. - let face = made.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { panic!("unbounded") }; + let (surf, [[u0, u1], [v0, v1]]) = the_face(&made).unwrap(); for i in 0..=16 { let u = u0 + (u1 - u0) * i as f64 / 16.0; for v in [v0, v1] { - let n = surf.normal(u, v); + let (_, su, sv) = surf.derivs(u, v).unwrap(); + let n = su.cross(sv); let worst = angle_deg(Vec3::new(n.x, n.y, n.z), Vec3::Z).min(angle_deg(Vec3::new(n.x, n.y, n.z), Vec3::Z * -1.0)); assert!(worst < 0.01, "at u = {u}, v = {v}: the normal is {worst}° off the top faces'"); } diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index 6f3ce61d9..324bc8520 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -1,15 +1,15 @@ -//! Building bodies: extrude and revolve planar regions, primitives. +//! Building bodies: extrude and revolve planar regions, primitives, lofts and sweeps, each +//! through SMLib ([`crate::smlib_sweeps`]); a profile face as its schema 4 record +//! ([`planar_face_record`]). -use mt::builder; -use solidcraft_geom::{Grid, Loop2, Plane, Region2, Ring, Seg2, Vec2, Vec3}; -use truck_modeling as mt; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; -use crate::body::{Body, Solid, from_p3, p3, v3}; -use crate::history::FaceProv; +use crate::body::Body; +use crate::draft_corners::DraftCorner; use crate::numbered::{self, NumberedLoop, NumberedRegion}; -use crate::record::{self, Side}; use crate::sweep_path::RailFit; -use crate::{KernelError, Result, guard}; +use crate::{KernelError, Result}; const MAX_SEGS: usize = 20_000; @@ -17,126 +17,6 @@ fn finite(x: f64, what: &str) -> Result { if x.is_finite() && x.abs() < 1e7 { Ok(x) } else { Err(KernelError::Invalid(format!("{what} = {x}"))) } } -/// A closed wire in 3D from a sketch loop, with each edge's segment and that segment's -/// position in the loop (a big arc makes two edges). -fn wire_sources(plane: &Plane, lp: &Loop2) -> Result<(mt::Wire, Vec<(mt::Edge, Seg2, usize)>)> { - let n = lp.segs.len(); - if n == 0 || n > MAX_SEGS { - return Err(KernelError::Invalid(format!("loop with {n} segments"))); - } - if !lp.is_closed(1e-6) { - return Err(KernelError::Invalid("profile loop is not closed".into())); - } - chain_sources(plane, &lp.segs, true) -} - -/// An open wire in 3D through a chain of sketch segments, each starting where the one before -/// ends (a closed chain makes a closed wire). -pub(crate) fn chain_wire(plane: &Plane, segs: &[Seg2]) -> Result { - chain_wire_seeds(plane, segs).map(|(wire, _)| wire) -} - -/// [`chain_wire`], with each edge's id and the position in the chain of the segment it was -/// built from (a big arc makes two edges), in wire order. -pub(crate) fn chain_wire_seeds(plane: &Plane, segs: &[Seg2]) -> Result<(mt::Wire, Vec<(mt::EdgeID, usize)>)> { - let n = segs.len(); - if n == 0 || n > MAX_SEGS { - return Err(KernelError::Invalid(format!("curve chain with {n} segments"))); - } - if !segs.iter().all(seg_ok) { - return Err(KernelError::Invalid("non-finite curve".into())); - } - for (s, t) in segs.iter().zip(segs.iter().skip(1)) { - if s.end().dist(t.start()) > 1e-6 { - return Err(KernelError::Invalid("the curves are not connected end to end".into())); - } - } - let closed = segs.first().zip(segs.last()).is_some_and(|(f, l)| l.end().dist(f.start()) <= 1e-6); - let (wire, sources) = chain_sources(plane, segs, closed)?; - Ok((wire, sources.into_iter().map(|(e, _, i)| (e.id(), i)).collect())) -} - -/// The edges of a chain of segments (closed: the last one ends on the first's start vertex), -/// with each edge's segment and that segment's position in the chain (a big arc makes two -/// edges). -fn chain_sources(plane: &Plane, segs: &[Seg2], closed: bool) -> Result<(mt::Wire, Vec<(mt::Edge, Seg2, usize)>)> { - let n = segs.len(); - let mut verts: Vec = segs.iter().map(|s| builder::vertex(p3(plane.to_world(s.start())))).collect(); - if !closed && let Some(last) = segs.last() { - verts.push(builder::vertex(p3(plane.to_world(last.end())))); - } - let mut edges = Vec::with_capacity(n); - let mut sources = Vec::with_capacity(n); - for (i, s) in segs.iter().enumerate() { - let (Some(a), Some(b)) = (verts.get(i), verts.get(if closed { (i + 1) % n } else { i + 1 })) else { continue }; - for e in seg_edges(plane, s, a, b)? { - sources.push((e.clone(), *s, i)); - edges.push(e); - } - } - Ok((edges.into(), sources)) -} - -/// The edges of one segment from `a` to `b` (a big arc makes two). -fn seg_edges(plane: &Plane, s: &Seg2, a: &mt::Vertex, b: &mt::Vertex) -> Result> { - Ok(match *s { - Seg2::Line { .. } => vec![builder::line(a, b)], - Seg2::Arc { sweep, .. } => { - if sweep.abs() < 1e-9 { - return Err(KernelError::Invalid("zero-length arc".into())); - } - // Split big arcs so every piece is well conditioned. - if sweep.abs() > std::f64::consts::PI * 1.5 { - let vm = builder::vertex(p3(plane.to_world(s.mid()))); - vec![ - builder::circle_arc(a, &vm, p3(plane.to_world(s.point_at(0.25)))), - builder::circle_arc(&vm, b, p3(plane.to_world(s.point_at(0.75)))), - ] - } else { - vec![builder::circle_arc(a, b, p3(plane.to_world(s.mid())))] - } - } - Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => { - vec![crate::freeform::edge(plane, s, a, b).ok_or_else(|| KernelError::Invalid("profile curve".into()))?] - } - }) -} - -/// An edge of a profile wire: the segment it was built from and the profile segments under it. -pub(crate) struct ProfileEdge { - pub edge: mt::Edge, - pub segment: Seg2, - pub numbers: Vec, -} - -/// A wire built from a profile loop, with its edges in wire order. -pub(crate) struct ProfileWire { - pub wire: mt::Wire, - pub edges: Vec, -} - -/// The wires of a region oriented as the builders build it ([`NumberedRegion::oriented`]), each -/// with what its edges were built from. -fn region_wires(plane: &Plane, r: &NumberedRegion) -> Result> { - r.loops() - .map(|lp| { - let (wire, s) = wire_sources(plane, &lp.lp)?; - let edges = s.into_iter().map(|(edge, segment, i)| ProfileEdge { edge, segment, numbers: lp.numbers(i).to_vec() }).collect(); - Ok(ProfileWire { wire, edges }) - }) - .collect() -} - -/// The wires alone. -fn wires_of(profile: &[ProfileWire]) -> Vec { - profile.iter().map(|p| p.wire.clone()).collect() -} - -/// The profile edges as sweep seeds: each edge with the profile segments under it. -fn seeds(profile: &[ProfileWire]) -> Vec<(mt::EdgeID, Vec)> { - profile.iter().flat_map(|p| &p.edges).map(|e| (e.edge.id(), e.numbers.clone())).collect() -} - /// A region numbered on its own, as given. fn numbered_region(r: &Region2) -> Result { numbered::number_regions(std::slice::from_ref(r)).pop().ok_or_else(|| KernelError::Invalid("profile".into())) @@ -147,16 +27,12 @@ fn oriented(r: &Region2) -> Result { numbered_region(r).map(|n| n.oriented()) } -/// A planar face from a region (outer loop with holes). -pub(crate) fn face(plane: &Plane, r: &Region2) -> Result { - attach_profile(&wires_of(®ion_wires(plane, &oriented(r)?)?)) +/// The outer loop a tapered extrusion takes: counterclockwise, collinear lines merged. +pub(crate) fn oriented_outer(r: &Region2) -> Result { + Ok(oriented(r)?.map_loops(|l| l.merged_lines(continues_straight)).outer.lp) } -fn attach_profile(wires: &[mt::Wire]) -> Result { - guard("face", || builder::try_attach_plane(wires).map_err(|e| KernelError::Invalid(format!("profile: {e}")))) -} - -fn region_ok(r: &Region2) -> Result<()> { +pub(crate) fn region_ok(r: &Region2) -> Result<()> { if r.area().abs() < 1e-9 { return Err(KernelError::Invalid("profile has no area".into())); } @@ -175,7 +51,7 @@ fn seg_ok(s: &Seg2) -> bool { } Seg2::Cubic { p0, p1, p2, p3 } => p0.is_finite() && p1.is_finite() && p2.is_finite() && p3.is_finite(), Seg2::Conic { a, apex, b, w } => a.is_finite() && apex.is_finite() && b.is_finite() && w.is_finite() && w > 1e-9, - Seg2::Bezier { n, p } => (4..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(&n) && p.iter().all(|q| q.is_finite()), + Seg2::Bezier { n, p } => (4..=solidcore_record::MAX_BEZIER_DEGREE as u8).contains(&n) && p.iter().all(|q| q.is_finite()), } } @@ -191,19 +67,33 @@ pub(crate) fn frame_ok(plane: &Plane) -> bool { /// Extrude each region from `start` to `end` along the plane normal (offsets in mm, `end > start`). pub fn extrude(plane: &Plane, regions: &[Region2], start: f64, end: f64) -> Result> { - extrude_with(plane, regions, start, end, false) + let _span = solidcraft_profile::span("kernel", "extrude"); + extrude_with(plane, regions, start, end, None) } /// [`extrude`] with each run of profile lines that continue one another in a straight line (a side /// drawn in two pieces, a mirrored half meeting its mirror image) swept into one side face over -/// all its pieces, rather than coplanar faces with an edge between them (#1788). The side's +/// all its pieces, rather than coplanar faces with an edge between them (#1788), and each run of +/// free-form segments (conics, Béziers) that `one_curve` says are pieces of one curve (an +/// ellipse's four quarters, a spline's spans) swept as that one curve into one wall. The side's /// history lists every piece under it. For the Extrude feature; other builders (sheet metal's /// flat pattern, tools) keep a face per segment. -pub fn extrude_whole_sides(plane: &Plane, regions: &[Region2], start: f64, end: f64) -> Result> { - extrude_with(plane, regions, start, end, true) +pub fn extrude_whole_sides(plane: &Plane, regions: &[Region2], start: f64, end: f64, one_curve: &dyn Fn(&Seg2, &Seg2) -> bool) -> Result> { + let _span = solidcraft_profile::span("kernel", "extrude_whole_sides"); + extrude_with(plane, regions, start, end, Some(one_curve)) } -fn extrude_with(plane: &Plane, regions: &[Region2], start: f64, end: f64, whole_sides: bool) -> Result> { +/// The degree of a free-form segment (a conic or a Bézier), none for a line or an arc. +fn free_form_degree(s: &Seg2) -> Option { + match *s { + Seg2::Conic { .. } => Some(2), + Seg2::Cubic { .. } => Some(3), + Seg2::Bezier { n, .. } => Some(n), + Seg2::Line { .. } | Seg2::Arc { .. } => None, + } +} + +fn extrude_with(plane: &Plane, regions: &[Region2], start: f64, end: f64, one_curve: Option<&dyn Fn(&Seg2, &Seg2) -> bool>) -> Result> { if !frame_ok(plane) { return Err(KernelError::Invalid("extrude frame is not finite and orthonormal".into())); } @@ -215,105 +105,38 @@ fn extrude_with(plane: &Plane, regions: &[Region2], start: f64, end: f64, whole_ if regions.is_empty() { return Err(KernelError::Invalid("no profile selected".into())); } - let n = plane.normal(); - let mut out = Vec::new(); - for r in regions { - region_ok(r)?; - let base = plane.offset(lo); - let pieces = oriented(r)?; - let numbered = if whole_sides { pieces.map_loops(|l| l.merged_lines(continues_straight)) } else { pieces.clone() }; - // A joined side's source is its first piece, a segment of the profile as drawn (the side - // lies along it): the sketch curve it is certified and named by, as when it stood alone. - let first_piece = |side: &ProfileEdge| { - pieces - .loops() - .flat_map(|l| l.lp.segs.iter()) - .copied() - .find(|piece| side.numbers.len() > 1 && piece.start() == side.segment.start()) - .unwrap_or(side.segment) - }; - let profile = region_wires(&base, &numbered)?; - let wires = wires_of(&profile); - let f = guard("extrude profile", || builder::try_attach_plane(&wires).map_err(|e| KernelError::Invalid(format!("profile: {e}"))))?; - let solid: Solid = guard("extrude", || Ok(builder::tsweep(&f, v3(n * (hi - lo)))))?; - let body = Body::new(solid)?; - // tsweep retains each actual input boundary edge on its generated side: one pass over - // the faces matches topology identity (never face order, surface samples or - // centroids) for both the face sources and the history. The profile face is the start - // cap, the one face holding no profile edge the end cap. - let (sources, history) = guard("extrude source identities", || { - let by_edge: std::collections::HashMap = - profile.iter().flat_map(|p| &p.edges).map(|e| (e.edge.id(), e)).collect(); - let mut faces: Vec<(mt::FaceID, Vec<&ProfileEdge>)> = Vec::new(); - let mut visits = 0usize; - for generated in body.solid.face_iter() { - let mut matching = Vec::new(); - for edge in generated.absolute_boundaries().iter().flatten() { - visits += 1; - if let Some(e) = by_edge.get(&edge.id()) { - matching.push(*e); + regions + .iter() + .map(|r| { + region_ok(r)?; + let pieces = oriented(r)?; + let Some(one_curve) = one_curve else { + return crate::smlib_sweeps::extrude(plane, &crate::smlib_sweeps::region_pieces(&pieces, &pieces), Some(r), lo, hi - lo, 1.0, None); + }; + // Pieces of one curve: free-form segments of one degree that the caller says are one + // curve. Each loop starts where such a run starts, so no run wraps round its end. + let joins = |s: &Seg2, t: &Seg2| free_form_degree(s).is_some_and(|d| free_form_degree(t) == Some(d)) && one_curve(s, t); + let numbered = pieces.map_loops(|l| l.merged_lines(continues_straight).starting_a_run(joins)); + let mut swept = crate::smlib_sweeps::region_pieces(&numbered, &pieces); + let mut k = 0; + for l in numbered.loops() { + for i in 1..l.lp.segs.len() { + if let (Some(s), Some(t)) = (l.lp.segs.get(i - 1), l.lp.segs.get(i)) + && let Some(x) = swept.get_mut(k + i) + { + x.joins_previous = joins(s, t); } } - faces.push((generated.id(), matching)); + k += l.lp.segs.len(); } - let mut ends = faces.iter().filter(|(id, matching)| *id != f.id() && matching.is_empty()).map(|(id, _)| *id); - let end = match (ends.next(), ends.next()) { - (Some(id), None) => Some(id), - _ => None, - }; - let upper = end.filter(|_| faces.len() <= 50_000 && visits <= 200_000); - let small = r.outer.segs.len() + r.holes.iter().map(|hole| hole.segs.len()).sum::() <= 4096; - let mut sources = Vec::with_capacity(faces.len()); - let mut history = Some(Vec::with_capacity(faces.len())); - for (id, matching) in &faces { - let (source, prov) = if *id == f.id() { - let source = upper.and_then(|_| { - small.then(|| crate::FaceSource::ExtrudeCap { - high: false, - region: r.clone(), - plane: Plane { origin: base.origin, x: plane.x, y: -plane.y }, - }) - }); - (source, Some(record::cap(false))) - } else if Some(*id) == upper { - (small.then(|| crate::FaceSource::ExtrudeCap { high: true, region: r.clone(), plane: plane.offset(hi) }), Some(record::cap(true))) - } else if let [side] = matching.as_slice() { - let basis = match side.segment { - Seg2::Line { a, b } => { - let d = b - a; - d.normalized().and_then(|direction| { - let foot = a - direction * a.dot(direction); - Plane::new(plane.to_world(foot), plane.dir_to_world(direction), n) - }) - } - _ => None, - }; - ( - Some(crate::FaceSource::ExtrudeSide { segment: first_piece(side), plane: basis, coalesced: false }), - Some(record::profile(&side.numbers)), - ) - } else if Some(*id) == end { - (None, Some(record::cap(true))) - } else { - (None, None) - }; - sources.push(source); - history = history.zip(prov).map(|(mut h, p)| { - h.push(p); - h - }); - } - Ok((sources, history)) - })?; - let body = body.with_face_sources(Some(std::sync::Arc::new(sources))); - out.push(record::attach(body, &[], history, Default::default())?); - } - Ok(out) + crate::smlib_sweeps::extrude(plane, &swept, Some(r), lo, hi - lo, 1.0, None) + }) + .collect() } /// `t` carries on from `s` in the same straight line: the turn at their meeting point is within /// rounding of none, measured against both lengths. -fn continues_straight(s: &Seg2, t: &Seg2) -> bool { +pub(crate) fn continues_straight(s: &Seg2, t: &Seg2) -> bool { let (u, v) = (s.end() - s.start(), t.end() - t.start()); let (lu, lv) = (u.len(), v.len()); lu > 0.0 && lv > 0.0 && s.end().dist(t.start()) <= 1e-9 * (lu + lv) && u.dot(v) > 0.0 && u.cross(v).abs() <= 1e-9 * lu * lv @@ -339,18 +162,20 @@ pub fn canonical_revolve_axis(plane: &Plane, region: &Region2, axis_origin: Vec2 /// Revolve each region about the sketch axis by `angle` radians. /// This legacy API preserves its historical sweep sign behavior. pub fn revolve(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result> { - revolved(plane, regions, axis_origin, axis_dir, angle, false) + let _span = solidcraft_profile::span("kernel", "revolve"); + revolved(plane, regions, axis_origin, axis_dir, angle) } -/// [`revolve`] for bodies that are final (new bodies, not a boolean's tools): a partial turn's -/// planar faces come out whole too, as a full turn's always do (#726). A tool is left as swept: -/// healed, its planar faces meet a target exactly where they are tangent to it, and the -/// boolean leaves pieces there that touch. The boolean heals its own result anyway. +/// [`revolve`] for bodies that are final (new bodies, not a boolean's tools), with each planar +/// face whole (#726): SMLib's revolution makes one face of each profile segment and of each +/// cap, so this is [`revolve`]. pub fn revolve_whole(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result> { - revolved(plane, regions, axis_origin, axis_dir, angle, true) + let _span = solidcraft_profile::span("kernel", "revolve_whole"); + revolved(plane, regions, axis_origin, axis_dir, angle) } -fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64, whole: bool) -> Result> { +/// Each region revolved through SMLib ([`crate::smlib_sweeps::revolve`]). +fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result> { let angle = finite(angle, "angle")?; if angle.abs() < 1e-6 { return Err(KernelError::Invalid("revolve angle is zero".into())); @@ -387,43 +212,6 @@ fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec arc => arc, }) }; - // Full circles start at an odd angle: their seam points then don't lie in the planes - // through the profile's centre that other bodies tend to cut along. Each new arc comes - // from every given arc it overlaps. - let reseam = |nl: NumberedLoop| -> NumberedLoop { - let l = &nl.lp; - let c = match l.segs.first() { - Some(Seg2::Arc { center, radius, .. }) => Some((*center, *radius)), - _ => None, - }; - // (A circle touching the axis keeps its vertex there.) - let touches = c.is_some_and(|(center, radius)| (d.cross(center - axis_origin).abs() - radius).abs() < 1e-7); - match c { - Some((center, radius)) - if !touches - && l.segs.iter().all( - |s| matches!(s, Seg2::Arc { center: c2, radius: r2, .. } if c2.dist(center) < 1e-9 && (r2 - radius).abs() < 1e-9), - ) - && (l - .segs - .iter() - .map(|s| match s { - Seg2::Arc { sweep, .. } => *sweep, - _ => 0.0, - }) - .sum::() - .abs() - - std::f64::consts::TAU) - .abs() - < 1e-6 => - { - let ccw = l.signed_area() > 0.0; - let n = Loop2::circle_from(center, radius, 0.4142); - nl.resplit_circle(if ccw { n } else { n.reversed() }) - } - _ => nl, - } - }; // Adjacent profiles revolved together leave the axis edge split where they met: one // edge again, so the builders for a profile with an edge on the axis take it (swept // pieces of the axis are zero-area faces that booleans fail on). @@ -432,90 +220,20 @@ fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec let (a, b, c) = (s.start(), s.end(), t.end()); on_axis(a) && on_axis(b) && on_axis(c) && (b - a).dot(c - b) > 0.0 }; - let given = numbered_region(r)?.map_loops(|l| reseam(snap_loop(l).merged_lines(axis_run))); - let r = &given.region(); - if angle.abs() >= std::f64::consts::TAU - 1e-9 - && r.holes.is_empty() - && let Some(b) = full_turn_on_axis(plane, &given.outer, axis_origin, d, angle)? - { - out.push(b); - continue; - } - let profile = region_wires(plane, &given.oriented())?; - let f = attach_profile(&wires_of(&profile))?; - // Partial revolves sweep toward the side the sketch normal points to (as features - // extrude toward it). + // Partial turns go toward the side the sketch normal points to (as features extrude + // toward it). + let given = numbered_region(r)?.map_loops(|l| snap_loop(l).merged_lines(axis_run)); let c = plane.to_world(r.centroid()); let radial = (c - o) - axis * (c - o).dot(axis); - let toward = axis.cross(radial).dot(plane.normal()); - let angle = if toward < 0.0 { -angle } else { angle }; - // A profile with an edge on the axis: no zero-area face where that edge turns on itself. - if r.holes.is_empty() - && let Some(b) = revolve_on_axis(plane, &given.outer, axis_origin, d, angle)? - { - out.push(b); - continue; - } - // Edges on the axis (a spherical shell's two radial lines, say) sweep into degenerate faces - // there, which truck only tessellates reliably with the axis through the world origin. Off - // it, the body measured too large and booleans with it failed or removed the wrong side. - // Build such a profile there and move it into place, as `revolve_touching_axis` does. - let axis_edges = r.outer.segs.iter().filter(|s| matches!(**s, Seg2::Line { a, b } if on_axis(a) && on_axis(b))).count(); - let shift = if axis_edges > 0 { o } else { Vec3::ZERO }; - let (profile, f) = if shift.len() > 0.0 { - let local = Plane { origin: plane.origin - shift, ..*plane }; - let profile = region_wires(&local, &given.oriented())?; - let f = attach_profile(&wires_of(&profile))?; - (profile, f) - } else { - (profile, f) - }; - let solid: Solid = guard("revolve", || Ok(builder::rsweep(&f, p3(o - shift), v3(axis), mt::Rad(angle))))?; - let closed = angle.abs() >= std::f64::consts::TAU; - let history = guard("revolve history", || Ok(record::swept_face(&solid, &f, &seeds(&profile), closed)))?; - let solid = if shift.len() > 0.0 { builder::translated(&solid, v3(shift)) } else { solid }; - let (solid, history) = if closed || whole { turned_whole(solid, history) } else { (solid, history) }; - out.push(record::attach(Body::new(solid)?, &[], history, Default::default())?); + let angle = if axis.cross(radial).dot(plane.normal()) < 0.0 { -angle } else { angle }; + out.push(crate::smlib_sweeps::revolve(plane, &crate::smlib_sweeps::pieces(given.oriented().loops()), o, axis, angle)?); } Ok(out) } -/// A revolved solid with its planar faces whole (#726): the sweep turns each profile edge into -/// two or three patches, the planar ones on revolved surfaces, which stayed apart until a later -/// feature healed the body, so a pick on one took part of the face. Healed as booleans heal -/// their results, each face is still generated, from the profile edges of the patches merged -/// into it. The solid as it was when healing fails or can't be followed. -fn turned_whole(solid: Solid, faces: Option>) -> (Solid, Option>) { - let Some(given) = faces.as_ref() else { return (solid, faces) }; - let Ok(size) = Body::new(solid.clone()).map(|b| b.size()) else { return (solid, faces) }; - let healed = guard("heal revolve", || { - let (healed, map) = crate::heal::heal_traced(solid.clone(), size, &[]); - let failed = || KernelError::Failed("heal revolve".into()); - if !crate::boolean_record::edges_evaluate(&healed) { - return Err(failed()); - } - let carried = map - .ok_or_else(failed)? - .faces - .iter() - .map(|under| { - let mut origins: Vec<_> = under.iter().map(|i| given.get(*i).map(|f| f.origins.clone())).collect::>>()?.concat(); - origins.sort(); - origins.dedup(); - Some(FaceProv { origins, change: crate::history::Change::Generated }) - }) - .collect::>>() - .ok_or_else(failed)?; - Ok((healed, carried)) - }); - match healed { - Ok((healed, carried)) => (healed, Some(carried)), - Err(_) => (solid, faces), - } -} - /// Axis-aligned box between two corners. pub fn box_solid(a: Vec3, b: Vec3) -> Result { + let _span = solidcraft_profile::span("kernel", "box_solid"); let (lo, hi) = (a.min(b), a.max(b)); let s = hi - lo; if !(s.x > 1e-6 && s.y > 1e-6 && s.z > 1e-6 && s.is_finite() && s.len() < 1e7) { @@ -563,6 +281,7 @@ pub(crate) const SEAM_ANGLE: f64 = 0.6131; /// Cylinder with base centre `base`, axis direction `axis`, radius and height. pub fn cylinder(base: Vec3, axis: Vec3, radius: f64, height: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "cylinder"); let plane = Plane::from_normal(base, axis).ok_or_else(|| KernelError::Invalid("cylinder axis".into()))?; let radius = finite(radius, "radius")?; if radius <= 1e-6 { @@ -575,13 +294,20 @@ pub fn cylinder(base: Vec3, axis: Vec3, radius: f64, height: f64) -> Result Result { - sphere_patches(center, radius) + let _span = solidcraft_profile::span("kernel", "sphere"); + let radius = finite(radius, "radius")?; + if radius <= 1e-6 || !center.is_finite() || center.len() >= 1e7 { + return Err(KernelError::Invalid("radius must be positive".into())); + } + crate::smlib_sweeps::sphere(center, radius) } /// Torus about the Z axis through `center`. pub fn torus(center: Vec3, major: f64, minor: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "torus"); let (major, minor) = (finite(major, "major radius")?, finite(minor, "minor radius")?); if !(minor > 1e-6 && major > minor) { return Err(KernelError::Invalid("torus needs major > minor > 0".into())); @@ -597,7 +323,7 @@ pub fn torus(center: Vec3, major: f64, minor: f64) -> Result { /// neighbours now meet at one point). Loops of arcs on one circle, and loops of lines, arcs and /// free curves (spline and conic pieces, such as the outlines of text) where the arcs meet their /// neighbours tangentially are supported. -fn offset_loop(lp: &Loop2, d: f64) -> Result>> { +pub(crate) fn offset_loop(lp: &Loop2, d: f64) -> Result>> { if d == 0.0 { return Ok(lp.segs.iter().copied().map(Some).collect()); } @@ -747,7 +473,7 @@ fn true_offset(s: &Seg2, t: f64, d: f64) -> Option { /// higher Bézier moves its control polygon ([`offset_polygon`]), its middle then put on the true /// offset. Its ends then go to `a` and `b`, along its end tangents (where moved neighbours meet /// it), their handles kept pointing the same way. Close for a curve that turns little against -/// `d`; [`offset_splits`] cuts the others into such pieces first. +/// `d`. fn offset_curve(s: &Seg2, a: Vec2, b: Vec2, d: f64) -> Option { let (n0, n1) = (true_offset(s, 0.0, d)?, true_offset(s, 1.0, d)?); let (t0, t3) = (s.start_tangent(), s.end_tangent()); @@ -799,7 +525,7 @@ fn offset_curve(s: &Seg2, a: Vec2, b: Vec2, d: f64) -> Option { q } Seg2::Bezier { n, p } => { - let k = (n as usize).clamp(1, solidcraft_geom::MAX_BEZIER_DEGREE); + let k = (n as usize).clamp(1, solidcore_record::MAX_BEZIER_DEGREE); let mut q = offset_polygon(p.get(..=k)?, n0, n1, d)?; let mut all = p; for (dst, src) in all.iter_mut().zip(&q) { @@ -850,79 +576,6 @@ fn offset_curve(s: &Seg2, a: Vec2, b: Vec2, d: f64) -> Option { }) } -/// How far a moved free curve strays from the free curve `s`'s true offset by `d`: the largest -/// distance from its points to the true offset's (on polylines of [`OFFSET_SAMPLES`] spans). -pub(crate) fn offset_error(s: &Seg2, d: f64) -> Option { - let (a, b) = (true_offset(s, 0.0, d)?, true_offset(s, 1.0, d)?); - let moved = offset_curve(s, a, b, d)?; - let n = OFFSET_SAMPLES * 2; - let truth: Vec = (0..=n).map(|k| true_offset(s, k as f64 / n as f64, d)).collect::>()?; - let near = |p: Vec2| { - truth - .iter() - .zip(truth.iter().skip(1)) - .map(|(x, y)| Seg2::Line { a: *x, b: *y }) - .map(|l| l.point_at(l.closest_param(p)).dist(p)) - .fold(f64::INFINITY, f64::min) - }; - Some((0..=n).map(|k| near(moved.point_at(k as f64 / n as f64))).fold(0.0, f64::max)) -} - -/// How close a moved free curve is kept to its true offset by `d`: 2 % of it, or 10 µm (a -/// slope's offset is a fraction of a millimetre on text: finer would cut letters into many -/// pieces, and every piece a face the booleans meet). -pub(crate) fn offset_tolerance(d: f64) -> f64 { - (d.abs() * 2e-2).max(1e-2) -} - -/// Deepest halving of a free curve in [`offset_splits`] (at most 2^6 pieces). -const MAX_OFFSET_DEPTH: u32 = 6; - -/// Whether the free curve `s` bends anywhere tighter than `d` (its radius of curvature below -/// |d|, on [`OFFSET_SAMPLES`] points): moved that far towards its centre, its true offset folds -/// over itself there. -fn tighter_than(s: &Seg2, d: f64) -> bool { - let h = 1e-4; - (0..=OFFSET_SAMPLES).any(|k| { - let t = (k as f64 / OFFSET_SAMPLES as f64).clamp(h, 1.0 - h); - let (v, a) = (s.derivative(t), (s.derivative(t + h) - s.derivative(t - h)) * (0.5 / h)); - let speed = v.len(); - speed > 1e-12 && v.cross(a).abs() * d.abs() >= speed.powi(3) - }) -} - -/// The loop `lp` with each free curve cut into pieces whose offset by up to `d` (either way) -/// [`offset_curve`] fits within a small part of `d`, and the segment of `lp` each piece comes -/// from. Lines and arcs stay whole, and so does a piece bending tighter than `d` -/// ([`tighter_than`]): its true offset folds there, and a piece following it would carry the -/// fold, where one moved piece smooths it over. -pub(crate) fn offset_splits(lp: &Loop2, d: f64) -> (Loop2, Vec) { - let tol = offset_tolerance(d); - let mut segs = Vec::with_capacity(lp.segs.len()); - let mut from = Vec::with_capacity(lp.segs.len()); - for (i, s) in lp.segs.iter().enumerate() { - if s.is_line_or_arc() || d == 0.0 { - segs.push(*s); - from.push(i); - continue; - } - // Spans still to check, the last pushed checked first: the right half goes in first. - let mut todo = vec![(*s, 0u32)]; - while let Some((piece, depth)) = todo.pop() { - let close = |d: f64| offset_error(&piece, d).is_some_and(|e| e <= tol); - if depth < MAX_OFFSET_DEPTH && !tighter_than(&piece, d) && !(close(d) && close(-d)) { - let (left, right) = piece.split_at(0.5); - todo.push((right, depth + 1)); - todo.push((left, depth + 1)); - continue; - } - segs.push(piece); - from.push(i); - } - } - (Loop2 { segs }, from) -} - /// [`offset_loop`] for a loop of lines, arcs and free curves. Each arc keeps its centre and /// angles and its radius moves by `d` (so its side stays an exact cone), each line moves `d` to /// its right, and each free curve moves its control polygon ([`offset_polygon`]). Where two @@ -1059,8 +712,7 @@ fn offset_segments(lp: &Loop2, d: f64) -> Result>> { /// /// Its limit: curves are sampled at [`MEET_SAMPLES`] points, so two that cross twice within one /// sample span (a tight curve against its neighbour) can be missed. The corner then gets the -/// mitre of the end tangents instead, and the loop that makes, if it crosses itself, is refused -/// by [`offset_crosses`] rather than built. +/// mitre of the end tangents instead. fn meet(p: &Seg2, q: &Seg2) -> Option<(f64, f64, Vec2)> { const SAMPLES: usize = MEET_SAMPLES; let samples = |s: &Seg2| -> Vec<(f64, Vec2)> { @@ -1109,7 +761,7 @@ fn with_end(s: &Seg2, x: Vec2) -> Seg2 { Seg2::Conic { a, apex, w, .. } => Seg2::Conic { a, apex, b: x, w }, Seg2::Bezier { n, p } => { let mut q = p; - if let Some(last) = q.get_mut((n as usize).clamp(1, solidcraft_geom::MAX_BEZIER_DEGREE)) { + if let Some(last) = q.get_mut((n as usize).clamp(1, solidcore_record::MAX_BEZIER_DEGREE)) { *last = x; } Seg2::Bezier { n, p: q } @@ -1138,144 +790,12 @@ fn with_start(s: &Seg2, x: Vec2) -> Seg2 { /// Points a free curve is sampled at by [`meet`]. const MEET_SAMPLES: usize = 48; -/// Most pairs of polyline pieces [`offset_crosses`] compares before it gives up. -const CROSSING_BUDGET: usize = 20_000_000; - -/// Whether the offset loops of a region cross themselves or each other, on polylines within -/// `tol` of them: the taper is too steep for the profile's details (a stroke thinner than the -/// taper, a curve tighter than it, two loops it brings together). `None` when there is too -/// much to compare within [`CROSSING_BUDGET`]: then the offset is not known to be sound. -fn offset_crosses(loops: &[Vec>], tol: f64) -> Option { - let lines: Vec> = loops - .iter() - .map(|l| { - let mut pts: Vec = Vec::new(); - for s in l.iter().flatten() { - let p = s.polyline(tol); - pts.extend(p.iter().skip(if pts.is_empty() { 0 } else { 1 })); - } - pts - }) - .collect(); - // Each piece: its loop, its place in the loop, its ends. - let mut pieces: Vec<(usize, usize, usize, Vec2, Vec2)> = Vec::new(); - for (k, pts) in lines.iter().enumerate() { - for (i, (a, b)) in pts.iter().zip(pts.iter().skip(1)).enumerate() { - pieces.push((k, i, pts.len() - 1, *a, *b)); - } - } - pieces.sort_by(|p, q| p.3.x.min(p.4.x).total_cmp(&q.3.x.min(q.4.x))); - let side = |p: Vec2, q: Vec2, r: Vec2| (q - p).cross(r - p); - let mut work = 0usize; - for (n, &(k, i, len, a, b)) in pieces.iter().enumerate() { - let right = a.x.max(b.x); - for &(k2, i2, _, c, d) in pieces.iter().skip(n + 1) { - if c.x.min(d.x) > right { - break; - } - work += 1; - if work > CROSSING_BUDGET { - return None; - } - // Neighbours in one loop share an end. - if k == k2 && (i.abs_diff(i2) <= 1 || i.abs_diff(i2) == len.saturating_sub(1)) { - continue; - } - if a.y.max(b.y) < c.y.min(d.y) || c.y.max(d.y) < a.y.min(b.y) { - continue; - } - let (d1, d2, d3, d4) = (side(c, d, a), side(c, d, b), side(a, b, c), side(a, b, d)); - if d1 * d2 < 0.0 && d3 * d4 < 0.0 { - return Some(true); - } - } - } - Some(false) -} - -/// The side faces of one loop of a tapered extrude through `levels` of it, bottom to top (the -/// loop offset in a plane, one entry per profile segment, `None` where the offset swallowed a -/// line), with the bottom and top wires. Between two levels each side is ruled between a -/// segment's two offsets, through straight edges shared with its neighbours; a line swallowed -/// at one level makes a flat triangle up to where its neighbours meet. `numbers`: the profile -/// segments under each segment. -fn taper_loop(levels: &[(Plane, &[Option])], numbers: impl Fn(usize) -> Vec) -> Result<(Vec, mt::Wire, mt::Wire)> { - let bad = || KernelError::Failed("taper: profile loop".into()); - let n = levels.first().map_or(0, |(_, segs)| segs.len()); - if levels.len() < 2 || levels.iter().any(|(_, segs)| segs.len() != n) { - return Err(bad()); - } - // Each level's vertices (each segment's start: its own, or for a swallowed one the next kept - // one's) and each kept segment's edges. - type Level = (Vec, Vec>>); - let built: Vec = levels - .iter() - .map(|(plane, segs)| { - let own: Vec> = segs.iter().map(|s| s.map(|s| builder::vertex(p3(plane.to_world(s.start()))))).collect(); - let v: Vec = - (0..n).map(|i| (0..n).find_map(|k| own.get((i + k) % n).cloned().flatten()).ok_or_else(bad)).collect::>()?; - let edges = (0..n) - .map(|i| match (segs.get(i).copied().flatten(), v.get(i), v.get((i + 1) % n)) { - (Some(s), Some(a), Some(b)) => seg_edges(plane, &s, a, b).map(Some), - _ => Ok(None), - }) - .collect::>()?; - Ok((v, edges)) - }) - .collect::>()?; - let mut rulings: std::collections::HashMap<(mt::VertexID, mt::VertexID), mt::Edge> = std::collections::HashMap::new(); - let mut ruling = |a: &mt::Vertex, b: &mt::Vertex| rulings.entry((a.id(), b.id())).or_insert_with(|| builder::line(a, b)).clone(); - let flat = |wire: mt::Wire| builder::try_attach_plane(&[wire]).map_err(|e| KernelError::Failed(format!("taper sides: {e}"))); - let mut sides = Vec::new(); - for (((bv, bottom), (tv, top)), (low_segs, high_segs)) in - built.iter().zip(built.iter().skip(1)).zip(levels.iter().map(|(_, s)| s).zip(levels.iter().skip(1).map(|(_, s)| s))) - { - for i in 0..n { - let j = (i + 1) % n; - let (Some(b0), Some(b1), Some(t0), Some(t1)) = (bv.get(i), bv.get(j), tv.get(i), tv.get(j)) else { return Err(bad()) }; - let prov = Some(record::profile(&numbers(i))); - match (bottom.get(i).and_then(Option::as_ref), top.get(i).and_then(Option::as_ref)) { - (Some(low), Some(high)) => { - if low.len() != high.len() { - return Err(bad()); - } - // A line and its moved copy run side by side: their side is a plane, kept - // one (a flat side the booleans meet exactly, however slight the taper). - let lines = matches!( - (low_segs.get(i).copied().flatten(), high_segs.get(i).copied().flatten()), - (Some(Seg2::Line { .. }), Some(Seg2::Line { .. })) - ); - for (e, t) in low.iter().zip(high) { - let wire: mt::Wire = vec![e.clone(), ruling(e.back(), t.back()), t.inverse(), ruling(e.front(), t.front()).inverse()].into(); - if lines { - sides.push((flat(wire)?, prov.clone())); - continue; - } - let surface = mt::BSplineSurface::homotopy(e.oriented_curve().lift_up(), t.oriented_curve().lift_up()); - sides.push((mt::Face::new(vec![wire], mt::Surface::NurbsSurface(mt::NurbsSurface::new(surface))), prov.clone())); - } - } - (Some(low), None) => { - let [e] = &low[..] else { return Err(bad()) }; - sides.push((flat(vec![e.clone(), ruling(e.back(), t1), ruling(e.front(), t0).inverse()].into())?, prov)); - } - (None, Some(high)) => { - let [t] = &high[..] else { return Err(bad()) }; - sides.push((flat(vec![ruling(b1, t.back()), t.inverse(), ruling(b0, t.front()).inverse()].into())?, prov)); - } - (None, None) => {} - } - } - } - let wire = - |level: Option<&Level>| -> mt::Wire { level.map(|(_, edges)| edges.iter().flatten().flatten().cloned().collect()).unwrap_or_default() }; - Ok((sides, wire(built.first()), wire(built.last()))) -} - /// Extrude one region by `length` along `dir_sign` × the plane normal with a taper angle -/// (radians; positive grows the profile). -pub fn extrude_tapered(plane: &Plane, region: &Region2, length: f64, dir_sign: f64, taper: f64) -> Result { - extrude_tapered_between(plane, region, 0.0, length, 0.0, dir_sign, taper) +/// (radians; positive grows the profile), its sharp corners closed by `corner` +/// ([`crate::draft_corners`] says what each rule gives at each corner). +pub fn extrude_tapered(plane: &Plane, region: &Region2, length: f64, dir_sign: f64, taper: f64, corner: DraftCorner) -> Result { + let _span = solidcraft_profile::span("kernel", "extrude_tapered"); + extrude_tapered_between(plane, region, 0.0, length, 0.0, dir_sign, taper, corner) } /// [`extrude_tapered`] from `from` to `to` along `dir_sign` × the plane normal, the region @@ -1284,7 +804,18 @@ pub fn extrude_tapered(plane: &Plane, region: &Region2, length: f64, dir_sign: f /// grown by the taper. With a `foot` (a height, less than `to - from`), the sides stand /// straight for that height above `from` and only then slope, up to the same top: a face the /// solid stands on can then be pushed into the body it joins, as a prism's can. -pub fn extrude_tapered_between(plane: &Plane, region: &Region2, from: f64, to: f64, foot: f64, dir_sign: f64, taper: f64) -> Result { +#[allow(clippy::too_many_arguments)] +pub fn extrude_tapered_between( + plane: &Plane, + region: &Region2, + from: f64, + to: f64, + foot: f64, + dir_sign: f64, + taper: f64, + corner: DraftCorner, +) -> Result { + let _span = solidcraft_profile::span("kernel", "extrude_tapered_between"); let (from, to, foot, taper) = (finite(from, "start")?, finite(to, "distance")?, finite(foot, "foot")?, finite(taper, "taper")?); if to - from <= 1e-6 { return Err(KernelError::Invalid("extrude distance is zero".into())); @@ -1296,533 +827,167 @@ pub fn extrude_tapered_between(plane: &Plane, region: &Region2, from: f64, to: f return Err(KernelError::Invalid("taper must be between −90° and 90°".into())); } region_ok(region)?; - let (t, sign) = (taper.tan(), dir_sign.signum()); - let (bottom_plane, top_plane) = (plane.offset(from * sign), plane.offset(to * sign)); - // A side drawn in collinear pieces slopes as one face over all of them, as a straight - // extrude's does (#1788). - let loops0 = oriented(region)?.map_loops(|l| l.merged_lines(continues_straight)); - let split: Vec<(Loop2, Vec)> = loops0.loops().map(|l| offset_splits(&l.lp, from.abs().max(to.abs()) * t)).collect(); - let ends = |h: f64| split.iter().map(|(lp, _)| offset_loop(lp, h * t)).collect::>>(); - let (bottoms, tops) = (ends(from)?, ends(to)?); - // Polylines within a small part of the larger offset of it. - let tol = (from.abs().max(to.abs()) * t.abs() * 0.02).max(1e-6); - if t != 0.0 { - match (offset_crosses(&bottoms, tol), offset_crosses(&tops, tol)) { - (Some(false), Some(false)) => {} - (Some(true), _) | (_, Some(true)) => { - return Err(KernelError::Invalid( - "the taper closes the profile: at this distance its sides would cross (a stroke, a curve or a gap narrower than the taper); try a smaller taper or distance".into(), - )); - } - _ => { - return Err(KernelError::TooLarge( - "the tapered profile has too many details to check that its sides stay apart; taper fewer profiles at a time".into(), - )); - } - } - } - guard("tapered extrude", || { - let mut sides: Vec = Vec::new(); - let (mut w0, mut w1): (Vec, Vec) = (Vec::new(), Vec::new()); - for (((l, (_, origin)), b), t) in loops0.loops().zip(&split).zip(&bottoms).zip(&tops) { - let mut levels = vec![(bottom_plane, &b[..])]; - if foot > 0.0 { - levels.push((plane.offset((from + foot) * sign), &b[..])); - } - levels.push((top_plane, &t[..])); - let (s, below, above) = taper_loop(&levels, |i| origin.get(i).map(|&k| l.numbers(k).to_vec()).unwrap_or_default())?; - sides.extend(s); - w0.push(below); - w1.push(above); - } - let (faces, prov): (Vec, Vec>) = sides.into_iter().unzip(); - // The sides, then the bottom and top as pushed below. - let history: Option> = prov.into_iter().chain([Some(record::cap(false)), Some(record::cap(true))]).collect(); - let bottom = builder::try_attach_plane(&w0.iter().map(|w| w.inverse()).collect::>()) - .map_err(|e| KernelError::Failed(format!("taper bottom: {e}")))?; - let top = builder::try_attach_plane(&w1).map_err(|e| KernelError::Failed(format!("taper top: {e}")))?; - let mut tries: Vec<(mt::Face, mt::Face)> = vec![(bottom.clone(), top.clone())]; - tries.push((bottom.inverse(), top.inverse())); - let mut last = String::new(); - for (b, t) in tries { - let mut all = faces.clone(); - all.push(b); - all.push(t); - let shell: mt::Shell = all.into(); - match Solid::try_new(vec![shell]) { - Ok(s) => return record::attach(Body::new(s)?, &[], history, Default::default()), - Err(e) => last = e.to_string(), - } - } - Err(KernelError::Failed(format!("tapered extrude: {last}"))) - }) + smlib_tapered(plane, region, from, to, foot, dir_sign.signum(), taper, corner) } -/// Revolve 360° a loop that has exactly one line segment on the axis, without degenerate faces. -/// A loop made of a half circle and its diameter on the axis: (centre, radius). -fn half_disc(lp: &Loop2, axis_origin: Vec2, d: Vec2) -> Option<(Vec2, f64)> { - let on_axis = |p: Vec2| d.cross(p - axis_origin).abs() < 1e-7 * (1.0 + p.len()); - let mut arcs = Vec::new(); - for s in &lp.segs { - match *s { - Seg2::Line { a, b } if on_axis(a) && on_axis(b) => {} - Seg2::Arc { center, radius, sweep, .. } if on_axis(center) => arcs.push((center, radius, sweep)), - _ => return None, +/// [`extrude_tapered_between`] through SMLib's draft extrusion, its section at `from` the +/// profile offset by the taper, after any straight foot. SMLib's draft extrusion takes one loop: +/// a region with holes is its outer loop drafted, less each hole drafted the other way (every +/// wall leaning by the taper on the material's side), refused only where the taper would make a +/// hole meet the outer wall or another hole within the extrusion. +#[allow(clippy::too_many_arguments)] +fn smlib_tapered(plane: &Plane, region: &Region2, from: f64, to: f64, foot: f64, sign: f64, taper: f64, corner: DraftCorner) -> Result { + let joined = oriented(region)?.map_loops(|l| l.merged_lines(continues_straight)); + // A loop's section `at` along the extrusion: counter-clockwise, grown by `taper` (a hole's + // the other way, as the wall of the material round it leans). + let section = |l: &NumberedLoop, at: f64, taper: f64| -> Result { + let ccw = l.oriented(false); + if at == 0.0 || taper == 0.0 { + return Ok(ccw); } + let segs: Option> = offset_loop(&ccw.lp, at * taper.tan())?.into_iter().collect(); + let segs = segs.ok_or_else(|| crate::smlib_sweeps::refuse("draft extrusion that starts before its profile where the taper closes a side"))?; + Ok(NumberedLoop { lp: Loop2 { segs }, from: ccw.from }) + }; + let outer = section(&joined.outer, from, taper)?; + let draft = (taper != 0.0).then_some(crate::smlib_sweeps::Draft { taper, foot, corner }); + if joined.holes.is_empty() { + return crate::smlib_sweeps::extrude(plane, &crate::smlib_sweeps::pieces([&outer]), Some(region), from * sign, to - from, sign, draft); } - let (c, r, _) = *arcs.first()?; - let total: f64 = arcs.iter().map(|a| a.2.abs()).sum(); - let same = arcs.iter().all(|(c2, r2, _)| c2.dist(c) < 1e-7 * (1.0 + r) && (r2 - r).abs() < 1e-7 * (1.0 + r)); - (same && (total - std::f64::consts::PI).abs() < 1e-6).then_some((c, r)) -} - -/// A full turn of a loop with edges on the axis, built without the zero-area faces truck sweeps -/// from them (booleans can't handle those). `None` when no builder here takes the loop. -fn full_turn_on_axis(plane: &Plane, nl: &NumberedLoop, axis_origin: Vec2, d: Vec2, angle: f64) -> Result> { - let lp = &nl.lp; - // A half disc on the axis revolved fully is a sphere: build it without poles. Every - // patch is swept from the half disc's arcs. - if let Some((c, rad)) = half_disc(lp, axis_origin, d) { - let arcs: Vec = - lp.segs.iter().enumerate().filter(|(_, s)| matches!(s, Seg2::Arc { .. })).flat_map(|(i, _)| nl.numbers(i).to_vec()).collect(); - return sphere_solid(plane.to_world(c), rad, [Vec3::X, Vec3::Y, Vec3::Z], &arcs).map(Some); - } - // A full turn of a profile that comes back to the axis along a curve (a half slot about - // its centreline, a dome at the far end): truck's cone gives the faces - // swept from it the wrong region (their pole is at the end of their curve), and cuts with - // such a body failed (#1853). It is built as part turns are, a third of a turn at a time. - if pole_at_end(lp, axis_origin, d) - && let Some(b) = revolve_on_axis(plane, nl, axis_origin, d, angle)? - { - return Ok(Some(b)); - } - // A full revolution of a profile with one edge on the axis: sweep the rest of the loop - // as a cone-like shell (no zero-area faces, which booleans can't handle). - if let Some(b) = revolve_touching_axis(plane, nl, axis_origin, d)? { - return Ok(Some(b)); - } - // Several edges on the axis (a spherical shell's two radial lines): each run of the loop - // from the axis back to it, closed along the axis, turns into a shell of its own, a solid - // where it runs the way the loop does and a void where it runs the other way. Swept whole, - // the edges on the axis became zero-area faces joining the shells, and a cut through a pole - // there failed (#451). - let on_axis = |s: &Seg2| matches!(*s, Seg2::Line { a, b } if d.cross(a - axis_origin).abs() < 1e-9 && d.cross(b - axis_origin).abs() < 1e-9); - let n = lp.segs.len(); - let axis_segs: Vec = (0..n).filter(|i| lp.segs.get(*i).is_some_and(on_axis)).collect(); - let [k0, _, ..] = axis_segs[..] else { return Ok(None) }; - let mut parts = Vec::new(); - for (i, &k) in axis_segs.iter().enumerate() { - let run: Vec = (k + 1..axis_segs.get(i + 1).copied().unwrap_or(k0 + n)).map(|j| j % n).collect(); - let mut segs: Vec = run.iter().filter_map(|j| lp.segs.get(*j).copied()).collect(); - let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Ok(None) }; - segs.push(Seg2::Line { a: last.end(), b: first.start() }); - let sub = NumberedLoop { lp: Loop2 { segs }, from: run.iter().map(|j| nl.numbers(*j).to_vec()).chain([Vec::new()]).collect() }; - let void = sub.lp.is_ccw() != lp.is_ccw(); - let Some(b) = full_turn_on_axis(plane, &if void { sub.reversed() } else { sub }, axis_origin, d, angle)? else { return Ok(None) }; - parts.push((b, void)); - } - let faces: Option> = - parts.iter().map(|(b, _)| b.history().map(|h| h.faces.clone())).collect::>>().map(|f| f.concat()); - let solid = guard("revolve", || { - let mut shells = Vec::new(); - for (b, void) in &parts { - let mut s = b.solid.as_ref().clone(); - if *void { - s.not(); + let Some(draft) = draft else { + return Err(KernelError::Invalid("a tapered extrusion needs a taper".into())); + }; + let holes: Vec = joined.holes.iter().map(|h| section(h, from, -taper)).collect::>()?; + // A loop's section `at` as it is there: a line the offset swallows is gone, its neighbours + // meeting where it was (its wall closes on the way; whether that wall is built is the + // draft's to say). + let shape = |l: &NumberedLoop, at: f64, taper: f64| -> Result { + let ccw = l.oriented(false); + if at == 0.0 || taper == 0.0 { + return Ok(ccw); + } + let segs: Vec = offset_loop(&ccw.lp, at * taper.tan())?.into_iter().flatten().collect(); + Ok(NumberedLoop { lp: Loop2 { segs }, from: ccw.from }) + }; + // The sections where the walls are farthest moved, the two ends: each hole stays inside the + // outer loop and clear of the other holes there (the walls are planes, cones and their like, + // which move monotonically in between). + for at in [from, to] { + let o = shape(&joined.outer, at, taper)?; + let hs: Vec = joined.holes.iter().map(|h| shape(h, at, -taper)).collect::>()?; + let pts = |l: &NumberedLoop| l.lp.segs.iter().flat_map(|s| s.polyline(1e-3)).collect::>(); + // Apart: no point of either inside the other. + let apart = |a: &NumberedLoop, b: &NumberedLoop| !pts(a).iter().any(|p| b.lp.contains(*p)) && !pts(b).iter().any(|p| a.lp.contains(*p)); + for (i, h) in hs.iter().enumerate() { + let inside = pts(h).iter().all(|p| o.lp.contains(*p)) && !pts(&o).iter().any(|p| h.lp.contains(*p)); + if !inside || hs.iter().skip(i + 1).any(|k| !apart(h, k)) { + return Err(KernelError::Invalid("the draft makes a hole meet the outer wall or another hole".into())); } - shells.extend(s.boundaries().iter().cloned()); - } - Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("revolve: {e}"))) - })?; - record::attach(Body::new(solid)?, &[], faces, Default::default()).map(Some) -} - -/// Whether the loop has one edge on the axis and comes back to it along a curve (the segment -/// before the axis edge is not a line). A line there (a drill point) sweeps a cone, which -/// truck's cone builds right. -fn pole_at_end(lp: &Loop2, axis_origin: Vec2, d: Vec2) -> bool { - let on_axis = |p: Vec2| d.cross(p - axis_origin).abs() < 1e-9; - let n = lp.segs.len(); - let axis_segs: Vec = - (0..n).filter(|i| lp.segs.get(*i).is_some_and(|s| matches!(s, Seg2::Line { a, b } if on_axis(*a) && on_axis(*b)))).collect(); - let [k] = axis_segs[..] else { return false }; - lp.segs.get((k + n - 1) % n).is_some_and(|s| !on_axis(s.start()) && !matches!(s, Seg2::Line { .. })) -} - -/// The edge from `a` to `b` along the profile segment `sg` (in `plane`), for a revolve's sweep. -/// One that ends on the axis (`ends_on_axis`) is built from there and turned round, so that the -/// surface swept from its curve has its pole at the curve's start. truck's revolved surface -/// reads a point on its axis at the start of its curve with the angle of the point before it, -/// but one at the end with an angle of 2π when it has no hint, past a part turn's span: the face -/// came out as another region (#1853). -fn swept_edge(plane: &Plane, sg: &Seg2, a: &mt::Vertex, b: &mt::Vertex, ends_on_axis: bool) -> mt::Edge { - if ends_on_axis { - return swept_edge(plane, &sg.reversed(), b, a, false).inverse(); - } - match *sg { - Seg2::Line { .. } => builder::line(a, b), - Seg2::Arc { .. } => builder::circle_arc(a, b, p3(plane.to_world(sg.mid()))), - Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => { - crate::freeform::edge(plane, sg, a, b).unwrap_or_else(|| builder::line(a, b)) } } + let all: Vec = std::iter::once(outer.clone()).chain(holes.iter().map(|h| h.oriented(true))).collect(); + crate::smlib_sweeps::extrude_drafted_with_holes( + plane, + &crate::smlib_sweeps::pieces([&outer]), + &holes.iter().map(|h| crate::smlib_sweeps::pieces([h])).collect::>(), + &crate::smlib_sweeps::pieces(all.iter()), + from * sign, + to - from, + sign, + draft, + ) } -/// Where [`revolve_on_axis`]'s full turns start, from the profile: an angle no plane a part is -/// commonly cut along lies at (as full circles start, see `reseam`). -const FULL_TURN_START: f64 = 0.4142; - -/// A revolve of a loop with one edge on the axis: the other edges sweep their faces, a third of a -/// turn at most each. A partial turn is closed by two caps (the profile at the start and at the -/// end), which share the axis edge; a full turn ends where it started. `None` when the loop -/// isn't like that. -fn revolve_on_axis(plane: &Plane, numbered: &NumberedLoop, axis_origin: Vec2, d: Vec2, angle: f64) -> Result> { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchNearestParameter, Transformed}; - let lp = &numbered.lp; - let on_axis = |p: Vec2| d.cross(p - axis_origin).abs() < 1e-9; - let n = lp.segs.len(); - let axis_segs: Vec = - (0..n).filter(|i| lp.segs.get(*i).is_some_and(|s| matches!(s, Seg2::Line { a, b } if on_axis(*a) && on_axis(*b)))).collect(); - let [k] = axis_segs[..] else { return Ok(None) }; - // The open chain after the axis segment, back around to it: only its ends on the axis. - let chain: Vec = (1..n).filter_map(|j| lp.segs.get((k + j) % n).copied()).collect(); - if chain.is_empty() || chain.iter().skip(1).any(|s| on_axis(s.start())) || chain.iter().any(|s| on_axis(s.mid())) { - return Ok(None); +/// A planar region on `plane` as the schema 4 record of one face (an open sheet): the plane's +/// own axes as its parameters (its natural normal the sketch's), the outer loop +/// counter-clockwise and the holes clockwise, each sketch segment one edge of its exact record +/// curve ([`crate::point_path::sketch_record_curve`]) with its exact pcurve on the plane. The record +/// equivalent of a profile face: SMLib takes it with `Brep::from_record`. +pub fn planar_face_record(plane: &Plane, r: &Region2) -> Result { + use solidcore_record::brep::{self as rec}; + use solidcraft_geom::brep::pcurve; + if !frame_ok(plane) { + return Err(KernelError::Invalid("the face's plane is not finite and orthonormal".into())); } - let full = angle.abs() >= std::f64::consts::TAU - 1e-9; - // Faces of a third of a turn at most, as truck sweeps a full turn: a boolean could not - // intersect a half turn's faces and the half circles bounding them (a half slot turned half a - // turn into a plate, #1853), and a sphere's face needs room for its poles (below). - let pieces = (angle.abs() / (std::f64::consts::TAU / 3.0) - 1e-9).ceil().max(1.0) as usize; - let step = angle / pieces as f64; - // Built with the axis through the world origin, then moved into place. - let shift = plane.to_world(axis_origin); - let local = Plane { origin: plane.origin - shift, ..*plane }; - let plane = &local; - let axis = plane.dir_to_world(d); - let turned = |by: f64| mt::Matrix4::from_axis_angle(v3(axis), mt::Rad(by)); - let turn = |m: &mt::Matrix4, p: Vec3| from_p3(mt::EuclideanSpace::from_vec((m * p3(p).to_homogeneous()).truncate())); - guard("revolve", || { - let fail = |m: &str| KernelError::Failed(format!("revolve: {m}")); - let pts: Vec = chain.iter().map(|s| plane.to_world(s.start())).chain(chain.last().map(|s| plane.to_world(s.end()))).collect(); - let last = pts.len() - 1; - let pv: Vec = pts.iter().map(|p| builder::vertex(p3(*p))).collect(); - let mut e: Vec = Vec::new(); - for (i, sg) in chain.iter().enumerate() { - let (Some(a), Some(b)) = (pv.get(i), pv.get(i + 1)) else { return Err(fail("chain")) }; - e.push(swept_edge(plane, sg, a, b, on_axis(sg.end()))); - } - // The profile's vertices and edges where each piece starts and ends: turned by the step, - // the ends staying where they are (on the axis). A part turn starts on the profile. A full - // turn starts at an odd angle and ends where it started: the profile lies in the plane - // it was drawn on, often a face of the body cut, and a seam lying in that face as well - // left the cut nothing it could intersect there (#1853). - let start = if full { FULL_TURN_START } else { 0.0 }; - let mut levels: Vec<(Vec, Vec)> = Vec::new(); - for j in 0..=pieces { - if j == 0 && !full { - levels.push((pv.clone(), e.clone())); - continue; - } - if let (true, Some(first)) = (j == pieces && full, levels.first()) { - levels.push(first.clone()); - continue; - } - let rot = turned(start + step * j as f64); - let qv: Vec = pts - .iter() - .enumerate() - .map(|(i, p)| { - if i == 0 || i == last { - pv.get(i).cloned().unwrap_or_else(|| builder::vertex(p3(*p))) - } else { - builder::vertex(p3(turn(&rot, *p))) + region_ok(r)?; + let region = oriented(r)?; + let tolerance = 1e-7; + let d = |v: Vec3| [v.x, v.y, v.z]; + let surface = rec::Surface::Plane { origin: d(plane.origin), u_axis: d(plane.x), v_axis: d(plane.y) }; + let bad = |what: &str| KernelError::Invalid(format!("profile {what}")); + // Edges and vertices numbered as the face's loops first meet them. + let mut edges: Vec = Vec::new(); + let mut vertices: Vec = Vec::new(); + let mut loops: Vec> = Vec::new(); + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for (li, l) in region.loops().enumerate() { + let segs = &l.lp.segs; + let first = u32::try_from(vertices.len()).map_err(|_| bad("size"))?; + let mut ids = Vec::with_capacity(segs.len()); + for (k, s) in segs.iter().enumerate() { + let (curve, interval) = crate::point_path::sketch_record_curve(plane, s).ok_or_else(|| bad("curve"))?; + let start = u32::try_from(vertices.len()).map_err(|_| bad("size"))?; + vertices.push(rec::Vertex { point: d(plane.to_world(s.start())), tolerance }); + let end = if k + 1 == segs.len() { first } else { start + 1 }; + let e = u32::try_from(edges.len()).map_err(|_| bad("size"))?; + let (li, k) = (u32::try_from(li).map_err(|_| bad("size"))?, u32::try_from(k).map_err(|_| bad("size"))?); + edges.push(rec::Edge { + nurbs: None, + curve, + interval, + vertices: [start, end], + tolerance, + uses: vec![rec::EdgeUseRef { face: 0, r#loop: li, position: k, upper: false }], + }); + ids.push(e); + for q in s.polyline(tolerance) { + for (i, x) in [q.x, q.y].into_iter().enumerate() { + if let (Some(a), Some(b)) = (lo.get_mut(i), hi.get_mut(i)) { + *a = a.min(x); + *b = b.max(x); } + } + } + } + loops.push(ids); + } + let uses: Vec>> = loops + .iter() + .map(|ids| { + ids.iter() + .filter_map(|&e| { + let edge = edges.get(e as usize)?; + Some(pcurve::EdgeUse { edge: e, curve: edge.parameters(), interval: edge.interval, forward: true, tolerance, given: None }) }) - .collect(); - let mut er: Vec = Vec::new(); - for (i, edge) in e.iter().enumerate() { - let (Some(qa), Some(qb)) = (qv.get(i), qv.get(i + 1)) else { return Err(fail("chain")) }; - let curve = edge.curve().transformed(rot); - er.push(if edge.orientation() { mt::Edge::new(qa, qb, curve) } else { mt::Edge::new(qb, qa, curve).inverse() }); - } - levels.push((qv, er)); - } - // Side faces: each edge's swept surface, oriented to agree with its boundary, from the - // profile segment the edge was built from. - let mut faces: Vec<(mt::Face, FaceProv)> = Vec::new(); - for (j, piece) in levels.windows(2).enumerate() { - let [(pv, e), (qv, er)] = piece else { return Err(fail("pieces")) }; - let half = turned(start + step * (j as f64 + 0.5)); - // Arcs swept by the vertices off the axis. - let mut arcs: Vec> = vec![None; pts.len()]; - for i in 1..last { - let (Some(a), Some(b), Some(p)) = (pv.get(i), qv.get(i), pts.get(i)) else { continue }; - if let Some(slot) = arcs.get_mut(i) { - *slot = Some(builder::circle_arc(a, b, p3(turn(&half, *p)))); - } - } - for (i, sg) in chain.iter().enumerate() { - let (Some(ei), Some(eri)) = (e.get(i), er.get(i)) else { return Err(fail("edges")) }; - let mut ws: Vec = vec![ei.clone()]; - if let Some(Some(c)) = arcs.get(i + 1) { - ws.push(c.clone()); - } - ws.push(eri.inverse()); - if let Some(Some(c)) = arcs.get(i) { - ws.push(c.inverse()); - } - let wire: mt::Wire = ws.into(); - let radial = matches!(*sg, Seg2::Line { a, b } if (b - a).normalized().is_some_and(|u| u.dot(d).abs() < 1e-9)); - let f = if radial { - builder::try_attach_plane(&[wire]).map_err(|er| fail(&er.to_string()))? - } else { - // The surface turns from the piece's start through |step|, so its angle runs - // from 0 across the face. Inverting it turns its axis round, which puts the - // face at 2π - |step| to 2π: its start then lies on the angle's seam, where - // points (and a pole without a hint) read as 0, the far side, and the face - // meshed and intersected as the wrong region (#1853). The face is turned - // round instead. - let (dir, by) = if step < 0.0 { (-axis, -step) } else { (axis, step) }; - let surface = match *sg { - // An arc about a centre on the axis that reaches it sweeps part of a sphere - // with its pole there, and a boolean can't follow an intersection into a - // pole: a cut by the plane through the axis (the face the profile was drawn - // on) failed (#1853). The face lies on the sphere turned about the axis - // square to the revolve's and to the face's middle, as `sphere_solid`'s - // patches do: its poles are a quarter turn from that middle, past the - // face's third of a turn, and its seam runs round the back. - Seg2::Arc { center, radius, .. } if on_axis(center) && (on_axis(sg.start()) || on_axis(sg.end())) => { - let c = plane.to_world(center); - let out = turn(&half, plane.to_world(sg.mid())) - c; - let out = (out - axis * out.dot(axis)).normalized().ok_or_else(|| fail("sphere"))?; - let pole = axis.cross(out); - let meridian = builder::circle_arc( - &builder::vertex(p3(c + pole * radius)), - &builder::vertex(p3(c - pole * radius)), - p3(c - out * radius), - ); - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution( - meridian.oriented_curve(), - p3(c), - v3(pole), - ))) - } - _ => { - let template = builder::rsweep(ei, mt::Point3::new(0.0, 0.0, 0.0), v3(dir), mt::Rad(by)); - template.face_iter().next().map(|f| f.surface()).ok_or_else(|| fail("swept face"))? - } - }; - // The loop's turning (Newell) against the surface normal halfway round. - let poly: Ring = wire - .edge_iter() - .flat_map(|ed| { - let c = ed.oriented_curve(); - let (t0, t1) = c.range_tuple(); - (0..8).map(move |j| from_p3(c.subs(t0 + (t1 - t0) * j as f64 / 8.0))).collect::>() - }) - .collect(); - let nw = poly.area_vector(); - let probe = turn(&half, plane.to_world(sg.mid())); - let sn = surface.search_nearest_parameter(p3(probe), None, 100).map(|(u, v)| surface.normal(u, v)); - if sn.is_some_and(|m| nw.dot(Vec3::new(m.x, m.y, m.z)) < 0.0) { - mt::Face::try_new(vec![wire.inverse()], surface).map_err(|er| fail(&er.to_string()))?.inverse() - } else { - mt::Face::try_new(vec![wire], surface).map_err(|er| fail(&er.to_string()))? - } - }; - faces.push((f, record::profile(numbered.numbers((k + 1 + i) % n)))); - } - } - let (faces, mut history): (Vec, Vec) = faces.into_iter().unzip(); - let close = |solid: Solid, history: Vec| { - let solid = if shift.len() > 0.0 { builder::translated(&solid, v3(shift)) } else { solid }; - record::attach(Body::new(solid)?, &[], Some(history), Default::default()).map(Some) - }; - if full { - return close(Solid::try_new(vec![faces.into()]).map_err(|er| fail(&er.to_string()))?, history); - } - // Caps: the profile at the start and at the end, sharing the axis edge. - let ((Some(a0), Some(an)), Some((_, er))) = ((pv.first(), pv.get(last)), levels.last()) else { return Err(fail("ends")) }; - let axis_edge = builder::line(an, a0); - let start: mt::Wire = e.iter().rev().map(|x| x.inverse()).chain(std::iter::once(axis_edge.inverse())).collect::>().into(); - let end: mt::Wire = er.iter().cloned().chain(std::iter::once(axis_edge.clone())).collect::>().into(); - let cs = builder::try_attach_plane(&[start]).map_err(|er| fail(&er.to_string()))?; - let ce = builder::try_attach_plane(&[end]).map_err(|er| fail(&er.to_string()))?; - history.extend([record::cap(false), record::cap(true)]); - let mut last_err = String::new(); - for flip in 0..4 { - let mut all = faces.clone(); - all.push(if flip & 1 == 0 { cs.clone() } else { cs.inverse() }); - all.push(if flip & 2 == 0 { ce.clone() } else { ce.inverse() }); - match Solid::try_new(vec![all.into()]) { - Ok(solid) => return close(solid, history), - Err(er) => last_err = er.to_string(), - } - } - Err(fail(&last_err)) - }) -} - -fn revolve_touching_axis(plane: &Plane, numbered: &NumberedLoop, axis_origin: Vec2, d: Vec2) -> Result> { - let lp = &numbered.lp; - let on_axis = |p: Vec2| d.cross(p - axis_origin).abs() < 1e-9; - let n = lp.segs.len(); - let axis_segs: Vec = - (0..n).filter(|i| lp.segs.get(*i).is_some_and(|s| matches!(s, Seg2::Line { a, b } if on_axis(*a) && on_axis(*b)))).collect(); - let [k] = axis_segs[..] else { return Ok(None) }; - // The open chain after the axis segment, back around to it, with the profile segments - // under each piece. - let mut chain: Vec = (1..n).filter_map(|j| lp.segs.get((k + j) % n).copied()).collect(); - let mut chain_src: Vec<&[usize]> = (1..n).map(|j| numbered.numbers((k + j) % n)).collect(); - // A single arc (a sphere) is split off-centre: a seam on the equator would lie in the very - // planes other bodies are often cut with. - if let [Seg2::Arc { center, radius, start, sweep }] = chain[..] { - let f = 0.37; - chain = vec![ - Seg2::Arc { center, radius, start, sweep: sweep * f }, - Seg2::Arc { center, radius, start: start + sweep * f, sweep: sweep * (1.0 - f) }, - ]; - chain_src = vec![numbered.numbers((k + 1) % n); 2]; - } - if chain.is_empty() || chain.iter().skip(1).take(chain.len().saturating_sub(2)).any(|s| on_axis(s.start()) && on_axis(s.end())) { - return Ok(None); - } - // Built with the axis through the world origin (truck tessellates such cones reliably), then - // moved into place. - let shift = plane.to_world(axis_origin); - let local = Plane { origin: plane.origin - shift, ..*plane }; - let plane = &local; - // Radial lines at the ends become planar caps (no degenerate disc centres). - let radial = |sg: &Seg2| matches!(*sg, Seg2::Line { a, b } if (b - a).normalized().is_some_and(|u| u.dot(d).abs() < 1e-9)); - let mut mid: &[Seg2] = &chain; - let mut mid_src: &[&[usize]] = &chain_src; - // The segments of the radial lines that become caps. - let (mut start_cap, mut end_cap) = (None, None); - if mid.first().is_some_and(|f| radial(f) && on_axis(f.start())) { - mid = mid.get(1..).unwrap_or(&[]); - start_cap = mid_src.first().copied(); - mid_src = mid_src.get(1..).unwrap_or(&[]); - } - if mid.last().is_some_and(|l| radial(l) && on_axis(l.end())) { - mid = mid.get(..mid.len().saturating_sub(1)).unwrap_or(&[]); - end_cap = mid_src.last().copied(); - mid_src = mid_src.get(..mid_src.len().saturating_sub(1)).unwrap_or(&[]); - } - if mid.is_empty() { - return Ok(None); - } - let apex_start = mid.first().is_some_and(|f| on_axis(f.start())); - let apex_end = mid.last().is_some_and(|l| on_axis(l.end())); - guard("revolve", || { - let verts: Vec = mid - .iter() - .map(|s| builder::vertex(p3(plane.to_world(s.start())))) - .chain(mid.last().map(|s| builder::vertex(p3(plane.to_world(s.end()))))) - .collect(); - let mut edges: Vec = Vec::new(); - for (i, s) in mid.iter().enumerate() { - let (Some(a), Some(b)) = (verts.get(i), verts.get(i + 1)) else { continue }; - edges.push(match *s { - Seg2::Line { .. } => builder::line(a, b), - Seg2::Arc { .. } => builder::circle_arc(a, b, p3(plane.to_world(s.mid()))), - Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => match crate::freeform::edge(plane, s, a, b) { - Some(e) => e, - None => builder::line(a, b), - }, - }); - } - // Each edge with the profile segments under it, before the wire may be turned round. - let seeds: Vec<(mt::EdgeID, Vec)> = edges.iter().map(|e| e.id()).zip(mid_src.iter().map(|s| s.to_vec())).collect(); - let mut w: mt::Wire = edges.into(); - let axis = plane.dir_to_world(d); - let mut shell = if apex_start || apex_end { - if !apex_start { - // builder::cone wants the apex first. - w = w.inverse(); - } - builder::cone(&w, v3(axis), mt::Rad(std::f64::consts::TAU)) - } else { - builder::rsweep(&w, p3(plane.to_world(axis_origin)), v3(axis), mt::Rad(std::f64::consts::TAU)) - }; - let sides = shell.len(); - // History. truck sweeps each wire edge round into a column of faces (triangles at an - // apex, which stays put); each cap is the disc a trimmed radial line sweeps, found by - // the profile vertex on its rim. - let fixed: Vec = - [(apex_start, verts.first()), (apex_end, verts.last())].into_iter().filter_map(|(apex, v)| v.filter(|_| apex).map(|v| v.id())).collect(); - let mut history: Option> = (seeds.len() == mid.len()) - .then(|| record::columns(shell.face_iter(), &seeds, None, record::Column::ToEnd, &fixed)) - .flatten() - .and_then(|sides| sides.into_iter().collect()); - let (first_vertex, last_vertex) = (verts.first().map(|v| v.id()), verts.last().map(|v| v.id())); - for b in shell.extract_boundaries() { - let at = |v: Option| v.is_some_and(|v| b.vertex_iter().any(|x| x.id() == v)); - let src = if at(first_vertex) { - start_cap - } else if at(last_vertex) { - end_cap - } else { - None - }; - history = history.zip(src).map(|(mut h, numbers)| { - h.push(record::profile(numbers)); - h - }); - let cap = builder::try_attach_plane(&[b]).map_err(|e| KernelError::Failed(format!("revolve cap: {e}")))?; - shell.push(cap); - } - let solid = Solid::try_new(vec![shell.clone()]).or_else(|_| { - // Caps may come out facing inwards: flip them. - let mut s2 = shell.clone(); - for f in s2.face_iter_mut().skip(sides) { - f.invert(); - } - Solid::try_new(vec![s2]) - }); - let solid = solid.map_err(|e| KernelError::Failed(format!("revolve: {e}")))?; - let solid = if shift.len() > 0.0 { builder::translated(&solid, v3(shift)) } else { solid }; - record::attach(Body::new(solid)?, &[], history, Default::default()).map(Some) - }) -} - -/// Close a ruled shell (side faces between matching wires, with their provenance as built) -/// with planar caps into a body, whose history is the sides' and the caps': the profile at -/// `w0` is the start cap and at `w1` the end cap (the other way round when `from_end`). -pub(crate) fn cap_and_close(sides: Vec, w0: &[mt::Wire], w1: &[mt::Wire], from_end: bool) -> Result { - let (mut faces, prov): (Vec, Vec>) = sides.into_iter().unzip(); - let history: Option> = prov.into_iter().chain([Some(record::cap(from_end)), Some(record::cap(!from_end))]).collect(); - let bottom = - builder::try_attach_plane(&w0.iter().map(|w| w.inverse()).collect::>()).map_err(|e| KernelError::Failed(format!("cap: {e}")))?; - let top = builder::try_attach_plane(w1).map_err(|e| KernelError::Failed(format!("cap: {e}")))?; - let mut last = String::new(); - for (b, t) in [(bottom.clone(), top.clone()), (bottom.inverse(), top.inverse()), (bottom.clone(), top.inverse()), (bottom.inverse(), top)] { - let mut all = std::mem::take(&mut faces); - let keep = all.clone(); - all.push(b); - all.push(t); - let shell: mt::Shell = all.into(); - match Solid::try_new(vec![shell]) { - Ok(s) => return record::attach(Body::new(s)?, &[], history, Default::default()), - Err(e) => last = e.to_string(), - } - faces = keep; - } - Err(KernelError::Failed(format!("closing the shell: {last}"))) -} - -/// A sweep whose walls already close, including separate shells around profile holes. -pub(crate) fn close_sweep(sides: Vec) -> Result { - let sources: std::collections::HashMap<_, _> = sides.iter().map(|(f, p)| (f.id(), p.clone())).collect(); - let shell: mt::Shell = sides.into_iter().map(|(f, _)| f).collect(); - let solid = Solid::try_new(shell.connected_components()).map_err(|e| KernelError::Failed(format!("closing the sweep: {e}")))?; - let history = solid.face_iter().map(|f| sources.get(&f.id()).cloned().flatten()).collect(); - record::attach(Body::new(solid)?, &[], history, Default::default()) + .collect() + }) + .collect(); + let pcurves = pcurve::pcurves(&surface, &uses, tolerance).map_err(|e| KernelError::Failed(format!("profile pcurves: {e}")))?; + let face_loops = loops + .iter() + .zip(pcurves) + .map(|(ids, pcs)| rec::Loop::Edges { + edges: ids.iter().zip(pcs).map(|(&edge, pcurve)| rec::OrientedEdge { edge, forward: true, pcurve }).collect(), + }) + .collect(); + let pad = tolerance * 10.0; + let brep = rec::Brep { + version: rec::VERSION, + tolerance, + regions: vec![rec::Region { shells: vec![0], void: false }], + shells: vec![rec::Shell::Faces { faces: vec![rec::OrientedFace { face: 0, forward: true }], wires: vec![] }], + faces: vec![rec::Face { nurbs: None, surface, domain: [[lo[0] - pad, hi[0] + pad], [lo[1] - pad, hi[1] + pad]], loops: face_loops }], + edges, + vertices, + }; + solidcraft_geom::brep::check::validate(&brep).map_err(|e| KernelError::Failed(format!("profile face: {e}")))?; + Ok(brep) } /// Ruled loft through two or more planar sections (outer loops only). The sections and the /// same sections in reverse order give the same body. pub fn loft(sections: &[(Plane, Loop2)]) -> Result { + let _span = solidcraft_profile::span("kernel", "loft"); loft_with_rails(sections, &[], RailFit::Scale) } @@ -1830,29 +995,16 @@ pub fn loft(sections: &[(Plane, Loop2)]) -> Result { /// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the /// sections between. Without rails, the plain loft. pub fn loft_with_rails(sections: &[(Plane, Loop2)], rails: &[Vec], fit: RailFit) -> Result { - let (wires, edge_sources, reversed) = loft_wires(sections)?; - let (Some(first), Some(last)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("loft: sections".into())) }; - let mut planes: Vec = sections.iter().map(|(p, _)| *p).collect(); - if reversed { - planes.reverse(); + let _span = solidcraft_profile::span("kernel", "loft_with_rails"); + let reversed = loft_reversed(sections)?; + let numbered = sections.iter().map(|(p, _)| *p).zip(numbered::number_loops(sections.iter().map(|(_, l)| l))).collect::>(); + let loops = loft_numbered_loops(&numbered, reversed)?; + let first = if reversed { loops.len().saturating_sub(1) } else { 0 }; + let pieces: Vec<(Plane, Vec)> = loops.iter().map(|(p, l)| (*p, crate::smlib_sweeps::pieces([l]))).collect(); + if !rails.is_empty() { + return crate::smlib_sweeps::loft_rails(&pieces, first, rails, fit); } - let all = guard("loft", || crate::loft_rails::railed_wires(&planes, &wires, true, rails, fit))?; - // The wires run from the first section given, or (turned round) the last. - // Three wires or more: one smooth surface through them all for each segment. A plain loft - // falls back to ruled faces where that fails; a railed one has to follow its rails. - if all.len() >= 3 { - let smooth = guard("loft", || { - let faces = smooth_loft_faces(&all, &edge_sources, true)?; - cap_and_close(faces, std::slice::from_ref(first), std::slice::from_ref(last), reversed) - }); - if smooth.is_ok() || !rails.is_empty() { - return smooth; - } - } - guard("loft", || { - let sides = ruled_loft_faces(&wires, &edge_sources)?; - cap_and_close(sides, std::slice::from_ref(first), std::slice::from_ref(last), reversed) - }) + crate::smlib_sweeps::loft(&pieces, first) } /// A loft through regions with matching hole counts. Hole walls are built alongside the @@ -1860,6 +1012,7 @@ pub fn loft_with_rails(sections: &[(Plane, Loop2)], rails: &[Vec], fit: Ra /// Holes are paired by their positions relative to the outline, independently of sketch /// curve order. A hole cannot appear or disappear partway through a loft. pub fn loft_regions(sections: &[(Plane, Region2)]) -> Result { + let _span = solidcraft_profile::span("kernel", "loft_regions"); if !(2..=50).contains(§ions.len()) { return Err(KernelError::Invalid("a loft needs 2…50 sections".into())); } @@ -1934,56 +1087,36 @@ pub fn loft_regions(sections: &[(Plane, Region2)]) -> Result { if counts.iter().sum::() > MAX_SEGS { return Err(KernelError::Invalid("matching loft sections would create too many segments".into())); } - guard("loft with holes", || { - let mut loops = vec![loft_numbered_wires(&outlines, reversed)?]; - for i in 0..holes { - let secs = planes - .iter() - .zip(&numbered) - .map(|(p, r)| r.holes.get(i).cloned().map(|h| (*p, h)).ok_or_else(|| KernelError::Invalid("missing loft hole".into()))) - .collect::>>()?; - // The holes have already been ordered with the outline. - loops.push(loft_numbered_wires(&secs, false)?); - } - let close = |smooth: bool| { - let mut sides = Vec::new(); - let mut first = Vec::new(); - let mut last = Vec::new(); - for (i, (wires, sources)) in loops.iter().enumerate() { - let faces = if smooth { smooth_loft_faces(wires, sources, true)? } else { ruled_loft_faces(wires, sources)? }; - let (Some(a), Some(b)) = (wires.first(), wires.last()) else { return Err(KernelError::Invalid("no loft sections".into())) }; - if i == 0 { - sides.extend(faces); - first.push(a.clone()); - last.push(b.clone()); - } else { - sides.extend(faces.into_iter().map(|(f, source)| (f.inverse(), source))); - first.push(a.inverse()); - last.push(b.inverse()); - } - } - cap_and_close(sides, &first, &last, reversed) - }; - if sections.len() >= 3 - && let Ok(body) = guard("smooth loft with holes", || close(true)) - { - return Ok(body); - } - close(false) - }) + smlib_loft_regions(&outlines, &planes, &numbered, reversed) } -/// The wires of a loft's closed sections, matched: oriented alike, resampled to the same -/// segment count and turned to start alike; with the profile segments under each wire edge, and -/// whether the sections were turned round into the canonical order. -pub(crate) fn loft_wires(sections: &[(Plane, Loop2)]) -> Result<(Vec, Vec>>, bool)> { - let reversed = loft_reversed(sections)?; - let ordered = sections.iter().map(|(p, _)| *p).zip(numbered::number_loops(sections.iter().map(|(_, l)| l))).collect::>(); - let (wires, sources) = guard("loft sections", || loft_numbered_wires(&ordered, reversed))?; - Ok((wires, sources, reversed)) +/// [`loft_regions`] through SMLib's skin, which lofts a section's loops (its outline, then its +/// holes, in the order given) to the loops in the same place in the next: the outline and each +/// hole matched as above, every section's loops one profile, the holes turned against the +/// outline. `outlines` are as given, `planes` and the holes of `numbered` in canonical order. +fn smlib_loft_regions(outlines: &[(Plane, NumberedLoop)], planes: &[Plane], numbered: &[NumberedRegion], reversed: bool) -> Result { + let mut sections: Vec<(Plane, Vec)> = + loft_numbered_loops(outlines, reversed)?.iter().map(|(p, l)| (*p, crate::smlib_sweeps::pieces([l]))).collect(); + let holes = numbered.first().map_or(0, |r| r.holes.len()); + for i in 0..holes { + let secs = planes + .iter() + .zip(numbered) + .map(|(p, r)| r.holes.get(i).cloned().map(|h| (*p, h)).ok_or_else(|| KernelError::Invalid("missing loft hole".into()))) + .collect::>>()?; + let hole = loft_numbered_loops(&secs, false)?; + if hole.len() != sections.len() { + return Err(KernelError::Invalid("missing loft hole".into())); + } + for ((_, pieces), (_, h)) in sections.iter_mut().zip(&hole) { + pieces.extend(crate::smlib_sweeps::pieces([&h.reversed()])); + } + } + let first = if reversed { sections.len().saturating_sub(1) } else { 0 }; + crate::smlib_sweeps::loft(§ions, first) } -fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result { +pub(crate) fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result { if sections.len() < 2 || sections.len() > 50 { return Err(KernelError::Invalid("a loft needs 2…50 sections".into())); } @@ -2015,20 +1148,15 @@ fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result { Ok(big < 0.0) } -fn loft_numbered_wires(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result<(Vec, Vec>>)> { - let mut wires: Vec = Vec::new(); - // Per section, the profile segments under each of its wire's edges. - let mut edge_sources: Vec>> = 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> { +/// The loft's sections as the walls are built through them: in canonical order (`reversed` +/// turns them round), each oriented the same way, re-split to the same number of segments and +/// started at the segment that lines up with the section before it. Every section is matched to +/// its neighbour, as the walls pair them: it winds the way the section before it does about the +/// normal they share (its plane's normal, turned over where it faces back from the one before), +/// so sections whose planes turn on round the loft (a bar bent half a turn) keep one winding; +/// and it starts where its vertices line up best with the section before it. The first section is +/// matched to the one with the most segments, whose count every section takes. +pub(crate) fn loft_numbered_loops(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result> { 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())); @@ -2038,32 +1166,17 @@ pub(crate) fn loft_section_loops(sections: &[(Plane, NumberedLoop)], reversed: b if reversed { ordered.reverse(); } - // Orient every section counter-clockwise about the first section's normal (`Body::new` - // turns the solid outward), then match segment counts and starting points to the section - // 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)) - }) - .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 = lead.1.lp.segs.iter().map(|s| lead.0.to_world(s.start()) - lead_c).collect(); + let lead = ordered.iter().max_by_key(|(_, l)| l.lp.segs.len()).ok_or_else(|| KernelError::Invalid("no sections".into()))?; + let corners = |p: &Plane, l: &NumberedLoop| -> (Vec3, Vec) { + let c = p.to_world(l.lp.centroid()); + (c, l.lp.segs.iter().map(|s| p.to_world(s.start()) - c).collect()) + }; + let first_normal = ordered.first().map(|(p, _)| p.normal()).ok_or_else(|| KernelError::Invalid("no sections".into()))?; + // What each section is matched to: the normal the windings share, and the corners' directions + // from the centre (the lead's for the first section, then the section before). + let (mut normal, mut dirs) = (first_normal, corners(&lead.0, &lead.1.oriented(lead.0.normal().dot(first_normal) < 0.0)).1); // 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. + // breaks when the matched directions do not go round in order. let lead_len: f64 = lead.1.lp.segs.iter().map(Seg2::length).sum(); let fractions: Vec = lead .1 @@ -2076,167 +1189,33 @@ pub(crate) fn loft_section_loops(sections: &[(Plane, NumberedLoop)], reversed: b Some(f) }) .collect(); - let mut out: Vec<(Plane, NumberedLoop)> = 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 = lead_dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y)).angle()).collect(); - // 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 { - r = r.oriented(true); - } - // Start where every vertex lines up best with the lead's vertex of the same number (the - // largest sum of dot products of their directions from the centroids). The one vertex - // closest in direction to the lead's first vertex twisted non-convex sections (#881): a - // zig-zag's centroid sits off its outline, so its first vertex can point away from the - // lead's. - let dirs: Vec = lead_dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y))).collect(); + let mut out = Vec::with_capacity(ordered.len()); + for (p, l) in &ordered { + let back = p.normal().dot(normal) < 0.0; + let local: Vec = dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y))).collect(); + // Break angles: the matched corners seen in this plane. A re-split circle runs counter- + // clockwise in its plane; wound the other way when the plane faces back. + let angles: Vec = local.iter().map(|d| d.angle()).collect(); + let mut r = l.oriented(back).resample(n, &angles, &fractions, false).oriented(back); + // Start where every vertex lines up best with the matched one of the same number (the + // largest sum of dot products of their directions from the centroids): the single vertex + // closest in direction twisted non-convex sections (#881). + let c = r.lp.centroid(); let m = r.lp.segs.len(); let fit = - |k: usize| -> f64 { dirs.iter().enumerate().filter_map(|(i, d)| r.lp.segs.get((i + k) % m).map(|s| (s.start() - c).dot(*d))).sum() }; + |k: usize| -> f64 { local.iter().enumerate().filter_map(|(i, d)| r.lp.segs.get((i + k) % m).map(|s| (s.start() - c).dot(*d))).sum() }; if let Some(k) = (0..m).min_by(|a, b| fit(*b).total_cmp(&fit(*a))) { r.rotate_left(k); } + normal = if back { p.normal() * -1.0 } else { p.normal() }; + dirs = corners(p, &r).1; out.push((*p, r)); } Ok(out) } -/// Ruled faces between each two neighbouring section wires; each comes from the section edges -/// it spans. -pub(crate) fn ruled_loft_faces(wires: &[mt::Wire], edge_sources: &[Vec>]) -> Result> { - let mut sides: Vec = Vec::new(); - for (k, w) in wires.windows(2).enumerate() { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; - let shell = builder::try_wire_homotopy(a, b).map_err(|e| KernelError::Failed(format!("loft: {e}")))?; - match (edge_sources.get(k), edge_sources.get(k + 1)) { - (Some(na), Some(nb)) => sides.extend(record::ruled(&shell, a, b, na, nb)), - _ => sides.extend(shell.face_iter().map(|f| (f.clone(), None))), - } - } - Ok(sides) -} - -/// Points across the sections (one per section, in order) as a smooth B-spline through them at the -/// parameters `u` (rising from 0 to 1, one per section): cubic through four or more, quadratic -/// through three. -pub(crate) fn across(pts: &[Vec3], u: &[f64]) -> Option> { - match pts { - [a, b, c] => { - // The quadratic Bezier through `b` at t = u[1]. - let t = *u.get(1)?; - if !(t > 0.0 && t < 1.0) { - return None; - } - let m = (*b - *a * ((1.0 - t) * (1.0 - t)) - *c * (t * t)) * (1.0 / (2.0 * t * (1.0 - t))); - mt::BSplineCurve::try_new(mt::KnotVec::bezier_knot(2), vec![p3(*a), p3(m), p3(*c)]).ok() - } - _ => interpolate_cubic_at(pts, u), - } -} - -/// The parameters of the sections along a loft: in proportion to the distance between them (the -/// mean over the wires' vertices), so that unevenly spaced sections get a surface that follows -/// them. At a uniform parameter a section close to its neighbour makes the surface overshoot -/// between the others (by several times the section's size when the spacing differs tenfold). -/// Evenly spaced sections give the uniform parameters. -pub(crate) fn section_parameters(edges: &[Vec]) -> Vec { - let m = edges.len(); - let uniform = || (0..m).map(|i| i as f64 / (m.max(2) - 1) as f64).collect::>(); - let corners: Vec> = edges.iter().map(|es| es.iter().map(|e| from_p3(e.front().point())).collect()).collect(); - let mut u = vec![0.0]; - for w in corners.windows(2) { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return uniform() }; - let n = a.len().min(b.len()); - if n == 0 { - return uniform(); - } - let step = a.iter().zip(b).map(|(p, q)| p.dist(*q)).sum::() / n as f64; - u.push(u.last().copied().unwrap_or(0.0) + step); - } - let Some(total) = u.last().copied().filter(|t| t.is_finite() && *t > 0.0) else { return uniform() }; - let u: Vec = u.iter().map(|x| x / total).collect(); - // A section on top of its neighbour: no parameter for it, so the uniform ones. - if u.windows(2).any(|w| w.get(1).zip(w.first()).is_none_or(|(b, a)| b - a < 1e-6)) { - return uniform(); - } - u -} - -/// A loft whose side faces are B-spline surfaces through every section (smooth across the -/// middle sections, which leave no edges). Every section wire comes from `uniform_wire`, so the -/// k-th edges of all sections share one knot vector and their control points pair up. Face k -/// comes from the profile segments under the k-th edge of every section (`numbers`: by -/// section, by edge); the caps as [`cap_and_close`] takes them (`from_end`). -/// One smooth face through every section for each wire edge (cubic across four sections or -/// more, quadratic across three), neighbours sharing their seams. `closed` wires join their -/// last edge to their first; open ones have a seam at each end. -pub(crate) fn smooth_loft_faces(wires: &[mt::Wire], numbers: &[Vec>], closed: bool) -> Result> { - let fail = |m: &str| KernelError::Failed(format!("smooth loft: {m}")); - let edges: Vec> = wires.iter().map(|w| w.edge_iter().cloned().collect()).collect(); - let n = edges.first().map(Vec::len).ok_or_else(|| fail("no sections"))?; - if edges.iter().any(|e| e.len() != n) { - return Err(fail("sections with different edge counts")); - } - let curve_of = |e: &mt::Edge| -> Option> { - match e.curve() { - mt::Curve::BSplineCurve(c) if e.orientation() => Some(c), - _ => None, - } - }; - let (Some(first), Some(last)) = (edges.first(), edges.last()) else { return Err(fail("sections")) }; - let along = section_parameters(&edges); - // Seams: through the k-th vertex of every section (an open wire's last one at the end of - // its last edge). - let vertex = |e: &mt::Edge, end: bool| if end { e.back().clone() } else { e.front().clone() }; - let seam_count = if closed { n } else { n + 1 }; - let mut seams: Vec = Vec::with_capacity(seam_count); - for k in 0..seam_count { - let (at, end) = if k < n { (k, false) } else { (n - 1, true) }; - let pts: Vec = edges.iter().filter_map(|es| es.get(at).map(|e| from_p3(vertex(e, end).point()))).collect(); - let c = across(&pts, &along).ok_or_else(|| fail("seam"))?; - let (Some(a), Some(b)) = (first.get(at), last.get(at)) else { return Err(fail("seam")) }; - seams.push(mt::Edge::new(&vertex(a, end), &vertex(b, end), mt::Curve::BSplineCurve(c))); - } - let mut faces = Vec::with_capacity(n); - for k in 0..n { - let curves: Vec> = - edges.iter().map(|es| es.get(k).and_then(curve_of)).collect::>().ok_or_else(|| fail("section curves"))?; - let c0 = curves.first().ok_or_else(|| fail("section curves"))?; - let uk = c0.knot_vec().clone(); - let m = c0.control_points().len(); - if curves.iter().any(|c| c.control_points().len() != m || c.knot_vec() != &uk) { - return Err(fail("sections parameterised differently")); - } - let mut ctrl: Vec> = Vec::with_capacity(m); - let mut vk = None; - for j in 0..m { - let pts: Vec = curves.iter().filter_map(|c| c.control_points().get(j).map(|p| from_p3(*p))).collect(); - let c = across(&pts, &along).ok_or_else(|| fail("surface"))?; - vk = Some(c.knot_vec().clone()); - ctrl.push(c.control_points().clone()); - } - let vk = vk.ok_or_else(|| fail("surface"))?; - let surface = mt::BSplineSurface::try_new((uk, vk), ctrl).map_err(|e| fail(&e.to_string()))?; - let (Some(e0), Some(e1), Some(s0), Some(s1)) = (first.get(k), last.get(k), seams.get(k), seams.get((k + 1) % seam_count)) else { - return Err(fail("face")); - }; - // u along the section edge, v across the sections: counter-clockwise in (u, v). - let w: mt::Wire = vec![e0.clone(), s1.clone(), e1.inverse(), s0.inverse()].into(); - let face = mt::Face::try_new(vec![w], mt::Surface::BSplineSurface(surface)).map_err(|e| fail(&e.to_string()))?; - let under: Vec<&usize> = numbers.iter().filter_map(|s| s.get(k)).flatten().collect(); - faces.push((face, (under.len() >= numbers.len().max(1)).then(|| record::profile(under)))); - } - Ok(faces) -} - /// A 3D path segment for sweeps. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum PathSeg { Line { a: Vec3, @@ -2249,11 +1228,38 @@ pub enum PathSeg { axis: Vec3, angle: f64, }, + /// A free-form curve of a sketch (a Bézier or conic piece): `seg` on `plane`. + Curve { + plane: Plane, + seg: Seg2, + }, + /// A rational Bézier span in space: a span of a drawn 3D sketch spline + /// ([`crate::PathPiece::Spline`]) or of an edge's curve ([`crate::edge_path`]). + Bezier(crate::point_path::SpaceBezier), } impl PathSeg { + /// Where the segment starts. + pub fn start(&self) -> Vec3 { + match *self { + PathSeg::Line { a, .. } | PathSeg::Arc { a, .. } => a, + PathSeg::Curve { plane, seg } => plane.to_world(seg.start()), + PathSeg::Bezier(b) => b.start(), + } + } + + /// Where the segment ends. + pub fn end(&self) -> Vec3 { + match *self { + PathSeg::Line { b, .. } => b, + PathSeg::Arc { a, center, axis, angle } => axis.normalized().map_or(a, |k| rotate_about(a, center, k, angle)), + PathSeg::Curve { plane, seg } => plane.to_world(seg.end()), + PathSeg::Bezier(b) => b.end(), + } + } + /// Unit directions of the path where the segment starts and ends. - pub(crate) fn tangents(&self) -> Option<(Vec3, Vec3)> { + pub fn tangents(&self) -> Option<(Vec3, Vec3)> { match *self { PathSeg::Line { a, b } => { let t = (b - a).normalized()?; @@ -2264,13 +1270,122 @@ impl PathSeg { let end = rotate_about(a, center, k, angle); Some((k.cross(a - center).normalized()?, k.cross(end - center).normalized()?)) } + PathSeg::Curve { plane, seg } => { + Some((plane.dir_to_world(seg.start_tangent()).normalized()?, plane.dir_to_world(seg.end_tangent()).normalized()?)) + } + PathSeg::Bezier(b) => Some((b.derivative(0.0)?.normalized()?, b.derivative(1.0)?.normalized()?)), } } + /// The segment as the rational Bézier span in space that is the same curve on the same + /// parameter: a sketch cubic, Bézier or conic carried onto its plane (an affine image keeps + /// the weights). `None` for a line or an arc, which have closed forms of their own, and for a + /// span that does not evaluate. + fn space_bezier(&self) -> Option { + use solidcraft_geom::bspline::HPoint; + let PathSeg::Curve { plane, seg } = *self else { + return match *self { + PathSeg::Bezier(b) => Some(b), + _ => None, + }; + }; + let w = |p: Vec2, weight: f64| HPoint::weighted(plane.to_world(p), weight); + match seg { + Seg2::Cubic { p0, p1, p2, p3 } => crate::point_path::SpaceBezier::new(&[w(p0, 1.0), w(p1, 1.0), w(p2, 1.0), w(p3, 1.0)]), + Seg2::Bezier { n, p } => { + let ctrl: Vec = p.get(..=usize::from(n))?.iter().map(|q| w(*q, 1.0)).collect(); + crate::point_path::SpaceBezier::new(&ctrl) + } + Seg2::Conic { a, apex, b, w: weight } => crate::point_path::SpaceBezier::new(&[w(a, 1.0), w(apex, weight), w(b, 1.0)]), + Seg2::Line { .. } | Seg2::Arc { .. } => None, + } + } + + /// The segment's length: a line's and an arc's in closed form, a free-form span's by its + /// arc-length integral ([`crate::SpaceBezier::length`]). `None` for a segment that does not + /// evaluate. + pub fn length(&self) -> Option { + let l = match *self { + PathSeg::Line { a, b } => a.dist(b), + PathSeg::Arc { a, center, angle, .. } => a.dist(center) * angle.abs(), + PathSeg::Curve { plane, seg: seg @ (Seg2::Line { .. } | Seg2::Arc { .. }) } => return PathSeg::of_sketch(&plane, &seg).length(), + PathSeg::Curve { .. } | PathSeg::Bezier(_) => self.space_bezier()?.length()?, + }; + l.is_finite().then_some(l) + } + + /// The point a fraction `f` (0…1) of the way along the segment by arc length, and the unit + /// direction of travel there: a line's and an arc's in closed form (an arc's length grows + /// with its angle), a free-form span's at the parameter where its arc-length integral reaches + /// that fraction ([`crate::SpaceBezier::along`]). `None` for a segment that does not + /// evaluate or has no direction. + pub fn along(&self, f: f64) -> Option<(Vec3, Vec3)> { + let f = f.clamp(0.0, 1.0); + match *self { + PathSeg::Line { a, b } => Some((a.lerp(b, f), (b - a).normalized()?)), + PathSeg::Arc { a, center, axis, angle } => { + let k = axis.normalized()?; + let p = rotate_about(a, center, k, angle * f); + Some((p, (k.cross(p - center) * angle.signum()).normalized()?)) + } + PathSeg::Curve { plane, seg: seg @ (Seg2::Line { .. } | Seg2::Arc { .. }) } => PathSeg::of_sketch(&plane, &seg).along(f), + PathSeg::Curve { .. } | PathSeg::Bezier(_) => self.space_bezier()?.along(f), + } + } + + /// The segment the other way round. + pub fn reversed(&self) -> PathSeg { + match *self { + PathSeg::Line { a, b } => PathSeg::Line { a: b, b: a }, + PathSeg::Arc { center, axis, angle, .. } => PathSeg::Arc { a: self.end(), center, axis: axis * -1.0, angle }, + PathSeg::Curve { plane, seg } => PathSeg::Curve { plane, seg: seg.reversed() }, + PathSeg::Bezier(b) => PathSeg::Bezier(b.reversed()), + } + } + + /// The segment carried by the rigid motion `point` of points and `vector` of directions + /// (a placement); `None` where a carried span no longer evaluates. + pub fn mapped(&self, point: impl Fn(Vec3) -> Vec3, vector: impl Fn(Vec3) -> Vec3) -> Option { + Some(match *self { + PathSeg::Line { a, b } => PathSeg::Line { a: point(a), b: point(b) }, + PathSeg::Arc { a, center, axis, angle } => PathSeg::Arc { a: point(a), center: point(center), axis: vector(axis), angle }, + PathSeg::Curve { plane, seg } => PathSeg::Curve { plane: Plane::new(point(plane.origin), vector(plane.x), vector(plane.y))?, seg }, + PathSeg::Bezier(b) => PathSeg::Bezier(b.mapped(point)?), + }) + } + + /// A sketch segment on `plane` as the path segment that is the same curve: a line, an arc + /// about the plane's normal, or the free curve on its plane. + pub fn of_sketch(plane: &Plane, s: &Seg2) -> PathSeg { + let w = |p: Vec2| plane.to_world(p); + match *s { + Seg2::Line { a, b } => PathSeg::Line { a: w(a), b: w(b) }, + Seg2::Arc { center, sweep, .. } => { + PathSeg::Arc { a: w(s.start()), center: w(center), axis: plane.normal() * sweep.signum(), angle: sweep.abs() } + } + Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => PathSeg::Curve { plane: *plane, seg: *s }, + } + } + + /// The path with each free-form curve as the lines of its polyline within 0.01 mm, as the + /// sheet sweeps follow it. + pub fn flattened(path: &[PathSeg]) -> Vec { + path.iter() + .flat_map(|s| match *s { + PathSeg::Curve { plane, seg } => { + seg.polyline(1e-2).windows(2).map(|q| PathSeg::Line { a: plane.to_world(q[0]), b: plane.to_world(q[1]) }).collect() + } + _ => vec![*s], + }) + .collect() + } + /// Points along the segment (an arc within `tol` of its chords), without its start. pub(crate) fn points_after_start(&self, tol: f64) -> Vec { match *self { PathSeg::Line { b, .. } => vec![b], + PathSeg::Curve { plane, seg } => seg.polyline(tol).into_iter().skip(1).map(|q| plane.to_world(q)).collect(), + PathSeg::Bezier(b) => b.polyline(tol), PathSeg::Arc { a, center, axis, angle } => { let Some(k) = axis.normalized() else { return vec![a] }; let r = (a - center).len(); @@ -2289,27 +1404,11 @@ pub(crate) fn rotate_about(p: Vec3, center: Vec3, k: Vec3, angle: f64) -> Vec3 { center + v * c + k.cross(v) * s + k * (k.dot(v) * (1.0 - c)) } -/// The path as a polyline: its first point, then each segment's points (arcs within 0.01 mm of -/// their chords). -pub fn path_polyline(path: &[PathSeg]) -> Result> { - let first = match path.first() { - Some(PathSeg::Line { a, .. } | PathSeg::Arc { a, .. }) => *a, - None => return Err(KernelError::Invalid("the path needs 1…1000 segments".into())), - }; - let mut pts = vec![first]; - for seg in path { - pts.extend(seg.points_after_start(1e-2)); - } - Ok(pts) -} - -/// [`sweep`] with sweep options. The default options are exactly [`sweep`]; any other -/// orientation, a twist or an end scale follow the path as a polyline through stations (see -/// [`crate::sweep_path_with`]). -pub fn sweep_with(plane: &Plane, region: &Region2, path: &[PathSeg], ctl: &crate::SweepControl) -> Result { - if ctl.is_default() { - return sweep(plane, region, path); - } +/// [`sweep_with`] through SMLib: its curve sweep for the profile turning with the path or only +/// moving along it (orientation parallel), the walls meeting in mitres at the path's corners; a +/// twist, an end scale, guide rails or an orientation direction place the profile at stations +/// along a path without corners ([`crate::smlib_sweeps::sweep_controlled`]). +fn smlib_sweep(plane: &Plane, region: &Region2, path: &[PathSeg], ctl: &crate::SweepControl) -> Result { ctl.check()?; region_ok(region)?; if path.is_empty() || path.len() > 1000 { @@ -2318,339 +1417,36 @@ pub fn sweep_with(plane: &Plane, region: &Region2, path: &[PathSeg], ctl: &crate if path.iter().any(|s| s.tangents().is_none()) { return Err(KernelError::Invalid("a path segment has no direction".into())); } - crate::sweep_path::sweep_path_with(plane, region, &path_polyline(path)?, ctl) + let translate = match ctl.orientation { + _ if ctl.varies() => return crate::smlib_sweeps::sweep_controlled(plane, &oriented(region)?, path, ctl), + crate::SweepOrientation::Perpendicular => false, + crate::SweepOrientation::Parallel => true, + crate::SweepOrientation::Direction(_) => return crate::smlib_sweeps::sweep_controlled(plane, &oriented(region)?, path, ctl), + }; + crate::smlib_sweeps::sweep(plane, &crate::smlib_sweeps::pieces(oriented(region)?.loops()), path, translate) } -/// Sweep a planar region (outer loop) along a chain of path segments, keeping the profile -/// perpendicular to the path (lines translate it, arcs rotate it). A path with sharp corners -/// is swept as a polyline, mitred at the corners. -pub fn sweep(plane: &Plane, region: &Region2, path: &[PathSeg]) -> Result { - region_ok(region)?; - if path.is_empty() || path.len() > 1000 { - return Err(KernelError::Invalid("the path needs 1…1000 segments".into())); - } - // Segment by segment the profile only follows a path whose direction runs on across each - // joint: at a corner the next line would slide the profile within its own plane. - let ends: Vec<(Vec3, Vec3)> = - path.iter().map(PathSeg::tangents).collect::>().ok_or_else(|| KernelError::Invalid("a path segment has no direction".into()))?; - let corner = ends.windows(2).any(|w| w[0].1.dot(w[1].0) < (1e-3f64).cos()); - if corner { - return crate::sweep_path::sweep_path(plane, region, &path_polyline(path)?); - } - let points = path_polyline(path)?; - if crate::sweep_path::closed_path(&points) { - // Sketch circles have two half arcs. Sweep the whole turn in one operation so truck - // shares the closing edges itself. Other closed paths use stations with shared ends. - if let Some((center, axis, angle)) = full_circle(path) { - return guard("closed sweep", || { - let profile = region_wires(plane, &oriented(region)?)?; - let mut sides = Vec::new(); - for p in &profile { - let shell: mt::Shell = builder::rsweep(&p.wire, p3(center), v3(axis), mt::Rad(angle)); - let numbers = seeds(std::slice::from_ref(p)); - let prov = record::columns(shell.face_iter(), &numbers, None, record::Column::ToEnd, &[]); - sides.extend(shell.face_iter().enumerate().map(|(i, f)| (f.clone(), prov.as_ref().and_then(|p| p.get(i)).cloned().flatten()))); - } - close_sweep(sides) - }); - } - return crate::sweep_path::sweep_path(plane, region, &points); - } - // The outer loop and each hole, swept along the path; the ends are capped with holes. - let profile = region_wires(plane, &oriented(region)?)?; - let starts = wires_of(&profile); - guard("sweep", || { - let mut shell = mt::Shell::new(); - let mut ends = Vec::new(); - for w0 in &starts { - let mut cur = w0.clone(); - for seg in path { - let mut part: mt::Shell = match *seg { - PathSeg::Line { a, b } => builder::tsweep(&cur, v3(b - a)), - PathSeg::Arc { center, axis, angle, .. } => { - let ax = axis.normalized().ok_or_else(|| KernelError::Invalid("arc axis".into()))?; - builder::rsweep(&cur, p3(center), v3(ax), mt::Rad(angle)) - } - }; - let next = part - .extract_boundaries() - .into_iter() - .find(|w| w.edge_iter().all(|e| !cur.edge_iter().any(|c| c.id() == e.id()))) - .ok_or_else(|| KernelError::Failed("sweep: lost the profile".into()))?; - shell.append(&mut part); - cur = next.inverse(); - } - ends.push(cur); - } - // A straight profile edge square to an arc's axis turns in its own plane: that face is - // given a plane, so that it is found lying on a planar face of another body. - let mut bounds = solidcraft_geom::Aabb3::EMPTY; - shell.vertex_iter().for_each(|v| bounds.add(from_p3(v.point()))); - let size = bounds.size().len(); - if size.is_finite() - && let Some(flat) = crate::heal::planar_surfaces(&shell, (size * 1e-7).max(1e-9)) - { - shell = flat; - } - // truck sweeps the faces: each profile edge's run along the whole path, path segment - // after segment. - let sides: Vec = match record::columns(shell.face_iter(), &seeds(&profile), None, record::Column::ToEnd, &[]) { - Some(prov) => shell.face_iter().cloned().zip(prov).collect(), - None => shell.face_iter().map(|f| (f.clone(), None)).collect(), - }; - cap_and_close(sides, &starts, &ends, false) - }) -} - -/// A connected, single turn about one centre and axis, possibly split into sketch arcs. -fn full_circle(path: &[PathSeg]) -> Option<(Vec3, Vec3, f64)> { - let PathSeg::Arc { a: first, center, axis, .. } = *path.first()? else { return None }; - let axis = axis.normalized()?; - let mut end = first; - let mut total = 0.0; +/// The path as a polyline: its first point, then each segment's points (arcs within 0.01 mm of +/// their chords). +pub fn path_polyline(path: &[PathSeg]) -> Result> { + let first = path.first().map(PathSeg::start).ok_or_else(|| KernelError::Invalid("the path needs 1…1000 segments".into()))?; + let mut pts = vec![first]; for seg in path { - let PathSeg::Arc { a, center: c, axis: k, angle } = *seg else { return None }; - if a.dist(end) > 1e-7 || c.dist(center) > 1e-7 || k.normalized()?.dist(axis) > 1e-9 || !angle.is_finite() { - return None; - } - total += angle; - end = rotate_about(a, c, axis, angle); + pts.extend(seg.points_after_start(1e-2)); } - ((total.abs() - std::f64::consts::TAU).abs() < 1e-9).then_some((center, axis, total)) + Ok(pts) } -/// Cox–de Boor basis values N_{j,3}(u) for all j. -fn cubic_basis(knots: &[f64], n_ctrl: usize, u: f64) -> Vec { - let p = 3; - let m = knots.len(); - let mut n = vec![0.0; m.saturating_sub(1)]; - let last = n_ctrl.saturating_sub(1); - for (j, v) in n.iter_mut().enumerate() { - let (Some(&a), Some(&b)) = (knots.get(j), knots.get(j + 1)) else { continue }; - // Half-open spans, with the last span closed at the end. - if (a <= u && u < b) || (u >= b && (b - a) > 0.0 && j == last && (u - b).abs() < 1e-12) { - *v = 1.0; - } - } - for k in 1..=p { - for j in 0..m.saturating_sub(1 + k) { - let (Some(&tj), Some(&tjk), Some(&tj1), Some(&tjk1)) = (knots.get(j), knots.get(j + k), knots.get(j + 1), knots.get(j + k + 1)) else { - continue; - }; - let left = if tjk - tj > 0.0 { (u - tj) / (tjk - tj) * n.get(j).copied().unwrap_or(0.0) } else { 0.0 }; - let right = if tjk1 - tj1 > 0.0 { (tjk1 - u) / (tjk1 - tj1) * n.get(j + 1).copied().unwrap_or(0.0) } else { 0.0 }; - if let Some(v) = n.get_mut(j) { - *v = left + right; - } - } - } - n.truncate(n_ctrl); - n +/// [`sweep`] with sweep options. The default options are exactly [`sweep`]; a twist, an end +/// scale, guide rails or an orientation direction place the profile at stations along the path. +pub fn sweep_with(plane: &Plane, region: &Region2, path: &[PathSeg], ctl: &crate::SweepControl) -> Result { + let _span = solidcraft_profile::span("kernel", "sweep_with"); + smlib_sweep(plane, region, path, ctl) } -/// Cubic B-spline through points at uniform parameters (clamped, knots by averaging). -pub(crate) fn interpolate_cubic(pts: &[Vec3]) -> Option> { - let m = pts.len(); - let u: Vec = (0..m).map(|i| i as f64 / (m.max(2) - 1) as f64).collect(); - interpolate_cubic_at(pts, &u) -} - -/// A cubic B-spline surface through a grid of samples at uniform parameters: cubics across v -/// through each u index's samples, then cubics across u through their control points. -pub(crate) struct NetFit { - pub surface: mt::BSplineSurface, - /// The surface's edges at the first and the last u (curves across v). - pub u_ends: [mt::BSplineCurve; 2], - /// The surface's edges at the first and the last v (curves across u). - pub v_ends: [mt::BSplineCurve; 2], -} - -/// [`NetFit`] through `samples`; `None` with fewer than four samples across either direction. -pub(crate) fn interpolate_net(samples: &Grid) -> Option { - let across_v: Vec> = samples.transposed().lines().map(interpolate_cubic).collect::>()?; - let across_u: Vec> = - control_net(&across_v)?.lines().map(|run| interpolate_cubic(&run.iter().map(|&p| from_p3(p)).collect::>())).collect::>()?; - let net = control_net(&across_u)?.transposed().into_u_rows(); - let knots = (across_u.first()?.knot_vec().clone(), across_v.first()?.knot_vec().clone()); - let surface = mt::BSplineSurface::try_new(knots, net).ok()?; - let u_ends = [across_v.first()?.clone(), across_v.last()?.clone()]; - let v_ends = [across_u.first()?.clone(), across_u.last()?.clone()]; - Some(NetFit { surface, u_ends, v_ends }) -} - -/// The control points of `curves` as a grid: value `(i, j)` is control point `j` of curve `i`. -/// `None` unless every curve has as many control points. -fn control_net(curves: &[mt::BSplineCurve]) -> Option> { - let rows: Vec<&[mt::Point3]> = curves.iter().map(|c| c.control_points().as_slice()).collect(); - Grid::from_u_rows(&rows) -} - -/// [`interpolate_cubic`] by chord length: the parameters (0 to 1) in proportion to the distance -/// along the points. Points closer together toward an end (where a curve leaves another -/// tangentially) then don't slow the curve to a stop there, where a uniform parameter lets it -/// double back on itself. -pub(crate) fn interpolate_cubic_chordal(pts: &[Vec3]) -> Option<(mt::BSplineCurve, Vec)> { - let mut u = vec![0.0]; - for w in pts.windows(2) { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return None }; - u.push(u.last().copied().unwrap_or(0.0) + a.dist(*b)); - } - let total = u.last().copied().filter(|t| t.is_finite() && *t > 0.0)?; - let u: Vec = u.iter().map(|x| x / total).collect(); - if u.windows(2).any(|w| w.first() >= w.get(1)) { - return None; - } - interpolate_cubic_at(pts, &u).map(|c| (c, u)) -} - -/// The cubic B-spline through `pts` at parameters `u` (rising from 0 to 1), its knots averaged. -fn interpolate_cubic_at(pts: &[Vec3], u: &[f64]) -> Option> { - let m = pts.len(); - if m < 4 || u.len() != m { - return None; - } - let mut knots = vec![0.0; 4]; - for j in 1..(m - 3) { - knots.push((j..j + 3).filter_map(|i| u.get(i)).sum::() / 3.0); - } - knots.extend([1.0; 4]); - // Dense solve of N · P = Q for each coordinate. - let mut a: Vec> = u.iter().map(|ui| cubic_basis(&knots, m, *ui)).collect(); - let mut q: Vec<[f64; 3]> = pts.iter().map(|p| [p.x, p.y, p.z]).collect(); - for col in 0..m { - let piv = (col..m).max_by(|x, y| a[*x][col].abs().total_cmp(&a[*y][col].abs()))?; - if a[piv][col].abs() < 1e-14 { - return None; - } - a.swap(col, piv); - q.swap(col, piv); - for r in 0..m { - if r == col { - continue; - } - let f = a[r][col] / a[col][col]; - if f == 0.0 { - continue; - } - let prow = a[col].clone(); - for (x, v) in a[r].iter_mut().zip(&prow).skip(col) { - *x -= f * v; - } - let qc = q[col]; - for k in 0..3 { - q[r][k] -= f * qc[k]; - } - } - } - let ctrl: Vec = (0..m).map(|i| mt::Point3::new(q[i][0] / a[i][i], q[i][1] / a[i][i], q[i][2] / a[i][i])).collect(); - mt::BSplineCurve::try_new(mt::KnotVec::from(knots), ctrl).ok() -} - -/// A closed wire whose edges are cubic B-splines parameterised (nearly) by arc length, so that -/// ruled surfaces between sections pair points proportionally along each edge. -pub(crate) fn uniform_wire(plane: &Plane, lp: &Loop2) -> Result { - uniform_chain_wire(plane, &lp.segs, true) -} - -/// [`uniform_wire`] of a chain of segments, open or `closed`. -pub(crate) fn uniform_chain_wire(plane: &Plane, segs: &[Seg2], closed: bool) -> Result { - const SAMPLES: usize = 24; - let n = segs.len(); - let mut verts: Vec = segs.iter().map(|s| builder::vertex(p3(plane.to_world(s.start())))).collect(); - if !closed && let Some(last) = segs.last() { - verts.push(builder::vertex(p3(plane.to_world(last.end())))); - } - let mut edges = Vec::with_capacity(n); - for (i, s) in segs.iter().enumerate() { - let (Some(a), Some(b)) = (verts.get(i), verts.get(if closed { (i + 1) % n } else { i + 1 })) else { continue }; - let pts: Vec = (0..SAMPLES).map(|k| plane.to_world(s.point_at(k as f64 / (SAMPLES - 1) as f64))).collect(); - let curve = interpolate_cubic(&pts).ok_or_else(|| KernelError::Failed("loft curve".into()))?; - edges.push(mt::Edge::new(a, b, mt::Curve::BSplineCurve(curve))); - } - Ok(edges.into()) -} - -/// A sphere as six patches (the cube's faces projected onto it) on revolved surfaces whose poles -/// and seams lie outside each patch. No face has a singular point, which the boolean needs; the -/// patches are one analytic sphere, so measured topology counts it as one face. -pub fn sphere_patches(center: Vec3, radius: f64) -> Result { - sphere_patches_rotated(center, radius, [Vec3::X, Vec3::Y, Vec3::Z]) -} - -/// [`sphere_patches`] with the patch layout turned to the frame `rot` (orthonormal columns). -pub fn sphere_patches_rotated(center: Vec3, radius: f64, rot: [Vec3; 3]) -> Result { - // Every patch is swept from the arc (segment 0) of the half disc a sphere revolves. - sphere_solid(center, radius, rot, &[0]) -} - -/// [`sphere_patches_rotated`], every patch swept from profile segments `arcs`. -fn sphere_solid(center: Vec3, radius: f64, rot: [Vec3; 3], arcs: &[usize]) -> Result { - guard("sphere", || { - let shell: mt::Shell = sphere_patch_faces(center, radius, rot)?.into(); - let solid = Solid::try_new(vec![shell]).map_err(|e| KernelError::Failed(format!("sphere: {e}")))?; - record::attach(Body::new(solid)?, &[], Some(vec![record::profile(arcs); 6]), Default::default()) - }) -} - -/// The six outward patch faces of [`sphere_patches_rotated`]; truck calls, so callers guard them. -pub(crate) fn sphere_patch_faces(center: Vec3, radius: f64, rot: [Vec3; 3]) -> Result> { - let radius = finite(radius, "radius")?; - let turn = |v: Vec3| rot[0] * v.x + rot[1] * v.y + rot[2] * v.z; - if radius <= 1e-6 || !center.is_finite() { - return Err(KernelError::Invalid("radius must be positive".into())); - } - let k = radius / 3f64.sqrt(); - let corner = |sx: f64, sy: f64, sz: f64| center + turn(Vec3::new(sx * k, sy * k, sz * k)); - // Cube faces: outward direction, rotation axis for the patch's surface (perpendicular to it), - // and the four corner sign triples counter-clockwise seen from outside. - let faces: [(Vec3, Vec3, [[f64; 3]; 4]); 6] = [ - (Vec3::X, Vec3::Z, [[1.0, -1.0, -1.0], [1.0, 1.0, -1.0], [1.0, 1.0, 1.0], [1.0, -1.0, 1.0]]), - (-Vec3::X, Vec3::Z, [[-1.0, 1.0, -1.0], [-1.0, -1.0, -1.0], [-1.0, -1.0, 1.0], [-1.0, 1.0, 1.0]]), - (Vec3::Y, Vec3::Z, [[1.0, 1.0, -1.0], [-1.0, 1.0, -1.0], [-1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]), - (-Vec3::Y, Vec3::Z, [[-1.0, -1.0, -1.0], [1.0, -1.0, -1.0], [1.0, -1.0, 1.0], [-1.0, -1.0, 1.0]]), - (Vec3::Z, Vec3::X, [[-1.0, -1.0, 1.0], [1.0, -1.0, 1.0], [1.0, 1.0, 1.0], [-1.0, 1.0, 1.0]]), - (-Vec3::Z, Vec3::X, [[-1.0, 1.0, -1.0], [1.0, 1.0, -1.0], [1.0, -1.0, -1.0], [-1.0, -1.0, -1.0]]), - ]; - let key = |s: [f64; 3]| ((s[0] > 0.0) as usize) | (((s[1] > 0.0) as usize) << 1) | (((s[2] > 0.0) as usize) << 2); - let mut verts: std::collections::HashMap = std::collections::HashMap::new(); - let mut vert = |s: [f64; 3]| verts.entry(key(s)).or_insert_with(|| builder::vertex(p3(corner(s[0], s[1], s[2])))).clone(); - let mut edges: std::collections::HashMap<(usize, usize), mt::Edge> = std::collections::HashMap::new(); - let mut out: Vec = Vec::new(); - for (dir, axis, cs) in faces { - let (dir, axis) = (turn(dir), turn(axis)); - let mut wire: Vec = Vec::new(); - for i in 0..4 { - let (a, b) = (cs[i], cs[(i + 1) % 4]); - let (ka, kb) = (key(a), key(b)); - let e = match edges.get(&(ka.min(kb), ka.max(kb))) { - Some(e) => e.clone(), - None => { - let (lo, hi) = if ka < kb { (a, b) } else { (b, a) }; - let (va, vb) = (vert(lo), vert(hi)); - let mid = (corner(lo[0], lo[1], lo[2]) + corner(hi[0], hi[1], hi[2])) * 0.5 - center; - let transit = center + mid.normalized().unwrap_or(dir) * radius; - let e = builder::circle_arc(&va, &vb, p3(transit)); - edges.insert((ka.min(kb), ka.max(kb)), e.clone()); - e - } - }; - wire.push(if ka < kb { e } else { e.inverse() }); - } - // The meridian runs pole to pole through the side away from the patch. - let (np, sp, back) = (center + axis * radius, center - axis * radius, center - dir * radius); - let meridian = builder::circle_arc(&builder::vertex(p3(np)), &builder::vertex(p3(sp)), p3(back)); - let mut surface = - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(meridian.oriented_curve(), p3(center), v3(axis)))); - // Outward normal at the patch centre. - let probe = p3(center + dir * radius); - use mt::{ParametricSurface3D, SearchParameter}; - if let Some((u, v)) = surface.search_parameter(probe, mt::SPHint2D::None, 100) { - let n = surface.normal(u, v); - if mt::InnerSpace::dot(n, v3(dir)) < 0.0 { - mt::Invertible::invert(&mut surface); - } - } - out.push(mt::Face::new(vec![wire.into()], surface)); - } - Ok(out) +/// Sweep a planar region along a chain of path segments, keeping the profile perpendicular to +/// the path; at sharp corners the walls meet in mitres. +pub fn sweep(plane: &Plane, region: &Region2, path: &[PathSeg]) -> Result { + let _span = solidcraft_profile::span("kernel", "sweep"); + smlib_sweep(plane, region, path, &crate::SweepControl::default()) } diff --git a/crates/kernel/src/candidate_reach.rs b/crates/kernel/src/candidate_reach.rs deleted file mode 100644 index 75992c4ff..000000000 --- a/crates/kernel/src/candidate_reach.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! A boolean candidate whose edges run far outside its operands is discarded before it is -//! meshed (#3020). -//! -//! The retries of a boolean mesh every candidate to measure its volume. A candidate made at a -//! coarse tolerance can come out with an edge that leaves the body altogether: in the design of -//! #3020, a face of a revolved dovetail (a cone) got a trim loop several metres long on a part -//! 155 mm across, its points kilometres from the cone, and meshing that face never finished. -//! Its volume (±1e10 mm³) would have failed the check anyway; only measuring it hung. -//! -//! Every edge of a union, a cut or an intersection lies on the operands' faces, within the -//! boolean's tolerance (a small fraction of their size). So a candidate with a point of an edge -//! further outside the box the operands span than [`MARGIN`] of their size is not a result of -//! the operation, whatever its faces are, and it is discarded without meshing it. That needs no -//! search for the edge's points on its faces' surfaces, which is the very thing that runs away -//! on such a face. - -use std::collections::HashSet; - -use solidcraft_geom::{Aabb3, Mesh, Vec3}; -use truck_modeling as mt; - -use crate::body::{Body, from_p3}; - -#[cfg(test)] -#[path = "candidate_reach_tests.rs"] -mod tests; - -/// Samples along each edge, ends included: a runaway edge leaves the body over a good part of -/// its length (the loop of #3020 was thousands of times the body's size). -const EDGE_SAMPLES: u32 = 16; - -/// How far an edge of a candidate may run outside the box of the operands' meshes, as a fraction -/// of the operands' size: well above any boolean tolerance (2e-3 of the size at the coarsest) and -/// the temporary face shifts of the retries (1.4e-2 of it), well below the metres a runaway edge -/// spans. -pub(crate) const MARGIN: f64 = 0.05; - -/// Where a candidate's edges may run when the operands could not be meshed: their edges only -/// bound them loosely (a sphere's seam spans half of it), so the box of those grows by their -/// whole size. -const MARGIN_UNMESHED: f64 = 1.0; - -/// The box the operands of a boolean span, grown by the room a result's edges may take. -#[derive(Clone, Copy, Debug)] -pub(crate) struct Reach { - bounds: Aabb3, - margin: f64, -} - -impl Reach { - /// The reach of operands `a` and `b` of size `size`, from their meshes where both were made - /// (`meshes`), else from their edges. `None` when neither gives a finite box. - pub(crate) fn new(a: &Body, b: &Body, meshes: (Option<&Mesh>, Option<&Mesh>), size: f64) -> Option { - let mut bounds = Aabb3::EMPTY; - let margin = match meshes { - (Some(ma), Some(mb)) => { - ma.positions.iter().chain(&mb.positions).for_each(|p| bounds.add(*p)); - MARGIN * size - } - _ => { - for body in [a, b] { - edge_points(body, |p| { - bounds.add(p); - true - })?; - } - MARGIN_UNMESHED * size - } - }; - (!bounds.is_empty() && margin.is_finite() && margin > 0.0).then_some(Reach { bounds, margin }) - } - - /// Why `candidate` cannot be a result of a boolean of these operands: an edge of it runs - /// further outside them than the margin, or has a point that is not finite. `None` when its - /// edges stay within reach, and when they could not be sampled (it is then meshed and - /// checked as before). - pub(crate) fn runaway(&self, candidate: &Body) -> Option { - let (lo, hi) = (self.bounds.min, self.bounds.max); - let mut worst = 0.0f64; - let mut infinite = false; - edge_points(candidate, |p| { - if !p.is_finite() { - infinite = true; - return false; - } - let outside = Vec3::new(excess(p.x, lo.x, hi.x), excess(p.y, lo.y, hi.y), excess(p.z, lo.z, hi.z)).len(); - worst = worst.max(outside); - true - })?; - if infinite { - Some("a result whose edge has points that are not finite".into()) - } else if worst > self.margin { - Some(format!("a result whose edge runs {worst:.4e} mm outside the operands (more than {:.4e} mm), not meshed to measure it", self.margin)) - } else { - None - } - } -} - -/// How far `x` lies outside `[lo, hi]`. -fn excess(x: f64, lo: f64, hi: f64) -> f64 { - (lo - x).max(x - hi).max(0.0) -} - -/// Visits [`EDGE_SAMPLES`] points along each edge of `body` (once per edge) until `visit` says -/// stop. `None` when the curves could not be evaluated. -fn edge_points(body: &Body, mut visit: impl FnMut(Vec3) -> bool) -> Option<()> { - crate::guard("candidate edges", || { - use mt::{BoundedCurve, ParametricCurve}; - let mut seen = HashSet::new(); - for edge in body.solid.edge_iter() { - if !seen.insert(edge.id()) { - continue; - } - let curve = edge.curve(); - let (t0, t1) = curve.range_tuple(); - for i in 0..=EDGE_SAMPLES { - let t = t0 + (t1 - t0) * f64::from(i) / f64::from(EDGE_SAMPLES); - if !visit(from_p3(curve.subs(t))) { - return Ok(()); - } - } - } - Ok(()) - }) - .ok() -} diff --git a/crates/kernel/src/candidate_reach_tests.rs b/crates/kernel/src/candidate_reach_tests.rs deleted file mode 100644 index e237b6b6d..000000000 --- a/crates/kernel/src/candidate_reach_tests.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! A boolean candidate with a trim loop that runs off its surface is discarded fast (#3020). -//! -//! In the design of #3020 a coarse candidate of a nudged union came out with a face on a cone -//! (a revolved line: its profile parameter bounded to [0, 1], its angle periodic) whose trim -//! loop left the cone and ran thousands of profile lengths along its continuation, kilometres -//! from the part. Meshing that face to measure the candidate never finished. Here such a face -//! is made on purpose: the check finds its edge outside the operands without meshing it. - -use std::time::{Duration, Instant}; - -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, ParametricSurface, builder}; - -use super::{MARGIN, Reach}; -use crate::body::Body; - -/// The cone of the report: a profile line 2 mm out and 4 mm up from radius 20 mm (its length, -/// √20 mm, is the |∂S/∂u| measured on the runaway face), turned about Z. -fn cone() -> mt::Surface { - let profile = mt::Curve::Line(mt::Line(mt::Point3::new(20.0, 0.0, 0.0), mt::Point3::new(22.0, 0.0, 4.0))); - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(profile, mt::Point3::new(0.0, 0.0, 0.0), mt::Vector3::unit_z()))) -} - -/// A solid of one face of `surface` bounded by straight edges through `corners`, given in the -/// surface's parameters and moved `off` mm off it along its normal. -fn face_body(surface: &mt::Surface, corners: &[(f64, f64, f64)]) -> Body { - use mt::ParametricSurface3D; - let vertices: Vec = corners.iter().map(|&(u, v, off)| builder::vertex(surface.subs(u, v) + surface.normal(u, v) * off)).collect(); - let edges: Vec = (0..vertices.len()).map(|i| builder::line(&vertices[i], &vertices[(i + 1) % vertices.len()])).collect(); - let face = mt::Face::new(vec![edges.into_iter().collect()], surface.clone()); - let solid = mt::Solid::new_unchecked(vec![vec![face].into()]); - Body::new(solid).unwrap() -} - -/// The operands: a plate and the cone's own patch, which spans u in [0, 1] (radius 20-22 mm, -/// 4 mm high) over a quarter turn. -fn operands() -> (Body, Body) { - let plate = crate::box_solid(Vec3::new(-30.0, -30.0, -6.0), Vec3::new(30.0, 30.0, 0.0)).unwrap(); - let patch = face_body(&cone(), &[(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.5, 0.0), (0.0, 1.5, 0.0)]); - (plate, patch) -} - -fn reach(a: &Body, b: &Body) -> Reach { - let size = a.size().max(b.size()); - let meshes = (a.tessellate_with(size * 5e-4, true).unwrap(), b.tessellate_with(size * 5e-4, true).unwrap()); - Reach::new(a, b, (Some(&meshes.0), Some(&meshes.1)), size).unwrap() -} - -/// The runaway face: on the cone, its loop leaves the patch at u = 0 and follows the cone's -/// continuation out to u = -2450 (as the logged loop did, -2452 … 1349), 1.5 mm off it, and -/// back. -fn runaway() -> Body { - face_body(&cone(), &[(1.0, 0.2, 0.0), (1.0, 1.3, 0.0), (0.0, 1.3, 0.0), (-2450.0, 0.9, 1.5), (-2450.0, 0.6, 1.5), (0.0, 0.2, 0.0)]) -} - -#[test] -fn a_candidate_with_a_trim_loop_off_its_surface_is_rejected_fast() { - let (a, b) = operands(); - let reach = reach(&a, &b); - let candidate = runaway(); - let start = Instant::now(); - let reason = reach.runaway(&candidate); - let took = start.elapsed(); - let reason = reason.expect("an edge kilometres outside the operands"); - assert!(reason.contains("outside the operands"), "{reason}"); - assert!(took < Duration::from_secs(1), "{took:?}"); -} - -#[test] -fn sound_candidates_stay_within_reach() { - let (a, b) = operands(); - let reach = reach(&a, &b); - // The operands themselves, and a union of the plate with a cylinder standing on it. - assert_eq!(reach.runaway(&a), None); - assert_eq!(reach.runaway(&b), None); - let post = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 5.0, 20.0).unwrap(); - let reach = self::reach(&a, &post); - let union = crate::boolean(&a, &post, crate::BoolOp::Union).unwrap().unwrap(); - assert_eq!(reach.runaway(&union), None); -} - -#[test] -fn an_edge_just_past_the_margin_is_out_of_reach() { - let (a, b) = operands(); - let size = a.size().max(b.size()); - let reach = reach(&a, &b); - // A box reaching past the plate's side by twice the margin, and one within it. - let top = Vec3::new(30.0, 30.0, 0.0); - let past = crate::box_solid(Vec3::new(0.0, 0.0, -6.0), top + Vec3::X * (2.0 * MARGIN * size)).unwrap(); - let within = crate::box_solid(Vec3::new(0.0, 0.0, -6.0), top + Vec3::X * (0.5 * MARGIN * size)).unwrap(); - assert!(reach.runaway(&past).is_some()); - assert_eq!(reach.runaway(&within), None); -} - -/// The bound on a loop's span is in lengths of a bounded parameter's range: a plane's unit box -/// is only a chart, so a plate thousands of millimetres across (its loops thousands of units -/// wide) still meshes, as does a long cylinder. -#[test] -fn large_faces_still_mesh() { - let plate = crate::box_solid(Vec3::new(-2500.0, -2500.0, 0.0), Vec3::new(2500.0, 2500.0, 3.0)).unwrap(); - let rod = crate::cylinder(Vec3::ZERO, Vec3::Z, 0.5, 3000.0).unwrap(); - for body in [plate, rod] { - assert!(!body.tessellate_with(0.05, true).unwrap().triangles.is_empty()); - assert_eq!(body.unmeshed_faces(), 0); - } -} diff --git a/crates/kernel/src/chamfer_sides_curved_tests.rs b/crates/kernel/src/chamfer_sides_curved_tests.rs index 53e97e93d..6486162d5 100644 --- a/crates/kernel/src/chamfer_sides_curved_tests.rs +++ b/crates/kernel/src/chamfer_sides_curved_tests.rs @@ -5,10 +5,10 @@ use std::f64::consts::PI; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::build::{box_solid, extrude, extrude_tapered}; -use crate::{Body, BoolOp, ChamferSide, KernelError, boolean, chamfer, chamfer_sides}; +use crate::{Body, BoolOp, ChamferSide, boolean, chamfer, chamfer_sides}; const TOL: f64 = 1e-3; @@ -167,7 +167,7 @@ fn boss_foot_fills() { fn cone_rim() { let taper = 10f64.to_radians(); let region = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 10.0, 0.0), holes: vec![] }; - let f = extrude_tapered(&Plane::XY, ®ion, 20.0, 1.0, -taper).unwrap(); + let f = extrude_tapered(&Plane::XY, ®ion, 20.0, 1.0, -taper, crate::DraftCorner::default()).unwrap(); let base = volume(&f); let top = 10.0 - 20.0 * taper.tan(); let rim = Vec3::new(top, 0.0, 20.0); @@ -193,30 +193,13 @@ fn cone_rim() { assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out)); } +/// A cylinder's seam is smooth: no edge there to chamfer. (The rim chamfers too large for the +/// faces, past the bottom, past the wall and of an elliptical rim are the rig's +/// fillets/2893-chamfer-* cases; the seam's place is the kernel's, so it stays here.) #[test] fn too_large_or_unsupported_is_refused() { let c = cylinder(0.0); - // Across the whole top: the cone would end in a point. - assert!(chamfer_sides(&c, &[RIM], 10.0, ChamferSide::Distance(3.0), false).is_err()); - assert!(chamfer_sides(&c, &[RIM], 12.0, ChamferSide::Distance(3.0), false).is_err()); - // Down past the bottom. - assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(25.0), false).is_err()); - // An angle that runs past the wall. - assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(PI / 2.0 + 0.01), false).is_err()); - // A cylinder's seam is smooth: nothing to chamfer. assert!(chamfer_sides(&c, &[Vec3::new(10.0, 0.0, 10.0)], 2.0, ChamferSide::Distance(3.0), false).is_err()); - // A tilted cylinder cut flat: its rim on the cut is an ellipse, which the loop chamfer does - // not take. Refused as not supported, never a wrong solid. - let tilted = crate::build::cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::new(1.0, 0.0, 2.0), 5.0, 40.0).unwrap(); - let cut = box_solid(Vec3::new(-50.0, -50.0, 10.0), Vec3::new(50.0, 50.0, 50.0)).unwrap(); - let t = boolean(&tilted, &cut, BoolOp::Cut).unwrap().unwrap(); - let solid = t.deep_copy(); - let rim = crate::body::Body::unique_edges(&solid).iter().filter_map(crate::blend::edge_mid).find(|m| (m.z - 10.0).abs() < 1e-6).unwrap(); - match chamfer_sides(&t, &[rim], 1.0, ChamferSide::Distance(2.0), false) { - Err(KernelError::Failed(m)) => assert!(m.starts_with("not supported yet"), "{m}"), - Err(e) => panic!("{e}"), - Ok(_) => panic!("an unequal chamfer of an elliptical rim was built"), - } } /// The top loop of a plate with rounded corners: lines and quarter circles, planar and diff --git a/crates/kernel/src/clearance.rs b/crates/kernel/src/clearance.rs deleted file mode 100644 index 3a505e3aa..000000000 --- a/crates/kernel/src/clearance.rs +++ /dev/null @@ -1,377 +0,0 @@ -//! Has a face room to move? -//! -//! Coincident faces are pushed apart before a boolean (see [`crate::coplanar`]). That leaves -//! the result as it was only where the space a face moves through holds nothing of the other -//! body (a cut), or nothing but its material (a join). A [`Clearance`] decides that on the -//! other body's faces: every triangle of its mesh is clipped against that space, so a wall, a -//! rib or a hole anywhere in it is found. Sample points miss what lies between them. -//! -//! A cut's or join's tool grown past the faces it lies on, to keep coincident faces out of its -//! boolean, is asked the same way (in the document's evaluation): it may gain only empty space -//! (a cut) or material (a join). - -use std::collections::HashMap; - -use solidcraft_geom::{Aabb3, Mesh, Vec3}; -use truck_modeling as mt; - -use crate::body::Body; -use crate::offset::{Surf, surf_of}; - -/// How a body's material sits in a region of space. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Occupancy { - /// The region holds none of it. - Empty, - /// The region lies wholly in it. - Full, - /// A face reaches into the region, or may: no answer. - Mixed, -} - -/// A convex region: the points `p` with `n · p <= d` for every side `(n, d)`, `n` a unit vector -/// pointing out of it. -struct Convex(Vec<(Vec3, f64)>); - -impl Convex { - /// The prism a triangle sweeps when it moves along the unit vector `along` (not in its - /// plane) from the distance `lo` to `hi`, its sides moved out by `margin` (in, when - /// negative). `None` for a triangle without area or an empty interval. - fn swept(tri: [Vec3; 3], along: Vec3, margin: f64, lo: f64, hi: f64) -> Option { - let [a, b, c] = tri; - let centre = (a + b + c) / 3.0; - if hi <= lo || !(margin + lo + hi).is_finite() || (b - a).cross(c - a).dot(along).abs() < 1e-300 { - return None; - } - let mut sides = Vec::with_capacity(5); - for (p, q) in [(a, b), (b, c), (c, a)] { - let mut out = (q - p).cross(along).normalized()?; - if out.dot(centre - p) > 0.0 { - out = -out; - } - sides.push((out, out.dot(p) + margin)); - } - let base = along.dot(a); - sides.push((along, base + hi)); - sides.push((-along, -(base + lo))); - Some(Convex(sides)) - } - - fn contains(&self, p: Vec3) -> bool { - self.0.iter().all(|(n, d)| n.dot(p) <= *d) - } - - /// Does the triangle reach into the region? Touching its boundary counts. - fn meets(&self, tri: [Vec3; 3]) -> bool { - // A side with the whole triangle beyond it settles most triangles at once. - if self.0.iter().any(|(n, d)| tri.iter().all(|p| n.dot(*p) > *d)) { - return false; - } - // What the sides leave of the triangle, one side after the other. - let mut left: Vec = tri.to_vec(); - let mut next: Vec = Vec::with_capacity(tri.len() + self.0.len()); - for (n, d) in &self.0 { - let Some(&last) = left.last() else { return false }; - next.clear(); - let (mut p, mut sp) = (last, n.dot(last) - d); - for &q in &left { - let sq = n.dot(q) - d; - if (sp < 0.0 && sq > 0.0) || (sp > 0.0 && sq < 0.0) { - next.push(p + (q - p) * (sp / (sp - sq))); - } - if sq <= 0.0 { - next.push(q); - } - (p, sp) = (q, sq); - } - std::mem::swap(&mut left, &mut next); - } - !left.is_empty() - } -} - -/// How far a face can stand off its triangles, seen from a region along one direction. -#[derive(Clone, Copy)] -enum Reach { - /// Not at all: a planar face, a facet of a mesh body. - Exact, - /// Sideways only: a wall of straight lines along the direction (a hole drilled along it). - Sideways, - /// By the chord error, any way. - Around, - /// By the chord error, to one side: a face of a cylinder, a cone or a sphere lies beyond its - /// triangles seen from the material when it is `convex`, seen from outside when it is not. - Beyond { convex: bool }, - /// It ends before the region begins or begins past its end (a fillet running into the - /// plane the region starts from). - Never, -} - -/// A body's faces, for telling how its material sits in the space a face moves through. -pub struct Clearance<'a> { - body: &'a Body, - mesh: Mesh, - /// How far a curved face may stand off its triangles. - sag: f64, - tol: f64, - /// Whether curved faces are judged by their exact bounds (see [`Clearance::with_exact_bounds`]). - exact: bool, -} - -/// Pairs of triangles one question may compare; beyond it there is no answer. -const MAX_PAIRS: usize = 2_000_000; - -impl<'a> Clearance<'a> { - /// `chord`: the chord error of the mesh the body is asked on. - pub fn new(body: &'a Body, chord: f64) -> Option> { - let mesh = body.tessellate_with(chord, true).ok()?; - (!mesh.triangles.is_empty()).then(|| Clearance { body, mesh, sag: 2.0 * chord, tol: (body.size() * 1e-7).max(1e-9), exact: false }) - } - - /// Judge curved faces by their exact bounds where `clear_of_slab` is asked, not by the chord error each way. A B-spline or NURBS - /// face lies in the hull of its control net, so a face whose net ends before a region begins (a loft's side running out in the - /// plane the region starts from) can't reach into it, however its triangles stand off it. A face of a sphere or a cylinder - /// stands off its triangles away from the centre or the axis only, so a triangle that lies clear of the region and leans away - /// from it is clear (a dome standing on the plane the region starts from). Without this such a face counts as reaching in by - /// the chord error. - pub(crate) fn with_exact_bounds(mut self, on: bool) -> Self { - self.exact = on; - self - } - - /// How the body's material sits in the space that `faces` move through when they go along - /// the unit vector `along` from the distance `lo` to `hi`. `faces`: the triangles of - /// planar faces square to `along`, each with how far its face reaches past it sideways - /// (negative: the triangle's sides are drawn in, so that faces lying against them don't - /// count). `Mixed` as soon as a face of the body reaches into that space. - pub fn swept(&self, faces: &[([Vec3; 3], f64)], along: Vec3, lo: f64, hi: f64) -> Occupancy { - let Some((first, _)) = faces.first() else { return Occupancy::Mixed }; - let base = along.dot(first[0]); - // The body's triangles near that space. - let mut space = Aabb3::EMPTY; - let mut pad = self.sag; - for (tri, margin) in faces { - pad = pad.max(self.sag + margin); - tri.iter().for_each(|p| [lo - self.sag, hi + self.sag].iter().for_each(|s| space.add(*p + along * *s))); - } - let (min, max) = (space.min - Vec3::new(pad, pad, pad), space.max + Vec3::new(pad, pad, pad)); - let outside = |tri: &[Vec3; 3]| { - let all = |f: &dyn Fn(Vec3) -> bool| tri.iter().all(|p| f(*p)); - all(&|p| p.x < min.x) - || all(&|p| p.x > max.x) - || all(&|p| p.y < min.y) - || all(&|p| p.y > max.y) - || all(&|p| p.z < min.z) - || all(&|p| p.z > max.z) - }; - let mut near: Vec<(u32, [Vec3; 3])> = Vec::new(); - for (t, face) in self.mesh.triangles.iter().zip(&self.mesh.tri_face) { - let Some(tri) = self.mesh.tri(t) else { return Occupancy::Mixed }; - if !outside(&tri) { - near.push((*face, tri)); - } - } - if faces.len().saturating_mul(near.len()) > MAX_PAIRS { - return Occupancy::Mixed; - } - let inside = self.mesh.inside_index(); - let mut reach: HashMap = HashMap::new(); - let mut all = None; - for (tri, margin) in faces { - let prism = |side: f64, end: f64| Convex::swept(*tri, along, margin + side, lo - end, hi + end); - let probe = (tri[0] + tri[1] + tri[2]) / 3.0 + along * ((lo + hi) * 0.5); - // A sliver thinner than its margins covers nothing that its neighbours don't. - let Some(tight) = prism(0.0, 0.0).filter(|p| p.contains(probe)) else { continue }; - let (Some(sideways), Some(around)) = (prism(self.sag, 0.0), prism(self.sag, self.sag)) else { return Occupancy::Mixed }; - // With no face in it, the prism is all material or all empty. - let here = if inside.contains(probe) { Occupancy::Full } else { Occupancy::Empty }; - let reaches = |(face, t): &(u32, [Vec3; 3])| { - around.meets(*t) - && match *reach.entry(*face).or_insert_with(|| self.reach(*face, along, base + lo, base + hi)) { - Reach::Exact => tight.meets(*t), - Reach::Sideways => sideways.meets(*t), - // Its triangles lie between the prism and the face. - Reach::Beyond { convex } if convex == (here == Occupancy::Full) => tight.meets(*t), - Reach::Around | Reach::Beyond { .. } => true, - Reach::Never => false, - } - }; - if near.iter().any(reaches) { - return Occupancy::Mixed; - } - if all.is_some_and(|seen| seen != here) { - return Occupancy::Mixed; - } - all = Some(here); - } - all.unwrap_or(Occupancy::Mixed) - } - - /// Has the body nothing between the heights `lo` and `hi` above the plane `n · p = d` (`n` - /// a unit vector), anywhere? - pub(crate) fn clear_of_slab(&self, n: Vec3, d: f64, lo: f64, hi: f64) -> bool { - let mut reach: HashMap = HashMap::new(); - let mut round: HashMap> = HashMap::new(); - self.mesh.triangles.iter().zip(&self.mesh.tri_face).all(|(t, face)| { - let Some(tri) = self.mesh.tri(t) else { return false }; - // How far the face may stand off its triangle towards larger and towards smaller heights. - let (up, down) = match *reach.entry(*face).or_insert_with(|| self.reach(*face, n, d + lo, d + hi)) { - Reach::Never => return true, - Reach::Around => (self.sag, self.sag), - Reach::Beyond { .. } => match self.exact.then(|| round.entry(*face).or_insert_with(|| self.round_of(*face))).and_then(|s| s.as_ref()) - { - Some(s) => self.bulge(s, (tri[0] + tri[1] + tri[2]) / 3.0, n), - None => (self.sag, self.sag), - }, - Reach::Exact | Reach::Sideways => (0.0, 0.0), - }; - let heights = tri.map(|p| n.dot(p) - d); - heights.iter().all(|s| s + up < lo) || heights.iter().all(|s| s - down > hi) - }) - } - - /// The round surface (sphere, cylinder, cone, torus) a face lies on, if it is one. - fn round_of(&self, face: u32) -> Option { - let f = self.body.solid.face_iter().nth(face as usize)?; - surf_of(f, self.tol * 100.0) - } - - /// How far the surface may stand off a triangle with its centroid at `p`, towards larger and towards smaller heights along `n`: a - /// sphere or a cylinder lies radially outward from its triangles, within the chord error. - fn bulge(&self, s: &Surf, p: Vec3, n: Vec3) -> (f64, f64) { - let radial = match *s { - Surf::Sphere { c, .. } => p - c, - Surf::Cylinder { o, a, .. } => (p - o) - a * (p - o).dot(a), - _ => return (self.sag, self.sag), - }; - let Some(out) = radial.normalized() else { return (self.sag, self.sag) }; - let lean = out.dot(n); - (self.sag * lean.max(0.0), self.sag * (-lean).max(0.0)) - } - - /// How the face's triangles stand for it in a region between the heights `lo` and `hi` - /// along `along` (measured as `along · p`). - fn reach(&self, face: u32, along: Vec3, lo: f64, hi: f64) -> Reach { - if self.body.is_mesh() { - return Reach::Exact; - } - crate::guard("face reach", || { - let Some(f) = self.body.solid.face_iter().nth(face as usize) else { return Ok(Reach::Around) }; - let surface = f.oriented_surface(); - if matches!(surface, mt::Surface::Plane(_)) { - return Ok(Reach::Exact); - } - if self.exact - && let Some((least, greatest)) = crate::planar_faces::control_net_span(&surface, along) - && (greatest <= lo || least >= hi) - { - return Ok(Reach::Never); - } - let round = surf_of(f, self.tol * 100.0); - // A flat face stored otherwise (a revolve's end: a line swept round its axis) is - // a plane all the same: its triangles lie in it. - if matches!(round, Some(Surf::Plane { .. })) { - return Ok(Reach::Exact); - } - let straight = matches!(round, Some(Surf::Cylinder { a, .. }) if a.dot(along).abs() > 1.0 - 1e-12) - || crate::prism::wall_along(&surface, along, self.tol * 10.0, &mut 262_144); - Ok(if straight { - Reach::Sideways - } else if round.and_then(|s| span(&s, along)).is_some_and(|(s0, s1)| s1 <= lo || s0 >= hi) { - Reach::Never - } else if let Some(Surf::Cylinder { convex, .. } | Surf::Cone { convex, .. } | Surf::Sphere { convex, .. }) = round { - Reach::Beyond { convex } - } else { - Reach::Around - }) - }) - .unwrap_or(Reach::Around) - } -} - -/// The whole extent of a round surface along `along`, where it has one. -fn span(s: &Surf, along: Vec3) -> Option<(f64, f64)> { - let about = |c: Vec3, r: f64| Some((along.dot(c) - r.abs(), along.dot(c) + r.abs())); - match *s { - Surf::Cylinder { o, a, r, .. } if a.dot(along).abs() < 1e-9 => about(o, r), - Surf::Sphere { c, r, .. } => about(c, r), - Surf::Torus { o, a, h, r, .. } if a.dot(along).abs() > 1.0 - 1e-12 => about(o + a * h, r), - _ => None, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{BoolOp, boolean, box_solid, cylinder, fillet}; - - fn clearance(body: &Body) -> Clearance<'_> { - Clearance::new(body, body.size() * 2e-4).unwrap() - } - - /// The top face of a 200 x 100 x 20 block between x = `x0` and `x1`, y = 10 and 90, as two - /// triangles with their sides drawn in by 1e-4. - fn top(x0: f64, x1: f64) -> Vec<([Vec3; 3], f64)> { - let p = |x: f64, y: f64| Vec3::new(x, y, 20.0); - vec![([p(x0, 10.0), p(x1, 10.0), p(x1, 90.0)], -1e-4), ([p(x0, 10.0), p(x1, 90.0), p(x0, 90.0)], -1e-4)] - } - - /// The space over a block's top face is empty and the space under it is material, up to - /// the smallest thing that stands in it, wherever that is. - #[test] - fn the_space_a_face_moves_through_is_empty_or_material_until_something_stands_in_it() { - let block = box_solid(Vec3::ZERO, Vec3::new(200.0, 100.0, 20.0)).unwrap(); - let c = clearance(&block); - assert_eq!(c.swept(&top(10.0, 190.0), Vec3::Z, 1e-4, 3.0), Occupancy::Empty); - assert_eq!(c.swept(&top(10.0, 190.0), -Vec3::Z, 1e-4, 3.0), Occupancy::Full); - // 25 down is through the bottom face (the block is 20 thick); 210 is past its side x = 200. - assert_eq!(c.swept(&top(10.0, 190.0), -Vec3::Z, 1e-4, 25.0), Occupancy::Mixed); - assert_eq!(c.swept(&top(10.0, 210.0), -Vec3::Z, 1e-4, 3.0), Occupancy::Mixed); - assert_eq!(c.swept(&[], Vec3::Z, 1e-4, 3.0), Occupancy::Mixed); - assert!(c.clear_of_slab(Vec3::Z, 20.0, 1e-4, 3.0) && !c.clear_of_slab(Vec3::Z, 20.0, -3.0, -1e-4)); - // A pin 0.4 x 0.4 on the top face, at x = 137.3 to 137.7: in the way of what covers it only. - let pin = box_solid(Vec3::new(137.3, 61.1, 20.0), Vec3::new(137.7, 61.5, 26.0)).unwrap(); - let pinned = boolean(&block, &pin, BoolOp::Union).unwrap().unwrap(); - let c = clearance(&pinned); - assert_eq!(c.swept(&top(10.0, 190.0), Vec3::Z, 1e-4, 3.0), Occupancy::Mixed); - assert_eq!(c.swept(&top(10.0, 137.0), Vec3::Z, 1e-4, 3.0), Occupancy::Empty); - assert!(!c.clear_of_slab(Vec3::Z, 20.0, 1e-4, 3.0) && c.clear_of_slab(Vec3::Z, 20.0, 6.0 + 1e-4, 9.0)); - // A 4 mm hole through the block at x = 60: no material all the way under what covers it. - let hole = cylinder(Vec3::new(60.0, 50.0, -5.0), Vec3::Z, 2.0, 30.0).unwrap(); - let holed = boolean(&block, &hole, BoolOp::Cut).unwrap().unwrap(); - let c = clearance(&holed); - assert_eq!(c.swept(&top(10.0, 190.0), -Vec3::Z, 1e-4, 3.0), Occupancy::Mixed); - assert_eq!(c.swept(&top(70.0, 190.0), -Vec3::Z, 1e-4, 3.0), Occupancy::Full); - } - - /// Round faces that end in the plane a face lies in leave the space beyond it free: a - /// hole's wall, a fillet running into the top face. A round face that rises into that space - /// by less than its chords show does not. - #[test] - fn round_faces_ending_at_the_plane_leave_the_space_beyond_it_free() { - let block = box_solid(Vec3::ZERO, Vec3::new(200.0, 100.0, 20.0)).unwrap(); - let hole = cylinder(Vec3::new(60.0, 50.0, -5.0), Vec3::Z, 8.0, 30.0).unwrap(); - let holed = boolean(&block, &hole, BoolOp::Cut).unwrap().unwrap(); - // The fillet (r = 4) along the edge y = 0 of the top face ends on the line y = 4, z = 20. - let rounded = fillet(&holed, &[Vec3::new(100.0, 0.0, 20.0)], 4.0).unwrap(); - let c = clearance(&rounded); - // The top face from x = `x0` to 190 and y = `y0` to 90. - let rect = |x0: f64, y0: f64| { - let p = |x: f64, y: f64| Vec3::new(x, y, 20.0); - vec![([p(x0, y0), p(190.0, y0), p(190.0, 90.0)], -1e-4), ([p(x0, y0), p(190.0, 90.0), p(x0, 90.0)], -1e-4)] - }; - assert_eq!(c.swept(&rect(10.0, -10.0), Vec3::Z, 1e-4, 3.0), Occupancy::Empty); - assert!(c.clear_of_slab(Vec3::Z, 20.0, 1e-4, 3.0)); - // Under the top face the fillet is in the way from its tangent line y = 4 down (and no - // further: its chords lie inside it), the hole from x = 68 down. - assert_eq!(c.swept(&rect(80.0, 4.0), -Vec3::Z, 1e-4, 3.0), Occupancy::Full); - assert_eq!(c.swept(&rect(80.0, 3.9), -Vec3::Z, 1e-4, 3.0), Occupancy::Mixed); - assert_eq!(c.swept(&rect(60.0, 5.0), -Vec3::Z, 1e-4, 3.0), Occupancy::Mixed); - // A bar lying along x (axis at z = 12): its top ends 0.05 um short of where the space - // begins (z = 20.0001), then reaches 0.9 um into it. - for (radius, want) in [(8.00005, Occupancy::Empty), (8.001, Occupancy::Mixed)] { - let bar = cylinder(Vec3::new(20.0, 50.0, 12.0), Vec3::X, radius, 160.0).unwrap(); - assert_eq!(clearance(&bar).swept(&top(30.0, 150.0), Vec3::Z, 1e-4, 3.0), want, "radius {radius}"); - } - } -} diff --git a/crates/kernel/src/coaxial_overlap.rs b/crates/kernel/src/coaxial_overlap.rs deleted file mode 100644 index c7331f18b..000000000 --- a/crates/kernel/src/coaxial_overlap.rs +++ /dev/null @@ -1,686 +0,0 @@ -//! The shared volume of a pin in a hole of (nearly) its own size whose axis is a hair off the -//! hole's (parts placed from rounded coordinates), or on it: a pin seated line to line. -//! -//! The pin's wall and the hole's wall then meet along two lines where they are all but tangent, -//! or lie on one another, which the boolean cannot intersect, and the facets of the two walls pass through each other -//! by less than the boolean's sampled shortcuts can see. So the overlap is worked out in two -//! parts instead. The pin's wall is moved off the hole's by a clear step (`offset_body`; where a -//! blend running into the pin's wall keeps it from moving, the hole's wall is moved instead) and the -//! bodies are intersected as they then are, which the boolean can do: narrowed, that gives the -//! overlap away from the walls (the core). In the band the move swept, what the two walls -//! share is a crescent in every section, whose area follows from the two circles alone. The -//! band is assumed to hold nothing but the two walls; that is checked by intersecting with the -//! pin widened by half the step and by the whole step, whose volumes must come out as the core -//! plus the crescents those wider circles give. Where they don't (a cross hole through the -//! band, a hole that is not round all the way, a pin end inside the hole), the overlap is not -//! answered here and the caller takes the general boolean. - -use solidcraft_geom::{Aabb3, UnitVec3, Vec3}; - -use crate::body::Body; -use crate::{BoolOp, FaceSurface}; - -/// The overlap of two bodies with a pin of one in a hole of the other, worked out as above. -#[derive(Clone, Debug)] -pub struct CoaxialOverlap { - pub volume: f64, - /// Approximate: the core's area plus the crescents' walls and ends. - pub area: f64, - pub centroid: Vec3, - pub bbox: Aabb3, - /// The largest offset between a pin's axis and its hole's, and the length they share. - pub offset: f64, - pub length: f64, -} - -/// Largest axis offset plus radius difference handled, as a share of the radius. -const NEAR: f64 = 0.01; -/// The step the pin's wall is moved by, as a share of its radius. -const STEP: f64 = 0.1; -/// The tries each intersection here gets: with a wall moved clear it takes one or two, and a -/// few more where a flush face is pulled back or the tool is nudged by a hair; one that needs -/// more than that meets something this work does not cover. -const ATTEMPTS: usize = 10; - -/// The faces of one body on one cylinder, the side its material is on and their extent along -/// the axis. -#[derive(Clone, Debug)] -struct Wall { - faces: Vec, - origin: Vec3, - axis: UnitVec3, - radius: f64, - /// Material inside the cylinder (a pin), not outside it (a hole). - boss: bool, - /// Intervals along `axis` from `origin`, one per face. - spans: Vec<(f64, f64)>, -} - -/// A pin of one body (`pin_in_a`) in a hole of the other, and the length they share. -#[derive(Clone, Debug)] -struct Pair { - pin: Wall, - pin_in_a: bool, - hole: Wall, - /// The hole's axis seen from the pin's, across it, and how far. - toward: Vec3, - offset: f64, - /// Where they share length along the pin's axis. - shared: Vec<(f64, f64)>, - step: f64, -} - -/// The overlap of `a` and `b` when a pin of one sits in a hole of the other on nearly the same -/// cylinder (axes parallel, offset plus radius difference within 1 % of the radius, none for a -/// pin seated line to line), worked out as the module says. `None` when there is no such pin, or the -/// bodies hold more than the pin and the hole where the work assumes they don't: the caller -/// then takes the general boolean. -pub fn coaxial_overlap(a: &Body, b: &Body) -> Option { - if a.is_mesh() || b.is_mesh() { - return None; - } - // The boolean that takes the core can fail in one order of the bodies and not the other. - crate::guard("near-coaxial overlap", || Ok(overlap(a, b).or_else(|| overlap(b, a)))).ok().flatten() -} - -/// Whether a cylinder of `a` and one of `b` are on one cylinder or nearly (what -/// [`coaxial_overlap`] asks first, from the faces' surfaces alone): a cheap test for whether -/// it is worth preparing the bodies for it. `Some(true)` when every such pair is on one cylinder -/// within the kernel's same-surface tolerance, which the boolean takes as one wall; `Some(false)` -/// when one is a hair off, which it cannot intersect and may even pass as clear. -pub fn coaxial_candidate(a: &Body, b: &Body) -> Option { - if a.is_mesh() || b.is_mesh() { - return None; - } - crate::guard("near-coaxial candidate", || { - let same = same_surface(a.size().max(b.size())); - let (ca, cb) = (cylinders(a), cylinders(b)); - let mut found = None; - for x in &ca { - for y in &cb { - if x.axis.dot(y.axis).abs() <= 1.0 - 1e-9 { - continue; - } - if let Some((_, offset)) = near(x, y) { - let one = offset + (x.radius - y.radius).abs() <= same; - found = Some(found.unwrap_or(true) && one); - } - } - } - Ok(found) - }) - .ok() - .flatten() -} - -/// The distance within which the kernel takes two surfaces as one, for bodies of `size`. -fn same_surface(size: f64) -> f64 { - (size * 1e-7).max(1e-9) * 10.0 -} - -fn overlap(a: &Body, b: &Body) -> Option { - let size = a.size().max(b.size()); - if !(size.is_finite() && size > 0.0) { - return None; - } - // The same surface as the kernel takes it elsewhere: walls that close are one wall. - let same = same_surface(size); - // Meshed only when two cylinders are close enough to be asked about. - let (ca, cb) = (cylinders(a), cylinders(b)); - let close = |x: &Wall, y: &Wall| x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && near(x, y).is_some(); - if !ca.iter().any(|x| cb.iter().any(|y| close(x, y))) { - return None; - } - // A wall that runs once round along a seam edge (as STEP files have them) is cut in two - // first: the boolean cannot always intersect it whole. - let (sa, sb) = (crate::step_in::split::split_seams(a), crate::step_in::split::split_seams(b)); - let (ca, cb) = match (&sa, &sb) { - (None, None) => (ca, cb), - _ => (sa.as_ref().map_or(ca, cylinders), sb.as_ref().map_or(cb, cylinders)), - }; - let (a, b) = (sa.as_ref().unwrap_or(a), sb.as_ref().unwrap_or(b)); - let (wa, wb) = (walls(a, ca, same)?, walls(b, cb, same)?); - let mut pairs = Vec::new(); - for x in &wa { - for y in &wb { - if x.axis.dot(y.axis).abs() <= 1.0 - 1e-9 { - continue; - } - let (pin, hole, pin_in_a) = match (x.boss, y.boss) { - (true, false) => (x, y, true), - (false, true) => (y, x, false), - // Two pins or two holes on nearly one cylinder, side by side along it: not this - // case. Apart along the axis (a screw's head beside a bush of its radius), they - // don't meet. - _ if near(x, y).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None, - _ => continue, - }; - let Some((toward, offset)) = near(pin, hole) else { continue }; - let shared = intersect(&union(&pin.spans), &union(&project(hole, pin))); - if total(&shared) <= same { - continue; - } - let step = (pin.radius * STEP).min(size * 0.02); - // Within the kernel's same-surface tolerance the two walls are one: no crescent. - let mut hole = hole.clone(); - let offset = if offset + (pin.radius - hole.radius).abs() <= same { - hole.radius = pin.radius; - 0.0 - } else { - offset - }; - pairs.push(Pair { pin: pin.clone(), pin_in_a, hole, toward, offset, shared, step }); - } - } - if pairs.is_empty() { - return None; - } - // A pin's face flush against the other body (a rivet's head on the sheet) touches it over - // an area, which the boolean cannot always take: it is pulled back off it by a little. - // Only material outside the other body goes, so the overlap is the same. - let back = pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 0.05; - let flat = (flush(a, b, same, back), flush(b, a, same, back), back); - // The pin's wall is moved where its neighbours let it; where they don't (a blend running - // into it), the hole's wall is moved away from the pin instead. - let stuck = std::cell::Cell::new(false); - answer(a, b, &pairs, size, &flat, false, &stuck).or_else(|| if stuck.get() { answer(a, b, &pairs, size, &flat, true, &stuck) } else { None }) -} - -/// The overlap of the `pairs` worked out with each pin's wall moved by steps, or each hole's -/// (`move_hole`); `stuck` set when a body could not be moved. `flat` holds the faces of `a` -/// and of `b` that touch the other flat, and how far they are pulled back off it. -fn answer( - a: &Body, - b: &Body, - pairs: &[Pair], - size: f64, - flat: &(Vec, Vec, f64), - move_hole: bool, - stuck: &std::cell::Cell, -) -> Option { - let (fa, fb, back) = (&flat.0, &flat.1, flat.2); - // The pin's and the hole's radius with the moved wall `k` steps toward the other. - let radii = |p: &Pair, k: f64| if move_hole { (p.pin.radius, p.hole.radius - p.step * k) } else { (p.pin.radius + p.step * k, p.hole.radius) }; - // A wall's faces move together: one step for each of them (a wall does not repeat across - // pairs unless one pin is near two holes, which the check below then answers). - let shared_at = |k: f64| -> Option<(f64, Option)> { - let moved = |body: &Body, in_a: bool| -> Option { - let mine: Vec<(&Wall, f64)> = pairs - .iter() - .filter_map(|p| match (move_hole, p.pin_in_a == in_a) { - (false, true) => Some((&p.pin, p.step)), - (true, false) => Some((&p.hole, p.step)), - _ => None, - }) - .collect(); - if mine.is_empty() { - return Some(body.clone()); - } - let flush = if in_a { fa } else { fb }; - let shift = |i: usize, _| match mine.iter().find(|(w, _)| w.faces.contains(&i)) { - Some((_, step)) => step * k, - None if flush.contains(&i) => -back, - None => 0.0, - }; - let m = crate::offset::offset_body(body, shift).ok().filter(|m| m.validity().is_empty()); - if m.is_none() { - stuck.set(true); - } - m - }; - let (ma, mb) = (moved(a, true)?, moved(b, false)?); - let (r, report) = - crate::capture_boolean_diagnostics(|| crate::ops::with_attempt_budget(ATTEMPTS, || crate::ops::boolean(&ma, &mb, BoolOp::Intersect))); - // The core is the answer and must be exact. The wider pins only check the band, to - // 2 % of what it gains: a tool nudged by a hair of the step there is as good. - let nudge = if k > 0.0 { pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 1e-2 } else { 0.0 }; - if report.unverified().is_some() || !altered_by_at_most(&report, nudge, size) { - return None; - } - match r.ok()? { - None => Some((0.0, None)), - Some(body) => Some((crate::measure(&body).ok()?.volume, Some(body))), - } - }; - // The crescents' area along each pair with the moved walls `k` steps toward each other. - let crescent_at = |p: &Pair, k: f64| { - let (r, h) = radii(p, k); - crescent(r, h, p.offset).area - }; - let crescents = |k: f64| -> f64 { pairs.iter().map(|p| total(&p.shared) * crescent_at(p, k)).sum() }; - let (core, core_body) = shared_at(-1.0)?; - for k in [0.5, 1.0] { - let (v, _) = shared_at(k)?; - let gain = crescents(k) - crescents(-1.0); - if !((v - core - gain).abs() <= 0.002 * gain + 1e-4 * v.abs() + 1e-12 * size.powi(3)) { - return None; - } - } - // The band held the two walls only: the overlap is the core plus the crescents. - let mut volume = core; - let mut moment = Vec3::ZERO; - let mut area = 0.0; - let mut bbox = Aabb3::EMPTY; - if let Some(body) = &core_body - && let Ok(m) = crate::measure(body) - { - moment = m.centroid * m.volume; - area = m.area; - bbox = m.bbox; - volume = m.volume; - } - for p in pairs { - let c = crescent(p.pin.radius, p.hole.radius, p.offset); - let length = total(&p.shared); - // Less what the moved walls already shared (nothing, unless the hole is the smaller). - let v = length * (c.area - crescent_at(p, -1.0)); - let mid = p.shared.iter().map(|(s, t)| (s + t) * 0.5 * (t - s)).sum::() / length; - let side = p.toward.cross(p.pin.axis); - moment += (p.pin.origin + p.pin.axis * mid + p.toward * c.centroid) * v; - volume += v; - area += p.shared.len() as f64 * 2.0 * c.area + length * c.perimeter; - for (s, t) in &p.shared { - for q in crescent_outline(p.pin.radius, p.hole.radius, p.offset) { - let at = p.pin.origin + p.toward * q.0 + side * q.1; - bbox.add(at + p.pin.axis * *s); - bbox.add(at + p.pin.axis * *t); - } - } - } - let centroid = if volume > 0.0 { moment / volume } else { bbox.center() }; - let offset = pairs.iter().map(|p| p.offset).fold(0.0, f64::max); - let length = pairs.iter().map(|p| total(&p.shared)).sum(); - Some(CoaxialOverlap { volume: volume.max(0.0), area, centroid, bbox, offset, length }) -} - -/// Whether every retry of a boolean that can change its result moved the tool by at most -/// `limit` (a rotation counted at the bodies' `size` from its pivot): none for a `limit` of 0. -fn altered_by_at_most(report: &crate::BooleanDiagnostics, limit: f64, size: f64) -> bool { - !report.truncated - && report - .events - .iter() - .filter(|e| e.strategy.alters_result()) - .all(|e| e.strategy == crate::BooleanStrategy::ToolNudge && limit > 0.0 && e.translation_mm + e.rotation_rad * size <= limit) -} - -/// The pin's offset to the hole, when the two are on one cylinder or nearly: the unit direction -/// from the pin's axis to the hole's (any, for one axis) and the distance. -fn near(pin: &Wall, hole: &Wall) -> Option<(Vec3, f64)> { - let d = hole.origin - pin.origin; - let across = d - pin.axis * d.dot(pin.axis); - let offset = across.len(); - let gap = (pin.radius - hole.radius).abs(); - if !(offset + gap <= NEAR * pin.radius.min(hole.radius)) { - return None; - } - let toward = across.normalized().unwrap_or_else(|| pin.axis.any_perp()); - Some((toward, offset)) -} - -/// The planar faces of `x` that lie on a face of `y`'s facing the other way, where the two touch -/// flat: on a plane of `y`'s, with `y` just beyond the face and not just behind it (within -/// `depth`, at every sampled facet of it). A face on such a plane elsewhere (a collar's -/// underside inside the other body, level with a pocket's floor) is not one. -fn flush(x: &Body, y: &Body, same: f64, depth: f64) -> Vec { - let planes = |b: &Body| -> Vec<(usize, Vec3, Vec3)> { - (0..b.face_count()) - .filter_map(|i| match crate::face_surface(b, i)? { - FaceSurface::Plane { normal, point } => Some((i, normal.vec(), point)), - _ => None, - }) - .collect() - }; - let theirs = planes(y); - let level: Vec<(usize, Vec3)> = planes(x) - .into_iter() - .filter(|(_, n, p)| theirs.iter().any(|(_, m, q)| n.dot(*m) < -1.0 + 1e-9 && (*q - *p).dot(*n).abs() <= same)) - .map(|(i, n, _)| (i, n)) - .collect(); - if level.is_empty() || !(depth.is_finite() && depth > 0.0) { - return Vec::new(); - } - let tol = (x.size().max(y.size()) * 2e-3).max(1e-4); - let (Ok(mx), Ok(my)) = (x.tessellate(tol), y.tessellate(tol)) else { return Vec::new() }; - // At most this many facets of a face are sampled. - const SAMPLES: usize = 64; - level - .into_iter() - .filter(|&(i, n)| { - let centres: Vec = mx - .triangles - .iter() - .zip(&mx.tri_face) - .filter(|(_, f)| **f as usize == i) - .filter_map(|(t, _)| mx.tri(t)) - .filter(|[a, b, c]| (*b - *a).cross(*c - *a).len() > 0.0) - .map(|[a, b, c]| (a + b + c) / 3.0) - .collect(); - let stride = centres.len().div_ceil(SAMPLES).max(1); - !centres.is_empty() && centres.iter().step_by(stride).all(|c| my.contains(*c + n * depth) && !my.contains(*c - n * depth)) - }) - .map(|(i, _)| i) - .collect() -} - -/// The body's cylindrical faces, each as a wall of its own with no side or extent yet. -fn cylinders(b: &Body) -> Vec { - (0..b.face_count()) - .filter_map(|i| match crate::face_surface(b, i)? { - FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => { - Some(Wall { faces: vec![i], origin, axis, radius, boss: false, spans: Vec::new() }) - } - _ => None, - }) - .collect() -} - -/// The cylindrical walls of a body from its `cylinders`: its faces on each cylinder, which side -/// its material is on and where they run along the axis. `None` when the body can't be meshed. -fn walls(b: &Body, cylinders: Vec, same: f64) -> Option> { - let mut out: Vec = Vec::new(); - let mesh = b.tessellate_with((b.size() * 1e-3).max(1e-4), true).ok()?; - for Wall { faces, origin, axis, radius, .. } in cylinders { - let Some(&face) = faces.first() else { continue }; - // Which way the face looks: out of the axis for a pin, toward it for a hole. - let (mut facing, mut lo, mut hi) = (0.0, f64::INFINITY, f64::NEG_INFINITY); - for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) { - if *f as usize != face { - continue; - } - let Some([p, q, r]) = mesh.tri(t) else { continue }; - let c = (p + q + r) / 3.0; - let radial = (c - origin) - axis * (c - origin).dot(axis); - facing += (q - p).cross(r - p).dot(radial); - for x in [p, q, r] { - let s = (x - origin).dot(axis); - lo = lo.min(s); - hi = hi.max(s); - } - } - if !(lo < hi) || facing == 0.0 { - continue; - } - let boss = facing > 0.0; - let wall = Wall { faces: vec![face], origin, axis, radius, boss, spans: vec![(lo, hi)] }; - match out.iter_mut().find(|w| w.boss == boss && on_one_cylinder(w, &wall, same)) { - Some(w) => { - // Where the face's origin lies along the wall's axis; a face whose axis runs the - // other way measures its span backwards from there. - let s = (origin - w.origin).dot(w.axis); - let (a, b) = if axis.dot(w.axis) < 0.0 { (-hi, -lo) } else { (lo, hi) }; - w.faces.push(face); - w.spans.push((a + s, b + s)); - } - None => out.push(wall), - } - } - Some(out) -} - -fn on_one_cylinder(x: &Wall, y: &Wall, same: f64) -> bool { - let d = y.origin - x.origin; - x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && (x.radius - y.radius).abs() < same && (d - x.axis * d.dot(x.axis)).len() < same -} - -/// `wall`'s spans along `onto`'s axis. -fn project(wall: &Wall, onto: &Wall) -> Vec<(f64, f64)> { - let flip = wall.axis.dot(onto.axis) < 0.0; - let s = (wall.origin - onto.origin).dot(onto.axis); - wall.spans.iter().map(|&(lo, hi)| if flip { (s - hi, s - lo) } else { (s + lo, s + hi) }).collect() -} - -/// Sorted, disjoint intervals covering `spans`. -fn union(spans: &[(f64, f64)]) -> Vec<(f64, f64)> { - let mut v: Vec<(f64, f64)> = spans.iter().copied().filter(|(a, b)| a < b).collect(); - v.sort_by(|x, y| x.0.total_cmp(&y.0)); - let mut out: Vec<(f64, f64)> = Vec::with_capacity(v.len()); - for (a, b) in v { - match out.last_mut() { - Some(last) if a <= last.1 => last.1 = last.1.max(b), - _ => out.push((a, b)), - } - } - out -} - -fn intersect(x: &[(f64, f64)], y: &[(f64, f64)]) -> Vec<(f64, f64)> { - let mut out = Vec::new(); - for &(a, b) in x { - for &(c, d) in y { - let (lo, hi) = (a.max(c), b.min(d)); - if lo < hi { - out.push((lo, hi)); - } - } - } - out -} - -fn total(spans: &[(f64, f64)]) -> f64 { - spans.iter().map(|(a, b)| b - a).sum() -} - -/// The part of a disc of radius `pin` outside a disc of radius `hole` whose centre is `offset` -/// away along +x: its area, its centroid's x (y is 0) and its perimeter. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct Crescent { - pub(crate) area: f64, - pub(crate) centroid: f64, - pub(crate) perimeter: f64, -} - -pub(crate) fn crescent(pin: f64, hole: f64, offset: f64) -> Crescent { - use std::f64::consts::PI; - let (r, q, e) = (pin.max(0.0), hole.max(0.0), offset.abs()); - let disc = PI * r * r; - if e >= r + q { - return Crescent { area: disc, centroid: 0.0, perimeter: 2.0 * PI * r }; - } - if e <= (r - q).abs() { - return if q >= r { - Crescent { area: 0.0, centroid: 0.0, perimeter: 0.0 } - } else { - let area = disc - PI * q * q; - Crescent { area, centroid: -PI * q * q * e / area, perimeter: 2.0 * PI * (r + q) } - }; - } - // Half-angles of the lens's two segments, seen from each centre. - let alpha = ((e * e + r * r - q * q) / (2.0 * e * r)).clamp(-1.0, 1.0).acos(); - let beta = ((e * e + q * q - r * r) / (2.0 * e * q)).clamp(-1.0, 1.0).acos(); - let segment = |radius: f64, half: f64| { - let area = radius * radius * (half - half.sin() * half.cos()); - let w = 2.0 * half - (2.0 * half).sin(); - let from_centre = if w > 1e-12 { 4.0 * radius * half.sin().powi(3) / (3.0 * w) } else { radius }; - (area, from_centre) - }; - let (sa, da) = segment(r, alpha); - let (sb, db) = segment(q, beta); - let lens = sa + sb; - let area = (disc - lens).max(0.0); - let moment = -(sa * da + sb * (e - db)); - let centroid = if area > 0.0 { moment / area } else { 0.0 }; - Crescent { area, centroid, perimeter: r * (2.0 * PI - 2.0 * alpha) + q * 2.0 * beta } -} - -/// Points around the crescent's outline (x toward the hole's centre, y across), for its box. -fn crescent_outline(pin: f64, hole: f64, offset: f64) -> Vec<(f64, f64)> { - let (r, q, e) = (pin, hole, offset); - let alpha = if e > 0.0 { ((e * e + r * r - q * q) / (2.0 * e * r)).clamp(-1.0, 1.0).acos() } else { 0.0 }; - let n = 32; - (0..=n) - .map(|i| { - let t = alpha + (2.0 * std::f64::consts::PI - 2.0 * alpha) * f64::from(i) / f64::from(n); - (r * t.cos(), r * t.sin()) - }) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The crescent against the textbook lens of two equal circles, and its limits. - #[test] - fn crescent_matches_the_lens_formula() { - let (r, e) = (3.0f64, 0.01f64); - let lens = 2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt(); - let c = crescent(r, r, e); - assert!((c.area - (std::f64::consts::PI * r * r - lens)).abs() < 1e-12, "{c:?}"); - // Thin: twice the radius times the offset, its centroid π/4 of the radius away from - // the hole's centre, its outline nearly two half circles. - assert!((c.area - 2.0 * r * e).abs() < 1e-6, "{c:?}"); - assert!((c.centroid + std::f64::consts::FRAC_PI_4 * r).abs() < 1e-2, "{c:?}"); - assert!((c.perimeter - 2.0 * std::f64::consts::PI * r).abs() < 1e-3, "{c:?}"); - assert_eq!(crescent(r, r, 0.0).area, 0.0); - // A pin with clearance in its hole shares nothing; a pin wider than its hole a ring. - assert_eq!(crescent(2.99, 3.0, 0.005).area, 0.0); - let ring = crescent(3.01, 3.0, 0.0); - assert!((ring.area - std::f64::consts::PI * (3.01f64.powi(2) - 9.0)).abs() < 1e-12, "{ring:?}"); - } - - /// A 20 x 20 x 5 plate with a hole of radius 3 through it, and a pin of radius `pin` through - /// the hole, `offset` off its axis along X. - fn plate_and_pin(pin: f64, offset: f64) -> (Body, Body) { - let block = crate::box_solid(Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 5.0)).unwrap(); - let drill = crate::cylinder(Vec3::new(0.0, 0.0, -2.0), Vec3::Z, 3.0, 9.0).unwrap(); - let plate = crate::boolean(&block, &drill, BoolOp::Cut).unwrap().unwrap(); - (plate, crate::cylinder(Vec3::new(offset, 0.0, -2.0), Vec3::Z, pin, 9.0).unwrap()) - } - - /// The pin shares a crescent with the plate over the plate's thickness, in either order. - #[test] - fn a_pin_off_its_hole_shares_a_crescent() { - let (plate, pin) = plate_and_pin(3.0, 0.01); - let want = 5.0 * crescent(3.0, 3.0, 0.01).area; - for (x, y) in [(&plate, &pin), (&pin, &plate)] { - let o = coaxial_overlap(x, y).unwrap(); - assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}"); - assert!((o.offset - 0.01).abs() < 1e-9 && (o.length - 5.0).abs() < 1e-9, "{o:?}"); - // The crescent is on the pin's side away from the hole's axis (+X). - assert!(o.centroid.x > 2.0 && o.bbox.min.z > -1e-9 && o.bbox.max.z < 5.0 + 1e-9, "{o:?}"); - } - } - - /// A pin with clearance all round, though off the axis, shares nothing. - #[test] - fn a_pin_with_clearance_shares_nothing() { - let (plate, pin) = plate_and_pin(2.995, 0.003); - let o = coaxial_overlap(&plate, &pin).unwrap(); - assert!(o.volume < 1e-9, "{o:?}"); - } - - /// A slot through the hole's wall where the crescent would be: the band holds more than the - /// two walls, the widened pin says so, and the pair is left to the boolean. - #[test] - fn a_slot_through_the_band_is_left_to_the_boolean() { - let (plate, pin) = plate_and_pin(3.0, 0.01); - let slot = crate::box_solid(Vec3::new(2.5, -1.0, -1.0), Vec3::new(4.0, 1.0, 6.0)).unwrap(); - let slotted = crate::boolean(&plate, &slot, BoolOp::Cut).unwrap().unwrap(); - assert!(coaxial_overlap(&slotted, &pin).is_none()); - // So it is for a pin on the very axis; one far off it isn't asked about. - assert!(coaxial_overlap(&slotted, &plate_and_pin(3.0, 0.0).1).is_none()); - assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.5).1).is_none()); - } - - /// A pin seated line to line, on the hole's very axis: the walls share nothing, and a head - /// sunk 0.2 into the plate's face shares the ring under it. - #[test] - fn a_pin_seated_line_to_line_shares_only_what_its_head_sinks() { - let (plate, pin) = plate_and_pin(3.0, 0.0); - for (x, y) in [(&plate, &pin), (&pin, &plate)] { - let o = coaxial_overlap(x, y).unwrap(); - assert!(o.volume < 1e-9 && o.offset < 1e-9 && (o.length - 5.0).abs() < 1e-9, "{o:?}"); - } - let head = crate::cylinder(Vec3::new(0.0, 0.0, 4.8), Vec3::Z, 5.0, 2.0).unwrap(); - let headed = crate::boolean(&pin, &head, BoolOp::Union).unwrap().unwrap(); - let want = std::f64::consts::PI * (5.0f64.powi(2) - 3.0f64.powi(2)) * 0.2; - let o = coaxial_overlap(&plate, &headed).unwrap(); - // Measured off the core's mesh, as a boolean's result is. - assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}"); - assert!((o.centroid.z - 4.9).abs() < 1e-6, "{o:?}"); - } - - /// A bush and a headed screw whose shank ends inside the bore, both written to STEP and - /// read back: their cylinders come back as one face each that runs once round along a seam - /// edge, which the boolean cannot intersect where the shank's end meets the bore. The - /// walls are cut in two first and the answer is the one of the bodies as built. - #[test] - fn a_screw_in_a_bush_after_a_step_round_trip() { - let e = 0.01; - let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap(); - let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 12.0).unwrap(); - let bush = crate::boolean(&outer, &bore, BoolOp::Cut).unwrap().unwrap(); - let shank = crate::cylinder(Vec3::new(e, 0.0, -2.0), Vec3::Z, 3.0, 8.0).unwrap(); - let head = crate::cylinder(Vec3::new(e, 0.0, -5.0), Vec3::Z, 5.25, 3.0).unwrap(); - let screw = crate::boolean(&shank, &head, BoolOp::Union).unwrap().unwrap(); - let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body; - let (bush, screw) = (back(&bush), back(&screw)); - // The shank shares a crescent with the bush over the 6 mm it reaches into the bore. - let want = 6.0 * crescent(3.0, 3.0, e).area; - for (x, y) in [(&bush, &screw), (&screw, &bush)] { - let o = coaxial_overlap(x, y).unwrap(); - assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}"); - assert!((o.length - 6.0).abs() < 1e-6, "{o:?}"); - } - // Cut in two, each wall is a face more and the body keeps its volume. - let split = crate::step_in::split::split_seams(&bush).unwrap(); - assert_eq!(split.face_count(), bush.face_count() + 2); - let (v0, v1) = (crate::measure(&bush).unwrap().volume, crate::measure(&split).unwrap().volume); - assert!((v0 - v1).abs() < 1e-6 * v0, "{v0} {v1}"); - assert!(crate::step_in::split::split_seams(&outer).is_none()); - } - - /// A pin with a Ø7 collar embedded in a block (the collar's underside at z = 0, inside the - /// block's material), a hair off its hole, and a pocket elsewhere in the block whose floor - /// is at z = 0 too, facing the collar's underside: the two are level but don't touch, so the - /// collar is not pulled back, and all of it inside the block counts. - #[test] - fn a_collar_level_with_a_pocket_floor_elsewhere_is_not_pulled_back() { - let e = 0.01; - let mut block = crate::box_solid(Vec3::new(-10.0, -10.0, -5.0), Vec3::new(20.0, 10.0, 3.0)).unwrap(); - let hole = crate::cylinder(Vec3::new(0.0, 0.0, -6.0), Vec3::Z, 2.0, 10.0).unwrap(); - let pocket = crate::box_solid(Vec3::new(10.0, -3.0, 0.0), Vec3::new(14.0, 3.0, 4.0)).unwrap(); - for cut in [&hole, &pocket] { - block = crate::boolean(&block, cut, BoolOp::Cut).unwrap().unwrap(); - } - let shank = crate::cylinder(Vec3::new(e, 0.0, -7.0), Vec3::Z, 2.0, 8.0).unwrap(); - let collar = crate::cylinder(Vec3::new(e, 0.0, 0.0), Vec3::Z, 3.5, 1.0).unwrap(); - let pin = crate::boolean(&shank, &collar, BoolOp::Union).unwrap().unwrap(); - // The collar less the hole, plus the shank's crescent over the 5 mm below the collar. - let want = std::f64::consts::PI * (3.5 * 3.5 - 2.0 * 2.0) + 5.0 * crescent(2.0, 2.0, e).area; - for (x, y) in [(&block, &pin), (&pin, &block)] { - let o = coaxial_overlap(x, y).unwrap(); - assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}"); - } - } - - /// Two rivets with their heads flush on both faces of a sheet, each a hair off its hole, - /// read back from STEP: the heads touch the sheet flat, which the boolean cannot always - /// take, so they are pulled back off it first. Each rivet shares its own crescent. - #[test] - fn two_rivets_flush_on_a_sheet_after_a_step_round_trip() { - let rivet = |x: f64| { - let shank = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 3.5).unwrap(); - let under = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 3.5, 1.0).unwrap(); - let over = crate::cylinder(Vec3::new(x, 0.0, 1.5), Vec3::Z, 3.5, 1.0).unwrap(); - let r = crate::boolean(&shank, &under, BoolOp::Union).unwrap().unwrap(); - crate::boolean(&r, &over, BoolOp::Union).unwrap().unwrap() - }; - let mut sheet = crate::box_solid(Vec3::new(-20.0, -10.0, 0.0), Vec3::new(20.0, 10.0, 1.5)).unwrap(); - for x in [-4.0, 4.0] { - let drill = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 4.0).unwrap(); - sheet = crate::boolean(&sheet, &drill, BoolOp::Cut).unwrap().unwrap(); - } - let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body; - let sheet = back(&sheet); - for (x, e) in [(-4.0, 0.004), (4.0, 0.006)] { - let r = back(&rivet(x + e)); - let want = 1.5 * crescent(2.0, 2.0, e).area; - for (p, q) in [(&sheet, &r), (&r, &sheet)] { - let o = coaxial_overlap(p, q).unwrap(); - assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}"); - } - } - } -} diff --git a/crates/kernel/src/continuity.rs b/crates/kernel/src/continuity.rs index 001e32898..ebd266091 100644 --- a/crates/kernel/src/continuity.rs +++ b/crates/kernel/src/continuity.rs @@ -1,12 +1,18 @@ //! Continuity diagnostics across the seams between a body's faces: do the two faces that meet -//! at an edge share a curve (G0), a tangent plane (G1) and a curvature (G2)? +//! at an edge share a curve (G0), a tangent plane (G1), a curvature (G2), the way that curvature +//! changes across the seam (G3) and the way that change changes (G4)? //! //! The stations are taken on the edge itself — the curve both faces are supposed to share — so //! the numbers describe the B-rep and not a tessellation: each station is projected onto each //! face's own surface, and the two projections are compared. The gap is the distance between //! them (G0); the normal angle is the angle between the faces' outward normals there (G1); the //! curvature jump is the difference of their normal curvatures in the normal section square to -//! the edge, from the second fundamental form of each surface (G2). A rolling-ball fillet is +//! the edge, from the second fundamental form of each surface (G2); the curvature-change jump and +//! its rate's jump compare the first and second arc-length derivatives of those normal sections' +//! curvatures across the edge (G3, G4). All three come from each surface's exact partial +//! derivatives ([`solidcraft_geom::brep::normal_section`]), never from samples. Each seam's +//! [`SeamReport::order`] is the highest order whose test, and every lower one, its worst station +//! passes. A rolling-ball fillet is //! tangent to the faces it joins but is not curvature continuous: where it meets a plane its //! seam reads 0° and 1 / radius, which no chord tolerance would reveal. //! @@ -14,10 +20,14 @@ //! the join, and backs the engine's `inspect.continuity`. use serde::Serialize; -use solidcraft_geom::Vec3; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self as b}; +use solidcraft_geom::brep::normal_section::{SectionJet, normal_section}; +use solidcraft_geom::brep::{eval::CurveEval, eval::SurfaceEval}; +use solidcraft_geom::prelude::*; -use crate::body::{Body, from_p3, p3}; +use crate::body::Body; +use crate::continuity_order::Continuity; use crate::{KernelError, Result}; /// Bodies with more edges than this are refused rather than sampled for minutes. @@ -36,6 +46,8 @@ const PICK_SAMPLES: usize = 32; /// ends and the middle. pub const MIN_SAMPLES: usize = 3; pub const MAX_SAMPLES: usize = 257; +/// Stations along one edge where a measurement does not say (`inspect.continuity`'s default). +pub const DEFAULT_SAMPLES: usize = 33; /// How an edge is picked: a point on (or near) it, or its index in the display mesh's edge /// order ([`Body::edges`]), which is what a viewport pick carries. @@ -54,8 +66,37 @@ pub struct ContinuityTolerances { pub angle_deg: f64, /// Largest curvature jump that still counts as curvature continuous (G2), 1/mm. pub curvature_per_mm: f64, + /// Largest jump of the curvature's change across the seam that still counts as G3, 1/mm². + pub curvature_change_per_mm2: f64, + /// Largest jump of that change's rate that still counts as G4, 1/mm³. + pub curvature_change_rate_per_mm3: f64, } +impl Default for ContinuityTolerances { + /// A micron of gap, a degree of normal angle, a curvature jump of 1/100 mm, and a change of + /// curvature (and its rate) a tenth as large again per millimetre. + fn default() -> Self { + ContinuityTolerances { + gap_mm: 1e-3, + angle_deg: 1.0, + curvature_per_mm: 1e-2, + curvature_change_per_mm2: 1e-3, + curvature_change_rate_per_mm3: 1e-4, + } + } +} + +impl ContinuityTolerances { + /// The tolerance of each metric, in [`Metrics`] order (G0 … G4). + fn by_order(&self) -> Metrics { + [self.gap_mm, self.angle_deg, self.curvature_per_mm, self.curvature_change_per_mm2, self.curvature_change_rate_per_mm3] + } +} + +/// One value per order a seam is tested for, G0 … G4: the gap, the normal angle, and the jumps of +/// the curvature, of its change, and of that change's rate. +type Metrics = [f64; 5]; + /// The worst value of one metric along an edge, with where it was found. #[derive(Clone, Copy, Debug, Serialize)] pub struct SeamWorst { @@ -67,8 +108,9 @@ pub struct SeamWorst { } /// Which test a seam fails, from the best continuity to the worst: [`SeamVerdict::Smooth`] is -/// within every tolerance (G2 or better), then a tangent seam whose curvature jumps (G1), then -/// a visible crease (G0 only), and finally faces that do not meet at all. +/// curvature continuous (G2 or better: [`SeamReport::order`] says how much better), then a +/// tangent seam whose curvature jumps (G1), then a visible crease (G0 only), and finally faces +/// that do not meet at all. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] #[serde(rename_all = "snake_case")] pub enum SeamVerdict { @@ -78,6 +120,18 @@ pub enum SeamVerdict { Gap, } +impl SeamVerdict { + /// The verdict of a seam whose highest order met is `order` (`None`: not even G0). + pub fn of(order: Option) -> SeamVerdict { + match order { + None => SeamVerdict::Gap, + Some(Continuity::G0) => SeamVerdict::Sharp, + Some(Continuity::G1) => SeamVerdict::CurvatureJump, + Some(_) => SeamVerdict::Smooth, + } + } +} + /// One edge's diagnostics: the worst of each metric along it, and where. #[derive(Clone, Debug, Serialize)] pub struct SeamReport { @@ -90,10 +144,51 @@ pub struct SeamReport { pub gap_mm: SeamWorst, pub normal_angle_deg: SeamWorst, pub curvature_jump_per_mm: SeamWorst, - /// What the tolerances make of the seam. + /// The worst jump of the curvature's arc-length derivative across the seam (G3), 1/mm². + pub curvature_change_jump_per_mm2: SeamWorst, + /// The worst jump of its second derivative (G4), 1/mm³. + pub curvature_change_rate_jump_per_mm3: SeamWorst, + /// The highest order every station meets within the tolerances (`None`: the faces do not + /// meet). + pub order: Option, + /// What the tolerances make of the seam ([`SeamVerdict::of`] its order). pub verdict: SeamVerdict, /// The stations in order: what a viewport shades. pub points: Vec, + /// What each of `points` measured, in the same order. + pub stations: Vec, +} + +/// One station of a seam: how far along the edge, and the five metrics there. +#[derive(Clone, Copy, Debug, Serialize)] +pub struct SeamStation { + /// 0 at the edge's start, 1 at its end. + pub edge_fraction: f64, + pub gap_mm: f64, + pub normal_angle_deg: f64, + pub curvature_jump_per_mm: f64, + pub curvature_change_jump_per_mm2: f64, + pub curvature_change_rate_jump_per_mm3: f64, +} + +impl SeamStation { + fn new(edge_fraction: f64, m: Metrics) -> SeamStation { + let [gap_mm, normal_angle_deg, curvature_jump_per_mm, curvature_change_jump_per_mm2, curvature_change_rate_jump_per_mm3] = m; + SeamStation { + edge_fraction, + gap_mm, + normal_angle_deg, + curvature_jump_per_mm, + curvature_change_jump_per_mm2, + curvature_change_rate_jump_per_mm3, + } + } +} + +/// The highest order whose metric, and every lower one, is within its tolerance. +fn highest_met(worst: Metrics, tolerances: Metrics) -> Option { + let met = worst.iter().zip(tolerances).take_while(|(w, t)| **w <= *t).count(); + met.checked_sub(1).and_then(Continuity::from_order) } /// The seam diagnostics of one body. @@ -117,16 +212,16 @@ pub fn pick_edges(body: &Body, picks: &[EdgePick]) -> Result> { return Err(KernelError::Invalid(format!("pick at most {MAX_PICKS} edges"))); } crate::guard("continuity picks", || { - let (edges, adjacent) = topology(body)?; + let Topology { record, adjacent, .. } = topology(body)?; if picks.is_empty() { - return Ok((0..edges.len()).filter(|i| two_sided(&adjacent, *i)).collect()); + return Ok((0..record.edges.len()).filter(|i| two_sided(&adjacent, *i)).collect()); } let reach = body.size() * 0.05 + 1e-6; let mut out: Vec = Vec::new(); for pick in picks { let index = match *pick { EdgePick::Index(index) => index, - EdgePick::Point(p) => nearest_edge(&edges, p, reach)?, + EdgePick::Point(p) => nearest_edge(&record.edges, p, reach)?, }; if !two_sided(&adjacent, index) { return Err(KernelError::Invalid(format!("edge {index} of this body is not a seam between two faces"))); @@ -148,7 +243,8 @@ pub fn seam_diagnostics(body: &Body, edges: &[usize], samples: usize, tolerances if !(MIN_SAMPLES..=MAX_SAMPLES).contains(&samples) { return Err(KernelError::Invalid(format!("`samples` must be {MIN_SAMPLES}…{MAX_SAMPLES}"))); } - for (name, value) in [("gap", tolerances.gap_mm), ("angle", tolerances.angle_deg), ("curvature", tolerances.curvature_per_mm)] { + let names = ["gap", "angle", "curvature", "curvature change", "curvature change rate"]; + for (name, value) in names.into_iter().zip(tolerances.by_order()) { // A range test also throws out NaN (both comparisons are false). if !(0.0..1e9).contains(&value) { return Err(KernelError::Invalid(format!("the {name} tolerance must be a finite number, 0 or more"))); @@ -157,16 +253,46 @@ pub fn seam_diagnostics(body: &Body, edges: &[usize], samples: usize, tolerances crate::guard("continuity", || measure(body, edges, samples, tolerances)) } -/// The body's unique edges and the faces meeting at each of them, either under the caps. -fn topology(body: &Body) -> Result<(Vec, Vec>)> { - if body.solid.face_iter().take(MAX_FACES + 1).count() > MAX_FACES { +/// The body's record with, per edge, the faces it bounds (each once: a periodic face's own seam +/// bounds one), and per face whether its surface's natural normal points out of the material; +/// refused past the caps. +struct Topology { + record: b::Brep, + adjacent: Vec>, + outward: Vec, +} + +fn topology(body: &Body) -> Result { + let record = crate::native::brep_record(body)?; + if record.faces.len() > MAX_FACES { return Err(KernelError::TooLarge(format!("the body has more than {MAX_FACES} faces"))); } - let (edges, adjacent) = crate::body::edge_order(body.solid.face_iter()); - if edges.len() > MAX_EDGES { + if record.edges.len() > MAX_EDGES { return Err(KernelError::TooLarge(format!("the body has more than {MAX_EDGES} edges"))); } - Ok((edges, adjacent)) + let adjacent = record + .edges + .iter() + .map(|e| { + let mut faces: Vec = e.uses.iter().map(|u| u.face as usize).collect(); + faces.sort_unstable(); + faces.dedup(); + faces + }) + .collect(); + // A face's side in the first shell that uses it (canonical order walks faces that way). + let mut outward: Vec> = vec![None; record.faces.len()]; + for shell in &record.shells { + if let b::Shell::Faces { faces, .. } = shell { + for f in faces { + if let Some(slot) = outward.get_mut(f.face as usize) { + slot.get_or_insert(f.forward); + } + } + } + } + let outward = outward.into_iter().map(|o| o.unwrap_or(true)).collect(); + Ok(Topology { record, adjacent, outward }) } /// Is the edge at `index` shared by (exactly) two faces of the body? @@ -175,17 +301,13 @@ fn two_sided(adjacent: &[Vec], index: usize) -> bool { } /// The index of the edge whose curve comes nearest `p`, within `reach`. -fn nearest_edge(edges: &[mt::Edge], p: Vec3, reach: f64) -> Result { - use mt::ParametricCurve; +fn nearest_edge(edges: &[b::Edge], p: Vec3, reach: f64) -> Result { let mut best: Option<(f64, usize)> = None; for (index, edge) in edges.iter().enumerate() { - let curve = edge.curve(); - let Some((t0, t1)) = curve.try_range_tuple() else { continue }; - if !(t0.is_finite() && t1.is_finite() && t1 > t0) { - continue; - } + let Ok(curve) = CurveEval::new(edge.parameters()) else { continue }; + let [t0, t1] = edge.interval; for k in 0..=PICK_SAMPLES { - let q = from_p3(curve.subs(t0 + (t1 - t0) * k as f64 / PICK_SAMPLES as f64)); + let Some(q) = curve.point(t0 + (t1 - t0) * k as f64 / PICK_SAMPLES as f64) else { continue }; let d = q.dist(p); if d.is_finite() && best.is_none_or(|(bd, _)| d < bd) { best = Some((d, index)); @@ -199,12 +321,11 @@ fn nearest_edge(edges: &[mt::Edge], p: Vec3, reach: f64) -> Result { } fn measure(body: &Body, edges: &[usize], samples: usize, tolerances: ContinuityTolerances) -> Result { - let (list, adjacent) = topology(body)?; - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); + let Topology { record, adjacent, outward } = topology(body)?; let mut selected: Vec = Vec::new(); let mut skipped = 0usize; if edges.is_empty() { - for index in 0..list.len() { + for index in 0..record.edges.len() { if two_sided(&adjacent, index) { selected.push(index); } else { @@ -216,7 +337,7 @@ fn measure(body: &Body, edges: &[usize], samples: usize, tolerances: ContinuityT selected.sort_unstable(); selected.dedup(); for &index in &selected { - if index >= list.len() { + if index >= record.edges.len() { return Err(KernelError::Invalid(format!("the body has no edge {index}"))); } if !two_sided(&adjacent, index) { @@ -224,21 +345,27 @@ fn measure(body: &Body, edges: &[usize], samples: usize, tolerances: ContinuityT } } } + let face = |i: usize| -> Option { + let f = record.faces.get(i)?; + FaceSurface::new(f.parameters(), outward.get(i).copied().unwrap_or(true)) + }; let mut seams = Vec::new(); let mut unmeasured = 0usize; let mut budget = MAX_STATIONS; for index in selected { - let Some(face_pair) = adjacent.get(index).filter(|faces| faces.len() == 2) else { continue }; - let (Some(&first), Some(&second)) = (face_pair.first(), face_pair.get(1)) else { continue }; - let (Some(a), Some(b)) = (faces.get(first).copied(), faces.get(second).copied()) else { continue }; - let Some(edge) = list.get(index) else { continue }; + let Some([first, second]) = adjacent.get(index).and_then(|f| <[usize; 2]>::try_from(f.as_slice()).ok()) else { continue }; + let Some(edge) = record.edges.get(index) else { continue }; // Every edge costs `samples` stations; a run out of budget stops cleanly. if budget < samples { skipped += 1; continue; } budget -= samples; - match seam(index, edge, a, b, samples, tolerances) { + let report = match (face(first), face(second), CurveEval::new(edge.parameters())) { + (Some(a), Some(b), Ok(curve)) => seam(index, &curve, edge.interval, a, b, samples, tolerances), + _ => None, + }; + match report { Some(report) => seams.push(report), None => unmeasured += 1, } @@ -246,54 +373,34 @@ fn measure(body: &Body, edges: &[usize], samples: usize, tolerances: ContinuityT Ok(ContinuityReport { seams, skipped, unmeasured }) } -/// One edge's worst gap, normal angle and curvature jump. -fn seam(index: usize, edge: &mt::Edge, face_a: &mt::Face, face_b: &mt::Face, samples: usize, tolerances: ContinuityTolerances) -> Option { - use mt::ParametricCurve; - let curve = edge.curve(); - let (t0, t1) = curve.try_range_tuple()?; +/// One edge's worst gap, normal angle and jumps of curvature, its change and that change's rate. +fn seam( + index: usize, + curve: &CurveEval, + [t0, t1]: [f64; 2], + mut on_a: FaceSurface, + mut on_b: FaceSurface, + samples: usize, + tolerances: ContinuityTolerances, +) -> Option { // The station fractions: 0 at the edge's start, 1 at its end. let steps = samples.checked_sub(1)?; - let fraction = |k: usize| k as f64 / steps as f64; - let mut on_a = FaceSurface::new(face_a); - let mut on_b = FaceSurface::new(face_b); - let mut gap = None; - let mut angle = None; - let mut jump = None; + let mut worst: [Option; 5] = [None; 5]; let mut points = Vec::with_capacity(samples); + let mut stations = Vec::with_capacity(samples); for k in 0..samples { - let f = fraction(k); - let at = from_p3(curve.subs(t0 + (t1 - t0) * f)); - if !at.is_finite() { - continue; - } - // Both projections and both curvatures, or the station says nothing. - let (Some((qa, na, uv_a)), Some((qb, nb, uv_b))) = (on_a.project(at), on_b.project(at)) else { continue }; - let tangent = curve.der(t0 + (t1 - t0) * f); - let Some(tangent) = Vec3::new(tangent.x, tangent.y, tangent.z).normalized() else { continue }; - // The normal sections square to the seam: one direction per face, in its tangent plane. - let (Some(ka), Some(kb)) = (on_a.normal_curvature(uv_a, na, across(na, tangent)), on_b.normal_curvature(uv_b, nb, across(nb, tangent))) - else { - continue; - }; - // The faces' outward normals agree on a smooth seam; where they are opposed (a knife - // edge) the curvatures are compared in one frame, since bending away from one face is - // bending towards the other. - let signed = if na.dot(nb) < 0.0 { ka + kb } else { ka - kb }; + let f = k as f64 / steps as f64; + let Some((at, tangent)) = curve.derivs(t0 + (t1 - t0) * f) else { continue }; + let Some(metrics) = station(at, tangent, &mut on_a, &mut on_b) else { continue }; points.push(at); - keep(&mut gap, qa.dist(qb), at, f); - keep(&mut angle, na.dot(nb).clamp(-1.0, 1.0).acos().to_degrees(), at, f); - keep(&mut jump, signed.abs(), at, f); + stations.push(SeamStation::new(f, metrics)); + for (w, value) in worst.iter_mut().zip(metrics) { + keep(w, value, at, f); + } } - let (gap, angle, jump) = (gap?, angle?, jump?); - let verdict = if gap.value > tolerances.gap_mm { - SeamVerdict::Gap - } else if angle.value > tolerances.angle_deg { - SeamVerdict::Sharp - } else if jump.value > tolerances.curvature_per_mm { - SeamVerdict::CurvatureJump - } else { - SeamVerdict::Smooth - }; + let [gap, angle, jump, change, rate] = worst; + let [gap, angle, jump, change, rate] = [gap?, angle?, jump?, change?, rate?]; + let order = highest_met([gap.value, angle.value, jump.value, change.value, rate.value], tolerances.by_order()); let length = points.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum(); Some(SeamReport { edge: index, @@ -302,11 +409,38 @@ fn seam(index: usize, edge: &mt::Edge, face_a: &mt::Face, face_b: &mt::Face, sam gap_mm: gap, normal_angle_deg: angle, curvature_jump_per_mm: jump, - verdict, + curvature_change_jump_per_mm2: change, + curvature_change_rate_jump_per_mm3: rate, + order, + verdict: SeamVerdict::of(order), points, + stations, }) } +/// The five metrics at the seam point `at` (edge tangent `tangent`): both projections and both +/// faces' normal sections square to the seam, or the station says nothing. +fn station(at: Vec3, tangent: Vec3, on_a: &mut FaceSurface, on_b: &mut FaceSurface) -> Option { + if !at.is_finite() { + return None; + } + let ((qa, na, uv_a), (qb, nb, uv_b)) = (on_a.project(at)?, on_b.project(at)?); + let tangent = tangent.normalized()?; + let ja = on_a.section(uv_a, na, across(na, tangent))?; + let jb = on_b.section(uv_b, nb, across(nb, tangent))?; + // The faces' outward normals agree on a smooth seam; where they are opposed (a knife edge) + // the sections are compared in one frame: face b's normal and its across direction both turn + // round, so its k-th derivative of curvature reads (−1)^(k+1) times as much in face a's. + let opposed = na.dot(nb) < 0.0; + let jump = |k: usize, a: f64, b: f64| { + let flip = if opposed && k.is_multiple_of(2) { -1.0 } else { 1.0 }; + (a - flip * b).abs() + }; + let [ka, ca, ra] = ja.values(); + let [kb, cb, rb] = jb.values(); + Some([qa.dist(qb), na.dot(nb).clamp(-1.0, 1.0).acos().to_degrees(), jump(0, ka, kb), jump(1, ca, cb), jump(2, ra, rb)]) +} + /// The direction in which a face's curvature is read at a seam: across the edge, square to it, /// inside the face's tangent plane (a zero vector where the edge runs along the normal, which /// leaves that station unmeasured). @@ -324,90 +458,47 @@ fn keep(worst: &mut Option, value: f64, at: Vec3, edge_fraction: f64) /// A face's surface, kept over the stations of one edge so each search can start at the last /// answer (stations run along the edge, so the parameters move smoothly). struct FaceSurface { - surface: mt::Surface, - hint: Option<(f64, f64)>, + surface: SurfaceEval, + /// +1 where the natural normal points out of the material, −1 where it points in. + side: f64, + hint: Option<[f64; 2]>, } impl FaceSurface { - /// The face's own outward-facing surface (`oriented_surface`: a reversed face's surface is - /// inverted, so its normal is the material's outward normal). - fn new(face: &mt::Face) -> Self { - Self { surface: face.oriented_surface(), hint: None } + fn new(surface: &b::Surface, outward: bool) -> Option { + Some(Self { surface: SurfaceEval::new(surface).ok()?, side: if outward { 1.0 } else { -1.0 }, hint: None }) } /// The nearest point of the surface to `p`, the outward unit normal there and the /// parameters. `None` where the search or the normal is unusable. - fn project(&mut self, p: Vec3) -> Option<(Vec3, Vec3, (f64, f64))> { - use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let uv = self.surface.search_nearest_parameter(p3(p), self.hint, 100).or_else(|| self.surface.search_nearest_parameter(p3(p), None, 100))?; - if !(uv.0.is_finite() && uv.1.is_finite()) { - return None; - } - let q = from_p3(self.surface.subs(uv.0, uv.1)); - let n = self.surface.normal(uv.0, uv.1); + fn project(&mut self, p: Vec3) -> Option<(Vec3, Vec3, [f64; 2])> { + let uv = self.surface.project(p, self.hint, f64::INFINITY).or_else(|| self.surface.project(p, None, f64::INFINITY))?; + let (q, su, sv) = self.surface.derivs(uv[0], uv[1])?; if !q.is_finite() { return None; } - let normal = Vec3::new(n.x, n.y, n.z).normalized()?; + let normal = (su.cross(sv) * self.side).normalized()?; self.hint = Some(uv); Some((q, normal, uv)) } - /// The normal curvature of the face at `uv` along `direction` (a unit vector of its tangent - /// plane), from the second fundamental form. A surface point `r(u, v)` with unit normal `n` - /// crossed that way has curvature `κ = n · r''` of the curve whose tangent there is - /// `direction`: a plane reads 0 and a cylinder of radius `R`, across its axis, −1 / R - /// (bending towards its axis). `None` at a degenerate parameter point (a cone's apex), where - /// the surface has no curvature. - fn normal_curvature(&self, uv: (f64, f64), normal: Vec3, direction: Vec3) -> Option { - use mt::ParametricSurface; - let ru = vec3(self.surface.uder(uv.0, uv.1)); - let rv = vec3(self.surface.vder(uv.0, uv.1)); - let (ru_len, rv_len) = (ru.len(), rv.len()); - if !(ru_len > 0.0 && rv_len > 0.0) { - return None; - } - // Solve the direction in the unit basis (r_u / |r_u|, r_v / |r_v|): the curve then runs - // its parameters at du/ds = α / |r_u| and dv/ds = β / |r_v|, and - // `r'' = r_uu (du/ds)² + 2 r_uv (du/ds)(dv/ds) + r_vv (dv/ds)²`. - let cos = (ru.dot(rv) / (ru_len * rv_len)).clamp(-1.0, 1.0); - let sin2 = 1.0 - cos * cos; - if !(sin2 > 1e-12) { - return None; - } - let (cu, cv) = (direction.dot(ru) / ru_len, direction.dot(rv) / rv_len); - let (du, dv) = ((cu - cv * cos) / sin2 / ru_len, (cv - cu * cos) / sin2 / rv_len); - if !(du.is_finite() && dv.is_finite()) { - return None; - } - // `direction` is a unit vector: divide by the speed the parameters imply (they only miss - // it by rounding), so κ does not depend on how the surface is parameterized. - let speed = (ru * du + rv * dv).len(); - if !(speed > 1e-6) { - return None; - } - let second = normal.dot( - vec3(self.surface.uuder(uv.0, uv.1)) * (du * du) - + vec3(self.surface.uvder(uv.0, uv.1)) * (2.0 * du * dv) - + vec3(self.surface.vvder(uv.0, uv.1)) * (dv * dv), - ); - (second / (speed * speed)).is_finite().then_some(second / (speed * speed)) + /// The face's normal section at `uv` along `direction` (a unit vector of its tangent plane): + /// its curvature `κ = n · r″` and κ's first two arc-length derivatives, from the surface's + /// exact partials. A plane reads 0 and a cylinder of radius `R`, across its axis, −1 / R + /// (bending towards its axis). `None` at a degenerate parameter point (a cone's apex). + fn section(&self, uv: [f64; 2], normal: Vec3, direction: Vec3) -> Option { + normal_section(&self.surface.partials(uv[0], uv[1])?, normal, direction) } } -/// A kernel point as a vector. -fn vec3(p: mt::Vector3) -> Vec3 { - Vec3::new(p.x, p.y, p.z) -} - #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; - use solidcraft_geom::Plane; + use solidcore_record::{Plane, Seg2}; fn tolerances() -> ContinuityTolerances { - ContinuityTolerances { gap_mm: 1e-3, angle_deg: 1.0, curvature_per_mm: 0.01 } + ContinuityTolerances::default() } fn box_body() -> Body { @@ -429,6 +520,7 @@ mod tests { assert!((seam.normal_angle_deg.value - 90.0).abs() < 1e-9, "angle {}", seam.normal_angle_deg.value); assert!(seam.curvature_jump_per_mm.value < 1e-9, "jump {}", seam.curvature_jump_per_mm.value); assert_eq!(seam.verdict, SeamVerdict::Sharp); + assert_eq!(seam.order, Some(Continuity::G0)); assert_eq!(seam.samples, 33); assert!((seam.length - 10.0).abs() < 1e-9); } @@ -449,13 +541,16 @@ mod tests { assert!(seam.curvature_jump_per_mm.value.is_finite()); assert!((seam.curvature_jump_per_mm.value - 0.25).abs() < 1e-6, "1 / radius, got {}", seam.curvature_jump_per_mm.value); assert_eq!(seam.verdict, SeamVerdict::CurvatureJump); + // A plane tangent to a cylinder: G1, not G2. Neither section's curvature changes. + assert_eq!(seam.order, Some(Continuity::G1)); + assert!(seam.curvature_change_jump_per_mm2.value < 1e-9 && seam.curvature_change_rate_jump_per_mm3.value < 1e-9); } assert_eq!(r.seams.iter().filter(|s| s.verdict == SeamVerdict::Sharp).count(), 13); } #[test] fn a_line_tangent_into_an_arc_reports_one_over_its_radius() { - use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; + use solidcore_record::{Loop2, Region2, Seg2, Vec2}; let v = |x: f64, y: f64| Vec2::new(x, y); let outer = Loop2 { segs: vec![ @@ -478,6 +573,89 @@ mod tests { } } + /// A 3 mm tall prism over a profile that runs along a line from (-20, 0) to the origin, on + /// into `transition` (starting at the origin, leaving along +x), and back straight to + /// (-20, 20): its one tangent wall seam is the line meeting the transition. + fn line_into(transition: Seg2) -> Body { + use solidcore_record::{Loop2, Region2, Vec2}; + let end = match transition { + Seg2::Cubic { p3, .. } => p3, + Seg2::Bezier { n, p } => p[usize::from(n)], + _ => Vec2::new(0.0, 0.0), + }; + let outer = Loop2 { + segs: vec![ + Seg2::Line { a: Vec2::new(-20.0, 0.0), b: Vec2::new(0.0, 0.0) }, + transition, + Seg2::Line { a: end, b: Vec2::new(-20.0, 20.0) }, + Seg2::Line { a: Vec2::new(-20.0, 20.0), b: Vec2::new(-20.0, 0.0) }, + ], + }; + crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0.0, 3.0).unwrap().remove(0) + } + + /// The one seam of `body` where the faces are tangent. + fn tangent_seam(body: &Body) -> SeamReport { + let r = report(body); + let mut tangent: Vec = r.seams.into_iter().filter(|s| s.normal_angle_deg.value < 0.01).collect(); + assert_eq!(tangent.len(), 1, "{tangent:?}"); + tangent.remove(0) + } + + /// A plane into a cubic whose first three control points lie on the plane's line: the cubic + /// starts with zero curvature (G2), but its curvature changes there. For control points + /// (0,0), (L,0), (2L,0), (3L,H): B′ = (3L, 0), B″ = 0 and B‴ = (0, 6H) at the start, so + /// dκ/dt = (x′y‴ − y′x‴) / |B′|³ = 2H / (3L²) and, at ds/dt = 3L, dκ/ds = 2H / (9L³): with + /// L = H = 10, 2 / 900 per mm². + #[test] + fn a_plane_into_a_g2_transition_is_curvature_continuous_but_not_g3() { + use solidcore_record::Vec2; + let v = Vec2::new; + let body = line_into(Seg2::Cubic { p0: v(0.0, 0.0), p1: v(10.0, 0.0), p2: v(20.0, 0.0), p3: v(30.0, 10.0) }); + let seam = tangent_seam(&body); + assert!(seam.curvature_jump_per_mm.value < 1e-9, "{}", seam.curvature_jump_per_mm.value); + let change = seam.curvature_change_jump_per_mm2.value; + assert!((change - 2.0 / 900.0).abs() < 1e-9, "dκ/ds 2/900, got {change}"); + assert_eq!(seam.order, Some(Continuity::G2)); + assert_eq!(seam.verdict, SeamVerdict::Smooth, "G2 is still smooth to the older verdict"); + } + + /// A plane into a quartic whose first four control points are evenly spaced on the plane's + /// line: curvature and its change both start at zero (G3), but the change's rate does not. + /// For (0,0), (L,0), (2L,0), (3L,0), (4L,H): B′ = (4L, 0), B″ = B‴ = 0 and B⁗ = (0, 24H), + /// so d²κ/dt² = (x′y⁗ − y′x⁗) / |B′|³ = 3H / (2L²) and, at ds/dt = 4L, d²κ/ds² = 3H / (32L⁴): + /// with L = 5, H = 10, 3 / 2000 per mm³. + #[test] + fn a_plane_into_a_g3_transition_holds_the_change_of_curvature_but_not_g4() { + use solidcore_record::Vec2; + let mut p = [Vec2::new(0.0, 0.0); solidcore_record::MAX_BEZIER_CTRL]; + for (k, q) in [(5.0, 0.0), (10.0, 0.0), (15.0, 0.0), (20.0, 10.0)].into_iter().enumerate() { + p[k + 1] = Vec2::new(q.0, q.1); + } + let body = line_into(Seg2::Bezier { n: 4, p }); + let seam = tangent_seam(&body); + assert!(seam.curvature_jump_per_mm.value < 1e-9 && seam.curvature_change_jump_per_mm2.value < 1e-9, "{seam:?}"); + let rate = seam.curvature_change_rate_jump_per_mm3.value; + assert!((rate - 3.0 / 2000.0).abs() < 1e-9, "d²κ/ds² 3/2000, got {rate}"); + assert_eq!(seam.order, Some(Continuity::G3)); + // Within a looser rate tolerance the same seam reads G4. + let loose = ContinuityTolerances { curvature_change_rate_per_mm3: 1e-2, ..tolerances() }; + let r = seam_diagnostics(&body, &[seam.edge], 33, loose).unwrap(); + assert_eq!(r.seams[0].order, Some(Continuity::G4)); + } + + #[test] + fn the_highest_order_met_needs_every_order_below_it() { + let tol = [1.0; 5]; + assert_eq!(highest_met([0.0; 5], tol), Some(Continuity::G4)); + assert_eq!(highest_met([0.0, 0.0, 2.0, 0.0, 0.0], tol), Some(Continuity::G1), "a G2 failure caps the order"); + assert_eq!(highest_met([2.0, 0.0, 0.0, 0.0, 0.0], tol), None, "faces that do not meet have no order"); + assert_eq!(highest_met([0.0, 0.0, 0.0, f64::NAN, 0.0], tol), Some(Continuity::G2), "NaN never passes"); + for (order, verdict) in [(None, SeamVerdict::Gap), (Some(Continuity::G0), SeamVerdict::Sharp), (Some(Continuity::G3), SeamVerdict::Smooth)] { + assert_eq!(SeamVerdict::of(order), verdict); + } + } + #[test] fn picks_refuse_what_is_not_there() { let body = box_body(); @@ -492,6 +670,7 @@ mod tests { assert!(seam_diagnostics(&body, &[], 2, tolerances()).is_err()); assert!(seam_diagnostics(&body, &[], 258, tolerances()).is_err()); assert!(seam_diagnostics(&body, &[], 33, ContinuityTolerances { gap_mm: f64::NAN, ..tolerances() }).is_err()); + assert!(seam_diagnostics(&body, &[], 33, ContinuityTolerances { curvature_change_rate_per_mm3: -1.0, ..tolerances() }).is_err()); assert!(seam_diagnostics(&body, &[999], 33, tolerances()).is_err()); } } diff --git a/crates/kernel/src/continuity_order.rs b/crates/kernel/src/continuity_order.rs new file mode 100644 index 000000000..98318cdee --- /dev/null +++ b/crates/kernel/src/continuity_order.rs @@ -0,0 +1,237 @@ +//! The orders of geometric continuity, G0 to G4, in one table: the word a command parameter and +//! a design file use (`g0` … `g4`), the code shown in hover texts, help and messages (`G0` … +//! `G4`), and the message ids of the plain word a control shows (Position, Tangent, Curvature, +//! Curvature change, Smooth curvature change) and of its hover text. Labels never show the code. +//! +//! Each order adds one condition across a seam: G0 the position, G1 the tangent plane, G2 the +//! curvature, G3 how the curvature changes across the seam (its first derivative by arc length), +//! G4 how that change itself changes (the second derivative). +//! +//! [`Construction`] says which orders each construction builds today, and +//! [`Continuity::built_by`] is the one check that refuses the rest. + +use crate::{KernelError, Result}; + +/// How smoothly a surface or curve continues across a seam: the number of derivatives it shares. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Continuity { + /// The position alone: the surfaces meet, with a crease where they do. + G0, + /// Position and tangent plane. + #[default] + G1, + /// Position, tangent plane and curvature. + G2, + /// Position, tangent plane, curvature and the change of curvature across the seam. + G3, + /// All of G3, and how that change of curvature itself changes. + G4, +} + +/// One row of the table: what an order is called where. +struct Words { + /// The command parameter and design-file word. + word: &'static str, + /// The code, for hover texts, help and messages only. + code: &'static str, + /// The message id of the plain word a control shows. + label: &'static str, + /// The message id of the hover text, which names the code. + tip: &'static str, +} + +/// The table, indexed by [`Continuity::order`]. +const WORDS: [Words; 5] = [ + Words { word: "g0", code: "G0", label: "ui.continuity_position", tip: "ui.continuity_position_tip" }, + Words { word: "g1", code: "G1", label: "ui.continuity_tangent", tip: "ui.continuity_tangent_tip" }, + Words { word: "g2", code: "G2", label: "ui.continuity_curvature", tip: "ui.continuity_curvature_tip" }, + Words { word: "g3", code: "G3", label: "ui.continuity_curvature_change", tip: "ui.continuity_curvature_change_tip" }, + Words { word: "g4", code: "G4", label: "ui.continuity_smooth_curvature_change", tip: "ui.continuity_smooth_curvature_change_tip" }, +]; + +impl Continuity { + /// Every order, from G0 up. + pub const ALL: [Continuity; 5] = [Continuity::G0, Continuity::G1, Continuity::G2, Continuity::G3, Continuity::G4]; + + /// The number of derivatives across the seam it fixes: 0 (G0) up to 4 (G4). + pub fn order(self) -> usize { + self as usize + } + + /// The order with `order` derivatives, `None` past G4. + pub fn from_order(order: usize) -> Option { + Continuity::ALL.get(order).copied() + } + + /// Conditions a side carries: the position and one per derivative, 1 (G0) up to 5 (G4). + pub fn conditions(self) -> usize { + self.order() + 1 + } + + /// The word a command parameter and a design use: `g0` … `g4`. + pub fn as_str(self) -> &'static str { + self.row().word + } + + /// The code `G0` … `G4`: for hover texts, help and messages, never a label. + pub fn code(self) -> &'static str { + self.row().code + } + + /// The message id of the plain word a control shows for this order. + pub fn label_id(self) -> &'static str { + self.row().label + } + + /// The message id of this order's hover text (which names its code). + pub fn tip_id(self) -> &'static str { + self.row().tip + } + + /// Parse a word (`g0` … `g4`, either case, surrounding blanks ignored); `None` for anything else. + pub fn parse(s: &str) -> Option { + let s = s.trim(); + Continuity::ALL.into_iter().find(|g| g.as_str().eq_ignore_ascii_case(s)) + } + + /// The words of `from` up to `to` for a message: "g0, g1 or g2". + pub fn words(from: Continuity, to: Continuity) -> String { + let words: Vec<&str> = Continuity::ALL.into_iter().filter(|g| (from..=to).contains(g)).map(Continuity::as_str).collect(); + match words.split_last() { + Some((last, [])) => (*last).to_string(), + Some((last, rest)) => format!("{} or {last}", rest.join(", ")), + None => String::new(), + } + } + + /// This order if `by` builds it, else a refusal that names the orders it does build. The one + /// check every command and kernel entry point makes ([`Construction`]). + pub fn built_by(self, by: Construction) -> Result { + let (lowest, highest) = by.orders(); + if self < lowest { + return Err(KernelError::Invalid(format!("{} takes {}", by.what(), Continuity::words(lowest, highest)))); + } + if self > highest { + return Err(KernelError::Invalid(format!( + "not supported yet: {} is built with {}, not {}", + by.what(), + Continuity::words(lowest, highest), + self.as_str() + ))); + } + Ok(self) + } + + fn row(self) -> &'static Words { + // `WORDS` has a row for every variant (`order` is at most 4). + &WORDS[self.order()] + } +} + +/// What builds geometry to a continuity order, and the orders each one builds today. +/// +/// HAND-OFF POINT: this table is the only place that says how far a construction goes. When a +/// construction learns a higher order, raise its `highest` in [`Construction::orders`]; every +/// command, dialog and kernel entry point reads it from here, so nothing else changes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Construction { + /// A patch filling a loop of edges (`surface.patch`). + Patch, + /// A bridge of Hermite rows: a blend surface, a boundary patch on a loop of sketch curves, a + /// loft's ends and a match surface's seam. + Bridge, + /// A surface through a curve network (`surface.boundary` with `u` and `v` curves). + Network, + /// A match surface: a bridge that must at least share the tangent plane. + Match, + /// A sketch blend curve (`sketch.blend_curve`): one Bézier through G1 … G4. + BlendCurve, +} + +impl Construction { + /// The lowest and the highest order this construction builds. + pub fn orders(self) -> (Continuity, Continuity) { + match self { + Construction::Patch => (Continuity::G0, Continuity::G4), + Construction::Bridge => (Continuity::G0, Continuity::G3), + Construction::Network => (Continuity::G0, Continuity::G2), + Construction::Match => (Continuity::G1, Construction::Bridge.orders().1), + Construction::BlendCurve => (Continuity::G1, Continuity::G4), + } + } + + /// Whether this construction builds `g`. + pub fn builds(self, g: Continuity) -> bool { + let (lowest, highest) = self.orders(); + (lowest..=highest).contains(&g) + } + + /// The orders it builds, from its lowest up: what a dialog offers. + pub fn offered(self) -> Vec { + Continuity::ALL.into_iter().filter(|g| self.builds(*g)).collect() + } + + /// What it is called in a message. + fn what(self) -> &'static str { + match self { + Construction::Patch => "a patch", + Construction::Bridge => "a blend, boundary, loft or match surface", + Construction::Network => "a curve network", + Construction::Match => "a match surface", + Construction::BlendCurve => "a blend curve", + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn every_order_round_trips_through_its_word_and_serde() { + for (k, g) in Continuity::ALL.into_iter().enumerate() { + assert_eq!(g.order(), k); + assert_eq!(Continuity::from_order(k), Some(g)); + assert_eq!(g.conditions(), k + 1); + assert_eq!(g.as_str(), format!("g{k}")); + assert_eq!(g.code(), format!("G{k}")); + assert_eq!(Continuity::parse(g.as_str()), Some(g)); + assert_eq!(Continuity::parse(&format!(" {} ", g.code())), Some(g)); + // The design file's word is the command word. + assert_eq!(serde_json::to_value(g).unwrap(), serde_json::json!(g.as_str())); + assert_eq!(serde_json::from_value::(serde_json::json!(g.as_str())).unwrap(), g); + } + assert_eq!(Continuity::from_order(5), None); + for word in ["", "g5", "G-1", "curvature", "g 1"] { + assert_eq!(Continuity::parse(word), None, "{word:?}"); + } + } + + #[test] + fn labels_are_words_and_tips_are_their_own() { + let ids: Vec<&str> = Continuity::ALL.iter().flat_map(|g| [g.label_id(), g.tip_id()]).collect(); + for (i, id) in ids.iter().enumerate() { + assert!(id.starts_with("ui.continuity_"), "{id}"); + assert!(!ids[..i].contains(id), "{id} twice"); + assert!(!id.contains("_g"), "a message id names its word, not its code: {id}"); + } + } + + #[test] + fn a_construction_refuses_what_it_does_not_build_and_names_what_it_does() { + assert_eq!(Continuity::words(Continuity::G0, Continuity::G2), "g0, g1 or g2"); + assert_eq!(Continuity::words(Continuity::G4, Continuity::G4), "g4"); + assert_eq!(Continuity::G4.built_by(Construction::Patch).unwrap(), Continuity::G4); + let e = Continuity::G3.built_by(Construction::Network).unwrap_err().to_string(); + assert!(e.contains("not supported yet") && e.contains("g0, g1 or g2") && e.contains("g3"), "{e}"); + let e = Continuity::G0.built_by(Construction::Match).unwrap_err().to_string(); + assert!(e.contains("g1, g2 or g3"), "{e}"); + assert!(Continuity::G4.built_by(Construction::Bridge).is_err()); + assert!(Continuity::G4.built_by(Construction::BlendCurve).is_ok()); + assert_eq!(Construction::Patch.offered(), Continuity::ALL.to_vec()); + assert_eq!(Construction::Network.offered(), vec![Continuity::G0, Continuity::G1, Continuity::G2]); + assert_eq!(Construction::BlendCurve.offered().first(), Some(&Continuity::G1)); + } +} diff --git a/crates/kernel/src/coplanar.rs b/crates/kernel/src/coplanar.rs deleted file mode 100644 index 9f4059210..000000000 --- a/crates/kernel/src/coplanar.rs +++ /dev/null @@ -1,1828 +0,0 @@ -//! Booleans of bodies with coincident planar faces, by moving faces apart first. -//! -//! The mesh-based intersection cannot handle faces that lie in the same plane, nor the edges -//! lying in them. A face whose neighbours stand perpendicular to it (any extruded or -//! box-like part) can be pushed along its normal exactly, by rebuilding it and stretching or -//! shrinking its neighbours. Then: -//! - cut and intersect: the tool's coincident face moves out of the way (outward when the -//! bodies are on the same side of the plane, away from the target when they touch back to -//! back), which leaves the result unchanged; -//! - union of faces facing the same way: both faces move outward by different amounts, the -//! union is taken, and the slab beyond the plane is cut off (now a transversal cut); -//! - union of faces back to back: the tool's face moves into the target, which overlaps it. -//! -//! Each of these leaves the result unchanged only where the space a face moves through holds -//! what the boolean leaves there anyway: none of the target for a cut or an intersection, the -//! target's material for a union, nothing of either body beyond a plane whose slab is cut off -//! again. The faces of a coincident plane lie on each other, but nothing says that what lies -//! beside them does: a tool's side in the face of a wall has the neighbouring walls beside it, -//! a channel's top in the face a rib stands on has the rib over it. So a face is asked first -//! what it would move through: a join's face moving into the target at points behind it -//! (`backed`), the others on the other body's faces (see [`crate::clearance`]). A face with -//! no room stays where it is and the boolean fails with [`NO_ROOM`], for the strategies that -//! take the bodies as they lie. - -use std::collections::HashMap; - -use solidcraft_geom::{Aabb3, Ring, UnitVec3, Vec3}; -use truck_modeling::{self as mt, builder}; - -use crate::body::shell_groups::boxes_separate; -use crate::body::{Body, Solid, from_p3, p3, v3}; -use crate::clearance::{Clearance, Occupancy}; -use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv, History}; -use crate::{BoolOp, KernelError, Result, guard, record}; - -#[derive(Clone, Copy, Debug)] -struct PlaneFace { - n: Vec3, - d: f64, -} - -fn planes(b: &Body) -> Vec<(usize, PlaneFace)> { - b.solid - .face_iter() - .enumerate() - .filter_map(|(i, f)| match f.oriented_surface() { - mt::Surface::Plane(p) => { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - Some((i, PlaneFace { n, d: n.dot(from_p3(p.origin())) })) - } - _ => None, - }) - .collect() -} - -/// Push the planar faces of `b` lying in the plane (n, d) — n their outward normal — along n -/// by `delta` (negative: inward). Their neighbours must stand perpendicular to the plane. The -/// result's history is over `[b]`. -pub(crate) fn push_faces(b: &Body, n: Vec3, d: f64, delta: f64) -> Result { - // The exact rebuild, unless it came out unsound (a curved side it couldn't re-sweep). - match push_faces_exact(b, n, d, delta) - .and_then(|r| if r.validity().is_empty() { Ok(r) } else { Err(KernelError::Failed("pushing a face: an unsound result".into())) }) - { - Ok(r) => Ok(r), - // Faces of planes and cylinders: every face follows (any neighbours). - Err(e) => { - let size = b.size(); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let planes: Vec = b - .solid - .face_iter() - .map(|f| match f.oriented_surface() { - mt::Surface::Plane(p) => { - let m = p.normal(); - let m = Vec3::new(m.x, m.y, m.z); - m.dot(n) > 1.0 - 1e-9 && (n.dot(from_p3(p.origin())) - d).abs() < tol - } - _ => false, - }) - .collect(); - crate::offset::offset_body(b, |i, _| if planes.get(i).copied().unwrap_or(false) { delta } else { 0.0 }).map_err(|_| e) - } - } -} - -pub(crate) fn push_faces_exact(b: &Body, n: Vec3, d: f64, delta: f64) -> Result { - let size = b.size(); - let tol = (size * 1e-7).max(1e-9); - let fail = |m: &str| KernelError::Failed(format!("pushing a face: {m}")); - guard("push face", || { - let solid = b.deep_copy(); - // The copy's edges are b's, in order; the faces come out in place, one for one. - let mut edge_origins = record::edge_origins(&solid, 0); - let mut faces_from = Vec::new(); - let shift = n * delta; - let mat = mt::Matrix4::from_translation(v3(shift)); - let mut shells = Vec::new(); - for sh in solid.boundaries() { - let faces: Vec = sh.face_iter().cloned().collect(); - let on_plane = |f: &mt::Face| match f.oriented_surface() { - mt::Surface::Plane(p) => { - let m = p.normal(); - let m = Vec3::new(m.x, m.y, m.z); - m.dot(n) > 1.0 - 1e-9 && (n.dot(from_p3(p.origin())) - d).abs() < tol * 10.0 - } - _ => false, - }; - let moving: Vec = (0..faces.len()).filter(|i| faces.get(*i).is_some_and(on_plane)).collect(); - let first = faces_from.len(); - if moving.is_empty() { - faces_from.extend((first..first + faces.len()).map(|i| record::from_face(0, i, Change::Kept))); - shells.push(sh.clone()); - continue; - } - // Vertices and edges of the moving faces. - let mut vmap: HashMap = HashMap::new(); - let mut emap: HashMap = HashMap::new(); - for i in &moving { - let f = faces.get(*i).ok_or_else(|| fail("face"))?; - for v in f.vertex_iter() { - vmap.entry(v.id()).or_insert_with(|| builder::vertex(p3(from_p3(v.point()) + shift))); - } - } - for i in &moving { - let f = faces.get(*i).ok_or_else(|| fail("face"))?; - for e in f.edge_iter() { - if emap.contains_key(&e.id()) { - continue; - } - let (a, bb) = ( - vmap.get(&e.absolute_front().id()).ok_or_else(|| fail("vertex"))?, - vmap.get(&e.absolute_back().id()).ok_or_else(|| fail("vertex"))?, - ); - let curve = mt::Transformed::transformed(&e.curve(), mat); - emap.insert(e.id(), mt::Edge::new(a, bb, curve)); - } - } - // Edges leaving the plane at moved vertices: straight, along n. - for f in &faces { - for e in f.edge_iter() { - if emap.contains_key(&e.id()) { - continue; - } - let (fa, fb) = (e.absolute_front(), e.absolute_back()); - let (ma, mb) = (vmap.get(&fa.id()), vmap.get(&fb.id())); - if ma.is_none() && mb.is_none() { - continue; - } - if !matches!(e.curve(), mt::Curve::Line(_)) { - return Err(fail("a neighbouring edge is not straight")); - } - let dir = (from_p3(fb.point()) - from_p3(fa.point())).normalized().ok_or_else(|| fail("zero edge"))?; - if dir.cross(n).len() > 1e-9 { - return Err(fail("a neighbouring face is not perpendicular")); - } - let (na, nb) = (ma.cloned().unwrap_or_else(|| fa.clone()), mb.cloned().unwrap_or_else(|| fb.clone())); - if (from_p3(nb.point()) - from_p3(na.point())).dot(dir) <= tol { - return Err(fail("the face would pass its opposite side")); - } - emap.insert(e.id(), builder::line(&na, &nb)); - } - } - let rebuild_wires = |f: &mt::Face| -> Vec { - f.absolute_boundaries() - .iter() - .map(|w| { - w.edge_iter() - .map(|e| match emap.get(&e.id()) { - Some(ne) => { - if e.front() == e.absolute_front() { - ne.clone() - } else { - ne.inverse() - } - } - None => e.clone(), - }) - .collect::>() - .into() - }) - .collect() - }; - // Each moved or stretched edge stands for the one it replaces. - for (old, new) in &emap { - if let Some(o) = edge_origins.get(old).cloned() { - edge_origins.insert(new.id(), o); - } - } - use mt::{ParametricSurface3D, SearchNearestParameter}; - let mut out: Vec = Vec::new(); - for (i, f) in faces.iter().enumerate() { - let touches = f.edge_iter().any(|e| emap.contains_key(&e.id())); - let change = if touches { Change::Modified } else { Change::Kept }; - faces_from.push(record::from_face(0, first + i, change)); - if !touches { - out.push(f.clone()); - continue; - } - let wires = rebuild_wires(f); - let surface = if moving.contains(&i) { - mt::Transformed::transformed(&f.surface(), mat) - } else if matches!(f.surface(), mt::Surface::Plane(_)) { - f.surface() - } else { - // A curved side: sweep its edge in the plane along the new height. - let base = f.edge_iter().find_map(|e| { - emap.get(&e.id()).filter(|_| { - let (a, bb) = (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point())); - (n.dot(a) - d).abs() < tol * 10.0 && (n.dot(bb) - d).abs() < tol * 10.0 - }) - }); - let base = base.ok_or_else(|| fail("a curved side without an edge in the plane"))?; - let height = f.vertex_iter().map(|v| n.dot(from_p3(v.point())) - d).fold(0.0f64, |m, x| if x.abs() > m.abs() { x } else { m }); - let swept: mt::Face = builder::tsweep(base, v3(n * (height - delta))); - let mut s = swept.surface(); - // Same normal as the old side at a point both share. - let probe = f.vertex_iter().map(|v| from_p3(v.point())).fold(Vec3::ZERO, |a, x| a + x) / f.vertex_iter().count().max(1) as f64; - let old = f.surface(); - if let (Some((u0, v0)), Some((u1, v1))) = - (old.search_nearest_parameter(p3(probe), None, 100), s.search_nearest_parameter(p3(probe), None, 100)) - { - let (a, bb) = (old.normal(u0, v0), s.normal(u1, v1)); - if mt::InnerSpace::dot(a, bb) < 0.0 { - s = mt::Invertible::inverse(&s); - } - } - s - }; - let mut nf = mt::Face::try_new(wires, surface).map_err(|e| fail(&e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - out.push(nf); - } - shells.push(out.into()); - } - let s = Solid::try_new(shells).map_err(|e| fail(&e.to_string()))?; - record::build(s, &record::counts(&[b]), Some(faces_from), Some(&edge_origins)) - }) -} - -/// Move the planar faces of `b` that lie in the plane (n, d), n their outward normal, out by `delta`, whatever their -/// neighbours are. [`push_faces`] stretches the neighbours, which must stand square to the face along straight edges (a -/// box, an extruded outline); the neighbours of a lofted tube's end cap curve and lean. Here nothing is stretched: the -/// faces move, and each edge one shares with a face that stays gets a new face between them, the edge swept along `n` -/// (a strip). The neighbours keep their surfaces and meet the strips at a crease along the old edge, so the body is -/// the old one with a short prism of the faces' outline on each of them. Exact, with no boolean. The result has no -/// history. -pub(crate) fn grow_faces_exact(b: &Body, n: Vec3, d: f64, delta: f64) -> Result { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; - let size = b.size(); - let tol = (size * 1e-7).max(1e-9); - let fail = |m: &str| KernelError::Failed(format!("growing a face: {m}")); - guard("grow face", || { - let solid = b.deep_copy(); - let shift = n * delta; - let mat = mt::Matrix4::from_translation(v3(shift)); - let mut shells = Vec::new(); - for sh in solid.boundaries() { - let faces: Vec = sh.face_iter().cloned().collect(); - let on_plane = |f: &mt::Face| match f.oriented_surface() { - mt::Surface::Plane(p) => { - let m = p.normal(); - let m = Vec3::new(m.x, m.y, m.z); - m.dot(n) > 1.0 - 1e-9 && (n.dot(from_p3(p.origin())) - d).abs() < tol * 10.0 - } - _ => false, - }; - let moving: Vec = (0..faces.len()).filter(|i| faces.get(*i).is_some_and(on_plane)).collect(); - if moving.is_empty() { - shells.push(sh.clone()); - continue; - } - let stays = |i: &usize| !moving.contains(i); - // The faces each edge bounds. - let mut bounds: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for e in f.edge_iter() { - bounds.entry(e.id()).or_default().push(i); - } - } - // The moved copies of the moving faces' vertices and edges. - let mut vmap: HashMap = HashMap::new(); - let mut emap: HashMap = HashMap::new(); - for i in &moving { - let f = faces.get(*i).ok_or_else(|| fail("face"))?; - for v in f.vertex_iter() { - vmap.entry(v.id()).or_insert_with(|| builder::vertex(p3(from_p3(v.point()) + shift))); - } - } - for i in &moving { - let f = faces.get(*i).ok_or_else(|| fail("face"))?; - for e in f.edge_iter() { - if emap.contains_key(&e.id()) { - continue; - } - let (a, bb) = ( - vmap.get(&e.absolute_front().id()).ok_or_else(|| fail("vertex"))?, - vmap.get(&e.absolute_back().id()).ok_or_else(|| fail("vertex"))?, - ); - emap.insert(e.id(), mt::Edge::new(a, bb, mt::Transformed::transformed(&e.curve(), mat))); - } - } - // The moved copy of an edge, running the way the edge does. - let moved = |e: &mt::Edge| -> Result { - let ne = emap.get(&e.id()).ok_or_else(|| fail("edge"))?; - Ok(if e.front() == e.absolute_front() { ne.clone() } else { ne.inverse() }) - }; - // A strip on every edge between a moving face and one that stays; the edges from a vertex to its moved copy are - // shared by the two strips that meet there. - let mut lateral: HashMap = HashMap::new(); - let mut strips: Vec = Vec::new(); - for i in &moving { - let f = faces.get(*i).ok_or_else(|| fail("face"))?; - for w in f.boundaries() { - for e in w.edge_iter() { - let Some(&beside) = bounds.get(&e.id()).and_then(|fs| fs.iter().find(|j| stays(j))) else { continue }; - // The moving face runs along the edge from p to q; the strip runs along it the same way. - let (p, q) = (e.front().clone(), e.back().clone()); - let mut lat = |v: &mt::Vertex| -> Result { - let to = vmap.get(&v.id()).ok_or_else(|| fail("vertex"))?; - Ok(lateral.entry(v.id()).or_insert_with(|| builder::line(v, to)).clone()) - }; - let (lp, lq) = (lat(&p)?, lat(&q)?); - let wire: mt::Wire = vec![e.clone(), lq, moved(e)?.inverse(), lp.inverse()].into(); - // Its surface is the edge's curve swept along `n`, facing the way the face beside it does; a straight edge - // sweeps to a plane (truck makes that a B-spline patch, which does not mesh). - let curve = e.curve(); - let (t0, t1) = curve.range_tuple(); - let mid = from_p3(curve.subs(0.5 * (t0 + t1))); - let old = faces.get(beside).ok_or_else(|| fail("face"))?.oriented_surface(); - let Some((u0, v0)) = old.search_nearest_parameter(p3(mid), None, 100) else { - return Err(fail("which way a strip faces")); - }; - let outward = old.normal(u0, v0); - let outward = Vec3::new(outward.x, outward.y, outward.z); - // (a loft's straight section edge is a B-spline of degree one, so ask the points, not the type) - let straight = [0.2, 0.4, 0.6, 0.8].iter().all(|t| { - let x = from_p3(curve.subs(t0 + t * (t1 - t0))); - let chord = from_p3(q.point()) - from_p3(p.point()); - let off = (x - from_p3(p.point())).cross(chord).len(); - off <= tol * 10.0 * chord.len() - }); - let s = if straight { - let dir = (from_p3(q.point()) - from_p3(p.point())).normalized().ok_or_else(|| fail("a zero edge"))?; - let mut m = dir.cross(n).normalized().ok_or_else(|| fail("an edge along the normal"))?; - if m.dot(outward) < 0.0 { - m = -m; - } - let o = from_p3(p.point()); - mt::Surface::Plane(mt::Plane::new(p3(o), p3(o + dir), p3(o + m.cross(dir)))) - } else { - let swept: mt::Face = builder::tsweep(e, v3(shift)); - let mut s = swept.surface(); - let Some((u1, v1)) = s.search_nearest_parameter(p3(mid + shift * 0.5), None, 100) else { - return Err(fail("which way a strip faces")); - }; - let now = s.normal(u1, v1); - if outward.dot(Vec3::new(now.x, now.y, now.z)) < 0.0 { - s = mt::Invertible::inverse(&s); - } - s - }; - strips.push(mt::Face::try_new(vec![wire], s).map_err(|e| fail(&e.to_string()))?); - } - } - } - let mut out: Vec = Vec::new(); - for (i, f) in faces.iter().enumerate() { - if !moving.contains(&i) { - out.push(f.clone()); - continue; - } - let wires = f - .absolute_boundaries() - .iter() - .map(|w| w.edge_iter().map(&moved).collect::>>().map(mt::Wire::from)) - .collect::>>()?; - let mut nf = mt::Face::try_new(wires, mt::Transformed::transformed(&f.surface(), mat)).map_err(|e| fail(&e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - out.push(nf); - } - out.extend(strips); - shells.push(out.into()); - } - let s = Solid::try_new(shells).map_err(|e| fail(&e.to_string()))?; - let r = Body::new(s)?; - let problems = r.validity(); - if !problems.is_empty() { - return Err(fail(&format!("an unsound result ({})", problems.iter().take(2).cloned().collect::>().join("; ")))); - } - Ok(r) - }) -} - -/// An edge's points from its start to its end along its curve, `k + 1` of them. -fn edge_samples(e: &mt::Edge, k: u32) -> Vec { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=k).map(|i| from_p3(c.subs(t0 + (t1 - t0) * f64::from(i) / f64::from(k)))).collect() -} - -/// Where the edges of `b` cross the plane (n, d), one point for every time (edges are cut there before a body is trimmed). -fn plane_crossings(b: &Body, n: Vec3, d: f64, tol: f64) -> Vec { - use mt::{BoundedCurve, ParametricCurve}; - const STEPS: u32 = 64; - let mut out = Vec::new(); - for e in b.solid.edge_iter() { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let at = |t: f64| from_p3(c.subs(t)); - let h = |t: f64| n.dot(at(t)) - d; - let ts: Vec = (0..=STEPS).map(|i| t0 + (t1 - t0) * f64::from(i) / f64::from(STEPS)).collect(); - // The samples clear of the plane, and between each two that lie on different sides the crossing. - let clear: Vec<(f64, f64)> = ts.iter().map(|t| (*t, h(*t))).filter(|(_, x)| x.abs() > tol).collect(); - for pair in clear.windows(2) { - let [(ta, ha), (tb, hb)] = pair else { continue }; - if (*ha < 0.0) == (*hb < 0.0) { - continue; - } - let (mut lo, mut hi, mut hlo) = (*ta, *tb, *ha); - for _ in 0..80 { - let mid = 0.5 * (lo + hi); - let hm = h(mid); - if (hm < 0.0) == (hlo < 0.0) { - lo = mid; - hlo = hm; - } else { - hi = mid; - } - } - out.push(at(0.5 * (lo + hi))); - } - } - out -} - -/// Which side of the plane (n, d) an edge lies on, once edges that cross it are cut: -1 near, +1 far, 0 in it. -fn edge_side(e: &mt::Edge, n: Vec3, d: f64, tol: f64) -> Result { - let hs: Vec = edge_samples(e, 8).iter().map(|p| n.dot(*p) - d).collect(); - let (lo, hi) = hs.iter().fold((f64::MAX, f64::MIN), |(l, h), x| (l.min(*x), h.max(*x))); - if hi <= tol && lo >= -tol { - Ok(0) - } else if hi <= tol { - Ok(-1) - } else if lo >= -tol { - Ok(1) - } else { - Err(KernelError::Failed("trimming at a plane: an edge still crosses it".into())) - } -} - -/// Whether the point lies on the surface, to within `tol`. -fn on_surface(s: &mt::Surface, p: Vec3, tol: f64) -> bool { - use mt::{ParametricSurface, SearchNearestParameter}; - if let mt::Surface::Plane(pl) = s { - let m = pl.normal(); - return (Vec3::new(m.x, m.y, m.z).dot(p - from_p3(pl.origin()))).abs() <= tol; - } - s.search_nearest_parameter(p3(p), None, 100).is_some_and(|(u, v)| from_p3(s.subs(u, v)).dist(p) <= tol) -} - -/// The edge that closes the boundary of the flat face `face` from the vertex `from` to the vertex `to` (both in the plane) where a run of -/// its edges beyond the plane went: the segment between them, which lies in the face. (A curved face that crosses the plane has been -/// divided along it already.) Nothing when they are the same vertex. -fn bridge(face: &mt::Face, from: &mt::Vertex, to: &mt::Vertex, tol: f64) -> Result> { - if from.id() == to.id() { - return Ok(Vec::new()); - } - let (p, q) = (from_p3(from.point()), from_p3(to.point())); - let surface = face.oriented_surface(); - if [0.25, 0.5, 0.75].iter().all(|t| on_surface(&surface, p + (q - p) * *t, tol * 10.0)) { - Ok(vec![builder::line(from, to)]) - } else { - Err(KernelError::Failed("trimming at a plane: a curved face crosses the plane where it could not be divided".into())) - } -} - -/// One boundary of the flat face `face`, which crosses the plane (n, d), clipped to the near side: the edges beyond the plane go and the -/// segment in the plane from where the boundary leaves it to where it comes back takes their place. `None` when nothing of the boundary -/// is on the near side. -fn clip_wire(face: &mt::Face, w: &mt::Wire, n: Vec3, d: f64, tol: f64) -> Result>> { - let fail = |m: &str| KernelError::Failed(format!("trimming at a plane: {m}")); - let mut edges: Vec<(mt::Edge, i8)> = Vec::new(); - for e in w.edge_iter() { - let side = edge_side(e, n, d, tol)?; - edges.push((e.clone(), side)); - } - if !edges.iter().any(|(_, side)| *side < 0) { - return Ok(None); - } - let m = edges.len(); - let gone = |i: usize| edges.get(i % m).is_some_and(|(_, side)| *side > 0); - // Begin where a run of edges beyond the plane ends, so that no run is split between the end and the start. - let Some(start) = (0..m).find(|i| !gone(*i) && gone(*i + m - 1)) else { - return Ok(Some(edges.into_iter().map(|(e, _)| e).collect())); - }; - let mut out: Vec = Vec::new(); - let mut skipping = false; - for k in 0..m { - let Some((e, side)) = edges.get((start + k) % m) else { continue }; - if *side > 0 { - skipping = true; - continue; - } - if skipping { - let from = out.last().ok_or_else(|| fail("a run beyond the plane first"))?.back().clone(); - out.extend(bridge(face, &from, e.front(), tol)?); - skipping = false; - } - out.push(e.clone()); - } - if skipping { - let from = out.last().ok_or_else(|| fail("nothing kept"))?.back().clone(); - let to = out.first().ok_or_else(|| fail("nothing kept"))?.front().clone(); - out.extend(bridge(face, &from, &to, tol)?); - } - Ok(Some(out)) -} - -/// `b` with everything beyond the plane (n, d) cut off, for a body that was grown or pushed past the plane (the faces that -/// [`grow_faces_exact`] and [`push_faces`] moved) and joined there. A cut with a boolean would run along the edges where the grown -/// faces meet their neighbours, which the mesh intersection cannot take. Here the edges that cross the plane are cut at it, the -/// faces beyond it go, each face that crosses it gets one edge in the plane where its far part was, and the rim they leave (edges -/// lying in the plane) is closed with flat faces. The result has no history. -pub(crate) fn trim_exact(b: &Body, n: Vec3, d: f64) -> Result { - let fail = |m: &str| KernelError::Failed(format!("trimming at a plane: {m}")); - let tol = (b.size() * 1e-6).max(1e-9); - // A curved face that crosses the plane (a sphere or a cylinder stretched past it) is divided along the plane where they meet, exactly - // ([`crate::splitface::split_faces`]); the flat ones are clipped below. - let curved: Vec = b - .solid - .face_iter() - .enumerate() - .filter(|(_, f)| !matches!(f.oriented_surface(), mt::Surface::Plane(_))) - .filter(|(_, f)| { - let (mut near, mut far) = (false, false); - for e in f.edge_iter() { - for p in edge_samples(&e, 8) { - near |= n.dot(p) - d < -tol; - far |= n.dot(p) - d > tol; - } - } - near && far - }) - .map(|(i, _)| i) - .collect(); - let divided = if curved.is_empty() { - b.clone() - } else { - let u = n.any_perp(); - let plane = solidcraft_geom::Plane::new(n * d, u, n.cross(u)).ok_or_else(|| fail("the plane"))?; - crate::splitface::split_faces(b, &curved, &crate::SplitTool::Plane(plane))? - }; - let cut = crate::splitface::split_edges_at(÷d, &plane_crossings(÷d, n, d, tol))?; - guard("trim at a plane", || { - let mut kept: Vec = Vec::new(); - for f in cut.solid.face_iter() { - let mut sides: Vec = Vec::new(); - for e in f.edge_iter() { - sides.push(edge_side(&e, n, d, tol)?); - } - match (sides.contains(&-1), sides.contains(&1)) { - (true, false) => kept.push(f.clone()), - (false, true) => {} - // A face lying in the plane (a sliver the join left there) goes with the others: the rim it leaves is closed below. - (false, false) => {} - (true, true) => { - let mut wires: Vec = Vec::new(); - for (i, w) in f.absolute_boundaries().iter().enumerate() { - match clip_wire(f, w, n, d, tol)? { - Some(edges) => wires.push(edges.into()), - None if i == 0 => return Err(fail("a face with no edge left on the near side")), - None => {} - } - } - let mut nf = mt::Face::try_new(wires, f.surface()).map_err(|x| fail(&x.to_string()))?; - if !f.orientation() { - nf.invert(); - } - kept.push(nf); - } - } - } - close_rim(kept, n, d, tol) - }) -} - -/// The body whose faces are `faces`, which leave an opening in the plane (n, d): the edges only one face is on (all lying in the plane) -/// are closed with flat faces. Counterclockwise loops about the normal are outlines, the others holes in the outline around them. -fn close_rim(mut faces: Vec, n: Vec3, d: f64, tol: f64) -> Result { - let fail = |m: &str| KernelError::Failed(format!("closing the cut: {m}")); - let mut uses: HashMap = HashMap::new(); - for f in &faces { - for e in f.edge_iter() { - *uses.entry(e.id()).or_default() += 1; - } - } - if uses.values().any(|c| *c > 2) { - return Err(fail("an edge on more than two faces")); - } - let mut open: Vec = Vec::new(); - for f in &faces { - for w in f.boundaries() { - for e in w.edge_iter() { - if uses.get(&e.id()) == Some(&1) { - if edge_samples(e, 8).iter().any(|p| (n.dot(*p) - d).abs() > tol) { - return Err(fail("an edge left open off the plane")); - } - // The cap runs along it the other way. - open.push(e.inverse()); - } - } - } - } - if open.is_empty() { - return Err(fail("nothing was cut off")); - } - let mut loops: Vec> = Vec::new(); - while let Some(first) = open.pop() { - let start = first.front().id(); - let mut at = first.back().id(); - let mut chain = vec![first]; - while at != start { - let next: Vec = (0..open.len()).filter(|i| open.get(*i).is_some_and(|e| e.front().id() == at)).collect(); - let [i] = next[..] else { return Err(fail("the rim does not close up, or pinches")) }; - let e = open.remove(i); - at = e.back().id(); - chain.push(e); - } - loops.push(chain); - } - let u = n.any_perp(); - let v = n.cross(u); - let origin = n * d; - let polys: Vec> = loops - .iter() - .map(|chain| { - chain - .iter() - .flat_map(|e| { - let mut pts = edge_samples(e, 8); - if !e.orientation() { - pts.reverse(); - } - pts.pop(); - pts - }) - .map(|p| ((p - origin).dot(u), (p - origin).dot(v))) - .collect() - }) - .collect(); - let areas: Vec = polys - .iter() - .map(|poly| { - let m = poly.len(); - (0..m) - .map(|i| match (poly.get(i), poly.get((i + 1) % m)) { - (Some(a), Some(b)) => a.0 * b.1 - b.0 * a.1, - _ => 0.0, - }) - .sum::() - * 0.5 - }) - .collect(); - let inside = |poly: &[(f64, f64)], q: (f64, f64)| -> bool { - let m = poly.len(); - (0..m) - .filter(|i| match (poly.get(*i), poly.get((*i + 1) % m)) { - (Some(a), Some(b)) => (a.1 > q.1) != (b.1 > q.1) && q.0 < (b.0 - a.0) * (q.1 - a.1) / (b.1 - a.1) + a.0, - _ => false, - }) - .count() - % 2 - == 1 - }; - let outers: Vec = (0..loops.len()).filter(|i| areas.get(*i).is_some_and(|a| *a > 0.0)).collect(); - let mut holes_of: HashMap> = HashMap::new(); - for i in (0..loops.len()).filter(|i| !outers.contains(i)) { - let q = polys.get(i).and_then(|p| p.first()).copied().ok_or_else(|| fail("an empty loop"))?; - let around = outers - .iter() - .filter(|o| polys.get(**o).is_some_and(|p| inside(p, q))) - .min_by(|x, y| areas.get(**x).partial_cmp(&areas.get(**y)).unwrap_or(std::cmp::Ordering::Equal)) - .ok_or_else(|| fail("a hole outside every outline"))?; - holes_of.entry(*around).or_default().push(i); - } - let surface = mt::Surface::Plane(mt::Plane::new(p3(origin), p3(origin + u), p3(origin + v))); - for o in &outers { - let mut wires: Vec = vec![loops.get(*o).cloned().ok_or_else(|| fail("a loop"))?.into()]; - for h in holes_of.get(o).into_iter().flatten() { - wires.push(loops.get(*h).cloned().ok_or_else(|| fail("a loop"))?.into()); - } - faces.push(mt::Face::try_new(wires, surface.clone()).map_err(|x| fail(&x.to_string()))?); - } - let shell: mt::Shell = faces.into(); - let solid = Solid::try_new(crate::polybool::components_in_order(&shell)).map_err(|x| fail(&x.to_string()))?; - let r = Body::new(solid)?; - let problems = r.validity(); - if !problems.is_empty() { - return Err(fail(&format!("an unsound result ({})", problems.iter().take(2).cloned().collect::>().join("; ")))); - } - Ok(r) -} - -/// Move the planar faces of `x` in the plane (n, d) out by `delta`: stretched ([`push_faces`]) where their neighbours -/// allow it, else, when `grow`, grown ([`grow_faces_exact`]). Whether it grew them (the body then has no history). -fn move_out(x: &Body, n: Vec3, d: f64, delta: f64, grow: bool) -> Result<(Body, bool)> { - match push_faces(x, n, d, delta) { - Ok(r) => Ok((r, false)), - Err(e) if grow => grow_faces_exact(x, n, d, delta).map(|r| (r, true)).map_err(|_| e), - Err(e) => Err(e), - } -} - -/// A box covering everything beyond the plane (n, d) by up to `depth`. -fn slab_beyond(n: Vec3, d: f64, depth: f64, extent: f64) -> Result { - let u = n.any_perp(); - let w = n.cross(u); - let o = n * d; - let pl = solidcraft_geom::Plane::new(o, u, w).ok_or_else(|| KernelError::Failed("slab plane".into()))?; - let sq = solidcraft_geom::Loop2::polygon(&[ - solidcraft_geom::Vec2::new(-extent, -extent), - solidcraft_geom::Vec2::new(extent, -extent), - solidcraft_geom::Vec2::new(extent, extent), - solidcraft_geom::Vec2::new(-extent, extent), - ]); - let r = solidcraft_geom::Region2 { outer: sq, holes: vec![] }; - crate::extrude(&pl, &[r], 0.0, depth)?.pop().ok_or_else(|| KernelError::Failed("slab".into())) -} - -/// The box of a face's boundary sampled to within `tol` of each curve: the face, planar, lies -/// within `tol` of it. `None` when the boundary can't be sampled. -fn face_box(f: &mt::Face, tol: f64) -> Option { - use mt::{BoundedCurve, ParameterDivision1D}; - const MAX_POINTS: usize = 100_000; - guard("face box", || { - let mut bb = Aabb3::EMPTY; - let mut count = 0usize; - for e in f.edge_iter() { - let points = match e.curve() { - mt::Curve::Line(_) => vec![e.front().point(), e.back().point()], - // The division checks its deviation at midpoints only (as in blend.rs). - c => c.parameter_division(c.range_tuple(), tol * 0.25).1, - }; - count = count.saturating_add(points.len()); - if count > MAX_POINTS { - return Err(KernelError::Failed("face box: too many boundary points".into())); - } - for p in points { - bb.add(from_p3(p)); - } - } - if bb.is_empty() { - return Err(KernelError::Failed("face box: no boundary".into())); - } - Ok(bb) - }) - .ok() -} - -/// The planes (normal, offset) in which a planar face of `a` and one of `b` coincide, as `a`'s -/// face lies in them, each with whether `b`'s face points the same way. Faces in a common plane but apart from -/// each other (the tops of two posts standing on one floor) don't coincide: they need no -/// pushing apart. A face whose extent can't be found counts as meeting every face in its plane. -pub(crate) fn coincident_planes(a: &Body, b: &Body) -> Vec<(Vec3, f64, bool)> { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let sample = (size * 1e-4).max(tol); - let (fa, fb): (Vec<&mt::Face>, Vec<&mt::Face>) = (a.solid.face_iter().collect(), b.solid.face_iter().collect()); - let (pa, pb) = (planes(a), planes(b)); - let (mut boxes_a, mut boxes_b): (Vec>>, Vec>>) = (vec![None; fa.len()], vec![None; fb.len()]); - let mut found: Vec<(Vec3, f64, bool)> = Vec::new(); - for (ia, x) in &pa { - for (ib, y) in &pb { - let cos = x.n.dot(y.n); - if cos.abs() <= 1.0 - 1e-9 || (x.d - y.d * cos).abs() >= tol { - continue; - } - let same = cos > 0.0; - if found.iter().any(|(n, d, s)| *s == same && n.dot(x.n) > 1.0 - 1e-9 && (d - x.d).abs() < tol) { - continue; - } - let ba = boxes_a.get_mut(*ia).and_then(|b| *b.get_or_insert_with(|| fa.get(*ia).and_then(|f| face_box(f, sample)))); - let bb = boxes_b.get_mut(*ib).and_then(|b| *b.get_or_insert_with(|| fb.get(*ib).and_then(|f| face_box(f, sample)))); - // Each box is within `sample` of its face. - if !ba.zip(bb).is_some_and(|(p, q)| boxes_separate(p, q, 2.0 * sample)) { - found.push((x.n, x.d, same)); - } - } - } - found -} - -/// What [`boolean_apart`] fails with when a face has no room to move. -pub(crate) const NO_ROOM: &str = "coincident faces were left in place: pushing them apart would change the result"; - -/// Retry a failed boolean with coincident planar faces pushed apart. `None` when there are no -/// coincident faces or the faces can't be pushed; the error [`NO_ROOM`] when a face would -/// move through something that changes the result. -pub(crate) fn boolean_apart(a: &Body, b: &Body, op: BoolOp) -> Option>> { - apart_with(a, b, op, false) -} - -/// [`boolean_apart`] for a join whose coincident faces cannot be pushed, because the neighbours of one of them curve -/// (a flange flush with the end of a lofted tube): such a face is grown instead ([`grow_faces_exact`]) and the join's excess beyond -/// the plane is cut off again by editing faces ([`trim_exact`]), where a boolean would fail on the edges the grown faces meet their -/// neighbours along. The planar faces that sit on B-spline surfaces (a loft's flat sides) are put on planes first so that they -/// are seen. Asked after the other routes have failed, so that what they take stays as it was. `None` when it does not apply. -pub(crate) fn boolean_grown(a: &Body, b: &Body, op: BoolOp) -> Option>> { - if op != BoolOp::Union { - return None; - } - let (pa, pb) = (crate::planar_faces::planarized(a), crate::planar_faces::planarized(b)); - apart_with(pa.as_ref().unwrap_or(a), pb.as_ref().unwrap_or(b), op, true) -} - -fn apart_with(a: &Body, b: &Body, op: BoolOp, grow: bool) -> Option>> { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9); - let coincident = coincident_planes(a, b); - if coincident.is_empty() { - return None; - } - let same: Vec<(Vec3, f64)> = coincident.iter().filter(|(_, _, s)| *s).map(|(n, d, _)| (*n, *d)).collect(); - let back: Vec<(Vec3, f64)> = coincident.iter().filter(|(_, _, s)| !*s).map(|(n, d, _)| (*n, *d)).collect(); - let (d1, d2) = (size * 0.0137, size * 0.0229); - let counts = record::counts(&[a, b]); - let (skin, chord) = (tol * 10.0, size * 2e-4); - let no_room = || KernelError::Failed(NO_ROOM.into()); - let run = || -> Result> { - // The target's faces, meshed when the first face asks what it would move through. - let faces_of_a = std::cell::OnceCell::new(); - let target = || faces_of_a.get_or_init(|| Clearance::new(a, chord).map(|c| c.with_exact_bounds(grow))).as_ref().ok_or_else(no_room); - let (mut a2, mut b2) = (a.clone(), b.clone()); - // What the pushed bodies are made of: their histories over [a] and [b]. - let (mut ha, mut hb) = (crate::boolean_record::kept(a, 0, 1), crate::boolean_record::kept(b, 0, 1)); - for (n, d) in &same { - // b's face points along n too. - let free = if op == BoolOp::Union { - // Both faces move out and the slab beyond the plane is cut off the joined body - // again, everywhere: neither body may have anything in it. - let depth = d1.max(d2) * 3.0 * 1.25; - let tool = Clearance::new(b, chord).ok_or_else(no_room)?.with_exact_bounds(grow); - target()?.clear_of_slab(*n, *d, skin, depth) && tool.clear_of_slab(*n, *d, skin, depth) - } else { - // The tool takes whatever of `a` its face moves through (a rib standing on the - // face a cut ends in). - target()?.swept(&in_plane(&b2, *n, *d, skin), *n, skin, d2 * 1.25) == Occupancy::Empty - }; - if !free { - return Err(no_room()); - } - // A body that has to be grown goes deeper than one that is pushed: the pushed body's stretched sides then end inside - // the prism the grown one leaves beyond the plane, wherever they meet it, and cross the plane once each. - let swap = grow && push_faces(&a2, *n, *d, d1).is_err() && push_faces(&b2, *n, *d, d2).is_ok(); - let (da, db) = if swap { (d2, d1) } else { (d1, d2) }; - let (moved_b, b_grown) = move_out(&b2, *n, *d, db, grow)?; - b2 = moved_b; - hb = if b_grown { None } else { crate::boolean_record::through(&b2, 0, hb.as_ref()) }; - if op == BoolOp::Union { - let (moved_a, a_grown) = move_out(&a2, *n, *d, da, grow)?; - a2 = moved_a; - ha = if a_grown { None } else { crate::boolean_record::through(&a2, 0, ha.as_ref()) }; - } - } - for (n, d) in &back { - // a's face points along n; b's face points along −n at the same plane (−d). - let shift = if op == BoolOp::Union { - // Pushed into `a`, b's face must have a's material behind it all over and that - // deep: over a hole in a's face (a narrowed bore's rim over the other body's - // bore, a rib standing half over a window) it would fill the hole, through a - // thin wall it would stick out the far side (#616). The other retries take - // such a join instead. - [d2, d2 * 0.25, d2 * 0.0625] - .into_iter() - .find(|depth| backed(a, b, -*n, -*d, *depth)) - .ok_or_else(|| KernelError::Failed("pushing a face: part of it lies over a hole or past the edge of the other body".into()))? - } else { - // Back into the tool, the face gives up what the tool took of `a` there (a - // wall standing beside the face the tool's foot lies on). - if target()?.swept(&in_plane(&b2, -*n, -*d, skin), *n, skin, d2 * 1.25) != Occupancy::Empty { - return Err(no_room()); - } - -d2 - }; - b2 = push_faces(&b2, -*n, -*d, shift)?; - hb = crate::boolean_record::through(&b2, 0, hb.as_ref()); - } - let Some(mut r) = crate::ops::boolean(&a2, &b2, op)? else { return Ok(None) }; - // The pushed bodies' histories as over [a, b], a's and b's in their places. - let (ha, hb) = (crate::boolean_record::placed(ha, 0, 2), crate::boolean_record::placed(hb, 1, 2)); - let mut h = crate::boolean_record::of_pair(&r, &ha, &hb); - if op == BoolOp::Union && grow { - // What grown faces left beyond each plane is cut off by editing the faces: a cut along the plane would run along the - // edges where the grown faces meet their neighbours, which the mesh intersection cannot take. - for (n, d) in &same { - r = trim_exact(&r, *n, *d)?; - } - h = None; - } else if op == BoolOp::Union { - for (n, d) in &same { - let slab = slab_beyond(*n, *d, d1.max(d2) * 3.0, size * 4.0)?; - match crate::ops::boolean(&r, &slab, BoolOp::Cut) { - Ok(Some(x)) => { - h = h.and_then(|h| trimmed(&x, h, &slab, [a, b], *n, *d, tol)); - r = x; - } - Ok(None) => return Ok(None), - // An edge of the union can lie in the plane, where a pushed side crosses a side - // of the other body (a prism's edge in the plane lying in a slab's end face): - // the cut along it fails, and the same trim is made by editing the faces. - Err(e) => { - r = trim_exact(&r, *n, *d).map_err(|_| e)?; - h = None; - } - } - } - } - Ok(Some(r.with_checked_history(h, &counts))) - }; - Some(run()) -} - -/// The history over `[a, b]` of `x`, the union `r` of `a` and `b` (with history `h` over them), -/// pushed out past the plane (n, d), with the slab beyond it (`slab`, whose start cap lies in -/// the plane) cut off. The slab's cap in `x` is where the operands' faces in that plane were -/// (all of them, so only a cap that stays one face says which), and where it meets a side of -/// an operand is that side's edge along one of those faces. `None` where that is not so. -fn trimmed(x: &Body, h: History, slab: &Body, operands: [&Body; 2], n: Vec3, d: f64, tol: f64) -> Option { - let mut cut = x.history()?.clone(); - cut.substitute(0, &h).ok()?; - let cap = slab.history()?.faces.iter().position(|f| f.origins == [FaceOrigin::Cap { end: false }])?; - let cap = FaceOrigin::Face { operand: 2, face: cap }; - // The operands' faces in the plane, facing along n, and their edges with each other face. - let in_plane: Vec> = operands - .iter() - .map(|o| planes(o).into_iter().filter(|(_, p)| p.n.dot(n) > 1.0 - 1e-9 && (p.d - d).abs() < tol * 10.0).map(|(i, _)| i).collect()) - .collect(); - let bounds: Vec>> = operands.iter().map(|o| crate::history::edge_faces(&o.solid)).collect(); - if cut.faces.iter().filter(|f| f.origins.contains(&cap)).count() != 1 { - return None; - } - for f in &mut cut.faces { - if f.origins.contains(&cap) { - let mut origins: std::collections::BTreeSet = f.origins.iter().copied().filter(|o| *o != cap).collect(); - for (operand, faces) in in_plane.iter().enumerate() { - origins.extend(faces.iter().map(|face| FaceOrigin::Face { operand, face: *face })); - } - f.change = if origins.len() > 1 { Change::Merged } else { Change::Modified }; - f.origins = origins.into_iter().collect(); - } - } - let cap = crate::history::Side::from(cap); - for e in &mut cut.edges { - for o in &mut e.origins { - let side = match o { - EdgeOrigin::Meet { a, b } if *a == cap => b, - EdgeOrigin::Meet { a, b } if *b == cap => a, - _ => continue, - }; - let Some(FaceOrigin::Face { operand, face }) = side.single() else { return None }; - let (plane_faces, bounds) = (in_plane.get(operand)?, bounds.get(operand)?); - let mut along = (0..bounds.len()) - .filter(|k| bounds.get(*k).is_some_and(|fs| fs.len() == 2 && fs.contains(&face) && fs.iter().any(|f| plane_faces.contains(f)))); - let (Some(edge), None) = (along.next(), along.next()) else { return None }; - *o = EdgeOrigin::Edge { operand, edge }; - } - } - cut.renumber(&[Some(0), Some(1), None], 2).ok()?; - Some(cut) -} - -/// Do the bodies touch over an area, back to back on a common plane: has `a` material just -/// behind some part of a face of `b` lying in a plane of a face of `a` that faces the other way? -/// (Contact along a line or at a point is not this.) -pub(crate) fn faces_touch(a: &Body, b: &Body) -> bool { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let pa = planes(a); - let faces: Vec<(usize, Vec3)> = planes(b) - .into_iter() - .filter(|(_, y)| pa.iter().any(|(_, x)| x.n.dot(y.n) < -1.0 + 1e-9 && (x.d + y.d).abs() < tol)) - .map(|(i, y)| (i, y.n)) - .collect(); - if faces.is_empty() { - return false; - } - let (Ok(ma), Ok(mb)) = (a.tessellate_with(size * 1e-3, true), b.tessellate_with(size * 1e-3, true)) else { return false }; - let inside = ma.inside_index(); - let depth = (size * 1e-4).max(1e-6); - mb.triangles.iter().zip(&mb.tri_face).take(100_000).any(|(t, fi)| { - let Some((_, n)) = faces.iter().find(|(i, _)| *i == *fi as usize) else { return false }; - mb.tri(t).is_some_and(|[p, q, r]| inside.contains((p + q + r) / 3.0 + *n * depth)) - }) -} - -/// Does `r` hold a skin of no thickness: a planar face lying on another of its planar faces that -/// faces the other way, with no material behind part of it? A cut whose tool ends exactly on a -/// face of the target can come out with the target's face whole over the hole and the tool's end -/// face under it, closing the hole. No volume shows that, and points sampled off the surface see -/// the hole either way. Faces back to back in one plane with material behind both (the top of a -/// step beside the underside of an overhang) are not this. `mesh` is `r`'s mesh; what counts is -/// an area of the faces with nothing behind it, so that the few triangles along an edge where the -/// mesh of a curved neighbour cuts the corner don't. -pub(crate) fn has_skin(r: &Body, mesh: &solidcraft_geom::Mesh) -> bool { - let size = r.size(); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let p = planes(r); - if p.len() > MAX_SKIN_FACES { - return false; - } - let paired: HashMap = p - .iter() - .filter(|(i, x)| p.iter().any(|(j, y)| i != j && x.n.dot(y.n) < -1.0 + 1e-9 && (x.d + y.d).abs() < tol)) - .map(|(i, x)| (*i, x.n)) - .collect(); - if paired.is_empty() { - return false; - } - let inside = mesh.inside_index(); - let depth = (size * 1e-4).max(1e-6); - let mut open = 0.0; - for (t, face) in mesh.triangles.iter().zip(&mesh.tri_face).take(100_000) { - let (Some(n), Some([a, b, c])) = (paired.get(&(*face as usize)), mesh.tri(t)) else { continue }; - if !inside.contains((a + b + c) / 3.0 - *n * depth) { - open += (b - a).cross(c - a).len() * 0.5; - } - } - open > (size * size * 1e-6).max(1e-9) -} - -/// The most planar faces [`has_skin`] pairs up (every pair is compared). -const MAX_SKIN_FACES: usize = 2000; - -/// The triangles of `tool`'s faces in the plane (`m`, `d`), `m` their outward normal, each with -/// how far its face reaches past it sideways. A face bounded by straight edges is its -/// triangles; they are drawn in by `skin`, so that faces of the other body lying against the -/// face's sides are not in its way. A face with a curved edge reaches past its triangles by -/// the chord error. -fn in_plane(tool: &Body, m: Vec3, d: f64, skin: f64) -> Vec<([Vec3; 3], f64)> { - let chord = (tool.size() * 2e-4).max(skin); - let Ok(mesh) = tool.tessellate_with(chord, true) else { return Vec::new() }; - let faces: Vec<&mt::Face> = tool.solid.face_iter().collect(); - let margins: HashMap = planes(tool) - .into_iter() - .filter(|(_, p)| p.n.dot(m) > 1.0 - 1e-9 && (p.d - d).abs() < skin) - .filter_map(|(i, _)| { - let straight = faces.get(i)?.edge_iter().all(|e| matches!(e.curve(), mt::Curve::Line(_))); - Some((i, if straight { -skin } else { 2.0 * chord })) - }) - .collect(); - mesh.triangles.iter().zip(&mesh.tri_face).filter_map(|(t, face)| Some((mesh.tri(t)?, *margins.get(&(*face as usize))?))).collect() -} - -/// Has `a` material behind every part of b's faces in the plane (m, d) (m their outward -/// normal, pointing into `a`), to `depth`? Checked at points inside the faces' triangles. -fn backed(a: &Body, b: &Body, m: Vec3, d: f64, depth: f64) -> bool { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let faces: Vec = planes(b).into_iter().filter(|(_, p)| p.n.dot(m) > 1.0 - 1e-9 && (p.d - d).abs() < tol).map(|(i, _)| i).collect(); - let (Ok(ma), Ok(mb)) = (a.tessellate_with(size * 1e-3, true), b.tessellate_with(size * 1e-3, true)) else { return false }; - let inside = ma.inside_index(); - let mut points = Vec::new(); - for (t, fi) in mb.triangles.iter().zip(&mb.tri_face) { - if !faces.contains(&(*fi as usize)) { - continue; - } - let Some([p, q, r]) = mb.tri(t) else { continue }; - let c = (p + q + r) / 3.0; - points.extend([c, c.lerp(p, 0.8), c.lerp(q, 0.8), c.lerp(r, 0.8)]); - if points.len() > 4000 { - break; - } - } - !points.is_empty() && points.iter().all(|p| [0.05, 0.5, 1.0].iter().all(|k| inside.contains(*p + m * (depth * k)))) -} - -/// The faces of `body` lying in the plane (n, d), facing along n. -pub(crate) fn faces_in(body: &Body, n: Vec3, d: f64, tol: f64) -> Vec { - planes(body).into_iter().filter(|(_, p)| p.n.dot(n) > 1.0 - 1e-9 && (p.d - d).abs() < tol).map(|(i, _)| i).collect() -} - -/// Do two face surfaces lie on one plane or one cylinder? -fn same_surface(x: &Option, y: &Option, tol: f64) -> bool { - use crate::FaceSurface::{Cylinder, Plane}; - match (x, y) { - (Some(Plane { normal: n1, point: p1 }), Some(Plane { normal: n2, point: p2 })) => n1.dot(*n2) > 1.0 - 1e-9 && n1.dot(*p2 - *p1).abs() < tol, - (Some(Cylinder { origin: o1, axis: a1, radius: r1 }), Some(Cylinder { origin: o2, axis: a2, radius: r2 })) => { - let off = *o2 - *o1; - a1.dot(*a2).abs() > 1.0 - 1e-9 && (r1 - r2).abs() < tol && (off - *a1 * off.dot(*a1)).len() < tol - } - _ => false, - } -} - -/// A box around face `f` from its edges' control points (a B-spline or NURBS curve with positive -/// weights lies in their hull; an edge's curve may run past the edge, which only grows the box). -/// No dividing: for choosing faces it need only contain the face, and dividing a split face's -/// curved edges down to a tolerance ran away on the sensor enclosure's lid (gigabytes, minutes). -/// `None` for an edge on an intersection curve or with weights that don't bound it. -fn hull_box(f: &mt::Face) -> Option { - let mut bb = Aabb3::EMPTY; - for e in f.edge_iter() { - match e.curve() { - mt::Curve::Line(_) => { - bb.add(from_p3(e.front().point())); - bb.add(from_p3(e.back().point())); - } - mt::Curve::BSplineCurve(c) => c.control_points().iter().for_each(|p| bb.add(from_p3(*p))), - mt::Curve::NurbsCurve(c) => { - for p in c.control_points() { - if !(p.w > 0.0 && p.w.is_finite()) { - return None; - } - bb.add(Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)); - } - } - mt::Curve::IntersectionCurve(_) => return None, - } - } - (!bb.is_empty() && bb.min.is_finite() && bb.max.is_finite()).then_some(bb) -} - -/// The box around faces `faces` of `body` ([`hull_box`]), grown by `gap`. `None` when a face's -/// extent can't be found. -fn faces_box(body: &Body, faces: &[usize], gap: f64) -> Option { - let fs: Vec<&mt::Face> = body.solid.face_iter().collect(); - let mut bb = Aabb3::EMPTY; - for f in faces { - let b = hull_box(fs.get(*f)?)?; - bb.add(b.min); - bb.add(b.max); - } - (!bb.is_empty()).then(|| bb.inflated(gap)) -} - -/// `body` (with its history `h` over its operand) with its faces in the plane (n, d) split -/// where the faces of `tool` next to the tool's faces in the opposite plane cross them: the -/// outline of the tool's contact imprinted on the body's. Only the faces near the contact are -/// split, and each surface once. -fn imprinted(body: Body, mut h: Option, n: Vec3, d: f64, tool: &Body, tol: f64) -> Result<(Body, Option)> { - let contact = faces_in(tool, -n, -d, tol); - let gap = tol * 10.0; - // A face whose extent can't be found counts as near. - let region = faces_box(tool, &contact, gap); - let near = |b: &Body, faces: Vec| -> Vec { - let Some(region) = region else { return faces }; - let fs: Vec<&mt::Face> = b.solid.face_iter().collect(); - faces.into_iter().filter(|f| fs.get(*f).and_then(|x| hull_box(x)).is_none_or(|bx| !boxes_separate(bx, region, gap))).collect() - }; - let bounds = crate::history::edge_faces(&tool.solid); - let mut beside: Vec = bounds - .iter() - .filter(|fs| fs.len() == 2 && fs.iter().any(|f| contact.contains(f))) - .flat_map(|fs| fs.iter().copied()) - .filter(|f| !contact.contains(f)) - .collect(); - beside.sort_unstable(); - beside.dedup(); - let mut body = body; - // One split per surface: the halves of a round side lie on one cylinder, and splitting - // along it again re-traces the line already there, leaving a sliver (or not) depending - // on how the second trace falls. - let mut used: Vec> = Vec::new(); - for t in beside { - let surface = crate::face_surface(tool, t); - if used.iter().any(|u| same_surface(u, &surface, tol)) { - continue; - } - used.push(surface); - let faces = near(&body, faces_in(&body, n, d, tol)); - if faces.is_empty() { - break; - } - // Faces the tool's face does not cross stay as they are; none crossed is an error. - let Ok((split, _)) = crate::splitface::split_any(&body, &faces, &crate::SplitTool::Face { body: tool, face: t }) else { continue }; - h = crate::boolean_record::through(&split, 0, h.as_ref()); - body = split; - } - Ok((body, h)) -} - -/// Union of bodies touching back to back over part of a planar face (a pad half past the edge -/// of the face it stands on, two blocks meeting over some of their faces, #674, #679): each -/// body's contact faces are split along the outline of the other's, so the common area is the -/// same face in both, and those faces are glued away. `None` when that does not give a result -/// `accept`ed. -pub(crate) fn imprint_union(a: &Body, b: &Body, accept: &dyn Fn(&Body) -> bool) -> Option { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let back: Vec<(Vec3, f64)> = coincident_planes(a, b).into_iter().filter(|(_, _, same)| !*same).map(|(n, d, _)| (n, d)).collect(); - if back.is_empty() { - return None; - } - let run = || -> Result> { - let (mut a2, mut ha) = (a.clone(), crate::boolean_record::kept(a, 0, 1)); - let (mut b2, mut hb) = (b.clone(), crate::boolean_record::kept(b, 0, 1)); - for (n, d) in &back { - // a's faces face along n in the plane; b's face the other way. - (a2, ha) = imprinted(a2, ha, *n, *d, b, tol)?; - (b2, hb) = imprinted(b2, hb, -*n, -*d, a, tol)?; - } - // The common faces' boundaries with the same vertices on both sides. - for (n, d) in &back { - let corners = |body: &Body, n: Vec3, d: f64| -> Vec { - let fs: Vec<&mt::Face> = body.solid.face_iter().collect(); - let mut out: Vec = - faces_in(body, n, d, tol).iter().filter_map(|i| fs.get(*i)).flat_map(|f| f.vertex_iter().map(|v| from_p3(v.point()))).collect(); - out.dedup_by(|x, y| x.dist(*y) <= tol); - out - }; - let (pa, pb) = (corners(&a2, *n, *d), corners(&b2, -*n, -*d)); - let a3 = crate::splitface::split_edges_at(&a2, &pb)?; - ha = crate::boolean_record::through(&a3, 0, ha.as_ref()); - let b3 = crate::splitface::split_edges_at(&b2, &pa)?; - hb = crate::boolean_record::through(&b3, 0, hb.as_ref()); - (a2, b2) = (a3, b3); - } - let Some(r) = glue(&a2, &b2) else { return Ok(None) }; - let r = r?; - let (ha, hb) = (crate::boolean_record::placed(ha, 0, 2), crate::boolean_record::placed(hb, 1, 2)); - let h = crate::boolean_record::of_pair(&r, &ha, &hb); - Ok(Some(r.with_checked_history(h, &record::counts(&[a, b])))) - }; - match guard("imprint union", run) { - Ok(Some(r)) if accept(&r) => Some(r), - _ => None, - } -} - -/// Union of bodies that touch along identical planar faces, back to back (a body joined with -/// its mirror image, or the pieces of a body cut apart by a plane, which may meet in several -/// faces): every such pair of faces goes and the shells are stitched along their edges. `None` -/// when no such pair of faces exists. -pub(crate) fn glue(a: &Body, b: &Body) -> Option> { - glue_impl(a, b, false) -} - -/// Glue every certified start cap, retaining each tool's original contact tolerance. -pub(crate) fn glue_all_caps(a: &Body, b: &Body) -> Option> { - glue_impl(a, b, true) -} - -fn glue_impl(a: &Body, b: &Body, all_caps: bool) -> Option> { - use mt::{BoundedCurve, ParametricCurve}; - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let mid = |e: &mt::Edge| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - from_p3(c.subs((t0 + t1) * 0.5)) - }; - // Matching faces: same plane, opposite normals, the same edges. Every pair is glued: a - // pair left behind would stay inside the result as a zero-thickness slit (issue #616). - let (pa, pb) = (planes(a), planes(b)); - let mut tool_sizes = HashMap::new(); - if all_caps { - for shell in b.solid.boundaries() { - let mut bounds = solidcraft_geom::Aabb3::EMPTY; - for vertex in shell.vertex_iter() { - bounds.add(from_p3(vertex.point())); - } - let size = bounds.diagonal(); - if !size.is_finite() { - return None; - } - for face in shell.face_iter() { - tool_sizes.insert(face.id(), size); - } - } - } - let fa_list: Vec<&mt::Face> = a.solid.face_iter().collect(); - let fb_list: Vec<&mt::Face> = b.solid.face_iter().collect(); - // B edge → the matching A edge; B vertex → the matching A vertex. - let mut map: HashMap = HashMap::new(); - let mut vmap: HashMap = HashMap::new(); - let (mut glued_a, mut glued_b): (Vec, Vec) = (Vec::new(), Vec::new()); - if all_caps && pa.len().saturating_mul(pb.len()) > 2_000_000 { - return None; - } - for (ia, x) in &pa { - for (ib, y) in &pb { - if all_caps - && !matches!(b.face_sources().and_then(|sources| sources.get(*ib)), Some(Some(crate::FaceSource::ExtrudeCap { high: false, .. }))) - { - continue; - } - let tol = if all_caps { (a.size().max(*tool_sizes.get(&fb_list.get(*ib)?.id())?) * 1e-7).max(1e-9) * 10.0 } else { tol }; - let key = |p: Vec3| ((p.x / tol).round() as i64, (p.y / tol).round() as i64, (p.z / tol).round() as i64); - if glued_a.contains(ia) || glued_b.contains(ib) || x.n.dot(y.n) > -1.0 + 1e-9 || (x.d + y.d).abs() > tol { - continue; - } - let (Some(fa), Some(fb)) = (fa_list.get(*ia), fb_list.get(*ib)) else { continue }; - let ea: Vec = fa.edge_iter().collect(); - let eb: Vec = fb.edge_iter().collect(); - if ea.len() != eb.len() { - continue; - } - let (mut pair_map, mut pair_vmap) = (Vec::new(), Vec::new()); - let mut ok = true; - for e in &eb { - let ends = (key(from_p3(e.absolute_front().point())), key(from_p3(e.absolute_back().point()))); - let m = mid(e); - // The same curve: the same ends and e's middle on f (curves of one shape may be - // parametrised differently, so their parameter middles needn't coincide). - let on = |f: &mt::Edge| { - use mt::SearchNearestParameter; - let c = f.curve(); - let (t0, t1) = c.range_tuple(); - key(mid(f)) == key(m) - || c.search_nearest_parameter(p3(m), None, 100) - .is_some_and(|t| (t0.min(t1) - 1e-9..=t0.max(t1) + 1e-9).contains(&t) && from_p3(c.subs(t)).dist(m) <= tol) - }; - let hit = ea.iter().find(|f| { - let fe = (key(from_p3(f.absolute_front().point())), key(from_p3(f.absolute_back().point()))); - (fe == ends || fe == (ends.1, ends.0)) && on(f) - }); - let Some(f) = hit else { - ok = false; - break; - }; - let same = key(from_p3(f.absolute_front().point())) == ends.0; - pair_map.push((e.id(), if same { f.absolute_clone() } else { f.absolute_clone().inverse() })); - let (fa_v, fb_v) = if same { - (f.absolute_front().clone(), f.absolute_back().clone()) - } else { - (f.absolute_back().clone(), f.absolute_front().clone()) - }; - pair_vmap.push((e.absolute_front().id(), fa_v)); - pair_vmap.push((e.absolute_back().id(), fb_v)); - } - if !ok { - continue; - } - map.extend(pair_map); - vmap.extend(pair_vmap); - glued_a.push(*ia); - glued_b.push(*ib); - } - } - if all_caps - && b.face_sources()? - .iter() - .enumerate() - .any(|(index, source)| matches!(source, Some(crate::FaceSource::ExtrudeCap { high: false, .. })) && !glued_b.contains(&index)) - { - return None; - } - if glued_a.is_empty() { - return None; - } - Some(guard("glue", || { - let fail = |m: &str| KernelError::Failed(format!("joining touching faces: {m}")); - // B's other edges, rebuilt on A's vertices where they meet a seam. - let mut edges: HashMap = map.clone(); - for e in b.solid.edge_iter() { - if edges.contains_key(&e.id()) { - continue; - } - let (f0, f1) = (e.absolute_front(), e.absolute_back()); - if !vmap.contains_key(&f0.id()) && !vmap.contains_key(&f1.id()) { - edges.insert(e.id(), e.absolute_clone()); - continue; - } - let v0 = vmap.get(&f0.id()).cloned().unwrap_or_else(|| f0.clone()); - let v1 = vmap.get(&f1.id()).cloned().unwrap_or_else(|| f1.clone()); - edges.insert(e.id(), mt::Edge::new(&v0, &v1, e.curve())); - } - let mut faces: Vec = fa_list.iter().enumerate().filter(|(i, _)| !glued_a.contains(i)).map(|(_, f)| (*f).clone()).collect(); - // Every face but the glued ones is kept; an edge along a seam is an edge of both. - let kept = |operand: usize, n: usize, skip: &[usize]| { - (0..n).filter(|i| !skip.contains(i)).map(move |i| record::from_face(operand, i, Change::Kept)).collect::>() - }; - let from: Vec = kept(0, fa_list.len(), &glued_a).into_iter().chain(kept(1, fb_list.len(), &glued_b)).collect(); - let mut origins = record::edge_origins(&a.solid, 0); - for (old, o) in record::edge_origins(&b.solid, 1) { - if let Some(new) = edges.get(&old) { - origins.entry(new.id()).or_default().extend(o); - } - } - for (i, f) in fb_list.iter().enumerate() { - if glued_b.contains(&i) { - continue; - } - let wires: Vec = f - .absolute_boundaries() - .iter() - .map(|w| { - w.edge_iter() - .filter_map(|e| edges.get(&e.id()).map(|ne| if e.front() == e.absolute_front() { ne.clone() } else { ne.inverse() })) - .collect::>() - .into() - }) - .collect(); - let mut nf = mt::Face::try_new(wires, f.surface()).map_err(|e| fail(&e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - faces.push(nf); - } - // Bodies of several pieces stay in several pieces (each face's provenance follows it). - let prov: HashMap = faces.iter().map(|f| f.id()).zip(from).collect(); - let shell: mt::Shell = faces.into(); - let solid = Solid::try_new(crate::polybool::components_in_order(&shell)).map_err(|e| fail(&e.to_string()))?; - let from: Vec = solid.face_iter().filter_map(|f| prov.get(&f.id()).cloned()).collect(); - // Each edge's origins in the solid's edge order. - let origins = crate::body::edge_order(solid.face_iter()).0.iter().map(|e| origins.get(&e.id()).cloned()).collect(); - let keep: Vec<_> = a.split_keep().iter().chain(b.split_keep()).cloned().collect(); - crate::boolean_record::heal_build(solid, size, &keep, Some(from), origins, &record::counts(&[a, b])) - .map(|body| body.with_split_lines(Some(std::sync::Arc::new(keep)))) - })) -} - -/// Union of bodies touching back to back where a planar face of one lies wholly inside a -/// coincident face of the other, clear of its edges (a loft or revolve standing on a box top, -/// #396): the inner face goes, and the outer face takes its outline as a hole, sharing its -/// edges. `None` when no such pair of faces exists. The caller checks that the bodies don't -/// also overlap elsewhere. -pub(crate) fn inset(a: &Body, b: &Body) -> Option> { - inset_into(a, b, 0).or_else(|| inset_into(b, a, 1)) -} - -/// [`inset`] with a face of `inner` inside one of `outer`, `outer` being operand `outer_operand`. -fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option> { - use mt::{BoundedCurve, ParametricCurve}; - const SAMPLES: usize = 64; - const MAX_WORK: usize = 4_000_000; - let size = outer.size().max(inner.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - // Clear of the outer face's edges by more than the samples' chord error. - let clear = (size * 2e-3).max(1e-6); - let sample = |w: &mt::Wire| -> Option> { - if w.len() > 1000 { - return None; - } - let mut pts = Vec::with_capacity(w.len() * SAMPLES); - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - pts.extend((0..SAMPLES).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / SAMPLES as f64)))); - } - (!pts.is_empty() && pts.iter().all(|p| p.is_finite())).then(|| Ring::new(pts)) - }; - let fo: Vec<&mt::Face> = outer.solid.face_iter().collect(); - let fi: Vec<&mt::Face> = inner.solid.face_iter().collect(); - for (io, x) in &planes(outer) { - for (ii, y) in &planes(inner) { - if x.n.dot(y.n) > -1.0 + 1e-9 || (x.d + y.d).abs() > tol { - continue; - } - let (Some(face_o), Some(face_i)) = (fo.get(*io), fi.get(*ii)) else { continue }; - let outline = match face_i.boundaries().as_slice() { - [w] => w.clone(), - _ => continue, - }; - let (Some(inner_pts), Some(outer_loops)) = (sample(&outline), face_o.boundaries().iter().map(sample).collect::>>()) else { - continue; - }; - let outer_count: usize = outer_loops.iter().map(|l| l.len()).sum(); - if inner_pts.len().saturating_mul(outer_count) > MAX_WORK { - continue; - } - let u = x.n.any_perp(); - let w = x.n.cross(u); - let flat = |pts: &[Vec3]| { - solidcraft_geom::Loop2::polygon(&pts.iter().map(|p| solidcraft_geom::Vec2::new(p.dot(u), p.dot(w))).collect::>()) - }; - let flat_point = |p: Vec3| solidcraft_geom::Vec2::new(p.dot(u), p.dot(w)); - let outer_polys: Vec<_> = outer_loops.iter().map(|l| flat(l)).collect(); - let inner_poly = flat(&inner_pts); - let in_outer = |p: Vec3| outer_polys.iter().filter(|l| l.contains(flat_point(p))).count() % 2 == 1; - let near_outer = |p: Vec3| outer_loops.iter().any(|l| l.edges().any(|(s, t)| p.dist_to_segment(*s, *t) < clear)); - let fits = inner_pts.iter().all(|p| in_outer(*p) && !near_outer(*p)) - && outer_loops.iter().flatten().all(|p| !inner_poly.contains(flat_point(*p))); - if !fits { - continue; - } - return Some(guard("inset", || { - let fail = |m: &str| KernelError::Failed(format!("joining a face standing inside another: {m}")); - // The outline runs round the inner face's outward normal, the reverse of the - // outer face's: the way a hole in the outer face runs. - let mut wires = face_o.absolute_boundaries().clone(); - wires.push(if face_o.orientation() { outline.clone() } else { outline.inverse() }); - let mut holed = mt::Face::try_new(wires, face_o.surface()).map_err(|e| fail(&e.to_string()))?; - if !face_o.orientation() { - holed.invert(); - } - let inner_operand = 1 - outer_operand; - let mut faces = Vec::with_capacity(fo.len() + fi.len()); - let mut from = Vec::with_capacity(fo.len() + fi.len()); - for (i, f) in fo.iter().enumerate() { - let (face, change) = if i == *io { (holed.clone(), Change::Modified) } else { ((*f).clone(), Change::Kept) }; - faces.push(face); - from.push(record::from_face(outer_operand, i, change)); - } - for (i, f) in fi.iter().enumerate().filter(|(i, _)| i != ii) { - faces.push((*f).clone()); - from.push(record::from_face(inner_operand, i, Change::Kept)); - } - let solid = Solid::try_new(vec![faces.into()]).map_err(|e| fail(&e.to_string()))?; - let mut origins = record::edge_origins(&outer.solid, outer_operand); - origins.extend(record::edge_origins(&inner.solid, inner_operand)); - let origins = crate::body::edge_order(solid.face_iter()).0.iter().map(|e| origins.get(&e.id()).cloned()).collect(); - let counts = if outer_operand == 0 { record::counts(&[outer, inner]) } else { record::counts(&[inner, outer]) }; - crate::boolean_record::heal_build(solid, size, &[], Some(from), origins, &counts) - })); - } - } - None -} - -/// A cylindrical face: its index, a point on the axis, the unit axis and the radius. -#[derive(Clone, Copy, Debug)] -struct CylFace { - index: usize, - origin: Vec3, - axis: UnitVec3, - radius: f64, -} - -fn cylinders(b: &Body) -> Vec { - (0..b.face_count()) - .filter_map(|index| match crate::face_surface(b, index)? { - crate::FaceSurface::Cylinder { origin, axis, radius } => Some(CylFace { index, origin, axis, radius }), - _ => None, - }) - .collect() -} - -/// Do the two cylinders lie on the same surface? -fn same_cylinder(x: &CylFace, y: &CylFace, tol: f64) -> bool { - let off = y.origin - x.origin; - x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && (x.radius - y.radius).abs() < tol && (off - x.axis * off.dot(x.axis)).len() < tol -} - -/// The history over `[a, b]` of `r`, made in [`bore_union`]: `joined` (the target joined with -/// `narrowed`, the tool with its bore narrowed) less `cut`, the cylinder whose wall restores the -/// tool's bore faces `bore` (the tool is operand `tool_operand`). Nothing of the cylinder but its -/// wall may be left. Only a bore of one face: the cylinder's wall faces are split where its own -/// construction splits them, so which of several bore faces a piece of it lies over is not known. -fn recut(r: &Body, joined: &Body, narrowed: &Body, cut: &Body, bore: &[usize], tool_operand: usize) -> Option { - if bore.len() != 1 { - return None; - } - // Over [target, tool]. - let joined = crate::boolean_record::through(joined, 1, narrowed.history())?; - let wall = || record::region(bore.iter().map(|&face| FaceOrigin::Face { operand: 1, face }).collect(), false); - let faces = cut - .history()? - .faces - .iter() - .map(|f| match f.origins.first() { - Some(FaceOrigin::Profile { .. }) => wall(), - _ => record::generated(Vec::new()), - }) - .collect(); - let cut = record::from_faces(&cut.solid, 2, faces); - let h = crate::boolean_record::of_pair(r, &Some(joined), &Some(cut))?; - let map = if tool_operand == 1 { [Some(0), Some(1)] } else { [Some(1), Some(0)] }; - crate::boolean_record::composed(h.renumbered(&map, 2)) -} - -/// Do the bodies have cylindrical faces on a common cylinder? -pub(crate) fn has_coincident_cylinders(a: &Body, b: &Body) -> bool { - let tol = (a.size().max(b.size()) * 1e-7).max(1e-9) * 10.0; - let cb = cylinders(b); - cylinders(a).iter().any(|x| cb.iter().any(|y| same_cylinder(x, y, tol))) -} - -/// Union of bodies with bores on a common cylinder (a drain pad's bore around the drain hole -/// it is joined over). The mesh intersection can't take the coincident walls, so the tool's -/// bore is narrowed (its walls pushed toward the axis, now clear of the target's), the bodies -/// are joined, and the cylinder of the original bore is cut out again over the tool's length. -/// Recutting is valid only where that cylinder holds no material of either body. The -/// samples are plausibility checks; a whole-boundary guard rejects additional boundaries -/// crossing the recut. Original common-bore trims retain the legacy eligibility policy. -/// This is not a general emptiness or Boolean-equivalence certificate. Each direction -/// returns a result only when `accept` takes it; otherwise this returns `None`. The result's -/// history is over `[a, b]`. -/// -/// A boss standing in the other body's bore on that cylinder (a disc joined into the bottom of -/// a hole it fills) is grown instead ([`grown_boss_union`]). -pub(crate) fn bore_union(a: &Body, b: &Body, accept: &dyn Fn(&Body) -> bool) -> Option { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let mtol = size * 2e-3; - let (ma, mb) = (a.tessellate_with(mtol, true).ok()?, b.tessellate_with(mtol, true).ok()?); - let (ia, ib) = (ma.inside_index(), mb.inside_index()); - let empty = |p: Vec3| !ia.contains(p) && !ib.contains(p); - let (ca, cb) = (cylinders(a), cylinders(b)); - // (body to narrow, its operand number, its mesh and inside test, the other body and its - // inside test, their faces on the cylinder). - let ways = [(b, 1, &mb, &ib, a, &ia, &cb, &ca), (a, 0, &ma, &ia, b, &ib, &ca, &cb)]; - for (tool, tool_operand, mesh, inside, target, target_inside, ct, co) in ways { - for c in ct { - if !co.iter().any(|o| same_cylinder(c, o, tol)) { - continue; - } - let bore: Vec = ct.iter().filter(|x| same_cylinder(c, x, tol)).map(|x| x.index).collect(); - // The tool's extent along the axis on that cylinder, and whether it is a bore (the - // material outside it) at a point of the face. - let (mut t0, mut t1) = (f64::INFINITY, f64::NEG_INFINITY); - let mut probe = None; - for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) { - if !bore.contains(&(*fi as usize)) { - continue; - } - let Some(ps) = mesh.tri(t) else { continue }; - for p in ps { - let s = (p - c.origin).dot(c.axis); - t0 = t0.min(s); - t1 = t1.max(s); - } - if probe.is_none() { - probe = Some((ps[0] + ps[1] + ps[2]) / 3.0); - } - } - let Some(q) = probe else { continue }; - if !(t1 - t0 > tol && c.radius > tol) { - continue; - } - let along = c.origin + c.axis * (q - c.origin).dot(c.axis); - let Some(radial) = (q - along).normalized() else { continue }; - let on = along + radial * c.radius; - let e = (c.radius * 0.05).max(size * 1e-4); - if inside.contains(on - radial * e) && !inside.contains(on + radial * e) { - let boss = Boss { tool, operand: tool_operand, cylinder: c, faces: &bore, t0, t1 }; - if let Some(r) = grown_boss_union(a, b, &boss, target_inside, size, accept) { - return Some(r); - } - continue; - } - if !(inside.contains(on + radial * e) && !inside.contains(on - radial * e)) { - continue; - } - // The cylinder over the tool's length holds no material of either body. - let (u, w) = (c.axis.any_perp(), c.axis.cross(c.axis.any_perp())); - let at = |s: f64, r: f64, ang: f64| c.origin + c.axis * s + (u * ang.cos() + w * ang.sin()) * r; - let clear = (1..=9).all(|i| { - let s = t0 + (t1 - t0) * f64::from(i) / 10.0; - empty(at(s, 0.0, 0.0)) - && (0..8).all(|k| { - let ang = f64::from(k) * std::f64::consts::FRAC_PI_4 + 0.3; - empty(at(s, c.radius * 0.5, ang)) && empty(at(s, c.radius * 0.9, ang)) - }) - }); - if !clear { - continue; - } - // Past an end where the space is empty well beyond the radius too, the cut runs on a - // little (so its cap doesn't lie in a face's plane). Not where the other body's bore - // goes on: the cut's side would lie on its wall. - let ext = size * 0.01; - let past = |s: f64| { - empty(at(s, 0.0, 0.0)) - && (0..8).all(|k| { - let ang = f64::from(k) * std::f64::consts::FRAC_PI_4 + 0.3; - empty(at(s, c.radius * 0.9, ang)) && empty(at(s, c.radius * 1.1, ang)) && empty(at(s, c.radius * 1.5, ang)) - }) - }; - let lo = if past(t0 - ext * 0.5) && past(t0 - ext) { t0 - ext } else { t0 }; - let hi = if past(t1 + ext * 0.5) && past(t1 + ext) { t1 + ext } else { t1 }; - // The samples above are plausibility checks, not proof that an - // arbitrarily thin web is absent. Every additional current boundary - // must be wholly clear of the recut; unsupported trims refuse. - let other_bore: Vec = co.iter().filter(|x| same_cylinder(c, x, tol)).map(|x| x.index).collect(); - if crate::bore_guard::boundaries_clear(tool, &bore, c.origin, c.axis, c.radius, lo, hi, tol).is_none() - || crate::bore_guard::boundaries_clear(target, &other_bore, c.origin, c.axis, c.radius, lo, hi, tol).is_none() - { - continue; - } - let d = (c.radius * 0.2).min(size * 0.01); - let run = || -> Result> { - let narrowed = crate::offset::offset_body(tool, |i, _| if bore.contains(&i) { d } else { 0.0 })?; - if !narrowed.validity().is_empty() { - return Err(KernelError::Failed("narrowing a bore: an unsound result".into())); - } - let Some(joined) = crate::ops::boolean(target, &narrowed, BoolOp::Union)? else { return Ok(None) }; - let cut = crate::build::cylinder(at(lo, 0.0, 0.0), *c.axis, c.radius, hi - lo)?; - let Some(r) = crate::ops::boolean(&joined, &cut, BoolOp::Cut)? else { return Ok(None) }; - let h = recut(&r, &joined, &narrowed, &cut, &bore, tool_operand); - Ok(Some(r.with_checked_history(h, &record::counts(&[a, b])))) - }; - let (result, diagnostics) = crate::capture_boolean_diagnostics(run); - match result { - Ok(Some(r)) if accept(&r) => { - crate::boolean_diagnostics::merge(diagnostics); - let mut event = crate::BooleanFallback::new(crate::BooleanStrategy::CommonBore); - event.face_shift_mm = d; - crate::boolean_diagnostics::record(event); - return Some(r); - } - _ => continue, - } - } - } - None -} - -/// A tool (operand `operand`) with faces on a cylinder it shares with the other body, the -/// material inside them (a boss), and its extent `t0..t1` along the axis there. -struct Boss<'a> { - tool: &'a Body, - operand: usize, - cylinder: &'a CylFace, - faces: &'a [usize], - t0: f64, - t1: f64, -} - -/// Union of `a` and `b` where one has a boss on a cylinder that is a bore of the other body (a disc joined into the bottom of a hole it fills): the boss's walls -/// coincide with the bore's, which the mesh intersection can't take. Grown outward by a step, -/// the boss reaches into the material around the bore instead, and joining it adds nothing -/// more, provided that material is there all along the boss. The ring the step adds is sampled -/// against the other body for that, and `accept` checks the result as a whole. The result's -/// history is over `[a, b]` (the grown tool keeps the tool's faces and edges). -fn grown_boss_union( - a: &Body, - b: &Body, - boss: &Boss, - target_inside: &solidcraft_geom::InsideIndex, - size: f64, - accept: &dyn Fn(&Body) -> bool, -) -> Option { - let c = boss.cylinder; - let d = (c.radius * 0.2).min(size * 0.01); - let (u, w) = (c.axis.any_perp(), c.axis.cross(c.axis.any_perp())); - let at = |s: f64, r: f64, ang: f64| c.origin + c.axis * s + (u * ang.cos() + w * ang.sin()) * r; - // The other body's material all around the boss, as far out as it grows, over its length. - let backed = (1..=9).all(|i| { - let s = boss.t0 + (boss.t1 - boss.t0) * f64::from(i) / 10.0; - (0..16).all(|k| { - let ang = f64::from(k) * std::f64::consts::FRAC_PI_8 + 0.3; - [0.1, 0.5, 0.95].iter().all(|f| target_inside.contains(at(s, c.radius + d * f, ang))) - }) - }); - if !backed { - return None; - } - // Ends where the bore comes out of the other body and the boss's cap lies flush with the - // face it comes out of (a floor at the bottom of a through hole): faces in one plane, which - // the intersection can't take either. There the cap is moved out by the same step, and the - // stub that leaves past the face is deleted afterwards, the face healing over it. - let tol = (size * 1e-7).max(1e-9) * 10.0; - let target = if boss.operand == 1 { a } else { b }; - let along = |p: Vec3| (p - c.origin).dot(c.axis); - let radial = |p: Vec3| (p - c.origin - c.axis * along(p)).len(); - let plane_at = |body: &Body, i: usize, s: f64, out: f64| { - matches!(crate::face_surface(body, i), Some(crate::FaceSurface::Plane { normal, point }) - if normal.dot(c.axis) * out > 1.0 - 1e-9 && (along(point) - s).abs() < tol) - }; - let mut caps: Vec<(usize, f64, f64)> = Vec::new(); - for (s, out) in [(boss.t0, -1.0), (boss.t1, 1.0)] { - let open = (0..8).all(|k| { - let ang = f64::from(k) * std::f64::consts::FRAC_PI_4 + 0.3; - !target_inside.contains(at(s + out * d * 0.5, c.radius + d * 0.5, ang)) - }); - if !open || !(0..target.face_count()).any(|i| plane_at(target, i, s, out)) { - continue; - } - let cap = boss - .tool - .solid - .face_iter() - .enumerate() - .position(|(i, f)| plane_at(boss.tool, i, s, out) && f.vertex_iter().all(|v| radial(from_p3(v.point())) < c.radius + tol)); - // A flush end with no cap of its own to move: the faces would stay in one plane. - caps.push((cap?, s, out)); - } - let counts = record::counts(&[a, b]); - let run = || -> Result> { - let grown = crate::offset::offset_body(boss.tool, |i, _| if boss.faces.contains(&i) || caps.iter().any(|x| x.0 == i) { d } else { 0.0 })?; - if !grown.validity().is_empty() { - return Err(KernelError::Failed("growing a boss: an unsound result".into())); - } - // In the operands' order, so the history is over [a, b] once the grown tool's own is - // composed in. - let joined = if boss.operand == 1 { crate::ops::boolean(a, &grown, BoolOp::Union)? } else { crate::ops::boolean(&grown, b, BoolOp::Union)? }; - let Some(joined) = joined else { return Ok(None) }; - let joined = { - let h = crate::boolean_record::through(&joined, boss.operand, grown.history()); - joined.with_checked_history(h, &counts) - }; - if caps.is_empty() { - return Ok(Some(joined)); - } - // The stubs: faces wholly past a flush end, within the grown boss, reaching out to its cap. - let stubs: Vec = joined - .solid - .face_iter() - .enumerate() - .filter(|(_, f)| { - let ps: Vec = f.vertex_iter().map(|v| from_p3(v.point())).collect(); - caps.iter().any(|&(_, s, out)| { - let past = |p: &Vec3| (along(*p) - s) * out; - !ps.is_empty() && ps.iter().all(|p| past(p) > -tol && radial(*p) < c.radius + d * 1.01) && ps.iter().any(|p| past(p) > d * 0.5) - }) - }) - .map(|(i, _)| i) - .collect(); - if stubs.is_empty() { - return Err(KernelError::Failed("growing a boss: no stub past its flush end".into())); - } - let healed = crate::delete_faces(&joined, &stubs)?; - let h = crate::boolean_record::through(&healed, 0, joined.history()); - Ok(Some(healed.with_checked_history(h, &counts))) - }; - let (result, diagnostics) = crate::capture_boolean_diagnostics(run); - match result { - Ok(Some(r)) if accept(&r) => { - crate::boolean_diagnostics::merge(diagnostics); - let mut event = crate::BooleanFallback::new(crate::BooleanStrategy::GrownBoss); - event.face_shift_mm = d; - crate::boolean_diagnostics::record(event); - Some(r) - } - _ => None, - } -} - -#[cfg(test)] -#[path = "coplanar_tests.rs"] -mod tests; diff --git a/crates/kernel/src/coplanar_tests.rs b/crates/kernel/src/coplanar_tests.rs index 7700bb5ae..a1a21fedd 100644 --- a/crates/kernel/src/coplanar_tests.rs +++ b/crates/kernel/src/coplanar_tests.rs @@ -1,8 +1,8 @@ -//! Booleans of bodies with faces in a common plane: a face is pushed out of the plane only where -//! that leaves the result as it is. Every expected volume is what the two bodies define. +//! Booleans of bodies with faces in a common plane. Every expected volume is what the two bodies +//! define. #![allow(clippy::unwrap_used, clippy::panic)] use crate::*; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; /// An l x w x h block with two bottom edges chamfered by 1 mm: no prism along any axis, so /// its booleans are not done on sections. @@ -25,26 +25,19 @@ fn channel() -> Body { box_solid(Vec3::new(-20.0, 30.0, 10.0), Vec3::new(220.0, 70.0, 20.0)).unwrap() } -/// What the boolean of `a` and `b` adds to a's volume, the result's lumps, and how it was made. -fn change(a: &Body, b: &Body, op: BoolOp) -> (f64, usize, BooleanDiagnostics) { - let (r, how) = capture_boolean_diagnostics(|| boolean(a, b, op)); - let r = r.unwrap().unwrap(); - (measure(&r).unwrap().volume - measure(a).unwrap().volume, r.lumps().unwrap().len(), how) -} - -fn used(how: &BooleanDiagnostics, strategy: BooleanStrategy) -> bool { - how.events.iter().any(|e| e.strategy == strategy) +/// What the boolean of `a` and `b` adds to a's volume, and the result's lumps. +fn change(a: &Body, b: &Body, op: BoolOp) -> (f64, usize) { + let r = boolean(a, b, op).unwrap().unwrap(); + (measure(&r).unwrap().volume - measure(a).unwrap().volume, r.lumps().unwrap().len()) } /// A channel cut along a block, up to the face a rib stands on. The channel's top lies in -/// that face's plane and the rib bridges it: pushed up out of the plane (2.29 % of the -/// body's size, 5.6 mm), the top would cut a notch 20 x 40 into the rib. +/// that face's plane and the rib bridges it. #[test] fn a_cut_up_to_a_face_leaves_what_stands_on_the_face() { - let (added, lumps, how) = change(&ribbed(), &channel(), BoolOp::Cut); + let (added, lumps) = change(&ribbed(), &channel(), BoolOp::Cut); // It takes 200 x 40 x 10 of the block and nothing of the rib. - assert!((added + 80_000.0).abs() < 1e-6 && lumps == 1, "{added}, {lumps} lumps, {how:?}"); - assert!(!used(&how, BooleanStrategy::CoplanarSeparation), "{how:?}"); + assert!((added + 80_000.0).abs() < 1e-6 && lumps == 1, "{added}, {lumps} lumps"); } /// The same with a round hole through the block beside the channel (r 4 at 30, 15: y 11 to @@ -54,26 +47,23 @@ fn a_cut_up_to_a_face_leaves_what_stands_on_the_face() { fn a_round_hole_beside_the_cut_changes_nothing() { let hole = cylinder(Vec3::new(30.0, 15.0, -1.0), Vec3::Z, 4.0, 22.0).unwrap(); let drilled = boolean(&ribbed(), &hole, BoolOp::Cut).unwrap().unwrap(); - let (added, lumps, how) = change(&drilled, &channel(), BoolOp::Cut); + let (added, lumps) = change(&drilled, &channel(), BoolOp::Cut); // 200 x 40 x 10 again (the hole is measured on its mesh, before and after). - assert!((added + 80_000.0).abs() < 1e-3 && lumps == 1, "{added}, {lumps} lumps, {how:?}"); - assert!(!used(&how, BooleanStrategy::CoplanarSeparation), "{how:?}"); + assert!((added + 80_000.0).abs() < 1e-3 && lumps == 1, "{added}, {lumps} lumps"); } -/// With nothing in their way the faces are pushed as before: a pocket's top out of the plane -/// of the block's top face, a pad's foot into the block. (This holds without the check too: -/// it keeps the check from refusing what is harmless.) +/// A pocket whose top lies in the plane of the block's top face, and a pad whose foot does. #[test] -fn faces_with_room_are_pushed_apart() { +fn faces_in_a_common_plane_cut_and_join() { let block = block(200.0, 100.0, 20.0); // A pocket 50 x 60 x 5 from the top face: 15 000 less. let pocket = box_solid(Vec3::new(75.0, 20.0, 15.0), Vec3::new(125.0, 80.0, 20.0)).unwrap(); - let (added, _, how) = change(&block, &pocket, BoolOp::Cut); - assert!((added + 15_000.0).abs() < 1e-6 && used(&how, BooleanStrategy::CoplanarSeparation), "{added}, {how:?}"); + let (added, _) = change(&block, &pocket, BoolOp::Cut); + assert!((added + 15_000.0).abs() < 1e-6, "{added}"); // A pad 50 x 60 x 10 on the top face: 30 000 more. let pad = box_solid(Vec3::new(75.0, 20.0, 20.0), Vec3::new(125.0, 80.0, 30.0)).unwrap(); - let (added, lumps, how) = change(&block, &pad, BoolOp::Union); - assert!((added - 30_000.0).abs() < 1e-6 && lumps == 1 && used(&how, BooleanStrategy::CoplanarSeparation), "{added}, {how:?}"); + let (added, lumps) = change(&block, &pad, BoolOp::Union); + assert!((added - 30_000.0).abs() < 1e-6 && lumps == 1, "{added}"); } /// A disc joined into a round hole it fills (issue: "boolean Union: no result" for a 1 mm @@ -87,13 +77,10 @@ fn a_disc_joined_into_the_hole_it_fills() { for (z0, z1) in [(0.0, 1.0), (5.0, 8.0), (19.0, 20.0)] { let disc = cylinder(Vec3::new(150.0, 50.0, z0), Vec3::Z, 20.0, z1 - z0).unwrap(); let want = measure(&disc).unwrap().volume; - let (r, how) = capture_boolean_diagnostics(|| boolean(&drilled, &disc, BoolOp::Union)); - let r = r.unwrap().unwrap(); + let r = boolean(&drilled, &disc, BoolOp::Union).unwrap().unwrap(); let added = measure(&r).unwrap().volume - measure(&drilled).unwrap().volume; - assert!((added - want).abs() < want * 1e-3, "{z0}..{z1}: {added} vs {want}, {how:?}"); + assert!((added - want).abs() < want * 1e-3, "{z0}..{z1}: {added} vs {want}"); assert!(r.lumps().unwrap().len() == 1 && r.validity().is_empty(), "{z0}..{z1}: {:?}", r.validity()); - // Exact: nothing of the tool is moved. - assert!(used(&how, BooleanStrategy::GrownBoss) && !used(&how, BooleanStrategy::ToolNudge), "{z0}..{z1}: {how:?}"); } } @@ -105,9 +92,8 @@ fn hemisphere(r: f64) -> Body { } /// A hemisphere (r 20) and a block (x 5 to 35, y -30 to 30, z 0 to 25) that both stand on z = 0, the block's foot over most of the -/// hemisphere's flat face. The neighbour of that face is the sphere, which cannot be stretched, so its face is grown instead (a -/// strip along its rim) and what the join leaves below the plane is cut off by editing faces. The block takes the part of the dome -/// beyond x = 5, half of a cap 15 high: the union is the dome and the block less that part. +/// hemisphere's flat face. The block takes the part of the dome beyond x = 5, half of a cap 15 high: the union is the dome and the +/// block less that part. #[test] fn a_block_flush_with_the_flat_face_of_a_hemisphere_joins_exactly() { let (r, x0) = (20.0, 5.0); @@ -116,41 +102,14 @@ fn a_block_flush_with_the_flat_face_of_a_hemisphere_joins_exactly() { let h = r - x0; let expected = 2.0 / 3.0 * std::f64::consts::PI * r.powi(3) - std::f64::consts::PI * h * h * (3.0 * r - h) / 6.0 + 30.0 * 60.0 * 25.0; for (a, b) in [(&dome, &block), (&block, &dome)] { - let joined = crate::coplanar::boolean_grown(a, b, BoolOp::Union).expect("the route applies").unwrap().unwrap(); + let joined = boolean(a, b, BoolOp::Union).unwrap().unwrap(); let v = measure(&joined).unwrap().volume; assert!((v - expected).abs() < expected * 1e-4, "{v} against {expected}"); assert_eq!(joined.lumps().unwrap().len(), 1); assert!(joined.validity().is_empty(), "{:?}", joined.validity()); // The flat faces are one plane again: nothing of the join stays below z = 0. - let mesh = joined.tessellate(0.05).unwrap(); + let mesh = joined.mesh(&crate::MeshTolerance::chord(0.05)).unwrap(); let lowest = mesh.positions.iter().map(|p| p.z).fold(f64::MAX, f64::min); assert!(lowest > -1e-6, "the join reaches down to z = {lowest}"); } } - -/// Growing the flat face of a dome past its plane and cutting what that adds off again gives the dome back: the same volume, the same -/// faces, nothing below the plane. -#[test] -fn what_growing_a_face_adds_is_cut_off_again_exactly() { - let dome = hemisphere(20.0); - let measured = measure(&dome).unwrap().volume; - let grown = crate::coplanar::grow_faces_exact(&dome, -Vec3::Z, 0.0, 3.0).unwrap(); - assert!(measure(&grown).unwrap().volume > measured + 3.0 * 300.0, "the stub adds volume"); - let back = crate::coplanar::trim_exact(&grown, -Vec3::Z, 0.0).unwrap(); - let v = measure(&back).unwrap().volume; - assert!((v - measured).abs() < measured * 1e-6, "{v} against {measured}"); - assert_eq!(back.face_count(), dome.face_count()); - assert!(back.validity().is_empty(), "{:?}", back.validity()); - let lowest = back.tessellate(0.05).unwrap().positions.iter().map(|p| p.z).fold(f64::MAX, f64::min); - assert!(lowest > -1e-6, "the body reaches down to z = {lowest}"); -} - -/// A plane the body stands on has nothing beyond it, and one clear of the body is refused (nothing is cut off). -#[test] -fn trimming_at_a_plane_with_nothing_beyond_it() { - let dome = hemisphere(20.0); - let measured = measure(&dome).unwrap().volume; - let same = crate::coplanar::trim_exact(&dome, -Vec3::Z, 0.0).unwrap(); - assert!((measure(&same).unwrap().volume - measured).abs() < measured * 1e-9); - assert!(crate::coplanar::trim_exact(&dome, -Vec3::Z, 5.0).is_err()); -} diff --git a/crates/kernel/src/corner_g2.rs b/crates/kernel/src/corner_g2.rs index 22e236df6..63cd23a99 100644 --- a/crates/kernel/src/corner_g2.rs +++ b/crates/kernel/src/corner_g2.rs @@ -1,501 +1,51 @@ -//! G2 corner patches: the patch that fills a vertex where filleted edges meet, built to repeat each -//! blend's surface up to the second order instead of the rolling ball's sphere. +//! G2 fillet corners (`corner: G2`): the corner where three or more rounded edges meet, filled +//! with a patch that meets every face around it to the second order, instead of the rolling +//! ball's sphere (or SMLib's Coons patch), which is only tangent to the rounds and keeps its own +//! 1 / r across each seam. //! -//! [`crate::blend_corner`] and [`crate::curvecorner`] fill the corner of a vertex with a piece of -//! the ball that rolls along the three edges (a sphere for equal radii, a rational patch for -//! unequal ones). That patch is tangent to every blend along the sections where they stop, so the -//! corner is G1 — but across a seam the ball keeps its own 1/r where a fillet is flat along its -//! axis, so the two surfaces meet with a jump in curvature. +//! The corner is set back: SMLib runs each round whole to its cross-section a setback from the +//! vertex and leaves the corner open ([`crate::blend_smlib::fillet_setback_open`]), so the hole's +//! boundary is the rounds' sections and, on each face between two rounds, SMLib's curve from one +//! round's contact line to the next. Each hole is filled with one face +//! ([`crate::fill::matched_patch`]): a bicubic height field over the hole's plane fitted to every +//! face beside the hole — its position, its tangent plane and its normal curvature across the +//! boundary, read off the face's own surface — the rounds and the planes alike, so the patch is +//! G2 to all of them. The faces are sewn into one solid by SMLib ([`crate::stitch`]). //! -//! Here the corner is one tensor patch whose boundary is the blends' section curves themselves and -//! whose cross-sections carry each blend's own derivatives: the position, the direction the patch -//! leaves the blend's surface in, and the blend's curvature vector along that direction are the -//! first three control points of every cross-section, one control point per continuity condition, -//! exactly as [`crate::bridge`]'s sections do. The other end of every cross-section gathers at -//! `apex` — a point inside the material the corner caps — where the sections arrive in a common -//! tangent plane with a common curvature, so the patch closes there smoothly like a sphere's pole. -//! Along a seam the patch therefore repeats the blend up to the second order (G2). -//! -//! The boundary is a closed loop (the three sections joined corner to corner), so the direction -//! along it is a *closed* cubic B-spline: an interpolating curve with free ends swings wide at the -//! corner where the loop joins and folds the patch there. Where two blends meet at that corner -//! their sections leave in directions 90° apart and ask for different curvature at that one point -//! (a fillet is flat across its own seam, the other is not), which no single surface can hold; the -//! corner is a still point of the construction and [`seam_error`] is measured clear of it. A patch -//! that folds, or a corner with no room, is refused rather than replaced by the G1 ball. +//! Without a setback the boundary would be the three sections alone, meeting at points where +//! two rounds 90° apart ask for different curvatures; with it, the only points where two faces +//! disagree are the hole's corners, where a section ends on a plane: the round's G1 seam with the +//! plane, whose 1 / r jump every round has along its whole length, ends there, and no surface is +//! G2 to both the round and the plane at that point. The patch passes from one to the other +//! within 15% of each side from the corner (`solidcraft_geom::fill_matched::FADE_SHARE`) and +//! is G2 along the rest of every seam. -use solidcraft_geom::Vec3; -use solidcraft_geom::bspline::{HPoint, NurbsSurface}; -use truck_modeling::{self as mt, builder}; +use solidcraft_geom::fill_matched::MatchedFill; -use crate::blend::unsupported; -use crate::body::{from_p3, p3}; -use crate::bridge::Frame; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::{KernelError, Result}; -/// A corner's name in an error. -fn fail(m: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("G2 corner: {m}")) -} +/// A corner's default setback: this times its round's radius along each edge. It must reach +/// past where the rounds meet without one (the radius, at a square corner), and SMLib's own +/// patch bulges past the faces beyond about twice the radius; one and a half leaves the patch a +/// side as long as the round's section is wide, with room either way. +pub const DEFAULT_SETBACK_FACTOR: f64 = 1.5; -/// One of the surface's own derivative vectors as ours. -fn vec_of(v: mt::Vector3) -> Vec3 { - Vec3::new(v.x, v.y, v.z) -} +/// How far the patch's normal curvature across a seam may be from the face's, clear of the hole's +/// corners: this share of the corner's round's curvature 1 / r, the jump a rolling ball makes. +pub const CURVATURE_SHARE: f64 = 5e-3; -/// Conditions each end of a cross-section carries: position, tangent and curvature. -const END_CONDITIONS: usize = 3; -/// Degree across the patch: three conditions at each end, less the control point they share. -const ACROSS: usize = 2 * END_CONDITIONS - 1; -/// Degree along the seam loop. -const ALONG: usize = 3; -/// Fewest stations a section curve may be sampled at (a cubic through them). -const MIN_STATIONS: usize = 4; -/// Most stations one section curve may carry. -const MAX_STATIONS: usize = 512; -/// How much of a station's `leave` has to lie across its seam for the patch to have a direction to -/// leave the blend in at all. -const ACROSS_ENOUGH: f64 = 0.2; - -/// The G2 corner patch over three blends' section curves: `sides[i]` is one blend's section curve, -/// sampled in order from one corner of the vertex to the next, each side's last station the next -/// side's first (the three close a loop). `apex` is a point inside the material the corner caps; -/// the patch gathers there. The face's boundary edges are the section curves themselves (one edge -/// per side, cut out of the patch's own boundary curve, so they lie on it exactly); the caller -/// re-wraps the wire where it needs its own orientation. -pub fn corner_g2_patch(sides: &[Vec], apex: Vec3) -> Result> { - guard("G2 corner patch", || build(sides, apex)) -} - -/// The seam's own direction at station `i` of a side, from a four-point central difference through -/// the stations (`crate::bridge::frames` samples a chain evenly, and a corner's own callers do the -/// same): a two-point chord would only be second order in the step and would tilt the corner's -/// tangent plane by more than G2 is judged at. `None` within two stations of a side's end. -fn seam_tangent(side: &[Frame], i: usize) -> Option { - let at = |j: isize| usize::try_from(j).ok().and_then(|j| side.get(j)).map(|f| f.p); - let (a, b, c, d) = (at(i as isize - 2)?, at(i as isize - 1)?, at(i as isize + 1)?, at(i as isize + 2)?); - (b * 8.0 - a - c * 8.0 + d).normalized() -} - -/// The seam's direction at every station of the closed loop (the same difference, wrapping round -/// its ends), falling back to the chord to a neighbour where the four points are not there. -fn loop_tangents(frames: &[Frame]) -> Vec> { - let m = frames.len(); - if m == 0 { - return Vec::new(); +/// The patch filling one open corner of `sheet` (a sheet from +/// [`crate::blend_smlib::fillet_setback_open`]): `hole` its edges in order, each with whether the +/// face beside it runs it forwards; `radius` the corner's round's radius, which sets the +/// curvature tolerance. The patch is a one-face sheet on the sheet's own edges. +pub(crate) fn corner_patch(sheet: &Body, hole: &[(usize, bool)], radius: f64) -> Result<(Body, MatchedFill)> { + if !(radius.is_finite() && radius > 0.0) { + return Err(KernelError::Invalid("a G2 corner's radius must be finite and positive".into())); } - let at = |j: isize| frames.get(j.rem_euclid(m as isize) as usize).map(|f| f.p); - (0..m) - .map(|i| { - let four = || { - let (a, b, c, d) = (at(i as isize - 2)?, at(i as isize - 1)?, at(i as isize + 1)?, at(i as isize + 2)?); - (b * 8.0 - a - c * 8.0 + d).normalized() - }; - four().or_else(|| { - let prev = at(i as isize - 1)?; - let next = at(i as isize + 1)?; - (next - prev).normalized() - }) - }) - .collect() -} - -/// The three section curves as one closed loop of stations, the loop index each side starts at, -/// and the corner's own size (twice the mean distance of a station from their centre). -fn corner_loop(sides: &[Vec]) -> Result<(Vec, Vec, f64)> { - if sides.len() != 3 { - return Err(unsupported("a G2 corner needs three blends meeting at one vertex (a corner of two, or one, still ends on the ball's patch)")); - } - let mut frames: Vec = Vec::new(); - let mut starts: Vec = Vec::new(); - for side in sides { - if side.len() < MIN_STATIONS || side.len() > MAX_STATIONS { - return Err(KernelError::Invalid(format!("a corner section curve needs {MIN_STATIONS} to {MAX_STATIONS} sampled stations"))); - } - for f in side { - if ![f.p, f.leave, f.bend, f.bend_change].into_iter().all(Vec3::is_finite) || !(f.leave.len() > 0.5) { - return Err(KernelError::Invalid("a corner station must carry finite data and a unit direction".into())); - } - } - starts.push(frames.len()); - // A side runs from one corner to the next; its last station is the next side's first, so the - // loop takes it once. - frames.extend(side.iter().take(side.len() - 1).copied()); - } - let centre = frames.iter().fold(Vec3::ZERO, |a, f| a + f.p) * (1.0 / frames.len().max(1) as f64); - let size = frames.iter().map(|f| f.p.dist(centre)).fold(0.0, f64::max) * 2.0; - if !(size > 0.0 && size.is_finite()) { - return Err(unsupported("a corner whose section curves have no extent")); - } - for (i, side) in sides.iter().enumerate() { - let Some(prev) = sides.get((i + sides.len() - 1) % sides.len()).and_then(|s| s.last()) else { continue }; - let Some(&here) = side.first() else { continue }; - if prev.p.dist(here.p) > size * 1e-3 { - return Err(unsupported("the section curves do not meet at a corner")); - } - } - Ok((frames, starts, size)) -} - -/// Every station's `leave` squared up with the seam it belongs to: the part of it across the seam, -/// which is the direction the cross-section has to leave the blend in. A `leave` along the seam -/// itself leaves the cross-section no room, and is refused. -fn transverse(frames: &[Frame], tangents: &[Option]) -> Result> { - let mut out = Vec::with_capacity(frames.len()); - for (f, t) in frames.iter().zip(tangents) { - let across = match t { - Some(t) => f.leave - *t * f.leave.dot(*t), - // Stations that offer no direction along the seam: the leave stands as it came. - None => f.leave, - }; - if across.len() < ACROSS_ENOUGH * f.leave.len() { - return Err(unsupported("a section curve meets the corner patch along its own tangent, so the patch has no direction to leave it in")); - } - let leave = across.normalized().ok_or_else(|| unsupported("a corner station has no direction across its seam"))?; - out.push(Frame { leave, ..*f }); - } - Ok(out) -} - -/// One station's cross-section: `ACROSS + 1` control points of a Bézier from the seam point to -/// `apex`. The first three hold the blend: its position, the direction the patch leaves it in -/// (one control point along `leave`) and its curvature vector across the seam (one more). The last -/// three hold the apex: the point, a tangent in the apex's own plane, and the curvature of a dome -/// over the corner, so the sections arrive smoothly instead of leaving a point. -fn section(f: &Frame, apex: Vec3, n_apex: Vec3, kappa: f64) -> Result<[Vec3; ACROSS + 1]> { - let k = ACROSS as f64; - let chord = f.p.dist(apex); - if !(chord.is_finite() && chord > 0.0) { - return Err(unsupported("a blend too small for the corner patch to fit")); - } - let speed = chord / 3.0; - let to_apex = (f.p - apex).normalized().ok_or_else(|| unsupported("a section curve starts on the apex"))?; - let leave_apex = - (to_apex - n_apex * to_apex.dot(n_apex)).normalized().ok_or_else(|| unsupported("a section curve reaches the apex along the apex normal"))?; - let mut c = [Vec3::ZERO; ACROSS + 1]; - c[0] = f.p; - c[1] = f.p + f.leave * (speed / k); - c[2] = f.bend * (speed * speed / (k * (k - 1.0))) + c[1] * 2.0 - c[0]; - c[ACROSS] = apex; - c[ACROSS - 1] = apex + leave_apex * (speed / k); - c[ACROSS - 2] = (-n_apex * kappa) * (speed * speed / (k * (k - 1.0))) + c[ACROSS - 1] * 2.0 - c[ACROSS]; - if c.iter().any(|p| !p.is_finite()) { - return Err(fail("a cross-section of the corner is not finite")); - } - Ok(c) -} - -/// A closed uniform cubic B-spline through `points`, once round the loop: the curve at each station -/// is `(q[i-1] + 4 q[i] + q[i+1]) / 6`, so the stations fix the net by a cyclic tridiagonal system, -/// solved here with the Sherman–Morrison form of the Thomas algorithm (a corner's loop runs to -/// hundreds of stations). The net comes back in the open form the tensor surface wants — the first -/// three control points repeated past the end — so it still closes, with one uniform span per -/// station and no free end anywhere. -fn closed_layer(points: &[Vec3]) -> Result> { - let m = points.len(); - if m < 2 * ALONG + 2 { - return Err(fail("a corner loop needs at least eight stations")); - } - // Sub-diagonal 1, diagonal 4, super-diagonal 1, and 1 in both corners. - let (sub, diag, sup, corner) = (1.0f64, 4.0f64, 1.0f64, 1.0f64); - let gamma = -diag; - let mut bb = vec![diag; m]; - if let Some(first) = bb.first_mut() { - *first = diag - gamma; - } - if let Some(last) = bb.last_mut() { - *last = diag - corner * corner / gamma; - } - // Thomas, one right-hand side at a time (three components solved together). - let thomas = |rhs: &[Vec3]| -> Result> { - let mut c = vec![0.0f64; m]; - let mut d = rhs.to_vec(); - let mut denom = bb.first().copied().unwrap_or(0.0); - if !(denom.abs() > 1e-300) { - return Err(fail("the corner's stations are degenerate")); - } - let (Some(c0), Some(d0)) = (c.first_mut(), d.first_mut()) else { return Err(fail("stations")) }; - *c0 = sup / denom; - *d0 = *d0 * (1.0 / denom); - for i in 1..m { - let (prev_c, prev_d) = (c.get(i - 1).copied().unwrap_or(0.0), d.get(i - 1).copied().unwrap_or(Vec3::ZERO)); - let b = bb.get(i).copied().unwrap_or(diag); - denom = b - sub * prev_c; - if !(denom.abs() > 1e-300) { - return Err(fail("the corner's stations are degenerate")); - } - if let Some(slot) = c.get_mut(i) { - *slot = if i + 1 < m { sup / denom } else { 0.0 }; - } - if let Some(slot) = d.get_mut(i) { - *slot = (*slot - prev_d * sub) * (1.0 / denom); - } - } - let mut x = vec![Vec3::ZERO; m]; - let last = d.last().copied().unwrap_or(Vec3::ZERO); - if let Some(slot) = x.last_mut() { - *slot = last; - } - for i in (0..m - 1).rev() { - let (Some(ci), Some(xn)) = (c.get(i).copied(), x.get(i + 1).copied()) else { continue }; - let di = d.get(i).copied().unwrap_or(Vec3::ZERO); - if let Some(slot) = x.get_mut(i) { - *slot = di - xn * ci; - } - } - Ok(x) - }; - let rhs: Vec = points.iter().map(|p| *p * 6.0).collect(); - let x = thomas(&rhs)?; - // The unit right-hand side the corner terms add: gamma at the first station, the corner at the - // last. - let mut unit = vec![Vec3::ZERO; m]; - if let Some(slot) = unit.first_mut() { - *slot = Vec3::new(gamma, gamma, gamma); - } - if let Some(slot) = unit.last_mut() { - *slot = Vec3::new(corner, corner, corner); - } - let z = thomas(&unit)?; - let (x0, xn) = (x.first().copied().unwrap_or(Vec3::ZERO), x.last().copied().unwrap_or(Vec3::ZERO)); - let (z0, zn) = (z.first().copied().unwrap_or(Vec3::ZERO), z.last().copied().unwrap_or(Vec3::ZERO)); - // z answers a scalar right-hand side, so the correction is one scalar factor per component. - let factor = |x0: f64, xn: f64, z0: f64, zn: f64| (x0 + corner * xn / gamma) / (1.0 + z0 + corner * zn / gamma); - let f = Vec3::new(factor(x0.x, xn.x, z0.x, zn.x), factor(x0.y, xn.y, z0.y, zn.y), factor(x0.z, xn.z, z0.z, zn.z)); - let mut out = Vec::with_capacity(m + ALONG); - for i in 0..m { - let (xi, zi) = (x.get(i).copied().unwrap_or(Vec3::ZERO), z.get(i).copied().unwrap_or(Vec3::ZERO)); - out.push(xi - Vec3::new(f.x * zi.x, f.y * zi.y, f.z * zi.z)); - } - if !out.iter().all(|p| p.is_finite()) { - return Err(fail("the corner's boundary is not finite")); - } - for i in 0..ALONG { - let p = out.get(i).copied().unwrap_or(Vec3::ZERO); - out.push(p); - } - Ok(out) -} - -/// The stations of the loop as one tensor control net: across (v) each station's cross-section is -/// the Bézier above, along the seam loop (u) each of its control points is a closed cubic through -/// the stations, so the face passes through every section exactly and its parameter line along the -/// loop closes without an end to swing from. The loop's station count comes back with it: station -/// `i` sits at parameter `i + ALONG`, and the loop closes at `count + ALONG`. -fn tensor(layers: &[[Vec3; ACROSS + 1]]) -> Result<(NurbsSurface, f64)> { - let m = layers.len(); - let nu = m + ALONG; - let knots_u: Vec = (0..=(nu + ALONG) as i64).map(|i| i as f64).collect(); - let mut ctrl: Vec = Vec::with_capacity(nu * (ACROSS + 1)); - for j in 0..=ACROSS { - let points: Vec = layers.iter().map(|c| c.get(j).copied().unwrap_or(Vec3::ZERO)).collect(); - let net = closed_layer(&points)?; - for p in &net { - ctrl.push(HPoint::weighted(*p, 1.0)); - } - } - let mut knots_v = vec![0.0; ACROSS + 1]; - knots_v.extend(std::iter::repeat_n(1.0, ACROSS + 1)); - let s = NurbsSurface::from_homogeneous([ALONG, ACROSS], [knots_u, knots_v], ctrl).map_err(|e| fail(format!("the corner patch: {e}")))?; - Ok((s, m as f64)) -} - -/// The surface across its own domain: the patch must keep facing one way, or a blend would be met -/// by a piece of the patch folded back on itself. -fn no_fold(surface: &mt::Surface, loop_range: (f64, f64)) -> Result<()> { - use mt::ParametricSurface; - // The u knots run past the loop at both ends (a closed curve has no clamped ends to name), so - // the loop's own range is brought in rather than read off the knot vector. - let (u0, u1) = loop_range; - let Some((v0, v1)) = surface.try_range_tuple().1 else { - return Err(fail("the corner patch has no parameter domain")); - }; - let normal = |u: f64, v: f64| -> Option { vec_of(surface.uder(u, v)).cross(vec_of(surface.vder(u, v))).normalized() }; - let mid = normal((u0 + u1) * 0.5, v0 + (v1 - v0) * 0.5).ok_or_else(|| unsupported("the corner patch has no normal at its middle"))?; - // Clear of the apex (v1), where the patch's parameter line along the seam collapses to a point - // and the normal is read from the sections approaching it. - for i in 0..=8 { - for j in 0..9 { - let u = u0 + (u1 - u0) * i as f64 / 8.0; - let v = v0 + (v1 - v0) * j as f64 / 9.0; - let n = normal(u, v).ok_or_else(|| unsupported("the corner patch folds back on itself"))?; - if n.dot(mid) <= 0.0 { - return Err(unsupported("the corner patch folds back on itself with these section curves")); - } - } - } - Ok(()) -} - -/// Build the patch: sections, tensor surface, and the wire of the section curves themselves. -fn build(sides: &[Vec], apex: Vec3) -> Result> { - if !apex.is_finite() { - return Err(KernelError::Invalid("the corner apex must be a finite point".into())); - } - let (frames, starts, size) = corner_loop(sides)?; - let frames = transverse(&frames, &loop_tangents(&frames))?; - // The apex's own plane: the mean direction from the apex to the boundary it caps. - let n_apex = frames - .iter() - .fold(Vec3::ZERO, |a, f| a + (f.p - apex)) - .normalized() - .ok_or_else(|| unsupported("the corner's apex sits on its own boundary curves"))?; - // How hard the patch bends into the apex: as much as its blends do across their seams, and - // never flatter than a dome of the corner's own size (a flat cap would end in a point). - let mean_bend = frames.iter().map(|f| f.bend.len()).sum::() / frames.len().max(1) as f64; - let reach = (frames.iter().map(|f| f.p.dist(apex)).sum::() / frames.len().max(1) as f64).max(size * 1e-3); - let kappa = mean_bend.max(1.0 / (2.0 * reach)); - if !(kappa.is_finite() && kappa > 0.0) { - return Err(unsupported("a corner the patch cannot span")); - } - let layers: Vec<[Vec3; ACROSS + 1]> = frames.iter().map(|f| section(f, apex, n_apex, kappa)).collect::>()?; - let (nurbs, m) = tensor(&layers)?; - let surface = crate::spline_conv::surface(&nurbs)?; - no_fold(&surface, (ALONG as f64, m + ALONG as f64))?; - // The boundary is the loop of section curves; each side is cut out of the patch's own boundary - // curve so that it lies on the patch exactly. - let nu = nurbs.count().first().copied().unwrap_or(0); - let row: Vec = (0..nu).map(|i| nurbs.point(i, 0)).collect(); - let Some(knots_u) = nurbs.knots().first().cloned() else { return Err(fail("knots")) }; - let loop_curve = crate::spline_conv::nurbs_curve(mt::KnotVec::from(knots_u), &row)?; - let mut cuts: Vec = starts.iter().map(|i| *i as f64 + ALONG as f64).collect(); - cuts.push(m + ALONG as f64); - let mut verts: Vec = Vec::with_capacity(sides.len()); - for side in sides { - let first = side.first().ok_or_else(|| fail("a section curve has no stations"))?; - verts.push(builder::vertex(p3(first.p))); - } - let mut edges: Vec = Vec::with_capacity(sides.len()); - for i in 0..sides.len() { - let (Some(&a), Some(&b)) = (cuts.get(i), cuts.get(i + 1)) else { return Err(fail("the corner's seams")) }; - let mut piece = loop_curve.clone(); - let _tail = mt::Cut::cut(&mut piece, b); - let piece = mt::Cut::cut(&mut piece, a); - let (Some(from), Some(to)) = (verts.get(i), verts.get((i + 1) % verts.len())) else { return Err(fail("the corner's vertices")) }; - edges.push(mt::Edge::try_new(from, to, piece).map_err(|e| fail(format!("a corner seam: {e}")))?); - } - let face = mt::Face::try_new(vec![mt::Wire::from(edges)], surface).map_err(|e| fail(format!("the corner patch: {e}")))?; - Ok(vec![face]) -} - -/// What the patch achieves along the seams of `sides`: the largest distance from a seam station to -/// the patch, the largest angle (radians) between the patch's normal there and the blend's, and the -/// largest difference between the curvature across the seam and the blend's own, relative to -/// `reference` — the curvature a rolling-ball corner shows across the same seam, which is what G2 -/// removes. Measured on the built surface alone, by the same finite differences of its own samples -/// that `crate::bridge`'s tests read a cross-section's shape with, so it is evidence about the -/// geometry and not about the construction. -pub fn seam_error(surface: &mt::Surface, sides: &[Vec], reference: f64) -> Result<(f64, f64, f64)> { - use mt::{ParametricSurface, SearchNearestParameter}; - if !(reference.is_finite() && reference > 0.0) { - return Err(KernelError::Invalid("a reference curvature must be finite and positive".into())); - } - let (Some((u0, u1)), Some((v0, v1))) = surface.try_range_tuple() else { - return Err(fail("the corner patch has no parameter domain")); - }; - // Samples across the section for a five-point difference, as `bridge`'s tests use. - const INWARDS: usize = 5; - let hv = (v1 - v0).abs() * 1e-3; - let hu = (u1 - u0).abs() * 1e-3; - if !(hv > 0.0 && hu > 0.0) { - return Err(fail("the corner patch has no extent to measure")); - } - let (mut gap, mut angle, mut curvature) = (0.0f64, 0.0f64, 0.0f64); - for side in sides { - if side.len() < 5 { - return Err(KernelError::Invalid("a seam needs at least five stations to measure its direction".into())); - } - let mut hint: Option<(f64, f64)> = None; - for (i, f) in side.iter().enumerate() { - let Some(t) = seam_tangent(side, i) else { continue }; - let found = surface - .search_nearest_parameter(p3(f.p), hint, 100) - .or_else(|| surface.search_nearest_parameter(p3(f.p), None, 200)) - .ok_or_else(|| fail("a seam station is not on the corner patch"))?; - hint = Some(found); - let (u, v) = found; - let at = from_p3(surface.subs(u, v)); - gap = gap.max(at.dist(f.p)); - // The cross-section, sampled inwards from the seam (or from the other end of the patch, - // with the odd differences turned round). - let out = v <= (v0 + v1) * 0.5; - let step = if out { hv } else { -hv }; - let q: Vec = (0..INWARDS).map(|k| from_p3(surface.subs(u, v + step * k as f64))).collect(); - let (Some(&f0), Some(&f1), Some(&f2), Some(&f3), Some(&f4)) = (q.first(), q.get(1), q.get(2), q.get(3), q.get(4)) else { - return Err(fail("the corner patch has no room for a sample")); - }; - let sign = if out { 1.0 } else { -1.0 }; - let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (sign / (12.0 * hv)); - let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * hv * hv)); - // Along the seam, to stand the tangent plane up. - let du = if u - hu >= u0 && u + hu <= u1 { - (from_p3(surface.subs(u + hu, v)) - from_p3(surface.subs(u - hu, v))) * (0.5 / hu) - } else { - let (a, b) = if u + hu <= u1 { (u, u + hu) } else { (u, u - hu) }; - (from_p3(surface.subs(b, v)) - from_p3(surface.subs(a, v))) * (1.0 / hu) - }; - let n = du.cross(d1).normalized().ok_or_else(|| fail("the corner patch has no normal at a seam"))?; - let blend_n = t.cross(f.leave).normalized().ok_or_else(|| fail("a blend has no normal at a seam"))?; - angle = angle.max(n.dot(blend_n).abs().clamp(0.0, 1.0).acos()); - // The curvature vector of the cross-seam curve: what the blend's own surface does along - // the direction the patch leaves it in. - let speed2 = d1.len2().max(1e-300); - let bend = (d2 - d1 * (d2.dot(d1) / speed2)) * (1.0 / speed2); - curvature = curvature.max((bend - f.bend).len() / reference.max(f.bend.len()).max(1e-30)); - } - } - Ok((gap, angle, curvature)) + crate::fill::matched_patch(sheet, hole, CURVATURE_SHARE / radius) } #[cfg(test)] #[path = "corner_g2_tests.rs"] mod tests; - -/// The G2 corner through the fillet path: a box's three edges at one corner rounded, rolling ball -/// against G2 patch, measured on the built bodies with the continuity analysis. -#[cfg(test)] -#[allow(clippy::unwrap_used)] -mod fillet_corner_tests { - use super::*; - use crate::{ContinuityTolerances, SeamReport, measure, seam_diagnostics}; - - /// A 20 mm box with its three edges at one corner rounded by 4: the rolling ball fills that - /// corner with a piece of its sphere, the G2 route with a patch on the blends' own sections. - fn cornered(g2: bool) -> crate::Body { - let b = crate::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); - let edges = [Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 0.0, 10.0)]; - if g2 { crate::fillet_g2_corners(&b, &edges, 4.0).unwrap() } else { crate::fillet(&b, &edges, 4.0).unwrap() } - } - - #[test] - fn the_ball_corner_is_measurably_g1_and_a_g2_corner_is_refused_until_it_sews() { - // The rolling ball: tangent to every blend, keeping its own 1/r across each corner seam. - let body = cornered(false); - let volume = measure(&body).unwrap().volume; - assert!(volume > 7000.0 && volume < 8000.0, "the box is still a solid: {volume}"); - let report = seam_diagnostics(&body, &[], 33, ContinuityTolerances { gap_mm: 1e-3, angle_deg: 1.0, curvature_per_mm: 1e-6 }).unwrap(); - // Every seam of a filleted box is tangent; the corner's three are the short ones (the - // blend-to-face seams run the edge's own 12 mm and more). - let tangent: Vec<&SeamReport> = report.seams.iter().filter(|s| s.normal_angle_deg.value < 0.01).collect(); - let corner: Vec<&&SeamReport> = tangent.iter().filter(|s| s.length < 8.0).collect(); - assert_eq!( - corner.len(), - 3, - "three corner seams among {} tangent ones: {:?}", - tangent.len(), - tangent.iter().map(|s| s.length).collect::>() - ); - let worst = corner.iter().map(|s| s.curvature_jump_per_mm.value).fold(0.0f64, f64::max); - eprintln!("rolling ball: corner seams jump {worst:.6} per mm (volume {volume:.3})"); - assert!((worst - 0.25).abs() < 1e-3, "the ball keeps its own 1/r (r = 4) across the seam: {worst}"); - - // The G2 corner patch is built on the blends' own sections, but sewing it into the shell - // is not done yet: the fillet with `corner: g2` refuses with a clear message rather than - // leaving the shell open, and leaves the ball the corner. - let b = crate::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); - let edges = [Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 0.0, 10.0)]; - let err = crate::fillet_g2_corners(&b, &edges, 4.0).unwrap_err().to_string(); - eprintln!("G2 corner: {err}"); - assert!(err.contains("not supported yet:") && err.contains("G2 corner"), "{err}"); - } -} diff --git a/crates/kernel/src/corner_g2_tests.rs b/crates/kernel/src/corner_g2_tests.rs index 0968522b6..f0d14d183 100644 --- a/crates/kernel/src/corner_g2_tests.rs +++ b/crates/kernel/src/corner_g2_tests.rs @@ -1,154 +1,369 @@ -//! What the G2 corner patch has to prove on a corner whose answer is known analytically: the box. +use solidcore_record::Vec3; +use solidcore_record::brep as b; +use solidcraft_geom::prelude::*; -use super::*; -use std::f64::consts::FRAC_PI_2; +use crate::*; -use crate::body::v3; - -/// One seam of a box corner: a quarter circle about `centre` from direction `u` to direction `w`, -/// with `leave` the way the patch leaves the blend's surface. A fillet is flat along its own axis, -/// so its curvature across the seam is nothing. -fn seam(centre: Vec3, u: Vec3, w: Vec3, leave: Vec3, r: f64, n: usize) -> Vec { - (0..n) - .map(|i| { - let theta = FRAC_PI_2 * i as f64 / (n - 1) as f64; - Frame { p: centre + (u * theta.cos() + w * theta.sin()) * r, leave, bend: Vec3::ZERO, bend_change: Vec3::ZERO } - }) - .collect() +/// The three r5 rounds at the corner (60, 40, 20) of a 60 x 40 x 20 box (ladder 07/009 and +/// 07/015). +fn box_corner() -> (Body, [Vec3; 3]) { + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + (b, [Vec3::new(30.0, 40.0, 20.0), Vec3::new(60.0, 20.0, 20.0), Vec3::new(60.0, 40.0, 10.0)]) } -/// A box corner at the origin (material x, y, z ≥ 0) with three fillets of radius `r`: the three -/// section curves where the fillets stop, meeting at (0,r,r), (r,0,r) and (r,r,0), and the middle of -/// the ball's octant a rolling ball would leave there. -fn box_corner(r: f64, n: usize) -> (Vec>, Vec3, Vec3) { - let c = Vec3::new(r, r, r); - let (a, b, d) = (Vec3::new(0.0, r, r), Vec3::new(r, 0.0, r), Vec3::new(r, r, 0.0)); - let dir = |p: Vec3| (p - c).normalized().unwrap_or(Vec3::X); - let sides = vec![ - // A → B on the z edge's cylinder (flat along z), B → C on the x edge's, C → A on the y - // edge's; each patch leaves the blend towards the material the corner caps. - seam(c, dir(a), dir(b), Vec3::new(0.0, 0.0, -1.0), r, n), - seam(c, dir(b), dir(d), Vec3::new(-1.0, 0.0, 0.0), r, n), - seam(c, dir(d), dir(a), Vec3::new(0.0, -1.0, 0.0), r, n), - ]; - let apex = c - Vec3::new(1.0, 1.0, 1.0).normalized().unwrap_or(Vec3::Z) * r; - (sides, apex, c) -} - -/// The rolling-ball corner the kernel builds today: the sphere through the same three seams, made -/// the way `curvecorner` makes it (a meridian arc swept about the axis through the ball's centre). -fn rolling_ball(r: f64, c: Vec3) -> mt::Surface { - let axis = Vec3::new(1.0, 1.0, 1.0).normalized().unwrap_or(Vec3::Z); - let side = axis.any_perp(); - let meridian = builder::circle_arc(&builder::vertex(p3(c + axis * r)), &builder::vertex(p3(c - axis * r)), p3(c + side * r)); - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(meridian.oriented_curve(), p3(c), v3(axis)))) -} - -/// The stations clear of the corners. Two blends meet at a corner with their seams 90° apart and -/// ask for different curvature at that one point, which no single patch can hold, and the corner's -/// own spline rounds the seam there; both effects fade within a few stations, so the measurement -/// starts clear of them. -fn interior(sides: &[Vec]) -> Vec> { - sides.iter().map(|s| s.iter().skip(4).take(s.len().saturating_sub(8)).copied().collect()).collect() -} - -#[test] -fn a_box_corner_is_curvature_continuous_with_every_blend() { - let r = 2.0; - let (sides, apex, centre) = box_corner(r, 25); - let faces = corner_g2_patch(&sides, apex).unwrap(); - let face = faces.first().expect("a corner patch"); - let surface = face.oriented_surface(); - let inner = interior(&sides); - let (gap, angle, curvature) = seam_error(&surface, &inner, 1.0 / r).unwrap(); - println!("G2 corner: gap {gap:e}, normal angle {angle:e} rad, curvature {curvature:e} (relative to 1/r)"); - assert!(gap <= r * 1e-5, "the patch is {gap} from the seam"); - // The stated tolerances: the normal angle within 0.01° and the curvature across the seam within - // 1% of the blend's own (here the fillet is flat across the seam, so that is 1% of 1/r). - assert!(angle < 0.01f64.to_radians(), "normal angle {angle} rad"); - assert!(curvature < 1e-2, "curvature across the seam is {curvature} of the blend's"); - - // The same measurement on the rolling-ball corner the kernel builds today: G1 (angle nought) - // but the ball's own 1/r across each seam, which is the whole of the blend's curvature. - let ball = rolling_ball(r, centre); - let (ball_gap, ball_angle, ball_curvature) = seam_error(&ball, &inner, 1.0 / r).unwrap(); - println!("rolling ball: gap {ball_gap:e}, normal angle {ball_angle:e} rad, curvature {ball_curvature:e}"); - assert!(ball_angle < 0.01f64.to_radians(), "the ball is tangent to each blend"); - assert!(ball_curvature > 0.5, "the ball keeps its own curvature across the seam: {ball_curvature}"); - assert!(curvature * 20.0 < ball_curvature, "the G2 patch has to be far closer than the ball"); -} - -#[test] -fn a_corner_meets_three_blends_of_different_shape_apart() { - // Blends that differ along their seams: a fillet of radius 2 next to rounder walls, each asking - // for its own curvature across the seam, at its own direction. - let r = 2.0; - let (mut sides, apex, _) = box_corner(r, 33); - let bends = [0.25, 0.4, 0.6]; - for (i, bend) in bends.iter().enumerate() { - let Some(side) = sides.get_mut(i) else { continue }; - for f in side.iter_mut() { - // Across the seam, perpendicular to both the leave direction and the seam. - f.bend = f.leave.any_perp() * *bend; - } - } - let faces = corner_g2_patch(&sides, apex).unwrap(); - let surface = faces.first().expect("a corner patch").oriented_surface(); - let inner = interior(&sides); - let (gap, angle, curvature) = seam_error(&surface, &inner, bends.iter().copied().fold(0.0, f64::max)).unwrap(); - println!("three different blends: gap {gap:e}, angle {angle:e} rad, curvature {curvature:e}"); - assert!(gap <= r * 1e-6, "{gap}"); - assert!(angle < 0.01f64.to_radians(), "{angle}"); - assert!(curvature < 1e-2, "each blend's own curvature across the seam: {curvature}"); -} - -#[test] -fn a_g2_corner_refuses_what_it_cannot_hold() { - let r = 2.0; - let (sides, apex, _) = box_corner(r, 9); - assert!(corner_g2_patch(&sides, apex).is_ok()); - - // Two blends (the ball's patch still fills that corner), or one. - assert!(corner_g2_patch(&sides[..2], apex).is_err()); - assert!(corner_g2_patch(&sides[..1], apex).is_err()); - assert!(corner_g2_patch(&[], apex).is_err()); - - // Too few stations to interpolate a cubic through, and too many to work with. - let thin: Vec> = sides.iter().map(|s| s[..3].to_vec()).collect(); - assert!(corner_g2_patch(&thin, apex).is_err()); - let fat: Vec> = sides.iter().map(|s| s[..1].iter().cycle().take(MAX_STATIONS + 1).copied().collect()).collect(); - assert!(corner_g2_patch(&fat, apex).is_err()); - - // A vertex the construction cannot hold: the section curves do not meet at their corners. - let mut apart = sides.clone(); - if let Some(first) = apart.first_mut().and_then(|s| s.first_mut()) { - first.p += Vec3::new(0.5, 0.0, 0.0); - } - assert!(corner_g2_patch(&apart, apex).is_err()); - - // A section curve that runs along the seam, so the patch has no direction to leave it in. - let along: Vec> = sides +/// The worst curvature jump across the seams of the faces that are none of the box's planes or +/// rounds (the corner's: a sphere, or a patch), and the same clear of the hole's corners: a station counts there when +/// it is at least `share` of its seam's side (its edge and the edge that continues it smoothly: +/// SMLib splits each side in two) from the end of the side at a corner, a vertex where the seam +/// turns. +fn corner_seams(body: &Body, share: f64) -> (f64, f64, usize) { + let rec = brep_record(body).unwrap(); + let corner_faces: Vec = rec + .faces .iter() - .map(|s| { - s.windows(2) - .map(|w| { - let d = w.first().zip(w.get(1)).map(|(a, b)| (b.p - a.p).normalized().unwrap_or(Vec3::X)).unwrap_or(Vec3::X); - Frame { leave: d, ..w.first().copied().unwrap_or(s[0]) } - }) - .chain(s.last().copied()) - .collect() + .enumerate() + .filter(|(_, f)| !matches!(f.surface, b::Surface::Plane { .. } | b::Surface::PlaneThrough { .. } | b::Surface::Cylinder { .. })) + .map(|(i, _)| i) + .collect(); + let edges: Vec = (0..rec.edges.len()).filter(|e| rec.edges[*e].uses.iter().any(|u| corner_faces.contains(&(u.face as usize)))).collect(); + let report = + seam_diagnostics(body, &edges, 65, ContinuityTolerances { gap_mm: 1e-3, angle_deg: 1.0, curvature_per_mm: 1e-6, ..Default::default() }) + .unwrap(); + // The corner's vertices where its boundary turns: an end of two of its seams whose + // directions there differ. + let ends: Vec<(Vec3, Vec3, f64)> = report + .seams + .iter() + .flat_map(|s| { + let (p0, p1) = (s.points[0], *s.points.last().unwrap()); + let d0 = (s.points[1] - p0).normalized().unwrap(); + let d1 = (s.points[s.points.len() - 2] - p1).normalized().unwrap(); + [(p0, d0, s.length), (p1, d1, s.length)] }) .collect(); - assert!(corner_g2_patch(&along, apex).is_err()); - - // Hostile numbers never panic. - let mut nan = sides.clone(); - if let Some(f) = nan.first_mut().and_then(|s| s.get_mut(1)) { - f.p = Vec3::new(f64::NAN, 0.0, 0.0); + let turns = + |p: Vec3, d: Vec3| ends.iter().any(|(q, e, _)| q.dist(p) < 1e-6 && (d - *e).len() > 1e-6 && d.dot(*e) > -0.9998 && d.dot(*e) < 0.9998); + let (mut all, mut clear, mut n) = (0.0f64, 0.0f64, 0usize); + for s in &report.seams { + let (p0, p1) = (s.points[0], *s.points.last().unwrap()); + let d0 = (s.points[1] - p0).normalized().unwrap(); + let d1 = (s.points[s.points.len() - 2] - p1).normalized().unwrap(); + let corner_end = if turns(p0, d0) { + Some(0.0) + } else if turns(p1, d1) { + Some(1.0) + } else { + None + }; + for st in &s.stations { + all = all.max(st.curvature_jump_per_mm); + // Half a side per edge: `share` of the side is twice that of the edge. + if corner_end.is_none_or(|c| (st.edge_fraction - c).abs() >= 2.0 * share) { + clear = clear.max(st.curvature_jump_per_mm); + n += 1; + } + } } - assert!(corner_g2_patch(&nan, apex).is_err()); - assert!(corner_g2_patch(&sides, Vec3::new(f64::INFINITY, 0.0, 0.0)).is_err()); - // A corner with no room: every station on the apex. - let on_apex: Vec> = sides.iter().map(|s| s.iter().map(|f| Frame { p: apex, ..*f }).collect()).collect(); - assert!(corner_g2_patch(&on_apex, apex).is_err()); + (all, clear, n) +} + +/// The G2 corner of 07/015, set back the default 7.5 (1.5 r): one closed valid solid of the box's +/// six faces, the three rounds and the patch (10 faces, as the sphere corner's 07/009), within +/// the box, whose volume lies between the corner cube's hull of the body's points on its faces +/// (the body is convex) and the rounds' prisms, as the setback's own does; and across every +/// seam of the patch the curvature jump, a fifth per mm on the rolling ball's, is under +/// `CURVATURE_SHARE / r` clear of the hole's corners. +#[test] +fn the_box_corner_g2_patch_is_a_closed_solid_curvature_continuous_to_its_neighbours() { + let (body, edges) = box_corner(); + let ball = fillet(&body, &edges, 5.0).unwrap(); + let g2 = fillet_g2_corners(&body, &edges, 5.0, &[]).unwrap(); + assert!(g2.validity().is_empty(), "{:?}", g2.validity()); + let v = crate::validity::validity(&g2); + assert!(v.ok(), "{:?}", v); + let m = measure(&g2).unwrap(); + let mb = measure(&ball).unwrap(); + eprintln!("G2 corner: faces {} edges {} vertices {}, volume {:.6} (ball {:.6})", m.faces, m.edges, m.vertices, m.volume, mb.volume); + assert_eq!(m.faces, 10); + assert!((m.bbox.min - Vec3::ZERO).len() < 1e-6 && (m.bbox.max - Vec3::new(60.0, 40.0, 20.0)).len() < 1e-6, "{:?}", m.bbox); + let (all, clear, n) = corner_seams(&g2, 0.15); + let (ball_all, ball_clear, _) = corner_seams(&ball, 0.15); + eprintln!( + "G2 corner seams: worst jump {all:.4e} per mm, {clear:.4e} clear of the corners ({n} stations); the ball's {ball_all:.4e} / {ball_clear:.4e}" + ); + assert!(clear <= CURVATURE_SHARE / 5.0, "{clear}"); +} + +/// Set back 8, as SMLib's own setback test: outside the corner cube [52, 60] x [32, 40] x +/// [12, 20] the body is the sphere corner's, and inside it the convex body holds the hull of its +/// points on the cube's faces (299.0201, by a hull of them sampled) and lies within the three +/// rounds' prisms (`fillet_setback_tests`). +#[test] +fn set_back_8_the_g2_corner_lies_between_the_hull_and_the_prisms() { + let pi = std::f64::consts::PI; + let (body, edges) = box_corner(); + let sphere = measure(&fillet(&body, &edges, 5.0).unwrap()).unwrap().volume; + let g2 = fillet_g2_corners(&body, &edges, 5.0, &[(Vec3::new(60.0, 40.0, 20.0), 8.0)]).unwrap(); + let v = measure(&g2).unwrap().volume; + let outside = sphere - (512.0 - 225.0 * (1.0 - pi / 4.0) - 125.0 * (1.0 - pi / 6.0)); + let prisms = 512.0 - 225.0 * (1.0 - pi / 4.0) - 125.0 * (2f64.sqrt() - 1.0); + eprintln!("G2 corner set back 8: volume {v:.6} in [{:.6}, {:.6}]", outside + 299.0201, outside + prisms); + assert!(v > outside + 299.0201 && v < outside + prisms); + let (_, clear, _) = corner_seams(&g2, 0.15); + assert!(clear <= CURVATURE_SHARE / 5.0, "{clear}"); +} + +/// How far past the box (60, 40, 20) face `face` of `rec` reaches within its trim: the highest +/// `max(x - 60, y - 40, z - 20)` on it, bracketed `(lo, hi)` from its exact surface alone, with no +/// mesh. The surface (a polynomial B-spline) is cut into its Bézier patches and those split in +/// four (de Casteljau, exact up to rounding) while they can still hold a higher point: a patch +/// lies in the hull of its control points, so its controls' highest value bounds it from above +/// (`hi`), and its corners are points of the surface (`lo`, where inside the trim). A patch +/// clear of the trim (the face's pcurves, sampled densely in its (u, v)) is dropped; one whose +/// hull cannot beat `lo` by 1e-12 is done; one split 18 times counts its hull in `hi`. Returns +/// the bracket and the (u, v) where `lo` is reached. +fn past_the_box(rec: &b::Brep, face: usize) -> (f64, f64, [f64; 2]) { + use solidcraft_geom::bspline::{HPoint, segment}; + let f = &rec.faces[face]; + let (b::Surface::Spline { u_knots, v_knots, points }, None) = (&f.surface, &f.nurbs) else { + panic!("face {face} is no polynomial B-spline: {:?}", std::mem::discriminant(&f.surface)); + }; + let excess = |p: Vec3| (p.x - 60.0).max(p.y - 40.0).max(p.z - 20.0); + // The trim: every loop's pcurves as one polygon set, inside by the even-odd rule. + let mut rings: Vec> = Vec::new(); + for l in &f.loops { + let b::Loop::Edges { edges } = l else { continue }; + let mut ring = Vec::new(); + for oe in edges { + let [t0, t1] = oe.pcurve.interval().unwrap(); + let mut seg: Vec<[f64; 2]> = + (0..=400).map(|k| solidcraft_geom::brep::pcurve::eval(&oe.pcurve, t0 + (t1 - t0) * f64::from(k) / 400.0).unwrap()).collect(); + if !oe.forward { + seg.reverse(); + } + ring.extend(seg); + } + rings.push(ring); + } + let inside = |w: [f64; 2]| { + let mut odd = false; + for r in &rings { + for k in 0..r.len() { + let (p, q) = (r[k], r[(k + 1) % r.len()]); + if (p[1] > w[1]) != (q[1] > w[1]) && w[0] < p[0] + (w[1] - p[1]) * (q[0] - p[0]) / (q[1] - p[1]) { + odd = !odd; + } + } + } + odd + }; + let touches = |u: [f64; 2], v: [f64; 2]| { + rings.iter().flatten().any(|w| (u[0]..=u[1]).contains(&w[0]) && (v[0]..=v[1]).contains(&w[1])) + || [[u[0], v[0]], [u[1], v[0]], [u[0], v[1]], [u[1], v[1]]].into_iter().any(inside) + }; + // The Bézier patches: each knot span in u, then in v (control point [i][j], i along u). + let (nu, nv) = (points.len(), points[0].len()); + let (p, q) = (u_knots.len() - nu - 1, v_knots.len() - nv - 1); + let spans = |k: &[f64], n: usize, d: usize| { + let mut x: Vec = k[d..=n].to_vec(); + x.dedup(); + x.windows(2).map(|w| [w[0], w[1]]).collect::>() + }; + type Patch = (Vec>, [f64; 2], [f64; 2], u32); + let mut todo: Vec = Vec::new(); + for su in spans(u_knots, nu, p) { + // Each v column cut to the u span: (p + 1) x nv. + let cols: Vec> = (0..nv) + .map(|j| { + let c: Vec = (0..nu).map(|i| HPoint::weighted(Vec3::from(points[i][j]), 1.0)).collect(); + segment(p, u_knots, &c, su[0], su[1]).unwrap().1 + }) + .collect(); + for sv in spans(v_knots, nv, q) { + let net: Vec> = (0..=p) + .map(|i| { + segment(q, v_knots, &cols.iter().map(|c| c[i]).collect::>(), sv[0], sv[1]).unwrap().1.iter().map(|h| h.xyz()).collect() + }) + .collect(); + todo.push((net, su, sv, 0)); + } + } + let half = |c: &[Vec3]| { + let (mut l, mut r, mut pts) = (Vec::new(), Vec::new(), c.to_vec()); + while let (Some(&a), Some(&z)) = (pts.first(), pts.last()) { + l.push(a); + r.push(z); + pts = pts.windows(2).map(|w| w[0].lerp(w[1], 0.5)).collect(); + } + r.reverse(); + (l, r) + }; + let (mut lo, mut hi, mut at) = (f64::NEG_INFINITY, f64::NEG_INFINITY, [f64::NAN; 2]); + while let Some((net, u, v, depth)) = todo.pop() { + if !touches(u, v) { + continue; + } + for (i, j, uv) in [(0, 0, [u[0], v[0]]), (p, 0, [u[1], v[0]]), (0, q, [u[0], v[1]]), (p, q, [u[1], v[1]])] { + let e = excess(net[i][j]); + if e > lo && inside(uv) { + (lo, at) = (e, uv); + } + } + let hull = net.iter().flatten().map(|c| excess(*c)).fold(f64::NEG_INFINITY, f64::max); + if hull <= lo + 1e-12 { + continue; + } + if depth == 18 { + hi = hi.max(hull); + continue; + } + // Split in u (each column of the net is a v row: split the rows across i), then in v. + let (mut a, mut z) = (vec![Vec::new(); p + 1], vec![Vec::new(); p + 1]); + for j in 0..=q { + let (l, r) = half(&net.iter().map(|row| row[j]).collect::>()); + for i in 0..=p { + a[i].push(l[i]); + z[i].push(r[i]); + } + } + let (um, vm) = (0.5 * (u[0] + u[1]), 0.5 * (v[0] + v[1])); + for (n, uu) in [(a, [u[0], um]), (z, [um, u[1]])] { + let (l, r): (Vec<_>, Vec<_>) = n.iter().map(|row| half(row)).unzip(); + todo.push((l, uu, [v[0], vm], depth + 1)); + todo.push((r, uu, [vm, v[1]], depth + 1)); + } + } + (lo, hi.max(lo), at) +} + +/// Long setbacks, where SMLib's own patch bulges past the faces (beyond about 2 r, by 0.25 at +/// 3 r): the G2 patch is fitted to the faces' own planes along their curves and stays inside the +/// box, G2 clear of the hole's corners. The body is convex (a box with its edges and corner +/// rounded), and a convex face lies on the inner side of every tangent plane: the patch meets +/// each of the box's planes tangentially along its seam there, so it reaches past none of them, +/// up to rounding (1e-9 mm, the patch's seams lie on the planes to 1e-13). Measured on the +/// patch's exact surface within its trim ([`past_the_box`]), not on a mesh of it. +#[test] +fn a_long_setback_keeps_the_g2_patch_inside_the_box() { + let (body, edges) = box_corner(); + let mut wrong = Vec::new(); + for s in [11.0, 12.0, 13.0, 14.0, 15.0] { + let g2 = fillet_g2_corners(&body, &edges, 5.0, &[(Vec3::new(60.0, 40.0, 20.0), s)]).unwrap(); + let rec = brep_record(&g2).unwrap(); + let patch: Vec = (0..rec.faces.len()).filter(|f| matches!(rec.faces[*f].surface, b::Surface::Spline { .. })).collect(); + assert_eq!(patch.len(), 1, "{s}: one patch"); + let (lo, hi, at) = past_the_box(&rec, patch[0]); + let (_, clear, _) = corner_seams(&g2, 0.15); + eprintln!("set back {s}: past the box by {lo:.4e} at (u, v) {at:?} (at most {hi:.4e}), curvature jump clear of the corners {clear:.3e}"); + if !(hi <= 1e-9 && clear <= CURVATURE_SHARE / 5.0) { + wrong.push(format!("set back {s}: past the box by {lo:.4e}..{hi:.4e} at (u, v) {at:?}, curvature jump {clear:.3e}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Every edge of a box rounded: eight corners, each set back and filled, one closed solid. +#[test] +fn a_box_with_every_edge_rounded_has_eight_g2_corners() { + let body = box_solid(Vec3::ZERO, Vec3::new(30.0, 20.0, 10.0)).unwrap(); + let mut edges = Vec::new(); + for (x, y) in [(0.0, 0.0), (30.0, 0.0), (0.0, 20.0), (30.0, 20.0)] { + edges.push(Vec3::new(x, y, 5.0)); + } + for (y, z) in [(0.0, 0.0), (20.0, 0.0), (0.0, 10.0), (20.0, 10.0)] { + edges.push(Vec3::new(15.0, y, z)); + } + for (x, z) in [(0.0, 0.0), (30.0, 0.0), (0.0, 10.0), (30.0, 10.0)] { + edges.push(Vec3::new(x, 10.0, z)); + } + let g2 = fillet_g2_corners(&body, &edges, 2.0, &[]).unwrap(); + assert!(g2.validity().is_empty(), "{:?}", g2.validity()); + let v = crate::validity::validity(&g2); + let m = measure(&g2).unwrap(); + eprintln!("eight G2 corners: {} faces, volume {:.4}, valid {}", m.faces, m.volume, v.ok()); + assert!(v.ok(), "{v:?}"); + assert_eq!(m.faces, 6 + 12 + 8); +} + +/// What the G2 corner cannot do is refused: a setback naming no corner, one that does not reach +/// past where the rounds meet; two rounded edges at a corner are no G2 corner, the plain fillet. +#[test] +fn what_the_g2_corner_cannot_build_is_refused() { + let (body, edges) = box_corner(); + let off = fillet_g2_corners(&body, &edges, 5.0, &[(Vec3::new(30.0, 20.0, 10.0), 8.0)]).unwrap_err().to_string(); + assert!(off.contains("names no G2 corner"), "{off}"); + let short = fillet_g2_corners(&body, &edges, 5.0, &[(Vec3::new(60.0, 40.0, 20.0), 4.0)]); + eprintln!("set back 4 at r5: {short:?}"); + assert!(short.is_err()); + let two = fillet_g2_corners(&body, &edges[..2], 5.0, &[]).unwrap(); + let plain = fillet(&body, &edges[..2], 5.0).unwrap(); + assert_eq!(measure(&two).unwrap().faces, measure(&plain).unwrap().faces); +} + +/// The 60 x 40 x 20 box with a 20 x 20 x 10 notch cut from its top corner (60, 40, 20): its +/// inner corner (40, 20, 10) where three concave edges meet, and the notch's outer corner +/// (60, 20, 10) where the concave edge along x meets two convex ones. +fn notched() -> Body { + let a = box_solid(Vec3::ZERO, Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let b = box_solid(Vec3::new(40.0, 20.0, 10.0), Vec3::new(70.0, 50.0, 30.0)).unwrap(); + boolean(&a, &b, BoolOp::Cut).unwrap().unwrap() +} + +/// The notch's inner corner, three concave r5 rounds (ladder 07/019): set back 7.5 and filled, +/// one closed valid solid with the faces the ball corner has, the patch's seams G2 clear of the +/// hole's corners where the ball's jump 1/r. +#[test] +fn a_concave_corner_takes_the_g2_patch_too() { + let body = notched(); + let edges = [Vec3::new(50.0, 20.0, 10.0), Vec3::new(40.0, 30.0, 10.0), Vec3::new(40.0, 20.0, 15.0)]; + let ball = fillet(&body, &edges, 5.0).unwrap(); + let g2 = fillet_g2_corners(&body, &edges, 5.0, &[]).unwrap(); + assert!(g2.validity().is_empty(), "{:?}", g2.validity()); + let v = crate::validity::validity(&g2); + assert!(v.ok(), "{v:?}"); + let (m, mb) = (measure(&g2).unwrap(), measure(&ball).unwrap()); + let (_, clear, n) = corner_seams(&g2, 0.15); + let (_, ball_clear, _) = corner_seams(&ball, 0.15); + eprintln!( + "concave G2 corner: {} faces (ball {}), volume {:.4} (ball {:.4}), jump clear of the corners {clear:.3e} ({n} stations), ball's {ball_clear:.3e}", + m.faces, mb.faces, m.volume, mb.volume + ); + assert_eq!(m.faces, mb.faces); + assert!(clear <= CURVATURE_SHARE / 5.0 && ball_clear > 0.19, "{clear} {ball_clear}"); +} + +/// The notch's outer corner, two convex rounds and a concave one: SMLib sets back only a corner +/// of one convexity, so the G2 corner is refused as not supported (the rolling ball builds). +#[test] +fn a_mixed_convexity_corner_is_refused() { + let body = notched(); + let edges = [Vec3::new(50.0, 20.0, 10.0), Vec3::new(60.0, 30.0, 10.0), Vec3::new(60.0, 20.0, 15.0)]; + assert!(fillet(&body, &edges, 5.0).is_ok()); + let err = fillet_g2_corners(&body, &edges, 5.0, &[]).unwrap_err().to_string(); + eprintln!("mixed corner: {err}"); + // The refusal names the corner and why: its rounds are not all of one convexity. + assert!(err.contains("not supported yet") && err.contains("(60.000, 20.000, 10.000)") && err.contains("all convex or all concave"), "{err}"); +} + +/// Curvature-continuous rounds (`fillet_g2`, equivalent radius 5) of the three edges at the box +/// corner: SMLib's own corner between them is its setback corner, whose fill for curvature +/// sections meets the rounds and faces curvature-continuously (SmBlendSetback.h: G2 for an order +/// 2 section), as the G2 patch filled between the curvature rounds' setback sections does: each +/// one closed valid solid, curvature-continuous across every seam round the corner clear of the +/// hole's corners. +#[test] +fn curvature_rounds_meet_at_a_g2_corner() { + let (body, edges) = box_corner(); + let smlib_corner = fillet_g2(&body, &edges, 5.0).unwrap(); + let g2 = fillet_g2_with_g2_corners(&body, &edges, 5.0, &[]).unwrap(); + assert!(g2.validity().is_empty(), "{:?}", g2.validity()); + let v = crate::validity::validity(&g2); + assert!(v.ok(), "{:?}", v); + let (_, clear, n) = corner_seams(&g2, 0.15); + let (_, smlib_clear, smlib_n) = corner_seams(&smlib_corner, 0.15); + assert!(n > 0 && clear <= CURVATURE_SHARE / 5.0, "{clear} over {n} stations"); + assert!(smlib_n > 0 && smlib_clear <= CURVATURE_SHARE / 5.0, "SMLib's own corner: {smlib_clear} over {smlib_n} stations"); + // Both differ only within the setback cube (side 1.5 r = 7.5) at the corner. + let (a, b) = (measure(&g2).unwrap().volume, measure(&smlib_corner).unwrap().volume); + assert!((a - b).abs() < 7.5f64.powi(3), "{a} vs {b}"); } diff --git a/crates/kernel/src/curvature_comb.rs b/crates/kernel/src/curvature_comb.rs new file mode 100644 index 000000000..0f3d71d1e --- /dev/null +++ b/crates/kernel/src/curvature_comb.rs @@ -0,0 +1,173 @@ +//! Curvature combs on a body's edges and along a face's isoparametric curves, from the exact +//! geometry: each tooth stands at an even step of the curve's own parameter and carries the +//! curvature vector there, worked out from the record's derivatives (never from the display +//! mesh), so a comb does not depend on the tessellation and has as many teeth as asked for. +//! +//! An edge's tooth is its curve's curvature vector `κ N` ([`CurveEval::jet`]: lines, conics, +//! polylines, B-splines and NURBS from their first two derivatives, a traced intersection from +//! both surfaces' normal curvatures). A face's tooth along an iso line is the surface's normal +//! curvature in the line's direction times the surface normal, `κₙ n` with +//! `κₙ = n · S_tt / |S_t|²` (the second fundamental form over the first, in that direction). + +use solidcore_record::Vec3; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; +use solidcraft_geom::prelude::*; + +use crate::body::Body; +use crate::iso::IsoLine; +use crate::{KernelError, Result}; + +/// Fewest and most teeth along one curve. +pub const MIN_COMB_TEETH: usize = 2; +pub const MAX_COMB_TEETH: usize = 2000; + +/// Samples along each edge for the first, coarse look for the edge nearest a point. +const PICK_SAMPLES: usize = 32; +/// Edges (nearest by the coarse look) whose distance is then found exactly. +const PICK_REFINED: usize = 8; +/// Golden-section steps of the exact distance: the bracket shrinks to 0.618⁹⁰ ≈ 10⁻¹⁹ of a sample step. +const PICK_STEPS: usize = 90; + +/// One tooth of a comb. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CombTooth { + /// Where the tooth stands, on the curve. + pub at: Vec3, + /// The curvature vector there, 1/mm: towards the centre of curvature, its length the + /// curvature (a face's: the normal curvature along the iso line, along the surface normal). + pub curvature: Vec3, +} + +fn check_density(density: usize) -> Result<()> { + if (MIN_COMB_TEETH..=MAX_COMB_TEETH).contains(&density) { + Ok(()) + } else { + Err(KernelError::Invalid(format!("a comb has {MIN_COMB_TEETH}…{MAX_COMB_TEETH} teeth"))) + } +} + +/// The station fractions of `density` teeth: both ends of an open curve, every step of a closed +/// one once (its end is its start). +fn fractions(density: usize, closed: bool) -> impl Iterator { + let steps = if closed { density } else { density.saturating_sub(1).max(1) }; + (0..density).map(move |k| k as f64 / steps as f64) +} + +/// The edge of `body` nearest `at` and its exact distance: the distance to the edge's own curve +/// over its interval, not to a tessellation. A periodic face's own seam (an edge whose uses are +/// all on one face, the face meeting itself) and a degenerate edge (a pole) are not edges a comb +/// is drawn on. `None` when the body has no such edge. +pub fn comb_edge_near(body: &Body, at: Vec3) -> Result> { + body.require_brep("a curvature comb")?; + if !at.is_finite() { + return Err(KernelError::Invalid("the point must be finite".into())); + } + crate::guard("curvature comb pick", || { + let record = body.record(); + let mut coarse: Vec<(f64, usize, usize)> = Vec::new(); + for (index, edge) in record.edges.iter().enumerate() { + let seam = edge.uses.len() >= 2 && edge.uses.iter().all(|u| edge.uses.first().is_some_and(|f| f.face == u.face)); + let Ok(curve) = CurveEval::new(edge.parameters()) else { continue }; + let [t0, t1] = edge.interval; + if seam || curve.jet(0.5 * (t0 + t1)).is_none() { + continue; + } + let best = (0..=PICK_SAMPLES) + .filter_map(|k| curve.point(t0 + (t1 - t0) * k as f64 / PICK_SAMPLES as f64).map(|q| (q.dist(at), k))) + .filter(|(d, _)| d.is_finite()) + .min_by(|a, b| a.0.total_cmp(&b.0)); + if let Some((d, k)) = best { + coarse.push((d, index, k)); + } + } + coarse.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut best: Option<(f64, usize)> = None; + for &(_, index, k) in coarse.iter().take(PICK_REFINED) { + let Some(edge) = record.edges.get(index) else { continue }; + let Ok(curve) = CurveEval::new(edge.parameters()) else { continue }; + let Some(d) = nearest_on(&curve, edge.interval, k, at) else { continue }; + if best.is_none_or(|(bd, _)| d < bd) { + best = Some((d, index)); + } + } + Ok(best) + }) +} + +/// The distance from `at` to `curve` on `[t0, t1]`, by golden-section search on the sample steps +/// either side of sample `k` (the nearest of [`PICK_SAMPLES`] + 1), ends included. +fn nearest_on(curve: &CurveEval, [t0, t1]: [f64; 2], k: usize, at: Vec3) -> Option { + let step = (t1 - t0) / PICK_SAMPLES as f64; + let mid = t0 + step * k as f64; + let (mut a, mut b) = ((mid - step).max(t0.min(t1)), (mid + step).min(t0.max(t1))); + let dist = |t: f64| curve.point(t).map(|q| q.dist(at)).filter(|d| d.is_finite()); + let ratio = 0.5 * (5f64.sqrt() - 1.0); + let mut best = dist(mid)?; + let (mut x, mut y) = (b - (b - a) * ratio, a + (b - a) * ratio); + let (mut fx, mut fy) = (dist(x)?, dist(y)?); + for _ in 0..PICK_STEPS { + if fx < fy { + (b, y, fy) = (y, x, fx); + x = b - (b - a) * ratio; + fx = dist(x)?; + } else { + (a, x, fx) = (x, y, fy); + y = a + (b - a) * ratio; + fy = dist(y)?; + } + } + for d in [fx, fy, dist(a)?, dist(b)?] { + best = best.min(d); + } + Some(best) +} + +/// The comb of edge `edge` of `body` (its index in the body's edge order): `density` teeth at +/// even steps of the edge curve's parameter over the edge, ends included (a closed edge's end is +/// its start, once), each with the curve's exact curvature vector. Stations where the curve has +/// no tangent are left out. +pub fn edge_comb(body: &Body, edge: usize, density: usize) -> Result> { + body.require_brep("a curvature comb")?; + check_density(density)?; + crate::guard("curvature comb", || { + let e = body.record().edges.get(edge).ok_or_else(|| KernelError::Invalid(format!("the body has no edge {edge}")))?; + let curve = CurveEval::new(e.parameters()).map_err(|err| KernelError::Failed(format!("curvature comb: {err}")))?; + let [t0, t1] = e.interval; + let closed = e.vertices[0] == e.vertices[1]; + Ok(fractions(density, closed) + .filter_map(|f| curve.jet(t0 + (t1 - t0) * f)) + .map(|j| CombTooth { at: j.point, curvature: j.curvature }) + .collect()) + }) +} + +/// The comb along `line`, an isoparametric curve of face `face` of `body` ([`crate::iso_grid`]): +/// `density` teeth at even steps of the surface parameter that runs along it, ends included, each +/// the surface's normal curvature in the line's direction along its normal, from the surface's +/// exact partial derivatives. Stations at a pole (no tangent along the line) are left out. +pub fn iso_comb(body: &Body, face: usize, line: &IsoLine, density: usize) -> Result> { + body.require_brep("a curvature comb")?; + check_density(density)?; + crate::guard("curvature comb", || { + let f = body.record().faces.get(face).ok_or_else(|| KernelError::Invalid(format!("the body has no face {face}")))?; + let surface = SurfaceEval::new(f.parameters()).map_err(|err| KernelError::Failed(format!("curvature comb: {err}")))?; + let [s0, s1] = line.span; + let mut out = Vec::with_capacity(density); + for frac in fractions(density, false) { + let s = s0 + (s1 - s0) * frac; + let [u, v] = if line.along_u { [s, line.fixed] } else { [line.fixed, s] }; + let Some(d) = surface.partials(u, v) else { continue }; + let (along, bend) = if line.along_u { (d[1][0], d[2][0]) } else { (d[0][1], d[0][2]) }; + let speed2 = along.len2(); + let Some(n) = d[1][0].cross(d[0][1]).normalized() else { continue }; + if !(speed2 > 0.0) { + continue; + } + let curvature = n * (n.dot(bend) / speed2); + if d[0][0].is_finite() && curvature.is_finite() { + out.push(CombTooth { at: d[0][0], curvature }); + } + } + Ok(out) + }) +} diff --git a/crates/kernel/src/curveblend.rs b/crates/kernel/src/curveblend.rs deleted file mode 100644 index 1051cae30..000000000 --- a/crates/kernel/src/curveblend.rs +++ /dev/null @@ -1,2257 +0,0 @@ -//! Rolling-ball blends along a closed chain of smooth edges between two smooth groups of faces -//! of any surfaces (a branch pipe meeting a main pipe, a boss on a cylinder). A ball rolls along -//! the edge touching both sides; its centre traces the spine and its contacts the curves where -//! the blend meets each side. The blend face is a rational B-spline through the circular -//! cross-sections (exact arcs at the samples), the side faces are trimmed back to the contact -//! curves, and seams that met the edge (lines, or arcs of an end face) are shortened to the -//! contacts. -//! -//! The ball's size along the chain is one of [`Size`]: one radius all along (the ordinary -//! fillet), a chord width across the blend (each section spans the requested width from contact -//! to contact, so its radius is `chord / (2 sin(ψ/2))` for the `ψ` between the two outward -//! normals where the ball touches), or a radius law along the chain (a [`RadiusSpline`] whose -//! positions are the fraction of the chain's arc length, zero only at an end, where the blend -//! closes to the edge's end point as the straight-edge fillet does). - -use std::collections::HashMap; - -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, builder}; - -use crate::blend::too_large; -use crate::blend_variable::RadiusSpline; -use crate::body::{Solid, from_p3, p3}; -use crate::record::Rebuild; -use crate::{KernelError, Result}; - -fn unsupported(msg: &str) -> KernelError { - KernelError::Failed(format!("not supported yet: {msg}")) -} - -/// Samples per edge for the contact curves and the blend surface. -const SAMPLES: usize = 24; -const MAX_SAMPLES: usize = 369; -const MAX_CHAIN_SAMPLES: usize = 100_000; -/// Sections past a slanted end of an open chain. -const EXTENSION: usize = 8; -/// `1 + n1·n2` below this: a knife edge, where the faces' normals are opposite and the ball's -/// centre is found by sliding along the faces rather than from their normals. -const KNIFE: f64 = 1e-4; -/// An end face this close to square-on-to-its-sides' normal counts as tangent to a side. -const TANGENT_END: f64 = 1e-6; -/// Times the run past a tangent end is halved when the ball does not fit along it (and the run -/// past a curved end is shortened when its sections wrap round). -const TANGENT_RETRIES: usize = 8; -/// The longest step between the centres of neighbouring sections past an open chain's end, as a -/// multiple of the step along the end tangent: longer, and the sections have wrapped round a -/// curved edge's ring of centres. -const MAX_STEP_STRETCH: f64 = 3.0; -/// Slides of the ball's centre along a knife edge's faces, each 1.6 times the last. -const KNIFE_STEPS: usize = 40; -/// Corrections of the radius a chord fillet makes to the width it measures across the blend. -const CHORD_STEPS: usize = 12; -/// A section this close to a point is closed: the blend ends at the edge's end point (a radius -/// that has run to zero there). -const CLOSED: f64 = 1e-7; -/// Parameters an edge is sampled at to measure the arc length a radius law is read off. -const LENGTH_STEPS: usize = 64; - -/// The ball's size along the edge chain. -#[derive(Clone, Copy)] -enum Size<'a> { - /// One radius all along. - Constant(f64), - /// The width across the blend, from contact to contact, at every station. - Chord(f64), - /// The radius at the station's arc-length fraction along the chain, 0 at the front and 1 at - /// the back of its edge. - Law(&'a RadiusSpline), -} - -struct Fit { - surface: mt::Surface, - contacts: [mt::Curve; 2], - /// Parameter range belonging to this edge (the fit includes neighbouring sections). - range: (f64, f64), - /// The part of the fit that is the chain's own run, as fractions of its parameter range. - span: (f64, f64), -} - -struct Guide { - sections: Vec
, - /// The size law's parameter (the arc-length fraction along the chain) at each section: the - /// radius between the samples is read off the law there, not off the spine's own length. - law: Vec, - lengths: Vec, - /// The part of the guide that is the chain itself, as fractions of its length: the sections - /// run on past the ends of the chain (only so that the fit can be cut back there) and the fit - /// is checked for accuracy on the chain alone. - span: (f64, f64), -} - -impl Guide { - /// A guide whose law parameter is the section's own fraction of it (the size is one radius, - /// which needs no law). - fn new(sections: Vec
) -> Result { - let den = sections.len().max(2) - 1; - let law = (0..sections.len()).map(|i| i as f64 / den as f64).collect(); - Self::with_law(sections, law) - } - - fn with_law(sections: Vec
, law: Vec) -> Result { - if sections.len() != law.len() { - return Err(unsupported("degenerate rolling-ball spine")); - } - let mut lengths = vec![0.0]; - let mut total = 0.0; - for pair in sections.windows(2) { - let (Some(a), Some(b)) = (pair.first(), pair.get(1)) else { continue }; - total += a.c.dist(b.c); - lengths.push(total); - } - if !total.is_finite() || total <= 1e-12 { - return Err(unsupported("degenerate rolling-ball spine")); - } - Ok(Self { sections, law, lengths, span: (0.0, 1.0) }) - } - - /// The centre and tangent at `along` of the spine. - fn anchor(&self, along: f64) -> Option<(Vec3, Vec3)> { - self.anchor_at(along).map(|(centre, tangent, _)| (centre, tangent)) - } - - /// [`Guide::anchor`] with the size law's parameter at that station. - fn anchor_at(&self, along: f64) -> Option<(Vec3, Vec3, f64)> { - if self.lengths.len() < 2 || !along.is_finite() || !(0.0..=1.0).contains(&along) { - return None; - } - let distance = self.lengths.last()? * along; - let hi = self.lengths.partition_point(|length| *length < distance).clamp(1, self.lengths.len().checked_sub(1)?); - let (a, b) = (self.sections.get(hi - 1)?, self.sections.get(hi)?); - let (lo, hi_length) = (self.lengths.get(hi - 1)?, self.lengths.get(hi)?); - let span = hi_length - lo; - if span <= 1e-12 { - return None; - } - let fraction = (distance - lo) / span; - let law = self.law.get(hi - 1)? * (1.0 - fraction) + self.law.get(hi)? * fraction; - Some((a.c + (b.c - a.c) * fraction, (b.c - a.c).normalized()?, law)) - } -} - -/// One interpolation for both the face and its boundary curves. Fitting the contacts -/// independently gives different end conditions and leaves gaps between the same faces. -fn fit_sections(sections: &[Vec
], k: usize, closed: bool, round: bool) -> Result { - let fail = |m: &str| KernelError::Failed(format!("curve blend: {m}")); - let n = sections.len(); - let list = sections.get(k).ok_or_else(|| fail("section"))?; - let mut before = Vec::new(); - if closed || k > 0 { - let prev = sections.get((k + n - 1) % n).ok_or_else(|| fail("section"))?; - before.extend(prev.iter().rev().skip(1).take(2).rev().copied()); - } - let mut after = Vec::new(); - if closed || k + 1 < n { - let next = sections.get((k + 1) % n).ok_or_else(|| fail("section"))?; - after.extend(next.iter().skip(1).take(2).copied()); - } - fit_strip(list, &before, &after, round) -} - -/// [`fit_sections`] with the neighbouring sections given: best spaced as the strip's own, since -/// the interpolation's parameters are uniform. -fn fit_strip(list: &[Section], before: &[Section], after: &[Section], round: bool) -> Result { - use mt::Cut; - let fail = |m: &str| KernelError::Failed(format!("curve blend: {m}")); - let mut ext = Vec::with_capacity(list.len() + before.len() + after.len()); - ext.extend(before.iter().copied()); - ext.extend(list.iter().copied()); - ext.extend(after.iter().copied()); - let before = before.len(); - let ctrl: Vec<[mt::Vector4; 3]> = ext.iter().map(|s| section_controls(s, round)).collect::>().ok_or_else(|| fail("section"))?; - let mut rows = Vec::with_capacity(3); - let mut vknots = None; - for j in 0..3 { - let xyz: Vec = ctrl.iter().filter_map(|c| c.get(j)).map(|c| Vec3::new(c.x, c.y, c.z)).collect(); - let ww: Vec = ctrl.iter().filter_map(|c| c.get(j)).map(|c| Vec3::new(c.w, 0.0, 0.0)).collect(); - let bx = crate::build::interpolate_cubic(&xyz).ok_or_else(|| fail("blend surface"))?; - let bw = crate::build::interpolate_cubic(&ww).ok_or_else(|| fail("blend surface"))?; - vknots = Some(bx.knot_vec().clone()); - rows.push(bx.control_points().iter().zip(bw.control_points()).map(|(p, w)| mt::Vector4::new(p.x, p.y, p.z, w.x)).collect::>()); - } - let vk = vknots.ok_or_else(|| fail("knots"))?; - let den = ext.len().saturating_sub(1) as f64; - if den <= 0.0 { - return Err(fail("empty sections")); - } - let range = (before as f64 / den, (before + list.len().saturating_sub(1)) as f64 / den); - let contact = |row: usize| -> Result { - let points = rows.get(row).cloned().ok_or_else(|| fail("contact row"))?; - let bs = mt::BSplineCurve::try_new(vk.clone(), points).map_err(|e| fail(&e.to_string()))?; - let mut curve = mt::NurbsCurve::new(bs); - if range.0 > 0.0 { - curve = curve.cut(range.0); - } - if range.1 < 1.0 { - let _ = curve.cut(range.1); - } - Ok(mt::Curve::NurbsCurve(curve)) - }; - let contacts = [contact(0)?, contact(2)?]; - let bs = mt::BSplineSurface::try_new((mt::KnotVec::bezier_knot(2), vk), rows).map_err(|e| fail(&e.to_string()))?; - Ok(Fit { surface: mt::Surface::NurbsSurface(mt::NurbsSurface::new(bs)), contacts, range, span: (0.0, 1.0) }) -} - -/// Compare the fitted strip with a solved circular section between interpolation nodes. -/// This checks the supporting contacts as well as the middle of the fillet band. -fn section_fits(fit: &Fit, section: &Section, along: f64, round: bool, sigma: f64, tolerance: f64) -> bool { - use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let Some(ctrl) = section_controls(section, round) else { return false }; - let v = fit.range.0 + (fit.range.1 - fit.range.0) * along; - for u in [0.0, 0.25, 0.5, 0.75, 1.0] { - let [a, b, c] = ctrl; - let h = a * (1.0 - u) * (1.0 - u) + b * (2.0 * u * (1.0 - u)) + c * u * u; - if !h.w.is_finite() || h.w <= 1e-12 { - return false; - } - let exact = Vec3::new(h.x / h.w, h.y / h.w, h.z / h.w); - // The input intersection edge may use piecewise leader-curve parameters. A - // parameter-speed change is not a geometric error: compare nearest points, with - // contacts constrained to the corresponding boundary and all probes to the strip. - let (probe_u, probe_v) = if u == 0.0 || u == 1.0 { - let Some(contact) = fit.contacts.get(usize::from(u == 1.0)) else { return false }; - let Some(parameter) = contact.search_nearest_parameter(p3(exact), v, 32) else { return false }; - (u, parameter.clamp(fit.range.0, fit.range.1)) - } else { - let Some((pu, pv)) = fit.surface.search_nearest_parameter(p3(exact), Some((u, v)), 32) else { return false }; - (pu.clamp(0.0, 1.0), pv.clamp(fit.range.0, fit.range.1)) - }; - let actual = from_p3(fit.surface.subs(probe_u, probe_v)); - if !actual.is_finite() || actual.dist(exact) > tolerance { - return false; - } - if round && (u == 0.0 || u == 1.0) { - let Some(want) = ((section.c - exact) * sigma).normalized() else { return false }; - let normal = fit.surface.normal(probe_u, probe_v); - let Some(normal) = Vec3::new(normal.x, normal.y, normal.z).normalized() else { return false }; - if normal.dot(want).abs() < 0.5f64.to_radians().cos() { - return false; - } - } - } - true -} - -/// Where a blend strip run on past a chain end meets the end face: the contacts' parameters -/// there and the end curve from contact 1 to contact 2 (fitted through points where the -/// strip's cross-section curves meet the face's surface, and checked against both). -fn end_cap(fit: &Fit, g: &mt::Face, at: &Section, seams: [Option<&mt::Edge>; 2], round: bool, tolerance: f64) -> Result<(f64, f64, mt::Curve)> { - use mt::{ParametricCurve, ParametricSurface, SearchNearestParameter}; - let fail = || unsupported("the blend's end on its end face"); - let (surf, gs) = (&fit.surface, g.surface()); - let mid = if round { at.c + ((at.q1 - at.c) + (at.q2 - at.c)).normalized().ok_or_else(fail)? * at.c.dist(at.q1) } else { (at.q1 + at.q2) * 0.5 }; - let (_, v_start) = surf.search_nearest_parameter(p3(mid), None, 100).ok_or_else(fail)?; - // S(u, v) = G(a, b) for v, a, b by Newton from v. - let meet = |u: f64, v: f64| -> Option { - let mut v = v; - let (mut a, mut b) = gs.search_nearest_parameter(surf.subs(u, v), None, 100)?; - for _ in 0..60 { - let f = from_p3(surf.subs(u, v)) - from_p3(gs.subs(a, b)); - if !f.is_finite() { - return None; - } - if f.len() <= tolerance * 1e-3 { - return (-1e-9..=1.0 + 1e-9).contains(&v).then_some(v.clamp(0.0, 1.0)); - } - let (sv, ga, gb) = (surf.vder(u, v), gs.uder(a, b), gs.vder(a, b)); - let m = [[sv.x, -ga.x, -gb.x], [sv.y, -ga.y, -gb.y], [sv.z, -ga.z, -gb.z]]; - let [dv, da, db] = crate::polyhedron::solve3_pub(m, [-f.x, -f.y, -f.z])?; - // Keep each step within the strip's parameters. - let k = if dv.abs() > 0.1 { 0.1 / dv.abs() } else { 1.0 }; - v += dv * k; - a += da * k; - b += db * k; - } - None - }; - for m in [16usize, 32, 64] { - let mut pts = Vec::with_capacity(m + 1); - let mut vs = Vec::with_capacity(m + 1); - // From the middle out to both contacts, each search starting where the last ended. - let half = m / 2; - let mid_v = meet(0.5_f64.min(half as f64 / m as f64), v_start).ok_or_else(fail)?; - let mut found = vec![None; m + 1]; - if let Some(slot) = found.get_mut(half) { - *slot = Some(mid_v); - } - let mut last = mid_v; - for i in (0..half).rev() { - last = meet(i as f64 / m as f64, last).ok_or_else(fail)?; - if let Some(slot) = found.get_mut(i) { - *slot = Some(last); - } - } - last = mid_v; - for i in half + 1..=m { - last = meet(i as f64 / m as f64, last).ok_or_else(fail)?; - if let Some(slot) = found.get_mut(i) { - *slot = Some(last); - } - } - for (i, v) in found.iter().enumerate() { - let v = v.ok_or_else(fail)?; - vs.push(v); - pts.push(from_p3(surf.subs(i as f64 / m as f64, v))); - } - snap_to_seams(&mut pts, seams, tolerance); - let bs = crate::build::interpolate_cubic(&pts).ok_or_else(fail)?; - let fits = (0..m).all(|i| { - let q = p3(from_p3(bs.subs((i as f64 + 0.5) / m as f64))); - let hint = vs.get(i).map(|v| ((i as f64 + 0.5) / m as f64, *v)); - let on_g = gs.search_nearest_parameter(q, None, 100).is_some_and(|(a, b)| from_p3(gs.subs(a, b)).dist(from_p3(q)) <= tolerance); - let on_s = surf.search_nearest_parameter(q, hint, 100).is_some_and(|(u, v)| from_p3(surf.subs(u, v)).dist(from_p3(q)) <= tolerance); - on_g && on_s - }); - if fits { - let (Some(t1), Some(t2)) = (vs.first(), vs.last()) else { return Err(fail()) }; - // Both contacts are cut there: strictly inside the strip's own part. - let inside = |t: f64| t > fit.range.0 + 1e-6 && t < fit.range.1 - 1e-6; - if !(inside(*t1) && inside(*t2)) { - return Err(too_large("the blend is larger than the neighbouring faces (site 309)")); - } - return Ok((*t1, *t2, mt::Curve::BSplineCurve(bs))); - } - } - Err(fail()) -} - -/// The ends of an end curve (contact 1 to contact 2) that land within `tolerance` of an end of -/// their side's seam are that point exactly: the blend and the faces there meet at one vertex. -fn snap_to_seams(pts: &mut [Vec3], seams: [Option<&mt::Edge>; 2], tolerance: f64) { - let snap = |p: &mut Vec3, seam: Option<&mt::Edge>| { - for q in seam.into_iter().flat_map(|e| [from_p3(e.front().point()), from_p3(e.back().point())]) { - if p.dist(q) <= tolerance { - *p = q; - } - } - }; - if let Some(first) = pts.first_mut() { - snap(first, seams[0]); - } - if let Some(last) = pts.last_mut() { - snap(last, seams[1]); - } -} - -/// Where a blend strip run on past a chain end meets an end face that lies along the edge and is -/// tangent to one side there (a wall running out into the face, an earlier round that touches a -/// side along its contact): the end curve from contact 1 to contact 2, the same result as -/// [`end_cap`]. The strip touches the face along the tangent side's contact, so a Newton solve -/// for the crossing is singular there. -/// -/// Both ends of the curve are where a contact meets a seam, which is a plain crossing: the -/// tangent side's contact leaves the end face where it crosses the seam of that side with the -/// face, the other contact where it crosses the other side's seam. Between those stations each -/// cross-section crosses the face once, a simple root. Either station may lie before or after -/// the vertex's section: the curve runs inwards along the edge or out along the extension. -fn tangent_cap(fit: &Fit, g: &mt::Face, tangent_side: u8, seams: [Option<&mt::Edge>; 2], tolerance: f64) -> Result<(f64, f64, mt::Curve)> { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface, SearchNearestParameter}; - let fail = || unsupported("the blend's end on its end face"); - let surf = &fit.surface; - let (lo, hi) = (fit.range.0.min(fit.range.1), fit.range.0.max(fit.range.1)); - let (u_t, u_o, seam_t, seam_o) = if tangent_side == 1 { (0.0, 1.0, seams[0], seams[1]) } else { (1.0, 0.0, seams[1], seams[0]) }; - let (seam_t, seam_o) = (seam_t.ok_or_else(fail)?, seam_o.ok_or_else(fail)?); - // The station where the strip's contact `u` crosses `seam`. - let crossing = |u: f64, seam: &mt::Edge| -> Option { - let curve = seam.curve(); - let (a, b) = curve.range_tuple(); - let polyline: Vec = (0..=1024).map(|i| from_p3(curve.subs(a + (b - a) * f64::from(i) / 1024.0))).collect(); - let dist = |v: f64| -> f64 { - let x = from_p3(surf.subs(u, v)); - polyline.windows(2).map(|w| x.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min) - }; - let n = 400; - let step = (hi - lo) / f64::from(n); - let (mut best, mut best_d) = (lo, f64::INFINITY); - for i in 0..=n { - let v = lo + step * f64::from(i); - let d = dist(v); - if d < best_d { - (best, best_d) = (v, d); - } - } - let (mut x0, mut x1) = ((best - step).max(lo), (best + step).min(hi)); - let phi = 0.618_033_988_749_894_9; - for _ in 0..80 { - let (c, d) = (x1 - phi * (x1 - x0), x0 + phi * (x1 - x0)); - if dist(c) < dist(d) { - x1 = d; - } else { - x0 = c; - } - } - let v = 0.5 * (x0 + x1); - (dist(v) <= tolerance).then_some(v) - }; - let (rt, ra) = (crossing(u_t, seam_t), crossing(u_o, seam_o)); - let v_t = rt.ok_or_else(fail)?; - let v_a = ra.ok_or_else(|| too_large("the blend is larger than the neighbouring faces (site 387)"))?; - let inside = |t: f64| t > lo + 1e-6 && t < hi - 1e-6; - if !(inside(v_a) && inside(v_t)) || (v_a - v_t).abs() < 1e-9 { - return Err(too_large("the blend is larger than the neighbouring faces (site 390)")); - } - // How far the strip's point (u, v) is outside the end face (negative: inside the body). - let outside = |u: f64, v: f64| -> Option { - let x = from_p3(surf.subs(u, v)); - let (q, n, _) = project(g, x, None)?; - Some((x - q).dot(n)) - }; - // Root of `f` between `lo` and `hi`, `f(lo)` and `f(hi)` of different sign. - let bisect = |f: &dyn Fn(f64) -> Option, mut x0: f64, mut x1: f64| -> Option { - let f0 = f(x0)?; - for _ in 0..60 { - let mid = 0.5 * (x0 + x1); - let fm = f(mid)?; - if fm.abs() <= tolerance * 1e-6 { - return Some(mid); - } - if fm.is_sign_negative() == f0.is_sign_negative() { - x0 = mid; - } else { - x1 = mid; - } - } - Some(0.5 * (x0 + x1)) - }; - for m in [16usize, 32, 64, 128] { - // The curve at stations v_i from the crossing contact to the tangent one, as (u, v, point). - let mut stations: Vec<(f64, f64, Vec3)> = Vec::with_capacity(m + 1); - for i in 0..=m { - // Clustered at both ends, where the curve can meet a contact tangentially (a square - // root in the station) and a uniform spacing would fit it poorly. - let v = v_a + (v_t - v_a) * 0.5 * (1.0 - (std::f64::consts::PI * i as f64 / m as f64).cos()); - let u = if i == 0 { - u_o - } else if i == m { - u_t - } else { - let at_t = outside(u_t, v).ok_or_else(fail)?; - let at_o = outside(u_o, v).ok_or_else(fail)?; - // No crossing where the contacts are on one side: the curve is at the tangent one. - if at_t * at_o >= 0.0 { u_t } else { bisect(&|x| outside(x, v), u_o, u_t).ok_or_else(fail)? } - }; - stations.push((u, v, from_p3(surf.subs(u, v)))); - } - let mut pts: Vec = stations.iter().map(|x| x.2).collect(); - // The curve runs from contact 1 to contact 2. - if u_o == 1.0 { - pts.reverse(); - } - snap_to_seams(&mut pts, seams, tolerance); - let bs = crate::build::interpolate_cubic(&pts).ok_or_else(fail)?; - let gs = g.surface(); - let fits = stations.windows(2).enumerate().all(|(i, w)| { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return false }; - let t = if u_o == 1.0 { 1.0 - (i as f64 + 0.5) / m as f64 } else { (i as f64 + 0.5) / m as f64 }; - let q = p3(from_p3(bs.subs(t))); - let hint = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1)); - let on_g = gs.search_nearest_parameter(q, None, 100).is_some_and(|(x, y)| from_p3(gs.subs(x, y)).dist(from_p3(q)) <= tolerance); - let on_s = surf.search_nearest_parameter(q, Some(hint), 100).is_some_and(|(x, y)| from_p3(surf.subs(x, y)).dist(from_p3(q)) <= tolerance); - on_g && on_s - }); - if fits { - let (t1, t2) = if u_o == 0.0 { (v_a, v_t) } else { (v_t, v_a) }; - return Ok((t1, t2, mt::Curve::BSplineCurve(bs))); - } - } - Err(fail()) -} - -/// One cross-section of the blend: ball centre and its contacts with side 1 and side 2. -#[derive(Clone, Copy, Debug)] -struct Section { - c: Vec3, - q1: Vec3, - q2: Vec3, -} - -/// The third condition of a section's solve, in place of staying in the plane square to the edge: a contact held at a seam. -#[derive(Clone, Copy)] -enum Extra<'a> { - /// Side `k`'s contact lies in this plane (a point on it, its normal): beside a straight seam. - Plane(usize, Vec3, Vec3), - /// Side `k`'s contact lies on this curved seam (a lofted wall's seam between its two halves). - Seam(usize, &'a mt::Edge), -} - -/// The seam's point nearest `x` and its unit tangent there. -fn nearest_on_seam(seam: &mt::Edge, x: Vec3) -> Option<(Vec3, Vec3)> { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - let curve = seam.curve(); - let (lo, hi) = curve.range_tuple(); - let at = |t: f64| from_p3(curve.subs(t)); - // The nearest of a few samples starts the search: a long seam holds the point's neighbourhood - // far from its ends. - let hint = (0..=64).map(|i| lo + (hi - lo) * i as f64 / 64.0).min_by(|a, b| at(*a).dist(x).total_cmp(&at(*b).dist(x)))?; - let t = curve.search_nearest_parameter(p3(x), hint, 100)?.clamp(lo, hi); - let d = curve.der(t); - Some((at(t), Vec3::new(d.x, d.y, d.z).normalized()?)) -} - -/// Nearest point of a face's surface and the outward normal there. -pub(crate) fn project(f: &mt::Face, p: Vec3, hint: Option<(f64, f64)>) -> Option<(Vec3, Vec3, (f64, f64))> { - use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let s = f.oriented_surface(); - let uv = s.search_nearest_parameter(p3(p), hint, 100).or_else(|| s.search_nearest_parameter(p3(p), None, 100))?; - let q = from_p3(s.subs(uv.0, uv.1)); - let n = s.normal(uv.0, uv.1); - Some((q, Vec3::new(n.x, n.y, n.z).normalized()?, uv)) -} - -/// Whether `uv` lies within the parameters of the face's surface (unbounded directions pass). -pub(crate) fn in_range(f: &mt::Face, uv: (f64, f64)) -> bool { - use mt::ParametricSurface; - use std::ops::Bound; - let inside = |range: (Bound, Bound), x: f64| { - let slack = |a: f64, b: f64| (b - a).abs() * 1e-6 + 1e-9; - match range { - (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => x >= a - slack(a, b) && x <= b + slack(a, b), - (Bound::Included(a) | Bound::Excluded(a), Bound::Unbounded) => x >= a - 1e-9, - (Bound::Unbounded, Bound::Included(b) | Bound::Excluded(b)) => x <= b + 1e-9, - (Bound::Unbounded, Bound::Unbounded) => true, - } - }; - let (ru, rv) = f.oriented_surface().parameter_range(); - uv.0.is_finite() && uv.1.is_finite() && inside(ru, uv.0) && inside(rv, uv.1) -} - -/// Solve for the ball touching both sides near `p`. `extra` adds a third condition (a plane the -/// side-k contact must lie in, or a curved seam it must lie on); without it the centre stays in the -/// plane through `p` square to `t`. `sigma` is +1 when the ball sits outside the material (concave edge), −1 inside. -/// `cusp` is ±1 at a knife edge (the faces' normals opposite: both leave the edge the same way, -/// along `cusp · n1 × t`, and the ball lies where the cusp has opened to its width), else 0. -#[allow(clippy::too_many_arguments)] -fn solve(f1: &[&mt::Face], f2: &[&mt::Face], p: Vec3, t: Vec3, r: f64, sigma: f64, cusp: f64, extra: Option>, tol: f64) -> Option
{ - solve_from(f1, f2, p, t, r, sigma, cusp, extra, tol, None) -} - -/// [`solve`], started from the centre `start` when given (the corner builder's balls at a knife -/// edge start beside the last one). -#[allow(clippy::too_many_arguments)] -fn solve_from( - f1: &[&mt::Face], - f2: &[&mt::Face], - p: Vec3, - t: Vec3, - r: f64, - sigma: f64, - cusp: f64, - extra: Option>, - tol: f64, - start: Option, -) -> Option
{ - // The nearest face of a side (several faces on one smooth surface group). Each face's - // search starts from its last answer: the centre moves little between iterations. An - // answer outside the surface's parameters, or farther than that last point (the search - // ran away or settled on the far side), is searched again cold. - let last = std::cell::RefCell::new(HashMap::::new()); - let near = |fs: &[&mt::Face], c: Vec3| -> Option<(Vec3, Vec3)> { - fs.iter() - .filter_map(|f| { - let prev = last.borrow().get(&f.id()).copied(); - let warm = - prev.and_then(|(uv, q)| project(f, c, Some(uv)).filter(|(x, _, uv)| in_range(f, *uv) && x.dist(c) <= q.dist(c) + tol * 1e-3)); - let (q, n, uv) = match warm { - Some(x) => x, - None => project(f, c, None)?, - }; - last.borrow_mut().insert(f.id(), (uv, q)); - Some((q, n)) - }) - .min_by(|a, b| a.0.dist(c).total_cmp(&b.0.dist(c))) - }; - let (q1, n1) = near(f1, p)?; - let (q2, n2) = near(f2, p)?; - let _ = (q1, q2); - let den = 1.0 + n1.dot(n2); - let mut c = if let Some(c) = start { - c - } else if cusp != 0.0 && den.abs() < KNIFE { - // The normals are (nearly) opposite: `(n1 + n2) / den` has no direction. The centre is r - // inside face 1 and slides along it, away from the edge, until it is r from face 2 too. - let w = n1.cross(t).normalized()? * cusp; - let centre = |s: f64| -> Option { - let (qa, na) = near(f1, p + w * s)?; - Some(qa + na * (sigma * r)) - }; - let gap = |s: f64| -> Option { - let c = centre(s)?; - let (q2, n2) = near(f2, c)?; - Some((c - q2).dot(n2) - sigma * r) - }; - let (mut lo, mut g_lo) = (0.0, gap(0.0)?); - let mut hi = None; - let mut s = r * 0.05; - for _ in 0..KNIFE_STEPS { - let Some(g) = gap(s) else { break }; - if g == 0.0 || g.is_sign_negative() != g_lo.is_sign_negative() { - hi = Some(s); - break; - } - (lo, g_lo) = (s, g); - s *= 1.6; - } - let mut hi = hi?; - for _ in 0..60 { - let mid = 0.5 * (lo + hi); - match gap(mid) { - Some(g) if g.is_sign_negative() == g_lo.is_sign_negative() => lo = mid, - Some(_) => hi = mid, - None => break, - } - } - centre(0.5 * (lo + hi))? - } else { - if den.abs() < 1e-9 { - return None; - } - p + (n1 + n2) * (sigma * r / den) - }; - for _ in 0..60 { - let (q1, n1) = near(f1, c)?; - let (q2, n2) = near(f2, c)?; - let g1 = (c - q1).dot(n1) - sigma * r; - let g2 = (c - q2).dot(n2) - sigma * r; - // Third row: stay in the section plane, or put a contact on the seam plane. - let (row3, g3) = match extra { - None => (t, (c - p).dot(t)), - Some(Extra::Plane(k, o, m)) => { - let q = if k == 1 { q1 } else { q2 }; - (m, (q - o).dot(m)) - } - Some(Extra::Seam(k, seam)) => { - // The plane through the seam's nearest point to the contact, square to that side's - // surface, taken afresh each step: it holds the contact on the curved seam as the - // steps close in. - let (q, n) = if k == 1 { (q1, n1) } else { (q2, n2) }; - let (on_seam, d) = nearest_on_seam(seam, q)?; - let m = d.cross(n).normalized()?; - (m, (q - on_seam).dot(m)) - } - }; - let a = [[n1.x, n1.y, n1.z], [n2.x, n2.y, n2.z], [row3.x, row3.y, row3.z]]; - let b = [-g1, -g2, -g3]; - let x = crate::polyhedron::solve3_pub(a, b)?; - let dc = Vec3::new(x[0], x[1], x[2]); - c += dc; - if dc.len() < tol * 1e-3 && g1.abs() < tol && g2.abs() < tol && g3.abs() < tol { - let (q1, _) = near(f1, c)?; - let (q2, _) = near(f2, c)?; - return Some(Section { c, q1, q2 }); - } - } - None -} - -/// Contacts of a convex chamfer in a cross-section normal to a straight edge. The caller -/// checks that sweeping the section stays on both supports within the fitting tolerance. -pub(crate) fn straight_chamfer_contacts(f1: &mt::Face, f2: &mt::Face, p: Vec3, d: Vec3, r: f64, tolerance: f64) -> Option<(Vec3, Vec3)> { - let section = solve(&[f1], &[f2], p, d, r, -1.0, 0.0, None, tolerance)?; - Some((section.q1, section.q2)) -} - -/// The section whose two contacts are `chord` apart: the ball's radius is `chord / (2 sin(ψ/2))` -/// for the `ψ` between the two outward normals where it touches, `|q1 − q2| = 2 r sin(ψ/2)`. The -/// normals turn as the ball grows against curved faces, so the width is measured on the solved -/// section and the radius corrected until it matches (the width is proportional to the radius, -/// so the corrections converge quickly). The normals at `p` give the first radius, exact where -/// both faces are planar; `None` where the faces meet too nearly tangentially to span a chord. -#[allow(clippy::too_many_arguments)] -fn solve_chord( - f1: &[&mt::Face], - f2: &[&mt::Face], - p: Vec3, - t: Vec3, - chord: f64, - sigma: f64, - cusp: f64, - extra: Option>, - tol: f64, -) -> Option<(Section, f64)> { - let normal = |fs: &[&mt::Face]| fs.iter().filter_map(|f| project(f, p, None)).min_by(|a, b| a.0.dist(p).total_cmp(&b.0.dist(p))).map(|x| x.1); - let (n1, n2) = (normal(f1)?, normal(f2)?); - let half = (n1.dot(n2).clamp(-1.0, 1.0).acos() / 2.0).sin(); - if !(half > 1e-3) { - return None; - } - let mut r = chord / (2.0 * half); - for _ in 0..CHORD_STEPS { - if !(r.is_finite() && r > 0.0 && r < 1e9) { - return None; - } - let s = solve(f1, f2, p, t, r, sigma, cusp, extra, tol)?; - let width = s.q1.dist(s.q2); - if !width.is_finite() || width <= 0.0 { - return None; - } - if (width - chord).abs() <= (chord * 1e-9).max(tol * 0.5) { - return Some((s, r)); - } - r *= chord / width; - } - None -} - -/// The rolling ball at one station, sized by the blend's law. -struct Sizer<'a> { - size: Size<'a>, - /// The tolerance the section's equations are solved at. - tol: f64, -} - -impl Sizer<'_> { - /// The section at `p` (tangent `t`, the size law's parameter `s`) holding the third - /// condition `extra` when given, with the radius it was solved at. - #[allow(clippy::too_many_arguments)] - fn section( - &self, - f1: &[&mt::Face], - f2: &[&mt::Face], - p: Vec3, - t: Vec3, - s: f64, - sigma: f64, - cusp: f64, - extra: Option>, - ) -> Option<(Section, f64)> { - match self.size { - Size::Constant(r) => solve(f1, f2, p, t, r, sigma, cusp, extra, self.tol).map(|x| (x, r)), - Size::Chord(chord) => solve_chord(f1, f2, p, t, chord, sigma, cusp, extra, self.tol), - Size::Law(law) => { - let r = law_beyond(law, s)?; - if !(r.is_finite() && (0.0..1e6).contains(&r)) { - return None; - } - solve(f1, f2, p, t, r, sigma, cusp, extra, self.tol).map(|x| (x, r)) - } - } - } - - /// What a station the ball does not fit at is refused with: a chord too large is about the - /// size asked for, anything else about where the ball is. - fn refusal(&self) -> KernelError { - match self.size { - Size::Chord(_) => too_large("the blend is larger than the neighbouring faces (site 704)"), - _ => unsupported("the ball doesn't fit along the edge"), - } - } -} - -/// Whether the strip's curvature jumps where two runs of sections meet (each three sections from -/// the joint outward, the joint's first): for the centres or either contact, the difference of -/// the circles through them would move the middle section by more than a tenth of `tolerance`. -fn bends(a: [&Section; 3], b: [&Section; 3], tolerance: f64) -> bool { - let curvature = |p: [Vec3; 3]| { - let (x, y, z) = (p[1] - p[0], p[2] - p[1], p[2] - p[0]); - let d = x.len() * y.len() * z.len(); - if d > 1e-300 { 2.0 * x.cross(y).len() / d } else { 0.0 } - }; - let h = a[0].c.dist(a[1].c); - [|s: &Section| s.c, |s: &Section| s.q1, |s: &Section| s.q2] - .iter() - .any(|f| (curvature(a.map(f)) - curvature(b.map(f))).abs() * h * h > tolerance * 0.1) -} - -/// Whether the section is a point: a blend whose radius has run to zero, closing to the edge's -/// end point there. -fn closed_section(s: &Section) -> bool { - s.c.dist(s.q1) <= CLOSED && s.c.dist(s.q2) <= CLOSED -} - -/// Homogeneous control points of the circular (or straight) cross-section from q1 to q2. -fn section_controls(s: &Section, round: bool) -> Option<[mt::Vector4; 3]> { - let h = |p: Vec3, w: f64| mt::Vector4::new(p.x * w, p.y * w, p.z * w, w); - if !round { - let m = (s.q1 + s.q2) * 0.5; - return Some([h(s.q1, 1.0), h(m, 1.0), h(s.q2, 1.0)]); - } - if closed_section(s) { - // A closed section: the arc has shrunk to the edge's end point, all three controls - // there, so the fitted strips of the neighbouring faces meet at that vertex. - return Some([h(s.c, 1.0), h(s.c, 1.0), h(s.c, 1.0)]); - } - let (a, b) = (s.q1 - s.c, s.q2 - s.c); - let theta = a.normalized()?.dot(b.normalized()?).clamp(-1.0, 1.0).acos(); - if !(theta > 1e-6 && theta < std::f64::consts::PI - 1e-6) { - return None; - } - let half = (theta / 2.0).cos(); - let bis = (a + b).normalized()?; - let m = s.c + bis * (a.len() / half); - Some([h(s.q1, 1.0), h(m, half), h(s.q2, 1.0)]) -} - -/// Where to start the ball at a knife edge through `p` (direction `t`, the sides running on from -/// it along `into`): the first point along them, from the edge, where they are a diameter -/// apart, midway. -fn knife_start(o1: &[&mt::Face], o2: &[&mt::Face], p: Vec3, t: Vec3, into: Vec3, r: f64) -> Option { - let w = (into - t * into.dot(t)).normalized()?; - (1..=256).find_map(|k| { - let x = p + w * (r * k as f64 / 8.0); - let a = o1.iter().filter_map(|f| project(f, x, None)).min_by(|a, b| a.0.dist(x).total_cmp(&b.0.dist(x)))?; - let b = o2.iter().filter_map(|f| project(f, x, None)).min_by(|a, b| a.0.dist(x).total_cmp(&b.0.dist(x)))?; - let c = (a.0 + b.0) * 0.5; - (a.0.dist(b.0) >= 2.0 * r).then(|| c - t * (c - p).dot(t)) - }) -} - -/// Whether two faces meeting at no angle at `pm` (the first's outward normal `n1`, running on -/// from the edge along `into`) hold the material between them: a little way in, the second is -/// behind the first. -fn knife_convex(f1: &mt::Face, f2: &mt::Face, pm: Vec3, into: Vec3, r: f64) -> Option { - let x = pm + into * r; - let (a, b) = (project(f1, x, None)?, project(f2, x, None)?); - Some((b.0 - a.0).dot(a.1) < 0.0) -} - -/// The nearest point of a face's (oriented) surface to `x`, its outward normal and parameters; -/// `last`: where the last search on it ended (the points asked about come in small steps). -fn nearest_on(surface: &mt::Surface, last: &std::cell::Cell>, x: Vec3) -> Option<(Vec3, Vec3, (f64, f64))> { - use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - // The nearest of the search from the last answer, a fresh one (the first time, also from - // a grid over the surface's parameters: a fresh search on a conic can settle on its far - // side) and either kept within the parameters (past them a conic runs on round). - let (ru, rv) = surface.try_range_tuple(); - let ((u0, u1), (v0, v1)) = (ru.unwrap_or((f64::NEG_INFINITY, f64::INFINITY)), rv.unwrap_or((f64::NEG_INFINITY, f64::INFINITY))); - let inside = |uv: (f64, f64)| uv.0 >= u0 - 1e-9 && uv.0 <= u1 + 1e-9 && uv.1 >= v0 - 1e-9 && uv.1 <= v1 + 1e-9; - let warm = last.get().and_then(|hint| surface.search_nearest_parameter(p3(x), Some(hint), 20)); - let mut found: Vec<(f64, f64)> = warm.into_iter().collect(); - if !warm.is_some_and(inside) { - found.extend(surface.search_nearest_parameter(p3(x), None, 100)); - } - if last.get().is_none() && [u0, u1, v0, v1].iter().all(|x| x.is_finite()) { - for i in 0..5 { - for j in 0..5 { - let hint = (u0 + (u1 - u0) * (i as f64 + 0.5) / 5.0, v0 + (v1 - v0) * (j as f64 + 0.5) / 5.0); - found.extend(surface.search_nearest_parameter(p3(x), Some(hint), 50)); - } - } - } - let clamped: Vec<(f64, f64)> = found.iter().map(|(u, v)| (u.clamp(u0, u1), v.clamp(v0, v1))).collect(); - found.extend(clamped); - let d = |uv: &(f64, f64)| from_p3(surface.subs(uv.0, uv.1)).dist(x); - let uv = found.into_iter().filter(|uv| d(uv).is_finite()).min_by(|a, b| d(a).total_cmp(&d(b)))?; - last.set(Some(uv)); - let n = surface.normal(uv.0, uv.1); - Some((from_p3(surface.subs(uv.0, uv.1)), Vec3::new(n.x, n.y, n.z).normalized()?, uv)) -} - -/// The strip with parameters in proportion to its lengths across and along (the same surface). -/// The mesher triangulates a face in its parameters: on a unit square for a strip a few -/// millimetres wide and tens long, the points of a slanted end fan out into triangles so long -/// along the curve that they turn over. -fn in_proportion(surface: &mt::Surface) -> Result { - use mt::ParametricSurface; - let fail = || KernelError::Failed("curve blend: strip parameters".into()); - let mt::Surface::NurbsSurface(ns) = surface else { return Err(fail()) }; - let length = |at: &dyn Fn(f64) -> Vec3| (0..32).map(|i| at(i as f64 / 32.0).dist(at((i + 1) as f64 / 32.0))).sum::(); - let across = length(&|u| from_p3(surface.subs(u, 0.5))); - let along = length(&|v| from_p3(surface.subs(0.5, v))); - if !(across.is_finite() && along.is_finite() && across > 1e-9 && along > 1e-9) { - return Err(fail()); - } - let bs = ns.non_rationalized(); - let (mut uk, mut vk) = bs.knot_vecs().clone(); - uk.transform(across, 0.0); - vk.transform(along, 0.0); - let bs = mt::BSplineSurface::try_new((uk, vk), bs.control_points().clone()).map_err(|_| fail())?; - Ok(mt::Surface::NurbsSurface(mt::NurbsSurface::new(bs))) -} - -/// A chain edge the ball turns about instead of rolling along: an arc of the blend's radius on a -/// planar side (`side`), curving round the ball (a rounded corner rounded again). The ball's -/// centre stays at `c`, it touches the planar side only at the arc's centre `o`, and the blend -/// there is a piece of sphere (of cone, for a chamfer) about the axis through `c` along `axis`. -#[derive(Clone, Copy, Debug)] -struct Pivot { - c: Vec3, - o: Vec3, - axis: Vec3, - side: usize, -} - -/// The circle an edge lies on (centre, radius, axis), if it is an arc of one within `tol`. -pub(crate) fn circle_of(e: &mt::Edge, tol: f64) -> Option<(Vec3, f64, Vec3)> { - use mt::{BoundedCurve, ParametricCurve}; - let curve = e.oriented_curve(); - let (t0, t1) = curve.range_tuple(); - let at = |f: f64| from_p3(curve.subs(t0 + (t1 - t0) * f)); - let (a, u, v) = (at(0.0), at(0.5) - at(0.0), at(1.0) - at(0.0)); - let w = u.cross(v); - if w.len2() < 1e-24 { - return None; - } - let o = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2())); - let (rho, axis) = (o.dist(a), w.normalized()?); - (0..=8).map(|i| at(i as f64 / 8.0)).all(|p| (p.dist(o) - rho).abs() <= tol && (p - o).dot(axis).abs() <= tol).then_some((o, rho, axis)) -} - -/// The surface the section (homogeneous controls from contact 1 to contact 2) sweeps turning by -/// `angle` about the axis through `c` along the unit `axis`: rational quadratic arcs in v, a -/// quarter turn at most each, so it is exact. -fn revolve(ctrl: [mt::Vector4; 3], c: Vec3, axis: Vec3, angle: f64) -> Option { - let pieces = ((angle.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize).clamp(1, 8); - let step = angle / pieces as f64; - let half = (step / 2.0).cos(); - if !(half.is_finite() && half > 1e-6) { - return None; - } - let rot = |x: Vec3, phi: f64| { - let (s, co) = phi.sin_cos(); - x * co + axis.cross(x) * s + axis * (axis.dot(x) * (1.0 - co)) - }; - let h = |p: Vec3, w: f64| mt::Vector4::new(p.x * w, p.y * w, p.z * w, w); - let mut rows = Vec::with_capacity(3); - for q in ctrl { - if !(q.w.is_finite() && q.w > 1e-12) { - return None; - } - let x = Vec3::new(q.x / q.w, q.y / q.w, q.z / q.w) - c; - let along = axis * axis.dot(x); - let mut row = vec![h(c + x, q.w)]; - for i in 0..pieces { - let a0 = step * i as f64; - row.push(h(c + along + rot(x - along, a0 + step / 2.0) * (1.0 / half), q.w * half)); - row.push(h(c + rot(x, a0 + step), q.w)); - } - rows.push(row); - } - let mut knots = vec![0.0; 3]; - for i in 1..pieces { - let k = i as f64 / pieces as f64; - knots.extend([k, k]); - } - knots.extend([1.0; 3]); - let bs = mt::BSplineSurface::try_new((mt::KnotVec::bezier_knot(2), mt::KnotVec::from(knots)), rows).ok()?; - Some(mt::Surface::NurbsSurface(mt::NurbsSurface::new(bs))) -} - -/// Whether the edge is straight: a line, or a curve on the segment between its ends within -/// `tol` (an earlier blend's contact along a straight edge is a fitted curve). -pub(crate) fn straight(e: &mt::Edge, tol: f64) -> bool { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - if matches!(c, mt::Curve::Line(_)) { - return true; - } - let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point())); - let (t0, t1) = c.range_tuple(); - a.dist(b) > tol && (0..=16).all(|i| from_p3(c.subs(t0 + (t1 - t0) * i as f64 / 16.0)).dist_to_segment(a, b) <= tol) -} - -/// Consuming both seams of a side can leave its old boundary and a fitted contact on the -/// same curve (#1113). They are distinct topological edges but enclose no usable face. Keep -/// genuine two-edge faces (a lens or lune); refuse only coincident traces, in both directions -/// since the curves need not have the same parameterisation. -fn collapsed_boundary(edges: &[mt::Edge], tolerance: f64) -> bool { - use mt::{BoundedCurve, ParametricCurve}; - let [a, b] = edges else { return false }; - [(a, b), (b, a)].into_iter().all(|(edge, other)| { - let curve = edge.curve(); - let (lo, hi) = curve.range_tuple(); - (0..=16).all(|k| { - let p = from_p3(curve.subs(lo + (hi - lo) * f64::from(k) / 16.0)); - crate::blend::on_edge(other, p, tolerance).is_some() - }) - }) -} - -/// A curved seam (an arc of an end face) shortened to the blend's contacts: the part of its -/// curve between the new ends `a` and `b` (`None` keeps that end), which must lie on it, in -/// order, short of each other. -pub(crate) fn trim_curved_seam(seam: &mt::Edge, a: Option, b: Option, size: f64) -> Result { - // A closed seam (a full circle starting and ending at one vertex) has no "between": which - // end a contact replaces, and which way round the kept piece runs, are both ambiguous. - if seam.front() == seam.back() { - return Err(unsupported("a closed curved edge where the blend ends")); - } - use mt::{BoundedCurve, Cut, SearchNearestParameter}; - let mut curve = seam.curve(); - let (lo, hi) = curve.range_tuple(); - let at = |v: &Option, end: f64| -> Result { - let Some(v) = v else { return Ok(end) }; - // Start from the nearest of a few samples: from the far end of a long arc - // the search can settle on the opposite side of the circle. - let q = from_p3(v.point()); - let hint = (0..=32) - .map(|i| lo + (hi - lo) * i as f64 / 32.0) - .min_by(|x, y| { - let d = |t: f64| from_p3(mt::ParametricCurve::subs(&curve, t)).dist(q); - d(*x).total_cmp(&d(*y)) - }) - .unwrap_or(end); - let t = curve.search_nearest_parameter(v.point(), hint, 100).ok_or_else(|| unsupported("the blend is larger than the neighbouring faces"))?; - if !(t.is_finite() && from_p3(mt::ParametricCurve::subs(&curve, t)).dist(from_p3(v.point())) <= size * 1e-5) { - return Err(too_large("the blend is larger than the neighbouring faces (site 938)")); - } - Ok(t) - }; - let (ta, tb) = (at(&a, lo)?, at(&b, hi)?); - let margin = (hi - lo) * 1e-9; - if ta < lo - margin || tb > hi + margin || tb - ta < (hi - lo) * 1e-6 { - return Err(too_large("the blend is larger than the neighbouring faces (site 945)")); - } - if tb < hi { - let _ = curve.cut(tb); - } - let piece = if ta > lo { curve.cut(ta) } else { curve }; - let a = a.unwrap_or_else(|| seam.front().clone()); - let b = b.unwrap_or_else(|| seam.back().clone()); - mt::Edge::try_new(&a, &b, piece).map_err(|e| KernelError::Failed(format!("curve blend: seam: {e}"))) -} - -/// A monotone curve's parameter read off a table of its values at uniform parameters (`None` for -/// an empty table): the fraction of the way through it. -fn sampled(table: &[f64], along: f64) -> Option { - if table.len() < 2 || !along.is_finite() { - return None; - } - let x = along.clamp(0.0, 1.0) * (table.len() - 1) as f64; - let i = (x.floor() as usize).min(table.len() - 2); - let f = x - i as f64; - Some(table.get(i)? * (1.0 - f) + table.get(i + 1)? * f) -} - -/// The arc length of `edge` from its front to its back at each of `LENGTH_STEPS + 1` uniform -/// parameters, accumulated. `None` for an edge that has no length (or runs back over itself). -fn edge_lengths(edge: &mt::Edge) -> Option> { - use mt::{BoundedCurve, ParametricCurve}; - let c = edge.oriented_curve(); - let (a, b) = c.range_tuple(); - let mut last = from_p3(c.subs(a)); - let mut total = 0.0; - let mut out = Vec::with_capacity(LENGTH_STEPS + 1); - out.push(0.0); - for i in 1..=LENGTH_STEPS { - let p = from_p3(c.subs(a + (b - a) * i as f64 / LENGTH_STEPS as f64)); - total += last.dist(p); - last = p; - out.push(total); - } - (total.is_finite() && total > 1e-12).then_some(out) -} - -/// The radius a law gives at the chain fraction `s`, continued past 0 and 1 at the law's own end -/// slope. The ball runs on past a chain end (to be cut back there by its end face), and holding -/// the end radius would kink the strip exactly where the edge begins: a kink a cubic fit spreads -/// back over the whole blend. Never below a fifth of the end radius, so that a law running down -/// steeply still has a ball to run on with. -fn law_beyond(law: &RadiusSpline, s: f64) -> Option { - if (0.0..=1.0).contains(&s) { - return Some(law.eval(s)); - } - let (end, step) = if s < 0.0 { (0.0, s) } else { (1.0, s - 1.0) }; - let h = 1e-3; - let slope = (law.eval(end + h) - law.eval(end)) / h; - let r = law.eval(end); - let r = (r + slope * step).max(0.2 * r); - (r.is_finite() && r > 0.0).then_some(r) -} - -/// Blend the closed chain of edges (ids in any order) with radius `r`; with what it built from -/// `solid` (each blend face in place of its chain edge). -pub(crate) fn curve_blend(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Result<(Solid, Rebuild)> { - curve_blend_with_limit(solid, ids, size, r, round, MAX_SAMPLES) -} - -/// [`curve_blend`] with the blend `chord` wide across, from contact to contact, at every station. -pub(crate) fn curve_blend_chord(solid: &Solid, ids: &[mt::EdgeID], size: f64, chord: f64, round: bool) -> Result<(Solid, Rebuild)> { - curve_blend_sized(solid, ids, size, Size::Chord(chord), round, MAX_SAMPLES) -} - -/// [`curve_blend`] with the radius following `law` along the chain (its positions the fraction of -/// the chain's arc length, from the front of its first edge to the back of its last). -pub(crate) fn curve_blend_law(solid: &Solid, ids: &[mt::EdgeID], size: f64, law: &RadiusSpline, round: bool) -> Result<(Solid, Rebuild)> { - curve_blend_sized(solid, ids, size, Size::Law(law), round, MAX_SAMPLES) -} - -fn curve_blend_with_limit(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool, max_samples: usize) -> Result<(Solid, Rebuild)> { - curve_blend_sized(solid, ids, size, Size::Constant(r), round, max_samples) -} - -/// Blend the chain of edges (ids in any order) sized by `size`: one radius, a chord width, or a -/// radius law. With what it built from `solid` (each blend face in place of its chain edge). -fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Size<'_>, round: bool, max_samples: usize) -> Result<(Solid, Rebuild)> { - if !(size.is_finite() && size > 0.0) { - return Err(KernelError::Invalid("curve blend size and radius must be finite and positive".into())); - } - match size_law { - Size::Constant(r) | Size::Chord(r) => { - if !(r.is_finite() && r > 1e-6 && r < 1e6) { - return Err(KernelError::Invalid("curve blend size and radius must be finite and positive".into())); - } - } - Size::Law(law) => { - let knots = law.knots.len() == law.radii.len() + law.degree + 1; - if law.radii.len() < 2 || !knots || law.radii.iter().any(|r| !(r.is_finite() && (0.0..1e6).contains(r))) { - return Err(KernelError::Invalid("a radius law along the edge must be finite and non-negative".into())); - } - // A law that runs to zero closes the blend at the edge's end point. The fitted strip - // pinches to a point there, and the sections' own interpolation cannot follow the last - // span of it: the straight-edge fillet, which builds that closure exactly, is the way. - if law.eval(0.0) <= CLOSED || law.eval(1.0) <= CLOSED { - return Err(unsupported("a radius law that runs to zero along a curved edge")); - } - } - } - if !(4..=MAX_SAMPLES).contains(&max_samples) { - return Err(KernelError::Invalid("curve blend section limit is outside the supported range".into())); - } - let tol = (size * 1e-7).max(1e-9); - let shells = solid.boundaries(); - let (si, shell) = shells - .iter() - .enumerate() - .find(|(_, sh)| sh.edge_iter().any(|e| ids.contains(&e.id()))) - .ok_or_else(|| KernelError::Failed("edge not found".into()))?; - let faces: Vec = shell.face_iter().cloned().collect(); - // Order the chain: edges as stored (absolute direction), each starting where the last ended. - let mut chain: Vec = Vec::new(); - let all: Vec = { - let mut seen = std::collections::HashSet::new(); - shell.edge_iter().filter(|e| ids.contains(&e.id()) && seen.insert(e.id())).map(|e| e.absolute_clone()).collect() - }; - // An open chain starts at a vertex only one of its edges touches. - let uses = |v: &mt::Vertex| all.iter().filter(|e| e.front() == v || e.back() == v).count(); - let first = match all.iter().find_map(|e| { - if uses(e.front()) == 1 { - Some(e.clone()) - } else if uses(e.back()) == 1 { - Some(e.inverse()) - } else { - None - } - }) { - Some(e) => e, - None => all.first().cloned().ok_or_else(|| KernelError::Failed("no edges".into()))?, - }; - chain.push(first.clone()); - while chain.len() < all.len() { - let end = chain.last().map(|e| e.back().clone()).ok_or_else(|| KernelError::Failed("chain".into()))?; - let next = all - .iter() - .find(|e| !chain.iter().any(|c| c.id() == e.id()) && (*e.front() == end || *e.back() == end)) - .ok_or_else(|| unsupported("the edges don't form one chain"))?; - chain.push(if *next.front() == end { next.clone() } else { next.inverse() }); - } - let closed = chain.first().map(|e| e.front().clone()) == chain.last().map(|e| e.back().clone()); - let n = chain.len(); - // The chain's vertices (n for a closed chain, n + 1 for an open one). - let mut verts: Vec = chain.iter().map(|e| e.front().clone()).collect(); - if !closed && let Some(e) = chain.last() { - verts.push(e.back().clone()); - } - let nv = verts.len(); - // Faces of each edge, split into the two sides. - let faces_of = |e: &mt::Edge| -> Vec { - (0..faces.len()).filter(|i| faces.get(*i).is_some_and(|f| f.edge_iter().any(|x| x.id() == e.id()))).collect() - }; - let mut side1: Vec = Vec::new(); - let mut side2: Vec = Vec::new(); - for (k, e) in chain.iter().enumerate() { - let fs = faces_of(e); - let [a, b] = fs[..] else { return Err(unsupported("an edge without two faces")) }; - if k == 0 { - side1.push(a); - side2.push(b); - continue; - } - // The side-1 face of this edge is the one whose normal matches side 1 at the joint. - let p = from_p3(e.front().point()); - let nrm = |fi: usize| faces.get(fi).and_then(|f| project(f, p, None)).map(|x| x.1); - let prev1 = side1.last().copied().and_then(nrm); - let (na, nb) = (nrm(a), nrm(b)); - let a_is_1 = match (prev1, na, nb) { - (Some(x), Some(y), Some(z)) => x.dot(y) >= x.dot(z), - _ => return Err(KernelError::Failed("blend: normals".into())), - }; - if a_is_1 { - side1.push(a); - side2.push(b); - } else { - side1.push(b); - side2.push(a); - } - } - let s1: Vec<&mt::Face> = side1.iter().filter_map(|i| faces.get(*i)).collect(); - let s2: Vec<&mt::Face> = side2.iter().filter_map(|i| faces.get(*i)).collect(); - // The faces the ball may touch near edges `ks` of the chain: their own, on each side. (The - // surface of another face of a side, such as a wall's plane past the bend it runs into, - // may pass nearer than the face the ball actually rolls on.) - let edge_sides = |ks: &[usize]| -> (Vec<&mt::Face>, Vec<&mt::Face>) { - let pick = |side: &[usize]| { - let mut out: Vec = Vec::new(); - for k in ks { - if let Some(fi) = side.get(*k) - && !out.contains(fi) - { - out.push(*fi); - } - } - out.iter().filter_map(|i| faces.get(*i)).collect::>() - }; - (pick(&side1), pick(&side2)) - }; - // The chain's edges at vertex k. - let vertex_edges = |k: usize| -> Vec { - if closed { - vec![(k + n - 1) % n, k % n] - } else if k == 0 { - vec![0] - } else if k >= n { - vec![n - 1] - } else { - vec![k - 1, k] - } - }; - // Convex or concave, from the first edge as its side-1 face runs it. - let e0 = chain.first().ok_or_else(|| KernelError::Failed("chain".into()))?; - let f1 = s1.first().ok_or_else(|| KernelError::Failed("side".into()))?; - let in_f1 = f1.boundary_iters().into_iter().flatten().find(|e| e.id() == e0.id()).ok_or_else(|| KernelError::Failed("edge use".into()))?; - let (pm, t1) = { - use mt::{BoundedCurve, ParametricCurve}; - let c = in_f1.oriented_curve(); - let (a, b) = c.range_tuple(); - let m = (a + b) * 0.5; - let d = c.der(m); - (from_p3(c.subs(m)), Vec3::new(d.x, d.y, d.z).normalized().ok_or_else(|| KernelError::Failed("tangent".into()))?) - }; - let (n1, n2) = match (project(f1, pm, None), s2.first().and_then(|f| project(f, pm, None))) { - (Some(x), Some(y)) => (x.1, y.1), - _ => return Err(KernelError::Failed("blend: normals".into())), - }; - // A knife edge (opposite normals): both faces leave the edge along `w`; the second one lies - // below the first (against its outward normal) when the cusp is material, above when it is - // a gap. The cross product of the normals, which tells the other edges apart, is zero here. - let knife = 1.0 + n1.dot(n2) < KNIFE; - // The one radius, where the size is one radius (a chord or a law has none). - let fixed = match size_law { - Size::Constant(r) => Some(r), - _ => None, - }; - // The blend's scale where the size itself is not what matters (the knife edge's probe): the - // radius asked for, or the law's middle value. - let scale = match size_law { - Size::Constant(r) | Size::Chord(r) => r, - Size::Law(law) => law.eval(0.5).max(1e-6), - }; - let (convex, cusp) = if knife { - let w = n1.cross(t1).normalized().ok_or_else(|| KernelError::Failed("blend: cusp direction".into()))?; - // Second order: from the point of face 1 a little way along `w`, face 2's nearest point. - let probe = project(f1, pm + w * scale, None) - .and_then(|(qa, na, _)| s2.first().and_then(|f| project(f, qa, None)).map(|(qb, _, _)| (qb - qa).dot(na))) - .filter(|depth| depth.abs() > size * 1e-9) - .ok_or_else(|| unsupported("a knife edge whose faces lie flat on each other"))?; - // Whether the chain runs along the edge as face 1 uses it decides which way `w` points - // from the chain's tangent. - (probe < 0.0, if in_f1.front() == e0.front() { 1.0 } else { -1.0 }) - } else { - (t1.dot(n1.cross(n2)) > 0.0, 0.0) - }; - let sigma = if convex { -1.0 } else { 1.0 }; - if n1.dot(n2) > 1.0 - 1e-6 { - return Err(unsupported("blending a smooth edge")); - } - // The chain's arc length, in fractions of its whole, at each station: where the size is one - // radius it is not read, but the sections take their parameter from it all the same. - let tables: Vec> = chain.iter().map(|e| edge_lengths(e).unwrap_or_else(|| vec![0.0; LENGTH_STEPS + 1])).collect(); - let total: f64 = tables.iter().filter_map(|t| t.last().copied()).sum(); - if !matches!(size_law, Size::Constant(_)) && !(total.is_finite() && total > 1e-12) { - return Err(unsupported("a zero-length edge of the chain")); - } - let total = if total > 1e-12 { total } else { 1.0 }; - let mut cum: Vec = Vec::with_capacity(n + 1); - let mut acc = 0.0; - for table in &tables { - cum.push(acc); - acc += table.last().copied().unwrap_or(0.0); - } - cum.push(acc); - // A law that runs around a closed chain meets itself: its two ends must agree there. - if closed - && let Size::Law(law) = size_law - && (law.eval(0.0) - law.eval(1.0)).abs() > 1e-9 * law.radii.iter().copied().fold(1.0_f64, f64::max) - { - return Err(KernelError::Invalid("a closed edge chain runs back into itself: give the same radius law at both ends".into())); - } - // The law's parameter at `along` of edge `k` (its front to its back). - let frac_at = |k: usize, along: f64| -> f64 { - let (Some(table), Some(lo)) = (tables.get(k), cum.get(k)) else { return if k >= n { 1.0 } else { 0.0 } }; - let s = sampled(table, along).unwrap_or(0.0); - ((lo + s) / total).clamp(0.0, 1.0) - }; - let sizer = Sizer { size: size_law, tol: tol * 100.0 }; - // Arcs on a planar side that curve round the ball: its centre runs round them at their - // radius less the blend's. Less than nothing is too large; nothing is a pivot. - let mut pivots: Vec> = vec![None; n]; - 'pivots: for (k, e) in chain.iter().enumerate() { - // A size that varies along the edge has no one radius to compare a corner's arc with. - let Some(r) = fixed else { break 'pivots }; - let Some((o, rho, _)) = circle_of(e, tol * 1e3) else { continue }; - for side in [1, 2] { - let Some(f) = (if side == 1 { side1.get(k) } else { side2.get(k) }).and_then(|i| faces.get(*i)) else { continue }; - let mt::Surface::Plane(pl) = f.oriented_surface() else { continue }; - let Some(np) = Vec3::new(pl.normal().x, pl.normal().y, pl.normal().z).normalized() else { continue }; - // Into the face (left of the edge as the face runs it, about its outward normal). - let Some(used) = f.boundary_iters().into_iter().flatten().find(|x| x.id() == e.id()) else { continue }; - let Some((pm, tm)) = ({ - use mt::{BoundedCurve, ParametricCurve}; - let c = used.oriented_curve(); - let (a, b) = c.range_tuple(); - let d = c.der((a + b) * 0.5); - Vec3::new(d.x, d.y, d.z).normalized().map(|t| (from_p3(c.subs((a + b) * 0.5)), t)) - }) else { - continue; - }; - if (o - pm).dot(np.cross(tm)) <= 0.0 { - continue; - } - if rho < r - tol * 1e3 { - return Err(too_large("the blend is larger than a corner radius (site 1257)")); - } - if (rho - r).abs() > tol * 1e3 { - continue; - } - // The ball sits on the planar side at the arc's centre; the other side must be a round - // about the same axis, the ball touching it all along. - let c = o + np * (sigma * r); - let (a1, a2) = edge_sides(&[k]); - let other = if side == 1 { a2 } else { a1 }; - let reach = other.iter().filter_map(|f| project(f, c, None)).map(|x| x.0.dist(c)).fold(f64::INFINITY, f64::min); - if (reach - r).abs() <= size * 1e-4 { - if let Some(slot) = pivots.get_mut(k) { - *slot = Some(Pivot { c, o, axis: np, side }); - } - break; - } - } - } - if pivots.iter().all(Option::is_some) { - return Err(unsupported("rounding again only rounded corners of the blend's radius")); - } - // Seams at the chain's vertices: edges there that aren't in the chain, and their side. - let chain_ids: Vec = chain.iter().map(|e| e.id()).collect(); - let mut seams: Vec> = Vec::with_capacity(nv); - // At an open chain's ends: the end face (planar, square to the edge there). - let mut end_faces: Vec<(usize, usize)> = Vec::new(); // (vertex index, face index) - // A flat strip on planar sides can end across two planar faces (an earlier chamfer). - // Their shared seam is shortened to the crossing of the new chamfer plane. - let mut split_ends: Vec<(usize, usize, usize, mt::Edge)> = Vec::new(); - // Chain ends whose end face is not a plane square to the edge: (vertex, face, point, tangent, - // the side (1 or 2) the end face is tangent to when it lies along the edge there). - let mut slanted: Vec<(usize, usize, Vec3, Vec3, Option)> = Vec::new(); - for (k, v) in verts.iter().enumerate() { - let at_end = !closed && (k == 0 || k == nv - 1); - let (k1, k2) = { - let ei = if k == nv - 1 && !closed { n - 1 } else { k.min(n - 1) }; - (side1.get(ei).copied().unwrap_or(usize::MAX), side2.get(ei).copied().unwrap_or(usize::MAX)) - }; - let mut found: Vec<(usize, mt::Edge)> = Vec::new(); - for (fi, f) in faces.iter().enumerate() { - if !f.vertex_iter().any(|x| x == *v) { - continue; - } - let on_side = side1.contains(&fi) || side2.contains(&fi); - if !on_side { - if !at_end || end_faces.iter().filter(|(kk, _)| *kk == k).count() >= 2 { - return Err(unsupported("a vertex of the edge chain where other faces meet")); - } - end_faces.push((k, fi)); - continue; - } - for x in f.edge_iter() { - if chain_ids.contains(&x.id()) || !(*x.front() == *v || *x.back() == *v) || found.iter().any(|(_, y)| y.id() == x.id()) { - continue; - } - let side = if fi == k1 || (side1.contains(&fi) && fi != k2) { 1 } else { 2 }; - found.push((side, x.absolute_clone())); - } - } - if at_end && !end_faces.iter().any(|(kk, _)| *kk == k) { - return Err(unsupported("an open chain of curved edges must end at a face")); - } - let ends: Vec = end_faces.iter().filter(|(kk, _)| *kk == k).map(|(_, fi)| *fi).collect(); - if let [ga, gb] = ends[..] { - let terminal = chain.get(if k == 0 { 0 } else { n - 1 }).ok_or_else(|| unsupported("chain end"))?; - let planar = [ga, gb, k1, k2].iter().all(|i| faces.get(*i).and_then(crate::blend::plane_normal).is_some()); - if round || !planar || !straight(terminal, tol * 10.0) { - return Err(unsupported("a vertex of the edge chain where other faces meet")); - } - let shares = |g: usize, side: usize| { - faces - .get(g) - .zip(faces.get(side)) - .is_some_and(|(g, s)| g.edge_iter().any(|e| (e.front() == v || e.back() == v) && s.edge_iter().any(|x| x.id() == e.id()))) - }; - let (ga, gb) = if shares(ga, k1) && shares(gb, k2) { - (ga, gb) - } else if shares(gb, k1) && shares(ga, k2) { - (gb, ga) - } else { - return Err(unsupported("the end faces do not meet both sides of the chain")); - }; - let seam = faces - .get(ga) - .and_then(|a| { - faces.get(gb).and_then(|b| a.edge_iter().find(|e| (e.front() == v || e.back() == v) && b.edge_iter().any(|x| x.id() == e.id()))) - }) - .ok_or_else(|| unsupported("the end faces have no shared seam"))?; - if !straight(&seam, tol * 10.0) { - return Err(unsupported("a curved seam between the end faces")); - } - // The first face is the one reached by side 1's contact. - end_faces.retain(|(kk, _)| *kk != k); - end_faces.extend([(k, ga), (k, gb)]); - split_ends.push((k, ga, gb, seam.absolute_clone())); - } - // At most one seam per side. - if found.iter().filter(|x| x.0 == 1).count() > 1 || found.iter().filter(|x| x.0 == 2).count() > 1 { - return Err(unsupported("a vertex of the edge chain where several seams meet")); - } - seams.push(found); - } - // Sections: at each vertex (a contact on the seam there), then along each edge. - let tangent_at = |e: &mt::Edge, s: f64| -> Option<(Vec3, Vec3)> { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.oriented_curve(); - let (a, b) = c.range_tuple(); - let t = a + (b - a) * s; - let d = c.der(t); - Some((from_p3(c.subs(t)), Vec3::new(d.x, d.y, d.z).normalized()?)) - }; - let mut vsec: Vec
= Vec::with_capacity(nv); - // The radius each vertex section was solved at (the closed end of a law: zero). - let mut vradius: Vec = Vec::with_capacity(nv); - for k in 0..nv { - let (p, t) = if k < n { - tangent_at(chain.get(k).ok_or_else(|| KernelError::Failed("edge".into()))?, 0.0) - } else { - tangent_at(chain.get(n - 1).ok_or_else(|| KernelError::Failed("edge".into()))?, 1.0) - } - .ok_or_else(|| KernelError::Failed("tangent".into()))?; - let here = seams.get(k).cloned().unwrap_or_default(); - let at_end = end_faces.iter().any(|(kk, _)| *kk == k); - // Next to a pivot the ball is at its centre, touching the other side square above the - // vertex. - let pivoting: Vec = [(k < n).then_some(k), if k > 0 { Some(k - 1) } else { closed.then_some(n - 1) }] - .into_iter() - .flatten() - .filter_map(|i| pivots.get(i).copied().flatten()) - .collect(); - if let Some(pv) = pivoting.first().copied() { - if at_end || pivoting.iter().any(|x| x.c.dist(pv.c) > tol * 1e3) { - return Err(unsupported("a rounded corner of the blend's radius where the edge chain ends or turns")); - } - let q = pv.c + (p - pv.o); - vsec.push(if pv.side == 1 { Section { c: pv.c, q1: pv.o, q2: q } } else { Section { c: pv.c, q1: q, q2: pv.o } }); - vradius.push(fixed.unwrap_or_default()); - continue; - } - // The law's parameter at this vertex: the front of its edge, or the back of the last - // edge at an open chain's end. - let law_s = if k < n { frac_at(k, 0.0) } else { frac_at(n - 1, 1.0) }; - if at_end { - // A plane square to the edge holds the blend's end section. Any other end face: the - // blend runs on past the end and is cut back where it meets that face. - let (_, fi) = end_faces.iter().find(|(kk, _)| *kk == k).copied().unwrap_or_default(); - let g = faces.get(fi).ok_or_else(|| KernelError::Failed("end face".into()))?; - let square = match g.oriented_surface() { - mt::Surface::Plane(pl) => { - let m = pl.normal(); - Vec3::new(m.x, m.y, m.z).normalized().is_some_and(|ng| ng.dot(t).abs() >= 1.0 - 1e-6) - } - _ => false, - }; - // A radius that has run to zero closes the blend at the vertex itself: it does not run - // on past the end, and the end face keeps the corner it had there. - let closed_end = matches!(size_law, Size::Law(law) if law.eval(law_s) <= CLOSED); - if (!square || split_ends.iter().any(|e| e.0 == k)) && !closed_end { - slanted.push((k, fi, p, t, None)); - } - } - let extra = match here.first().filter(|_| !at_end) { - None => None, - // A curved seam holds the contact on itself (the chain runs on smoothly across it: a - // lofted wall's two halves). - Some((side, seam)) if !straight(seam, tol * 10.0) => Some(Extra::Seam(*side, seam)), - Some((side, seam)) => { - let side = *side; - // The plane through the seam square to that side's surface. - let o = from_p3(seam.front().point()); - let d = (from_p3(seam.back().point()) - o).normalized().ok_or_else(|| KernelError::Failed("seam".into()))?; - let fs = if side == 1 { &s1 } else { &s2 }; - // The side's normal at the joint: from its face nearest the joint (any face of a - // longer side is no guide here). - let nn = fs - .iter() - .filter_map(|f| project(f, p, None)) - .min_by(|a, b| a.0.dist(p).total_cmp(&b.0.dist(p))) - .map(|x| x.1) - .ok_or_else(|| KernelError::Failed("seam normal".into()))?; - Some(Extra::Plane(side, o, d.cross(nn).normalized().ok_or_else(|| KernelError::Failed("seam plane".into()))?)) - } - }; - // On the faces of the edge from this vertex alone (the last edge's at an open chain's - // end): the other edge's faces are untrimmed here and can run on near the ball where it no - // longer is (a wall past the round at a corner, which a ball rolling round it pokes - // through). - let (a1, a2) = edge_sides(&[k.min(n - 1)]); - let (s, r) = sizer.section(&a1, &a2, p, t, law_s, sigma, cusp, extra).ok_or_else(|| sizer.refusal())?; - // A seam on the other side too must pass through that side's contact. - if let Some((side, seam)) = here.get(1).filter(|_| !at_end) { - let q = if *side == 1 { s.q1 } else { s.q2 }; - let (a, b) = (from_p3(seam.front().point()), from_p3(seam.back().point())); - if !straight(seam, tol * 10.0) || q.dist_to_segment(a, b) > tol * 1e3 { - return Err(unsupported("seams on both sides of a corner of the edge chain")); - } - } - vsec.push(s); - vradius.push(r); - } - // Past a slanted end: sections of the same rolling ball beyond the end vertex (far to near - // at the chain's start, near to far at its end), far enough to cross the end face. - let mut beyond: Vec<(usize, Vec
, Vec)> = Vec::new(); - for (k, fi, p, t, tangent) in slanted.iter_mut() { - let g = faces.get(*fi).ok_or_else(|| KernelError::Failed("end face".into()))?; - let at = vsec.get(*k).copied().ok_or_else(|| KernelError::Failed("section".into()))?; - let (_, ng, _) = project(g, *p, None).ok_or_else(|| unsupported("the blend's end on its end face"))?; - let cos = split_ends - .iter() - .find(|e| e.0 == *k) - .and_then(|(_, _, gb, _)| faces.get(*gb)) - .and_then(crate::blend::plane_normal) - .map_or(ng.dot(*t).abs(), |nb| ng.dot(*t).abs().min(nb.dot(*t).abs())); - // An end face along the edge and tangent to one side there (a wall that runs out into - // the face): the blend meets it along a curve that touches that side's contact at the - // vertex. Any other end face that close to the edge is refused. - let (e1, e2) = edge_sides(&vertex_edges(*k)); - *tangent = if cos < TANGENT_END { - [(1u8, &e1), (2u8, &e2)].into_iter().find_map(|(side, faces)| { - faces.iter().filter_map(|f| project(f, *p, None)).any(|(_, n, _)| n.dot(ng).abs() > 1.0 - TANGENT_END).then_some(side) - }) - } else { - None - }; - if cos < 0.15 && tangent.is_none() { - return Err(unsupported("an end face almost along the edge")); - } - let width = at.q1.dist(*p).max(at.q2.dist(*p)).max(at.c.dist(*p)) + vradius.get(*k).copied().unwrap_or(scale); - let reach = 1.5 * width / if tangent.is_some() { 1.0 } else { cos }; - let out = if *k == 0 { -*t } else { *t }; - // The run on past the end only gives the fit its context (the end face cuts it back), but - // it keeps the law's end slope: the radius is read at the distance past the end. - let law_s = |d: f64| if *k == 0 { -d / total } else { 1.0 + d / total }; - // Past a tangent end the straight run along the tangent leaves the curved spine: where - // the ball no longer fits, the run is shortened (it only gives the fit its context). - let mut list = Vec::with_capacity(EXTENSION); - let mut laws = Vec::with_capacity(EXTENSION); - let mut reach = reach; - // Past the end of a curved edge the planes square to its end tangent cut the ring of - // centres further and further round it, until a step jumps across the ring (#1255: a - // knuckle's cap circle with a round as wide as 0.7 of its radius). The run is shortened - // then, as long as one of its sections still lies wholly past the end face. - let ng_out = if ng.dot(out) < 0.0 { -ng } else { ng }; - let past = |sec: &Section| [sec.c, sec.q1, sec.q2].iter().all(|x| (*x - *p).dot(ng_out) > tol); - // A run shortened when its centres jump across the ring (a knuckle's cap circle, #1255) - // stands if no full-length run works; a size law's own end slope is read at each station's - // distance past the end. - let mut fallback: Option> = None; - for attempt in 0..TANGENT_RETRIES { - list.clear(); - laws.clear(); - let step = reach / EXTENSION as f64; - let sections = (1..=EXTENSION).map(|j| { - let d = step * j as f64; - let anchor = *p + out * d; - let s = law_s(d); - sizer.section(&e1, &e2, anchor, *t, s, sigma, cusp, None).map(|(section, _)| (s, section)) - }); - match sections.collect::>>() { - Some(all) => { - let smooth = tangent.is_some() - || std::iter::once(at.c).chain(all.iter().map(|(_, s)| s.c)).collect::>().windows(2).all(|w| match w { - [a, b] => a.dist(*b) <= MAX_STEP_STRETCH * step, - _ => true, - }); - if smooth { - // A shortened run must still cross the end face; else the first, - // full-length run stands. - if fallback.is_none() || all.iter().any(|(_, s)| past(s)) { - list = all.iter().map(|(_, s)| *s).collect(); - laws = all.iter().map(|(s, _)| *s).collect(); - } - break; - } - fallback.get_or_insert(all); - } - None if tangent.is_none() || fallback.is_some() || attempt + 1 == TANGENT_RETRIES => break, - None => {} - } - reach *= if tangent.is_some() { 0.5 } else { 0.75 }; - } - if list.is_empty() { - match fallback { - // The shortened run stands when the ring's step jumped, whatever its size. - Some(all) => { - list = all.iter().map(|(_, s)| *s).collect(); - laws = all.iter().map(|(s, _)| *s).collect(); - } - // A size asked for beyond what the faces around the end hold is refused as such; - // one radius past the end is the rolling ball's own failure to fit. - None => { - return Err(match size_law { - Size::Constant(_) => unsupported("the ball doesn't fit past the end of the edge"), - _ => too_large("the blend is larger than the neighbouring faces (site 1472)"), - }); - } - } - } - if *k == 0 { - list.reverse(); - laws.reverse(); - } - beyond.push((*k, list, laws)); - } - // Uniform refinement preserves a common spacing across neighbouring patches. Work is - // capped: a difficult strip returns an error instead of accepting an inaccurate fit. - let fit_tolerance = (size * 1e-5).clamp(1e-5, 0.001); - // At a seam the contact lies on the seam plane, which need not be square to the - // original edge. Its ball centre therefore need not lie in the edge's normal plane. - // Interpolate that plane's displacement so the interior sections tend to the exact - // seam sections, rather than leaving a finite jump as sampling gets finer. - let offsets: Vec<(f64, f64)> = chain - .iter() - .enumerate() - .map(|(k, edge)| { - let (p0, t0) = tangent_at(edge, 0.0).ok_or_else(|| KernelError::Failed("tangent".into()))?; - let (p1, t1) = tangent_at(edge, 1.0).ok_or_else(|| KernelError::Failed("tangent".into()))?; - let start = vsec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?; - let end = vsec.get((k + 1) % nv).ok_or_else(|| KernelError::Failed("section".into()))?; - Ok(((start.c - p0).dot(t0), (end.c - p1).dot(t1))) - }) - .collect::>()?; - let section_at = |k: usize, edge: &mt::Edge, along: f64| -> Result<(Section, f64)> { - let (p, t) = tangent_at(edge, along).ok_or_else(|| KernelError::Failed("tangent".into()))?; - let (start, end) = offsets.get(k).copied().ok_or_else(|| KernelError::Failed("section offset".into()))?; - let anchor = p + t * (start * (1.0 - along) + end * along); - let (a1, a2) = edge_sides(&[k]); - sizer.section(&a1, &a2, anchor, t, frac_at(k, along), sigma, cusp, None).ok_or_else(|| sizer.refusal()) - }; - let mut samples = SAMPLES.min(max_samples); - let (esec, fits) = loop { - if n.checked_mul(samples).is_none_or(|count| count > MAX_CHAIN_SAMPLES) { - return Err(unsupported("curve blend exceeds the section fitting limit")); - } - // No guide along a pivot: its sections are the two at its ends. - let mut guides: Vec> = Vec::with_capacity(n); - for (k, e) in chain.iter().enumerate() { - if pivots.get(k).copied().flatten().is_some() { - guides.push(None); - continue; - } - let mut list = vec![*vsec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?]; - let mut law = vec![frac_at(k, 0.0)]; - let (mut front_beyond, mut back_beyond) = (0usize, 0usize); - for j in 1..samples - 1 { - let along = j as f64 / (samples - 1) as f64; - let (section, _) = section_at(k, e, along)?; - list.push(section); - law.push(frac_at(k, along)); - } - list.push(*vsec.get((k + 1) % nv).ok_or_else(|| KernelError::Failed("section".into()))?); - law.push(frac_at(k, 1.0)); - for (kv, ext, exts) in &beyond { - if *kv == k && k == 0 { - list.splice(0..0, ext.iter().copied()); - law.splice(0..0, exts.iter().copied()); - front_beyond = ext.len(); - } else if *kv == k + 1 && k + 1 == nv - 1 { - list.extend(ext.iter().copied()); - law.extend(exts.iter().copied()); - back_beyond = ext.len(); - } - } - let mut guide = Guide::with_law(list, law)?; - // The chain's own run: the spliced sections at either end are context for the fit - // only (the blend is cut back where it meets the end face there). - let last = guide.lengths.last().copied().unwrap_or(0.0); - let at = |i: usize| if last > 0.0 { guide.lengths.get(i).copied().unwrap_or(0.0) / last } else { 0.0 }; - guide.span = (at(front_beyond), at(guide.sections.len().saturating_sub(1 + back_beyond))); - guides.push(Some(guide)); - } - // Intersection curves inherit their leader's piecewise parameter speed. Fitting - // those parameters creates oscillations even on a geometrically smooth spine. - // Resample by distance along the rolling centres, projecting each interpolated - // centre back onto the exact two offset surfaces before it becomes a section. - let uniform_section = |k: usize, along: f64| -> Result
{ - let guide = guides.get(k).and_then(Option::as_ref).ok_or_else(|| KernelError::Failed("spine guide".into()))?; - if along == 0.0 { - return guide.sections.first().copied().ok_or_else(|| KernelError::Failed("section".into())); - } - if along == 1.0 { - return guide.sections.last().copied().ok_or_else(|| KernelError::Failed("section".into())); - } - let (anchor, tangent, law_s) = guide.anchor_at(along).ok_or_else(|| unsupported("degenerate rolling-ball spine"))?; - let (a1, a2) = edge_sides(&[k]); - sizer - .section(&a1, &a2, anchor, tangent, law_s, sigma, cusp, None) - .map(|(section, _)| section) - .ok_or_else(|| unsupported("the ball doesn't fit along the resampled spine")) - }; - let esec: Vec> = (0..n) - .map(|k| match guides.get(k) { - Some(Some(_)) => (0..samples).map(|j| uniform_section(k, j as f64 / (samples - 1) as f64)).collect::>>(), - _ => Ok(vec![ - *vsec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?, - *vsec.get((k + 1) % nv).ok_or_else(|| KernelError::Failed("section".into()))?, - ]), - }) - .collect::>()?; - // Each strip's neighbouring sections at its own spacing (edges of different lengths - // have differently spaced samples, which makes a uniform interpolation overshoot). - let length = |k: usize| guides.get(k).and_then(Option::as_ref).and_then(|g| g.lengths.last().copied()).unwrap_or(0.0); - let rolls = |k: usize| guides.get(k).is_some_and(Option::is_some); - let mut fits: Vec> = Vec::with_capacity(n); - for k in 0..n { - // A pivot's surface is made whole (`revolve`); a strip next to one ends on the joint's - // section on its own. - if !rolls(k) { - fits.push(None); - continue; - } - let h = length(k) / (samples - 1) as f64; - // A neighbour shorter than two of the strip's steps lends none: its own sections are - // spaced far closer (a small round beside a long line), and borrowing them made the - // strip overshoot and fold back on itself past the joint, which its faces' meshes - // then folded with (#1667). The strip ends on the joint's section on its own. - let spaced = |nb: usize, from_end: bool| -> Result> { - let l = length(nb); - if !(l > 2.0 * h && h > 0.0) { - return Ok(Vec::new()); - } - let mut out = Vec::with_capacity(2); - for j in [1.0, 2.0] { - out.push(uniform_section(nb, if from_end { 1.0 - j * h / l } else { j * h / l })?); - } - if from_end { - out.reverse(); - } - Ok(out) - }; - let (prev, next) = ((k + n - 1) % n, (k + 1) % n); - let list = esec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?; - // Not across a joint where the strip's curvature jumps (a line or a wide arc into a - // small round): a spline smooth through it spreads the jump over the sections beside - // it, and the error falls only with the square of their spacing. The strip then ends - // on the joint's section on its own, which the next one shares. - let smooth = |near: [Option<&Section>; 3], beyond: [Option<&Section>; 3]| match (near, beyond) { - ([Some(a), Some(b), Some(c)], [Some(x), Some(y), Some(z)]) => !bends([a, b, c], [x, y, z], fit_tolerance), - _ => false, - }; - let before = match (closed || k > 0) && rolls(prev) { - true => { - let b = spaced(prev, true)?; - if smooth([list.first(), list.get(1), list.get(2)], [list.first(), b.get(1), b.first()]) { b } else { Vec::new() } - } - false => Vec::new(), - }; - let after = match (closed || k + 1 < n) && rolls(next) { - true => { - let a = spaced(next, false)?; - let m = list.len(); - let tail = [list.last(), m.checked_sub(2).and_then(|i| list.get(i)), m.checked_sub(3).and_then(|i| list.get(i))]; - if smooth(tail, [list.last(), a.first(), a.get(1)]) { a } else { Vec::new() } - } - false => Vec::new(), - }; - let mut fit = crate::guard("fit curve blend", || fit_strip(list, &before, &after, round))?; - fit.span = guides.get(k).and_then(Option::as_ref).map(|g| g.span).unwrap_or((0.0, 1.0)); - fits.push(Some(fit)); - } - let mut accurate = true; - 'edges: for k in 0..n { - let Some(Some(fit)) = fits.get(k) else { continue }; - for j in 0..samples - 1 { - for fraction in [0.25, 0.5, 0.75] { - let along = (j as f64 + fraction) / (samples - 1) as f64; - // A size that varies along the edge reaches past its ends only for the fit's - // context (the end face cuts that away), so it is not held to the tolerance - // there. One radius keeps the check it always had, the whole strip. - if !matches!(size_law, Size::Constant(_)) - && fits.get(k).and_then(Option::as_ref).is_some_and(|f| along < f.span.0 || along > f.span.1) - { - continue; - } - let section = uniform_section(k, along)?; - if !crate::guard("check curve blend fit", || Ok(section_fits(fit, §ion, along, round, sigma, fit_tolerance)))? { - accurate = false; - break 'edges; - } - } - } - } - if accurate { - break (esec, fits); - } - if samples >= max_samples { - return Err(KernelError::Failed("curve blend: could not fit the rolling-ball surface within the accuracy and section limits".into())); - } - samples = (2 * samples - 1).min(max_samples); - }; - // Where each extended blend meets its slanted end face: (vertex, edge, cut parameters of - // the two contacts, the end curve from contact 1 to contact 2). - let mut caps: Vec<(usize, usize, f64, f64, mt::Curve)> = Vec::new(); - let mut split_caps: Vec<(usize, mt::Edge, Vec3)> = Vec::new(); - for (k, fi, _, _, tangent) in &slanted { - let ke = if *k == 0 { 0 } else { n - 1 }; - let fit = fits.get(ke).and_then(Option::as_ref).ok_or_else(|| KernelError::Failed("curve blend fit".into()))?; - let g = faces.get(*fi).ok_or_else(|| KernelError::Failed("end face".into()))?; - let at = vsec.get(*k).copied().ok_or_else(|| KernelError::Failed("section".into()))?; - let seam = |s: u8| seams.get(*k).and_then(|l| l.iter().find(|(x, _)| *x as u8 == s)).map(|(_, e)| e); - let both = [seam(1), seam(2)]; - if let Some((_, ga, gb, middle)) = split_ends.iter().find(|e| e.0 == *k) { - use mt::{BSplineCurve, KnotVec, ParametricCurve, SearchNearestParameter}; - let fail = || unsupported("the chamfer does not cross both end faces"); - let p = from_p3(verts.get(*k).ok_or_else(fail)?.point()); - let (_, t) = tangent_at(chain.get(ke).ok_or_else(fail)?, if *k == 0 { 0.0 } else { 1.0 }).ok_or_else(fail)?; - let hit = |q: Vec3, fi: usize| -> Option { - let normal = faces.get(fi).and_then(crate::blend::plane_normal)?; - let den = normal.dot(t); - (den.abs() > 1e-6).then(|| q - t * (normal.dot(q - p) / den)) - }; - let a = hit(at.q1, *ga).ok_or_else(fail)?; - let b = hit(at.q2, *gb).ok_or_else(fail)?; - let m = (at.q2 - at.q1).cross(t).normalized().ok_or_else(fail)?; - let far = if middle.front() == verts.get(*k).ok_or_else(fail)? { middle.back() } else { middle.front() }; - let u = from_p3(far.point()) - p; - let den = m.dot(u); - if den.abs() < tol { - return Err(fail()); - } - let fraction = m.dot(at.q1 - p) / den; - let c = p + u * fraction; - let across = (c - at.q1).dot(at.q2 - at.q1) / (at.q2 - at.q1).len2(); - if !(fraction > 1e-6 && fraction < 1.0 - 1e-6 && across > 1e-6 && across < 1.0 - 1e-6) { - return Err(fail()); - } - let parameter = |row: usize, q: Vec3| -> Option { - let curve = fit.contacts.get(row)?; - let v = curve.search_nearest_parameter(p3(q), None, 100)?; - (v > fit.range.0 + 1e-6 && v < fit.range.1 - 1e-6 && from_p3(curve.subs(v)).dist(q) <= fit_tolerance).then_some(v) - }; - let (ta, tb) = (parameter(0, a).ok_or_else(fail)?, parameter(1, b).ok_or_else(fail)?); - let curve = BSplineCurve::try_new(KnotVec::from(vec![0.0, 0.0, 0.5, 1.0, 1.0]), vec![p3(a), p3(c), p3(b)]) - .map_err(|e| KernelError::Failed(format!("chamfer end: {e}")))?; - caps.push((*k, ke, ta, tb, mt::Curve::BSplineCurve(curve))); - split_caps.push((*k, middle.clone(), c)); - continue; - } - let cap = crate::guard("curve blend end", || match tangent { - Some(side) => tangent_cap(fit, g, *side, both, fit_tolerance), - None => end_cap(fit, g, &at, both, round, fit_tolerance), - })?; - caps.push((*k, ke, cap.0, cap.1, cap.2)); - } - // Both ends of one edge cut back: the contacts must keep a piece between them. - if let [(_, 0, s1, s2, _), (_, 0, e1, e2, _)] = &caps[..] - && n == 1 - && !(s1 + 1e-6 < *e1 && s2 + 1e-6 < *e2) - { - return Err(too_large("the blend is larger than the neighbouring faces (site 1668)")); - } - crate::guard("curve blend", || { - let fail = |m: &str| KernelError::Failed(format!("curve blend: {m}")); - // Vertices and arcs at the chain's vertices. - let mut v1: Vec = vsec.iter().map(|s| builder::vertex(p3(s.q1))).collect(); - let mut v2: Vec = vsec.iter().map(|s| builder::vertex(p3(s.q2))).collect(); - for (k, _, _, _, curve) in &caps { - use mt::{BoundedCurve, ParametricCurve}; - let (lo, hi) = curve.range_tuple(); - if let (Some(a), Some(b)) = (v1.get_mut(*k), v2.get_mut(*k)) { - *a = builder::vertex(curve.subs(lo)); - *b = builder::vertex(curve.subs(hi)); - } - } - // A closed section (a radius that has run to zero) has one vertex for both contacts, so - // the blend face's wire and the side faces' meet there. - for (k, s) in vsec.iter().enumerate() { - if !closed_section(s) { - continue; - } - if let Some(v) = v1.get(k).cloned() - && let Some(slot) = v2.get_mut(k) - { - *slot = v; - } - } - // Along a pivot the planar side's contact is one point: one vertex at both its ends. - for (k, pv) in pivots.iter().enumerate() { - let Some(pv) = pv else { continue }; - let vs = if pv.side == 1 { &mut v1 } else { &mut v2 }; - if let Some(v) = vs.get(k).cloned() - && let Some(slot) = vs.get_mut((k + 1) % nv) - { - *slot = v; - } - } - // A chain end (a cap, or the section at a square end) on the far end of its seam uses that - // seam up: that vertex is the end. - let mut consumed: HashMap = HashMap::new(); - for (k, _) in &end_faces { - for (side, seam) in seams.get(*k).into_iter().flatten() { - let Some(old) = verts.get(*k) else { continue }; - let far = if seam.front() == old { seam.back() } else { seam.front() }; - let slot = if *side == 1 { v1.get_mut(*k) } else { v2.get_mut(*k) }; - if let Some(nv) = slot - && far != old - && from_p3(far.point()).dist(from_p3(nv.point())) <= fit_tolerance - { - *nv = far.clone(); - consumed.insert(seam.id(), far.clone()); - } - } - } - // The section's own radius, where the blend is sized by a law or a chord width (`r` is the - // one radius of a constant blend, exactly as before). - let rad = |s: &Section| match size_law { - Size::Constant(r) => r, - Size::Chord(_) | Size::Law(_) => s.c.dist(s.q1), - }; - let mut arcs: Vec> = Vec::with_capacity(nv); - let mut split_arcs: HashMap> = HashMap::new(); - for (k, s) in vsec.iter().enumerate() { - let (a, b) = (v1.get(k).ok_or_else(|| fail("vertex"))?, v2.get(k).ok_or_else(|| fail("vertex"))?); - // A closed section has no arc to run between the contacts: the blend meets itself - // there, at the edge's end point. - let e = if closed_section(s) { - None - } else if round { - let m = s.c + ((s.q1 - s.c) + (s.q2 - s.c)).normalized().ok_or_else(|| fail("arc"))? * rad(s); - Some(builder::circle_arc(a, b, p3(m))) - } else { - Some(builder::line(a, b)) - }; - let e = match caps.iter().find(|c| c.0 == k) { - Some((_, _, _, _, curve)) => Some(mt::Edge::try_new(a, b, curve.clone()).map_err(|e| fail(&e.to_string()))?), - None => e, - }; - if let Some((_, _, c)) = split_caps.iter().find(|cap| cap.0 == k) { - let v = builder::vertex(p3(*c)); - split_arcs.insert(k, vec![builder::line(a, &v), builder::line(&v, b)]); - } - arcs.push(e); - } - // Outward: toward the ball centre on a concave edge, away on a convex one. - let oriented = |mut surface: mt::Surface, list: &[Section]| -> Result { - use mt::{ParametricSurface3D, SearchNearestParameter}; - let s = list.get(list.len() / 2).ok_or_else(|| fail("section"))?; - let mid = s.c + ((s.q1 - s.c) + (s.q2 - s.c)).normalized().ok_or_else(|| fail("mid"))? * rad(s); - if let Some((u, v)) = surface.search_nearest_parameter(p3(mid), None, 100) { - let nn = surface.normal(u, v); - let want = (s.c - mid) * sigma; - if Vec3::new(nn.x, nn.y, nn.z).dot(want) < 0.0 { - surface = mt::Invertible::inverse(&surface); - } - } - Ok(surface) - }; - // Contact curves and blend faces per edge. - // (None: the planar side's contact along a pivot, a point.) - let mut c1: Vec> = Vec::with_capacity(n); - let mut c2: Vec> = Vec::with_capacity(n); - let mut blends: Vec = Vec::with_capacity(n); - for (k, list) in esec.iter().enumerate() { - let k1 = (k + 1) % nv; - let (a1, b1, a2, b2) = (v1.get(k), v1.get(k1), v2.get(k), v2.get(k1)); - let (Some(a1), Some(b1), Some(a2), Some(b2)) = (a1, b1, a2, b2) else { return Err(fail("vertex")) }; - if let Some(pv) = pivots.get(k).copied().flatten() { - // The section at the start turned about the axis to the one at the end; the other - // side's contact is the circle its end runs on. - let (s0, s1e) = (list.first().ok_or_else(|| fail("section"))?, list.last().ok_or_else(|| fail("section"))?); - let (qa, qb) = if pv.side == 1 { (s0.q2, s1e.q2) } else { (s0.q1, s1e.q1) }; - let (a, b) = (qa - pv.c, qb - pv.c); - let angle = pv.axis.dot(a.cross(b)).atan2(a.dot(b)); - let (sn, cs) = (angle / 2.0).sin_cos(); - let mid = pv.c + a * cs + pv.axis.cross(a) * sn + pv.axis * (pv.axis.dot(a) * (1.0 - cs)); - let surface = section_controls(s0, round).and_then(|ctrl| revolve(ctrl, pv.c, pv.axis, angle)).ok_or_else(|| fail("pivot"))?; - let (from, to) = if pv.side == 1 { (a2, b2) } else { (a1, b1) }; - let arc = builder::circle_arc(from, to, p3(mid)); - let (e1, e2) = if pv.side == 1 { (None, Some(arc)) } else { (Some(arc), None) }; - c1.push(e1); - c2.push(e2); - blends.push(oriented(surface, list)?); - continue; - } - let fit = fits.get(k).and_then(Option::as_ref).ok_or_else(|| fail("fit"))?; - let [cv1, cv2] = &fit.contacts; - // Contacts past a slanted end stop at the end curve. - let (mut cv1, mut cv2) = (cv1.clone(), cv2.clone()); - for (kv, _, t1, t2, _) in caps.iter().filter(|c| c.1 == k) { - use mt::Cut; - if *kv == k + 1 { - let _ = cv1.cut(*t1); - let _ = cv2.cut(*t2); - } - } - for (kv, _, t1, t2, _) in caps.iter().filter(|c| c.1 == k) { - use mt::Cut; - if *kv == k && k == 0 { - cv1 = cv1.cut(*t1); - cv2 = cv2.cut(*t2); - } - } - c1.push(Some(mt::Edge::new(a1, b1, cv1))); - c2.push(Some(mt::Edge::new(a2, b2, cv2))); - blends.push(oriented(fit.surface.clone(), list)?); - } - // Rebuild the side faces: chain edges become contact curves, seams start at contacts. - let mut subst: HashMap, Option)> = HashMap::new(); - for (k, e) in chain.iter().enumerate() { - let (Some(x), Some(y)) = (c1.get(k), c2.get(k)) else { return Err(fail("contact")) }; - subst.insert(e.id(), (x.clone(), y.clone())); - } - // Seams get new ends at the contacts (an edge between two chain vertices at both). - let mut ends: HashMap, Option)> = HashMap::new(); - for (k, sm) in seams.iter().enumerate().flat_map(|(k, l)| l.iter().map(move |x| (k, x))) { - let (side, seam) = sm; - let v = verts.get(k).cloned().ok_or_else(|| fail("vertex"))?; - let nv = if *side == 1 { v1.get(k) } else { v2.get(k) }.ok_or_else(|| fail("vertex"))?.clone(); - let slot = ends.entry(seam.id()).or_insert_with(|| (seam.clone(), None, None)); - if *seam.front() == v { - slot.1 = Some(nv); - } else { - slot.2 = Some(nv); - } - } - let mut seam_subst: HashMap = HashMap::new(); - for (k, seam, _) in &split_caps { - let old = verts.get(*k).ok_or_else(|| fail("end vertex"))?; - let v = split_arcs.get(k).and_then(|es| es.first()).map(|e| e.back()).ok_or_else(|| fail("end seam"))?; - seam_subst.insert(seam.id(), crate::blend::retarget(seam, old, v, fit_tolerance)?); - } - for (id, (seam, a, b)) in ends { - if consumed.contains_key(&id) { - continue; - } - // At an end of an open chain the blend may stop past the seam's old end (a slanted end - // face, or one turning back past the side, as a box side beside a boss joined to it): - // the seam then runs on along its line or circle, within its planar face. - let one_end = match (&a, &b) { - (Some(nv), None) => Some((seam.front().clone(), nv.clone())), - (None, Some(nv)) => Some((seam.back().clone(), nv.clone())), - _ => None, - }; - if let Some((old, nv)) = one_end - && end_faces.iter().any(|(k, _)| verts.get(*k) == Some(&old)) - { - let on_tol = (size * 1e-5).max(1e-6); - let q = from_p3(nv.point()); - if crate::blend::on_edge(&seam, q, on_tol).is_none() { - let fits = faces - .iter() - .filter(|f| f.edge_iter().any(|e| e.id() == id)) - .any(|f| crate::blend::plane_normal(f).is_some() && crate::blend::extension_fits(f, from_p3(old.point()), q, tol)); - if !fits || !crate::blend::on_extension(&seam, q, on_tol) { - return Err(too_large("the blend is larger than the neighbouring faces (site 1853)")); - } - } - seam_subst.insert(id, crate::blend::retarget(&seam, &old, &nv, on_tol)?); - continue; - } - if !matches!(seam.curve(), mt::Curve::Line(_)) { - seam_subst.insert(id, trim_curved_seam(&seam, a, b, size)?); - continue; - } - // The new ends must stay on the seam, in order, short of each other. - let (p0, p1) = (from_p3(seam.front().point()), from_p3(seam.back().point())); - let at = |v: &mt::Vertex| { - let q = from_p3(v.point()); - let d = p1 - p0; - ((q - p0).dot(d) / d.len2().max(1e-300), (q - p0 - d * ((q - p0).dot(d) / d.len2().max(1e-300))).len()) - }; - let (ta, oa) = a.as_ref().map(at).unwrap_or((0.0, 0.0)); - let (tb, ob) = b.as_ref().map(at).unwrap_or((1.0, 0.0)); - if oa > size * 1e-5 || ob > size * 1e-5 || ta < -1e-9 || tb > 1.0 + 1e-9 || tb - ta < 1e-6 { - return Err(too_large("the blend is larger than the neighbouring faces (site 1873)")); - } - let a = a.unwrap_or_else(|| seam.front().clone()); - let b = b.unwrap_or_else(|| seam.back().clone()); - seam_subst.insert(id, builder::line(&a, &b)); - } - let mut out: Vec = Vec::new(); - let mut rec = Rebuild::default(); - rec.pieces(&seam_subst); - for (fi, f) in faces.iter().enumerate() { - let corners: Vec = end_faces.iter().filter(|(_, g)| *g == fi).map(|(k, _)| *k).collect(); - if !corners.is_empty() { - if corners.iter().any(|k| split_arcs.contains_key(k)) { - let connectors: Vec = corners - .iter() - .flat_map(|k| split_arcs.get(k).cloned().unwrap_or_else(|| arcs.get(*k).cloned().flatten().into_iter().collect())) - .collect(); - let rebuilt = crate::blend::rebuild_face(f, &seam_subst, &connectors)?; - rec.face(&rebuilt, f); - out.push(rebuilt); - continue; - } - // The end face (one or both ends of the chain): its two edges at a chain end now - // stop at the contacts, with the blend's end arc between them. - let mut wires = Vec::new(); - for w in f.absolute_boundaries() { - let mut es: Vec = Vec::new(); - for e in w.edge_iter() { - let ne = match seam_subst.get(&e.id()) { - Some(s) => { - if e.front() == e.absolute_front() { - s.clone() - } else { - s.inverse() - } - } - None => e.clone(), - }; - // Arriving at an old corner: continue along that end's arc. A seam the - // blend used up is left out, and the arc starts at its far end. - let arrives = corners.iter().copied().find(|k| verts.get(*k).is_some_and(|v| *e.back() == *v)); - let used_up = consumed.contains_key(&e.id()); - if !used_up { - es.push(ne.clone()); - } - if let Some(k) = arrives { - // A closed section has no blend arc at the corner: the blend ends at - // the vertex itself and the end face keeps the corner it had. - let (Some(arc), Some(a1), Some(a2)) = (arcs.get(k).and_then(Option::as_ref), v1.get(k), v2.get(k)) else { - continue; - }; - let to = if used_up { e.front() } else { ne.back() }; - let corner = if to == a1 { - arc.clone() - } else if to == a2 { - arc.inverse() - } else { - return Err(fail("end face corner")); - }; - es.push(corner); - } - } - wires.push(mt::Wire::from(es)); - } - let rebuilt = crate::heal::absolute_face(f, wires).ok_or_else(|| fail("an end face could not be rebuilt"))?; - rec.face(&rebuilt, f); - out.push(rebuilt); - continue; - } - let on1 = side1.contains(&fi); - let on2 = side2.contains(&fi); - if !on1 && !on2 && !f.edge_iter().any(|e| seam_subst.contains_key(&e.id())) { - out.push(f.clone()); - continue; - } - let mut wires = Vec::new(); - for w in f.absolute_boundaries() { - let mut es = Vec::new(); - for e in w.edge_iter() { - let ne = if let Some((x, y)) = subst.get(&e.id()) { - // A point along a pivot: the contacts beside it meet there. - let Some(base) = (if on1 { x } else { y }) else { continue }; - // Same direction as the chain edge, or reversed. - let chain_e = chain.iter().find(|c| c.id() == e.id()).ok_or_else(|| fail("edge"))?; - if e.front() == chain_e.front() { base.clone() } else { base.inverse() } - } else if let Some(s) = seam_subst.get(&e.id()) { - if e.front() == e.absolute_front() { s.clone() } else { s.inverse() } - } else if consumed.contains_key(&e.id()) { - continue; - } else { - e.clone() - }; - es.push(ne); - } - if collapsed_boundary(&es, fit_tolerance) { - return Err(too_large("the blend would consume a neighbouring face")); - } - wires.push(mt::Wire::from(es)); - } - let rebuilt = crate::heal::absolute_face(f, wires).ok_or_else(|| fail("a side face could not be rebuilt"))?; - rec.face(&rebuilt, f); - out.push(rebuilt); - } - // Blend faces: each runs its side-1 contact the other way from side 1's face. - for (k, bf) in blends.iter().enumerate() { - let (Some(e1), Some(e2)) = (c1.get(k), c2.get(k)) else { - return Err(fail("blend")); - }; - let ak = arcs.get(k).and_then(Option::as_ref); - let ak1 = arcs.get((k + 1) % nv).and_then(Option::as_ref); - let f1i = side1.get(k).ok_or_else(|| fail("side"))?; - let f1 = faces.get(*f1i).ok_or_else(|| fail("side"))?; - let chain_e = chain.get(k).ok_or_else(|| fail("edge"))?; - let used_fwd = f1 - .boundary_iters() - .into_iter() - .flatten() - .find(|e| e.id() == chain_e.id()) - .map(|e| e.front() == chain_e.front()) - .ok_or_else(|| fail("edge use"))?; - // Side 1 runs the contact forward (as the chain) when it ran the edge forward. - // A pivot's planar contact is a point: three sides. A closed section has no arc: two. - let edges: Vec = if used_fwd { - [e1.as_ref().map(|e| e.inverse()), ak.cloned(), e2.clone(), ak1.map(|e| e.inverse())] - } else { - [e1.clone(), ak1.cloned(), e2.as_ref().map(|e| e.inverse()), ak.map(|e| e.inverse())] - } - .into_iter() - .flatten() - .collect(); - // An arc the chamfer crossed is two lines through the crossing: the blend meets the - // shortened seam there. - let wire: mt::Wire = edges - .into_iter() - .flat_map(|e| { - let split = [(k, ak), ((k + 1) % nv, ak1)] - .into_iter() - .filter_map(|(i, arc)| arc.map(|arc| (i, arc.clone()))) - .find(|(_, arc)| arc.id() == e.id()) - .and_then(|(i, arc)| split_arcs.get(&i).map(|parts| (arc, parts))); - match split { - Some((arc, parts)) if e.orientation() == arc.orientation() => parts.clone(), - Some((_, parts)) => parts.iter().rev().map(|p| p.inverse()).collect(), - None => vec![e], - } - }) - .collect(); - let face = mt::Face::try_new(vec![wire], bf.clone()).map_err(|e| fail(&e.to_string()))?; - rec.blend(&face, [chain_e.id()]); - out.push(face); - } - let mut shells = solid.boundaries().clone(); - if let Some(sh) = shells.get_mut(si) { - *sh = out.into(); - } - Ok((Solid::try_new(shells).map_err(|e| fail(&format!("invalid solid: {e}")))?, rec)) - }) -} - -#[path = "curvecorner.rs"] -mod corner; -pub(crate) use corner::{corner_blend_style, param_on}; -// The planar corner builder the G2 corner work left in place of `corner_blend_style`'s sphere. -#[allow(unused_imports)] -pub(crate) use corner::corner_blend; - -#[cfg(test)] -#[path = "curveblend_tests.rs"] -mod tests; - -#[cfg(test)] -#[path = "curveblend_law_tests.rs"] -mod law_tests; diff --git a/crates/kernel/src/curveblend_law_tests.rs b/crates/kernel/src/curveblend_law_tests.rs deleted file mode 100644 index f9d5195d9..000000000 --- a/crates/kernel/src/curveblend_law_tests.rs +++ /dev/null @@ -1,315 +0,0 @@ -//! Chord-width and radius-law blends along curved edges: the width across the blend at every -//! station, and the radius along the edge, measured on the body the kernel built against values -//! worked out from the input geometry alone (the two cylinders' axes, the arc's axis). - -use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; -use solidcraft_geom::Vec3; - -use super::*; -use crate::blend::vtx; -use crate::blend_variable::{RadiusSpline, fillet_chord, fillet_variable, fillet_variable_points, fillet_variable_spline}; -use crate::{Body, BoolOp, boolean, box_solid, cylinder, fillet, measure, step_export}; - -/// An oblique boss: a rod of radius 8 whose axis leans 26.57° from the plate's normal, standing on -/// a 5 mm plate. The edge where its side meets the plate's top plane is an ellipse whose two faces -/// run from 63° to 117° apart around it. -fn oblique_boss() -> (Body, Vec3, Vec3) { - let plate = box_solid(Vec3::new(-40.0, -40.0, 0.0), Vec3::new(40.0, 40.0, 5.0)).unwrap(); - let base = Vec3::new(0.0, 0.0, -10.0); - let axis = Vec3::new(0.5, 0.0, 1.0).normalized().unwrap(); - let rod = cylinder(base, axis, 8.0, 30.0).unwrap(); - (boolean(&plate, &rod, BoolOp::Union).unwrap().unwrap(), base, axis) -} - -/// A 40 × 40 × 20 box whose front wall is an arc of radius 40 about a Z axis: `concave` cuts a -/// cylinder away from the front (the wall curves into the part), otherwise the part is the box -/// within the cylinder (the wall curves out). With the bottom arc's midpoint, the axis's base -/// point and the side of the wall the material is on (+1 away from the axis, −1 toward it). -fn arc_walled_box(concave: bool) -> (Body, Vec3, Vec3, f64) { - let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 20.0)).unwrap(); - let (axis, op, side) = - if concave { (Vec3::new(20.0, -30.0, 0.0), BoolOp::Cut, 1.0) } else { (Vec3::new(20.0, 70.0, 0.0), BoolOp::Intersect, -1.0) }; - let tool = cylinder(axis, Vec3::Z, 40.0, 20.0).unwrap(); - let body = boolean(&block, &tool, op).unwrap().unwrap(); - (body, axis + Vec3::new(0.0, side * 40.0, 0.0), axis, side) -} - -/// The blend face a blend built over `input`: the fitted surface that is on neither of the faces -/// it runs between (a boolean leaves the curved faces it kept as fitted surfaces themselves). -fn blend_face(input: &Body, body: &Body) -> Option { - use mt::ParametricSurface; - let on_input = |p: Vec3| input.solid.face_iter().any(|f| project(f, p, None).is_some_and(|(q, _, _)| q.dist(p) <= 1e-6)); - body.solid - .face_iter() - .filter(|f| matches!(f.oriented_surface(), mt::Surface::NurbsSurface(_))) - .find(|f| !on_input(from_p3(f.surface().subs(0.5, 0.5)))) - .cloned() -} - -/// The edges of the blend face's boundary, each once, with the point at the middle of it (the -/// blend is bounded by its two contacts and, at each end, an arc or the curve of an end face). -fn blend_boundary(input: &Body, body: &Body) -> Vec<(mt::Edge, Vec3)> { - let Some(f) = blend_face(input, body) else { return Vec::new() }; - let mut out: Vec<(mt::Edge, Vec3)> = Vec::new(); - for w in f.absolute_boundaries() { - for e in w.edge_iter() { - if out.iter().any(|(x, _)| x.id() == e.id()) { - continue; - } - let c = e.oriented_curve(); - let (lo, hi) = c.range_tuple(); - out.push((e.absolute_clone(), from_p3(c.subs((lo + hi) * 0.5)))); - } - } - out -} - -/// The edges of a contact: the boundary of the blend face whose middle point `side` picks out. -fn contact(input: &Body, body: &Body, side: &dyn Fn(Vec3) -> bool) -> Vec { - blend_boundary(input, body).into_iter().filter(|(_, m)| side(*m)).map(|(e, _)| e).collect() -} - -/// The fraction of the way along `edge` (its absolute front to its back) of the point of it -/// nearest `q`. -fn along_fraction(edge: &mt::Edge, q: Vec3) -> Option { - let e = edge.absolute_clone(); - let c = e.oriented_curve(); - let (lo, hi) = c.range_tuple(); - let steps = 512; - let mut at = vec![from_p3(c.subs(lo))]; - let mut run = vec![0.0]; - for i in 1..=steps { - let p = from_p3(c.subs(lo + (hi - lo) * i as f64 / steps as f64)); - run.push(run.last().copied()? + at.last().copied()?.dist(p)); - at.push(p); - } - let total = *run.last()?; - let d = |i: usize| at.get(i).map(|p| p.dist(q)).unwrap_or(f64::INFINITY); - let hint = (0..=steps).min_by(|x, y| d(*x).total_cmp(&d(*y))).unwrap_or(0); - let t = c.search_nearest_parameter(p3(q), lo + (hi - lo) * hint as f64 / steps as f64, 100)?; - let i = (((t - lo) / (hi - lo)) * steps as f64).clamp(0.0, steps as f64); - let (k, f) = (i.floor() as usize, i.fract()); - let (Some(a), Some(b)) = (run.get(k), run.get((k + 1).min(steps))) else { return None }; - Some((a + (b - a) * f) / total) -} - -/// The azimuth of `p` about the Z axis through `axis`. -fn azimuth(axis: Vec3, p: Vec3) -> f64 { - (p.y - axis.y).atan2(p.x - axis.x) -} - -/// The point of the curves running round the Z axis through `axis` at the azimuth `phi`. -fn at_azimuth(edges: &[mt::Edge], axis: Vec3, phi: f64) -> Option { - let off = |p: Vec3| { - let mut d = azimuth(axis, p) - phi; - while d > std::f64::consts::PI { - d -= std::f64::consts::TAU; - } - while d < -std::f64::consts::PI { - d += std::f64::consts::TAU; - } - d - }; - let (mut best, mut best_d) = (Vec3::ZERO, f64::INFINITY); - for e in edges { - let c = e.oriented_curve(); - let (lo, hi) = c.range_tuple(); - let steps = 512; - let mut at = lo; - let mut dist = f64::INFINITY; - for i in 0..=steps { - let t = lo + (hi - lo) * i as f64 / steps as f64; - let d = off(from_p3(c.subs(t))).abs(); - if d < dist { - (at, dist) = (t, d); - } - } - let step = (hi - lo) / steps as f64; - let (mut x0, mut x1) = ((at - step).max(lo), (at + step).min(hi)); - let g = 0.618_033_988_749_894_9; - for _ in 0..80 { - let (a, b) = (x1 - g * (x1 - x0), x0 + g * (x1 - x0)); - if off(from_p3(c.subs(a))).abs() < off(from_p3(c.subs(b))).abs() { - x1 = b; - } else { - x0 = a; - } - } - let t = 0.5 * (x0 + x1); - let d = off(from_p3(c.subs(t))).abs(); - if d < best_d { - (best, best_d) = (from_p3(c.subs(t)), d); - } - } - (best_d < 1e-6).then_some(best) -} - -/// A chord fillet along the cylinder-into-plane edge of an oblique boss — the two faces run from -/// 63° to 117° apart around it. The blend's chain stops at the seams between the patches a boolean -/// left of the rod's surface, where the end face is tangent to the rod; the cap that cuts the strip -/// back there is only placed for one radius, so a width that varies along the edge is refused -/// rather than approximated (the fixed radius of `fillet` along the same edge rolls). -#[test] -fn a_chord_fillet_along_an_oblique_boss_edge_is_refused() { - let (body, _, _) = oblique_boss(); - let pick = Vec3::new(7.5 + 8.944_271_909_999_16, 0.0, 5.0); - // A fixed radius rolls along the same chain: the edge itself is supported. - assert!(fillet(&body, &[pick], 2.5).is_ok()); - let e = fillet_chord(&body, &[pick], 4.0).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); -} - -/// A chord fillet along an arc whose two faces meet at a right angle: the width across the blend -/// is the chord, so the round is the one of radius `chord / √2` (checked against the constant -/// fillet of that radius) and its two contacts are that far apart at every station. -#[test] -fn chord_fillet_along_an_arc_edge() { - let (chord, r) = (3.0, 3.0 / 2f64.sqrt()); - let (body, mid, axis, _) = arc_walled_box(false); - let blended = fillet_chord(&body, &[mid], chord).unwrap(); - assert!(blended.validity().is_empty(), "{:?}", blended.validity()); - assert_eq!(blended.unmeshed_faces(), 0); - let plain = fillet(&body, &[mid], r).unwrap(); - let (made, exact) = (measure(&blended).unwrap().volume, measure(&plain).unwrap().volume); - assert!((made - exact).abs() < exact * 1e-6, "volume {made} vs {exact}"); - // The contact on the plane and the one on the wall at the same azimuth: the width across. - let plane = contact(&body, &blended, &|m| m.z.abs() < 1e-6); - let wall = contact(&body, &blended, &|m| m.z.abs() >= 1e-6); - assert!(!plane.is_empty() && !wall.is_empty(), "the contacts are not the plane's and the wall's"); - let mid_azimuth = azimuth(axis, mid); - let mut worst: f64 = 0.0f64; - let mut stations = 0; - for i in 1..12 { - let phi = mid_azimuth + (i as f64 / 12.0 - 0.5) * 0.9; - let (Some(p), Some(w)) = (at_azimuth(&plane, axis, phi), at_azimuth(&wall, axis, phi)) else { continue }; - stations += 1; - worst = worst.max((p.dist(w) - chord).abs()); - } - eprintln!("arc chord {chord}: worst width error {worst:.6} mm at {stations} stations"); - assert!(stations >= 9, "only {stations} stations measured"); - assert!(worst < 0.01, "the width across the blend is {worst} mm off the chord {chord}"); -} - -/// A chord fillet on a straight edge between planar faces is still the exact local round: the -/// same body, bit for bit, as the fillet of the radius the chord gives (a right angle: chord c is -/// r = c / √2). -#[test] -fn chord_fillet_on_a_straight_edge_is_unchanged() { - let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); - let (at, chord) = (Vec3::new(10.0, 10.0, 30.0), 4.0); - let f = fillet_chord(&b, &[at], chord).unwrap(); - let k = fillet(&b, &[at], chord / 2f64.sqrt()).unwrap(); - assert_eq!(step_export(&[&f], "part").unwrap(), step_export(&[&k], "part").unwrap()); - assert_eq!(f.unmeshed_faces(), 0); -} - -/// A variable radius along an arc edge: a ball whose radius is the law's at each station's fraction -/// of the edge's length rolls along it, and the setback on the planar face — the plane and the -/// wall meet at a right angle, so it is the section's radius — follows the law from end to end. -#[test] -fn variable_radius_along_an_arc_edge_follows_the_law() { - let (body, mid, axis, _) = arc_walled_box(false); - let edge = crate::surfaces::edge_near(&body, mid).unwrap(); - // Started from the edge's back end: the law runs the other way, as the positions are from the - // end nearest `start`. - let start = vtx(edge.absolute_back()); - // A wider law (2 → 4, the radius doubling over the arc) is out of reach of the fitted strip: - // the sections' own last spans cannot be held to the fit's accuracy there. That is refused, - // not approximated. - for wide in [4.0, 5.0] { - let e = fillet_variable(&body, mid, start, 2.0, wide).unwrap_err(); - assert!(e.to_string().contains("accuracy and section limits"), "2 -> {wide}: {e}"); - } - let (r0, r1) = (2.0, 3.4); - let blended = fillet_variable(&body, mid, start, r0, r1).unwrap(); - assert!(blended.validity().is_empty(), "{:?}", blended.validity()); - assert_eq!(blended.unmeshed_faces(), 0); - let law = RadiusSpline::through(&[(0.0, r0), (1.0, r1)], false); - // The law runs from the end nearest `start`: the chain's front here is the far end. - let want = if vtx(edge.absolute_back()).dist(start) < vtx(edge.absolute_front()).dist(start) { law.reversed() } else { law.clone() }; - // `start` is the chain's back end, so the law is read back to front there: r0 at the back, r1 - // at the front. - assert!((want.eval(1.0) - r0).abs() < 1e-12 && (want.eval(0.0) - r1).abs() < 1e-12); - // The blend's contact on the bottom plane is at 40 − r from the axis. - let plane = contact(&body, &blended, &|m| m.z.abs() < 1e-6); - assert!(!plane.is_empty(), "no contact on the bottom plane"); - let mut worst: f64 = 0.0; - let mut stations = 0; - let mut shown = Vec::new(); - for e in &plane { - let c = e.oriented_curve(); - let (lo, hi) = c.range_tuple(); - for i in 0..=32 { - let p = from_p3(c.subs(lo + (hi - lo) * i as f64 / 32.0)); - let measured = 40.0 - (p - axis).len(); - let along = along_fraction(&edge, p).unwrap(); - // Leave the two ends, where the caps cut the contact: the blend closes on the end - // faces there. - if !(0.04..=0.96).contains(&along) { - continue; - } - stations += 1; - if shown.len() < 3 || (0.45..0.55).contains(&along) { - shown.push((along, measured, want.eval(along))); - } - worst = worst.max((measured - want.eval(along)).abs()); - } - } - eprintln!("arc variable {r0} -> {r1}: worst radius error {worst:.6} mm at {stations} stations; law vs measured {shown:?}"); - assert!(stations >= 24, "only {stations} stations measured"); - assert!(worst < 0.02, "the section radius is {worst} mm off the law"); - // Wider, still inside what the strip holds: the same body as the exact straight-edge case of - // that law is not built here, but the radius is the law's at every station measured. -} - -/// A radius law that runs to zero at an end of a curved edge: refused by name. The blend would -/// close to the edge's end point, but the fitted strip pinches to a point there and the last span -/// of it cannot be held to the fit's accuracy: the straight-edge fillet, which closes exactly, is -/// the way (see `variable_radius_down_to_zero_at_one_end`). -#[test] -fn a_law_running_to_zero_along_a_curved_edge_is_refused() { - let (body, mid, _, _) = arc_walled_box(false); - let edge = crate::surfaces::edge_near(&body, mid).unwrap(); - for start in [vtx(edge.absolute_front()), vtx(edge.absolute_back())] { - let e = fillet_variable(&body, mid, start, 3.0, 0.0).unwrap_err(); - assert!(e.to_string().contains("runs to zero along a curved edge"), "{e}"); - let law = RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], radii: vec![0.0, 3.0] }; - assert!(fillet_variable_spline(&body, mid, mid, &law).is_err()); - // A law that stays clear of zero along it rolls: the blend is closed, a three-sided face - // where nothing closes it. - let made = fillet_variable(&body, mid, start, 3.0, 2.4).unwrap(); - assert!(made.validity().is_empty(), "{:?}", made.validity()); - let mesh = made.tessellate_with(5e-4, true).unwrap(); - let about = |o: Vec3| { - mesh.triangles - .iter() - .map(|t| (mesh.positions[t[0] as usize] - o).dot((mesh.positions[t[1] as usize] - o).cross(mesh.positions[t[2] as usize] - o)) / 6.0) - .sum::() - }; - assert!((about(Vec3::ZERO) - about(Vec3::new(-100.0, 50.0, 30.0))).abs() < 1e-2, "the mesh is not closed"); - } -} - -/// What a chord or a law the local geometry cannot hold is refused with: an error naming the size, -/// never a silent approximation and never a panic. -#[test] -fn a_chord_or_radius_the_faces_cannot_hold_is_refused() { - let (body, mid, _, _) = arc_walled_box(false); - // A chord of 30 across a 40 mm wide wall (r ≈ 21, past the side walls and the block). - let e = fillet_chord(&body, &[mid], 30.0).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); - assert!(fillet_chord(&body, &[mid], 3.0 / 2f64.sqrt()).is_ok()); - // A radius law too large for the wall. - assert!(fillet_variable(&body, mid, Vec3::new(0.0, 30.0, 0.0), 2.0, 30.0).is_err()); - assert!(fillet_variable(&body, mid, Vec3::new(0.0, 30.0, 0.0), 20.0, 20.0).is_err()); - // Non-finite, negative and zero-at-both-ends laws: refused before the geometry is touched. - let bad = |radii: Vec| RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], radii }; - assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![2.0, f64::NAN])).is_err()); - assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![2.0, f64::INFINITY])).is_err()); - assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![2.0, -1.0])).is_err()); - assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![0.0, 0.0])).is_err()); - assert!(fillet_variable_spline(&body, mid, mid, &RadiusSpline { degree: 1, knots: vec![0.0, 0.5, 1.0], radii: vec![2.0, 3.0] }).is_err()); - assert!(fillet_variable_points(&body, mid, mid, &[(0.0, 2.0), (1.5, 3.0)], false).is_err()); - // An edge the body does not have is refused by name, not approximated. - assert!(fillet_chord(&body, &[Vec3::new(500.0, 500.0, 500.0)], 3.0).is_err()); -} diff --git a/crates/kernel/src/curveblend_tests.rs b/crates/kernel/src/curveblend_tests.rs deleted file mode 100644 index ae70fc7c3..000000000 --- a/crates/kernel/src/curveblend_tests.rs +++ /dev/null @@ -1,731 +0,0 @@ -//! Independent analytic reference: the centre of a ball tangent to two perpendicular -//! cylinders lies on the intersection of their radius-offset cylinders. - -use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - -use super::*; -use crate::blend::plane_normal; -use crate::issue_851_tests::planned_volume; -use crate::{Body, BoolOp, boolean, cylinder, fillet}; - -#[test] -fn issue_1303_chamfer_open_rim_after_end_chamfer() { - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; - let rim = Region2 { - outer: Loop2 { - segs: vec![ - Seg2::Line { a: Vec2::new(31.0, -15.0), b: Vec2::new(31.0, -11.75) }, - Seg2::Line { a: Vec2::new(31.0, -11.75), b: Vec2::new(0.0, -11.75) }, - Seg2::Arc { center: Vec2::ZERO, radius: 11.75, start: -std::f64::consts::FRAC_PI_2, sweep: -std::f64::consts::PI }, - Seg2::Line { a: Vec2::new(0.0, 11.75), b: Vec2::new(31.0, 11.75) }, - Seg2::Line { a: Vec2::new(31.0, 11.75), b: Vec2::new(31.0, 15.0) }, - Seg2::Line { a: Vec2::new(31.0, 15.0), b: Vec2::new(0.0, 15.0) }, - Seg2::Arc { center: Vec2::ZERO, radius: 15.0, start: std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI }, - Seg2::Line { a: Vec2::new(0.0, -15.0), b: Vec2::new(31.0, -15.0) }, - ], - }, - holes: vec![], - }; - let mut body = crate::extrude(&Plane::XY, &[rim], 0.0, 13.0).unwrap().pop().unwrap(); - // Exact local end bevels, meeting at the four-face vertices (30, +/-11.75, 13). - body = crate::blend_corner::chamfer( - &body, - &[Vec3::new(31.0, 13.375, 13.0), Vec3::new(31.0, -13.375, 13.0), Vec3::new(31.0, 11.75, 8.0), Vec3::new(31.0, -11.75, 8.0)], - 1.0, - ) - .unwrap(); - let picks = [Vec3::new(-11.75, 0.0, 13.0), Vec3::new(15.0, 11.75, 13.0), Vec3::new(15.0, -11.75, 13.0)]; - let result = crate::chamfer(&body, &picks, 1.0).unwrap(); - assert!(result.validity().is_empty(), "{:?}", result.validity()); - assert_eq!(result.crossed_face_loops().unwrap(), 0); - // At height 12 + u, the removed half-ring area is pi/2 * (2*r*u + u^2). - // The straight strips end at min(31-u, 30+v), 0 <= v <= u. Their integral - // over 0 <= u <= 1 is 30 + 1/6; this includes both split end sections. - let expected = 30.0 + 1.0 / 6.0 + std::f64::consts::PI * (11.75 / 2.0 + 1.0 / 6.0); - let volume = |b: &Body| b.tessellate_with(0.0001, true).unwrap().measure().volume; - let removed = volume(&body) - volume(&result); - assert!((removed - expected).abs() < 0.02, "removed {removed}, expected {expected}"); - for p in [Vec3::new(30.5, 12.25, 12.5), Vec3::new(30.5, -12.25, 12.5)] { - assert!(result.solid.vertex_iter().any(|v| from_p3(v.point()).dist(p) < 1e-6)); - } - for selection in [vec![picks[0]], picks.into_iter().rev().collect()] { - let other = crate::chamfer(&body, &selection, 1.0).unwrap(); - assert!(other.validity().is_empty(), "{:?}", other.validity()); - assert!((volume(&body) - volume(&other) - expected).abs() < 0.02); - } - assert!(crate::chamfer(&body, &picks, 4.0).is_err()); -} - -fn tee(scale: f64, origin: Vec3) -> Body { - let main = cylinder(origin + Vec3::new(-40.0, 0.0, 0.0) * scale, Vec3::X, 15.0 * scale, 80.0 * scale).unwrap(); - let branch = cylinder(origin, Vec3::Z, 10.0 * scale, 35.0 * scale).unwrap(); - boolean(&main, &branch, BoolOp::Union).unwrap().unwrap() -} - -fn analytic_section(theta: f64, scale: f64, origin: Vec3) -> (Vec3, Vec3, Vec3) { - let centre = Vec3::new(13.0 * theta.cos(), 13.0 * theta.sin(), (324.0 - 169.0 * theta.sin().powi(2)).sqrt()); - let main = Vec3::new(centre.x, centre.y * 15.0 / 18.0, centre.z * 15.0 / 18.0); - let branch = Vec3::new(centre.x * 10.0 / 13.0, centre.y * 10.0 / 13.0, centre.z); - (origin + centre * scale, origin + main * scale, origin + branch * scale) -} - -fn nearest_blend(surfaces: &[mt::Surface], point: Vec3) -> (f64, Vec3) { - surfaces - .iter() - .filter_map(|s| { - let (u, v) = s.search_nearest_parameter(p3(point), None, 100)?; - let actual = from_p3(s.subs(u, v)); - let n = s.normal(u, v); - Some((actual.dist(point), Vec3::new(n.x, n.y, n.z).normalized()?)) - }) - .min_by(|a, b| a.0.total_cmp(&b.0)) - .unwrap() -} - -fn distance_to_analytic_arc(theta: f64, point: Vec3) -> f64 { - let (centre, main, branch) = analytic_section(theta, 1.0, Vec3::ZERO); - let a = (main - centre).normalized().unwrap(); - let b = (branch - centre).normalized().unwrap(); - let plane = a.cross(b).normalized().unwrap(); - let radial = point - centre; - let projected = radial - plane * radial.dot(plane); - let direction = projected.normalized().unwrap(); - let angle = a.dot(b).clamp(-1.0, 1.0).acos(); - let from_main = a.dot(direction).clamp(-1.0, 1.0).acos(); - let from_branch = b.dot(direction).clamp(-1.0, 1.0).acos(); - if (from_main + from_branch - angle).abs() < 1e-7 { point.dist(centre + direction * 3.0) } else { point.dist(main).min(point.dist(branch)) } -} - -fn distance_to_analytic_band(point: Vec3) -> f64 { - // The arc's XY azimuth stays between its two contacts' azimuths. Their difference - // for this tee is less than 0.1 rad; bracket generously around the query azimuth. - let azimuth = point.y.atan2(point.x); - let (mut lo, mut hi) = (azimuth - 0.3, azimuth + 0.3); - for _ in 0..55 { - let a = lo + (hi - lo) * 0.38196601125; - let b = lo + (hi - lo) * 0.61803398875; - if distance_to_analytic_arc(a, point) < distance_to_analytic_arc(b, point) { - hi = b; - } else { - lo = a; - } - } - distance_to_analytic_arc((lo + hi) * 0.5, point) -} - -#[test] -fn fitted_contact_edges_coincide_with_their_surface_boundaries() { - let sections: Vec> = (0..4) - .map(|k| { - (0..SAMPLES) - .map(|i| { - let theta = std::f64::consts::FRAC_PI_2 * (k as f64 + i as f64 / (SAMPLES - 1) as f64); - let (c, q1, q2) = analytic_section(theta, 1.0, Vec3::ZERO); - Section { c, q1, q2 } - }) - .collect() - }) - .collect(); - for k in 0..sections.len() { - let fit = crate::guard("contact consistency", || fit_sections(§ions, k, true, true)).unwrap(); - for (side, curve) in fit.contacts.iter().enumerate() { - let (lo, hi) = curve.range_tuple(); - for i in 0..=200 { - let parameter = lo + (hi - lo) * i as f64 / 200.0; - let edge = from_p3(curve.subs(parameter)); - let surface = from_p3(fit.surface.subs(side as f64, parameter)); - assert!(edge.dist(surface) < 1e-9, "contact-to-surface gap {}", edge.dist(surface)); - } - } - } -} - -#[test] -fn rolling_ball_matches_analytic_tee_and_contacts() { - for (scale, origin) in [(1.0, Vec3::ZERO), (0.25, Vec3::new(23.0, -17.0, 9.0))] { - let body = tee(scale, origin); - let point = origin + Vec3::new(0.0, 10.0, 125f64.sqrt()) * scale; - let blend = fillet(&body, &[point], 3.0 * scale).unwrap(); - assert!(blend.validity().is_empty(), "{:?}", blend.validity()); - let surfaces: Vec<_> = blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect(); - assert!(!surfaces.is_empty()); - let mut distance: f64 = 0.0; - let mut tangent_angle: f64 = 0.0; - for i in 0..96 { - // Offset the angular samples from patch seams; contact endpoints are tested below. - let theta = std::f64::consts::TAU * (i as f64 + 0.37) / 96.0; - let (centre, main, branch) = analytic_section(theta, scale, origin); - let a = (main - centre).normalized().unwrap(); - let b = (branch - centre).normalized().unwrap(); - let angle = a.dot(b).clamp(-1.0, 1.0).acos(); - for fraction in [0.0, 0.25, 0.5, 0.75, 1.0] { - // Spherical linear interpolation of the radial unit vectors, independent of - // the production rational control-point construction and fitting parameters. - let radial = (a * ((1.0 - fraction) * angle).sin() + b * (fraction * angle).sin()) / angle.sin(); - let exact = centre + radial * (3.0 * scale); - let (error, normal) = nearest_blend(&surfaces, exact); - distance = distance.max(error); - if fraction == 0.0 || fraction == 1.0 { - let want = (centre - exact).normalized().unwrap(); - tangent_angle = tangent_angle.max(normal.dot(want).abs().min(1.0).acos().to_degrees()); - } - } - } - assert!(distance <= 0.005, "scale {scale}: analytic surface deviation {distance} mm"); - assert!(tangent_angle <= 0.5, "scale {scale}: contact normals differ by {tangent_angle} degrees"); - - // The reverse direction uses points on the actual trimmed face mesh, so an - // untrimmed neighbouring surface cannot conceal an overshooting blend patch. - let mesh = blend.tessellate_with(0.002, true).unwrap(); - let mut reverse_distance: f64 = 0.0; - let mut probes = 0; - for point in mesh.positions.iter().step_by(19) { - let p = (*point - origin) / scale; - if (p.x * p.x + p.y * p.y).sqrt() <= 10.000001 - || (p.y * p.y + p.z * p.z).sqrt() <= 15.000001 - || !(10.0..20.0).contains(&p.z) - || p.x.abs() > 16.0 - { - continue; - } - probes += 1; - reverse_distance = reverse_distance.max(distance_to_analytic_band(p) * scale); - } - assert!(probes > 300, "only {probes} trimmed surface points checked"); - assert!(reverse_distance <= 0.005, "scale {scale}: reverse analytic deviation {reverse_distance} mm"); - eprintln!("scale {scale}: surface {distance:.9} mm, reverse {reverse_distance:.9} mm, contact normals {tangent_angle:.6} degrees"); - - let mut contact_count = 0; - for edge in Body::unique_edges(&blend.solid) { - let curve = edge.oriented_curve(); - let (lo, hi) = curve.range_tuple(); - let endpoints = [from_p3(curve.subs(lo)), from_p3(curve.subs(hi))].map(|p| (p - origin) / scale); - if endpoints.iter().any(|p| !(9.0..20.0).contains(&p.z) || p.x.abs() > 16.0) { - continue; - } - let branch = endpoints.iter().all(|p| ((p.x * p.x + p.y * p.y).sqrt() - 10.0).abs() < 1e-5); - let main = endpoints.iter().all(|p| ((p.y * p.y + p.z * p.z).sqrt() - 15.0).abs() < 1e-5); - if !branch && !main { - continue; - } - contact_count += 1; - for i in 0..=200 { - let p = (from_p3(curve.subs(lo + (hi - lo) * i as f64 / 200.0)) - origin) / scale; - let radius_error = if branch { ((p.x * p.x + p.y * p.y).sqrt() - 10.0).abs() } else { ((p.y * p.y + p.z * p.z).sqrt() - 15.0).abs() }; - assert!(radius_error * scale <= 0.002, "supporting cylinder deviation {} mm", radius_error * scale); - } - } - assert!(contact_count >= 4, "only {contact_count} contacts checked"); - } -} - -#[test] -fn rolling_ball_refinement_cap_returns_an_error_and_preserves_input() { - let body = tee(1.0, Vec3::ZERO); - let solid = body.deep_copy(); - let ids: Vec<_> = Body::unique_edges(&solid) - .iter() - .filter(|edge| { - let curve = edge.oriented_curve(); - let (lo, hi) = curve.range_tuple(); - let p = from_p3(curve.subs((lo + hi) * 0.5)); - p.z > 10.0 && ((p.x * p.x + p.y * p.y).sqrt() - 10.0).abs() < 0.01 && ((p.y * p.y + p.z * p.z).sqrt() - 15.0).abs() < 0.01 - }) - .map(mt::Edge::id) - .collect(); - assert!(!ids.is_empty()); - let before = crate::step_export(&[&body], "unchanged").unwrap(); - let input_before = crate::step_export(&[&Body::new(solid.clone()).unwrap()], "unchanged").unwrap(); - // Four sections deliberately undersample the saddle; production starts at 24. - let error = crate::guard("limited rolling ball", || curve_blend_with_limit(&solid, &ids, body.size(), 3.0, true, 4)).unwrap_err(); - assert!(error.to_string().contains("accuracy and section limits"), "{error}"); - assert_eq!(crate::step_export(&[&body], "unchanged").unwrap(), before); - assert_eq!(crate::step_export(&[&Body::new(solid.clone()).unwrap()], "unchanged").unwrap(), input_before); -} - -/// Plan-view construction of a round between two overlapping circles (a concave vertical edge -/// where two Z cylinders meet): the ball centre `f`, the circle and fillet arc angles, and the -/// area the round fills in, all independent of the kernel. -struct Gap { - /// Points along the round's arc in plan, contacts included. - arc: Vec, - /// Arc angles on circle 1, circle 2 and the fillet between the corner and the contacts. - angles: [f64; 3], - area: f64, -} - -fn gap(c1: Vec3, r1: f64, c2: Vec3, r2: f64, corner: Vec3, r: f64) -> Gap { - // The ball centre is r from both circles, on the corner's side of the centre line. - let (a, b) = (r1 + r, r2 + r); - let d = c1.dist(c2); - let u = (c2 - c1) * (1.0 / d); - let along = (a * a - b * b + d * d) / (2.0 * d); - let mut side = Vec3::new(-u.y, u.x, 0.0); - if (corner - c1).dot(side) < 0.0 { - side = side * -1.0; - } - let f = c1 + u * along + side * (a * a - along * along).sqrt(); - let (t1, t2) = (c1 + (f - c1) * (r1 / a), c2 + (f - c2) * (r2 / b)); - let angle = |c: Vec3, p: Vec3, q: Vec3| (p - c).normalized().unwrap().dot((q - c).normalized().unwrap()).clamp(-1.0, 1.0).acos(); - let angles = [angle(c1, t1, corner), angle(c2, corner, t2), angle(f, t2, t1)]; - // Shoelace over the three short arcs: circle 1 to the corner, circle 2 on, fillet back. - let mut ring = Vec::new(); - for (c, p, q) in [(c1, t1, corner), (c2, corner, t2), (f, t2, t1)] { - let (p0, q0) = (p - c, q - c); - let (a0, a1) = (p0.y.atan2(p0.x), q0.y.atan2(q0.x)); - let mut sweep = a1 - a0; - while sweep > std::f64::consts::PI { - sweep -= std::f64::consts::TAU; - } - while sweep < -std::f64::consts::PI { - sweep += std::f64::consts::TAU; - } - let rr = p0.len(); - for i in 0..20_000 { - let t = a0 + sweep * i as f64 / 20_000.0; - ring.push(c + Vec3::new(t.cos(), t.sin(), 0.0) * rr); - } - } - let area = ring.iter().map(|p| solidcraft_geom::Vec2::new(p.x, p.y)).collect::>().signed_area().abs(); - let (p, q) = ((t1 - f).normalized().unwrap(), (t2 - f).normalized().unwrap()); - let arc = (0..=8).map(|i| angles[2] * i as f64 / 8.0).map(|t| f + (p * ((angles[2] - t).sin()) + q * t.sin()) * (r / angles[2].sin())).collect(); - Gap { arc, angles, area } -} - -#[test] -fn rolling_ball_along_a_straight_edge_between_cylinders_trims_curved_end_seams() { - // Two Z cylinders crossing square to each other: the vertical lines where they meet are - // concave edges between two curved faces, and the blend ends on the planar caps, where the - // seams are arcs. - let (r1, r2, h, r) = (17.0, 9.5, 10.0, 6.0); - let (c1, c2) = (Vec3::ZERO, Vec3::new(r1, r2, 0.0)); - let a = cylinder(c1, Vec3::Z, r1, h).unwrap(); - let b = cylinder(c2, Vec3::Z, r2, h).unwrap(); - let body = boolean(&a, &b, BoolOp::Union).unwrap().unwrap(); - // The corner: one of the two points where the circles cross. - let d = c1.dist(c2); - let u = (c2 - c1) * (1.0 / d); - let along = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d); - let corner = c1 + u * along + Vec3::new(-u.y, u.x, 0.0) * (r1 * r1 - along * along).sqrt(); - let g = gap(c1, r1, c2, r2, corner, r); - let blend = fillet(&body, &[corner + Vec3::Z * (h / 2.0)], r).unwrap(); - assert!(blend.validity().is_empty(), "{:?}", blend.validity()); - // One blend face; the edge is replaced by two contact lines and two end arcs. - let (before, after) = (crate::measure(&body).unwrap(), crate::measure(&blend).unwrap()); - assert_eq!((after.faces, after.edges, after.vertices), (before.faces + 1, before.edges + 3, before.vertices + 2), "{before:?} -> {after:?}"); - // The round fills the gap over the full height. The caps gain it twice; the walls lose - // their arcs to the contacts and gain the round. - let (m0, m1) = (body.tessellate_with(0.0005, true).unwrap().measure(), blend.tessellate_with(0.0005, true).unwrap().measure()); - let volume = h * g.area; - assert!((m1.volume - m0.volume - volume).abs() < volume * 3e-3, "added volume {} vs {volume}", m1.volume - m0.volume); - let [a1, a2, af] = g.angles; - let area = 2.0 * g.area + h * (r * af - r1 * a1 - r2 * a2); - assert!((m1.area - m0.area - area).abs() < area.abs() * 3e-3, "added area {} vs {area}", m1.area - m0.area); - // The round is the analytic arc at every height, from contact to contact. - let surfaces: Vec<_> = blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect(); - let mut worst: f64 = 0.0; - for z in [0.0, 0.25, 0.5, 0.75, 1.0] { - for p in &g.arc { - worst = worst.max(nearest_blend(&surfaces, *p + Vec3::Z * (h * z)).0); - } - } - assert!(worst < 1e-3, "blend surface is {worst} mm off the analytic round"); -} - -#[test] -fn closed_curved_seam_is_not_supported() { - // A closed seam (one edge starting and ending at the same vertex, as a full cap circle can - // be in imported geometry) has no "between" two contacts, so trimming it is refused rather - // than guessed. - let body = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0).unwrap(); - let arc = body.solid.edge_iter().find(|e| !matches!(e.curve(), mt::Curve::Line(_))).expect("a cap arc"); - let circle = mt::Edge::new_unchecked(arc.front(), arc.front(), arc.curve()); - assert_eq!(circle.front(), circle.back()); - // Contacts on the circle itself: a third and two thirds of the way round. - let (lo, hi) = circle.curve().range_tuple(); - let on = |f: f64| mt::Vertex::new(circle.curve().subs(lo + (hi - lo) * f)); - for (a, b) in [(Some(on(1.0 / 3.0)), None), (None, Some(on(2.0 / 3.0))), (Some(on(1.0 / 3.0)), Some(on(2.0 / 3.0))), (None, None)] { - let err = trim_curved_seam(&circle, a, b, 20.0).unwrap_err(); - assert!(err.to_string().contains("not supported yet: a closed curved edge"), "{err}"); - } -} - -#[test] -fn rolling_ball_past_the_end_seam_is_too_large_and_reduces() { - // The crossing cylinders of the test above with the small one's centre inside the large - // one: a round of 3 would reach past the end of the cap arc it trims, so it is too large - // (a smaller one fits), and the largest that fits is the analytic round over the full height - // (checked on its surface: its added volume is too small beside the body's to measure). - let (r1, r2, d, h) = (17.0, 9.5, 12.0, 10.0); - let (c1, c2) = (Vec3::ZERO, Vec3::new(d, 0.0, 0.0)); - let body = boolean(&cylinder(c1, Vec3::Z, r1, h).unwrap(), &cylinder(c2, Vec3::Z, r2, h).unwrap(), BoolOp::Union).unwrap().unwrap(); - let along = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d); - let corner = Vec3::new(along, (r1 * r1 - along * along).sqrt(), 0.0); - let at = [corner + Vec3::Z * (h / 2.0)]; - let e = fillet(&body, &at, 3.0).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); - let (r, blend) = crate::fillet_max(&body, &at, 3.0).unwrap(); - assert!(r > 1.5 && r < 3.0, "{r}"); - assert!(blend.validity().is_empty(), "{:?}", blend.validity()); - let g = gap(c1, r1, c2, r2, corner, r); - let surfaces: Vec<_> = blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect(); - let mut worst: f64 = 0.0; - for z in [0.0, 0.25, 0.5, 0.75, 1.0] { - for p in &g.arc { - worst = worst.max(nearest_blend(&surfaces, *p + Vec3::Z * (h * z)).0); - } - } - assert!(worst < 1e-3, "blend surface is {worst} mm off the analytic round at r {r}"); -} - -#[test] -fn a_refused_edge_is_not_rolled_again_after_blends_far_from_it() { - // The crossing cylinders' seam refuses a round of 3 (too large). A bar joined to them has - // two straight edges at its far end that round on their own. Each blend there leaves the - // seam's surroundings as they were, so the seam is tried once, not once per blend, and the - // refusal is the same. - let (r1, r2, d, h) = (17.0, 9.5, 12.0, 10.0); - let body = boolean(&cylinder(Vec3::ZERO, Vec3::Z, r1, h).unwrap(), &cylinder(Vec3::new(d, 0.0, 0.0), Vec3::Z, r2, h).unwrap(), BoolOp::Union) - .unwrap() - .unwrap(); - let bar = crate::box_solid(Vec3::new(-80.0, -5.0, 0.0), Vec3::new(-10.0, 5.0, h)).unwrap(); - let body = boolean(&body, &bar, BoolOp::Union).unwrap().unwrap(); - let along = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d); - let seam = Vec3::new(along, (r1 * r1 - along * along).sqrt(), h / 2.0); - let ends = [Vec3::new(-80.0, -5.0, h / 2.0), Vec3::new(-80.0, 5.0, h / 2.0)]; - crate::blend::ROLLS.with(|n| n.set(0)); - let e = fillet(&body, &[seam, ends[0], ends[1]], 3.0).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); - let rolls = crate::blend::ROLLS.with(|n| n.get()); - assert_eq!(rolls, 1, "the seam was rolled {rolls} times"); - // The far edges alone still round. - assert!(fillet(&body, &ends, 3.0).is_ok()); -} - -/// At a knife edge (the plane and the wall's normals opposite) the ball's centre is the same -/// whichever face is side 1: `r` inside the plane and `r` outside the wall's cylinder. -#[test] -fn knife_edge_ball_centre_does_not_depend_on_the_side_order() { - const R: f64 = 21.0; - let tip = Vec3::new(62.0 + 1.0 / 6.0, 0.0, 5.0); - let slab = crate::box_solid(Vec3::new(0.0, -R, 0.0), Vec3::new(tip.x, 0.0, 10.0)).unwrap(); - let disc = cylinder(Vec3::new(tip.x, -R, 0.0), Vec3::Z, R, 10.0).unwrap(); - let body = boolean(&slab, &disc, BoolOp::Cut).unwrap().unwrap(); - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); - let plane = faces.iter().copied().find(|f| plane_normal(f).is_some_and(|n| n.y > 0.99)).unwrap(); - let wall = faces.iter().copied().find(|f| plane_normal(f).is_none()).unwrap(); - for r in [0.5, 2.0, 5.0] { - let centre = Vec3::new(tip.x - (4.0 * R * r).sqrt(), -r, tip.z); - // `cusp` is +1 when n1 × t points into the cusp: the wall's normal is −y, the plane's +y. - for (f1, f2, cusp) in [(wall, plane, 1.0), (plane, wall, -1.0)] { - let s = solve(&[f1], &[f2], tip, Vec3::Z, r, -1.0, cusp, None, 1e-6).unwrap(); - assert!(s.c.dist(centre) < 1e-6, "r={r} cusp={cusp}: centre {:?}, expected {centre:?}", s.c); - } - } -} - -/// #896: the seams where rounds run into the faces beside them are picked to be rounded again. -/// The faces meet tangentially there, so there is nothing to round: the refusal says so, rather -/// than that blending such an edge isn't supported yet. -#[test] -fn a_smooth_seam_is_refused_as_having_no_corner() { - let b = crate::box_solid(Vec3::ZERO, Vec3::new(150.0, 200.0, 70.0)).unwrap(); - let mut edges = Vec::new(); - for (x, y) in [(0.0, 0.0), (150.0, 0.0), (0.0, 200.0), (150.0, 200.0)] { - edges.push(Vec3::new(x, y, 35.0)); - } - for (a, z) in [(0.0, 0.0), (150.0, 0.0), (0.0, 70.0), (150.0, 70.0)] { - edges.push(Vec3::new(a, 100.0, z)); - } - for (y, z) in [(0.0, 0.0), (200.0, 0.0), (0.0, 70.0), (200.0, 70.0)] { - edges.push(Vec3::new(75.0, y, z)); - } - let rounded = fillet(&b, &edges, 10.0).unwrap(); - // The seam on the top face beside the round of the edge along y at x = 0, and the seam - // with the end face x = 0 beside the round of the top edge along y. - for seam in [Vec3::new(10.0, 100.0, 70.0), Vec3::new(0.0, 100.0, 60.0)] { - for chamfer in [false, true] { - let r = if chamfer { crate::chamfer(&rounded, &[seam], 1.0) } else { fillet(&rounded, &[seam], 1.0) }; - match r { - Err(KernelError::Invalid(m)) => assert!(m.contains("smooth") && m.contains("no corner"), "{m}"), - other => panic!("{seam:?}: {:?}", other.map(|_| "a body")), - } - } - } - // A sharp edge of a box with one round still takes a fillet beside the round's seams. - let one = fillet(&crate::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(), &[Vec3::new(40.0, 30.0, 10.0)], 5.0).unwrap(); - assert!(fillet(&one, &[Vec3::new(20.0, 0.0, 20.0)], 1.0).is_ok()); - assert!(matches!(fillet(&one, &[Vec3::new(35.0, 30.0, 10.0)], 1.0), Err(KernelError::Invalid(_)))); -} - -/// A 40 × 40 × 20 box whose front wall is an arc of radius 40 about a Z axis: `concave` cuts a -/// cylinder away from the front (the wall curves into the part), otherwise the part is the box -/// within the cylinder (the wall curves out). The arc meets the planar side walls x = 0 and -/// x = 40 at an angle, not square. With the bottom arc's midpoint, the axis's base point and the -/// side of the wall the material is on (+1 away from the axis, −1 toward it). -fn arc_walled_box(concave: bool) -> (Body, Vec3, Vec3, f64) { - let block = crate::box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 20.0)).unwrap(); - let (axis, op, side) = - if concave { (Vec3::new(20.0, -30.0, 0.0), BoolOp::Cut, 1.0) } else { (Vec3::new(20.0, 70.0, 0.0), BoolOp::Intersect, -1.0) }; - let tool = cylinder(axis, Vec3::Z, 40.0, 20.0).unwrap(); - let body = boolean(&block, &tool, op).unwrap().unwrap(); - (body, axis + Vec3::new(0.0, side * 40.0, 0.0), axis, side) -} - -/// Volume the blend removes along the bottom arc: the corner's cross-section at each distance -/// ρ from the axis (`depth(x)`, x ∈ [0, size] from the wall into the material), times the arc -/// of radius ρ between the side walls. -fn removed_volume(side: f64, size: f64, depth: impl Fn(f64) -> f64) -> f64 { - let steps = 4000; - let h = size / steps as f64; - (0..=steps) - .map(|i| { - let x = i as f64 * h; - let rho = 40.0 + side * x; - let w = if i == 0 || i == steps { - 1.0 - } else if i % 2 == 1 { - 4.0 - } else { - 2.0 - }; - w * depth(x) * 2.0 * rho * (20.0 / rho).asin() - }) - .sum::() - * h - / 3.0 -} - -#[test] -fn rolling_ball_along_an_arc_ends_in_side_walls_at_an_angle() { - // The bottom edge of an arc wall ends in the side walls at an angle (#556). The round is the - // torus about the cylinder's axis (centre circle of radius 40 ± r at height r), trimmed by - // the side walls; the chamfer is the cone between the two contacts. - let r = 2.0; - for concave in [true, false] { - let (body, mid, axis, side) = arc_walled_box(concave); - let v0 = planned_volume(&body); - for round in [true, false] { - let what = format!("{} {}", if concave { "concave" } else { "convex" }, if round { "fillet" } else { "chamfer" }); - let blend = if round { fillet(&body, &[mid], r) } else { crate::chamfer(&body, &[mid], r) }.unwrap_or_else(|e| panic!("{what}: {e}")); - assert!(blend.validity().is_empty(), "{what}: {:?}", blend.validity()); - let volume = planned_volume(&blend); - let removed = - if round { removed_volume(side, r, |x| r - (r * r - (r - x) * (r - x)).max(0.0).sqrt()) } else { removed_volume(side, r, |x| r - x) }; - assert!((v0 - volume - removed).abs() < removed * 3e-3, "{what}: removed {} vs {removed}", v0 - volume); - // The blend face stays between the side walls and, for the round, on the torus. - let surfaces: Vec<_> = - blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect(); - assert!(!surfaces.is_empty(), "{what}: no blend face"); - let mesh = blend.tessellate_with(0.0005, true).unwrap(); - let (lo, hi) = mesh.positions.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.x), hi.max(p.x))); - assert!(lo > -1e-3 && hi < 40.0 + 1e-3, "{what}: the blend runs past the side walls: x {lo}..{hi}"); - if round { - // Sections of the round across the arc: the quarter circle about the centre - // ring (radius 40 ± r about the axis, at height r) from contact to contact. - let ring = 40.0 + side * r; - let mut worst: f64 = 0.0; - for i in 0..=40 { - let x = 40.0 * i as f64 / 40.0; - for a in 1..8 { - let t = std::f64::consts::FRAC_PI_2 * a as f64 / 8.0; - let (rho, z) = (ring - side * r * t.cos(), r - r * t.sin()); - let dx = x - axis.x; - let dy = (rho * rho - dx * dx).sqrt() * if concave { 1.0 } else { -1.0 }; - let p = Vec3::new(x, axis.y + dy, z); - worst = worst.max(nearest_blend(&surfaces, p).0); - } - } - assert!(worst < 1e-3, "{what}: blend surface is {worst} mm off the torus"); - } - } - } -} - -#[test] -fn rolling_ball_past_a_slanted_end_face_is_too_large_and_reduces() { - // On the outward-curving wall a round of 4 would run its bottom contact into the back face - // before it reaches the side wall (the contact circle of radius 36 meets x = 0 at y ≈ 40.07): - // too large, and the largest that fits rounds the edge. - let (body, mid, _, _) = arc_walled_box(false); - let e = fillet(&body, &[mid], 4.0).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); - let (r, blend) = crate::fillet_max(&body, &[mid], 4.0).unwrap(); - assert!(r > 3.0 && r < 4.0, "{r}"); - assert!(blend.validity().is_empty(), "{:?}", blend.validity()); -} - -#[test] -fn rolling_ball_runs_into_a_knife_edge_tip() { - // The corner of a block outside a cylinder of radius 21 about (21, −21): its wall meets the - // back face y = 0 tangentially at (21, 0) and the left face x = 0 at (0, −21), knife-edge - // tips at both ends of the arc. The round of the bottom arc runs into both, cut off by the - // end faces' planes, which touch the wall contact at the tips without crossing it: at - // distance ρ from the axis it runs from x = 0 to y = 0, ρ (asin(21 / ρ) − acos(21 / ρ)). - let block = crate::box_solid(Vec3::new(0.0, -21.0, 0.0), Vec3::new(21.0, 0.0, 10.0)).unwrap(); - let body = boolean(&block, &cylinder(Vec3::new(21.0, -21.0, -1.0), Vec3::Z, 21.0, 12.0).unwrap(), BoolOp::Cut).unwrap().unwrap(); - let mid = Vec3::new(21.0 - 21.0 * std::f64::consts::FRAC_1_SQRT_2, -21.0 + 21.0 * std::f64::consts::FRAC_1_SQRT_2, 0.0); - let r = 2.0; - let blend = fillet(&body, &[mid], r).unwrap(); - assert!(blend.validity().is_empty(), "{:?}", blend.validity()); - let (n, h) = (4000, r / 4000.0); - let removed = (0..=n) - .map(|i| { - let x = i as f64 * h; - let rho = 21.0 + x; - let w = if i == 0 || i == n { - 1.0 - } else if i % 2 == 1 { - 4.0 - } else { - 2.0 - }; - w * (r - (r * r - (r - x) * (r - x)).max(0.0).sqrt()) * rho * ((21.0 / rho).asin() - (21.0 / rho).acos()) - }) - .sum::() - * h - / 3.0; - let got = planned_volume(&body) - planned_volume(&blend); - assert!((got - removed).abs() < removed * 5e-3, "removed {got} vs {removed}"); -} - -#[test] -fn rolling_ball_turns_about_a_rounded_corner_of_its_radius() { - // The box with the inward-curving wall, its 60° corner at x = 0 rounded (r 2) first. The - // bottom edges then run: the side wall's, the corner round's (an arc of radius 2) and the - // arc wall's into the slanted side wall at x = 40. Rounded again with r 2 the ball can't - // roll round the corner: it turns about one point there, and the blend is a piece of sphere. - // It is what the rolling round tends to as its radius tends to the corner's, too large past - // it, and its mesh is closed. - let (body, _, _, _) = arc_walled_box(true); - let body = fillet(&body, &[Vec3::new(0.0, 4.641016151377546, 10.0)], 2.0).unwrap(); - // The corner round's centre is 4 from the corner along its bisector, (2, 8.105): its arc's - // middle is 2 back toward the corner. - let ends = [Vec3::new(0.0, 25.0, 0.0), Vec3::new(1.0, 6.373, 0.0), Vec3::new(20.0, 10.0, 0.0)]; - let v0 = planned_volume(&body); - let removed = |r: f64| { - let b = fillet(&body, &ends, r).unwrap_or_else(|e| panic!("r {r}: {e}")); - assert!(b.validity().is_empty(), "r {r}: {:?}", b.validity()); - v0 - planned_volume(&b) - }; - let (a, b, at) = (removed(1.96), removed(1.98), removed(2.0)); - let expected = 2.0 * b - a; - assert!((at - expected).abs() < expected * 2e-3, "removed {at} at r 2, {a} and {b} before it"); - let e = fillet(&body, &ends, 2.5).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); - let (r, _) = crate::fillet_max(&body, &ends, 2.5).unwrap(); - assert!(r > 1.5 && r <= 2.0 + 1e-9, "{r}"); -} - -#[test] -fn rolling_ball_along_a_straight_edge_ends_in_a_curved_face() { - // The box with the inward-curving wall: the bottom edge of the side wall x = 0 runs from the - // back to the curved wall (#556). The round of radius 2 along it is cut off by that wall: - // at d from the side wall it runs from y = −30 + √(40² − (d − 20)²) to the back at y = 40. - let (body, _, _, _) = arc_walled_box(true); - let r = 2.0; - for round in [true, false] { - let blend = - if round { fillet(&body, &[Vec3::new(0.0, 25.0, 0.0)], r) } else { crate::chamfer(&body, &[Vec3::new(0.0, 25.0, 0.0)], r) }.unwrap(); - assert!(blend.validity().is_empty(), "{:?}", blend.validity()); - let (n, h) = (4000, r / 4000.0); - let removed = (0..=n) - .map(|i| { - let d = i as f64 * h; - let w = if i == 0 || i == n { - 1.0 - } else if i % 2 == 1 { - 4.0 - } else { - 2.0 - }; - let depth = if round { r - (r * r - (r - d) * (r - d)).max(0.0).sqrt() } else { r - d }; - w * depth * (40.0 - (-30.0 + (1600.0 - (d - 20.0) * (d - 20.0)).sqrt())) - }) - .sum::() - * h - / 3.0; - let (m0, m1) = (body.tessellate_with(0.0005, true).unwrap(), blend.tessellate_with(0.0005, true).unwrap()); - let got = m0.measure().volume - m1.measure().volume; - assert!((got - removed).abs() < removed * 3e-3, "round {round}: removed {got} vs {removed}"); - let volume_about = |o: Vec3| { - let at = |i: u32| m1.positions[i as usize] - o; - m1.triangles.iter().map(|t| at(t[0]).dot(at(t[1]).cross(at(t[2]))) / 6.0).sum::() - }; - let shift = volume_about(Vec3::ZERO) - volume_about(Vec3::new(-100.0, 50.0, 30.0)); - assert!(shift.abs() < 1e-2, "round {round}: the mesh is not closed (volume moves {shift} with the origin)"); - } -} - -#[test] -fn chamfer_a_chain_of_a_line_and_an_arc_into_a_slanted_end() { - // A 40 × 40 block, 20 high, whose front runs straight for 20 and then along an arc of - // radius 29 about (20, 29), tangent to it, up to (40, 8): the right face meets the arc at an - // angle. The top front chain chamfered by 2 (the planes' and the cone's sections are 2 × 2 - // corners, 2 − w high at w in from the edge): 2 a millimetre along the line, and along the - // arc out to the right face, at each distance ρ from its axis, the height times the arc of - // radius ρ inside x ≤ 40. - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; - let start = -std::f64::consts::FRAC_PI_2; - let end = (-21.0f64).atan2(20.0); - let segs = vec![ - Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(20.0, 0.0) }, - Seg2::Arc { center: Vec2::new(20.0, 29.0), radius: 29.0, start, sweep: end - start }, - Seg2::Line { a: Vec2::new(40.0, 8.0), b: Vec2::new(40.0, 40.0) }, - Seg2::Line { a: Vec2::new(40.0, 40.0), b: Vec2::new(0.0, 40.0) }, - Seg2::Line { a: Vec2::new(0.0, 40.0), b: Vec2::new(0.0, 0.0) }, - ]; - let body = crate::extrude(&Plane::XY, &[Region2 { outer: Loop2 { segs }, holes: vec![] }], 0.0, 20.0).unwrap().pop().unwrap(); - let volume = |b: &Body| b.tessellate_with(0.0005, true).unwrap().measure().volume; - let made = crate::chamfer(&body, &[Vec3::new(10.0, 0.0, 20.0)], 2.0).unwrap(); - let n = 2000; - let h = 2.0 / n as f64; - let arc = (0..=n) - .map(|i| { - let rho = 27.0 + i as f64 * h; - let w = if i == 0 || i == n { 1.0 } else { [2.0, 4.0][i % 2] }; - w * (rho - 27.0) * rho * (20.0 / rho).asin() - }) - .sum::() - * h - / 3.0; - let want = 40.0 + arc; - let got = volume(&body) - volume(&made); - assert!((got - want).abs() < want * 1e-3, "removed {got} vs {want}"); -} - -/// #1667: an R1 round around the end of a long bar whose four long edges are R5. The chain is -/// 290 mm lines and quarter turns of 7.85 mm, so the lines' sections are spaced far wider than -/// the turns'; borrowing the turns' sections for the lines' ends made their strips overshoot and -/// fold back past the joints, the strips' meshes folded with them, and the measured volume came -/// out thousands of mm³ off. The R1 pipe is exact: the corner's section, `1 - π/4`, along the -/// lines, and round each turn's axis at the section's centroid (Pappus). -#[test] -fn round_along_long_lines_and_small_turns_measures_its_volume() { - use std::f64::consts::{FRAC_PI_2, FRAC_PI_4}; - let (w, d, h) = (300.0, 60.0, 40.0); - let bar = crate::build::box_solid(Vec3::new(-w / 2.0, 0.0, 0.0), Vec3::new(w / 2.0, d, h)).unwrap(); - let long = [Vec3::new(-w / 2.0, d / 2.0, 0.0), Vec3::new(w / 2.0, d / 2.0, 0.0), Vec3::new(-w / 2.0, d / 2.0, h), Vec3::new(w / 2.0, d / 2.0, h)]; - let rounded = fillet(&bar, &long, 5.0).unwrap(); - // The rolling ball along the end face's loop (the exact blends would take this loop; a - // loop next to free-form faces, as in the issue, comes here). - let ids: Vec = crate::body::Body::unique_edges(&rounded.solid) - .into_iter() - .filter(|e| [e.front(), e.back()].iter().all(|v| crate::blend::vtx(v).y.abs() < 1e-9)) - .map(|e| e.id()) - .collect(); - assert_eq!(ids.len(), 8); - let (solid, _) = crate::guard("test", || curve_blend(&rounded.solid, &ids, rounded.size(), 1.0, true)).unwrap(); - let body = Body::new(solid).unwrap(); - assert!(body.validity().is_empty(), "{:?}", body.validity()); - let section = 1.0 - FRAC_PI_4; - // The section's centroid lies this far from its corner along each side. - let inset = (5.0 / 6.0 - FRAC_PI_4) / section; - let lines = 2.0 * (w - 10.0) + 2.0 * (h - 10.0); - let turns = 4.0 * FRAC_PI_2 * (5.0 - inset); - let want = w * d * h - 4.0 * 25.0 * section * d - section * (lines + turns); - let m = crate::measure(&body).unwrap(); - assert!((m.volume - want).abs() < 1e-5 * want, "{} vs {want}", m.volume); - // Centred across the bar, as the part is. - assert!(m.centroid.x.abs() < 1e-3, "centre of mass x {}", m.centroid.x); -} diff --git a/crates/kernel/src/curvecorner.rs b/crates/kernel/src/curvecorner.rs deleted file mode 100644 index a3dbc8892..000000000 --- a/crates/kernel/src/curvecorner.rs +++ /dev/null @@ -1,1246 +0,0 @@ -//! Corners where rolling-ball blends meet on faces of any surface (the arc wall of an extruded -//! profile and the edges round it): what [`crate::blend_corner`] does for straight edges between -//! planes, with each blend fitted as in the parent module. -//! -//! Each blended edge's strip (its rolling-ball sections, fitted) runs a little past both ends. -//! Every end vertex has three faces and three edges. There: -//! - one blended edge: the strip ends where the third face cuts it, between where its contacts -//! cross the other two edges; -//! - two: the strips cut each other along a crease, from where their contacts cross on the face -//! they share to the third edge. When one strip's contact -//! reaches further along the third edge, the other's ends on the crease alone and the first -//! runs on beyond it to end on the other's third face; -//! - three (one radius): each strip ends at its section through the ball touching all three -//! faces, and a piece of that ball's sphere fills the corner. - -use std::cell::Cell; -use std::collections::{HashMap, HashSet}; - -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, builder}; - -use super::{ - Guide, MAX_SAMPLES, SAMPLES, Section, fit_sections, in_proportion, knife_convex, knife_start, nearest_on, project, section_fits, solve_from, - unsupported, -}; -use crate::blend::{too_large, vtx}; -use crate::body::{Solid, from_p3, p3, v3}; -use crate::bridge::Frame; -use crate::record::Rebuild; -use crate::{KernelError, Result}; - -fn fail(m: &str) -> KernelError { - KernelError::Failed(format!("blend corner: {m}")) -} - -/// One blended edge's strip: the fitted rolling-ball surface (u across, from the contact with -/// side `fa` at 0 to side `fb`'s at 1; v along the edge from its front, running on past both -/// ends), its contacts (in v) and its sections. -struct Strip { - edge: mt::Edge, - fa: usize, - fb: usize, - surface: mt::Surface, - contacts: [mt::Curve; 2], - /// v of the sections at the edge's front and back vertex. - ends: [f64; 2], - /// +1 when the surface's normal points out of the material, −1 when into it. - flip: f64, - /// −1 for a convex edge (the ball inside the material), +1 for a concave one. - sigma: f64, - /// Sections with their v. - sections: Vec<(f64, Section)>, -} - -impl Strip { - fn row(&self, f: usize) -> Result { - if f == self.fa { - Ok(0) - } else if f == self.fb { - Ok(1) - } else { - Err(fail("a face beside a blend")) - } - } - - fn contact(&self, f: usize) -> Result<&mt::Curve> { - self.contacts.get(self.row(f)?).ok_or_else(|| fail("contact")) - } - - /// u of the contact with face `f`. - fn u(&self, f: usize) -> Result { - self.row(f).map(|i| i as f64) - } - - fn at(&self, u: f64, v: f64) -> Vec3 { - use mt::ParametricSurface; - from_p3(self.surface.subs(u, v)) - } - - /// The edge's own stretch of v. - fn own(&self) -> (f64, f64) { - let [a, b] = self.ends; - (a.min(b), a.max(b)) - } - - /// v of the edge's end at `v`, and +1 when the strip runs on past it toward larger v. - fn end_at(&self, v: &mt::Vertex) -> (f64, f64) { - let [a, b] = self.ends; - if self.edge.front() == v { (a, -1.0) } else { (b, 1.0) } - } - - /// The strip's nearest point to `x` (u and v within it): from the section whose ball is - /// nearest, by Gauss-Newton steps kept within the strip. - fn nearest(&self, x: Vec3) -> Option<(f64, f64)> { - use mt::ParametricSurface; - let (v0, s0) = self.sections.iter().min_by(|a, b| a.1.c.dist(x).total_cmp(&b.1.c.dist(x)))?; - let (a, b, w) = (s0.q1 - s0.c, s0.q2 - s0.c, x - s0.c); - let angle = |p: Vec3, q: Vec3| (p.dot(q) / (p.len() * q.len()).max(1e-300)).clamp(-1.0, 1.0).acos(); - let total = angle(a, b); - let mut uv = ((angle(a, w) / total.max(1e-12)).clamp(0.0, 1.0), *v0); - let dist = |uv: (f64, f64)| from_p3(self.surface.subs(uv.0, uv.1)).dist(x); - let mut d = dist(uv); - for _ in 0..50 { - let p = from_p3(self.surface.subs(uv.0, uv.1)); - let (su, sv) = (self.surface.uder(uv.0, uv.1), self.surface.vder(uv.0, uv.1)); - let (su, sv) = (Vec3::new(su.x, su.y, su.z), Vec3::new(sv.x, sv.y, sv.z)); - let r = x - p; - let (a11, a12, a22) = (su.dot(su), su.dot(sv), sv.dot(sv)); - let (b1, b2) = (su.dot(r), sv.dot(r)); - let det = a11 * a22 - a12 * a12; - if !(det.abs() > 1e-300) { - break; - } - let (mut du, mut dv) = ((b1 * a22 - b2 * a12) / det, (a11 * b2 - a12 * b1) / det); - let mut moved = false; - for _ in 0..30 { - let next = ((uv.0 + du).clamp(0.0, 1.0), (uv.1 + dv).clamp(0.0, 1.0)); - let dn = dist(next); - if dn <= d { - moved = (next.0 - uv.0).abs() + (next.1 - uv.1).abs() > 1e-15; - uv = next; - d = dn; - break; - } - du *= 0.5; - dv *= 0.5; - } - if !moved { - break; - } - } - Some(uv) - } -} - -/// Signed distance from a surface, positive out of the material; each search starts where the -/// last ended (the points asked about come in small steps). A strip's is measured to its -/// nearest point within it: past a contact, to the contact along the face there. -enum Away<'a> { - Face(Box<(mt::Surface, Cell>)>), - Strip(&'a Strip), -} - -impl<'a> Away<'a> { - fn face(f: &mt::Face) -> Self { - Away::Face(Box::new((f.oriented_surface(), Cell::new(None)))) - } - - fn strip(s: &'a Strip) -> Self { - Away::Strip(s) - } - - fn at(&self, x: Vec3) -> Option { - use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - match self { - Away::Face(face) if matches!(face.0, mt::Surface::Plane(_)) => nearest_on(&face.0, &face.1, x).map(|(q, n, _)| (x - q).dot(n)), - Away::Face(face) => { - let (surface, last) = (&face.0, &face.1); - // The nearest of the search from the last answer, a fresh one and either kept - // within the surface's parameters: past them a conic's patch runs on round to - // its far side, where a search can settle. - let (ru, rv) = surface.try_range_tuple(); - let ((u0, u1), (v0, v1)) = (ru.unwrap_or((f64::NEG_INFINITY, f64::INFINITY)), rv.unwrap_or((f64::NEG_INFINITY, f64::INFINITY))); - let inside = |uv: (f64, f64)| uv.0 >= u0 - 1e-9 && uv.0 <= u1 + 1e-9 && uv.1 >= v0 - 1e-9 && uv.1 <= v1 + 1e-9; - let warm = last.get().and_then(|h| surface.search_nearest_parameter(p3(x), Some(h), 20)); - let mut found: Vec<(f64, f64)> = warm.into_iter().collect(); - if !warm.is_some_and(inside) { - found.extend(surface.search_nearest_parameter(p3(x), None, 100)); - } - let clamped: Vec<(f64, f64)> = found.iter().map(|(u, v)| (u.clamp(u0, u1), v.clamp(v0, v1))).collect(); - found.extend(clamped); - let d = |uv: &(f64, f64)| from_p3(surface.subs(uv.0, uv.1)).dist(x); - let uv = found.into_iter().filter(|uv| d(uv).is_finite()).min_by(|a, b| d(a).total_cmp(&d(b)))?; - last.set(Some(uv)); - let q = from_p3(surface.subs(uv.0, uv.1)); - let n = surface.normal(uv.0, uv.1); - Some((x - q).dot(Vec3::new(n.x, n.y, n.z).normalized()?)) - } - Away::Strip(s) => { - let (u, v) = s.nearest(x)?; - let q = from_p3(s.surface.subs(u, v)); - let n = s.surface.normal(u, v); - Some((x - q).dot(Vec3::new(n.x, n.y, n.z).normalized()?) * s.flip) - } - } - } -} - -/// Unit direction along a curve at `t`. -fn tangent(c: &mt::Curve, t: f64) -> Option { - use mt::ParametricCurve; - let d = c.der(t); - Vec3::new(d.x, d.y, d.z).normalized() -} - -/// Nearest parameter on `c` to `x`, started from the nearest of a few samples. -/// The radius of edge `e` seen along the unit `axis`: its points, moved along the axis into one -/// plane, all on one circle (within `tol`). -fn radius_along(e: &mt::Edge, axis: Vec3, tol: f64) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let curve = e.curve(); - let (t0, t1) = curve.range_tuple(); - let at = |f: f64| { - let p = from_p3(curve.subs(t0 + (t1 - t0) * f)); - p - axis * axis.dot(p) - }; - let (a, u, v) = (at(0.0), at(0.5) - at(0.0), at(1.0) - at(0.0)); - let w = u.cross(v); - if w.len2() < 1e-24 || w.normalized()?.dot(axis).abs() < 1.0 - 1e-6 { - return None; - } - let o = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2())); - let rho = o.dist(a); - (0..=16).map(|i| at(i as f64 / 16.0)).all(|p| (p.dist(o) - rho).abs() <= tol).then_some(rho) -} - -/// The parameter of `c`'s point nearest `x`: the nearest of 65 samples, refined where that -/// comes nearer. -pub(crate) fn param_on(c: &mt::Curve, x: Vec3) -> Option { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - let (lo, hi) = c.range_tuple(); - let d = |t: f64| from_p3(c.subs(t)).dist(x); - let hint = (0..=64).map(|i| lo + (hi - lo) * i as f64 / 64.0).min_by(|a, b| d(*a).total_cmp(&d(*b)))?; - let t = c.search_nearest_parameter(p3(x), hint, 100).unwrap_or(hint).clamp(lo, hi); - Some(if d(t) <= d(hint) { t } else { hint }) -} - -/// Where curve `a` crosses curve `b` on face `f`, both lying in it: its parameter on `a` and -/// the point. Of several, the one within `own` (a range of `a`'s parameter) nearest `near`. -fn cross(a: &mt::Curve, b: &mt::Curve, f: &mt::Face, near: Vec3, own: (f64, f64), tol: f64) -> Option<(f64, Vec3)> { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - let (a0, a1) = a.range_tuple(); - let (b0, b1) = b.range_tuple(); - let surface = f.oriented_surface(); - let last = Cell::new(None); - let hint = Cell::new(None::); - // Signed distance across `b` in the face, and how far `b`'s nearest point is. - // `b` sampled once (an intersection curve is slow to evaluate). - let along_b: Vec<(f64, Vec3)> = (0..=64).map(|i| b0 + (b1 - b0) * i as f64 / 64.0).map(|t| (t, from_p3(b.subs(t)))).collect(); - let lateral = |s: f64| -> Option<(f64, f64)> { - let x = from_p3(a.subs(s)); - // From the last answer when that is still nearest, else from the nearest sample of `b` - // (a search from the far end of a short arc can stay there). - let d = |t: f64| from_p3(b.subs(t)).dist(x); - let warm = hint.get().map(|h| b.search_nearest_parameter(p3(x), h, 50).unwrap_or(h).clamp(b0, b1)); - let (start, ds) = along_b.iter().map(|(t, p)| (*t, p.dist(x))).min_by(|p, q| p.1.total_cmp(&q.1))?; - let t = match warm { - Some(w) if d(w) <= ds => w, - _ => { - let cold = b.search_nearest_parameter(p3(x), start, 50).unwrap_or(start).clamp(b0, b1); - match warm { - Some(w) if d(w) <= d(cold).min(ds) => w, - _ if d(cold) <= ds => cold, - _ => start, - } - } - }; - hint.set(Some(t)); - let y = from_p3(b.subs(t)); - let (_, n, _) = nearest_on(&surface, &last, y)?; - let m = n.cross(tangent(b, t)?).normalized()?; - Some(((x - y).dot(m), x.dist(y))) - }; - let steps = 256; - let samples: Vec<(f64, Option<(f64, f64)>)> = (0..=steps) - .map(|i| { - let s = a0 + (a1 - a0) * i as f64 / steps as f64; - (s, lateral(s)) - }) - .collect(); - // Only where `a` comes within a sample's step of `b` (elsewhere the side flips only round - // an end of `b`). - let step = samples.windows(2).map(|w| from_p3(a.subs(w[1].0)).dist(from_p3(a.subs(w[0].0)))).fold(0.0, f64::max); - let close = |d: f64| d <= 2.0 * step + tol; - let mut found: Vec<(f64, Vec3)> = Vec::new(); - for w in samples.windows(2) { - let [(s0, Some((h0, d0))), (s1, Some((h1, d1)))] = w else { continue }; - if h1.abs() <= tol && *d1 <= tol { - found.push((*s1, from_p3(a.subs(*s1)))); - continue; - } - if (*h0 < 0.0) == (*h1 < 0.0) || !(close(*d0) || close(*d1)) { - continue; - } - let (mut lo, mut hi, glo) = (*s0, *s1, *h0); - hint.set(None); - for _ in 0..60 { - let m = (lo + hi) * 0.5; - let Some((hm, _)) = lateral(m) else { break }; - if (hm < 0.0) == (glo < 0.0) { - lo = m; - } else { - hi = m; - } - } - let s = (lo + hi) * 0.5; - hint.set(None); - if lateral(s).is_some_and(|(_, d)| d <= tol) { - found.push((s, from_p3(a.subs(s)))); - } - } - if let Some((s, Some((h, d)))) = samples.first() - && h.abs() <= tol - && *d <= tol - { - found.push((*s, from_p3(a.subs(*s)))); - } - // Touching without crossing: through an end of `b` (an edge the blend uses up to its far - // vertex), where the side `b` is measured from turns over. Where the distance comes down - // to nothing. - for w in samples.windows(3) { - let [(s0, Some((_, d0))), (_, Some((_, d1))), (s2, Some((_, d2)))] = w else { continue }; - if !(d1 <= d0 && d1 <= d2 && close(*d1)) { - continue; - } - let gap = |s: f64| { - hint.set(None); - lateral(s).map_or(f64::INFINITY, |x| x.1) - }; - let (mut lo, mut hi) = (*s0, *s2); - for _ in 0..80 { - let (x, y) = (lo + (hi - lo) * 0.381_966, lo + (hi - lo) * 0.618_034); - if gap(x) < gap(y) { - hi = y; - } else { - lo = x; - } - } - let s = (lo + hi) * 0.5; - if gap(s) <= tol && !found.iter().any(|f| (f.0 - s).abs() <= (a1 - a0) * 1e-6) { - found.push((s, from_p3(a.subs(s)))); - } - } - let slack = (a1 - a0) * 1e-6; - let outside = |s: f64| s < own.0 - slack || s > own.1 + slack; - found.into_iter().min_by(|x, y| outside(x.0).cmp(&outside(y.0)).then(x.1.dist(near).total_cmp(&y.1.dist(near)))) -} - -/// Where curve `c` crosses `side`'s surface: its parameter and the point; of several, the one -/// nearest `near`. -fn reach(c: &mt::Curve, side: &Away, near: Vec3, tol: f64) -> Option<(f64, Vec3)> { - use mt::{BoundedCurve, ParametricCurve}; - let (lo, hi) = c.range_tuple(); - let g = |s: f64| side.at(from_p3(c.subs(s))).filter(|x| x.is_finite()); - let steps = 256; - let samples: Vec<(f64, Option)> = (0..=steps) - .map(|i| { - let s = lo + (hi - lo) * i as f64 / steps as f64; - (s, g(s)) - }) - .collect(); - let mut found: Vec<(f64, Vec3)> = Vec::new(); - for w in samples.windows(2) { - let [(s0, Some(g0)), (s1, Some(g1))] = w else { continue }; - if (*g0 < 0.0) == (*g1 < 0.0) { - continue; - } - let (mut a, mut b, ga) = (*s0, *s1, *g0); - for _ in 0..60 { - let m = (a + b) * 0.5; - let Some(gm) = g(m) else { break }; - if (gm < 0.0) == (ga < 0.0) { - a = m; - } else { - b = m; - } - } - let s = (a + b) * 0.5; - if g(s).is_some_and(|x| x.abs() <= tol) { - found.push((s, from_p3(c.subs(s)))); - } - } - found.into_iter().min_by(|x, y| x.1.dist(near).total_cmp(&y.1.dist(near))) -} - -/// The curve on strip `s` from `a` to `b` (each u, v and point) where `side` changes sign (it is -/// negative in the material kept): for each u between, the v where it does nearest a guess -/// between the ends, stepping toward `out` (+1: larger v) while inside. Interpolated by chord -/// length through u spaced closer toward the ends; between its points it stays on the strip and -/// on the surface. -fn trace(s: &Strip, a: (f64, f64, Vec3), b: (f64, f64, Vec3), side: &Away, out: f64, tolerance: f64) -> Result { - use mt::ParametricCurve; - let beyond = || too_large("the blend is larger than the neighbouring faces"); - let (ua, va, pa) = a; - let (ub, vb, pb) = b; - let f = |u: f64, v: f64| side.at(s.at(u, v)).unwrap_or(f64::NAN); - let root = |frac: f64| -> Option<(f64, f64)> { - let u = ua + (ub - ua) * frac; - let guess = (va + (vb - va) * frac).clamp(0.0, 1.0); - // Steps in proportion to the distance from the nearer end, where the curve is known: a - // face tangent to a contact there (a knife-edge tip) crosses the strip only within a - // window that narrows toward it. - let step = (vb - va).abs().max(1e-3) * frac.min(1.0 - frac).clamp(1e-6, 0.5) / 8.0; - let g = f(u, guess); - if !g.is_finite() { - return None; - } - let dir = if g < 0.0 { out } else { -out }; - let mut prev = (guess, g); - for i in 1..=4096 { - let v = (guess + dir * step * i as f64).clamp(0.0, 1.0); - let cur = (v, f(u, v)); - if !cur.1.is_finite() { - return None; - } - if (prev.1 < 0.0) != (cur.1 < 0.0) { - let (mut x, mut y) = (prev, cur); - for _ in 0..60 { - let m = (x.0 + y.0) * 0.5; - let fm = f(u, m); - if (fm < 0.0) == (x.1 < 0.0) { - x = (m, fm); - } else { - y = (m, fm); - } - } - return Some((u, (x.0 + y.0) * 0.5)); - } - if v <= 0.0 || v >= 1.0 { - return None; - } - prev = cur; - } - None - }; - let across = |t: f64| (1.0 - (std::f64::consts::PI * t).cos()) * 0.5; - let mut m = 8; - loop { - let mut pts = vec![pa]; - for i in 1..m { - let (u, v) = root(across(i as f64 / m as f64)).ok_or_else(beyond)?; - pts.push(s.at(u, v)); - } - pts.push(pb); - let (curve, params) = crate::build::interpolate_cubic_chordal(&pts).ok_or_else(|| fail("end curve"))?; - let mut accurate = true; - for (i, w) in params.windows(2).enumerate() { - let (Some(t0), Some(t1)) = (w.first(), w.get(1)) else { continue }; - root(across((i as f64 + 0.5) / m as f64)).ok_or_else(beyond)?; - let x = from_p3(curve.subs((t0 + t1) * 0.5)); - let on = s.nearest(x).map(|(a, b)| s.at(a, b).dist(x)); - let off = side.at(x).map(f64::abs); - if !(on.is_some_and(|d| d <= tolerance) && off.is_some_and(|d| d <= tolerance)) { - accurate = false; - break; - } - } - if accurate { - return Ok(mt::Curve::BSplineCurve(curve)); - } - if m >= 256 { - return Err(fail("could not fit where the blends meet")); - } - m *= 2; - } -} - -/// Convex (−1) or concave (+1): from the edge's direction as its first face runs it and the -/// faces' outward normals at its middle. At a knife edge (normals opposite), also the -/// direction both faces run on from it. -fn convexity(faces: &[mt::Face], e: &mt::Edge, fa: usize, fb: usize, r: f64) -> Result<(f64, Option)> { - use mt::{BoundedCurve, ParametricCurve}; - let (Some(f1), Some(f2)) = (faces.get(fa), faces.get(fb)) else { return Err(fail("face")) }; - let used = f1.boundary_iters().into_iter().flatten().find(|x| x.id() == e.id()).ok_or_else(|| fail("edge use"))?; - let c = used.oriented_curve(); - let (a, b) = c.range_tuple(); - let pm = from_p3(c.subs((a + b) * 0.5)); - let t = tangent(&c, (a + b) * 0.5).ok_or_else(|| fail("tangent"))?; - let (Some(n1), Some(n2)) = (project(f1, pm, None).map(|x| x.1), project(f2, pm, None).map(|x| x.1)) else { return Err(fail("normals")) }; - if n1.dot(n2) > 1.0 - 1e-6 { - return Err(unsupported("blending a smooth edge")); - } - if n1.dot(n2) < -1.0 + 1e-6 { - let into = n1.cross(t).normalized().ok_or_else(|| fail("normals"))?; - return match knife_convex(f1, f2, pm, into, r) { - Some(true) => Ok((-1.0, Some(into))), - _ => Err(unsupported("blending a knife edge inside the material (a crack)")), - }; - } - Ok((if t.dot(n1.cross(n2)) > 0.0 { -1.0 } else { 1.0 }, None)) -} - -/// The strip of edge `e` between faces `fa` and `fb`, running on past each end as far as the -/// ball still fits, up to `reach`. -#[allow(clippy::too_many_arguments)] -fn strip( - faces: &[mt::Face], - e: &mt::Edge, - (fa, fb): (usize, usize), - r: f64, - round: bool, - (sigma, knife): (f64, Option), - reach: f64, - tol: f64, - fit_tol: f64, -) -> Result { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; - let (Some(f1), Some(f2)) = (faces.get(fa), faces.get(fb)) else { return Err(fail("face")) }; - let (o1, o2) = ([f1], [f2]); - let curve = e.curve(); - let (t0, t1) = curve.range_tuple(); - let at = |s: f64| -> Option<(Vec3, Vec3)> { - let t = t0 + (t1 - t0) * s; - Some((from_p3(curve.subs(t)), tangent(&curve, t)?)) - }; - // At a knife edge each ball starts where the last one was, beside it (the first where the - // faces are a diameter apart): the edge itself is no start. - let offset: Cell> = Cell::new(None); - let ball = |p: Vec3, t: Vec3| -> Option
{ - let start = match (knife, offset.get()) { - (None, _) => None, - (Some(_), Some(o)) => Some(p + o), - (Some(into), None) => Some(knife_start(&o1, &o2, p, t, into, r)?), - }; - let s = solve_from(&o1, &o2, p, t, r, sigma, 0.0, None, tol * 100.0, start)?; - if knife.is_some() { - offset.set(Some(s.c - p)); - } - Some(s) - }; - // Along the edge, then on along its curve past its ends (a line runs straight on, a conic's - // arc round its circle) while the ball fits. - let mut raw: Vec
= Vec::new(); - let (p0, _) = at(0.0).ok_or_else(|| fail("tangent"))?; - let n = 32; - let mut along = Vec::with_capacity(n + 1); - for i in 0..=n { - let (p, t) = at(i as f64 / n as f64).ok_or_else(|| fail("tangent"))?; - along.push(ball(p, t).ok_or_else(|| unsupported("the ball doesn't fit along the edge"))?); - } - let length = (0..n).filter_map(|i| Some(at(i as f64 / n as f64)?.0.dist(at((i + 1) as f64 / n as f64)?.0))).sum::(); - if !(length.is_finite() && length > tol) { - return Err(fail("edge length")); - } - let past = |sign: f64| -> Vec
{ - let mut list = Vec::new(); - for k in 1..=16 { - let s = (sign * reach * k as f64 / 16.0) / length; - match at(if sign < 0.0 { s } else { 1.0 + s }).filter(|(p, t)| p.is_finite() && t.is_finite()).and_then(|(p, t)| ball(p, t)) { - Some(x) => list.push(x), - None => break, - } - } - list - }; - let after = past(1.0); - offset.set(along.first().map(|s| s.c - p0)); - let before = past(-1.0); - raw.extend(before.iter().rev().copied()); - let first = raw.len(); - raw.extend(along); - let last = raw.len() - 1; - raw.extend(after); - let guide = Guide::new(raw)?; - let total = guide.lengths.last().copied().ok_or_else(|| fail("spine"))?; - let ends = [ - guide.lengths.get(first).copied().ok_or_else(|| fail("spine"))? / total, - guide.lengths.get(last).copied().ok_or_else(|| fail("spine"))? / total, - ]; - let uniform = |along: f64| -> Result
{ - if along <= 0.0 { - return guide.sections.first().copied().ok_or_else(|| fail("section")); - } - if along >= 1.0 { - return guide.sections.last().copied().ok_or_else(|| fail("section")); - } - let (anchor, t) = guide.anchor(along).ok_or_else(|| unsupported("degenerate rolling-ball spine"))?; - solve_from(&o1, &o2, anchor, t, r, sigma, 0.0, None, tol * 100.0, None) - .ok_or_else(|| unsupported("the ball doesn't fit along the resampled spine")) - }; - let mut samples = SAMPLES; - let (list, fit) = loop { - let list: Vec
= (0..samples).map(|j| uniform(j as f64 / (samples - 1) as f64)).collect::>()?; - let fit = crate::guard("fit corner blend", || fit_sections(std::slice::from_ref(&list), 0, false, round))?; - let mut accurate = true; - 'check: for j in 0..samples - 1 { - for fraction in [0.25, 0.5, 0.75] { - let along = (j as f64 + fraction) / (samples - 1) as f64; - if !section_fits(&fit, &uniform(along)?, along, round, sigma, fit_tol) { - accurate = false; - break 'check; - } - } - } - if accurate { - break (list, fit); - } - if samples >= MAX_SAMPLES { - return Err(fail("could not fit the rolling-ball surface")); - } - samples = (2 * samples - 1).min(MAX_SAMPLES); - }; - // Outward: toward the ball centre on a concave edge, away on a convex one. - let mid = list.get(list.len() / 2).ok_or_else(|| fail("section"))?; - let m = mid.c + ((mid.q1 - mid.c) + (mid.q2 - mid.c)).normalized().ok_or_else(|| fail("section"))? * r; - let (u, v) = fit.surface.search_nearest_parameter(p3(m), Some((0.5, 0.5)), 100).ok_or_else(|| fail("orientation"))?; - let nn = fit.surface.normal(u, v); - let flip = if Vec3::new(nn.x, nn.y, nn.z).dot((mid.c - m) * sigma) < 0.0 { -1.0 } else { 1.0 }; - let sections = list.iter().enumerate().map(|(j, s)| (j as f64 / (samples - 1) as f64, *s)).collect(); - let [c1, c2] = fit.contacts; - Ok(Strip { edge: e.clone(), fa, fb, surface: fit.surface, contacts: [c1, c2], ends, flip, sigma, sections }) -} - -/// The point a radius from all three faces (inside the material for a convex corner), from -/// `start`, and its contacts with them. -fn corner_ball(faces: [&mt::Face; 3], start: Vec3, r: f64, sigma: f64, tol: f64) -> Option<(Vec3, [Vec3; 3])> { - let mut c = start; - for _ in 0..100 { - let mut rows = [[0.0; 3]; 3]; - let mut rhs = [0.0; 3]; - let mut qs = [Vec3::ZERO; 3]; - let mut worst: f64 = 0.0; - for (((f, row), b), q) in faces.iter().zip(rows.iter_mut()).zip(rhs.iter_mut()).zip(qs.iter_mut()) { - let (x, n, _) = project(f, c, None)?; - let g = (c - x).dot(n) - sigma * r; - *row = [n.x, n.y, n.z]; - *b = -g; - *q = x; - worst = worst.max(g.abs()); - } - let d = crate::polyhedron::solve3_pub(rows, rhs)?; - let dc = Vec3::new(d[0], d[1], d[2]); - if worst < tol && dc.len() < tol { - return Some((c, qs)); - } - c += dc; - if !c.is_finite() { - return None; - } - } - None -} - -/// Flip a surface so that its normal near `at` points along `outward`. -fn orient(mut surf: mt::Surface, at: Vec3, outward: Vec3) -> mt::Surface { - use mt::{ParametricSurface3D, SearchNearestParameter}; - if let Some((u, v)) = surf.search_nearest_parameter(p3(at), None, 100) { - let n = surf.normal(u, v); - if Vec3::new(n.x, n.y, n.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); - } - } - surf -} - -/// Where a blend's contact ends at a vertex where it ends alone: crossing the edge there (its -/// parameter and the point), or past that edge's far vertex `w`, crossing the next edge `g` of -/// its face there (`h`: the third edge at `w`, between the faces `f4` beyond and the vertex's -/// third face). -enum Reached { - Edge(f64, Vec3), - Past { t: f64, p: Vec3, w: mt::Vertex, g: mt::EdgeID, h: mt::EdgeID, f4: usize }, -} - -/// A face of the shell being rebuilt, a strip, or a corner's sphere. -#[derive(Clone, Copy, PartialEq)] -enum Owner { - Face(usize), - Strip(mt::EdgeID), - Patch, -} - -/// Edges from `from` to `to` through the pool edges of `owner`. -fn connect(from: &mt::Vertex, to: &mt::Vertex, pool: &[(mt::Edge, Vec)], owner: Owner) -> Result> { - let mut out = Vec::new(); - let mut used: HashSet = HashSet::new(); - let mut cur = from.clone(); - for _ in 0..=pool.len() { - if &cur == to { - return Ok(out); - } - let next = pool.iter().filter(|(e, o)| o.contains(&owner) && !used.contains(&e.id())).find_map(|(e, _)| { - if e.front() == &cur { - Some(e.clone()) - } else if e.back() == &cur { - Some(e.inverse()) - } else { - None - } - }); - let Some(e) = next else { break }; - used.insert(e.id()); - cur = e.back().clone(); - out.push(e); - } - Err(fail("a boundary does not close")) -} - -/// The strip's own station nearest the corner ball `c`: the section where the strip stops against -/// that ball, where its direction of leave and its curvature are read. -fn corner_station(strip: &Strip, c: Vec3) -> Option { - strip.sections.iter().min_by(|a, b| a.1.c.dist(c).total_cmp(&b.1.c.dist(c))).map(|x| x.0) -} - -/// One side of a G2 corner: the corner ball's own section arc of radius `r` about `c`, from its -/// contact `q_from` to its contact `q_to`, each station carrying the direction the corner patch -/// leaves the blend in (towards the corner's apex) and the blend's own curvature across it, read -/// from `strip` where the ball stops against it. A rolling ball's section is a circular arc about -/// its own centre wherever the edge runs, so this arc is the blend's section curve itself, and its -/// ends are the ball's contacts exactly — the sides close the loop whatever the fit's station -/// spacing is. -fn g2_side(strip: &Strip, c: Vec3, r: f64, q_from: Vec3, q_to: Vec3, apex: Vec3) -> Result> { - use mt::ParametricSurface; - /// Stations across one section: enough for the patch's cubic cross-sections, few enough to - /// keep the corner's own patch small. - const STATIONS: usize = 9; - let vec_of = |d: mt::Vector3| Vec3::new(d.x, d.y, d.z); - let v = corner_station(strip, c).ok_or_else(|| fail("corner section"))?; - let a = (q_from - c).normalized().ok_or_else(|| fail("corner contact"))?; - let b = (q_to - c).normalized().ok_or_else(|| fail("corner contact"))?; - let dot = a.dot(b).clamp(-1.0, 1.0); - let w = (b - a * dot).normalized().ok_or_else(|| fail("corner contact"))?; - let theta = dot.acos(); - // The blend's own direction of leave and curvature across the seam, at its corner station. - let speed = vec_of(strip.surface.vder(0.5, v)).len(); - if !(speed > 1e-30) { - return Err(unsupported("a corner section of no width")); - } - let leave = vec_of(strip.surface.vder(0.5, v)) * (1.0 / speed); - let bend = vec_of(strip.surface.vvder(0.5, v)) * (1.0 / (speed * speed)); - if !(leave.is_finite() && bend.is_finite() && theta.is_finite() && r.is_finite()) { - return Err(unsupported("a corner section that is not finite")); - } - let mut out = Vec::with_capacity(STATIONS); - for k in 0..STATIONS { - let t = theta * k as f64 / (STATIONS - 1) as f64; - let p = c + (a * t.cos() + w * t.sin()) * r; - // The patch leaves the blend towards the material the corner caps, so the sign is the one - // towards the corner's apex (the blends' own v direction runs away from the vertex). - let leave = if leave.dot(apex - p) < 0.0 { -leave } else { leave }; - if !(p.is_finite() && leave.is_finite() && bend.is_finite()) { - return Err(unsupported("a corner section that is not finite")); - } - out.push(Frame { p, leave, bend, bend_change: Vec3::ZERO }); - } - Ok(out) -} - -/// Blend the edges `ids` of `solid` with radius `r` (a chamfer's distance), rebuilding the -/// corners at their ends; with what it built from `solid`. -pub(crate) fn corner_blend(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Result<(Solid, Rebuild)> { - corner_blend_style(solid, ids, size, r, round, false) -} - -/// [`corner_blend`]; with `g2`, the corners where three blends meet are G2 patches -/// ([`crate::corner_g2`]) instead of pieces of the rolling ball's sphere. -pub(crate) fn corner_blend_style(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool, g2: bool) -> Result<(Solid, Rebuild)> { - if !(size.is_finite() && size > 0.0 && r.is_finite() && r > 0.0) { - return Err(KernelError::Invalid("blend size and radius must be finite and positive".into())); - } - if ids.is_empty() || ids.len() > 64 { - return Err(KernelError::Invalid("select 1…64 edges".into())); - } - let tol = (size * 1e-7).max(1e-9); - let fit_tol = (size * 1e-5).clamp(1e-5, 0.001); - let shells = solid.boundaries(); - let si = shells.iter().position(|sh| sh.edge_iter().any(|e| ids.contains(&e.id()))).ok_or_else(|| fail("edge not found"))?; - let shell = shells.get(si).ok_or_else(|| fail("shell"))?; - if ids.iter().any(|id| !shell.edge_iter().any(|e| e.id() == *id)) { - return Err(unsupported("blends on separate lumps in one go")); - } - let faces: Vec = shell.face_iter().cloned().collect(); - let edges: HashMap = shell.edge_iter().map(|e| (e.id(), e.absolute_clone())).collect(); - let mut on_edge: HashMap> = HashMap::new(); - let mut at_vertex: HashMap, Vec)> = HashMap::new(); - for (fi, f) in faces.iter().enumerate() { - for e in f.edge_iter() { - let list = on_edge.entry(e.id()).or_default(); - if !list.contains(&fi) { - list.push(fi); - } - for v in [e.front(), e.back()] { - let a = at_vertex.entry(v.id()).or_default(); - a.0.insert(e.id()); - if !a.1.contains(&fi) { - a.1.push(fi); - } - } - } - } - let face_with = |a: mt::EdgeID, b: mt::EdgeID| -> Result { - let fa = on_edge.get(&a).cloned().unwrap_or_default(); - let fb = on_edge.get(&b).cloned().unwrap_or_default(); - fa.into_iter().find(|f| fb.contains(f)).ok_or_else(|| fail("faces")) - }; - let face = |fi: usize| faces.get(fi).ok_or_else(|| fail("face")); - - // The vertices at the blended edges' ends: three faces, three edges. - let mut touched: HashMap = HashMap::new(); - let mut sides: HashMap)> = HashMap::new(); - for id in ids { - let e = edges.get(id).ok_or_else(|| fail("edge"))?; - if e.front() == e.back() { - return Err(unsupported("blending a closed edge at a corner")); - } - let fs = on_edge.get(id).cloned().unwrap_or_default(); - let [fa, fb] = fs[..] else { return Err(unsupported("the edge is not between two faces")) }; - let (sigma, knife) = convexity(&faces, e, fa, fb, r)?; - sides.insert(*id, (fa, fb, sigma, knife)); - touched.insert(e.front().id(), e.front().clone()); - touched.insert(e.back().id(), e.back().clone()); - } - for vid in touched.keys() { - let (eids, fids) = at_vertex.get(vid).ok_or_else(|| fail("vertex"))?; - if eids.len() != 3 || fids.len() != 3 { - return Err(unsupported("blends ending where more than three edges meet")); - } - let chosen: Vec<&mt::EdgeID> = eids.iter().filter(|id| sides.contains_key(id)).collect(); - if chosen.len() >= 2 && chosen.iter().any(|id| sides.get(*id).is_none_or(|s| s.2 > 0.0)) { - return Err(unsupported("concave blends meeting at a corner")); - } - if chosen.len() == 3 && !round { - return Err(unsupported("three chamfers at one corner")); - } - // A blended edge running on smoothly into one that isn't: the blend follows it there - // (a chain round the corner, blended elsewhere), unless it is an earlier round's arc of - // this radius, which the blend ends in. Round a smaller one the ball can't. - let v = touched.get(vid).ok_or_else(|| fail("vertex"))?; - let leaves = |e: &mt::Edge| { - use mt::BoundedCurve; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - tangent(&c, if e.front() == v { t0 } else { t1 }).map(|d| if e.front() == v { d } else { -d }) - }; - for id in &chosen { - let Some(d) = edges.get(*id).and_then(leaves) else { continue }; - for g in eids.iter().filter(|g| !sides.contains_key(*g)) { - let Some(e) = edges.get(g) else { continue }; - if !leaves(e).is_some_and(|x| x.dot(d) < -1.0 + 1e-6) { - continue; - } - // The earlier round's end may also be where it meets a curved face: a circle only - // seen along the round's axis, which its contact with the third face runs along. - let third = eids.iter().find(|x| *x != *id && *x != g).and_then(|x| edges.get(x)).and_then(leaves); - let seen = super::circle_of(e, tol * 1e3).map(|c| c.1).or_else(|| third.and_then(|a| radius_along(e, a, tol * 1e3))); - match seen { - Some(rho) if (rho - r).abs() <= tol * 1e3 => {} - Some(rho) if rho < r => return Err(too_large("the blend is larger than a corner radius")), - _ => return Err(unsupported("a blend running on smoothly into an edge not blended")), - } - } - } - } - - crate::guard("blend corners", || { - // The strips. - let mut strips: HashMap = HashMap::new(); - for id in ids { - let (Some(e), Some((fa, fb, sigma, knife))) = (edges.get(id), sides.get(id).copied()) else { return Err(fail("edge")) }; - strips.insert(*id, strip(&faces, e, (fa, fb), r, round, (sigma, knife), 8.0 * r, tol, fit_tol)?); - } - let strip_of = |id: &mt::EdgeID| strips.get(id).ok_or_else(|| fail("strip")); - // New end points: (edge, vertex, the face of a blended edge's contact). - let mut endpt: HashMap<(mt::EdgeID, mt::VertexID, Option), mt::Vertex> = HashMap::new(); - let mut pool: HashMap)>> = HashMap::new(); - let mut patches: Vec<(mt::Face, Vec)> = Vec::new(); - // Edges a blend uses up to their far vertex (an earlier round's edge, when the radii - // are equal): left out, the blend ends at that vertex. - let mut consumed: HashSet = HashSet::new(); - // Vertices a blend takes in (an earlier round's corner past the end of its edge). - let mut gone: HashMap = HashMap::new(); - // In a fixed order (by position): the work and the result don't depend on hashing. - let mut order_v: Vec<(&mt::VertexID, &mt::Vertex)> = touched.iter().collect(); - order_v.sort_by(|a, b| { - let (p, q) = (vtx(a.1), vtx(b.1)); - p.x.total_cmp(&q.x).then(p.y.total_cmp(&q.y)).then(p.z.total_cmp(&q.z)) - }); - for (vid, vert) in order_v { - let v = vtx(vert); - let (eids, _) = at_vertex.get(vid).ok_or_else(|| fail("vertex"))?; - let mut chosen: Vec = eids.iter().filter(|id| sides.contains_key(id)).copied().collect(); - let rest: Vec = eids.iter().filter(|id| !sides.contains_key(id)).copied().collect(); - chosen.sort_by_key(|id| ids.iter().position(|x| x == id)); - let curve_of = |id: &mt::EdgeID| edges.get(id).map(|e| e.curve()).ok_or_else(|| fail("edge")); - // The new end on edge `id` at `p`: its far vertex when the blend reaches it. - // A contact (`along`: the curves arriving there, and where) that runs into that - // vertex along another of its edges would leave a face no wider than nothing: refused. - let at_end = |id: &mt::EdgeID, p: Vec3, along: &[(&mt::Curve, f64, usize)]| -> Result<(mt::Vertex, bool)> { - let far = edges.get(id).map(|e| if e.front().id() == *vid { e.back().clone() } else { e.front().clone() }); - let Some(w) = far.filter(|w| vtx(w).dist(p) <= fit_tol * 10.0 && !touched.contains_key(&w.id())) else { - return Ok((builder::vertex(p3(p)), false)); - }; - let others = at_vertex.get(&w.id()).map(|x| x.0.iter().filter(|g| *g != id).copied().collect::>()).unwrap_or_default(); - for g in others { - use mt::BoundedCurve; - let Some(e) = edges.get(&g) else { continue }; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let leaves = tangent(&c, if e.front() == &w { t0 } else { t1 }); - let of = on_edge.get(&g).cloned().unwrap_or_default(); - if along - .iter() - .filter(|(_, _, f)| of.contains(f)) - .filter_map(|(c, t, _)| tangent(c, *t)) - .any(|d| leaves.is_some_and(|l| l.dot(d).abs() > 1.0 - 1e-6)) - { - return Err(unsupported("a blend that runs along an edge where it ends")); - } - } - Ok((w, true)) - }; - let mut ending = |id: &mt::EdgeID, p: Vec3, along: &[(&mt::Curve, f64, usize)]| -> Result { - let (w, used) = at_end(id, p, along)?; - if used { - consumed.insert(*id); - } - Ok(w) - }; - let list = pool.entry(*vid).or_default(); - match (&chosen[..], &rest[..]) { - ([e1], [e2, e3]) => { - let s1 = strip_of(e1)?; - let (f12, f31, f23) = (face_with(*e1, *e2)?, face_with(*e1, *e3)?, face_with(*e2, *e3)?); - let (_, out) = s1.end_at(vert); - let (c12, c31) = (s1.contact(f12)?, s1.contact(f31)?); - let none = || too_large("the blend is larger than the neighbouring faces"); - // Each contact crosses its edge at the vertex, or runs past that edge's far - // end (the blend takes in that corner, an earlier round's) to the next edge of - // its face there. - let side = |ei: &mt::EdgeID, fi: usize| -> Result { - let c = s1.contact(fi)?; - if let Some((t, p)) = cross(c, &curve_of(ei)?, face(fi)?, v, s1.own(), fit_tol) { - return Ok(Reached::Edge(t, p)); - } - // Only an earlier round's corner: the third face runs on smoothly from a - // side at the vertex (else the blend would wrap round a corner of the part). - let normal = |f: usize| face(f).ok().and_then(|g| project(g, v, None)).map(|x| x.1); - let smooth = normal(f23).is_some_and(|n| [f12, f31].iter().any(|f| normal(*f).is_some_and(|m| m.dot(n) > 1.0 - 1e-6))); - if !smooth { - return Err(none()); - } - let e = edges.get(ei).ok_or_else(|| fail("edge"))?; - let w = if e.front().id() == *vid { e.back().clone() } else { e.front().clone() }; - let (ws, wf) = at_vertex.get(&w.id()).ok_or_else(|| fail("vertex"))?; - if touched.contains_key(&w.id()) || ws.len() != 3 || wf.len() != 3 || ws.iter().any(|x| sides.contains_key(x)) { - return Err(none()); - } - let on = |f: usize| ws.iter().filter(|x| *x != ei).find(|x| on_edge.get(*x).is_some_and(|fs| fs.contains(&f))).copied(); - let (Some(g), Some(h)) = (on(fi), on(f23)) else { return Err(none()) }; - let f4 = face_with(g, h)?; - let (t, p) = cross(c, &curve_of(&g)?, face(fi)?, v, s1.own(), fit_tol).ok_or_else(none)?; - // Through that far vertex itself: the contact reaches the edge's end there - // (touching it where it runs in tangent to the contact, as at a knife-edge - // tip). - if p.dist(vtx(&w)) <= fit_tol * 10.0 { - return Ok(Reached::Edge(t, vtx(&w))); - } - Ok(Reached::Past { t, p, w, g, h, f4 }) - }; - match (side(e2, f12)?, side(e3, f31)?) { - (Reached::Edge(v2, p2), Reached::Edge(v3, p3_)) => { - let (a, b) = (ending(e2, p2, &[(c12, v2, f12)])?, ending(e3, p3_, &[(c31, v3, f31)])?); - endpt.insert((*e2, *vid, None), a.clone()); - endpt.insert((*e1, *vid, Some(f12)), a.clone()); - endpt.insert((*e3, *vid, None), b.clone()); - endpt.insert((*e1, *vid, Some(f31)), b.clone()); - let end = Away::face(face(f23)?); - let c = trace(s1, (s1.u(f12)?, v2, p2), (s1.u(f31)?, v3, p3_), &end, out, fit_tol)?; - list.push((mt::Edge::new(&a, &b, c), vec![Owner::Face(f23), Owner::Strip(*e1)])); - } - (r2, r3) => { - // The end runs from the edge reached across the third face to where - // it crosses the edge `h` from the corner taken in, then across the - // face beyond (`f4`) to the next edge `g`. - let ((ed, fd, td, pd), (ex, fx, past)) = match (r2, r3) { - (Reached::Edge(t, p), past @ Reached::Past { .. }) => ((e2, f12, t, p), (e3, f31, past)), - (past @ Reached::Past { .. }, Reached::Edge(t, p)) => ((e3, f31, t, p), (e2, f12, past)), - _ => return Err(unsupported("a blend running past both edges where it ends")), - }; - let Reached::Past { t: tx, p: px, w, g, h, f4 } = past else { return Err(fail("corner")) }; - let a = ending(ed, pd, &[(s1.contact(fd)?, td, fd)])?; - let b = builder::vertex(p3(px)); - let (_, y) = reach(&curve_of(&h)?, &Away::strip(s1), vtx(&w), fit_tol).ok_or_else(none)?; - let (u_y, v_y) = s1.nearest(y).ok_or_else(none)?; - if s1.at(u_y, v_y).dist(y) > fit_tol * 10.0 { - return Err(none()); - } - let yv = builder::vertex(p3(y)); - consumed.insert(*ex); - gone.insert(w.id(), w.clone()); - endpt.insert((*ed, *vid, None), a.clone()); - endpt.insert((*e1, *vid, Some(fd)), a.clone()); - endpt.insert((*e1, *vid, Some(fx)), b.clone()); - endpt.insert((g, w.id(), None), b.clone()); - endpt.insert((h, w.id(), None), yv.clone()); - let first = trace(s1, (s1.u(fd)?, td, pd), (u_y, v_y, y), &Away::face(face(f23)?), out, fit_tol)?; - let second = trace(s1, (u_y, v_y, y), (s1.u(fx)?, tx, px), &Away::face(face(f4)?), out, fit_tol)?; - list.push((mt::Edge::new(&a, &yv, first), vec![Owner::Face(f23), Owner::Strip(*e1)])); - list.push((mt::Edge::new(&yv, &b, second), vec![Owner::Face(f4), Owner::Strip(*e1)])); - } - } - } - ([ea, eb], [e3]) => { - let (sa, sb) = (strip_of(ea)?, strip_of(eb)?); - let fab = face_with(*ea, *eb)?; - let (fa3, fb3) = (face_with(*ea, *e3)?, face_with(*eb, *e3)?); - let c3 = curve_of(e3)?; - let none = || too_large("the blend is larger than the neighbouring faces"); - // Where the contacts cross on the shared face, and each reaches the third edge. - let (va_q, q) = cross(sa.contact(fab)?, sb.contact(fab)?, face(fab)?, v, sa.own(), fit_tol).ok_or_else(none)?; - let vb_q = param_on(sb.contact(fab)?, q).ok_or_else(none)?; - let (va_x, xa) = cross(sa.contact(fa3)?, &c3, face(fa3)?, v, sa.own(), fit_tol).ok_or_else(none)?; - let (vb_x, xb) = cross(sb.contact(fb3)?, &c3, face(fb3)?, v, sb.own(), fit_tol).ok_or_else(none)?; - let qv = builder::vertex(p3(q)); - endpt.insert((*ea, *vid, Some(fab)), qv.clone()); - endpt.insert((*eb, *vid, Some(fab)), qv.clone()); - if xa.dist(xb) <= fit_tol * 10.0 { - // The crease runs to the third edge. - let x = (xa + xb) * 0.5; - let xv = ending(e3, x, &[(sa.contact(fa3)?, va_x, fa3), (sb.contact(fb3)?, vb_x, fb3)])?; - endpt.insert((*e3, *vid, None), xv.clone()); - endpt.insert((*ea, *vid, Some(fa3)), xv.clone()); - endpt.insert((*eb, *vid, Some(fb3)), xv.clone()); - let (_, out) = sa.end_at(vert); - let c = trace(sa, (sa.u(fab)?, va_q, q), (sa.u(fa3)?, va_x, x), &Away::strip(sb), out, fit_tol)?; - list.push((mt::Edge::new(&qv, &xv, c), vec![Owner::Strip(*ea), Owner::Strip(*eb)])); - } else { - // The strip reaching further along the third edge (`big`) runs on past - // the crease to end on the other's third face. - let (big, small, ebig, esmall, fbig3, fsmall3, x, vbig_x) = - if xa.dist(v) > xb.dist(v) { (sa, sb, *ea, *eb, fa3, fb3, xa, va_x) } else { (sb, sa, *eb, *ea, fb3, fa3, xb, vb_x) }; - let vs_q = if esmall == *ea { va_q } else { vb_q }; - let (vs_y, y) = reach(small.contact(fsmall3)?, &Away::strip(big), v, fit_tol).ok_or_else(none)?; - let (u_y, v_y) = big.nearest(y).ok_or_else(none)?; - if big.at(u_y, v_y).dist(y) > fit_tol * 10.0 { - return Err(unsupported("blends this different at one corner")); - } - let xv = ending(e3, x, &[(big.contact(fbig3)?, vbig_x, fbig3)])?; - let yv = builder::vertex(p3(y)); - endpt.insert((*e3, *vid, None), xv.clone()); - endpt.insert((ebig, *vid, Some(fbig3)), xv.clone()); - endpt.insert((esmall, *vid, Some(fsmall3)), yv.clone()); - let (_, out_s) = small.end_at(vert); - let (_, out_b) = big.end_at(vert); - let crease = trace(small, (small.u(fab)?, vs_q, q), (small.u(fsmall3)?, vs_y, y), &Away::strip(big), out_s, fit_tol)?; - let section = trace(big, (u_y, v_y, y), (big.u(fbig3)?, vbig_x, x), &Away::face(face(fsmall3)?), out_b, fit_tol)?; - list.push((mt::Edge::new(&qv, &yv, crease), vec![Owner::Strip(*ea), Owner::Strip(*eb)])); - list.push((mt::Edge::new(&yv, &xv, section), vec![Owner::Face(fsmall3), Owner::Strip(ebig)])); - } - } - ([e1, e2, e3], []) => { - let s1 = strip_of(e1)?; - let (f12, f23, f31) = (face_with(*e1, *e2)?, face_with(*e2, *e3)?, face_with(*e3, *e1)?); - // The corner ball, from the first strip's section nearest the vertex. - let (v1, _) = s1.end_at(vert); - let start = s1 - .sections - .iter() - .min_by(|a, b| (a.0 - v1).abs().total_cmp(&(b.0 - v1).abs())) - .map(|x| x.1.c) - .ok_or_else(|| fail("section"))?; - let (c, [q12, q23, q31]) = corner_ball([face(f12)?, face(f23)?, face(f31)?], start, r, s1.sigma, tol * 100.0) - .ok_or_else(|| unsupported("the ball doesn't fit in the corner"))?; - let (v12, v23, v31) = (builder::vertex(p3(q12)), builder::vertex(p3(q23)), builder::vertex(p3(q31))); - for (e, f, x) in [(e1, f12, &v12), (e2, f12, &v12), (e2, f23, &v23), (e3, f23, &v23), (e3, f31, &v31), (e1, f31, &v31)] { - endpt.insert((*e, *vid, Some(f)), x.clone()); - } - let arc = |a: &mt::Vertex, b: &mt::Vertex| -> Result { - let m = c + ((vtx(a) - c) + (vtx(b) - c)).normalized().ok_or_else(|| fail("corner arc"))? * r; - Ok(builder::circle_arc(a, b, p3(m))) - }; - let (a1, a2, a3) = (arc(&v12, &v31)?, arc(&v12, &v23)?, arc(&v23, &v31)?); - // A sphere with its poles and seam away from the patch. - let n = |f: usize, q: Vec3| face(f).ok().and_then(|g| project(g, q, None)).map(|x| x.1).unwrap_or(Vec3::Z); - let out = (n(f12, q12) + n(f23, q23) + n(f31, q31)).normalized().unwrap_or(Vec3::Z); - let side = out.any_perp(); - let (np, sp, back) = (c + side * r, c - side * r, c - out * r); - if g2 { - // A G2 patch on the blends' own end sections, gathered at the ball's pole - // (the point the sphere's meridians are built through above). Each side is - // the strip's section through the ball's contact with the face it shares - // with the previous strip; the strips run on past their edges, so that - // station is found by projecting the contact point, not taken from the - // edge's own end. - let s2 = strip_of(e2)?; - let s3 = strip_of(e3)?; - // The cap's own pole: the ball's point nearest the corner (the sphere - // patch's `back` above is its opposite pole, where the meridian starts). - let apex = c + out * r; - // Side 1 runs from the ball's contact with the face it shares with e3 - // round to the one it shares with e2, and so on round the loop: each - // side's last station is the next side's first, at that contact. - let sides = [g2_side(s1, c, r, q31, q12, apex)?, g2_side(s2, c, r, q12, q23, apex)?, g2_side(s3, c, r, q23, q31, apex)?]; - let _patch = crate::corner_g2::corner_g2_patch(&sides, apex)?; - // Sewing the patch into the shell is not done yet: it brings its own - // boundary vertices where the strips' contacts end at the ball's contacts - // (`v12`/`v23`/`v31`), and a truck vertex is its allocation, not its point, - // so the rebuilt shell does not close there (rewrapping the section curves - // onto the contacts is the missing step). Refused rather than left open: - // the rolling ball fills the corner instead. - return Err(unsupported( - "a G2 corner sewn between these blends (the patch's section curves do not join the blends' contacts yet)", - )); - } - let meridian = builder::circle_arc(&builder::vertex(p3(np)), &builder::vertex(p3(sp)), p3(back)); - let surf = mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution( - meridian.oriented_curve(), - p3(c), - v3(side), - ))); - let surf = orient(surf, c + out * r, out * -s1.sigma); - let wire: mt::Wire = vec![a2.clone(), a3.clone(), a1.inverse()].into(); - let patch = mt::Face::try_new(vec![wire], surf).map_err(|e| fail(&format!("corner patch: {e}")))?; - patches.push((patch, vec![*e1, *e2, *e3])); - list.push((a1, vec![Owner::Strip(*e1), Owner::Patch])); - list.push((a2, vec![Owner::Strip(*e2), Owner::Patch])); - list.push((a3, vec![Owner::Strip(*e3), Owner::Patch])); - } - _ => return Err(unsupported("this corner")), - } - } - - // Rebuilt edges: contacts per (edge, face), shortened edges per edge. - let end_of = - |id: mt::EdgeID, v: &mt::Vertex, f: Option| -> mt::Vertex { endpt.get(&(id, v.id(), f)).cloned().unwrap_or_else(|| v.clone()) }; - let mut lines: HashMap<(mt::EdgeID, Option), mt::Edge> = HashMap::new(); - let mut line_of = |e: &mt::Edge, f: Option| -> Result { - use mt::Cut; - if let Some(x) = lines.get(&(e.id(), f)) { - return Ok(x.clone()); - } - let abs = e.absolute_clone(); - let (a, b) = (end_of(e.id(), abs.front(), f), end_of(e.id(), abs.back(), f)); - let x = match (f, strips.get(&e.id())) { - (Some(fi), Some(s)) => { - // The contact between its new ends. - let c = s.contact(fi)?; - let none = || too_large("the blend is larger than the neighbouring faces"); - let (ta, tb) = (param_on(c, vtx(&a)).ok_or_else(none)?, param_on(c, vtx(&b)).ok_or_else(none)?); - if tb - ta < 1e-9 { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - let mut piece = c.clone(); - let _ = piece.cut(tb); - let piece = piece.cut(ta); - mt::Edge::try_new(&a, &b, piece).map_err(|e| fail(&format!("contact: {e}")))? - } - _ => { - let orig = vtx(abs.back()) - vtx(abs.front()); - if (vtx(&b) - vtx(&a)).dot(orig) <= size * 1e-9 * orig.len() { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - if matches!(abs.curve(), mt::Curve::Line(_)) { - builder::line(&a, &b) - } else { - let moved = |n: &mt::Vertex, o: &mt::Vertex| (n != o).then(|| n.clone()); - super::trim_curved_seam(&abs, moved(&a, abs.front()), moved(&b, abs.back()), size)? - } - } - }; - lines.insert((e.id(), f), x.clone()); - Ok(x) - }; - let changed = |v: &mt::Vertex| touched.contains_key(&v.id()) || gone.contains_key(&v.id()); - let moved = |e: &mt::Edge| changed(e.front()) || changed(e.back()); - let everywhere: Vec<(mt::Edge, Vec)> = pool.values().flatten().cloned().collect(); - let mut rec = Rebuild::default(); - let mut out: Vec = Vec::with_capacity(faces.len() + strips.len() + patches.len()); - for (fi, f) in faces.iter().enumerate() { - if !f.vertex_iter().any(|v| changed(&v)) { - out.push(f.clone()); - continue; - } - let mut wires = Vec::new(); - for w in f.boundaries() { - let olds: Vec = w.edge_iter().filter(|e| !consumed.contains(&e.id())).cloned().collect(); - let mut news = Vec::with_capacity(olds.len()); - for e in &olds { - let ne = if strips.contains_key(&e.id()) { - line_of(e, Some(fi))? - } else if moved(e) { - let piece = line_of(e, None)?; - rec.piece(&piece, e); - piece - } else { - news.push(e.clone()); - continue; - }; - news.push(if e.front() == e.absolute_front() { ne } else { ne.inverse() }); - } - let n = news.len(); - let mut ws = Vec::new(); - for i in 0..n { - let (Some(a), Some(b)) = (news.get(i), news.get((i + 1) % n)) else { continue }; - ws.push(a.clone()); - if a.back() != b.front() { - ws.extend(connect(a.back(), b.front(), &everywhere, Owner::Face(fi))?); - } - } - wires.push(mt::Wire::from(ws)); - } - let rebuilt = mt::Face::try_new(wires, f.oriented_surface()).map_err(|e| fail(&format!("face: {e}")))?; - rec.face(&rebuilt, f); - out.push(rebuilt); - } - // The strips: back along the first face's contact, round the front corner, along the - // second's, round the back corner. - for id in ids { - let (Some(s), Some(e)) = (strips.get(id), edges.get(id)) else { continue }; - let (va, vb) = (e.front(), e.back()); - let a_forward = faces.get(s.fa).is_some_and(|f| f.boundaries().iter().any(|w| w.edge_iter().any(|x| x.id() == *id && x.front() == va))); - let la = line_of(e, Some(s.fa))?; - let lb = line_of(e, Some(s.fb))?; - let (first, second) = if a_forward { (la.inverse(), lb) } else { (lb.inverse(), la) }; - let p1 = pool.get(&va.id()).map(|x| &x[..]).unwrap_or(&[]); - let p2 = pool.get(&vb.id()).map(|x| &x[..]).unwrap_or(&[]); - let mut w = vec![first.clone()]; - w.extend(connect(first.back(), second.front(), p1, Owner::Strip(*id))?); - w.push(second.clone()); - w.extend(connect(second.back(), first.front(), p2, Owner::Strip(*id))?); - let surface = if s.flip < 0.0 { mt::Invertible::inverse(&s.surface) } else { s.surface.clone() }; - let surface = in_proportion(&surface)?; - let blend = mt::Face::try_new(vec![w.into()], surface).map_err(|e| fail(&format!("blend face: {e}")))?; - rec.blend(&blend, [*id]); - out.push(blend); - } - // Corner patches run each section opposite to its strip. - for (mut p, corner) in patches { - let uses = |f: &mt::Face, id: mt::EdgeID| { - f.boundaries().iter().flat_map(|w| w.edge_iter().cloned().collect::>()).find(|x| x.id() == id).map(|x| x.front().id()) - }; - let flip = p - .boundaries() - .first() - .and_then(|w| w.edge_iter().next()) - .and_then(|pe| out.iter().find_map(|f| uses(f, pe.id())).map(|front| front == pe.front().id())); - if flip == Some(true) { - let surf = p.oriented_surface(); - let wires: Vec = p.boundaries().iter().map(|w| w.inverse()).collect(); - p = mt::Face::try_new(wires, surf).map_err(|e| fail(&format!("corner patch: {e}")))?; - } - rec.blend(&p, corner); - out.push(p); - } - let mut shells = solid.boundaries().clone(); - if let Some(sh) = shells.get_mut(si) { - *sh = out.into(); - } - let res = Solid::try_new(shells).map_err(|e| fail(&format!("invalid solid: {e}")))?; - Ok((res, rec)) - }) -} - -#[cfg(test)] -#[path = "curvecorner_tests.rs"] -mod tests; diff --git a/crates/kernel/src/curvecorner_tests.rs b/crates/kernel/src/curvecorner_tests.rs index 3153d107c..6cc984552 100644 --- a/crates/kernel/src/curvecorner_tests.rs +++ b/crates/kernel/src/curvecorner_tests.rs @@ -1,4 +1,5 @@ -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use crate::Body; @@ -166,22 +167,6 @@ fn off_tip(x: f64, y: f64) -> bool { (x - k.x).hypot(y - k.y) > 2.0 && a >= (-21.0 - k.y).atan2(CX - k.x) && a <= std::f64::consts::FRAC_PI_2 } -/// The knife-edge tip (the arc and the top line meeting at no angle) rounds to the ball 2 from -/// both, 13 back from the tip; its chamfer cuts the cusp at the chord between the same contacts. -#[test] -fn a_knife_edge_tip_rounds_where_the_ball_fits() { - let k = tip_ball(); - let round = over_cusp(k.x - 1.0, |x, y| if off_tip(x, y) { 1.0 } else { 0.0 }) * 10.0; - let got = removed(true, &[TIP]); - assert!((got - round).abs() < round * 1e-3, "round: removed {got} vs {round}"); - // The chord from the top line's contact to the arc's. - let (a, b) = (Vec2::new(k.x, 0.0), k + (Vec2::new(CX, -21.0) - k) * (2.0 / 23.0)); - let beyond = |x: f64, y: f64| (b.x - a.x) * (y - a.y) - (b.y - a.y) * (x - a.x) > 0.0; - let flat = over_cusp(k.x - 1.0, |x, y| if beyond(x, y) { 1.0 } else { 0.0 }) * 10.0; - let got = removed(false, &[TIP]); - assert!((got - flat).abs() < flat * 1e-3, "chamfer: removed {got} vs {flat}"); -} - /// The tip's round with the arc's or the back edge's at the top, where all three meet: as at /// the front corner, each alone less what both would take twice — over the tip's corner region, /// the other's (above 8 + √(4 − d²), d across from its ball's path). @@ -239,28 +224,32 @@ fn a_round_ending_in_an_earlier_round_matches_both_together() { (arc_top(), TIP), (BACK, TIP), (arc_top(), BACK), + // The other order (the arc's round once left 0.05 mm³ more at the knife-edge tip). + (BACK, arc_top()), ] { one_then_the_other(first, then); } } -/// The back edge rounded first, then the arc's top edge: the same solid as both together, or the -/// other order (the arc's round once left 0.05 mm³ more at the knife-edge tip). -#[test] -fn the_arc_rounded_after_the_back_edge_matches_both_together() { - one_then_the_other(BACK, arc_top()); -} - -/// The edge at `first` rounded (2), then the one at `then` as a fillet of its own, against both -/// rounded together. +/// The edge at `first` rounded (2), then the one at `then` as a fillet of its own, each with its +/// tangent chain as the Fillet feature rounds by default (tangent propagation), against the same +/// edges of the part rounded together: the picks' chains, and every edge of the part that the +/// second round's chain carried on into across the first round (the left front upright, after +/// the front edge's round: the left top edge runs on round that round's end arc and down the +/// upright, a sphere octant at the corner where the three rounds meet). fn one_then_the_other(first: Vec3, then: Vec3) { let body = arc_part(); - let step = crate::fillet(&body, &[first], 2.0).unwrap(); - let after = crate::fillet(&step, &[then], 2.0).unwrap(); + let chained = |b: &Body, pts: &[Vec3]| crate::tangent_chain(b, pts).unwrap(); + let step = crate::fillet(&body, &chained(&body, &[first]), 2.0).unwrap_or_else(|e| panic!("{first:?}: {e}")); + let second = chained(&step, &[then]); + let after = crate::fillet(&step, &second, 2.0).unwrap_or_else(|e| panic!("{first:?} then {then:?}: {e}")); let v = volume(&after); - let together = volume(&crate::fillet(&body, &[first, then], 2.0).unwrap()); + // The part's own edges among the second chain's (points on an edge of the part). + let mut picks = vec![first, then]; + picks.extend(second.iter().skip(1).filter(|p| crate::tangent_chain(&body, &[**p]).is_ok())); + let together = volume(&crate::fillet(&body, &chained(&body, &picks), 2.0).unwrap()); // Within the display meshes' accuracy (two different B-reps, meshed apart). - assert!((v - together).abs() < 5e-3, "{first:?} then {then:?}: {v} vs together {together}"); + assert!((v - together).abs() < 5e-3, "{first:?} then {then:?}: {v} vs together {together} ({picks:?})"); } /// Edges rounded together come out the same in any order: a round made first doesn't carry the @@ -275,9 +264,9 @@ fn rounds_together_in_any_order() { } } -/// The blends this part needs the corner build for (and the back edge, rolled into the tip) at +/// The blends this part has corners in (and the back edge, rounded into the tip) at /// 0.01 and 100 times the part's size, the radius scaled with it: they take off what they take at -/// full size, scaled by the cube, so the build's tolerances and limits follow the model's size. +/// full size, scaled by the cube, so the tolerances and limits follow the model's size. #[test] fn corner_blends_hold_at_any_scale() { let cases: [(&str, Vec>); 6] = [ @@ -291,7 +280,7 @@ fn corner_blends_hold_at_any_scale() { // What a blend takes off the part scaled by `k`, over k³, through a display plan of matching // accuracy. let removed = |k: f64, steps: &[Vec]| { - let volume = |b: &Body| b.display_plan(2e-4 * k).unwrap().evaluate().measure().volume; + let volume = |b: &Body| b.mesh_plan(&crate::MeshTolerance::chord(2e-4 * k)).unwrap().evaluate().measure().volume; let body = scaled_arc_part(k); let mut b = body.clone(); for pts in steps { diff --git a/crates/kernel/src/delete_face.rs b/crates/kernel/src/delete_face.rs index e7cc07de6..7d938b0ec 100644 --- a/crates/kernel/src/delete_face.rs +++ b/crates/kernel/src/delete_face.rs @@ -1,52 +1,32 @@ //! Delete Face with healing: faces are removed and their planar neighbours extend to close the //! gap, as when a fillet, chamfer, boss or hole is taken off a part. //! -//! The body is rebuilt from its own topology. Faces away from the gap are kept as they are. -//! Each neighbouring face (planar) keeps its edges that don't touch the gap; a loop that ran -//! entirely along deleted faces is dropped for a hole's rim or a boss's footprint, or restored -//! at the moved corners for a face enclosed by rounds. A corner on the +//! The body is rebuilt from its own schema 4 record. Faces away from the gap are kept as they +//! are. Each neighbouring face (planar) keeps its plane and its edges that don't touch the gap; +//! a loop that ran entirely along deleted faces is dropped for a hole's rim or a boss's +//! footprint, or restored at the moved corners for a face enclosed by rounds. A corner on the //! gap moves to where its planes meet the neighbours across the gap (a fillet's tangent points //! go to the sharp corner), and the stretch of loop that bordered deleted faces closes with a //! straight edge between the moved corners. Anything else (curved neighbours, a gap the //! neighbours cannot close) is refused, naming the face. +use solidcraft_geom::prelude::*; use std::collections::{BTreeSet, HashMap}; -use solidcraft_geom::{Aabb3, Vec3}; -use truck_modeling::{self as mt, builder}; +use solidcore_record::Vec3; +use solidcore_record::brep::Curve; +use solidcraft_geom::Aabb3; -use crate::body::{Body, Solid, from_p3, p3}; +use crate::assemble::{AFace, AUse, Assembly}; +use crate::body::Body; +use crate::history::Change; +use crate::offset::{Surf, surf_of}; use crate::{KernelError, Result, guard}; fn fail(m: impl Into) -> KernelError { KernelError::Invalid(format!("Delete Face: {}", m.into())) } -/// Outward plane (unit normal, offset) of a face, if it is planar: sampled along its edges, -/// the surface's outward normal stays the same and the points stay on one plane. -fn face_plane(f: &mt::Face, tol: f64) -> Option<(Vec3, f64)> { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; - let surf = f.oriented_surface(); - let mut pts: Vec<(Vec3, Vec3)> = Vec::new(); - let mut last: Option<(f64, f64)> = None; - for w in f.boundaries() { - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..6 { - let p = c.subs(t0 + (t1 - t0) * k as f64 / 6.0); - let (u, v) = surf.search_nearest_parameter(p, last, 50)?; - last = Some((u, v)); - let n = surf.normal(u, v); - pts.push((from_p3(p), Vec3::new(n.x, n.y, n.z).normalized()?)); - } - } - } - let (p0, n0) = *pts.first()?; - let d = n0.dot(p0); - pts.iter().all(|(p, n)| n.dot(n0) > 1.0 - 1e-9 && (n0.dot(*p) - d).abs() <= tol).then_some((n0, d)) -} - type Key = (i64, i64, i64); /// Key of a point for sharing vertices and edges between rebuilt faces. @@ -55,12 +35,77 @@ fn key(p: Vec3, q: f64) -> Key { (r(p.x), r(p.y), r(p.z)) } +/// The vertices and straight edges the rebuilt faces share, by where they are. +struct Shared { + q: f64, + vertices: HashMap, + lines: HashMap<(Key, Key), u32>, +} + +impl Shared { + fn vertex(&mut self, asm: &mut Assembly, p: Vec3) -> Result { + let k = key(p, self.q); + if let Some(v) = self.vertices.get(&k) { + return Ok(*v); + } + let v = asm.vertex(p)?; + self.vertices.insert(k, v); + Ok(v) + } + + /// The straight edge from `a` to `b`, made once and used both ways. + fn line(&mut self, asm: &mut Assembly, a: Vec3, b: Vec3) -> Result { + let (ka, kb) = (key(a, self.q), key(b, self.q)); + if let Some(e) = self.lines.get(&(ka, kb)) { + return Ok(AUse { edge: *e, forward: true, given: None }); + } + if let Some(e) = self.lines.get(&(kb, ka)) { + return Ok(AUse { edge: *e, forward: false, given: None }); + } + let (va, vb) = (self.vertex(asm, a)?, self.vertex(asm, b)?); + let e = asm.line(va, vb)?; + self.lines.insert((ka, kb), e); + Ok(AUse { edge: e, forward: true, given: None }) + } +} + +/// The corners along a gap stretch, closed to `a`: straight edges between them, with corners +/// that coincide or lie in line with their neighbours dropped (two rounds meeting in a mitre +/// leave the sharp corner between them). +fn close(pts: Vec, a: Vec3, q: f64) -> Vec<(Vec3, Vec3)> { + let mut c: Vec = Vec::new(); + for p in pts.into_iter().chain(std::iter::once(a)) { + if c.last().is_some_and(|l| l.dist(p) <= q * 10.0) { + continue; + } + if let [.., x, y] = c[..] + && (y - x).cross(p - y).len() <= q * 10.0 * (p - x).len() + && (y - x).dot(p - y) > 0.0 + { + c.pop(); + } + c.push(p); + } + c.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect() +} + +/// Whether the use's edge has a corner that moves. +fn corner_moves(asm: &Assembly, moved: &HashMap, u: &AUse) -> bool { + asm.ends(u).is_some_and(|(a, b)| moved.contains_key(&a) || moved.contains_key(&b)) +} + +/// Where vertex `v` is after the corners move. +fn position(asm: &Assembly, moved: &HashMap, v: u32) -> Result { + moved.get(&v).copied().or_else(|| asm.point(v)).ok_or_else(|| fail("vertex")) +} + /// Delete faces (indices in the body's face order, as in its mesh's `tri_face`) and heal the /// gap by extending the neighbouring planes. The result's history is over `[body]`. pub fn delete_faces(body: &Body, faces: &[usize]) -> Result { + let _span = solidcraft_profile::span("kernel", "delete_faces"); body.require_brep("Delete Face")?; - let all: Vec = body.solid.face_iter().cloned().collect(); - let n = all.len(); + let rec = crate::native::brep_record(body)?; + let n = rec.faces.len(); if faces.is_empty() { return Err(fail("no faces given")); } @@ -72,282 +117,228 @@ pub fn delete_faces(body: &Body, faces: &[usize]) -> Result { return Err(fail("that would delete every face")); } let size = body.size().max(1e-9); - // Edge and vertex → faces. - let mut efaces: HashMap> = HashMap::new(); - let mut vfaces: HashMap> = HashMap::new(); - for (i, f) in all.iter().enumerate() { - for e in f.edge_iter() { - let v = efaces.entry(e.id()).or_default(); - if !v.contains(&i) { - v.push(i); - } - } - for v in f.vertex_iter() { - let l = vfaces.entry(v.id()).or_default(); - if !l.contains(&i) { - l.push(i); - } - } - } - // Neighbours: faces sharing an edge with a deleted face; they must be planar. - let mut neighbours: BTreeSet = BTreeSet::new(); - for fs in efaces.values() { - if fs.iter().any(|f| del.contains(f)) { - neighbours.extend(fs.iter().filter(|f| !del.contains(f))); - } - } - if neighbours.is_empty() { - return Err(fail("the faces don't border the rest of the body")); - } - let mut planes: HashMap = HashMap::new(); - for &f in &neighbours { - // Planar by its geometry (boolean results may carry a plane as another surface type). - match all.get(f).and_then(|x| face_plane(x, size * 1e-6)) { - Some(p) => { - planes.insert(f, p); - } - None => { - let by = efaces - .values() - .find(|fs| fs.contains(&f) && fs.iter().any(|x| del.contains(x))) - .and_then(|fs| fs.iter().find(|x| del.contains(x)).copied()) - .unwrap_or(0); - return Err(fail(format!("face {by} borders face {f}, which is curved; only planar neighbours can extend to close the gap yet"))); - } - } - } - // Corners across the gap: three neighbour planes meeting near the deleted faces. - let gap: Aabb3 = del.iter().flat_map(|f| all.get(*f).into_iter().flat_map(|x| x.vertex_iter())).map(|v| from_p3(v.point())).collect(); - let near_gap = gap.inflated(gap.diagonal().max(size * 1e-3)); - let near = |p: Vec3| near_gap.contains(p); - let on = |p: Vec3, f: usize| planes.get(&f).is_some_and(|(n, d)| (n.dot(p) - d).abs() <= size * 1e-6); - let nb: Vec = neighbours.iter().copied().collect(); - let mut corners: Vec = Vec::new(); - for i in 0..nb.len() { - for j in (i + 1)..nb.len() { - for k in (j + 1)..nb.len() { - let (Some(a), Some(b), Some(c)) = - (nb.get(i).and_then(|x| planes.get(x)), nb.get(j).and_then(|x| planes.get(x)), nb.get(k).and_then(|x| planes.get(x))) - else { - continue; - }; - let den = a.0.dot(b.0.cross(c.0)); - if den.abs() < 1e-9 { - continue; + guard("delete face", || { + let mut asm = Assembly::from_record(&rec)?; + // Edge and vertex → faces. + let mut efaces: HashMap> = HashMap::new(); + let mut vfaces: HashMap> = HashMap::new(); + for (i, f) in asm.faces.iter().enumerate() { + for u in f.iter().flat_map(|f| &f.loops).flatten() { + let l = efaces.entry(u.edge).or_default(); + if !l.contains(&i) { + l.push(i); } - let x = (b.0.cross(c.0) * a.1 + c.0.cross(a.0) * b.1 + a.0.cross(b.0) * c.1) / den; - if x.is_finite() && near(x) { - corners.push(x); + let (a, b) = asm.ends(u).ok_or_else(|| fail("edge"))?; + for v in [a, b] { + let l = vfaces.entry(v).or_default(); + if !l.contains(&i) { + l.push(i); + } } } } - } - // Where each vertex on the gap goes: the nearest corner on all of its remaining planes. - let mut moved: HashMap = HashMap::new(); - for &f in &del { - for v in all.get(f).into_iter().flat_map(|x| x.vertex_iter()) { - let Some(fs) = vfaces.get(&v.id()) else { continue }; + let gap_edge = |e: u32| efaces.get(&e).is_some_and(|fs| fs.iter().any(|x| del.contains(x))); + // Neighbours: faces sharing an edge with a deleted face; they must be planar. + let mut neighbours: BTreeSet = BTreeSet::new(); + for fs in efaces.values() { + if fs.iter().any(|f| del.contains(f)) { + neighbours.extend(fs.iter().filter(|f| !del.contains(f))); + } + } + if neighbours.is_empty() { + return Err(fail("the faces don't border the rest of the body")); + } + let mut planes: HashMap = HashMap::new(); + for &f in &neighbours { + match surf_of(&rec, f) { + Some(Surf::Plane { n, d }) => { + planes.insert(f, (n, d)); + } + _ => { + let by = efaces + .values() + .find(|fs| fs.contains(&f) && fs.iter().any(|x| del.contains(x))) + .and_then(|fs| fs.iter().find(|x| del.contains(x)).copied()) + .unwrap_or(0); + return Err(fail(format!("face {by} borders face {f}, which is curved; only planar neighbours can extend to close the gap yet"))); + } + } + } + // The deleted faces' vertices. + let gap_vertices: BTreeSet = vfaces.iter().filter(|(_, fs)| fs.iter().any(|f| del.contains(f))).map(|(v, _)| *v).collect(); + // Corners across the gap: three neighbour planes meeting near the deleted faces. + let gap: Aabb3 = gap_vertices.iter().filter_map(|v| asm.point(*v)).collect(); + let near_gap = gap.inflated(gap.diagonal().max(size * 1e-3)); + let on = |p: Vec3, f: usize| planes.get(&f).is_some_and(|(n, d)| (n.dot(p) - d).abs() <= size * 1e-6); + let nb: Vec<(Vec3, f64)> = neighbours.iter().filter_map(|f| planes.get(f).copied()).collect(); + let mut corners: Vec = Vec::new(); + for (i, a) in nb.iter().enumerate() { + for (j, b) in nb.iter().enumerate().skip(i + 1) { + for c in nb.iter().skip(j + 1) { + let den = a.0.dot(b.0.cross(c.0)); + if den.abs() < 1e-9 { + continue; + } + let x = (b.0.cross(c.0) * a.1 + c.0.cross(a.0) * b.1 + a.0.cross(b.0) * c.1) / den; + if x.is_finite() && near_gap.contains(x) { + corners.push(x); + } + } + } + } + // Where each vertex on the gap goes: the nearest corner on all of its remaining planes. + let mut moved: HashMap = HashMap::new(); + for v in &gap_vertices { + let Some(fs) = vfaces.get(v) else { continue }; let keep: Vec = fs.iter().copied().filter(|x| !del.contains(x)).collect(); if keep.is_empty() || keep.len() >= 3 { continue; } if keep.iter().any(|x| !planes.contains_key(x)) { + let f = fs.iter().find(|x| del.contains(x)).copied().unwrap_or(0); return Err(fail(format!("a corner of face {f} touches a face that cannot move"))); } - let p = from_p3(v.point()); + let p = asm.point(*v).ok_or_else(|| fail("vertex"))?; let best = corners.iter().filter(|c| keep.iter().all(|x| on(**c, *x))).min_by(|a, b| a.dist(p).total_cmp(&b.dist(p))); if let Some(c) = best { - moved.insert(v.id(), *c); + moved.insert(*v, *c); } } - } - let q = size * 1e-7; - guard("delete face", || { - // Shared vertices and new straight edges between the rebuilt faces. - let mut verts: HashMap = HashMap::new(); - for v in body.solid.vertex_iter() { - if !moved.contains_key(&v.id()) { - verts.insert(key(from_p3(v.point()), q), v.clone()); + let q = size * 1e-7; + let mut shared = Shared { q, vertices: HashMap::new(), lines: HashMap::new() }; + for (i, v) in asm.vertices.iter().enumerate() { + if !moved.contains_key(&(i as u32)) { + shared.vertices.insert(key(Vec3::from(v.point), q), i as u32); } } - let mut lines: HashMap<(Key, Key), mt::Edge> = HashMap::new(); - let mut line = |a: Vec3, b: Vec3, verts: &mut HashMap| -> mt::Edge { - let (ka, kb) = (key(a, q), key(b, q)); - if let Some(e) = lines.get(&(ka, kb)) { - return e.clone(); - } - if let Some(e) = lines.get(&(kb, ka)) { - return e.inverse(); - } - let va = verts.entry(ka).or_insert_with(|| builder::vertex(p3(a))).clone(); - let vb = verts.entry(kb).or_insert_with(|| builder::vertex(p3(b))).clone(); - let e = builder::line(&va, &vb); - lines.insert((ka, kb), e.clone()); - e - }; - // Neighbours rebuilt from themselves, moved edges pieces of themselves; the edges that - // close the gap are new. - let mut rec = crate::record::Rebuild::default(); - let mut out: Vec = Vec::new(); - for (fi, f) in all.iter().enumerate() { + let mut history = Vec::new(); + let mut rebuilt: Vec<(usize, AFace)> = Vec::new(); + for fi in 0..n { if del.contains(&fi) { continue; } + let f = asm.faces.get(fi).and_then(Option::as_ref).ok_or_else(|| fail("face"))?.clone(); if !neighbours.contains(&fi) { // Untouched, unless one of its corners moves. - if f.vertex_iter().any(|v| moved.contains_key(&v.id())) { + if f.loops.iter().flatten().any(|u| corner_moves(&asm, &moved, u)) { return Err(fail(format!("face {fi} meets the gap only at a corner; it cannot follow"))); } - out.push(f.clone()); + history.push(crate::record::from_face(0, fi, Change::Kept)); continue; } - let pos = |v: &mt::Vertex| moved.get(&v.id()).copied().unwrap_or_else(|| from_p3(v.point())); - let gap = |e: &mt::Edge| efaces.get(&e.id()).is_some_and(|fs| fs.iter().any(|x| del.contains(x))); - // A face that only loses whole loops (a hole's rim, a pocket's opening) and has no - // corner moving keeps its own surface: rebuilding a plane from its outer boundary - // fails when imported edges are not exactly on one plane. - let mut stays = f.vertex_iter().all(|v| !moved.contains_key(&v.id())); - let mut kept: Vec = Vec::new(); - for w in f.absolute_boundaries() { - let gaps = w.edge_iter().filter(|e| gap(e)).count(); - if gaps == 0 { - kept.push(w.clone()); - } else if gaps != w.len() { - stays = false; + let mut loops: Vec> = Vec::new(); + for l in &f.loops { + let gaps = l.iter().filter(|u| gap_edge(u.edge)).count(); + if gaps == 0 && !l.iter().any(|u| corner_moves(&asm, &moved, u)) { + loops.push(l.clone()); + continue; } - } - if stays && !kept.is_empty() { - let mut face = mt::Face::try_new(kept, f.surface()).map_err(|e| fail(format!("face {fi} cannot close: {e}")))?; - if !f.orientation() { - face.invert(); - } - rec.face(&face, f); - out.push(face); - continue; - } - let mut wires: Vec = Vec::new(); - for w in f.boundaries() { - let edges: Vec = w.edge_iter().cloned().collect(); - if edges.iter().all(gap) { - // A hole or boss footprint disappears when its walls are removed. A - // face surrounded by rounds does not: its whole boundary moves back to - // the intersections of the remaining planes (#1557). Keep that loop, - // sharing its restored edges with the adjacent rebuilt faces. - let moving = edges.iter().any(|e| moved.contains_key(&e.front().id()) || moved.contains_key(&e.back().id())); - if moving { - if !edges.iter().all(|e| moved.contains_key(&e.front().id()) && moved.contains_key(&e.back().id())) { + if gaps == l.len() { + // A hole or boss footprint disappears when its walls are removed. A face + // surrounded by rounds does not: its whole boundary moves back to the + // intersections of the remaining planes (#1557), its restored edges shared + // with the adjacent rebuilt faces. + if !l.iter().any(|u| corner_moves(&asm, &moved, u)) { + continue; + } + let mut boundary = Vec::new(); + for u in l { + let (a, b) = asm.ends(u).ok_or_else(|| fail("edge"))?; + let (Some(pa), Some(pb)) = (moved.get(&a).copied(), moved.get(&b).copied()) else { return Err(fail(format!("face {fi} has a closed gap boundary that cannot be restored completely"))); + }; + if pa.dist(pb) > q * 10.0 { + let restored = shared.line(&mut asm, pa, pb)?; + asm.piece(restored.edge, u.edge); + boundary.push(restored); } - let mut boundary = Vec::new(); - for e in &edges { - let (a, b) = (pos(e.front()), pos(e.back())); - if a.dist(b) > q * 10.0 { - let restored = line(a, b, &mut verts); - rec.piece(&restored, e); - boundary.push(restored); - } - } - if !boundary.is_empty() { - wires.push(boundary.into()); - } + } + if !boundary.is_empty() { + loops.push(boundary); } continue; } // Start after a gap stretch so stretches don't wrap around. - let m = edges.len(); - let start = (0..m).find(|i| edges.get((i + m - 1) % m).is_some_and(gap) && edges.get(*i).is_some_and(|e| !gap(e))).unwrap_or(0); - let mut new_edges: Vec = Vec::new(); - // The moved corners along a gap stretch (two rounds meeting in a mitre leave - // the sharp corner between them). + let m = l.len(); + let is_gap = |k: usize| l.get(k).is_some_and(|u| gap_edge(u.edge)); + let start = (0..m).find(|i| is_gap((i + m - 1) % m) && !is_gap(*i)).unwrap_or(0); + let mut edges: Vec = Vec::new(); + // The moved corners along a gap stretch. let mut pending: Option> = None; - let close = |pts: Vec, a: Vec3| -> Vec<(Vec3, Vec3)> { - let mut c: Vec = Vec::new(); - for p in pts.into_iter().chain(std::iter::once(a)) { - if c.last().is_some_and(|l| l.dist(p) <= q * 10.0) { - continue; - } - // Drop a corner in line with its neighbours. - if let [.., x, y] = c[..] - && (y - x).cross(p - y).len() <= q * 10.0 * (p - x).len() - && (y - x).dot(p - y) > 0.0 - { - c.pop(); - } - c.push(p); - } - c.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect() - }; for k in 0..m { - let Some(e) = edges.get((start + k) % m) else { continue }; - if gap(e) { - pending.get_or_insert_with(Vec::new).extend([pos(e.front()), pos(e.back())]); + let Some(u) = l.get((start + k) % m) else { continue }; + let (va, vb) = asm.ends(u).ok_or_else(|| fail("edge"))?; + let (a, b) = (position(&asm, &moved, va)?, position(&asm, &moved, vb)?); + if gap_edge(u.edge) { + pending.get_or_insert_with(Vec::new).extend([a, b]); continue; } - let (a, b) = (pos(e.front()), pos(e.back())); if let Some(p) = pending.take() { - for (x, y) in close(p, a) { - new_edges.push(line(x, y, &mut verts)); + for (x, y) in close(p, a, q) { + edges.push(shared.line(&mut asm, x, y)?); } } - let moves = moved.contains_key(&e.front().id()) || moved.contains_key(&e.back().id()); - if !moves { - new_edges.push(e.clone()); - } else if matches!(e.oriented_curve(), mt::Curve::Line(_)) { + if !corner_moves(&asm, &moved, u) { + edges.push(u.clone()); + } else if matches!(asm.edges.get(u.edge as usize).map(|e| &e.curve), Some(Curve::Line { .. })) { if a.dist(b) > q * 10.0 { - let moved = line(a, b, &mut verts); - rec.piece(&moved, e); - new_edges.push(moved); + let stretched = shared.line(&mut asm, a, b)?; + asm.piece(stretched.edge, u.edge); + edges.push(stretched); } } else { return Err(fail(format!("face {fi} has a curved edge that would have to stretch"))); } } // A gap stretch at the end closes back to the first edge. - if let (Some(p), Some(first)) = (pending, new_edges.first()) { - let a = from_p3(first.front().point()); - for (x, y) in close(p, a) { - new_edges.push(line(x, y, &mut verts)); + if let (Some(p), Some(first)) = (pending, edges.first()) { + let (v0, _) = asm.ends(first).ok_or_else(|| fail("edge"))?; + let a = asm.point(v0).ok_or_else(|| fail("vertex"))?; + for (x, y) in close(p, a, q) { + edges.push(shared.line(&mut asm, x, y)?); } } - if new_edges.is_empty() { + if edges.is_empty() { return Err(fail(format!("face {fi} would lose its boundary"))); } - wires.push(new_edges.into()); + loops.push(edges); } - let face = builder::try_attach_plane(&wires).map_err(|e| fail(format!("face {fi} cannot close: {e}")))?; - // Keep the face's outward side. - let (nrm, _) = planes.get(&fi).copied().ok_or_else(|| fail("plane"))?; - let face = match face.surface() { - mt::Surface::Plane(pl) => { - let pn = pl.normal(); - let along = Vec3::new(pn.x, pn.y, pn.z).dot(nrm); - if (along > 0.0) == face.orientation() { face } else { face.inverse() } - } - _ => face, - }; - rec.face(&face, f); - out.push(face); + if loops.is_empty() { + return Err(fail(format!("face {fi} would lose its boundary"))); + } + // The face keeps its plane: every moved corner lies on it. + rebuilt.push((fi, AFace { loops, domain: None, ..f })); + history.push(crate::record::from_face(0, fi, Change::Modified)); } - let shell: mt::Shell = out.into(); - let solid = Solid::try_new(vec![shell]).map_err(|e| fail(format!("the neighbouring faces do not close the gap ({e})")))?; - crate::record::rebuilt(solid, &[&body.solid], &rec) + for &fi in &del { + if let Some(slot) = asm.faces.get_mut(fi) { + *slot = None; + } + } + for (fi, face) in rebuilt { + if let Some(slot) = asm.faces.get_mut(fi) { + *slot = Some(face); + } + } + let finished = asm.finish().map_err(|e| fail(format!("the neighbouring faces do not close the gap ({e})")))?; + crate::assemble::body_with_history(finished, &asm, body, history) }) } #[cfg(test)] mod tests { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; use super::delete_faces; use crate::{BoolOp, boolean, box_solid, chamfer, cylinder, fillet}; fn volume(b: &crate::Body) -> f64 { - b.tessellate(1e-3).unwrap().measure().volume + b.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume } /// The faces of `b` with every triangle corner passing `keep`. fn faces_where(b: &crate::Body, keep: impl Fn(Vec3) -> bool) -> Vec { - let m = b.tessellate(1e-3).unwrap(); + let m = b.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap(); let n = m.tri_face.iter().max().map(|x| *x as usize + 1).unwrap_or(0); (0..n) .filter(|f| { @@ -361,46 +352,15 @@ mod tests { let b = box_solid(Vec3::ZERO, Vec3::new(25.0, 25.0, 10.0)).unwrap(); let picks = [Vec3::new(12.5, 0.0, 0.0), Vec3::new(25.0, 12.5, 0.0), Vec3::new(12.5, 25.0, 0.0), Vec3::new(0.0, 12.5, 0.0)]; let rounded = fillet(&b, &picks, 2.0).unwrap(); + let record = crate::brep_record(&rounded).unwrap(); let rounds: Vec = - rounded.solid.face_iter().enumerate().filter(|(_, f)| crate::blend::plane_normal(f).is_none()).map(|(i, _)| i).collect(); + (0..record.faces.len()).filter(|i| !matches!(crate::offset::surf_of(&record, *i), Some(crate::offset::Surf::Plane { .. }))).collect(); assert_eq!(rounds.len(), 4); let restored = delete_faces(&rounded, &rounds).unwrap(); assert_eq!(restored.face_count(), 6); assert_eq!(restored.unmeshed_faces(), 0); assert!((volume(&restored) - 6250.0).abs() < 1e-6); - assert!(restored.contains(Vec3::new(0.1, 0.1, 0.1))); - } - - #[test] - fn delete_pocket_keeps_an_imported_face_around_it() { - use truck_modeling as mt; - // A shallow round pocket in the top of a plate whose top edges bow 5e-5 mm off the - // plane, as the edges of an imported part do: within the planar test, but too far for a - // plane rebuilt from them. The top only loses its inner loop, so it keeps its surface. - let plate = box_solid(Vec3::ZERO, Vec3::new(100.0, 100.0, 10.0)).unwrap(); - let tool = cylinder(Vec3::new(50.0, 50.0, 9.5), Vec3::Z, 7.5, 2.0).unwrap(); - let pocketed = boolean(&plate, &tool, BoolOp::Cut).unwrap().unwrap(); - let pocket = faces_where(&pocketed, |p| (p.x - 50.0).hypot(p.y - 50.0) < 7.5 + 1e-3 && p.z > 9.5 - 1e-6); - assert!(!pocket.is_empty()); - let mut bowed = 0; - for e in pocketed.solid.edge_iter() { - let (a, b) = (e.front().point(), e.back().point()); - if let mt::Curve::Line(_) = e.curve() - && (a.z - 10.0).abs() < 1e-9 - && (b.z - 10.0).abs() < 1e-9 - { - let lift = mt::Vector3::new(0.0, 0.0, 1e-4); - let mid = mt::Point3::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0, 10.0) + lift; - let c = if e.orientation() { vec![a, mid, b] } else { vec![b, mid, a] }; - e.set_curve(mt::Curve::BSplineCurve(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), c))); - bowed += 1; - } - } - assert_eq!(bowed, 4); - let filled = delete_faces(&pocketed, &pocket).unwrap(); - assert_eq!(filled.face_count(), 6); - assert_eq!(filled.unmeshed_faces(), 0); - assert!((volume(&filled) - 100000.0).abs() < 1e-3, "{}", volume(&filled)); + assert_eq!(restored.classify_point(Vec3::new(0.1, 0.1, 0.1)).unwrap(), crate::PointClass::Inside); } #[test] diff --git a/crates/kernel/src/display_mesh_tests.rs b/crates/kernel/src/display_mesh_tests.rs index d94945e20..a4ea0dcdb 100644 --- a/crates/kernel/src/display_mesh_tests.rs +++ b/crates/kernel/src/display_mesh_tests.rs @@ -1,10 +1,12 @@ //! The display mesh of a large body with small radii: bends and holes look round, the mesh //! stays closed, and the cost stays bounded. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Mesh, UnitVec3}; use super::{Body, DISPLAY_ANGLE}; use crate::{FaceSurface, extrude, face_surface}; @@ -150,14 +152,17 @@ fn rim(m: &Mesh, centre: Vec2, radius: f64, z: f64) -> (usize, f64) { (segments, widest) } +/// What the display mesh of a bent sheet 3000 mm long shows at its r1 and r3 bends, whose +/// sagitta is below the chord tolerance: each bend round, a quarter turn in facets that each turn +/// at most `DISPLAY_ANGLE` and so sag at most 1 − cos(angle / 2) of the radius, within the chord +/// tolerance. #[test] fn a_small_bend_on_a_large_sheet_is_meshed_round() { let b = bent_sheet(3000.0); let tol = display_tol(&b); // The tolerance is larger than either side's sagitta: 1 - cos 45° of the radius. assert!(tol > 3.0 * (1.0 - (PI / 4.0).cos())); - let coarse = b.display_mesh(tol).unwrap(); - let round = b.display_mesh_angular(tol, DISPLAY_ANGLE).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap(); // A quarter turn in facets of at most DISPLAY_ANGLE. let facets = (FRAC_PI_2 / DISPLAY_ANGLE).ceil() as usize; assert_eq!(facets, 5); @@ -165,9 +170,6 @@ fn a_small_bend_on_a_large_sheet_is_meshed_round() { let faces = cylinder_faces(&b, radius); assert_eq!(faces.len(), 1, "one bend face of radius {radius}"); let (face, origin, axis) = faces[0]; - // The chord tolerance alone: one flat strip from tangent line to tangent line. - assert_eq!(angles_around(&coarse, face, origin, *axis).len(), 2, "radius {radius}"); - assert!(sag(&coarse, face, origin, *axis, radius) > 0.29 * radius); let a = angles_around(&round, face, origin, *axis); assert!(a.len() > facets, "radius {radius}: {} facets across the bend", a.len() - 1); assert!((a[a.len() - 1] - FRAC_PI_2).abs() < 1e-6, "the bend is a quarter turn: {a:?}"); @@ -178,27 +180,14 @@ fn a_small_bend_on_a_large_sheet_is_meshed_round() { let s = sag(&round, face, origin, *axis, radius); assert!(s <= radius * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001 && s < tol, "radius {radius}: sag {s}"); } - // The flat faces along the sheet meet the bends in straight lines and need nothing more: - // only the bends, and the two ends where their arcs now have more points, gain triangles. - let count = |m: &Mesh, face: usize| m.tri_face.iter().filter(|f| **f as usize == face).count(); - let mut along = 0; - for face in 0..b.face_count() { - if let Some(FaceSurface::Plane { normal, .. }) = face_surface(&b, face) - && normal.dot(Vec3::Z).abs() < 0.5 - { - along += 1; - assert_eq!(count(&round, face), count(&coarse, face), "face {face}"); - } - } - assert_eq!(along, 6); } #[test] fn the_round_display_mesh_stays_closed_and_keeps_its_edges_and_bounds() { let b = bent_sheet(3000.0); let tol = display_tol(&b); - let coarse = b.display_mesh(tol).unwrap(); - let round = b.display_mesh_angular(tol, DISPLAY_ANGLE).unwrap(); + let coarse = b.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap(); // Neighbouring faces share the points of the edge between them. assert_eq!(open_sides(&round, 1e-6), 0); // The same edges in the same order, between the same faces, with the same ends and flags. @@ -223,8 +212,8 @@ fn a_small_hole_on_a_large_plate_has_a_round_rim() { let b = plate_with_holes(&[centre], 2.0); let tol = display_tol(&b); assert!(tol > 2.0, "the hole's radius is below the chord tolerance"); - let coarse = b.display_mesh(tol).unwrap(); - let round = b.display_mesh_angular(tol, DISPLAY_ANGLE).unwrap(); + let coarse = b.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap(); let segments = (TAU / DISPLAY_ANGLE).ceil() as usize; assert_eq!(segments, 18); for z in [0.0, 2.0] { @@ -249,15 +238,18 @@ fn a_small_hole_on_a_large_plate_has_a_round_rim() { fn an_arc_the_chord_tolerance_already_divides_finely_is_left_alone() { // A 40 mm cylinder at a tolerance of 0.01 mm: 64 facets around, far inside the angle. let b = crate::cylinder(Vec3::ZERO, Vec3::Z, 20.0, 30.0).unwrap(); - let coarse = b.display_mesh(0.01).unwrap(); - let round = b.display_mesh_angular(0.01, DISPLAY_ANGLE).unwrap(); + let coarse = b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(DISPLAY_ANGLE) }).unwrap(); assert_eq!(round.positions, coarse.positions); assert_eq!(round.triangles, coarse.triangles); assert_eq!(round.edges, coarse.edges); // And a body with nothing curved at any tolerance. let b = crate::box_solid(Vec3::ZERO, Vec3::new(3000.0, 1000.0, 2.0)).unwrap(); let tol = display_tol(&b); - assert_eq!(b.display_mesh_angular(tol, DISPLAY_ANGLE).unwrap().positions, b.display_mesh(tol).unwrap().positions); + assert_eq!( + b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap().positions, + b.mesh(&crate::MeshTolerance::chord(tol)).unwrap().positions + ); } #[test] @@ -268,14 +260,14 @@ fn a_radius_far_below_the_tolerance_keeps_its_chord_facets() { let centre = Vec2::new(30.0, 20.0); let b = plate_with_holes(&[centre], 0.002); let tol = display_tol(&b); - let coarse = b.display_mesh(tol).unwrap(); - let round = b.display_mesh_angular(tol, DISPLAY_ANGLE).unwrap(); + let coarse = b.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap(); assert_eq!(round.triangles.len(), coarse.triangles.len()); assert_eq!(round.edges, coarse.edges); // Just above the floor the rim is divided, but coarsely: the angle stops where the sag // falls below the floor, not where the facets reach the angle. let b = plate_with_holes(&[centre], 0.01); - let round = b.display_mesh_angular(display_tol(&b), DISPLAY_ANGLE).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: display_tol(&b), angle: Some(DISPLAY_ANGLE) }).unwrap(); let (n, _) = rim(&round, centre, 0.01, 2.0); assert!((3..18).contains(&n), "{n} segments"); } @@ -288,10 +280,10 @@ fn a_face_crowded_with_holes_gets_a_coarser_angle_and_bounded_work() { let centres: Vec = (0..50).flat_map(|i| (0..20).map(move |j| Vec2::new(30.0 + 60.0 * i as f64, 25.0 + 50.0 * j as f64))).collect(); let b = plate_with_holes(¢res, 2.0); let tol = display_tol(&b); - let coarse = b.display_mesh(tol).unwrap(); - let round = b.display_mesh_angular(tol, DISPLAY_ANGLE).unwrap(); + let coarse = b.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap(); let boundary = |m: &Mesh, z: f64| m.edges.iter().filter(|e| e.iter().all(|p| (p.z - z).abs() < 1e-6)).map(|e| e.len() - 1).sum::(); - let budget = truck_meshalgo::tessellation::Deflection::MAX_ANGLE_BOUNDARY; + let budget = crate::tess::size::MAX_ANGLE_BOUNDARY; for z in [0.0, 2.0] { // At the chord tolerance alone each rim is divided only as far as a face can be bounded // by it (two segments, a line, are divided again). @@ -313,7 +305,7 @@ fn a_face_crowded_with_holes_gets_a_coarser_angle_and_bounded_work() { assert_eq!(open_sides(&round, 1e-6), 0); // A plate with few holes keeps the full angle. let few = plate_with_holes(¢res[..40], 2.0); - let round = few.display_mesh_angular(display_tol(&few), DISPLAY_ANGLE).unwrap(); + let round = few.mesh(&crate::MeshTolerance { chord: display_tol(&few), angle: Some(DISPLAY_ANGLE) }).unwrap(); assert!(rim(&round, centres[0], 2.0, 2.0).0 >= 18); } @@ -325,7 +317,7 @@ fn round_faces_of_every_kind_are_divided_by_the_angle() { let bodies = [ ("sphere", crate::sphere(Vec3::ZERO, 4.0).unwrap()), ("torus", crate::torus(Vec3::ZERO, 6.0, 2.0).unwrap()), - ("cone", crate::extrude_tapered(&Plane::XY, &disc, 6.0, 1.0, -0.3).unwrap()), + ("cone", crate::extrude_tapered(&Plane::XY, &disc, 6.0, 1.0, -0.3, crate::DraftCorner::default()).unwrap()), ]; // The most the surface normal turns along one side of a triangle of a curved face. let turn = |b: &Body, m: &Mesh| { @@ -340,8 +332,8 @@ fn round_faces_of_every_kind_are_divided_by_the_angle() { .fold(0.0, f64::max) }; let check = |name: &str, b: &Body| { - let coarse = b.display_mesh(3.0).unwrap(); - let round = b.display_mesh_angular(3.0, DISPLAY_ANGLE).unwrap(); + let coarse = b.mesh(&crate::MeshTolerance::chord(3.0)).unwrap(); + let round = b.mesh(&crate::MeshTolerance { chord: 3.0, angle: Some(DISPLAY_ANGLE) }).unwrap(); // The chord tolerance alone leaves facets coarser than the angle (the size rules' longest // side and aspect limit already keep them near 40°), so the angle has work to do. assert!(turn(b, &coarse) > 1.5 * DISPLAY_ANGLE, "{name}: the chord tolerance leaves facets of {} degrees", turn(b, &coarse).to_degrees()); @@ -375,9 +367,10 @@ fn a_cylinder_wall_split_along_its_seam_meshes_round() { let outer: Vec = (0..cup.face_count()) .map(|i| matches!(face_surface(&cup, i), Some(FaceSurface::Cylinder { radius, .. }) if (radius - 50.0).abs() < 1e-6)) .collect(); - assert_eq!(outer.iter().filter(|o| **o).count(), 2); + // One periodic face (SMLib sweeps the one circle segment once), its seam split at z = 2. + assert_eq!(outer.iter().filter(|o| **o).count(), 1); for tol in [display_tol(&cup), 0.1, 0.01] { - let m = cup.tessellate(tol).unwrap(); + let m = cup.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); assert_eq!(open_sides(&m, 1e-6), 0); let v = mesh_volume(&m); assert!((v - exact).abs() < exact * 0.01, "tolerance {tol}: mesh volume {v:.1}, exact {exact:.1}"); @@ -403,7 +396,7 @@ fn outline_bounds_hold_the_display_mesh() { let rod = crate::cylinder(Vec3::new(5., 5., 0.), Vec3::Z, 4., 25.).unwrap(); for body in [cube, rounded, rod] { let outline = body.outline_bounds(); - let mesh = body.reference_display_mesh_angular(body.size() * 1e-3, crate::DISPLAY_ANGLE).unwrap().bounds(); + let mesh = body.mesh(&crate::MeshTolerance { chord: body.size() * 1e-3, angle: Some(crate::DISPLAY_ANGLE) }).unwrap().bounds(); let slack = body.size() * 1e-6; for (lo, hi, m_lo, m_hi) in [ (outline.min.x, outline.max.x, mesh.min.x, mesh.max.x), diff --git a/crates/kernel/src/distance.rs b/crates/kernel/src/distance.rs index 86a648012..71dccde70 100644 --- a/crates/kernel/src/distance.rs +++ b/crates/kernel/src/distance.rs @@ -5,18 +5,21 @@ //! one from both sides. The answer itself comes from the exact geometry. Near the nearest mesh //! points, each body offers the face there and the edges of that face that pass close by; the //! points are moved in turn to the nearest point of one feature from the other (alternating -//! projection) until they settle, on analytic surfaces in closed form and on other surfaces and -//! curves through the kernel's point inversion. A point that settles off its face (past the +//! projection) until they settle, on analytic surfaces in closed form, on other surfaces through +//! the record's point inversion ([`SurfaceEval::project`]) and on curves by a bracketed search of +//! the record curve's own points. A point that settles off its face (past the //! face's boundary) is dropped: the face's edges, offered too, then carry the minimum. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use std::sync::OnceLock; +use solidcore_record::Vec3; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; use solidcraft_geom::mesh_distance::{MeshClosest, TriangleSet}; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; -use truck_modeling as mt; +use solidcraft_geom::{Aabb3, Mesh}; -use crate::body::{Body, from_p3, p3}; +use crate::body::Body; use crate::surface_kind::{FaceSurface, surface_of}; use crate::{Result, guard}; @@ -40,8 +43,8 @@ pub struct DistanceShape<'a> { mesh: &'a Mesh, set: TriangleSet, chord: f64, - faces: Vec, - edges: Vec, + faces: Vec>, + edges: Vec>, surfaces: Vec>>, face_tris: OnceLock>>, } @@ -57,9 +60,9 @@ const ALONG: f64 = 1e-3; impl<'a> DistanceShape<'a> { /// `mesh` is `body`'s mesh, within `chord` (mm) of its faces. pub fn new(body: &'a Body, mesh: &'a Mesh, chord: f64) -> DistanceShape<'a> { - let exact = body.mesh.is_none(); - let faces: Vec = if exact { body.solid.face_iter().cloned().collect() } else { Vec::new() }; - let edges = if exact { Body::unique_edges(&body.solid) } else { Vec::new() }; + let record = body.record(); + let faces: Vec> = record.faces.iter().map(|f| SurfaceEval::new(f.parameters()).ok()).collect(); + let edges = record.edges.iter().map(|e| CurveEval::new(e.parameters()).ok().map(|c| (c, e.interval))).collect(); let surfaces = faces.iter().map(|_| OnceLock::new()).collect(); let chord = if chord.is_finite() && chord > 0.0 { chord } else { 0.0 }; DistanceShape { body, mesh, set: TriangleSet::new(mesh), chord, faces, edges, surfaces, face_tris: OnceLock::new() } @@ -81,7 +84,7 @@ impl<'a> DistanceShape<'a> { } fn surface(&self, face: usize) -> Option { - *self.surfaces.get(face)?.get_or_init(|| self.faces.get(face).and_then(|f| surface_of(f, self.body.size()))) + *self.surfaces.get(face)?.get_or_init(|| surface_of(self.body.record(), face)) } fn face_triangles(&self, face: u32) -> &[u32] { @@ -181,48 +184,52 @@ impl<'a> DistanceShape<'a> { /// The point of `f` nearest `p`, with the parameter hint for the next call. fn project(&self, f: Feature, p: Vec3, hint: &mut Hint) -> Option { - use mt::{ParametricSurface, SearchNearestParameter}; match f { Feature::Face(i) => { if let Some(q) = self.surface(i).and_then(|s| s.nearest(p)) { return Some(q); } - let s = self.faces.get(i)?.oriented_surface(); - let uv = s.search_nearest_parameter(p3(p), hint.uv, 100).or_else(|| s.search_nearest_parameter(p3(p), None, 100))?; + let s = self.faces.get(i)?.as_ref()?; + let uv = s.project(p, hint.uv, f64::INFINITY).or_else(|| s.project(p, None, f64::INFINITY))?; hint.uv = Some(uv); - Some(from_p3(s.subs(uv.0, uv.1))).filter(|q| q.is_finite()) + s.point(uv).filter(|q| q.is_finite()) } Feature::Edge(i) => self.edge_nearest(i, p, hint).map(|(q, _)| q), } } - /// The point of edge `i` nearest `p`, with the edge's direction there. + /// The point of edge `i` nearest `p`, with the edge's direction there: the nearest of evenly + /// spaced points along it (or the last call's), narrowed between its neighbours by golden + /// section on the record curve's own points. fn edge_nearest(&self, i: usize, p: Vec3, hint: &mut Hint) -> Option<(Vec3, Vec3)> { - use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - let c = self.edges.get(i)?.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let (lo, hi) = (t0.min(t1), t0.max(t1)); - let at = |t: f64| from_p3(c.subs(t)); + let (c, [t0, t1]) = self.edges.get(i)?.as_ref()?; + let (t0, t1) = (*t0, *t1); + let dist = |t: f64| c.point(t).map_or(f64::INFINITY, |q| q.dist(p)); + let n = 32; + let step = (t1 - t0) / f64::from(n); let start = match hint.t { - Some(t) => t, - None => { - // A coarse look along the curve, then the inversion from the best sample. - let n = 32; - (0..=n).map(|k| t0 + (t1 - t0) * f64::from(k) / f64::from(n)).min_by(|a, b| at(*a).dist(p).total_cmp(&at(*b).dist(p)))? - } + Some(t) if dist(t).is_finite() => t, + _ => (0..=n).map(|k| t0 + step * f64::from(k)).min_by(|a, b| dist(*a).total_cmp(&dist(*b)))?, }; - let mut best = (start.clamp(lo, hi), f64::INFINITY); - best.1 = at(best.0).dist(p); - for t in [c.search_nearest_parameter(p3(p), Some(start), 64).map(|t| t.clamp(lo, hi)), Some(t0), Some(t1)].into_iter().flatten() { - let d = at(t).dist(p); - if d < best.1 { - best = (t, d); + let (mut lo, mut hi) = ((start - step).max(t0), (start + step).min(t1)); + let golden = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..80 { + let (x, y) = (hi - golden * (hi - lo), lo + golden * (hi - lo)); + if dist(x) <= dist(y) { + hi = y; + } else { + lo = x; } } - hint.t = Some(best.0); - let d = c.der(best.0); - let q = at(best.0); - q.is_finite().then_some((q, Vec3::new(d.x, d.y, d.z))) + let t = [0.5 * (lo + hi), t0, t1].into_iter().min_by(|a, b| dist(*a).total_cmp(&dist(*b)))?; + hint.t = Some(t); + let q = c.point(t)?; + let h = (t1 - t0) * 1e-6; + let dir = match c.derivs(t) { + Some((_, d)) => d, + None => c.point((t + h).min(t1))? - c.point((t - h).max(t0))?, + }; + q.is_finite().then_some((q, dir)) } } @@ -234,7 +241,7 @@ enum Feature { #[derive(Clone, Copy, Default)] struct Hint { - uv: Option<(f64, f64)>, + uv: Option<[f64; 2]>, t: Option, } @@ -266,7 +273,7 @@ pub fn body_distance(a: &DistanceShape, b: &DistanceShape, limit: f64) -> Result let slack = 2.0 * (a.chord + b.chord); let Some(m) = a.mesh_closest(b, if limit.is_finite() { limit + slack } else { f64::INFINITY }) else { return Ok(None) }; let mesh = BodyDistance { distance: m.distance, from: m.a, to: m.b, exact: false }; - if a.faces.is_empty() || b.faces.is_empty() { + if a.body.is_mesh() || b.body.is_mesh() { return Ok(Some(mesh)); } // The face pairs near the nearest mesh points, each with its nearest triangle pair. diff --git a/crates/kernel/src/draft_corners.rs b/crates/kernel/src/draft_corners.rs new file mode 100644 index 000000000..885c5d4d6 --- /dev/null +++ b/crates/kernel/src/draft_corners.rs @@ -0,0 +1,228 @@ +//! How a tapered extrusion closes its profile's sharp corners ([`DraftCorner`]), and what each +//! rule gives at each corner of a profile ([`draft_corners`]), so a dialog can offer the others +//! where the chosen one is a poor fit. +//! +//! At the far end the profile is offset by the run of its sides (`distance · tan taper`). Where +//! a corner turns away from that offset the offset curves part, and the rule closes the gap: +//! [`DraftCorner::PreserveCurvature`] continues each curve as itself (a line along its line, an +//! arc along its circle) to where the two cross, [`DraftCorner::Tangent`] continues each straight +//! along its end tangent, [`DraftCorner::Round`] closes it with an arc about the corner. Where the +//! corner turns into the offset the offset curves overlap and every rule trims them where they +//! cross. +use serde::{Deserialize, Serialize}; +use solidcore_record::{Region2, Seg2, Vec2}; +use solidcraft_geom::prelude::*; + +use crate::Result; + +/// How a tapered extrusion closes the gap its offset opens at a sharp corner of the profile. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DraftCorner { + /// Each wall continues as itself (a line's plane, an arc's cone) until it meets its + /// neighbour: every section is the profile's curves offset and continued as themselves. + #[default] + PreserveCurvature, + /// Each offset curve continues straight along its end tangent (a flat face each side). + Tangent, + /// An arc about the corner (a cone about it). + Round, +} + +impl DraftCorner { + /// The three rules, in the order a dialog offers them. + pub const ALL: [DraftCorner; 3] = [DraftCorner::PreserveCurvature, DraftCorner::Tangent, DraftCorner::Round]; +} + +/// Why a rule cannot close a corner. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CornerRefusal { + /// The continued curves do not meet (two parallel lines, two circles that part). + Apart, + /// A curve of the profile is neither a line nor an arc: its wall has no exact continuation. + NotExact, + /// A wall at the corner closes before the far end (its arc shrinks to its centre). + WallCloses, +} + +/// What one rule gives at a corner, at the far end of the extrusion. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct CornerFill { + /// How far the offset curve before the corner and the one after it run on past their ends + /// to close it (negative: trimmed back where they overlap). For [`DraftCorner::Round`] the + /// arc's length is split between the two. + pub extension: [f64; 2], + /// Whether the corner cuts inside the exact offset of the corner itself (its far point is + /// nearer the profile's corner than the offset distance): the notch preserving curvature + /// makes where a curve bends back toward the solid. + pub inward: bool, +} + +/// What one rule gives at a corner, or why it cannot close it. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct CornerOption { + pub rule: DraftCorner, + pub fill: std::result::Result, +} + +/// One sharp corner of a profile and what each rule gives there. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CornerReport { + /// The corner on the profile, in the sketch's coordinates. + pub at: Vec2, + /// Whether the offset opens a gap there (the rules differ) or the offset curves overlap + /// (every rule trims them where they cross). + pub gap: bool, + /// [`DraftCorner::ALL`] in order. + pub options: [CornerOption; 3], +} + +/// An offset curve at the far end as its rule continues it: a line or a circle, or neither. +#[derive(Clone, Copy, Debug)] +enum Carrier { + Line { p: Vec2, d: Vec2 }, + Circle { c: Vec2, r: f64, ccw: bool }, + Free, +} + +/// The sharp corners of `region`'s outer loop (the loop a tapered extrusion takes) and what each +/// rule gives at each, for an extrusion `distance` long whose sides run out by `taper` radians +/// (positive grows the profile, as [`crate::extrude_tapered`] takes it). +pub fn draft_corners(region: &Region2, distance: f64, taper: f64) -> Result> { + crate::build::region_ok(region)?; + if !(distance.is_finite() && taper.is_finite()) { + return Err(crate::KernelError::Invalid("taper or distance is not finite".into())); + } + let outer = crate::build::oriented_outer(region)?; + let segs = &outer.segs; + let d = distance * taper.tan(); + let n = segs.len(); + // The walls are built as one exact set: a profile with a sharp corner keeps its curvature only + // when every curve is a line or an arc. + let free = segs.iter().any(|s| matches!(carrier(s, d), Carrier::Free)); + let mut out = Vec::new(); + for k in 0..n { + let (Some(a), Some(b)) = (segs.get((k + n - 1) % n), segs.get(k)) else { continue }; + let (ta, tb) = (a.end_tangent(), b.start_tangent()); + let turn = ta.cross(tb).atan2(ta.dot(tb)); + if turn.abs() <= 1e-9 { + continue; + } + let p = b.start(); + // The outer loop runs counterclockwise: growing moves each curve to its right. + let (ca, cb) = (carrier(a, d), carrier(b, d)); + let (ea, eb) = (a.end() + right(ta) * d, b.start() + right(tb) * d); + // A left turn opens a gap when the profile grows, a right turn when it shrinks. + let gap = (turn > 0.0) == (d > 0.0); + let curvature = if free { Err(CornerRefusal::NotExact) } else { continued(ca, cb, ea, eb, p, d) }; + let options = if gap { + [ + CornerOption { rule: DraftCorner::PreserveCurvature, fill: curvature }, + CornerOption { rule: DraftCorner::Tangent, fill: tangent(ea, ta, eb, tb, p, d) }, + CornerOption { + rule: DraftCorner::Round, + fill: Ok(CornerFill { extension: [0.5 * d.abs() * turn.abs(), 0.5 * d.abs() * turn.abs()], inward: false }), + }, + ] + } else { + // Overlapping offsets: every rule trims them where they cross. + let trim = curvature.map(|f| CornerFill { inward: false, ..f }); + DraftCorner::ALL.map(|rule| CornerOption { rule, fill: if rule == DraftCorner::PreserveCurvature { curvature } else { trim } }) + }; + out.push(CornerReport { at: p, gap, options }); + } + Ok(out) +} + +fn right(t: Vec2) -> Vec2 { + let t = t.normalized().unwrap_or(t); + Vec2::new(t.y, -t.x) +} + +/// `s` offset by `d` to its right, as the curve its far-end section continues along. +fn carrier(s: &Seg2, d: f64) -> Carrier { + match *s { + Seg2::Line { a, b } => match (b - a).normalized() { + Some(t) => Carrier::Line { p: a + right(t) * d, d: t }, + None => Carrier::Free, + }, + Seg2::Arc { center, radius, sweep, .. } => { + let ccw = sweep > 0.0; + // Right of a counterclockwise arc is away from its centre. + Carrier::Circle { c: center, r: if ccw { radius + d } else { radius - d }, ccw } + } + _ => Carrier::Free, + } +} + +/// The tangent rule: the end tangents' crossing. +fn tangent(ea: Vec2, ta: Vec2, eb: Vec2, tb: Vec2, p: Vec2, d: f64) -> std::result::Result { + let (ta, tb) = (ta.normalized().unwrap_or(ta), tb.normalized().unwrap_or(tb)); + let den = ta.cross(tb); + if den.abs() < 1e-12 { + return Err(CornerRefusal::Apart); + } + let s = (eb - ea).cross(tb) / den; + let x = ea + ta * s; + let t = (x - eb).dot(tb); + Ok(CornerFill { extension: [s, -t], inward: x.dist(p) < d.abs() - 1e-9 }) +} + +/// The curvature rule: the continued curves' crossing nearest the corner. +fn continued(ca: Carrier, cb: Carrier, ea: Vec2, eb: Vec2, p: Vec2, d: f64) -> std::result::Result { + for c in [ca, cb] { + match c { + Carrier::Free => return Err(CornerRefusal::NotExact), + Carrier::Circle { r, .. } if r <= 0.0 => return Err(CornerRefusal::WallCloses), + _ => {} + } + } + let mut cands: Vec = Vec::with_capacity(2); + match (ca, cb) { + (Carrier::Line { p: pa, d: da }, Carrier::Line { p: pb, d: db }) => { + let den = da.cross(db); + if den.abs() >= 1e-12 { + cands.push(pa + da * ((pb - pa).cross(db) / den)); + } + } + (Carrier::Line { p: l, d: dl }, Carrier::Circle { c, r, .. }) | (Carrier::Circle { c, r, .. }, Carrier::Line { p: l, d: dl }) => { + let w = l - c; + let bq = dl.dot(w); + let disc = bq * bq - (w.len2() - r * r); + if disc >= 0.0 { + let root = disc.sqrt(); + cands.extend([l + dl * (-bq - root), l + dl * (-bq + root)]); + } + } + (Carrier::Circle { c: c1, r: r1, .. }, Carrier::Circle { c: c2, r: r2, .. }) => { + let e = c2 - c1; + let dd = e.len(); + if dd > 1e-12 { + let e = e / dd; + let along = (r1 * r1 - r2 * r2 + dd * dd) / (2.0 * dd); + let h2 = r1 * r1 - along * along; + if h2 >= 0.0 { + let h = h2.sqrt(); + cands.extend([c1 + e * along + e.perp() * h, c1 + e * along - e.perp() * h]); + } + } + } + _ => {} + } + let Some(x) = cands.into_iter().min_by(|u, v| u.dist(p).total_cmp(&v.dist(p))) else { return Err(CornerRefusal::Apart) }; + let extension = [run(ca, ea, x), -run(cb, eb, x)]; + Ok(CornerFill { extension, inward: x.dist(p) < d.abs() - 1e-9 }) +} + +/// How far along a carrier, the way the profile runs, from `from` to `x`. +fn run(c: Carrier, from: Vec2, x: Vec2) -> f64 { + match c { + Carrier::Line { d, .. } => (x - from).dot(d), + Carrier::Circle { c, r, ccw } => { + let turn = (from - c).cross(x - c).atan2((from - c).dot(x - c)); + r * if ccw { turn } else { -turn } + } + Carrier::Free => 0.0, + } +} diff --git a/crates/kernel/src/edge_polyline_tests.rs b/crates/kernel/src/edge_polyline_tests.rs deleted file mode 100644 index a3d558573..000000000 --- a/crates/kernel/src/edge_polyline_tests.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! The vendored edge division evaluates each parameter once (the ends of a piece are carried -//! along, its midpoint is the probe and an end of both halves). Regressions against the division -//! as it was, which evaluated both ends of every piece again: the polylines must be the same, bit -//! for bit, including the fallbacks for samples that do not evaluate. -#![allow(clippy::unwrap_used, clippy::panic)] -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; - -use solidcraft_geom::Vec3; -use truck_meshalgo::prelude::PolylineCurve; -use truck_meshalgo::tessellation::{Deflection, TrySubs, bounded_polyline}; -use truck_modeling::{BoundedCurve, Curve, EuclideanSpace, MetricSpace, ParameterDivision1D, ParameterRange, ParametricCurve, Point3, Vector3}; - -use crate::*; - -/// A curve that counts its evaluations. -#[derive(Clone)] -struct Counted { - curve: Curve, - calls: Arc, -} - -impl Counted { - fn new(curve: &Curve) -> Self { - Counted { curve: curve.clone(), calls: Arc::default() } - } - - fn calls(&self) -> usize { - self.calls.load(Ordering::Relaxed) - } -} - -impl ParametricCurve for Counted { - type Point = Point3; - type Vector = Vector3; - fn subs(&self, t: f64) -> Point3 { - self.calls.fetch_add(1, Ordering::Relaxed); - self.curve.subs(t) - } - fn der(&self, t: f64) -> Vector3 { - self.curve.der(t) - } - fn der2(&self, t: f64) -> Vector3 { - self.curve.der2(t) - } - fn parameter_range(&self) -> ParameterRange { - self.curve.parameter_range() - } - fn period(&self) -> Option { - self.curve.period() - } -} - -impl BoundedCurve for Counted {} - -/// The division samples through `TrySubs`: count those evaluations. -impl TrySubs for Counted { - fn try_subs(&self, t: f64) -> Option { - self.calls.fetch_add(1, Ordering::Relaxed); - TrySubs::try_subs(&self.curve, t) - } - fn approx_subs(&self, t: f64) -> Point3 { - self.calls.fetch_add(1, Ordering::Relaxed); - TrySubs::approx_subs(&self.curve, t) - } -} - -impl ParameterDivision1D for Counted { - type Point = Point3; - fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { - self.curve.parameter_division(range, tol) - } -} - -/// `bounded_polyline` before it carried the end points: 4 evaluations per piece (both ends, the -/// probe and the midpoint), with the same fallbacks for samples that do not evaluate. -fn reference(curve: &Counted, range: (f64, f64), d: Deflection) -> PolylineCurve { - const MAX_EDGE_POINTS: usize = 20_000; - let (tol, turn2) = (d.chord, d.turn2()); - let end = |t: f64| curve.try_subs(t).unwrap_or_else(|| curve.approx_subs(t)); - let probe = |t: f64| curve.try_subs(t).unwrap_or(Point3::new(f64::NAN, f64::NAN, f64::NAN)); - let mut out = vec![end(range.0)]; - let mut stack: Vec<(f64, f64, usize)> = vec![(range.0, range.1, 0)]; - while let Some((a, b, depth)) = stack.pop() { - let (pa, pb) = (end(a), end(b)); - let t = a + (b - a) * 0.4729; - let chord = pa + (pb - pa) * 0.4729; - let d2 = probe(t).distance2(chord); - let tm = 0.5 * (a + b); - let dm = probe(tm).distance2(pa.midpoint(pb)); - let flat = !(d2 >= tol * tol || dm >= tol * tol); - let flat = flat && !d.turns(turn2, d2.max(dm), pa.distance2(pb)); - if flat || depth >= 24 || out.len() + stack.len() >= MAX_EDGE_POINTS { - out.push(pb); - } else { - stack.push((tm, b, depth + 1)); - stack.push((a, tm, depth + 1)); - } - } - PolylineCurve(out) -} - -/// Divides `curve` both ways and checks the points, their order and the evaluations; returns -/// the polyline. -fn same_division(curve: &Curve, d: Deflection) -> Vec { - let range = curve.range_tuple(); - let (before, after) = (Counted::new(curve), Counted::new(curve)); - let old = reference(&before, range, d).0; - let new = bounded_polyline(&after, range, d).0; - let bits = |p: &Point3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]; - assert_eq!(old.len(), new.len(), "{d:?}"); - for (i, (p, q)) in old.iter().zip(&new).enumerate() { - assert_eq!(bits(p), bits(q), "point {i} of {}: {p:?} before, {q:?} now ({d:?})", new.len()); - } - // Every piece is kept (one point) or halved: n points come from 2n - 3 pieces. - let pieces = 2 * new.len() - 3; - assert_eq!(before.calls(), 1 + 4 * pieces); - assert_eq!(after.calls(), 2 + 2 * pieces); - new -} - -/// The chord tolerance alone (booleans), then with the display's facet angle. -fn deflections(tol: f64) -> [Deflection; 2] { - [Deflection::chord(tol), Deflection { chord: tol, angle: DISPLAY_ANGLE, floor: tol * 0.05, display: true }] -} - -#[test] -fn intersection_curves_of_a_drilled_cylinder_divide_as_before() { - // The radial hole of a clamping hub: both cylinders are NURBS, so each point of the edges - // is two grid searches. - let hub = cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::Z, 8.0, 20.0).unwrap(); - let drill = cylinder(Vec3::new(-12.0, 0.0, 1.5), Vec3::X, 1.25, 24.0).unwrap(); - let drilled = boolean(&hub, &drill, BoolOp::Cut).unwrap().unwrap(); - let curves: Vec = drilled.solid.edge_iter().map(|e| e.curve()).filter(|c| matches!(c, Curve::IntersectionCurve(_))).collect(); - assert!(curves.len() >= 2, "{} intersection curves", curves.len()); - // One curve with each deflection (each division takes about half a second here). - for (curve, d) in curves.iter().zip(deflections(0.01)) { - let points = same_division(curve, d); - assert!(points.len() > 8, "{} points ({d:?})", points.len()); - // On the drill's wall. - for p in &points { - let r = (p.y * p.y + (p.z - 1.5) * (p.z - 1.5)).sqrt(); - assert!((r - 1.25).abs() < 1e-3, "{p:?} at {r} from the drill's axis"); - } - } -} - -#[test] -fn circle_divides_as_before() { - let body = cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap(); - let circle = body.solid.edge_iter().map(|e| e.curve()).find(|c| !matches!(c, Curve::Line(_))).unwrap(); - for d in deflections(0.001) { - let points = same_division(&circle, d); - assert!(points.len() > 18, "{} points ({d:?})", points.len()); - for p in &points { - assert!(((p.x * p.x + p.y * p.y).sqrt() - 5.0).abs() < 1e-9, "{p:?}"); - } - } -} diff --git a/crates/kernel/src/emboss.rs b/crates/kernel/src/emboss.rs index 94acc8c17..80dfd54be 100644 --- a/crates/kernel/src/emboss.rs +++ b/crates/kernel/src/emboss.rs @@ -1,12 +1,18 @@ -//! Exact radial embossing of orthogonal profiles on complete cylindrical walls. -use crate::body::{Body, Solid, from_p3, p3}; +//! Exact radial embossing of orthogonal profiles on complete cylindrical walls, built on the +//! body's schema 4 record: the wall's face loses the profiles' footprints, and each profile +//! adds its walls (planes, along the axis or square to it) and its raised or sunk cap (the +//! wall's cylinder at the new radius). +use crate::assemble::{AFace, AUse, Assembly}; +use crate::body::Body; use crate::history::Change; use crate::numbered::NumberedRegion; -use crate::offset::{Surf, surf_of}; -use crate::record::Operand; +use crate::offset::{Surf, face_edges, surf_of}; use crate::{KernelError, Result, guard}; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; -use truck_modeling::{self as mt, Transformed, builder}; +use solidcore_record::brep::{Brep, Curve, Frame, Loop, Surface}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::brep::form; +use solidcraft_geom::prelude::*; fn fail(s: &str) -> KernelError { KernelError::Invalid(format!("cylinder emboss: {s}")) @@ -16,34 +22,54 @@ fn angle(p: Vec3, o: Vec3, axis: Vec3, radial: Vec3, tangent: Vec3) -> f64 { let w = w - axis * w.dot(axis); w.dot(tangent).atan2(w.dot(radial)) } -fn unwrap(a: f64, around: f64) -> f64 { - around + (a - around + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI +fn arr(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] } -fn wall_angles(face: &mt::Face, o: Vec3, axis: Vec3, radial: Vec3, tangent: Vec3, tol: f64) -> Option<(f64, f64)> { - if face.boundaries().len() != 1 || face.edge_iter().count() != 4 { +/// The angles a wall face spans about the axis, seen from `radial`: from one of its arcs about +/// the axis (a face of one loop of four edge uses: two arcs and two lines, or a whole turn's two +/// circles and its seam used twice). +fn wall_angles(b: &Brep, face: usize, o: Vec3, axis: Vec3, radial: Vec3, tangent: Vec3) -> Option<(f64, f64)> { + let f = b.faces.get(face)?; + let [Loop::Edges { edges }] = f.loops.as_slice() else { return None }; + if edges.len() != 4 { return None; } - for edge in face.edge_iter() { - if let Some(Some(mid)) = crate::offset::arc_mid(&edge, tol * 10.) { - let am = angle(mid, o, axis, radial, tangent); - let aa = unwrap(angle(from_p3(edge.front().point()), o, axis, radial, tangent), am); - let ab = unwrap(angle(from_p3(edge.back().point()), o, axis, radial, tangent), am); - return Some((aa.min(ab), aa.max(ab))); + for u in edges { + let e = b.edges.get(u.edge as usize)?; + let Curve::Circle { frame, .. } = &e.curve else { continue }; + let z = Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis)); + if z.dot(axis).abs() < 1.0 - 1e-9 { + continue; } + // The circle's parameter is its angle: the wall spans the edge's angles on the circle + // (`interval` is on its NURBS form where it has one) about the angle of its middle (a + // whole turn, from the seam, for a wall in one piece). + let c = CurveEval::new(&e.curve).ok()?; + let [t0, t1] = solidcraft_geom::brep::label::edge_curve_interval(e)?; + let am = angle(c.point(0.5 * (t0 + t1))?, o, axis, radial, tangent); + let half = 0.5 * (t1 - t0); + return Some((am - half, am + half)); } None } +/// The body's record, for the queries below (a mesh body has none). +fn record(body: &Body) -> Result { + crate::native::brep_record(body) +} + /// Certify a tessellated pick and project it onto the cylinder used by emboss. pub fn cylinder_emboss_anchor(body: &Body, face: usize, at: Vec3) -> Result { if !at.is_finite() || at.len() > 1e9 { return Err(fail("invalid selected face point")); } guard("cylinder emboss anchor", || { - let f = body.solid.face_iter().nth(face).ok_or_else(|| fail("selected face"))?; - let tol = (body.size() * 1e-8).max(1e-8); - let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(f, tol) else { + let rec = record(body)?; + if face >= rec.faces.len() { + return Err(fail("selected face")); + } + let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(&rec, face) else { return Err(fail("selected face is not an exterior cylinder")); }; let w = at - o; @@ -92,13 +118,14 @@ pub fn infer_cylinder_emboss(body: &Body, plane: &Plane, regions: &[Region2], de return Ok(None); } guard("cylinder emboss inference", || { + let rec = record(body)?; let tol = (body.size() * 1e-8).max(1e-8); let mut tangent = false; - for (index, face) in body.solid.face_iter().enumerate() { - if index >= 50_000 { + for face in 0..rec.faces.len() { + if face >= 50_000 { return Err(fail("target search exceeds face work limit")); } - if let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(face, tol) { + if let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(&rec, face) { let w = plane.origin - o; let normal = plane.normal(); let signed = w.dot(normal); @@ -111,7 +138,7 @@ pub fn infer_cylinder_emboss(body: &Body, plane: &Plane, regions: &[Region2], de if !profile_interval_overlaps(plane, regions, o, a.cross(radial), -std::f64::consts::PI * r, std::f64::consts::PI * r)? { continue; } - if let Some((lo, hi)) = wall_angles(face, o, a, radial, a.cross(radial), tol) { + if let Some((lo, hi)) = wall_angles(&rec, face, o, a, radial, a.cross(radial)) { if lo >= -tol / r || hi <= tol / r { continue; } @@ -119,7 +146,7 @@ pub fn infer_cylinder_emboss(body: &Body, plane: &Plane, regions: &[Region2], de continue; } } - let relevant = match face_axial_bounds(face, o, a)? { + let relevant = match face_axial_bounds(&rec, face, o, a)? { Some((lo, hi)) => profile_interval_overlaps(plane, regions, o, a, lo, hi)?, None => true, }; @@ -148,18 +175,14 @@ pub fn has_cylinder_emboss_wall(body: &Body) -> Result { return Ok(false); } guard("cylinder emboss target", || { - let tol = (body.size() * 1e-8).max(1e-8); - for (index, face) in body.solid.face_iter().enumerate() { - if index >= 50_000 { - return Err(fail("target search exceeds face work limit")); - } - if matches!(surf_of(face, tol), Some(Surf::Cylinder { convex: true, .. })) { - return Ok(true); - } + let rec = record(body)?; + if rec.faces.len() > 50_000 { + return Err(fail("target search exceeds face work limit")); } - Ok(false) + Ok((0..rec.faces.len()).any(|face| matches!(surf_of(&rec, face), Some(Surf::Cylinder { convex: true, .. })))) }) } + fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Region2], depth: f64, qualify: bool) -> Result { body.require_brep("cylinder emboss")?; if !depth.is_finite() || depth.abs() < 1e-6 || depth.abs() > 1e6 || regions.is_empty() || regions.len() > 64 { @@ -175,13 +198,14 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi return Err(fail("invalid sketch frame")); } guard("cylinder emboss", || { - if body.solid.boundaries().len() != 1 || body.solid.face_iter().take(17).count() > 16 || body.solid.edge_iter().take(257).count() > 256 { + let rec = record(body)?; + if rec.shells.len() != 1 || rec.faces.len() > 16 || rec.edges.len() > 256 { return Err(fail("requires a complete cylinder or coaxial sleeve")); } - let faces: Vec<_> = body.solid.face_iter().cloned().collect(); let tol = (body.size() * 1e-8).max(1e-8); - let surfaces: Vec<_> = - faces.iter().map(|f| surf_of(f, tol).ok_or_else(|| fail("requires only cylindrical walls and planar endcaps"))).collect::>()?; + let surfaces: Vec = (0..rec.faces.len()) + .map(|f| surf_of(&rec, f).ok_or_else(|| fail("requires only cylindrical walls and planar endcaps"))) + .collect::>()?; let mut chosen = None; for (fi, s) in surfaces.iter().enumerate() { let Surf::Cylinder { o, a, r, convex: true } = *s else { continue }; @@ -192,11 +216,7 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi } let radial = radial.normalized().ok_or_else(|| fail("radial frame"))?; let tangent = a.cross(radial); - let f = faces.get(fi).ok_or_else(|| fail("face"))?; - if f.boundaries().len() != 1 || f.edge_iter().count() != 4 { - continue; - } - let Some((alo, ahi)) = wall_angles(f, o, a, radial, tangent, tol) else { + let Some((alo, ahi)) = wall_angles(&rec, fi, o, a, radial, tangent) else { continue; }; if alo >= -tol / r || ahi <= tol / r { @@ -246,10 +266,13 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi return Err(fail("depth reaches the axis or inner wall")); } if let Some(at) = anchor { + // The saved pick identifies the wall, not the face the sketch is tangent to: every + // exterior cylindrical face of the body is that wall (a stepped or interrupted + // cylinder was refused above), stored as several faces between its seams. So the + // pick lies on it wherever it is on the cylinder between the endcaps (#3782). let h = (at - o).dot(axis); let v = at - o - axis * h; - let theta = angle(at, o, axis, radial, tangent); - if (v.len() - r).abs() > tol * 10.0 || theta <= alo + tol / r || theta >= ahi - tol / r || h <= lo + tol || h >= hi - tol { + if (v.len() - r).abs() > tol * 10.0 || h <= lo + tol || h >= hi - tol { return Err(fail("saved selection no longer identifies the sketch's cylindrical face")); } } @@ -307,39 +330,18 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi let at = o + axis * p.y + (radial * (p.x / r).cos() + tangent * (p.x / r).sin()) * r; return Ok(EmbossOutcome::Anchor(fi, at)); } - let at = |p: Vec2, radius: f64| o + axis * p.y + (radial * (p.x / r).cos() + tangent * (p.x / r).sin()) * radius; - let selected = faces.get(fi).ok_or_else(|| fail("face"))?; - let mut base_patches = vec![selected.absolute_boundaries().clone()]; + let mut asm = Assembly::from_record(&rec)?; + let selected = asm.faces.get_mut(fi).and_then(Option::take).ok_or_else(|| fail("face"))?; + // The footprint's arcs lie on the wall face and are labelled on its frame, so their NURBS + // forms run on the face's own quarter grid and their pcurves there are exact. + let label = form::frame_of(&selected.surface); + let wall = Wrap { o, axis, radial, tangent, r, label, tol }; + // The wall's pieces left around the footprints: the face itself, then one per profile + // hole (the original radius inside it). + let mut base_patches: Vec>> = vec![selected.loops.clone()]; let mut hole_patches = Vec::new(); let mut footprints = Vec::new(); - let mut added = Vec::new(); - let k = rr / r; - let coord = |v: Vec3| [v.x, v.y, v.z]; - let av = coord(axis); - let ov = coord(o); - let mut m = [[0.0; 4]; 4]; - for (j, col) in m.iter_mut().take(3).enumerate() { - for (i, slot) in col.iter_mut().take(3).enumerate() { - *slot = if i == j { k } else { 0.0 } + (1.0 - k) * av.get(i).copied().unwrap_or(0.0) * av.get(j).copied().unwrap_or(0.0); - } - } - for (i, oi) in ov.iter().enumerate() { - let translation = - *oi - (0..3).map(|j| m.get(j).and_then(|row| row.get(i)).copied().unwrap_or(0.0) * ov.get(j).copied().unwrap_or(0.0)).sum::(); - if let Some(slot) = m.get_mut(3).and_then(|row| row.get_mut(i)) { - *slot = translation; - } - } - if let Some(slot) = m.get_mut(3).and_then(|row| row.get_mut(3)) { - *slot = 1.0; - } - let [c0, c1, c2, c3] = m; - let [a, b, c, d] = c0; - let [e, f, g, h] = c1; - let [i, j, l, n] = c2; - let [p, q, s, t] = c3; - let mat = mt::Matrix4::new(a, b, c, d, e, f, g, h, i, j, l, n, p, q, s, t); - let raised = selected.oriented_surface().transformed(mat); + let mut added: Vec = Vec::new(); // History of the faces added (walls from their profile segments, the raised or sunk // region the profile's end cap), in the order added. let mut added_history = Vec::new(); @@ -347,20 +349,21 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi let mut cap = Vec::new(); for (li, numbered_loop) in reg.loops().enumerate() { let lp = &numbered_loop.lp; - let (base, top, walls) = wrapped_loop(lp, r, rr, &at)?; + let (base, top, walls) = wall.wrapped_loop(&mut asm, lp, rr, selected.shell)?; // One wall per segment, in order. added_history.extend((0..walls.len()).map(|j| crate::record::profile(numbered_loop.numbers(j)))); + let hole = reversed(&base); if li == 0 { - footprints.push((lp, base.inverse())); + footprints.push((lp, hole)); } else { let index = base_patches.len(); - base_patches.push(vec![base.inverse()]); + base_patches.push(vec![hole]); hole_patches.push((lp, index)); } cap.push(top); added.extend(walls); } - added.push(mt::Face::try_new(cap, raised.clone()).map_err(|e| fail(&e.to_string()))?); + added.push(AFace { surface: wall.cylinder(rr), nurbs: None, natural_out: true, loops: cap, shell: selected.shell, domain: None }); added_history.push(crate::record::cap(true)); } // An island inside a profile hole cuts that hole's original-radius patch, @@ -375,27 +378,191 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi .unwrap_or(0); base_patches.get_mut(owner).ok_or_else(|| fail("profile ownership"))?.push(wire); } - let mut all: Vec<_> = faces.iter().enumerate().filter(|(i, _)| *i != fi).map(|(_, f)| f.clone()).collect(); // History (one operand, the body; profile numbering over `regions`), face by face as // gathered: the other faces kept, the wall's pieces left around the footprints (split // when the profile's holes leave more than one), then the faces added. let pieces = if base_patches.len() > 1 { Change::Split } else { Change::Modified }; - let mut history: Vec<_> = crate::record::kept_except(faces.len(), fi).collect(); + let mut history: Vec<_> = crate::record::kept_except(rec.faces.len(), fi).collect(); history.extend(std::iter::repeat_n(crate::record::from_face(0, fi, pieces), base_patches.len())); history.extend(added_history); - for patch in base_patches { - all.push(mt::Face::try_new(patch, selected.oriented_surface()).map_err(|e| fail(&e.to_string()))?); + for (k, loops) in base_patches.into_iter().enumerate() { + // The face's own parameter box only where it keeps its outer loop. + let domain = if k == 0 { selected.domain } else { None }; + asm.face(AFace { + surface: selected.surface.clone(), + nurbs: selected.nurbs.clone(), + natural_out: selected.natural_out, + loops, + shell: selected.shell, + domain, + }); } - all.extend(added); - let solid = Solid::try_new(vec![all.into()]).map_err(|e| fail(&e.to_string()))?; - let result = Body::new(solid)?; + for f in added { + asm.face(f); + } + let finished = asm.finish()?; + let result = crate::assemble::body_with_history(finished, &asm, body, history)?; if !result.validity().is_empty() { return Err(fail("rebuilt cylinder is not a closed manifold")); } - Ok(EmbossOutcome::Body(crate::record::attach(result, &[Operand::new(body)], Some(history), Default::default())?)) + Ok(EmbossOutcome::Body(result)) }) } +/// A loop's uses the other way round. +fn reversed(l: &[AUse]) -> Vec { + l.iter().rev().map(|u| AUse { edge: u.edge, forward: !u.forward, given: None }).collect() +} + +/// The wall a profile wraps onto: its axis, the sketch's radial and tangent directions there, +/// and its radius. +struct Wrap { + o: Vec3, + axis: Vec3, + radial: Vec3, + tangent: Vec3, + r: f64, + /// The wall face's own frame, which the arcs at its radius are labelled on. + label: Option, + tol: f64, +} + +impl Wrap { + /// The point at wrapped profile coordinates `p` (arc length at the wall, height) at `radius`. + fn at(&self, p: Vec2, radius: f64) -> Vec3 { + let t = p.x / self.r; + self.o + self.axis * p.y + (self.radial * t.cos() + self.tangent * t.sin()) * radius + } + + /// The wall's cylinder at `radius` (its angle measured from the sketch's radial). + fn cylinder(&self, radius: f64) -> Surface { + Surface::Cylinder { frame: Frame { origin: arr(self.o), x_axis: arr(self.radial), y_axis: arr(self.tangent) }, radius } + } + + /// An edge from vertex `a` at `p` to vertex `b` at `q` (wrapped coordinates) at `radius`: + /// an arc about the axis where the segment runs round the wall, else a line along it. The + /// use that runs from `a` to `b`. + fn edge(&self, asm: &mut Assembly, a: u32, b: u32, p: Vec2, q: Vec2, radius: f64) -> Result { + if (q.x - p.x).abs() <= 1e-10 { + return Ok(AUse { edge: asm.line(a, b)?, forward: true, given: None }); + } + let frame = Frame { origin: arr(self.o + self.axis * p.y), x_axis: arr(self.radial), y_axis: arr(self.tangent) }; + let (ta, tb) = (p.x / self.r, q.x / self.r); + let forward = ta < tb; + let (interval, ends) = if forward { ([ta, tb], (a, b)) } else { ([tb, ta], (b, a)) }; + let circle = Curve::Circle { frame, radius }; + let (circle, interval) = match &self.label { + Some(label) if (radius - self.r).abs() <= self.tol => form::on_frame(&circle, interval, label, self.tol).unwrap_or((circle, interval)), + _ => (circle, interval), + }; + Ok(AUse { edge: asm.edge(circle, interval, ends.0, ends.1)?, forward, given: None }) + } + + /// A profile loop wrapped onto the wall: its footprint at the wall's radius and its cap's + /// loop at `rr`, both running as the loop does, and one planar wall per segment between + /// them (each loop seen from outside the body). + fn wrapped_loop(&self, asm: &mut Assembly, lp: &Loop2, rr: f64, shell: usize) -> Result<(Vec, Vec, Vec)> { + let corners: Vec = lp.segs.iter().map(Seg2::start).collect(); + let base: Vec = corners.iter().map(|p| asm.vertex(self.at(*p, self.r))).collect::>()?; + let top: Vec = corners.iter().map(|p| asm.vertex(self.at(*p, rr))).collect::>()?; + let radial: Vec = base.iter().zip(&top).map(|(a, b)| asm.line(*a, *b)).collect::>()?; + let n = corners.len(); + let (mut be, mut te, mut walls) = (Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)); + for i in 0..n { + let j = (i + 1) % n; + let (Some(&p), Some(&q), Some(&ba), Some(&bb), Some(&ta), Some(&tb), Some(&ra), Some(&rb)) = + (corners.get(i), corners.get(j), base.get(i), base.get(j), top.get(i), top.get(j), radial.get(i), radial.get(j)) + else { + return Err(fail("loop topology")); + }; + let eb = self.edge(asm, ba, bb, p, q, self.r)?; + let et = self.edge(asm, ta, tb, p, q, rr)?; + // The wall's plane, its natural normal along the loop's turning: out of the + // material whether the cap is raised or sunk. + let mid = (p + q) * 0.5; + let ring = [self.at(p, self.r), self.at(mid, self.r), self.at(q, self.r), self.at(q, rr), self.at(mid, rr), self.at(p, rr)]; + let normal = newell(&ring).ok_or_else(|| fail("a wall of no area"))?; + let u = (ring[2] - ring[0]).normalized().ok_or_else(|| fail("a wall of no width"))?; + let u = (u - normal * u.dot(normal)).normalized().ok_or_else(|| fail("a wall of no width"))?; + let surface = Surface::Plane { origin: arr(ring[0]), u_axis: arr(u), v_axis: arr(normal.cross(u)) }; + let lp = vec![ + eb.clone(), + AUse { edge: rb, forward: true, given: None }, + AUse { edge: et.edge, forward: !et.forward, given: None }, + AUse { edge: ra, forward: false, given: None }, + ]; + walls.push(AFace { surface, nurbs: None, natural_out: true, loops: vec![lp], shell, domain: None }); + be.push(eb); + te.push(et); + } + Ok((be, te, walls)) + } +} + +/// The unit normal of a planar ring of points, along its turning (right-hand rule). +fn newell(ring: &[Vec3]) -> Option { + let n = ring.len(); + let mut s = Vec3::ZERO; + for i in 0..n { + let (a, b) = (*ring.get(i)?, *ring.get((i + 1) % n)?); + s += a.cross(b); + } + s.normalized() +} + +/// The span along `axis` from `o` of face `face`'s edges, from their exact bounds (a line's +/// ends, a circle's extreme heights, a spline's control points); `None` for any other curve. +fn face_axial_bounds(b: &Brep, face: usize, o: Vec3, axis: Vec3) -> Result> { + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + let mut count = 0usize; + let mut add = |z0: f64, z1: f64| -> Result<()> { + count = count.saturating_add(1); + if count > 100_000 || !z0.is_finite() || !z1.is_finite() { + return Err(fail("target boundary work limit or nonfinite geometry")); + } + lo = lo.min(z0); + hi = hi.max(z1); + Ok(()) + }; + let height = |p: Vec3| (p - o).dot(axis); + for e in face_edges(b, face) { + let edge = b.edges.get(e as usize).ok_or_else(|| fail("edge"))?; + match &edge.curve { + Curve::Line { .. } => { + let c = CurveEval::new(edge.parameters()).map_err(|e| fail(&e.to_string()))?; + for t in edge.interval { + let z = height(c.point(t).ok_or_else(|| fail("edge point"))?); + add(z, z)?; + } + } + Curve::Circle { frame, radius } => { + let (x, y) = (Vec3::from(frame.x_axis), Vec3::from(frame.y_axis)); + let z = height(Vec3::from(frame.origin)); + let reach = radius * x.dot(axis).hypot(y.dot(axis)); + add(z - reach, z + reach)?; + } + Curve::Spline { points, .. } => { + for p in points { + let z = height(Vec3::from(*p)); + add(z, z)?; + } + } + Curve::RationalSpline { homogeneous, .. } => { + for h in homogeneous { + if !h[3].is_finite() || h[3] <= 0.0 { + return Ok(None); + } + let z = height(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])); + add(z, z)?; + } + } + Curve::Ellipse { .. } | Curve::Polyline { .. } | Curve::SurfaceIntersection { .. } => return Ok(None), + } + } + Ok((lo.is_finite() && hi.is_finite()).then_some((lo, hi))) +} + fn profile_interval_overlaps(plane: &Plane, regions: &[Region2], o: Vec3, axis: Vec3, lo: f64, hi: f64) -> Result { let z0 = (plane.origin - o).dot(axis); let direction = Vec2::new(plane.x.dot(axis), plane.y.dot(axis)); @@ -442,7 +609,7 @@ fn profile_interval_overlaps(plane: &Plane, regions: &[Region2], o: Vec3, axis: add(p)?; } } - Seg2::Bezier { n, p } if (1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(&n) => { + Seg2::Bezier { n, p } if (1..=solidcore_record::MAX_BEZIER_DEGREE as u8).contains(&n) => { for p in p.iter().take(usize::from(n) + 1) { add(*p)?; } @@ -455,70 +622,6 @@ fn profile_interval_overlaps(plane: &Plane, regions: &[Region2], o: Vec3, axis: Ok(overlaps) } -fn face_axial_bounds(face: &mt::Face, o: Vec3, axis: Vec3) -> Result> { - let mut lo = f64::INFINITY; - let mut hi = f64::NEG_INFINITY; - let mut count = 0usize; - let mut add = |point: Vec3| -> Result<()> { - count = count.saturating_add(1); - if count > 100_000 || !point.is_finite() { - return Err(fail("target boundary work limit or nonfinite geometry")); - } - let z = (point - o).dot(axis); - lo = lo.min(z); - hi = hi.max(z); - Ok(()) - }; - for edge in face.edge_iter() { - match edge.curve() { - mt::Curve::Line(_) => { - add(from_p3(edge.front().point()))?; - add(from_p3(edge.back().point()))?; - } - mt::Curve::BSplineCurve(curve) => { - for point in curve.control_points() { - add(from_p3(*point))?; - } - } - mt::Curve::NurbsCurve(curve) => { - for point in curve.control_points() { - if !point.w.is_finite() || point.w <= 0.0 { - return Ok(None); - } - add(Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w))?; - } - } - mt::Curve::IntersectionCurve(_) => return Ok(None), - } - } - Ok((lo.is_finite() && hi.is_finite()).then_some((lo, hi))) -} - -fn wrapped_loop(lp: &Loop2, r: f64, rr: f64, at: &impl Fn(Vec2, f64) -> Vec3) -> Result<(mt::Wire, mt::Wire, Vec)> { - let base: Vec<_> = lp.segs.iter().map(|s| builder::vertex(p3(at(s.start(), r)))).collect(); - let top: Vec<_> = lp.segs.iter().map(|s| builder::vertex(p3(at(s.start(), rr)))).collect(); - let radial: Vec<_> = base.iter().zip(&top).map(|(a, b)| builder::line(a, b)).collect(); - let mut be = Vec::new(); - let mut te = Vec::new(); - let mut walls = Vec::new(); - for (i, s) in lp.segs.iter().enumerate() { - let next = (i + 1) % lp.segs.len(); - let (Some(a), Some(b), Some(c), Some(d), Some(ra), Some(rb)) = - (base.get(i), base.get(next), top.get(i), top.get(next), radial.get(i), radial.get(next)) - else { - return Err(fail("loop topology")); - }; - let circular = (s.end().x - s.start().x).abs() > 1e-10; - let eb = if circular { builder::circle_arc(a, b, p3(at(s.mid(), r))) } else { builder::line(a, b) }; - let et = if circular { builder::circle_arc(c, d, p3(at(s.mid(), rr))) } else { builder::line(c, d) }; - let w: mt::Wire = vec![eb.clone(), rb.clone(), et.inverse(), ra.inverse()].into(); - walls.push(builder::try_attach_plane(&[w]).map_err(|e| fail(&e.to_string()))?); - be.push(eb); - te.push(et); - } - Ok((be.into(), te.into(), walls)) -} - fn validate_profiles(regions: &[Region2], tol: f64) -> Result<()> { let loops: Vec<_> = regions.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).collect(); let edges: Vec<_> = loops.iter().enumerate().flat_map(|(l, lp)| lp.segs.iter().enumerate().map(move |(i, s)| (l, i, *s))).collect(); @@ -615,9 +718,9 @@ mod tests { Region2 { outer: Loop2::polygon(&[Vec2::new(-5., 5.), Vec2::new(-1., 5.), Vec2::new(-1., 10.), Vec2::new(-5., 10.)]), holes: vec![] }; let (_, other_anchor) = infer_cylinder_emboss(&near, &shifted, std::slice::from_ref(&shifted_profile), 1.).unwrap().unwrap(); assert!(other_anchor.dist(anchor) < 1e-10); - let before = near.tessellate_with(1e-4, true).unwrap().measure().volume; + let before = near.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let result = emboss_cylinder_at(&near, other_anchor, &shifted, &[shifted_profile], 1.).unwrap(); - assert!((result.tessellate_with(1e-4, true).unwrap().measure().volume - before - 21.).abs() < 0.02); + assert!((result.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume - before - 21.).abs() < 0.02); assert!(infer_cylinder_emboss(&near, &plane(), ®ions, -10.).is_err()); let inward = Plane::new(Vec3::Y * 10., Vec3::X, Vec3::Z).unwrap(); assert!(infer_cylinder_emboss(&near, &inward, ®ions, 1.).unwrap_err().to_string().contains("outwards")); @@ -629,16 +732,16 @@ mod tests { ring.holes.push(Loop2::polygon(&[Vec2::new(-1., 6.), Vec2::new(1., 6.), Vec2::new(1., 9.), Vec2::new(-1., 9.)])); let island = Region2 { outer: Loop2::polygon(&[Vec2::new(-0.5, 6.5), Vec2::new(0.5, 6.5), Vec2::new(0.5, 8.5), Vec2::new(-0.5, 8.5)]), holes: vec![] }; - let before = body.tessellate_with(1e-4, true).unwrap().measure().volume; + let before = body.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; for depth in [1., -1.] { for regions in [vec![ring.clone(), island.clone()], vec![island.clone(), ring.clone()]] { let result = emboss_cylinder(&body, &plane(), ®ions, depth).unwrap(); assert_eq!(result.shell_count(), 1); assert!(result.validity().is_empty()); - let after = result.tessellate_with(1e-4, true).unwrap().measure().volume; + let after = result.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let expected = 16. * (depth + depth * depth / 20.); assert!((after - before - expected).abs() < 0.02, "{} vs {expected}", after - before); - let mesh = result.tessellate_with(0.001, true).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); for (s, raised) in [(0., true), (0.75, false), (1.5, true)] { let radial = -Vec3::X * (s / 10.0_f64).sin() + Vec3::Y * (s / 10.0_f64).cos(); let radius = if depth > 0. { 10.5 } else { 9.5 }; @@ -655,11 +758,11 @@ mod tests { let result = emboss_cylinder(&body, &plane(), &[profile()], depth).unwrap(); assert_eq!(result.shell_count(), 1); assert!(result.validity().is_empty()); - let before = body.tessellate_with(1e-4, true).unwrap().measure().volume; - let after = result.tessellate_with(1e-4, true).unwrap().measure().volume; + let before = body.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; + let after = result.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let expected = if depth > 0. { 21. } else { -19. }; assert!((after - before - expected).abs() < 0.02, "{} vs {expected}", after - before); - let mesh = result.tessellate_with(0.001, true).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); for s in [-1.5, 0., 1.5] { let radial = -Vec3::X * (s / 10.0_f64).sin() + Vec3::Y * (s / 10.0_f64).cos(); assert_eq!(mesh.contains(radial * (if depth > 0. { 10.5 } else { 9.5 }) + Vec3::Z * 7.5), depth > 0.); @@ -692,12 +795,12 @@ mod tests { for depth in [1., -1.] { let result = emboss_cylinder_at(&body, origin + radial * 10.0 + axis * 7.5, &plane, std::slice::from_ref(&profile), depth).unwrap(); assert_eq!(result.shell_count(), 1); - let before = body.tessellate_with(1e-4, true).unwrap().measure().volume; - let after = result.tessellate_with(1e-4, true).unwrap().measure().volume; + let before = body.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; + let after = result.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let want = profile.area().abs() * (depth + depth * depth / 20.0); assert!((after - before - want).abs() < 0.02, "{} vs {want}", after - before); let point = |s: f64, z: f64, r: f64| origin + axis * z + (radial * (s / 10.0).cos() + tangent * (s / 10.0).sin()) * r; - let mesh = result.tessellate_with(0.001, true).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); for (s, z) in [(-1.5, 7.5), (1.5, 7.5), (0.5, 6.5)] { let material = profile.contains(Vec2::new(s, z)); assert_eq!(mesh.contains(point(s, z, if depth > 0. { 10.5 } else { 9.5 })), if depth > 0. { material } else { !material }); @@ -707,7 +810,7 @@ mod tests { assert_eq!(imported.bodies.len(), 1); let round = imported.bodies.first().unwrap(); assert!(round.body.validity().is_empty()); - let roundmesh = round.body.tessellate_with(0.001, true).unwrap(); + let roundmesh = round.body.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); assert_eq!(roundmesh.contains(point(-1.5, 7.5, if depth > 0. { 10.5 } else { 9.5 })), depth > 0.); let cut = crate::boolean( &round.body, @@ -716,7 +819,7 @@ mod tests { ) .unwrap() .unwrap(); - assert!(!cut.tessellate(0.01).unwrap().contains(point(-1.5, 7.5, 9.0))); + assert!(!cut.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().contains(point(-1.5, 7.5, 9.0))); } } } @@ -744,7 +847,9 @@ mod tests { ] { assert!(emboss_cylinder(&sleeve, &plane(), &profiles, d).is_err()); } - assert!(emboss_cylinder_at(&sleeve, -Vec3::Y * 10. + Vec3::Z * 7.5, &plane(), &[profile()], 1.).is_err()); + // A pick anywhere on the exterior wall identifies it (#3782); one on the bore does not. + assert!(emboss_cylinder_at(&sleeve, -Vec3::Y * 10. + Vec3::Z * 7.5, &plane(), &[profile()], 1.).is_ok()); + assert!(emboss_cylinder_at(&sleeve, -Vec3::Y * 8. + Vec3::Z * 7.5, &plane(), &[profile()], 1.).is_err()); assert_eq!(crate::step_export(&[&sleeve], "unchanged").unwrap(), before); } } diff --git a/crates/kernel/src/empty_retry_tests.rs b/crates/kernel/src/empty_retry_tests.rs deleted file mode 100644 index 318bbe87a..000000000 --- a/crates/kernel/src/empty_retry_tests.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! A shallow circular cut after a pocket (#1765): repeated empty numerical answers must not -//! stop the later geometric strategies. Inject the numerical failure on a real small part; -//! the exact rounding and ray classification of the original design are not available. - -use super::*; -use crate::{box_solid, cylinder, fillet, measure, sphere, step_export, step_import}; -use std::cell::Cell; -use std::f64::consts::PI; - -#[test] -fn shallow_cut_after_a_pocket_recovers_from_empty_numerical_attempts() { - let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(); - let plate = fillet(&plate, &[Vec3::new(20.0, 0.0, 10.0)], 2.0).unwrap(); - let pocket = box_solid(Vec3::new(5.0, 15.0, 9.25), Vec3::new(35.0, 25.0, 10.25)).unwrap(); - let target = boolean(&plate, &pocket, BoolOp::Cut).unwrap().unwrap(); - let tool = cylinder(Vec3::new(12.0, 15.0, 8.5), Vec3::Z, 5.0, 1.75).unwrap(); - let attempts = Cell::new(0); - let empty = |_: &Body, _: &Body, _: BoolOp, _: Option, _: f64| { - attempts.set(attempts.get() + 1); - Ok((Solid::new_unchecked(Vec::new()), None)) - }; - let (result, diagnostics) = - capture_boolean_diagnostics(|| boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty))); - assert!(attempts.get() >= 2, "the first two numerical tries must really have failed"); - let cut = result.unwrap().expect("a shallow cut leaves the plate"); - assert!(cut.validity().is_empty(), "{:?}", cut.validity()); - assert_eq!(cut.lumps().unwrap().len(), 1); - // Half of the circle overlaps the existing 0.75 mm pocket. - let expected = 40.0 * 30.0 * 10.0 - (4.0 - PI) * 40.0 - 30.0 * 10.0 * 0.75 - PI * 25.0 * (1.5 - 0.75 / 2.0); - let actual = measure(&cut).unwrap().volume; - assert!((actual - expected).abs() < 0.02, "{actual} vs {expected}"); - assert!(diagnostics.events.iter().all(|e| e.strategy != BooleanStrategy::RefinedTolerance)); -} - -#[test] -fn step_seam_cut_recovers_from_empty_numerical_attempts() { - let pin = cylinder(Vec3::new(-5.0, 0.0, 0.0), Vec3::X, 4.5, 10.0).unwrap(); - let target = step_import(&step_export(&[&pin], "seam regression").unwrap()).unwrap().bodies.remove(0).body; - let tool = sphere(Vec3::new(-5.0, 0.0, 0.0), 6.0).unwrap(); - assert!(crate::seam_faces::needed(&target, &tool)); - let attempts = Cell::new(0); - let shifted_attempts = Cell::new(0); - let empty = |_: &Body, _: &Body, _: BoolOp, shift: Option, _: f64| { - attempts.set(attempts.get() + 1); - if shift.is_some() { - shifted_attempts.set(shifted_attempts.get() + 1); - } - Ok((Solid::new_unchecked(Vec::new()), None)) - }; - let (result, diagnostics) = - capture_boolean_diagnostics(|| boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty))); - assert!(attempts.get() >= 2, "the initial numerical tries must really have failed"); - assert_eq!(shifted_attempts.get(), 0, "seam recovery must precede displaced retries"); - let cut = result.unwrap().expect("the spherical cut leaves the end of the pin"); - assert!(cut.validity().is_empty(), "{:?}", cut.validity()); - assert_eq!(cut.lumps().unwrap().len(), 1); - assert!(cut.history().is_some()); - // Along the common axis, integrate min(pi*4.5^2, pi*(6^2-x^2)) from 0 to 6. - let full_radius_end = (6.0_f64.powi(2) - 4.5_f64.powi(2)).sqrt(); - let removed = PI * (4.5_f64.powi(2) * full_radius_end + 36.0 * (6.0 - full_radius_end) - (216.0 - full_radius_end.powi(3)) / 3.0); - let expected = PI * 4.5_f64.powi(2) * 10.0 - removed; - let actual = measure(&cut).unwrap().volume; - assert!((actual - expected).abs() < expected * 1e-3, "{actual} vs {expected}"); - assert!(diagnostics.warning().is_none(), "{:?}", diagnostics.warning()); -} - -#[test] -fn unrecovered_empty_attempts_keep_refusal_without_displacing_tool() { - // These spheres keep fine_tols empty, isolating retries after the exact local strategies. - let target = sphere(Vec3::ZERO, 10.0).unwrap(); - let tool = sphere(Vec3::new(8.0, 0.0, 0.0), 5.0).unwrap(); - let shifted_attempts = Cell::new(0); - let empty = |_: &Body, _: &Body, _: BoolOp, shift: Option, _: f64| { - if shift.is_some() { - shifted_attempts.set(shifted_attempts.get() + 1); - } - Ok((Solid::new_unchecked(Vec::new()), None)) - }; - let result = boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty)); - assert_eq!(shifted_attempts.get(), 0, "unrecovered empty attempts must not enable displaced retries"); - let error = result.unwrap_err(); - assert!(error.to_string().contains("it came out empty"), "{error}"); -} diff --git a/crates/kernel/src/face_params.rs b/crates/kernel/src/face_params.rs deleted file mode 100644 index 5011a1bdf..000000000 --- a/crates/kernel/src/face_params.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! A face's boundary in its surface's parameters, and exact parameter lines on a surface: -//! shared by the operations that rework a face on the surface it lies on (Untrim, Extend). -//! -//! A face's loops are sampled into parameters with periodic directions unwrapped along each -//! loop; which loop is the outer one is worked out from those parameters (the loop enclosing -//! the most area), never from the order the loops are stored in: an imported face can list -//! its holes first. - -use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface, SearchNearestParameter, Transformed}; -use solidcraft_geom::tess::EvalSurface; -use solidcraft_geom::{Ring, Vec3}; -use truck_modeling as mt; - -use crate::body::from_p3; -use crate::tess::uv::{self, Domain}; -use crate::{KernelError, Result}; - -/// Samples along each boundary edge when working out the face's parameter loops. -pub(crate) const EDGE_SAMPLES: usize = 32; -/// Golden-section steps that place an extreme of the face's span on an edge. -const EXTREME_STEPS: usize = 60; - -/// A boundary loop of a face sampled in 3D and in the surface's parameters: for each of its -/// edges (as the loop runs) the curve parameters, points and parameters of its samples, ends -/// included. Periodic parameters are unwrapped along the loop. -pub(crate) struct LoopSamples { - pub(crate) edges: Vec<(mt::Curve, Vec<(f64, Vec3, [f64; 2])>)>, -} - -impl LoopSamples { - /// The loop as a polygon in parameters (each edge's samples but its last, which the next - /// edge starts on). - pub(crate) fn polygon(&self) -> Ring<[f64; 2]> { - self.edges.iter().flat_map(|(_, s)| s.iter().take(s.len().saturating_sub(1)).map(|x| x.2)).collect() - } - - /// Signed area of the loop in parameters (positive: counter-clockwise). - pub(crate) fn area(&self) -> f64 { - self.polygon().signed_area() - } - - /// How far `p` is from the loop (from its samples). - pub(crate) fn dist(&self, p: Vec3) -> f64 { - self.edges.iter().flat_map(|(_, s)| s.iter().map(|x| x.1.dist(p))).fold(f64::INFINITY, f64::min) - } -} - -/// A face's boundary loops (absolute: as they run on its surface) in the surface's parameters, -/// and which of them is the outer one. -pub(crate) struct FaceLoops { - pub(crate) eval: EvalSurface, - pub(crate) dom: Domain, - pub(crate) wires: Vec, - pub(crate) loops: Vec, - pub(crate) outer: usize, -} - -impl FaceLoops { - /// The loops of `face`, its boundary found on its surface within `accept`; `what` names the - /// operation for a surface no evaluator takes. - pub(crate) fn of(face: &mt::Face, accept: f64, what: &str) -> Result { - let eval = crate::tess::surface::eval_surface(&face.surface()) - .ok_or_else(|| KernelError::TooLarge(format!("{what} a face on this kind of surface")))?; - let dom = uv::domain(&eval); - let wires: Vec = face.absolute_boundaries().clone(); - let loops: Vec = wires.iter().map(|w| sample_loop(&eval, &dom, w, accept)).collect::>()?; - // The outer loop encloses the others: the most area in parameters. - let outer = loops - .iter() - .map(LoopSamples::area) - .enumerate() - .max_by(|a, b| a.1.abs().total_cmp(&b.1.abs())) - .map(|(i, _)| i) - .ok_or_else(|| KernelError::Invalid("the face has no boundary".into()))?; - Ok(FaceLoops { eval, dom, wires, loops, outer }) - } -} - -/// Sample a boundary loop (absolute: as it runs on the surface) in the surface's parameters. -pub(crate) fn sample_loop(s: &EvalSurface, dom: &Domain, wire: &mt::Wire, accept: f64) -> Result { - let mut edges = Vec::new(); - let mut prev: Option<[f64; 2]> = None; - for e in wire.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let mut samples = Vec::with_capacity(EDGE_SAMPLES + 1); - for k in 0..=EDGE_SAMPLES { - let t = t0 + (t1 - t0) * k as f64 / EDGE_SAMPLES as f64; - let p = from_p3(c.subs(t)); - let q = parameters(s, dom, p, prev, accept)?; - samples.push((t, p, q)); - prev = Some(q); - } - edges.push((c, samples)); - } - Ok(LoopSamples { edges }) -} - -/// The parameters of `p` on the surface, unwrapped to lie near `near` along periodic directions. -pub(crate) fn parameters(s: &EvalSurface, dom: &Domain, p: Vec3, near: Option<[f64; 2]>, accept: f64) -> Result<[f64; 2]> { - let mut q = uv::project(s, dom, p, near, accept).ok_or_else(|| KernelError::Failed("the face's boundary does not lie on its surface".into()))?; - if let Some(n) = near { - for d in 0..2 { - q[d] = uv::unwrap(q[d], n[d], dom.period[d]); - } - } - Ok(q) -} - -/// The parameter box the outer boundary is restored to: along each direction the surface's own -/// range where it has one of its own (a free-form surface's; not a periodic or unbounded -/// direction, and not an analytic surface's), else the face's own span. -pub(crate) fn natural_span(s: &EvalSurface, dom: &Domain, outer: &LoopSamples, analytic: bool, accept: f64) -> Result<[(f64, f64); 2]> { - let mut span = [(0.0, 0.0); 2]; - for (d, out) in span.iter_mut().enumerate() { - *out = match (dom.range.get(d).copied().flatten(), dom.period.get(d).copied().flatten()) { - (Some(range), None) if !analytic => range, - (_, period) => { - let lo = extreme(s, dom, outer, d, false, accept); - let hi = extreme(s, dom, outer, d, true, accept); - if let Some(p) = period - && hi - lo >= p * (1.0 - 1e-9) - { - return Err(KernelError::TooLarge("a face that goes all the way round its surface".into())); - } - (lo, hi) - } - }; - if !(out.1 - out.0 > 1e-12 * (1.0 + out.0.abs() + out.1.abs())) || !out.0.is_finite() || !out.1.is_finite() { - return Err(KernelError::Invalid("the face has no extent along its surface".into())); - } - } - Ok(span) -} - -/// The least (`max == false`) or greatest parameter along direction `d` the loop reaches: the -/// extreme sample, then placed on its edge between the neighbouring samples. Samples where the -/// surface does not move along `d` (a pole) say nothing about `d` and are passed over. -pub(crate) fn extreme(s: &EvalSurface, dom: &Domain, lp: &LoopSamples, d: usize, max: bool, accept: f64) -> f64 { - let sign = if max { 1.0 } else { -1.0 }; - let mut best: Option<(f64, usize, usize)> = None; - for (ei, (_, samples)) in lp.edges.iter().enumerate() { - for (k, (_, _, q)) in samples.iter().enumerate() { - if uv::degenerate(s, *q, d) { - continue; - } - let x = sign * q[d]; - if best.is_none_or(|(b, _, _)| x > b) { - best = Some((x, ei, k)); - } - } - } - let Some((x, ei, k)) = best else { return f64::NAN }; - let Some((curve, samples)) = lp.edges.get(ei) else { return sign * x }; - let (Some(at), Some(lo), Some(hi)) = (samples.get(k), samples.get(k.saturating_sub(1)), samples.get(k + 1).or(samples.get(k))) else { - return sign * x; - }; - // Golden-section search for the extreme between the neighbouring samples. - let value = |t: f64| -> Option { - let p = from_p3(curve.subs(t)); - let q = uv::project(s, dom, p, Some(at.2), accept)?; - Some(sign * uv::unwrap(q[d], at.2[d], dom.period[d])) - }; - let g = (5f64.sqrt() - 1.0) / 2.0; - let (mut a, mut b) = (lo.0, hi.0); - let mut best = x; - for _ in 0..EXTREME_STEPS { - let (c, e) = (b - g * (b - a), a + g * (b - a)); - let (Some(fc), Some(fe)) = (value(c), value(e)) else { break }; - best = best.max(fc).max(fe); - if fc > fe { - b = e; - } else { - a = c; - } - } - sign * best -} - -/// Whether the curve passes within `tol` of `p`. -pub(crate) fn passes(curve: &mt::Curve, p: mt::Point3, tol: f64) -> bool { - let (t0, t1) = curve.range_tuple(); - let start = (0..=64) - .map(|k| t0 + (t1 - t0) * k as f64 / 64.0) - .min_by(|a, b| curve.subs(*a).distance(p).total_cmp(&curve.subs(*b).distance(p))) - .unwrap_or(t0); - let t = curve.search_nearest_parameter(p, Some(start), 100).unwrap_or(start).clamp(t0.min(t1), t0.max(t1)); - curve.subs(t).distance(p) <= tol -} - -/// The parameter line of `surface` at `w` (v = w when `along_u`, else u = w) from parameter -/// `from` to `to` along it, exact: a line on a plane, a B-spline surface's iso-curve, and on a -/// revolved surface the profile turned to its angle or an arc about the axis. -pub(crate) fn iso_curve(surface: &mt::Surface, along_u: bool, w: f64, from: f64, to: f64) -> Result { - let at = |t: f64| if along_u { surface.subs(t, w) } else { surface.subs(w, t) }; - match surface { - mt::Surface::Plane(_) => Ok(mt::Curve::Line(mt::Line(at(from), at(to)))), - mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => { - let hom: mt::BSplineSurface = match surface { - mt::Surface::BSplineSurface(b) => mt::BSplineSurface::new( - b.knot_vecs().clone(), - b.control_points().iter().map(|row| row.iter().map(|p| p.to_homogeneous()).collect()).collect(), - ), - mt::Surface::NurbsSurface(n) => n.non_rationalized().clone(), - _ => return Err(KernelError::Failed("not a B-spline surface".into())), - }; - let iso = crate::step_in::split::iso_bsp(&hom, w, along_u).map_err(KernelError::Failed)?; - Ok(piece(mt::Curve::NurbsCurve(iso), from, to)) - } - mt::Surface::RevolutedCurve(proc) => { - let rev = proc.entity(); - // Truck's revolved surface is (profile parameter, angle), swapped when the processor - // is turned over; the processor's matrix places it. - let along_profile = along_u == proc.orientation(); - let transform = *proc.transform(); - let (origin, axis) = (rev.origin(), rev.axis().normalize()); - if along_profile { - let profile = rev.entity_curve(); - if let mt::Curve::Line(_) = profile { - return Ok(mt::Curve::Line(mt::Line(at(from), at(to)))); - } - if let mt::Curve::IntersectionCurve(_) = profile { - return Err(KernelError::TooLarge("untrimming a surface revolved from an intersection curve".into())); - } - let turn = mt::Matrix4::from_translation(origin - mt::Point3::new(0.0, 0.0, 0.0)) - * mt::Matrix4::from_axis_angle(axis, mt::Rad(w)) - * mt::Matrix4::from_translation(mt::Point3::new(0.0, 0.0, 0.0) - origin); - Ok(piece(profile.transformed(transform * turn), from, to)) - } else { - // The profile point at `w` turns about the axis: an arc from angle `from` to `to`. - let p = rev.entity_curve().subs(w); - let centre = origin + axis * (p - origin).dot(axis); - let r = (p - centre).magnitude(); - if !(r > 1e-12) { - return Err(KernelError::Failed("an arc on the axis of a revolved surface".into())); - } - let x = (p - centre) / r; - let frame = crate::step_in::geom::Frame { o: centre, x, y: axis.cross(x), z: axis }; - let arc = if to > from { - crate::step_in::geom::conic_arc(&frame, r, r, from, to - from) - } else { - crate::step_in::geom::conic_arc(&frame, r, r, to, from - to).inverse() - }; - Ok(mt::Curve::NurbsCurve(arc).transformed(transform)) - } - } - } -} - -/// The piece of `curve` between its parameters `from` and `to`, running from `from`. -pub(crate) fn piece(mut curve: mt::Curve, from: f64, to: f64) -> mt::Curve { - let (lo, hi) = if from < to { (from, to) } else { (to, from) }; - let (t0, t1) = curve.range_tuple(); - let eps = (t1 - t0).abs() * 1e-12; - if lo > t0 + eps { - curve = curve.cut(lo); - } - if hi < t1 - eps { - let _ = curve.cut(hi); - } - if from > to { - curve.invert(); - } - curve -} diff --git a/crates/kernel/src/face_source_tests.rs b/crates/kernel/src/face_source_tests.rs index 59a1dd834..eafdd4848 100644 --- a/crates/kernel/src/face_source_tests.rs +++ b/crates/kernel/src/face_source_tests.rs @@ -1,8 +1,9 @@ use crate::{FaceSource, extrude, transform_matrix}; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; fn assert_exact_planes(body: &crate::Body) { - let mesh = body.tessellate(0.001).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); for (index, _) in body.face_sources().unwrap().iter().enumerate() { let Some(plane) = body.face_plane(index) else { continue }; let mut count = 0; @@ -27,6 +28,12 @@ fn box_certificates_are_six_construction_roles_with_dimension_stable_axes() { (Vec3::new(2., 3., 4.), Vec3::new(12., 23., 34.)), (Vec3::new(12., 23., 34.), Vec3::new(2., 3., 4.)), (Vec3::new(2., -8., 4.), Vec3::new(22., 43., 54.)), + // A side far shorter than the body (a 0.3 mm label of a metre): its walls' edges lie + // closer together than the sweep's body-sized nearness, and each keeps its own role. + (Vec3::new(500., -0.3, 1400.), Vec3::new(1500., 0., 1800.)), + // Far thinner than the body's flatness tolerance (0.1 µm in 14 mm): each cap is in its + // own plane only. + (Vec3::ZERO, Vec3::new(10., 10., 1e-4)), ] { let body = crate::box_solid(a, b).unwrap().with_box_certificate(42).unwrap(); let mut roles = std::collections::HashSet::new(); @@ -81,7 +88,7 @@ fn cap_roles_follow_exact_offset_planes_and_canonical_profile_memberships() { assert_eq!(caps.len(), 2); assert_exact_planes(&body); let expected = (400. - 5. * std::f64::consts::PI) * (end - start).abs(); - assert!((body.tessellate(1e-4).unwrap().measure().volume - expected).abs() < 0.03); + assert!((body.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume - expected).abs() < 0.03); } } } @@ -94,7 +101,14 @@ fn construction_planes_follow_reflected_and_sheared_affine_images() { [[-1., 0., 0., 0.], [0.4, 2., 0., 0.], [0., 0.3, 1., 0.], [8., 9., 10., 1.]], ] { let placed = transform_matrix(&body, m).unwrap(); - for (original, transformed) in body.face_sources().unwrap().iter().zip(placed.face_sources().unwrap()) { + // SMLib numbers the placed faces afresh: each is matched with the face its history names. + let history = placed.history().unwrap(); + let originals = body.face_sources().unwrap(); + for (f, transformed) in placed.face_sources().unwrap().iter().enumerate() { + let [crate::history::FaceOrigin::Face { operand: 0, face }] = history.faces[f].origins.as_slice() else { + panic!("face {f} has no one origin") + }; + let original = &originals[*face]; let ( Some(FaceSource::Box { producer: a, axis: aa, high: ah, plane: ap }), Some(FaceSource::Box { producer: b, axis: ba, high: bh, plane: bp }), @@ -120,7 +134,7 @@ fn material_changes_preserve_only_unchanged_planar_support_certificates() { let base = crate::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap().with_box_certificate(42).unwrap(); let tool = crate::box_solid(Vec3::new(5., -1., -1.), Vec3::new(11., 11., 11.)).unwrap(); let cut = crate::boolean(&base, &tool, crate::BoolOp::Cut).unwrap().unwrap(); - assert!((cut.tessellate(1e-4).unwrap().measure().volume - 500.).abs() < 1e-8); + assert!((cut.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume - 500.).abs() < 1e-8); // Unchanged uniquely certified supports retain their role; a newly cut // support must never inherit the removed opposite wall's source identity. let mut retained = 0; @@ -236,7 +250,7 @@ fn constructed_annulus_sides_follow_exact_source_edges() { let body = &bodies[0]; let sources = body.face_sources().unwrap(); assert_eq!(sources.len(), body.face_count()); - let mesh = body.tessellate(0.001).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); let mut inner = 0; let mut outer = 0; for (index, source) in sources.iter().enumerate() { @@ -259,7 +273,7 @@ fn constructed_annulus_sides_follow_exact_source_edges() { } assert!(vertices > 0); } - assert_eq!((outer, inner), (2, 2), "full circles split into two actual edges each"); + assert_eq!((outer, inner), (1, 1), "each full circle sweeps one side face"); assert_eq!(sources.iter().filter(|source| matches!(source, Some(FaceSource::ExtrudeCap { .. }))).count(), 2); } } @@ -298,10 +312,10 @@ fn constructed_large_arc_split_and_reversal_preserve_one_source_segment() { _ => None, }) .collect(); - assert_eq!(arcs.len(), 2, "large input arc explicitly creates two actual boundary edges"); + assert_eq!(arcs.len(), 1, "the large input arc sweeps one side face"); assert!(arcs.iter().all(|(radius, sweep)| (**radius - 10.).abs() < 1e-12 && (sweep.abs() - std::f64::consts::PI * 5. / 3.).abs() < 1e-12)); assert_eq!(sources.iter().filter(|source| matches!(source, Some(FaceSource::ExtrudeSide { segment: Seg2::Line { .. }, .. }))).count(), 1); - let mesh = body.tessellate(0.001).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); for (triangle, face) in mesh.triangles.iter().zip(&mesh.tri_face) { if matches!(sources[*face as usize], Some(FaceSource::ExtrudeSide { segment: Seg2::Arc { .. }, .. })) { assert!(mesh.tri(triangle).unwrap().iter().all(|point| (point.x.hypot(point.y) - 10.).abs() < 1e-7)); diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rs index 95bbfa533..d584e69b1 100644 --- a/crates/kernel/src/fair.rs +++ b/crates/kernel/src/fair.rs @@ -43,20 +43,28 @@ //! control point that does not change the geometry at all — is reported as an error and the //! geometry is left alone. +use solidcore_record::Vec3; +use solidcore_record::brep as b; +use solidcraft_geom::Grid; use solidcraft_geom::bspline::{HPoint, MAX_SPLINE_DEGREE, NurbsSurface, Side, SplineError, check_knots, local_basis}; -use solidcraft_geom::{Grid, Vec3}; -use truck_modeling as mt; use crate::body::Body; use crate::history::Change; -use crate::{KernelError, Result, guard}; +use crate::{KernelError, Result}; /// Most steps one fairing run takes (see [`FairOptions::iterations`]). pub const MAX_FAIR_ITERATIONS: usize = 1000; -/// Most control points one fairing run accepts (a 64 × 64 net): plenty for any face's control -/// net, and small enough that a step stays cheap whatever a design file contains. -pub const MAX_FAIR_POINTS: usize = 4096; -/// Most entries of the banded system (2²¹ doubles, 16 MB). +/// Most control points one fairing run accepts (a 128 × 128 net). `MAX_FAIR_BAND` is what +/// bounds the solver's memory and its factorisation; this bounds the rest of a step, the energy +/// sweep over every control point (`(2p_u + 1)(2p_v + 1)` neighbours each, three terms) and the +/// copies of the net: for a bicubic net a few million multiply-adds and under a megabyte. It is +/// set above the band's own limit for square bicubic nets (about 90 × 90), so a face's net is +/// refused for the system it needs rather than for its size: SMLib's thickenings make faces of +/// 72 × 78 control points, which the band takes at about 1.1 M entries. +pub const MAX_FAIR_POINTS: usize = 1 << 14; +/// Most entries of the banded system (2²¹ doubles, 16 MB). The factorisation's work is at most +/// `n · min(n, bw)²` for `n` unknowns `bw` apart with `n · (bw + 1)` within this, a few 10⁹ +/// multiply-adds at the very worst (`n ≈ bw ≈ 1450`), and each solve's at most twice the band. const MAX_FAIR_BAND: usize = 1 << 21; /// The fairness energy of a curve, as a one-direction net: the `(order in u, order in v, weight)` /// term list of `∫∫ (∂S)²`. @@ -278,13 +286,20 @@ struct Net<'a, const N: usize> { /// The control points as the design has them; the run moves copies. ctrl: &'a Grid<[f64; N]>, gram: [Gram; 2], - terms: &'static [(usize, usize, f64)], + /// The energy's terms that the net's degrees can carry (see [`Net::new`]). + terms: Vec<(usize, usize, f64)>, } impl<'a, const N: usize> Net<'a, N> { /// Check the degrees, knots and counts and build the Gram matrices: an error, never a panic, /// for a degree above [`MAX_SPLINE_DEGREE`], too few control points for the degree, a knot /// vector of the wrong length, unusable knots or an empty parameter range. + /// + /// A term that differentiates a direction more often than its degree is dropped: on every + /// span the basis functions are polynomials of that degree, so the derivative is zero and so + /// is the term, exactly. A face of degree 1 one way (an extruded curve) has no `S_vv` that + /// way: its energy is the bending along the curve and the twist, and the straight direction + /// pays nothing. fn new(degree: [usize; 2], knots: [Vec; 2], ctrl: &'a Grid<[f64; N]>, terms: &'static [(usize, usize, f64)]) -> Result> { let count = ctrl.count(); if ctrl.cells().len() > MAX_FAIR_POINTS { @@ -311,8 +326,12 @@ impl<'a, const N: usize> Net<'a, N> { return Err(KernelError::Invalid("the fairing's parameter range is empty".into())); } } - if terms.iter().any(|&(ru, rv, w)| ru > degree[0] || rv > degree[1] || !(w.is_finite() && w >= 0.0)) { - return Err(KernelError::Invalid("a fairness term does not fit the net's degrees".into())); + if terms.iter().any(|&(_, _, w)| !(w.is_finite() && w >= 0.0)) { + return Err(KernelError::Invalid("a fairness term's weight is not a non-negative number".into())); + } + let terms: Vec<(usize, usize, f64)> = terms.iter().copied().filter(|&(ru, rv, _)| ru <= degree[0] && rv <= degree[1]).collect(); + if terms.is_empty() { + return Err(KernelError::Invalid(format!("a net of degree {} × {} does not bend: there is nothing to fair", degree[0], degree[1]))); } let gram = [Gram::new(degree[0], &knots[0], count[0])?, Gram::new(degree[1], &knots[1], count[1])?]; Ok(Net { degree, ctrl, gram, terms }) @@ -342,7 +361,7 @@ impl<'a, const N: usize> Net<'a, N> { for j in 0..cv { for i in 0..cu { let mut acc = [0.0f64; N]; - for &(ru, rv, w) in self.terms { + for &(ru, rv, w) in &self.terms { for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) { for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) { let a = w * self.gram[0].at(ru, i, k) * self.gram[1].at(rv, j, l); @@ -380,7 +399,7 @@ impl<'a, const N: usize> Net<'a, N> { let mut band = Band::new(interior.points.len(), pu + rows * interior.cols)?; for (r, &at) in interior.points.iter().enumerate() { let (i, j) = (at % cu, at / cu); - for &(ru, rv, w) in self.terms { + for &(ru, rv, w) in &self.terms { for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) { for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) { let Some(s) = interior.slot.get(self.index(k, l)).copied().flatten() else { continue }; @@ -392,6 +411,23 @@ impl<'a, const N: usize> Net<'a, N> { band.factorised() } + /// Whether holding `keep` layers at each end of each direction holds every control point: a + /// direction of more than one control point and no more than `2 · keep` of them. + fn all_held(&self, keep: usize) -> bool { + self.count().iter().any(|&c| c > 1 && c <= 2 * keep) + } + + /// The report of a run that moved nothing: the net's energy before and after, no steps. + fn unmoved(&self) -> Result { + let mut grad = vec![[0.0; N]; self.total()]; + let energy = self.energy_gradient(self.ctrl.cells(), &mut grad); + if !energy.is_finite() { + return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into())); + } + let energy = energy.max(0.0); + Ok(FairReport { energy_before: energy, energy_after: energy, steps: 0, movement: 0.0, energy_trace: Vec::new() }) + } + /// Fair the net with checked `opts`: see the module docs. The result is the input with the /// interior control points moved; the held ones are bit-identical. fn fair(&self, opts: &FairOptions) -> Result<(Grid<[f64; N]>, FairReport)> { @@ -720,60 +756,62 @@ pub fn fair_net(degree: [usize; 2], knots: [&[f64]; 2], ctrl: &G Ok(FairNet { degree, knots: [knots[0].to_vec(), knots[1].to_vec()], ctrl: faired, report }) } -/// Fair a truck B-spline curve's control points: [`fair_curve`] on its three-dimensional points, -/// rebuilt as a B-spline of the same knots. Guarded here itself, like every call into truck, so a -/// panic inside comes back as an error and the design is left alone. -pub fn fair_bspline_curve(curve: &mt::BSplineCurve, opts: &FairOptions) -> Result<(mt::BSplineCurve, FairReport)> { - guard("fair a B-spline curve", || { - let ctrl: Vec<[f64; 3]> = curve.control_points().iter().map(|p| [p.x, p.y, p.z]).collect(); - let faired = fair_curve(curve.degree(), curve.knot_vec(), &ctrl, opts)?; - let points: Vec = faired.ctrl.iter().map(|c| mt::Point3::new(c[0], c[1], c[2])).collect(); - let curve = mt::BSplineCurve::try_new(mt::KnotVec::from(faired.knots), points).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; - Ok((curve, faired.report)) - }) +/// The degree of a spline record of `count` control points on `knots`. +fn degree_of(knots: &[f64], count: usize) -> Result { + knots.len().checked_sub(count + 1).ok_or_else(|| KernelError::Invalid(format!("{} knots are too few for {count} control points", knots.len()))) } -/// Fair a truck rational curve's control points: its Cartesian control points are faired like any -/// other curve and its weights are kept, so the result is the same rational curve with moved -/// control points. The convex-hull bound that keeps the geometry within the tolerance still -/// holds, because with the weights unchanged the rational basis functions are non-negative and -/// sum to one. Guarded like [`fair_bspline_curve`]. -pub fn fair_nurbs_curve(curve: &mt::NurbsCurve, opts: &FairOptions) -> Result<(mt::NurbsCurve, FairReport)> { - guard("fair a NURBS curve", || { - let count = curve.control_points().len(); - let mut ctrl = Vec::with_capacity(count); - let mut weights = Vec::with_capacity(count); - for h in curve.control_points() { - let Some(p) = (HPoint { x: h.x, y: h.y, z: h.z, w: h.w }).project() else { - return Err(KernelError::Invalid("a control point has no position: its weight is zero".into())); - }; - ctrl.push([p.x, p.y, p.z]); - weights.push(h.w); - } - let faired = fair_curve(curve.degree(), curve.knot_vec(), &ctrl, opts)?; - let points: Vec = faired.ctrl.iter().zip(&weights).map(|(c, w)| mt::Vector4::new(c[0] * w, c[1] * w, c[2] * w, *w)).collect(); - let bsp = mt::BSplineCurve::try_new(mt::KnotVec::from(faired.knots), points).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; - Ok((mt::NurbsCurve::new(bsp), faired.report)) - }) +/// Fair a B-spline curve record's control points (a `Curve::Spline`): [`fair_curve`] on its +/// points, the same knots. +pub fn fair_bspline_curve(curve: &b::Curve, opts: &FairOptions) -> Result<(b::Curve, FairReport)> { + let b::Curve::Spline { knots, points } = curve else { return Err(KernelError::Invalid("not a B-spline curve".into())) }; + let faired = fair_curve(degree_of(knots, points.len())?, knots, points, opts)?; + Ok((b::Curve::Spline { knots: faired.knots, points: faired.ctrl }, faired.report)) } -/// Fair a truck B-spline surface's control net: [`fair_net`] on its points, rebuilt as a B-spline -/// of the same knots, with the boundary rows held. Guarded like [`fair_bspline_curve`]. -pub fn fair_bspline_surface(surface: &mt::BSplineSurface, opts: &FairOptions) -> Result<(mt::BSplineSurface, FairReport)> { - guard("fair a B-spline surface", || { - let net = truck_net(surface.control_points())?; - let (ku, kv) = surface.knot_vecs(); - let (pu, pv) = surface.degrees(); - let faired = fair_net([pu, pv], [ku, kv], &net.map(|p| [p.x, p.y, p.z]), opts)?; - let net = faired.ctrl.map(|[x, y, z]| mt::Point3::new(x, y, z)).into_u_rows(); - let surface = mt::BSplineSurface::try_new((ku.clone(), kv.clone()), net).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; - Ok((surface, faired.report)) - }) +/// Fair a rational curve record's control points (a `Curve::RationalSpline`): its Cartesian +/// control points are faired like any other curve and its weights are kept, so the result is the +/// same rational curve with moved control points. The convex-hull bound that keeps the geometry +/// within the tolerance still holds, because with the weights unchanged the rational basis +/// functions are non-negative and sum to one. +pub fn fair_nurbs_curve(curve: &b::Curve, opts: &FairOptions) -> Result<(b::Curve, FairReport)> { + let b::Curve::RationalSpline { knots, homogeneous } = curve else { return Err(KernelError::Invalid("not a rational B-spline curve".into())) }; + let hpoints: Vec = homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(); + let ctrl = positions(&Grid::row(hpoints.clone()))?; + let faired = fair_curve(degree_of(knots, homogeneous.len())?, knots, ctrl.cells(), opts)?; + let net = reweighted(Grid::row(hpoints), &Grid::row(faired.ctrl)); + let homogeneous = net.into_cells().into_iter().map(|h| [h.x, h.y, h.z, h.w]).collect(); + Ok((b::Curve::RationalSpline { knots: faired.knots, homogeneous }, faired.report)) } -/// A truck surface's control net (`rows[i][j]`, i along u) as a grid: refused when it is empty +/// Fair a B-spline surface record's control net (a `Surface::Spline`): [`fair_net`] on its +/// points, the same knots, the boundary rows held. +pub fn fair_bspline_surface(surface: &b::Surface, opts: &FairOptions) -> Result<(b::Surface, FairReport)> { + let b::Surface::Spline { u_knots, v_knots, points } = surface else { return Err(KernelError::Invalid("not a B-spline surface".into())) }; + let net = record_net(points)?; + let [cu, cv] = net.count(); + let degree = [degree_of(u_knots, cu)?, degree_of(v_knots, cv)?]; + let faired = fair_net(degree, [u_knots, v_knots], &net, opts)?; + Ok((b::Surface::Spline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), points: faired.ctrl.into_u_rows() }, faired.report)) +} + +/// Fair a rational surface record's control net (a `Surface::RationalSpline`), like +/// [`fair_surface`]: the Cartesian control points are faired, the weights kept. +pub fn fair_nurbs_surface(surface: &b::Surface, opts: &FairOptions) -> Result<(b::Surface, FairReport)> { + let b::Surface::RationalSpline { u_knots, v_knots, homogeneous } = surface else { + return Err(KernelError::Invalid("not a rational B-spline surface".into())); + }; + let net = record_net(homogeneous)?.map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }); + let [cu, cv] = net.count(); + let degree = [degree_of(u_knots, cu)?, degree_of(v_knots, cv)?]; + let faired = fair_net(degree, [u_knots, v_knots], &positions(&net)?, opts)?; + let homogeneous = reweighted(net, &faired.ctrl).map(|h| [h.x, h.y, h.z, h.w]).into_u_rows(); + Ok((b::Surface::RationalSpline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), homogeneous }, faired.report)) +} + +/// A surface record's control net (`rows[i][j]`, i along u) as a grid: refused when it is empty /// or not rectangular. -fn truck_net(rows: &[Vec

]) -> Result> { +fn record_net(rows: &[Vec

]) -> Result> { let net = Grid::from_u_rows(rows).ok_or_else(|| KernelError::Invalid("the surface's control net is not rectangular".into()))?; if net.is_empty() { return Err(KernelError::Invalid("the surface has no control points".into())); @@ -813,30 +851,17 @@ pub fn fair_surface(surface: &NurbsSurface, opts: &FairOptions) -> Result<(Nurbs Ok((out, faired.report)) } -/// Fair a truck rational surface's control net, like [`fair_surface`]: the Cartesian control -/// points are faired, the weights kept, and the result is a NURBS surface of the same knots. -/// Guarded like [`fair_bspline_curve`]. -pub fn fair_nurbs_surface(surface: &mt::NurbsSurface, opts: &FairOptions) -> Result<(mt::NurbsSurface, FairReport)> { - guard("fair a NURBS surface", || { - let bsp = surface.non_rationalized(); - let net = truck_net(bsp.control_points())?.map(|h| HPoint { x: h.x, y: h.y, z: h.z, w: h.w }); - let (ku, kv) = bsp.knot_vecs(); - let (pu, pv) = bsp.degrees(); - let faired = fair_net([pu, pv], [ku, kv], &positions(&net)?, opts)?; - let net = reweighted(net, &faired.ctrl).map(|h| mt::Vector4::new(h.x, h.y, h.z, h.w)).into_u_rows(); - let bsp = mt::BSplineSurface::try_new((ku.clone(), kv.clone()), net).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; - Ok((mt::NurbsSurface::new(bsp), faired.report)) - }) -} - /// Fair the B-spline faces at `faces` (indices in `body`'s face order) of `body`: each face's /// interior control vertices move to flatten the thin-plate energy of the face while its boundary /// rows stay put, so the face keeps meeting its neighbours as it did. /// -/// Every picked face keeps the very wires, edges and vertices it had and the way it pointed: only -/// the surface between them changes, so the body is as closed (or as open) as it was, holes and -/// all. A face that is not a B-spline (a plane, cylinder, cone, sphere, torus or swept face) has no -/// control points to fair and is refused by name; a mesh body has no faces to fair at all. +/// Every picked face keeps the very loops, edges and vertices it had and the way it pointed: only +/// its surface changes in the body's record, so the body is as closed (or as open) as it was, +/// holes and all, and SMLib builds it from that record. A face that is not a B-spline (a plane, +/// cylinder, cone, sphere, torus or revolution) has no control points to fair and is refused by +/// name; a mesh body has no faces to fair at all. A face whose held layers are its whole net (see +/// [`held_face`]) has no interior control vertex to move and is left exactly as it is, its energy +/// reported unchanged. /// /// The report is over the picked faces together: the energies summed, the largest movement of any /// control point, and the energy trace as the sum at each step (a face that stops early keeps its @@ -844,14 +869,15 @@ pub fn fair_nurbs_surface(surface: &mt::NurbsSurface, opts: &FairOp pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(Body, FairReport)> { let opts = opts.checked()?; body.require_brep("fair")?; - let all: Vec = body.solid.face_iter().cloned().collect(); - if all.is_empty() { + let mut record = crate::native::brep_record(body)?; + let count = record.faces.len(); + if count == 0 { return Err(KernelError::Invalid("the body has no faces".into())); } let mut picked: Vec = Vec::new(); for &i in faces { - if i >= all.len() { - return Err(KernelError::Invalid(format!("no face {i}: the body has {}", all.len()))); + if i >= count { + return Err(KernelError::Invalid(format!("no face {i}: the body has {count}"))); } if !picked.contains(&i) { picked.push(i); @@ -860,78 +886,84 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B if picked.is_empty() { return Err(KernelError::Invalid("pick the faces to fair".into())); } - guard("fair faces", || { - let mut faired = all.clone(); - let mut reports: Vec = Vec::with_capacity(picked.len()); - for &i in &picked { - let Some(face) = all.get(i) else { continue }; - let (surface, report) = match face.surface() { - mt::Surface::BSplineSurface(s) => { - let (faired, report) = fair_bspline_surface(&s, &opts)?; - (mt::Surface::BSplineSurface(faired), report) - } - mt::Surface::NurbsSurface(s) => { - let (faired, report) = fair_nurbs_surface(&s, &opts)?; - (mt::Surface::NurbsSurface(faired), report) - } - _ => { - return Err(KernelError::Invalid(format!( - "face {i} is not a B-spline face: a plane, cylinder, cone, sphere, torus or swept face has no control points to fair" - ))); - } - }; - // The same face as before, wires and all, with the faired surface between them. - let mut nf = mt::Face::new_unchecked(face.absolute_boundaries().clone(), surface); - if !face.orientation() { - nf.invert(); - } - if let Some(slot) = faired.get_mut(i) { - *slot = nf; - } + let mut reports: Vec = Vec::with_capacity(picked.len()); + let mut changed: Vec = Vec::with_capacity(picked.len()); + for &i in &picked { + let Some(face) = record.faces.get_mut(i) else { continue }; + if let Some(report) = held_face(&face.surface, &opts)? { reports.push(report); + continue; } - let report = FairReport { - energy_before: reports.iter().map(|r| r.energy_before).sum(), - energy_after: reports.iter().map(|r| r.energy_after).sum(), - steps: reports.iter().map(|r| r.steps).max().unwrap_or(0), - movement: reports.iter().fold(0.0f64, |m, r| m.max(r.movement)), - energy_trace: { - let longest = reports.iter().map(|r| r.energy_trace.len()).max().unwrap_or(0); - (0..longest).map(|k| reports.iter().map(|r| r.energy_trace.get(k).copied().unwrap_or(r.energy_after)).sum()).collect() - }, - }; - // The body shell for shell, in its own face order: a body with holes keeps them. - let mut shells: Vec = Vec::with_capacity(body.solid.boundaries().len()); - let mut index = 0usize; - for shell in body.solid.boundaries() { - let mut shell_faces = Vec::with_capacity(shell.face_iter().count()); - for f in shell.face_iter() { - let i = index; - index += 1; - shell_faces.push(faired.get(i).cloned().unwrap_or_else(|| f.clone())); + let (surface, report) = match &face.surface { + b::Surface::Spline { .. } => fair_bspline_surface(&face.surface, &opts)?, + b::Surface::RationalSpline { .. } => fair_nurbs_surface(&face.surface, &opts)?, + _ => { + return Err(KernelError::Invalid(format!( + "face {i} is not a B-spline face: a plane, cylinder, cone, sphere, torus or revolution has no control points to fair" + ))); } - shells.push(mt::Shell::from(shell_faces)); + }; + face.surface = surface; + reports.push(report); + changed.push(i); + } + let report = FairReport { + energy_before: reports.iter().map(|r| r.energy_before).sum(), + energy_after: reports.iter().map(|r| r.energy_after).sum(), + steps: reports.iter().map(|r| r.steps).max().unwrap_or(0), + movement: reports.iter().fold(0.0f64, |m, r| m.max(r.movement)), + energy_trace: { + let longest = reports.iter().map(|r| r.energy_trace.len()).max().unwrap_or(0); + (0..longest).map(|k| reports.iter().map(|r| r.energy_trace.get(k).copied().unwrap_or(r.energy_after)).sum()).collect() + }, + }; + if changed.is_empty() { + return Ok((body.clone(), report)); + } + let smlib = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| KernelError::smlib("fair: SMLib", e))?; + let (result, order) = crate::native::body_from_smlib_ordered(&smlib)?; + // The topology is the body's own, so SMLib's order is the body's: each face kept or + // modified, each edge kept. Where SMLib's order is not the record's the history is not known. + let kept = order.is_some_and(|o| o.faces.iter().enumerate().all(|(i, f)| i == *f) && o.edges.iter().enumerate().all(|(i, e)| i == *e)); + if !kept || result.face_count() != body.face_count() || result.edge_count() != body.edge_count() { + return Ok((result, report)); + } + let mut history = ::identity(body); + for &i in &changed { + if let Some(f) = history.faces.get_mut(i) { + f.change = Change::Modified; } - // The topology is the body's own, face for face, so the solid is built as it (the shells - // are as closed, or as open, as they were) and only the shape is measured anew. - let mut result = body.clone(); - result.solid = std::sync::Arc::new(mt::Solid::new_unchecked(shells)); - result.size = 0.0; - result.volume = Some(std::sync::Arc::new(std::sync::Mutex::new(None))); - result.coarse_missing = None; - result.history = None; - result.phased = false; - let faces: Vec = - (0..all.len()).map(|i| crate::record::from_face(0, i, if picked.contains(&i) { Change::Modified } else { Change::Kept })).collect(); - let result = crate::record::attach(result, &[crate::record::Operand::new(body)], Some(faces), std::collections::HashMap::new())?; - Ok((result, report)) - }) + } + Ok((result.with_history(history, &[body])?, report)) +} + +/// The report for a B-spline face whose every control point `opts` holds, which the run leaves +/// exactly as it is: a direction of no more control points than the held layers (a single-span +/// cubic with its edges kept, an extruded curve's two rows) holds the whole net, since every row +/// is a boundary row or one next to it. `None` when some control point is free to move, and for a +/// face that is not a B-spline. +fn held_face(surface: &b::Surface, opts: &FairOptions) -> Result> { + let (u_knots, v_knots, ctrl) = match surface { + b::Surface::Spline { u_knots, v_knots, points } => (u_knots, v_knots, record_net(points)?), + b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + (u_knots, v_knots, positions(&record_net(homogeneous)?.map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }))?) + } + _ => return Ok(None), + }; + let [cu, cv] = ctrl.count(); + let degree = [degree_of(u_knots, cu)?, degree_of(v_knots, cv)?]; + let net = Net::new(degree, [u_knots.clone(), v_knots.clone()], &ctrl, &SURFACE_ENERGY)?; + if !net.all_held(if opts.keep_edges { 2 } else { 1 }) { + return Ok(None); + } + net.unmoved().map(Some) } #[cfg(test)] mod tests { use super::*; - use mt::ParametricCurve; + use solidcraft_geom::brep::eval::CurveEval; + use solidcraft_geom::prelude::*; /// A clamped uniform knot vector over `[0, spans]` of degree `degree`: `spans + degree` /// control points. @@ -984,8 +1016,8 @@ mod tests { } /// The greatest distance between two points of space, in mm. - fn apart(a: mt::Point3, b: mt::Point3) -> f64 { - ((a.x - b.x).powi(2) + (a.y - b.y).powi(2) + (a.z - b.z).powi(2)).sqrt() + fn apart(a: Vec3, b: Vec3) -> f64 { + a.dist(b) } /// A geom point as a coordinate triple. @@ -1218,28 +1250,29 @@ mod tests { } #[test] - fn the_truck_wrappers_fair_a_spline_curve_and_surface_with_their_ends_held() { + fn the_record_wrappers_fair_a_spline_curve_and_surface_with_their_ends_held() { let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 9.0, 9.0, 9.0, 9.0]; let smooth = affine_curve(&knots, 3, [-20.0, 5.0, 1.5], [4.0, -2.5, 3.0]); let mut rough = smooth.clone(); rough[2][2] += 3.0; rough[4][1] -= 2.0; - let points = |net: &[[f64; 3]]| -> Vec { net.iter().map(|c| mt::Point3::new(c[0], c[1], c[2])).collect() }; - let curve = mt::BSplineCurve::try_new(mt::KnotVec::from(knots.to_vec()), points(&rough)).unwrap(); + let curve = b::Curve::Spline { knots: knots.to_vec(), points: rough.clone() }; let tolerance = 5.0; let opts = FairOptions::new(1.0, 8, false, tolerance).unwrap(); let (faired, report) = fair_bspline_curve(&curve, &opts).unwrap(); + let (fe, ce) = (CurveEval::new(&faired).unwrap(), CurveEval::new(&curve).unwrap()); let mut off = 0.0f64; for k in 0..=64 { let t = 9.0 * f64::from(k) / 64.0; - off = off.max(apart(faired.subs(t), curve.subs(t))); + off = off.max(apart(fe.point(t).unwrap(), ce.point(t).unwrap())); } eprintln!( - "truck curve: energy {:e} → {:e} in {} steps, moved {off:e} mm ({:e} mm of control points)", + "record curve: energy {:e} → {:e} in {} steps, moved {off:e} mm ({:e} mm of control points)", report.energy_before, report.energy_after, report.steps, report.movement ); - assert_eq!(faired.control_points().first().copied(), curve.control_points().first().copied()); - assert_eq!(faired.control_points().last().copied(), curve.control_points().last().copied()); + let b::Curve::Spline { points: moved, .. } = &faired else { panic!("a B-spline curve") }; + assert_eq!(moved.first(), rough.first()); + assert_eq!(moved.last(), rough.last()); assert!(off <= tolerance * (1.0 + 1e-9), "{off:e}"); assert!(report.energy_after < 1e-9 * report.energy_before); @@ -1251,25 +1284,25 @@ mod tests { let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]); let mut rough = smooth.clone(); rough[2 * cu + 2][2] += 5.0; - let rows: Vec> = - (0..cu).map(|i| (0..cv).map(|j| mt::Point3::new(rough[j * cu + i][0], rough[j * cu + i][1], rough[j * cu + i][2])).collect()).collect(); - let surface = mt::BSplineSurface::try_new((mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone())), rows).unwrap(); + let rows: Vec> = (0..cu).map(|i| (0..cv).map(|j| rough[j * cu + i]).collect()).collect(); + let surface = b::Surface::Spline { u_knots: ku.clone(), v_knots: kv.clone(), points: rows.clone() }; let (faired, report) = fair_bspline_surface(&surface, &FairOptions::new(1.0, 6, true, 8.0).unwrap()).unwrap(); - eprintln!("truck surface: energy {:e} → {:e}, {} steps", report.energy_before, report.energy_after, report.steps); + let b::Surface::Spline { points: moved, .. } = &faired else { panic!("a B-spline surface") }; + eprintln!("record surface: energy {:e} → {:e}, {} steps", report.energy_before, report.energy_after, report.steps); for i in 0..cu { for j in 0..cv { if i < 2 || i + 2 >= cu || j < 2 || j + 2 >= cv { - assert_eq!(faired.control_points()[i][j], surface.control_points()[i][j], "({i}, {j}) is a boundary layer and moved"); + assert_eq!(moved[i][j], rows[i][j], "({i}, {j}) is a boundary layer and moved"); } } } assert!(report.energy_after < report.energy_before); - assert!(faired.control_points()[2][2].z < surface.control_points()[2][2].z, "the bump should come down"); + assert!(moved[2][2][2] < rows[2][2][2], "the bump should come down"); } #[test] fn a_rational_surface_fairs_with_its_boundary_and_tolerance_intact() { - // The truck NURBS wrapper, on weights away from one: fairing moves the Cartesian control + // The rational record wrapper, on weights away from one: fairing moves the Cartesian control // points and keeps the weights, so the surface still cannot move more than the tolerance. let (ku, kv) = (clamped(3, 3), clamped(3, 3)); let degree = [3, 3]; @@ -1278,25 +1311,25 @@ mod tests { let mut rough = smooth.clone(); rough[2 * cu + 3][2] += 6.0; let weights: Vec = (0..cu * cv).map(|k| 0.75 + (k % 3) as f64 * 0.5).collect(); - let rows: Vec> = (0..cu) + let rows: Vec> = (0..cu) .map(|i| { (0..cv) .map(|j| { let (c, w) = (rough[j * cu + i], weights[j * cu + i]); - mt::Vector4::new(c[0] * w, c[1] * w, c[2] * w, w) + [c[0] * w, c[1] * w, c[2] * w, w] }) .collect() }) .collect(); - let bsp = mt::BSplineSurface::try_new((mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone())), rows).unwrap(); - let surface = mt::NurbsSurface::new(bsp); + let surface = b::Surface::RationalSpline { u_knots: ku.clone(), v_knots: kv.clone(), homogeneous: rows.clone() }; let (faired, report) = fair_nurbs_surface(&surface, &FairOptions::new(1.0, 6, false, 0.5).unwrap()).unwrap(); eprintln!("rational surface: energy {:e} → {:e}, movement {:e} mm", report.energy_before, report.energy_after, report.movement); assert!(report.movement <= 0.5 && report.energy_after < report.energy_before); + let b::Surface::RationalSpline { homogeneous: moved, .. } = &faired else { panic!("a rational surface") }; for i in 0..cu { for j in 0..cv { - let (before, after) = (surface.non_rationalized().control_points()[i][j], faired.non_rationalized().control_points()[i][j]); - assert_eq!(after.w, before.w, "the weight of ({i}, {j}) changed"); + let (before, after) = (rows[i][j], moved[i][j]); + assert_eq!(after[3], before[3], "the weight of ({i}, {j}) changed"); if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv { assert_eq!(after, before, "({i}, {j}) is on the boundary and moved"); } @@ -1344,7 +1377,8 @@ mod tests { ); // A net too large to fair, refused before anything is allocated for it. let line = [0.0, 0.0, 1.0, 1.0]; - assert!(fair_net([1, 1], [&line, &line], &Grid::from_fn([65, 65], |_, _| [0.0; 3]).unwrap(), &ok).is_err(), "4225 control points"); + let huge = fair_net([1, 1], [&line, &line], &Grid::from_fn([129, 129], |_, _| [0.0; 3]).unwrap(), &ok).unwrap_err(); + assert!(matches!(huge, KernelError::TooLarge(_)), "16641 control points: {huge}"); // A singular system: a cubic whose last control points lie past the end of its domain // (0.5), where they do not move the curve at all, so the interior equations have no // unique solution and the run must refuse rather than move anything. @@ -1401,23 +1435,95 @@ mod tests { assert_eq!(faired.ctrl[rough.len() - 1], rough[rough.len() - 1]); } + #[test] + fn a_net_of_degree_one_across_fairs_along_its_curved_direction_only() { + // Cubic along u, linear across v over two spans (three rows): `S_vv` is zero on every + // span, so only the bending along u and the twist count. A plane's net bumped at its + // middle row fairs back to the plane, the boundary rows bit-identical. + let (ku, kv) = (clamped(3, 3), vec![0.0, 0.0, 1.0, 2.0, 2.0]); + let degree = [3, 1]; + let (cu, cv) = (ku.len() - 4, kv.len() - 2); + assert_eq!((cu, cv), (6, 3)); + let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [30.0, 0.0, 0.0], [0.0, 20.0, 4.0]); + let mut rough = smooth.clone(); + rough[cu + 2][2] += 2.0; + rough[cu + 3][2] -= 1.0; + let faired = fair_net( + degree, + [&ku, &kv], + &Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(), + &FairOptions::new(1.0, 8, false, 100.0).unwrap(), + ) + .unwrap(); + let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max); + eprintln!("degree 3 × 1 net: faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after); + assert!(near < 1e-6 && faired.report.energy_after < 1e-9 * faired.report.energy_before); + for i in 0..cu { + for j in [0, cv - 1] { + assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "({i}, {j}) is on the boundary and moved"); + } + } + } + + #[test] + fn a_face_whose_edges_hold_its_whole_net_is_left_as_it_is() { + // A single-span bicubic with its edges kept: every row is a boundary row or the one next + // to it, so there is nothing to move. The run succeeds, the body is the one it was and + // the report says no step was taken. + let (ku, kv) = (clamped(1, 3), clamped(1, 3)); + let mut net = planar_net(&ku, &kv, [3, 3], [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]); + net[5][2] += 2.0; + let body = sheet(&ku, &kv, &net); + let (faired, report) = fair_faces(&body, &[0], &FairOptions::new(1.0, 10, true, 1.0).unwrap()).unwrap(); + eprintln!("held face: energy {:e} → {:e}, {} steps", report.energy_before, report.energy_after, report.steps); + assert_eq!(face_surface(&faired, 0), face_surface(&body, 0)); + assert_eq!(edge_records(&faired), edge_records(&body)); + assert_eq!((report.steps, report.movement), (0, 0.0)); + assert!(report.energy_before > 0.0 && report.energy_after == report.energy_before); + } + /// A one-face sheet body of the bicubic surface `net` (u fastest) over the clamped knots `ku` /// and `kv`, its sides the straight lines between the surface's corners — true while the /// net's boundary rows describe lines, which is how a plane's control net is built here. fn sheet(ku: &[f64], kv: &[f64], net: &[[f64; 3]]) -> Body { + use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble}; let (cu, cv) = (ku.len() - 4, kv.len() - 4); assert_eq!(net.len(), cu * cv, "the net does not fit the knots"); - let rows: Vec> = - (0..cu).map(|i| (0..cv).map(|j| mt::Point3::new(net[j * cu + i][0], net[j * cu + i][1], net[j * cu + i][2])).collect()).collect(); - let bsp = mt::BSplineSurface::try_new((mt::KnotVec::from(ku.to_vec()), mt::KnotVec::from(kv.to_vec())), rows).unwrap(); - let corner = |i: usize, j: usize| { - let c = net[j * cu + i]; - mt::Vertex::new(mt::Point3::new(c[0], c[1], c[2])) - }; - let v = [corner(0, 0), corner(cu - 1, 0), corner(cu - 1, cv - 1), corner(0, cv - 1)]; - let line = |a: &mt::Vertex, b: &mt::Vertex| mt::Edge::new(a, b, mt::Curve::Line(mt::Line(a.point(), b.point()))); - let wire: mt::Wire = vec![line(&v[0], &v[1]), line(&v[1], &v[2]), line(&v[2], &v[3]), line(&v[3], &v[0])].into(); - crate::surfaces::surface_body(vec![mt::Face::try_new(vec![wire], mt::Surface::BSplineSurface(bsp)).unwrap()]) + let points: Vec> = (0..cu).map(|i| (0..cv).map(|j| net[j * cu + i]).collect()).collect(); + let surface = b::Surface::Spline { u_knots: ku.to_vec(), v_knots: kv.to_vec(), points }; + let corners = [(0, 0), (cu - 1, 0), (cu - 1, cv - 1), (0, cv - 1)]; + let (u, v) = ([ku[3], ku[cu]], [kv[3], kv[cv]]); + let uv = [[u[0], v[0]], [u[1], v[0]], [u[1], v[1]], [u[0], v[1]]]; + let vertices: Vec<[f64; 3]> = corners.iter().map(|&(i, j)| net[j * cu + i]).collect(); + let edges = (0..4) + .map(|k| PartEdge { + nurbs: None, + curve: b::Curve::Line { start: vertices[k], end: vertices[(k + 1) % 4] }, + interval: [0.0, 1.0], + vertices: [k as u32, ((k + 1) % 4) as u32], + }) + .collect(); + let loops = vec![ + (0..4) + .map(|k| PartUse { + edge: k as u32, + forward: true, + given: Some(b::Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![uv[k], uv[(k + 1) % 4]] }), + }) + .collect(), + ]; + let made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops }], tolerance: 1e-6 }, false).unwrap(); + crate::native::body_from_smlib(&solidcraft_smlib::Brep::from_record(&made.brep, true).unwrap()).unwrap() + } + + /// Each edge of the body's record: its curve, interval and vertices. + fn edge_records(body: &Body) -> Vec<(b::Curve, [f64; 2], [u32; 2])> { + crate::native::brep_record(body).unwrap().edges.into_iter().map(|e| (e.curve, e.interval, e.vertices)).collect() + } + + /// The surface of face `i` of the body's record. + fn face_surface(body: &Body, i: usize) -> b::Surface { + crate::native::brep_record(body).unwrap().faces[i].surface.clone() } #[test] @@ -1432,12 +1538,10 @@ mod tests { rough[j * cu + i][2] += d; } let body = sheet(&ku, &kv, &rough); - let before: Vec<_> = - body.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect(); + let before = edge_records(&body); assert!(!before.is_empty()); let (faired, report) = fair_faces(&body, &[0], &FairOptions::new(1.0, 6, false, 50.0).unwrap()).unwrap(); - let after: Vec<_> = - faired.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect(); + let after = edge_records(&faired); eprintln!( "face: energy {:e} → {:e} in {} steps, movement {:e} mm, {} faces, history {}", report.energy_before, @@ -1452,12 +1556,12 @@ mod tests { assert!(faired.history().is_some(), "the face came from the one it was faired from"); assert!(report.energy_after < 1e-9 * report.energy_before); // The face's own surface is back on the plane, boundary rows bit for bit as they were. - let Some(mt::Surface::BSplineSurface(s)) = faired.solid.face_iter().next().map(|f| f.surface()) else { panic!("a B-spline face") }; + let b::Surface::Spline { points, .. } = face_surface(&faired, 0) else { panic!("a B-spline face") }; for j in 0..cv { for i in 0..cu { - let p = s.control_points()[i][j]; + let p = points[i][j]; let want = if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv { rough[j * cu + i] } else { smooth[j * cu + i] }; - assert!(dist(&[p.x, p.y, p.z], &want) < 1e-6, "({i}, {j})"); + assert!(dist(&p, &want) < 1e-6, "({i}, {j})"); } } // A solid keeps its shells, its faces and its edges: thickening the sheet gives a closed @@ -1465,18 +1569,13 @@ mod tests { // solid of the same shape. let solid = crate::thicken(&body, 2.0, false).unwrap(); assert!(!solid.is_surface()); - let top = - (0..solid.face_count()).find(|&i| matches!(solid.solid.face_iter().nth(i).map(|f| f.surface()), Some(mt::Surface::BSplineSurface(_)))); + let top = (0..solid.face_count()).find(|&i| matches!(face_surface(&solid, i), b::Surface::Spline { .. })); let Some(top) = top else { panic!("the thickened sheet keeps its B-spline face") }; - let edges: Vec<_> = - solid.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect(); + let edges = edge_records(&solid); let (faired, report) = fair_faces(&solid, &[top], &FairOptions::new(1.0, 6, false, 0.5).unwrap()).unwrap(); eprintln!("thickened solid: energy {:e} → {:e}, movement {:e} mm", report.energy_before, report.energy_after, report.movement); assert!(!faired.is_surface() && faired.face_count() == solid.face_count() && faired.shell_count() == solid.shell_count()); - assert_eq!( - faired.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect::>(), - edges - ); + assert_eq!(edge_records(&faired), edges); assert!(report.energy_after < report.energy_before); // A face with no control points to fair is refused, by name. let cube = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); diff --git a/crates/kernel/src/fill.rs b/crates/kernel/src/fill.rs index ce2b8e05c..c10d60283 100644 --- a/crates/kernel/src/fill.rs +++ b/crates/kernel/src/fill.rs @@ -1,22 +1,36 @@ -//! Filling a closed loop of a body's edges that is not planar with one face, bounded by the -//! body's own edges, whole: a B-spline height field over the loop's best-fit plane -//! (`solidcraft_geom::fill::fill_loop`) when the patch only has to meet the edges (G0) and the -//! loop bounds one; otherwise the general fill (`solidcraft_geom::fill_general`), developed from -//! the loop itself, which also meets the faces beside the loop with G1 or G2 and passes through -//! given points. +//! Filling a closed loop of a body's edges with one face, bounded by the body's own edges, +//! whole: the loop's plane when its edges certainly lie in one, otherwise a B-spline height field +//! over the loop's best-fit plane (`solidcraft_geom::fill::fill_loop`). The face is assembled on +//! the body's own edge records (`sew::assemble`) and built by SMLib. The height field's +//! parameters are plane coordinates, so each edge's pcurve is its exact projection onto the +//! plane. +//! +//! The general fill, which also meets the faces beside the loop with G1 … G4, passes through +//! given points, and fills loops that bound no height field, is a patch whose boundary rows are +//! the loop's own edges (`solidcraft_geom::fill_iso`): each edge's pcurve is a straight line in +//! (u, v), affine in the edge's own parameter. It takes loops of three to sixteen line, spline or +//! rational edges (a circle's arc on the NURBS form SMLib holds it as); the frames across each +//! edge are read off the neighbouring face's record surface, with its exact derivatives to the +//! order asked: the neighbour as a height over its tangent plane to that order +//! (`solidcraft_geom::linkage`). -use solidcraft_geom::Vec3; -use solidcraft_geom::bspline::SplineError; -use solidcraft_geom::fill_general::{Across, FillSpec, MAX_FILL_POINTS, Station}; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self as b, Curve2}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::brep::eval::SurfaceEval; +use solidcraft_geom::bspline::{HPoint, SplineError}; +use solidcraft_geom::fill_general::{Across, MAX_FILL_POINTS, Station}; +use solidcraft_geom::fill_iso::{IsoEdge, IsoFill, IsoSpec}; +use solidcraft_geom::fill_matched::{MatchedFill, MatchedSpec}; +use solidcraft_geom::prelude::*; -use crate::body::{Body, from_p3}; -use crate::bridge::{Continuity, frames_across}; -use crate::plane_fit::EdgeSampler; -use crate::record::{Rebuild, rebuilt_body}; +use crate::body::Body; +use crate::bridge::Continuity; +use crate::history::{Change, EdgeOrigin, EdgeProv, FaceProv, History}; +use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble}; use crate::{KernelError, Result}; -/// How far (degrees) a G1 or G2 patch's normal may turn from its neighbour's along the loop. +/// How far (degrees) a G1 … G4 patch's normal may turn from its neighbour's along the loop. pub const PATCH_ANGLE_TOL_DEG: f64 = 0.05; /// A spline error as the patch reports it. @@ -30,7 +44,7 @@ fn spline_error(e: SplineError) -> KernelError { /// What a patch on a loop of edges must do besides filling it. #[derive(Clone, Debug, PartialEq)] pub struct PatchSpec { - /// How every edge's neighbour is met (G0, G1 or G2). + /// How every edge's neighbour is met (G0 … G4). pub continuity: Continuity, /// Edges met otherwise: a point on the edge and its continuity. pub edges: Vec<(Vec3, Continuity)>, @@ -68,9 +82,14 @@ pub struct PatchReport { /// corners where the neighbours themselves disagree, and anywhere. pub normal_deviation_deg: f64, pub normal_deviation_all_deg: f64, - /// The largest difference (1/mm) between the patch's normal curvature across a G2 edge and - /// the neighbour's. - pub curvature_mismatch: f64, + /// The largest angle (degrees) by which the patch's normal misses a neighbour's beyond the + /// loop edge's own lean out of that neighbour's tangent plane (what the tolerance holds). + pub normal_excess_deg: f64, + /// `jumps[k]`, k = 2 … 4: the largest jump across the edges asked for order k or more, clear + /// of the loop's corners, of the k-th derivative of the linkage curves' height above the + /// neighbour (1/mmᵏ⁻¹): the normal curvature (k = 2), its rate of change + /// (3) and that rate's (4) (`solidcraft_geom::fill_iso::Achieved::jumps`). + pub jumps: [f64; solidcraft_geom::linkage::MAX_CONTINUITY + 1], /// The farthest point from the surface. pub point_gap: f64, } @@ -91,10 +110,6 @@ pub fn patch_edges_report(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result< if !(solidcraft_geom::fill::MIN_CROWN..=solidcraft_geom::fill::MAX_CROWN).contains(&spec.crown) { return Err(KernelError::Invalid("a patch's crown must be between -0.9 and 3".into())); } - let g3 = |g: Continuity| g == Continuity::G3; - if g3(spec.continuity) || spec.edges.iter().any(|(_, g)| g3(*g)) { - return Err(KernelError::Invalid("not supported yet: a patch meets its neighbours with g0, g1 or g2".into())); - } if spec.edges.len() > 10_000 || spec.edges.iter().any(|(p, _)| !p.is_finite()) { return Err(KernelError::Invalid("pick at most 10000 edges, each by a finite point, for their continuity".into())); } @@ -105,207 +120,380 @@ pub fn patch_edges_report(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result< return patch_edges_crowned(body, at, spec.crown).map(|b| (b, PatchReport::default())); } body.require_brep("patch")?; - crate::guard("patch", || { - let chain = crate::surfaces::picked_loop(body, at)?; - let mut orders = vec![spec.continuity; chain.len()]; - for (p, g) in &spec.edges { - let e = crate::surfaces::edge_near(body, *p).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?; - let k = chain - .iter() - .position(|c| c.id() == e.id()) - .ok_or_else(|| KernelError::Invalid("a continuity pick is not on an edge of the loop".into()))?; - if let Some(slot) = orders.get_mut(k) { - *slot = *g; - } + let record = crate::native::brep_record(body)?; + let chain = picked_loop(&record, at, body.size() * 0.05 + 1e-6)?; + let mut orders = vec![spec.continuity; chain.len()]; + for (p, g) in &spec.edges { + let e = nearest_edge(&record, *p, body.size() * 0.05 + 1e-6).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?; + let k = chain.iter().position(|c| c.0 == e).ok_or_else(|| KernelError::Invalid("a continuity pick is not on an edge of the loop".into()))?; + if let Some(slot) = orders.get_mut(k) { + *slot = *g; } - if spec.crown != 0.0 && orders.iter().all(|g| *g == Continuity::G0) { - return Err(KernelError::Invalid("not supported yet: a crown on a patch through points with no g1 or g2 edge".into())); - } - general_fill(body, &chain, &orders, &spec.points, spec.crown) - }) + } + if spec.crown != 0.0 && orders.iter().all(|g| *g == Continuity::G0) { + return Err(KernelError::Invalid("not supported yet: a crown on a patch through points with no g1 or higher edge".into())); + } + general_fill(body, &record, &chain, &orders, &spec.points, spec.crown) } -/// One edge of the loop as the general fill samples it. -struct Side { - sampler: EdgeSampler, - start: Vec3, - /// The face beside the edge, and whether its boundary runs the edge the way the loop does. - face: mt::Face, - along: bool, - order: Continuity, - /// The loop has a corner at the edge's start, and the neighbours' tangent planes disagree - /// there. - corner: bool, - clash: bool, -} - -impl Side { - fn point(&mut self, t: f64) -> Option { - // The loop's corners are its vertices (an imported edge's curve may end a little off). - if t <= 0.0 { Some(self.start) } else { self.sampler.at(t) } +/// The general fill of the loop `chain` of the record's edges, edge `k` meeting the face beside it +/// with `orders[k]` (module docs). +fn general_fill( + body: &Body, + record: &b::Brep, + chain: &[(usize, bool)], + orders: &[Continuity], + points: &[Vec3], + crown: f64, +) -> Result<(Body, PatchReport)> { + if !(1..=solidcraft_geom::fill_iso::MAX_ISO_EDGES).contains(&chain.len()) { + return Err(KernelError::Invalid(format!( + "not supported yet: a general patch on a loop of {} edges (one to {})", + chain.len(), + solidcraft_geom::fill_iso::MAX_ISO_EDGES + ))); } - - /// The loop's unit tangent at `t`, by a central difference (one-sided at the ends). - fn tangent(&mut self, t: f64) -> Option { - const STEP: f64 = 1e-4; - let (a, b) = ((t - STEP).max(0.0), (t + STEP).min(1.0)); - let (p, q) = (self.sampler.at(a)?, self.sampler.at(b)?); - (q - p).normalized() - } - - /// The face's frames at points of this edge with the loop's tangents there. - fn frames(&self, stations: &[(Vec3, Vec3)], size: f64, shape: bool) -> Result> { - let along: Vec<(Vec3, Vec3)> = stations.iter().map(|(p, t)| (*p, if self.along { *t } else { *t * -1.0 })).collect(); - frames_across(&self.face, &along, size, shape) - } -} - -/// The general fill of the closed loop `chain` of `body`'s edges, edge `k` meeting the face beside -/// it with `orders[k]`, passing through `points`, its middle made fuller by `crown` (see -/// [`PatchSpec::crown`]). Call it under [`crate::guard`]. -pub(crate) fn general_fill(body: &Body, chain: &[mt::Edge], orders: &[Continuity], points: &[Vec3], crown: f64) -> Result<(Body, PatchReport)> { - let tol = face_tolerance(body); + let pieces = loop_pieces(record, chain)?; + let edges: Vec = pieces.iter().map(|p| iso_edge(record, p)).collect::>()?; let size = body.size().max(solidcraft_geom::LINEAR_TOL); - let mut sides: Vec = Vec::with_capacity(chain.len()); - for (e, order) in chain.iter().zip(orders) { - let faces: Vec<&mt::Face> = body.solid.face_iter().filter(|f| f.edge_iter().any(|x| x.id() == e.id())).collect(); - let face = match faces.as_slice() { - [f] => (*f).clone(), - [f, ..] if *order == Continuity::G0 => (*f).clone(), - [] => return Err(KernelError::Failed("patch: an edge of the loop bounds no face".into())), - _ => return Err(KernelError::Invalid("an edge of the loop lies between two faces: g1 and g2 need the one face beside it".into())), - }; - let along = face - .boundaries() - .iter() - .flat_map(|w| w.edge_iter()) - .find(|x| x.id() == e.id()) - .map(|x| x.orientation() == e.orientation()) - .ok_or_else(|| KernelError::Failed("patch: the face beside an edge does not hold it".into()))?; - let sampler = EdgeSampler::new(e).ok_or_else(|| KernelError::Invalid("an edge has no parameter range".into()))?; - sides.push(Side { sampler, start: from_p3(e.front().point()), face, along, order: *order, corner: false, clash: false }); + let mut beside: Vec> = Vec::with_capacity(pieces.len()); + for p in &pieces { + let order = chain.iter().position(|&(e, _)| e == p.edge).and_then(|k| orders.get(k)).copied().unwrap_or(Continuity::G0); + beside.push(if order == Continuity::G0 { None } else { Some(Beside::new(record, p.edge, p.forward, order, size)?) }); } - // The corners: where the loop's tangent turns, and where the faces beside it disagree. - let n = sides.len(); - for k in 0..n { - let prev = (k + n - 1) % n; - let (Some(t_in), Some(t_out)) = (sides.get_mut(prev).and_then(|s| s.tangent(1.0)), sides.get_mut(k).and_then(|s| s.tangent(0.0))) else { - return Err(KernelError::Invalid("an edge of the loop has no tangent".into())); - }; - let Some(vertex) = sides.get(k).map(|s| s.start) else { continue }; - let corner = t_in.dot(t_out) < CORNER_DEG.to_radians().cos(); - let normal = |s: Option<&Side>, t: Vec3| -> Result { - let s = s.ok_or_else(|| KernelError::Failed("patch: side".into()))?; - let f = s.frames(&[(vertex, t)], size, false)?; - f.first().map(|f| f.1).ok_or_else(|| KernelError::Failed("patch: frame".into())) - }; - let g1 = |s: Option<&Side>| s.is_some_and(|s| s.order != Continuity::G0); - let clash = if g1(sides.get(prev)) || g1(sides.get(k)) { - let (a, b) = (normal(sides.get(prev), t_in)?, normal(sides.get(k), t_out)?); - a.dot(b).abs() < (2.0 * PATCH_ANGLE_TOL_DEG).to_radians().cos() - } else { - false - }; - if let Some(s) = sides.get_mut(k) { - s.corner = corner; - s.clash = clash; + let mut across = |k: usize, ts: &[f64]| -> std::result::Result>, String> { + match beside.get(k) { + None => Err("no such edge".into()), + Some(None) => Ok(vec![None; ts.len()]), + Some(Some(side)) => ts.iter().map(|t| side.across(record, *t).map_err(|e| e.to_string())).collect(), } - } - let mut stations = |k: usize, ts: &[f64]| -> std::result::Result, String> { - let side = sides.get_mut(k).ok_or("no such side")?; - let mut at = Vec::with_capacity(ts.len()); - for &t in ts { - let (Some(p), Some(tangent)) = (side.point(t), side.tangent(t)) else { return Err("an edge cannot be sampled".into()) }; - at.push((p, tangent)); - } - let frames = side.frames(&at, size, side.order == Continuity::G2).map_err(|e| e.to_string())?; - let mut out = Vec::with_capacity(ts.len()); - for ((&t, (p, tangent)), (frame, normal)) in ts.iter().zip(&at).zip(&frames) { - let up = tangent.cross(frame.leave).normalized().ok_or("the loop runs across its neighbour")?; - let across = (side.order != Continuity::G0).then(|| Across { - leave: frame.leave, - normal: *normal, - bend: (side.order == Continuity::G2).then_some(frame.bend), - }); - let first = t <= 0.0; - out.push(Station { p: *p, up, across, corner: first && side.corner, clash: first && side.clash }); - } - Ok(out) }; - let spec = FillSpec { tol, angle_tol: PATCH_ANGLE_TOL_DEG.to_radians(), crown, points }; - let fill = solidcraft_geom::fill_general::fill_general(chain.len(), &mut stations, &spec).map_err(spline_error)?; - // The wire runs counter-clockwise about the surface's normal. - let wire: mt::Wire = - if fill.counter_clockwise { chain.to_vec().into() } else { chain.iter().rev().map(mt::Edge::inverse).collect::>().into() }; - let face = mt::Face::try_new(vec![wire], crate::spline_conv::surface(&fill.surface)?).map_err(|e| KernelError::Failed(format!("fill: {e}")))?; - let mut rec = Rebuild::default(); - rec.made(&face, Vec::new()); + let spec = + IsoSpec { tol: face_tolerance(body), angle_tol: PATCH_ANGLE_TOL_DEG.to_radians(), crown, corner_turn: CORNER_TURN_DEG.to_radians(), points }; + let fill = solidcraft_geom::fill_iso::iso_fill(&edges, &mut across, &spec).map_err(spline_error)?; + let made = quilt_body(body, record, &pieces, &fill, face_tolerance(body))?; + let a = fill.achieved; let report = PatchReport { general: true, - gap: fill.deviation, - normal_deviation_deg: fill.normal_deviation.to_degrees(), - normal_deviation_all_deg: fill.normal_deviation_all.to_degrees(), - curvature_mismatch: fill.curvature_mismatch, - point_gap: fill.point_deviation, + gap: 0.0, + normal_deviation_deg: a.normal_deviation.to_degrees(), + normal_deviation_all_deg: a.normal_deviation_all.to_degrees(), + normal_excess_deg: a.normal_excess.to_degrees(), + jumps: a.jumps, + point_gap: a.point_deviation, }; - Ok((rebuilt_body(crate::surfaces::surface_body(vec![face]), &[&body.solid], &rec), report)) + Ok((made, report)) } -/// The loop turns by more than this (degrees) at a corner: its stations hold position only. -const CORNER_DEG: f64 = 1.0; +/// How far (degrees) the loop may turn at a vertex for it not to be a corner of the loop. +const CORNER_TURN_DEG: f64 = 1.0; -/// A surface body of one face filling the closed loop `chain` of `body`'s edges (each edge -/// oriented along the loop, each ending where the next starts), within [`face_tolerance`] of -/// every edge. Its history is over `[body]`: the face is new, its edges the body's own. Call it -/// under [`crate::guard`]. -pub(crate) fn fill_loop(body: &Body, chain: &[mt::Edge]) -> Result { - fill_loop_crowned(body, chain, 0.0) -} - -/// [`fill_loop`] with a crown: positive makes the fitted patch's middle fuller, negative flatter, -/// by `crown` times the loop's size (see `solidcraft_geom::fill::fill_loop`). The bump vanishes on -/// the loop, so the face still meets the body's own edges exactly as the plain fill does. -pub(crate) fn fill_loop_crowned(body: &Body, chain: &[mt::Edge], crown: f64) -> Result { - let tol = face_tolerance(body); - let mut sides: Vec<(EdgeSampler, Vec3)> = Vec::with_capacity(chain.len()); - for e in chain { - let sampler = EdgeSampler::new(e).ok_or_else(|| KernelError::Invalid("an edge has no parameter range".into()))?; - sides.push((sampler, from_p3(e.front().point()))); +/// The one-face sheet on the loop `chain` of `body`'s own edges (each a free edge of the face +/// beside it), a height field over the loop's plane that meets every face beside the loop with +/// G2 (`solidcraft_geom::fill_matched`), within [`face_tolerance`] of the loop, its normal within +/// [`PATCH_ANGLE_TOL_DEG`] and its normal curvature across the loop within `curvature_tol` of +/// each face's, clear of the loop's corners (a vertex where the loop turns, where two faces +/// meet). Each edge's pcurve is its exact projection onto the plane. Its history is over +/// `[body]`: the face is new, each edge the body's own. +pub(crate) fn matched_patch(body: &Body, chain: &[(usize, bool)], curvature_tol: f64) -> Result<(Body, MatchedFill)> { + body.require_brep("patch")?; + if chain.len() < 2 { + return Err(KernelError::Invalid("a patch needs a loop of two or more edges".into())); } - let mut point = |k: usize, t: f64| -> Option { - let (sampler, start) = sides.get_mut(k)?; - // The loop's corners are its vertices (an imported edge's curve may end a little off). - if t <= 0.0 { Some(*start) } else { sampler.at(t) } + let record = crate::native::brep_record(body)?; + let size = body.size().max(solidcraft_geom::LINEAR_TOL); + let mut sides = Vec::with_capacity(chain.len()); + let mut beside = Vec::with_capacity(chain.len()); + for &(e, forward) in chain { + sides.push(Side::new(&record, e, forward)?); + beside.push(Beside::new(&record, e, forward, Continuity::G2, size)?); + } + // A vertex of the loop is a corner where the loop turns there: the edge arriving and the one + // leaving go different ways. + let n = chain.len(); + let mut corner = vec![false; n]; + for (k, slot) in corner.iter_mut().enumerate() { + let prev = (k + n - 1) % n; + let (Some(a), Some(b)) = (sides.get(prev), sides.get(k)) else { continue }; + let (Some(arrive), Some(leave)) = (a.direction(1.0), b.direction(0.0)) else { continue }; + *slot = arrive.dot(leave) < CORNER_TURN_DEG.to_radians().cos(); + } + let mut stations = |k: usize, ts: &[f64]| -> std::result::Result, String> { + let (Some(side), Some(face)) = (sides.get_mut(k), beside.get(k)) else { return Err("no such edge".into()) }; + let edge = record.edges.get(face.edge).ok_or("edge reference")?; + let [a, z] = edge.interval; + ts.iter() + .map(|&t| { + let p = side.point(t).ok_or("an edge has no point there")?; + let across = face.across(&record, a + (z - a) * t).map_err(|e| e.to_string())?.ok_or("an edge has no tangent there")?; + let at_corner = t == 0.0 && corner.get(k).copied().unwrap_or(false); + Ok(Station { p, up: across.normal, across: Some(across), corner: at_corner, clash: false }) + }) + .collect() }; - let fill = match solidcraft_geom::fill::fill_loop(chain.len(), &mut point, tol, crown) { - Ok(fill) => fill, - // Not a height field over its plane (or too wavy for one): the general fill, developed - // from the loop itself, when no crown asks for the height field's bump. - Err(SplineError::Unsupported(_)) if crown == 0.0 => { - let orders = vec![Continuity::G0; chain.len()]; - return general_fill(body, chain, &orders, &[], 0.0).map(|(b, _)| b); + let spec = MatchedSpec { tol: face_tolerance(body), angle_tol: PATCH_ANGLE_TOL_DEG.to_radians(), curvature_tol }; + let fill = solidcraft_geom::fill_matched::fill_matched(n, &mut stations, &spec).map_err(spline_error)?; + let projection = Projection { origin: fill.fill.origin, axes: fill.fill.axes }; + let surface = crate::surfaces::spline_surface(&fill.fill.surface); + let made = patch_body(body, &record, chain, surface, fill.fill.counter_clockwise, &Pcurves::Projected(&projection), face_tolerance(body))?; + Ok((made, fill)) +} + +/// A piece of a loop edge as the general fill takes it: record edge `edge` over `interval` (in +/// its own parameter, min < max), run the loop's way along it (`forward`) or back. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Piece { + edge: usize, + forward: bool, + interval: [f64; 2], +} + +/// The loop `chain` as the general fill's sides: each edge whole, but for a loop of one or two +/// edges (a tube's end: one closed circle) each edge in equal pieces of its parameter, four sides +/// in all, so the fill is one four-sided patch on pieces of the edges' own curves. +fn loop_pieces(record: &b::Brep, chain: &[(usize, bool)]) -> Result> { + let split = match chain.len() { + 1 => 4, + 2 => 2, + _ => 1, + }; + let mut out = Vec::with_capacity(chain.len() * split); + for &(e, forward) in chain { + let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; + let [a, z] = edge.interval; + // A break that falls on one of the curve's own knots (a conic's quarter points) is that + // knot exactly: a piece must not start a rounding error off one. + let own: Vec = match edge.parameters() { + b::Curve::Spline { knots, .. } | b::Curve::RationalSpline { knots, .. } => knots.clone(), + _ => Vec::new(), + }; + let at = |i: usize| { + if i == 0 { + a + } else if i == split { + z + } else { + let t = a + (z - a) * i as f64 / split as f64; + own.iter().copied().find(|k| (k - t).abs() <= 1e-9 * (z - a).abs()).unwrap_or(t) + } + }; + let mut pieces: Vec = (0..split).map(|i| Piece { edge: e, forward, interval: [at(i), at(i + 1)] }).collect(); + if !forward { + pieces.reverse(); + } + out.extend(pieces); + } + Ok(out) +} + +/// The general fill's parameter `t` along a piece `[plo, phi]` of a record edge on `[a, z]`, run +/// the loop's way (`forward`) or back, in the record edge's own parameter: the edge's, reflected +/// where the loop runs against it, a piece's end or middle exactly. +fn on_record(a: f64, z: f64, [plo, phi]: [f64; 2], forward: bool, t: f64) -> f64 { + let near = 1e-9 * (1.0 + (z - a).abs() + a.abs().max(z.abs())); + let t = if forward { t } else { reflected(a, z, t) }; + [plo, phi, 0.5 * (plo + phi)].into_iter().find(|s| (s - t).abs() <= near).unwrap_or(t) +} + +/// `t` on an edge's interval `[a, z]` reflected about its middle: the loop's parameter along an +/// edge it runs against. +fn reflected(a: f64, z: f64, t: f64) -> f64 { + if t == a { + z + } else if t == z { + a + } else { + a + z - t + } +} + +/// A loop edge as the patch takes it: a B-spline on the edge's interval, rational when the edge +/// is (a circle or ellipse on the NURBS form SMLib holds it as, whose parameter the edge's interval +/// and pcurves are in), running the loop's way, its ends on the edge's vertices. A traced curve +/// has no such form in its own parameter and is refused by name. +fn iso_edge(record: &b::Brep, piece: &Piece) -> Result { + let Piece { edge: e, forward, interval: [lo, hi] } = *piece; + let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; + let v3 = |p: &[f64; 3]| Vec3::new(p[0], p[1], p[2]); + let [a, z] = edge.interval; + let (degree, knots, h): (usize, Vec, Vec) = match edge.parameters() { + b::Curve::Line { start, end } => { + let (s, t) = (v3(start), v3(end)); + (1, vec![a, a, z, z], vec![HPoint::weighted(s + (t - s) * a, 1.0), HPoint::weighted(s + (t - s) * z, 1.0)]) + } + b::Curve::Polyline { points } => { + let mut knots = vec![0.0]; + knots.extend((0..points.len()).map(|i| i as f64)); + knots.push(points.len().saturating_sub(1) as f64); + (1, knots, points.iter().map(|p| HPoint::weighted(v3(p), 1.0)).collect()) + } + b::Curve::Spline { knots, points } => { + (knots.len().saturating_sub(points.len() + 1), knots.clone(), points.iter().map(|p| HPoint::weighted(v3(p), 1.0)).collect()) + } + b::Curve::RationalSpline { knots, homogeneous } => ( + knots.len().saturating_sub(homogeneous.len() + 1), + knots.clone(), + homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(), + ), + _ => { + return Err(KernelError::Invalid(format!( + "not supported yet: a general patch on edge {e}, a circle or ellipse with no NURBS form, or a traced curve (its pcurve on the patch has no exact form in its own parameter)" + ))); } - Err(e) => return Err(spline_error(e)), }; - // The wire runs counter-clockwise about the surface's normal. - let wire: mt::Wire = - if fill.counter_clockwise { chain.to_vec().into() } else { chain.iter().rev().map(mt::Edge::inverse).collect::>().into() }; - let face = mt::Face::try_new(vec![wire], crate::spline_conv::surface(&fill.surface)?).map_err(|e| KernelError::Failed(format!("fill: {e}")))?; - let mut rec = Rebuild::default(); - rec.made(&face, Vec::new()); - Ok(rebuilt_body(crate::surfaces::surface_body(vec![face]), &[&body.solid], &rec)) + // The piece of the edge, then run the loop's way (the edge's parameter reflected about its + // interval's middle). + let (mut knots, mut h) = solidcraft_geom::bspline::segment(degree, &knots, &h, lo, hi).map_err(spline_error)?; + if !forward { + knots = knots.iter().rev().map(|k| a + z - k).collect(); + h.reverse(); + // The ends exactly (the reflection's rounding), so a piece's ends name them. + let (rlo, rhi) = (reflected(a, z, hi), reflected(a, z, lo)); + let n = knots.len(); + for (i, k) in knots.iter_mut().enumerate() { + if i <= degree { + *k = rlo; + } else if i + degree + 1 >= n { + *k = rhi; + } + } + } + let rational = h.iter().any(|q| q.w != 1.0); + let mut points = h + .iter() + .map(|q| q.project().filter(|_| q.w > 0.0)) + .collect::>>() + .ok_or_else(|| KernelError::Invalid(format!("not supported yet: a general patch on edge {e}, whose weights are not all positive")))?; + // Its ends exactly on the loop's vertices, where they are the edge's ends. + let vertex = |at: f64| match (at == a, at == z) { + (true, _) => record.vertices.get(edge.vertices[0] as usize).map(|v| v3(&v.point)), + (_, true) => record.vertices.get(edge.vertices[1] as usize).map(|v| v3(&v.point)), + _ => None, + }; + let (first, last) = if forward { (vertex(lo), vertex(hi)) } else { (vertex(hi), vertex(lo)) }; + if let (Some(p), Some(f)) = (first, points.first_mut()) { + *f = p; + } + if let (Some(q), Some(l)) = (last, points.last_mut()) { + *l = q; + } + let weights = rational.then(|| h.iter().map(|q| q.w).collect()); + Ok(IsoEdge { degree, knots, points, weights }) +} + +/// The face beside a G1 … G4 edge, read at points of the edge: its record surface, which side of +/// it is outward, whether its boundary runs the edge the loop's way, and how much of it is read +/// (`order`: its tangent plane for G1, and its jet to that order above). +struct Beside { + surface: SurfaceEval, + side: f64, + along: bool, + edge: usize, + forward: bool, + order: Continuity, + reach: f64, +} + +impl Beside { + fn new(record: &b::Brep, e: usize, forward: bool, order: Continuity, size: f64) -> Result { + let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; + let [u] = edge.uses.as_slice() else { + return Err(KernelError::Invalid("an edge of the loop lies between two faces: g1 and up need the one face beside it".into())); + }; + let face = record.faces.get(u.face as usize).ok_or_else(|| KernelError::Failed("patch: face reference".into()))?; + let surface = SurfaceEval::new(face.parameters()) + .map_err(|err| KernelError::Invalid(format!("the face beside edge {e} cannot be evaluated: {err}")))?; + let outward = record + .shells + .iter() + .find_map(|s| match s { + b::Shell::Faces { faces, .. } => faces.iter().find(|f| f.face == u.face).map(|f| f.forward), + _ => None, + }) + .unwrap_or(true); + let used_forward = match face.loops.get(u.r#loop as usize) { + Some(b::Loop::Edges { edges }) => edges.get(u.position as usize).map(|x| x.forward), + _ => None, + } + .ok_or_else(|| KernelError::Failed("patch: edge use".into()))?; + // A face's boundary runs counter-clockwise about its outward normal: the record's loops + // run so about the natural normal, reversed where the outward side is the other. + let runs_forward = used_forward == outward; + Ok(Beside { + surface, + side: if outward { 1.0 } else { -1.0 }, + along: runs_forward == forward, + edge: e, + forward, + order, + reach: (size * 1e-4).max(1e-6), + }) + } + + /// The neighbour's conditions at parameter `t` of the loop's edge (its `IsoEdge`, run the + /// loop's way, whose parameter is the edge's reversed where the loop runs against it): + /// its normal, the direction it leaves the edge in, away from it, and for G2 and up its + /// curvature vector along that direction and its jet to the order asked + /// (`solidcraft_geom::linkage::surface_jet`, on the frame of the boundary and the leave + /// direction). `None` where the edge has no tangent there. + fn across(&self, record: &b::Brep, t: f64) -> Result> { + let edge = record.edges.get(self.edge).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; + let [a, z] = edge.interval; + let tau = if self.forward { t } else { a + z - t }; + let curve = CurveEval::new(edge.parameters()).map_err(|e| KernelError::Invalid(e.to_string()))?; + let Some((p, d)) = curve.derivs(tau) else { return Ok(None) }; + let Some(tangent) = (d * if self.forward { 1.0 } else { -1.0 }).normalized() else { return Ok(None) }; + let uv = + self.surface.project(p, None, self.reach).ok_or_else(|| KernelError::Invalid("a picked edge is not on the face beside it".into()))?; + let (_, su, sv) = + self.surface.derivs(uv[0], uv[1]).ok_or_else(|| KernelError::Failed("patch: the face beside an edge has no derivatives".into()))?; + let normal = + (su.cross(sv) * self.side).normalized().ok_or_else(|| KernelError::Failed("patch: the face beside an edge has no normal".into()))?; + // Away from the face: its boundary's direction × its outward normal. + let boundary = if self.along { tangent } else { tangent * -1.0 }; + let leave = boundary.cross(normal).normalized().ok_or_else(|| KernelError::Invalid("the boundary runs along the face's normal".into()))?; + let order = continuity_order(self.order); + if order < 2 { + return Ok(Some(Across { leave, normal, bend: None, jet: None })); + } + let bend = Some(normal * normal_curvature(&self.surface, uv, normal, leave)?); + let jet = solidcraft_geom::linkage::surface_jet(&self.surface, uv, normal, leave, order).ok_or_else(|| { + KernelError::Invalid(format!("not supported yet: g{order} to a face whose surface has no derivatives of order {order} there")) + })?; + Ok(Some(Across { leave, normal, bend, jet: Some(jet) })) + } +} + +/// The continuity order a [`Continuity`] asks: 0 (G0) … n, the one place it is read as a number. +fn continuity_order(g: Continuity) -> usize { + g.conditions().saturating_sub(1) +} + +/// The normal curvature of a surface at `uv` along the unit tangent `w`: `n·r''` of the unit-speed +/// curve on it leaving that way (the second fundamental form, exact second derivatives). +fn normal_curvature(s: &SurfaceEval, uv: [f64; 2], n: Vec3, w: Vec3) -> Result { + let fail = || KernelError::Failed("patch: the face beside an edge has no curvature there".into()); + let (_, ru, rv) = s.derivs(uv[0], uv[1]).ok_or_else(fail)?; + let (ruu, ruv, rvv) = s.second(uv[0], uv[1]).ok_or_else(fail)?; + // w = ru·α + rv·β, solved in the tangent plane. + let (e, f, g) = (ru.dot(ru), ru.dot(rv), rv.dot(rv)); + let det = e * g - f * f; + if !(det > 0.0) { + return Err(fail()); + } + let (wu, wv) = (w.dot(ru), w.dot(rv)); + let (alpha, beta) = ((g * wu - f * wv) / det, (e * wv - f * wu) / det); + let k = n.dot(ruu * (alpha * alpha) + ruv * (2.0 * alpha * beta) + rvv * (beta * beta)); + k.is_finite().then_some(k).ok_or_else(fail) } /// [`crate::patch_edges`] with a crown on the fitted face: positive makes the patch's middle /// fuller, negative flatter, by `crown` times the loop's size (its projected box's diagonal), the /// bump vanishing along the loop, so the face still meets the body's own edges. `crown` 0 is -/// exactly [`crate::patch_edges`], and a loop that is certainly planar ([`crate::plane_fit`]) -/// makes the same exact planar face whatever the crown. Its history is over `[body]`: the face is -/// new, its edges the body's own. +/// exactly [`crate::patch_edges`], and a loop that is certainly planar makes the same exact planar +/// face whatever the crown. Its history is over `[body]`: the face is new, its edges the body's +/// own. pub fn patch_edges_crowned(body: &Body, at: &[Vec3], crown: f64) -> Result { - if crown == 0.0 { - return crate::surfaces::patch_edges(body, at); - } body.require_brep("patch")?; if at.is_empty() || at.len() > 10_000 { return Err(KernelError::Invalid("pick the edges of a closed loop".into())); @@ -314,17 +502,500 @@ pub fn patch_edges_crowned(body: &Body, at: &[Vec3], crown: f64) -> Result if !(solidcraft_geom::fill::MIN_CROWN..=solidcraft_geom::fill::MAX_CROWN).contains(&crown) { return Err(KernelError::Invalid("a patch's crown must be between -0.9 and 3".into())); } - crate::guard("patch", || { - let chain = crate::surfaces::picked_loop(body, at)?; - let Some(face) = crate::plane_fit::planar_face(&chain, planarity_tolerance(body))? else { - // Not certainly planar: a fitted surface, crowned. - return fill_loop_crowned(body, &chain, crown); + patch_loop(body, at, crown) +} + +/// The patch on the closed loop of `body`'s edges picked by `at`: the loop's plane when it is +/// certainly planar (within [`planarity_tolerance`]), else the height field crowned by `crown`. +/// What `crate::patch_edges` makes with `crown` 0. +pub(crate) fn patch_loop(body: &Body, at: &[Vec3], crown: f64) -> Result { + let record = crate::native::brep_record(body)?; + let reach = body.size() * 0.05 + 1e-6; + let chain = picked_loop(&record, at, reach)?; + let mut sides = Vec::with_capacity(chain.len()); + for &(e, forward) in &chain { + sides.push(Side::new(&record, e, forward)?); + } + let (surface, ccw, pcurve): (b::Surface, bool, Option) = match planar(&record, &chain, &mut sides, planarity_tolerance(body))? { + Some(plane) => (plane, true, None), + None => { + let tol = face_tolerance(body); + let mut point = |k: usize, t: f64| sides.get_mut(k).and_then(|s| s.point(t)); + let fill = match solidcraft_geom::fill::fill_loop(chain.len(), &mut point, tol, crown) { + Ok(fill) => fill, + // Not a height field over its plane: the general fill, when no crown asks for the + // height field's bump. + Err(SplineError::Unsupported(_)) if crown == 0.0 => { + let orders = vec![Continuity::G0; chain.len()]; + return general_fill(body, &record, &chain, &orders, &[], 0.0).map(|(b, _)| b); + } + Err(e) => return Err(spline_error(e)), + }; + let projection = Projection { origin: fill.origin, axes: fill.axes }; + (crate::surfaces::spline_surface(&fill.surface), fill.counter_clockwise, Some(projection)) + } + }; + let pcurves = match &pcurve { + Some(p) => Pcurves::Projected(p), + None => Pcurves::Computed, + }; + patch_body(body, &record, &chain, surface, ccw, &pcurves, face_tolerance(body)) +} + +/// The closed loop of `record`'s edges picked by points on them (the edge nearest each, within +/// `reach`), each with whether the loop runs along it: it starts with the last edge picked, run +/// its own way. Edges that branch, or do not close one loop, are refused. +fn picked_loop(record: &b::Brep, at: &[Vec3], reach: f64) -> Result> { + let mut picked: Vec = Vec::new(); + for p in at { + if !p.is_finite() { + return Err(KernelError::Invalid(format!("no edge at {p:?}"))); + } + let e = nearest_edge(record, *p, reach).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?; + if !picked.contains(&e) { + picked.push(e); + } + } + let ends = |e: usize| record.edges.get(e).map(|x| x.vertices); + let mut uses: std::collections::HashMap = std::collections::HashMap::new(); + for &e in &picked { + for v in ends(e).into_iter().flatten() { + *uses.entry(v).or_default() += 1; + } + } + if uses.values().any(|n| *n > 2) { + return Err(KernelError::Invalid("the edges branch: pick one chain".into())); + } + let open = || KernelError::Invalid("the edges do not form a closed loop".into()); + if uses.values().any(|n| *n != 2) { + return Err(open()); + } + let first = picked.pop().ok_or_else(open)?; + let [start, mut at_v] = ends(first).ok_or_else(open)?; + let mut chain = vec![(first, true)]; + while at_v != start { + let k = picked.iter().position(|e| ends(*e).is_some_and(|[a, z]| a == at_v || z == at_v)).ok_or_else(open)?; + let e = picked.remove(k); + let [a, z] = ends(e).ok_or_else(open)?; + let forward = a == at_v; + at_v = if forward { z } else { a }; + chain.push((e, forward)); + } + if !picked.is_empty() { + return Err(open()); + } + Ok(chain) +} + +/// The record edge whose curve comes nearest `p` (by samples along each), within `reach`. +fn nearest_edge(record: &b::Brep, p: Vec3, reach: f64) -> Option { + let mut best: Option<(f64, usize)> = None; + for (i, e) in record.edges.iter().enumerate() { + let Ok(c) = CurveEval::new(e.parameters()) else { continue }; + let [t0, t1] = e.interval; + for k in 0..=32 { + let Some(q) = c.point(t0 + (t1 - t0) * k as f64 / 32.0) else { continue }; + let d = q.dist(p); + if best.is_none_or(|(bd, _)| d < bd) { + best = Some((d, i)); + } + } + } + best.filter(|(d, _)| *d <= reach).map(|(_, e)| e) +} + +/// One edge of the loop as the fill samples it: `t` from 0 at the loop's start of the edge to 1 at +/// its end, the start being the edge's own vertex (an imported edge's curve may end a little off +/// it). +struct Side { + curve: CurveEval, + interval: [f64; 2], + forward: bool, + start: Vec3, +} + +impl Side { + fn new(record: &b::Brep, e: usize, forward: bool) -> Result { + let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; + let curve = CurveEval::new(edge.parameters()).map_err(|err| KernelError::Invalid(format!("edge {e} cannot be sampled: {err}")))?; + let v = edge.vertices[if forward { 0 } else { 1 }]; + let start = record.vertices.get(v as usize).map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])); + let start = start.ok_or_else(|| KernelError::Failed("patch: vertex reference".into()))?; + Ok(Side { curve, interval: edge.interval, forward, start }) + } + + fn point(&mut self, t: f64) -> Option { + if t <= 0.0 { + return Some(self.start); + } + let [a, z] = self.interval; + let s = t.min(1.0); + self.curve.point(if self.forward { a + (z - a) * s } else { z - (z - a) * s }) + } + + /// The unit direction the loop runs the edge in at `t`. + fn direction(&self, t: f64) -> Option { + let [a, z] = self.interval; + let s = t.clamp(0.0, 1.0); + let (_, d) = self.curve.derivs(if self.forward { a + (z - a) * s } else { z - (z - a) * s })?; + (if self.forward { d } else { d * -1.0 }).normalized() + } +} + +/// The plane of the loop when its edges certainly lie in one within `tol`, `None` otherwise. The +/// plane is fitted to points along the edges (through their mean, its normal the loop's area +/// vector, so the loop runs counter-clockwise about it); each edge is then certified +/// conservatively: a line by its ends, a polyline or spline by its control points (the curve lies +/// in their convex hull, weights positive), a circle or ellipse by its centre and how far its +/// axes tilt out of the plane, a traced intersection only when one of its two surfaces is a plane +/// that the loop's points lie on. Samples alone are never trusted: a spline can bulge out of the +/// plane between them. +fn planar(record: &b::Brep, chain: &[(usize, bool)], sides: &mut [Side], tol: f64) -> Result> { + const SAMPLES: usize = 16; + let mut pts = Vec::with_capacity(sides.len() * SAMPLES); + for side in sides.iter_mut() { + for k in 0..SAMPLES { + let Some(p) = side.point(k as f64 / SAMPLES as f64) else { return Ok(None) }; + pts.push(p); + } + } + let mean = pts.iter().fold(Vec3::ZERO, |s, p| s + *p) * (1.0 / pts.len().max(1) as f64); + let area = pts.iter().zip(pts.iter().cycle().skip(1)).fold(Vec3::ZERO, |n, (p, q)| n + (*p - mean).cross(*q - mean)); + let Some(n) = area.normalized() else { return Ok(None) }; + let off = |p: Vec3| (p - mean).dot(n).abs(); + let on = |p: [f64; 3]| off(Vec3::new(p[0], p[1], p[2])) <= tol; + if !pts.iter().all(|p| off(*p) <= tol) { + return Ok(None); + } + let holds = |s: &b::Surface| -> bool { + let (o, normal) = match s { + b::Surface::Plane { origin, u_axis, v_axis } => { + let (u, v) = (Vec3::new(u_axis[0], u_axis[1], u_axis[2]), Vec3::new(v_axis[0], v_axis[1], v_axis[2])); + (Vec3::new(origin[0], origin[1], origin[2]), u.cross(v).normalized()) + } + _ => return false, }; - // A new face on the body's own edges (a plane has no middle to fill). - let mut rec = Rebuild::default(); - rec.made(&face, Vec::new()); - Ok(rebuilt_body(crate::surfaces::surface_body(vec![face]), &[&body.solid], &rec)) - }) + let Some(q) = normal else { return false }; + pts.iter().all(|p| (*p - o).dot(q).abs() <= tol && (*p - n * (*p - mean).dot(n) - o).dot(q).abs() <= tol) + }; + for &(e, _) in chain { + let Some(edge) = record.edges.get(e) else { return Ok(None) }; + let certified = match &edge.curve { + b::Curve::Line { start, end } => on(*start) && on(*end), + b::Curve::Polyline { points } | b::Curve::Spline { points, .. } => points.iter().all(|p| on(*p)), + b::Curve::RationalSpline { homogeneous, .. } => homogeneous.iter().all(|h| h[3] > 0.0 && on([h[0] / h[3], h[1] / h[3], h[2] / h[3]])), + b::Curve::Circle { frame, radius } => conic_on(frame, [*radius; 2], &on, n, tol), + b::Curve::Ellipse { frame, radii } => conic_on(frame, *radii, &on, n, tol), + b::Curve::SurfaceIntersection { surfaces, .. } => surfaces.iter().any(|s| holds(s)), + }; + if !certified { + return Ok(None); + } + } + let t = if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }; + let Some(u) = (t - n * t.dot(n)).normalized() else { return Ok(None) }; + let arr = |p: Vec3| [p.x, p.y, p.z]; + Ok(Some(b::Surface::Plane { origin: arr(mean), u_axis: arr(u), v_axis: arr(n.cross(u)) })) +} + +/// A conic lies within `tol` of the plane (normal `n`) when its centre does and its axes, scaled by +/// its radii, tilt out of the plane by no more than that together. +fn conic_on(frame: &b::Frame, radii: [f64; 2], on: &dyn Fn([f64; 3]) -> bool, n: Vec3, tol: f64) -> bool { + let axis = |a: [f64; 3]| Vec3::new(a[0], a[1], a[2]).dot(n).abs(); + on(frame.origin) && radii[0] * axis(frame.x_axis) + radii[1] * axis(frame.y_axis) <= tol +} + +/// Where a patch's pcurves come from: the record's routine (a plane), or the exact projection +/// onto a height field's plane. +enum Pcurves<'a> { + Computed, + Projected(&'a Projection), +} + +/// The plane a height field stands on: its parameters are coordinates along `axes` from `origin`. +struct Projection { + origin: Vec3, + axes: [Vec3; 2], +} + +impl Projection { + /// The edge's exact pcurve on the height field: its curve projected onto the plane, which is + /// affine, so a line or spline stays one with its knots and weights. `None` for a conic or a + /// traced intersection, whose angle or trace parameter no B-spline in (u, v) reproduces. + fn pcurve(&self, curve: &b::Curve, [a, z]: [f64; 2]) -> Option { + let uv = |p: Vec3| [(p - self.origin).dot(self.axes[0]), (p - self.origin).dot(self.axes[1])]; + let v = |p: &[f64; 3]| Vec3::new(p[0], p[1], p[2]); + let (degree, knots, ctrl): (usize, Vec, Vec) = match curve { + b::Curve::Line { start, end } => { + let (s, e) = (v(start), v(end)); + let (p, q) = (s + (e - s) * a, s + (e - s) * z); + return Some(Curve2::Spline { knots: vec![a, a, z, z], points: vec![uv(p), uv(q)] }); + } + b::Curve::Polyline { points } => { + let mut knots = vec![0.0]; + knots.extend((0..points.len()).map(|i| i as f64)); + knots.push(points.len().saturating_sub(1) as f64); + (1, knots, points.iter().map(|p| HPoint::weighted(v(p), 1.0)).collect()) + } + b::Curve::Spline { knots, points } => { + (knots.len().checked_sub(points.len() + 1)?, knots.clone(), points.iter().map(|p| HPoint::weighted(v(p), 1.0)).collect()) + } + b::Curve::RationalSpline { knots, homogeneous } => ( + knots.len().checked_sub(homogeneous.len() + 1)?, + knots.clone(), + homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(), + ), + b::Curve::Circle { .. } | b::Curve::Ellipse { .. } | b::Curve::SurfaceIntersection { .. } => return None, + }; + // The piece on the edge's own interval (the same points at the same parameters). + let domain = [*knots.get(degree)?, *knots.get(knots.len() - degree - 1)?]; + let (knots, ctrl) = if domain == [a, z] { (knots, ctrl) } else { solidcraft_geom::bspline::segment(degree, &knots, &ctrl, a, z).ok()? }; + let homogeneous = ctrl + .iter() + .map(|h| { + let p = uv(Vec3::new(h.x / h.w, h.y / h.w, h.z / h.w)); + [p[0] * h.w, p[1] * h.w, h.w] + }) + .collect(); + Some(Curve2::RationalSpline { knots, homogeneous }) + } +} + +/// The one-face sheet on `surface` bounded by the loop `chain` of `record`'s own edges, run +/// counter-clockwise about the surface's natural normal (`ccw`: the chain already does), each +/// edge's pcurve the exact projection where the surface is a height field. Its history is over +/// `[body]`: the face is new, each edge the body's own. +fn patch_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], surface: b::Surface, ccw: bool, pcurves: &Pcurves, tol: f64) -> Result { + let fail = |m: &str| KernelError::Failed(format!("patch: {m}")); + let mut vertices: Vec<[f64; 3]> = Vec::new(); + let mut vertex_of: std::collections::HashMap = std::collections::HashMap::new(); + let mut edges = Vec::with_capacity(chain.len()); + let mut uses = Vec::with_capacity(chain.len()); + for (k, &(e, forward)) in chain.iter().enumerate() { + let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?; + let mut ends = [0u32; 2]; + for (end, v) in ends.iter_mut().zip(edge.vertices) { + let next = u32::try_from(vertices.len()).map_err(|_| fail("vertex budget"))?; + *end = *vertex_of.entry(v).or_insert(next); + if *end == next { + vertices.push(record.vertices.get(v as usize).ok_or_else(|| fail("vertex reference"))?.point); + } + } + let given = match pcurves { + Pcurves::Projected(p) => Some(p.pcurve(edge.parameters(), edge.interval).ok_or_else(|| { + KernelError::Invalid( + "not supported yet: a fitted patch on a circular, elliptic or traced edge (it has no exact pcurve on the fit)".into(), + ) + })?), + Pcurves::Computed => None, + }; + edges.push(PartEdge { curve: edge.curve.clone(), nurbs: edge.nurbs.clone(), interval: edge.interval, vertices: ends }); + uses.push(PartUse { edge: k as u32, forward, given }); + } + if !ccw { + uses = uses.into_iter().rev().map(|u| PartUse { forward: !u.forward, ..u }).collect(); + } + let mut made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: tol }, false)?; + hold_gap(&mut made.brep, tol); + let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::smlib("patch: SMLib", e))?; + let (patch, order) = crate::native::body_from_smlib_ordered(&smlib)?; + // The patch's edges in its own order, each from the loop edge it is. + let Some(order) = order else { return Ok(patch) }; + let mut origins: Vec> = vec![None; patch.edge_count()]; + for (k, c) in made.edges.iter().enumerate() { + let (Some(c), Some(&(e, _))) = (c, chain.get(k)) else { continue }; + let j = if order.edges.is_empty() { *c } else { *order.edges.get(*c).ok_or_else(|| fail("edge order"))? }; + *origins.get_mut(j).ok_or_else(|| fail("edge order"))? = Some(e); + } + let Some(origins) = origins.into_iter().collect::>>() else { return Ok(patch) }; + let history = History { + operands: 1, + faces: vec![FaceProv { origins: Vec::new(), change: Change::Generated }], + edges: origins.into_iter().map(|edge| EdgeProv { faces: vec![0], origins: vec![EdgeOrigin::Edge { operand: 0, edge }] }).collect(), + }; + patch.with_history(history, &[body]) +} + +/// The sheet of the general fill's patches on the loop `chain` of the record's edges: each edge +/// whole, or (a loop of five or more) its two halves at the middle of its interval, both on its +/// exact curve record; the spokes from the halves' common vertex to the centre; every pcurve the +/// straight line in (u, v) the patch gives its side. Its history is over `[body]`: every face is +/// new, each loop edge (or half) a piece of the body's own, each spoke new. +fn quilt_body(body: &Body, record: &b::Brep, chain: &[Piece], fill: &IsoFill, tol: f64) -> Result { + use solidcraft_geom::fill_iso::{IsoSide, SpokeEnd}; + let fail = |m: &str| KernelError::Failed(format!("patch: {m}")); + let index = |n: usize| u32::try_from(n).map_err(|_| fail("budget")); + let mut vertices: Vec<[f64; 3]> = Vec::new(); + let mut vertex_of: std::collections::HashMap = std::collections::HashMap::new(); + let mut middle_of: std::collections::HashMap<(usize, u64), u32> = std::collections::HashMap::new(); + let mut edges: Vec = Vec::new(); + // Each part edge's origin: the record edge it is a piece of (`None` for a spoke). + let mut origin: Vec> = Vec::new(); + let mut piece_of: std::collections::HashMap<(usize, u64, u64), u32> = std::collections::HashMap::new(); + let mut spoke_of: std::collections::HashMap = std::collections::HashMap::new(); + // The fill's vertices inside the loop first. + for c in &fill.inner { + vertices.push([c.x, c.y, c.z]); + } + let mut faces = Vec::with_capacity(fill.patches.len()); + for patch in &fill.patches { + let mut uses = Vec::with_capacity(patch.sides.len()); + for side in &patch.sides { + let line = |interval: [f64; 2], at: [[f64; 2]; 2]| Curve2::Spline { + knots: vec![interval[0], interval[0], interval[1], interval[1]], + points: at.to_vec(), + }; + match *side { + IsoSide::Edge { edge: k, from, to, uv } => { + let &Piece { edge: e, forward, interval: [plo, phi] } = chain.get(k).ok_or_else(|| fail("side"))?; + let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?; + let [a, z] = edge.interval; + // The patch's parameter runs the loop's way: the edge's own, reflected where the + // loop runs against it; a side's ends are its piece's ends or middle, exactly. + let tau = |t: f64| on_record(a, z, [plo, phi], forward, t); + let (tf, tt) = (tau(from), tau(to)); + let (lo, hi, along) = if tf < tt { (tf, tt, true) } else { (tt, tf, false) }; + let key = (e, lo.to_bits(), hi.to_bits()); + let id = match piece_of.get(&key) { + Some(id) => *id, + None => { + let ends = [ + vertex_on(record, &mut vertices, &mut vertex_of, &mut middle_of, e, lo)?, + vertex_on(record, &mut vertices, &mut vertex_of, &mut middle_of, e, hi)?, + ]; + let id = index(edges.len())?; + // The edge itself: the interval and the pcurve's parameter are on its + // NURBS form (a conic's), which it keeps. + edges.push(PartEdge { curve: edge.curve.clone(), nurbs: edge.nurbs.clone(), interval: [lo, hi], vertices: ends }); + origin.push(Some(e)); + piece_of.insert(key, id); + id + } + }; + let at = if along { uv } else { [uv[1], uv[0]] }; + uses.push(PartUse { edge: id, forward: along, given: Some(line([lo, hi], at)) }); + } + IsoSide::Spoke { spoke, forward, uv } => { + let id = match spoke_of.get(&spoke) { + Some(id) => *id, + None => { + let curve = fill.spokes.get(spoke).ok_or_else(|| fail("spoke"))?; + // Its ends: on the loop, in the record edge's parameter as the sides' + // pieces are (the same bits where a side's piece ends there), or inside. + let ends = fill.ends.get(spoke).ok_or_else(|| fail("spoke"))?; + let mut at = [0u32; 2]; + for (slot, end) in at.iter_mut().zip(ends) { + *slot = match *end { + SpokeEnd::Inner(i) if i < fill.inner.len() => index(i)?, + SpokeEnd::Inner(_) => return Err(fail("spoke end")), + SpokeEnd::Loop { edge: k, t } => { + let &Piece { edge: e, forward, interval: [plo, phi] } = chain.get(k).ok_or_else(|| fail("spoke"))?; + let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?; + let [a, z] = edge.interval; + vertex_on(record, &mut vertices, &mut vertex_of, &mut middle_of, e, on_record(a, z, [plo, phi], forward, t))? + } + }; + } + let [start, end] = at; + let id = index(edges.len())?; + let spline = match &curve.weights { + Some(w) => b::Curve::RationalSpline { + knots: curve.knots.clone(), + homogeneous: curve.points.iter().zip(w).map(|(p, w)| [p.x * w, p.y * w, p.z * w, *w]).collect(), + }, + None => { + b::Curve::Spline { knots: curve.knots.clone(), points: curve.points.iter().map(|p| [p.x, p.y, p.z]).collect() } + } + }; + edges.push(PartEdge { curve: spline, nurbs: None, interval: [0.0, 1.0], vertices: [start, end] }); + origin.push(None); + spoke_of.insert(spoke, id); + id + } + }; + let at = if forward { uv } else { [uv[1], uv[0]] }; + uses.push(PartUse { edge: id, forward, given: Some(line([0.0, 1.0], at)) }); + } + } + } + faces.push(PartFace { surface: crate::surfaces::spline_surface(&patch.surface), forward: true, loops: vec![uses] }); + } + let mut made = assemble(Parts { vertices, edges, faces, tolerance: tol }, false)?; + hold_gap(&mut made.brep, tol); + let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::smlib("patch: SMLib", e))?; + let (sheet, order) = crate::native::body_from_smlib_ordered(&smlib)?; + let Some(order) = order else { return Ok(sheet) }; + let place = |list: &[usize], c: usize| if list.is_empty() { Some(c) } else { list.get(c).copied() }; + // Each body edge's origin and the body faces beside it. + let mut prov: Vec> = vec![None; sheet.edge_count()]; + let record_out = &made.brep; + for (pe, c) in made.edges.iter().enumerate() { + let Some(c) = *c else { continue }; + let j = place(&order.edges, c).ok_or_else(|| fail("edge order"))?; + let mut beside: Vec = + record_out.edges.get(c).map(|x| x.uses.iter().filter_map(|u| place(&order.faces, u.face as usize)).collect()).unwrap_or_default(); + beside.sort_unstable(); + beside.dedup(); + let origins = origin.get(pe).copied().flatten().map(|edge| vec![EdgeOrigin::Edge { operand: 0, edge }]).unwrap_or_default(); + *prov.get_mut(j).ok_or_else(|| fail("edge order"))? = Some(EdgeProv { faces: beside, origins }); + } + let Some(edges) = prov.into_iter().collect::>>() else { return Ok(sheet) }; + let history = History { operands: 1, faces: vec![FaceProv { origins: Vec::new(), change: Change::Generated }; sheet.face_count()], edges }; + sheet.with_history(history, &[body]) +} + +/// A patch record's edges and vertices given the tolerances that hold a surface `gap` from them. +/// A record's tolerance is SMLib's intersection tolerance, twice the zone tolerance SMLib holds an +/// edge's gap to its faces to, and a vertex holds gaps up to half its zone tolerance (SMLib's +/// `SM_XSECT_TO_ZONETOL3D`, `SmBrep::ValidateAndUpdateTolerances`): an edge takes `2·gap`, a +/// vertex `4·gap`. +fn hold_gap(brep: &mut b::Brep, gap: f64) { + for e in &mut brep.edges { + e.tolerance = e.tolerance.max(2.0 * gap); + } + for v in &mut brep.vertices { + v.tolerance = v.tolerance.max(4.0 * gap); + } +} + +/// The part vertex at parameter `t` of record edge `e`: the record's own vertex at an end of the +/// edge's interval (made once), else [`middle`]. +fn vertex_on( + record: &b::Brep, + vertices: &mut Vec<[f64; 3]>, + vertex_of: &mut std::collections::HashMap, + middle_of: &mut std::collections::HashMap<(usize, u64), u32>, + e: usize, + t: f64, +) -> Result { + let fail = |m: &str| KernelError::Failed(format!("patch: {m}")); + let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?; + let [a, z] = edge.interval; + if t != a && t != z { + return middle(vertices, middle_of, e, edge, t); + } + let [start, finish] = edge.vertices; + let v = if t == a { start } else { finish }; + let next = u32::try_from(vertices.len()).map_err(|_| fail("vertex budget"))?; + let id = *vertex_of.entry(v).or_insert(next); + if id == next { + vertices.push(record.vertices.get(v as usize).ok_or_else(|| fail("vertex reference"))?.point); + } + Ok(id) +} + +/// The vertex at parameter `t` inside record edge `e` (`edge`), made once. +fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap<(usize, u64), u32>, e: usize, edge: &b::Edge, t: f64) -> Result { + let k = (e, t.to_bits()); + if let Some(v) = made.get(&k) { + return Ok(*v); + } + let p = + CurveEval::new(edge.parameters()).ok().and_then(|c| c.point(t)).ok_or_else(|| KernelError::Failed("patch: an edge has no middle".into()))?; + let v = u32::try_from(vertices.len()).map_err(|_| KernelError::Failed("patch: vertex budget".into()))?; + vertices.push([p.x, p.y, p.z]); + made.insert(k, v); + Ok(v) } /// How far a loop's edges may be from a plane for its patch to be that plane: `10⁻⁷` of the @@ -332,34 +1003,50 @@ pub fn patch_edges_crowned(body: &Body, at: &[Vec3], crown: f64) -> Result /// tolerance, since a planar face is exact and other operations treat it as containing its /// edges to that tolerance. A fitted face gets [`face_tolerance`], ten times looser. pub(crate) fn planarity_tolerance(body: &Body) -> f64 { - (body.size() * 1e-7).max(solidcraft_geom::LINEAR_TOL) + (placed_size(body) * 1e-7).max(solidcraft_geom::LINEAR_TOL) } -/// How far the fill's surface may be from the loop's edges: `10⁻⁶` of the body's size, at least -/// `10⁻⁵` mm — ten times [`planarity_tolerance`]. Truck meshes a face from its edges' own -/// polylines (shared with the neighbouring faces), so the mesh stays watertight whatever the -/// gap: measured on a five-sided rim, fills whose edges were up to `4.5·10⁻⁴` mm off the surface -/// meshed cleanly and stitched back into closed solids. Ten times the linear tolerance because a +/// The body's size as the fill tolerances take it, the same wherever the body is and however it +/// is turned (the bounding box's diagonal is not: a cup turned 0.7 rad about (1, 2, 3) grows from +/// 54.7 to 61.6, and its fill was sampled to another tolerance): the diameter of the smallest ball +/// holding its vertices. (Twice the farthest vertex's distance from their centroid is not the +/// body's size where the vertices crowd one end: up to twice its diameter, and a rounded box's G2 +/// corner patch, its vertices crowding that corner, then fitted past the box.) A body with no +/// vertices takes its box's diagonal. +fn placed_size(body: &Body) -> f64 { + let vertices: Vec = body.record().vertices.iter().map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])).collect(); + solidcraft_geom::Ball::enclosing(&vertices).map_or_else(|| body.size(), |ball| ball.diameter()) +} + +/// How far the fill's surface may be from the loop's edges: `10⁻⁶` of the body's size +/// ([`placed_size`]), at least +/// `10⁻⁵` mm — ten times [`planarity_tolerance`]. Ten times the linear tolerance because a /// fitted surface approaches curved edges like a cubic spline, so each further factor of ten /// costs about twice the spans each way, and imported edges may already lie `10⁻⁵` mm or more off -/// their vertices; two orders below what meshing tolerates. Later operations must take the face -/// to contain its edges within this tolerance, not the linear one: the face's edges are the -/// body's exact edges, the surface between them is the fit. +/// their vertices. Later operations must take the face to contain its edges within this +/// tolerance, not the linear one: the face's edges are the body's exact edges, the surface +/// between them is the fit (the patch record's edges and vertices hold this gap: [`hold_gap`]). pub(crate) fn face_tolerance(body: &Body) -> f64 { - (body.size() * 1e-6).max(1e-5) + (placed_size(body) * 1e-6).max(1e-5) } #[cfg(test)] mod tests { - use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface}; - use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; - use truck_modeling as mt; + use solidcore_record::brep::{self as b}; + use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; + use solidcraft_geom::brep::{eval::CurveEval, eval::SurfaceEval}; + use solidcraft_geom::prelude::*; - use crate::body::{Body, from_p3, p3}; + use crate::body::Body; use crate::boolean_record::tests::{Reach, checked}; use crate::history::{Change, EdgeOrigin}; + use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble}; use crate::{BoolOp, boolean, copy_faces, cylinder, extrude, measure, patch_edges, patch_edges_crowned, stitch}; + fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) + } + /// The cutting cylinder: axis along y at x = 0, z = 50, radius 40, so the top of a prism /// within 20 of the axis and 20 high is cut away everywhere (to between 10 and 15.4 mm). fn cut_height(x: f64) -> f64 { @@ -390,55 +1077,66 @@ mod tests { (0..n).map(|k| Vec2::from_angle(phase + k as f64 * std::f64::consts::TAU / n as f64) * 20.0).collect() } - /// The distance from `p` to the surface: the nearest of a grid of samples, then Gauss–Newton - /// within the domain. - fn to_surface(s: &mt::Surface, p: mt::Point3) -> f64 { - let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { panic!("a bounded surface") }; - let n = 80; - let mut best = (f64::MAX, u0, v0); - for i in 0..=n { - for j in 0..=n { - let (u, v) = (u0 + (u1 - u0) * i as f64 / n as f64, v0 + (v1 - v0) * j as f64 / n as f64); - let d = s.subs(u, v).distance(p); - if d < best.0 { - best = (d, u, v); - } - } - } - let (_, mut u, mut v) = best; - for _ in 0..50 { - let (q, a, b) = (s.subs(u, v), s.uder(u, v), s.vder(u, v)); - let r = q - p; - let (aa, ab, bb) = (a.dot(a), a.dot(b), b.dot(b)); - let det = aa * bb - ab * ab; - if det.abs() < 1e-300 { - break; - } - let (ga, gb) = (a.dot(r), b.dot(r)); - u = (u - (bb * ga - ab * gb) / det).clamp(u0, u1); - v = (v - (aa * gb - ab * ga) / det).clamp(v0, v1); - } - s.subs(u, v).distance(p) + /// The body's record. + fn record(body: &Body) -> b::Brep { + crate::native::brep_record(body).unwrap() } - /// The farthest point along the face's edges from its surface. - fn edges_off_surface(face: &mt::Face) -> f64 { - let s = face.surface(); + /// The surface of the body's first face. + fn first_surface(body: &Body) -> b::Surface { + record(body).faces[0].surface.clone() + } + + /// The distance from `p` to the surface (its nearest point). + fn to_surface(s: &b::Surface, p: Vec3) -> f64 { + let e = SurfaceEval::new(s).unwrap(); + let uv = e.project(p, None, f64::INFINITY).expect("a nearest point"); + e.point(uv).unwrap().dist(p) + } + + /// The farthest point along the first face's edges from its surface. + fn edges_off_surface(body: &Body) -> f64 { + let r = record(body); + let face = &r.faces[0]; let mut worst = 0.0f64; - for e in face.boundaries().iter().flat_map(|w| w.edge_iter()) { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..=24 { - worst = worst.max(to_surface(&s, c.subs(t0 + (t1 - t0) * k as f64 / 24.0))); + for l in &face.loops { + let b::Loop::Edges { edges } = l else { continue }; + for u in edges { + let e = &r.edges[u.edge as usize]; + let c = CurveEval::new(e.parameters()).unwrap(); + let [t0, t1] = e.interval; + for k in 0..=24 { + worst = worst.max(to_surface(&face.surface, c.point(t0 + (t1 - t0) * k as f64 / 24.0).unwrap())); + } } } worst } + /// Whether every edge of `made` is one of `of`'s own: the same kind of curve, on the same + /// interval, on the curve it is parameterised on (its NURBS form where it has one) to + /// rounding: the same knots and control points within 10⁻¹² of their size. (SMLib makes a + /// conic's frame and NURBS form again on a round trip, the last bit of a coordinate apart.) + fn own_edges(made: &Body, of: &Body) -> bool { + let own = record(of).edges; + let kind = |e: &b::Edge| std::mem::discriminant(&e.curve); + let close = |p: &[f64], q: &[f64]| p.len() == q.len() && p.iter().zip(q).all(|(x, y)| (x - y).abs() <= 1e-12 * (1.0 + x.abs().max(y.abs()))); + let same = |c: &b::Curve, d: &b::Curve| match (c, d) { + (b::Curve::Spline { knots: k, points: p }, b::Curve::Spline { knots: l, points: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + (b::Curve::RationalSpline { knots: k, homogeneous: p }, b::Curve::RationalSpline { knots: l, homogeneous: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + _ => c == d, + }; + record(made).edges.iter().all(|e| own.iter().any(|o| kind(o) == kind(e) && same(o.parameters(), e.parameters()) && o.interval == e.interval)) + } + /// The fill's mesh: every normal finite, and no triangle folded over (all face the same way /// as the mesh's total area vector, by a clear margin). fn mesh_is_clean(fill: &Body) -> f64 { - let m = fill.tessellate(0.01).unwrap(); + let m = fill.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!(!m.triangles.is_empty()); assert!(m.normals.iter().all(|n| n.is_finite() && n.len() > 0.5), "a mesh normal is not finite"); let tri = |t: &[u32; 3]| m.tri(t).unwrap(); @@ -463,15 +1161,13 @@ mod tests { let fill = patch_edges(open, rim).unwrap(); assert!(fill.is_surface()); assert_eq!(fill.face_count(), 1, "one face"); - let face = fill.solid.face_iter().next().unwrap().clone(); - assert!(!matches!(face.surface(), mt::Surface::Plane(_))); - // Its edges are the open body's own, by identity, and nothing else. - let own: Vec = open.solid.edge_iter().map(|e| e.id()).collect(); - assert!(fill.solid.edge_iter().all(|e| own.contains(&e.id())), "an edge that is not the body's"); + assert!(!matches!(first_surface(&fill), b::Surface::Plane { .. })); + // Its edges are the open body's own, and nothing else. + assert!(own_edges(&fill, open), "an edge that is not the body's"); let h = checked(&fill, &[open], 0.05, Reach { made: 0.0, moved: 0.0 }, &|_| true); assert!(h.faces.iter().all(|f| f.change == Change::Generated && f.origins.is_empty())); assert!(h.edges.iter().all(|e| matches!(e.origins.as_slice(), [EdgeOrigin::Edge { operand: 0, .. }]))); - let off = edges_off_surface(&face); + let off = edges_off_surface(&fill); let tol = super::face_tolerance(open); assert!(off <= tol, "an edge is {off} off the face (tolerance {tol})"); mesh_is_clean(&fill); @@ -481,12 +1177,15 @@ mod tests { } /// The fill's height over the point `(x, y)`: Newton's method on the surface's `x`, `y` from - /// the nearest of a grid of samples. - fn height_over(s: &mt::Surface, x: f64, y: f64, start: &mut Option<(f64, f64)>) -> Option { - let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { return None }; + /// the middle of its face's domain (or the last answer). + fn height_over(body: &Body, x: f64, y: f64, start: &mut Option<(f64, f64)>) -> Option { + let r = record(body); + let face = &r.faces[0]; + let s = SurfaceEval::new(face.parameters()).ok()?; + let [[u0, u1], [v0, v1]] = face.domain; let (mut u, mut v) = start.unwrap_or(((u0 + u1) / 2.0, (v0 + v1) / 2.0)); for _ in 0..30 { - let (q, a, b) = (s.subs(u, v), s.uder(u, v), s.vder(u, v)); + let (q, a, b) = s.derivs(u, v)?; let (rx, ry) = (q.x - x, q.y - y); let det = a.x * b.y - a.y * b.x; if det.abs() < 1e-300 { @@ -495,7 +1194,7 @@ mod tests { u = (u - (b.y * rx - b.x * ry) / det).clamp(u0, u1); v = (v - (a.x * ry - a.y * rx) / det).clamp(v0, v1); } - let q = s.subs(u, v); + let q = s.point([u, v])?; *start = Some((u, v)); ((q.x - x).hypot(q.y - y) < 1e-9).then_some(q.z) } @@ -504,7 +1203,6 @@ mod tests { /// cylinder integrated over the polygon (midpoint rule on a 300 × 300 grid; the integrand /// vanishes on the rim, so cells across it add little error). fn gained(fill: &Body, corners: &[Vec2]) -> f64 { - let s = fill.solid.face_iter().next().unwrap().surface(); let polygon = solidcraft_geom::Ring::from(corners.to_vec()); let solidcraft_geom::Aabb2 { min: lo, max: hi } = polygon.bounds(); let n = 300; @@ -517,7 +1215,7 @@ mod tests { for j in 0..n { let y = lo.y + (j as f64 + 0.5) * dy; if inside(x, y) { - let h = height_over(&s, x, y, &mut start).expect("the fill covers the polygon"); + let h = height_over(fill, x, y, &mut start).expect("the fill covers the polygon"); sum += (h - cut_height(x)) * dx * dy; } } @@ -538,6 +1236,79 @@ mod tests { assert!((got - want).abs() <= bound, "{name}: {got} vs {want}"); } + /// An open sheet of walls hanging from the closed loop `top` (each a curve record from one + /// corner to the next, `corners[k]` to `corners[k + 1]`), each wall swept straight along + /// `drop`: a plane under a line, a ruled B-spline under a spline (its pcurves its exact iso + /// lines and rulings). + fn walls(corners: &[Vec3], top: &[b::Curve], drop: Vec3) -> Body { + let n = corners.len(); + let arr = |p: Vec3| [p.x, p.y, p.z]; + // Vertices: the top corners, then the bottom ones. + let vertices: Vec<[f64; 3]> = corners.iter().map(|p| arr(*p)).chain(corners.iter().map(|p| arr(*p + drop))).collect(); + let moved = |c: &b::Curve| match c { + b::Curve::Line { start, end } => b::Curve::Line { start: arr(v3(*start) + drop), end: arr(v3(*end) + drop) }, + b::Curve::Spline { knots, points } => { + b::Curve::Spline { knots: knots.clone(), points: points.iter().map(|p| arr(v3(*p) + drop)).collect() } + } + _ => panic!("lines and splines"), + }; + let interval = |c: &b::Curve| match c { + b::Curve::Spline { knots, points } => [knots[knots.len() - points.len() - 1], knots[points.len()]], + _ => [0.0, 1.0], + }; + let mut edges = Vec::new(); + for k in 0..n { + let c = &top[k]; + edges.push(PartEdge { nurbs: None, curve: c.clone(), interval: interval(c), vertices: [k as u32, ((k + 1) % n) as u32] }); + edges.push(PartEdge { nurbs: None, curve: moved(c), interval: interval(c), vertices: [(n + k) as u32, (n + (k + 1) % n) as u32] }); + edges.push(PartEdge { + nurbs: None, + curve: b::Curve::Line { start: arr(corners[k]), end: arr(corners[k] + drop) }, + interval: [0.0, 1.0], + vertices: [k as u32, (n + k) as u32], + }); + } + let (top_edge, bottom_edge, down) = (|k: usize| 3 * k as u32, |k: usize| 3 * k as u32 + 1, |k: usize| 3 * (k % n) as u32 + 2); + let mut faces = Vec::new(); + for k in 0..n { + let (surface, given) = match &top[k] { + b::Curve::Spline { knots, points } => { + let rows: Vec> = points.iter().map(|p| vec![*p, arr(v3(*p) + drop)]).collect(); + let [a, z] = interval(&top[k]); + let degree = knots.len() - points.len() - 1; + let greville = |v: f64| -> b::Curve2 { + let pts = (0..points.len()).map(|i| [(1..=degree).map(|r| knots[i + r]).sum::() / degree as f64, v]).collect(); + b::Curve2::Spline { knots: knots.clone(), points: pts } + }; + let ruling = |u: f64| b::Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![[u, 0.0], [u, 1.0]] }; + let surface = b::Surface::Spline { u_knots: knots.clone(), v_knots: vec![0.0, 0.0, 1.0, 1.0], points: rows }; + (surface, Some([greville(0.0), ruling(z), greville(1.0), ruling(a)])) + } + _ => { + let (p, q) = (corners[k], corners[(k + 1) % n]); + let u = (q - p).normalized().unwrap(); + let w = (drop - u * drop.dot(u)).normalized().unwrap(); + (b::Surface::Plane { origin: arr(p), u_axis: arr(u), v_axis: arr(w) }, None) + } + }; + // Round the wall: along the top, down its far side, back along the bottom, up. + let mut uses = vec![ + PartUse { edge: top_edge(k), forward: true, given: None }, + PartUse { edge: down(k + 1), forward: true, given: None }, + PartUse { edge: bottom_edge(k), forward: false, given: None }, + PartUse { edge: down(k), forward: false, given: None }, + ]; + if let Some(given) = given { + for (u, g) in uses.iter_mut().zip(given) { + u.given = Some(g); + } + } + faces.push(PartFace { surface, forward: true, loops: vec![uses] }); + } + let made = assemble(Parts { vertices, edges, faces, tolerance: 1e-6 }, false).unwrap(); + crate::native::body_from_smlib(&solidcraft_smlib::Brep::from_record(&made.brep, true).unwrap()).unwrap() + } + #[test] fn regular_rims_of_three_to_eight_sides_fill_with_one_face_and_close_the_cup() { for n in 3..=8 { @@ -586,18 +1357,15 @@ mod tests { fn a_flat_corner_between_two_edges_is_kept() { // A rim of five straight edges, two of them in line (a 180° corner between them), the // four true corners at different heights; walls hang below it. - let p = |x: f64, y: f64, z: f64| mt::Vertex::new(mt::Point3::new(x, y, z)); + let p = |x: f64, y: f64, z: f64| Vec3::new(x, y, z); let v = [p(-14.0, -14.0, 12.0), p(0.0, -14.0, 12.0), p(14.0, -14.0, 12.0), p(14.0, 14.0, 15.0), p(-14.0, 14.0, 10.0)]; - let line = |a: &mt::Vertex, b: &mt::Vertex| mt::Edge::new(a, b, mt::Curve::Line(mt::Line(a.point(), b.point()))); - let wire: mt::Wire = (0..5).map(|k| line(&v[k], &v[(k + 1) % 5])).collect::>().into(); - let low = mt::builder::translated(&wire, mt::Vector3::new(0.0, 0.0, -10.0)); - let walls = mt::builder::try_wire_homotopy(&wire, &low).unwrap(); - let body = crate::surfaces::surface_body(walls.face_iter().cloned().collect()); - let rim: Vec = (0..5).map(|k| from_p3(v[k].point()).lerp(from_p3(v[(k + 1) % 5].point()), 0.5)).collect(); + let arr = |q: Vec3| [q.x, q.y, q.z]; + let top: Vec = (0..5).map(|k| b::Curve::Line { start: arr(v[k]), end: arr(v[(k + 1) % 5]) }).collect(); + let body = walls(&v, &top, Vec3::new(0.0, 0.0, -10.0)); + let rim: Vec = (0..5).map(|k| v[k].lerp(v[(k + 1) % 5], 0.5)).collect(); let fill = patch_edges(&body, &rim).unwrap(); assert_eq!((fill.face_count(), fill.edge_count()), (1, 5), "one face on all five edges"); - let face = fill.solid.face_iter().next().unwrap().clone(); - assert!(edges_off_surface(&face) <= super::face_tolerance(&body)); + assert!(edges_off_surface(&fill) <= super::face_tolerance(&body)); let area = mesh_is_clean(&fill); eprintln!("flat corner: one face of area {area}"); assert!(area > 28.0 * 28.0 * 0.99 && area < 28.0 * 28.0 * 1.05, "{area}"); @@ -611,12 +1379,13 @@ mod tests { shuffled.rotate_left(3); shuffled.swap(0, 1); let (b, _) = fill_rim(&open, &shuffled); - let (sa, sb) = (a.solid.face_iter().next().unwrap().surface(), b.solid.face_iter().next().unwrap().surface()); - let (Some((u0, u1)), Some((v0, v1))) = sa.try_range_tuple() else { panic!() }; + let (ra, rb) = (record(&a), record(&b)); + let (sa, sb) = (SurfaceEval::new(ra.faces[0].parameters()).unwrap(), SurfaceEval::new(rb.faces[0].parameters()).unwrap()); + let [[u0, u1], [v0, v1]] = ra.faces[0].domain; let mut gap = 0.0f64; for (x, y) in [(0.2, 0.3), (0.5, 0.5), (0.7, 0.9)] { - let (u, v) = (u0 + (u1 - u0) * x, v0 + (v1 - v0) * y); - gap = gap.max(sa.subs(u, v).distance(sb.subs(u, v))); + let uv = [u0 + (u1 - u0) * x, v0 + (v1 - v0) * y]; + gap = gap.max(sa.point(uv).unwrap().dist(sb.point(uv).unwrap())); } assert!(gap < 1e-7, "pick order moved the surface by {gap}"); let (area_a, area_b) = (mesh_is_clean(&a), mesh_is_clean(&b)); @@ -661,12 +1430,12 @@ mod tests { // The cup's vertices moved 2·10⁻⁵ mm off their curves, as a file might give them. let corners = regular(5, 0.3); let (solid, open, rim) = cup(&corners, Vec2::ZERO); - let shell = open.solid.boundaries()[0].mapped( - |p: &mt::Point3| *p + mt::Vector3::new(2e-5, 0.0, 0.0), - |c: &mt::Curve| c.clone(), - |s: &mt::Surface| s.clone(), - ); - let imported = crate::surfaces::surface_body(shell.face_iter().cloned().collect()); + let mut moved = record(&open); + for v in &mut moved.vertices { + v.point[0] += 2e-5; + v.tolerance = v.tolerance.max(1e-4); + } + let imported = crate::native::body_from_smlib(&solidcraft_smlib::Brep::from_record(&moved, true).unwrap()).unwrap(); let (fill, got) = fill_rim(&imported, &rim); check_volume("imported", &solid, &fill, &corners, got); } @@ -679,26 +1448,27 @@ mod tests { // a 32 × 32 grid, and then it is refused. for (spans, raised, must_fill) in [(1, 1, true), (64, 30, false)] { let count = spans + 3; - let pts: Vec = - (0..count).map(|i| mt::Point3::new(20.0 * i as f64 / (count - 1) as f64, 0.0, if i == raised { 1.5 } else { 0.0 })).collect(); - let spline = mt::BSplineCurve::new(mt::KnotVec::uniform_knot(3, spans), pts); - let v: Vec = - [(0.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)].iter().map(|&(x, y)| mt::Vertex::new(mt::Point3::new(x, y, 0.0))).collect(); - let line = |a: &mt::Vertex, b: &mt::Vertex| mt::Edge::new(a, b, mt::Curve::Line(mt::Line(a.point(), b.point()))); - let bottom = mt::Edge::new(&v[0], &v[1], mt::Curve::BSplineCurve(spline.clone())); - let wire: mt::Wire = vec![bottom, line(&v[1], &v[2]), line(&v[2], &v[3]), line(&v[3], &v[0])].into(); - let top = mt::builder::translated(&wire, mt::Vector3::new(0.0, 0.0, -5.0)); - let walls = mt::builder::try_wire_homotopy(&wire, &top).unwrap(); - let body = crate::surfaces::surface_body(walls.face_iter().cloned().collect()); - let peak = from_p3(spline.subs((raised as f64 + 1.0) / (count + 1) as f64)); - let rim = [from_p3(spline.subs(0.5)), Vec3::new(20.0, 5.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(0.0, 5.0, 0.0)]; + let points: Vec<[f64; 3]> = + (0..count).map(|i| [20.0 * i as f64 / (count - 1) as f64, 0.0, if i == raised { 1.5 } else { 0.0 }]).collect(); + // Uniform knots over [0, 1], clamped. + let mut knots = vec![0.0; 4]; + knots.extend((1..spans).map(|i| i as f64 / spans as f64)); + knots.extend([1.0; 4]); + let spline = b::Curve::Spline { knots, points }; + let c = CurveEval::new(&spline).unwrap(); + let corners: Vec = [(0.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)].iter().map(|&(x, y)| Vec3::new(x, y, 0.0)).collect(); + let line = |a: Vec3, z: Vec3| b::Curve::Line { start: [a.x, a.y, a.z], end: [z.x, z.y, z.z] }; + let top = vec![spline.clone(), line(corners[1], corners[2]), line(corners[2], corners[3]), line(corners[3], corners[0])]; + let body = walls(&corners, &top, Vec3::new(0.0, 0.0, -5.0)); + let peak = c.point((raised as f64 + 1.0) / (count + 1) as f64).unwrap(); + let rim = [c.point(0.5).unwrap(), Vec3::new(20.0, 5.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(0.0, 5.0, 0.0)]; match patch_edges(&body, &rim) { Ok(fill) => { - let face = fill.solid.face_iter().next().unwrap().clone(); - assert!(!matches!(face.surface(), mt::Surface::Plane(_)), "a plane would miss the bulge"); - let (off, tol) = (edges_off_surface(&face), super::face_tolerance(&body)); + let surface = first_surface(&fill); + assert!(!matches!(surface, b::Surface::Plane { .. }), "a plane would miss the bulge"); + let (off, tol) = (edges_off_surface(&fill), super::face_tolerance(&body)); eprintln!("{spans}-span bump: filled, edges within {off:e} of the face"); - assert!(off <= tol && to_surface(&face.surface(), p3(peak)) <= tol); + assert!(off <= tol && to_surface(&surface, peak) <= tol); mesh_is_clean(&fill); } Err(e) => { @@ -711,18 +1481,13 @@ mod tests { /// A point on each edge that bounds one face of `body` (its free edges). fn free_edge_points(body: &Body) -> Vec { - let mut uses: std::collections::HashMap = std::collections::HashMap::new(); - for f in body.solid.face_iter() { - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - uses.entry(e.id()).or_insert((0, e.clone())).0 += 1; - } - } - uses.values() - .filter(|(n, _)| *n == 1) - .map(|(_, e)| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - from_p3(c.subs(0.5 * (t0 + t1))) + let r = record(body); + r.edges + .iter() + .filter(|e| e.uses.len() == 1) + .map(|e| { + let [t0, t1] = e.interval; + CurveEval::new(e.parameters()).unwrap().point(0.5 * (t0 + t1)).unwrap() }) .collect() } @@ -742,8 +1507,7 @@ mod tests { let rim = free_edge_points(&side); let fill = patch_edges(&side, &rim).unwrap(); assert_eq!(fill.face_count(), 1, "one face"); - let face = fill.solid.face_iter().next().unwrap().clone(); - let (off, tol) = (edges_off_surface(&face), super::face_tolerance(&side)); + let (off, tol) = (edges_off_surface(&fill), super::face_tolerance(&side)); assert!(off <= tol, "an edge is {off} off the face (tolerance {tol})"); // Its area is at least its shadow on the plane x = 0 (the 20 × 20 square the loop bounds // there) and, a least-bending fill, no more than the half side it spans. @@ -776,7 +1540,7 @@ mod tests { let lid = patch_edges(&open, &rim).unwrap(); assert_eq!(lid.face_count(), 1); let edges = lid.edge_count(); - assert!(matches!(lid.solid.face_iter().next().unwrap().surface(), mt::Surface::Plane(_)), "tilt {tilt:?}"); + assert!(matches!(first_surface(&lid), b::Surface::Plane { .. }), "tilt {tilt:?}"); let closed = stitch(&[&open, &lid], 0.0).unwrap(); assert!(!closed.is_surface()); let (want, got) = (measure(&solid).unwrap().volume, measure(&closed).unwrap().volume); @@ -796,7 +1560,7 @@ mod tests { let rim = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; let lid = patch_edges(&open, &rim).unwrap(); assert_eq!(lid.face_count(), 1); - assert!(matches!(lid.solid.face_iter().next().unwrap().surface(), mt::Surface::Plane(_))); + assert!(matches!(first_surface(&lid), b::Surface::Plane { .. })); let closed = stitch(&[&open, &lid], 0.0).unwrap(); assert!((measure(&closed).unwrap().volume - 1000.0).abs() < 1e-9); } @@ -824,21 +1588,26 @@ mod tests { for crown in [0.25, -0.25] { let full = patch_edges_crowned(&open, &rim, crown).unwrap(); assert_eq!(full.face_count(), 1, "one face"); - let face = full.solid.face_iter().next().unwrap().clone(); - assert!(!matches!(face.surface(), mt::Surface::Plane(_))); - let own: Vec = open.solid.edge_iter().map(|e| e.id()).collect(); - assert!(full.solid.edge_iter().all(|e| own.contains(&e.id())), "an edge that is not the body's"); + assert!(!matches!(first_surface(&full), b::Surface::Plane { .. })); + assert!(own_edges(&full, &open), "an edge that is not the body's"); // The loop's edges are within the fill's tolerance of the face, as for the plain fill. - let off = edges_off_surface(&face); + let off = edges_off_surface(&full); assert!(off <= super::face_tolerance(&open), "an edge is {off} off the crowned face"); mesh_is_clean(&full); - // The middle of the loop's box moved by crown × its diagonal (the bump is 1 there). - let a = plain.solid.face_iter().next().unwrap().surface(); - let b = face.surface(); - let (Some((bu0, bu1)), Some((bv0, bv1))) = a.try_range_tuple() else { panic!("a bounded surface") }; + // The middle of the fill's box moved by crown × its diagonal (the bump is 1 there). + let (ra, rb) = (record(&plain), record(&full)); + let (a, b) = (SurfaceEval::new(ra.faces[0].parameters()).unwrap(), SurfaceEval::new(rb.faces[0].parameters()).unwrap()); + // The height field's box is its surface's whole domain (the loop's box and 1% more + // each way, where the bubble is nought), not the face's: SMLib holds a face's domain + // as its loop's extent, 2% less across. + let (b::Surface::Spline { u_knots, v_knots, .. } | b::Surface::RationalSpline { u_knots, v_knots, .. }) = ra.faces[0].parameters() else { + panic!("a height field is a spline") + }; + let ends = |k: &[f64]| [k[0], k[k.len() - 1]]; + let ([bu0, bu1], [bv0, bv1]) = (ends(u_knots), ends(v_knots)); let (uc, vc) = ((bu0 + bu1) / 2.0, (bv0 + bv1) / 2.0); let size = (bu1 - bu0).hypot(bv1 - bv0); - let bump = a.subs(uc, vc).distance(b.subs(uc, vc)); + let bump = a.point([uc, vc]).unwrap().dist(b.point([uc, vc]).unwrap()); let want = (crown * size).abs(); eprintln!("crown {crown}: the middle moved {bump:.6}, wanted {want:.6}"); assert!((bump - want).abs() < 1e-6 * size, "middle {bump} against {want}"); @@ -852,10 +1621,11 @@ mod tests { .unwrap(); let rim = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; let lid = patch_edges_crowned(&open, &rim, 1.0).unwrap(); - assert!(matches!(lid.solid.face_iter().next().unwrap().surface(), mt::Surface::Plane(_)), "a planar loop is a plane"); + assert!(matches!(first_surface(&lid), b::Surface::Plane { .. }), "a planar loop is a plane"); // Hostile crowns are refused before anything is built. for crown in [f64::NAN, f64::INFINITY, 3.01, -0.91, 1e300] { - assert!(patch_edges_crowned(&open, &rim, crown).is_err(), "crown {crown}"); + let e = patch_edges_crowned(&open, &rim, crown).unwrap_err(); + assert!(e.to_string().contains("crown must be between -0.9 and 3"), "crown {crown}: {e}"); } } } diff --git a/crates/kernel/src/fill_general_tests.rs b/crates/kernel/src/fill_general_tests.rs index 3ac620ca3..a7716e729 100644 --- a/crates/kernel/src/fill_general_tests.rs +++ b/crates/kernel/src/fill_general_tests.rs @@ -3,64 +3,121 @@ //! against the analytic surface the loop was cut from, or against a quadrature of the fitted //! surface itself, never against the mesher alone. -use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface, ParametricSurface3D}; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; -use truck_modeling as mt; +use solidcore_record::brep::{self as b}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcraft_geom::brep::{eval::CurveEval, eval::SurfaceEval}; +use solidcraft_geom::prelude::*; use super::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, face_tolerance, patch_edges_report}; -use crate::body::{Body, from_p3, p3}; +use crate::body::Body; use crate::bridge::Continuity; -use crate::{BoolOp, boolean, box_solid, copy_faces, cylinder, extrude, measure, patch_edges, stitch, torus}; +use crate::{BoolOp, boolean, box_solid, copy_faces, cylinder, extrude, measure, patch_edges, stitch}; -/// The surface's parameters nearest `p`: the nearest of a grid of samples (or `hint`), then -/// Gauss–Newton within the domain. -fn nearest(s: &mt::Surface, p: Vec3, hint: Option<(f64, f64)>) -> (f64, f64) { - let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { panic!("a bounded surface") }; - let p = p3(p); - let (mut u, mut v) = match hint { - Some(h) => h, - None => { - let n = 100; - let mut best = (f64::MAX, u0, v0); - for i in 0..=n { - for j in 0..=n { - let (u, v) = (u0 + (u1 - u0) * i as f64 / n as f64, v0 + (v1 - v0) * j as f64 / n as f64); - let d = (s.subs(u, v) - p).magnitude(); - if d < best.0 { - best = (d, u, v); +/// A body's faces as surfaces over their parameter boxes, with the (u, v) polygon of each face's +/// loops (its exact pcurves, sampled). +struct Faces { + faces: Vec<(SurfaceEval, [[f64; 2]; 2], Vec>)>, +} + +impl Faces { + fn of(body: &Body) -> Faces { + let r = body.record(); + let faces = r + .faces + .iter() + .map(|f| { + let polys = f + .loops + .iter() + .filter_map(|l| match l { + b::Loop::Edges { edges } => Some( + edges + .iter() + .flat_map(|u| { + let [t0, t1] = r.edges[u.edge as usize].interval; + (0..64).map(move |k| { + let x = k as f64 / 64.0; + solidcraft_geom::brep::pcurve::eval( + &u.pcurve, + if u.forward { t0 + (t1 - t0) * x } else { t1 - (t1 - t0) * x }, + ) + .unwrap() + }) + }) + .collect(), + ), + b::Loop::Vertex { .. } => None, + }) + .collect(); + (SurfaceEval::new(f.parameters()).unwrap(), f.domain, polys) + }) + .collect(); + Faces { faces } + } + + /// The face, parameters and point of the fill nearest `p`. + fn nearest(&self, p: Vec3) -> (usize, [f64; 2], Vec3) { + let mut best: Option<(f64, usize, [f64; 2], Vec3)> = None; + for (k, (s, dom, _)) in self.faces.iter().enumerate() { + let [[u0, u1], [v0, v1]] = *dom; + let Some(uv) = s.project(p, None, f64::INFINITY) else { continue }; + let uv = [uv[0].clamp(u0, u1), uv[1].clamp(v0, v1)]; + let q = s.point(uv).unwrap(); + if best.is_none_or(|(d, ..)| q.dist(p) < d) { + best = Some((q.dist(p), k, uv, q)); + } + } + let (_, k, uv, q) = best.unwrap(); + (k, uv, q) + } + + /// `∫∫ f(S, S_u × S_v) du dv` over every face's own region (inside its loops' (u, v) + /// polygons), by the midpoint rule on an `n × n` grid over each region's box. + fn quadrature(&self, n: usize, f: &dyn Fn(Vec3, Vec3) -> f64) -> f64 { + let mut sum = 0.0; + for (s, _, polys) in &self.faces { + let all: Vec<[f64; 2]> = polys.iter().flatten().copied().collect(); + let (mut lo, mut hi) = ([f64::MAX; 2], [f64::MIN; 2]); + for q in &all { + lo = [lo[0].min(q[0]), lo[1].min(q[1])]; + hi = [hi[0].max(q[0]), hi[1].max(q[1])]; + } + let inside = |u: f64, v: f64| { + let mut w = false; + for poly in polys { + for k in 0..poly.len() { + let (a, c) = (poly[k], poly[(k + 1) % poly.len()]); + if (a[1] > v) != (c[1] > v) && u < a[0] + (v - a[1]) / (c[1] - a[1]) * (c[0] - a[0]) { + w = !w; + } + } + } + w + }; + let (du, dv) = ((hi[0] - lo[0]) / n as f64, (hi[1] - lo[1]) / n as f64); + for i in 0..n { + for j in 0..n { + let (u, v) = (lo[0] + (i as f64 + 0.5) * du, lo[1] + (j as f64 + 0.5) * dv); + if inside(u, v) { + let (p, su, sv) = s.derivs(u, v).unwrap(); + sum += f(p, su.cross(sv)) * du * dv; } } } - (best.1, best.2) } - }; - for _ in 0..60 { - let (q, a, b) = (s.subs(u, v), s.uder(u, v), s.vder(u, v)); - let r = q - p; - let (aa, ab, bb) = (a.dot(a), a.dot(b), b.dot(b)); - let det = aa * bb - ab * ab; - if det.abs() < 1e-300 { - break; - } - let (ga, gb) = (a.dot(r), b.dot(r)); - u = (u - (bb * ga - ab * gb) / det).clamp(u0, u1); - v = (v - (aa * gb - ab * ga) / det).clamp(v0, v1); + sum } - (u, v) } -fn v3(v: mt::Vector3) -> Vec3 { - Vec3::new(v.x, v.y, v.z) -} - -/// Points along every edge of the loop: `per` on each. -fn rim_points(face: &mt::Face, per: usize) -> Vec { +/// Points along every free edge of the fill (its loop): `per` on each. +fn rim_points(body: &Body, per: usize) -> Vec { + let r = body.record(); let mut out = Vec::new(); - for e in face.boundaries().iter().flat_map(|w| w.edge_iter()) { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); + for e in r.edges.iter().filter(|e| e.uses.len() == 1) { + let c = CurveEval::new(e.parameters()).unwrap(); + let [t0, t1] = e.interval; for k in 0..per { - out.push(from_p3(c.subs(t0 + (t1 - t0) * (k as f64 + 0.5) / per as f64))); + out.push(c.point(t0 + (t1 - t0) * (k as f64 + 0.5) / per as f64).unwrap()); } } out @@ -71,107 +128,69 @@ fn rim_points(face: &mt::Face, per: usize) -> Vec { /// the whole loop: a fold would show as 180°), and the largest difference between the patch's /// normal curvature across the loop and `curvature(p)`, the neighbour's. fn along_the_loop(fill: &Body, normal: &dyn Fn(Vec3) -> Vec3, curvature: &dyn Fn(Vec3) -> f64) -> (f64, f64, f64) { - let face = fill.solid.face_iter().next().unwrap().clone(); - let s = face.surface(); - let pts = rim_points(&face, 200); - let mut found = Vec::with_capacity(pts.len()); - let mut hint = None; - for p in &pts { - let uv = nearest(&s, *p, hint); - hint = Some(uv); - found.push(uv); - } + let faces = Faces::of(fill); + let pts = rim_points(fill, 200); + let found: Vec<(usize, [f64; 2], Vec3)> = pts.iter().map(|p| faces.nearest(*p)).collect(); + let patch_normal = |k: usize, uv: [f64; 2]| { + let (_, su, sv) = faces.faces[k].0.derivs(uv[0], uv[1]).unwrap(); + su.cross(sv).normalized().unwrap() + }; // One sign for the whole loop: the one most rim points agree with. - let patch_normal = |(u, v): (f64, f64)| v3(s.normal(u, v)); - let agree: f64 = pts.iter().zip(&found).map(|(p, uv)| patch_normal(*uv).dot(normal(*p)).signum()).sum(); + let agree: f64 = pts.iter().zip(&found).map(|(p, (k, uv, _))| patch_normal(*k, *uv).dot(normal(*p)).signum()).sum(); let sign = agree.signum(); let (mut gap, mut angle, mut kappa) = (0.0f64, 0.0f64, 0.0f64); - for (k, (p, &(u, v))) in pts.iter().zip(&found).enumerate() { - gap = gap.max(from_p3(s.subs(u, v)).dist(*p)); - let n = patch_normal((u, v)); + for (i, (p, &(k, uv, q))) in pts.iter().zip(&found).enumerate() { + gap = gap.max(q.dist(*p)); + let n = patch_normal(k, uv); let want = normal(*p) * sign; angle = angle.max(n.dot(want).clamp(-1.0, 1.0).acos().to_degrees()); // Across the loop: the tangent-plane direction square to the rim. - let next = pts.get(k + 1).or(pts.get(k.wrapping_sub(1))).copied().unwrap(); + let next = pts.get(i + 1).or(pts.get(i.wrapping_sub(1))).copied().unwrap(); let t = (next - *p).normalized().unwrap(); let Some(d) = n.cross(t).normalized() else { continue }; - let (su, sv) = (v3(s.uder(u, v)), v3(s.vder(u, v))); + let s = &faces.faces[k].0; + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); // d = a·su + b·sv. let (aa, ab, bb) = (su.dot(su), su.dot(sv), sv.dot(sv)); let det = aa * bb - ab * ab; - let (a, b) = ((bb * d.dot(su) - ab * d.dot(sv)) / det, (aa * d.dot(sv) - ab * d.dot(su)) / det); - // The second derivatives by central differences of the surface's own points. - let h = 1e-3; - let e = |du: f64, dv: f64| from_p3(s.subs(u + du * h, v + dv * h)); - let suu = (e(1.0, 0.0) - e(0.0, 0.0) * 2.0 + e(-1.0, 0.0)) * (1.0 / (h * h)); - let svv = (e(0.0, 1.0) - e(0.0, 0.0) * 2.0 + e(0.0, -1.0)) * (1.0 / (h * h)); - let suv = (e(1.0, 1.0) - e(1.0, -1.0) - e(-1.0, 1.0) + e(-1.0, -1.0)) * (0.25 / (h * h)); - let second = suu * (a * a) + suv * (2.0 * a * b) + svv * (b * b); + let (a, c) = ((bb * d.dot(su) - ab * d.dot(sv)) / det, (aa * d.dot(sv) - ab * d.dot(su)) / det); + let (suu, suv, svv) = s.second(uv[0], uv[1]).unwrap(); + let second = suu * (a * a) + suv * (2.0 * a * c) + svv * (c * c); kappa = kappa.max((second.dot(want) - curvature(*p)).abs()); } (gap, angle, kappa) } -/// `∫∫ f(S, S_u × S_v) du dv` over the face's own region of its surface (its loop taken into -/// parameter space by the nearest parameters of points along it), by the midpoint rule on a -/// `n × n` grid over the region's box: the quadrature the mesher's area is checked against. -fn quadrature(face: &mt::Face, n: usize, f: &dyn Fn(Vec3, Vec3) -> f64) -> f64 { - let s = face.surface(); - let mut poly: Vec<(f64, f64)> = Vec::new(); - let mut hint = None; - for p in rim_points(face, 400) { - let uv = nearest(&s, p, hint); - hint = Some(uv); - poly.push(uv); - } - let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN)); - for &(u, v) in &poly { - lo = (lo.0.min(u), lo.1.min(v)); - hi = (hi.0.max(u), hi.1.max(v)); - } - let inside = |u: f64, v: f64| { - let mut w = false; - for k in 0..poly.len() { - let (a, b) = (poly[k], poly[(k + 1) % poly.len()]); - if (a.1 > v) != (b.1 > v) && u < a.0 + (v - a.1) / (b.1 - a.1) * (b.0 - a.0) { - w = !w; - } - } - w - }; - let (du, dv) = ((hi.0 - lo.0) / n as f64, (hi.1 - lo.1) / n as f64); - let mut sum = 0.0; - for i in 0..n { - for j in 0..n { - let (u, v) = (lo.0 + (i as f64 + 0.5) * du, lo.1 + (j as f64 + 0.5) * dv); - if inside(u, v) { - sum += f(from_p3(s.subs(u, v)), v3(s.uder(u, v)).cross(v3(s.vder(u, v)))) * du * dv; - } - } - } - sum -} - -/// The fill is one face on the open body's own edges, within the fill's tolerance of them; its -/// mesh has no folded triangle (each faces the way its corners' normals do); and the mesher's -/// area agrees with a quadrature of the surface over its own region. Returns the area. +/// The fill is a sheet on the open body's own edges (its free edges lie on the body's edge curves; +/// a loop of five or more edges is filled by patches about a centre, its edges in halves), within +/// the fill's tolerance of them; its mesh has no folded triangle (each faces the way its corners' +/// normals do); and the mesher's area agrees with a quadrature of the surfaces over their own +/// regions. Returns the area. fn check_face(name: &str, open: &Body, fill: &Body) -> f64 { assert!(fill.is_surface()); - assert_eq!(fill.face_count(), 1, "{name}: one face"); - let own: Vec = open.solid.edge_iter().map(|e| e.id()).collect(); - assert!(fill.solid.edge_iter().all(|e| own.contains(&e.id())), "{name}: an edge that is not the body's"); - let face = fill.solid.face_iter().next().unwrap().clone(); - let s = face.surface(); - let tol = face_tolerance(open); - let mut off = 0.0f64; - let mut hint = None; - for p in rim_points(&face, 64) { - let uv = nearest(&s, p, hint); - hint = Some(uv); - off = off.max(from_p3(s.subs(uv.0, uv.1)).dist(p)); + assert!(fill.face_count() >= 1, "{name}: a face"); + let (own, made) = (open.record(), fill.record()); + // The same kind of curve on the same curve it is parameterised on, to rounding (SMLib makes a + // conic's frame and NURBS form again on a round trip, the last bit of a coordinate apart). + let close = |p: &[f64], q: &[f64]| p.len() == q.len() && p.iter().zip(q).all(|(x, y)| (x - y).abs() <= 1e-12 * (1.0 + x.abs().max(y.abs()))); + let same = |c: &b::Curve, d: &b::Curve| match (c, d) { + (b::Curve::Spline { knots: k, points: p }, b::Curve::Spline { knots: l, points: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + (b::Curve::RationalSpline { knots: k, homogeneous: p }, b::Curve::RationalSpline { knots: l, homogeneous: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + _ => c == d, + }; + let kind = |e: &b::Edge| std::mem::discriminant(&e.curve); + for e in made.edges.iter().filter(|e| e.uses.len() == 1) { + assert!(own.edges.iter().any(|o| kind(o) == kind(e) && same(o.parameters(), e.parameters())), "{name}: an edge that is not the body's"); } + let faces = Faces::of(fill); + let tol = face_tolerance(open); + let off = rim_points(fill, 64).iter().map(|p| faces.nearest(*p).2.dist(*p)).fold(0.0f64, f64::max); assert!(off <= tol * 1.01, "{name}: an edge is {off} off the face (tolerance {tol})"); - let m = fill.tessellate(0.01).unwrap(); + let m = fill.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!(!m.triangles.is_empty(), "{name}: the face meshes"); for t in &m.triangles { let [a, b, c] = m.tri(t).unwrap(); @@ -182,8 +201,8 @@ fn check_face(name: &str, open: &Body, fill: &Body) -> f64 { } } let area = measure(fill).unwrap().area; - let quad = quadrature(&face, 500, &|_, n| n.len()); - eprintln!("{name}: one face, edges within {off:e} (tolerance {tol:e}), mesh area {area:.4}, quadrature {quad:.4}"); + let quad = faces.quadrature(500, &|_, n| n.len()); + eprintln!("{name}: {} faces, edges within {off:e} (tolerance {tol:e}), mesh area {area:.4}, quadrature {quad:.4}", fill.face_count()); assert!((area - quad).abs() < 3e-3 * quad, "{name}: mesh area {area} against the surface's {quad}"); area } @@ -195,28 +214,23 @@ fn spec(g: Continuity) -> PatchSpec { fn report(name: &str, r: &PatchReport) { eprintln!( "{name}: fill reports gap {:e}, normals within {:.4}° ({:.4}° near clashing corners), curvature mismatch {:e}, points within {:e}", - r.gap, r.normal_deviation_deg, r.normal_deviation_all_deg, r.curvature_mismatch, r.point_gap + r.gap, r.normal_deviation_deg, r.normal_deviation_all_deg, r.jumps[2], r.point_gap ); } -/// A cylinder about z of radius 10 and 30 high with its top face taken off; points around the rim. -fn open_tube() -> (Body, Vec) { - let solid = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 30.0).unwrap(); - let open = copy_faces(&solid, &[&around(10.0, 15.0)[..], &[Vec3::ZERO]].concat()).unwrap(); - assert!(open.is_surface()); - let rim = (0..8).map(|k| Vec2::from_angle(k as f64 * 0.785).extend(0.0) * 10.0 + Vec3::Z * 30.0).collect(); - (open, rim) -} - /// `body` without its planar faces but those at height `z0` or `z1` (the ends of a cylinder): /// a cut solid's walls (and ends) as a surface, the faces the cut made taken away. fn curved_and_ends(body: &Body, ends: &[f64]) -> Body { - let drop: Vec = body - .solid - .face_iter() + let r = body.record(); + let drop: Vec = r + .faces + .iter() .enumerate() - .filter(|(_, f)| match f.surface() { - mt::Surface::Plane(p) => !ends.iter().any(|z| (p.origin().z - z).abs() < 1e-9 && p.normal().z.abs() > 1.0 - 1e-12), + .filter(|(_, f)| match &f.surface { + b::Surface::Plane { origin, u_axis, v_axis } => { + let n = Vec3::from(*u_axis).cross(Vec3::from(*v_axis)).normalized().unwrap(); + !ends.iter().any(|z| (origin[2] - z).abs() < 1e-9 && n.z.abs() > 1.0 - 1e-12) + } _ => false, }) .map(|(i, _)| i) @@ -229,152 +243,22 @@ fn curved_and_ends(body: &Body, ends: &[f64]) -> Body { /// A point on each edge that bounds only one face of `body` (its free edges): the middle of /// each, where the edge picker samples it. fn free_edge_points(body: &Body) -> Vec { - let mut uses: std::collections::HashMap = std::collections::HashMap::new(); - for f in body.solid.face_iter() { - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - uses.entry(e.id()).or_insert((0, e.clone())).0 += 1; - } - } - let mut points = uses - .values() - .filter(|(n, _)| *n == 1) - .map(|(_, e)| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - from_p3(c.subs(0.5 * (t0 + t1))) - }) + let r = body.record(); + let mut points = r + .edges + .iter() + .filter(|e| e.uses.len() == 1) + .map(|e| CurveEval::new(e.parameters()).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap()) .collect::>(); - // In a fixed order, whatever the map's. + // In a fixed order. points.sort_by(|a, b| (a.z, a.y, a.x).partial_cmp(&(b.z, b.y, b.x)).unwrap()); points } -/// Points round the circle of radius `r` about z at height `z`, every 30°. -fn around(r: f64, z: f64) -> Vec { - (0..12).map(|k| Vec2::from_angle(0.1 + k as f64 * std::f64::consts::TAU / 12.0).extend(0.0) * r + Vec3::Z * z).collect() -} - fn radial(p: Vec3) -> Vec3 { Vec3::new(p.x, p.y, 0.0).normalized().unwrap() } -#[test] -fn an_opened_tube_end_capped_g1_and_g2_meets_the_wall() { - let (open, rim) = open_tube(); - let mut kappas = Vec::new(); - for g in [Continuity::G1, Continuity::G2] { - let name = format!("tube end {}", g.as_str()); - let started = std::time::Instant::now(); - let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap(); - eprintln!("{name}: filled in {:?}", started.elapsed()); - report(&name, &r); - assert!(r.general); - let area = check_face(&name, &open, &fill); - // The wall's normal is radial and it does not bend along its axis. - let (gap, angle, kappa) = along_the_loop(&fill, &radial, &|_| 0.0); - eprintln!( - "{name}: along the rim (1600 points): within {gap:e} of it, normal within {angle:.5}° of the wall's, curvature across {kappa:e} /mm (the wall's 0)" - ); - assert!(angle < 0.1, "{name}: the normal turns {angle}° from the wall's"); - kappas.push(kappa); - // A dome over the rim, not a flat lid: more than the disc. - assert!(area > std::f64::consts::PI * 100.0 * 1.05, "{name}: {area}"); - // Sealed: the tube's volume plus the dome's, the dome's by the divergence theorem over the - // patch (∫∫ (z − 30)·n_z dA), independent of the mesher. - let closed = stitch(&[&open, &fill], 0.0).unwrap(); - assert!(!closed.is_surface(), "{name}: the cap closes the tube"); - let face = fill.solid.face_iter().next().unwrap().clone(); - let dome = quadrature(&face, 500, &|p, n| (p.z - 30.0) * n.z).abs(); - let (got, want) = (measure(&closed).unwrap().volume, std::f64::consts::PI * 100.0 * 30.0 + dome); - eprintln!("{name}: sealed volume {got:.3}, tube + dome {want:.3}"); - assert!((got - want).abs() < 2e-4 * want, "{name}: {got} vs {want}"); - } - eprintln!("tube end: curvature across the rim g1 {:e}, g2 {:e} /mm", kappas[0], kappas[1]); - assert!(kappas[1] < kappas[0], "g2 holds the wall's curvature closer than g1"); -} - -/// A cylinder about z (radius 10, 40 high) with a window `half` either side of the x axis -/// through its wall, from z = 15 to 25; the wall and both ends without the faces the cut made (the -/// window's edges bound only the wall), and a point on each of the window's edges. -fn windowed(half: f64) -> (Body, Body, Vec) { - let solid = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 40.0).unwrap(); - let x = 10.0 * half.cos(); - let tool = box_solid(Vec3::new(x, -11.0, 15.0), Vec3::new(11.0, 11.0, 25.0)).unwrap(); - let cut = boolean(&solid, &tool, BoolOp::Cut).unwrap().unwrap(); - let open = curved_and_ends(&cut, &[0.0, 40.0]); - let rim = free_edge_points(&open); - (solid, open, rim) -} - -#[test] -fn a_window_cut_through_a_cylinder_wall_past_half_way_fills_g1_close_to_the_cylinder() { - // 240° round: seen along any direction the window folds over itself, so it bounds no height - // field; the old fill refused it. - let half = 2.0 * std::f64::consts::PI / 3.0; - let (solid, open, rim) = windowed(half); - for g in [Continuity::G0, Continuity::G1] { - let name = format!("window {}", g.as_str()); - let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap(); - report(&name, &r); - let area = check_face(&name, &open, &fill); - let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0); - eprintln!("{name}: along the window (1600 points): within {gap:e}, normal within {angle:.5}° of the wall's"); - // How far the fill strays from the cylinder it replaces, inside. - let face = fill.solid.face_iter().next().unwrap().clone(); - let s = face.surface(); - let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { panic!() }; - let mut stray = 0.0f64; - for i in 0..=40 { - for j in 0..=40 { - let p = from_p3(s.subs(u0 + (u1 - u0) * i as f64 / 40.0, v0 + (v1 - v0) * j as f64 / 40.0)); - let ang = p.y.atan2(p.x); - if ang.abs() < half - 0.05 && p.z > 15.5 && p.z < 24.5 { - stray = stray.max((Vec2::new(p.x, p.y).len() - 10.0).abs()); - } - } - } - let exact = 10.0 * 2.0 * half * 10.0; - let closed = stitch(&[&open, &fill], 0.0).unwrap(); - let (got, want) = (measure(&closed).unwrap().volume, measure(&solid).unwrap().volume); - eprintln!( - "{name}: area {area:.3} (the cylinder's window {exact:.3}), the fill within {stray:.4} of the cylinder inside, sealed volume {got:.2} against the whole cylinder's {want:.2}" - ); - assert!(!closed.is_surface()); - if g == Continuity::G1 { - assert!(angle < 0.1, "{name}: the normal turns {angle}° from the wall's"); - assert!((area - exact).abs() < 0.01 * exact && stray < 0.25, "{name}: {area} vs {exact}, stray {stray}"); - assert!((got - want).abs() < 0.005 * want, "{name}: {got} vs {want}"); - } - } -} - -#[test] -fn a_saddle_window_in_a_torus_fills_g0_and_g1() { - // The inner wall of a torus (major 20, minor 8) is saddle-shaped; a window 240° round it - // between z = ±3 bounds no height field. - let solid = torus(Vec3::ZERO, 20.0, 8.0).unwrap(); - let tool = box_solid(Vec3::new(-6.0, -13.0, -3.0), Vec3::new(13.0, 13.0, 3.0)).unwrap(); - let cut = boolean(&solid, &tool, BoolOp::Cut).unwrap().unwrap(); - let open = curved_and_ends(&cut, &[]); - let rim = free_edge_points(&open); - // The torus's normal: from the tube's centre circle. - let normal = |p: Vec3| { - let c = Vec3::new(p.x, p.y, 0.0).normalized().unwrap() * 20.0; - (p - c).normalized().unwrap() - }; - for g in [Continuity::G0, Continuity::G1] { - let name = format!("torus window {}", g.as_str()); - let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap(); - report(&name, &r); - check_face(&name, &open, &fill); - let (gap, angle, _) = along_the_loop(&fill, &normal, &|_| 0.0); - eprintln!("{name}: along the window (1600 points): within {gap:e}, normal within {angle:.5}° of the torus's"); - if g == Continuity::G1 { - assert!(angle < 0.1, "{name}: {angle}°"); - } - } -} - /// A cylinder about z (radius 10, 40 high) with a pentagonal pocket cut into its wall from the /// +x side (the pentagon in the yz plane about z = 20, circumradius 6): the wall and both ends /// copied out, and a point on each of the pocket rim's five edges. @@ -389,11 +273,10 @@ fn pentagon_window() -> (Body, Vec) { } #[test] -fn a_five_sided_window_fills_as_one_face_g1_and_through_a_point() { +fn a_five_sided_window_fills_g1_and_through_a_point() { let (open, rim) = pentagon_window(); let (fill, r) = patch_edges_report(&open, &rim, &spec(Continuity::G1)).unwrap(); report("pentagon g1", &r); - assert!(fill.edge_count() >= 5, "the rim's own edges (five, or more where a seam splits one)"); check_face("pentagon g1", &open, &fill); let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0); eprintln!("pentagon g1: along the rim: within {gap:e}, normal within {angle:.5}° of the wall's"); @@ -406,9 +289,7 @@ fn a_five_sided_window_fills_as_one_face_g1_and_through_a_point() { let (fill, r) = patch_edges_report(&open, &rim, &spec).unwrap(); report(&name, &r); check_face(&name, &open, &fill); - let s = fill.solid.face_iter().next().unwrap().surface(); - let (u, v) = nearest(&s, point, None); - let off = from_p3(s.subs(u, v)).dist(point); + let off = Faces::of(&fill).nearest(point).2.dist(point); eprintln!("{name}: the point is {off:e} off the surface"); assert!(off <= face_tolerance(&open), "{name}: {off}"); } @@ -431,17 +312,13 @@ fn a_hexagonal_rim_fills_through_a_point_and_g1_to_walls_meeting_at_angles_holds let open = copy_faces(&solid, &keep).unwrap(); let plain = patch_edges(&open, &rim).unwrap(); let sealed = |f: &Body| measure(&stitch(&[&open, f], 0.0).unwrap()).unwrap().volume; - // Six sides, G0, through a point 3 mm above the middle of the plain fill: one face. - let s = plain.solid.face_iter().next().unwrap().surface(); - let (u, v) = nearest(&s, Vec3::new(0.0, 0.0, 12.0), None); - let point = from_p3(s.subs(u, v)) + Vec3::Z * 3.0; + // Six sides, G0, through a point 3 mm above the middle of the plain fill: it passes through + // the point and seals the cup into a closed solid holding more than the plain fill's. + let point = Faces::of(&plain).nearest(Vec3::new(0.0, 0.0, 12.0)).2 + Vec3::Z * 3.0; let (lifted, r) = patch_edges_report(&open, &rim, &PatchSpec { points: vec![point], ..PatchSpec::default() }).unwrap(); report("hexagon through a point", &r); - assert_eq!(lifted.edge_count(), 6, "the rim's own six edges"); check_face("hexagon through a point", &open, &lifted); - let s = lifted.solid.face_iter().next().unwrap().surface(); - let (u, v) = nearest(&s, point, None); - let off = from_p3(s.subs(u, v)).dist(point); + let off = Faces::of(&lifted).nearest(point).2.dist(point); eprintln!("hexagon through a point: the point is {off:e} off the surface; sealed {:.2} against {:.2} plain", sealed(&lifted), sealed(&plain)); assert!(off <= face_tolerance(&open) && sealed(&lifted) > sealed(&plain)); // G1 to the walls: at a corner no surface is tangent to both walls (its tangent plane there @@ -472,8 +349,6 @@ fn per_edge_continuity_and_hostile_specs() { check_face("pentagon, two edges g1/g2", &open, &fill); let bad = |spec: PatchSpec| patch_edges_report(&open, &rim, &spec).is_err(); let g1 = PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }; - assert!(bad(PatchSpec { continuity: Continuity::G3, ..g1.clone() })); - assert!(bad(PatchSpec { edges: vec![(rim[0], Continuity::G3)], ..g1.clone() })); assert!(bad(PatchSpec { edges: vec![(Vec3::new(0.0, 0.0, 40.0), Continuity::G1)], ..g1.clone() }), "an edge off the loop"); assert!(bad(PatchSpec { edges: vec![(Vec3::new(f64::NAN, 0.0, 0.0), Continuity::G1)], ..g1.clone() })); assert!(bad(PatchSpec { points: vec![Vec3::new(f64::INFINITY, 0.0, 0.0)], ..g1.clone() })); @@ -491,9 +366,7 @@ fn per_edge_continuity_and_hostile_specs() { check_face("pentagon g1 crown 0.1", &open, &full); let (_, angle, _) = along_the_loop(&full, &radial, &|_| 0.0); let middle = |b: &Body| { - let s = b.solid.face_iter().next().unwrap().surface(); - let (u, v) = nearest(&s, Vec3::new(10.0, 0.0, 20.0), None); - let p = from_p3(s.subs(u, v)); + let p = Faces::of(b).nearest(Vec3::new(10.0, 0.0, 20.0)).2; Vec2::new(p.x, p.y).len() }; let (a, b) = (middle(&plain), middle(&full)); @@ -504,3 +377,128 @@ fn per_edge_continuity_and_hostile_specs() { let top = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; assert!(patch_edges_report(&b, &top, &PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }).is_err()); } + +/// The seams between `fill` and the faces of `open` beside its edges, in the middle of each +/// edge (30 % to 70 %): per seam, the largest normal angle (degrees) and jumps of `H₂`, `H₃` and +/// `H₄` along the direction across the seam (`solidcraft_geom::linkage`), read off the two +/// faces' own surfaces: the normal curvature, its rate of change and that rate's. +fn seam_jumps(open: &Body, fill: &Body) -> Vec<[f64; 4]> { + use solidcraft_geom::linkage::surface_jet; + let (ro, rf) = (open.record(), fill.record()); + let normal = |s: &SurfaceEval, uv: [f64; 2]| { + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + su.cross(sv).normalized().unwrap() + }; + let mut out = Vec::new(); + for e in &rf.edges { + let curve = CurveEval::new(e.parameters()).unwrap(); + let [t0, t1] = e.interval; + let on_fill = SurfaceEval::new(rf.faces[e.uses[0].face as usize].parameters()).unwrap(); + // The face of `open` whose own free edge this is. + let mid = curve.point(0.5 * (t0 + t1)).unwrap(); + let near = |x: &b::Edge| { + let c = CurveEval::new(x.parameters()).unwrap(); + (0..=32).map(|k| c.point(x.interval[0] + (x.interval[1] - x.interval[0]) * k as f64 / 32.0).unwrap().dist(mid)).fold(f64::MAX, f64::min) + }; + let beside = ro.edges.iter().filter(|x| x.uses.len() == 1).min_by(|a, b| near(a).total_cmp(&near(b))).unwrap(); + let on_open = SurfaceEval::new(ro.faces[beside.uses[0].face as usize].parameters()).unwrap(); + let mut worst = [0.0f64; 4]; + for i in 0..=20 { + let (p, d) = curve.derivs(t0 + (t1 - t0) * (0.3 + 0.4 * i as f64 / 20.0)).unwrap(); + let (ua, ub) = (on_fill.project(p, None, f64::INFINITY).unwrap(), on_open.project(p, None, f64::INFINITY).unwrap()); + let na = normal(&on_fill, ua); + let nb = normal(&on_open, ub) * normal(&on_open, ub).dot(na).signum(); + let w = na.cross(d.normalized().unwrap()).normalized().unwrap(); + let (ja, jb) = (surface_jet(&on_fill, ua, na, w, 4).unwrap(), surface_jet(&on_open, ub, nb, w, 4).unwrap()); + worst[0] = worst[0].max(na.dot(nb).clamp(-1.0, 1.0).acos().to_degrees()); + for k in 2..=4 { + worst[k - 1] = worst[k - 1].max((ja.form(k, [0.0, 1.0]).unwrap() - jb.form(k, [0.0, 1.0]).unwrap()).abs()); + } + } + out.push(worst); + } + out +} + +/// The Continuity Analysis (`inspect.continuity`) of `fill` sewn into `open`, on the seams at +/// `hole`: per seam, its order over the whole edge, its order over the stations from 30 % to 70 % +/// (the corners left out), and the worst G3 jump there (1/mm²). +fn continuity_analysis(open: &Body, fill: &Body, hole: &[Vec3]) -> Vec<(Option, Option, f64)> { + use crate::{ContinuityTolerances, EdgePick, pick_edges, seam_diagnostics}; + let sewn = stitch(&[open, fill], 1e-3).unwrap(); + let picks: Vec = hole.iter().map(|p| EdgePick::Point(*p)).collect(); + let edges = pick_edges(&sewn, &picks).unwrap(); + let t = ContinuityTolerances::default(); + let limits = [t.gap_mm, t.angle_deg, t.curvature_per_mm, t.curvature_change_per_mm2, t.curvature_change_rate_per_mm3]; + let report = seam_diagnostics(&sewn, &edges, 33, t).unwrap(); + report + .seams + .iter() + .map(|seam| { + let inside: Vec<_> = seam.stations.iter().filter(|s| (0.3..=0.7).contains(&s.edge_fraction)).collect(); + let worst = |f: fn(&crate::SeamStation) -> f64| inside.iter().map(|s| f(s)).fold(0.0f64, f64::max); + let metrics = [ + worst(|s| s.gap_mm), + worst(|s| s.normal_angle_deg), + worst(|s| s.curvature_jump_per_mm), + worst(|s| s.curvature_change_jump_per_mm2), + worst(|s| s.curvature_change_rate_jump_per_mm3), + ]; + let met = metrics.iter().zip(limits).take_while(|(w, l)| **w <= *l).count(); + (seam.order, met.checked_sub(1).and_then(Continuity::from_order), metrics[3]) + }) + .collect() +} + +/// A box's corner where a round of 8 up the vertical edge meets the rounds of 4 along the top +/// (one blend face rolls the top round over the vertical one); that face taken off, and the hole +/// patched G2, G3 and G4 to the rounds and the top around it. Read off the faces themselves in +/// the middle of each seam: all meet the tangent planes and the curvature; the G3 patch also meets +/// the curvature's rate of change, which the G2 patch leaves many times larger. The Continuity +/// Analysis reads each seam's middle at the order asked, and the whole seam G1: at the corners the +/// rounds' curvatures differ, so no patch can meet both. G3 to an edge between two faces is +/// refused. +#[test] +fn a_corner_of_three_rounds_patched_g3_holds_the_curvature_change_a_g2_patch_does_not() { + let solid = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 30.0)).unwrap(); + let up = crate::fillet(&solid, &[Vec3::new(40.0, 40.0, 15.0)], 8.0).unwrap(); + // The top edges and the arc between them over the vertical round: one tangent chain. + let arc = Vec3::new(32.0, 32.0, 30.0) + Vec3::new(1.0, 1.0, 0.0) * (8.0 / 2f64.sqrt()); + let rounded = crate::fillet(&up, &[Vec3::new(40.0, 20.0, 30.0), arc, Vec3::new(20.0, 40.0, 30.0)], 4.0).unwrap(); + // The blend face at the corner: the one face neither plane nor cylinder there. + let corner = Vec3::new(37.79, 36.155, 28.43); + let faces = Faces::of(&rounded); + let (k, _, _) = faces.nearest(corner); + let open = crate::remove_faces(&rounded, &[k]).unwrap(); + assert!(open.is_surface()); + let hole = [Vec3::new(34.828, 34.828, 30.0), Vec3::new(37.657, 37.657, 26.0), Vec3::new(38.828, 32.0, 28.828), Vec3::new(32.0, 38.828, 28.828)]; + let mut read = Vec::new(); + for g in [Continuity::G2, Continuity::G3, Continuity::G4] { + let name = format!("three-round corner {}", g.as_str()); + let (fill, r) = patch_edges_report(&open, &hole, &spec(g)).unwrap(); + report(&name, &r); + let seams = seam_jumps(&open, &fill); + eprintln!("{name}: jumps of the fill's report {:?}; read off the faces, per seam [angle°, H2, H3, H4] {seams:?}", r.jumps); + let analysed = continuity_analysis(&open, &fill, &hole); + eprintln!("{name}: Continuity Analysis, per seam [order over the edge, order 30-70 %, worst G3 jump 30-70 % /mm²] {analysed:?}"); + assert_eq!(analysed.len(), 4, "{name}: four seams analysed"); + for (whole, middle, _) in &analysed { + assert_eq!(*middle, Some(g), "{name}: the Continuity Analysis reads the order asked in the middle of each seam"); + assert_eq!(*whole, Some(Continuity::G1), "{name}: the corners, where the rounds' curvatures differ, hold the tangent plane only"); + } + assert_eq!(seams.len(), 4, "{name}: four seams"); + for s in &seams { + assert!(s[0] < PATCH_ANGLE_TOL_DEG, "{name}: the tangent planes meet: {s:?}"); + assert!(s[1] < 1e-3, "{name}: the curvature meets: {s:?}"); + } + read.push(seams); + } + for (g2, g3) in read[0].iter().zip(&read[1]) { + assert!(g3[2] < 1e-2, "G3 meets the curvature change: {g3:?}"); + assert!(g2[2] > 20.0 * g3[2].max(1e-6), "G2 leaves the curvature change: {g2:?} vs G3 {g3:?}"); + } + // A closed box's top edges lie between two faces: there is no one face to meet G3. + let top = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + assert!(patch_edges_report(&b, &top, &spec(Continuity::G3)).is_err()); +} diff --git a/crates/kernel/src/fillet_setback_tests.rs b/crates/kernel/src/fillet_setback_tests.rs new file mode 100644 index 000000000..f12b4da01 --- /dev/null +++ b/crates/kernel/src/fillet_setback_tests.rs @@ -0,0 +1,76 @@ +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; + +use crate::*; + +/// The 60 x 40 x 20 box with r5 rounds on the three edges at (60, 40, 20). +fn corner_case(setback: Option) -> Result { + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let edges = [Vec3::new(30.0, 40.0, 20.0), Vec3::new(60.0, 20.0, 20.0), Vec3::new(60.0, 40.0, 10.0)]; + match setback { + Some(s) => fillet_setback(&b, &edges, 5.0, &[(Vec3::new(60.0, 40.0, 20.0), s)]), + None => fillet(&b, &edges, 5.0), + } +} + +/// Set back 8 along each edge: outside the corner cube [52, 60] x [32, 40] x [12, 20] the body +/// is the sphere corner's, and inside it the convex body holds the hull of its points on the +/// cube's faces (299.0201) and lies within the three rounds' prisms (512 - 225 (1 - pi/4) - +/// 125 (sqrt 2 - 1)); see capi/tests/ops_kernel.cpp, corner_setback. The patch is SMLib's two +/// quadrilaterals per side: 15 faces, 36 edges, 23 vertices; the box stays the box. +#[test] +fn a_corner_set_back_8_blends_through_a_larger_patch() { + let pi = std::f64::consts::PI; + let sphere = measure(&corner_case(None).unwrap()).unwrap().volume; + let out = corner_case(Some(8.0)).unwrap(); + assert!(out.validity().is_empty(), "{:?}", out.validity()); + let m = measure(&out).unwrap(); + let in_c_sphere = 512.0 - 225.0 * (1.0 - pi / 4.0) - 125.0 * (1.0 - pi / 6.0); + let prisms = 512.0 - 225.0 * (1.0 - pi / 4.0) - 125.0 * (2f64.sqrt() - 1.0); + let outside = sphere - in_c_sphere; + assert!(m.volume > outside + 299.0201 && m.volume < outside + prisms, "{} not in [{}, {}]", m.volume, outside + 299.0201, outside + prisms); + assert_eq!((m.faces, m.edges, m.vertices), (15, 36, 23)); + assert!((m.bbox.min - Vec3::new(0.0, 0.0, 0.0)).len() < 1e-6 && (m.bbox.max - Vec3::new(60.0, 40.0, 20.0)).len() < 1e-6, "{:?}", m.bbox); +} + +/// A setback point at no vertex, at a corner where no edge is rounded, or as long as an edge +/// there, is refused. +#[test] +fn a_setback_off_the_rounded_corner_is_refused() { + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let edges = [Vec3::new(30.0, 40.0, 20.0), Vec3::new(60.0, 20.0, 20.0), Vec3::new(60.0, 40.0, 10.0)]; + assert!(fillet_setback(&b, &edges, 5.0, &[(Vec3::new(30.0, 20.0, 10.0), 8.0)]).is_err()); + assert!(fillet_setback(&b, &edges, 5.0, &[(Vec3::new(0.0, 0.0, 0.0), 8.0)]).is_err()); + assert!(matches!(corner_case(Some(20.0)), Err(KernelError::TooLarge(_)))); +} + +/// A setback that does not reach past where the corner's rounds meet without one (on faces square +/// to each other, the radius) is refused before SMLib runs, naming that least setback. Past it, a +/// setback still too short for the corner fill (certified convex only from a setback on, as SMLib +/// f916a8d's setback corner does) is refused naming the smallest that builds, +/// at most twice the one asked for (the certificate scales the setbacks up to 2); that one builds. +#[test] +fn a_setback_not_past_the_radius_is_refused_naming_the_least() { + for s in [2.0, 5.0] { + match corner_case(Some(s)) { + Err(KernelError::Invalid(why)) => assert!(why.contains("setback must be more than the radius (5 mm)"), "{why}"), + other => panic!("setback {s}: {:?}", other.map(|b| b.face_count())), + } + } + let least = match corner_case(Some(5.5)) { + Err(KernelError::Invalid(why)) => { + let named = why.split_once(SETBACK_AT_LEAST).and_then(|(_, rest)| rest.split_once(" mm")).and_then(|(n, _)| n.parse::().ok()); + named.unwrap_or_else(|| panic!("no least setback named: {why}")) + } + other => panic!("setback 5.5: {:?}", other.map(|b| b.face_count())), + }; + eprintln!("setback 5.5 refused: the smallest that builds is {least}"); + assert!(least > 5.5 && least <= 11.0, "{least}"); + let out = corner_case(Some(least)).unwrap(); + assert!(out.validity().is_empty(), "{:?}", out.validity()); + // The least the refusal names, for a form to show before it runs; none at no vertex. + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let least = crate::fillet_least_setback(&b, Vec3::new(60.0, 40.0, 20.0), 5.0).unwrap(); + assert!(least.is_some_and(|l| (l - 5.0).abs() < 1e-9), "{least:?}"); + assert_eq!(crate::fillet_least_setback(&b, Vec3::new(30.0, 20.0, 10.0), 5.0).unwrap(), None); +} diff --git a/crates/kernel/src/freeform.rs b/crates/kernel/src/freeform.rs index c860332d1..f608aecb7 100644 --- a/crates/kernel/src/freeform.rs +++ b/crates/kernel/src/freeform.rs @@ -1,29 +1,106 @@ -//! Free-form profile edges: Béziers (cubic and higher) as B-spline curves and conics as rational quadratic -//! NURBS curves (exact ellipses, parabolas and hyperbolas from sketches). +//! Profile segments as exact schema 4 curves: each sketch segment on its plane becomes a 3D edge +//! curve and, on the plane's own surface (`origin + u x + v y`, (u, v) the sketch coordinates), its +//! pcurve, both on t in [0, 1] with the same knots and weights, so the pcurve lifts onto the edge +//! exactly. Lines are lines; arcs rational quadratic B-splines (one span per quarter turn or less); +//! cubic and higher Béziers B-splines on their own control points; conics rational quadratic +//! Béziers (exact ellipses, parabolas and hyperbolas). -use solidcraft_geom::{Plane, Seg2}; -use truck_modeling as mt; +use solidcore_record::brep::{Curve, Curve2, Surface}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; -use crate::body::p3; +use crate::{KernelError, Result}; -/// The edge for a free-form segment between two existing vertices (None for lines and arcs). -pub(crate) fn edge(plane: &Plane, s: &Seg2, a: &mt::Vertex, b: &mt::Vertex) -> Option { - match *s { - Seg2::Cubic { p1, p2, .. } => Some(mt::builder::bezier(a, b, vec![p3(plane.to_world(p1)), p3(plane.to_world(p2))])), - Seg2::Conic { apex, w, .. } => { - let (pa, pb, px) = (a.point(), b.point(), p3(plane.to_world(apex))); - let ctrl = vec![ - mt::Vector4::new(pa.x, pa.y, pa.z, 1.0), - mt::Vector4::new(px.x * w, px.y * w, px.z * w, w), - mt::Vector4::new(pb.x, pb.y, pb.z, 1.0), - ]; - let curve = mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), ctrl)); - Some(mt::Edge::new(a, b, mt::Curve::NurbsCurve(curve))) +/// The interval every curve [`segment`] makes runs on. +pub(crate) const INTERVAL: [f64; 2] = [0.0, 1.0]; + +/// The plane of a sketch as a record surface whose (u, v) are the sketch's coordinates. +pub(crate) fn plane_surface(plane: &Plane) -> Surface { + let a = |v: Vec3| [v.x, v.y, v.z]; + Surface::Plane { origin: a(plane.origin), u_axis: a(plane.x), v_axis: a(plane.y) } +} + +/// A clamped Bézier knot vector of `degree`. +fn bezier_knots(degree: usize) -> Vec { + std::iter::repeat_n(0.0, degree + 1).chain(std::iter::repeat_n(1.0, degree + 1)).collect() +} + +/// The 2D rational control net of `s` (points, weights, knots), on t in [0, 1]. +fn net(s: &Seg2) -> Result<(Vec, Vec, Vec)> { + Ok(match *s { + Seg2::Line { a, b } => (vec![a, b], vec![1.0; 2], bezier_knots(1)), + Seg2::Arc { center, radius, start, sweep } => { + if !(radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep != 0.0 && sweep.abs() <= std::f64::consts::TAU * (1.0 + 1e-9)) { + return Err(KernelError::Invalid("an arc with no radius or turn, or turning more than once".into())); + } + let sweep = sweep.clamp(-std::f64::consts::TAU, std::f64::consts::TAU); + let m = (sweep.abs() / std::f64::consts::FRAC_PI_2 - 1e-9).ceil().max(1.0) as usize; + let d = sweep / m as f64; + let at = |a: f64, r: f64| center + Vec2::new(a.cos(), a.sin()) * r; + let w = (d / 2.0).cos(); + let (mut pts, mut weights, mut knots) = (vec![at(start, radius)], vec![1.0], vec![0.0; 3]); + for j in 0..m { + let a0 = start + d * j as f64; + pts.push(at(a0 + d / 2.0, radius / w)); + weights.push(w); + pts.push(at(a0 + d, radius)); + weights.push(1.0); + let u = (j + 1) as f64 / m as f64; + if j + 1 < m { + knots.extend([u, u]); + } else { + knots.extend([1.0; 3]); + } + } + (pts, weights, knots) + } + Seg2::Cubic { p0, p1, p2, p3 } => (vec![p0, p1, p2, p3], vec![1.0; 4], bezier_knots(3)), + Seg2::Conic { a, apex, b, w } => { + if !(w.is_finite() && w > 0.0) { + return Err(KernelError::Invalid("a conic's weight must be positive".into())); + } + (vec![a, apex, b], vec![1.0, w, 1.0], bezier_knots(2)) } Seg2::Bezier { n, ref p } => { - let inner = p.get(1..(n as usize).clamp(1, solidcraft_geom::MAX_BEZIER_DEGREE))?; - Some(mt::builder::bezier(a, b, inner.iter().map(|q| p3(plane.to_world(*q))).collect())) + let n = usize::from(n); + let pts = p.get(..=n).filter(|_| (1..=solidcore_record::MAX_BEZIER_DEGREE).contains(&n)); + let pts = pts.ok_or_else(|| KernelError::Invalid("Bézier degree".into()))?; + (pts.to_vec(), vec![1.0; n + 1], bezier_knots(n)) } - Seg2::Line { .. } | Seg2::Arc { .. } => None, + }) +} + +/// The segment `s` on `plane` as an edge curve and its pcurve on [`plane_surface`], both on +/// [`INTERVAL`]. +pub(crate) fn segment(plane: &Plane, s: &Seg2) -> Result<(Curve, Curve2)> { + let (pts, weights, knots) = net(s)?; + if pts.iter().any(|q| !q.is_finite()) { + return Err(KernelError::Invalid("a profile curve is not finite".into())); } + let w = |q: Vec2| { + let p = plane.to_world(q); + [p.x, p.y, p.z] + }; + if let Seg2::Line { a, b } = *s { + if a.dist(b) <= 0.0 { + return Err(KernelError::Invalid("a profile line has no length".into())); + } + let pc = Curve2::Spline { knots, points: vec![[a.x, a.y], [b.x, b.y]] }; + return Ok((Curve::Line { start: w(a), end: w(b) }, pc)); + } + if weights.iter().all(|x| *x == 1.0) { + let curve = Curve::Spline { knots: knots.clone(), points: pts.iter().map(|q| w(*q)).collect() }; + return Ok((curve, Curve2::Spline { knots, points: pts.iter().map(|q| [q.x, q.y]).collect() })); + } + let homogeneous = pts + .iter() + .zip(&weights) + .map(|(q, h)| { + let [x, y, z] = w(*q); + [x * h, y * h, z * h, *h] + }) + .collect(); + let pcurve = + Curve2::RationalSpline { knots: knots.clone(), homogeneous: pts.iter().zip(&weights).map(|(q, h)| [q.x * h, q.y * h, *h]).collect() }; + Ok((Curve::RationalSpline { knots, homogeneous }, pcurve)) } diff --git a/crates/kernel/src/fuzz.rs b/crates/kernel/src/fuzz.rs index d02678b01..4219a2b5d 100644 --- a/crates/kernel/src/fuzz.rs +++ b/crates/kernel/src/fuzz.rs @@ -3,7 +3,7 @@ //! placed on a coarse grid, so coincident faces and tangencies come up often. use serde::Serialize; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::{Body, BoolOp, boolean, box_solid, cylinder, measure, sphere, torus}; @@ -99,8 +99,6 @@ pub struct BoolCase { /// "ok", or the kind of failure: "error", "invalid", "identity". pub outcome: String, pub detail: String, - pub boolean_fallbacks: std::collections::BTreeMap, - pub boolean_reports_truncated: bool, } fn vol(b: &Option) -> crate::Result { @@ -120,15 +118,7 @@ pub fn boolean_shapes(seed: u64) -> (Shape, Shape) { /// V(A∪B) + V(A∩B) = V(A) + V(B) and V(A−B) = V(A) − V(A∩B), within 0.2 %. pub fn boolean_case(seed: u64) -> BoolCase { let (a, b) = boolean_shapes(seed); - let mut case = BoolCase { - seed, - a: a.clone(), - b: b.clone(), - outcome: "ok".into(), - detail: String::new(), - boolean_fallbacks: Default::default(), - boolean_reports_truncated: false, - }; + let mut case = BoolCase { seed, a: a.clone(), b: b.clone(), outcome: "ok".into(), detail: String::new() }; let fail = |c: &mut BoolCase, kind: &str, d: String| { c.outcome = kind.into(); c.detail = d; @@ -139,11 +129,7 @@ pub fn boolean_case(seed: u64) -> BoolCase { }; let mut res = Vec::new(); for op in [BoolOp::Union, BoolOp::Intersect, BoolOp::Cut] { - let (result, diagnostics) = crate::capture_boolean_diagnostics(|| boolean(&ba, &bb, op)); - case.boolean_reports_truncated |= diagnostics.truncated; - for event in diagnostics.events { - *case.boolean_fallbacks.entry(event.strategy).or_default() += 1; - } + let result = boolean(&ba, &bb, op); match result { Ok(x) => { if let Some(body) = &x { diff --git a/crates/kernel/src/heal.rs b/crates/kernel/src/heal.rs index 6d0f5995a..45f1f7f66 100644 --- a/crates/kernel/src/heal.rs +++ b/crates/kernel/src/heal.rs @@ -1,36 +1,15 @@ -//! Clean-up after operations: coplanar neighbouring faces become one face, and two straight -//! edges meeting in line at a vertex nothing else uses become one edge (they are kept as one). +//! Clean-up after operations: faces on one surface that meet along an edge become one face, and +//! two edges on one curve meeting at a vertex nothing else uses become one edge. SMLib does it +//! (`Brep::merge_faces`, its `SmBrep::RemoveTopologicalEdgesAndVertices`; its booleans do the +//! same at their end), keeping apart the faces split on purpose along the body's split lines. -use std::collections::{BTreeSet, HashMap}; +use solidcore_record::Vec3; +use solidcore_record::brep::Brep; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::prelude::*; -use solidcraft_geom::{Ring, Vec3}; -use truck_modeling::{self as mt, builder}; - -use crate::body::{Solid, from_p3}; -use crate::history::{Change, EdgeOrigin, FaceProv}; - -fn plane_of(f: &mt::Face) -> Option<(Vec3, f64)> { - match f.oriented_surface() { - mt::Surface::Plane(p) => { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - let o = p.origin(); - Some((n, n.dot(Vec3::new(o.x, o.y, o.z)))) - } - _ => None, - } -} - -/// A face like `f` with new boundary wires given in `f`'s absolute (stored) orientation: -/// built on the stored surface and turned like `f` (rebuilding on the turned surface can make -/// the mesher pick the wrong side of a trim on periodic surfaces). -pub(crate) fn absolute_face(f: &mt::Face, wires: Vec) -> Option { - let mut nf = mt::Face::try_new(wires, f.surface()).ok()?; - if !f.orientation() { - nf.invert(); - } - Some(nf) -} +use crate::body::Body; +use crate::{KernelError, Result}; pub(crate) fn find(p: &mut [usize], mut i: usize) -> usize { while let Some(&q) = p.get(i) { @@ -42,34 +21,6 @@ pub(crate) fn find(p: &mut [usize], mut i: usize) -> usize { i } -/// Points along an oriented edge (for loop areas and containment). -fn samples(e: &mt::Edge) -> Vec { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - (0..8).map(|k| t0 + (t1 - t0) * k as f64 / 8.0).map(|t| from_p3(c.subs(t))).collect() -} - -fn loop_area(edges: &[mt::Edge], n: Vec3) -> f64 { - edges.iter().flat_map(samples).collect::>().area_vector().dot(n) -} - -fn inside(p: Vec3, edges: &[mt::Edge], n: Vec3) -> bool { - let u = n.any_perp(); - let w = n.cross(u); - let pts: Vec<(f64, f64)> = edges.iter().flat_map(samples).map(|q| (q.dot(u), q.dot(w))).collect(); - let (px, py) = (p.dot(u), p.dot(w)); - let k = pts.len(); - let mut c = false; - for i in 0..k { - let (Some(&(ax, ay)), Some(&(bx, by))) = (pts.get(i), pts.get((i + 1) % k)) else { continue }; - if (ay > py) != (by > py) && px < ax + (py - ay) / (by - ay) * (bx - ax) { - c = !c; - } - } - c -} - /// Do the points lie along one of the lines faces were split along on purpose (polylines; /// chords of a curved line sag by under a tenth of their length)? pub(crate) fn on_split_line(pts: &[Vec3], keep: &[Vec]) -> bool { @@ -81,643 +32,34 @@ pub(crate) fn on_split_line(pts: &[Vec3], keep: &[Vec]) -> bool { }) } -/// Points along an edge (ends and three inside). -pub(crate) fn edge_points(e: &mt::Edge) -> Vec { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=4).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 4.0))).collect() +/// Points along edge `e` of the record `b`: its ends and three inside, evenly in its parameter +/// (the middle one at the middle of its interval). +pub(crate) fn edge_points(b: &Brep, e: u32) -> Vec { + let Some(edge) = b.edges.get(e as usize) else { return Vec::new() }; + let Ok(c) = CurveEval::new(edge.parameters()) else { return Vec::new() }; + let [t0, t1] = edge.interval; + (0..=4).filter_map(|k| c.point(t0 + (t1 - t0) * k as f64 / 4.0)).collect() } -/// Merge each group of edge-connected coplanar faces into one face (keeping faces apart along -/// the lines in `keep`). Returns the new shell and, for each of its faces, the faces of `shell` -/// it was made from (by position); None when nothing changed or a merged face can't be built. -fn merge_coplanar(shell: &mt::Shell, tol: f64, keep: &[Vec]) -> Option<(mt::Shell, Vec>)> { - let faces: Vec = shell.face_iter().cloned().collect(); - let planes: Vec> = faces.iter().map(plane_of).collect(); - let mut parent: Vec = (0..faces.len()).collect(); - let mut by_edge: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for e in f.edge_iter() { - by_edge.entry(e.id()).or_default().push(i); - } - } - let mut merged_any = false; - let edges: HashMap = shell.edge_iter().map(|e| (e.id(), e)).collect(); - for (id, fs) in &by_edge { - if let [a, b] = fs[..] - && a != b - && (keep.is_empty() || !edges.get(id).is_some_and(|e| on_split_line(&edge_points(e), keep))) - && let (Some(Some((na, da))), Some(Some((nb, db)))) = (planes.get(a), planes.get(b)) - && na.dot(*nb) > 1.0 - 1e-9 - && (da - db).abs() < tol - { - // The lesser root wins, so each group's root is its first face whatever order the - // edges (in hash order of their addresses) are met in (#707). - let (ra, rb) = (find(&mut parent, a), find(&mut parent, b)); - if ra != rb { - if let Some(x) = parent.get_mut(ra.max(rb)) { - *x = ra.min(rb); - } - merged_any = true; +/// `body` with its faces on one surface merged and its edges on one curve joined, except along +/// the lines in `keep` (its split lines, as Split Face made them): each face and edge of the +/// result comes from those of `body` as SMLib's history says (a merged face from every face +/// merged into it), over `[body]`. +pub(crate) fn heal(body: &Body, keep: &[Vec]) -> Result { + let _span = solidcraft_profile::span("kernel", "heal"); + let record = crate::native::brep_record(body)?; + // Each edge along a split line, by the point halfway along it. + let mut kept: Vec<[f64; 3]> = Vec::new(); + if !keep.is_empty() { + for e in 0..record.edges.len() { + let pts = edge_points(&record, e as u32); + if on_split_line(&pts, keep) { + let mid = pts.get(2).ok_or_else(|| KernelError::Failed(format!("healing: edge {e} has no middle point")))?; + kept.push([mid.x, mid.y, mid.z]); } } } - if !merged_any { - return None; - } - let mut groups: HashMap> = HashMap::new(); - for i in 0..faces.len() { - let r = find(&mut parent, i); - groups.entry(r).or_default().push(i); - } - let mut out: Vec = Vec::new(); - let mut from: Vec> = Vec::new(); - let mut order: Vec = groups.keys().copied().collect(); - order.sort_unstable(); - for g in order { - let members = groups.get(&g)?; - if members.len() == 1 { - out.push(faces.get(*members.first()?)?.clone()); - from.push(members.clone()); - continue; - } - let (n, _) = (*planes.get(*members.first()?)?)?; - // Oriented boundary edges of the group; edges used twice inside it are dropped. - let mut count: HashMap = HashMap::new(); - for m in members { - for e in faces.get(*m)?.boundary_iters().into_iter().flatten() { - *count.entry(e.id()).or_insert(0) += 1; - } - } - let mut rest: Vec = Vec::new(); - for m in members { - for e in faces.get(*m)?.boundary_iters().into_iter().flatten() { - if count.get(&e.id()).copied().unwrap_or(0) == 1 { - rest.push(e); - } - } - } - // Chain into loops. - let mut loops: Vec> = Vec::new(); - while let Some(first) = rest.pop() { - let start = first.front().clone(); - let mut cur = first.back().clone(); - let mut lp = vec![first]; - let mut guard = 0; - while cur != start && guard < 100_000 { - guard += 1; - let k = rest.iter().position(|e| e.front() == &cur)?; - let e = rest.remove(k); - cur = e.back().clone(); - lp.push(e); - } - loops.push(lp); - } - let (outer, holes): (Vec>, Vec>) = loops.into_iter().partition(|l| loop_area(l, n) > 0.0); - let surface = faces.get(*members.first()?)?.oriented_surface(); - for o in &outer { - let mut wires: Vec = vec![o.clone().into()]; - for h in &holes { - let probe = h.first().map(|e| from_p3(e.front().point()))?; - // The innermost outer loop around the hole owns it. - let owner = outer.iter().filter(|x| inside(probe, x, n)).min_by(|a, b| loop_area(a, n).total_cmp(&loop_area(b, n))); - if owner.is_some_and(|x| std::ptr::eq(x, o)) { - wires.push(h.clone().into()); - } - } - out.push(mt::Face::try_new(wires, surface.clone()).ok()?); - from.push(members.clone()); - } - } - Some((out.into(), from)) -} - -/// Join runs of collinear straight edges at vertices only they use: each run becomes one edge, -/// every face it borders is rebuilt once (linear in the shell, however long the runs; a faceted -/// body such as a modeled thread has thousands of such edges). -fn merge_collinear(shell: &mt::Shell, trace: &mut Trace) -> Option { - let mut faces: Vec = shell.face_iter().cloned().collect(); - let mut edges: Vec = Vec::new(); - let mut index: HashMap = HashMap::new(); - let mut at: HashMap> = HashMap::new(); - for f in &faces { - for e in f.edge_iter() { - if index.contains_key(&e.id()) { - continue; - } - index.insert(e.id(), edges.len()); - at.entry(e.front().id()).or_default().push(edges.len()); - at.entry(e.back().id()).or_default().push(edges.len()); - edges.push(e.absolute_clone()); - } - } - // Edges that continue each other in line through a vertex nothing else uses. - let mut parent: Vec = (0..edges.len()).collect(); - let mut any = false; - for (v, es) in &at { - let [ia, ib] = es[..] else { continue }; - let (Some(a), Some(b)) = (edges.get(ia), edges.get(ib)) else { continue }; - if !matches!(a.curve(), mt::Curve::Line(_)) || !matches!(b.curve(), mt::Curve::Line(_)) { - continue; - } - let other = |e: &mt::Edge| if e.front().id() == *v { e.back().clone() } else { e.front().clone() }; - let mid = if a.front().id() == *v { a.front().clone() } else { a.back().clone() }; - let (pa, pm, pb) = (from_p3(other(a).point()), from_p3(mid.point()), from_p3(other(b).point())); - let (Some(u), Some(w)) = ((pm - pa).normalized(), (pb - pm).normalized()) else { continue }; - if u.dot(w) > 1.0 - 1e-10 { - // The lesser root wins: each run's root is its first edge whatever order the - // vertices are met in (#707). - let (ra, rb) = (find(&mut parent, ia), find(&mut parent, ib)); - if ra != rb - && let Some(x) = parent.get_mut(ra.max(rb)) - { - *x = ra.min(rb); - any = true; - } - } - } - if !any { - return None; - } - // Ordered by run (and each run's ends by first use below): which end a joined edge starts - // from must not follow hash order, or the same heal gives a different body from run to run. - let mut runs: std::collections::BTreeMap> = std::collections::BTreeMap::new(); - for i in 0..edges.len() { - let r = find(&mut parent, i); - runs.entry(r).or_default().push(i); - } - // Each run's joined edge, and the position of its vertices along it. - let mut joined: Vec<(mt::Edge, HashMap)> = Vec::new(); - let mut run_of: HashMap = HashMap::new(); - for members in runs.values().filter(|m| m.len() > 1) { - let mut ends: Vec<(mt::VertexID, usize, mt::Vertex)> = Vec::new(); - for i in members { - let Some(e) = edges.get(*i) else { continue }; - for v in [e.front(), e.back()] { - match ends.iter_mut().find(|(id, ..)| *id == v.id()) { - Some(end) => end.1 += 1, - None => ends.push((v.id(), 1, v.clone())), - } - } - } - let mut ends = ends.into_iter().filter(|(_, n, _)| *n == 1).map(|(.., v)| v); - let (Some(first), Some(last), None) = (ends.next(), ends.next(), ends.next()) else { continue }; - // Walk the run from one end, collecting its vertices in order. - let mut order = vec![first.id()]; - let (mut cur, mut prev) = (first.id(), usize::MAX); - for _ in 0..members.len() { - let next = at.get(&cur).and_then(|es| es.iter().copied().find(|i| *i != prev && members.contains(i))); - let Some(e) = next.and_then(|i| edges.get(i).map(|e| (i, e))) else { break }; - cur = if e.1.front().id() == cur { e.1.back().id() } else { e.1.front().id() }; - prev = e.0; - order.push(cur); - } - if order.last() != Some(&last.id()) || order.len() != members.len() + 1 { - continue; - } - // Every piece must lie along the whole run, not just along its neighbour. - let Some(dir) = (from_p3(last.point()) - from_p3(first.point())).normalized() else { continue }; - let straight = members - .iter() - .filter_map(|i| edges.get(*i)) - .all(|e| (from_p3(e.back().point()) - from_p3(e.front().point())).normalized().is_some_and(|d| d.dot(dir).abs() > 1.0 - 1e-10)); - if !straight { - continue; - } - let line = builder::line(&first, &last); - trace.made_of(&line, members.iter().filter_map(|i| edges.get(*i)).map(|e| e.id())); - for i in members { - if let Some(e) = edges.get(*i) { - run_of.insert(e.id(), joined.len()); - } - } - joined.push((line, order.into_iter().enumerate().map(|(k, v)| (v, k)).collect())); - } - if joined.is_empty() { - return None; - } - for f in &mut faces { - if !f.edge_iter().any(|e| run_of.contains_key(&e.id())) { - continue; - } - let mut wires = Vec::new(); - for w in f.absolute_boundaries() { - let mut done = std::collections::HashSet::new(); - let mut es: Vec = Vec::new(); - for e in w.edge_iter() { - let Some(r) = run_of.get(&e.id()).copied() else { - es.push(e.clone()); - continue; - }; - // The run's pieces become its joined edge, in this wire's direction: once each - // way, as a seam runs along its wire both ways. - if let Some((line, pos)) = joined.get(r) { - let forward = pos.get(&e.front().id()) < pos.get(&e.back().id()); - if done.insert((r, forward)) { - es.push(if forward { line.clone() } else { line.inverse() }); - } - } - } - wires.push(mt::Wire::from(es)); - } - *f = absolute_face(f, wires)?; - } - Some(faces.into()) -} - -/// The exact curve an approximate edge (a boolean's intersection curve) really is: a line or a -/// circular arc, when every sample lies on it. -fn exact_curve(e: &mt::Edge, tol: f64) -> Option { - // Only the approximate curves booleans make; exact ones stay as they are. - if !matches!(e.curve(), mt::Curve::IntersectionCurve(_)) { - return None; - } - fit_exact(e, tol) -} - -/// A line or circular arc through the edge's samples, if they all lie on one. -fn fit_exact(e: &mt::Edge, tol: f64) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let pts: Vec = (0..=16).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 16.0))).collect(); - let (a, b) = (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point())); - if e.absolute_front() == e.absolute_back() || a.dist(b) < tol { - return None; - } - if pts.iter().all(|p| p.dist_to_segment(a, b) < tol) { - return Some(builder::line(e.absolute_front(), e.absolute_back())); - } - // A circle through the ends and the middle sample. - let m = *pts.get(8)?; - let n = (m - a).cross(b - a).normalized()?; - let (ab, am) = (b - a, m - a); - // Centre in the plane: solve |c-a| = |c-b| = |c-m|. - let d = 2.0 * ab.cross(am).len2(); - if d < 1e-300 { - return None; - } - // Circumcentre: a + (|u|² v×w + |v|² w×u) / (2|w|²), u = b−a, v = m−a, w = u×v. - let w = ab.cross(am); - let centre = a + (am.cross(w) * ab.len2() + w.cross(ab) * am.len2()) * (1.0 / d); - let r = centre.dist(a); - if pts.iter().all(|p| (p.dist(centre) - r).abs() < tol && (*p - a).dot(n).abs() < tol) { - return Some(builder::circle_arc(e.absolute_front(), e.absolute_back(), mt::Point3::new(m.x, m.y, m.z))); - } - None -} - -/// Replace approximate edges that are really lines or arcs with exact ones. -fn exact_edges(shell: &mt::Shell, tol: f64, trace: &mut Trace) -> Option { - let mut subst: HashMap = HashMap::new(); - for e in shell.edge_iter() { - if !subst.contains_key(&e.id()) - && let Some(x) = exact_curve(&e, tol) - { - trace.made(&x, [e.id()]); - subst.insert(e.id(), x); - } - } - if subst.is_empty() { - return None; - } - let mut faces = Vec::new(); - for f in shell.face_iter() { - let mut wires = Vec::new(); - for w in f.absolute_boundaries() { - let es: Vec = w - .edge_iter() - .map(|e| match subst.get(&e.id()) { - // The new edge runs absolute front → back; match this use's direction. - Some(n) => { - if e.front() == e.absolute_front() { - n.clone() - } else { - n.inverse() - } - } - None => e.clone(), - }) - .collect(); - wires.push(mt::Wire::from(es)); - } - faces.push(absolute_face(f, wires)?); - } - Some(faces.into()) -} - -/// Faces whose surface is flat but not a plane (a revolved line square to the axis, a swept -/// line) get a real plane, so they merge with their coplanar neighbours and blend like planes. -pub(crate) fn planar_surfaces(shell: &mt::Shell, tol: f64) -> Option { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let mut changed = false; - let mut faces = Vec::new(); - for f in shell.face_iter() { - let surf = f.surface(); - if matches!(surf, mt::Surface::Plane(_)) { - faces.push(f.clone()); - continue; - } - // Parameter box of the boundary, then a grid of surface points in it. - let mut uv: Vec<(f64, f64)> = Vec::new(); - let mut pts: Vec = Vec::new(); - for w in f.absolute_boundaries() { - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..6 { - let p = c.subs(t0 + (t1 - t0) * k as f64 / 6.0); - pts.push(from_p3(p)); - if let Some(x) = surf.search_nearest_parameter(p, uv.last().copied(), 50) { - uv.push(x); - } - } - } - } - if uv.len() < 3 || pts.len() < 3 { - faces.push(f.clone()); - continue; - } - let (u0, u1) = uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, x| (a.0.min(x.0), a.1.max(x.0))); - let (v0, v1) = uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, x| (a.0.min(x.1), a.1.max(x.1))); - for i in 0..=4 { - for j in 0..=4 { - pts.push(from_p3(surf.subs(u0 + (u1 - u0) * i as f64 / 4.0, v0 + (v1 - v0) * j as f64 / 4.0))); - } - } - // The plane through the points (normal from the surface). - let (um, vm) = ((u0 + u1) / 2.0, (v0 + v1) / 2.0); - let nn = surf.normal(um, vm); - let Some(n) = Vec3::new(nn.x, nn.y, nn.z).normalized() else { - faces.push(f.clone()); - continue; - }; - let o = from_p3(surf.subs(um, vm)); - if pts.iter().any(|p| (*p - o).dot(n).abs() > tol) { - faces.push(f.clone()); - continue; - } - let u = n.any_perp(); - let w = n.cross(u); - let plane = mt::Plane::new(crate::body::p3(o), crate::body::p3(o + u), crate::body::p3(o + w)); - match mt::Face::try_new(f.absolute_boundaries().clone(), mt::Surface::Plane(plane)) { - Ok(mut nf) => { - if !f.orientation() { - nf.invert(); - } - faces.push(nf); - changed = true; - } - Err(_) => faces.push(f.clone()), - } - } - changed.then(|| faces.into()) -} - -/// Heal a solid; returns the input unchanged when nothing applies or healing fails. -#[cfg(test)] -pub fn heal(solid: Solid, size: f64) -> Solid { - healed(solid, size, &[], false, false).0 -} - -/// What healing made each face and edge of its result from. -#[derive(Debug)] -pub(crate) struct HealMap { - /// For each face of the result (in its face order), the input faces it was made from (by - /// position in the input's face order): one, or several merged into it. - pub faces: Vec>, - /// For each edge of the result (by identity), the input edges it was made from (by - /// position in the input's edge order): one, or several joined into it. - pub edges: HashMap>, -} - -impl HealMap { - /// The history of the healed solid, from that of its input (`faces` in the input's face - /// order, each a region of operand faces; `edges` the origins of each edge, in its edge - /// order): a face healing merged from several is Merged when they came from several, the - /// rest keep their origins (see [`crate::record::regions`]). Faces in the healed solid's - /// face order, edges by identity. - pub(crate) fn carry(&self, faces: &[FaceProv], edges: &[Vec]) -> Option<(Vec, HashMap>)> { - let regions = self - .faces - .iter() - .map(|under| { - let whole = matches!(under.as_slice(), [i] if faces.get(*i).is_some_and(|f| f.change == Change::Kept)); - let mut origins = BTreeSet::new(); - for i in under { - origins.extend(faces.get(*i)?.origins.iter().copied()); - } - Some((origins, whole)) - }) - .collect::>>()?; - let edges = self - .edges - .iter() - .map(|(id, under)| { - let mut origins = BTreeSet::new(); - for i in under { - origins.extend(edges.get(*i)?.iter().cloned()); - } - Some((*id, origins.into_iter().collect())) - }) - .collect::>>()?; - Some((crate::record::regions(regions), edges)) - } - - /// Every face and edge of `solid` as itself (nothing healed). - fn identity(solid: &Solid) -> HealMap { - let faces = (0..solid.face_iter().count()).map(|i| vec![i]).collect(); - let edges = crate::record::edge_index(solid).into_iter().map(|(id, i)| (id, vec![i])).collect(); - HealMap { faces, edges } - } -} - -/// Heal a solid (the input unchanged when nothing applies or healing fails), keeping faces apart -/// along lines they were split along on purpose (`keep`), with what each face and edge of the -/// result was made from (`None` when that could not be followed). -pub(crate) fn heal_traced(solid: Solid, size: f64, keep: &[Vec]) -> (Solid, Option) { - healed(solid, size, keep, true, false) -} - -/// [`heal_traced`] that only merges coplanar neighbouring faces and joins the straight edges -/// they leave split in line (#1049), leaving every curve and surface as it is: for results -/// whose geometry is already exact (a prism boolean's). -pub(crate) fn merge_faces_traced(solid: Solid, size: f64, keep: &[Vec]) -> (Solid, Option) { - healed(solid, size, keep, true, true) -} - -/// The healed solid, and what it was made from when `traced`. -fn healed(solid: Solid, size: f64, keep: &[Vec], traced: bool, faces_only: bool) -> (Solid, Option) { - // Edges a boolean made are intersection curves, which panic where they no longer - // evaluate; the solid then stays as it is. - match crate::guard("heal", || Ok(heal_shells(&solid, size, keep, traced, faces_only))) { - Ok(Some((healed, map))) => (healed, map), - _ => { - let map = if traced { crate::guard("heal map", || Ok(HealMap::identity(&solid))).ok() } else { None }; - (solid, map) - } - } -} - -/// The input edges each edge made while healing comes from. Input edges live as long as the -/// healing (the input solid is borrowed throughout), so their identities are never reused; an -/// edge healing makes is recorded when it is made, from edges then alive, which overwrites any -/// entry left under its identity by an edge made earlier and dropped since. Records nothing -/// when not `on`. -struct Trace { - on: bool, - input: HashMap, - made: HashMap>, -} - -impl Trace { - /// The input edges under the live edge `id`. - fn of(&self, id: &mt::EdgeID) -> Vec { - match self.made.get(id) { - Some(from) => from.clone(), - None => self.input.get(id).map(|i| vec![*i]).unwrap_or_default(), - } - } - - /// `edge` was made from the live edges `from`. - fn made(&mut self, edge: &mt::Edge, from: [mt::EdgeID; N]) { - self.made_of(edge, from); - } - - /// `edge` was made from the live edges `from`, however many. - fn made_of(&mut self, edge: &mt::Edge, from: impl IntoIterator) { - if !self.on { - return; - } - let mut under: Vec = from.into_iter().flat_map(|id| self.of(&id)).collect(); - under.sort_unstable(); - under.dedup(); - self.made.insert(edge.id(), under); - } -} - -fn heal_shells(solid: &Solid, size: f64, keep: &[Vec], traced: bool, faces_only: bool) -> Option<(Solid, Option)> { - let tol = (size * 1e-7).max(1e-9); - let mut shells = Vec::new(); - let mut changed = false; - let input = if traced { crate::record::edge_index(solid) } else { HashMap::new() }; - let mut trace = Trace { on: traced, input, made: HashMap::new() }; - // Each face of the shells so far, as the input faces it was made from. - let mut faces: Vec> = Vec::new(); - let mut first = 0; - for sh in solid.boundaries() { - let mut cur = sh.clone(); - let count = cur.face_iter().count(); - let mut from: Vec> = (first..first + count).map(|i| vec![i]).collect(); - first += count; - // Faces come out in place, one for one, except where coplanar ones merge. - if !faces_only && let Some(m) = planar_surfaces(&cur, (size * 1e-7).max(1e-9)) { - cur = m; - changed = true; - } - if !faces_only && let Some(m) = exact_edges(&cur, (size * 1e-5).max(1e-7), &mut trace) { - cur = m; - changed = true; - } - if let Some((m, groups)) = merge_coplanar(&cur, tol, keep) { - cur = m; - from = groups.iter().map(|g| g.iter().filter_map(|i| from.get(*i)).flatten().copied().collect()).collect(); - changed = true; - } - // Straight edges the merged pieces leave split at vertices nothing else uses join - // into one, after any boolean (#1049): later features meet one edge, not the pieces. - if let Some(m) = merge_collinear(&cur, &mut trace) { - cur = m; - changed = true; - } - faces.extend(from); - shells.push(cur); - } - if !changed { - return None; - } - let healed = Solid::try_new(shells).ok()?; - if !traced { - return Some((healed, None)); - } - let edges: Option>> = crate::body::edge_order(healed.face_iter()) - .0 - .iter() - .map(|e| { - let under = trace.of(&e.id()); - (!under.is_empty()).then(|| (e.id(), under)) - }) - .collect(); - let map = edges.map(|edges| HealMap { faces, edges }); - Some((healed, map)) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Body; - - /// Distinct faces, edges and vertices of a shell (its iterators repeat shared ones). - fn counts(shell: &mt::Shell) -> (usize, usize, usize) { - let edges: std::collections::HashSet<_> = shell.edge_iter().map(|e| e.id()).collect(); - let vertices: std::collections::HashSet<_> = shell.vertex_iter().map(|v| v.id()).collect(); - (shell.face_iter().count(), edges.len(), vertices.len()) - } - - /// A prism whose front face was cut into `n` strips along a single line: the strips merge - /// into one face, which leaves `n` collinear pieces on each of its long edges. - fn strip_prism(n: usize) -> Solid { - let pts: Vec = (0..=n) - .map(|k| builder::vertex(mt::Point3::new(k as f64, 0.0, 0.0))) - .chain([builder::vertex(mt::Point3::new(n as f64, 3.0, 0.0)), builder::vertex(mt::Point3::new(0.0, 3.0, 0.0))]) - .collect(); - let pts: solidcraft_geom::Ring = pts.into(); - let edges: Vec = pts.edges().map(|(a, b)| builder::line(a, b)).collect(); - let face = builder::try_attach_plane(&[mt::Wire::from(edges)]).expect("a plane"); - builder::tsweep(&face, mt::Vector3::new(0.0, 0.0, 2.0)) - } - - /// Runs of collinear edges join in one pass, however long: past the 10 000 pieces the old - /// pairwise loop stopped at, and in time (a modeled thread has thousands of such pieces, - /// and filleting beside one froze the app). - #[test] - fn long_collinear_runs_join_whole() { - let n = 12_000; - let started = std::time::Instant::now(); - let healed = heal(strip_prism(n), n as f64); - let shell = healed.boundaries().first().expect("a shell").clone(); - assert_eq!(counts(&shell), (6, 12, 8)); - let body = Body::new(healed).expect("a valid body"); - let volume = crate::measure::measure(&body).expect("measures").volume; - assert!((volume - n as f64 * 3.0 * 2.0).abs() < 1e-6 * volume, "{volume}"); - assert!(started.elapsed().as_secs() < 30, "took {:?}", started.elapsed()); - } - - #[test] - fn short_collinear_runs_join_and_keep_the_corners() { - let healed = heal(strip_prism(3), 3.0); - let shell = healed.boundaries().first().expect("a shell").clone(); - assert_eq!(counts(&shell), (6, 12, 8)); - } - - #[test] - fn approximate_arcs_become_exact() { - // A cubic (non-rational) spline through a quarter circle. - let (a, b) = (builder::vertex(mt::Point3::new(10.0, 0.0, 0.0)), builder::vertex(mt::Point3::new(0.0, 10.0, 0.0))); - let pts: Vec = (0..=40) - .map(|k| { - let t = std::f64::consts::FRAC_PI_2 * k as f64 / 40.0; - Vec3::new(10.0 * t.cos(), 10.0 * t.sin(), 0.0) - }) - .collect(); - let curve = mt::Curve::BSplineCurve(crate::build::interpolate_cubic(&pts).expect("spline")); - let e = mt::Edge::new(&a, &b, curve); - let x = fit_exact(&e, 1e-2).expect("an arc"); - use mt::{BoundedCurve, ParametricCurve}; - let c = x.curve(); - let (t0, t1) = c.range_tuple(); - let mid = c.subs((t0 + t1) / 2.0); - assert!(((mid.x * mid.x + mid.y * mid.y).sqrt() - 10.0).abs() < 1e-9, "{mid:?}"); - } + let tolerance = record.tolerance * 10.0; + let (healed, history) = crate::offset_backend::run("healing", body, None, |b| b.merge_faces(&kept, tolerance))?; + Ok(healed.with_checked_history(history, &crate::record::counts(&[body])).with_split_lines(body.splits.clone())) } diff --git a/crates/kernel/src/helix.rs b/crates/kernel/src/helix.rs index 37b4a52c9..f774f4ce1 100644 --- a/crates/kernel/src/helix.rs +++ b/crates/kernel/src/helix.rs @@ -1,14 +1,11 @@ //! Helical sweeps (coils, springs) and lofts to a point (pyramids, cones). -use mt::builder; -use solidcraft_geom::{Grid, Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; -use truck_modeling as mt; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::Mesh; +use solidcraft_geom::prelude::*; -use crate::body::{Body, Solid, p3}; -use crate::build::{NetFit, cap_and_close, interpolate_net, uniform_wire}; -use crate::numbered::NumberedLoop; -use crate::record::{self, Side}; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::{KernelError, Result}; /// Rotate `v` about the unit axis `k` by `ang` (Rodrigues). fn rot(v: Vec3, k: Vec3, ang: f64) -> Vec3 { @@ -17,10 +14,50 @@ fn rot(v: Vec3, k: Vec3, ang: f64) -> Vec3 { /// Sweep a planar region's outer loop along a helix about `axis` through `axis_origin`: /// `turns` revolutions (right-handed about `axis`), rising `pitch` per turn. The profile keeps -/// its attitude relative to the axis, as a screw motion does. The walls are B-spline surfaces -/// (one per profile segment); if those cannot be built, ruled walls between stations 3° apart -/// stand in. +/// its attitude relative to the axis, as a screw motion does: SMLib's screw sweep, one wall per +/// profile segment. pub fn sweep_helix(plane: &Plane, region: &Region2, axis_origin: Vec3, axis: Vec3, pitch: f64, turns: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "sweep_helix"); + let (k, profile) = helix_profile(plane, region, axis_origin, axis, pitch, turns)?; + crate::smlib_sweeps::screw(plane, &crate::smlib_sweeps::pieces([&profile]), axis_origin, k, pitch, turns) +} + +/// [`sweep_helix`] with the profile moved off the axis as it turns: at turn t it first moves +/// `offset(t)` mm away from the axis (negative: towards it) in its half-plane, `offset` piecewise +/// linear through `law`'s (turn, offset) pairs, turns ascending within [0, `turns`]. A thread's +/// groove fading in or out over a runout: SMLib's radial screw sweep. +pub fn sweep_helix_radial( + plane: &Plane, + region: &Region2, + axis_origin: Vec3, + axis: Vec3, + pitch: f64, + turns: f64, + law: &[(f64, f64)], +) -> Result { + let _span = solidcraft_profile::span("kernel", "sweep_helix_radial"); + if law.is_empty() { + return sweep_helix(plane, region, axis_origin, axis, pitch, turns); + } + let (k, profile) = helix_profile(plane, region, axis_origin, axis, pitch, turns)?; + if !law.windows(2).all(|w| matches!(w, [a, b] if b.0 > a.0)) + || law.iter().any(|(t, o)| !(t.is_finite() && o.is_finite() && *t >= 0.0 && *t <= turns)) + { + return Err(KernelError::Invalid("helix: the radial law's turns must ascend within the sweep's turns".into())); + } + crate::smlib_sweeps::screw_radial(plane, &crate::smlib_sweeps::pieces([&profile]), axis_origin, k, pitch, turns, law) +} + +/// A helical sweep's axis and profile (the region's outer loop), checked: finite turns and +/// pitch, an area, and a profile that clears itself after one turn. +fn helix_profile( + plane: &Plane, + region: &Region2, + axis_origin: Vec3, + axis: Vec3, + pitch: f64, + turns: f64, +) -> Result<(Vec3, crate::numbered::NumberedLoop)> { let k = axis.normalized().ok_or_else(|| KernelError::Invalid("helix axis".into()))?; if !(pitch.is_finite() && turns.is_finite() && turns > 0.0 && turns <= 200.0 && pitch.abs() < 1e7 && axis_origin.is_finite()) { return Err(KernelError::Invalid("helix: turns must be in (0, 200] and the pitch finite".into())); @@ -38,37 +75,14 @@ pub fn sweep_helix(plane: &Plane, region: &Region2, axis_origin: Vec3, axis: Vec if turns > 1.0 && pitch.abs() <= extent { return Err(KernelError::Invalid(format!("the coil runs into itself: the pitch must exceed the section ({extent:.3} mm)"))); } - // One smooth B-spline wall per profile segment; the ruled walls below are the fallback. - if let Ok(b) = smooth_helix(plane, &profile, axis_origin, k, pitch, turns) { - return Ok(b); - } - let n = ((turns * 120.0).ceil() as usize).clamp(4, 24_000); - let total = std::f64::consts::TAU * turns; - let mut wires = Vec::with_capacity(n + 1); - for i in 0..=n { - let a = total * i as f64 / n as f64; - let lift = k * (pitch * a / std::f64::consts::TAU); - let o = axis_origin + rot(plane.origin - axis_origin, k, a) + lift; - let pl = Plane { origin: o, x: rot(plane.x, k, a), y: rot(plane.y, k, a) }; - wires.push(uniform_wire(&pl, lp)?); - } - guard("helix sweep", || { - // Every station's wire has the profile's segments, edge for edge. - let mut faces: Vec = Vec::new(); - for w in wires.windows(2) { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; - let sides = builder::try_wire_homotopy(a, b).map_err(|e| KernelError::Failed(format!("helix: {e}")))?; - faces.extend(record::ruled(&sides, a, b, &profile.from, &profile.from)); - } - let (Some(first), Some(last)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("helix".into())) }; - cap_and_close(faces, std::slice::from_ref(first), std::slice::from_ref(last), false) - }) + Ok((k, profile)) } /// A screw sweep of a convex polygon (in `plane`'s coordinates) as a closed triangle mesh, /// wound outward: `stations` sections per turn, flat end caps. Watertight by construction, for /// faceted booleans (modelled threads). pub fn sweep_helix_mesh(plane: &Plane, polygon: &[Vec2], axis_origin: Vec3, axis: Vec3, pitch: f64, turns: f64, stations: usize) -> Result { + let _span = solidcraft_profile::span("kernel", "sweep_helix_mesh"); let k = axis.normalized().ok_or_else(|| KernelError::Invalid("helix axis".into()))?; let m = polygon.len(); if !(pitch.is_finite() && turns.is_finite() && turns > 0.0 && turns <= 200.0 && (3..=64).contains(&m) && (8..=720).contains(&stations)) { @@ -104,85 +118,10 @@ pub fn sweep_helix_mesh(plane: &Plane, polygon: &[Vec2], axis_origin: Vec3, axis Ok(mesh) } -/// Samples per profile segment and stations per turn of the smooth helical walls. -const SEG_SAMPLES: usize = 12; -const STATIONS_PER_TURN: f64 = 12.0; - -/// Helical walls as B-spline surfaces: each profile segment, sampled at every station of the -/// screw motion, interpolated by cubics across the profile and then along the helix. -fn smooth_helix(plane: &Plane, profile: &NumberedLoop, o: Vec3, k: Vec3, pitch: f64, turns: f64) -> Result { - let lp = &profile.lp; - let nseg = lp.segs.len(); - if nseg == 0 || nseg > 64 { - return Err(KernelError::Invalid("helix profile".into())); - } - let n = ((turns * STATIONS_PER_TURN).ceil() as usize).clamp(4, 4800); - let total = std::f64::consts::TAU * turns; - let at = |i: usize, q: solidcraft_geom::Vec2| { - let a = total * i as f64 / n as f64; - let w = plane.to_world(q); - o + rot(w - o, k, a) + k * (pitch * a / std::f64::consts::TAU) - }; - let fail = |w: &str| KernelError::Failed(format!("smooth helix: {w}")); - // Per segment: the wall surface through its samples at every station. - let mut faces_data = Vec::with_capacity(nseg); - for s in &lp.segs { - // u along the helix (the stations), v along the profile segment. - let samples = - Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?; - faces_data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?); - } - guard("smooth helix", || { - let start: Vec = lp.segs.iter().map(|s| builder::vertex(p3(at(0, s.start())))).collect(); - let end: Vec = lp.segs.iter().map(|s| builder::vertex(p3(at(n, s.start())))).collect(); - let mut e0 = Vec::with_capacity(nseg); - let mut e1 = Vec::with_capacity(nseg); - let mut seams = Vec::with_capacity(nseg); - for (j, NetFit { u_ends: [c0, c1], v_ends: [seam, _], .. }) in faces_data.iter().enumerate() { - let (Some(a0), Some(b0), Some(a1), Some(b1)) = (start.get(j), start.get((j + 1) % nseg), end.get(j), end.get((j + 1) % nseg)) else { - return Err(fail("vertices")); - }; - e0.push(mt::Edge::try_new(a0, b0, mt::Curve::BSplineCurve(c0.clone())).map_err(|e| fail(&e.to_string()))?); - e1.push(mt::Edge::try_new(a1, b1, mt::Curve::BSplineCurve(c1.clone())).map_err(|e| fail(&e.to_string()))?); - seams.push(mt::Edge::try_new(a0, a1, mt::Curve::BSplineCurve(seam.clone())).map_err(|e| fail(&e.to_string()))?); - } - let mut walls = Vec::with_capacity(nseg); - for (j, NetFit { surface: surf, .. }) in faces_data.iter().enumerate() { - let (Some(a), Some(b), Some(sa), Some(sb)) = (e0.get(j), e1.get(j), seams.get(j), seams.get((j + 1) % nseg)) else { - return Err(fail("edges")); - }; - // Counter-clockwise in the surface's (u along the helix, v along the profile) space. - let w: mt::Wire = vec![sa.clone(), b.clone(), sb.inverse(), a.inverse()].into(); - let wall = mt::Face::try_new(vec![w], mt::Surface::BSplineSurface(surf.clone())).map_err(|e| fail(&e.to_string()))?; - walls.push((wall, Some(record::profile(profile.numbers(j))))); - } - let w0: mt::Wire = e0.iter().cloned().collect(); - let w1: mt::Wire = e1.iter().cloned().collect(); - // Either orientation of the walls; keep the one that measures as a proper solid. - let expected = lp_area_path(plane, lp, o, k, turns); - // A coarse mesh (within ~10%) is enough to tell a proper solid from an empty or inside-out one. - let section_tol = (lp.signed_area().abs().sqrt() * 0.05).max(1e-3); - for ws in [walls.clone(), walls.iter().map(|(f, prov)| (f.inverse(), prov.clone())).collect()] { - if let Ok(b) = cap_and_close(ws, std::slice::from_ref(&w0), std::slice::from_ref(&w1), false) - && b.tessellate(section_tol).is_ok_and(|m| (m.measure().volume - expected).abs() <= 0.15 * expected.abs()) - { - return Ok(b); - } - } - Err(fail("the walls do not close into the expected solid")) - }) -} - -/// Pappus estimate of a screw sweep's volume: section area × the centroid's path around the axis. -fn lp_area_path(plane: &Plane, lp: &Loop2, o: Vec3, k: Vec3, turns: f64) -> f64 { - let c = plane.to_world(lp.centroid()); - let d = c - o; - let r = (d - k * d.dot(k)).len(); - lp.signed_area().abs() * std::f64::consts::TAU * r * turns -} - -/// A solid from a planar loop of straight segments to an apex point off its plane (a pyramid). +/// A solid from a planar loop of straight segments to an apex point off its plane (a pyramid): +/// SMLib's loft to a point. pub fn loft_to_point(plane: &Plane, lp: &Loop2, apex: Vec3) -> Result { + let _span = solidcraft_profile::span("kernel", "loft_to_point"); if !apex.is_finite() || lp.segs.is_empty() || lp.segs.len() > 10_000 { return Err(KernelError::Invalid("loft to a point: bad section or apex".into())); } @@ -195,43 +134,12 @@ pub fn loft_to_point(plane: &Plane, lp: &Loop2, apex: Vec3) -> Result { // Wind the base so its normal points away from the apex. let above = (apex - plane.origin).dot(plane.normal()) > 0.0; let base = crate::numbered::number_loops([lp]).pop().ok_or_else(|| KernelError::Invalid("loft to a point: bad section".into()))?.oriented(above); - let lp = &base.lp; - guard("loft to point", || { - let verts: Vec = lp.segs.iter().map(|s| builder::vertex(p3(plane.to_world(s.start())))).collect(); - let top = builder::vertex(p3(apex)); - let m = verts.len(); - let edges: Vec = (0..m).filter_map(|i| Some(builder::line(verts.get(i)?, verts.get((i + 1) % m)?))).collect(); - let sides: Vec = verts.iter().map(|v| builder::line(v, &top)).collect(); - let mut faces = Vec::with_capacity(m + 1); - // History as the faces are made: the base is the section (the start cap), each - // triangle comes from its base segment. - let mut history = Vec::with_capacity(m + 1); - let bw: mt::Wire = edges.iter().cloned().collect(); - faces.push(builder::try_attach_plane(&[bw]).map_err(|e| KernelError::Failed(format!("loft base: {e}")))?); - history.push(record::cap(false)); - for i in 0..m { - let (Some(e), Some(up), Some(down)) = (edges.get(i), sides.get((i + 1) % m), sides.get(i)) else { continue }; - // Triangle i: along the base edge, up to the apex, back down — opposite to the base's winding. - let w: mt::Wire = vec![e.inverse(), down.clone(), up.inverse()].into(); - faces.push(builder::try_attach_plane(&[w]).map_err(|e| KernelError::Failed(format!("loft side: {e}")))?); - history.push(record::profile(base.numbers(i))); - } - let shell: mt::Shell = faces.into(); - let body = match Solid::try_new(vec![shell.clone()]) { - Ok(s) => Body::new(s)?, - Err(_) => { - let inv: mt::Shell = shell.face_iter().map(|f| f.inverse()).collect(); - Body::new(Solid::try_new(vec![inv]).map_err(|e| KernelError::Failed(format!("loft to point: {e}")))?)? - } - }; - record::attach(body, &[], Some(history), Default::default()) - }) + crate::smlib_sweeps::loft_to_point(plane, &crate::smlib_sweeps::pieces([&base]), apex) } #[cfg(test)] mod tests { use super::*; - use solidcraft_geom::Vec2; #[test] fn coil_volume_is_section_times_helix_length() { @@ -241,7 +149,8 @@ mod tests { let region = Region2 { outer: Loop2::circle(Vec2::new(20.0, 0.0), 2.0), holes: vec![] }; let b = sweep_helix(&pl, ®ion, Vec3::ZERO, Vec3::Z, 8.0, 3.0).unwrap(); let v = crate::measure(&b).unwrap().volume; - assert_eq!(b.face_count(), 4, "two smooth walls and two caps"); + // SMLib sweeps the circle (one segment) as one smooth wall. + assert_eq!(b.face_count(), 3, "one smooth wall and two caps"); let want = std::f64::consts::PI * 4.0 * std::f64::consts::TAU * 20.0 * 3.0; assert!((v - want).abs() / want < 1e-3, "{v} vs {want}"); assert!(sweep_helix(&pl, ®ion, Vec3::ZERO, Vec3::Z, 3.0, 3.0).is_err(), "pitch below the section"); diff --git a/crates/kernel/src/history.rs b/crates/kernel/src/history.rs index 938283b3d..b50d9e339 100644 --- a/crates/kernel/src/history.rs +++ b/crates/kernel/src/history.rs @@ -1,8 +1,8 @@ //! Exact face and edge history: for each face and edge of an operation's result, what it came //! from among the operation's operands, recorded by the code that built it (never sampled). //! -//! Indices are positions in a body's face order (`face_iter`) and edge order (`unique_edges`, -//! the order of [`Body::edges`] and of a tessellation's edges). Operand numbers are positions in +//! Indices are positions in a body's record (canonical face and edge order, the order of +//! [`Body::edges`] and of a mesh's edges). Operand numbers are positions in //! the operation's own operand list, which each operation documents. A body made by an //! operation carries its history (see [`Body::history`]); [`History::substitute`] composes an //! operation with one that made one of its operands. @@ -15,164 +15,40 @@ //! history here gives its faces attachments with no attachment code of its own. An operation //! that can't should leave its result without one (`Body::without_history`), never guess. -use std::collections::BTreeSet; +pub use solidcore_record::brep::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History, Side}; -use crate::body::{Body, FaceSource, Solid}; +use crate::body::{Body, FaceSource}; use crate::{KernelError, Result}; +use solidcore_record::brep::{Brep, part::Part}; -/// Where a result face came from. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)] -pub enum FaceOrigin { - /// A face of input `operand` (its index in the operand's face order). - Face { operand: usize, face: usize }, - /// Swept from segment `segment` of the profile's loops (in order: outer, then holes). - Profile { segment: usize }, - /// The start or end cap of a sweep (the profile itself, or where it ends up). - Cap { end: bool }, - /// Made in place of edge `edge` of input `operand` (a fillet or chamfer). - Edge { operand: usize, edge: usize }, - /// An offset of face `face` of input `operand` (a shell's inner wall). - Offset { operand: usize, face: usize }, -} - -/// How a result face relates to its origins. -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum Change { - /// The same face as its origin (same region). - Kept, - /// Its origin's surface, trimmed differently. - Modified, - /// One of several result faces made from one input face. - Split, - /// Made from several input faces (coplanar or cosurface faces joined). - Merged, - /// New to the operation (no input face under it). - Generated, -} - -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct FaceProv { - pub origins: Vec, - pub change: Change, -} - -/// One side of a meeting: the origins of the face on that side of the edge. One origin, or -/// several where that face was made from several (a merged face) and the edge lies along it -/// as a whole. Never empty; sorted, without repeats, so equal sides compare equal. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)] -pub struct Side(Vec); - -impl Side { - /// The side made of `origins` (in any order, repeats allowed); `None` when there are none. - pub fn new(origins: impl IntoIterator) -> Option { - let side = Side::canonical(origins.into_iter().collect()); - (!side.0.is_empty()).then_some(side) - } - - /// Its origins, sorted. - pub fn origins(&self) -> &[FaceOrigin] { - &self.0 - } - - /// The side's one origin, when it has exactly one. - pub fn single(&self) -> Option { - match self.0.as_slice() { - [o] => Some(*o), - _ => None, - } - } - - /// The same side with each origin mapped by `f` (failing where `f` does). - fn try_map(&self, f: impl Fn(FaceOrigin) -> Result) -> Result { - Ok(Side::canonical(self.0.iter().map(|o| f(*o)).collect::>()?)) - } - - /// The same side with each origin's operand renumbered by `f`. - fn map_operand(&self, f: impl Fn(usize) -> usize) -> Side { - Side::canonical(self.0.iter().map(|o| o.map_operand(&f)).collect()) - } - - /// `origins` sorted, without repeats. - fn canonical(mut origins: Vec) -> Side { - origins.sort_unstable(); - origins.dedup(); - Side(origins) +impl From for KernelError { + fn from(e: solidcore_record::brep::history::Failed) -> KernelError { + KernelError::Failed(e.to_string()) } } -impl From for Side { - fn from(origin: FaceOrigin) -> Side { - Side(vec![origin]) - } -} - -/// Where a result edge came from. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)] -pub enum EdgeOrigin { - /// (Part of) edge `edge` of input `operand`. - Edge { operand: usize, edge: usize }, - /// Where two faces meet that met nowhere before (a boolean's intersection curve): the - /// origins of the face on each side, `a <= b` (made with [`EdgeOrigin::meet`]). - Meet { a: Side, b: Side }, -} - -/// A result edge: the result faces it separates and what it came from (empty when it is new -/// and lies between faces new to the operation). -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct EdgeProv { - pub faces: Vec, - pub origins: Vec, -} - -/// History of an operation's result: one entry per face and per edge, in the result's orders. -#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct History { - /// How many operands the operation had. - pub operands: usize, - pub faces: Vec, - pub edges: Vec, -} - -fn failed(detail: &str) -> KernelError { - KernelError::Failed(format!("history: {detail}")) -} - -impl FaceOrigin { - /// The same origin with its operand (if it has one) renumbered by `f`. - fn map_operand(self, f: impl Fn(usize) -> usize) -> FaceOrigin { - match self { - FaceOrigin::Face { operand, face } => FaceOrigin::Face { operand: f(operand), face }, - FaceOrigin::Edge { operand, edge } => FaceOrigin::Edge { operand: f(operand), edge }, - FaceOrigin::Offset { operand, face } => FaceOrigin::Offset { operand: f(operand), face }, - other => other, - } - } -} - -impl EdgeOrigin { - /// Where the faces with origins `a` and `b` (sides, or single origins) meet, in canonical - /// order (the lesser side first). - pub fn meet(a: impl Into, b: impl Into) -> EdgeOrigin { - let (a, b) = (a.into(), b.into()); - if a <= b { EdgeOrigin::Meet { a, b } } else { EdgeOrigin::Meet { a: b, b: a } } - } - - /// The same origin with its operands renumbered by `f`. - fn map_operand(&self, f: impl Fn(usize) -> usize) -> EdgeOrigin { - match self { - EdgeOrigin::Edge { operand, edge } => EdgeOrigin::Edge { operand: f(*operand), edge: *edge }, - EdgeOrigin::Meet { a, b } => EdgeOrigin::meet(a.map_operand(&f), b.map_operand(&f)), - } - } -} - -impl History { +/// What a [`History`] needs a kernel body for: the history types belong to +/// `solidcore_record::brep::history`, so a backend can report them without this crate. +pub trait BodyHistory { /// The history of an operation that keeps every face and edge of its one operand in place /// (a rigid move, a rebuild that keeps the topology's order). - pub fn identity(body: &Body) -> History { + fn identity(body: &Body) -> History; + /// Check that this history describes `result` made from `operands`: one entry per face and + /// edge, and every origin within its operand's faces and edges. + fn check(&self, result: &Body, operands: &[&Body]) -> Result<()>; + /// The result's face sources, carried from its operands' through this history: a face + /// kept, modified or split from one face keeps that face's source; a merged face keeps the + /// source its origins share, if they share one; a generated face has none. + fn face_sources(&self, operands: &[&Body]) -> Vec>; +} + +impl BodyHistory for History { + /// The history of an operation that keeps every face and edge of its one operand in place + /// (a rigid move, a rebuild that keeps the topology's order). + fn identity(body: &Body) -> History { let faces = (0..body.face_count()).map(|face| FaceProv { origins: vec![FaceOrigin::Face { operand: 0, face }], change: Change::Kept }).collect(); - let edges = edge_faces(&body.solid) + let edges = edge_faces(body.record()) .into_iter() .enumerate() .map(|(edge, faces)| EdgeProv { faces, origins: vec![EdgeOrigin::Edge { operand: 0, edge }] }) @@ -182,208 +58,15 @@ impl History { /// Check that this history describes `result` made from `operands`: one entry per face and /// edge, and every origin within its operand's faces and edges. - pub fn check(&self, result: &Body, operands: &[&Body]) -> Result<()> { + fn check(&self, result: &Body, operands: &[&Body]) -> Result<()> { let counts: Vec<(usize, usize)> = operands.iter().map(|b| (b.face_count(), b.edge_count())).collect(); - self.check_counts((result.face_count(), result.edge_count()), &counts) - } - - /// [`History::check`] against the result's and each operand's face and edge counts. - pub(crate) fn check_counts(&self, result: (usize, usize), counts: &[(usize, usize)]) -> Result<()> { - if self.operands != counts.len() { - return Err(failed("operand count does not match")); - } - if self.faces.len() != result.0 || self.edges.len() != result.1 { - return Err(failed("entries do not match the result's faces and edges")); - } - let face_ok = |o: &FaceOrigin| match *o { - FaceOrigin::Face { operand, face } | FaceOrigin::Offset { operand, face } => counts.get(operand).is_some_and(|c| face < c.0), - FaceOrigin::Edge { operand, edge } => counts.get(operand).is_some_and(|c| edge < c.1), - FaceOrigin::Profile { .. } | FaceOrigin::Cap { .. } => true, - }; - if !self.faces.iter().all(|f| f.origins.iter().all(face_ok)) { - return Err(failed("a face origin lies outside its operand")); - } - for e in &self.edges { - if e.faces.iter().any(|f| *f >= self.faces.len()) { - return Err(failed("an edge lies on a face outside the result")); - } - let ok = e.origins.iter().all(|o| match o { - EdgeOrigin::Edge { operand, edge } => counts.get(*operand).is_some_and(|c| *edge < c.1), - EdgeOrigin::Meet { a, b } => a.origins().iter().chain(b.origins()).all(face_ok), - }); - if !ok { - return Err(failed("an edge origin lies outside its operand")); - } - if e.origins.iter().any(|o| matches!(o, EdgeOrigin::Meet { a, b } if a > b)) { - return Err(failed("a meeting's sides are out of order")); - } - } - Ok(()) - } - - /// Compose with the history of the operation that made operand `k`: origins on operand `k` - /// become that operation's origins, its operands (none, for a body made from a sketch) - /// taking `k`'s place in the operand list; a meeting's side becomes the origins of the faces - /// it names (several where that operation merged faces). Fails, without changing `self`, - /// where a lineage cannot be expressed (an offset of a face that operation generated or - /// merged, a blend of an edge it generated, a meeting with a face it made from nothing). - pub fn substitute(&mut self, k: usize, inner: &History) -> Result<()> { - if k >= self.operands { - return Err(failed("no such operand")); - } - let n = inner.operands; - // Operands before k stay, k's come in at k, those after k move by n - 1. - let outer = |op: usize| if op < k { op } else { op + n - 1 }; - let lifted = |op: usize| op + k; - let inner_face = |face: usize| inner.faces.get(face).ok_or_else(|| failed("a face origin lies outside the inner result")); - let inner_edge = |edge: usize| inner.edges.get(edge).ok_or_else(|| failed("an edge origin lies outside the inner result")); - // A face origin as origins of the composed operation, with the inner face's change. - let map_face = |o: FaceOrigin| -> Result<(Vec, Option)> { - match o { - FaceOrigin::Face { operand, face } if operand == k => { - let p = inner_face(face)?; - Ok((p.origins.iter().map(|x| x.map_operand(lifted)).collect(), Some(p.change))) - } - FaceOrigin::Offset { operand, face } if operand == k => match inner_face(face)?.origins.as_slice() { - [FaceOrigin::Face { operand, face }] => Ok((vec![FaceOrigin::Offset { operand: lifted(*operand), face: *face }], None)), - _ => Err(failed("an offset of a face the inner operation generated or merged")), - }, - FaceOrigin::Edge { operand, edge } if operand == k => match inner_edge(edge)?.origins.as_slice() { - [EdgeOrigin::Edge { operand, edge }] => Ok((vec![FaceOrigin::Edge { operand: lifted(*operand), edge: *edge }], None)), - _ => Err(failed("a blend of an edge the inner operation generated")), - }, - other => Ok((vec![other.map_operand(outer)], None)), - } - }; - let mut faces = Vec::with_capacity(self.faces.len()); - for f in &self.faces { - let mut origins = BTreeSet::new(); - let mut kept = f.change == Change::Kept; - for o in &f.origins { - let (os, change) = map_face(*o)?; - origins.extend(os); - kept &= change.is_none_or(|c| c == Change::Kept); - } - let origins: Vec = origins.into_iter().collect(); - let change = if f.change == Change::Generated || !origins.iter().any(|o| matches!(o, FaceOrigin::Face { .. })) { - Change::Generated - } else if origins.len() > 1 { - Change::Merged - } else if kept { - Change::Kept - } else { - Change::Modified - }; - faces.push(FaceProv { origins, change }); - } - // Split where an origin lies under several composed faces (pieces the inner operation - // split and this one joined back, or dropped all but one of, are not). - crate::record::mark_shared_split(&mut faces); - // One side of a meeting: the origins of what its faces were made from. - let side = |s: &Side| -> Result { - let mut origins = Vec::new(); - for o in s.origins() { - origins.extend(map_face(*o)?.0); - } - Side::new(origins).ok_or_else(|| failed("an edge meets a face the inner operation made from nothing")) - }; - let mut edges = Vec::with_capacity(self.edges.len()); - for e in &self.edges { - let mut origins = BTreeSet::new(); - for o in &e.origins { - match o { - EdgeOrigin::Edge { operand, edge } if *operand == k => { - origins.extend(inner_edge(*edge)?.origins.iter().map(|x| x.map_operand(lifted))) - } - EdgeOrigin::Edge { .. } => { - origins.insert(o.map_operand(outer)); - } - EdgeOrigin::Meet { a, b } => { - origins.insert(EdgeOrigin::meet(side(a)?, side(b)?)); - } - } - } - edges.push(EdgeProv { faces: e.faces.clone(), origins: origins.into_iter().collect() }); - } - self.operands = self.operands + n - 1; - self.faces = faces; - self.edges = edges; - Ok(()) - } - - /// Renumber the operands: operand `i` becomes `map[i]` of `operands` (several may become - /// one, which joins their origins), or is dropped (`None`), which fails, without changing - /// `self`, where an origin lies on it. - pub(crate) fn renumber(&mut self, map: &[Option], operands: usize) -> Result<()> { - if map.len() != self.operands || map.iter().flatten().any(|op| *op >= operands) { - return Err(failed("operand map does not match")); - } - let to = |op: usize| map.get(op).copied().flatten().ok_or_else(|| failed("an origin lies on a dropped operand")); - let face = |o: FaceOrigin| -> Result { - Ok(match o { - FaceOrigin::Face { operand, face } => FaceOrigin::Face { operand: to(operand)?, face }, - FaceOrigin::Edge { operand, edge } => FaceOrigin::Edge { operand: to(operand)?, edge }, - FaceOrigin::Offset { operand, face } => FaceOrigin::Offset { operand: to(operand)?, face }, - other => other, - }) - }; - let mut faces = Vec::with_capacity(self.faces.len()); - for f in &self.faces { - let origins: BTreeSet = f.origins.iter().map(|o| face(*o)).collect::>()?; - // Origins that became one are one face: no longer a merge. - let change = if f.change == Change::Merged && origins.len() == 1 { Change::Modified } else { f.change }; - faces.push(FaceProv { origins: origins.into_iter().collect(), change }); - } - let mut edges = Vec::with_capacity(self.edges.len()); - for e in &self.edges { - let origins: BTreeSet = e - .origins - .iter() - .map(|o| match o { - EdgeOrigin::Edge { operand, edge } => Ok(EdgeOrigin::Edge { operand: to(*operand)?, edge: *edge }), - EdgeOrigin::Meet { a, b } => Ok(EdgeOrigin::meet(a.try_map(face)?, b.try_map(face)?)), - }) - .collect::>()?; - edges.push(EdgeProv { faces: e.faces.clone(), origins: origins.into_iter().collect() }); - } - self.operands = operands; - self.faces = faces; - self.edges = edges; - Ok(()) - } - - /// [`History::renumber`], consuming. - pub(crate) fn renumbered(mut self, map: &[Option], operands: usize) -> Result { - self.renumber(map, operands)?; - Ok(self) - } - - /// [`History::substitute`], consuming. - pub(crate) fn substituted(mut self, k: usize, inner: &History) -> Result { - self.substitute(k, inner)?; - Ok(self) - } - - /// This history, whose operand `i` was made by the operation `parts[i]` describes (all of - /// them over the same operands), as a history over those operands. - pub(crate) fn over(mut self, parts: &[&History]) -> Result { - let n = parts.first().map_or(0, |p| p.operands); - if parts.len() != self.operands || parts.iter().any(|p| p.operands != n) { - return Err(failed("operand histories do not match")); - } - // Each part's operands come in at its place: then part i's operand j is i * n + j. - for (k, part) in parts.iter().enumerate().rev() { - self.substitute(k, part)?; - } - let map: Vec> = (0..self.operands).map(|op| op.checked_rem(n)).collect(); - self.renumber(&map, n)?; - Ok(self) + Ok(self.check_counts((result.face_count(), result.edge_count()), &counts)?) } /// The result's face sources, carried from its operands' through this history: a face /// kept, modified or split from one face keeps that face's source; a merged face keeps the /// source its origins share, if they share one; a generated face has none. - pub fn face_sources(&self, operands: &[&Body]) -> Vec> { + fn face_sources(&self, operands: &[&Body]) -> Vec> { let source = |o: &FaceOrigin| match *o { FaceOrigin::Face { operand, face } => operands.get(operand).and_then(|b| b.face_sources()).and_then(|s| s.get(face)).cloned().flatten(), _ => None, @@ -402,9 +85,56 @@ impl History { } } -/// The faces each edge separates, in the body's edge order. -pub(crate) fn edge_faces(solid: &Solid) -> Vec> { - crate::body::edge_order(solid.face_iter()).1 +/// The faces each edge separates, in the record's edge order: each face it bounds, once, in the +/// order of the edge's uses. +pub(crate) fn edge_faces(record: &Brep) -> Vec> { + record + .edges + .iter() + .map(|e| { + let mut faces: Vec = Vec::with_capacity(e.uses.len()); + for u in &e.uses { + if !faces.contains(&(u.face as usize)) { + faces.push(u.face as usize); + } + } + faces + }) + .collect() +} + +/// The history of a part cut from, or a compound joined of, records numbered one after another +/// (`counts`: each operand's faces and edges, in order): every face and edge of the part is its +/// operand's own, kept. +pub(crate) fn of_part(part: &Part, counts: &[(usize, usize)]) -> History { + // Operand and local index of an item numbered across the operands one after another. + let locate = |mut i: usize, pick: fn(&(usize, usize)) -> usize| { + for (operand, c) in counts.iter().enumerate() { + if i < pick(c) { + return (operand, i); + } + i -= pick(c); + } + (counts.len(), i) + }; + let faces = part + .faces + .iter() + .map(|&f| { + let (operand, face) = locate(f as usize, |c| c.0); + FaceProv { origins: vec![FaceOrigin::Face { operand, face }], change: Change::Kept } + }) + .collect(); + let edges = part + .edges + .iter() + .zip(edge_faces(&part.brep)) + .map(|(&e, faces)| { + let (operand, edge) = locate(e as usize, |c| c.1); + EdgeProv { faces, origins: vec![EdgeOrigin::Edge { operand, edge }] } + }) + .collect(); + History { operands: counts.len(), faces, edges } } #[cfg(test)] diff --git a/crates/kernel/src/history_tests.rs b/crates/kernel/src/history_tests.rs index 7ce1c10ce..13fdc31e8 100644 --- a/crates/kernel/src/history_tests.rs +++ b/crates/kernel/src/history_tests.rs @@ -1,6 +1,8 @@ -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History, Side}; +use crate::history::BodyHistory; use crate::{Body, box_solid, transform}; fn face(operand: usize, face: usize) -> FaceOrigin { @@ -32,11 +34,11 @@ fn a_transform_keeps_every_face_and_edge_in_place() { assert!(rot(before).dist(after) < 1e-6, "{before:?} → {after:?}"); } // Each edge separates the same faces it did. - let (ea, em) = (super::edge_faces(&a.solid), super::edge_faces(&moved.solid)); + let (ea, em) = (super::edge_faces(a.record()), super::edge_faces(moved.record())); assert_eq!(ea, em); assert!(h.edges.iter().all(|e| e.faces.len() == 2 && e.origins.len() == 1)); // The history's edges are the tessellation's edges, bounding the same faces. - let mesh = moved.tessellate(1e-3).unwrap(); + let mesh = moved.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap(); let mesh_faces: Vec> = mesh.edge_faces.iter().map(|fs| fs.iter().map(|f| *f as usize).collect()).collect(); assert_eq!(mesh_faces, h.edges.iter().map(|e| e.faces.clone()).collect::>()); } @@ -65,7 +67,7 @@ fn substitute_a_body_made_from_a_sketch() { #[test] fn bodies_without_reported_history_have_none() { let a = box_solid(Vec3::ZERO, Vec3::new(4.0, 3.0, 1.0)).unwrap(); - let bare = Body::new(a.deep_copy()).unwrap(); + let bare = Body::from_record(a.record().clone()).unwrap(); assert!(bare.history().is_none()); } @@ -249,12 +251,12 @@ fn face_sources_follow_kept_split_and_agreeing_merged_faces() { /// side face over both pieces, not two coplanar faces with an edge between them (#1788). #[test] fn collinear_profile_lines_extrude_into_one_side_face() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; let pts = [(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)].map(|(x, y)| Vec2::new(x, y)); let region = Region2 { outer: Loop2::polygon(&pts), holes: vec![] }; // Plain `extrude` keeps a face per segment (sheet metal's flat pattern relies on it). assert_eq!(crate::extrude(&Plane::XY, std::slice::from_ref(®ion), 0.0, 5.0).unwrap()[0].face_count(), 7); - let body = crate::extrude_whole_sides(&Plane::XY, &[region], 0.0, 5.0).unwrap().pop().unwrap(); + let body = crate::extrude_whole_sides(&Plane::XY, &[region], 0.0, 5.0, &|_, _| false).unwrap().pop().unwrap(); assert_eq!(body.face_count(), 6, "a box has six faces"); assert!((crate::measure(&body).unwrap().volume - 1000.0).abs() < 1e-9); let h = body.history().unwrap(); @@ -274,23 +276,88 @@ fn collinear_profile_lines_extrude_into_one_side_face() { ); // A corner is not a straight run: an L-shaped step keeps its faces. let step = [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0), (20.0, 5.0), (20.0, 10.0), (0.0, 10.0)].map(|(x, y)| Vec2::new(x, y)); - let body = crate::extrude_whole_sides(&Plane::XY, &[Region2 { outer: Loop2::polygon(&step), holes: vec![] }], 0.0, 5.0).unwrap().pop().unwrap(); + let body = crate::extrude_whole_sides(&Plane::XY, &[Region2 { outer: Loop2::polygon(&step), holes: vec![] }], 0.0, 5.0, &|_, _| false) + .unwrap() + .pop() + .unwrap(); assert_eq!(body.face_count(), 8); } +/// The pieces of one ellipse (four conic quarters) or one spline (its cubic spans) that the +/// caller calls one curve sweep into one wall generated by all of them, the same solid as a face +/// per piece: the ellipse's volume is π a b h. Pieces not called one curve keep a face each. +#[test] +fn pieces_of_one_curve_extrude_into_one_wall() { + use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; + let v = Vec2::new; + let (c, u, w) = (v(1.0, 2.0), v(10.0, 0.0), v(0.0, 5.0)); + let corners = [c + u, c + w, c - u, c - w]; + let ellipse: Vec = (0..4) + .map(|i| { + let (a, b) = (corners[i], corners[(i + 1) % 4]); + Seg2::Conic { a, apex: a + b - c, b, w: std::f64::consts::FRAC_1_SQRT_2 } + }) + .collect(); + // A cubic spline's three spans (C2 at its joints, on unequal knot spans), closed by lines. + let spline = vec![ + Seg2::Cubic { + p0: v(0.0, 0.0), + p1: v(3.478154619431441, -1.9606112245268097), + p2: v(6.956309238862882, -3.921222449053619), + p3: v(10.0, -3.0), + }, + Seg2::Cubic { + p0: v(10.0, -3.0), + p1: v(13.55861013478923, -1.9229288384169465), + p2: v(16.52332013301099, 3.0935296384274267), + p3: v(20.0, 4.0), + }, + Seg2::Cubic { + p0: v(20.0, 4.0), + p1: v(23.067612954017893, 4.799814860722723), + p2: v(26.533806477008945, 2.3999074303613614), + p3: v(30.0, 0.0), + }, + Seg2::Line { a: v(30.0, 0.0), b: v(30.0, 20.0) }, + Seg2::Line { a: v(30.0, 20.0), b: v(0.0, 20.0) }, + Seg2::Line { a: v(0.0, 20.0), b: v(0.0, 0.0) }, + ]; + for (segs, walls, pieces) in [(ellipse, 1, 4), (spline, 4, 3)] { + let region = Region2 { outer: Loop2 { segs }, holes: vec![] }; + let apart = crate::extrude_whole_sides(&Plane::XY, std::slice::from_ref(®ion), 0.0, 7.0, &|_, _| false).unwrap().remove(0); + let body = crate::extrude_whole_sides(&Plane::XY, std::slice::from_ref(®ion), 0.0, 7.0, &|_, _| true).unwrap().remove(0); + assert_eq!(apart.face_count(), 2 + walls - 1 + pieces, "a face per piece when they are not one curve"); + assert_eq!(body.face_count(), 2 + walls, "one wall over the curve's pieces"); + let (joined, each) = (crate::measure(&body).unwrap().volume, crate::measure(&apart).unwrap().volume); + assert!((joined - each).abs() < 1e-9 * each, "{joined} vs {each}"); + let h = body.history().unwrap(); + h.check(&body, &[]).unwrap(); + let curved: Vec> = h.faces.iter().map(|f| f.origins.clone()).filter(|o| o.len() > 1).collect(); + assert_eq!(curved.len(), 1, "{:?}", h.faces); + let mut segments: Vec = + curved[0].iter().filter_map(|o| if let FaceOrigin::Profile { segment } = o { Some(*segment) } else { None }).collect(); + segments.sort(); + assert_eq!(segments, (0..pieces).collect::>(), "the wall is generated by every piece of the curve"); + if walls == 1 { + let exact = std::f64::consts::PI * 10.0 * 5.0 * 7.0; + assert!((joined - exact).abs() < 1e-6 * exact, "{joined} vs π a b h = {exact}"); + } + } +} + /// A tapered extrude joins a side drawn in collinear pieces as the straight extrude does /// (#1788): one sloped face generated by both pieces, and the same solid as a side in one piece. #[test] fn collinear_profile_lines_taper_into_one_side_face() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; let polygon = |pts: &[(f64, f64)]| Region2 { outer: Loop2::polygon(&pts.iter().map(|&(x, y)| Vec2::new(x, y)).collect::>()), holes: vec![] }; let split = polygon(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)]); let whole = polygon(&[(0.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)]); let taper = 5f64.to_radians(); for (from, to, foot) in [(0.0, 5.0, 0.0), (-1.0, 5.0, 1.0)] { - let body = crate::extrude_tapered_between(&Plane::XY, &split, from, to, foot, 1.0, taper).unwrap(); - let reference = crate::extrude_tapered_between(&Plane::XY, &whole, from, to, foot, 1.0, taper).unwrap(); + let body = crate::extrude_tapered_between(&Plane::XY, &split, from, to, foot, 1.0, taper, crate::DraftCorner::default()).unwrap(); + let reference = crate::extrude_tapered_between(&Plane::XY, &whole, from, to, foot, 1.0, taper, crate::DraftCorner::default()).unwrap(); assert_eq!(body.face_count(), reference.face_count(), "{from}..{to} foot {foot}: as many faces as one piece"); let (v, w) = (crate::measure(&body).unwrap().volume, crate::measure(&reference).unwrap().volume); assert!((v - w).abs() < 1e-9 * w, "{v} vs {w}"); diff --git a/crates/kernel/src/iges_in.rs b/crates/kernel/src/iges_in.rs index 7a6765b5b..36715d2ee 100644 --- a/crates/kernel/src/iges_in.rs +++ b/crates/kernel/src/iges_in.rs @@ -288,7 +288,8 @@ fn parse(text: &str) -> R { /// A model curve segment ready for an edge: STEP curve id, its end points, points a quarter and /// three quarters of the way along and one at the middle (for matching shared edges), and -/// whether the curve runs from `b` to `a`. +/// whether the curve runs from `b` to `a`; and its geometry, for a curve that has to be made to +/// end where its piece meets the next ([`Tr::closed`]). #[derive(Clone, Copy, Debug)] struct Seg { curve: u64, @@ -298,11 +299,28 @@ struct Seg { q3: V3, mid: V3, rev: bool, + shape: Shape, +} + +/// A segment's curve as it can be rebuilt: a line, or the B-spline `Tr::splines[i]`; another +/// curve keeps its ends. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Shape { + Line, + Spline(usize), + Other, } impl Seg { fn along(curve: u64, f: impl Fn(f64) -> V3) -> Seg { - Seg { curve, a: f(0.0), b: f(1.0), q: f(0.25), q3: f(0.75), mid: f(0.5), rev: false } + Seg { curve, a: f(0.0), b: f(1.0), q: f(0.25), q3: f(0.75), mid: f(0.5), rev: false, shape: Shape::Other } + } + fn with(self, shape: Shape) -> Seg { + Seg { shape, ..self } + } + /// Its length, along the points it keeps. + fn length(&self) -> f64 { + norm(sub(self.q, self.a)) + norm(sub(self.mid, self.q)) + norm(sub(self.q3, self.mid)) + norm(sub(self.b, self.q3)) } fn reversed(self) -> Seg { Seg { a: self.b, b: self.a, q: self.q3, q3: self.q, rev: !self.rev, ..self } @@ -343,6 +361,7 @@ fn perp(z: V3) -> V3 { } /// A rational B-spline curve evaluated by de Boor's algorithm. +#[derive(Clone)] struct Nurbs { deg: usize, knots: Vec, @@ -431,8 +450,8 @@ struct Tr<'a> { curve_work: usize, /// Composite curves (102) on the path being expanded. composites: Vec, - /// Farthest a trim loop's end was moved to close a gap (mm; see `close_gaps`). - snapped: f64, + /// The B-splines of segments ([`Shape::Spline`]). + splines: Vec, } fn xf_key(x: &Xf) -> [u64; 12] { @@ -539,7 +558,7 @@ impl<'a> Tr<'a> { let dd = self.o.dir(d); let v = self.o.add(format!("VECTOR('',#{dd},{})", r(norm(sub(b, a))))); let c = self.o.add(format!("LINE('',#{pa},#{v})")); - Ok(vec![Seg::along(c, |t| add(a, mul(sub(b, a), t)))]) + Ok(vec![Seg::along(c, |t| add(a, mul(sub(b, a), t))).with(Shape::Line)]) } 100 => { let Arc { c, rad, a0, a1 } = self.arc(seq)?; @@ -577,7 +596,9 @@ impl<'a> Tr<'a> { nb.eval(t0 + (t1 - t0) * k as f64 / 4.0).ok_or_else(|| format!("entity {seq}: B-spline cannot be evaluated"))?; } let c = self.write_nurbs_curve(&nb); - Ok(vec![Seg::along(c, |t| nb.eval(t0 + (t1 - t0) * t).unwrap_or([0.0; 3]))]) + let seg = Seg::along(c, |t| nb.eval(t0 + (t1 - t0) * t).unwrap_or([0.0; 3])); + self.splines.push(nb); + Ok(vec![seg.with(Shape::Spline(self.splines.len() - 1))]) } 104 => { // Ellipse (form 1) in canonical position: A x² + C y² + F = 0. @@ -970,6 +991,59 @@ impl<'a> Tr<'a> { Nurbs { deg: m2, knots: t_knots, pts: column }.eval(v).ok_or_else(|| "surface cannot be evaluated".into()) } + /// Segment `s` made to run from `pa` to `pb`, the vertices its piece meets the pieces before + /// and after it at. A line is the line between them; a clamped B-spline has its end control + /// points moved onto them (it ends at them exactly, its shape inside changed by no more than + /// the gap). Any other curve keeps its ends, and the gap is reported. + fn closed(&mut self, s: &Seg, pa: V3, pb: V3) -> Seg { + let gap = norm(sub(s.a, pa)).max(norm(sub(s.b, pb))); + if gap <= self.tol { + return *s; + } + match s.shape { + Shape::Line if norm(sub(pb, pa)) > self.tol => { + let (p, d) = (self.o.point(pa), unit(sub(pb, pa)).unwrap_or([1.0, 0.0, 0.0])); + let dd = self.o.dir(d); + let v = self.o.add(format!("VECTOR('',#{dd},{})", r(norm(sub(pb, pa))))); + let c = self.o.add(format!("LINE('',#{p},#{v})")); + return Seg::along(c, |t| add(pa, mul(sub(pb, pa), t))).with(Shape::Line); + } + Shape::Spline(i) => { + if let Some(mut nb) = self.splines.get(i).cloned() { + let (n, p) = (nb.pts.len(), nb.deg); + let clamped = n > p + && nb.knots.len() == n + p + 1 + && nb.knots[..=p].iter().all(|k| *k == nb.knots[0]) + && nb.knots[n..].iter().all(|k| *k == nb.knots[n + p]); + if clamped { + // The curve runs from `a` to `b`, or from `b` to `a` when reversed. + let (start, end) = if s.rev { (pb, pa) } else { (pa, pb) }; + for (k, q) in [(0, start), (n - 1, end)] { + let w = nb.pts[k][3]; + nb.pts[k] = [q[0] * w, q[1] * w, q[2] * w, w]; + } + let (t0, t1) = nb.range(); + let c = self.write_nurbs_curve(&nb); + let seg = Seg::along(c, |t| nb.eval(t0 + (t1 - t0) * t).unwrap_or([0.0; 3])); + self.splines.push(nb); + let seg = seg.with(Shape::Spline(self.splines.len() - 1)); + return if s.rev { seg.reversed() } else { seg }; + } + } + } + _ => {} + } + let near = if norm(sub(s.a, pa)) >= norm(sub(s.b, pb)) { pa } else { pb }; + self.warn(format!( + "trim curve pieces miss each other by {} mm at ({}, {}, {}): the gap is left open within the vertex's tolerance", + r(gap), + r(near[0]), + r(near[1]), + r(near[2]) + )); + *s + } + /// 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> { @@ -1004,7 +1078,8 @@ impl<'a> Tr<'a> { continue; // a pole } let c = self.write_nurbs_curve(&nb); - let seg = Seg::along(c, |t| ev(t).unwrap_or([0.0; 3])); + let seg = Seg::along(c, |t| ev(t).unwrap_or([0.0; 3])).with(Shape::Spline(self.splines.len())); + self.splines.push(nb.clone()); out.push(if rev { seg.reversed() } else { seg }); } Ok(out) @@ -1075,6 +1150,10 @@ impl Sewer { /// the segment runs along it. fn edge(&mut self, s: &Seg) -> (usize, bool) { let (a, b) = (self.vertex(s.a), self.vertex(s.b)); + self.edge_between(s, a, b) + } + /// [`Sewer::edge`] for a segment from vertex `a` to vertex `b`. + fn edge_between(&mut self, s: &Seg, a: usize, b: usize) -> (usize, bool) { let key = (a.min(b), a.max(b)); let close = |x: V3, y: V3| norm(sub(x, y)) <= self.tol * 10.0 + 1e-9; if let Some(list) = self.by_ends.get(&key) { @@ -1233,6 +1312,7 @@ fn write_shell(o: &mut Out, sw: &Sewer, faces: &[FaceB], styles: &mut Vec<(u64, /// This was the one importer stage outside every panic guard, so a panic here reached the CLI /// and the wasm build, where nothing catches it. pub fn iges_to_step(text: &str) -> std::result::Result<(String, Vec), String> { + let _span = solidcraft_profile::span("import", "iges.to_step"); crate::guard("IGES import", || translate(text).map_err(crate::KernelError::Invalid)).map_err(|e| match e { crate::KernelError::Invalid(m) => m, other => other.to_string(), @@ -1243,7 +1323,7 @@ fn translate(text: &str) -> std::result::Result<(String, Vec), String> { if text.len() > MAX_IGES_BYTES { return Err("IGES file too large".into()); } - let f = parse(text)?; + let f = solidcraft_profile::scope("import", "iges.parse", || parse(text))?; let tol = (f.resolution * f.unit).clamp(1e-6, 0.05).max(1e-5); let mut t = Tr { f: &f, @@ -1253,13 +1333,12 @@ fn translate(text: &str) -> std::result::Result<(String, Vec), String> { surf_cache: HashMap::new(), curve_work: 0, composites: Vec::new(), - snapped: 0.0, + splines: Vec::new(), }; // Header: units and context. let mm = t.o.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); let rad = t.o.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))"); let sr = t.o.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())"); - let unc_line = t.o.lines.len(); let unc = t.o.add(format!("UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{mm},'distance_accuracy_value','')", r(tol))); let ctx = t.o.add(format!( "(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{unc}))GLOBAL_UNIT_ASSIGNED_CONTEXT((#{mm},#{rad},#{sr}))REPRESENTATION_CONTEXT('',''))" @@ -1305,13 +1384,6 @@ fn translate(text: &str) -> std::result::Result<(String, Vec), String> { } } assembly.write(&mut t, &seqs, &solids, &mut styles, ctx)?; - if t.snapped > 0.0 { - // The STEP reader takes vertices up to ten times the stated accuracy off their curves: - // state enough to cover the ends `close_gaps` moved, and no more. - if let Some(l) = t.o.lines.get_mut(unc_line) { - *l = format!("UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{mm},'distance_accuracy_value','')", r(tol.max(t.snapped * 0.2))); - } - } 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})")); @@ -1366,11 +1438,7 @@ fn sew_surfaces( Err(e) => t.warn(format!("surface {seq}: not read: {e}")), } } - close_gaps(t, &mut drafts, sw.tol); - for d in drafts { - let loops = d.loops.iter().map(|l| l.iter().map(|s| sw.edge(s)).collect()).collect(); - faces.push(FaceB { surface: d.surface, sense: true, loops, color: d.color }); - } + faces.extend(sew(t, sw, drafts)); if faces.is_empty() { return Ok(Vec::new()); } @@ -1441,75 +1509,97 @@ const MAX_TRIM_GAP: f64 = 0.1; /// ...and a gap must also be at most this share of the shorter piece on either side. const MAX_TRIM_GAP_SHARE: f64 = 0.05; -/// Close the small gaps between consecutive pieces of the faces' trim loops. Some exporters -/// write each piece's model-space curve separately, and consecutive pieces can then miss by a -/// few micrometres to a tenth of a millimetre, well past the file's stated resolution: the loop -/// does not close, its face is lost and the shell stays open. The two ends of each such gap, and -/// every other piece end at either of them (the neighbouring faces at that corner), move to -/// their mean, so all the faces there sew to one vertex. A gap wider than `MAX_TRIM_GAP`, or not -/// small next to its pieces, is left open; the sewing tolerance stays the file's. -fn close_gaps(t: &mut Tr, faces: &mut [Draft], tol: f64) { - let length = |s: &Seg| norm(sub(s.q, s.a)) + norm(sub(s.mid, s.q)) + norm(sub(s.q3, s.mid)) + norm(sub(s.b, s.q3)); - // The gaps' ends as vertices, joined into groups (union-find). - let mut ends = Sewer { tol, verts: Vec::new(), grid: HashMap::new(), edges: Vec::new(), by_ends: HashMap::new() }; - let mut parent: Vec = Vec::new(); - let root = |parent: &[usize], mut i: usize| { - while let Some(&p) = parent.get(i).filter(|p| **p != i) { +/// Faces read from trimmed surfaces, sewn by their shared edges. A boundary loop is one closed +/// curve: each piece ends where the next one starts (IGES 5.3, 4.24 composite curve, and +/// 4.34/4.35 a trimmed surface's boundaries are closed curves). Some exporters write each +/// piece's model-space curve separately, and consecutive pieces can then miss by a few +/// micrometres to a tenth of a millimetre, well past the file's stated resolution. Each meeting +/// point of two pieces is then still one vertex, unless the gap is wider than `MAX_TRIM_GAP` or +/// not small next to its pieces (`MAX_TRIM_GAP_SHARE`): past that the ends may be different +/// corners of the model, and the gap stays open. The vertex goes where most of the piece ends +/// meeting there agree (the neighbouring faces at that corner), and a piece that misses it is +/// made to end there ([`Tr::closed`]): the edges then meet at their vertices exactly, as the +/// file means them to, and the sewing tolerance stays the file's. +fn sew(t: &mut Tr, sw: &mut Sewer, faces: Vec) -> Vec { + // Every piece's end vertices, then the vertices each meeting point joins made one. + let ends: Vec>> = + faces.iter().map(|f| f.loops.iter().map(|l| l.iter().map(|s| [sw.vertex(s.a), sw.vertex(s.b)]).collect()).collect()).collect(); + let mut same: Vec = (0..sw.verts.len()).collect(); + fn root(same: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = same.get(i) { + if p == i { + break; + } + let up = same.get(p).copied().unwrap_or(p); + if let Some(slot) = same.get_mut(i) { + *slot = up; + } i = p; } i - }; - for l in faces.iter().flat_map(|f| f.loops.iter()) { - for (i, prev) in l.iter().enumerate() { - let Some(next) = l.get((i + 1) % l.len()) else { continue }; - let gap = norm(sub(next.a, prev.b)); - if gap <= tol || gap > MAX_TRIM_GAP || gap > MAX_TRIM_GAP_SHARE * length(prev).min(length(next)) { - continue; - } - let (a, b) = (ends.vertex(prev.b), ends.vertex(next.a)); - while parent.len() < ends.verts.len() { - parent.push(parent.len()); - } - let (ra, rb) = (root(&parent, a), root(&parent, b)); - if let Some(x) = parent.get_mut(ra) { - *x = rb; - } - } } - if ends.verts.is_empty() { - return; - } - // Each group's mean; a group that spreads wider than a gap may be is left alone. - let mut sums: HashMap = HashMap::new(); - for (i, p) in ends.verts.iter().enumerate() { - let e = sums.entry(root(&parent, i)).or_insert(([0.0; 3], 0)); - e.0 = add(e.0, *p); - e.1 += 1; - } - let mean: HashMap = sums.into_iter().map(|(r, (s, n))| (r, mul(s, 1.0 / n as f64))).collect(); - let mut to: Vec> = ends.verts.iter().enumerate().map(|(i, _)| mean.get(&root(&parent, i)).copied()).collect(); - for (i, p) in ends.verts.iter().enumerate() { - if to.get(i).copied().flatten().is_some_and(|m| norm(sub(m, *p)) > MAX_TRIM_GAP / 2.0) { - let r = root(&parent, i); - for (k, x) in to.iter_mut().enumerate() { - if root(&parent, k) == r { - *x = None; + for (f, fe) in faces.iter().zip(&ends) { + for (l, le) in f.loops.iter().zip(fe) { + for (k, (prev, e)) in l.iter().zip(le).enumerate() { + let (Some(next), Some(next_ends)) = (l.get((k + 1) % l.len()), le.get((k + 1) % le.len())) else { continue }; + let gap = norm(sub(next.a, prev.b)); + if gap > MAX_TRIM_GAP || gap > MAX_TRIM_GAP_SHARE * prev.length().min(next.length()) { + continue; + } + let (a, b) = (root(&mut same, e[1]), root(&mut same, next_ends[0])); + if let Some(slot) = same.get_mut(a.max(b)) { + *slot = a.min(b); } } } } - let mut moved = 0.0f64; - let mut snap = |p: &mut V3| { - if let Some(m) = ends.find(*p).and_then(|i| to.get(i).copied().flatten()) { - moved = moved.max(norm(sub(m, *p))); - *p = m; + // The piece ends at each joined vertex, and the vertex where most of them are. + let mut at: HashMap> = HashMap::new(); + for (f, fe) in faces.iter().zip(&ends) { + for (l, le) in f.loops.iter().zip(fe) { + for (s, [a, b]) in l.iter().zip(le) { + at.entry(root(&mut same, *a)).or_default().push(s.a); + at.entry(root(&mut same, *b)).or_default().push(s.b); + } } - }; - for s in faces.iter_mut().flat_map(|f| f.loops.iter_mut()).flat_map(|l| l.iter_mut()) { - snap(&mut s.a); - snap(&mut s.b); } - t.snapped = t.snapped.max(moved); + for (v, pts) in at { + let agree = |p: V3| pts.iter().filter(|q| norm(sub(**q, p)) <= sw.tol).count(); + let Some(here) = sw.verts.get(v).copied() else { continue }; + let mut best = (agree(here), here); + for p in &pts { + let n = agree(*p); + if n > best.0 { + best = (n, *p); + } + } + if let Some(slot) = sw.verts.get_mut(v) { + *slot = best.1; + } + } + faces + .into_iter() + .zip(ends) + .map(|(f, ends)| { + let loops = f + .loops + .iter() + .zip(ends) + .map(|(l, e)| { + l.iter() + .zip(e) + .map(|(s, [a, b])| { + let (a, b) = (root(&mut same, a), root(&mut same, b)); + let (pa, pb) = (sw.verts.get(a).copied().unwrap_or(s.a), sw.verts.get(b).copied().unwrap_or(s.b)); + let s = t.closed(s, pa, pb); + sw.edge_between(&s, a, b) + }) + .collect() + }) + .collect(); + FaceB { surface: f.surface, sense: true, loops, color: f.color } + }) + .collect() } /// A trimmed (144) or bounded (143) surface, or a bare B-spline surface, as a face. @@ -1588,10 +1678,16 @@ fn cos_curve(t: &mut Tr, seq: i64, xf: &Xf, surface: i64) -> R> { } /// 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. +/// at the end nearer `start` (when known), else at its end away from the second piece. 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, start: Option, tol: f64) -> Vec { - let mut prev = start; + let from_second = || { + let (f, n) = (segs.first()?, segs.get(1)?); + let to_second = |p: V3| norm(sub(p, n.a)).min(norm(sub(p, n.b))); + Some(if to_second(f.a) < to_second(f.b) { f.b } else { f.a }) + }; + let mut prev = start.or_else(from_second); segs.into_iter() .map(|s| { let s = match prev { @@ -1776,6 +1872,7 @@ fn brep_edge(t: &mut Tr, sw: &mut Sewer, list: i64, ndx: i64, xf: &Xf) -> R<(usi /// Read IGES text: its solids, or its surfaces sewn into shells, as the STEP reader gives them. pub fn iges_import(text: &str) -> crate::Result { + let _span = solidcraft_profile::span("import", "iges.import"); let (step, warnings) = iges_to_step(text).map_err(crate::KernelError::Invalid)?; let mut imp = crate::step_import(&step)?; imp.warnings.splice(0..0, warnings); diff --git a/crates/kernel/src/iges_in/tests.rs b/crates/kernel/src/iges_in/tests.rs index b253f3b19..1d181b0fd 100644 --- a/crates/kernel/src/iges_in/tests.rs +++ b/crates/kernel/src/iges_in/tests.rs @@ -1,6 +1,7 @@ use super::*; use crate::{Body, BoolOp, ExportBody, StepHeader, boolean, box_solid, cylinder, fillet, iges_export_bodies, measure, sphere, torus}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; fn rel(a: f64, b: f64) -> f64 { (a - b).abs() / b.abs().max(1e-9) @@ -138,7 +139,7 @@ fn an_arc_revolved_about_its_centre_is_a_cap_not_a_ball() { ]; 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 mesh = imp.bodies[0].body.mesh(&crate::MeshTolerance::chord(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() { @@ -361,11 +362,59 @@ fn surfaces_in_separate_groups_remain_separate_parts() { } } +/// The box of [`trimmed_surfaces_sew_into_a_solid`] with its edge (0, 0, 0)–(0, 20, 0) stopping +/// 0.01 mm short of its corner in both faces that use it, its next pieces starting at the +/// corner. The pieces of a trim curve run on from one another, so the edge ends at the corner the +/// other three edges there agree on, exactly: a closed box SMLib finds valid. The edge was left +/// short with the gap on the vertex's tolerance, 2000 times the file's resolution (#3845). +#[test] +fn trim_pieces_that_miss_their_corner_are_closed_onto_it() { + 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 short = [0.0, 19.99, 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(); + 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])); + 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 (p0, p1) in [(a, b), (b, cc), (cc, d), (d, a)] { + // The short edge: its end at (0, 20, 0) is 0.01 short. + let (p0, p1) = match (p0, p1) { + ([0.0, 0.0, 0.0], [0.0, 20.0, 0.0]) => (p0, short), + ([0.0, 20.0, 0.0], [0.0, 0.0, 0.0]) => (short, p1), + x => x, + }; + 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::>().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(), "{:?}", imp.warnings); + assert!(imp.bodies[0].closed); + let body = &imp.bodies[0].body; + let check = body.smlib().unwrap().check(solidcraft_smlib::CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{check}"); + for v in &body.record().vertices { + assert!(v.tolerance <= body.record().tolerance, "a vertex {:?} kept a gap in its tolerance {}", v.point, v.tolerance); + } + let m = measure(body).unwrap(); + assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "{} {}", m.volume, m.area); +} + #[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 // apex and straight back). - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; let plate = box_solid(Vec3::new(-20.0, -15.0, 0.0), Vec3::new(20.0, 15.0, 10.0)).unwrap(); let profile = Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 2.0), Vec2::new(4.0, 5.0), Vec2::new(4.0, 11.0), Vec2::new(0.0, 11.0)]), holes: vec![] }; @@ -557,5 +606,4 @@ fn a_curve_over_a_tiny_knot_span_still_bounds_its_faces() { fn the_global_sections_native_system_becomes_the_originating_system() { let imp = round_trip(&box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap()); assert_eq!(imp.system, "SolidCraft"); - assert_eq!(imp.preprocessor, "SolidCraft IGES"); } diff --git a/crates/kernel/src/iges_out.rs b/crates/kernel/src/iges_out.rs index ae9fb327a..a53768512 100644 --- a/crates/kernel/src/iges_out.rs +++ b/crates/kernel/src/iges_out.rs @@ -1,14 +1,18 @@ -//! IGES 5.3 export, written from the published specification: each body as a manifold solid -//! B-rep (186) with its shell, faces, loops, edge and vertex lists, on analytic surfaces -//! (planes, cylinders, cones, spheres, tori), surfaces of revolution and extrusion, and -//! rational B-splines, with body names (406 name properties) and colours (314). The bodies are -//! first written as STEP (so faces are merged and surfaces recognised exactly as in a STEP -//! export) and restated entity by entity. +//! IGES 5.3 export, written from the published specification: each body's record as manifold +//! solid B-reps (186, one per material region, with its voids) and open shells (514 form 2), +//! with their faces, loops, edge and vertex lists, on analytic surfaces (planes, cylinders, +//! cones, spheres, tori), surfaces of revolution and rational B-splines, with body names (406 +//! name properties) and colours (314). Geometry is the record's, exact, in the same STEP form +//! the STEP export writes ([`solidcraft_step::write::topology`]); IGES loops run +//! counter-clockwise about their surface's normal. use std::collections::HashMap; use std::fmt::Write as _; -use crate::step_in::p21::{self, Exchange, Param}; +use solidcore_record::brep::{Brep, Loop, Shell}; +use solidcraft_step::geom::{Curve, Placement, Surface}; +use solidcraft_step::write::topology; + use crate::{ExportBody, KernelError, Result, StepHeader}; type V3 = [f64; 3]; @@ -22,13 +26,6 @@ fn dot(a: V3, b: V3) -> f64 { fn cross(a: V3, b: V3) -> V3 { [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] } -fn norm(a: V3) -> f64 { - dot(a, a).sqrt() -} -fn unit(a: V3) -> Option { - let n = norm(a); - (n > 1e-300 && n.is_finite()).then(|| a.map(|x| x / n)) -} /// A real in IGES free format (always with a decimal point). fn real(x: f64) -> String { @@ -64,6 +61,8 @@ struct Ent { struct W { ents: Vec, colors: HashMap<[u32; 3], i64>, + /// The largest coordinate written (the global section's maximum coordinate). + max_coord: f64, } impl W { @@ -74,8 +73,14 @@ impl W { fn get_mut(&mut self, de: i64) -> Option<&mut Ent> { usize::try_from((de - 1) / 2).ok().and_then(|i| self.ents.get_mut(i)) } + /// Coordinates of a model point, noted for the maximum coordinate. + fn coords(&mut self, p: V3) -> [String; 3] { + self.max_coord = p.iter().fold(self.max_coord, |m, x| if x.is_finite() { m.max(x.abs()) } else { m }); + p.map(real) + } fn point(&mut self, p: V3) -> i64 { - self.add(116, 0, vec![real(p[0]), real(p[1]), real(p[2])]) + let c = self.coords(p); + self.add(116, 0, c.to_vec()) } fn direction(&mut self, d: V3) -> i64 { self.add(123, 0, vec![real(d[0]), real(d[1]), real(d[2])]) @@ -100,137 +105,50 @@ impl W { } } -/// Reading the STEP exchange. -struct S<'a> { - ex: &'a Exchange, +fn failed(what: impl std::fmt::Display) -> KernelError { + KernelError::Failed(format!("IGES export: {what}")) } -impl<'a> S<'a> { - fn e(&self, id: u64) -> Result<&'a p21::Entity> { - self.ex.get(id).ok_or_else(|| KernelError::Failed(format!("IGES export: missing #{id}"))) - } - fn r(&self, p: Option<&Param>) -> Result { - p.and_then(Param::as_ref_id).ok_or_else(|| KernelError::Failed("IGES export: bad reference".into())) - } - fn f(&self, p: Option<&Param>) -> Result { - p.and_then(Param::as_f64).ok_or_else(|| KernelError::Failed("IGES export: bad number".into())) - } - fn list(&self, p: Option<&'a Param>) -> Result<&'a [Param]> { - p.and_then(Param::as_list).ok_or_else(|| KernelError::Failed("IGES export: bad list".into())) - } - fn point(&self, id: u64) -> Result { - let e = self.e(id)?; - let c = self.list(e.params().get(1))?; - Ok([self.f(c.first())?, self.f(c.get(1))?, self.f(c.get(2))?]) - } - fn dir(&self, id: u64) -> Result { - let d = self.point(id)?; - unit(d).ok_or_else(|| KernelError::Failed("IGES export: zero direction".into())) - } - fn vertex(&self, id: u64) -> Result { - self.point(self.r(self.e(id)?.params().get(1))?) - } - /// AXIS2_PLACEMENT_3D: origin, z, x. - fn placement(&self, id: u64) -> Result<(V3, V3, V3)> { - let p = self.e(id)?.params(); - let o = self.point(self.r(p.get(1))?)?; - let z = match p.get(2).and_then(Param::as_ref_id) { - Some(d) => self.dir(d)?, - None => [0.0, 0.0, 1.0], - }; - let x0 = match p.get(3).and_then(Param::as_ref_id) { - Some(d) => self.dir(d)?, - None => [1.0, 0.0, 0.0], - }; - let x = unit(sub(x0, z.map(|c| c * dot(x0, z)))).unwrap_or_else(|| { - let a = if z[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; - unit(sub(a, z.map(|c| c * dot(a, z)))).unwrap_or([1.0, 0.0, 0.0]) - }); - Ok((o, z, x)) - } +/// The record's surface parameters' frame axes, as IGES's analytic surfaces take them. +fn axes(p: &Placement) -> (V3, V3, V3) { + (p.origin, p.axis, p.ref_direction) } -/// B-spline data of a STEP curve or surface record set: degrees, control rows, weights, knots. -struct Spline { - deg: Vec, - pts: Vec>, - weights: Option>>, - knots: Vec>, +/// A B-spline (126) of degree `degree` on full `knots`, over `[t0, t1]`. +fn bspline_curve(w: &mut W, degree: usize, knots: &[f64], weights: &[f64], points: &[V3], [t0, t1]: [f64; 2]) -> i64 { + let rational = weights.iter().any(|x| (x - 1.0).abs() > 1e-12); + let mut p = vec![ + points.len().saturating_sub(1).to_string(), + degree.to_string(), + "0".into(), + "0".into(), + if rational { "0" } else { "1" }.into(), + "0".into(), + ]; + p.extend(knots.iter().map(|x| real(*x))); + p.extend(weights.iter().map(|x| real(*x))); + for q in points { + p.extend(w.coords(*q)); + } + p.extend([real(t0), real(t1), real(0.0), real(0.0), real(0.0)]); + w.add(126, 0, p) } -fn expand(mults: &[Param], knots: &[Param]) -> Option> { - let mut out = Vec::new(); - for (m, k) in mults.iter().zip(knots) { - let (m, k) = (m.as_i64()?, k.as_f64()?); - if !(1..=64).contains(&m) { - return None; +/// Full knots of a STEP B-spline (each repeated by its multiplicity). +fn full_knots(knots: &[f64], mults: &[usize]) -> Vec { + knots.iter().zip(mults).flat_map(|(k, m)| std::iter::repeat_n(*k, *m)).collect() +} + +/// The curve over `[t0, t1]` as an IGES entity running from `a` to `b` (the edge's vertices at +/// its interval's ends); `closed` when they are one vertex. The DE pointer. +fn curve(w: &mut W, c: &Curve, interval: [f64; 2], a: V3, b: V3, closed: bool) -> Result { + match c { + Curve::Line { .. } => { + let (ca, cb) = (w.coords(a), w.coords(b)); + Ok(w.add(110, 0, ca.into_iter().chain(cb).collect())) } - for _ in 0..m { - out.push(k); - } - } - Some(out) -} - -fn spline(s: &S, e: &p21::Entity, surface: bool) -> Result { - let bad = || KernelError::Failed("IGES export: unreadable B-spline".into()); - let (base, kn): (Vec, Vec) = if e.is_complex() { - let b = e.record(if surface { "B_SPLINE_SURFACE" } else { "B_SPLINE_CURVE" }).ok_or_else(bad)?; - let k = e.record(if surface { "B_SPLINE_SURFACE_WITH_KNOTS" } else { "B_SPLINE_CURVE_WITH_KNOTS" }).ok_or_else(bad)?; - let mut v = vec![Param::Str(String::new())]; - v.extend(b.iter().cloned()); - (v, k.to_vec()) - } else { - let p = e.params(); - let skip = if surface { 8 } else { 6 }; - (p.to_vec(), p.get(skip..).map(<[Param]>::to_vec).unwrap_or_default()) - }; - let deg_n = if surface { 2 } else { 1 }; - let deg: Vec = (0..deg_n) - .map(|i| base.get(1 + i).and_then(Param::as_i64).filter(|d| (1..=32).contains(d)).map(|d| d as usize).ok_or_else(bad)) - .collect::>()?; - let ctrl = base.get(1 + deg_n).and_then(Param::as_list).ok_or_else(bad)?; - let pts: Vec> = if surface { - ctrl.iter() - .map(|row| row.as_list().ok_or_else(bad)?.iter().map(|c| s.point(c.as_ref_id().ok_or_else(bad)?)).collect::>>()) - .collect::>()? - } else { - vec![ctrl.iter().map(|c| s.point(c.as_ref_id().ok_or_else(bad)?)).collect::>>()?] - }; - let knots: Vec> = if surface { - let (mu, mv, ku, kv) = (kn.first(), kn.get(1), kn.get(2), kn.get(3)); - vec![ - expand(mu.and_then(Param::as_list).ok_or_else(bad)?, ku.and_then(Param::as_list).ok_or_else(bad)?).ok_or_else(bad)?, - expand(mv.and_then(Param::as_list).ok_or_else(bad)?, kv.and_then(Param::as_list).ok_or_else(bad)?).ok_or_else(bad)?, - ] - } else { - vec![expand(kn.first().and_then(Param::as_list).ok_or_else(bad)?, kn.get(1).and_then(Param::as_list).ok_or_else(bad)?).ok_or_else(bad)?] - }; - let weights = match e.record(if surface { "RATIONAL_B_SPLINE_SURFACE" } else { "RATIONAL_B_SPLINE_CURVE" }) { - Some(r) => { - let w = r.first().and_then(Param::as_list).ok_or_else(bad)?; - Some(if surface { - w.iter() - .map(|row| row.as_list().ok_or_else(bad)?.iter().map(|x| x.as_f64().ok_or_else(bad)).collect::>>()) - .collect::>()? - } else { - vec![w.iter().map(|x| x.as_f64().ok_or_else(bad)).collect::>>()?] - }) - } - None => None, - }; - Ok(Spline { deg, pts, weights, knots }) -} - -/// A curve as an IGES entity running from `a` to `b` (its direction in the STEP file), the DE -/// pointer. -fn curve(w: &mut W, s: &S, id: u64, a: V3, b: V3, closed: bool) -> Result { - let e = s.e(id)?; - match e.name() { - "LINE" => Ok(w.add(110, 0, [a, b].iter().flatten().map(|x| real(*x)).collect())), - "CIRCLE" | "ELLIPSE" => { - let p = e.params(); - let (o, z, x) = s.placement(s.r(p.get(1))?)?; + Curve::Circle { position, .. } | Curve::Ellipse { position, .. } => { + let (o, z, x) = axes(position); let y = cross(z, x); let local = |q: V3| { let v = sub(q, o); @@ -238,152 +156,99 @@ fn curve(w: &mut W, s: &S, id: u64, a: V3, b: V3, closed: bool) -> Result { }; let (la, lb) = (local(a), if closed { local(a) } else { local(b) }); let tr = w.frame(o, x, z); - let de = if e.name() == "CIRCLE" { - w.add(100, 0, vec![real(0.0), real(0.0), real(0.0), real(la[0]), real(la[1]), real(lb[0]), real(lb[1])]) - } else { - let (ra, rb) = (s.f(p.get(2))?, s.f(p.get(3))?); - // A x² + C y² + F = 0 with F = -1: A = 1/ra², C = 1/rb². - w.add( - 104, - 1, - vec![ - real(1.0 / (ra * ra)), - real(0.0), - real(1.0 / (rb * rb)), - real(0.0), - real(0.0), - real(-1.0), - real(0.0), - real(la[0]), - real(la[1]), - real(lb[0]), - real(lb[1]), - ], - ) + let de = match c { + Curve::Ellipse { semi_axis_1: ra, semi_axis_2: rb, .. } => { + // A x² + C y² + F = 0 with F = -1: A = 1/ra², C = 1/rb². + w.add( + 104, + 1, + vec![ + real(1.0 / (ra * ra)), + real(0.0), + real(1.0 / (rb * rb)), + real(0.0), + real(0.0), + real(-1.0), + real(0.0), + real(la[0]), + real(la[1]), + real(lb[0]), + real(lb[1]), + ], + ) + } + _ => w.add(100, 0, vec![real(0.0), real(0.0), real(0.0), real(la[0]), real(la[1]), real(lb[0]), real(lb[1])]), }; if let Some(ent) = w.get_mut(de) { ent.xform = tr; } Ok(de) } - _ if e.has("B_SPLINE_CURVE") || e.name() == "B_SPLINE_CURVE_WITH_KNOTS" => { - let sp = spline(s, e, false)?; - let (Some(pts), Some(knots), Some(°)) = (sp.pts.first(), sp.knots.first(), sp.deg.first()) else { - return Err(KernelError::Failed("IGES export: empty B-spline".into())); - }; - let k = pts.len().saturating_sub(1); - let ws = sp.weights.as_ref().and_then(|w| w.first().cloned()).unwrap_or_else(|| vec![1.0; pts.len()]); - let rational = ws.iter().any(|w| (w - 1.0).abs() > 1e-12); - let (t0, t1) = (knots.get(deg).copied().unwrap_or(0.0), knots.get(pts.len()).copied().unwrap_or(1.0)); - let mut p = vec![k.to_string(), deg.to_string(), "0".into(), "0".into(), if rational { "0" } else { "1" }.into(), "0".into()]; - p.extend(knots.iter().map(|x| real(*x))); - p.extend(ws.iter().map(|x| real(*x))); - p.extend(pts.iter().flatten().map(|x| real(*x))); - p.extend([real(t0), real(t1), real(0.0), real(0.0), real(0.0)]); - Ok(w.add(126, 0, p)) + Curve::BSpline(s) => { + let weights = s.weights.clone().unwrap_or_else(|| vec![1.0; s.points.len()]); + Ok(bspline_curve(w, s.degree, &full_knots(&s.knots, &s.multiplicities), &weights, &s.points, interval)) } - n => Err(KernelError::Failed(format!("IGES export: curve {n} is not written yet"))), + // Segment i on [i, i + 1]: a degree-1 B-spline on knots 0, 0, 1, …, n − 1, n − 1. + Curve::Polyline(points) => { + let n = points.len(); + let knots: Vec = std::iter::once(0.0).chain((0..n).map(|i| i as f64)).chain(std::iter::once(n.saturating_sub(1) as f64)).collect(); + Ok(bspline_curve(w, 1, &knots, &vec![1.0; n], points, interval)) + } + _ => Err(failed("a curve of this kind is not written yet")), } } -/// Start point of a STEP curve (for extrusion directrices). -fn curve_start(s: &S, id: u64) -> Result { - let e = s.e(id)?; - match e.name() { - "LINE" => s.point(s.r(e.params().get(1))?), - "CIRCLE" => { - let (o, _, x) = s.placement(s.r(e.params().get(1))?)?; - let r = s.f(e.params().get(2))?; - Ok([o[0] + r * x[0], o[1] + r * x[1], o[2] + r * x[2]]) - } - _ => { - let sp = spline(s, e, false)?; - sp.pts.first().and_then(|r| r.first()).copied().ok_or_else(|| KernelError::Failed("IGES export: empty curve".into())) - } - } +/// A revolution's profile written over `range` of its parameter. +fn profile(w: &mut W, c: &Curve, range: [f64; 2]) -> Result { + let at = |t: f64| c.point(t).ok_or_else(|| failed(format!("the profile has no point at {t}"))); + let (a, b) = (at(range[0])?, at(range[1])?); + curve(w, c, range, a, b, false) } -/// A curve written whole (a revolution's generatrix, an extrusion's directrix). -fn whole_curve(w: &mut W, s: &S, id: u64) -> Result { - let e = s.e(id)?; - match e.name() { - "LINE" => { - let p = e.params(); - let o = s.point(s.r(p.get(1))?)?; - let v = s.e(s.r(p.get(2))?)?; - let d = s.dir(s.r(v.params().get(1))?)?; - let m = s.f(v.params().get(2))?; - curve(w, s, id, o, [o[0] + d[0] * m, o[1] + d[1] * m, o[2] + d[2] * m], false) - } - "CIRCLE" | "ELLIPSE" => { - let a = curve_start(s, id)?; - curve(w, s, id, a, a, true) - } - _ => curve(w, s, id, [0.0; 3], [0.0; 3], false), - } -} - -fn surface(w: &mut W, s: &S, id: u64) -> Result { - let e = s.e(id)?; - let p = e.params(); - let analytic = |w: &mut W, typ: i64, place: u64, extra: &[f64]| -> Result { - let (o, z, x) = s.placement(place)?; +/// A face's surface; `domain` is the face's parameter box in the surface's (STEP) parameters. +fn surface(w: &mut W, s: &Surface, domain: [[f64; 2]; 2]) -> Result { + let analytic = |w: &mut W, typ: i64, p: &Placement, extra: &[f64]| -> Result { + let (o, z, x) = axes(p); let (po, pz, px) = (w.point(o), w.direction(z), w.direction(x)); let mut v = vec![po.to_string()]; + let e = |i: usize| real(extra.get(i).copied().unwrap_or(0.0)); match typ { 190 => v.extend([pz.to_string(), px.to_string()]), - 192 => v.extend([pz.to_string(), real(extra.first().copied().unwrap_or(0.0)), px.to_string()]), - 194 => v.extend([ - pz.to_string(), - real(extra.first().copied().unwrap_or(0.0)), - real(extra.get(1).copied().unwrap_or(0.0).to_degrees()), - px.to_string(), - ]), - 196 => v.extend([real(extra.first().copied().unwrap_or(0.0)), pz.to_string(), px.to_string()]), - _ => v.extend([pz.to_string(), real(extra.first().copied().unwrap_or(0.0)), real(extra.get(1).copied().unwrap_or(0.0)), px.to_string()]), + 192 => v.extend([pz.to_string(), e(0), px.to_string()]), + 194 => v.extend([pz.to_string(), e(0), real(extra.get(1).copied().unwrap_or(0.0).to_degrees()), px.to_string()]), + 196 => v.extend([e(0), pz.to_string(), px.to_string()]), + _ => v.extend([pz.to_string(), e(0), e(1), px.to_string()]), } Ok(w.add(typ, 1, v)) }; - match e.name() { - "PLANE" => analytic(w, 190, s.r(p.get(1))?, &[]), - "CYLINDRICAL_SURFACE" => analytic(w, 192, s.r(p.get(1))?, &[s.f(p.get(2))?]), - "CONICAL_SURFACE" => analytic(w, 194, s.r(p.get(1))?, &[s.f(p.get(2))?, s.f(p.get(3))?]), - "SPHERICAL_SURFACE" => analytic(w, 196, s.r(p.get(1))?, &[s.f(p.get(2))?]), - "TOROIDAL_SURFACE" => analytic(w, 198, s.r(p.get(1))?, &[s.f(p.get(2))?, s.f(p.get(3))?]), - "SURFACE_OF_REVOLUTION" => { - let gen_curve = whole_curve(w, s, s.r(p.get(1))?)?; - let ax = s.e(s.r(p.get(2))?)?; - let o = s.point(s.r(ax.params().get(1))?)?; - let d = s.dir(s.r(ax.params().get(2))?)?; - let axis = w.add(110, 0, [o, [o[0] + d[0], o[1] + d[1], o[2] + d[2]]].iter().flatten().map(|x| real(*x)).collect()); - Ok(w.add(120, 0, vec![axis.to_string(), gen_curve.to_string(), real(0.0), real(std::f64::consts::TAU)])) + match s { + Surface::Plane { position } => analytic(w, 190, position, &[]), + Surface::Cylinder { position, radius } => analytic(w, 192, position, &[*radius]), + Surface::Cone { position, radius, semi_angle } => analytic(w, 194, position, &[*radius, *semi_angle]), + Surface::Sphere { position, radius } => analytic(w, 196, position, &[*radius]), + Surface::Torus { position, major_radius, minor_radius } => analytic(w, 198, position, &[*major_radius, *minor_radius]), + Surface::Revolution { profile: c, axis } => { + // STEP's v is the profile's parameter: the generatrix over the face's. + let generatrix = profile(w, c, domain[1])?; + let (o, d) = (axis.origin, axis.direction); + let (co, cd) = (w.coords(o), w.coords([o[0] + d[0], o[1] + d[1], o[2] + d[2]])); + let line = w.add(110, 0, co.into_iter().chain(cd).collect()); + Ok(w.add(120, 0, vec![line.to_string(), generatrix.to_string(), real(0.0), real(std::f64::consts::TAU)])) } - "SURFACE_OF_LINEAR_EXTRUSION" => { - let c = s.r(p.get(1))?; - let dir = whole_curve(w, s, c)?; - let start = curve_start(s, c)?; - let v = s.e(s.r(p.get(2))?)?; - let d = s.dir(s.r(v.params().get(1))?)?; - let m = s.f(v.params().get(2))?; - Ok(w.add(122, 0, vec![dir.to_string(), real(start[0] + d[0] * m), real(start[1] + d[1] * m), real(start[2] + d[2] * m)])) - } - _ if e.has("B_SPLINE_SURFACE") || e.name() == "B_SPLINE_SURFACE_WITH_KNOTS" => { - let sp = spline(s, e, true)?; - let (Some(&du), Some(&dv), Some(ku), Some(kv)) = (sp.deg.first(), sp.deg.get(1), sp.knots.first(), sp.knots.get(1)) else { - return Err(KernelError::Failed("IGES export: bad B-spline surface".into())); - }; - let nu = sp.pts.len(); - let nv = sp.pts.first().map(Vec::len).unwrap_or(0); - if nu == 0 || nv == 0 || sp.pts.iter().any(|r| r.len() != nv) { - return Err(KernelError::Failed("IGES export: ragged B-spline surface".into())); + Surface::BSpline(b) => { + let nu = b.points.len(); + let nv = b.points.first().map_or(0, Vec::len); + if nu == 0 || nv == 0 || b.points.iter().any(|r| r.len() != nv) { + return Err(failed("a ragged B-spline surface")); } - let wt = |i: usize, j: usize| sp.weights.as_ref().and_then(|w| w.get(i)?.get(j).copied()).unwrap_or(1.0); + let (ku, kv) = (full_knots(&b.u_knots, &b.u_multiplicities), full_knots(&b.v_knots, &b.v_multiplicities)); + let wt = |i: usize, j: usize| b.weights.as_ref().and_then(|w| w.get(i)?.get(j).copied()).unwrap_or(1.0); let rational = (0..nu).any(|i| (0..nv).any(|j| (wt(i, j) - 1.0).abs() > 1e-12)); let mut v = vec![ (nu - 1).to_string(), (nv - 1).to_string(), - du.to_string(), - dv.to_string(), + b.u_degree.to_string(), + b.v_degree.to_string(), "0".into(), "0".into(), if rational { "0" } else { "1" }.into(), @@ -400,110 +265,68 @@ fn surface(w: &mut W, s: &S, id: u64) -> Result { } for j in 0..nv { for i in 0..nu { - let q = sp.pts.get(i).and_then(|r| r.get(j)).copied().unwrap_or([0.0; 3]); - v.extend(q.map(real)); + let q = b.points.get(i).and_then(|r| r.get(j)).copied().unwrap_or([0.0; 3]); + v.extend(w.coords(q)); } } - let range = |k: &Vec, d: usize, n: usize| (k.get(d).copied().unwrap_or(0.0), k.get(n).copied().unwrap_or(1.0)); - let ((u0, u1), (v0, v1)) = (range(ku, du, nu), range(kv, dv, nv)); + let range = |k: &[f64], d: usize, n: usize| (k.get(d).copied().unwrap_or(0.0), k.get(n).copied().unwrap_or(1.0)); + let ((u0, u1), (v0, v1)) = (range(&ku, b.u_degree, nu), range(&kv, b.v_degree, nv)); v.extend([real(u0), real(u1), real(v0), real(v1)]); Ok(w.add(128, 0, v)) } - n => Err(KernelError::Failed(format!("IGES export: surface {n} is not written yet"))), + _ => Err(failed("a surface of this kind is not written yet")), } } -/// Colours of styled items (solids and faces). -fn colours(ex: &Exchange) -> HashMap { - let mut out = HashMap::new(); - for e in ex.entities.values() { - if e.name() != "STYLED_ITEM" { - continue; - } - let Some(item) = e.params().get(2).and_then(Param::as_ref_id) else { continue }; - let mut queue: Vec = - e.params().get(1).and_then(Param::as_list).map(|l| l.iter().filter_map(Param::as_ref_id).collect()).unwrap_or_default(); - let mut seen = 0; - while let Some(id) = queue.pop() { - seen += 1; - if seen > 64 { - break; - } - let Some(s) = ex.get(id) else { continue }; - if s.name() == "COLOUR_RGB" { - let c = |i: usize| s.params().get(i).and_then(Param::as_f64).map(|x| x.clamp(0.0, 1.0) as f32); - if let (Some(r), Some(g), Some(b)) = (c(1), c(2), c(3)) { - out.insert(item, [r, g, b]); - } - break; - } - for r in &s.records { - for p in &r.params { - match p { - Param::Ref(x) => queue.push(*x), - Param::List(v) => queue.extend(v.iter().filter_map(Param::as_ref_id)), - _ => {} - } - } - } - } - } - out +/// The face's parameter box mapped onto its STEP surface's parameters (a linear map: the box +/// of the mapped corners). +fn mapped_domain(domain: [[f64; 2]; 2], map: topology::Map) -> [[f64; 2]; 2] { + let [[u0, u1], [v0, v1]] = domain; + let corners = [[u0, v0], [u1, v0], [u0, v1], [u1, v1]].map(|c| map.apply(c)); + let span = |d: usize| corners.iter().fold([f64::INFINITY, f64::NEG_INFINITY], |[lo, hi], c| [lo.min(c[d]), hi.max(c[d])]); + [span(0), span(1)] } -/// A shell (514) with its vertex list, edge list, loops and faces. -fn shell(w: &mut W, s: &S, id: u64, colors: &HashMap) -> Result { - let sh = s.e(id)?; - let faces = s.list(sh.params().get(1))?; +/// The parameters of a shell (514): its faces, with their vertex list, edge list and loops +/// written first. +fn shell(w: &mut W, b: &Brep, si: u32, paint: &HashMap) -> Result> { + let Some(Shell::Faces { faces, .. }) = b.shells.get(si as usize) else { return Err(failed(format!("shell {si} is not a face shell"))) }; // Vertices and edges of the shell, in first-use order. - let mut vidx: HashMap = HashMap::new(); - let mut verts: Vec = Vec::new(); - let mut eidx: HashMap = HashMap::new(); - let mut edges: Vec<(u64, bool, usize, usize)> = Vec::new(); // curve, same sense, start, end - let mut face_data = Vec::new(); - for f in faces { - let fid = s.r(Some(f))?; - let fe = s.e(fid)?; - let sense = fe.params().get(3).and_then(Param::as_bool).unwrap_or(true); - let mut loops: Vec> = Vec::new(); - let bounds = s.list(fe.params().get(1))?; - // The outer bound first. - let mut ordered: Vec<&Param> = - bounds.iter().filter(|b| b.as_ref_id().and_then(|x| s.ex.get(x)).is_some_and(|e| e.name() == "FACE_OUTER_BOUND")).collect(); - ordered.extend(bounds.iter().filter(|b| b.as_ref_id().and_then(|x| s.ex.get(x)).is_some_and(|e| e.name() != "FACE_OUTER_BOUND"))); - for b in ordered { - let be = s.e(s.r(Some(b))?)?; - let orient = be.params().get(2).and_then(Param::as_bool).unwrap_or(true); - let lp = s.e(s.r(be.params().get(1))?)?; - if lp.name() != "EDGE_LOOP" { - continue; - } - let mut l = Vec::new(); - for oe in s.list(lp.params().get(1))? { - let oe = s.e(s.r(Some(oe))?)?; - let ec = s.r(oe.params().get(3))?; - let d = oe.params().get(4).and_then(Param::as_bool).unwrap_or(true); - #[allow(clippy::map_entry)] // the edge's vertices are numbered before it - if !eidx.contains_key(&ec) { - let ee = s.e(ec)?; - let (v0, v1) = (s.r(ee.params().get(1))?, s.r(ee.params().get(2))?); - let mut vi = |v: u64| -> Result { - if let Some(i) = vidx.get(&v) { - return Ok(*i); + let (mut vidx, mut verts): (HashMap, Vec) = (HashMap::new(), Vec::new()); + let (mut eidx, mut edges): (HashMap, Vec) = (HashMap::new(), Vec::new()); + let mut face_data = Vec::with_capacity(faces.len()); + for of in faces { + let face = b.faces.get(of.face as usize).ok_or_else(|| failed(format!("face {}: no such face", of.face)))?; + let (s, map) = topology::surface(face.parameters()).map_err(|e| failed(format!("face {}: {e}", of.face)))?; + let keeps = map.keeps_normal(); + let outer = topology::outer_loop(b, face); + let order: Vec = outer.into_iter().chain((0..face.loops.len()).filter(|l| Some(*l) != outer)).collect(); + let mut loops: Vec> = Vec::new(); + for li in order { + let Some(Loop::Edges { edges: uses }) = face.loops.get(li) else { continue }; + let mut l = Vec::with_capacity(uses.len()); + for u in uses { + let k = match eidx.get(&u.edge) { + Some(k) => *k, + None => { + let e = b.edges.get(u.edge as usize).ok_or_else(|| failed(format!("edge {}: no such edge", u.edge)))?; + for v in e.vertices { + if let std::collections::hash_map::Entry::Vacant(e) = vidx.entry(v) { + let p = b.vertices.get(v as usize).ok_or_else(|| failed(format!("vertex {v}: no such vertex")))?.point; + e.insert(verts.len()); + verts.push(p); + } } - verts.push(s.vertex(v)?); - vidx.insert(v, verts.len() - 1); - Ok(verts.len() - 1) - }; - let (a, bb) = (vi(v0)?, vi(v1)?); - let same = ee.params().get(4).and_then(Param::as_bool).unwrap_or(true); - eidx.insert(ec, edges.len()); - edges.push((s.r(ee.params().get(3))?, same, a, bb)); - } - l.push((ec, d)); + eidx.insert(u.edge, edges.len()); + edges.push(u.edge); + edges.len() - 1 + } + }; + l.push((k, u.forward)); } - // IGES loops run counter-clockwise about the surface normal. - if orient != sense { + // Record loops run counter-clockwise about the natural normal; IGES's about the + // surface's. + if !keeps { l.reverse(); for x in &mut l { x.1 = !x.1; @@ -511,95 +334,93 @@ fn shell(w: &mut W, s: &S, id: u64, colors: &HashMap) -> Result, name: &str, color: Option<[f32; 3]>) -> i64 { + let np = w.add(406, 15, vec!["1".into(), holl(name)]); + params.extend(["0".into(), "1".into(), np.to_string()]); + let d = w.add(typ, form, params); + let c = color.map(|c| w.color(c)); + if let Some(ent) = w.get_mut(d) { + ent.dependent = false; + ent.label = name.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect(); + if let Some(c) = c { + ent.color = -c; + } + } + d } /// IGES text (5.3, millimetres) for bodies. pub fn iges_export_bodies(bodies: &[ExportBody], header: &StepHeader) -> Result { - let step = crate::step_export_bodies(bodies, header)?; - let ex = p21::parse(&step).map_err(|e| KernelError::Failed(format!("IGES export: {e}")))?; - let s = S { ex: &ex }; - let colors = colours(&ex); - let mut w = W::default(); - let mut solids: Vec = - ex.entities.iter().filter(|(_, e)| matches!(e.name(), "MANIFOLD_SOLID_BREP" | "BREP_WITH_VOIDS")).map(|(i, _)| *i).collect(); - solids.sort(); - let mut max_coord: f64 = 1.0; - for p in ex.entities.values().filter(|e| e.name() == "CARTESIAN_POINT") { - if let Some(c) = p.params().get(1).and_then(Param::as_list) { - for x in c.iter().filter_map(Param::as_f64) { - max_coord = max_coord.max(x.abs()); + let mut w = W { max_coord: 1.0, ..W::default() }; + for eb in bodies { + eb.body.require_brep("IGES export")?; + let b = eb.body.record(); + let paint: HashMap = eb.body.paint().map(|p| p.faces.iter().map(|f| (f.face, f.color)).collect()).unwrap_or_default(); + let items = topology::layout(b).map_err(failed)?; + // A closed shell is form 1, an open one form 2. + for solid in &items.solids { + let params = shell(&mut w, b, solid.outer, &paint)?; + let outer = w.add(514, 1, params); + let mut p = vec![outer.to_string(), "1".into(), solid.voids.len().to_string()]; + for &v in &solid.voids { + let params = shell(&mut w, b, v, &paint)?; + p.extend([w.add(514, 1, params).to_string(), "1".into()]); } + top_level(&mut w, 186, 0, p, &eb.name, eb.color); } - } - for id in solids { - let e = s.e(id)?; - let name = e.params().first().and_then(Param::as_str).unwrap_or("").to_string(); - let outer = shell(&mut w, &s, s.r(e.params().get(1))?, &colors)?; - let mut p = vec![outer.to_string(), "1".into()]; - let voids: Vec = if e.name() == "BREP_WITH_VOIDS" { - s.list(e.params().get(2))?.iter().map(|v| shell(&mut w, &s, s.r(Some(v))?, &colors)).collect::>()? - } else { - Vec::new() - }; - p.push(voids.len().to_string()); - for v in voids { - p.extend([v.to_string(), "1".into()]); - } - // The body's name as a name property (406 form 15). - let np = w.add(406, 15, vec!["1".into(), holl(&name)]); - p.extend(["0".into(), "1".into(), np.to_string()]); - let d = w.add(186, 0, p); - let c = colors.get(&id).map(|c| w.color(*c)); - if let Some(ent) = w.get_mut(d) { - ent.dependent = false; - ent.label = name.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect(); - if let Some(c) = c { - ent.color = -c; - } + for &si in &items.sheets { + let params = shell(&mut w, b, si, &paint)?; + top_level(&mut w, 514, 2, params, &eb.name, eb.color); } } if w.ents.is_empty() { return Err(KernelError::Invalid("nothing to export".into())); } + let max_coord = w.max_coord; Ok(layout(&w, header, max_coord)) } diff --git a/crates/kernel/src/intersection.rs b/crates/kernel/src/intersection.rs new file mode 100644 index 000000000..4cb74586e --- /dev/null +++ b/crates/kernel/src/intersection.rs @@ -0,0 +1,67 @@ +//! Where two bodies meet, each whole or one face of it: the edges SMLib's imprint of the first by +//! the second makes (`capi/include/smlib.h`, "Imprint": each face the tool meets is cut along the +//! intersection). SMLib intersects the faces' surfaces and trims each curve to both faces, so an +//! edge it makes is exactly where they meet: its record curve (a B-spline SMLib fitted within its +//! tolerance, or the line, circle or ellipse it is) on its interval. Which edges are new comes from +//! the imprint's own history: an edge no edge of either operand became. + +use solidcore_record::Vec3; +use solidcore_record::brep::Curve; + +use crate::body::{Body, MeshTolerance}; +use crate::{KernelError, Result}; + +/// One edge where two bodies meet. +#[derive(Clone, Debug, PartialEq)] +pub struct MeetingEdge { + /// The edge's record curve, exactly as SMLib made it. + pub curve: Curve, + /// Its interval on `curve`. + pub interval: [f64; 2], + /// Its points at the chord tolerance asked for, from its start to its end. + pub points: Vec, +} + +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib intersection curve: {what}"), e) +} + +/// `body` itself, or its faces `faces` (in its face order) alone as a surface body. +fn part(body: &Body, faces: Option<&[usize]>) -> Result { + let Some(faces) = faces else { return Ok(body.clone()) }; + let count = body.record().faces.len(); + if let Some(f) = faces.iter().find(|f| **f >= count) { + return Err(KernelError::Invalid(format!("the body has no face {f}"))); + } + if faces.is_empty() { + return Err(KernelError::Invalid("no face given".into())); + } + let taken: Vec<(usize, bool)> = faces.iter().map(|f| (*f, false)).collect(); + crate::surfaces::taken(body, body.record(), &taken) +} + +/// Where `a` (or its faces `a_face`) meets `b` (or its faces `b_face`): every edge SMLib's imprint +/// of the one by the other makes, its points at `chord` mm. Empty where they do not meet. +pub fn meeting_edges(a: &Body, a_face: Option<&[usize]>, b: &Body, b_face: Option<&[usize]>, chord: f64) -> Result> { + let (a, b) = (part(a, a_face)?, part(b, b_face)?); + let ta = a.smlib()?.tagged(0).map_err(|e| failed("tag", e))?; + let tb = b.smlib()?.tagged(1).map_err(|e| failed("tag", e))?; + let Some(cut) = ta.imprint(&tb).map_err(|e| failed("imprint", e))? else { return Ok(Vec::new()) }; + let history = cut.history().map_err(|e| failed("history", e))?; + let (body, order) = crate::native::body_from_smlib_ordered(&cut)?; + let order = order.ok_or_else(|| failed("history", "the imprint's edges cannot be numbered"))?; + let mesh = body.mesh(&MeshTolerance::chord(chord))?; + let record = body.record(); + let mut out = Vec::new(); + for (i, edge) in history.edges.iter().enumerate() { + if !edge.origins.is_empty() { + continue; + } + let at = if order.edges.is_empty() { Some(i) } else { order.edges.get(i).copied() }; + let (Some(e), Some(points)) = (at.and_then(|k| record.edges.get(k)), at.and_then(|k| mesh.edges.get(k))) else { + return Err(failed("history", format!("edge {i} is not in the imprinted body"))); + }; + out.push(MeetingEdge { curve: e.parameters().clone(), interval: e.interval, points: points.clone() }); + } + Ok(out) +} diff --git a/crates/kernel/src/intersection_curve_tests.rs b/crates/kernel/src/intersection_curve_tests.rs index c4eee490d..9ee9c851e 100644 --- a/crates/kernel/src/intersection_curve_tests.rs +++ b/crates/kernel/src/intersection_curve_tests.rs @@ -1,116 +1,80 @@ -//! Regressions against the actual patched truck constructor, run by workspace CI. -use truck_meshalgo::prelude::PolylineCurve; -use truck_modeling::{BoundedCurve, ParametricCurve, Plane, Point3, Sphere}; -use truck_shapeops::IntersectionCurveWithParameters; +//! A face whose edge is an intersection curve that does not evaluate (#1252): meshing it neither +//! panics nor gives non-finite points. -fn planes() -> (Plane, Plane) { - let o = Point3::new(0.0, 0.0, 0.0); - (Plane::new(o, Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0)), Plane::new(o, Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 0.0, 1.0))) +use solidcore_record::brep::{self as b, Curve, Curve2, Surface}; + +/// A plane at height `z` with its parameters along x and y. +fn plane(z: f64) -> Surface { + Surface::Plane { origin: [0.0, 0.0, z], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] } } -#[test] -fn degenerate_intersection_polylines_return_none_without_panicking() { - let origin = Point3::new(0.0, 0.0, 0.0); - for points in [ - vec![], - vec![origin], - vec![origin, origin], - vec![origin; 3], - vec![origin, Point3::new(f64::NAN, 0.0, 0.0)], - vec![origin, Point3::new(f64::INFINITY, 0.0, 0.0)], - ] { - let (a, b) = planes(); - let result = std::panic::catch_unwind(|| IntersectionCurveWithParameters::try_new(a, b, PolylineCurve(points.clone()), 0.01)); - assert!(result.is_ok(), "constructor panicked for {points:?}"); - assert!(result.unwrap().is_none(), "collapsed input must not create a curve: {points:?}"); - } +/// A triangular sheet at z = 0.5 whose first edge is the intersection of two planes: the parallel +/// planes `z = 0` and `z = 1` when `support_gap` is `1.0` (the projection onto both never +/// converges), the same plane twice when it is `0.0` (the leader lies on both and always +/// evaluates). +fn triangle_with_intersection_edge(support_gap: f64) -> b::Brep { + let corners = [[0.0, 0.0, 0.5], [1.0, 0.0, 0.5], [0.5, 1.0, 0.5]]; + let uv = [[0.0, 0.0], [1.0, 0.0], [0.5, 1.0]]; + let traced = Curve::SurfaceIntersection { + surfaces: [Box::new(plane(0.5 - support_gap / 2.0)), Box::new(plane(0.5 + support_gap / 2.0))], + leader: Box::new(Curve::Polyline { points: vec![corners[0], corners[1]] }), + tolerance: 0.01, + }; + let curve = |k: usize| if k == 0 { traced.clone() } else { Curve::Line { start: corners[k], end: corners[(k + 1) % 3] } }; + let edges = (0..3) + .map(|k| b::Edge { + nurbs: None, + curve: curve(k), + interval: [0.0, 1.0], + vertices: [k as u32, ((k + 1) % 3) as u32], + tolerance: 1e-6, + uses: Vec::new(), + }) + .collect(); + let uses = (0..3) + .map(|k| b::OrientedEdge { + edge: k as u32, + forward: true, + pcurve: Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![uv[k], uv[(k + 1) % 3]] }, + }) + .collect(); + let face = b::Face { nurbs: None, surface: plane(0.5), domain: [[0.0, 1.0], [0.0, 1.0]], loops: vec![b::Loop::Edges { edges: uses }] }; + let loose = b::Brep { + version: b::VERSION, + tolerance: 1e-6, + regions: vec![b::Region { shells: vec![0], void: false }], + shells: vec![b::Shell::Faces { faces: vec![b::OrientedFace { face: 0, forward: true }], wires: Vec::new() }], + faces: vec![face], + edges, + vertices: corners.iter().map(|p| b::Vertex { point: *p, tolerance: 1e-6 }).collect(), + }; + loose.canonical().unwrap().brep } -#[test] -fn closed_intersection_retains_the_closure_and_spherical_supports() { - let a = Sphere::new(Point3::new(0.0, 0.0, 1.0), 2.0_f64.sqrt()); - let b = Sphere::new(Point3::new(0.0, 0.0, -1.0), 2.0_f64.sqrt()); - let poly = PolylineCurve(vec![ - Point3::new(1.0, 0.0, 0.0), - Point3::new(0.0, 1.0, 0.0), - Point3::new(-1.0, 0.0, 0.0), - Point3::new(0.0, -1.0, 0.0), - Point3::new(1.0, 0.0, 0.0), - ]); - let curve = IntersectionCurveWithParameters::try_new(a, b, poly, 0.01).unwrap(); - let (lo, hi) = curve.range_tuple(); - assert_eq!(curve.subs(lo), curve.subs(hi)); - for i in 0..=40 { - let p = curve.subs(lo + (hi - lo) * i as f64 / 40.0); - assert!(p.z.abs() < 1e-8, "{p:?}"); - assert!(((p.x * p.x + p.y * p.y).sqrt() - 1.0).abs() <= 0.01, "{p:?}"); - } -} - -#[test] -fn open_intersection_keeps_endpoints_on_both_planes() { - let (a, b) = planes(); - let start = Point3::new(1.0, 0.0, 0.0); - let end = Point3::new(3.0, 0.0, 0.0); - let curve = IntersectionCurveWithParameters::try_new(a, b, PolylineCurve(vec![start, end]), 0.01).unwrap(); - let (lo, hi) = curve.range_tuple(); - assert_eq!(curve.subs(lo), start); - assert_eq!(curve.subs(hi), end); - assert_eq!(curve.subs((lo + hi) / 2.0), Point3::new(2.0, 0.0, 0.0)); -} - -/// A triangular face whose first edge is an intersection curve of two planes: the parallel planes -/// `z = 0` and `z = 1` when `support_gap` is `1.0` (the projection onto both never converges), the -/// same plane twice when it is `0.0` (the leader lies on both and always evaluates). -fn triangle_with_intersection_edge(support_gap: f64) -> truck_modeling::Shell { - use truck_modeling::{Curve, Edge, Face, IntersectionCurve, Leader, Line, Shell, Surface, Vertex, Wire}; - let plane = |z: f64| Surface::Plane(Plane::new(Point3::new(0.0, 0.0, z), Point3::new(1.0, 0.0, z), Point3::new(0.0, 1.0, z))); - let (v0, v1, v2) = (Vertex::new(Point3::new(0.0, 0.0, 0.5)), Vertex::new(Point3::new(1.0, 0.0, 0.5)), Vertex::new(Point3::new(0.5, 1.0, 0.5))); - let leader = Leader::Polyline(PolylineCurve(vec![Point3::new(0.0, 0.0, 0.5), Point3::new(1.0, 0.0, 0.5)])); - let bad = IntersectionCurve::new_unchecked(Box::new(plane(0.5 - support_gap / 2.0)), Box::new(plane(0.5 + support_gap / 2.0)), leader, 0.01); - let line = |a: &Vertex, b: &Vertex| Edge::new(a, b, Curve::Line(Line(a.point(), b.point()))); - let wire = Wire::from(vec![Edge::new(&v0, &v1, Curve::IntersectionCurve(bad)), line(&v1, &v2), line(&v2, &v0)]); - Shell::from(vec![Face::new(vec![wire], plane(0.5))]) -} - -/// Meshing an edge whose intersection curve does not evaluate (#1252): `IntersectionCurve::subs` -/// unwraps a failed projection, and the mesher sampled the edge through it. The two supports here -/// are parallel planes, so the projection never converges. Nothing may panic (wasm aborts on one, -/// and the native guard prints the message first) and the mesh stays finite. +/// Meshing an edge whose intersection curve does not evaluate (#1252): the two supports here are +/// parallel planes, so the projection never converges. Nothing may panic (wasm aborts on one, and +/// the native guard prints the message first), and a mesh that comes back is finite. #[test] fn meshing_an_edge_that_does_not_evaluate_neither_panics_nor_goes_non_finite() { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; - use truck_meshalgo::prelude::RobustMeshableShape; - let shell = triangle_with_intersection_edge(1.0); - - let me = std::thread::current().id(); - let count = Arc::new(AtomicUsize::new(0)); - let c2 = count.clone(); - let prev = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |_| { - if std::thread::current().id() == me { - c2.fetch_add(1, Ordering::SeqCst); - } - })); - let meshed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| shell.robust_triangulation(0.01))); - std::panic::set_hook(prev); - assert_eq!(count.load(Ordering::SeqCst), 0, "panics while meshing"); - let meshed = meshed.unwrap(); - for face in meshed.face_iter() { - if let Some(mesh) = face.surface() { - assert!(mesh.positions().iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite())); + for gap in [1.0, 0.0] { + let me = std::thread::current().id(); + let count = Arc::new(AtomicUsize::new(0)); + let c2 = count.clone(); + let prev = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |_| { + if std::thread::current().id() == me { + c2.fetch_add(1, Ordering::SeqCst); + } + })); + let meshed = std::panic::catch_unwind(|| { + crate::Body::from_record(triangle_with_intersection_edge(gap)).and_then(|body| body.mesh(&crate::MeshTolerance::chord(0.01))) + }); + std::panic::set_hook(prev); + assert_eq!(count.load(Ordering::SeqCst), 0, "gap {gap}: panics while meshing"); + if let Ok(Ok(mesh)) = meshed { + assert!(mesh.positions.iter().all(|p| p.is_finite()), "gap {gap}"); } } } - -/// A boolean's result with an edge that does not evaluate is refused with an error (#1252). The -/// mesher's panic on such an edge used to reject the attempt; now that it no longer panics, the -/// result must be refused explicitly or a plausible-looking mesh would let it through. -#[test] -fn a_result_with_an_edge_that_does_not_evaluate_is_refused() { - use truck_modeling::Solid; - let solid = |gap: f64| Solid::new_unchecked(vec![triangle_with_intersection_edge(gap)]); - assert!(!crate::boolean_record::edges_evaluate(&solid(1.0))); - assert!(crate::boolean_record::edges_evaluate(&solid(0.0))); -} diff --git a/crates/kernel/src/iso.rs b/crates/kernel/src/iso.rs new file mode 100644 index 000000000..820a5cfb3 --- /dev/null +++ b/crates/kernel/src/iso.rs @@ -0,0 +1,373 @@ +//! Isoparametric curves of a face: the curves of its surface along which one parameter is held +//! (u = const or v = const), each exactly as a record curve, cut to the face by its trims (the +//! pcurves of its loops in (u, v)). One routine clips an iso line to a face ([`FaceTrims::clip`]); +//! the curve through a point ([`iso_curves`], projected into sketches) and the analysis grid +//! across a face ([`iso_grid`], drawn by Isocurve Analysis) both use it. +//! +//! Seams, poles and periods need nothing of their own: a face's loops and pcurves lie in one lift +//! of its surface's (u, v) inside its box ([`brep::Face::domain`]), a seam edge is in the loop +//! twice (once on each side of the box), and a pole is a degenerate edge or a vertex loop on the +//! box's side, where the outer loop's polygon closes. Every iso line of a closed surface is +//! therefore one line across the box, cut where it crosses the loops. + +use solidcore_record::Vec3; +use solidcore_record::brep; +use solidcraft_geom::brep::eval::SurfaceEval; +use solidcraft_geom::prelude::*; + +use crate::body::Body; +use crate::point_path::{MAX_CURVE_POINTS, curve_path}; +use crate::{KernelError, Result}; + +/// Samples per knot span (and at least this many per pcurve) where the iso curves look for the +/// crossings of a face's loops and classify the face's inside. +const ISO_SAMPLES: usize = 64; + +/// Most iso curves each way [`iso_grid`] draws across one face. +pub const MAX_ISO_COUNT: usize = 100; + +/// One piece of an isoparametric curve of a face, inside the face. +#[derive(Clone, Debug, PartialEq)] +pub struct IsoLine { + /// The curve runs along the surface's first parameter (u runs, v is held), or its second. + pub along_u: bool, + /// The parameter held: v when `along_u`, else u. + pub fixed: f64, + /// The exact record curve on `interval` of its own parameter. + pub curve: brep::Curve, + pub interval: [f64; 2], + /// The surface parameter that runs along the curve (u when `along_u`, else v), from the + /// start of `interval` to its end. + pub span: [f64; 2], + /// Its points from the start of `interval` to its end, at the chord tolerance asked for. + pub points: Vec, +} + +/// A face's surface and its loops in (u, v), read once for any number of iso lines. +struct FaceTrims<'a> { + surface: &'a brep::Surface, + eval: SurfaceEval, + domain: [[f64; 2]; 2], + /// Each edge loop's pcurves, each with its samples ([`pcurve_samples`]) and whether the loop + /// runs along it (from its interval's start to its end). + loops: Vec, bool)>>, + /// Each edge loop as a closed polygon in (u, v), for telling the face's inside. + polygons: Vec>, +} + +impl<'a> FaceTrims<'a> { + fn new(body: &'a Body, face: usize) -> Result> { + let f = body.record().faces.get(face).ok_or_else(|| KernelError::Invalid(format!("the body has no face {face}")))?; + let surface = f.parameters(); + let eval = SurfaceEval::new(surface).map_err(|e| KernelError::Failed(format!("iso curve: {e}")))?; + let loops: Vec, bool)>> = f + .loops + .iter() + .filter_map(|l| match l { + brep::Loop::Edges { edges } => Some(edges.iter().map(|e| (&e.pcurve, pcurve_samples(&e.pcurve), e.forward)).collect()), + // A pole: the outer loop's polygon closes along the box's side there. + brep::Loop::Vertex { .. } => None, + }) + .collect(); + let polygons = loops + .iter() + .map(|l| { + // In the loop's order: a pcurve runs along its edge's interval whichever way the + // loop does, so one the loop runs against is walked backwards. + let mut poly: Vec<[f64; 2]> = Vec::new(); + for (_, samples, forward) in l { + let pts = samples.iter().map(|(_, q)| *q); + if *forward { poly.extend(pts) } else { poly.extend(pts.rev()) } + } + // Closed: a loop whose pcurves leave a side of the box out (a sphere's poles, as + // vertex loops) has that side as its closing edge. + if let Some(first) = poly.first().copied() { + poly.push(first); + } + poly + }) + .collect(); + Ok(FaceTrims { surface, eval, domain: f.domain, loops, polygons }) + } + + /// The face's own extent in (u, v): the box around its loops, within the surface's box. + fn extent(&self) -> [[f64; 2]; 2] { + let mut b = [[f64::INFINITY, f64::NEG_INFINITY]; 2]; + for q in self.polygons.iter().flatten() { + for (k, x) in q.iter().enumerate() { + b[k] = [b[k][0].min(*x), b[k][1].max(*x)]; + } + } + let [[u0, u1], [v0, v1]] = self.domain; + [[b[0][0].max(u0), b[0][1].min(u1)], [b[1][0].max(v0), b[1][1].min(v1)]] + } + + /// Whether `q` is inside the face: inside its outer loop and outside its holes. + fn inside(&self, q: [f64; 2]) -> bool { + self.polygons.iter().filter(|l| crosses_right(q, l)).count() % 2 == 1 + } + + /// The iso line of the surface at `fixed` (v when `along_u`, else u) across the face's box, + /// cut to the face: the pieces inside it, each as its exact record curve on its interval and + /// the running parameter's span, in the order the line runs (none when the line misses the + /// face). + fn clip(&self, along_u: bool, fixed: f64) -> Result> { + let [[u0, u1], [v0, v1]] = self.domain; + let (lo, hi) = if along_u { (u0, u1) } else { (v0, v1) }; + let at_t = |t: f64| if along_u { [t, fixed] } else { [fixed, t] }; + // Where the line crosses the loops' pcurves (along it), each crossing solved on the + // pcurve itself, with the box's ends. + let across = |q: [f64; 2]| if along_u { q[1] - fixed } else { q[0] - fixed }; + let along = |q: [f64; 2]| if along_u { q[0] } else { q[1] }; + let mut cuts = vec![lo, hi]; + for (c, samples, _) in self.loops.iter().flatten() { + for w in samples.windows(2) { + let ((ta, qa), (tb, qb)) = (w[0], w[1]); + let (ka, kb) = (across(qa), across(qb)); + if (ka < 0.0) == (kb < 0.0) || ka == kb { + continue; + } + let (mut x, mut y) = (ta, tb); + for _ in 0..80 { + let m = 0.5 * (x + y); + match solidcraft_geom::brep::pcurve::eval(c, m).map(across) { + Some(k) if (k < 0.0) == (ka < 0.0) => x = m, + Some(_) => y = m, + None => break, + } + } + if let Some(t) = solidcraft_geom::brep::pcurve::eval(c, 0.5 * (x + y)).map(along).filter(|t| *t > lo && *t < hi) { + cuts.push(t); + } + } + } + cuts.sort_by(f64::total_cmp); + cuts.dedup_by(|a, b| (*a - *b).abs() <= 1e-9 * (1.0 + b.abs())); + let mut out = Vec::new(); + // Neighbouring inside pieces are one piece. + let mut run: Option<(f64, f64)> = None; + for w in cuts.windows(2) { + let (a, b) = (w[0], w[1]); + if !(b - a > 1e-12) { + continue; + } + if self.inside(at_t(0.5 * (a + b))) { + run = Some(run.map_or((a, b), |(s, _)| (s, b))); + } else if let Some(r) = run.take() { + let (curve, interval) = iso_record(self.surface, along_u, fixed, r)?; + out.push((curve, interval, [r.0, r.1])); + } + } + if let Some(r) = run { + let (curve, interval) = iso_record(self.surface, along_u, fixed, r)?; + out.push((curve, interval, [r.0, r.1])); + } + Ok(out) + } +} + +/// The isoparametric curve of face `face` of `body` through the point `at` on it, the pieces of +/// it inside the face, each as its exact record curve on its interval: along the surface's first +/// parameter (`along_u`; around a cylinder, cone, sphere or torus) or its second (along them). +/// On a B-spline surface the curve is the surface's row at the point's other parameter (each +/// control point the column through it evaluated there, exactly); on an analytic surface its +/// line or circle. The pieces are where the curve crosses the face's loops (their pcurves). +pub fn iso_curves(body: &Body, face: usize, at: Vec3, along_u: bool) -> Result> { + let trims = FaceTrims::new(body, face)?; + let [[u0, u1], [v0, v1]] = trims.domain; + let size = body.size().max(1e-9); + let mid = [0.5 * (u0 + u1), 0.5 * (v0 + v1)]; + let [mut pu, mut pv] = trims + .eval + .project(at, Some(mid), size * 1e-3 + 1e-6) + .ok_or_else(|| KernelError::Invalid("iso curve: the point is not on the face".into()))?; + // Into the face's box, by whole periods. + let period = trims.eval.domain().period; + for (x, (lo, hi), p) in [(&mut pu, (u0, u1), period[0]), (&mut pv, (v0, v1), period[1])] { + if let Some(p) = p.filter(|p| *p > 0.0) { + *x = lo + (*x - lo).rem_euclid(p); + if *x > hi + 1e-12 { + *x -= p; + } + } + } + let out: Vec<(brep::Curve, [f64; 2])> = trims.clip(along_u, if along_u { pv } else { pu })?.into_iter().map(|(c, i, _)| (c, i)).collect(); + if out.is_empty() { + return Err(KernelError::Invalid("the iso curve runs outside the face".into())); + } + Ok(out) +} + +/// The isoparametric curves of face `face` of `body` for Isocurve Analysis: `count` +/// (1…[`MAX_ISO_COUNT`]) curves each way, evenly spaced across the face, the held parameter at +/// `lo + k · (hi − lo) / (count + 1)` for `k = 1…count` over the face's extent in (u, v), so +/// neither side of the extent (the face's boundary) is drawn as a curve. Faces of the body on the +/// very same surface (a face a boss splits in two) are spaced together, across the extent of all +/// of them, so their curves are the same lines, straight across where they meet. Each curve is +/// cut to the face ([`FaceTrims::clip`]), its points at chord tolerance `chord`. Along u first, +/// then v. +pub fn iso_grid(body: &Body, face: usize, count: usize, chord: f64) -> Result> { + if !(1..=MAX_ISO_COUNT).contains(&count) { + return Err(KernelError::Invalid(format!("iso curves: 1…{MAX_ISO_COUNT} each way"))); + } + if !(chord.is_finite() && chord > 0.0) { + return Err(KernelError::Invalid("iso curves: the chord tolerance must be positive".into())); + } + let trims = FaceTrims::new(body, face)?; + let [[u0, u1], [v0, v1]] = shared_extent(body, face, &trims)?; + let mut out = Vec::new(); + for along_u in [true, false] { + let (lo, hi) = if along_u { (v0, v1) } else { (u0, u1) }; + if !(hi > lo) { + continue; + } + for k in 1..=count { + let fixed = lo + (hi - lo) * k as f64 / (count + 1) as f64; + for (curve, interval, span) in trims.clip(along_u, fixed)? { + let segs = curve_path(&curve, interval)?; + let mut points: Vec = segs.first().map(crate::PathSeg::start).into_iter().collect(); + for s in &segs { + points.extend(s.points_after_start(chord)); + } + out.push(IsoLine { along_u, fixed, curve, interval, span, points }); + } + } + } + Ok(out) +} + +/// The extent in (u, v) of face `face` together with every other face of `body` on the same +/// surface record (the same surface and parameters, so one (u, v) for all of them): the box round +/// all their extents ([`FaceTrims::extent`]). +fn shared_extent(body: &Body, face: usize, trims: &FaceTrims) -> Result<[[f64; 2]; 2]> { + let mut b = trims.extent(); + for (i, other) in body.record().faces.iter().enumerate() { + if i == face || other.parameters() != trims.surface { + continue; + } + let [[a0, a1], [c0, c1]] = FaceTrims::new(body, i)?.extent(); + b = [[b[0][0].min(a0), b[0][1].max(a1)], [b[1][0].min(c0), b[1][1].max(c1)]]; + } + Ok(b) +} + +/// A pcurve's parameters and points at [`ISO_SAMPLES`] per knot span, in its direction. +fn pcurve_samples(c: &brep::Curve2) -> Vec<(f64, [f64; 2])> { + let Some([a, b]) = c.interval() else { return Vec::new() }; + let spans = match c { + brep::Curve2::Spline { knots, .. } | brep::Curve2::RationalSpline { knots, .. } => knots.windows(2).filter(|w| w[1] > w[0]).count().max(1), + }; + let n = (spans * ISO_SAMPLES).min(1 << 16); + (0..=n) + .filter_map(|i| { + let t = a + (b - a) * i as f64 / n as f64; + solidcraft_geom::brep::pcurve::eval(c, t).map(|q| (t, q)) + }) + .collect() +} + +/// Whether the ray from `q` along +u crosses the closed polygon `l` an odd number of times. +fn crosses_right(q: [f64; 2], l: &[[f64; 2]]) -> bool { + let mut odd = false; + for w in l.windows(2) { + let (a, b) = (w[0], w[1]); + if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (b[0] - a[0]) * (q[1] - a[1]) / (b[1] - a[1]) { + odd = !odd; + } + } + odd +} + +/// The iso curve of `surface` at `fixed` (the other parameter) as a record curve on `[a, b]` of +/// its own parameter: the surface's own line or circle, or its B-spline row. +fn iso_record(surface: &brep::Surface, along_u: bool, fixed: f64, (a, b): (f64, f64)) -> Result<(brep::Curve, [f64; 2])> { + use solidcore_record::brep::{Curve, Frame, Surface}; + let v = |q: [f64; 3]| Vec3::new(q[0], q[1], q[2]); + let d = |q: Vec3| [q.x, q.y, q.z]; + let line = |p: Vec3, q: Vec3| (Curve::Line { start: d(p), end: d(q) }, [0.0, 1.0]); + let circle = |o: Vec3, x: Vec3, y: Vec3, r: f64| (Curve::Circle { frame: Frame { origin: d(o), x_axis: d(x), y_axis: d(y) }, radius: r }, [a, b]); + let frame = |f: &Frame| (v(f.origin), v(f.x_axis), v(f.y_axis), v(f.x_axis).cross(v(f.y_axis))); + Ok(match surface { + Surface::Plane { origin, u_axis, v_axis } => { + let (o, x, y) = (v(*origin), v(*u_axis), v(*v_axis)); + let at = |t: f64| if along_u { o + x * t + y * fixed } else { o + x * fixed + y * t }; + line(at(a), at(b)) + } + Surface::PlaneThrough { origin, u_point, v_point } => { + let (o, x, y) = (v(*origin), v(*u_point) - v(*origin), v(*v_point) - v(*origin)); + let at = |t: f64| if along_u { o + x * t + y * fixed } else { o + x * fixed + y * t }; + line(at(a), at(b)) + } + Surface::Cylinder { frame: f, radius } => { + let (o, x, y, z) = frame(f); + if along_u { + circle(o + z * fixed, x, y, *radius) + } else { + let r = (x * fixed.cos() + y * fixed.sin()) * *radius; + line(o + r + z * a, o + r + z * b) + } + } + Surface::Cone { frame: f, radius_at_origin, half_angle } => { + let (o, x, y, z) = frame(f); + let r = |h: f64| radius_at_origin + h * half_angle.tan(); + if along_u { + circle(o + z * fixed, x, y, r(fixed)) + } else { + let dir = x * fixed.cos() + y * fixed.sin(); + line(o + dir * r(a) + z * a, o + dir * r(b) + z * b) + } + } + Surface::Sphere { frame: f, radius } => { + let (o, x, y, z) = frame(f); + if along_u { + circle(o + z * (radius * fixed.sin()), x, y, radius * fixed.cos()) + } else { + circle(o, x * fixed.cos() + y * fixed.sin(), z, *radius) + } + } + Surface::Torus { frame: f, major_radius, minor_radius, tube_start } => { + let (o, x, y, z) = frame(f); + if along_u { + let w = fixed + tube_start; + circle(o + z * (minor_radius * w.sin()), x, y, major_radius + minor_radius * w.cos()) + } else { + // The tube circle from its start, so its angle is v. + let dir = x * fixed.cos() + y * fixed.sin(); + let (s, c) = tube_start.sin_cos(); + circle(o + dir * *major_radius, dir * c + z * s, z * c - dir * s, *minor_radius) + } + } + Surface::Spline { u_knots, v_knots, points } => { + let rows: Vec> = points.iter().map(|r| r.iter().map(|q| [q[0], q[1], q[2], 1.0]).collect()).collect(); + spline_iso(u_knots, v_knots, &rows, along_u, fixed, a, b)? + } + Surface::RationalSpline { u_knots, v_knots, homogeneous } => spline_iso(u_knots, v_knots, homogeneous, along_u, fixed, a, b)?, + Surface::PlacedRevolution { .. } => { + return Err(KernelError::Failed("not supported yet: an iso curve of a revolved surface record".into())); + } + // A label: the face's (u, v) are its NURBS form's, whose rows are its iso curves. + Surface::BallPatch { .. } => return Err(KernelError::Invalid("an iso curve of a ball patch's label (take its NURBS form's)".into())), + }) +} + +/// The row of a B-spline surface (homogeneous `net[i][j]`, i along u) at `fixed`: along u, each +/// control point the v-column through it evaluated at `fixed` (along v, the u-row), on `[a, b]`. +fn spline_iso(u_knots: &[f64], v_knots: &[f64], net: &[Vec<[f64; 4]>], along_u: bool, fixed: f64, a: f64, b: f64) -> Result<(brep::Curve, [f64; 2])> { + use solidcraft_geom::bspline::CurveN; + let bad = || KernelError::Invalid("iso curve: the surface's B-spline does not evaluate".into()); + let (nu, nv) = (net.len(), net.first().map_or(0, Vec::len)); + if nu * nv > MAX_CURVE_POINTS || net.iter().any(|r| r.len() != nv) { + return Err(bad()); + } + let (pu, pv) = (u_knots.len().checked_sub(nu + 1).ok_or_else(bad)?, v_knots.len().checked_sub(nv + 1).ok_or_else(bad)?); + let at = |degree: usize, knots: &[f64], ctrl: Vec<[f64; 4]>| CurveN::<4> { degree, knots: knots.to_vec(), ctrl }.eval(fixed).map(|(p, _)| p); + let (knots, homogeneous): (Vec, Vec<[f64; 4]>) = if along_u { + (u_knots.to_vec(), net.iter().map(|row| at(pv, v_knots, row.clone())).collect::>().ok_or_else(bad)?) + } else { + ( + v_knots.to_vec(), + (0..nv).map(|j| at(pu, u_knots, net.iter().filter_map(|r| r.get(j).copied()).collect())).collect::>().ok_or_else(bad)?, + ) + }; + Ok((brep::Curve::RationalSpline { knots, homogeneous }, [a, b])) +} diff --git a/crates/kernel/src/issue_1038_tests.rs b/crates/kernel/src/issue_1038_tests.rs index 979ff729d..71e1630a5 100644 --- a/crates/kernel/src/issue_1038_tests.rs +++ b/crates/kernel/src/issue_1038_tests.rs @@ -1,13 +1,9 @@ -//! #1038: a small hole on a large curved face divides its intersection edges from each point's -//! neighbour (the vendored `IntersectionCurve::parameter_division`) instead of searching both -//! surfaces from nothing for every point. These pin the hinted division to the search from -//! nothing, so a refresh of the vendored crate can't quietly lose the speedup or change a body. +//! #1038: a small hole on a large curved face cuts cleanly, its rim on the face an intersection +//! edge. -use std::time::{Duration, Instant}; - -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; -use truck_modeling as mt; -use truck_modeling::{BoundedCurve, ParameterDivision1D}; +use solidcore_record::brep::Curve; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use crate::{Body, BoolOp, build::extrude, cylinder, ops::boolean}; @@ -24,23 +20,24 @@ fn holed() -> (Body, Body) { (block, cut) } -fn intersection_curves(body: &Body) -> Vec { - body.solid.edge_iter().map(|e| e.curve()).filter(|c| matches!(c, mt::Curve::IntersectionCurve(_))).collect() -} - -fn timed(f: impl Fn() -> T) -> (T, Duration) { - let start = Instant::now(); - let out = f(); - (out, start.elapsed()) +/// The edges that are intersection curves: neither lines nor conics (a hole's rim on a spline +/// face is a spline). +fn intersection_curves(body: &Body) -> Vec { + body.record() + .edges + .iter() + .map(|e| e.curve.clone()) + .filter(|c| matches!(c, Curve::Spline { .. } | Curve::RationalSpline { .. } | Curve::SurfaceIntersection { .. })) + .collect() } #[test] fn a_small_hole_in_a_large_spline_face_cuts_cleanly() { let (block, cut) = holed(); assert!(cut.validity().is_empty(), "{:?}", cut.validity()); - // The hole adds its wall (two half cylinders) and splits nothing: the bottom and the wave - // each gain a loop. - assert_eq!(cut.face_count(), block.face_count() + 2); + // The hole adds its wall (one cylinder, closed along its seam) and splits nothing: the + // bottom and the wave each gain a loop. + assert_eq!(cut.face_count(), block.face_count() + 1); let curves = intersection_curves(&cut); assert!(!curves.is_empty(), "the hole's rim on the wave is an intersection edge"); // The wave is within a few tenths of a millimetre of flat across a Ø1 hole, so the hole @@ -49,53 +46,3 @@ fn a_small_hole_in_a_large_spline_face_cuts_cleanly() { let removed = std::f64::consts::PI * 0.25 * 40.0; assert!((v0 - v1 - removed).abs() < 0.05 * removed, "removed {} of {removed}", v0 - v1); } - -#[test] -fn hinted_division_matches_the_search_from_nothing_and_is_faster() { - let (_, cut) = holed(); - let (mut hinted_time, mut scratch_time) = (Duration::ZERO, Duration::ZERO); - for curve in intersection_curves(&cut) { - let mt::Curve::IntersectionCurve(ic) = &curve else { continue }; - let range = ic.range_tuple(); - for tol in [0.01, 0.001] { - let ((hp, hq), ht) = timed(|| ic.parameter_division(range, tol)); - let ((sp, _), st) = timed(|| mt::algo::curve::parameter_division(ic, range, tol)); - hinted_time += ht; - scratch_time += st; - // The same division up to rounding: the hinted projections converge to within the - // Newton tolerance of the searched ones, so a split the chord test only just asks for - // can come out one way or the other, but no more than that. - assert_eq!((hp.first(), hp.last()), (sp.first(), sp.last()), "tol {tol}"); - assert!(hp.len().abs_diff(sp.len()) <= 2, "tol {tol}: {} points hinted, {} from nothing", hp.len(), sp.len()); - // Every hinted point is the curve's own point at its parameter. - for (t, h) in hp.iter().zip(&hq) { - let s = ic.search_triple(*t).unwrap().0; - assert!(mt::MetricSpace::distance(*h, s) < 1e-6, "tol {tol}, t {t}: {h:?} vs {s:?}"); - } - } - } - eprintln!("hinted {hinted_time:?}, from nothing {scratch_time:?}"); - // The hinted path skips each point's grid search of the B-spline face; a loose bound, so a - // loaded runner doesn't trip it, but one a fallback to the search for every point would. - assert!(hinted_time * 2 < scratch_time, "hinted {hinted_time:?}, from nothing {scratch_time:?}"); -} - -/// #4623: dividing an intersection edge at a tolerance finer than truck's 1e-6 (or one that is -/// not a number) panicked in truck's tolerance assertion, and the join that asked for it failed. -/// It divides at 1e-6 instead. -#[test] -fn dividing_an_intersection_edge_finer_than_truck_allows_divides_at_its_tolerance() { - let (_, cut) = holed(); - let curves = intersection_curves(&cut); - assert!(!curves.is_empty()); - for curve in curves { - let mt::Curve::IntersectionCurve(ic) = &curve else { continue }; - let range = ic.range_tuple(); - let at_truck = ic.parameter_division(range, 1e-6); - for tol in [5e-7, 1e-12, 0.0, -1.0, f64::NAN] { - let got = std::panic::catch_unwind(|| ic.parameter_division(range, tol)); - let Ok(got) = got else { panic!("dividing at {tol:e} panicked") }; - assert_eq!(got, at_truck, "tolerance {tol:e}"); - } - } -} diff --git a/crates/kernel/src/issue_1080_tests.rs b/crates/kernel/src/issue_1080_tests.rs index e7ac18c55..f1f30e32e 100644 --- a/crates/kernel/src/issue_1080_tests.rs +++ b/crates/kernel/src/issue_1080_tests.rs @@ -1,7 +1,11 @@ -//! #1080: fillets and chamfers that would run past the faces beside their edge (into a pocket, -//! a hole, another blend) are refused with the largest size that fits, not built through it. +//! #1080: fillets and chamfers that would run past the faces beside their edge. A convex blend +//! running over a face's far edge into a pocket or a hole (a cliff) is built as if its faces went +//! on and what it removes is cut from the body, so it never bridges the opening (the owner's +//! blend-overflow decision, 237f0ae74); blends that would cross each other are refused as too +//! large, and the largest size that fits is found by searching ([`crate::fillet_max`], +//! [`crate::chamfer_max`]). -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::{Body, BoolOp, ChamferSide, KernelError, build::box_solid, ops::boolean}; @@ -22,33 +26,53 @@ fn too_large(r: crate::Result) -> String { match r { Err(KernelError::TooLarge(m)) => m, Err(e) => panic!("refused, but not as too large: {e}"), - Ok(_) => panic!("a blend through the pocket was accepted"), + Ok(_) => panic!("a blend that runs into another was accepted"), } } +/// The pocketed block's volume: 16000 less the 1000 mm³ pocket. +const POCKETED: f64 = 15000.0; + +/// The 6 mm chamfer runs 2 mm past the pocket's rim at x = 36: its triangle +/// (40 − x) + (20 − z) <= 6, area 18 along the 20 mm edge, less its part over the pocket +/// (x in [34, 36], z >= 54 − x: area 2, along the pocket's 10 mm), is cut away: 360 − 20. #[test] -fn chamfer_into_a_pocket_is_refused_with_the_size_that_fits() { +fn chamfer_into_a_pocket_is_cut_by_it() { let p = pocketed(); - let m = too_large(crate::chamfer(&p, &[EDGE], 6.0)); - assert!(m.contains("runs past the faces beside the edge") && m.contains("the largest size that fits is 4 mm"), "{m}"); + let b = crate::chamfer(&p, &[EDGE], 6.0).unwrap(); + assert!(b.validity().is_empty(), "{:?}", b.validity()); + let v = crate::measure(&b).unwrap().volume; + assert!((v - (POCKETED - 340.0)).abs() < 1e-6, "{v}"); // Up to the pocket's rim it builds: the triangle along the 20 mm edge. for s in [2.0, 4.0] { let b = crate::chamfer(&p, &[EDGE], s).unwrap(); let v = b.volume_at(0.01).unwrap(); assert!((p.volume_at(0.01).unwrap() - v - 0.5 * s * s * 20.0).abs() < 1e-6, "{s}: {v}"); } - // Unequal sides: along the top 6 is past the pocket, along the side it is not. - let m = too_large(crate::chamfer_sides(&p, &[EDGE], 6.0, ChamferSide::Distance(2.0), false)); - assert!(m.contains("runs past"), "{m}"); - assert!(crate::chamfer_sides(&p, &[EDGE], 2.0, ChamferSide::Distance(6.0), false).is_ok()); + // Unequal sides, 6 along the top and 2 down the side: the triangle + // (40 − x) / 6 + (20 − z) / 2 <= 1, area 6 along 20, less its part over the pocket + // (x in [34, 36], a triangle 2 by 2/3), along 10: 120 − 20/3. The other way round it stays + // clear of the pocket: 120. + let b = crate::chamfer_sides(&p, &[EDGE], 6.0, ChamferSide::Distance(2.0), false).unwrap(); + let v = crate::measure(&b).unwrap().volume; + assert!((v - (POCKETED - (120.0 - 20.0 / 3.0))).abs() < 1e-6, "{v}"); + let b = crate::chamfer_sides(&p, &[EDGE], 2.0, ChamferSide::Distance(6.0), false).unwrap(); + let v = crate::measure(&b).unwrap().volume; + assert!((v - (POCKETED - 120.0)).abs() < 1e-6, "{v}"); } +/// R5 runs 1 mm past the pocket's rim: the round's section (1 − π/4)·25 along 20, less its part +/// over the pocket, the square [35, 36] × [15, 20] outside the circle about (35, 15) of radius 5, +/// ∫₀¹ (5 − √(25 − t²)) dt = 5 − (√24 / 2 + (25/2)·asin(1/5)), along 10. #[test] -fn fillet_into_a_pocket_is_refused_and_one_that_fits_builds() { +fn fillet_into_a_pocket_is_cut_by_it_and_one_that_fits_builds() { let p = pocketed(); - // The round build refuses it itself; the largest radius that fits is added. - let m = crate::fillet(&p, &[EDGE], 5.0).unwrap_err().to_string(); - assert!(m.contains("the largest radius that fits is 4 mm"), "{m}"); + let over = 5.0 - (24f64.sqrt() / 2.0 + 12.5 * (0.2f64).asin()); + let want = POCKETED - ((1.0 - std::f64::consts::FRAC_PI_4) * 25.0 * 20.0 - over * 10.0); + let b = crate::fillet(&p, &[EDGE], 5.0).unwrap(); + assert!(b.validity().is_empty(), "{:?}", b.validity()); + let v = crate::measure(&b).unwrap().volume; + assert!((v - want).abs() < 1e-6 * want, "{v} vs {want}"); let b = crate::fillet(&p, &[EDGE], 3.0).unwrap(); assert!(b.validity().is_empty(), "{:?}", b.validity()); assert_eq!(b.face_count(), p.face_count() + 1); @@ -56,19 +80,23 @@ fn fillet_into_a_pocket_is_refused_and_one_that_fits_builds() { /// A rib 4 mm wide: chamfers of its two top edges meet in the middle of its top face at 2 mm; /// past that they would cross each other. Neither reaches the far side's face below 4 mm, -/// so only the two blends clash. +/// so only the two blends clash: refused as too large, and the largest that fits is 2 mm. #[test] fn chamfers_crossing_each_other_are_refused() { let rib = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 4.0, 20.0)).unwrap(); let edges = [Vec3::new(20.0, 0.0, 20.0), Vec3::new(20.0, 4.0, 20.0)]; - let m = too_large(crate::chamfer(&rib, &edges, 3.0)); - assert!(m.contains("would cross each other") && m.contains("the largest size that fits is 2 mm"), "{m}"); - let m = crate::fillet(&rib, &edges, 3.0).unwrap_err().to_string(); - assert!(m.contains("the largest radius that fits is 2 mm"), "{m}"); + too_large(crate::chamfer(&rib, &edges, 3.0)); + too_large(crate::fillet(&rib, &edges, 3.0)); + assert_eq!(crate::chamfer_max(&rib, &edges, 3.0).unwrap().map(|x| x.0), Some(2.0)); + assert_eq!(crate::fillet_max(&rib, &edges, 3.0, crate::FilletTurn::Mitre).unwrap().map(|x| x.0), Some(2.0)); // Below half the width both build. let b = crate::chamfer(&rib, &edges, 1.5).unwrap(); assert!((b.volume_at(0.01).unwrap() - (3200.0 - 2.0 * 0.5 * 1.5 * 1.5 * 40.0)).abs() < 1e-6); - assert!(crate::fillet(&rib, &edges, 1.5).is_ok()); + // Two rounds of radius 1.5 along 40: each removes (1 − π/4)·1.5² of section. + let b = crate::fillet(&rib, &edges, 1.5).unwrap(); + let want = 3200.0 - 2.0 * (1.0 - std::f64::consts::FRAC_PI_4) * 2.25 * 40.0; + let v = crate::measure(&b).unwrap().volume; + assert!((v - want).abs() < 1e-6 * want, "{v} vs {want}"); } /// Edges meeting at a corner mitre: their chamfers overlap there and are not refused for it. @@ -76,87 +104,14 @@ fn chamfers_crossing_each_other_are_refused() { fn chamfers_meeting_at_a_corner_still_build() { let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(20.0, 20.0, 20.0)).unwrap(); let edges = [Vec3::new(10.0, 0.0, 20.0), Vec3::new(20.0, 10.0, 20.0), Vec3::new(10.0, 20.0, 20.0), Vec3::new(0.0, 10.0, 20.0)]; - assert!(crate::chamfer(&b, &edges, 5.0).is_ok()); - assert!(crate::fillet(&b, &edges, 5.0).is_ok()); -} - -/// A result that changes more of the part than the blends can is refused (#871's shelled box -/// lost 240 mm³ more than any round of its edge could take). -#[test] -fn a_result_that_removes_more_than_the_blend_is_refused() { - let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(20.0, 20.0, 20.0)).unwrap(); - let e = [Vec3::new(10.0, 0.0, 20.0)]; - let size = crate::blend_fit::Size::Chamfer(2.0); - let good = crate::chamfer(&b, &e, 2.0).unwrap(); - assert!(crate::blend_fit::check_volume(&b, good, &e, size).is_ok()); - // A chamfer and a 1 mm slab off the far side as well. - let worse = cut(&crate::chamfer(&b, &e, 2.0).unwrap(), [0.0, 19.0, 0.0], [20.0, 20.0, 20.0]); - let m = too_large(crate::blend_fit::check_volume(&b, worse, &e, size)); - assert!(m.contains("more than the chamfer can"), "{m}"); -} - -/// #1668: a box shelled outward 2 mm, open at the bottom. R5 on its top outer edge alone leaves -/// the sharp inside corner 2 mm away on its ball's side, 0.76 mm inside the round; it reaches -/// the corner only past 2√2 / (√2 - 1) ≈ 6.83 mm. With the inside edge rounded in the same -/// fillet, the two build as one feature as they do one after the other: the outer round takes -/// (1 - π/4) · 25 mm² along 104 mm, the inner one adds it along 100 mm. -#[test] -fn rounds_on_both_sides_of_a_wall_build_as_one_fillet() { - let outer = box_solid(Vec3::new(-52.0, -32.0, 0.0), Vec3::new(52.0, 32.0, 42.0)).unwrap(); - let shelled = cut(&outer, [-50.0, -30.0, -1.0], [50.0, 30.0, 40.0]); - let (out_edge, in_edge) = (Vec3::new(0.0, 32.0, 42.0), Vec3::new(0.0, 30.0, 40.0)); - let section = (1.0 - std::f64::consts::FRAC_PI_4) * 25.0; - let alone = crate::fillet(&shelled, &[out_edge], 5.0).unwrap(); - assert!(alone.validity().is_empty(), "{:?}", alone.validity()); - let want = shelled.volume_at(0.01).unwrap() - section * 104.0; - assert!((crate::measure(&alone).unwrap().volume - want).abs() < 1e-4 * want); - let m = too_large(crate::fillet(&shelled, &[out_edge], 7.0)); - let largest: f64 = m.rsplit("that fits is ").next().and_then(|t| t.trim_end_matches(" mm").parse().ok()).unwrap_or(0.0); - let limit = 2.0 * 2f64.sqrt() / (2f64.sqrt() - 1.0); - assert!(largest <= limit && largest > limit - 0.5, "{m}"); - let both = crate::fillet(&shelled, &[out_edge, in_edge], 5.0).unwrap(); - assert!(both.validity().is_empty(), "{:?}", both.validity()); - let want = shelled.volume_at(0.01).unwrap() - section * 104.0 + section * 100.0; - let v = crate::measure(&both).unwrap().volume; - assert!((v - want).abs() < 1e-4 * want, "{v} vs {want}"); - let stepped = crate::fillet(&crate::fillet(&shelled, &[in_edge], 5.0).unwrap(), &[out_edge], 5.0).unwrap(); - assert!((crate::measure(&stepped).unwrap().volume - v).abs() < 1e-4 * want); - // Past the wall's own room they still cross: R7's outer round reaches the inner one's arc. - let m = too_large(crate::fillet(&shelled, &[out_edge, in_edge], 7.0)); - assert!(m.contains("the largest radius that fits"), "{m}"); -} - -/// A shell 3 mm thick bent over like an upside-down U: 60 wide, 20 long, 50 high, its top -/// plate from z = 47 to 50 and its walls from x = 0 to 3 and 57 to 60. -fn bent_shell() -> Body { - let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 20.0, 50.0)).unwrap(); - cut(&b, [3.0, -1.0, -1.0], [57.0, 21.0, 47.0]) -} - -/// The corner left by a round of radius `r` on a 90° edge, per unit length. -fn corner(r: f64) -> f64 { - r * r * (1.0 - std::f64::consts::FRAC_PI_4) -} - -/// An outside round concentric with the inside one keeps the wall 3 mm thick: the inside round -/// lies inside the outside one's wedge, but on its ball's side of the arc, which the round -/// leaves as it is. It used to be refused as running into other geometry. -#[test] -fn outside_round_concentric_with_the_inside_round_of_a_wall_fits() { - let s = bent_shell(); - let inside = [Vec3::new(3.0, 10.0, 47.0), Vec3::new(57.0, 10.0, 47.0)]; - let outside = [Vec3::new(0.0, 10.0, 50.0), Vec3::new(60.0, 10.0, 50.0)]; - let a = crate::fillet(&s, &inside, 15.0).unwrap(); - let b = crate::fillet(&a, &outside, 18.0).unwrap(); - assert!(b.validity().is_empty(), "{:?}", b.validity()); - // The inside rounds fill their corners, the outside ones take theirs away. - let want = s.volume_at(0.01).unwrap() + 2.0 * 20.0 * (corner(15.0) - corner(18.0)); - let got = b.volume_at(0.01).unwrap(); - assert!((got - want).abs() < 1e-3 * want, "{got} for {want}"); - // Larger, the outside round's centre moves off the inside one's: it runs into the hollow - // where its arc crosses the inside round's, at r = (18√2 - 15) / (√2 - 1) ≈ 25.24 mm. - let m = too_large(crate::fillet(&a, &outside, 30.0)); - let largest: f64 = m.rsplit("that fits is ").next().and_then(|t| t.trim_end_matches(" mm").parse().ok()).unwrap_or(0.0); - let limit = (18.0 * 2f64.sqrt() - 15.0) / (2f64.sqrt() - 1.0); - assert!(largest <= limit && largest > limit - 0.5, "{m}"); + // The chamfers leave the 20 x 20 x 15 block under a frustum from 20 x 20 to 10 x 10, 5 high: + // 6000 + (5/3)(400 + 100 + √(400·100)). + let v = crate::measure(&crate::chamfer(&b, &edges, 5.0).unwrap()).unwrap().volume; + let want = 6000.0 + 5.0 / 3.0 * (400.0 + 100.0 + 200.0); + assert!((v - want).abs() < 1e-6 * want, "{v} vs {want}"); + // The rounds: (1 − π/4)·25 of section along each edge's 10 mm between the corners, and in each + // 5 mm corner cube the two cylinders' intersection is kept, ∫₀⁵ (25 − w²) dw = 250/3 of 125. + let v = crate::measure(&crate::fillet(&b, &edges, 5.0).unwrap()).unwrap().volume; + let want = 8000.0 - 4.0 * (1.0 - std::f64::consts::FRAC_PI_4) * 25.0 * 10.0 - 4.0 * (125.0 - 250.0 / 3.0); + assert!((v - want).abs() < 1e-6 * want, "{v} vs {want}"); } diff --git a/crates/kernel/src/issue_1510_tests.rs b/crates/kernel/src/issue_1510_tests.rs index b942ebe18..a908d647b 100644 --- a/crates/kernel/src/issue_1510_tests.rs +++ b/crates/kernel/src/issue_1510_tests.rs @@ -1,7 +1,8 @@ //! #1510: a body split by a plane that a face of the body lies in: the parts meet in the plane //! and together are the body. -use solidcraft_geom::{Plane, Vec3}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::prelude::*; use crate::{Body, BoolOp, build::box_solid, build::cylinder, ops::boolean, ops::split_by_plane}; @@ -22,13 +23,14 @@ fn plate(width: f64) -> Body { fn a_split_in_the_plane_of_a_face_keeps_all_of_the_body() { for width in [4.0, 5.0] { let b = plate(width); - let v = b.volume_at(1e-3).unwrap(); + // Exact volumes (SMLib's, to 1e-8): a mesh's at a 1e-3 chord sags round the hole by more + // than the millionth the parts are held to. + let v = crate::measure(&b).unwrap().volume; let plane = Plane::from_normal(Vec3::new(0.0, 0.0, 1.5), Vec3::Z).unwrap(); - let (parts, d) = crate::capture_boolean_diagnostics(|| split_by_plane(&b, &plane)); - let parts = parts.unwrap(); + let parts = split_by_plane(&b, &plane).unwrap(); assert_eq!(parts.len(), 2, "{width}"); - let vs: Vec = parts.iter().map(|p| p.volume_at(1e-3).unwrap()).collect(); - assert!((vs.iter().sum::() - v).abs() < 1e-6 * v, "{width}: {vs:?} against {v}; {:?}", d.summary()); + let vs: Vec = parts.iter().map(|p| crate::measure(p).unwrap().volume).collect(); + assert!((vs.iter().sum::() - v).abs() < 1e-6 * v, "{width}: {vs:?} against {v}"); // Above: the plate from 1.5 to 2.5 less the hole; below: less the hole and the groove. let (r, h) = (2.5f64, width / 2.0); let hole = std::f64::consts::PI * r * r; @@ -36,44 +38,31 @@ fn a_split_in_the_plane_of_a_face_keeps_all_of_the_body() { let groove = width * 20.0 - (h * (r * r - h * h).sqrt() + r * r * (h / r).asin()); let want = [800.0 - hole, 1.5 * (800.0 - hole - groove)]; for (got, want) in vs.iter().zip(want) { - assert!((got - want).abs() < 0.05, "{width}: {vs:?} against {want}; {:?}", d.summary()); + assert!((got - want).abs() < 0.05, "{width}: {vs:?} against {want}"); } // Both parts end in the plane, not off it. let z: Vec<(f64, f64)> = parts.iter().map(|p| crate::measure(p).map(|m| (m.bbox.min.z, m.bbox.max.z)).unwrap()).collect(); - assert!((z[0].0 - 1.5).abs() < 1e-6 && (z[1].1 - 1.5).abs() < 1e-6, "{width}: {z:?}; {:?}", d.summary()); + assert!((z[0].0 - 1.5).abs() < 1e-6 && (z[1].1 - 1.5).abs() < 1e-6, "{width}: {z:?}"); } } /// A slab whose bottom rises 0.03 mm over its 700 mm length, its plane through the origin: its -/// normal is within 1e-9 of the split plane's, but it doesn't lie in the plane, so it is not -/// moved, and the part on the upper side is the whole slab. +/// normal is within 1e-9 of the split plane's, but it doesn't lie in the plane, so the part on +/// the upper side is the whole slab. #[test] fn a_face_only_nearly_in_the_plane_is_not_moved() { - use truck_modeling as mt; - let v = |x: f64, y: f64, z: f64| mt::builder::vertex(crate::body::p3(Vec3::new(x, y, z))); - let p = [v(0.0, 0.0, 0.0), v(0.0, 100.0, 0.0), v(700.0, 100.0, 0.03), v(700.0, 0.0, 0.03)]; - let wire: mt::Wire = (0..4).map(|i| mt::builder::line(&p[i], &p[(i + 1) % 4])).collect(); - let surface = mt::Plane::new(crate::body::p3(Vec3::ZERO), crate::body::p3(Vec3::Y), crate::body::p3(Vec3::new(700.0, 0.0, 0.03))); - let bottom = mt::Face::new(vec![wire], mt::Surface::Plane(surface)); - let b = Body::new(mt::builder::tsweep(&bottom, mt::Vector3::new(0.0, 0.0, 10.0))).unwrap(); + let x = Vec3::new(700.0, 0.0, 0.03).normalized().unwrap(); + let bottom = Plane::new(Vec3::ZERO, x, Vec3::Y).unwrap(); + let outer = solidcore_record::Loop2::polygon(&[ + solidcore_record::Vec2::new(0.0, 0.0), + solidcore_record::Vec2::new(Vec3::new(700.0, 0.0, 0.03).len(), 0.0), + solidcore_record::Vec2::new(Vec3::new(700.0, 0.0, 0.03).len(), 100.0), + solidcore_record::Vec2::new(0.0, 100.0), + ]); + let b = crate::extrude(&bottom, &[solidcore_record::Region2 { outer, holes: vec![] }], 0.0, 10.0).unwrap().pop().unwrap(); let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap(); - assert!(crate::ops::off_plane(&b, &plane, true).is_none()); let v0 = b.volume_at(1e-2).unwrap(); let up = crate::ops::half_space(&b, &plane, true).unwrap().0.unwrap(); let v1 = up.volume_at(1e-2).unwrap(); assert!((v1 - v0).abs() < 1e-3 * v0, "{v1} against {v0}"); } - -/// A box whose top face is 3e-5 above the plane, within the boolean's tolerance but off it: the -/// face bounds a real sliver, and it is not moved. -#[test] -fn a_face_close_to_the_plane_but_off_it_is_not_moved() { - let b = box_solid(Vec3::new(0.0, 0.0, -10.0), Vec3::new(700.0, 100.0, 3e-5)).unwrap(); - let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap(); - assert!(crate::ops::off_plane(&b, &plane, true).is_none()); - assert!(crate::ops::off_plane(&b, &plane, false).is_none()); - // A face in the plane is moved. - let plate = plate(4.0); - let at = Plane::from_normal(Vec3::new(0.0, 0.0, 1.5), Vec3::Z).unwrap(); - assert!(crate::ops::off_plane(&plate, &at, true).is_some() && crate::ops::off_plane(&plate, &at, false).is_some()); -} diff --git a/crates/kernel/src/issue_2005_tests.rs b/crates/kernel/src/issue_2005_tests.rs index 78c328e43..2db4e7036 100644 --- a/crates/kernel/src/issue_2005_tests.rs +++ b/crates/kernel/src/issue_2005_tests.rs @@ -5,7 +5,7 @@ use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::{Body, BoolOp, PathSeg, SweepControl, boolean, measure, sweep_with}; @@ -31,9 +31,12 @@ fn circle_path() -> [PathSeg; 2] { fn tube(body: &Body, volume: f64, genus: usize) { let m = measure(body).unwrap(); assert!((m.volume - volume).abs() < volume * 0.01, "{m:?}, expected {volume}"); - // A closed orientable tube has Euler characteristic 2 - 2g. Coincident caps gave 2. - assert_eq!(m.vertices + m.faces + 2 * genus, m.edges + 2, "{m:?}"); - assert!(body.solid.boundaries().iter().all(|s| s.extract_boundaries().is_empty())); + // A closed orientable tube of genus g: V - E + F - (L - F) = 2 - 2g (Euler-Poincare, L the + // loops: an annular face has two). Coincident caps gave 2 - 2g + 2. + let loops: usize = body.record().faces.iter().map(|f| f.loops.len()).sum(); + assert_eq!(m.vertices + 2 * m.faces + 2 * genus, m.edges + loops + 2, "{m:?}, {loops} loops"); + // Every shell closed: each edge bounds two faces. + assert!(body.record().edges.iter().all(|e| e.uses.len() >= 2)); let h = body.history().expect("sweep provenance"); assert!(h.faces.iter().all(|f| f.origins.iter().all(|o| matches!(o, crate::history::FaceOrigin::Profile { .. })))); } diff --git a/crates/kernel/src/issue_324_tests.rs b/crates/kernel/src/issue_324_tests.rs deleted file mode 100644 index 57cb86a52..000000000 --- a/crates/kernel/src/issue_324_tests.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! #324: a round on a block's top edge that would overlap a through hole is refused, and the -//! largest radius the refusal offers fits. - -use solidcraft_geom::Vec3; - -use crate::{Body, BoolOp, build::box_solid, build::cylinder, ops::boolean}; - -/// A 40 x 20 x 10 block with a through hole of radius 3 at (20, `y`). -fn block_with_hole(y: f64) -> Body { - let block = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 20.0, 10.0)).unwrap(); - let hole = cylinder(Vec3::new(20.0, y, -1.0), Vec3::Z, 3.0, 12.0).unwrap(); - boolean(&block, &hole, BoolOp::Cut).unwrap().unwrap() -} - -/// The round on the top edge at y = 20 covers the top face from y = 20 - r, and the hole's -/// wall reaches y = 17.5: a radius over 2.5 runs into the hole. The refusal of 4 mm offered -/// 2.721 mm, which was refused the same way: the curved wall's mesh, with its tolerance, was -/// first seen inside the round's region 0.22 mm past where the wall really enters it. -#[test] -fn the_radius_offered_beside_a_hole_fits() { - let b = block_with_hole(14.5); - let edge = Vec3::new(10.0, 20.0, 10.0); - let m = crate::fillet(&b, &[edge], 4.0).unwrap_err().to_string(); - let offered: f64 = m - .split("the largest radius that fits is ") - .nth(1) - .and_then(|s| s.split(' ').next()) - .and_then(|s| s.parse().ok()) - .unwrap_or_else(|| panic!("no radius offered: {m}")); - assert!(offered > 2.0 && offered <= 2.5, "{m}"); - let r = crate::fillet(&b, &[edge], offered).unwrap(); - assert!(r.validity().is_empty(), "{:?}", r.validity()); - // The block, the hole and the round's corner: the round stays clear of the hole. - let want = 8000.0 - std::f64::consts::PI * 9.0 * 10.0 - 40.0 * offered * offered * (1.0 - std::f64::consts::FRAC_PI_4); - let v = r.volume_at(0.005).unwrap(); - assert!((v - want).abs() < 0.05, "{v} against {want}"); -} diff --git a/crates/kernel/src/issue_616_tests.rs b/crates/kernel/src/issue_616_tests.rs index 5d6d9e0b8..ec7a118b4 100644 --- a/crates/kernel/src/issue_616_tests.rs +++ b/crates/kernel/src/issue_616_tests.rs @@ -1,7 +1,9 @@ //! Issue #616: small boxes joined flush to the walls and floor of a part never change it away //! from the box, and a retry that would is refused. -use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Aabb3, Mesh}; use crate::*; @@ -54,7 +56,11 @@ fn moved_outside(from: &Mesh, onto: &Mesh, region: &Aabb3, tol: f64) -> Option 0.99)).unwrap(); - let side = b.solid.face_iter().position(|f| !matches!(f.surface(), Surface::Plane(_))).unwrap(); + let side = b + .record() + .faces + .iter() + .position(|f| !matches!(f.surface, solidcore_record::brep::Surface::Plane { .. } | solidcore_record::brep::Surface::PlaneThrough { .. })) + .unwrap(); let r = split_faces(&a, &[face], &SplitTool::Face { body: &b, face: side }).unwrap(); assert_eq!(r.face_count(), a.face_count() + 1); assert!(r.validity().is_empty(), "{:?}", r.validity()); @@ -19,20 +24,11 @@ fn split_contact_arc_crossing_one_edge_twice_preserves_the_body() { assert!((before.area - after.area).abs() < 1e-7); } -#[test] -fn partial_contact_does_not_join_tangent_or_separated_faces() { - let a = box_solid(Vec3::ZERO, Vec3::new(25.0, 47.5, 37.5)).unwrap(); - for z in [-5.0, -6.0] { - let b = cylinder(Vec3::new(0.0, 7.5, z), -Vec3::X, 5.0, 2.5).unwrap(); - assert!(crate::coplanar::imprint_union(&a, &b, &|_| true).is_none()); - } -} - #[test] fn partial_contact_retains_an_authored_split_away_from_the_contact() { let a = box_solid(Vec3::ZERO, Vec3::new(25.0, 47.5, 37.5)).unwrap(); let face = a.faces(0.01).unwrap().iter().position(|f| f.plane_normal.is_some_and(|n| n.dot(Vec3::X) > 0.99)).unwrap(); - let a = split_faces(&a, &[face], &SplitTool::Plane(solidcraft_geom::Plane { origin: Vec3::new(0.0, 0.0, 15.0), ..solidcraft_geom::Plane::XY })) + let a = split_faces(&a, &[face], &SplitTool::Plane(solidcore_record::Plane { origin: Vec3::new(0.0, 0.0, 15.0), ..solidcore_record::Plane::XY })) .unwrap(); let b = cylinder(Vec3::new(0.0, 7.5, 0.0), -Vec3::X, 5.0, 2.5).unwrap(); let r = boolean(&a, &b, BoolOp::Union).unwrap().unwrap(); diff --git a/crates/kernel/src/issue_679_tests.rs b/crates/kernel/src/issue_679_tests.rs index 3306c2aec..a1dc7bd8e 100644 --- a/crates/kernel/src/issue_679_tests.rs +++ b/crates/kernel/src/issue_679_tests.rs @@ -2,7 +2,7 @@ //! grid extruded up and down (#679), a pad half past the edge of the face it stands on (#674), //! several contact regions, contact beside a shared edge, and random rectangles. -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::*; @@ -15,9 +15,8 @@ fn rect(x0: f64, y0: f64, x1: f64, y1: f64, z0: f64, z1: f64) -> Body { box_solid(Vec3::new(x0, y0, z0), Vec3::new(x1, y1, z1)).unwrap() } -fn fused(a: &Body, b: &Body) -> (Body, BooleanDiagnostics) { - let (r, d) = capture_boolean_diagnostics(|| boolean(a, b, BoolOp::Union)); - (r.unwrap().unwrap(), d) +fn fused(a: &Body, b: &Body) -> Body { + boolean(a, b, BoolOp::Union).unwrap().unwrap() } fn assert_one_solid(r: &Body, volume: f64, tol: f64, what: &str) { @@ -34,9 +33,8 @@ fn two_ls_up_and_down_fuse_into_one_solid() { let up = prism(&[[-10., -10.], [10., -10.], [10., 0.], [0., 0.], [0., 10.], [-10., 10.]], 0., 10.); let down = prism(&[[-10., 10.], [-10., 0.], [0., 0.], [0., -10.], [10., -10.], [10., 10.]], -10., 0.); for (a, b) in [(&up, &down), (&down, &up)] { - let (r, d) = fused(a, b); + let r = fused(a, b); assert_one_solid(&r, 6000.0, 1e-6, "#679"); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{d:?}"); // Two tops, two bottoms, the two cells left open at z = 0, six sides. assert_eq!(r.face_count(), 12); } @@ -51,12 +49,12 @@ fn several_contact_regions_and_edge_contact() { let ups = boolean(&up, &up2, BoolOp::Union).unwrap().unwrap(); // Down under both up cells, and under one more. let down = prism(&[[-10., -10.], [0., -10.], [0., 0.], [10., 0.], [10., 10.], [-10., 10.]], -5., 0.); - let (r, _) = fused(&ups, &down); + let r = fused(&ups, &down); assert_one_solid(&r, 2.0 * 640.0 + 3.0 * 500.0, 1e-6, "two contacts"); // Down under one up cell and beside the other: one face contact and one edge contact. // A plate under one block, flush with two of its sides and running on past the third. let down = rect(-10., -10., -2., 5., -5., 0.); - let (r, _) = fused(&up, &down); + let r = fused(&up, &down); assert_one_solid(&r, 640.0 + 8.0 * 15.0 * 5.0, 1e-6, "contact and flush sides"); } @@ -71,10 +69,9 @@ fn a_pad_half_past_the_edge_of_its_face_fuses() { let want = measure(&block).unwrap().volume + measure(&pad).unwrap().volume; assert!((want - (25.0 * 47.5 * 37.5 + std::f64::consts::PI * 25.0 * 2.5)).abs() < 0.1); for (a, b) in [(&block, &pad), (&pad, &block)] { - let (r, d) = fused(a, b); + let r = fused(a, b); assert_one_solid(&r, want, 1e-6 * want, "#674"); - assert!(d.events.is_empty(), "an exact join: {d:?}"); - let bounds = r.tessellate(0.01).unwrap().bounds(); + let bounds = r.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().bounds(); assert!((bounds.min.y + 2.5).abs() < 1e-9 && (bounds.min.z + 5.0).abs() < 0.01, "{bounds:?}"); } } @@ -101,9 +98,8 @@ fn random_rectangles_either_side_of_a_plane_fuse_exactly() { let down = rect(x1, y1, x1 + w1, y1 + h1, -t1, 0.); let want = w0 * h0 * t0 + w1 * h1 * t1; let what = format!("case {case}: up {x0},{y0} {w0}x{h0}x{t0}, down {x1},{y1} {w1}x{h1}x{t1}"); - let (r, d) = fused(&up, &down); + let r = fused(&up, &down); assert_one_solid(&r, want, 1e-6 * want, &what); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{what}: {d:?}"); done += 1; } assert_eq!(done, 30); diff --git a/crates/kernel/src/issue_788_tests.rs b/crates/kernel/src/issue_788_tests.rs index f12492352..7a3d5ab52 100644 --- a/crates/kernel/src/issue_788_tests.rs +++ b/crates/kernel/src/issue_788_tests.rs @@ -1,9 +1,8 @@ //! Two bores of one radius crossing each other (#788): the surfaces touch where the two ellipses //! of the crossing meet, which a mesh intersection cannot trace and a boolean cannot take in the //! middle of a face. -use crate::tangent_cylinders; use crate::*; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use std::f64::consts::PI; const SIDE: f64 = 45.0; @@ -114,38 +113,3 @@ fn faces_split_for_the_crossing_leave_the_operands_alone() { assert_eq!(one.face_count(), faces); assert_eq!(volume(&one), volume_before); } - -#[test] -fn crossings_that_are_not_touching_are_left_alone() { - let r = 10.0; - let size = 100.0; - let tol = size * 1e-6; - let cyl = |face, origin: Vec3, axis: Vec3, radius| tangent_cylinders::Cylinder::new(face, origin, axis, radius).unwrap(); - let z = cyl(0, Vec3::ZERO, Vec3::Z, r); - // Different radius, parallel axes, skew axes: no touching points to split at. - assert!(tangent_cylinders::crossing(&z, &cyl(1, Vec3::ZERO, Vec3::Y, r * 0.9), tol).is_none()); - assert!(tangent_cylinders::crossing(&z, &cyl(1, Vec3::new(5.0, 0.0, 0.0), Vec3::Z, r), tol).is_none()); - assert!(tangent_cylinders::crossing(&z, &cyl(1, Vec3::new(0.0, 0.0, 0.0), Vec3::new(1e-6, 0.0, 1.0), r), tol).is_none()); - assert!(tangent_cylinders::crossing(&z, &cyl(1, Vec3::new(1.0, 0.0, 0.0), Vec3::Y, r), tol).is_none()); - // Axes that meet: two touching points, a radius either side of the crossing. - let found = tangent_cylinders::crossing(&z, &cyl(1, Vec3::ZERO, Vec3::Y, r), tol).unwrap(); - assert!(found.points.iter().any(|p| p.dist(Vec3::new(r, 0.0, 0.0)) < 1e-9)); - assert!(found.points.iter().any(|p| p.dist(Vec3::new(-r, 0.0, 0.0)) < 1e-9)); -} - -#[test] -fn hostile_cylinders_are_refused() { - let tol = 1e-4; - let cyl = |axis: Vec3, radius, origin: Vec3| tangent_cylinders::Cylinder::new(0, origin, axis, radius); - // An axis with no direction cannot make a cylinder at all. - assert!(cyl(Vec3::new(f64::NAN, 0.0, 1.0), 10.0, Vec3::ZERO).is_none()); - assert!(cyl(Vec3::ZERO, 10.0, Vec3::ZERO).is_none()); - let good = cyl(Vec3::Z, 10.0, Vec3::ZERO).unwrap(); - for bad in [ - cyl(Vec3::Y, f64::NAN, Vec3::ZERO).unwrap(), - cyl(Vec3::Y, f64::INFINITY, Vec3::ZERO).unwrap(), - cyl(Vec3::Y, 10.0, Vec3::new(f64::INFINITY, 0.0, 0.0)).unwrap(), - ] { - assert!(tangent_cylinders::crossing(&good, &bad, tol).is_none(), "{bad:?}"); - } -} diff --git a/crates/kernel/src/issue_851_tests.rs b/crates/kernel/src/issue_851_tests.rs index a214d68f2..8190730b5 100644 --- a/crates/kernel/src/issue_851_tests.rs +++ b/crates/kernel/src/issue_851_tests.rs @@ -1,6 +1,6 @@ //! Fillets and chamfers where a curved wall runs out into a flat face in a knife edge (#851). use crate::*; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use std::f64::consts::PI; const R_WALL: f64 = 21.0; @@ -56,19 +56,6 @@ fn part_cut_from_a_box() -> Body { boolean(&slab, &disc, BoolOp::Cut).unwrap().unwrap() } -/// Area a chamfer of distance `d` takes off the cusp: the triangle between the plane's contact, -/// the tip and the wall's contact, less the wall's circular segment. -fn chamfered_area(d: f64) -> f64 { - let beta = ((R_WALL - d) / (R_WALL + d)).acos(); - let o = (TIP_X - (4.0 * R_WALL * d).sqrt(), -d); - let c = (TIP_X, -R_WALL); - let k = R_WALL / (R_WALL + d); - let q2 = (c.0 + (o.0 - c.0) * k, c.1 + (o.1 - c.1) * k); - let (t1, tip) = ((o.0, 0.0), (TIP_X, 0.0)); - let triangle = 0.5 * ((tip.0 - t1.0) * (q2.1 - t1.1) - (q2.0 - t1.0) * (tip.1 - t1.1)).abs(); - triangle - 0.5 * R_WALL * R_WALL * (beta - beta.sin()) -} - #[test] fn fillet_the_knife_edge() { for (name, body) in [("plate first", part()), ("corner first", part_other_order()), ("cut from a box", part_cut_from_a_box())] { @@ -84,21 +71,6 @@ fn fillet_the_knife_edge() { } } -#[test] -fn chamfer_the_knife_edge() { - for (name, body) in [("plate first", part()), ("corner first", part_other_order()), ("cut from a box", part_cut_from_a_box())] { - let before = measure(&body).unwrap().volume; - for d in [0.5, 2.0, 5.0] { - let cut = chamfer(&body, &[knife()], d).unwrap_or_else(|e| panic!("{name} d={d}: {e}")); - assert!(cut.validity().is_empty(), "{name} d={d}: {:?}", cut.validity()); - assert_eq!(cut.face_count(), body.face_count() + 1, "{name} d={d}: one chamfer face"); - let v = measure(&cut).unwrap().volume; - let expected = before - HEIGHT * chamfered_area(d); - assert!((v - expected).abs() < 1e-3 * expected.abs(), "{name} d={d}: volume {v}, expected {expected}"); - } - } -} - /// A ball that does not fit between the faces, and sizes at the ends of the range, are refused /// or blended; they never panic or give an invalid solid. #[test] @@ -164,7 +136,7 @@ fn arc_top_removed(size: f64, round: bool) -> f64 { /// Volume through the display planner (the mesh the app draws): closed and exact where the /// legacy mesher behind `measure` can leak at a zero-angle corner like the one at the tip. pub(crate) fn planned_volume(b: &Body) -> f64 { - let mesh = b.display_plan(2e-4).unwrap().evaluate(); + let mesh = b.mesh_plan(&crate::MeshTolerance::chord(2e-4)).unwrap().evaluate(); let key = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]; let mut uses: std::collections::HashMap<([u64; 3], [u64; 3]), i32> = std::collections::HashMap::new(); for t in &mesh.triangles { @@ -231,33 +203,6 @@ fn arc_top_edge_sizes_never_panic() { } } -/// At the full wall height the fitted contact coincides with the bottom arc: retaining that -/// wall produces a zero-area face, not a successful blend (#1113). Just below the limit the -/// wall still has area and must remain supported. Face order and mirrored edge directions -/// do not change either outcome. -#[test] -fn arc_top_blend_refuses_a_collapsed_wall() { - for body in [part(), part_other_order(), part_cut_from_a_box()] { - for z in [1.0, -1.0] { - let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, z, 0.0], [0.0, 0.0, 0.0, 1.0]]; - let body = transform_matrix(&body, matrix).unwrap(); - let at = arc_top(); - let pick = [Vec3::new(at.x, at.y, at.z * z)]; - for round in [true, false] { - let blend = |r| if round { fillet(&body, &pick, r) } else { chamfer(&body, &pick, r) }; - let error = blend(HEIGHT).unwrap_err(); - assert!(matches!(error, KernelError::TooLarge(_)), "round={round}, mirror={z}: {error}"); - let made = blend(HEIGHT - 0.5).unwrap(); - assert!(made.validity().is_empty(), "round={round}, mirror={z}: {:?}", made.validity()); - let before = planned_volume(&body); - let removed = before - planned_volume(&made); - let expected = arc_top_removed(HEIGHT - 0.5, round); - assert!((removed - expected).abs() < 0.01 * expected + 0.01, "round={round}, mirror={z}: removed {removed}, expected {expected}"); - } - } - } -} - fn tf() -> Vec3 { Vec3::new(20.0, -R_WALL, HEIGHT) } @@ -406,22 +351,6 @@ fn unfilleted_knife_edge_input_has_a_closed_display_plan() { } } -/// The construction does not depend on the faces being curved: at a box's corner it gives the -/// body the planar corner builder does (a sphere's octant where the three rounds meet). -#[test] -fn the_sphere_at_a_box_corner_is_the_planar_corner_builders() { - let b = box_solid(Vec3::ZERO, Vec3::new(30.0, 20.0, 10.0)).unwrap(); - let picks = [Vec3::new(15.0, 0.0, 10.0), Vec3::new(0.0, 10.0, 10.0), Vec3::new(0.0, 0.0, 5.0)]; - for r in [1.0, 2.5] { - let local = crate::blend_corner::fillet_radii(&b, &picks.iter().map(|p| (*p, r)).collect::>()).unwrap(); - let ball = crate::blend_vertex::fillet_ball_vertices(&b, &picks, r).unwrap_or_else(|e| panic!("r={r}: {e}")); - assert!(ball.validity().is_empty(), "r={r}: {:?}", ball.validity()); - assert_eq!(ball.face_count(), local.face_count(), "r={r}"); - let (a, c) = (planned_volume(&local), planned_volume(&ball)); - assert!((a - c).abs() < 1e-3 * a, "r={r}: planar corner {a}, ball corner {c}"); - } -} - /// Sizes at the ends of the range at a ball vertex: rounded or refused, never a panic. #[test] fn rounds_ending_in_a_sphere_of_any_size_never_panic() { @@ -432,3 +361,26 @@ fn rounds_ending_in_a_sphere_of_any_size_never_panic() { } } } + +/// The front's top edge rounded r 2, then the edge between that round and the arc wall (the +/// middle of the arc top edge's tangent chain) at the round's own radius: the ball sits on the +/// round's axis, fixed, and the plane square to the edge at its top end misses that centre, so +/// no round ends there. solidcore refuses it as a collapsed offset (`NoRoomReason:: +/// OffsetCollapses`, solidcore#2431), naming 2 less its fit margin; the refusal says why. +#[test] +fn a_ball_as_wide_as_the_round_it_rolls_on_is_refused_saying_why() { + let rounded = fillet(&part(), &[tf()], 2.0).unwrap(); + let middle = Vec3::new(41.17486688363082, -20.41321806796856, 9.415188112149071); + let why = match fillet(&rounded, &[middle], 2.0) { + Err(KernelError::TooLarge(why)) => why, + other => panic!("{:?}", other.map(|b| b.face_count())), + }; + assert!(why.contains("the ball is as wide as a face it rolls on, so its centre stays put and the round cannot end at the edge's end"), "{why}"); + // 2 less solidcore's fit margin. + let largest: f64 = why + .split_once("the largest radius that fits is ") + .and_then(|(_, n)| n.split_once(" mm")) + .and_then(|(n, _)| n.parse().ok()) + .unwrap_or_else(|| panic!("{why}")); + assert!(largest < 2.0 && largest > 1.9, "{why}"); +} diff --git a/crates/kernel/src/issue_871_tests.rs b/crates/kernel/src/issue_871_tests.rs index a9430c332..ba65f4bd9 100644 --- a/crates/kernel/src/issue_871_tests.rs +++ b/crates/kernel/src/issue_871_tests.rs @@ -1,6 +1,6 @@ //! #871: a fillet that opened holes in the model must be refused, not accepted. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::{Body, BoolOp, build::box_solid, ops::boolean}; @@ -49,12 +49,28 @@ fn overlapping_rounds_are_refused() { } } -/// Below half the wall the rounds fit: a closed solid with a round on every edge. +/// Below half the wall the rounds fit: a closed solid with a round on every edge. Each end face's +/// round section at depth u into the round is the end face's outline moved in by +/// d = r − √(r² − (r − u)²), each edge parallel to itself and every corner mitred (two rounds +/// meeting at a corner beside an unpicked sharp edge, convex or concave: the owner's ruling of +/// 2026-10-30): the area less L d (L the outline's and the window's length together, +/// 2 · 41.5 + 2 · 12.3 = 107.6), plus d² at each of the six convex corners (the two strips +/// overlap) and less d² at each of the six concave ones (the two shoulders and the window's four +/// corners: the mitre takes the d × d square beyond both strips). The corner terms cancel, so +/// both ends remove 2 L ∫ d = 2 L r² (1 − π/4). #[test] fn rounds_that_fit_are_closed() { + use std::f64::consts::FRAC_PI_4; let p = part(); - let b = crate::fillet(&p, &edges(), 0.5).unwrap(); + let r = 0.5; + let b = crate::fillet(&p, &edges(), r).unwrap(); assert!(b.validity().is_empty(), "{:?}", b.validity()); assert_eq!(b.crossed_face_loops().unwrap(), 0); - assert_eq!(b.face_count(), p.face_count() + edges().len()); + let (a, top) = (12.74437365538526, 22.69275963366936); + let part_volume = 14.0 * (21.5 * 10.0 + (top - a) * 10.0 - 5.2 * 7.1); + assert!((crate::measure(&p).unwrap().volume - part_volume).abs() < 1e-9 * part_volume); + let length = 2.0 * (21.5 + 20.0) + 2.0 * (5.2 + 7.1); + let removed = 2.0 * length * r * r * (1.0 - FRAC_PI_4); + let v = crate::measure(&b).unwrap().volume; + assert!((v - (part_volume - removed)).abs() < 1e-7 * part_volume, "{v} vs {}", part_volume - removed); } diff --git a/crates/kernel/src/join_between_caps_tests.rs b/crates/kernel/src/join_between_caps_tests.rs index a5c171fc6..810441ff8 100644 --- a/crates/kernel/src/join_between_caps_tests.rs +++ b/crates/kernel/src/join_between_caps_tests.rs @@ -7,9 +7,8 @@ use std::f64::consts::PI; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; -use crate::body::from_p3; use crate::*; /// A 40 × 20 × 6 plate (z 5 … 11) with a 14 × 10 × 6 leaf under its back edge, 1 mm into it: @@ -23,7 +22,7 @@ fn plate_with_leaf() -> Body { /// Barrels along x with their axis on the leaf's back bottom edge (y 20, z 0): radius 5 (its top /// meets the plate's back edge) and 4.9, ends flush with both of the leaf's sides, with one, and /// running on past both under the plate. A quarter of the barrel lies in the leaf (where the -/// leaf is). Each join is exact: no retry, one solid, and every vertex on a level along x of the +/// leaf is). Each join is exact: one solid, and every vertex on a level along x of the /// plate, the leaf or the barrel. #[test] fn a_barrel_between_the_sides_of_a_leaf_joins_exactly() { @@ -31,16 +30,14 @@ fn a_barrel_between_the_sides_of_a_leaf_joins_exactly() { for (r, x0, x1) in [(5., 10., 24.), (4.9, 10., 24.), (5., 10., 23.), (5., 8.5, 25.5)] { let what = format!("radius {r}, x {x0} … {x1}"); let barrel = cylinder(Vec3::new(x0, 20., 0.), Vec3::X, r, x1 - x0).unwrap(); - let (joined, d) = capture_boolean_diagnostics(|| boolean(&part, &barrel, BoolOp::Union)); - let joined = joined.unwrap().unwrap(); - assert!(d.events.is_empty(), "{what}: {d:?}"); + let joined = boolean(&part, &barrel, BoolOp::Union).unwrap().unwrap(); assert_eq!(joined.shell_count(), 1, "{what}"); assert!(joined.validity().is_empty(), "{what}: {:?}", joined.validity()); let inside = (x1.min(24.) - x0.max(10.)) / 4.; let want = 5500. + PI * r * r * (x1 - x0 - inside); - let v = joined.tessellate(1e-4).unwrap().measure().volume; + let v = joined.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; assert!((v - want).abs() < want * 1e-5, "{what}: volume {v} vs {want}"); - for p in joined.solid.vertex_iter().map(|v| from_p3(v.point())) { + for p in joined.record().vertices.iter().map(|v| Vec3::from(v.point)) { assert!([0., 10., 24., 40., x0, x1].iter().any(|x| (p.x - x).abs() < 1e-9), "{what}: a vertex at {p:?}"); } } diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 25e8013bd..6ee0794b8 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -12,41 +12,37 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod assemble; mod blend; mod blend_corner; -mod blend_fit; +mod blend_smlib; mod blend_variable; -mod blend_vertex; #[cfg(test)] mod blend_wrong_way_tests; mod body; -mod boolean_diagnostics; -mod boolean_guard; mod boolean_record; -mod bore_guard; mod boundary; mod boundary_network; mod bridge; mod build; -mod candidate_reach; #[cfg(test)] mod chamfer_sides_curved_tests; -mod clearance; -mod coaxial_overlap; mod continuity; -mod coplanar; +mod continuity_order; +#[cfg(test)] +mod coplanar_tests; mod corner_g2; -mod curveblend; +mod curvature_comb; mod delete_face; mod distance; -#[cfg(test)] -mod edge_polyline_tests; +mod draft_corners; mod emboss; -mod face_params; #[cfg(test)] mod face_source_tests; mod fair; mod fill; +#[cfg(test)] +mod fillet_setback_tests; mod freeform; pub mod fuzz; mod heal; @@ -54,8 +50,10 @@ mod helix; pub mod history; mod iges_in; mod iges_out; +mod intersection; #[cfg(test)] mod intersection_curve_tests; +mod iso; #[cfg(test)] mod issue_1038_tests; #[cfg(test)] @@ -65,8 +63,6 @@ mod issue_1510_tests; #[cfg(test)] mod issue_2005_tests; #[cfg(test)] -mod issue_324_tests; -#[cfg(test)] mod issue_616_tests; #[cfg(test)] mod issue_674_tests; @@ -87,7 +83,6 @@ mod loft_rails; mod loft_rails_tests; #[cfg(test)] mod loft_region_tests; -mod loopblend; mod matchsurf; mod measure; mod mesh_convert; @@ -97,32 +92,37 @@ mod modify_history_tests; mod native; mod numbered; mod offset; +mod offset_backend; mod ops; -mod outline; #[cfg(test)] mod outline_tests; mod par; -pub use par::{for_each_on_threads, map_on_threads, map_with_local_pools}; +pub use par::{KERNEL_STACK, for_each_on_threads, kernel_thread, map_on_threads, map_with_local_pools}; #[cfg(test)] mod pinch_tests; -mod planar_faces; #[cfg(test)] mod planar_faces_tests; mod plane_fit; +mod point_path; mod polybool; mod polyhedron; mod prism; mod prism_curve; -mod prism_local; mod prism_measure; pub mod profile; pub mod provenance; mod record; -mod seam_faces; +mod repair; +#[cfg(test)] +mod seam_faces_tests; mod sew; +mod smlib_boolean; +mod smlib_sweeps; +#[cfg(test)] +mod smlib_sweeps_tests; mod smooth_edges; -mod sphere_lens; -mod spline_conv; +#[cfg(test)] +mod sphere_lens_tests; mod splitface; mod step; mod step_in; @@ -139,7 +139,7 @@ mod surfaces; mod sweep_path; #[cfg(test)] mod sweep_rails_tests; -mod tangent_cylinders; +mod tangent_edge; mod tess; #[cfg(test)] mod thin_face_tests; @@ -148,69 +148,85 @@ mod thread_display_tests; #[cfg(test)] mod thread_tests; mod topo; -mod touching_walls; mod tspline; #[cfg(test)] mod untouched_faces_tests; +mod validation; +mod validity; 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::{ + ChamferSide, FilletTurn, SETBACK_AT_LEAST, blend_edges, chamfer, chamfer_max, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, + fillet_g2_with_g2_corners, fillet_least_setback, fillet_max, fillet_max_each, fillet_removing, fillet_setback, largest_fit_note, + names_largest_fit, tangent_chain, with_fit_note, +}; pub use blend_corner::fillet_radii; pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper}; -pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, Paint}; -pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics}; +pub use body::{ + Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, MeshTolerance, Paint, PointClass, Refusal, + SurfaceKind, +}; pub use boundary::{Boundary, boundary_patch}; pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDGE_PICKS, boundary_join, boundary_surface}; -pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid}; +pub use bridge::{Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid}; pub use build::{ PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, extrude_whole_sides, loft, loft_regions, - loft_with_rails, path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus, + loft_with_rails, path_polyline, planar_face_record, revolve, revolve_whole, sphere, sweep, sweep_with, torus, }; -pub use clearance::{Clearance, Occupancy}; -pub use coaxial_overlap::{CoaxialOverlap, coaxial_candidate, coaxial_overlap}; pub use continuity::{ - ContinuityReport, ContinuityTolerances, EdgePick, MAX_SAMPLES, MIN_SAMPLES, SeamReport, SeamVerdict, SeamWorst, pick_edges, seam_diagnostics, + ContinuityReport, ContinuityTolerances, DEFAULT_SAMPLES, EdgePick, MAX_SAMPLES, MIN_SAMPLES, SeamReport, SeamStation, SeamVerdict, SeamWorst, + pick_edges, seam_diagnostics, }; -pub use corner_g2::{corner_g2_patch, seam_error}; +pub use continuity_order::{Construction, Continuity}; +pub use corner_g2::{CURVATURE_SHARE, DEFAULT_SETBACK_FACTOR}; +pub use curvature_comb::{CombTooth, MAX_COMB_TEETH, MIN_COMB_TEETH, comb_edge_near, edge_comb, iso_comb}; pub use delete_face::delete_faces; pub use distance::{BodyDistance, DistanceShape, body_distance}; +pub use draft_corners::{CornerFill, CornerOption, CornerRefusal, CornerReport, DraftCorner, draft_corners}; pub use emboss::{cylinder_emboss_anchor, emboss_cylinder, emboss_cylinder_at, has_cylinder_emboss_wall, infer_cylinder_emboss}; pub use fair::{ FairCurve, FairNet, FairOptions, FairReport, MAX_FAIR_ITERATIONS, MAX_FAIR_POINTS, fair_bspline_curve, fair_bspline_surface, fair_curve, fair_faces, fair_net, fair_nurbs_curve, fair_nurbs_surface, fair_surface, }; pub use fill::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, patch_edges_crowned, patch_edges_report, patch_edges_with}; -pub use helix::{loft_to_point, sweep_helix, sweep_helix_mesh}; +pub use helix::{loft_to_point, sweep_helix, sweep_helix_mesh, sweep_helix_radial}; pub use iges_in::{MAX_IGES_BYTES, iges_import, iges_to_step}; pub use iges_out::iges_export_bodies; +pub use intersection::{MeetingEdge, meeting_edges}; +pub use iso::{IsoLine, MAX_ISO_COUNT, iso_curves, iso_grid}; pub use lip::{raise_band, rim_band}; pub use loft_blend::loft_blend; pub use matchsurf::{match_surface, seam_continuity}; pub use measure::{BodyMeasure, MassMeasure, measure, measure_mass}; pub use mesh_convert::convert_prismatic_mesh; pub use meshbody::{MAX_TRIANGLES, mesh_body}; -pub use native::{decode_native_body, encode_native_body, native_preview_mesh}; +pub use native::{body_from_smlib, smlib_body}; +pub use native::{brep_record, decode_native_body, encode_native_body, native_preview_mesh}; pub use offset::with_same_surface; -pub use ops::{ - BoolOp, boolean, can_join_all_touching_faces, can_join_touching_faces, compound_disjoint_extrusions, half_space, is_planar, join_apart, - place_matrix, split_by_plane, transform, transform_matrix, union_apart, with_attempt_budget, +pub use ops::{BoolOp, apart, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_all, union_apart}; +pub use point_path::{ + PathPiece, PointPath, SpaceBezier, along_path, curve_path, edge_path, face_section_along, project_onto_face, sketch_record_curve, + sweep_point_path_with, }; -pub use polybool::{faceted_boolean, planar_boolean}; +pub use polybool::faceted_boolean; pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell}; pub use prism::{PLANAR_FIT_TOL, extrude_planar_regions, planar_regions_boolean}; -pub use prism_measure::certified_prism_equivalent; +pub use prism_curve::{PlanarPiece, PlanarSpline}; +pub use prism_measure::{PrismSection, certified_prism_equivalent, certified_prism_section}; +pub use repair::{Hole, RebuiltFace, RefusedFace, RepairOptions, RepairReport, SewnGap, repair}; pub use sew::{EdgeSpec, FaceSpec, SurfSpec, sew, sew_touching}; +pub use solidcraft_smlib::trace as smlib_trace; pub use splitface::{SplitTool, split_body, split_faces, split_faces_with_map}; pub use step::step_export; pub use step_in::{ - ImportedBody, StepImport, StepNode, StepReading, step_cache_alive, step_import, step_import_shared, step_orientation_errors, step_validate, + ImportIssue, ImportReport, ImportedBody, IssueKind, StepImport, StepNode, StepReading, step_cache_alive, step_import, step_import_shared, + step_orientation_errors, step_validate, }; pub use step_out::{ExportBody, ExportProduct, StepHeader, step_export_bodies, step_export_products}; pub use surface_extend::{ExtendLimit, ExtendMode, ExtendOptions, extend_surface}; pub use surface_kind::{EdgeCircle, FaceSurface, edge_circle, face_surface}; pub use surface_offset::offset_surface; -pub use surface_ruled::{Ruled, RuledCorners, RuledMode, ruled_surface}; +pub use surface_ruled::{Ruled, RuledCorners, RuledMode, ruled_far_handles, ruled_surface, ruled_surface_with}; pub use surface_trim::{TrimKeep, mutual_trim, trim, trim_keep}; pub use surface_untrim::{UntrimHoles, untrim}; pub use surfaces::{ @@ -218,10 +234,11 @@ pub use surfaces::{ stitch, sweep_sheet, sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, unstitch, }; pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_path_with}; -pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at}; +pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at, material_in_ring}; 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}; +pub use validation::{Validation, check_kept, validating}; +pub use validity::{SmlibCheck, Validity, smlib_dump_dir, validity}; #[derive(Debug, Clone, PartialEq, thiserror::Error)] pub enum KernelError { @@ -240,6 +257,53 @@ pub enum KernelError { pub type Result = std::result::Result; +/// Why a kernel step failed: a message, or an error of the solidcore wrapper, which may be a +/// panic the wrapper caught ([`solidcraft_smlib::Error::Internal`]). +pub(crate) trait Cause: std::fmt::Display { + /// The panic's message, when the cause is one. + fn panic(&self) -> Option<&str> { + None + } +} + +impl Cause for solidcraft_smlib::Error { + fn panic(&self) -> Option<&str> { + match self { + solidcraft_smlib::Error::Internal(m) => Some(m), + _ => None, + } + } +} + +impl Cause for str {} +impl Cause for String {} +impl Cause for solidcraft_smlib::CheckReport {} +impl Cause for solidcraft_smlib::export::ExportError {} +impl Cause for solidcore_record::brep::history::Failed {} +impl Cause for solidcraft_geom::brep::pcurve::Error {} +impl Cause for &T { + fn panic(&self) -> Option<&str> { + (**self).panic() + } +} + +impl KernelError { + /// A kernel step's failure, `context` before its cause: a panic the solidcore wrapper caught + /// (its kernel replaced by a fresh one) stays an internal error ([`KernelError::Internal`]), + /// so the engine reports it as one; any other cause is the operation's failure. + pub(crate) fn smlib(context: impl std::fmt::Display, e: impl Cause) -> KernelError { + match e.panic() { + Some(m) => KernelError::Internal(format!("{context}: {m}")), + None => KernelError::Failed(format!("{context}: {e}")), + } + } +} + +/// The native kernel call running right now (SMLib), for crash reports. +pub fn native_call_in_flight() -> Option { + solidcraft_smlib::current_call() +} + thread_local! { static GUARDED: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -247,7 +311,13 @@ thread_local! { /// Is this thread inside [`guard`]? (A panic now will be caught and turned into an error; the /// engine's crash reports mark it recovered.) pub fn guarded() -> bool { - GUARDED.with(std::cell::Cell::get) > 0 + GUARDED.with(std::cell::Cell::get) > 0 || solidcraft_smlib::in_call() +} + +/// A panic inside a solidcore call, caught there and reported as the kernel's internal error +/// ([`KernelError::Internal`]): the crash-report check (`diagnostics.crash_test`'s kernel mode). +pub fn crash_test() -> Result<()> { + solidcraft_smlib::crash_test().map_err(|e| KernelError::smlib("crash test", e)) } /// Run third-party kernel code, converting a panic into an error. diff --git a/crates/kernel/src/lip.rs b/crates/kernel/src/lip.rs index 7faed0fb3..80feb2045 100644 --- a/crates/kernel/src/lip.rs +++ b/crates/kernel/src/lip.rs @@ -1,32 +1,66 @@ //! Raising a band of a planar face (a plastic part's lip): the band along one of the face's //! boundary loops, a set width into the face, is pushed out along the face's normal. Built -//! directly from the body's faces (the band's walls continue the walls below, which a boolean -//! union can't join: their faces would coincide). +//! directly on the body's schema 4 record (the band's walls continue the walls below, which a +//! boolean union can't join: their faces would coincide). -use solidcraft_geom::{Loop2, Plane, Region2, Ring, Seg2, Vec3}; -use truck_modeling::{self as mt, builder}; +use solidcore_record::brep::{Brep, Curve, Frame, Surface}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec3}; +use solidcraft_geom::Ring; +use solidcraft_geom::prelude::*; -use crate::body::{Body, Solid, from_p3, p3, v3}; +use crate::assemble::{AFace, AUse, Assembly}; +use crate::body::Body; use crate::history::{Change, FaceOrigin, FaceProv}; -use crate::record::Operand; +use crate::offset::{Surf, surf_of}; use crate::{KernelError, Result, guard}; fn fail(m: &str) -> KernelError { KernelError::Failed(format!("raising a band: {m}")) } -/// A boundary edge of the face, as its ends and (for an arc) a point halfway. +fn arr(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +/// A boundary edge of the face, as its ends and, for an arc, its circle: the centre and the +/// angle it turns through about the face's normal from `a` to `b` (positive counter-clockwise; +/// ±2π for a whole circle, whose ends are one point). #[derive(Clone, Copy)] struct Piece { a: Vec3, b: Vec3, - mid: Option, + arc: Option, +} + +#[derive(Clone, Copy)] +struct Arc { + centre: Vec3, + sweep: f64, +} + +impl Piece { + /// The point a fraction `f` of the way along the piece (an arc turning about `n`). + fn at(&self, n: Vec3, f: f64) -> Vec3 { + match self.arc { + None => self.a + (self.b - self.a) * f, + Some(Arc { centre, sweep }) => { + let x = self.a - centre; + let (s, c) = (f * sweep).sin_cos(); + centre + x * c + n.cross(x) * s + } + } + } + + /// The piece moved by `d`. + fn moved(&self, d: Vec3) -> Piece { + Piece { a: self.a + d, b: self.b + d, arc: self.arc.map(|x| Arc { centre: x.centre + d, ..x }) } + } } /// The planar face of `body` at `at`: its index and outward normal. -fn face_at(body: &Body, at: Vec3) -> Result<(usize, Vec3)> { +fn face_at(body: &Body, rec: &Brep, at: Vec3) -> Result<(usize, Vec3)> { let size = body.size(); - let mesh = body.tessellate((size * 1e-3).max(1e-3))?; + let mesh = body.mesh(&crate::MeshTolerance::chord((size * 1e-3).max(1e-3)))?; let near = mesh .triangles .iter() @@ -43,12 +77,10 @@ fn face_at(body: &Body, at: Vec3) -> Result<(usize, Vec3)> { if d > size * 1e-3 { return Err(fail("no face there")); } - guard("rim face", || { - let face = body.solid.face_iter().nth(f).ok_or_else(|| fail("face"))?; - let mt::Surface::Plane(pl) = face.oriented_surface() else { return Err(fail("the face must be planar")) }; - let n = pl.normal(); - Ok((f, Vec3::new(n.x, n.y, n.z).normalized().ok_or_else(|| fail("normal"))?)) - }) + match surf_of(rec, f) { + Some(Surf::Plane { n, .. }) => Ok((f, n)), + _ => Err(fail("the face must be planar")), + } } /// The face's loop moved `w` into the face (to the left of its edges, as a face's boundary has @@ -57,25 +89,21 @@ fn offset_loop(pieces: &[Piece], n: Vec3, w: f64, tol: f64) -> Result let left = |a: Vec3, b: Vec3| n.cross(b - a).normalized(); let mut out: Vec = Vec::new(); for p in pieces { - out.push(match p.mid { + out.push(match p.arc { None => { let l = left(p.a, p.b).ok_or_else(|| fail("zero edge"))?; - Piece { a: p.a + l * w, b: p.b + l * w, mid: None } + p.moved(l * w) } - Some(m) => { - // Each point moves square to the arc (along its radius), to the left. - let lm = left(p.a, p.b).ok_or_else(|| fail("arc"))?; - let c = circle_centre(p.a, m, p.b).ok_or_else(|| fail("arc"))?; - let r = m.dist(c); - let shift = if (m - c).dot(lm) >= 0.0 { w } else { -w }; + Some(arc) => { + // Each point moves along its radius, to the left: towards the centre of an arc + // turning counter-clockwise, away from that of one turning clockwise. + let r = p.a.dist(arc.centre); + let shift = if arc.sweep > 0.0 { -w } else { w }; if r + shift <= tol { return Err(fail("the offset closes an arc")); } - // Use one radial scale for the whole arc. At a semicircle's ends the - // radial is perpendicular to the chord's left, so its dot product cannot - // reliably choose the side independently at each end. - let moved = |q: Vec3| c + (q - c) * ((r + shift) / r); - Piece { a: moved(p.a), b: moved(p.b), mid: Some(moved(m)) } + let moved = |q: Vec3| arc.centre + (q - arc.centre) * ((r + shift) / r); + Piece { a: moved(p.a), b: moved(p.b), arc: Some(arc) } } }); } @@ -91,7 +119,7 @@ fn offset_loop(pieces: &[Piece], n: Vec3, w: f64, tol: f64) -> Result } continue; } - match (pi.mid, pj.mid) { + match (pi.arc, pj.arc) { (None, None) => { let (d1, d2) = (pi.b - pi.a, pj.b - pj.a); let w0 = pj.a - pi.a; @@ -115,64 +143,61 @@ fn offset_loop(pieces: &[Piece], n: Vec3, w: f64, tol: f64) -> Result Ok(out) } -fn circle_centre(a: Vec3, m: Vec3, b: Vec3) -> Option { - let (u, v) = (b - a, m - a); - let w = u.cross(v); - let d = 2.0 * w.len2(); - if d < 1e-300 { - return None; - } - Some(a + (v.cross(w) * u.len2() + w.cross(u) * v.len2()) * (1.0 / d)) -} - -fn pieces(wire: &mt::Wire, size: f64) -> Result> { - wire.edge_iter() - .map(|e| { - let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point())); - match crate::offset::arc_mid(e, size * 1e-6) { - Some(mid) => Ok(Piece { a, b, mid }), - None => Err(fail("edges must be lines or arcs")), +/// The pieces of a loop (seen from outside the body, whose normal is `n`), from its record edges: +/// lines, and arcs with their circle. +fn pieces(asm: &Assembly, lp: &[AUse], n: Vec3) -> Result> { + lp.iter() + .map(|u| { + let e = asm.edges.get(u.edge as usize).ok_or_else(|| fail("edge"))?; + let (s, t) = asm.ends(u).ok_or_else(|| fail("edge"))?; + let (a, b) = (asm.point(s).ok_or_else(|| fail("vertex"))?, asm.point(t).ok_or_else(|| fail("vertex"))?); + // The arc's angles, on the circle itself (its NURBS form, if any, is parameterised otherwise). + let [t0, t1] = solidcraft_geom::brep::label::curve_interval(&e.curve, e.nurbs.as_ref(), e.interval).ok_or_else(|| fail("edge"))?; + match &e.curve { + Curve::Line { .. } => Ok(Piece { a, b, arc: None }), + Curve::Circle { frame, .. } => { + // The parameter is the angle about the frame's z, which lies along ±n. + let z = Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis)); + if z.cross(n).len() > 1e-9 { + return Err(fail("an arc not in the face's plane")); + } + let along = if u.forward { 1.0 } else { -1.0 }; + let sweep = (t1 - t0) * along * z.dot(n).signum(); + Ok(Piece { a, b, arc: Some(Arc { centre: Vec3::from(frame.origin), sweep }) }) + } + _ => Err(fail("edges must be lines or arcs")), } }) .collect() } -/// Signed area ordering including arc midpoints: two semicircles have only two -/// vertices, whose polygon has zero area for both the inner and outer loops. -fn turn(wire: &mt::Wire, n: Vec3) -> f64 { - use mt::{BoundedCurve, ParametricCurve}; - let ring: Ring = wire - .edge_iter() - .flat_map(|e| { - let c = e.oriented_curve(); - let (a, b) = c.range_tuple(); - [from_p3(e.front().point()), from_p3(c.subs((a + b) * 0.5))] - }) - .collect(); +/// Signed area ordering, through points along the arcs: a whole circle has one vertex, two +/// semicircles two, whose polygon has no area. +fn turn(pieces: &[Piece], n: Vec3) -> f64 { + let ring: Ring = + pieces.iter().flat_map(|p| if p.arc.is_some() { vec![p.a, p.at(n, 1.0 / 3.0), p.at(n, 2.0 / 3.0)] } else { vec![p.a] }).collect(); ring.area_vector().dot(n) } -fn rim_loops(wires: &[mt::Wire], n: Vec3) -> Result<(&mt::Wire, &mt::Wire)> { - let [a, b] = wires else { return Err(fail("the face must have an outer and one inner loop (a rim)")) }; - Ok(if turn(a, n) >= turn(b, n) { (a, b) } else { (b, a) }) +/// The face's two loops, outer then inner (a rim), as uses seen from outside. +fn rim_loops(asm: &Assembly, fi: usize, n: Vec3) -> Result<(Vec, Vec)> { + let f = asm.faces.get(fi).and_then(Option::as_ref).ok_or_else(|| fail("face"))?; + let [a, b] = f.loops.as_slice() else { return Err(fail("the face must have an outer and one inner loop (a rim)")) }; + let (ta, tb) = (turn(&pieces(asm, a, n)?, n), turn(&pieces(asm, b, n)?, n)); + Ok(if ta >= tb { (a.clone(), b.clone()) } else { (b.clone(), a.clone()) }) } fn profile(pieces: &[Piece], plane: &Plane) -> Result { - use std::f64::consts::TAU; let segs = pieces .iter() .map(|p| { let (a, b) = (plane.to_local(p.a), plane.to_local(p.b)); - Ok(match p.mid { + Ok(match p.arc { None => Seg2::Line { a, b }, - Some(m) => { - let center = plane.to_local(circle_centre(p.a, m, p.b).ok_or_else(|| fail("arc"))?); - let mid = plane.to_local(m); - let start = (a - center).angle(); - let end = (b - center).angle(); - let sweep = (end - start).rem_euclid(TAU); - let sweep = if ((mid - center).angle() - start).rem_euclid(TAU) <= sweep { sweep } else { sweep - TAU }; - Seg2::Arc { center, radius: a.dist(center), start, sweep } + // The plane's normal is the face's: the arc turns the same way in it. + Some(arc) => { + let center = plane.to_local(arc.centre); + Seg2::Arc { center, radius: a.dist(center), start: (a - center).angle(), sweep: arc.sweep } } }) }) @@ -188,13 +213,13 @@ pub fn rim_band(body: &Body, at: Vec3, width: f64, free: f64, outside: bool) -> if !(width.is_finite() && width > 0.0 && free.is_finite() && free >= 0.0) { return Err(KernelError::Invalid("invalid rim band width".into())); } - let (fi, n) = face_at(body, at)?; + let rec = crate::native::brep_record(body)?; + let (fi, n) = face_at(body, &rec, at)?; guard("rim band", || { - let face = body.solid.face_iter().nth(fi).ok_or_else(|| fail("face"))?; - let wires = face.boundaries(); - let (outer, inner) = rim_loops(&wires, n)?; + let asm = Assembly::from_record(&rec)?; + let (outer, inner) = rim_loops(&asm, fi, n)?; let along = if outside { outer } else { inner }; - let p = pieces(along, body.size())?; + let p = pieces(&asm, &along, n)?; let tol = (body.size() * 1e-5).max(1e-7); let plane = Plane::from_normal(at, n).ok_or_else(|| fail("rim plane"))?; let into = profile(&offset_loop(&p, n, width, tol)?, &plane)?; @@ -204,6 +229,52 @@ pub fn rim_band(body: &Body, at: Vec3, width: f64, free: f64, outside: bool) -> }) } +/// An edge from vertex `a` to vertex `b` along `p` (a line, or an arc of its circle about `n`): +/// the use that runs from `a` to `b`. +fn piece_edge(asm: &mut Assembly, a: u32, b: u32, p: &Piece, n: Vec3) -> Result { + let Some(arc) = p.arc else { return Ok(AUse { edge: asm.line(a, b)?, forward: true, given: None }) }; + let r = arc.centre.dist(p.a); + let x = (p.a - arc.centre).normalized().ok_or_else(|| fail("arc"))?; + let frame = Frame { origin: arr(arc.centre), x_axis: arr(x), y_axis: arr(n.cross(x)) }; + // Counter-clockwise about n from a (angle 0) to b, or clockwise: then from b to a. + let tau = std::f64::consts::TAU; + let (interval, ends, forward) = if arc.sweep > 0.0 { ([0.0, arc.sweep], (a, b), true) } else { ([tau + arc.sweep, tau], (b, a), false) }; + Ok(AUse { edge: asm.edge(Curve::Circle { frame, radius: r }, interval, ends.0, ends.1)?, forward, given: None }) +} + +/// The wall raised along `p` (from `bottom` to `top`, joined by `up_a` and `up_b` from its +/// ends), its outside on the right of `p` seen from `n` (`right`) or on its left. +fn wall(p: &Piece, n: Vec3, bottom: &AUse, top: &AUse, up_a: u32, up_b: u32, right: bool, shell: usize) -> Result { + let mut lp = vec![ + bottom.clone(), + AUse { edge: up_b, forward: true, given: None }, + AUse { edge: top.edge, forward: !top.forward, given: None }, + AUse { edge: up_a, forward: false, given: None }, + ]; + let (surface, natural_out) = match p.arc { + None => { + let d = (p.b - p.a).normalized().ok_or_else(|| fail("zero edge"))?; + // Natural normal d × n: the right of the piece. + (Surface::Plane { origin: arr(p.a), u_axis: arr(d), v_axis: arr(n) }, right) + } + Some(arc) => { + let x = (p.a - arc.centre).normalized().ok_or_else(|| fail("arc"))?; + let surface = + Surface::Cylinder { frame: Frame { origin: arr(arc.centre), x_axis: arr(x), y_axis: arr(n.cross(x)) }, radius: arc.centre.dist(p.a) }; + // Right of an arc turning counter-clockwise about n is away from its axis. + (surface, (arc.sweep > 0.0) == right) + } + }; + // The loop runs up the piece's right: the outside there. On its left it runs the other way. + if !right { + lp.reverse(); + for u in &mut lp { + u.forward = !u.forward; + } + } + Ok(AFace { surface, nurbs: None, natural_out, loops: vec![lp], shell, domain: None }) +} + /// Raise the band of the planar face at `at` that runs `width` wide along its outer loop /// (`outside`) or its inner loop, by `height` along the face's normal. pub fn raise_band(body: &Body, at: Vec3, width: f64, height: f64, outside: bool) -> Result { @@ -211,96 +282,107 @@ pub fn raise_band(body: &Body, at: Vec3, width: f64, height: f64, outside: bool) if !(width > 1e-6 && height > 1e-6 && width.is_finite() && height.is_finite()) { return Err(KernelError::Invalid("the band's width and height must be positive".into())); } - if body.solid.boundaries().len() != 1 { + let rec = crate::native::brep_record(body)?; + if rec.shells.len() != 1 { return Err(fail("a body in one piece")); } let size = body.size(); let tol = (size * 1e-7).max(1e-9) * 100.0; - let (fi, n) = face_at(body, at)?; + let (fi, n) = face_at(body, &rec, at)?; guard("lip", || { - let faces: Vec = body.solid.face_iter().cloned().collect(); - let f = faces.get(fi).ok_or_else(|| fail("face"))?; - let wires = f.boundaries(); - let (outer, inner) = rim_loops(&wires, n)?; + let mut asm = Assembly::from_record(&rec)?; + let (outer, inner) = rim_loops(&asm, fi, n)?; let (along, other) = if outside { (outer, inner) } else { (inner, outer) }; - let pieces = pieces(along, size)?; - let moved = offset_loop(&pieces, n, width, tol)?; - // The band's other edge, on the face. - let verts: Vec = moved.iter().map(|p| builder::vertex(p3(p.a))).collect(); - let k = verts.len(); - let mut cedges: Vec = Vec::with_capacity(k); - for (i, p) in moved.iter().enumerate() { - let (Some(a), Some(b)) = (verts.get(i), verts.get((i + 1) % k)) else { return Err(fail("vertex")) }; - cedges.push(match p.mid { - None => builder::line(a, b), - Some(m) => builder::circle_arc(a, b, p3(m)), - }); + let face = asm.faces.get_mut(fi).and_then(Option::take).ok_or_else(|| fail("face"))?; + let below = pieces(&asm, &along, n)?; + let moved = offset_loop(&below, n, width, tol)?; + let k = moved.len(); + let up = n * height; + // The band's other edge, on the face, and the band's top edges above both. + let cverts: Vec = moved.iter().map(|p| asm.vertex(p.a)).collect::>()?; + let averts: Vec = along.iter().map(|u| asm.ends(u).map(|e| e.0).ok_or_else(|| fail("edge"))).collect::>()?; + let atop: Vec = below.iter().map(|p| asm.vertex(p.a + up)).collect::>()?; + let ctop: Vec = moved.iter().map(|p| asm.vertex(p.a + up)).collect::>()?; + let lift = |p: &Piece| p.moved(up); + let (mut cedges, mut aup, mut cup, mut atops, mut ctops) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for i in 0..k { + let j = (i + 1) % k; + let (Some(&ca), Some(&cb), Some(&ta), Some(&tb), Some(&da), Some(&db), Some(&va)) = + (cverts.get(i), cverts.get(j), atop.get(i), atop.get(j), ctop.get(i), ctop.get(j), averts.get(i)) + else { + return Err(fail("vertex")); + }; + let (Some(pb), Some(pc)) = (below.get(i), moved.get(i)) else { return Err(fail("piece")) }; + cedges.push(piece_edge(&mut asm, ca, cb, pc, n)?); + atops.push(piece_edge(&mut asm, ta, tb, &lift(pb), n)?); + ctops.push(piece_edge(&mut asm, da, db, &lift(pc), n)?); + aup.push(asm.line(va, ta)?); + cup.push(asm.line(ca, da)?); } - // The loop's edges and the band's edge beside each, by the loop edge's index in the body. - let operand = Operand::new(body); - let mut wall_edge: std::collections::HashMap = std::collections::HashMap::new(); - for (e, ce) in along.edge_iter().zip(&cedges) { - if let Some(i) = operand.edges.get(&e.id()) { - wall_edge.insert(e.id(), *i); - wall_edge.insert(ce.id(), *i); - } - } - let c: mt::Wire = cedges.into(); // The rest of the face: its other loop, and the band's edge as a loop of its own. // (The band's edge runs the face's way round: a hole when the band follows the inner // loop, the outer loop when it follows the outer.) - let rest = mt::Face::try_new(vec![other.clone(), c.clone()], f.oriented_surface()).map_err(|e| fail(&e.to_string()))?; - // Walls: the face's loop and the band's edge swept out; the band's top. - let up = v3(n * height); - let wall_along: mt::Shell = builder::tsweep(along, up); - let wall_c: mt::Shell = builder::tsweep(&c, up); - let top_of = |sh: &mt::Shell| -> Vec { - sh.extract_boundaries().into_iter().filter(|w| w.vertex_iter().all(|v| (from_p3(v.point()) - at).dot(n) > height * 0.5)).collect() + let rest_loops = if outside { vec![cedges.clone(), other] } else { vec![other, cedges.clone()] }; + let rest = AFace { + surface: face.surface.clone(), + nurbs: face.nurbs.clone(), + natural_out: face.natural_out, + loops: rest_loops, + shell: face.shell, + domain: face.domain, }; - let flipped = |sh: &mt::Shell, yes: bool| -> mt::Shell { - if yes { sh.face_iter().map(|x| x.inverse()).collect::>().into() } else { sh.clone() } - }; - // History (one operand, the body), face by face as gathered below: the other faces - // kept, the face trimmed to what the band leaves, each wall made along the loop - // edge it rises from (the band's inner wall along the edge it runs beside), and the - // band's top an offset of the face. (Flipping a face keeps its edges.) - let history: Option> = crate::record::kept_except(faces.len(), fi) - .map(Some) - .chain([Some(crate::record::from_face(0, fi, Change::Modified))]) - .chain(wall_along.face_iter().chain(wall_c.face_iter()).map(|w| { - let edge = w.absolute_boundaries().iter().flatten().find_map(|e| wall_edge.get(&e.id()))?; - Some(crate::record::generated(vec![FaceOrigin::Edge { operand: 0, edge: *edge }])) - })) - .chain([Some(crate::record::generated(vec![FaceOrigin::Offset { operand: 0, face: fi }]))]) - .collect(); - let mut last = String::new(); - for flip in 0..8u32 { - let (wa, wc) = (flipped(&wall_along, flip & 1 == 1), flipped(&wall_c, flip & 2 == 2)); - let mut tops = top_of(&wa); - tops.extend(top_of(&wc)); - if tops.len() != 2 { - return Err(fail("the band's top")); - } - // The top closes both walls: its loops run against theirs. - let tops: Vec = tops.iter().map(|w| w.inverse()).collect(); - let Ok(top) = builder::try_attach_plane(&tops) else { continue }; - let top = if flip & 4 == 4 { top.inverse() } else { top }; - let mut all: Vec = faces.iter().enumerate().filter(|(i, _)| *i != fi).map(|(_, x)| x.clone()).collect(); - all.push(rest.clone()); - all.extend(wa.face_iter().cloned()); - all.extend(wc.face_iter().cloned()); - all.push(top); - match Solid::try_new(vec![all.into()]) { - Ok(s) => { - let b = Body::new(s)?; - if b.validity().is_empty() { - return crate::record::attach(b, std::slice::from_ref(&operand), history.clone(), Default::default()); - } - last = b.validity().join("; "); - } - Err(e) => last = e.to_string(), + // Walls: along the face's loop (the band's outside continues the walls below, on the + // loop's right) and along the band's edge (its outside on that edge's left). + let mut walls = Vec::with_capacity(2 * k); + for (right, (pieces, (bottoms, (tops, ups)))) in [(true, (&below, (&along, (&atops, &aup)))), (false, (&moved, (&cedges, (&ctops, &cup))))] { + for i in 0..k { + let j = (i + 1) % k; + let (Some(p), Some(bottom), Some(top), Some(&ua), Some(&ub)) = (pieces.get(i), bottoms.get(i), tops.get(i), ups.get(i), ups.get(j)) + else { + return Err(fail("wall")); + }; + let bottom = AUse { edge: bottom.edge, forward: bottom.forward, given: None }; + walls.push(wall(p, n, &bottom, top, ua, ub, right, face.shell)?); } } - Err(fail(&last)) + // The band's top: above the face's loop as it runs, above the band's edge the other way. + let reversed = |l: &[AUse]| -> Vec { l.iter().rev().map(|u| AUse { edge: u.edge, forward: !u.forward, given: None }).collect() }; + let top_loops = if outside { vec![atops.clone(), reversed(&ctops)] } else { vec![reversed(&ctops), atops.clone()] }; + let origin = below.first().map(|p| p.a + up).ok_or_else(|| fail("piece"))?; + let u = n.any_perp(); + let top = AFace { + surface: Surface::Plane { origin: arr(origin), u_axis: arr(u), v_axis: arr(n.cross(u)) }, + nurbs: None, + natural_out: true, + loops: top_loops, + shell: face.shell, + domain: None, + }; + // History (one operand, the body), face by face as gathered below: the other faces + // kept, the face trimmed to what the band leaves, each wall made along the loop edge it + // rises from (the band's inner wall along the edge it runs beside), and the band's top + // an offset of the face. + let loop_edges: Vec> = along.iter().map(|u| asm.edges.get(u.edge as usize).and_then(|e| e.source)).collect(); + let mut history: Vec = crate::record::kept_except(rec.faces.len(), fi).collect(); + history.push(crate::record::from_face(0, fi, Change::Modified)); + for _ in 0..2 { + for e in &loop_edges { + let e = e.ok_or_else(|| fail("a loop edge the body doesn't have"))?; + history.push(crate::record::generated(vec![FaceOrigin::Edge { operand: 0, edge: e }])); + } + } + history.push(crate::record::generated(vec![FaceOrigin::Offset { operand: 0, face: fi }])); + asm.face(rest); + for w in walls { + asm.face(w); + } + asm.face(top); + let finished = asm.finish()?; + let b = crate::assemble::body_with_history(finished, &asm, body, history)?; + let problems = b.validity(); + if !problems.is_empty() { + return Err(fail(&problems.join("; "))); + } + Ok(b) }) } diff --git a/crates/kernel/src/loft_blend.rs b/crates/kernel/src/loft_blend.rs index 2364b200a..6e5c1bf19 100644 --- a/crates/kernel/src/loft_blend.rs +++ b/crates/kernel/src/loft_blend.rs @@ -40,15 +40,14 @@ //! to 3 fuller, down to −0.9 flatter), exactly as a bridge's crown does. It shapes the middle of //! each end span and leaves every joint's conditions alone. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::brep::eval::SurfaceEval; use solidcraft_geom::bspline::{CurveN, HPoint, MAX_SPLINE_DEGREE, NurbsSurface}; -use truck_modeling as mt; -use truck_modeling::{ParametricSurface3D, SearchNearestParameter}; +use solidcraft_geom::prelude::*; -use crate::body::{Body, from_p3, p3}; +use crate::body::Body; use crate::bridge::{Continuity, Frame}; -use crate::surfaces::surface_body; -use crate::{KernelError, Result, guard}; +use crate::{KernelError, Result}; /// Most cross-sections one blend may run through. pub const MAX_BLEND_SECTIONS: usize = 50; @@ -79,9 +78,12 @@ const ROWS_PER_SOLVE: usize = 16; /// [`MAX_BLEND_STATIONS`], a frame that is not finite or a `leave` with no direction, a crown /// outside its range, and two neighbouring sections that meet at a station (no room for a blend). pub fn loft_blend(sections: &[Vec], orders: [Continuity; 2], crown: [f64; 2], samples: usize) -> Result { + for g in orders { + g.built_by(crate::continuity_order::Construction::Bridge)?; + } let blend = Blend::new(sections, orders, crown, samples)?; let net = blend.net()?; - guard("loft blend surface", || crate::spline_conv::tensor_face(&net).map(|f| surface_body(vec![f]))) + crate::surfaces::tensor_sheet(&net) } /// The frames of one cross-section picked as an edge chain of a body, sampled at `stations` @@ -94,34 +96,36 @@ pub fn loft_blend(sections: &[Vec], orders: [Continuity; 2], crown: [f64; /// tangent plane (a direction normal to it has no tangent plane to leave in). The last section's /// `leave` runs back into the blend, towards the section before it. pub fn section_frames(body: &Body, edges: &[Vec3], leave: Vec3, stations: usize) -> Result> { - guard("loft blend section", || { - let chain = crate::bridge::chain(body, edges)?; - let leave = - leave.normalized().filter(|l| l.is_finite()).ok_or_else(|| KernelError::Invalid("the leave direction must be a finite vector".into()))?; - let first = chain.first().ok_or_else(|| KernelError::Failed("loft blend: no chain".into()))?; - let mid = (from_p3(first.front().point()) + from_p3(first.back().point())) * 0.5; - // The face the chain lies on that the blend leaves through: the one whose tangent plane - // holds as much of `leave` as possible. - let mut best: Option<(f64, mt::Face)> = None; - for face in body.solid.face_iter() { - if !chain.iter().all(|e| face.edge_iter().any(|f| f.id() == e.id())) { - continue; - } - let surf = face.surface(); - let Some((u, v)) = surf.search_nearest_parameter(p3(mid), None, 100) else { continue }; - let normal = surf.normal(u, v); - let n = Vec3::new(normal.x, normal.y, normal.z).normalized().unwrap_or(Vec3::ZERO); - let score = (leave - n * leave.dot(n)).len(); - if best.as_ref().is_none_or(|(b, _)| score > *b) { - best = Some((score, face.clone())); - } + let chain = crate::bridge::chain(body, edges)?; + let leave = + leave.normalized().filter(|l| l.is_finite()).ok_or_else(|| KernelError::Invalid("the leave direction must be a finite vector".into()))?; + let r = body.record(); + let &(first, _) = chain.first().ok_or_else(|| KernelError::Failed("loft blend: no chain".into()))?; + let ends = r.edges.get(first).map(|e| e.vertices).ok_or_else(|| KernelError::Failed("loft blend: an edge reference".into()))?; + let point = |v: u32| r.vertices.get(v as usize).map(|x| Vec3::new(x.point[0], x.point[1], x.point[2])); + let (Some(a), Some(b)) = (point(ends[0]), point(ends[1])) else { return Err(KernelError::Failed("loft blend: a vertex reference".into())) }; + let mid = (a + b) * 0.5; + // The face the chain lies on that the blend leaves through: the one whose tangent plane holds + // as much of `leave` as possible. + let bounds = |f: usize, e: usize| r.edges.get(e).is_some_and(|x| x.uses.iter().any(|u| u.face as usize == f)); + let mut best: Option<(f64, usize)> = None; + for (f, face) in r.faces.iter().enumerate() { + if !chain.iter().all(|(e, _)| bounds(f, *e)) { + continue; } - let (score, face) = best.ok_or_else(|| KernelError::Invalid("no face of the body holds the picked edges".into()))?; - if score < 0.2 { - return Err(KernelError::Invalid("the direction towards the next section lies in no face at the picked edges".into())); + let Ok(surf) = SurfaceEval::new(face.parameters()) else { continue }; + let Some((_, su, sv)) = surf.project(mid, None, f64::INFINITY).and_then(|uv| surf.derivs(uv[0], uv[1])) else { continue }; + let n = su.cross(sv).normalized().unwrap_or(Vec3::ZERO); + let score = (leave - n * leave.dot(n)).len(); + if best.is_none_or(|(b, _)| score > b) { + best = Some((score, f)); } - crate::bridge::frames(&face, &chain, leave, stations) - }) + } + let (score, face) = best.ok_or_else(|| KernelError::Invalid("no face of the body holds the picked edges".into()))?; + if score < 0.2 { + return Err(KernelError::Invalid("the direction towards the next section lies in no face at the picked edges".into())); + } + crate::bridge::frames(body, face, &chain, leave, stations) } /// What the face has to do at one section: where it is, and the run direction's first, second and diff --git a/crates/kernel/src/loft_blend_tests.rs b/crates/kernel/src/loft_blend_tests.rs index df60b675c..e2f933650 100644 --- a/crates/kernel/src/loft_blend_tests.rs +++ b/crates/kernel/src/loft_blend_tests.rs @@ -2,14 +2,12 @@ //! measured back off the face it built (a grid of points, five-point differences along the run). use super::*; -use crate::body::from_p3; use crate::bridge::{bridge, sample_grid}; -use truck_modeling as mt; -use truck_modeling::ParametricSurface; +use solidcraft_geom::brep::eval::SurfaceEval; /// The blend's surface: it is one face. -fn surface_of(body: &Body) -> mt::Surface { - body.solid.face_iter().next().unwrap().surface() +fn surface_of(body: &Body) -> SurfaceEval { + SurfaceEval::new(&body.record().faces[0].surface).unwrap() } /// Position and the run direction's first three derivatives at `(t, v)` of the face, read with the @@ -18,10 +16,9 @@ fn surface_of(body: &Body) -> mt::Surface { /// the parameter falling and turns the odd derivatives round, so every value is a derivative in /// the run direction `u`. fn run_derivs(body: &Body, t: f64, v: f64, backwards: bool, h: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let surf = face.surface(); + let surf = surface_of(body); let dir = if backwards { -1.0 } else { 1.0 }; - let q: Vec = (0..5).map(|k| from_p3(surf.subs(t + dir * k as f64 * h, v))).collect(); + let q: Vec = (0..5).map(|k| surf.point([t + dir * k as f64 * h, v]).unwrap()).collect(); let d1 = (q[0] * -25.0 + q[1] * 48.0 + q[2] * -36.0 + q[3] * 16.0 + q[4] * -3.0) * (dir / (12.0 * h)); let d2 = (q[0] * 35.0 + q[1] * -104.0 + q[2] * 114.0 + q[3] * -56.0 + q[4] * 11.0) * (1.0 / (12.0 * h * h)); let d3 = (q[0] * -5.0 + q[1] * 18.0 + q[2] * -24.0 + q[3] * 14.0 + q[4] * -3.0) * (dir / (2.0 * h * h * h)); @@ -354,8 +351,8 @@ fn a_two_section_blend_is_the_bridge() { // The blend runs with the sections, the bridge crosses from one boundary to the other: the // same face, its two parameters the other way round. for (run, station) in [(0.0, 0.0), (0.25, 0.3), (0.5, 0.7), (0.75, 0.1), (1.0, 1.0)] { - let x = from_p3(surface_of(&made).subs(run, station)); - let y = from_p3(surface_of(&other).subs(station, run)); + let x = surface_of(&made).point([run, station]).unwrap(); + let y = surface_of(&other).point([station, run]).unwrap(); assert!(x.dist(y) < 1e-9, "run {run} station {station}: {x:?} vs {y:?}"); } let grid = sample_grid(&other, 9, 7).unwrap(); @@ -378,7 +375,7 @@ fn crown_shapes_the_middle_without_moving_the_joints() { assert!(p.dist(sections[1][4].p) < 1e-9, "the crown left the joint where the sections put it"); joints.push((d1, d2)); // Halfway up the first span is where a fuller crown reaches further. - heights.push(from_p3(surface_of(&body).subs(0.25, 0.5)).z); + heights.push(surface_of(&body).point([0.25, 0.5]).unwrap().z); assert_runs_through(&body, §ions, n); } for (d1, d2) in &joints { diff --git a/crates/kernel/src/loft_rails.rs b/crates/kernel/src/loft_rails.rs index 72acd5e6e..b0ffbfb96 100644 --- a/crates/kernel/src/loft_rails.rs +++ b/crates/kernel/src/loft_rails.rs @@ -8,26 +8,90 @@ //! (stretches along that line), leaning to follow the second. At the sections the move is none, //! so the sections and the loft's caps stay exactly as drawn; the loft's smooth surfaces then run //! through the sections and the stations together. +//! +//! Sections are exact NURBS curves ([`Section`], from the sketch segments' record curves); a +//! station is the plain loft's control points moved by an affine map, so each is exact too. -use mt::{BoundedCurve, ParametricCurve}; -use solidcraft_geom::{Plane, Vec3}; -use truck_modeling as mt; +use solidcore_record::{Plane, Seg2, Vec3}; +use solidcraft_geom::bspline::CurveN; +use solidcraft_geom::prelude::*; -use crate::body::{from_p3, p3}; use crate::sweep_path::RailFit; use crate::{KernelError, Result}; -/// Most wires a railed loft is skinned through, sections and stations together. -const MAX_WIRES: usize = 33; +/// Most curves a railed loft is skinned through per column, sections and stations together. +pub(crate) const MAX_WIRES: usize = 33; /// Most stations between two sections. -const MAX_PER_SPAN: usize = 15; +pub(crate) const MAX_PER_SPAN: usize = 15; -type Curve = mt::BSplineCurve; +/// A loft section: its plane and its curves in order, each a NURBS curve with homogeneous control +/// points `[x w, y w, z w, w]`, and the profile segments each curve stands for. +#[derive(Clone, Debug)] +pub(crate) struct Section { + pub plane: Plane, + pub curves: Vec>, + pub numbers: Vec>, +} -/// Where a rail meets a section: the point of the section's wire it guides (as a wire parameter: -/// the edge's index plus how far along the edge), that point, how far it is from where the rail -/// crosses the section's plane (the nudge onto it), and how far along the rail that crossing is -/// (segment and fraction). +impl Section { + /// The sketch segments `segs` on `plane` as a section (their exact record curves), segment i + /// standing for the profile segments `numbers[i]`. + pub(crate) fn of(plane: &Plane, segs: &[Seg2], numbers: Vec>) -> Result

{ + let curves = segs.iter().map(|s| nurbs(&crate::freeform::segment(plane, s)?.0)).collect::>>()?; + Ok(Section { plane: *plane, curves, numbers }) + } +} + +/// A record line or (rational) B-spline as a homogeneous NURBS curve. +fn nurbs(c: &solidcore_record::brep::Curve) -> Result> { + use solidcore_record::brep::Curve; + let degree = |knots: &[f64], n: usize| knots.len().checked_sub(n + 1).ok_or_else(|| KernelError::Invalid("spline degree".into())); + Ok(match c { + Curve::Line { start, end } => { + CurveN { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], ctrl: vec![[start[0], start[1], start[2], 1.0], [end[0], end[1], end[2], 1.0]] } + } + Curve::Spline { knots, points } => { + CurveN { degree: degree(knots, points.len())?, knots: knots.clone(), ctrl: points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() } + } + Curve::RationalSpline { knots, homogeneous } => { + CurveN { degree: degree(knots, homogeneous.len())?, knots: knots.clone(), ctrl: homogeneous.clone() } + } + _ => return Err(KernelError::Invalid("a loft section curve that is not a line or a spline".into())), + }) +} + +/// A curve's control points (x, y, z) and weights. +fn points(c: &CurveN<4>) -> (Vec, Vec) { + c.ctrl.iter().map(|h| (Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]), h[3])).unzip() +} + +/// `c` with the control points `pts` (its own weights and knots). +fn with(c: &CurveN<4>, pts: &[Vec3]) -> CurveN<4> { + let ctrl = pts.iter().zip(&c.ctrl).map(|(p, h)| [p.x * h[3], p.y * h[3], p.z * h[3], h[3]]).collect(); + CurveN { degree: c.degree, knots: c.knots.clone(), ctrl } +} + +/// The point `f` (0…1) of the way along a curve's parameter range. +fn point_at(c: &CurveN<4>, f: f64) -> Option { + let (t0, t1) = (*c.knots.get(c.degree)?, *c.knots.get(c.ctrl.len())?); + let ([x, y, z, w], _) = c.eval(t0 + (t1 - t0) * f.clamp(0.0, 1.0))?; + (w.abs() > 1e-300).then(|| Vec3::new(x / w, y / w, z / w)) +} + +/// Whether two curves pair up: the same degree, knots and weights (their control points +/// correspond). +fn pairs(a: &CurveN<4>, b: &CurveN<4>) -> bool { + let near = |x: f64, y: f64| (x - y).abs() <= 1e-9 * (1.0 + x.abs()); + a.degree == b.degree + && a.ctrl.len() == b.ctrl.len() + && a.knots.len() == b.knots.len() + && a.knots.iter().zip(&b.knots).all(|(x, y)| near(*x, *y)) + && a.ctrl.iter().zip(&b.ctrl).all(|(x, y)| near(x[3], y[3])) +} + +/// Where a rail meets a section: the point of the section it guides (as a wire parameter: the +/// curve's index plus how far along its parameter range), that point, the nudge onto it from where +/// the rail meets the section's plane, and how far along the rail that is (segment and fraction). struct Anchor { g: f64, on: Vec3, @@ -42,64 +106,41 @@ struct Rail { } /// An affine move: `x` goes to `to + m·(x − from)` (`m` by columns). -struct Affine { +pub(crate) struct Affine { from: Vec3, to: Vec3, m: [Vec3; 3], } impl Affine { - fn apply(&self, x: Vec3) -> Vec3 { + pub(crate) fn apply(&self, x: Vec3) -> Vec3 { let d = x - self.from; self.to + self.m[0] * d.x + self.m[1] * d.y + self.m[2] * d.z } } -/// The loft's wires with stations added between the sections so that the loft follows `rails` -/// (polylines; see the module notes). `planes` are the sections' planes, `wires` their matched -/// wires (as [`crate::build::loft_wires`] or a sheet loft makes them: the k-th edges of every -/// wire are B-splines on one knot vector), both in loft order; `closed` whether the wires close. -/// Without rails the wires come back as they are. -pub(crate) fn railed_wires(planes: &[Plane], wires: &[mt::Wire], closed: bool, rails: &[Vec], fit: RailFit) -> Result> { +/// The loft's sections with stations added between them so that the loft follows `rails` +/// (polylines; see the module notes), in loft order: each entry one section's (or station's) +/// curves. `closed` says whether the sections close. Without rails the sections' own curves come +/// back. With rails, every section's k-th curve has to pair with the others' (the same kind, +/// so their control points correspond). +pub(crate) fn railed(sections: &[Section], closed: bool, rails: &[Vec], fit: RailFit) -> Result>>> { if rails.is_empty() { - return Ok(wires.to_vec()); + return Ok(sections.iter().map(|s| s.curves.clone()).collect()); } if rails.len() > 2 { return Err(KernelError::Invalid("a loft takes one or two guide rails".into())); } let fail = |m: &str| KernelError::Failed(format!("loft rails: {m}")); - let count = wires.len(); - if count < 2 || planes.len() != count { - return Err(fail("sections")); + let count = sections.len(); + let lead = sections.first().map(|s| &s.curves).ok_or_else(|| fail("sections"))?; + let n = lead.len(); + if count < 2 || n == 0 || sections.iter().any(|s| s.curves.len() != n || s.curves.iter().zip(lead).any(|(a, b)| !pairs(a, b))) { + return Err(KernelError::Invalid( + "not supported yet: a loft along guide rails between sections whose curves differ in kind (a line against an arc)".into(), + )); } - // Each section's edge curves, and the knot vector the k-th edges share. - let curves: Vec> = wires - .iter() - .map(|w| { - w.edge_iter() - .map(|e| match e.curve() { - mt::Curve::BSplineCurve(c) if e.orientation() => Some(c), - _ => None, - }) - .collect::>>() - }) - .collect::>() - .ok_or_else(|| fail("section curves"))?; - let first = curves.first().ok_or_else(|| fail("sections"))?; - let n = first.len(); - let knots: Vec = first.iter().map(|c| c.knot_vec().clone()).collect(); - let sizes: Vec = first.iter().map(|c| c.control_points().len()).collect(); - if n == 0 - || curves - .iter() - .any(|cs| cs.len() != n || cs.iter().zip(&knots).zip(&sizes).any(|((c, k), m)| c.knot_vec() != k || c.control_points().len() != *m)) - { - return Err(fail("sections parameterised differently")); - } - let ctrl: Vec>> = - curves.iter().map(|cs| cs.iter().map(|c| c.control_points().iter().map(|p| from_p3(*p)).collect()).collect()).collect(); - let edges: Vec> = wires.iter().map(|w| w.edge_iter().cloned().collect()).collect(); - let along = crate::build::section_parameters(&edges); + let ctrl: Vec>> = sections.iter().map(|s| s.curves.iter().map(|c| points(c).0).collect()).collect(); let mut bounds = solidcraft_geom::Aabb3::EMPTY; for p in ctrl.iter().flatten().flatten() { if !p.is_finite() { @@ -109,86 +150,90 @@ pub(crate) fn railed_wires(planes: &[Plane], wires: &[mt::Wire], closed: bool, r } let size = bounds.diagonal(); let tol = (size * 1e-4).max(1e-6); - let start = centroid(ctrl.first().ok_or_else(|| fail("sections"))?); - let rails: Vec = rails.iter().map(|r| rail(r, start, planes, &curves, tol)).collect::>()?; - if let [a, b] = &rails[..] - && a.anchors.iter().zip(&b.anchors).any(|(p, q)| p.on.dist(q.on) <= tol) - { - return Err(KernelError::Invalid("the two guide rails meet a section at the same point".into())); + // The sections' parameters along the loft: in proportion to the mean distance between their + // curves' starts. + let mut along = vec![0.0]; + for w in ctrl.windows(2) { + let step = w[0].iter().zip(&w[1]).filter_map(|(a, b)| Some(a.first()?.dist(*b.first()?))).sum::() / n as f64; + along.push(along.last().copied().unwrap_or(0.0) + step); } - // The plain loft between the sections: each control point across them, straight between two - // sections, the smooth loft's curve through three or more. - let across: Vec>> = if count == 2 { + let total = along.last().copied().unwrap_or(0.0); + if !(total > 1e-9) || along.windows(2).any(|w| !(w[1] - w[0] > 1e-9 * total)) { + return Err(KernelError::Invalid("two loft sections sit on top of each other".into())); + } + along.iter_mut().for_each(|u| *u /= total); + // The plain loft between the sections: each control point straight between two sections, the + // curve (quadratic, or cubic from four) through them across more. + let degree = (count - 1).min(3); + let across: Vec>> = if count == 2 { Vec::new() } else { (0..n) .map(|k| { - (0..sizes.get(k).copied().unwrap_or(0)) + (0..lead.get(k).map_or(0, |c| c.ctrl.len())) .map(|j| { - let pts: Vec = ctrl.iter().filter_map(|s| s.get(k).and_then(|e| e.get(j)).copied()).collect(); - crate::build::across(&pts, &along) + let pts: Vec<[f64; 3]> = ctrl.iter().filter_map(|s| s.get(k)?.get(j).map(|q| [q.x, q.y, q.z])).collect(); + CurveN::interpolate(&along, &pts, degree).map_err(|e| fail(&e.to_string())) }) - .collect() + .collect::>>() }) - .collect() + .collect::>()? }; let plain = |v: f64| -> Result>> { let (Some(a), Some(b)) = (ctrl.first(), ctrl.last()) else { return Err(fail("sections")) }; if count == 2 { return Ok(a.iter().zip(b).map(|(ea, eb)| ea.iter().zip(eb).map(|(p, q)| p.lerp(*q, v)).collect()).collect()); } - across.iter().map(|cs| cs.iter().map(|c| c.as_ref().map(|c| from_p3(c.subs(v))).ok_or_else(|| fail("the plain loft"))).collect()).collect() + across + .iter() + .map(|cs| cs.iter().map(|c| c.eval(v).map(|([x, y, z], _)| Vec3::new(x, y, z)).ok_or_else(|| fail("the plain loft"))).collect()) + .collect() }; - // The middle of the plain loft (the middles of the sections' control points, across them as - // the control points are: the middle is linear in them) and its direction. - let middles: Vec = ctrl.iter().map(|s| centroid(s)).collect(); - let middle_curve = if count == 2 { None } else { Some(crate::build::across(&middles, &along).ok_or_else(|| fail("the plain loft"))?) }; + let curves_of = |pts: &[Vec]| -> Vec> { lead.iter().zip(pts).map(|(c, p)| with(c, p)).collect() }; + // The plain loft's middle and its direction there. + let middle_at = |v: f64| -> Result { centroid(&curves_of(&plain(v)?)).ok_or_else(|| fail("the plain loft")) }; let middle = |v: f64| -> Result<(Vec3, Vec3)> { - let (p, d) = match (&middle_curve, middles.first(), middles.last()) { - (Some(c), ..) => { - let d = c.der(v); - (from_p3(c.subs(v)), Vec3::new(d.x, d.y, d.z)) - } - (None, Some(a), Some(b)) => (a.lerp(*b, v), *b - *a), - _ => return Err(fail("sections")), - }; + let h = 1e-4; + let d = middle_at((v + h).min(1.0))? - middle_at((v - h).max(0.0))?; let d = d.normalized().ok_or_else(|| KernelError::Invalid("two loft sections sit on top of each other".into()))?; - Ok((p, d)) + Ok((middle_at(v)?, d)) }; + let start = centroid(lead).ok_or_else(|| fail("sections"))?; + let rails: Vec = rails.iter().map(|r| rail(r, start, sections, tol)).collect::>()?; + if let [a, b] = &rails[..] + && a.anchors.iter().zip(&b.anchors).any(|(p, q)| p.on.dist(q.on) <= tol) + { + return Err(KernelError::Invalid("the two guide rails meet a section at the same point".into())); + } // The sections' normals, turned to agree with the first's. let mut normals: Vec = Vec::with_capacity(count); - for p in planes { - let n = p.normal(); - let prev = normals.last().copied().unwrap_or(n); - normals.push(if n.dot(prev) < 0.0 { n * -1.0 } else { n }); + for s in sections { + let nn = s.plane.normal(); + let prev = normals.last().copied().unwrap_or(nn); + normals.push(if nn.dot(prev) < 0.0 { nn * -1.0 } else { nn }); } let spans = count - 1; let per = (MAX_WIRES.saturating_sub(count) / spans).clamp(1, MAX_PER_SPAN); let mut out = Vec::with_capacity(count + spans * per); for i in 0..spans { - out.push(wires.get(i).cloned().ok_or_else(|| fail("sections"))?); + out.push(sections.get(i).map(|s| s.curves.clone()).ok_or_else(|| fail("sections"))?); let (Some(&v0), Some(&v1), Some(&n0), Some(&n1)) = (along.get(i), along.get(i + 1), normals.get(i), normals.get(i + 1)) else { return Err(fail("sections")); }; - // Each rail's anchors at the span's two sections, and where its walk has got to. - let mut spans_of: Vec<(&Rail, &Anchor, &Anchor, (usize, f64))> = Vec::with_capacity(rails.len()); - for r in &rails { - let (Some(a0), Some(a1)) = (r.anchors.get(i), r.anchors.get(i + 1)) else { return Err(fail("rail")) }; - spans_of.push((r, a0, a1, a0.at)); - } + let mut cursors: Vec<(usize, f64)> = rails.iter().map(|r| r.anchors.get(i).map_or((0, 0.0), |a| a.at)).collect(); for q in 1..=per { let f = q as f64 / (per + 1) as f64; let v = v0 + f * (v1 - v0); - let station = plain(v)?; + let station = curves_of(&plain(v)?); let (mid, dir) = middle(v)?; // The station's plane turns from one section's to the next's. let normal = n0.lerp(n1, f).normalized().ok_or_else(|| fail("section planes"))?; let mut pairs = Vec::with_capacity(rails.len()); - for (r, a0, a1, cursor) in &mut spans_of { - let anchor = wire_point(&station, &knots, interpolate_g(a0.g, a1.g, f, n, closed))?; - // Where the rail crosses the station's plane through the point it guides, nudged - // so that at each section it is the section's own point (a rail drawn a hair off - // a section moves nothing there). + for (r, cursor) in rails.iter().zip(cursors.iter_mut()) { + let (Some(a0), Some(a1)) = (r.anchors.get(i), r.anchors.get(i + 1)) else { return Err(fail("rail")) }; + let anchor = wire_point(&station, interpolate_g(a0.g, a1.g, f, n, closed))?; + // Where the rail crosses the station's plane through the point it guides, nudged so + // that at each section it is the section's own point. let Some((hit, at)) = crate::sweep_path::rail_crossing(&r.pts, anchor, normal, *cursor, tol) else { return Err(KernelError::Invalid(format!( "a guide rail turns back between sections {} and {}: it has to run on from one section to the next", @@ -197,21 +242,25 @@ pub(crate) fn railed_wires(planes: &[Plane], wires: &[mt::Wire], closed: bool, r ))); }; *cursor = at; - let target = hit + a0.nudge * (1.0 - f) + a1.nudge * f; - pairs.push((anchor, target)); + pairs.push((anchor, hit + a0.nudge * (1.0 - f) + a1.nudge * f)); } let map = station_map(&pairs, mid, dir, fit, size)?; - let moved: Vec> = station.iter().map(|e| e.iter().map(|p| map.apply(*p)).collect()).collect(); - out.push(wire_of(&moved, &knots, closed)?); + out.push(station.iter().map(|c| with(c, &points(c).0.iter().map(|p| map.apply(*p)).collect::>())).collect()); } } - out.push(wires.last().cloned().ok_or_else(|| fail("sections"))?); + out.push(sections.last().map(|s| s.curves.clone()).ok_or_else(|| fail("sections"))?); Ok(out) } -/// The rail `pts` from its end nearer `start` (the first section's middle), where it meets each -/// section: across the section's plane, on the section's curve within `tol`. -fn rail(pts: &[Vec3], start: Vec3, planes: &[Plane], curves: &[Vec], tol: f64) -> Result { +/// The rail `pts` from its end nearer `start` (the first section's middle), and where it meets +/// each section, on the section's curve within `tol`. +/// +/// A rail runs from the first section to the last: it meets the last section at its end. In +/// between it meets each section where it first crosses the section's plane after the section +/// before. The end is not a crossing: a rail that lies in the last section's plane (a keel drawn +/// in the bow's sketch plane) crosses that plane all along, first at the far section, and meets the +/// section only where it ends. +fn rail(pts: &[Vec3], start: Vec3, sections: &[Section], tol: f64) -> Result { let mut pts = crate::sweep_path::clean(pts).map_err(|_| KernelError::Invalid("a guide rail needs 2…100000 finite points along its length".into()))?; if let (Some(a), Some(b)) = (pts.first(), pts.last()) @@ -219,17 +268,27 @@ fn rail(pts: &[Vec3], start: Vec3, planes: &[Plane], curves: &[Vec], tol: { pts.reverse(); } + let not_reached = |i: usize| { + KernelError::Invalid(format!( + "a guide rail does not reach section {}: a rail has to run from the first section to the last, through every one", + i + 1 + )) + }; let mut cursor = (0usize, 0.0f64); - let mut anchors = Vec::with_capacity(planes.len()); - for (i, (plane, section)) in planes.iter().zip(curves).enumerate() { - let Some((hit, at)) = crate::sweep_path::rail_crossing(&pts, plane.origin, plane.normal(), cursor, tol) else { - return Err(KernelError::Invalid(format!( - "a guide rail does not reach section {}: a rail has to run from the first section to the last, through every one", - i + 1 - ))); + let mut anchors = Vec::with_capacity(sections.len()); + for (i, s) in sections.iter().enumerate() { + let (plane, curves) = (&s.plane, &s.curves); + let (hit, at) = if i + 1 == sections.len() { + let end = *pts.last().ok_or_else(|| not_reached(i))?; + if plane.height(end).abs() > tol { + return Err(not_reached(i)); + } + (end, (pts.len().saturating_sub(2), 1.0)) + } else { + crate::sweep_path::rail_crossing(&pts, plane.origin, plane.normal(), cursor, tol).ok_or_else(|| not_reached(i))? }; cursor = at; - let (g, on, d) = nearest_on(section, hit).ok_or_else(|| KernelError::Failed("loft rails: section".into()))?; + let (g, on, d) = nearest_on(curves, hit).ok_or_else(|| KernelError::Failed("loft rails: section".into()))?; if d > tol { return Err(KernelError::Invalid(format!( "a guide rail crosses section {}'s plane {d:.3} mm from its curves: a rail has to pass through every section", @@ -241,17 +300,28 @@ fn rail(pts: &[Vec3], start: Vec3, planes: &[Plane], curves: &[Vec], tol: Ok(Rail { pts, anchors }) } -/// The point of a section's wire (its edge curves) nearest `p`: as a wire parameter, the point, -/// and how far it is. -fn nearest_on(section: &[Curve], p: Vec3) -> Option<(f64, Vec3, f64)> { +/// The point of a section (its curves) nearest `p`: as a wire parameter, the point, and how far +/// it is. Each curve is searched from its nearest of 256 even samples by golden-section search. +fn nearest_on(section: &[CurveN<4>], p: Vec3) -> Option<(f64, Vec3, f64)> { + const SAMPLES: usize = 256; let mut best: Option<(f64, Vec3, f64)> = None; for (k, c) in section.iter().enumerate() { - let (t0, t1) = c.range_tuple(); - let t = crate::curveblend::param_on(&mt::Curve::BSplineCurve(c.clone()), p)?; - let q = from_p3(c.subs(t)); - let d = q.dist(p); - if best.as_ref().is_none_or(|b| d < b.2) { - best = Some((k as f64 + (t - t0) / (t1 - t0).max(1e-300), q, d)); + let d = |f: f64| point_at(c, f).map_or(f64::INFINITY, |q| q.dist(p)); + let Some(i) = (0..=SAMPLES).min_by(|a, b| d(*a as f64 / SAMPLES as f64).total_cmp(&d(*b as f64 / SAMPLES as f64))) else { continue }; + let (mut lo, mut hi) = ((i as f64 - 1.0).max(0.0) / SAMPLES as f64, (i as f64 + 1.0).min(SAMPLES as f64) / SAMPLES as f64); + let g = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..80 { + let (a, b) = (hi - g * (hi - lo), lo + g * (hi - lo)); + if d(a) < d(b) { + hi = b; + } else { + lo = a; + } + } + let f = 0.5 * (lo + hi); + let q = point_at(c, f)?; + if best.as_ref().is_none_or(|b| q.dist(p) < b.2) { + best = Some((k as f64 + f, q, q.dist(p))); } } best @@ -259,7 +329,7 @@ fn nearest_on(section: &[Curve], p: Vec3) -> Option<(f64, Vec3, f64)> { /// A wire parameter `f` of the way from `g0` to `g1`; round a closed wire of `n` edges the /// shorter way. -fn interpolate_g(g0: f64, g1: f64, f: f64, n: usize, closed: bool) -> f64 { +pub(crate) fn interpolate_g(g0: f64, g1: f64, f: f64, n: usize, closed: bool) -> f64 { let n = n as f64; if !closed { return (g0 + f * (g1 - g0)).clamp(0.0, n); @@ -273,28 +343,49 @@ fn interpolate_g(g0: f64, g1: f64, f: f64, n: usize, closed: bool) -> f64 { (g0 + f * d).rem_euclid(n) } -/// The point at wire parameter `g` of a wire given by its edges' control points on `knots`. -fn wire_point(ctrl: &[Vec], knots: &[mt::KnotVec], g: f64) -> Result { - let n = ctrl.len(); - let k = (g.floor().max(0.0) as usize).min(n.saturating_sub(1)); - let (Some(pts), Some(kv)) = (ctrl.get(k), knots.get(k)) else { return Err(KernelError::Failed("loft rails: wire".into())) }; - let c = edge_curve(kv, pts)?; - let (t0, t1) = c.range_tuple(); - let f = (g - k as f64).clamp(0.0, 1.0); - Ok(from_p3(c.subs(t0 + (t1 - t0) * f))) +/// The point at wire parameter `g` of a section's curves. +fn wire_point(section: &[CurveN<4>], g: f64) -> Result { + let k = (g.floor().max(0.0) as usize).min(section.len().saturating_sub(1)); + section.get(k).and_then(|c| point_at(c, g - k as f64)).ok_or_else(|| KernelError::Failed("loft rails: section".into())) } -/// The middle of a wire's control points. -fn centroid(ctrl: &[Vec]) -> Vec3 { - let (sum, n) = ctrl.iter().flatten().fold((Vec3::ZERO, 0usize), |(s, n), p| (s + *p, n + 1)); - sum * (1.0 / n.max(1) as f64) +/// The middle of a section: the centroid of its curves by length, ∫ x ds / ∫ ds, each knot +/// span by 8-point Gauss–Legendre. It is the section's shape alone, whatever control points +/// describe it: a circle's is its centre, however many pieces it is drawn in (a whole circle as +/// one closed rational curve repeats its first control point as its last, and the mean of the +/// control points sat a ninth of the radius towards it). `None` for a section with no length. +fn centroid(section: &[CurveN<4>]) -> Option { + let (mut sum, mut length) = (Vec3::ZERO, 0.0); + for c in section { + let (lo, hi) = (*c.knots.get(c.degree)?, *c.knots.get(c.ctrl.len())?); + for w in c.knots.windows(2) { + let (a, b) = (w[0].max(lo), w[1].min(hi)); + if !(b > a) { + continue; + } + let (mid, half) = (0.5 * (a + b), 0.5 * (b - a)); + for (x, wt) in solidcraft_geom::bspline::GAUSS_8 { + let ([hx, hy, hz, hw], [dx, dy, dz, dw]) = c.eval(mid + half * x)?; + if !(hw.abs() > 1e-300) { + return None; + } + let p = Vec3::new(hx / hw, hy / hw, hz / hw); + // The rational point's derivative: (h' − p w') / w. + let speed = ((Vec3::new(dx, dy, dz) - p * dw) * (1.0 / hw)).len(); + let ds = wt * half * speed; + sum += p * ds; + length += ds; + } + } + } + (length > 0.0 && sum.is_finite()).then(|| sum * (1.0 / length)) } /// The move that puts a station's guided points onto the rails (`pairs`: each point with its /// rail's point), the station's middle `middle`, the loft's direction there `dir` (unit); `size` /// the loft's size. One rail: turned about `dir` and sized about the middle, shifted along `dir`; /// two: carried with the first, turned and sized with the line between them, leaning along `dir`. -fn station_map(pairs: &[(Vec3, Vec3)], middle: Vec3, dir: Vec3, fit: RailFit, size: f64) -> Result { +pub(crate) fn station_map(pairs: &[(Vec3, Vec3)], middle: Vec3, dir: Vec3, fit: RailFit, size: f64) -> Result { let (from, to, a, r, two) = match pairs { [(p, q)] => (middle, middle, *p - middle, *q - middle, false), [(p1, q1), (p2, q2)] => (*p1, *q1, *p2 - *p1, *q2 - *q1, true), @@ -324,26 +415,3 @@ fn station_map(pairs: &[(Vec3, Vec3)], middle: Vec3, dir: Vec3, fit: RailFit, si let shift = if two { Vec3::ZERO } else { dir * lead }; Ok(Affine { from, to: to + shift, m }) } - -/// A wire of B-spline edges with these control points on these knots, joined end to end -/// (closing back on its first edge's start when `closed`). -fn wire_of(ctrl: &[Vec], knots: &[mt::KnotVec], closed: bool) -> Result { - let fail = || KernelError::Failed("loft rails: station".into()); - let n = ctrl.len(); - let mut verts: Vec = ctrl.iter().map(|e| e.first().map(|p| mt::Vertex::new(p3(*p)))).collect::>().ok_or_else(fail)?; - if !closed { - verts.push(mt::Vertex::new(p3(*ctrl.last().and_then(|e| e.last()).ok_or_else(fail)?))); - } - let mut edges = Vec::with_capacity(n); - for (i, (pts, kv)) in ctrl.iter().zip(knots).enumerate() { - let (Some(a), Some(b)) = (verts.get(i), verts.get(if closed { (i + 1) % n } else { i + 1 })) else { return Err(fail()) }; - let c = edge_curve(kv, pts)?; - edges.push(mt::Edge::new(a, b, mt::Curve::BSplineCurve(c))); - } - Ok(edges.into()) -} - -/// An edge's B-spline from its control points on its knots. -fn edge_curve(kv: &mt::KnotVec, pts: &[Vec3]) -> Result { - Curve::try_new(kv.clone(), pts.iter().map(|p| p3(*p)).collect()).map_err(|e| KernelError::Failed(format!("loft rails: {e}"))) -} diff --git a/crates/kernel/src/loft_rails_tests.rs b/crates/kernel/src/loft_rails_tests.rs index 4755dfee2..d4c206aa8 100644 --- a/crates/kernel/src/loft_rails_tests.rs +++ b/crates/kernel/src/loft_rails_tests.rs @@ -5,9 +5,10 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use solidcraft_geom::prelude::*; use std::f64::consts::PI; -use solidcraft_geom::{Loop2, Plane, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Seg2, Vec2, Vec3}; use crate::{KernelError, RailFit, loft, loft_sheet_with_rails, loft_with_rails, measure}; @@ -42,15 +43,15 @@ fn volume(b: &crate::Body) -> f64 { b.volume_at(1e-4).unwrap() } -/// How far `p` is from the nearest face of the body. +/// How far `p` is from the nearest face's surface of the body. fn off(b: &crate::Body, p: Vec3) -> f64 { - use truck_modeling::{ParametricSurface, SearchNearestParameter}; - b.solid - .face_iter() + b.record() + .faces + .iter() .filter_map(|f| { - let s = f.surface(); - let (u, v) = s.search_nearest_parameter(crate::body::p3(p), None, 100)?; - Some(crate::body::from_p3(s.subs(u, v)).dist(p)) + let s = solidcraft_geom::brep::eval::SurfaceEval::new(&f.surface).ok()?; + let uv = s.project(p, None, f64::INFINITY)?; + Some(s.point(uv)?.dist(p)) }) .fold(f64::INFINITY, f64::min) } diff --git a/crates/kernel/src/loft_region_tests.rs b/crates/kernel/src/loft_region_tests.rs index 462ea8217..02e9b7b8a 100644 --- a/crates/kernel/src/loft_region_tests.rs +++ b/crates/kernel/src/loft_region_tests.rs @@ -1,8 +1,9 @@ //! Analytic regressions for lofted passages (#2435). +use solidcraft_geom::prelude::*; use std::f64::consts::PI; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::{Body, loft_regions, measure, step_export, step_import}; @@ -25,7 +26,7 @@ fn loft_regions_preserve_a_tapered_round_passage_and_step() { for secs in [secs.to_vec(), secs.into_iter().rev().collect()] { let body = loft_regions(&secs).unwrap(); check(&body, want, 1e-3); - assert!(!body.tessellate(0.001).unwrap().contains(Vec3::new(0.0, 0.0, 10.0)), "passage was filled"); + assert!(!body.mesh(&crate::MeshTolerance::chord(0.001)).unwrap().contains(Vec3::new(0.0, 0.0, 10.0)), "passage was filled"); let imported = step_import(&step_export(&[&body], "SolidCraft").unwrap()).unwrap(); assert_eq!(imported.bodies.len(), 1); check(&imported.bodies[0].body, want, 1e-3); @@ -41,7 +42,7 @@ fn loft_regions_smooth_inner_and_outer_walls_together() { for secs in [secs.to_vec(), secs.into_iter().rev().collect()] { let b = loft_regions(&secs).unwrap(); check(&b, 22400.0, 1e-4); - assert!(!b.tessellate(0.001).unwrap().contains(Vec3::new(0.0, 0.0, 10.0)), "passage was filled"); + assert!(!b.mesh(&crate::MeshTolerance::chord(0.001)).unwrap().contains(Vec3::new(0.0, 0.0, 10.0)), "passage was filled"); assert_eq!(measure(&b).unwrap().merged.faces, 10, "four outer walls, four inner walls, two caps"); } } @@ -58,7 +59,7 @@ fn loft_regions_match_holes_in_opposite_curve_orders_and_facing_planes() { for secs in [secs.to_vec(), secs.into_iter().rev().collect()] { let body = loft_regions(&secs).unwrap(); check(&body, (1600.0 - PI * 34.0) * 20.0, 1e-3); - let mesh = body.tessellate(0.001).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); assert!(!mesh.contains(Vec3::new(-8.0, 0.0, 10.0))); assert!(!mesh.contains(Vec3::new(8.0, 0.0, 10.0))); assert!(mesh.contains(Vec3::new(0.0, 12.0, 10.0))); @@ -90,7 +91,7 @@ fn loft_regions_bound_segments_after_matching() { // would exceed it in every section. Refuse before allocating the topology. let circle = |x, n| Loop2 { segs: (0..n) - .map(|i| solidcraft_geom::Seg2::Arc { + .map(|i| solidcore_record::Seg2::Arc { center: Vec2::new(x, 0.0), radius: 1.0, start: i as f64 * std::f64::consts::TAU / n as f64, diff --git a/crates/kernel/src/loopblend.rs b/crates/kernel/src/loopblend.rs deleted file mode 100644 index 89b21a2ef..000000000 --- a/crates/kernel/src/loopblend.rs +++ /dev/null @@ -1,959 +0,0 @@ -//! Blending a whole boundary loop of a planar face whose neighbours are walls standing -//! perpendicular to it (planes, and cylinders with axes along the face normal): a pocket floor, -//! the top outline of an extruded plate. Lines and arcs can meet tangentially or at mitred sharp -//! corners. The face shrinks by the radius, the walls are trimmed by it, and each loop edge -//! gets a blend face: a cylinder (or plane, for a chamfer) along a line, a torus (or cone) along -//! an arc, all meeting along the profile curves at the joints. Sharp joints at perpendicular -//! curved walls follow the intersections of the exact offsets, fitted within tolerance. -//! A chamfer may also set back by different distances on the face and up the walls (two -//! distances, or a distance and an angle: [`loop_chamfer_sides`]). - -use std::collections::HashMap; - -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, builder}; - -use crate::blend::{ChamferSide, too_large}; -use crate::body::{Solid, from_p3, p3, v3}; -use crate::record::Rebuild; -use crate::{KernelError, Result}; - -fn unsupported(msg: &str) -> KernelError { - KernelError::Failed(format!("not supported yet: {msg}")) -} - -#[derive(Clone, Copy, Debug)] -enum Seg { - Line { - a: Vec3, - b: Vec3, - }, - /// Arc from `a` to `b` about `c` turning by `angle` about `axis` (right hand, angle > 0). - Arc { - a: Vec3, - c: Vec3, - axis: Vec3, - angle: f64, - mid: Vec3, - }, -} - -impl Seg { - fn start(&self) -> Vec3 { - match *self { - Seg::Line { a, .. } | Seg::Arc { a, .. } => a, - } - } - fn end(&self) -> Vec3 { - match *self { - Seg::Line { b, .. } => b, - Seg::Arc { a, c, axis, angle, .. } => turn(a, c, axis, angle), - } - } - /// Unit tangent (direction of travel) at a point of the segment. - fn tangent(&self, p: Vec3) -> Option { - match *self { - Seg::Line { a, b } => (b - a).normalized(), - Seg::Arc { c, axis, .. } => axis.cross(p - c).normalized(), - } - } -} - -/// Intersection of two inward offsets nearest their shared corner, in the face plane. -fn offset_joint(prev: &Seg, cur: &Seg, n: Vec3, d: f64) -> Option { - let p = cur.start(); - let line_circle = |line: &Seg, arc: &Seg| { - let Seg::Arc { a, c, .. } = *arc else { return None }; - let tangent = line.tangent(p)?; - let origin = p + n.cross(tangent) * d; - let radius = a.dist(c) + n.cross(arc.tangent(p)?).dot((p - c).normalized()?) * d; - let foot = origin + tangent * (c - origin).dot(tangent); - let height2 = radius * radius - foot.dist(c).powi(2); - if !(radius > 0.0 && height2 >= 0.0) { - return None; - } - let (a, b) = (foot + tangent * height2.sqrt(), foot - tangent * height2.sqrt()); - Some(if a.dist(p) < b.dist(p) { a } else { b }) - }; - match (prev, cur) { - (Seg::Line { .. }, Seg::Arc { .. }) => line_circle(prev, cur), - (Seg::Arc { .. }, Seg::Line { .. }) => line_circle(cur, prev), - (Seg::Arc { a: a0, c: c0, .. }, Seg::Arc { a: a1, c: c1, .. }) => { - let delta = *c1 - *c0; - let distance = delta.len(); - let axis = delta.normalized()?; - let r0 = a0.dist(*c0) + n.cross(prev.tangent(p)?).dot((p - *c0).normalized()?) * d; - let r1 = a1.dist(*c1) + n.cross(cur.tangent(p)?).dot((p - *c1).normalized()?) * d; - let along = (r0 * r0 - r1 * r1 + distance * distance) / (2.0 * distance); - let height2 = r0 * r0 - along * along; - if !(r0 > 0.0 && r1 > 0.0 && height2 >= 0.0) { - return None; - } - let foot = *c0 + axis * along; - let across = n.cross(axis) * height2.sqrt(); - let (a, b) = (foot + across, foot - across); - Some(if a.dist(p) < b.dist(p) { a } else { b }) - } - _ => None, - } -} - -/// A curved-wall joint is generally not planar. Fit its exact offset slices rather than -/// projecting a circular section onto a tangent mitre and revolving that distorted section. -/// `(r, rw)`: the round's radius (`rw` unused), or a chamfer's setbacks on the face and up the wall. -fn offset_profile(prev: &Seg, cur: &Seg, n: Vec3, side: f64, (r, rw): (f64, f64), round: bool, tol: f64) -> Result { - use mt::ParametricCurve; - let point = |u: f64| { - let (d, h) = if round { - let (sin, cos) = (u * std::f64::consts::FRAC_PI_2).sin_cos(); - (r * (1.0 - sin), r * (1.0 - cos)) - } else { - (r * (1.0 - u), rw * u) - }; - offset_joint(prev, cur, n, d).map(|p| p + n * (side * h)) - }; - for count in [8, 16, 32, 64, 128] { - let pts = (0..=count) - .map(|i| point(f64::from(i) / f64::from(count))) - .collect::>>() - .ok_or_else(|| too_large("the blend's offset walls do not meet"))?; - let curve = crate::build::interpolate_cubic(&pts).ok_or_else(|| unsupported("curved corner profile"))?; - if (0..count).all(|i| { - let u = (f64::from(i) + 0.5) / f64::from(count); - point(u).is_some_and(|p| p.dist(from_p3(curve.subs(u))) <= tol) - }) { - return Ok(mt::Curve::BSplineCurve(curve)); - } - } - Err(unsupported("could not fit the curved corner within tolerance")) -} - -/// The exact shape of an oriented loop edge (a line, or an arc found from samples). -fn seg_of(e: &mt::Edge, tol: f64) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point())); - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let pts: Vec = (0..=16).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 16.0))).collect(); - let closed = a.dist(b) < tol; - if !closed && pts.iter().all(|p| p.dist_to_segment(a, b) < tol) { - return Some(Seg::Line { a, b }); - } - let m = *pts.get(8)?; - // A closed edge (a full circle): fit through points a third of the way round. - let (b_fit, m_fit) = if closed { (*pts.get(5)?, *pts.get(11)?) } else { (b, m) }; - let (u, v) = (b_fit - a, m_fit - a); - let w = u.cross(v); - let d = 2.0 * w.len2(); - if d < 1e-300 { - return None; - } - let centre = a + (v.cross(w) * u.len2() + w.cross(u) * v.len2()) * (1.0 / d); - let r = centre.dist(a); - if !pts.iter().all(|p| (p.dist(centre) - r).abs() < tol) { - return None; - } - // Turning direction: the travel at a is axis × (a − c). - let t_a = (*pts.get(1)? - a).normalized()?; - let mut axis = w.normalized()?; - if axis.cross(a - centre).dot(t_a) < 0.0 { - axis = -axis; - } - let (ra, rb) = ((a - centre).normalized()?, (b - centre).normalized()?); - let mut angle = ra.dot(rb).clamp(-1.0, 1.0).acos(); - if ra.cross(rb).dot(axis) < 0.0 { - angle = std::f64::consts::TAU - angle; - } - if closed { - angle = std::f64::consts::TAU; - } - Some(Seg::Arc { a, c: centre, axis, angle, mid: m }) -} - -/// Whether an edge is a straight segment: a line, or a curve whose points all lie on the chord -/// (the contact lines of a rolling-ball blend between parallel walls are such curves). -fn is_straight(e: &mt::Edge, tol: f64) -> bool { - use mt::{BoundedCurve, ParametricCurve}; - if matches!(e.curve(), mt::Curve::Line(_)) { - return true; - } - let (a, b) = (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point())); - if a.dist(b) < tol { - return false; - } - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=16).all(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 16.0)).dist_to_segment(a, b) < tol) -} - -/// `p` turned about the line (c, axis) by `ang`. -fn turn(p: Vec3, c: Vec3, axis: Vec3, ang: f64) -> Vec3 { - let k = axis.normalized().unwrap_or(Vec3::Z); - let v = p - c; - let (s, co) = ang.sin_cos(); - c + v * co + k.cross(v) * s + k * (k.dot(v) * (1.0 - co)) -} - -/// Split full circles in two halves (an edge needs two ends). -fn pieces(segs: &[Seg]) -> Vec<(usize, Seg)> { - let mut out = Vec::new(); - for (i, s) in segs.iter().enumerate() { - match *s { - Seg::Arc { a, c, axis, angle, .. } if angle > std::f64::consts::TAU - 1e-9 => { - let h = std::f64::consts::PI; - let a2 = turn(a, c, axis, h); - out.push((i, Seg::Arc { a, c, axis, angle: h, mid: turn(a, c, axis, h / 2.0) })); - out.push((i, Seg::Arc { a: a2, c, axis, angle: h, mid: turn(a, c, axis, 1.5 * h) })); - } - _ => out.push((i, *s)), - } - } - out -} - -fn plane_normal(f: &mt::Face) -> Option { - match f.oriented_surface() { - mt::Surface::Plane(p) => { - let n = p.normal(); - Vec3::new(n.x, n.y, n.z).normalized() - } - _ => None, - } -} - -/// Outward normal of a face at a point on it. -fn face_normal(f: &mt::Face, p: Vec3) -> Option { - use mt::{ParametricSurface3D, SearchNearestParameter, SearchParameter}; - let s = f.oriented_surface(); - let (u, v) = s.search_parameter(p3(p), None, 100).or_else(|| s.search_nearest_parameter(p3(p), None, 100))?; - let n = s.normal(u, v); - Vec3::new(n.x, n.y, n.z).normalized() -} - -/// Blend `edges` (by id) if they form a boundary loop or neighbouring run of a planar face with -/// perpendicular walls, with what it built from `solid` (each blend face in place of its loop -/// edge). `None` when the edges are not such a loop. -pub(crate) fn loop_blend(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Option> { - loop_blend_sized(solid, edge_ids, size, Sizing::Equal { r, round }) -} - -/// [`loop_blend`] as a chamfer of `d1` on its first face and the second side by `side`. The -/// first face is the one facing up most (the planar face or its wall, decided as for a straight -/// edge, see [`crate::chamfer_sides`]), the other one with `flip`. -pub(crate) fn loop_chamfer_sides( - solid: &Solid, - edge_ids: &[mt::EdgeID], - size: f64, - d1: f64, - side: ChamferSide, - flip: bool, -) -> Option> { - loop_blend_sized(solid, edge_ids, size, Sizing::Sides { d1, side, flip }) -} - -/// How large a loop blend is. -#[derive(Clone, Copy, Debug)] -enum Sizing { - /// A round of radius `r` (`round`), or an equal-distance chamfer of `r`. - Equal { r: f64, round: bool }, - /// A chamfer of `d1` on its first face, the second side by `side` ([`loop_chamfer_sides`]). - Sides { d1: f64, side: ChamferSide, flip: bool }, -} - -fn loop_blend_sized(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option> { - match crate::guard("loop blend", || Ok(loop_blend_inner(solid, edge_ids, size, sizing))) { - Ok(result) => result, - Err(error) => Some(Err(error)), - } -} - -fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option> { - #[cfg(test)] - assert!(crate::guarded(), "loop selection must run inside the kernel guard"); - let tol = (size * 1e-6).max(1e-7); - for (si, shell) in solid.boundaries().iter().enumerate() { - let faces: Vec<&mt::Face> = shell.face_iter().collect(); - for (fi, f) in faces.iter().enumerate() { - let Some(n) = plane_normal(f) else { continue }; - for (wi, w) in f.boundaries().iter().enumerate() { - let ids: Vec = w.edge_iter().map(|e| e.id()).collect(); - if !edge_ids.iter().all(|e| ids.contains(e)) { - continue; - } - if ids.len() == edge_ids.len() { - return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, None)); - } - // A run of neighbouring edges of the loop (its ends meet unblended edges). - let m = ids.len(); - let inside = |i: usize| ids.get(i % m).is_some_and(|x| edge_ids.contains(x)); - let starts: Vec = (0..m).filter(|i| inside(*i) && !inside(*i + m - 1)).collect(); - if let [s0] = starts[..] - && (0..edge_ids.len()).all(|j| inside(s0 + j)) - { - return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, Some((s0, edge_ids.len())))); - } - } - } - } - None -} - -#[allow(clippy::too_many_arguments)] -fn build( - solid: &Solid, - si: usize, - faces: &[&mt::Face], - fi: usize, - wi: usize, - n: Vec3, - size: f64, - tol: f64, - sizing: Sizing, - run: Option<(usize, usize)>, -) -> Result<(Solid, Rebuild)> { - #[cfg(test)] - assert!(crate::guarded(), "loop construction must run inside the kernel guard"); - // `r`: the round's radius or the equal chamfer's size; an unequal chamfer's first distance - // (its setbacks come from `frame`). - let (r, round, sides) = match sizing { - Sizing::Equal { r, round } => (r, round, None), - Sizing::Sides { d1, side, flip } => (d1, false, Some((side, flip))), - }; - let f = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?; - let wire = f.boundaries().get(wi).cloned().ok_or_else(|| KernelError::Failed("loop".into()))?; - let all_edges: Vec = wire.edge_iter().cloned().collect(); - // The blended edges in loop order: the whole loop, or a run of it (open). - let open = run.is_some(); - let edges: Vec = match run { - None => all_edges, - Some((s0, len)) => (0..len).filter_map(|j| all_edges.get((s0 + j) % all_edges.len().max(1)).cloned()).collect(), - }; - let edge_segs: Vec = edges - .iter() - .map(|e| seg_of(e, (size * 1e-5).max(1e-6))) - .collect::>() - .ok_or_else(|| unsupported("loop edges must be lines or arcs"))?; - // Pieces: the loop's edges, full circles in halves; each knows its edge. - let split = pieces(&edge_segs); - let owner: Vec = split.iter().map(|x| x.0).collect(); - let segs: Vec = split.iter().map(|x| x.1).collect(); - let k = segs.len(); - // Joints: k round a whole loop; k + 1 along a run (its two ends included). - let nj = if open { k + 1 } else { k }; - let nxt = |i: usize| if open { i + 1 } else { (i + 1) % k }; - // Joints: smooth, or sharp where the walls meet in one straight seam (the blends - // then meet in a mitre). A loop can therefore mix lines and arcs at its corners. - let mut mitre = vec![false; nj]; - for i in 0..k { - if open && i == 0 { - continue; - } - let (Some(prev), Some(cur)) = (segs.get((i + k - 1) % k), segs.get(i)) else { continue }; - let p = cur.start(); - let (Some(ta), Some(tb)) = (prev.tangent(p), cur.tangent(p)) else { return Err(unsupported("degenerate loop edge")) }; - if ta.dot(tb) < 1.0 - 1e-6 { - if ta.dot(tb) < -1.0 + 1e-3 { - return Err(unsupported("blending a loop with sharp corners next to arcs")); - } - if let Some(x) = mitre.get_mut(i) { - *x = true; - } - } - } - // Walls: the other face of each edge, perpendicular to the face; all on one side. - let mut walls: Vec = Vec::with_capacity(k); - let mut side = 0.0; - for (oi, s) in owner.iter().zip(&segs) { - let e = edges.get(*oi).ok_or_else(|| KernelError::Failed("edge".into()))?; - let wf = faces - .iter() - .position(|g| !std::ptr::eq(*g, *f) && g.edge_iter().any(|x| x.id() == e.id())) - .ok_or_else(|| unsupported("an edge with one face"))?; - let mid = match *s { - Seg::Line { a, b } => (a + b) * 0.5, - Seg::Arc { mid, .. } => mid, - }; - let g = faces.get(wf).ok_or_else(|| KernelError::Failed("wall".into()))?; - let gn = face_normal(g, mid).ok_or_else(|| unsupported("wall normal"))?; - if gn.dot(n).abs() > 1.0 - 1e-6 { - return Err(unsupported("a wall tangent to the face")); - } - // Into the face from the loop: left of travel. - let m = n.cross(s.tangent(mid).ok_or_else(|| unsupported("tangent"))?); - let sd = if gn.dot(m) > 0.0 { 1.0 } else { -1.0 }; - if side != 0.0 && sd != side { - return Err(unsupported("a loop that is partly convex and partly concave")); - } - side = sd; - walls.push(wf); - } - // A run ends in the cross-section through its end vertex: the face there must hold it (a - // plane square to the run). One at an angle cuts the blend's two contacts at different - // places, which the rolling-ball blend handles. - if open { - let ends = [ - (edges.first().map(|e| e.front().clone()), segs.first().map(|s| (s.start(), *s))), - (edges.last().map(|e| e.back().clone()), segs.last().map(|s| (s.end(), *s))), - ]; - for (v, seg) in ends { - let (Some(v), Some((p, s))) = (v, seg) else { return Err(KernelError::Failed("run end".into())) }; - let t = s.tangent(p).ok_or_else(|| unsupported("degenerate loop edge"))?; - let square = faces - .iter() - .enumerate() - .filter(|(gi, g)| *gi != fi && !walls.contains(gi) && g.vertex_iter().any(|x| x == v)) - .all(|(_, g)| plane_normal(g).is_some_and(|gn| gn.dot(t).abs() > 1.0 - 1e-6)); - if !square { - return Err(unsupported("a run of edges ending at a face at an angle")); - } - } - } - // Cross-section at a loop point: into the face (m) and up the wall (t, away from the edge, - // up a concave wall and down a convex one). The ball of radius r touches both at the - // setback s = r / tan(φ/2), φ the angle between m and t; its centre is on the bisector. - let into = |s: &Seg, p: Vec3| -> Vec3 { s.tangent(p).map(|t| n.cross(t)).unwrap_or(Vec3::ZERO) }; - let up = |i: usize, p: Vec3| -> Option { - let s = segs.get(i)?; - let g = faces.get(*walls.get(i)?)?; - let gn = face_normal(g, p)?; - let t = s.tangent(p)?.cross(gn).normalized()?; - Some(if t.dot(n * side) < 0.0 { -t } else { t }) - }; - // An unequal chamfer: whether its first side is the planar face (else the walls). As for a - // straight edge, that is the one facing up most (a curved wall by its mean normal along each - // edge), the other with `flip`; it must be the same all round the loop. - let face_first = match sides { - None => true, - Some((_, flip)) => { - use mt::{BoundedCurve, ParametricCurve}; - let up = Vec3::new(1e-6, 1e-3, 1.0); - let face_up = n.dot(up); - let mut first: Option = None; - for (pi, oi) in owner.iter().enumerate() { - if pi > 0 && owner.get(pi - 1) == Some(oi) { - continue; - } - let (Some(e), Some(g)) = (edges.get(*oi), walls.get(pi).and_then(|w| faces.get(*w))) else { - return Err(KernelError::Failed("loop edge".into())); - }; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let ups: Vec = - (0..=8).filter_map(|j| face_normal(g, from_p3(c.subs(t0 + (t1 - t0) * f64::from(j) / 8.0))).map(|gn| gn.dot(up))).collect(); - if ups.is_empty() { - return Err(unsupported("wall normal")); - } - let wall_up = ups.iter().sum::() / ups.len() as f64; - let mine = (face_up >= wall_up) != flip; - if first.is_some_and(|x| x != mine) { - return Err(unsupported( - "an unequal chamfer round a loop whose first face changes along it (the face faces up more than some walls and less than others)", - )); - } - first = Some(mine); - } - first.unwrap_or(true) - } - }; - // Into the face (m), up the wall (t), the setbacks along each and the distance from the edge - // to a round's centre. - let frame = |i: usize, p: Vec3| -> Option<(Vec3, Vec3, f64, f64, f64)> { - let s = segs.get(i)?; - let (m, t) = (into(s, p), up(i, p)?); - let phi = m.dot(t).clamp(-1.0, 1.0).acos(); - if !(phi > 1e-3 && phi < std::f64::consts::PI - 1e-3) { - return None; - } - let (sf, sw) = match sides { - None => { - let sb = if round { r / (phi / 2.0).tan() } else { r }; - (sb, sb) - } - Some((cs, _)) => { - let d2 = match cs { - ChamferSide::Distance(d) => d, - // The triangle edge–A–B: angle φ at the edge, `a` at A (on the first side). - ChamferSide::Angle(a) => { - let den = (phi + a).sin(); - if den <= 1e-9 { - return None; - } - r * a.sin() / den - } - }; - if face_first { (r, d2) } else { (d2, r) } - } - }; - Some((m, t, sf, sw, r / (phi / 2.0).sin())) - }; - if let Some((ChamferSide::Angle(a), _)) = sides { - for (i, s) in segs.iter().enumerate() { - let p = s.start(); - if let Some(t) = up(i, p) - && (into(s, p).dot(t).clamp(-1.0, 1.0).acos() + a).sin() <= 1e-9 - { - return Err(KernelError::Invalid("that chamfer angle runs past the other face".into())); - } - } - } - // The straight seam between the walls at a sharp joint (direction away from the face). - let seam_dir = |i: usize, p: Vec3| -> Option { - let o = owner.get(i)?; - let v = edges.get(*o)?.front().clone(); - let loop_ids: Vec = edges.iter().map(|e| e.id()).collect(); - let mut dirs = Vec::new(); - for g in faces { - for e in g.edge_iter() { - if loop_ids.contains(&e.id()) || !(*e.front() == v || *e.back() == v) { - continue; - } - let other = if *e.front() == v { e.back().clone() } else { e.front().clone() }; - if let Some(d) = (from_p3(other.point()) - p).normalized() - && !dirs.iter().any(|x: &Vec3| x.dot(d) > 1.0 - 1e-9) - { - dirs.push(d); - } - } - } - match dirs[..] { - [d] => Some(d), - _ => None, - } - }; - let mut pa = Vec::with_capacity(nj); - let mut pb = Vec::with_capacity(nj); - let mut centres = Vec::with_capacity(nj); - let mut curved_joint = vec![false; nj]; - // Joint i: the start of piece i (the end of the last piece for a run's far end). - let joint_point = |i: usize| if i < k { segs.get(i).map(|s| s.start()) } else { segs.last().map(|s| s.end()) }; - for i in 0..nj { - let p = joint_point(i).unwrap_or_default(); - let (m, t, sb, sbw, dc) = frame(i.min(k - 1), p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; - centres.push(p + (m + t).normalized().unwrap_or(m) * dc); - if !mitre.get(i).copied().unwrap_or(false) { - pa.push(p + m * sb); - pb.push(p + t * sbw); - continue; - } - // Sharp joint: the face rails meet where the two offset lines cross; the wall rails - // meet on the seam. - let ip = (i + k - 1) % k; - let (m0, t0, sb0, sbw0, _) = frame(ip, p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; - let (Some(d0), Some(d1)) = (segs.get(ip).and_then(|x| x.tangent(p)), segs.get(i).and_then(|x| x.tangent(p))) else { - return Err(unsupported("degenerate loop edge")); - }; - let x = d0.cross(d1); - let lam = ((m * sb - m0 * sb0).cross(d1)).dot(x) / x.len2(); - let exact = (matches!(segs.get(ip), Some(Seg::Arc { .. })) || matches!(segs.get(i), Some(Seg::Arc { .. }))) - && t.dot(n * side) > 1.0 - 1e-9 - && t0.dot(n * side) > 1.0 - 1e-9; - if exact { - let (Some(prev), Some(cur)) = (segs.get(ip), segs.get(i)) else { return Err(unsupported("corner segments")) }; - pa.push( - offset_joint(prev, cur, n, if sides.is_some() { sb } else { r }).ok_or_else(|| too_large("the blend's offset walls do not meet"))?, - ); - if let Some(slot) = curved_joint.get_mut(i) { - *slot = true; - } - } else { - pa.push(p + m0 * sb0 + d0 * lam); - } - let e = seam_dir(i, p).ok_or_else(|| unsupported("a sharp corner without one straight seam"))?; - let (h0, h1) = (e.dot(t0), e.dot(t)); - if h0 < 1e-6 || h1 < 1e-6 || (sbw0 / h0 - sbw / h1).abs() > tol * 10.0 { - return Err(unsupported("a sharp corner whose walls meet the blend differently")); - } - pb.push(p + e * (sbw / h1)); - } - // Sharp joints between straight rim edges can extend beyond the old corner. - // Equal wall slopes reach this path instead of the corner builder, and must - // also reject an extension through the outer wall or another hole. - for (i, q) in pa.iter().enumerate() { - // Smooth arc transitions and open-run ends retain their existing checks. - if !mitre.get(i).copied().unwrap_or(false) { - continue; - } - let p = joint_point(i).ok_or_else(|| unsupported("degenerate loop joint"))?; - if !crate::blend::extension_fits(f, p, *q, size * 1e-7) { - return Err(too_large("the blend is larger than the neighbouring faces")); - } - } - // The offset arcs must not turn inside out; an arc of exactly the blend's radius shrinks - // to a point (a rounded corner rounded again: the blend there is a sphere). - let mut collapsed = vec![false; k.max(nj)]; - for (i, s) in segs.iter().enumerate() { - if let Seg::Arc { a, c, .. } = *s { - let toward = into(s, a).dot(c - a) > 0.0; - // An unequal chamfer's offset on the face; it never ends in a point (a cone's apex). - if sides.is_some() { - let reach = frame(i, a).map(|x| x.2).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; - if toward && a.dist(c) <= reach + tol * 10.0 { - return Err(too_large("the chamfer is larger than a corner radius")); - } - continue; - } - if toward && (a.dist(c) - r).abs() <= tol * 10.0 && !mitre.get(i).copied().unwrap_or(true) && !mitre.get(nxt(i)).copied().unwrap_or(true) - { - if let Some(x) = collapsed.get_mut(i) { - *x = true; - } - } else if toward && a.dist(c) <= r + tol { - return Err(too_large("the blend is larger than a corner radius")); - } - } - } - if collapsed.iter().all(|x| *x) { - return Err(too_large("the blend is larger than a corner radius")); - } - let mut va: Vec = pa.iter().map(|p| builder::vertex(p3(*p))).collect(); - // A collapsed piece starts and ends at one vertex. - for i in 0..k { - if collapsed.get(i).copied().unwrap_or(false) - && let Some(v) = va.get(i).cloned() - && let Some(slot) = va.get_mut(nxt(i)) - { - *slot = v; - } - } - // Model vertices at the joints (the second half of a circle starts at none). - let mut joint_vertex: Vec> = (0..k) - .map(|i| if i == 0 || owner.get(i) != owner.get(i - 1) { owner.get(i).and_then(|o| edges.get(*o)).map(|e| e.front().clone()) } else { None }) - .collect(); - if open { - joint_vertex.push(edges.last().map(|e| e.back().clone())); - } - let loop_ids: Vec = edges.iter().map(|e| e.id()).collect(); - let on_face = |e: &mt::Edge| f.edge_iter().any(|x| x.id() == e.id()); - // A blend as tall as its walls uses them up: each wall seam ends exactly where the - // wall-side rail would, at a vertex of the walls' far boundary, which becomes the rail. - let wall_end: Vec> = joint_vertex - .iter() - .zip(&pb) - .map(|(v, target)| { - let v = v.as_ref()?; - faces.iter().flat_map(|g| g.edge_iter()).find_map(|e| { - if loop_ids.contains(&e.id()) || on_face(&e) || !(e.front() == v || e.back() == v) || !matches!(e.curve(), mt::Curve::Line(_)) { - return None; - } - let other = if e.front() == v { e.back().clone() } else { e.front().clone() }; - (from_p3(other.point()).dist(*target) <= tol * 10.0).then_some(other) - }) - }) - .collect(); - let used_up = wall_end.iter().filter(|x| x.is_some()).count(); - if used_up > 0 && (used_up != nj || open) { - return Err(unsupported("the blend uses up only part of the walls")); - } - let walls_used_up = used_up > 0; - let vb: Vec = match walls_used_up { - true => wall_end.into_iter().flatten().collect(), - false => pb.iter().map(|p| builder::vertex(p3(*p))).collect(), - }; - let centre = |i: usize| centres.get(i).copied().unwrap_or_default(); - let profile_mid = |i: usize| { - let (Some(p), c) = (joint_point(i), centre(i)) else { return Vec3::ZERO }; - c + (p - c).normalized().unwrap_or(n) * r - }; - // Profiles at the joints (face side → wall side). - let mut profiles: Vec = Vec::with_capacity(nj); - for i in 0..nj { - let (Some(a), Some(b)) = (va.get(i), vb.get(i)) else { return Err(KernelError::Failed("joint".into())) }; - if curved_joint.get(i).copied().unwrap_or(false) { - let (Some(prev), Some(cur)) = (segs.get((i + k - 1) % k), segs.get(i)) else { return Err(unsupported("corner segments")) }; - let setbacks = match sides { - None => (r, r), - Some(_) => joint_point(i).and_then(|p| frame(i.min(k - 1), p)).map(|x| (x.2, x.3)).ok_or_else(|| unsupported("frame"))?, - }; - let curve = offset_profile(prev, cur, n, side, setbacks, round, (setbacks.0.min(setbacks.1) * 1e-7).max(1e-9))?; - profiles.push(mt::Edge::try_new(a, b, curve).map_err(|e| KernelError::Failed(format!("curved corner: {e}")))?); - continue; - } - if !round { - profiles.push(builder::line(a, b)); - continue; - } - if !mitre.get(i).copied().unwrap_or(false) { - profiles.push(builder::circle_arc(a, b, p3(profile_mid(i)))); - continue; - } - // Mitre: the cross-section circle of this edge's blend where it passes the face-side - // point, slid along the edge onto the mitre plane (an ellipse arc, on both blends). - let p = segs.get(i).map(|x| x.start()).unwrap_or_default(); - let d1 = segs.get(i).and_then(|x| x.tangent(p)).ok_or_else(|| unsupported("tangent"))?; - let (pa_i, pb_i) = (from_p3(a.point()), from_p3(b.point())); - let lam = (pa_i - p).dot(d1); - let (_, t, sb, _, _) = frame(i, p).ok_or_else(|| unsupported("frame"))?; - let cc = centre(i) + d1 * lam; - let q = p + t * sb + d1 * lam; - let mid = cc + ((pa_i - cc) + (q - cc)).normalized().unwrap_or(t) * r; - // q projects onto the wall rail at pb_i; fitting through pb_i before projection - // would distort the circular cross-section at mixed line/arc corners. - let arc = builder::circle_arc(&builder::vertex(p3(pa_i)), &builder::vertex(p3(q)), p3(mid)); - let nb = (pa_i - p).cross(pb_i - p).normalized().ok_or_else(|| unsupported("mitre plane"))?; - let den = d1.dot(nb); - if den.abs() < 1e-9 { - return Err(unsupported("mitre plane along the edge")); - } - // x ↦ x − d1 ((x − p)·nb) / (d1·nb), column-major. - let col = |j: usize| { - let ej = [Vec3::X, Vec3::Y, Vec3::Z][j]; - ej - d1 * (ej.dot(nb) / den) - }; - let (c0, c1, c2) = (col(0), col(1), col(2)); - let tr = d1 * (p.dot(nb) / den); - let mat = mt::Matrix4::new(c0.x, c0.y, c0.z, 0.0, c1.x, c1.y, c1.z, 0.0, c2.x, c2.y, c2.z, 0.0, tr.x, tr.y, tr.z, 1.0); - let mut curve = arc.curve(); - mt::Transformed::transform_by(&mut curve, mat); - profiles.push(mt::Edge::new(a, b, curve)); - } - let rail = |vs: &[mt::Vertex], i: usize, offset: &dyn Fn(Vec3, &Seg) -> Vec3| -> Option { - let s = segs.get(i)?; - if std::ptr::eq(vs, va.as_slice()) && collapsed.get(i).copied().unwrap_or(false) { - return None; - } - let (a, b) = (vs.get(i)?, vs.get(nxt(i))?); - Some(match *s { - Seg::Line { .. } => builder::line(a, b), - Seg::Arc { mid, .. } => builder::circle_arc(a, b, p3(offset(mid, s))), - }) - }; - let piece_of = |s: &Seg| segs.iter().position(|x| std::ptr::eq(x, s)).unwrap_or(0); - let face_off = |p: Vec3, s: &Seg| { - let i = piece_of(s); - frame(i, p).map(|(m, _, sb, _, _)| p + m * sb).unwrap_or(p) - }; - let wall_off = |p: Vec3, s: &Seg| { - let i = piece_of(s); - frame(i, p).map(|(_, t, _, sbw, _)| p + t * sbw).unwrap_or(p) - }; - let face_rails: Vec> = (0..k).map(|i| rail(&va, i, &face_off)).collect(); - if face_rails.iter().zip(&collapsed).any(|(r, c)| r.is_none() && !c) { - return Err(KernelError::Failed("rail".into())); - } - let wall_rails: Vec = if walls_used_up { - // Each piece's wall rail is the wall's far edge between the joints, where the offset - // rail lies (checked at the piece's middle). - (0..k) - .map(|i| -> Result { - let (Some(a), Some(b), Some(s), Some(wf)) = (vb.get(i), vb.get(nxt(i)), segs.get(i), walls.get(i)) else { - return Err(KernelError::Failed("rail".into())); - }; - let mid = match *s { - Seg::Line { a, b } => (a + b) * 0.5, - Seg::Arc { mid, .. } => mid, - }; - let want = wall_off(mid, s); - let g = faces.get(*wf).ok_or_else(|| KernelError::Failed("wall".into()))?; - g.edge_iter() - .find(|e| (e.front() == a && e.back() == b) || (e.front() == b && e.back() == a)) - .filter(|e| crate::blend::edge_mid(e).is_some_and(|m| m.dist(want) <= tol * 10.0)) - .map(|e| if e.front() == a { e.clone() } else { e.inverse() }) - .ok_or_else(|| unsupported("the blend uses up walls whose far edge is not where the blend ends")) - }) - .collect::>()? - } else { - (0..k).map(|i| rail(&vb, i, &wall_off)).collect::>().ok_or_else(|| KernelError::Failed("rail".into()))? - }; - // Seams between neighbouring walls at the joints get shorter. - // At a run's ends the face's next loop edges stop at the face-side point. - let mut seam_subst: HashMap = HashMap::new(); - let mut seam_ends: HashMap, Option)> = HashMap::new(); - for (i, v) in joint_vertex.iter().enumerate() { - let Some(v) = v else { continue }; - for g in faces { - for e in g.edge_iter() { - if loop_ids.contains(&e.id()) || !(e.front() == v || e.back() == v) { - continue; - } - // Once per edge and joint (an edge between both ends of a run is met twice). - if seam_ends.get(&e.id()).is_some_and(|x: &(mt::Edge, Option, Option)| { - (x.0.absolute_front() == v && x.1.is_some()) || (x.0.absolute_back() == v && x.2.is_some()) - }) { - continue; - } - let (fa, fb) = (e.absolute_front().clone(), e.absolute_back().clone()); - let other = if &fa == v { &fb } else { &fa }; - if !is_straight(&e, (size * 1e-5).max(1e-6)) { - return Err(unsupported("the wall seams must be straight")); - } - let face_side = on_face(&e); - // A used-up wall goes, seams and all. - if walls_used_up && !face_side { - continue; - } - let target = if face_side { pa.get(i) } else { pb.get(i) }.copied().unwrap_or_default(); - let along = (from_p3(other.point()) - from_p3(v.point())).dot(target - from_p3(v.point())); - let reach = (target - from_p3(v.point())).len2(); - if along <= reach + tol { - return Err(too_large(if face_side { "the blend is longer than the next edge" } else { "the blend is taller than the walls" })); - } - let nb = if face_side { va.get(i) } else { vb.get(i) }.ok_or_else(|| KernelError::Failed("joint".into()))?; - let slot = seam_ends.entry(e.id()).or_insert_with(|| (e.absolute_clone(), None, None)); - if &fa == v { - slot.1 = Some(nb.clone()); - } else { - slot.2 = Some(nb.clone()); - } - } - } - } - for (id, (e, a, b)) in seam_ends { - let a = a.unwrap_or_else(|| e.absolute_front().clone()); - let b = b.unwrap_or_else(|| e.absolute_back().clone()); - if from_p3(a.point()).dist(from_p3(b.point())) < tol * 10.0 { - return Err(too_large("the blend is longer than the next edge")); - } - seam_subst.insert(id, builder::line(&a, &b)); - } - // Rebuild faces. - let idx_of = |id: mt::EdgeID| loop_ids.iter().position(|x| *x == id); - let rebuild = |g: &mt::Face, rails: &[Option]| -> Result { - let mut wires = Vec::new(); - for w in g.absolute_boundaries() { - let mut es = Vec::new(); - for e in w.edge_iter() { - if let Some(i) = idx_of(e.id()) { - // Rails run in loop order; an edge used the other way takes them reversed. - let mine: Vec<&mt::Edge> = owner.iter().zip(rails).filter(|(o, _)| **o == i).filter_map(|(_, r)| r.as_ref()).collect(); - let same = edges.get(i).is_some_and(|le| le.orientation() == e.orientation()); - if same { - es.extend(mine.into_iter().cloned()); - } else { - es.extend(mine.into_iter().rev().map(|r| r.inverse())); - } - continue; - } - let ne = if let Some(s) = seam_subst.get(&e.id()) { - if e.front() == e.absolute_front() { s.clone() } else { s.inverse() } - } else { - e.clone() - }; - es.push(ne); - } - // A run's end: the face's edge and the wall's seam now stop at the two ends of the - // end profile, which closes the gap between them. - if open { - let mut fixed: Vec = Vec::with_capacity(es.len() + 2); - let m = es.len(); - for j in 0..m { - let (Some(cur), Some(next)) = (es.get(j), es.get((j + 1) % m)) else { continue }; - fixed.push(cur.clone()); - if cur.back() == next.front() { - continue; - } - for ji in [0, nj - 1] { - let (Some(a), Some(b), Some(pr)) = (va.get(ji), vb.get(ji), profiles.get(ji)) else { continue }; - if cur.back() == a && next.front() == b { - fixed.push(pr.clone()); - } else if cur.back() == b && next.front() == a { - fixed.push(pr.inverse()); - } - } - } - es = fixed; - } - wires.push(mt::Wire::from(es)); - } - crate::heal::absolute_face(g, wires).ok_or_else(|| KernelError::Failed("loop blend: a face could not be rebuilt".into())) - }; - let mut out: Vec = Vec::new(); - let mut rec = Rebuild::default(); - rec.pieces(&seam_subst); - for (gi, g) in faces.iter().enumerate() { - let rebuilt = if gi == fi { - rebuild(g, &face_rails)? - } else if walls.contains(&gi) { - if walls_used_up { - continue; - } - let wr: Vec> = wall_rails.iter().cloned().map(Some).collect(); - rebuild(g, &wr)? - } else if g.edge_iter().any(|e| seam_subst.contains_key(&e.id())) { - rebuild(g, &[])? - } else { - (*g).clone() - }; - rec.face(&rebuilt, g); - out.push(rebuilt); - } - // Blend faces. - use mt::{ParametricSurface3D, SearchNearestParameter}; - for i in 0..k { - let (Some(s), Some(pr), Some(pr_next), Some(fr), Some(wr)) = - (segs.get(i), profiles.get(i), profiles.get(nxt(i)), face_rails.get(i), wall_rails.get(i)) - else { - continue; - }; - let swept: mt::Shell = match *s { - Seg::Line { a, b } => { - // The cross-section at the start, swept along the whole edge and beyond (the - // face may reach past the edge's ends at a mitre). - let d = (b - a).normalized().ok_or_else(|| unsupported("degenerate loop edge"))?; - let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?; - let m = into(s, a); - let ext = size; - let back = d * -ext; - let (fa, wa) = (builder::vertex(p3(a + m * sb + back)), builder::vertex(p3(a + t * sbw + back))); - let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i) + back)) } else { builder::line(&fa, &wa) }; - vec![builder::tsweep(&base, v3(b - a + d * (2.0 * ext)))].into() - } - Seg::Arc { .. } if collapsed.get(i).copied().unwrap_or(false) => { - // A sphere about the profile's centre, its poles well away from the corner - // patch (a pole inside a face's corner confuses the meshing). - let c = centre(i); - let corners = [from_p3(pr.front().point()), from_p3(pr.back().point()), from_p3(pr_next.back().point())]; - let g = corners.iter().fold(Vec3::ZERO, |acc, q| acc + (*q - c).normalized().unwrap_or(Vec3::ZERO)); - let g = g.normalized().ok_or_else(|| unsupported("sphere corner"))?; - let w = g.any_perp(); - let (top, eq, bottom) = (builder::vertex(p3(c + w * r)), p3(c + g * r), builder::vertex(p3(c - w * r))); - let meridian = builder::circle_arc(&top, &bottom, eq); - builder::rsweep(&meridian, p3(c), v3(w), mt::Rad(std::f64::consts::TAU)) - } - Seg::Arc { c, axis, angle, .. } - if !curved_joint.get(i).copied().unwrap_or(false) && !curved_joint.get(nxt(i)).copied().unwrap_or(false) => - { - builder::rsweep(pr, p3(c), v3(axis), mt::Rad(angle)) - } - Seg::Arc { a, c, axis, angle, .. } => { - // Sweep a radial section, not the shared corner curve: the latter can be - // nonplanar and would change the round's radius all along this edge. - let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?; - let (fa, wa) = (builder::vertex(p3(a + into(s, a) * sb)), builder::vertex(p3(a + t * sbw))); - let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i))) } else { builder::line(&fa, &wa) }; - builder::rsweep(&base, p3(c), v3(axis), mt::Rad(angle)) - } - }; - let mut surf = swept.face_iter().next().map(|x| x.oriented_surface()).ok_or_else(|| KernelError::Failed("blend surface".into()))?; - // Outward: toward the profile centre on a concave loop, away from it on a convex one. - // An unequal chamfer's profile has no centre: its middle, away from the edge on a concave - // loop (where the chamfer fills) and toward it on a convex one. - let (c, mid) = (centre(i), profile_mid(i)); - let (mid, outward) = match (sides, joint_point(i)) { - (Some(_), Some(p)) => { - let m = (from_p3(pr.front().point()) + from_p3(pr.back().point())) * 0.5; - (m, (m - p) * side) - } - _ => (mid, (c - mid) * side), - }; - if let Some((u, v)) = surf.search_nearest_parameter(p3(mid), None, 100) { - let nn = surf.normal(u, v); - if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); - } - } - let w: mt::Wire = match fr { - Some(fr) => vec![fr.inverse(), pr.clone(), wr.clone(), pr_next.inverse()].into(), - None => vec![pr.clone(), wr.clone(), pr_next.inverse()].into(), - }; - let face = mt::Face::try_new(vec![w.clone()], surf.clone()).map_err(|e| KernelError::Failed(format!("blend face: {e}")))?; - // In place of the loop edge this piece runs along (a full circle's two halves both). - rec.blend(&face, owner.get(i).and_then(|o| edges.get(*o)).map(|e| e.id())); - out.push(face); - } - let mut shells = solid.boundaries().clone(); - if let Some(sh) = shells.get_mut(si) { - *sh = out.into(); - } - let solid = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("loop blend produced an invalid solid: {e}")))?; - Ok((solid, rec)) -} diff --git a/crates/kernel/src/matchsurf.rs b/crates/kernel/src/matchsurf.rs index 8134ea341..dbdee8a93 100644 --- a/crates/kernel/src/matchsurf.rs +++ b/crates/kernel/src/matchsurf.rs @@ -16,15 +16,16 @@ //! of the target meet, with shapes that part company, is a seam the target itself does not hold //! beyond that order, and no surface can be told to carry a condition the target has not got. -use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::Vec3; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self as b}; +use solidcraft_geom::brep::{eval::CurveEval, eval::SurfaceEval}; +use solidcraft_geom::prelude::*; -use crate::body::{Body, from_p3, p3}; +use crate::body::Body; use crate::bridge::{self, Continuity, Frame}; -use crate::record::Rebuild; -use crate::surfaces::surface_body; -use crate::{KernelError, Result, guard}; +use crate::history::{Change, EdgeProv, History}; +use crate::surfaces::Chain; +use crate::{KernelError, Result}; /// Stations a match reads along the seam and along the boundary it keeps. const STATIONS: usize = 33; @@ -61,27 +62,31 @@ const SUPPLY_BEND_REL: f64 = 1e-1; /// target's own shape along it up to `order` — position, tangent, curvature vector, and the /// change of that curvature vector along the direction the match leaves in. The boundary /// opposite keeps its place and the original surface's own frame, and the middle is shaped to -/// stay as close to the original surface as the conditions allow. +/// stay as close to the original surface as the conditions allow. Its history is over +/// `[body, target]`: the face is the body's face, modified; its edges are new. pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[Vec3], order: Continuity) -> Result { body.require_brep("match")?; target.require_brep("match")?; if !body.is_surface() { return Err(KernelError::Invalid("match rebuilds a surface body: this one is closed".into())); } - let face = face_near(body, faces)?; + let (record, target_record) = (body.record(), target.record()); + let face = face_near(record, faces, body.size() * 0.05 + 1e-6)?; + let original = Patch::of(record, face)?; let chain = bridge::chain(target, target_pick)?; - let near = nearest_side(&face, &chain)?; + let line = chain_polyline(target_record, &chain)?; + let near = nearest_side(&original, &line)?; let far = near.opposite(); - let far_edges = side_edges(&face, far, body.size() * 1e-6 + 1e-9)?; - let (mid_near, mid_far) = (chain_mid(&chain)?, Side::at(&face.surface(), &ranges(&face)?, far, 0.5)); + let far_edges = side_edges(record, face, &original, far, body.size() * 1e-6 + 1e-9)?; + let (mid_near, mid_far) = (chain_mid(&line)?, original.at(far, 0.5)?); let leave = (mid_far - mid_near) .normalized() .filter(|l| l.is_finite()) .ok_or_else(|| KernelError::Invalid("the far boundary sits on the picked chain: there is nothing to match".into()))?; // Which face of the target the match continues from, and how much of the requested order the // target itself holds along that chain. - let candidates = support_faces(target, &chain, leave)?; - let supply = supply_order(&candidates, &chain, leave, target.size())?; + let candidates = support_faces(target, &chain, &line, leave)?; + let supply = supply_order(target, &candidates, &chain, leave)?; if order.conditions() > supply.conditions() { return Err(KernelError::Invalid(format!( "the target's own surfaces part company at the picked edges: they hold only {} there, so a seam cannot hold {}", @@ -89,13 +94,13 @@ pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[ order.as_str() ))); } - let Some((target_face, _)) = candidates.first() else { + let Some(&(target_face, _)) = candidates.first() else { return Err(KernelError::Invalid("no face of the target holds the picked edges".into())); }; // The stations of the seam: what the target does there along the direction the match leaves // in, and what the far boundary does coming back the other way. - let mut near_frames = bridge::frames(target_face, &chain, leave, STATIONS)?; - let far_frames = bridge::frames(&face, &far_edges, leave * -1.0, STATIONS)?; + let mut near_frames = bridge::frames(target, target_face, &chain, leave, STATIONS)?; + let far_frames = bridge::frames(body, face, &far_edges, leave * -1.0, STATIONS)?; // The two chains are sampled from their own starts: turn one round when that pairs the // stations better (a match is built station to station). let direct: f64 = near_frames.iter().zip(&far_frames).map(|(a, b)| a.p.dist(b.p)).sum(); @@ -103,37 +108,36 @@ pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[ if reversed < direct { near_frames.reverse(); } - guard("surface match", || { - // The crown is the free knob: keep the one whose surface stays closest to the original. - let mut best: Option<(f64, mt::Face)> = None; - for crown_near in CROWNS { - for crown_far in CROWNS { - let made = bridge::bridge(&near_frames, &far_frames, [order, Continuity::G1], [crown_near, crown_far])?; - let Some(made) = made.solid.face_iter().next().cloned() else { - return Err(KernelError::Failed("match: the bridge made no face".into())); - }; - let stray = deviation(&made, &face)?; - if best.as_ref().is_none_or(|(b, _)| stray < *b) { - best = Some((stray, made)); - } + // The crown is the free knob: keep the one whose surface stays closest to the original. + let mut best: Option<(f64, Body)> = None; + for crown_near in CROWNS { + for crown_far in CROWNS { + let made = bridge::bridge(&near_frames, &far_frames, [order, Continuity::G1], [crown_near, crown_far])?; + let stray = deviation(&Patch::of(made.record(), 0)?, &original)?; + if best.as_ref().is_none_or(|(b, _)| stray < *b) { + best = Some((stray, made)); } } - let Some((_, made)) = best else { - return Err(KernelError::Failed("match: no crown built a surface".into())); - }; - let mut kept = made; - // The rebuilt face takes the target's own sense at the seam: the two surfaces then meet - // the same way round, which is what a stitch, a thicken or a display of the result reads. - let seam = chain_mid(&chain)?; - if let (Some((made_n, _)), Some((target_n, _))) = (normal_near(&kept, seam), normal_near(target_face, seam)) - && made_n.dot(target_n) < 0.0 - { - kept.invert(); - } - let mut rec = Rebuild::default(); - rec.face(&kept, &face); - Ok(crate::record::rebuilt_body(surface_body(vec![kept]), &[&body.solid, &target.solid], &rec)) - }) + } + let Some((_, made)) = best else { + return Err(KernelError::Failed("match: no crown built a surface".into())); + }; + // The rebuilt face takes the target's own sense at the seam: the two surfaces then meet the + // same way round, which is what a stitch, a thicken or a display of the result reads. + let seam = chain_mid(&line)?; + let made_record = made.record(); + let turn = match (Patch::of(made_record, 0)?.normal_near(seam), Patch::of(target_record, target_face)?.normal_near(seam)) { + (Some((m, _)), Some((t, _))) => m.dot(t) < 0.0, + _ => false, + }; + let kept = crate::surfaces::Parts::of(made_record, &[(0, turn)])?.canonical()?; + let sheet = crate::surfaces::surface_body(&kept.brep)?; + let history = History { + operands: 2, + faces: vec![crate::record::from_face(0, face, Change::Modified)], + edges: (0..sheet.edge_count()).map(|_| EdgeProv { faces: vec![0], origins: Vec::new() }).collect(), + }; + sheet.with_history(history, &[body, target]) } /// How well the rebuilt surface `made` meets `target` along the chain picked by `target_pick`: @@ -143,68 +147,61 @@ pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[ pub fn seam_continuity(made: &Body, target: &Body, target_pick: &[Vec3]) -> Result<(f64, f64, Continuity)> { made.require_brep("match")?; target.require_brep("match")?; + let (record, target_record) = (made.record(), target.record()); let chain = bridge::chain(target, target_pick)?; - let poly = chain_polyline(&chain)?; + let poly = chain_polyline(target_record, &chain)?; // The face whose boundary runs along the chain: the one nearest it, so that a body that has // not been matched yet — where the seam is still some way off — can be measured too. - let mid = chain_mid(&chain)?; - let face = made - .solid - .face_iter() - .filter_map(|f| face_distance(f, mid).map(|d| (d, f))) + let mid = chain_mid(&poly)?; + let face = (0..record.faces.len()) + .filter_map(|f| Patch::of(record, f).ok().and_then(|p| p.normal_near(mid).map(|(_, d)| (d, p)))) .min_by(|a, b| a.0.total_cmp(&b.0)) - .map(|(_, f)| f.clone()) + .map(|(_, p)| p) .ok_or_else(|| KernelError::Failed("match: the body has no faces".into()))?; - let near = nearest_side(&face, &chain)?; + let near = nearest_side(&face, &poly)?; let far = near.opposite(); - let ranges = ranges(&face)?; - let mid_far = Side::at(&face.surface(), &ranges, far, 0.5); - let leave = (mid_far - chain_mid(&chain)?) + let leave = (face.at(far, 0.5)? - mid) .normalized() .ok_or_else(|| KernelError::Invalid("the seam and the far boundary coincide: there is nothing to measure".into()))?; - let candidates = support_faces(target, &chain, leave)?; - let Some((target_face, _)) = candidates.first() else { + let candidates = support_faces(target, &chain, &poly, leave)?; + let Some(&(target_face, _)) = candidates.first() else { return Err(KernelError::Invalid("no face of the target holds the picked edges".into())); }; - let frames = bridge::frames(target_face, &chain, leave, STATIONS)?; + let target_patch = Patch::of(target_record, target_face)?; + let frames = bridge::frames(target, target_face, &chain, leave, STATIONS)?; let size = target.size(); - guard("surface match", || { - let surf = face.surface(); - let (mut gap, mut deg, mut curv, mut bend) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); - for i in 0..STATIONS { - let t = i as f64 / (STATIONS - 1) as f64; - let p = Side::at(&surf, &ranges, near, t); - gap = gap.max(chain_distance(&poly, p)); - // What the target says there, and what the rebuilt surface actually does there. - let Some(frame) = frames.iter().min_by(|a, b| a.p.dist(p).total_cmp(&b.p.dist(p))) else { - return Err(KernelError::Failed("match: the target has no frames".into())); - }; - let (_, t_made, bend_made, change_made) = seam_shape(&surf, &ranges, near, t)?; - if let Some((n_made, _)) = normal_near(&face, p) - && let Some((n_target, _)) = normal_near(target_face, p) - { - deg = deg.max(angle_deg(n_made, n_target)); - } - let scale = frame.bend.len().max(bend_made.len()).max(1.0 / size); - curv = curv.max((bend_made - frame.bend).len() / scale); - // The change of curvature is what a surface can hold: only its normal part counts, - // and it turns round with the direction of travel. - let change = if t_made.dot(frame.leave) < 0.0 { change_made * -1.0 } else { change_made }; - let scale3 = frame.bend_change.len().max(change.len()).max(scale / size); - bend = bend.max((change - frame.bend_change).len() / scale3); + let (mut gap, mut deg, mut curv, mut bend) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); + for i in 0..STATIONS { + let t = i as f64 / (STATIONS - 1) as f64; + let p = face.at(near, t)?; + gap = gap.max(chain_distance(&poly, p)); + // What the target says there, and what the rebuilt surface actually does there. + let Some(frame) = frames.iter().min_by(|a, b| a.p.dist(p).total_cmp(&b.p.dist(p))) else { + return Err(KernelError::Failed("match: the target has no frames".into())); + }; + let (_, t_made, bend_made, change_made) = face.seam_shape(near, t)?; + if let (Some((n_made, _)), Some((n_target, _))) = (face.normal_near(p), target_patch.normal_near(p)) { + deg = deg.max(angle_deg(n_made, n_target)); } - let mut order = Continuity::G0; - if deg <= G1_DEG { - order = Continuity::G1; - if curv <= G2_REL { - order = Continuity::G2; - if bend <= G3_REL { - order = Continuity::G3; - } + let scale = frame.bend.len().max(bend_made.len()).max(1.0 / size); + curv = curv.max((bend_made - frame.bend).len() / scale); + // The change of curvature is what a surface can hold: only its normal part counts, and it + // turns round with the direction of travel. + let change = if t_made.dot(frame.leave) < 0.0 { change_made * -1.0 } else { change_made }; + let scale3 = frame.bend_change.len().max(change.len()).max(scale / size); + bend = bend.max((change - frame.bend_change).len() / scale3); + } + let mut order = Continuity::G0; + if deg <= G1_DEG { + order = Continuity::G1; + if curv <= G2_REL { + order = Continuity::G2; + if bend <= G3_REL { + order = Continuity::G3; } } - Ok((gap, deg, order)) - }) + } + Ok((gap, deg, order)) } /// Which side of a face's parameter rectangle a boundary runs along: the match reads its face as @@ -251,58 +248,89 @@ impl Side { } /// The point at the normalized station `t` along the side. - fn at(surf: &mt::Surface, ranges: &[(f64, f64); 2], side: Side, t: f64) -> Vec3 { + fn at(surf: &SurfaceEval, ranges: &[(f64, f64); 2], side: Side, t: f64) -> Result { let (u, v) = (ranges[0], ranges[1]); let (fixed, along) = side.fixed_and_along(u, v); let t = along.0 + (along.1 - along.0) * t.clamp(0.0, 1.0); - if side.is_u() { from_p3(surf.subs(fixed, t)) } else { from_p3(surf.subs(t, fixed)) } + surf.point(if side.is_u() { [fixed, t] } else { [t, fixed] }).ok_or_else(|| KernelError::Failed("match: a side has no point there".into())) } } -/// The bounded parameter ranges of a face's surface. -fn ranges(face: &mt::Face) -> Result<[(f64, f64); 2]> { - let surf = face.surface(); - let (Some(u), Some(v)) = surf.try_range_tuple() else { - return Err(KernelError::Failed("match: the face's surface is unbounded".into())); - }; - Ok([u, v]) +/// A face read as a tensor patch: its record surface and its parameter box. +struct Patch { + surface: SurfaceEval, + ranges: [(f64, f64); 2], } -/// How far `p` is from the face's own surface. -fn face_distance(face: &mt::Face, p: Vec3) -> Option { - let surf = face.surface(); - let (u, v) = surf.search_nearest_parameter(p3(p), None, 100)?; - Some(from_p3(surf.subs(u, v)).dist(p)) +impl Patch { + fn of(r: &b::Brep, face: usize) -> Result { + let f = r.faces.get(face).ok_or_else(|| KernelError::Invalid(format!("no face {face}")))?; + let surface = SurfaceEval::new(f.parameters()).map_err(|e| KernelError::Failed(format!("match: face {face}: {e}")))?; + let [[u0, u1], [v0, v1]] = f.domain; + Ok(Patch { surface, ranges: [(u0, u1), (v0, v1)] }) + } + + fn at(&self, side: Side, t: f64) -> Result { + Side::at(&self.surface, &self.ranges, side, t) + } + + /// The surface's unit normal at the point nearest `p`, and how far `p` is from that point. + fn normal_near(&self, p: Vec3) -> Option<(Vec3, f64)> { + let uv = self.surface.project(p, None, f64::INFINITY)?; + let (q, su, sv) = self.surface.derivs(uv[0], uv[1])?; + Some((su.cross(sv).normalized()?, q.dist(p))) + } + + /// The parameters of the point nearest `p`. + fn parameters(&self, p: Vec3) -> Option<[f64; 2]> { + self.surface.project(p, None, f64::INFINITY) + } + + /// The shape of the surface along its cross direction at the station `t`, read inwards from + /// the boundary `near` over five one-sided samples: the point, the unit tangent, the + /// curvature vector and the change of that curvature. The same finite difference + /// [`crate::bridge::frames`] reads a support surface with, so that a rebuilt seam can be + /// compared with what it matched. + fn seam_shape(&self, near: Side, t: f64) -> Result<(Vec3, Vec3, Vec3, Vec3)> { + let ranges = self.ranges; + let (station, cross, at_start) = if near.is_u() { + (ranges[1].0 + (ranges[1].1 - ranges[1].0) * t, ranges[0], near == Side::U0) + } else { + (ranges[0].0 + (ranges[0].1 - ranges[0].0) * t, ranges[1], near == Side::V0) + }; + let span = (cross.1 - cross.0).abs().max(1e-12); + let h = span * 1e-3; + let c0 = if at_start { cross.0 } else { cross.1 }; + let sgn = if at_start { 1.0 } else { -1.0 }; + let at = |x: f64| self.surface.point(if near.is_u() { [x, station] } else { [station, x] }); + let q: Vec = + (0..5).map(|k| at(c0 + sgn * k as f64 * h)).collect::>().ok_or_else(|| KernelError::Failed("match: seam samples".into()))?; + let (Some(&q0), Some(&q1), Some(&q2), Some(&q3), Some(&q4)) = (q.first(), q.get(1), q.get(2), q.get(3), q.get(4)) else { + return Err(KernelError::Failed("match: seam samples".into())); + }; + let d1 = (q0 * -25.0 + q1 * 48.0 + q2 * -36.0 + q3 * 16.0 + q4 * -3.0) * (sgn / (12.0 * h)); + let d2 = (q0 * 35.0 + q1 * -104.0 + q2 * 114.0 + q3 * -56.0 + q4 * 11.0) * (1.0 / (12.0 * h * h)); + let d3 = (q0 * -5.0 + q1 * 18.0 + q2 * -24.0 + q3 * 14.0 + q4 * -3.0) * (sgn / (2.0 * h * h * h)); + let (t, bend, change) = shape(d1, d2, d3)?; + Ok((q0, t, bend, change)) + } } -/// The surface's unit normal at the point nearest `p`, and how far `p` is from that point. -fn normal_near(face: &mt::Face, p: Vec3) -> Option<(Vec3, f64)> { - let surf = face.surface(); - let (u, v) = surf.search_nearest_parameter(p3(p), None, 100)?; - let n = surf.normal(u, v); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - Some((n, from_p3(surf.subs(u, v)).dist(p))) -} - -/// The face of `body` the picks lie on: they must all pick the same one. A pick is a point the -/// caller clicked, so the face nearest it within the body's own pick tolerance is the face it -/// means (`crate::surfaces::edge_near` reads points the same way). -fn face_near(body: &Body, picks: &[Vec3]) -> Result { +/// The face of the record the picks lie on: they must all pick the same one, each within `reach` +/// of its surface (a pick is a point the caller clicked). +fn face_near(r: &b::Brep, picks: &[Vec3], reach: f64) -> Result { if picks.is_empty() || picks.len() > MAX_PICKS || picks.iter().any(|p| !p.is_finite()) { return Err(KernelError::Invalid(format!("pick 1 to {MAX_PICKS} points on the face to match"))); } - let tol = body.size() * 0.05 + 1e-6; - let mut found: Option = None; + let mut found: Option = None; for p in picks { - let hit = body - .solid - .face_iter() - .filter_map(|f| face_distance(f, *p).map(|d| (d, f))) + let hit = (0..r.faces.len()) + .filter_map(|f| Patch::of(r, f).ok().and_then(|x| x.normal_near(*p)).map(|(_, d)| (d, f))) .min_by(|a, b| a.0.total_cmp(&b.0)) - .filter(|(d, _)| *d <= tol) - .map(|(_, f)| f.clone()) + .filter(|(d, _)| *d <= reach) + .map(|(_, f)| f) .ok_or_else(|| KernelError::Invalid(format!("no face of the body passes through {p:?}")))?; - if found.as_ref().is_some_and(|f| f.id() != hit.id()) { + if found.is_some_and(|f| f != hit) { return Err(KernelError::Invalid("the picks are on different faces: match one face".into())); } found = Some(hit); @@ -310,28 +338,27 @@ fn face_near(body: &Body, picks: &[Vec3]) -> Result { found.ok_or_else(|| KernelError::Invalid("pick a point on the face to match".into())) } -/// A chain of edges as a polyline (each edge sampled), for lengths and distances. -fn chain_polyline(chain: &[mt::Edge]) -> Result> { +/// A chain of the record's edges as a polyline (each edge sampled the chain's way), for lengths +/// and distances. +fn chain_polyline(r: &b::Brep, chain: &Chain) -> Result> { if chain.is_empty() { return Err(KernelError::Invalid("the chain has no edges".into())); } let mut out = Vec::with_capacity(chain.len() * (PER_EDGE + 1)); - for e in chain { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - if !(t1 > t0) || ![t0, t1].into_iter().all(f64::is_finite) { - return Err(KernelError::Failed("match: an edge has no parameter range".into())); - } + for &(e, forward) in chain { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid("an edge reference".into()))?; + let c = CurveEval::new(edge.parameters()).map_err(|err| KernelError::Failed(format!("match: {err}")))?; + let [t0, t1] = edge.interval; + let (a, z) = if forward { (t0, t1) } else { (t1, t0) }; for k in 0..=PER_EDGE { - out.push(from_p3(c.subs(t0 + (t1 - t0) * k as f64 / PER_EDGE as f64))); + out.push(c.point(a + (z - a) * k as f64 / PER_EDGE as f64).ok_or_else(|| KernelError::Failed("match: an edge has no point".into()))?); } } Ok(out) } -/// The point at the middle of a chain, by length. -fn chain_mid(chain: &[mt::Edge]) -> Result { - let poly = chain_polyline(chain)?; +/// The point at the middle of a polyline, by length. +fn chain_mid(poly: &[Vec3]) -> Result { let mut cum = Vec::with_capacity(poly.len()); cum.push(0.0); for w in poly.windows(2) { @@ -345,10 +372,7 @@ fn chain_mid(chain: &[mt::Edge]) -> Result { } let half = total * 0.5; let hi = cum.partition_point(|x| *x < half).clamp(1, poly.len().saturating_sub(1)); - let (Some(a), Some(b)) = (poly.get(hi - 1), poly.get(hi)) else { - return Err(KernelError::Failed("match: chain".into())); - }; - let (Some(&lo), Some(&up)) = (cum.get(hi - 1), cum.get(hi)) else { + let (Some(a), Some(b), Some(&lo), Some(&up)) = (poly.get(hi - 1), poly.get(hi), cum.get(hi - 1), cum.get(hi)) else { return Err(KernelError::Failed("match: chain".into())); }; let span = up - lo; @@ -368,19 +392,15 @@ fn chain_distance(poly: &[Vec3], p: Vec3) -> f64 { best } -/// The side of the face's own parameter rectangle the picked chain sits nearest. -fn nearest_side(face: &mt::Face, chain: &[mt::Edge]) -> Result { - let surf = face.surface(); - let ranges = ranges(face)?; - let poly = chain_polyline(chain)?; +/// The side of the face's own parameter rectangle the picked chain (as a polyline) sits nearest. +fn nearest_side(face: &Patch, poly: &[Vec3]) -> Result { /// Samples of each side used to tell which one the chain runs along. const SAMPLES: usize = 17; let mut best: Option<(f64, Side)> = None; for side in Side::ALL { let mut total = 0.0; for k in 0..SAMPLES { - let t = k as f64 / (SAMPLES - 1) as f64; - total += chain_distance(&poly, Side::at(&surf, &ranges, side, t)); + total += chain_distance(poly, face.at(side, k as f64 / (SAMPLES - 1) as f64)?); } let mean = total / SAMPLES as f64; if best.is_none_or(|(b, _)| mean < b) { @@ -392,49 +412,48 @@ fn nearest_side(face: &mt::Face, chain: &[mt::Edge]) -> Result { /// The face's own edges that run along a side of its parameter rectangle, chained head to tail. /// A match keeps the far side's own edges, so they must be a chain that runs on. -fn side_edges(face: &mt::Face, side: Side, tol: f64) -> Result> { - let surf = face.surface(); - let ranges = ranges(face)?; - let (fixed, along) = side.fixed_and_along(ranges[0], ranges[1]); +fn side_edges(r: &b::Brep, face: usize, patch: &Patch, side: Side, tol: f64) -> Result { + let (fixed, along) = side.fixed_and_along(patch.ranges[0], patch.ranges[1]); let band = (along.1 - along.0).abs().max(1e-12) * 1e-3; - let mut pool: Vec = Vec::new(); - for e in face.edge_iter() { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let p = from_p3(c.subs(0.5 * (t0 + t1))); - let Some((u, v)) = surf.search_nearest_parameter(p3(p), None, 100) else { continue }; - if from_p3(surf.subs(u, v)).dist(p) > tol { - continue; - } - let got = if side.is_u() { u } else { v }; - if (got - fixed).abs() <= band { - pool.push(e.clone()); + let f = r.faces.get(face).ok_or_else(|| KernelError::Invalid(format!("no face {face}")))?; + let mut pool: Vec = Vec::new(); + for l in &f.loops { + let b::Loop::Edges { edges } = l else { continue }; + for u in edges { + let e = u.edge as usize; + let Some(edge) = r.edges.get(e) else { continue }; + let Ok(c) = CurveEval::new(edge.parameters()) else { continue }; + let Some(p) = c.point(0.5 * (edge.interval[0] + edge.interval[1])) else { continue }; + let Some(uv) = patch.parameters(p) else { continue }; + if patch.surface.point(uv).is_none_or(|q| q.dist(p) > tol) { + continue; + } + let got = if side.is_u() { uv[0] } else { uv[1] }; + if (got - fixed).abs() <= band && !pool.contains(&e) { + pool.push(e); + } } } if pool.is_empty() { return Err(KernelError::Invalid("the face has no edges along the boundary a match would keep".into())); } + let ends = |e: usize| r.edges.get(e).map(|x| x.vertices).unwrap_or([u32::MAX; 2]); let first = pool.remove(0); - let mut chain = vec![first]; - let mut end = match chain.first() { - Some(e) => e.back().clone(), - None => return Err(KernelError::Failed("match: chain".into())), - }; - while let Some(k) = pool.iter().position(|e| e.front().id() == end.id() || e.back().id() == end.id()) { + let mut chain: Chain = vec![(first, true)]; + let [mut start, mut end] = ends(first); + while let Some(k) = pool.iter().position(|e| ends(*e).contains(&end)) { let e = pool.remove(k); - let e = if e.front().id() == end.id() { e } else { e.inverse() }; - end = e.back().clone(); - chain.push(e); + let [a, z] = ends(e); + let forward = a == end; + end = if forward { z } else { a }; + chain.push((e, forward)); } - let mut start = match chain.first() { - Some(e) => e.front().clone(), - None => return Err(KernelError::Failed("match: chain".into())), - }; - while let Some(k) = pool.iter().position(|e| e.front().id() == start.id() || e.back().id() == start.id()) { + while let Some(k) = pool.iter().position(|e| ends(*e).contains(&start)) { let e = pool.remove(k); - let e = if e.back().id() == start.id() { e } else { e.inverse() }; - start = e.front().clone(); - chain.insert(0, e); + let [a, z] = ends(e); + let forward = z == start; + start = if forward { a } else { z }; + chain.insert(0, (e, forward)); } if !pool.is_empty() { return Err(KernelError::Invalid("the face's edges along that boundary do not run on from one another".into())); @@ -442,23 +461,26 @@ fn side_edges(face: &mt::Face, side: Side, tol: f64) -> Result> { Ok(chain) } -/// The faces of `target` that meet the chain and whose tangent plane holds the leave direction, -/// best first: the face a match continues from, and the ones it might have been read from. -fn support_faces(target: &Body, chain: &[mt::Edge], leave: Vec3) -> Result> { - let mid = chain_mid(chain)?; +/// The faces of `target` that bound every edge of the chain and whose tangent plane holds the +/// leave direction, best first: the face a match continues from, and the ones it might have been +/// read from. +fn support_faces(target: &Body, chain: &Chain, poly: &[Vec3], leave: Vec3) -> Result> { + let r = target.record(); + let mid = chain_mid(poly)?; let tol = target.size() * 1e-6 + 1e-9; - let mut out: Vec<(mt::Face, f64)> = Vec::new(); - for face in target.solid.face_iter() { - if !chain.iter().all(|e| face.edge_iter().any(|f| f.id() == e.id())) { + let bounds = |f: usize, e: usize| r.edges.get(e).is_some_and(|x| x.uses.iter().any(|u| u.face as usize == f)); + let mut out: Vec<(usize, f64)> = Vec::new(); + for f in 0..r.faces.len() { + if !chain.iter().all(|(e, _)| bounds(f, *e)) { continue; } - let Some((n, d)) = normal_near(face, mid) else { continue }; + let Some((n, d)) = Patch::of(r, f).ok().and_then(|p| p.normal_near(mid)) else { continue }; if d > tol { continue; } let score = (leave - n * leave.dot(n)).len(); if score.is_finite() && score >= 0.2 { - out.push((face.clone(), score)); + out.push((f, score)); } } if out.is_empty() { @@ -474,25 +496,29 @@ fn support_faces(target: &Body, chain: &[mt::Edge], leave: Vec3) -> Result Result { - let Some((first, best)) = candidates.first() else { +fn supply_order(target: &Body, candidates: &[(usize, f64)], chain: &Chain, leave: Vec3) -> Result { + let Some(&(first, best)) = candidates.first() else { return Err(KernelError::Invalid("no face of the target holds the picked edges".into())); }; - let keep: Vec<&mt::Face> = candidates.iter().filter(|(_, s)| *s >= 0.5 * best).map(|(f, _)| f).collect(); + let keep: Vec = candidates.iter().filter(|(_, s)| *s >= 0.5 * best).map(|(f, _)| *f).collect(); let mut order = Continuity::G3; if keep.len() < 2 { return Ok(order); } - let primary: Vec = bridge::frames(first, chain, leave, STATIONS)?; - for other in keep.iter().skip(1) { + let r = target.record(); + let size = target.size(); + let first_patch = Patch::of(r, first)?; + let primary: Vec = bridge::frames(target, first, chain, leave, STATIONS)?; + for &other in keep.iter().skip(1) { // A face that cannot be read along the whole chain says nothing here: the face the match // is built on is the one that must be able to supply it. - let Ok(other_frames) = bridge::frames(other, chain, leave, STATIONS) else { continue }; + let Ok(other_frames) = bridge::frames(target, other, chain, leave, STATIONS) else { continue }; + let other_patch = Patch::of(r, other)?; let mut worst_deg = 0.0f64; let mut worst = 0.0f64; let mut worst_change = 0.0f64; for (a, b) in primary.iter().zip(&other_frames) { - if let (Some((na, _)), Some((nb, _))) = (normal_near(first, a.p), normal_near(other, b.p)) { + if let (Some((na, _)), Some((nb, _))) = (first_patch.normal_near(a.p), other_patch.normal_near(b.p)) { worst_deg = worst_deg.max(angle_deg(na, nb)); } let scale = a.bend.len().max(b.bend.len()).max(1.0 / size); @@ -544,46 +570,18 @@ fn shape(d1: Vec3, d2: Vec3, d3: Vec3) -> Result<(Vec3, Vec3, Vec3)> { Ok((t, nn * (1.0 / (sigma * sigma)), change)) } -/// The shape of a face's surface along its cross direction at the station `t`, read inwards from -/// the boundary `near` over five one-sided samples: the point, the unit tangent, the curvature -/// vector and the change of that curvature. The same finite difference [`crate::bridge::frames`] -/// reads a support surface with, so that a rebuilt seam can be compared with what it matched. -fn seam_shape(surf: &mt::Surface, ranges: &[(f64, f64); 2], near: Side, t: f64) -> Result<(Vec3, Vec3, Vec3, Vec3)> { - let (station, cross, at_start) = if near.is_u() { - (ranges[1].0 + (ranges[1].1 - ranges[1].0) * t, ranges[0], near == Side::U0) - } else { - (ranges[0].0 + (ranges[0].1 - ranges[0].0) * t, ranges[1], near == Side::V0) - }; - let span = (cross.1 - cross.0).abs().max(1e-12); - let h = span * 1e-3; - let c0 = if at_start { cross.0 } else { cross.1 }; - let sgn = if at_start { 1.0 } else { -1.0 }; - let at = |x: f64| if near.is_u() { from_p3(surf.subs(x, station)) } else { from_p3(surf.subs(station, x)) }; - let q: Vec = (0..5).map(|k| at(c0 + sgn * k as f64 * h)).collect(); - let (Some(&q0), Some(&q1), Some(&q2), Some(&q3), Some(&q4)) = (q.first(), q.get(1), q.get(2), q.get(3), q.get(4)) else { - return Err(KernelError::Failed("match: seam samples".into())); - }; - let d1 = (q0 * -25.0 + q1 * 48.0 + q2 * -36.0 + q3 * 16.0 + q4 * -3.0) * (sgn / (12.0 * h)); - let d2 = (q0 * 35.0 + q1 * -104.0 + q2 * 114.0 + q3 * -56.0 + q4 * 11.0) * (1.0 / (12.0 * h * h)); - let d3 = (q0 * -5.0 + q1 * 18.0 + q2 * -24.0 + q3 * 14.0 + q4 * -3.0) * (sgn / (2.0 * h * h * h)); - let (t, bend, change) = shape(d1, d2, d3)?; - Ok((q0, t, bend, change)) -} - /// How far the rebuilt surface strays from the original one: the root mean square of the /// distances from a grid of its samples to the original surface. -fn deviation(made: &mt::Face, original: &mt::Face) -> Result { - let (surf, os) = (made.surface(), original.surface()); - let ranges = ranges(made)?; +fn deviation(made: &Patch, original: &Patch) -> Result { + let ranges = made.ranges; let mut sum = 0.0f64; let mut n = 0usize; for i in 0..GRID { for j in 0..GRID { let u = ranges[0].0 + (ranges[0].1 - ranges[0].0) * i as f64 / (GRID - 1) as f64; let v = ranges[1].0 + (ranges[1].1 - ranges[1].0) * j as f64 / (GRID - 1) as f64; - let q = from_p3(surf.subs(u, v)); - let Some((a, b)) = os.search_nearest_parameter(p3(q), None, 100) else { continue }; - let d = from_p3(os.subs(a, b)).dist(q); + let Some(q) = made.surface.point([u, v]) else { continue }; + let Some((_, d)) = original.normal_near(q) else { continue }; if d.is_finite() { sum += d * d; n += 1; diff --git a/crates/kernel/src/matchsurf_tests.rs b/crates/kernel/src/matchsurf_tests.rs index f99066be4..1d55e1de3 100644 --- a/crates/kernel/src/matchsurf_tests.rs +++ b/crates/kernel/src/matchsurf_tests.rs @@ -6,8 +6,7 @@ use super::*; use crate::bridge::{Continuity, Frame}; use crate::build::SEAM_ANGLE; use crate::{cylinder, stitch}; -use solidcraft_geom::Vec3; -use truck_modeling as mt; +use solidcore_record::Vec3; /// The radius of the cylinder a sheet is matched to, the radius the sheet starts at, its height, /// and how far round the cylinder the sheet runs. @@ -54,33 +53,31 @@ fn sheet_and_pick() -> (Body, [Vec3; 1]) { (cylinder_sheet(R_SHEET, SEAM_ANGLE, SEAM_ANGLE + SPAN, 9), [at(SEAM_ANGLE, R_SHEET, HEIGHT * 0.5)]) } -/// The middle of the edge of `body`'s first face nearest `p`. -fn edge_at(body: &Body, p: Vec3) -> mt::Edge { - let face = body.solid.face_iter().next().unwrap(); - let mut best: Option<(f64, mt::Edge)> = None; - for e in face.edge_iter() { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let m = from_p3(c.subs(0.5 * (t0 + t1))); +/// The edge of `body`'s first face whose middle is nearest `p`, as a one-edge chain. +fn edge_at(body: &Body, p: Vec3) -> Chain { + let r = body.record(); + let b::Loop::Edges { edges } = &r.faces[0].loops[0] else { panic!("an edge loop") }; + let mut best: Option<(f64, usize)> = None; + for u in edges { + let e = &r.edges[u.edge as usize]; + let m = CurveEval::new(e.parameters()).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap(); let d = m.dist(p); - if best.as_ref().is_none_or(|(b, _)| d < *b) { - best = Some((d, e.clone())); + if best.is_none_or(|(b, _)| d < b) { + best = Some((d, u.edge as usize)); } } - best.unwrap().1 + vec![(best.unwrap().1, true)] } /// How far the rebuilt face's far boundary lies from the original one, in mm: the far row of the /// rebuilt surface sampled at its own stations, against the original boundary edge's own points. fn far_drift(made: &Body, sheet: &Body, far_mid: Vec3) -> f64 { - let face = made.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let (Some((u0, u1)), Some((_, v1))) = surf.try_range_tuple() else { panic!("unbounded") }; - let edge = edge_at(sheet, far_mid); - let poly = chain_polyline(&[edge]).unwrap(); + let patch = Patch::of(made.record(), 0).unwrap(); + let ((u0, u1), (_, v1)) = (patch.ranges[0], patch.ranges[1]); + let poly = chain_polyline(sheet.record(), &edge_at(sheet, far_mid)).unwrap(); let mut worst = 0.0f64; for k in 0..=8 { - let p = from_p3(surf.subs(u0 + (u1 - u0) * k as f64 / 8.0, v1)); + let p = patch.surface.point([u0 + (u1 - u0) * k as f64 / 8.0, v1]).unwrap(); worst = worst.max(chain_distance(&poly, p)); } worst @@ -90,9 +87,7 @@ fn far_drift(made: &Body, sheet: &Body, far_mid: Vec3) -> f64 { /// point, the unit tangent, the curvature vector and the change of that curvature, read off the /// finished surface (never from the construction). fn seam_at(body: &Body, t: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let ranges = super::ranges(face).unwrap(); - super::seam_shape(&face.surface(), &ranges, Side::V0, t).unwrap() + Patch::of(body.record(), 0).unwrap().seam_shape(Side::V0, t).unwrap() } /// The stations a seam is measured at, as fractions of its length. @@ -127,8 +122,7 @@ fn a_g2_match_meets_a_cylinder_with_its_own_curvature() { println!("g2: far boundary drift {drift:e} mm"); assert!(drift < 1e-9, "the far boundary drifted {drift:e} mm"); // The interior stays near the original: the crowning that leaves it closest. - let (face, original) = (made.solid.face_iter().next().unwrap().clone(), sheet.solid.face_iter().next().unwrap().clone()); - let stray = deviation(&face, &original).unwrap(); + let stray = deviation(&Patch::of(made.record(), 0).unwrap(), &Patch::of(sheet.record(), 0).unwrap()).unwrap(); println!("g2: interior stray {stray:.6} mm rms"); // The seam moved 1 mm, so the face cannot be closer than that at the seam itself: over the // whole face the root mean square distance is well under half of it. @@ -209,7 +203,7 @@ fn a_target_that_jumps_in_curvature_supplies_only_g1() { } let plane = bridge::bridge(&a, &b, [Continuity::G2, Continuity::G2], [0.0, 0.0]).unwrap(); let joined = stitch(&[&wall, &plane], 1e-6).unwrap(); - assert_eq!(joined.solid.face_iter().count(), 2, "the two sheets sewed into one body"); + assert_eq!(joined.face_count(), 2, "the two sheets sewed into one body"); let picks = [at(SEAM_ANGLE, R_TARGET, 6.0), at(SEAM_ANGLE, R_TARGET, 24.0)]; let (sheet, pick) = sheet_and_pick(); // The seam is smooth enough to match, so G1 goes through; the curvature jumps there, so G2 diff --git a/crates/kernel/src/measure.rs b/crates/kernel/src/measure.rs index 71299aa7e..233aca3a1 100644 --- a/crates/kernel/src/measure.rs +++ b/crates/kernel/src/measure.rs @@ -1,5 +1,6 @@ use serde::Serialize; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Aabb3; use crate::Result; use crate::body::Body; @@ -20,64 +21,44 @@ pub struct BodyMeasure { /// Counts after merging split pieces of the same analytic surface/curve (comparable with /// systems that use periodic faces and edges). pub merged: TopoCounts, -} - -/// Per-face sums: area, 6 × signed volume and 24 × first moments (divergence theorem), taken -/// about `o` (the moments relative to it), and the sum of the area vectors (zero over a closed -/// surface). Over a closed surface the volume does not depend on `o`; over one that leaves a -/// gap, the gap is closed by a cone to `o`, so `o` near the body keeps that cone small. -fn face_sums(m: &Mesh, nf: usize, o: Vec3) -> Vec<(f64, f64, Vec3, Vec3)> { - let mut out = vec![(0.0, 0.0, Vec3::ZERO, Vec3::ZERO); nf]; - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - let (Some([a, b, c]), Some(slot)) = (m.tri(t), out.get_mut(*f as usize)) else { continue }; - let n = (b - a).cross(c - a) * 0.5; - let (a, b, c) = (a - o, b - o, c - o); - let d = a.dot(b.cross(c)); - slot.0 += n.len(); - slot.1 += d; - slot.2 += (a + b + c) * d; - slot.3 += n; - } - out -} - -/// Smallest radius of curvature along the mesh's edge polylines (straight edges ignored). -fn min_edge_radius(m: &Mesh) -> Option { - let mut best: Option = None; - for e in &m.edges { - for w in e.windows(3) { - let (Some(&a), Some(&b), Some(&c)) = (w.first(), w.get(1), w.get(2)) else { continue }; - let (ab, bc, ca) = (b - a, c - b, a - c); - let cross = ab.cross(bc).len(); - if !(cross > 1e-12 * ab.len() * bc.len()) { - continue; - } - let r = ab.len() * bc.len() * ca.len() / (2.0 * cross); - if r.is_finite() && r > 0.0 && best.is_none_or(|x| r < x) { - best = Some(r); - } - } - } - best + /// What volume, area and centre come from: `smlib` (exact, integrated on the surfaces) or + /// `mesh` (a mesh body's own triangles). + pub measured_by: &'static str, + /// Anything the measurement says about itself. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub notes: Vec, } /// Volume, area, centre and box of a body, as [`measure`] works them out, without the topology -/// counts (and the tessellation they take). -#[derive(Clone, Copy, Debug, Serialize)] +/// counts. +#[derive(Clone, Debug, Serialize)] pub struct MassMeasure { pub volume: f64, pub area: f64, pub centroid: Vec3, pub bbox: Aabb3, + /// As [`BodyMeasure::measured_by`]. + pub measured_by: &'static str, + /// As [`BodyMeasure::notes`]. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub notes: Vec, } -/// Measure a body from a fine tessellation (chord tolerance 5e-5 of the body size, finer for -/// small radii down to 5e-6). Faces whose fine tessellation disagrees with a coarse one (a -/// meshing failure) use the coarse result. +/// The relative accuracy SMLib integrates at: the finest the C API takes +/// ([`solidcraft_smlib::MEASURE_ACCURACY`], 1e-8). `smlib_brep_mass_properties` calls the +/// kernel's integration directly because SmApiBrepComputeMassProperties clamps to [1e-4, 1e-1], +/// which leaves curved faces off by 1e-5 to 1e-3; asking 1e-4 here threw that away. +const ACCURACY: f64 = solidcraft_smlib::MEASURE_ACCURACY; + +/// Measure a body. A B-rep body's volume, area and centre are SMLib's, integrated on its exact +/// surfaces over its material regions (a sheet's: its faces' area and their centre, volume 0), +/// and its box is SMLib's exact box; a body SMLib cannot measure is an error. A mesh body is +/// measured from its triangles, exactly. pub fn measure(b: &Body) -> Result { + let _span = solidcraft_profile::span("kernel", "measure"); if let Some((pos, tris)) = b.triangle_mesh() { // Exact for a mesh body; topology counts are facets, sides and vertices. - let m = b.tessellate(1.0)?; + let m = b.mesh(&crate::MeshTolerance::chord(1.0))?; let mm = m.measure(); let edges = b.mesh.as_ref().map(|m| m.edge_count()).unwrap_or(0); let merged = @@ -92,13 +73,12 @@ pub fn measure(b: &Body) -> Result { vertices: pos.len(), shells: 1, merged, + measured_by: "mesh", + notes: Vec::new(), }); } - let (m, topo) = mass(b, true)?; - let topo = match topo { - Some(t) => t, - None => b.tessellate((b.size() * 1e-3).max(1e-3))?, - }; + let m = measure_mass(b)?; + let topo = b.mesh(&crate::MeshTolerance::chord((b.size() * 1e-3).max(1e-3)))?; Ok(BodyMeasure { volume: m.volume, area: m.area, @@ -109,96 +89,34 @@ pub fn measure(b: &Body) -> Result { vertices: b.vertex_count(), shells: b.shell_count(), merged: merged_topology(b, &topo)?, + measured_by: m.measured_by, + notes: m.notes, }) } -/// [`measure`]'s volume, area, centre and box alone: the same numbers, a tessellation fewer -/// (for callers that need no topology counts, such as an interference check). +/// [`measure`]'s volume, area, centre and box alone (for callers that need no topology counts, +/// such as an interference check). pub fn measure_mass(b: &Body) -> Result { + let _span = solidcraft_profile::span("kernel", "measure_mass"); if b.triangle_mesh().is_some() { let m = measure(b)?; - return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox }); + return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox, measured_by: m.measured_by, notes: m.notes }); } - Ok(mass(b, false)?.0) -} - -/// The mass properties of a B-rep body from three tessellations: a coarse one (which sets how -/// fine the others go), then a fine and a medium one at once on desktop (one after the other -/// in the browser). With `topology`, also the coarse unrefined mesh the topology counts take, -/// made alongside them. -fn mass(b: &Body, topology: bool) -> Result<(MassMeasure, Option)> { - let size = b.size(); - let coarse_tol = (size * 1e-3).max(1e-3); - let coarse = b.tessellate_with(coarse_tol, true)?; - // Chord error relative to a radius sets the volume error: keep it near 3e-4 of the - // smallest radius (thin tubes, small fillets). - let tight = min_edge_radius(&coarse).map(|r| r * 3e-4).unwrap_or(f64::INFINITY); - let fine_tol = (size * 5e-5).min(tight).max(size * 5e-6).max(1e-4); - let mut jobs = vec![(fine_tol, true), ((fine_tol * 5.0).max(2e-4), true)]; - if topology { - jobs.push((coarse_tol, false)); - } - // Independent tessellations of one body: each on its own thread, the calling thread's - // profile counting their wall time once as tessellation. Not from inside a worker pool: a - // pool thread blocked on threads of its own could leave their meshing (which runs on the - // shared pool) without a worker. - #[cfg(not(target_arch = "wasm32"))] - let threads = if rayon::current_thread_index().is_none() { jobs.len() } else { 1 }; - #[cfg(target_arch = "wasm32")] - let threads = 1; - let made = crate::profile::timed(crate::profile::Kind::Tessellate, || { - crate::par::map_on_threads(&jobs, threads, |&(tol, refine)| b.tessellate_with(tol, refine)) - }); - let mut made = made.into_iter().map(|m| m.unwrap_or_else(|| Err(crate::KernelError::Internal("tessellation failed".into())))); - let missing = || crate::KernelError::Internal("tessellation missing".into()); - let fine = made.next().ok_or_else(missing)??; - let medium = made.next().ok_or_else(missing)??; - let topo = match made.next() { - Some(m) => Some(m?), - None => None, - }; - let nf = b.face_count(); - // About the box's centre when the meshes leave only a crack: see `face_sums`. A body that is - // open on purpose (a surface, or a cup whose lid is still a separate sheet) has no volume of - // its own; it keeps the origin, so such bodies still compare with each other when the centre - // of their boxes moves (a crowned lid rises, the open cup under it doesn't change). - let (surface, gap) = face_sums(&fine, nf, Vec3::ZERO).iter().fold((0.0, Vec3::ZERO), |s, f| (s.0 + f.0, s.1 + f.3)); - let o = Some(fine.bounds().center()).filter(|c| c.is_finite() && gap.len() <= 0.01 * surface).unwrap_or(Vec3::ZERO); - let (sf, sm, sc) = (face_sums(&fine, nf, o), face_sums(&medium, nf, o), face_sums(&coarse, nf, o)); - let close = |x: f64, y: f64| (x - y).abs() <= 0.01 * x.abs().max(y.abs()) + 1e-9; - let (mut area, mut v6, mut mom) = (0.0, 0.0, Vec3::ZERO); - for ((f, m), c) in sf.iter().zip(&sm).zip(&sc) { - // Trust the finest tessellation that agrees with the next coarser one. - let pick = if close(f.0, m.0) { - f - } else if close(m.0, c.0) { - m - } else { - f - }; - area += pick.0; - v6 += pick.1; - mom += pick.2; - } - // The moments back about the origin. A gap the meshes leave (a crack where a trimmed face - // meets a hole cut into it) is closed by a cone to the box's centre, which keeps it small - // (a crack of 0.3 mm² moved a part ring's volume by 7 % about the origin 1000 mm away; about - // the centre, by 0.1 %). Every body is measured by the same meshes this way, so a body and the - // pieces a boolean cuts it into add up: a closed display plan measured instead would mesh - // some faces more coarsely than the sums do and break that. - let mom = o * (4.0 * v6) + mom; - let volume = v6 / 6.0; - let centroid = if v6.abs() > 1e-12 { mom / (4.0 * v6) } else { fine.bounds().center() }; - Ok((MassMeasure { volume, area, centroid, bbox: coarse.bounds().union(&fine.bounds()) }, topo)) + let m = crate::guard("SMLib mass properties", || { + b.smlib()?.mass_properties(ACCURACY).map_err(|e| crate::KernelError::smlib("SMLib mass properties", e)) + })?; + let [x, y, z] = m.centroid; + Ok(MassMeasure { volume: m.volume, area: m.area, centroid: Vec3::new(x, y, z), bbox: b.exact_bounds()?, measured_by: "smlib", notes: Vec::new() }) } #[cfg(test)] mod tests { use super::*; use crate::{BoolOp, boolean, cylinder, torus}; + use solidcraft_geom::prelude::*; - /// The mass properties alone are [`measure`]'s, to the bit, with the tessellations made at - /// once; and on a curved intersection they are the textbook ones. + /// The mass properties alone are [`measure`]'s, to the bit; and on a curved intersection + /// they are the textbook ones. #[test] fn mass_alone_is_the_full_measure() { let ring = torus(Vec3::ZERO, 10.0, 2.0).unwrap(); @@ -217,69 +135,13 @@ mod tests { assert!(measure(&ring).unwrap().merged.faces > 0); } - /// A 10 mm cube at `at`, each side in n × n squares of two triangles, one face per side; - /// without its first `open` triangles. - fn cube(at: Vec3, n: usize, open: usize) -> Mesh { - let mut m = Mesh::default(); - let s = 10.0; - for axis in 0..3 { - for side in [0.0, 1.0] { - for i in 0..n { - for j in 0..n { - let corner = |a: usize, b: usize| { - let mut c = [0.0; 3]; - c[axis] = side * s; - c[(axis + 1) % 3] = a as f64 * s / n as f64; - c[(axis + 2) % 3] = b as f64 * s / n as f64; - at + Vec3::new(c[0], c[1], c[2]) - }; - let k = m.positions.len() as u32; - m.positions.extend([corner(i, j), corner(i + 1, j), corner(i + 1, j + 1), corner(i, j + 1)]); - m.triangles.extend(if side > 0.0 { [[k, k + 1, k + 2], [k, k + 2, k + 3]] } else { [[k, k + 2, k + 1], [k, k + 3, k + 2]] }); - m.tri_face.extend([(2 * axis) as u32 + side as u32; 2]); - } - } - } - } - m.triangles.drain(..open); - m.tri_face.drain(..open); - m - } - - /// The summed per-face sums of `m` about `o`, with the moments about the origin (as - /// `measure` passes them on). - fn sums(m: &Mesh, o: Vec3) -> (f64, f64, Vec3, Vec3) { - let (area, v6, mom, normal) = - face_sums(m, 6, o).iter().fold((0.0, 0.0, Vec3::ZERO, Vec3::ZERO), |s, f| (s.0 + f.0, s.1 + f.1, s.2 + f.2, s.3 + f.3)); - (area, v6, o * (4.0 * v6) + mom, normal) - } - /// A cube 1000 mm from the origin with one 0.5 mm² facet left out: about the box's centre /// the sums miss a cone of that facet to the centre (0.08 %), where about the origin they are /// 17 % over. Closed, it measures the same about either. - #[test] - fn a_mesh_left_open_is_measured_about_its_centre() { - let at = Vec3::new(1000.0, 1000.0, 1000.0); - let (closed, open) = (cube(at, 10, 0), cube(at, 10, 1)); - let centre = at + Vec3::new(5.0, 5.0, 5.0); - for o in [Vec3::ZERO, centre] { - let (area, v6, mom, normal) = sums(&closed, o); - assert!((area - 600.0).abs() < 1e-9 && (v6 / 6.0 - 1000.0).abs() < 1e-6 && normal.len() < 1e-9); - assert!((mom / (4.0 * v6) - centre).len() < 1e-6 * at.len(), "{o:?}"); - } - let (_, v6_origin, _, normal) = sums(&open, Vec3::ZERO); - assert!((normal.len() - 0.5).abs() < 1e-9); - // The facet faces the origin: leaving it out adds its cone to the origin, 167 mm³. - assert!((v6_origin / 6.0 - (1000.0 + 0.5 * 1000.0 / 3.0)).abs() < 1e-3, "{}", v6_origin / 6.0); - let (_, v6, mom, _) = sums(&open, centre); - assert!((v6 / 6.0 - (1000.0 - 0.5 * 5.0 / 3.0)).abs() < 1e-6, "{}", v6 / 6.0); - assert!((mom / (4.0 * v6) - centre).len() < 0.01, "{:?}", mom / (4.0 * v6)); - } - // A body's measured volume does not depend on where it sits: the same revolved ring of cones // and cylinders, moved far from the origin, measures what it measures at the origin. use crate::{revolve, transform}; - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; use std::f64::consts::{PI, TAU}; /// Ring cross-section in (radius, height): cones top and bottom, cylinders inside and out. diff --git a/crates/kernel/src/mesh_convert.rs b/crates/kernel/src/mesh_convert.rs index ebe19af92..862bdb270 100644 --- a/crates/kernel/src/mesh_convert.rs +++ b/crates/kernel/src/mesh_convert.rs @@ -1,9 +1,10 @@ //! Conservative reconstruction of constant-section mechanical mesh parts. //! Geometry is inferred from closed, manifold input, never from a display mesh. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::{Body, KernelError, Result}; @@ -49,6 +50,7 @@ pub fn convert_prismatic_mesh(body: &Body, tolerance: f64) -> Result { return Err(invalid("triangle refers to a missing vertex")); }; let cross = (*pb - *pa).cross(*pc - *pa); + // `weld` dropped the triangles of no area, so none is left here. let Some(mut n) = cross.normalized() else { return Err(invalid("degenerate triangle")) }; for (a, b) in [(a, b), (b, c), (c, a)] { let entry = edges.entry((a.min(b), a.max(b))).or_default(); @@ -126,17 +128,39 @@ fn weld(mesh: &crate::meshbody::TriMesh, tolerance: f64) -> Result { }; remap.push(i); } - let triangles = mesh - .triangles - .iter() - .map(|t| { - let (Some(&a), Some(&b), Some(&c)) = (remap.get(t[0] as usize), remap.get(t[1] as usize), remap.get(t[2] as usize)) else { - return Err(invalid("missing triangle vertex")); - }; - Ok([a, b, c]) - }) - .collect::>>()?; - crate::mesh_body(&positions, &triangles) + // A triangle of no area (its corners on one line, or welded into one another) adds no + // surface, so it is dropped rather than refused (#4561); the closed-manifold check that + // follows still refuses a mesh that needed it to close. Only the vertices the kept triangles + // use stay, so a dropped triangle's corner cannot widen the part's extent. + let mut used: Vec> = vec![None; positions.len()]; + let mut kept_positions: Vec = Vec::new(); + let mut triangles = Vec::with_capacity(mesh.triangles.len()); + for t in &mesh.triangles { + let (Some(&a), Some(&b), Some(&c)) = (remap.get(t[0] as usize), remap.get(t[1] as usize), remap.get(t[2] as usize)) else { + return Err(invalid("missing triangle vertex")); + }; + let (Some(&pa), Some(&pb), Some(&pc)) = (positions.get(a as usize), positions.get(b as usize), positions.get(c as usize)) else { + return Err(invalid("missing triangle vertex")); + }; + if (pb - pa).cross(pc - pa).normalized().is_none() { + continue; + } + let mut keep = |i: u32| -> Result { + let slot = used.get_mut(i as usize).ok_or_else(|| invalid("missing triangle vertex"))?; + if let Some(k) = *slot { + return Ok(k); + } + let k = u32::try_from(kept_positions.len()).map_err(|_| invalid("too many vertices"))?; + kept_positions.push(positions.get(i as usize).copied().ok_or_else(|| invalid("missing triangle vertex"))?); + *slot = Some(k); + Ok(k) + }; + triangles.push([keep(a)?, keep(b)?, keep(c)?]); + } + if triangles.is_empty() { + return Err(invalid("the mesh has no triangle of any area")); + } + crate::mesh_body(&kept_positions, &triangles) } fn extrusion(mesh: &crate::meshbody::TriMesh, axis: Vec3, tolerance: f64) -> Result> { @@ -237,7 +261,7 @@ fn extrusion(mesh: &crate::meshbody::TriMesh, axis: Vec3, tolerance: f64) -> Res } let p = plane.to_local(*p); if !boundary_segments.iter().any(|&(a, b)| { - solidcraft_geom::Seg2::Line { a, b }.point_at(solidcraft_geom::Seg2::Line { a, b }.closest_param(p)).dist(p) <= epsilon * 3. + solidcore_record::Seg2::Line { a, b }.point_at(solidcore_record::Seg2::Line { a, b }.closest_param(p)).dist(p) <= epsilon * 3. }) { return Ok(None); } @@ -388,7 +412,7 @@ fn fit_loop(points: &[Vec2], tolerance: f64, epsilon: f64) -> Loop2 { } let remove = (0..n).find(|&i| { let (Some(a), Some(b), Some(c)) = (points.get((i + n - 1) % n), points.get(i), points.get((i + 1) % n)) else { return false }; - let edge = solidcraft_geom::Seg2::Line { a: *a, b: *c }; + let edge = solidcore_record::Seg2::Line { a: *a, b: *c }; edge.point_at(edge.closest_param(*b)).dist(*b) <= linear_tolerance }); let Some(index) = remove else { break }; @@ -402,7 +426,7 @@ mod tests { use super::*; fn mesh_of(body: &Body) -> Body { - let mesh = body.tessellate(0.005).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.005)).unwrap(); crate::mesh_body(&mesh.positions, &mesh.triangles).unwrap() } @@ -425,7 +449,7 @@ mod tests { assert!(!converted.is_mesh()); assert!(converted.validity().is_empty()); let expected = (1000. - std::f64::consts::PI * 16.) * 15.; - let fine_volume = |body: &Body| body.tessellate_with(1e-5, true).unwrap().measure().volume; + let fine_volume = |body: &Body| body.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap().measure().volume; assert!((fine_volume(&converted) - expected).abs() < 0.02); assert!((crate::measure(&converted).unwrap().volume - crate::measure(&source).unwrap().volume).abs() < 1e-7); assert_eq!(crate::measure(&converted).unwrap().merged.face_types.get("cylinder"), Some(&1)); @@ -455,7 +479,14 @@ mod tests { }) .collect(); assert_eq!(fit_loop(&points, 0.001, 1e-6).segs.len(), 16); - assert_eq!(fit_loop(&points, 0.2, 1e-6).segs.len(), 2); + assert_exact_circle(&fit_loop(&points, 0.2, 1e-6), Vec2::ZERO, 10.); + } + + /// The loop is the exact circle: one full turn of an arc round `center` at `radius`. + fn assert_exact_circle(fitted: &Loop2, center: Vec2, radius: f64) { + let [solidcore_record::Seg2::Arc { center: c, radius: r, sweep, .. }] = fitted.segs.as_slice() else { panic!("not one arc: {fitted:?}") }; + assert!(c.dist(center) < 1e-9 && (r - radius).abs() < 1e-9, "centre {c:?}, radius {r}"); + assert!((sweep.abs() - std::f64::consts::TAU).abs() < 1e-9, "sweep {sweep}"); } #[test] @@ -475,6 +506,30 @@ mod tests { } } + /// #4561: a closed box mesh with one extra triangle of no area along its bottom front edge + /// ((0,0,0), (10,0,0), (20,0,0)) converts to the box: the triangle adds no surface and is + /// dropped, its middle corner with it. V = 20 * 10 * 5 = 1000, six faces. + #[test] + fn a_zero_area_triangle_is_dropped() { + let source = crate::box_solid(Vec3::ZERO, Vec3::new(20., 10., 5.)).unwrap(); + let mesh = source.mesh(&crate::MeshTolerance::chord(0.005)).unwrap(); + let mut positions = mesh.positions.clone(); + let mut triangles = mesh.triangles.clone(); + let at = |ps: &[Vec3], p: Vec3| ps.iter().position(|q| q.dist(p) < 1e-9).and_then(|i| u32::try_from(i).ok()).unwrap(); + let (a, b) = (at(&positions, Vec3::ZERO), at(&positions, Vec3::new(20., 0., 0.))); + positions.push(Vec3::new(10., 0., 0.)); + let m = u32::try_from(positions.len() - 1).unwrap(); + triangles.push([a, m, b]); + let body = crate::mesh_body(&positions, &triangles).unwrap(); + let result = convert_prismatic_mesh(&body, 0.01).unwrap(); + assert_eq!(result.faces(0.01).unwrap().len(), 6); + assert!((crate::measure(&result).unwrap().volume - 1000.).abs() < 1e-6); + // A mesh of nothing but a triangle of no area has nothing left to convert. + let sliver = crate::mesh_body(&[Vec3::ZERO, Vec3::X, Vec3::new(2., 0., 0.)], &[[0, 1, 2]]).unwrap(); + let refused = convert_prismatic_mesh(&sliver, 0.05).unwrap_err(); + assert!(refused.to_string().contains("no triangle of any area"), "{refused}"); + } + #[test] fn a_mesh_over_the_budget_says_how_big_it_is_and_what_converts() { // #346: a freeform mesh just over the limit (a strip of 50001 triangles) is refused with @@ -502,7 +557,7 @@ mod tests { .collect(); let inner = Loop2::polygon(&points); let fitted = fit_loop(&points, 0.05, 1e-6); - assert_eq!(fitted.segs.len(), 2); + assert_exact_circle(&fitted, Vec2::ZERO, 1.02); assert!(certify_nesting(&[outer.clone(), inner], &[outer, fitted], 1e-6, 3.).is_err()); } diff --git a/crates/kernel/src/mesh_memo_tests.rs b/crates/kernel/src/mesh_memo_tests.rs index 915b1dcaf..adef8c548 100644 --- a/crates/kernel/src/mesh_memo_tests.rs +++ b/crates/kernel/src/mesh_memo_tests.rs @@ -14,8 +14,9 @@ fn plate() -> Body { plate } -/// Regions cut from a body that keeps its meshes come out as from the body itself, to the bit, -/// and the body is meshed once for all of them. +/// Regions cut from a body that keeps its meshes come out as from the body itself, to the bit. +/// SMLib's booleans read the exact record and mesh neither operand, so they leave the memo +/// empty; the body's own meshing then fills it once per tolerance and reuses it. #[test] fn regions_cut_from_a_body_keeping_its_meshes_are_unchanged() { let plate = plate(); @@ -35,11 +36,11 @@ fn regions_cut_from_a_body_keeping_its_meshes_are_unchanged() { ); } let memo = kept.meshes.as_ref().unwrap(); - assert_eq!(memo.shells.lock().unwrap().len(), 1, "one tolerance, one meshing"); - assert!(!memo.made.lock().unwrap().is_empty()); + assert_eq!(memo.made.lock().unwrap().len(), 0, "a boolean meshes neither operand"); // A mesh from the memo is the mesh made afresh. - let (a, b) = (kept.tessellate_with(0.05, true).unwrap(), plate.tessellate_with(0.05, true).unwrap()); - let (a2, _) = (kept.tessellate_with(0.05, true).unwrap(), ()); + let (a, b) = (kept.mesh(&crate::MeshTolerance::chord(0.05)).unwrap(), plate.mesh(&crate::MeshTolerance::chord(0.05)).unwrap()); + let (a2, _) = (kept.mesh(&crate::MeshTolerance::chord(0.05)).unwrap(), ()); + assert_eq!(memo.made.lock().unwrap().len(), 1, "one tolerance, one meshing"); for m in [&a, &a2] { assert_eq!(m.triangles, b.triangles); assert!( @@ -57,9 +58,34 @@ fn a_copy_with_another_solid_makes_its_own_meshes() { let kept = plate().keeping_meshes(); let other = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); let mut swapped = kept.clone(); - swapped.solid = other.solid.clone(); - let _ = kept.tessellate_with(0.5, true).unwrap(); - let m = swapped.tessellate_with(0.5, true).unwrap(); - assert_eq!(m.triangles.len(), other.tessellate_with(0.5, true).unwrap().triangles.len()); - assert!(swapped.boolean_meshes(0.01).is_none()); + swapped.record = other.record.clone(); + swapped.smlib = other.smlib.clone(); + let _ = kept.mesh(&crate::MeshTolerance::chord(0.5)).unwrap(); + let m = swapped.mesh(&crate::MeshTolerance::chord(0.5)).unwrap(); + assert_eq!(m.triangles.len(), other.mesh(&crate::MeshTolerance::chord(0.5)).unwrap().triangles.len()); +} + +/// A placed copy that shows its original's display is planned as the original, moved: the same +/// triangles on every face, its points the original's placed (so within the original's chord of +/// the copy's surfaces), and the original planned once for every copy. +#[test] +fn a_placed_copy_is_planned_as_its_original_moved() { + let part = plate(); + let share = DisplayShare::new(part.clone()); + let (angle, shift) = (0.7f64, Vec3::new(50.0, -20.0, 5.0)); + let (c, s) = (angle.cos(), angle.sin()); + let t = [[c, s, 0., 0.], [-s, c, 0., 0.], [0., 0., 1., 0.], [shift.x, shift.y, shift.z, 1.]]; + let copies: Vec = + (0..2).map(|_| crate::transform(&part, shift, Vec3::ZERO, Vec3::Z, angle).unwrap().with_display_share(&share, t)).collect(); + let tol = crate::MeshTolerance::display_of(part.size()); + let original = part.mesh_plan(&tol).unwrap().evaluate(); + for copy in &copies { + let m = copy.mesh_of(©.mesh_plan(&tol).unwrap()).unwrap(); + assert_eq!(m.triangles, original.triangles); + assert_eq!(m.tri_face, original.tri_face); + let placed = placed_mesh(&original, &t).unwrap(); + let far = m.positions.iter().zip(&placed.positions).map(|(p, q)| p.dist(*q)).fold(0.0, f64::max); + assert!(far < 1e-9, "{far}"); + } + assert_eq!(share.0.plans.lock().unwrap().len(), 1, "planned once for both copies"); } diff --git a/crates/kernel/src/meshbody.rs b/crates/kernel/src/meshbody.rs index 1b859f6a6..f6bfae1c6 100644 --- a/crates/kernel/src/meshbody.rs +++ b/crates/kernel/src/meshbody.rs @@ -1,10 +1,11 @@ //! Mesh bodies: triangles without a B-rep (imported 3MF/STL). They render, measure, move and //! export; B-rep features refuse them. +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use std::sync::Arc; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use crate::body::Body; use crate::{KernelError, Result}; @@ -41,17 +42,6 @@ impl TriMesh { } /// Distinct undirected triangle sides. - /// The diagonal of the box around the vertices: a mesh body's size ([`Body::size`]), - /// measured once when the body is made. 0 when it has none. - pub(crate) fn span(&self) -> f64 { - let mut b = solidcraft_geom::Aabb3::EMPTY; - for p in &self.positions { - b.add(*p); - } - let d = b.diagonal(); - if d.is_finite() && d > 0.0 { d } else { 0.0 } - } - pub(crate) fn edge_count(&self) -> usize { let mut set = std::collections::HashSet::new(); for t in &self.triangles { @@ -75,6 +65,7 @@ impl TriMesh { /// A mesh body from triangles (`positions` in mm). Coincident vertices are merged, degenerate /// triangles dropped, and a closed mesh with inward winding is turned outward. pub fn mesh_body(positions: &[Vec3], triangles: &[[u32; 3]]) -> Result { + let _span = solidcraft_profile::span("kernel", "mesh_body"); if triangles.len() > MAX_TRIANGLES { return Err(KernelError::Invalid(format!("mesh with {} triangles (limit {MAX_TRIANGLES})", triangles.len()))); } @@ -112,23 +103,7 @@ pub fn mesh_body(positions: &[Vec3], triangles: &[[u32; 3]]) -> Result { t.swap(1, 2); } } - Ok(Body { - solid: Arc::new(crate::body::Solid::new_unchecked(Vec::new())), - size: out.span(), - boundary_tol: None, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: None, - mesh: Some(Arc::new(out)), - color: None, - paint: None, - splits: None, - face_sources: None, - history: None, - display_of: None, - meshes: None, - phased: false, - regularization_protected: false, - }) + Ok(Body::of_mesh(out)) } /// Wind every connected piece one way: a triangle that runs a side in the same direction as @@ -212,22 +187,11 @@ impl Body { t.swap(1, 2); } } - Some(Body { - solid: self.solid.clone(), - size: out.span(), - boundary_tol: None, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: None, - mesh: Some(Arc::new(out)), - color: self.color, - paint: self.paint.clone(), - splits: self.splits.clone(), - face_sources: None, - history: None, - display_of: None, - meshes: None, - phased: false, - regularization_protected: self.regularization_protected, - }) + let mut placed = Body::of_mesh(out); + placed.color = self.color; + placed.paint = self.paint.clone(); + placed.splits = self.splits.clone(); + placed.regularization_protected = self.regularization_protected; + Some(placed) } } diff --git a/crates/kernel/src/modify_history_tests.rs b/crates/kernel/src/modify_history_tests.rs index e6e1896f0..883da7727 100644 --- a/crates/kernel/src/modify_history_tests.rs +++ b/crates/kernel/src/modify_history_tests.rs @@ -2,10 +2,12 @@ //! face and edge origin checked against the geometry of the operands (in tests only: the history //! itself is recorded, never sampled), and the exact origins asserted where the outcome is known. -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use crate::body::Body; use crate::boolean_record::tests::{self, Reach, changes, to_edge, to_face}; +use crate::history::BodyHistory; use crate::history::{Change, EdgeOrigin, FaceOrigin, History}; use crate::{BoolOp, boolean, box_solid, cylinder, extrude}; @@ -50,10 +52,14 @@ fn edge_at(b: &Body, p: Vec3) -> usize { /// The index of the face of `b` holding `p`. fn face_at(b: &Body, p: Vec3) -> usize { - let m = b.tessellate(TOL).unwrap(); + let m = b.mesh(&crate::MeshTolerance::chord(TOL)).unwrap(); (0..b.face_count()).min_by(|x, y| to_face(&m, *x, p).total_cmp(&to_face(&m, *y, p))).unwrap() } +fn volume(b: &Body) -> f64 { + crate::measure(b).unwrap().volume +} + fn cube() -> Body { box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap() } @@ -226,6 +232,8 @@ fn shell_lines_the_walls_with_offsets() { let b = cube(); let top = Vec3::new(20.0, 15.0, 20.0); let r = crate::shell(&b, &[top], 2.0).unwrap(); + // The cavity is 36 x 26 x 18 (the floor 2 thick, the top open). + assert!((volume(&r) - (24000.0 - 36.0 * 26.0 * 18.0)).abs() < 1e-3, "{}", volume(&r)); let h = verified(&r, &b, reach(2.0)); // Five inner walls, each an offset of the face it lines; the top is left as a rim. let top = face_at(&b, top); @@ -235,7 +243,7 @@ fn shell_lines_the_walls_with_offsets() { assert_eq!(h.faces[walls[0]].change, Change::Generated); } assert!(with(h, &[FaceOrigin::Offset { operand: 0, face: top }]).is_empty()); - assert_eq!(changes(h), [0, 6, 0, 0, 5]); + assert_eq!(changes(h), [0, 6, 0, 0, 5], "{h:?}"); } #[test] @@ -262,15 +270,23 @@ fn shell_of_a_stepped_body_joins_its_walls() { assert_eq!(offsets, b.face_count() - 1, "{h:?}"); } -/// A shell of a painted block: its faces are used as they are (unhealed), keeping the paint's -/// face order, with the history of that copy. Paint is an authored boundary, so the cavity Cut -/// keeps the side faces it sews across the rim's level in pieces (Split). +/// A shell of a painted block: the painted face (face 0) comes through as one face on its own +/// support, so the paint has one face to follow, and each of the five inner walls is an offset of +/// the face it lines, as on the plain block (`shell_lines_the_walls_with_offsets`). #[test] fn shell_of_a_painted_body() { let b = painted_cube(); - let r = crate::shell(&b, &[Vec3::new(20.0, 15.0, 20.0)], 2.0).unwrap(); + let top = Vec3::new(20.0, 15.0, 20.0); + let r = crate::shell(&b, &[top], 2.0).unwrap(); let h = verified(&r, &b, reach(2.0)); - assert_eq!(changes(h), [0, 2, 8, 0, 5], "{h:?}"); + assert_eq!(with(h, &[face(0)]).len(), 1, "the painted face is one face: {h:?}"); + let top = face_at(&b, top); + for f in (0..6).filter(|f| *f != top) { + let walls = with(h, &[FaceOrigin::Offset { operand: 0, face: f }]); + assert_eq!(walls.len(), 1, "{h:?}"); + assert_eq!(h.faces[walls[0]].change, Change::Generated); + } + assert!(with(h, &[FaceOrigin::Offset { operand: 0, face: top }]).is_empty()); } #[test] @@ -279,7 +295,10 @@ fn draft_tilts_faces() { let side = Vec3::new(40.0, 15.0, 10.0); let r = crate::draft(&b, &[side], &Plane::XY, Vec3::Z, 5f64.to_radians()).unwrap(); let h = verified(&r, &b, Reach { made: 0.0, moved: 2.0 }); - assert_eq!(changes(h), [0, 6, 0, 0, 0]); + // The side tilts about its bottom edge (on the neutral plane z = 0); the top and the two + // faces beside it lose a wedge along their moved edges. The bottom and the opposite side + // are untouched. + assert_eq!(changes(h), [2, 4, 0, 0, 0]); assert_eq!(with(h, &[face(face_at(&b, side))]).len(), 1); // Walls of a body that is not convex. let l = ell(); @@ -294,10 +313,17 @@ fn offset_moves_a_face() { let b = ell(); let top = Vec3::new(5.0, 5.0, 20.0); let r = crate::offset_faces(&b, &[top], 3.0).unwrap(); + // The L's plan is 40 x 15 + 15 x 15 = 825; 23 high. + assert!((volume(&r) - 825.0 * 23.0).abs() < 1e-3, "{}", volume(&r)); let h = verified(&r, &b, Reach { made: 0.0, moved: 3.0 * 1.1 }); assert_eq!(h.faces.len(), b.face_count()); - assert_eq!(with(h, &[face(face_at(&b, top))]).len(), 1); + let moved = with(h, &[face(face_at(&b, top))]); + assert_eq!(moved.len(), 1); + assert_eq!(h.faces[moved[0]].change, Change::Modified); assert!(h.edges.iter().all(|e| matches!(e.origins.as_slice(), [EdgeOrigin::Edge { .. }]))); + // Into the body by its whole height: nothing is left behind the face. + let e = crate::offset_faces(&b, &[top], -20.0).unwrap_err(); + assert!(e.to_string().contains("no room"), "{e}"); } #[test] @@ -366,10 +392,22 @@ fn surfaces_keep_their_faces() { let h = checked(&lid, &[&open], reach(0.0), &|_| true); assert_eq!(h.faces[0].change, Change::Generated); assert!(h.edges.iter().all(|e| matches!(e.origins.as_slice(), [EdgeOrigin::Edge { operand: 0, .. }]))); - // Stitched: each face the one it was sewn from, the seam the edges sewn together. + // Stitched: each face the one it was sewn from (its geometry checked against it), the five + // walls each one of the open box's and the lid the patch, and the seam the edges sewn + // together. let closed = crate::stitch(&[&open, &lid], 0.0).unwrap(); let h = checked(&closed, &[&open, &lid], reach(0.0), &|_| false); - assert!(h.faces.iter().all(|f| f.change == Change::Kept && f.origins.len() == 1)); + let mut sewn: Vec = h + .faces + .iter() + .map(|f| match f.origins[..] { + [o] => o, + _ => panic!("a stitched face from one face: {f:?}"), + }) + .collect(); + sewn.sort(); + let want = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0)].map(|(operand, face)| FaceOrigin::Face { operand, face }); + assert_eq!(sewn, want, "{h:?}"); assert_eq!(h.edges.iter().filter(|e| e.origins.len() == 2).count(), 4); let patch = crate::patch_region(&Plane::XY, &Region2 { outer: square(0.0, 0.0, 10.0, 10.0), holes: vec![] }).unwrap(); assert_eq!(patch.history().unwrap().operands, 0); @@ -379,10 +417,24 @@ fn surfaces_keep_their_faces() { fn thicken_offsets_the_surface() { let s = crate::patch_region(&Plane::XY, &Region2 { outer: square(0.0, 0.0, 10.0, 10.0), holes: vec![] }).unwrap(); let t = crate::thicken(&s, 2.0, false).unwrap(); + assert!((volume(&t) - 200.0).abs() < 1e-6, "{}", volume(&t)); + // Along the sheet's normal (+Z). + let m = t.mesh(&crate::MeshTolerance::chord(TOL)).unwrap(); + let (lo, hi) = m.positions.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.z), hi.max(p.z))); + assert!(lo.abs() < 1e-9 && (hi - 2.0).abs() < 1e-9, "z {lo}..{hi}"); let h = verified(&t, &s, reach(2.0)); - assert_eq!(with(h, &[face(0)]).len(), 1); - assert_eq!(with(h, &[FaceOrigin::Offset { operand: 0, face: 0 }]).len(), 1); - assert_eq!(blends(h).len(), 4); + assert_eq!(with(h, &[face(0)]).len(), 1, "{h:?}"); + assert_eq!(with(h, &[FaceOrigin::Offset { operand: 0, face: 0 }]).len(), 1, "{h:?}"); + assert_eq!(blends(h).len(), 4, "{h:?}"); + let both = crate::thicken(&s, 2.0, true).unwrap(); + let m = both.mesh(&crate::MeshTolerance::chord(TOL)).unwrap(); + let (lo, hi) = m.positions.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.z), hi.max(p.z))); + assert!((lo + 1.0).abs() < 1e-9 && (hi - 1.0).abs() < 1e-9, "z {lo}..{hi}"); + let h = verified(&both, &s, reach(1.0)); + assert_eq!(with(h, &[FaceOrigin::Offset { operand: 0, face: 0 }]).len(), 2, "{h:?}"); + assert_eq!(blends(h).len(), 4, "{h:?}"); + let against = crate::thicken(&s, -2.0, false).unwrap(); + assert!((volume(&against) - 200.0).abs() < 1e-6); } #[test] @@ -393,7 +445,7 @@ fn mirrored_copy_keeps_every_face_and_edge() { let h = r.history().unwrap(); h.check(&r, &[&b]).unwrap(); // Each edge is the mirror image of the one it says it is. - let (rm, bm) = (r.tessellate(TOL).unwrap(), b.tessellate(TOL).unwrap()); + let (rm, bm) = (r.mesh(&crate::MeshTolerance::chord(TOL)).unwrap(), b.mesh(&crate::MeshTolerance::chord(TOL)).unwrap()); for (j, e) in h.edges.iter().enumerate() { let [EdgeOrigin::Edge { edge, .. }] = e.origins[..] else { panic!("edge {j}: {e:?}") }; for p in &rm.edges[j] { @@ -428,29 +480,16 @@ fn box_cuts_of(b: &Body) -> Vec<(&'static str, Body, Body)> { .collect() } -/// Meetings with a side of several origins (a face the modifier's heal merged). -fn merged_meetings(h: &History) -> usize { - h.edges.iter().flat_map(|e| &e.origins).filter(|o| matches!(o, EdgeOrigin::Meet { a, b } if a.single().is_none() || b.single().is_none())).count() -} - -/// A fillet right after a box cut. The cut joins the walls it sews in pieces across its slabs -/// on their common supports, so the fillet finds whole faces. Where the block is painted the cut -/// keeps those pieces (it has more faces), the fillet's heal merges them, and the edges where -/// the round runs into such a face meet all of it. Composed with the cut, over the block and -/// the tool. +/// A fillet right after a box cut, on the plain and the painted block: the round stands in place +/// of the picked edge, and composed with the cut its history holds over the block and the tool. #[test] fn fillet_after_box_cuts() { let at = Vec3::new(5.0, 0.0, 20.0); - let plain = box_cuts_of(&cube()); for (b, painted) in [(cube(), false), (painted_cube(), true)] { - let cuts = if painted { box_cuts_of(&b) } else { plain.clone() }; - for ((name, cut, tool), (_, whole, _)) in cuts.into_iter().zip(&plain) { + for (name, cut, tool) in box_cuts_of(&b) { let r = crate::fillet(&cut, &[at], 2.0).unwrap(); let h = verified(&r, &cut, reach(2.0 * 1.5)); - assert_eq!(blends(h), [vec![edge(edge_at(&cut, at))]], "{name}"); - let pieces = cut.face_count() > whole.face_count(); - assert_eq!(pieces, painted && name != "notch" && name != "hole", "{name} (painted: {painted})"); - assert_eq!(merged_meetings(h) > 0, pieces, "{name} (painted: {painted}): {h:?}"); + assert_eq!(blends(h), [vec![edge(edge_at(&cut, at))]], "{name} (painted: {painted})"); let mut through = h.clone(); through.substitute(0, cut.history().unwrap()).unwrap(); through.check(&r, &[&b, &tool]).unwrap(); @@ -473,12 +512,85 @@ fn chamfer_after_box_cuts() { for (name, cut, tool) in box_cuts_of(&b) { let r = crate::chamfer(&cut, &[at], 2.0).unwrap(); let h = verified(&r, &cut, reach(2.0 * 1.5)); - // On the painted block the chamfer face keeps the boundaries the cut left. - let faces = with(h, &[edge(edge_at(&cut, at))]).len(); - assert!(if painted { faces >= 1 } else { faces == 1 }, "{name} (painted: {painted}): {h:?}"); + // The picked edge is one edge of the cut body on either block (its round is one face, + // `fillet_after_box_cuts`), so its chamfer is one face too. + assert_eq!(with(h, &[edge(edge_at(&cut, at))]).len(), 1, "{name} (painted: {painted}): {h:?}"); let mut through = h.clone(); through.substitute(0, cut.history().unwrap()).unwrap(); through.check(&r, &[&b, &tool]).unwrap(); } } } + +/// Shell, offset faces and draft straight through `crate::offset_backend`: refusals, and their +/// histories checked against the geometry and their numbers against the analytic ones. +mod smlib { + use super::*; + use crate::offset_backend; + + /// tangency-labs/solidcore#380: a closed shell whose wall leaves no room inside the body is + /// refused before SMLib's offset sees it, by the body's own inradius (the L's legs are 15 + /// wide, the largest ball fits at the inner corner: 15 * sqrt(2) / (1 + sqrt(2)) = 8.79), + /// never by its box (whose half extent, 10, the old guard used). + #[test] + fn a_wall_with_no_room_inside_is_refused() { + let b = ell(); + for t in [8.8, 9.5, 12.0] { + let e = offset_backend::shell(&b, &[], t).unwrap_err(); + assert!(e.to_string().contains("no room"), "{t}: {e}"); + } + let e = offset_backend::shell(&b, &[Vec3::new(5.0, 5.0, 20.0)], 8.8).unwrap_err(); + assert!(e.to_string().contains("no room"), "{e}"); + } + + /// A hole's wall is stored as two halves; a pick on the line between them opens the whole + /// wall (kernel-cases shell/4010). The cavity is the plate inset by 2.5 less the hole's + /// cylinder, open to the hole. + #[test] + fn shell_open_at_a_hole_wall_opens_the_whole_wall() { + let hole = Loop2::circle(Vec2::new(20.0, 15.0), 5.0); + let plate = extrude(&Plane::XY, &[Region2 { outer: square(0.0, 0.0, 40.0, 30.0), holes: vec![hole] }], 0.0, 12.5).unwrap().pop().unwrap(); + let r = offset_backend::shell(&plate, &[Vec3::new(25.0, 15.0, 6.25)], 2.5).unwrap(); + let pi = std::f64::consts::PI; + let want = (15000.0 - pi * 25.0 * 12.5) - (35.0 * 25.0 * 7.5 - pi * 25.0 * 7.5); + // The measure is a mesh volume (within 1e-5 of the true one on this round hole). + assert!((volume(&r) - want).abs() < want * 1e-5, "{} vs {want}", volume(&r)); + verified(&r, &plate, reach(2.5 * 1.5)); + } + + /// A 40 x 40 x 10 plate with an r2 hole 3 from its side, shelled 1.5 open at the top: the + /// hole's offset just reaches the side's, so the walls would meet along a line. Refused, + /// saying so and with the wall, never as SMLib's bare status. + #[test] + fn a_shell_whose_walls_would_meet_is_refused_saying_so() { + let hole = Loop2::circle(Vec2::new(5.0, 20.0), 2.0); + let plate = extrude(&Plane::XY, &[Region2 { outer: square(0.0, 0.0, 40.0, 40.0), holes: vec![hole] }], 0.0, 10.0).unwrap().pop().unwrap(); + let e = offset_backend::shell(&plate, &[Vec3::new(35.0, 20.0, 10.0)], 1.5).unwrap_err().to_string(); + assert!(e.contains("the 1.5 mm walls would meet along a line"), "{e}"); + } + + #[test] + fn draft_tilts_a_side_and_keeps_its_name() { + let b = cube(); + let side = Vec3::new(40.0, 15.0, 10.0); + let deg = std::f64::consts::PI / 180.0; + let r = offset_backend::draft(&b, &[side], &Plane::XY, Vec3::Z, 5.0 * deg).unwrap(); + // The side leans in 20 tan 5 deg at the top: a wedge of 20 x 20 tan 5 deg / 2 x 30 comes off. + let wedge = 0.5 * 20.0 * 20.0 * (5.0 * deg).tan() * 30.0; + assert!((volume(&r) - (24000.0 - wedge)).abs() < 1e-3, "{}", volume(&r)); + let h = verified(&r, &b, Reach { made: 0.0, moved: 2.0 }); + assert_eq!(h.faces.len(), 6); + let tilted = with(h, &[face(face_at(&b, side))]); + assert_eq!(tilted.len(), 1, "{h:?}"); + assert_eq!(h.faces[tilted[0]].change, Change::Modified); + // A round wall along the pull leans in the same way: the rod drafts to a frustum, radius + // 5 at the neutral plane and 5 - 10 tan 5 deg at the top. The top isn't parallel to the pull. + let rod = cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap(); + let frustum = offset_backend::draft(&rod, &[Vec3::new(5.0, 0.0, 5.0)], &Plane::XY, Vec3::Z, 5.0 * deg).unwrap(); + let top = 5.0 - 10.0 * (5.0 * deg).tan(); + let exact = std::f64::consts::PI * 10.0 * (25.0 + 5.0 * top + top * top) / 3.0; + assert!((volume(&frustum) - exact).abs() < 1e-3, "{} vs {exact}", volume(&frustum)); + let e = offset_backend::draft(&b, &[Vec3::new(20.0, 15.0, 20.0)], &Plane::XY, Vec3::Z, 5.0 * deg).unwrap_err(); + assert!(e.to_string().contains("not supported yet"), "{e}"); + } +} diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index fe05f55da..5409ee0aa 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -1,54 +1,25 @@ //! SolidCraft native, versioned binary geometry. No STEP conversion or display meshes. //! Exact: a decoded body is the encoded one, number for number, for the same producer. use crate::{Body, KernelError, Result, guard}; -use serde::{Deserialize, Serialize}; -use serde_json::{Map, Number, Value}; -use std::sync::Arc; +use solidcore_record::native::{self as file, Runtime, Saved}; -mod adapter; -mod binary; mod metadata; mod preview; pub use preview::native_preview_mesh; -// 01/02 were development-only prototypes; independent metadata records start at 03; 04 stores -// procedural intersections and placed revolutions exactly, and the measured runtime values. -const MAGIC: &[u8; 8] = b"SCBREP04"; -// A body's own limits. A design's cache holds many bodies within the container's budgets, and -// decoding is linear in the bytes, so one large part (an imported casting) fits. -const MAX_BYTES: usize = 256 << 20; -const MAX_ITEMS: usize = 1_000_000; -const MAX_VALUES: usize = 20_000_000; - -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct SavedBody { - solid: solidcraft_geom::brep::Brep, - metadata: solidcraft_geom::brep::envelope::Metadata, - runtime: Runtime, -} - -/// What a body measured about itself that later operations read: kept so a decoded body works -/// to the same tolerances as the one encoded, without measuring again. -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Runtime { - /// [`Body::size`] as stored (0: not measured). - size: f64, - /// The orientation mesh's missing-face count at its tolerance. - coarse_missing: Option<(f64, u64)>, - /// [`Body::boundary_tol`]: the accuracy the file it was read from declares. Written only - /// when there is one, so a body without it is stored as before. - #[serde(default, skip_serializing_if = "Option::is_none")] - boundary_tol: Option, -} fn invalid(detail: impl std::fmt::Display) -> KernelError { KernelError::Invalid(format!("native B-rep: {detail}")) } +/// A refusal of the native file (its own message, "native B-rep: ..."). +fn refused(e: file::Error) -> KernelError { + KernelError::Invalid(e.to_string()) +} -/// Explicit topology, spatial geometry, construction certificates and history, exactly. -/// Failure is a cache miss at the IO boundary, never a failed document save. +/// Explicit topology, spatial geometry, construction certificates and history, exactly: the +/// body's own record and what it carries. Failure is a cache miss at the IO boundary, never a +/// failed document save. pub fn encode_native_body(body: &Body) -> Result> { + let _span = solidcraft_profile::span("kernel", "encode_native_body"); guard("encode native B-rep", || { for source in body.face_sources.iter().flat_map(|s| s.iter()).flatten() { let mut at = source; @@ -61,152 +32,223 @@ pub fn encode_native_body(body: &Body) -> Result> { at = source; } } - if body.face_count() > MAX_ITEMS - || body.solid.edge_iter().take(MAX_ITEMS + 1).count() > MAX_ITEMS - || body.mesh.as_ref().is_some_and(|m| m.positions.len() > MAX_ITEMS || m.triangles.len() > MAX_ITEMS) - { - return Err(invalid("native geometry budget")); - } if body.mesh.is_some() { return Err(invalid("mesh bodies are source blobs, not B-rep")); } - let runtime = - Runtime { size: body.size, coarse_missing: body.coarse_missing.map(|(tol, n)| (tol, n as u64)), boundary_tol: body.boundary_tol }; - let saved = SavedBody { solid: adapter::encode(&body.solid)?, metadata: metadata::encode(body)?, runtime }; - // Structural validation does not invoke another geometric reconstruction. - validate_topology(&saved)?; - let value = serde_json::to_value(saved).map_err(invalid)?; - validate_value(&value, 0)?; - if value_nodes(&value) > MAX_VALUES { - return Err(invalid("value budget")); + if body.face_count() > file::MAX_ITEMS || body.edge_count() > file::MAX_ITEMS { + return Err(invalid("native geometry budget")); } - let mut out = MAGIC.to_vec(); - binary::write(&value, &mut out, 0)?; - Ok(out) + let runtime = Runtime { size: body.size, coarse_missing: None }; + let saved = Saved { solid: body.record().clone(), metadata: metadata::encode(body)?, runtime }; + // The record's own checks: no geometric reconstruction. + check(&saved)?; + file::encode(&saved).map_err(refused) }) } +/// The schema 4 record of a solid body, in canonical order with its pcurves: the body itself. +/// Mesh bodies have none. +pub fn brep_record(body: &Body) -> Result { + let _span = solidcraft_profile::span("kernel", "brep_record"); + if body.mesh.is_some() { + return Err(invalid("mesh bodies are source blobs, not B-rep")); + } + Ok(body.record().clone()) +} + +/// The body in SMLib (see [`Body::smlib`]), as an owned copy. +pub fn smlib_body(body: &Body) -> Result { + let _span = solidcraft_profile::span("kernel", "smlib_body"); + body.smlib()?.try_clone().map_err(|e| KernelError::smlib("SMLib", e)) +} + /// Decode bounded untrusted data. Validate indices before topology extraction. /// Only a caller that has checked who produced the data may treat it as evaluated geometry. pub fn decode_native_body(bytes: &[u8]) -> Result { - if bytes.len() > MAX_BYTES || bytes.get(..8) != Some(MAGIC.as_slice()) { - return Err(invalid("version or size")); - } + let _span = solidcraft_profile::span("kernel", "decode_native_body"); guard("decode native B-rep", || { - let mut input = bytes.get(8..).ok_or_else(|| invalid("header"))?; - let mut remaining = MAX_VALUES; - let value = binary::read(&mut input, 0, &mut remaining)?; - if !input.is_empty() { - return Err(invalid("trailing data")); + let saved = file::decode(bytes).map_err(refused)?; + check(&saved)?; + let size = saved.runtime.size; + let mut body = Body::from_record(saved.solid)?; + if size > 0.0 { + body.size = size; } - validate_value(&value, 0)?; - let saved: SavedBody = serde_json::from_value(value).map_err(invalid)?; - validate_topology(&saved)?; - let solid = adapter::decode(saved.solid)?; - let Runtime { size, coarse_missing, boundary_tol } = saved.runtime; - if !(size.is_finite() && size >= 0.0) - || coarse_missing.is_some_and(|(tol, n)| !tol.is_finite() || n > MAX_ITEMS as u64) - || boundary_tol.is_some_and(|t| !(t.is_finite() && t > 0.0)) - { - return Err(invalid("runtime values")); - } - let mut body = Body { - solid: Arc::new(solid), - size, - boundary_tol, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: coarse_missing.map(|(tol, n)| (tol, n as usize)), - mesh: None, - color: None, - paint: None, - splits: None, - face_sources: None, - history: None, - display_of: None, - meshes: None, - phased: false, - regularization_protected: false, - }; metadata::apply(&mut body, saved.metadata)?; Ok(body) }) } -fn validate_topology(saved: &SavedBody) -> Result<()> { - saved.solid.validate().map_err(invalid)?; - let faces: usize = saved.solid.shells.iter().map(|s| s.faces.len()).sum(); - let edges: usize = saved.solid.shells.iter().map(|s| s.edges.len()).sum(); - let saved = &saved.metadata; - if saved.version != solidcraft_geom::brep::envelope::VERSION { - return Err(invalid("metadata version")); - } - if saved.face_sources.as_ref().is_some_and(|s| s.len() != faces) { - return Err(invalid("face source count")); - } - if let Some(history) = &saved.history - && (history.faces.len() != faces - || history.edges.len() != edges - || history.operands as usize > MAX_ITEMS - || history.edges.iter().flat_map(|e| &e.faces).any(|&f| f as usize >= faces)) - { - return Err(invalid("history topology")); - } - if saved.color.is_some_and(|c| c.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v))) { - return Err(invalid("colour")); - } - if let Some(paint) = &saved.paint - && (!paint.opacity.is_finite() - || !(0.0..=1.0).contains(&paint.opacity) - || paint.faces.iter().any(|p| { - p.face as usize >= faces - || !p.opacity.is_finite() - || !(0.0..=1.0).contains(&p.opacity) - || p.color.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v)) - })) - { - return Err(invalid("face paint")); - } - Ok(()) +/// An SMLib body as a kernel body: SMLib's export mapped by `solidcraft_smlib` (canonical order, +/// radians, pcurves) is the body's record ([`Body::from_smlib_record`]). +pub fn body_from_smlib(brep: &solidcraft_smlib::Brep) -> Result { + let _span = solidcraft_profile::span("kernel", "body_from_smlib"); + body_from_smlib_ordered(brep).map(|(body, _)| body) } -// The binary reader bounds allocation before deserialization. Geometry semantics -// are checked by the independent schema validator, not by backend serde internals. -fn validate_value(v: &Value, depth: usize) -> Result<()> { - if depth > 48 { - return Err(invalid("nesting")); - } - match v { - Value::String(s) if s.len() > 1 << 20 => return Err(invalid("string budget")), - Value::Number(n) if n.is_f64() && n.as_f64().is_none_or(|x| !x.is_finite() || x.abs() > 1e12) => return Err(invalid("non-finite metadata")), - Value::Array(a) => { - if a.len() > MAX_ITEMS { - return Err(invalid("array budget")); - } - for x in a { - validate_value(x, depth + 1)?; - } - } - Value::Object(o) => { - for x in o.values() { - validate_value(x, depth + 1)?; - } - } - _ => {} - } - Ok(()) +/// [`body_from_smlib`], with where each of SMLib's faces and edges is in the body's face and +/// edge order ([`crate::history`]). +pub(crate) fn body_from_smlib_ordered(brep: &solidcraft_smlib::Brep) -> Result<(Body, Option)> { + let _span = solidcraft_profile::span("kernel", "body_from_smlib_ordered"); + let (record, order) = brep.to_native_ordered().map_err(|e| KernelError::Failed(e.to_string()))?; + Ok((Body::from_smlib_record(record)?, Some(order))) } -fn value_nodes(v: &Value) -> usize { +/// `body` in SMLib, with where each of SMLib's faces and edges is in the body's face and edge +/// order: SMLib's export of the imported body, checked to number every face, edge and vertex as +/// the body's record does. `None` where it does not. +pub(crate) fn smlib_body_ordered(body: &Body) -> Result<(solidcraft_smlib::Brep, Option)> { + let brep = smlib_body(body)?; + Ok((brep.try_clone().map_err(|e| KernelError::smlib("SMLib", e))?, numbering(body.record(), &brep))) +} + +/// `record` in SMLib, imported as given (SMLib's own form; a record it refuses is an error that +/// names why), with where each of SMLib's faces and edges is in the record's order. +pub(crate) fn smlib_record_ordered( + record: &solidcore_record::brep::Brep, +) -> Result<(solidcraft_smlib::Brep, Option)> { + let _span = solidcraft_profile::span("kernel", "smlib_record_ordered"); + let brep = solidcraft_smlib::Brep::from_record(record, true).map_err(|e| KernelError::smlib("SMLib", e))?; + let order = numbering(record, &brep); + Ok((brep, order)) +} + +/// Where SMLib's faces and edges of `brep` (imported from `record`) are in the record's order: +/// `None` where SMLib's export does not number them as the record does. +/// +/// SMLib's export is in canonical order, and `order` says where SMLib's own face and edge `i` +/// went in it. Where the canonical record numbers them as `record` does, `order` maps SMLib's +/// to the record's. Otherwise SMLib may still keep the record's own order (an import lists +/// SMLib's faces and edges in the record's order, and canonical order can list them otherwise, +/// a tube's seam edges among them): the export put back in SMLib's order then numbers them as +/// `record` does, and SMLib's face and edge `i` are the record's `i`. +fn numbering(record: &solidcore_record::brep::Brep, brep: &solidcraft_smlib::Brep) -> Option { + match brep.to_native_ordered() { + Ok((back, order)) => { + if same_numbering(record, &back) { + return Some(order); + } + let in_smlib_order = in_smlib_order(&back, &order)?; + same_numbering(record, &in_smlib_order).then(solidcraft_smlib::history::Order::default) + } + Err(e) => { + log::debug!(target: "smlib", "no order for an operand: {e}"); + None + } + } +} + +/// The canonical record `back` with its faces and edges in SMLib's own order (`order`: where +/// SMLib's face and edge `i` are in `back`), each loop naming its edges by SMLib's numbers. +/// `None` where `order` is not a renumbering of `back`'s faces and edges (an edge split into +/// pieces where solids touch along it is more than one record edge). +fn in_smlib_order(back: &solidcore_record::brep::Brep, order: &solidcraft_smlib::history::Order) -> Option { + use solidcore_record::brep::Loop; + let permutation = |to: &[usize], n: usize| -> Option> { + if to.is_empty() { + return Some((0..n).collect()); + } + let mut from = vec![usize::MAX; n]; + for (i, &k) in to.iter().enumerate() { + let slot = from.get_mut(k)?; + if *slot != usize::MAX { + return None; + } + *slot = i; + } + (to.len() == n).then_some(from) + }; + if !order.pieces.is_empty() { + return None; + } + // `faces_from[k]`: SMLib's number of `back`'s face k; likewise for edges. + let faces_from = permutation(&order.faces, back.faces.len())?; + let edges_from = permutation(&order.edges, back.edges.len())?; + let mut out = back.clone(); + for (k, face) in back.faces.iter().enumerate() { + let mut face = face.clone(); + for l in &mut face.loops { + if let Loop::Edges { edges } = l { + for e in edges.iter_mut() { + e.edge = u32::try_from(*edges_from.get(usize::try_from(e.edge).ok()?)?).ok()?; + } + } + } + *out.faces.get_mut(*faces_from.get(k)?)? = face; + } + for (k, edge) in back.edges.iter().enumerate() { + *out.edges.get_mut(*edges_from.get(k)?)? = edge.clone(); + } + Some(out) +} + +/// Whether two records of one body number its faces, edges and vertices alike: the same loops of +/// the same edges, the same edge ends, and each vertex where the other's is. +fn same_numbering(a: &solidcore_record::brep::Brep, b: &solidcore_record::brep::Brep) -> bool { + use solidcore_record::brep::Loop; + if a.faces.len() != b.faces.len() || a.edges.len() != b.edges.len() || a.vertices.len() != b.vertices.len() { + return false; + } + let loops_alike = a.faces.iter().zip(&b.faces).all(|(fa, fb)| { + fa.loops.len() == fb.loops.len() + && fa.loops.iter().zip(&fb.loops).all(|pair| match pair { + (Loop::Edges { edges: x }, Loop::Edges { edges: y }) => same_cycle(x, y), + (Loop::Vertex { vertex: x }, Loop::Vertex { vertex: y }) => x == y, + _ => false, + }) + }); + let ends_alike = a.edges.iter().zip(&b.edges).all(|(x, y)| x.vertices == y.vertices); + let at_same_place = a.vertices.iter().zip(&b.vertices).all(|(x, y)| { + let d = (0..3).map(|k| (x.point[k] - y.point[k]).powi(2)).sum::().sqrt(); + d <= x.tolerance + y.tolerance + a.tolerance + b.tolerance + }); + loops_alike && ends_alike && at_same_place +} + +/// Whether two loops walk the same edges: in the same order from some edge on, or in the +/// opposite order with each edge the other way round. SMLib walks a face whose surface it turned +/// (a hole's wall) the other way, starting where it likes; its faces and edges are numbered +/// alike all the same. +fn same_cycle(x: &[solidcore_record::brep::OrientedEdge], y: &[solidcore_record::brep::OrientedEdge]) -> bool { + let n = x.len(); + if n != y.len() { + return false; + } + let Some(first) = x.first() else { return true }; + let at = |k: usize| y.get(k % n); + (0..n).filter(|k| at(*k).is_some_and(|e| e.edge == first.edge)).any(|k| { + let ahead = x.iter().enumerate().all(|(i, u)| at(k + i).is_some_and(|w| w.edge == u.edge && w.forward == u.forward)); + let back = x.iter().enumerate().all(|(i, u)| at(k + n - i).is_some_and(|w| w.edge == u.edge && w.forward != u.forward)); + ahead || back + }) +} + +/// The kernel's checks of a saved body's record that the file's own structural checks leave to +/// it ([`solidcraft_geom::brep::check::geometry`]: frames, planes, placements). +fn check(saved: &Saved) -> Result<()> { + solidcraft_geom::brep::check::geometry(&saved.solid).map_err(invalid) +} + +/// How many values `v` is (a collection and each of its items): [`file::MAX_VALUES`] at most. +#[cfg(test)] +fn value_nodes(v: &serde_json::Value) -> usize { + use serde_json::Value; match v { Value::Array(a) => a.iter().fold(1usize, |n, v| n.saturating_add(value_nodes(v))), Value::Object(o) => o.values().fold(1usize, |n, v| n.saturating_add(value_nodes(v))), _ => 1, } } +#[cfg(test)] +mod smlib_import_tests; + #[cfg(test)] mod tests { use super::*; - use solidcraft_geom::Vec3; + use serde_json::Value; + use solidcore_record::Vec3; + use solidcraft_geom::prelude::*; + use std::sync::Arc; fn equal(a: &Body, b: &Body) { assert_eq!(a.face_count(), b.face_count()); assert_eq!(a.face_sources, b.face_sources); @@ -229,7 +271,7 @@ mod tests { for body in [cube, rounded, cut] { let body = body.with_color(Some([0.1, 0.5, 0.9])); let bytes = encode_native_body(&body).unwrap(); - assert!(bytes.starts_with(MAGIC)); + assert!(bytes.starts_with(file::MAGIC)); let decoded = decode_native_body(&bytes).unwrap(); equal(&body, &decoded); let a = crate::boolean(&body, &bore, crate::BoolOp::Cut).unwrap().unwrap(); @@ -237,18 +279,6 @@ mod tests { assert!((crate::measure(&a).unwrap().volume - crate::measure(&b).unwrap().volume).abs() < 1e-7); } } - /// A body read from a file keeps the accuracy the file declares through the model cache, so - /// a reopened design plans its faces as the import did; one without it is stored as before. - #[test] - fn a_files_declared_accuracy_survives_the_model_cache() { - let cube = crate::box_solid(Vec3::ZERO, Vec3::new(4., 3., 1.)).unwrap(); - let plain = encode_native_body(&cube).unwrap(); - assert_eq!(decode_native_body(&plain).unwrap().boundary_tol, None); - let read = cube.with_boundary_tol(Some(1e-5)); - let bytes = encode_native_body(&read).unwrap(); - assert_ne!(bytes, plain); - assert_eq!(decode_native_body(&bytes).unwrap().boundary_tol, Some(1e-5)); - } #[test] fn native_spheres_tori_and_open_faces_round_trip_without_conversion() { let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap(); @@ -267,6 +297,64 @@ mod tests { } } + /// The encoding as it was made before the encoder wrote as it serialized: the whole record as + /// a JSON value, checked, then written. + fn encoded_through_a_value(body: &Body) -> Result> { + let runtime = Runtime { size: body.size, coarse_missing: None }; + let saved = Saved { solid: body.record().clone(), metadata: metadata::encode(body)?, runtime }; + check(&saved)?; + file::check(&saved).map_err(refused)?; + let value = serde_json::to_value(saved).map_err(invalid)?; + file::check_value(&value).map_err(refused)?; + if value_nodes(&value) > file::MAX_VALUES { + return Err(invalid("value budget")); + } + let mut out = file::MAGIC.to_vec(); + file::write_value(&value, &mut out).map_err(refused)?; + Ok(out) + } + + /// Written as it serializes, a body's encoding is the bytes its JSON value gave, byte for + /// byte: plain, blended, cut (history), extruded (face sources), coloured, painted, split + /// along lines, round (spline forms), open, and placed far off. + #[test] + fn the_encoding_is_the_bytes_of_the_record_as_a_json_value() { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; + let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap(); + let rounded = crate::fillet(&cube, &[Vec3::new(20., 0., 10.)], 2.).unwrap(); + let bore = crate::cylinder(Vec3::new(10., 10., -1.), Vec3::Z, 3., 12.).unwrap(); + let cut = crate::boolean(&rounded, &bore, crate::BoolOp::Cut).unwrap().unwrap(); + let region = Region2 { + outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]), + holes: vec![Loop2::circle(Vec2::new(10., 10.), 4.)], + }; + let extruded = crate::extrude(&Plane::XY, &[region], 0., 5.).unwrap().remove(0); + assert!(extruded.face_sources().is_some_and(|s| s.iter().any(Option::is_some)), "an extrusion carries its face sources"); + assert!(cut.history().is_some(), "a cut carries its history"); + let paint = crate::Paint { opacity: 0.5, faces: vec![crate::FacePaint { face: 1, color: [0.9, 0.1, 0.2], opacity: 0.75 }] }; + let painted = cube.clone().with_color(Some([0.1, 0.5, 0.9])).with_paint(Some(paint)); + let top = (0..cube.face_count()).find(|f| cube.planar_face(*f).is_some_and(|p| p.normal().z > 0.5 && p.origin.z > 9.)).unwrap(); + let split = + crate::split_faces(&cube, &[top], &crate::SplitTool::Plane(Plane::from_normal(Vec3::new(20., 0., 0.), Vec3::X).unwrap())).unwrap(); + let surface = crate::copy_faces(&cube, &[Vec3::new(20., 15., 10.)]).unwrap(); + let far = crate::transform(&cut, Vec3::new(1.0e6, -2.5e5, 3.0e4), Vec3::ZERO, Vec3::Z, 0.7).unwrap(); + let bodies = [ + cube, + rounded, + cut, + extruded, + painted, + split, + surface, + crate::sphere(Vec3::ZERO, 12.).unwrap(), + crate::torus(Vec3::ZERO, 20., 4.).unwrap(), + far, + ]; + for (i, body) in bodies.iter().enumerate() { + assert_eq!(encode_native_body(body).unwrap(), encoded_through_a_value(body).unwrap(), "body {i}"); + } + } + #[test] fn box_and_fillet_have_stable_wire_records() { let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap(); @@ -275,15 +363,20 @@ mod tests { .iter() .map(|body| { let bytes = encode_native_body(body).unwrap(); - assert_eq!(&bytes[..8], b"SCBREP04"); + assert_eq!(&bytes[..8], b"SCBREP05"); let mut raw = &bytes[8..]; - let value = binary::read(&mut raw, 0, &mut 2_000_000).unwrap(); + let value = file::read_value(&mut raw, &mut 2_000_000).unwrap(); assert!(raw.is_empty()); value }) .collect(); let actual = serde_json::json!(records); - let expected: Value = serde_json::from_str(include_str!("native/fixtures/box-fillet-v4.json")).unwrap(); + // An intended change to the wire records rewrites the fixture with NATIVE_BREP_BLESS=1. + if std::env::var_os("NATIVE_BREP_BLESS").is_some() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/native/fixtures/box-fillet-v5.json"); + std::fs::write(path, serde_json::to_string_pretty(&actual).unwrap() + "\n").unwrap(); + } + let expected: Value = serde_json::from_str(include_str!("native/fixtures/box-fillet-v5.json")).unwrap(); compare_wire(&expected, &actual); } @@ -322,24 +415,41 @@ mod tests { assert!(std::panic::catch_unwind(|| decode_native_body(&bad)).is_ok()); } let mut raw = &bytes[8..]; - let value = binary::read(&mut raw, 0, &mut 2_000_000).unwrap(); + let value = file::read_value(&mut raw, &mut 2_000_000).unwrap(); for key in ["vertices", "index"] { let mut v = value.clone(); if key == "vertices" { - v["solid"]["shells"][0]["edges"][0]["vertices"] = serde_json::json!([u64::MAX, 0]); + v["solid"]["edges"][0]["vertices"] = serde_json::json!([u64::MAX, 0]); } else { - v["solid"]["shells"][0]["faces"][0]["loops"][0][0]["edge"] = serde_json::json!(u64::MAX); + v["solid"]["faces"][0]["loops"][0]["edges"][0]["edge"] = serde_json::json!(u64::MAX); } - let mut bad = MAGIC.to_vec(); - binary::write(&v, &mut bad, 0).unwrap(); + let mut bad = file::MAGIC.to_vec(); + file::write_value(&v, &mut bad).unwrap(); assert!(decode_native_body(&bad).is_err()); } - let mut huge = MAGIC.to_vec(); + let mut huge = file::MAGIC.to_vec(); huge.push(7); huge.extend(u32::MAX.to_le_bytes()); assert!(decode_native_body(&huge).is_err()); } + #[test] + fn a_kernel_body_past_the_file_item_budget_is_taken_and_a_file_of_it_refused() { + // The box with its first edge a polyline of the file item budget's worth of points: a + // record the kernel's own operations may make (#3992), and more than a file may carry. + let body = crate::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); + let mut record = body.record().clone(); + let [t0, t1] = record.edges[0].interval; + let n = solidcore_record::brep::MAX_ITEMS; + let points = (0..n).map(|i| [i as f64 * 1e-6, 0., 0.]).collect(); + record.edges[0].curve = solidcore_record::brep::Curve::Polyline { points }; + assert!(t0 >= 0.0 && t1 <= (n - 1) as f64); + Body::from_record(record.clone()).unwrap(); + let saved = Saved { solid: record, metadata: metadata::encode(&body).unwrap(), runtime: Runtime { size: 0.0, coarse_missing: None } }; + let refused = file::check(&saved).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(refused.contains("item budget"), "{refused}"); + } + #[test] fn native_preserves_face_appearance_and_authored_boundaries() { let mut body = crate::box_solid(Vec3::new(1., 2., 3.), Vec3::new(10., 20., 30.)) diff --git a/crates/kernel/src/native/adapter.rs b/crates/kernel/src/native/adapter.rs deleted file mode 100644 index 800724439..000000000 --- a/crates/kernel/src/native/adapter.rs +++ /dev/null @@ -1,421 +0,0 @@ -//! The truck adapter. Persisted data belongs to solidcraft_geom::brep, never truck. -use super::{Result, invalid}; -use mt::Invertible; -use solidcraft_geom::brep as b; -use truck_modeling as mt; - -#[path = "analytic.rs"] -mod analytic; -use analytic::{arc, full_turn, load_analytic, revolved}; -fn point(p: mt::Point3) -> [f64; 3] { - [p.x, p.y, p.z] -} -fn vector(p: mt::Vector3) -> [f64; 3] { - [p.x, p.y, p.z] -} -fn vector4(p: mt::Vector4) -> [f64; 4] { - [p.x, p.y, p.z, p.w] -} -fn p([x, y, z]: [f64; 3]) -> mt::Point3 { - mt::Point3::new(x, y, z) -} -fn v([x, y, z]: [f64; 3]) -> mt::Vector3 { - mt::Vector3::new(x, y, z) -} -fn v4([x, y, z, w]: [f64; 4]) -> mt::Vector4 { - mt::Vector4::new(x, y, z, w) -} -fn index(i: usize) -> Result { - u32::try_from(i).map_err(invalid) -} -fn depth(d: usize) -> Result<()> { - if d > 16 { Err(invalid("geometry nesting")) } else { Ok(()) } -} - -// Truck evaluates the full knot interval. The portable domain is the standard -// active interval, so only coincident (clamped) domains can cross this adapter. -fn clamped(knots: &[f64], count: usize) -> Result<()> { - let degree = knots.len().checked_sub(count + 1).ok_or_else(|| invalid("spline degree"))?; - if knots.first() != knots.get(degree) || knots.last() != knots.get(count) { - return Err(invalid("unclamped spline domain unsupported by this adapter")); - } - Ok(()) -} -fn compatible_curve(c: &b::Curve) -> Result<()> { - match c { - b::Curve::Spline { knots, points } => clamped(knots, points.len()), - b::Curve::RationalSpline { knots, homogeneous } => clamped(knots, homogeneous.len()), - b::Curve::Intersection { knots, points, .. } => clamped(knots, points.len()), - // The producer's own trace: its surfaces must load; its leader is kept as it was. - b::Curve::SurfaceIntersection { surfaces, .. } => surfaces.iter().try_for_each(|s| compatible_surface(s)), - _ => Ok(()), - } -} -fn compatible_surface(s: &b::Surface) -> Result<()> { - match s { - b::Surface::Plane { origin, u_axis, v_axis } => { - let plane = mt::Plane::new(p(*origin), p(*origin) + v(*u_axis), p(*origin) + v(*v_axis)); - if vector(plane.u_axis()) != *u_axis || vector(plane.v_axis()) != *v_axis { - return Err(invalid("plane axes cannot be reconstructed exactly")); - } - Ok(()) - } - b::Surface::Spline { u_knots, v_knots, points } => { - clamped(u_knots, points.len())?; - clamped(v_knots, points.first().map_or(0, Vec::len)) - } - b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => { - clamped(u_knots, homogeneous.len())?; - clamped(v_knots, homogeneous.first().map_or(0, Vec::len)) - } - b::Surface::Revolution { profile, angle, .. } => { - full_turn(angle)?; - compatible_curve(profile) - } - b::Surface::PlaneThrough { .. } => Ok(()), - b::Surface::PlacedRevolution { profile, .. } => compatible_curve(profile), - b::Surface::Cylinder { angle, .. } | b::Surface::Cone { angle, .. } => full_turn(angle), - b::Surface::Sphere { longitude, .. } | b::Surface::Torus { longitude, .. } => full_turn(longitude), - } -} -fn compatible(body: &b::Brep) -> Result<()> { - for shell in &body.shells { - for edge in &shell.edges { - compatible_curve(&edge.curve)?; - } - for face in &shell.faces { - compatible_surface(&face.surface)?; - } - } - Ok(()) -} - -pub(super) fn encode(solid: &mt::Solid) -> Result { - let mut shells = Vec::new(); - for shell in solid.compress().boundaries { - let vertices = shell.vertices.into_iter().map(point).collect(); - let edges = shell - .edges - .into_iter() - .map(|e| Ok(b::Edge { vertices: [index(e.vertices.0)?, index(e.vertices.1)?], curve: save_curve(&e.curve, 0)? })) - .collect::>()?; - let faces = shell - .faces - .into_iter() - .map(|f| { - let surface = save_surface(&f.surface, 0)?; - Ok(b::Face { - loops: f - .boundaries - .into_iter() - .map(|w| { - let mut uses = w - .into_iter() - .map(|e| Ok(b::EdgeUse { edge: index(e.index)?, forward: e.orientation })) - .collect::>>()?; - // Wire direction is explicit; Face.forward changes only the normal. - if !f.orientation { - reverse_wire(&mut uses); - } - Ok(uses) - }) - .collect::>()?, - surface, - forward: f.orientation, - }) - }) - .collect::>()?; - shells.push(b::Shell { vertices, edges, faces }); - } - let result = b::Brep { version: b::VERSION, shells }; - result.validate().map_err(invalid)?; - compatible(&result)?; - Ok(result) -} -pub(super) fn decode(body: b::Brep) -> Result { - body.validate().map_err(invalid)?; - compatible(&body)?; - let shells = body.shells.into_iter().map(shell).collect::>>()?; - if shells.iter().any(|s| s.shell_condition() == mt::ShellCondition::Irregular) { - return Err(invalid("non-manifold shell")); - } - Ok(mt::Solid::new_unchecked(shells)) -} -/// A shell's topology as recorded, references already checked: built as the kernel built it, -/// without truck's checks for wires that touch themselves (a seam edge used twice, a closed edge -/// on one vertex), which imported and modelled faces have. -fn shell(s: b::Shell) -> Result { - let vertices: Vec = s.vertices.into_iter().map(|v| mt::Vertex::new(p(v))).collect(); - let vertex = |i: u32| vertices.get(i as usize).ok_or_else(|| invalid("edge vertices")); - let edges = s - .edges - .into_iter() - .map(|e| Ok(mt::Edge::new_unchecked(vertex(e.vertices[0])?, vertex(e.vertices[1])?, load_curve(e.curve)?))) - .collect::>>()?; - s.faces - .into_iter() - .map(|f| { - let mut loops = f.loops; - if !f.forward { - for wire in &mut loops { - reverse_wire(wire); - } - } - let wires = loops - .into_iter() - .map(|w| { - w.into_iter() - .map(|u| { - let e = edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; - Ok(if u.forward { e.clone() } else { e.inverse() }) - }) - .collect::>() - }) - .collect::>>()?; - let mut face = mt::Face::new_unchecked(wires, load_surface(f.surface)?); - if !f.forward { - face.invert(); - } - Ok(face) - }) - .collect() -} -fn reverse_wire(wire: &mut [b::EdgeUse]) { - wire.reverse(); - for edge in wire { - edge.forward = !edge.forward; - } -} -/// Exact: every record holds the producer's own numbers, so loading it gives back the same -/// curve, never a refit. -fn save_curve(c: &mt::Curve, d: usize) -> Result { - depth(d)?; - Ok(match c { - mt::Curve::Line(c) => b::Curve::Line { start: point(c.0), end: point(c.1) }, - mt::Curve::BSplineCurve(c) => { - b::Curve::Spline { knots: c.knot_vec().iter().copied().collect(), points: c.control_points().iter().copied().map(point).collect() } - } - mt::Curve::NurbsCurve(c) => b::Curve::RationalSpline { - knots: c.knot_vec().iter().copied().collect(), - homogeneous: c.control_points().iter().copied().map(vector4).collect(), - }, - mt::Curve::IntersectionCurve(c) => { - let leader = match c.leader() { - mt::Leader::Polyline(p) => b::Curve::Polyline { points: p.0.iter().copied().map(point).collect() }, - mt::Leader::BSpline(c) => b::Curve::Spline { - knots: c.knot_vec().iter().copied().collect(), - points: c.control_points().iter().copied().map(point).collect(), - }, - }; - b::Curve::SurfaceIntersection { - surfaces: [Box::new(save_surface(c.surface0(), d + 1)?), Box::new(save_surface(c.surface1(), d + 1)?)], - leader: Box::new(leader), - tolerance: c.tolerance(), - } - } - }) -} -/// A plane as truck holds it: three points. -#[derive(serde::Serialize, serde::Deserialize)] -struct PlanePoints { - o: mt::Point3, - p: mt::Point3, - q: mt::Point3, -} - -/// A revolution as truck holds it, built from its parts as they are (its constructors normalize -/// the axis and compose the placement with the identity, either of which can round). -#[derive(serde::Serialize)] -struct PlacedRevolution { - entity: Revolved, - transform: mt::Matrix4, - orientation: bool, -} -#[derive(serde::Serialize)] -struct Revolved { - curve: mt::Curve, - revolution: Axis, -} -#[derive(serde::Serialize)] -struct Axis { - origin: mt::Point3, - axis: mt::Vector3, -} - -fn save_surface(s: &mt::Surface, d: usize) -> Result { - depth(d)?; - Ok(match s { - mt::Surface::Plane(s) => { - let PlanePoints { o, p, q } = serde_json::from_value(serde_json::to_value(s).map_err(invalid)?).map_err(invalid)?; - b::Surface::PlaneThrough { origin: point(o), u_point: point(p), v_point: point(q) } - } - mt::Surface::BSplineSurface(s) => b::Surface::Spline { - u_knots: s.uknot_vec().iter().copied().collect(), - v_knots: s.vknot_vec().iter().copied().collect(), - points: s.control_points().iter().map(|r| r.iter().copied().map(point).collect()).collect(), - }, - mt::Surface::NurbsSurface(s) => b::Surface::RationalSpline { - u_knots: s.uknot_vec().iter().copied().collect(), - v_knots: s.vknot_vec().iter().copied().collect(), - homogeneous: s.control_points().iter().map(|r| r.iter().copied().map(vector4).collect()).collect(), - }, - mt::Surface::RevolutedCurve(s) => { - let m = *s.transform(); - b::Surface::PlacedRevolution { - profile: Box::new(save_curve(s.entity().entity_curve(), d + 1)?), - origin: point(s.entity().origin()), - axis: vector(s.entity().axis()), - matrix: [m.x, m.y, m.z, m.w].map(vector4), - forward: s.orientation(), - } - } - }) -} -fn load_curve(c: b::Curve) -> Result { - Ok(match c { - b::Curve::Line { start, end } => mt::Curve::Line(mt::Line(p(start), p(end))), - b::Curve::CircleArc { frame, radius, angle } => arc(&frame, [radius, radius], angle)?, - b::Curve::EllipseArc { frame, radii, angle } => arc(&frame, radii, angle)?, - b::Curve::Spline { knots, points } => { - mt::Curve::BSplineCurve(mt::BSplineCurve::try_new(knots.into(), points.into_iter().map(p).collect()).map_err(invalid)?) - } - b::Curve::RationalSpline { knots, homogeneous } => mt::Curve::NurbsCurve(mt::NurbsCurve::new( - mt::BSplineCurve::try_new(knots.into(), homogeneous.into_iter().map(v4).collect()).map_err(invalid)?, - )), - b::Curve::Polyline { .. } => return Err(invalid("standalone polyline unsupported by this adapter")), - b::Curve::Intersection { knots, points, .. } => { - mt::Curve::BSplineCurve(mt::BSplineCurve::try_new(knots.into(), points.into_iter().map(p).collect()).map_err(invalid)?) - } - b::Curve::SurfaceIntersection { surfaces: [s0, s1], leader, tolerance } => { - let leader = match *leader { - b::Curve::Polyline { points } => mt::Leader::Polyline(mt::PolylineCurve(points.into_iter().map(p).collect())), - b::Curve::Spline { knots, points } => { - mt::Leader::BSpline(mt::BSplineCurve::try_new(knots.into(), points.into_iter().map(p).collect()).map_err(invalid)?) - } - _ => return Err(invalid("intersection leader")), - }; - let (s0, s1) = (load_surface(*s0)?, load_surface(*s1)?); - mt::Curve::IntersectionCurve(mt::IntersectionCurve::new_unchecked(Box::new(s0), Box::new(s1), leader, tolerance)) - } - }) -} -fn load_surface(s: b::Surface) -> Result { - Ok(match s { - b::Surface::Plane { origin, u_axis, v_axis } => mt::Surface::Plane(mt::Plane::new(p(origin), p(origin) + v(u_axis), p(origin) + v(v_axis))), - b::Surface::Spline { u_knots, v_knots, points } => mt::Surface::BSplineSurface( - mt::BSplineSurface::try_new((u_knots.into(), v_knots.into()), points.into_iter().map(|r| r.into_iter().map(p).collect()).collect()) - .map_err(invalid)?, - ), - b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => mt::Surface::NurbsSurface(mt::NurbsSurface::new( - mt::BSplineSurface::try_new((u_knots.into(), v_knots.into()), homogeneous.into_iter().map(|r| r.into_iter().map(v4).collect()).collect()) - .map_err(invalid)?, - )), - b::Surface::Revolution { profile, origin, axis, angle } => { - full_turn(&angle)?; - revolved(load_curve(*profile)?, p(origin), v(axis), false) - } - b::Surface::PlaneThrough { origin, u_point, v_point } => mt::Surface::Plane(mt::Plane::new(p(origin), p(u_point), p(v_point))), - b::Surface::PlacedRevolution { profile, origin, axis, matrix: [x, y, z, w], forward } => { - let placed = PlacedRevolution { - entity: Revolved { curve: load_curve(*profile)?, revolution: Axis { origin: p(origin), axis: v(axis) } }, - transform: mt::Matrix4::from_cols(v4(x), v4(y), v4(z), v4(w)), - orientation: forward, - }; - mt::Surface::RevolutedCurve(serde_json::from_value(serde_json::to_value(placed).map_err(invalid)?).map_err(invalid)?) - } - analytic => load_analytic(analytic)?, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use mt::{BoundedCurve, InnerSpace, ParametricCurve, Transformed}; - - #[test] - fn refuses_domain_or_axis_changes_instead_of_approximating() { - let curve = b::Curve::Spline { knots: vec![0., 1., 2., 3.], points: vec![[0.; 3], [1.; 3]] }; - assert!(compatible_curve(&curve).is_err()); - let plane = b::Surface::Plane { origin: [1e12; 3], u_axis: [1e-6, 0., 0.], v_axis: [0., 1., 0.] }; - assert!(compatible_surface(&plane).is_err()); - assert!(clamped(&[0., 0., 1., 1.], 2).is_ok()); - } - - #[test] - fn analytic_records_decode_as_their_mathematical_loci_and_normals() { - use mt::{MetricSpace, ParametricSurface, ParametricSurface3D}; - use std::f64::consts::{FRAC_PI_2, TAU}; - let frame = b::Frame { origin: [1., 2., 3.], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; - let circle = load_curve(b::Curve::CircleArc { frame: frame.clone(), radius: 2., angle: [0., FRAC_PI_2] }).unwrap(); - assert!(circle.subs(0.).distance(p([3., 2., 3.])) < 1e-12); - assert!(circle.subs(1.).distance(p([1., 4., 3.])) < 1e-12); - let ellipse = load_curve(b::Curve::EllipseArc { frame: frame.clone(), radii: [2., 3.], angle: [0., FRAC_PI_2] }).unwrap(); - assert!(ellipse.subs(1.).distance(p([1., 5., 3.])) < 1e-12); - let cases = [ - (b::Surface::Cylinder { frame: frame.clone(), radius: 2., angle: [0., TAU], height: [-1., 3.] }, 0.5, [3., 2., 4.], [1., 0., 0.]), - ( - b::Surface::Cone { frame: frame.clone(), radius_at_origin: 2., half_angle: 0.2, angle: [0., TAU], height: [0., 3.] }, - 0.5, - [3. + 1.5 * 0.2f64.tan(), 2., 4.5], - [1., 0., -0.2f64.tan()], - ), - ( - b::Surface::Sphere { frame: frame.clone(), radius: 2., longitude: [0., TAU], latitude: [-FRAC_PI_2, FRAC_PI_2] }, - 0.5, - [3., 2., 3.], - [1., 0., 0.], - ), - ( - b::Surface::Torus { frame, major_radius: 4., minor_radius: 1., longitude: [0., TAU], meridian: [0., TAU] }, - 0., - [6., 2., 3.], - [1., 0., 0.], - ), - ]; - for (record, parameter, expected, normal) in cases { - let surface = load_surface(record).unwrap(); - assert!(surface.subs(0., parameter).distance(p(expected)) < 1e-10); - assert!(surface.normal(0., parameter).normalize().dot(v(normal).normalize()) > 1. - 1e-10); - } - } - - #[test] - fn intersections_and_revolutions_reload_exactly() { - use solidcraft_geom::Vec3; - let cyl = crate::cylinder(Vec3::ZERO, Vec3::Z, 5., 40.).unwrap(); - let block = crate::box_solid(Vec3::new(-20., -20., 20.), Vec3::new(20., 20., 60.)).unwrap(); - let block = crate::transform(&block, Vec3::ZERO, Vec3::new(0., 0., 20.), Vec3::X, 0.4).unwrap(); - let cut = crate::boolean(&cyl, &block, crate::BoolOp::Cut).unwrap().unwrap(); - let curve = cut.solid.edge_iter().map(|e| e.curve()).find(|c| matches!(c, mt::Curve::IntersectionCurve(_))).unwrap(); - let record = save_curve(&curve, 0).unwrap(); - assert!(matches!(record, b::Curve::SurfaceIntersection { .. }), "the procedural curve itself, not a fit"); - let restored = load_curve(record.clone()).unwrap(); - let (a, b) = curve.range_tuple(); - for i in 0..=64 { - let t = a + (b - a) * i as f64 / 64.; - assert_eq!(curve.subs(t), restored.subs(t), "sample {i}"); - } - assert_eq!(save_curve(&restored, 0).unwrap(), record); - // The whole body: the same records again, and the same volume to the last bit. - let bytes = crate::encode_native_body(&cut).unwrap(); - let decoded = crate::decode_native_body(&bytes).unwrap(); - assert_eq!(crate::encode_native_body(&decoded).unwrap(), bytes); - assert_eq!(crate::measure(&decoded).unwrap().volume, crate::measure(&cut).unwrap().volume); - // A revolution keeps its own placement, reversed normal included. - let line = mt::Curve::Line(mt::Line(mt::Point3::new(2., 0., 0.), mt::Point3::new(2.5, 0., 3.))); - let mt::Surface::RevolutedCurve(mut placed) = revolved(line, mt::Point3::new(0., 1., 0.), mt::Vector3::new(0., 0., 1.), true) else { - panic!("a revolution") - }; - placed.transform_by(mt::Matrix4::from_translation(mt::Vector3::new(1., 2., 3.)) * mt::Matrix4::from_angle_x(mt::Rad(0.3))); - let placed = mt::Surface::RevolutedCurve(placed); - let record = save_surface(&placed, 0).unwrap(); - assert!(matches!(record, b::Surface::PlacedRevolution { forward: false, .. })); - let restored = load_surface(record.clone()).unwrap(); - assert_eq!(save_surface(&restored, 0).unwrap(), record); - use mt::{ParametricSurface, ParametricSurface3D}; - for (u, v) in [(0., 0.), (1.3, 0.4), (4., 1.)] { - assert_eq!(placed.subs(u, v), restored.subs(u, v)); - assert_eq!(placed.normal(u, v), restored.normal(u, v)); - } - } -} diff --git a/crates/kernel/src/native/analytic.rs b/crates/kernel/src/native/analytic.rs deleted file mode 100644 index 2de6b1a96..000000000 --- a/crates/kernel/src/native/analytic.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Analytic wire records are mathematical loci, independent of backend parameterizations. -use super::*; - -pub(super) fn full_turn(angle: &[f64; 2]) -> Result<()> { - if (angle[1] - angle[0] - std::f64::consts::TAU).abs() > 1e-12 { - Err(invalid("partial angular surface domains need another adapter representation")) - } else { - Ok(()) - } -} - -/// Exact rational conic locus. The adapter reparameterizes angle by rational spans. -pub(super) fn arc(frame: &b::Frame, radii: [f64; 2], angle: [f64; 2]) -> Result { - let span = angle[1] - angle[0]; - let count = (span / std::f64::consts::FRAC_PI_2).ceil().clamp(1., 4.) as usize; - let step = span / count as f64; - let weight = (step / 2.).cos(); - let at = |t: f64, scale: f64| p(frame.origin) + v(frame.x_axis) * (radii[0] * t.cos() / scale) + v(frame.y_axis) * (radii[1] * t.sin() / scale); - let mut controls = vec![at(angle[0], 1.).to_homogeneous()]; - let mut knots = vec![0.; 3]; - for i in 0..count { - let start = angle[0] + i as f64 * step; - controls.push(at(start + step / 2., weight).to_homogeneous() * weight); - controls.push(at(start + step, 1.).to_homogeneous()); - knots.extend(std::iter::repeat_n((i + 1) as f64 / count as f64, if i + 1 == count { 3 } else { 2 })); - } - Ok(mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::try_new(knots.into(), controls).map_err(invalid)?))) -} - -pub(super) fn revolved(profile: mt::Curve, origin: mt::Point3, axis: mt::Vector3, normal_flip: bool) -> mt::Surface { - let mut s = mt::Processor::new(mt::RevolutedCurve::by_revolution(profile, origin, axis)); - // Internal parameter swapping is allowed; no such flag is persisted in a surface record. - if normal_flip { - s.invert(); - } - mt::Surface::RevolutedCurve(s) -} - -pub(super) fn load_analytic(surface: b::Surface) -> Result { - let axis = |f: &b::Frame| v(f.x_axis).cross(v(f.y_axis)); - Ok(match surface { - b::Surface::Cylinder { frame, radius, angle, height } => { - full_turn(&angle)?; - let z = axis(&frame); - let at = |h| p(frame.origin) + v(frame.x_axis) * radius + z * h; - revolved(mt::Curve::Line(mt::Line(at(height[0]), at(height[1]))), p(frame.origin), z, true) - } - b::Surface::Cone { frame, radius_at_origin, half_angle, angle, height } => { - full_turn(&angle)?; - let z = axis(&frame); - let at = |h| p(frame.origin) + v(frame.x_axis) * (radius_at_origin + h * half_angle.tan()) + z * h; - revolved(mt::Curve::Line(mt::Line(at(height[0]), at(height[1]))), p(frame.origin), z, true) - } - b::Surface::Sphere { frame, radius, longitude, latitude } => { - full_turn(&longitude)?; - let z = axis(&frame); - let meridian = b::Frame { origin: frame.origin, x_axis: frame.x_axis, y_axis: vector(z) }; - revolved(arc(&meridian, [radius; 2], latitude)?, p(frame.origin), z, true) - } - b::Surface::Torus { frame, major_radius, minor_radius, longitude, meridian } => { - full_turn(&longitude)?; - let z = axis(&frame); - let profile = b::Frame { origin: point(p(frame.origin) + v(frame.x_axis) * major_radius), x_axis: frame.x_axis, y_axis: vector(z) }; - revolved(arc(&profile, [minor_radius; 2], meridian)?, p(frame.origin), z, true) - } - _ => return Err(invalid("expected analytic surface")), - }) -} diff --git a/crates/kernel/src/native/binary.rs b/crates/kernel/src/native/binary.rs deleted file mode 100644 index a5e855927..000000000 --- a/crates/kernel/src/native/binary.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Bounded tagged binary values: integer and f64 bits stay exact, no base64/text numbers. -use super::*; -fn bytes<'a>(input: &mut &'a [u8], n: usize) -> Result<&'a [u8]> { - let head = input.get(..n).ok_or_else(|| invalid("truncated value"))?; - *input = input.get(n..).ok_or_else(|| invalid("truncated value"))?; - Ok(head) -} -fn length(input: &mut &[u8]) -> Result { - let raw: [u8; 4] = bytes(input, 4)?.try_into().map_err(invalid)?; - usize::try_from(u32::from_le_bytes(raw)).map_err(invalid) -} -fn string(input: &mut &[u8]) -> Result { - let n = length(input)?; - if n > 1 << 20 { - return Err(invalid("string budget")); - } - Ok(std::str::from_utf8(bytes(input, n)?).map_err(invalid)?.to_owned()) -} -pub(super) fn read(input: &mut &[u8], depth: usize, budget: &mut usize) -> Result { - if depth > 48 || *budget == 0 { - return Err(invalid("value budget/depth")); - } - *budget -= 1; - let tag = *bytes(input, 1)?.first().ok_or_else(|| invalid("tag"))?; - Ok(match tag { - 0 => Value::Null, - 1 => Value::Bool(false), - 2 => Value::Bool(true), - 3..=5 => { - let raw: [u8; 8] = bytes(input, 8)?.try_into().map_err(invalid)?; - Value::Number(match tag { - 3 => Number::from(i64::from_le_bytes(raw)), - 4 => Number::from(u64::from_le_bytes(raw)), - _ => Number::from_f64(f64::from_le_bytes(raw)).ok_or_else(|| invalid("non-finite number"))?, - }) - } - 6 => Value::String(string(input)?), - 7 | 8 => { - let n = length(input)?; - if n > MAX_ITEMS || n > input.len() || n > *budget { - return Err(invalid("collection budget")); - } - if tag == 7 { - let mut a = Vec::new(); - for _ in 0..n { - a.push(read(input, depth + 1, budget)?); - } - Value::Array(a) - } else { - let mut map = Map::new(); - for _ in 0..n { - let key = string(input)?; - if map.contains_key(&key) { - return Err(invalid("duplicate key")); - } - map.insert(key, read(input, depth + 1, budget)?); - } - Value::Object(map) - } - } - _ => return Err(invalid("unknown binary tag")), - }) -} -fn count(n: usize, out: &mut Vec) -> Result<()> { - out.extend_from_slice(&u32::try_from(n).map_err(invalid)?.to_le_bytes()); - Ok(()) -} -fn text(s: &str, out: &mut Vec) -> Result<()> { - count(s.len(), out)?; - out.extend_from_slice(s.as_bytes()); - Ok(()) -} -pub(super) fn write(value: &Value, out: &mut Vec, depth: usize) -> Result<()> { - if depth > 48 || out.len() > MAX_BYTES { - return Err(invalid("encoding budget")); - } - match value { - Value::Null => out.push(0), - Value::Bool(b) => out.push(if *b { 2 } else { 1 }), - Value::Number(n) => { - if n.is_f64() { - out.push(5); - out.extend_from_slice(&n.as_f64().ok_or_else(|| invalid("number"))?.to_le_bytes()); - } else if let Some(n) = n.as_u64() { - out.push(4); - out.extend_from_slice(&n.to_le_bytes()); - } else { - out.push(3); - out.extend_from_slice(&n.as_i64().ok_or_else(|| invalid("integer"))?.to_le_bytes()); - } - } - Value::String(s) => { - out.push(6); - text(s, out)?; - } - Value::Array(a) => { - out.push(7); - count(a.len(), out)?; - for v in a { - write(v, out, depth + 1)?; - } - } - Value::Object(map) => { - out.push(8); - count(map.len(), out)?; - for (k, v) in map { - text(k, out)?; - write(v, out, depth + 1)?; - } - } - } - if out.len() > MAX_BYTES { - return Err(invalid("encoding size")); - } - Ok(()) -} diff --git a/crates/kernel/src/native/fixtures/box-fillet-v4.json b/crates/kernel/src/native/fixtures/box-fillet-v4.json deleted file mode 100644 index cb6f314ed..000000000 --- a/crates/kernel/src/native/fixtures/box-fillet-v4.json +++ /dev/null @@ -1,1976 +0,0 @@ -[ - { - "metadata": { - "boundaries": null, - "color": null, - "face_sources": [ - { - "axis": 2, - "high": false, - "kind": "box_face", - "plane": { - "origin": [ - 0.0, - 0.0, - 0.0 - ], - "x_axis": [ - 1.0, - 0.0, - 0.0 - ], - "y_axis": [ - -0.0, - -1.0, - -0.0 - ] - }, - "producer": null - }, - { - "axis": 1, - "high": false, - "kind": "box_face", - "plane": { - "origin": [ - 0.0, - 0.0, - 0.0 - ], - "x_axis": [ - 1.0, - 0.0, - 0.0 - ], - "y_axis": [ - 0.0, - 0.0, - 1.0 - ] - }, - "producer": null - }, - { - "axis": 0, - "high": true, - "kind": "box_face", - "plane": { - "origin": [ - 40.0, - 0.0, - 0.0 - ], - "x_axis": [ - 0.0, - 1.0, - 0.0 - ], - "y_axis": [ - 0.0, - 0.0, - 1.0 - ] - }, - "producer": null - }, - { - "axis": 1, - "high": true, - "kind": "box_face", - "plane": { - "origin": [ - 0.0, - 30.0, - 0.0 - ], - "x_axis": [ - 1.0, - 0.0, - 0.0 - ], - "y_axis": [ - -0.0, - -0.0, - -1.0 - ] - }, - "producer": null - }, - { - "axis": 0, - "high": false, - "kind": "box_face", - "plane": { - "origin": [ - 0.0, - 0.0, - 0.0 - ], - "x_axis": [ - 0.0, - 1.0, - 0.0 - ], - "y_axis": [ - -0.0, - -0.0, - -1.0 - ] - }, - "producer": null - }, - { - "axis": 2, - "high": true, - "kind": "box_face", - "plane": { - "origin": [ - 0.0, - 0.0, - 10.0 - ], - "x_axis": [ - 1.0, - 0.0, - 0.0 - ], - "y_axis": [ - 0.0, - 1.0, - 0.0 - ] - }, - "producer": null - } - ], - "history": { - "edges": [ - { - "faces": [ - 0, - 4 - ], - "origins": [] - }, - { - "faces": [ - 0, - 3 - ], - "origins": [] - }, - { - "faces": [ - 0, - 2 - ], - "origins": [] - }, - { - "faces": [ - 0, - 1 - ], - "origins": [] - }, - { - "faces": [ - 1, - 2 - ], - "origins": [] - }, - { - "faces": [ - 1, - 5 - ], - "origins": [] - }, - { - "faces": [ - 1, - 4 - ], - "origins": [] - }, - { - "faces": [ - 2, - 3 - ], - "origins": [] - }, - { - "faces": [ - 2, - 5 - ], - "origins": [] - }, - { - "faces": [ - 3, - 4 - ], - "origins": [] - }, - { - "faces": [ - 3, - 5 - ], - "origins": [] - }, - { - "faces": [ - 4, - 5 - ], - "origins": [] - } - ], - "faces": [ - { - "change": "generated", - "origins": [ - { - "end": false, - "kind": "cap" - } - ] - }, - { - "change": "generated", - "origins": [ - { - "kind": "profile", - "segment": 0 - } - ] - }, - { - "change": "generated", - "origins": [ - { - "kind": "profile", - "segment": 1 - } - ] - }, - { - "change": "generated", - "origins": [ - { - "kind": "profile", - "segment": 2 - } - ] - }, - { - "change": "generated", - "origins": [ - { - "kind": "profile", - "segment": 3 - } - ] - }, - { - "change": "generated", - "origins": [ - { - "end": true, - "kind": "cap" - } - ] - } - ], - "operands": 0 - }, - "paint": null, - "preserve_boundaries": false, - "version": 1 - }, - "runtime": { - "coarse_missing": [ - 0.5099019513592785, - 0 - ], - "size": 50.99019513592785 - }, - "solid": { - "shells": [ - { - "edges": [ - { - "curve": { - "end": [ - 40.0, - 0.0, - 0.0 - ], - "kind": "line", - "start": [ - 0.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 0, - 1 - ] - }, - { - "curve": { - "end": [ - 40.0, - 30.0, - 0.0 - ], - "kind": "line", - "start": [ - 40.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 1, - 2 - ] - }, - { - "curve": { - "end": [ - 0.0, - 30.0, - 0.0 - ], - "kind": "line", - "start": [ - 40.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 2, - 3 - ] - }, - { - "curve": { - "end": [ - 0.0, - 0.0, - 0.0 - ], - "kind": "line", - "start": [ - 0.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 3, - 0 - ] - }, - { - "curve": { - "end": [ - 40.0, - 0.0, - 10.0 - ], - "kind": "line", - "start": [ - 40.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 1, - 4 - ] - }, - { - "curve": { - "end": [ - 40.0, - 0.0, - 10.0 - ], - "kind": "line", - "start": [ - 0.0, - 0.0, - 10.0 - ] - }, - "vertices": [ - 5, - 4 - ] - }, - { - "curve": { - "end": [ - 0.0, - 0.0, - 10.0 - ], - "kind": "line", - "start": [ - 0.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 0, - 5 - ] - }, - { - "curve": { - "end": [ - 40.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 40.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 2, - 6 - ] - }, - { - "curve": { - "end": [ - 40.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 40.0, - 0.0, - 10.0 - ] - }, - "vertices": [ - 4, - 6 - ] - }, - { - "curve": { - "end": [ - 0.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 0.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 3, - 7 - ] - }, - { - "curve": { - "end": [ - 0.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 40.0, - 30.0, - 10.0 - ] - }, - "vertices": [ - 6, - 7 - ] - }, - { - "curve": { - "end": [ - 0.0, - 0.0, - 10.0 - ], - "kind": "line", - "start": [ - 0.0, - 30.0, - 10.0 - ] - }, - "vertices": [ - 7, - 5 - ] - } - ], - "faces": [ - { - "forward": false, - "loops": [ - [ - { - "edge": 3, - "forward": false - }, - { - "edge": 2, - "forward": false - }, - { - "edge": 1, - "forward": false - }, - { - "edge": 0, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 30.0, - 0.0 - ], - "u_point": [ - 0.0, - 30.0, - 0.0 - ], - "v_point": [ - 40.0, - 0.0, - 0.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 0, - "forward": true - }, - { - "edge": 4, - "forward": true - }, - { - "edge": 5, - "forward": false - }, - { - "edge": 6, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 0.0, - 0.0, - 0.0 - ], - "u_point": [ - 40.0, - 0.0, - 0.0 - ], - "v_point": [ - 0.0, - 0.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 1, - "forward": true - }, - { - "edge": 7, - "forward": true - }, - { - "edge": 8, - "forward": false - }, - { - "edge": 4, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 0.0, - 0.0 - ], - "u_point": [ - 40.0, - 30.0, - 0.0 - ], - "v_point": [ - 40.0, - 0.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 2, - "forward": true - }, - { - "edge": 9, - "forward": true - }, - { - "edge": 10, - "forward": false - }, - { - "edge": 7, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 30.0, - 0.0 - ], - "u_point": [ - 0.0, - 30.0, - 0.0 - ], - "v_point": [ - 40.0, - 30.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 3, - "forward": true - }, - { - "edge": 6, - "forward": true - }, - { - "edge": 11, - "forward": false - }, - { - "edge": 9, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 0.0, - 30.0, - 0.0 - ], - "u_point": [ - 0.0, - 0.0, - 0.0 - ], - "v_point": [ - 0.0, - 30.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 5, - "forward": true - }, - { - "edge": 8, - "forward": true - }, - { - "edge": 10, - "forward": true - }, - { - "edge": 11, - "forward": true - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 30.0, - 10.0 - ], - "u_point": [ - 0.0, - 30.0, - 10.0 - ], - "v_point": [ - 40.0, - 0.0, - 10.0 - ] - } - } - ], - "vertices": [ - [ - 0.0, - 0.0, - 0.0 - ], - [ - 40.0, - 0.0, - 0.0 - ], - [ - 40.0, - 30.0, - 0.0 - ], - [ - 0.0, - 30.0, - 0.0 - ], - [ - 40.0, - 0.0, - 10.0 - ], - [ - 0.0, - 0.0, - 10.0 - ], - [ - 40.0, - 30.0, - 10.0 - ], - [ - 0.0, - 30.0, - 10.0 - ] - ] - } - ], - "version": 3 - } - }, - { - "metadata": { - "boundaries": null, - "color": null, - "face_sources": null, - "history": { - "edges": [ - { - "faces": [ - 0, - 4 - ], - "origins": [ - { - "edge": 0, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 0, - 3 - ], - "origins": [ - { - "edge": 1, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 0, - 2 - ], - "origins": [ - { - "edge": 2, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 0, - 1 - ], - "origins": [ - { - "edge": 3, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 1, - 2 - ], - "origins": [ - { - "edge": 4, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 1, - 6 - ], - "origins": [ - { - "kind": "meeting", - "sides": [ - [ - { - "face": 1, - "kind": "face", - "operand": 0 - } - ], - [ - { - "edge": 5, - "kind": "edge", - "operand": 0 - } - ] - ] - } - ] - }, - { - "faces": [ - 1, - 4 - ], - "origins": [ - { - "edge": 6, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 2, - 3 - ], - "origins": [ - { - "edge": 7, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 2, - 5 - ], - "origins": [ - { - "edge": 8, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 2, - 6 - ], - "origins": [ - { - "kind": "meeting", - "sides": [ - [ - { - "face": 2, - "kind": "face", - "operand": 0 - } - ], - [ - { - "edge": 5, - "kind": "edge", - "operand": 0 - } - ] - ] - } - ] - }, - { - "faces": [ - 3, - 4 - ], - "origins": [ - { - "edge": 9, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 3, - 5 - ], - "origins": [ - { - "edge": 10, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 4, - 6 - ], - "origins": [ - { - "kind": "meeting", - "sides": [ - [ - { - "face": 4, - "kind": "face", - "operand": 0 - } - ], - [ - { - "edge": 5, - "kind": "edge", - "operand": 0 - } - ] - ] - } - ] - }, - { - "faces": [ - 4, - 5 - ], - "origins": [ - { - "edge": 11, - "kind": "edge", - "operand": 0 - } - ] - }, - { - "faces": [ - 5, - 6 - ], - "origins": [ - { - "kind": "meeting", - "sides": [ - [ - { - "face": 5, - "kind": "face", - "operand": 0 - } - ], - [ - { - "edge": 5, - "kind": "edge", - "operand": 0 - } - ] - ] - } - ] - } - ], - "faces": [ - { - "change": "kept", - "origins": [ - { - "face": 0, - "kind": "face", - "operand": 0 - } - ] - }, - { - "change": "modified", - "origins": [ - { - "face": 1, - "kind": "face", - "operand": 0 - } - ] - }, - { - "change": "modified", - "origins": [ - { - "face": 2, - "kind": "face", - "operand": 0 - } - ] - }, - { - "change": "kept", - "origins": [ - { - "face": 3, - "kind": "face", - "operand": 0 - } - ] - }, - { - "change": "modified", - "origins": [ - { - "face": 4, - "kind": "face", - "operand": 0 - } - ] - }, - { - "change": "modified", - "origins": [ - { - "face": 5, - "kind": "face", - "operand": 0 - } - ] - }, - { - "change": "generated", - "origins": [ - { - "edge": 5, - "kind": "edge", - "operand": 0 - } - ] - } - ], - "operands": 1 - }, - "paint": null, - "preserve_boundaries": false, - "version": 1 - }, - "runtime": { - "coarse_missing": [ - 0.5099019513592785, - 0 - ], - "size": 50.99019513592785 - }, - "solid": { - "shells": [ - { - "edges": [ - { - "curve": { - "end": [ - 40.0, - 0.0, - 0.0 - ], - "kind": "line", - "start": [ - 0.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 0, - 1 - ] - }, - { - "curve": { - "end": [ - 40.0, - 30.0, - 0.0 - ], - "kind": "line", - "start": [ - 40.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 1, - 2 - ] - }, - { - "curve": { - "end": [ - 0.0, - 30.0, - 0.0 - ], - "kind": "line", - "start": [ - 40.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 2, - 3 - ] - }, - { - "curve": { - "end": [ - 0.0, - 0.0, - 0.0 - ], - "kind": "line", - "start": [ - 0.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 3, - 0 - ] - }, - { - "curve": { - "end": [ - 40.0, - 0.0, - 8.0 - ], - "kind": "line", - "start": [ - 40.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 1, - 4 - ] - }, - { - "curve": { - "end": [ - 40.0, - 0.0, - 8.0 - ], - "kind": "line", - "start": [ - 0.0, - 0.0, - 8.0 - ] - }, - "vertices": [ - 5, - 4 - ] - }, - { - "curve": { - "end": [ - 0.0, - 0.0, - 8.0 - ], - "kind": "line", - "start": [ - 0.0, - 0.0, - 0.0 - ] - }, - "vertices": [ - 0, - 5 - ] - }, - { - "curve": { - "end": [ - 40.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 40.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 2, - 6 - ] - }, - { - "curve": { - "end": [ - 40.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 40.0, - 2.0000000000000004, - 10.0 - ] - }, - "vertices": [ - 7, - 6 - ] - }, - { - "curve": { - "homogeneous": [ - [ - 40.0, - 0.0, - 8.0, - 1.0 - ], - [ - 37.07106781186547, - -2.220446049250313e-16, - 7.767766952966368, - 0.9267766952966368 - ], - [ - 34.142135623730944, - 0.2499999999999991, - 7.785533905932737, - 0.8535533905932736 - ], - [ - 34.142135623730944, - 0.7499999999999988, - 8.285533905932736, - 0.8535533905932736 - ], - [ - 37.07106781186547, - 1.4999999999999982, - 9.267766952966369, - 0.9267766952966368 - ], - [ - 40.0, - 1.9999999999999984, - 10.0, - 1.0 - ] - ], - "kind": "rational_spline", - "knots": [ - 0.0, - 0.0, - 0.0, - 0.25, - 0.5, - 0.75, - 1.0, - 1.0, - 1.0 - ] - }, - "vertices": [ - 4, - 7 - ] - }, - { - "curve": { - "end": [ - 0.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 0.0, - 30.0, - 0.0 - ] - }, - "vertices": [ - 3, - 8 - ] - }, - { - "curve": { - "end": [ - 0.0, - 30.0, - 10.0 - ], - "kind": "line", - "start": [ - 40.0, - 30.0, - 10.0 - ] - }, - "vertices": [ - 6, - 8 - ] - }, - { - "curve": { - "homogeneous": [ - [ - 0.0, - 0.0, - 8.0, - 1.0 - ], - [ - 0.0, - -2.220446049250313e-16, - 7.767766952966368, - 0.9267766952966368 - ], - [ - 0.0, - 0.2499999999999991, - 7.785533905932737, - 0.8535533905932736 - ], - [ - 0.0, - 0.7499999999999988, - 8.285533905932736, - 0.8535533905932736 - ], - [ - 0.0, - 1.4999999999999982, - 9.267766952966369, - 0.9267766952966368 - ], - [ - 0.0, - 1.9999999999999984, - 10.0, - 1.0 - ] - ], - "kind": "rational_spline", - "knots": [ - 0.0, - 0.0, - 0.0, - 0.25, - 0.5, - 0.75, - 1.0, - 1.0, - 1.0 - ] - }, - "vertices": [ - 5, - 9 - ] - }, - { - "curve": { - "end": [ - 0.0, - 2.0000000000000004, - 10.0 - ], - "kind": "line", - "start": [ - 0.0, - 30.0, - 10.0 - ] - }, - "vertices": [ - 8, - 9 - ] - }, - { - "curve": { - "end": [ - 40.0, - 2.0000000000000004, - 10.0 - ], - "kind": "line", - "start": [ - 0.0, - 2.0000000000000004, - 10.0 - ] - }, - "vertices": [ - 9, - 7 - ] - } - ], - "faces": [ - { - "forward": false, - "loops": [ - [ - { - "edge": 3, - "forward": false - }, - { - "edge": 2, - "forward": false - }, - { - "edge": 1, - "forward": false - }, - { - "edge": 0, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 30.0, - 0.0 - ], - "u_point": [ - 0.0, - 30.0, - 0.0 - ], - "v_point": [ - 40.0, - 0.0, - 0.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 0, - "forward": true - }, - { - "edge": 4, - "forward": true - }, - { - "edge": 5, - "forward": false - }, - { - "edge": 6, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 0.0, - 0.0, - 0.0 - ], - "u_point": [ - 40.0, - 0.0, - 0.0 - ], - "v_point": [ - 0.0, - 0.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 1, - "forward": true - }, - { - "edge": 7, - "forward": true - }, - { - "edge": 8, - "forward": false - }, - { - "edge": 9, - "forward": false - }, - { - "edge": 4, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 0.0, - 0.0 - ], - "u_point": [ - 40.0, - 30.0, - 0.0 - ], - "v_point": [ - 40.0, - 0.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 2, - "forward": true - }, - { - "edge": 10, - "forward": true - }, - { - "edge": 11, - "forward": false - }, - { - "edge": 7, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 30.0, - 0.0 - ], - "u_point": [ - 0.0, - 30.0, - 0.0 - ], - "v_point": [ - 40.0, - 30.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 3, - "forward": true - }, - { - "edge": 6, - "forward": true - }, - { - "edge": 12, - "forward": true - }, - { - "edge": 13, - "forward": false - }, - { - "edge": 10, - "forward": false - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 0.0, - 30.0, - 0.0 - ], - "u_point": [ - 0.0, - 0.0, - 0.0 - ], - "v_point": [ - 0.0, - 30.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 14, - "forward": true - }, - { - "edge": 8, - "forward": true - }, - { - "edge": 11, - "forward": true - }, - { - "edge": 13, - "forward": true - } - ] - ], - "surface": { - "kind": "plane_through", - "origin": [ - 40.0, - 30.0, - 10.0 - ], - "u_point": [ - 0.0, - 30.0, - 10.0 - ], - "v_point": [ - 40.0, - 0.0, - 10.0 - ] - } - }, - { - "forward": true, - "loops": [ - [ - { - "edge": 5, - "forward": true - }, - { - "edge": 9, - "forward": true - }, - { - "edge": 14, - "forward": false - }, - { - "edge": 12, - "forward": false - } - ] - ], - "surface": { - "homogeneous": [ - [ - [ - -2.0, - 0.0, - 8.0, - 1.0 - ], - [ - -1.8535533905932735, - -2.220446049250313e-16, - 7.767766952966368, - 0.9267766952966368 - ], - [ - -1.7071067811865472, - 0.2499999999999991, - 7.785533905932737, - 0.8535533905932736 - ], - [ - -1.7071067811865472, - 0.7499999999999988, - 8.285533905932736, - 0.8535533905932736 - ], - [ - -1.8535533905932735, - 1.4999999999999982, - 9.267766952966369, - 0.9267766952966368 - ], - [ - -2.0, - 1.9999999999999984, - 10.0, - 1.0 - ] - ], - [ - [ - 42.0, - 0.0, - 8.0, - 1.0 - ], - [ - 38.92462120245874, - -2.220446049250313e-16, - 7.767766952966368, - 0.9267766952966368 - ], - [ - 35.84924240491749, - 0.2499999999999991, - 7.785533905932737, - 0.8535533905932736 - ], - [ - 35.84924240491749, - 0.7499999999999988, - 8.285533905932736, - 0.8535533905932736 - ], - [ - 38.92462120245874, - 1.4999999999999982, - 9.267766952966369, - 0.9267766952966368 - ], - [ - 42.0, - 1.9999999999999984, - 10.0, - 1.0 - ] - ] - ], - "kind": "rational_spline", - "u_knots": [ - 0.0, - 0.0, - 1.0, - 1.0 - ], - "v_knots": [ - 0.0, - 0.0, - 0.0, - 0.25, - 0.5, - 0.75, - 1.0, - 1.0, - 1.0 - ] - } - } - ], - "vertices": [ - [ - 0.0, - 0.0, - 0.0 - ], - [ - 40.0, - 0.0, - 0.0 - ], - [ - 40.0, - 30.0, - 0.0 - ], - [ - 0.0, - 30.0, - 0.0 - ], - [ - 40.0, - 0.0, - 8.0 - ], - [ - 0.0, - 0.0, - 8.0 - ], - [ - 40.0, - 30.0, - 10.0 - ], - [ - 40.0, - 2.0000000000000004, - 10.0 - ], - [ - 0.0, - 30.0, - 10.0 - ], - [ - 0.0, - 2.0000000000000004, - 10.0 - ] - ] - } - ], - "version": 3 - } - } -] diff --git a/crates/kernel/src/native/fixtures/box-fillet-v5.json b/crates/kernel/src/native/fixtures/box-fillet-v5.json new file mode 100644 index 000000000..d3d807104 --- /dev/null +++ b/crates/kernel/src/native/fixtures/box-fillet-v5.json @@ -0,0 +1,3811 @@ +[ + { + "metadata": { + "boundaries": null, + "color": null, + "face_sources": [ + { + "axis": 2, + "high": true, + "kind": "box_face", + "plane": { + "origin": [ + 0.0, + 0.0, + 10.0 + ], + "x_axis": [ + 1.0, + 0.0, + 0.0 + ], + "y_axis": [ + 0.0, + 1.0, + 0.0 + ] + }, + "producer": null + }, + { + "axis": 1, + "high": true, + "kind": "box_face", + "plane": { + "origin": [ + 0.0, + 30.0, + 0.0 + ], + "x_axis": [ + 1.0, + 0.0, + 0.0 + ], + "y_axis": [ + -0.0, + -0.0, + -1.0 + ] + }, + "producer": null + }, + { + "axis": 0, + "high": false, + "kind": "box_face", + "plane": { + "origin": [ + 0.0, + 0.0, + 0.0 + ], + "x_axis": [ + 0.0, + 1.0, + 0.0 + ], + "y_axis": [ + -0.0, + -0.0, + -1.0 + ] + }, + "producer": null + }, + { + "axis": 1, + "high": false, + "kind": "box_face", + "plane": { + "origin": [ + 0.0, + 0.0, + 0.0 + ], + "x_axis": [ + 1.0, + 0.0, + 0.0 + ], + "y_axis": [ + 0.0, + 0.0, + 1.0 + ] + }, + "producer": null + }, + { + "axis": 0, + "high": true, + "kind": "box_face", + "plane": { + "origin": [ + 40.0, + 0.0, + 0.0 + ], + "x_axis": [ + 0.0, + 1.0, + 0.0 + ], + "y_axis": [ + 0.0, + 0.0, + 1.0 + ] + }, + "producer": null + }, + { + "axis": 2, + "high": false, + "kind": "box_face", + "plane": { + "origin": [ + 0.0, + 0.0, + 0.0 + ], + "x_axis": [ + 1.0, + 0.0, + 0.0 + ], + "y_axis": [ + -0.0, + -1.0, + -0.0 + ] + }, + "producer": null + } + ], + "history": { + "edges": [ + { + "faces": [ + 0, + 2 + ], + "origins": [] + }, + { + "faces": [ + 0, + 3 + ], + "origins": [] + }, + { + "faces": [ + 0, + 4 + ], + "origins": [] + }, + { + "faces": [ + 0, + 1 + ], + "origins": [] + }, + { + "faces": [ + 1, + 4 + ], + "origins": [] + }, + { + "faces": [ + 1, + 5 + ], + "origins": [] + }, + { + "faces": [ + 1, + 2 + ], + "origins": [] + }, + { + "faces": [ + 2, + 5 + ], + "origins": [] + }, + { + "faces": [ + 2, + 3 + ], + "origins": [] + }, + { + "faces": [ + 3, + 5 + ], + "origins": [] + }, + { + "faces": [ + 3, + 4 + ], + "origins": [] + }, + { + "faces": [ + 4, + 5 + ], + "origins": [] + } + ], + "faces": [ + { + "change": "generated", + "origins": [ + { + "end": true, + "kind": "cap" + } + ] + }, + { + "change": "generated", + "origins": [ + { + "kind": "profile", + "segment": 2 + } + ] + }, + { + "change": "generated", + "origins": [ + { + "kind": "profile", + "segment": 3 + } + ] + }, + { + "change": "generated", + "origins": [ + { + "kind": "profile", + "segment": 0 + } + ] + }, + { + "change": "generated", + "origins": [ + { + "kind": "profile", + "segment": 1 + } + ] + }, + { + "change": "generated", + "origins": [ + { + "end": false, + "kind": "cap" + } + ] + } + ], + "operands": 0 + }, + "paint": null, + "preserve_boundaries": false, + "version": 1 + }, + "runtime": { + "coarse_missing": null, + "size": 50.99019513592785 + }, + "solid": { + "edges": [ + { + "curve": { + "end": [ + 0.0, + 0.0, + 10.0 + ], + "kind": "line", + "start": [ + 0.0, + 30.0, + 10.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 0, + "upper": false + }, + { + "face": 2, + "loop": 0, + "position": 3, + "upper": true + } + ], + "vertices": [ + 0, + 1 + ] + }, + { + "curve": { + "end": [ + 40.0, + 0.0, + 10.0 + ], + "kind": "line", + "start": [ + 0.0, + 0.0, + 10.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 1, + "upper": false + }, + { + "face": 3, + "loop": 0, + "position": 3, + "upper": true + } + ], + "vertices": [ + 1, + 2 + ] + }, + { + "curve": { + "end": [ + 40.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 0.0, + 10.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 2, + "upper": false + }, + { + "face": 4, + "loop": 0, + "position": 3, + "upper": true + } + ], + "vertices": [ + 2, + 3 + ] + }, + { + "curve": { + "end": [ + 0.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 30.0, + 10.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 3, + "upper": false + }, + { + "face": 1, + "loop": 0, + "position": 3, + "upper": true + } + ], + "vertices": [ + 3, + 0 + ] + }, + { + "curve": { + "end": [ + 40.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 1, + "loop": 0, + "position": 0, + "upper": true + }, + { + "face": 4, + "loop": 0, + "position": 2, + "upper": false + } + ], + "vertices": [ + 4, + 3 + ] + }, + { + "curve": { + "end": [ + 0.0, + 30.0, + 0.0 + ], + "kind": "line", + "start": [ + 40.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 1, + "loop": 0, + "position": 1, + "upper": false + }, + { + "face": 5, + "loop": 0, + "position": 1, + "upper": true + } + ], + "vertices": [ + 4, + 5 + ] + }, + { + "curve": { + "end": [ + 0.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 0.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 1, + "loop": 0, + "position": 2, + "upper": false + }, + { + "face": 2, + "loop": 0, + "position": 0, + "upper": true + } + ], + "vertices": [ + 5, + 0 + ] + }, + { + "curve": { + "end": [ + 0.0, + 0.0, + 0.0 + ], + "kind": "line", + "start": [ + 0.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 2, + "loop": 0, + "position": 1, + "upper": false + }, + { + "face": 5, + "loop": 0, + "position": 0, + "upper": true + } + ], + "vertices": [ + 5, + 6 + ] + }, + { + "curve": { + "end": [ + 0.0, + 0.0, + 10.0 + ], + "kind": "line", + "start": [ + 0.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 2, + "loop": 0, + "position": 2, + "upper": false + }, + { + "face": 3, + "loop": 0, + "position": 0, + "upper": true + } + ], + "vertices": [ + 6, + 1 + ] + }, + { + "curve": { + "end": [ + 40.0, + 0.0, + 0.0 + ], + "kind": "line", + "start": [ + 0.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 3, + "loop": 0, + "position": 1, + "upper": false + }, + { + "face": 5, + "loop": 0, + "position": 3, + "upper": true + } + ], + "vertices": [ + 6, + 7 + ] + }, + { + "curve": { + "end": [ + 40.0, + 0.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 3, + "loop": 0, + "position": 2, + "upper": false + }, + { + "face": 4, + "loop": 0, + "position": 0, + "upper": true + } + ], + "vertices": [ + 7, + 2 + ] + }, + { + "curve": { + "end": [ + 40.0, + 30.0, + 0.0 + ], + "kind": "line", + "start": [ + 40.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 4, + "loop": 0, + "position": 1, + "upper": false + }, + { + "face": 5, + "loop": 0, + "position": 2, + "upper": true + } + ], + "vertices": [ + 7, + 4 + ] + } + ], + "faces": [ + { + "domain": [ + [ + 0.0, + 55.0 + ], + [ + 0.0, + 55.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 0, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 42.5, + 47.5 + ], + [ + 12.500000000000002, + 47.5 + ] + ] + } + }, + { + "edge": 1, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 12.500000000000004, + 47.5 + ], + [ + 12.500000000000004, + 7.499999999999999 + ] + ] + } + }, + { + "edge": 2, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 12.500000000000004, + 7.499999999999999 + ], + [ + 42.5, + 7.499999999999999 + ] + ] + } + }, + { + "edge": 3, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 42.5, + 7.499999999999999 + ], + [ + 42.5, + 47.5 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 47.5, + -12.500000000000004, + 10.0 + ], + "u_axis": [ + 0.0, + 1.0, + 0.0 + ], + "v_axis": [ + -1.0, + 0.0, + 0.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 40.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 4, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 10.0 + ] + ] + } + }, + { + "edge": 5, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 40.0, + 0.0 + ] + ] + } + }, + { + "edge": 6, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 40.0, + 0.0 + ], + [ + 40.0, + 10.0 + ] + ] + } + }, + { + "edge": 3, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 10.0 + ], + [ + 40.0, + 10.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 40.0, + 30.0, + 0.0 + ], + "u_axis": [ + -1.0, + 0.0, + 0.0 + ], + "v_axis": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 30.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 6, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 10.0 + ] + ] + } + }, + { + "edge": 7, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 30.0, + 0.0 + ] + ] + } + }, + { + "edge": 8, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 30.0, + 0.0 + ], + [ + 30.0, + 10.0 + ] + ] + } + }, + { + "edge": 0, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 10.0 + ], + [ + 30.0, + 10.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 0.0, + 30.0, + 0.0 + ], + "u_axis": [ + 0.0, + -1.0, + 0.0 + ], + "v_axis": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 40.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 8, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 10.0 + ] + ] + } + }, + { + "edge": 9, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 40.0, + 0.0 + ] + ] + } + }, + { + "edge": 10, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 40.0, + 0.0 + ], + [ + 40.0, + 10.0 + ] + ] + } + }, + { + "edge": 1, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 10.0 + ], + [ + 40.0, + 10.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 0.0, + 0.0, + 0.0 + ], + "u_axis": [ + 1.0, + 0.0, + 0.0 + ], + "v_axis": [ + -0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 30.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 10, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 10.0 + ] + ] + } + }, + { + "edge": 11, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 30.0, + 0.0 + ] + ] + } + }, + { + "edge": 4, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 30.0, + 0.0 + ], + [ + 30.0, + 10.0 + ] + ] + } + }, + { + "edge": 2, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 10.0 + ], + [ + 30.0, + 10.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 40.0, + 0.0, + 0.0 + ], + "u_axis": [ + 0.0, + 1.0, + 0.0 + ], + "v_axis": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 55.0 + ], + [ + 0.0, + 55.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 7, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 47.499999999999986, + 42.499999999999986 + ], + [ + 47.5, + 12.499999999999991 + ] + ] + } + }, + { + "edge": 5, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 7.49999999999999, + 42.5 + ], + [ + 47.499999999999986, + 42.499999999999986 + ] + ] + } + }, + { + "edge": 11, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 7.4999999999999964, + 12.500000000000002 + ], + [ + 7.49999999999999, + 42.5 + ] + ] + } + }, + { + "edge": 9, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 47.5, + 12.499999999999993 + ], + [ + 7.4999999999999964, + 12.500000000000002 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 47.5, + -12.500000000000004, + 0.0 + ], + "u_axis": [ + -1.0, + 0.0, + 0.0 + ], + "v_axis": [ + 0.0, + 1.0, + 0.0 + ] + } + } + ], + "regions": [ + { + "shells": [ + 0 + ], + "void": false + }, + { + "shells": [ + 0 + ], + "void": false + } + ], + "shells": [ + { + "faces": [ + { + "face": 0, + "forward": true + }, + { + "face": 1, + "forward": true + }, + { + "face": 2, + "forward": true + }, + { + "face": 3, + "forward": true + }, + { + "face": 4, + "forward": true + }, + { + "face": 5, + "forward": true + } + ], + "kind": "faces", + "wires": [] + } + ], + "tolerance": 0.00002, + "version": 4, + "vertices": [ + { + "point": [ + 0.0, + 30.0, + 10.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 0.0, + 0.0, + 10.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 40.0, + 0.0, + 10.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 40.0, + 30.0, + 10.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 40.0, + 30.0, + 0.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 0.0, + 30.0, + 0.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 0.0, + 0.0, + 0.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 40.0, + 0.0, + 0.0 + ], + "tolerance": 0.00002 + } + ] + } + }, + { + "metadata": { + "boundaries": null, + "color": null, + "face_sources": null, + "history": { + "edges": [ + { + "faces": [ + 0, + 6 + ], + "origins": [ + { + "kind": "meeting", + "sides": [ + [ + { + "face": 0, + "kind": "face", + "operand": 0 + } + ], + [ + { + "edge": 1, + "kind": "edge", + "operand": 0 + } + ] + ] + } + ] + }, + { + "faces": [ + 0, + 5 + ], + "origins": [ + { + "edge": 2, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 0, + 1 + ], + "origins": [ + { + "edge": 3, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 0, + 4 + ], + "origins": [ + { + "edge": 0, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 1, + 5 + ], + "origins": [ + { + "edge": 4, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 1, + 2 + ], + "origins": [ + { + "edge": 5, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 1, + 4 + ], + "origins": [ + { + "edge": 6, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 2, + 4 + ], + "origins": [ + { + "edge": 7, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 2, + 5 + ], + "origins": [ + { + "edge": 11, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 2, + 3 + ], + "origins": [ + { + "edge": 9, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 3, + 6 + ], + "origins": [ + { + "kind": "meeting", + "sides": [ + [ + { + "face": 3, + "kind": "face", + "operand": 0 + } + ], + [ + { + "edge": 1, + "kind": "edge", + "operand": 0 + } + ] + ] + } + ] + }, + { + "faces": [ + 3, + 4 + ], + "origins": [ + { + "edge": 8, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 3, + 5 + ], + "origins": [ + { + "edge": 10, + "kind": "edge", + "operand": 0 + } + ] + }, + { + "faces": [ + 4, + 6 + ], + "origins": [ + { + "kind": "meeting", + "sides": [ + [ + { + "face": 2, + "kind": "face", + "operand": 0 + } + ], + [ + { + "edge": 1, + "kind": "edge", + "operand": 0 + } + ] + ] + } + ] + }, + { + "faces": [ + 5, + 6 + ], + "origins": [ + { + "kind": "meeting", + "sides": [ + [ + { + "face": 4, + "kind": "face", + "operand": 0 + } + ], + [ + { + "edge": 1, + "kind": "edge", + "operand": 0 + } + ] + ] + } + ] + } + ], + "faces": [ + { + "change": "modified", + "origins": [ + { + "face": 0, + "kind": "face", + "operand": 0 + } + ] + }, + { + "change": "kept", + "origins": [ + { + "face": 1, + "kind": "face", + "operand": 0 + } + ] + }, + { + "change": "kept", + "origins": [ + { + "face": 5, + "kind": "face", + "operand": 0 + } + ] + }, + { + "change": "modified", + "origins": [ + { + "face": 3, + "kind": "face", + "operand": 0 + } + ] + }, + { + "change": "modified", + "origins": [ + { + "face": 2, + "kind": "face", + "operand": 0 + } + ] + }, + { + "change": "modified", + "origins": [ + { + "face": 4, + "kind": "face", + "operand": 0 + } + ] + }, + { + "change": "generated", + "origins": [ + { + "edge": 1, + "kind": "edge", + "operand": 0 + } + ] + } + ], + "operands": 1 + }, + "paint": null, + "preserve_boundaries": false, + "version": 1 + }, + "runtime": { + "coarse_missing": null, + "size": 50.990195135927856 + }, + "solid": { + "edges": [ + { + "curve": { + "end": [ + 60.0, + 1.9999999999999964, + 10.0 + ], + "kind": "line", + "start": [ + -20.0, + 1.9999999999999964, + 10.0 + ] + }, + "interval": [ + 0.25, + 0.75 + ], + "tolerance": 0.00008, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 0, + "upper": false + }, + { + "face": 6, + "loop": 0, + "position": 0, + "upper": true + } + ], + "vertices": [ + 0, + 1 + ] + }, + { + "curve": { + "end": [ + 40.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 0.0, + 10.0 + ] + }, + "interval": [ + 0.06666666666666655, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 1, + "upper": false + }, + { + "face": 5, + "loop": 0, + "position": 4, + "upper": true + } + ], + "vertices": [ + 1, + 2 + ] + }, + { + "curve": { + "end": [ + 0.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 30.0, + 10.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 2, + "upper": false + }, + { + "face": 1, + "loop": 0, + "position": 3, + "upper": true + } + ], + "vertices": [ + 2, + 3 + ] + }, + { + "curve": { + "end": [ + 0.0, + 0.0, + 10.0 + ], + "kind": "line", + "start": [ + 0.0, + 30.0, + 10.0 + ] + }, + "interval": [ + 0.0, + 0.9333333333333335 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 0, + "loop": 0, + "position": 3, + "upper": false + }, + { + "face": 4, + "loop": 0, + "position": 1, + "upper": true + } + ], + "vertices": [ + 3, + 0 + ] + }, + { + "curve": { + "end": [ + 40.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 1, + "loop": 0, + "position": 0, + "upper": true + }, + { + "face": 5, + "loop": 0, + "position": 3, + "upper": false + } + ], + "vertices": [ + 4, + 2 + ] + }, + { + "curve": { + "end": [ + 0.0, + 30.0, + 0.0 + ], + "kind": "line", + "start": [ + 40.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 1, + "loop": 0, + "position": 1, + "upper": false + }, + { + "face": 2, + "loop": 0, + "position": 1, + "upper": true + } + ], + "vertices": [ + 4, + 5 + ] + }, + { + "curve": { + "end": [ + 0.0, + 30.0, + 10.0 + ], + "kind": "line", + "start": [ + 0.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 1, + "loop": 0, + "position": 2, + "upper": false + }, + { + "face": 4, + "loop": 0, + "position": 2, + "upper": true + } + ], + "vertices": [ + 5, + 3 + ] + }, + { + "curve": { + "end": [ + 0.0, + 0.0, + 0.0 + ], + "kind": "line", + "start": [ + 0.0, + 30.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 2, + "loop": 0, + "position": 0, + "upper": true + }, + { + "face": 4, + "loop": 0, + "position": 3, + "upper": false + } + ], + "vertices": [ + 5, + 6 + ] + }, + { + "curve": { + "end": [ + 40.0, + 30.0, + 0.0 + ], + "kind": "line", + "start": [ + 40.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 2, + "loop": 0, + "position": 2, + "upper": true + }, + { + "face": 5, + "loop": 0, + "position": 2, + "upper": false + } + ], + "vertices": [ + 7, + 4 + ] + }, + { + "curve": { + "end": [ + 40.0, + 0.0, + 0.0 + ], + "kind": "line", + "start": [ + 0.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 1.0 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 2, + "loop": 0, + "position": 3, + "upper": true + }, + { + "face": 3, + "loop": 0, + "position": 2, + "upper": false + } + ], + "vertices": [ + 6, + 7 + ] + }, + { + "curve": { + "end": [ + 60.0, + 0.0, + 8.0 + ], + "kind": "line", + "start": [ + -20.0, + 0.0, + 8.0 + ] + }, + "interval": [ + 0.25, + 0.75 + ], + "tolerance": 0.00008, + "uses": [ + { + "face": 3, + "loop": 0, + "position": 0, + "upper": true + }, + { + "face": 6, + "loop": 0, + "position": 2, + "upper": false + } + ], + "vertices": [ + 8, + 9 + ] + }, + { + "curve": { + "end": [ + 0.0, + 0.0, + 10.0 + ], + "kind": "line", + "start": [ + 0.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 0.8 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 3, + "loop": 0, + "position": 1, + "upper": true + }, + { + "face": 4, + "loop": 0, + "position": 4, + "upper": false + } + ], + "vertices": [ + 6, + 8 + ] + }, + { + "curve": { + "end": [ + 40.0, + 0.0, + 10.0 + ], + "kind": "line", + "start": [ + 40.0, + 0.0, + 0.0 + ] + }, + "interval": [ + 0.0, + 0.8 + ], + "tolerance": 0.00002, + "uses": [ + { + "face": 3, + "loop": 0, + "position": 3, + "upper": false + }, + { + "face": 5, + "loop": 0, + "position": 1, + "upper": true + } + ], + "vertices": [ + 7, + 9 + ] + }, + { + "curve": { + "frame": { + "origin": [ + 0.0, + 2.000000000000002, + 7.999999999999997 + ], + "x_axis": [ + 0.0, + -2.886579864025403e-15, + 1.0 + ], + "y_axis": [ + 0.0, + -1.0, + -2.886579864025403e-15 + ] + }, + "kind": "circle", + "radius": 2.000000000000003 + }, + "interval": [ + 0.0, + 1.0 + ], + "nurbs": { + "homogeneous": [ + [ + 0.0, + 1.9999999999999964, + 10.0, + 1.0 + ], + [ + 0.0, + 1.0638579009562312e-15, + 7.071067811865485, + 0.7071067811865489 + ], + [ + 0.0, + -8.881784197001252e-16, + 7.999999999999999, + 1.0 + ] + ], + "kind": "rational_spline", + "knots": [ + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0 + ] + }, + "tolerance": 0.00008, + "uses": [ + { + "face": 4, + "loop": 0, + "position": 0, + "upper": true + }, + { + "face": 6, + "loop": 0, + "position": 1, + "upper": false + } + ], + "vertices": [ + 0, + 8 + ] + }, + { + "curve": { + "frame": { + "origin": [ + 40.0, + 2.000000000000002, + 7.999999999999997 + ], + "x_axis": [ + 0.0, + -2.886579864025403e-15, + 1.0 + ], + "y_axis": [ + 0.0, + 1.0, + 2.886579864025403e-15 + ] + }, + "kind": "circle", + "radius": 2.000000000000003 + }, + "interval": [ + 0.0, + 1.0 + ], + "nurbs": { + "homogeneous": [ + [ + 40.0, + -8.881784197001252e-16, + 7.999999999999999, + 1.0 + ], + [ + 28.284271247461955, + 1.0638579009562312e-15, + 7.071067811865485, + 0.7071067811865489 + ], + [ + 40.0, + 1.9999999999999964, + 10.0, + 1.0 + ] + ], + "kind": "rational_spline", + "knots": [ + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0 + ] + }, + "tolerance": 0.00008, + "uses": [ + { + "face": 5, + "loop": 0, + "position": 0, + "upper": true + }, + { + "face": 6, + "loop": 0, + "position": 3, + "upper": false + } + ], + "vertices": [ + 9, + 1 + ] + } + ], + "faces": [ + { + "domain": [ + [ + 0.0, + 55.0 + ], + [ + 0.0, + 55.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 0, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.25, + 0.25, + 0.75, + 0.75 + ], + "points": [ + [ + 14.5, + 47.5 + ], + [ + 14.5, + 7.5 + ] + ] + } + }, + { + "edge": 1, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.06666666666666655, + 0.06666666666666655, + 1.0, + 1.0 + ], + "points": [ + [ + 14.5, + 7.5 + ], + [ + 42.5, + 7.5 + ] + ] + } + }, + { + "edge": 2, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 42.5, + 7.5 + ], + [ + 42.5, + 47.5 + ] + ] + } + }, + { + "edge": 3, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 0.9333333333333335, + 0.9333333333333335 + ], + "points": [ + [ + 42.5, + 47.5 + ], + [ + 14.5, + 47.5 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 47.5, + -12.500000000000004, + 10.0 + ], + "u_axis": [ + 0.0, + 1.0, + 0.0 + ], + "v_axis": [ + -1.0, + 0.0, + 0.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 40.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 4, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 10.0 + ] + ] + } + }, + { + "edge": 5, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 40.0, + 0.0 + ] + ] + } + }, + { + "edge": 6, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 40.0, + 0.0 + ], + [ + 40.0, + 10.0 + ] + ] + } + }, + { + "edge": 2, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 10.0 + ], + [ + 40.0, + 10.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 40.0, + 30.0, + 0.0 + ], + "u_axis": [ + -1.0, + 0.0, + 0.0 + ], + "v_axis": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 55.0 + ], + [ + 0.0, + 55.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 7, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 47.5, + 42.5 + ], + [ + 47.5, + 12.500000000000004 + ] + ] + } + }, + { + "edge": 5, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 7.5, + 42.5 + ], + [ + 47.5, + 42.5 + ] + ] + } + }, + { + "edge": 8, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 7.5, + 12.500000000000004 + ], + [ + 7.5, + 42.5 + ] + ] + } + }, + { + "edge": 9, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 47.5, + 12.500000000000004 + ], + [ + 7.5, + 12.500000000000004 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 47.5, + -12.500000000000004, + 0.0 + ], + "u_axis": [ + -1.0, + 0.0, + 0.0 + ], + "v_axis": [ + 0.0, + 1.0, + 0.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 40.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 10, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.25, + 0.25, + 0.75, + 0.75 + ], + "points": [ + [ + 0.0, + 8.0 + ], + [ + 40.0, + 8.0 + ] + ] + } + }, + { + "edge": 11, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 0.8, + 0.8 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 8.0 + ] + ] + } + }, + { + "edge": 9, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 40.0, + 0.0 + ] + ] + } + }, + { + "edge": 12, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 0.8, + 0.8 + ], + "points": [ + [ + 40.0, + 0.0 + ], + [ + 40.0, + 8.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 0.0, + 0.0, + 0.0 + ], + "u_axis": [ + 1.0, + 0.0, + 0.0 + ], + "v_axis": [ + -0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 30.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 13, + "forward": false, + "pcurve": { + "homogeneous": [ + [ + 28.000000000000004, + 10.0, + 1.0 + ], + [ + 21.213203435596466, + 7.071067811865485, + 0.7071067811865489 + ], + [ + 30.0, + 7.999999999999999, + 1.0 + ] + ], + "kind": "rational_spline", + "knots": [ + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0 + ] + } + }, + { + "edge": 3, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 0.9333333333333335, + 0.9333333333333335 + ], + "points": [ + [ + 0.0, + 10.0 + ], + [ + 28.000000000000004, + 10.0 + ] + ] + } + }, + { + "edge": 6, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 10.0 + ] + ] + } + }, + { + "edge": 7, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 30.0, + 0.0 + ] + ] + } + }, + { + "edge": 11, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 0.8, + 0.8 + ], + "points": [ + [ + 30.0, + 0.0 + ], + [ + 30.0, + 8.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 0.0, + 30.0, + 0.0 + ], + "u_axis": [ + 0.0, + -1.0, + 0.0 + ], + "v_axis": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 30.0 + ], + [ + 0.0, + 10.0 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 14, + "forward": false, + "pcurve": { + "homogeneous": [ + [ + 0.0, + 7.999999999999999, + 1.0 + ], + [ + 1.0638579009562312e-15, + 7.071067811865485, + 0.7071067811865489 + ], + [ + 1.9999999999999964, + 10.0, + 1.0 + ] + ], + "kind": "rational_spline", + "knots": [ + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0 + ] + } + }, + { + "edge": 12, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 0.8, + 0.8 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 0.0, + 8.0 + ] + ] + } + }, + { + "edge": 8, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.0, + 0.0 + ], + [ + 30.0, + 0.0 + ] + ] + } + }, + { + "edge": 4, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 30.0, + 0.0 + ], + [ + 30.0, + 10.0 + ] + ] + } + }, + { + "edge": 1, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.06666666666666655, + 0.06666666666666655, + 1.0, + 1.0 + ], + "points": [ + [ + 1.9999999999999967, + 10.0 + ], + [ + 30.0, + 10.0 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "surface": { + "kind": "plane", + "origin": [ + 40.0, + 0.0, + 0.0 + ], + "u_axis": [ + 0.0, + 1.0, + 0.0 + ], + "v_axis": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "domain": [ + [ + 0.0, + 1.0 + ], + [ + 0.25, + 0.7500000000000001 + ] + ], + "loops": [ + { + "edges": [ + { + "edge": 0, + "forward": false, + "pcurve": { + "kind": "spline", + "knots": [ + 0.25, + 0.25, + 0.75, + 0.75 + ], + "points": [ + [ + -5.551115123125784e-17, + 0.25000000000000006 + ], + [ + -1.6653345369377348e-16, + 0.75 + ] + ] + } + }, + { + "edge": 13, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + -5.551115123125784e-17, + 0.25000000000000006 + ], + [ + 0.9999999999999999, + 0.24999999999999983 + ] + ] + } + }, + { + "edge": 10, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.25, + 0.25, + 0.75, + 0.75 + ], + "points": [ + [ + 0.9999999999999999, + 0.24999999999999983 + ], + [ + 0.9999999999999998, + 0.7499999999999998 + ] + ] + } + }, + { + "edge": 14, + "forward": true, + "pcurve": { + "kind": "spline", + "knots": [ + 0.0, + 0.0, + 1.0, + 1.0 + ], + "points": [ + [ + 0.9999999999999998, + 0.7499999999999999 + ], + [ + -1.665334536937735e-16, + 0.7500000000000001 + ] + ] + } + } + ], + "kind": "edges" + } + ], + "nurbs": { + "homogeneous": [ + [ + [ + -3.552713678800501e-15, + 1.9999999999999964, + 10.0, + 1.0 + ], + [ + 40.0, + 1.9999999999999964, + 10.0, + 1.0 + ] + ], + [ + [ + -2.512147933894045e-15, + 1.3778763926929864e-15, + 7.071067811865485, + 0.7071067811865489 + ], + [ + 28.284271247461955, + 1.3778763926929864e-15, + 7.071067811865485, + 0.7071067811865489 + ] + ], + [ + [ + -3.552713678800501e-15, + -4.440892098500626e-16, + 8.0, + 1.0 + ], + [ + 40.0, + -4.440892098500626e-16, + 8.0, + 1.0 + ] + ] + ], + "kind": "rational_spline", + "u_knots": [ + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0 + ], + "v_knots": [ + 0.25, + 0.25, + 0.7500000000000001, + 0.7500000000000001 + ] + }, + "surface": { + "frame": { + "origin": [ + -20.0, + 2.000000000000002, + 7.999999999999997 + ], + "x_axis": [ + 0.0, + -2.886579864025403e-15, + 1.0 + ], + "y_axis": [ + 0.0, + -1.0, + -2.886579864025403e-15 + ] + }, + "kind": "cylinder", + "radius": 2.000000000000003 + } + } + ], + "regions": [ + { + "shells": [ + 0 + ], + "void": false + }, + { + "shells": [ + 0 + ], + "void": false + } + ], + "shells": [ + { + "faces": [ + { + "face": 0, + "forward": true + }, + { + "face": 1, + "forward": true + }, + { + "face": 2, + "forward": true + }, + { + "face": 3, + "forward": true + }, + { + "face": 4, + "forward": true + }, + { + "face": 5, + "forward": true + }, + { + "face": 6, + "forward": true + } + ], + "kind": "faces", + "wires": [] + } + ], + "tolerance": 0.00002, + "version": 4, + "vertices": [ + { + "point": [ + 0.0, + 1.9999999999999964, + 10.0 + ], + "tolerance": 0.00008 + }, + { + "point": [ + 40.0, + 1.9999999999999964, + 10.0 + ], + "tolerance": 0.00008 + }, + { + "point": [ + 40.0, + 30.0, + 10.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 0.0, + 30.0, + 10.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 40.0, + 30.0, + 0.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 0.0, + 30.0, + 0.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 0.0, + 0.0, + 0.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 40.0, + 0.0, + 0.0 + ], + "tolerance": 0.00002 + }, + { + "point": [ + 0.0, + 0.0, + 8.0 + ], + "tolerance": 0.00008 + }, + { + "point": [ + 40.0, + -8.881784197001252e-16, + 7.999999999999999 + ], + "tolerance": 0.00008 + } + ] + } + } +] diff --git a/crates/kernel/src/native/metadata.rs b/crates/kernel/src/native/metadata.rs index f87bd4ea0..49eb812d8 100644 --- a/crates/kernel/src/native/metadata.rs +++ b/crates/kernel/src/native/metadata.rs @@ -1,7 +1,8 @@ //! Explicit conversions between runtime metadata and the versioned wire records. use super::{Result, invalid}; use crate::{Body, FaceSource, history as h}; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3, brep::envelope as w}; +use solidcore_record::brep::envelope as w; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; fn index(n: usize) -> Result { u32::try_from(n).map_err(invalid) @@ -32,7 +33,8 @@ fn segment(s: &Seg2) -> Result { Seg2::Conic { a, apex, b, w } => w::Segment::Conic { points: [a, apex, b].map(point2), middle_weight: w }, Seg2::Bezier { n, p } => { let count = usize::from(n) + 1; - if !(5..=solidcraft_geom::MAX_BEZIER_CTRL).contains(&count) || p.get(count..).is_none_or(|unused| unused.iter().any(|p| *p != Vec2::ZERO)) + if !(5..=solidcore_record::MAX_BEZIER_CTRL).contains(&count) + || p.get(count..).is_none_or(|unused| unused.iter().any(|p| *p != Vec2::ZERO)) { return Err(invalid("unsupported certificate Bezier layout")); } @@ -47,10 +49,10 @@ fn load_segment(s: w::Segment) -> Result { w::Segment::Cubic { points: [a, b, c, d] } => Seg2::Cubic { p0: p2(a), p1: p2(b), p2: p2(c), p3: p2(d) }, w::Segment::Conic { points: [a, apex, b], middle_weight } => Seg2::Conic { a: p2(a), apex: p2(apex), b: p2(b), w: middle_weight }, w::Segment::Bezier { points } => { - if !(5..=solidcraft_geom::MAX_BEZIER_CTRL).contains(&points.len()) { + if !(5..=solidcore_record::MAX_BEZIER_CTRL).contains(&points.len()) { return Err(invalid("certificate Bezier degree")); } - let mut p = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL]; + let mut p = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; let n = (points.len() - 1) as u8; for (slot, value) in p.iter_mut().zip(points) { *slot = p2(value); @@ -244,7 +246,7 @@ pub(super) fn encode(body: &Body) -> Result { .paint .as_ref() .map(|p| { - Ok(w::Paint { + Ok::<_, crate::KernelError>(w::Paint { opacity: p.opacity, faces: p .faces @@ -325,7 +327,7 @@ mod tests { for value in sources { assert_eq!(value, source(&load_source(value.clone(), 0).unwrap(), 0).unwrap()); } - assert!(load_segment(w::Segment::Bezier { points: vec![[0., 0.]; solidcraft_geom::MAX_BEZIER_CTRL + 1] }).is_err()); + assert!(load_segment(w::Segment::Bezier { points: vec![[0., 0.]; solidcore_record::MAX_BEZIER_CTRL + 1] }).is_err()); } #[test] diff --git a/crates/kernel/src/native/preview.rs b/crates/kernel/src/native/preview.rs index 27a1f70e2..4a4dce9e6 100644 --- a/crates/kernel/src/native/preview.rs +++ b/crates/kernel/src/native/preview.rs @@ -1,137 +1,31 @@ -//! Bounded provisional tessellation. Fixed sampling avoids untrusted adaptive -//! subdivision before output budgets can be checked; editing uses the normal mesh. +//! Bounded provisional display of a decoded body, before its edit mesh. The budget is taken +//! before meshing (at least one triangle per face) and charged with what the mesh used; the +//! planner bounds its own work per face, so hostile records cost a bounded amount. use super::{Body, Result, invalid}; -use mt::{BoundedCurve, ParametricCurve}; -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::Mesh; -use truck_modeling as mt; - -fn curve_safe(c: &mt::Curve, depth: usize) -> bool { - if depth > 4 { - return false; - } - match c { - mt::Curve::Line(_) => true, - mt::Curve::BSplineCurve(c) => c.control_points().len() <= 256, - mt::Curve::NurbsCurve(c) => c.control_points().len() <= 256, - mt::Curve::IntersectionCurve(c) => { - let leader = match c.leader() { - mt::Leader::Polyline(p) => p.len() <= 256, - mt::Leader::BSpline(p) => p.control_points().len() <= 256, - }; - leader && surface_safe(c.surface0(), depth + 1) && surface_safe(c.surface1(), depth + 1) - } - } -} -fn surface_safe(s: &mt::Surface, depth: usize) -> bool { - if depth > 4 { - return false; - } - match s { - mt::Surface::Plane(_) => true, - mt::Surface::BSplineSurface(s) => s.control_points().iter().map(Vec::len).sum::() <= 256, - mt::Surface::NurbsSurface(s) => s.control_points().iter().map(Vec::len).sum::() <= 256, - mt::Surface::RevolutedCurve(s) => { - !matches!(s.entity().entity_curve(), mt::Curve::IntersectionCurve(_)) && curve_safe(s.entity().entity_curve(), depth + 1) - } - } -} - -/// Approximate read-only display. Boundary and grid sampling are fixed before -/// triangulation, and the complete body's upper bound is checked before projection. +/// A coarse mesh of `body` (finer with `detail`, 1–8) charged to `remaining` triangles. pub fn native_preview_mesh(body: &Body, detail: usize, remaining: &mut usize) -> Result { - crate::guard("bounded native preview", || { - if body.mesh.is_some() { - return Err(invalid("native preview requires B-rep")); - } - let detail = detail.clamp(1, 8); - - let mut prepared = Vec::new(); - let mut estimate = 0usize; - for face in body.solid.face_iter() { - let surface = face.surface(); - let grid = if matches!(surface, mt::Surface::Plane(_)) { 1 } else { detail * 2 }; - if !surface_safe(&surface, 0) { - return Err(invalid("preview surface complexity")); - } - let mut loops = Vec::new(); - let mut count = 0usize; - for wire in face.absolute_boundaries() { - let mut points = Vec::new(); - for edge in wire { - let curve = edge.oriented_curve(); - if !curve_safe(&curve, 0) { - return Err(invalid("preview curve complexity")); - } - let n = if matches!(curve, mt::Curve::Line(_)) { 1 } else { detail * 4 }; - count = count.saturating_add(n); - if count > 4096 { - return Err(invalid("preview boundary budget")); - } - let (a, b) = curve.range_tuple(); - for i in 0..n { - let t = a * (1. - i as f64 / n as f64) + b * (i as f64 / n as f64); - let point = match &curve { - mt::Curve::IntersectionCurve(c) => c.leader().subs(t), - _ => curve.subs(t), - }; - if !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite() { - return Err(invalid("preview sample")); - } - points.push(point); - } - } - let first = points.first().copied().ok_or_else(|| invalid("empty preview wire"))?; - points.push(first); - count = count.saturating_add(1); - if count > 4096 { - return Err(invalid("preview boundary budget")); - } - loops.push(points); - } - // Projection duplicates at most each input point, seams add eight - // fixed polylines, and a planar triangulation has fewer than 2V faces. - estimate = estimate.saturating_add(2 * (2 * count + 8 * (grid + 1) + (grid + 1).pow(2)) + 16); - if estimate > *remaining { - return Err(invalid("preview allocation budget")); - } - prepared.push((surface, face.orientation(), loops, grid)); - } - *remaining -= estimate; - let mut out = Mesh::default(); - for (surface, forward, loops, grid) in prepared { - let mesh = truck_meshalgo::tessellation::preview_face(&surface, &loops, grid).ok_or_else(|| invalid("preview projection"))?; - let mut count = 0; - for triangle in mesh.faces().triangle_iter() { - if out.triangles.len() >= estimate { - return Err(invalid("preview output budget")); - } - let mut indices = [0u32; 3]; - for (slot, index) in indices.iter_mut().zip(triangle) { - let p = mesh.positions().get(index.pos).ok_or_else(|| invalid("preview vertex"))?; - if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { - return Err(invalid("preview vertex")); - } - *slot = u32::try_from(out.positions.len()).map_err(invalid)?; - out.positions.push(Vec3::new(p.x, p.y, p.z)); - } - if !forward { - indices.swap(1, 2); - } - out.triangles.push(indices); - count += 1; - } - if count == 0 { - return Err(invalid("missing preview face")); - } - } - Ok(out) - }) + if body.mesh.is_some() { + return Err(invalid("native preview requires B-rep")); + } + if body.face_count() > *remaining { + return Err(invalid("preview budget")); + } + let detail = detail.clamp(1, 8) as f64; + let chord = (body.size() * 0.01 / detail).max(1e-3); + let mesh = body.mesh(&crate::MeshTolerance::display(chord))?; + if mesh.triangles.len() > *remaining || mesh.positions.iter().any(|p| !p.is_finite()) { + return Err(invalid("preview budget")); + } + *remaining -= mesh.triangles.len(); + Ok(mesh) } #[cfg(test)] mod tests { use super::*; + use solidcore_record::Vec3; #[test] fn native_preview_is_finite_and_budgeted_before_meshing() { for body in [ diff --git a/crates/kernel/src/native/smlib_import_tests.rs b/crates/kernel/src/native/smlib_import_tests.rs new file mode 100644 index 000000000..7c5adc8cb --- /dev/null +++ b/crates/kernel/src/native/smlib_import_tests.rs @@ -0,0 +1,163 @@ +//! Bodies into SMLib through their schema 4 records: the kernel's primitives keep their analytic +//! volume. +use std::f64::consts::PI; + +use solidcore_record::Vec3; + +use crate::{Body, box_solid, cylinder, sphere, torus}; + +fn v(x: f64, y: f64, z: f64) -> Vec3 { + Vec3::new(x, y, z) +} + +/// The body's SMLib volume, and whether SMLib finds it a manifold solid. +fn in_smlib(body: &Body) -> Result<(f64, bool), String> { + let s = super::smlib_body(body).map_err(|e| e.to_string())?; + Ok((s.volume(1e-7).map_err(|e| e.to_string())?, s.is_manifold_solid().unwrap_or(false))) +} + +#[test] +fn primitives_keep_their_analytic_volume() { + let (got, solid) = in_smlib(&box_solid(v(0., 0., 0.), v(10., 20., 30.)).unwrap()).unwrap(); + assert!(solid && (got - 6000.0).abs() <= 1e-9 * 6000.0, "box: SMLib volume {got}, manifold {solid}"); + let (got, solid) = in_smlib(&cylinder(v(1., 2., 3.), v(0., 0., 1.), 5.0, 10.0).unwrap()).unwrap(); + assert!(solid && (got - 250.0 * PI).abs() <= 1e-6 * 250.0 * PI, "cylinder: SMLib volume {got}, manifold {solid}"); + let (got, solid) = in_smlib(&cylinder(v(0., 0., 0.), v(1., 1., 1.), 2.0, 7.0).unwrap()).unwrap(); + assert!(solid && (got - 28.0 * PI).abs() <= 1e-6 * 28.0 * PI, "tilted cylinder: SMLib volume {got}, manifold {solid}"); +} + +/// Truck holds spheres and tori as revolutions (`PlacedRevolution`): SMLib gets them as its +/// analytic sphere and torus, faces turned over where the revolution's normal points inward. +#[test] +fn revolutions_keep_their_analytic_volume() { + let cases = [ + ("sphere", sphere(v(1., 2., 3.), 5.0).unwrap(), 4.0 / 3.0 * PI * 125.0), + ("torus", torus(v(0., 0., 0.), 10.0, 2.0).unwrap(), 2.0 * PI * PI * 10.0 * 4.0), + ]; + for (name, body, exact) in cases { + let s = super::smlib_body(&body).unwrap_or_else(|e| panic!("{name}: {e}")); + let check = s.check(solidcraft_smlib::CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{name}: {check}"); + let got = s.volume(1e-7).unwrap(); + assert!(s.is_manifold_solid().unwrap_or(false) && (got - exact).abs() <= 1e-6 * exact, "{name}: SMLib volume {got}, exact {exact}"); + } +} + +/// A body SMLib made (analytic faces) comes back as a record and goes into SMLib again as the +/// same analytic faces: a second boolean on a first one's result. +#[test] +fn smlib_results_go_back_into_smlib() { + for (name, body, exact) in [ + ("cylinder", cylinder(v(1., 2., 3.), v(0., 0., 1.), 5.0, 10.0).unwrap(), 250.0 * PI), + ("sphere", sphere(v(0., 0., 0.), 3.0).unwrap(), 36.0 * PI), + ] { + let first = super::smlib_body(&body).unwrap(); + let back = super::body_from_smlib(&first).unwrap_or_else(|e| panic!("{name}: {e}")); + let again = super::smlib_body(&back).unwrap_or_else(|e| panic!("{name}: {e}")); + let check = again.check(solidcraft_smlib::CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{name}: {check}"); + let got = again.volume(1e-7).unwrap(); + assert!((got - exact).abs() <= 1e-6 * exact, "{name}: SMLib volume {got}, exact {exact}"); + } +} + +/// Extruded circles go into SMLib as its cylinder, so a boolean with one intersects a plane with +/// a cylinder, not with a spline. The record holds the wall as the cylinder it is (one face, +/// closed along its seam). +#[test] +fn extruded_circles_go_as_cylinders() { + use solidcraft_smlib::flat; + let body = cylinder(v(0., 50., -60.), v(0., 0., 1.), 40.0, 120.0).unwrap(); + let record = super::brep_record(&body).unwrap(); + let walls = record.faces.iter().filter(|f| matches!(f.surface, solidcore_record::brep::Surface::Cylinder { .. })).count(); + assert_eq!((walls, record.faces.len()), (1, 3)); + let arrays = solidcraft_smlib::import::arrays(&record, true).unwrap(); + let kinds = &arrays.ints[&flat::FACE_SURFACE_TYPE]; + assert!(kinds.iter().all(|k| *k == i64::from(flat::SURFACE_PLANE) || *k == i64::from(flat::SURFACE_CYLINDER)), "{kinds:?}"); + assert_eq!(kinds.iter().filter(|k| **k == i64::from(flat::SURFACE_CYLINDER)).count(), record.faces.len() - 2); + // A box cut by it is a valid SMLib solid (as a spline it had edges 0.78 mm off its faces). + let block = box_solid(v(-14., 0., -14.), v(14., 20., 14.)).unwrap(); + let r = super::smlib_body(&block).unwrap().boolean(&super::smlib_body(&body).unwrap(), solidcraft_smlib::BooleanOp::Subtract).unwrap().unwrap(); + let check = r.check(solidcraft_smlib::CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{check}"); +} + +/// A cavity cut out of a block: SMLib's result lists the cavity's faces on the void's side with +/// mixed orientations, and every one of them comes back. +#[test] +fn a_cavity_comes_back_from_smlib() { + let block = box_solid(v(0., 0., 0.), v(40., 40., 40.)).unwrap(); + let cavity = box_solid(v(25., 25., 25.), v(30., 30., 30.)).unwrap(); + let r = super::smlib_body(&block).unwrap().boolean(&super::smlib_body(&cavity).unwrap(), solidcraft_smlib::BooleanOp::Subtract).unwrap().unwrap(); + let back = super::body_from_smlib(&r).unwrap(); + assert_eq!((back.shell_count(), back.face_count()), (2, 12)); + let got = super::smlib_body(&back).unwrap().volume(1e-7).unwrap(); + assert!((got - (64_000.0 - 125.0)).abs() < 1e-6, "{got}"); +} + +/// A square revolved off the axis through three quarters of a turn: its flat ends are planes +/// square to the axis (annular sectors), its walls cylinders. +#[test] +fn a_revolved_annulus_goes_with_its_flat_faces() { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; + let square = + Region2 { outer: Loop2::polygon(&[Vec2::new(4., 12.), Vec2::new(12., 12.), Vec2::new(12., 20.), Vec2::new(4., 20.)]), holes: vec![] }; + let plane = Plane { y: v(0., 0., 1.), ..Plane::XZ }; + let body = crate::revolve(&plane, &[square], Vec2::ZERO, Vec2::Y, 1.5 * PI).unwrap().pop().unwrap(); + let s = super::smlib_body(&body).unwrap(); + let check = s.check(solidcraft_smlib::CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{check}"); + let exact = 0.75 * PI * (144.0 - 16.0) * 8.0; + let got = s.volume(1e-7).unwrap(); + assert!((got - exact).abs() <= 1e-6 * exact, "SMLib volume {got}, exact {exact}"); +} +/// A drill point (a cone ending in its apex) through SMLib and back measures as it went in. +#[test] +fn a_cone_apex_comes_back_measuring_as_it_went() { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; + let r = 3.4; + let h = r / (59f64.to_radians()).tan(); + let profile = + Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 3.0 - h), Vec2::new(r, 3.0), Vec2::new(r, 16.0), Vec2::new(0.0, 16.0)]), holes: vec![] }; + let plane = Plane { origin: v(20.0, 15.0, 0.0), x: v(1., 0., 0.), y: v(0., 0., 1.) }; + let tool = crate::revolve(&plane, &[profile], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU).unwrap().pop().unwrap(); + let back = super::body_from_smlib(&super::smlib_body(&tool).unwrap()).unwrap(); + let (m0, m1) = (crate::measure(&tool).unwrap(), crate::measure(&back).unwrap()); + assert!((m1.area - m0.area).abs() < 1e-5 * m0.area, "area {} -> {}", m0.area, m1.area); + assert!((m1.volume - m0.volume).abs() < 1e-5 * m0.volume, "volume {} -> {}", m0.volume, m1.volume); +} + +/// A revolved cap's dome comes back from SMLib as a rational spline closed around the axis, +/// bounded by its rim, its seam both ways and the pole; a ball centred on the dome near the seam +/// cuts a hole in it. Opened at the pole the outer loop spans v in [-1, 0] while the hole +/// projects into [0, 1]: the mesh covered the hole as well (+1694 mm³) until the hole is moved +/// a period to lie inside the outer loop (tangency-labs/solidcore#433). +#[test] +fn a_hole_in_a_dome_by_its_seam_measures_as_smlib_cuts_it() { + use solidcraft_smlib::sweeps::Curve; + let a0 = 6.9f64.atan2(26.0); + let line = |a: [f64; 2], b: [f64; 2]| Curve::Line { start: [a[0], 0.0, a[1]], end: [b[0], 0.0, b[1]] }; + let profile = [ + line([0., 0.], [7., 0.]), + line([7., 0.], [7., 20.]), + line([7., 20.], [26., 39.]), + Curve::Arc { center: [0., 0., 32.1], axis: [0., -1., 0.], reference: [1., 0., 0.], radius: 26.9, start: a0, end: PI / 2.0 }, + line([0., 59.], [0., 0.]), + ]; + // Turned about -z, as the engine revolves the sketch (its normal is -y): the dome's v runs + // clockwise seen from above, which puts the hole at v near 1. + let revolved = solidcraft_smlib::Brep::revolve(&profile, [0.; 3], [0., 0., -1.], std::f64::consts::TAU, true).unwrap(); + let cap = super::smlib_body(&super::body_from_smlib(&revolved).unwrap()).unwrap(); + let ball = super::smlib_body(&sphere(v(17.38629136, 4.658642729, 52.090595805), 4.0).unwrap()).unwrap(); + let cut = cap.tagged(0).unwrap().boolean(&ball.tagged(1).unwrap(), solidcraft_smlib::BooleanOp::Subtract).unwrap().unwrap(); + // The cap less the lens of two spheres, radii 4 and 26.9 at 26.9 apart. + let (big, small) = (26.9f64, 4.0f64); + let cap_volume = PI * (49.0 * 20.0 + (26f64.powi(3) - 343.0) / 3.0 + big * big * 20.0 - (big.powi(3) - 6.9f64.powi(3)) / 3.0); + let lens = PI * small.powi(2) * (8.0 * big * small - 3.0 * small * small) / (12.0 * big); + let exact = cap_volume - lens; + let got = cut.volume(1e-7).unwrap(); + assert!((got - exact).abs() <= 1e-6 * exact, "SMLib volume {got}, exact {exact}"); + let back = super::body_from_smlib(&cut).unwrap(); + let m = crate::measure(&back).unwrap(); + assert!((m.volume - exact).abs() <= 2e-4 * exact, "mesh volume {} ({}), exact {exact}", m.volume, m.measured_by); +} diff --git a/crates/kernel/src/numbered.rs b/crates/kernel/src/numbered.rs index d713ef67a..475ace9d4 100644 --- a/crates/kernel/src/numbered.rs +++ b/crates/kernel/src/numbered.rs @@ -4,9 +4,10 @@ //! numbers are defined here: the segments of the caller's regions in order, each region its outer //! loop and then its holes ([`profile_loops`]). +use solidcraft_geom::prelude::*; use std::collections::BTreeSet; -use solidcraft_geom::{Loop2, Region2, Seg2}; +use solidcore_record::{Loop2, Region2, Seg2}; /// The loops of `regions` in profile order: each region's outer loop, then its holes. pub(crate) fn profile_loops(regions: &[Region2]) -> impl Iterator { @@ -151,6 +152,19 @@ impl NumberedLoop { out } + /// The same loop started at a segment `joins` does not join to the one before it, so no run of + /// joined segments wraps round the loop's end (as it is when every segment joins the next). + pub(crate) fn starting_a_run(&self, joins: impl Fn(&Seg2, &Seg2) -> bool) -> NumberedLoop { + let segs = &self.lp.segs; + let n = segs.len(); + let joined = |i: usize| matches!((segs.get((i + n - 1) % n), segs.get(i)), (Some(s), Some(t)) if joins(s, t)); + let mut out = self.clone(); + if let Some(k) = (0..n).find(|&i| !joined(i)) { + out.rotate_left(k); + } + out + } + /// Split segment `k` in half, both halves over what it ran over. fn split_half(&mut self, k: usize) { if k >= self.lp.segs.len() || k >= self.from.len() { diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rs index 264b82387..bd65c92e4 100644 --- a/crates/kernel/src/offset.rs +++ b/crates/kernel/src/offset.rs @@ -1,19 +1,13 @@ -//! Topology-preserving face offsets for bodies made of planes and cylinders (shells, offset -//! faces). Each face moves along its outward normal by its own distance: a plane is translated, -//! a cylinder changes radius about its axis. Every vertex and edge goes to where its faces' -//! moved surfaces meet; edges are lines or circular arcs. This is exact when the moved -//! surfaces meet the way the old ones did (prismatic parts, bosses, fillets between walls). -//! A corner where more than three planes meet, whose moved planes miss a common point (a -//! floor falling to a drain, a pyramid's apex), becomes several corners joined by short edges. -//! Anything else is refused, so callers can fall back. +//! What analytic surface a face of the schema 4 record lies on, with its outward side, and the +//! faces that continue a chosen face on the same surface (a hole's wall stored in halves). +//! Moving faces along their normals (offset faces, shell, draft) is SMLib's +//! (`crate::offset_backend`). -use std::collections::HashMap; +use solidcore_record::Vec3; +use solidcore_record::brep::{Brep, Frame, Loop, Surface}; +use solidcraft_geom::prelude::*; -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, builder}; - -use crate::body::{Body, Solid, from_p3, p3}; -use crate::{KernelError, Result, guard}; +use crate::body::Body; #[derive(Clone, Copy, Debug)] pub(crate) enum Surf { @@ -28,1420 +22,116 @@ pub(crate) enum Surf { /// outward normal points away from the axis. Cone { v: Vec3, a: Vec3, half: f64, convex: bool }, /// Axis point and unit axis, the tube's centre circle (radius `big` at height `h` along the - /// axis) and the tube radius; `big` is negative on the inner sheet of a spindle torus, - /// whose meridian circle's centre lies across the axis. `convex` when the outward normal - /// points away from the tube's centre. + /// axis) and the tube radius; `convex` when the outward normal points away from the tube's + /// centre. Torus { o: Vec3, a: Vec3, big: f64, h: f64, r: f64, convex: bool }, } -/// The centre of a torus tube nearest `p`. -fn tube_centre(o: Vec3, a: Vec3, big: f64, h: f64, p: Vec3) -> Option { - let w = p - o; - let u = (w - a * w.dot(a)).normalized()?; - Some(o + a * h + u * big) +fn axes(f: &Frame) -> Option<(Vec3, Vec3)> { + let (x, y) = (Vec3::from(f.x_axis), Vec3::from(f.y_axis)); + Some((Vec3::from(f.origin), x.cross(y).normalized()?)) +} + +/// What surface face `face` of the record `b` lies on, as its record says (planes, cylinders, +/// cones, spheres and tori; `None` for a free-form face). The record's analytic surfaces have +/// their natural normals away from their axis or centre, so a face is convex when its shell +/// uses its natural side. +pub(crate) fn surf_of(b: &Brep, face: usize) -> Option { + let f = b.faces.get(face)?; + // `forward` is about the face's NURBS form, which may run against its surface. + let out = crate::assemble::natural_out(b, face)? != solidcraft_geom::brep::label::form_turns(f)?; + let sign = if out { 1.0 } else { -1.0 }; + Some(match &f.surface { + Surface::Plane { origin, u_axis, v_axis } => { + let n = Vec3::from(*u_axis).cross(Vec3::from(*v_axis)).normalized()? * sign; + Surf::Plane { n, d: n.dot(Vec3::from(*origin)) } + } + Surface::PlaneThrough { origin, u_point, v_point } => { + let o = Vec3::from(*origin); + let n = (Vec3::from(*u_point) - o).cross(Vec3::from(*v_point) - o).normalized()? * sign; + Surf::Plane { n, d: n.dot(o) } + } + Surface::Cylinder { frame, radius } => { + let (o, a) = axes(frame)?; + Surf::Cylinder { o, a, r: *radius, convex: out } + } + Surface::Sphere { frame, radius } => Surf::Sphere { c: Vec3::from(frame.origin), r: *radius, convex: out }, + Surface::BallPatch { center, radius } => Surf::Sphere { c: Vec3::from(*center), r: *radius, convex: out }, + Surface::Cone { frame, radius_at_origin, half_angle } => { + let (o, z) = axes(frame)?; + let apex = o + z * (-radius_at_origin / half_angle.tan()); + let a = if *half_angle > 0.0 { z } else { -z }; + Surf::Cone { v: apex, a, half: half_angle.abs(), convex: out } + } + Surface::Torus { frame, major_radius, minor_radius, .. } => { + let (o, a) = axes(frame)?; + Surf::Torus { o, a, big: *major_radius, h: 0.0, r: *minor_radius, convex: out } + } + Surface::Spline { .. } | Surface::RationalSpline { .. } | Surface::PlacedRevolution { .. } => return None, + }) } impl Surf { - /// Outward unit normal of the surface at `p` (on or near it). - pub(crate) fn normal(&self, p: Vec3) -> Option { - match *self { - Surf::Plane { n, .. } => Some(n), - Surf::Cylinder { o, a, convex, .. } => { - let v = p - o; - let radial = (v - a * v.dot(a)).normalized()?; - Some(if convex { radial } else { -radial }) + /// Whether `other` is this surface, with the same outward side, within `tol`. + pub(crate) fn same(&self, other: &Surf, tol: f64) -> bool { + match (*self, *other) { + (Surf::Plane { n, d }, Surf::Plane { n: m, d: e }) => n.dot(m) > 1.0 - 1e-9 && (d - e).abs() < tol, + (Surf::Cylinder { o, a, r, convex }, Surf::Cylinder { o: o2, a: a2, r: r2, convex: c2 }) => { + a.dot(a2).abs() > 1.0 - 1e-9 && (r - r2).abs() < tol && convex == c2 && (o2 - o - a * (o2 - o).dot(a)).len() < tol } - Surf::Sphere { c, convex, .. } => { - let radial = (p - c).normalized()?; - Some(if convex { radial } else { -radial }) + (Surf::Sphere { c, r, convex }, Surf::Sphere { c: c2, r: r2, convex: k2 }) => c.dist(c2) < tol && (r - r2).abs() < tol && convex == k2, + (Surf::Cone { v, a, half, convex }, Surf::Cone { v: v2, a: a2, half: h2, convex: k2 }) => { + v.dist(v2) < tol && a.dot(a2) > 1.0 - 1e-9 && (half - h2).abs() < 1e-9 && convex == k2 } - Surf::Cone { v, a, half, convex } => { - let w = p - v; - let q = (w - a * w.dot(a)).normalized()?; - let n = q * half.cos() - a * half.sin(); - Some(if convex { n } else { -n }) + (Surf::Torus { o, a, big, h, r, convex }, Surf::Torus { o: o2, a: a2, big: b2, h: h2, r: r2, convex: k2 }) => { + (o + a * h).dist(o2 + a2 * h2) < tol && a.dot(a2).abs() > 1.0 - 1e-9 && (big - b2).abs() < tol && (r - r2).abs() < tol && convex == k2 } - Surf::Torus { o, a, big, h, convex, .. } => { - let n = (p - tube_centre(o, a, big, h, p)?).normalized()?; - Some(if convex { n } else { -n }) - } - } - } - /// The gradient of [`Surf::dist`] (the normal before orientation). - fn grad(&self, p: Vec3) -> Option { - match *self { - Surf::Plane { n, .. } => Some(n), - Surf::Cylinder { convex, .. } | Surf::Sphere { convex, .. } | Surf::Cone { convex, .. } | Surf::Torus { convex, .. } => { - self.normal(p).map(|n| if convex { n } else { -n }) - } - } - } - fn moved(&self, s: f64) -> Option { - match *self { - Surf::Plane { n, d } => Some(Surf::Plane { n, d: d + s }), - Surf::Cylinder { o, a, r, convex } => { - let r2 = if convex { r + s } else { r - s }; - (r2 > 1e-9).then_some(Surf::Cylinder { o, a, r: r2, convex }) - } - Surf::Sphere { c, r, convex } => { - let r2 = if convex { r + s } else { r - s }; - (r2 > 1e-9).then_some(Surf::Sphere { c, r: r2, convex }) - } - // Moving a cone along its normal moves its apex along the axis. - Surf::Cone { v, a, half, convex } => { - let s = if convex { s } else { -s }; - let sh = half.sin(); - (sh > 1e-9).then_some(Surf::Cone { v: v - a * (s / sh), a, half, convex }) - } - Surf::Torus { o, a, big, h, r, convex } => { - let r2 = if convex { r + s } else { r - s }; - (r2 > 1e-9).then_some(Surf::Torus { o, a, big, h, r: r2, convex }) - } - } - } - fn dist(&self, p: Vec3) -> f64 { - match *self { - Surf::Plane { n, d } => n.dot(p) - d, - Surf::Cylinder { o, a, r, .. } => { - let v = p - o; - (v - a * v.dot(a)).len() - r - } - Surf::Sphere { c, r, .. } => p.dist(c) - r, - Surf::Cone { v, a, half, .. } => { - let w = p - v; - let h = w.dot(a); - (w - a * h).len() * half.cos() - h * half.sin() - } - Surf::Torus { o, a, big, h, r, .. } => tube_centre(o, a, big, h, p).map(|c| p.dist(c) - r).unwrap_or(f64::INFINITY), - } - } - /// The affine map taking this surface onto `to` (same kind, same axis). - fn map_to(&self, to: &Surf) -> Option { - match (*self, *to) { - (Surf::Sphere { c, r, .. }, Surf::Sphere { r: r2, .. }) => { - let k = r2 / r; - let t = c * (1.0 - k); - Some(mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z)) * mt::Matrix4::from_scale(k)) - } - (Surf::Cone { v, .. }, Surf::Cone { v: v2, .. }) => { - let t = v2 - v; - Some(mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z))) - } - (Surf::Plane { n, d }, Surf::Plane { d: d2, .. }) => { - let t = n * (d2 - d); - Some(mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z))) - } - (Surf::Cylinder { o, a, r, .. }, Surf::Cylinder { r: r2, .. }) => { - // Scale by k across the axis: x ↦ o + k (x − o) + (1 − k) a a·(x − o). - let k = r2 / r; - let m = |i: usize, j: usize| { - let (ai, aj) = ([a.x, a.y, a.z][i], [a.x, a.y, a.z][j]); - (if i == j { k } else { 0.0 }) + (1.0 - k) * ai * aj - }; - let lin = [[m(0, 0), m(0, 1), m(0, 2)], [m(1, 0), m(1, 1), m(1, 2)], [m(2, 0), m(2, 1), m(2, 2)]]; - let ov = [o.x, o.y, o.z]; - let t: Vec = (0..3).map(|i| ov[i] - (0..3).map(|j| lin[i][j] * ov[j]).sum::()).collect(); - // Column-major. - Some(mt::Matrix4::new( - lin[0][0], - lin[1][0], - lin[2][0], - 0.0, - lin[0][1], - lin[1][1], - lin[2][1], - 0.0, - lin[0][2], - lin[1][2], - lin[2][2], - 0.0, - *t.first()?, - *t.get(1)?, - *t.get(2)?, - 1.0, - )) - } - _ => None, + _ => false, } } } -fn fail(m: &str) -> KernelError { - KernelError::Failed(format!("offset: {m}")) -} - -/// Points and outward normals sampled over a face (boundary and a grid inside its -/// parameter box). -fn samples(f: &mt::Face) -> Vec<(Vec3, Vec3)> { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let surf = f.oriented_surface(); - let mut uv: Vec<(f64, f64)> = Vec::new(); - for w in f.boundaries() { - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..5 { - // The previous point's parameters as a hint, unless that lands elsewhere (a - // singular point such as a pole holds the search). - let q = c.subs(t0 + (t1 - t0) * k as f64 / 5.0); - let near = |x: (f64, f64)| from_p3(surf.subs(x.0, x.1)).dist(from_p3(q)) < 1e-6 * (1.0 + from_p3(q).len()); - let found = surf - .search_nearest_parameter(q, uv.last().copied(), 50) - .filter(|x| near(*x)) - .or_else(|| surf.search_nearest_parameter(q, None, 100).filter(|x| near(*x))); - if let Some(x) = found { - uv.push(x); - } - } - } - } - let Some(&(u0, v0)) = uv.first() else { return Vec::new() }; - let (mut lo, mut hi) = ((u0, v0), (u0, v0)); - for (u, v) in &uv { - lo = (lo.0.min(*u), lo.1.min(*v)); - hi = (hi.0.max(*u), hi.1.max(*v)); - } - for i in 0..=4 { - for j in 0..=4 { - uv.push((lo.0 + (hi.0 - lo.0) * i as f64 / 4.0, lo.1 + (hi.1 - lo.1) * j as f64 / 4.0)); - } - } - // Parameter steps for checking that the normal is steady (not at a cone's apex). - let (du, dv) = (((hi.0 - lo.0) * 1e-6).max(1e-9), ((hi.1 - lo.1) * 1e-6).max(1e-9)); - let nrm = |u: f64, v: f64| { - let n = surf.normal(u, v); - Vec3::new(n.x, n.y, n.z).normalized() - }; - uv.iter() - .filter_map(|(u, v)| { - let n = nrm(*u, *v)?; - let steady = - [nrm(*u + du, *v), nrm(*u - du, *v), nrm(*u, *v + dv), nrm(*u, *v - dv)].iter().all(|m| m.is_some_and(|m| m.dot(n) > 1.0 - 1e-6)); - steady.then(|| (from_p3(surf.subs(*u, *v)), n)) - }) - .collect() -} - -/// What surface a face lies on (planes and cylinders only). -pub(crate) fn surf_of(f: &mt::Face, tol: f64) -> Option { - if let mt::Surface::Plane(pl) = f.oriented_surface() { - let n = pl.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - return Some(Surf::Plane { n, d: n.dot(from_p3(pl.origin())) }); - } - let s = samples(f); - if let Some(t) = torus_of(f, &s, tol) { - return Some(t); - } - let (p0, n0) = *s.first()?; - // Flat though not built as a plane (a radial line swept round an axis). - if s.iter().all(|(p, n)| n.dot(n0) > 1.0 - 1e-9 && (*p - p0).dot(n0).abs() < tol) { - return Some(Surf::Plane { n: n0, d: n0.dot(p0) }); - } - // The normal most square to the first (a half cylinder's two ends are opposite). - let far = s.iter().map(|x| x.1).min_by(|a, b| a.dot(n0).abs().total_cmp(&b.dot(n0).abs()))?; - let Some(a) = n0.cross(far).normalized() else { return sphere_or_cone(&s, tol) }; - if s.iter().any(|(_, n)| n.dot(a).abs() > 1e-6) { - return sphere_or_cone(&s, tol); - } - // The axis: where the normal lines through two samples meet (seen along a). - let (p1, n1) = *s.iter().min_by(|x, y| x.1.dot(n0).abs().total_cmp(&y.1.dot(n0).abs()))?; - // p0 + t0 n0 = p1 + t1 n1 (projected): solve in the plane ⟂ a. - let w = p1 - p0; - let c = n0.dot(n1); - let den = 1.0 - c * c; - if den.abs() < 1e-9 { - return None; - } - let t0 = (w.dot(n0) - c * w.dot(n1)) / den; - let o = p0 + n0 * t0; - let o = o - a * (o - p0).dot(a); - let r = t0.abs(); - // Outward normal away from the axis: p = o + r n (t0 < 0 means o = p − r n). - let convex = t0 < 0.0; - let cyl = Surf::Cylinder { o, a, r, convex }; - let ok = s.iter().all(|(p, n)| cyl.dist(*p).abs() < tol && cyl.normal(*p).is_some_and(|m| m.dot(*n) > 1.0 - 1e-6)); - ok.then_some(cyl) -} - -/// A torus: a surface of revolution whose normals (in the meridian plane) all point from one -/// circle, the tube's centre, at one distance. -fn torus_of(f: &mt::Face, s: &[(Vec3, Vec3)], tol: f64) -> Option { - let mt::Surface::RevolutedCurve(rc) = f.surface() else { return None }; - if *rc.transform() != ::one() { - return None; - } - let (o, ax) = (from_p3(rc.entity().origin()), rc.entity().axis()); - let a = Vec3::new(ax.x, ax.y, ax.z).normalized()?; - // Meridian coordinates: ρ − r n_ρ = R and h − r n_h = h0 for every sample, least squares - // in (R, h0, r). - let mut m = [[0.0f64; 3]; 3]; - let mut rhs = [0.0f64; 3]; - for (p, n) in s { - let w = *p - o; - let hh = w.dot(a); - let radial = w - a * hh; - let u = radial.normalized()?; - for (row, val) in [([1.0, 0.0, n.dot(u)], radial.len()), ([0.0, 1.0, n.dot(a)], hh)] { - for i in 0..3 { - for j in 0..3 { - m[i][j] += row[i] * row[j]; - } - rhs[i] += row[i] * val; - } - } - } - let x = crate::polyhedron::solve3_pub(m, rhs)?; - let (big, h, r) = (x[0], x[1], x[2]); - // A spindle torus also has an inner sheet: a barrel revolved from an arc whose - // centre is across the axis. Its signed ring radius is negative; retain that sign - // so distances, normals and the moved meridian use the centre on the opposite side. - if !(big.abs() > 1e-9 && r.abs() > 1e-9) { - return None; - } - let t = Surf::Torus { o, a, big, h, r: r.abs(), convex: r > 0.0 }; - s.iter().all(|(p, n)| t.dist(*p).abs() < tol && t.normal(*p).is_some_and(|m| m.dot(*n) > 1.0 - 1e-6)).then_some(t) -} - -/// A sphere (normal lines all through one point) or a cone (tangent planes all through one -/// point, normals at one angle to an axis) through the samples. -fn sphere_or_cone(s: &[(Vec3, Vec3)], tol: f64) -> Option { - // Least squares point nearest all the normal lines: Σ (I − n nᵀ) x = Σ (I − n nᵀ) p. - let mut m = [[0.0f64; 3]; 3]; - let mut r = [0.0f64; 3]; - for (p, n) in s { - let nv = [n.x, n.y, n.z]; - let pv = [p.x, p.y, p.z]; - for i in 0..3 { - for j in 0..3 { - let a = (if i == j { 1.0 } else { 0.0 }) - nv[i] * nv[j]; - m[i][j] += a; - r[i] += a * pv[j]; - } - } - } - if let Some(x) = crate::polyhedron::solve3_pub(m, r) { - let c = Vec3::new(x[0], x[1], x[2]); - let (p0, n0) = *s.first()?; - let rad = p0.dist(c); - let convex = (p0 - c).dot(n0) > 0.0; - let sp = Surf::Sphere { c, r: rad, convex }; - if rad > tol && s.iter().all(|(p, n)| sp.dist(*p).abs() < tol && sp.normal(*p).is_some_and(|q| q.dot(*n) > 1.0 - 1e-6)) { - return Some(sp); - } - } - // Cone: the apex lies on every tangent plane, n·(v − p) = 0. - let mut m = [[0.0f64; 3]; 3]; - let mut r = [0.0f64; 3]; - for (p, n) in s { - let nv = [n.x, n.y, n.z]; - let k = n.dot(*p); - for i in 0..3 { - for j in 0..3 { - m[i][j] += nv[i] * nv[j]; - } - r[i] += nv[i] * k; - } - } - let x = crate::polyhedron::solve3_pub(m, r)?; - let v = Vec3::new(x[0], x[1], x[2]); - // Axis: from the apex toward the samples' centroid (the cone opens that way). - let cen = s.iter().fold(Vec3::ZERO, |acc, (p, _)| acc + *p) * (1.0 / s.len() as f64); - // Normals make a constant angle with the axis: fit it from three spread normals. - let n0 = s.first()?.1; - let n1 = s.iter().map(|x| x.1).max_by(|a, b| (*a - n0).len().total_cmp(&(*b - n0).len()))?; - let n2 = s.iter().map(|x| x.1).max_by(|a, b| (*a - n0).cross(n1 - n0).len().total_cmp(&(*b - n0).cross(n1 - n0).len()))?; - let mut a = (n1 - n0).cross(n2 - n0).normalized()?; - if a.dot(cen - v) < 0.0 { - a = -a; - } - let half = n0.dot(a).abs().clamp(0.0, 1.0).asin(); - if !(half > 1e-3 && half < std::f64::consts::FRAC_PI_2 - 1e-3) { - return None; - } - let (p0, n0) = *s.first()?; - let q = { - let w = p0 - v; - (w - a * w.dot(a)).normalized()? - }; - let convex = n0.dot(q) > 0.0; - let cone = Surf::Cone { v, a, half, convex }; - s.iter().all(|(p, n)| cone.dist(*p).abs() < tol && cone.normal(*p).is_some_and(|m| m.dot(*n) > 1.0 - 1e-6)).then_some(cone) -} - -/// Move `p` (on all of `old`) onto the moved surfaces `new`: the smallest displacement δ with -/// n_i · δ = s_i for each face's normal n_i at p, then checked against the moved surfaces. -fn move_point(p: Vec3, old: &[Surf], shifts: &[f64], new: &[Surf], tol: f64) -> Option { - let ns: Vec = old.iter().map(|sf| sf.normal(p)).collect::>()?; - let mut q = p + span_step(&ns, shifts)?; - // The step is exact for planes; a curved face meeting another at an angle needs a few - // Newton steps onto the moved surfaces. - for _ in 0..30 { - let d: Vec = new.iter().map(|sf| sf.dist(q)).collect(); - if d.iter().all(|x| x.abs() < tol) { - return Some(q); - } - let gs: Vec = new.iter().map(|sf| sf.grad(q)).collect::>()?; - let rhs: Vec = d.iter().map(|x| -x).collect(); - q += span_step(&gs, &rhs)?; - } - new.iter().all(|sf| sf.dist(q).abs() < tol).then_some(q) -} - -/// The smallest move `v` (in the span of `ns`) with `n_i · v = s_i` (least squares). -fn span_step(ns: &[Vec3], s: &[f64]) -> Option { - // Orthonormal basis of the normals' span (tangent faces share a normal). - let mut basis: Vec = Vec::new(); - for n in ns { - let mut v = *n; - for e in &basis { - v = v - *e * v.dot(*e); - } - if let Some(u) = v.normalized().filter(|_| v.len() > 1e-6) { - basis.push(u); - } - } - // Least squares in the span: rows n_i · e_k, right-hand sides s_i. - let r = basis.len(); - let mut m = [[0.0f64; 3]; 3]; - let mut rhs = [0.0f64; 3]; - for (n, si) in ns.iter().zip(s) { - let row: Vec = basis.iter().map(|e| n.dot(*e)).collect(); - for i in 0..r { - for j in 0..r { - m[i][j] += row[i] * row[j]; - } - rhs[i] += row[i] * si; - } - } - // Pad unused dimensions with the identity. - for (i, row) in m.iter_mut().enumerate().skip(r) { - row[i] = 1.0; - } - let c = crate::polyhedron::solve3_pub(m, rhs)?; - let mut v = Vec3::ZERO; - for (k, e) in basis.iter().enumerate() { - v += *e * c[k]; - } - Some(v) -} - -/// Most faces round one corner that [`split_corner`] takes on. -const MAX_SPLIT_FACES: usize = 48; - -/// The corners in place of a corner where more than three planar faces meet and whose moved -/// planes miss a common point (a hip floor's corner, a pyramid's apex): each new corner with -/// the faces through it. Corners sharing two faces are joined by a new edge on those faces. -/// Only corners whose edges are all convex or all concave: the faces there bound a convex -/// region (the body's side or the outside's), and after the move its corners are the points on -/// three moved planes inside all the others. -fn split_corner( - v: &mt::Vertex, - at: &[usize], - faces: &[mt::Face], - efaces: &HashMap>, - old: &[Surf], - new: &[Surf], - size: f64, -) -> Option)>> { - if at.len() < 4 || at.len() > MAX_SPLIT_FACES { - return None; - } - let p = from_p3(v.point()); - // (face, outward normal, old offset, moved offset). - let planes: Vec<(usize, Vec3, f64, f64)> = at - .iter() - .map(|i| match (old.get(*i)?, new.get(*i)?) { - (Surf::Plane { n, d }, Surf::Plane { d: d2, .. }) => Some((*i, *n, *d, *d2)), - _ => None, - }) - .collect::>()?; - let normal = |fi: usize| planes.iter().find(|x| x.0 == fi).map(|x| x.1); - // Edge kinds round the corner: a face's loop runs counter-clockwise about its outward - // normal, so its inside is to the left; the edge is convex when the face beyond it falls - // away from there. - let mut sign = 0.0f64; - let mut mixed = false; - let mut pairs: Vec<(usize, usize)> = Vec::new(); - for &(fi, na, ..) in &planes { - for w in faces.get(fi)?.boundaries() { - for e in w.edge_iter() { - if e.front().id() != v.id() && e.back().id() != v.id() { - continue; - } - let fb = efaces.get(&e.id())?.iter().copied().find(|j| *j != fi)?; - pairs.push((fi, fb)); - let dir = (from_p3(e.back().point()) - from_p3(e.front().point())).normalized()?; - let s = normal(fb)?.dot(na.cross(dir)); - if s.abs() < 1e-9 { - continue; - } - if sign * s < 0.0 { - mixed = true; - } - sign = s.signum(); - } - } - } - if sign == 0.0 { - return None; - } - // Which triples of faces may meet at a new corner. All convex or all concave: any triple - // whose point is inside all the other moved planes. Mixed (a saddle, such as a box on a - // box that overhangs its side): the faces round the corner in order, and each new corner - // on three faces in a row (the two new edges on the middle face meet there). A saddle's - // faces bound no convex region, so a right corner can be outside another face's moved - // plane, and the inside-all-the-others test does not apply. What keeps a corner in place - // is that it is where its middle face's two new edges meet; a corner past the far end of - // one of the corner's edges turns that edge round, and a face whose loops cross after the - // move is refused (both checked in `offset_body`). - let triples: Vec<[usize; 3]> = if mixed { - let ring = face_ring(&pairs, planes.len())?; - let n = ring.len(); - (0..n).map(|i| [ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]]).collect() - } else { - let mut t = Vec::new(); - for ia in 0..planes.len() { - for ib in ia + 1..planes.len() { - for ic in ib + 1..planes.len() { - t.push([planes[ia].0, planes[ib].0, planes[ic].0]); - } - } - } - t - }; - let plane_of = |fi: usize| planes.iter().find(|x| x.0 == fi); - // Convex: the body's side, n·x ≤ d; concave: the outside's, n·x ≥ d. - let side = -sign; - let merge = size * 1e-6; - let mut nodes: Vec<(Vec3, Vec)> = Vec::new(); - for [fa, fb, fc] in triples { - let (a, b, c) = (plane_of(fa)?, plane_of(fb)?, plane_of(fc)?); - let den = a.1.dot(b.1.cross(c.1)); - if den.abs() < 1e-9 { - continue; - } - let x = (b.1.cross(c.1) * a.3 + c.1.cross(a.1) * b.3 + a.1.cross(b.1) * c.3) * (1.0 / den); - if !x.is_finite() || x.dist(p) > size || (!mixed && planes.iter().any(|q| side * (q.1.dot(x) - q.3) > merge)) { - continue; - } - let fs = [fa, fb, fc]; - match nodes.iter_mut().find(|(q, _)| q.dist(x) < merge) { - Some((_, nf)) => { - for f in fs { - if !nf.contains(&f) { - nf.push(f); - } - } - } - None => nodes.push((x, fs.to_vec())), - } - } - // Every face keeps a corner here, and every edge an end. - if planes.iter().any(|q| !nodes.iter().any(|(_, nf)| nf.contains(&q.0))) - || pairs.iter().any(|(x, y)| !nodes.iter().any(|(_, nf)| nf.contains(x) && nf.contains(y))) - { - return None; - } - // Each corner where its planes meet best (least squares, for planes meeting at one point - // to within the merge distance). - for (q, nf) in nodes.iter_mut() { - let (ns, ss): (Vec, Vec) = nf.iter().filter_map(|f| planes.iter().find(|x| x.0 == *f)).map(|x| (x.1, x.3 - x.2)).unzip(); - *q = p + span_step(&ns, &ss)?; - } - Some(nodes) -} - -/// The faces round a corner in order, from the pairs of faces on each of its edges: `None` -/// unless they form one simple ring of `count` faces (each face meets the corner once, between -/// exactly two neighbours). -fn face_ring(pairs: &[(usize, usize)], count: usize) -> Option> { - let mut next: HashMap> = HashMap::new(); - for &(a, b) in pairs { - for (x, y) in [(a, b), (b, a)] { - let ns = next.entry(x).or_default(); - if !ns.contains(&y) { - ns.push(y); - } - } - } - if next.len() != count || next.values().any(|ns| ns.len() != 2) { - return None; - } - let first = *next.keys().min()?; - let mut ring = vec![first]; - let mut prev = first; - let mut cur = *next.get(&first)?.first()?; - while cur != first { - if ring.len() >= count { - return None; - } - ring.push(cur); - let ns = next.get(&cur)?; - let to = if ns[0] == prev { ns[1] } else { ns[0] }; - prev = cur; - cur = to; - } - (ring.len() == count).then_some(ring) -} - -/// The corners of a split corner (see [`split_corner`]) on face `face`, in order from corner -/// `from` to corner `to`, along the new edges between them. -fn split_path(nodes: &[(Vec3, Vec)], face: usize, from: usize, to: usize) -> Option> { - let joined = |x: usize, y: usize| { - let (Some((_, a)), Some((_, b))) = (nodes.get(x), nodes.get(y)) else { return false }; - a.contains(&face) && b.contains(&face) && a.iter().filter(|f| b.contains(f)).count() >= 2 - }; - // Breadth first; `prev` leads back to `from`. - let mut prev: Vec> = vec![None; nodes.len()]; - let mut queue = std::collections::VecDeque::from([from]); - let mut seen = vec![false; nodes.len()]; - *seen.get_mut(from)? = true; - while let Some(x) = queue.pop_front() { - if x == to { - let mut path = vec![to]; - let mut cur = to; - while let Some(p) = prev.get(cur).copied().flatten() { - path.push(p); - cur = p; - } - path.reverse(); - return Some(path); - } - for y in 0..nodes.len() { - if !seen.get(y).copied().unwrap_or(true) && joined(x, y) { - *seen.get_mut(y)? = true; - *prev.get_mut(y)? = Some(x); - queue.push_back(y); - } - } - } - None -} - -/// A line or circular arc through an edge (by samples): `None` for other curves. -/// Maximum straight edges per face checked pairwise for crossings. -const MAX_CROSSING_EDGES: usize = 2000; - -/// Where the moved straight edges of a planar face cross each other (or a loop of straight -/// edges turns round), if they do. Faces next to a collapsed round are left to the other checks. -fn crossed_loops( - faces: &[mt::Face], - old: &[Surf], - pos: &dyn Fn(&mt::Vertex, &mt::Edge) -> Option, - edge_collapsed: &dyn Fn(&mt::Edge) -> bool, - size: f64, -) -> Option { - let eps = size * 1e-9; - for (f, sf) in faces.iter().zip(old) { - let Surf::Plane { n, .. } = *sf else { continue }; - if f.edge_iter().any(|e| edge_collapsed(&e)) { - continue; - } - let (u, w) = (n.any_perp(), n.cross(n.any_perp())); - let flat = |p: Vec3| (p.dot(u), p.dot(w)); - // Straight edges as (vertex ids, new ends in the plane, the plane's new offset). - let mut segs: Vec<([mt::VertexID; 2], [(f64, f64); 2], f64)> = Vec::new(); - for wire in f.absolute_boundaries() { - let (mut area_old, mut area_new, mut straight) = (0.0, 0.0, true); - for e in wire.edge_iter() { - let (v0, v1) = (e.front(), e.back()); - let (Some(q0), Some(q1)) = (pos(v0, e), pos(v1, e)) else { return None }; - let (o0, o1, n0, n1) = (flat(from_p3(v0.point())), flat(from_p3(v1.point())), flat(q0), flat(q1)); - area_old += o0.0 * o1.1 - o1.0 * o0.1; - area_new += n0.0 * n1.1 - n1.0 * n0.1; - if arc_mid(e, size * 1e-6) == Some(None) { - segs.push(([v0.id(), v1.id()], [n0, n1], n.dot(q0))); - } else { - straight = false; - } - } - if straight && area_old.abs() > eps && area_old * area_new <= 0.0 { - return wire.edge_iter().next().and_then(|e| pos(e.front(), e)); - } - } - if segs.len() > MAX_CROSSING_EDGES { - continue; - } - let side = |a: (f64, f64), c: (f64, f64), p: (f64, f64)| (c.0 - a.0) * (p.1 - a.1) - (c.1 - a.1) * (p.0 - a.0); - for (i, (ia, [a0, a1], d)) in segs.iter().enumerate() { - for (ib, [b0, b1], _) in segs.iter().skip(i + 1) { - if ia.iter().any(|v| ib.contains(v)) { - continue; - } - let (s0, s1) = (side(*a0, *a1, *b0), side(*a0, *a1, *b1)); - let (t0, t1) = (side(*b0, *b1, *a0), side(*b0, *b1, *a1)); - let tol = eps * size; - if ((s0 > tol && s1 < -tol) || (s0 < -tol && s1 > tol)) && ((t0 > tol && t1 < -tol) || (t0 < -tol && t1 > tol)) { - let k = t0 / (t0 - t1); - let (x, y) = (a0.0 + (a1.0 - a0.0) * k, a0.1 + (a1.1 - a0.1) * k); - return Some(u * x + w * y + n * *d); - } - } - } - } - None -} - -pub(crate) fn arc_mid(e: &mt::Edge, tol: f64) -> Option> { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let pts: Vec = (0..=16).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 16.0))).collect(); - let (a, b, m) = (*pts.first()?, *pts.last()?, *pts.get(8)?); - if a.dist(b) < tol { - return None; - } - if pts.iter().all(|p| p.dist_to_segment(a, b) < tol) { - return Some(None); - } - let (u, v) = (b - a, m - a); - let w = u.cross(v); - let d = 2.0 * w.len2(); - if d < 1e-300 { - return None; - } - let centre = a + (v.cross(w) * u.len2() + w.cross(u) * v.len2()) * (1.0 / d); - let r = centre.dist(a); - pts.iter().all(|p| (p.dist(centre) - r).abs() < tol && (*p - centre).dot(w.normalized().unwrap_or(Vec3::Z)).abs() < tol).then_some(Some(m)) -} - -/// The body with each face moved along its outward normal by `shift(face index, normal at a -/// face point)`, keeping the topology. Faces must be planes or cylinders. The result's history -/// is over `[b]`: each face is the face it was moved from, each edge the edge it was moved from; -/// faces moved to nothing are gone, and their neighbours meet along new edges. -pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Result { - let faces: Vec = b.solid.face_iter().cloned().collect(); - let size = b.size(); - let tol = (size * 1e-7).max(1e-9); - let mut old = Vec::with_capacity(faces.len()); - let mut new = Vec::with_capacity(faces.len()); - let mut shifts = Vec::with_capacity(faces.len()); - // Faces moved to nothing (a round thinner than the move): they go, their neighbours meet. - let mut collapsed: Vec = Vec::with_capacity(faces.len()); - for (i, f) in faces.iter().enumerate() { - let sf = surf_of(f, tol * 100.0).ok_or_else(|| { - let at = samples(f).first().map(|(p, _)| format!(" (a face at [{:.2}, {:.2}, {:.2}])", p.x, p.y, p.z)).unwrap_or_default(); - fail(&format!("only bodies with planes, cylinders, cones, spheres and tori{at}")) - })?; - let n = match sf { - Surf::Plane { n, .. } => n, - Surf::Cylinder { a, .. } | Surf::Cone { a, .. } | Surf::Torus { a, .. } => a.any_perp(), - Surf::Sphere { .. } => Vec3::Z, - }; - let s = shift(i, n); - old.push(sf); - match sf.moved(s) { - Some(x) => { - new.push(x); - collapsed.push(false); - } - None => { - new.push(sf); - collapsed.push(true); - } - } - shifts.push(s); - } - let pick = |ids: &[usize]| -> (Vec, Vec, Vec) { - ( - ids.iter().filter_map(|i| old.get(*i).copied()).collect(), - ids.iter().filter_map(|i| shifts.get(*i).copied()).collect(), - ids.iter().filter_map(|i| new.get(*i).copied()).collect(), - ) - }; - // Vertex → its faces; edge → its faces. - let mut vfaces: HashMap> = HashMap::new(); - let mut efaces: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for v in f.vertex_iter() { - let e = vfaces.entry(v.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - for ed in f.edge_iter() { - let e = efaces.entry(ed.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - } - let is_collapsed = |i: usize| collapsed.get(i).copied().unwrap_or(false); - let any_collapsed = collapsed.iter().any(|c| *c); - // A collapsed face's place is taken by the faces around it (through other collapsed ones). - let mut nbrs: HashMap> = HashMap::new(); - for fs in efaces.values() { - for a in fs { - for b2 in fs { - if a != b2 { - let e = nbrs.entry(*a).or_default(); - if !e.contains(b2) { - e.push(*b2); - } - } - } - } - } - let expand = |fs: &[usize]| -> Vec { - let mut out: Vec = fs.iter().copied().filter(|i| !is_collapsed(*i)).collect(); - let mut queue: Vec = fs.iter().copied().filter(|i| is_collapsed(*i)).collect(); - let mut seen = queue.clone(); - while let Some(c) = queue.pop() { - for nb in nbrs.get(&c).into_iter().flatten() { - if is_collapsed(*nb) { - if !seen.contains(nb) { - seen.push(*nb); - queue.push(*nb); - } - } else if !out.contains(nb) { - out.push(*nb); - } - } - } - out - }; - // Each edge's ends and middle, and the faces either side. - let edge_pts: Vec<(Vec, [Vec3; 3])> = b - .solid - .edge_iter() - .filter_map(|e| { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - Some(( - efaces.get(&e.id())?.clone(), - [from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()), from_p3(c.subs((t0 + t1) / 2.0))], - )) +/// The record edges each face of `b` uses. +pub(crate) fn face_edges(b: &Brep, face: usize) -> Vec { + let mut out: Vec = b + .faces + .get(face) + .into_iter() + .flat_map(|f| &f.loops) + .flat_map(|l| match l { + Loop::Edges { edges } => edges.iter().map(|u| u.edge).collect(), + Loop::Vertex { .. } => Vec::new(), }) .collect(); - // Across the collapsed rounds next to edge `e` (its faces `fs`): a round is a strip, crossed - // to its side that shares no vertex with the edge, through further collapsed rounds. - let opposite_side = |e: &mt::Edge, fs: &[usize]| -> Vec { - let mut out: Vec = Vec::new(); - let mut seen: Vec = Vec::new(); - let mut queue: Vec<(usize, [mt::VertexID; 2])> = - fs.iter().copied().filter(|i| is_collapsed(*i)).map(|i| (i, [e.front().id(), e.back().id()])).collect(); - while let Some((cf, avoid)) = queue.pop() { - if seen.contains(&cf) { - continue; - } - seen.push(cf); - let Some(face) = faces.get(cf) else { continue }; - for side in face.edge_iter() { - if avoid.contains(&side.front().id()) || avoid.contains(&side.back().id()) { - continue; - } - for nb in efaces.get(&side.id()).into_iter().flatten().copied() { - if nb == cf || fs.contains(&nb) { - continue; - } - if is_collapsed(nb) { - queue.push((nb, [side.front().id(), side.back().id()])); - } else if !out.contains(&nb) { - out.push(nb); - } - } - } - } - out - }; - // For a point on a collapsed round touching the faces `at`: the faces it keeps (`at`'s - // own, not collapsed), and the faces along the rounds it is on, nearest `p` first. - let across = |at: &[usize], p: Vec3| -> (Vec, Vec) { - let own: Vec = at.iter().copied().filter(|i| !is_collapsed(*i)).collect(); - let mut cand: Vec<(f64, usize)> = expand(at) - .into_iter() - .filter(|nb| !own.contains(nb)) - .map(|nb| { - let d = edge_pts - .iter() - .filter(|(fs, _)| fs.contains(&nb) && fs.iter().any(|i| is_collapsed(*i))) - .flat_map(|(_, q)| q.iter().map(|x| x.dist(p))) - .fold(f64::INFINITY, f64::min); - (d, nb) - }) - .collect(); - cand.sort_by(|x, y| x.0.total_cmp(&y.0)); - (own, cand.into_iter().map(|(_, nb)| nb).collect()) - }; - let mut newpos: HashMap = HashMap::new(); - // Corners whose moved faces meet at several points (see `split_corner`). - let mut splits: HashMap)>> = HashMap::new(); - for v in b.solid.vertex_iter() { - let at = vfaces.get(&v.id()).ok_or_else(|| fail("vertex"))?; - let p = from_p3(v.point()); - let fs: Vec = if at.iter().any(|i| is_collapsed(*i)) { - // On a collapsed round: its own faces, then the faces along the rounds it is on, - // nearest first, until they fix a point. - let (mut own, cand) = across(at, p); - let rank = |ids: &[usize]| -> usize { - let mut basis: Vec = Vec::new(); - for i in ids { - let Some(nv) = old.get(*i).and_then(|sf| sf.normal(p)) else { continue }; - let mut w = nv; - for e in &basis { - w = w - *e * w.dot(*e); - } - if let Some(u) = w.normalized().filter(|_| w.len() > 1e-6) { - basis.push(u); - } - } - basis.len() - }; - for c in cand { - if rank(&own) >= 3 { - break; - } - own.push(c); - } - own - } else { - at.clone() - }; - let (o, s, n) = pick(&fs); - // A cone's apex goes with the cone (its normal is not defined there). - let apex = o.iter().zip(&n).find_map(|(a, b)| match (a, b) { - (Surf::Cone { v: va, .. }, Surf::Cone { v: vb, .. }) if va.dist(p) < size * 1e-6 => Some(*vb), - _ => None, - }); - let q = match apex { - Some(q) if n.iter().all(|sf| sf.dist(q).abs() < size * 1e-6) => q, - _ => match move_point(p, &o, &s, &n, size * 1e-6) { - Some(q) => q, - None => { - let nodes = (fs == *at) - .then(|| split_corner(&v, at, &faces, &efaces, &old, &new, size)) - .flatten() - .ok_or_else(|| fail("a corner whose faces don't meet the same way after the move"))?; - let q = nodes.first().map(|x| x.0).ok_or_else(|| fail("corner"))?; - splits.insert(v.id(), nodes); - q - } - }, - }; - newpos.insert(v.id(), q); - } - // Which of a split corner's new corners an edge ends at. - let node_of = |v: mt::VertexID, e: mt::EdgeID| -> Option { - let fs = efaces.get(&e)?; - splits.get(&v)?.iter().position(|(_, nf)| fs.iter().all(|i| nf.contains(i))) - }; - // Where an edge's end goes. - let end_pos = |v: &mt::Vertex, e: &mt::Edge| -> Option { - match splits.get(&v.id()) { - Some(nodes) => nodes.get(node_of(v.id(), e.id())?).map(|x| x.0), - None => newpos.get(&v.id()).copied(), - } - }; - // An edge turned round: faces crossed over (a wall thinner than the move), which would - // leave the body inside out. - let edge_collapsed = |e: &mt::Edge| efaces.get(&e.id()).is_some_and(|fs| fs.iter().any(|i| is_collapsed(*i))); - for e in b.solid.edge_iter() { - if edge_collapsed(&e) { - continue; - } - let (f0, f1) = (e.absolute_front(), e.absolute_back()); - let (Some(q0), Some(q1)) = (end_pos(f0, &e), end_pos(f1, &e)) else { continue }; - let (old_v, new_v) = (from_p3(f1.point()) - from_p3(f0.point()), q1 - q0); - if old_v.len() > size * 1e-6 && old_v.dot(new_v) < 0.0 { - return Err(fail("not supported yet: the move is larger than a wall or step is thick (faces would cross)")); - } - } - // A plane's loops crossing after the move: a rim or ledge narrower than the move (the hole - // in a top face sliding past its outer edge) turns part of the face inside out, though no - // edge turns round. - if let Some(at) = crossed_loops(&faces, &old, &end_pos, &edge_collapsed, size) { - return Err(fail(&format!( - "not supported yet: the move is larger than a rim or ledge near [{:.1}, {:.1}, {:.1}] is wide (a face would turn inside out)", - at.x, at.y, at.z - ))); - } - guard("offset", || { - // Vertices of collapsed faces that land together become one. - let on_collapsed: std::collections::HashSet = faces - .iter() - .enumerate() - .filter(|(i, _)| is_collapsed(*i)) - .flat_map(|(_, f)| f.vertex_iter().map(|v| v.id()).collect::>()) - .collect(); - let mut verts: HashMap = HashMap::new(); - let mut welded: Vec<(Vec3, mt::Vertex)> = Vec::new(); - for v in b.solid.vertex_iter() { - let Some(p) = newpos.get(&v.id()).copied() else { continue }; - let nv = if any_collapsed && on_collapsed.contains(&v.id()) { - match welded.iter().find(|(q, _)| q.dist(p) < size * 1e-6) { - Some((_, w)) => w.clone(), - None => { - let w = builder::vertex(p3(p)); - welded.push((p, w.clone())); - w - } - } - } else { - builder::vertex(p3(p)) - }; - verts.insert(v.id(), nv); - } - let node_verts: HashMap> = - splits.iter().map(|(id, nodes)| (*id, nodes.iter().map(|(q, _)| builder::vertex(p3(*q))).collect())).collect(); - let vert_at = |v: &mt::Vertex, e: &mt::Edge| -> Option<&mt::Vertex> { - match node_verts.get(&v.id()) { - Some(nv) => nv.get(node_of(v.id(), e.id())?), - None => verts.get(&v.id()), - } - }; - // New edges between a split corner's corners (stored from the lower index). - let mut links: HashMap<(mt::VertexID, usize, usize), mt::Edge> = HashMap::new(); - // Old edge → new edge, and whether it runs the other way (merged with its twin). - let mut edges: HashMap = HashMap::new(); - // Moved faces and edges; an edge where neighbours of a collapsed face meet is new. - let mut rec = crate::record::Rebuild::default(); - // New edges along collapsed rounds: ends and points along them, for their twins. - let mut merged: Vec<(mt::VertexID, mt::VertexID, Vec, mt::Edge)> = Vec::new(); - for e in b.solid.edge_iter() { - if edges.contains_key(&e.id()) { - continue; - } - let (Some(a), Some(c)) = (vert_at(e.absolute_front(), &e), vert_at(e.absolute_back(), &e)) else { return Err(fail("edge")) }; - let touches = edge_collapsed(&e); - if a == c || from_p3(a.point()).dist(from_p3(c.point())) < size * 1e-9 { - if touches { - continue; - } - return Err(fail("an edge vanishes (the offset is too large)")); - } - if efaces.get(&e.id()).is_some_and(|fs| fs.iter().all(|i| is_collapsed(*i))) { - continue; - } - if touches { - // Along a collapsed round: where the edge's own face meets the face across the - // round, between the edge's moved ends, through the edge's middle moved onto - // both: a line (planes, or a plane along a cylinder's axis) or an arc (a plane - // square to a coaxial cylinder); faces that meet in another curve are refused. - // Shared with its twin from the round's other side: the new edge with the same - // ends through the same middle (two arcs of one circle have the same ends). - use mt::{BoundedCurve, ParametricCurve}; - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let cv = e.curve(); - let (t0, t1) = cv.range_tuple(); - let mid = from_p3(cv.subs((t0 + t1) / 2.0)); - // The face across: the strip's far side (`opposite_side`), the nearest of them - // when several; the nearest along the rounds when the strip has none. - let (mut meet, cand) = across(fs, mid); - let far = opposite_side(&e, fs); - meet.extend(cand.iter().find(|c| far.contains(c)).or(cand.first())); - if meet.len() < 2 { - return Err(fail("an edge along a collapsed round with no face across it")); - } - let (o, s, n) = pick(&meet); - let m = move_point(mid, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("faces that don't meet along a collapsed round"))?; - let near = size * 1e-5; - let twin = merged.iter().find(|(x, y, pts, _)| { - ((*x == a.id() && *y == c.id()) || (*x == c.id() && *y == a.id())) - && pts.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(p, q)| m.dist_to_segment(*p, *q) < near)) - }); - let ne = match twin { - Some((_, _, _, x)) => x.clone(), - None => { - let (pa, pc) = (from_p3(a.point()), from_p3(c.point())); - let x = if m.dist_to_segment(pa, pc) < near { builder::line(a, c) } else { builder::circle_arc(a, c, p3(m)) }; - let xc = x.curve(); - let (u0, u1) = xc.range_tuple(); - let pts: Vec = (0..=16).map(|j| from_p3(xc.subs(u0 + (u1 - u0) * j as f64 / 16.0))).collect(); - if !pts.iter().all(|p| n.iter().all(|sf| sf.dist(*p).abs() < near)) { - return Err(fail("not supported yet: faces meeting along a collapsed round in a curve other than a line or circle")); - } - merged.push((a.id(), c.id(), pts, x.clone())); - x - } - }; - let flipped = ne.front() != a; - edges.insert(e.id(), (ne, flipped)); - continue; - } - let Some(kind) = arc_mid(&e, size * 1e-6) else { - // Another curve (where two cylinders meet): its points moved onto the moved - // faces, through a smooth curve. - use mt::{BoundedCurve, ParametricCurve}; - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let (o, s, n) = pick(fs); - let cv = e.curve(); - let (t0, t1) = cv.range_tuple(); - let k = 16; - let mut pts = vec![from_p3(a.point())]; - for j in 1..k { - let p = from_p3(cv.subs(t0 + (t1 - t0) * j as f64 / k as f64)); - pts.push( - move_point(p, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("an edge whose faces don't meet the same way after the move"))?, - ); - } - pts.push(from_p3(c.point())); - let curve = crate::build::interpolate_cubic(&pts).ok_or_else(|| fail("edge curve"))?; - let ne = mt::Edge::new(a, c, mt::Curve::BSplineCurve(curve)); - rec.piece(&ne, &e); - edges.insert(e.id(), (ne, false)); - continue; - }; - let ne = match kind { - None => builder::line(a, c), - Some(m) => { - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let (o, s, n) = pick(fs); - let m2 = - move_point(m, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("an edge whose faces don't meet the same way after the move"))?; - // An arc turned round: its ends moved past its middle (next to a face it meets - // tangentially), so the arc through them goes the long way round its circle. - let (a0, c0, a1, c1) = - (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()), from_p3(a.point()), from_p3(c.point())); - if (m - a0).cross(c0 - a0).dot((m2 - a1).cross(c1 - a1)) < 0.0 { - return Err(fail("not supported yet: the move is larger than a wall or step is thick (faces would cross)")); - } - builder::circle_arc(a, c, p3(m2)) - } - }; - rec.piece(&ne, &e); - edges.insert(e.id(), (ne, false)); - } - let mut out = Vec::new(); - for (i, f) in faces.iter().enumerate() { - if is_collapsed(i) { - continue; - } - let mut wires: Vec = Vec::new(); - for w in f.absolute_boundaries() { - let old_edges: Vec = w.edge_iter().cloned().collect(); - let mut wire: Vec = Vec::new(); - for (j, e) in old_edges.iter().enumerate() { - if let Some((ne, flip)) = edges.get(&e.id()) { - wire.push(if (e.front() == e.absolute_front()) != *flip { ne.clone() } else { ne.inverse() }); - } - // At a split corner, along the new edges from this edge's end to the next's. - let v = e.back(); - let (Some(nodes), Some(next)) = (splits.get(&v.id()), old_edges.get((j + 1) % old_edges.len())) else { continue }; - let (Some(from), Some(to)) = (node_of(v.id(), e.id()), node_of(v.id(), next.id())) else { return Err(fail("split corner")) }; - let path = split_path(nodes, i, from, to).ok_or_else(|| fail("split corner"))?; - for pair in path.windows(2) { - let (Some(&x), Some(&y)) = (pair.first(), pair.get(1)) else { continue }; - let key = (v.id(), x.min(y), x.max(y)); - let link = match links.get(&key) { - Some(l) => l.clone(), - None => { - let nv = node_verts.get(&v.id()).ok_or_else(|| fail("split corner"))?; - let (Some(va), Some(vb)) = (nv.get(key.1), nv.get(key.2)) else { return Err(fail("split corner")) }; - let l = builder::line(va, vb); - links.insert(key, l.clone()); - l - } - }; - wire.push(if x < y { link } else { link.inverse() }); - } - } - wires.push(wire.into()); - } - let (Some(o), Some(n)) = (old.get(i), new.get(i)) else { return Err(fail("face")) }; - let surface = match (o.map_to(n), *o, *n) { - (Some(mat), _, _) => mt::Transformed::transformed(&f.surface(), mat), - // A torus: its tube's circle scaled about the tube's centre, revolved again. - (None, Surf::Torus { o: to, a, big, h, r, .. }, Surf::Torus { r: r2, .. }) => { - use mt::{BoundedCurve, ParametricCurve}; - let mt::Surface::RevolutedCurve(rc) = f.surface() else { return Err(fail("torus surface")) }; - let curve = rc.entity().entity_curve().clone(); - let (t0, t1) = curve.range_tuple(); - let q = from_p3(curve.subs((t0 + t1) / 2.0)); - let c = tube_centre(to, a, big, h, q).ok_or_else(|| fail("torus"))?; - let k = r2 / r; - let t = c * (1.0 - k); - let mat = mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z)) * mt::Matrix4::from_scale(k); - let moved = mt::Transformed::transformed(&curve, mat); - let mut p = mt::Processor::new(mt::RevolutedCurve::by_revolution(moved, rc.entity().origin(), rc.entity().axis())); - if !rc.orientation() { - mt::Invertible::invert(&mut p); - } - mt::Surface::RevolutedCurve(p) - } - _ => return Err(fail("surface")), - }; - let mut nf = mt::Face::try_new(wires, surface).map_err(|e| fail(&e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - rec.face(&nf, f); - out.push(nf); - } - // One shell per shell of the body (pieces, voids), less the collapsed faces. - let mut shells: Vec = Vec::new(); - let mut it = out.into_iter(); - let mut k = 0; - for sh in b.solid.boundaries() { - let keep = (k..k + sh.len()).filter(|i| !is_collapsed(*i)).count(); - k += sh.len(); - shells.push(it.by_ref().take(keep).collect::>().into()); - } - let solid = Solid::try_new(shells).map_err(|e| fail(&e.to_string()))?; - crate::record::rebuilt(solid, &[&b.solid], &rec) - }) -} - -/// Draft walls parallel to `pull` (planes, and cylinders about axes along `pull`) by `angle` -/// about their line on the neutral plane: at height h along `pull` a wall moves along its -/// outward normal by −h·tan(angle), so planes tilt and cylinders become cones. The faces that -/// share a corner with a drafted wall must be caps square to `pull` or walls; the rest of the -/// body (a rounded edge elsewhere, say) is left as it is. The topology is kept, and the -/// result's history is over `[b]` (each face and edge the one it was moved from). -pub(crate) fn draft_walls(b: &Body, chosen: &[usize], neutral: &solidcraft_geom::Plane, pull: Vec3, angle: f64) -> Result { - let faces: Vec = b.solid.face_iter().cloned().collect(); - let size = b.size(); - let tol = (size * 1e-7).max(1e-9); - let nn = neutral.normal(); - let den = pull.dot(nn); - if den.abs() < 1e-9 { - return Err(fail("the neutral plane is parallel to the pull direction")); - } - let height = |p: Vec3| (p - neutral.origin).dot(nn) / den; - let tan = angle.tan(); - let mut vfaces: HashMap> = HashMap::new(); - let mut efaces: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for v in f.vertex_iter() { - let e = vfaces.entry(v.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - for ed in f.edge_iter() { - let e = efaces.entry(ed.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - } - // A corner moves when one of its faces is drafted; the faces round a moving corner must be - // walls or caps for the corner to follow them. Faces away from the drafted walls may be - // anything: they keep their surface and their edges. - let moves = |vid: &mt::VertexID| vfaces.get(vid).is_some_and(|fs| fs.iter().any(|i| chosen.contains(i))); - let touched: Vec = faces.iter().enumerate().map(|(i, f)| chosen.contains(&i) || f.vertex_iter().any(|v| moves(&v.id()))).collect(); - let mut old: Vec> = Vec::with_capacity(faces.len()); - for (i, f) in faces.iter().enumerate() { - if !touched.get(i).copied().unwrap_or(false) { - old.push(None); - continue; - } - let sf = surf_of(f, tol * 100.0).ok_or_else(|| fail("draft: the faces next to the drafted walls must be planes or cylinders"))?; - let wall = match sf { - Surf::Plane { n, .. } => n.dot(pull).abs() < 1e-9, - Surf::Cylinder { a, .. } => a.dot(pull).abs() > 1.0 - 1e-9, - Surf::Sphere { .. } | Surf::Cone { .. } | Surf::Torus { .. } => false, - }; - let cap = matches!(sf, Surf::Plane { n, .. } if n.dot(pull).abs() > 1.0 - 1e-9); - if chosen.contains(&i) && !wall { - return Err(fail("draft: a chosen face isn't parallel to the pull direction")); - } - if !chosen.contains(&i) && !cap && !wall { - return Err(fail("draft: faces next to the drafted walls must be square to the pull direction")); - } - old.push(Some(sf)); - } - // Shifts and moved surfaces at a height. - let at = |ids: &[usize], h: f64| -> Option<(Vec, Vec, Vec)> { - let mut o = Vec::new(); - let mut s = Vec::new(); - let mut n = Vec::new(); - for i in ids { - let sf = (*old.get(*i)?)?; - let sh = if chosen.contains(i) { -h * tan } else { 0.0 }; - o.push(sf); - s.push(sh); - n.push(sf.moved(sh)?); - } - Some((o, s, n)) - }; - let mut newpos: HashMap = HashMap::new(); - for v in b.solid.vertex_iter() { - let p = from_p3(v.point()); - if !moves(&v.id()) { - newpos.insert(v.id(), p); - continue; - } - let fs = vfaces.get(&v.id()).ok_or_else(|| fail("vertex"))?; - let (o, s, n) = at(fs, height(p)).ok_or_else(|| fail("draft: a wall shrinks to nothing"))?; - let q = move_point(p, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("draft: a corner whose faces don't meet the same way after the draft"))?; - newpos.insert(v.id(), q); - } - // New surfaces for the drafted walls: planes through their hinge line, cylinders → cones. - let mut surfaces: Vec> = vec![None; faces.len()]; - for (i, sf) in old.iter().enumerate() { - let (true, Some(sf)) = (chosen.contains(&i), *sf) else { continue }; - let surface = match sf { - Surf::Plane { n, d } => { - let n2 = (n * angle.cos() + pull * angle.sin()).normalized().ok_or_else(|| fail("draft"))?; - // A point of the old plane on the neutral plane: the hinge. - let o = neutral.intersect_ray(n * d, pull).ok_or_else(|| fail("draft: hinge"))?; - let u = n2.cross(pull).normalized().ok_or_else(|| fail("draft"))?; - let w = n2.cross(u); - mt::Surface::Plane(mt::Plane::new(p3(o), p3(o + u), p3(o + w))) - } - Surf::Cylinder { o, a, r, convex } => { - // Generator: the wall at two heights along one radial direction. - let u = a.any_perp(); - // Over the face's heights (and a little beyond), short of the apex. - let hs: Vec = faces.get(i).map(|f| f.vertex_iter().map(|v| height(from_p3(v.point()))).collect()).unwrap_or_default(); - let (lo, hi) = hs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |m, h| (m.0.min(*h), m.1.max(*h))); - if !(lo.is_finite() && hi.is_finite()) { - return Err(fail("draft: a wall without corners")); - } - let pad = (hi - lo).max(size * 1e-3) * 0.25; - let (mut h0, mut h1) = (lo - pad, hi + pad); - // Keep the radius positive along the generator. - let r_at = |h: f64| if convex { r - h * tan } else { r + h * tan }; - for h in [&mut h0, &mut h1] { - if r_at(*h) <= r * 1e-3 { - *h = if (*h - lo).abs() < (*h - hi).abs() { lo } else { hi }; - } - } - let base = |h: f64| { - let rr = if convex { r - h * tan } else { r + h * tan }; - o + pull * (h - height(o)) + u * rr - }; - let (pa, pb) = (base(h0), base(h1)); - let line = mt::Curve::Line(mt::Line(p3(pa), p3(pb))); - let rc = mt::RevolutedCurve::by_revolution(line, p3(o), mt::Vector3::new(a.x, a.y, a.z)); - mt::Surface::RevolutedCurve(mt::Processor::new(rc)) - } - Surf::Sphere { .. } | Surf::Cone { .. } | Surf::Torus { .. } => { - return Err(fail("draft: only planes and cylinders along the pull can be drafted")); - } - }; - if let Some(slot) = surfaces.get_mut(i) { - *slot = Some(surface); - } - } - guard("draft", || { - let verts: HashMap = newpos.iter().map(|(k, p)| (*k, builder::vertex(p3(*p)))).collect(); - let mut edges: HashMap = HashMap::new(); - let mut rec = crate::record::Rebuild::default(); - for e in b.solid.edge_iter() { - if edges.contains_key(&e.id()) { - continue; - } - let (Some(a), Some(c)) = (verts.get(&e.absolute_front().id()), verts.get(&e.absolute_back().id())) else { return Err(fail("edge")) }; - // An edge whose ends stay keeps its curve (it may be anything: a blend's spline). - if !moves(&e.absolute_front().id()) && !moves(&e.absolute_back().id()) { - let ne = mt::Edge::try_new(a, c, e.curve().clone()).map_err(|e| fail(&e.to_string()))?; - rec.piece(&ne, &e); - edges.insert(e.id(), ne); - continue; - } - let kind = arc_mid(&e, size * 1e-6).ok_or_else(|| fail("draft: edges next to the drafted walls must be lines or arcs"))?; - let ne = match kind { - None => builder::line(a, c), - Some(m) => { - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let (o, s, n) = at(fs, height(m)).ok_or_else(|| fail("draft"))?; - let m2 = move_point(m, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("draft: an arc that can't follow its faces"))?; - builder::circle_arc(a, c, p3(m2)) - } - }; - rec.piece(&ne, &e); - edges.insert(e.id(), ne); - } - let mut out = Vec::new(); - for (i, f) in faces.iter().enumerate() { - let wires: Vec = f - .boundaries() - .iter() - .map(|w| { - w.edge_iter() - .filter_map(|e| edges.get(&e.id()).map(|ne| if e.front() == e.absolute_front() { ne.clone() } else { ne.inverse() })) - .collect::>() - .into() - }) - .collect(); - let nf = match surfaces.get(i).cloned().flatten() { - Some(mut surface) => { - // Outward like the old face (checked at a boundary point). - let probe = f.boundaries().first().and_then(|w| w.vertex_iter().next()).map(|v| from_p3(v.point())); - let want = probe.and_then(|p| old.get(i).copied().flatten().and_then(|s| s.normal(p))); - if let (Some(p), Some(want)) = (probe, want) { - use mt::{ParametricSurface3D, SearchNearestParameter}; - if let Some((u, v)) = surface.search_nearest_parameter(p3(p), None, 100) { - let nn = surface.normal(u, v); - if Vec3::new(nn.x, nn.y, nn.z).dot(want) < 0.0 { - surface = mt::Invertible::inverse(&surface); - } - } - } - mt::Face::try_new(wires, surface).map_err(|e| fail(&e.to_string()))? - } - None => { - // Unchanged surface: rebuild on the oriented boundary. - let mut nf = mt::Face::try_new( - f.absolute_boundaries() - .iter() - .map(|w| { - w.edge_iter() - .filter_map(|e| { - edges.get(&e.id()).map(|ne| if e.front() == e.absolute_front() { ne.clone() } else { ne.inverse() }) - }) - .collect::>() - .into() - }) - .collect(), - f.surface(), - ) - .map_err(|e| fail(&e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - nf - } - }; - rec.face(&nf, f); - out.push(nf); - } - let shell: mt::Shell = out.into(); - let solid = Solid::try_new(vec![shell]).map_err(|e| fail(&e.to_string()))?; - crate::record::rebuilt(solid, &[&b.solid], &rec) - }) + out.sort_unstable(); + out.dedup(); + out } /// The chosen faces and every face on the same surface joined to them (the halves of a hole's /// wall), as face indices. Pieces of a face split on purpose (Split Face) stay apart. pub fn with_same_surface(b: &Body, chosen: &[usize]) -> Vec { - let faces: Vec = b.solid.face_iter().cloned().collect(); - let size = b.size(); - let tol = (size * 1e-7).max(1e-9) * 100.0; - let surfs: Vec> = faces.iter().map(|f| surf_of(f, tol)).collect(); - let same = |x: &Surf, y: &Surf| match (*x, *y) { - (Surf::Plane { n, d }, Surf::Plane { n: m, d: e }) => n.dot(m) > 1.0 - 1e-9 && (d - e).abs() < tol, - (Surf::Cylinder { o, a, r, convex }, Surf::Cylinder { o: o2, a: a2, r: r2, convex: c2 }) => { - a.dot(a2).abs() > 1.0 - 1e-9 && (r - r2).abs() < tol && convex == c2 && { (o2 - o - a * (o2 - o).dot(a)).len() < tol } - } - (Surf::Sphere { c, r, convex }, Surf::Sphere { c: c2, r: r2, convex: k2 }) => c.dist(c2) < tol && (r - r2).abs() < tol && convex == k2, - (Surf::Cone { v, a, half, convex }, Surf::Cone { v: v2, a: a2, half: h2, convex: k2 }) => { - v.dist(v2) < tol && a.dot(a2) > 1.0 - 1e-9 && (half - h2).abs() < 1e-9 && convex == k2 - } - (Surf::Torus { o, a, big, h, r, convex }, Surf::Torus { o: o2, a: a2, big: b2, h: h2, r: r2, convex: k2 }) => { - (o + a * h).dist(o2 + a2 * h2) < tol && a.dot(a2).abs() > 1.0 - 1e-9 && (big - b2).abs() < tol && (r - r2).abs() < tol && convex == k2 - } - _ => false, - }; + let Ok(record) = crate::native::brep_record(b) else { return chosen.to_vec() }; + let tol = (b.size() * 1e-7).max(1e-9) * 100.0; + let surfs: Vec> = (0..record.faces.len()).map(|i| surf_of(&record, i)).collect(); + let edges: Vec> = (0..record.faces.len()).map(|i| face_edges(&record, i)).collect(); let keep = b.split_keep(); let mut out: Vec = chosen.to_vec(); let mut grew = true; while grew { grew = false; - for (i, f) in faces.iter().enumerate() { + for i in 0..record.faces.len() { if out.contains(&i) { continue; } let Some(Some(si)) = surfs.get(i) else { continue }; + let mine = edges.get(i).map(Vec::as_slice).unwrap_or(&[]); let joins = out.iter().any(|j| { - surfs.get(*j).and_then(|x| x.as_ref()).is_some_and(|sj| same(si, sj)) - && faces.get(*j).is_some_and(|g| { - g.edge_iter().any(|e| { - f.edge_iter().any(|x| x.id() == e.id()) - && (keep.is_empty() || !crate::heal::on_split_line(&crate::heal::edge_points(&e), keep)) + surfs.get(*j).and_then(|x| x.as_ref()).is_some_and(|sj| si.same(sj, tol)) + && edges.get(*j).is_some_and(|theirs| { + theirs.iter().any(|e| { + mine.binary_search(e).is_ok() + && (keep.is_empty() || !crate::heal::on_split_line(&crate::heal::edge_points(&record, *e), keep)) }) }) }); diff --git a/crates/kernel/src/offset_backend.rs b/crates/kernel/src/offset_backend.rs new file mode 100644 index 000000000..1f72ed2d8 --- /dev/null +++ b/crates/kernel/src/offset_backend.rs @@ -0,0 +1,293 @@ +//! Shell, offset faces, draft and thicken through SMLib: the body goes to SMLib as its schema 4 +//! record, tagged as operand 0, SMLib runs the operation, and the result comes back with SMLib's own +//! history, renumbered into the body's and the result's face and edge order (as +//! `crate::smlib_boolean` does for booleans). A result SMLib's own check refuses is an +//! error, never a body. +//! +//! SMLib's tags travel through the copies its offset makes, so a shell's inner wall and a +//! thickened sheet's moved copy carry the tag of the face they were made from, and SMLib reads +//! both that face and its copy as pieces of it (Split). Which is which is a matter of where they +//! lie: the copy is the operation's distance from the face, the face itself on it. So a result +//! face farther from its tagged face than half that distance is recorded as its offset +//! ([`FaceOrigin::Offset`]), and its edges as where its faces meet. A face SMLib makes new along +//! a sheet's open edge (a thickened sheet's wall) is recorded as made in place of that edge. + +use solidcraft_geom::prelude::*; +use std::collections::{BTreeMap, BTreeSet}; + +use solidcore_record::Vec3; +use solidcraft_smlib::{Brep, CheckLevel, Error as SmError}; + +use crate::body::Body; +use crate::history::{Change, EdgeOrigin, FaceOrigin, History}; +use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; +use crate::{KernelError, Result, record}; + +fn failed(op: &str, what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {op}: {what}"), e) +} + +/// The error for SMLib's refusal of `op`, in the words of the operation; `wall` is its wall's +/// thickness, where it has one. +fn refused(op: &str, wall: Option, e: SmError) -> KernelError { + match e { + SmError::NoRoom => KernelError::Invalid(format!("{op}: the wall is too thick: it leaves no room inside the body")), + // The walls just meet: thinner they stay apart, thicker they cross and merge. + SmError::WallsTouch => { + let wall = wall.map(|t| format!(" {t} mm")).unwrap_or_default(); + KernelError::Invalid(format!( + "{op}: the{wall} walls would meet along a line (between a hole and the side, for example), which leaves no solid there; \ + use a thinner or thicker wall, or move the feature" + )) + } + // solidcore's one construction: a face curves tighter than the wall is thick. + SmError::WallFolds { largest } => { + let largest = largest.map(|w| format!("; the largest wall that works is {} mm", crate::blend::trimmed_mm(w))).unwrap_or_default(); + KernelError::Invalid(format!("{op}: the wall is thicker than a face curves, so the face's offset would fold{largest}")) + } + SmError::NoMatch { point } => KernelError::Invalid(format!("{op}: no face at selection point {}", point + 1)), + SmError::Ambiguous { point } => KernelError::Invalid(format!("{op}: selection point {} is as near to two faces", point + 1)), + SmError::Unsupported => KernelError::Failed(format!("not supported yet: SMLib {op} for this geometry")), + SmError::NoEffect => KernelError::Failed(format!("SMLib made no change: the {op} reported success but moved no face onto its new surface")), + e => failed(op, "operation", e), + } +} + +/// How far a selection point may be from the face it picks: the kernel's own picking reach. +fn pick_tolerance(b: &Body) -> f64 { + b.size() * 1e-3 + 1e-6 +} + +fn points(p: &[Vec3]) -> Vec<[f64; 3]> { + p.iter().map(|v| [v.x, v.y, v.z]).collect() +} + +/// Runs `op` on `b` in SMLib, tagged as operand 0, and brings the result back with SMLib's +/// history over `[b]` (none where an order cannot be matched). `wall`: the operation's wall +/// thickness, for its refusals. +pub(crate) fn run( + name: &str, + b: &Body, + wall: Option, + op: impl FnOnce(&Brep) -> std::result::Result, +) -> Result<(Body, Option)> { + b.require_brep(name)?; + let (sb, ob) = smlib_body_ordered(b)?; + let tagged = sb.tagged(0).map_err(|e| failed(name, "tag", e))?; + let r = op(&tagged).map_err(|e| refused(name, wall, e))?; + let check = r.check(CheckLevel::All).map_err(|e| failed(name, "check", e))?; + if !check.is_valid() { + let input = sb.check(CheckLevel::All).is_ok_and(|c| !c.is_valid()); + let what = if input { "SMLib's check refuses the result (the body already fails it)" } else { "SMLib's check refuses the result" }; + return Err(failed(name, what, check)); + } + let (body, or) = body_from_smlib_ordered(&r)?; + let history = match (ob, or) { + (Some(ob), Some(or)) => r.history().map_err(|e| failed(name, "history", e))?.history(&[ob], &or).map(Some).unwrap_or_else(|e| { + log::debug!(target: "smlib", "{name} history: {e}"); + None + }), + _ => None, + }; + Ok((body, history)) +} + +/// [`crate::shell`] through SMLib: walls of `thickness` inside, open at the faces under the +/// points `open` (the face of the nearest triangle) and the faces +/// on the same surface joined to them: a round wall stored in pieces (a hole's two halves) opens +/// whole. SMLib is given one point inside each, never the pick itself, which may lie on the +/// line between two pieces. +pub(crate) fn shell(b: &Body, open: &[Vec3], thickness: f64) -> Result { + if !(thickness.is_finite() && thickness > 1e-6) { + return Err(KernelError::Invalid("shell thickness must be positive".into())); + } + let picked = faces_under(b, open)?; + let opened = crate::offset::with_same_surface(b, &picked); + let tol = pick_tolerance(b); + let pts = points(&face_points(b, &opened)?); + let (r, h) = run("shell", b, Some(thickness), |s| s.shell(&pts, tol, -thickness))?; + let h = h.and_then(|h| with_offsets(&r, b, h, thickness)); + Ok(r.with_checked_history(h, &record::counts(&[b]))) +} + +/// [`crate::offset_faces`] through SMLib: the faces `chosen` (indices in `b`'s face order) +/// moved `distance` along their outward normals. The moved faces are the faces themselves, +/// moved (Modified). +pub(crate) fn offset_faces(b: &Body, chosen: &[usize], distance: f64) -> Result { + let at = face_points(b, chosen)?; + let tol = pick_tolerance(b); + let pts = points(&at); + let (r, h) = run("offset faces", b, None, |s| s.offset_faces(&pts, tol, distance))?; + let h = h.map(|mut h| { + for f in &mut h.faces { + if f.change == Change::Kept && f.origins.iter().any(|o| matches!(o, FaceOrigin::Face { face, .. } if chosen.contains(face))) { + f.change = Change::Modified; + } + } + h + }); + Ok(r.with_checked_history(h, &record::counts(&[b]))) +} + +/// [`crate::thicken`] through SMLib: the sheet `b` grown by `thickness` along its faces' +/// normals, or half each way when `symmetric`. +pub(crate) fn thicken(b: &Body, thickness: f64, symmetric: bool) -> Result { + if !(thickness.is_finite() && thickness.abs() > 1e-9) { + return Err(KernelError::Invalid("thickness must be non-zero".into())); + } + let (r, h) = run("thicken", b, Some(thickness.abs()), |s| s.thicken(thickness, symmetric))?; + let step = if symmetric { thickness.abs() / 2.0 } else { thickness.abs() }; + // The walls first, while the sheet's edges still carry their tags on both copies. + let h = h.map(with_edge_walls).and_then(|h| with_offsets(&r, b, h, step)); + Ok(r.with_checked_history(h, &record::counts(&[b]))) +} + +/// [`crate::draft`] through SMLib: the faces under the points `at` (flat, parallel to `pull`) +/// tilted by `angle` about their lines on `neutral`, leaning in going along `pull`; the faces +/// around them extended or trimmed to meet them. A tilted face is the face itself (Modified). +/// A face SMLib can't draft (not flat, or not parallel to the pull) is "not supported yet". +pub(crate) fn draft(b: &Body, at: &[Vec3], neutral: &solidcore_record::Plane, pull: Vec3, angle: f64) -> Result { + if !angle.is_finite() || angle.abs() >= std::f64::consts::FRAC_PI_2 - 1e-3 { + return Err(KernelError::Invalid("draft angle must be between −90° and 90°".into())); + } + let pull = pull.normalized().ok_or_else(|| KernelError::Invalid("pull direction".into()))?; + let normal = neutral.normal().normalized().ok_or_else(|| KernelError::Invalid("neutral plane".into()))?; + if normal.dot(pull).abs() < 1e-9 { + return Err(KernelError::Failed("the neutral plane is parallel to the pull direction".into())); + } + let chosen = faces_under(b, at)?; + let tol = pick_tolerance(b); + let pts = points(&face_points(b, &chosen)?); + let o = neutral.origin; + let (r, h) = run("draft", b, None, |s| s.draft(&pts, tol, [o.x, o.y, o.z], [normal.x, normal.y, normal.z], [pull.x, pull.y, pull.z], angle))?; + let h = h.map(|mut h| { + for f in &mut h.faces { + if f.change == Change::Kept && f.origins.iter().any(|o| matches!(o, FaceOrigin::Face { face, .. } if chosen.contains(face))) { + f.change = Change::Modified; + } + } + h + }); + Ok(r.with_checked_history(h, &record::counts(&[b]))) +} + +/// The face of `b` under each point: the face of the nearest triangle, within the picking reach. +fn faces_under(b: &Body, at: &[Vec3]) -> Result> { + let reach = pick_tolerance(b); + let mesh = b.mesh(&crate::MeshTolerance::chord((b.size() * 1e-3).max(1e-3)))?; + let mut out: Vec = Vec::new(); + for p in at { + let near = mesh + .triangles + .iter() + .zip(&mesh.tri_face) + .filter_map(|(t, f)| mesh.tri(t).map(|[x, y, z]| (solidcraft_geom::compare::closest_on_triangle(*p, x, y, z).dist(*p), *f as usize))) + .min_by(|x, y| x.0.total_cmp(&y.0)); + match near { + Some((d, f)) if d < reach => { + if !out.contains(&f) { + out.push(f); + } + } + _ => return Err(KernelError::Invalid(format!("no face at {:?}", [p.x, p.y, p.z]))), + } + } + Ok(out) +} + +/// One point inside each face `faces` of `b`: the centroid of its largest triangle. +fn face_points(b: &Body, faces: &[usize]) -> Result> { + let mesh = b.mesh(&crate::MeshTolerance::chord((b.size() * 1e-3).max(1e-3)))?; + faces + .iter() + .map(|f| { + mesh.triangles + .iter() + .zip(&mesh.tri_face) + .filter(|(_, t)| **t as usize == *f) + .filter_map(|(t, _)| mesh.tri(t)) + .max_by(|x, y| area(x).total_cmp(&area(y))) + .map(|[p, q, s]| (p + q + s) * (1.0 / 3.0)) + .ok_or_else(|| KernelError::Failed(format!("offset faces: face {f} has no triangles"))) + }) + .collect() +} + +fn area([a, b, c]: &[Vec3; 3]) -> f64 { + (*b - *a).cross(*c - *a).len() +} + +/// `h` over `[input]` with each result face that lies `distance` (more than half of it) from +/// the input face it is tagged with recorded as that face's offset, the faces left on their +/// input face Split only where several still share it, and every edge of an offset face as +/// where its faces meet. `None` where a face cannot be measured. +fn with_offsets(result: &Body, input: &Body, mut h: History, distance: f64) -> Option { + let chord = (input.size().max(result.size()) * 1e-3).min(distance / 8.0).max(1e-6); + let source = input.mesh(&crate::MeshTolerance::chord(chord)).ok()?; + let made = result.mesh(&crate::MeshTolerance::chord(chord)).ok()?; + let at = |mesh: &solidcraft_geom::Mesh, face: usize| -> Vec<[Vec3; 3]> { + mesh.triangles.iter().zip(&mesh.tri_face).filter(|(_, t)| **t as usize == face).filter_map(|(t, _)| mesh.tri(t)).collect() + }; + let mut offset = vec![false; h.faces.len()]; + for (i, f) in h.faces.iter_mut().enumerate() { + let [FaceOrigin::Face { operand: 0, face }] = f.origins[..] else { continue }; + let tris = at(&made, i); + let p = tris.iter().max_by(|x, y| area(x).total_cmp(&area(y))).map(|[a, b, c]| (*a + *b + *c) * (1.0 / 3.0))?; + let under = at(&source, face); + let d = under.iter().map(|[a, b, c]| solidcraft_geom::compare::closest_on_triangle(p, *a, *b, *c).dist(p)).fold(f64::INFINITY, f64::min); + if !d.is_finite() { + return None; + } + if d > distance / 2.0 { + *f = record::generated(vec![FaceOrigin::Offset { operand: 0, face }]); + offset[i] = true; + } + } + // Faces still on an input face: Split only where several share it. + let mut uses: BTreeMap = BTreeMap::new(); + for f in &h.faces { + if let [o @ FaceOrigin::Face { .. }] = f.origins[..] { + *uses.entry(o).or_default() += 1; + } + } + for f in &mut h.faces { + if f.change == Change::Split + && let [o @ FaceOrigin::Face { .. }] = f.origins[..] + && uses.get(&o) == Some(&1) + { + f.change = Change::Modified; + } + } + let faces = h.faces.clone(); + for e in &mut h.edges { + if e.faces.iter().any(|f| offset.get(*f).copied().unwrap_or(false)) { + e.origins = record::meeting(&e.faces, &faces); + } + } + Some(h) +} + +/// `h` with each face new to the operation that stands on exactly one input edge (its edges +/// tagged with that edge, a thickened sheet's wall) recorded as made in place of that edge. +fn with_edge_walls(mut h: History) -> History { + let mut along: Vec> = vec![BTreeSet::new(); h.faces.len()]; + for e in &h.edges { + for o in &e.origins { + if let EdgeOrigin::Edge { operand: 0, edge } = o { + for f in &e.faces { + if let Some(s) = along.get_mut(*f) { + s.insert(*edge); + } + } + } + } + } + for (f, edges) in h.faces.iter_mut().zip(&along) { + if f.origins.is_empty() + && let [edge] = edges.iter().copied().collect::>()[..] + { + *f = record::generated(vec![FaceOrigin::Edge { operand: 0, edge }]); + } + } + h +} diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 37891c4ca..f238f9628 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -1,22 +1,15 @@ -//! Operations on bodies: booleans and rigid transforms. +//! Operations on bodies: booleans, placements and splits by a plane, through SMLib. Bodies apart +//! from each other join without any intersection work, their records side by side. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::part; +use solidcraft_geom::brep::placement::Rigid; +use solidcraft_geom::prelude::*; -use std::collections::HashMap; - -use crate::body::{Body, Solid, from_p3}; -use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record, reject}; -use crate::boolean_record::{self as recorded, Traced}; -use crate::{KernelError, Result, guard, record}; - -#[cfg(test)] -#[path = "bore_union_tests.rs"] -mod bore_union_tests; - -#[path = "tool_reseam.rs"] -mod tool_reseam; +use crate::body::Body; +use crate::history::{BodyHistory, History}; +use crate::{KernelError, Result, guard}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -26,2347 +19,239 @@ pub enum BoolOp { Intersect, } -/// Exact planar Booleans need no sampled enlargement of their tool footprint. -pub fn is_planar(body: &Body) -> bool { - if body.is_mesh() || body.face_count() > 16_384 { - return false; - } - guard("planar body", || Ok(body.solid.face_iter().all(|face| matches!(face.oriented_surface(), mt::Surface::Plane(_))))).unwrap_or(false) +/// Boolean of two bodies in SMLib. The result may be empty (`Ok(None)`) for a cut that removes +/// everything or an intersection of disjoint bodies. A result SMLib's check refuses is an error. +/// +/// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`, from +/// SMLib's own tags, or none where a body's order cannot be matched to SMLib's. A cut by a tool +/// apart from the body is the body itself (its faces and edges kept), and their intersection empty. +pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { + crate::profile::timed(crate::profile::Kind::Boolean, "boolean", || { + // A tool apart from the body (their exact boxes, grown by the tolerances, do not meet) + // leaves a cut the body itself and an intersection nothing, with no intersection work. + if matches!(op, BoolOp::Cut | BoolOp::Intersect) && apart(a, b)? { + return Ok(match op { + BoolOp::Cut => Some(crate::boolean_record::operand(a, 0, &crate::record::counts(&[a, b]))), + _ => None, + }); + } + let r = guard("SMLib boolean", || crate::smlib_boolean::smlib_boolean(a, b, op)); + with_operand_roles(a, b, op, r) + }) } -/// Batch separated extrusion tools without repeatedly unioning an ever-growing target. -/// Construction caps provide conservative bounds, including the full circle of each arc; -/// unsupported or touching tools retain the caller's sequential Boolean path. -pub fn compound_disjoint_extrusions(tools: &[Body]) -> Result> { - if tools.len() < 2 || tools.len() > 1024 { - return Ok(None); - } - guard("compound extrusion tools", || { - let mut bounds = Vec::with_capacity(tools.len()); - let mut corners = Vec::with_capacity(tools.len()); - let mut axes = Vec::with_capacity(tools.len()); - let mut remaining = 16_384usize; - for tool in tools { - let Some(sources) = tool.face_sources() else { return Ok(None) }; - if sources.len() != tool.face_count() { - return Ok(None); - } - let mut bb = solidcraft_geom::Aabb3::EMPTY; - let mut points = Some(Vec::new()); - let mut directions = Vec::new(); - let mut caps = 0; - for source in sources { - let Some(left) = remaining.checked_sub(1) else { return Ok(None) }; - remaining = left; - match source { - Some(crate::FaceSource::ExtrudeCap { region, plane, high }) => { - caps += 1; - // The bottom support is outward-facing, but its region retains - // the original sketch coordinates (see build::extrude). - let plane = if *high { *plane } else { solidcraft_geom::Plane { y: -plane.y, ..*plane } }; - for segment in ®ion.outer.segs { - let Some(left) = remaining.checked_sub(1) else { return Ok(None) }; - remaining = left; - match *segment { - solidcraft_geom::Seg2::Line { a, b } => { - let (a, b) = (plane.to_world(a), plane.to_world(b)); - bb.add(a); - bb.add(b); - if let Some(points) = points.as_mut() { - points.extend([a, b]); - } - if let Some(axis) = (b - a).cross(plane.normal()).normalized() { - directions.push(axis); - } - } - solidcraft_geom::Seg2::Arc { center, radius, .. } => { - points = None; - for x in [-radius, radius] { - for y in [-radius, radius] { - bb.add(plane.to_world(center + solidcraft_geom::Vec2::new(x, y))); - } - } - } - _ => return Ok(None), - } - } - } - Some(crate::FaceSource::ExtrudeSide { .. }) => {} - _ => return Ok(None), - } - } - if caps != 2 || bb.is_empty() || !bb.min.is_finite() || !bb.max.is_finite() { - return Ok(None); - } - bounds.push(bb); - corners.push(points); - axes.push(directions); +/// The union of `bodies` (at least one) in one SMLib call, each body taking part in about +/// log2(n) of its unions, the result checked once. A result SMLib's check refuses is an error. +/// +/// The result carries its exact history over `bodies` in order, as [`boolean`]'s does, and +/// what the operands' faces stood for (their regularization protection and the planar roles on +/// supports it kept). +pub fn union_all(bodies: &[&Body]) -> Result { + crate::profile::timed(crate::profile::Kind::Boolean, "union_all", || { + if bodies.is_empty() { + return Err(KernelError::Invalid("a union of no bodies".into())); } - let mut remaining_separation_work = 16_000_000usize; - for (i, a) in bounds.iter().enumerate() { - for (j, b) in bounds.iter().enumerate().skip(i + 1) { - let gap = (a.diagonal().max(b.diagonal()) * 1e-6).max(1e-7); - let separated = a.max.x + gap < b.min.x - || b.max.x + gap < a.min.x - || a.max.y + gap < b.min.y - || b.max.y + gap < a.min.y - || a.max.z + gap < b.min.z - || b.max.z + gap < a.min.z; - if separated { - continue; + guard("SMLib union", || crate::smlib_boolean::smlib_union_all(bodies))? + .inherit_split_lines(bodies) + .with_preserved_union_planar_sources(bodies) + }) +} + +/// Whether B-rep bodies `a` and `b` are apart: their exact boxes, each grown by twice its +/// record's tolerance (as [`union_apart`] takes them), do not meet. Never for a mesh body. The +/// way to skip work on bodies that cannot meet: a mesh's box is not the body's. +pub fn apart(a: &Body, b: &Body) -> Result { + if a.is_mesh() || b.is_mesh() { + return Ok(false); + } + let grown = |x: &Body| x.exact_bounds().map(|bb| bb.inflated(2.0 * x.record().tolerance)); + Ok(!grown(a)?.meets(&grown(b)?)) +} + +/// A boolean's result with what its operands' faces stood for carried over: regularization +/// protection, the lines they were split along on purpose, and the planar construction and shell roles on supports it kept. +fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result>) -> Result> { + let r = r + .map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b).inherit_split_lines(&[a, b]))); + match op { + BoolOp::Cut => r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()), + BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(&[a, b])).transpose()), + // Every face of an intersection lies on one operand's face, as a union's does: the same + // roles carry over (#565). + BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(&[a, b])).transpose()), + } +} + +/// The union of bodies when no two of them meet or touch, as one body of several pieces (see +/// [`join_apart`]); `None` when fewer than two are given, one is a mesh, or two of them are not +/// apart (their exact boxes, grown by the bodies' tolerances, overlap). +pub fn union_apart(bodies: &[Body]) -> Result> { + crate::profile::timed(crate::profile::Kind::Boolean, "union_apart", || { + if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) { + return Ok(None); + } + let mut boxes = Vec::with_capacity(bodies.len()); + for b in bodies { + boxes.push(b.exact_bounds()?.inflated(2.0 * b.record().tolerance)); + } + // Sweep along x: only boxes whose x ranges overlap are compared. + let mut order: Vec = (0..boxes.len()).collect(); + order.sort_by(|&i, &j| boxes.get(i).map(|b| b.min.x).unwrap_or(0.0).total_cmp(&boxes.get(j).map(|b| b.min.x).unwrap_or(0.0))); + for (k, &i) in order.iter().enumerate() { + let Some(a) = boxes.get(i) else { continue }; + for &j in order.iter().skip(k + 1) { + let Some(b) = boxes.get(j) else { continue }; + if b.min.x > a.max.x { + break; } - let (Some(Some(x)), Some(Some(y))) = (corners.get(i), corners.get(j)) else { return Ok(None) }; - let Some(origin) = x.first() else { return Ok(None) }; - // Every straight extrusion lies inside the hull of its cap corners. - // A separating cap-edge axis therefore proves clearance even when - // rotated tools' world-coordinate boxes overlap. Arcs retain the box test. - let range = |points: &[Vec3], axis: Vec3| { - points.iter().map(|p| (*p - *origin).dot(axis)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v))) - }; - let rounding = origin.x.abs().max(origin.y.abs()).max(origin.z.abs()) * f64::EPSILON * 128.0; - let separated = axes.get(i).into_iter().flatten().chain(axes.get(j).into_iter().flatten()).any(|axis| { - let Some(left) = remaining_separation_work.checked_sub(x.len().saturating_add(y.len())) else { return false }; - remaining_separation_work = left; - let (a, b) = (range(x, *axis), range(y, *axis)); - a.1 + gap + rounding < b.0 || b.1 + gap + rounding < a.0 - }); - if !separated { + if a.meets(b) { return Ok(None); } } } - let sources: std::collections::HashMap<_, _> = tools - .iter() - .flat_map(|tool| { - tool.solid - .face_iter() - .zip(tool.face_sources().unwrap_or_default()) - .map(|(face, source)| (face.id(), (face.orientation(), source.clone()))) - }) - .collect(); - let operands: Vec<_> = tools.iter().collect(); - let shells = tools.iter().flat_map(|tool| tool.solid.boundaries().clone()).collect(); - let solid = Solid::try_new(shells).map_err(|error| KernelError::Failed(format!("extrusion compound: {error}")))?; - let faces = tools - .iter() - .enumerate() - .flat_map(|(operand, tool)| (0..tool.face_count()).map(move |face| record::from_face(operand, face, crate::history::Change::Kept))) - .collect(); - let mut edges = HashMap::new(); - for (operand, tool) in tools.iter().enumerate() { - edges.extend(record::edge_origins(&tool.solid, operand)); - } - record::build(solid, &record::counts(&operands), Some(faces), Some(&edges)).map(|mut body| { - body.regularization_protected = tools.iter().any(|tool| tool.regularization_protected); - // Only unchanged face identities carry these transient tool witnesses. - // No whole-compound extrusion/producer certificate is created. - let mapped = body - .solid - .face_iter() - .map(|face| { - sources.get(&face.id()).filter(|(orientation, _)| *orientation == face.orientation()).and_then(|(_, source)| source.clone()) - }) - .collect(); - Some(body.with_face_sources(Some(std::sync::Arc::new(mapped)))) - }) + join_apart(bodies) }) } -/// Whether a union can sew two matching planar faces without intersecting them. -/// Callers can retain the exact touching tool instead of extending it into material. -pub fn can_join_touching_faces(a: &Body, b: &Body) -> bool { - a.solid.boundaries().len() == 1 && b.solid.boundaries().len() == 1 && crate::coplanar::glue(a, b).is_some_and(|r| r.is_ok()) -} - -/// Check all separated extrusion starts in one construction, without rebuilding -/// the unchanged target once for each face. Partial seams keep the ordinary path. -pub fn can_join_all_touching_faces(a: &Body, b: &Body) -> bool { - if a.solid.boundaries().len() != 1 || !(2..=1024).contains(&b.solid.boundaries().len()) || a.face_count().max(b.face_count()) > 16_384 { - return false; - } - guard("check extrusion seams", || Ok(crate::coplanar::glue_all_caps(a, b).is_some_and(|result| result.is_ok()))).unwrap_or(false) -} - -/// Shifts applied to both operands on retries. The boolean classifies some faces by casting a -/// ray whose direction is derived from point coordinates; moving both solids (and the result -/// back) leaves the geometry unchanged but changes those rays. -const JITTER: [[f64; 3]; 4] = [[0.0, 0.0, 0.0], [0.1373, 0.2719, 0.3911], [-0.5127, 0.0833, 0.2291], [0.6911, -0.3337, -0.6127]]; - -fn volume(b: &Body) -> f64 { - // Measured once per (solid, tolerance) and shared by clones, so an operand a later - // boolean takes again is not meshed twice for the same number. - b.volume_at(b.size() * 2e-3).unwrap_or(f64::NAN) -} - -/// Halton low-discrepancy value (base `b`) for index `i`. -fn halton(mut i: usize, b: usize) -> f64 { - let (mut f, mut r) = (1.0, 0.0); - while i > 0 { - f /= b as f64; - r += f * (i % b) as f64; - i /= b; - } - r -} - -/// Fraction of sample points where `result` disagrees with `op` applied to `a` and `b` -/// (membership by ray parity). Samples cover the overlap box densely and the union box lightly. -fn mismatch(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh, result: &solidcraft_geom::Mesh, op: BoolOp) -> Option { - if a.triangles.len() + b.triangles.len() + result.triangles.len() > 60_000 { - return None; - } - let (ba, bb) = (a.bounds(), b.bounds()); - let lo = ba.min.max(bb.min); - let hi = ba.max.min(bb.max); - let all = ba.union(&bb); - let mut boxes = vec![(all, 300usize)]; - // A touching seam can overlap by round-off only. Samples there sit on the - // operands' boundaries, where ray parity cannot classify membership reliably. - let gap = all.diagonal().max(1.0) * 1e-9; - if hi.x - lo.x > gap && hi.y - lo.y > gap && hi.z - lo.z > gap { - boxes.push((solidcraft_geom::Aabb3 { min: lo, max: hi }, 900)); - } - let (ia_idx, ib_idx, ir_idx) = (a.inside_index(), b.inside_index(), result.inside_index()); - let (mut n, mut bad) = (0usize, 0usize); - for (bx, count) in boxes { - let s = bx.size(); - for i in 1..=count { - let p = bx.min + Vec3::new(s.x * halton(i, 2), s.y * halton(i, 3), s.z * halton(i, 5)); - let (ia, ib) = (ia_idx.contains(p), ib_idx.contains(p)); - let want = match op { - BoolOp::Union => ia || ib, - BoolOp::Cut => ia && !ib, - BoolOp::Intersect => ia && ib, - }; - n += 1; - if ir_idx.contains(p) != want { - bad += 1; - } - } - } - Some(bad as f64 / n.max(1) as f64) -} - -/// How one body sits relative to another, from sample points: (fraction of `b`'s samples -/// inside `a`, fraction of `a`'s samples inside `b`). -fn overlap( - a: &solidcraft_geom::Mesh, - b: &solidcraft_geom::Mesh, - ia: &solidcraft_geom::InsideIndex, - ib: &solidcraft_geom::InsideIndex, -) -> Option<(f64, f64)> { - let frac = |inner: &solidcraft_geom::Mesh, inner_i: &solidcraft_geom::InsideIndex, outer_i: &solidcraft_geom::InsideIndex| -> Option { - let bx = inner.bounds(); - let s = bx.size(); - let (mut n, mut hit) = (0usize, 0usize); - // A slender body lying across its box (a long hole tool drilled at an angle) fills - // little of it: the samples go on past the first 2000 until enough land inside. - for i in 1..=64_000 { - if i > 2000 && n >= 50 { - break; - } - let p = bx.min + Vec3::new(s.x * halton(i, 2), s.y * halton(i, 3), s.z * halton(i, 5)); - if !inner_i.contains(p) { - continue; - } - n += 1; - if outer_i.contains(p) { - hit += 1; - } - } - (n >= 50).then(|| hit as f64 / n as f64) - }; - Some((frac(b, ib, ia)?, frac(a, ia, ib)?)) -} - -/// Whether some facet of `m` has material just under it (`depth` in from its middle) that is -/// inside the other body (`inside`) or outside it. With `within`, only facets in that box. -/// Points for which `ignored` holds, asked with the point and the facet's face (`u32::MAX` -/// where the mesh has none), are no evidence either. -fn under_surface( - m: &solidcraft_geom::Mesh, - own: &solidcraft_geom::InsideIndex, - other: &solidcraft_geom::InsideIndex, - depth: f64, - inside: bool, - within: Option<&solidcraft_geom::Aabb3>, - ignored: &dyn Fn(Vec3, u32) -> bool, -) -> bool { - m.triangles.iter().enumerate().filter_map(|(i, t)| Some((m.tri(t)?, m.tri_face.get(i).copied().unwrap_or(u32::MAX)))).any(|([p, q, r], face)| { - let Some(n) = (q - p).cross(r - p).normalized() else { return false }; - let c = (p + q + r) * (1.0 / 3.0) - n * depth; - let near = within.is_none_or(|b| c.x >= b.min.x && c.x <= b.max.x && c.y >= b.min.y && c.y <= b.max.y && c.z >= b.min.z && c.z <= b.max.z); - // A wall thinner than `depth` puts the point outside its own body: no evidence. - near && other.contains(c) == inside && own.contains(c) && !ignored(c, face) - }) -} - -/// Whether the bodies' facetings show that the samples' answer (see [`trivial`]) is wrong: -/// their surfaces pass through each other, or a facet of one has material under it on the -/// wrong side of the other. Overlaps and gaps shallower than `tol` are not seen, nor surfaces -/// that pass through each other only on a cylinder both bodies have faces on, there between -/// those faces or one of them and an end face across its axis, nor material under such an end -/// face's facets at the cylinder (`shared`, asked only when the facetings disagree). -fn contradicted( - (ma, ia): (&solidcraft_geom::Mesh, &solidcraft_geom::InsideIndex), - (mb, ib): (&solidcraft_geom::Mesh, &solidcraft_geom::InsideIndex), - (disjoint, b_in_a, a_in_b): (bool, bool, bool), - tol: f64, - shared: &dyn Fn() -> SharedCylinders, -) -> bool { - if !(disjoint || b_in_a || a_in_b) { - return false; - } - let cylinders = std::cell::OnceCell::new(); - let shared = || cylinders.get_or_init(shared); - if ma.crosses(mb, tol) { - let shared = shared(); - if shared.cylinders.is_empty() || ma.crosses_except(mb, tol, |p, fa, fb| shared.ignores(p, fa, fb, tol)) { - return true; - } - } - // The end faces of a shared cylinder end on it at their own faceting: a facet of a pin's end - // inside the hole, or of the hole part's end face round the pin, has its middle within the - // facetings' error of the cylinder, where the other body's facets can reach over it. - let (under_a, under_b) = (|p: Vec3, f: u32| shared().under_cap(p, f, true, tol), |p: Vec3, f: u32| shared().under_cap(p, f, false, tol)); - if disjoint { - let (ba, bb) = (ma.bounds(), mb.bounds()); - let meet = ba.intersection(&bb); - return !meet.is_empty() - && (under_surface(ma, ia, ib, tol, true, Some(&meet), &under_a) || under_surface(mb, ib, ia, tol, true, Some(&meet), &under_b)); - } - (a_in_b && under_surface(ma, ia, ib, tol, false, None, &under_a)) || (b_in_a && !a_in_b && under_surface(mb, ib, ia, tol, false, None, &under_b)) -} - -/// Sampled overlap fraction below which two bodies share no material. -const NONE: f64 = 0.003; - -/// A cylinder both bodies have faces on (a pin in a hole of its own size, a bore drilled again), -/// and where along its axis both do. The two facetings of it are chords of one circle at -/// different angles: where one body's facets end on it (a pin's wall through the end face of the -/// hole's part, the pin's end inside the hole) they cross the other's by up to the facetings' -/// error, though the surfaces only touch. -struct SharedCylinder { - origin: Vec3, - axis: Vec3, - radius: f64, - span: (f64, f64), - /// The faces on it: of the first body, of the second. - faces: (usize, usize), - /// The end faces across its axis that keep to their body's side of it (a hole part's end - /// face round the hole, a pin's end inside it), within the facetings' error: of the first - /// body, of the second. A D-bore's end face, which reaches into the cylinder to the flat, - /// is not one. - caps: (Vec, Vec), -} - -impl SharedCylinder { - /// Whether `p` lies on the cylinder, within `tol`, where both bodies have faces on it. - fn holds(&self, p: Vec3, tol: f64) -> bool { - let v = p - self.origin; - let along = v.dot(self.axis); - ((v - self.axis * along).len() - self.radius).abs() <= tol && along >= self.span.0 - tol && along <= self.span.1 + tol - } -} - -/// The cylinders both bodies have faces on (see [`shared_cylinders`]). -#[derive(Default)] -struct SharedCylinders { - cylinders: Vec, -} - -impl SharedCylinders { - /// Whether a crossing at `p` of the first body's face `fa` with the second's `fb` is only - /// the facetings of a shared cylinder: on it, between the two faces on it, or between one of - /// them and one of its end faces (a pin's wall through the hole part's end face, the pin's - /// end inside the hole). A flat, key or rib along the axis still counts. - fn ignores(&self, p: Vec3, fa: u32, fb: u32, tol: f64) -> bool { - let (fa, fb) = (fa as usize, fb as usize); - self.cylinders.iter().any(|c| { - let (on_a, on_b) = (fa == c.faces.0, fb == c.faces.1); - ((on_a && on_b) || (on_a && c.caps.1.contains(&fb)) || (c.caps.0.contains(&fa) && on_b)) && c.holds(p, tol) - }) - } - - /// Whether `p`, just under a facet of the first body's face `face` (`first`) or the second's, - /// lies within `tol` of a shared cylinder with that face one of its end faces: material the - /// other body's facets of the cylinder can cover there, though the surfaces only touch. - fn under_cap(&self, p: Vec3, face: u32, first: bool, tol: f64) -> bool { - let face = face as usize; - self.cylinders.iter().any(|c| (if first { &c.caps.0 } else { &c.caps.1 }).contains(&face) && c.holds(p, tol)) - } -} - -/// The cylinders on which both `a` and `b` have faces: axes parallel and within `same` of each -/// other, radii within `same` (a pin a hair off its hole's axis shares a crescent, which this -/// tolerance leaves far below any volume worth reporting). Spans from the meshes `ma`, `mb`. -fn shared_cylinders(a: &Body, b: &Body, ma: &solidcraft_geom::Mesh, mb: &solidcraft_geom::Mesh, same: f64) -> SharedCylinders { - let cylinders = |body: &Body| -> Vec<(usize, Vec3, Vec3, f64)> { - (0..body.face_count()) - .filter_map(|i| match crate::face_surface(body, i)? { - crate::FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => { - Some((i, origin, axis.normalized()?, radius)) - } - _ => None, - }) - .collect() - }; - let (ca, cb) = (cylinders(a), cylinders(b)); - if ca.is_empty() || cb.is_empty() { - return SharedCylinders::default(); - } - // Where a face's facets reach along an axis. - let span = |m: &solidcraft_geom::Mesh, face: usize, origin: Vec3, axis: Vec3| -> Option<(f64, f64)> { - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - if *f as usize != face { - continue; - } - for p in m.tri(t)? { - let s = (p - origin).dot(axis); - lo = lo.min(s); - hi = hi.max(s); - } - } - (lo <= hi).then_some((lo, hi)) - }; - // A face's facets. - fn facets(m: &solidcraft_geom::Mesh, face: usize) -> impl Iterator + '_ { - m.triangles.iter().zip(&m.tri_face).filter(move |(_, f)| **f as usize == face).filter_map(|(t, _)| m.tri(t)) - } - // How near to and far from an axis a face's facets reach (nearest on their edges), and - // whether its material is inside the cylinder there (its normals point away from the axis). - let reach = |m: &solidcraft_geom::Mesh, face: usize, origin: Vec3, axis: Vec3| -> (f64, f64, bool) { - let radial = |p: Vec3| { - let v = p - origin; - v - axis * v.dot(axis) - }; - let (mut near, mut far, mut out) = (f64::INFINITY, 0.0f64, 0.0); - for t in facets(m, face) { - for (p, q) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { - let (p, q) = (radial(p), radial(q)); - let d = q - p; - let s = if d.dot(d) > 0.0 { (-p.dot(d) / d.dot(d)).clamp(0.0, 1.0) } else { 0.0 }; - near = near.min((p + d * s).len()); - far = far.max(p.len()); - } - out += (t[1] - t[0]).cross(t[2] - t[0]).dot(radial((t[0] + t[1] + t[2]) * (1.0 / 3.0))); - } - (near, far, out > 0.0) - }; - let planes = |body: &Body| -> Vec<(usize, Vec3)> { - (0..body.face_count()) - .filter_map(|i| match crate::face_surface(body, i)? { - crate::FaceSurface::Plane { normal, .. } => Some((i, normal.normalized()?)), - _ => None, - }) - .collect() - }; - let (pa, pb) = (planes(a), planes(b)); - let mut out = Vec::new(); - for &(fa, oa, xa, ra) in &ca { - for &(fb, ob, xb, rb) in &cb { - let d = ob - oa; - if xa.dot(xb).abs() <= 1.0 - 1e-9 || (ra - rb).abs() > same || (d - xa * d.dot(xa)).len() > same { - continue; - } - let (Some(sa), Some(sb)) = (span(ma, fa, oa, xa), span(mb, fb, oa, xa)) else { continue }; - let (lo, hi) = (sa.0.max(sb.0), sa.1.min(sb.1)); - if lo > hi { - continue; - } - // The facetings' error on the cylinder: how far inside it their chords pass. - let ((na, _, boss_a), (nb, _, boss_b)) = (reach(ma, fa, oa, xa), reach(mb, fb, oa, xa)); - let error = 2.0 * (ra - na).max(ra - nb).max(0.0) + same; - // End faces across the axis that keep to their body's side of the cylinder. - let caps = |m: &solidcraft_geom::Mesh, planes: &[(usize, Vec3)], boss: bool| -> Vec { - planes - .iter() - .filter(|(_, n)| n.dot(xa).abs() >= 1.0 - 1e-6) - .filter(|(i, _)| { - let (near, far, _) = reach(m, *i, oa, xa); - near <= far && if boss { far <= ra + error } else { near >= ra - error } - }) - .map(|(i, _)| *i) - .collect() - }; - let caps = (caps(ma, &pa, boss_a), caps(mb, &pb, boss_b)); - out.push(SharedCylinder { origin: oa, axis: xa, radius: ra, span: (lo, hi), faces: (fa, fb), caps }); - } - } - SharedCylinders { cylinders: out } -} - -/// Booleans that need no intersection: one body clear of the other, or inside it. These are -/// common with coincident curved faces (a hole drilled where one already is, a body joined -/// with itself), which the intersection can't handle. `counts`: the operands' faces and edges. -/// `tol`: how far the meshes' surfaces may pass through each other and still count as touching -/// (they are facetings of the bodies, so a few times their tolerance). -/// -/// The second value is false when the facetings contradict the samples ([`contradicted`]): -/// the answer is then only what to fall back on if the bodies can't be intersected. -fn trivial( - a: &Body, - b: &Body, - op: BoolOp, - ma: &solidcraft_geom::Mesh, - mb: &solidcraft_geom::Mesh, - counts: &[(usize, usize)], - tol: f64, -) -> Option<(Option, bool)> { - if ma.triangles.len() + mb.triangles.len() > 80_000 { - return None; - } - let (ia, ib) = (ma.inside_index(), mb.inside_index()); - let (b_in_a, a_in_b) = overlap(ma, mb, &ia, &ib)?; - const ALL: f64 = 0.997; - let disjoint = b_in_a < NONE && a_in_b < NONE; - // The samples only say that nearly all of one body is clear of, or inside, the other. A - // small part can still be on the wrong side (a peg overlapping a rib, a chamfer taken off - // one edge), and then the bodies have to be intersected. - // The same surface as the kernel takes it elsewhere (see `coaxial_overlap`). - let same = (a.size().max(b.size()) * 1e-7).max(1e-9) * 10.0; - let shared = || shared_cylinders(a, b, ma, mb, same); - let sure = !contradicted((ma, &ia), (mb, &ib), (disjoint, b_in_a > ALL, a_in_b > ALL), tol, &shared); - let answer = match op { - // Sampling only selects this candidate. Validate every shell boundary and the - // complete material/void nesting before preserving a disconnected union. - BoolOp::Union if disjoint => { - let pieces = vec![(a.clone(), recorded::kept(a, 0, 2)), (b.clone(), recorded::kept(b, 1, 2))]; - let joined = recorded::join(pieces, counts).ok().flatten()?; - joined.separated_lumps().ok()?; - Some(Some(joined)) - } - BoolOp::Cut if disjoint => Some(Some(recorded::operand(a, 0, counts))), - BoolOp::Cut if a_in_b > ALL => Some(None), - BoolOp::Intersect if disjoint => Some(None), - BoolOp::Intersect if b_in_a > ALL => Some(Some(recorded::operand(b, 1, counts))), - BoolOp::Intersect if a_in_b > ALL => Some(Some(recorded::operand(a, 0, counts))), - BoolOp::Union if b_in_a > ALL => Some(Some(recorded::operand(a, 0, counts))), - BoolOp::Union if a_in_b > ALL => Some(Some(recorded::operand(b, 1, counts))), - // The tool wholly inside, clear of the outside: a void. - BoolOp::Cut if b_in_a > ALL => { - let candidate = void(a, b, counts).ok().flatten()?; - candidate.separated_lumps().ok()?; - Some(Some(candidate)) - } - _ => None, - }; - answer.map(|r| (r, sure)) -} - -#[cfg(test)] -mod shortcut_tests { - use super::*; - - #[test] - fn seam_roundoff_is_not_a_thin_meeting_but_real_thin_solids_are() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - - // This circle's seams lie on the X axis: its cylinder's vertex box is flat in Y. - let region = Region2 { outer: Loop2::circle(Vec2::ZERO, 8.0), holes: vec![] }; - let periodic = crate::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap(); - let block = crate::box_solid(Vec3::new(-40.0, -40.0, -10.0), Vec3::new(40.0, 40.0, 10.0)).unwrap(); - assert!(meeting_size(&periodic, &block).is_infinite()); - let thin = crate::box_solid(Vec3::ZERO, Vec3::new(80.0, 80.0, 1e-5)).unwrap(); - assert!((meeting_size(&thin, &thin) - 1e-5).abs() < 1e-12); - } - - #[test] - fn rotated_extrusion_bounds_use_exact_cap_separation_and_keep_sources() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let rectangle = |angle: f64, offset: f64| { - let (c, s) = (angle.cos(), angle.sin()); - Region2 { - outer: Loop2::polygon( - &[(-2., -0.5), (2., -0.5), (2., 0.5), (-2., 0.5)].map(|(x, y)| Vec2::new(x * c - (y + offset) * s, x * s + (y + offset) * c)), - ), - holes: vec![], - } - }; - for offset in [1.2, 1., 0.8] { - let tools = crate::extrude(&Plane::XY, &[rectangle(0.7, 0.), rectangle(0.7, offset)], 0., 2.).unwrap(); - let compound = compound_disjoint_extrusions(&tools).unwrap(); - assert_eq!(compound.is_some(), offset > 1.); - if let Some(compound) = compound { - let sources = compound.face_sources().unwrap(); - assert_eq!(sources.len(), compound.face_count()); - assert_eq!(sources.iter().filter(|source| matches!(source, Some(crate::FaceSource::ExtrudeCap { high: false, .. }))).count(), 2); - assert!(compound.validity().is_empty()); - } - } - } - - #[test] - fn batched_contact_test_matches_individual_tolerances() { - let target = crate::cylinder(Vec3::ZERO, Vec3::Z, 5., 3.).unwrap(); - let tools = [ - crate::box_solid(Vec3::new(-1., -1., 3.), Vec3::new(1., 1., 5.)).unwrap(), - crate::box_solid(Vec3::new(-1., -1., 3.002), Vec3::new(1., 1., 5.)).unwrap(), - crate::sphere(Vec3::new(20., 0., 1.), 1.).unwrap(), - ]; - let expected = tools.iter().map(|tool| target.meets(tool).unwrap()).collect::>(); - assert_eq!(target.meets_each(&tools).unwrap(), expected); - assert!(target.meets_each(&[]).unwrap().is_empty()); - } - - #[test] - fn compound_span_does_not_relax_full_face_seam_tolerance() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let mut target = crate::box_solid(Vec3::new(0., 0., -3.), Vec3::new(100., 2., -2.)).unwrap(); - for x in [0., 98.] { - let boss = crate::box_solid(Vec3::new(x, 0., -2.), Vec3::new(x + 2., 2., 0.)).unwrap(); - target = boolean(&target, &boss, BoolOp::Union).unwrap().unwrap(); - } - let regions: Vec<_> = [0., 98.] - .into_iter() - .map(|x| Region2 { - outer: Loop2::polygon(&[Vec2::new(x, 0.), Vec2::new(x + 2., 0.), Vec2::new(x + 2., 2.), Vec2::new(x, 2.)]), - holes: vec![], - }) - .collect(); - let tools = crate::extrude(&Plane::XY, ®ions, 0.000_105, 200.).unwrap(); - assert!(tools.iter().all(|tool| !can_join_touching_faces(&target, tool))); - let compound = compound_disjoint_extrusions(&tools).unwrap().unwrap(); - assert!(!can_join_all_touching_faces(&target, &compound)); - } - - #[test] - fn extrusion_compound_requires_separated_construction_bounds() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let rectangle = |x: f64| Region2 { - outer: Loop2::polygon(&[Vec2::new(x, 0.0), Vec2::new(x + 2.0, 0.0), Vec2::new(x + 2.0, 2.0), Vec2::new(x, 2.0)]), - holes: vec![], - }; - let plane = Plane::from_normal(Vec3::new(100.0, -20.0, 8.0), Vec3::new(1.0, 2.0, 3.0)).unwrap(); - let tools = crate::extrude(&plane, &[rectangle(0.0), rectangle(20.0)], -1.0, 5.0).unwrap(); - let compound = compound_disjoint_extrusions(&tools).unwrap().unwrap(); - assert_eq!(compound.shell_count(), 2); - assert_eq!(compound.history().unwrap().operands, 2); - assert!((crate::measure(&compound).unwrap().volume - 48.0).abs() < 1e-8); - assert!(compound.validity().is_empty()); - for x in [1.0, 2.0, 2.000_000_1] { - let touching = crate::extrude(&solidcraft_geom::Plane::XY, &[rectangle(0.0), rectangle(x)], 0.0, 5.0).unwrap(); - assert!(compound_disjoint_extrusions(&touching).unwrap().is_none()); - } - let unsupported = [crate::sphere(Vec3::ZERO, 1.0).unwrap(), crate::sphere(Vec3::new(10.0, 0.0, 0.0), 1.0).unwrap()]; - assert!(compound_disjoint_extrusions(&unsupported).unwrap().is_none()); - } - - #[test] - fn extrusion_compound_includes_arc_extrema_between_seam_vertices() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let circle = |x| Region2 { outer: Loop2::circle(Vec2::new(x, 0.0), 2.0), holes: vec![] }; - let separated = crate::extrude(&Plane::XY, &[circle(0.0), circle(8.0)], 0.0, 5.0).unwrap(); - assert!(compound_disjoint_extrusions(&separated).unwrap().is_some()); - let overlapping = crate::extrude(&Plane::XY, &[circle(0.0), circle(3.0)], 0.0, 5.0).unwrap(); - assert!(compound_disjoint_extrusions(&overlapping).unwrap().is_none()); - } - - #[test] - fn curved_near_contact_never_uses_a_shell_only_boolean_candidate() { - let direction = Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(); - let outer = crate::sphere(Vec3::ZERO, 10.0).unwrap(); - let mesh = outer.tessellate(0.03).unwrap(); - for distance in [19.999, 20.001] { - let other = crate::sphere(direction * distance, 10.0).unwrap(); - let other_mesh = other.tessellate(0.03).unwrap(); - let counts = record::counts(&[&outer, &other]); - assert!(trivial(&outer, &other, BoolOp::Union, &mesh, &other_mesh, &counts, 0.09).is_none()); - assert!(trivial(&other, &outer, BoolOp::Union, &other_mesh, &mesh, &counts, 0.09).is_none()); - } - let protruding = crate::sphere(direction * 9.001, 1.0).unwrap(); - let protruding_mesh = protruding.tessellate(0.03).unwrap(); - let counts = record::counts(&[&outer, &protruding]); - assert!(trivial(&outer, &protruding, BoolOp::Cut, &mesh, &protruding_mesh, &counts, 0.09).is_none()); - } - - /// A pin turned from a profile (its wall in three faces) in the bore of a tube (its wall in - /// two): one cylinder, faceted at different angles, so the pin's facets cross the tube's end - /// face and the bore's facets cross the pin's end by the facetings' error. The pin is still - /// clear of the tube, exactly on its axis or a hair off it (parts placed from rounded - /// coordinates), with the pin's end inside the bore or through it, and with a slit along - /// the tube: answered at once, without the boolean's retries. - #[test] - fn a_pin_in_a_bore_of_its_size_is_clear_of_it_whatever_the_facets() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let rect = |x1: f64, y0: f64, y1: f64| Region2 { - outer: Loop2::polygon(&[Vec2::new(0.0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(0.0, y1)]), - holes: vec![], - }; - let pin = |off: Vec3, z0: f64, z1: f64| { - let plane = Plane { origin: off, x: Vec3::X, y: Vec3::Z }; - crate::revolve(&plane, &[rect(3.0, z0, z1)], Vec2::ZERO, Vec2::new(0.0, 1.0), std::f64::consts::TAU).unwrap().pop().unwrap() - }; - let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, 19.55).unwrap(); - let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 21.55).unwrap(); - let tube = boolean(&outer, &bore, BoolOp::Cut).unwrap().unwrap(); - let slit = crate::box_solid(Vec3::new(-6.0, -0.05, -1.0), Vec3::new(0.0, 0.05, 21.0)).unwrap(); - let slit_tube = boolean(&tube, &slit, BoolOp::Cut).unwrap().unwrap(); - let tube_volume = crate::measure(&tube).unwrap().volume; - for off in [Vec3::ZERO, Vec3::new(2.2e-8, 4.7e-7, 0.0)] { - for (p, t) in [(pin(off, -2.35, 9.65), &tube), (pin(off, -3.0, 22.0), &tube), (pin(off, -2.35, 9.65), &slit_tube)] { - assert_eq!(p.face_count(), 5); - for (x, y) in [(&p, t), (t, &p)] { - let (r, report) = crate::capture_boolean_diagnostics(|| boolean(x, y, BoolOp::Intersect)); - assert!(r.unwrap().is_none() && report.events.is_empty(), "{off:?} {report:?}"); - } - let cut = boolean(&tube, &p, BoolOp::Cut).unwrap().unwrap(); - assert!((crate::measure(&cut).unwrap().volume - tube_volume).abs() < 1e-6 * tube_volume); - } - } - // Off the axis by 0.01 mm the pin shares a crescent with the tube: not taken for apart. - let (ma, mb) = (pin(Vec3::new(0.01, 0.0, 0.0), -2.35, 9.65), tube.clone()); - let counts = record::counts(&[&ma, &mb]); - let (sa, sb) = (ma.tessellate_with(0.009, true).unwrap(), mb.tessellate_with(0.009, true).unwrap()); - assert!(trivial(&ma, &mb, BoolOp::Intersect, &sa, &sb, &counts, 0.027).is_none_or(|(_, sure)| !sure)); - } - - /// A pin turned from a profile (its wall in three faces) and a plate with a bore of the pin's - /// size (its wall in two), the pin's end inside the bore: turned about the pin's axis and - /// the pair placed and tilted. - fn pin_in_plate_bore(radius: f64, turn: f64, (to, axis, angle): (Vec3, Vec3, f64)) -> (Body, Body) { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let profile = Region2 { - outer: Loop2::polygon(&[Vec2::new(0.0, -2.35), Vec2::new(radius, -2.35), Vec2::new(radius, 9.65), Vec2::new(0.0, 9.65)]), - holes: vec![], - }; - let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; - let pin = crate::revolve(&plane, &[profile], Vec2::ZERO, Vec2::new(0.0, 1.0), std::f64::consts::TAU).unwrap().pop().unwrap(); - let pin = crate::transform(&pin, Vec3::ZERO, Vec3::ZERO, Vec3::Z, turn).unwrap(); - let block = crate::box_solid(Vec3::new(-8.0, -8.0, 0.0), Vec3::new(8.0, 8.0, 19.5)).unwrap(); - let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 21.5).unwrap(); - let plate = boolean(&block, &bore, BoolOp::Cut).unwrap().unwrap(); - let place = |b: &Body| crate::transform(b, to, Vec3::ZERO, axis, angle).unwrap(); - (place(&pin), place(&plate)) - } - - /// Placements of the pair: as built, far off the origin on its side, and tilted two ways. - const PLACEMENTS: [(Vec3, Vec3, f64); 4] = [ - (Vec3::ZERO, Vec3::Z, 0.0), - (Vec3::new(-270.0, 267.1, 546.7), Vec3::Y, -std::f64::consts::FRAC_PI_2), - (Vec3::new(120.0, -40.0, 15.0), Vec3::new(1.0, 1.0, 0.0), 0.7), - (Vec3::new(-35.0, 80.0, -60.0), Vec3::new(0.3, -0.5, 1.0), 2.1), - ]; - - /// The pin's end lies on the bore's rim at its own faceting, the plate's end face round the - /// pin at the bore's: the middle of a facet there can be just under the other body's facets - /// of the cylinder, so the material under it looked inside the other body though the two - /// only touch (the pin turned 9 steps and the pair tilted about x = y did, the boolean then - /// fell back on its retries and called its answer unverified). At every turn and placement - /// the pin is clear of the plate, answered at once. - #[test] - fn a_pin_in_a_plate_bore_of_its_size_is_clear_of_it_at_any_placement() { - for k in 0..12 { - for placement in PLACEMENTS { - let (pin, plate) = pin_in_plate_bore(3.0, k as f64 * 0.13, placement); - for (x, y) in [(&pin, &plate), (&plate, &pin)] { - let (r, report) = crate::capture_boolean_diagnostics(|| boolean(x, y, BoolOp::Intersect)); - assert!(matches!(r, Ok(None)) && report.events.is_empty(), "{k} {placement:?} {r:?} {report:?}"); - } - } - } - } - - /// The same pin 0.02 mm larger than the bore shares a ring with the plate along the length - /// it is in it: an overlap, at the placements above too. - #[test] - fn a_pin_slightly_larger_than_its_plate_bore_still_overlaps_it() { - let want = std::f64::consts::PI * (3.02f64.powi(2) - 9.0) * 9.65; - for k in [0, 3, 6, 9] { - for placement in PLACEMENTS { - let (pin, plate) = pin_in_plate_bore(3.02, k as f64 * 0.13, placement); - let (r, report) = crate::capture_boolean_diagnostics(|| boolean(&pin, &plate, BoolOp::Intersect)); - let shared = r.unwrap().map(|b| crate::measure(&b).unwrap().volume); - assert!(shared.is_some_and(|v| (v - want).abs() < 0.05 * want), "{k} {placement:?} {shared:?} {want} {report:?}"); - } - } - } - - /// A pin of the bore's size pushed 0.05 mm on past the bore, into a narrower one, shares a - /// ring with the tube there (0.2 % of the pin, under what the samples see): the crossings on - /// the shared cylinder are left out, those of the pin's end with the narrow bore are not. - #[test] - fn a_pin_pushed_into_a_narrower_bore_is_not_taken_for_clear() { - let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, 19.55).unwrap(); - let wide = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 10.0).unwrap(); - let narrow = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 2.0, 21.55).unwrap(); - let tube = boolean(&boolean(&outer, &wide, BoolOp::Cut).unwrap().unwrap(), &narrow, BoolOp::Cut).unwrap().unwrap(); - let pin = crate::cylinder(Vec3::new(0.0, 0.0, -2.0), Vec3::Z, 3.0, 11.05).unwrap(); - let counts = record::counts(&[&pin, &tube]); - let (ma, mb) = (pin.tessellate_with(0.009, true).unwrap(), tube.tessellate_with(0.009, true).unwrap()); - for op in [BoolOp::Intersect, BoolOp::Cut] { - assert!(trivial(&pin, &tube, op, &ma, &mb, &counts, 0.027).is_none_or(|(_, sure)| !sure), "{op:?}"); - } - } - - /// A pin of the bore's size through a D-bore whose flat is 0.022 mm inside the pin (a sliver - /// of 0.21 mm³ along the bore): the pin's wall passes through the tube's end faces where the - /// flat reaches into the cylinder, near the shared cylinder but deeper than its facetings' - /// error. That is real overlap, and must not be taken for the facetings of the cylinder. - #[test] - fn a_pin_through_a_d_bore_of_its_size_still_overlaps_the_flat() { - let (r, flat, length) = (3.0, 2.978, 19.55); - let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, length).unwrap(); - let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, r, length + 2.0).unwrap(); - let keep = crate::box_solid(Vec3::new(-4.0, -4.0, -2.0), Vec3::new(flat, 4.0, length + 2.0)).unwrap(); - let d_bore = boolean(&bore, &keep, BoolOp::Intersect).unwrap().unwrap(); - let tube = boolean(&outer, &d_bore, BoolOp::Cut).unwrap().unwrap(); - let pin = crate::cylinder(Vec3::new(0.0, 0.0, -3.0), Vec3::Z, r, length + 6.0).unwrap(); - // Faceted as the boolean does for bodies of this size (0.015 mm deep crossings seen). - let counts = record::counts(&[&pin, &tube]); - let (ma, mb) = (pin.tessellate_with(0.005, true).unwrap(), tube.tessellate_with(0.005, true).unwrap()); - for op in [BoolOp::Intersect, BoolOp::Cut] { - assert!(trivial(&pin, &tube, op, &ma, &mb, &counts, 0.015).is_none_or(|(_, sure)| !sure), "{op:?}"); - } - // Nor does the boolean pass them as clear without saying so: the shortcut it falls back - // on is reported unverified (the bodies can't be intersected along the shared walls), - // and the caller measures the overlap another way. - let (shared, report) = crate::capture_boolean_diagnostics(|| boolean(&pin, &tube, BoolOp::Intersect)); - assert!(shared.unwrap().is_some() || report.unverified().is_some(), "{report:?}"); - } - - /// Bodies sharing less than the samples can see still meet: no shortcut, and the boolean - /// gives the shared part. - #[test] - fn a_small_overlap_is_not_taken_for_apart_or_inside() { - let cube = |x: f64, y: f64| crate::box_solid(Vec3::new(x, y, 0.0), Vec3::new(x + 10.0, y + 10.0, 10.0)).unwrap(); - let a = cube(0.0, 0.0); - // A 0.01 slab between parallel faces (0.1 % of each cube), and a 0.02 x 0.02 corner. - for (b, want) in [(cube(9.99, 0.0), 1.0), (cube(9.98, 9.98), 0.004)] { - let (ma, mb) = (a.tessellate(0.001).unwrap(), b.tessellate(0.001).unwrap()); - let counts = record::counts(&[&a, &b]); - for op in [BoolOp::Intersect, BoolOp::Cut, BoolOp::Union] { - assert!(trivial(&a, &b, op, &ma, &mb, &counts, 0.003).is_none_or(|(_, sure)| !sure), "{op:?} {want}"); - } - let shared = boolean(&a, &b, BoolOp::Intersect).unwrap().unwrap(); - assert!((crate::measure(&shared).unwrap().volume - want).abs() < 1e-9, "{want}"); - let cut = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap(); - assert!((crate::measure(&cut).unwrap().volume - (1000.0 - want)).abs() < 1e-9, "{want}"); - } - // Touching on a face, and one cube well inside the other, still take the shortcut. - let (touching, inner) = (cube(10.0, 0.0), crate::box_solid(Vec3::new(2.0, 2.0, 2.0), Vec3::new(8.0, 8.0, 8.0)).unwrap()); - let ma = a.tessellate(0.001).unwrap(); - for (b, op) in [(&touching, BoolOp::Intersect), (&inner, BoolOp::Intersect), (&inner, BoolOp::Union)] { - let counts = record::counts(&[&a, b]); - assert!(trivial(&a, b, op, &ma, &b.tessellate(0.001).unwrap(), &counts, 0.003).is_some_and(|(_, sure)| sure), "{op:?}"); - } - } -} - -/// `a` with the inside of `b` (wholly within it) taken out: a second, inward-facing shell. -fn void(a: &Body, b: &Body, counts: &[(usize, usize)]) -> Result> { - guard("void", || { - let mut inner = b.deep_copy(); - let inner_edges = record::edge_origins(&inner, 1); - inner.not(); - let mut shells = a.solid.boundaries().clone(); - shells.extend(inner.boundaries().iter().cloned()); - let s = crate::body::Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("void: {e}")))?; - let (faces, edges) = recorded::void(a, inner_edges, b.face_count()); - Ok(Some(record::build(s, counts, Some(faces), Some(&edges))?)) - }) -} - -thread_local! { - /// Set while a boolean runs on bodies whose coincident faces were pushed apart (no - /// second round of pushing). - static APART: std::cell::Cell = const { std::cell::Cell::new(false) }; - /// Set while a union runs with a bore narrowed off a common cylinder (no second round). - static BORES: std::cell::Cell = const { std::cell::Cell::new(false) }; - /// The intersections left to the booleans running under [`with_attempt_budget`], if any. - static ATTEMPTS: std::cell::Cell> = const { std::cell::Cell::new(None) }; -} - -/// `f`, with the booleans it runs on this thread allowed `attempts` of the kernel's own -/// intersections between them (each try of a boolean takes one): past those, a boolean fails at -/// once instead of trying on. For a caller that would rather report a pair it could not answer -/// than wait on bodies the boolean cannot take, and the same on every machine. A budget inside -/// another takes the smaller and uses up the outer one's too. -pub fn with_attempt_budget(attempts: usize, f: impl FnOnce() -> T) -> T { - struct Restore(Option, usize); - impl Drop for Restore { - fn drop(&mut self) { - let left = ATTEMPTS.with(|c| c.get()).unwrap_or(0); - ATTEMPTS.with(|c| c.set(self.0.map(|outer| outer.saturating_sub(self.1.saturating_sub(left))))); - } - } - let outer = ATTEMPTS.with(|c| c.get()); - let mine = outer.map_or(attempts, |o| o.min(attempts)); - ATTEMPTS.with(|c| c.set(Some(mine))); - let _restore = Restore(outer, mine); - f() -} - -/// Takes one of the attempts left under [`with_attempt_budget`]; false when none is left. -fn take_attempt() -> bool { - ATTEMPTS.with(|c| match c.get() { - None => true, - Some(0) => false, - Some(n) => { - c.set(Some(n - 1)); - true - } - }) -} - -/// Boolean of two bodies. The result may be empty (`Ok(None)`) for a cut that removes -/// everything or an intersection of disjoint bodies. Results are checked against volume bounds -/// and retried with shifted copies and other tolerances when they fail or look wrong. -/// -/// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`, -/// whichever way it was made, or none where a step it took does not report one. -pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { - crate::profile::timed(crate::profile::Kind::Boolean, || boolean_untimed(a, b, op)) -} - -fn boolean_untimed(a: &Body, b: &Body, op: BoolOp) -> Result> { - if let Some(r) = with_hollow_tool(a, b, op) { - return finished(a, b, op, Ok(r)); - } - // Earlier coarse bores can leave a junction a later pattern copy cannot intersect. - // Resolve conical-cut junctions from the first copy, while the operands are unchanged. - if op == BoolOp::Cut && !APART.with(|c| c.get()) && conical_cut_junction(a, b) { - let refined = |a: &Body, b: &Body, op| boolean_whole_with_refinement(a, b, op, true); - if let Ok(result) = boolean_via(a, b, op, &refined) { - return Ok(result); - } - } - let r = boolean_via(a, b, op, &boolean_whole); - if r.is_err() - && op == BoolOp::Cut - && !APART.with(|c| c.get()) - && let Some(result) = tool_reseam::cut(a, b) - { - return Ok(Some(result)); - } - if r.is_ok() || !crate::tangent_cylinders::needed(a, b) { - return r; - } - // Equal cylinders crossing each other touch at two points the boolean cannot take in the - // middle of a face (#788): once more with the faces split along them. - let split = |a: &Body, b: &Body, op| { - crate::tangent_cylinders::boolean(a, b, op, &boolean_whole).unwrap_or_else(|| Err(KernelError::Failed("no split of faces helps".into()))) - }; - boolean_via(a, b, op, &split).or(r) -} - -/// A conical cutter meeting a body with an earlier conical cut needs finer tracing at -/// their junctions. Guard the analytic recognition as well as the Boolean itself. -fn conical_cut_junction(a: &Body, b: &Body) -> bool { - guard("conical cut junction", || { - let conical = |body: &Body| { - let tol = (body.size() * 1e-5).max(1e-7); - body.solid.face_iter().any(|face| matches!(crate::offset::surf_of(face, tol), Some(crate::offset::Surf::Cone { .. }))) - }; - Ok(conical(b) && conical(a)) - }) - .unwrap_or(false) -} - -/// [`boolean`], the boolean of the whole bodies taken by `whole`. -fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, BoolOp) -> Result>) -> Result> { - let (mut r, mut diagnostics) = capture_boolean_diagnostics(|| whole(a, b, op)); - // Bodies in several pieces: when the whole failed (or came out empty), a piece at a time. - let retry = match &r { - Err(_) => true, - Ok(None) => op != BoolOp::Intersect, - Ok(Some(_)) => false, - }; - if retry && (a.solid.boundaries().len() > 1 || b.solid.boundaries().len() > 1) { - let (la, lb) = (a.lumps()?, b.lumps()?); - if la.len() > 1 || lb.len() > 1 { - let (pieces, report) = capture_boolean_diagnostics(|| by_lumps(a, b, la, lb, op)); - if let Ok(Some(x)) = pieces { - r = Ok(Some(x)); - diagnostics = report; - diagnostics.push(BooleanFallback::new(BooleanStrategy::Piecewise)); - } - } - } - // A piece with sealed voids, cut clear of them: the outer shell alone, the voids put back. - if op == BoolOp::Cut && r.is_err() { - let (cut, report) = capture_boolean_diagnostics(|| cut_around_voids(a, b, whole)); - if let Ok(Some(x)) = cut { - r = Ok(Some(x)); - diagnostics = report; - diagnostics.push(BooleanFallback::new(BooleanStrategy::Piecewise)); - } - } - if op == BoolOp::Union - && let Ok(Some(body)) = &r - && !preserves_planar_surfaces(a, b, body) - { - // Numerical retries must not quietly alter a planar design's dimensions. - // Prefer the exact polygon result; reject an edge-only pinch if it cannot - // form a closed solid without displacing either operand. - r = match crate::polybool::planar_boolean(a, b, op) { - Ok(Some(exact)) if preserves_planar_surfaces(a, b, &exact) => { - diagnostics = Default::default(); - diagnostics.events.push(BooleanFallback::new(BooleanStrategy::PlanarFallback)); - Ok(Some(exact)) - } - _ => Err(KernelError::Invalid( - "join cannot preserve the original faces; check for zero-thickness edge contact or add intentional overlap".into(), - )), - }; - } - r = finished(a, b, op, r); - // A retry's result is held to what the operation can do at all; one that fails is refused - // rather than returned wrong (issue #616). - if (!diagnostics.events.is_empty() || diagnostics.truncated) - && let Ok(result) = &r - && let Err(e) = crate::boolean_guard::check_retry(a, b, op, result.as_ref()) - { - let tried = diagnostics.summary().unwrap_or_default(); - r = Err(match e { - KernelError::Failed(m) => KernelError::Failed(format!("{m} ({})", tried.trim_start_matches("Boolean retry: "))), - other => other, - }); - } - if r.is_ok() { - merge(diagnostics); - } - r -} - -/// What a boolean's result keeps of its operands: their regularization protection, and the -/// sources of the planar faces it keeps. -fn finished(a: &Body, b: &Body, op: BoolOp, r: Result>) -> Result> { - let r = r.map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b))); - match op { - BoolOp::Cut => r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()), - BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), - // Every face of an intersection lies on one operand's face, as a union's does: the same - // roles carry over (#565). - BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), - } -} - -/// The most shells [`cut_around_voids`] takes apart. -const MAX_VOID_SHELLS: usize = 64; - -/// `a` cut by `b` around `a`'s voids: when `a` is one piece with sealed voids (inner shells) and -/// `b` stays clear of every void, the outer shell alone is cut and the voids are put back. The cut -/// of the whole failed on such bodies where the same cut of the outer shell works: a sphere cut -/// far from a void (robustness seed 15). `None` when `a` has no voids, `b` comes near one, or -/// the cut of the outer shell fails too. The result carries no history. -fn cut_around_voids(a: &Body, b: &Body, whole: &dyn Fn(&Body, &Body, BoolOp) -> Result>) -> Result> { - let shells = a.solid.boundaries().clone(); - if shells.len() < 2 || shells.len() > MAX_VOID_SHELLS || b.solid.boundaries().len() != 1 || a.lumps()?.len() != 1 { - return Ok(None); - } - let tol = (a.size() * 1e-3).max(1e-3); - let mut boxes = Vec::with_capacity(shells.len()); - for sh in &shells { - let piece = - guard("void shell", || Body::new(Solid::try_new(vec![sh.clone()]).map_err(|e| KernelError::Failed(format!("void shell: {e}")))?))?; - let m = piece.tessellate(tol)?; - if m.positions.is_empty() { - return Ok(None); - } - boxes.push(m.bounds()); - } - let extent = |i: usize| { - boxes.get(i).map_or(0.0, |x| { - let d = x.max - x.min; - d.x * d.y * d.z - }) - }; - let Some(outer) = (0..shells.len()).max_by(|i, j| extent(*i).total_cmp(&extent(*j))) else { return Ok(None) }; - let Some(ob) = boxes.get(outer) else { return Ok(None) }; - let tm = b.tessellate((b.size() * 1e-3).max(1e-3))?; - let tb = tm.bounds(); - // Clear of the tool by more than both meshes' deflection. - let gap = 4.0 * tol + (b.size() * 1e-3).max(1e-3); - let inside = |x: &solidcraft_geom::Aabb3| { - x.min.x >= ob.min.x && x.min.y >= ob.min.y && x.min.z >= ob.min.z && x.max.x <= ob.max.x && x.max.y <= ob.max.y && x.max.z <= ob.max.z - }; - let clear = |x: &solidcraft_geom::Aabb3| { - x.max.x + gap < tb.min.x - || tb.max.x + gap < x.min.x - || x.max.y + gap < tb.min.y - || tb.max.y + gap < x.min.y - || x.max.z + gap < tb.min.z - || tb.max.z + gap < x.min.z - }; - let mut voids = Vec::new(); - for (i, (sh, x)) in shells.iter().zip(&boxes).enumerate() { - if i == outer { - continue; - } - if !inside(x) || !clear(x) { - return Ok(None); - } - voids.push(sh.clone()); - } - let Some(outer_shell) = shells.get(outer) else { return Ok(None) }; - let alone = - guard("outer shell", || Body::new(Solid::try_new(vec![outer_shell.clone()]).map_err(|e| KernelError::Failed(format!("outer shell: {e}")))?))?; - let Some(cut) = boolean_via(&alone, b, BoolOp::Cut, whole)? else { return Ok(None) }; - let mut all = cut.solid.boundaries().clone(); - all.extend(voids); - Ok(Some(guard("voids back", || Body::new(Solid::try_new(all).map_err(|e| KernelError::Failed(format!("voids back: {e}")))?))?)) -} - -/// A cut or union with `b` when `b` is one outer shell with sealed voids, from booleans with the -/// outer shell and with the solids the voids are: `a` cut by `b` is `a` cut by the outer shell -/// beside `a` within each void, and `a` joined with `b` is `a` joined with the outer shell, with -/// what of each void `a` does not fill as a void. truck takes a tool's shells one at a time, each -/// as if it were a body of its own, which is neither: such cuts came out empty, or kept only what -/// lies in the void (a block crossing both spheres of a spherical shell, #451). Planar tools are -/// left to the exact paths. `None` for other operations and tools, a void not inside the outer -/// shell, and a result that fails the membership samples the general way's results are held to -/// (a piece that failed or came out empty): the bodies then go the general way. -fn with_hollow_tool(a: &Body, b: &Body, op: BoolOp) -> Option> { - let shells = b.solid.boundaries(); - if op == BoolOp::Intersect || b.is_mesh() || shells.len() < 2 || shells.len() > MAX_VOID_SHELLS || is_planar(b) { - return None; - } - let (mut outer, mut voids) = (None, Vec::new()); - for sh in shells { - if crate::body::faces_inward(sh).ok()? { - voids.push(sh.clone()); - } else if outer.replace(sh.clone()).is_some() { - return None; - } - } - // Each shell a body of its own, a void turned outwards: the solid it holds. - let parts: Vec = std::iter::once(outer?) - .chain(voids) - .map(|sh| guard("hollow tool", || Body::new(Solid::try_new(vec![sh]).map_err(|e| KernelError::Failed(format!("hollow tool: {e}")))?))) - .collect::>() - .ok()?; - let t = a.size().max(b.size()) * 5e-4; - let (shell, holes) = parts.split_first()?; - let mesh = shell.tessellate(t).ok()?; - let inside = mesh.inside_index(); - if !holes.iter().all(|h| h.solid.vertex_iter().all(|v| inside.contains(from_p3(v.point())))) { - return None; - } - let r = by_outer_and_voids(a, b, parts, op).ok()?; - let mr = match &r { - Some(r) => r.tessellate_with(t, true).ok()?, - None => solidcraft_geom::Mesh::default(), - }; - mismatch(&a.tessellate_with(t, true).ok()?, &b.tessellate_with(t, true).ok()?, &mr, op).is_some_and(|f| f < 0.004).then_some(r) -} - -/// [`with_hollow_tool`]'s booleans, with `b` as its outer shell's solid, then its voids'. -fn by_outer_and_voids(a: &Body, b: &Body, parts: Vec, op: BoolOp) -> Result> { - let counts = record::counts(&[a, b]); - let traced: Vec = recorded::parts_of(&parts, b).into_iter().zip(parts).map(|(h, p)| (p, recorded::placed(h, 1, 2))).collect(); - let pair = |(x, hx): &Traced, (y, hy): &Traced, op: BoolOp| -> Result> { - Ok(boolean(x, y, op)?.map(|r| { - let h = recorded::of_pair(&r, hx, hy); - (r, h) - })) - }; - let a = (a.clone(), recorded::kept(a, 0, 2)); - let Some((shell, voids)) = traced.split_first() else { return Ok(None) }; - if op == BoolOp::Cut { - let mut pieces: Vec = pair(&a, shell, BoolOp::Cut)?.into_iter().collect(); - for v in voids { - pieces.extend(pair(&a, v, BoolOp::Intersect)?); - } - return recorded::join(pieces, &counts); - } - let Some(mut joined) = pair(&a, shell, BoolOp::Union)? else { return Ok(None) }; - // What of a void `a` leaves empty lies inside the outer shell, clear of the outside: a void again. - for v in voids { - if let Some((left, hl)) = pair(v, &a, BoolOp::Cut)? - && let Some(r) = void(&joined.0, &left, &record::counts(&[&joined.0, &left]))? - { - let h = recorded::of_pair(&r, &joined.1, &hl); - joined = (r, h); - } - } - Ok(Some(joined.0.with_checked_history(joined.1, &counts))) -} - -/// Every face of an all-planar union must remain on an operand's original plane. -/// Curved operands keep their existing surface-specific boolean handling. -fn preserves_planar_surfaces(a: &Body, b: &Body, result: &Body) -> bool { - guard("validate planar union", || Ok(planar_surfaces_match(a, b, result))).unwrap_or(false) -} - -fn planar_surfaces_match(a: &Body, b: &Body, result: &Body) -> bool { - let planes: Option> = a - .solid - .face_iter() - .chain(b.solid.face_iter()) - .map(|f| { - let mt::Surface::Plane(p) = f.oriented_surface() else { return None }; - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - Some((n, n.dot(from_p3(p.origin())))) - }) - .collect(); - let Some(planes) = planes else { return true }; - let tol = (a.size().max(b.size()) * 1e-9).max(1e-9); - result.solid.face_iter().all(|f| { - matches!(f.oriented_surface(), mt::Surface::Plane(_)) - && planes.iter().any(|(n, d)| f.vertex_iter().all(|v| (n.dot(from_p3(v.point())) - d).abs() <= tol)) - }) -} - -/// Smallest side of the box where the bodies' vertex boxes overlap (infinite when they don't). -fn meeting_size(a: &Body, b: &Body) -> f64 { - let bbox = |x: &Body| { - let mut bb = solidcraft_geom::Aabb3::EMPTY; - for v in x.solid.vertex_iter() { - bb.add(from_p3(v.point())); - } - bb - }; - let (ba, bb) = (bbox(a), bbox(b)); - let s = ba.intersection(&bb).size(); - // A closed sweep's section seams need not span its geometry. Roundoff in a flat - // vertex box is not a thin meeting region: refining for it - // makes millions of triangles and skips the bounded containment shortcut (#2005). - let roundoff = a.size().max(b.size()) * 1e-12; - if s.x > roundoff && s.y > roundoff && s.z > roundoff { s.x.min(s.y).min(s.z) } else { f64::INFINITY } -} - -/// Smallest side of the box where the bounds of two meshes overlap (infinite when they don't). -/// Unlike [`meeting_size`], this follows curved faces: a cylinder's vertices are only the points -/// on its seam, so its vertex box says nothing about where its side reaches. -fn mesh_meeting_size(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh) -> f64 { - let (ba, bb) = (a.bounds(), b.bounds()); - let s = ba.intersection(&bb).size(); - if s.x > 0.0 && s.y > 0.0 && s.z > 0.0 { s.x.min(s.y).min(s.z) } else { f64::INFINITY } -} - -/// Whether a result volume is plausible for `op`: within the bounds the operands' volumes -/// leave, plus the slack the meshed volumes are measured to. -fn plausible(v: f64, op: BoolOp, va: f64, vb: f64, slack: f64) -> bool { - v > 0.0 - && match op { - BoolOp::Union => v >= va.max(vb) - slack && v <= va + vb + slack, - BoolOp::Cut => v >= va - vb - slack && v <= va + slack, - BoolOp::Intersect => v <= va.min(vb) + slack, - } -} - -/// A boolean in 2D of prisms along one direction (see [`prism_result`]). -type Route = fn(&Body, &Body, BoolOp) -> Option>>; - -/// A prism route's result (`route`: [`crate::prism::prism_boolean`] or -/// [`crate::prism::prism_union_between_caps`]): `Some` when both operands are prisms along one -/// direction, with a union's slab seams healed as the general B-rep boolean does. -fn prism_result(a: &Body, b: &Body, op: BoolOp, size: f64, counts: &[(usize, usize)], route: Route) -> Option>> { - // Slab-by-slab prism booleans sew a closed solid, but leave cap and wall pieces along slab - // boundaries: a cut along Z through a box whose side wall already has a port in it splits - // that wall into strips at the port's top and bottom, though the cut never touches it. Merge - // those coplanar faces for every operation, just as the general B-rep boolean does, retaining - // intentional Split Face lines. Authored boundaries (painted faces, regularization - // protection) keep their pieces. - let keep: Vec> = a.split_keep().iter().chain(b.split_keep()).cloned().collect(); - let authored = |x: &Body| x.regularization_protected || x.paint().is_some_and(|p| !p.faces.is_empty()); - route(a, b, op).map(|result| { - result.map(|body| { - body.map(|body| { - if op == BoolOp::Union { - guard("heal prism boolean", || recorded::heal_body(&body, (*body.solid).clone(), size, &keep, counts)).unwrap_or(body) - } else if authored(a) || authored(b) { - body - } else { - guard("heal prism boolean", || recorded::heal_prism_result(&body, size, &keep, counts)).unwrap_or(body) - } - }) - }) - }) -} -/// Walls swept along splines have flat B-spline tops and bottoms. With those made planes the -/// operands are prisms, and two of them (same height, one direction) are decided in 2D: fast, and -/// with no intersection of spline surfaces, which is what fails on them. The outlines are fitted -/// by arcs within a micron (`prism_boolean_free_form`). `None` when the operands have no such -/// face, are not such prisms, or the answer is implausible: the general boolean then takes over. -fn swept_prism(a: &Body, b: &Body, op: BoolOp) -> Option { - let (pa, pb) = (crate::planar_faces::planarized(a), crate::planar_faces::planarized(b)); - if pa.is_none() && pb.is_none() { - return None; - } - let (ra, rb) = (pa.as_ref().unwrap_or(a), pb.as_ref().unwrap_or(b)); - let Some(Ok(Some(body))) = crate::prism::prism_boolean_free_form(ra, rb, op) else { return None }; - let (va, vb) = (volume(a), volume(b)); - plausible(volume(&body), op, va, vb, 2e-3 * (va + vb) + 1e-9).then_some(body) -} - -fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { - boolean_whole_with_refinement(a, b, op, false) -} - -fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -> Result> { - boolean_whole_with(a, b, op, refine, &truck_boolean) -} - -/// The whole-body strategies with the numerical intersection supplied separately, so tests -/// can reproduce an empty numerical attempt without depending on a particular ray seed. -fn boolean_whole_with(a: &Body, b: &Body, op: BoolOp, refine: bool, intersect: &F) -> Result> -where - F: Fn(&Body, &Body, BoolOp, Option, f64) -> Result<(Solid, Option)>, -{ - if let Some(body) = swept_prism(a, b, op) { - return Ok(Some(body)); - } - a.require_brep("a boolean")?; - b.require_brep("a boolean")?; - let size = a.size().max(b.size()); - let counts = record::counts(&[a, b]); - // The checks mesh both bodies; where they meet in a region much thinner than they are (a - // thin part trimmed by a long one), a step from their size would facet the small faces - // there coarsely enough to fail the membership test on a correct result. The meshes are - // refined: a round side trimmed to a thin band (a short boss crossing a gently sloping - // floor) is otherwise spanned by triangles cutting through it, which reads as missing - // material. - let mut tol_m = (size * 5e-4).min(meeting_size(a, b) * 2e-3).max(size * 1e-5); - // A prism pair (a plate and the tool through it) is decided exactly in 2D, with no mesh of - // either operand. The sampled shortcuts below need a refined mesh of both, and that mesh is - // most of what a boolean costs: a pattern or a multi-profile sketch rebuilds the whole - // target's mesh once per tool. Only a cut or an intersection meets its tool often enough to - // be worth asking first - parts that stay apart are settled far more cheaply by the shell - // join the sampled shortcut does. A pair the route cannot answer still takes the path below, - // unchanged. - let early_prism = matches!(op, BoolOp::Cut | BoolOp::Intersect); - let prism = early_prism.then(|| prism_result(a, b, op, size, &counts, crate::prism::prism_boolean)).flatten(); - if let Some(Ok(Some(body))) = &prism { - let (va0, vb0) = (volume(a), volume(b)); - let (v0, slack0) = (volume(body), 2e-3 * (va0 + vb0) + 1e-9); - // A tool that misses its target, or covers it whole, leaves it as it is, and the - // sampled shortcut below answers that by reusing the operand itself: the very same body. - // The 2D route rebuilds it instead - the same shape on new faces - which would turn an - // untouched body in a timeline into a different solid. The route declines those pairs - // itself, from its exact sections (a volume measured off meshes could not tell an - // engraving of thin strokes from no change), and they take the path below, which - // decides them, and the identity they keep, exactly as it always has. - if plausible(v0, op, va0, vb0, slack0) { - return Ok(Some(body.clone())); - } - } - let mut meshes = (a.tessellate_with(tol_m, true).ok(), b.tessellate_with(tol_m, true).ok()); - // The vertex boxes above miss a curved operand's reach (a cylinder has only seam vertices), - // so a thin meeting region of curved bodies kept the coarse step: a sliver 0.5 mm thick was - // faceted at 0.017 mm and a correct result failed the membership test. The meshes just made - // do span the bodies, so the step is set again from where they meet and the meshes are - // remade once, when that is a much finer step. - let refined = match &meshes { - // A meeting box only a few steps thick is the tessellation error of bodies that merely - // touch or miss each other: a finer mesh there cannot help and only slows the operation. - (Some(ma), Some(mb)) => { - let meet = mesh_meeting_size(ma, mb); - (meet > tol_m * 8.0).then(|| (size * 5e-4).min(meet * 2e-3).max(size * 1e-5)) - } - _ => None, - }; - if let Some(refined) = refined - && refined < tol_m * 0.5 - { - let again = (a.tessellate_with(refined, true).ok(), b.tessellate_with(refined, true).ok()); - if again.0.is_some() && again.1.is_some() { - tol_m = refined; - meshes = again; - } - } - let (va, vb) = match &meshes { - (Some(ma), Some(mb)) => (ma.measure().volume, mb.measure().volume), - _ => (volume(a), volume(b)), - }; - let slack = 2e-3 * (va + vb) + 1e-9; - // Where a result's edges can run: a candidate with an edge far outside the operands is - // discarded before it is meshed (#3020), as meshing such a face may never finish. - let reach = crate::candidate_reach::Reach::new(a, b, (meshes.0.as_ref(), meshes.1.as_ref()), size); - // Volume bounds, then membership against the operands (catches misclassified pieces), on - // one mesh of the result. Returns (plausible, volume). - // Shells that touch were never fused: coincident back-to-back faces leave the intersection - // nothing to cut, so it returns both operands side by side (#396). Volume and point - // sampling cannot see that; the shell grouping can. Only contact over an area counts - // (bodies tangent along a line stay two lumps), and operands already like that, saved - // before this was caught, stay joinable. Nor can they see a skin of no thickness left over - // a hole by a tool ending in a face of the target ([`crate::coplanar::has_skin`]). - let unfused = |r: &Body| { - op == BoolOp::Union - && r.shell_count() > 1 - && r.union_lumps().is_err() - && a.union_lumps().is_ok() - && b.union_lumps().is_ok() - && crate::coplanar::faces_touch(a, b) - }; - let check = |r: &Body| -> (bool, f64) { - if let Some(reason) = reach.as_ref().and_then(|reach| reach.runaway(r)) { - reject(reason); - return (false, f64::NAN); - } - let Ok(mr) = r.tessellate_with(tol_m, true) else { return (false, f64::NAN) }; - let v = mr.measure().volume; - let bounds = plausible(v, op, va, vb, slack); - if !bounds { - return (false, v); - } - if unfused(r) || crate::coplanar::has_skin(r, &mr) { - return (false, v); - } - let consistent = match &meshes { - (Some(ma), Some(mb)) => mismatch(ma, mb, &mr, op).is_none_or(|f| f < 0.004), - _ => true, - }; - (consistent, v) - }; - if refine { - let keep: Vec> = a.split_keep().iter().chain(b.split_keep()).cloned().collect(); - // Bounded to two finer meshes; no tool displacement or relaxed acceptance tests. - for k in [1e-5, 1e-6] { - let tol = (size * k).max(1e-6); - if let Ok((solid, history)) = intersect(a, b, op, None, tol) - && !solid.boundaries().is_empty() - && let Ok(body) = guard("refined boolean result", || recorded::truck_result(solid, history, size, &keep, &counts)) - && check(&body).0 - && crate::boolean_guard::check_retry(a, b, op, Some(&body)).is_ok() - { - let mut event = BooleanFallback::new(BooleanStrategy::RefinedTolerance); - event.tolerance_mm = tol; - record(event); - return Ok(Some(body)); - } - } - return Err(KernelError::Failed("no reliable result at refined tolerances".into())); - } - // One body clear of or inside the other: no intersection needed. - // Kept for the end when the facetings disagree with it: bodies that touch along curved - // faces can pass through each other slightly, and often can't be intersected. - let mut doubted = None; - if let (Some(ma), Some(mb)) = &meshes - && let Some((r, sure)) = trivial(a, b, op, ma, mb, &counts, 3.0 * tol_m) - { - if sure { - return Ok(r); - } - doubted = Some(r); - } - let mut last = String::new(); - // Coincident faces make the intersection fail after many retries; push them apart first. - // Prisms along one direction (plates with holes): exact, in 2D (so only the volume bounds - // are checked). For a cut or an intersection this already ran above; the other operations - // ask here, after the sampled shortcut, which is where that shortcut is cheapest. - let prism = prism.or_else(|| (!early_prism).then(|| prism_result(a, b, op, size, &counts, crate::prism::prism_boolean)).flatten()); - if let Some(result) = prism { - match result { - Ok(Some(body)) => { - // Measured as the operands were: a coarser mesh of a plate with many holes - // overstates its volume by more than the slack. - let v = match &meshes { - (Some(_), Some(_)) => body.tessellate_with(tol_m, true).map(|m| m.measure().volume).unwrap_or(f64::NAN), - _ => volume(&body), - }; - if plausible(v, op, va, vb, slack) { - return Ok(Some(body)); - } - } - Ok(None) => return Ok(None), - // A failed prism attempt keeps trying the other strategies, as it did before. - Err(_) => {} - } - } - // Bodies touching along one whole face (a part joined with its mirror image). - if op == BoolOp::Union && a.solid.boundaries().len() == 1 { - let glued = if b.solid.boundaries().len() == 1 { crate::coplanar::glue(a, b) } else { crate::coplanar::glue_all_caps(a, b) }; - if let Some(Ok(body)) = glued { - let (ok, _) = check(&body); - if ok { - return Ok(Some(body)); - } - } - } - // Bores on a common cylinder (a pad's bore around the hole it is joined over, a disc filling - // a hole). Asked before faces are pushed apart: that doesn't part walls on one cylinder, and - // its tries at the general boolean, all failing on those walls, cost seconds. - if op == BoolOp::Union && !BORES.with(|c| c.get()) && crate::coplanar::has_coincident_cylinders(a, b) { - BORES.with(|c| c.set(true)); - let (r, diagnostics) = capture_boolean_diagnostics(|| crate::coplanar::bore_union(a, b, &|body| check(body).0)); - BORES.with(|c| c.set(false)); - if let Some(body) = r { - merge(diagnostics); - return Ok(Some(body)); - } - } - // Coincident planar faces: push them apart (exactly). Tried once, before the general - // boolean; why it failed is reported if everything else fails too. - let mut apart_failed = String::new(); - // The exact polygon boolean's answer, when it was asked for early. - let mut planar = None; - if !APART.with(|c| c.get()) { - APART.with(|c| c.set(true)); - let (r, diagnostics) = capture_boolean_diagnostics(|| crate::coplanar::boolean_apart(a, b, op)); - APART.with(|c| c.set(false)); - match r { - Some(Ok(Some(body))) => { - let (ok, v) = check(&body); - if ok { - merge(diagnostics); - let mut event = BooleanFallback::new(BooleanStrategy::CoplanarSeparation); - event.face_shift_mm = size * 0.0229; - record(event); - return Ok(Some(body)); - } - apart_failed = format!("; faces pushed apart gave an implausible volume {v:.4}"); - } - Some(Err(e)) => apart_failed = format!("; {e}"), - Some(Ok(None)) | None => {} - } - // A face with no room to move would take or add what it moves through. The exact - // polygon boolean takes the bodies as they lie (bodies with only planar faces, or a - // planar tool clear of the other body's curved faces): it is asked now, before the - // general boolean has its tries at faces lying in each other. - if apart_failed.contains(crate::coplanar::NO_ROOM) { - // What its own booleans report counts only when its result is taken. - let (exact, diagnostics) = capture_boolean_diagnostics(|| crate::polybool::planar_boolean(a, b, op)); - match exact { - Ok(Some(body)) if check(&body).0 => { - merge(diagnostics); - record(BooleanFallback::new(BooleanStrategy::PlanarFallback)); - return Ok(Some(body)); - } - other => planar = Some(other), - } - } - } - // A face standing wholly inside a coincident face of the other body, back to back, and no - // other contact (#396): exact, by topology alone. - if op == BoolOp::Union - && a.solid.boundaries().len() == 1 - && b.solid.boundaries().len() == 1 - && let Some(Ok(body)) = crate::coplanar::inset(a, b) - && let (Some(ma), Some(mb)) = &meshes - && overlap(ma, mb, &ma.inside_index(), &mb.inside_index()).is_some_and(|(b_in_a, a_in_b)| b_in_a < NONE && a_in_b < NONE) - && check(&body).0 - { - return Ok(Some(body)); - } - // Faces back to back over part of their area: imprinted on each other and glued (exact; held - // to the retry guard's checks all the same). - if op == BoolOp::Union && crate::coplanar::faces_touch(a, b) { - let accept = |body: &Body| check(body).0 && !unfused(body) && crate::boolean_guard::check_retry(a, b, op, Some(body)).is_ok(); - // Imprinted along the contact's own outline (faces there bounded by lines and arcs), then - // along the sides' surfaces. - if let Some(body) = crate::outline::outline_union(a, b, &accept) { - return Ok(Some(body)); - } - if let Some(body) = crate::coplanar::imprint_union(a, b, &accept) { - return Ok(Some(body)); - } - } - let mut empty_votes = 0; - let mut empty_diagnostics = crate::BooleanDiagnostics::default(); - let keep: Vec> = a.split_keep().iter().chain(b.split_keep()).cloned().collect(); - // The tolerances below follow the larger body. Where the bodies meet in a region much - // smaller than that (a hole a few millimetres across drilled through a long part, whose tool - // is longer still), they are as coarse as the tool itself: its intersection curves are - // traced at a step wider than the hole, and the cut comes out empty or fails. When those - // tries fail, the same boolean is asked again at tolerances (and shifts) scaled to where the - // bodies meet. Its result is checked as the others are, and held to the retry guard. - // Bodies in several shells are retried a piece at a time (see [`boolean`]), where each - // piece gets this pass of its own. - let fine_tols: Vec = match &meshes { - (Some(ma), Some(mb)) if a.solid.boundaries().len() == 1 && b.solid.boundaries().len() == 1 => { - let (ba, bb) = (ma.bounds(), mb.bounds()); - let s = ba.intersection(&bb).size(); - // The thinner operand's thickness (twice its volume over its area: a plate's - // thickness, a rod's radius) bounds what the tolerance must resolve as well. - let thickness = |m: &solidcraft_geom::Mesh| { - let x = m.measure(); - if x.area > 0.0 { 2.0 * x.volume.abs() / x.area } else { f64::INFINITY } - }; - let feature = s.x.min(s.y).min(s.z).min(thickness(ma)).min(thickness(mb)).max(size * 1e-4); - if feature > 0.0 && feature * 2e-3 < size * 2.5e-4 { vec![(feature * 2e-3).max(1e-6), (feature * 5e-4).max(1e-6)] } else { Vec::new() } - } - _ => Vec::new(), - }; - let fine = |last: &mut String| -> Option { - let feature = fine_tols.first().map(|t| t / 2e-3)?; - // Unshifted, then once shifted: each try at these tolerances costs many coarser ones. - for (attempt, j) in JITTER.iter().enumerate().take(2) { - let shift = mt::Vector3::new(j[0], j[1], j[2]) * (feature * 0.01); - for &tol in &fine_tols { - match intersect(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol) { - Ok((s, _)) if s.boundaries().is_empty() || s.face_iter().next().is_none() => *last = "empty result".into(), - Ok((s, h)) => match guard("boolean result", || recorded::truck_result(s, h, size, &keep, &counts)) { - Ok(body) => { - let (ok, v) = check(&body); - if ok { - let mut event = BooleanFallback::new(if attempt > 0 { - BooleanStrategy::ShiftedOperands - } else { - BooleanStrategy::RefinedTolerance - }); - event.translation_mm = Vec3::new(j[0], j[1], j[2]).len() * (feature * 0.01); - event.tolerance_mm = tol; - record(event); - return Some(body); - } - *last = format!("implausible result volume {v:.4}"); - } - Err(e) => *last = e.to_string(), - }, - Err(e) => *last = e.to_string(), - } - } - } - None - }; - for (attempt, j) in JITTER.iter().enumerate() { - // The operands as they lie failed. A planar tool beside the target's curved faces (a tooth - // or a pocket cut next to a round edge) is decided exactly in the slab it lies in, where - // the target is planar too, before the shifted tries: that is where they end anyway, as a - // retry, after costing several times as much (on every copy of a pattern, #1197). - if attempt == 1 && matches!(op, BoolOp::Cut | BoolOp::Intersect) { - let (sliced, diagnostics) = capture_boolean_diagnostics(|| crate::polybool::sliced_planar_boolean(a, b, op)); - if let Some(Ok(Some(body))) = sliced - && check(&body).0 - { - merge(diagnostics); - return Ok(Some(body)); - } - } - // A prism tool whose walls only touch the target (a corner of its outline on a ring's bore - // or in its end face, the wall beside it outside the ring): with those walls pushed - // outward, clear of the target, it takes the same cut exactly, without the contact the - // tries below fail on (and the nudge after them got through only seconds later, leaving a - // face of no width at the corner). - if attempt == 1 - && op == BoolOp::Cut - && let (Some(ma), Some(_)) = &meshes - && let Some(body) = pushed_walls_cut(a, b, ma, 2.0 * tol_m, size, &keep, &counts, &check) - { - return Ok(Some(body)); - } - // A prism tool whose target is a prism along its direction only round it (a pocket made - // deeper in a plate with a chamfered rim, a ring cut round a counterbored hole in a - // chamfered disc): the exact 2D route in a column cut round the tool. Its walls lying on - // the target's are what the tries below fail on. - if attempt == 1 && matches!(op, BoolOp::Cut | BoolOp::Intersect) { - let (local, diagnostics) = capture_boolean_diagnostics(|| crate::prism_local::local_prism_boolean(a, b, op)); - if let Some(Ok(Some(body))) = local - && check(&body).0 - { - merge(diagnostics); - return Ok(Some(body)); - } - } - // A lens cut from a sphere's projected outline carries a redundant cylinder - // tangent to the sphere (#2750). Remove it only after proving that it - // encloses the entire target, keeping the other wall and both caps exact. - if attempt == 1 && op == BoolOp::Cut { - let (lens, diagnostics) = capture_boolean_diagnostics(|| crate::sphere_lens::cut(a, b, &boolean_whole)); - if let Some(Ok(result)) = lens - && result.as_ref().is_none_or(|body| check(body).0) - { - merge(diagnostics); - return Ok(result); - } - } - // A whole turn of a cylinder or cone bounded by one wire along its seam (as STEP files - // write them) can't be divided by a loop lying inside it, and the tries below end in a - // nudged tool, or fail: the same boolean with such faces in two halves, which is exact. - if attempt == 1 && crate::seam_faces::needed(a, b) { - let (halves, diagnostics) = capture_boolean_diagnostics(|| crate::seam_faces::boolean(a, b, op, &boolean)); - if let Some(Ok(r)) = halves - && r.as_ref().is_none_or(|body| check(body).0) - { - merge(diagnostics); - return Ok(r); - } - } - // An implausible empty result from the unshifted numerical tries must still give - // the exact strategies above a chance (#1765), including seam-face recovery. If none - // recovers it, keep the original candidate for the outer guard, before displaced retries. - if empty_votes >= 2 && op != BoolOp::Union { - merge(empty_diagnostics); - return Ok(None); - } - let shift = mt::Vector3::new(j[0], j[1], j[2]) * (size * 0.01); - for k in [2e-3, 5e-4] { - let tol = (size * k).max(1e-5); - let r = intersect(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol); - match r { - Ok((s, _)) if s.boundaries().is_empty() || s.face_iter().next().is_none() => { - empty_votes += 1; - if attempt > 0 || k != 2e-3 { - let mut event = - BooleanFallback::new(if attempt > 0 { BooleanStrategy::ShiftedOperands } else { BooleanStrategy::RefinedTolerance }); - event.translation_mm = Vec3::new(j[0], j[1], j[2]).len() * (size * 0.01); - event.tolerance_mm = tol; - empty_diagnostics.push(event); - } - last = "empty result".into(); - } - Ok((s, h)) => match guard("boolean result", || recorded::truck_result(s, h, size, &keep, &counts)) { - Ok(body) => { - let (ok, v) = check(&body); - if ok { - if attempt > 0 || k != 2e-3 { - let mut event = BooleanFallback::new(if attempt > 0 { - BooleanStrategy::ShiftedOperands - } else { - BooleanStrategy::RefinedTolerance - }); - event.translation_mm = Vec3::new(j[0], j[1], j[2]).len() * (size * 0.01); - event.tolerance_mm = tol; - record(event); - } - return Ok(Some(body)); - } - last = if unfused(&body) { - "the bodies touch along faces that could not be fused".into() - } else { - format!("implausible result volume {v:.4}") - }; - } - Err(e) => last = e.to_string(), - }, - Err(e) => last = e.to_string(), - } - } - if empty_votes >= 2 && op != BoolOp::Union { - if let Some(body) = fine(&mut last) { - return Ok(Some(body)); - } - if attempt == 0 && crate::boolean_guard::check_retry(a, b, op, None).is_err() { - continue; - } - merge(empty_diagnostics); - return Ok(None); - } - } - last.push_str(&apart_failed); - // Coincident faces defeat the B-rep boolean; bodies with only planar faces have an exact - // polygon fallback. - match planar.unwrap_or_else(|| crate::polybool::planar_boolean(a, b, op)) { - Ok(Some(body)) => { - let (ok, v) = check(&body); - if ok { - record(BooleanFallback::new(BooleanStrategy::PlanarFallback)); - return Ok(Some(body)); - } - last = format!("planar fallback gave an implausible volume {v:.4}"); - } - Ok(None) => { - record(BooleanFallback::new(BooleanStrategy::PlanarFallback)); - return Ok(None); - } - Err(e) => last = format!("{last}; {e}"), - } - // Prisms along one direction that end at different levels (a barrel joined between two - // faces of a wider part, its ends flush with them) were left to the B-rep boolean, which - // the coincident ends defeat, with no room to push them apart (the part goes on past - // them). In 2D they join exactly: asked before the tool is moved. - if let Some(Ok(Some(body))) = prism_result(a, b, op, size, &counts, crate::prism::prism_union_between_caps) { - let (ok, v) = check(&body); - if ok { - return Ok(Some(body)); - } - last = format!("{last}; the prisms joined in 2D gave an implausible volume {v:.4}"); - } - // Last resort: nudge the tool by a micron-scale screw motion (turned 2e-6 rad about a - // skew axis and moved 2e-6 of the size), which breaks tangencies and seams lying exactly on - // the other body. The result moves by no more than that. - if !APART.with(|c| c.get()) { - APART.with(|c| c.set(true)); - let c = b.solid.vertex_iter().fold(Vec3::ZERO, |acc, v| acc + from_p3(v.point())) * (1.0 / b.solid.vertex_iter().count().max(1) as f64); - let translation = |screw: usize| SCREWS.get(screw).map_or(Vec3::ZERO, |s| Vec3::new(s.0[0], s.0[1], s.0[2]) * (size * 2e-6)); - let nudge = |screw: usize, sign: f64| { - let axis = SCREWS.get(screw).map_or(Vec3::Z, |s| Vec3::new(s.1[0], s.1[1], s.1[2])); - capture_boolean_diagnostics(|| { - transform(b, translation(screw) * sign, c, axis, 2e-6 * sign).and_then(|nb| Ok(boolean(a, &nb, op)?.map(|r| nudged(r, &nb, &counts)))) - }) - }; - let mut used = 0; - let (mut r, mut diagnostics) = nudge(used, 1.0); - // A nudge that pushes a face into a curved face it only touched (a cut whose end lies - // tangent to a round side) leaves a sliver of that face behind, a fraction of a - // millimetre wide, which later features (a shell, a fillet) can't work with. The - // opposite nudge parts them instead. It is tried when this one failed or left more - // slivers than the operands brought (a thin wall or a small round is no reason to run - // another boolean), and taken when it works with fewer; an empty result stays as it is. - let slivers = match &r { - Ok(Some(body)) if check(body).0 => Some(sliver_faces(body, size)), - _ => None, - }; - let made = slivers.is_none_or(|n| n > 0 && n > sliver_faces(a, size).saturating_add(sliver_faces(b, size))); - if !matches!(r, Ok(None)) && made { - let (r2, diagnostics2) = nudge(used, -1.0); - if let Ok(Some(body)) = &r2 - && slivers.is_none_or(|n| sliver_faces(body, size) < n) - && check(body).0 - { - (r, diagnostics) = (r2, diagnostics2); - } - } - // Neither way worked: the screw can turn the tool along a seam it lies in (a loft - // standing in the rim of a shelled case with its ends in the wall's inner face, #1490). - // The other screws are tried in turn, and the first result that checks is taken. - let works = |r: &Result>| match r { - Ok(None) => true, - Ok(Some(body)) => check(body).0, - Err(_) => false, - }; - if !works(&r) { - 'screws: for screw in 1..SCREWS.len() { - for sign in [1.0, -1.0] { - let (r2, diagnostics2) = nudge(screw, sign); - if matches!(&r2, Ok(Some(body)) if check(body).0) { - (r, diagnostics, used) = (r2, diagnostics2, screw); - break 'screws; - } - } - } - } - let translation = translation(used); - APART.with(|c| c.set(false)); - match r { - Ok(Some(body)) => { - let (ok, v) = check(&body); - // Measured finely too: a face the boolean left a hair wide, its loops a hair - // apart, can mesh as its whole plane at a fine step though it meshed as a sliver - // at the check's (#1360: an annulus cut flush with a hole's wall came out 21000 - // mm³ larger than the part it was cut from, a square plane across it). - let fine_ok = ok && crate::measure(&body).is_ok_and(|m| plausible(m.volume, op, va, vb, slack)); - if ok && !fine_ok { - last = format!("{last}; the nudged tool gave a solid whose faces mesh inconsistently"); - } else if ok { - merge(diagnostics); - let mut event = BooleanFallback::new(BooleanStrategy::ToolNudge); - event.translation_mm = translation.len(); - event.rotation_rad = 2e-6; - record(event); - return Ok(Some(body)); - } else { - last = format!("{last}; the nudged tool gave an implausible volume {v:.4}"); - } - } - Ok(None) => { - merge(diagnostics); - let mut event = BooleanFallback::new(BooleanStrategy::ToolNudge); - event.translation_mm = translation.len(); - event.rotation_rad = 2e-6; - record(event); - return Ok(None); - } - Err(e) => last = format!("{last}; nudged: {e}"), - } - } - // A join whose coincident planar faces cannot be pushed apart because the neighbours of one of them curve (a flange - // flush with the end of a lofted tube): the faces are grown instead, and what the growth leaves beyond the plane is cut - // off by editing the faces. After every route above, the nudge included, has failed, so that a join any of them takes - // stays as it was. - if op == BoolOp::Union && !APART.with(|c| c.get()) { - APART.with(|c| c.set(true)); - let (r, diagnostics) = capture_boolean_diagnostics(|| crate::coplanar::boolean_grown(a, b, op)); - APART.with(|c| c.set(false)); - match r { - Some(Ok(Some(body))) => { - let (ok, v) = check(&body); - if ok { - merge(diagnostics); - let mut event = BooleanFallback::new(BooleanStrategy::CoplanarSeparation); - event.face_shift_mm = size * 0.0137; - record(event); - return Ok(Some(body)); - } - last = format!("{last}; faces grown apart gave an implausible volume {v:.4}"); - } - Some(Err(e)) => last = format!("{last}; {e}"), - Some(Ok(None)) | None => {} - } - } - // The tries at the meeting region's scale come last, after every strategy that answered - // before them, so a result any of those gave is kept as it was. - if let Some(body) = fine(&mut last) { - return Ok(Some(body)); - } - // An intersection keeps what lies in both bodies: when the sampled answer keeps one of them - // whole and is contradicted by facets that cross well past their faceting error, keeping it - // would keep exactly what the intersection was asked to trim (#3244: teeth standing 0.27 mm - // out of a trimming cylinder came back untrimmed). It fails instead, and the model is kept. - // An empty answer stays reported as unverified: the clearance checks measure it another way. - let deep = 2.0 * 3.0 * tol_m; - if op == BoolOp::Intersect - && matches!(doubted, Some(Some(_))) - && let (Some(ma), Some(mb)) = &meshes - && ma.crosses(mb, deep) - { - return Err(KernelError::Failed(format!( - "boolean {op:?}: the bodies pass through each other by more than {deep:.3e} mm where they could not be intersected; {last}" - ))); - } - match doubted { - Some(r) => { - let mut event = BooleanFallback::new(BooleanStrategy::UnverifiedShortcut); - event.tolerance_mm = 3.0 * tol_m; - record(event); - Ok(r) - } - None => Err(KernelError::Failed(format!("boolean {op:?}: {last}"))), - } -} - -/// `a` cut by `b` with the walls of `b` that only touch `a` pushed outward (see -/// [`crate::touching_walls`]), at each of the general boolean's tolerances by a little more than -/// it (at least `by`, past the sag of `target`, the mesh of `a`): the first result that checks -/// and whose faces lie on none of the pushed walls. The pushed tool keeps `b`'s order, so the -/// history holds for `b`. -#[allow(clippy::too_many_arguments)] -fn pushed_walls_cut( - a: &Body, - b: &Body, - target: &solidcraft_geom::Mesh, - by: f64, - size: f64, - keep: &[Vec], - counts: &[(usize, usize)], - check: &dyn Fn(&Body) -> (bool, f64), -) -> Option { - let inside = target.inside_index(); - for k in [2e-3, 5e-4] { - // Pushed past what the boolean takes for touching, and past the mesh's sag. - let tol = (size * k).max(1e-5); - let Some(pushed) = crate::touching_walls::pushed_tool(b, &inside, (2.5 * tol).max(by)) else { continue }; - let Ok((s, h)) = truck_boolean(a, &pushed.tool, BoolOp::Cut, None, tol) else { continue }; - if s.boundaries().is_empty() || s.face_iter().next().is_none() { - continue; - } - let Ok(body) = guard("boolean result", || recorded::truck_result(s, h, size, keep, counts)) else { continue }; - if pushed.untouched(&body) && check(&body).0 { - return Some(body); - } - } - None -} - -/// The screw motions a tool is nudged by as a last resort: (direction of the move, axis of the -/// turn), each tried both ways. The first is the one every nudge used before #1490; the others -/// are asked only when it fails both ways. -const SCREWS: [([f64; 3], [f64; 3]); 3] = - [([0.61, -0.37, 0.71], [0.27, 0.83, -0.49]), ([-0.42, 0.68, 0.6], [0.77, -0.18, 0.61]), ([0.31, 0.52, -0.79], [-0.58, 0.41, 0.70])]; - -/// Faces of `b` narrower than 1/200 of `size` (twice their area over their boundary's -/// length): the slivers a nudged tool leaves where it was pushed into a face it touched. -fn sliver_faces(b: &Body, size: f64) -> usize { - use std::collections::HashMap; - let Ok(m) = b.tessellate((size * 1e-3).max(1e-4)) else { return usize::MAX }; - let q = (size * 1e-7).max(1e-12); - let key = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64); - // Per face: its area, and how many of its triangles use each mesh edge (its boundary once). - let mut area: HashMap = HashMap::new(); - let mut sides: HashMap<(u32, (i64, i64, i64), (i64, i64, i64)), (u32, f64)> = HashMap::new(); - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - let Some([a, b, c]) = m.tri(t) else { continue }; - *area.entry(*f).or_default() += (b - a).cross(c - a).len() * 0.5; - for (p, r) in [(a, b), (b, c), (c, a)] { - let (kp, kr) = (key(p), key(r)); - let k = if kp <= kr { (*f, kp, kr) } else { (*f, kr, kp) }; - sides.entry(k).or_insert((0, p.dist(r))).0 += 1; - } - } - let mut boundary: HashMap = HashMap::new(); - for ((f, _, _), (n, len)) in &sides { - if *n == 1 { - *boundary.entry(*f).or_default() += len; - } - } - area.iter().filter(|(f, a)| boundary.get(f).is_some_and(|l| *l > 0.0 && 2.0 * **a / l < size * 5e-3)).count() -} - -/// `r`, a boolean of the target and `nb` (the tool nudged), with its history over the target and -/// the tool itself (the nudge keeps every face and edge). -pub(crate) fn nudged(r: Body, nb: &Body, counts: &[(usize, usize)]) -> Body { - let h = recorded::through(&r, 1, nb.history()); - r.with_checked_history(h, counts) -} - -/// What truck's boolean makes of `a` and `b`: the solid, and its history in our terms (see -/// [`recorded::shapeops`]). On copies of the operands moved by `shift` (when given; the result -/// is moved back), which changes the rays the boolean classifies faces by. Copies (and moved -/// copies) keep the operands' face and edge order, and so does moving the result back, so the -/// history truck records holds for the operands themselves. -pub(crate) fn truck_boolean(a: &Body, b: &Body, op: BoolOp, shift: Option, tol: f64) -> Result<(Solid, Option)> { - if !take_attempt() { - return Err(KernelError::Failed("no result in the tries it was given".into())); - } - guard("boolean", || { - let (mut sa, mut sb) = (a.deep_copy(), b.deep_copy()); - if let Some(shift) = shift { - sa = mt::builder::translated(&sa, shift); - sb = mt::builder::translated(&sb, shift); - } - let tool_edges = (op == BoolOp::Cut).then(|| record::edge_origins(&sb, 1)); - // A body that keeps its meshes is meshed once for all its booleans at this tolerance. - let meshed = shift.is_none().then(|| a.boolean_meshes(tol)).flatten(); - let and = |sa: &Solid, sb: &Solid| match &meshed { - Some(m) => truck_shapeops::and_with_history_meshed(sa, m, sb, tol), - None => truck_shapeops::and_with_history(sa, sb, tol), - }; - let res = match op { - BoolOp::Union => truck_shapeops::or_with_history(&sa, &sb, tol), - BoolOp::Cut => { - sb.not(); - and(&sa, &sb) - } - BoolOp::Intersect => and(&sa, &sb), - }; - let (s, h) = res.ok_or_else(|| KernelError::Failed("no result".into()))?; - let h = h.and_then(|h| recorded::shapeops(&h, &sb, tool_edges.as_ref())); - Ok((if let Some(shift) = shift { mt::builder::translated(&s, -shift) } else { s }, h)) - }) -} - -/// A boolean of `a` and `b` given as their pieces (`la`, `lb`); the result's pieces in one body. -pub(crate) fn by_lumps(a: &Body, b: &Body, la: Vec, lb: Vec, op: BoolOp) -> Result> { - let boxes_meet = |x: &Body, y: &Body| -> bool { - let (Ok(mx), Ok(my)) = (x.tessellate(x.size() * 0.05 + 1e-3), y.tessellate(y.size() * 0.05 + 1e-3)) else { return true }; - let (bx, by) = (mx.bounds(), my.bounds()); - let g = (x.size() + y.size()) * 0.01; - bx.min.x <= by.max.x + g - && by.min.x <= bx.max.x + g - && bx.min.y <= by.max.y + g - && by.min.y <= bx.max.y + g - && bx.min.z <= by.max.z + g - && by.min.z <= bx.max.z + g - }; - // Each piece with its history over [a, b] (a piece's faces and edges are its body's own). - let traced = |pieces: Vec, whole: &Body, operand: usize| -> Vec { - let histories = recorded::parts_of(&pieces, whole); - pieces.into_iter().zip(histories).map(|(p, h)| (p, recorded::placed(h, operand, 2))).collect() - }; - let (la, lb) = (traced(la, a, 0), traced(lb, b, 1)); - let pair = |(x, hx): &Traced, (y, hy): &Traced, op: BoolOp| -> Result> { - Ok(boolean(x, y, op)?.map(|r| { - let h = recorded::of_pair(&r, hx, hy); - (r, h) - })) - }; - let mut out: Vec = Vec::new(); - match op { - BoolOp::Cut => { - for x in la { - let mut cur = Some(x); - for y in &lb { - cur = match cur { - Some(c) if boxes_meet(&c.0, &y.0) => pair(&c, y, BoolOp::Cut)?, - other => other, - }; - } - out.extend(cur); - } - } - BoolOp::Intersect => { - for x in &la { - for y in &lb { - if boxes_meet(&x.0, &y.0) - && let Some(r) = pair(x, y, BoolOp::Intersect)? - { - out.push(r); - } - } - } - } - BoolOp::Union => { - out = la; - for y in lb { - let mut cur = y; - let mut rest = Vec::new(); - for x in out { - if boxes_meet(&x.0, &cur.0) { - match pair(&x, &cur, BoolOp::Union)? { - Some(u) if u.0.solid.boundaries().len() == 1 => cur = u, - _ => rest.push(x), - } - } else { - rest.push(x); - } - } - rest.push(cur); - out = rest; - } - } - } - recorded::join(out, &record::counts(&[a, b])) -} - -/// Bodies whose bounding boxes are clearly apart, as one body of several pieces, without any -/// intersection work (many identical pattern tools, #261). `None` when any two may meet, or a -/// body is a mesh: the caller unions those the usual way. -pub fn union_apart(bodies: &[Body]) -> Result> { - crate::profile::timed(crate::profile::Kind::Boolean, || union_apart_untimed(bodies)) -} - -fn union_apart_untimed(bodies: &[Body]) -> Result> { - if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) { - return Ok(None); - } - let mut boxes = Vec::with_capacity(bodies.len()); - for b in bodies { - // A coarse mesh is enough: the chord tolerance bounds how far the true surface lies - // outside it, and the box grows by twice that. - let tol = (b.size() * 0.02).max(1e-3); - let bb = b.tessellate(tol)?.bounds(); - if bb.is_empty() { - return Ok(None); - } - boxes.push(bb.inflated(2.0 * tol)); - } - // Sweep along x: only boxes whose x ranges overlap are compared. - let mut order: Vec = (0..boxes.len()).collect(); - order.sort_by(|&i, &j| boxes.get(i).map(|b| b.min.x).unwrap_or(0.0).total_cmp(&boxes.get(j).map(|b| b.min.x).unwrap_or(0.0))); - for (k, &i) in order.iter().enumerate() { - let Some(a) = boxes.get(i) else { continue }; - for &j in order.iter().skip(k + 1) { - let Some(b) = boxes.get(j) else { continue }; - if b.min.x > a.max.x { - break; - } - if a.min.y <= b.max.y && b.min.y <= a.max.y && a.min.z <= b.max.z && b.min.z <= a.max.z { - return Ok(None); - } - } - } - join_apart(bodies) -} - /// Bodies the caller knows are apart (no two meet or touch), as one body of several pieces, /// without any intersection work: [`union_apart`] without its check, for tools whose making -/// shows they are apart (profiles apart in their sketch, extruded alike). `None` for fewer than -/// two bodies or a mesh. +/// shows they are apart. Each face and edge of the result is its piece's own (its history over +/// `bodies`). `None` for fewer than two bodies or a mesh. pub fn join_apart(bodies: &[Body]) -> Result> { - crate::profile::timed(crate::profile::Kind::Boolean, || join_apart_untimed(bodies)) -} - -fn join_apart_untimed(bodies: &[Body]) -> Result> { if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) { return Ok(None); } - // The pieces stay as they are, side by side: each face and edge of the result is its piece's - // own (the history over `bodies`). - let Some(joined) = join_pieces(bodies.to_vec())? else { return Ok(None) }; - let operands: Vec<&Body> = bodies.iter().collect(); - let faces = bodies - .iter() - .enumerate() - .flat_map(|(operand, b)| { - (0..b.face_count()).map(move |face| (std::collections::BTreeSet::from([crate::history::FaceOrigin::Face { operand, face }]), true)) - }) - .collect(); - let mut edges = HashMap::new(); - for (operand, b) in bodies.iter().enumerate() { - edges.extend(record::edge_origins(&b.solid, operand)); - } - Ok(Some(record::traced(joined, &record::counts(&operands), Some(record::regions(faces)), Some(&edges)))) + let (joined, part) = joined(bodies)?; + let counts: Vec<(usize, usize)> = bodies.iter().map(|b| (b.face_count(), b.edge_count())).collect(); + let history = crate::history::of_part(&part, &counts); + Ok(Some(joined.with_checked_history(Some(history), &counts))) } -/// Bodies (apart from each other) as one body of several pieces. +/// Bodies (apart from each other) as one body of several pieces, their face sources carried. pub(crate) fn join_pieces(pieces: Vec) -> Result> { match pieces.len() { 0 => Ok(None), 1 => Ok(pieces.into_iter().next()), - _ => { - let shells: Vec = pieces.iter().flat_map(|p| p.solid.boundaries().clone()).collect(); - let solid = guard("pieces", || Solid::try_new(shells).map_err(|e| KernelError::Failed(e.to_string())))?; - let protected = pieces.iter().any(|piece| piece.regularization_protected); - Body::new(solid).map(|mut body| { - body.regularization_protected = protected; - Some(body) - }) - } + _ => joined(&pieces).map(|(body, _)| Some(body)), } } -/// Determinant of the linear part of a column-major 4x4 matrix: negative means the placement -/// mirrors, which turns a solid inside out. -fn det3(m: &[[f64; 4]; 4]) -> f64 { - m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) - + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) +/// The records of `bodies` side by side, as one body, and where its items come from. +fn joined(bodies: &[Body]) -> Result<(Body, part::Part)> { + let records: Vec<&solidcore_record::brep::Brep> = bodies.iter().map(Body::record).collect(); + let part = part::compound(&records).map_err(|e| KernelError::Failed(format!("pieces: {e}")))?; + // Each face's source, numbered as `compound` numbers the inputs: one after another. + let sources: Vec> = + bodies.iter().flat_map(|b| (0..b.face_count()).map(move |f| b.face_sources().and_then(|s| s.get(f)).cloned().flatten())).collect(); + let mapped = bodies + .iter() + .any(|b| b.face_sources().is_some()) + .then(|| std::sync::Arc::new(part.faces.iter().map(|&f| sources.get(f as usize).cloned().flatten()).collect::>())); + let mut body = Body::from_record(part.brep.clone())?.with_face_sources(mapped); + body.regularization_protected = bodies.iter().any(|b| b.regularization_protected); + Ok((body, part)) } -/// Whether the linear part is a rigid motion (rotation or reflection: no scale or shear). -pub(crate) fn rigid_placement(m: &[[f64; 4]; 4]) -> bool { - let r = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])]; - (0..3).all(|i| (r[i].dot(r[i]) - 1.0).abs() < 1e-9) && r[0].dot(r[1]).abs() < 1e-9 && r[0].dot(r[2]).abs() < 1e-9 && r[1].dot(r[2]).abs() < 1e-9 -} - -/// Affine transform by a column-major 4x4 matrix (rotations, translations, reflections). +/// Affine transform by a column-major 4x4 matrix (rotations, translations, reflections, +/// scalings). A rigid motion moves the record itself, every parameter and index as it was; any +/// other matrix goes through SMLib's transform. Either way the result's faces and edges are +/// the body's, in its history. pub fn transform_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result { - transform_matrix_keeping(body, m, false) -} - -/// [`transform_matrix`] for showing a body where an assembly places it (world placement): the -/// revolved faces stay turned the way the body has them instead of being searched again for -/// every placed copy (#3044). A modelling operation keeps using [`transform_matrix`]: where a -/// face wraps all the way round, the turn it finds depends on the copy's own coordinates, and -/// booleans on the copy depend on that. -pub fn place_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result { - transform_matrix_keeping(body, m, body.phased) -} - -fn transform_matrix_keeping(body: &Body, m: [[f64; 4]; 4], phased: bool) -> Result { + let _span = solidcraft_profile::span("kernel", "transform_matrix"); if m.iter().flatten().any(|x| !x.is_finite()) { return Err(KernelError::Invalid("non-finite transform".into())); } - // A perspective row or a flattening (from a design file or a command's parameters) leaves - // no solid: refused rather than built into faces that mesh to nonsense. - let scale = (0..3).map(|c| Vec3::new(m[c][0], m[c][1], m[c][2]).len()).fold(0.0, f64::max); - if m[0][3].abs() > 1e-12 || m[1][3].abs() > 1e-12 || m[2][3].abs() > 1e-12 || (m[3][3] - 1.0).abs() > 1e-12 { - return Err(KernelError::Invalid("the transform is not affine: its last row must be 0, 0, 0, 1".into())); - } - if det3(&m).abs() <= 1e-12 * scale.powi(3) { - return Err(KernelError::Invalid("the transform flattens the body: its linear part is singular".into())); - } if let Some(placed) = body.mesh_transformed(&m) { - let history = crate::history::History::identity(&placed); + let history = History::identity(&placed); return placed.with_history(history, &[body]); } - guard("transform", || { - let mat = mt::Matrix4::new( - m[0][0], m[0][1], m[0][2], m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3], m[3][0], m[3][1], m[3][2], - m[3][3], - ); - // An affine placement retains face order and appearance metadata. Its edges are the - // body's by identity: a reflection turns the solid inside out, which walks each face's - // edges the other way and so changes the edge order. - let sources = body.transformed_sources(m)?; - let (solid, copies) = placed_topology_mapped(&body.solid, mat)?; - let mut rec = record::Rebuild::default(); - rec.pieces(&copies); - for (copy, face) in solid.face_iter().zip(body.solid.face_iter()) { - rec.whole(copy, face); + let sources = body.transformed_sources(m)?; + let (placed, sources, paint) = match Rigid::of_matrix(&m) { + Some(motion) => { + let moved = Body::from_record(solidcraft_geom::brep::placement::moved(body.record(), &motion))?; + let history = History::identity(&moved); + (moved.with_history(history, &[body])?, sources, body.paint().cloned()) } - let (faces, edges) = rec.history(&solid, &[&body.solid]).unzip(); - let counts = record::solid_counts(&[&body.solid]); - // A rigid placement leaves every face's mesh, and so the missing-face count, as it was; - // a mirrored one turns the solid inside out. Either way the orientation is read from the - // matrix instead of meshing the whole copy again. - let placed = record::build_placed( - solid, - &counts, - faces, - edges.as_ref(), - det3(&m) < 0.0, - rigid_placement(&m).then_some(body.coarse_missing).flatten(), - phased, - )?; - Ok(placed.with_color(body.color()).with_paint(body.paint().cloned()).with_face_sources(sources).inherit_regularization_protection(body)) - }) -} - -/// `source` moved by `matrix`, keeping its face and edge order (transforms report an identity -/// [`crate::history::History`] on that basis). Built here rather than by generic topology -/// builders: a STEP periodic face may traverse a seam edge twice, and those reject that wire -/// while cloning even though placement preserves its topology. -pub(crate) fn placed_topology(source: &Solid, matrix: mt::Matrix4) -> Result { - placed_topology_mapped(source, matrix).map(|(solid, _)| solid) -} - -/// [`placed_topology`], with each edge of `source` (by identity) and its copy. -fn placed_topology_mapped(source: &Solid, matrix: mt::Matrix4) -> Result<(Solid, HashMap)> { - use mt::{Transform, Transformed}; - let mut vertices = HashMap::new(); - let mut edges = HashMap::new(); - let mut shells = Vec::new(); - let mut face_count = 0usize; - let mut edge_visits = 0usize; - for shell in source.boundaries() { - let mut faces = Vec::new(); - for face in shell { - face_count = face_count.saturating_add(1); - if face_count > 500_000 { - return Err(KernelError::Invalid("placement exceeds face work limit".into())); - } - let mut wires = Vec::new(); - for wire in face.absolute_boundaries() { - let mut mapped = Vec::new(); - for edge in wire { - edge_visits = edge_visits.saturating_add(1); - if edge_visits > 4_000_000 { - return Err(KernelError::Invalid("placement exceeds edge work limit".into())); - } - if let std::collections::hash_map::Entry::Vacant(entry) = edges.entry(edge.id()) { - for vertex in [edge.absolute_front(), edge.absolute_back()] { - if let std::collections::hash_map::Entry::Vacant(entry) = vertices.entry(vertex.id()) { - let point = matrix.transform_point(vertex.point()); - if !from_p3(point).is_finite() { - return Err(KernelError::Invalid("placement produced nonfinite geometry".into())); - } - entry.insert(mt::Vertex::new(point)); - } - } - let front = - vertices.get(&edge.absolute_front().id()).ok_or_else(|| KernelError::Failed("placement vertex missing".into()))?; - let back = vertices.get(&edge.absolute_back().id()).ok_or_else(|| KernelError::Failed("placement vertex missing".into()))?; - entry.insert(mt::Edge::new_unchecked(front, back, edge.curve().transformed(matrix))); - } - let copied = edges.get(&edge.id()).ok_or_else(|| KernelError::Failed("placement edge missing".into()))?; - mapped.push(if edge.orientation() { copied.clone() } else { copied.inverse() }); + None => { + // SMLib numbers the moved body's faces afresh: each face's source and paint follow it + // by the history (a face whose origin is not known keeps no source; with no history + // the paint stays as it was). + let placed = transformed(body, &m)?; + let origin: Vec> = (0..placed.face_count()).map(|f| moved_from(placed.history(), f)).collect(); + let sources = sources.map(|s| std::sync::Arc::new(origin.iter().map(|o| o.and_then(|j| s.get(j).cloned().flatten())).collect())); + let paint = body.paint().cloned().map(|mut p| { + if placed.history().is_none() { + return p; } - wires.push(mt::Wire::from(mapped)); - } - // Wire connectivity, seam sharing and orientation are copied exactly; - // no new topology is introduced by this geometry-only operation. - let mut copied = mt::Face::new_unchecked(wires, face.surface().transformed(matrix)); - if !face.orientation() { - copied.invert(); - } - faces.push(copied); + p.faces = p + .faces + .iter() + .flat_map(|fp| { + origin.iter().enumerate().filter(|(_, o)| **o == Some(fp.face)).map(|(face, _)| crate::FacePaint { face, ..fp.clone() }) + }) + .collect(); + p + }); + (placed, sources, paint) } - shells.push(mt::Shell::from(faces)); - } - Ok((Solid::new_unchecked(shells), edges)) + }; + Ok(placed.with_color(body.color()).with_paint(paint).with_face_sources(sources).inherit_regularization_protection(body)) } -#[cfg(test)] -#[test] -fn affine_placement_keeps_body_and_face_paint_attached() { - let paint = crate::Paint { opacity: 0.4, faces: vec![crate::FacePaint { face: 0, color: [0.8, 0.2, 0.1], opacity: 0.3 }] }; - let body = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap().with_color(Some([0.2, 0.6, 0.8])).with_paint(Some(paint.clone())); - let source_faces = body.faces(0.01).unwrap(); - let transform = [[0.0, 2.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0], [30.0, 40.0, 50.0, 1.0]]; - let placed = transform_matrix(&body, transform).unwrap(); - assert_eq!(placed.color(), body.color()); - assert_eq!(placed.paint(), Some(&paint)); - let faces = placed.faces(0.01).unwrap(); - for source in source_faces { - let target = faces.iter().find(|f| f.index == source.index).unwrap(); - let p = source.centroid; - assert!(target.centroid.dist(Vec3::new(30.0 - p.y, 40.0 + 2.0 * p.x, 50.0 + 0.5 * p.z)) < 1e-6); +/// The face of the operand that face `f` of a moved body is, by the move's history. +fn moved_from(history: Option<&History>, f: usize) -> Option { + match history?.faces.get(f)?.origins.as_slice() { + [crate::history::FaceOrigin::Face { operand: 0, face }] => Some(*face), + _ => None, } } +/// `body` moved by a matrix that is not a rigid motion, in SMLib, its history from SMLib's tags. +fn transformed(body: &Body, m: &[[f64; 4]; 4]) -> Result { + let failed = |what: &str, e: solidcraft_smlib::Error| KernelError::smlib(format!("SMLib transform: {what}"), e); + let (handle, order) = crate::native::smlib_body_ordered(body)?; + let moved = handle.tagged(0).map_err(|e| failed("tag", e))?.transformed(m).map_err(|e| failed("operation", e))?; + let (result, result_order) = crate::native::body_from_smlib_ordered(&moved)?; + let history = match (order, result_order) { + (Some(o), Some(r)) => moved.history().ok().and_then(|h| h.history(&[o], &r).ok()), + _ => None, + }; + Ok(result.with_checked_history(history, &[(body.face_count(), body.edge_count())])) +} + +/// [`transform_matrix`] for showing a body where an assembly places it (world placement). +pub fn place_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result { + transform_matrix(body, m) +} + /// Rigid transform: rotate about `axis` through `origin` by `angle` radians, then translate. pub fn transform(body: &Body, translate: Vec3, origin: Vec3, axis: Vec3, angle: f64) -> Result { if !(translate.is_finite() && origin.is_finite() && angle.is_finite()) { return Err(KernelError::Invalid("non-finite transform".into())); } - { - // Same motion as a matrix: rotate about the line through `origin`, then translate. - let ax = if angle.abs() > 1e-12 { axis.normalized().ok_or_else(|| KernelError::Invalid("rotation axis".into()))? } else { Vec3::Z }; - let (c, s) = (angle.cos(), angle.sin()); - let t = 1.0 - c; - let r = [ - [t * ax.x * ax.x + c, t * ax.x * ax.y + s * ax.z, t * ax.x * ax.z - s * ax.y], - [t * ax.x * ax.y - s * ax.z, t * ax.y * ax.y + c, t * ax.y * ax.z + s * ax.x], - [t * ax.x * ax.z + s * ax.y, t * ax.y * ax.z - s * ax.x, t * ax.z * ax.z + c], - ]; - let ro = Vec3::new( - r[0][0] * origin.x + r[1][0] * origin.y + r[2][0] * origin.z, - r[0][1] * origin.x + r[1][1] * origin.y + r[2][1] * origin.z, - r[0][2] * origin.x + r[1][2] * origin.y + r[2][2] * origin.z, - ); - let tr = origin - ro + translate; - let m = [[r[0][0], r[0][1], r[0][2], 0.0], [r[1][0], r[1][1], r[1][2], 0.0], [r[2][0], r[2][1], r[2][2], 0.0], [tr.x, tr.y, tr.z, 1.0]]; - transform_matrix(body, m) - } + // Same motion as a matrix: rotate about the line through `origin`, then translate. + let ax = if angle.abs() > 1e-12 { axis.normalized().ok_or_else(|| KernelError::Invalid("rotation axis".into()))? } else { Vec3::Z }; + let (c, s) = (angle.cos(), angle.sin()); + let t = 1.0 - c; + let r = [ + [t * ax.x * ax.x + c, t * ax.x * ax.y + s * ax.z, t * ax.x * ax.z - s * ax.y], + [t * ax.x * ax.y - s * ax.z, t * ax.y * ax.y + c, t * ax.y * ax.z + s * ax.x], + [t * ax.x * ax.z + s * ax.y, t * ax.y * ax.z - s * ax.x, t * ax.z * ax.z + c], + ]; + let ro = Vec3::new( + r[0][0] * origin.x + r[1][0] * origin.y + r[2][0] * origin.z, + r[0][1] * origin.x + r[1][1] * origin.y + r[2][1] * origin.z, + r[0][2] * origin.x + r[1][2] * origin.y + r[2][2] * origin.z, + ); + let tr = origin - ro + translate; + let m = [[r[0][0], r[0][1], r[0][2], 0.0], [r[1][0], r[1][1], r[1][2], 0.0], [r[2][0], r[2][1], r[2][2], 0.0], [tr.x, tr.y, tr.z, 1.0]]; + transform_matrix(body, m) } /// Split a body with a plane: the parts on the positive and the negative side of the plane /// (only the non-empty ones). -pub fn split_by_plane(body: &Body, plane: &solidcraft_geom::Plane) -> Result> { +pub fn split_by_plane(body: &Body, plane: &solidcore_record::Plane) -> Result> { + let _span = solidcraft_profile::span("kernel", "split_by_plane"); let mut out = Vec::new(); for positive in [true, false] { out.extend(half_space(body, plane, positive)?.0); @@ -2378,108 +263,25 @@ pub fn split_by_plane(body: &Body, plane: &solidcraft_geom::Plane) -> Result Result<(Option, Body)> { +pub fn half_space(body: &Body, plane: &solidcore_record::Plane, positive: bool) -> Result<(Option, Body)> { + let _span = solidcraft_profile::span("kernel", "half_space"); // The box's own construction roles describe no face of the design: the cut face has none. let tool = half_box(body, plane, positive)?.with_face_sources(None); - let (part, report) = capture_boolean_diagnostics(|| boolean(body, &tool, BoolOp::Intersect)); - // Faces of the body lying in the plane coincide with the box's cap, which the boolean may - // only take by nudging the box, by a share of its own size: the cut face then moves off the - // plane, a different way for each part, and the parts lose the slab between (#1510). Moved - // off the plane to the side the box leaves out, those faces change nothing of the part, and - // the cap meets no face. Asked only when the boolean failed or nudged the box: a part made - // without, its faces' names included, stays as it is. - let nudged = report.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge); - if (part.is_err() || nudged) - && let Some(moved) = off_plane(body, plane, positive) - { - let (exact, moved_report) = capture_boolean_diagnostics(|| boolean(&moved, &tool, BoolOp::Intersect)); - if let Ok(exact) = exact { - merge(moved_report); - // The part's history over [body, box], through the moved body (its faces are the body's). - let hb = recorded::placed(recorded::through(&moved, 0, recorded::kept(body, 0, 1).as_ref()), 0, 2); - let ht = recorded::placed(recorded::kept(&tool, 0, 1), 1, 2); - let counts = record::counts(&[body, &tool]); - let exact = exact.map(|r| { - let h = recorded::of_pair(&r, &hb, &ht); - r.with_checked_history(h, &counts) - }); - return Ok((exact, tool)); - } - } - merge(report); - Ok((part?, tool)) -} - -/// `body` with its planar faces lying in `plane` moved off it, a thousandth of the body's size, -/// to the side a split's part on the `positive` side leaves out. `None` when no face lies there -/// or moving them doesn't give a sound body. -pub(crate) fn off_plane(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Option { - let m = plane.normal().normalized()?; - let keep = if positive { m } else { -m }; - let size = body.size(); - let tol = (size * 1e-7).max(1e-9); - // Lying in the plane means in it, not within the boolean's tolerance of it: a face that close - // but off it bounds a real sliver, which moving the face would take or add. - let exact = (size * 1e-9).max(1e-12); - let delta = size * 1e-3; - let mut out: Option = None; - for n in [keep, -keep] { - let d = n.dot(plane.origin); - // The faces `push_faces` takes for this plane (by their surface), which must all lie in - // it: one only nearly parallel, its origin in the plane, would be moved where it isn't. - let taken: Vec<&mt::Face> = body - .solid - .face_iter() - .filter(|f| match f.oriented_surface() { - mt::Surface::Plane(p) => { - let q = p.normal(); - Vec3::new(q.x, q.y, q.z).normalized().is_some_and(|q| q.dot(n) > 1.0 - 1e-9) - && (n.dot(from_p3(p.origin())) - d).abs() < tol * 10.0 - } - _ => false, - }) - .collect(); - if taken.is_empty() { - continue; - } - // Its vertices and points along its edges (a disc has one vertex). - let lies = |f: &mt::Face| { - use mt::{BoundedCurve, ParametricCurve}; - let on = |p: mt::Point3| (n.dot(from_p3(p)) - d).abs() < exact; - f.vertex_iter().all(|v| on(v.point())) - && f.edge_iter().all(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - [0.25, 0.5, 0.75].iter().all(|k| on(c.subs(t0 + (t1 - t0) * k))) - }) - }; - if !taken.iter().all(|f| lies(f)) { - return None; - } - // Along -keep: inwards for a face facing the kept side, outwards for one facing away. - let shift = if n.dot(keep) > 0.0 { -delta } else { delta }; - let cur = out.as_ref().unwrap_or(body); - out = Some(crate::coplanar::push_faces(cur, n, d, shift).ok().filter(|b| b.validity().is_empty())?); - } - out + Ok((boolean(body, &tool, BoolOp::Intersect)?, tool)) } /// A box covering everything of `body` on one side of a plane, its start cap in the plane. -pub(crate) fn half_box(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result { +pub(crate) fn half_box(body: &Body, plane: &solidcore_record::Plane, positive: bool) -> Result { body.require_brep("split")?; - let size = body.size(); - let mut bb = solidcraft_geom::Aabb3::EMPTY; - for v in body.solid.vertex_iter() { - bb.add(crate::body::from_p3(v.point())); - } - let reach = (bb.diagonal() + plane.origin.dist(bb.center())) * 2.0 + size; + let bb = body.exact_bounds()?; + let reach = (bb.diagonal() + plane.origin.dist(bb.center())) * 2.0 + body.size(); let c = plane.to_local(bb.center()); - let sq = solidcraft_geom::Region2 { - outer: solidcraft_geom::Loop2::polygon(&[ - solidcraft_geom::Vec2::new(c.x - reach, c.y - reach), - solidcraft_geom::Vec2::new(c.x + reach, c.y - reach), - solidcraft_geom::Vec2::new(c.x + reach, c.y + reach), - solidcraft_geom::Vec2::new(c.x - reach, c.y + reach), + let sq = solidcore_record::Region2 { + outer: solidcore_record::Loop2::polygon(&[ + solidcore_record::Vec2::new(c.x - reach, c.y - reach), + solidcore_record::Vec2::new(c.x + reach, c.y - reach), + solidcore_record::Vec2::new(c.x + reach, c.y + reach), + solidcore_record::Vec2::new(c.x - reach, c.y + reach), ]), holes: vec![], }; @@ -2487,14 +289,6 @@ pub(crate) fn half_box(body: &Body, plane: &solidcraft_geom::Plane, positive: bo crate::build::extrude(plane, std::slice::from_ref(&sq), lo, hi)?.pop().ok_or_else(|| KernelError::Failed("half space".into())) } -#[cfg(test)] -#[path = "empty_retry_tests.rs"] -mod empty_retry_tests; - -#[cfg(test)] -#[path = "prism_fast_path_tests.rs"] -mod prism_fast_path_tests; - #[cfg(test)] #[path = "placement_tests.rs"] mod placement_tests; diff --git a/crates/kernel/src/outline.rs b/crates/kernel/src/outline.rs deleted file mode 100644 index 456e88c10..000000000 --- a/crates/kernel/src/outline.rs +++ /dev/null @@ -1,566 +0,0 @@ -//! Union of bodies touching back to back over part of a planar face, imprinted along the -//! outline of the contact itself. -//! -//! [`crate::coplanar::imprint_union`] splits each body's face along the other's sides, extended -//! to whole planes and cylinders. Where a side's surface runs on into the contact (the inner -//! wall of a lip swept round a corner, whose straight part is tangent to its round part), the -//! two bodies' pieces don't match and the faces can't be glued. Here each face in the plane is -//! divided only by the other body's edges in the plane, as far as they run across it: both -//! bodies' faces in the plane are lines and circular arcs, every edge is cut where the other's -//! edges cross or touch it, the other's edges lying inside a face are copied into it, and the -//! face is rebuilt as the regions those edges bound. The common regions are then the same faces -//! in both bodies, and [`crate::coplanar::glue`] takes them away. - -use std::collections::HashMap; -use std::f64::consts::TAU; - -use mt::{BoundedCurve, ParametricCurve}; -use solidcraft_geom::{Vec2, Vec3}; -use truck_modeling as mt; - -use crate::body::{Body, from_p3}; -use crate::history::History; -use crate::record::Rebuild; -use crate::{KernelError, Result, guard, record}; - -/// Most edges of a body's faces in the plane the outline imprint takes on. -const MAX_EDGES: usize = 2000; - -/// A frame in the plane, `x × y` its normal. -#[derive(Clone, Copy)] -struct Frame { - o: Vec3, - x: Vec3, - y: Vec3, -} - -impl Frame { - /// The plane `n · p = d` (`n` a unit normal). - fn new(n: Vec3, d: f64) -> Frame { - let x = n.any_perp(); - Frame { o: n * d, x, y: n.cross(x) } - } - - fn normal(&self) -> Vec3 { - self.x.cross(self.y) - } - - /// The same plane seen from its other side. - fn flipped(&self) -> Frame { - Frame { o: self.o, x: self.x, y: -self.y } - } - - fn local(&self, p: Vec3) -> Vec2 { - let v = p - self.o; - Vec2::new(v.dot(self.x), v.dot(self.y)) - } - - fn world(&self, q: Vec2) -> Vec3 { - self.o + self.x * q.x + self.y * q.y - } -} - -/// A line or circular arc in the plane, in the direction of the edge it is. -#[derive(Clone, Copy, Debug)] -enum Piece { - Line { - a: Vec2, - b: Vec2, - }, - /// From the angle `t0` about `c`, turning by `sweep` (counter-clockwise when positive). - Arc { - c: Vec2, - r: f64, - t0: f64, - sweep: f64, - }, -} - -/// A fixed direction for counting crossings, clear of the axes and of round angles. -const RAY: (f64, f64) = (0.951_056_516_295_153_6, 0.309_016_994_374_947_45); - -impl Piece { - fn at(&self, s: f64) -> Vec2 { - match *self { - Piece::Line { a, b } => a.lerp(b, s), - Piece::Arc { c, r, t0, sweep } => c + Vec2::from_angle(t0 + sweep * s) * r, - } - } - - fn len(&self) -> f64 { - match *self { - Piece::Line { a, b } => a.dist(b), - Piece::Arc { r, sweep, .. } => r * sweep.abs(), - } - } - - /// Where the angle `t` lies along the arc (0 at its start, 1 at its end), if it does. - fn arc_fraction(t0: f64, sweep: f64, t: f64) -> Option { - let turned = if sweep >= 0.0 { (t - t0).rem_euclid(TAU) } else { (t0 - t).rem_euclid(TAU) }; - let span = sweep.abs(); - if turned <= span { - Some(turned / span) - } else if span >= TAU - 1e-12 { - Some(0.0) - } else { - None - } - } - - /// Distance from `p` to the piece. - fn dist(&self, p: Vec2) -> f64 { - match *self { - Piece::Line { a, b } => { - let d = b - a; - let l2 = d.len2(); - let s = if l2 > 0.0 { ((p - a).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 }; - p.dist(a + d * s) - } - Piece::Arc { c, r, t0, sweep } => match Self::arc_fraction(t0, sweep, (p - c).angle()) { - Some(_) => ((p - c).len() - r).abs(), - None => p.dist(self.at(0.0)).min(p.dist(self.at(1.0))), - }, - } - } - - /// How many times the ray from `p` along [`RAY`] crosses the piece. - fn crossings(&self, p: Vec2) -> usize { - let dir = Vec2::new(RAY.0, RAY.1); - match *self { - Piece::Line { a, b } => { - let e = b - a; - let den = dir.cross(e); - if den.abs() < 1e-300 { - return 0; - } - let w = a - p; - let t = w.cross(e) / den; - let s = w.cross(dir) / den; - usize::from(t > 0.0 && (0.0..1.0).contains(&s)) - } - Piece::Arc { c, r, t0, sweep } => { - // p + t·dir on the circle: t² + 2t(w·dir) + |w|² − r² = 0, w = p − c. - let w = p - c; - let bq = w.dot(dir); - let disc = bq * bq - (w.len2() - r * r); - if !(disc > 0.0) { - return 0; - } - let root = disc.sqrt(); - [-bq - root, -bq + root] - .into_iter() - .filter(|t| *t > 0.0) - .filter(|t| Self::arc_fraction(t0, sweep, (p + dir * *t - c).angle()).is_some_and(|f| f < 1.0 || sweep.abs() >= TAU - 1e-12)) - .count() - } - } - } - - /// The unit direction from the piece's start (`end` false) or end (`end` true) toward a - /// point a little along it: the direction it leaves or enters its vertex, with its bend. - fn leaving(&self, end: bool) -> Option { - let len = self.len(); - let s = if len > 0.0 { (1e-3 / len).min(0.25) } else { 0.25 }; - let (v, q) = if end { (self.at(1.0), self.at(1.0 - s)) } else { (self.at(0.0), self.at(s)) }; - (q - v).normalized() - } -} - -/// The edge `e` (in its own direction) as a line or arc in the frame's plane; `None` when it is -/// off the plane or neither. -fn piece_of(e: &mt::Edge, fr: &Frame, tol: f64) -> Option { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let n = fr.normal(); - let pts: Vec = (0..=8).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 8.0))).collect(); - if pts.iter().any(|p| (*p - fr.o).dot(n).abs() > tol) { - return None; - } - let q: Vec = pts.iter().map(|p| fr.local(*p)).collect(); - let (&a, &b, &m) = (q.first()?, q.last()?, q.get(4)?); - let closed = a.dist(b) <= tol; - if !closed { - let line = Piece::Line { a, b }; - if q.iter().all(|p| line.dist(*p) <= tol) { - return Some(line); - } - } - // The circle through three of the points. - let (p1, p2, p3) = if closed { (a, *q.get(3)?, *q.get(6)?) } else { (a, m, b) }; - let (u, v) = (p2 - p1, p3 - p1); - let den = 2.0 * u.cross(v); - if den.abs() < 1e-300 { - return None; - } - let centre = p1 + Vec2::new(v.y * u.len2() - u.y * v.len2(), u.x * v.len2() - v.x * u.len2()) * (1.0 / den); - let r = (a - centre).len(); - if !(r > tol) || q.iter().any(|p| ((*p - centre).len() - r).abs() > tol) { - return None; - } - let start = (a - centre).angle(); - let ccw = (a - centre).cross(*q.get(1)? - centre) > 0.0; - let sweep = if closed { - if ccw { TAU } else { -TAU } - } else if ccw { - ((b - centre).angle() - start).rem_euclid(TAU) - } else { - -((start - (b - centre).angle()).rem_euclid(TAU)) - }; - // The samples run along it in order (a rational arc is not even in angle). - let mut last = -1e-9; - for p in q.iter().skip(1).take(7) { - let f = Piece::arc_fraction(start, sweep, (*p - centre).angle())?; - if f < last { - return None; - } - last = f; - } - Some(Piece::Arc { c: centre, r, t0: start, sweep }) -} - -/// Where two pieces cross or touch (each point within `tol` of both). -fn meetings(p: &Piece, q: &Piece, tol: f64) -> Vec { - let mut out: Vec = Vec::new(); - let line_circle = |a: Vec2, b: Vec2, c: Vec2, r: f64, out: &mut Vec| { - let Some(dir) = (b - a).normalized() else { return }; - let foot = a + dir * (c - a).dot(dir); - let h = (c - foot).len(); - if h > r + tol { - return; - } - if (h - r).abs() <= tol { - out.push(foot); - } else { - let k = (r * r - h * h).max(0.0).sqrt(); - out.extend([foot - dir * k, foot + dir * k]); - } - }; - match (*p, *q) { - (Piece::Line { a, b }, Piece::Line { a: c, b: d }) => { - let (e, f) = (b - a, d - c); - let den = e.cross(f); - if den.abs() > 1e-12 * e.len() * f.len() { - let s = (c - a).cross(f) / den; - out.push(a + e * s); - } - } - (Piece::Line { a, b }, Piece::Arc { c, r, .. }) | (Piece::Arc { c, r, .. }, Piece::Line { a, b }) => line_circle(a, b, c, r, &mut out), - (Piece::Arc { c: c1, r: r1, .. }, Piece::Arc { c: c2, r: r2, .. }) => { - let d = c1.dist(c2); - if d > tol && d <= r1 + r2 + tol && d + tol >= (r1 - r2).abs() { - let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d); - let h = (r1 * r1 - a * a).max(0.0).sqrt(); - let u = (c2 - c1) * (1.0 / d); - let base = c1 + u * a; - if h <= tol { - out.push(base); - } else { - out.extend([base + u.perp() * h, base - u.perp() * h]); - } - } - } - } - // The ends of either lying on the other (a T, or where overlapping pieces part). - for (x, y) in [(p, q), (q, p)] { - for end in [x.at(0.0), x.at(1.0)] { - if y.dist(end) <= tol { - out.push(end); - } - } - } - out.retain(|m| p.dist(*m) <= tol && q.dist(*m) <= tol); - out -} - -/// The edges of `body`'s faces in the plane of `fr` that face along its normal, once each, in -/// their absolute direction, with their pieces. `None` when one is neither a line nor an arc. -fn plane_edges(body: &Body, faces: &[usize], fr: &Frame, tol: f64) -> Option> { - let fs: Vec<&mt::Face> = body.solid.face_iter().collect(); - let mut seen = std::collections::HashSet::new(); - let mut out = Vec::new(); - for f in faces.iter().filter_map(|i| fs.get(*i)) { - for e in f.edge_iter() { - if !seen.insert(e.id()) { - continue; - } - let abs = if e.orientation() { e.clone() } else { e.inverse() }; - out.push((abs.clone(), piece_of(&abs, fr, tol)?)); - if out.len() > MAX_EDGES { - return None; - } - } - } - Some(out) -} - -/// Points where the edges of `own` are to be cut so that every piece of them lies inside, -/// outside or along the edges of `other` (in world coordinates). -fn cuts(own: &[(mt::Edge, Piece)], other: &[(mt::Edge, Piece)], fr: &Frame, tol: f64) -> Vec { - let mut out = Vec::new(); - for (_, p) in own { - for (_, q) in other { - for m in meetings(p, q, tol) { - if m.dist(p.at(0.0)) > tol && m.dist(p.at(1.0)) > tol { - out.push(fr.world(m)); - } - } - } - } - out -} - -/// One edge use in a face being rebuilt: the edge as the face uses it, its piece in that -/// direction, its ends, and its reverse use when it is a copy used both ways. -struct Use { - edge: mt::Edge, - piece: Piece, - from: mt::VertexID, - to: mt::VertexID, - twin: Option, -} - -/// Does the point lie inside the region bounded by `pieces` (closed loops, holes included)? -fn inside(pieces: &[Piece], p: Vec2) -> bool { - pieces.iter().map(|x| x.crossings(p)).sum::() % 2 == 1 -} - -/// The loops of uses, each next use the one leaving the vertex furthest clockwise from the way -/// the last one came in: each loop runs round one region with it on the left. -fn loops(uses: &[Use]) -> Option>> { - let mut out_of: HashMap> = HashMap::new(); - for (i, u) in uses.iter().enumerate() { - out_of.entry(u.from).or_default().push(i); - } - let mut used = vec![false; uses.len()]; - let mut out = Vec::new(); - for start in 0..uses.len() { - if used.get(start).copied().unwrap_or(true) { - continue; - } - let mut lp = vec![start]; - if let Some(x) = used.get_mut(start) { - *x = true; - } - let mut cur = start; - loop { - let u = uses.get(cur)?; - let back = u.piece.leaving(true)?; - let next = out_of - .get(&u.to)? - .iter() - .copied() - .filter(|k| Some(*k) != u.twin) - .filter_map(|k| { - let d = uses.get(k)?.piece.leaving(false)?; - // Counter-clockwise from the way back, in (0, 2π]. - let turn = back.cross(d).atan2(back.dot(d)); - Some((k, if turn <= 0.0 { turn + TAU } else { turn })) - }) - .max_by(|x, y| x.1.total_cmp(&y.1)) - .map(|(k, _)| k)?; - if next == start { - break; - } - if used.get(next).copied().unwrap_or(true) || lp.len() > uses.len() { - return None; - } - if let Some(x) = used.get_mut(next) { - *x = true; - } - lp.push(next); - cur = next; - } - out.push(lp); - } - Some(out) -} - -/// The signed area a loop bounds (positive counter-clockwise). -fn area(uses: &[Use], lp: &[usize]) -> f64 { - let pts: Vec = lp.iter().filter_map(|i| uses.get(*i)).flat_map(|u| (0..16).map(move |k| u.piece.at(k as f64 / 16.0))).collect(); - (0..pts.len()).map(|i| pts.get(i).zip(pts.get((i + 1) % pts.len())).map(|(a, b)| a.cross(*b)).unwrap_or(0.0)).sum::() * 0.5 -} - -/// `body` with its faces `faces` (in the plane of `fr`, facing along its normal) divided by those -/// edges of `other` that run inside them: each such edge is copied into the face, and the face -/// is rebuilt as the regions its own edges and the copies bound. History over `[body]`. `None` -/// when a face can't be rebuilt so. -fn divided(body: &Body, faces: &[usize], other: &[(mt::Edge, Piece)], fr: &Frame, tol: f64) -> Result> { - let fs: Vec<&mt::Face> = body.solid.face_iter().collect(); - // Each face's own edge uses, in the direction it runs them (counter-clockwise about the - // frame's normal round its outside). - let mut own: Vec<(usize, Vec<(mt::Edge, Piece)>)> = Vec::new(); - for &fi in faces { - let Some(f) = fs.get(fi) else { continue }; - let mut es = Vec::new(); - for w in f.boundaries() { - for e in w.edge_iter() { - let Some(p) = piece_of(e, fr, tol) else { return Ok(None) }; - es.push((e.clone(), p)); - } - } - own.push((fi, es)); - } - let all_own: Vec = own.iter().flat_map(|(_, es)| es.iter().map(|(_, p)| *p)).collect(); - // The vertices the copies end on: the faces' own where they meet, else new ones shared. - let mut pool: Vec = own.iter().flat_map(|(_, es)| es.iter().flat_map(|(e, _)| [e.front().clone(), e.back().clone()])).collect(); - let mut vertex = |p: Vec3| -> mt::Vertex { - if let Some(v) = pool.iter().find(|v| from_p3(v.point()).dist(p) <= tol) { - return v.clone(); - } - let v = mt::Vertex::new(crate::body::p3(p)); - pool.push(v.clone()); - v - }; - let mut copies: HashMap> = HashMap::new(); - for (e, p) in other { - // Along the faces' own edges: nothing to add. - if [0.25, 0.5, 0.75].iter().all(|s| all_own.iter().any(|o| o.dist(p.at(*s)) <= tol * 10.0)) { - continue; - } - let mid = p.at(0.5); - let Some((fi, _)) = own.iter().find(|(_, es)| inside(&es.iter().map(|(_, x)| *x).collect::>(), mid)) else { continue }; - let (v0, v1) = (vertex(from_p3(e.front().point())), vertex(from_p3(e.back().point()))); - // On the face's own vertices, which lie within `tol` of the edge's ends. - let copy = mt::Edge::new_unchecked(&v0, &v1, e.curve()); - let Some(cp) = piece_of(©, fr, tol) else { return Ok(None) }; - copies.entry(*fi).or_default().push((copy, cp)); - } - if copies.is_empty() { - return Ok(None); - } - let mut rebuilt: HashMap> = HashMap::new(); - for (fi, es) in &own { - let Some(cs) = copies.get(fi) else { continue }; - let Some(f) = fs.get(*fi) else { continue }; - let mut uses: Vec = - es.iter().map(|(e, p)| Use { edge: e.clone(), piece: *p, from: e.front().id(), to: e.back().id(), twin: None }).collect(); - for (e, p) in cs { - let k = uses.len(); - let back = e.inverse(); - let Some(bp) = piece_of(&back, fr, tol) else { return Ok(None) }; - uses.push(Use { edge: e.clone(), piece: *p, from: e.front().id(), to: e.back().id(), twin: Some(k + 1) }); - uses.push(Use { from: back.front().id(), to: back.back().id(), edge: back, piece: bp, twin: Some(k) }); - } - let Some(lps) = loops(&uses) else { return Ok(None) }; - let (outer, holes): (Vec<(Vec, f64)>, Vec<(Vec, f64)>) = lps - .into_iter() - .map(|lp| { - let a = area(&uses, &lp); - (lp, a) - }) - .partition(|(_, a)| *a > 0.0); - let pieces_of = |lp: &[usize]| -> Vec { lp.iter().filter_map(|i| uses.get(*i)).map(|u| u.piece).collect() }; - let mut groups: Vec<(Vec, f64, Vec>)> = outer.into_iter().map(|(lp, a)| (lp, a, Vec::new())).collect(); - for (hole, _) in holes { - let Some(p) = hole.first().and_then(|i| uses.get(*i)).map(|u| u.piece.at(0.5)) else { return Ok(None) }; - let Some(g) = groups.iter_mut().filter(|(lp, _, _)| inside(&pieces_of(lp), p)).min_by(|x, y| x.1.total_cmp(&y.1)) else { - return Ok(None); - }; - g.2.push(hole); - } - let wire = |lp: &[usize]| -> mt::Wire { lp.iter().filter_map(|i| uses.get(*i)).map(|u| u.edge.clone()).collect::>().into() }; - let mut made = Vec::new(); - for (lp, _, hs) in &groups { - let wires: Vec = std::iter::once(wire(lp)).chain(hs.iter().map(|h| wire(h))).collect(); - // The loops run round the face as its normal sees them; a face turned against its - // surface stores them the other way. - let nf = if f.orientation() { - mt::Face::try_new(wires, f.surface()) - } else { - mt::Face::try_new(wires.iter().map(|w| w.inverse()).collect(), f.surface()).map(|mut x| { - x.invert(); - x - }) - }; - made.push(nf.map_err(|x| KernelError::Failed(format!("rebuilding a face of the contact: {x}")))?); - } - rebuilt.insert(*fi, made); - } - let mut rec = Rebuild::default(); - let mut index = 0; - let mut shells = Vec::new(); - for sh in body.solid.boundaries() { - let mut faces = Vec::new(); - for f in sh.face_iter() { - match rebuilt.get(&index) { - Some(made) => { - for nf in made { - rec.whole(nf, f); - faces.push(nf.clone()); - } - } - None => { - rec.whole(f, f); - faces.push(f.clone()); - } - } - index += 1; - } - shells.push(mt::Shell::from(faces)); - } - let Ok(solid) = mt::Solid::try_new(shells) else { return Ok(None) }; - let split = Body { - solid: std::sync::Arc::new(solid), - size: 0.0, - boundary_tol: body.boundary_tol, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: None, - mesh: None, - color: body.color, - paint: None, - splits: body.splits.clone(), - face_sources: None, - history: None, - regularization_protected: true, - display_of: None, - meshes: None, - phased: false, - }; - Ok(Some(record::rebuilt_body(split, &[&body.solid], &rec))) -} - -/// Union of bodies touching back to back over part of a planar face whose edges there are lines -/// and circular arcs (a lip swept along a rim, flush with a round side): imprinted on each other -/// along the outline of the contact and glued. `None` when that does not give a result -/// `accept`ed. -pub(crate) fn outline_union(a: &Body, b: &Body, accept: &dyn Fn(&Body) -> bool) -> Option { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let back: Vec<(Vec3, f64)> = crate::coplanar::coincident_planes(a, b).into_iter().filter(|(_, _, same)| !*same).map(|(n, d, _)| (n, d)).collect(); - if back.is_empty() { - return None; - } - let run = || -> Result> { - let (mut a2, mut ha): (Body, Option) = (a.clone(), crate::boolean_record::kept(a, 0, 1)); - let (mut b2, mut hb): (Body, Option) = (b.clone(), crate::boolean_record::kept(b, 0, 1)); - for (n, d) in &back { - // a's faces face along n in the plane; b's the other way. - let fa = Frame::new(*n, *d); - let fb = fa.flipped(); - let in_a = |x: &Body| crate::coplanar::faces_in(x, *n, *d, tol); - let in_b = |x: &Body| crate::coplanar::faces_in(x, -*n, -*d, tol); - let (Some(ea), Some(eb)) = (plane_edges(&a2, &in_a(&a2), &fa, tol), plane_edges(&b2, &in_b(&b2), &fa, tol)) else { return Ok(None) }; - let a3 = crate::splitface::split_edges_at(&a2, &cuts(&ea, &eb, &fa, tol))?; - ha = crate::boolean_record::through(&a3, 0, ha.as_ref()); - let b3 = crate::splitface::split_edges_at(&b2, &cuts(&eb, &ea, &fa, tol))?; - hb = crate::boolean_record::through(&b3, 0, hb.as_ref()); - // Each side's edges as the other side's frame sees them. - let (Some(eb), Some(ea)) = (plane_edges(&b3, &in_b(&b3), &fa, tol), plane_edges(&a3, &in_a(&a3), &fb, tol)) else { return Ok(None) }; - let a4 = divided(&a3, &in_a(&a3), &eb, &fa, tol)?.unwrap_or(a3); - let b4 = divided(&b3, &in_b(&b3), &ea, &fb, tol)?.unwrap_or(b3); - ha = crate::boolean_record::through(&a4, 0, ha.as_ref()); - hb = crate::boolean_record::through(&b4, 0, hb.as_ref()); - (a2, b2) = (a4, b4); - } - let Some(r) = crate::coplanar::glue(&a2, &b2) else { return Ok(None) }; - let r = r?; - let (ha, hb) = (crate::boolean_record::placed(ha, 0, 2), crate::boolean_record::placed(hb, 1, 2)); - let h = crate::boolean_record::of_pair(&r, &ha, &hb); - Ok(Some(r.with_checked_history(h, &record::counts(&[a, b])))) - }; - match guard("outline union", run) { - Ok(Some(r)) if accept(&r) => Some(r), - _ => None, - } -} diff --git a/crates/kernel/src/outline_tests.rs b/crates/kernel/src/outline_tests.rs index 7cd95417d..d583f1463 100644 --- a/crates/kernel/src/outline_tests.rs +++ b/crates/kernel/src/outline_tests.rs @@ -1,9 +1,10 @@ //! A lip swept along the rim of a round body joins it, flush with its side or set in from it: //! the lip's foot lies on the body's top, and its sides are round where the rim is. +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI}; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::*; @@ -23,17 +24,19 @@ fn a_lip_swept_on_a_round_rim_joins_it() { for inset in [0.0, 0.5] { let (r0, r1) = (9.0 - inset, 10.0 - inset); // Measured as the result is (the round faces' volume from their meshes). - let mesh_volume = |b: &Body| b.tessellate(1e-5).unwrap().measure().volume; + let mesh_volume = |b: &Body| b.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap().measure().volume; let want = mesh_volume(&body) + mesh_volume(&lip(inset)); assert!((want - PI * 1000.0 - PI * (r1 * r1 - r0 * r0) / 4.0).abs() < 0.05); for (a, b) in [(&body, &lip(inset)), (&lip(inset), &body)] { - let (r, d) = capture_boolean_diagnostics(|| boolean(a, b, BoolOp::Union)); - let r = r.unwrap().unwrap(); + let r = boolean(a, b, BoolOp::Union).unwrap().unwrap(); assert_eq!(r.shell_count(), 1, "inset {inset}: one solid"); assert!(r.validity().is_empty(), "inset {inset}: {:?}", r.validity()); + // Each mesh lies within its chord (1e-5) of its faces: two meshes of the same solid, + // tessellated face by face as each body has its faces, differ by at most their area + // times twice that. let v = mesh_volume(&r); - assert!((v - want).abs() < 1e-3, "inset {inset}: volume {v} vs {want}"); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "inset {inset}: an exact join: {d:?}"); + let bound = crate::measure(&r).unwrap().area * 2e-5; + assert!((v - want).abs() < bound, "inset {inset}: volume {v} vs {want} (within {bound})"); } } } @@ -42,8 +45,11 @@ fn a_lip_swept_on_a_round_rim_joins_it() { #[test] fn a_swept_lips_foot_is_a_plane() { let l = lip(0.0); - let foot = crate::coplanar::faces_in(&l, -Vec3::Z, -10.0, 1e-6); - let m = l.tessellate(1e-5).unwrap(); + // The faces lying in the plane z = 10 facing down: planar, normal -z, through z = 10. + let foot: Vec = (0..l.face_count()) + .filter(|&i| l.planar_face(i).is_some_and(|p| p.normal().dot(-Vec3::Z) > 1.0 - 1e-9 && (p.origin.z - 10.0).abs() < 1e-6)) + .collect(); + let m = l.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap(); let area: f64 = m .triangles .iter() diff --git a/crates/kernel/src/par.rs b/crates/kernel/src/par.rs index b18ea88bb..972bac0d8 100644 --- a/crates/kernel/src/par.rs +++ b/crates/kernel/src/par.rs @@ -4,19 +4,51 @@ use crate::{Result, guard}; +/// The stack of a thread that runs kernel work: solidcore's algorithms recurse (subdivision, +/// intersection, filleting), and its README asks for 8 MiB, a native main thread's stack, where +/// Rust starts other threads with 2 MiB. +pub const KERNEL_STACK: usize = 8 << 20; + +/// A thread named `name` with the kernel's stack ([`KERNEL_STACK`]), for a thread that runs +/// kernel work (an operation, an evaluation, a mesh). +pub fn kernel_thread(name: &str) -> std::thread::Builder { + std::thread::Builder::new().name(name.to_owned()).stack_size(KERNEL_STACK) +} + +/// The kernel's worker pool, its threads with the kernel's stack; `None` when it cannot start +/// (the work then runs on the calling thread). +#[cfg(not(target_arch = "wasm32"))] +fn pool() -> Option<&'static rayon::ThreadPool> { + static POOL: std::sync::OnceLock> = std::sync::OnceLock::new(); + POOL.get_or_init(|| rayon::ThreadPoolBuilder::new().thread_name(|i| format!("solidcraft-kernel-{i}")).stack_size(KERNEL_STACK).build().ok()) + .as_ref() +} + /// `f` over `items`, results in item order: on the pool when `parallel`, else on the calling /// thread. Waking the pool's workers costs tens of microseconds, so callers ask for it only /// when the items carry more work than that (decided from the work, not the item count). pub(crate) fn map(what: &'static str, items: &[T], parallel: bool, f: impl Fn(&T) -> Result + Sync) -> Vec> { - let one = |item: &T| guard(what, || f(item)); + // The workers run under the caller's validation mode (`crate::validation`). + let scope = crate::validation::current(); + let one = |item: &T| crate::validation::within(scope.clone(), || guard(what, || f(item))); // The browser build has no worker pool: everything runs on the calling thread. #[cfg(target_arch = "wasm32")] let _ = parallel; #[cfg(not(target_arch = "wasm32"))] { use rayon::prelude::*; - if parallel && items.len() > 1 && rayon::current_num_threads() > 1 { - return items.par_iter().map(one).collect(); + if parallel && items.len() > 1 { + if rayon::current_thread_index().is_some() { + // On a pool's worker (the kernel's, or a one-thread pool of + // `map_with_local_pools`): that pool's threads, as many as it has. + if rayon::current_num_threads() > 1 { + return items.par_iter().map(one).collect(); + } + } else if let Some(pool) = pool() + && pool.current_num_threads() > 1 + { + return pool.install(|| items.par_iter().map(one).collect()); + } } } items.iter().map(one).collect() @@ -48,12 +80,14 @@ pub fn map_with_local_pools(items: &[T], max_threads: usize, f if cell.get().is_none() { let pool = rayon::ThreadPoolBuilder::new() .num_threads(1) + .stack_size(KERNEL_STACK) .build() .map_err(|e| crate::KernelError::Failed(format!("cannot start mesh worker: {e}")))?; let _ = cell.set(pool); } let pool = cell.get().ok_or_else(|| crate::KernelError::Failed("missing mesh worker".into()))?; - pool.install(|| guard("mesh worker", || f(item))) + let scope = crate::validation::current(); + pool.install(|| crate::validation::within(scope, || guard("mesh worker", || f(item)))) }) }; #[cfg(target_arch = "wasm32")] @@ -67,7 +101,9 @@ pub fn map_with_local_pools(items: &[T], max_threads: usize, f /// `f` over `items` as [`for_each_on_threads`] runs it, results in item order (`None` where an /// item panicked). pub fn map_on_threads(items: &[T], max_threads: usize, f: impl Fn(&T) -> R + Sync) -> Vec> { - let one = |item: &T| guard("parallel item", || Ok(f(item))).ok(); + // The threads run under the caller's validation mode (`crate::validation`). + let scope = crate::validation::current(); + let one = |item: &T| crate::validation::within(scope.clone(), || guard("parallel item", || Ok(f(item))).ok()); #[cfg(not(target_arch = "wasm32"))] { use std::sync::atomic::{AtomicUsize, Ordering}; @@ -86,8 +122,7 @@ pub fn map_on_threads(items: &[T], max_threads: usize, f: impl let mut out: Vec> = std::iter::repeat_with(|| None).take(items.len()).collect(); std::thread::scope(|scope| { // A thread that cannot start leaves its share to the others. - let helpers: Vec<_> = - (1..threads).filter_map(|_| std::thread::Builder::new().name("solidcraft-each".into()).spawn_scoped(scope, work).ok()).collect(); + let helpers: Vec<_> = (1..threads).filter_map(|_| kernel_thread("solidcraft-each").spawn_scoped(scope, work).ok()).collect(); let mut all = work(); for h in helpers { // `work` never panics (every item runs under the guard). @@ -150,6 +185,29 @@ mod tests { } } + /// `depth` frames of recursion, each holding 64 KiB on the stack, summing their depths: 80 is + /// 5 MiB, past the 2 MiB Rust gives a thread and within the kernel's 8 MiB. + fn deep(depth: u8) -> u64 { + let frame = std::hint::black_box([depth; 64 * 1024]); + let here = u64::from(frame[usize::from(depth)]); + if depth == 0 { here } else { here + deep(depth - 1) } + } + + /// Kernel work recurses as deep as solidcore's algorithms do on every thread the kernel runs + /// it on: a kernel thread, the pool's workers, and the helpers of `map_on_threads`. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn kernel_threads_have_the_kernels_stack() { + let want: u64 = (0..=80).sum(); + let on_thread = kernel_thread("deep").spawn(|| deep(80)).unwrap().join().unwrap(); + assert_eq!(on_thread, want); + let items = [80u8; 16]; + let on_pool = kernel_thread("deep-pool").spawn(move || map("deep", &items, true, |&d| Ok(deep(d)))).unwrap().join().unwrap(); + assert!(on_pool.iter().all(|r| r.as_ref().ok() == Some(&want)), "{on_pool:?}"); + let on_helpers = kernel_thread("deep-helpers").spawn(move || map_on_threads(&items, 8, |&d| deep(d))).unwrap().join().unwrap(); + assert!(on_helpers.iter().all(|r| *r == Some(want)), "{on_helpers:?}"); + } + #[test] fn keeps_order_and_errors() { let items: Vec = (0..1000).collect(); diff --git a/crates/kernel/src/pinch_tests.rs b/crates/kernel/src/pinch_tests.rs index 7fd7331e9..c98155a72 100644 --- a/crates/kernel/src/pinch_tests.rs +++ b/crates/kernel/src/pinch_tests.rs @@ -3,7 +3,7 @@ //! along a line give separate shells, and near-tangent numbers from the sketch solver (a //! circle 1e-13 mm past the side) behave like exact ones. -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::*; @@ -24,7 +24,7 @@ fn disc(cx: f64, cy: f64, r: f64) -> Loop2 { } fn assert_solid(r: &Body, volume: f64, rel: f64, shells: usize, what: &str) { - let v = r.tessellate(1e-4).unwrap().measure().volume; + let v = r.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; assert!((v - volume).abs() <= volume * rel, "{what}: volume {v} vs {volume}"); assert_eq!(r.shell_count(), shells, "{what}: shells"); assert!(r.validity().is_empty(), "{what}: {:?}", r.validity()); @@ -41,10 +41,9 @@ fn disc_tangent_to_a_side_and_overhanging_joins() { let top = prism(disc(18.5, cy, r), 10., 20.); let want = 8990.0 + std::f64::consts::PI * r * r * 10.0; for (a, b) in [(&block, &top), (&top, &block)] { - let (res, d) = capture_boolean_diagnostics(|| boolean(a, b, BoolOp::Union)); + let res = boolean(a, b, BoolOp::Union); let res = res.unwrap().unwrap(); assert_solid(&res, want, 1e-5, 1, &format!("disc at {cy}, r {r}")); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{d:?}"); } } } @@ -129,10 +128,9 @@ fn hole_tangent_inside_a_stepped_boss_cuts_exactly() { for (z0, z1, want) in [(-1., 20., 2000. + 1000. - 25. * 15.), (6., 20., 2000. + 1000. - 25. * 9.), (-1., 4., 2000. + 1000. - 25. * 4.)] { let what = format!("hole z {z0}…{z1}, turned {turn}, flip {flip}"); let hole = prism(circle(15., 5.), z0, z1); - let (res, d) = capture_boolean_diagnostics(|| boolean(&stepped, &hole, BoolOp::Cut)); + let res = boolean(&stepped, &hole, BoolOp::Cut); let res = res.unwrap_or_else(|e| panic!("{what}: {e}")).unwrap(); assert_solid(&res, PI * want, 1e-5, 1, &what); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{what}: {d:?}"); } } } @@ -146,10 +144,9 @@ fn hole_tangent_to_a_flat_side_of_a_stepped_block_cuts_exactly() { let boss = prism(rect(10., 10., 40., 30.), 5., 15.); let stepped = boolean(&block, &boss, BoolOp::Union).unwrap().unwrap(); let hole = prism(disc(35., 20., 5.), -1., 20.); - let (res, d) = capture_boolean_diagnostics(|| boolean(&stepped, &hole, BoolOp::Cut)); + let res = boolean(&stepped, &hole, BoolOp::Cut); let res = res.unwrap().unwrap(); assert_solid(&res, 8000. + 6000. - std::f64::consts::PI * 25. * 15., 1e-5, 1, "hole tangent to a flat side"); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{d:?}"); } /// A stepped block cut by a disc tangent to its back side from inside leaves two posts meeting @@ -163,7 +160,7 @@ fn stepped_cuts_touching_along_a_line_keep_their_pieces() { let back = prism(rect(0., 20., 25., 29.), 10., 20.); let stepped = boolean(&block, &back, BoolOp::Union).unwrap().unwrap(); let tool = prism(disc(18.5, 4., 25.), -1., 21.); - let (res, d) = capture_boolean_diagnostics(|| boolean(&stepped, &tool, BoolOp::Cut)); + let res = boolean(&stepped, &tool, BoolOp::Cut); let res = res.unwrap().unwrap(); let n = 400_000; let dx = 31.0 / n as f64; @@ -174,20 +171,16 @@ fn stepped_cuts_touching_along_a_line_keep_their_pieces() { post(x) * dx * if x < 25.0 { 20.0 } else { 10.0 } }) .sum(); - let v = res.tessellate(1e-4).unwrap().measure().volume; + let v = res.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; assert!((v - volume).abs() <= volume * 1e-4, "posts: volume {v} vs {volume}"); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{d:?}"); - let sewn = crate::prism::prism_boolean(&stepped, &tool, BoolOp::Cut); - assert!(!matches!(&sewn, Some(Ok(Some(b))) if b.shell_count() < 2), "posts sewn into one shell"); let block = prism(rect(0., 0., 40., 40.), 0., 5.); let boss = prism(rect(10., 10., 40., 30.), 5., 15.); let stepped = boolean(&block, &boss, BoolOp::Union).unwrap().unwrap(); let diamond = prism(poly(&[[30., 20.], [35., 15.], [40., 20.], [35., 25.]]), -1., 20.); - let (res, d) = capture_boolean_diagnostics(|| boolean(&stepped, &diamond, BoolOp::Cut)); + let res = boolean(&stepped, &diamond, BoolOp::Cut); let res = res.unwrap().unwrap(); assert_solid(&res, 8000. + 6000. - 50. * 15., 1e-9, 1, "diamond hole with a corner on a stepped side"); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{d:?}"); } /// A row of holes each touching the next (a 5 mm pattern of Ø5 holes) through a stepped plate: @@ -199,9 +192,8 @@ fn row_of_touching_holes_through_a_stepped_plate_cuts_exactly() { let mut body = boolean(&plate, ¬ch, BoolOp::Cut).unwrap().unwrap(); for x in [15.45, 20.45, 25.45] { let hole = prism(disc(x, 15.7, 2.5), -5., 7.5); - let (res, d) = capture_boolean_diagnostics(|| boolean(&body, &hole, BoolOp::Cut)); + let res = boolean(&body, &hole, BoolOp::Cut); body = res.unwrap().unwrap(); - assert!(!d.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "hole at {x}: {d:?}"); } assert_solid(&body, 7312.5 - 3.0 * std::f64::consts::PI * 6.25 * 7.5, 1e-5, 1, "touching holes"); } diff --git a/crates/kernel/src/placement_tests.rs b/crates/kernel/src/placement_tests.rs index 2a038bf08..cb451dda5 100644 --- a/crates/kernel/src/placement_tests.rs +++ b/crates/kernel/src/placement_tests.rs @@ -1,64 +1,41 @@ use super::*; -use crate::body::{p3, v3}; -use mt::builder; +use crate::history::BodyHistory; -fn assert_topology(source: &Body, placed: &Body, matrix: [[f64; 4]; 4]) { - use std::collections::HashMap; - let mut vertices = HashMap::new(); - let mut edges = HashMap::new(); - for (a, b) in source.solid.face_iter().zip(placed.solid.face_iter()) { - assert_eq!(a.orientation(), b.orientation()); - let aw = a.absolute_boundaries(); - let bw = b.absolute_boundaries(); - assert_eq!(aw.len(), bw.len()); - for (a, b) in aw.iter().zip(bw.iter()) { - assert_eq!(a.len(), b.len()); - for (a, b) in a.edge_iter().zip(b.edge_iter()) { - assert_eq!(a.orientation(), b.orientation()); - assert_ne!(a.id(), b.id()); - assert_eq!(*edges.entry(a.id()).or_insert(b.id()), b.id()); - for (a, b) in [(a.absolute_front(), b.absolute_front()), (a.absolute_back(), b.absolute_back())] { - assert_ne!(a.id(), b.id()); - assert_eq!(*vertices.entry(a.id()).or_insert(b.id()), b.id()); - let p = from_p3(a.point()); - let expected = Vec3::new( - matrix[0][0] * p.x + matrix[1][0] * p.y + matrix[2][0] * p.z + matrix[3][0], - matrix[0][1] * p.x + matrix[1][1] * p.y + matrix[2][1] * p.z + matrix[3][1], - matrix[0][2] * p.x + matrix[1][2] * p.y + matrix[2][2] * p.z + matrix[3][2], - ); - assert!(from_p3(b.point()).dist(expected) < 1e-9); - } - } - } - } - assert_eq!(edges.len(), source.solid.edge_iter().map(|e| e.id()).collect::>().len()); +/// `p` moved by the column-major affine `matrix`. +fn moved(matrix: [[f64; 4]; 4], p: [f64; 3]) -> Vec3 { + Vec3::new( + matrix[0][0] * p[0] + matrix[1][0] * p[1] + matrix[2][0] * p[2] + matrix[3][0], + matrix[0][1] * p[0] + matrix[1][1] * p[1] + matrix[2][1] * p[2] + matrix[3][1], + matrix[0][2] * p[0] + matrix[1][2] * p[1] + matrix[2][2] * p[2] + matrix[3][2], + ) } +/// A rigid placement moves the record and nothing else: the same regions, shells, faces' loops +/// (edges, directions and pcurves: each surface moves with its parameters), edges' ends and uses; +/// every vertex moved by the motion; and the history the identity's. +fn assert_topology(source: &Body, placed: &Body, matrix: [[f64; 4]; 4]) { + let (a, b) = (source.record(), placed.record()); + assert_eq!(a.regions, b.regions); + assert_eq!(a.shells, b.shells); + assert_eq!(a.faces.len(), b.faces.len()); + for (fa, fb) in a.faces.iter().zip(&b.faces) { + assert_eq!(fa.loops, fb.loops); + assert_eq!(fa.domain, fb.domain); + } + assert_eq!(a.edges.len(), b.edges.len()); + for (ea, eb) in a.edges.iter().zip(&b.edges) { + assert_eq!((ea.vertices, &ea.uses, ea.interval), (eb.vertices, &eb.uses, eb.interval)); + } + assert_eq!(a.vertices.len(), b.vertices.len()); + for (va, vb) in a.vertices.iter().zip(&b.vertices) { + assert!(Vec3::from(vb.point).dist(moved(matrix, va.point)) < 1e-9); + } + assert_eq!(placed.history(), Some(&::identity(source))); +} + +/// A cylinder whose wall is one face with a seam: the seam edge is used twice by the wall's loop. fn periodic_cylinder() -> Body { - let b0 = builder::vertex(p3(Vec3::new(10., 0., 0.))); - let b1 = builder::vertex(p3(Vec3::new(-10., 0., 0.))); - let t0 = builder::vertex(p3(Vec3::new(10., 0., 20.))); - let t1 = builder::vertex(p3(Vec3::new(-10., 0., 20.))); - let bottom: mt::Wire = - vec![builder::circle_arc(&b0, &b1, p3(Vec3::new(0., 10., 0.))), builder::circle_arc(&b1, &b0, p3(Vec3::new(0., -10., 0.)))].into(); - let top: mt::Wire = - vec![builder::circle_arc(&t0, &t1, p3(Vec3::new(0., 10., 20.))), builder::circle_arc(&t1, &t0, p3(Vec3::new(0., -10., 20.)))].into(); - let seam = builder::line(&b0, &t0); - let mut boundary: Vec<_> = bottom.edge_iter().cloned().collect(); - boundary.push(seam.clone()); - boundary.extend(top.inverse().edge_iter().cloned()); - boundary.push(seam.inverse()); - let wall = mt::Face::new_unchecked( - vec![boundary.into()], - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution( - seam.inverse().oriented_curve(), - p3(Vec3::ZERO), - v3(Vec3::Z), - ))), - ); - let lower = builder::try_attach_plane(&[bottom.inverse()]).unwrap(); - let upper = builder::try_attach_plane(&[top]).unwrap(); - Body::new(Solid::new_unchecked(vec![vec![wall, lower, upper].into()])).unwrap() + crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 20.0).unwrap() } #[test] @@ -68,11 +45,16 @@ fn periodic_step_seam_survives_identity_rotation_and_translation() { let imported = crate::step_import(&bytes).unwrap(); assert!(imported.warnings.is_empty(), "{:?}", imported.warnings); let body = &imported.bodies.first().unwrap().body; - assert!(body.solid.face_iter().any(|f| f.absolute_boundaries().iter().any(|w| !w.is_simple()))); - let source_vertices: Vec<_> = body.solid.vertex_iter().map(|v| from_p3(v.point())).collect(); - let source_faces = body.solid.face_iter().count(); + // A face whose loop uses an edge twice (the seam). + let seamed = body.record().faces.iter().any(|f| { + f.loops.iter().any(|l| match l { + solidcore_record::brep::Loop::Edges { edges } => edges.iter().any(|u| edges.iter().filter(|w| w.edge == u.edge).count() > 1), + solidcore_record::brep::Loop::Vertex { .. } => false, + }) + }); + assert!(seamed); let unchanged = crate::step_export(&[body], "source snapshot").unwrap(); - let before = body.tessellate_with(1e-3, true).unwrap().measure().volume; + let before = body.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume; assert!((before - 2000. * std::f64::consts::PI).abs() < 1.); for matrix in [ [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]], @@ -81,15 +63,35 @@ fn periodic_step_seam_survives_identity_rotation_and_translation() { ] { let moved = transform_matrix(body, matrix).unwrap(); assert_topology(body, &moved, matrix); - assert_eq!(moved.solid.face_iter().count(), source_faces); - assert_eq!(moved.solid.vertex_iter().count(), source_vertices.len()); - let after = moved.tessellate_with(1e-3, true).unwrap().measure().volume; + let after = moved.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume; assert!((after - before).abs() < 1e-5, "{after} vs {before}"); let roundtrip = crate::step_import(&crate::step_export(&[&moved], "placement regression").unwrap()).unwrap(); assert!(roundtrip.warnings.is_empty(), "{:?}", roundtrip.warnings); - assert!((roundtrip.bodies.first().unwrap().body.tessellate_with(1e-3, true).unwrap().measure().volume - before).abs() < 1e-4); + assert!((roundtrip.bodies.first().unwrap().body.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume - before).abs() < 1e-4); } let rigid = transform(body, Vec3::new(10., 10., 30.), Vec3::ZERO, Vec3::Z, std::f64::consts::FRAC_PI_2).unwrap(); assert_topology(body, &rigid, [[0., 1., 0., 0.], [-1., 0., 0., 0.], [0., 0., 1., 0.], [10., 10., 30., 1.]]); assert_eq!(crate::step_export(&[body], "source snapshot").unwrap(), unchanged); } + +/// A body mirrored in SMLib reads back from its record as the same valid solid: a plate with a +/// through hole (the hole's cylinder comes out inside out) and a box with two rounds meeting at a +/// corner (their intersection edge has a tolerance of its own, wider than the body's). Read back +/// from the record, the hole's cylinder swept the wrong way about its axis 30 mm off its NURBS, +/// and the rounds' shared edge lost its tolerance to the body's. +#[test] +fn mirrored_bodies_read_back_from_their_records_valid() { + let plate = crate::box_solid(Vec3::ZERO, Vec3::new(30., 40., 20.)).unwrap(); + let hole = crate::cylinder(Vec3::new(20., 20., -5.), Vec3::Z, 5.0, 30.0).unwrap(); + let holed = crate::boolean(&plate, &hole, crate::BoolOp::Cut).unwrap().unwrap(); + let rounded = crate::fillet(&plate, &[Vec3::new(15., 0., 20.), Vec3::new(0., 0., 10.)], 3.0).unwrap(); + // The mirror in x = 30. + let mirror = [[-1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [60., 0., 0., 1.]]; + for (what, body) in [("holed plate", holed), ("rounded box", rounded)] { + let mirrored = transform_matrix(&body, mirror).unwrap(); + let read_back = Body::from_record(mirrored.record().clone()).unwrap(); + assert!(matches!(crate::validity(&read_back).smlib, Some(crate::SmlibCheck::Valid)), "{what}: {:?}", crate::validity(&read_back).smlib); + let (want, got) = (crate::measure(&body).unwrap().volume, crate::measure(&read_back).unwrap().volume); + assert!((got - want).abs() < 1e-6 * want, "{what}: volume {got}, expected {want}"); + } +} diff --git a/crates/kernel/src/planar_faces.rs b/crates/kernel/src/planar_faces.rs deleted file mode 100644 index 17e1b3130..000000000 --- a/crates/kernel/src/planar_faces.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Flat faces that sit on B-spline surfaces become planes. -//! -//! A wall swept along a curve has a top and a bottom that are flat but are made of the same -//! B-spline surfaces as everything else the sweep makes. The coplanar handling of a boolean -//! (coincident faces pushed apart, faces glued back to back, the exact planar fallback) looks -//! for faces on true planes, so it never sees them: two such walls that share a top plane were -//! left to the general intersection, which fails on faces that coincide. - -use solidcraft_geom::Vec3; -use truck_modeling as mt; - -use crate::body::{Body, Solid, from_p3, p3}; -use crate::{KernelError, guard}; - -/// Most control points looked at in one surface. -const MAX_CONTROL_POINTS: usize = 1_000_000; - -/// The control points of a B-spline or NURBS surface, as points. -fn control_points(s: &mt::Surface) -> Option> { - match s { - mt::Surface::BSplineSurface(b) => { - let pts: Vec = b.control_points().iter().flatten().take(MAX_CONTROL_POINTS + 1).map(|p| from_p3(*p)).collect(); - (pts.len() <= MAX_CONTROL_POINTS).then_some(pts) - } - mt::Surface::NurbsSurface(n) => { - let mut pts = Vec::new(); - for v in n.control_points().iter().flatten() { - if !(v.w > 0.0) || pts.len() >= MAX_CONTROL_POINTS { - return None; - } - pts.push(Vec3::new(v.x / v.w, v.y / v.w, v.z / v.w)); - } - Some(pts) - } - _ => None, - } -} - -/// The least and the greatest `along · p` over the control points of a B-spline or NURBS surface; the surface lies -/// between them (it is in the convex hull of its control net). `None` for any other surface. -pub(crate) fn control_net_span(s: &mt::Surface, along: Vec3) -> Option<(f64, f64)> { - let pts = control_points(s)?; - pts.iter().map(|p| along.dot(*p)).fold(None, |acc, h| Some(acc.map_or((h, h), |(lo, hi): (f64, f64)| (lo.min(h), hi.max(h))))) -} - -/// A point and the unit normal of the plane every point lies within `tol` of, if there is one. -fn common_plane(pts: &[Vec3], tol: f64) -> Option<(Vec3, Vec3)> { - let p0 = *pts.first()?; - let far = |from: Vec3, pick: &dyn Fn(Vec3) -> f64| pts.iter().copied().max_by(|a, b| pick(*a - from).total_cmp(&pick(*b - from))); - let p1 = far(p0, &|d| d.len())?; - let dir = (p1 - p0).normalized()?; - let p2 = far(p0, &|d| (d - dir * d.dot(dir)).len())?; - let n = (p1 - p0).cross(p2 - p0).normalized()?; - pts.iter().all(|p| n.dot(*p - p0).abs() <= tol).then_some((p0, n)) -} - -/// `b` with every face that is flat on a B-spline surface put on a plane; `None` when there is -/// no such face. The faces keep their order, their edges and their orientation. -pub(crate) fn planarized(b: &Body) -> Option { - if b.is_mesh() { - return None; - } - let tol = (b.size() * 1e-9).max(1e-9); - guard("planar faces", || { - use mt::{ParametricSurface, ParametricSurface3D}; - let mut changed = 0usize; - let mut shells = Vec::new(); - for sh in b.solid.boundaries() { - let mut faces: Vec = Vec::new(); - for f in sh.face_iter() { - let surface = f.surface(); - let plane = control_points(&surface).and_then(|pts| common_plane(&pts, tol)); - let Some((origin, mut n)) = plane else { - faces.push(f.clone()); - continue; - }; - // The plane faces the way the surface does; a surface with no normal at any of the - // places looked at is left as it is. - let (ur, vr) = surface.try_range_tuple(); - let ((u0, u1), (v0, v1)) = (ur.unwrap_or((0.0, 1.0)), vr.unwrap_or((0.0, 1.0))); - let old = [(0.5, 0.5), (0.25, 0.25), (0.75, 0.75), (0.25, 0.75), (0.75, 0.25)] - .iter() - .map(|(s, t)| surface.normal(u0 + s * (u1 - u0), v0 + t * (v1 - v0))) - .find(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite() && v.x * v.x + v.y * v.y + v.z * v.z > 1e-18); - let Some(old) = old else { - faces.push(f.clone()); - continue; - }; - if n.dot(Vec3::new(old.x, old.y, old.z)) < 0.0 { - n = -n; - } - let u = n.any_perp().normalized().ok_or_else(|| KernelError::Failed("planar faces: no axis".into()))?; - let w = n.cross(u); - let plane = mt::Plane::new(p3(origin), p3(origin + u), p3(origin + w)); - let mut nf = - mt::Face::try_new(f.absolute_boundaries().to_vec(), mt::Surface::Plane(plane)).map_err(|e| KernelError::Failed(e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - faces.push(nf); - changed += 1; - } - shells.push(faces.into()); - } - if changed == 0 { - return Ok(None); - } - let solid = Solid::try_new(shells).map_err(|e| KernelError::Failed(e.to_string()))?; - Ok(Some(Body::new(solid)?)) - }) - .ok() - .flatten() -} diff --git a/crates/kernel/src/planar_faces_tests.rs b/crates/kernel/src/planar_faces_tests.rs index 1c6788f46..10bac4691 100644 --- a/crates/kernel/src/planar_faces_tests.rs +++ b/crates/kernel/src/planar_faces_tests.rs @@ -1,12 +1,11 @@ #![allow(clippy::unwrap_used, clippy::panic)] -//! A wall swept along a spiral has a flat top and bottom that are B-spline faces. They have to be -//! planes for the coplanar handling of a boolean to see them: a join of two such walls ran into -//! the general intersection with faces that coincide, and failed. With planes, the walls are prisms -//! and a join of two is decided in 2D (`prism.rs`). +//! A wall swept along a spiral has a flat top and bottom that are B-spline faces: a join of two +//! such walls, whose tops and bottoms coincide. -use std::f64::consts::{FRAC_PI_2, TAU}; +use solidcraft_geom::prelude::*; +use std::f64::consts::TAU; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use crate::*; @@ -46,43 +45,6 @@ fn two_walls(turn: f64, stations: usize) -> (Body, Body) { (spiral_wall(60.0, 0.0, turn, stations), spiral_wall(71.0, 0.26, turn, stations)) } -/// Faces that lie on a `Plane` surface (the face-type counts of `measure` also count flat splines). -fn plane_faces(b: &Body) -> usize { - b.solid.face_iter().filter(|f| matches!(f.surface(), truck_modeling::Surface::Plane(_))).count() -} - -fn volume(b: &Body) -> f64 { - b.tessellate_with(1e-3, true).unwrap().measure().volume -} - -#[test] -fn the_flat_faces_of_a_swept_wall_become_planes() { - let wall = spiral_wall(60.0, 0.0, FRAC_PI_2, 8); - // Two end caps are planes already; the top and bottom are flat B-splines like the two sides. - assert_eq!(plane_faces(&wall), 2); - let flat = crate::planar_faces::planarized(&wall).expect("the top and the bottom are flat"); - assert_eq!(plane_faces(&flat), 4); - assert_eq!(flat.face_count(), wall.face_count()); - assert!(flat.validity().is_empty(), "{:?}", flat.validity()); - let (before, after) = (volume(&wall), volume(&flat)); - assert!((before - after).abs() < 1e-3 * before, "{before} vs {after}"); - // Nothing flat is left to change, and a box has nothing to begin with. - assert!(crate::planar_faces::planarized(&flat).is_none()); - assert!(crate::planar_faces::planarized(&box_solid(Vec3::ZERO, Vec3::new(1.0, 2.0, 3.0)).unwrap()).is_none()); -} - -#[test] -fn walls_that_share_a_top_and_a_bottom_coincide_only_once_those_are_planes() { - let (a, b) = two_walls(FRAC_PI_2, 8); - assert!(crate::coplanar::coincident_planes(&a, &b).is_empty()); - let (pa, pb) = (crate::planar_faces::planarized(&a).unwrap(), crate::planar_faces::planarized(&b).unwrap()); - let planes = crate::coplanar::coincident_planes(&pa, &pb); - assert_eq!(planes.len(), 2, "{planes:?}"); - let mut heights: Vec = planes.iter().map(|(n, d, _)| d * n.z).collect(); - heights.sort_by(f64::total_cmp); - assert!(heights[0].abs() < 1e-6 && (heights[1] - HEIGHT).abs() < 1e-6, "{heights:?}"); -} - /// The plan area of the union of the walls (each given as `(radius, start)`), by sampling every /// 0.4 mm: a point is in a wall if it is within half its thickness of the wall's centreline and /// not beyond either end (flat ends). @@ -122,18 +84,16 @@ fn free_form_faces(b: &Body) -> usize { fn join_checked(a: &Body, b: &Body, walls: &[(f64, f64)], turn: f64) { let joined = boolean(a, b, BoolOp::Union).unwrap().unwrap(); - assert_eq!(joined.solid.boundaries().len(), 1); + assert_eq!(joined.shell_count(), 1); assert!(joined.validity().is_empty(), "{:?}", joined.validity()); // Decided in 2D: the walls come back as arcs, not as splines. assert_eq!(free_form_faces(&joined), 0); let want = HEIGHT * union_plan_area(walls, turn); - let got = joined.tessellate_with(1e-2, true).unwrap().measure().volume; + let got = joined.mesh(&crate::MeshTolerance::chord(1e-2)).unwrap().measure().volume; assert!((got - want).abs() < 5e-3 * want, "{got} vs {want}"); } -/// The general intersection fails on these two walls (`no result`: their tops and bottoms coincide, -/// and as B-splines the coincident-face handling does not see them). With flat faces made planes -/// they are prisms, and the join is decided in 2D, with the walls fitted by arcs within a micron. +/// Two walls whose tops and bottoms coincide: the join is one solid with the walls as arcs. #[test] fn a_join_of_swept_walls_is_decided_in_2d() { let turn = 0.6; @@ -155,12 +115,12 @@ fn interleaved_spiral_walls_join() { #[test] fn a_cut_of_an_extruded_spline_keeps_its_spline_wall() { let p = Vec2::new; - let line = |a: Vec2, b: Vec2| solidcraft_geom::Seg2::Line { a, b }; + let line = |a: Vec2, b: Vec2| solidcore_record::Seg2::Line { a, b }; let outline = Loop2 { segs: vec![ line(p(0.0, 0.0), p(40.0, 0.0)), line(p(40.0, 0.0), p(40.0, 20.0)), - solidcraft_geom::Seg2::Cubic { p0: p(40.0, 20.0), p1: p(30.0, 35.0), p2: p(10.0, 5.0), p3: p(0.0, 20.0) }, + solidcore_record::Seg2::Cubic { p0: p(40.0, 20.0), p1: p(30.0, 35.0), p2: p(10.0, 5.0), p3: p(0.0, 20.0) }, line(p(0.0, 20.0), p(0.0, 0.0)), ], }; diff --git a/crates/kernel/src/planar_regularize.rs b/crates/kernel/src/planar_regularize.rs index b899ff87f..09394b868 100644 --- a/crates/kernel/src/planar_regularize.rs +++ b/crates/kernel/src/planar_regularize.rs @@ -1,168 +1,33 @@ //! Exact topological removal of construction-induced planar subdivisions. -//! Shared edge identity and complete construction lineage select the groups. -use super::{Body, from_p3}; -use crate::history::FaceOrigin; -use crate::{Result, guard}; -use solidcraft_geom::Plane; -use std::collections::{BTreeMap, HashMap, HashSet}; +//! Shared edge identity and complete construction lineage select the edges; SMLib joins the +//! faces either side of them where they are topological (`solidcraft_smlib::Brep::merge_faces`, +//! every other edge kept by a point at its middle). +use super::Body; +use crate::{KernelError, Result, guard}; +use solidcore_record::Vec3; +use solidcore_record::brep::{self}; +use solidcraft_geom::brep::eval::CurveEval; use std::sync::Arc; -use truck_modeling as mt; -fn root(parent: &mut [usize], mut i: usize) -> usize { - while parent[i] != i { - parent[i] = parent[parent[i]]; - i = parent[i]; - } - i +/// Points along a record edge (ends and three inside). +fn edge_points(e: &brep::Edge) -> Vec { + let Ok(c) = CurveEval::new(e.parameters()) else { return Vec::new() }; + let [t0, t1] = e.interval; + (0..=4).filter_map(|k| c.point(t0 + (t1 - t0) * k as f64 / 4.0)).collect() } -fn merged_face(faces: &[&mt::Face], members: &[usize], plane: Plane, eligible: &HashSet) -> Option { - let mut counts = HashMap::::new(); - for i in members { - for edge in faces.get(*i)?.boundary_iters().into_iter().flatten() { - // Whole linear supports, not a sampled plane fit. - let mt::Curve::Line(line) = edge.curve() else { return None }; - let (a, b) = (from_p3(line.0), from_p3(line.1)); - if !a.is_finite() || !b.is_finite() || a.len().max(b.len()) > 1e9 { - return None; - } - let front = from_p3(edge.absolute_front().point()); - let back = from_p3(edge.absolute_back().point()); - if !front.is_finite() || !back.is_finite() { - return None; - } - let error = 4096. * f64::EPSILON * (1. + a.len() + b.len() + plane.origin.len()); - if plane.height(a).abs() > error || plane.height(b).abs() > error || a.dist(front) > error || b.dist(back) > error { - return None; - } - let count = counts.entry(edge.id()).or_insert((0, edge.orientation())); - if count.0 == 1 && (!eligible.contains(&edge.id()) || count.1 == edge.orientation()) { - return None; - } - count.0 += 1; - if count.0 > 2 { - return None; - } - } - } - let mut boundary = Vec::new(); - for i in members { - for edge in faces.get(*i)?.boundary_iters().into_iter().flatten() { - if counts.get(&edge.id()).is_some_and(|(n, _)| *n == 1) { - boundary.push(edge); - } - } - } - let mut next = HashMap::new(); - let mut incoming = HashMap::new(); - for (i, edge) in boundary.iter().enumerate() { - if next.insert(edge.front().id(), i).is_some() || incoming.insert(edge.back().id(), i).is_some() { - return None; - } - } - if next.len() != incoming.len() || next.keys().any(|id| !incoming.contains_key(id)) { - return None; - } - let mut used = vec![false; boundary.len()]; - let mut outer = None; - let mut holes = Vec::new(); - for first in 0..boundary.len() { - if used[first] { - continue; - } - let start = boundary.get(first)?.front().id(); - let origin = from_p3(boundary.get(first)?.front().point()); - let mut index = first; - let mut edges = Vec::new(); - let (mut area, mut magnitude, mut arithmetic_error) = (0., 0., 0.); - loop { - if *used.get(index)? { - return None; - } - used[index] = true; - let edge = boundary.get(index)?.clone(); - let da = from_p3(edge.front().point()) - origin; - let db = from_p3(edge.back().point()) - origin; - let a = solidcraft_geom::Vec2::new(da.dot(plane.x), da.dot(plane.y)); - let b = solidcraft_geom::Vec2::new(db.dot(plane.x), db.dot(plane.y)); - let term = a.cross(b); - area += term; - magnitude += term.abs(); - let coordinate_error = - 128. * f64::EPSILON * (1. + origin.len() + from_p3(edge.front().point()).len() + from_p3(edge.back().point()).len()); - arithmetic_error += coordinate_error * (da.len() + db.len() + coordinate_error) * 16.; - let back = edge.back().id(); - edges.push(edge); - if back == start { - break; - } - index = *next.get(&back)?; - } - if edges.len() < 3 || !area.is_finite() || area.abs() <= arithmetic_error + 64. * f64::EPSILON * (edges.len() as f64 + 1.) * magnitude.max(1.) - { - return None; - } - let wire = mt::Wire::from(edges); - if area > 0. { - if outer.replace(wire).is_some() { - return None; - } - } else { - holes.push(wire); - } - } - let mut wires = vec![outer?]; - wires.extend(holes); - mt::Face::try_new(wires, faces.get(*members.first()?)?.oriented_surface()).ok() +/// The point halfway along a record edge's interval. +fn edge_middle(e: &brep::Edge) -> Option { + let [t0, t1] = e.interval; + CurveEval::new(e.parameters()).ok()?.point(0.5 * (t0 + t1)) } -/// `body` with its history: `input`'s faces with each output face made of the input faces -/// `members` lists for it (every edge of `body` one of `input`'s, by identity), composed with -/// the history of the operation that made `input`; none where `input` has none. -fn with_joined_history(body: Body, input: &Body, members: Vec>) -> Body { - let Some(inner) = input.history() else { return body }; - let faces = members.into_iter().map(|m| (m.iter().map(|&face| FaceOrigin::Face { operand: 0, face }).collect(), m.len() == 1)).collect(); - let joined = crate::record::traced( - body, - &crate::record::counts(&[input]), - Some(crate::record::regions(faces)), - Some(&crate::record::edge_origins(&input.solid, 0)), - ); - // Both steps are checked (`traced` against `input`, `through` composing over its checked - // history); the composed operands' counts are not known here, so it is set in place. - let history = crate::boolean_record::through(&joined, 0, Some(inner)); - Body { history: history.map(Arc::new), ..joined } +fn failed(e: impl crate::Cause) -> KernelError { + KernelError::smlib("SMLib planar regularization", e) } impl Body { pub(crate) fn regularize_certified_planar_faces(self) -> Result { - self.regularize_planar_faces(false) - } - - /// Only newly produced Cut walls call this path. The temporary planes carry - /// construction support, never persistent ancestor/source-role authority. - pub(crate) fn regularize_generated_planar_faces(self) -> Result { - let body = self.regularize_planar_faces(true)?; - let sources = body.face_sources().map(|sources| { - sources - .iter() - .map(|source| { - let mut source = source.clone(); - if let Some(super::FaceSource::ExtrudeSide { plane, coalesced, .. }) = &mut source { - if plane.is_some() && !*coalesced { - source = None; - } else { - *plane = None; - } - } - source - }) - .collect() - }); - Ok(body.with_face_sources(sources.map(Arc::new))) - } - - fn regularize_planar_faces(self, generated: bool) -> Result { if self.regularization_protected { return Ok(self); } @@ -173,63 +38,47 @@ impl Body { let split_points = self.split_keep().iter().try_fold(0usize, |sum, line| sum.checked_add(line.len())); let Some(split_points) = split_points.filter(|n| *n <= 65_536) else { return Ok(self) }; let result = guard("certified planar topology regularization", || { - let mut faces = Vec::new(); - let mut shell_owner = Vec::new(); - let mut use_budget = 65_536usize; - for (shell_index, shell) in self.solid.boundaries().iter().enumerate() { - for face in shell.face_iter() { - if faces.len() >= sources.len() { - return Ok(None); - } - for _ in face.edge_iter() { - let Some(left) = use_budget.checked_sub(1) else { return Ok(None) }; - use_budget = left; - } - faces.push(face); - shell_owner.push(shell_index); - } - } - if faces.len() != sources.len() { + if self.face_count() != sources.len() { return Ok(None); } - let valid: Vec<_> = faces + let actual = super::planar_sources::actual_planes(&self)?; + let at = super::planar_sources::Resolution::of(&self); + let valid: Vec<_> = actual .iter() .zip(sources) - .map(|(f, s)| { + .map(|(actual, s)| { s.as_ref() - .and_then(|source| { - if generated { - match source { - super::FaceSource::ExtrudeSide { segment: solidcraft_geom::Seg2::Line { .. }, plane: Some(p), .. } => Some(*p), - _ => None, - } - } else { - super::planar_sources::certified_plane(source) - } - }) - .filter(|p| super::planar_sources::actual_plane(f).is_some_and(|actual| super::planar_sources::same_support(p, &actual))) + .and_then(super::planar_sources::certified_plane) + .filter(|p| actual.is_some_and(|actual| super::planar_sources::same_support(p, &actual, at))) }) .collect(); - let mut adjacency = HashMap::>::new(); - for (i, face) in faces.iter().enumerate() { - for edge in face.boundary_iters().into_iter().flatten() { - adjacency.entry(edge.id()).or_default().push((i, edge)); + let record = self.record(); + let mut shell_of = vec![usize::MAX; record.faces.len()]; + for (k, shell) in record.shells.iter().enumerate() { + if let brep::Shell::Faces { faces, .. } = shell { + for o in faces { + if let Some(slot) = shell_of.get_mut(o.face as usize) { + *slot = k; + } + } } } - let mut eligible = HashSet::new(); - let mut parent: Vec<_> = (0..faces.len()).collect(); + // The edges between two faces of one shell on one certified plane, from one source, + // off every authored split line. + let mut eligible = Vec::new(); let mut identity = 16_000_000usize; let mut work = 2_000_000usize; - for uses in adjacency.values() { - let [(a, ea), (b, eb)] = uses.as_slice() else { continue }; - if a == b || shell_owner[*a] != shell_owner[*b] || ea.orientation() == eb.orientation() { + for (k, e) in record.edges.iter().enumerate() { + let [ua, ub] = e.uses.as_slice() else { continue }; + let (a, b) = (ua.face as usize, ub.face as usize); + if a == b || shell_of.get(a) != shell_of.get(b) { continue; } - let (Some(pa), Some(pb)) = (valid[*a], valid[*b]) else { continue }; + let (Some(Some(pa)), Some(Some(pb))) = (valid.get(a), valid.get(b)) else { continue }; if pa != pb { continue; } - let (Some(sa), Some(sb)) = (sources[*a].as_ref(), sources[*b].as_ref()) else { continue }; + let (Some(Some(sa)), Some(Some(sb))) = (sources.get(a), sources.get(b)) else { continue }; let Some(cost) = super::planar_sources::descriptor_cost(sa) .and_then(|a| super::planar_sources::descriptor_cost(sb).and_then(|b| a.checked_add(b))) else { @@ -237,118 +86,70 @@ impl Body { }; let Some(left) = identity.checked_sub(cost) else { return Ok(None) }; identity = left; - if !generated && sa != sb { + if sa != sb { continue; } let Some(cost) = split_points.checked_mul(6).and_then(|n| n.checked_add(1)) else { return Ok(None) }; let Some(left) = work.checked_sub(cost) else { return Ok(None) }; work = left; - if crate::heal::on_split_line(&crate::heal::edge_points(ea), self.split_keep()) { + if crate::heal::on_split_line(&edge_points(e), self.split_keep()) { continue; } - eligible.insert(ea.id()); - let (ra, rb) = (root(&mut parent, *a), root(&mut parent, *b)); - parent[ra.max(rb)] = ra.min(rb); + eligible.push(k); } - let mut groups = BTreeMap::>::new(); - for i in 0..faces.len() { - groups.entry(root(&mut parent, i)).or_default().push(i); + if eligible.is_empty() { + return Ok(None); } - let mut replacements = HashMap::new(); - let mut changed = false; + // SMLib removes the topological edges and vertices but those under the points kept: + // every edge not chosen (at its middle) stays. + let keep: Vec<[f64; 3]> = record + .edges + .iter() + .enumerate() + .filter(|(k, _)| eligible.binary_search(k).is_err()) + .map(|(_, e)| edge_middle(e).map(|p| [p.x, p.y, p.z])) + .collect::>() + .ok_or_else(|| failed("an edge of the body has no middle point"))?; + if keep.len() > solidcraft_smlib::MAX_POINTS { + return Ok(None); + } + let (sb, ob) = crate::native::smlib_body_ordered(&self)?; + let ob = ob.ok_or_else(|| failed("SMLib numbers the body's edges unlike its record"))?; + let r = sb.tagged(0).map_err(failed)?.merge_faces(&keep, (self.size() * 1e-6).max(1e-9)).map_err(failed)?; + if r.counts().map_err(failed)?.first() == Some(&self.face_count()) { + return Ok(None); + } + let check = r.check(solidcraft_smlib::CheckLevel::All).map_err(failed)?; + if !check.is_valid() { + return Err(failed(format!("SMLib's check refuses the result: {check}"))); + } + let (body, or) = crate::native::body_from_smlib_ordered(&r)?; + let or = or.ok_or_else(|| failed("the result's record is numbered unlike SMLib's body"))?; + let h = r.history().map_err(failed)?.history(std::slice::from_ref(&ob), &or).map_err(failed)?; + // Each face keeps the source of the first face it is made of. let mut metadata = 2_000_000usize; - for (leader, members) in &groups { - if members.len() < 2 { - continue; + let mut output = Vec::with_capacity(h.faces.len()); + for f in &h.faces { + let members: Vec = + f.origins.iter().filter_map(|o| if let crate::history::FaceOrigin::Face { face, .. } = o { Some(*face) } else { None }).collect(); + let source = members.iter().min().and_then(|m| sources.get(*m)).cloned().flatten(); + if let Some(s) = &source { + let Some(cost) = super::planar_sources::descriptor_cost(s) else { return Ok(None) }; + let Some(left) = metadata.checked_sub(cost) else { return Ok(None) }; + metadata = left; } - let Some(face) = valid[*leader].and_then(|p| merged_face(&faces, members, p, &eligible)) else { continue }; - replacements.insert(*leader, face); - changed = true; + output.push(source); } - if !changed { - return Ok(None); - } - let mut shells = Vec::new(); - let mut output_sources = Vec::new(); - let mut output_ids = Vec::new(); - // The input faces each output face is made of, for its history. - let mut output_members: Vec> = Vec::new(); - let mut offset = 0; - for shell in self.solid.boundaries() { - let mut output = Vec::new(); - for face in shell.face_iter() { - let leader = root(&mut parent, offset); - if let Some(merged) = replacements.get(&leader) { - if offset == leader { - output.push(merged.clone()); - let Some(members) = groups.remove(&leader) else { return Ok(None) }; - output_members.push(members); - } else { - offset += 1; - continue; - } - } else { - output.push(face.clone()); - output_members.push(vec![offset]); - } - output_ids.push(output.last().ok_or_else(|| crate::KernelError::Failed("missing regularized face".into()))?.id()); - let source = sources[offset].as_ref(); - if let Some(source) = source { - let Some(cost) = super::planar_sources::descriptor_cost(source) else { return Ok(None) }; - let Some(left) = metadata.checked_sub(cost) else { return Ok(None) }; - metadata = left; - } - let mut source = source.cloned(); - if generated - && replacements.contains_key(&leader) - && let Some(super::FaceSource::ExtrudeSide { coalesced, .. }) = &mut source - { - *coalesced = true; - } - output_sources.push(source); - offset += 1; - } - shells.push(mt::Shell::from(output)); - } - let solid = mt::Solid::try_new(shells).map_err(|e| crate::KernelError::Failed(format!("planar regularization does not close: {e}")))?; - let body = Body::new(solid)?.with_color(self.color()).with_paint(self.paint().cloned()).with_split_lines(self.split_lines().cloned()); - if !body.solid.face_iter().map(|f| f.id()).eq(output_ids) { - return Ok(None); - } - Ok(Some(with_joined_history(body.with_face_sources(Some(Arc::new(output_sources))), &self, output_members))) + let body = body + .with_color(self.color()) + .with_paint(self.paint().cloned()) + .with_split_lines(self.split_lines().cloned()) + .with_face_sources(Some(Arc::new(output))) + .with_checked_history(Some(h), &crate::record::counts(&[&self])); + // Over the operands of the operation that made `self`, as `self`'s history is. + let history = crate::boolean_record::through(&body, 0, self.history()); + Ok(Some(Body { history: history.map(Arc::new), ..body })) })?; Ok(result.unwrap_or(self)) } } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn alternate_adjacency_path_cannot_remove_protected_internal_edge() { - let vertices: Vec<_> = - (0..9).map(|i| mt::builder::vertex(super::super::p3(solidcraft_geom::Vec3::new((i % 3) as f64, (i / 3) as f64, 0.)))).collect(); - let mut edges = HashMap::<(usize, usize), mt::Edge>::new(); - let mut faces = Vec::new(); - for (x, y) in [(0, 0), (1, 0), (0, 1), (1, 1)] { - let ids = [y * 3 + x, y * 3 + x + 1, (y + 1) * 3 + x + 1, (y + 1) * 3 + x]; - let wire: mt::Wire = (0..4) - .map(|i| { - let (a, b) = (ids[i], ids[(i + 1) % 4]); - let key = (a.min(b), a.max(b)); - let edge = edges.entry(key).or_insert_with(|| mt::builder::line(&vertices[key.0], &vertices[key.1])); - if a == key.0 { edge.clone() } else { edge.inverse() } - }) - .collect(); - faces.push(mt::builder::try_attach_plane(&[wire]).unwrap()); - } - let refs: Vec<_> = faces.iter().collect(); - let mut eligible: HashSet<_> = edges.values().map(|e| e.id()).collect(); - assert!(merged_face(&refs, &[0, 1, 2, 3], Plane::XY, &eligible).is_some()); - eligible.remove(&edges[&(1, 4)].id()); - assert!( - merged_face(&refs, &[0, 1, 2, 3], Plane::XY, &eligible).is_none(), - "remaining three internal joins cannot bypass authored split protection" - ); - } -} diff --git a/crates/kernel/src/planar_sources.rs b/crates/kernel/src/planar_sources.rs index 8637b2726..c9e28198b 100644 --- a/crates/kernel/src/planar_sources.rs +++ b/crates/kernel/src/planar_sources.rs @@ -1,40 +1,288 @@ //! Exact oriented planar support lineage through a trim and an inside shell. //! No tessellated face names, centroids, or nearest-plane choices are used. -use super::{Body, FaceSource, from_p3}; +use super::{Body, FaceSource}; use crate::{KernelError, Result, guard}; -use solidcraft_geom::{Plane, Vec3}; +use solidcore_record::brep::{self, Surface}; +use solidcore_record::{Plane, Vec3}; +use solidcraft_geom::prelude::*; +use std::collections::HashMap; use std::sync::Arc; -use truck_modeling as mt; -pub(super) fn actual_plane(face: &mt::Face) -> Option { - let mt::Surface::Plane(p) = face.oriented_surface() else { return None }; - let u = p.u_axis(); - let v = p.v_axis(); - let u = Vec3::new(u.x, u.y, u.z); - let v = Vec3::new(v.x, v.y, v.z); - if !u.is_finite() || !v.is_finite() || u.cross(v).len() <= u.len() * v.len() * 1e-8 { - return None; +/// The oriented plane each face of `body` lies on (in face order), from its record: the +/// surface's plane, its normal turned with the face; none for a face on any other surface. +pub(super) fn actual_planes(body: &Body) -> Result>> { + let record = body.record(); + let mut forward = vec![true; record.faces.len()]; + for shell in &record.shells { + if let brep::Shell::Faces { faces, .. } = shell { + for o in faces { + if let Some(f) = forward.get_mut(o.face as usize) { + *f = o.forward; + } + } + } } - Plane::new(from_p3(p.origin()), u, v) + let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]); + Ok(record + .faces + .iter() + .zip(forward) + .map(|(face, forward)| { + let (o, u, w) = match face.surface { + Surface::Plane { origin, u_axis, v_axis } => (v(origin), v(u_axis), v(v_axis)), + Surface::PlaneThrough { origin, u_point, v_point } => (v(origin), v(u_point) - v(origin), v(v_point) - v(origin)), + _ => return None, + }; + if !o.is_finite() || !u.is_finite() || !w.is_finite() || u.cross(w).len() <= u.len() * w.len() * 1e-8 { + return None; + } + // A reversed face faces against its surface's normal. + if forward { Plane::new(o, u, w) } else { Plane::new(o, w, u) } + }) + .collect()) } -/// How far apart the normals' x components of two planes `same_support` accepts can be, with -/// room to spare: their unit normals are within about 1e-12 of each other. -const NORMAL_WINDOW: f64 = 1e-9; - -/// The entries of `sorted` (ordered by their plane's normal x) whose normal x is within -/// [`NORMAL_WINDOW`] of `nx`: the only ones `same_support` can accept for a plane with that normal. -fn normal_window(sorted: &[T], plane: impl Fn(&T) -> &Plane, nx: f64) -> &[T] { - let first = sorted.partition_point(|t| plane(t).normal().x < nx - NORMAL_WINDOW); - let last = sorted.partition_point(|t| plane(t).normal().x <= nx + NORMAL_WINDOW); - sorted.get(first..last.max(first)).unwrap_or_default() +/// The resolution two planar supports are compared at: SMLib's own, by which it calls two planes +/// coincident (SmPlane::CoincidenceCheck): a distance within the body's intersection tolerance +/// (the record's `tolerance`, SMLib's XSectTol3d) and normals within the angle that tolerance +/// makes across the body (`tolerance / size`; SMLib takes the plane's own extent, the body's is +/// at least as large, so this is no looser), never finer than rounding. Faces SMLib rebuilt +/// through a boolean lie within it of the plane they were made on (a cut cap at z = 10 came back +/// 2.1e-11 off and 1.4e-12 rad turned), not within a few ulps of it. +#[derive(Clone, Copy, Debug)] +pub(super) struct Resolution { + linear: f64, + angular: f64, } -pub(super) fn same_support(a: &Plane, b: &Plane) -> bool { - let error = 4096. * f64::EPSILON * (1. + a.origin.len() + b.origin.len()); - a.normal().cross(b.normal()).len() <= 4096. * f64::EPSILON - && a.normal().dot(b.normal()) > 0. - && (a.origin - b.origin).dot(a.normal()).abs() <= error +impl Resolution { + pub(super) fn of(body: &Body) -> Self { + let tolerance = body.record().tolerance; + let size = body.size(); + let rounding = 4096. * f64::EPSILON; + let linear = if tolerance.is_finite() && tolerance > 0. { tolerance } else { 0. }; + let angular = if size.is_finite() && size > 0. { linear / size } else { 0. }; + Resolution { linear: linear.max(rounding * (1. + size.max(0.))), angular: angular.max(rounding) } + } +} + +/// The planes of a list indexed by their unit normal and their offset, so the planes that can be +/// one support with a given plane at a resolution (`same_support`) are found without looking at +/// the rest: a superset of them, which the caller decides on exactly with `same_support`. +/// +/// Two unit normals within the resolution's angle (`|na × nb| <= angular`, `na · nb > 0`) differ +/// by at most their angle, `asin(angular) <= π/2 · angular < 2 · angular`: the normal cells are +/// twice that wide and a plane looks in its own cell and the neighbour on each side it is near. +/// Their offsets from a common centre `c`, `d = (o - c) · n`, satisfy +/// `d_b - d_a = (b.o - a.o) · n_b + (a.o - c) · (n_b - n_a)`, so a match is within +/// `linear + |a.o - c| · |n_b - n_a|` of the plane's own offset; each cell is sorted by offset and +/// searched in that window, widened by far more than the rounding of the offsets. A plane whose +/// normal is not of unit length (a hostile record) is kept aside and offered to every query. +struct PlaneIndex { + cells: HashMap<[i64; 3], Vec<(f64, usize)>>, + /// Entries whose normal is not unit to `UNIT`: offered to every query. + loose: Vec, + len: usize, + centre: Vec3, + /// The farthest origin of an indexed plane from `centre`. + reach: f64, + /// The bound on two matching normals' difference; the cells are `2 * normal_reach` wide. + normal_reach: f64, + linear: f64, +} + +/// How far from unit length a normal may be for the index's bounds to hold. +const UNIT: f64 = 1e-9; + +impl PlaneIndex { + fn new<'a>(planes: impl Iterator + Clone, at: Resolution) -> Self { + let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); + let mut hi = -lo; + for p in planes.clone().filter(|p| p.origin.is_finite()) { + lo = Vec3::new(lo.x.min(p.origin.x), lo.y.min(p.origin.y), lo.z.min(p.origin.z)); + hi = Vec3::new(hi.x.max(p.origin.x), hi.y.max(p.origin.y), hi.z.max(p.origin.z)); + } + let centre = if lo.is_finite() && hi.is_finite() { (lo + hi) * 0.5 } else { Vec3::ZERO }; + let normal_reach = 2. * at.angular + 4. * UNIT; + let mut index = PlaneIndex { cells: HashMap::new(), loose: Vec::new(), len: 0, centre, reach: 0., normal_reach, linear: at.linear }; + for (position, plane) in planes.enumerate() { + index.len += 1; + let n = plane.normal(); + let d = (plane.origin - centre).dot(n); + match index.cell(n) { + Some(key) if (n.len() - 1.).abs() <= UNIT && d.is_finite() => { + index.reach = index.reach.max((plane.origin - centre).len()); + index.cells.entry(key).or_default().push((d, position)); + } + _ => index.loose.push(position), + } + } + for cell in index.cells.values_mut() { + cell.sort_by(|a, b| a.0.total_cmp(&b.0)); + } + index + } + + fn cell(&self, n: Vec3) -> Option<[i64; 3]> { + let width = 2. * self.normal_reach; + let key = |v: f64| { + let k = (v / width).floor(); + (k.is_finite() && k.abs() < 1e15).then_some(k as i64) + }; + Some([key(n.x)?, key(n.y)?, key(n.z)?]) + } + + /// The positions of the indexed planes that can be one support with `plane`, in no order: + /// every one `same_support` accepts, and others it refuses. + fn near(&self, plane: &Plane) -> Vec { + let n = plane.normal(); + let offset = (plane.origin - self.centre).dot(n); + let from_centre = (plane.origin - self.centre).len(); + let (Some(low), Some(high)) = + (self.cell(n - Vec3::new(1., 1., 1.) * self.normal_reach), self.cell(n + Vec3::new(1., 1., 1.) * self.normal_reach)) + else { + return (0..self.len).collect(); + }; + if (n.len() - 1.).abs() > UNIT || !offset.is_finite() || !from_centre.is_finite() { + return (0..self.len).collect(); + } + let window = self.linear + from_centre * self.normal_reach + 1e-12 * (1. + from_centre + self.reach); + let mut out = self.loose.clone(); + for x in low[0]..=high[0] { + for y in low[1]..=high[1] { + for z in low[2]..=high[2] { + let Some(cell) = self.cells.get(&[x, y, z]) else { continue }; + let first = cell.partition_point(|e| e.0 < offset - window); + let last = cell.partition_point(|e| e.0 <= offset + window); + out.extend(cell.get(first..last.max(first)).unwrap_or_default().iter().map(|e| e.1)); + } + } + } + out + } +} + +/// Whether `a` and `b` are one oriented plane at resolution `at`: normals the same way within its +/// angle, each origin within its distance of the other plane. +pub(super) fn same_support(a: &Plane, b: &Plane, at: Resolution) -> bool { + let (na, nb) = (a.normal(), b.normal()); + na.cross(nb).len() <= at.angular + && na.dot(nb) > 0. + && (b.origin - a.origin).dot(na).abs() <= at.linear + && (a.origin - b.origin).dot(nb).abs() <= at.linear +} + +/// A source a face on its plane can take: the plane it names (for a shell's inner role, the +/// source's plane moved in and turned round), the source, and whether it is that inner role. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Candidate<'a> { + plane: Plane, + source: &'a FaceSource, + inner: bool, +} + +/// What a mapping's inputs say of one plane of its result. +#[derive(Debug, PartialEq)] +enum Support<'a> { + /// A face without a role, or a competing tool face, lies on the plane. + Blocked, + /// Every candidate on the plane is one source, plane and role: the pieces of one logical face. + Source(Candidate<'a>), + /// No candidate lies on the plane, or candidates of distinct identities do. + Unnamed, +} + +/// Planes partitioned into supports, in their order: a plane starts a group unless it is one +/// support (`same_support`) with the first plane of an earlier group, which it then joins. Returns +/// each plane's group and each group's first plane; `looked` counts the planes looked at. +fn group_supports(planes: &[Plane], at: Resolution, looked: &mut usize) -> (Vec, Vec) { + let index = PlaneIndex::new(planes.iter(), at); + let mut group: Vec> = vec![None; planes.len()]; + let mut first = Vec::new(); + for (i, plane) in planes.iter().enumerate() { + if group.get(i).is_some_and(Option::is_some) { + continue; + } + let g = first.len(); + first.push(i); + let near = index.near(plane); + *looked += near.len(); + for j in near { + if let Some(slot @ None) = group.get_mut(j) + && (j == i || planes.get(j).is_some_and(|other| same_support(plane, other, at))) + { + *slot = Some(g); + } + } + } + (group.into_iter().map(|g| g.unwrap_or(usize::MAX)).collect(), first) +} + +/// The candidates and blocking planes of a mapping grouped by support once, so each result face +/// looks up its plane's few groups instead of every candidate on that plane: with many coplanar +/// faces the work grows with the faces plus the candidates, not with their product. +struct SupportDecisions<'a> { + /// Each candidate group's first plane, and its decision: its first candidate, or none when + /// the group holds candidates of distinct identities. + groups: Vec<(Plane, Option>)>, + group_index: PlaneIndex, + /// The first plane of each group of the faces without a role and the competing tool faces. + blocking: Vec, + blocking_index: PlaneIndex, + at: Resolution, + /// The planes looked at, building the groups and deciding faces. + looked: usize, +} + +impl<'a> SupportDecisions<'a> { + /// `candidates` in the order that decides between them. + fn new(candidates: &[Candidate<'a>], unknown: &[Plane], competing: &[Plane], at: Resolution) -> Self { + let mut looked = 0; + let planes: Vec = candidates.iter().map(|c| c.plane).collect(); + let (group, first) = group_supports(&planes, at, &mut looked); + let mut groups: Vec<(Plane, Option>)> = first.iter().filter_map(|&i| candidates.get(i)).map(|c| (c.plane, Some(*c))).collect(); + for (candidate, g) in candidates.iter().zip(&group) { + if let Some((_, decision)) = groups.get_mut(*g) + && decision.is_some_and(|d| d != *candidate) + { + *decision = None; + } + } + let group_index = PlaneIndex::new(groups.iter().map(|g| &g.0), at); + let all_blocking: Vec = unknown.iter().chain(competing).copied().collect(); + let (_, first) = group_supports(&all_blocking, at, &mut looked); + let blocking: Vec = first.iter().filter_map(|&i| all_blocking.get(i).copied()).collect(); + let blocking_index = PlaneIndex::new(blocking.iter(), at); + SupportDecisions { groups, group_index, blocking, blocking_index, at, looked } + } + + /// What the inputs say of a face on `actual`. + fn at(&mut self, actual: &Plane) -> Support<'a> { + let at = self.at; + let near = self.blocking_index.near(actual); + self.looked += near.len(); + if near.into_iter().any(|i| self.blocking.get(i).is_some_and(|plane| same_support(plane, actual, at))) { + return Support::Blocked; + } + let mut near = self.group_index.near(actual); + self.looked += near.len(); + // Groups are numbered in the candidates' order, so the first matching group's first + // candidate is the first candidate on the plane. + near.sort_unstable(); + let mut chosen: Option> = None; + for (plane, decision) in near.into_iter().filter_map(|g| self.groups.get(g)) { + if !same_support(plane, actual, at) { + continue; + } + match (chosen, decision) { + (_, None) => return Support::Unnamed, + (None, Some(d)) => chosen = Some(*d), + (Some(c), Some(d)) if c != *d => return Support::Unnamed, + _ => {} + } + } + chosen.map_or(Support::Unnamed, Support::Source) + } } fn base_plane(source: &FaceSource, actual: &Plane) -> Option { @@ -135,15 +383,15 @@ impl Body { self_.map_planar_sources(&[input], None, Some(tool), &[], constructed) } - /// Retain exact construction and shell roles through a Union from both operands, only on - /// unchanged supports. Coplanar supports of the two operands carry distinct identities, so - /// a face merged from both stays without a role. - pub(crate) fn with_preserved_union_planar_sources(self, a: &Body, b: &Body) -> Result { - let self_ = self.inherit_regularization_protection(a).inherit_regularization_protection(b); - if ![a, b].iter().any(|input| input.face_sources().is_some_and(|sources| sources.iter().flatten().any(|s| boolean_source(s, true)))) { + /// Retain exact construction and shell roles through a Union from every operand, only on + /// unchanged supports. Coplanar supports of different operands carry distinct identities, so + /// a face merged from several stays without a role. + pub(crate) fn with_preserved_union_planar_sources(self, operands: &[&Body]) -> Result { + let self_ = operands.iter().fold(self, |body, operand| body.inherit_regularization_protection(operand)); + if !operands.iter().any(|input| input.face_sources().is_some_and(|sources| sources.iter().flatten().any(|s| boolean_source(s, true)))) { return Ok(self_); } - self_.map_planar_sources(&[a, b], None, None, &[], true) + self_.map_planar_sources(operands, None, None, &[], true) } fn map_planar_sources(mut self, inputs: &[&Body], shell: Option, blocker: Option<&Body>, open: &[Vec3], constructed: bool) -> Result { @@ -156,14 +404,7 @@ impl Body { if inputs.iter().all(|input| input.face_sources().is_none()) { return Ok(self); } - if inputs.len() > 2 - || inputs.iter().any(|input| input.solid.face_iter().count() > 16_384) - || self.solid.face_iter().count() > 16_384 - || blocker.is_some_and(|b| b.solid.face_iter().count() > 16_384) - { - return Err(KernelError::Invalid("planar source face budget exceeded".into())); - } - if inputs.iter().any(|input| input.face_sources().is_some_and(|sources| sources.len() != input.solid.face_iter().count())) { + if inputs.iter().any(|input| input.face_sources().is_some_and(|sources| sources.len() != input.face_count())) { return Err(KernelError::Invalid("planar source alignment mismatch".into())); } if shell.is_some_and(|t| !t.is_finite() || t <= 0.) { @@ -172,23 +413,29 @@ impl Body { if open.len() > 256 { return Ok(self); } + let at = Resolution::of(&self); let opening_tolerance = if shell.is_some() { inputs.iter().map(|input| input.size()).fold(0., f64::max) * 1e-4 + 1e-6 } else { 0. }; let mapped = guard("exact planar support lineage", || { let mut competing = Vec::new(); - for plane in blocker.into_iter().flat_map(|b| b.solid.face_iter()).filter_map(actual_plane) { - // A tool face blocks a face on its plane facing either way. + for plane in blocker.map(actual_planes).transpose()?.into_iter().flatten().flatten() { + // A cut's tool face enters the result turned round (the wall of the hollow it + // leaves), so it competes only with a face on its plane facing against it: a + // pocket's floor, or a target face the tool sat on from outside. A tool face that + // faces the same way as the target's face on its plane (a pocket cut down from a + // cap, its top on the cap) is the tool's own outside and leaves the cap the cap. let opposing = Plane::new(plane.origin, plane.x, -plane.y).ok_or_else(|| KernelError::Invalid("invalid opposing plane".into()))?; - competing.extend([plane, opposing]); + competing.push(opposing); } - competing.sort_by(|a, b| a.normal().x.total_cmp(&b.normal().x)); let mut candidates = Vec::new(); let mut unknown_supports = Vec::new(); - let faces = inputs.iter().flat_map(|input| { + let mut faces = Vec::new(); + for input in inputs { let sources = input.face_sources().unwrap_or_default(); - input.solid.face_iter().enumerate().map(move |(index, face)| (face, sources.get(index).and_then(Option::as_ref))) - }); - for (face, source) in faces { - let Some(actual) = actual_plane(face) else { continue }; + faces + .extend(actual_planes(input)?.into_iter().enumerate().map(|(index, plane)| (plane, sources.get(index).and_then(Option::as_ref)))); + } + for (actual, source) in faces { + let Some(actual) = actual else { continue }; let Some(source) = source else { unknown_supports.push(actual); continue; @@ -201,112 +448,44 @@ impl Body { unknown_supports.push(actual); continue; }; - if !same_support(&plane, &actual) || (shell.is_some() && open.iter().any(|p| actual.height(*p).abs() <= opening_tolerance)) { + if !same_support(&plane, &actual, at) || (shell.is_some() && open.iter().any(|p| actual.height(*p).abs() <= opening_tolerance)) { unknown_supports.push(actual); continue; } - let Some(cost) = descriptor_cost(source) else { + if descriptor_cost(source).is_none() { unknown_supports.push(actual); continue; - }; - candidates.push((plane, source, false, cost)); + } + candidates.push(Candidate { plane, source, inner: false }); if let Some(t) = shell { let inner = Plane::new(plane.origin - plane.normal() * t, plane.x, -plane.y) .ok_or_else(|| KernelError::Invalid("invalid shell inner source plane".into()))?; - candidates.push((inner, source, true, cost)); + candidates.push(Candidate { plane: inner, source, inner: true }); } } - // Planes that match must have (nearly) the same unit normal (`same_support`), so the - // lists are sorted by the normal's x and each face looks only at its window of them. - unknown_supports.sort_by(|a, b| a.normal().x.total_cmp(&b.normal().x)); - candidates.sort_by(|a, b| a.0.normal().x.total_cmp(&b.0.normal().x)); - let mut work = 2_000_000usize; - let mut metadata = 2_000_000usize; - let mut identity_bytes = 16_000_000usize; + // The candidates are taken in the order of their normal's x: where several match one + // face, the first decides which the rest are compared with. + candidates.sort_by(|a, b| a.plane.normal().x.total_cmp(&b.plane.normal().x)); + let mut decide = SupportDecisions::new(&candidates, &unknown_supports, &competing, at); let mut result = Vec::new(); - for (index, face) in self.solid.face_iter().enumerate() { - let mut found = None; - if let Some(actual) = actual_plane(face) { - let mut blocked = false; - let nx = actual.normal().x; - for plane in normal_window(&unknown_supports, |p| p, nx) { - work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("unknown planar source comparison budget exceeded".into()))?; - if same_support(plane, &actual) { - blocked = true; - break; - } - } - for plane in normal_window(&competing, |p| p, nx) { - work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("planar tool comparison budget exceeded".into()))?; - if same_support(plane, &actual) { - blocked = true; - break; - } - } - if blocked { - let existing = self - .face_sources() - .and_then(|sources| sources.get(index)) - .and_then(|s| s.as_ref()) - .filter(|s| (boolean || self.face_was_coalesced(index)) && !boolean_source(s, constructed)); - let keep = existing.and_then(|s| { - descriptor_cost(s).and_then(|cost| { - metadata.checked_sub(cost).map(|remaining| { - metadata = remaining; - s.clone() - }) - }) - }); - result.push(keep); - continue; - } - let mut chosen: Option<(Plane, &FaceSource, bool, usize)> = None; - for (plane, source, inner, cost) in normal_window(&candidates, |c| &c.0, nx) { - work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("planar source comparison budget exceeded".into()))?; - if same_support(plane, &actual) { - if let Some((previous_plane, previous_source, previous_inner, _)) = chosen { - let Some(remaining) = identity_bytes.checked_sub(*cost) else { - chosen = None; - break; - }; - identity_bytes = remaining; - // Several current pieces of one exact source are one - // logical face; distinct source identities remain ambiguous. - if previous_plane != *plane || previous_source != *source || previous_inner != *inner { - chosen = None; - break; - } - } else { - chosen = Some((*plane, *source, *inner, *cost)); - } - } - } - if let Some((plane, source, inner, cost)) = chosen - && let Some(remaining) = metadata.checked_sub(cost) - { - metadata = remaining; - found = Some(if shell.is_some() { - FaceSource::ShellPlanar { producer: None, source: Box::new(source.clone()), inner, plane } - } else { - source.clone() - }); - } - } - if found.is_none() && (boolean || self.face_was_coalesced(index)) { - found = self - .face_sources() + for (index, actual) in actual_planes(&self)?.into_iter().enumerate() { + // A face no candidate names keeps what it had, where an operation could have left + // it a source no role describes. + let existing = || { + self.face_sources() .and_then(|sources| sources.get(index)) .and_then(|s| s.as_ref()) - .filter(|s| !boolean_source(s, constructed)) - .and_then(|s| { - descriptor_cost(s).and_then(|cost| { - metadata.checked_sub(cost).map(|remaining| { - metadata = remaining; - s.clone() - }) - }) - }); - } + .filter(|s| (boolean || self.face_was_coalesced(index)) && !boolean_source(s, constructed) && descriptor_cost(s).is_some()) + .cloned() + }; + let found = match actual.map(|actual| decide.at(&actual)) { + Some(Support::Source(Candidate { plane, source, inner })) => Some(if shell.is_some() { + FaceSource::ShellPlanar { producer: None, source: Box::new(source.clone()), inner, plane } + } else { + source.clone() + }), + Some(Support::Blocked | Support::Unnamed) | None => existing(), + }; result.push(found); } Ok(result) @@ -336,6 +515,204 @@ mod tests { use super::*; use crate::{box_solid, fillet, shell, transform_matrix}; + /// The corner points of face `i` of `b`, from its record. + fn face_points(b: &Body, i: usize) -> Vec { + let record = b.record(); + let mut out = Vec::new(); + for l in &record.faces[i].loops { + match l { + brep::Loop::Edges { edges } => { + for e in edges { + for v in record.edges[e.edge as usize].vertices { + let p = record.vertices[v as usize].point; + out.push(Vec3::new(p[0], p[1], p[2])); + } + } + } + brep::Loop::Vertex { vertex } => { + let p = record.vertices[*vertex as usize].point; + out.push(Vec3::new(p[0], p[1], p[2])); + } + } + } + out + } + + /// The edges of face `i` of `b` as their end points, from its record. + fn face_edges(b: &Body, i: usize) -> Vec<(Vec3, Vec3)> { + let record = b.record(); + let at = |v: u32| { + let p = record.vertices[v as usize].point; + Vec3::new(p[0], p[1], p[2]) + }; + record.faces[i] + .loops + .iter() + .flat_map(|l| match l { + brep::Loop::Edges { edges } => edges.iter().map(|e| record.edges[e.edge as usize].vertices).map(|[a, b]| (at(a), at(b))).collect(), + brep::Loop::Vertex { .. } => Vec::new(), + }) + .collect() + } + + /// One body holding `a` and `b` side by side (their records' shells together, `b` wholly + /// beyond `a` along x), each face's source that of the face of its own operand on the same + /// plane (none from `b` when `b_sources` is false). + fn side_by_side(a: &Body, b: &Body, b_sources: bool) -> Body { + let part = brep::part::compound(&[a.record(), b.record()]).unwrap(); + let mut combined = Body::from_record(part.brep).unwrap(); + let planes = |x: &Body| actual_planes(x).unwrap(); + let (pa, pb, pc) = (planes(a), planes(b), planes(&combined)); + let a_right = a.outline_bounds().max.x; + let sources: Vec> = pc + .iter() + .enumerate() + .map(|(i, p)| { + let p = (*p)?; + let find = |of: &Body, ps: &[Option]| { + ps.iter() + .position(|q| q.is_some_and(|q| same_support(&q, &p, Resolution::of(&combined)))) + .and_then(|i| of.face_sources()?[i].clone()) + }; + let in_a = face_points(&combined, i).iter().all(|q| q.x <= a_right + 1e-9); + if in_a { + find(a, &pa) + } else if b_sources { + find(b, &pb) + } else { + None + } + }) + .collect(); + combined.face_sources = Some(Arc::new(sources)); + combined + } + + /// The plane index offers every plane `same_support` accepts: planes turned and moved by + /// about the resolution (either side of it, so across cell edges), far from the centre, and + /// with normals not of unit length, each checked against a scan of them all. + #[test] + fn plane_index_finds_every_support_a_scan_finds() { + let body = box_solid(Vec3::ZERO, Vec3::new(1000., 1000., 1000.)).unwrap(); + let at = Resolution::of(&body); + let (eps, tol) = (at.angular, at.linear); + let mut planes = Vec::new(); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 * 2. - 1. + }; + for base in [Vec3::X, Vec3::Y, Vec3::Z, -Vec3::Z, Vec3::new(1., 2., 3.)] { + for k in 0..200 { + let base = base.normalized().unwrap(); + let n = (base + Vec3::new(next(), next(), next()) * (eps * 1.2)).normalized().unwrap(); + // A point of the base plane (through the world origin), near or far, moved off it + // by up to one and a half times the resolution's distance. + let r = Vec3::new(next(), next(), next()) * if k % 3 == 0 { 1e4 } else { 300. }; + let origin = r - base * r.dot(base) + n * (next() * tol * 1.5); + let p = Plane::from_normal(origin, n).unwrap(); + planes.push(if k % 50 == 0 { Plane { x: p.x * 1.5, ..p } } else { p }); + } + } + let index = PlaneIndex::new(planes.iter(), at); + let mut matches = 0; + for query in &planes { + let mut near = index.near(query); + near.sort_unstable(); + let found: Vec = near.into_iter().filter(|&i| same_support(&planes[i], query, at)).collect(); + let scan: Vec = (0..planes.len()).filter(|&i| same_support(&planes[i], query, at)).collect(); + assert_eq!(found, scan); + matches += scan.len(); + } + assert!(matches > 2 * planes.len(), "the planes meet each other, not only themselves: {matches}"); + } + + /// Many faces on one plane are decided with work that grows with the faces plus the + /// candidates: each face looks at its plane's one group, never at every candidate on it. + #[test] + fn coplanar_faces_are_decided_by_group_in_linear_work() { + let body = box_solid(Vec3::ZERO, Vec3::new(1000., 1000., 10.)).unwrap(); + let at = Resolution::of(&body); + let top = Plane::new(Vec3::new(0., 0., 10.), Vec3::X, Vec3::Y).unwrap(); + let one = FaceSource::Box { producer: Some(1), axis: 2, high: true, plane: top }; + let other = FaceSource::Box { producer: Some(2), axis: 2, high: true, plane: top }; + for n in [100usize, 1000] { + // `n` pieces of one cap and `n` faces of the result on its plane, each a little moved + // along the plane (as a split face's pieces are). + let pieces: Vec = (0..n).map(|k| Plane::new(Vec3::new(k as f64, 0., 10.), Vec3::X, Vec3::Y).unwrap()).collect(); + let candidates: Vec = (0..n).map(|_| Candidate { plane: top, source: &one, inner: false }).collect(); + let mut decide = SupportDecisions::new(&candidates, &[], &[], at); + for piece in &pieces { + assert_eq!(decide.at(piece), Support::Source(Candidate { plane: top, source: &one, inner: false })); + } + // One look per candidate to group them, one per face to find its group: a scan of + // every candidate per face would look n * n times. + assert_eq!(decide.looked, 2 * n); + // A second identity among the candidates leaves the plane unnamed; a face without a + // role on it blocks it. + let mut mixed = candidates.clone(); + mixed[n / 2] = Candidate { plane: top, source: &other, inner: false }; + assert_eq!(SupportDecisions::new(&mixed, &[], &[], at).at(&pieces[0]), Support::Unnamed); + let unknown = vec![top; n]; + let mut blocked = SupportDecisions::new(&candidates, &unknown, &[], at); + assert!(pieces.iter().all(|piece| blocked.at(piece) == Support::Blocked)); + assert_eq!(blocked.looked, 3 * n); + } + } + + /// A plate with 300 holes whose top a comb of grooves cuts into 62 strips: every strip keeps + /// the top cap's source, every bottom face the bottom cap's, however many there are. + #[test] + fn many_coplanar_pieces_of_a_holed_plate_all_keep_their_cap_source() { + use solidcore_record::{Loop2, Region2, Vec2}; + let holes: Vec = + (0..60).flat_map(|k| (0..5).map(move |r| Loop2::circle(Vec2::new(10. + 10. * k as f64, 5. + 10. * r as f64), 1.))).collect(); + let outer = Loop2::polygon(&[Vec2::new(0., 0.), Vec2::new(610., 0.), Vec2::new(610., 50.), Vec2::new(0., 50.)]); + let region = Region2 { outer, holes }; + let raw = crate::extrude(&Plane::XY, std::slice::from_ref(®ion), 0., 10.).unwrap().remove(0); + let hole_ids: Vec> = (0..300).map(|k| vec![format!("c{k}")]).collect(); + let signatures: Vec<_> = raw + .face_sources() + .unwrap() + .iter() + .map(|s| matches!(s, Some(FaceSource::ExtrudeCap { .. })).then(|| (vec!["l1".to_string()], hole_ids.clone()))) + .collect(); + let plate = raw.with_extrude_cap_certificates(5, 3, &signatures).unwrap(); + // A comb: 61 teeth 2 wide across the plate between the columns of holes, 2 deep. + let mut comb = vec![Vec2::new(-5., 55.), Vec2::new(-5., 60.), Vec2::new(615., 60.), Vec2::new(615., 55.)]; + for k in (0..=60).rev() { + let x = 4. + 10. * k as f64; + comb.extend([Vec2::new(x + 2., 55.), Vec2::new(x + 2., -5.), Vec2::new(x, -5.), Vec2::new(x, 55.)]); + } + let comb = Region2 { outer: Loop2::polygon(&comb), holes: vec![] }; + let tool = crate::extrude(&Plane::XY, std::slice::from_ref(&comb), 8., 12.).unwrap().remove(0); + let cut = crate::boolean(&plate, &tool, crate::BoolOp::Cut).unwrap().unwrap(); + let sources = cut.face_sources().unwrap(); + let (mut tops, mut bottoms) = (0, 0); + for (i, plane) in actual_planes(&cut).unwrap().into_iter().enumerate() { + let Some(plane) = plane else { continue }; + let high = if plane.normal().dot(Vec3::Z) > 0.999999 && (plane.origin.z - 10.).abs() < 1e-9 { + true + } else if plane.normal().dot(Vec3::Z) < -0.999999 && plane.origin.z.abs() < 1e-9 { + false + } else { + continue; + }; + let Some(FaceSource::CertifiedExtrudeCap { producer: 5, high: h, holes, .. }) = &sources[i] else { + panic!("face {i} on the {} cap lost its source: {:?}", if high { "top" } else { "bottom" }, sources[i]); + }; + assert_eq!((*h, holes.len()), (high, 300)); + if high { + tops += 1; + } else { + bottoms += 1; + } + } + assert_eq!((tops, bottoms), (62, 1)); + } + #[test] fn rounded_shell_planar_roles_are_exact_distinct_and_transformable() { for (width, thickness) in [(80., 2.), (100., 3.)] { @@ -372,51 +749,19 @@ mod tests { if matches!(s, Some(FaceSource::ExtrudeSide { coalesced: true, plane: None, .. })) { assert!(cup.face_plane(i).is_none(), "loss witness is not source authority"); } else if s.is_some() { - assert!(same_support(&cup.face_plane(i).unwrap(), &cup.planar_face(i).unwrap())); + assert!(same_support(&cup.face_plane(i).unwrap(), &cup.planar_face(i).unwrap(), Resolution::of(&cup))); } } let moved = transform_matrix(&cup, [[0., 1., 0., 0.], [-1., 0., 0., 0.], [0., 0., 1., 0.], [100., 200., 300., 1.]]).unwrap(); assert!((moved.face_plane(floor).unwrap().origin.z - (300. + thickness)).abs() < 1e-9); assert!(matches!(moved.face_sources().unwrap().get(right), Some(Some(FaceSource::ShellPlanar { producer: Some(9), inner: false, .. })))); assert!(moved.face_plane(right).unwrap().normal().dot(Vec3::Y) > 0.999999); - let raw = cup.tessellate(0.01).unwrap(); - let display = cup.display_mesh(0.01).unwrap(); - let cylindrical: Vec<_> = cup - .solid - .face_iter() - .enumerate() - .filter_map(|(i, f)| { - let crate::FaceSurface::Cylinder { radius, .. } = crate::face_surface(&cup, i)? else { return None }; - let lo = f.vertex_iter().map(|v| v.point().z).fold(f64::INFINITY, f64::min); - let hi = f.vertex_iter().map(|v| v.point().z).fold(f64::NEG_INFINITY, f64::max); - Some((i, radius, lo, hi)) - }) - .collect(); - eprintln!("roundedShell width{width} thickness{thickness} raw{} cylindrical roles{cylindrical:?}", cup.solid.face_iter().count()); - let mut corner_joins = 0; - for (edge, adjacent) in raw.edge_faces.iter().enumerate() { - let [a, b] = adjacent.as_slice() else { continue }; - if raw.edges[edge].iter().all(|p| (p.z - thickness).abs() < 1e-8) - && cylindrical.iter().any(|(i, r, _, _)| *i == *a as usize && (*r - 6.).abs() < 1e-6) - && cylindrical.iter().any(|(i, r, _, _)| *i == *b as usize && (*r - 6.).abs() < 1e-6) - { - corner_joins += 1; - assert!(display.seams[edge], "existing cylindrical corner joins must not draw a floor-height arc"); - } - } - assert_eq!(corner_joins, 0, "no physical lower corner strip remains"); - assert_eq!(cup.face_count(), 19); - let outer: Vec<_> = cylindrical.iter().filter(|(_, r, _, _)| (*r - 6.).abs() < 1e-6).collect(); - assert_eq!(outer.len(), 4); - assert!(outer.iter().all(|(i, _, _, _)| cup.face_was_coalesced(*i) && moved.face_was_coalesced(*i))); - assert!(outer.iter().all(|(_, _, lo, hi)| lo.abs() < 1e-9 && (*hi - 30.).abs() < 1e-9)); - + let display = cup.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); for axis in 0..2 { for high in [false, true] { let matching: Vec<_> = sources.iter().enumerate().filter_map(|(i,s)| matches!(s,Some(FaceSource::ShellPlanar {inner:false,source,..}) if matches!(source.as_ref(),FaceSource::Box {axis:a,high:h,..} if *a==axis && *h==high)).then_some(i)).collect(); assert_eq!(matching.len(), 1, "each straight exterior wall is one actual face"); - let face = cup.solid.face_iter().nth(matching[0]).unwrap(); - let z: Vec<_> = face.vertex_iter().map(|v| v.point().z).collect(); + let z: Vec<_> = face_points(&cup, matching[0]).iter().map(|p| p.z).collect(); assert!(z.iter().any(|z| z.abs() < 1e-9)); assert!(z.iter().any(|z| (*z - 30.).abs() < 1e-9)); } @@ -424,30 +769,31 @@ mod tests { assert!(display.contains(Vec3::new(width / 2. - thickness / 2., 0., thickness / 2.))); assert!(display.contains(Vec3::new(width / 2. - thickness / 2., 0., 15.))); assert!(!display.contains(Vec3::new(0., 0., 15.))); - // Different meshers (the display plan and the reference), both within 0.01 mm. - let (rv, dv) = (raw.measure().volume, display.measure().volume); - assert!((rv - dv).abs() <= raw.measure().area * 0.01, "display volume {dv} vs {rv}"); + // The rounded box less its inside, the box moved in by the wall with its corners' + // rounds at 6 − t, open at the top: exact (SMLib's volume, to 1e-8; the rounds + // are its surfaces). let expected = (width * 60. - (4. - std::f64::consts::PI) * 36.) * 30. - ((width - 2. * thickness) * (60. - 2. * thickness) - (4. - std::f64::consts::PI) * (6. - thickness).powi(2)) * (30. - thickness); - assert!((cup.tessellate(1e-4).unwrap().measure().volume - expected).abs() < 0.2); + let v = crate::measure(&cup).unwrap().volume; + assert!((v - expected).abs() < 1e-6 * expected, "{v} vs {expected}"); let imported = crate::step_import(&crate::step_export(&[&cup], "regularized rounded shell").unwrap()).unwrap(); assert!(imported.warnings.is_empty()); let copy = &imported.bodies[0].body; - assert_eq!(copy.face_count(), 19); - // STEP may additionally coalesce cylindrical corner patches. The - // certified planar wall topology itself must survive unchanged. + // The certified planar walls come back from STEP as one full-height face each. for (axis, coordinate) in [(Vec3::X, width / 2.), (-Vec3::X, width / 2.), (Vec3::Y, 30.), (-Vec3::Y, 30.)] { - let walls: Vec<_> = copy - .solid - .face_iter() - .filter(|f| actual_plane(f).is_some_and(|p| p.normal().dot(axis) > 0.999 && (p.origin.dot(axis) - coordinate).abs() < 1e-8)) + let walls: Vec = actual_planes(copy) + .unwrap() + .iter() + .enumerate() + .filter(|(_, p)| p.is_some_and(|p| p.normal().dot(axis) > 0.999 && (p.origin.dot(axis) - coordinate).abs() < 1e-8)) + .map(|(i, _)| i) .collect(); assert_eq!(walls.len(), 1); - let z: Vec<_> = walls[0].vertex_iter().map(|v| v.point().z).collect(); + let z: Vec<_> = face_points(copy, walls[0]).iter().map(|p| p.z).collect(); assert!(z.iter().any(|z| z.abs() < 1e-8)); assert!(z.iter().any(|z| (*z - 30.).abs() < 1e-8)); } - let copy_mesh = copy.tessellate(1e-4).unwrap(); + let copy_mesh = copy.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap(); assert!((copy_mesh.measure().volume - expected).abs() < 0.2); assert!(copy_mesh.contains(Vec3::new(width / 2. - thickness / 2., 0., 15.))); assert!(!copy_mesh.contains(Vec3::new(0., 0., 15.))); @@ -458,8 +804,8 @@ mod tests { let source = box_solid(Vec3::ZERO, Vec3::new(40., 30., 20.)).unwrap().with_box_certificate(1).unwrap(); let pending = shell(&source, &[Vec3::new(20., 15., 20.)], 2.).unwrap(); let cup = pending.clone().with_shell_certificate(2).unwrap(); - assert_eq!(cup.solid.face_iter().count(), 11); - let mesh = cup.tessellate(0.01).unwrap(); + assert_eq!(cup.face_count(), 11); + let mesh = cup.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!((mesh.measure().volume - (40. * 30. * 20. - 36. * 26. * 18.)).abs() < 1e-6); assert!(mesh.contains(Vec3::new(20., 1., 1.))); assert!(mesh.contains(Vec3::new(20., 1., 10.))); @@ -467,8 +813,8 @@ mod tests { let imported = crate::step_import(&crate::step_export(&[&cup], "regularized shell").unwrap()).unwrap(); assert!(imported.warnings.is_empty()); let copy = &imported.bodies[0].body; - assert_eq!(copy.solid.face_iter().count(), 11); - assert!((copy.tessellate(0.01).unwrap().measure().volume - mesh.measure().volume).abs() < 1e-6); + assert_eq!(copy.face_count(), 11); + assert!((copy.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().volume - mesh.measure().volume).abs() < 1e-6); } #[test] fn union_keeps_unchanged_supports_of_both_operands_and_drops_shared_ones() { @@ -479,8 +825,8 @@ mod tests { let joined = boolean(&a, &b, BoolOp::Union).unwrap().unwrap(); let sources = joined.face_sources().unwrap(); let mut seen = Vec::new(); - for (i, face) in joined.solid.face_iter().enumerate() { - let plane = actual_plane(face).unwrap(); + for (i, plane) in actual_planes(&joined).unwrap().into_iter().enumerate() { + let plane = plane.unwrap(); let source = sources[i].as_ref(); let height = plane.origin.z; if plane.normal().z > 0.999 && (height - 10.).abs() < 1e-9 { @@ -502,30 +848,25 @@ mod tests { fn coincident_competing_source_planes_and_tool_planes_stay_unknown() { let a = box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap().with_box_certificate(1).unwrap(); let b = box_solid(Vec3::new(20., 0., 0.), Vec3::new(30., 10., 10.)).unwrap().with_box_certificate(2).unwrap(); - let mut shells = a.solid.boundaries().to_vec(); - shells.extend(b.solid.boundaries().iter().cloned()); - let mut combined = Body::new(mt::Solid::try_new(shells).unwrap()).unwrap(); - combined.face_sources = Some(Arc::new(a.face_sources().unwrap().iter().chain(b.face_sources().unwrap()).cloned().collect())); + let combined = side_by_side(&a, &b, true); let result = a.clone().with_preserved_planar_sources(&combined).unwrap(); - for (i, face) in result.solid.face_iter().enumerate() { - if actual_plane(face).unwrap().normal().dot(Vec3::Z).abs() > 0.999 { + for (i, p) in actual_planes(&result).unwrap().into_iter().enumerate() { + if p.unwrap().normal().dot(Vec3::Z).abs() > 0.999 { assert!(result.face_sources().unwrap()[i].is_none()); } } - let mut mixed = combined.clone(); - mixed.face_sources = - Some(Arc::new(a.face_sources().unwrap().iter().cloned().chain(std::iter::repeat_n(None, b.solid.face_iter().count())).collect())); + let mixed = side_by_side(&a, &b, false); let guarded = a.clone().with_preserved_planar_sources(&mixed).unwrap(); - for (i, face) in guarded.solid.face_iter().enumerate() { - if actual_plane(face).unwrap().normal().dot(Vec3::Z).abs() > 0.999 { + for (i, p) in actual_planes(&guarded).unwrap().into_iter().enumerate() { + if p.unwrap().normal().dot(Vec3::Z).abs() > 0.999 { assert!(guarded.face_sources().unwrap()[i].is_none(), "uncertified competing support must not gain identity"); } } let cup = shell(&a, &[Vec3::new(5., 5., 10.)], 1.).unwrap().with_shell_certificate(3).unwrap(); let tool = box_solid(Vec3::new(2., 2., 1.), Vec3::new(4., 4., 3.)).unwrap(); let preserved = cup.clone().with_preserved_boolean_planar_sources(&cup, &tool, false).unwrap(); - for (i, face) in preserved.solid.face_iter().enumerate() { - let Some(p) = actual_plane(face) else { continue }; + for (i, p) in actual_planes(&preserved).unwrap().into_iter().enumerate() { + let Some(p) = p else { continue }; if p.normal().dot(Vec3::Z) > 0.999 && (p.origin.z - 1.).abs() < 1e-9 { assert!(preserved.face_sources().unwrap()[i].is_none()); } @@ -534,7 +875,7 @@ mod tests { #[test] fn pocket_cut_removes_internal_wall_faces_in_actual_topology() { - use solidcraft_geom::{Loop2, Region2, Vec2}; + use solidcore_record::{Loop2, Region2, Vec2}; let region = Region2 { outer: Loop2::polygon(&[Vec2::new(-30., -27.), Vec2::new(30., -27.), Vec2::new(30., 27.), Vec2::new(-30., 27.)]), holes: vec![], @@ -551,19 +892,18 @@ mod tests { let (x, y) = (24.73317426966596, 21.733174269665962); let cutter = box_solid(Vec3::new(-x, -y, 1.), Vec3::new(x, y, 10.)).unwrap(); let pocket = crate::boolean(&original, &cutter, crate::BoolOp::Cut).unwrap().unwrap(); - let raw = pocket.tessellate(0.01).unwrap(); - let display = pocket.display_mesh(0.01).unwrap(); + let raw = pocket.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); + let display = pocket.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); let sources = pocket.face_sources().unwrap(); - assert_eq!(pocket.solid.face_iter().count(), 11, "four outer walls, four inner walls, rim, floor, bottom"); + assert_eq!(pocket.face_count(), 11, "four outer walls, four inner walls, rim, floor, bottom"); let sides: Vec<_> = sources.iter().enumerate().filter_map(|(i, s)| matches!(s, Some(FaceSource::CertifiedExtrudeSide { .. })).then_some(i)).collect(); assert_eq!(sides.len(), 4); for i in sides { - let face = pocket.solid.face_iter().nth(i).unwrap(); - let z: Vec<_> = face.vertex_iter().map(|v| v.point().z).collect(); + let z: Vec<_> = face_points(&pocket, i).iter().map(|p| p.z).collect(); assert!(z.iter().any(|z| z.abs() < 1e-9)); assert!(z.iter().any(|z| (*z - 10.).abs() < 1e-9)); - assert!(!face.edge_iter().any(|e| (e.front().point().z - 1.).abs() < 1e-9 && (e.back().point().z - 1.).abs() < 1e-9)); + assert!(!face_edges(&pocket, i).iter().any(|(a, b)| (a.z - 1.).abs() < 1e-9 && (b.z - 1.).abs() < 1e-9)); } assert!(display.contains(Vec3::new(0., 0., 0.5))); assert!(!display.contains(Vec3::new(0., 0., 5.))); @@ -574,8 +914,8 @@ mod tests { let imported = crate::step_import(&crate::step_export(&[&pocket], "regularized pocket").unwrap()).unwrap(); assert!(imported.warnings.is_empty()); let copy = &imported.bodies[0].body; - assert_eq!(copy.solid.face_iter().count(), 11); - let copy_mesh = copy.tessellate(0.01).unwrap(); + assert_eq!(copy.face_count(), 11); + let copy_mesh = copy.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!((copy_mesh.measure().volume - raw.measure().volume).abs() < 1e-6); assert!(copy_mesh.contains(Vec3::new(0., 0., 0.5))); assert!(!copy_mesh.contains(Vec3::new(0., 0., 5.))); diff --git a/crates/kernel/src/plane_fit.rs b/crates/kernel/src/plane_fit.rs index f44b7f316..de4a22cac 100644 --- a/crates/kernel/src/plane_fit.rs +++ b/crates/kernel/src/plane_fit.rs @@ -1,41 +1,6 @@ -//! Planes fitted to points around a loop (Newell's method), for planar faces of polygons read -//! from files and for patches filling a planar loop of edges, and points sampled along edges -//! (shared with the fill of a loop that is not planar). +//! The area vector of a loop of points (Newell's method): its normal and the area it encloses. -use mt::{BoundedCurve, EuclideanSpace, InnerSpace, MetricSpace, ParametricCurve}; -use solidcraft_geom::Vec3; -use truck_modeling as mt; - -use crate::body::{from_p3, p3}; -use crate::{KernelError, Result}; - -/// The plane through points round a loop: its normal by Newell's method (turning with the -/// loop), through their centroid; `None` for fewer than three points or no area. -pub(crate) fn plane_through(pts: &[mt::Point3]) -> Option { - let n = pts.len(); - if n < 3 { - return None; - } - let mut nrm = mt::Vector3::new(0.0, 0.0, 0.0); - let mut c = mt::Vector3::new(0.0, 0.0, 0.0); - for i in 0..n { - let (a, b) = (pts.get(i)?, pts.get((i + 1) % n)?); - nrm.x += (a.y - b.y) * (a.z + b.z); - nrm.y += (a.z - b.z) * (a.x + b.x); - nrm.z += (a.x - b.x) * (a.y + b.y); - c += a.to_vec(); - } - let len = nrm.magnitude(); - if !(len > 1e-12) { - return None; - } - let z = nrm / len; - let o = mt::Point3::from_vec(c / n as f64); - let a = if z.x.abs() < 0.9 { mt::Vector3::unit_x() } else { mt::Vector3::unit_y() }; - let x = (a - z * a.dot(z)).normalize(); - let y = z.cross(x); - Some(mt::Plane::new(o, o + x, o + y)) -} +use solidcore_record::Vec3; /// The area vector of a closed polygon (Newell's method): normal to the loop, as long as the area /// it encloses, pointing the way the loop runs round by the right-hand rule. @@ -47,98 +12,3 @@ pub(crate) fn loop_area(points: &[Vec3]) -> Vec3 { } n * 0.5 } - -/// The point of `c` at `t` (`None` where an intersection curve cannot find it). -fn curve_point(c: &mt::Curve, t: f64) -> Option { - let p = match c { - mt::Curve::IntersectionCurve(ic) => ic.search_triple(t)?.0, - other => other.subs(t), - }; - let p = from_p3(p); - p.is_finite().then_some(p) -} - -/// Points along an edge, in its own direction, at `s ∈ [0, 1]` of its parameter range. An -/// intersection curve's point is searched from the surface parameters of the point found before -/// when that one is near (an eighth of the range), and kept only when it lies near the curve's -/// leader (a seeded search can slide to another branch of the surfaces' intersection); else the -/// unseeded search decides. `None` where no point is found. -pub(crate) struct EdgeSampler { - curve: mt::Curve, - range: (f64, f64), - hint: Option<(f64, mt::Point2, mt::Point2)>, -} - -impl EdgeSampler { - pub(crate) fn new(edge: &mt::Edge) -> Option { - let curve = edge.oriented_curve(); - let range = curve.range_tuple(); - (range.0.is_finite() && range.1.is_finite() && range.0 < range.1).then_some(EdgeSampler { curve, range, hint: None }) - } - - pub(crate) fn at(&mut self, s: f64) -> Option { - let (t0, t1) = self.range; - let t = if s >= 1.0 { t1 } else { t0 + (t1 - t0) * s }; - let mt::Curve::IntersectionCurve(ic) = &self.curve else { return curve_point(&self.curve, t) }; - let leader = ic.leader(); - let (p, d) = (leader.subs(t), leader.der(t)); - let near = |q: mt::Point3| q.distance(p) <= 4.0 * ic.tolerance() + 1e-6; - let seeded = self - .hint - .filter(|(tp, _, _)| (t - tp).abs() <= (t1 - t0) / 8.0) - .and_then(|(_, a, b)| mt::double_projection(ic.surface0(), Some((a.x, a.y)), ic.surface1(), Some((b.x, b.y)), p, d, 100)) - .filter(|f| near(f.0)); - let found = seeded.or_else(|| mt::double_projection(ic.surface0(), None, ic.surface1(), None, p, d, 100))?; - self.hint = Some((t, found.1, found.2)); - let q = from_p3(found.0); - q.is_finite().then_some(q) - } -} - -/// The planar face bounded by the closed loop `chain` (each edge oriented along it) when its -/// edges are certainly in one plane, `None` otherwise (also when an edge cannot be sampled). -/// The plane is fitted to points along the edges ([`plane_through`], the normal turning with the -/// loop); the edges are certified within `tol` of it conservatively: a line by its ends, a -/// B-spline or NURBS curve with positive weights by its control points (the curve lies in their -/// convex hull), an intersection curve only when one of its two surfaces is a plane that the -/// loop's points lie on and the fitted plane agrees with over the loop (the curve lies in that -/// plane). Samples alone are never trusted: a spline can bulge out of the plane between them. -pub(crate) fn planar_face(chain: &[mt::Edge], tol: f64) -> Result> { - const SAMPLES: usize = 16; - let mut pts = Vec::with_capacity(chain.len() * SAMPLES); - for e in chain { - let Some(mut sampler) = EdgeSampler::new(e) else { return Ok(None) }; - for k in 0..SAMPLES { - let Some(p) = sampler.at(k as f64 / SAMPLES as f64) else { return Ok(None) }; - pts.push(p3(p)); - } - } - let Some(plane) = plane_through(&pts) else { return Ok(None) }; - let (o, n) = (plane.origin(), plane.normal()); - let off = |p: mt::Point3, o: mt::Point3, n: mt::Vector3| (p - o).dot(n).abs(); - let on_plane = |p: mt::Point3| off(p, o, n) <= tol; - if !pts.iter().all(|p| on_plane(*p)) { - return Ok(None); - } - // A support plane `q` of an intersection curve holds the loop when the loop's points lie on - // it and their feet on the fitted plane do too. - let holds = |q: &mt::Plane| { - let (qo, qn) = (q.origin(), q.normal()); - pts.iter().all(|p| off(*p, qo, qn) <= tol && off(*p - n * (*p - o).dot(n), qo, qn) <= tol) - }; - for e in chain { - let certified = match e.curve() { - mt::Curve::Line(l) => on_plane(l.0) && on_plane(l.1), - mt::Curve::BSplineCurve(b) => b.control_points().iter().all(|p| on_plane(*p)), - mt::Curve::NurbsCurve(c) => { - c.non_rationalized().control_points().iter().all(|h| h.w > 0.0 && on_plane(mt::Point3::new(h.x / h.w, h.y / h.w, h.z / h.w))) - } - mt::Curve::IntersectionCurve(ic) => [ic.surface0(), ic.surface1()].into_iter().any(|s| matches!(s, mt::Surface::Plane(q) if holds(q))), - }; - if !certified { - return Ok(None); - } - } - let wire: mt::Wire = chain.to_vec().into(); - Ok(Some(mt::Face::try_new(vec![wire], mt::Surface::Plane(plane)).map_err(|e| KernelError::Failed(format!("patch: {e}")))?)) -} diff --git a/crates/kernel/src/point_path.rs b/crates/kernel/src/point_path.rs new file mode 100644 index 000000000..c125bc860 --- /dev/null +++ b/crates/kernel/src/point_path.rs @@ -0,0 +1,525 @@ +//! Sweep paths through 3D sketch curves ([`PointPath`]): drawn 3D splines, which the kernel gets +//! as their fit points and so exactly ([`solidcraft_geom::catmull_rom`]); curves it holds +//! exactly as path segments (sketch curves, body edges: [`edge_path`]); and polylines (curves +//! that reach it only as points: projected onto a face, intersection and iso curves). SMLib +//! follows the path's segments ([`PointPath::segs`]), each free-form span exactly as a +//! [`PathSeg::Bezier`] ([`SpaceBezier`]); [`PointPath::points`] is its polyline, for what takes +//! points (rails, curve networks). + +use solidcore_record::brep; +use solidcore_record::{MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, Plane, Region2, Vec3}; +use solidcraft_geom::bspline::{HPoint, bezier_point, segment}; +use solidcraft_geom::catmull_rom; +use solidcraft_geom::prelude::*; + +use crate::body::Body; +use crate::{KernelError, PathSeg, Result, SweepControl}; + +/// One curve of a [`PointPath`], in the path's direction of travel. +#[derive(Clone, Debug, PartialEq)] +pub enum PathPiece { + /// Points joined by straight lines. + Polyline(Vec), + /// A drawn 3D spline: the centripetal Catmull–Rom spline through `fit`, from its last fit + /// point back to its first when `reversed`. + Spline { fit: Vec, reversed: bool }, + /// A curve the kernel holds exactly as path segments end to end: a sketch curve + /// ([`PathSeg::of_sketch`]) or a body edge ([`edge_path`]). + Segs(Vec), +} + +impl PathPiece { + /// The piece's points in its direction of travel: the polyline, or the spline's samples + /// ([`catmull_rom::samples`]). + pub fn points(&self) -> Vec { + match self { + PathPiece::Polyline(pts) => pts.clone(), + PathPiece::Spline { fit, reversed } => { + let mut pts = catmull_rom::samples(fit); + if *reversed { + pts.reverse(); + } + pts + } + PathPiece::Segs(segs) => { + let mut pts: Vec = segs.first().map(PathSeg::start).into_iter().collect(); + for s in segs { + pts.extend(s.points_after_start(1e-2)); + } + pts + } + } + } + + /// The piece the other way round. + pub fn reversed(self) -> PathPiece { + match self { + PathPiece::Polyline(mut pts) => { + pts.reverse(); + PathPiece::Polyline(pts) + } + PathPiece::Spline { fit, reversed } => PathPiece::Spline { fit, reversed: !reversed }, + PathPiece::Segs(segs) => PathPiece::Segs(segs.iter().rev().map(PathSeg::reversed).collect()), + } + } + + /// The piece's exact segments in the direction of travel: a spline of three or more fit + /// points as its spans ([`PathSeg::Bezier`]), a curve held exactly as its segments; `None` + /// for a polyline (and a spline of one or two points, a point or a line). + pub fn spans(&self) -> Result>> { + let (fit, reversed) = match self { + PathPiece::Spline { fit, reversed } => (fit, reversed), + PathPiece::Segs(segs) => return Ok(Some(segs.clone())), + PathPiece::Polyline(_) => return Ok(None), + }; + let spans = catmull_rom::beziers(fit).ok_or_else(|| KernelError::Invalid("the 3D sketch spline is not finite".into()))?; + if spans.is_empty() { + return Ok(None); + } + let seg = |p: [Vec3; 4]| { + SpaceBezier::cubic(p).map(PathSeg::Bezier).ok_or_else(|| KernelError::Invalid("the 3D sketch spline is not finite".into())) + }; + Ok(Some(if *reversed { + spans.into_iter().rev().map(|[a, b, c, d]| seg([d, c, b, a])).collect::>()? + } else { + spans.into_iter().map(seg).collect::>()? + })) + } +} + +/// A sweep path through 3D sketch curves: its pieces end to end, each starting where the one +/// before it ended. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PointPath { + pub pieces: Vec, +} + +impl PointPath { + /// A path of one polyline. + pub fn polyline(pts: Vec) -> PointPath { + PointPath { pieces: vec![PathPiece::Polyline(pts)] } + } + + /// The path as one polyline: the first piece's points, then each next piece's after its + /// first (where the one before ended). + pub fn points(&self) -> Vec { + let mut chain: Vec = Vec::new(); + for p in &self.pieces { + let pts = p.points(); + if chain.is_empty() { + chain = pts; + } else { + chain.extend(pts.into_iter().skip(1)); + } + } + chain + } + + /// The path as segments: each spline span exactly ([`PathSeg::Bezier`]), each polyline as the + /// lines between its points, starting where the piece before it ended (as [`Self::points`] + /// chains them). + pub(crate) fn segs(&self) -> Result> { + let mut out: Vec = Vec::new(); + for piece in &self.pieces { + if let Some(spans) = piece.spans()? { + out.extend(spans); + continue; + } + let mut pts = piece.points(); + if let (Some(end), Some(first)) = (out.last().map(PathSeg::end), pts.first_mut()) { + *first = end; + } + out.extend(pts.windows(2).filter(|w| w[0].dist(w[1]) > 1e-9).map(|w| PathSeg::Line { a: w[0], b: w[1] })); + } + Ok(out) + } +} + +/// Sweep a planar region along a path through 3D sketch curves: its splines exactly, its +/// polylines as lines (through SMLib). +pub fn sweep_point_path_with(plane: &Plane, region: &Region2, path: &PointPath, ctl: &SweepControl) -> Result { + ctl.check()?; + crate::sweep_path::smlib_sweep_points(plane, region, path, ctl) +} + +/// The point a fraction `t` of the way along `path` (its segments end to end) by arc length, and +/// the unit direction of travel there: 0 is where the path starts, 1 where it ends. Each +/// segment's length and its point at a length are exact ([`PathSeg::length`], +/// [`PathSeg::along`]): closed forms for lines and arcs, the arc-length parameter of a free-form +/// span. A `t` outside 0…1 is refused: the path does not go on past its ends. +pub fn along_path(path: &[PathSeg], t: f64) -> Result<(Vec3, Vec3)> { + if !(0.0..=1.0).contains(&t) { + return Err(KernelError::Invalid(format!("t is {t}: a point along a path is 0 (its start) to 1 (its end) of the way along it"))); + } + let bad = || KernelError::Invalid("a segment of the path does not evaluate".into()); + let lengths: Vec = path.iter().map(|s| s.length().ok_or_else(bad)).collect::>()?; + let total: f64 = lengths.iter().sum(); + if !(total > 0.0 && total.is_finite()) { + return Err(KernelError::Invalid("the path has no length".into())); + } + let mut left = t * total; + let live = || path.iter().zip(&lengths).filter(|(_, l)| **l > 0.0); + let last = live().next_back().ok_or_else(bad)?; + for (seg, &l) in live() { + if left <= l || std::ptr::eq(seg, last.0) { + return seg.along((left / l).min(1.0)).ok_or_else(bad); + } + left -= l; + } + Err(bad()) +} + +/// Most segments one edge's curve may give a path. +const MAX_EDGE_SEGS: usize = 1000; + +/// Edge `edge` of `body` (its index in the body's edge order) as the path segments that are its +/// curve exactly, from its start vertex to its end: a line, an arc, rational quadratic spans of +/// an ellipse, the lines of a polyline, the Bézier spans of a B-spline between its knots. An +/// intersection curve, which the record holds only as its surfaces and a leader near it, is +/// refused. +pub fn edge_path(body: &Body, edge: usize) -> Result> { + let record = crate::native::brep_record(body)?; + let e = record.edges.get(edge).ok_or_else(|| KernelError::Invalid(format!("the body has no edge {edge}")))?; + curve_path(e.parameters(), e.interval) +} + +/// The sketch segments `segs` on `plane` projected along `direction` (pointing from them toward +/// the face) onto the face of `body` at `face_at`, as the record curves SMLib's projection makes +/// (one per piece of the projection that stays on the face), each on its interval. +pub fn project_onto_face( + body: &Body, + face_at: Vec3, + plane: &Plane, + segs: &[solidcore_record::Seg2], + direction: Vec3, +) -> Result> { + if !(face_at.is_finite() && direction.is_finite() && direction.len() > 1e-12) || segs.is_empty() || segs.len() > 4096 { + return Err(KernelError::Invalid("curve projection: a point, a direction and 1…4096 curves".into())); + } + crate::smlib_sweeps::project_onto_face(body, face_at, plane, segs, direction) +} + +/// The face `face` of `body` through `at` cut along `along` by the plane through `at` that holds +/// the face's normal there (its exact normal from the record) and `along`: SMLib's section curves +/// on that face, as record curves on their intervals. +pub fn face_section_along(body: &Body, face: usize, at: Vec3, along: Vec3) -> Result> { + use solidcraft_geom::brep::eval::SurfaceEval; + let f = body.record().faces.get(face).ok_or_else(|| KernelError::Invalid(format!("the body has no face {face}")))?; + let eval = SurfaceEval::new(f.parameters()).map_err(|e| KernelError::Failed(format!("face section: {e}")))?; + let [[u0, u1], [v0, v1]] = f.domain; + let size = body.size().max(1e-9); + let uv = eval + .project(at, Some([0.5 * (u0 + u1), 0.5 * (v0 + v1)]), size * 1e-3 + 1e-6) + .ok_or_else(|| KernelError::Invalid("face section: the point is not on the face".into()))?; + let (_, du, dv) = eval.derivs(uv[0], uv[1]).ok_or_else(|| KernelError::Failed("face section: the surface does not evaluate there".into()))?; + let normal = du + .cross(dv) + .cross(along) + .normalized() + .ok_or_else(|| KernelError::Invalid("face section: the direction runs along the face's normal".into()))?; + crate::smlib_sweeps::face_section(body, at, at, normal) +} + +/// Most control points a record curve given to [`curve_path`] may have. +pub(crate) const MAX_CURVE_POINTS: usize = 100_000; + +/// The record curve `c` on `[t0, t1]` as path segments ([`edge_path`]); the numbers are checked +/// first (they may come from a design file). +pub fn curve_path(c: &brep::Curve, [t0, t1]: [f64; 2]) -> Result> { + let bad = |what: &str| KernelError::Invalid(format!("the curve's {what} does not evaluate")); + if !(t0.is_finite() && t1.is_finite() && t0 < t1 && t0.abs() < 1e9 && t1.abs() < 1e9) { + return Err(bad("interval")); + } + let v = |q: [f64; 3]| Vec3::new(q[0], q[1], q[2]); + let frame_ok = |f: &brep::Frame| { + let (x, y) = (v(f.x_axis), v(f.y_axis)); + v(f.origin).is_finite() && (x.len() - 1.0).abs() < 1e-6 && (y.len() - 1.0).abs() < 1e-6 && x.dot(y).abs() < 1e-6 + }; + let finite = |pts: &[[f64; 3]]| pts.len() <= MAX_CURVE_POINTS && pts.iter().all(|q| v(*q).is_finite()); + match c { + brep::Curve::Line { start, end } if !finite(&[*start, *end]) => return Err(bad("line")), + brep::Curve::Circle { frame, radius } if !(frame_ok(frame) && radius.is_finite() && *radius > 0.0) => return Err(bad("circle")), + brep::Curve::Ellipse { frame, radii } if !(frame_ok(frame) && radii.iter().all(|r| r.is_finite() && *r > 0.0)) => return Err(bad("ellipse")), + brep::Curve::Polyline { points } | brep::Curve::Spline { points, .. } if !finite(points) => return Err(bad("points")), + brep::Curve::RationalSpline { homogeneous, .. } if homogeneous.len() > MAX_CURVE_POINTS => return Err(bad("points")), + _ => {} + } + let out = match c { + brep::Curve::Line { start, end } => { + let (s, e) = (v(*start), v(*end)); + vec![PathSeg::Line { a: s + (e - s) * t0, b: s + (e - s) * t1 }] + } + brep::Curve::Circle { frame, radius } => { + let (o, x, y) = (v(frame.origin), v(frame.x_axis), v(frame.y_axis)); + vec![PathSeg::Arc { a: o + (x * t0.cos() + y * t0.sin()) * *radius, center: o, axis: x.cross(y), angle: t1 - t0 }] + } + brep::Curve::Ellipse { frame, radii } => { + // Each span of at most a quarter turn the affine image of a circular arc's rational + // quadratic: ends on the ellipse, the middle point at the tangents' meeting, weight + // cos(half the span). + let (o, x, y) = (v(frame.origin), v(frame.x_axis) * radii[0], v(frame.y_axis) * radii[1]); + let at = |t: f64, r: f64| o + (x * t.cos() + y * t.sin()) * r; + let m = ((t1 - t0) / std::f64::consts::FRAC_PI_2 - 1e-9).ceil().max(1.0) as usize; + if m > MAX_EDGE_SEGS { + return Err(bad("ellipse")); + } + let d = (t1 - t0) / m as f64; + (0..m) + .map(|i| { + let a = t0 + d * i as f64; + let w = (d / 2.0).cos(); + let ctrl = + [HPoint::weighted(at(a, 1.0), 1.0), HPoint::weighted(at(a + d / 2.0, 1.0 / w), w), HPoint::weighted(at(a + d, 1.0), 1.0)]; + SpaceBezier::new(&ctrl).map(PathSeg::Bezier).ok_or_else(|| bad("ellipse")) + }) + .collect::>()? + } + brep::Curve::Polyline { points } => { + let at = |t: f64| -> Option { + let i = (t.floor().max(0.0) as usize).min(points.len().saturating_sub(2)); + let (a, b) = (v(*points.get(i)?), v(*points.get(i + 1)?)); + Some(a + (b - a) * (t - i as f64)) + }; + let mut ts = vec![t0]; + ts.extend((t0.floor() as i64 + 1..=t1.ceil() as i64 - 1).map(|k| k as f64).filter(|k| *k > t0 && *k < t1)); + ts.push(t1); + if ts.len() > MAX_EDGE_SEGS { + return Err(bad("polyline")); + } + ts.windows(2).map(|w| Some(PathSeg::Line { a: at(w[0])?, b: at(w[1])? })).collect::>().ok_or_else(|| bad("polyline"))? + } + brep::Curve::Spline { knots, points } => { + let ctrl: Vec = points.iter().map(|q| HPoint::weighted(v(*q), 1.0)).collect(); + spline_spans(knots, &ctrl, t0, t1)? + } + brep::Curve::RationalSpline { knots, homogeneous } => { + let ctrl: Vec = homogeneous.iter().map(|q| HPoint { x: q[0], y: q[1], z: q[2], w: q[3] }).collect(); + spline_spans(knots, &ctrl, t0, t1)? + } + brep::Curve::SurfaceIntersection { .. } => { + return Err(KernelError::Failed("not supported yet: a path along an intersection curve (the record holds no exact curve for it)".into())); + } + }; + Ok(out) +} + +/// A sketch segment on `plane` as the record curve that is it, on its interval, running the +/// segment's way: a line, a circle (an arc's; clockwise ones on the frame turned over), a cubic +/// or Bézier as a spline of its degree, a conic as a rational quadratic. `None` for a segment +/// with non-finite numbers. +pub fn sketch_record_curve(plane: &Plane, s: &solidcore_record::Seg2) -> Option<(brep::Curve, [f64; 2])> { + use solidcore_record::Seg2; + let w = |p: solidcore_record::Vec2| { + let q = plane.to_world(p); + [q.x, q.y, q.z] + }; + let d = |v: Vec3| [v.x, v.y, v.z]; + let bezier = |pts: &[solidcore_record::Vec2]| { + let n = pts.len().checked_sub(1)?; + let knots = std::iter::repeat_n(0.0, n + 1).chain(std::iter::repeat_n(1.0, n + 1)).collect(); + Some((brep::Curve::Spline { knots, points: pts.iter().map(|p| w(*p)).collect() }, [0.0, 1.0])) + }; + let out = match *s { + Seg2::Line { a, b } => (brep::Curve::Line { start: w(a), end: w(b) }, [0.0, 1.0]), + Seg2::Arc { center, radius, start, sweep } => { + let (y, t0) = if sweep >= 0.0 { (plane.y, start) } else { (plane.y * -1.0, -start) }; + let frame = brep::Frame { origin: w(center), x_axis: d(plane.x), y_axis: d(y) }; + (brep::Curve::Circle { frame, radius }, [t0, t0 + sweep.abs()]) + } + Seg2::Cubic { p0, p1, p2, p3 } => bezier(&[p0, p1, p2, p3])?, + Seg2::Bezier { n, p } => bezier(p.get(..=usize::from(n))?)?, + Seg2::Conic { a, apex, b, w: wt } => { + let h = |p: solidcore_record::Vec2, k: f64| { + let q = w(p); + [q[0] * k, q[1] * k, q[2] * k, k] + }; + ( + brep::Curve::RationalSpline { knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], homogeneous: vec![h(a, 1.0), h(apex, wt), h(b, 1.0)] }, + [0.0, 1.0], + ) + } + }; + let finite = |q: &[f64]| q.iter().all(|x| x.is_finite()); + let ok = match &out.0 { + brep::Curve::Line { start, end } => finite(start) && finite(end), + brep::Curve::Circle { frame, radius } => finite(&frame.origin) && radius.is_finite() && *radius > 0.0, + brep::Curve::Spline { points, .. } => points.iter().all(|q| finite(q)), + brep::Curve::RationalSpline { homogeneous, .. } => homogeneous.iter().all(|q| finite(q) && q[3] > 0.0), + _ => false, + }; + (ok && out.1.iter().all(|t| t.is_finite())).then_some(out) +} + +/// The B-spline (homogeneous `ctrl` on `knots`) on `[t0, t1]` as its Bézier spans, one per knot +/// span: each the piece of the spline between two neighbouring knots ([`segment`]), exactly. +fn spline_spans(knots: &[f64], ctrl: &[HPoint], t0: f64, t1: f64) -> Result> { + let bad = || KernelError::Invalid("the edge's B-spline does not evaluate".into()); + let p = knots.len().checked_sub(ctrl.len() + 1).ok_or_else(bad)?; + if !(1..=MAX_BEZIER_DEGREE).contains(&p) { + return Err(KernelError::Failed(format!("not supported yet: a path along a B-spline of degree {p}"))); + } + let mut cuts = vec![t0]; + cuts.extend(knots.iter().copied().filter(|k| *k > t0 && *k < t1)); + cuts.push(t1); + cuts.dedup(); + if cuts.len() > MAX_EDGE_SEGS { + return Err(KernelError::Failed("not supported yet: a path along an edge of more than 1000 spans".into())); + } + cuts.windows(2) + .map(|w| { + let (_, piece) = segment(p, knots, ctrl, w[0], w[1]).map_err(|e| KernelError::Invalid(format!("the edge's B-spline: {e}")))?; + SpaceBezier::new(&piece).map(PathSeg::Bezier).ok_or_else(bad) + }) + .collect() +} + +/// A rational Bézier span in space (a [`PathSeg::Bezier`]): degree 1…[`MAX_BEZIER_DEGREE`], +/// homogeneous control points `(x·w, y·w, z·w, w)` with positive weights, on 0…1. A drawn 3D +/// spline's spans are cubics of weight one; an edge's NURBS curve and an ellipse are spans of +/// their degree, exactly. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SpaceBezier { + n: u8, + p: [HPoint; MAX_BEZIER_CTRL], +} + +/// Pieces a span's length is integrated over (8-point Gauss–Legendre on each). +const LENGTH_PIECES: usize = 16; + +/// Nodes and weights of the 8-point Gauss–Legendre rule on [-1, 1]. +const GAUSS_8: [(f64, f64); 8] = [ + (-0.960_289_856_497_536_2, 0.101_228_536_290_376_26), + (-0.796_666_477_413_626_7, 0.222_381_034_453_374_47), + (-0.525_532_409_916_329, 0.313_706_645_877_887_3), + (-0.183_434_642_495_649_8, 0.362_683_783_378_362), + (0.183_434_642_495_649_8, 0.362_683_783_378_362), + (0.525_532_409_916_329, 0.313_706_645_877_887_3), + (0.796_666_477_413_626_7, 0.222_381_034_453_374_47), + (0.960_289_856_497_536_2, 0.101_228_536_290_376_26), +]; + +impl SpaceBezier { + /// The span over `ctrl` (2…[`MAX_BEZIER_CTRL`] finite homogeneous points, positive weights). + pub fn new(ctrl: &[HPoint]) -> Option { + let n = u8::try_from(ctrl.len().checked_sub(1)?).ok()?; + if !(1..=MAX_BEZIER_DEGREE as u8).contains(&n) || ctrl.iter().any(|q| !q.is_finite() || !(q.w > 0.0)) { + return None; + } + let mut p = [HPoint::ZERO; MAX_BEZIER_CTRL]; + p.get_mut(..ctrl.len())?.copy_from_slice(ctrl); + Some(SpaceBezier { n, p }) + } + + /// The cubic over `p` (weights one). + pub fn cubic(p: [Vec3; 4]) -> Option { + SpaceBezier::new(&p.map(|q| HPoint::weighted(q, 1.0))) + } + + pub fn degree(&self) -> usize { + usize::from(self.n) + } + + /// The homogeneous control points. + pub fn ctrl(&self) -> &[HPoint] { + self.p.get(..=self.degree()).unwrap_or(&[]) + } + + /// The point at `x` (0…1). + pub fn point(&self, x: f64) -> Option { + bezier_point(self.ctrl(), x).project() + } + + pub fn start(&self) -> Vec3 { + self.ctrl().first().and_then(|q| q.project()).unwrap_or_default() + } + + pub fn end(&self) -> Vec3 { + self.ctrl().last().and_then(|q| q.project()).unwrap_or_default() + } + + /// The derivative at `x`: the quotient rule on the homogeneous curve and its hodograph. + pub fn derivative(&self, x: f64) -> Option { + let c = self.ctrl(); + let n = self.degree() as f64; + let hodograph: Vec = c.windows(2).map(|w| (w[1] - w[0]) * n).collect(); + let (h, d) = (bezier_point(c, x), bezier_point(&hodograph, x)); + (h.w.abs() > f64::MIN_POSITIVE).then(|| (d.xyz() * h.w - h.xyz() * d.w) * (1.0 / (h.w * h.w))).filter(|v| v.is_finite()) + } + + /// The span the other way round. + pub fn reversed(&self) -> SpaceBezier { + let mut r = *self; + if let Some(c) = r.p.get_mut(..=self.degree()) { + c.reverse(); + } + r + } + + /// The span carried by the affine map `f` of points (weights kept: an affine image of a + /// rational Bézier is the Bézier of the images of its control points). + pub fn mapped(&self, f: impl Fn(Vec3) -> Vec3) -> Option { + let ctrl: Vec = self.ctrl().iter().map(|q| q.project().map(|p| HPoint::weighted(f(p), q.w))).collect::>()?; + SpaceBezier::new(&ctrl) + } + + /// The control points as SMLib takes them: (x, y, z, weight). + pub(crate) fn weighted_points(&self) -> Option> { + self.ctrl().iter().map(|q| q.project().map(|p| [p.x, p.y, p.z, q.w])).collect() + } + + fn speed(&self, x: f64) -> Option { + self.derivative(x).map(Vec3::len) + } + + /// The length from `a` to `b` (8-point Gauss–Legendre). + fn length_between(&self, a: f64, b: f64) -> Option { + let (mid, half) = (0.5 * (a + b), 0.5 * (b - a)); + GAUSS_8.iter().try_fold(0.0, |sum, (x, w)| Some(sum + w * half * self.speed(mid + half * x)?)) + } + + /// The length before each of the [`LENGTH_PIECES`] pieces, and the whole length last. + fn lengths(&self) -> Option> { + let mut out = vec![0.0]; + for i in 0..LENGTH_PIECES { + let (a, b) = (i as f64 / LENGTH_PIECES as f64, (i + 1) as f64 / LENGTH_PIECES as f64); + out.push(out.last().copied().unwrap_or(0.0) + self.length_between(a, b)?); + } + out.last().is_some_and(|t| t.is_finite()).then_some(out) + } + + /// Its length (`None` for a span that does not evaluate). + pub fn length(&self) -> Option { + self.lengths()?.last().copied() + } + + /// The point `f` (0…1) of the way along the span by length, and the unit direction there. + pub fn along(&self, f: f64) -> Option<(Vec3, Vec3)> { + let table = self.lengths()?; + let want = table.last()? * f.clamp(0.0, 1.0); + let k = table.partition_point(|l| *l <= want).saturating_sub(1).min(LENGTH_PIECES - 1); + let (a, before) = (k as f64 / LENGTH_PIECES as f64, *table.get(k)?); + let (mut lo, mut hi) = (a, (k + 1) as f64 / LENGTH_PIECES as f64); + for _ in 0..60 { + let x = 0.5 * (lo + hi); + if before + self.length_between(a, x)? < want { + lo = x; + } else { + hi = x; + } + } + let x = 0.5 * (lo + hi); + Some((self.point(x)?, self.derivative(x)?.normalized()?)) + } + + /// Points along the span, without its start, every chord within `tol` of it (by the bound + /// on the homogeneous second differences, as for a polynomial span of weight one; a rational + /// span's homogeneous bound over its smallest weight). + pub fn polyline(&self, tol: f64) -> Vec { + let c = self.ctrl(); + let n = self.degree() as f64; + let wmin = c.iter().map(|q| q.w).fold(f64::INFINITY, f64::min).max(1e-12); + let bend = c.windows(3).map(|w| (w[0] - w[1] * 2.0 + w[2]).xyz().len()).fold(0.0, f64::max) * n * (n - 1.0).max(1.0) / wmin; + let k = ((bend / (8.0 * tol.max(1e-9))).sqrt().ceil() as usize).clamp(1, 512); + (1..=k).filter_map(|i| self.point(i as f64 / k as f64)).collect() + } +} diff --git a/crates/kernel/src/polybool.rs b/crates/kernel/src/polybool.rs index ca72b5930..ce4b8952c 100644 --- a/crates/kernel/src/polybool.rs +++ b/crates/kernel/src/polybool.rs @@ -1,349 +1,36 @@ -//! Exact-plane booleans for bodies whose faces are all planar (BSP-tree CSG on polygons, in -//! the classic style), used when the B-rep boolean fails — typically on coincident faces, such -//! as a wall flush with the side of its base. The polygons are rebuilt into a B-rep: coplanar -//! pieces are merged into faces, T-junctions are split so neighbouring faces share edges. +//! Booleans of a body with a closed triangle mesh: the mesh becomes a polyhedral solid (each +//! run of coplanar triangles joined across their shared edges one planar face, sewn), which +//! SMLib's boolean takes with the body as it is. The result's history is over the body and the +//! mesh, the mesh's faces being its triangles. -use std::collections::{BTreeMap, BTreeSet, HashMap}; +use solidcraft_geom::prelude::*; +use std::collections::{BTreeMap, BTreeSet}; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; -use truck_modeling::{self as mt, builder}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; -use crate::body::{Body, Solid, edge_order, from_p3, p3}; -use crate::boolean_record::{self as recorded, Traced}; +use crate::body::Body; use crate::heal::find; -use crate::history::{EdgeOrigin, FaceOrigin, History}; -use crate::{BoolOp, KernelError, Result, guard, record}; +use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History, Side}; +use crate::sew::{EdgeSpec, FaceSpec, SurfSpec}; +use crate::{BoolOp, KernelError, Result}; -const MAX_DEPTH: usize = 4000; -const MAX_POLYS: usize = 200_000; +/// The most triangles a mesh operand may have. +const MAX_TRIANGLES: usize = 200_000; -#[derive(Clone, Copy, Debug)] -struct PlaneEq { - n: Vec3, - w: f64, +fn failed(what: &str) -> KernelError { + KernelError::Failed(format!("faceted boolean: {what}")) } -impl PlaneEq { - fn flipped(self) -> PlaneEq { - PlaneEq { n: -self.n, w: -self.w } - } -} - -#[derive(Clone, Debug)] -struct Poly { - v: Vec, - plane: PlaneEq, - /// The operand face this is (a piece of). - src: FaceOrigin, -} - -impl Poly { - fn flip(&mut self) { - self.v.reverse(); - self.plane = self.plane.flipped(); - } -} - -const COPLANAR: u8 = 0; -const FRONT: u8 = 1; -const BACK: u8 = 2; -const SPANNING: u8 = 3; - -/// Split `p` by `pl` into the four buckets. -fn split(pl: PlaneEq, p: &Poly, eps: f64, cf: &mut Vec, cb: &mut Vec, f: &mut Vec, b: &mut Vec) { - let mut ptype = 0u8; - let types: Vec = - p.v.iter() - .map(|v| { - let t = pl.n.dot(*v) - pl.w; - let ty = if t < -eps { - BACK - } else if t > eps { - FRONT - } else { - COPLANAR - }; - ptype |= ty; - ty - }) - .collect(); - match ptype { - COPLANAR => { - if pl.n.dot(p.plane.n) > 0.0 { - cf.push(p.clone()); - } else { - cb.push(p.clone()); - } - } - FRONT => f.push(p.clone()), - BACK => b.push(p.clone()), - _ => { - let (mut fv, mut bv) = (Vec::new(), Vec::new()); - let n = p.v.len(); - for i in 0..n { - let j = (i + 1) % n; - let (Some(&ti), Some(&tj), Some(&vi), Some(&vj)) = (types.get(i), types.get(j), p.v.get(i), p.v.get(j)) else { continue }; - if ti != BACK { - fv.push(vi); - } - if ti != FRONT { - bv.push(vi); - } - if (ti | tj) == SPANNING { - let den = pl.n.dot(vj - vi); - if den.abs() > 1e-300 { - let t = (pl.w - pl.n.dot(vi)) / den; - let x = vi.lerp(vj, t); - fv.push(x); - bv.push(x); - } - } - } - if fv.len() >= 3 { - f.push(Poly { v: fv, plane: p.plane, src: p.src }); - } - if bv.len() >= 3 { - b.push(Poly { v: bv, plane: p.plane, src: p.src }); - } - } - } -} - -#[derive(Default)] -struct Node { - plane: Option, - front: Option>, - back: Option>, - polys: Vec, -} - -impl Node { - fn build(&mut self, polys: Vec, eps: f64, depth: usize) -> Result<()> { - if polys.is_empty() { - return Ok(()); - } - if depth > MAX_DEPTH { - return Err(KernelError::Failed("planar boolean: tree too deep".into())); - } - let pl = match self.plane { - Some(p) => p, - None => { - let p = polys.first().map(|p| p.plane).ok_or_else(|| KernelError::Failed("bsp".into()))?; - self.plane = Some(p); - p - } - }; - let (mut f, mut b) = (Vec::new(), Vec::new()); - let mut cf = Vec::new(); - let mut cb = Vec::new(); - for p in &polys { - split(pl, p, eps, &mut cf, &mut cb, &mut f, &mut b); - } - self.polys.extend(cf); - self.polys.extend(cb); - if !f.is_empty() { - self.front.get_or_insert_with(Default::default).build(f, eps, depth + 1)?; - } - if !b.is_empty() { - self.back.get_or_insert_with(Default::default).build(b, eps, depth + 1)?; - } - Ok(()) - } - fn invert(&mut self) { - for p in &mut self.polys { - p.flip(); - } - self.plane = self.plane.map(PlaneEq::flipped); - if let Some(f) = &mut self.front { - f.invert(); - } - if let Some(b) = &mut self.back { - b.invert(); - } - std::mem::swap(&mut self.front, &mut self.back); - } - fn clip_polys(&self, polys: Vec, eps: f64) -> Vec { - let Some(pl) = self.plane else { return polys }; - let (mut f, mut b) = (Vec::new(), Vec::new()); - let (mut cf, mut cb) = (Vec::new(), Vec::new()); - for p in &polys { - split(pl, p, eps, &mut cf, &mut cb, &mut f, &mut b); - } - f.extend(cf); - b.extend(cb); - let f = match &self.front { - Some(n) => n.clip_polys(f, eps), - None => f, - }; - let b = match &self.back { - Some(n) => n.clip_polys(b, eps), - None => Vec::new(), - }; - let mut out = f; - out.extend(b); - out - } - fn clip_to(&mut self, other: &Node, eps: f64) { - let polys = std::mem::take(&mut self.polys); - self.polys = other.clip_polys(polys, eps); - if let Some(f) = &mut self.front { - f.clip_to(other, eps); - } - if let Some(b) = &mut self.back { - b.clip_to(other, eps); - } - } - fn all(&self, out: &mut Vec) { - out.extend(self.polys.iter().cloned()); - if let Some(f) = &self.front { - f.all(out); - } - if let Some(b) = &self.back { - b.all(out); - } - } -} - -/// Why a body's polygons can't be had: in words that finish "the {role} has …" or "the -/// {role}'s …". -#[derive(Debug, PartialEq)] -enum NotPlanar { - /// Faces on curved surfaces, counted by kind. - Curved(std::collections::BTreeMap<&'static str, usize>), - /// Something else (a face that could not be meshed, too many polygons). - Other(String), -} - -impl NotPlanar { - fn describe(&self, role: &str) -> String { - match self { - NotPlanar::Curved(kinds) => { - let n: usize = kinds.values().sum(); - let list: Vec<&str> = kinds.keys().copied().collect(); - format!("the {role} has {n} curved face{} ({})", if n == 1 { "" } else { "s" }, list.join(", ")) - } - NotPlanar::Other(m) => format!("the {role}'s {m}"), - } - } -} - -/// The kind of curved surface `face` lies on, or None when it lies on a plane. `flat`: whether -/// its mesh is flat. The meshes here are as coarse as a thousandth of the body, which spans a -/// round much smaller than that (a 2 mm corner of a 1.2 m channel) with one flat strip of -/// facets: the surface decides, and the mesh only for a surface none of these kinds fits. -fn curved_kind(face: &mt::Face, flat: bool, tol: f64) -> Option<&'static str> { - use crate::offset::{Surf, surf_of}; - if matches!(face.surface(), mt::Surface::Plane(_)) { - return None; - } - match surf_of(face, tol) { - Some(Surf::Plane { .. }) => None, - Some(Surf::Cylinder { .. }) => Some("cylinder"), - Some(Surf::Cone { .. }) => Some("cone"), - Some(Surf::Sphere { .. }) => Some("sphere"), - Some(Surf::Torus { .. }) => Some("torus"), - None => (!flat).then_some("freeform"), - } -} - -/// The tolerance [`curved_kind`] tells surfaces apart by: face_surface's, with the body's -/// bounds computed once. Walking to each indexed face separately made curved-body diagnostics -/// quadratic. -fn kind_tol(b: &Body) -> f64 { - (b.size() * 1e-7).max(1e-9) * 100.0 -} - -/// The plane of each face (from its mesh, which must be flat), or what stands in the way: the -/// curved faces by the kind of surface they lie on. -fn face_planes(b: &Body, faces: &[crate::FaceInfo]) -> std::result::Result, NotPlanar> { - let surface_tol = kind_tol(b); - let mut surfaces = b.solid.face_iter(); - let mut curved: std::collections::BTreeMap<&'static str, usize> = std::collections::BTreeMap::new(); - let mut out = Vec::with_capacity(faces.len()); - for (index, f) in faces.iter().enumerate() { - let Some(surface) = surfaces.next() else { - return Err(NotPlanar::Other("mesh is inconsistent".into())); - }; - if f.index != index { - return Err(NotPlanar::Other("mesh is inconsistent".into())); - } - if f.area <= 0.0 { - return Err(NotPlanar::Other(format!("face {} could not be meshed", f.index))); - } - match (f.plane_normal, curved_kind(surface, f.plane_normal.is_some(), surface_tol)) { - (Some(n), None) => out.push(PlaneEq { n, w: n.dot(f.centroid) }), - (None, None) => return Err(NotPlanar::Other(format!("face {} is planar but its mesh is not flat", f.index))), - (_, Some(kind)) => *curved.entry(kind).or_insert(0) += 1, - } - } - if surfaces.next().is_some() { - return Err(NotPlanar::Other("mesh is inconsistent".into())); - } - if curved.is_empty() { Ok(out) } else { Err(NotPlanar::Curved(curved)) } -} - -/// Polygons of a body whose faces are all planar, as pieces of its faces as operand `operand`. -fn planar_polys(b: &Body, operand: usize) -> std::result::Result, NotPlanar> { - let tol = (b.size() * 1e-3).max(1e-3); - let unmeshed = |e: KernelError| NotPlanar::Other(format!("faces could not be meshed ({e})")); - let faces = b.faces(tol).map_err(unmeshed)?; - let mesh = b.tessellate(tol).map_err(unmeshed)?; - let planes = face_planes(b, &faces)?; - if mesh.triangles.len() > MAX_POLYS { - return Err(NotPlanar::Other(format!("mesh is too detailed ({} triangles)", mesh.triangles.len()))); - } - let bad_mesh = || NotPlanar::Other("mesh is inconsistent".into()); - let mut out = Vec::new(); - for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) { - let [a, bb, c] = mesh.tri(t).ok_or_else(bad_mesh)?; - let plane = *planes.get(*fi as usize).ok_or_else(bad_mesh)?; - // Snap the vertices onto the exact face plane. - let snap = |p: Vec3| p - plane.n * (plane.n.dot(p) - plane.w); - let mut v = vec![snap(a), snap(bb), snap(c)]; - if (v[1] - v[0]).cross(v[2] - v[0]).dot(plane.n) < 0.0 { - v.reverse(); - } - out.push(Poly { v, plane, src: FaceOrigin::Face { operand, face: *fi as usize } }); - } - Ok(out) -} - -/// Polygons of any body: planar faces exactly, curved ones as their triangles (within `tol`); -/// pieces of its faces as operand `operand`. -fn faceted_polys(b: &Body, tol: f64, operand: usize) -> Option> { - let faces = b.faces(tol).ok()?; - let mesh = b.tessellate(tol).ok()?; - let planes: Vec> = faces.iter().map(|f| f.plane_normal.map(|n| PlaneEq { n, w: n.dot(f.centroid) })).collect(); - let mut out = Vec::new(); - for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) { - let [a, bb, c] = mesh.tri(t)?; - let plane = match planes.get(*fi as usize)? { - Some(pl) => *pl, - None => { - let Some(n) = (bb - a).cross(c - a).normalized() else { continue }; - PlaneEq { n, w: n.dot(a) } - } - }; - let snap = |p: Vec3| p - plane.n * (plane.n.dot(p) - plane.w); - let mut v = vec![snap(a), snap(bb), snap(c)]; - if (v[1] - v[0]).cross(v[2] - v[0]).dot(plane.n) < 0.0 { - v.reverse(); - } - out.push(Poly { v, plane, src: FaceOrigin::Face { operand, face: *fi as usize } }); - } - (out.len() <= MAX_POLYS).then_some(out) -} - -/// Boolean of a body, its curved faces faceted to `tol`, with a closed triangle mesh (wound -/// outward); the result has planar faces only. For tools the B-rep boolean cannot take, such as -/// the helical groove of a thread. +/// Boolean of a body with a closed triangle mesh (wound outward). `tol` (mm): how far a +/// triangle's corners may lie off the plane of the triangles beside it and still make one +/// face with them. For tools that come as meshes; the body keeps its exact faces. /// /// The result's history is over `[a, b]`, the mesh's faces being its triangles (and it having -/// no edges): a face of the result lies on faces of `a` (a facet of a curved one) or on -/// triangles of `b`; an edge between facets of one face of `a`, or between triangles of `b`, -/// has no origin. +/// no edges): a face of the result lies on faces of `a` or on triangles of `b`; an edge where +/// `a` meets the mesh meets the triangles of the face it lies along. pub fn faceted_boolean(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result> { - crate::profile::timed(crate::profile::Kind::Boolean, || faceted_boolean_untimed(a, b, op, tol)) + crate::profile::timed(crate::profile::Kind::Boolean, "faceted_boolean", || faceted_boolean_untimed(a, b, op, tol)) } fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result> { @@ -351,964 +38,188 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result 0.0) { return Err(KernelError::Invalid("facet tolerance".into())); } - let Some(pa) = faceted_polys(a, tol, 0) else { - return Err(KernelError::Failed("the body is too detailed to facet".into())); + if b.triangles.len() > MAX_TRIANGLES { + return Err(failed(&format!("the mesh is too detailed ({} triangles, at most {MAX_TRIANGLES})", b.triangles.len()))); + } + let welded = welded(b); + let b = &welded; + let groups = coplanar_groups(b, tol)?; + let mut faces = Vec::new(); + let mut face_group = Vec::new(); + for (g, triangles) in groups.iter().enumerate() { + for spec in group_faces(b, triangles)? { + faces.push(spec); + face_group.push(g); + } + } + let (tool, from) = crate::sew::sew_touching_with_sources(&faces, &vec![None; faces.len()])?; + let Some(result) = crate::boolean(a, &tool, op)? else { return Ok(None) }; + // The result's history over [a, tool], with the tool's own over the mesh put in its place. + let inner = from.and_then(|from| tool_history(&tool, &from, &face_group, &groups)); + let history = match (result.history(), inner) { + (Some(h), Some(inner)) => h.clone().substituted(1, &inner).ok(), + _ => None, }; - let mut pb = Vec::with_capacity(b.triangles.len()); - for (face, t) in b.triangles.iter().enumerate() { - let Some([p, q, r]) = b.tri(t) else { continue }; - let Some(n) = (q - p).cross(r - p).normalized() else { continue }; - pb.push(Poly { v: vec![p, q, r], plane: PlaneEq { n, w: n.dot(p) }, src: FaceOrigin::Face { operand: 1, face } }); - } - let edges = OperandEdges::of(a); - let sources = Sources { counts: vec![(a.face_count(), edges.ends.len()), (b.triangles.len(), 0)], edges: vec![Some(edges), None] }; - if pa.len() + pb.len() > MAX_POLYS { - return Err(KernelError::Failed("the bodies are too detailed to facet".into())); - } - let size = if b.positions.is_empty() { a.size() } else { a.size().max(b.positions.iter().copied().collect::().diagonal()) }; - // Fine facets of curved faces meet at shallow angles, where the coplanar test decides - // whether the pieces' boundaries come out consistent: try a few tolerances, and take the - // first whose result is watertight and agrees with the complementary boolean (A − B and - // A ∩ B add up to A; A ∪ B is A plus B less A ∩ B). - // The BSP takes each list's first polygon as its splitting plane. Facets in sweep order - // (a thread's groove, turn after turn) make every splitter cut nothing, so the tree is as - // deep as the list is long: quadratic time and memory, and a long thread ran out of depth - // (#1250). The same lists in a fixed shuffled order give a shallow tree. - let (pa, pb) = (shuffled(pa), shuffled(pb)); - let (va, vb) = (polys_volume(&pa), polys_volume(&pb)); - let mut last = KernelError::Failed("faceted boolean".into()); - for rel in [1e-8, 1e-7, 3e-8, 1e-9, 3e-7] { - let eps = size * rel; - let out = csg(pa.clone(), pb.clone(), op, eps)?; - let both = csg(pa.clone(), pb.clone(), BoolOp::Intersect, eps)?; - let (vo, vi) = (polys_volume(&out), polys_volume(&both)); - let expect = match op { - BoolOp::Cut => va - vi, - BoolOp::Union => va + vb - vi, - BoolOp::Intersect => vi, - }; - if (vo - expect).abs() > 1e-6 * (va.abs() + vb.abs()) || vi < -1e-9 * (va.abs() + vb.abs()) { - last = KernelError::Failed(format!("faceted boolean: inconsistent volumes ({vo} vs {expect})")); - continue; - } - if out.is_empty() { - return Ok(None); - } - let weld = size * 1e-7; - match rebuild(&out, size, weld, &sources) { - Ok(b) => return Ok(Some(b)), - Err(e) => last = e, - } - // Thin facets at a thread crest can be narrower than the usual reconstruction - // tolerance. Welding/splitting at that coarser tolerance collapses their boundaries - // into a non-manifold edge. Retry the same volume-checked polygons at the BSP's - // finer precision. Allow a small margin for points classified on either side of - // a splitter, then try the exact BSP tolerance if that still collapses a facet. - // Never return a shell that fails the closed-solid check. - for precision in [3.0 * eps, eps] { - if precision < weld { - match rebuild(&out, size, precision, &sources) { - Ok(b) => return Ok(Some(b)), - Err(e) => last = e, - } - } - } - } - Err(last) + let counts = [(a.face_count(), a.edge_count()), (b.triangles.len(), 0)]; + Ok(Some(result.with_checked_history(history, &counts))) } -/// `polys` in a fixed pseudo-random order (the same every run, so results are reproducible). -fn shuffled(mut polys: Vec) -> Vec { - let mut state = 0x9E37_79B9_7F4A_7C15u64 ^ polys.len() as u64; - let mut next = || { - // SplitMix64. - state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = state; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - }; - for i in (1..polys.len()).rev() { - polys.swap(i, (next() % (i as u64 + 1)) as usize); - } - polys -} - -/// Boolean of two all-planar bodies. -pub fn planar_boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { - a.require_brep("a boolean")?; - b.require_brep("a boolean")?; - let (pa, pb) = match (planar_polys(a, 0), planar_polys(b, 1)) { - (Ok(pa), Ok(pb)) => (pa, pb), - (ra, rb) => { - if let Some(r) = sliced_planar_boolean(a, b, op) { - return r; - } - let why: Vec = - [(ra.err(), "target"), (rb.err(), "tool")].into_iter().filter_map(|(e, role)| e.map(|e| e.describe(role))).collect(); - return Err(KernelError::Failed(format!( - "not supported yet: the exact fallback for where the bodies meet (faces that touch, or cross at a shallow angle) takes planar faces only, and {}", - why.join(" and ") - ))); - } - }; - let size = a.size().max(b.size()); - polys_boolean(pa, pb, size, op, size * 1e-9, &Sources::of(&[a, b])) -} - -/// [`planar_boolean`] of a body with curved faces and an all-planar one, when a slab between -/// two parallel planes holds `b` and none of `a`'s curved faces (a pocket cut beside a round -/// hole): `a` is split across the slab, the middle piece takes the exact boolean, and the -/// pieces outside are joined back on. `None` when no such slab exists. -pub(crate) fn sliced_planar_boolean(a: &Body, b: &Body, op: BoolOp) -> Option>> { - let pb = planar_polys(b, 1).ok()?; - let size = a.size().max(b.size()); - let tol = (a.size() * 1e-3).max(1e-3); - let infos = a.faces(tol).ok()?; - let mesh = a.tessellate(tol).ok()?; - // Each face's plane normal where it is planar (see [`curved_kind`]): a small round meshed - // flat is no plane, and taken for one the middle piece would rebuild it as a chamfer. - let surface_tol = kind_tol(a); - let planes: Vec> = - a.solid.face_iter().zip(&infos).map(|(f, info)| info.plane_normal.filter(|_| curved_kind(f, true, surface_tol).is_none())).collect(); - let mut curved: BTreeMap = BTreeMap::new(); - for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) { - if planes.get(*fi as usize)?.is_some() { - continue; - } - let bx = curved.entry(*fi).or_insert(solidcraft_geom::Aabb3::EMPTY); - for p in mesh.tri(t)? { - bx.add(p); - } - } - // All planar: the exact boolean itself, not this. - if curved.is_empty() { - return None; - } - let mut tool = solidcraft_geom::Aabb3::EMPTY; - for p in pb.iter().flat_map(|p| &p.v) { - tool.add(*p); - } - let at = |v: Vec3, k: usize| [v.x, v.y, v.z].get(k).copied().unwrap_or(0.0); - let axes = [Vec3::X, Vec3::Y, Vec3::Z]; - // Planar faces of `a` square to an axis: a cut must not land in one of their planes. - let flat: Vec<(Vec3, Vec3)> = planes.iter().zip(&infos).filter_map(|(n, f)| Some(((*n)?, f.centroid))).collect(); - let gap = size * 1e-4; - let place = |k: usize, near: f64, far: f64| -> Option { - let axis = *axes.get(k)?; - [0.5, 0.37, 0.63, 0.25, 0.75] - .iter() - .map(|t| near + (far - near) * t) - .find(|x| !flat.iter().any(|(n, c)| n.dot(axis).abs() > 1.0 - 1e-9 && (at(*c, k) - x).abs() < gap)) - }; - // An axis along which every curved face lies clear of the tool: the cuts either side. - let (k, lo, hi) = (0..3).find_map(|k| { - let (t0, t1) = (at(tool.min, k), at(tool.max, k)); - let (mut below, mut above) = (None::, None::); - for bx in curved.values() { - let (c0, c1) = (at(bx.min, k), at(bx.max, k)); - if c1 < t0 - gap { - below = Some(below.map_or(c1, |x| x.max(c1))); - } else if c0 > t1 + gap { - above = Some(above.map_or(c0, |x| x.min(c0))); - } else { - return None; - } - } - let lo = match below { - Some(c) => Some(place(k, t0, c)?), - None => None, - }; - let hi = match above { - Some(c) => Some(place(k, t1, c)?), - None => None, - }; - Some((k, lo, hi)) - })?; - let (u, w) = match k { - 0 => (Vec3::Y, Vec3::Z), - 1 => (Vec3::Z, Vec3::X), - _ => (Vec3::X, Vec3::Y), - }; - let axis = *axes.get(k)?; - let run = || -> Result> { - let fail = |m: &str| KernelError::Failed(format!("planar boolean beside curved faces: {m}")); - // Every piece with its history over [a, b, then the boxes of each cut: the one away - // from the middle, the one around it]; the boxes' faces are gone from the result (glued - // away), so they are dropped at the end. - let n = 6; - let mut middle: Traced = (a.clone(), recorded::kept(a, 0, n)); - let mut outside: Vec = Vec::new(); - for (slot, (cut, keep_positive)) in [(2, (lo, true)), (4, (hi, false))] { - let Some(x) = cut else { continue }; - let plane = solidcraft_geom::Plane::new(axis * x, u, w).ok_or_else(|| fail("plane"))?; - // Split along the plane (an imprint: no boolean); two booleans with half boxes - // where the split can't be sorted into one piece kept and the rest away. - if let Some((away, kept)) = split_beside(&middle, &plane, axis, x, keep_positive) { - outside.extend(away); - middle = kept; - continue; - } - let (away, kept) = (crate::ops::half_box(&middle.0, &plane, !keep_positive)?, crate::ops::half_box(&middle.0, &plane, keep_positive)?); - let (h_away, h_kept) = (recorded::kept(&away, slot, n), recorded::kept(&kept, slot + 1, n)); - if let Some(o) = crate::ops::boolean(&middle.0, &away, BoolOp::Intersect)? { - let h = recorded::of_pair(&o, &middle.1, &h_away); - outside.push((o, h)); - } - let m = crate::ops::boolean(&middle.0, &kept, BoolOp::Intersect)?.ok_or_else(|| fail("nothing beside the tool"))?; - let h = recorded::of_pair(&m, &middle.1, &h_kept); - middle = (m, h); - } - let pm = planar_polys(&middle.0, 0).map_err(|e| fail(&e.describe("middle piece")))?; - let r = polys_boolean(pm, pb, size, op, size * 1e-9, &Sources::of(&[&middle.0, b]))?; - reassembled(a, b, op, &middle, r, outside, n, &fail) - }; - Some(run()) -} - -/// The middle piece's boolean with `b` (`r`, over `[middle, b]`) and the pieces of `a` split -/// away from the middle (`outside`) glued back into one result over `[a, b]`: the operands past -/// the second (`n` in all, the boxes a piece was cut with) are dropped. `fail` names the route -/// in its errors. Shared with [`crate::prism_local`]. -#[allow(clippy::too_many_arguments)] -pub(crate) fn reassembled( - a: &Body, - b: &Body, - op: BoolOp, - middle: &Traced, - r: Option, - outside: Vec, - n: usize, - fail: &dyn Fn(&str) -> KernelError, -) -> Result> { - let size = a.size().max(b.size()); - let h_b = recorded::kept(b, 1, n); - let counts = record::counts(&[a, b]); - if op == BoolOp::Intersect { - return Ok(r.map(|r| { - let h = dropped(recorded::of_pair(&r, &middle.1, &h_b)); - r.with_checked_history(h, &counts) - })); - } - // The rebuild leaves the cut faces' edges split where other polygons were cut; healed, - // they match the pieces outside edge for edge. - let pieces: Vec = match r { - Some(m) => { - let healed = recorded::heal_body(&m, m.deep_copy(), size, a.split_keep(), &record::counts(&[&middle.0, b]))?; - let h = recorded::of_pair(&healed, &middle.1, &h_b); - vec![(healed, h)] - } - None => Vec::new(), - }; - // Each piece in its lumps: a cut plane crossing a frame or a ring leaves the middle (or - // a piece outside) in several parts, which meet the others along several cut faces. - let lumps = |(whole, h): Traced| -> Result> { - if whole.solid.boundaries().len() == 1 { - return Ok(vec![(whole, h)]); - } - let parts = whole.lumps()?; - let histories = recorded::parts_of(&parts, &whole); - Ok(parts - .into_iter() - .zip(histories) - .map(|(p, hp)| { - let h = match (hp, h.as_ref()) { - (Some(hp), Some(h)) => recorded::composed(hp.substituted(0, h)), - _ => None, - }; - (p, h) +/// `m` with corners at the very same point made one vertex, triangles in their order: a body's +/// own mesh (Body::mesh) gives each face its own vertices, the faces along an edge its very +/// points, and is closed only once they are one. +fn welded(m: &Mesh) -> Mesh { + let mut at: BTreeMap<[u64; 3], u32> = BTreeMap::new(); + let mut positions = Vec::with_capacity(m.positions.len()); + let index: Vec = m + .positions + .iter() + .map(|p| { + *at.entry([p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]).or_insert_with(|| { + positions.push(*p); + (positions.len() - 1) as u32 }) - .collect()) - }; - let mut all: Vec = Vec::new(); - for piece in pieces.into_iter().chain(outside) { - all.extend(lumps(piece)?); - } - // Glue pieces that meet along their cut faces until one is left; every cut face pair - // goes (a pair left behind would be a slit through the result). - let mut joined: Vec = Vec::new(); - while let Some(mut cur) = all.pop() { - loop { - let found = all.iter().enumerate().find_map(|(i, (o, _))| Some((i, crate::coplanar::glue(&cur.0, o)?.ok()?))); - let Some((i, j)) = found else { break }; - let other = all.swap_remove(i); - let h = recorded::of_pair(&j, &cur.1, &other.1); - cur = (j, h); - } - joined.push(cur); - } - if joined.iter().any(|(x, _)| x.solid.boundaries().len() != 1) { - return Err(fail("a piece in several parts")); - } - // A join onto one piece is one piece: anything apart is a cut face that did not glue. - if op == BoolOp::Union && a.solid.boundaries().len() == 1 && joined.len() != 1 { - return Err(fail("a piece does not join back")); - } - let pieces = joined; - recorded::join(pieces.into_iter().map(|(p, h)| (p, dropped(h))).collect(), &counts) -} - -/// `piece` split by `plane` (at `x` along `axis`): the parts on the side away from the tool -/// and the one part on its side (positive along `axis` when `keep_positive`), each with its -/// history over the operands `piece`'s is over. `None` when the split leaves no part on either -/// side, or several on the tool's. -pub(crate) fn split_beside(piece: &Traced, plane: &solidcraft_geom::Plane, axis: Vec3, x: f64, keep_positive: bool) -> Option<(Vec, Traced)> { - let parts = crate::splitface::split_body(&piece.0, &crate::splitface::SplitTool::Plane(*plane)).ok()?; - if parts.len() < 2 { - return None; - } - let tol = piece.0.size() * 1e-6 + 1e-9; - let (mut away, mut kept) = (Vec::new(), Vec::new()); - for part in parts { - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for v in part.solid.vertex_iter() { - let t = from_p3(v.point()).dot(axis) - x; - lo = lo.min(t); - hi = hi.max(t); - } - let h = match (part.history(), piece.1.as_ref()) { - (Some(hp), Some(h)) => recorded::composed(hp.clone().substituted(0, h)), - _ => None, - }; - let positive = if lo >= -tol { - true - } else if hi <= tol { - false - } else { - return None; - }; - if positive == keep_positive { kept.push((part, h)) } else { away.push((part, h)) } - } - let kept = kept.pop().filter(|_| kept.is_empty())?; - (!away.is_empty()).then_some((away, kept)) -} - -/// `h` over `[a, b]`: the operands after them (the boxes a piece was cut with) dropped, which -/// fails where something of them is left. -fn dropped(h: Option) -> Option { - let h = h?; - let map: Vec> = (0..h.operands).map(|op| (op < 2).then_some(op)).collect(); - recorded::composed(h.renumbered(&map, 2)) -} - -fn polys_boolean(pa: Vec, pb: Vec, size: f64, op: BoolOp, eps: f64, sources: &Sources) -> Result> { - let polys = csg(pa, pb, op, eps)?; - if polys.is_empty() { - return Ok(None); - } - rebuild(&polys, size, size * 1e-7, sources).map(Some) -} - -/// What a rebuilt body's history is over: each operand's face and edge counts and, where it is -/// a B-rep, its edges in its edge order (the faces each bounds, and its ends). -struct Sources { - counts: Vec<(usize, usize)>, - edges: Vec>, -} - -/// An operand's edges in its edge order (each one's ends), and those between each pair of its -/// faces (lesser face first). -struct OperandEdges { - ends: Vec<(Vec3, Vec3)>, - between: BTreeMap<(usize, usize), Vec>, -} - -impl OperandEdges { - fn of(b: &Body) -> OperandEdges { - let (edges, bounds) = edge_order(b.solid.face_iter()); - let mut between: BTreeMap<(usize, usize), Vec> = BTreeMap::new(); - for (i, fs) in bounds.iter().enumerate() { - if let [f, g] = fs.as_slice() { - between.entry((*f.min(g), *f.max(g))).or_default().push(i); - } - } - let ends = edges.iter().map(|e| (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()))).collect(); - OperandEdges { ends, between } - } -} - -impl Sources { - fn of(bodies: &[&Body]) -> Sources { - let edges: Vec = bodies.iter().map(|b| OperandEdges::of(b)).collect(); - let counts = bodies.iter().zip(&edges).map(|(b, e)| (b.face_count(), e.ends.len())).collect(); - Sources { counts, edges: edges.into_iter().map(Some).collect() } - } - - /// The origins of an edge between a piece of `p` and a piece of `q` running from `ends.0` - /// to `ends.1`: where faces of two operands meet; the edge between two faces of one - /// operand (the one the piece lies along, when they share several); none between pieces of - /// one face, or between triangles of a mesh operand. `None` when it can't be told. - fn edge(&self, p: FaceOrigin, q: FaceOrigin, ends: (Vec3, Vec3), tol: f64) -> Option> { - let (FaceOrigin::Face { operand: x, face: f }, FaceOrigin::Face { operand: y, face: g }) = (p, q) else { return None }; - if x != y { - return Some(vec![EdgeOrigin::meet(p, q)]); - } - let Some(edges) = self.edges.get(x)?.as_ref() else { return Some(Vec::new()) }; - if f == g { - return Some(Vec::new()); - } - let between = edges.between.get(&(f.min(g), f.max(g)))?; - let along: Vec = match between.as_slice() { - [_] => between.clone(), - _ => between - .iter() - .copied() - .filter(|i| edges.ends.get(*i).is_some_and(|(s, t)| ends.0.dist_to_segment(*s, *t) <= tol && ends.1.dist_to_segment(*s, *t) <= tol)) - .collect(), - }; - match along.as_slice() { - [edge] => Some(vec![EdgeOrigin::Edge { operand: x, edge: *edge }]), - _ => None, - } - } -} - -/// Enclosed volume of a closed set of polygons (divergence theorem). -fn polys_volume(ps: &[Poly]) -> f64 { - let mut v6 = 0.0; - for p in ps { - let Some(&o) = p.v.first() else { continue }; - for w in p.v.windows(2).skip(1) { - v6 += o.dot(w[0].cross(w[1])); - } - } - v6 / 6.0 -} - -/// The polygons of a BSP boolean (csg.js style). -fn csg(pa: Vec, pb: Vec, op: BoolOp, eps: f64) -> Result> { - let (mut na, mut nb) = (Node::default(), Node::default()); - na.build(pa, eps, 0)?; - nb.build(pb, eps, 0)?; - match op { - BoolOp::Union => { - na.clip_to(&nb, eps); - nb.clip_to(&na, eps); - nb.invert(); - nb.clip_to(&na, eps); - nb.invert(); - let mut extra = Vec::new(); - nb.all(&mut extra); - na.build(extra, eps, 0)?; - } - BoolOp::Cut => { - na.invert(); - na.clip_to(&nb, eps); - nb.clip_to(&na, eps); - nb.invert(); - nb.clip_to(&na, eps); - nb.invert(); - let mut extra = Vec::new(); - nb.all(&mut extra); - na.build(extra, eps, 0)?; - na.invert(); - } - BoolOp::Intersect => { - na.invert(); - nb.clip_to(&na, eps); - nb.invert(); - na.clip_to(&nb, eps); - nb.clip_to(&na, eps); - let mut extra = Vec::new(); - nb.all(&mut extra); - na.build(extra, eps, 0)?; - na.invert(); - } - } - let mut polys = Vec::new(); - na.all(&mut polys); - Ok(polys) -} - -/// `shell`'s connected components, each face in the shell's order and the components by their -/// first face. truck's own come out in the hash order of face addresses, so the same rebuild -/// gave a body with its faces in a different order from run to run (#707). -pub(crate) fn components_in_order(shell: &mt::Shell) -> Vec { - let pos: HashMap = shell.face_iter().enumerate().map(|(i, f)| (f.id(), i)).collect(); - let key = |f: &mt::Face| pos.get(&f.id()).copied().unwrap_or(usize::MAX); - let mut comps: Vec> = shell - .connected_components() - .into_iter() - .map(|c| { - let mut faces: Vec = c.into_iter().collect(); - faces.sort_by_key(|f| key(f)); - faces }) .collect(); - comps.sort_by_key(|c| c.first().map(key).unwrap_or(usize::MAX)); - comps.into_iter().map(mt::Shell::from).collect() + let triangles = m.triangles.iter().map(|t| t.map(|i| index.get(i as usize).copied().unwrap_or(i))).collect(); + Mesh { positions, triangles, ..Mesh::default() } } -/// Position key for vertex merging. -fn key(p: Vec3, q: f64) -> (i64, i64, i64) { - ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64) -} - -/// Turn polygons into a B-rep solid: merge by plane, split T-junctions, chain boundary loops. -/// Its history over the operands the polygons are pieces of (`sources`): each face the -/// operand faces whose pieces it joins (pieces joined across the edges between them), each edge -/// what the pieces either side of it say (see [`Sources::edge`]). -fn rebuild(polys: &[Poly], size: f64, q: f64, sources: &Sources) -> Result { - // Global vertex table. - let mut index: BTreeMap<(i64, i64, i64), usize> = BTreeMap::new(); - let mut verts: Vec = Vec::new(); - // Points within `q` share a vertex, also across the rounding grid's cell boundaries. - let mut id = |p: Vec3, verts: &mut Vec| -> usize { - let k = key(p, q); - for dx in -1..=1 { - for dy in -1..=1 { - for dz in -1..=1 { - if let Some(&i) = index.get(&(k.0 + dx, k.1 + dy, k.2 + dz)) - && verts.get(i).is_some_and(|v| (*v - p).len() <= q) - { - return i; - } - } - } - } - verts.push(p); - index.insert(k, verts.len() - 1); - verts.len() - 1 - }; - let mut loops: Vec<(PlaneEq, Vec)> = Vec::new(); - let mut srcs: Vec = Vec::new(); - for p in polys { - let mut l: Vec = p.v.iter().map(|v| id(*v, &mut verts)).collect(); - l.dedup(); - if l.first() == l.last() && l.len() > 1 { - l.pop(); - } - if l.len() >= 3 { - loops.push((p.plane, l)); - srcs.push(p.src); +/// The mesh's triangles in runs that make one planar face each: triangles sharing an edge, on +/// one plane within `tol`, are one run. +fn coplanar_groups(m: &Mesh, tol: f64) -> Result>> { + let mut planes = Vec::with_capacity(m.triangles.len()); + for t in &m.triangles { + let [p, q, r] = m.tri(t).ok_or_else(|| failed("a triangle refers to a missing vertex"))?; + let n = (q - p).cross(r - p).normalized().ok_or_else(|| failed("a triangle has no area"))?; + planes.push((n, n.dot(p))); + } + let mut by_edge: BTreeMap<(u32, u32), Vec> = BTreeMap::new(); + for (i, t) in m.triangles.iter().enumerate() { + for k in 0..3 { + let (a, b) = (t[k], t[(k + 1) % 3]); + by_edge.entry((a.min(b), a.max(b))).or_default().push(i); } } - // Split every polygon edge at vertices lying on it (T-junctions). Vertices are binned in a - // grid sized to the typical edge, so each edge only looks at its neighbourhood. - let tol = size * 1e-7; - let edge_len: Vec = loops + let on_plane = |(n, w): (Vec3, f64), t: usize| { + m.triangles.get(t).and_then(|t| m.tri(t)).is_some_and(|corners| corners.iter().all(|p| (n.dot(*p) - w).abs() <= tol)) + }; + let mut parent: Vec = (0..m.triangles.len()).collect(); + for sharing in by_edge.values() { + let &[t, u] = sharing.as_slice() else { return Err(failed("the mesh is not closed: an edge is not shared by exactly two triangles")) }; + let (Some(&pt), Some(&pu)) = (planes.get(t), planes.get(u)) else { continue }; + if pt.0.dot(pu.0) > 1.0 - 1e-12 && on_plane(pt, u) && on_plane(pu, t) { + let (rt, ru) = (find(&mut parent, t), find(&mut parent, u)); + if let Some(slot) = parent.get_mut(rt) { + *slot = ru; + } + } + } + let mut groups: BTreeMap> = BTreeMap::new(); + for t in 0..m.triangles.len() { + groups.entry(find(&mut parent, t)).or_default().push(t); + } + Ok(groups.into_values().collect()) +} + +/// The planar faces of one run of coplanar triangles: its boundary (the edges no other triangle +/// of the run runs back along) chained into loops, split where a loop passes a vertex twice, +/// each outer loop (counter-clockwise about the run's normal) with the holes it holds. +fn group_faces(m: &Mesh, triangles: &[usize]) -> Result> { + let bad = || failed("a triangle refers to a missing vertex"); + let first = *triangles.first().ok_or_else(|| failed("an empty face"))?; + let [p, q, r] = m.triangles.get(first).and_then(|t| m.tri(t)).ok_or_else(bad)?; + let normal = (q - p).cross(r - p).normalized().ok_or_else(|| failed("a triangle has no area"))?; + let directed: BTreeSet<(u32, u32)> = + triangles.iter().filter_map(|t| m.triangles.get(*t)).flat_map(|t| (0..3).map(move |k| (t[k], t[(k + 1) % 3]))).collect(); + let mut out: BTreeMap> = BTreeMap::new(); + for &(a, b) in &directed { + if !directed.contains(&(b, a)) { + out.entry(a).or_default().push(b); + } + } + let point = |v: u32| m.positions.get(v as usize).copied().ok_or_else(bad); + let mut loops: Vec> = Vec::new(); + while let Some((&start, _)) = out.iter().find(|(_, next)| !next.is_empty()) { + let mut walk = vec![start]; + let mut at = start; + loop { + let next = out.get_mut(&at).and_then(Vec::pop).ok_or_else(|| failed("a face's boundary does not close"))?; + if next == start { + break; + } + walk.push(next); + at = next; + } + // A walk through a vertex twice (two loops touching there) is split into simple loops. + let mut stack: Vec = Vec::new(); + for v in walk { + if let Some(at) = stack.iter().position(|x| *x == v) { + loops.push(stack.split_off(at)); + } + stack.push(v); + } + loops.push(stack); + } + let polygon = |lp: &[u32]| lp.iter().map(|v| point(*v)).collect::>>(); + let area = |pts: &[Vec3]| pts.iter().zip(pts.iter().cycle().skip(1)).fold(Vec3::ZERO, |s, (a, b)| s + a.cross(*b)).dot(normal) * 0.5; + let (u, w) = (normal.any_perp(), normal.cross(normal.any_perp())); + let inside = |pt: Vec3, poly: &[Vec3]| { + let (px, py) = (pt.dot(u), pt.dot(w)); + let mut odd = false; + for (a, b) in poly.iter().zip(poly.iter().cycle().skip(1)) { + let ((ax, ay), (bx, by)) = ((a.dot(u), a.dot(w)), (b.dot(u), b.dot(w))); + if (ay > py) != (by > py) && px < ax + (py - ay) / (by - ay) * (bx - ax) { + odd = !odd; + } + } + odd + }; + let polys: Vec> = loops.iter().filter(|l| l.len() >= 3).map(|l| polygon(l)).collect::>()?; + let (outers, holes): (Vec<&Vec>, Vec<&Vec>) = polys.iter().partition(|p| area(p) > 0.0); + let edges = |poly: &[Vec3]| poly.iter().zip(poly.iter().cycle().skip(1)).map(|(a, b)| EdgeSpec::Line { a: *a, b: *b }).collect::>(); + let mut faces: Vec = outers.iter().map(|o| FaceSpec { loops: vec![edges(o)], surface: SurfSpec::Plane, probe: None }).collect(); + for hole in holes { + let probe = *hole.first().ok_or_else(|| failed("an empty loop"))?; + // The innermost outer loop holding the hole. + let owner = (0..outers.len()) + .filter(|i| outers.get(*i).is_some_and(|o| inside(probe, o))) + .min_by(|x, y| outers.get(*x).map_or(0.0, |o| area(o)).total_cmp(&outers.get(*y).map_or(0.0, |o| area(o)))) + .ok_or_else(|| failed("a hole in no face"))?; + if let Some(face) = faces.get_mut(owner) { + face.loops.push(edges(hole)); + } + } + Ok(faces) +} + +/// The tool's history over the mesh: each face from the triangles of its run (`from` gives +/// the face spec each tool face was sewn from, `face_group` the run of each spec); each edge +/// where the runs of the faces either side of it meet. `None` where a face can't be followed. +fn tool_history(tool: &Body, from: &[usize], face_group: &[usize], groups: &[Vec]) -> Option { + let triangles = |face: usize| -> Option<&Vec> { groups.get(*face_group.get(*from.get(face)?)?) }; + let origins = + |face: usize| -> Option> { Some(triangles(face)?.iter().map(|t| FaceOrigin::Face { operand: 0, face: *t }).collect()) }; + let faces = (0..tool.face_count()) + .map(|f| { + let origins = origins(f)?; + let change = if origins.len() == 1 { Change::Kept } else { Change::Merged }; + Some(FaceProv { origins, change }) + }) + .collect::>>()?; + let record = crate::native::brep_record(tool).ok()?; + let edges = record + .edges .iter() - .flat_map(|(_, l)| (0..l.len()).filter_map(move |i| Some((*l.get(i)?, *l.get((i + 1) % l.len())?)))) - .filter_map(|(a, b)| Some((*verts.get(b)? - *verts.get(a)?).len())) - .collect(); - let mean = edge_len.iter().sum::() / edge_len.len().max(1) as f64; - let cell = mean.max(size * 1e-4).max(1e-9); - let ckey = |p: Vec3| ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64, (p.z / cell).floor() as i64); - let mut grid: BTreeMap<(i64, i64, i64), Vec> = BTreeMap::new(); - for (k, v) in verts.iter().enumerate() { - grid.entry(ckey(*v)).or_default().push(k); - } - let mut directed: Vec<(usize, usize, usize)> = Vec::new(); // (plane group, from, to) - // The polygons (by loop) each directed edge comes from. - let mut owners: BTreeMap<(usize, usize, usize), Vec> = BTreeMap::new(); - let mut groups: Vec = Vec::new(); - let mut group_of: BTreeMap<(i64, i64, i64, i64), usize> = BTreeMap::new(); - for (li, (pl, l)) in loops.iter().enumerate() { - let gk = ((pl.n.x * 1e8).round() as i64, (pl.n.y * 1e8).round() as i64, (pl.n.z * 1e8).round() as i64, (pl.w / (tol * 10.0)).round() as i64); - let g = *group_of.entry(gk).or_insert_with(|| { - groups.push(*pl); - groups.len() - 1 - }); - let n = l.len(); - for i in 0..n { - let (Some(&a), Some(&b)) = (l.get(i), l.get((i + 1) % n)) else { continue }; - let (Some(&pa), Some(&pb)) = (verts.get(a), verts.get(b)) else { continue }; - let d = pb - pa; - let len2 = d.len2(); - let (lo, hi) = (ckey(pa.min(pb) - Vec3::new(q, q, q)), ckey(pa.max(pb) + Vec3::new(q, q, q))); - let cells = (hi.0 - lo.0 + 1) * (hi.1 - lo.1 + 1) * (hi.2 - lo.2 + 1); - let candidates: Vec = if cells > 4096 { - (0..verts.len()).collect() - } else { - let mut c = Vec::new(); - for x in lo.0..=hi.0 { - for y in lo.1..=hi.1 { - for z in lo.2..=hi.2 { - if let Some(ks) = grid.get(&(x, y, z)) { - c.extend(ks.iter().copied()); - } - } - } - } - c + .map(|e| { + let mut sides: Vec = e.uses.iter().map(|u| u.face as usize).collect(); + sides.sort_unstable(); + sides.dedup(); + let meet = match sides.as_slice() { + [f, g] => vec![EdgeOrigin::meet(Side::new(origins(*f)?)?, Side::new(origins(*g)?)?)], + _ => Vec::new(), }; - let mut on: Vec<(f64, usize)> = candidates - .into_iter() - .filter(|k| *k != a && *k != b) - .filter_map(|k| { - let v = verts.get(k)?; - let t = (*v - pa).dot(d) / len2.max(1e-300); - (t > 1e-9 && t < 1.0 - 1e-9 && v.dist_to_segment(pa, pb) < q).then_some((t, k)) - }) - .collect(); - on.sort_by(|x, y| x.0.total_cmp(&y.0)); - let mut prev = a; - for (_, k) in on { - directed.push((g, prev, k)); - owners.entry((g, prev, k)).or_default().push(li); - prev = k; - } - directed.push((g, prev, b)); - owners.entry((g, prev, b)).or_default().push(li); - } - } - // Interior edges cancel against their reverse within the same plane group. - let mut count: BTreeMap<(usize, usize, usize), i64> = BTreeMap::new(); - for (g, a, b) in &directed { - *count.entry((*g, *a, *b)).or_insert(0) += 1; - } - let mut boundary: Vec<(usize, usize, usize)> = Vec::new(); - for (&(g, a, b), &c) in &count { - let rev = count.get(&(g, b, a)).copied().unwrap_or(0); - for _ in 0..(c - rev).max(0) { - boundary.push((g, a, b)); - } - } - boundary.sort_unstable(); - // Pieces either side of an edge inside a plane group lie in one face. - let mut parent: Vec = (0..loops.len()).collect(); - for ((g, a, b), here) in &owners { - let (Some(there), Some(&first)) = (owners.get(&(*g, *b, *a)), here.first()) else { continue }; - for other in here.iter().chain(there) { - let (rp, rq) = (find(&mut parent, first), find(&mut parent, *other)); - if let Some(slot) = parent.get_mut(rp) { - *slot = rq; - } - } - } - let roots: Vec = (0..loops.len()).map(|li| find(&mut parent, li)).collect(); - let mut joined: BTreeMap> = BTreeMap::new(); - for (root, src) in roots.iter().zip(&srcs) { - joined.entry(*root).or_default().insert(*src); - } - // What lies on each side of each boundary edge (from, to): the faces of its polygons. - let mut side: BTreeMap<(usize, usize), BTreeSet> = BTreeMap::new(); - for (g, a, b) in &boundary { - let set = side.entry((*a, *b)).or_default(); - for li in owners.get(&(*g, *a, *b)).into_iter().flatten() { - set.extend(srcs.get(*li)); - } - } - // The faces of one boundary loop's polygons. - let loop_faces = |g: usize, lp: &[usize]| -> Option> { - let (a, b) = (*lp.first()?, *lp.get(1)?); - let li = *owners.get(&(g, a, b))?.first()?; - joined.get(roots.get(li)?).cloned() - }; - guard("planar boolean rebuild", || { - let mut verts = verts.clone(); - // Every plane group's boundary loops (vertex indices). - let mut all_loops: Vec>> = Vec::new(); - for (g, _) in groups.iter().enumerate() { - let mut segs: Vec<(usize, usize)> = boundary.iter().filter(|e| e.0 == g).map(|e| (e.1, e.2)).collect(); - let mut loops_g: Vec> = Vec::new(); - while let Some((s, t)) = segs.pop() { - let mut lp = vec![s, t]; - let mut cur = t; - let mut guard_n = 0; - while cur != s && guard_n < 100_000 { - guard_n += 1; - let Some(k) = segs.iter().position(|(a, _)| *a == cur) else { break }; - let (_, nb) = segs.remove(k); - lp.push(nb); - cur = nb; - } - if cur == s { - lp.pop(); - // A walk through a vertex twice (two loops touching there) is split into - // simple loops at that vertex. - let mut stack: Vec = Vec::new(); - for v in lp { - if let Some(at) = stack.iter().position(|x| *x == v) { - let sub: Vec = stack.split_off(at); - if sub.len() >= 3 { - loops_g.push(sub); - } - } - stack.push(v); - } - if stack.len() >= 3 { - loops_g.push(stack); - } - } - } - all_loops.push(loops_g); - } - // The original vertex of each vertex index (pinched vertices get copies, below). - let mut orig: Vec = (0..verts.len()).collect(); - split_pinched_vertices(&mut all_loops, &mut verts, &mut orig); - let tv: Vec = verts.iter().map(|v| builder::vertex(p3(*v))).collect(); - let mut edges: BTreeMap<(usize, usize), mt::Edge> = BTreeMap::new(); - let mut faces: Vec = Vec::new(); - let mut face_from: HashMap>> = HashMap::new(); - for (g, plane) in groups.iter().enumerate() { - let Some(loops_g) = all_loops.get(g) else { continue }; - let mut wires: Vec = Vec::new(); - for lp in loops_g { - let n = lp.len(); - let mut es = Vec::with_capacity(n); - for i in 0..n { - let (Some(&a), Some(&b)) = (lp.get(i), lp.get((i + 1) % n)) else { continue }; - let k = (a.min(b), a.max(b)); - let e = match edges.get(&k) { - Some(e) => e.clone(), - None => { - let (Some(va), Some(vb)) = (tv.get(k.0), tv.get(k.1)) else { continue }; - let e = builder::line(va, vb); - edges.insert(k, e.clone()); - e - } - }; - es.push(if a < b { e } else { e.inverse() }); - } - wires.push(es.into()); - } - if wires.is_empty() { - continue; - } - // Outer loops are counter-clockwise about the plane normal; holes go with the - // outer loop that contains them. - let area = |lp: &Vec| -> f64 { - let n = lp.len(); - let mut s = Vec3::ZERO; - for i in 0..n { - if let (Some(a), Some(b)) = (lp.get(i).and_then(|k| verts.get(*k)), lp.get((i + 1) % n).and_then(|k| verts.get(*k))) { - s += a.cross(*b); - } - } - s.dot(plane.n) * 0.5 - }; - let (outer, holes): (Vec, Vec) = (0..loops_g.len()).partition(|i| loops_g.get(*i).is_some_and(|l| area(l) > 0.0)); - let u = plane.n.any_perp(); - let w = plane.n.cross(u); - let to2 = |p: Vec3| (p.dot(u), p.dot(w)); - let inside = |pt: Vec3, lp: &Vec| { - let (px, py) = to2(pt); - let n = lp.len(); - let mut c = false; - for i in 0..n { - let (Some(a), Some(b)) = (lp.get(i).and_then(|k| verts.get(*k)), lp.get((i + 1) % n).and_then(|k| verts.get(*k))) else { - continue; - }; - let ((ax, ay), (bx, by)) = (to2(*a), to2(*b)); - if (ay > py) != (by > py) && px < ax + (py - ay) / (by - ay) * (bx - ax) { - c = !c; - } - } - c - }; - for o in &outer { - let Some(ol) = loops_g.get(*o) else { continue }; - let mut ws = vec![wires.get(*o).cloned().ok_or_else(|| KernelError::Failed("wire".into()))?]; - for h in &holes { - let Some(hl) = loops_g.get(*h) else { continue }; - let probe = hl.first().and_then(|k| verts.get(*k)).copied().unwrap_or_default(); - // The innermost outer loop containing the hole. - let owner = outer.iter().filter(|x| loops_g.get(**x).is_some_and(|l| inside(probe, l))).min_by(|x, y| { - let ax = loops_g.get(**x).map(area).unwrap_or(0.0); - let ay = loops_g.get(**y).map(area).unwrap_or(0.0); - ax.total_cmp(&ay) - }); - if owner == Some(o) { - ws.push(wires.get(*h).cloned().ok_or_else(|| KernelError::Failed("wire".into()))?); - } - } - let from = loop_faces(g, &ol.iter().map(|k| orig.get(*k).copied().unwrap_or(*k)).collect::>()); - // A loop a hair off flat (fine facets of a curved face) takes the group's plane. - let face = match builder::try_attach_plane(&ws) { - Ok(f) => f, - Err(e) => { - let o = plane.n * plane.w; - let surface = mt::Plane::new(p3(o), p3(o + u), p3(o + w)); - mt::Face::try_new(ws, mt::Surface::Plane(surface)) - .map_err(|e2| KernelError::Failed(format!("planar boolean face: {e}; {e2}")))? - } - }; - face_from.insert(face.id(), from); - faces.push(face); - } - } - let shell: mt::Shell = faces.into(); - let parts = components_in_order(&shell); - let solid = Solid::try_new(parts).map_err(|e| KernelError::Failed(format!("planar boolean: {e}")))?; - let regions = solid.face_iter().map(|f| face_from.get(&f.id()).cloned().flatten().map(|o| (o, false))).collect::>>(); - let tol = size * 1e-6; - let edge_from = edges - .iter() - .map(|((a, b), e)| { - let ends = (*verts.get(*a)?, *verts.get(*b)?); - let (a, b) = (orig.get(*a)?, orig.get(*b)?); - let mut origins = BTreeSet::new(); - for p in side.get(&(*a, *b))? { - for q in side.get(&(*b, *a))? { - origins.extend(sources.edge(*p, *q, ends, tol)?); - } - } - Some((e.id(), origins.into_iter().collect())) - }) - .collect::>>>(); - record::build(solid, &sources.counts, regions.map(record::regions), edge_from.as_ref()) - }) -} - -/// A vertex where the solid's surface pinches, as where two blocks meet at one corner only -/// (#679): the faces around it form several fans that share no edge there. Each fan past the -/// first gets its own copy of the vertex (same point), so every vertex of the shell is a -/// manifold one. -fn split_pinched_vertices(loops: &mut [Vec>], verts: &mut Vec, orig: &mut Vec) { - // Every corner: (group, loop, position), by vertex. - let mut corners: BTreeMap> = BTreeMap::new(); - for (g, ls) in loops.iter().enumerate() { - for (li, l) in ls.iter().enumerate() { - for (i, v) in l.iter().enumerate() { - corners.entry(*v).or_default().push((g, li, i)); - } - } - } - let mut renames: Vec<((usize, usize, usize), usize)> = Vec::new(); - let mut ids: Vec = corners.keys().copied().collect(); - ids.sort_unstable(); - for v in ids { - let Some(cs) = corners.get(&v) else { continue }; - if cs.len() < 2 { - continue; - } - // The two neighbours of each corner; corners sharing an edge (v, x) are in one fan. - let nbrs: Vec<[usize; 2]> = cs - .iter() - .map(|(g, li, i)| { - let l = loops.get(*g).and_then(|ls| ls.get(*li)).map(Vec::as_slice).unwrap_or(&[]); - let n = l.len().max(1); - [l.get((i + n - 1) % n).copied().unwrap_or(v), l.get((i + 1) % n).copied().unwrap_or(v)] - }) - .collect(); - let mut parent: Vec = (0..cs.len()).collect(); - for i in 0..cs.len() { - for j in i + 1..cs.len() { - let (Some(a), Some(b)) = (nbrs.get(i), nbrs.get(j)) else { continue }; - if a.iter().any(|x| b.contains(x)) { - let (ri, rj) = (find(&mut parent, i), find(&mut parent, j)); - if let Some(slot) = parent.get_mut(ri) { - *slot = rj; - } - } - } - } - let mut fan_id: BTreeMap = BTreeMap::new(); - for (k, c) in cs.iter().enumerate() { - let root = find(&mut parent, k); - let next = fan_id.len(); - let fan = *fan_id.entry(root).or_insert(next); - if fan > 0 { - // A copy per extra fan. - let copy = verts.len() + fan - 1; - renames.push((*c, copy)); - } - } - let p = verts.get(v).copied().unwrap_or_default(); - for _ in 1..fan_id.len() { - verts.push(p); - orig.push(v); - } - } - for ((g, li, i), new) in renames { - if let Some(slot) = loops.get_mut(g).and_then(|ls| ls.get_mut(li)).and_then(|l| l.get_mut(i)) { - *slot = new; - } - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used)] -mod diagnostic_tests { - use super::*; - - #[test] - fn compound_curved_diagnostics_count_every_surface_kind() { - // Many independent shells exercise the error path without performing a costly - // Boolean. Each cylinder has two analytic half-cylinder walls and two flat caps. - let mut shells = Vec::new(); - for i in 0..64 { - let cylinder = crate::cylinder(Vec3::X * (i as f64 * 6.0), Vec3::Z, 2.0, 5.0).unwrap(); - shells.extend(cylinder.solid.boundaries().iter().cloned()); - } - let sphere = crate::sphere(Vec3::new(0.0, 12.0, 0.0), 2.0).unwrap(); - let sphere_faces = sphere.face_count(); - shells.extend(sphere.solid.boundaries().iter().cloned()); - let body = guard("diagnostic compound", || Body::new(Solid::try_new(shells).unwrap())).unwrap(); - let faces = body.faces(0.02).unwrap(); - let error = face_planes(&body, &faces).err().unwrap(); - let expected = std::collections::BTreeMap::from([("cylinder", 128), ("sphere", sphere_faces)]); - assert_eq!(error, NotPlanar::Curved(expected)); - assert_eq!(error.describe("tool"), format!("the tool has {} curved faces (cylinder, sphere)", 128 + sphere_faces)); - } - - #[test] - fn planar_mesh_inconsistency_does_not_become_curved_classification() { - let body = crate::box_solid(Vec3::ZERO, Vec3::new(4.0, 5.0, 6.0)).unwrap(); - let mut faces = body.faces(0.01).unwrap(); - assert_eq!(face_planes(&body, &faces).unwrap().len(), 6); - faces[0].plane_normal = None; - assert_eq!(face_planes(&body, &faces).err().unwrap(), NotPlanar::Other("face 0 is planar but its mesh is not flat".into())); - faces[0].area = 0.0; - assert_eq!(face_planes(&body, &faces).err().unwrap(), NotPlanar::Other("face 0 could not be meshed".into())); - faces[0].index = 999; - assert_eq!(face_planes(&body, &faces).err().unwrap(), NotPlanar::Other("mesh is inconsistent".into())); - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used)] -mod small_round_tests { - use std::f64::consts::FRAC_PI_2; - - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; - - use super::*; - - /// An `l` x `w` x 1 plate on XY with its four corners rounded (radius `r`), and a hole of - /// diameter 4 through it 100 from one end when `hole`. - fn rounded_plate(l: f64, w: f64, r: f64, hole: bool) -> Body { - let (x, y) = (l / 2.0, w / 2.0); - let corners = [(x - r, y - r), (r - x, y - r), (r - x, r - y), (x - r, r - y)]; - let mut segs = Vec::new(); - for (k, (cx, cy)) in corners.iter().enumerate() { - let start = k as f64 * FRAC_PI_2; - let at = |t: f64| Vec2::new(cx + r * t.cos(), cy + r * t.sin()); - segs.push(Seg2::Arc { center: Vec2::new(*cx, *cy), radius: r, start, sweep: FRAC_PI_2 }); - let (nx, ny) = corners[(k + 1) % 4]; - let next = start + FRAC_PI_2; - segs.push(Seg2::Line { a: at(next), b: Vec2::new(nx + r * next.cos(), ny + r * next.sin()) }); - } - let holes = if hole { vec![Loop2::circle(Vec2::new(x - 100.0, 0.0), 2.0).reversed()] } else { Vec::new() }; - crate::extrude_planar_regions(&Plane::XY, &[Region2 { outer: Loop2 { segs }, holes }], 0.0, 1.0).unwrap() - } - - /// Faces of `b` on cylinders of radius `r`. - fn cylinders(b: &Body, r: f64) -> usize { - (0..b.face_count()) - .filter(|&i| matches!(crate::face_surface(b, i), Some(crate::FaceSurface::Cylinder { radius, .. }) if (radius - r).abs() < 1e-9)) - .count() - } - - /// A pocket cut into the middle of a long plate by the exact fallback leaves the plate's - /// small corner rounds round. Meshed at a thousandth of the 1200 mm plate (1.2 mm), each - /// 2 mm quarter round (its chord 0.59 mm inside the arc) is one flat strip of facets, which - /// was taken for a plane: the whole plate went to the polygon boolean (and, beside a round - /// hole, the rounds went into the planar slab around the pocket), and the rounds came back - /// flat chamfers, each taking r^2 (pi/4 - 1/2) = 1.14 mm^3 more than its round. - #[test] - fn a_long_plates_small_rounds_stay_round_beside_a_pocket() { - for hole in [false, true] { - let plate = rounded_plate(1200.0, 40.0, 2.0, hole); - assert_eq!(cylinders(&plate, 2.0), 4 + 2 * usize::from(hole)); - // 10 x 5, 0.1 deep from the top. - let tool = crate::box_solid(Vec3::new(-5.0, -2.5, 0.9), Vec3::new(5.0, 2.5, 1.0)).unwrap(); - let r = planar_boolean(&plate, &tool, BoolOp::Cut).unwrap().unwrap(); - assert_eq!(cylinders(&r, 2.0), 4 + 2 * usize::from(hole), "hole {hole}"); - // The pocket's 10 x 5 x 0.1 and nothing else (a flattened round takes 1.14 more). - let removed = crate::measure(&plate).unwrap().volume - crate::measure(&r).unwrap().volume; - assert!((removed - 5.0).abs() < 1e-3, "hole {hole}: removed {removed}"); - } - } + Some(EdgeProv { faces: sides, origins: meet }) + }) + .collect::>>()?; + Some(History { operands: 1, faces, edges }) } diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rs index 22ef37f51..543425360 100644 --- a/crates/kernel/src/polyhedron.rs +++ b/crates/kernel/src/polyhedron.rs @@ -1,17 +1,17 @@ -//! Convex polyhedra from planes, and the operations that use them on convex planar bodies: -//! shell (hollow out with open faces) and draft (tilt faces about a neutral plane). The solid -//! is built directly from its planes (vertices are triple-plane intersections), so it is exact -//! and needs no booleans except the final shell subtraction. +//! Convex polyhedra from planes, and the local operations on a body's faces: shell (hollow out +//! with open faces), draft (tilt faces about a neutral plane) and offset faces, which are SMLib's +//! ([`crate::offset_backend`]). A polyhedron is its schema 4 record built directly from its +//! planes (vertices are triple-plane intersections, edges lines, faces planes, pcurves exact), +//! taken by SMLib and checked there. +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use solidcraft_geom::{Plane, Vec3}; -use truck_modeling::{self as mt, builder}; +use solidcore_record::Vec3; +use solidcore_record::brep::{self as rec, Curve2, EdgeUseRef, Loop, OrientedEdge, OrientedFace}; -use crate::body::{Body, Solid, from_p3, p3, v3}; -use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv, History}; -use crate::record; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::{KernelError, Result}; /// A half-space `n · x <= d` (n is the outward unit normal). #[derive(Clone, Copy, Debug)] @@ -77,852 +77,161 @@ fn combinatorics(hs: &[HalfSpace]) -> Result<(Vec, Vec<(usize, Vec) /// The convex polyhedron bounded by the half-spaces. pub fn convex_polyhedron(hs: &[HalfSpace]) -> Result { - polyhedron(hs).map(|(b, _)| b) + let (verts, faces) = combinatorics(hs)?; + crate::smlib_sweeps::body_from_record(&polyhedron_record(hs, &verts, &faces)?, "polyhedron") } -/// [`convex_polyhedron`], with the half-space each of its faces lies on (in face order). -fn polyhedron(hs: &[HalfSpace]) -> Result<(Body, Vec)> { - let (verts, faces_idx) = combinatorics(hs)?; - let on: Vec = faces_idx.iter().map(|(hi, _)| *hi).collect(); - guard("polyhedron", || { - let tv: Vec = verts.iter().map(|v| builder::vertex(p3(*v))).collect(); - let mut edges: HashMap<(usize, usize), mt::Edge> = HashMap::new(); - let mut faces: Vec = Vec::new(); - for (_, f) in &faces_idx { - let n = f.len(); - let mut wire: Vec = Vec::with_capacity(n); - for k in 0..n { - let (Some(&a), Some(&b)) = (f.get(k), f.get((k + 1) % n)) else { continue }; - let key = (a.min(b), a.max(b)); - let e = match edges.get(&key) { - Some(e) => e.clone(), - None => { - let (Some(va), Some(vb)) = (tv.get(key.0), tv.get(key.1)) else { continue }; - let e = builder::line(va, vb); - edges.insert(key, e.clone()); - e +/// The record of the closed polyhedron with corners `verts` whose faces are `faces` (the +/// half-space each lies on, and its corners counter-clockwise about that half-space's outward +/// normal): each face on its plane with the outward normal as the natural one, each edge a line +/// used by its two faces, everything numbered in canonical order (faces as given, edges and +/// vertices as the faces first meet them). +fn polyhedron_record(hs: &[HalfSpace], verts: &[Vec3], faces: &[(usize, Vec)]) -> Result { + let bad = || KernelError::Failed("polyhedron: the planes do not close a solid".into()); + let p = |i: usize| verts.get(i).map(|v| [v.x, v.y, v.z]).ok_or_else(bad); + let scale = verts.iter().map(|v| v.len()).fold(1.0, f64::max); + let tolerance = (scale * 1e-9).max(1e-7); + // Each edge by its corners as first met, with its uses in walking order. + let mut edge_of: HashMap<(usize, usize), u32> = HashMap::new(); + let mut ends: Vec<(usize, usize)> = Vec::new(); + let mut uses: Vec> = Vec::new(); + let mut out = Vec::with_capacity(faces.len()); + for (fi, (hi, cycle)) in faces.iter().enumerate() { + let n = hs.get(*hi).and_then(|h| h.n.normalized()).ok_or_else(bad)?; + let first = cycle.first().ok_or_else(bad)?; + let o = verts.get(*first).copied().ok_or_else(bad)?; + let (u, v) = (n.any_perp(), n.cross(n.any_perp())); + let uv = |q: [f64; 3]| { + let d = Vec3::new(q[0], q[1], q[2]) - o; + [d.dot(u), d.dot(v)] + }; + let (mut lo, mut hi_uv) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + let mut edges = Vec::with_capacity(cycle.len()); + for k in 0..cycle.len() { + let (Some(&a), Some(&b)) = (cycle.get(k), cycle.get((k + 1) % cycle.len())) else { return Err(bad()) }; + let (e, forward) = match edge_of.get(&(b, a)) { + Some(&e) => (e, false), + None => { + if edge_of.contains_key(&(a, b)) { + return Err(bad()); } - }; - wire.push(if a < b { e } else { e.inverse() }); + let e = u32::try_from(ends.len()).map_err(|_| bad())?; + edge_of.insert((a, b), e); + ends.push((a, b)); + uses.push(Vec::new()); + (e, true) + } + }; + let face = u32::try_from(fi).map_err(|_| bad())?; + let position = u32::try_from(k).map_err(|_| bad())?; + uses.get_mut(e as usize).ok_or_else(bad)?.push(EdgeUseRef { face, r#loop: 0, position, upper: !forward }); + let &(s, t) = ends.get(e as usize).ok_or_else(bad)?; + let (ps, pt) = (uv(p(s)?), uv(p(t)?)); + for q in [ps, pt] { + for i in 0..2 { + lo[i] = lo[i].min(q[i]); + hi_uv[i] = hi_uv[i].max(q[i]); + } } - let face = builder::try_attach_plane(&[wire.into()]).map_err(|e| KernelError::Failed(format!("polyhedron face: {e}")))?; - faces.push(face); + // The line in the plane's parameters, on the edge's interval in its direction. + edges.push(OrientedEdge { edge: e, forward, pcurve: Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![ps, pt] } }); } - let shell: mt::Shell = faces.into(); - let solid = Solid::try_new(vec![shell]).map_err(|e| KernelError::Failed(format!("polyhedron: {e}")))?; - Ok((Body::new(solid)?, on)) - }) -} - -/// The half-spaces of a convex body with only planar faces, each with a point on it and the -/// body's faces on its plane (in face order), or an error. -pub fn planar_convex(b: &Body) -> Result)>> { - b.require_brep("this operation")?; - let tol = (b.size() * 1e-3).max(1e-3); - let faces = b.faces(tol)?; - let mut out: Vec<(HalfSpace, Vec3, Vec)> = Vec::new(); - for f in &faces { - let n = f.plane_normal.ok_or_else(|| KernelError::Failed("not supported yet: bodies with curved faces".into()))?; - let d = n.dot(f.centroid); - match out.iter_mut().find(|(h, ..)| h.n.dot(n) > 1.0 - 1e-9 && (h.d - d).abs() < tol) { - Some((.., on)) => on.push(f.index), - None => out.push((HalfSpace { n, d }, f.centroid, vec![f.index])), + let w = |x: Vec3| [x.x, x.y, x.z]; + out.push(rec::Face { + nurbs: None, + surface: rec::Surface::Plane { origin: w(o), u_axis: w(u), v_axis: w(v) }, + domain: [[lo[0], hi_uv[0]], [lo[1], hi_uv[1]]], + loops: vec![Loop::Edges { edges }], + }); + } + // Vertices as the edges first meet them. + let mut vertex_of: HashMap = HashMap::new(); + let mut vertices: Vec = Vec::new(); + let mut edges = Vec::with_capacity(ends.len()); + for ((s, t), uses) in ends.iter().copied().zip(uses) { + if uses.len() != 2 { + return Err(bad()); } + let mut number = |c: usize| -> Result { + if let Some(&i) = vertex_of.get(&c) { + return Ok(i); + } + let i = u32::try_from(vertices.len()).map_err(|_| bad())?; + vertices.push(rec::Vertex { point: p(c)?, tolerance }); + vertex_of.insert(c, i); + Ok(i) + }; + let vs = [number(s)?, number(t)?]; + edges.push(rec::Edge { + nurbs: None, + curve: rec::Curve::Line { start: p(s)?, end: p(t)? }, + interval: [0.0, 1.0], + vertices: vs, + tolerance, + uses, + }); } - let verts: Vec = b.solid.vertex_iter().map(|v| from_p3(v.point())).collect(); - for (h, ..) in &out { - if verts.iter().any(|v| h.n.dot(*v) > h.d + tol) { - return Err(KernelError::Failed("not supported yet: shell and draft of non-convex bodies".into())); - } - } - Ok(out) -} - -/// The faces of `b` on half-space `k`'s plane (`groups[k]`) as the face over them: moved, or -/// merged when several. -fn on_plane(under: &[usize]) -> FaceProv { - record::region(under.iter().map(|&face| FaceOrigin::Face { operand: 0, face }).collect(), false) -} - -/// The edges of `b` between faces on two of its planes (`groups[k]`: its faces on plane `k`), -/// by pair of planes (the lower first). -fn plane_edges(b: &Body, groups: &[Vec]) -> HashMap<(usize, usize), Vec> { - let plane_of: HashMap = groups.iter().enumerate().flat_map(|(k, g)| g.iter().map(move |f| (*f, k))).collect(); - let mut out: HashMap<(usize, usize), Vec> = HashMap::new(); - for (edge, fs) in crate::history::edge_faces(&b.solid).iter().enumerate() { - if let [p, q] = fs[..] - && let (Some(&x), Some(&y)) = (plane_of.get(&p), plane_of.get(&q)) - && x != y - { - out.entry((x.min(y), x.max(y))).or_default().push(edge); - } - } - out -} - -/// The history over `[b]` of a convex polyhedron `poly` whose face `j` lies on the plane of -/// half-space `on[j]`, made from the faces `groups[k]` of `b` on half-space `k`'s plane: each -/// face the faces under it, each edge along the edges of `b` between faces of its two planes, -/// or new where they met nowhere. -fn planes_history(poly: &Body, on: &[usize], groups: &[Vec], b: &Body) -> Option { - let faces: Vec = on.iter().map(|k| groups.get(*k).map(|under| on_plane(under))).collect::>()?; - let along = plane_edges(b, groups); - let mut h = record::from_faces(&poly.solid, 1, faces); - for e in &mut h.edges { - if let [x, y] = e.faces[..] - && let (Some(&kx), Some(&ky)) = (on.get(x), on.get(y)) - && let Some(edges) = along.get(&(kx.min(ky), kx.max(ky))) - { - e.origins = edges.iter().map(|&edge| EdgeOrigin::Edge { operand: 0, edge }).collect(); - } - } - Some(h) -} - -/// The history over `[b]` of a cavity `poly` whose face `j` lies on half-space `on[j]`, moved -/// in from the faces `groups[k]` of `b`: each face an offset of the faces it lines, each edge new. -fn cavity_history(poly: &Body, on: &[usize], groups: &[Vec]) -> Option { - let faces = on - .iter() - .map(|k| groups.get(*k).map(|under| record::generated(under.iter().map(|&face| FaceOrigin::Offset { operand: 0, face }).collect()))) - .collect::>()?; - Some(record::from_faces(&poly.solid, 1, faces)) -} - -/// Hollow a convex planar body: walls of `thickness` inside, faces near `open` removed. The -/// result's history is over `[b]`: the inner walls are offsets of the faces they line. -pub fn shell(b: &Body, open: &[Vec3], thickness: f64) -> Result { - guard("shell", || shell_impl(b, open, thickness)?.with_shell_planar_sources(b, thickness, open)) -} - -fn shell_impl(b: &Body, open: &[Vec3], thickness: f64) -> Result { - b.require_brep("shell")?; - if !(thickness.is_finite() && thickness > 1e-6) { - return Err(KernelError::Invalid("shell thickness must be positive".into())); - } - let hs = match planar_convex(b) { - Ok(h) => h, - Err(_) => return shell_planar(b, open, thickness), + let count = u32::try_from(out.len()).map_err(|_| bad())?; + let brep = rec::Brep { + version: rec::VERSION, + tolerance, + regions: vec![rec::Region { shells: vec![0], void: false }, rec::Region { shells: vec![0], void: false }], + shells: vec![rec::Shell::Faces { faces: (0..count).map(|face| OrientedFace { face, forward: true }).collect(), wires: vec![] }], + faces: out, + edges, + vertices, }; - let size = b.size(); - let inner: Vec = hs - .iter() - .map(|(h, c, _)| { - let removed = open.iter().any(|p| (h.n.dot(*p) - h.d).abs() < size * 1e-4 + 1e-6 && p.dist(*c) < size * 2.0); - if removed { HalfSpace { n: h.n, d: h.d + thickness + size * 0.05 } } else { HalfSpace { n: h.n, d: h.d - thickness } } - }) - .collect(); - if !hs.iter().zip(&inner).any(|((h, ..), i)| i.d > h.d) { - return Err(KernelError::Invalid("select at least one face to remove".into())); - } - let (cavity, on) = polyhedron(&inner)?; - let groups: Vec> = hs.into_iter().map(|(.., under)| under).collect(); - let walls = cavity_history(&cavity, &on, &groups); - let r = crate::ops::boolean(b, &cavity, crate::BoolOp::Cut)?.ok_or_else(|| KernelError::Failed("the shell removed everything".into()))?; - Ok(hollowed(r, b, walls)) + solidcraft_geom::brep::check::validate(&brep).map_err(|e| KernelError::Failed(format!("polyhedron: {e}")))?; + Ok(brep) } -/// `r`, `b` less a cavity whose history over `[b]` is `walls`, with its history over `[b]`. -fn hollowed(r: Body, b: &Body, walls: Option) -> Body { - let h = crate::boolean_record::of_pair(&r, &crate::boolean_record::kept(b, 0, 1), &walls); - r.with_checked_history(h, &record::counts(&[b])) -} - -/// The history over `[b]` of a cavity `offset` made from `b` by moving its faces (whose history -/// over `[b]` says so): each face an offset of the face it was moved from, each edge new. -fn offsets(offset: &Body) -> Option { - let h = offset.history()?; - let faces: Vec = h - .faces - .iter() - .map(|f| match f.origins.as_slice() { - [FaceOrigin::Face { operand, face }] => Some(record::generated(vec![FaceOrigin::Offset { operand: *operand, face: *face }])), - _ => None, - }) - .collect::>()?; - Some(record::from_faces(&offset.solid, h.operands, faces)) +/// Hollow a body: walls of `thickness` inside, open at the faces under `open` (SMLib's shell). +/// The result's history is over `[b]`: the inner walls are offsets of the faces they line. Each +/// kept planar wall and its inner lining carry the outer and inner shell roles of the face they +/// came from (face certificates: sketches and press-pulls attach to them), and the body keeps +/// the lines its faces were split along on purpose. +pub fn shell(b: &Body, open: &[Vec3], thickness: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "shell"); + crate::offset_backend::shell(b, open, thickness)?.inherit_split_lines(&[b]).with_shell_planar_sources(b, thickness, open) } /// Tilt the faces near `faces` by `angle` about their line on the neutral plane, so that they -/// lean in (positive angle) going along `pull`. -pub fn draft(b: &Body, faces: &[Vec3], neutral: &Plane, pull: Vec3, angle: f64) -> Result { +/// lean in (positive angle) going along `pull` (SMLib's draft). +pub fn draft(b: &Body, faces: &[Vec3], neutral: &solidcore_record::Plane, pull: Vec3, angle: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "draft"); b.require_brep("draft")?; - if !angle.is_finite() || angle.abs() >= std::f64::consts::FRAC_PI_2 - 1e-3 { - return Err(KernelError::Invalid("draft angle must be between −90° and 90°".into())); - } - let pull = pull.normalized().ok_or_else(|| KernelError::Invalid("pull direction".into()))?; - let hs = match planar_convex(b) { - Ok(h) => h, - Err(_) => return draft_walls(b, faces, neutral, pull, angle), - }; - let size = b.size(); - let mut out = Vec::new(); - let mut moved = 0; - for (h, c, _) in &hs { - let chosen = faces.iter().any(|p| (h.n.dot(*p) - h.d).abs() < size * 1e-4 + 1e-6 && p.dist(*c) < size * 2.0); - if !chosen { - out.push(*h); - continue; - } - if h.n.dot(pull).abs() > 1e-6 { - return Err(KernelError::Failed("not supported yet: drafting faces that aren't parallel to the pull direction".into())); - } - // Hinge: the face's line on the neutral plane; rotate the normal toward the pull. - let n2 = (h.n * angle.cos() + pull * angle.sin()).normalized().ok_or_else(|| KernelError::Failed("draft".into()))?; - let hinge_pt = - neutral.intersect_ray(*c, pull).ok_or_else(|| KernelError::Failed("the neutral plane is parallel to the pull direction".into()))?; - out.push(HalfSpace { n: n2, d: n2.dot(hinge_pt) }); - moved += 1; - } - if moved == 0 { - return Err(KernelError::Invalid("no faces to draft".into())); - } - // Each half-space in place of the one it was made from: its faces moved (or as they were). - let (r, on) = polyhedron(&out)?; - let groups: Vec> = hs.into_iter().map(|(.., under)| under).collect(); - let h = planes_history(&r, &on, &groups, b); - Ok(r.with_checked_history(h, &record::counts(&[b]))) + crate::offset_backend::draft(b, faces, neutral, pull, angle) } -/// Draft of a non-convex body: walls (planes, cylinders) next to caps square to `pull`. -fn draft_walls(b: &Body, at: &[Vec3], neutral: &Plane, pull: Vec3, angle: f64) -> Result { - let healed = crate::boolean_record::healed(b)?; - let size = healed.size(); - let mesh = healed.tessellate((size * 1e-3).max(1e-3))?; - let mut chosen: Vec = Vec::new(); - for p in at { - let near = mesh - .triangles - .iter() - .zip(&mesh.tri_face) - .filter_map(|(t, f)| mesh.tri(t).map(|[x, y, z]| (point_tri(*p, x, y, z), *f as usize))) - .min_by(|a, c| a.0.total_cmp(&c.0)); - match near { - Some((d, f)) if d < size * 1e-3 + 1e-6 => { - if !chosen.contains(&f) { - chosen.push(f); - } - } - _ => return Err(KernelError::Invalid(format!("no face at {:?}", [p.x, p.y, p.z]))), - } - } - // A round wall is stored in pieces (a cylinder's two halves): picking one drafts the whole wall. - let chosen = crate::offset::with_same_surface(&healed, &chosen); - Ok(record::after(crate::offset::draft_walls(&healed, &chosen, neutral, pull, angle)?, &healed, &record::counts(&[b]))) -} - -/// Round every edge of a convex body with planar faces by `r`: faces shrink, each edge becomes a -/// cylinder and each corner a sphere patch (the body is the inner polyhedron grown by a ball). -/// The result's history is over `[b]`: each cylinder in place of the edges of `b` between its -/// two planes' faces, each corner patch in place of those round its corner. -pub fn round_all_edges(b: &Body, r: f64) -> Result { - let planes = planar_convex(b)?; - let hs: Vec = planes.iter().map(|(h, ..)| *h).collect(); - let groups: Vec> = planes.iter().map(|(.., under)| under.clone()).collect(); - // The edges of `b` between faces on planes f and g. - let edges = plane_edges(b, &groups); - let along = |f: usize, g: usize| -> Vec { - edges.get(&(f.min(g), f.max(g))).into_iter().flatten().map(|&edge| FaceOrigin::Edge { operand: 0, edge }).collect() - }; - let inner: Vec = hs.iter().map(|h| HalfSpace { n: h.n, d: h.d - r }).collect(); - let (q, faces) = combinatorics(&inner)?; - if faces.len() != hs.len() { - return Err(KernelError::Failed("not supported yet: the rounding is larger than a face".into())); - } - let normal = |hi: usize| hs.get(hi).map(|h| h.n).unwrap_or(Vec3::Z); - // Edges of the inner polyhedron: (vertex a, vertex b) → (face left, face right). - let mut edge_faces: HashMap<(usize, usize), Vec> = HashMap::new(); - for (hi, lp) in &faces { - let n = lp.len(); - for k in 0..n { - let (Some(&a), Some(&bb)) = (lp.get(k), lp.get((k + 1) % n)) else { continue }; - edge_faces.entry((a.min(bb), a.max(bb))).or_default().push(*hi); - } - } - if edge_faces.values().any(|f| f.len() != 2) { - return Err(KernelError::Failed("not supported yet: rounding this shape".into())); - } - guard("round edges", || { - // Vertex of face `hi` at inner vertex `qi`. - let mut verts: HashMap<(usize, usize), mt::Vertex> = HashMap::new(); - let mut vert = |hi: usize, qi: usize| -> mt::Vertex { - verts.entry((hi, qi)).or_insert_with(|| builder::vertex(p3(q.get(qi).copied().unwrap_or_default() + normal(hi) * r))).clone() - }; - let mut lines: HashMap<(usize, usize, usize), mt::Edge> = HashMap::new(); - let mut arcs: HashMap<(usize, usize, usize), mt::Edge> = HashMap::new(); - // Straight edge of face hi between inner vertices a and b (stored low → high). - let mut line = |hi: usize, a: usize, bb: usize, vert: &mut dyn FnMut(usize, usize) -> mt::Vertex| -> mt::Edge { - let (lo, hi_v) = (a.min(bb), a.max(bb)); - let e = lines.entry((hi, lo, hi_v)).or_insert_with(|| builder::line(&vert(hi, lo), &vert(hi, hi_v))).clone(); - if a < bb { e } else { e.inverse() } - }; - // Arc at inner vertex qi from face f to face g (stored with f < g). - let mut arc = |qi: usize, f: usize, g: usize, vert: &mut dyn FnMut(usize, usize) -> mt::Vertex| -> mt::Edge { - let (lo, hi_f) = (f.min(g), f.max(g)); - let c = q.get(qi).copied().unwrap_or_default(); - let e = arcs - .entry((qi, lo, hi_f)) - .or_insert_with(|| { - let mid = c + (normal(lo) + normal(hi_f)).normalized().unwrap_or(Vec3::Z) * r; - builder::circle_arc(&vert(lo, qi), &vert(hi_f, qi), p3(mid)) - }) - .clone(); - if f < g { e } else { e.inverse() } - }; - let mut out: Vec = Vec::new(); - // What each face is made from (in `out`'s order). - let mut made: Vec = Vec::new(); - // Planar faces. - for (hi, lp) in &faces { - let n = lp.len(); - let mut w: Vec = Vec::new(); - for k in 0..n { - let (Some(&a), Some(&bb)) = (lp.get(k), lp.get((k + 1) % n)) else { continue }; - w.push(line(*hi, a, bb, &mut vert)); - } - out.push(builder::try_attach_plane(&[w.into()]).map_err(|e| KernelError::Failed(format!("rounded face: {e}")))?); - made.push(on_plane(groups.get(*hi).map_or(&[], Vec::as_slice))); - } - use mt::{ParametricSurface3D, SearchNearestParameter}; - let orient = |mut surf: mt::Surface, at: Vec3, outward: Vec3| -> mt::Surface { - if let Some((u, v)) = surf.search_nearest_parameter(p3(at), None, 100) { - let nn = surf.normal(u, v); - if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); - } - } - surf - }; - // Edge cylinders: face f's loop runs a → b, so the cylinder (to f's right) runs b → a - // along f, then across to g. - for ((a, bb), fs) in &edge_faces { - let (Some(&f0), Some(&f1)) = (fs.first(), fs.get(1)) else { continue }; - // Which face runs a → b? - let runs = |hi: usize| { - faces.iter().find(|(h, _)| *h == hi).is_some_and(|(_, lp)| { - let n = lp.len(); - (0..n).any(|k| lp.get(k) == Some(a) && lp.get((k + 1) % n) == Some(bb)) - }) - }; - let (f, g) = if runs(f0) { (f0, f1) } else { (f1, f0) }; - let w: Vec = - vec![line(f, *bb, *a, &mut vert), arc(*a, f, g, &mut vert), line(g, *a, *bb, &mut vert), arc(*bb, g, f, &mut vert)]; - let (qa, qb) = (q.get(*a).copied().unwrap_or_default(), q.get(*bb).copied().unwrap_or_default()); - let profile = arc(*a, f, g, &mut vert); - let swept = builder::tsweep(&profile, v3(qb - qa)); - let out_dir = (normal(f) + normal(g)).normalized().unwrap_or(Vec3::Z); - let mid = (qa + qb) * 0.5 + out_dir * r; - let surf = orient(swept.oriented_surface(), mid, out_dir); - out.push(mt::Face::try_new(vec![w.into()], surf).map_err(|e| KernelError::Failed(format!("rounded edge: {e}")))?); - made.push(record::generated(along(f, g))); - } - // Corner sphere patches: the faces around each inner vertex, counter-clockwise. - for (qi, c) in q.iter().enumerate() { - let mut around: Vec = faces.iter().filter(|(_, lp)| lp.contains(&qi)).map(|(h, _)| *h).collect(); - let axis = around.iter().fold(Vec3::ZERO, |acc, h| acc + normal(*h)).normalized().unwrap_or(Vec3::Z); - let u = axis.any_perp(); - let w2 = axis.cross(u); - around.sort_by(|x, y| { - let ang = |h: usize| normal(h).dot(w2).atan2(normal(h).dot(u)); - ang(*x).total_cmp(&ang(*y)) - }); - let k = around.len(); - let w: Vec = (0..k).filter_map(|i| Some(arc(qi, *around.get(i)?, *around.get((i + 1) % k)?, &mut vert))).collect(); - // A sphere surface whose poles and seam are away from this patch. - let side = axis.any_perp(); - let (np, sp, back) = (*c + side * r, *c - side * r, *c - axis * r); - let meridian = builder::circle_arc(&builder::vertex(p3(np)), &builder::vertex(p3(sp)), p3(back)); - let surf = - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(meridian.oriented_curve(), p3(*c), v3(side)))); - let surf = orient(surf, *c + axis * r, axis); - out.push(mt::Face::try_new(vec![w.into()], surf).map_err(|e| KernelError::Failed(format!("rounded corner: {e}")))?); - let mut corner: Vec = - (0..k).filter_map(|i| Some((*around.get(i)?, *around.get((i + 1) % k)?))).flat_map(|(f, g)| along(f, g)).collect(); - corner.sort(); - corner.dedup(); - made.push(record::generated(corner)); - } - let shell: mt::Shell = out.into(); - let solid = Solid::try_new(vec![shell]).map_err(|e| KernelError::Failed(format!("rounded body: {e}")))?; - let body = Body::new(solid)?; - // Every face from something of `b` (a blend between planes that met nowhere has none). - let history = made.iter().all(|f| !f.origins.is_empty()).then(|| record::from_faces(&body.solid, 1, made)); - Ok(body.with_checked_history(history, &record::counts(&[b]))) - }) -} - -/// Shell of a body whose faces are all planar (convex or not): every face plane moves inward -/// by the thickness (open faces outward, past the body) keeping the body's topology, which -/// gives the cavity; the shell is the body minus the cavity. -fn shell_planar(b: &Body, open: &[Vec3], thickness: f64) -> Result { - // Face paint and authored splits are construction boundaries. Retain their - // eligibility veto through the temporary body used for the cavity Cut. - // Paint indices stay in source order by avoiding healing in that case. - let healed = - if b.paint().is_some_and(|paint| !paint.faces.is_empty()) { crate::boolean_record::copied(b)? } else { crate::boolean_record::healed(b)? }; - let healed = healed.with_paint(b.paint().cloned()).with_split_lines(b.split_lines().cloned()).inherit_regularization_protection(b); - let size = healed.size(); - let mesh = healed.tessellate((size * 1e-3).max(1e-3))?; - // Faces to open: the face of the triangle nearest each point. - let mut opened: Vec = Vec::new(); - for p in open { - let near = mesh - .triangles - .iter() - .zip(&mesh.tri_face) - .filter_map(|(t, f)| mesh.tri(t).map(|[x, y, z]| (point_tri(*p, x, y, z), *f as usize))) - .min_by(|a, c| a.0.total_cmp(&c.0)); - if let Some((d, f)) = near - && d < size * 1e-3 + 1e-6 - && !opened.contains(&f) - { - opened.push(f); - } - } - if opened.is_empty() { - return Err(KernelError::Invalid("select at least one face to remove".into())); - } - // A successful Boolean is not evidence that a tangential rim has wall thickness. - // Refuse only when the entire planar opening loses its rim. A single collapsed - // round can still end in a valid sharp edge (the tutorial plate, for example). - if let Some(r) = rim_without_thickness(&healed, &opened, thickness, true) { - return Err(unsupported_shell(&format!( - "the rim would have no thickness: an open face meets a round of radius {r:.4} mm tangentially, and the shell is {thickness:.4} mm thick (make the round smaller than the thickness)" - ))); - } - if let Some(shell) = shell_barrel(&healed, &opened, thickness)? { - return Ok(record::after(shell, &healed, &record::counts(&[b]))); - } - let margin = thickness + size * 0.05; - shell_opened(b, &healed, open, &opened, thickness, margin).map_err(|e| match rim_without_thickness(&healed, &opened, thickness, false) { - Some(r) => unsupported_shell(&format!( - "the rim would have no thickness: an open face meets a round of radius {r:.4} mm tangentially, and the shell is {thickness:.4} mm thick (make the round smaller than the thickness)" - )), - None => e, - }) -} - -/// A convex circular-meridian barrel between two axial caps. Sew its exact inset walls -/// to the original walls at annular rims: a Boolean of the two spindle sheets cannot -/// reliably find their cap intersections, and sweeping an inset cap makes a cylindrical -/// lip that cuts away part of the curved wall. -fn shell_barrel(b: &Body, opened: &[usize], thickness: f64) -> Result> { - use crate::offset::Surf; - if b.solid.boundaries().len() != 1 || b.face_count() > 256 { - return Ok(None); - } - let faces: Vec = b.solid.face_iter().cloned().collect(); - let tol = (b.size() * 1e-7).max(1e-9) * 100.0; - let surfs: Option> = faces.iter().map(|f| crate::offset::surf_of(f, tol)).collect(); - let Some(surfs) = surfs else { return Ok(None) }; - let Some((centre, axis, big, radius)) = surfs.iter().find_map(|s| match *s { - Surf::Torus { o, a, big, h, r, convex: true } if big < -tol => Some((o + a * h, a, big, r)), - _ => None, - }) else { - return Ok(None); - }; - let mut caps = Vec::new(); - for (i, s) in surfs.iter().enumerate() { - match *s { - Surf::Torus { o, a, big: ring, h, r, convex: true } - if (o + a * h).dist(centre) < tol && a.dot(axis).abs() > 1.0 - 1e-9 && (ring - big).abs() < tol && (r - radius).abs() < tol => {} - Surf::Plane { n, d } if n.dot(axis).abs() > 1.0 - 1e-9 && faces.get(i).is_some_and(|f| f.boundaries().len() == 1) => { - caps.push((i, (d - n.dot(centre)) / n.dot(axis), n.dot(axis))); - } - _ => return Ok(None), - } - } - if caps.len() != 2 || opened.iter().any(|i| !caps.iter().any(|c| c.0 == *i)) { - return Ok(None); - } - caps.sort_by(|a, b| a.1.total_cmp(&b.1)); - let (Some(&(lower, lo, down)), Some(&(upper, hi, up))) = (caps.first(), caps.get(1)) else { return Ok(None) }; - if down >= 0.0 || up <= 0.0 { - return Ok(None); - } - let lo = lo + if opened.contains(&lower) { 0.0 } else { thickness }; - let hi = hi - if opened.contains(&upper) { 0.0 } else { thickness }; - let inner_radius = radius - thickness; - if lo >= hi || inner_radius <= 0.0 || [lo, hi].iter().any(|z| inner_radius * inner_radius - z * z <= big * big) { - return Err(KernelError::Invalid("shell thickness leaves no barrel cavity".into())); - } - let cavity = offset_planar(b, |i, _| if opened.contains(&i) { 0.0 } else { -thickness })?; - let history = cavity.history().ok_or_else(|| unsupported_shell("the barrel cavity has no face history"))?; - // Every wall must still be the one offset of its source, in source order. No collapsed - // faces or changed topology can be sewn by this construction. - if cavity.face_count() != faces.len() - || history.faces.iter().enumerate().any(|(i, f)| f.origins.as_slice() != [FaceOrigin::Face { operand: 0, face: i }]) - { - return Err(unsupported_shell("the barrel cavity changed topology")); - } - let inner: Vec = cavity.solid.face_iter().cloned().collect(); - let mut out = Vec::new(); - let mut provenance = Vec::new(); - for (i, outer) in faces.iter().enumerate() { - let inset = inner.get(i).ok_or_else(|| unsupported_shell("the barrel cavity lost a face"))?; - if opened.contains(&i) { - let mut wires = outer.absolute_boundaries().to_vec(); - wires.extend(inset.absolute_boundaries().iter().map(|w| w.inverse())); - let mut rim = mt::Face::try_new(wires, outer.surface()).map_err(|e| KernelError::Failed(format!("shell rim: {e}")))?; - if !outer.orientation() { - rim.invert(); - } - out.push(rim); - provenance.push(record::from_face(0, i, Change::Modified)); - } else { - out.extend([outer.clone(), inset.inverse()]); - provenance.extend([record::from_face(0, i, Change::Kept), record::generated(vec![FaceOrigin::Offset { operand: 0, face: i }])]); - } - } - let solid = Solid::try_new(vec![out.into()]).map_err(|e| KernelError::Failed(format!("shell barrel: {e}")))?; - let copies = record::edges_by_identity(&cavity, history).filter_map(|(id, origins)| origins.into_iter().next().map(|o| (id, o))).collect(); - record::attach(Body::new(solid)?, &[record::Operand::new(b)], Some(provenance), copies).map(Some) -} - -/// The radius of a convex round (cylinder or torus) that meets an open face tangentially and -/// is at least `thickness`: the cavity's wall then passes through the rim where the round meets -/// the open face, leaving nothing between them. -fn rim_without_thickness(b: &Body, opened: &[usize], thickness: f64, whole_rim: bool) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let faces: Vec<&mt::Face> = b.solid.face_iter().take(if whole_rim { 4097 } else { usize::MAX }).collect(); - let tol = (b.size() * 1e-7).max(1e-9) * 100.0; - // A distant shell can make the body's tolerance larger than this wall. - // Such a diagnostic candidate is not sufficient to refuse a valid opening. - if whole_rim && tol > thickness * 1e-3 { - return None; - } - opened.iter().filter_map(|fi| faces.get(*fi)).find_map(|open| { - let plane = crate::offset::surf_of(open, tol)?; - if whole_rim && (!matches!(plane, crate::offset::Surf::Plane { .. }) || faces.len() > 4096 || open.edge_iter().take(1025).count() > 1024) { - return None; - } - let radius = |edge: &mt::Edge| { - faces.iter().filter(|g| !std::ptr::eq(**g, *open)).find_map(|g| { - if !g.edge_iter().any(|e| e.id() == edge.id()) { - return None; - } - let round = crate::offset::surf_of(g, tol)?; - let r = match round { - crate::offset::Surf::Cylinder { r, convex: true, .. } | crate::offset::Surf::Torus { r, convex: true, .. } => r, - _ => return None, - }; - let c = edge.curve(); - let (t0, t1) = c.range_tuple(); - if !t0.is_finite() || !t1.is_finite() || t0 >= t1 { - return None; - } - let parameter = t0 * 0.5 + t1 * 0.5; - if !parameter.is_finite() || parameter < t0 || parameter > t1 { - return None; - } - let mid = from_p3(c.subs(parameter)); - let tangent = plane.normal(mid)?.dot(round.normal(mid)?) > 1.0 - 1e-6; - (tangent && r >= thickness - tol).then_some(r) - }) - }; - if whole_rim { - let mut found = None; - for edge in open.edge_iter() { - found = Some(radius(&edge)?); - } - found - } else { - open.edge_iter().find_map(|edge| radius(&edge)) - } - }) -} - -fn shell_opened(b: &Body, healed: &Body, open: &[Vec3], opened: &[usize], thickness: f64, margin: f64) -> Result { - let size = healed.size(); - // Open faces pushed out past the body: the simple way, unless a face tangent to an open - // one (a fillet along its edge) can't follow; then every face moves in (tangencies keep) - // and the opening is the open face's copy swept out through the body. - let cavity = match offset_planar(healed, |fi, _| if opened.contains(&fi) { margin } else { -thickness }) { - Ok(c) => c, - Err(e) => return shell_by_opening(healed, opened, thickness, margin).map_err(|_| e), - }; - let cavity = match opening_overreach(healed, &cavity, opened, thickness, margin) { - Ok(Some(trimmed)) => trimmed, - Ok(None) => cavity, - Err(e) => { - log::warn!("shell: could not trim the opening to the open faces ({e}); the wall next to it may be cut"); - cavity - } - }; - let r = crate::ops::boolean(healed, &cavity, crate::BoolOp::Cut); - if r.is_err() - && let Ok(x) = shell_by_opening(healed, opened, thickness, margin) - { - return Ok(x); - } - match r { - Ok(Some(r)) => { - // Over `[healed]`, the cavity's faces offsets of the faces they line; then over `[b]`. - Ok(record::after(hollowed(r, healed, offsets(&cavity)), healed, &record::counts(&[b]))) - } - Ok(None) => Err(KernelError::Failed("the shell removed everything".into())), - // Healing can leave faces the boolean dislikes (revolved patches): the body as it was, - // its faces to open found again. - Err(e) => { - let raw = b.tessellate((size * 1e-3).max(1e-3)).map_err(|_| e.clone())?; - let mut opened_raw: Vec = Vec::new(); - for p in open { - let near = raw - .triangles - .iter() - .zip(&raw.tri_face) - .filter_map(|(t, f)| raw.tri(t).map(|[x, y, z]| (point_tri(*p, x, y, z), *f as usize))) - .min_by(|a, c| a.0.total_cmp(&c.0)); - if let Some((d, f)) = near - && d < size * 1e-3 + 1e-6 - && !opened_raw.contains(&f) - { - opened_raw.push(f); - } - } - let opened = opened_raw; - let cavity = offset_planar(b, |fi, _| if opened.contains(&fi) { margin } else { -thickness }).map_err(|_| e.clone())?; - let r = crate::ops::boolean(b, &cavity, crate::BoolOp::Cut) - .map_err(|_| e)? - .ok_or_else(|| KernelError::Failed("the shell removed everything".into()))?; - Ok(hollowed(r, b, offsets(&cavity))) - } - } -} - -/// The cavity with each open face pushed out (`cavity`), trimmed so that beyond an open face's -/// plane it only reaches through the open face itself; `None` when it already does. -/// -/// The pushed-out face carries the cavity past every edge of the open face. Past a convex edge -/// that is outside the body, but past a concave one (a box on a box, its side face open where it -/// meets the lower box's top) it runs on into the neighbouring wall and cuts a strip through it, -/// as wide as the push. The trimmed cavity is the shell's cavity with every face moved in, -/// together with the pushed-out cavity's parts that are on the body's side of every open face's -/// plane or in front of that open face. -fn opening_overreach(healed: &Body, cavity: &Body, opened: &[usize], thickness: f64, margin: f64) -> Result> { - let size = healed.size(); - let tol = size * 1e-6 + 1e-9; - let faces: Vec = healed.solid.face_iter().cloned().collect(); - // Each open face's plane (outward normal, offset) and its triangles. - let mesh = healed.tessellate((size * 1e-3).max(1e-3))?; - let mut open: Vec<(&mt::Face, Vec3, f64, Vec<[Vec3; 3]>)> = Vec::new(); - for fi in opened { - let Some(f) = faces.get(*fi) else { return Ok(None) }; - let mt::Surface::Plane(pl) = f.oriented_surface() else { return Ok(None) }; - let n = pl.normal(); - let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return Ok(None) }; - let d = n.dot(from_p3(pl.origin())); - let tris: Vec<[Vec3; 3]> = - mesh.triangles.iter().zip(&mesh.tri_face).filter(|(_, f)| **f as usize == *fi).filter_map(|(t, _)| mesh.tri(t)).collect(); - if tris.is_empty() { - return Ok(None); - } - open.push((f, n, d, tris)); - } - // Only a corner of the cavity past an open face's plane and not in front of that face can be - // in a wall; with none, the cavity is right as it is. - let overreach = cavity.solid.vertex_iter().any(|v| { - let q = from_p3(v.point()); - open.iter().any(|(_, n, d, tris)| { - let h = n.dot(q) - d; - h > tol && { - let on = q - *n * h; - !tris.iter().any(|[a, b, c]| point_tri(on, *a, *b, *c) < size * 1e-4 + 1e-6) - } - }) - }); - if !overreach { - return Ok(None); - } - let closed = offset_planar(healed, |_, _| -thickness)?; - // Keep: on the body's side of each open plane, or in front of the open face. - let reach = size * 4.0; - let mut keep: Option = None; - for (f, n, d, _) in &open { - let c = *n * *d; - let mut hs = vec![HalfSpace { n: *n, d: *d }]; - for axis in [Vec3::X, Vec3::Y, Vec3::Z] { - hs.push(HalfSpace { n: axis, d: axis.dot(c) + reach }); - hs.push(HalfSpace { n: axis * -1.0, d: -axis.dot(c) + reach }); - } - let (side, _) = polyhedron(&hs)?; - // In front of the face: its prism, from half a wall inside the body (overlapping `side` - // rather than touching it) to past the pushed-out face. - let inset = thickness * 0.5; - let prism = guard("shell opening prism", || { - let start = builder::translated(*f, v3(*n * -inset)); - let solid: Solid = builder::tsweep(&start, v3(*n * (inset + margin * 2.0))); - Ok(solid) - })?; - let prism = Body::new(prism)?; - let k = crate::ops::boolean(&side, &prism, crate::BoolOp::Union)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?; - keep = Some(match keep { - None => k, - Some(acc) => crate::ops::boolean(&acc, &k, crate::BoolOp::Intersect)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?, - }); - } - let Some(keep) = keep else { return Ok(None) }; - let kept = crate::ops::boolean(cavity, &keep, crate::BoolOp::Intersect)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?; - let trimmed = crate::ops::boolean(&closed, &kept, crate::BoolOp::Union)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?; - Ok(Some(trimmed)) -} - -/// A shell made from the cavity with every face moved in by the thickness (open faces too), -/// joined with each open face's moved copy swept out through the body. No history: the -/// opening's walls, swept from the cavity's edges, come from nothing of `b`. -fn shell_by_opening(b: &Body, opened: &[usize], thickness: f64, reach: f64) -> Result { - let closed = offset_planar(b, |_, _| -thickness)?; - let faces: Vec = closed.solid.face_iter().cloned().collect(); - let mut cavity = closed.clone(); - for fi in opened { - let f = faces.get(*fi).ok_or_else(|| KernelError::Failed("shell: open face".into()))?; - let mt::Surface::Plane(pl) = f.oriented_surface() else { - return Err(unsupported_shell("the open face must be planar here")); - }; - let n = pl.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized().ok_or_else(|| KernelError::Failed("shell: open face normal".into()))?; - let prism = guard("shell opening", || { - let solid: Solid = builder::tsweep(f, v3(n * (thickness + reach))); - Ok(solid) - })?; - let prism = Body::new(prism)?; - cavity = crate::ops::boolean(&cavity, &prism, crate::BoolOp::Union)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?; - } - let r = crate::ops::boolean(b, &cavity, crate::BoolOp::Cut)?.ok_or_else(|| KernelError::Failed("the shell removed everything".into()))?; - Ok(r.without_history()) -} - -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 { - let n = (b - a).cross(c - a); - let Some(nn) = n.normalized() else { return f64::INFINITY }; - let h = (p - a).dot(nn); - let q = p - nn * h; - let inside = [(a, b), (b, c), (c, a)].iter().all(|(u, v)| (*v - *u).cross(q - *u).dot(n) >= -1e-12); - if inside { h.abs() } else { [(a, b), (b, c), (c, a)].iter().map(|(u, v)| p.dist_to_segment(*u, *v)).fold(f64::INFINITY, f64::min) } -} - -/// The body with every planar face moved along its outward normal by `shift(face index, -/// normal)`, keeping the topology: each vertex goes to where its faces' moved planes meet. -pub(crate) fn offset_planar(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Result { - crate::offset::offset_body(b, shift) -} - -pub(crate) fn solve3_pub(m: [[f64; 3]; 3], r: [f64; 3]) -> Option<[f64; 3]> { - solve3(m, r) -} - -fn solve3(m: [[f64; 3]; 3], r: [f64; 3]) -> Option<[f64; 3]> { - let det = |a: [[f64; 3]; 3]| { - a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) - + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) - }; - let d = det(m); - if d.abs() < 1e-9 { - return None; - } - let mut out = [0.0; 3]; - for (k, o) in out.iter_mut().enumerate() { - let mut mk = m; - for (row, rv) in mk.iter_mut().zip(r) { - row[k] = rv; - } - *o = det(mk) / d; - } - Some(out) -} - -/// The faces of `body` the given points pick, each whole (every piece of its surface). -/// -/// Taken per body rather than once, because an operation may be tried again on the same body -/// with a face split in two, and the pieces are numbered differently then. The points do not -/// move, so they pick the same surface either way. -fn faces_at(body: &Body, at: &[Vec3]) -> Result> { - let size = body.size(); - let mesh = body.tessellate((size * 1e-3).max(1e-3))?; - let mut chosen: Vec = Vec::new(); - for p in at { - let near = mesh - .triangles - .iter() - .zip(&mesh.tri_face) - .filter_map(|(t, f)| mesh.tri(t).map(|[x, y, z]| (point_tri(*p, x, y, z), *f as usize))) - .min_by(|a, c| a.0.total_cmp(&c.0)); - match near { - Some((d, f)) if d < size * 1e-3 + 1e-6 => { - if !chosen.contains(&f) { - chosen.push(f); - } - } - _ => return Err(KernelError::Invalid(format!("no face at {:?}", [p.x, p.y, p.z]))), - } - } - Ok(crate::offset::with_same_surface(body, &chosen)) -} - -/// Move the planar faces at the given points along their outward normals by `distance` -/// (negative: into the body). The body's other faces follow (its topology is kept). +/// Move the faces at the given points along their outward normals by `distance` (negative: into +/// the body), SMLib's offset of faces: the faces around them are extended or trimmed to meet them. pub fn offset_faces(b: &Body, at: &[Vec3], distance: f64) -> Result { + let _span = solidcraft_profile::span("kernel", "offset_faces"); b.require_brep("offset faces")?; if !distance.is_finite() || distance.abs() > 1e6 { return Err(KernelError::Invalid("offset distance".into())); } - // Healing is part of the attempt, not a step before it: a face that runs along a seam edge - // twice fails there, and the retry below needs the whole of it to run on the split body. - let run = |body: &Body| -> Result { - let healed = crate::boolean_record::healed(body)?.with_split_lines(body.splits.clone()); - let chosen = faces_at(&healed, at)?; - match offset_planar(&healed, |fi, _| if chosen.contains(&fi) { distance } else { 0.0 }) { - Ok(r) => Ok(record::after(r, &healed, &record::counts(&[body]))), - // A piece of a split face (its neighbour stays): the piece swept along its normal - // joins on (outward) or cuts in, with walls along the split lines. - Err(e) if !healed.split_keep().is_empty() => press_pieces(&healed, &chosen, distance).map_err(|_| e), - Err(e) => Err(e), + let healed = crate::boolean_record::healed(b)?.with_split_lines(b.splits.clone()); + let size = healed.size(); + let mesh = healed.mesh(&crate::MeshTolerance::chord((size * 1e-3).max(1e-3)))?; + let mut chosen: Vec = Vec::new(); + for p in at { + let near = mesh + .triangles + .iter() + .zip(&mesh.tri_face) + .filter_map(|(t, f)| mesh.tri(t).map(|[x, y, z]| (solidcraft_geom::compare::closest_on_triangle(*p, x, y, z).dist(*p), *f as usize))) + .min_by(|a, c| a.0.total_cmp(&c.0)); + match near { + Some((d, f)) if d < size * 1e-3 + 1e-6 => { + if !chosen.contains(&f) { + chosen.push(f); + } + } + _ => return Err(KernelError::Invalid(format!("no face at {:?}", [p.x, p.y, p.z]))), } - }; - match crate::guard("offset faces", || run(b)) { - Ok(r) => Ok(r), - // A face that runs along a seam edge twice — a hole's wall as a STEP file writes it, one - // whole turn bounded by one wire. Healing it, or moving its neighbour, fails where the - // same body with that face in two halves works, so split it and ask again, which is what - // a boolean already does (`seam_faces`). - Err(e) => match crate::seam_faces::one_body(b, "offset faces off their seams", &run) { - Some(Ok(r)) => Ok(r), - _ => Err(e), - }, - } -} - -/// No history: the walls along the split lines are swept from edges, and come from nothing of -/// `b`. -fn press_pieces(b: &Body, chosen: &[usize], distance: f64) -> Result { - let faces: Vec = b.solid.face_iter().cloned().collect(); - let mut cur = b.clone(); - for fi in chosen { - let f = faces.get(*fi).ok_or_else(|| KernelError::Failed("offset: face".into()))?; - let n = crate::blend::plane_normal(f).ok_or_else(|| KernelError::Failed("offset: only planar pieces".into()))?; - let tool = guard("offset face", || Body::new(builder::tsweep(f, crate::body::v3(n * distance))))?; - let op = if distance > 0.0 { crate::BoolOp::Union } else { crate::BoolOp::Cut }; - cur = crate::ops::boolean(&cur, &tool, op)?.ok_or_else(|| KernelError::Failed("offset: the piece moved off the body".into()))?; - } - Ok(cur.with_split_lines(b.splits.clone()).without_history()) -} - -#[cfg(test)] -mod rim_preflight_tests { - use super::*; - - #[test] - fn a_distant_shell_does_not_turn_a_smaller_local_round_into_a_zero_rim() { - let block = crate::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(); - let edges = [Vec3::new(20.0, 0.0, 0.0), Vec3::new(40.0, 15.0, 0.0), Vec3::new(20.0, 30.0, 0.0), Vec3::new(0.0, 15.0, 0.0)]; - let rounded = crate::fillet(&block, &edges, 1.5).unwrap(); - let distant = crate::box_solid(Vec3::new(1_000_000.0, 0.0, 0.0), Vec3::new(1_000_010.0, 10.0, 10.0)).unwrap(); - let combined = crate::boolean(&rounded, &distant, crate::BoolOp::Union).unwrap().unwrap(); - let faces: Vec<_> = (0..combined.solid.face_iter().count()).collect(); - assert!(rim_without_thickness(&combined, &faces, 2.0, true).is_none()); } + let chosen = crate::offset::with_same_surface(&healed, &chosen); + let moved = crate::offset_backend::offset_faces(&healed, &chosen, distance)?; + Ok(crate::record::after(moved, &healed, &crate::record::counts(&[b]))) } diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rs index f6dabc76b..9a1386b99 100644 --- a/crates/kernel/src/prism.rs +++ b/crates/kernel/src/prism.rs @@ -1,2604 +1,299 @@ -//! Booleans of prisms in 2D: when the target is a prism (two caps square to one direction, -//! walls of planes and cylinders along it) and the tool a prism along the same direction -//! spanning the target's height, the result is the prism over the 2D boolean of their -//! sections. Hole-free intersections may instead use the common height interval. Plates with holes, slots and patterns of them: exact, and immune to the mesh -//! intersection's trouble with walls meeting along lines. -//! Stepped extrusions (case floors and walls) use sections between every cap level, so a -//! circular boss can meet the rim without shifting either operand off its exact plane. +//! Booleans of planar regions (lines, circular arcs and free-form curves) and the extrusion of +//! planar material from them, both on SMLib's 2D boolean: each operand a sheet of planar faces +//! built from its loops' own curves, combined as regions of the plane, its faces read back. The +//! result's boundaries are the operands' curves, cut at their crossings and never refitted. +//! Also the test of whether a record surface is a wall swept along a direction. -use std::borrow::Cow; +use solidcore_record::{Plane, Region2, Seg2, Vec2}; +use solidcraft_geom::prelude::*; -use solidcraft_geom::{Aabb2, Loop2, Plane, Region2, Seg2, Vec2, Vec3}; -use truck_modeling as mt; - -use crate::body::{Body, from_p3}; +use crate::body::Body; use crate::{BoolOp, KernelError, Result}; -#[path = "prism_lineage.rs"] -mod lineage; - -#[cfg(test)] -#[path = "prism_spline_tests.rs"] -mod spline_tests; - const MAX_PLANAR_SEGMENTS: usize = 8192; -const MAX_PLANAR_EVENTS: usize = 131_072; -const MAX_PLANAR_PAIRS: usize = 16_000_000; -/// Free-form boundary segments (conics, Béziers) take part in planar booleans as lines and -/// arcs within this distance (mm); loops that come out whole get their exact segments back. +/// How far a free-form boundary may be replaced by lines and arcs where a caller needs lines and +/// arcs only (sheet metal's flat patterns, mm). The booleans here keep free-form curves exact. pub const PLANAR_FIT_TOL: f64 = 1e-3; -/// Boolean of planar regions bounded by straight lines, circular arcs and free-form segments. -/// Lines and arcs stay analytic. Free-form loops are arranged as tangent arcs within -/// [`PLANAR_FIT_TOL`]: a loop the operation leaves whole comes back exact, one it cuts keeps -/// the arcs. Disjoint results and retained islands are returned as separate regions. +/// Boolean of planar regions bounded by straight lines, circular arcs and free-form segments, +/// exact: every boundary of the result is a piece of a boundary of `a` or `b`, cut where it +/// crosses the other (SMLib's 2D boolean). Disjoint results and retained islands are returned as +/// separate regions. `tolerance` (mm, 1e-9 to 1) is how far apart a loop's segments may end and +/// still close it. pub fn planar_regions_boolean(a: &[Region2], b: &[Region2], op: BoolOp, tolerance: f64) -> Result> { crate::guard("planar region boolean", || { if !tolerance.is_finite() || !(1e-9..=1.0).contains(&tolerance) { return Err(KernelError::Invalid("planar boolean tolerance must be finite and between 1e-9 and 1 mm".into())); } - let mut exact: Vec<(Loop2, Loop2)> = Vec::new(); - let mut pieces = 0usize; - let (a, b) = (fit_free_form(a, &mut exact, &mut pieces)?, fit_free_form(b, &mut exact, &mut pieces)?); - let (a, b): (&[Region2], &[Region2]) = (&a, &b); - let loops = || a.iter().chain(b).flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)); - let mut edges = 0usize; - let mut samples = 0usize; - for lp in loops() { - edges = edges.saturating_add(lp.segs.len()); - if edges > MAX_PLANAR_SEGMENTS || lp.segs.is_empty() || !lp.is_closed(tolerance * 10.0) { - return Err(KernelError::Invalid("planar boolean needs closed loops within its geometry budget".into())); - } - for s in &lp.segs { - let finite = |p: Vec2| p.x.is_finite() && p.y.is_finite() && p.x.abs() < 1e9 && p.y.abs() < 1e9; - let valid = match *s { - Seg2::Line { a, b } => finite(a) && finite(b) && a.dist(b) > 1e-12, - Seg2::Arc { center, radius, start, sweep } => { - finite(center) - && radius.is_finite() - && radius > 0.0 - && radius < 1e9 - && start.is_finite() - && sweep.is_finite() - && sweep.abs() > 1e-12 - && sweep.abs() <= std::f64::consts::TAU + 1e-9 - } - _ => false, - }; - if !valid { - return Err(KernelError::Invalid("planar boolean supports finite nondegenerate lines and circular arcs".into())); - } - samples = samples.saturating_add(s.polyline(1e-3).len()); - if samples > 65_536 { - return Err(KernelError::Invalid("planar boolean sampled geometry exceeds its budget".into())); - } - } + check_regions(a.iter().chain(b), tolerance)?; + match (a.is_empty(), b.is_empty(), op) { + (true, _, BoolOp::Union) => return Ok(b.to_vec()), + (true, _, _) | (false, true, BoolOp::Intersect) => return Ok(Vec::new()), + (false, true, _) => return Ok(a.to_vec()), + _ => {} } - let out = boolean2d(a, b, op, tolerance) - .ok_or_else(|| KernelError::Failed("planar region arrangement failed or exceeded its bounded processing budget".into()))?; - Ok(restore_exact_loops(out, &exact, tolerance)) + let r = sheets::combine(&sheets::sheet(a, tolerance)?, &sheets::sheet(b, tolerance)?, op)?; + Ok(match r { + Some(sheet) => sheets::regions(&sheet, tolerance)?.regions, + None => Vec::new(), + }) }) } -/// Regions with their free-form loops fitted by lines and arcs; `exact` records each fitted -/// loop with the loop it stands for, `pieces` counts the fitted segments. Regions of lines and -/// arcs alone are passed on as they are. -fn fit_free_form<'a>(regions: &'a [Region2], exact: &mut Vec<(Loop2, Loop2)>, pieces: &mut usize) -> Result> { - if regions.iter().all(Region2::is_line_arc) { - return Ok(Cow::Borrowed(regions)); - } - let mut fit = |lp: &Loop2| -> Result { - if lp.is_line_arc() { - return Ok(lp.clone()); +/// Each loop closed within ten times `tol` and within the segment budget, each segment finite +/// and of some length (a line's ends apart, an arc of a positive radius turning at most once). +fn check_regions<'a>(regions: impl Iterator, tol: f64) -> Result<()> { + let mut edges = 0usize; + for lp in regions.flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)) { + edges = edges.saturating_add(lp.segs.len()); + if edges > MAX_PLANAR_SEGMENTS || lp.segs.is_empty() || !lp.is_closed(tol * 10.0) { + return Err(KernelError::Invalid("planar boolean needs closed loops within its geometry budget".into())); } - let fitted = lp.fit_arcs(PLANAR_FIT_TOL).filter(|f| { - *pieces = pieces.saturating_add(f.segs.len()); - *pieces <= MAX_PLANAR_SEGMENTS - }); - let fitted = fitted.ok_or_else(|| { - KernelError::Invalid("planar boolean: a free-form boundary is not finite or takes more arcs than the geometry budget".into()) - })?; - exact.push((fitted.clone(), lp.clone())); - Ok(fitted) - }; - let fitted: Result> = - regions.iter().map(|r| Ok(Region2 { outer: fit(&r.outer)?, holes: r.holes.iter().map(&mut fit).collect::>()? })).collect(); - fitted.map(Cow::Owned) -} - -/// Output loops that are a fitted free-form loop, whole (from any start, either way round), get -/// the exact loop back, running the same way. -fn restore_exact_loops(regions: Vec, exact: &[(Loop2, Loop2)], tol: f64) -> Vec { - if exact.is_empty() { - return regions; - } - let near = |p: Vec2, q: Vec2| p.dist(q) <= tol * 10.0; - let same_run = |l: &Loop2, f: &Loop2| -> bool { - let n = f.segs.len(); - let Some(first) = l.segs.first() else { return false }; - (0..n).any(|k| { - f.segs.get(k).is_some_and(|s| near(s.start(), first.start())) - && l.segs.iter().enumerate().all(|(i, s)| { - f.segs.get((k + i) % n).is_some_and(|g| near(g.start(), s.start()) && near(g.end(), s.end()) && near(g.mid(), s.mid())) - }) - }) - }; - let restore = |l: Loop2| -> Loop2 { - for (fitted, original) in exact { - if fitted.segs.len() != l.segs.len() { - continue; - } - if same_run(&l, fitted) { - return original.clone(); - } - if same_run(&l, &fitted.reversed()) { - return original.reversed(); + let finite = |p: Vec2| p.x.is_finite() && p.y.is_finite() && p.x.abs() < 1e9 && p.y.abs() < 1e9; + for s in &lp.segs { + let valid = match *s { + Seg2::Line { a, b } => finite(a) && finite(b) && a.dist(b) > 1e-12, + Seg2::Arc { center, radius, start, sweep } => { + finite(center) + && radius.is_finite() + && radius > 0.0 + && radius < 1e9 + && start.is_finite() + && sweep.is_finite() + && sweep.abs() > 1e-12 + && sweep.abs() <= std::f64::consts::TAU + 1e-9 + } + Seg2::Cubic { p0, p1, p2, p3 } => [p0, p1, p2, p3].into_iter().all(finite) && p0.dist(p3) > 1e-12, + Seg2::Conic { a, apex, b, w } => [a, apex, b].into_iter().all(finite) && w.is_finite() && w > 1e-9 && a.dist(b) > 1e-12, + Seg2::Bezier { n, ref p } => { + p.get(..=usize::from(n)).is_some_and(|p| p.iter().copied().all(finite)) && s.start().dist(s.end()) > 1e-12 + } + }; + if !valid { + let what = if s.is_line_or_arc() { "lines and circular arcs" } else { "free-form segments" }; + return Err(KernelError::Invalid(format!("planar boolean supports finite nondegenerate {what}"))); } } - l - }; - regions.into_iter().map(|r| Region2 { outer: restore(r.outer), holes: r.holes.into_iter().map(&restore).collect() }).collect() + } + Ok(()) } /// Extrude normalized planar material as one logical compound, retaining every disjoint -/// region and its holes. Planar arrangement certifies separation before shells are joined. +/// region and its holes. The regions are united in the plane first (overlapping ones merge), +/// and pieces of the union that touch each other are refused: apart, +/// each is extruded on its own and the solids joined as one body. pub fn extrude_planar_regions(plane: &Plane, regions: &[Region2], start: f64, end: f64) -> Result { crate::guard("planar material extrusion", || { - // Validate aggregate inputs first; an arrangement compares opposite operands, - // so regions in the same operand must be normalized through balanced unions. - planar_regions_boolean(regions, &[], BoolOp::Union, 1e-7)?; - let mut groups: Vec> = regions.iter().cloned().map(|r| vec![r]).collect(); - let mut remaining_pairs = 32_000_000usize; - while groups.len() > 1 { - let mut next = Vec::new(); - let mut iter = groups.into_iter(); - while let Some(a) = iter.next() { - if let Some(b) = iter.next() { - let count = |rs: &[Region2]| { - rs.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).fold(0usize, |n, l| n.saturating_add(l.segs.len())) - }; - remaining_pairs = remaining_pairs - .checked_sub(count(&a).saturating_mul(count(&b))) - .ok_or_else(|| KernelError::Invalid("planar extrusion arrangement exceeds its work budget".into()))?; - next.push(planar_regions_boolean(&a, &b, BoolOp::Union, 1e-7)?); - } else { - next.push(a); - } - } - groups = next; - } - let normalized = groups.pop().unwrap_or_default(); - if normalized.is_empty() { + check_regions(regions.iter(), 1e-7)?; + if regions.is_empty() { return Err(KernelError::Invalid("empty planar material extrusion".into())); } - // The separation test knows lines and arcs: free-form loops take part as their arcs. - let fitted = fit_free_form(&normalized, &mut Vec::new(), &mut 0)?; - for (i, a) in fitted.iter().enumerate() { - for b in fitted.iter().skip(i + 1) { - for s in std::iter::once(&a.outer).chain(&a.holes).flat_map(|l| &l.segs) { - for t in std::iter::once(&b.outer).chain(&b.holes).flat_map(|l| &l.segs) { - remaining_pairs = remaining_pairs - .checked_sub(1) - .ok_or_else(|| KernelError::Invalid("planar extrusion separation exceeds its work budget".into()))?; - let endpoints_touch = [s.start(), s.end()].iter().any(|p| t.point_at(closest_param(t, *p)).dist(*p) <= 1e-7) - || [t.start(), t.end()].iter().any(|p| s.point_at(closest_param(s, *p)).dist(*p) <= 1e-7); - if endpoints_touch || !crossings(s, t, 1e-7).is_empty() { - return Err(KernelError::Invalid("planar material pieces touch at a boundary".into())); - } - } - } - } + // One sheet of all the regions: their material united, so overlapping ones merge. + let union = sheets::sheet(regions, 1e-7)?; + let united = sheets::regions(&union, 1e-7)?; + if united.touching { + return Err(KernelError::Invalid("planar material pieces touch at a boundary".into())); } - let pieces = crate::extrude(plane, &normalized, start, end)?; + if united.regions.is_empty() { + return Err(KernelError::Invalid("empty planar material extrusion".into())); + } + let pieces = crate::extrude(plane, &united.regions, start, end)?; crate::ops::join_pieces(pieces)?.ok_or_else(|| KernelError::Failed("empty planar material extrusion".into())) }) } -/// A prism: the plane of its bottom cap (normal along the walls), its height and section (its -/// segments' tags alongside). -struct Prism { - lo: f64, - hi: f64, - section: Section, +/// The regions of a planar sheet, and whether two of its faces touch (share a vertex). +struct Regions { + regions: Vec, + touching: bool, } -/// What a section's segment was made from, for the history of what is built over it: an -/// operand's cap edge (`edge`, by its place in the operand's edge order), the wall face beside it -/// (`wall`), and the operand's vertices (by [`Index`]) the segment starts and ends at (`None` -/// where it was split off a longer one). Where the wall ends with a slab of a stepped operand, at -/// a cap whose outline runs along the whole segment, `far` is the operand's edge there (the -/// segment may have been read off a cap at another level). A segment carried through levels -/// beside the same wall keeps the vertices it was read at, which may lie at another level: they -/// say which line two walls meet along, not which edge of it. `None` fields: not known (no -/// history then). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Tag { - pub operand: usize, - pub wall: Option, - pub edge: Option, - pub far: Option, - pub start: Option, - pub end: Option, - /// Inside [`boolean2d_tagged`] only: the free-form segment (by number) the arc this tags - /// was fitted to, so the result's pieces of it get the exact curve back. - pub free: Option, -} +mod sheets { + use solidcore_record::Loop2; + use solidcore_record::Vec3; + use solidcore_record::brep::Loop; + use solidcore_record::brep::Surface; + use solidcraft_smlib::{BooleanOp, Brep}; -/// A segment nothing is known of. -const BLANK: Tag = Tag { operand: 0, wall: None, edge: None, far: None, start: None, end: None, free: None }; + use super::*; + use crate::prism_curve::{Run, projected}; -impl Tag { - /// The segment run the other way. - fn reversed(self) -> Tag { - Tag { start: self.end, end: self.start, ..self } + fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib planar regions: {what}"), e) } - /// Piece `k` of `n` the segment was split into, in its direction. - fn piece(self, k: usize, n: usize) -> Tag { - Tag { start: if k == 0 { self.start } else { None }, end: if k + 1 == n { self.end } else { None }, ..self } - } - - /// The segment beside `wall` instead (`None`: not known). Its edge and vertices were read - /// beside the wall it leaves, so they are dropped with it. - fn beside(self, wall: Option) -> Tag { - if wall == self.wall { self } else { Tag { operand: self.operand, wall, ..BLANK } } - } -} - -/// An operand's [`Index`], built when first needed (only bodies that are prisms are read). -pub(crate) struct LazyIndex<'a> { - body: &'a Body, - operand: usize, - index: std::cell::OnceCell, -} - -impl<'a> LazyIndex<'a> { - fn new(body: &'a Body, operand: usize) -> LazyIndex<'a> { - LazyIndex { body, operand, index: std::cell::OnceCell::new() } - } - - fn get(&self) -> &Index { - self.index.get_or_init(|| Index::new(self.body, self.operand)) - } -} - -/// Regions with a tag for each segment: per region, per loop (outer, then holes), per segment. -#[derive(Clone, Debug, Default, PartialEq)] -pub(crate) struct Section { - pub regions: Vec, - pub tags: Vec>>, -} - -impl Section { - /// Regions whose segments nothing is known of. - fn untagged(regions: &[Region2]) -> Section { - let tags = regions.iter().map(|r| std::iter::once(&r.outer).chain(&r.holes).map(|l| vec![BLANK; l.segs.len()]).collect()).collect(); - Section { regions: regions.to_vec(), tags } - } - - /// The tag of segment `s` of loop `l` of region `r` (blank where missing). - fn tag(&self, r: usize, l: usize, s: usize) -> Tag { - self.tags.get(r).and_then(|t| t.get(l)).and_then(|t| t.get(s)).copied().unwrap_or(BLANK) - } - - /// The tags of region `r`'s loops, as long as its loops (blank where missing). - fn region_tags(&self, r: usize) -> Vec> { - self.regions - .get(r) - .map(|reg| { - std::iter::once(®.outer) - .chain(®.holes) - .enumerate() - .map(|(l, lp)| (0..lp.segs.len()).map(|s| self.tag(r, l, s)).collect()) - .collect() - }) - .unwrap_or_default() - } - - /// One region from its loops (each segment tagged): the loop with the largest area is the - /// outer one. - fn from_loops(loops: Vec<(Loop2, Vec)>) -> Option
{ - let ((outer, outer_tags), holes) = split_outer(loops)?; - let (holes, hole_tags): (Vec, Vec>) = holes.into_iter().unzip(); - Some(Section { regions: vec![Region2 { outer, holes }], tags: vec![std::iter::once(outer_tags).chain(hole_tags).collect()] }) - } - - /// Region `r` alone. - fn region(&self, r: usize) -> Section { - Section { regions: self.regions.get(r).cloned().into_iter().collect(), tags: vec![self.region_tags(r)] } - } - - /// Every segment in order (regions, then loops) with its tag. - fn segments(&self) -> (Vec, Vec) { - let mut out = (Vec::new(), Vec::new()); - for (r, reg) in self.regions.iter().enumerate() { - for (l, lp) in std::iter::once(®.outer).chain(®.holes).enumerate() { - for (s, seg) in lp.segs.iter().enumerate() { - out.0.push(*seg); - out.1.push(self.tag(r, l, s)); + /// `regions` (in the plane's own coordinates) as one sheet on z = 0. SMLib's face builder + /// refuses curves of which more than two meet at one end point (`CreatePlanarFacesWith3DCurves`, + /// SmBrep.cpp: "spine points"), as where pieces of material touch at a corner or an outline + /// passes a point twice. So each loop, oriented (outer counter-clockwise, holes clockwise), is + /// split where it passes a point twice into simple loops, and each simple loop is a face of its + /// own; those running counter-clockwise are material, the others holes. Each region is its + /// material united less its holes united (SMLib's 2D boolean, which takes touching faces), and + /// the sheet is the regions united: a region may lie in another's hole (the island inside a + /// ring), where the other's hole must not take it. `tol` (mm): how close a loop's passes + /// through one point are. + pub(super) fn sheet(regions: &[Region2], tol: f64) -> Result { + let mut sheets = Vec::with_capacity(regions.len()); + for r in regions { + let (mut material, mut holes) = (Vec::new(), Vec::new()); + let loops = std::iter::once(r.outer.ccw()).chain(r.holes.iter().map(|h| h.ccw().reversed())); + for lp in loops { + let near = tol * 10.0; + for piece in simple_loops(lp.segs.into_iter().map(|s| (s.start(), s)).collect(), |a, b| a.dist(*b) < near) { + let face = face(&piece)?; + if piece.signed_area() > 0.0 { material.push(face) } else { holes.push(face) } } } + let Some(material) = united(material)? else { continue }; + sheets.push(match united(holes)? { + Some(holes) => combine(&material, &holes, BoolOp::Cut)?.ok_or_else(|| failed("sheet", "the holes take all the material"))?, + None => material, + }); } - out + united(sheets)?.ok_or_else(|| failed("sheet", "the regions hold no material")) } - /// Each segment's tag mapped by `f`. - fn retag(&mut self, f: impl Fn(Tag) -> Tag) { - for t in self.tags.iter_mut().flatten().flatten() { - *t = f(*t); - } + /// A simple closed loop as one planar face. + fn face(lp: &Loop2) -> Result { + let curves = lp.segs.iter().map(|s| crate::smlib_sweeps::curve(&Plane::XY, s)).collect::>>()?; + Brep::planar_faces(&curves).map_err(|e| failed("sheet", e)) } - /// Mark each segment of a slab with its `far` edge: the operand's edge where its wall meets - /// one of `caps` (the outlines of the operand's caps ending the slab). - /// - /// The operand's topology settles it where `top` gives the wall's edge (the wall ends at the - /// caps in that one edge, [`Stations::top_edge`]): that edge is over every segment beside it. - /// - /// Otherwise, for a wall meeting the caps in several edges (its top split at vertices an - /// earlier operation left, or beside a wall across it there) or carrying on past the caps - /// elsewhere, which edge is over a segment depends on where the segment lies along the wall, - /// and nothing in the topology says that. Only there is position compared: the segment takes - /// the edge of the cap segment beside the same wall it runs along end to end. A segment - /// along none, or along segments of different edges, stays unmarked; so do those past - /// `budget` (segment pairs compared). - fn mark_far(&mut self, caps: &[&Section], top: impl Fn(usize) -> Option, tol: f64, budget: &mut usize) { - let mut tops: std::collections::HashMap> = std::collections::HashMap::new(); - // The caps' segments by wall, gathered only once a wall needs position. - let mut by_wall: Option)>>> = None; - for (reg, tags) in self.regions.iter().zip(&mut self.tags) { - for (lp, tags) in std::iter::once(®.outer).chain(®.holes).zip(tags) { - for (seg, tag) in lp.segs.iter().zip(tags) { - let Some(w) = tag.wall else { continue }; - if let Some(e) = *tops.entry(w).or_insert_with(|| top(w)) { - tag.far = Some(e); - continue; - } - let by_wall = by_wall.get_or_insert_with(|| { - let mut by_wall: std::collections::HashMap)>> = std::collections::HashMap::new(); - for (segs, tags) in caps.iter().map(|c| c.segments()) { - for (seg, tag) in segs.into_iter().zip(tags) { - if let Some(w) = tag.wall { - by_wall.entry(w).or_default().push((seg, tag.edge)); - } - } - } - by_wall - }); - let Some(beside) = by_wall.get(&w) else { continue }; - let Some(left) = budget.checked_sub(beside.len()) else { continue }; - *budget = left; - // The one edge it runs along (`Some(None)`: along none, or not one edge). - let mut along: Option> = None; - for (_, edge) in beside.iter().filter(|(t, _)| runs_along(seg, t, tol)) { - along = match along { - None => Some(*edge), - Some(e) if e == *edge => Some(e), - Some(_) => Some(None), - }; - } - if let Some(Some(e)) = along { - tag.far = Some(e); - } - } - } - } - } - - /// Segments beside a wall another crosses between levels `lo` and `hi` are not beside it - /// all the way: their walls are not known. - fn drop_crossed(&mut self, stations: &Stations, lo: f64, hi: f64, tol: f64) { - self.retag(|t| match t.wall { - Some(w) if stations.across(w, lo, hi, tol) => t.beside(None), - _ => t, - }); - } - - /// Loops oriented: outers counter-clockwise, holes clockwise; the tags following their - /// segments. - fn oriented(&self) -> Section { - let turn = |lp: &Loop2, tags: Vec, reverse: bool| -> (Loop2, Vec) { - if reverse { (lp.reversed(), tags.into_iter().rev().map(Tag::reversed).collect()) } else { (lp.clone(), tags) } - }; - let mut out = Section::default(); - for (r, reg) in self.regions.iter().enumerate() { - let mut tags = self.region_tags(r).into_iter(); - let (outer, outer_tags) = turn(®.outer, tags.next().unwrap_or_default(), reg.outer.signed_area() < 0.0); - let mut loop_tags = vec![outer_tags]; - let mut holes = Vec::new(); - for h in ®.holes { - let (hole, hole_tags) = turn(h, tags.next().unwrap_or_default(), h.signed_area() > 0.0); - holes.push(hole); - loop_tags.push(hole_tags); - } - out.regions.push(Region2 { outer, holes }); - out.tags.push(loop_tags); - } - out - } -} - -/// An operand's faces, edges and vertices by identity, to tag the section segments read off its -/// caps ([`Tag`]). -pub(crate) struct Index { - operand: usize, - /// Each edge's place in the edge order. - edges: std::collections::HashMap, - /// Per edge (edge order): the faces it bounds, and its ends (by vertex number). - bounds: Vec<(Vec, Option, Option)>, - /// The edges between each pair of faces (lesser first; a face twice for a seam). - between: std::collections::HashMap<(usize, usize), Vec>, - /// Each vertex's number (first seen along the edge order). - vertices: std::collections::HashMap, - /// Each vertex's point, by number. - points: Vec, - /// Per edge (edge order): whether it is a line. - lines: Vec, - /// Per edge (edge order) that is not a line: the points its curve lies within (see - /// [`control_hull`]); `None` where they are not known. - hulls: Vec>>, -} - -impl Index { - fn new(b: &Body, operand: usize) -> Index { - let (edges, bounds) = crate::body::edge_order(b.solid.face_iter()); - let mut vertices = std::collections::HashMap::new(); - let mut points = Vec::new(); - for e in &edges { - for v in [e.absolute_front(), e.absolute_back()] { - if let std::collections::hash_map::Entry::Vacant(slot) = vertices.entry(v.id()) { - slot.insert(points.len()); - points.push(from_p3(v.point())); - } - } - } - let lines = edges.iter().map(|e| matches!(e.curve(), mt::Curve::Line(_))).collect(); - let hulls = edges.iter().map(|e| control_hull(&e.curve())).collect(); - let mut between: std::collections::HashMap<(usize, usize), Vec> = std::collections::HashMap::new(); - for (i, fs) in bounds.iter().enumerate() { - match fs.as_slice() { - [f] => between.entry((*f, *f)).or_default().push(i), - [f, g] => between.entry((*f.min(g), *f.max(g))).or_default().push(i), - _ => {} - } - } - let bounds = edges - .iter() - .zip(bounds) - .map(|(e, fs)| (fs, vertices.get(&e.absolute_front().id()).copied(), vertices.get(&e.absolute_back().id()).copied())) - .collect(); - Index { operand, edges: crate::record::edge_index(&b.solid), bounds, between, vertices, points, lines, hulls } - } - - /// The tag of the segments read off edge `e` (as it runs in a wire) of cap face `cap`. - fn tag(&self, e: &mt::Edge, cap: usize) -> Tag { - let edge = self.edges.get(&e.id()).copied(); - let wall = edge.and_then(|i| self.bounds.get(i)).and_then(|(fs, _, _)| match fs.as_slice() { - [x, y] if *x == cap => Some(*y), - [x, y] if *y == cap => Some(*x), - _ => None, - }); - Tag { - operand: self.operand, - wall, - edge, - far: None, - start: self.vertices.get(&e.front().id()).copied(), - end: self.vertices.get(&e.back().id()).copied(), - free: None, - } - } - - /// The loops of cap face `f` (number `cap`) as segments, each with its tag; `None` where an - /// edge isn't a line or an arc in the plane. - fn loops(&self, f: &mt::Face, cap: usize, plane: &Plane, tol: f64, work: &mut usize, segments: &mut usize) -> Option)>> { - let mut loops = Vec::new(); - for w in f.boundaries() { - let (mut segs, mut tags) = (Vec::new(), Vec::new()); - for e in w.edge_iter() { - let pieces = if FREE_FORM.with(|c| c.get()) { - crate::prism_curve::segment_fitted(e, plane, tol, PLANAR_FIT_TOL, work)? - } else { - crate::prism_curve::segment(e, plane, tol, work)? - }; - *segments = segments.checked_sub(pieces.len())?; - let tag = self.tag(e, cap); - tags.extend((0..pieces.len()).map(|k| tag.piece(k, pieces.len()))); - segs.extend(pieces); - } - loops.push((Loop2 { segs }, tags)); - } - Some(loops) - } -} - -/// Where an operand's walls along a direction end other than at its caps: at edges between two -/// walls that do not run along the direction (between pieces of one surface an earlier operation -/// left apart). A section segment carried through a level keeps the wall it was read beside -/// only where these say so, as its operand's prism or slab is read. -struct Stations { - /// Each wall's highest level. - tops: std::collections::HashMap, - /// Per wall, the edges across it: the other wall and the edge's lowest and highest levels. - /// A curve other than a line spans every level, unless it lies at one level. - cross: std::collections::HashMap>, -} - -impl Stations { - /// From the operand's walls (by face number, with their highest levels). - fn new(index: &Index, tops: std::collections::HashMap, d: Vec3, plane: &Plane, tol: f64) -> Stations { - let mut cross: std::collections::HashMap> = std::collections::HashMap::new(); - for (i, (fs, front, back)) in index.bounds.iter().enumerate() { - let [f, g] = fs[..] else { continue }; - if f == g || !tops.contains_key(&f) || !tops.contains_key(&g) { - continue; - } - let ends = front.and_then(|v| index.points.get(v)).zip(back.and_then(|v| index.points.get(v))); - let (lo, hi) = match ends { - Some((p, q)) if index.lines.get(i) == Some(&true) => { - let run = *q - *p; - if (run - d * run.dot(d)).len() < tol { - continue; // Along the direction: between walls over two segments. - } - let (h, k) = (plane.height(*p), plane.height(*q)); - (h.min(k), h.max(k)) - } - // A curve at one level (where a piece of a wall's surface stacked on another - // meets it: a boss's cylinder over the arc of the plate it stands on) crosses - // the walls there only. Any other spans every level. - _ => match index.hulls.get(i).and_then(Option::as_deref).map(|hull| level_span(hull, plane)) { - Some((lo, hi)) if hi - lo < tol => (lo, hi), - _ => (f64::NEG_INFINITY, f64::INFINITY), - }, - }; - cross.entry(f).or_default().push((g, lo, hi)); - cross.entry(g).or_default().push((f, lo, hi)); - } - Stations { tops, cross } - } - - /// The edges across wall `w`. - fn of(&self, w: usize) -> &[(usize, f64, f64)] { - self.cross.get(&w).map_or(&[], Vec::as_slice) - } - - /// The operand's edge (in `index`) where wall `w` ends at level `z`, when it ends there in - /// one edge: `z` is its top, no other wall crosses it there, and it meets the faces `caps` - /// (the caps at `z`) in exactly one edge. Found by topology alone, no position compared. The wall reaching no higher, every segment beside - /// it in a slab up to `z` ends on its edges at `z`, which are that one edge alone. - fn top_edge(&self, index: &Index, w: usize, caps: &[usize], z: f64, tol: f64) -> Option { - let ends = self.tops.get(&w).is_some_and(|t| (*t - z).abs() < tol); - if !ends || self.of(w).iter().any(|(_, l, h)| *l < z + tol && *h > z - tol) { - return None; - } - let mut edges = caps.iter().filter_map(|c| index.between.get(&(w.min(*c), w.max(*c)))).flatten(); - match (edges.next(), edges.next()) { - (Some(e), None) => Some(*e), - _ => None, - } - } - - /// Does wall `w` meet another wall across it between levels `lo` and `hi` (not at them)? - fn across(&self, w: usize, lo: f64, hi: f64, tol: f64) -> bool { - self.of(w).iter().any(|(_, l, h)| *l < hi - tol && *h > lo + tol) - } - - /// The wall over a section segment beside wall `w` just past level `z`, when the segment - /// runs on through `z` without meeting a cap there: `w` itself when nothing crosses it at - /// `z`, and it reaches past; the one wall across it at `z` when it ends there; else not - /// known. - fn past(&self, w: usize, z: f64, tol: f64) -> Option { - let at: std::collections::BTreeSet = - self.of(w).iter().filter(|(_, l, h)| (*l - z).abs() < tol && (*h - z).abs() < tol).map(|(y, _, _)| *y).collect(); - let reaches = self.tops.get(&w).is_some_and(|t| *t > z + tol); - match (at.len(), reaches) { - (0, true) => Some(w), - (1, false) => at.first().copied(), - _ => None, - } - } -} - -/// The most control points [`control_hull`] reads of one curve. -const MAX_HULL_POINTS: usize = 4096; - -/// The points curve `c` lies within: a B-spline's control points, or a NURBS curve's where its -/// weights are positive (the curve then lies in their convex hull). `None` for a line, an -/// intersection curve, other weights or too many points. -fn control_hull(c: &mt::Curve) -> Option> { - match c { - mt::Curve::BSplineCurve(c) if c.control_points().len() <= MAX_HULL_POINTS => Some(c.control_points().iter().map(|p| from_p3(*p)).collect()), - mt::Curve::NurbsCurve(c) if c.control_points().len() <= MAX_HULL_POINTS => { - c.control_points().iter().map(|p| (p.w > 0.0 && p.w.is_finite()).then(|| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w))).collect() - } - _ => None, - } -} - -/// The lowest and highest levels of `points` (infinite where there are none, or one isn't -/// finite). -fn level_span(points: &[Vec3], plane: &Plane) -> (f64, f64) { - let span = points - .iter() - .map(|p| plane.height(*p)) - .try_fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), h| h.is_finite().then(|| (lo.min(h), hi.max(h)))); - match span { - Some((lo, hi)) if lo <= hi => (lo, hi), - _ => (f64::NEG_INFINITY, f64::INFINITY), - } -} - -/// The highest level of face `f`'s vertices. -fn top_of(f: &mt::Face, plane: &Plane) -> f64 { - f.vertex_iter().map(|v| plane.height(from_p3(v.point()))).fold(f64::NEG_INFINITY, f64::max) -} - -/// Certify that a curved wall is swept along `d` from its surface representation. -/// Seam vertices alone cannot establish this: a half-cylinder's seam normals can -/// both be perpendicular to a transverse direction, silently filling its hole. -pub(crate) fn wall_along(surface: &mt::Surface, d: Vec3, tol: f64, remaining: &mut usize) -> bool { - if let mt::Surface::RevolutedCurve(processor) = surface { - let revolution = processor.entity(); - let mt::Curve::Line(line) = revolution.entity_curve() else { return false }; - let axis = revolution.axis(); - let meridian = line.1 - line.0; - let local_axis = Vec3::new(axis.x, axis.y, axis.z); - let local_meridian = Vec3::new(meridian.x, meridian.y, meridian.z); - let (Some(a), Some(m)) = (local_axis.normalized(), local_meridian.normalized()) else { return false }; - if a.cross(m).len() > 1e-9 { - return false; // A conical meridian is not a cylindrical wall. - } - let placed = *processor.transform() * mt::Vector4::new(axis.x, axis.y, axis.z, 0.0); - return placed.w.abs() < 1e-12 && Vec3::new(placed.x, placed.y, placed.z).normalized().is_some_and(|a| a.cross(d).len() < 1e-9); - } - let dimensions = match surface { - mt::Surface::BSplineSurface(s) => (s.control_points().len(), s.control_points().first().map_or(0, Vec::len)), - mt::Surface::NurbsSurface(s) => (s.control_points().len(), s.control_points().first().map_or(0, Vec::len)), - _ => return false, - }; - let (rows, cols) = dimensions; - let count = rows.saturating_mul(cols); - let rectangular = match surface { - mt::Surface::BSplineSurface(s) => s.control_points().iter().all(|r| r.len() == cols), - mt::Surface::NurbsSurface(s) => s.control_points().iter().all(|r| r.len() == cols), - _ => false, - }; - if rows < 2 || cols < 2 || count > 16_384 || !rectangular { - return false; - } - let Some(left) = remaining.checked_sub(count.saturating_mul(2)) else { return false }; - *remaining = left; - let points: Vec> = match surface { - mt::Surface::BSplineSurface(s) => s.control_points().iter().map(|r| r.iter().map(|p| (from_p3(*p), 1.0)).collect()).collect(), - mt::Surface::NurbsSurface(s) => { - s.control_points().iter().map(|r| r.iter().map(|p| (Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w), p.w)).collect()).collect() - } - _ => return false, - }; - if points.iter().any(|r| r.len() != cols) - || points.iter().flatten().any(|(p, w)| !w.is_finite() || *w <= 0.0 || [p.x, p.y, p.z].iter().any(|x| !x.is_finite())) - { - return false; - } - let max_weight = points.iter().flatten().map(|p| p.1).fold(0.0, f64::max); - if points.iter().flatten().any(|p| p.1 / max_weight < 1e-12) { - return false; - } - // Either parameter can be the extrusion direction. Projected positions must - // be invariant in that parameter; rational weights must also separate into - // a product of one factor per parameter, otherwise mixed weights bend the wall. - for transpose in [false, true] { - let (groups, length) = if transpose { (cols, rows) } else { (rows, cols) }; - let at = |i: usize, j: usize| if transpose { points[j][i] } else { points[i][j] }; - let mut valid = true; - let mut extended = false; - for i in 0..groups { - let (base, base_w) = at(i, 0); - for j in 0..length { - let (p, w) = at(i, j); - let delta = p - base; - let magnitude = [p.x.abs(), p.y.abs(), p.z.abs(), base.x.abs(), base.y.abs(), base.z.abs()].into_iter().fold(1.0, f64::max); - if delta.cross(d).len() > tol * 1e-3 + magnitude * f64::EPSILON * 128.0 { - valid = false; - break; - } - extended |= delta.dot(d).abs() > tol * 1e-3; - let lhs = w / max_weight * (at(0, 0).1 / max_weight); - let rhs = base_w / max_weight * (at(0, j).1 / max_weight); - if (lhs - rhs).abs() > 1e-12 * lhs.abs().max(rhs.abs()) { - valid = false; - break; - } - } - if !valid { - break; - } - } - if valid && extended { - return true; - } - } - false -} - -/// The body as a prism along `d` (unit), seen in `plane` (normal `d`). -#[cfg(test)] -fn prism_of(b: &Body, d: Vec3, plane: &Plane, tol: f64) -> Option { - prism_tagged(b, d, plane, tol, &LazyIndex::new(b, 0)) -} - -/// [`prism_of`], its section's segments tagged from `index` (the body's). -fn prism_tagged(b: &Body, d: Vec3, plane: &Plane, tol: f64, index: &LazyIndex) -> Option { - // A simple extrusion with N section edges has N walls plus its cap faces. - // Even disconnected two-arc sections need at most 2N faces. Keep that - // complete planar arrangement envelope, independently of stepped limits. - let mut remaining_faces = MAX_PLANAR_SEGMENTS * 2; - let mut lo = f64::INFINITY; - let mut hi = f64::NEG_INFINITY; - let mut tops: Vec<(usize, &mt::Face)> = Vec::new(); - let mut top_h = Vec::new(); - let mut bottom_h = Vec::new(); - let mut walls = std::collections::HashMap::new(); - let mut wall_work = 262_144; - let mut curve_work = 2_000_000usize; - for (fi, f) in b.solid.face_iter().enumerate() { - remaining_faces = remaining_faces.checked_sub(1)?; - curve_work = curve_work.checked_sub(1)?; - let surf = f.oriented_surface(); - if let mt::Surface::Plane(p) = &surf { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - let h = plane.height(from_p3(p.origin())); - if n.dot(d) > 1.0 - 1e-9 { - tops.push((fi, f)); - top_h.push(h); - hi = hi.max(h); - continue; - } - if n.dot(d) < -1.0 + 1e-9 { - bottom_h.push(h); - lo = lo.min(h); - continue; - } - if n.dot(d).abs() > 1e-9 { - return None; - } - walls.insert(fi, top_of(f, plane)); - continue; - } - if !wall_along(&surf, d, tol, &mut wall_work) { - return None; - } - walls.insert(fi, top_of(f, plane)); - } - // One height for every top (and bottom) cap. - if top_h.iter().any(|h| (h - hi).abs() > tol) || bottom_h.iter().any(|h| (h - lo).abs() > tol) || !(lo.is_finite() && hi > lo + tol) { - return None; - } - let mut section = Section::default(); - let mut remaining_segments = MAX_PLANAR_SEGMENTS; - let mut remaining_loops = MAX_PLANAR_SEGMENTS; - for (fi, f) in tops { - remaining_loops = remaining_loops.checked_sub(f.boundaries().len())?; - let loops = index.get().loops(f, fi, plane, tol, &mut curve_work, &mut remaining_segments)?; - let one = Section::from_loops(loops)?; - section.regions.extend(one.regions); - section.tags.extend(one.tags); - } - section.drop_crossed(&Stations::new(index.get(), walls, d, plane, tol), lo, hi, tol); - Some(Prism { lo, hi, section }) -} - -/// The loop with the largest area is the outer one. -fn split_outer(mut loops: Vec<(Loop2, T)>) -> Option<((Loop2, T), Vec<(Loop2, T)>)> { - let i = (0..loops.len()).max_by(|a, b| loops[*a].0.signed_area().abs().total_cmp(&loops[*b].0.signed_area().abs()))?; - let outer = loops.remove(i); - Some((outer, loops)) -} - -fn heights_of(b: &Body, plane: &Plane) -> (f64, f64) { - b.solid.vertex_iter().map(|v| plane.height(from_p3(v.point()))).fold((f64::INFINITY, f64::NEG_INFINITY), |m, h| (m.0.min(h), m.1.max(h))) -} - -/// Does `s` run along `t` from end to end? Two lines, `s`'s ends on `t`; two arcs of one -/// circle, `s`'s ends and middle on `t`. -fn runs_along(s: &Seg2, t: &Seg2, tol: f64) -> bool { - let on = |p: Vec2| t.point_at(closest_param(t, p)).dist(p) < tol; - match (*s, *t) { - (Seg2::Line { .. }, Seg2::Line { .. }) => on(s.start()) && on(s.end()), - (Seg2::Arc { center: c, radius: r, .. }, Seg2::Arc { center: d, radius: q, .. }) => { - c.dist(d) < tol && (r - q).abs() < tol && on(s.start()) && on(s.end()) && on(s.point_at(0.5)) - } - _ => false, - } -} - -/// Points where two segments cross (parameters on each), lines and arcs only. -/// -/// Curves that touch within the tolerance (a line tangent to an arc, two circles tangent inside -/// or outside) meet at one point, taken from the centres: the foot of the centre on the line, -/// or the point on the line of centres. The intersection formulas' two roots there are rounding -/// noise spread along the curves by its square root (a 1e-12 mm error in a distance puts them -/// ±2e-6 mm from a 2 mm arc's tangent point), close enough to both curves to pass for two -/// crossings; when the noise falls the other way there is no root and the contact is missed. -fn crossings(s: &Seg2, t: &Seg2, tol: f64) -> Vec<(f64, f64)> { - let mut pts: Vec = Vec::new(); - match (*s, *t) { - (Seg2::Line { a, b }, Seg2::Line { a: c, b: d }) => { - let (r, q) = (b - a, d - c); - let den = r.cross(q); - // Lines lying on one another within the tolerance do not cross: their ends split - // them. A hair from parallel they still meet at a point, anywhere along the overlap, - // and a split there leaves a piece shorter than the tolerance or a vertex that - // neither outline has. - let off = |p: Vec2, o: Vec2, dir: Vec2| (p - o).cross(dir).abs() / dir.len().max(1e-300); - let collinear = off(c, a, r) < tol && off(d, a, r) < tol || off(a, c, q) < tol && off(b, c, q) < tol; - if den.abs() > 1e-300 && !collinear { - let u = (c - a).cross(q) / den; - pts.push(a + r * u); - } - } - (Seg2::Line { a, b }, Seg2::Arc { center, radius, .. }) | (Seg2::Arc { center, radius, .. }, Seg2::Line { a, b }) => { - let dir = b - a; - let f = a - center; - let (qa, qb, qc) = (dir.dot(dir), 2.0 * f.dot(dir), f.dot(f) - radius * radius); - let disc = qb * qb - 4.0 * qa * qc; - if qa > 1e-300 { - let foot = a + dir * (-qb / (2.0 * qa)); - if (foot.dist(center) - radius).abs() < tol { - pts.push(foot); - } else if disc >= -tol * tol * qa { - let sd = disc.max(0.0).sqrt(); - for u in [(-qb - sd) / (2.0 * qa), (-qb + sd) / (2.0 * qa)] { - pts.push(a + dir * u); - } - } - } - } - (Seg2::Arc { center: c0, radius: r0, .. }, Seg2::Arc { center: c1, radius: r1, .. }) => { - let dd = c0.dist(c1); - if dd > 1e-12 && dd <= r0 + r1 + tol && dd >= (r0 - r1).abs() - tol { - // Circles of nearly one radius about nearly one centre lie on each other for a - // long way rather than touch at a point (centres 1000 tolerances apart: within - // the tolerance of each other over 5° of arc): those keep the general formula. - let inside = (dd - (r0 - r1).abs()).abs() < tol && dd > 1e3 * tol; - if (dd - (r0 + r1)).abs() < tol || inside { - pts.push(c0 + (c1 - c0) * (if inside && r1 > r0 { -r0 } else { r0 } / dd)); - } else { - let a = (r0 * r0 - r1 * r1 + dd * dd) / (2.0 * dd); - let h = (r0 * r0 - a * a).max(0.0).sqrt(); - let m = c0 + (c1 - c0) * (a / dd); - let perp = (c1 - c0).perp() * (1.0 / dd); - pts.push(m + perp * h); - pts.push(m - perp * h); - } - } - } - _ => {} - } - let mut out = Vec::new(); - for p in pts { - let (u, v) = (closest_param(s, p), closest_param(t, p)); - if s.point_at(u).dist(p) < tol && t.point_at(v).dist(p) < tol { - out.push((u, v)); - } - } - out -} - -/// Ray parity against analytic lines/arcs. Fragment classification must not depend on a -/// display chord tolerance: a tiny tool can sit between a circular boundary and its chords. -/// Loops are closed only within the chaining tolerance (an arrangement's own output joins its -/// pieces within `10 · tol`), so a gap where one line ends and the next begins is closed by a -/// straight connector: a ray through the gap would otherwise slip out of the loop without a -/// crossing and flip the parity of points level with the corner. Arcs decide their own ends -/// within an angular tolerance (below), so joints with an arc keep that rule. -fn inside_loop(lp: &Loop2, p: Vec2) -> bool { - // A ray through a vertex or grazing an arc's top or bottom is decided by the half-open - // rule, which needs both curves meeting there to agree on that point exactly. Arcs read - // back from a solid (a patterned hole's two halves) can disagree by a few ulps, so one half - // counts the touch and the other misses it. Move the ray off such points: a shift far below - // any modelling tolerance cannot change the answer for a point that is not on the loop. - let scale = 1.0 + p.x.abs().max(p.y.abs()); - // A point clear of the loop's box (by more than the ray shifts below) is outside it: skip - // the costly tests, which a region with a thousand cut-outs runs for every probe (#732). - if let Some(b) = loop_box(lp) - && !b.inflated(scale * 1e-6).contains(p) - { - return false; - } - // A point on the loop keeps the half-open answer. - if lp.segs.iter().any(|s| s.point_at(closest_param(s, p)).dist(p) < scale * 1e-9) { - return inside_loop_ray(lp, p); - } - let grazes = |q: Vec2| { - let near = |y: f64| (y - q.y).abs() < scale * 1e-9; - lp.segs.iter().any(|s| { - near(s.start().y) - || match *s { - Seg2::Arc { center, radius, .. } => near(center.y + radius) || near(center.y - radius), - _ => false, - } - }) - }; - let ray = [0.0, 1.0, -1.0, 2.0, -2.0, 3.0, -3.0].into_iter().map(|k| Vec2::new(p.x, p.y + k * scale * 1e-7)).find(|q| !grazes(*q)).unwrap_or(p); - inside_loop_ray(lp, ray) -} - -/// A box holding a loop of lines and arcs (an arc's whole circle); None for other curves. -fn loop_box(lp: &Loop2) -> Option { - let mut b = Aabb2::EMPTY; - for seg in &lp.segs { - b = b.union(&match *seg { - Seg2::Line { a, b } => Aabb2 { min: Vec2::new(a.x.min(b.x), a.y.min(b.y)), max: Vec2::new(a.x.max(b.x), a.y.max(b.y)) }, - Seg2::Arc { center, radius, .. } => Aabb2 { min: center, max: center }.inflated(radius.abs()), - _ => return None, - }); - } - (!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then_some(b) -} - -/// [`inside_loop`] with the ray along +x from `p` taken as given. -fn inside_loop_ray(lp: &Loop2, p: Vec2) -> bool { - let mut odd = false; - let nexts = lp.segs.iter().skip(1).chain(lp.segs.first()); - for (seg, next) in lp.segs.iter().zip(nexts) { - if let (Seg2::Line { b: a, .. }, Seg2::Line { a: b, .. }) = (*seg, *next) - && (a.y > p.y) != (b.y > p.y) - && a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y) > p.x - { - odd = !odd; - } - match *seg { - Seg2::Line { a, b } => { - if (a.y > p.y) != (b.y > p.y) { - let x = a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y); - if x > p.x { - odd = !odd; - } - } - } - Seg2::Arc { center, radius, start, sweep } => { - let y = (p.y - center.y) / radius; - if !(-1.0..=1.0).contains(&y) { - continue; - } - let a = y.asin(); - let root = (1.0 - y * y).max(0.0).sqrt(); - let full = (sweep.abs() - std::f64::consts::TAU).abs() < 1e-12; - for (i, (angle, x)) in [(a, center.x + radius * root), (std::f64::consts::PI - a, center.x - radius * root)].into_iter().enumerate() { - // A tangent has one geometric root. Interior tangencies contribute zero - // parity; a minimum at an endpoint follows the same half-open rule as lines. - if root == 0.0 && i == 1 { - continue; - } - if x <= p.x { - continue; - } - let mut delta = if sweep > 0.0 { angle - start } else { start - angle }; - delta = delta.rem_euclid(std::f64::consts::TAU); - if (delta - std::f64::consts::TAU).abs() < 1e-12 { - delta = 0.0; - } - if delta > sweep.abs() + 1e-12 { - continue; - } - let dy = angle.cos() * sweep; - let tangent = dy.abs() < sweep.abs() * 1e-12; - let at_start = delta < 1e-12; - let at_end = (delta - sweep.abs()).abs() < 1e-12; - let crosses = if full { - !tangent - } else if at_start { - dy > 0.0 && !tangent || tangent && y < 0.0 - } else if at_end { - dy < 0.0 && !tangent || tangent && y < 0.0 - } else { - !tangent - }; - if crosses { - odd = !odd; - } - } - } - _ => { - // Private prism callers only supply lines/arcs. Keep a controlled fallback - // for future internal callers; the public helper rejects other segment kinds. - let points = seg.polyline(1e-7); - for pair in points.windows(2) { - if let [a, b] = pair - && (a.y > p.y) != (b.y > p.y) - && a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y) > p.x - { - odd = !odd; - } - } - } - } - } - odd -} - -fn inside(regions: &[Region2], p: Vec2) -> bool { - regions.iter().any(|r| inside_loop(&r.outer, p) && !r.holes.iter().any(|h| inside_loop(h, p))) -} - -/// Call only after proving the point is at least `tol` from the other boundary. -/// This sub-tolerance interior probe cannot cross that boundary, and avoids casting -/// exactly through fitted arc/line endpoints whose heights differ by roundoff. -fn inside_clear(regions: &[Region2], point: Vec2, tol: f64) -> bool { - inside(regions, point + Vec2::new(tol * 0.173, tol * 0.317)) -} - -/// Analytic projections avoid iterative searches at every planar boundary probe. -/// Other curve types keep the shared solver introduced on main. -fn closest_param(segment: &Seg2, point: Vec2) -> f64 { - match *segment { - Seg2::Line { a, b } => { - let direction = b - a; - let length2 = direction.dot(direction); - if length2 > 1e-300 && length2.is_finite() { ((point - a).dot(direction) / length2).clamp(0.0, 1.0) } else { 0.0 } - } - Seg2::Arc { center, radius, start, sweep } if radius > 0.0 && sweep.abs() > 1e-12 && sweep.abs() <= std::f64::consts::TAU + 1e-9 => { - let offset = point - center; - let delta = ((offset.y.atan2(offset.x) - start) * sweep.signum()).rem_euclid(std::f64::consts::TAU); - if delta <= sweep.abs() { - (delta / sweep.abs()).clamp(0.0, 1.0) - } else if segment.start().dist(point) <= segment.end().dist(point) { - 0.0 - } else { - 1.0 - } - } - _ => segment.closest_param(point), - } -} - -fn dist_to(regions: &[Region2], p: Vec2) -> f64 { - regions - .iter() - .flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)) - .flat_map(|l| l.segs.iter()) - .map(|s| s.point_at(closest_param(s, p)).dist(p)) - .fold(f64::INFINITY, f64::min) -} - -/// The bounding box of a line or an arc, grown by twice the tolerance (and by the rounding of -/// its own corners). Whatever lies within the tolerance of the segment lies in the box. `None` -/// for other segments and for values that are not finite: no box, and nothing is skipped for it. -fn seg_box(s: &Seg2, tol: f64) -> Option { - let mut pts = vec![s.start(), s.end()]; - match *s { - Seg2::Line { .. } => {} - Seg2::Arc { center, radius, start, sweep } => { - // The axis extremes the arc passes. - for k in 0..4 { - let ang = k as f64 * std::f64::consts::FRAC_PI_2; - let delta = - if sweep >= 0.0 { (ang - start).rem_euclid(std::f64::consts::TAU) } else { (start - ang).rem_euclid(std::f64::consts::TAU) }; - if delta <= sweep.abs() { - pts.push(center + Vec2::from_angle(ang) * radius); - } - } - } - _ => return None, - } - let g = tol * 2.0 + 1e-12 * pts.iter().fold(0.0, |m: f64, p| m.max(p.x.abs()).max(p.y.abs())); - (pts.iter().all(|p| p.is_finite()) && g.is_finite()).then(|| pts.iter().copied().collect::().inflated(g)) -} - -fn boxes_meet(a: Option, b: Option) -> bool { - match (a, b) { - (Some(a), Some(b)) => a.meets(&b), - _ => true, - } -} - -fn box_holds(b: Option, p: Vec2) -> bool { - b.is_none_or(|b| b.contains(p)) -} - -/// Distance from `p` to the nearest of `segs` whose box holds it: infinite when none does (no -/// segment is within the tolerance of `p` then). -fn near_dist(segs: &[Seg2], boxes: &[Option], p: Vec2) -> f64 { - segs.iter().zip(boxes).filter(|(_, b)| box_holds(**b, p)).map(|(s, _)| s.point_at(closest_param(s, p)).dist(p)).fold(f64::INFINITY, f64::min) -} - -/// Direction of the first of `segs` through `p` (within `tol`), as it runs. -fn near_dir(segs: &[Seg2], boxes: &[Option], p: Vec2, tol: f64) -> Option { - let (s, t) = segs - .iter() - .zip(boxes) - .filter(|(_, b)| box_holds(**b, p)) - .map(|(s, _)| (s, closest_param(s, p))) - .find(|(s, t)| s.point_at(*t).dist(p) < tol)?; - s.derivative(t).normalized() -} - -/// 2D boolean of regions bounded by lines and arcs. -fn boolean2d(a: &[Region2], b: &[Region2], op: BoolOp, tol: f64) -> Option> { - boolean2d_tagged(&Section::untagged(a), &Section::untagged(b), op, tol).map(|s| s.regions) -} - -/// [`boolean2d`] of tagged sections: each segment of the result tagged as the segment of `a` or -/// `b` it is (a piece of). Free-form segments (a font's curves) take part as arcs within -/// [`PLANAR_FIT_TOL`]; each piece of one in the result is the exact curve again, ending where -/// it exactly meets the segment next to it (see [`exact_again`]). -fn boolean2d_tagged(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option
{ - let line_arc = |s: &Section| s.regions.iter().all(Region2::is_line_arc); - if line_arc(a) && line_arc(b) { - return boolean2d_arcs(a, b, op, tol); - } - let mut sources = Vec::new(); - let (fa, fb) = (fitted(a, &mut sources, PLANAR_FIT_TOL)?, fitted(b, &mut sources, PLANAR_FIT_TOL)?); - let out = boolean2d_arcs(&fa, &fb, op, tol)?; - Some(exact_again(out, &sources, tol)) -} - -/// `s` with each free-form segment replaced by lines and arcs within `fit`, tagged with its -/// number in `sources` (where it is put). -fn fitted(s: &Section, sources: &mut Vec, fit: f64) -> Option
{ - let mut out = Section::default(); - let mut pieces = 0usize; - for (r, reg) in s.regions.iter().enumerate() { - let mut loops = Vec::new(); - let mut tags = Vec::new(); - for (l, lp) in std::iter::once(®.outer).chain(®.holes).enumerate() { - let (mut segs, mut ts) = (Vec::new(), Vec::new()); - for (i, seg) in lp.segs.iter().enumerate() { - let tag = s.tag(r, l, i); - if seg.is_line_or_arc() { - segs.push(*seg); - ts.push(tag); - continue; - } - let arcs = seg.fit_arcs(fit)?; - pieces = pieces.checked_add(arcs.len()).filter(|n| *n <= MAX_PLANAR_SEGMENTS)?; - let n = arcs.len(); - ts.extend((0..n).map(|k| Tag { free: Some(sources.len()), ..tag.piece(k, n) })); - segs.extend(arcs); - sources.push(*seg); - } - loops.push(Loop2 { segs }); - tags.push(ts); - } - let mut loops = loops.into_iter(); - out.regions.push(Region2 { outer: loops.next()?, holes: loops.collect() }); - out.tags.push(tags); - } - Some(out) -} - -/// A loop's piece in [`exact_again`]: a run of arcs fitted to free-form segment `src`, standing -/// for its exact curve from parameter `t0` to `t1` (`t1 < t0`: run backwards), from `a` to `b`; -/// or a line or arc as it is. -#[derive(Clone, Copy)] -enum Piece { - Exact { src: usize, t0: f64, t1: f64, a: Vec2, b: Vec2, tag: Tag }, - Plain(Seg2, Tag), -} - -impl Piece { - fn end(&self) -> Vec2 { - match self { - Piece::Exact { b, .. } => *b, - Piece::Plain(s, _) => s.end(), - } - } - - /// The piece ending at `at` (an exact curve: at its parameter `t`, when given). - fn set_end(&mut self, t: Option, at: Vec2) { - match self { - Piece::Exact { t1, b, .. } => { - if let Some(t) = t { - *t1 = t; - } - *b = at; - } - Piece::Plain(s, _) => *s = seg_with_ends(s, s.start(), at), - } - } - - /// The piece starting at `at` (an exact curve: at its parameter `t`, when given). - fn set_start(&mut self, t: Option, at: Vec2) { - match self { - Piece::Exact { t0, a, .. } => { - if let Some(t) = t { - *t0 = t; - } - *a = at; - } - Piece::Plain(s, _) => *s = seg_with_ends(s, at, s.end()), - } - } -} - -/// `s` running from `a` to `b` instead (points on it or a hair off it): a line between them, an -/// arc of the same circle, a free-form segment with those end control points. -fn seg_with_ends(s: &Seg2, a: Vec2, b: Vec2) -> Seg2 { - match *s { - Seg2::Line { .. } => Seg2::Line { a, b }, - Seg2::Arc { center, radius, start, sweep } => { - let new_start = (a - center).angle(); - let end = start + sweep; - // The same way round, through the same part of the circle. - let shift = |x: f64, near: f64| x + ((near - x) / std::f64::consts::TAU).round() * std::f64::consts::TAU; - let s0 = shift(new_start, start); - let s1 = shift((b - center).angle(), end); - Seg2::Arc { center, radius, start: s0, sweep: s1 - s0 } - } - Seg2::Cubic { p1, p2, .. } => Seg2::Cubic { p0: a, p1, p2, p3: b }, - Seg2::Conic { apex, w, .. } => Seg2::Conic { a, apex, b, w }, - Seg2::Bezier { n, mut p } => { - if let Some(x) = p.first_mut() { - *x = a; - } - if let Some(x) = p.get_mut(n as usize) { - *x = b; - } - Seg2::Bezier { n, p } - } - } -} - -/// The exact piece of `src` from parameter `t0` to `t1` (either way round), from `a` to `b`. -fn trimmed(src: &Seg2, t0: f64, t1: f64, a: Vec2, b: Vec2) -> Seg2 { - let (lo, hi) = (t0.min(t1), t0.max(t1)); - let mut s = *src; - if lo > 1e-12 { - s = s.split_at(lo).1; - } - if hi < 1.0 - 1e-12 { - // Splitting a conic renormalises its weights, which moves its parameters: the second - // split is found on the piece. - let at = closest_param(&s, src.point_at(hi)); - if at < 1.0 - 1e-12 { - s = s.split_at(at).0; - } - } - if t0 <= t1 { seg_with_ends(&s, a, b) } else { seg_with_ends(&s.reversed(), a, b) } -} - -/// Where curve `p` near its parameter `t` meets `q` near its parameter `u`, by Newton's method: -/// their parameters there, or `None` when the crossing doesn't settle within `near` of `p(t)`. -fn meet(p: &Seg2, t: f64, q: &Seg2, u: f64, near: f64) -> Option<(f64, f64)> { - let (mut t, mut u) = (t, u); - let start = p.point_at(t); - let scale = 1.0 + start.x.abs().max(start.y.abs()); - for _ in 0..50 { - let f = p.point_at(t) - q.point_at(u); - if f.len() < 1e-14 * scale { - break; - } - // P(t) - Q(u) = f; the step solves [P'(t), -Q'(u)] (dt, du) = -f. - let (dp, dq) = (p.derivative(t), q.derivative(u)); - let det = -dp.cross(dq); - if !(det.abs() > 1e-300 && det.is_finite()) { - return None; - } - t = (t + f.cross(dq) / det).clamp(0.0, 1.0); - u = (u + f.cross(dp) / det).clamp(0.0, 1.0); - } - let (x, y) = (p.point_at(t), q.point_at(u)); - (x.dist(y) < 1e-9 * scale && x.dist(start) < near).then_some((t, u)) -} - -/// The whole line or circle a line or arc lies on (as a segment reaching past it), what an exact -/// crossing with a curve is looked for on. -fn carrier(s: &Seg2) -> Option { - match *s { - Seg2::Line { a, b } => Some(Seg2::Line { a: a - (b - a), b: b + (b - a) }), - Seg2::Arc { center, radius, start, sweep } => { - let turn = sweep.signum() * std::f64::consts::PI; - Some(Seg2::Arc { center, radius, start: start + sweep * 0.5 - turn, sweep: 2.0 * turn }) - } - _ => None, - } -} - -/// The exact curves back in the result of a boolean of [`fitted`] sections: each run of arcs -/// fitted to one free-form segment becomes that segment's exact piece, and where a run ends on -/// another segment (a cut across the curve) both end at their exact crossing. Where that -/// crossing can't be found they end where the arrangement put them, within -/// [`PLANAR_FIT_TOL`] of it. -fn exact_again(out: Section, sources: &[Seg2], tol: f64) -> Section { - let near = (PLANAR_FIT_TOL + tol) * 10.0; - let mut res = Section::default(); - for (r, reg) in out.regions.iter().enumerate() { - let tags = out.region_tags(r); - let mut loops = Vec::new(); - let mut loop_tags = Vec::new(); - for (l, lp) in std::iter::once(®.outer).chain(®.holes).enumerate() { - let (segs, ts) = exact_loop(lp, tags.get(l).map(Vec::as_slice).unwrap_or(&[]), sources, near); - // A sliver the arrangement found where a curve's arcs nearly touch another part of - // the outline (at the waist of a 3) closes up to nothing on the exact curves: it - // encloses nothing and would make edges with no length, so it is left out. - if segs.iter().map(Seg2::length).sum::() <= near { - if l == 0 { - break; - } - continue; - } - loops.push(Loop2 { segs }); - loop_tags.push(ts); - } - let mut loops = loops.into_iter(); - let Some(outer) = loops.next() else { continue }; - res.regions.push(Region2 { outer, holes: loops.collect() }); - res.tags.push(loop_tags); - } - res -} - -/// One loop of [`exact_again`]: its segments and their tags. -fn exact_loop(lp: &Loop2, tags: &[Tag], sources: &[Seg2], near: f64) -> (Vec, Vec) { - let n = lp.segs.len(); - let tag = |i: usize| Tag { free: None, ..tags.get(i).copied().unwrap_or(BLANK) }; - let free = |i: usize| tags.get(i).and_then(|t| t.free); - let plain = || (lp.segs.clone(), (0..n).map(tag).collect::>()); - // Start at the first segment of a run (a loop that is one run stays as it is). - let Some(first) = (0..n).find(|&i| free(i).is_none() || free(i) != free((i + n - 1) % n)) else { return plain() }; - let mut pieces: Vec = Vec::new(); - let mut k = 0; - while k < n { - let i = (first + k) % n; - let Some(seg) = lp.segs.get(i) else { return plain() }; - let Some((f, src)) = free(i).and_then(|f| sources.get(f).map(|s| (f, s))) else { - pieces.push(Piece::Plain(*seg, tag(i))); - k += 1; - continue; - }; - let mut j = k; - while j + 1 < n && free((first + j + 1) % n) == Some(f) { - j += 1; - } - let Some(last) = lp.segs.get((first + j) % n) else { return plain() }; - // A run reaching the curve's end is the curve to its end, exactly: the same curve the - // walls over it are read from, which a parameter found by projection (a hair short of 1) - // would cut short into a different one. - let at = |p: Vec2| { - if p.dist(src.start()) < near { - 0.0 - } else if p.dist(src.end()) < near { - 1.0 - } else { - closest_param(src, p) - } - }; - let (t0, t1) = (at(seg.start()), at(last.end())); - if (t1 - t0).abs() < 1e-9 { - // A sliver of the curve: its arcs as they are, or, shorter than the tolerance (where - // a curve lies on another, as when the same letters are cut again), nothing: its - // neighbours meet where it was, and as an edge it would have no length. - let length: f64 = (k..=j).filter_map(|m| lp.segs.get((first + m) % n)).map(Seg2::length).sum(); - if length > near { - for m in k..=j { - let q = (first + m) % n; - pieces.push(Piece::Plain(*lp.segs.get(q).unwrap_or(seg), tag(q))); - } - } - } else { - let t = Tag { end: tag((first + j) % n).end, ..tag(i) }; - pieces.push(Piece::Exact { src: f, t0, t1, a: src.point_at(t0), b: src.point_at(t1), tag: t }); - } - k = j + 1; - } - // Each joint at an exact curve: both sides end at the same point, the exact crossing where - // the curve is cut, its own end point where it ends. - if pieces.is_empty() { - return plain(); - } - let m = pieces.len(); - let inner = |t: f64| t > 1e-9 && t < 1.0 - 1e-9; - for i in 0..m { - let (Some(p), Some(q)) = (pieces.get(i).copied(), pieces.get((i + 1) % m).copied()) else { continue }; - let joint = p.end(); - let src = |f: usize| sources.get(f); - let found = match (p, q) { - (Piece::Exact { src: f, t1, .. }, Piece::Exact { src: g, t0, .. }) if f != g && (inner(t1) || inner(t0)) => { - src(f).zip(src(g)).and_then(|(x, y)| meet(x, t1, y, t0, near).map(|(a, b)| (Some(a), Some(b), x.point_at(a)))) - } - (Piece::Exact { src: f, t1, .. }, Piece::Plain(s, _)) if inner(t1) => src(f) - .zip(carrier(&s)) - .and_then(|(x, c)| meet(x, t1, &c, closest_param(&c, joint), near).map(|(a, _)| (Some(a), None, x.point_at(a)))), - (Piece::Plain(s, _), Piece::Exact { src: f, t0, .. }) if inner(t0) => src(f) - .zip(carrier(&s)) - .and_then(|(x, c)| meet(x, t0, &c, closest_param(&c, joint), near).map(|(a, _)| (None, Some(a), x.point_at(a)))), - _ => None, - }; - // No crossing to refine (or none found): both end where the curve does. - let found = found.or(match (p, q) { - (Piece::Exact { b, .. }, _) => Some((None, None, b)), - (_, Piece::Exact { a, .. }) => Some((None, None, a)), - _ => None, - }); - let Some((x, y, at)) = found else { continue }; - if let Some(p) = pieces.get_mut(i) { - p.set_end(x, at); - } - if let Some(q) = pieces.get_mut((i + 1) % m) { - q.set_start(y, at); - } - } - let mut segs = Vec::with_capacity(m); - let mut ts = Vec::with_capacity(m); - for p in pieces { - match p { - Piece::Exact { src, t0, t1, a, b, tag } => match sources.get(src) { - Some(s) => { - segs.push(trimmed(s, t0, t1, a, b)); - ts.push(tag); - } - None => return plain(), - }, - Piece::Plain(s, t) => { - segs.push(s); - ts.push(t); - } - } - } - // The loop closed exactly: where a segment ends a hair from where the next starts (a font's - // nearly round curve read as an arc ends a few hundredths of a micron off the curve after - // it), the one that is not an arc moves its end onto the arc's (an arc's ends stay on its - // circle). Two arcs are left as they meet, as a boolean of lines and arcs leaves them. - let m = segs.len(); - for i in 0..m { - let j = (i + 1) % m; - let (Some(x), Some(y)) = (segs.get(i).copied(), segs.get(j).copied()) else { continue }; - let gap = x.end().dist(y.start()); - if gap == 0.0 || gap > near { - continue; - } - let arc = |s: &Seg2| matches!(s, Seg2::Arc { .. }); - if !arc(&y) { - if let Some(s) = segs.get_mut(j) { - *s = seg_with_ends(&y, x.end(), y.end()); - } - } else if !arc(&x) - && let Some(s) = segs.get_mut(i) - { - *s = seg_with_ends(&x, x.start(), y.start()); - } - } - (segs, ts) -} - -/// The boolean of sections of lines and arcs alone ([`boolean2d_tagged`]). -fn boolean2d_arcs(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option
{ - let count = - |rs: &[Region2]| rs.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).fold(0usize, |n, lp| n.saturating_add(lp.segs.len())); - let (na, nb) = (count(&a.regions), count(&b.regions)); - if na.saturating_add(nb) > MAX_PLANAR_SEGMENTS || na.saturating_mul(nb) > MAX_PLANAR_PAIRS { - return None; - } - let (a, b) = (a.oriented(), b.oriented()); - let ((sa, ta), (sb, tb)) = (a.segments(), b.segments()); - let (a, b) = (a.regions, b.regions); - if sa.iter().chain(&sb).any(|s| !matches!(s, Seg2::Line { .. } | Seg2::Arc { .. })) { - return None; - } - // Only segments whose bounding boxes meet can cross, touch or lie on each other: the other - // pairs skip the exact tests (a closest-point search each). - let (box_a, box_b): (Vec<_>, Vec<_>) = (sa.iter().map(|s| seg_box(s, tol)).collect(), sb.iter().map(|s| seg_box(s, tol)).collect()); - let apart = |i: usize, j: usize| !boxes_meet(box_a.get(i).copied().flatten(), box_b.get(j).copied().flatten()); - // Split every segment where it crosses the other side's boundary. - let mut cut_a: Vec> = vec![Vec::new(); sa.len()]; - let mut cut_b: Vec> = vec![Vec::new(); sb.len()]; - let mut events = 0usize; - for (i, s) in sa.iter().enumerate() { - for (j, t) in sb.iter().enumerate() { - if apart(i, j) { - continue; - } - for (u, v) in crossings(s, t, tol) { - events += 2; - if events > MAX_PLANAR_EVENTS { - return None; - } - cut_a.get_mut(i)?.push(u); - cut_b.get_mut(j)?.push(v); - } - } - } - // Ends of the other side's segments lying on a segment split it too (touching corners). - for (i, s) in sa.iter().enumerate() { - for (j, t) in sb.iter().enumerate() { - if apart(i, j) { - continue; - } - for p in [t.start(), t.end()] { - let u = closest_param(s, p); - if s.point_at(u).dist(p) < tol { - events += 1; - if events > MAX_PLANAR_EVENTS { - return None; - } - cut_a.get_mut(i)?.push(u); - } - } - } - } - for (j, t) in sb.iter().enumerate() { - for (i, s) in sa.iter().enumerate() { - if apart(i, j) { - continue; - } - for p in [s.start(), s.end()] { - let v = closest_param(t, p); - if t.point_at(v).dist(p) < tol { - events += 1; - if events > MAX_PLANAR_EVENTS { - return None; - } - cut_b.get_mut(j)?.push(v); - } - } - } - } - // The loops below are chained by joining pieces whose ends lie within `near` of each other, - // so to them a piece shorter than that runs from a point back to the same point: a cut that - // would leave one, at either end of what is left of the segment, is not made. Two edges - // 0.57° apart that share a corner up to rounding cross a hundred times that rounding short - // of it; split there, the sliver between the crossing and the corner was taken for a - // second way out of the corner and closed as a loop of its own. - let near = tol * 10.0; - let pieces = |s: &Seg2, cuts: &mut Vec| -> Vec { - cuts.sort_by(f64::total_cmp); - let mut out = Vec::new(); - let mut rest = *s; - let mut done = 0.0; - for &c in cuts.iter() { - if c <= done + 1e-9 || c >= 1.0 - 1e-9 { - continue; - } - let local = (c - done) / (1.0 - done); - let (x, y) = rest.split_at(local); - if x.length() > near && y.length() > near { - out.push(x); - rest = y; - done = c; - } - } - out.push(rest); - out - }; - let mut kept: Vec<(Seg2, Tag)> = Vec::new(); - // A's pieces. - for (i, s) in sa.iter().enumerate() { - if cut_a.get(i)?.len() > MAX_PLANAR_SEGMENTS { - return None; - } - let split = pieces(s, cut_a.get_mut(i)?); - let (n, tag) = (split.len(), ta.get(i).copied().unwrap_or(BLANK)); - for (k, p) in split.into_iter().enumerate() { - let m = p.point_at(0.5); - let on = near_dist(&sb, &box_b, m) < tol; - let keep = if on { - let same = near_dir(&sb, &box_b, m, tol).is_some_and(|d| d.dot(p.derivative(0.5)) > 0.0); - match op { - BoolOp::Union | BoolOp::Intersect => same, - BoolOp::Cut => !same, - } - } else { - let ins = inside_clear(&b, m, tol); - match op { - BoolOp::Union | BoolOp::Cut => !ins, - BoolOp::Intersect => ins, - } - }; - if keep { - if kept.len() >= MAX_PLANAR_SEGMENTS { - return None; - } - kept.push((p, tag.piece(k, n))); - } - } - } - // B's pieces (coincident ones were decided with A's). - for (j, t) in sb.iter().enumerate() { - if cut_b.get(j)?.len() > MAX_PLANAR_SEGMENTS { - return None; - } - let split = pieces(t, cut_b.get_mut(j)?); - let (n, tag) = (split.len(), tb.get(j).copied().unwrap_or(BLANK)); - for (k, p) in split.into_iter().enumerate() { - let m = p.point_at(0.5); - if near_dist(&sa, &box_a, m) < tol { - continue; - } - let ins = inside_clear(&a, m, tol); - if kept.len() >= MAX_PLANAR_SEGMENTS { - return None; - } - let tag = tag.piece(k, n); - match op { - BoolOp::Union if !ins => kept.push((p, tag)), - BoolOp::Intersect if ins => kept.push((p, tag)), - BoolOp::Cut if ins => kept.push((p.reversed(), tag.reversed())), - _ => {} - } - } - } - // Chain into loops. Where several kept pieces leave the point a loop has reached (outlines - // pinching at a vertex on an edge, a circle tangent to a side, two corners touching), the - // loop takes the one keeping the material on its left most tightly, so that pieces of - // material meeting only at that point close as loops of their own; returning to its start, - // a loop closes only when that is the tightest turn too. A loop that still passes a point - // twice (a hole touching the outline) is split there into simple loops. - let mut loops: Vec<(Loop2, Vec)> = Vec::new(); - let mut used = vec![false; kept.len()]; - for start in 0..kept.len() { - if used.get(start).copied().unwrap_or(true) { - continue; - } - let (seg, tag) = *kept.get(start)?; - let (mut segs, mut tags) = (vec![seg], vec![tag]); - if let Some(u) = used.get_mut(start) { - *u = true; - } - let first = seg.start(); - let mut guard = 0; - loop { - guard += 1; - if guard > kept.len() + 2 { - return None; - } - let last = *segs.last()?; - let end = last.end(); - let full_circle = - segs.first().is_some_and(|s| matches!(s, Seg2::Arc { sweep, .. } if (sweep.abs() - std::f64::consts::TAU).abs() < 1e-9)); - let closes = end.dist(first) < near && (segs.len() > 1 || full_circle); - let leaving: Vec = - (0..kept.len()).filter(|k| !used.get(*k).copied().unwrap_or(true) && kept[*k].0.start().dist(end) < near).collect(); - let next = match leaving.as_slice() { - [] if end.dist(first) < near => break, - [] => return None, - [only] if !closes => *only, - _ => { - // The loop's own first piece stands for closing it. - let mut out: Vec = leaving.iter().map(|k| kept[*k].0).collect(); - if closes { - out.push(*segs.first()?); - } - let pick = tightest_left(&last, &out)?; - match leaving.get(pick) { - Some(k) => *k, - None => break, - } - } - }; - let (seg, tag) = *kept.get(next)?; - if let Some(u) = used.get_mut(next) { - *u = true; - } - segs.push(seg); - tags.push(tag); - } - for (l, t) in simple_loops(Loop2 { segs }, tags, near) { - if l.signed_area().abs() > tol * tol { - loops.push((l, t)); - } - } - } - // Outers (counter-clockwise) take the holes they contain, the smallest first. - let (mut outers, holes): (Vec<(Loop2, Vec)>, Vec<(Loop2, Vec)>) = loops.into_iter().partition(|(l, _)| l.signed_area() > 0.0); - outers.sort_by(|x, y| x.0.signed_area().abs().total_cmp(&y.0.signed_area().abs())); - let mut out = Section::default(); - for (o, tags) in outers { - out.regions.push(Region2 { outer: o, holes: Vec::new() }); - out.tags.push(vec![tags]); - } - for (h, tags) in holes { - let p = h.segs.first()?.point_at(0.5); - let r = out.regions.iter().position(|r| inside_loop(&r.outer, p) && r.outer.signed_area().abs() > h.signed_area().abs())?; - out.regions.get_mut(r)?.holes.push(h); - out.tags.get_mut(r)?.push(tags); - } - Some(out) -} - -/// The boolean done on prism sections, or `None` when it doesn't apply. -/// The pieces of a segment between the given points (those lying on it, inside it). -/// Of the pieces in `out` leaving the point where `incoming` ends, the one turning most to the -/// left: the largest counter-clockwise angle from the way back along `incoming`. A loop with -/// its material on its left that always takes it encloses the least, so material meeting -/// another piece only at a point closes there as a loop of its own. -/// -/// Directions are read a short way along each piece (the same distance on all, a twentieth of -/// the shortest), not from tangents: a circle tangent to a line leaves the point along the -/// line, and only its curvature says which side it turns to. The pieces of an arrangement -/// don't cross, and none turns more than a twentieth of its sweep within that distance, so the -/// order the points lie in is the order the pieces leave in. -fn tightest_left(incoming: &Seg2, out: &[Seg2]) -> Option { - let shortest = out.iter().map(Seg2::length).fold(incoming.length(), f64::min); - let h = shortest * 0.05; - if !(h > 0.0) || !h.is_finite() { - return None; - } - let at = incoming.end(); - let back = incoming.point_at(1.0 - h / incoming.length()) - at; - let turn = |s: &Seg2| { - let d = s.point_at(h / s.length()) - at; - let a = back.cross(d).atan2(back.dot(d)); - if a < 0.0 { a + std::f64::consts::TAU } else { a } - }; - (0..out.len()).max_by(|x, y| turn(&out[*x]).total_cmp(&turn(&out[*y]))) -} - -/// A closed loop split where it passes a point twice (within `near`) into loops that pass -/// every point once, with their segments' tags. Counter-clockwise pieces are material, the -/// others holes in it: a hole touching the outline at one point, or two pieces of material -/// meeting at a corner, come out as two loops sharing that point. -fn simple_loops(lp: Loop2, tags: Vec, near: f64) -> Vec<(Loop2, Vec)> { - let mut todo = vec![(lp.segs, tags)]; - let mut out = Vec::new(); - // Each split leaves two shorter loops, so the work is bounded by the segment count. - while let Some((segs, tags)) = todo.pop() { - let n = segs.len(); - let repeat = (0..n).find_map(|i| { - let p = segs.get(i)?.start(); - (i + 1..n).find(|j| segs.get(*j).is_some_and(|s| s.start().dist(p) < near)).map(|j| (i, j)) - }); - match repeat { - Some((i, j)) if j > i => { - let part = |v: &[Seg2], r: std::ops::Range| v.get(r).unwrap_or(&[]).to_vec(); - let part_t = |v: &[Tag], r: std::ops::Range| v.get(r).unwrap_or(&[]).to_vec(); - let inner = (part(&segs, i..j), part_t(&tags, i..j)); - let outer = ([part(&segs, j..n), part(&segs, 0..i)].concat(), [part_t(&tags, j..n), part_t(&tags, 0..i)].concat()); - todo.push(inner); - todo.push(outer); - } - _ => out.push((Loop2 { segs }, tags)), - } - } - out -} - -fn split_seg(seg: &Seg2, pts: &[Vec2], tol: f64) -> Option> { - let mut ts: Vec = pts - .iter() - .filter_map(|p| { - // A point within `tol` of an arc is within `tol` of its circle: the others need no - // (sampled) projection. - if let Seg2::Arc { center, radius, .. } = seg - && (p.dist(*center) - radius).abs() >= tol - { - return None; - } - // A point within `tol` of an end is that end (the sewing welds them into one): a cut - // there would leave a piece with no length. - if p.dist(seg.start()) < tol || p.dist(seg.end()) < tol { - return None; - } - let t = closest_param(seg, *p); - (t > 1e-9 && t < 1.0 - 1e-9 && seg.point_at(t).dist(*p) < tol).then_some(t) - }) - .collect(); - ts.sort_by(f64::total_cmp); - ts.dedup_by(|x, y| (*x - *y).abs() < 1e-9); - let mut out = Vec::new(); - let mut t0 = 0.0; - for t1 in ts.into_iter().chain(std::iter::once(1.0)) { - out.push(match *seg { - Seg2::Line { .. } => Seg2::Line { a: seg.point_at(t0), b: seg.point_at(t1) }, - Seg2::Arc { center, radius, start, sweep } => Seg2::Arc { center, radius, start: start + sweep * t0, sweep: sweep * (t1 - t0) }, - _ => trimmed(seg, t0, t1, seg.point_at(t0), seg.point_at(t1)), - }); - t0 = t1; - } - Some(out) -} - -/// The union of two prisms along `d` stacked end to end (or overlapping) with different -/// sections, sewn from its faces: each slab between the prisms' end levels has walls over its -/// section's outline; each level has a face up over the section below less the one above, and -/// a face down over the one above less the one below. Every outline is split where any other -/// meets it, so the faces share their edges. `None` when a slab is empty or a curve isn't a -/// line or an arc. -fn sew_stack(plane: &Plane, d: Vec3, pa: &Prism, pb: &Prism, tol: f64, history: &lineage::Context) -> Option> { - let mut levels = vec![pa.lo, pa.hi, pb.lo, pb.hi]; - levels.sort_by(f64::total_cmp); - levels.dedup_by(|x, y| (*x - *y).abs() < tol); - let covers = |p: &Prism, z0: f64, z1: f64| p.lo <= z0 + tol && p.hi >= z1 - tol; - let mut slabs: Vec
= Vec::new(); - for w in levels.windows(2) { - let (z0, z1) = (*w.first()?, *w.get(1)?); - let s = match (covers(pa, z0, z1), covers(pb, z0, z1)) { - (true, true) => boolean2d_tagged(&pa.section, &pb.section, BoolOp::Union, tol)?, - (true, false) => pa.section.clone(), - (false, true) => pb.section.clone(), - (false, false) => return None, - }; - slabs.push(s.oriented()); - } - sew_sections(plane, d, &levels, &slabs, tol, false, history) -} - -/// Sew the exact sections between successive levels, including empty gaps. With `coalesce`, -/// walls over one segment through successive slabs are one face. -fn sew_sections( - plane: &Plane, - d: Vec3, - levels: &[f64], - slabs: &[Section], - tol: f64, - coalesce: bool, - history: &lineage::Context, -) -> Option> { - if levels.len() != slabs.len() + 1 - || slabs.len() > 128 - || plane.normal().dot(d) < 1. - 1e-12 - || levels.iter().any(|z| !z.is_finite()) - || levels.windows(2).any(|z| z[0] >= z[1]) - { - return None; - } - let mut blocks = Vec::new(); - let mut start = None; - for (i, slab) in slabs.iter().enumerate() { - if slab.regions.is_empty() { - if let Some(first) = start.take() { - blocks.push((first, i)); - } - } else if start.is_none() { - start = Some(i); - } - } - if let Some(first) = start { - blocks.push((first, slabs.len())); - } - if blocks.is_empty() { - return None; - } - Some((|| { - let mut pieces = Vec::new(); - let mut remaining_constructed_faces = MAX_PLANAR_SEGMENTS * 2; - let mut remaining_faces = MAX_PLANAR_SEGMENTS * 2; - for (first, end) in blocks { - let tagged = slabs.get(first).ok_or_else(|| KernelError::Failed("missing prism section".into()))?; - let section = &tagged.regions; - if slabs[first..end].iter().all(|s| s.regions == *section) { - let edge_count = section.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).flat_map(|l| &l.segs).fold(0usize, |n, s| { - n.saturating_add(match s { - Seg2::Arc { sweep, .. } if sweep.abs() > 1.5 * std::f64::consts::PI => 2, - _ => 1, - }) + /// `sheets` united in balanced rounds (each union of two sheets of about the same size); + /// `None` for none. + fn united(mut sheets: Vec) -> Result> { + while sheets.len() > 1 { + let mut next = Vec::with_capacity(sheets.len().div_ceil(2)); + let mut iter = sheets.into_iter(); + while let Some(a) = iter.next() { + next.push(match iter.next() { + Some(b) => combine(&a, &b, BoolOp::Union)?.ok_or_else(|| failed("sheet", "a union of faces is empty"))?, + None => a, }); - remaining_constructed_faces = remaining_constructed_faces - .checked_sub(edge_count.saturating_add(section.len().saturating_mul(2))) - .ok_or_else(|| KernelError::Failed("prism construction face budget".into()))?; - // This is a NEW exact extrusion of the current Boolean section, - // not copied lineage from either operand's old footprint. - for (r, piece) in crate::extrude(plane, section, levels[first], levels[end])?.into_iter().enumerate() { - remaining_faces = - remaining_faces.checked_sub(piece.face_count()).ok_or_else(|| KernelError::Failed("prism output face budget".into()))?; - // Each slab's section, as read there: the same outline, but its walls - // read beside whichever operand is there. - let layers = - (first..end).map(|k| Some((slabs.get(k)?.region(r), *levels.get(k)?, *levels.get(k + 1)?))).collect::>>(); - let layers = layers.ok_or_else(|| KernelError::Failed("missing prism section".into()))?; - pieces.push((piece, lineage::Built::Extruded { layers })); - } - } else { - let (piece, built) = sew_connected_sections(plane, d, &levels[first..=end], &slabs[first..end], tol, coalesce, history) - .ok_or_else(|| KernelError::Failed("stepped prism construction failed".into()))??; - remaining_faces = - remaining_faces.checked_sub(piece.face_count()).ok_or_else(|| KernelError::Failed("prism output face budget".into()))?; - pieces.push((piece, built)); } + sheets = next; } - let mut old = std::collections::HashMap::new(); - let mut shells = Vec::new(); - let mut remaining_map_faces = MAX_PLANAR_SEGMENTS * 2; - for (piece, _) in &pieces { - for (index, face) in piece.solid.face_iter().enumerate() { - remaining_map_faces = remaining_map_faces.checked_sub(1).ok_or_else(|| KernelError::Failed("prism output face budget".into()))?; - let source = piece.face_sources().and_then(|s| s.get(index)).and_then(Option::as_ref); - if old.insert(face.id(), Some((face.orientation(), source))).is_some() { - old.insert(face.id(), None); - } - } - shells.extend(piece.solid.boundaries().iter().cloned()); - } - let body = Body::new(crate::body::Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("prism compound: {e}")))?)?; - let sources = body - .solid - .face_iter() - .map(|face| match old.get(&face.id()) { - Some(Some((orientation, source))) if *orientation == face.orientation() => source.cloned(), - _ => None, - }) - .collect(); - let body = body.with_face_sources(Some(std::sync::Arc::new(sources))); - Ok(history.attach(body, &pieces)) - })()) -} + Ok(sheets.pop()) + } -/// Stable exact identity for the bounded analytic segment subset. -fn wall_key(s: &Seg2) -> Option<[u64; 6]> { - let bits = |v: f64| v.is_finite().then(|| if v == 0. { 0 } else { v.to_bits() }); - match s { - Seg2::Line { a, b } => Some([0, bits(a.x)?, bits(a.y)?, bits(b.x)?, bits(b.y)?, 0]), - Seg2::Arc { center, radius, start, sweep } => Some([1, bits(center.x)?, bits(center.y)?, bits(*radius)?, bits(*start)?, bits(*sweep)?]), - // Its ends and a point between them: free-form segments with the same ones are the same - // curve as far as a wall over it goes. - _ => { - let (a, m, b) = (s.start(), s.point_at(0.5), s.end()); - let h = |x: f64, y: f64| bits(x).zip(bits(y)).map(|(x, y)| x ^ y.rotate_left(17)); - Some([2, h(a.x, a.y)?, h(m.x, m.y)?, h(b.x, b.y)?, bits(m.x)?, bits(m.y)?]) + /// A closed loop, each segment with where it starts, split where it passes a point twice + /// (`same` start for two of its segments) into loops that pass every point once. + fn simple_loops(segs: Vec<(K, Seg2)>, same: impl Fn(&K, &K) -> bool) -> Vec { + let mut todo = vec![segs]; + let mut out = Vec::new(); + // Each split leaves two shorter loops, so the work is bounded by the segment count. + while let Some(segs) = todo.pop() { + let repeat = (0..segs.len()).find_map(|i| (i + 1..segs.len()).find(|&j| same(&segs[i].0, &segs[j].0)).map(|j| (i, j))); + match repeat { + Some((i, j)) => { + let mut rest = segs; + let inner: Vec<(K, Seg2)> = rest.drain(i..j).collect(); + rest.rotate_left(i); + todo.push(inner); + todo.push(rest); + } + None => out.push(Loop2 { segs: segs.into_iter().map(|(_, s)| s).collect() }), + } } + out } -} -/// A free-form segment as the control points of the cubic Bézier it is (a quadratic raised to -/// a cubic); `None` for those no cubic is exactly (rational conics, higher degrees). -fn cubic_of(s: &Seg2) -> Option<[Vec2; 4]> { - match *s { - Seg2::Cubic { p0, p1, p2, p3 } => Some([p0, p1, p2, p3]), - Seg2::Conic { a, apex, b, w } if (w - 1.0).abs() < 1e-12 => Some([a, a + (apex - a) * (2.0 / 3.0), b + (apex - b) * (2.0 / 3.0), b]), - Seg2::Bezier { n: 3, p } => Some([p[0], p[1], p[2], p[3]]), - _ => None, + /// `a` and `b` combined by `op`; `None` when nothing is left. + pub(super) fn combine(a: &Brep, b: &Brep, op: BoolOp) -> Result> { + let op = match op { + BoolOp::Union => BooleanOp::Union, + BoolOp::Cut => BooleanOp::Subtract, + BoolOp::Intersect => BooleanOp::Intersect, + }; + a.boolean2d(b, op).map_err(|e| failed("2D boolean", e)) } -} -/// A genuinely stepped connected axial block has no single extrusion footprint. -fn sew_connected_sections( - plane: &Plane, - d: Vec3, - levels: &[f64], - slabs: &[Section], - tol: f64, - coalesce: bool, - history: &lineage::Context, -) -> Option> { - use crate::sew::{EdgeSpec, FaceSpec, SurfSpec}; - // Faces at each level: up where the slab below sticks out, down where the one above does. - let diff = |x: &Section, y: &Section| -> Option
{ - match (x.regions.is_empty(), y.regions.is_empty()) { - (true, _) => Some(Section::default()), - (false, true) => Some(x.clone()), - (false, false) => boolean2d_tagged(x, y, BoolOp::Cut, tol).map(|r| r.oriented()), - } - }; - let empty = Section::default(); - let mut caps: Vec<(f64, bool, Section)> = Vec::new(); - for (k, z) in levels.iter().enumerate() { - let below: &Section = if k == 0 { &empty } else { slabs.get(k - 1)? }; - let above: &Section = slabs.get(k).unwrap_or(&empty); - caps.push((*z, true, diff(below, above)?)); - caps.push((*z, false, diff(above, below)?)); - } - // Every segment end, everywhere: outlines split there. - let loops_of = - |rs: &[Region2]| -> Vec { rs.iter().flat_map(|r| std::iter::once(r.outer.clone()).chain(r.holes.iter().cloned())).collect() }; - let mut pts: Vec = Vec::new(); - for lp in slabs.iter().flat_map(|s| loops_of(&s.regions)).chain(caps.iter().flat_map(|c| loops_of(&c.2.regions))) { - for sg in &lp.segs { - pts.push(sg.start()); - pts.push(sg.end()); - } - } - // Ends within `tol` of each other are one point. The 2D boolean closes its loops within - // `tol`, not exactly: where a font's nearly round curve was read as an arc, the arc ends a - // few hundredths of a micron from the curve next to it. Sewing joins only ends at the same - // point, so such a loop would not close. - let cell = |u: Vec2| ((u.x / tol).floor() as i64, (u.y / tol).floor() as i64); - let mut ends: Vec = Vec::new(); - let mut grid: std::collections::HashMap<(i64, i64), Vec> = std::collections::HashMap::new(); - let weld = |ends: &[Vec2], grid: &std::collections::HashMap<(i64, i64), Vec>, u: Vec2| -> Option { - let (cx, cy) = cell(u); - (cx - 1..=cx + 1) - .flat_map(|x| (cy - 1..=cy + 1).map(move |y| (x, y))) - .filter_map(|c| grid.get(&c)) - .flatten() - .filter_map(|&i| ends.get(i).copied()) - .find(|e| e.dist(u) <= tol) - }; - for &u in &pts { - if weld(&ends, &grid, u).is_none() { - grid.entry(cell(u)).or_default().push(ends.len()); - ends.push(u); - } - } - // Welding above keeps its original encounter order. Side splitting needs - // only the distinct stations, whose resulting parameters are sorted anyway. - // Deduplicate in place, with bounded sorting work and no extra point list. - if pts.len() <= MAX_PLANAR_SEGMENTS * 8 { - pts.sort_unstable_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); - pts.dedup_by_key(|p| (p.x.to_bits(), p.y.to_bits())); - } - // A piece of a free-form curve whose ends weld into one point (a font's curve cut a hair from - // its end) is no edge and has no wall: the pieces on either side meet there. (Lines and arcs - // are left as they were: such a piece of one fails the sewing, as before.) - let short = |s: &Seg2| { - !s.is_line_or_arc() - && s.length() <= 2.0 * tol - && matches!((weld(&ends, &grid, s.start()), weld(&ends, &grid, s.end())), (Some(p), Some(q)) if p == q) - }; - // One curve between two ends, as the walls and the caps beside them each read it: their - // sections come from different booleans, which split it from different pieces, so the - // control points can differ by a hair, and sewing tells edges apart by them. The first - // reading stands for all of them. - let chains: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); - let same_chain = |c: [Vec3; 4]| -> [Vec3; 4] { - let mid = |k: &[Vec3; 4]| (k[0] + (k[1] + k[2]) * 3.0 + k[3]) * 0.125; - let mut known = chains.borrow_mut(); - for k in known.iter() { - if mid(k).dist(mid(&c)) <= tol * 10.0 { - if k[0] == c[0] && k[3] == c[3] { - return *k; - } - if k[0] == c[3] && k[3] == c[0] { - return [k[3], k[2], k[1], k[0]]; - } + /// The faces of `sheet` as regions: each face's loops read off its edges exactly + /// ([`projected`]), the one running counter-clockwise about the face's normal its outer loop, + /// turned to run counter-clockwise in the plane and its holes clockwise. `tol` (mm, at least + /// the record's) is how far an edge's curve may end from its vertices. + pub(super) fn regions(sheet: &Brep, tol: f64) -> Result { + let record = sheet.to_native().map_err(|e| failed("export", e))?; + let tol = tol.max(record.tolerance); + let mut work = 2_000_000usize; + let mut owner: std::collections::HashMap = std::collections::HashMap::new(); + let mut touching = false; + let mut out = Vec::with_capacity(record.faces.len()); + for (f, face) in record.faces.iter().enumerate() { + let up = natural_normal(&face.surface).ok_or_else(|| failed("face", format!("face {f} is not on a plane")))?.z; + if up.abs() < 1.0 - 1e-9 { + return Err(failed("face", format!("face {f} is not in the plane of the regions"))); } - } - known.push(c); - c - }; - let at = |u: Vec2, z: f64| plane.to_world(u) + d * z; - let welded = |u: Vec2, z: f64| at(weld(&ends, &grid, u).unwrap_or(u), z); - // One edge between two ends, whichever way a wall or a cap reads the curve there: a piece of - // a font's curve so short that one section reads it as an arc within the tolerance, where - // another has the curve itself (the same letters cut again), is one edge. The first reading - // stands for all of them. - let readings: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); - let same_edge = |spec: EdgeSpec, a: Vec3, b: Vec3, mid: Vec3| -> EdgeSpec { - let mut known = readings.borrow_mut(); - for (ka, kb, km, k) in known.iter() { - if km.dist(mid) <= tol * 10.0 { - if *ka == a && *kb == b { - return k.clone(); - } - if *ka == b && *kb == a { - return k.reversed(); - } - } - } - known.push((a, b, mid, spec.clone())); - spec - }; - let edge = |sg: &Seg2, z: f64| -> Option { - Some(match sg { - Seg2::Line { .. } => EdgeSpec::Line { a: welded(sg.start(), z), b: welded(sg.end(), z) }, - Seg2::Arc { .. } => { - let (a, b, mid) = (welded(sg.start(), z), welded(sg.end(), z), at(sg.point_at(0.5), z)); - same_edge(EdgeSpec::Arc { a, b, mid }, a, b, mid) - } - _ => { - let [p0, p1, p2, p3] = cubic_of(sg)?; - let c = same_chain([welded(p0, z), at(p1, z), at(p2, z), welded(p3, z)]); - let mid = (c[0] + (c[1] + c[2]) * 3.0 + c[3]) * 0.125; - same_edge(EdgeSpec::Chain { degree: 3, ctrl: c.to_vec().into() }, c[0], c[3], mid) - } - }) - }; - // Exact oriented generated segments alone define a run. No support fitting, - // proximity matching, or old face lineage is used here. - // Each run, with what its wall is over in each of its slabs (for the result's history). - type Run = (usize, usize, Seg2, Vec); - let mut runs: Vec = Vec::new(); - let mut last = std::collections::BTreeMap::new(); - let mut remaining = MAX_PLANAR_SEGMENTS * 2; - for (i, slab) in slabs.iter().enumerate() { - for (r, reg) in slab.regions.iter().enumerate() { - for (l, lp) in std::iter::once(®.outer).chain(®.holes).enumerate() { - // The loop's walls in order: the run each joins, its tag and where it ends. - let mut around: Vec<(usize, Tag, Vec2)> = Vec::new(); - for (si, sg0) in lp.segs.iter().enumerate() { - let pieces = split_seg(sg0, &pts, tol)?; - let (n, tag) = (pieces.len(), slab.tag(r, l, si)); - for (k, sg) in pieces.into_iter().enumerate() { - if short(&sg) { - continue; - } - remaining = remaining.checked_sub(1)?; - let key = wall_key(&sg)?; - let prior = if coalesce { last.get(&key).copied() } else { None }; - let run = match prior.map(|index| runs.get_mut(index).map(|run: &mut Run| (index, run))) { - Some(None) => return None, - Some(Some((index, run))) if run.1 == i => { - run.1 = i + 1; - index - } - // Duplicate oriented boundaries in one slab are not - // a valid reason to reconstruct a larger wall. - Some(Some((_, run))) if run.1 == i + 1 => return None, - _ => { - if coalesce { - last.insert(key, runs.len()); - } - runs.push((i, i + 1, sg, Vec::new())); - runs.len() - 1 - } - }; - around.push((run, tag.piece(k, n), sg.end())); + // Each loop as it runs in the plane, then split where it passes a point twice (a + // cut-out touching the outline, material meeting at a corner): counter-clockwise + // pieces are material, the others holes in the material that holds them. + // A loop passes a point twice where it passes one vertex of the record twice: the + // record's vertices, not their places, which may lie closer together than its + // tolerance at the ends of a short edge. + let mut pieces = Vec::new(); + for lp in &face.loops { + let Loop::Edges { edges } = lp else { return Err(failed("face", format!("face {f} has a vertex loop"))) }; + let mut segs = Vec::new(); + for e in edges { + let edge = record.edges.get(e.edge as usize).ok_or_else(|| failed("edge", format!("edge {} is missing", e.edge)))?; + let run = Run::of(&record, e.edge as usize, e.forward).ok_or_else(|| failed("edge", format!("edge {} is missing", e.edge)))?; + let read = projected(&run, &Plane::XY, tol, &mut work) + .ok_or_else(|| failed("edge", format!("edge {} of face {f} is not read exactly in the plane", e.edge)))?; + // The first piece of the edge starts on the use's first vertex. + let start = if e.forward { edge.vertices[0] } else { edge.vertices[1] }; + segs.extend(read.into_iter().enumerate().map(|(k, s)| ((k == 0).then_some(start), s))); + for v in edge.vertices { + touching |= *owner.entry(v).or_insert(f) != f; } } - // Each wall runs into the next one of its loop, the last into the first. - for (k, (run, tag, at)) in around.iter().enumerate() { - let next = around.get((k + 1) % around.len())?.0; - runs.get_mut(*run)?.3.push(lineage::Slab { tag: *tag, next, at: *at }); + // Seen from the face's normal, the outer loop runs counter-clockwise and holes clockwise. + for piece in simple_loops(segs, |a, b| a.is_some() && a == b) { + pieces.push(if up > 0.0 { piece } else { piece.reversed() }); } } - } - } - let mut faces: Vec = Vec::new(); - let mut sources = Vec::new(); - let mut specs: Vec = Vec::with_capacity(runs.len()); - let frame_is_orthonormal = plane.origin.is_finite() - && plane.x.is_finite() - && plane.y.is_finite() - && d.is_finite() - && (plane.x.len2() - 1.).abs() <= 64. * f64::EPSILON - && (plane.y.len2() - 1.).abs() <= 64. * f64::EPSILON - && (d.len2() - 1.).abs() <= 64. * f64::EPSILON - && plane.x.dot(plane.y).abs() <= 64. * f64::EPSILON - && plane.x.dot(d).abs() <= 64. * f64::EPSILON - && plane.y.dot(d).abs() <= 64. * f64::EPSILON; - for (first, end, sg, over) in runs { - let (z0, z1) = (levels[first], levels[end]); - let (a, b) = (sg.start(), sg.end()); - let mut lp3 = Vec::with_capacity(2 + 2 * (end - first)); - lp3.push(edge(&sg, z0)?); - // Keep station vertices at both ends: neighboring stepped walls/caps - // must share complete edges rather than create T-junctions. - for k in first..end { - lp3.push(EdgeSpec::Line { a: welded(b, levels[k]), b: welded(b, levels[k + 1]) }); - } - lp3.push(edge(&sg.reversed(), z1)?); - for k in (first..end).rev() { - lp3.push(EdgeSpec::Line { a: welded(a, levels[k + 1]), b: welded(a, levels[k]) }); - } - let outward = plane.dir_to_world(sg.derivative(0.5)).cross(d).normalized()?; - let surface = match sg { - Seg2::Line { .. } => SurfSpec::Plane, - Seg2::Arc { .. } => SurfSpec::Extruded { a: at(a, z0), b: at(b, z0), mid: at(sg.point_at(0.5), z0), dir: d * (z1 - z0) }, - // A free-form wall: the lines along `d` joining the curve at both levels. - _ => SurfSpec::Ruled { a: edge(&sg, z0)?, b: edge(&sg, z1)? }, - }; - faces.push(FaceSpec { loops: vec![lp3], surface, probe: Some((at(sg.point_at(0.5), (z0 + z1) / 2.0), outward)) }); - // Axis-aligned generated lines have a common oriented support frame - // independent of axial stations or along-line endpoint interpolation. - let generated_plane = if coalesce - && frame_is_orthonormal - && let Seg2::Line { a, b } = sg - { - let (origin, x) = if a.y == b.y && a.x != b.x { - (at(Vec2::new(0., a.y), 0.), plane.x * (b.x - a.x).signum()) - } else if a.x == b.x && a.y != b.y { - (at(Vec2::new(a.x, 0.), 0.), plane.y * (b.y - a.y).signum()) - } else { - (Vec3::ZERO, Vec3::ZERO) - }; - (origin.is_finite() && x.len2() > 0.).then_some(Plane { origin, x, y: d }) - } else { - None - }; - sources.push((generated_plane.is_some() || end > first + 1).then_some(crate::FaceSource::ExtrudeSide { - segment: sg, - plane: generated_plane, - coalesced: end > first + 1, - })); - specs.push(lineage::Spec::Wall { levels: levels.get(first..=end)?.to_vec(), slabs: over }); - } - for (z, up, rs) in &caps { - for (ri, r) in rs.regions.iter().enumerate() { - let mut loops = Vec::new(); - for lp in std::iter::once(&r.outer).chain(&r.holes) { - let mut segs: Vec = Vec::new(); - for sg in &lp.segs { - segs.extend(split_seg(sg, &pts, tol)?.into_iter().filter(|s| !short(s))); - } - let segs: Vec = if *up { segs } else { segs.iter().rev().map(Seg2::reversed).collect() }; - loops.push(segs.iter().map(|sg| edge(sg, *z)).collect::>>()?); + let (outers, holes): (Vec, Vec) = pieces.into_iter().partition(|lp| lp.signed_area() > 0.0); + let first = out.len(); + out.extend(outers.into_iter().map(|outer| Region2 { outer, holes: Vec::new() })); + for hole in holes { + // The smallest material piece of this face holding the hole's middle. + let mid = hole.segs.first().map(|s| s.point_at(0.5)).ok_or_else(|| failed("face", format!("face {f} has an empty loop")))?; + let owner = out[first..] + .iter_mut() + .filter(|r| holds(&r.outer, mid)) + .min_by(|a, b| a.outer.signed_area().total_cmp(&b.outer.signed_area())) + .ok_or_else(|| failed("face", format!("face {f} has a hole outside its material")))?; + owner.holes.push(hole); } - faces.push(FaceSpec { loops, surface: SurfSpec::Plane, probe: None }); - sources.push(None); - specs.push(lineage::Spec::Cap { section: rs.region(ri), z: *z, up: *up }); + } + Ok(Regions { regions: out, touching }) + } + + /// Whether the loop `outer` holds `p`: even-odd against its polyline within a quarter of + /// `p`'s distance from it, so the polyline's chords cannot pass `p` by (a loop's own + /// [`Loop2::contains`] reads it within 1e-3 mm, and a hole closer than that to an arc of the + /// outline was taken for one outside it, a chord cutting it off). + fn holds(outer: &Loop2, p: Vec2) -> bool { + let d = outer.segs.iter().map(|s| s.point_at(s.closest_param(p)).dist(p)).fold(f64::INFINITY, f64::min); + outer.polyline((d * 0.25).clamp(1e-9, 1e-3)).contains(p) + } + + /// The natural normal of a planar surface record. + fn natural_normal(s: &Surface) -> Option { + let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]); + match s { + Surface::Plane { u_axis, v_axis, .. } => v(*u_axis).cross(v(*v_axis)).normalized(), + Surface::PlaneThrough { origin, u_point, v_point } => (v(*u_point) - v(*origin)).cross(v(*v_point) - v(*origin)).normalized(), + _ => None, } } - let sewn = crate::sew::sew_touching_with_sources(&faces, &sources).map(|(body, from)| (body, lineage::Built::Sewn { specs, faces: from })); - // Generated walls joined on their common supports: the piece's history over the operands, - // carried through the joining. - Some(if coalesce { - sewn.and_then(|(body, built)| { - let body = history.attach(body.clone(), &[(&body, built)]).regularize_generated_planar_faces()?; - Ok((body, lineage::Built::Traced)) - }) - } else { - sewn - }) -} - -#[cfg(test)] -fn simple_prism_boolean(a: &Body, b: &Body, op: BoolOp) -> Option>> { - simple_prism_indexed(a, b, op, [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)]) -} - -/// [`prism_boolean`] of single prisms, the operands' indexes given. -fn simple_prism_indexed(a: &Body, b: &Body, op: BoolOp, [ia, ib]: [&LazyIndex; 2]) -> Option>> { - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - // Candidate directions (each line once, pointing up). - let dirs: Vec = directions(a, b)?.into_iter().map(|n| if n.dot(Vec3::new(1e-3, 1e-6, 1.0)) < 0.0 { -n } else { n }).collect(); - let (d, plane, pa, pb) = dirs.into_iter().find_map(|d| { - let plane = Plane::from_normal(Vec3::ZERO, d)?; - let pa = prism_tagged(a, d, &plane, tol, ia)?; - let pb = prism_tagged(b, d, &plane, tol, ib)?; - Some((d, plane, pa, pb)) - })?; - let history = lineage::Context::new(op, [a, b], [ia.get(), ib.get()], plane, tol, Some([(pa.lo, pa.hi), (pb.lo, pb.hi)])); - let (blo, bhi) = heights_of(b, &plane); - let spans = blo <= pa.lo + tol && bhi >= pa.hi - tol; - let same = (pb.lo - pa.lo).abs() < tol && (pb.hi - pa.hi).abs() < tol; - let area = - |rs: &[Region2]| rs.iter().map(|r| r.outer.signed_area().abs() - r.holes.iter().map(|h| h.signed_area().abs()).sum::()).sum::(); - // Prisms of one section overlapping or touching end to end: one longer prism. - let stacked = op == BoolOp::Union && !same && pb.lo <= pa.hi + tol && pa.lo <= pb.hi + tol; - let ok = match op { - BoolOp::Cut => spans, - // An intersection keeps only the common height. Unlike a through cut, its - // other operand need not span the target's entire extrusion. - BoolOp::Intersect => { - if pa.hi <= pb.lo || pb.hi <= pa.lo { - return Some(Ok(None)); - } - true - } - BoolOp::Union => same || stacked, - }; - if !ok { - return None; - } - let section = boolean2d_tagged(&pa.section, &pb.section, op, tol)?; - let regions = §ion.regions; - if regions.is_empty() { - return Some(Ok(None)); - } - // Keep newly clipped perforated sections on the established B-rep route. Re-extruding - // a thin annulus with different circular seam splits can leave both cap meshes empty. - if op == BoolOp::Intersect && !spans && regions.iter().any(|r| !r.holes.is_empty()) { - return None; - } - let (u, x, y) = (area(regions), area(&pa.section.regions), area(&pb.section.regions)); - let alike = |v: f64| (u - v).abs() <= tol * (1.0 + u); - // A tool that misses its target (or an intersection that is one operand whole) leaves it - // as it is: the B-rep boolean reuses that operand itself, where this would rebuild it. - if matches!(op, BoolOp::Cut | BoolOp::Intersect) && (same_area(u, x, tol) || (op == BoolOp::Intersect && same_area(u, y, tol))) { - return None; - } - let (lo, hi) = if stacked { - // Different sections (a boss hanging over a plate's edge): sewn slab by slab. - if !alike(x) || !alike(y) { - return sew_stack(&plane, d, &pa, &pb, tol, &history).map(|r| r.map(Some)); - } - // One outline end to end: also slab by slab, so the history follows each operand's - // walls (one longer prism, whose walls are made from both). - if let Some(Ok(body)) = sew_stack(&plane, d, &pa, &pb, tol, &history) - && body.history().is_some() - { - return Some(Ok(Some(body))); - } - (pa.lo.min(pb.lo), pa.hi.max(pb.hi)) - } else if op == BoolOp::Intersect { - (pa.lo.max(pb.lo), pa.hi.min(pb.hi)) - } else { - (pa.lo, pa.hi) - }; - let base = plane.offset(lo); - let bodies = match crate::extrude(&base, regions, 0.0, hi - lo) { - Ok(b) => b, - Err(e) => return Some(Err(e)), - }; - // Each body over its region. - let mut pieces: Vec<(Body, lineage::Built)> = - bodies.into_iter().enumerate().map(|(r, b)| (b, lineage::Built::Extruded { layers: vec![(section.region(r), lo, hi)] })).collect(); - let last = pieces.pop()?; - if !pieces.is_empty() { - // Several pieces: one body of several lumps (the last first). - pieces.push(last); - pieces.rotate_right(1); - let shells: Vec = pieces.iter().flat_map(|(b, _)| b.solid.boundaries().iter().cloned()).collect(); - return Some( - crate::body::Solid::try_new(shells) - .map_err(|e| crate::KernelError::Failed(e.to_string())) - .and_then(Body::new) - .map(|body| Some(history.attach(body, &pieces))), - ); - } - Some(Ok(Some(history.attach(last.0.clone(), &[last])))) -} - -/// The directions to try the operands as prisms along: the first eight plane directions of the -/// target (in its face order), then those of the tool's caps (a pair of opposite plane faces) -/// that the target has further on. A target cut many times over (a line of text, a group of -/// letters at a time) has more plane directions than eight, its walls' among them: in face -/// order its caps' direction can come too late. `None` past the face budget. -fn directions(a: &Body, b: &Body) -> Option> { - if a.face_count().saturating_add(b.face_count()) > MAX_PLANAR_SEGMENTS * 2 { - return None; - } - let normals = |x: &Body| -> Vec { - x.solid - .face_iter() - .filter_map(|f| match f.oriented_surface() { - mt::Surface::Plane(p) => { - let n = p.normal(); - Vec3::new(n.x, n.y, n.z).normalized() - } - _ => None, - }) - .collect() - }; - let mut target: Vec = Vec::new(); - for n in normals(a) { - if !target.iter().any(|m| m.dot(n).abs() > 1.0 - 1e-9) { - target.push(n); - } - } - let tool = normals(b); - let capped = |d: &Vec3| tool.iter().any(|n| n.dot(*d) > 1.0 - 1e-9) && tool.iter().any(|n| n.dot(*d) < -1.0 + 1e-9); - let mut dirs: Vec = target.iter().take(8).copied().collect(); - dirs.extend(target.iter().skip(8).filter(|d| capped(d)).take(8)); - Some(dirs) -} - -/// The direction `b` is a prism (or a stack of prisms) along: the first of its planar faces' -/// normals along which it is one. `None` when there is none. -pub(crate) fn prism_axis(b: &Body) -> Option { - if b.face_count() > MAX_PLANAR_SEGMENTS { - return None; - } - let tol = (b.size() * 1e-7).max(1e-9) * 10.0; - let index = LazyIndex::new(b, 1); - let mut tried: Vec = Vec::new(); - for f in b.solid.face_iter() { - let mt::Surface::Plane(p) = f.oriented_surface() else { continue }; - let n = p.normal(); - let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { continue }; - if tried.iter().any(|m| m.dot(n).abs() > 1.0 - 1e-9) { - continue; - } - tried.push(n); - if tried.len() > 16 { - return None; - } - let plane = Plane::from_normal(Vec3::ZERO, n)?; - if stack_tagged(b, n, &plane, tol, &index).is_some() { - return Some(n); - } - } - None -} - -/// Whether a boolean of sections left one of area `v` as it was (area `u` after): the same to -/// within rounding, as the very same outline gives (a change is at least a sliver `tol` wide). -fn same_area(u: f64, v: f64, tol: f64) -> bool { - (u - v).abs() <= 1e-9 * u.abs().max(v.abs()) + tol * tol -} - -/// A stepped extrusion (case floor plus walls), recovered from its cap events. -/// Downward caps add a section above their level; upward caps remove one. -#[cfg(test)] -fn stack_of(b: &Body, d: Vec3, plane: &Plane, tol: f64) -> Option> { - stack_tagged(b, d, plane, tol, &LazyIndex::new(b, 0)) -} - -/// [`stack_of`], its sections' segments tagged from `index` (the body's). -fn stack_tagged(b: &Body, d: Vec3, plane: &Plane, tol: f64, index: &LazyIndex) -> Option> { - if let Some(p) = prism_tagged(b, d, plane, tol, index) { - return Some(vec![p]); - } - if b.face_count() > 2048 { - return None; - } - let mut events = Vec::new(); - let mut walls = std::collections::HashMap::new(); - let mut wall_work = 262_144; - let mut curve_work = 2_000_000; - let mut segments = usize::MAX; - for (fi, f) in b.solid.face_iter().enumerate() { - let surf = f.oriented_surface(); - if let mt::Surface::Plane(p) = &surf { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - if n.dot(d).abs() > 1.0 - 1e-9 { - let section = Section::from_loops(index.get().loops(f, fi, plane, tol, &mut curve_work, &mut segments)?)?; - events.push((plane.height(from_p3(p.origin())), n.dot(d) > 0.0, section.oriented(), fi)); - continue; - } - if n.dot(d).abs() > 1e-9 { - return None; - } - } else if !wall_along(&surf, d, tol, &mut wall_work) { - return None; - } - walls.insert(fi, top_of(f, plane)); - } - let mut levels: Vec = events.iter().map(|(z, _, _, _)| *z).collect(); - levels.sort_by(f64::total_cmp); - levels.dedup_by(|x, y| (*x - *y).abs() < tol); - if levels.len() < 2 || levels.len() > 64 || levels.iter().any(|z| !z.is_finite()) { - return None; - } - let stations = Stations::new(index.get(), walls, d, plane, tol); - let mut current = Section::default(); - let mut stack: Vec = Vec::new(); - let mut budget = MAX_PLANAR_PAIRS; - for (i, z) in levels.iter().enumerate() { - // The caps here end the slab below: its walls meet them. - if let Some(below) = stack.last_mut().filter(|p| (p.hi - *z).abs() < tol) { - let (faces, caps): (Vec, Vec<&Section>) = - events.iter().filter(|(h, _, _, _)| (*h - *z).abs() < tol).map(|(_, _, s, f)| (*f, s)).unzip(); - below.section.mark_far(&caps, |w| stations.top_edge(index.get(), w, &faces, *z, tol), tol, &mut budget); - } - // The segments carried here run on past it, beside the walls there. - current.retag(|t| match t.wall { - Some(w) => t.beside(stations.past(w, *z, tol)), - None => t, - }); - // Remove terminating material before adding any material starting here. - for up in [true, false] { - for (_, _, section, _) in events.iter().filter(|(h, u, _, _)| (*h - *z).abs() < tol && *u == up) { - current = match (current.regions.is_empty(), up) { - (true, false) => section.clone(), - (true, true) => return None, - (false, _) => boolean2d_tagged(¤t, section, if up { BoolOp::Cut } else { BoolOp::Union }, tol)?, - }; - } - } - if let Some(next) = levels.get(i + 1) - && !current.regions.is_empty() - { - current.drop_crossed(&stations, *z, *next, tol); - stack.push(Prism { lo: *z, hi: *next, section: current.oriented() }); - } - } - (current.regions.is_empty() && !stack.is_empty()).then_some(stack) -} - -#[cfg(test)] -fn stack_boolean(a: &Body, b: &Body, op: BoolOp) -> Option>> { - stack_indexed(a, b, op, [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)], true) -} - -/// [`prism_boolean`] of stepped prisms, the operands' indexes given. A union is taken of -/// operands that end at a common level when `common_cap` is set, else of those that don't (see -/// [`prism_union_between_caps`]). -fn stack_indexed(a: &Body, b: &Body, op: BoolOp, [ia, ib]: [&LazyIndex; 2], common_cap: bool) -> Option>> { - // Common-cap joins and overlapping partial-depth cuts of aligned stepped prisms can - // retain their exact section boundaries instead of intersecting meshes. - // Nonaligned bodies retain their existing B-rep path. - if !matches!(op, BoolOp::Union | BoolOp::Cut) { - return None; - } - if op == BoolOp::Cut && a.face_count().saturating_add(b.face_count()) > 2048 { - return None; - } - fn section(ps: &[Prism], lo: f64, hi: f64, tol: f64) -> Section { - ps.iter().find(|p| p.lo <= lo + tol && p.hi >= hi - tol).map(|p| p.section.clone()).unwrap_or_default() - } - let tol = (a.size().max(b.size()) * 1e-7).max(1e-9) * 10.0; - let dirs = directions(a, b)?; - let ends = |ps: &[Prism]| ps.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.lo), hi.max(p.hi))); - let (d, plane, pa, pb) = dirs.into_iter().find_map(|d| { - let plane = Plane::from_normal(Vec3::ZERO, d)?; - let pa = stack_tagged(a, d, &plane, tol, ia)?; - let pb = stack_tagged(b, d, &plane, tol, ib)?; - let (ea, eb) = (ends(&pa), ends(&pb)); - let shared = (ea.0 - eb.0).abs() < tol || (ea.1 - eb.1).abs() < tol; - match op { - BoolOp::Union if shared != common_cap => return None, - // A cut tool may extend past a cap into empty space. Exact slab sections - // discard that space rather than intersecting coincident cylinder walls. - BoolOp::Cut if ea.1 <= eb.0 + tol || eb.1 <= ea.0 + tol => return None, - _ => {} - } - Some((d, plane, pa, pb)) - })?; - let mut levels: Vec = pa.iter().chain(&pb).flat_map(|p| [p.lo, p.hi]).collect(); - levels.sort_by(f64::total_cmp); - levels.dedup_by(|x, y| (*x - *y).abs() < tol); - let mut slabs = Vec::new(); - let mut work = 0usize; - let mut output_edges = 0usize; - let area = - |rs: &[Region2]| rs.iter().map(|r| r.outer.signed_area().abs() - r.holes.iter().map(|h| h.signed_area().abs()).sum::()).sum::(); - // Whether some slab's section came out other than the target's (else the tool missed it). - let mut changed = false; - let edges = |regions: &[Region2]| regions.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).map(|l| l.segs.len()).sum::(); - for w in levels.windows(2) { - let (lo, hi) = (*w.first()?, *w.get(1)?); - let (x, y) = (section(&pa, lo, hi, tol), section(&pb, lo, hi, tol)); - let before = area(&x.regions); - if op == BoolOp::Cut { - let count = edges(&x.regions).saturating_add(edges(&y.regions)); - work = work.saturating_add(count.saturating_mul(count)); - if work > 32_000_000 { - return None; - } - } - let s = match (x.regions.is_empty(), y.regions.is_empty(), op) { - (true, _, BoolOp::Cut | BoolOp::Intersect) | (_, true, BoolOp::Intersect) => Section::default(), - (true, _, BoolOp::Union) => y, - (_, true, _) => x, - _ => boolean2d_tagged(&x, &y, op, tol)?, - }; - changed |= !same_area(area(&s.regions), before, tol); - if op == BoolOp::Cut { - output_edges = output_edges.saturating_add(edges(&s.regions)); - if output_edges > 8192 { - return None; - } - } - slabs.push(s.oriented()); - } - if slabs.iter().all(|s| s.regions.is_empty()) { - return Some(Ok(None)); - } - // A cut that takes nothing leaves the target as it is: the B-rep boolean reuses it itself, - // where this would rebuild it. - if op == BoolOp::Cut && !changed { - return None; - } - let history = lineage::Context::new(op, [a, b], [ia.get(), ib.get()], plane, tol, None); - let coalesce = op == BoolOp::Cut - && !a.regularization_protected - && !b.regularization_protected - && a.split_keep().is_empty() - && b.split_keep().is_empty() - && a.paint().is_none_or(|p| p.faces.is_empty()) - && b.paint().is_none_or(|p| p.faces.is_empty()); - sew_sections(&plane, d, &levels, &slabs, tol, coalesce, &history).map(|r| r.map(Some)) -} - -thread_local! { - /// Set while [`prism_boolean_free_form`] runs: spline outlines are read as arcs within - /// [`PLANAR_FIT_TOL`] instead of refusing the prism. - static FREE_FORM: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// [`prism_boolean`] for prisms whose walls are splines (swept along one): the outlines are -/// fitted by arcs within [`PLANAR_FIT_TOL`], so the result is exact to that, and the walls it -/// keeps are those arcs. Only for bodies the caller knows are such sweeps. -pub(crate) fn prism_boolean_free_form(a: &Body, b: &Body, op: BoolOp) -> Option>> { - /// Clears the flag however the boolean ends, a caught panic included. - struct Reset; - impl Drop for Reset { - fn drop(&mut self) { - FREE_FORM.with(|c| c.set(false)); - } - } - FREE_FORM.with(|c| c.set(true)); - let _reset = Reset; - prism_boolean(a, b, op) -} - -/// Boolean of prisms along a common direction, in 2D (see the module notes); `None` when it -/// doesn't apply. The result carries its history over `[a, b]` (see [`lineage`]). -pub(crate) fn prism_boolean(a: &Body, b: &Body, op: BoolOp) -> Option>> { - // Each operand's index is built once, and only if it is read as a prism. - let index = [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)]; - crate::guard("prism boolean", || Ok(simple_prism_indexed(a, b, op, index).or_else(|| stack_indexed(a, b, op, index, true)))).ok().flatten() -} - -/// [`prism_boolean`] of a union of stepped prisms along one direction that end at different -/// levels (a barrel joined between two faces of a wider part, its ends flush with them), which -/// that route leaves to the B-rep boolean: for when that boolean has failed. `None` for other -/// operations and operands. -pub(crate) fn prism_union_between_caps(a: &Body, b: &Body, op: BoolOp) -> Option>> { - if op != BoolOp::Union { - return None; - } - let index = [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)]; - crate::guard("prism boolean", || Ok(stack_indexed(a, b, op, index, false))).ok().flatten() } #[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] mod planar_tests { use super::*; + use solidcore_record::Loop2; #[test] fn single_prism_intersection_uses_common_height_in_both_orders() { for k in [1.0, 0.05] { @@ -2609,10 +304,11 @@ mod planar_tests { (22.5, 10.0, None), (25.0, 10.0, None), ] { - let a = crate::cylinder(Vec3::new(12.5, 5.0, 5.0) * k, Vec3::Z, 2.5 * k, 17.5 * k).unwrap(); - let b = crate::box_solid(Vec3::new(10.0, 5.0, lo) * k, Vec3::new(22.5, 10.0, lo + height) * k).unwrap(); + let a = crate::cylinder(solidcore_record::Vec3::new(12.5, 5.0, 5.0) * k, solidcore_record::Vec3::Z, 2.5 * k, 17.5 * k).unwrap(); + let b = crate::box_solid(solidcore_record::Vec3::new(10.0, 5.0, lo) * k, solidcore_record::Vec3::new(22.5, 10.0, lo + height) * k) + .unwrap(); for (lhs, rhs) in [(&a, &b), (&b, &a)] { - let result = simple_prism_boolean(lhs, rhs, BoolOp::Intersect).expect("the exact prism route applies").unwrap(); + let result = crate::boolean(lhs, rhs, BoolOp::Intersect).unwrap(); if let Some((bottom, top)) = expected { let body = result.expect("a positive-height half disc is a solid"); assert!(body.validity().is_empty()); @@ -2620,7 +316,7 @@ mod planar_tests { let expected = std::f64::consts::PI * (2.5 * k).powi(2) * (top - bottom) * k / 2.0; let actual = crate::measure(&body).unwrap().volume; assert!((actual - expected).abs() < expected * 2e-3, "{lo} {height} {k}: {actual} != {expected}"); - let bounds = body.tessellate(k * 1e-3).unwrap().bounds(); + let bounds = body.mesh(&crate::MeshTolerance::chord(k * 1e-3)).unwrap().bounds(); assert!((bounds.min.z - bottom * k).abs() < k * 1e-7); assert!((bounds.max.z - top * k).abs() < k * 1e-7); } else { @@ -2662,485 +358,27 @@ mod planar_tests { } } #[test] - fn analytic_projection_keeps_clamped_lines_and_wrapped_arcs() { - let line = Seg2::Line { a: Vec2::new(2., 3.), b: Vec2::new(5., 7.) }; - for (point, expected) in [(Vec2::new(-1., -1.), 0.), (Vec2::new(3.5, 5.), 0.5), (Vec2::new(8., 11.), 1.)] { - assert!((closest_param(&line, point) - expected).abs() < 1e-12); - } - for start in [-7., -0.5, 3., 7.] { - for sweep in [-std::f64::consts::TAU, -5., -0.2, 0.2, 5., std::f64::consts::TAU] { - let arc = Seg2::Arc { center: Vec2::new(2., -3.), radius: 4., start, sweep }; - for index in 0..128 { - let angle = index as f64 * std::f64::consts::TAU / 128.; - let point = Vec2::new(2., -3.) + Vec2::new(angle.cos(), angle.sin()) * 6.; - let nearest = arc.point_at(closest_param(&arc, point)); - // Includes both signs, sweeps over pi, seam crossings and endpoint clamps. - for sample in 0..=128 { - assert!(nearest.dist(point) <= arc.point_at(sample as f64 / 128.).dist(point) + 1e-10); - } - } - for t in [0., 0.25, 0.5, 0.75, 1.] { - let point = arc.point_at(t); - assert!(arc.point_at(closest_param(&arc, point)).dist(point) < 1e-10); - } - } - } + fn a_ledge_shorter_than_the_record_tolerance_reads_back_as_one_region() { + // A plate with a ledge 0.0001 tall along part of its lower edge: SMLib's record holds a + // tolerance of 2e-5 mm, so the ledge's short side has both ends within ten times that. + // Read back, its outline is one loop of six lines, not split into a loop of one line. + let ledged = Region2 { + outer: Loop2::polygon( + &[(100.0, 3.0), (100.0, 3.0001), (97.0, 3.0001), (97.0, 60.0), (0.0, 60.0), (0.0, 3.0)].map(|(x, y)| Vec2::new(x, y)), + ), + holes: vec![], + }; + let below = rectangle(Vec2::new(0.0, -12.0), Vec2::new(100.0, 0.0)); + let out = planar_regions_boolean(std::slice::from_ref(&ledged), std::slice::from_ref(&below), BoolOp::Union, 1e-7).unwrap(); + assert_eq!(out.len(), 2, "{out:?}"); + let top = out.iter().find(|r| r.outer.contains(Vec2::new(50.0, 30.0))).unwrap(); + assert!(top.outer.segs.len() == 6 && top.outer.is_closed(1e-9), "{top:?}"); + assert!((top.area() - ledged.area()).abs() < 1e-9, "{}", top.area()); } fn rectangle(a: Vec2, b: Vec2) -> Region2 { Region2 { outer: Loop2::polygon(&[a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)]), holes: vec![] } } #[test] - fn simple_prism_retains_large_analytic_section_budget() { - let count = 2050; - let radius = 1000.; - let points: Vec<_> = (0..count) - .map(|i| { - let angle = std::f64::consts::TAU * i as f64 / count as f64; - Vec2::new(radius * angle.cos(), radius * angle.sin()) - }) - .collect(); - let region = Region2 { outer: Loop2::polygon(&points), holes: vec![] }; - let stock = crate::extrude(&Plane::XY, &[region], 0., 2.).unwrap().pop().unwrap(); - assert_eq!(stock.face_count(), count + 2); - assert!(stock.face_count() > 2048 && stock.validity().is_empty()); - let before: Vec<_> = stock.solid.vertex_iter().map(|v| (v.id(), v.point())).collect(); - let recovered = prism_of(&stock, Vec3::Z, &Plane::XY, 1e-5).expect("large simple line prism remains supported"); - assert_eq!(recovered.section.regions.len(), 1); - assert_eq!(recovered.section.regions[0].outer.segs.len(), count); - assert!(recovered.section.regions[0].outer.segs.iter().all(|s| matches!(s, Seg2::Line { .. }))); - let area = count as f64 * radius * radius * (std::f64::consts::TAU / count as f64).sin() / 2.; - assert!((recovered.section.regions[0].area() - area).abs() < area * 1e-12); - assert!((recovered.lo - 0.).abs() < 1e-8 && (recovered.hi - 2.).abs() < 1e-8); - let cutter = crate::box_solid(Vec3::new(-1001., -1001., -1.), Vec3::new(1001., 1001., 3.)).unwrap(); - assert!( - simple_prism_boolean(&stock, &cutter, BoolOp::Cut) - .expect("large analytic section routes through the exact simple path") - .unwrap() - .is_none() - ); - assert_eq!(stock.solid.vertex_iter().map(|v| (v.id(), v.point())).collect::>(), before); - } - #[test] - fn curved_stop_cut_constructs_fresh_current_cap_for_only_uniform_lump() { - let cylinder = crate::cylinder(Vec3::new(25., 25., 0.), Vec3::Z, 2., 20.).unwrap(); - let stop = crate::box_solid(Vec3::new(19., 19., 1.), Vec3::new(31., 31., 2.)).unwrap(); - let roof = crate::boolean(&cylinder, &stop, BoolOp::Union).unwrap().unwrap(); - let original = rectangle(Vec2::new(20., 20.), Vec2::new(30., 30.)); - let tool = crate::extrude(&Plane::XY, &[original], 0., 25.).unwrap().pop().unwrap(); - let before_tool = crate::step_export(&[&tool], "tool").unwrap(); - let before_roof = crate::step_export(&[&roof], "roof").unwrap(); - let trimmed = crate::boolean(&tool, &roof, BoolOp::Cut).unwrap().unwrap(); - let lumps = trimmed.lumps().unwrap(); - assert_eq!(lumps.len(), 2); - let mut lower = 0; - let mut upper = 0; - for lump in &lumps { - assert!(lump.validity().is_empty()); - let mesh = lump.tessellate(1e-5).unwrap(); - if mesh.contains(Vec3::new(21., 21., 0.5)) { - lower += 1; - assert!(!mesh.contains(Vec3::new(25., 25., 0.5))); - assert!(!mesh.contains(Vec3::new(21., 21., 1.5))); - assert!((mesh.measure().volume - (100. - 4. * std::f64::consts::PI)).abs() < 0.002); - let sources = lump.face_sources().expect("fresh actual extrusion has complete sources"); - assert_eq!(sources.len(), lump.face_count()); - assert!(sources.iter().all(Option::is_some)); - let mut caps = 0; - for source in sources.iter().flatten() { - match source { - crate::FaceSource::ExtrudeCap { region, plane, .. } => { - assert_eq!(region.holes.len(), 1); - assert!((region.area() - (100. - 4. * std::f64::consts::PI)).abs() < 1e-8); - assert!(plane.normal().z.abs() > 1. - 1e-10); - assert!((plane.origin.z - if plane.normal().z > 0. { 1. } else { 0. }).abs() < 1e-8); - caps += 1; - } - crate::FaceSource::ExtrudeSide { .. } => {} - _ => panic!("old producer lineage must not survive a changed Boolean footprint"), - } - } - assert_eq!(caps, 2); - } else { - upper += 1; - assert!(mesh.contains(Vec3::new(21., 21., 3.))); - assert!(!mesh.contains(Vec3::new(25., 25., 3.))); - assert!(mesh.contains(Vec3::new(25., 25., 22.))); - assert!( - lump.face_sources().is_none_or(|s| s - .iter() - .all(|s| s.is_none() || matches!(s, Some(crate::FaceSource::ExtrudeSide { coalesced: true, plane: None, .. })))), - "genuinely stepped geometry has no durable certificate" - ); - assert!((mesh.measure().volume - (18. * (100. - 4. * std::f64::consts::PI) + 500.)).abs() < 0.02); - } - } - assert_eq!((lower, upper), (1, 1)); - assert_eq!(crate::step_export(&[&tool], "tool").unwrap(), before_tool); - assert_eq!(crate::step_export(&[&roof], "roof").unwrap(), before_roof); - } - fn stepped_tab_stock() -> Body { - let stock = crate::box_solid(Vec3::new(-20., -15., 0.), Vec3::new(20., 15., 24.)).unwrap(); - let tab = crate::box_solid(Vec3::new(-12., -25., 8.), Vec3::new(-4., -15., 16.)).unwrap(); - crate::boolean(&stock, &tab, BoolOp::Union).unwrap().unwrap() - } - - fn coplanar_joins(body: &Body) -> usize { - let faces: Vec<_> = body.solid.face_iter().collect(); - let mut adjacency = std::collections::HashMap::<_, Vec>::new(); - for (i, face) in faces.iter().enumerate() { - for edge in face.edge_iter() { - adjacency.entry(edge.id()).or_default().push(i); - } - } - adjacency - .values() - .filter(|faces| { - let [a, b] = faces.as_slice() else { return false }; - let (Some(pa), Some(pb)) = (body.planar_face(*a), body.planar_face(*b)) else { return false }; - let (na, nb) = (pa.normal(), pb.normal()); - na.dot(nb) > 1. - 1e-12 && (pb.origin - pa.origin).dot(na).abs() < 1e-10 - }) - .count() - } - - #[test] - fn shell_of_joined_stepped_tabs_has_no_artificial_planar_stations() { - let stock = stepped_tab_stock(); - let snapshot = crate::step_export(&[&stock], "unchanged stock").unwrap(); - assert_eq!(coplanar_joins(&stock), 0); - let shell = crate::shell(&stock, &[Vec3::new(0., 0., 24.)], 1.).unwrap(); - assert_eq!(coplanar_joins(&shell), 0, "Shell must not add internal edges across continuous planar walls"); - assert!(shell.validity().is_empty()); - let mesh = shell.tessellate(1e-5).unwrap(); - let expected = 40. * 30. * 24. + 8. * 10. * 8. - (38. * 28. * 23. + 6. * 10. * 6.); - assert!((mesh.measure().volume - expected).abs() < 1e-6); - for (point, material) in [ - (Vec3::new(0., 0., 0.5), true), - (Vec3::new(0., 0., 10.), false), - (Vec3::new(0., -14.5, 10.), true), - (Vec3::new(19.5, 0., 10.), true), - (Vec3::new(-8., -24.5, 12.), true), - (Vec3::new(-8., -20., 12.), false), - (Vec3::new(0., -18., 9.), false), - ] { - assert_eq!(mesh.contains(point), material, "wrong material at {point:?}"); - } - let step = crate::step_export(&[&shell], "stepped tab shell").unwrap(); - let reopened = crate::step_import(&step).unwrap(); - let body = &reopened.bodies[0].body; - assert_eq!(body.face_count(), shell.face_count()); - assert_eq!(coplanar_joins(body), 0); - assert!((body.tessellate(1e-5).unwrap().measure().volume - expected).abs() < 1e-6); - assert_eq!(crate::step_export(&[&stock], "unchanged stock").unwrap(), snapshot); - } - - #[test] - fn contiguous_analytic_walls_remove_faces_but_retain_vertical_stations() { - for curved in [false, true] { - let outer = if curved { - Region2 { outer: Loop2::circle(Vec2::ZERO, 10.), holes: vec![] } - } else { - rectangle(Vec2::new(-10., -10.), Vec2::new(10., 10.)) - }; - let mut upper = outer.clone(); - upper.holes.push(if curved { - Loop2::circle(Vec2::ZERO, 5.).reversed() - } else { - rectangle(Vec2::new(-5., -5.), Vec2::new(5., 5.)).outer.reversed() - }); - let slabs = vec![Section::untagged(&[outer]), Section::untagged(&[upper])]; - // Sections nothing is known of: no history, the construction alone is under test. - let operand = crate::extrude(&Plane::XY, &[rectangle(Vec2::new(-1., -1.), Vec2::new(1., 1.))], 0., 1.).unwrap().pop().unwrap(); - let index = LazyIndex::new(&operand, 0); - let history = lineage::Context::new(BoolOp::Cut, [&operand, &operand], [index.get(), index.get()], Plane::XY, 1e-7, None); - let old = sew_sections(&Plane::XY, Vec3::Z, &[0., 2., 20.], &slabs, 1e-7, false, &history).unwrap().unwrap(); - let merged = sew_sections(&Plane::XY, Vec3::Z, &[0., 2., 20.], &slabs, 1e-7, true, &history).unwrap().unwrap(); - let count = if curved { 2 } else { 4 }; - assert_eq!(old.face_count() - merged.face_count(), count); - let marked: Vec<_> = merged.solid.face_iter().enumerate().filter(|(i, _)| merged.face_was_coalesced(*i)).collect(); - assert_eq!(marked.len(), count); - for (_, face) in marked { - assert_eq!(face.boundaries()[0].len(), 6, "all axial station vertices are retained"); - let heights: Vec<_> = face.vertex_iter().map(|v| v.point().z).collect(); - for z in [0., 2., 20.] { - assert!(heights.contains(&z)); - } - } - assert!(old.face_sources().is_none_or(|s| s.iter().all(Option::is_none))); - let expected = if curved { std::f64::consts::PI * (100. * 20. - 25. * 18.) } else { 400. * 20. - 100. * 18. }; - let mesh = merged.tessellate(1e-5).unwrap(); - assert!((mesh.measure().volume - expected).abs() < 0.03); - assert!(mesh.contains(Vec3::new(0., 0., 1.))); - assert!(!mesh.contains(Vec3::new(0., 0., 10.))); - assert!(merged.validity().is_empty()); - assert_ne!(wall_key(&slabs[0].regions[0].outer.segs[0]), wall_key(&slabs[0].regions[0].outer.segs[0].reversed())); - } - } - - #[test] - fn cut_run_coalescing_respects_authored_splits_and_face_paint() { - let region = Region2 { outer: Loop2::circle(Vec2::ZERO, 10.), holes: vec![] }; - let tool_region = Region2 { outer: Loop2::circle(Vec2::ZERO, 5.), holes: vec![] }; - let stock = crate::extrude(&Plane::XY, &[region], 0., 20.).unwrap().pop().unwrap(); - let cutter = crate::extrude(&Plane::XY, &[tool_region], 2., 22.).unwrap().pop().unwrap(); - let merged = stack_boolean(&stock, &cutter, BoolOp::Cut).unwrap().unwrap().unwrap(); - let protected = [ - stock.clone().with_split_lines(Some(std::sync::Arc::new(vec![vec![Vec3::new(10., 0., 0.), Vec3::new(10., 0., 20.)]]))), - stock.with_paint(Some(crate::Paint { opacity: 1., faces: vec![crate::FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }] })), - ]; - for input in protected { - let output = stack_boolean(&input, &cutter, BoolOp::Cut).unwrap().unwrap().unwrap(); - assert_eq!(output.face_count(), merged.face_count() + 2); - assert!((0..output.face_count()).all(|i| !output.face_was_coalesced(i))); - // Independent circular chord-volume bound: 2*pi*(10*20+5*18)*1e-5 < .019. - let expected = std::f64::consts::PI * (100. * 20. - 25. * 18.); - for body in [&output, &merged] { - let mesh = body.tessellate(1e-5).unwrap(); - assert!((mesh.measure().volume - expected).abs() < 0.03); - assert!(mesh.contains(Vec3::new(0., 0., 1.))); - assert!(!mesh.contains(Vec3::new(0., 0., 10.))); - assert!(mesh.contains(Vec3::new(7., 0., 10.))); - } - } - } - - #[test] - fn annular_inward_tool_recovers_exact_stacks_before_cap_policy() { - let plane = Plane::XY; - let mut region = rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0)); - region.holes.push(Loop2::circle(Vec2::new(20.0, 15.0), 5.0)); - let mut stock = crate::extrude(&plane, std::slice::from_ref(®ion), 0.0, 20.0).unwrap().pop().unwrap(); - for (lo, hi) in [(20.0, 30.0), (30.0, 35.0)] { - let positive = crate::extrude(&plane, std::slice::from_ref(®ion), lo, hi).unwrap().pop().unwrap(); - stock = crate::boolean(&stock, &positive, BoolOp::Union).unwrap().unwrap(); - } - let mut grown = rectangle(Vec2::new(-0.3, -0.3), Vec2::new(40.3, 30.3)); - grown.holes = region.holes; - let tool = crate::extrude(&plane, &[grown], 30.0, 35.6).unwrap().pop().unwrap(); - let tol = stock.size().max(tool.size()) * 1e-6; - let a = stack_of(&stock, Vec3::Z, &plane, tol).expect("annular stock qualifies"); - let b = stack_of(&tool, Vec3::Z, &plane, tol).expect("overrun tool qualifies"); - assert_eq!(a.len(), 1); - assert_eq!(b.len(), 1); - assert!((a[0].lo - 0.0).abs() < tol && (a[0].hi - 35.0).abs() < tol); - assert!((b[0].lo - 30.0).abs() < tol && (b[0].hi - 35.6).abs() < tol); - assert_eq!(a[0].section.regions[0].holes.len(), 1); - assert_eq!(b[0].section.regions[0].holes.len(), 1); - assert!((a[0].section.regions[0].area() - (1200.0 - 25.0 * std::f64::consts::PI)).abs() < 1e-8); - assert!(simple_prism_boolean(&stock, &tool, BoolOp::Cut).is_none()); - let result = stack_boolean(&stock, &tool, BoolOp::Cut).expect("qualified overlapping stacks").unwrap().unwrap(); - assert_eq!(result.shell_count(), 1); - assert!(result.validity().is_empty()); - let mesh = result.tessellate(1e-5).unwrap(); - let expected = (1200.0 - 25.0 * std::f64::consts::PI) * 30.0; - // An inscribed circular mesh at radial chord error 1e-5 has volume - // deficit below 2*pi*R*height*error, conservatively 0.01 mm^3 here. - assert!((mesh.measure().volume - expected).abs() < 0.02); - for (point, present) in [ - (Vec3::new(5.0, 5.0, 29.0), true), - (Vec3::new(5.0, 5.0, 31.0), false), - (Vec3::new(20.0, 15.0, 29.0), false), - (Vec3::new(24.8, 15.0, 29.0), false), - (Vec3::new(25.2, 15.0, 29.0), true), - ] { - assert_eq!(mesh.contains(point), present, "{point:?}"); - } - } - #[test] - fn annular_partial_cut_overruns_and_interior_lumps_preserve_material() { - let area = 1200.0 - 25.0 * std::f64::consts::PI; - for seam in [0.0, 0.37] { - for plane in [Plane::XY, Plane::new(Vec3::new(30.0, 20.0, 10.0), Vec3::X, Vec3::Z).unwrap()] { - let mut region = rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0)); - region.holes.push(Loop2::circle_from(Vec2::new(20.0, 15.0), 5.0, seam)); - let stock = crate::extrude(&plane, std::slice::from_ref(®ion), 0.0, 35.0).unwrap().pop().unwrap(); - let before = crate::step_export(&[&stock], "source").unwrap(); - for (lo, hi, retained, shells) in [(30.0, 35.6, 30.0, 1), (-0.6, 5.0, 30.0, 1), (10.0, 15.0, 30.0, 2), (30.0, 35.0, 30.0, 1)] { - let tool = crate::extrude(&plane, std::slice::from_ref(®ion), lo, hi).unwrap().pop().unwrap(); - let result = stack_boolean(&stock, &tool, BoolOp::Cut).expect("exact aligned cut path").unwrap().unwrap(); - assert_eq!(result.shell_count(), shells); - assert!(result.validity().is_empty()); - let mesh = result.tessellate(1e-5).unwrap(); - assert!((mesh.measure().volume - retained * area).abs() < 0.02); - let at = |x: f64, y: f64, z: f64| plane.to_world(Vec2::new(x, y)) + plane.normal() * z; - for z in [2.5, 12.5, 32.5] { - let material = !(lo < z && z < hi); - assert_eq!(mesh.contains(at(5.0, 5.0, z)), material); - assert!(!mesh.contains(at(20.0, 15.0, z))); - assert_eq!(mesh.contains(at(25.2, 15.0, z)), material); - } - let public = crate::boolean(&stock, &tool, BoolOp::Cut).unwrap().unwrap(); - assert!((public.tessellate(1e-5).unwrap().measure().volume - retained * area).abs() < 0.02); - if lo == 30.0 && hi > 35.0 { - let imported = crate::step_import(&crate::step_export(&[&result], "inward annular cut").unwrap()).unwrap(); - assert!(imported.warnings.is_empty()); - let saved = &imported.bodies.first().unwrap().body; - assert!((saved.tessellate(1e-5).unwrap().measure().volume - 30.0 * area).abs() < 0.02); - let next = crate::extrude(&plane, std::slice::from_ref(®ion), 25.0, 31.0).unwrap().pop().unwrap(); - let shortened = crate::boolean(saved, &next, BoolOp::Cut).unwrap().unwrap(); - let next_volume = shortened.tessellate(1e-5).unwrap().measure().volume; - assert!( - (next_volume - 25.0 * area).abs() < 0.02, - "seam {seam}, plane {plane:?}, next cut volume {next_volume}, expected {}", - 25.0 * area - ); - assert!(shortened.contains(at(5.0, 5.0, 24.0))); - assert!(!shortened.contains(at(5.0, 5.0, 26.0))); - assert!(!shortened.contains(at(20.0, 15.0, 24.0))); - } - } - let clear = crate::extrude(&plane, std::slice::from_ref(®ion), 36.0, 40.0).unwrap().pop().unwrap(); - assert!(stack_boolean(&stock, &clear, BoolOp::Cut).is_none()); - let unchanged = crate::boolean(&stock, &clear, BoolOp::Cut).unwrap().unwrap(); - assert!(std::sync::Arc::ptr_eq(&stock.solid, &unchanged.solid), "disjoint Cut must retain exact source topology"); - let unchanged_mesh = unchanged.tessellate(1e-5).unwrap(); - let source_mesh = stock.tessellate(1e-5).unwrap(); - assert_eq!(unchanged_mesh.measure().volume, source_mesh.measure().volume); - // tessellate() floors tolerance at body.size()*1e-6. The arc - // polygon's area error is at most perimeter*radial chord error. - let bound = std::f64::consts::TAU * 5.0 * 35.0 * (stock.size() * 1e-6).max(1e-5) + 1e-5; - assert!((unchanged_mesh.measure().volume - 35.0 * area).abs() < bound); - assert!(!unchanged_mesh.contains(plane.to_world(Vec2::new(20.0, 15.0)) + plane.normal() * 12.5)); - let all = crate::extrude(&plane, std::slice::from_ref(®ion), -1.0, 36.0).unwrap().pop().unwrap(); - assert!(stack_boolean(&stock, &all, BoolOp::Cut).unwrap().unwrap().is_none()); - assert_eq!(crate::step_export(&[&stock], "source").unwrap(), before); - } - } - } - #[test] - fn annular_partial_cut_preserves_unequal_radii_and_conservative_refusals() { - let mut region = rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0)); - region.holes.push(Loop2::circle(Vec2::new(20.0, 15.0), 5.0)); - let stock = crate::extrude(&Plane::XY, std::slice::from_ref(®ion), 0.0, 35.0).unwrap().pop().unwrap(); - let before = crate::step_export(&[&stock], "unchanged source").unwrap(); - let mut larger_hole = region.clone(); - larger_hole.holes = vec![Loop2::circle(Vec2::new(20.0, 15.0), 5.1)]; - let tool = crate::extrude(&Plane::XY, &[larger_hole], 30.0, 36.0).unwrap().pop().unwrap(); - let result = stack_boolean(&stock, &tool, BoolOp::Cut).unwrap().unwrap().unwrap(); - let expected = (1200.0 - 25.0 * std::f64::consts::PI) * 30.0 + std::f64::consts::PI * (5.1_f64.powi(2) - 25.0) * 5.0; - let mesh = result.tessellate(1e-5).unwrap(); - assert!((mesh.measure().volume - expected).abs() < 0.02); - assert!(mesh.contains(Vec3::new(25.05, 15.0, 32.0))); - assert!(!mesh.contains(Vec3::new(25.2, 15.0, 32.0))); - assert!(!mesh.contains(Vec3::new(20.0, 15.0, 32.0))); - let interior = crate::extrude(&Plane::XY, std::slice::from_ref(®ion), 10.0, 15.0).unwrap().pop().unwrap(); - for d in [Vec3::X, Vec3::Y] { - let plane = Plane::from_normal(Vec3::ZERO, d).unwrap(); - let tol = stock.size() * 1e-6; - assert!(stack_of(&stock, d, &plane, tol).is_none(), "transverse cylinder axis must not fill the hole"); - assert!(stack_of(&interior, d, &plane, tol).is_none()); - } - assert!(stack_boolean(&stock, &interior, BoolOp::Union).is_none(), "Union retains its common-cap policy"); - let tapered = crate::extrude_tapered(&Plane::XY.offset(30.0), &rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0)), 6.0, 1.0, 0.05).unwrap(); - assert!(stack_boolean(&stock, &tapered, BoolOp::Cut).is_none(), "slanted walls are not aligned prisms"); - let curved_cap = crate::sphere(Vec3::new(20.0, 15.0, 35.0), 5.0).unwrap(); - assert!(stack_boolean(&stock, &curved_cap, BoolOp::Cut).is_none()); - let pieces = - (0..350).map(|i| crate::box_solid(Vec3::new(i as f64 * 3.0, 0.0, 0.0), Vec3::new(i as f64 * 3.0 + 1.0, 1.0, 1.0)).unwrap()).collect(); - let over_budget = crate::ops::join_pieces(pieces).unwrap().unwrap(); - assert!(over_budget.face_count() > 2048); - assert!(stack_boolean(&over_budget, &interior, BoolOp::Cut).is_none()); - assert_eq!(crate::step_export(&[&stock], "unchanged source").unwrap(), before); - } - #[test] - fn curved_prism_wall_requires_positive_separable_rational_weights() { - let surface = |mixed: bool| { - let weight = if mixed { 2.0 } else { 1.0 }; - let points = vec![ - vec![mt::Vector4::new(0.0, 0.0, 0.0, 1.0), mt::Vector4::new(0.0, 0.0, 10.0, 1.0)], - vec![mt::Vector4::new(5.0, 0.0, 0.0, 1.0), mt::Vector4::new(5.0 * weight, 0.0, 10.0 * weight, weight)], - ]; - mt::Surface::NurbsSurface(mt::NurbsSurface::new(mt::BSplineSurface::new( - (mt::KnotVec::bezier_knot(1), mt::KnotVec::bezier_knot(1)), - points, - ))) - }; - assert!(wall_along(&surface(false), Vec3::Z, 1e-5, &mut 1000)); - assert!(!wall_along(&surface(true), Vec3::Z, 1e-5, &mut 1000), "parallel Euclidean controls alone do not certify a rational sweep"); - assert!(!wall_along(&surface(false), Vec3::Y, 1e-5, &mut 1000)); - assert!(!wall_along(&surface(false), Vec3::Z, 1e-5, &mut 0)); - } - #[test] - fn partial_depth_cuts_touching_a_through_hole_use_exact_stacked_sections() { - let plane = Plane::named("XY").unwrap(); - let mut plate = rectangle(Vec2::ZERO, Vec2::new(100., 60.)); - plate.holes.push(rectangle(Vec2::new(25., 20.), Vec2::new(30., 30.)).outer); - let stock = crate::extrude(&plane, &[plate], 0., 2.5).unwrap().pop().unwrap(); - let low = crate::extrude(&plane, &[rectangle(Vec2::new(20., 20.), Vec2::new(30., 30.))], 0., 1.5).unwrap().pop().unwrap(); - let high = crate::extrude(&plane, &[rectangle(Vec2::new(25., 20.), Vec2::new(35., 30.))], 1., 2.5).unwrap().pop().unwrap(); - for tools in [[&low, &high], [&high, &low]] { - let mut result = stock.clone(); - for tool in tools { - let target = result; - result = stack_boolean(&target, tool, BoolOp::Cut).expect("exact stack path").unwrap().unwrap(); - // The second cut's target has walls in pieces across its slabs, followed level by - // level: its history is exact. - let exact = crate::boolean_record::tests::Reach { made: 0., moved: 0. }; - crate::boolean_record::tests::checked(&result, &[&target, tool], 1e-3, exact, &|_| false); - } - assert!(result.validity().is_empty()); - assert_eq!(result.shell_count(), 1); - assert!((crate::measure(&result).unwrap().volume - 14_725.).abs() < 1e-6); - let mesh = result.tessellate(1e-4).unwrap(); - for (point, material) in [ - (Vec3::new(22.5, 25., 0.5), false), - (Vec3::new(22.5, 25., 2.), true), - (Vec3::new(32.5, 25., 0.5), true), - (Vec3::new(32.5, 25., 2.), false), - (Vec3::new(27.5, 25., 1.25), false), - (Vec3::new(10., 10., 1.25), true), - ] { - assert_eq!(mesh.contains(point), material, "{point:?}"); - } - let imported = crate::step_import(&crate::step_export(&[&result], "layered cut").unwrap()).unwrap(); - assert!(imported.warnings.is_empty()); - assert!((crate::measure(&imported.bodies.first().unwrap().body).unwrap().volume - 14_725.).abs() < 1e-6); - let next = crate::extrude(&plane, &[rectangle(Vec2::new(20., 20.), Vec2::new(25., 30.))], 1.5, 2.5).unwrap().pop().unwrap(); - let opened = crate::boolean(&imported.bodies.first().unwrap().body, &next, BoolOp::Cut).unwrap().unwrap(); - assert!((crate::measure(&opened).unwrap().volume - 14_675.).abs() < 1e-6); - assert!(opened.validity().is_empty()); - } - } - #[test] - fn far_edges_of_a_stepped_slab_come_from_the_operand_topology() { - // A block with a notch in its back, read along -y: the slab from the notch floor to the - // front has three segments beside the top face, read off the back and the notch floor. - // The top face ends at the front in one edge: the far edge of all three, found with no - // position compared (no pair budget). - let notched = Loop2::polygon(&[ - Vec2::new(0., 0.), - Vec2::new(40., 0.), - Vec2::new(40., 30.), - Vec2::new(25., 30.), - Vec2::new(25., 25.), - Vec2::new(15., 25.), - Vec2::new(15., 30.), - Vec2::new(0., 30.), - ]); - let block = crate::extrude(&Plane::named("XY").unwrap(), &[Region2 { outer: notched, holes: vec![] }], 0., 20.).unwrap().pop().unwrap(); - let (d, tol) = (-Vec3::Y, 1e-6); - let plane = Plane::from_normal(Vec3::ZERO, d).unwrap(); - let normal = |f: &mt::Face| crate::blend::plane_normal(f).unwrap_or(Vec3::ZERO); - let faces: Vec<(usize, &mt::Face)> = block.solid.face_iter().enumerate().collect(); - let find = |n: Vec3| faces.iter().find(|(_, f)| normal(f).dot(n) > 1. - 1e-9).map(|(i, _)| *i).unwrap(); - let (top, front) = (find(Vec3::Z), find(-Vec3::Y)); - let walls = faces.iter().filter(|(_, f)| normal(f).dot(d).abs() < 1e-9).map(|(i, f)| (*i, top_of(f, &plane))).collect(); - let index = Index::new(&block, 0); - let stations = Stations::new(&index, walls, d, &plane, tol); - let cap = Section::from_loops(index.loops(faces[front].1, front, &plane, tol, &mut 1000, &mut 1000).unwrap()).unwrap().oriented(); - let edge = match index.between.get(&(top.min(front), top.max(front))).map(Vec::as_slice) { - Some([e]) => *e, - other => panic!("one edge between the top and the front: {other:?}"), - }; - let mut slab = stack_of(&block, d, &plane, tol).unwrap().pop().unwrap(); - assert!((slab.lo + 25.).abs() < tol && slab.hi.abs() < tol); - let beside_top = |s: &Section| s.segments().1.into_iter().filter(|t| t.wall == Some(top)).map(|t| t.far).collect::>(); - assert_eq!(beside_top(&slab.section), vec![Some(edge); 3], "read as a stack"); - slab.section.retag(|t| Tag { far: None, ..t }); - slab.section.mark_far(&[&cap], |w| stations.top_edge(&index, w, &[front], 0., tol), tol, &mut 0); - assert_eq!(beside_top(&slab.section), vec![Some(edge); 3], "by topology alone"); - } - #[test] fn compound_planar_extrusion_normalizes_overlap_and_retains_islands() { let plane = Plane::named("XY").unwrap(); let a = rectangle(Vec2::ZERO, Vec2::new(10.0, 10.0)); @@ -3154,14 +392,13 @@ mod planar_tests { let body = extrude_planar_regions(&plane, &[annulus, inner], 0.0, 2.0).unwrap(); let expected = (100.0 - std::f64::consts::PI * 5.0) * 2.0; assert!((crate::measure(&body).unwrap().volume - expected).abs() < 0.1); - assert_eq!(body.solid.boundaries().len(), 2); + assert_eq!(body.shell_count(), 2); let a = rectangle(Vec2::ZERO, Vec2::new(10.0, 10.0)); let b = rectangle(Vec2::new(10.0, 10.0), Vec2::new(20.0, 20.0)); assert!(extrude_planar_regions(&plane, &[a, b], 0.0, 2.0).is_err()); let circles = [Vec2::ZERO, Vec2::new(10.0, 0.0)].map(|center| Region2 { outer: Loop2::circle(center, 5.0), holes: vec![] }); assert!(extrude_planar_regions(&plane, &circles, 0.0, 2.0).is_err()); } - /// An ellipse about `c` with semi-axes `a` (along x) and `b`, as four exact conics. fn ellipse(c: Vec2, a: f64, b: f64) -> Loop2 { let corners = [c + Vec2::new(a, 0.0), c + Vec2::new(0.0, b), c - Vec2::new(a, 0.0), c - Vec2::new(0.0, b)]; @@ -3170,9 +407,8 @@ mod planar_tests { segs: (0..4).map(|i| Seg2::Conic { a: corners[i], apex: corners[i] + corners[(i + 1) % 4] - c, b: corners[(i + 1) % 4], w }).collect(), } } - #[test] - fn free_form_cut_outs_stay_exact_when_whole_and_follow_arcs_when_cut() { + fn free_form_cut_outs_stay_exact_whole_or_cut() { let plate = rectangle(Vec2::ZERO, Vec2::new(100.0, 60.0)); let hole = Region2 { outer: ellipse(Vec2::new(40.0, 30.0), 15.0, 8.0), holes: vec![] }; let out = planar_regions_boolean(std::slice::from_ref(&plate), std::slice::from_ref(&hole), BoolOp::Cut, 1e-7).unwrap(); @@ -3190,17 +426,18 @@ mod planar_tests { let taken = planar_regions_boolean(std::slice::from_ref(&plate), std::slice::from_ref(&hole), BoolOp::Intersect, 1e-7).unwrap(); assert!(taken.len() == 1 && taken[0].outer.segs.iter().all(|s| hole.outer.segs.contains(s)), "{taken:?}"); // An ellipse centred on the plate's edge makes a notch of half the ellipse: its part - // inside follows arcs within the fit tolerance (times half the perimeter, 37 mm). + // inside is the ellipse's own conics, cut where they cross the edge, so the notch takes + // exactly half the ellipse. let over = Region2 { outer: ellipse(Vec2::new(100.0, 30.0), 15.0, 8.0), holes: vec![] }; let out = planar_regions_boolean(std::slice::from_ref(&plate), std::slice::from_ref(&over), BoolOp::Cut, 1e-7).unwrap(); assert_eq!(out.len(), 1); - assert!(out[0].holes.is_empty() && out[0].outer.is_line_arc()); + assert!(out[0].holes.is_empty() && !out[0].outer.is_line_arc()); let notched = 6000.0 - std::f64::consts::PI * 15.0 * 8.0 / 2.0; - assert!((out[0].area() - notched).abs() < PLANAR_FIT_TOL * 37.0, "{} vs {notched}", out[0].area()); - // Two ellipses that overlap join into one outline of arcs; apart, both stay exact. + assert!((out[0].area() - notched).abs() < 1e-6, "{} vs {notched}", out[0].area()); + // Two ellipses that overlap join into one outline of their conics; apart, both stay whole. let beside = |dx: f64| Region2 { outer: ellipse(Vec2::new(40.0 + dx, 30.0), 15.0, 8.0), holes: vec![] }; let joined = planar_regions_boolean(std::slice::from_ref(&hole), &[beside(20.0)], BoolOp::Union, 1e-7).unwrap(); - assert!(joined.len() == 1 && joined[0].outer.is_line_arc(), "{joined:?}"); + assert!(joined.len() == 1 && joined[0].outer.segs.iter().all(|s| !s.is_line_or_arc()), "{joined:?}"); let apart = planar_regions_boolean(std::slice::from_ref(&hole), &[beside(40.0)], BoolOp::Union, 1e-7).unwrap(); assert!(apart.len() == 2 && apart.iter().all(|r| r.outer.segs.len() == 4 && !r.outer.is_line_arc()), "{apart:?}"); // The flat material extrudes with the exact elliptic wall: four conic faces, two caps. @@ -3209,41 +446,14 @@ mod planar_tests { let v = crate::measure(&body).unwrap().volume; assert!((v - exact * 2.0).abs() < 1e-3 * exact, "{v}"); } - #[test] - fn free_form_loops_that_cannot_be_followed_are_refused() { + fn free_form_loops_that_are_not_finite_are_refused() { let plate = rectangle(Vec2::ZERO, Vec2::new(100.0, 60.0)); let mut bad = ellipse(Vec2::new(40.0, 30.0), 15.0, 8.0); bad.segs[1] = Seg2::Conic { a: bad.segs[1].start(), apex: Vec2::new(f64::NAN, 0.0), b: bad.segs[1].end(), w: 1.0 }; let e = planar_regions_boolean(std::slice::from_ref(&plate), &[Region2 { outer: bad, holes: vec![] }], BoolOp::Cut, 1e-7).unwrap_err(); assert!(e.to_string().contains("free-form"), "{e}"); - // More fitted arcs than the arrangement's segment budget. - let many: Vec = (0..400).map(|i| Region2 { outer: ellipse(Vec2::new(40.0 * i as f64, 0.0), 15.0, 8.0), holes: vec![] }).collect(); - assert!(planar_regions_boolean(&[plate], &many, BoolOp::Cut, 1e-7).is_err()); } - - #[test] - fn segment_boxes_hold_what_lies_within_the_tolerance() { - // An arc of radius 10 about the origin from 45° to 135° passes the top of its circle: - // x within ±10/√2, y from 10/√2 to 10, grown by twice the tolerance. - let r = 10.0 * std::f64::consts::FRAC_1_SQRT_2; - let arc = Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: std::f64::consts::FRAC_PI_4, sweep: std::f64::consts::FRAC_PI_2 }; - for s in [arc, arc.reversed()] { - let Aabb2 { min: lo, max: hi } = seg_box(&s, 1e-3).unwrap(); - assert!(lo.dist(Vec2::new(-r - 2e-3, r - 2e-3)) < 1e-9 && hi.dist(Vec2::new(r + 2e-3, 10.0 + 2e-3)) < 1e-9, "{lo:?} {hi:?}"); - } - let Aabb2 { min: lo, max: hi } = seg_box(&Seg2::Line { a: Vec2::new(3.0, -1.0), b: Vec2::new(-2.0, 4.0) }, 0.5).unwrap(); - assert!(lo.dist(Vec2::new(-3.0, -2.0)) < 1e-9 && hi.dist(Vec2::new(4.0, 5.0)) < 1e-9, "{lo:?} {hi:?}"); - // A line 3 tolerances above the arc's top meets its box (each is grown by two); one - // 5 tolerances above does not. No box (a free-form segment, a value that is not - // finite) hides nothing. - let level = |y: f64| seg_box(&Seg2::Line { a: Vec2::new(-1.0, y), b: Vec2::new(1.0, y) }, 1e-3); - assert!(boxes_meet(seg_box(&arc, 1e-3), level(10.003)) && !boxes_meet(seg_box(&arc, 1e-3), level(10.005))); - let free = ellipse(Vec2::ZERO, 2.0, 1.0).segs[0]; - assert!(seg_box(&free, 1e-3).is_none() && seg_box(&Seg2::Line { a: Vec2::new(f64::NAN, 0.0), b: Vec2::X }, 1e-3).is_none()); - assert!(boxes_meet(None, level(500.0)) && box_holds(None, Vec2::new(500.0, 500.0))); - } - #[test] fn many_small_cut_outs_far_apart_cut_as_before() { // 400 round holes in a strip: almost every pair of segments is far apart. @@ -3256,54 +466,6 @@ mod planar_tests { let exact = 40_000.0 - 400.0 * std::f64::consts::PI * 1.8 * 1.8; assert!((out[0].area() - exact).abs() < 1e-6, "{}", out[0].area()); } - - #[test] - fn analytic_circle_classification_respects_signed_sweeps_and_seams() { - for seam in [0.0, 0.13, std::f64::consts::FRAC_PI_2, -std::f64::consts::FRAC_PI_2] { - for reversed in [false, true] { - let lp = Loop2::circle_from(Vec2::ZERO, 10.0, seam); - let lp = if reversed { lp.reversed() } else { lp }; - for p in [Vec2::ZERO, Vec2::new(9.9998, 0.0), Vec2::new(0.0, 9.9998), Vec2::new(0.0, -9.9998)] { - assert!(inside_loop(&lp, p), "{seam} {reversed} {p:?}"); - } - for p in [Vec2::new(11.0, 0.0), Vec2::new(0.0, 10.0), Vec2::new(0.0, -10.0)] { - assert!(!inside_loop(&lp, p), "{seam} {reversed} {p:?}"); - } - } - } - let half = Loop2 { - segs: vec![ - Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: -std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI }, - Seg2::Line { a: Vec2::new(0.0, 10.0), b: Vec2::new(0.0, -10.0) }, - ], - }; - for lp in [half.clone(), half.reversed()] { - assert!(inside_loop(&lp, Vec2::new(5.0, 0.0))); - assert!(!inside_loop(&lp, Vec2::new(-5.0, 0.0))); - assert!(!inside_loop(&lp, Vec2::new(-5.0, -10.0))); - } - // #307: a circle read back as two halves whose centres disagree by a few ulps, split - // at its bottom. A ray grazing that bottom must not count one half's touch only. - let halves = Loop2 { - segs: vec![ - Seg2::Arc { center: Vec2::new(0.0, 25.0), radius: 5.0, start: -std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI }, - Seg2::Arc { - center: Vec2::new(2.9e-15, 25.000000000000004), - radius: 4.99999999999999, - start: std::f64::consts::FRAC_PI_2, - sweep: std::f64::consts::PI, - }, - ], - }; - for lp in [halves.clone(), halves.reversed()] { - for x in [-30.0, -5.0, -0.1] { - assert!(!inside_loop(&lp, Vec2::new(x, 20.0)), "{x}"); - assert!(!inside_loop(&lp, Vec2::new(x, 30.0)), "{x}"); - } - assert!(inside_loop(&lp, Vec2::new(0.0, 25.0))); - } - } - /// Loops are closed only within the chaining tolerance. A ray level with one end of such a /// gap slipped through it without a crossing, so a point beside the loop counted as inside: /// a sheet shrunk by a parameter change (sketch solver residuals of 1e-13 mm) lost a bend @@ -3320,11 +482,6 @@ mod planar_tests { Seg2::Line { a: Vec2::new(0.0, 5.0), b: Vec2::new(0.0, 0.0) }, ], }; - for lp in [square.clone(), square.reversed()] { - assert!(!inside_loop(&lp, Vec2::new(-5.0, 5.0))); - assert!(inside_loop(&lp, Vec2::new(5.0, 5.0))); - assert!(!inside_loop(&lp, Vec2::new(15.0, 5.0))); - } // A neighbour with an edge level with the gap joins the square instead of being // dropped as if it lay inside it (which left the outline open: no result at all). let a = Region2 { outer: square, holes: vec![] }; @@ -3336,8 +493,8 @@ mod planar_tests { /// Two edges lying on one another within the tolerance, a hair from parallel, meet at a /// point somewhere along their overlap. Taken for a crossing, that point split the square's /// edge once more: 5e-8 mm before its end, which left an edge shorter than the tolerance in - /// the result, or in the middle of a straight edge. The ends of an overlap are what split - /// the edges. + /// the result, or in the middle of a straight edge. Edges on one line within the tolerance + /// are one edge of the result: where they meet is no corner. #[test] fn overlapping_lines_a_hair_from_parallel_do_not_cross() { let square = rectangle(Vec2::ZERO, Vec2::new(10.0, 10.0)); @@ -3358,32 +515,25 @@ mod planar_tests { }; let same = |got: &[f64], want: &[f64]| got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6); for meet in [10.0 - 5e-8, 7.0] { - // Below the square, against its bottom edge: cut away, it leaves the square, the - // bottom edge split only at x = 4, where the quadrilateral's corner lies on it. + // Below the square, against its bottom edge: cut away, it leaves the square, its four + // edges whole (the quadrilateral's corner at x = 4 lies within 1e-8 of the bottom + // edge, on its line, and its edge from there is no more than 1e-8 off it). let below = quad(meet, -5.0); let cut = planar_regions_boolean(std::slice::from_ref(&square), std::slice::from_ref(&below), BoolOp::Cut, 1e-7).unwrap(); assert_eq!(cut.len(), 1, "{meet}"); - assert!(same(&lengths(&cut[0]), &[4.0, 6.0, 10.0, 10.0, 10.0]), "{meet}: cut edges {:?}", lengths(&cut[0])); + assert!(same(&lengths(&cut[0]), &[10.0, 10.0, 10.0, 10.0]), "{meet}: cut edges {:?}", lengths(&cut[0])); assert!((cut[0].area() - 100.0).abs() < 1e-6, "{meet}: {}", cut[0].area()); // Over the square, flush with that edge and reaching past it to x = 14: the - // union's outline runs along y = 0 once, in the pieces 0..4, 4..10 and 10..14. + // union's outline runs along y = 0 once, one edge from 0 to 14 (the quadrilateral's + // bottom edge lies within 1e-8 of the line y = 0 all along). let flush = quad(meet, 5.0); let union = planar_regions_boolean(std::slice::from_ref(&square), std::slice::from_ref(&flush), BoolOp::Union, 1e-7) .unwrap_or_else(|e| panic!("{meet}: union {e}")); assert_eq!(union.len(), 1, "{meet}"); - assert!(same(&lengths(&union[0]), &[4.0, 4.0, 4.0, 5.0, 5.0, 6.0, 10.0, 10.0]), "{meet}: union edges {:?}", lengths(&union[0])); + assert!(same(&lengths(&union[0]), &[4.0, 5.0, 5.0, 10.0, 10.0, 14.0]), "{meet}: union edges {:?}", lengths(&union[0])); assert!((union[0].area() - 120.0).abs() < 1e-6, "{meet}: {}", union[0].area()); - // The two edges themselves, either way round. - let (edge, tilted) = (square.outer.segs[0], flush.outer.segs[0]); - assert!(crossings(&edge, &tilted, 1e-7).is_empty() && crossings(&tilted, &edge, 1e-7).is_empty(), "{meet}"); } - // Lines further apart than the tolerance at their ends still cross: tilted by 1e-3 rad - // about (7, 0), the edge from (4, 3e-3) to (14, -7e-3) meets the bottom edge at x = 7. - let (edge, steep) = (square.outer.segs[0], Seg2::Line { a: Vec2::new(4.0, 3e-3), b: Vec2::new(14.0, -7e-3) }); - let hits = crossings(&edge, &steep, 1e-7); - assert!(hits.len() == 1 && (hits[0].0 - 0.7).abs() < 1e-12 && (hits[0].1 - 0.3).abs() < 1e-12, "{hits:?}"); } - #[test] fn tiny_tool_between_circle_and_display_chord_is_not_lost() { let circle = Region2 { outer: Loop2::circle(Vec2::ZERO, 10.0), holes: vec![] }; @@ -3416,7 +566,6 @@ mod planar_tests { Region2 { outer: Loop2 { segs: vec![arc, Seg2::Line { a: arc.end(), b: out }, Seg2::Line { a: out, b: arc.start() }] }, holes: vec![] }; (plate, cut) } - /// A contact between a line and an arc that touch is one point. The quadratic's two roots /// there are rounding noise: a 1e-12 mm error in the centre's distance from the line moves /// them 2e-6 mm either way along it, and the cut then ran that far along the plate's edge @@ -3449,7 +598,6 @@ mod planar_tests { } } } - /// A 55 x 30 plate whose bottom edge bends up by `slope` over its last 5 mm before the /// corner at (100, 50), and a strip 3 wide below the straight 50 mm, as a sheet's bend zone /// lies against its base: the strip's corners on that edge rounded to the nanometre, as a @@ -3462,14 +610,14 @@ mod planar_tests { let strip = [nm(rot(100.0, 50.0)), rot(100.0, 47.0), rot(150.0, 47.0), nm(rot(150.0, 50.0))]; (Region2 { outer: Loop2::polygon(&plate), holes: vec![] }, Region2 { outer: Loop2::polygon(&strip), holes: vec![] }) } - /// The bent piece of the plate's edge, a hair from the strip's edge, crosses it short of /// the corner they share: the corners a nanometre apart at most, the crossing up to a /// hundred times that before it at a slope of 1 in 100, a thousand at 1 in 1000. A split /// there left a sliver of edge shorter than the distance within which the loops join their /// pieces; the chaining took it for a second way out of the corner, and a loop of that one /// sliver is open, its area not zero away from the origin: a hole no outline held (no - /// result at all) or a region of its own. The union is the plate and the strip, whole. + /// result at all) or a region of its own. The union is the plate and the strip, whole: six + /// edges, the strip's end and the plate's on the line x = 150 one edge from y = 47 to 80. #[test] fn a_bent_edge_crossing_its_neighbour_by_their_corner_leaves_no_sliver() { let union_is_whole = |(plate, strip): (Region2, Region2), what: &str| { @@ -3480,7 +628,7 @@ mod planar_tests { assert_eq!(out.len(), 1, "{what}: {out:?}"); let lp = &out[0].outer; let shortest = lp.segs.iter().map(Seg2::length).fold(f64::MAX, f64::min); - assert!(out[0].holes.is_empty() && lp.segs.len() == 7 && shortest > 2.9, "{what}: {} edges, shortest {shortest:e}", lp.segs.len()); + assert!(out[0].holes.is_empty() && lp.segs.len() == 6 && shortest > 2.9, "{what}: {} edges, shortest {shortest:e}", lp.segs.len()); assert!((out[0].area() - want).abs() < 1e-6, "{what}: {} vs {want}", out[0].area()); } }; @@ -3499,37 +647,6 @@ mod planar_tests { } } } - - /// Touching circles meet at one point on the line of their centres, inside and outside. - #[test] - fn touching_lines_and_arcs_meet_at_one_point() { - let full = |c: Vec2, r: f64| Seg2::Arc { center: c, radius: r, start: 0.3, sweep: std::f64::consts::TAU - 1e-3 }; - for k in 0..=360 { - let dir = Vec2::from_angle((k as f64 * 0.25).to_radians()); - let c = Vec2::new(151.3, -37.7); - for (r0, r1, d) in [(2.0, 3.0, 5.0), (7.0, 3.0, 4.0), (3.0, 7.0, 4.0), (250.0, 2.0, 248.0)] { - let hits = crossings(&full(c, r0), &full(c + dir * d, r1), 1e-7); - let touch = c + dir * if r1 > r0 && d < r1 { -r0 } else { r0 }; - let pts: Vec = hits.iter().map(|(u, _)| full(c, r0).point_at(*u)).collect(); - assert!(!pts.is_empty() && pts.iter().all(|p| p.dist(touch) < 1e-9), "{k} {r0} {r1}: {pts:?} vs {touch:?}"); - } - // A line touching a circle, the circle's side of it and the far side by rounding. - for r in [2.0, 250.0] { - let foot = c + dir * r; - let line = Seg2::Line { a: foot - dir.perp() * 120.0, b: foot + dir.perp() * 78.0 }; - let hits = crossings(&line, &full(c, r), 1e-7); - let pts: Vec = hits.iter().map(|(u, _)| line.point_at(*u)).collect(); - assert!(!pts.is_empty() && pts.iter().all(|p| p.dist(foot) < 1e-9), "{k} {r}: {pts:?} vs {foot:?}"); - } - } - // Real crossings stay two points: a chord 0.01 mm deep in a 2 mm circle. - let line = Seg2::Line { a: Vec2::new(-5.0, 1.99), b: Vec2::new(5.0, 1.99) }; - let hits = crossings(&line, &full(Vec2::ZERO, 2.0), 1e-7); - let half = (4.0f64 - 1.99 * 1.99).sqrt(); - assert_eq!(hits.len(), 2); - assert!(hits.iter().all(|(u, _)| (line.point_at(*u).x.abs() - half).abs() < 1e-12), "{hits:?}"); - } - #[test] fn planar_region_api_rejects_hostile_values_and_budgets() { let plate = rectangle(Vec2::ZERO, Vec2::new(10.0, 10.0)); diff --git a/crates/kernel/src/prism_curve.rs b/crates/kernel/src/prism_curve.rs index 7a14a9bb2..e6b11f700 100644 --- a/crates/kernel/src/prism_curve.rs +++ b/crates/kernel/src/prism_curve.rs @@ -1,8 +1,12 @@ -//! Whole-span certificates for analytic planar prism boundaries. -//! Samples propose a circle; only positive rational Bernstein bounds accept it. -use crate::body::from_p3; -use solidcraft_geom::{Plane, Seg2, Vec2}; -use truck_modeling::{self as mt, BoundedCurve, Invertible, ParametricCurve}; +//! Whole-span certificates for analytic planar prism boundaries, read off the curves of schema 4 +//! record edges. A record's lines and circles are read as they are; a spline is read span by +//! span (its Bézier pieces): samples propose a circle, and only positive rational Bernstein +//! bounds accept it. +use solidcore_record::brep::{Brep, Curve}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::bspline::{self, HPoint}; +use solidcraft_geom::prelude::*; const MAX_DEGREE: usize = 32; /// How far an arc read off a curve may end from the curve's end (mm): half the gap a profile @@ -11,38 +15,126 @@ const ARC_END_TOL: f64 = 5e-7; const MAX_CONTROLS: usize = 4096; type H = [f64; 3]; +/// A curve over `interval` (in its own parameter), run from `ends[0]` to `ends[1]`: from the +/// interval's min to its max when `forward`, the other way otherwise. The ends are the points +/// the curve must reach there (a record edge's vertices). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Run<'a> { + pub curve: &'a Curve, + pub interval: [f64; 2], + pub forward: bool, + pub ends: [Vec3; 2], +} + +impl<'a> Run<'a> { + /// Edge `edge` of `record`, run `forward` (from its start vertex to its end) or back. + pub(crate) fn of(record: &'a Brep, edge: usize, forward: bool) -> Option> { + let e = record.edges.get(edge)?; + let at = |v: u32| record.vertices.get(v as usize).map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])); + let (start, end) = (at(e.vertices[0])?, at(e.vertices[1])?); + Some(Run { curve: e.parameters(), interval: e.interval, forward, ends: if forward { [start, end] } else { [end, start] } }) + } + + /// The parameters it runs from and to. + fn ends_along(&self) -> (f64, f64) { + let [t0, t1] = self.interval; + if self.forward { (t0, t1) } else { (t1, t0) } + } +} + fn charge(work: &mut usize, n: usize) -> Option<()> { *work = work.checked_sub(n)?; Some(()) } -fn preflight(c: &mt::Curve, work: &mut usize) -> Option<()> { - charge(work, 1)?; - let (knots, controls) = match c { - mt::Curve::Line(_) => return Some(()), - mt::Curve::BSplineCurve(b) => (b.knot_vec(), b.control_points().len()), - mt::Curve::NurbsCurve(b) => (b.knot_vec(), b.control_points().len()), - _ => return None, - }; - let degree = knots.len().checked_sub(controls + 1)?; - if !(1..=MAX_DEGREE).contains(°ree) || controls > MAX_CONTROLS || knots.len() > 8192 { - return None; - } - if knots.iter().any(|t| !t.is_finite()) || knots.windows(2).any(|w| w[1] < w[0]) { - return None; - } - // Charge decomposition before its cloning / knot insertion allocations. - charge(work, controls.checked_mul(knots.len())?.checked_mul(degree + 1)?) +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) } -fn controls(c: &mt::Curve, plane: &Plane, h: f64, tol: f64) -> Option<(Vec>, f64)> { - let spans: Vec> = match c { - mt::Curve::BSplineCurve(b) => { - b.bezier_decomposition().into_iter().map(|s| s.control_points().iter().map(|p| mt::Vector4::new(p.x, p.y, p.z, 1.)).collect()).collect() +/// The Bézier spans of a B-spline (homogeneous control points `ctrl` on `knots`) over `[t0, t1]`, +/// in parameter order: the piece clamped to the interval (Boehm insertion of its ends), then every +/// interior knot inserted until it repeats `degree` times; the span between two knots is the +/// `degree + 1` control points ending at the last of the knots below it. Exact up to rounding. +fn spline_spans(knots: &[f64], ctrl: &[HPoint], t0: f64, t1: f64, work: &mut usize) -> Option>> { + let degree = knots.len().checked_sub(ctrl.len() + 1)?; + if !(1..=MAX_DEGREE).contains(°ree) || ctrl.len() > MAX_CONTROLS || knots.len() > 8192 { + return None; + } + if knots.iter().any(|t| !t.is_finite()) || knots.windows(2).any(|w| w[1] < w[0]) || ctrl.iter().any(|p| !p.is_finite()) { + return None; + } + // Charge decomposition before its knot insertion allocations. + charge(work, ctrl.len().checked_mul(knots.len())?.checked_mul(degree + 1)?)?; + let (mut k, mut c) = bspline::segment(degree, knots, ctrl, t0, t1).ok()?; + let mut interior: Vec = k.iter().copied().filter(|t| *t > t0 && *t < t1).collect(); + interior.dedup(); + for u in interior { + while k.iter().filter(|t| **t == u).count() < degree { + (k, c) = bspline::insert_knot(degree, &k, &c, u).ok()?; + } + } + let n = c.len(); + let mut spans = Vec::new(); + for i in degree..n { + let (Some(a), Some(b)) = (k.get(i), k.get(i + 1)) else { return None }; + if a < b { + spans.push(c.get(i - degree..=i)?.to_vec()); + } + } + Some(spans) +} + +/// An ellipse (`o + rx cos t x + ry sin t y`) from `t0` to `t1` (either way round) as rational +/// quadratic Bézier spans of at most a quarter turn each: each the conic through the span's ends +/// whose tangents meet at the apex, with the middle weight the cosine of half its angle. Exact: +/// an affine image of the circle's rational quadratic arcs. +fn ellipse_spans(o: Vec3, x: Vec3, y: Vec3, radii: [f64; 2], t0: f64, t1: f64, work: &mut usize) -> Option>> { + let span = t1 - t0; + if !span.is_finite() || span.abs() > std::f64::consts::TAU * 2.0 { + return None; + } + let n = (span.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize; + charge(work, n.checked_mul(3)?)?; + let at = |t: f64, scale: f64| o + (x * (radii[0] * t.cos()) + y * (radii[1] * t.sin())) * scale; + let h = span / n as f64 / 2.0; + let w = h.cos(); + Some( + (0..n) + .map(|i| { + let a = t0 + span * i as f64 / n as f64; + let m = a + h; + vec![HPoint::weighted(at(a, 1.0), 1.0), HPoint::weighted(at(m, 1.0 / w), w), HPoint::weighted(at(a + 2.0 * h, 1.0), 1.0)] + }) + .collect(), + ) +} + +/// `run`'s curve as homogeneous Bézier spans in the direction it runs; `None` for a curve that +/// isn't a spline or an ellipse. +fn spans_of(run: &Run, work: &mut usize) -> Option>> { + let [t0, t1] = run.interval; + let spans = match run.curve { + Curve::Spline { knots, points } => { + let ctrl: Vec = points.iter().map(|p| HPoint::weighted(v3(*p), 1.0)).collect(); + spline_spans(knots, &ctrl, t0, t1, work)? + } + Curve::RationalSpline { knots, homogeneous } => { + let ctrl: Vec = homogeneous.iter().map(|p| HPoint { x: p[0], y: p[1], z: p[2], w: p[3] }).collect(); + spline_spans(knots, &ctrl, t0, t1, work)? + } + Curve::Ellipse { frame, radii } => { + let (x, y) = (v3(frame.x_axis), v3(frame.y_axis)); + let (a, b) = run.ends_along(); + return ellipse_spans(v3(frame.origin), x, y, *radii, a, b, work); } - mt::Curve::NurbsCurve(b) => b.non_rationalized().bezier_decomposition().into_iter().map(|s| s.control_points().clone()).collect(), _ => return None, }; + Some(if run.forward { spans } else { spans.into_iter().rev().map(|s| s.into_iter().rev().collect()).collect() }) +} + +/// The spans in `plane`: `[x·w, y·w, w]` per control point (weights scaled to at most 1), and the +/// rounding error of reading them; `None` where a control point lies off the level `h`. +fn controls(spans: Vec>, plane: &Plane, h: f64, tol: f64) -> Option<(Vec>, f64)> { if spans.is_empty() || spans.len() > 256 || spans.iter().map(Vec::len).sum::() > 8192 { return None; } @@ -58,10 +150,10 @@ fn controls(c: &mt::Curve, plane: &Plane, h: f64, tol: f64) -> Option<(Vec Option> { - if let Some(exact) = segment(e, plane, tol, work) { - return Some(exact); +/// `run` in `plane` exactly, as lines, circular arcs and free-form segments (each free-form +/// curve one segment): `None` when it doesn't lie in a plane parallel to `plane`, isn't read +/// exactly, isn't finite or goes over the work budget. +pub(crate) fn segment(run: &Run, plane: &Plane, tol: f64, work: &mut usize) -> Option> { + read(run, plane, tol, work, false) +} + +/// `run` in `plane` exactly as segments: as [`segment`], and a curve of several Bézier spans +/// (a chain of a font's curves, a spline through points) as one segment per span, each the +/// line, conic or Bézier it is, for a planar region's outline. `None` when the edge doesn't lie +/// in a plane parallel to `plane` or isn't read exactly. +pub(crate) fn projected(run: &Run, plane: &Plane, tol: f64, work: &mut usize) -> Option> { + read(run, plane, tol, work, true) +} + +/// A free-form curve of several Bézier spans in a plane, as the one B-spline it is: its degree, +/// clamped knots, control points in the plane's coordinates and weights (none: a polynomial +/// B-spline). Its first and last control points are its ends. +#[derive(Clone, Debug, PartialEq)] +pub struct PlanarSpline { + pub degree: usize, + pub knots: Vec, + pub points: Vec, + pub weights: Vec, +} + +/// One piece of an edge read exactly in a plane: a line, arc or single free-form segment, or a +/// free-form curve of several spans as one [`PlanarSpline`]. +#[derive(Clone, Debug, PartialEq)] +pub enum PlanarPiece { + Seg(Seg2), + Spline(PlanarSpline), +} + +/// `run` in `plane` exactly, for a sketch to project it: as [`segment`], and a curve of several +/// Bézier spans (a spline edge, an elliptical arc past a quarter turn, a chain of a font's +/// curves) as the one B-spline it is, its knots and weights its own. `None` when the edge +/// doesn't lie in a plane parallel to `plane` or isn't read exactly. +pub(crate) fn projected_curves(run: &Run, plane: &Plane, tol: f64, work: &mut usize) -> Option> { + if let Some(segs) = read(run, plane, tol, work, false) { + return Some(segs.into_iter().map(PlanarPiece::Seg).collect()); } - if !tol.is_finite() || tol <= 0. || !fit.is_finite() || fit <= 0. { + one_spline(run, plane, tol, work).map(|s| vec![PlanarPiece::Spline(s)]) +} + +/// `run`'s spline (or ellipse) over its interval, in the direction it runs, as one clamped +/// B-spline in `plane`: the piece of the curve between the interval's ends (Boehm insertion, +/// exact up to rounding), its control points read in the plane. `None` when a control point lies +/// off the level of the curve's start (the curve is not in a plane parallel to `plane`), the +/// ends miss the run's ends, or the work budget runs out. +fn one_spline(run: &Run, plane: &Plane, tol: f64, work: &mut usize) -> Option { + if !tol.is_finite() || tol <= 0. || run.interval[1] <= run.interval[0] { return None; } - let mut c = e.curve(); - preflight(&c, work)?; - if !e.orientation() { - c.invert(); - } - let (t0, t1) = c.range_tuple(); - if !(t0.is_finite() && t1.is_finite() && t1 > t0) { - return None; - } - let (a3, b3) = (from_p3(c.subs(t0)), from_p3(c.subs(t1))); - if !a3.is_finite() || !b3.is_finite() || a3.dist(from_p3(e.front().point())) > tol || b3.dist(from_p3(e.back().point())) > tol { - return None; - } - let (spans, _) = controls(&c, plane, plane.height(a3), tol)?; - let mut out = Vec::new(); - for span in spans { - if span.iter().any(|p| (p[2] - 1.).abs() > 1e-9) { + charge(work, 1)?; + let [t0, t1] = run.interval; + let clamped = |knots: &[f64], ctrl: Vec, work: &mut usize| -> Option<(usize, Vec, Vec)> { + let degree = knots.len().checked_sub(ctrl.len() + 1)?; + if !(1..=MAX_DEGREE).contains(°ree) || ctrl.len() > MAX_CONTROLS || knots.len() > 8192 { return None; } - charge(work, 64)?; - let points: Vec = span.iter().map(|p| point(*p)).collect(); - out.extend(solidcraft_geom::bezier(&points)?.fit_arcs(fit)?); - if out.len() > MAX_CONTROLS { + if knots.iter().any(|t| !t.is_finite()) || knots.windows(2).any(|w| w[1] < w[0]) || ctrl.iter().any(|p| !p.is_finite()) { return None; } + charge(work, ctrl.len().checked_mul(degree + 1)?.checked_mul(2)?)?; + let (k, c) = bspline::segment(degree, knots, &ctrl, t0, t1).ok()?; + Some((degree, k, c)) + }; + // In the curve's own direction, then the way the run goes. + let (degree, knots, ctrl) = match run.curve { + Curve::Spline { knots, points } => along(run, clamped(knots, points.iter().map(|p| HPoint::weighted(v3(*p), 1.0)).collect(), work)?)?, + Curve::RationalSpline { knots, homogeneous } => { + along(run, clamped(knots, homogeneous.iter().map(|p| HPoint { x: p[0], y: p[1], z: p[2], w: p[3] }).collect(), work)?)? + } + // Rational quadratic spans, already the way the run goes, joined: each joint knot twice. + Curve::Ellipse { .. } => { + let spans = spans_of(run, work)?; + let mut knots = vec![0.0; 3]; + let mut ctrl: Vec = Vec::new(); + for (i, span) in spans.iter().enumerate() { + let [p0, p1, p2] = span.as_slice() else { return None }; + if let Some(last) = ctrl.last() { + if (last.w - p0.w).abs() > 1e-12 * last.w.abs().max(p0.w.abs()) { + return None; + } + } else { + ctrl.push(*p0); + } + ctrl.extend([*p1, *p2]); + knots.extend([(i + 1) as f64; 2]); + } + knots.push(spans.len() as f64); + (2, knots, ctrl) + } + _ => return None, + }; + let max_w = ctrl.iter().map(|p| p.w).fold(0., f64::max); + if !(max_w.is_finite() && max_w > 0.) { + return None; } - Some(out) + let (Some(first), Some(last)) = (ctrl.first().and_then(|p| p.project()), ctrl.last().and_then(|p| p.project())) else { return None }; + let level = plane.height(first); + let (a, b) = (plane.to_local(first), plane.to_local(last)); + if first.dist(run.ends[0]) > tol || last.dist(run.ends[1]) > tol { + return None; + } + let mut points = Vec::with_capacity(ctrl.len()); + let mut weights = Vec::with_capacity(ctrl.len()); + for p in &ctrl { + if p.w / max_w < 1e-12 { + return None; + } + let v = p.project()?; + let error = (v.x.abs() + v.y.abs() + v.z.abs() + plane.origin.len()) * f64::EPSILON * 256.; + if (plane.height(v) - level).abs() + error > tol || error > tol * 0.1 { + return None; + } + let local = plane.to_local(v); + if !(local.x.is_finite() && local.y.is_finite()) { + return None; + } + points.push(local); + weights.push(p.w / max_w); + } + // The ends exactly where the curve ends. + if let Some(p) = points.first_mut() { + *p = a; + } + if let Some(p) = points.last_mut() { + *p = b; + } + if weights.iter().all(|w| (w - 1.).abs() <= 1e-12) { + weights.clear(); + } + Some(PlanarSpline { degree, knots, points, weights }) } -pub(super) fn segment(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize) -> Option> { - read(e, plane, tol, work, false) +/// A clamped B-spline `(degree, knots, control points)` run the way `run` goes: as it is +/// forward, its knots mirrored and its control points reversed back. +fn along(run: &Run, (degree, knots, ctrl): (usize, Vec, Vec)) -> Option<(usize, Vec, Vec)> { + if run.forward { + return Some((degree, knots, ctrl)); + } + let sum = knots.first()? + knots.last()?; + Some((degree, knots.iter().rev().map(|k| sum - k).collect(), ctrl.into_iter().rev().collect())) } -/// Edge `e` in `plane` exactly, for a sketch to project it: as [`segment`], and a curve of -/// several Bézier spans (a chain of a font's curves, a spline through points) as one segment -/// per span, each the line, conic or Bézier it is. `None` when the edge doesn't lie in a plane -/// parallel to `plane` or isn't read exactly. -pub(crate) fn projected(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize) -> Option> { - read(e, plane, tol, work, true) -} - -fn read(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize, each_span: bool) -> Option> { +fn read(run: &Run, plane: &Plane, tol: f64, work: &mut usize, each_span: bool) -> Option> { if !tol.is_finite() || tol <= 0. { return None; } - let mut c = e.curve(); - preflight(&c, work)?; - if !e.orientation() { - c.invert(); - } - let (t0, t1) = c.range_tuple(); - if !t0.is_finite() || !t1.is_finite() || t1 <= t0 { + charge(work, 1)?; + if matches!(run.curve, Curve::SurfaceIntersection { .. }) { return None; } - let (a3, b3) = (from_p3(c.subs(t0)), from_p3(c.subs(t1))); + let (ts, te) = run.ends_along(); + if !ts.is_finite() || !te.is_finite() || run.interval[1] <= run.interval[0] { + return None; + } + let eval = CurveEval::new(run.curve).ok()?; + let (a3, b3) = (eval.point(ts)?, eval.point(te)?); let (a, b) = (plane.to_local(a3), plane.to_local(b3)); if !a3.is_finite() || !b3.is_finite() || ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite()) - || a3.dist(from_p3(e.front().point())) > tol - || b3.dist(from_p3(e.back().point())) > tol + || a3.dist(run.ends[0]) > tol + || b3.dist(run.ends[1]) > tol { return None; } - if matches!(c, mt::Curve::Line(_)) { - let error = (a3.len() + b3.len() + plane.origin.len()) * f64::EPSILON * 256.; - return (error < tol * 0.1 && a.dist(b) > tol && (plane.height(a3) - plane.height(b3)).abs() + error <= tol) - .then_some(vec![Seg2::Line { a, b }]); + let level = plane.height(a3); + match run.curve { + Curve::Line { .. } => { + let error = (a3.len() + b3.len() + plane.origin.len()) * f64::EPSILON * 256.; + return (error < tol * 0.1 && a.dist(b) > tol && (level - plane.height(b3)).abs() + error <= tol).then_some(vec![Seg2::Line { a, b }]); + } + Curve::Polyline { points } => return polyline(points, ts, te, plane, level, tol, work), + Curve::Circle { frame, radius } => return circle(v3(frame.origin), v3(frame.x_axis), v3(frame.y_axis), *radius, ts, te, a, b, plane, tol), + _ => {} } - let (spans, error) = controls(&c, plane, plane.height(a3), tol)?; + let (spans, error) = controls(spans_of(run, work)?, plane, level, tol)?; if spans.windows(2).any(|pair| point(pair[0][pair[0].len() - 1]).dist(point(pair[1][0])) + 2. * error > tol) || point(spans.first()?.first().copied()?).dist(a) + error > tol || point(spans.last()?.last().copied()?).dist(b) + error > tol @@ -291,11 +483,73 @@ fn read(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize, each_span: bool if a.dist(b) > tol && spans.iter().all(|s| line_span(s, a, b, tol, error, work).is_some()) { return Some(vec![Seg2::Line { a, b }]); } - arc(&c, &spans, plane, a, b, tol, error, work) + arc(&eval, (ts, te), &spans, plane, a, b, tol, error, work) .or_else(|| free_form(&spans, a, b, tol)) .or_else(|| if each_span { span_by_span(&spans, a, b, tol) } else { None }) } +/// A polyline from parameter `ts` to `te` (either way round; segment i spans [i, i + 1]) as its +/// lines, each at level `level` of `plane`. +fn polyline(points: &[[f64; 3]], ts: f64, te: f64, plane: &Plane, level: f64, tol: f64, work: &mut usize) -> Option> { + charge(work, points.len())?; + let (lo, hi) = (ts.min(te), ts.max(te)); + if !(lo >= 0. && hi <= points.len() as f64) { + return None; + } + let at = |t: f64| -> Option { + let last = points.len().checked_sub(2)?; + let i = (t.floor().max(0.) as usize).min(last); + let (p, q) = (v3(*points.get(i)?), v3(*points.get(i + 1)?)); + Some(p + (q - p) * (t - i as f64)) + }; + let mut stations = vec![lo]; + stations.extend((lo.floor() as i64 + 1..=hi.ceil() as i64 - 1).map(|k| k as f64).filter(|k| *k > lo && *k < hi)); + stations.push(hi); + if ts > te { + stations.reverse(); + } + let mut out = Vec::with_capacity(stations.len()); + for pair in stations.windows(2) { + let (p, q) = (at(pair[0])?, at(pair[1])?); + let (u, v) = (plane.to_local(p), plane.to_local(q)); + if (plane.height(p) - level).abs() > tol || (plane.height(q) - level).abs() > tol || u.dist(v) <= tol { + return None; + } + out.push(Seg2::Line { a: u, b: v }); + } + Some(out) +} + +/// A circle (`o + r (cos t x + sin t y)`) from `ts` to `te`, ending at `a` and `b` in `plane`, as +/// the arc it is: `None` when it doesn't lie in a plane parallel to `plane`. A whole circle comes +/// back as its two halves. +#[allow(clippy::too_many_arguments)] +fn circle(o: Vec3, x: Vec3, y: Vec3, radius: f64, ts: f64, te: f64, a: Vec2, b: Vec2, plane: &Plane, tol: f64) -> Option> { + let n = plane.normal(); + let z = x.cross(y); + let tilt = radius * z.cross(n).len(); + let error = (o.len() + radius + plane.origin.len()) * f64::EPSILON * 256.; + if !(radius.is_finite() && radius > tol) || tilt + error > tol || error > tol * 0.1 { + return None; + } + let center = plane.to_local(o); + let sweep = (te - ts) * z.dot(n).signum(); + let angular_tol = tol / radius; + if sweep.abs() > std::f64::consts::TAU + angular_tol || sweep.abs() < angular_tol { + return None; + } + let start = (a - center).angle(); + let end = center + Vec2::new((start + sweep).cos(), (start + sweep).sin()) * radius; + if end.dist(b) + error > tol.min(ARC_END_TOL) || (a.dist(center) - radius).abs() > tol { + return None; + } + if (sweep.abs() - std::f64::consts::TAU).abs() <= angular_tol { + let h = sweep.signum() * std::f64::consts::PI; + return Some(vec![Seg2::Arc { center, radius, start, sweep: h }, Seg2::Arc { center, radius, start: start + h, sweep: h }]); + } + Some(vec![Seg2::Arc { center, radius, start, sweep }]) +} + /// Several `spans` end to end, from `a` to `b`, each as the segment it is: a span whose control /// polygon lies along its chord a line, the others as [`free_form`] reads them. Spans whose /// ends meet are left out; each segment starts where the one before ended. @@ -334,7 +588,7 @@ fn off_chord(pts: &[Vec2]) -> f64 { /// One Bézier span that is neither a line nor an arc, as the exact free-form segment it is /// (a font's quadratic or cubic, a conic), its ends `a` and `b`. `None` for several spans (a -/// curve that may wind about more than once), degrees past [`solidcraft_geom::MAX_BEZIER_DEGREE`], +/// curve that may wind about more than once), degrees past [`solidcore_record::MAX_BEZIER_DEGREE`], /// rational spans other than conics, and control polygons with no area (a curve doubling back /// along a line). fn free_form(spans: &[Vec], a: Vec2, b: Vec2, tol: f64) -> Option> { @@ -378,15 +632,24 @@ fn free_form(spans: &[Vec], a: Vec2, b: Vec2, tol: f64) -> Option> Some(vec![seg]) } -/// The spline `c` (its Bézier `spans` in the plane, from `a` to `b`) as a circular arc, when -/// whole-span proofs show it is one. +/// The spline (`eval` from parameter `ts` to `te`; its Bézier `spans` in the plane, from `a` to +/// `b`) as a circular arc, when whole-span proofs show it is one. #[allow(clippy::too_many_arguments)] -fn arc(c: &mt::Curve, spans: &[Vec], plane: &Plane, a: Vec2, b: Vec2, tol: f64, error: f64, work: &mut usize) -> Option> { - let (t0, t1) = c.range_tuple(); +fn arc( + eval: &CurveEval, + (ts, te): (f64, f64), + spans: &[Vec], + plane: &Plane, + a: Vec2, + b: Vec2, + tol: f64, + error: f64, + work: &mut usize, +) -> Option> { // Samples are only a candidate proposal. Whole-span implicit and oriented // angular proofs below are required before converting any spline to an arc. - let q = plane.to_local(from_p3(c.subs(t0 + (t1 - t0) * 5. / 16.))) - a; - let r = plane.to_local(from_p3(c.subs(t0 + (t1 - t0) * 11. / 16.))) - a; + let q = plane.to_local(eval.point(ts + (te - ts) * 5. / 16.)?) - a; + let r = plane.to_local(eval.point(ts + (te - ts) * 11. / 16.)?) - a; let det = 2. * (q.x * r.y - q.y * r.x); if !det.is_finite() || det.abs() < 1e-300 { return None; @@ -432,7 +695,6 @@ fn arc(c: &mt::Curve, spans: &[Vec], plane: &Plane, a: Vec2, b: Vec2, tol: f6 #[allow(clippy::unwrap_used, clippy::panic)] mod tests { use super::*; - use mt::builder; fn choose(n: usize, k: usize) -> f64 { (0..k).fold(1., |v, i| v * (n - i) as f64 / (i + 1) as f64) @@ -449,82 +711,117 @@ mod tests { } out } - fn trap() -> Vec { - let mut p = vec![1.]; - for k in 0..=16 { - p = multiply(&p, &[-(k as f64) / 16., 1.]); + /// The power basis `p` (in t) over the span t = a + h s, in s. + fn shifted(p: &[f64], a: f64, h: f64) -> Vec { + let mut out = vec![0.]; + for c in p.iter().rev() { + out = multiply(&out, &[a, h]); + out[0] += c; } - let mid = (0..=16).map(|k| 1. / 32. - k as f64 / 16.).product::(); - p.iter_mut().for_each(|v| *v /= mid); - p + out } - fn edge(x: &[f64], y: &[f64], w: &[f64], degree: usize) -> mt::Edge { + /// A spline of `degree` over spans [k/16, (k+1)/16] (k = 0..16), joined C0 (each interior + /// knot `degree` times), whose homogeneous `x`, `y`, `w` are the power bases `f(k)` gives + /// in the span's own parameter s ∈ [0, 1]: a curve that bends only between the knots. + fn spans(degree: usize, f: impl Fn(usize) -> [Vec; 3]) -> Curve { + let mut knots = vec![0.; degree + 1]; + let mut homogeneous: Vec<[f64; 4]> = Vec::new(); + for k in 0..16 { + let [x, y, w] = f(k); + let (x, y, w) = (bernstein(&x, degree), bernstein(&y, degree), bernstein(&w, degree)); + let controls = x.iter().zip(y).zip(w).map(|((x, y), w)| [*x, y, 0., w]); + homogeneous.extend(controls.skip(usize::from(k > 0))); + knots.extend(std::iter::repeat_n((k + 1) as f64 / 16., degree)); + } + knots.push(1.); + Curve::RationalSpline { knots, homogeneous } + } + /// The bump s (1 - s) / (1/4) in the span's own parameter: 0 at both its ends (every old + /// sample location k/16 is a knot), 1 half way along the first span (t = 1/32). + fn bump(k: usize) -> Vec { + if k == 0 { vec![0., 4., -4.] } else { vec![0.] } + } + fn bezier_knots(degree: usize) -> Vec { + std::iter::repeat_n(0., degree + 1).chain(std::iter::repeat_n(1., degree + 1)).collect() + } + /// A NURBS curve of homogeneous control points `(x, y, 0, w)` (power bases in `x`, `y`, `w`). + fn curve(x: &[f64], y: &[f64], w: &[f64], degree: usize) -> Curve { let (x, y, w) = (bernstein(x, degree), bernstein(y, degree), bernstein(w, degree)); - let controls = x.iter().zip(y).zip(w).map(|((x, y), w)| mt::Vector4::new(*x, y, 0., w)).collect(); - let c = mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(degree), controls))); - let a = mt::Vertex::new(c.subs(0.)); - let b = mt::Vertex::new(c.subs(1.)); - mt::Edge::new(&a, &b, c) + let homogeneous = x.iter().zip(y).zip(w).map(|((x, y), w)| [*x, y, 0., w]).collect(); + Curve::RationalSpline { knots: bezier_knots(degree), homogeneous } + } + fn at(c: &Curve, t: f64) -> Vec3 { + CurveEval::new(c).unwrap().point(t).unwrap() + } + /// `c` over its whole domain, run forward (or back). + fn run(c: &Curve, forward: bool) -> Run<'_> { + let interval = match c.natural() { + solidcore_record::brep::Natural::Range(a, b) => [a, b], + solidcore_record::brep::Natural::Periodic => [0., std::f64::consts::TAU], + }; + let ends = [at(c, interval[0]), at(c, interval[1])]; + Run { curve: c, interval, forward, ends: if forward { ends } else { [ends[1], ends[0]] } } + } + /// The quarter circle of radius 10 about the origin from +x to +y, as a rational quadratic + /// spline. + fn quarter() -> Curve { + let w = std::f64::consts::FRAC_1_SQRT_2; + Curve::RationalSpline { knots: bezier_knots(2), homogeneous: vec![[10., 0., 0., 1.], [10. * w, 10. * w, 0., w], [0., 10., 0., 1.]] } } + /// Sampling must not certify a spline cap that merely passes through the sample points. + /// Once that took a single polynomial of degree 17 with a root at each of the 17 old sample + /// locations k/16, more than a B-rep record holds (MAX_SPLINE_DEGREE 16); here the aliasing is + /// in the knots instead: a C0 quadratic spline with a knot at every k/16, on the line (or + /// the circle) at each of them, and bowing off it between (by 1 mm, 1/32 along). #[test] fn sample_aliasing_does_not_certify_spline_caps() { - let e = edge(&[0., 10.], &trap(), &[1.], 17); + let e = spans(2, |k| { + let h = 1. / 16.; + [shifted(&[0., 10.], k as f64 * h, h), bump(k), vec![1.]] + }); for k in 0..=16 { - assert!(e.curve().subs(k as f64 / 16.).y.abs() < 1e-4, "old sample locations must see a line"); + assert!(at(&e, k as f64 / 16.).y.abs() < 1e-12, "old sample locations must see a line"); } - assert!((e.curve().subs(1. / 32.).y - 1.).abs() < 1e-6); - assert!(segment(&e, &Plane::XY, 1e-3, &mut 2_000_000).is_none()); - let front = e.front(); - let back = e.back(); - let low_right = mt::Vertex::new(mt::Point3::new(10., -3., 0.)); - let low_left = mt::Vertex::new(mt::Point3::new(0., -3., 0.)); - let wire: mt::Wire = - vec![e.clone(), builder::line(back, &low_right), builder::line(&low_right, &low_left), builder::line(&low_left, front)].into(); - let cap = builder::try_attach_plane(&[wire]).unwrap(); - let body = crate::body::Body::new(builder::tsweep(&cap, mt::Vector3::new(0., 0., 1.))).unwrap(); - assert!(body.validity().is_empty()); - let tool = crate::box_solid(solidcraft_geom::Vec3::new(-1., -4., 0.5), solidcraft_geom::Vec3::new(12., 7., 1.)).unwrap(); - assert!( - crate::prism::prism_boolean(&body, &tool, crate::BoolOp::Cut).is_none(), - "an actual extruded aliased spline cap must reach the generic route" - ); - let q = trap(); - let mut perturb = q.iter().map(|v| v * 0.1).collect::>(); - perturb[0] += 1.; + assert!((at(&e, 1. / 32.).y - 1.).abs() < 1e-12); + assert!(segment(&run(&e, true), &Plane::XY, 1e-3, &mut 2_000_000).is_none()); + // The quarter circle of radius 10, its homogeneous coordinates scaled by 1 + bump / 10 but + // its weight not: radius 10 at every k/16, 11 at 1/32. let w = std::f64::consts::FRAC_1_SQRT_2; - let x = multiply(&[10., 20. * (w - 1.), 10. * (1. - 2. * w)], &perturb); - let y = multiply(&[0., 20. * w, 10. * (1. - 2. * w)], &perturb); - let circle = edge(&x, &y, &[1., 2. * (w - 1.), 2. * (1. - w)], 19); + let (x, y, wt) = ([10., 20. * (w - 1.), 10. * (1. - 2. * w)], [0., 20. * w, 10. * (1. - 2. * w)], [1., 2. * (w - 1.), 2. * (1. - w)]); + let circle = spans(4, |k| { + let (a, h) = (k as f64 / 16., 1. / 16.); + let scale: Vec = bump(k).iter().enumerate().map(|(i, v)| v / 10. + if i == 0 { 1. } else { 0. }).collect(); + [multiply(&shifted(&x, a, h), &scale), multiply(&shifted(&y, a, h), &scale), shifted(&wt, a, h)] + }); for k in 0..=16 { - let p = circle.curve().subs(k as f64 / 16.); - assert!((p.x.hypot(p.y) - 10.).abs() < 1e-3, "old sample locations must see a circle"); + let p = at(&circle, k as f64 / 16.); + assert!((p.x.hypot(p.y) - 10.).abs() < 1e-9, "old sample locations must see a circle"); } - let p = circle.curve().subs(1. / 32.); - assert!((p.x.hypot(p.y) - 11.).abs() < 1e-5); - assert!(segment(&circle, &Plane::XY, 1e-3, &mut 2_000_000).is_none()); + let p = at(&circle, 1. / 32.); + assert!((p.x.hypot(p.y) - 11.).abs() < 1e-9); + assert!(segment(&run(&circle, true), &Plane::XY, 1e-3, &mut 2_000_000).is_none()); } #[test] fn genuine_curves_and_oriented_traversal_are_certified() { - let a = mt::Vertex::new(mt::Point3::new(10., 0., 0.)); - let b = mt::Vertex::new(mt::Point3::new(0., 10., 0.)); - let arc = builder::circle_arc(&a, &b, mt::Point3::new(10. / 2f64.sqrt(), 10. / 2f64.sqrt(), 0.)); - for e in [&arc, &arc.inverse()] { - let result = segment(e, &Plane::XY, 1e-5, &mut 2_000_000).unwrap(); + let arc = quarter(); + for forward in [true, false] { + let result = segment(&run(&arc, forward), &Plane::XY, 1e-5, &mut 2_000_000).unwrap(); let Seg2::Arc { center, radius, sweep, .. } = result[0] else { panic!("expected arc") }; assert!(center.len() < 1e-8 && (radius - 10.).abs() < 1e-8); assert!((sweep.abs() - std::f64::consts::FRAC_PI_2).abs() < 1e-8); - assert_eq!(sweep > 0., e.orientation()); + assert_eq!(sweep > 0., forward); } - let line = edge(&[0., 10.], &[0.], &[1.], 17); - assert!(matches!(segment(&line, &Plane::XY, 1e-5, &mut 2_000_000).unwrap()[0], Seg2::Line { .. })); + // A line written at the highest degree a B-rep record holds (MAX_SPLINE_DEGREE). + let line = curve(&[0., 10.], &[0.], &[1.], solidcraft_geom::bspline::MAX_SPLINE_DEGREE); + assert!(matches!(segment(&run(&line, true), &Plane::XY, 1e-5, &mut 2_000_000).unwrap()[0], Seg2::Line { .. })); // The longitudinal derivative is negative at t=1/3, independently // establishing genuine retracing rather than a stationary tangent. - let backtrack = edge(&[0., 10., -35., 35.], &[0.], &[1.], 3); - assert!(backtrack.curve().der(1. / 3.).x < -1.); - assert!(segment(&backtrack, &Plane::XY, 1e-5, &mut 2_000_000).is_none()); - assert!(segment(&arc, &Plane::XY, 1e-5, &mut 0).is_none()); + let backtrack = curve(&[0., 10., -35., 35.], &[0.], &[1.], 3); + assert!((at(&backtrack, 1. / 3. + 1e-6).x - at(&backtrack, 1. / 3.).x) / 1e-6 < -1.); + assert!(segment(&run(&backtrack, true), &Plane::XY, 1e-5, &mut 2_000_000).is_none()); + assert!(segment(&run(&arc, true), &Plane::XY, 1e-5, &mut 0).is_none()); } /// A curve read as an arc ends where the curve does, however large the tolerance (it grows @@ -534,38 +831,33 @@ mod tests { #[test] fn a_curve_near_a_circle_is_not_an_arc_ending_off_it() { // A parabola within a micron of the circle through its ends and middle. - let e = edge(&[0., 2., 0.], &[0., 0., 0.2], &[1.], 2); + let e = curve(&[0., 2., 0.], &[0., 0., 0.2], &[1.], 2); let (a, b) = (Vec2::new(0., 0.), Vec2::new(2., 0.2)); - assert!(from_p3(e.back().point()).dist(solidcraft_geom::Vec3::new(2., 0.2, 0.)) < 1e-12); + assert!(at(&e, 1.).dist(Vec3::new(2., 0.2, 0.)) < 1e-12); for tol in [1e-5, 2e-3] { - let segs = segment(&e, &Plane::XY, tol, &mut 2_000_000).unwrap(); + let segs = segment(&run(&e, true), &Plane::XY, tol, &mut 2_000_000).unwrap(); let (first, last) = (segs.first().unwrap(), segs.last().unwrap()); assert!(first.start().dist(a) < 1e-9 && last.end().dist(b) < 1e-9, "{tol}: {segs:?}"); } // A true arc is still one at either tolerance. - let (p, q) = (mt::Vertex::new(mt::Point3::new(10., 0., 0.)), mt::Vertex::new(mt::Point3::new(0., 10., 0.))); - let arc = builder::circle_arc(&p, &q, mt::Point3::new(10. / 2f64.sqrt(), 10. / 2f64.sqrt(), 0.)); + let arc = quarter(); for tol in [1e-5, 2e-3] { - assert!(matches!(segment(&arc, &Plane::XY, tol, &mut 2_000_000).unwrap()[..], [Seg2::Arc { .. }])); + assert!(matches!(segment(&run(&arc, true), &Plane::XY, tol, &mut 2_000_000).unwrap()[..], [Seg2::Arc { .. }])); } } #[test] fn discontinuous_and_multiple_winding_curves_decline() { - let edge_from = |knots: Vec, points: Vec| { - let c = mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::from(knots), points))); - let (lo, hi) = c.range_tuple(); - mt::Edge::new(&mt::Vertex::new(c.subs(lo)), &mt::Vertex::new(c.subs(hi)), c) - }; + let spline = |knots: Vec, homogeneous: Vec<[f64; 4]>| Curve::RationalSpline { knots, homogeneous }; let w = std::f64::consts::FRAC_1_SQRT_2; - let p = |x, y, w| mt::Vector4::new(x, y, 0., w); - let disconnected = edge_from( + let p = |x, y, w| [x, y, 0., w]; + let disconnected = spline( vec![0., 0., 0., 1., 1., 1., 2., 2., 2.], vec![p(10., 0., 1.), p(10. * w, 10. * w, w), p(0., 10., 1.), p(-10., 0., 1.), p(-10. * w, -10. * w, w), p(0., -10., 1.)], ); - assert!(segment(&disconnected, &Plane::XY, 1e-5, &mut 2_000_000).is_none()); - let skipped_line = edge_from(vec![0., 0., 1., 1., 2., 2.], vec![p(0., 0., 1.), p(2., 0., 1.), p(5., 0., 1.), p(10., 0., 1.)]); - assert!(segment(&skipped_line, &Plane::XY, 1e-5, &mut 2_000_000).is_none()); + assert!(segment(&run(&disconnected, true), &Plane::XY, 1e-5, &mut 2_000_000).is_none()); + let skipped_line = spline(vec![0., 0., 1., 1., 2., 2.], vec![p(0., 0., 1.), p(2., 0., 1.), p(5., 0., 1.), p(10., 0., 1.)]); + assert!(segment(&run(&skipped_line, true), &Plane::XY, 1e-5, &mut 2_000_000).is_none()); let mut points = vec![p(10., 0., 1.)]; let mut knots = vec![0., 0., 0.]; for i in 0..8 { @@ -576,7 +868,7 @@ mod tests { knots.extend([i as f64 + 1.; 2]); } knots.push(8.); - let twice = edge_from(knots, points); - assert!(segment(&twice, &Plane::XY, 1e-5, &mut 2_000_000).is_none()); + let twice = spline(knots, points); + assert!(segment(&run(&twice, true), &Plane::XY, 1e-5, &mut 2_000_000).is_none()); } } diff --git a/crates/kernel/src/prism_fast_path_tests.rs b/crates/kernel/src/prism_fast_path_tests.rs deleted file mode 100644 index 37231e0ac..000000000 --- a/crates/kernel/src/prism_fast_path_tests.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! The prism fast path: `boolean_whole` asks the exact 2D prism route before it meshes both -//! operands, so a plate and the tool through it are decided without a mesh of either. -use super::*; -use crate::{BoolOp, boolean, box_solid, cylinder, measure}; -use std::f64::consts::PI; - -/// A cylindrical tool through a plate: the exact prism route answers the pair, and the material -/// it removes is the tool's own. -#[test] -fn a_hole_through_a_plate_removes_the_tool_volume() { - let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).expect("plate"); - let tool = cylinder(Vec3::new(20.0, 15.0, -1.0), Vec3::Z, 5.0, 12.0).expect("tool"); - let cut = boolean(&plate, &tool, BoolOp::Cut).expect("cut").expect("a hole leaves material"); - let m = measure(&cut).expect("measure"); - let want = 40.0 * 30.0 * 10.0 - PI * 25.0 * 10.0; - assert!((m.volume - want).abs() < want * 5e-3, "{} vs {want}", m.volume); - assert!(cut.validity().is_empty(), "{:?}", cut.validity()); -} - -/// Boxes that stay apart: the union keeps both, whichever route decides it. -#[test] -fn bodies_that_stay_apart_join_into_one_body_with_both_lumps() { - let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).expect("a"); - let b = box_solid(Vec3::new(20.0, 0.0, 0.0), Vec3::new(30.0, 10.0, 10.0)).expect("b"); - let joined = boolean(&a, &b, BoolOp::Union).expect("union").expect("two boxes"); - assert!((measure(&joined).expect("measure").volume - 2000.0).abs() < 1e-6); - assert_eq!(joined.lumps().expect("lumps").len(), 2); -} - -/// A tool wholly inside its target leaves a closed void, not a through cut. -#[test] -fn a_tool_wholly_inside_leaves_a_closed_void() { - let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 40.0)).expect("block"); - let inner = box_solid(Vec3::new(15.0, 15.0, 15.0), Vec3::new(25.0, 25.0, 25.0)).expect("inner"); - let cut = boolean(&block, &inner, BoolOp::Cut).expect("cut").expect("a void leaves material"); - assert!((measure(&cut).expect("measure").volume - 63000.0).abs() < 1e-6); - assert!(cut.validity().is_empty(), "{:?}", cut.validity()); -} - -/// A tool that misses its target, in section or along the extrusion, leaves it as it is: the -/// sampled shortcut answers that by reusing the operand itself, and the 2D route must not -/// rebuild it into a look-alike solid on the way past - an untouched body in a timeline has to -/// stay the very same body. -#[test] -fn a_cut_that_changes_nothing_keeps_the_original_body() { - let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).expect("plate"); - let past_the_end = box_solid(Vec3::new(200.0, 200.0, -5.0), Vec3::new(210.0, 210.0, 20.0)).expect("tool"); - assert!( - boolean(&plate, &past_the_end, BoolOp::Cut).expect("cut").expect("material stays").same(&plate), - "a tool clear of the plate must leave the very same body" - ); - let inside_the_height = box_solid(Vec3::new(200.0, 200.0, 5.0), Vec3::new(210.0, 210.0, 20.0)).expect("tool"); - assert!( - boolean(&plate, &inside_the_height, BoolOp::Cut).expect("cut").expect("material stays").same(&plate), - "a tool that only overlaps the plate's height must leave the very same body" - ); - let covers_it = box_solid(Vec3::new(-10.0, -10.0, -10.0), Vec3::new(50.0, 40.0, 20.0)).expect("tool"); - assert!(boolean(&plate, &covers_it, BoolOp::Cut).expect("cut").is_none(), "a tool over the whole plate removes it"); -} diff --git a/crates/kernel/src/prism_lineage.rs b/crates/kernel/src/prism_lineage.rs deleted file mode 100644 index 0fb977595..000000000 --- a/crates/kernel/src/prism_lineage.rs +++ /dev/null @@ -1,538 +0,0 @@ -//! The history of a prism boolean's result (see [`super::prism_boolean`]), from what its faces -//! were built over: each wall over a section segment whose [`Tag`] says which operand wall it -//! was read beside, each cap over a section region lying on operand caps at its level. Edges -//! follow from the same tags: a wall's edge with a cap is the operand's edge between them (or -//! the meeting of the wall with the other operand's cap); an edge between walls at a section -//! vertex is the operand's edge there (or the meeting of two operands' walls). - -use std::collections::{BTreeSet, HashMap}; - -use solidcraft_geom::{Plane, Region2, Vec2, Vec3}; -use truck_modeling as mt; - -use super::{Index, Section, Tag, dist_to, inside}; -use crate::BoolOp; -use crate::body::{Body, edge_order, from_p3}; -use crate::history::{EdgeOrigin, FaceOrigin, FaceOrigin::Face, FaceProv, Side}; - -/// A cap of an operand: a planar face square to the prism direction. -struct Cap { - origin: FaceOrigin, - /// Its level and whether it faces along the direction. - z: f64, - up: bool, - outline: Outline, -} - -/// A section's regions with the walls its outline was read beside and its segments' middles, -/// to tell whether two sections overlap. -struct Outline { - regions: Vec, - walls: BTreeSet<(usize, usize)>, - middles: Vec, -} - -impl Outline { - fn of(s: &Section) -> Outline { - let (segs, tags) = s.segments(); - Outline { - regions: s.regions.clone(), - walls: tags.iter().filter_map(|t| Some((t.operand, t.wall?))).collect(), - middles: segs.iter().map(|g| g.point_at(0.5)).collect(), - } - } -} - -/// What a prism boolean's result is built from: the operands (target, tool), the direction and -/// the plane square to it that sections are drawn in, and for simple prisms each operand's -/// extent along the direction. -pub(super) struct Context<'a> { - pub op: BoolOp, - pub operands: [&'a Body; 2], - pub index: [&'a Index; 2], - pub plane: Plane, - pub tol: f64, - pub heights: Option<[(f64, f64); 2]>, - /// Both operands' caps, read once (see [`Context::caps`]). - caps: std::cell::OnceCell>>, -} - -/// How one piece of the result was built. -pub(super) enum Built { - /// One body of `crate::extrude` of a section's one region through `layers`: successive - /// slabs (the section as read in each, between its two levels), bottom first, all of one - /// outline. Several where operands stacked end to end share an outline (one wall then lies - /// over each operand's wall in turn, and is made from all of them). - Extruded { layers: Vec<(Section, f64, f64)> }, - /// Sewn (`sew_connected_sections`) from these faces, the sewing saying which each face of - /// the piece was built from (`None`: it could not). - Sewn { specs: Vec, faces: Option> }, - /// Built some other way, carrying its own history over the operands (none: not known). - Traced, -} - -/// A face sewn into a stepped prism. -pub(super) enum Spec { - /// A wall over one section segment through successive slabs, between successive `levels` - /// (one more than `slabs`): what it is over in each slab. - Wall { levels: Vec, slabs: Vec }, - /// A cap over `section` at level `z`, facing along the direction when `up`. - Cap { section: Section, z: f64, up: bool }, -} - -/// A wall in one slab: over a segment tagged `tag`; `next` is the wall over the next segment -/// of its loop in that slab, which it meets at `at`. -pub(super) struct Slab { - pub tag: Tag, - pub next: usize, - pub at: Vec2, -} - -impl Spec { - /// The wall's slab between levels `lo` and `hi` (`hi` above `lo`). - fn slab(&self, lo: f64, hi: f64) -> Option<&Slab> { - let Spec::Wall { levels, slabs } = self else { return None }; - let mid = (lo + hi) / 2.0; - slabs.iter().zip(levels.windows(2)).find(|(_, z)| z[0] < mid && mid < z[1]).map(|(s, _)| s) - } - - /// The wall's slab at its bottom level, when that is `z`. - fn bottom(&self, z: f64, tol: f64) -> Option<&Slab> { - let Spec::Wall { levels, slabs } = self else { return None }; - ((levels.first()? - z).abs() <= tol).then_some(slabs.first()?) - } - - /// The wall's slab at its top level, when that is `z`. - fn top(&self, z: f64, tol: f64) -> Option<&Slab> { - let Spec::Wall { levels, slabs } = self else { return None }; - ((levels.last()? - z).abs() <= tol).then_some(slabs.last()?) - } - - /// The wall's slab at its bottom or top level `z`. - fn end(&self, z: f64, tol: f64) -> Option<&Slab> { - self.bottom(z, tol).or_else(|| self.top(z, tol)) - } -} - -/// A face of an extruded piece: a wall or a cap. -#[derive(Clone, Copy)] -enum Kind { - /// The wall over this segment of the section. - Wall(usize), - Cap(usize), -} - -impl<'a> Context<'a> { - pub(super) fn new(op: BoolOp, operands: [&'a Body; 2], index: [&'a Index; 2], plane: Plane, tol: f64, heights: Option<[(f64, f64); 2]>) -> Self { - Context { op, operands, index, plane, tol, heights, caps: std::cell::OnceCell::new() } - } - - /// `body`, made of `pieces` (their shells in order), with its history over the operands - /// (none where it is not known). - pub(super) fn attach>(&self, body: Body, pieces: &[(B, Built)]) -> Body { - let pieces: Vec<(&Body, &Built)> = pieces.iter().map(|(b, k)| (b.borrow(), k)).collect(); - let (faces, edges) = self.history(&pieces).unzip(); - crate::record::traced(body, &crate::record::counts(&self.operands), faces, edges.as_ref()) - } - - /// The faces (each a region of operand faces, and whether it is one untouched) and the edges - /// (by identity) of the pieces, in order; `None` where something is not known. - pub(super) fn history(&self, pieces: &[(&Body, &Built)]) -> Option<(Vec, HashMap>)> { - let caps = self.caps.get_or_init(|| self.caps()).as_deref()?; - let mut faces = Vec::new(); - let mut edges = HashMap::new(); - for (body, built) in pieces { - let (f, e) = match built { - Built::Extruded { layers } => self.extruded(caps, body, layers)?, - Built::Sewn { specs, faces } => self.sewn(caps, body, specs, faces.as_deref()?)?, - Built::Traced => { - let h = body.history()?; - faces.extend(h.faces.iter().cloned()); - edges.extend(crate::record::edges_by_identity(body, h)); - continue; - } - }; - faces.extend(f.into_iter().map(|(origins, whole)| crate::record::region(origins, whole))); - edges.extend(e); - } - // Pieces of one body can share an origin. - crate::record::mark_shared_split(&mut faces); - Some((faces, edges)) - } - - /// Both operands' caps, their outlines tagged. - fn caps(&self) -> Option> { - let d = self.plane.normal(); - let mut caps = Vec::new(); - let (mut work, mut segments) = (2_000_000usize, super::MAX_PLANAR_SEGMENTS * 2); - for (operand, (body, index)) in self.operands.iter().zip(self.index).enumerate() { - for (face, f) in body.solid.face_iter().enumerate() { - let mt::Surface::Plane(p) = f.oriented_surface() else { continue }; - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - if n.dot(d).abs() < 1.0 - 1e-9 { - continue; - } - let section = Section::from_loops(index.loops(f, face, &self.plane, self.tol, &mut work, &mut segments)?)?; - let (z, up) = (self.plane.height(from_p3(p.origin())), n.dot(d) > 0.0); - caps.push(Cap { origin: Face { operand, face }, z, up, outline: Outline::of(§ion.oriented()) }); - } - } - Some(caps) - } - - /// The operand caps under a result cap over `section` at level `z` (facing along the - /// direction when `up`): the target's caps there facing the same way, and the tool's facing - /// the same way (a union or intersection) or the other way (a cut, whose tool's caps bound - /// what it leaves), wherever they overlap the section. - fn cap_origins(&self, caps: &[Cap], section: &Section, z: f64, up: bool) -> BTreeSet { - let outline = Outline::of(section); - caps.iter() - .filter(|c| { - let facing = match c.origin { - Face { operand: 1, .. } if self.op == BoolOp::Cut => c.up != up, - _ => c.up == up, - }; - facing && (c.z - z).abs() < self.tol && self.overlap(&outline, &c.outline) - }) - .map(|c| c.origin) - .collect() - } - - /// Do two sections (at one level) overlap? Where their outlines share a wall, or a point of - /// one's outline, clear of the other's, lies inside it. - fn overlap(&self, x: &Outline, y: &Outline) -> bool { - let within = |x: &Outline, y: &Outline| x.middles.iter().any(|m| dist_to(&y.regions, *m) > self.tol && inside(&y.regions, *m)); - !x.walls.is_disjoint(&y.walls) || within(x, y) || within(y, x) - } - - /// The operand wall a segment was read beside. - fn wall(t: Tag) -> Option { - Some(Face { operand: t.operand, face: t.wall? }) - } - - /// The operand's edges (by number) bounding exactly the faces `faces`. - fn edges_between(&self, operand: usize, [f, g]: [usize; 2]) -> &[usize] { - self.index.get(operand).and_then(|index| index.between.get(&(f.min(g), f.max(g)))).map_or(&[], Vec::as_slice) - } - - /// Is the wall over a segment tagged `t` between `lo` and `hi` its operand wall untouched? - /// The whole cap edge it was read off, the operand's whole height (simple prisms), and a - /// wall with no other cap edges than its two. - fn whole(&self, caps: &[Cap], t: Tag, lo: f64, hi: f64) -> bool { - let (Some(heights), Some(wall), Some(_), Some(_)) = (self.heights, t.wall, t.start, t.end) else { return false }; - let Some((l, h)) = heights.get(t.operand) else { return false }; - let Some(index) = self.index.get(t.operand) else { return false }; - let cap_edges: usize = caps - .iter() - .filter_map(|c| match c.origin { - Face { operand, face } if operand == t.operand => index.between.get(&(face.min(wall), face.max(wall))).map(Vec::len), - _ => None, - }) - .sum(); - (lo - l).abs() < self.tol && (hi - h).abs() < self.tol && cap_edges == 2 - } - - /// The origins of the edge between the wall over a segment tagged `t` and a cap lying on the - /// operand faces `cap`: the operand's edge between the wall and its own cap there (the very - /// edge the segment was read off, or the one it runs along where its slab ends: the one - /// running through `at`, a point of the edge, where the wall meets its caps along several), - /// else where the wall meets the cap (all of the faces it lies on). - fn cap_edge(&self, t: Tag, cap: &BTreeSet, at: Vec3) -> Option> { - let (x, w) = (t.operand, t.wall?); - let own: Vec = - cap.iter().filter_map(|o| if let Face { operand, face } = *o { (operand == x).then_some(face) } else { None }).collect(); - let index = self.index.get(x)?; - let beside = |e: &usize| index.bounds.get(*e).is_some_and(|(fs, _, _)| fs.contains(&w) && fs.iter().any(|f| own.contains(f))); - if let Some(e) = [t.edge, t.far].into_iter().flatten().find(beside) { - return Some(vec![EdgeOrigin::Edge { operand: x, edge: e }]); - } - let along: Vec = own.iter().flat_map(|c| self.edges_between(x, [w, *c])).copied().collect(); - match along.as_slice() { - [e] => Some(vec![EdgeOrigin::Edge { operand: x, edge: *e }]), - [] => Some(vec![EdgeOrigin::meet(Self::wall(t)?, Side::new(cap.iter().copied())?)]), - // One wall with openings meets its caps along several edges (a side wall with ports - // cut through it meets the ports' floors at each port): the one this edge lies on, - // else (a new opening beside them) where the wall meets the cap. - many => match self.edge_through(x, many, at)? { - Some(edge) => Some(vec![EdgeOrigin::Edge { operand: x, edge }]), - None => Some(vec![EdgeOrigin::meet(Self::wall(t)?, Side::new(cap.iter().copied())?)]), - }, - } - } - - /// Of the operand's edges `edges`, the one the point `at` lies on (`Some(None)` when none - /// does; `None` when several do). - fn edge_through(&self, operand: usize, edges: &[usize], at: Vec3) -> Option> { - if edges.len() > 4096 { - return None; - } - let body = self.operands.get(operand)?; - let order = crate::body::edge_order(body.solid.face_iter()).0; - let mut on = edges.iter().filter(|e| { - order.get(**e).is_some_and(|edge| { - use mt::{BoundedCurve, ParametricCurve}; - let c = edge.curve(); - let (t0, t1) = c.range_tuple(); - // The edge as a fine polyline: a line exactly, an arc within its chords' sag. - let n = if matches!(c, mt::Curve::Line(_)) { 1 } else { 64 }; - let pts: Vec = (0..=n).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / n as f64))).collect(); - let length: f64 = pts.windows(2).map(|w| w[0].dist(w[1])).sum(); - let near = self.tol * 10.0 + if n == 1 { 0.0 } else { length * 2e-3 }; - pts.windows(2).any(|w| at.dist_to_segment(w[0], w[1]) <= near) - }) - }); - match (on.next(), on.next()) { - (Some(e), None) => Some(Some(*e)), - (None, _) => Some(None), - _ => None, - } - } - - /// The origins of the edge between the walls over two segments where the first (tagged - /// `t1`) runs into the second (`t2`), between levels `lo` and `hi`: the operand's edge there - /// between its walls (along the line through the operand vertex the segments meet at, else - /// the one edge between them), where two operands' walls meet, or none within one wall (a - /// segment split there). - fn junction(&self, t1: Tag, t2: Tag, lo: f64, hi: f64) -> Option> { - let (p, q) = (Self::wall(t1)?, Self::wall(t2)?); - if t1.operand != t2.operand { - return Some(vec![EdgeOrigin::meet(p, q)]); - } - let (x, w1, w2) = (t1.operand, t1.wall?, t2.wall?); - match (t1.end, t2.start) { - // At that vertex: the operand's edge there (a seam, within one wall), else two edges - // of one wall's cap outline running on through it. - (Some(v), Some(u)) if v == u => self.edge_over(x, [w1, w2], Some(v), lo, hi).or_else(|| (w1 == w2).then(Vec::new)), - _ if w1 == w2 => Some(Vec::new()), - // Elsewhere (a segment split off there, or read off another cap): only the operand's - // walls are around the edge, so the operand has its edge between them there, and - // that is the one edge between them over these levels where there is one. - _ => self.edge_over(x, [w1, w2], None, lo, hi), - } - } - - /// The operand's edge between the walls `faces` that runs over the levels `lo` to `hi`, - /// when it has exactly one; with `at`, among the edges between them chained to that vertex. - /// The segments' vertex was read at one level and carried through others, and the line - /// between two walls is in several edges where vertices an earlier operation left (stations) - /// split it: the levels say which of them a slab's edge runs along. - fn edge_over(&self, operand: usize, faces: [usize; 2], at: Option, lo: f64, hi: f64) -> Option> { - let index = self.index.get(operand)?; - let between = self.edges_between(operand, faces); - if between.len() > 4096 { - return None; - } - let ends: Vec<(Option, Option)> = - between.iter().map(|e| index.bounds.get(*e).map_or((None, None), |(_, front, back)| (*front, *back))).collect(); - // With `at`: the edges reached from it through shared vertices. - let mut chained = vec![at.is_none(); between.len()]; - let mut reached: Vec = at.into_iter().collect(); - while let Some(p) = reached.pop() { - for (k, (front, back)) in ends.iter().enumerate() { - if !chained[k] && (*front == Some(p) || *back == Some(p)) { - chained[k] = true; - reached.extend(if *front == Some(p) { *back } else { *front }); - } - } - } - let height = |v: Option| v.and_then(|v| index.points.get(v)).map(|p| self.plane.height(*p)); - let mut over = between.iter().zip(&ends).zip(chained).filter_map(|((e, (front, back)), chained)| { - let (a, b) = (height(*front)?, height(*back)?); - (chained && a.min(b) <= lo + self.tol && a.max(b) >= hi - self.tol).then_some(*e) - }); - match (over.next(), over.next()) { - (Some(edge), None) => Some(vec![EdgeOrigin::Edge { operand, edge }]), - _ => None, - } - } - - /// The origins of the edge between walls over one segment stacked at a level (tagged `t1` - /// below, `t2` above): within one wall (none), along the operand's edge between two of its - /// walls, or where two operands' walls meet. - fn stacked(&self, t1: Tag, t2: Tag) -> Option> { - let (p, q) = (Self::wall(t1)?, Self::wall(t2)?); - if p == q { - return Some(Vec::new()); - } - if t1.operand != t2.operand { - return Some(vec![EdgeOrigin::meet(p, q)]); - } - // An edge across the direction at a level: the levels cannot tell edges apart here. - self.one_edge(t1.operand, [t1.wall?, t2.wall?]) - } - - /// The operand's edge between the faces `faces`, when it has exactly one. - fn one_edge(&self, operand: usize, faces: [usize; 2]) -> Option> { - match self.edges_between(operand, faces) { - [edge] => Some(vec![EdgeOrigin::Edge { operand, edge: *edge }]), - _ => None, - } - } - - /// Faces and edges of a piece `crate::extrude` built from a section of one region through - /// `layers` (see [`Built::Extruded`]). Its history says which faces are walls over which - /// segment (numbered over the region's loops in order) and which are its caps; the start - /// cap's wires run over the segments in loop order (as the extrude builds them), so the - /// vertex after each wire edge is where one segment runs into the next, or splits. A wall - /// through several layers is made from the wall each layer's segment was read beside, and - /// an edge between two walls from the operand edges there in each layer. - #[allow(clippy::type_complexity)] - fn extruded( - &self, - caps: &[Cap], - body: &Body, - layers: &[(Section, f64, f64)], - ) -> Option<(Vec<(BTreeSet, bool)>, HashMap>)> { - let h = body.history()?; - let ((first, lo, _), (last, _, hi)) = (layers.first()?, layers.last()?); - let (lo, hi) = (*lo, *hi); - let tags: Vec> = layers.iter().map(|(section, ..)| section.segments().1).collect(); - let count = tags.first()?.len(); - if tags.iter().any(|t| t.len() != count) { - return None; - } - let tag = |layer: usize, segment: usize| tags.get(layer).and_then(|t| t.get(segment)).copied(); - let tops = [self.cap_origins(caps, first, lo, false), self.cap_origins(caps, last, hi, true)]; - let kinds: Vec = h - .faces - .iter() - .map(|f| match f.origins.as_slice() { - [FaceOrigin::Profile { segment }] => (*segment < count).then_some(Kind::Wall(*segment)), - [FaceOrigin::Cap { end }] => Some(Kind::Cap(usize::from(*end))), - _ => None, - }) - .collect::>()?; - let faces = kinds - .iter() - .map(|k| match *k { - Kind::Wall(segment) => { - let walls = (0..layers.len()).map(|layer| Self::wall(tag(layer, segment)?)).collect::>>()?; - let whole = match layers { - [(_, lo, hi)] => self.whole(caps, tag(0, segment)?, *lo, *hi), - _ => false, - }; - Some((walls, whole)) - } - Kind::Cap(end) => Some(tops.get(end).filter(|o| !o.is_empty())?.clone()).map(|o| (o, false)), - }) - .collect::>>()?; - let (edges, bounds) = edge_order(body.solid.face_iter()); - let position: HashMap = edges.iter().enumerate().map(|(i, e)| (e.id(), i)).collect(); - // The segment of the wall beside an edge of the start cap. - let segment_of = |e: &mt::Edge| -> Option { - bounds.get(*position.get(&e.id())?)?.iter().find_map(|f| match h.faces.get(*f)?.origins.as_slice() { - [FaceOrigin::Profile { segment }] => Some(*segment), - _ => None, - }) - }; - let start = kinds.iter().position(|k| matches!(k, Kind::Cap(0)))?; - // At each vertex of the start cap: the segment running into it, the one running out, - // and whether that is one segment the extrude split there. - let mut junctions: HashMap = HashMap::new(); - for w in body.solid.face_iter().nth(start)?.absolute_boundaries() { - let es: Vec = w.edge_iter().cloned().collect(); - let segs: Vec = es.iter().map(segment_of).collect::>()?; - if segs.windows(2).any(|p| p.first() > p.get(1)) { - return None; - } - for (k, e) in es.iter().enumerate() { - let (s, next) = (*segs.get(k)?, *segs.get((k + 1) % segs.len())?); - junctions.insert(e.back().id(), (s, next, s == next && k + 1 != segs.len())); - } - } - let mut origins = HashMap::new(); - for (e, fs) in edges.iter().zip(&bounds) { - let [f, g] = fs.as_slice() else { return None }; - let o = match (kinds.get(*f)?, kinds.get(*g)?) { - (Kind::Wall(segment), Kind::Cap(end)) | (Kind::Cap(end), Kind::Wall(segment)) => { - let layer = if *end == 0 { 0 } else { layers.len() - 1 }; - self.cap_edge(tag(layer, *segment)?, tops.get(*end)?, crate::heal::edge_points(e).get(2).copied()?)? - } - (Kind::Wall(..), Kind::Wall(..)) => { - let (s, next, split) = *[e.absolute_front().id(), e.absolute_back().id()].iter().find_map(|v| junctions.get(v))?; - let mut o = BTreeSet::new(); - for (layer, (_, lo, hi)) in layers.iter().enumerate() { - let (t, u) = (tag(layer, s)?, tag(layer, next)?); - // A segment the extrude split in two runs on through the vertex between. - let (t, u) = if split { (Tag { end: None, ..t }, Tag { start: None, ..t }) } else { (t, u) }; - o.extend(self.junction(t, u, *lo, *hi)?); - } - o.into_iter().collect() - } - _ => return None, - }; - origins.insert(e.id(), o); - } - Some((faces, origins)) - } - - /// Faces and edges of a piece sewn from `specs`: the sewing reports which spec each face was - /// built from. Walls meeting at a vertex of their loop (when two walls meet at both ends, - /// the edge's vertex says which); walls over one segment meeting at a level; walls meeting - /// caps. - #[allow(clippy::type_complexity)] - fn sewn( - &self, - caps: &[Cap], - body: &Body, - specs: &[Spec], - built: &[usize], - ) -> Option<(Vec<(BTreeSet, bool)>, HashMap>)> { - let cap_of: Vec>> = specs - .iter() - .map(|s| match s { - Spec::Cap { section, z, up } => Some(self.cap_origins(caps, section, *z, *up)).filter(|o| !o.is_empty()), - Spec::Wall { .. } => None, - }) - .collect(); - let faces = built - .iter() - .map(|i| match specs.get(*i)? { - Spec::Wall { slabs, .. } => Some((slabs.iter().map(|s| Self::wall(s.tag)).collect::>()?, false)), - Spec::Cap { .. } => cap_of.get(*i)?.clone().map(|o| (o, false)), - }) - .collect::>>()?; - let (edges, bounds) = edge_order(body.solid.face_iter()); - let mut origins = HashMap::new(); - for (e, fs) in edges.iter().zip(&bounds) { - let [f, g] = fs.as_slice() else { return None }; - let (i, j) = (*built.get(*f)?, *built.get(*g)?); - let (x, y) = (specs.get(i)?, specs.get(j)?); - // The edge's levels, lower first, and where it stands in plan. - let (front, back) = (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point())); - let (h1, h2) = (self.plane.height(front), self.plane.height(back)); - let (lo, hi) = (h1.min(h2), h1.max(h2)); - let middle = || crate::heal::edge_points(e).get(2).copied(); - let o = match (x, y) { - (Spec::Wall { .. }, Spec::Cap { .. }) => self.cap_edge(x.end(lo, self.tol)?.tag, cap_of.get(j)?.as_ref()?, middle()?)?, - (Spec::Cap { .. }, Spec::Wall { .. }) => self.cap_edge(y.end(lo, self.tol)?.tag, cap_of.get(i)?.as_ref()?, middle()?)?, - (Spec::Wall { .. }, Spec::Wall { .. }) if hi - lo <= self.tol => { - // One over the other at a level: the lower first. - let (below, above) = match (x.top(lo, self.tol), y.bottom(lo, self.tol)) { - (Some(s), Some(t)) => (s, t), - _ => (y.top(lo, self.tol)?, x.bottom(lo, self.tol)?), - }; - self.stacked(below.tag, above.tag)? - } - (Spec::Wall { .. }, Spec::Wall { .. }) => { - // Side by side within a slab: the vertex the edge stands on (in plan) says - // which way round they meet. - let (s, t) = (x.slab(lo, hi)?, y.slab(lo, hi)?); - let p = self.plane.to_local(front); - let at = |q: &Vec2| p.dist(*q) < self.tol * 10.0; - if s.next == j && at(&s.at) { - self.junction(s.tag, t.tag, lo, hi)? - } else if t.next == i && at(&t.at) { - self.junction(t.tag, s.tag, lo, hi)? - } else { - return None; - } - } - _ => return None, - }; - origins.insert(e.id(), o); - } - Some((faces, origins)) - } -} diff --git a/crates/kernel/src/prism_local.rs b/crates/kernel/src/prism_local.rs deleted file mode 100644 index 8456d4537..000000000 --- a/crates/kernel/src/prism_local.rs +++ /dev/null @@ -1,353 +0,0 @@ -//! Booleans of a prism tool with a target that is a prism along the tool's direction only round -//! the tool: a pocket made deeper in a plate whose rim is chamfered, a ring cut round a -//! counterbored hole in a chamfered disc. The tool's walls lie on the target's there, which the -//! B-rep boolean can't intersect, and the 2D route ([`crate::prism::prism_boolean`]) declines the -//! target for a face far away (the chamfer) that is neither a wall along the direction nor a cap -//! square to it. -//! -//! The target is split by planes into a column round the tool that holds none of those faces; -//! the column takes the exact 2D boolean, and the pieces are glued back along the cut faces, as -//! [`crate::polybool::sliced_planar_boolean`] does for an all-planar tool beside curved faces. -//! The cuts are imprints (no boolean), each placed beside the tool on one of three axes: the -//! tool's direction and two square to it. A cut that leaves every offending face of the middle -//! piece beyond it goes first; otherwise one close beside the tool, which splits them (a -//! chamfer all round a disc is split into two pieces apart, which the next cut leaves out). - -use solidcraft_geom::{Plane, Vec3}; -use truck_modeling as mt; - -use crate::body::Body; -use crate::boolean_record::{self as recorded, Traced}; -use crate::{BoolOp, KernelError, Result}; - -/// Cuts at most, each splitting the middle piece once. -const MAX_CUTS: usize = 6; - -/// Cuts made with half boxes at most (two booleans each, with their retries): an imprint traced -/// wrong across a curved face is rare, and the booleans cost seconds on curved parts. -const MAX_BOX_CUTS: usize = 2; - -/// Operands a piece's history is over: `a`, `b`, then the two half boxes each cut may be made -/// with (dropped from the result, whose faces are none of theirs). -const OPERANDS: usize = 2 + 2 * MAX_CUTS; - -thread_local! { - /// Set while [`local_prism_boolean`] runs: the booleans it makes a cut with (a piece and a - /// half box) take the general path, not this one again. - static RUNNING: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// An extent along each of three axes. -type Extent = [(f64, f64); 3]; - -/// [`crate::prism::prism_boolean`] of `a` and the prism `b`, taken in a column of `a` round `b` -/// (see the module notes). `None` when `b` is not a prism, `a` is one along `b`'s direction -/// already, or no column round `b` is clear of `a`'s other faces: the caller goes on as before. -pub(crate) fn local_prism_boolean(a: &Body, b: &Body, op: BoolOp) -> Option>> { - // A cut or an intersection: what a tool meeting the target's walls fails on. A union (a - // shell's cavity joined with its opening) is left to the general path. - if !matches!(op, BoolOp::Cut | BoolOp::Intersect) || a.face_count() > 4096 || RUNNING.with(std::cell::Cell::get) { - return None; - } - /// Clears the flag however the boolean ends, a caught panic included. - struct Reset; - impl Drop for Reset { - fn drop(&mut self) { - RUNNING.with(|r| r.set(false)); - } - } - RUNNING.with(|r| r.set(true)); - let _reset = Reset; - let d = crate::prism::prism_axis(b)?; - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let frame = Plane::from_normal(Vec3::ZERO, d)?; - let axes = [frame.x, frame.y, d]; - // Extents come from meshes this close to the faces, widened by as much. - let mesh_tol = (size * 1e-3).max(1e-4); - let tool = widened(extent(&b.tessellate(mesh_tol).ok()?.positions, axes)?, mesh_tol); - let gap = size * 1e-4 + 1e-6; - let pieces = survey(a, d, tol, mesh_tol, axes)?.pieces; - if pieces.is_empty() { - return None; - } - // A piece of an offending face within a hair of the tool's box: no column round the tool - // can leave it out, so nothing is cut. - let reach = size * 2e-3 + 2.0 * gap; - if pieces.iter().any(|(_, e)| e.iter().zip(&tool).all(|((c0, c1), (t0, t1))| *c1 > t0 - reach && *c0 < t1 + reach)) { - return None; - } - let run = || -> Result> { - let fail = |m: &str| KernelError::Failed(format!("prism boolean in a column round the tool: {m}")); - let mut middle: Traced = (a.clone(), recorded::kept(a, 0, OPERANDS)); - let mut outside: Vec = Vec::new(); - // The sides already cut (axis, positive side): each is cut once. - let mut cut: Vec<(usize, bool)> = Vec::new(); - let mut box_cuts = 0; - for _ in 0..MAX_CUTS { - let survey = survey(&middle.0, d, tol, mesh_tol, axes).ok_or_else(|| fail("the middle piece"))?; - let off = survey.faces(); - if off.is_empty() { - break; - } - let (k, places, keep_positive) = - next_cut(&off, &tool, &survey.here, &survey.flat, &cut, axes, size, gap).ok_or_else(|| fail("no cut leaves the other faces out"))?; - cut.push((k, !keep_positive)); - let axis = axes[k]; - let (u, w) = (axes[(k + 1) % 3], axes[(k + 2) % 3]); - // The first of the places where the piece splits into parts that add up to it (a - // plane whose section through the piece doesn't close is passed over). The cut's - // half boxes, if it takes them, are operands `slot` and `slot + 1`. - let slot = 2 * cut.len(); - let (away, kept) = places - .iter() - .enumerate() - .find_map(|(i, x)| { - let plane = Plane::new(axis * *x, u, w)?; - let with_boxes = i == 0 && box_cuts < MAX_BOX_CUTS; - // Only a plane across an offending face can be traced wrong (a cone's piece - // meshed past its bounds): the others are taken as they are. - let verify = survey.pieces.iter().any(|(_, e)| e[k].0 < *x && e[k].1 > *x); - let r = split(&middle, &plane, axis, *x, keep_positive, slot, with_boxes, verify)?; - box_cuts += usize::from(r.2); - Some((r.0, r.1)) - }) - .ok_or_else(|| fail("a cut beside the tool"))?; - outside.extend(away); - middle = kept; - } - if !survey(&middle.0, d, tol, mesh_tol, axes).is_some_and(|s| s.pieces.is_empty()) { - return Err(fail("other faces are left round the tool")); - } - let r = match crate::prism::prism_boolean(&middle.0, b, op) { - Some(r) => r?, - None => return Err(fail("the column is not a prism along the tool")), - }; - crate::polybool::reassembled(a, b, op, &middle, r, outside, OPERANDS, &fail) - }; - Some(run()) -} - -/// `piece` split by `plane` (at `x` along `axis`, square to it): the parts away from the tool -/// and the one on its side (positive along `axis` when `keep_positive`), with their histories. -/// An imprint of the plane, taken as it is unless `verify`; else where its parts don't add up to -/// the piece (a plane across a cone can be traced wrong) and `with_boxes`, the piece's intersections with the half boxes -/// either side (the cut's operands `slot` and `slot + 1`), and then whether it took them. `None` -/// when neither adds up. -#[allow(clippy::too_many_arguments)] -fn split( - piece: &Traced, - plane: &Plane, - axis: Vec3, - x: f64, - keep_positive: bool, - slot: usize, - with_boxes: bool, - verify: bool, -) -> Option<(Vec, Traced, bool)> { - if !verify { - let (away, kept) = crate::polybool::split_beside(piece, plane, axis, x, keep_positive)?; - return Some((away, kept, false)); - } - let whole = crate::measure(&piece.0).ok()?.volume; - let adds_up = |away: &[Traced], kept: &Traced| { - let sum: Option = away.iter().chain([kept]).map(|(p, _)| crate::measure(p).ok().map(|m| m.volume)).sum(); - sum.is_some_and(|sum| (sum - whole).abs() <= whole.abs() * 5e-5 + 1e-9) - }; - if let Some((away, kept)) = crate::polybool::split_beside(piece, plane, axis, x, keep_positive) - && adds_up(&away, &kept) - { - return Some((away, kept, false)); - } - if !with_boxes { - return None; - } - let boxes = (crate::ops::half_box(&piece.0, plane, !keep_positive).ok()?, crate::ops::half_box(&piece.0, plane, keep_positive).ok()?); - let (h_away, h_kept) = (recorded::kept(&boxes.0, slot, OPERANDS), recorded::kept(&boxes.1, slot + 1, OPERANDS)); - let away = crate::ops::boolean(&piece.0, &boxes.0, BoolOp::Intersect).ok()?; - let kept = crate::ops::boolean(&piece.0, &boxes.1, BoolOp::Intersect).ok()??; - let away: Vec = away - .into_iter() - .map(|o| { - let h = recorded::of_pair(&o, &piece.1, &h_away); - (o, h) - }) - .collect(); - let kept: Traced = { - let h = recorded::of_pair(&kept, &piece.1, &h_kept); - (kept, h) - }; - adds_up(&away, &kept).then_some((away, kept, true)) -} - -/// The extent of `points` along each of `axes`; `None` for no points. -fn extent(points: &[Vec3], axes: [Vec3; 3]) -> Option { - if points.is_empty() { - return None; - } - let mut e = [(f64::INFINITY, f64::NEG_INFINITY); 3]; - for p in points { - for (slot, axis) in e.iter_mut().zip(axes) { - let t = p.dot(axis); - *slot = (slot.0.min(t), slot.1.max(t)); - } - } - e.iter().all(|(lo, hi)| lo.is_finite() && hi.is_finite()).then_some(e) -} - -/// What a cut is chosen from: a piece's extent (`here`), the mesh triangles of its faces that -/// are neither a wall along the direction nor a plane square to it (the faces that keep it from -/// being a prism along it: each one's index and extent), and its planar faces (unit normal, -/// offset along it) for a cut to keep out of. Extents are widened by the mesh's tolerance. -struct Survey { - here: Extent, - pieces: Vec<(usize, Extent)>, - flat: Vec<(Vec3, f64)>, -} - -impl Survey { - /// The extent of each offending face. - fn faces(&self) -> Vec { - let mut faces: Vec<(usize, Extent)> = Vec::new(); - for (i, e) in &self.pieces { - match faces.iter_mut().find(|(j, _)| j == i) { - Some((_, acc)) => { - for (x, y) in acc.iter_mut().zip(e) { - *x = (x.0.min(y.0), x.1.max(y.1)); - } - } - None => faces.push((*i, *e)), - } - } - faces.into_iter().map(|(_, e)| e).collect() - } -} - -/// [`Survey`] of `body` along `d`, from one mesh of it. `None` when it can't be meshed. -fn survey(body: &Body, d: Vec3, tol: f64, mesh_tol: f64, axes: [Vec3; 3]) -> Option { - let mut work = 262_144usize; - let mut flat = Vec::new(); - let off: Vec = body - .solid - .face_iter() - .map(|f| { - let surface = f.oriented_surface(); - match &surface { - mt::Surface::Plane(p) => { - let n = p.normal(); - let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return true }; - let o = p.origin(); - flat.push((n, n.dot(Vec3::new(o.x, o.y, o.z)))); - let along = n.dot(d).abs(); - // NaN counts as inside, as the comparisons it replaces did. - along.is_nan() || (1e-9..=1.0 - 1e-9).contains(&along) - } - _ => !crate::prism::wall_along(&surface, d, tol, &mut work), - } - }) - .collect(); - let mesh = body.tessellate(mesh_tol).ok()?; - let here = widened(extent(&mesh.positions, axes)?, mesh_tol); - let mut pieces = Vec::new(); - if off.iter().any(|x| *x) { - for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) { - let i = *fi as usize; - if !off.get(i).copied().unwrap_or(false) { - continue; - } - let Some(tri) = mesh.tri(t) else { continue }; - if let Some(e) = extent(&tri, axes) { - pieces.push((i, widened(e, mesh_tol))); - } - } - } - Some(Survey { here, pieces, flat }) -} - -/// `e` grown by `by` each way. -fn widened(mut e: Extent, by: f64) -> Extent { - for (lo, hi) in e.iter_mut() { - *lo -= by; - *hi += by; - } - e -} - -/// The next cut of the middle piece (its extent `here`, its planar faces `flat`): the axis, the -/// place along it and whether the tool's side is the positive one. A cut leaving the most -/// offending faces (`off`) wholly beyond it, on a side not `cut` yet, placed halfway to the nearest of them; failing -/// that, one beside the tool across the most of them (on an axis square to the direction -/// first). `None` when no cut beside the tool has any offending face beyond it. -#[allow(clippy::too_many_arguments)] -fn next_cut( - off: &[Extent], - tool: &Extent, - here: &Extent, - flat: &[(Vec3, f64)], - cut: &[(usize, bool)], - axes: [Vec3; 3], - size: f64, - gap: f64, -) -> Option<(usize, Vec, bool)> { - // Places between `near` (beside the tool) and `far`, best first, out of the planes of the - // piece's faces square to the axis. - let place = |k: usize, near: f64, far: f64| -> Option> { - let axis = axes[k]; - let places: Vec = [0.5, 0.37, 0.63, 0.25, 0.75, 0.1, 0.9] - .iter() - .map(|t| near + (far - near) * t) - .filter(|x| !flat.iter().any(|(n, o)| n.dot(axis).abs() > 1.0 - 1e-9 && (o * n.dot(axis).signum() - x).abs() < gap)) - .collect(); - (!places.is_empty()).then_some(places) - }; - let mut whole: Option<(usize, usize, Vec, bool)> = None; - let mut across: Option<(usize, usize, Vec, bool)> = None; - let beside = size * 2e-3; - for k in [0usize, 1, 2] { - let (t0, t1) = tool[k]; - let (h0, h1) = here[k]; - for positive_side in [true, false] { - if cut.contains(&(k, positive_side)) { - continue; - } - // Past the tool on this side: is there any of the piece to cut away? - let (edge, room) = if positive_side { (t1 + gap, h1 - t1) } else { (t0 - gap, t0 - h0) }; - if room <= 2.0 * gap { - continue; - } - let beyond: Vec = off - .iter() - .filter_map(|e| { - let (c0, c1) = e[k]; - if positive_side { (c0 > edge).then_some(c0) } else { (c1 < edge).then_some(c1) } - }) - .collect(); - if let Some(nearest) = beyond.iter().copied().reduce(if positive_side { f64::min } else { f64::max }) { - let Some(x) = place(k, edge, nearest) else { continue }; - if whole.as_ref().is_none_or(|(_, n, ..)| beyond.len() > *n) { - whole = Some((k, beyond.len(), x, !positive_side)); - } - continue; - } - if k == 2 && across.is_some() { - continue; - } - let near = edge + if positive_side { beside } else { -beside }; - let crossing = off.iter().filter(|e| if positive_side { e[k].1 > near } else { e[k].0 < near }).count(); - let limit = if positive_side { h1 } else { h0 }; - if crossing == 0 { - continue; - } - let Some(x) = place(k, edge, near + (near - edge)) - .map(|p| p.into_iter().filter(|x| if positive_side { *x < limit - gap } else { *x > limit + gap }).collect::>()) - .filter(|p| !p.is_empty()) - else { - continue; - }; - if across.as_ref().is_none_or(|(_, n, ..)| crossing > *n) { - across = Some((k, crossing, x, !positive_side)); - } - } - } - whole.or(across).map(|(k, _, x, keep_positive)| (k, x, keep_positive)) -} diff --git a/crates/kernel/src/prism_measure.rs b/crates/kernel/src/prism_measure.rs index f0cf64f58..3fa704752 100644 --- a/crates/kernel/src/prism_measure.rs +++ b/crates/kernel/src/prism_measure.rs @@ -1,8 +1,15 @@ -//! Independent current-geometry intervals for uniform prisms. -//! These are not mesh measurements or certificates of construction history. -use crate::body::from_p3; -use solidcraft_geom::{Plane, Ring, Seg2, Vec2, Vec3}; -use truck_modeling as mt; +//! Independent current-geometry intervals for uniform prisms, read off the body's schema 4 +//! record. These are not mesh measurements or certificates of construction history. +use crate::prism_curve::{Run, segment}; +use solidcore_record::brep::{Brep, Curve, Loop, Shell, Surface}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::Ring; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::prelude::*; + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} #[derive(Clone, Copy, Debug)] struct Interval { @@ -52,11 +59,8 @@ struct CapLoop { /// Cross-product cancellation belongs to the surface representation, not /// just the later incidence dot product. Reject ill-conditioned plane bases. -fn plane_normal(p: &mt::Plane) -> Option<(Vec3, Vec3)> { - let u = p.u_axis(); - let v = p.v_axis(); - let u = Vec3::new(u.x, u.y, u.z); - let v = Vec3::new(v.x, v.y, v.z); +/// The natural normal of the plane spanned by `u` and `v`, and a bound on its rounding error. +fn plane_normal(u: Vec3, v: Vec3) -> Option<(Vec3, Vec3)> { let cross = u.cross(v); let length = cross.len(); if !length.is_finite() || length <= 1e-6 * u.len() * v.len() { @@ -69,52 +73,77 @@ fn plane_normal(p: &mt::Plane) -> Option<(Vec3, Vec3)> { (ne.x.is_finite() && ne.y.is_finite() && ne.z.is_finite()).then_some((n, ne)) } +/// A planar surface's origin and spanning vectors (as its record holds them). +fn plane_of(s: &Surface) -> Option<(Vec3, Vec3, Vec3)> { + match s { + Surface::Plane { origin, u_axis, v_axis } => Some((v3(*origin), v3(*u_axis), v3(*v_axis))), + Surface::PlaneThrough { origin, u_point, v_point } => { + let o = v3(*origin); + Some((o, v3(*u_point) - o, v3(*v_point) - o)) + } + _ => None, + } +} + +/// `v` (a point when `w` is 1, a direction when 0) mapped by the column-major affine `m`; `None` +/// where the map is not affine there. +fn placed(m: &[[f64; 4]; 4], v: Vec3, w: f64) -> Option { + let c = |k: usize| m[0][k] * v.x + m[1][k] * v.y + m[2][k] * v.z + m[3][k] * w; + (c(3) == w).then(|| Vec3::new(c(0), c(1), c(2))) +} + +/// A revolution of a line: the line's ends, the axis origin and unit axis, the placement. +type Revolved<'a> = (Vec3, Vec3, Vec3, Vec3, &'a [[f64; 4]; 4]); + +fn revolved_line(s: &Surface) -> Option> { + let Surface::PlacedRevolution { profile, origin, axis, matrix, .. } = s else { return None }; + let Curve::Line { start, end } = &**profile else { return None }; + Some((v3(*start), v3(*end), v3(*origin), v3(*axis).normalized()?, matrix)) +} + +/// A spline surface's control net, `(point, weight)` with `[i][j]` i along u, and its knots. +type Net<'a> = (Vec>, &'a [f64], &'a [f64]); + +fn net_of(s: &Surface) -> Option> { + match s { + Surface::Spline { u_knots, v_knots, points } => { + Some((points.iter().map(|r| r.iter().map(|p| (v3(*p), 1.)).collect()).collect(), u_knots, v_knots)) + } + Surface::RationalSpline { u_knots, v_knots, homogeneous } => Some(( + homogeneous.iter().map(|r| r.iter().map(|p| (Vec3::new(p[0] / p[3], p[1] / p[3], p[2] / p[3]), p[3])).collect()).collect(), + u_knots, + v_knots, + )), + _ => None, + } +} + /// A whole positive control-net bound for the wall's projected variation. /// A sampled normal or a vertex-only test is deliberately insufficient. -fn wall_error(surface: &mt::Surface, d: Vec3, height: f64, work: &mut usize) -> Option { - if let mt::Surface::Plane(p) = surface { - let (n, ne) = plane_normal(p)?; +fn wall_error(surface: &Surface, d: Vec3, height: f64, work: &mut usize) -> Option { + if let Some((_, u, v)) = plane_of(surface) { + let (n, ne) = plane_normal(u, v)?; let terms = (n.x * d.x).abs() + (n.y * d.y).abs() + (n.z * d.z).abs(); let error = ne.x * d.x.abs() + ne.y * d.y.abs() + ne.z * d.z.abs() + 1024. * f64::EPSILON * terms; return Some((n.dot(d).abs() + error) * height * 2.); } - if let mt::Surface::RevolutedCurve(p) = surface { - let r = p.entity(); - let mt::Curve::Line(line) = r.entity_curve() else { return None }; - let axis = r.axis(); - let meridian = line.1 - line.0; - let a = Vec3::new(axis.x, axis.y, axis.z).normalized()?; - let m = Vec3::new(meridian.x, meridian.y, meridian.z).normalized()?; - let placed = *p.transform() * mt::Vector4::new(axis.x, axis.y, axis.z, 0.); - if placed.w != 0. { - return None; - } - let pa = Vec3::new(placed.x, placed.y, placed.z).normalized()?; + if let Surface::Cylinder { frame, .. } = surface { + let a = v3(frame.x_axis).cross(v3(frame.y_axis)).normalized()?; + return Some(a.cross(d).len() * height * 4.); + } + if let Some((start, end, _, a, matrix)) = revolved_line(surface) { + let m = (end - start).normalized()?; + let pa = placed(matrix, a, 0.)?.normalized()?; return Some((a.cross(m).len() + pa.cross(d).len()) * height * 4.); } - let (rows, cols) = match surface { - mt::Surface::BSplineSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - mt::Surface::NurbsSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - _ => return None, - }; + let (points, _, _) = net_of(surface)?; + let (rows, cols) = (points.len(), points.first()?.len()); let count = rows.checked_mul(cols)?; - let rectangular = match surface { - mt::Surface::BSplineSurface(s) => s.control_points().iter().all(|r| r.len() == cols), - mt::Surface::NurbsSurface(s) => s.control_points().iter().all(|r| r.len() == cols), - _ => false, - }; - if rows < 2 || cols < 2 || count > 16_384 || !rectangular { + if rows < 2 || cols < 2 || count > 16_384 || !points.iter().all(|r| r.len() == cols) { return None; } *work = work.checked_sub(count.checked_mul(4)?)?; - let points: Vec> = match surface { - mt::Surface::BSplineSurface(s) => s.control_points().iter().map(|r| r.iter().map(|p| (from_p3(*p), 1.)).collect()).collect(), - mt::Surface::NurbsSurface(s) => { - s.control_points().iter().map(|r| r.iter().map(|p| (Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w), p.w)).collect()).collect() - } - _ => return None, - }; - if points.iter().any(|r| r.len() != cols) || points.iter().flatten().any(|(p, w)| !p.is_finite() || !w.is_finite() || *w <= 0.) { + if points.iter().flatten().any(|(p, w)| !p.is_finite() || !w.is_finite() || *w <= 0.) { return None; } let max_w = points.iter().flatten().map(|p| p.1).fold(0., f64::max); @@ -181,16 +210,24 @@ fn segment_same(a: &Seg2, b: &Seg2, tolerance: f64) -> bool { } } -fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, levels: (f64, f64), tol: f64, work: &mut usize) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let cap = crate::prism_curve::segment(edge, plane, tol, work)?; - if let mt::Surface::Plane(p) = surface { - let (n, ne) = plane_normal(p)?; - let origin = from_p3(p.origin()); +/// Does the wall (`surface` over the face's `domain`) carry the cap boundary `cap` (an edge of a +/// cap at level `level`, read in `plane`) between the cap levels `levels`? +fn wall_supports_cap( + surface: &Surface, + domain: &[[f64; 2]; 2], + cap: &[Seg2], + level: f64, + plane: &Plane, + levels: (f64, f64), + tol: f64, + work: &mut usize, +) -> Option { + if let Some((origin, u, v)) = plane_of(surface) { + let (n, ne) = plane_normal(u, v)?; for s in cap { - let Seg2::Line { a, b } = s else { return Some(false) }; + let Seg2::Line { a, b } = *s else { return Some(false) }; for q in [a, b] { - let point = plane.to_world(q) + plane.normal() * plane.height(from_p3(edge.front().point())); + let point = plane.to_world(q) + plane.normal() * level; let delta = point - origin; let error = 1024. * f64::EPSILON * (1. + point.len() + origin.len()) + delta.x.abs() * ne.x + delta.y.abs() * ne.y + delta.z.abs() * ne.z; @@ -201,28 +238,33 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve } return Some(true); } - if let mt::Surface::RevolutedCurve(processor) = surface { - let r = processor.entity(); - let mt::Curve::Line(line) = r.entity_curve() else { return None }; - let o = from_p3(r.origin()); - let axis = r.axis(); - let axis = Vec3::new(axis.x, axis.y, axis.z).normalized()?; - let delta = from_p3(line.0) - o; + let on_circle = |center: Vec2, radius: f64| { + cap.iter().all(|s| matches!(*s, Seg2::Arc { center: c, radius: r, .. } if c.dist(center) + (r - radius).abs() <= tol * 8.)) + }; + let spans = |ha: f64, hb: f64| !(ha.min(hb) > levels.0 + tol * 8. || ha.max(hb) < levels.1 - tol * 8.); + if let Surface::Cylinder { frame, radius } = surface { + let (o, x, y) = (v3(frame.origin), v3(frame.x_axis), v3(frame.y_axis)); + let z = x.cross(y); + // The face's heights along the axis: the rest of the cylinder carries no cap. + let [v0, v1] = domain[1]; + if !spans(plane.height(o + z * v0), plane.height(o + z * v1)) { + return Some(false); + } + if x.dot(plane.normal()).abs() * radius > tol || y.dot(plane.normal()).abs() * radius > tol { + return None; + } + return Some(on_circle(plane.to_local(o), *radius)); + } + if let Some((start, end, o, axis, matrix)) = revolved_line(surface) { + let delta = start - o; let radial = (delta - axis * delta.dot(axis)).len(); let u = axis.any_perp(); let v = axis.cross(u); - let matrix = *processor.transform(); - let place = |p: Vec3, w: f64| { - let q = matrix * mt::Vector4::new(p.x, p.y, p.z, w); - (q.w == w).then_some(Vec3::new(q.x, q.y, q.z)) - }; - let center = plane.to_local(place(o, 1.)?); - let ha = plane.height(place(from_p3(line.0), 1.)?); - let hb = plane.height(place(from_p3(line.1), 1.)?); - if ha.min(hb) > levels.0 + tol * 8. || ha.max(hb) < levels.1 - tol * 8. { + let center = plane.to_local(placed(matrix, o, 1.)?); + if !spans(plane.height(placed(matrix, start, 1.)?), plane.height(placed(matrix, end, 1.)?)) { return Some(false); } - let (pu, pv) = (place(u, 0.)?, place(v, 0.)?); + let (pu, pv) = (placed(matrix, u, 0.)?, placed(matrix, v, 0.)?); let radius = pu.len() * radial; if (pu.len() - pv.len()).abs() * radial > tol || pu.dot(pv).abs() * radial > tol @@ -231,21 +273,12 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve { return None; } - return Some(cap.iter().all(|s| matches!(*s,Seg2::Arc {center:c,radius:r,..} if c.dist(center)+(r-radius).abs()<=tol*8.))); + return Some(on_circle(center, radius)); } - let (rows, cols) = match surface { - mt::Surface::BSplineSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - mt::Surface::NurbsSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - _ => return None, - }; + let (points, u_knots, v_knots) = net_of(surface)?; + let (rows, cols) = (points.len(), points.first()?.len()); *work = work.checked_sub(rows.checked_mul(cols)?.checked_mul(4)?)?; - let at = |i: usize, j: usize| -> Option<(Vec3, f64)> { - match surface { - mt::Surface::BSplineSurface(s) => s.control_points().get(i)?.get(j).map(|p| (from_p3(*p), 1.)), - mt::Surface::NurbsSurface(s) => s.control_points().get(i)?.get(j).map(|p| (Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w), p.w)), - _ => None, - } - }; + let at = |i: usize, j: usize| -> Option<(Vec3, f64)> { points.get(i)?.get(j).copied() }; for transpose in [false, true] { let point = |i, j| if transpose { at(j, i) } else { at(i, j) }; let (groups, length) = if transpose { (cols, rows) } else { (rows, cols) }; @@ -255,23 +288,7 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve if !(2..=4096).contains(&groups) || length != 2 { continue; } - let axial_knots = match surface { - mt::Surface::BSplineSurface(s) => { - if transpose { - s.uknot_vec() - } else { - s.vknot_vec() - } - } - mt::Surface::NurbsSurface(s) => { - if transpose { - s.uknot_vec() - } else { - s.vknot_vec() - } - } - _ => return None, - }; + let axial_knots = if transpose { u_knots } else { v_knots }; if axial_knots.len() != 4 || axial_knots.first() != axial_knots.get(1) || axial_knots.get(2) != axial_knots.last() @@ -286,7 +303,7 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve let (base, w) = point(i, 0)?; let h0 = plane.height(base); let h1 = plane.height(point(i, 1)?.0); - if h0.min(h1) > levels.0 + tol * 8. || h0.max(h1) < levels.1 - tol * 8. || increasing.is_some_and(|s| s != (h1 > h0)) { + if !spans(h0, h1) || increasing.is_some_and(|s| s != (h1 > h0)) { valid = false; break; } @@ -299,46 +316,35 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve } } let q = plane.to_world(p); - projected.push(mt::Vector4::new(q.x * w, q.y * w, q.z * w, w)); + projected.push([q.x * w, q.y * w, q.z * w, w]); } if !valid { continue; } - let knots = match surface { - mt::Surface::BSplineSurface(s) => { - if transpose { - s.vknot_vec() - } else { - s.uknot_vec() - } - } - mt::Surface::NurbsSurface(s) => { - if transpose { - s.vknot_vec() - } else { - s.uknot_vec() - } - } - _ => return None, - }; + let knots = if transpose { v_knots } else { u_knots }; if knots.len() > 8192 { return None; } *work = work.checked_sub(knots.len())?; - let c = mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::try_new(knots.clone(), projected).ok()?)); - let (a, b) = c.range_tuple(); - let support = mt::Edge::new(&mt::Vertex::new(c.subs(a)), &mt::Vertex::new(c.subs(b)), c); - let Some(fit) = crate::prism_curve::segment(&support, plane, tol, work) else { + let degree = knots.len().checked_sub(projected.len() + 1)?; + let interval = [*knots.get(degree)?, *knots.get(projected.len())?]; + if !(interval[0] < interval[1]) { + continue; + } + let support = Curve::RationalSpline { knots: knots.to_vec(), homogeneous: projected }; + let eval = CurveEval::new(&support).ok()?; + let ends = [eval.point(interval[0])?, eval.point(interval[1])?]; + let Some(fit) = segment(&Run { curve: &support, interval, forward: true, ends }, plane, tol, work) else { continue; }; let fit_loop = CapLoop { segments: Ring::from(fit.clone()), area: Interval::enclosing(0., 0.)? }; if let Some((center, radius)) = circle(&fit_loop, tol * 8.) - && cap.iter().all(|s| matches!(*s,Seg2::Arc {center:c,radius:r,..} if c.dist(center)+(r-radius).abs()<=tol*8.)) + && on_circle(center, radius) { return Some(true); } let same = loops_same( - &CapLoop { segments: Ring::from(cap.clone()), area: Interval::enclosing(0., 0.)? }, + &CapLoop { segments: Ring::from(cap.to_vec()), area: Interval::enclosing(0., 0.)? }, &CapLoop { segments: Ring::from(fit), area: Interval::enclosing(0., 0.)? }, tol * 8., work, @@ -399,23 +405,370 @@ struct Certificate { hi: f64, } -fn preflight_body(body: &crate::Body) -> Option<()> { - if body.solid.boundaries().len() != 1 || body.mesh.is_some() { +/// One closed face shell within the budgets: each face's outward side (whether it is its +/// surface's natural normal). +fn preflight(record: &Brep) -> Option> { + let [Shell::Faces { faces, .. }] = record.shells.as_slice() else { return None }; + if record.faces.len() > 16_384 || faces.len() != record.faces.len() { return None; } - let mut faces = 16_384usize; let mut edges = 65_536usize; - for face in body.solid.face_iter() { - faces = faces.checked_sub(1)?; - // Borrow absolute wires: the oriented iterator would clone a hostile - // oversized wire before its edge count has been checked. - for wire in face.absolute_boundaries() { - for _ in wire.edge_iter() { - edges = edges.checked_sub(1)?; + for face in &record.faces { + for lp in &face.loops { + if let Loop::Edges { edges: uses } = lp { + edges = edges.checked_sub(uses.len())?; } } } - Some(()) + let mut outward = vec![None; record.faces.len()]; + for f in faces { + let slot = outward.get_mut(f.face as usize)?; + if slot.is_some() { + return None; + } + *slot = Some(f.forward); + } + outward.into_iter().collect() +} + +/// Face `face`'s edges, each once per use. +fn face_edges(record: &Brep, face: usize) -> impl Iterator + '_ { + record + .faces + .get(face) + .into_iter() + .flat_map(|f| &f.loops) + .flat_map(|lp| match lp { + Loop::Edges { edges } => edges.as_slice(), + Loop::Vertex { .. } => &[], + }) + .map(|e| e.edge as usize) +} + +/// The points of face `face`'s vertices (once per edge use). +fn face_points(record: &Brep, face: usize) -> impl Iterator + '_ { + face_edges(record, face) + .filter_map(|e| record.edges.get(e)) + .flat_map(|e| e.vertices) + .filter_map(|v| record.vertices.get(v as usize)) + .map(|v| v3(v.point)) +} + +/// Loop `l` of face `face` as it runs about the face's outward normal (`outward`: the natural +/// one), each edge with its number. +fn loop_runs(record: &Brep, face: usize, l: usize, outward: bool) -> Option)>> { + let Loop::Edges { edges } = record.faces.get(face)?.loops.get(l)? else { return None }; + let mut runs = + edges.iter().map(|e| Some((e.edge as usize, Run::of(record, e.edge as usize, e.forward == outward)?))).collect::>>()?; + if !outward { + runs.reverse(); + } + Some(runs) +} + +fn certificate(record: &Brep, body_size: f64, plane: &Plane, tol: f64) -> Option { + let outward = preflight(record)?; + let d = plane.normal(); + let mut caps = Vec::new(); + let mut walls = Vec::new(); + let mut edge_uses = 65_536usize; + for (fi, face) in record.faces.iter().enumerate() { + for _ in face_edges(record, fi) { + edge_uses = edge_uses.checked_sub(1)?; + } + let out = *outward.get(fi)?; + if let Some((_, u, v)) = plane_of(&face.surface) { + let n = u.cross(v).normalized()? * if out { 1. } else { -1. }; + if n.dot(d).abs() > 1. - 1e-12 { + if n.cross(d).len() * body_size > tol { + return None; + } + // A planar support's parameter origin may be arbitrarily far + // from its trimmed face. Use actual boundary geometry only. + let level = plane.height(face_points(record, fi).next()?); + caps.push((fi, level, n.dot(d) > 0.)); + if caps.len() > 2 { + return None; + } + continue; + } + } + walls.push(fi); + } + if caps.len() != 2 { + return None; + } + let top = *caps.iter().find(|c| c.2)?; + let bottom = *caps.iter().find(|c| !c.2)?; + let height = top.1 - bottom.1; + if height <= tol || !height.is_finite() { + return None; + } + for cap in [top, bottom] { + let (origin, u, v) = plane_of(&record.faces.get(cap.0)?.surface)?; + let (n, ne) = plane_normal(u, v)?; + for point in face_points(record, cap.0) { + let delta = point - origin; + let terms = (delta.x * n.x).abs() + (delta.y * n.y).abs() + (delta.z * n.z).abs(); + let error = 1024. * f64::EPSILON * terms + delta.x.abs() * ne.x + delta.y.abs() * ne.y + delta.z.abs() * ne.z; + if delta.dot(n).abs() + error > tol * 2. || (plane.height(point) - cap.1).abs() > tol * 2. { + return None; + } + } + } + let mut work = 2_000_000; + let cap_loops = |cap: usize, work: &mut usize| -> Option> { + let out = *outward.get(cap)?; + (0..record.faces.get(cap)?.loops.len()).map(|l| cap_loop(&loop_runs(record, cap, l, out)?, plane, tol, work)).collect() + }; + let loops = cap_loops(top.0, &mut work)?; + let lower = cap_loops(bottom.0, &mut work)?; + if loops.len() != lower.len() || loops.is_empty() || loops.len() > 8192 { + return None; + } + let mut pair_work = 16_000_000; + for a in &loops { + // Bottom cap has the opposite material orientation. + let reverse = CapLoop { segments: a.segments.clone(), area: Interval { lo: -a.area.hi, hi: -a.area.lo } }; + let mut matches = 0usize; + for b in &lower { + if loops_same(&reverse, b, tol * 8., &mut pair_work)? { + matches += 1; + } + } + if matches != 1 { + return None; + } + } + let mut controls = 262_144; + // Include cap fitting, support fitting and the <=8tol support-to-cap + // comparison, not just the control-net's projected ruling variation. + let mut corridor = tol * 16.; + let top_edges: std::collections::BTreeSet = face_edges(record, top.0).collect(); + let bottom_edges: std::collections::BTreeSet = face_edges(record, bottom.0).collect(); + let cap_edges = face_edges(record, top.0).count().checked_add(face_edges(record, bottom.0).count())?; + pair_work = pair_work.checked_sub((65_536 - edge_uses).checked_mul(cap_edges)?)?; + for &wall in &walls { + let face = record.faces.get(wall)?; + let variation = wall_error(&face.surface, d, height, &mut controls)?; + if variation > tol * 8. { + return None; + } + corridor = corridor.max(tol * 16. + variation); + if corridor > tol * 24. { + return None; + } + // Every wall must end on these actual cap wires. This is topology + // correspondence, not nearest geometry or stale face provenance. + let mut upper = 0usize; + let mut lower = 0usize; + for edge in face_edges(record, wall) { + let run = Run::of(record, edge, true)?; + let (on_top, on_bottom) = (top_edges.contains(&edge), bottom_edges.contains(&edge)); + if on_top || on_bottom { + let cap = segment(&run, plane, tol, &mut work)?; + if !wall_supports_cap(&face.surface, &face.domain, &cap, plane.height(run.ends[0]), plane, (bottom.1, top.1), tol, &mut work)? { + return None; + } + if on_top { + upper += 1; + } else { + lower += 1; + } + continue; + } + if !matches!(run.curve, Curve::Line { .. }) { + return None; + } + let eval = CurveEval::new(run.curve).ok()?; + let (p, q) = (eval.point(run.interval[0])?, eval.point(run.interval[1])?); + if p.dist(run.ends[0]) > tol || q.dist(run.ends[1]) > tol { + return None; + } + let delta = q - p; + if delta.cross(d).len() > corridor || delta.dot(d).abs() < height - tol * 8. { + return None; + } + } + if upper == 0 || upper != lower { + return None; + } + } + let mut area = Interval::enclosing(0., 0.)?; + let mut length = 0.; + let mut count = 0usize; + for lp in &loops { + area = area.add(lp.area)?; + for edge in &lp.segments { + length += edge.length(); + count = count.checked_add(1)?; + } + } + if count > 8192 || area.lo <= 0. { + return None; + } + separated_material(&loops, corridor * 16., &mut pair_work)?; + // Each boundary's monotone radial/linear corridor contributes at most a + // two-sided strip plus four endpoint disks. Unknown intersecting or + // touching corridors will be refused by the separation check below. + let strip = 2. * length * corridor + 4. * std::f64::consts::PI * count as f64 * corridor * corridor; + // Each cap's vertices are within 2tol and its whole rational edge + // control heights within another tol; include both cap corridors. + let h_error = tol * 8.; + if area.lo <= strip || height <= h_error { + return None; + } + let lo = (area.lo - strip) * (height - h_error); + let hi = (area.hi + strip) * (height + h_error); + let volume = Interval::enclosing((lo + hi) * 0.5, (hi - lo) * 0.5)?; + if volume.lo <= 0. || volume.hi - volume.lo > 0.001 { + return None; + } + Some(Certificate { loops, volume, lo: bottom.1, hi: top.1 }) +} + +/// Independently prove equality of the supported current uniform prisms. +/// `None` means unproved, including budget exhaustion; it never grants a copy. +pub fn certified_prism_equivalent(a: &crate::Body, b: &crate::Body) -> crate::Result> { + crate::guard("certified prism comparison", || { + if a.is_mesh() || b.is_mesh() || !a.size().is_finite() || !b.size().is_finite() { + return Ok(None); + } + let (ra, rb) = (crate::native::brep_record(a)?, crate::native::brep_record(b)?); + Ok(equivalent(&ra, a.size(), &rb, b.size())) + }) +} + +/// A uniform prism along a plane's normal, read off a body's record: its levels above the plane +/// and its section in the plane's coordinates. +#[derive(Clone, Debug, PartialEq)] +pub struct PrismSection { + /// The levels of its bottom and its top cap above the plane (`lo < hi`). + pub lo: f64, + pub hi: f64, + /// Its section, exact: lines and arcs, the outer loop counter-clockwise, the holes clockwise. + pub region: solidcore_record::Region2, + /// How far the levels may be off the body's caps (the caps' vertices lie within it of them). + pub tolerance: f64, +} + +/// The uniform prism `body` is along `plane`'s normal, when its record proves it one: two caps +/// square to the normal, every other face a wall running straight between them along the +/// normal and standing on both caps' edges, the two caps one section (see [`certified_prism_equivalent`] +/// for the profiles it proves: a convex straight outline or a circle, with separate round +/// holes). The body's current geometry, not how it was made: a tool trimmed by a boolean that +/// left it a prism is one. `None` when that is not proved. +pub fn certified_prism_section(body: &crate::Body, plane: &Plane) -> crate::Result> { + crate::guard("certified prism section", || { + if body.is_mesh() || !body.size().is_finite() { + return Ok(None); + } + let record = crate::native::brep_record(body)?; + let tol = body.size().max(1.) * 1e-10; + let Some(c) = certificate(&record, body.size(), plane, tol) else { return Ok(None) }; + let mut outer = None; + let mut holes = Vec::new(); + for lp in c.loops { + let positive = lp.area.lo > 0.; + let lp = solidcore_record::Loop2 { segs: lp.segments.into_vec() }; + if positive { + if outer.replace(lp).is_some() { + return Ok(None); + } + } else { + holes.push(lp); + } + } + let Some(outer) = outer else { return Ok(None) }; + // The caps' vertices are within twice the tolerance of their levels (`certificate`), and + // the levels are worked out from the plane's origin. + let tolerance = 2. * tol + 128. * f64::EPSILON * (plane.origin.len() + c.lo.abs() + c.hi.abs()).max(1.); + Ok(Some(PrismSection { lo: c.lo, hi: c.hi, region: solidcore_record::Region2 { outer, holes }, tolerance })) + }) +} + +/// [`certified_prism_equivalent`] of the records `a` and `b` of bodies of sizes `size_a` and +/// `size_b`. +fn equivalent(a: &Brep, size_a: f64, b: &Brep, size_b: f64) -> Option { + let outward = preflight(a)?; + preflight(b)?; + let size = size_a.max(size_b).max(1.); + let tol = size * 1e-10; + let identity_tol = size * 1e-7; + let origin = v3(a.vertices.first()?.point); + let mut candidates = Vec::new(); + for (face, out) in a.faces.iter().zip(&outward) { + if let Some((_, u, v)) = plane_of(&face.surface) { + let n = u.cross(v).normalized()? * if *out { 1. } else { -1. }; + if !candidates.iter().any(|d: &Vec3| d.dot(n).abs() > 1. - 1e-12) { + candidates.push(n); + if candidates.len() == 8 { + break; + } + } + } + } + for d in candidates { + let plane = Plane::from_normal(origin, d)?; + let Some(ca) = certificate(a, size_a, &plane, tol) else { continue }; + let Some(cb) = certificate(b, size_b, &plane, tol) else { continue }; + if (ca.lo - cb.lo).abs() > identity_tol || (ca.hi - cb.hi).abs() > identity_tol || ca.loops.len() != cb.loops.len() { + return Some(false); + } + let mut work = 16_000_000; + let mut used = vec![false; cb.loops.len()]; + for lp in &ca.loops { + let mut matched = None; + for (i, other) in cb.loops.iter().enumerate() { + if !used.get(i).copied()? && loops_same(lp, other, identity_tol, &mut work)? { + if matched.is_some() { + return None; + } + matched = Some(i); + } + } + let Some(i) = matched else { return Some(false) }; + *used.get_mut(i)? = true; + } + let delta = (ca.volume.hi - cb.volume.lo).abs().max((cb.volume.hi - ca.volume.lo).abs()); + return Some(delta <= 1e-5 * (1. + ca.volume.lo.abs())); + } + None +} + +/// A cap's loop from its edges in order (each with its edge number), certified segment by +/// segment, with the interval of its signed area. +fn cap_loop(runs: &[(usize, Run)], plane: &Plane, tolerance: f64, work: &mut usize) -> Option { + let mut segments = Vec::new(); + let mut area = Interval::enclosing(0., 0.)?; + let mut ids = std::collections::HashSet::new(); + for (id, run) in runs { + if !ids.insert(*id) { + return None; + } + let certified = segment(run, plane, tolerance, work)?; + if segments.len().checked_add(certified.len())? > 8192 { + return None; + } + for segment in &certified { + area = area.add(green_interval(segment, tolerance)?)?; + } + segments.extend(certified); + } + // The edges run end to end round the loop. + let closed = runs.iter().zip(runs.iter().cycle().skip(1)).all(|((_, a), (_, b))| a.ends[1].dist(b.ends[0]) <= 2. * tolerance); + if segments.is_empty() || !closed { + return None; + } + // Curve endpoints already agree with actual shared vertices in the + // whole-span proof. Check the fitted representation's continuity too. + let segments = Ring::new(segments); + for (a, b) in segments.edges() { + if a.end().dist(b.start()) > 2. * tolerance { + return None; + } + } + Some(CapLoop { segments, area }) } /// Initial material scope: a convex straight outer or a circle, with separated @@ -493,264 +846,13 @@ fn separated_material(loops: &[CapLoop], clearance: f64, work: &mut usize) -> Op Some(()) } -fn certificate(body: &crate::Body, plane: &Plane, tol: f64) -> Option { - preflight_body(body)?; - let d = plane.normal(); - let body_size = body.size(); - let mut remaining = 16_384usize; - let mut caps = Vec::new(); - let mut walls = Vec::new(); - let mut edge_uses = 65_536usize; - for face in body.solid.face_iter() { - remaining = remaining.checked_sub(1)?; - for _ in face.edge_iter() { - edge_uses = edge_uses.checked_sub(1)?; - } - let surface = face.oriented_surface(); - if let mt::Surface::Plane(p) = &surface { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - if n.dot(d).abs() > 1. - 1e-12 { - if n.cross(d).len() * body_size > tol { - return None; - } - // A planar support's parameter origin may be arbitrarily far - // from its trimmed face. Use actual boundary geometry only. - let level = plane.height(from_p3(face.vertex_iter().next()?.point())); - caps.push((face, level, n.dot(d) > 0.)); - if caps.len() > 2 { - return None; - } - continue; - } - } - walls.push((face, surface)); - } - if caps.len() != 2 { - return None; - } - let top = caps.iter().find(|c| c.2)?; - let bottom = caps.iter().find(|c| !c.2)?; - let height = top.1 - bottom.1; - if height <= tol || !height.is_finite() { - return None; - } - for cap in [top, bottom] { - let mt::Surface::Plane(support) = cap.0.oriented_surface() else { - return None; - }; - let origin = from_p3(support.origin()); - let (n, ne) = plane_normal(&support)?; - for vertex in cap.0.vertex_iter() { - let point = from_p3(vertex.point()); - let delta = point - origin; - let terms = (delta.x * n.x).abs() + (delta.y * n.y).abs() + (delta.z * n.z).abs(); - let error = 1024. * f64::EPSILON * terms + delta.x.abs() * ne.x + delta.y.abs() * ne.y + delta.z.abs() * ne.z; - if delta.dot(n).abs() + error > tol * 2. || (plane.height(point) - cap.1).abs() > tol * 2. { - return None; - } - } - } - let mut work = 2_000_000; - let loops = top.0.boundaries().iter().map(|w| cap_loop(w, plane, tol, &mut work)).collect::>>()?; - let lower = bottom.0.boundaries().iter().map(|w| cap_loop(w, plane, tol, &mut work)).collect::>>()?; - if loops.len() != lower.len() || loops.is_empty() || loops.len() > 8192 { - return None; - } - let mut pair_work = 16_000_000; - for a in &loops { - // Bottom cap has the opposite material orientation. - let reverse = CapLoop { segments: a.segments.clone(), area: Interval { lo: -a.area.hi, hi: -a.area.lo } }; - let mut matches = 0usize; - for b in &lower { - if loops_same(&reverse, b, tol * 8., &mut pair_work)? { - matches += 1; - } - } - if matches != 1 { - return None; - } - } - let mut controls = 262_144; - // Include cap fitting, support fitting and the <=8tol support-to-cap - // comparison, not just the control-net's projected ruling variation. - let mut corridor = tol * 16.; - let cap_edges = top.0.edge_iter().count().checked_add(bottom.0.edge_iter().count())?; - pair_work = pair_work.checked_sub((65_536 - edge_uses).checked_mul(cap_edges)?)?; - for (face, surface) in &walls { - let variation = wall_error(surface, d, height, &mut controls)?; - if variation > tol * 8. { - return None; - } - corridor = corridor.max(tol * 16. + variation); - if corridor > tol * 24. { - return None; - } - // Every wall must end on these actual cap wires. This is topology - // correspondence, not nearest geometry or stale face provenance. - let mut upper = 0usize; - let mut lower = 0usize; - for edge in face.edge_iter() { - if top.0.edge_iter().any(|e| e.id() == edge.id()) { - if !wall_supports_cap(surface, &edge, plane, (bottom.1, top.1), tol, &mut work)? { - return None; - } - upper += 1; - continue; - } - if bottom.0.edge_iter().any(|e| e.id() == edge.id()) { - if !wall_supports_cap(surface, &edge, plane, (bottom.1, top.1), tol, &mut work)? { - return None; - } - lower += 1; - continue; - } - let mt::Curve::Line(line) = edge.curve() else { return None }; - if from_p3(line.0).dist(from_p3(edge.absolute_front().point())) > tol || from_p3(line.1).dist(from_p3(edge.absolute_back().point())) > tol - { - return None; - } - let delta = from_p3(line.1) - from_p3(line.0); - if delta.cross(d).len() > corridor || delta.dot(d).abs() < height - tol * 8. { - return None; - } - } - if upper == 0 || upper != lower { - return None; - } - } - let mut area = Interval::enclosing(0., 0.)?; - let mut length = 0.; - let mut count = 0usize; - for lp in &loops { - area = area.add(lp.area)?; - for edge in &lp.segments { - length += edge.length(); - count = count.checked_add(1)?; - } - } - if count > 8192 || area.lo <= 0. { - return None; - } - separated_material(&loops, corridor * 16., &mut pair_work)?; - // Each boundary's monotone radial/linear corridor contributes at most a - // two-sided strip plus four endpoint disks. Unknown intersecting or - // touching corridors will be refused by the separation check below. - let strip = 2. * length * corridor + 4. * std::f64::consts::PI * count as f64 * corridor * corridor; - // Each cap's vertices are within 2tol and its whole rational edge - // control heights within another tol; include both cap corridors. - let h_error = tol * 8.; - if area.lo <= strip || height <= h_error { - return None; - } - let lo = (area.lo - strip) * (height - h_error); - let hi = (area.hi + strip) * (height + h_error); - let volume = Interval::enclosing((lo + hi) * 0.5, (hi - lo) * 0.5)?; - if volume.lo <= 0. || volume.hi - volume.lo > 0.001 { - return None; - } - Some(Certificate { loops, volume, lo: bottom.1, hi: top.1 }) -} - -/// Independently prove equality of the supported current uniform prisms. -/// `None` means unproved, including budget exhaustion; it never grants a copy. -pub fn certified_prism_equivalent(a: &crate::Body, b: &crate::Body) -> crate::Result> { - crate::guard("certified prism comparison", || { - let result = (|| { - preflight_body(a)?; - preflight_body(b)?; - if !a.size().is_finite() || !b.size().is_finite() { - return None; - } - let size = a.size().max(b.size()).max(1.); - let tol = size * 1e-10; - let identity_tol = size * 1e-7; - let origin = a.solid.vertex_iter().next().map(|v| from_p3(v.point()))?; - let mut candidates = Vec::new(); - let mut remaining = 16_384usize; - for f in a.solid.face_iter() { - remaining = remaining.checked_sub(1)?; - if let mt::Surface::Plane(p) = f.oriented_surface() { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - if !candidates.iter().any(|d: &Vec3| d.dot(n).abs() > 1. - 1e-12) { - candidates.push(n); - if candidates.len() == 8 { - break; - } - } - } - } - for d in candidates { - let plane = Plane::from_normal(origin, d)?; - let Some(ca) = certificate(a, &plane, tol) else { continue }; - let Some(cb) = certificate(b, &plane, tol) else { continue }; - if (ca.lo - cb.lo).abs() > identity_tol || (ca.hi - cb.hi).abs() > identity_tol || ca.loops.len() != cb.loops.len() { - return Some(false); - } - let mut work = 16_000_000; - let mut used = vec![false; cb.loops.len()]; - for lp in &ca.loops { - let mut matched = None; - for (i, other) in cb.loops.iter().enumerate() { - if !used.get(i).copied()? && loops_same(lp, other, identity_tol, &mut work)? { - if matched.is_some() { - return None; - } - matched = Some(i); - } - } - let Some(i) = matched else { return Some(false) }; - *used.get_mut(i)? = true; - } - let delta = (ca.volume.hi - cb.volume.lo).abs().max((cb.volume.hi - ca.volume.lo).abs()); - return Some(delta <= 1e-5 * (1. + ca.volume.lo.abs())); - } - None - })(); - Ok(result) - }) -} - -fn cap_loop(wire: &mt::Wire, plane: &Plane, tolerance: f64, work: &mut usize) -> Option { - let mut segments = Vec::new(); - let mut area = Interval::enclosing(0., 0.)?; - let mut ids = std::collections::HashSet::new(); - for edge in wire.edge_iter() { - if !ids.insert(edge.id()) { - return None; - } - let certified = crate::prism_curve::segment(edge, plane, tolerance, work)?; - if segments.len().checked_add(certified.len())? > 8192 { - return None; - } - for segment in &certified { - area = area.add(green_interval(segment, tolerance)?)?; - } - segments.extend(certified); - } - if segments.is_empty() || !wire.is_closed() { - return None; - } - // Curve endpoints already agree with actual shared vertices in the - // whole-span proof. Check the fitted representation's continuity too. - let segments = Ring::new(segments); - for (a, b) in segments.edges() { - if a.end().dist(b.start()) > 2. * tolerance { - return None; - } - } - Some(CapLoop { segments, area }) -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { use super::*; - use mt::builder; fn drilled(radius: f64, shift: f64) -> crate::Body { - use solidcraft_geom::{Loop2, Region2}; + use solidcore_record::{Loop2, Region2}; let region = Region2 { outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]), holes: vec![Loop2::circle(Vec2::new(10. + shift, 10.), radius)], @@ -758,6 +860,44 @@ mod tests { crate::extrude(&Plane::XY, &[region], 0., 10.).unwrap().remove(0) } + fn record(b: &crate::Body) -> Brep { + crate::native::brep_record(b).unwrap() + } + + fn cert(b: &crate::Body, tol: f64) -> Option { + certificate(&record(b), b.size(), &Plane::XY, tol) + } + + /// The first face of `r` not on a plane. + fn curved(r: &Brep) -> usize { + r.faces.iter().position(|f| plane_of(&f.surface).is_none()).unwrap() + } + + /// A 10 x 10 tool from z = 0 cut by a pin of radius 2 standing through it, joined to a plate + /// at z 1 ... 2 (a To Object tool trimmed by its curved target): the lump under the plate is + /// a prism from 0 to 1 whose section is the square less the pin's circle, 100 - 4π; the lump + /// above it steps (the pin stands up through it) and is no prism. + #[test] + fn a_trimmed_tool_reads_as_the_prism_of_its_current_section() { + use solidcore_record::{Loop2, Region2}; + let pin = crate::cylinder(Vec3::new(25., 25., 0.), Vec3::Z, 2., 20.).unwrap(); + let stop = crate::box_solid(Vec3::new(19., 19., 1.), Vec3::new(31., 31., 2.)).unwrap(); + let roof = crate::boolean(&pin, &stop, crate::BoolOp::Union).unwrap().unwrap(); + let square = + Region2 { outer: Loop2::polygon(&[Vec2::new(20., 20.), Vec2::new(30., 20.), Vec2::new(30., 30.), Vec2::new(20., 30.)]), holes: vec![] }; + let tool = crate::extrude(&Plane::XY, &[square], 0., 25.).unwrap().remove(0); + let lumps = crate::boolean(&tool, &roof, crate::BoolOp::Cut).unwrap().unwrap().lumps().unwrap(); + assert_eq!(lumps.len(), 2); + let sections: Vec> = lumps.iter().map(|l| certified_prism_section(l, &Plane::XY).unwrap()).collect(); + let lower = sections.iter().flatten().collect::>(); + assert_eq!(lower.len(), 1, "only the lump under the plate is a prism"); + let lower = lower[0]; + assert!(lower.lo.abs() <= lower.tolerance && (lower.hi - 1.).abs() <= lower.tolerance, "{} … {}", lower.lo, lower.hi); + assert_eq!(lower.region.holes.len(), 1); + assert!(lower.region.outer.signed_area() > 0. && lower.region.holes[0].signed_area() < 0.); + assert!((lower.region.area() - (100. - 4. * std::f64::consts::PI)).abs() < 1e-8, "{}", lower.region.area()); + } + #[test] fn actual_drilled_prism_and_step_reopen_are_certified_without_history() { let source = drilled(6., 0.); @@ -766,18 +906,18 @@ mod tests { let copy = &imported.bodies[0].body; let exact = 4000. - 360. * std::f64::consts::PI; for body in [&source, copy] { - let cap = certificate(body, &Plane::XY, 3e-9).expect("actual complete current cap and walls"); + let cap = cert(body, 3e-9).expect("actual complete current cap and walls"); assert!(cap.volume.lo <= exact && cap.volume.hi >= exact, "{:?}, expected {exact}", cap.volume); assert!(cap.volume.hi - cap.volume.lo <= 0.001); } assert_eq!(certified_prism_equivalent(&source, copy).unwrap(), Some(true)); let wider = drilled(6.0001, 0.); - let a = certificate(&source, &Plane::XY, 3e-9).unwrap(); - let b = certificate(&wider, &Plane::XY, 3e-9).unwrap(); + let a = cert(&source, 3e-9).unwrap(); + let b = cert(&wider, 3e-9).unwrap(); assert!(a.volume.lo - b.volume.hi > 1e-5 * (1. + a.volume.hi)); assert_eq!(certified_prism_equivalent(&source, &wider).unwrap(), Some(false)); let shifted = drilled(6., 0.0001); - let same_volume = certificate(&shifted, &Plane::XY, 3e-9).unwrap(); + let same_volume = cert(&shifted, 3e-9).unwrap(); assert!(same_volume.volume.lo <= exact && same_volume.volume.hi >= exact); assert_eq!(certified_prism_equivalent(&source, &shifted).unwrap(), Some(false)); assert_eq!(crate::step_export(&[&source], "source").unwrap(), before); @@ -785,15 +925,14 @@ mod tests { #[test] fn poorly_conditioned_plane_walls_do_not_get_certificates() { - let origin = mt::Point3::new(0., 0., 0.); - let u = mt::Point3::new(1., 0., 0.); - let v = mt::Point3::new(1., 0., 1e-9); - let surface = mt::Surface::Plane(mt::Plane::new(origin, u, v)); - let edge = builder::line(&mt::Vertex::new(origin), &mt::Vertex::new(u)); + let surface = Surface::Plane { origin: [0., 0., 0.], u_axis: [1., 0., 0.], v_axis: [1., 0., 1e-9] }; + let line = Curve::Line { start: [0., 0., 0.], end: [1., 0., 0.] }; let mut work = 2_000_000; + let cap = + segment(&Run { curve: &line, interval: [0., 1.], forward: true, ends: [Vec3::ZERO, Vec3::X] }, &Plane::XY, 1e-9, &mut work).unwrap(); assert!(wall_error(&surface, Vec3::Z, 10., &mut work).is_none()); - assert!(wall_supports_cap(&surface, &edge, &Plane::XY, (0., 10.), 1e-9, &mut work).is_none()); - let normal = plane_normal(&mt::Plane::new(origin, u, mt::Point3::new(0., 0., 1.))).unwrap(); + assert!(wall_supports_cap(&surface, &[[0., 1.], [0., 1.]], &cap, 0., &Plane::XY, (0., 10.), 1e-9, &mut work).is_none()); + let normal = plane_normal(Vec3::X, Vec3::Z).unwrap(); assert!(normal.0.dist(-Vec3::Y) < 1e-12); assert!(normal.1.len() > 0.); } @@ -807,61 +946,75 @@ mod tests { let saved = crate::step_export(&[&moved], "actual boolean").unwrap(); let imported = crate::step_import(&saved).unwrap(); assert_eq!(certified_prism_equivalent(&moved, &imported.bodies[0].body).unwrap(), Some(true)); - // Preserve every current cap/edge ID while replacing only the curved + // Preserve every current cap/edge while replacing only the curved // wall support with radius five. Topology incidence alone must fail. - let wrong = drilled(5., 0.); - let wrong_surface = wrong.solid.face_iter().find(|f| !matches!(f.surface(), mt::Surface::Plane(_))).unwrap().surface(); - let faces = source - .solid - .face_iter() - .map(|f| { - if matches!(f.surface(), mt::Surface::Plane(_)) { - return f.clone(); - } - let mut face = mt::Face::new(f.absolute_boundaries().clone(), wrong_surface.clone()); - if !f.orientation() { - face.invert(); - } - face + let wrong = record(&drilled(5., 0.)); + let mut invalid = record(&source); + let wall = curved(&invalid); + invalid.faces[wall].surface = wrong.faces[curved(&wrong)].surface.clone(); + assert!(certificate(&invalid, source.size(), &Plane::XY, 3e-9).is_none()); + // The actual wall moved 1000 up: it carries no cap edge at the part's levels. + let actual = record(&source); + let wall = curved(&actual); + let mut shifted = actual.faces[wall].surface.clone(); + match &mut shifted { + Surface::Cylinder { frame, .. } => frame.origin[2] += 1000., + Surface::PlacedRevolution { matrix, .. } => matrix[3][2] += 1000., + Surface::Spline { points, .. } => points.iter_mut().flatten().for_each(|p| p[2] += 1000.), + Surface::RationalSpline { homogeneous, .. } => homogeneous.iter_mut().flatten().for_each(|p| p[2] += 1000. * p[3]), + other => panic!("unexpected wall {other:?}"), + } + let outward = preflight(&actual).unwrap(); + let top = (0..actual.faces.len()) + .find(|&f| { + plane_of(&actual.faces[f].surface) + .is_some_and(|(_, u, v)| u.cross(v).normalized().unwrap().z * if outward[f] { 1. } else { -1. } > 0.9) }) - .collect::>(); - let invalid = crate::Body::new(crate::body::Solid::try_new(vec![faces.into()]).unwrap()).unwrap(); - assert!(certificate(&invalid, &Plane::XY, 3e-9).is_none()); - let actual = source.solid.face_iter().find(|f| !matches!(f.surface(), mt::Surface::Plane(_))).unwrap().surface(); - let shifted = mt::Transformed::transformed(&actual, mt::Matrix4::from_translation(mt::Vector3::new(0., 0., 1000.))); - let top = source.solid.face_iter().find(|f| matches!(f.oriented_surface(),mt::Surface::Plane(p) if p.normal().z>0.9)).unwrap(); - let arc = top.edge_iter().find(|e| !matches!(e.curve(), mt::Curve::Line(_))).unwrap(); - assert_ne!(wall_supports_cap(&shifted, &arc, &Plane::XY, (0., 10.), 3e-9, &mut 2_000_000), Some(true)); + .unwrap(); + let arc = face_edges(&actual, top).find(|e| !matches!(actual.edges[*e].curve, Curve::Line { .. })).unwrap(); + let run = Run::of(&actual, arc, true).unwrap(); + let cap = segment(&run, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); + let domain = actual.faces[wall].domain; + assert_ne!( + wall_supports_cap(&shifted, &domain, &cap, Plane::XY.height(run.ends[0]), &Plane::XY, (0., 10.), 3e-9, &mut 2_000_000), + Some(true) + ); } #[test] fn cap_support_origin_is_not_a_trimmed_face_height() { let source = drilled(6., 0.); - let faces = source - .solid - .face_iter() - .map(|f| { - let mt::Surface::Plane(p) = f.surface() else { - return f.clone(); - }; - if p.normal().z.abs() < 0.9 { - return f.clone(); + let original = record(&source); + let mut same = original.clone(); + for face in &mut same.faces { + match &mut face.surface { + Surface::Plane { origin, u_axis, v_axis } if v3(*u_axis).cross(v3(*v_axis)).normalized().unwrap().z.abs() > 0.9 => { + *origin = (v3(*origin) + v3(*u_axis) * 1e8).into(); } - let origin = p.origin() + p.u_axis() * 1e8; - let plane = mt::Surface::Plane(mt::Plane::new(origin, origin + p.u_axis(), origin + p.v_axis())); - let mut face = mt::Face::new(f.absolute_boundaries().clone(), plane); - if !f.orientation() { - face.invert(); + Surface::PlaneThrough { origin, u_point, v_point } => { + let (o, u, v) = (v3(*origin), v3(*u_point), v3(*v_point)); + if (u - o).cross(v - o).normalized().unwrap().z.abs() > 0.9 { + let shift = (u - o) * 1e8; + (*origin, *u_point, *v_point) = ((o + shift).into(), (u + shift).into(), (v + shift).into()); + } } - face - }) - .collect::>(); - let same = crate::Body::new(crate::body::Solid::try_new(vec![faces.into()]).unwrap()).unwrap(); - assert_eq!(certified_prism_equivalent(&source, &same).unwrap(), Some(true)); + _ => {} + } + } + assert_eq!(equivalent(&original, source.size(), &same, source.size()), Some(true)); + // A cap: a face whose plane is square to z (the record's face order is SMLib's, its last + // face may be the hole's wall). + let cap = original + .faces + .iter() + .position(|f| plane_of(&f.surface).is_some_and(|(_, u, v)| u.cross(v).normalized().is_some_and(|n| n.z.abs() > 0.9))) + .unwrap(); + let outward = preflight(&original).unwrap()[cap]; + let runs = loop_runs(&original, cap, 0, outward).unwrap(); assert!( loops_same( - &cap_loop(&source.solid.face_iter().last().unwrap().boundaries()[0], &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), - &cap_loop(&source.solid.face_iter().last().unwrap().boundaries()[0], &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), + &cap_loop(&runs, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), + &cap_loop(&runs, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), 1e-6, &mut 0 ) @@ -875,30 +1028,47 @@ mod tests { let retraced = CapLoop { segments: Ring::from([arc, arc.reversed(), arc]), area: Interval::enclosing(36. * std::f64::consts::PI, 1e-8).unwrap() }; assert!(circle(&retraced, 1e-6).is_none()); - let region = solidcraft_geom::Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]); + let region = solidcore_record::Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]); let doubled = CapLoop { segments: region.segs.iter().chain(®ion.segs).copied().collect(), area: Interval::enclosing(800., 1e-8).unwrap() }; assert!(separated_material(&[doubled], 1e-6, &mut 16_000_000).is_none()); - let thin = crate::box_solid(Vec3::ZERO, Vec3::new(20., 20., 1e-5)).unwrap(); - assert!(certificate(&thin, &Plane::XY, 3e-6).is_none()); + // Thinner than a body's tolerance (2e-5): SMLib refuses it as a solid; built, it gets none. + if let Ok(thin) = crate::box_solid(Vec3::ZERO, Vec3::new(20., 20., 1e-5)) { + assert!(cert(&thin, 3e-6).is_none()); + } } #[test] fn current_rational_circle_green_interval_encloses_independent_area() { let r = 6.; - let vertices = - [mt::Point3::new(r, 0., 0.), mt::Point3::new(0., r, 0.), mt::Point3::new(-r, 0., 0.), mt::Point3::new(0., -r, 0.)].map(builder::vertex); - let mut edges = Vec::new(); - for i in 0..4 { - let angle = (i as f64 + 0.5) * std::f64::consts::FRAC_PI_2; - edges.push(builder::circle_arc(&vertices[i], &vertices[(i + 1) % 4], mt::Point3::new(r * angle.cos(), r * angle.sin(), 0.))); - } - let wire: mt::Wire = edges.into(); - let cap = cap_loop(&wire, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); + let w = std::f64::consts::FRAC_1_SQRT_2; + let corner = |i: usize| { + let a = i as f64 * std::f64::consts::FRAC_PI_2; + Vec3::new(r * a.cos(), r * a.sin(), 0.) + }; + // Four quarter circles as rational quadratic splines. + let curves: Vec = (0..4) + .map(|i| { + let (a, b) = (corner(i), corner(i + 1)); + let apex = a + b; + Curve::RationalSpline { + knots: vec![0., 0., 0., 1., 1., 1.], + homogeneous: vec![[a.x, a.y, 0., 1.], [apex.x * w, apex.y * w, 0., w], [b.x, b.y, 0., 1.]], + } + }) + .collect(); + let runs: Vec<(usize, Run)> = curves + .iter() + .enumerate() + .map(|(i, c)| (i, Run { curve: c, interval: [0., 1.], forward: true, ends: [corner(i), corner(i + 1)] })) + .collect(); + let cap = cap_loop(&runs, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); let exact = std::f64::consts::PI * r * r; assert!(cap.area.lo <= exact && cap.area.hi >= exact, "{:?}", cap.area); assert!((cap.area.hi - cap.area.lo) * 10. < 0.001); assert_eq!(cap.segments.len(), 4); - let reversed = cap_loop(&wire.inverse(), &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); + let back: Vec<(usize, Run)> = + runs.iter().rev().map(|(i, run)| (*i, Run { forward: false, ends: [run.ends[1], run.ends[0]], ..*run })).collect(); + let reversed = cap_loop(&back, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); assert!(reversed.area.lo <= -exact && reversed.area.hi >= -exact); } } diff --git a/crates/kernel/src/prism_spline_tests.rs b/crates/kernel/src/prism_spline_tests.rs deleted file mode 100644 index 6fe0b48a7..000000000 --- a/crates/kernel/src/prism_spline_tests.rs +++ /dev/null @@ -1,87 +0,0 @@ -use super::*; - -/// A rounded square of four quadratic curves (a font's kind) about (20, 15). -fn rounded() -> Region2 { - let p = Vec2::new; - let q = |a: Vec2, apex: Vec2, b: Vec2| Seg2::Conic { a, apex, b, w: 1.0 }; - let segs = vec![ - q(p(10.0, 15.0), p(10.0, 5.0), p(20.0, 5.0)), - q(p(20.0, 5.0), p(30.0, 5.0), p(30.0, 15.0)), - q(p(30.0, 15.0), p(30.0, 25.0), p(20.0, 25.0)), - q(p(20.0, 25.0), p(10.0, 25.0), p(10.0, 15.0)), - ]; - Region2 { outer: Loop2 { segs }, holes: vec![] } -} - -fn block() -> Body { - crate::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 30.0, 10.0)).unwrap() -} - -/// Its free-form faces (the tool's walls kept as the curves they were). -fn spline_faces(b: &Body) -> usize { - b.solid.face_iter().filter(|f| matches!(f.surface(), mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_))).count() -} - -/// A shape of a font's curves engraved into a block is decided in 2D, its walls the exact curves. -#[test] -fn an_engraving_of_quadratic_curves_is_exact_in_2d() { - let region = rounded(); - let area = region.outer.signed_area().abs(); - let tool = crate::extrude(&Plane::XY, std::slice::from_ref(®ion), 9.0, 11.0).unwrap().remove(0); - let out = prism_boolean(&block(), &tool, BoolOp::Cut).expect("the 2D route takes it").unwrap().unwrap(); - assert!(out.validity().is_empty(), "{:?}", out.validity()); - // Half the tool, measured as the result is (meshes of curved faces are off by about 1e-4). - let taken = 12000.0 - crate::measure(&out).unwrap().volume; - let half = crate::measure(&tool).unwrap().volume / 2.0; - assert!((taken - half).abs() < 1e-6 * half && (taken - area).abs() < 2e-4 * area, "{taken} vs {half} ({area})"); - assert_eq!(spline_faces(&out), 4); -} - -/// A shape running off the block's side is cut where its curves exactly cross the side. -#[test] -fn an_engraving_running_off_the_side_ends_on_its_exact_crossings() { - let region = rounded(); - // Moved 14 to the left: the block's side x = 0 cuts its two left curves. - let shift = |s: &Seg2| match *s { - Seg2::Conic { a, apex, b, w } => { - Seg2::Conic { a: a - Vec2::new(14.0, 0.0), apex: apex - Vec2::new(14.0, 0.0), b: b - Vec2::new(14.0, 0.0), w } - } - other => other, - }; - let moved = Region2 { outer: Loop2 { segs: region.outer.segs.iter().map(shift).collect() }, holes: vec![] }; - let tool = crate::extrude(&Plane::XY, std::slice::from_ref(&moved), 9.0, 11.0).unwrap().remove(0); - let out = prism_boolean(&block(), &tool, BoolOp::Cut).expect("the 2D route takes it").unwrap().unwrap(); - assert!(out.validity().is_empty(), "{:?}", out.validity()); - // What the block keeps of the shape: the shape's part at x > 0. - let inside = planar_regions_boolean( - std::slice::from_ref(&moved), - &[Region2 { - outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), Vec2::new(40.0, 30.0), Vec2::new(0.0, 30.0)]), - holes: vec![], - }], - BoolOp::Intersect, - 1e-6, - ) - .unwrap(); - let area: f64 = inside.iter().map(|r| r.outer.signed_area().abs()).sum(); - let taken = 12000.0 - crate::measure(&out).unwrap().volume; - assert!((taken - area).abs() < 2e-4 * area, "{taken} vs {area}"); - assert!(spline_faces(&out) >= 2, "{}", spline_faces(&out)); -} - -/// A tool that misses its target leaves it as it is: the 2D route declines it (the B-rep -/// boolean then reuses the target itself). An engraving taking far less than a ten-thousandth -/// of a large part is a change all the same, and the route keeps it: told from the exact -/// sections, not from volumes measured off meshes, which could not tell it from no change. -#[test] -fn a_tool_that_misses_is_declined_and_a_fine_engraving_is_not() { - let big = crate::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(200.0, 200.0, 10.0)).unwrap(); - let region = rounded(); - let tool = |lo: f64, hi: f64| crate::extrude(&Plane::XY, std::slice::from_ref(®ion), lo, hi).unwrap().remove(0); - assert!(prism_boolean(&big, &tool(10.0, 12.0), BoolOp::Cut).is_none(), "a tool above the part misses it"); - // 0.05 mm deep: 17 mm³ of a 400000 mm³ part. - let out = prism_boolean(&big, &tool(9.95, 11.0), BoolOp::Cut).expect("an engraving is a change").unwrap().unwrap(); - let taken = 400_000.0 - crate::measure(&out).unwrap().volume; - let want = region.outer.signed_area().abs() * 0.05; - assert!((taken - want).abs() < 2e-3 * want, "{taken} vs {want}"); -} diff --git a/crates/kernel/src/profile.rs b/crates/kernel/src/profile.rs index bd40bd499..7f61c7ee7 100644 --- a/crates/kernel/src/profile.rs +++ b/crates/kernel/src/profile.rs @@ -74,8 +74,10 @@ pub fn credit(times: KernelTimes) { }); } -/// Time `f` as `kind` when a capture is running and no timed call is. -pub(crate) fn timed(kind: Kind, f: impl FnOnce() -> T) -> T { +/// Time `f` as `kind` when a capture is running and no timed call is; it is also the +/// profiler's span `name` (category `kernel`) whenever the profiler records. +pub(crate) fn timed(kind: Kind, name: &'static str, f: impl FnOnce() -> T) -> T { + let _span = solidcraft_profile::span("kernel", name); let st = STATE.with(Cell::get); if !st.on || st.busy { return f(); @@ -116,7 +118,7 @@ mod tests { #[test] fn nothing_is_timed_outside_a_capture() { - timed(Kind::Boolean, || spin(2)); + timed(Kind::Boolean, "test", || spin(2)); let ((), t) = capture(|| ()); assert_eq!(t, KernelTimes::default()); } @@ -125,11 +127,11 @@ mod tests { fn only_the_outermost_call_counts() { let started = web_time::Instant::now(); let ((), t) = capture(|| { - timed(Kind::Boolean, || { + timed(Kind::Boolean, "test", || { spin(3); - timed(Kind::Tessellate, || spin(3)); + timed(Kind::Tessellate, "test", || spin(3)); }); - timed(Kind::Tessellate, || spin(2)); + timed(Kind::Tessellate, "test", || spin(2)); }); let elapsed = started.elapsed().as_secs_f64() * 1000.0; assert!(t.boolean_ms >= 6.0 && t.tessellate_ms >= 2.0, "{t:?}"); @@ -145,7 +147,7 @@ mod tests { credit(t); credit(KernelTimes { boolean_ms: f64::NAN, tessellate_ms: -3.0 }); // Inside a timed call it would count twice: it is the call's time already. - timed(Kind::Boolean, || credit(t)); + timed(Kind::Boolean, "test", || credit(t)); }); assert_eq!((got.boolean_ms >= 4.0, got.boolean_ms < 8.0, got.tessellate_ms), (true, true, 1.0), "{got:?}"); } @@ -153,9 +155,9 @@ mod tests { #[test] fn inner_captures_add_to_the_outer_one_and_a_panic_restores_it() { let ((), outer) = capture(|| { - let ((), inner) = capture(|| timed(Kind::Boolean, || spin(2))); + let ((), inner) = capture(|| timed(Kind::Boolean, "test", || spin(2))); assert!(inner.boolean_ms >= 2.0); - let _ = std::panic::catch_unwind(|| capture(|| timed(Kind::Tessellate, || panic!("kernel")))); + let _ = std::panic::catch_unwind(|| capture(|| timed(Kind::Tessellate, "test", || panic!("kernel")))); }); assert!(outer.boolean_ms >= 2.0, "{outer:?}"); let st = STATE.with(Cell::get); @@ -164,15 +166,36 @@ mod tests { #[test] fn a_faceted_boolean_is_boolean_time_and_a_reference_mesh_tessellation() { use crate::{BoolOp, box_solid, faceted_boolean}; - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); - let tool = box_solid(Vec3::new(5.0, 5.0, 5.0), Vec3::new(15.0, 15.0, 15.0)).unwrap().tessellate(0.1).unwrap(); + let tool = box_solid(Vec3::new(5.0, 5.0, 5.0), Vec3::new(15.0, 15.0, 15.0)).unwrap().mesh(&crate::MeshTolerance::chord(0.1)).unwrap(); // The thread groove's route: the faceting it does first is the boolean's time too. let (r, t) = capture(|| faceted_boolean(&a, &tool, BoolOp::Cut, 0.01)); assert!(r.unwrap().is_some()); assert!(t.boolean_ms > 0.0 && t.tessellate_ms == 0.0, "{t:?}"); - let (m, t) = capture(|| a.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE)); + let (m, t) = capture(|| a.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) })); assert!(!m.unwrap().triangles.is_empty()); assert!(t.tessellate_ms > 0.0 && t.boolean_ms == 0.0, "{t:?}"); } + + #[test] + fn kernel_operations_are_profiler_spans_with_smlib_calls_inside() { + use crate::{BoolOp, boolean, box_solid}; + use solidcore_record::Vec3; + solidcraft_profile::set_enabled(true); + let mark = solidcraft_profile::mark(); + let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + let b = box_solid(Vec3::new(5.0, 5.0, 5.0), Vec3::new(15.0, 15.0, 15.0)).unwrap(); + let r = boolean(&a, &b, BoolOp::Cut); + let rep = mark.report(); + let row = |cat: &str, name: &str| rep.rows.iter().find(|r| r.category == cat && r.name == name).copied(); + let k = row("kernel", "boolean").unwrap_or_else(|| panic!("{rep:?}")); + assert!(k.count >= 1 && row("kernel", "box_solid").is_some(), "{rep:?}"); + if r.is_ok() { + // The geometry kernel's calls are children of the boolean: their time is not its self + // time. + let calls: std::time::Duration = rep.rows.iter().filter(|r| r.category == "solidcore").map(|r| r.total).sum(); + assert!(calls > std::time::Duration::ZERO && k.self_time < k.total, "{rep:?}"); + } + } } diff --git a/crates/kernel/src/provenance.rs b/crates/kernel/src/provenance.rs index 844a203d1..c39b7e532 100644 --- a/crates/kernel/src/provenance.rs +++ b/crates/kernel/src/provenance.rs @@ -8,9 +8,11 @@ //! name the same one. Operations that know more (which profile segment a side face sweeps, //! which edge a blend replaces) fill in generated faces' origins themselves. +use solidcraft_geom::prelude::*; use std::collections::BTreeSet; -use solidcraft_geom::{Aabb3, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Aabb3, Mesh}; use crate::Result; use crate::body::Body; @@ -20,13 +22,13 @@ use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History const SAMPLES: usize = 24; /// A face's triangles with their unit normals, and its box. -struct FaceTris { - tris: Vec<([Vec3; 3], Vec3)>, - bounds: Aabb3, - area: f64, +pub(crate) struct FaceTris { + pub(crate) tris: Vec<([Vec3; 3], Vec3)>, + pub(crate) bounds: Aabb3, + pub(crate) area: f64, } -fn face_tris(m: &Mesh) -> Vec { +pub(crate) fn face_tris(m: &Mesh) -> Vec { let n = m.tri_face.iter().copied().max().map(|x| x as usize + 1).unwrap_or(0); let mut out: Vec = (0..n).map(|_| FaceTris { tris: Vec::new(), bounds: Aabb3::EMPTY, area: 0.0 }).collect(); for (t, f) in m.triangles.iter().zip(&m.tri_face) { @@ -40,7 +42,7 @@ fn face_tris(m: &Mesh) -> Vec { out } -fn closest_on_tri(p: Vec3, [a, b, c]: [Vec3; 3]) -> Vec3 { +pub(crate) fn closest_on_tri(p: Vec3, [a, b, c]: [Vec3; 3]) -> Vec3 { let (ab, ac, ap) = (b - a, c - a, p - a); let (d1, d2) = (ab.dot(ap), ac.dot(ap)); if d1 <= 0.0 && d2 <= 0.0 { @@ -96,11 +98,11 @@ pub fn trace(result: &Body, inputs: &[&Body]) -> Result { let size = inputs.iter().map(|b| b.size()).fold(result.size(), f64::max).max(1e-9); let mesh_tol = size * 2e-4; let tol = mesh_tol * 2.0; - let rm = result.tessellate(mesh_tol)?; + let rm = result.mesh(&crate::MeshTolerance::chord(mesh_tol))?; let rfaces = face_tris(&rm); let mut imeshes = Vec::with_capacity(inputs.len()); for b in inputs { - imeshes.push(b.tessellate(mesh_tol)?); + imeshes.push(b.mesh(&crate::MeshTolerance::chord(mesh_tol))?); } let ifaces: Vec> = imeshes.iter().map(face_tris).collect(); // Each result face: the input faces most of its samples lie on. @@ -186,7 +188,7 @@ fn nearest_segment(segs: &[Seg2], pts: &[Vec2]) -> Option { /// caps on the start and end planes, sides by the profile segment they sweep. pub fn extrude_origins(tool: &Body, plane: &Plane, regions: &[Region2]) -> Result> { let size = tool.size().max(1e-9); - let m = tool.tessellate(size * 2e-4)?; + let m = tool.mesh(&crate::MeshTolerance::chord(size * 2e-4))?; let faces = face_tris(&m); let n = plane.normal(); let segs = segments(regions); @@ -216,7 +218,7 @@ pub fn extrude_origins(tool: &Body, plane: &Plane, regions: &[Region2]) -> Resul /// by the profile segment it turns. pub fn revolve_origins(tool: &Body, plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2) -> Result> { let size = tool.size().max(1e-9); - let m = tool.tessellate(size * 2e-4)?; + let m = tool.mesh(&crate::MeshTolerance::chord(size * 2e-4))?; let faces = face_tris(&m); let segs = segments(regions); let o = plane.to_world(axis_origin); @@ -261,8 +263,8 @@ pub fn revolve_origins(tool: &Body, plane: &Plane, regions: &[Region2], axis_ori /// edge indices in `input`'s mesh order): each blend face comes from the edge it lies along. pub fn blend_origins(result: &Body, input: &Body, edges: &[usize], prov: &mut History) -> Result<()> { let size = input.size().max(1e-9); - let rm = result.tessellate(size * 2e-4)?; - let im = input.tessellate(size * 2e-4)?; + let rm = result.mesh(&crate::MeshTolerance::chord(size * 2e-4))?; + let im = input.mesh(&crate::MeshTolerance::chord(size * 2e-4))?; let rfaces = face_tris(&rm); for (fi, fp) in prov.faces.iter_mut().enumerate() { if fp.change != Change::Generated { @@ -288,8 +290,8 @@ pub fn blend_origins(result: &Body, input: &Body, edges: &[usize], prov: &mut Hi pub fn offset_origins(result: &Body, input: &Body, thickness: f64, prov: &mut History) -> Result<()> { let size = input.size().max(1e-9); let tol = size * 4e-4; - let rm = result.tessellate(size * 2e-4)?; - let im = input.tessellate(size * 2e-4)?; + let rm = result.mesh(&crate::MeshTolerance::chord(size * 2e-4))?; + let im = input.mesh(&crate::MeshTolerance::chord(size * 2e-4))?; let rfaces = face_tris(&rm); let ifaces = face_tris(&im); for (fi, fp) in prov.faces.iter_mut().enumerate() { @@ -309,10 +311,13 @@ pub fn offset_origins(result: &Body, input: &Body, thickness: f64, prov: &mut Hi /// Origins of any swept tool's faces (sweep, loft, pipe; extrude and revolve too) from where /// they start: the face lying in the profile's plane is the start cap, a face with an edge in -/// that plane sweeps the profile segment under the edge, and the rest are end caps. +/// that plane sweeps the profile segment under the edge, and the rest are end caps. That holds +/// for a tool whose every wall runs the whole path; one swept piece by piece along its path +/// (SMLib's sweep along lines and arcs, mitred at each corner) has walls starting further on, +/// which only the tool's own history names ([`sweep_origins`]). pub fn swept_origins(tool: &Body, plane: &Plane, regions: &[Region2]) -> Result> { let size = tool.size().max(1e-9); - let m = tool.tessellate(size * 2e-4)?; + let m = tool.mesh(&crate::MeshTolerance::chord(size * 2e-4))?; let faces = face_tris(&m); let segs = segments(regions); let flat = |p: Vec3| plane.height(p).abs() <= size * 1e-6; @@ -339,32 +344,20 @@ pub fn swept_origins(tool: &Body, plane: &Plane, regions: &[Region2]) -> Result< Ok(out) } -/// Origins of a [`crate::sweep_path`] tool's faces. Its walls come in profile order (once for -/// smooth walls, once per station for ruled ones) followed by the start and end caps; checked -/// against the start cap lying in the profile's plane, else found as [`swept_origins`] does. +/// Origins of a [`crate::sweep_path`] tool's faces: the ones the sweep recorded as it built them +/// ([`Body::history`]: the start and end caps, each wall from the profile segment it sweeps, +/// along every piece of the path), the first of each face's; a face the tool names no origin +/// for (or a tool without a history) found as [`swept_origins`] does. pub fn sweep_origins(tool: &Body, plane: &Plane, regions: &[Region2]) -> Result> { - let n = tool.face_count(); - let k = segments(regions).len(); - let size = tool.size().max(1e-9); - if k > 0 && n >= 2 && (n - 2).is_multiple_of(k) { - let m = tool.tessellate(size * 2e-4)?; - let faces = face_tris(&m); - let start_flat = faces.get(n - 2).is_some_and(|f| f.tris.iter().all(|(t, _)| t.iter().all(|p| plane.height(*p).abs() <= size * 1e-6))); - if start_flat { - return Ok((0..n) - .map(|i| { - if i + 2 == n { - FaceOrigin::Cap { end: false } - } else if i + 1 == n { - FaceOrigin::Cap { end: true } - } else { - FaceOrigin::Profile { segment: i % k } - } - }) - .collect()); - } + let recorded: Vec> = match tool.history() { + Some(h) if h.faces.len() == tool.face_count() => h.faces.iter().map(|f| f.origins.first().copied()).collect(), + _ => vec![None; tool.face_count()], + }; + if recorded.iter().all(Option::is_some) { + return Ok(recorded.into_iter().flatten().collect()); } - swept_origins(tool, plane, regions) + let found = swept_origins(tool, plane, regions)?; + Ok(recorded.into_iter().zip(found).map(|(r, f)| r.unwrap_or(f)).collect()) } /// Replace origins on operand `operand` (a tool made by the operation) with that tool's own @@ -385,13 +378,14 @@ pub fn compose(prov: &mut History, operand: usize, tool: &[FaceOrigin]) { #[cfg(test)] mod tests { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; + use solidcraft_geom::prelude::*; use super::{Change, FaceOrigin, trace}; use crate::{BoolOp, boolean, box_solid, cylinder}; fn face_at(b: &crate::Body, p: Vec3) -> usize { - let m = b.tessellate(1e-3).unwrap(); + let m = b.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap(); let mut best = (f64::INFINITY, 0); for (t, f) in m.triangles.iter().zip(&m.tri_face) { let q = m.tri(t).unwrap(); @@ -437,7 +431,7 @@ mod tests { assert_eq!(p.faces[top].origins.len(), 2); } // Edges: the plate's untouched vertical edges come from the plate's edges. - let m = cut.tessellate(1e-3).unwrap(); + let m = cut.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap(); let p = trace(&cut, &[&a, &pin]).unwrap(); let corner = (0..m.edges.len()).find(|i| m.edges[*i].iter().all(|q| q.x.abs() < 1e-9 && q.y.abs() < 1e-9)).unwrap(); assert!(matches!(p.edges[corner].origins[..], [super::EdgeOrigin::Edge { operand: 0, .. }])); @@ -446,7 +440,7 @@ mod tests { #[test] fn provenance_of_sweeps_blends_and_shells() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; use super::{History, blend_origins, compose, extrude_origins, offset_origins, revolve_origins}; let plane = Plane::named("XY").unwrap(); @@ -479,7 +473,7 @@ mod tests { assert_eq!(ro[face_at(&rt, Vec3::new(15.0, 15.0, 0.0))], FaceOrigin::Cap { end: false }); // A fillet: the blend face comes from the edge it replaced. let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); - let bm = b.tessellate(1e-3).unwrap(); + let bm = b.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap(); let e = (0..bm.edges.len()).find(|i| bm.edges[*i].iter().all(|q| (q.y - 30.0).abs() < 1e-9 && (q.z - 20.0).abs() < 1e-9)).unwrap(); let f = crate::fillet(&b, &[Vec3::new(20.0, 30.0, 20.0)], 5.0).unwrap(); let mut p: History = trace(&f, &[&b]).unwrap(); diff --git a/crates/kernel/src/record.rs b/crates/kernel/src/record.rs index f05de1c58..279cf096c 100644 --- a/crates/kernel/src/record.rs +++ b/crates/kernel/src/record.rs @@ -1,23 +1,16 @@ -//! Recording the exact history of the bodies the creation builders make (extrude, revolve, -//! sweeps, lofts, primitives, and the builders that rebuild a body around new faces), by -//! topology identity inside the building call: which face a profile edge was swept into, -//! which edges an operand still owns. Nothing is sampled. -//! -//! Faces our code builds are paired with their provenance as they are made (a [`Side`]); only -//! where truck makes the faces itself (`tsweep`, `rsweep`, `cone`) are they found afterwards, -//! by following each profile edge's column of swept faces ([`follow`]). Profile segments are -//! numbered by [`crate::numbered`]. +//! Recording the exact history of the bodies operations build on the schema 4 record: for each +//! result face, what it is made from (operand faces it is the whole of or a piece of, profile +//! segments, caps, operand edges a blend replaces); for each result edge, the operand edges it is +//! or is a piece of, and otherwise the meeting of the two faces it separates. Indices are the +//! records' canonical ones, the result's and each operand's. Nothing is sampled: the building +//! code says what it built from what. Profile segments are numbered by [`crate::numbered`]. -use std::collections::{BTreeSet, HashMap}; +use std::collections::BTreeSet; -use truck_modeling as mt; +use solidcore_record::brep::Brep; -use crate::Result; -use crate::body::{Body, Solid, edge_order}; -use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History}; - -/// A face as built, with its provenance (`None` where the construction could not be followed). -pub(crate) type Side = (mt::Face, Option); +use crate::body::Body; +use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History, edge_faces}; /// A face made from all of profile segments `numbers` (in any order, repeats allowed). pub(crate) fn profile<'a>(numbers: impl IntoIterator) -> FaceProv { @@ -46,152 +39,51 @@ pub(crate) fn generated(origins: Vec) -> FaceProv { FaceProv { origins, change: Change::Generated } } -/// Result faces that are each a region of input faces, given as the input faces under it and -/// whether it is one input face untouched (`whole`). Kept when whole; Merged with several -/// origins; Split when its one origin lies under other result faces too; Modified otherwise; -/// Generated with no origin. -pub(crate) fn regions(faces: Vec<(BTreeSet, bool)>) -> Vec { - let mut faces: Vec = faces.into_iter().map(|(origins, whole)| region(origins, whole)).collect(); +pub(crate) use solidcore_record::brep::history::mark_shared_split; + +/// The origins of a result edge that is (a piece of, or the moved) edges `edges` of operand +/// `operand`. +pub(crate) fn pieces_of(operand: usize, edges: impl IntoIterator) -> Vec { + let edges: BTreeSet = edges.into_iter().collect(); + edges.into_iter().map(|edge| EdgeOrigin::Edge { operand, edge }).collect() +} + +/// The history over `operands` operands of `result`, whose faces (in its face order) come from +/// `faces` (an operand face shared by several result faces is marked Split), and whose edges come +/// from `edges` (by result edge index) where the building code knows them: an operand edge it +/// kept or re-made ([`pieces_of`]). Every other edge separates two faces that met nowhere before, +/// so it comes from their meeting ([`meeting`]); an operation with no operands (a body built +/// from a sketch) makes every face and edge new, so its edges have no origins. +pub(crate) fn of_faces(result: &Brep, operands: usize, mut faces: Vec, edges: &[Vec]) -> History { mark_shared_split(&mut faces); - faces + let edges = edge_faces(result) + .into_iter() + .enumerate() + .map(|(i, between)| { + let origins = match edges.get(i) { + Some(known) if !known.is_empty() => known.clone(), + _ if operands == 0 => Vec::new(), + _ => meeting(&between, &faces), + }; + EdgeProv { faces: between, origins } + }) + .collect(); + History { operands, faces, edges } } -/// A result face that is a region of the input faces `origins` (see [`regions`]), before -/// faces sharing an origin are marked Split. -pub(crate) fn region(origins: BTreeSet, whole: bool) -> FaceProv { - let change = match origins.len() { - 0 => Change::Generated, - 1 if whole => Change::Kept, - 1 => Change::Modified, - _ => Change::Merged, - }; - FaceProv { origins: origins.into_iter().collect(), change } -} - -/// Faces of one origin that is under other faces too, and that still say Kept or Modified, -/// are Split (also where histories are put side by side: pieces of one body can share a -/// source). -pub(crate) fn mark_shared_split(faces: &mut [FaceProv]) { - let mut uses: HashMap = HashMap::new(); - for o in faces.iter().flat_map(|f| &f.origins) { - *uses.entry(*o).or_default() += 1; - } - for f in faces.iter_mut() { - if matches!(f.change, Change::Kept | Change::Modified) - && let [o] = f.origins.as_slice() - && uses.get(o).copied().unwrap_or(0) > 1 - { - f.change = Change::Split; - } - } -} - -/// The index of each of `solid`'s edges by identity, in its edge order. -pub(crate) fn edge_index(solid: &crate::body::Solid) -> HashMap { - edge_order(solid.face_iter()).0.iter().enumerate().map(|(i, e)| (e.id(), i)).collect() -} - -/// The index of each of `solid`'s faces by identity, in its face order. -pub(crate) fn face_index(solid: &crate::body::Solid) -> HashMap { - solid.face_iter().enumerate().map(|(i, f)| (f.id(), i)).collect() -} - -/// Each of `solid`'s edges, by identity, as edge `i` (its position in the solid's edge order) of -/// operand `operand`: the operand's own edges, or a copy's made by `Body::deep_copy` or truck's -/// mapping builders (`translated`, `transformed`), which build the same faces, wires and edges -/// in the same order, so position `i` of the copy is position `i` of the body it copies. -pub(crate) fn edge_origins(solid: &crate::body::Solid, operand: usize) -> HashMap> { - edge_order(solid.face_iter()).0.iter().enumerate().map(|(edge, e)| (e.id(), vec![EdgeOrigin::Edge { operand, edge }])).collect() -} - -/// The edge entries of the history of `body`, each edge's origins from `origins` (by identity); -/// `None` when an edge has none there. -pub(crate) fn edge_provs(body: &Body, origins: &HashMap>) -> Option> { - let (edges, bounds) = edge_order(body.solid.face_iter()); - edges.iter().zip(bounds).map(|(e, faces)| Some(EdgeProv { faces, origins: origins.get(&e.id())?.clone() })).collect() -} - -/// `body` with the history whose faces are `faces` (in its face order) and whose edges' -/// origins are `edges` (by identity), made from operands with the face and edge `counts`; with -/// no history where either is missing, an edge has no entry, or the history does not describe -/// the body (an operation whose history could not be recorded still gives its result). -pub(crate) fn traced( - body: Body, - counts: &[(usize, usize)], - faces: Option>, - edges: Option<&HashMap>>, -) -> Body { - let history = faces.zip(edges).and_then(|(faces, edges)| Some(History { operands: counts.len(), faces, edges: edge_provs(&body, edges)? })); +/// `body`, made from operands with these face and edge `counts`, with the history [`of_faces`] +/// gives (none where the faces could not be followed, `None`, or the history does not describe +/// the body: an operation whose history could not be recorded still gives its result). +pub(crate) fn attach(body: Body, counts: &[(usize, usize)], faces: Option>, edges: &[Vec]) -> Body { + let history = faces.map(|faces| of_faces(body.record(), counts.len(), faces, edges)); body.with_checked_history(history, counts) } -/// [`traced`] of the body `Body::new` makes of `solid`: faces given in `solid`'s face order -/// and edges by identity, both of which `Body::new` keeps. -pub(crate) fn build( - solid: crate::body::Solid, - counts: &[(usize, usize)], - faces: Option>, - edges: Option<&HashMap>>, -) -> Result { - Ok(traced(Body::new(solid)?, counts, faces, edges)) -} - -/// [`build`] for a solid made by placing an already-oriented copy: the orientation comes from -/// the placement matrix instead of meshing the whole solid again (see -/// [`crate::body::Body::new_placed`]). -pub(crate) fn build_placed( - solid: crate::body::Solid, - counts: &[(usize, usize)], - faces: Option>, - edges: Option<&HashMap>>, - flip: bool, - coarse: Option<(f64, usize)>, - phased: bool, -) -> Result { - Ok(traced(Body::new_placed(solid, flip, coarse, phased)?, counts, faces, edges)) -} - -/// The origins of `body`'s edges by identity, from its history `h` (edges in its edge order). -pub(crate) fn edges_by_identity<'a>(body: &'a Body, h: &'a History) -> impl Iterator)> + 'a { - edge_order(body.solid.face_iter()).0.into_iter().zip(&h.edges).map(|(e, p)| (e.id(), p.origins.clone())) -} - /// The face and edge counts of `bodies`, for [`traced`]. pub(crate) fn counts(bodies: &[&Body]) -> Vec<(usize, usize)> { bodies.iter().map(|b| (b.face_count(), b.edge_count())).collect() } -/// An operation's operand, with its edges indexed by identity (in its edge order). -pub(crate) struct Operand<'a> { - pub body: &'a Body, - pub edges: HashMap, -} - -impl<'a> Operand<'a> { - pub(crate) fn new(body: &'a Body) -> Operand<'a> { - Operand { body, edges: edge_index(&body.solid) } - } -} - -/// Attach to `body`, made from `operands`, the history whose faces are `faces` (in its face -/// order); a body whose faces could not be followed (`None`) has no history. Each edge's -/// origin is the operand edge it is (the very edge, kept by the building code), or what -/// `copies` says: result edges the building code made as exact copies of operand edges. -pub(crate) fn attach(body: Body, operands: &[Operand], faces: Option>, copies: HashMap) -> Result { - let Some(faces) = faces else { return Ok(body) }; - let mut owned = copies; - for (operand, o) in operands.iter().enumerate() { - for (id, edge) in &o.edges { - owned.entry(*id).or_insert(EdgeOrigin::Edge { operand, edge: *edge }); - } - } - let (edges, bounds) = edge_order(body.solid.face_iter()); - let edges = edges.iter().zip(bounds).map(|(e, faces)| EdgeProv { faces, origins: owned.get(&e.id()).cloned().into_iter().collect() }).collect(); - let history = History { operands: operands.len(), faces, edges }; - let counts: Vec<(usize, usize)> = operands.iter().map(|o| (o.body.face_count(), o.edges.len())).collect(); - body.with_history_counts(history, &counts) -} - /// `step`, made from `prev` (the step's one operand), with its history carried back to what /// `prev` was made from: the operation's operands, with `counts` faces and edges. A multi-step /// operation starts from its operand with [`crate::boolean_record::operand`] (or healed, see @@ -202,146 +94,6 @@ pub(crate) fn after(mut step: Body, prev: &Body, counts: &[(usize, usize)]) -> B step.with_checked_history(h, counts) } -/// The history over `operands` operands of a body made by building `solid`, whose faces (in its -/// face order) come from `faces`: each edge new, where its two faces meet ([`meeting`]). -pub(crate) fn from_faces(solid: &Solid, operands: usize, faces: Vec) -> History { - let edges = edge_order(solid.face_iter()).1.into_iter().map(|between| EdgeProv { origins: meeting(&between, &faces), faces: between }).collect(); - History { operands, faces, edges } -} - -/// What a result face of a local rebuild was made from, by identity: an operand face it was -/// rebuilt from, or an operand edge it was made in place of (a blend). -#[derive(Clone, Copy, Debug)] -pub(crate) enum Was { - Face(mt::FaceID), - Edge(mt::EdgeID), -} - -/// What an operation built from its operands' topology, recorded by identity while the -/// operands and the result are both alive: the faces it made (each from what [`Was`], and -/// whether it is the whole of the one operand face it was rebuilt from: the same region) and -/// the edges it made as (parts of, or joins of) operand edges. A result face or edge that is an -/// operand's own (the very same topology, kept by the building code) is that, whatever was -/// recorded for it. Every -/// other edge is new, and comes from the meeting of the two faces it separates -/// ([`Rebuild::history`]). The record holds what it names, so that no identity it was given is -/// reused by later topology while it lives. -#[derive(Debug, Default)] -pub(crate) struct Rebuild { - faces: HashMap, bool)>, - edges: HashMap)>, -} - -impl Rebuild { - /// `new` is `from` rebuilt (trimmed differently, moved). - pub(crate) fn face(&mut self, new: &mt::Face, from: &mt::Face) { - self.made(new, vec![Was::Face(from.id())]); - } - - /// `new` is `from` rebuilt over the same region (its boundary edges cut or re-made). - pub(crate) fn whole(&mut self, new: &mt::Face, from: &mt::Face) { - self.faces.insert(new.id(), (new.clone(), vec![Was::Face(from.id())], true)); - } - - /// `new` is made in place of the operand edges `edges` (a blend; a corner patch lists the - /// edges meeting at its corner). - pub(crate) fn blend(&mut self, new: &mt::Face, edges: impl IntoIterator) { - self.made(new, edges.into_iter().map(Was::Edge).collect()); - } - - /// `new` is made from what `was` says (nothing: new to the operation). - pub(crate) fn made(&mut self, new: &mt::Face, was: Vec) { - self.faces.insert(new.id(), (new.clone(), was, false)); - } - - /// `new` is (a piece of, or the moved) edge `of`: an operand edge, or an edge recorded as - /// made from operand edges (a piece of a piece is a piece of the operand edge). - pub(crate) fn piece(&mut self, new: &mt::Edge, of: &mt::Edge) { - self.piece_of(new, of.id()); - } - - /// Every piece in `subst` (edge → the edge made in its place). - pub(crate) fn pieces<'a>(&mut self, subst: impl IntoIterator) { - for (old, new) in subst { - self.piece_of(new, *old); - } - } - - fn piece_of(&mut self, new: &mt::Edge, of: mt::EdgeID) { - let roots = self.edges.get(&of).map_or_else(|| vec![of], |(_, roots)| roots.clone()); - let (_, slot) = self.edges.entry(new.id()).or_insert_with(|| (new.clone(), Vec::new())); - for root in roots { - if !slot.contains(&root) { - slot.push(root); - } - } - } - - /// The history of `result` (in its face order; edges by identity) made from `operands` - /// (their solids, in the operation's operand order): faces and edges that are an operand's - /// own by identity (several operands' when they share it), the rest as recorded; an edge - /// recorded nowhere separates two faces that met nowhere before, so it comes from their - /// meeting ([`meeting`]). `None` when a face is neither an operand's nor recorded, or a record - /// names topology no operand has. - pub(crate) fn history(&self, result: &Solid, operands: &[&Solid]) -> Option<(Vec, HashMap>)> { - let mut face_at: HashMap> = HashMap::new(); - let mut edge_at: HashMap> = HashMap::new(); - for (operand, s) in operands.iter().enumerate() { - for (id, face) in face_index(s) { - face_at.entry(id).or_default().push(FaceOrigin::Face { operand, face }); - } - for (id, edge) in edge_index(s) { - edge_at.entry(id).or_default().push((operand, edge)); - } - } - let was = |w: &Was| -> Option> { - Some(match *w { - Was::Face(id) => face_at.get(&id)?.clone(), - Was::Edge(id) => edge_at.get(&id)?.iter().map(|&(operand, edge)| FaceOrigin::Edge { operand, edge }).collect(), - }) - }; - let mut faces = result - .face_iter() - .map(|f| { - let (origins, whole): (BTreeSet, bool) = match face_at.get(&f.id()) { - Some(own) => (own.iter().copied().collect(), true), - None => { - let (_, made, whole) = self.faces.get(&f.id())?; - (made.iter().map(was).collect::>>()?.into_iter().flatten().collect(), *whole) - } - }; - let on_faces = origins.iter().filter(|o| matches!(o, FaceOrigin::Face { .. })).count(); - let change = match on_faces { - 0 => Change::Generated, - 1 if origins.len() == 1 && whole => Change::Kept, - 1 if origins.len() == 1 => Change::Modified, - _ => Change::Merged, - }; - Some(FaceProv { origins: origins.into_iter().collect(), change }) - }) - .collect::>>()?; - mark_shared_split(&mut faces); - let edge_origins = |id: &mt::EdgeID| edge_at.get(id).map(|at| at.iter().map(|&(operand, edge)| EdgeOrigin::Edge { operand, edge })); - let (edges, bounds) = edge_order(result.face_iter()); - let mut origins = HashMap::with_capacity(edges.len()); - for (e, between) in edges.iter().zip(bounds) { - let of: Vec = if let Some(own) = edge_origins(&e.id()) { - own.collect() - } else if let Some((_, roots)) = self.edges.get(&e.id()) { - let mut set = BTreeSet::new(); - for root in roots { - set.extend(edge_origins(root)?); - } - set.into_iter().collect() - } else { - meeting(&between, &faces) - }; - origins.insert(e.id(), of); - } - Some((faces, origins)) - } -} - /// The origins of a new edge between the result faces `between` (whose provenance is in /// `faces`): the meeting of the two faces (each side all of its face's origins, one or /// several), when each comes from something and no origin is under both; else none (a seam, @@ -357,172 +109,6 @@ pub(crate) fn meeting(between: &[usize], faces: &[FaceProv]) -> Vec } } -/// The face and edge counts of the solids `operands`, for [`traced`]. -pub(crate) fn solid_counts(operands: &[&Solid]) -> Vec<(usize, usize)> { - operands.iter().map(|s| (s.face_iter().count(), edge_order(s.face_iter()).0.len())).collect() -} - -/// The body `Body::new` makes of `result`, which an operation built from `operands` (their -/// solids) as `rec` records, with that history (none where it could not be recorded). -pub(crate) fn rebuilt(result: Solid, operands: &[&Solid], rec: &Rebuild) -> Result { - let (faces, edges) = rec.history(&result, operands).unzip(); - build(result, &solid_counts(operands), faces, edges.as_ref()) -} - -/// [`rebuilt`] for a body made as it is (a surface, which `Body::new` does not take): its -/// solid is the one the operation built. -pub(crate) fn rebuilt_body(body: Body, operands: &[&Solid], rec: &Rebuild) -> Body { - let (faces, edges) = rec.history(&body.solid, operands).unzip(); - let counts = solid_counts(operands); - traced(body, &counts, faces, edges.as_ref()) -} - -/// Ruled faces (truck's `try_wire_homotopy` of wires `a` and `b`), each with the provenance of -/// the edges it spans: every face holds one edge of each wire, and comes from the profile -/// segments under both (`a_numbers`, `b_numbers`: by edge, in wire order). -pub(crate) fn ruled(faces: &mt::Shell, a: &mt::Wire, b: &mt::Wire, a_numbers: &[Vec], b_numbers: &[Vec]) -> Vec { - let under = |w: &mt::Wire, numbers: &[Vec]| -> HashMap> { - w.edge_iter().map(|e| e.id()).zip(numbers.iter().cloned()).collect() - }; - let (ua, ub) = (under(a, a_numbers), under(b, b_numbers)); - faces - .face_iter() - .map(|f| { - let held = |u: &HashMap>| -> Option> { - let mut found = f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).filter_map(|e| u.get(&e.id())); - let one = found.next()?.clone(); - found.next().is_none().then_some(one) - }; - let prov = held(&ua).zip(held(&ub)).map(|(x, y)| profile(x.iter().chain(&y))); - (f.clone(), prov) - }) - .collect() -} - -/// How far a column of swept faces runs. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Column { - /// Until no face lies beyond (an open sweep whose caps are not among the faces) or the - /// column comes back to its first face (a full turn). - ToEnd, - /// Exactly this many faces (the sweep's caps are among the faces). - Steps(usize), -} - -/// Follow the faces truck sweeps from the profile edges (`seeds`) they start at. A face swept -/// from an edge is bounded by one loop: the edge, its moved copy, and the paths its ends sweep -/// (none where an end stays put: a cone's apex, `fixed`). The copy is the loop's one other edge -/// that shares no moving vertex with the edge, and is where the next step of the sweep starts. -/// The face at `skip` is never entered. Returns, for each face, the seed whose column it lies -/// in; `None` when the faces don't follow that pattern (a face reached twice, a column with a -/// fork or of the wrong length). -pub(crate) fn follow<'a>( - faces: impl IntoIterator, - seeds: &[mt::EdgeID], - skip: Option, - run: Column, - fixed: &[mt::VertexID], -) -> Option>> { - let faces: Vec<&mt::Face> = faces.into_iter().collect(); - let mut by_edge: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - if skip == Some(i) { - continue; - } - for e in f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()) { - let slot = by_edge.entry(e.id()).or_default(); - if !slot.contains(&i) { - slot.push(i); - } - } - } - let mut owner: Vec> = vec![None; faces.len()]; - let limit = match run { - Column::Steps(n) => n, - Column::ToEnd => faces.len(), - }; - for (seed, start) in seeds.iter().enumerate() { - let (mut edge, mut prev, mut first) = (*start, None, None); - let mut count = 0; - while count < limit { - let next: Vec = by_edge.get(&edge).map(|v| v.iter().copied().filter(|f| Some(*f) != prev).collect()).unwrap_or_default(); - let next = match (next.as_slice(), first) { - ([], _) => break, - ([f], _) => *f, - // A full turn: the profile edge bounds the first face and the last. - ([f, _], None) if run == Column::ToEnd => *f, - _ => return None, - }; - if Some(next) == first { - break; - } - let slot = owner.get_mut(next)?; - if slot.is_some() { - return None; - } - *slot = Some(seed); - let [wire] = faces.get(next)?.absolute_boundaries().as_slice() else { return None }; - let here = wire.edge_iter().find(|e| e.id() == edge)?; - let moving: Vec = [here.front().id(), here.back().id()].into_iter().filter(|v| !fixed.contains(v)).collect(); - let mut copies = wire.edge_iter().filter(|e| e.id() != edge && !moving.contains(&e.front().id()) && !moving.contains(&e.back().id())); - let (Some(copy), None) = (copies.next(), copies.next()) else { return None }; - edge = copy.id(); - prev = Some(next); - first.get_or_insert(next); - count += 1; - } - if matches!(run, Column::Steps(n) if count != n) { - return None; - } - } - Some(owner) -} - -/// Each face's provenance by the column it lies in ([`follow`]), from the profile segments -/// under each seed edge. -pub(crate) fn columns<'a>( - faces: impl IntoIterator, - seeds: &[(mt::EdgeID, Vec)], - skip: Option, - run: Column, - fixed: &[mt::VertexID], -) -> Option>> { - let ids: Vec = seeds.iter().map(|(id, _)| *id).collect(); - Some(follow(faces, &ids, skip, run, fixed)?.into_iter().map(|o| o.and_then(|s| seeds.get(s)).map(|(_, numbers)| profile(numbers))).collect()) -} - -/// The history of a solid truck swept from the planar face `profile` (`rsweep` of it), whose -/// boundary edges `seeds` come from the profile segments given with them. Open -/// (`closed == false`): the profile face is the start cap, each edge's faces follow from it to -/// the end cap (the one face left), the same number of faces for every edge. Closed (a full -/// turn): no caps, each edge's faces go round. -pub(crate) fn swept_face(solid: &crate::body::Solid, profile: &mt::Face, seeds: &[(mt::EdgeID, Vec)], closed: bool) -> Option> { - let faces: Vec<&mt::Face> = solid.face_iter().collect(); - let start = faces.iter().position(|f| f.id() == profile.id()); - let run = match (closed, start) { - (true, None) => Column::ToEnd, - (false, Some(_)) => { - // Two caps, and as many faces for every edge. - let steps = faces.len().checked_sub(2)?.checked_div(seeds.len())?; - if steps == 0 || steps * seeds.len() + 2 != faces.len() { - return None; - } - Column::Steps(steps) - } - _ => return None, - }; - // Every face but the caps lies in a column, so the one face left open is the end cap. - columns(faces, seeds, start, run, &[])? - .into_iter() - .enumerate() - .map(|(i, p)| match p { - Some(p) => Some(p), - None if Some(i) == start => Some(cap(false)), - None => (!closed).then(|| cap(true)), - }) - .collect() -} - #[cfg(test)] #[path = "record_tests.rs"] mod tests; diff --git a/crates/kernel/src/record_tests.rs b/crates/kernel/src/record_tests.rs index e6cd574a3..124cfa389 100644 --- a/crates/kernel/src/record_tests.rs +++ b/crates/kernel/src/record_tests.rs @@ -1,12 +1,14 @@ //! The creation builders' histories: every face's origin checked against the geometry the //! builder made it from. +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use crate::body::Body; use crate::build::PathSeg; +use crate::history::BodyHistory; use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv, History, Side}; const P: fn(usize) -> FaceOrigin = |segment| FaceOrigin::Profile { segment }; @@ -20,7 +22,7 @@ fn sketch_made(b: &Body) -> &History { h.check(b, &[]).unwrap(); assert!(h.faces.iter().all(|f| f.change == Change::Generated && !f.origins.is_empty())); assert!(h.edges.iter().all(|e| e.origins.is_empty())); - assert_eq!(h.edges.iter().map(|e| e.faces.clone()).collect::>(), crate::history::edge_faces(&b.solid)); + assert_eq!(h.edges.iter().map(|e| e.faces.clone()).collect::>(), crate::history::edge_faces(b.record())); h } @@ -37,7 +39,7 @@ fn points(b: &Body) -> Vec> { /// Mesh vertices of each face, and its triangles' centres (off a curved face by up to the /// mesh's tolerance). fn mesh_points(b: &Body) -> (Vec>, Vec>) { - let m = b.tessellate(b.size() * 1e-3).unwrap(); + let m = b.mesh(&crate::MeshTolerance::chord(b.size() * 1e-3)).unwrap(); let (mut corners, mut centres) = (vec![Vec::new(); b.face_count()], vec![Vec::new(); b.face_count()]); for (t, f) in m.triangles.iter().zip(&m.tri_face) { let c = t.map(|i| m.positions[i as usize]); @@ -48,7 +50,9 @@ fn mesh_points(b: &Body) -> (Vec>, Vec>) { } /// The segments a face lies over: its vertices on them within `tol`, its triangles' centres -/// near them (`to_2d` takes a point into the profile's plane). +/// near them (`to_2d` takes a point into the profile's plane). A face over one segment has all +/// of them on it; a face over several (the one wall a circle drawn in arcs sweeps) has each +/// centre near one of them and each vertex on one of them. fn swept_from(b: &Body, loops: &[&Loop2], to_2d: impl Fn(Vec3) -> Vec2, tol: f64) -> Vec> { let (corners, centres) = mesh_points(b); let flat = |pts: &Vec| pts.iter().map(|p| to_2d(*p)).collect::>(); @@ -56,8 +60,19 @@ fn swept_from(b: &Body, loops: &[&Loop2], to_2d: impl Fn(Vec3) -> Vec2, tol: f64 .iter() .zip(¢res) .map(|(v, c)| { - let near = under(loops, &flat(c), b.size() * 3e-3); - under(loops, &flat(v), tol).into_iter().filter(|k| near.contains(k)).collect() + let (v, c) = (flat(v), flat(c)); + let near = under(loops, &c, b.size() * 3e-3); + let one: Vec = under(loops, &v, tol).into_iter().filter(|k| near.contains(k)).collect(); + if !one.is_empty() { + return one; + } + let each = |pts: &[Vec2], tol: f64| pts.iter().map(|q| under(loops, std::slice::from_ref(q), tol)).collect::>(); + let centre_segs = each(&c, b.size() * 3e-3); + let mut over: Vec = centre_segs.iter().flatten().copied().collect(); + over.sort_unstable(); + over.dedup(); + let covered = |segs: &[Vec]| segs.iter().all(|s| s.iter().any(|k| over.contains(k))); + if over.len() > 1 && covered(¢re_segs) && covered(&each(&v, tol)) { over } else { Vec::new() } }) .collect() } @@ -140,24 +155,30 @@ fn extrude_sides_follow_profile_segments_in_any_order() { // The certificates are produced as before. assert!(b.face_sources().unwrap().iter().all(Option::is_some)); } - // The +x side is whichever segment of the given loop runs along x = 40. + // The +x side is whichever segment of the given loop runs along x = 40 (the hole's wall at + // x = 10 faces +x too). let r = &variants[2]; let b = crate::extrude(&Plane::XY, std::slice::from_ref(r), 0.0, 10.0).unwrap().pop().unwrap(); let k = r.outer.segs.iter().position(|s| s.start().x == 40.0 && s.end().x == 40.0).unwrap(); - let side = b.faces(1e-3).unwrap().iter().position(|f| f.plane_normal.is_some_and(|n| n.dist(Vec3::X) < 1e-9)).unwrap(); + let side = b + .faces(1e-3) + .unwrap() + .iter() + .position(|f| f.plane_normal.is_some_and(|n| n.dist(Vec3::X) < 1e-9) && (f.centroid.x - 40.0).abs() < 1e-6) + .unwrap(); assert_eq!(origins(&b)[side], [P(k)]); } -/// A big arc is built as two edges: both faces come from it. +/// A big arc sweeps one face, as every segment does. #[test] -fn extrude_a_big_arc_gives_two_faces_of_one_segment() { +fn extrude_a_big_arc_gives_one_face_of_one_segment() { let (a, b) = (Vec2::new(10.0 * (0.3f64).cos(), -10.0 * (0.3f64).sin()), Vec2::new(10.0 * (0.3f64).cos(), 10.0 * (0.3f64).sin())); let arc = Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: 0.3, sweep: TAU - 0.6 }; let r = Region2 { outer: Loop2 { segs: vec![arc, Seg2::Line { a, b }] }, holes: vec![] }; let body = crate::extrude(&Plane::XY, std::slice::from_ref(&r), 0.0, 5.0).unwrap().pop().unwrap(); let got = origins(&body); assert_eq!(got, expected_extrusion(&body, &Plane::XY, &r, 5.0)); - assert_eq!(got.iter().filter(|o| **o == [P(0)]).count(), 2); + assert_eq!(got.iter().filter(|o| **o == [P(0)]).count(), 1); assert_eq!(got.iter().filter(|o| **o == [P(1)]).count(), 1); } @@ -176,18 +197,18 @@ fn primitives_report_their_construction() { assert_eq!(o, &[want]); } assert!(b.face_sources().unwrap().iter().all(|s| matches!(s, Some(crate::FaceSource::Box { .. })))); - // Cylinder: a circle of two arcs, extruded. + // Cylinder: a circle (one arc), extruded. let c = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.0, 8.0).unwrap(); let r = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 5.0, crate::build::SEAM_ANGLE), holes: vec![] }; let frame = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap(); let want = expected_extrusion(&c, &frame, &r, 8.0); assert_eq!(origins(&c), want); - // Sphere: six patches, all from the arc of the half disc it revolves. + // Sphere: one face, from the arc of the half disc it revolves. let s = crate::sphere(Vec3::ZERO, 5.0).unwrap(); - assert_eq!(origins(&s), vec![vec![P(0)]; 6]); - // Torus: a circle re-split for its seam, turned in three: each face from both arcs. + assert_eq!(origins(&s), vec![vec![P(0)]]); + // Torus: one face, from the circle (segment 0) it turns. let t = crate::torus(Vec3::ZERO, 10.0, 2.0).unwrap(); - assert_eq!(origins(&t), vec![vec![P(0), P(1)]; 6]); + assert_eq!(origins(&t), vec![vec![P(0)]]); } /// The plane the revolve tests sketch in (x across, y up the world z axis, the revolve axis). @@ -208,31 +229,29 @@ fn expected_revolution(b: &Body, r: &Region2) -> Vec> { #[test] fn revolve_partial_and_full() { let r = Region2 { outer: rect(10.0, 0.0, 20.0, 5.0), holes: vec![rect(12.0, 1.0, 14.0, 2.0).reversed()] }; - // Under half a turn truck sweeps in two parts, beyond it in three; a full turn has no caps, - // and its planar faces (from the segments square to the axis) are whole (#726), as a partial + // SMLib turns each segment into one face whatever the angle; a full turn has no caps, and + // its planar faces (from the segments square to the axis) are whole (#726), as a partial // turn's are when it is final (`revolve_whole`). let segs: Vec = r.outer.segs.iter().chain(r.holes.iter().flat_map(|h| &h.segs)).cloned().collect(); for whole in [false, true] { - for (angle, parts, caps) in [(FRAC_PI_2, 2, 2), (1.5 * PI, 3, 2), (TAU, 3, 0)] { + for (angle, caps) in [(FRAC_PI_2, 2), (1.5 * PI, 2), (TAU, 0)] { let revolve = if whole { crate::revolve_whole } else { crate::revolve }; let b = revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap(); let got = origins(&b); assert_eq!(got, expected_revolution(&b, &r), "angle {angle}, whole {whole}"); - for (k, s) in segs.iter().enumerate() { - let square = matches!(s, Seg2::Line { a, b } if (a.y - b.y).abs() < 1e-12); - let want = if (angle == TAU || whole) && square { 1 } else { parts }; - assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), want, "segment {k} at angle {angle}, whole {whole}"); + for k in 0..segs.len() { + assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), 1, "segment {k} at angle {angle}, whole {whole}"); } assert_eq!(got.iter().filter(|o| **o == [START] || **o == [END]).count(), caps); } } } -/// Loops given clockwise, a hole that is a full circle of three arcs: extrude numbers every -/// face by the segment as given; revolve re-seams the circle into two half circles, each from -/// every given arc it runs over. +/// Loops given clockwise, a hole that is a full circle of three arcs: extrude and revolve +/// number every face by the segments as given. Extruded, the circle's arcs sweep one wall, +/// made from all three; the rectangle's sides one face each. #[test] -fn clockwise_loops_and_a_reseamed_circle_keep_their_numbers() { +fn clockwise_loops_and_a_circle_of_arcs_keep_their_numbers() { let (c, rad) = (Vec2::new(20.0, 10.0), 4.0); let arcs = [(0.3, 2.0), (2.3, 2.5), (4.8, TAU - 4.5)]; let ccw = Loop2 { segs: arcs.iter().map(|&(start, sweep)| Seg2::Arc { center: c, radius: rad, start, sweep }).collect() }; @@ -241,31 +260,19 @@ fn clockwise_loops_and_a_reseamed_circle_keep_their_numbers() { let b = crate::extrude(&Plane::XY, std::slice::from_ref(&r), 0.0, 10.0).unwrap().pop().unwrap(); let got = origins(&b); assert_eq!(got, expected_extrusion(&b, &Plane::XY, &r, 10.0)); - for k in 0..7 { + for k in 0..4 { assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), 1, "segment {k}"); } - // Revolved, the circle restarts at 0.4142 rad: the half from there runs over the first two - // arcs (6, 5), the other half over all three (it ends past the first arc's start). - let first_half = |q: Vec2| (q - c).angle().rem_euclid(TAU); + assert_eq!(got.iter().filter(|o| **o == [P(4), P(5), P(6)]).count(), 1, "the circle's one wall"); + assert_eq!(got.len(), 7, "four sides, the wall, two caps"); + // Revolved, each arc turns into a face of its own, as the rectangle's sides do. for angle in [FRAC_PI_2, TAU] { let b = crate::revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap(); let got = origins(&b); - let want = expected_revolution(&b, &r); - let (_, centres) = mesh_points(&b); - let mut halves = [0, 0]; - for ((g, w), centres) in got.iter().zip(&want).zip(¢res) { - let flat: Vec = centres.iter().map(|p| Vec2::new(p.x.hypot(p.y), p.z)).collect(); - if flat.iter().all(|q| (q.dist(c) - rad).abs() < 0.1) { - let first = flat.iter().all(|q| (0.4142 - 1e-3..=0.4142 + PI + 1e-3).contains(&first_half(*q))); - assert_eq!(g, &if first { vec![P(5), P(6)] } else { vec![P(4), P(5), P(6)] }, "angle {angle}"); - halves[usize::from(!first)] += 1; - } else { - assert_eq!(g, w, "angle {angle}"); - } + assert_eq!(got, expected_revolution(&b, &r), "angle {angle}"); + for k in 0..7 { + assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), 1, "segment {k} at angle {angle}"); } - // Truck turns each half in as many parts as each rectangle side. - let parts = got.iter().filter(|o| **o == [P(0)]).count(); - assert_eq!(halves, [parts, parts], "angle {angle}"); } } @@ -277,11 +284,11 @@ fn revolve_with_an_edge_on_the_axis() { let got = origins(&partial); assert_eq!(got, expected_revolution(&partial, &r)); assert_eq!(got.len(), 5); - // A full turn: the radial segments 0 and 2 sweep discs, segment 1 the cylinder (three parts). + // A full turn: the radial segments 0 and 2 sweep discs, segment 1 the cylinder (one face). let full = crate::revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, TAU).unwrap().pop().unwrap(); let got = origins(&full); assert_eq!(got, expected_revolution(&full, &r)); - assert_eq!(got.iter().filter(|o| **o == [P(1)]).count(), 3); + assert_eq!(got.iter().filter(|o| **o == [P(1)]).count(), 1); assert_eq!(got.iter().filter(|o| **o == [P(0)] || **o == [P(2)]).count(), 2); // A cone: the slanted segment ends on the axis (the apex), the base disc. let tri = Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(0.0, 8.0)]), holes: vec![] }; @@ -291,7 +298,7 @@ fn revolve_with_an_edge_on_the_axis() { let turned = Region2 { outer: rotated(&tri.outer.reversed(), 1), holes: vec![] }; let cone = crate::revolve(&SIDE, std::slice::from_ref(&turned), Vec2::ZERO, Vec2::Y, TAU).unwrap().pop().unwrap(); assert_eq!(origins(&cone), expected_revolution(&cone, &turned)); - // A half disc: a sphere, every patch from the arc (segment 1 here). + // A half disc: a sphere, its one face from the arc (segment 1 here). let half = Region2 { outer: Loop2 { segs: vec![ @@ -302,13 +309,13 @@ fn revolve_with_an_edge_on_the_axis() { holes: vec![], }; let ball = crate::revolve(&SIDE, std::slice::from_ref(&half), Vec2::ZERO, Vec2::Y, TAU).unwrap().pop().unwrap(); - assert_eq!(origins(&ball), vec![vec![P(1)]; 6]); + assert_eq!(origins(&ball), vec![vec![P(1)]]); } #[test] fn tapered_extrusion() { let r = Region2 { outer: rotated(&rect(0.0, 0.0, 20.0, 10.0).reversed(), 1), holes: vec![] }; - let b = crate::extrude_tapered(&Plane::XY, &r, 10.0, 1.0, 0.1).unwrap(); + let b = crate::extrude_tapered(&Plane::XY, &r, 10.0, 1.0, 0.1, crate::DraftCorner::default()).unwrap(); let want: Vec> = points(&b) .iter() .map(|pts| { @@ -403,9 +410,10 @@ fn loft_sections() { assert_eq!(origins(&b), want); } -/// Faces of a sweep: the start cap in the profile's plane; each segment's faces run the whole -/// path, the first one standing on that segment. -fn check_sweep(b: &Body, plane: &Plane, r: &Region2, faces_per_segment: Option) { +/// Faces of a sweep: the start cap in the profile's plane; each segment's faces run along the +/// path, the first one standing on that segment; `faces_per_segment`, if given, the number of +/// faces each segment sweeps, in segment order. +fn check_sweep(b: &Body, plane: &Plane, r: &Region2, faces_per_segment: Option<&[usize]>) { let loops: Vec<&Loop2> = std::iter::once(&r.outer).chain(&r.holes).collect(); let n: usize = loops.iter().map(|l| l.segs.len()).sum(); let got = origins(b); @@ -430,7 +438,7 @@ fn check_sweep(b: &Body, plane: &Plane, r: &Region2, faces_per_segment: Option = (0..n).map(|k| got.iter().filter(|o| **o == [P(k)]).count()).collect(); match faces_per_segment { - Some(c) => assert!(counts.iter().all(|x| *x == c), "{counts:?}"), + Some(c) => assert_eq!(counts, c), None => assert!(counts.windows(2).all(|w| w[0] == w[1] && w[0] > 0), "{counts:?}"), } } @@ -438,14 +446,16 @@ fn check_sweep(b: &Body, plane: &Plane, r: &Region2, faces_per_segment: Option = (0..=40) .map(|i| { let t = i as f64 / 40.0 * FRAC_PI_2; @@ -455,19 +465,23 @@ fn sweeps_along_paths() { let plane = Plane::from_normal(curve[0], (curve[1] - curve[0]).normalized().unwrap()).unwrap(); let circle = Region2 { outer: Loop2::circle(Vec2::ZERO, 2.0), holes: vec![] }; let b = crate::sweep_path(&plane, &circle, &curve).unwrap(); - check_sweep(&b, &plane, &circle, Some(1)); - // A path with a corner, a holed profile: ruled walls station to station. + check_sweep(&b, &plane, &circle, Some(&[40])); + // A path with a corner, a holed profile: a wall along each leg, mitred at the corner. The + // corner turns the profile about Y, so each line at a constant y (segments 0 and 2 of the + // outer loop, 1 and 3 of the hole, drawn the other way round) sweeps the plane it lies in + // along both legs: one L-shaped planar face. The lines at a constant x make two each. let holed = Region2 { outer: rect(-3.0, -3.0, 3.0, 3.0), holes: vec![rect(-1.0, -1.0, 1.0, 1.0).reversed()] }; let b = crate::sweep_path(&Plane::XY, &holed, &[Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::new(20.0, 0.0, 20.0)]).unwrap(); - check_sweep(&b, &Plane::XY, &holed, Some(2)); + check_sweep(&b, &Plane::XY, &holed, Some(&[1, 2, 1, 2, 2, 1, 2, 1])); // A coil: a smooth wall per segment. let side = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; let ring = Region2 { outer: Loop2::circle(Vec2::new(20.0, 0.0), 2.0), holes: vec![] }; let b = crate::sweep_helix(&side, &ring, Vec3::ZERO, Vec3::Z, 8.0, 3.0).unwrap(); - check_sweep(&b, &side, &ring, Some(1)); + check_sweep(&b, &side, &ring, Some(&[1])); } -/// Kept faces are their origins, unchanged; each edge an operand still owns is that edge. +/// Kept faces are their origins, unchanged; each edge an operand still owns is that edge (a new +/// edge, where two faces meet, has a Meet origin instead). fn check_kept(result: &Body, input: &Body) { let h = result.history().unwrap(); h.check(result, &[input]).unwrap(); @@ -481,7 +495,11 @@ fn check_kept(result: &Body, input: &Body) { let mut owned = 0; for (e, p) in re.iter().zip(&h.edges) { for o in &p.origins { - let crate::history::EdgeOrigin::Edge { operand: 0, edge } = o else { panic!("{o:?}") }; + let edge = match o { + crate::history::EdgeOrigin::Edge { operand: 0, edge } => edge, + crate::history::EdgeOrigin::Meet { .. } => continue, + _ => panic!("{o:?}"), + }; assert!(e.mid.dist(ie[*edge].mid) < 1e-6, "edge {}", e.index); owned += 1; } @@ -505,12 +523,14 @@ fn thicken_reports_copies_offsets_and_walls() { let h = t.history().unwrap(); assert_eq!(h.faces[0].origins, [FaceOrigin::Face { operand: 0, face: 0 }]); assert_eq!(h.faces[1].origins, [FaceOrigin::Offset { operand: 0, face: 0 }]); - let free: Vec = (0..half.edge_count()).collect(); + // A wall along each free edge of the sheet: the side's two rims, not its seam (an edge the + // one face meets itself along, no boundary). + let free: Vec = (0..half.edge_count()).filter(|e| half.record().edges[*e].uses.len() == 1).collect(); for (i, f) in h.faces.iter().enumerate().skip(2) { let [FaceOrigin::Edge { operand: 0, edge }] = f.origins.as_slice() else { panic!("{f:?}") }; assert_eq!(*edge, nearest_edge(&t, i, &half, &free)); } - assert_eq!(h.faces.len(), 2 + half.edge_count()); + assert_eq!(h.faces.len(), 2 + free.len()); } #[test] @@ -524,7 +544,7 @@ fn raised_band_reports_kept_trimmed_and_new_faces() { let [FaceOrigin::Face { operand: 0, face: rim }] = rim.origins.as_slice() else { panic!() }; // The rim's inner loop: the edges the walls stand on. let loop_edges: Vec = - crate::history::edge_faces(&sh.solid).iter().enumerate().filter(|(_, fs)| fs.contains(rim)).map(|(i, _)| i).collect(); + crate::history::edge_faces(sh.record()).iter().enumerate().filter(|(_, fs)| fs.contains(rim)).map(|(i, _)| i).collect(); let mut walls = 0; for (i, f) in h.faces.iter().enumerate() { if let [FaceOrigin::Edge { operand: 0, edge }] = f.origins.as_slice() { diff --git a/crates/kernel/src/refine_cache_tests.rs b/crates/kernel/src/refine_cache_tests.rs deleted file mode 100644 index d6702df11..000000000 --- a/crates/kernel/src/refine_cache_tests.rs +++ /dev/null @@ -1,53 +0,0 @@ -use super::*; - -fn bits(v: Vec3) -> [u64; 3] { - [v.x.to_bits(), v.y.to_bits(), v.z.to_bits()] -} - -fn check_body(body: &Body) -> usize { - let meshes = mesh_shells(&body.solid, 0.5); - let mut changed = 0; - for (face, meshed) in body.solid.face_iter().zip(meshes.iter().flat_map(|shell| shell.face_iter())) { - let Some(mesh) = meshed.surface() else { continue }; - let surface = face.surface(); - let cached = refined_with_cache(&mesh, &surface, 0.002, true); - let original = refined_with_cache(&mesh, &surface, 0.002, false); - match (cached, original) { - (None, None) => {} - (Some(cached), Some(original)) => { - changed += 1; - assert_eq!(cached.len(), original.len(), "triangle count/winding must not change"); - for (cached, original) in cached.into_iter().zip(original) { - for ((point, normal), (old_point, old_normal)) in cached.into_iter().zip(original) { - assert_eq!(bits(point), bits(old_point), "every refined coordinate must remain bit-identical"); - assert_eq!(bits(normal), bits(old_normal), "every refined normal must remain bit-identical"); - } - } - } - _ => panic!("memoization changed the refine/no-refine decision"), - } - } - changed -} - -#[test] -fn exact_refinement_cache_preserves_periodic_seams_and_normals() { - let cylinder = crate::cylinder(Vec3::ZERO, Vec3::Z, 15., 8.).unwrap(); - let torus = crate::torus(Vec3::ZERO, 18., 4.).unwrap(); - assert!(check_body(&cylinder) > 0, "the fixture must actually refine"); - assert!(check_body(&torus) > 0, "the periodic fixture must actually refine"); -} - -#[test] -fn exact_refinement_cache_preserves_singular_poles_and_placed_surfaces() { - let sphere = crate::sphere(Vec3::ZERO, 12.).unwrap(); - assert!(check_body(&sphere) > 0, "the polar fixture must actually refine"); - let placed = crate::transform(&sphere, Vec3::new(120., -85., 40.), Vec3::ZERO, Vec3::new(1., 2., 3.), 0.371).unwrap(); - assert!(check_body(&placed) > 0); -} - -#[test] -fn exact_refinement_cache_keeps_unnecessary_planar_refinement_absent() { - let body = crate::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); - assert_eq!(check_body(&body), 0); -} diff --git a/crates/kernel/src/regularization_protection_tests.rs b/crates/kernel/src/regularization_protection_tests.rs index 5bcab8ab8..860c9f38d 100644 --- a/crates/kernel/src/regularization_protection_tests.rs +++ b/crates/kernel/src/regularization_protection_tests.rs @@ -1,5 +1,5 @@ use super::*; -use solidcraft_geom::Plane; +use solidcore_record::Plane; fn stamped_stock() -> Body { crate::box_solid(Vec3::new(-20., -15., 0.), Vec3::new(20., 15., 24.)).unwrap().with_box_certificate(7).unwrap() @@ -15,28 +15,26 @@ fn stamped_shell_keeps_authored_painted_and_split_boundaries() { let ordinary = cup(&stock); assert!(!ordinary.regularization_protected); let painted = stock.clone().with_paint(Some(Paint { opacity: 1., faces: vec![FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }] })); - let side = stock - .solid - .face_iter() - .enumerate() - .find(|(i, _)| stock.planar_face(*i).is_some_and(|p| p.normal().dot(Vec3::X) > 0.999 && p.origin.x == 20.)) - .unwrap() - .0; + let side = (0..stock.face_count()).find(|i| stock.planar_face(*i).is_some_and(|p| p.normal().dot(Vec3::X) > 0.999 && p.origin.x == 20.)).unwrap(); let split = crate::split_faces(&stock, &[side], &crate::SplitTool::Plane(Plane { origin: Vec3::new(0., 0., 8.), ..Plane::XY })).unwrap(); assert!(split.split_lines().is_some()); - for protected in [painted, split] { + // SMLib's shell makes no section strips: the ordinary cup is the stock's five kept faces, + // their five linings and the rim (11). A paint over a whole face authors no boundary inside + // it, so the painted cup has those same faces; the split side's line stays an edge on both + // walls (13). + for (protected, faces) in [(painted, ordinary.face_count()), (split, ordinary.face_count() + 2)] { let result = cup(&protected); assert!(result.regularization_protected); - assert!(result.face_count() > ordinary.face_count(), "authored boundaries must survive both Shell regularizers"); + assert_eq!(result.face_count(), faces, "authored boundaries must survive Shell"); + assert_eq!(result.split_lines(), protected.split_lines()); assert!(result.validity().is_empty()); let expected = 40. * 30. * 24. - 38. * 28. * 23.; - let mesh = result.tessellate(1e-5).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap(); assert!((mesh.measure().volume - expected).abs() < 1e-6); assert!(mesh.contains(Vec3::new(19.5, 0., 12.))); assert!(!mesh.contains(Vec3::new(0., 0., 12.))); let count = result.face_count(); assert_eq!(result.clone().regularize_certified_planar_faces().unwrap().face_count(), count); - assert_eq!(result.clone().regularize_generated_planar_faces().unwrap().face_count(), count); let placed = crate::transform(&result, Vec3::new(30., -40., 7.), Vec3::ZERO, Vec3::Z, 0.3).unwrap(); assert!(placed.regularization_protected); for lump in placed.lumps().unwrap() { diff --git a/crates/kernel/src/repair.rs b/crates/kernel/src/repair.rs new file mode 100644 index 000000000..81a356593 --- /dev/null +++ b/crates/kernel/src/repair.rs @@ -0,0 +1,589 @@ +//! Repair Part (#8371): a part SMLib refuses, or an open part that should be a solid, made into +//! one SMLib takes, saying what changed face by face. In order: +//! +//! 1. A face SMLib refuses on its own is rebuilt from its own surface, its geometry unchanged: a +//! cylinder, cone, sphere or torus face on a NURBS form SMLib rejects goes as the analytic +//! surface it is, which SMLib parameterises on its own form (the form's control net is the +//! import's construction; the surface it stands for is the label's, exactly). +//! 2. Free edges that pair up within `gap` (a sliver between two faces that should meet) are sewn +//! by SMLib's stitch, which gives each edge it glues its own tolerance from that pair's gap +//! (`SmBrep::GlueEdgesGeneral`: at least twice the gap); the body's tolerance, and every other +//! edge's, stays as it was. +//! 3. A loop of free edges no pair explains is a missing face: Patch on that loop is offered (and +//! made, and sewn in, when asked), planar only where the faces around it are that plane; where +//! they are curved the patch meets them tangent (G1). Extending the neighbours is not done. +//! +//! Nothing is moved: a face rebuilt keeps its surface, a sewn edge keeps its curve (SMLib keeps +//! one of the pair), a patch is a new face. What was done comes back in [`RepairReport`]. + +use solidcore_record::Vec3; +use solidcore_record::brep::{self as b, Brep}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::prelude::*; + +use crate::body::{Body, SurfaceKind}; +use crate::{Continuity, KernelError, Result}; + +/// Most free edges paired against each other (each against every other near it). +const MAX_FREE_EDGES: usize = 20_000; +/// Most faces sent into SMLib one by one to find the ones it refuses. +const MAX_FACE_PROBES: usize = 20_000; +/// Points along an edge where its distance to its partner is measured. +const GAP_SAMPLES: usize = 16; +/// SMLib's check tests that bound an item's tolerance by the body's (`SmBrep::AssertValid` #5, +/// #6: face; #59: edge, under 1000 times the body's; #82: vertex). An edge sewn across a gap +/// carries that gap; the body's tolerance is not raised to cover it, so these may fail on sewn +/// items, as they already fail on an import's edges that lie off their faces by more. +const TOLERANCE_BOUND_TESTS: [u32; 4] = [5, 6, 59, 82]; + +/// What a repair may do. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RepairOptions { + /// The widest gap between two free edges that is sewn, mm (> 0). + pub gap: f64, + /// Patch the loops of free edges no pair explains (missing faces), and sew the patches in. + pub patch_holes: bool, +} + +/// A face rebuilt so SMLib takes it. +#[derive(Clone, Debug, PartialEq)] +pub struct RebuiltFace { + /// Its index in the body before the repair. + pub face: usize, + pub surface: SurfaceKind, + /// Why SMLib refused it before. + pub why: String, +} + +/// A face SMLib refuses that the repair could not rebuild. +#[derive(Clone, Debug, PartialEq)] +pub struct RefusedFace { + pub face: usize, + pub surface: SurfaceKind, + pub why: String, +} + +/// Two free edges sewn into one. +#[derive(Clone, Debug, PartialEq)] +pub struct SewnGap { + /// The faces on either side, by index before the repair. + pub faces: [usize; 2], + /// The widest distance between the two edges, mm. + pub gap: f64, + /// A point halfway along the first edge. + pub at: Vec3, +} + +/// A loop of free edges no pair explains: a face is missing there. +#[derive(Clone, Debug, PartialEq)] +pub struct Hole { + /// The faces around it, by index before the repair. + pub faces: Vec, + /// A point halfway along each of its edges: Patch's `edges`. + pub edges: Vec, + /// How a patch meets the faces around it: G0 (the plane they lie in) or G1 (curved neighbours). + pub continuity: Continuity, + /// The patch was made and sewn in. + pub patched: bool, + /// Why it was not, when it was asked for. + pub why: Option, +} + +/// What a repair did. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RepairReport { + pub rebuilt: Vec, + pub refused: Vec, + pub sewn: Vec, + pub holes: Vec, + /// Faces before and after. + pub faces: [usize; 2], + /// The largest edge tolerance before and after, mm. + pub largest_edge_tolerance: [f64; 2], + /// The result is a closed solid. + pub closed: bool, + /// Whether SMLib takes the result as it is. + pub modelling: bool, +} + +impl RepairReport { + /// Whether the repair changed anything. + pub fn changed(&self) -> bool { + !self.rebuilt.is_empty() || !self.sewn.is_empty() || self.holes.iter().any(|h| h.patched) + } +} + +fn invalid(what: impl Into) -> KernelError { + KernelError::Invalid(what.into()) +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// `body` repaired as the module says, with what was done. Refused (with why) when nothing +/// applies: SMLib takes it and it has no free edges, or its only free edges bound holes and +/// `patch_holes` is off (the report's holes are then in the message). +pub fn repair(body: &Body, opts: &RepairOptions) -> Result<(Body, RepairReport)> { + let _span = solidcraft_profile::span("kernel", "repair"); + body.require_brep("repair")?; + if !(opts.gap.is_finite() && opts.gap > 0.0 && opts.gap <= 1.0) { + return Err(invalid("the gap to sew must be more than 0 and at most 1 mm")); + } + let before = body.record(); + let mut report = + RepairReport { faces: [before.faces.len(), 0], largest_edge_tolerance: [largest_tolerance(before), 0.0], ..RepairReport::default() }; + + // 1. Faces SMLib refuses on their own, rebuilt from their surfaces. + let mut record = before.clone(); + if body.smlib().is_err() { + rebuild_refused(&mut record, &mut report)?; + } + let mut current = if report.rebuilt.is_empty() { body.clone() } else { Body::from_record(record)?.with_color(body.color()) }; + if !report.refused.is_empty() && current.smlib().is_err() { + // SMLib still refuses the part: nothing can be sewn or patched (both are SMLib's). The + // faces rebuilt are kept, and the report names the ones left. + let list: Vec = report.refused.iter().map(|r| format!("face {} ({:?}): {}", r.face + 1, r.surface, r.why)).collect(); + if report.rebuilt.is_empty() { + return Err(KernelError::Failed(format!("SMLib refuses faces the repair cannot rebuild: {}", list.join("; ")))); + } + let r = current.record(); + report.holes = loops_of(r, &free_edges(r)?).iter().map(|l| hole(r, l)).collect(); + report.faces[1] = r.faces.len(); + report.largest_edge_tolerance[1] = largest_tolerance(r); + report.closed = false; + report.modelling = false; + return Ok((current, report)); + } + + // 2. and 3. The free edges: pairs within the gap, and loops of the rest. + let free = free_edges(current.record())?; + let pairs = pair_up(current.record(), &free, opts.gap); + let paired: std::collections::HashSet = pairs.iter().flat_map(|p| [p.edges[0], p.edges[1]]).collect(); + let rest: Vec = free.iter().copied().filter(|e| !paired.contains(e)).collect(); + let loops = loops_of(current.record(), &rest); + for l in &loops { + report.holes.push(hole(current.record(), l)); + } + for p in &pairs { + report.sewn.push(SewnGap { faces: p.faces, gap: p.gap, at: p.at }); + } + if !pairs.is_empty() { + let widest = pairs.iter().map(|p| p.gap).fold(0.0, f64::max); + // SMLib glues the lamina pairs within the stitch tolerance: just past the widest pair, so + // each of them glues and nothing farther apart does. + let tol = (widest * 1.05).max(current.record().tolerance * 2.0); + current = crate::surfaces::stitch_no_worse(&[¤t], tol, &TOLERANCE_BOUND_TESTS)?; + } + if opts.patch_holes && !report.holes.is_empty() { + current = patch_holes(current, &mut report.holes)?; + } + if !report.changed() { + let holes: Vec = report + .holes + .iter() + .map(|h| { + format!( + "a loop of {} edges around faces {}", + h.edges.len(), + h.faces.iter().map(|f| (f + 1).to_string()).collect::>().join(", ") + ) + }) + .collect(); + return Err(invalid(if holes.is_empty() { + "nothing to repair: SMLib takes the part and it has no gaps or holes".to_string() + } else { + format!("nothing sewn: the free edges bound holes ({}); patch them to close the part", holes.join("; ")) + })); + } + let after = current.record(); + report.faces[1] = after.faces.len(); + report.largest_edge_tolerance[1] = largest_tolerance(after); + report.closed = !after.faces.is_empty() && after.edges.iter().all(|e| e.uses.len() >= 2); + report.modelling = current.smlib().is_ok(); + Ok((current, report)) +} + +fn largest_tolerance(r: &Brep) -> f64 { + r.edges.iter().map(|e| e.tolerance).fold(r.tolerance, f64::max) +} + +// ---- 1. Faces SMLib refuses ------------------------------------------------------------- + +/// Whether SMLib takes face `f` of `r` on its own; `Err` with SMLib's reason when it does not. +fn alone(r: &Brep, f: usize) -> Result> { + let one = crate::surfaces::Parts::of(r, &[(f, false)])?.canonical()?; + Ok(solidcraft_smlib::Brep::from_record(&one.brep, true).map(|_| ()).map_err(|e| e.to_string())) +} + +/// Every face of `record` SMLib refuses on its own, rebuilt where its surface allows (into +/// `report.rebuilt`), else listed (`report.refused`). +fn rebuild_refused(record: &mut Brep, report: &mut RepairReport) -> Result<()> { + if record.faces.len() > MAX_FACE_PROBES { + return Err(KernelError::TooLarge(format!("a part of {} faces (the repair looks at most {MAX_FACE_PROBES})", record.faces.len()))); + } + for f in 0..record.faces.len() { + let Err(why) = alone(record, f)? else { continue }; + let Some(face) = record.faces.get(f) else { continue }; + let surface = SurfaceKind::of(&face.surface); + match rebuilt_face(record, f) { + Ok(Some(face)) => { + let mut trial = record.clone(); + if let Some(slot) = trial.faces.get_mut(f) { + *slot = face; + } + match alone(&trial, f)? { + Ok(()) => { + *record = trial; + report.rebuilt.push(RebuiltFace { face: f, surface, why }); + } + Err(still) => { + report.refused.push(RefusedFace { face: f, surface, why: format!("{why}; rebuilt on its own surface, still: {still}") }) + } + } + } + Ok(None) => report.refused.push(RefusedFace { face: f, surface, why }), + Err(e) => report.refused.push(RefusedFace { face: f, surface, why: format!("{why}; not rebuilt: {e}") }), + } + } + Ok(()) +} + +/// Face `f` of `r` rebuilt on its own surface: a cylinder, cone, sphere or torus face on a +/// NURBS form of the surface laid on arcs from where the face starts +/// ([`solidcraft_geom::brep::form::surface_on_own_arcs`]) instead of its frame's quarter grid, the same surface +/// exactly, with SMLib's own trims of the face's edges on it (`SmlibTrims`, as the import makes the +/// trims it has no closed form for). The face's edges and loops stay as they were. `None` for a +/// face on another surface. +fn rebuilt_face(r: &Brep, f: usize) -> Result> { + use solidcraft_geom::brep::pcurve::{TrimEdge, TrimFace, TrimUse, Trims}; + let face = r.faces.get(f).ok_or_else(|| invalid(format!("no face {f}")))?; + if !matches!(face.surface, b::Surface::Cylinder { .. } | b::Surface::Cone { .. } | b::Surface::Sphere { .. } | b::Surface::Torus { .. }) { + return Ok(None); + } + // The face's edges and vertices, numbered here as the trim face takes them. + let mut local: Vec = Vec::new(); + let mut vertices: Vec = Vec::new(); + let mut loops = Vec::with_capacity(face.loops.len()); + let mut boundary = Vec::with_capacity(face.loops.len()); + for l in &face.loops { + let b::Loop::Edges { edges } = l else { return Ok(None) }; + let mut uses = Vec::with_capacity(edges.len()); + let mut lb = Vec::with_capacity(edges.len()); + for u in edges { + let e = r.edges.get(u.edge as usize).ok_or_else(|| invalid(format!("no edge {}", u.edge)))?; + let k = match local.iter().position(|&x| x == u.edge) { + Some(k) => k, + None => { + local.push(u.edge); + local.len() - 1 + } + }; + uses.push(TrimUse { edge: u32::try_from(k).map_err(|_| invalid("too many edges"))?, forward: u.forward, pcurve: None }); + lb.push((&e.curve, e.interval, u.forward)); + } + loops.push(uses); + boundary.push(lb); + } + let mut edges = Vec::with_capacity(local.len()); + for &e in &local { + let edge = r.edges.get(e as usize).ok_or_else(|| invalid(format!("no edge {e}")))?; + let mut ends = [0u32; 2]; + for (end, v) in ends.iter_mut().zip(edge.vertices) { + let k = match vertices.iter().position(|&x| x == v) { + Some(k) => k, + None => { + vertices.push(v); + vertices.len() - 1 + } + }; + *end = u32::try_from(k).map_err(|_| invalid("too many vertices"))?; + } + edges.push(TrimEdge { curve: &edge.curve, nurbs: edge.nurbs.as_ref(), interval: edge.interval, vertices: ends, tolerance: edge.tolerance }); + } + let points = vertices + .iter() + .map(|&v| r.vertices.get(v as usize).map(|v| v.point).ok_or_else(|| invalid(format!("no vertex {v}")))) + .collect::>>()?; + let extent = solidcraft_geom::brep::form::extent(&face.surface, &boundary).ok_or_else(|| invalid("its boundary does not lie on its surface"))?; + let (form, domain) = solidcraft_geom::brep::form::surface_on_own_arcs( + &face.surface, + extent, + local.iter().filter_map(|&e| r.edges.get(e as usize)).map(|e| e.tolerance).fold(r.tolerance, f64::max), + ) + .ok_or_else(|| invalid("no NURBS form of its surface over its boundary"))?; + let trim = TrimFace { surface: &face.surface, nurbs: Some(&form), domain, edges, vertices: points, loops, tolerance: r.tolerance }; + let pcurves = solidcraft_smlib::pcurves::SmlibTrims.trims(&trim).map_err(KernelError::Failed)?; + let mut out = face.clone(); + out.nurbs = Some(form); + out.domain = domain; + let mut it = pcurves.into_iter(); + for l in &mut out.loops { + let b::Loop::Edges { edges } = l else { continue }; + let pcs = it.next().ok_or_else(|| invalid("pcurves of a loop"))?; + for (u, pc) in edges.iter_mut().zip(pcs) { + u.pcurve = pc; + } + } + Ok(Some(out)) +} + +// ---- 2. Gaps ---------------------------------------------------------------------------- + +/// The edges of `r` only one face uses. +fn free_edges(r: &Brep) -> Result> { + let free: Vec = + (0..r.edges.len()).filter(|&e| r.edges.get(e).is_some_and(|e| e.uses.len() == 1)).filter_map(|e| u32::try_from(e).ok()).collect(); + if free.len() > MAX_FREE_EDGES { + return Err(KernelError::TooLarge(format!("a part with {} free edges (the repair pairs at most {MAX_FREE_EDGES})", free.len()))); + } + Ok(free) +} + +/// Two free edges within the gap of each other. +struct Pair { + edges: [u32; 2], + faces: [usize; 2], + gap: f64, + at: Vec3, +} + +/// An edge's points, evenly in its parameter (ends included). +fn points(r: &Brep, e: u32, n: usize) -> Vec { + let Some(edge) = r.edges.get(e as usize) else { return Vec::new() }; + let Ok(c) = CurveEval::new(edge.parameters()) else { return Vec::new() }; + let [t0, t1] = edge.interval; + (0..=n).filter_map(|k| c.point(t0 + (t1 - t0) * k as f64 / n as f64)).collect() +} + +/// The widest distance from a point of edge `a` to edge `b` (each of `a`'s points to its nearest +/// point on `b`), `None` where `b` cannot be evaluated. +fn reach(r: &Brep, a: &[Vec3], b: u32) -> Option { + let edge = r.edges.get(b as usize)?; + let c = CurveEval::new(edge.parameters()).ok()?; + let ends = [c.point(edge.interval[0])?, c.point(edge.interval[1])?]; + a.iter() + .map(|p| { + let inside = crate::surfaces::nearest_parameter(&c, edge.interval, *p).map_or(f64::INFINITY, |(_, d)| d); + inside.min(ends[0].dist(*p)).min(ends[1].dist(*p)) + }) + .try_fold(0.0f64, |m, d| d.is_finite().then_some(m.max(d))) +} + +/// The free edges that pair up within `gap`, both ways (each edge's every point near the other), +/// each edge in at most one pair: the closest pairs first. An edge of a face with itself is not +/// a gap. +fn pair_up(r: &Brep, free: &[u32], gap: f64) -> Vec { + let samples: Vec> = free.iter().map(|&e| points(r, e, GAP_SAMPLES)).collect(); + let boxes: Vec> = samples + .iter() + .map(|s| { + let first = *s.first()?; + Some(s.iter().fold((first, first), |(lo, hi), p| (lo.min(*p), hi.max(*p)))) + }) + .collect(); + let face = |e: u32| r.edges.get(e as usize).and_then(|e| e.uses.first()).map(|u| u.face as usize); + let mut candidates = Vec::new(); + for i in 0..free.len() { + for j in i + 1..free.len() { + let (Some(&a), Some(&b)) = (free.get(i), free.get(j)) else { continue }; + let (Some(Some((alo, ahi))), Some(Some((blo, bhi)))) = (boxes.get(i), boxes.get(j)) else { continue }; + let apart = (blo.x - ahi.x).max(alo.x - bhi.x).max(blo.y - ahi.y).max(alo.y - bhi.y).max(blo.z - ahi.z).max(alo.z - bhi.z); + if apart > gap || face(a) == face(b) { + continue; + } + let (Some(sa), Some(sb)) = (samples.get(i), samples.get(j)) else { continue }; + let Some(d) = reach(r, sa, b).zip(reach(r, sb, a)).map(|(x, y)| x.max(y)) else { continue }; + if d <= gap { + candidates.push((d, a, b)); + } + } + } + candidates.sort_by(|x, y| x.0.total_cmp(&y.0)); + let mut taken = std::collections::HashSet::new(); + let mut out = Vec::new(); + for (d, a, b) in candidates { + if taken.contains(&a) || taken.contains(&b) { + continue; + } + let (Some(fa), Some(fb)) = (face(a), face(b)) else { continue }; + taken.insert(a); + taken.insert(b); + let at = points(r, a, 2).get(1).copied().unwrap_or(Vec3::ZERO); + out.push(Pair { edges: [a, b], faces: [fa, fb], gap: d, at }); + } + out +} + +// ---- 3. Holes --------------------------------------------------------------------------- + +/// The edges `rest` of `r` in chains joined at shared vertices: each a loop around a hole (or an +/// open run where the boundary does not close). +fn loops_of(r: &Brep, rest: &[u32]) -> Vec> { + let mut by_vertex: std::collections::HashMap> = std::collections::HashMap::new(); + for &e in rest { + if let Some(edge) = r.edges.get(e as usize) { + for v in edge.vertices { + by_vertex.entry(v).or_default().push(e); + } + } + } + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::new(); + for &start in rest { + if !seen.insert(start) { + continue; + } + let mut chain = vec![start]; + let mut stack = vec![start]; + while let Some(e) = stack.pop() { + let Some(edge) = r.edges.get(e as usize) else { continue }; + for v in edge.vertices { + for &n in by_vertex.get(&v).into_iter().flatten() { + if seen.insert(n) { + chain.push(n); + stack.push(n); + } + } + } + } + out.push(chain); + } + out +} + +/// The hole a loop of free edges bounds, and how a patch would meet the faces around it: flat +/// (the loop's plane) when the loop is planar and every face around it is a plane, else tangent +/// to them. +fn hole(r: &Brep, edges: &[u32]) -> Hole { + let mut faces: Vec = edges.iter().filter_map(|&e| r.edges.get(e as usize)?.uses.first().map(|u| u.face as usize)).collect(); + faces.sort_unstable(); + faces.dedup(); + let at: Vec = edges.iter().filter_map(|&e| points(r, e, 2).get(1).copied()).collect(); + let along: Vec = edges.iter().flat_map(|&e| points(r, e, 8)).collect(); + let tol = edges.iter().filter_map(|&e| r.edges.get(e as usize)).map(|e| e.tolerance).fold(r.tolerance, f64::max); + let planes = faces.iter().all(|&f| r.faces.get(f).is_some_and(|face| plane_of(&face.surface).is_some())); + let flat = planes && plane_through(&along).is_some_and(|(o, n)| along.iter().all(|p| (*p - o).dot(n).abs() <= tol)); + Hole { faces, edges: at, continuity: if flat { Continuity::G0 } else { Continuity::G1 }, patched: false, why: None } +} + +/// The plane of a closed polygon's points (Newell's normal, through their centroid); `None` +/// where they enclose no area. +fn plane_through(pts: &[Vec3]) -> Option<(Vec3, Vec3)> { + let n = pts.len(); + if n < 3 { + return None; + } + let c = pts.iter().fold(Vec3::ZERO, |s, p| s + *p) * (1.0 / n as f64); + let normal = (0..n).filter_map(|i| Some((pts.get(i)?, pts.get((i + 1) % n)?))).fold(Vec3::ZERO, |s, (p, q)| s + (*p - c).cross(*q - c)); + Some((c, normal.normalized()?)) +} + +/// A plane surface's point and unit normal. +fn plane_of(s: &b::Surface) -> Option<(Vec3, Vec3)> { + let (o, u, v) = match s { + b::Surface::Plane { origin, u_axis, v_axis } => (v3(*origin), v3(*u_axis), v3(*v_axis)), + b::Surface::PlaneThrough { origin, u_point, v_point } => (v3(*origin), v3(*u_point) - v3(*origin), v3(*v_point) - v3(*origin)), + _ => return None, + }; + Some((o, u.cross(v).normalized()?)) +} + +/// `body` with each hole patched (Patch on its loop, at its continuity) and the patches sewn in +/// along the hole's own edges; a hole whose patch fails keeps why. +fn patch_holes(body: Body, holes: &mut [Hole]) -> Result { + let mut patches = Vec::new(); + let mut tol = body.record().tolerance; + for h in holes.iter_mut() { + let spec = crate::PatchSpec { continuity: h.continuity, ..crate::PatchSpec::default() }; + match crate::patch_edges_with(&body, &h.edges, &spec) { + Ok(p) => { + tol = tol.max(largest_tolerance(p.record())); + patches.push(p); + h.patched = true; + } + Err(e) => h.why = Some(e.to_string()), + } + } + if patches.is_empty() { + return Ok(body); + } + let mut all: Vec<&Body> = vec![&body]; + all.extend(patches.iter()); + // A patch's edges are the hole's own: they meet within those edges' tolerances. + crate::surfaces::stitch_no_worse(&all, tol * 2.0, &TOLERANCE_BOUND_TESTS) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{box_solid, copy_faces, measure, stitch, transform}; + + /// The six faces of a 10 × 20 × 30 box, each its own surface body: bottom, top, then the sides. + fn box_faces() -> Vec { + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); + [[5.0, 10.0, 0.0], [5.0, 10.0, 30.0], [0.0, 10.0, 15.0], [10.0, 10.0, 15.0], [5.0, 0.0, 15.0], [5.0, 20.0, 15.0]] + .iter() + .map(|p| copy_faces(&b, &[v3(*p)]).unwrap()) + .collect() + } + + /// The box without its top: an open part with a hole the four sides and their plane bound. + fn open_box(faces: &[Body]) -> Body { + stitch(&[&faces[0], &faces[2], &faces[3], &faces[4], &faces[5]], 0.0).unwrap() + } + + #[test] + fn a_gap_between_faces_is_sewn_each_sewn_edge_carrying_its_gap() { + let faces = box_faces(); + let open = open_box(&faces); + // The lid 0.05 mm above the walls: one part of six faces whose top edges pair up 0.05 apart. + let lid = transform(&faces[1], Vec3::new(0.0, 0.0, 0.05), Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap(); + let part = stitch(&[&open, &lid], 1e-6).unwrap(); + assert_eq!(part.record().edges.iter().filter(|e| e.uses.len() == 1).count(), 8, "the gap's edges are free"); + let opts = RepairOptions { gap: 0.1, patch_holes: false }; + let (fixed, report) = repair(&part, &opts).unwrap(); + assert_eq!(report.sewn.len(), 4, "{report:?}"); + assert!(report.sewn.iter().all(|g| (g.gap - 0.05).abs() < 1e-6), "{report:?}"); + assert!(report.holes.is_empty() && report.rebuilt.is_empty()); + assert!(report.closed && report.modelling, "{report:?}"); + assert_eq!(report.faces, [6, 6]); + let volume = measure(&fixed).unwrap().volume; + assert!((6000.0..=6010.0).contains(&volume), "{volume}"); + // Only the four sewn edges carry the gap; the body's tolerance and every other edge's + // stay SMLib's own. + let r = fixed.record(); + assert_eq!(r.tolerance, part.record().tolerance); + let loose: Vec = r.edges.iter().map(|e| e.tolerance).filter(|t| *t > 0.01).collect(); + assert_eq!(loose.len(), 4, "{loose:?}"); + assert!(loose.iter().all(|t| *t >= 0.05 && *t <= 0.25), "{loose:?}"); + // A gap wider than asked for is not sewn: the free edges then bound holes. + let err = repair(&part, &RepairOptions { gap: 0.01, patch_holes: false }).unwrap_err().to_string(); + assert!(err.contains("nothing sewn"), "{err}"); + } + + #[test] + fn a_hole_is_offered_then_patched_flat_in_the_plane_around_it() { + let open = open_box(&box_faces()); + let opts = RepairOptions { gap: 0.2, patch_holes: false }; + let err = repair(&open, &opts).unwrap_err().to_string(); + assert!(err.contains("a loop of 4 edges"), "{err}"); + // Planar walls around a planar loop: the patch is the loop's plane. + let (fixed, report) = repair(&open, &RepairOptions { patch_holes: true, ..opts }).unwrap(); + let [hole] = report.holes.as_slice() else { panic!("{report:?}") }; + assert_eq!((hole.faces.len(), hole.edges.len(), hole.continuity, hole.patched), (4, 4, Continuity::G0, true), "{hole:?}"); + assert!(report.closed && report.modelling, "{report:?}"); + assert_eq!(report.faces, [5, 6]); + assert!((measure(&fixed).unwrap().volume - 6000.0).abs() < 1e-6); + } + + #[test] + fn a_part_with_nothing_to_repair_is_refused_with_why() { + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); + let err = repair(&b, &RepairOptions { gap: 0.2, patch_holes: true }).unwrap_err().to_string(); + assert!(err.contains("nothing to repair"), "{err}"); + for gap in [0.0, -1.0, 2.0, f64::NAN, f64::INFINITY] { + assert!(repair(&b, &RepairOptions { gap, patch_holes: false }).is_err(), "{gap}"); + } + } +} diff --git a/crates/kernel/src/seam_faces.rs b/crates/kernel/src/seam_faces.rs deleted file mode 100644 index 1aa38212e..000000000 --- a/crates/kernel/src/seam_faces.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! Faces that run along a seam edge twice: a whole turn of a cylinder or a cone bounded by one -//! wire, as STEP files write them (the wire goes round one end, along the seam, round the other -//! end and back along the seam). SolidCraft builds its own round faces in pieces with no such -//! seam, and a boolean that has to divide one of these faces can fail where the same bodies with -//! the face in two halves work: an intersection loop lying wholly inside the face is a hole in a -//! piece whose outer wire visits the seam's vertices twice, which the boolean refuses. So when the -//! first tries at the boolean of the bodies as they are fail, each such face is split in two along -//! a plane through its axis, a quarter turn either side of the seam (the solids are unchanged), and -//! the boolean is asked again; the result's history is composed back over the operands as they -//! were given. - -use solidcraft_geom::{Plane, Vec3}; - -use crate::body::{Body, from_p3}; -use crate::boolean_record as recorded; -use crate::history::History; -use crate::splitface::{SplitTool, split_any}; -use crate::{BoolOp, FaceSurface, Result, face_surface}; - -/// Most faces split before the boolean. -const MAX_SPLITS: usize = 64; - -thread_local! { - /// Set while the boolean of the split bodies runs (no second round of splitting). - static SPLITTING: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// The first face of `body` whose wire runs along a seam edge twice, on a cylinder or a cone, -/// with the plane that splits it in two: through its axis, square to the seam. -fn next_split(body: &Body) -> Option<(usize, Plane)> { - body.solid.face_iter().enumerate().find_map(|(i, face)| { - let mut seen = std::collections::HashSet::new(); - let seam = face.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).find(|e| !seen.insert(e.id()))?; - let (origin, axis) = match face_surface(body, i)? { - FaceSurface::Cylinder { origin, axis, .. } => (origin, axis), - FaceSurface::Cone { apex, axis, .. } => (apex, axis), - _ => return None, - }; - let p = from_p3(seam.front().point()); - let off = p - origin; - let radial: Vec3 = (off - axis * off.dot(axis)).normalized()?; - Some((i, Plane::from_normal(origin, radial)?)) - }) -} - -/// Whether either body has a face for [`boolean`] to split. -pub(crate) fn needed(a: &Body, b: &Body) -> bool { - !a.is_mesh() && !b.is_mesh() && !SPLITTING.with(|c| c.get()) && (next_split(a).is_some() || next_split(b).is_some()) -} - -/// Whether `body` has a face for [`one_body`] to split. -pub(crate) fn needed_one(body: &Body) -> bool { - !body.is_mesh() && !SPLITTING.with(|c| c.get()) && next_split(body).is_some() -} - -/// `body` with every face that runs along a seam edge twice split in two, and its history over -/// `body`. `None` when a split fails. -fn halved(body: &Body) -> Option<(Body, Option)> { - let (mut x, mut h) = (body.clone(), Some(History::identity(body))); - for _ in 0..MAX_SPLITS { - let Some((face, plane)) = next_split(&x) else { return Some((x, h)) }; - let (mut done, _) = split_any(&x, &[face], &SplitTool::Plane(plane)).ok()?; - // The split is no authored boundary: a later feature may still merge what it separates. - done.regularization_protected = x.regularization_protected; - let through = recorded::through(&done, 0, h.as_ref()); - (x, h) = (done, through); - } - next_split(&x).is_none().then_some((x, h)) -} - -/// The boolean `op` of `a` and `b` with their faces that run along a seam edge twice split in -/// two, `run` doing the boolean of the split bodies. `None` when neither body has such a face, a -/// split fails, or the boolean of the split bodies gave no (checked) result: the caller then -/// keeps what it had. -pub(crate) fn boolean(a: &Body, b: &Body, op: BoolOp, run: &dyn Fn(&Body, &Body, BoolOp) -> Result>) -> Option>> { - if !needed(a, b) { - return None; - } - let ((x, hx), (y, hy)) = (halved(a)?, halved(b)?); - SPLITTING.with(|c| c.set(true)); - let result = crate::guard("boolean of faces split off their seams", || run(&x, &y, op)); - SPLITTING.with(|c| c.set(false)); - let Ok(result) = result else { return None }; - // Held to what a boolean can do, as a retry's result is (see `boolean_guard`). - crate::boolean_guard::check_retry(a, b, op, result.as_ref()).ok()?; - let counts = crate::record::counts(&[a, b]); - Some(Ok(result.map(|body| { - // Each step's history over the operands `[a, b]`. - let history = recorded::of_pair(&body, &recorded::placed(hx.clone(), 0, 2), &recorded::placed(hy.clone(), 1, 2)); - body.with_checked_history(history, &counts) - }))) -} - -/// `run` over `body` with every face that runs along a seam edge twice split in two, for an -/// operation that takes one body. `None` when the body has no such face, a split fails, or the -/// run over the split body fails: the caller then keeps the error it had. -/// -/// The same answer as [`boolean`] gives, for the same reason — an operation that has to divide -/// such a face can fail where the body with the face in two halves works — and it matters most -/// to a body read from a STEP file, which is where a whole-turn face comes from. The result's -/// history is composed back over `body` as it was given, so a caller that knows `body`'s faces -/// still recognises them: the split is no authored boundary. -pub(crate) fn one_body(body: &Body, what: &str, run: &dyn Fn(&Body) -> Result) -> Option> { - if !needed_one(body) { - return None; - } - let (split, over) = halved(body)?; - SPLITTING.with(|c| c.set(true)); - let result = crate::guard(what, || run(&split)); - SPLITTING.with(|c| c.set(false)); - let out = result.ok()?; - let history = recorded::through(&out, 0, over.as_ref()); - Some(Ok(out.with_checked_history(history, &crate::record::counts(&[body])))) -} - -#[cfg(test)] -#[path = "seam_faces_tests.rs"] -mod tests; diff --git a/crates/kernel/src/seam_faces_tests.rs b/crates/kernel/src/seam_faces_tests.rs index e93145fb4..80cd8c736 100644 --- a/crates/kernel/src/seam_faces_tests.rs +++ b/crates/kernel/src/seam_faces_tests.rs @@ -1,8 +1,7 @@ //! Round faces read from STEP: a whole turn bounded by one wire that runs along its seam twice. -//! A boolean whose intersection loop lies wholly inside such a face takes it in two halves -//! (exactly), where it used to end in a nudged tool or fail. +//! A boolean whose intersection loop lies wholly inside such a face is exact. use crate::*; -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use std::f64::consts::PI; const R: f64 = 4.5; @@ -38,53 +37,9 @@ fn pressed_volume() -> f64 { 10.0 * segment } -/// The boolean, which must be exact: no retry that moves the tool or ignores part of where the -/// bodies meet. +/// The boolean, which must succeed (SMLib's, exact: there is no other). fn exact(a: &Body, b: &Body, op: BoolOp) -> Option { - let (r, report) = capture_boolean_diagnostics(|| boolean(a, b, op)); - assert!(report.warning().is_none(), "{op:?}: {:?}", report.warning()); - r.unwrap() -} - -#[test] -fn a_pin_read_from_step_has_one_face_along_its_seam() { - let read = through_step(&pin()); - assert_eq!(read.face_count(), 3); - assert!(super::needed(&read, &block())); - assert!(!super::needed(&pin(), &block())); - // Split in two halves, with the same solid. - let (halved, history) = super::halved(&read).unwrap(); - assert!(super::next_split(&halved).is_none() && halved.face_count() > 3); - assert!(history.is_some()); - assert!(rel(volume(&halved), PI * R * R * 40.0) < 1e-3); -} - -/// Offset Face on a body read from STEP, where the hole's wall is one face along its seam. -/// -/// Healing such a body, which Offset Face does before it moves anything, fails inside `truck` -/// ("This wire is not simple"), so the top could not be moved at all — and importing is how a -/// part with a hole usually arrives. The offset now splits the face off its seam and asks again, -/// as a boolean does. -#[test] -fn the_top_of_a_read_block_with_a_hole_moves() { - // A 20 x 20 x 10 block with a 6 mm hole through the middle of it. - let block = box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 10.0)).unwrap(); - let drill = cylinder(Vec3::new(10.0, 10.0, -5.0), Vec3::Z, 3.0, 20.0).unwrap(); - let built = boolean(&block, &drill, BoolOp::Cut).unwrap().unwrap(); - let read = through_step(&built); - // Read back, the hole's wall is one whole turn instead of the two halves it was built as. - assert!(read.face_count() < built.face_count()); - assert!(super::needed_one(&read) && !super::needed_one(&built)); - - // The top, 2 mm up: the part grows by the plate's section, the hole still through it. - let section = 400.0 - PI * 9.0; - let moved = offset_faces(&read, &[Vec3::new(5.0, 5.0, 10.0)], 2.0).unwrap(); - assert!(rel(volume(&moved), volume(&read) + section * 2.0) < 1e-3, "{} {}", volume(&moved), volume(&read) + section * 2.0); - // The same answer as moving the built body's top, which never needed the split. - let straight = offset_faces(&built, &[Vec3::new(5.0, 5.0, 10.0)], 2.0).unwrap(); - assert!(rel(volume(&moved), volume(&straight)) < 1e-5, "{} {}", volume(&moved), volume(&straight)); - // And the faces still say where they came from, so names and sketches survive the retry. - assert!(moved.history().is_some()); + boolean(a, b, op).unwrap() } #[test] @@ -114,7 +69,6 @@ fn a_block_pressed_into_a_read_cones_side_matches_the_built_cone() { Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(8.0, 0.0), Vec2::new(5.0, 20.0), Vec2::new(0.0, 20.0)]), holes: vec![] }; let cone = revolve(&Plane::YZ, &[outline], Vec2::ZERO, Vec2::Y, 2.0 * PI).unwrap().pop().unwrap(); let read = through_step(&cone); - assert!(super::needed(&read, &cone)); let block = box_solid(Vec3::new(-2.0, 4.0, 6.0), Vec3::new(2.0, 12.0, 12.0)).unwrap(); let built = volume(&boolean(&cone, &block, BoolOp::Intersect).unwrap().unwrap()); let read = volume(&exact(&read, &block, BoolOp::Intersect).unwrap()); diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rs index ce9123dcb..85372dfdb 100644 --- a/crates/kernel/src/sew.rs +++ b/crates/kernel/src/sew.rs @@ -4,15 +4,23 @@ //! Bézier chains). Vertices and edges at the same places are shared, so the faces close into //! one shell without booleans — for solids whose faces are known exactly, such as folded //! sheet metal. +//! +//! The faces are assembled into a schema 4 record with exactly the topology the descriptions +//! give ([`assemble`]: shared edges, shells, regions, canonical order), which SMLib builds the +//! body from. No tolerance stitching is involved: two sheets of material meeting along one +//! geometric edge keep an edge each. +use solidcraft_geom::prelude::*; use std::collections::HashMap; use std::sync::Arc; -use mt::builder; -use solidcraft_geom::{Ring, Vec3}; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self as b, Curve2}; +use solidcraft_geom::Ring; +use solidcraft_geom::brep::eval::{SurfaceEval, face_flux}; +use solidcraft_geom::brep::pcurve; -use crate::body::{Body, Solid, p3, v3}; +use crate::body::Body; use crate::{KernelError, Result, guard}; /// Most control points of one Bézier chain edge. @@ -219,77 +227,526 @@ fn welded(faces: &[FaceSpec]) -> Option> { ) } -#[derive(Default)] -struct Cache { - /// Vertices by point and fan (see [`corner_fans`]). - verts: HashMap<(Key, usize), mt::Vertex>, - edges: HashMap<(Key, usize, Key, usize, Option, usize), mt::Edge>, +fn arr(p: Vec3) -> [f64; 3] { + [p.x, p.y, p.z] } -impl Cache { - fn vertex(&mut self, p: Vec3, fan: usize) -> mt::Vertex { - self.verts.entry((key(p), fan)).or_insert_with(|| builder::vertex(p3(p))).clone() +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// The vertices and edges of the faces being sewn, shared by key. +#[derive(Default)] +struct Builder { + vertices: Vec<[f64; 3]>, + /// Vertices by point and fan (see [`corner_fans`]). + verts: HashMap<(Key, usize), u32>, + edges: Vec, + by_key: HashMap<(Key, usize, Key, usize, Option, usize), u32>, +} + +impl Builder { + fn vertex(&mut self, p: Vec3, fan: usize) -> Result { + if let Some(v) = self.verts.get(&(key(p), fan)) { + return Ok(*v); + } + let v = u32::try_from(self.vertices.len()).map_err(|_| KernelError::Invalid("sew: vertex budget exceeded".into()))?; + self.vertices.push(arr(p)); + self.verts.insert((key(p), fan), v); + Ok(v) } - /// The edge `e` on boundary sheet `sheet`, between the vertices of fans `fans` at its ends. - fn edge(&mut self, e: &EdgeSpec, sheet: usize, (fa, fb): (usize, usize)) -> Result { + + fn point(&self, v: u32) -> Vec3 { + self.vertices.get(v as usize).copied().map_or(Vec3::ZERO, v3) + } + + /// Where the vertex at `p` is (the first point met in its cell), `p` itself before any. + fn at(&self, p: Vec3) -> Vec3 { + self.verts.get(&(key(p), 0)).map_or(p, |v| self.point(*v)) + } + + /// The edge `e` on boundary sheet `sheet`, between the vertices of fans `fans` at its ends, + /// and whether `e` runs along it. + fn edge(&mut self, e: &EdgeSpec, sheet: usize, (fa, fb): (usize, usize)) -> Result<(u32, bool)> { let (a, b) = e.ends(); let mid = e.mid_key(); let (ka, kb) = (key(a), key(b)); - if let Some(found) = self.edges.get(&(ka, fa, kb, fb, mid, sheet)) { - return Ok(found.clone()); + if let Some(found) = self.by_key.get(&(ka, fa, kb, fb, mid, sheet)) { + return Ok((*found, true)); } - if let Some(found) = self.edges.get(&(kb, fb, ka, fa, mid, sheet)) { - return Ok(found.inverse()); + if let Some(found) = self.by_key.get(&(kb, fb, ka, fa, mid, sheet)) { + return Ok((*found, false)); } - let (va, vb) = (self.vertex(a, fa), self.vertex(b, fb)); - let made = match e { - EdgeSpec::Line { .. } => builder::line(&va, &vb), - EdgeSpec::Arc { mid, .. } => arc_edge(&va, &vb, *mid), + let (va, vb) = (self.vertex(a, fa)?, self.vertex(b, fb)?); + let (pa, pb) = (self.point(va), self.point(vb)); + let (curve, interval) = match e { + EdgeSpec::Line { .. } => (b::Curve::Line { start: arr(pa), end: arr(pb) }, [0.0, 1.0]), + EdgeSpec::Arc { mid, .. } => arc_curve(pa, pb, *mid)?, EdgeSpec::Chain { .. } => { - let curve = self.chain(e)?; - mt::Edge::try_new(&va, &vb, mt::Curve::BSplineCurve(curve)).map_err(|e| KernelError::Failed(format!("sew: chain edge: {e}")))? + let (knots, points) = chain(e, pa, pb)?; + let n = knots.last().copied().unwrap_or(1.0); + (b::Curve::Spline { knots, points }, [0.0, n]) } }; - self.edges.insert((ka, fa, kb, fb, mid, sheet), made.clone()); - Ok(made) + let id = u32::try_from(self.edges.len()).map_err(|_| KernelError::Invalid("sew: edge budget exceeded".into()))?; + self.edges.push(PartEdge { nurbs: None, curve, interval, vertices: [va, vb] }); + self.by_key.insert((ka, fa, kb, fb, mid, sheet), id); + Ok((id, true)) } - /// A Bézier chain as a B-spline of its degree (inner knots as many times as the degree) - /// ending on the shared vertices. - fn chain(&mut self, e: &EdgeSpec) -> Result> { - let EdgeSpec::Chain { degree, ctrl } = e else { return Err(KernelError::Invalid("sew: not a Bézier chain".into())) }; - if !e.valid() { - return Err(KernelError::Invalid("sew: a Bézier chain needs degree·n + 1 finite control points".into())); + /// The surface of face `fi` and whether its natural normal points outward; on a ruled face, + /// each use's exact pcurve is filled in. + fn surface(&self, fi: usize, f: &FaceSpec, loops: &mut [Vec], tol: f64) -> Result<(b::Surface, bool)> { + let fail = |m: &str| KernelError::Invalid(format!("sew: face {fi}: {m}")); + match &f.surface { + SurfSpec::Plane => plane_of(f).map(|s| (s, true)).ok_or_else(|| fail("cannot attach a plane to a wire that is not on one plane")), + SurfSpec::Revolved { a, b, axis_origin, axis, angle: _ } => { + let s = revolved(*a, *b, *axis_origin, *axis).map_err(|m| fail(&m))?; + Ok((s.clone(), outward(&s, f.probe))) + } + SurfSpec::Extruded { a, b, mid, dir } => { + let c = circumcentre(*a, *mid, *b).ok_or_else(|| fail("an arc through points in line"))?; + let n = (*mid - *a).cross(*b - *mid).normalized().ok_or_else(|| fail("an arc through points in line"))?; + let z = dir.normalized().ok_or_else(|| fail("an extrusion of no length"))?; + if n.cross(z).len() > 1e-9 { + return Err(fail("not supported yet: an arc wall extruded askew to its arc's axis")); + } + let x = (*a - c).normalized().ok_or_else(|| fail("an arc of no radius"))?; + let y = z.cross(x).normalized().ok_or_else(|| fail("an arc of no radius"))?; + let frame = b::Frame { origin: arr(c), x_axis: arr(x), y_axis: arr(y) }; + let s = b::Surface::Cylinder { frame, radius: a.dist(c) }; + Ok((s.clone(), outward(&s, f.probe))) + } + SurfSpec::Ruled { a, b } => { + let (ka, pa) = chain(a, self.at(a.ends().0), self.at(a.ends().1))?; + let (kb, pb) = chain(b, self.at(b.ends().0), self.at(b.ends().1))?; + let (EdgeSpec::Chain { degree: da, .. }, EdgeSpec::Chain { degree: db, .. }) = (a, b) else { + return Err(KernelError::Invalid("sew: not a Bézier chain".into())); + }; + if da != db || pa.len() != pb.len() || ka != kb { + return Err(KernelError::Invalid("sew: ruled chains differ in pieces".into())); + } + let points = pa.iter().zip(&pb).map(|(p, q)| vec![*p, *q]).collect(); + let s = b::Surface::Spline { u_knots: ka.clone(), v_knots: vec![0.0, 0.0, 1.0, 1.0], points }; + for u in loops.iter_mut().flatten() { + let e = self.edges.get(u.edge as usize).ok_or_else(|| fail("edge"))?; + u.given = Some(ruled_pcurve(e, *da, &ka, [&pa, &pb], tol).ok_or_else(|| fail("not supported yet: an edge across a ruled face"))?); + } + Ok((s.clone(), outward(&s, f.probe))) + } } - let d = *degree; - let n = (ctrl.len() - 1) / d; - let mut knots = vec![0.0; d + 1]; - for i in 1..n { - knots.extend(std::iter::repeat_n(i as f64, d)); - } - knots.extend(std::iter::repeat_n(n as f64, d + 1)); - let mut pts: Vec = ctrl.iter().map(|p| p3(*p)).collect(); - let (a, b) = e.ends(); - if let Some(first) = pts.first_mut() { - *first = self.vertex(a, 0).point(); - } - if let Some(last) = pts.last_mut() { - *last = self.vertex(b, 0).point(); - } - mt::BSplineCurve::try_new(mt::KnotVec::from(knots), pts).map_err(|e| KernelError::Failed(format!("sew: chain curve: {e}"))) } } +/// A Bézier chain as a B-spline of its degree (inner knots as many times as the degree) ending on +/// `a` and `b` (its vertices). +fn chain(e: &EdgeSpec, a: Vec3, b: Vec3) -> Result<(Vec, Vec<[f64; 3]>)> { + let EdgeSpec::Chain { degree, ctrl } = e else { return Err(KernelError::Invalid("sew: not a Bézier chain".into())) }; + if !e.valid() { + return Err(KernelError::Invalid("sew: a Bézier chain needs degree·n + 1 finite control points".into())); + } + let d = *degree; + let n = (ctrl.len() - 1) / d; + let mut knots = vec![0.0; d + 1]; + for i in 1..n { + knots.extend(std::iter::repeat_n(i as f64, d)); + } + knots.extend(std::iter::repeat_n(n as f64, d + 1)); + let mut pts: Vec<[f64; 3]> = ctrl.iter().map(|p| arr(*p)).collect(); + if let Some(first) = pts.first_mut() { + *first = arr(a); + } + if let Some(last) = pts.last_mut() { + *last = arr(b); + } + Ok((knots, pts)) +} + +/// Most Hermite pieces of a folded pcurve. +const FOLD_PIECES: usize = 1024; +/// How close, against the edge's size, a folded pcurve lifts onto its edge: as close as the +/// folded edge's own chain is to the fold (sheet metal's `BEND_CHAIN_TOL`). +const FOLD_TOL: f64 = 1e-7; + +/// The point and first three derivatives at `t` of a B-spline or NURBS curve (homogeneous +/// `[x·w, y·w, z·w, w]` points; weight 1 for a B-spline): the homogeneous derivatives `A⁽ᵏ⁾`, +/// `w⁽ᵏ⁾`, then `C⁽ᵏ⁾ = (A⁽ᵏ⁾ − Σⱼ₌₁ᵏ C(k, j) w⁽ʲ⁾ C⁽ᵏ⁻ʲ⁾) / w`. +fn curve_derivs(knots: &[f64], points: &[[f64; 4]], t: f64) -> Option<[Vec3; 4]> { + let degree = knots.len().checked_sub(points.len() + 1)?; + let (first, ders) = solidcraft_geom::bspline::basis_derivatives(knots, degree, points.len(), t, 3)?; + let (mut a, mut w) = ([Vec3::ZERO; 4], [0.0f64; 4]); + for (i, d) in ders.iter().enumerate() { + let h = points.get(first + i)?; + for k in 0..4 { + let n = d.get(k).copied().unwrap_or(0.0); + a[k] += Vec3::new(h[0], h[1], h[2]) * n; + w[k] += h[3] * n; + } + } + if !(w[0].abs() > 0.0) { + return None; + } + let mut c = [Vec3::ZERO; 4]; + for k in 0..4 { + let mut num = a[k]; + for j in 1..=k { + let binom = [[1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0], [1.0, 2.0, 1.0, 0.0], [1.0, 3.0, 3.0, 1.0]][k][j]; + num -= c[k - j] * (binom * w[j]); + } + c[k] = num * (1.0 / w[0]); + } + Some(c) +} + +/// A complex number as `(re, im)`. +type Cx = (f64, f64); + +fn cmul(p: Cx, q: Cx) -> Cx { + (p.0 * q.0 - p.1 * q.1, p.0 * q.1 + p.1 * q.0) +} + +fn cdiv(p: Cx, q: Cx) -> Cx { + let n = q.0 * q.0 + q.1 * q.1; + ((p.0 * q.0 + p.1 * q.1) / n, (p.1 * q.0 - p.0 * q.1) / n) +} + +/// The Bézier control points of the degree-7 Hermite piece on `[s0, s1]` with the values and +/// first three derivatives `p` at its start and `r` at its end (the k-th derivative of a Bézier of +/// degree 7 at an end is 7!/(7 − k)! times the k-th difference of the control points there, +/// scaled by `(s1 − s0)^k`). +fn hermite7(p: [[f64; 2]; 4], r: [[f64; 2]; 4], h: f64) -> [[f64; 2]; 8] { + let (k1, k2, k3) = (h / 7.0, h * h / 42.0, h * h * h / 210.0); + let at = |d: [[f64; 2]; 4], m: [f64; 4]| [0, 1].map(|i| d[0][i] * m[0] + d[1][i] * m[1] + d[2][i] * m[2] + d[3][i] * m[3]); + [ + p[0], + at(p, [1.0, k1, 0.0, 0.0]), + at(p, [1.0, 2.0 * k1, k2, 0.0]), + at(p, [1.0, 3.0 * k1, 3.0 * k2, k3]), + at(r, [1.0, -3.0 * k1, 3.0 * k2, -k3]), + at(r, [1.0, -2.0 * k1, k2, 0.0]), + at(r, [1.0, -k1, 0.0, 0.0]), + r[0], + ] +} + +/// The pcurve on a cylinder or cone face of a B-spline edge with no closed form there: a +/// flat-pattern edge folded across a bend, a helix, which no NURBS is (its 3D curve is already +/// degree-7 Hermite pieces of the fold). The same construction in (u, v): degree-7 Hermite pieces +/// on the edge's own parameter, matching the point and first three derivatives of its angle about +/// the axis (through the form's quarter parameter when `form` is given) and of its height along +/// the axis at each piece's ends. The pieces break where the angle crosses a quarter (the form's +/// parameter is only once differentiable there) and are halved until they lift onto the edge +/// within [`FOLD_TOL`]. An approximation by construction from exact derivatives, like the edge +/// itself; nothing is fitted. `None` for another face or curve, or past the piece budget. +fn folded_pcurve(label: &b::Surface, form: Option<&b::Surface>, curve: &b::Curve, [t0, t1]: [f64; 2]) -> Option { + use solidcraft_geom::bspline::{HPoint, bezier_point}; + use std::f64::consts::{FRAC_PI_2, FRAC_PI_8, TAU}; + let (b::Surface::Cylinder { frame, .. } | b::Surface::Cone { frame, .. }) = label else { return None }; + let (knots, points): (&[f64], Vec<[f64; 4]>) = match curve { + b::Curve::Spline { knots, points } => (knots, points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect()), + b::Curve::RationalSpline { knots, homogeneous } => (knots, homogeneous.clone()), + _ => return None, + }; + let points = points.as_slice(); + let (o, x, y) = (v3(frame.origin), v3(frame.x_axis).normalized()?, v3(frame.y_axis).normalized()?); + let z = x.cross(y).normalized()?; + let on = SurfaceEval::new(form.unwrap_or(label)).ok()?; + let edge = solidcraft_geom::brep::eval::CurveEval::new(curve).ok()?; + let raw_angle = |t: f64| -> Option { + let d = curve_derivs(knots, points, t)?[0] - o; + Some(d.dot(y).atan2(d.dot(x))) + }; + let angle_near = |t: f64, near: f64| raw_angle(t).map(|a| a + ((near - a) / TAU).round() * TAU); + // The angle's branch at the start: inside the form's u range when there is one. + let mut start = raw_angle(t0)?; + if let Some(b::Surface::RationalSpline { u_knots, .. }) = form { + let (lo, hi) = (*u_knots.first()?, *u_knots.last()?); + let inside = |a: f64| (lo - 1e-9..=hi + 1e-9).contains(&solidcraft_geom::brep::form::param(a)); + start = (-2..=2).map(|k| start + f64::from(k) * TAU).find(|a| inside(*a))?; + } + // The angle along the edge, unwrapped from its start, on a grid fine against the edge's spans. + let grid = 64 * knots.len().max(1); + let ts: Vec = (0..=grid).map(|i| t0 + (t1 - t0) * i as f64 / grid as f64).collect(); + let mut angles = Vec::with_capacity(ts.len()); + let mut prev = start; + for &t in &ts { + prev = angle_near(t, prev)?; + angles.push(prev); + } + // Breaks: the ends, and on a form each crossing of a quarter, found by bisection. + let mut breaks = vec![(t0, *angles.first()?)]; + if form.is_some() { + for i in 1..ts.len() { + let (a0, a1) = (*angles.get(i - 1)?, *angles.get(i)?); + let (q0, q1) = ((a0 / FRAC_PI_2).floor(), (a1 / FRAC_PI_2).floor()); + if q0 == q1 { + continue; + } + let target = q0.max(q1) * FRAC_PI_2; + let (mut lo, mut hi) = (*ts.get(i - 1)?, *ts.get(i)?); + for _ in 0..80 { + let mid = 0.5 * (lo + hi); + if (angle_near(mid, a0)? - target).signum() == (a0 - target).signum() { + lo = mid; + } else { + hi = mid; + } + } + breaks.push((0.5 * (lo + hi), target)); + } + } + breaks.push((t1, *angles.last()?)); + let size = points.iter().fold(1.0f64, |m, h| [h[0], h[1], h[2]].iter().fold(m, |m, c| m.max((c / h[3]).abs()))); + // A crossing within rounding of another break (or of an end), or nearer to it on the edge + // than the pcurve lifts onto the edge (`FOLD_TOL`), is that break; the end never goes into + // the start. An edge starting 3e-12 of its parameter short of a quarter had pieces 1.6e-12 + // long, whose knots SMLib took as one, past a multiplicity of the degree + 1. + let close = 1e-12 * (t1 - t0).abs().max(1.0); + let lifts = |a: f64, b: f64| matches!((edge.point(a), edge.point(b)), (Some(p), Some(q)) if p.dist(q) <= FOLD_TOL * size); + let mut kept: Vec<(f64, f64)> = Vec::with_capacity(breaks.len()); + for (i, b) in breaks.iter().enumerate() { + let is_end = i + 1 == breaks.len(); + let both_ends = is_end && kept.len() == 1; + match kept.last_mut() { + Some(last) if (b.0 - last.0).abs() <= close || (!both_ends && lifts(last.0, b.0)) => { + if is_end { + *last = *b; + } + } + _ => kept.push(*b), + } + } + let breaks = kept; + // u and v with their first three derivatives at `t`, angle `a`, in quarter `q` of the form. + let tq = FRAC_PI_8.tan(); + let uv = |t: f64, a: f64, q: f64| -> Option<[[f64; 2]; 4]> { + let c = curve_derivs(knots, points, t)?; + let w = |d: Vec3| (d.dot(x), d.dot(y)); + let (w0, r1, r2, r3) = (w(c[0] - o), w(c[1]), w(c[2]), w(c[3])); + let (r1, r2, r3) = (cdiv(r1, w0), cdiv(r2, w0), cdiv(r3, w0)); + // θ = Im log w: (log w)' = w'/w, (log w)'' = w''/w − (w'/w)², (log w)''' = w'''/w − + // 3 w''w'/w² + 2 (w'/w)³. + let a1 = r1.1; + let a2 = r2.1 - cmul(r1, r1).1; + let a3 = r3.1 - 3.0 * cmul(r2, r1).1 + 2.0 * cmul(cmul(r1, r1), r1).1; + let h = [(c[0] - o).dot(z), c[1].dot(z), c[2].dot(z), c[3].dot(z)]; + let u = if form.is_some() { + // The quarter parameter q + ½(1 + g/tan(π/8)), g = tan(ψ/2 − π/8), and its derivatives + // in θ, through to t by the chain rule. + let g = (0.5 * (a - q * FRAC_PI_2) - FRAC_PI_8).tan(); + let g1 = 0.5 * (1.0 + g * g); + let g2 = g * g1; + let g3 = g1 * g1 + g * g2; + let (f1, f2, f3) = (g1 / (2.0 * tq), g2 / (2.0 * tq), g3 / (2.0 * tq)); + [q + 0.5 * (1.0 + g / tq), f1 * a1, f2 * a1 * a1 + f1 * a2, f3 * a1 * a1 * a1 + 3.0 * f2 * a1 * a2 + f1 * a3] + } else { + [a, a1, a2, a3] + }; + Some([0, 1, 2, 3].map(|k| [u[k], h[k]])) + }; + let mut pieces = 1usize; + while pieces * breaks.len() <= FOLD_PIECES { + let mut knots2 = vec![t0; 8]; + let mut ctrl: Vec<[f64; 2]> = Vec::new(); + let mut worst = 0.0f64; + for w in breaks.windows(2) { + let (&(a, aa), &(e, ea)) = (w.first()?, w.get(1)?); + let q = (0.5 * (aa + ea) / FRAC_PI_2).floor(); + let mut last = aa; + for k in 0..pieces { + let (s0, s1) = (a + (e - a) * k as f64 / pieces as f64, a + (e - a) * (k + 1) as f64 / pieces as f64); + let (b0, b1) = (last, if k + 1 == pieces { ea } else { angle_near(s1, last)? }); + last = b1; + let piece = hermite7(uv(s0, b0, q)?, uv(s1, b1, q)?, s1 - s0); + ctrl.extend_from_slice(if ctrl.is_empty() { &piece[..] } else { &piece[1..] }); + knots2.extend(std::iter::repeat_n(s1, 7)); + let h = piece.map(|c| HPoint { x: c[0], y: c[1], z: 0.0, w: 1.0 }); + for j in 1..8 { + let f = f64::from(j) / 8.0; + let q2 = bezier_point(&h, f).project()?; + worst = worst.max(on.point([q2.x, q2.y])?.dist(edge.point(s0 + (s1 - s0) * f)?)); + } + } + } + knots2.push(t1); + if worst <= FOLD_TOL * size { + return Some(Curve2::Spline { knots: knots2, points: ctrl }); + } + pieces *= 2; + } + None +} + +/// The exact pcurve of an edge of a ruled face `(1 − v)·A(u) + v·B(u)` (`rows` its chains A and +/// B, of `degree` on `knots`): a chain lying on A or B either way round is `(u(t), 0 or 1)` with +/// `u` affine in its parameter, and a line from a corner of A to the corner of B at the same `u` +/// is a ruling, `(u, t)`. `None` for any other edge. +fn ruled_pcurve(e: &PartEdge, degree: usize, knots: &[f64], rows: [&[[f64; 3]]; 2], tol: f64) -> Option { + let near = |p: &[f64; 3], q: &[f64; 3]| v3(*p).dist(v3(*q)) <= tol; + let n = *knots.last()?; + match &e.curve { + b::Curve::Spline { knots: ek, points } if ek.as_slice() == knots => { + for (v, row) in [0.0, 1.0].into_iter().zip(rows) { + if row.len() != points.len() { + continue; + } + let forward = points.iter().zip(row).all(|(p, q)| near(p, q)); + let backward = points.iter().zip(row.iter().rev()).all(|(p, q)| near(p, q)); + if forward || backward { + // Control points at the Greville abscissae give the affine u(t) exactly. + let points = (0..points.len()) + .map(|i| { + let xi = (1..=degree).map(|r| knots.get(i + r).copied().unwrap_or(0.0)).sum::() / degree as f64; + [if forward { xi } else { n - xi }, v] + }) + .collect(); + return Some(Curve2::Spline { knots: knots.to_vec(), points }); + } + } + None + } + b::Curve::Line { start, end } => { + let corner = |p: &[f64; 3]| -> Option<[f64; 2]> { + for (v, row) in [0.0, 1.0].into_iter().zip(rows) { + if row.first().is_some_and(|q| near(p, q)) { + return Some([0.0, v]); + } + if row.last().is_some_and(|q| near(p, q)) { + return Some([n, v]); + } + } + None + }; + let (s, z) = (corner(start)?, corner(end)?); + (s[0] == z[0] && s[1] != z[1]).then(|| Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![s, z] }) + } + _ => None, + } +} + +/// The plane of a face's boundary: through the mean of its control points (arcs' midpoints and +/// chains' control points included), its normal the one the outer loop runs counter-clockwise +/// about, summed about that mean (about a far origin the rounding of the sum grows with the +/// square of the distance, and turns a thin face's short normal). None when the boundary has no +/// area or leaves the plane by more than 10⁻⁶ mm. +fn plane_of(f: &FaceSpec) -> Option { + let points = |e: &EdgeSpec| -> Vec { + match e { + EdgeSpec::Line { a, b } => vec![*a, *b], + EdgeSpec::Arc { a, b, mid } => vec![*a, *mid, *b], + EdgeSpec::Chain { ctrl, .. } => ctrl.to_vec(), + } + }; + let all: Vec = f.loops.iter().flatten().flat_map(points).collect(); + let mean = all.iter().fold(Vec3::ZERO, |s, p| s + *p) * (1.0 / all.len().max(1) as f64); + let n = f.loops.first()?.iter().fold(Vec3::ZERO, |n, e| { + let p = points(e); + p.iter().zip(p.iter().skip(1)).fold(n, |n, (a, b)| n + (*a - mean).cross(*b - mean)) + }); + let n = n.normalized()?; + if !mean.is_finite() || all.iter().any(|p| ((*p - mean).dot(n)).abs() > 1e-6) { + return None; + } + let t = if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }; + let u = (t - n * t.dot(n)).normalized()?; + let v = n.cross(u).normalized()?; + Some(b::Surface::Plane { origin: arr(mean), u_axis: arr(u), v_axis: arr(v) }) +} + +/// The surface the line `a`→`b` sweeps turning about the axis: a cylinder (the line along the +/// axis), a plane (square to it) or a cone (in a plane through it). A line skew to the axis +/// sweeps a hyperboloid, which has no exact form here. +fn revolved(a: Vec3, b: Vec3, origin: Vec3, axis: Vec3) -> std::result::Result { + let k = axis.normalized().ok_or("the axis has no direction")?; + let foot = |p: Vec3| origin + k * (p - origin).dot(k); + let (ra, rb) = (a - foot(a), b - foot(b)); + let along = (b - a).dot(k); + let scale = ra.len().max(rb.len()); + if !(scale > 1e-12) { + return Err("a line along the axis sweeps no surface".into()); + } + if ra.cross(rb).len() > 1e-9 * scale * scale || ra.dot(rb) < 0.0 { + return Err("not supported yet: a face revolved from a line skew to its axis or across it".into()); + } + let x = if ra.len() >= rb.len() { ra } else { rb }.normalized().ok_or("a line on the axis")?; + let frame = |z: Vec3| -> std::result::Result { + let y = z.cross(x).normalized().ok_or("frame")?; + Ok(b::Frame { origin: arr(foot(a)), x_axis: arr(x), y_axis: arr(y) }) + }; + if along.abs() <= 1e-12 * (b - a).len() { + let y = k.cross(x).normalized().ok_or("frame")?; + return Ok(b::Surface::Plane { origin: arr(foot(a)), u_axis: arr(x), v_axis: arr(y) }); + } + let slope = (rb.len() - ra.len()) / along; + if slope.abs() <= 1e-12 { + return Ok(b::Surface::Cylinder { frame: frame(k)?, radius: ra.len() }); + } + // The cone widens along its z. + let z = if slope > 0.0 { k } else { k * -1.0 }; + Ok(b::Surface::Cone { frame: frame(z)?, radius_at_origin: ra.len(), half_angle: slope.abs().atan() }) +} + +/// Whether the surface's natural normal at the probe point faces the probe's outward +/// direction (true without a probe, or where the point cannot be found on the surface). +fn outward(surface: &b::Surface, probe: Option<(Vec3, Vec3)>) -> bool { + let Some((p, out)) = probe else { return true }; + let Ok(s) = SurfaceEval::new(surface) else { return true }; + let Some((_, su, sv)) = s.project(p, None, f64::INFINITY).and_then(|uv| s.derivs(uv[0], uv[1])) else { return true }; + su.cross(sv).dot(out) >= 0.0 +} + +/// Below this sagitta-to-half-chord ratio an arc is the exact rational quadratic from its ends +/// and midpoint, rather than a circle about its circumcentre: the centre of an arc 12 mm long +/// with a 0.08 µm sagitta (a 225 m radius) is found to about 1e-6 mm, and the circle about it +/// would miss the arc's own ends by as much. +const FLAT_ARC: f64 = 1e-2; + +/// The arc from `a` to `b` through `mid` and its interval: a circle (angle from `a`), or for a +/// flat arc one rational quadratic: the middle control point on the line from the chord's +/// midpoint through `mid`, 2 / (1 − t²) as far, weight (1 − t²) / (1 + t²), where t is the +/// sagitta over the half chord. +fn arc_curve(a: Vec3, b: Vec3, mid: Vec3) -> Result<(b::Curve, [f64; 2])> { + let fail = || KernelError::Invalid("sew: an arc through points in line".into()); + let m = (a + b) * 0.5; + let half = a.dist(b) / 2.0; + let chord = (b - a).normalized().ok_or_else(fail)?; + let bow = mid - m; + let t = bow.len() / half; + if half > 1e-9 && t < FLAT_ARC && bow.dot(chord).abs() <= 1e-9 * half.max(1.0) { + let w = (1.0 - t * t) / (1.0 + t * t); + let apex = m + bow * (2.0 / (1.0 - t * t)); + let homogeneous = vec![[a.x, a.y, a.z, 1.0], [apex.x * w, apex.y * w, apex.z * w, w], [b.x, b.y, b.z, 1.0]]; + return Ok((b::Curve::RationalSpline { knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], homogeneous }, [0.0, 1.0])); + } + let c = circumcentre(a, mid, b).ok_or_else(fail)?; + let n = (mid - a).cross(b - mid).normalized().ok_or_else(fail)?; + let x = (a - c).normalized().ok_or_else(fail)?; + let y = n.cross(x).normalized().ok_or_else(fail)?; + let angle = |p: Vec3| { + let r = p - c; + r.dot(y).atan2(r.dot(x)).rem_euclid(std::f64::consts::TAU) + }; + let end = angle(b); + if !(end > 0.0) { + return Err(fail()); + } + Ok((b::Curve::Circle { frame: b::Frame { origin: arr(c), x_axis: arr(x), y_axis: arr(y) }, radius: a.dist(c) }, [0.0, end])) +} + /// Sew the faces into a closed solid. pub fn sew(faces: &[FaceSpec]) -> Result { + let _span = solidcraft_profile::span("kernel", "sew"); sew_impl(faces, false, None).map(|(body, _)| body) } /// Sew the faces into a closed solid that may touch itself: where four faces meet along a -/// straight edge (a cut-out's corner on the outline of a plate), each two of them get an edge of -/// their own (see [`touching_sheets`]), and where faces meet at a point in fans joined by no edge -/// (a hole's corner on its face's outline), each fan gets a vertex of its own. +/// straight edge (a cut-out's corner on the outline of a plate), each two of them that bound one +/// wedge of material get an edge of their own (see [`touching_sheets`]); where faces meet at a +/// point in fans joined by no edge (two caps touching at a corner), each fan gets a vertex of its +/// own; and a face whose loops meet at a vertex (a hole's corner on its face's outline) has them +/// as one loop through it (see [`join_touching_loops`]). pub fn sew_touching(faces: &[FaceSpec]) -> Result { + let _span = solidcraft_profile::span("kernel", "sew_touching"); sew_impl(faces, true, None).map(|(body, _)| body) } @@ -316,12 +773,10 @@ const SAME_WAY: f64 = 1e-6; /// of extruded arcs and on ruled walls are looked at. /// /// Each sheet bounds a wedge of material, so that pieces of material meeting along an edge stay -/// apart, except where that would make a face touch itself: a hole touching the outline from -/// inside (tangent, or at a corner) leaves its caps an outline and a hole meeting at the edge's -/// end, which with the material kept apart would share a vertex, and a face can't have that. -/// The material there goes round the hole, and the edges ending at such points get sheets that -/// bound the empty wedges instead: the hole's wall on either side is one sheet, the outline's -/// the other. +/// apart, as SMLib keeps a solid touching itself along a line: an edge for each wedge of +/// material, the two edges sharing their end vertices. A hole touching the outline from inside +/// (tangent, or at a corner) leaves its caps an outline and a hole meeting at the edge's end, at +/// one vertex: [`join_touching_loops`] makes them one loop through it. fn touching_sheets(faces: &[FaceSpec]) -> Result<(HashMap, HashMap)> { let mut uses: HashMap<(Key, Key), Vec<(EdgeUse, Vec3, Vec3)>> = HashMap::new(); for (fi, face) in faces.iter().enumerate() { @@ -338,69 +793,27 @@ fn touching_sheets(faces: &[FaceSpec]) -> Result<(HashMap, HashM } } } - // Each contact edge: its ends, both ways of pairing its faces, and whether the second is used. - let mut contacts = Vec::new(); - for (ends, group) in uses.iter().filter(|(_, g)| g.len() > 2) { - let [material, empty] = edge_sheets(faces, group)?; - contacts.push((*ends, material, empty, false)); - } - if contacts.is_empty() { - return Ok((HashMap::new(), corner_fans(faces, &HashMap::new()))); - } - let sheets_of = |contacts: &[((Key, Key), [[EdgeUse; 2]; 2], [[EdgeUse; 2]; 2], bool)]| -> HashMap { - let mut sheets = HashMap::new(); - for (_, material, empty, round) in contacts { - for (sheet, pair) in (if *round { empty } else { material }).iter().enumerate() { - for u in pair { - sheets.insert(*u, sheet); - } + // Each contact edge's sheets: its faces in the pairs that bound a wedge of material. + let mut sheets = HashMap::new(); + for group in uses.values().filter(|g| g.len() > 2) { + for (sheet, pair) in edge_sheets(faces, group)?.iter().enumerate() { + for u in pair { + sheets.insert(*u, sheet); } } - sheets - }; - // Each pass turns at least one edge round, and none back. - loop { - let sheets = sheets_of(&contacts); - let fans = corner_fans(faces, &sheets); - let touching = self_touching(faces, &fans); - let mut turned = false; - for (ends, _, _, round) in &mut contacts { - if !*round && (touching.contains(&ends.0) || touching.contains(&ends.1)) { - *round = true; - turned = true; - } - } - if !turned { - return Ok((sheets, fans)); - } } + let fans = corner_fans(faces, &sheets); + Ok((sheets, fans)) } -/// The points where a face has two corners at one vertex (its loops would touch there). -fn self_touching(faces: &[FaceSpec], fans: &HashMap) -> std::collections::HashSet { - let mut seen = std::collections::HashSet::new(); - let mut out = std::collections::HashSet::new(); - for (fi, f) in faces.iter().enumerate() { - for (li, l) in f.loops.iter().enumerate() { - for (ei, e) in l.iter().enumerate() { - let at = key(e.ends().0); - if !seen.insert((at, fans.get(&(fi, li, ei)).copied().unwrap_or(0), fi)) { - out.insert(at); - } - } - } - } - out -} - -/// The two ways of making sheets of an edge four faces meet along, as the pairs of faces -/// bounding each: around the wedges of material between them, and around the empty ones. +/// The sheets of an edge four faces meet along, as the pairs of faces bounding each: around the +/// wedges of material between them. /// /// Seen along the edge, each face leaves it as a curve; going round the edge, material and empty /// wedges between them alternate. Faces are ordered by the way they leave the edge and, where /// they leave it the same way (tangent faces), by how fast they turn from it: the order of /// points a short way into each face, as in 2D loop chaining (`prism::tightest_left`). -fn edge_sheets(faces: &[FaceSpec], group: &[(EdgeUse, Vec3, Vec3)]) -> Result<[[[EdgeUse; 2]; 2]; 2]> { +fn edge_sheets(faces: &[FaceSpec], group: &[(EdgeUse, Vec3, Vec3)]) -> Result<[[EdgeUse; 2]; 2]> { let fail = |s: &str| KernelError::Invalid(format!("sew: {s}")); let (Some((_, a0, b0)), 4) = (group.first(), group.len()) else { return Err(fail("unsupported edge contact")) }; let t = (if key(*a0) < key(*b0) { *b0 - *a0 } else { *a0 - *b0 }).normalized().ok_or_else(|| fail("a degenerate contact"))?; @@ -440,14 +853,11 @@ fn edge_sheets(faces: &[FaceSpec], group: &[(EdgeUse, Vec3, Vec3)]) -> Result<[[ if wedges.iter().any(|(p, q)| p.3 == q.3 || p.1 == q.1 || (same_way(p.4, q.4) && alike(p.2, q.2))) { return Err(fail("ambiguous edge contact")); } - let pairs = |material: bool| -> Result<[[EdgeUse; 2]; 2]> { - let mut it = wedges.iter().filter(|(p, _)| p.3 == material).map(|(p, q)| [p.0, q.0]); - match (it.next(), it.next()) { - (Some(x), Some(y)) => Ok([x, y]), - _ => Err(fail("ambiguous edge contact")), - } - }; - Ok([pairs(true)?, pairs(false)?]) + let mut it = wedges.iter().filter(|(p, _)| p.3).map(|(p, q)| [p.0, q.0]); + match (it.next(), it.next()) { + (Some(x), Some(y)) => Ok([x, y]), + _ => Err(fail("ambiguous edge contact")), + } } /// How a face leaves the straight edge `a`→`b` it bounds (its use `u`), seen along the edge's @@ -523,11 +933,10 @@ fn circumcentre(a: Vec3, b: Vec3, c: Vec3) -> Option { /// A loop corner: face, loop, and the edge of the loop that starts there. type Corner = (usize, usize, usize); -/// Where the faces meeting at a point form several fans, joined to each other by no edge (a hole -/// touching its face's outline at one point; two caps touching at a corner), the fan each corner -/// there is in, from 1 for every fan past the first (corners not listed are in fan 0). Each fan -/// gets its own vertex, so that a face's loops share no vertex (truck's faces need that) and -/// every vertex of the solid is a manifold one. +/// Where the faces meeting at a point form several fans, joined to each other by no edge (two +/// caps touching at a corner), the fan each corner there is in, from 1 for every fan past the +/// first (corners not listed are in fan 0). Each fan gets its own vertex, so that pieces of +/// material touching at a point share no vertex. fn corner_fans(faces: &[FaceSpec], sheets: &HashMap) -> HashMap { type EdgeId = (Key, Key, Option, usize); let id = |fi: usize, li: usize, ei: usize, e: &EdgeSpec| -> EdgeId { @@ -593,181 +1002,132 @@ fn corner_fans(faces: &[FaceSpec], sheets: &HashMap) -> HashMap< out } -fn faces_connected(faces: &[mt::Face]) -> bool { - let mut by_edge: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for e in f.edge_iter() { - by_edge.entry(e.id()).or_default().push(i); +/// The parent of `i` in a union-find forest, with path halving. +fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i) { + if p == i { + break; } - } - let mut seen = std::collections::HashSet::new(); - let mut todo = vec![0]; - while let Some(i) = todo.pop() { - if seen.insert(i) - && let Some(f) = faces.get(i) - { - for e in f.edge_iter() { - if let Some(adjacent) = by_edge.get(&e.id()) { - todo.extend(adjacent.iter().copied().filter(|j| !seen.contains(j))); - } - } + let up = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = up; } + i = p; } - seen.len() == faces.len() + i } -/// Keep disconnected closed boundaries as distinct shells, preserving orientation. -fn closed_components(faces: Vec) -> Result> { - const MAX_EDGE_USES: usize = 500_000; - const MAX_COMPONENTS: usize = 1024; - let fail = |s: &str| KernelError::Invalid(format!("sew: {s}")); - let mut by_edge: HashMap> = HashMap::new(); - let mut edge_uses = 0usize; - for (i, face) in faces.iter().enumerate() { - for edge in face.edge_iter() { - edge_uses = edge_uses.saturating_add(1); - if edge_uses > MAX_EDGE_USES { - return Err(fail("edge budget exceeded")); - } - let uses = by_edge.entry(edge.id()).or_default(); - if uses.len() >= 2 { - return Err(fail("nonmanifold edge contact")); - } - uses.push(i); +fn join(parent: &mut [usize], a: usize, b: usize) { + let (a, b) = (root(parent, a), root(parent, b)); + if let Some(slot) = parent.get_mut(a) { + *slot = b; + } +} + +/// The faces using each edge, a face once per use. +fn edge_users(edges: usize, faces: &[PartFace]) -> Result>> { + let mut users: Vec> = vec![Vec::new(); edges]; + for (fi, f) in faces.iter().enumerate() { + for u in f.loops.iter().flatten() { + users.get_mut(u.edge as usize).ok_or_else(|| KernelError::Failed("sew: edge reference".into()))?.push(fi); } } - if by_edge.values().any(|uses| uses.len() != 2) { - return Err(fail("the faces do not close")); + Ok(users) +} + +/// The connected groups of faces (joined through shared edges), each ascending, and each face's +/// group. +fn components(faces: usize, users: &[Vec]) -> (Vec>, Vec) { + let mut parent: Vec = (0..faces).collect(); + for u in users { + for w in u.windows(2) { + if let [a, b] = w { + join(&mut parent, *a, *b); + } + } } - let mut seen = vec![false; faces.len()]; - let mut vertices = HashMap::new(); - let mut components = Vec::new(); - for first in 0..faces.len() { - if seen.get(first).copied().unwrap_or(true) { - continue; + let mut group_of_root: HashMap = HashMap::new(); + let mut groups: Vec> = Vec::new(); + let mut of = vec![0; faces]; + for f in 0..faces { + let r = root(&mut parent, f); + let next = groups.len(); + let g = *group_of_root.entry(r).or_insert(next); + if g == next { + groups.push(Vec::new()); } - if components.len() >= MAX_COMPONENTS { - return Err(fail("component budget exceeded")); + if let (Some(group), Some(slot)) = (groups.get_mut(g), of.get_mut(f)) { + group.push(f); + *slot = g; } - let component = components.len(); - let mut todo = vec![first]; - if let Some(slot) = seen.get_mut(first) { - *slot = true; + } + (groups, of) +} + +/// A contact's edge sheets can end in separate vertex fans: each fan gets its own vertex at the +/// same point, so that every vertex of the boundary is a manifold one. A fan is the faces round +/// the vertex joined through the edges that end there. +fn split_vertex_fans(vertices: &mut Vec<[f64; 3]>, edges: &mut [PartEdge], faces: &[PartFace]) -> Result<()> { + let users = edge_users(edges.len(), faces)?; + let mut at: Vec> = vec![Vec::new(); vertices.len()]; + for (e, edge) in edges.iter().enumerate() { + for v in edge.vertices { + if let Some(list) = at.get_mut(v as usize) + && list.last() != Some(&e) + { + list.push(e); + } } - let mut indices = Vec::new(); - while let Some(i) = todo.pop() { - let face = faces.get(i).ok_or_else(|| fail("missing component face"))?; - indices.push(i); - for vertex in face.vertex_iter() { - if vertices.insert(vertex.id(), component).is_some_and(|previous| previous != component) { - return Err(fail("bodies touch only at a vertex")); + } + for (v, incident) in at.iter().enumerate() { + // Faces round the vertex, joined by each incident edge. + let mut parent: HashMap = HashMap::new(); + let mut local: Vec = Vec::new(); + let mut index = |f: usize, local: &mut Vec| -> usize { + *parent.entry(f).or_insert_with(|| { + local.push(local.len()); + local.len() - 1 + }) + }; + let mut edge_face = Vec::with_capacity(incident.len()); + for &e in incident { + let fs: Vec = users.get(e).map(|u| u.iter().map(|f| index(*f, &mut local)).collect()).unwrap_or_default(); + for w in fs.windows(2) { + if let [a, b] = w { + join(&mut local, *a, *b); } } - for edge in face.edge_iter() { - let adjacent = by_edge.get(&edge.id()).ok_or_else(|| fail("missing component edge"))?; - for j in adjacent { - let slot = seen.get_mut(*j).ok_or_else(|| fail("missing adjacent face"))?; - if !*slot { - *slot = true; - todo.push(*j); + edge_face.push((e, fs.first().copied())); + } + let mut fan_of_root: HashMap = HashMap::new(); + for (e, f) in edge_face { + let Some(f) = f else { continue }; + let r = root(&mut local, f); + let fan = match fan_of_root.get(&r) { + Some(fan) => *fan, + None => { + // The first fan keeps the vertex; each other gets a copy. + let fan = if fan_of_root.is_empty() { + v as u32 + } else { + let p = vertices.get(v).copied().ok_or_else(|| KernelError::Failed("sew: vertex".into()))?; + vertices.push(p); + u32::try_from(vertices.len() - 1).map_err(|_| KernelError::Invalid("sew: vertex budget exceeded".into()))? + }; + fan_of_root.insert(r, fan); + fan + } + }; + if let Some(edge) = edges.get_mut(e) { + for end in &mut edge.vertices { + if *end as usize == v { + *end = fan; } } } } - indices.sort_unstable(); - let component_faces = - indices.into_iter().map(|i| faces.get(i).cloned().ok_or_else(|| fail("missing component face"))).collect::>>()?; - components.push(component_faces.into()); } - Ok(components) -} - -/// A contact's edge sheets can terminate in separate vertex fans. Give each fan -/// its own vertex at the same coordinates so the boundary remains a manifold. -fn split_vertex_fans(faces: Vec) -> Result> { - let mut by_vertex: HashMap> = HashMap::new(); - let mut by_edge: HashMap> = HashMap::new(); - let mut vertices = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for v in f.vertex_iter() { - vertices.insert(v.id(), v.clone()); - by_vertex.entry(v.id()).or_default().push(i); - } - for e in f.edge_iter() { - by_edge.entry(e.id()).or_default().push(i); - } - } - let mut replacements: HashMap<(mt::VertexID, usize), mt::Vertex> = HashMap::new(); - for (id, members) in &mut by_vertex { - members.sort_unstable(); - members.dedup(); - let mut seen = std::collections::HashSet::new(); - let mut fans = Vec::new(); - for start in members.iter().copied() { - if seen.contains(&start) { - continue; - } - let mut todo = vec![start]; - let mut fan = Vec::new(); - while let Some(i) = todo.pop() { - if !seen.insert(i) { - continue; - } - fan.push(i); - if let Some(f) = faces.get(i) { - for e in f.edge_iter().filter(|e| e.absolute_front().id() == *id || e.absolute_back().id() == *id) { - if let Some(adjacent) = by_edge.get(&e.id()) { - todo.extend(adjacent.iter().copied().filter(|j| !seen.contains(j))); - } - } - } - } - fans.push(fan); - } - if fans.len() > 1 { - let original = vertices.get(id).ok_or_else(|| KernelError::Failed("sew: missing contact vertex".into()))?; - for fan in fans { - let vertex = builder::vertex(original.point()); - for i in fan { - replacements.insert((*id, i), vertex.clone()); - } - } - } - } - let mut edges = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for e in f.edge_iter() { - edges.entry(e.id()).or_insert_with(|| { - let (a, b) = (e.absolute_front(), e.absolute_back()); - let a = replacements.get(&(a.id(), i)).unwrap_or(a); - let b = replacements.get(&(b.id(), i)).unwrap_or(b); - mt::Edge::new(a, b, e.curve()) - }); - } - } - faces - .into_iter() - .map(|f| { - let wires: Vec = f - .absolute_boundaries() - .iter() - .map(|w| { - w.edge_iter() - .map(|e| { - let rebuilt = edges.get(&e.id()).ok_or_else(|| KernelError::Failed("sew: missing contact edge".into()))?; - Ok(if e.front() == e.absolute_front() { rebuilt.clone() } else { rebuilt.inverse() }) - }) - .collect::>>() - .map(Into::into) - }) - .collect::>()?; - let mut rebuilt = mt::Face::try_new(wires, f.surface()).map_err(|e| KernelError::Failed(format!("sew: contact face: {e}")))?; - if !f.orientation() { - rebuilt.invert(); - } - Ok(rebuilt) - }) - .collect() + Ok(()) } fn sew_impl(faces: &[FaceSpec], touching: bool, sources: Option<&[Option]>) -> Result<(Body, Option>)> { @@ -785,173 +1145,518 @@ fn sew_impl(faces: &[FaceSpec], touching: bool, sources: Option<&[Option = Vec::with_capacity(faces.len()); + let mut built = Builder::default(); + let mut parts: Vec>> = Vec::with_capacity(faces.len()); for (fi, f) in faces.iter().enumerate() { - let wires: Vec = f - .loops - .iter() - .enumerate() - .map(|(li, l)| { - let n = l.len().max(1); - l.iter() - .enumerate() - .map(|(ei, e)| { - cache.edge(e, sheets.get(&(fi, li, ei)).copied().unwrap_or(0), (fan((fi, li, ei)), fan((fi, li, (ei + 1) % n)))) - }) - .collect::>>() - .map(Into::into) - }) - .collect::>()?; - let face = match &f.surface { - SurfSpec::Plane => match builder::try_attach_plane(&wires) { - Ok(face) => face, - // truck's fit loses thin faces away from the origin: see `plane_about_the_mean`. - Err(e) => { - let plane = plane_about_the_mean(&wires).ok_or_else(|| KernelError::Failed(format!("sew: face {fi}: {e}")))?; - mt::Face::try_new(wires, mt::Surface::Plane(plane)).map_err(|e| KernelError::Failed(format!("sew: face {fi}: {e}")))? - } - }, - SurfSpec::Revolved { a, b, axis_origin, axis, angle } => { - let k = axis.normalized().ok_or_else(|| KernelError::Invalid("sew: axis".into()))?; - let (va, vb) = (builder::vertex(p3(*a)), builder::vertex(p3(*b))); - let swept: mt::Shell = builder::rsweep(&builder::line(&va, &vb), p3(*axis_origin), v3(k), mt::Rad(*angle)); - let tmp = swept.face_iter().next().cloned().ok_or_else(|| KernelError::Failed("sew: revolved surface".into()))?; - curved(tmp.oriented_surface(), wires, f.probe, fi)? + let mut loops = Vec::with_capacity(f.loops.len()); + for (li, l) in f.loops.iter().enumerate() { + let n = l.len().max(1); + let mut uses = Vec::with_capacity(l.len()); + for (ei, e) in l.iter().enumerate() { + let sheet = sheets.get(&(fi, li, ei)).copied().unwrap_or(0); + let (edge, forward) = built.edge(e, sheet, (fan((fi, li, ei)), fan((fi, li, (ei + 1) % n))))?; + uses.push(PartUse { edge, forward, given: None }); } - SurfSpec::Extruded { a, b, mid, dir } => { - let (va, vb) = (builder::vertex(p3(*a)), builder::vertex(p3(*b))); - let tmp: mt::Face = builder::tsweep(&arc_edge(&va, &vb, *mid), v3(*dir)); - curved(tmp.oriented_surface(), wires, f.probe, fi)? - } - SurfSpec::Ruled { a, b } => { - let (ca, cb) = (cache.chain(a)?, cache.chain(b)?); - if ca.degree() != cb.degree() || ca.control_points().len() != cb.control_points().len() { - return Err(KernelError::Invalid("sew: ruled chains differ in pieces".into())); - } - let surface = mt::Surface::BSplineSurface(mt::BSplineSurface::homotopy(ca, cb)); - curved(surface, wires, f.probe, fi)? - } - }; - out.push(face); + loops.push(uses); + } + parts.push(loops); } - let source_ids: HashMap<_, _> = out - .iter() - .enumerate() - .filter_map(|(i, f)| sources.and_then(|s| s.get(i)).and_then(Option::as_ref).map(|s| (f.id(), (f.orientation(), s)))) - .collect(); - if !sheets.is_empty() && !faces_connected(&out) { + let mut out: Vec = Vec::with_capacity(faces.len()); + for (fi, (f, mut loops)) in faces.iter().zip(parts).enumerate() { + let (surface, forward) = built.surface(fi, f, &mut loops, tol)?; + out.push(PartFace { surface, forward, loops }); + } + let Builder { mut vertices, mut edges, .. } = built; + let users = edge_users(edges.len(), &out)?; + if !sheets.is_empty() && components(out.len(), &users).0.len() > 1 { return Err(KernelError::Invalid("sew: bodies touch only along an edge".into())); } if !sheets.is_empty() { - out = split_vertex_fans(out)?; + split_vertex_fans(&mut vertices, &mut edges, &out)?; } - // Faces keep their identity into the solid (grouped into shells) and the body. - let built: HashMap = out.iter().enumerate().map(|(i, f)| (f.id(), i)).collect(); - let shells = closed_components(out)?; - let solid = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("sew: the faces do not close: {e}")))?; - let from = solid.face_iter().map(|f| built.get(&f.id()).copied()).collect(); - let body = Body::new(solid)?; - let mapped = - body.solid.face_iter().map(|f| source_ids.get(&f.id()).filter(|(o, _)| *o == f.orientation()).map(|(_, s)| (*s).clone())).collect(); - Ok((body.with_face_sources(sources.map(|_| std::sync::Arc::new(mapped))), from)) + join_touching_loops(&mut out, &edges)?; + // Each edge bounds two faces, and separate bodies share no vertex. + if users.iter().any(|u| u.len() > 2) { + return Err(KernelError::Invalid("sew: nonmanifold edge contact".into())); + } + if users.iter().any(|u| u.len() != 2) { + return Err(KernelError::Invalid("sew: the faces do not close".into())); + } + let (groups, group_of) = components(out.len(), &users); + if groups.len() > b::MAX_SHELLS { + return Err(KernelError::Invalid("sew: component budget exceeded".into())); + } + let mut vertex_group: Vec> = vec![None; vertices.len()]; + for (e, edge) in edges.iter().enumerate() { + let Some(&g) = users.get(e).and_then(|u| u.first()).and_then(|f| group_of.get(*f)) else { continue }; + for v in edge.vertices { + let slot = vertex_group.get_mut(v as usize).ok_or_else(|| KernelError::Failed("sew: vertex reference".into()))?; + if slot.is_some_and(|other| other != g) { + return Err(KernelError::Invalid("sew: bodies touch only at a vertex".into())); + } + *slot = Some(g); + } + } + let made = assemble(Parts { vertices, edges, faces: out, tolerance: tol }, true)?; + let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::smlib("sew: SMLib", e))?; + let (body, order) = crate::native::body_from_smlib_ordered(&smlib)?; + // The face of `faces` each face of the body was built from: record face `c` is SMLib's + // face `c`, which the order places in the body. + let from = order.and_then(|o| { + let mut from = vec![None; body.face_count()]; + for (spec, &c) in made.faces.iter().enumerate() { + let j = if o.faces.is_empty() { c } else { *o.faces.get(c)? }; + *from.get_mut(j)? = Some(spec); + } + from.into_iter().collect::>>() + }); + let mapped = sources.map(|s| { + let mapped: Vec> = match &from { + Some(from) => from.iter().map(|i| s.get(*i).cloned().flatten()).collect(), + None => vec![None; body.face_count()], + }; + Arc::new(mapped) + }); + Ok((body.with_face_sources(mapped), from)) }) } -/// Below this sagitta-to-half-chord ratio an arc is built as its exact rational quadratic from -/// its ends and midpoint. truck's three-point arc (circumcentre, then a turn about it) misses -/// its own ends on very flat arcs: one 12 mm long with a 0.08 µm sagitta (a 225 m radius) ends -/// about 1e-6 mm off its vertex, and a planar face holding it far from the origin could not be -/// given a plane (its wire's points no longer closed). -const FLAT_ARC: f64 = 1e-2; - -/// The arc from `a` to `b` through `mid`: the exact rational quadratic for a flat arc, truck's -/// three-point arc otherwise (and should the curve be refused, which its exact ends make -/// impossible). -fn arc_edge(a: &mt::Vertex, b: &mt::Vertex, mid: Vec3) -> mt::Edge { - let (pa, pb) = (a.point(), b.point()); - let (pa, pb) = (Vec3::new(pa.x, pa.y, pa.z), Vec3::new(pb.x, pb.y, pb.z)); - flat_arc(pa, pb, mid) - .and_then(|curve| mt::Edge::try_new(a, b, mt::Curve::NurbsCurve(curve)).ok()) - .unwrap_or_else(|| builder::circle_arc(a, b, p3(mid))) -} - -/// A flat arc (see [`FLAT_ARC`]) through its midpoint `mid` as one rational quadratic: the middle -/// control point on the line from the chord's midpoint through `mid`, 2 / (1 − t²) as far, weight -/// (1 − t²) / (1 + t²), where t is the sagitta over the half chord. None for a deeper arc, or -/// when `mid` is not halfway along the chord. -fn flat_arc(a: Vec3, b: Vec3, mid: Vec3) -> Option> { - let m = (a + b) * 0.5; - let half = a.dist(b) / 2.0; - let chord = (b - a).normalized()?; - let bow = mid - m; - let t = bow.len() / half; - if !(half > 1e-9) || !(t < FLAT_ARC) || bow.dot(chord).abs() > 1e-9 * half.max(1.0) { - return None; - } - let w = (1.0 - t * t) / (1.0 + t * t); - let apex = m + bow * (2.0 / (1.0 - t * t)); - let h = |p: Vec3, w: f64| mt::Vector4::new(p.x * w, p.y * w, p.z * w, w); - Some(mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![h(a, 1.0), h(apex, w), h(b, 1.0)]))) -} - -/// A curved face on `surf`, turned so its normal at the probe points outward. -fn curved(mut surf: mt::Surface, wires: Vec, probe: Option<(Vec3, Vec3)>, fi: usize) -> Result { - use mt::{ParametricSurface3D, SearchParameter}; - if let Some((p, outward)) = probe - && let Some((u, v)) = surf.search_parameter(p3(p), None, 100) - { - let n = surf.normal(u, v); - if Vec3::new(n.x, n.y, n.z).dot(outward) < 0.0 { - surf = mt::Invertible::inverse(&surf); +/// Each face's loops that meet at a vertex as one loop through it twice: the first loop up to the +/// vertex, the other from the vertex round to it again, then the rest of the first. That is how +/// SMLib keeps a face whose hole touches its outline, or whose holes touch each other, at a +/// corner: a face's loops share no vertex (SMLib's face tests 38 and 39), and two vertices at +/// one point are one (test 32). Each loop keeps its direction, so the joined loop keeps the face +/// on its left, and the outer loop stays first. +fn join_touching_loops(faces: &mut [PartFace], edges: &[PartEdge]) -> Result<()> { + let start = |u: &PartUse| -> Result { + let e = edges.get(u.edge as usize).ok_or_else(|| KernelError::Failed("sew: edge reference".into()))?; + Ok(if u.forward { e.vertices[0] } else { e.vertices[1] }) + }; + for f in faces { + // Each join takes one loop away. + 'join: while f.loops.len() > 1 { + for a in 0..f.loops.len() { + for b in a + 1..f.loops.len() { + let (Some(la), Some(lb)) = (f.loops.get(a), f.loops.get(b)) else { continue }; + let mut at = None; + 'find: for (ia, ua) in la.iter().enumerate() { + let v = start(ua)?; + for (ib, ub) in lb.iter().enumerate() { + if start(ub)? == v { + at = Some((ia, ib)); + break 'find; + } + } + } + let Some((ia, ib)) = at else { continue }; + let mut lb = f.loops.remove(b); + if let Some(la) = f.loops.get_mut(a) { + let rest = la.split_off(ia); + let head: Vec = lb.drain(..ib).collect(); + la.extend(lb); + la.extend(head); + la.extend(rest); + } + continue 'join; + } + } + break; } } - mt::Face::try_new(wires, surf).map_err(|e| KernelError::Failed(format!("sew: face {fi}: {e}"))) + Ok(()) } -/// The plane of a boundary that truck's fit (`builder::try_attach_plane`) refused: truck's fit -/// again, on the boundary moved so that the mean of its control points is the origin, and the -/// plane moved back. None when truck refuses that one too (the boundary is not flat within -/// truck's 1e-6, or has no area). -/// -/// truck sums the cross products of consecutive control points about a centre, and takes the -/// points' sum for that centre (it divides by the number of wires, not of points): eight times as -/// far from the origin as a rectangle of four lines. The sum is the same about any centre; its -/// rounding is not. It grows with the square of the centre's distance, and on a thin face, whose -/// normal is short, turns the normal far enough for truck's own flatness test to fail: truck -/// finds a 0.00013 x 30 mm face 360 mm from the origin 2e-6 mm out of the plane it fitted. With -/// the centre at the origin the same face is 1e-14 mm out at most. -fn plane_about_the_mean(wires: &[mt::Wire]) -> Option { - let (mut sum, mut count) = (Vec3::ZERO, 0usize); - for p in wires.iter().flat_map(|w| w.edge_iter()).flat_map(|e| e.oriented_curve().lift_up().control_points().clone()) { - sum += Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w); - count += 1; +/// One face to [`assemble`]. +pub(crate) struct PartFace { + pub surface: b::Surface, + /// The surface's natural normal points out of the material (on a sheet: to its front). + pub forward: bool, + /// The loops, counter-clockwise about the face's outward normal, the outer one first. + pub loops: Vec>, +} + +/// One use of an edge in a loop: whether the loop runs along it, and its exact pcurve where the +/// caller holds one (on the edge's interval, in its direction). +pub(crate) struct PartUse { + pub edge: u32, + pub forward: bool, + pub given: Option, +} + +pub(crate) struct PartEdge { + pub curve: b::Curve, + /// The NURBS form the edge is parameterised on, as a record edge keeps it + /// ([`b::Edge::nurbs`]): given, `interval` is on it and `curve` only says what the edge is, + /// so an edge taken from a record goes back as that same edge. + pub nurbs: Option, + pub interval: [f64; 2], + pub vertices: [u32; 2], +} + +/// Faces on shared edges and vertices, to be made a record; `tolerance` is every vertex's and +/// edge's, and the record's. +pub(crate) struct Parts { + pub vertices: Vec<[f64; 3]>, + pub edges: Vec, + pub faces: Vec, + pub tolerance: f64, +} + +/// An assembled record, with the canonical index of each face of the parts and of each edge +/// (`None` for an edge no face uses). +pub(crate) struct Assembled { + pub brep: b::Brep, + pub faces: Vec, + pub edges: Vec>, +} + +/// The schema 4 record of `parts`: each face its pcurves (the caller's exact ones where given, +/// else `pcurve::pcurves`) and parameter box; the faces grouped into shells through shared edges; +/// closed shells (every edge used twice in them) enclosing material, or a cavity where the +/// faces' outward normals enclose negative volume, each cavity in the solid around it; open +/// shells (sheets) in the infinite region; everything in canonical order and validated. +/// `solid`: every shell must be closed. +pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { + let _span = solidcraft_profile::span("kernel", "assemble"); + let fail = |m: String| KernelError::Invalid(format!("sew: {m}")); + let Parts { vertices, edges, faces, tolerance: tol } = parts; + let nf = faces.len(); + if nf == 0 { + return Err(fail("no faces".into())); } - let mean = sum * (1.0 / count.max(1) as f64); - if !mean.is_finite() { - return None; + // The loops as the record keeps them: relative to the surface's natural normal. + let loops: Vec)>>> = faces + .iter() + .map(|f| { + f.loops + .iter() + .map(|l| { + if f.forward { + l.iter().map(|u| (u.edge, u.forward, u.given.as_ref())).collect() + } else { + l.iter().rev().map(|u| (u.edge, !u.forward, u.given.as_ref())).collect() + } + }) + .collect() + }) + .collect(); + // Every circle and ellipse edge on its NURBS form (an edge the caller gave a pcurve for keeps + // the parameter that pcurve is on). + let given_on: Vec = { + let mut g = vec![false; edges.len()]; + for u in faces.iter().flat_map(|f| f.loops.iter().flatten()).filter(|u| u.given.is_some()) { + if let Some(slot) = g.get_mut(u.edge as usize) { + *slot = true; + } + } + g + }; + // Each edge's label and NURBS form (`form::edge`): a circle about a revolved face's axis on + // that face's frame, so its form lies on the face's quarter grid; an edge given with its form + // keeps it, and an edge the caller gave a pcurve for keeps the parameter that pcurve is on. + let mut frames_of: Vec> = vec![Vec::new(); edges.len()]; + for f in &faces { + let Some(frame) = solidcraft_geom::brep::form::frame_of(&f.surface) else { continue }; + for u in f.loops.iter().flatten() { + if let Some(slot) = frames_of.get_mut(u.edge as usize) { + slot.push(frame.clone()); + } + } } - let moved: Vec = wires.iter().map(|w| builder::transformed(w, mt::Matrix4::from_translation(v3(-mean)))).collect(); - match builder::try_attach_plane(&moved).ok()?.surface() { - mt::Surface::Plane(plane) => Some(mt::Transformed::transformed(&plane, mt::Matrix4::from_translation(v3(mean)))), - _ => None, + let mut labels: Vec<(b::Curve, [f64; 2])> = Vec::with_capacity(edges.len()); + let mut forms: Vec> = Vec::with_capacity(edges.len()); + for ((e, frames), given) in edges.iter().zip(&frames_of).zip(&given_on) { + if let Some(form) = &e.nurbs { + let on_label = solidcraft_geom::brep::label::curve_interval(&e.curve, Some(form), e.interval) + .ok_or_else(|| fail("an edge's NURBS form does not evaluate".into()))?; + labels.push((e.curve.clone(), on_label)); + forms.push(Some((form.clone(), e.interval))); + continue; + } + if *given { + labels.push((e.curve.clone(), e.interval)); + forms.push(None); + continue; + } + let (label, interval, form) = + solidcraft_geom::brep::form::edge(&e.curve, e.interval, frames.iter(), tol).ok_or_else(|| fail("an arc of more than one turn".into()))?; + labels.push((label, interval)); + forms.push(form); } + // Each face on its NURBS form: a cylinder, cone, sphere or torus over the extent its label's + // pcurves give, then every pcurve again on the forms, exactly. + let mut pcs: Vec>> = Vec::with_capacity(nf); + let mut domains = Vec::with_capacity(nf); + let mut face_forms: Vec> = Vec::with_capacity(nf); + for (fi, (f, ls)) in faces.iter().zip(&loops).enumerate() { + let failed = |e: pcurve::Error| KernelError::Failed(format!("sew: face {fi}: {e}")); + // Edges folded across a bend: B-spline edges with no given pcurve on a cylinder or cone. + let folded_on = |form: Option<&b::Surface>| -> Vec<(u32, Curve2)> { + ls.iter() + .flatten() + .filter(|(_, _, given)| given.is_none()) + .filter_map(|&(e, _, _)| { + let edge = edges.get(e as usize)?; + Some((e, folded_pcurve(&f.surface, form, &edge.curve, edge.interval)?)) + }) + .collect() + }; + // A cylinder, cone, sphere or torus on its NURBS form, over the extent of its boundary on + // its label. + let form = match f.surface { + b::Surface::Cylinder { .. } | b::Surface::Cone { .. } | b::Surface::Sphere { .. } | b::Surface::Torus { .. } => { + let boundary: Vec> = ls + .iter() + .map(|l| l.iter().filter_map(|&(e, forward, _)| labels.get(e as usize).map(|(c, i)| (c, *i, forward))).collect()) + .collect(); + let extent = solidcraft_geom::brep::form::extent(&f.surface, &boundary) + .ok_or_else(|| fail(format!("face {fi}: its boundary is not on its surface")))?; + Some(solidcraft_geom::brep::form::surface(&f.surface, extent).ok_or_else(|| fail(format!("face {fi}: more than one turn")))?) + } + _ => None, + }; + let (form, form_box) = match form { + Some((s, d)) => (Some(s), Some(d)), + None => (None, None), + }; + let on = form.as_ref().unwrap_or(&f.surface); + let folded_form = if form.is_some() { folded_on(form.as_ref()) } else { Vec::new() }; + let pc = pcurve::pcurves_within(on, &uses_of(&edges, &forms, ls, &folded_form, tol)?, tol, form_box).map_err(failed)?; + domains.push(domain_of(on, &pc).ok_or_else(|| fail(format!("face {fi} has no area in its parameters")))?); + pcs.push(pc); + face_forms.push(form); + } + let users = edge_users(edges.len(), &faces)?; + let (groups, _) = components(nf, &users); + if groups.len() > b::MAX_SHELLS { + return Err(fail("component budget exceeded".into())); + } + let closed: Vec = groups + .iter() + .map(|g| { + g.iter() + .flat_map(|f| faces.get(*f).into_iter().flat_map(|f| f.loops.iter().flatten())) + .all(|u| users.get(u.edge as usize).is_some_and(|x| x.len() >= 2)) + }) + .collect(); + if solid && closed.iter().any(|c| !c) { + return Err(fail("the faces do not close".into())); + } + // Closed shells: the volume their outward normals enclose, positive for a solid's outside. + let flux_of = |g: &[usize], field: &dyn Fn(Vec3) -> Vec3| -> Result { + let mut sum = 0.0; + for &f in g { + let (Some(face), Some(pc), Some(ls), Some(dom)) = (faces.get(f), pcs.get(f), loops.get(f), domains.get(f)) else { continue }; + let on = face_forms.get(f).and_then(Option::as_ref).unwrap_or(&face.surface); + let s = SurfaceEval::new(on).map_err(|e| KernelError::Failed(format!("sew: face {f}: {e}")))?; + let uses: Vec> = pc.iter().zip(ls).map(|(c, l)| c.iter().zip(l).map(|(c, u)| (c, u.1)).collect()).collect(); + let flux = face_flux(&s, dom[1][0], &uses, field).ok_or_else(|| KernelError::Failed(format!("sew: face {f} cannot be evaluated")))?; + sum += if face.forward { flux } else { -flux }; + } + Ok(sum) + }; + let mut volume = vec![0.0; groups.len()]; + for (k, g) in groups.iter().enumerate() { + if closed.get(k).copied().unwrap_or(false) { + let v = flux_of(g, &|p| p * (1.0 / 3.0))?; + if !(v.abs() > 0.0) || !v.is_finite() { + return Err(fail("a closed shell encloses no volume".into())); + } + if let Some(slot) = volume.get_mut(k) { + *slot = v; + } + } + } + let outers: Vec = (0..groups.len()).filter(|k| volume.get(*k).is_some_and(|v| *v > 0.0)).collect(); + // Each cavity in the smallest solid around it (by the winding number of one of its points). + let mut cavities: Vec> = vec![Vec::new(); groups.len()]; + for k in (0..groups.len()).filter(|k| volume.get(*k).is_some_and(|v| *v < 0.0)) { + let around = if let [only] = outers.as_slice() { + Some(*only) + } else { + let q = groups + .get(k) + .and_then(|g| g.first()) + .and_then(|f| faces.get(*f)) + .and_then(|f| f.loops.first()?.first()) + .and_then(|u| edges.get(u.edge as usize)) + .and_then(|e| vertices.get(e.vertices[0] as usize)) + .map(|p| v3(*p)) + .ok_or_else(|| fail("cavity".into()))?; + let field = move |p: Vec3| { + let d = p - q; + let r = d.len(); + d * (1.0 / (4.0 * std::f64::consts::PI * r * r * r)) + }; + let mut best: Option<(f64, usize)> = None; + for &o in &outers { + let w = flux_of(groups.get(o).map_or(&[][..], Vec::as_slice), &field)?; + let v = volume.get(o).copied().unwrap_or(0.0); + if (w - 1.0).abs() < 0.5 && best.is_none_or(|(b, _)| v < b) { + best = Some((v, o)); + } + } + best.map(|(_, o)| o) + }; + let o = around.ok_or_else(|| fail("a cavity lies in no solid".into()))?; + cavities.get_mut(o).ok_or_else(|| fail("cavity".into()))?.push(k); + } + // The record as its parts stand (shell k is group k, face i part face i, edges and vertices + // as given), then put in canonical order. + let index = |i: usize| u32::try_from(i).map_err(|_| fail("index".into())); + let open: Vec = (0..groups.len()).filter(|k| !closed.get(*k).copied().unwrap_or(false)).collect(); + let mut regions = vec![b::Region { shells: outers.iter().chain(&open).map(|g| index(*g)).collect::>()?, void: false }]; + for &o in &outers { + let mut shells = vec![index(o)?]; + for &c in cavities.get(o).into_iter().flatten() { + shells.push(index(c)?); + } + regions.push(b::Region { shells, void: false }); + } + for &o in &outers { + for &c in cavities.get(o).into_iter().flatten() { + regions.push(b::Region { shells: vec![index(c)?], void: true }); + } + } + let shells = groups + .iter() + .map(|g| { + let faces = g + .iter() + .map(|&f| Ok(b::OrientedFace { face: index(f)?, forward: faces.get(f).is_some_and(|x| x.forward) })) + .collect::>()?; + Ok(b::Shell::Faces { faces, wires: Vec::new() }) + }) + .collect::>()?; + let mut record_faces = Vec::with_capacity(nf); + for (f, ((face, ls), (pc, domain))) in faces.iter().zip(&loops).zip(pcs.iter().zip(&domains)).enumerate() { + let mut record_loops = Vec::with_capacity(ls.len()); + for (l, c) in ls.iter().zip(pc) { + let oriented = l.iter().zip(c).map(|(&(edge, forward, _), pcurve)| b::OrientedEdge { edge, forward, pcurve: pcurve.clone() }).collect(); + record_loops.push(b::Loop::Edges { edges: oriented }); + } + if record_loops.is_empty() { + return Err(fail(format!("face {f} has no loop"))); + } + let nurbs = face_forms.get(f).cloned().flatten(); + record_faces.push(b::Face { nurbs, surface: face.surface.clone(), domain: *domain, loops: record_loops }); + } + let record_edges = edges + .iter() + .zip(forms.iter().zip(&labels)) + .map(|(e, (form, (label, label_interval)))| { + let (nurbs, interval) = match form { + Some((c, i)) => (Some(c.clone()), *i), + None => (None, *label_interval), + }; + b::Edge { nurbs, curve: label.clone(), interval, vertices: e.vertices, tolerance: tol, uses: Vec::new() } + }) + .collect(); + let record_vertices = vertices.iter().map(|point| b::Vertex { point: *point, tolerance: tol }).collect(); + let loose = b::Brep { version: b::VERSION, tolerance: tol, regions, shells, faces: record_faces, edges: record_edges, vertices: record_vertices }; + let part = loose.canonical().map_err(|e| KernelError::Failed(format!("sew: the record is invalid: {e}")))?; + let mut face_new = vec![usize::MAX; nf]; + for (c, &f) in part.faces.iter().enumerate() { + if let Some(slot) = face_new.get_mut(f as usize) { + *slot = c; + } + } + let mut edge_new = vec![None; edges.len()]; + for (c, &e) in part.edges.iter().enumerate() { + if let Some(slot) = edge_new.get_mut(e as usize) { + *slot = Some(c); + } + } + Ok(Assembled { brep: part.brep, faces: face_new, edges: edge_new }) +} + +/// A face's parameter box: around its pcurves' control points (a B-spline lies in their hull), +/// held inside the surface's natural domain (one turn where periodic). None when it has no +/// width in either direction. +/// A face's edge uses for `pcurve::pcurves`: on each edge's NURBS form where it has one, else on +/// its curve as given; `folded` gives the pcurves of edges folded across the face (see +/// [`folded_pcurve`]). +fn uses_of<'a>( + edges: &'a [PartEdge], + forms: &'a [Option<(b::Curve, [f64; 2])>], + ls: &[Vec<(u32, bool, Option<&'a Curve2>)>], + folded: &'a [(u32, Curve2)], + tol: f64, +) -> Result>>> { + ls.iter() + .map(|l| { + l.iter() + .map(|&(e, forward, given)| { + let edge = edges.get(e as usize).ok_or_else(|| KernelError::Invalid("sew: edge reference".into()))?; + let (curve, interval) = match forms.get(e as usize).and_then(Option::as_ref) { + Some((c, i)) => (c, *i), + _ => (&edge.curve, edge.interval), + }; + let given = given.or_else(|| folded.iter().find(|(f, _)| *f == e).map(|(_, c)| c)); + Ok(pcurve::EdgeUse { edge: e, curve, interval, forward, tolerance: tol, given }) + }) + .collect() + }) + .collect() +} + +fn domain_of(surface: &b::Surface, pcs: &[Vec]) -> Option<[[f64; 2]; 2]> { + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for c in pcs.iter().flatten() { + let points: Vec<[f64; 2]> = match c { + Curve2::Spline { points, .. } => points.clone(), + Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().map(|h| [h[0] / h[2], h[1] / h[2]]).collect(), + }; + for p in points { + for d in 0..2 { + lo[d] = lo[d].min(p[d]); + hi[d] = hi[d].max(p[d]); + } + } + } + let natural = solidcraft_geom::brep::label::surface_natural(surface); + let mut out = [[0.0; 2]; 2]; + for d in 0..2 { + let (mut a, mut z) = (lo[d], hi[d]); + match natural[d] { + b::Natural::Periodic => z = z.min(a + std::f64::consts::TAU), + b::Natural::Range(n0, n1) => { + a = a.max(n0); + z = z.min(n1); + } + } + if !(a < z) { + return None; + } + out[d] = [a, z]; + } + Some(out) } #[cfg(test)] @@ -1005,7 +1710,7 @@ mod tests { let lumps = body.lumps().unwrap(); assert_eq!(lumps.len(), 2); assert!(lumps.iter().all(|b| (crate::measure(b).unwrap().volume - 24.0).abs() < 1e-9)); - let mesh = body.tessellate(0.01).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!(mesh.contains(Vec3::new(1.0, 1.0, 1.0))); assert!(mesh.contains(Vec3::new(11.0, 1.0, 1.0))); assert!(!mesh.contains(Vec3::new(5.0, 1.0, 1.0))); @@ -1034,7 +1739,7 @@ mod tests { assert_eq!(cavity.shell_count(), 2); assert_eq!(cavity.lumps().unwrap().len(), 1); assert!((crate::measure(&cavity).unwrap().volume - 21.0).abs() < 1e-9); - assert!(!cavity.tessellate(0.01).unwrap().contains(Vec3::new(1.0, 1.5, 2.0))); + assert!(!cavity.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().contains(Vec3::new(1.0, 1.5, 2.0))); let touching = box_faces(Vec3::new(2.0, 3.0, 4.0), Vec3::new(2.0, 3.0, 4.0)); assert!(sew(&outer.iter().chain(&touching).cloned().collect::>()).unwrap_err().to_string().contains("vertex")); let mut hostile = outer.clone(); @@ -1078,6 +1783,45 @@ mod tests { } } + /// A 10 x 6 x 2 plate with a triangular cut-out whose corner touches the plate's edge x = 0 + /// at (0, 3): the plate touches itself along the line of that corner, where four walls meet. + /// As SMLib keeps such a solid, each cap is one loop through the corner twice, the line two + /// edges (one per wedge of material) between the corner's two vertices: SMLib finds it valid. + /// The caps had been an outline and a hole, each with its own vertex at the corner, which + /// SMLib refuses (a face with coincident vertices, loops touching). + #[test] + fn a_cut_out_touching_the_outline_at_a_corner_caps_with_one_loop() { + let at = |x: f64, y: f64, z: f64| Vec3::new(x, y, z); + let outline = [(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (0.0, 6.0), (0.0, 3.0)]; + // Clockwise: a hole. + let hole = [(0.0, 3.0), (2.0, 3.5), (2.0, 2.5)]; + let ring = |pts: &[(f64, f64)], z: f64| -> Vec { + (0..pts.len()) + .map(|i| EdgeSpec::Line { a: at(pts[i].0, pts[i].1, z), b: at(pts[(i + 1) % pts.len()].0, pts[(i + 1) % pts.len()].1, z) }) + .collect() + }; + let down = |l: Vec| -> Vec { l.into_iter().rev().map(|e| e.reversed()).collect() }; + let mut faces = vec![ + FaceSpec { loops: vec![ring(&outline, 2.0), ring(&hole, 2.0)], surface: SurfSpec::Plane, probe: None }, + FaceSpec { loops: vec![down(ring(&outline, 0.0)), down(ring(&hole, 0.0))], surface: SurfSpec::Plane, probe: None }, + ]; + for pts in [&outline[..], &hole[..]] { + for i in 0..pts.len() { + let ((ax, ay), (bx, by)) = (pts[i], pts[(i + 1) % pts.len()]); + faces.push(quad(at(ax, ay, 0.0), at(bx, by, 0.0), at(bx, by, 2.0), at(ax, ay, 2.0))); + } + } + let body = sew_touching(&faces).unwrap(); + assert!((crate::measure(&body).unwrap().volume - 118.0).abs() < 1e-9); + let record = crate::brep_record(&body).unwrap(); + let caps: Vec<&b::Face> = + record.faces.iter().filter(|f| f.loops.len() == 1 && matches!(&f.loops[0], b::Loop::Edges { edges } if edges.len() == 8)).collect(); + assert_eq!(caps.len(), 2, "each cap one loop of the outline's five edges and the cut-out's three"); + assert_eq!(record.vertices.len(), 14, "the corner one vertex on each cap"); + let v = crate::validity(&body); + assert!(v.ok(), "{v:?}"); + } + #[test] fn a_sewn_box() { let p = |x: f64, y: f64, z: f64| Vec3::new(x, y, z); @@ -1220,13 +1964,10 @@ mod tests { #[test] fn thin_faces_away_from_the_origin_get_their_planes() { // Slabs 30 x 2 mm and 0.00013 to 0.1 mm thick, away from the origin and turned off the - // axes. truck's plane fit sums the cross products of a boundary's points about a centre - // and takes the points' sum for it, eight times as far from the origin as a rectangle; - // on the thin faces its normal then comes out so far off that truck finds a - // 0.00013 x 30 mm face at (-300, -200, 5) 2e-6 mm out of its own plane and refuses it: - // `cannot attach a plane to a wire that is not on one plane`. Nine of these 45 slabs - // have such a face. (Thinner slabs meet another limit, at the origin too: a face - // 0.00003 mm wide and askew to the axes is sewn but gets no triangles.) + // axes. A plane fitted by summing the cross products of a boundary's points about a far + // centre turns a thin face's short normal so far that a 0.00013 x 30 mm face at + // (-300, -200, 5) lies 2e-6 mm out of it; summed about the boundary's mean it lies + // within 1e-14 mm. let turned = |about_z: f64, about_x: f64| { let (sz, cz) = about_z.sin_cos(); let (sx, cx) = about_x.sin_cos(); diff --git a/crates/kernel/src/shell_groups.rs b/crates/kernel/src/shell_groups.rs index 40702e160..0873705ac 100644 --- a/crates/kernel/src/shell_groups.rs +++ b/crates/kernel/src/shell_groups.rs @@ -1,16 +1,13 @@ //! Group disconnected material regions without moving a cavity to another enclosing shell. //! A valid shell hierarchy alternates material and void at every nesting level. -use solidcraft_geom::{Aabb3, BoxedTriangle, Mesh, Vec3, find_close_pair}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Aabb3, BoxedTriangle, Mesh, find_close_pair}; use crate::{KernelError, Result}; -pub(super) const MAX_SHELLS: usize = 1024; -pub(super) const MAX_POINTS: usize = 100_000; -pub(super) const MAX_TRIANGLES: usize = 100_000; const MAX_PAIR_WORK: usize = 40_000_000; -const MAX_PROBES: usize = 2_000_000; -const MAX_CONTAINMENT_WORK: usize = 40_000_000; fn failed(detail: &str) -> KernelError { KernelError::Failed(format!("lumps: {detail}")) @@ -111,132 +108,3 @@ pub(super) fn meshes_meet(a: &Mesh, b: &Mesh, gap: f64) -> Result { // No boundary contact: they meet only if one lies wholly inside the other. Ok(b.positions.first().is_some_and(|p| a.contains(*p)) || a.positions.first().is_some_and(|p| b.contains(*p))) } - -pub(super) fn groups(meshes: &[Mesh], volumes: &[f64], gap: f64) -> Result>> { - if meshes.is_empty() || meshes.len() != volumes.len() || meshes.len() > MAX_SHELLS { - return Err(failed("shell count exceeds the grouping limit or is invalid")); - } - if !gap.is_finite() || gap <= 0.0 { - return Err(failed("invalid shell clearance")); - } - let mut points = 0usize; - let mut triangle_count = 0usize; - let mut triangles = Vec::with_capacity(meshes.len()); - let mut bounds = Vec::with_capacity(meshes.len()); - for (mesh, volume) in meshes.iter().zip(volumes) { - points = points.checked_add(mesh.positions.len()).ok_or_else(|| failed("point count exceeds the grouping limit"))?; - triangle_count = triangle_count.checked_add(mesh.triangles.len()).ok_or_else(|| failed("triangle count exceeds the grouping limit"))?; - if points > MAX_POINTS || triangle_count > MAX_TRIANGLES { - return Err(failed("mesh exceeds the shell grouping limit")); - } - if !volume.is_finite() - || *volume == 0.0 - || mesh.positions.is_empty() - || mesh.triangles.is_empty() - || mesh.positions.iter().any(|p| !p.is_finite()) - { - return Err(failed("cannot determine a closed shell's orientation")); - } - let tris: Vec<_> = mesh.triangles.iter().map(|t| mesh.tri(t).ok_or_else(|| failed("invalid shell triangle"))).collect::>()?; - if tris.iter().any(|[a, b, c]| unit((*b - *a).cross(*c - *a)).is_none()) { - return Err(failed("degenerate shell triangle")); - } - triangles.push(tris.into_iter().map(|t| (t, box_of(&t))).collect::>()); - bounds.push(mesh.bounds()); - } - let mut inside = vec![vec![false; meshes.len()]; meshes.len()]; - let mut pair_budget = MAX_PAIR_WORK; - let mut probes = 0usize; - let mut containment_work = 0usize; - for (i, mesh) in meshes.iter().enumerate() { - for j in i + 1..meshes.len() { - let (Some(a_bounds), Some(b_bounds)) = (bounds.get(i), bounds.get(j)) else { return Err(failed("missing shell bounds")) }; - if boxes_separate(*a_bounds, *b_bounds, gap) { - continue; - } - let (Some(a), Some(b)) = (triangles.get(i), triangles.get(j)) else { return Err(failed("missing shell triangles")) }; - if find_close_pair(a, b, gap, &mut pair_budget, |(x, _), (y, _)| triangles_meet(x, y, gap)) - .ok_or_else(|| failed("shell boundary work exceeds the grouping limit"))? - { - return Err(failed("shell boundaries intersect or touch; cavity ownership is ambiguous")); - } - for (inner, outer) in [(i, j), (j, i)] { - let ib = bounds.get(inner).ok_or_else(|| failed("missing shell bounds"))?; - let ob = bounds.get(outer).ok_or_else(|| failed("missing shell bounds"))?; - // With boundary intersections already excluded, a connected shell - // extending beyond another's bounds cannot be wholly contained. - if ib.min.x < ob.min.x - gap - || ib.min.y < ob.min.y - gap - || ib.min.z < ob.min.z - gap - || ib.max.x > ob.max.x + gap - || ib.max.y > ob.max.y + gap - || ib.max.z > ob.max.z + gap - { - continue; - } - let inner_mesh = if inner == i { mesh } else { meshes.get(inner).ok_or_else(|| failed("missing shell"))? }; - probes = probes.checked_add(inner_mesh.positions.len()).ok_or_else(|| failed("shell probes exceed the grouping limit"))?; - if probes > MAX_PROBES { - return Err(failed("shell probes exceed the grouping limit")); - } - let outer_mesh = meshes.get(outer).ok_or_else(|| failed("missing shell"))?; - let probe_count = inner_mesh.positions.len(); - let work = probe_count - .checked_mul(outer_mesh.triangles.len()) - .and_then(|n| n.checked_mul(3)) - .ok_or_else(|| failed("shell containment work exceeds the grouping limit"))?; - containment_work = containment_work.checked_add(work).ok_or_else(|| failed("shell containment work exceeds the grouping limit"))?; - if containment_work > MAX_CONTAINMENT_WORK { - return Err(failed("shell containment work exceeds the grouping limit")); - } - let mut contained = None; - for p in inner_mesh.positions.iter().copied() { - let hit = outer_mesh.contains(p); - if contained.is_some_and(|previous| previous != hit) { - return Err(failed("shell containment is inconsistent; cavity ownership is ambiguous")); - } - contained = Some(hit); - } - if let Some(slot) = inside.get_mut(inner).and_then(|row| row.get_mut(outer)) { - *slot = contained == Some(true); - } - } - } - } - let mut parent = Vec::with_capacity(meshes.len()); - for i in 0..meshes.len() { - let row = inside.get(i).ok_or_else(|| failed("missing containment"))?; - let candidates: Vec<_> = row.iter().enumerate().filter_map(|(j, hit)| hit.then_some(j)).collect(); - for (k, a) in candidates.iter().enumerate() { - for b in candidates.iter().skip(k + 1) { - if !inside.get(*a).and_then(|r| r.get(*b)).copied().unwrap_or(false) - && !inside.get(*b).and_then(|r| r.get(*a)).copied().unwrap_or(false) - { - return Err(failed("multiple overlapping shell owners")); - } - } - } - let owner = candidates.into_iter().min_by(|a, b| { - volumes.get(*a).copied().unwrap_or(f64::INFINITY).abs().total_cmp(&volumes.get(*b).copied().unwrap_or(f64::INFINITY).abs()) - }); - let outward = volumes.get(i).is_some_and(|v| *v > 0.0); - match owner { - None if !outward => return Err(failed("inward shell has no enclosing material shell")), - Some(p) if volumes.get(p).is_some_and(|v| (*v > 0.0) == outward) => { - return Err(failed("nested shells do not alternate material and void")); - } - _ => {} - } - parent.push(owner); - } - let mut groups = Vec::new(); - for (i, v) in volumes.iter().enumerate() { - if *v <= 0.0 { - continue; - } - let mut group = vec![i]; - group.extend(parent.iter().enumerate().filter_map(|(j, p)| (*p == Some(i)).then_some(j))); - groups.push(group); - } - Ok(groups) -} diff --git a/crates/kernel/src/smlib_boolean.rs b/crates/kernel/src/smlib_boolean.rs new file mode 100644 index 000000000..f660f631b --- /dev/null +++ b/crates/kernel/src/smlib_boolean.rs @@ -0,0 +1,129 @@ +//! Booleans through SMLib: each operand's schema 4 record built in SMLib and tagged as operand 0 +//! or 1, `SmBrep` boolean, the result exported to schema 4 and decoded as a kernel body. The result's history is SMLib's own (its tags carried through the +//! operation), renumbered from SMLib's face and edge order into the operands' and the result's +//! ([`crate::history::History`]'s contract). A result SMLib's own check or the record's geometry +//! check refuses is an error, never a body. + +pub(crate) use smlib::{boolean as smlib_boolean, union_all as smlib_union_all}; + +mod smlib { + use solidcraft_smlib::{BooleanOp, CheckLevel}; + + use crate::body::Body; + use crate::history::History; + use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; + use crate::ops::BoolOp; + use crate::validation::{Checked, Step}; + use crate::{KernelError, Result, record}; + + fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib boolean: {what}"), e) + } + + /// `a` and `b` combined by `op` in SMLib, with the history SMLib's tags give (none where a + /// body's face and edge order cannot be matched to SMLib's). `None`: the result is empty. + pub(crate) fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { + a.require_brep("a boolean")?; + b.require_brep("a boolean")?; + let (sa, oa) = smlib_body_ordered(a)?; + let (sb, ob) = smlib_body_ordered(b)?; + let ta = sa.tagged(0).map_err(|e| failed("tag", e))?; + let tb = sb.tagged(1).map_err(|e| failed("tag", e))?; + let kind = match op { + BoolOp::Union => BooleanOp::Union, + BoolOp::Cut => BooleanOp::Subtract, + BoolOp::Intersect => BooleanOp::Intersect, + }; + let Some(r) = ta.boolean(&tb, kind).map_err(|e| failed("operation", e))? else { return Ok(None) }; + let step = checked(&r, &[&sa, &sb])?; + let (body, or) = body_from_smlib_ordered(&r)?; + let history = match (oa, ob, or) { + (Some(oa), Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[oa, ob], &or).map(Some).unwrap_or_else(|e| { + log::debug!(target: "smlib", "boolean history: {e}"); + None + }), + _ => None, + }; + Ok(Some(left(with_history(body, history, a, b), step, r))) + } + + /// The union of `bodies` in one SMLib call, each tagged as its own operand, checked once: + /// the result's history is over `bodies` in order. At least one body. + pub(crate) fn union_all(bodies: &[&Body]) -> Result { + if bodies.len() > solidcraft_smlib::MAX_UNION_BREPS { + return Err(KernelError::Invalid(format!("a union takes at most {} bodies", solidcraft_smlib::MAX_UNION_BREPS))); + } + let mut operands = Vec::with_capacity(bodies.len()); + let mut tagged = Vec::with_capacity(bodies.len()); + let mut orders = Some(Vec::with_capacity(bodies.len())); + for (i, body) in bodies.iter().enumerate() { + body.require_brep("a union")?; + let (s, order) = smlib_body_ordered(body)?; + tagged.push(s.tagged(i).map_err(|e| failed("tag", e))?); + operands.push(s); + orders = orders.zip(order).map(|(mut v, o)| { + v.push(o); + v + }); + } + let refs: Vec<&solidcraft_smlib::Brep> = tagged.iter().collect(); + let r = solidcraft_smlib::Brep::union_all(&refs).map_err(|e| failed("operation", e))?; + let operand_refs: Vec<&solidcraft_smlib::Brep> = operands.iter().collect(); + let step = checked(&r, &operand_refs)?; + let (body, or) = body_from_smlib_ordered(&r)?; + let history = match (orders, or) { + (Some(orders), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&orders, &or).map(Some).unwrap_or_else(|e| { + log::debug!(target: "smlib", "union history: {e}"); + None + }), + _ => None, + }; + Ok(left(body.with_checked_history(history, &record::counts(bodies)), step, r)) + } + + /// `body`, decoded from `r`, keeping `r` for the check at the end of its feature when the + /// step left it there. + fn left(body: Body, step: Step, r: solidcraft_smlib::Brep) -> Body { + if step == Step::Defer { body.left_unchecked("SMLib boolean", Checked::Combined, r) } else { body } + } + + /// An error unless SMLib's check accepts `r`, the result of combining `operands` (checked + /// here unless the evaluation's validation mode leaves it to the feature's end, + /// `crate::validation`): what was done with the check. + fn checked(r: &solidcraft_smlib::Brep, operands: &[&solidcraft_smlib::Brep]) -> Result { + let step = crate::validation::step(); + if step != Step::Check { + return Ok(step); + } + // Solids touching each other along an edge or at a vertex come back as one non-manifold + // body, which the export splits into separate solids: SMLib's check is of those, imported + // as given (its check of the touching arrangement itself refuses the radial order of + // faces round an edge they share). + let check = crate::validation::check_result(r, Checked::Combined).map_err(|e| KernelError::Failed(format!("SMLib boolean: {e}")))?; + if check.is_valid() { + return Ok(step); + } + // Whether an operand failed it already says whose the fault is. + let failing: Vec = operands + .iter() + .enumerate() + .filter(|(_, s)| s.check(CheckLevel::All).is_ok_and(|c| !c.is_valid())) + .map(|(i, _)| match (operands.len(), i) { + (2, 0) => "the first operand".to_string(), + (2, _) => "the second operand".to_string(), + _ => format!("operand {i}"), + }) + .collect(); + let what = if failing.is_empty() { + "SMLib's check refuses the result".to_string() + } else { + format!("SMLib's check refuses the result ({} already fails it)", failing.join(" and ")) + }; + Err(failed(&what, check)) + } + + /// `body` with `history` where it describes `body` made from `a` and `b`. + fn with_history(body: Body, history: Option, a: &Body, b: &Body) -> Body { + body.with_checked_history(history, &record::counts(&[a, b])) + } +} diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rs new file mode 100644 index 000000000..5a7a68c0d --- /dev/null +++ b/crates/kernel/src/smlib_sweeps.rs @@ -0,0 +1,1701 @@ +//! Extrusions, revolutions, sweeps, lofts and screw sweeps through SMLib: the profile's +//! segments go to SMLib as 3D curves (lines, circular arcs, Béziers and conics as NURBS), SMLib +//! sweeps them, and the result comes back through its schema 4 record as a kernel body. A result +//! SMLib's own check refuses is an error, never a body. An option SMLib has no sweep for is "not +//! supported yet". +//! +//! A sweep that twists, scales, keeps an orientation direction or follows guide rails, and a +//! loft that follows guide rails, place the profile at stations by the laws the kernel's own +//! sweeps and lofts define ([`crate::sweep_path`], [`crate::loft_rails`]); each section is the +//! profile's exact image, and SMLib skins the walls through them. +//! +//! History is in the builders' vocabulary ([`FaceOrigin::Profile`], [`FaceOrigin::Cap`]), found +//! from the result's geometry ([`crate::provenance`] does the same for operations without exact +//! history): a wall comes from the profile segments whose curves its edge at the start runs +//! along (a wall SMLib makes over several tangent segments comes from all of them), and from +//! those whose middles it holds half-way along the sweep where that is known (extrusions, +//! revolutions); the face in the start plane is the start cap, the one in the end plane (or, +//! where the sweep has no end plane, the planar face left over) the end cap. + +use solidcore_record::{Plane, Region2, Seg2, Vec3}; +use solidcraft_geom::prelude::*; + +use crate::body::Body; +use crate::numbered::{NumberedLoop, NumberedRegion}; +use crate::{KernelError, Result}; + +/// A profile segment as SMLib gets it, with the profile segments it stands for. +pub(crate) struct Piece { + pub seg: Seg2, + pub numbers: Vec, + /// The segment as drawn that names it: itself, or for collinear lines joined into one, the + /// first of them. + pub drawn: Seg2, + /// It carries on the piece before it as one curve (pieces of one ellipse or spline): SMLib + /// gets the run as one B-spline and sweeps one wall over it. + pub joins_previous: bool, +} + +/// The segments of `loops` as pieces, loop after loop. +pub(crate) fn pieces<'a>(loops: impl IntoIterator) -> Vec { + loops + .into_iter() + .flat_map(|l| l.lp.segs.iter().enumerate().map(|(i, s)| Piece { seg: *s, numbers: l.numbers(i).to_vec(), drawn: *s, joins_previous: false })) + .collect() +} + +/// The pieces of `joined` (`drawn` with collinear lines joined): outer loop, then holes, each +/// joined line named by the first line drawn under it. +pub(crate) fn region_pieces(joined: &NumberedRegion, drawn: &NumberedRegion) -> Vec { + let firsts: Vec = drawn.loops().flat_map(|l| l.lp.segs.iter().copied()).collect(); + pieces(joined.loops()) + .into_iter() + .map(|mut x| { + if x.numbers.len() > 1 + && let Some(first) = firsts.iter().find(|d| d.start() == x.seg.start()) + { + x.drawn = *first; + } + x + }) + .collect() +} + +fn not_supported(what: &str) -> KernelError { + KernelError::Failed(format!("not supported yet: {what}")) +} + +/// How an extrusion's walls lean. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Draft { + /// Radians; positive grows the profile (as [`crate::extrude_tapered`] takes it). + pub taper: f64, + /// A height (less than the distance) the walls first stand straight for, before they slope + /// on to the same far end ([`crate::extrude_tapered_between`]'s foot). + pub foot: f64, + /// How the sharp corners close. + pub corner: crate::DraftCorner, +} + +pub(crate) use imp::{ + body_from_record, curve, extrude, extrude_drafted_with_holes, face_section, loft, loft_rails, loft_to_point, path_curve, project_onto_face, + revolve, screw, screw_radial, sphere, sweep, sweep_controlled, +}; + +/// Refuses what no SMLib sweep does, before any work. +pub(crate) fn refuse(what: &str) -> KernelError { + not_supported(&format!("SMLib {what}")) +} + +mod imp { + use std::collections::BTreeSet; + + use solidcraft_smlib::sweeps::{Affine, Curve, DraftCorner, Ends, SweepFrame}; + use solidcraft_smlib::{Brep, CheckLevel}; + + use solidcore_record::Vec2; + + use super::*; + use crate::history::FaceProv; + use crate::provenance::{closest_on_tri, face_tris}; + use crate::record; + + fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {what}"), e) + } + + fn corner(c: crate::DraftCorner) -> DraftCorner { + match c { + crate::DraftCorner::PreserveCurvature => DraftCorner::Curvature, + crate::DraftCorner::Tangent => DraftCorner::Tangent, + crate::DraftCorner::Round => DraftCorner::Round, + } + } + + fn p(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] + } + + /// The segment in 3D on `plane`, as SMLib's curve. + pub(crate) fn curve(plane: &Plane, s: &Seg2) -> Result { + let w = |q: Vec2| p(plane.to_world(q)); + let n = plane.x.cross(plane.y).normalized().ok_or_else(|| KernelError::Invalid("profile plane".into()))?; + let bezier = |pts: &[Vec2], weights: &[f64]| { + let degree = pts.len().saturating_sub(1); + let points = pts.iter().zip(weights).map(|(q, wt)| { + let [x, y, z] = w(*q); + [x, y, z, *wt] + }); + let knots = std::iter::repeat_n(0.0, degree + 1).chain(std::iter::repeat_n(1.0, degree + 1)).collect(); + Curve::Nurbs { degree, points: points.collect(), knots } + }; + Ok(match *s { + Seg2::Line { a, b } => Curve::Line { start: w(a), end: w(b) }, + Seg2::Arc { center, radius, start, sweep } => { + // A full circle re-split for a loft may come out a rounding over one turn. + if !(sweep.abs() <= std::f64::consts::TAU * (1.0 + 1e-9)) { + return Err(KernelError::Invalid("an arc turns more than once".into())); + } + let sweep = sweep.clamp(-std::f64::consts::TAU, std::f64::consts::TAU); + // Clockwise in the plane is counter-clockwise about the other normal, where a + // plane angle t is the angle -t. + let (axis, a0) = if sweep >= 0.0 { (n, start) } else { (-n, -start) }; + Curve::Arc { center: w(center), axis: p(axis), reference: p(plane.x), radius, start: a0, end: a0 + sweep.abs() } + } + Seg2::Cubic { p0, p1, p2, p3 } => bezier(&[p0, p1, p2, p3], &[1.0; 4]), + Seg2::Conic { a, apex, b, w: wt } => bezier(&[a, apex, b], &[1.0, wt, 1.0]), + Seg2::Bezier { n: degree, p: pts } => { + let pts = pts.get(..=usize::from(degree)).ok_or_else(|| KernelError::Invalid("Bézier degree".into()))?; + bezier(pts, &vec![1.0; pts.len()]) + } + }) + } + + /// The pieces as SMLib's curves: one each, but one B-spline for each run of pieces that join + /// the one before them ([`Piece::joins_previous`]). + fn curves(plane: &Plane, pieces: &[Piece]) -> Result> { + let mut out = Vec::new(); + let mut run = Vec::new(); + for x in pieces { + if !x.joins_previous && !run.is_empty() { + out.push(joined(std::mem::take(&mut run))?); + } + run.push(curve(plane, &x.seg)?); + } + if !run.is_empty() { + out.push(joined(run)?); + } + Ok(out) + } + + /// Bézier curves of one degree, each starting where the one before ends, as the one B-spline + /// they are, exactly: their control points in a row (each joint once) on knots repeated the + /// degree times at each joint. A rational piece's weights are scaled (which leaves it the same + /// curve) to meet the weight the piece before ends with. Each piece's knot span is as long as + /// keeps the speed through the joint the same on both sides, so pieces meeting tangentially + /// (the pieces of one ellipse or spline) join with a continuous first derivative: SMLib makes + /// one wall over a curve that is, and splits it where the derivative jumps. + fn joined(run: Vec) -> Result { + if run.len() == 1 { + return run.into_iter().next().ok_or_else(|| KernelError::Invalid("an empty run of curves".into())); + } + let not_one = || KernelError::Invalid("the pieces of one curve are not Béziers of one degree".into()); + let xyz = |q: &[f64; 4]| Vec3::new(q[0], q[1], q[2]); + let mut degree = None; + let mut points: Vec<[f64; 4]> = Vec::new(); + let mut knots = Vec::new(); + // The knot at the last joint, and the length of the span before it. + let (mut at, mut span) = (0.0, 1.0); + for c in &run { + let Curve::Nurbs { degree: d, points: ps, .. } = c else { return Err(not_one()) }; + if degree.is_some_and(|p| p != *d) || ps.len() != d + 1 || *d == 0 { + return Err(not_one()); + } + degree = Some(*d); + let (Some(first), Some(second)) = (ps.first(), ps.get(1)) else { return Err(not_one()) }; + let (Some(last), Some(before)) = (points.last(), points.len().checked_sub(2).and_then(|i| points.get(i))) else { + points.extend(ps.iter().copied()); + knots.extend(std::iter::repeat_n(0.0, d + 1)); + continue; + }; + let scale = last[3] / first[3]; + if !(scale.is_finite() && scale > 0.0) { + return Err(not_one()); + } + // The derivative of a rational Bézier on a span of length h at its end is + // d (w[d-1] / w[d]) (P[d] - P[d-1]) / h, at its start d (w[1] / w[0]) (P[1] - P[0]) / h. + let ending = (xyz(last) - xyz(before)) * (before[3] / last[3]) * (1.0 / span); + let starting = (xyz(second) - xyz(first)) * (second[3] / first[3]); + let next = starting.len() / ending.len(); + at += span; + span = if next.is_finite() && next > 0.0 { next } else { 1.0 }; + points.extend(ps.iter().skip(1).map(|q| [q[0], q[1], q[2], q[3] * scale])); + knots.extend(std::iter::repeat_n(at, *d)); + } + let degree = degree.ok_or_else(not_one)?; + knots.extend(std::iter::repeat_n(at + span, degree + 1)); + Ok(Curve::Nurbs { degree, points, knots }) + } + + /// A chain of sketch segments on `plane` as SMLib's curves, one each, exactly (lines, arcs, + /// Béziers and conics as NURBS): what SMLib's sweeps take as a profile or a path. + #[allow(dead_code)] // For the sheet builders, which still build their own wires. + pub(crate) fn chain_curves(plane: &Plane, segs: &[Seg2]) -> Result> { + segs.iter().map(|s| curve(plane, s)).collect() + } + + /// The kernel body of an SMLib result SMLib's own check finds valid (checked here unless the + /// evaluation's validation mode leaves it to the feature's end, `crate::validation`). + fn body_of(brep: Brep, what: &str) -> Result { + use crate::validation::{Checked, Step}; + let step = crate::validation::step(); + if step == Step::Check { + let check = brep.check(CheckLevel::All).map_err(|e| failed(what, e))?; + if !check.is_valid() { + return Err(failed(what, format!("SMLib's check refuses the result: {check}"))); + } + } + let body = crate::native::body_from_smlib(&brep)?; + Ok(if step == Step::Defer { body.left_unchecked(&format!("SMLib {what}"), Checked::AsIs, brep) } else { body }) + } + + /// The body (a solid or a sheet) a schema 4 record describes, taken by SMLib as a + /// modeller's own record (no healing) and checked there. + pub(crate) fn body_from_record(record: &solidcore_record::brep::Brep, what: &str) -> Result { + let brep = Brep::from_record(record, true).map_err(|e| failed(what, e))?; + body_of(brep, what) + } + + /// The sketch segments `segs` on `plane` projected along `direction` onto the face of + /// `body` at `face_at`: SMLib's projection (smlib_project_curves), each projected curve the + /// B-spline SMLib made, as a record curve on its interval, within a millionth of the body's + /// size of the true projection. + pub(crate) fn project_onto_face( + body: &Body, + face_at: Vec3, + plane: &Plane, + segs: &[Seg2], + direction: Vec3, + ) -> Result> { + let c = segs.iter().map(|s| curve(plane, s)).collect::>>()?; + let out = body + .smlib()? + .project_curves(p(face_at), pick_reach(body), &c, p(direction), curve_tolerance(body)) + .map_err(|e| curves_error("curve projection", e))?; + record_curves(out, "curve projection") + } + + /// The face of `body` at `face_at` cut by the plane through `plane_point` square to `normal`, + /// SMLib's section curves on that face, as record curves on their intervals. + pub(crate) fn face_section( + body: &Body, + face_at: Vec3, + plane_point: Vec3, + normal: Vec3, + ) -> Result> { + let out = body + .smlib()? + .face_section(p(face_at), pick_reach(body), p(plane_point), p(normal), curve_tolerance(body)) + .map_err(|e| curves_error("face section", e))?; + record_curves(out, "face section") + } + + /// How far a point may be from the face it picks: the kernel's picking reach. + fn pick_reach(body: &Body) -> f64 { + body.size().max(1e-9) * 1e-3 + 1e-6 + } + + /// How close a curve SMLib makes on a body's faces keeps to the true one: a millionth of the + /// body's size. + fn curve_tolerance(body: &Body) -> f64 { + (body.size() * 1e-6).max(1e-6) + } + + fn curves_error(what: &str, e: solidcraft_smlib::Error) -> KernelError { + match e { + solidcraft_smlib::Error::Empty => KernelError::Invalid(format!("{what}: no curve on the face")), + solidcraft_smlib::Error::NoMatch { .. } => KernelError::Invalid(format!("{what}: no face of the body at the point")), + e => failed(what, e), + } + } + + /// SMLib's NURBS curves as record curves (rational splines) on their intervals. + fn record_curves(out: Vec<(Curve, [f64; 2])>, what: &str) -> Result> { + out.into_iter() + .map(|(c, interval)| match c { + Curve::Nurbs { points, knots, .. } => { + let homogeneous = points.iter().map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).collect(); + Ok((solidcore_record::brep::Curve::RationalSpline { knots, homogeneous }, interval)) + } + _ => Err(failed(what, "a curve SMLib made is not a B-spline")), + }) + .collect() + } + + /// SMLib's sphere about `center`, each face swept from the arc (segment 0) of the half disc + /// a sphere revolves. + pub(crate) fn sphere(center: Vec3, radius: f64) -> Result { + let brep = Brep::make_sphere(p(center), radius).map_err(|e| failed("sphere", e))?; + let body = body_of(brep, "sphere")?; + let faces = body.face_count(); + Ok(record::attach(body, &[], Some(vec![record::profile(&[0usize]); faces]), &[])) + } + + /// A point a wall is known by: on its edge in the start plane, or inside it; and the piece + /// (by index) that sweeps it. + struct Seed { + at: Vec3, + piece: usize, + } + + fn seeds(plane: &Plane, pieces: &[Piece], to: impl Fn(Vec3) -> Vec3) -> Vec { + pieces.iter().enumerate().map(|(piece, x)| Seed { at: to(plane.to_world(x.seg.point_at(0.5))), piece }).collect() + } + + /// What a face of a swept body is. + #[derive(Clone, Debug, PartialEq)] + enum Role { + Start, + End, + /// A wall, swept from these pieces. + Wall(BTreeSet), + Unknown, + } + + /// The role of each face of `body` swept from the profile in `start` (see the module notes): + /// `edges` lie on the walls' edges in the start plane, `inside` inside the walls; the face in + /// `end` (or, with `end` unset and `rest_is_end`, a planar face nothing else claims) is the + /// end cap. + fn roles(body: &Body, start: &Plane, end: Option<&Plane>, edges: &[Seed], inside: &[Seed], rest_is_end: bool) -> Result> { + let size = body.size().max(1e-9); + let mesh_tol = (size * 2e-4).max(1e-6); + let m = body.mesh(&crate::MeshTolerance::chord(mesh_tol))?; + let faces = face_tris(&m); + let n = body.face_count(); + // A cap's points lie on its plane to the evaluation's precision. Sized to the body, the + // flatness tolerance can exceed the gap between parallel start and end planes (a box + // 0.1 µm thick in a 14 mm body), which would put each cap in both: it stays under a + // quarter of that gap. Planes that coincide (the ends of a half turn) are told apart by + // the profile's edges instead. + let gap = end + .filter(|e| e.normal().cross(start.normal()).len() < 1e-9) + .map(|e| start.height(e.origin).abs()) + .filter(|g| *g > size * 1e-9) + .unwrap_or(f64::INFINITY); + let flat_tol = (size * 1e-5 + 1e-9).min(0.25 * gap); + let near = 3.0 * mesh_tol + flat_tol; + let flat = |f: usize, pl: &Plane| { + faces.get(f).is_some_and(|ft| !ft.tris.is_empty() && ft.tris.iter().all(|(t, _)| t.iter().all(|q| pl.height(*q).abs() <= flat_tol))) + }; + let planar = + |f: usize| faces.get(f).is_some_and(|ft| ft.tris.first().is_some_and(|(_, n0)| ft.tris.iter().all(|(_, nn)| nn.dot(*n0) > 1.0 - 1e-6))); + // A face in the start plane is the start cap where the profile bounds it (a screw's far + // end after whole turns lies in the same plane, elsewhere). + let touches = |f: usize| { + edges.is_empty() + || faces.get(f).is_some_and(|ft| edges.iter().any(|s| ft.tris.iter().any(|(t, _)| closest_on_tri(s.at, *t).dist(s.at) <= near))) + }; + let start_cap: Vec = (0..n).map(|f| flat(f, start) && touches(f)).collect(); + let end_cap: Vec = (0..n).map(|f| end.is_some_and(|e| flat(f, e))).collect(); + let cap = |f: usize| start_cap.get(f).copied().unwrap_or(false) || end_cap.get(f).copied().unwrap_or(false); + let mut swept: Vec> = vec![BTreeSet::new(); n]; + // Each seed lies on its own piece's edge (within the mesh's sag on a curve); `near` is + // sized to the body, so on a side shorter than it (a 0.3 mm wall of a 1 m label) the + // neighbours' edges are near too. The seed marks only the edges nearest it: the one it + // lies on, or both pieces of an edge split at its middle. + let start_edges: Vec<(&Vec, &Vec)> = m + .edges + .iter() + .zip(&m.edge_faces) + .filter(|(poly, _)| poly.len() >= 2 && poly.iter().all(|q| start.height(*q).abs() <= flat_tol)) + .collect(); + for s in edges { + let dist = |poly: &[Vec3]| poly.windows(2).map(|w| s.at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min); + let ds: Vec = start_edges.iter().map(|(poly, _)| dist(poly)).collect(); + let nearest = ds.iter().copied().fold(f64::INFINITY, f64::min); + for ((_, fs), d) in start_edges.iter().zip(&ds) { + if *d <= near && *d <= nearest + flat_tol { + for f in fs.iter().map(|f| *f as usize).filter(|f| !cap(*f)) { + if let Some(set) = swept.get_mut(f) { + set.insert(s.piece); + } + } + } + } + } + // Inside the walls: the face nearest each point (bounded work). + let tris: usize = faces.iter().map(|f| f.tris.len()).sum(); + if tris.saturating_mul(inside.len()) <= 50_000_000 { + for s in inside { + let mut best = (f64::INFINITY, usize::MAX); + for (fi, ft) in faces.iter().enumerate() { + if !ft.bounds.inflated(best.0.min(size)).contains(s.at) { + continue; + } + for (t, _) in &ft.tris { + let d = closest_on_tri(s.at, *t).dist(s.at); + if d < best.0 { + best = (d, fi); + } + } + } + if best.0 <= 5.0 * near + && !cap(best.1) + && let Some(set) = swept.get_mut(best.1) + { + set.insert(s.piece); + } + } + } + Ok(swept + .into_iter() + .enumerate() + .map(|(f, set)| { + if start_cap.get(f).copied().unwrap_or(false) { + Role::Start + } else if end_cap.get(f).copied().unwrap_or(false) { + Role::End + } else if !set.is_empty() { + Role::Wall(set) + } else if end.is_none() && rest_is_end && planar(f) { + Role::End + } else { + log::debug!(target: "smlib", "sweep history: face {f} comes from no profile segment"); + Role::Unknown + } + }) + .collect()) + } + + /// The history the roles give: caps, and walls from their pieces' profile segments. + fn history(roles: &[Role], pieces: &[Piece]) -> Vec { + roles + .iter() + .map(|r| match r { + Role::Start => record::cap(false), + Role::End => record::cap(true), + Role::Wall(set) => record::profile(set.iter().filter_map(|i| pieces.get(*i)).flat_map(|x| x.numbers.iter())), + Role::Unknown => record::generated(Vec::new()), + }) + .collect() + } + + fn with_history(body: Body, roles: &[Role], pieces: &[Piece]) -> Result { + Ok(record::attach(body, &[], Some(history(roles, pieces)), &[])) + } + + /// The profile `pieces` on `plane`, moved `from` along its normal, extruded `distance` + /// along `sign` (±1) times the normal, straight or drafted. + pub(crate) fn extrude( + plane: &Plane, + pieces: &[Piece], + region: Option<&Region2>, + from: f64, + distance: f64, + sign: f64, + draft: Option, + ) -> Result { + let base = plane.offset(from); + let n = plane.x.cross(plane.y).normalized().ok_or_else(|| KernelError::Invalid("profile plane".into()))?; + let dir = n * sign.signum(); + let c = curves(&base, pieces)?; + let top = plane.offset(from + sign.signum() * distance); + let edges = seeds(&base, pieces, |q| q); + let foot = draft.map_or(0.0, |d| d.foot); + if let Some(d) = draft.filter(|d| d.foot > 0.0) { + // A straight foot, then the walls sloping from its top to the far end the taper gives + // from the base, joined face to face where they meet. + if !(foot < distance) { + return Err(KernelError::Invalid(format!("taper foot = {foot}"))); + } + let knee = plane.offset(from + sign.signum() * foot); + let lean = -(distance * d.taper.tan() / (distance - foot)).atan(); + let prism = Brep::extrude(&c, p(dir), foot, 0.0, DraftCorner::default(), true).map_err(|e| failed("extrude", e))?; + let slope = + Brep::extrude(&curves(&knee, pieces)?, p(dir), distance - foot, lean, corner(d.corner), true).map_err(|e| failed("extrude", e))?; + let brep = prism.boolean(&slope, solidcraft_smlib::BooleanOp::Union).map_err(|e| failed("extrude", e))?; + let brep = brep.ok_or_else(|| failed("extrude", "nothing is left"))?; + let body = body_of(brep, "extrude")?; + // The caps and the foot's walls from the base; the sloping walls (and the foot's again) + // from the edges at the knee, which both stand on. + let low = roles(&body, &base, Some(&top), &edges, &[], false)?; + let high = roles(&body, &knee, Some(&top), &seeds(&knee, pieces, |q| q), &[], false)?; + let roles: Vec = low + .into_iter() + .zip(high) + .map(|(a, b)| match (a, b) { + (Role::Wall(mut x), Role::Wall(y)) => { + x.extend(y); + Role::Wall(x) + } + (Role::Unknown, w @ Role::Wall(_)) => w, + (a, _) => a, + }) + .collect(); + return with_history(body, &roles, pieces); + } + // SMLib's draft is positive inward; the kernel's taper grows the profile. + let lean = draft.map_or(0.0, |d| -d.taper); + let rule = draft.map_or(DraftCorner::default(), |d| corner(d.corner)); + let brep = Brep::extrude(&c, p(dir), distance, lean, rule, true).map_err(|e| failed("extrude", e))?; + let body = body_of(brep, "extrude")?; + // Half-way along a straight wall lies over its segment; a drafted one has moved. + let inside = if draft.is_none() { seeds(&base, pieces, |q| q + dir * (distance * 0.5)) } else { Vec::new() }; + let roles = roles(&body, &base, Some(&top), &edges, &inside, false)?; + let sources = (draft.is_none() && sign > 0.0).then(|| extrude_sources(&roles, pieces, region, plane, &base, &top)); + let body = body.with_face_sources(sources.map(std::sync::Arc::new)); + with_history(body, &roles, pieces) + } + + /// The solid `pieces` (one closed loop) on `plane` sweep, moved `from` along its normal and + /// drafted `d` over `distance` along `sign` × the normal, as [`extrude`] builds it, without + /// its roles. + fn drafted_loop(plane: &Plane, pieces: &[Piece], from: f64, distance: f64, sign: f64, d: Draft) -> Result { + let base = plane.offset(from); + let n = plane.x.cross(plane.y).normalized().ok_or_else(|| KernelError::Invalid("profile plane".into()))?; + let dir = n * sign.signum(); + if d.foot > 0.0 { + if !(d.foot < distance) { + return Err(KernelError::Invalid(format!("taper foot = {}", d.foot))); + } + let knee = plane.offset(from + sign.signum() * d.foot); + let lean = -(distance * d.taper.tan() / (distance - d.foot)).atan(); + let prism = + Brep::extrude(&curves(&base, pieces)?, p(dir), d.foot, 0.0, DraftCorner::default(), true).map_err(|e| failed("extrude", e))?; + let slope = + Brep::extrude(&curves(&knee, pieces)?, p(dir), distance - d.foot, lean, corner(d.corner), true).map_err(|e| failed("extrude", e))?; + let brep = prism.boolean(&slope, solidcraft_smlib::BooleanOp::Union).map_err(|e| failed("extrude", e))?; + return brep.ok_or_else(|| failed("extrude", "nothing is left")); + } + Brep::extrude(&curves(&base, pieces)?, p(dir), distance, -d.taper, corner(d.corner), true).map_err(|e| failed("extrude", e)) + } + + /// A drafted extrusion of a region with holes: SMLib's draft extrusion takes one loop, so the + /// outer loop is drafted and each hole, turned counter-clockwise, is drafted the other way + /// and cut from it. Every wall leans by the taper on the material's side, as a single + /// drafted sweep would: a taper that narrows the outer boundary widens the holes. `outer` and + /// `holes` are the loops' pieces at `from` as [`extrude`] takes them, `all` the region's + /// pieces in their numbering (outer, then the holes as they bound the material), which the + /// walls' roles name. + pub(crate) fn extrude_drafted_with_holes( + plane: &Plane, + outer: &[Piece], + holes: &[Vec], + all: &[Piece], + from: f64, + distance: f64, + sign: f64, + draft: Draft, + ) -> Result { + let mut brep = drafted_loop(plane, outer, from, distance, sign, draft)?; + for h in holes { + let cutter = drafted_loop(plane, h, from, distance, sign, Draft { taper: -draft.taper, ..draft })?; + brep = brep + .boolean(&cutter, solidcraft_smlib::BooleanOp::Subtract) + .map_err(|e| failed("extrude", e))? + .ok_or_else(|| KernelError::Invalid("the draft leaves nothing of the profile".into()))?; + } + let body = body_of(brep, "extrude")?; + let base = plane.offset(from); + let top = plane.offset(from + sign.signum() * distance); + let low = roles(&body, &base, Some(&top), &seeds(&base, all, |q| q), &[], false)?; + let roles: Vec = if draft.foot > 0.0 { + // The sloping walls stand on their edges at the knee, as in [`extrude`]. + let knee = plane.offset(from + sign.signum() * draft.foot); + let high = roles(&body, &knee, Some(&top), &seeds(&knee, all, |q| q), &[], false)?; + low.into_iter() + .zip(high) + .map(|(a, b)| match (a, b) { + (Role::Wall(mut x), Role::Wall(y)) => { + x.extend(y); + Role::Wall(x) + } + (Role::Unknown, w @ Role::Wall(_)) => w, + (a, _) => a, + }) + .collect() + } else { + low + }; + with_history(body, &roles, all) + } + + /// The construction sources of a straight extrusion's faces along the normal of `sketch`, as + /// [`crate::extrude`] gives them: each cap the region at its end (both caps found once + /// each), each wall swept from one piece that piece as drawn, a line's with the wall's plane. + fn extrude_sources( + roles: &[Role], + pieces: &[Piece], + region: Option<&Region2>, + sketch: &Plane, + base: &Plane, + top: &Plane, + ) -> Vec> { + let once = |role: &Role| roles.iter().filter(|r| *r == role).count() == 1; + let caps = region.filter(|r| once(&Role::Start) && once(&Role::End) && numbered_segments(r) <= 4096); + roles + .iter() + .map(|role| match role { + Role::Start => caps.map(|r| crate::FaceSource::ExtrudeCap { + high: false, + region: r.clone(), + plane: Plane { origin: base.origin, x: sketch.x, y: -sketch.y }, + }), + Role::End => caps.map(|r| crate::FaceSource::ExtrudeCap { high: true, region: r.clone(), plane: *top }), + Role::Wall(set) if set.len() == 1 => set.first().and_then(|i| pieces.get(*i)).map(|x| { + let plane = match x.seg { + Seg2::Line { a, b } => (b - a).normalized().and_then(|d| { + let foot = a - d * a.dot(d); + Plane::new(sketch.to_world(foot), sketch.dir_to_world(d), sketch.normal()) + }), + _ => None, + }; + crate::FaceSource::ExtrudeSide { segment: x.drawn, plane, coalesced: false } + }), + // The one wall over a whole run of pieces of one curve: named by its first piece. + Role::Wall(set) if run_starts(pieces, set).is_some() => run_starts(pieces, set) + .and_then(|i| pieces.get(i)) + .map(|x| crate::FaceSource::ExtrudeSide { segment: x.drawn, plane: None, coalesced: false }), + _ => None, + }) + .collect() + } + + /// The first piece of the run of joined pieces `set` is exactly (all of it, and nothing else). + fn run_starts(pieces: &[Piece], set: &BTreeSet) -> Option { + let (&first, &last) = (set.first()?, set.last()?); + let run = pieces.get(first..=last)?; + let whole = last - first + 1 == set.len() + && run.first().is_some_and(|x| !x.joins_previous) + && run.iter().skip(1).all(|x| x.joins_previous) + && pieces.get(last + 1).is_none_or(|x| !x.joins_previous); + (set.len() > 1 && whole).then_some(first) + } + + fn numbered_segments(r: &Region2) -> usize { + r.outer.segs.len() + r.holes.iter().map(|h| h.segs.len()).sum::() + } + + /// `v` turned by `a` right-handed about the unit `k` (Rodrigues). + fn turned(v: Vec3, k: Vec3, a: f64) -> Vec3 { + v * a.cos() + k.cross(v) * a.sin() + k * (k.dot(v) * (1.0 - a.cos())) + } + + /// The profile `pieces` on `plane` turned `angle` radians (signed, right-handed about `axis`) + /// about the axis through `origin` (both in the plane). Segments on the axis sweep nothing. + pub(crate) fn revolve(plane: &Plane, pieces: &[Piece], origin: Vec3, axis: Vec3, angle: f64) -> Result { + let k = axis.normalized().ok_or_else(|| KernelError::Invalid("revolve axis".into()))?; + let (k, turn) = if angle < 0.0 { (-k, -angle) } else { (k, angle) }; + let turn = turn.min(std::f64::consts::TAU); + let c = curves(plane, pieces)?; + let brep = Brep::revolve(&c, p(origin), p(k), turn, true).map_err(|e| failed("revolve", e))?; + let body = body_of(brep, "revolve")?; + let size = body.size().max(1e-9); + let off_axis = |q: Vec3| { + let w = q - origin; + (w - k * w.dot(k)).len() > size * 1e-7 + }; + let walls: Vec = pieces + .iter() + .filter(|x| [0.0, 0.5, 1.0].iter().any(|t| off_axis(plane.to_world(x.seg.point_at(*t))))) + .map(|x| Piece { seg: x.seg, numbers: x.numbers.clone(), drawn: x.drawn, joins_previous: false }) + .collect(); + let about = |q: Vec3, a: f64| origin + turned(q - origin, k, a); + let full = turn >= std::f64::consts::TAU - 1e-9; + let edges = seeds(plane, &walls, |q| q); + let inside = seeds(plane, &walls, |q| about(q, turn * 0.5)); + let end = (!full).then(|| Plane { origin: about(plane.origin, turn), x: turned(plane.x, k, turn), y: turned(plane.y, k, turn) }); + // A full turn has no caps, and its profile plane holds seams only. + let roles = if full { + roles(&body, &plane.offset(size * 10.0), None, &[], &inside, false)? + } else { + roles(&body, plane, end.as_ref(), &edges, &inside, false)? + }; + with_history(body, &roles, &walls) + } + + /// A path segment as SMLib's curve, exactly. + pub(crate) fn path_curve(s: &crate::PathSeg) -> Result { + Ok(match *s { + crate::PathSeg::Line { a, b } => Curve::Line { start: p(a), end: p(b) }, + crate::PathSeg::Arc { a, center, axis, angle } => { + let k = axis.normalized().ok_or_else(|| KernelError::Invalid("path arc axis".into()))?; + let (k, turn) = if angle < 0.0 { (-k, -angle) } else { (k, angle) }; + let r = a - center; + let radius = r.len(); + let reference = r.normalized().ok_or_else(|| KernelError::Invalid("path arc radius".into()))?; + Curve::Arc { center: p(center), axis: p(k), reference: p(reference), radius, start: 0.0, end: turn } + } + crate::PathSeg::Curve { plane, seg } => curve(&plane, &seg)?, + crate::PathSeg::Bezier(b) => { + let degree = b.degree(); + let points = b.weighted_points().ok_or_else(|| KernelError::Invalid("a path span does not evaluate".into()))?; + Curve::Nurbs { degree, points, knots: std::iter::repeat_n(0.0, degree + 1).chain(std::iter::repeat_n(1.0, degree + 1)).collect() } + } + }) + } + + /// The profile `pieces` on `plane` swept along `path`, turning with it, or only moving along + /// it when `translate`. SMLib's sweep follows a smooth path; at a corner (the direction + /// jumping) the path is swept piece by piece ([`cornered`]). + pub(crate) fn sweep(plane: &Plane, pieces: &[Piece], path: &[crate::PathSeg], translate: bool) -> Result { + if translate { + // Every segment's direction of travel, at its ends and between them. + let bad = || KernelError::Invalid("a path segment has no direction".into()); + let tangents = path + .iter() + .flat_map(|s| (0..=CROSSING_SAMPLES).map(move |i| seg_at(s, i as f64 / CROSSING_SAMPLES as f64).map(|(_, t)| t))) + .collect::>>() + .ok_or_else(bad)?; + crate::sweep_path::crossing_check(plane, &tangents)?; + } + let runs = smooth_runs(path)?; + if runs.len() > 1 { + return cornered(plane, pieces, path, &runs, translate); + } + let (brep, [_, middle, last]) = swept(plane, pieces, path, translate)?; + let body = body_of(brep, "sweep")?; + // The walls known by the profile carried half way (past the start's edges: a wall the + // start touches by no edge, as round a closed path, and walls along later path segments). + let inside = seeds(plane, pieces, |q| apply(&middle, q)); + let start = path.first().map(crate::PathSeg::start); + let end = path.last().map(seg_ends).transpose()?.map(|(_, b)| b); + let roles = match (start, end) { + // Round a closed path there are no caps, and the start holds seams only. + (Some(a), Some(b)) if a.dist(b) <= 1e-6 => roles(&body, &plane.offset(body.size().max(1e-9) * 10.0), None, &[], &inside, false)?, + _ => roles(&body, plane, Some(&placed(plane, &last)), &seeds(plane, pieces, |q| q), &inside, false)?, + }; + with_history(body, &roles, pieces) + } + + /// The sweep of the profile on `plane` along `path`, with the rigid motions SMLib reports + /// carrying the profile onto its first, middle and last sections. + fn swept(plane: &Plane, pieces: &[Piece], path: &[crate::PathSeg], translate: bool) -> Result<(Brep, [Affine; 3])> { + let c = curves(plane, pieces)?; + let route = path.iter().map(path_curve).collect::>>()?; + let frame = if translate { SweepFrame::Translate } else { SweepFrame::Follow }; + Brep::sweep_placed(&c, &route, frame, true).map_err(|e| failed("sweep", e)) + } + + /// `q` moved by the motion `a`. + fn apply(a: &Affine, q: Vec3) -> Vec3 { + let col = |i: usize| a.m.get(i).map_or(Vec3::ZERO, |c| Vec3::new(c[0], c[1], c[2])); + col(0) * q.x + col(1) * q.y + col(2) * q.z + Vec3::new(a.t[0], a.t[1], a.t[2]) + } + + /// `pl` carried by the motion `a` (a rigid motion: its directions turn with it). + fn placed(pl: &Plane, a: &Affine) -> Plane { + let o = apply(a, Vec3::ZERO); + Plane { origin: apply(a, pl.origin), x: apply(a, pl.x) - o, y: apply(a, pl.y) - o } + } + + /// The path's segments in runs along which its direction carries on (within a thousandth of + /// a radian across each joint): a new run starts at each corner. + fn smooth_runs(path: &[crate::PathSeg]) -> Result>> { + let ends: Vec<(Vec3, Vec3)> = path + .iter() + .map(crate::PathSeg::tangents) + .collect::>() + .ok_or_else(|| KernelError::Invalid("a path segment has no direction".into()))?; + let mut runs = Vec::new(); + let mut from = 0; + for (i, w) in ends.windows(2).enumerate() { + if w[0].1.dot(w[1].0) < (1e-3f64).cos() { + runs.push(from..i + 1); + from = i + 1; + } + } + runs.push(from..path.len()); + Ok(runs) + } + + /// `pl` carried rigidly by a turn of `angle` about the unit `k` through `center`. + fn turned_plane(pl: &Plane, center: Vec3, k: Vec3, angle: f64) -> Plane { + Plane { origin: center + turned(pl.origin - center, k, angle), x: turned(pl.x, k, angle), y: turned(pl.y, k, angle) } + } + + fn moved_plane(pl: &Plane, by: Vec3) -> Plane { + Plane { origin: pl.origin + by, ..*pl } + } + + /// Where `s` starts and ends. + fn seg_ends(s: &crate::PathSeg) -> Result<(Vec3, Vec3)> { + Ok(match *s { + crate::PathSeg::Line { a, b } => (a, b), + crate::PathSeg::Arc { a, center, axis, angle } => { + let k = axis.normalized().ok_or_else(|| KernelError::Invalid("path arc axis".into()))?; + (a, crate::build::rotate_about(a, center, k, angle)) + } + crate::PathSeg::Curve { plane, seg } => (plane.to_world(seg.start()), plane.to_world(seg.end())), + crate::PathSeg::Bezier(b) => (b.start(), b.end()), + }) + } + + /// A box on one side of the plane through `at` square to the unit `normal`: a `size` square + /// in the plane, `size` deep along `normal`. + fn half_space(at: Vec3, normal: Vec3, size: f64) -> Result { + let u = if normal.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }; + let u = normal.cross(u).normalized().ok_or_else(|| KernelError::Invalid("mitre plane".into()))?; + let v = normal.cross(u); + let h = size * 0.5; + let c = [at + (u + v) * h, at + (v - u) * h, at - (u + v) * h, at + (u - v) * h]; + let square: Vec = (0..4).map(|i| Curve::Line { start: p(c[i]), end: p(c[(i + 1) % 4]) }).collect(); + Brep::extrude(&square, p(normal), size, 0.0, DraftCorner::default(), true).map_err(|e| failed("mitre", e)) + } + + fn combined(a: &Brep, b: &Brep, op: solidcraft_smlib::BooleanOp, what: &str) -> Result { + a.boolean(b, op).map_err(|e| failed(what, e))?.ok_or_else(|| failed(what, "nothing is left")) + } + + /// A sweep along a path with corners: each smooth run of it swept on its own, and the runs + /// joined at each corner. Turning with the path, the profile turns at a corner about the + /// line square to both directions, and the runs meet in a mitre: each run is swept on + /// straight past the corner (along its direction there) and cut back to the plane that halves + /// the corner, where the next run, cut back the same way, meets it face to face. Only moving + /// along the path, the profile is the same at the corner in both runs, which meet there. + /// + /// History: the start cap is the face in the profile's plane, the end cap the face in its + /// plane at the path's end; each wall comes from the profile segment it is swept from, found + /// on the first run's start or half-way along each run. + fn cornered(plane: &Plane, pieces: &[Piece], path: &[crate::PathSeg], runs: &[std::ops::Range], translate: bool) -> Result { + let start = path.first().map(seg_ends).transpose()?.map(|(a, _)| a).ok_or_else(|| KernelError::Invalid("empty path".into()))?; + // How far the profile reaches from the path. + let reach = pieces + .iter() + .flat_map(|x| (0..=8).map(move |i| x.seg.point_at(f64::from(i) / 8.0))) + .map(|q| plane.to_world(q).dist(start)) + .fold(0.0f64, f64::max); + let mut length = 0.0; + for s in path { + let (a, b) = seg_ends(s)?; + length += a.dist(b).max(match *s { + crate::PathSeg::Arc { a, center, angle, .. } => (a - center).len() * angle.abs(), + crate::PathSeg::Curve { seg, .. } => seg.length(), + crate::PathSeg::Bezier(_) => seg_len(s), + crate::PathSeg::Line { .. } => 0.0, + }); + } + let size = 4.0 * (length + reach) + 1.0; + let tangent = |s: Option<&crate::PathSeg>| { + s.and_then(crate::PathSeg::tangents).ok_or_else(|| KernelError::Invalid("a path segment has no direction".into())) + }; + let (first_t, _) = tangent(path.first())?; + let offsets = section_offsets(plane, pieces, start, first_t, 1.0); + let (_, last_t) = tangent(path.last())?; + let end = path.last().map(seg_ends).transpose()?.map(|(_, b)| b).ok_or_else(|| KernelError::Invalid("empty path".into()))?; + // A closed path ends where it starts, with no caps; at a corner there the last run and the + // first meet in a mitre too. + let closed = end.dist(start) <= 1e-6; + let closing = (closed && last_t.dot(first_t) < (1e-3f64).cos()).then_some(first_t); + let mut pose = *plane; + let mut body: Option = None; + let mut inside = Vec::new(); + // The mitre the next run starts from: its point, its normal (along the run) and the turn. + let mut entry: Option<(Vec3, Vec3, f64)> = match closing { + Some(_) if !translate => { + let (m, turn) = mitre_of(last_t, first_t)?; + Some((start, m, turn)) + } + _ => None, + }; + for (ri, run) in runs.iter().enumerate() { + let segs = path.get(run.clone()).ok_or_else(|| KernelError::Invalid("path run".into()))?; + let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err(KernelError::Invalid("path run".into())) }; + let (t0, _) = first.tangents().ok_or_else(|| KernelError::Invalid("a path segment has no direction".into()))?; + let (_, t1) = last.tangents().ok_or_else(|| KernelError::Invalid("a path segment has no direction".into()))?; + let (a0, _) = seg_ends(first)?; + let (_, b1) = seg_ends(last)?; + let next = match runs.get(ri + 1).and_then(|r| path.get(r.start)) { + Some(s) => Some(tangent(Some(s))?.0), + None => closing, + }; + // The plane halving the corner at the run's end, and the turn there. + let exit = next.map(|t2| mitre_of(t1, t2)).transpose()?; + // Each piece's sweep says where it left the profile: half-way along it each wall lies + // over its piece, and at its end (less any straight lead-out past the corner) the + // profile is where the next run takes it on. + let (piece, at_end) = if translate { + let (piece, [_, middle, last]) = swept(&pose, pieces, segs, true)?; + inside.extend(seeds(&pose, pieces, |q| apply(&middle, q))); + (piece, placed(&pose, &last)) + } else { + // On past each mitre, far enough to take every point of the section to the + // mitre's plane ([`mitre_lead`]). + let pre = entry.map_or(0.0, |(_, _, turn)| mitre_lead(&offsets, reach, turn, false)); + let post = exit.map(|(_, turn)| mitre_lead(&offsets, reach, turn, true)).unwrap_or(0.0); + let mut route = Vec::with_capacity(segs.len() + 2); + if pre > 0.0 { + route.push(crate::PathSeg::Line { a: a0 - t0 * pre, b: a0 }); + } + route.extend_from_slice(segs); + if post > 0.0 { + route.push(crate::PathSeg::Line { a: b1, b: b1 + t1 * post }); + } + let from = moved_plane(&pose, t0 * -pre); + let (mut piece, [_, middle, last]) = swept(&from, pieces, &route, false)?; + // Each wall is known by its piece's middle half way along the stretch of the run + // that point keeps between the mitres: a point standing `s` ahead of the path + // keeps the stretch `s` back from the run's (a profile at a slant to a run shorter + // than its slant reaches past the mitres from the run's middle section). + let run_length: f64 = segs.iter().map(seg_len).sum(); + let origin = a0 - t0 * pre; + inside.extend(pieces.iter().enumerate().map(|(piece, x)| { + let q = from.to_world(x.seg.point_at(0.5)); + let ahead = (q - origin).dot(t0); + let at = carried_along(&route, pre + 0.5 * run_length - ahead).map_or_else(|| apply(&middle, q), |m| apply(&m, q)); + Seed { at, piece } + })); + if let Some((at, toward, _)) = entry { + piece = combined(&piece, &half_space(at, -toward, size)?, solidcraft_smlib::BooleanOp::Subtract, "sweep mitre")?; + } + if let Some((m, _)) = exit { + piece = combined(&piece, &half_space(b1, m, size)?, solidcraft_smlib::BooleanOp::Subtract, "sweep mitre")?; + } + (piece, moved_plane(&placed(&from, &last), t1 * -post)) + }; + body = Some(match body { + None => piece, + Some(b) => combined(&b, &piece, solidcraft_smlib::BooleanOp::Union, "sweep corner")?, + }); + // The profile at the run's end, then turned through the corner onto the next run. + pose = at_end; + entry = None; + if let (Some(t2), Some((m, turn)), false) = (next, exit, translate) { + let k = t1.cross(t2).normalized().ok_or_else(|| KernelError::Invalid("path corner".into()))?; + pose = turned_plane(&pose, b1, k, turn); + entry = Some((b1, m, turn)); + } + } + let brep = body.ok_or_else(|| KernelError::Invalid("empty path".into()))?; + let body = body_of(brep, "sweep")?; + let roles = roles(&body, plane, (!closed).then_some(&pose), &seeds(plane, pieces, |q| q), &inside, false)?; + with_history(body, &roles, pieces) + } + + /// The rigid motion carrying a section from the start of `route` to `along` (clamped to the + /// route) along it, as SMLib's sweep turning with a path of lines and arcs carries it: moved + /// along each line, turned about each arc's axis. None for a route with another curve before + /// that point, whose frame only the sweep knows. + fn carried_along(route: &[crate::PathSeg], along: f64) -> Option { + let mut m = IDENTITY; + let mut left = along.max(0.0); + for s in route { + if left <= 0.0 { + break; + } + let length = seg_len(s); + let d = left.min(length); + m = match *s { + crate::PathSeg::Line { a, b } => affine_moved(&m, (b - a).normalized()? * d), + crate::PathSeg::Arc { center, axis, angle, .. } if length > 0.0 => { + affine_after(&affine_turned(center, axis.normalized()?, angle * d / length), &m) + } + _ => return None, + }; + left -= d; + } + Some(m) + } + + /// The length of a path segment. + fn seg_len(s: &crate::PathSeg) -> f64 { + match *s { + crate::PathSeg::Line { a, b } => a.dist(b), + crate::PathSeg::Arc { a, center, angle, .. } => angle.abs() * a.dist(center), + crate::PathSeg::Curve { seg, .. } => seg.length(), + crate::PathSeg::Bezier(b) => b.length().unwrap_or(f64::NAN), + } + } + + /// The point `f` (0…1) of the way along a path segment, and the unit direction of travel there. + fn seg_at(s: &crate::PathSeg, f: f64) -> Option<(Vec3, Vec3)> { + match *s { + crate::PathSeg::Line { a, b } => Some((a.lerp(b, f), (b - a).normalized()?)), + crate::PathSeg::Arc { a, center, axis, angle } => { + let k = axis.normalized()?; + let q = crate::build::rotate_about(a, center, k, angle * f); + Some((q, (k.cross(q - center) * angle.signum()).normalized()?)) + } + // The parameter whose length from the start is that share of the curve's. + crate::PathSeg::Curve { plane, seg } => { + let want = seg.length() * f; + let (mut lo, mut hi) = (0.0f64, 1.0f64); + for _ in 0..48 { + let t = 0.5 * (lo + hi); + if seg.split_at(t).0.length() < want { + lo = t; + } else { + hi = t; + } + } + let t = 0.5 * (lo + hi); + Some((plane.to_world(seg.point_at(t)), plane.dir_to_world(seg.derivative(t)).normalized()?)) + } + crate::PathSeg::Bezier(b) => b.along(f), + } + } + + /// `n + 1` points evenly spaced by length along `path` (exact on its lines and arcs), with the + /// unit directions of travel there. + fn path_samples(path: &[crate::PathSeg], n: usize) -> Result<(Vec, Vec)> { + let lens: Vec = path.iter().map(seg_len).collect(); + let total: f64 = lens.iter().sum(); + if !(total > 1e-9 && total.is_finite()) || n == 0 { + return Err(KernelError::Invalid("the sweep path has no length".into())); + } + let bad = || KernelError::Invalid("a path segment has no direction".into()); + let (mut pts, mut tangents) = (Vec::with_capacity(n + 1), Vec::with_capacity(n + 1)); + let (mut k, mut before) = (0usize, 0.0f64); + for i in 0..=n { + let at = total * i as f64 / n as f64; + while k + 1 < path.len() && lens.get(k).is_some_and(|l| before + l < at) { + before += lens.get(k).copied().unwrap_or(0.0); + k += 1; + } + let (seg, len) = path.get(k).zip(lens.get(k)).ok_or_else(bad)?; + let f = if *len > 0.0 { ((at - before) / len).clamp(0.0, 1.0) } else { 0.0 }; + let (q, t) = seg_at(seg, f).ok_or_else(bad)?; + pts.push(q); + tangents.push(t); + } + Ok((pts, tangents)) + } + + /// How far the direction of travel turns along a path segment (radians, all told). + fn path_turn(s: &crate::PathSeg) -> f64 { + match *s { + crate::PathSeg::Line { .. } => 0.0, + crate::PathSeg::Arc { angle, .. } => angle.abs(), + crate::PathSeg::Curve { seg, .. } => { + let pts = seg.polyline(1e-3); + pts.windows(3) + .filter_map(|w| Some(((w[1] - w[0]).normalized()?, (w[2] - w[1]).normalized()?))) + .map(|(u, v)| u.cross(v).atan2(u.dot(v)).abs()) + .sum() + } + crate::PathSeg::Bezier(b) => { + let pts: Vec = std::iter::once(b.start()).chain(b.polyline(1e-3)).collect(); + pts.windows(3) + .filter_map(|w| Some(((w[1] - w[0]).normalized()?, (w[2] - w[1]).normalized()?))) + .map(|(u, v)| u.cross(v).len().atan2(u.dot(v))) + .sum() + } + } + } + + /// Fewest and most stations of a sweep that twists, scales or follows rails. + const MIN_STATIONS: usize = 16; + /// Directions of travel read along each path segment for the parallel sweep's crossing check. + const CROSSING_SAMPLES: usize = 32; + const MAX_STATIONS: usize = 2048; + + /// The profile `region` on `plane` swept along the smooth `path` the way `ctl` asks: twisted, + /// scaled, kept at an orientation or guided by rails. The profile is placed at stations along + /// the path by [`crate::sweep_path`]'s laws (the same the polyline sweep uses), each section + /// exactly the profile's image, and SMLib skins the walls through them. Round a closed path the + /// last section has to land on the first, and the ends are joined. + /// + /// Along a straight path square to the profile, with no end scale or rails, a loop that is a + /// circle centred on the path's line maps onto itself at every station, and its wall is built + /// as the exact cylinder: a profile of such circles alone is swept untwisted, and such holes + /// in another outer loop are cut from the sweep of the rest. Other loops are skinned, and an + /// arc centred on the line within a loop of other curves still is. + pub(crate) fn sweep_controlled(plane: &Plane, region: &NumberedRegion, path: &[crate::PathSeg], ctl: &crate::SweepControl) -> Result { + let runs = smooth_runs(path)?; + if runs.len() > 1 { + return cornered_controlled(plane, region, path, &runs, ctl); + } + let pieces = pieces(region.loops()); + let start = path.first().map(crate::PathSeg::start).ok_or_else(|| KernelError::Invalid("the path needs 1…1000 segments".into()))?; + // A circle centred on the twist axis, swept straight along that axis, turns onto itself: + // its wall is exactly the cylinder, built as one rather than skinned (solidcore#2184: a + // skin lying within 4e-9 of a cylinder another body shares fails the boolean). + let axial = straight_axis(plane, path, ctl, start).map(|(k, length)| { + let round: Vec> = region.loops().map(|l| circle_on_axis(plane, &l.lp, start, k)).collect(); + (k, length, round) + }); + let mut bores: Vec<(Vec3, f64)> = Vec::new(); + let mut kept = region.clone(); + if let Some((_, _, round)) = &axial { + if round.iter().all(Option::is_some) { + // Every loop a circle about the axis: the twist changes nothing. + match sweep(plane, &pieces, path, false) { + Ok(body) => return Ok(body), + Err(e) => log::debug!(target: "smlib", "twisted sweep of circles about its path, swept untwisted: {e}; skinned instead"), + } + } else if round.first().is_some_and(Option::is_none) { + // The holes that are circles about the axis are cut as exact cylinders from the + // sweep of the rest, through and a little past both ends. + let (mut holes, mut cut) = (Vec::new(), Vec::new()); + for (h, r) in region.holes.iter().zip(round.iter().skip(1)) { + match r { + Some(circle) => cut.push(*circle), + None => holes.push(h.clone()), + } + } + if !cut.is_empty() { + bores = cut; + kept = NumberedRegion { outer: region.outer.clone(), holes }; + } + } + } + let skinned = skinned_controlled(plane, &kept, path, ctl, start, &bores, axial.as_ref().map(|(k, l, _)| (*k, *l))); + let (body, st, size, closed) = match skinned { + Ok(r) => r, + Err(e) if !bores.is_empty() => { + log::debug!(target: "smlib", "twisted sweep with its bores cut as cylinders: {e}; all skinned instead"); + skinned_controlled(plane, region, path, ctl, start, &[], None)? + } + Err(e) => return Err(e), + }; + let (Some(first), Some(last)) = (st.first(), st.last()) else { return Err(KernelError::Invalid("sweep path".into())) }; + let s0 = first.at; + let mid = st.get(st.len() / 2).copied().unwrap_or(*last); + let inside = seeds(plane, &pieces, |q| mid.at + mid.apply(q - s0)); + let roles = if closed { + // Round a closed path there are no caps, and the start holds seams only. + roles(&body, &plane.offset(size * 10.0), None, &[], &inside, false)? + } else { + let end = Plane::new(last.at + last.apply(plane.origin - s0), last.apply(plane.x), last.apply(plane.y)) + .ok_or_else(|| KernelError::Invalid("the sweep's end section is degenerate".into()))?; + roles(&body, plane, Some(&end), &seeds(plane, &pieces, |q| q), &inside, false)? + }; + with_history(body, &roles, &pieces) + } + + /// The unit direction of a path of lines running straight along the profile plane's normal, + /// and its length, when the sweep's laws only turn the profile about that line through the + /// path's start (no end scale, no rails): each station is then the profile turned about the + /// axis and moved along it. + fn straight_axis(plane: &Plane, path: &[crate::PathSeg], ctl: &crate::SweepControl, start: Vec3) -> Option<(Vec3, f64)> { + if ctl.scale != 1.0 || !ctl.rails.is_empty() { + return None; + } + let n = plane.normal().normalized()?; + let mut at = start; + let mut length = 0.0; + let mut k: Option = None; + for s in path { + let crate::PathSeg::Line { a, b } = *s else { return None }; + let d = b - a; + let t = d.normalized()?; + let scale = 1.0 + a.dist(start) + b.dist(start); + if a.dist(at) > 1e-9 * scale || t.dot(n).abs() < 1.0 - 1e-12 || k.is_some_and(|k| t.dot(k) < 1.0 - 1e-12) { + return None; + } + k.get_or_insert(t); + length += d.len(); + at = b; + } + k.filter(|_| length.is_finite() && length > 0.0).map(|k| (k, length)) + } + + /// The centre and radius of `lp` when it is one circle (in one or several arcs) centred on the + /// line through `start` along the unit `k`. + fn circle_on_axis(plane: &Plane, lp: &solidcore_record::Loop2, start: Vec3, k: Vec3) -> Option<(Vec3, f64)> { + let mut circle: Option<(Vec3, f64)> = None; + let mut turn = 0.0; + for s in &lp.segs { + let Seg2::Arc { center, radius, sweep, .. } = *s else { return None }; + let c = plane.to_world(center); + let tol = 1e-9 * (1.0 + radius.abs()); + let w = c - start; + if !(radius.is_finite() && radius > 0.0) || (w - k * w.dot(k)).len() > tol { + return None; + } + if let Some((c0, r0)) = circle + && (c0.dist(c) > tol || (r0 - radius).abs() > tol) + { + return None; + } + circle.get_or_insert((c, radius)); + turn += sweep.abs(); + } + circle.filter(|_| (turn - std::f64::consts::TAU).abs() <= 1e-9 * std::f64::consts::TAU) + } + + /// The controlled sweep of `region` skinned through its stations, with each of `bores` (a + /// centre and radius on the straight path's axis `straight`: its direction and length) cut + /// from it as an exact cylinder; the stations, the sweep's size and whether the path closes. + fn skinned_controlled( + plane: &Plane, + region: &NumberedRegion, + path: &[crate::PathSeg], + ctl: &crate::SweepControl, + start: Vec3, + bores: &[(Vec3, f64)], + straight: Option<(Vec3, f64)>, + ) -> Result<(Body, Vec, f64, bool)> { + let c = curves(plane, &pieces(region.loops()))?; + // Each point of the profile turns with the path and the twist, and SMLib's skin is a cubic + // interpolation through the stations with free ends, whose error near the ends falls only + // as the square of the step: a square of reach 7.1 twisted a quarter turn over 40 mm is + // 2e-7 off in volume at 1.4 degree steps and 2e-6 at 2.8 (measured against V = A L). A + // station per degree of turn. + let turn: f64 = path.iter().map(path_turn).sum::() + ctl.twist.abs(); + let step = std::f64::consts::PI / 180.0; + let rail_points = ctl.rails.iter().map(Vec::len).max().unwrap_or(0); + let n = ((turn / step).ceil() as usize).max(rail_points.saturating_sub(1)).clamp(MIN_STATIONS, MAX_STATIONS); + let (pts, tangents) = path_samples(path, n)?; + let st = crate::sweep_path::controlled_stations(plane, &pts, &tangents, &[], ctl)?; + let s0 = st.first().ok_or_else(|| KernelError::Invalid("sweep path".into()))?.at; + let size = pts.windows(2).map(|w| w[0].dist(w[1])).sum::() + region.outer.lp.signed_area().abs().sqrt(); + let closed = pts.last().is_some_and(|e| e.dist(start) <= 1e-7 * (1.0 + size)); + if closed { + for l in region.loops() { + crate::sweep_path::closing_offset(plane, l, &st)?; + } + } + let maps: Vec = st + .iter() + .map(|s| { + let [a, b, c] = s.m; + Affine { m: [p(a), p(b), p(c)], t: p(s.at - s.apply(s0)) } + }) + .collect(); + let mut brep = Brep::sweep_stations(&c, &maps, if closed { Ends::Joined } else { Ends::Capped }).map_err(|e| failed("sweep", e))?; + if let (false, Some((k, length))) = (bores.is_empty(), straight) { + // Past each end by a share of the sweep's size, so no face of the cut lies on a cap. + let past = 0.25 * size + 1e-3; + for (center, radius) in bores { + let from = *center - k * past; + let circle = + Curve::Arc { center: p(from), axis: p(k), reference: p(plane.x), radius: *radius, start: 0.0, end: std::f64::consts::TAU }; + let bore = + Brep::extrude(&[circle], p(k), length + 2.0 * past, 0.0, DraftCorner::default(), true).map_err(|e| failed("sweep bore", e))?; + brep = combined(&brep, &bore, solidcraft_smlib::BooleanOp::Subtract, "sweep bore")?; + } + } + Ok((body_of(brep, "sweep")?, st, size, closed)) + } + + /// `x` moved by `a`. + fn affine_apply(a: &Affine, x: Vec3) -> Vec3 { + let [c0, c1, c2] = a.m; + let v = |q: [f64; 3]| Vec3::new(q[0], q[1], q[2]); + v(c0) * x.x + v(c1) * x.y + v(c2) * x.z + v(a.t) + } + + /// `v` turned by `a`'s linear part. + fn affine_turn(a: &Affine, v: Vec3) -> Vec3 { + affine_apply(a, v) - affine_apply(a, Vec3::ZERO) + } + + /// `a` after `b`: x goes to a(b(x)). + fn affine_after(a: &Affine, b: &Affine) -> Affine { + let col = |c: [f64; 3]| p(affine_turn(a, Vec3::new(c[0], c[1], c[2]))); + Affine { m: [col(b.m[0]), col(b.m[1]), col(b.m[2])], t: p(affine_apply(a, Vec3::new(b.t[0], b.t[1], b.t[2]))) } + } + + /// The rigid turn by `angle` about the unit `k` through `center`, as an affine map. + fn affine_turned(center: Vec3, k: Vec3, angle: f64) -> Affine { + let col = |e: Vec3| p(turned(e, k, angle)); + Affine { m: [col(Vec3::X), col(Vec3::Y), col(Vec3::Z)], t: p(center - turned(center, k, angle)) } + } + + fn affine_moved(a: &Affine, by: Vec3) -> Affine { + Affine { m: a.m, t: p(Vec3::new(a.t[0], a.t[1], a.t[2]) + by) } + } + + const IDENTITY: Affine = Affine { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] }; + + /// A sweep that twists, scales, keeps an orientation direction or follows guide rails along + /// a path with corners, by the corner model of the plain sweep ([`cornered`]): each smooth run + /// of the path is swept through stations by the laws a smooth path has (the twist and the + /// scale running with the length along the whole path, each run going on from the section the + /// last one ended with), and the runs meet at each corner in a mitre. Turning with the path, + /// each run is carried on straight past its corners as a prism of its section there (the laws + /// hold still across a mitre: the two runs' sections meet on the plane halving the corner only + /// when both are the corner's section), cut back to that plane, and the section turned through + /// the corner about its binormal; only moving along the path, the runs meet at the corner's + /// section. + /// + /// At a corner an orientation direction turns the section as the corner does, and along the + /// next run it turns back about the path to the direction's frame, evenly along the run's + /// length, as a twist. Guide rails must turn with the path: each rail has a corner of its own + /// at every corner of the path, in the plane halving it and by the same turn, where it is cut + /// into the runs' rails. Round a closed path the last section has to land on the first: a + /// twist where the profile maps onto itself; an end scale never does. + fn cornered_controlled( + plane: &Plane, + region: &NumberedRegion, + path: &[crate::PathSeg], + runs: &[std::ops::Range], + ctl: &crate::SweepControl, + ) -> Result { + let translate = ctl.orientation == crate::SweepOrientation::Parallel; + let pieces = pieces(region.loops()); + let c = curves(plane, &pieces)?; + let bad = || KernelError::Invalid("a path segment has no direction".into()); + let start = path.first().map(crate::PathSeg::start).ok_or_else(|| KernelError::Invalid("empty path".into()))?; + let end = path.last().map(crate::PathSeg::end).ok_or_else(|| KernelError::Invalid("empty path".into()))?; + let lens: Vec = path.iter().map(seg_len).collect(); + let total: f64 = lens.iter().sum(); + if !(total > 1e-9 && total.is_finite()) { + return Err(KernelError::Invalid("the sweep path has no length".into())); + } + let tangent = |s: Option<&crate::PathSeg>| s.and_then(crate::PathSeg::tangents).ok_or_else(bad); + let (first_t, _) = tangent(path.first())?; + let (_, last_t) = tangent(path.last())?; + let closed = end.dist(start) <= 1e-6; + if closed && ctl.scale != 1.0 { + return Err(KernelError::Invalid( + "a sweep with an end scale can't go round a closed path: its last section would have to land on its first".into(), + )); + } + let closing = (closed && last_t.dot(first_t) < (1e-3f64).cos()).then_some(first_t); + let reach = pieces + .iter() + .flat_map(|x| (0..=8).map(move |i| x.seg.point_at(f64::from(i) / 8.0))) + .map(|q| plane.to_world(q).dist(start) * ctl.scale.max(1.0)) + .fold(0.0f64, f64::max); + let offsets = section_offsets(plane, &pieces, start, first_t, ctl.scale.max(1.0)); + let size = 4.0 * (total + reach) + 1.0; + let law = |u: f64| 1.0 + (ctl.scale - 1.0) * u; + let n0 = plane.normal().normalized().ok_or_else(|| KernelError::Invalid("profile plane".into()))?; + // Each run's rails, cut at the corners. + let rails = run_rails(path, runs, &ctl.rails, closing)?; + // The map carrying the profile as drawn onto the section where the next run starts, the + // mitre that run starts from (its point, its normal along the run, its turn) and how far + // along the path it starts. + let mut at_start = IDENTITY; + let mut entry: Option<(Vec3, Vec3, f64)> = match closing { + Some(_) if !translate => { + let (m, turn) = mitre_of(last_t, first_t)?; + Some((start, m, turn)) + } + _ => None, + }; + let mut before = 0.0f64; + let mut body: Option = None; + let mut inside = Vec::new(); + for (ri, run) in runs.iter().enumerate() { + let segs = path.get(run.clone()).ok_or_else(|| KernelError::Invalid("path run".into()))?; + let length: f64 = lens.get(run.clone()).ok_or_else(|| KernelError::Invalid("path run".into()))?.iter().sum(); + let (u0, u1) = (before / total, (before + length) / total); + let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err(KernelError::Invalid("path run".into())) }; + let ((t0, _), (_, t1)) = (first.tangents().ok_or_else(bad)?, last.tangents().ok_or_else(bad)?); + let (a0, b1) = (first.start(), last.end()); + let normal = affine_turn(&at_start, n0).normalized().ok_or_else(|| KernelError::Invalid("the sweep's section is degenerate".into()))?; + let pose = Plane::from_normal(a0, normal).ok_or_else(|| KernelError::Invalid("the sweep's section is degenerate".into()))?; + // The run's own laws on its section at the start: the twist over its length (less the + // turn back to the orientation direction after a corner), the scale from where the + // last run left it to where this one ends, the rails from corner to corner. + let back = match ctl.orientation { + crate::SweepOrientation::Direction(_) if ri > 0 => direction_offset(plane, start, first_t, a0, t0, u0, ctl, &at_start)?, + _ => 0.0, + }; + let run_ctl = crate::SweepControl { + orientation: ctl.orientation, + twist: ctl.twist * (u1 - u0) - back, + scale: law(u1) / law(u0), + rails: rails.get(ri).cloned().unwrap_or_default(), + rail_fit: ctl.rail_fit, + }; + // A station per degree the section turns, with the path and the twist. + let turn: f64 = segs.iter().map(path_turn).sum::() + run_ctl.twist.abs(); + let n = ((turn / (std::f64::consts::PI / 180.0)).ceil() as usize).clamp(MIN_STATIONS, MAX_STATIONS); + let (pts, tangents) = path_samples(segs, n)?; + let st = crate::sweep_path::controlled_stations(&pose, &pts, &tangents, &[], &run_ctl)?; + let maps: Vec = st + .iter() + .map(|s| { + let [a, b, cc] = s.m; + affine_after(&Affine { m: [p(a), p(b), p(cc)], t: p(s.at - s.apply(a0)) }, &at_start) + }) + .collect(); + let (Some(&first_map), Some(&end_map)) = (maps.first(), maps.last()) else { return Err(KernelError::Invalid("sweep path".into())) }; + // Each wall is known by its piece's middle at the station half way along the stretch + // of the run that point keeps between the mitres (the stations are evenly spaced by + // length): a point standing `s` ahead of the path keeps the stretch `s` back from the + // run's, as in the plain sweep ([`cornered`]). + let last_station = maps.len().saturating_sub(1); + inside.extend(pieces.iter().enumerate().map(|(piece, x)| { + let q = plane.to_world(x.seg.point_at(0.5)); + let ahead = (affine_apply(&first_map, q) - a0).dot(t0); + let share = if translate || !(length > 0.0) { 0.5 } else { (0.5 - ahead / length).clamp(0.0, 1.0) }; + let station = ((share * last_station as f64).round() as usize).min(last_station); + Seed { at: affine_apply(maps.get(station).unwrap_or(&end_map), q), piece } + })); + let mut piece = Brep::sweep_stations(&c, &maps, Ends::Capped).map_err(|e| failed("sweep", e))?; + let next = match runs.get(ri + 1).and_then(|r| path.get(r.start)) { + Some(s) => Some(tangent(Some(s))?.0), + None => closing, + }; + let exit = next.map(|t2| mitre_of(t1, t2)).transpose()?; + if !translate { + // On past each mitre, the run's section there held still, far enough to take + // every point of it to the mitre's plane ([`mitre_lead`]). + let prism = |map: Affine, toward: Vec3, by: f64| -> Result { + Brep::sweep_stations(&c, &[map, affine_moved(&map, toward * by)], Ends::Capped).map_err(|e| failed("sweep corner", e)) + }; + if let Some((at, m, turn)) = entry { + let pre = mitre_lead(&offsets, reach, turn, false); + let lead = prism(affine_moved(&first_map, t0 * -pre), t0, pre)?; + piece = combined(&piece, &lead, solidcraft_smlib::BooleanOp::Union, "sweep corner")?; + piece = combined(&piece, &half_space(at, -m, size)?, solidcraft_smlib::BooleanOp::Subtract, "sweep mitre")?; + } + if let Some((m, turn)) = exit { + let tail = prism(end_map, t1, mitre_lead(&offsets, reach, turn, true))?; + piece = combined(&piece, &tail, solidcraft_smlib::BooleanOp::Union, "sweep corner")?; + piece = combined(&piece, &half_space(b1, m, size)?, solidcraft_smlib::BooleanOp::Subtract, "sweep mitre")?; + } + } + body = Some(match body { + None => piece, + Some(b) => combined(&b, &piece, solidcraft_smlib::BooleanOp::Union, "sweep corner")?, + }); + // The section at the run's end, turned through the corner onto the next run. + at_start = end_map; + entry = None; + if let (Some(t2), Some((m, turn)), false) = (next, exit, translate) { + let k = t1.cross(t2).normalized().ok_or_else(|| KernelError::Invalid("path corner".into()))?; + at_start = affine_after(&affine_turned(b1, k, turn), &end_map); + entry = Some((b1, m, turn)); + } + before += length; + } + let brep = body.ok_or_else(|| KernelError::Invalid("empty path".into()))?; + if closed { + // Back at the start, the section has to be the profile again (a whole number of its + // symmetries of twist). + let to_station = |a: &Affine| { + let v = |q: [f64; 3]| Vec3::new(q[0], q[1], q[2]); + crate::sweep_path::Station { at: affine_apply(a, start), m: [v(a.m[0]), v(a.m[1]), v(a.m[2])] } + }; + for l in region.loops() { + crate::sweep_path::closing_offset(plane, l, &[to_station(&IDENTITY), to_station(&at_start)])?; + } + } + let body = body_of(brep, "sweep")?; + let roles = if closed { + roles(&body, &plane.offset(size * 10.0), None, &[], &inside, false)? + } else { + let end_plane = Plane::new(affine_apply(&at_start, plane.origin), affine_turn(&at_start, plane.x), affine_turn(&at_start, plane.y)) + .ok_or_else(|| KernelError::Invalid("the sweep's end section is degenerate".into()))?; + roles(&body, plane, Some(&end_plane), &seeds(plane, &pieces, |q| q), &inside, false)? + }; + with_history(body, &roles, &pieces) + } + + /// After a corner, how far the section at `a0` (the profile carried there by `at_start`) is + /// turned about its normal (toward the run's direction `t0`) from where the orientation direction's law puts it + /// (the law of a smooth path from `start`, leaving along `first_t`, `u0` of the way along): + /// the turn the next run takes back, as a twist. Radians, right-handed about `t0`. + #[allow(clippy::too_many_arguments)] + fn direction_offset( + plane: &Plane, + start: Vec3, + first_t: Vec3, + a0: Vec3, + t0: Vec3, + u0: f64, + ctl: &crate::SweepControl, + at_start: &Affine, + ) -> Result { + let law = crate::SweepControl { twist: ctl.twist * u0, scale: 1.0 + (ctl.scale - 1.0) * u0, rails: Vec::new(), ..ctl.clone() }; + // A two-station path from the start to here with the two directions: the law's section here. + let st = crate::sweep_path::controlled_stations(plane, &[start, a0], &[first_t, t0], &[], &law)?; + let want = st.last().map(|s| s.apply(plane.x)).ok_or_else(|| KernelError::Invalid("sweep path".into()))?; + let have = affine_turn(at_start, plane.x); + // About the section's normal, pointing the way the run leaves it (the twist's axis). + let n = affine_turn(at_start, plane.normal()); + let axis = (if n.dot(t0) < 0.0 { n * -1.0 } else { n }) + .normalized() + .ok_or_else(|| KernelError::Invalid("the sweep's section is degenerate".into()))?; + let flat = |v: Vec3| (v - axis * v.dot(axis)).normalized(); + let (Some(w), Some(h)) = (flat(want), flat(have)) else { + return Err(KernelError::Invalid("the profile lies along the sweep path at a corner".into())); + }; + Ok(w.cross(h).dot(axis).atan2(w.dot(h))) + } + + /// The guide rails cut at the path's corners, one set per run: each rail must turn with the + /// path there, with a corner of its own in the plane halving the path's corner and by the + /// same turn about the same axis. + fn run_rails( + path: &[crate::PathSeg], + runs: &[std::ops::Range], + rails: &[Vec], + closing: Option, + ) -> Result>>> { + if rails.is_empty() { + return Ok(vec![Vec::new(); runs.len()]); + } + if closing.is_some() { + return Err(KernelError::Invalid("guide rails can't follow a closed path with corners: a rail runs from the start to the end".into())); + } + let refused = |i: usize| { + KernelError::Invalid(format!( + "at corner {} of the path the guide rails have to turn with it: each rail needs a corner of its own there, in the plane halving the path's corner and by the same turn", + i + 1 + )) + }; + let mut rest: Vec> = rails.iter().map(|r| crate::sweep_path::clean(r)).collect::>()?; + let mut out = Vec::with_capacity(runs.len()); + for (ci, w) in runs.windows(2).enumerate() { + let (Some(a), Some(b)) = (w[0].end.checked_sub(1).and_then(|i| path.get(i)), path.get(w[1].start)) else { return Err(refused(ci)) }; + let ((_, t1), (t2, _)) = (a.tangents().ok_or_else(|| refused(ci))?, b.tangents().ok_or_else(|| refused(ci))?); + let (m, turn) = mitre_of(t1, t2)?; + let at = a.end(); + let k = t1.cross(t2).normalized().ok_or_else(|| refused(ci))?; + let mut here = Vec::with_capacity(rest.len()); + for rail in &mut rest { + let size = rail.windows(2).map(|q| q[0].dist(q[1])).sum::().max(1e-9); + let tol = (size * 1e-6).max(1e-6); + let corner = (1..rail.len().saturating_sub(1)).find(|&j| { + let (Some(p), Some(q), Some(r)) = (rail.get(j - 1), rail.get(j), rail.get(j + 1)) else { return false }; + let (Some(d1), Some(d2)) = ((*q - *p).normalized(), (*r - *q).normalized()) else { return false }; + (*q - at).dot(m).abs() <= tol + && (d1.dot(d2).clamp(-1.0, 1.0).acos() - turn).abs() <= 1e-3 + && d1.cross(d2).normalized().is_some_and(|kr| kr.dot(k) > 1.0 - 1e-6) + }); + let j = corner.ok_or_else(|| refused(ci))?; + let tail = rail.split_off(j); + let mut head = std::mem::replace(rail, tail); + head.extend(rail.first().copied()); + here.push(head); + } + out.push(here); + } + out.push(rest); + Ok(out) + } + + /// Where the profile's points sit from the path, as a section carries them along it: for + /// each sampled point of `pieces` on `plane`, its distance ahead of the path's `start` along + /// the unit direction of travel `t` there, and its distance square to that direction, both + /// times `scale`. A section that turns with the path (along a smooth run, and through a + /// corner about the line square to both directions) keeps both, a twist keeps both, and an + /// end scale grows them by at most its largest scale. + fn section_offsets(plane: &Plane, pieces: &[Piece], start: Vec3, t: Vec3, scale: f64) -> Vec<(f64, f64)> { + pieces + .iter() + .flat_map(|x| (0..=8).map(move |i| x.seg.point_at(f64::from(i) / 8.0))) + .map(|q| { + let d = plane.to_world(q) - start; + let s = d.dot(t); + (s * scale, (d - t * s).len() * scale) + }) + .collect() + } + + /// How far a run's section is carried straight on past a corner turning by `turn` (`ahead`), + /// or back before one (else), so that each of its points reaches the plane halving the + /// corner. A point `s` ahead of the path and `w` from it, the plane's unit normal `m` at half + /// the turn from the direction of travel `t`: `m · (s t + w) >= s cos(turn / 2) - w sin(turn / + /// 2)`, so carried on `e` along `t` it reaches the plane once `e >= w tan(turn / 2) - s` (and + /// back before the corner once `e >= w tan(turn / 2) + s`). A profile square to the path has + /// `s = 0`: its reach times the tangent of half the turn; one standing at a slant to the path + /// reaches across the mitre by its slant as well. A little further than the farthest point, + /// so the cut back runs through the walls, never along the run's own end. + fn mitre_lead(offsets: &[(f64, f64)], reach: f64, turn: f64, ahead: bool) -> f64 { + let k = (turn * 0.5).tan(); + let need = offsets.iter().map(|(s, w)| w * k + if ahead { -s } else { *s }).fold(0.0f64, f64::max); + need * 1.1 + reach * 1e-3 + 1e-6 + } + + /// The plane halving the corner from direction `t1` to `t2` (its unit normal) and the turn + /// there; a path that turns back on itself has none. + fn mitre_of(t1: Vec3, t2: Vec3) -> Result<(Vec3, f64)> { + let turn = t1.dot(t2).clamp(-1.0, 1.0).acos(); + if turn > std::f64::consts::PI - 1e-3 { + return Err(KernelError::Invalid("the path turns back on itself at a corner".into())); + } + Ok(((t1 + t2).normalized().ok_or_else(|| KernelError::Invalid("path corner".into()))?, turn)) + } + + /// A loft through `sections` (each a closed loop of pieces, all re-split to the same count + /// and lined up), `first` the index of the section given first (its cap is the start cap). + pub(crate) fn loft(sections: &[(Plane, Vec)], first: usize) -> Result { + let curves: Vec> = sections.iter().map(|(pl, ps)| curves(pl, ps)).collect::>()?; + // Ruled between two sections, else smooth through them (cubic from four). + let degree = match sections.len() { + 0..=2 => 1, + 3 => 2, + _ => 3, + }; + loft_through(sections, first, &curves, degree) + } + + /// The loft skinned through `curves` (the sections', or with stations between them), `degree` + /// across them; `sections` and `first` as [`loft`] takes them name the faces. + fn loft_through(sections: &[(Plane, Vec)], first: usize, curves: &[Vec], degree: u32) -> Result { + let brep = Brep::loft(curves, degree, true).map_err(|e| failed("loft", e))?; + let body = body_of(brep, "loft")?; + let (Some((start, lead)), Some(last)) = (sections.get(first), sections.get(if first == 0 { sections.len().saturating_sub(1) } else { 0 })) + else { + return Err(KernelError::Invalid("loft sections".into())); + }; + // Each wall comes from its column's segments in every section. + let columns: Vec = lead + .iter() + .enumerate() + .map(|(i, x)| { + let mut all: BTreeSet = BTreeSet::new(); + for (_, ps) in sections { + if let Some(q) = ps.get(i) { + all.extend(q.numbers.iter().copied()); + } + } + Piece { seg: x.seg, numbers: all.into_iter().collect(), drawn: x.drawn, joins_previous: false } + }) + .collect(); + let roles = roles(&body, start, Some(&last.0), &seeds(start, &columns, |q| q), &[], false)?; + with_history(body, &roles, &columns) + } + + /// A loft through `sections` (as [`loft`] takes them) guided by one or two `rails` (polylines + /// from the first section to the last, through every section's curve), by the law + /// [`crate::loft_rails::railed`] gives a loft's rails: between each two sections stations are + /// the plain loft there moved so that the points the rails guide land on the rails. Each + /// section curve has to pair with the others' (the same kind, so their control points pair + /// up). + pub(crate) fn loft_rails(sections: &[(Plane, Vec)], first: usize, rails: &[Vec], fit: crate::RailFit) -> Result { + if rails.is_empty() || rails.len() > 2 { + return Err(KernelError::Invalid("a loft takes one or two guide rails".into())); + } + let matched = sections + .iter() + .map(|(pl, ps)| { + let segs: Vec = ps.iter().map(|x| x.seg).collect(); + crate::loft_rails::Section::of(pl, &segs, ps.iter().map(|x| x.numbers.clone()).collect()) + }) + .collect::>>()?; + let all: Vec> = crate::loft_rails::railed(&matched, true, rails, fit)? + .iter() + .map(|section| { + section + .iter() + .map(|c| { + let points = c.ctrl.iter().map(|h| [h[0] / h[3], h[1] / h[3], h[2] / h[3], h[3]]).collect(); + Curve::Nurbs { degree: c.degree, points, knots: c.knots.clone() } + }) + .collect() + }) + .collect(); + loft_through(sections, first, &all, 3) + } + + /// A loft from the section `pieces` (lines) on `plane` to `apex`: the base is the start cap, + /// each triangle comes from the segment it stands on. + pub(crate) fn loft_to_point(plane: &Plane, pieces: &[Piece], apex: Vec3) -> Result { + let c = curves(plane, pieces)?; + let brep = Brep::loft_to_point(&c, p(apex)).map_err(|e| failed("loft to a point", e))?; + let body = body_of(brep, "loft to a point")?; + let roles = roles(&body, plane, None, &seeds(plane, pieces, |q| q), &[], false)?; + with_history(body, &roles, pieces) + } + + /// The profile `pieces` on `plane` carried by a screw motion about the axis through `origin` + /// along `axis`: `turns` right-handed turns, rising `pitch` per turn. + pub(crate) fn screw(plane: &Plane, pieces: &[Piece], origin: Vec3, axis: Vec3, pitch: f64, turns: f64) -> Result { + let c = curves(plane, pieces)?; + // Walls within a ten-thousandth of the pitch of the true screw surfaces. + let tolerance = (pitch.abs() * 1e-4).clamp(1e-6, 1e-2); + let brep = Brep::screw_sweep(&c, p(origin), p(axis), pitch, turns, tolerance).map_err(|e| failed("screw sweep", e))?; + let body = body_of(brep, "screw sweep")?; + let roles = roles(&body, plane, None, &seeds(plane, pieces, |q| q), &[], true)?; + with_history(body, &roles, pieces) + } + + /// [`screw`] with the profile moved `offset(t)` mm off the axis at turn t (negative: towards + /// it), piecewise linear through `law`'s (turn, offset) pairs: a groove fading over a runout. + pub(crate) fn screw_radial( + plane: &Plane, + pieces: &[Piece], + origin: Vec3, + axis: Vec3, + pitch: f64, + turns: f64, + law: &[(f64, f64)], + ) -> Result { + let c = curves(plane, pieces)?; + let tolerance = (pitch.abs() * 1e-4).clamp(1e-6, 1e-2); + let brep = + Brep::screw_sweep_radial(&c, p(origin), p(axis), pitch, turns, law, tolerance).map_err(|e| failed("screw sweep with a radial law", e))?; + let body = body_of(brep, "screw sweep")?; + let roles = roles(&body, plane, None, &seeds(plane, pieces, |q| q), &[], true)?; + with_history(body, &roles, pieces) + } +} diff --git a/crates/kernel/src/smlib_sweeps_tests.rs b/crates/kernel/src/smlib_sweeps_tests.rs new file mode 100644 index 000000000..ea1443cda --- /dev/null +++ b/crates/kernel/src/smlib_sweeps_tests.rs @@ -0,0 +1,351 @@ +//! The sweeps through SMLib ([`crate::smlib_sweeps`]): analytic volumes, and the history and +//! construction sources the builders' vocabulary gives each face. + +use solidcraft_geom::prelude::*; +use std::f64::consts::{PI, TAU}; + +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; + +use crate::FaceSource; +use crate::body::Body; +use crate::history::{FaceOrigin, History}; +use crate::numbered::number_regions; +use crate::smlib_sweeps::{self, Draft, Piece}; + +fn region(outer: Loop2) -> Region2 { + Region2 { outer, holes: Vec::new() } +} + +fn pieces_of(r: &Region2) -> Vec { + let n = number_regions(std::slice::from_ref(r)).pop().unwrap().oriented(); + smlib_sweeps::pieces(n.loops()) +} + +/// Measured on the body's mesh: curved faces come out within about 1e-3. +fn volume(b: &Body) -> f64 { + crate::measure(b).unwrap().volume +} + +fn close(got: f64, want: f64, rel: f64, what: &str) { + assert!((got - want).abs() <= rel * want.abs(), "{what}: {got} vs analytic {want}"); +} + +/// Each face's origins, sorted by their debug text (the faces' order is SMLib's). +fn origins(b: &Body) -> Vec { + let h: &History = b.history().expect("a history"); + let mut v: Vec = h.faces.iter().map(|f| format!("{:?}", f.origins)).collect(); + v.sort(); + v +} + +fn profile(k: usize) -> String { + format!("{:?}", vec![FaceOrigin::Profile { segment: k }]) +} + +fn cap(end: bool) -> String { + format!("{:?}", vec![FaceOrigin::Cap { end }]) +} + +#[test] +fn an_extrusion_names_its_caps_and_walls_and_keeps_their_sources() { + let r = region(Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 6.0), Vec2::new(0.0, 6.0)])); + let b = smlib_sweeps::extrude(&Plane::XY, &pieces_of(&r), Some(&r), 2.0, 5.0, 1.0, None).unwrap(); + close(volume(&b), 300.0, 1e-9, "prism"); + let mut want = vec![cap(false), cap(true), profile(0), profile(1), profile(2), profile(3)]; + want.sort(); + assert_eq!(origins(&b), want); + let sources = b.face_sources().expect("sources"); + let caps = sources.iter().filter(|s| matches!(s, Some(FaceSource::ExtrudeCap { .. }))).count(); + let sides = sources.iter().filter(|s| matches!(s, Some(FaceSource::ExtrudeSide { plane: Some(_), .. }))).count(); + assert_eq!((caps, sides), (2, 4)); + // A drafted disc: a frustum, its wall the circle's. + let disc = region(Loop2::circle(Vec2::ZERO, 5.0)); + let taper = -5f64.to_radians(); + let b = smlib_sweeps::extrude( + &Plane::XY, + &pieces_of(&disc), + Some(&disc), + 0.0, + 4.0, + 1.0, + Some(Draft { taper, foot: 0.0, corner: crate::DraftCorner::default() }), + ) + .unwrap(); + let r2 = 5.0 + 4.0 * taper.tan(); + close(volume(&b), PI * 4.0 / 3.0 * (25.0 + r2 * r2 + 5.0 * r2), 1e-3, "drafted disc"); + assert!(origins(&b).iter().filter(|o| o.contains("Profile")).count() >= 1); +} + +#[test] +fn a_revolution_names_its_walls_by_segment_and_skips_the_axis() { + // A half disc on the y axis of the xy plane: a sphere, every wall from the arc. + let half = Loop2 { + segs: vec![ + Seg2::Line { a: Vec2::new(0.0, -5.0), b: Vec2::new(0.0, 5.0) }, + Seg2::Arc { center: Vec2::ZERO, radius: 5.0, start: PI / 2.0, sweep: -PI }, + ], + }; + let r = region(half); + let b = smlib_sweeps::revolve(&Plane::XY, &pieces_of(&r), Vec3::ZERO, Vec3::Y, TAU).unwrap(); + close(volume(&b), 4.0 / 3.0 * PI * 125.0, 1e-3, "sphere (measured on a mesh)"); + assert!(origins(&b).iter().all(|o| *o == profile(1)), "{:?}", origins(&b)); + // A quarter turn of a square off the axis: two caps and four walls. + let sq = region(Loop2::polygon(&[Vec2::new(6.0, 0.0), Vec2::new(8.0, 0.0), Vec2::new(8.0, 2.0), Vec2::new(6.0, 2.0)])); + let b = smlib_sweeps::revolve(&Plane::XY, &pieces_of(&sq), Vec3::ZERO, Vec3::Y, PI / 2.0).unwrap(); + close(volume(&b), PI / 2.0 * 7.0 * 4.0, 1e-3, "quarter ring"); + let mut want = vec![cap(false), cap(true), profile(0), profile(1), profile(2), profile(3)]; + want.sort(); + assert_eq!(origins(&b), want); +} + +#[test] +fn a_loft_and_a_screw_sweep_name_their_ends() { + let square = |z: f64| { + let r = region(Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)])); + (Plane::XY.offset(z), pieces_of(&r)) + }; + let b = smlib_sweeps::loft(&[square(0.0), square(8.0)], 0).unwrap(); + close(volume(&b), 800.0, 1e-6, "loft"); + let o = origins(&b); + assert!(o.contains(&cap(false)) && o.contains(&cap(true)) && o.iter().filter(|x| x.contains("Profile")).count() == 4, "{o:?}"); + // A 0.4 mm square tooth at radius 4 in the xz plane, three turns of pitch 1 about z. + let xz = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; + let tooth = region(Loop2::polygon(&[Vec2::new(4.0, 0.0), Vec2::new(4.4, 0.0), Vec2::new(4.4, 0.4), Vec2::new(4.0, 0.4)])); + let b = smlib_sweeps::screw(&xz, &pieces_of(&tooth), Vec3::ZERO, Vec3::Z, 1.0, 3.0).unwrap(); + close(volume(&b), 0.16 * TAU * 4.2 * 3.0, 1e-3, "screw"); + let o = origins(&b); + assert!(o.contains(&cap(false)) && o.contains(&cap(true)), "{o:?}"); +} + +#[test] +fn a_sweep_keeps_a_profile_off_its_path_where_it_lies() { + // A disc 5 mm beside a quarter-arc path of radius 20 about (-20, 0, 0): Pappus at 25. + let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Y }; + let disc = region(Loop2::circle(Vec2::new(5.0, 0.0), 2.0)); + let path = [crate::PathSeg::Arc { a: Vec3::ZERO, center: Vec3::new(-20.0, 0.0, 0.0), axis: -Vec3::Y, angle: PI / 2.0 }]; + let b = smlib_sweeps::sweep(&plane, &pieces_of(&disc), &path, false).unwrap(); + close(volume(&b), PI * 4.0 * (PI / 2.0 * 25.0), 1e-3, "bent tube"); +} + +fn numbered(r: &Region2) -> crate::numbered::NumberedRegion { + number_regions(std::slice::from_ref(r)).pop().unwrap().oriented() +} + +#[test] +fn a_sweep_twists_scales_and_follows_rails_through_stations() { + let square = region(Loop2::polygon(&[Vec2::new(-5.0, -5.0), Vec2::new(5.0, -5.0), Vec2::new(5.0, 5.0), Vec2::new(-5.0, 5.0)])); + let up = [crate::PathSeg::Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 40.0) }]; + // Turning about the section's centre keeps its area: V = 100 * 40, the caps and the four + // walls named. + let ctl = crate::SweepControl { twist: PI / 2.0, ..Default::default() }; + let b = smlib_sweeps::sweep_controlled(&Plane::XY, &numbered(&square), &up, &ctl).unwrap(); + close(volume(&b), 4000.0, 1e-3, "twisted square"); + let o = origins(&b); + assert!(o.contains(&cap(false)) && o.contains(&cap(true)) && (0..4).all(|k| o.contains(&profile(k))), "{o:?}"); + // Scaled from 5 to 10 over 30, or between rails that widen as much: a cone frustum. + let disc = region(Loop2::circle(Vec2::ZERO, 5.0)); + let frustum = |h: f64| h / 3.0 * PI * (25.0 + 100.0 + 50.0); + let short = [crate::PathSeg::Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 30.0) }]; + let ctl = crate::SweepControl { scale: 2.0, ..Default::default() }; + close(volume(&smlib_sweeps::sweep_controlled(&Plane::XY, &numbered(&disc), &short, &ctl).unwrap()), frustum(30.0), 1e-3, "end scale"); + let rails = [vec![Vec3::new(5.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 30.0)], vec![Vec3::new(-5.0, 0.0, 0.0), Vec3::new(-10.0, 0.0, 30.0)]]; + for n in 1..=2 { + let ctl = crate::SweepControl { rails: rails[..n].to_vec(), ..Default::default() }; + close(volume(&smlib_sweeps::sweep_controlled(&Plane::XY, &numbered(&disc), &short, &ctl).unwrap()), frustum(30.0), 1e-3, "rails"); + } +} + +/// An 8 x 5 rectangle on the xy plane, centred on the path's start. +fn bar_section() -> Region2 { + region(Loop2::polygon(&[Vec2::new(-4.0, -2.5), Vec2::new(4.0, -2.5), Vec2::new(4.0, 2.5), Vec2::new(-4.0, 2.5)])) +} + +#[test] +fn a_sweep_round_a_corner_meets_in_a_mitre_and_names_every_wall() { + // 30 up then 40 across: mitred, the outer side gains what the inner loses, V = A (l1 + l2). + let path = [ + crate::PathSeg::Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 30.0) }, + crate::PathSeg::Line { a: Vec3::new(0.0, 0.0, 30.0), b: Vec3::new(40.0, 0.0, 30.0) }, + ]; + let b = smlib_sweeps::sweep(&Plane::XY, &pieces_of(&bar_section()), &path, false).unwrap(); + close(volume(&b), 2800.0, 1e-9, "mitred bar"); + // Each leg's four walls (the side walls in the bend's plane are one face round the corner, + // flat as they are) from the four segments; the start and the end cap. + let o = origins(&b); + assert_eq!(o.iter().filter(|x| **x == cap(false)).count(), 1, "{o:?}"); + assert_eq!(o.iter().filter(|x| **x == cap(true)).count(), 1, "{o:?}"); + assert!(o.iter().all(|x| x.contains("Profile") || x.contains("Cap")), "{o:?}"); + for k in 0..4 { + assert!(o.contains(&profile(k)), "segment {k}: {o:?}"); + } + // Every wall of a straight leg is a plane. + assert!((0..b.face_count()).all(|i| b.planar_face(i).is_some()), "{o:?}"); +} + +#[test] +fn a_sweep_round_a_closed_path_has_no_caps() { + // A square path of side 40 round the origin, the section in the plane square to its first + // side at its middle: four mitred legs closing on themselves. Each leg's centre line is 40, + // so V = A 4 40 (the mitres trade what they add and take). + let c = [Vec3::new(20.0, -20.0, 0.0), Vec3::new(20.0, 20.0, 0.0), Vec3::new(-20.0, 20.0, 0.0), Vec3::new(-20.0, -20.0, 0.0)]; + let start = Vec3::new(20.0, 0.0, 0.0); + let mut path = vec![crate::PathSeg::Line { a: start, b: c[1] }]; + for i in 1..4 { + path.push(crate::PathSeg::Line { a: c[i], b: c[(i + 1) % 4] }); + } + path.push(crate::PathSeg::Line { a: c[0], b: start }); + let plane = Plane { origin: start, x: Vec3::X, y: Vec3::Z }; + let sq = region(Loop2::polygon(&[Vec2::new(-2.0, -1.0), Vec2::new(2.0, -1.0), Vec2::new(2.0, 1.0), Vec2::new(-2.0, 1.0)])); + let b = smlib_sweeps::sweep(&plane, &pieces_of(&sq), &path, false).unwrap(); + close(volume(&b), 8.0 * 160.0, 1e-9, "square frame"); + let o = origins(&b); + assert!(o.iter().all(|x| x.contains("Profile")), "no caps round a closed path: {o:?}"); +} + +#[test] +fn a_loft_through_holed_sections_keeps_the_hole_and_names_its_walls() { + let ring = |z: f64| { + let r = Region2 { outer: Loop2::circle(Vec2::ZERO, 20.0), holes: vec![Loop2::circle(Vec2::ZERO, 12.0)] }; + (Plane::XY.offset(z), r) + }; + let b = crate::loft_regions(&[ring(0.0), ring(20.0)]).unwrap(); + close(volume(&b), PI * (400.0 - 144.0) * 20.0, 1e-3, "tube"); + let o = origins(&b); + assert_eq!(b.face_count(), 4, "{o:?}"); + assert!(o.contains(&cap(false)) && o.contains(&cap(true)), "{o:?}"); + assert_eq!(o.iter().filter(|x| x.contains("Profile")).count(), 2, "outer wall and bore: {o:?}"); +} + +#[test] +fn a_loft_to_a_point_is_a_pyramid() { + let sq = Loop2::polygon(&[Vec2::new(-10.0, -10.0), Vec2::new(10.0, -10.0), Vec2::new(10.0, 10.0), Vec2::new(-10.0, 10.0)]); + let b = crate::loft_to_point(&Plane::XY, &sq, Vec3::new(0.0, 0.0, 15.0)).unwrap(); + close(volume(&b), 2000.0, 1e-9, "pyramid"); + let mut want = vec![cap(false), profile(0), profile(1), profile(2), profile(3)]; + want.sort(); + assert_eq!(origins(&b), want); +} + +#[test] +fn a_drafted_extrusion_stands_on_a_straight_foot() { + // A 10 x 10 square, 1 straight, then sloping out 5 degrees (taken from the base) up to 10: + // the prism 100 and the frustum from 10 to 10 + 2 x 10 tan 5 over 9. + let sq = region(Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)])); + let taper = 5f64.to_radians(); + let b = smlib_sweeps::extrude( + &Plane::XY, + &pieces_of(&sq), + Some(&sq), + 0.0, + 10.0, + 1.0, + Some(Draft { taper, foot: 1.0, corner: crate::DraftCorner::default() }), + ) + .unwrap(); + let (a1, s2) = (100.0, 10.0 + 2.0 * 10.0 * taper.tan()); + let a2 = s2 * s2; + close(volume(&b), 100.0 + 9.0 / 3.0 * (a1 + a2 + (a1 * a2).sqrt()), 1e-9, "footed draft"); + let o = origins(&b); + assert!(o.contains(&cap(false)) && o.contains(&cap(true)), "{o:?}"); + // Each segment's foot and sloping wall. + for k in 0..4 { + assert_eq!(o.iter().filter(|x| **x == profile(k)).count(), 2, "segment {k}: {o:?}"); + } +} + +#[test] +fn a_twisted_sweep_round_a_closed_path_joins_its_ends() { + // An 8 x 8 square round a circle of radius 30, a quarter turn of twist (onto itself): Pappus. + let xz = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; + let square = region(Loop2::polygon(&[Vec2::new(26.0, -4.0), Vec2::new(34.0, -4.0), Vec2::new(34.0, 4.0), Vec2::new(26.0, 4.0)])); + let a = Vec3::new(30.0, 0.0, 0.0); + let round = [ + crate::PathSeg::Arc { a, center: Vec3::ZERO, axis: Vec3::Z, angle: PI }, + crate::PathSeg::Arc { a: -a, center: Vec3::ZERO, axis: Vec3::Z, angle: PI }, + ]; + let ctl = crate::SweepControl { twist: PI / 2.0, ..Default::default() }; + let b = smlib_sweeps::sweep_controlled(&xz, &numbered(&square), &round, &ctl).unwrap(); + close(volume(&b), 64.0 * TAU * 30.0, 1e-3, "twisted ring"); + assert!(origins(&b).iter().all(|o| o.contains("Profile")), "{:?}", origins(&b)); + // A twist that does not bring the square back onto itself cannot close. + let ctl = crate::SweepControl { twist: PI / 3.0, ..Default::default() }; + assert!(smlib_sweeps::sweep_controlled(&xz, &numbered(&square), &round, &ctl).is_err()); +} + +#[test] +fn a_sweep_follows_a_free_form_path_as_a_curve() { + // A 4 x 4 square along a planar S-shaped cubic Bézier (curvature radius above 20): V = A L. + let xz = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; + let seg = Seg2::Cubic { p0: Vec2::new(0.0, 0.0), p1: Vec2::new(0.0, 20.0), p2: Vec2::new(20.0, 20.0), p3: Vec2::new(20.0, 40.0) }; + let path = [crate::PathSeg::Curve { plane: xz, seg }]; + let sq = region(Loop2::polygon(&[Vec2::new(-2.0, -2.0), Vec2::new(2.0, -2.0), Vec2::new(2.0, 2.0), Vec2::new(-2.0, 2.0)])); + let b = smlib_sweeps::sweep(&Plane::XY, &pieces_of(&sq), &path, false).unwrap(); + close(volume(&b), 16.0 * 46.220575543, 1e-3, "square along a Bézier"); + assert_eq!(b.face_count(), 6, "four smooth walls and two caps"); + // Twisted along it, through stations placed by length along the curve: the area is kept. + let ctl = crate::SweepControl { twist: PI / 2.0, ..Default::default() }; + let b = smlib_sweeps::sweep_controlled(&Plane::XY, &numbered(&sq), &path, &ctl).unwrap(); + close(volume(&b), 16.0 * 46.220575543, 1e-3, "twisted square along a Bézier"); +} + +/// A ring about the origin: `outer` radius with a hole of radius `bore`. +fn ring(outer: f64, bore: f64) -> Region2 { + Region2 { outer: Loop2::circle(Vec2::ZERO, outer), holes: vec![Loop2::circle(Vec2::ZERO, bore)] } +} + +/// The faces of `b` on a cylinder about the z axis of radius `r`. +fn z_cylinders(b: &Body, r: f64) -> usize { + (0..b.face_count()) + .filter(|&f| match crate::face_surface(b, f) { + Some(crate::FaceSurface::Cylinder { origin, axis, radius }) => { + (radius - r).abs() <= 1e-9 && axis.cross(Vec3::Z).len() <= 1e-12 && origin.x.hypot(origin.y) <= 1e-9 + } + _ => false, + }) + .count() +} + +#[test] +fn a_twisted_sweep_builds_circles_about_its_path_as_exact_cylinders() { + // solidcore#2184: a tube r 2 / 1.5 extruded over z -2..3, joined with a tube r 2.5 / 1.5 swept + // 1.25 up z with a twist. The twist turns each circle onto itself, so both of the swept tube's + // walls are the exact cylinders, and its bore lies on the extruded tube's: one body, + // pi (1.75 x 5 + 4 x 1.25 - 1.75 x 1.25) = 11.5625 pi. Skinned, the bore stayed within 4e-9 + // of the cylinder and the join failed at 16, 20 and 30 degrees. + let a = crate::extrude(&Plane::XY, &[ring(2.0, 1.5)], -2.0, 3.0).unwrap().pop().unwrap(); + let up = [crate::PathSeg::Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 1.25) }]; + let want = PI * (1.75 * 5.0 + 4.0 * 1.25 - 1.75 * 1.25); + for deg in [10.0f64, 16.0, 18.0, 20.0, 30.0] { + let ctl = crate::SweepControl { twist: deg.to_radians(), ..Default::default() }; + let b = crate::sweep_with(&Plane::XY, &ring(2.5, 1.5), &up, &ctl).unwrap(); + assert_eq!((z_cylinders(&b, 1.5), z_cylinders(&b, 2.5)), (1, 1), "{deg} deg: the walls are cylinders"); + let mut want_b = vec![cap(false), cap(true), profile(0), profile(1)]; + want_b.sort(); + assert_eq!(origins(&b), want_b, "{deg} deg"); + let joined = crate::boolean(&a, &b, crate::BoolOp::Union).unwrap().unwrap(); + assert_eq!((joined.shell_count(), joined.validity()), (1, Vec::::new()), "{deg} deg"); + close(volume(&joined), want, 1e-8, &format!("{deg} deg join")); + assert!(z_cylinders(&joined, 1.5) >= 1, "{deg} deg: the bore is a cylinder"); + } + // A hexagon (circumradius 2.5, across flats 4.33, clear of the extruded tube's r 2) with the + // same bore, twisted 30 degrees: the hexagon's walls are skinned, the bore cut as the exact + // cylinder and named by its circle. The join is A + B less A's ring over 1.25. + let hex = + Loop2::polygon(&(0..6).map(|i| Vec2::new(2.5 * (f64::from(i) * PI / 3.0).cos(), 2.5 * (f64::from(i) * PI / 3.0).sin())).collect::>()); + let hexed = Region2 { outer: hex, holes: vec![Loop2::circle(Vec2::ZERO, 1.5)] }; + let ctl = crate::SweepControl { twist: 30f64.to_radians(), ..Default::default() }; + let b = crate::sweep_with(&Plane::XY, &hexed, &up, &ctl).unwrap(); + let hex_area = 1.5 * 3f64.sqrt() * 6.25; + close(volume(&b), (hex_area - PI * 2.25) * 1.25, 1e-5, "twisted hexagon"); + assert_eq!(z_cylinders(&b, 1.5), 1, "the bore is a cylinder"); + let o = origins(&b); + assert!(o.contains(&cap(false)) && o.contains(&cap(true)) && (0..7).all(|k| o.contains(&profile(k))), "{o:?}"); + let joined = crate::boolean(&a, &b, crate::BoolOp::Union).unwrap().unwrap(); + assert_eq!((joined.shell_count(), joined.validity()), (1, Vec::::new())); + close(volume(&joined), PI * 1.75 * 5.0 + (hex_area - PI * 2.25) * 1.25 - PI * 1.75 * 1.25, 1e-5, "hexagon join"); + // A circle off the path's line is skinned as before. + let off = region(Loop2::circle(Vec2::new(0.5, 0.0), 1.0)); + let b = crate::sweep_with(&Plane::XY, &off, &up, &ctl).unwrap(); + assert!((0..b.face_count()).all(|f| !matches!(crate::face_surface(&b, f), Some(crate::FaceSurface::Cylinder { .. })))); + close(volume(&b), PI * 1.25, 1e-6, "twisted circle off the axis"); +} diff --git a/crates/kernel/src/smooth_edges.rs b/crates/kernel/src/smooth_edges.rs index 90460e3e9..ae718e6df 100644 --- a/crates/kernel/src/smooth_edges.rs +++ b/crates/kernel/src/smooth_edges.rs @@ -1,231 +1,353 @@ -//! Display-only tangent joins. Unknown geometry retains its existing presentation. -use solidcraft_geom::{Mesh, Vec3}; -use truck_modeling as mt; +//! Display-only smooth joins: which edges the shaded view leaves out because they lie inside one +//! smooth surface (the two faces meet with one tangent plane and one curvature across the edge, +//! G2), and which it must keep because they are a crease or an authored split. A join that is +//! only tangent (G1: a fillet's boundary, a plane tangent to a cylinder) is a feature line and is +//! drawn. +//! +//! One rule for every surface: at stations along the edge, each face's outward normal and its +//! normal curvature across the edge are evaluated on its exact surface ([`Face::parameters`]) at +//! the edge's exact pcurve in that face (the use's own pcurve, so a seam a face meets itself +//! across is the same test with its two pcurves), turned by the side the shell uses the face on. +//! The edge is smooth when the normals agree within [`ANGLE`] and the curvatures within [`BEND`] +//! at every station; it is a crease where the normals differ by more than the +//! evaluation can account for anywhere (a crease far too small to see is both). Smoothness is +//! display-only: the edge keeps its identity, stays pickable and stays in the wireframe, and its +//! faces stay apart (pieces of one surface are [`crate::topo::seam_flags`]'s business). Unknown +//! geometry (a station that does not evaluate) keeps its existing presentation. +use solidcore_record::Vec3; +use solidcore_record::brep::{Brep, Loop, Shell}; +use solidcraft_geom::Mesh; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; +use solidcraft_geom::prelude::*; -use crate::body::{Body, from_p3}; +use crate::body::Body; const MAX_FACES: usize = 50_000; const MAX_EDGES: usize = 200_000; +/// Surface evaluations one body may spend (two per station). const WORK: usize = 2_000_000; -const ANGLE: f64 = 1e-8; +/// Stations along each edge: the middles of this many equal parameter spans, so neither end +/// (where a pole or a vertex of a degenerate face sits) is one. +const STATIONS: usize = 8; +/// Largest angle between the faces' normals, in radians, that still counts as tangent: half a +/// degree. Shading is the visible trace of a join: across a crease of angle θ the lit intensity +/// jumps by at most about θ of its range, and half a degree (0.0087) is under 1%, below the +/// 1–2% step the eye tells apart on a smooth gradient. So a join this close to tangent shows no +/// line in the shading. Exact tangency (fillets, analytic seams) reads 1e-12 or so, far inside +/// it; real creases a model means are degrees. Tangency alone does not hide an edge ([`BEND`]). +/// It is SolidCraft's one angle for smooth: a blend finds nothing to round below it too. +pub(crate) const ANGLE: f64 = 0.5 * std::f64::consts::PI / 180.0; +/// Largest difference of the two faces' normal curvatures across an edge, relative to the +/// larger one (or to 1 / the edge's length where both are flatter), that still counts as one +/// smooth surface (G2): [`ANGLE`], the same visibility criterion as for the normals. Continued +/// past the edge, two faces whose curvatures differ by Δκ turn their normals apart by Δκ per +/// mm; the bound keeps that under [`ANGLE`] over one radius of curvature (Δκ / κ) and over the +/// edge's own length (Δκ L), so the join leaves no visible kink in reflections either. A join +/// that is only tangent (G1) is a feature line and stays drawn: a fillet meets its plane with a +/// jump from 0 to 1 / radius (a relative difference of 1), a cylinder meets a tangent plane the +/// same way. Pieces of one surface pass: exact pieces agree to rounding, and a modelled thread's +/// flank pieces (spans of one sweep) differ by at most 0.0046 (measured, the thread test). +const BEND: f64 = ANGLE; +/// Below this sine of the angle between ∂S/∂u and ∂S/∂v the normal is undefined (a pole, an +/// apex): such a station says nothing. +const DEGENERATE: f64 = 1e-9; +/// Angle, in radians, that rounding alone can put between two unit normals evaluated in double +/// precision on exactly one tangent plane. +const ROUNDOFF: f64 = 1e-12; -#[derive(Clone, Copy)] -struct Boundary { - a: Vec3, - b: Vec3, - normal: Vec3, - error: f64, -} - -fn charge(work: &mut usize, amount: usize) -> Option<()> { - *work = work.checked_sub(amount)?; - Some(()) -} - -fn roundoff(points: &[Vec3]) -> f64 { - points.iter().flat_map(|p| [p.x.abs(), p.y.abs(), p.z.abs()]).fold(1., f64::max) * f64::EPSILON * 64. -} - -/// Only a clamped Bezier profile swept by one common linear translation. -/// Its whole ruling normal is bounded from the linear cross derivative, not sampled. -fn ruled(surface: &mt::Surface, orientation: bool, work: &mut usize) -> Option<[Boundary; 2]> { - let mt::Surface::BSplineSurface(surface) = surface else { return None }; - let controls = surface.control_points(); - let rows = controls.len(); - let cols = controls.first()?.len(); - if !(2..=33).contains(&rows) || !(2..=33).contains(&cols) || controls.iter().any(|row| row.len() != cols) { - return None; - } - charge(work, rows.checked_mul(cols)?.checked_mul(4)?)?; - let (ku, kv) = surface.knot_vecs(); - let clamped = |knots: &mt::KnotVec, count: usize| { - let (Some(first), Some(last)) = (knots.first(), knots.last()) else { return false }; - knots.len() == count * 2 - && first.is_finite() - && last.is_finite() - && first < last - && knots.iter().take(count).all(|k| k == first) - && knots.iter().skip(count).all(|k| k == last) - }; - if !clamped(ku, rows) || !clamped(kv, cols) { - return None; - } - for transpose in [false, true] { - let (count, axial) = if transpose { (cols, rows) } else { (rows, cols) }; - if axial != 2 { - continue; - } - let at = |i: usize, j: usize| { - let p = if transpose { controls.get(j)?.get(i)? } else { controls.get(i)?.get(j)? }; - let p = from_p3(*p); - p.is_finite().then_some(p) - }; - let a = at(0, 0)?; - let b = at(0, 1)?; - let ruling = b - a; - if ruling.len() < 1e-6 { - continue; - } - let mut valid = true; - for i in 0..count { - let p = at(i, 0)?; - let q = at(i, 1)?; - if (q - p - ruling).len() > roundoff(&[a, b, p, q]) { - valid = false; - break; - } - } - if !valid { - continue; - } - let boundary = |index: usize, next: usize, end: bool| { - let a = at(index, 0)?; - let b = at(index, 1)?; - let tangent = if end { a - at(next, 0)? } else { at(next, 0)? - a }; - let error = roundoff(&[a, b, at(next, 0)?]); - // Ill-conditioned derivatives cannot certify a tiny angular join. - if tangent.len() <= error / ANGLE || ruling.len() <= error / ANGLE { - return None; - } - let cross = if transpose { ruling.cross(tangent) } else { tangent.cross(ruling) }; - let normal = cross.normalized()? * if orientation { 1. } else { -1. }; - let top_tangent = if end { b - at(next, 1)? } else { at(next, 1)? - b }; - let top_cross = if transpose { ruling.cross(top_tangent) } else { top_tangent.cross(ruling) }; - let top_normal = top_cross.normalized()? * if orientation { 1. } else { -1. }; - // Along this linear ruling the cross derivative is a linear - // interpolation of these endpoint vectors. Positive alignment - // excludes a singularity; all intermediate normal directions lie - // between their directions. Include that whole-span variation. - if normal.dot(top_normal) <= 0. { - return None; - } - let conditioning = cross.len().min(top_cross.len()); - let normal_error = 8. * error * (tangent.len().max(top_tangent.len()) + ruling.len()) / conditioning + normal.dist(top_normal); - if !normal_error.is_finite() || normal_error > ANGLE { - return None; - } - Some(Boundary { a, b, normal, error: normal_error }) - }; - if let (Some(first), Some(last)) = (boundary(0, 1, false), boundary(count - 1, count - 2, true)) { - return Some([first, last]); - } - } - None -} - -fn on_boundary(boundaries: &[Boundary; 2], a: Vec3, b: Vec3) -> Option { - boundaries.iter().find_map(|boundary| { - let tolerance = roundoff(&[a, b, boundary.a, boundary.b]); - ((a.dist(boundary.a) <= tolerance && b.dist(boundary.b) <= tolerance) || (a.dist(boundary.b) <= tolerance && b.dist(boundary.a) <= tolerance)) - .then_some(*boundary) - }) +/// What the stations along one edge say. The two verdicts are separate: a join can be too +/// close to tangent to show in the shading (`smooth`) and still be a measured crease +/// (`crease`) — a real edge between two surfaces, kept pickable and apart even where a coarse +/// fit takes its faces for one surface ([`crate::topo::seam_flags`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Join { + /// Every station's normals agree within [`ANGLE`] and its curvatures across within [`BEND`]. + smooth: bool, + /// Some station's normals differ by more than the evaluation can account for: the pcurve + /// points lie some distance off the edge's curve (measured at the station), and over that + /// distance a normal turns by at most the distance times the surface's largest curvature. + crease: bool, } pub(crate) fn flags(body: &Body, mesh: &Mesh) -> (Vec, Vec) { crate::guard("smooth display edges", || Ok(classify(body, mesh, WORK))).unwrap_or_default() } +/// A face ready to evaluate: its surface and the sign that turns the natural normal outward. +struct FaceEval { + surface: SurfaceEval, + side: f64, +} + +/// Each face's evaluator, or `None` where its surface does not evaluate or no shell uses it. A +/// face's side is the one its first shell uses it on. +fn face_evals(record: &Brep) -> Vec> { + let mut forward: Vec> = vec![None; record.faces.len()]; + for shell in &record.shells { + if let Shell::Faces { faces, .. } = shell { + for f in faces { + if let Some(slot) = forward.get_mut(f.face as usize) { + slot.get_or_insert(f.forward); + } + } + } + } + record + .faces + .iter() + .zip(forward) + .map(|(face, forward)| { + let surface = SurfaceEval::new(face.parameters()).ok()?; + Some(FaceEval { surface, side: if forward? { 1.0 } else { -1.0 } }) + }) + .collect() +} + +/// A face at a station: its point, outward unit normal, first and second derivatives, and a +/// bound on its curvature. +struct Station { + point: Vec3, + normal: Vec3, + su: Vec3, + sv: Vec3, + /// `(S_uu, S_uv, S_vv)`; `None` where the surface has none (a revolution). + second: Option<(Vec3, Vec3, Vec3)>, + /// The larger principal curvature's size, 1/mm (`None`: no second derivatives, so a crease + /// cannot be told from evaluation error). + curvature: Option, +} + +impl Station { + /// The normal curvature in the tangent direction `w`, 1/mm, signed by the outward normal: + /// II(w) / I(w), with `w` written in (u, v) by its projection on the tangent plane. + fn across(&self, w: Vec3) -> Option { + let (suu, suv, svv) = self.second?; + let (e, f, g) = (self.su.dot(self.su), self.su.dot(self.sv), self.sv.dot(self.sv)); + let det = e * g - f * f; + let (wu, wv) = (self.su.dot(w), self.sv.dot(w)); + let (a, b) = ((g * wu - f * wv) / det, (e * wv - f * wu) / det); + let first = e * a * a + 2. * f * a * b + g * b * b; + let (l, m, n) = (suu.dot(self.normal), suv.dot(self.normal), svv.dot(self.normal)); + let k = (l * a * a + 2. * m * a * b + n * b * b) / first; + (det > 0. && first > 0. && k.is_finite()).then_some(k) + } +} + +/// `face` at `uv`; `Some(None)` where the normal is undefined there, `None` where it does not +/// evaluate. +fn station(face: &FaceEval, uv: [f64; 2]) -> Option> { + let (point, su, sv) = face.surface.derivs(uv[0], uv[1])?; + if !point.is_finite() || !su.is_finite() || !sv.is_finite() { + return None; + } + let n = su.cross(sv); + if !(n.len() > DEGENERATE * su.len() * sv.len()) { + return Some(None); + } + let Some(unit) = n.normalized() else { return Some(None) }; + let second = face.surface.second(uv[0], uv[1]).filter(|(a, b, c)| a.is_finite() && b.is_finite() && c.is_finite()); + // The principal curvatures, from the shape operator I⁻¹ II: H ± √(H² − K). + let curvature = second.and_then(|(suu, suv, svv)| { + let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv)); + let (l, m, n) = (suu.dot(unit), suv.dot(unit), svv.dot(unit)); + let det = e * g - f * f; + let mean = (e * n - 2. * f * m + g * l) / (2. * det); + let gauss = (l * n - m * m) / det; + let most = mean.abs() + (mean * mean - gauss).max(0.).sqrt(); + (det > 0. && most.is_finite()).then_some(most) + }); + Some(Some(Station { point, normal: unit * face.side, su, sv, second, curvature })) +} + +/// How the two uses of edge `e` meet: their faces' outward normals compared at [`STATIONS`] +/// stations, each through its own pcurve. +fn join(record: &Brep, faces: &[Option], e: usize, length: f64, work: &mut usize) -> Join { + let unknown = Join::default(); + let Some(edge) = record.edges.get(e) else { return unknown }; + let [a, b] = edge.uses.as_slice() else { return unknown }; + let side = |u: &solidcore_record::brep::EdgeUseRef| { + let face = faces.get(u.face as usize)?.as_ref()?; + let Loop::Edges { edges } = record.faces.get(u.face as usize)?.loops.get(u.r#loop as usize)? else { return None }; + let used = edges.get(u.position as usize)?; + (used.edge as usize == e).then_some((face, &used.pcurve)) + }; + let (Some((fa, pa)), Some((fb, pb))) = (side(a), side(b)) else { return unknown }; + let [t0, t1] = edge.interval; + if !(t0.is_finite() && t1.is_finite() && t0 < t1 && edge.tolerance.is_finite() && edge.tolerance >= 0.) { + return unknown; + } + let curve = CurveEval::new(edge.parameters()).ok(); + let (mut measured, mut smooth, mut crease) = (false, true, false); + for k in 0..STATIONS { + let Some(left) = work.checked_sub(2) else { return unknown }; + *work = left; + let t = t0 + (t1 - t0) * (k as f64 + 0.5) / STATIONS as f64; + let (Some(ua), Some(ub)) = (solidcraft_geom::brep::pcurve::eval(pa, t), solidcraft_geom::brep::pcurve::eval(pb, t)) else { return unknown }; + let (Some(sa), Some(sb)) = (station(fa, ua), station(fb, ub)) else { return unknown }; + let (Some(sa), Some(sb)) = (sa, sb) else { continue }; + let angle = sa.normal.cross(sb.normal).len().atan2(sa.normal.dot(sb.normal)); + if !angle.is_finite() { + return unknown; + } + measured = true; + smooth &= angle <= ANGLE && same_bend(&sa, &sb, curve.as_ref().and_then(|c| c.derivs(t)).map(|d| d.1), length); + // How far each evaluated point lies off the edge, measured on the edge's own curve + // (its tolerance where the curve does not evaluate). + let off = match curve.as_ref().and_then(|c| c.point(t)).filter(|c| c.is_finite()) { + Some(c) => sa.point.dist(c).max(sb.point.dist(c)).max(sa.point.dist(sb.point)), + None => edge.tolerance, + }; + if let (Some(ka), Some(kb)) = (sa.curvature, sb.curvature) { + crease |= angle > off * (ka + kb) + ROUNDOFF; + } + crease |= angle > ANGLE; + } + if measured { Join { smooth, crease } } else { unknown } +} + +/// Do the two faces bend alike across the edge at a station (G2 there): their normal +/// curvatures in the direction across the edge (in the tangent plane, square to the edge's +/// tangent `along`) within [`BEND`] of the larger, or of 1 / `length` where both are flatter +/// than that? Unknown (no tangent, no second derivatives) is no. +fn same_bend(a: &Station, b: &Station, along: Option, length: f64) -> bool { + let Some(w) = along.and_then(|t| a.normal.cross(t).normalized()) else { return false }; + let (Some(ka), Some(kb)) = (a.across(w), b.across(w)) else { return false }; + let scale = ka.abs().max(kb.abs()).max(1. / length); + (ka - kb).abs() <= BEND * scale +} + +/// Does the mesh's edge `e` bound the faces the record's edge `e` is used by? A mesh that says +/// otherwise is not this record's, and its edge keeps its presentation. +fn same_faces(record: &Brep, mesh: &Mesh, e: usize) -> bool { + let (Some(edge), Some(listed)) = (record.edges.get(e), mesh.edge_faces.get(e)) else { return false }; + let mut used: Vec = edge.uses.iter().map(|u| u.face).collect(); + let mut listed = listed.clone(); + used.sort_unstable(); + used.dedup(); + listed.sort_unstable(); + listed.dedup(); + used == listed +} + fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec, Vec) { - if body.solid.face_iter().take(MAX_FACES + 1).count() > MAX_FACES || mesh.edges.len() > MAX_EDGES { + let Ok(rec) = crate::native::brep_record(body) else { return (Vec::new(), Vec::new()) }; + if rec.faces.len() > MAX_FACES || mesh.edges.len() > MAX_EDGES { return (Vec::new(), Vec::new()); } let mut split_points = 0usize; for line in body.split_keep() { - if charge(&mut work, line.len().saturating_add(1)).is_none() { - return (Vec::new(), Vec::new()); - } + let Some(left) = work.checked_sub(line.len().saturating_add(1)) else { return (Vec::new(), Vec::new()) }; + work = left; let Some(total) = split_points.checked_add(line.len()) else { return (Vec::new(), Vec::new()) }; split_points = total; } - let mut boundaries = Vec::new(); - for face in body.solid.face_iter() { - // Borrow the geometry through mapping, avoiding a deep clone of an - // unknown/hostile surface before inspecting its control-net bounds. - let wires = face.absolute_boundaries(); - if wires.len() > 16 { - boundaries.push(None); - continue; - } - let edge_count = wires.iter().fold(0usize, |sum, wire| sum.saturating_add(wire.len())); - if edge_count > 16 || charge(&mut work, edge_count + 1).is_none() { - boundaries.push(None); - continue; - } - // Mapping rebuilds each edge through a check that refuses one starting and ending at - // the same vertex (a loop of one closed edge: a hole a closed curve cut). - if wires.iter().flat_map(|w| w.edge_iter()).any(|e| e.front().id() == e.back().id()) { - boundaries.push(None); - continue; - } - let mapped = face.try_mapped(|_| Some(()), |_| Some(()), |surface| ruled(surface, face.orientation(), &mut work)); - boundaries.push(mapped.map(|face| face.surface())); - } - let mut out = vec![false; mesh.edges.len()]; + let faces = face_evals(&rec); + let mut smooth = vec![false; mesh.edges.len()]; let mut sharp = vec![false; mesh.edges.len()]; - // Same first-occurrence order as tessellate().edges; never remove/reindex it. - let mut seen = std::collections::HashSet::new(); - let mut index = 0usize; - for edge in body.solid.edge_iter() { - if index >= mesh.edges.len() || seen.len() >= MAX_EDGES { - break; - } - if charge(&mut work, 1).is_none() { - break; - } - if !seen.insert(edge.id()) { - continue; - } - let current = index; - index += 1; - let Some([a, b]) = mesh.edge_faces.get(current).map(Vec::as_slice) else { continue }; - if a == b { - continue; - } - let Some(line) = mesh.edges.get(current) else { continue }; + // Edges of one join: the measured edges between the same faces that continue each other. + let mut joins: Vec = Vec::new(); + // The mesh's edges are the record's, in its order. + for (current, line) in mesh.edges.iter().enumerate().take(rec.edges.len()) { let Some(split_work) = line.len().checked_add(1).and_then(|n| n.checked_mul(split_points)) else { break }; - if charge(&mut work, split_work).is_none() { - break; - } - if crate::heal::on_split_line(line, body.split_keep()) { - if let Some(flag) = sharp.get_mut(current) { + let Some(left) = work.checked_sub(split_work) else { break }; + work = left; + let flag = if crate::heal::on_split_line(line, body.split_keep()) { + sharp.get_mut(current) + } else if !same_faces(&rec, mesh, current) { + None + } else { + joins.push(current); + let length: f64 = line.windows(2).map(|w| if let [a, b] = w { a.dist(*b) } else { 0. }).sum(); + let Join { smooth: tangent, crease } = + if length > 0. && length.is_finite() { join(&rec, &faces, current, length, &mut work) } else { Join::default() }; + if let (true, Some(flag)) = (tangent, smooth.get_mut(current)) { *flag = true; } - continue; + crease.then(|| sharp.get_mut(current)).flatten() + }; + if let Some(flag) = flag { + *flag = true; } - let (Some(Some(ba)), Some(Some(bb))) = (boundaries.get(*a as usize), boundaries.get(*b as usize)) else { continue }; - // Curve is inspected by borrowing. Only exact straight rulings qualify; - // a bowed/twisted edge with matching endpoints must remain visible. - let mapped = edge.try_mapped( - |_| Some(()), - |curve| match curve { - mt::Curve::Line(line) => Some((from_p3(line.0), from_p3(line.1))), - _ => None, - }, - ); - let Some(mapped) = mapped else { continue }; - let (p, q) = mapped.curve(); - let (Some(na), Some(nb)) = (on_boundary(ba, p, q), on_boundary(bb, p, q)) else { continue }; - let uncertainty = na.error + nb.error; - let cross = na.normal.cross(nb.normal).len(); - if na.normal.dot(nb.normal) > 0. - && cross + uncertainty <= ANGLE - && let Some(flag) = out.get_mut(current) - { - *flag = true; - } else if (cross > ANGLE + uncertainty || na.normal.dot(nb.normal) < -uncertainty) - && let Some(flag) = sharp.get_mut(current) - { - *flag = true; + if work == 0 { + break; + } + } + whole_joins(&rec, &joins, &mut smooth, work); + (smooth, sharp) +} + +/// One verdict for each join, however the B-rep splits it: the edges in `measured` between the +/// same faces that continue each other at a shared vertex (their curves' tangents there within +/// [`ANGLE`] of one line) are one join, smooth only where every one of its edges is. A seam +/// SMLib holds as two edges, G2 along one and only near G2 along the other (a G2 corner patch's +/// side next to the face it ends on), is drawn whole, never to a vertex in the middle of the +/// line. `work` bounds the pairs compared; past it the edges keep their own verdicts. +fn whole_joins(record: &Brep, measured: &[usize], smooth: &mut [bool], mut work: usize) { + // Per vertex, each measured edge ending there: its faces and its tangent leaving the vertex. + let mut ends: std::collections::HashMap, Vec3)>> = std::collections::HashMap::new(); + for &e in measured { + let Some(edge) = record.edges.get(e) else { continue }; + let Some(curve) = CurveEval::new(edge.parameters()).ok() else { continue }; + let mut faces: Vec = edge.uses.iter().map(|u| u.face).collect(); + faces.sort_unstable(); + faces.dedup(); + let [t0, t1] = edge.interval; + for (vertex, t, sign) in [(edge.vertices[0], t0, 1.), (edge.vertices[1], t1, -1.)] { + if let Some(d) = curve.derivs(t).and_then(|d| (d.1 * sign).normalized()) { + ends.entry(vertex).or_default().push((e, faces.clone(), d)); + } + } + } + let mut parent: Vec = (0..smooth.len()).collect(); + fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i) { + if p == i { + break; + } + let up = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = up; + } + i = up; + } + i + } + let cos = ANGLE.cos(); + 'vertices: for at in ends.values() { + for (i, (a, fa, da)) in at.iter().enumerate() { + for (b, fb, db) in at.iter().skip(i + 1) { + let Some(left) = work.checked_sub(1) else { break 'vertices }; + work = left; + // Leaving the vertex in opposite directions: one continues the other. + if a != b && fa == fb && da.dot(*db) <= -cos { + let (ra, rb) = (root(&mut parent, *a), root(&mut parent, *b)); + if let Some(slot) = parent.get_mut(ra) { + *slot = rb; + } + } + } + } + } + let mut whole: std::collections::HashMap = std::collections::HashMap::new(); + for &e in measured { + let r = root(&mut parent, e); + let own = smooth.get(e).copied().unwrap_or(false); + whole.entry(r).and_modify(|s| *s &= own).or_insert(own); + } + for &e in measured { + let r = root(&mut parent, e); + if let (Some(slot), Some(&all)) = (smooth.get_mut(e), whole.get(&r)) { + *slot = all; } } - (out, sharp) } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; + use solidcore_record::brep::Surface; + use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; fn circle(radius: f64, count: usize) -> Loop2 { let step = std::f64::consts::TAU / count as f64; @@ -261,11 +383,11 @@ mod tests { }, ) .unwrap(); - let ring: Vec = circle(4., 8).segs; + let ring: Vec = Loop2::circle(Vec2::ZERO, 4.).segs; let tool = crate::SplitTool::Curves { plane: Plane::XY, curves: vec![ring], along: None }; let holed = crate::trim(&sheet, &tool, Vec3::new(9., 9., 0.)).unwrap(); - assert!(holed.solid.edge_iter().any(|e| e.front().id() == e.back().id()), "a closed edge"); - let mesh = holed.tessellate(0.02).unwrap(); + assert!(crate::native::brep_record(&holed).unwrap().edges.iter().any(|e| e.vertices[0] == e.vertices[1]), "a closed edge"); + let mesh = holed.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); let (smooth, sharp) = classify(&holed, &mesh, WORK); assert_eq!((smooth.len(), sharp.len()), (mesh.edges.len(), mesh.edges.len())); } @@ -273,18 +395,19 @@ mod tests { #[test] fn periodic_ring_hides_only_whole_smooth_wall_joins() { let body = ring(256); - let mesh = body.display_mesh(0.02).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); assert_eq!(mesh.edges.len(), 1536); assert_eq!(mesh.smooth_edges.iter().filter(|f| **f).count(), 512); for (index, (line, smooth)) in mesh.edges.iter().zip(&mesh.smooth_edges).enumerate() { let vertical = (line.first().unwrap().z - line.last().unwrap().z).abs() > 2.9; assert_eq!(*smooth, vertical); + assert!(!(vertical && mesh.sharp_edges[index]), "a tangent join is measured as no crease"); if !vertical { assert!(mesh.shaded_edge_visible(index)); } } // Smoothing flags are display-only: the edges and faces keep the body's identities. - let raw = body.tessellate(0.02).unwrap(); + let raw = body.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); assert_eq!(mesh.edges.len(), raw.edges.len()); assert_eq!(mesh.edge_faces, raw.edge_faces); for (a, b) in mesh.edges.iter().zip(&raw.edges) { @@ -293,13 +416,13 @@ mod tests { let faces = |m: &Mesh| m.tri_face.iter().copied().collect::>(); assert_eq!(faces(&mesh), faces(&raw)); let moved = crate::transform_matrix(&body, [[1., 0., 0., 0.], [0., 0., 1., 0.], [0., -1., 0., 0.], [30., 20., 10., 1.]]).unwrap(); - assert_eq!(moved.display_mesh(0.02).unwrap().smooth_edges.iter().filter(|f| **f).count(), 512); + assert_eq!(moved.mesh(&crate::MeshTolerance::chord(0.02)).unwrap().smooth_edges.iter().filter(|f| **f).count(), 512); } #[test] fn authored_split_unknown_adjacency_and_exhausted_work_stay_visible() { let body = ring(8); - let mesh = body.display_mesh(0.02).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); let index = mesh.smooth_edges.iter().position(|f| *f).unwrap(); let split = body.clone().with_split_lines(Some(std::sync::Arc::new(vec![mesh.edges[index].clone()]))); assert!(!flags(&split, &mesh).0[index]); @@ -307,26 +430,42 @@ mod tests { unknown.edge_faces[index].push(999); assert!(!flags(&body, &unknown).0[index]); assert!(classify(&body, &mesh, 0).0.iter().all(|f| !*f)); - // Matching endpoints alone cannot authorize a bowed current edge. - let changed = Body::new(body.deep_copy()).unwrap(); - let edges = Body::unique_edges(&changed.solid); - let edge = &edges[index]; - let (a, b) = (edge.front().point(), edge.back().point()); - let mid = mt::Point3::new((a.x + b.x) / 2. + 0.1, (a.y + b.y) / 2., (a.z + b.z) / 2.); - edge.set_curve(mt::Curve::BSplineCurve(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![a, mid, b]))); - let (smooth, sharp) = flags(&changed, &mesh); - assert!(!smooth[index] && !sharp[index]); } + /// A G2 corner patch's sides are G2 to their rounds except near the faces they end on, and + /// SMLib holds each side as two edges: the side is one join, drawn whole, not up to the + /// vertex in its middle where the G2 half begins (the 20 mm box's r3 corner). #[test] - fn a_small_real_crease_is_visible() { + fn a_seam_split_in_two_edges_is_drawn_whole() { + let body = crate::box_solid(Vec3::ZERO, Vec3::new(20., 20., 20.)).unwrap(); + let picks = [Vec3::new(20., 20., 10.), Vec3::new(20., 10., 20.), Vec3::new(10., 20., 20.)]; + let g2 = crate::fillet_g2_corners(&body, &picks, 3., &[]).unwrap(); + let mesh = g2.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); + let rec = crate::native::brep_record(&g2).unwrap(); + let patch = rec + .faces + .iter() + .position(|f| !matches!(f.surface, Surface::Plane { .. } | Surface::PlaneThrough { .. } | Surface::Cylinder { .. })) + .unwrap() as u32; + let rounds: Vec = (0..rec.faces.len() as u32).filter(|f| matches!(rec.faces[*f as usize].surface, Surface::Cylinder { .. })).collect(); + assert_eq!(rounds.len(), 3); + for round in rounds { + let side: Vec = + (0..mesh.edges.len()).filter(|e| mesh.edge_faces[*e].contains(&patch) && mesh.edge_faces[*e].contains(&round)).collect(); + assert_eq!(side.len(), 2, "SMLib splits the side in two: {side:?}"); + assert!(side.iter().all(|e| mesh.shaded_edge_visible(*e)), "the side to round {round} is drawn whole: {side:?}"); + } + } + + /// An extruded circle of eight cubics whose first cubic leaves its start turned by `degrees`: + /// the wall join there is a crease of that angle. + fn creased(degrees: f64) -> (Body, Mesh, usize) { let mut outer = circle(10., 8); if let Seg2::Cubic { p0, p1, .. } = &mut outer.segs[0] { - p1.x += (p1.y - p0.y) * 1e-6; + p1.x += (p1.y - p0.y) * degrees.to_radians().tan(); } let body = crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0., 3.).unwrap().remove(0); - let mesh = body.display_mesh(0.02).unwrap(); - assert_eq!(mesh.smooth_edges.iter().filter(|f| **f).count(), 7); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); let crease = mesh .edges .iter() @@ -336,25 +475,37 @@ mod tests { && line.first().zip(line.last()).is_some_and(|(a, b)| (a.z - b.z).abs() > 2.9) }) .unwrap(); + (body, mesh, crease) + } + + #[test] + fn a_crease_over_half_a_degree_is_visible_and_one_under_it_is_not() { + let (_, mesh, crease) = creased(1.0); + // The crease's other end bends differently too: only six joins are one smooth surface. + assert_eq!(mesh.smooth_edges.iter().filter(|f| **f).count(), 6); assert!(!mesh.smooth_edges[crease]); assert!(mesh.sharp_edges[crease]); assert!(mesh.shaded_edge_visible(crease)); assert!(mesh.edge_pickable(crease)); + // Too small to see, but measured: not drawn in the shading, still a real edge. + for degrees in [0.2, 1e-4] { + let (_, mesh, crease) = creased(degrees); + assert_eq!(mesh.smooth_edges.iter().filter(|f| **f).count(), 8, "{degrees}"); + assert!(mesh.sharp_edges[crease], "{degrees}"); + assert!(!mesh.shaded_edge_visible(crease), "{degrees}"); + assert!(mesh.edge_visible(crease) && mesh.edge_pickable(crease), "{degrees}: a smooth join is only left undrawn"); + } } #[test] fn actual_authored_split_of_a_curved_ruled_wall_stays_visible() { let body = ring(4); - let face = body - .solid - .face_iter() - .position(|face| face.try_mapped(|_| Some(()), |_| Some(()), |surface| ruled(surface, face.orientation(), &mut { WORK })).is_some()) - .unwrap(); + let face = crate::native::brep_record(&body).unwrap().faces.iter().position(|face| matches!(face.surface, Surface::Spline { .. })).unwrap(); let tool = crate::SplitTool::Plane(Plane::new(Vec3::new(7., 0., 0.), Vec3::Y, Vec3::Z).unwrap()); let split = crate::split_faces(&body, &[face], &tool).unwrap(); assert!(split.face_count() > body.face_count()); assert!(!split.split_keep().is_empty()); - let mesh = split.display_mesh(0.02).unwrap(); + let mesh = split.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); let authored: Vec<_> = mesh.edges.iter().enumerate().filter(|(_, line)| crate::heal::on_split_line(line, split.split_keep())).map(|(i, _)| i).collect(); assert!(!authored.is_empty()); @@ -365,19 +516,87 @@ mod tests { } #[test] - fn singular_twisted_and_reversed_normal_certificates_are_conservative() { - let surface = |points: Vec>| { - mt::Surface::BSplineSurface(mt::BSplineSurface::new((mt::KnotVec::bezier_knot(points.len() - 1), mt::KnotVec::bezier_knot(1)), points)) + fn a_spheres_and_a_cylinders_seams_are_smooth_and_their_rims_creases() { + let sphere = crate::sphere(Vec3::ZERO, 10.).unwrap(); + let mesh = sphere.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); + let (smooth, sharp) = (mesh.smooth_edges.iter().filter(|f| **f).count(), mesh.sharp_edges.iter().filter(|f| **f).count()); + assert!(smooth >= 1 && sharp == 0, "sphere: {smooth} smooth, {sharp} creases"); + let cylinder = crate::cylinder(Vec3::ZERO, Vec3::Z, 8., 20.).unwrap(); + let mesh = cylinder.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); + for (i, line) in mesh.edges.iter().enumerate() { + let vertical = line.first().zip(line.last()).is_some_and(|(a, b)| (a.z - b.z).abs() > 19.); + assert_eq!(mesh.smooth_edges[i], vertical, "edge {i}"); + assert_eq!(mesh.sharp_edges[i], !vertical, "edge {i}: a rim is a crease"); + } + } + + /// A box with its top edges and one upright edge rounded: every round meets its faces and + /// its neighbours tangentially (G1, not G2), so each of those joins is a drawn feature line + /// but no crease; the box's own edges and the miters are creases. + #[test] + fn a_filleted_boxs_tangent_joins_are_drawn_and_its_corners_creases() { + let block = crate::box_solid(Vec3::ZERO, Vec3::new(20., 20., 10.)).unwrap(); + let picks = [Vec3::new(10., 0., 10.), Vec3::new(20., 10., 10.), Vec3::new(10., 20., 10.), Vec3::new(0., 10., 10.), Vec3::new(20., 20., 5.)]; + let rounded = crate::fillet(&block, &picks, 3.).unwrap(); + let mesh = rounded.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); + for (i, line) in mesh.edges.iter().enumerate() { + let (Some(a), Some(b)) = (line.first(), line.last()) else { panic!("edge {i} has no points") }; + let corner = |p: &Vec3| [p.x, p.y].iter().all(|c| c.abs() < 1e-6 || (c - 20.).abs() < 1e-6); + // The bottom rim, the three square upright edges, and the miters where two top + // rounds meet over a square corner are creases. + let bottom = line.iter().all(|p| p.z.abs() < 1e-6); + let square_upright = corner(a) && corner(b) && (a.z - b.z).abs() > 1.; + let miter = (corner(a) && (b.z - 10.).abs() < 1e-6) || (corner(b) && (a.z - 10.).abs() < 1e-6); + assert!(!mesh.smooth_edges[i] && mesh.shaded_edge_visible(i) && mesh.edge_pickable(i), "edge {i} {a:?}..{b:?} is drawn"); + assert_eq!(mesh.sharp_edges[i], bottom || square_upright || miter, "edge {i} {a:?}..{b:?}: only the box's edges are creases"); + } + } + + /// A plane tangent to a cylinder (a D-shaped prism): one tangent plane, but the curvature + /// jumps from 0 to 1 / radius, so the join is drawn. + #[test] + fn a_plane_tangent_to_a_cylinder_is_drawn() { + let (a, b, c, d) = (Vec2::new(-5., -5.), Vec2::new(5., -5.), Vec2::new(5., 5.), Vec2::new(-5., 5.)); + let outer = Loop2 { + segs: vec![ + Seg2::Line { a, b }, + Seg2::Arc { center: Vec2::new(5., 0.), radius: 5., start: -std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI }, + Seg2::Line { a: c, b: d }, + Seg2::Line { a: d, b: a }, + ], }; - let p = |x, y, z| mt::Point3::new(x, y, z); - let straight = surface(vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 0., 3.)]]); - let forward = ruled(&straight, true, &mut { WORK }).unwrap(); - let backward = ruled(&straight, false, &mut { WORK }).unwrap(); - assert!(forward[0].normal.dot(backward[0].normal) < -0.99); - let twisted = surface(vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 1., 3.)]]); - assert!(ruled(&twisted, true, &mut { WORK }).is_none()); - let singular = surface(vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 0., 3.)]]); - assert!(ruled(&singular, true, &mut { WORK }).is_none()); - assert!(ruled(&straight, true, &mut 0).is_none()); + let body = crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0., 3.).unwrap().remove(0); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.02)).unwrap(); + let joins: Vec = (0..mesh.edges.len()) + .filter(|&i| { + let line = &mesh.edges[i]; + line.first() + .zip(line.last()) + .is_some_and(|(p, q)| (p.x - 5.).abs() < 1e-6 && (p.y.abs() - 5.).abs() < 1e-6 && (p.z - q.z).abs() > 2.9) + }) + .collect(); + assert_eq!(joins.len(), 2, "{:?}", mesh.edges.iter().map(|l| (l.first(), l.last())).collect::>()); + for i in joins { + assert!(!mesh.smooth_edges[i] && !mesh.sharp_edges[i], "edge {i}: tangent, not curvature continuous, no crease"); + assert!(mesh.shaded_edge_visible(i) && mesh.edge_pickable(i)); + } + } + + #[test] + fn a_degenerate_normal_says_nothing() { + let face = FaceEval { + surface: SurfaceEval::new(&Surface::Sphere { + frame: solidcore_record::brep::Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, + radius: 2., + }) + .unwrap(), + side: 1., + }; + assert!(matches!(station(&face, [0.3, std::f64::consts::FRAC_PI_2]), Some(None)), "the pole"); + let at = station(&face, [0., 0.]).unwrap().unwrap(); + assert!((at.normal - Vec3::X).len() < 1e-12, "{:?}", at.normal); + // A sphere's normal curvature is 1 / radius in every direction. + assert!(at.curvature.is_some_and(|k| (k - 0.5).abs() < 1e-9), "{:?}", at.curvature); + assert!(station(&face, [f64::NAN, 0.]).is_none()); } } diff --git a/crates/kernel/src/sphere_lens.rs b/crates/kernel/src/sphere_lens.rs deleted file mode 100644 index 05eda9638..000000000 --- a/crates/kernel/src/sphere_lens.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! A lens extruded from a sphere's projected outline (#2750). One of its two -//! cylinders encloses the whole target and only touches the sphere. Removing that -//! redundant constraint gives the same cut without a tangent intersection. - -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; - -use crate::boolean_record as recorded; -use crate::history::Change; -use crate::{Body, BoolOp, FaceSource, FaceSurface, Result, face_surface}; - -/// Maximum signed height of a line or circular arc, including interior extrema. -fn height(segment: Seg2, plane: Plane, cap: Plane) -> Option { - let at = |p| cap.height(plane.to_world(p)); - let ends = at(segment.start()).max(at(segment.end())); - match segment { - Seg2::Line { .. } => Some(ends), - Seg2::Arc { center, radius, .. } => { - let n = cap.normal(); - let direction = Vec2::new(n.dot(plane.x), n.dot(plane.y)); - let probe = center + direction.normalized().unwrap_or(Vec2::X) * radius; - Some(ends.max(at(segment.point_at(segment.closest_param(probe))))) - } - _ => None, - } -} - -/// Recognize a quarter ball by its complete boundary: one spherical face, two -/// perpendicular semicircular caps sharing their diameter, each cap inside the -/// other's outward halfspace. The opposite cap orientation (three quarters of a -/// ball) is refused. Whole-span curve certificates prove the caps, not samples. -fn enclosing_ball(body: &Body, tol: f64) -> Option<(Vec3, f64, Vec)> { - if body.is_mesh() || body.shell_count() != 1 || body.face_count() != 3 { - return None; - } - let surfaces = (0..3).map(|i| face_surface(body, i)).collect::>>()?; - let (sphere, center, radius) = surfaces.iter().enumerate().find_map(|(i, surface)| match *surface { - FaceSurface::Sphere { center, radius } => Some((i, center, radius)), - _ => None, - })?; - let spherical = body.solid.face_iter().nth(sphere)?; - if spherical.boundaries().len() != 1 || spherical.edge_iter().count() != 2 { - return None; - } - let sphere_edges: std::collections::HashSet<_> = spherical.edge_iter().map(|e| e.id()).collect(); - let caps: Vec<_> = surfaces - .iter() - .filter_map(|surface| match *surface { - FaceSurface::Plane { normal, point } => Plane::from_normal(point, normal), - _ => None, - }) - .collect(); - let (cap0, cap1) = (*caps.first()?, *caps.get(1)?); - if caps.len() != 2 || cap0.normal().dot(cap1.normal()).abs() > 1e-9 || cap0.height(center).abs() > tol || cap1.height(center).abs() > tol { - return None; - } - let mut work = 2_000_000usize; - let mut diameters = Vec::new(); - for (i, face) in body.solid.face_iter().enumerate() { - if i == sphere { - continue; - } - let FaceSurface::Plane { normal, point } = *surfaces.get(i)? else { return None }; - let plane = Plane::from_normal(point, normal)?; - if face.boundaries().len() != 1 || face.edge_iter().count() != 2 { - return None; - } - let c = plane.to_local(center); - let mut arc = 0.; - let mut lines = 0; - for edge in face.edge_iter() { - if plane.height(crate::body::from_p3(edge.front().point())).abs() > tol - || plane.height(crate::body::from_p3(edge.back().point())).abs() > tol - { - return None; - } - for segment in crate::prism_curve::segment(&edge, &plane, tol, &mut work)? { - match segment { - Seg2::Line { a, b } if (a + b - c * 2.).len() <= tol && (a.dist(c) - radius).abs() <= tol => { - diameters.push(edge.id()); - lines += 1; - } - Seg2::Arc { center: q, radius: r, sweep, .. } if q.dist(c) + (r - radius).abs() <= tol && sphere_edges.contains(&edge.id()) => { - arc += sweep.abs(); - } - _ => return None, - } - if height(segment, plane, cap0)? > tol || height(segment, plane, cap1)? > tol { - return None; - } - } - } - if lines != 1 || (arc - std::f64::consts::PI).abs() > 1e-8 { - return None; - } - } - if diameters.len() != 2 || diameters.first()? != diameters.get(1)? { - return None; - } - Some((center, radius, caps)) -} - -/// Replace only a construction-certified, convex two-circle lens. Its cutting cylinder stays exact; a cap moves -/// only into a halfspace proved to be outside the target. The added tool material is outside the ball. -fn relaxed_tool(a: &Body, b: &Body) -> Option { - if b.is_mesh() || b.shell_count() != 1 || b.face_count() != 4 { - return None; - } - let tol = (a.size().max(b.size()) * 1e-9).max(1e-8); - let sources = b.face_sources()?; - let (region, plane) = sources.iter().find_map(|source| match source { - Some(FaceSource::ExtrudeCap { high: true, region, plane }) => Some((region, *plane)), - _ => None, - })?; - let bottom = sources.iter().find_map(|source| match source { - Some(FaceSource::ExtrudeCap { high: false, region: r, plane }) if r == region => Some(*plane), - _ => None, - })?; - if !region.holes.is_empty() || region.outer.segs.len() != 2 || !region.outer.is_closed(tol) { - return None; - } - let circles: Vec<(Vec2, f64)> = region - .outer - .segs - .iter() - .map(|s| match *s { - Seg2::Arc { center, radius, sweep, .. } if sweep > 0.0 && sweep <= std::f64::consts::PI + 1e-9 => Some((center, radius)), - _ => None, - }) - .collect::>()?; - let ((c0, r0), (c1, r1)) = (*circles.first()?, *circles.get(1)?); - let distance = c0.dist(c1); - if distance <= (r0 - r1).abs() + tol || distance >= r0 + r1 - tol { - return None; - } - let (center, radius, caps) = enclosing_ball(a, tol)?; - let projected = plane.to_local(center); - let redundant = circles.iter().position(|(c, r)| projected.dist(*c) + radius <= *r + tol)?; - let (c, r) = *circles.get(1 - redundant)?; - let height = plane.height(bottom.origin); - if !height.is_finite() || height >= -tol || plane.normal().dot(bottom.normal()) > -1.0 + 1e-9 { - return None; - } - // The proven quarter ball lies behind each cap. Extend a coincident tool - // end outward into that empty halfspace; this avoids the generic nudge's - // paper-thin lid across the opening, without moving the cutting cylinder. - let on_cap = |end: Plane| caps.iter().any(|cap| cap.normal().dot(end.normal()) > 1.0 - 1e-9 && cap.height(end.origin).abs() <= tol); - let (low, high) = (on_cap(bottom), on_cap(plane)); - if !low && !high { - return None; - } - let margin = (a.size().max(b.size()) * 0.01).max(1e-5); - let lo = height - if low { margin } else { 0. }; - let hi = if high { margin } else { 0. }; - let mut tool = - crate::extrude(&plane, &[Region2 { outer: Loop2::circle_from(c, r, crate::build::SEAM_ANGLE), holes: vec![] }], lo, hi).ok()?.pop()?; - // Each rebuilt surface names its original tool face. Extended portions never - // meet the target, so every face used in the cut still lies in that input face. - let mut faces = Vec::new(); - for i in 0..tool.face_count() { - let surface = face_surface(&tool, i)?; - let original = (0..b.face_count()).find(|j| match (surface, face_surface(b, *j)) { - (FaceSurface::Plane { normal: n, .. }, Some(FaceSurface::Plane { normal: m, .. })) => n.dot(m) > 1.0 - 1e-9, - (FaceSurface::Cylinder { origin: p, axis: n, radius: r }, Some(FaceSurface::Cylinder { origin: q, axis: m, radius: s })) => { - n.dot(m).abs() > 1.0 - 1e-9 && (p - q).cross(n).len() + (r - s).abs() <= tol - } - _ => false, - })?; - faces.push(crate::record::from_face(0, original, Change::Modified)); - } - let history = crate::record::from_faces(&tool.solid, 1, faces); - tool = tool.with_checked_history(Some(history), &crate::record::counts(&[b])); - Some(tool) -} - -pub(crate) fn cut(a: &Body, b: &Body, run: &dyn Fn(&Body, &Body, BoolOp) -> Result>) -> Option>> { - let tool = crate::guard("sphere lens tool", || Ok(relaxed_tool(a, b))).ok()??; - let result = run(a, &tool, BoolOp::Cut).ok()?; - crate::boolean_guard::check_retry(a, b, BoolOp::Cut, result.as_ref()).ok()?; - Some(Ok(result.map(|body| { - let history = recorded::through(&body, 1, tool.history()); - body.with_checked_history(history, &crate::record::counts(&[a, b])) - }))) -} - -#[cfg(test)] -#[path = "sphere_lens_tests.rs"] -mod tests; diff --git a/crates/kernel/src/sphere_lens_tests.rs b/crates/kernel/src/sphere_lens_tests.rs index b46be3e8f..c09023334 100644 --- a/crates/kernel/src/sphere_lens_tests.rs +++ b/crates/kernel/src/sphere_lens_tests.rs @@ -1,4 +1,8 @@ -use super::*; +//! A lens extruded from a sphere's projected outline cut from the sphere (#2750): one of its +//! cylinders encloses the target and only touches the sphere. +use crate::history::BodyHistory; +use crate::{Body, BoolOp}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use std::f64::consts::{FRAC_PI_2, PI}; fn dome() -> Body { @@ -36,9 +40,7 @@ fn tool(region: Region2, depth: f64) -> Body { fn projected_spherical_outline_does_not_block_a_lens_cut() { let target = dome(); let cutter = tool(lens(25.), 30.); - let (result, diagnostics) = crate::capture_boolean_diagnostics(|| crate::boolean(&target, &cutter, BoolOp::Cut)); - let result = result.unwrap().unwrap(); - assert!(diagnostics.events.iter().all(|event| !event.strategy.alters_result()), "{diagnostics:?}"); + let result = crate::boolean(&target, &cutter, BoolOp::Cut).unwrap().unwrap(); assert!(result.validity().is_empty(), "{:?}", result.validity()); assert_eq!(result.lumps().unwrap().len(), 1); // Integrating the half-disc cross-section left by the offset bore gives @@ -46,28 +48,10 @@ fn projected_spherical_outline_does_not_block_a_lens_cut() { let measured = crate::measure(&result).unwrap(); assert!((measured.volume - 8810.08973246).abs() < 2., "{measured:?}"); assert!(measured.bbox.max.z < 20.01, "no thin lid may remain above the cut: {measured:?}"); - assert!(result.contains(Vec3::new(0., -10., 2.))); - assert!(!result.contains(Vec3::new(0., -10., 15.))); + assert_eq!(result.classify_point(Vec3::new(0., -10., 2.)).unwrap(), crate::PointClass::Inside); + assert_eq!(result.classify_point(Vec3::new(0., -10., 15.)).unwrap(), crate::PointClass::Outside); assert_eq!(measured.merged.face_types.get("cylinder"), Some(&1)); - let history = result.history().expect("the retry composes the tool's face history"); + let history = result.history().expect("the cut has a face history"); history.check(&result, &[&target, &cutter]).unwrap(); assert!(history.faces.iter().all(|f| !f.origins.is_empty())); } - -#[test] -fn only_an_enclosing_wall_can_be_removed_and_cap_depth_stays_exact() { - let target = dome(); - assert!(relaxed_tool(&target, &tool(lens(24.), 30.)).is_none(), "a cylinder inside the sphere removes real material"); - let rectangle = - Region2 { outer: Loop2::polygon(&[Vec2::new(-4., 5.), Vec2::new(4., 5.), Vec2::new(4., 15.), Vec2::new(-4., 15.)]), holes: vec![] }; - assert!(relaxed_tool(&target, &tool(rectangle, 30.)).is_none()); - let cutter = tool(lens(25.), 7.); - let relaxed = relaxed_tool(&target, &cutter).unwrap(); - let bounds = crate::measure(&relaxed).unwrap().bbox; - assert!((bounds.min.y + 7.).abs() < 1e-6 && bounds.max.y > 0., "only the end outside the quarter ball is extended: {bounds:?}"); - let cut = crate::boolean(&target, &cutter, BoolOp::Cut).unwrap().unwrap(); - assert!(cut.contains(Vec3::new(0., -8., 15.)), "material past the pocket floor stays"); - assert!(!cut.contains(Vec3::new(0., -6., 15.)), "the shallow pocket removes material up to its floor"); - let box_target = crate::box_solid(Vec3::new(-25., -25., 0.), Vec3::new(25., 0., 25.)).unwrap(); - assert!(relaxed_tool(&box_target, &cutter).is_none()); -} diff --git a/crates/kernel/src/spline_conv.rs b/crates/kernel/src/spline_conv.rs deleted file mode 100644 index 01b870354..000000000 --- a/crates/kernel/src/spline_conv.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! geom's B-spline curves and surfaces as truck's NURBS geometry, weights kept (homogeneous -//! control points carried over as they are). - -use solidcraft_geom::bspline::{HPoint, NurbsSurface}; -use truck_modeling as mt; - -use crate::body::p3; -use crate::{KernelError, Result}; - -fn fail(m: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("spline geometry: {m}")) -} - -/// A homogeneous control point as truck's. -pub(crate) fn h4(h: HPoint) -> mt::Vector4 { - mt::Vector4::new(h.x, h.y, h.z, h.w) -} - -/// A NURBS curve of knots and homogeneous control points. -pub(crate) fn nurbs_curve(knots: mt::KnotVec, ctrl: &[HPoint]) -> Result { - let c = mt::BSplineCurve::try_new(knots, ctrl.iter().copied().map(h4).collect()).map_err(fail)?; - Ok(mt::Curve::NurbsCurve(mt::NurbsCurve::new(c))) -} - -/// A NURBS surface of knots and homogeneous control points (`rows[i][j]`: i along u). -pub(crate) fn nurbs_surface(knots: (mt::KnotVec, mt::KnotVec), rows: Vec>) -> Result { - let s = mt::BSplineSurface::try_new(knots, rows).map_err(fail)?; - Ok(mt::Surface::NurbsSurface(mt::NurbsSurface::new(s))) -} - -/// geom's tensor surface as truck's. -pub(crate) fn surface(s: &NurbsSurface) -> Result { - let [nu, nv] = s.count(); - let [ku, kv] = s.knots(); - let rows: Vec> = (0..nu).map(|i| (0..nv).map(|j| h4(s.point(i, j))).collect()).collect(); - nurbs_surface((mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone())), rows) -} - -/// One face of a whole tensor surface: its four boundary curves as edges, sharing the corners. -/// This is what a patch built as a single control net (`bridge`, `boundary`, the T-spline sheet) -/// hands to the B-rep. -pub(crate) fn tensor_face(s: &NurbsSurface) -> Result { - let [nu, nv] = s.count(); - if nu < 2 || nv < 2 { - return Err(fail("a face needs at least 2 x 2 control points")); - } - let [ku, kv] = s.knots(); - let corners = [s.point(0, 0), s.point(nu - 1, 0), s.point(nu - 1, nv - 1), s.point(0, nv - 1)]; - let mut v: Vec = Vec::with_capacity(4); - for c in corners { - let p = c.project().ok_or_else(|| fail("a corner has no position"))?; - v.push(mt::builder::vertex(p3(p))); - } - let row = |j: usize| -> Vec { (0..nu).map(|i| s.point(i, j)).collect() }; - let column = |i: usize| -> Vec { (0..nv).map(|j| s.point(i, j)).collect() }; - let (Some(v0), Some(v1), Some(v2), Some(v3)) = (v.first(), v.get(1), v.get(2), v.get(3)) else { return Err(fail("corners")) }; - let edge = |a: &mt::Vertex, b: &mt::Vertex, c: mt::Curve| mt::Edge::try_new(a, b, c).map_err(fail); - let bottom = edge(v0, v1, nurbs_curve(mt::KnotVec::from(ku.clone()), &row(0))?)?; - let right = edge(v1, v2, nurbs_curve(mt::KnotVec::from(kv.clone()), &column(nu - 1))?)?; - let top = edge(v3, v2, nurbs_curve(mt::KnotVec::from(ku.clone()), &row(nv - 1))?)?; - let left = edge(v0, v3, nurbs_curve(mt::KnotVec::from(kv.clone()), &column(0))?)?; - let wire: mt::Wire = vec![bottom, right, top.inverse(), left.inverse()].into(); - mt::Face::try_new(vec![wire], surface(s)?).map_err(fail) -} diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs index b6551a534..0da42b23d 100644 --- a/crates/kernel/src/splitface.rs +++ b/crates/kernel/src/splitface.rs @@ -1,1134 +1,456 @@ -//! Split Face: divide chosen faces of a body along where a tool meets them (a plane, another -//! face's surface, or sketch curves swept along the sketch normal), leaving the solid itself -//! unchanged. Edges the split line ends on are cut in every face that uses them. +//! Split Face and Split Body: divide chosen faces of a body along where a tool meets them (a +//! plane, another face's surface, or sketch curves swept along a direction), leaving the solid +//! unchanged, or cut a body in two along the tool. Edges the split line ends on are cut in every +//! face that uses them. //! -//! The tool is a signed field (which side of the tool a point is on). Its zero set on a face is -//! traced on the face's triangulation, every crossing is placed exactly on the surface by -//! bisection in the face's parameters, and the line ends exactly on the boundary edges. +//! A tool is a set of exact surface patches: schema 4 record surfaces, each over a parameter box, +//! unbounded where the tool is (a plane, a face's surface extended). A plane is one patch, so is a +//! face's surface; a sketch curve is one patch per segment swept along the direction (a line a +//! plane strip, an arc swept square to its sketch a cylinder strip, any other segment its exact +//! rational Bézier extruded), an open curve's ends continued by lines past the body. SMLib cuts +//! the faces where the patches meet them ([`solidcraft_smlib::Brep::split_faces`]), its own +//! intersection curves trimmed to each face, and slices a body with one patch +//! ([`solidcraft_smlib::Brep::split_body`]); the history is SMLib's own. +//! +//! Which side of a tool a point is on is its offset along the normal of the nearest patch +//! ([`ToolSide`]): each patch's surface is prepared once (its projection grid kept), never per +//! point. Every patch's normal points to the tool's positive side: a plane's normal, a face's +//! outward side, the left of a sketch curve (inside a closed one, counter-clockwise). -use std::collections::HashMap; +use solidcraft_geom::prelude::*; +use std::f64::consts::TAU; -use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::{Plane, Seg2, UnitVec3, Vec2, Vec3}; -use truck_meshalgo::tessellation::RobustMeshableShape; -use truck_modeling as mt; +use solidcore_record::brep::{self, Frame, Surface}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::Aabb3; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; +use solidcraft_geom::tess::uv::Starts; -use crate::body::{Body, from_p3, p3}; -use crate::record::Rebuild; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::history::{EdgeOrigin, FaceOrigin, History}; +use crate::{KernelError, Result, guard, record}; /// What splits the faces. #[derive(Clone, Debug)] pub enum SplitTool<'a> { /// A plane (unbounded). Plane(Plane), - /// The surface of another body's face (`face` in that body's face order), extended. + /// The surface of another body's face (`face` in that body's face order), extended. Split + /// Body by a face of a surface body joined tangentially to others cuts with their smooth + /// sheet as it is ([`split_body`]). Face { body: &'a Body, face: usize }, /// Sketch curves (chains of segments in `plane`) swept along `along` (none: the plane's - /// normal); each curve splits on its own, an open one extended past its ends. A single line - /// splits exactly (a plane), and so does a single arc swept along the normal (a cylinder); - /// longer chains, splines and arcs swept aslant follow the curve. + /// normal); each curve splits on its own, an open one extended past its ends. Curves { plane: Plane, curves: Vec>, along: Option }, } -/// Which side of the tool a point is on (zero on the tool). -enum Field { - Plane { - o: Vec3, - n: Vec3, - }, - Surface(mt::Surface), - /// A circular cylinder (radius `r` about the line through `o` along unit `axis`); `out` is - /// +1 when the tool's normal points away from the axis. - Cylinder { - o: Vec3, - axis: UnitVec3, - r: f64, - out: f64, - }, - /// A chain of points in `plane`, swept along `along` (the plane's normal when none). A - /// closed chain is positive inside it; an open one on its left, its end segments extended. - Curve { - plane: Plane, - pts: Vec, - closed: bool, - along: Option, - }, +/// Most segments a sketch tool may hold. +const MAX_SEGMENTS: usize = 4096; + +fn invalid(what: impl Into) -> KernelError { + KernelError::Invalid(what.into()) } -impl Field { - fn eval(&self, p: Vec3) -> f64 { - match self { - Field::Plane { o, n } => (p - *o).dot(*n), - Field::Surface(s) => match s.search_nearest_parameter(p3(p), None, 50) { - Some((u, v)) => { - let q = from_p3(s.subs(u, v)); - let n = s.normal(u, v); - (p - q).dot(Vec3::new(n.x, n.y, n.z)) - } - None => f64::NAN, - }, - Field::Cylinder { o, axis, r, out } => { - let v = p - *o; - let radial = v - *axis * v.dot(*axis); - *out * (radial.len() - *r) - } - Field::Curve { plane, pts, closed, along } => { - // Where p's line along the sweep direction meets the plane. - let p = match along { - Some(d) => p - *d * ((p - plane.origin).dot(plane.normal()) / d.dot(plane.normal())), - None => p, - }; - let q = plane.to_local(p); - let q = Vec2::new(q.x, q.y); - if *closed { - // Distance to the loop, positive inside it. - let d = (0..pts.len().saturating_sub(1)) - .filter_map(|i| Some((*pts.get(i)?, *pts.get(i + 1)?))) - .map(|(a, b)| { - let d = b - a; - let l2 = d.dot(d); - let t = if l2 > 0.0 { ((q - a).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 }; - (q - (a + d * t)).len() - }) - .fold(f64::INFINITY, f64::min); - let uv: Vec<(f64, f64)> = pts.iter().map(|p| (p.x, p.y)).collect(); - return if inside(&uv, (q.x, q.y)) { d } else { -d }; - } - // Signed distance to the polyline, its end segments extended as lines. - let n = pts.len(); - let mut best = (f64::INFINITY, 0.0); - for i in 0..n.saturating_sub(1) { - let (Some(&a), Some(&b)) = (pts.get(i), pts.get(i + 1)) else { continue }; - let d = b - a; - let l2 = d.dot(d); - if !(l2 > 0.0) { - continue; - } - let mut t = (q - a).dot(d) / l2; - if i > 0 { - t = t.max(0.0); - } - if i + 2 < n { - t = t.min(1.0); - } - let c = a + d * t; - let dist = (q - c).len(); - if dist < best.0 { - let side = d.x * (q.y - a.y) - d.y * (q.x - a.x); - best = (dist, if side >= 0.0 { dist } else { -dist }); - } - } - best.1 - } - } - } +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {what}"), e) } -/// A crossing of the split line with a face boundary edge. -#[derive(Clone)] -struct Hit { - edge: mt::Edge, - t: f64, - p: mt::Point3, +fn a3(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] } -/// One traced split line on a face: points (exact) with their surface parameters, and whether -/// it closes on itself. -struct Chain { - pts: Vec<(mt::Point3, (f64, f64))>, - closed: bool, +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) } -/// Mesh tolerance for tracing a face. -fn trace_tol(face: &mt::Face, size: f64) -> f64 { - let _ = face; - trace_tol_of(size) +/// One piece of a tool: a record surface over `domain` (`±∞` where the tool runs on without +/// end), `flip` when the tool's positive side is against the surface's normal. +#[derive(Clone, Debug)] +struct Patch { + surface: Surface, + domain: [[f64; 2]; 2], + flip: bool, } -/// Mesh tolerance for tracing on a body of this size. -fn trace_tol_of(size: f64) -> f64 { - (size * 2e-3).max(1e-4) -} +const ALL: [f64; 2] = [f64::NEG_INFINITY, f64::INFINITY]; -/// Trace the zero set of `g` over a face: chains of exact points. -fn trace(face: &mt::Face, g: &Field, size: f64) -> Result> { - if let Some(chains) = trace_flat(face, g, size) { - return Ok(chains); +impl Patch { + fn frame(origin: Vec3, x: Vec3, y: Vec3) -> Frame { + Frame { origin: a3(origin), x_axis: a3(x), y_axis: a3(y) } } - let tol = trace_tol(face, size); - let shell: mt::Shell = vec![face.clone()].into(); - let meshed = shell.robust_triangulation(tol); - let Some(mf) = meshed.face_iter().next() else { return Ok(Vec::new()) }; - let Some(pm) = mf.surface() else { return Err(KernelError::Failed("the face could not be meshed".into())) }; - let surface = face.surface(); - let (pos, uvs) = (pm.positions(), pm.uv_coords()); - // The face's triangles subdivided in parameter space, finely enough that a small split line - // (a hole's circle on a big face) crosses some triangle sides. Corners shared between - // triangles are found by their (rounded) parameters. - let step = size / 100.0; - let mut ids: HashMap<(i64, i64), usize> = HashMap::new(); - let mut corner_uv: Vec<(f64, f64)> = Vec::new(); - let (mut umin, mut umax, mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); - for uv in uvs { - umin = umin.min(uv.x); - umax = umax.max(uv.x); - vmin = vmin.min(uv.y); - vmax = vmax.max(uv.y); - } - let qu = ((umax - umin).abs() * 1e-9).max(1e-12); - let qv = ((vmax - vmin).abs() * 1e-9).max(1e-12); - let mut corner = |uv: (f64, f64)| -> usize { - let k = ((uv.0 / qu).round() as i64, (uv.1 / qv).round() as i64); - *ids.entry(k).or_insert_with(|| { - corner_uv.push(uv); - corner_uv.len() - 1 - }) - }; - let mut base: Vec<[((f64, f64), mt::Point3); 3]> = Vec::new(); - for t in pm.faces().triangle_iter() { - let mut c = [((0.0, 0.0), mt::Point3::new(0.0, 0.0, 0.0)); 3]; - for (k, v) in t.iter().enumerate() { - let Some(uv) = v.uv.and_then(|i| uvs.get(i)) else { return Err(KernelError::Failed("mesh without parameters".into())) }; - let p = pos.get(v.pos).copied().unwrap_or(mt::Point3::new(0.0, 0.0, 0.0)); - c[k] = ((uv.x, uv.y), p); - } - base.push(c); - } - // One division for every triangle, so shared sides divide alike. - let longest = base.iter().flat_map(|c| (0..3).map(move |k| c[k].1.distance(c[(k + 1) % 3].1))).fold(0.0, f64::max); - let n = ((longest / step).ceil() as usize).clamp(1, 48); - let mut tris: Vec<[(usize, (f64, f64)); 3]> = Vec::new(); - for c in base { - let at = |i: usize, j: usize| { - let (a, b, cc) = (c[0].0, c[1].0, c[2].0); - let (s, t) = (i as f64 / n as f64, j as f64 / n as f64); - (a.0 + (b.0 - a.0) * s + (cc.0 - a.0) * t, a.1 + (b.1 - a.1) * s + (cc.1 - a.1) * t) - }; - for i in 0..n { - for j in 0..n - i { - let (p0, p1, p2) = (at(i, j), at(i + 1, j), at(i, j + 1)); - tris.push([(corner(p0), p0), (corner(p1), p1), (corner(p2), p2)]); - if i + j + 1 < n { - let p3 = at(i + 1, j + 1); - tris.push([(corner(p1), p1), (corner(p3), p3), (corner(p2), p2)]); - } - } - } - if tris.len() > 4_000_000 { - return Err(KernelError::Failed("the face is too finely divided to trace".into())); - } - } - let gv: Vec = corner_uv.iter().map(|uv| g.eval(from_p3(surface.subs(uv.0, uv.1)))).collect(); - if gv.iter().any(|x| !x.is_finite()) { - return Err(KernelError::Failed("the splitting tool cannot be evaluated on the face".into())); - } - let side = |i: usize| gv.get(i).copied().unwrap_or(0.0) >= 0.0; - // Mesh edges crossed by the zero set, and which triangles link them. - let key = |a: usize, b: usize| (a.min(b), a.max(b)); - let mut node_uv: HashMap<(usize, usize), ((f64, f64), (f64, f64))> = HashMap::new(); - let mut links: HashMap<(usize, usize), Vec<(usize, usize)>> = HashMap::new(); - let mut edge_tris: HashMap<(usize, usize), usize> = HashMap::new(); - for t in &tris { - for k in 0..3 { - let (a, b) = (t[k], t[(k + 1) % 3]); - *edge_tris.entry(key(a.0, b.0)).or_default() += 1; - } - let crossed: Vec<(usize, usize)> = (0..3) - .filter_map(|k| { - let (a, b) = (t[k], t[(k + 1) % 3]); - (side(a.0) != side(b.0)).then(|| { - let kk = key(a.0, b.0); - let (ua, ub) = if a.0 < b.0 { (a.1, b.1) } else { (b.1, a.1) }; - node_uv.entry(kk).or_insert((ua, ub)); - kk - }) + + /// The patch with every unbounded range closed where it has passed all of `reach`: the + /// span of the box's corners in that parameter, which the surface is straight along (a + /// plane's two, a cylinder's or a cone's height). + fn bounded(&self, reach: &Aabb3) -> Result { + let corners: Vec = (0..8) + .map(|k| { + let pick = |bit: usize, lo: f64, hi: f64| if k & bit == 0 { lo } else { hi }; + Vec3::new(pick(1, reach.min.x, reach.max.x), pick(2, reach.min.y, reach.max.y), pick(4, reach.min.z, reach.max.z)) }) .collect(); - if let [x, y] = crossed[..] { - links.entry(x).or_default().push(y); - links.entry(y).or_default().push(x); - } - } - // Exact point on a crossed mesh edge: bisection along its parameter segment. - let exact = |k: (usize, usize)| -> Option<(mt::Point3, (f64, f64))> { - let (ua, ub) = *node_uv.get(&k)?; - let f = |s: f64| { - let uv = (ua.0 + (ub.0 - ua.0) * s, ua.1 + (ub.1 - ua.1) * s); - (g.eval(from_p3(surface.subs(uv.0, uv.1))), uv) - }; - let (mut lo, mut hi) = (0.0, 1.0); - let s0 = f(0.0).0 >= 0.0; - for _ in 0..48 { - let mid = 0.5 * (lo + hi); - if (f(mid).0 >= 0.0) == s0 { - lo = mid; - } else { - hi = mid; - } - } - let (val, uv) = f(0.5 * (lo + hi)); - // A side whose ends were on the same side after all (a corner exactly on the tool). - if !(val.abs() <= size * 1e-7) { - return None; - } - Some((surface.subs(uv.0, uv.1), uv)) - }; - // Walk the links into chains. - let mut seen: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new(); - let mut chains = Vec::new(); - let mut nodes: Vec<(usize, usize)> = links.keys().copied().collect(); - nodes.sort(); - // Open chains start at mesh boundary edges (one triangle). - nodes.sort_by_key(|k| edge_tris.get(k).copied().unwrap_or(0) != 1); - for start in nodes { - if seen.contains(&start) { - continue; - } - let mut path = vec![start]; - seen.insert(start); - let mut cur = start; - let closed; - loop { - let next = links.get(&cur).into_iter().flatten().find(|n| !seen.contains(*n)).copied(); - match next { - Some(n) => { - seen.insert(n); - path.push(n); - cur = n; + // The parameters of a corner along the surface's straight directions. + let params = |c: Vec3| -> Option<[f64; 2]> { + match &self.surface { + Surface::Plane { origin, u_axis, v_axis } => { + let (du, dv, r) = (v3(*u_axis), v3(*v_axis), c - v3(*origin)); + let (a, b, d) = (du.dot(du), du.dot(dv), dv.dot(dv)); + let det = a * d - b * b; + (det.abs() > 0.0).then(|| [(d * du.dot(r) - b * dv.dot(r)) / det, (a * dv.dot(r) - b * du.dot(r)) / det]) } - None => { - closed = path.len() > 2 && links.get(&cur).is_some_and(|l| l.contains(&start)); - break; + Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } => { + let z = v3(frame.x_axis).cross(v3(frame.y_axis)); + Some([0.0, (c - v3(frame.origin)).dot(z)]) } + _ => None, } - if path.len() > 1_000_000 { - return Err(KernelError::Failed("split line too long".into())); - } - } - // Points about a step apart (the ends kept). - let all: Vec<_> = path.iter().filter_map(|k| exact(*k)).collect(); - let mut pts: Vec<(mt::Point3, (f64, f64))> = Vec::new(); - for (i, p) in all.iter().enumerate() { - let keep = i == 0 || i + 1 == all.len() || pts.last().is_none_or(|l| l.0.distance(p.0) >= step * 0.5); - if keep { - pts.push(*p); - } - } - if pts.len() >= 2 { - chains.push(Chain { pts, closed }); - } - } - Ok(chains) -} - -/// A plane across a flat face (a plane, or a B-spline surface that is one) with straight edges, -/// exactly: the line the two planes meet in, inside the face between pairs of its crossings with -/// the boundary, taken in order along the line. Which side a corner is on is decided once, at -/// the corner, so a plane through a corner crosses the boundary there once or not at all, as it -/// should. `None` (traced on a mesh instead) for any other face or tool, and where an edge lies -/// in the plane. -fn trace_flat(face: &mt::Face, g: &Field, size: f64) -> Option> { - let Field::Plane { o, n } = g else { return None }; - let surface = face.surface(); - let Field::Plane { n: m, .. } = surface_field(&surface) else { return None }; - let along = m.cross(*n).normalized()?; - let tol = size * 1e-7 + 1e-9; - let mut hits: Vec = Vec::new(); - for e in face.boundaries().iter().flat_map(|w| w.edge_iter()) { - let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point())); - let (ga, gb) = ((a - *o).dot(*n), (b - *o).dot(*n)); - // Straight: a line, or a curve (a B-spline of degree one) whose points all lie on its - // chord; such an edge crosses the plane once at most. - let straight = matches!(e.curve(), mt::Curve::Line(_)) || { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (1..8).all(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 8.0)).dist_to_segment(a, b) <= tol) }; - if !straight || (ga.abs() <= tol && gb.abs() <= tol) || !ga.is_finite() || !gb.is_finite() { - return None; - } - if (ga >= 0.0) != (gb >= 0.0) { - hits.push(p3(a + (b - a) * (ga / (ga - gb)).clamp(0.0, 1.0))); - } - } - if !hits.len().is_multiple_of(2) { - return None; - } - hits.sort_by(|a, b| from_p3(*a).dot(along).total_cmp(&from_p3(*b).dot(along))); - let uv = |p: mt::Point3| surface.search_nearest_parameter(p, None, 50); - let mut chains = Vec::new(); - for pair in hits.chunks(2) { - let [a, b] = pair else { return None }; - // A corner the plane only touches: no line. - if a.distance(*b) <= tol { - continue; - } - chains.push(Chain { pts: vec![(*a, uv(*a)?), (*b, uv(*b)?)], closed: false }); - } - Some(chains) -} - -/// Where the zero set crosses a boundary edge of the face (exact, by bisection on the curve). -fn boundary_hits(face: &mt::Face, g: &Field) -> Vec { - let mut out = Vec::new(); - for w in face.absolute_boundaries() { - for e in w.edge_iter() { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let n = 64; - let val = |t: f64| g.eval(from_p3(c.subs(t))); - let mut prev = (t0, val(t0)); - for k in 1..=n { - let t = t0 + (t1 - t0) * k as f64 / n as f64; - let cur = (t, val(t)); - if (prev.1 >= 0.0) != (cur.1 >= 0.0) { - let (mut lo, mut hi) = (prev.0, cur.0); - let s0 = prev.1 >= 0.0; - for _ in 0..60 { - let mid = 0.5 * (lo + hi); - if (val(mid) >= 0.0) == s0 { - lo = mid; - } else { - hi = mid; - } - } - let t = 0.5 * (lo + hi); - out.push(Hit { edge: e.clone(), t, p: c.subs(t) }); - } - prev = cur; - } - } - } - out -} - -/// The exact boundary crossings each open chain runs between (`None` for closed chains and -/// for chains whose ends have no crossing of their own). -/// -/// A chain ends where the zero set crosses the boundary of the face's mesh, whose sides are -/// chords up to `mesh_tol` inside a curved boundary: the true crossing lies further along the -/// zero set, by the chord's sag over the sine of the angle the two meet at. A fixed snap -/// distance below the sag drops splits depending on where the mesh's vertices fall (a wall -/// crossing a disc's rim 0.06 mm past the last chord on a 50 mm part). Ends are matched within -/// a few sags (crossings at 15° or steeper), one crossing to one end, nearest pairs first, so -/// a wider reach never lets two ends share a crossing. -fn chain_ends(chains: &[Chain], hits: &[Hit], mesh_tol: f64) -> Vec> { - let reach = 4.0 * mesh_tol; - // (distance, end slot: chain * 2 + 0 for the first point, 1 for the last; hit index) - let mut pairs: Vec<(f64, usize, usize)> = Vec::new(); - for (c, ch) in chains.iter().enumerate() { - if ch.closed { - continue; - } - for (k, end) in [ch.pts.first(), ch.pts.last()].into_iter().enumerate() { - let Some(&(p, _)) = end else { continue }; - for (h, hit) in hits.iter().enumerate() { - let d = hit.p.distance(p); - if d <= reach { - pairs.push((d, c * 2 + k, h)); - } - } - } - } - pairs.sort_by(|x, y| x.0.total_cmp(&y.0)); - let mut slot: Vec> = vec![None; chains.len() * 2]; - let mut taken = vec![false; hits.len()]; - for (_, end, h) in pairs { - if slot.get(end).is_some_and(Option::is_none) && taken.get(h).is_some_and(|t| !*t) { - if let Some(s) = slot.get_mut(end) { - *s = Some(h); - } - if let Some(t) = taken.get_mut(h) { - *t = true; - } - } - } - (0..chains.len()) - .map(|c| match (slot.get(c * 2).copied().flatten(), slot.get(c * 2 + 1).copied().flatten()) { - (Some(a), Some(b)) => Some((hits.get(a)?.clone(), hits.get(b)?.clone())), - _ => None, - }) - .collect() -} - -/// A curve through points: a line when they are collinear, else a cubic through every point -/// (Catmull-Rom tangents; `closed` when the last point repeats the first). -pub(crate) fn fit(pts: &[mt::Point3], scale: f64) -> Result { - let (Some(a), Some(b)) = (pts.first(), pts.last()) else { return Err(KernelError::Failed("empty split line".into())) }; - let d = b - a; - let len = d.magnitude(); - let straight = len > 0.0 && pts.iter().all(|p| (p - a).cross(d).magnitude() / len <= scale * 1e-9); - if straight { - return Ok(mt::Curve::Line(mt::Line(*a, *b))); - } - let m = pts.len().saturating_sub(1); - if m < 1 { - return Err(KernelError::Failed("split line too short".into())); - } - let closed = a.distance(*b) <= scale * 1e-9 && m >= 3; - let at = |i: isize| -> mt::Point3 { - let i = if closed { i.rem_euclid(m as isize) as usize } else { i.clamp(0, m as isize) as usize }; - pts.get(i).copied().unwrap_or(*a) - }; - let mut ctrl = vec![*a]; - let mut knots = vec![0.0; 4]; - for i in 0..m as isize { - let (p0, p1) = (at(i), at(i + 1)); - let t0 = (at(i + 1) - at(i - 1)) / 6.0; - let t1 = (at(i + 2) - at(i)) / 6.0; - ctrl.extend([p0 + t0, p1 - t1, p1]); - let k = (i + 1) as f64; - knots.extend(if i + 1 == m as isize { [k; 4].to_vec() } else { [k; 3].to_vec() }); - } - let bsp = mt::BSplineCurve::try_new(mt::KnotVec::from(knots), ctrl).map_err(|e| KernelError::Failed(format!("split line: {e}")))?; - Ok(mt::Curve::BSplineCurve(bsp)) -} - -/// The curve of a split line: an exact circular arc when a cylinder meets a plane square to its -/// axis (a sketch arc splitting a planar face), else [`fit`]. -fn fit_on(g: &Field, face: &mt::Face, pts: &[mt::Point3], scale: f64) -> Result { - if let (Field::Cylinder { axis, .. }, mt::Surface::Plane(pl)) = (g, face.surface()) - && let (Some(a), Some(b), Some(m)) = (pts.first(), pts.last(), pts.get(pts.len() / 2)) - && a.distance(*b) > scale * 1e-9 - { - let n = pl.normal(); - if n.cross(crate::body::v3(axis.vec())).magnitude() < 1e-9 { - let (va, vb) = (mt::Vertex::new(*a), mt::Vertex::new(*b)); - let e = guard("split arc", || Ok(mt::builder::circle_arc(&va, &vb, *m)))?; - return Ok(e.curve()); - } - } - fit(pts, scale) -} - -/// Cut an edge at a parameter (none when the point is already a vertex): the vertex and the -/// pieces in the edge's absolute direction. -fn cut_edge(e: &mt::Edge, t: f64, p: mt::Point3, tol: f64) -> Result<(mt::Vertex, Option<(mt::Edge, mt::Edge)>)> { - let abs = if e.orientation() { e.clone() } else { e.inverse() }; - if abs.front().point().distance2(p) <= tol * tol { - return Ok((abs.front().clone(), None)); - } - if abs.back().point().distance2(p) <= tol * tol { - return Ok((abs.back().clone(), None)); - } - let v = mt::Vertex::new(p); - // `t` is on the edge as it was: when an earlier crossing already cut it (a split line - // crossing it twice), the parameter is found again on the piece. - let cut = abs.cut_with_parameter(&v, t).or_else(|| { - use mt::SearchNearestParameter; - let t = abs.curve().search_nearest_parameter(p, None, 100)?; - abs.cut_with_parameter(&v, t) - }); - let (a, b) = cut.ok_or_else(|| KernelError::Failed("cannot cut an edge at the split line".into()))?; - Ok((v, Some((a, b)))) -} - -/// Replace cut edges (absolute edge → its two pieces) in a face's loops. -fn recut(face: &mt::Face, cuts: &[(mt::Edge, (mt::Edge, mt::Edge))]) -> mt::Face { - let touches = face.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).any(|e| cuts.iter().any(|(c, _)| c.id() == e.id())); - if !touches { - return face.clone(); - } - let wires: Vec = face - .absolute_boundaries() - .iter() - .map(|w| { - let mut out: Vec = Vec::new(); - for e in w.edge_iter() { - expand(e, cuts, &mut out, 0); - } - out.into() - }) - .collect(); - let mut f = mt::Face::new_unchecked(wires, face.surface()); - if !face.orientation() { - f.invert(); - } - f -} - -/// `e` as the pieces it was cut into, in its direction; a piece cut again (a line crossing an -/// edge twice) as its own pieces. -fn expand(e: &mt::Edge, cuts: &[(mt::Edge, (mt::Edge, mt::Edge))], out: &mut Vec, depth: usize) { - match cuts.iter().find(|(c, _)| c.id() == e.id()).filter(|_| depth < 64) { - Some((c, (a, b))) if c.orientation() == e.orientation() => { - expand(a, cuts, out, depth + 1); - expand(b, cuts, out, depth + 1); - } - Some((_, (a, b))) => { - expand(&b.inverse(), cuts, out, depth + 1); - expand(&a.inverse(), cuts, out, depth + 1); - } - None => out.push(e.clone()), - } -} - -/// The parameter of the point of `c` nearest `q`, searched from the nearest of points along it (a -/// long arc's search from its middle can settle on the far side). -fn nearest(c: &mt::Curve, q: mt::Point3) -> Option { - let (t0, t1) = c.range_tuple(); - let hint = (0..=16).map(|k| t0 + (t1 - t0) * k as f64 / 16.0).min_by(|x, y| c.subs(*x).distance2(q).total_cmp(&c.subs(*y).distance2(q))); - c.search_nearest_parameter(q, hint, 100) -} - -/// `body` with its edges cut at the given points where they pass through them (not at their -/// ends): the faces either side keep the same region, bounded by the pieces. Used to give two -/// faces that cover the same region the same vertices before they are glued (#674). -pub(crate) fn split_edges_at(body: &Body, points: &[Vec3]) -> Result { - let size = body.size(); - let tol = size * 1e-7 + 1e-9; - guard("split edges", || { - let mut cuts: Vec<(mt::Edge, (mt::Edge, mt::Edge))> = Vec::new(); - let mut rec = Rebuild::default(); - // Each current piece and the body edge it is a piece of. - let mut current: Vec<(mt::Edge, mt::Edge)> = body - .solid - .edge_iter() - .map(|e| { - let abs = if e.orientation() { e.clone() } else { e.inverse() }; - (abs.clone(), abs) - }) - .collect(); - for p in points { - let q = p3(*p); - let hit = current.iter().position(|(e, _)| { - if e.front().point().distance(q) <= tol * 10.0 || e.back().point().distance(q) <= tol * 10.0 { - return false; - } - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - nearest(&c, q).is_some_and(|t| t > t0.min(t1) && t < t0.max(t1) && c.subs(t).distance(q) <= tol * 10.0) - }); - let Some(k) = hit else { continue }; - let (e, root) = current.swap_remove(k); - let Some(t) = nearest(&e.curve(), q) else { continue }; - let (_, cut) = cut_edge(&e, t, q, tol)?; - if let Some((a, b)) = cut { - rec.piece(&a, &root); - rec.piece(&b, &root); - current.push((a.clone(), root.clone())); - current.push((b.clone(), root.clone())); - cuts.push((e, (a, b))); - } else { - current.push((e, root)); - } - } - if cuts.is_empty() { - return Ok(body.clone()); - } - let shells: Vec = body - .solid - .boundaries() - .iter() - .map(|sh| { - sh.face_iter() - .map(|f| { - let nf = recut(f, &cuts); - rec.whole(&nf, f); - nf - }) - .collect::>() - .into() - }) - .collect(); - let solid = mt::Solid::new_unchecked(shells); - let split = Body { - solid: std::sync::Arc::new(solid), - size: 0.0, - boundary_tol: body.boundary_tol, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: None, - mesh: None, - color: body.color, - paint: None, - splits: body.splits.clone(), - face_sources: None, - history: None, - display_of: None, - meshes: None, - phased: false, - regularization_protected: true, - }; - Ok(crate::record::rebuilt_body(split, &[&body.solid], &rec)) - }) -} - -/// A face rebuilt from loops (absolute) on the same surface and orientation as `like`. -fn face_like(like: &mt::Face, wires: Vec) -> mt::Face { - let mut f = mt::Face::new_unchecked(wires, like.surface()); - if !like.orientation() { - f.invert(); - } - f -} - -/// Polygon of a loop in the surface's parameters (for inside tests). -fn loop_uv(s: &mt::Surface, w: &mt::Wire) -> Vec<(f64, f64)> { - let mut out = Vec::new(); - let mut hint = None; - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..8 { - let p = c.subs(t0 + (t1 - t0) * k as f64 / 8.0); - if let Some(uv) = s.search_nearest_parameter(p, hint, 50) { - hint = Some(uv); - out.push(uv); - } - } - } - out -} - -fn inside(poly: &[(f64, f64)], q: (f64, f64)) -> bool { - let mut c = false; - let n = poly.len(); - for i in 0..n { - let (Some(a), Some(b)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - if (a.1 > q.1) != (b.1 > q.1) && q.0 < a.0 + (b.0 - a.0) * (q.1 - a.1) / (b.1 - a.1) { - c = !c; - } - } - c -} - -/// Split one face (index `fi` in `faces`) by one field; `faces` is updated (the face replaced -/// by its pieces, boundary edges cut in every face). -/// Returns how many lines split it and how many faces now stand in its place (at `fi`). The -/// pieces of cut edges are recorded in `rec`. -fn split_one(faces: &mut Vec, fi: usize, g: &Field, size: f64, new_edges: &mut Vec, rec: &mut Rebuild) -> Result<(usize, usize)> { - let Some(face) = faces.get(fi).cloned() else { return Ok((0, 1)) }; - let chains = trace(&face, g, size)?; - if chains.is_empty() { - return Ok((0, 1)); - } - let tol = size * 1e-7 + 1e-9; - let hits = boundary_hits(&face, g); - let ends = chain_ends(&chains, &hits, trace_tol(&face, size)); - // Pieces of the original face as they are split. - let mut pieces: Vec = vec![face.clone()]; - let mut all_cuts: Vec<(mt::Edge, (mt::Edge, mt::Edge))> = Vec::new(); - let mut made = 0; - for (ch, end) in chains.into_iter().zip(ends) { - if ch.closed { - // A closed line inside the face: a new face inside it and a hole in the piece that holds it. - let mut pts: Vec = ch.pts.iter().map(|x| x.0).collect(); - if let Some(first) = pts.first().copied() { - pts.push(first); - } - let curve = fit(&pts, size)?; - let Some(&(p0, uv0)) = ch.pts.first() else { continue }; - let v = mt::Vertex::new(p0); - let e = mt::Edge::new_unchecked(&v, &v, curve); - new_edges.push(e.clone()); - let uv: Vec<(f64, f64)> = ch.pts.iter().map(|x| x.1).collect(); - let area: f64 = (0..uv.len()) - .map(|i| { - let (a, b) = (uv[i], uv[(i + 1) % uv.len()]); - a.0 * b.1 - b.0 * a.1 - }) - .sum(); - let s = face.surface(); - let Some(pi) = pieces.iter().position(|f| { - let ws = f.absolute_boundaries(); - ws.first().is_some_and(|o| inside(&loop_uv(&s, o), uv0)) && !ws.iter().skip(1).any(|h| inside(&loop_uv(&s, h), uv0)) - }) else { - continue; - }; - let Some(host) = pieces.get(pi).cloned() else { continue }; - // The new loop counter-clockwise in parameters (an outer loop); its reverse a hole. - let ccw: mt::Wire = if area > 0.0 { vec![e.clone()].into() } else { vec![e.inverse()].into() }; - let hole: mt::Wire = ccw.inverse(); - let ws = host.absolute_boundaries().clone(); - let mut outer_ws = vec![]; - let mut inner_ws = vec![ccw.clone()]; - for (k, w) in ws.iter().enumerate() { - let q = loop_uv(&s, w).first().copied(); - if k > 0 && q.is_some_and(|q| inside(&uv, q)) { - inner_ws.push(w.clone()); - } else { - outer_ws.push(w.clone()); - } - } - outer_ws.push(hole); - let a = face_like(&host, outer_ws); - let b = face_like(&host, inner_ws); - pieces.splice(pi..=pi, [a, b]); - made += 1; - continue; - } - // An open line: it must end on the boundary at two crossings. - let Some((ha, hb)) = end else { continue }; - // Cut the boundary edges (an edge may already have been cut by an earlier line). - let vert = |h: &Hit, cuts: &mut Vec<(mt::Edge, (mt::Edge, mt::Edge))>| -> Result { - // The current edge holding the hit: the original, or a piece of it. - let mut e = h.edge.clone(); - for (c, (x, y)) in cuts.iter() { - if c.id() == e.id() || c.id() == e.inverse().id() { - // The piece the hit lies on (a cut line's pieces are parametrised afresh, - // so by where the point is, not by the original parameter). - let off = |pc: &mt::Edge| { - use mt::SearchNearestParameter; - let cc = pc.curve(); - let (t0, t1) = cc.range_tuple(); - let t = cc.search_nearest_parameter(h.p, None, 100).unwrap_or(h.t).clamp(t0.min(t1), t0.max(t1)); - cc.subs(t).distance(h.p) - }; - e = if off(x) <= off(y) { x.clone() } else { y.clone() }; - } - } - let (v, cut) = cut_edge(&e, h.t, h.p, tol)?; - if let Some(pair) = cut { - let abs = if e.orientation() { e.clone() } else { e.inverse() }; - cuts.push((abs, pair)); - } - Ok(v) - }; - let va = vert(&ha, &mut all_cuts)?; - let vb = vert(&hb, &mut all_cuts)?; - if va.id() == vb.id() { - continue; - } - pieces = pieces.iter().map(|f| recut(f, &all_cuts)).collect(); - let mut pts: Vec = ch.pts.iter().map(|x| x.0).collect(); - if let Some(f) = pts.first_mut() { - *f = va.point(); - } - if let Some(l) = pts.last_mut() { - *l = vb.point(); - } - // A line from one loop of a piece to another (into a hole): the two loops become one, - // joined by the line run both ways; a later line divides it. - let in_loop = |w: &mt::Wire, v: &mt::Vertex| w.edge_iter().any(|e| e.front().id() == v.id()); - if let Some(pi) = pieces.iter().position(|f| { - let ws = f.absolute_boundaries(); - ws.iter().any(|w| in_loop(w, &va)) && ws.iter().any(|w| in_loop(w, &vb)) && !ws.iter().any(|w| in_loop(w, &va) && in_loop(w, &vb)) - }) && let Some(host) = pieces.get(pi).cloned() - { - let ws = host.absolute_boundaries().clone(); - let (Some(wa_i), Some(wb_i)) = (ws.iter().position(|w| in_loop(w, &va)), ws.iter().position(|w| in_loop(w, &vb))) else { continue }; - let from = |w: &mt::Wire, v: &mt::Vertex| -> Vec { - let edges: Vec = w.edge_iter().cloned().collect(); - let k = edges.iter().position(|e| e.front().id() == v.id()).unwrap_or(0); - edges.iter().skip(k).chain(edges.iter().take(k)).cloned().collect() - }; - let (Some(w1), Some(w2)) = (ws.get(wa_i), ws.get(wb_i)) else { continue }; - let slit = mt::Edge::new_unchecked(&va, &vb, fit_on(g, &face, &pts, size)?); - new_edges.push(slit.clone()); - let mut joined = from(w1, &va); - joined.push(slit.clone()); - joined.extend(from(w2, &vb)); - joined.push(slit.inverse()); - // The outer loop first. - let others = ws.iter().enumerate().filter(|(k, _)| *k != wa_i && *k != wb_i).map(|(_, w)| w.clone()); - let joined: mt::Wire = joined.into(); - let loops: Vec = if wa_i == 0 || wb_i == 0 { - std::iter::once(joined).chain(others).collect() - } else { - others.chain(std::iter::once(joined)).collect() - }; - pieces.splice(pi..=pi, [face_like(&host, loops)]); - continue; - } - // The piece whose loop passes both vertices. - let Some(pi) = pieces.iter().position(|f| { - f.absolute_boundaries().iter().any(|w| { - let ids: Vec<_> = w.edge_iter().map(|e| e.front().id()).collect(); - ids.contains(&va.id()) && ids.contains(&vb.id()) - }) - }) else { - continue; - }; - let Some(host) = pieces.get(pi).cloned() else { continue }; - let ws = host.absolute_boundaries().clone(); - let Some(wi) = ws.iter().position(|w| { - let ids: Vec<_> = w.edge_iter().map(|e| e.front().id()).collect(); - ids.contains(&va.id()) && ids.contains(&vb.id()) - }) else { - continue; - }; - let Some(w) = ws.get(wi) else { continue }; - let edges: Vec = w.edge_iter().cloned().collect(); - let n = edges.len(); - let (Some(ia), Some(ib)) = (edges.iter().position(|e| e.front().id() == va.id()), edges.iter().position(|e| e.front().id() == vb.id())) - else { - continue; - }; - let split = mt::Edge::new_unchecked(&va, &vb, fit_on(g, &face, &pts, size)?); - new_edges.push(split.clone()); - let run = |from: usize, to: usize| -> Vec { - let mut out = Vec::new(); - let mut i = from; - while i != to { - if let Some(e) = edges.get(i) { - out.push(e.clone()); - } - i = (i + 1) % n; - } - out - }; - // Piece A: a → b along the loop, back along the split. Piece B: b → a, then the split. - let mut wa = run(ia, ib); - wa.push(split.inverse()); - let mut wb = run(ib, ia); - wb.push(split.clone()); - let (wa, wb): (mt::Wire, mt::Wire) = (wa.into(), wb.into()); - if !wa.is_closed() || !wb.is_closed() { - return Err(KernelError::Failed("split loops do not close".into())); - } - // Other loops go to the piece on their side. - let s = face.surface(); - let (pa_poly, pb_poly) = (loop_uv(&s, &wa), loop_uv(&s, &wb)); - let (mut la, mut lb) = (vec![wa], vec![wb]); - for (k, other) in ws.iter().enumerate() { - if k == wi { + let mut domain = self.domain; + for (k, range) in domain.iter_mut().enumerate() { + if range.iter().all(|x| x.is_finite()) { continue; } - let q = loop_uv(&s, other).first().copied(); - match q { - Some(q) if inside(&pa_poly, q) => la.push(other.clone()), - Some(q) if inside(&pb_poly, q) => lb.push(other.clone()), - _ => return Err(KernelError::Failed("a hole meets the split line".into())), + let along: Option> = corners.iter().map(|c| params(*c).map(|p| p[k])).collect(); + let along = along.ok_or_else(|| invalid("not supported yet: a split tool unbounded on this surface"))?; + let (lo, hi) = along.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + let pad = (hi - lo) * 0.05 + 1.0; + *range = [range[0].max(lo - pad), range[1].min(hi + pad)]; + if !(range[0] < range[1]) { + // The tool ends before the body: an empty patch, which cuts nothing. + *range = [range[0], range[0]]; } } - let (a, b) = (face_like(&host, la), face_like(&host, lb)); - pieces.splice(pi..=pi, [a, b]); - made += 1; + Ok(Patch { domain, ..self.clone() }) } - if made == 0 { - return Ok((0, 1)); - } - // In the order they were cut: a piece cut again is a piece of the edge it came from. - for (c, (a, b)) in &all_cuts { - rec.piece(a, c); - rec.piece(b, c); - } - let count = pieces.len(); - // Neighbours take the cut edges. - let rest: Vec = faces.iter().enumerate().filter(|(k, _)| *k != fi).map(|(_, f)| recut(f, &all_cuts)).collect(); - let mut out = Vec::with_capacity(rest.len() + pieces.len()); - out.extend(rest.iter().take(fi).cloned()); - out.extend(pieces); - out.extend(rest.iter().skip(fi).cloned()); - *faces = out; - Ok((made, count)) } -/// The plane or circular cylinder a (B-spline) surface is, as a field with the surface's -/// normal; other surfaces as they are. -fn surface_field(s: &mt::Surface) -> Field { - let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { return Field::Surface(s.clone()) }; - if !matches!(s, mt::Surface::Plane(_) | mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_)) { - return Field::Surface(s.clone()); - } - let at = |a: f64, b: f64| from_p3(s.subs(u0 + (u1 - u0) * a, v0 + (v1 - v0) * b)); - let nrm = |a: f64, b: f64| { - let n = s.normal(u0 + (u1 - u0) * a, v0 + (v1 - v0) * b); - Vec3::new(n.x, n.y, n.z) - }; - let grid: Vec<(f64, f64)> = (0..=6).flat_map(|i| (0..=6).map(move |j| (i as f64 / 6.0, j as f64 / 6.0))).collect(); - let size = grid.iter().map(|(a, b)| at(*a, *b).dist(at(0.0, 0.0))).fold(1e-9, f64::max); - let tol = size * 1e-7; - // A plane: one normal, every point on it. - let n0 = nrm(0.5, 0.5); - let o = at(0.5, 0.5); - if grid.iter().all(|(a, b)| (at(*a, *b) - o).dot(n0).abs() <= tol) { - return Field::Plane { o, n: n0 }; - } - // A cylinder: straight along one parameter, a circle along the other. - for along_v in [true, false] { - let pt = |t: f64, w: f64| if along_v { at(t, w) } else { at(w, t) }; - let d = pt(0.0, 1.0) - pt(0.0, 0.0); - let Some(axis) = d.unit() else { continue }; - let straight = (0..=6).all(|k| { - let t = k as f64 / 6.0; - (0..=4).all(|m| (pt(t, m as f64 / 4.0) - pt(t, 0.0) - d * (m as f64 / 4.0)).len() <= tol) - }); - if !straight { - continue; - } - let prof: Vec = (0..=8).map(|k| pt(k as f64 / 8.0, 0.0)).collect(); - let (a, b, c) = (prof[0], prof[3], prof[6]); - let (ab, ac) = (b - a, c - a); - let nn = ab.cross(ac); - let n2 = nn.dot(nn); - if !(n2 > 1e-24) { - continue; - } - let centre = a + (nn.cross(ab) * ac.dot(ac) + ac.cross(nn) * ab.dot(ab)) * (0.5 / n2); - let r = (a - centre).len(); - if prof.iter().all(|p| ((*p - centre).len() - r).abs() <= tol) && nn.normalized().is_some_and(|nu| nu.cross(axis).len() < 1e-6) { - let mid = pt(0.5, 0.5); - let v = mid - centre; - let radial = v - axis * v.dot(axis); - let out = if nrm(0.5, 0.5).dot(radial) >= 0.0 { 1.0 } else { -1.0 }; - return Field::Cylinder { o: centre, axis, r, out }; - } - } - Field::Surface(s.clone()) -} - -/// A plane or circular cylinder behind a surface (for offsetting). -pub(crate) enum Analytic { - Plane { n: Vec3 }, - Cylinder { o: Vec3, axis: UnitVec3, r: f64, out: f64 }, -} - -pub(crate) fn analytic_field(s: &mt::Surface) -> Option { - match surface_field(s) { - Field::Plane { n, .. } => Some(Analytic::Plane { n }), - Field::Cylinder { o, axis, r, out } => Some(Analytic::Cylinder { o, axis, r, out }), - _ => None, - } -} - -/// Which side of a tool a point is on. -pub(crate) fn side_of_point(tool: &SplitTool, p: Vec3) -> Result { - Ok(ToolSide::of(tool)?.at(p)) -} - -/// Which side of a tool points are on, the tool's field built once for many points. -pub(crate) struct ToolSide(Field); - -impl ToolSide { - pub(crate) fn of(tool: &SplitTool) -> Result { - let mut f = fields(tool)?; - match (f.pop(), f.is_empty()) { - (Some(g), true) => Ok(ToolSide(g)), - _ => Err(KernelError::Invalid("one tool at a time".into())), - } - } - - /// The side of `p`: its sign says which, zero on the tool (NaN where it can't be told). - pub(crate) fn at(&self, p: Vec3) -> f64 { - self.0.eval(p) - } -} - -/// Which side of a tool a face lies on (its field well inside it). -pub(crate) fn face_side(face: &mt::Face, tool: &SplitTool, size: f64) -> Result { - let f = fields(tool)?; - let [g] = f.as_slice() else { return Err(KernelError::Invalid("one tool at a time".into())) }; - side_of(face, g, size) -} - -fn fields(tool: &SplitTool) -> Result> { - Ok(match tool { - SplitTool::Plane(p) => vec![Field::Plane { o: p.origin, n: p.normal() }], - SplitTool::Face { body: other, face } => { - other.require_brep("a split tool")?; - let f = other.solid.face_iter().nth(*face).ok_or_else(|| KernelError::Invalid(format!("the tool body has no face {face}")))?; - vec![surface_field(&f.oriented_surface())] +/// A box past the body (by its own size), which every unbounded patch is cut to. +fn reach_of(body: &Body) -> Aabb3 { + let b = body.outline_bounds(); + let pad = Vec3::new(1.0, 1.0, 1.0) * (b.diagonal() + 1.0); + Aabb3 { min: b.min - pad, max: b.max + pad } +} + +/// The tool as patches, one group for each field (a sketch tool: one for each curve). +fn cutters(tool: &SplitTool, reach: &Aabb3) -> Result>> { + match tool { + SplitTool::Plane(p) => { + let (x, y) = (p.x.normalized(), p.normal().cross(p.x).normalized()); + let (Some(x), Some(y)) = (x, y) else { return Err(invalid("a split plane with no normal")) }; + let surface = Surface::Plane { origin: a3(p.origin), u_axis: a3(x), v_axis: a3(y) }; + Ok(vec![vec![Patch { surface, domain: [ALL, ALL], flip: false }]]) } + SplitTool::Face { body, face } => Ok(vec![vec![face_patch(body, *face)?]]), SplitTool::Curves { plane, curves, along } => { - let n = plane.normal(); - // The sweep direction, turned to the plane's side (a direction along the plane sweeps - // nothing). - let along = match along { - None => None, - Some(d) => { - let d = d - .normalized() - .filter(|d| d.is_finite()) - .ok_or_else(|| KernelError::Invalid("the projection direction must be a nonzero vector".into()))?; - if d.dot(n).abs() < 1e-6 { - return Err(KernelError::Invalid("the projection direction runs along the sketch plane".into())); - } - let d = if d.dot(n) < 0.0 { -d } else { d }; - (d.cross(n).len() > 1e-12).then_some(d) - } - }; - let sweep = along.unwrap_or(n); - let mut out = Vec::new(); - for c in curves { - out.push(match c.as_slice() { - [Seg2::Line { a, b }] => { - let (wa, wb) = (plane.to_world(*a), plane.to_world(*b)); - let n = sweep.cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?; - Field::Plane { o: wa, n } - } - [Seg2::Arc { center, radius, .. }] if along.is_none() && radius.is_finite() && *radius > 0.0 => Field::Cylinder { - o: plane.to_world(*center), - axis: n.unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?, - r: *radius, - out: 1.0, - }, - segs => { - let mut pts: Vec = Vec::new(); - for sg in segs { - for p in sg.polyline(1e-3) { - if pts.last().is_none_or(|q| (*q - p).len() > 1e-9) { - pts.push(p); - } - } - } - if pts.len() < 2 || pts.iter().any(|p| !(p.x.is_finite() && p.y.is_finite())) || pts.len() > 1_000_000 { - return Err(KernelError::Invalid("split curves need finite segments".into())); - } - let span = pts.iter().fold(0.0f64, |m, p| m.max(p.len())); - let closed = pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| (*a - *b).len() <= span * 1e-9 + 1e-9); - Field::Curve { plane: *plane, pts, closed, along } - } - }); + let sweep = sweep_of(plane, *along)?; + if curves.iter().map(Vec::len).sum::() > MAX_SEGMENTS { + return Err(invalid("too many split curves")); } - out + curves.iter().map(|c| curve_patches(plane, c, sweep, reach)).collect() } - }) + } } -/// The body's shells with the chosen faces split by each field in turn, the new edges, and -/// how many lines split something. -/// What an imprint made: the shells' faces, for each face the body face it came from, the new -/// edges, and how many lines split each chosen face. -pub(crate) struct Imprint { - shells: Vec>, - origin: Vec, - new_edges: Vec, - made: HashMap, - /// The faces and edges made from the body's (each face over the same region as the body - /// face it came from, or a piece of it; cut edges' pieces). - rec: Rebuild, +/// The surface of face `face` of `body`, over its surface's whole parameter box (unbounded +/// where the surface is), facing out of the body. +fn face_patch(body: &Body, face: usize) -> Result { + body.require_brep("a split tool")?; + let record = body.record(); + let f = record.faces.get(face).ok_or_else(|| invalid(format!("the tool body has no face {face}")))?; + let forward = body.face_forward(face); + // The surface's own parameter box, unbounded where it is: of `surface` itself, not of its + // NURBS form (SMLib's cylinder is held on one, parameterised otherwise). + let dom = SurfaceEval::new(&f.surface).map_err(|e| invalid(format!("the split tool's surface: {e}")))?.domain(); + let range = |k: usize| dom.range[k].map_or(ALL, |(a, b)| [a, b]); + Ok(Patch { surface: f.surface.clone(), domain: [range(0), range(1)], flip: !forward }) } -fn imprint(body: &Body, faces: &[usize], fields: &[Field], size: f64) -> Result { - let mut out = Imprint { shells: Vec::new(), origin: Vec::new(), new_edges: Vec::new(), made: HashMap::new(), rec: Rebuild::default() }; - let body_faces: Vec<&mt::Face> = body.solid.face_iter().collect(); - let mut base = 0; - for sh in body.solid.boundaries() { - let mut fs: Vec = sh.face_iter().cloned().collect(); - // Which faces (by position) are to be split: the chosen ones and, later, their pieces; - // and the body face each came from. - let mut target: Vec = (0..fs.len()).map(|k| faces.contains(&(base + k))).collect(); - let mut origin: Vec = (0..fs.len()).map(|k| base + k).collect(); - base += fs.len(); - for g in fields { - let mut k = 0; - while k < fs.len() { - if !target.get(k).copied().unwrap_or(false) { - k += 1; - continue; +/// The unit sweep direction of a sketch tool, on the sketch normal's side (`None`: along the +/// normal). +fn sweep_of(plane: &Plane, along: Option) -> Result { + let n = plane.normal().normalized().ok_or_else(|| invalid("a sketch plane with no normal"))?; + let Some(d) = along else { return Ok(n) }; + let d = d.normalized().filter(|d| d.is_finite()).ok_or_else(|| invalid("the projection direction must be a nonzero vector"))?; + if d.dot(n).abs() < 1e-6 { + return Err(invalid("the projection direction runs along the sketch plane")); + } + Ok(if d.dot(n) < 0.0 { -d } else { d }) +} + +/// One sketch curve swept along `sweep`: a patch for each segment, unbounded along the sweep, +/// and an open curve's ends continued along their tangents past `reach`. Each patch's normal +/// points to the curve's left. +fn curve_patches(plane: &Plane, segs: &[Seg2], sweep: Vec3, reach: &Aabb3) -> Result> { + let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err(invalid("an empty split curve")) }; + let ok = |p: Vec2| p.x.is_finite() && p.y.is_finite(); + if !segs.iter().all(|s| ok(s.start()) && ok(s.end())) { + return Err(invalid("split curves need finite segments")); + } + let closed = (first.start() - last.end()).len() <= 1e-9 * (1.0 + first.start().len()); + let far = reach.diagonal() + (plane.origin - (reach.min + reach.max) * 0.5).len(); + let mut out = Vec::new(); + let line = |a: Vec2, b: Vec2, out: &mut Vec| -> Result<()> { + let (wa, wb) = (plane.to_world(a), plane.to_world(b)); + let d = wb - wa; + let len = d.len(); + let d = d.normalized().ok_or_else(|| invalid("a zero-length split line"))?; + // u along the sweep, v along the line: the normal sweep × line is the line's left. + let surface = Surface::Plane { origin: a3(wa), u_axis: a3(sweep), v_axis: a3(d) }; + out.push(Patch { surface, domain: [ALL, [0.0, len]], flip: false }); + Ok(()) + }; + // An open curve runs on along its end tangents: an end line lengthened, else a line added. + let mut segs = segs.to_vec(); + let (mut lead, mut tail) = (None, None); + if !closed { + let t0 = first.start_tangent().normalized().ok_or_else(|| invalid("a split curve with no tangent"))?; + let t1 = last.end_tangent().normalized().ok_or_else(|| invalid("a split curve with no tangent"))?; + let (s0, s1) = (first.start(), last.end()); + match segs.first_mut() { + Some(Seg2::Line { a, .. }) => *a = s0 - t0 * far, + _ => lead = Some((s0 - t0 * far, s0)), + } + match segs.last_mut() { + Some(Seg2::Line { b, .. }) => *b = s1 + t1 * far, + _ => tail = Some((s1, s1 + t1 * far)), + } + } + if let Some((a, b)) = lead { + line(a, b, &mut out)?; + } + let square = sweep.cross(plane.normal()).len() <= 1e-12; + for s in &segs { + match *s { + Seg2::Line { a, b } => line(a, b, &mut out)?, + Seg2::Arc { center, radius, start, sweep: turn } if square && radius.is_finite() && radius > 0.0 && turn.abs() <= TAU => { + // Angles about the sketch normal from the sketch's x; a counter-clockwise arc has + // its left inside, against the cylinder's outward normal. + let n = plane.normal().normalized().ok_or_else(|| invalid("a sketch plane with no normal"))?; + let surface = Surface::Cylinder { frame: Patch::frame(plane.to_world(center), plane.x, n.cross(plane.x)), radius }; + let (lo, hi) = if turn >= 0.0 { (start, start + turn) } else { (start + turn, start) }; + out.push(Patch { surface, domain: [[lo, hi], ALL], flip: turn > 0.0 }); + } + ref s => { + for (pts, w) in beziers(s)? { + out.push(extruded(plane, &pts, &w, sweep, reach)?); } - let src = origin.get(k).copied().unwrap_or(0); - let (m, pieces) = split_one(&mut fs, k, g, size, &mut out.new_edges, &mut out.rec)?; - *out.made.entry(src).or_default() += m; - // The pieces stand at k..k + pieces; positions after shift. - target = target.iter().take(k).copied().chain(std::iter::repeat_n(true, pieces)).chain(target.iter().skip(k + 1).copied()).collect(); - origin = origin.iter().take(k).copied().chain(std::iter::repeat_n(src, pieces)).chain(origin.iter().skip(k + 1).copied()).collect(); - k += pieces; } } - for (f, src) in fs.iter().zip(&origin) { - if let Some(from) = body_faces.get(*src) { - out.rec.whole(f, from); - } - } - out.shells.push(fs); - out.origin.extend(origin); + } + if let Some((a, b)) = tail { + line(a, b, &mut out)?; } Ok(out) } +/// A segment as rational Bézier pieces (control points and weights), exactly: an arc in pieces +/// of a quarter turn at most. +fn beziers(s: &Seg2) -> Result, Vec)>> { + Ok(match *s { + Seg2::Line { a, b } => vec![(vec![a, b], vec![1.0; 2])], + Seg2::Arc { center, radius, start, sweep } => { + if !(radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep.abs() <= TAU && sweep != 0.0) { + return Err(invalid("a split arc needs a positive radius and a turn of at most one revolution")); + } + let n = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize; + let h = sweep / (2 * n) as f64; + let at = |t: f64| center + Vec2::new(t.cos(), t.sin()) * radius; + (0..n) + .map(|i| { + let t0 = start + 2.0 * h * i as f64; + let apex = center + Vec2::new((t0 + h).cos(), (t0 + h).sin()) * (radius / h.cos()); + (vec![at(t0), apex, at(t0 + 2.0 * h)], vec![1.0, h.cos(), 1.0]) + }) + .collect() + } + Seg2::Cubic { p0, p1, p2, p3 } => vec![(vec![p0, p1, p2, p3], vec![1.0; 4])], + Seg2::Conic { a, apex, b, w } => vec![(vec![a, apex, b], vec![1.0, w, 1.0])], + Seg2::Bezier { n, p } => { + let pts = p.get(..=usize::from(n)).ok_or_else(|| invalid("Bézier degree"))?.to_vec(); + let w = vec![1.0; pts.len()]; + vec![(pts, w)] + } + }) +} + +/// A rational Bézier piece in `plane` swept along `sweep` across `reach`, exactly: a spline of +/// degree one along the sweep (u) and the piece's along the curve (v), so its normal is the +/// curve's left. +fn extruded(plane: &Plane, pts: &[Vec2], w: &[f64], sweep: Vec3, reach: &Aabb3) -> Result { + let n = plane.normal().normalized().ok_or_else(|| invalid("a sketch plane with no normal"))?; + // The sweep heights that take the sketch plane through the whole box. + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for k in 0..8 { + let pick = |bit: usize, a: f64, b: f64| if k & bit == 0 { a } else { b }; + let c = Vec3::new(pick(1, reach.min.x, reach.max.x), pick(2, reach.min.y, reach.max.y), pick(4, reach.min.z, reach.max.z)); + let h = (c - plane.origin).dot(n) / sweep.dot(n); + (lo, hi) = (lo.min(h), hi.max(h)); + } + let degree = pts.len().saturating_sub(1); + let knots = |d: usize| std::iter::repeat_n(0.0, d + 1).chain(std::iter::repeat_n(1.0, d + 1)).collect::>(); + let homogeneous: Vec> = [lo, hi] + .iter() + .map(|h| { + pts.iter() + .zip(w) + .map(|(p, wt)| { + let q = plane.to_world(*p) + sweep * *h; + [q.x * wt, q.y * wt, q.z * wt, *wt] + }) + .collect() + }) + .collect(); + let surface = Surface::RationalSpline { u_knots: knots(1), v_knots: knots(degree), homogeneous }; + Ok(Patch { surface, domain: [[0.0, 1.0], [0.0, 1.0]], flip: false }) +} + +/// One patch ready to measure points against: its surface prepared once. +struct Measured { + eval: SurfaceEval, + starts: Starts, + domain: [[f64; 2]; 2], + sign: f64, +} + +impl Measured { + fn new(p: &Patch) -> Result { + let eval = SurfaceEval::new(&p.surface).map_err(|e| invalid(format!("the split tool's surface: {e}")))?; + Ok(Measured { eval, starts: Starts::default(), domain: p.domain, sign: if p.flip { -1.0 } else { 1.0 } }) + } + + /// The nearest point of the patch to `p` (its parameters kept in the patch's box, a + /// periodic one taken round to it), and `p`'s offset along the patch's side there. + fn near(&self, p: Vec3) -> Option<(f64, f64)> { + let uv = self.eval.project_with(&self.starts, p, None, f64::INFINITY)?; + let period = self.eval.domain().period; + let mut q = [0.0; 2]; + for k in 0..2 { + let [lo, hi] = self.domain[k]; + let mut x = uv[k]; + if let Some(t) = period[k] { + x = lo + (x - lo).rem_euclid(t); + // Past the end of a strip: whichever end is nearer round the turn. + if x > hi && x - hi > lo + t - x { + x -= t; + } + } + q[k] = x.clamp(lo.min(hi), hi.max(lo)); + } + let (at, su, sv) = self.eval.derivs(q[0], q[1])?; + let n = su.cross(sv).normalized()?; + Some(((p - at).len(), (p - at).dot(n) * self.sign)) + } +} + +/// Which side of a tool a point is on, the tool's surfaces prepared once for many points. +pub(crate) struct ToolSide(Vec); + +impl ToolSide { + /// The side field of `tool` (one field: a sketch tool with one curve), its patches reaching + /// past `near`. + pub(crate) fn of(tool: &SplitTool, near: &Body) -> Result { + let mut groups = cutters(tool, &reach_of(near))?; + match (groups.pop(), groups.is_empty()) { + (Some(g), true) => Ok(ToolSide(g.iter().map(Measured::new).collect::>()?)), + _ => Err(invalid("one tool at a time")), + } + } + + /// The side of `p`: its sign says which, zero on the tool (NaN where it can't be told): the + /// offset from the nearest patch along its side. + pub(crate) fn at(&self, p: Vec3) -> f64 { + self.0.iter().filter_map(|m| m.near(p)).min_by(|a, b| a.0.total_cmp(&b.0)).map_or(f64::NAN, |(_, side)| side) + } +} + +/// How many fields a tool is (a sketch tool: one per curve). +pub(crate) fn field_count(tool: &SplitTool) -> Result { + Ok(match tool { + SplitTool::Curves { curves, .. } => curves.len(), + _ => 1, + }) +} + +/// The regions of a body cut by a tool: for each face (in face order), the region it lies in, +/// and how many there are. Faces are in one region when they meet at an edge the tool does not +/// run along; an edge along the tool (a split line) parts them. +pub(crate) fn regions(split: &Body, tool: &SplitTool) -> Result<(Vec, usize)> { + let record = split.record(); + let fields: Vec = cutters(tool, &reach_of(split))? + .iter() + .map(|g| g.iter().map(Measured::new).collect::>>().map(ToolSide)) + .collect::>()?; + let tol = (split.size() * 2e-3).max(1e-4); + let along = |e: &brep::Edge| -> bool { + let Ok(c) = CurveEval::new(e.parameters()) else { return false }; + let [t0, t1] = e.interval; + let at: Vec = [0.25, 0.5, 0.75].iter().filter_map(|s| c.point(t0 + (t1 - t0) * s)).collect(); + at.len() == 3 && fields.iter().any(|g| at.iter().all(|p| g.at(*p).abs() <= tol)) + }; + let n = record.faces.len(); + let mut parent: Vec = (0..n).collect(); + fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i).filter(|p| **p != i) { + i = p; + } + i + } + for e in &record.edges { + if along(e) { + continue; + } + let faces: Vec = e.uses.iter().map(|u| u.face as usize).collect(); + for pair in faces.windows(2) { + let (a, b) = (root(&mut parent, pair[0]), root(&mut parent, pair[1])); + if let Some(slot) = parent.get_mut(a.max(b)) { + *slot = a.min(b); + } + } + } + let mut ids = std::collections::BTreeMap::new(); + let region: Vec = (0..n) + .map(|i| { + let r = root(&mut parent, i); + let next = ids.len(); + *ids.entry(r).or_insert(next) + }) + .collect(); + Ok((region, ids.len())) +} + +/// SMLib's surfaces of the tool's patches, in the tool's order, each reaching past `reach`. +fn smlib_tools(groups: &[Vec], reach: &Aabb3) -> Result> { + let mut out = Vec::new(); + for p in groups.iter().flatten() { + let b = p.bounded(reach)?; + if b.domain.iter().any(|r| !(r[0] < r[1])) { + continue; + } + out.push(solidcraft_smlib::ssi::Surface::from_record(&b.surface, b.domain).map_err(|e| failed("split tool", e))?); + } + Ok(out) +} + +/// A result checked by SMLib and brought back with its history over `[body]`. +fn brought_back(name: &str, body: &Body, ob: &solidcraft_smlib::history::Order, r: &solidcraft_smlib::Brep) -> Result<(Body, History)> { + let check = r.check(solidcraft_smlib::CheckLevel::All).map_err(|e| failed(name, e))?; + if !check.is_valid() { + return Err(failed(name, format!("SMLib's check refuses the result: {check}"))); + } + let (out, or) = crate::native::body_from_smlib_ordered(r)?; + let or = or.ok_or_else(|| failed(name, "the result's record is numbered unlike SMLib's body"))?; + let h = r.history().map_err(|e| failed(name, e))?.history(std::slice::from_ref(ob), &or).map_err(|e| failed(name, e))?; + let out = out.with_color(body.color()).with_split_lines(body.split_lines().cloned()); + Ok((out, h)) +} + +/// `body` in SMLib, tagged as operand 0, with its record's order. +fn tagged(name: &str, body: &Body) -> Result<(solidcraft_smlib::Brep, solidcraft_smlib::history::Order)> { + let (sb, ob) = crate::native::smlib_body_ordered(body)?; + let ob = ob.ok_or_else(|| failed(name, "SMLib numbers the body's faces unlike its record"))?; + Ok((sb.tagged(0).map_err(|e| failed(name, e))?, ob)) +} + /// Split the given faces (indices in `body`'s face order) where the tool meets them. The solid /// is unchanged. A listed face the tool misses is an error naming it. The result's history is /// over `[body]`: each piece of a split face is Split from it, every other face Kept. @@ -1138,386 +460,201 @@ pub fn split_faces(body: &Body, faces: &[usize], tool: &SplitTool) -> Result Result<(Body, Vec)> { - let (b, imp) = split_any(body, faces, tool)?; - // The new edges, remembered so that export keeps the pieces apart. - let mut lines: Vec> = body.splits.as_ref().map(|l| l.to_vec()).unwrap_or_default(); - lines.extend(imp.new_edges.iter().filter_map(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let n = if matches!(c, mt::Curve::Line(_)) { 1 } else { 64 }; - let pts: Vec = (0..=n).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / n as f64))).collect(); - pts.iter().all(|p| p.is_finite()).then_some(pts) - })); - let b = b.with_split_lines(Some(std::sync::Arc::new(lines))); - if let Some(missed) = faces.iter().find(|f| imp.made.get(f).copied().unwrap_or(0) == 0) { - return Err(KernelError::Invalid(format!("the tool does not cross face {missed}"))); + let _span = solidcraft_profile::span("kernel", "split_faces_with_map"); + let (b, map, made) = split(body, faces, tool)?; + if let Some((missed, _)) = faces.iter().zip(&made).find(|(_, m)| **m == 0) { + return Err(invalid(format!("the tool does not cross face {missed}"))); } - Ok((b, imp.origin)) + Ok((b, map)) } -/// Split where the tool meets the listed faces (missing some is fine; missing all is an error). -pub(crate) fn split_any(body: &Body, faces: &[usize], tool: &SplitTool) -> Result<(Body, Imprint)> { - body.require_brep("split face")?; - let size = body.size(); - let fields = fields(tool)?; - let total = body.solid.face_iter().count(); - if faces.iter().any(|f| *f >= total) { - return Err(KernelError::Invalid("no such face".into())); +/// Split where the tool meets the listed faces (missing some is fine; missing all is an error), +/// with the body face each face of the result came from. +pub(crate) fn split_any(body: &Body, faces: &[usize], tool: &SplitTool) -> Result<(Body, Vec)> { + split(body, faces, tool).map(|(b, map, _)| (b, map)) +} + +/// The split, the body face each result face came from, and for each listed face how many faces +/// it became besides itself. +fn split(body: &Body, faces: &[usize], tool: &SplitTool) -> Result<(Body, Vec, Vec)> { + const NAME: &str = "split face"; + body.require_brep(NAME)?; + let total = body.face_count(); + if faces.is_empty() || faces.iter().any(|f| *f >= total) { + return Err(invalid("no such face")); } - guard("split face", || { - let mut imp = imprint(body, faces, &fields, size)?; - if imp.made.values().all(|m| *m == 0) { - return Err(KernelError::Invalid("the tool does not cross the selected faces".into())); - } - let shells = std::mem::take(&mut imp.shells); - let solid = mt::Solid::new_unchecked(shells.into_iter().map(mt::Shell::from).collect()); - let split = Body { - solid: std::sync::Arc::new(solid), - size: 0.0, - boundary_tol: body.boundary_tol, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: None, - mesh: None, - color: body.color, - paint: None, - splits: body.splits.clone(), - face_sources: None, - history: None, - display_of: None, - meshes: None, - phased: false, - regularization_protected: true, - }; - Ok((crate::record::rebuilt_body(split, &[&body.solid], &imp.rec), imp)) + if faces.iter().enumerate().any(|(i, f)| faces.get(..i).is_some_and(|before| before.contains(f))) { + return Err(invalid("a face is listed twice")); + } + let reach = reach_of(body); + let tools = smlib_tools(&cutters(tool, &reach)?, &reach)?; + let missed = || invalid("the tool does not cross the selected faces"); + if tools.is_empty() { + return Err(missed()); + } + guard(NAME, || { + let (sb, ob) = tagged(NAME, body)?; + let at: Vec = faces + .iter() + .map(|f| if ob.faces.is_empty() { Some(*f) } else { ob.faces.iter().position(|c| c == f) }) + .collect::>() + .ok_or_else(|| failed(NAME, "a listed face is not in SMLib's body"))?; + let refs: Vec<&solidcraft_smlib::ssi::Surface> = tools.iter().collect(); + let (r, made) = sb.split_faces(&at, &refs).map_err(|e| failed(NAME, e))?.ok_or_else(missed)?; + let (out, h) = brought_back(NAME, body, &ob, &r)?; + let map = h + .faces + .iter() + .map(|f| f.origins.iter().find_map(|o| if let FaceOrigin::Face { face, .. } = o { Some(*face) } else { None })) + .collect::>>() + .ok_or_else(|| failed(NAME, "a face of the result comes from no face of the body"))?; + // The new edges, remembered so that export keeps the pieces apart. + let mut lines: Vec> = body.split_lines().map(|l| l.to_vec()).unwrap_or_default(); + lines.extend(new_lines(&out, &h)?); + let mut out = out.with_split_lines(Some(std::sync::Arc::new(lines))).with_checked_history(Some(h), &record::counts(&[body])); + // An authored boundary: later rebuilds keep it. + out.regularization_protected = true; + Ok((out, map, made)) }) } -/// The field at a point well inside a face (a mesh triangle's centre where the field is -/// largest; for a plane, the face's corner farthest from it). -fn side_of(face: &mt::Face, g: &Field, size: f64) -> Result { - // A face the plane does not cross is on the side of whichever corner lies off it (the - // farthest, against rounding); a face with every corner on the plane is meshed. - if let Field::Plane { .. } = g { - let far = face - .boundaries() - .iter() - .flat_map(|w| w.vertex_iter()) - .map(|v| g.eval(from_p3(v.point()))) - .fold(0.0, |b: f64, x| if x.abs() > b.abs() { x } else { b }); - if far.abs() > size * 1e-6 { - return Ok(far); - } - } - let shell: mt::Shell = vec![face.clone()].into(); - let meshed = shell.robust_triangulation((size * 2e-3).max(1e-4)); - let pm = meshed.face_iter().next().and_then(|f| f.surface()).ok_or_else(|| KernelError::Failed("a face could not be meshed".into()))?; - let pos = pm.positions(); - let mut best: f64 = 0.0; - for t in pm.faces().triangle_iter() { - let c = t.iter().filter_map(|v| pos.get(v.pos)).fold(Vec3::ZERO, |a, p| a + from_p3(*p) / 3.0); - let x = g.eval(c); - if x.is_finite() && x.abs() > best.abs() { - best = x; - } - } - Ok(best) -} - -/// Loops from edges (each used once), chained end to start; edges are turned round as needed. -fn chain_loops(edges: &[mt::Edge]) -> Result>> { - let mut pool: Vec = edges.to_vec(); +/// The edges of `split` that no edge of the body was before (its split lines), as polylines +/// through their exact points. +fn new_lines(split: &Body, h: &History) -> Result>> { + let record = split.record(); let mut out = Vec::new(); - while let Some(first) = pool.pop() { - let start = first.front().id(); - let mut at = first.back().clone(); - let mut lp = vec![first]; - while at.id() != start { - let Some(k) = pool.iter().position(|e| e.front().id() == at.id() || e.back().id() == at.id()) else { - return Err(KernelError::Failed("the section through the body does not close".into())); - }; - let e = pool.remove(k); - let e = if e.front().id() == at.id() { e } else { e.inverse() }; - at = e.back().clone(); - lp.push(e); - if lp.len() > 1_000_000 { - return Err(KernelError::Failed("section loop too long".into())); - } + for (e, prov) in record.edges.iter().zip(&h.edges) { + if prov.origins.iter().any(|o| matches!(o, EdgeOrigin::Edge { .. })) { + continue; + } + let c = CurveEval::new(e.parameters()).map_err(|err| failed("split face", err))?; + let n = if matches!(e.curve, brep::Curve::Line { .. }) { 1 } else { 64 }; + let [t0, t1] = e.interval; + let pts: Option> = (0..=n).map(|k| c.point(t0 + (t1 - t0) * k as f64 / n as f64)).collect(); + if let Some(pts) = pts.filter(|p| p.iter().all(|q| q.is_finite())) { + out.push(pts); } - out.push(lp); } Ok(out) } -/// The regions of a body cut by a tool: for each face (in face order), the region it lies in, -/// and how many there are. Faces are in one region when they meet at an edge the tool does not -/// run along; an edge along the tool (a split line) parts them. -pub(crate) fn regions(split: &Body, tool: &SplitTool) -> Result<(Vec, usize)> { - let fields = fields(tool)?; - let tol = trace_tol_of(split.size()); - let faces: Vec<&mt::Face> = split.solid.face_iter().collect(); - let mut along_tool: HashMap = HashMap::new(); - let mut by_edge: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - by_edge.entry(e.id()).or_default().push(i); - along_tool.entry(e.id()).or_insert_with(|| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let at: Vec = [0.25, 0.5, 0.75].iter().map(|s| from_p3(c.subs(t0 + (t1 - t0) * s))).collect(); - fields.iter().any(|g| at.iter().all(|p| g.eval(*p).abs() <= tol)) - }); - } - } - let mut region = vec![usize::MAX; faces.len()]; - let mut count = 0; - for s in 0..faces.len() { - if region.get(s) != Some(&usize::MAX) { - continue; - } - if let Some(r) = region.get_mut(s) { - *r = count; - } - let mut stack = vec![s]; - while let Some(i) = stack.pop() { - let Some(f) = faces.get(i) else { continue }; - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - if along_tool.get(&e.id()).copied().unwrap_or(false) { - continue; - } - for &j in by_edge.get(&e.id()).into_iter().flatten() { - if let Some(r) = region.get_mut(j) - && *r == usize::MAX - { - *r = count; - stack.push(j); - } - } - } - } - count += 1; - } - Ok((region, count)) -} - -/// How many fields a tool is (a sketch tool: one per curve). -pub(crate) fn field_count(tool: &SplitTool) -> Result { - Ok(fields(tool)?.len()) -} - -/// Faces grouped by shared edges (in face order). -fn components(faces: Vec) -> Vec> { - let n = faces.len(); - let mut by_edge: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - by_edge.entry(e.id()).or_default().push(i); - } - } - let mut comp = vec![usize::MAX; n]; - let mut count = 0; - for s in 0..n { - if comp[s] != usize::MAX { - continue; - } - comp[s] = count; - let mut stack = vec![s]; - while let Some(i) = stack.pop() { - let Some(f) = faces.get(i) else { continue }; - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - for &j in by_edge.get(&e.id()).into_iter().flatten() { - if comp[j] == usize::MAX { - comp[j] = count; - stack.push(j); - } - } - } - } - count += 1; - } - let mut out: Vec> = vec![Vec::new(); count]; - for (f, c) in faces.into_iter().zip(comp) { - if let Some(v) = out.get_mut(c) { - v.push(f); - } - } - out -} - -/// Split a body into the parts on either side of a tool: a plane, or another face's surface -/// (extended). Faces are divided where the tool meets them and every part is closed with the -/// piece of the tool's surface inside the body; parts come in face order, those on the tool's -/// back first. A body the tool misses comes back whole. Each part's history is over `[body]`: +/// Split a body into the parts on either side of a tool: a plane, another face's surface +/// (extended; a face of a surface body joined tangentially to others: their smooth sheet as it +/// is, which must cross the body), or one sketch line swept along its direction. Every part is closed with the piece +/// of the tool's surface inside the body; parts on the tool's back come first, each side's in +/// face order. A body the tool misses comes back whole. Each part's history is over `[body]`: /// its faces the body's (or pieces of them), the section new. pub fn split_body(body: &Body, tool: &SplitTool) -> Result> { - body.require_brep("split body")?; - if body.solid.boundaries().len() != 1 { - return Err(KernelError::Invalid("not supported yet: splitting a body with voids".into())); + let _span = solidcraft_profile::span("kernel", "split_body"); + body.require_brep(SPLIT_BODY)?; + if let SplitTool::Face { body: sheet, face } = tool { + let faces = smooth_sheet(sheet, *face)?; + if faces.len() > 1 { + return split_by_sheet(body, sheet, *face, &faces); + } } - let size = body.size(); - let fields = fields(tool)?; - let [g] = fields.as_slice() else { return Err(KernelError::Invalid("a body is split by a plane or a face".into())) }; - // The tool surface, with the field's normal. - // The tool's whole surface for the section (a sheet that is part of a plane or cylinder - // is extended to all of it), with the field's normal. - let surface = match g { - Field::Plane { o, n } => { - let x = (if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).cross(*n).normalized().unwrap_or(Vec3::X); - let y = n.cross(x); - let o = p3(*o); - mt::Surface::Plane(mt::Plane::new(o, o + crate::body::v3(x), o + crate::body::v3(y))) - } - Field::Cylinder { o, axis, r, out } => { - // A line along the axis at radius r, long enough for the body, revolved. - let mut lo = f64::INFINITY; - let mut hi = f64::NEG_INFINITY; - for v in body.solid.vertex_iter() { - let t = (from_p3(v.point()) - *o).dot(*axis); - lo = lo.min(t); - hi = hi.max(t); - } - let (lo, hi) = (lo - size, hi + size); - let x = (if axis.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).cross(*axis).normalized().unwrap_or(Vec3::X); - let (a, b) = (*o + *axis * lo + x * *r, *o + *axis * hi + x * *r); - let line = mt::Curve::Line(mt::Line(p3(a), p3(b))); - crate::step_in::geom::revolved_oriented(line, p3(*o), crate::body::v3(axis.vec()), 0.5, crate::body::v3(x * *out)) - } - Field::Surface(s) => s.clone(), - Field::Curve { .. } => return Err(KernelError::Invalid("a body is split by a plane or a face".into())), + let reach = reach_of(body); + let groups = cutters(tool, &reach)?; + let [group] = groups.as_slice() else { return Err(invalid("a body is split by a plane or a face")) }; + let [patch] = group.as_slice() else { return Err(invalid("a body is split by a plane, a face or one sketch line")) }; + let Some(surface) = smlib_tools(std::slice::from_ref(group), &reach)?.pop() else { + return Ok(vec![crate::boolean_record::operand(body, 0, &record::counts(&[body]))]); }; - let total = body.solid.face_iter().count(); - let all: Vec = (0..total).collect(); - guard("split body", || { - let imp = imprint(body, &all, &fields, size)?; - let new_edges = imp.new_edges; - if imp.made.values().all(|m| *m == 0) || new_edges.is_empty() { - return Ok(vec![crate::boolean_record::operand(body, 0, &crate::record::counts(&[body]))]); - } - let mut rec = imp.rec; - let faces: Vec = imp.shells.into_iter().flatten().collect(); - // The section: loops of the new edges on the tool surface, outer loops counter-clockwise - // about its normal and holes inside them. - let loops = chain_loops(&new_edges)?; - let polys: Vec> = loops.iter().map(|l| loop_uv(&surface, &l.clone().into())).collect(); - let signed = |p: &[(f64, f64)]| { - (0..p.len()) - .map(|i| { - let (a, b) = (p[i], p[(i + 1) % p.len()]); - a.0 * b.1 - b.0 * a.1 - }) - .sum::() - }; - let depth: Vec = (0..loops.len()) - .map(|i| { - let q = polys.get(i).and_then(|p| p.first()).copied().unwrap_or((0.0, 0.0)); - (0..loops.len()).filter(|&j| j != i && polys.get(j).is_some_and(|p| inside(p, q))).count() - }) - .collect(); - let wire = |i: usize, ccw: bool| -> mt::Wire { - let w: mt::Wire = loops.get(i).cloned().unwrap_or_default().into(); - let is_ccw = polys.get(i).is_some_and(|p| signed(p) > 0.0); - if is_ccw == ccw { w } else { w.inverse() } - }; - let mut section = Vec::new(); - // On a surface of revolution, loops that run once round it (a cylinder through a box: - // its circles at the top and bottom) bound bands: taken in order along the profile, - // each pair is one face, the lower loop running back round and the upper forward. - let mut wrapping = vec![false; loops.len()]; - if let mt::Surface::RevolutedCurve(rc) = &surface { - let (o, axis) = (rc.entity().origin(), rc.entity().axis().normalize()); - let x0 = if axis.x.abs() < 0.9 { mt::Vector3::unit_x() } else { mt::Vector3::unit_y() }; - let ex = (x0 - axis * x0.dot(axis)).normalize(); - let ey = axis.cross(ex); - let tau = std::f64::consts::TAU; - let samples = |w: &mt::Wire| -> Vec { - w.edge_iter() - .flat_map(|e| { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - (0..32).map(move |k| c.subs(t0 + (t1 - t0) * k as f64 / 32.0)).collect::>() - }) - .collect() - }; - let mut bands: Vec<(f64, usize)> = Vec::new(); - for (i, l) in loops.iter().enumerate() { - let pts = samples(&l.clone().into()); - let ang = |p: &mt::Point3| (p - o).dot(ey).atan2((p - o).dot(ex)); - let turn: f64 = (0..pts.len()) - .map(|k| { - let d = ang(&pts[(k + 1) % pts.len()]) - ang(&pts[k]); - d - tau * (d / tau).round() - }) - .sum(); - if (turn.abs() - tau).abs() < 0.1 { - let along = pts.iter().map(|p| (p - o).dot(axis)).sum::() / pts.len().max(1) as f64; - bands.push((along, i)); - if let Some(w) = wrapping.get_mut(i) { - *w = true; - } - } - } - bands.sort_by(|a, b| a.0.total_cmp(&b.0)); - // A loop runs so that the band (towards `toward` along the axis) is on its left about - // the surface normal. - let oriented = |i: usize, toward: f64| -> mt::Wire { - let w: mt::Wire = loops.get(i).cloned().unwrap_or_default().into(); - let pts = samples(&w); - let (Some(p), Some(q)) = (pts.first(), pts.get(1)) else { return w }; - let n = surface.search_nearest_parameter(*p, None, 50).map(|(u, v)| surface.normal(u, v)).unwrap_or(axis); - let left = n.cross(q - p); - if left.dot(axis) * toward >= 0.0 { w } else { w.inverse() } - }; - for pair in bands.chunks(2) { - let [(_, lo), (_, hi)] = pair else { return Err(KernelError::Failed("an unmatched band edge in the section".into())) }; - section.push(mt::Face::new_unchecked(vec![oriented(*lo, 1.0), oriented(*hi, -1.0)], surface.clone())); - } - } - for (i, d) in depth.iter().enumerate() { - if d % 2 != 0 || wrapping.get(i).copied().unwrap_or(false) { + sliced(body, patch.flip, |sb| sb.split_body(&surface)) +} + +const SPLIT_BODY: &str = "split body"; + +/// `body` cut in two by `cut` (SMLib's slice of its tagged copy, giving the parts behind and in +/// front of the tool's surface), the parts in the tool's order of sides (`flip`: the tool's side +/// is its surface's back), each solid of a part its own body. The body whole where the tool +/// cuts nothing. +fn sliced( + body: &Body, + flip: bool, + cut: impl FnOnce(&solidcraft_smlib::Brep) -> solidcraft_smlib::Result>, +) -> Result> { + let counts = record::counts(&[body]); + let whole = || crate::boolean_record::operand(body, 0, &counts); + guard(SPLIT_BODY, || { + let (sb, ob) = tagged(SPLIT_BODY, body)?; + let Some((back, front)) = cut(&sb).map_err(|e| failed(SPLIT_BODY, e))? else { return Ok(vec![whole()]) }; + // SMLib's sides are the surface's; the tool's are the face's. + let sides = if flip { [front, back] } else { [back, front] }; + let (mut parts, mut cut) = (Vec::new(), false); + for side in &sides { + let (part, h) = brought_back(SPLIT_BODY, body, &ob, side)?; + // The section comes from no face of the body. + cut |= h.faces.iter().any(|f| f.origins.is_empty()); + let part = part.with_checked_history(Some(h), &counts); + let lumps = part.lumps()?; + if lumps.len() < 2 { + parts.push(part); continue; } - let mut ws = vec![wire(i, true)]; - for (j, dj) in depth.iter().enumerate() { - let q = polys.get(j).and_then(|p| p.first()).copied().unwrap_or((0.0, 0.0)); - if *dj == d + 1 && polys.get(i).is_some_and(|p| inside(p, q)) { - ws.push(wire(j, false)); - } - } - section.push(mt::Face::new_unchecked(ws, surface.clone())); - } - // Each face goes to the side its inside is on. - let (mut back, mut front) = (Vec::new(), Vec::new()); - for f in faces { - let x = side_of(&f, g, size)?; - if x.abs() <= size * 1e-9 { - return Err(KernelError::Invalid("not supported yet: the tool lies along a face of the body".into())); - } - if x < 0.0 { - back.push(f); - } else { - front.push(f); + for lump in lumps { + let h = crate::boolean_record::through(&lump, 0, part.history()); + parts.push(lump.with_checked_history(h, &counts)); } } - // The section is new: it comes from nothing of the body. - for f in §ion { - rec.made(f, Vec::new()); - } - // The section closes the back side facing the tool's normal, the front side facing away. - back.extend(section.iter().cloned()); - front.extend(section.iter().map(|f| f.inverse())); - let mut parts = Vec::new(); - for side in [back, front] { - for comp in components(side) { - let shell = mt::Shell::from(comp); - if shell.shell_condition() != mt::ShellCondition::Closed { - return Err(KernelError::Failed("a part of the split does not close".into())); - } - parts.push(crate::record::rebuilt(mt::Solid::new_unchecked(vec![shell]), &[&body.solid], &rec)?.with_color(body.color)); - } - } - Ok(parts) + Ok(if cut { parts } else { vec![whole()] }) }) } +/// The faces of the surface body `sheet` joined to its face `face` tangentially, through edges +/// along which the faces' normals agree all along ([`crate::tangent_edge`], within the one angle +/// for smooth, [`crate::smooth_edges::ANGLE`]), and through those faces' tangent neighbours in +/// turn: the smooth surface the face is part of, in face order. Only `face` for a closed body +/// (a solid's face splits with its own surface extended). +fn smooth_sheet(sheet: &Body, face: usize) -> Result> { + sheet.require_brep("a split tool")?; + let r = sheet.record(); + if r.faces.get(face).is_none() { + return Err(invalid(format!("the tool body has no face {face}"))); + } + if !r.edges.iter().any(|e| e.uses.len() == 1) { + return Ok(vec![face]); + } + let sides = crate::surfaces::face_sides(r); + let sign = |f: usize| sides.get(f).map(|forward| if *forward { 1.0 } else { -1.0 }); + let mut joined = std::collections::BTreeSet::from([face]); + let mut todo = vec![face]; + while let Some(f) = todo.pop() { + let Some(this) = r.faces.get(f) else { continue }; + for l in &this.loops { + let brep::Loop::Edges { edges } = l else { continue }; + for u in edges { + let e = u.edge as usize; + let Some([a, b]) = r.edges.get(e).map(|edge| edge.uses.as_slice()) else { continue }; + let g = if a.face as usize == f { b.face } else { a.face } as usize; + if g == f || joined.contains(&g) { + continue; + } + if crate::tangent_edge::tangent_all_along(r, sign, e, crate::smooth_edges::ANGLE)? { + joined.insert(g); + todo.push(g); + } + } + } + } + Ok(joined.into_iter().collect()) +} + +/// `body` cut in two by the faces `faces` of the surface body `sheet` as they are (a smooth sheet +/// of several faces, bounded where they end), its sides those of `sheet`'s face `face`: SMLib's +/// slice by the sheet ([`solidcraft_smlib::Brep::split_body_by_sheet`]). A sheet that does not +/// cross the body cuts nothing. +fn split_by_sheet(body: &Body, sheet: &Body, face: usize, faces: &[usize]) -> Result> { + let picked: Vec<(usize, bool)> = faces.iter().map(|f| (*f, false)).collect(); + let c = crate::surfaces::Parts::of(sheet.record(), &picked)?.canonical()?; + let at = c.faces.iter().position(|p| faces.get(*p) == Some(&face)).ok_or_else(|| failed(SPLIT_BODY, "the tool face is not in its sheet"))?; + let (tool, order) = crate::native::smlib_record_ordered(&c.brep)?; + let order = order.ok_or_else(|| failed(SPLIT_BODY, "SMLib numbers the tool sheet's faces unlike its record"))?; + // SMLib's face `i` is the record's `order.faces[i]` (the same where none is given). + let k = if order.faces.is_empty() { Some(at) } else { order.faces.iter().position(|f| *f == at) }; + let k = k.ok_or_else(|| failed(SPLIT_BODY, "the tool face has no SMLib face"))?; + sliced(body, !sheet.face_forward(face), |sb| sb.split_body_by_sheet(&tool, k)) +} #[cfg(test)] mod tests { use super::*; @@ -1576,9 +713,14 @@ mod tests { assert!(n > c.face_count()); // The pieces stay apart; the cylinder's incidental seam pieces still join as before. assert_eq!(round_trip_faces(&cs), round_trip_faces(&c) + 1); - // Without the record the export joins the top's pieces again (as it does for pieces a - // boolean left). - assert_eq!(round_trip_faces(&s.clone().with_split_lines(None)), 6); + // Without the record (no operation drops it: only Split Face's own removal, which + // rebuilds without the split) the pieces are incidental: the file has what the body + // has, and the next operation joins them as it joins any pieces on one surface (SMLib's + // booleans at their end, the local modifiers through the heal). + let unrecorded = s.clone().with_split_lines(None); + assert_eq!(round_trip_faces(&unrecorded), unrecorded.face_count()); + let joined = crate::boolean_record::healed(&unrecorded).unwrap(); + assert_eq!((joined.face_count(), round_trip_faces(&joined)), (6, 6)); // A split after a split keeps both lines. let pl2 = Plane::new(Vec3::new(0.0, 12.0, 0.0), Vec3::X, Vec3::Z).unwrap(); let tops: Vec = @@ -1600,12 +742,13 @@ mod tests { let m = measure(&s).unwrap(); // (Measured on meshes: curved faces agree to about 1e-4.) assert!(rel(m.volume, m0.volume) < 2e-4 && rel(m.area, m0.area) < 2e-4, "{} {} {} {}", m.volume, m0.volume, m.area, m0.area); - // The half side face splits at z = 5: a quarter and three quarters of its area. + // The side (one face round the whole turn) splits at z = 5: a quarter and three quarters + // of its area. let mut sides: Vec = s.faces(0.01).unwrap().iter().filter(|f| f.plane_normal.is_none()).map(|f| f.area).collect(); sides.sort_by(f64::total_cmp); - let half = std::f64::consts::PI * 10.0 * 20.0; - assert_eq!(sides.len(), 3); - assert!(rel(sides[0], half / 4.0) < 1e-3 && rel(sides[1], half * 0.75) < 1e-3 && rel(sides[2], half) < 1e-3, "{sides:?}"); + let whole = std::f64::consts::TAU * 10.0 * 20.0; + assert_eq!(sides.len(), 2); + assert!(rel(sides[0], whole / 4.0) < 1e-3 && rel(sides[1], whole * 0.75) < 1e-3, "{sides:?}"); assert!(s.face_count() > c.face_count()); // A smaller cylinder's side splits the top in a ring and a disc. let pin = cylinder(Vec3::ZERO, Vec3::Z, 4.0, 40.0).unwrap(); @@ -1638,6 +781,61 @@ mod tests { assert!(tops.iter().all(|a| rel(*a, half) < 1e-3), "{tops:?}"); } + /// Cubic spans of a spline, each with its x control points evenly spaced (so x runs linearly + /// along it and y is a cubic in x), meeting tangent, extruded from z = -5 to 15. + fn spans(ys: &[[f64; 4]]) -> Body { + let chain = ys + .iter() + .enumerate() + .map(|(i, y)| { + let x0 = -3.0 + 6.0 * i as f64; + let p = |k: usize| Vec2::new(x0 + 2.0 * k as f64, y[k]); + Seg2::Cubic { p0: p(0), p1: p(1), p2: p(2), p3: p(3) } + }) + .collect(); + crate::extrude_sheet(&Plane::XY, &[chain], -5.0, 15.0).unwrap() + } + + /// The face of `b` farthest to -x (by its centroid). + fn leftmost(b: &Body) -> usize { + let faces = b.faces(0.01).unwrap(); + (0..faces.len()).min_by(|i, j| faces[*i].centroid.x.total_cmp(&faces[*j].centroid.x)).unwrap() + } + + /// Split Body by a face of a smooth sheet cuts with the whole sheet (#3830): three spans + /// meeting tangent cross the cube 0…10, the face of the first alone does not. The part + /// under the spline is 10 ∫ y dx over x 0…10 (y a cubic in x on each span: Gauss–Legendre at + /// three points is exact). Two spans that end inside the cube cut nothing. + #[test] + fn a_face_of_a_smooth_sheet_splits_with_the_whole_sheet() { + let ys = [[5.0, 5.0, 4.0, 4.0], [4.0, 4.0, 6.0, 6.0], [6.0, 6.0, 5.0, 5.0]]; + let bern = |y: &[f64; 4], t: f64| { + let s = 1.0 - t; + y[0] * s * s * s + 3.0 * y[1] * s * s * t + 3.0 * y[2] * s * t * t + y[3] * t * t * t + }; + // ∫ y dx over the span's t0…t1 (dx = 6 dt). + let integral = |y: &[f64; 4], t0: f64, t1: f64| { + let (m, h) = (0.5 * (t0 + t1), 0.5 * (t1 - t0)); + let g = (0.6f64).sqrt(); + 6.0 * h * (5.0 * bern(y, m - h * g) + 8.0 * bern(y, m) + 5.0 * bern(y, m + h * g)) / 9.0 + }; + let under = 10.0 * (integral(&ys[0], 0.5, 1.0) + integral(&ys[1], 0.0, 1.0) + integral(&ys[2], 0.0, 1.0 / 6.0)); + let sheet = spans(&ys); + assert_eq!(sheet.face_count(), 3); + let first = leftmost(&sheet); + let cube = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + let parts = split_body(&cube, &SplitTool::Face { body: &sheet, face: first }).unwrap(); + let v = volumes(&parts); + assert_eq!(v.len(), 2, "{v:?}"); + assert!(rel(v[0], under) < 1e-6 && rel(v[1], 1000.0 - under) < 1e-6, "{v:?} vs {under}"); + + let short = spans(&ys[..2]); + let first = leftmost(&short); + let nicked = split_body(&cube, &SplitTool::Face { body: &short, face: first }).unwrap(); + let info: Vec<_> = nicked.iter().map(|b| (measure(b).unwrap().volume, b.face_count(), b.lumps().unwrap().len())).collect(); + assert_eq!(nicked.len(), 1, "{info:?}"); + } + fn volumes(parts: &[Body]) -> Vec { let mut v: Vec = parts.iter().map(|b| measure(b).unwrap().volume).collect(); v.sort_by(f64::total_cmp); @@ -1686,7 +884,8 @@ mod tests { let quarter = std::f64::consts::PI * 36.0 / 4.0; // (Face areas come from meshes.) assert!(rel(tops[0], quarter) < 1e-3 && rel(tops[1], 200.0 - quarter) < 1e-3, "{tops:?}"); - assert!(s.solid.edge_iter().any(|e| matches!(e.curve(), mt::Curve::NurbsCurve(_)))); + let record = s.record(); + assert!(record.edges.iter().any(|e| matches!(e.curve, brep::Curve::Circle { .. } | brep::Curve::RationalSpline { .. }))); // A listed face the tool misses is named: the plane z = 10 crosses the sides, not the top. let mid = Plane { origin: Vec3::new(0.0, 0.0, 10.0), ..Plane::XY }; let side = b.faces(0.01).unwrap().iter().position(|f| (f.centroid.x - 10.0).abs() < 1e-6).unwrap(); diff --git a/crates/kernel/src/step.rs b/crates/kernel/src/step.rs index 1f6d343e6..f298e3d11 100644 --- a/crates/kernel/src/step.rs +++ b/crates/kernel/src/step.rs @@ -1,97 +1,5 @@ -use truck_modeling as mt; -use truck_stepio::out; - +use crate::Result; use crate::body::Body; -use crate::{KernelError, Result, guard}; - -/// Intersection-curve edges (from booleans) as cubic B-splines through the exact curve: STEP -/// readers get plain 3D geometry that lies on both faces, and the file does not repeat the two -/// surfaces for every such edge. -fn plain_curves(b: &Body) -> Result { - let s = crate::ops::placed_topology(&b.solid, mt::Matrix4::from_scale(1.0))?; - let size = b.size(); - let mut seen = std::collections::HashSet::new(); - for e in s.edge_iter() { - if !seen.insert(e.id()) { - continue; - } - if let mt::Curve::IntersectionCurve(ic) = e.curve() - && let Some(c) = hermite_through(&ic, size * 1e-4) - { - e.set_curve(mt::Curve::BSplineCurve(c)); - } - } - Ok(s) -} - -/// A C¹ cubic B-spline through exact points of `c` spaced so that chords deviate at most `tol` -/// (Catmull–Rom tangents over chord length; the cubic is far closer than the chords). -fn hermite_through(c: &C, tol: f64) -> Option> -where - C: mt::ParametricCurve + mt::BoundedCurve + mt::ParameterDivision1D, -{ - use mt::{InnerSpace, MetricSpace}; - let (_, pts) = c.parameter_division(c.range_tuple(), tol); - let pts: Vec = pts.into_iter().fold(Vec::new(), |mut v: Vec, p| { - if v.last().is_none_or(|q| q.distance(p) > tol * 1e-3) { - v.push(p); - } - v - }); - let n = pts.len().checked_sub(1).filter(|n| *n >= 1 && *n < 1_000_000)?; - let mut u = vec![0.0; n + 1]; - for i in 1..=n { - u[i] = u[i - 1] + pts[i].distance(pts[i - 1]); - } - let tangent = |i: usize| { - let (a, b) = (i.saturating_sub(1), (i + 1).min(n)); - (pts[b] - pts[a]) / (u[b] - u[a]) - }; - let mut ctrl = vec![pts[0]]; - let mut knots = vec![u[0]; 4]; - for i in 0..n { - let h = u[i + 1] - u[i]; - ctrl.push(pts[i] + tangent(i) * (h / 3.0)); - ctrl.push(pts[i + 1] - tangent(i + 1) * (h / 3.0)); - ctrl.push(pts[i + 1]); - knots.extend(std::iter::repeat_n(u[i + 1], if i + 1 == n { 4 } else { 3 })); - } - if ctrl.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) || tangent(0).magnitude() == 0.0 { - return None; - } - mt::BSplineCurve::try_new(mt::KnotVec::from(knots), ctrl).ok() -} - -/// truck's STEP text for the given bodies (geometry and topology; product data is ours). -pub(crate) fn truck_step(bodies: &[&Body], system: &str) -> Result { - if bodies.is_empty() { - return Err(KernelError::Invalid("nothing to export".into())); - } - for b in bodies { - b.require_brep("STEP export")?; - } - guard("step export", || { - let cs: Vec<_> = bodies.iter().map(|b| plain_curves(b).map(|solid| solid.compress())).collect::>()?; - let models: out::StepModels<_, _, _> = cs.iter().collect(); - let header = out::StepHeaderDescriptor { organization_system: system.to_owned(), ..Default::default() }; - written(&out::CompleteStepDisplay::new(models, header)) - }) -} - -/// The text of truck's STEP writer, or an error. The writer refuses some geometry by returning -/// `fmt::Error` after a line saying why; `to_string` would turn that into a panic (caught by -/// `guard` on the desktop, but the browser build aborts on any panic). -fn written(display: &impl std::fmt::Display) -> Result { - use std::fmt::Write; - let mut text = String::new(); - match write!(text, "{display}") { - Ok(()) => Ok(text), - Err(_) => { - let why = text.lines().last().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).unwrap_or("unsupported geometry"); - Err(KernelError::Failed(format!("not supported yet: STEP export of this body ({why})"))) - } - } -} /// STEP (ISO 10303-21, AP242) text for the given bodies as one part (`Body1`…, with the /// bodies' colours). diff --git a/crates/kernel/src/step_in/brep.rs b/crates/kernel/src/step_in/brep.rs deleted file mode 100644 index 37591e5ac..000000000 --- a/crates/kernel/src/step_in/brep.rs +++ /dev/null @@ -1,663 +0,0 @@ -//! STEP topology (ISO 10303-42 topology entities) to kernel solids: breps, shells, faces, loops, -//! edges and vertices. A face that cannot be built is left out and reported; the rest of the -//! body is still imported (as an open body when a face is missing). - -use std::collections::HashMap; - -use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface}; -use truck_modeling as mt; - -use super::Ctx; -use super::geom::{self, R, entity}; -use super::p21::Param; -use crate::guard; - -/// Most faces in one body. -const MAX_FACES: usize = 500_000; -/// Most edges in one loop. -const MAX_LOOP: usize = 100_000; -/// Most boundary loops on one face. Each bound clones its edge handles into a new wire and the -/// face extent then samples nine points per edge, so one face listing the same 100,000-edge -/// loop a million times would hold 1e11 handles. -const MAX_BOUNDS: usize = 10_000; - -/// A body read from a brep entity. -pub(crate) struct BrepOut { - pub solid: mt::Solid, - /// Faces left out (with the reason). - pub failed: Vec, - /// The shells are closed (a solid) rather than open (missing faces, or a surface model). - pub closed: bool, - /// Faces read from the file (before band faces are split for the kernel). - pub file_faces: usize, - /// The file face of each kernel face, in face order. - pub face_origin: Vec, -} - -#[derive(Default)] -struct Builder { - vertices: HashMap, - edges: HashMap>, - poly_edges: HashMap<(u64, u64), mt::Edge>, - faces: usize, -} - -fn refs(p: Option<&Param>) -> Vec { - p.and_then(Param::as_list).map(|v| v.iter().filter_map(Param::as_ref_id).collect()).unwrap_or_default() -} - -fn rid(p: Option<&Param>, what: &str) -> R { - p.and_then(Param::as_ref_id).ok_or_else(|| format!("{what}: expected a reference")) -} - -/// 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 { - 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 = None; - let mut first: Option = 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(); - let curve = rc.entity_curve(); - let on_axis = |p: mt::Point3| (p - rc.origin()).cross(rc.axis()).magnitude() <= tol; - // A compact support has two legitimate sides of a closed trim (a sphere's - // hemispheres, for example); its winding must choose the side, not repair it. - if (on_axis(curve.front()) && on_axis(curve.back())) || curve.front().distance(curve.back()) <= tol { - return false; - } - } - let periods = truck_meshalgo::tessellation::surface_periods(surface); - let mut first = None::<[f64; 2]>; - let mut previous = None::<[f64; 2]>; - let (mut area, mut magnitude) = (0.0, 0.0); - for edge in wire.edge_iter() { - let curve = edge.oriented_curve(); - let (a, b) = curve.range_tuple(); - for k in 0..8 { - let point = curve.subs(a + (b - a) * f64::from(k) / 8.0); - let hint = previous.map(|p| (p[0], p[1])); - let valid = |&(u, v): &(f64, f64)| u.is_finite() && v.is_finite() && surface.subs(u, v).distance(point) <= tol; - let Some((u, v)) = truck_meshalgo::tessellation::project_trim_point(surface, point, hint, tol).filter(valid) else { - return false; - }; - // A pole has no unique parameter in its collapsed direction. Its arbitrary - // search result cannot determine the winding of an outer loop. - let (du, dv) = (surface.uder(u, v), surface.vder(u, v)); - if du.cross(dv).magnitude2() <= 1e-12 * (du.magnitude2() + dv.magnitude2()).powi(2) { - return false; - } - let mut p = [u, v]; - let origin = *first.get_or_insert(p); - if let Some(prev) = previous { - for (d, x) in p.iter_mut().enumerate() { - if let Some(period) = periods.get(d).copied().flatten().filter(|p| *p > 0.0) { - *x -= ((*x - prev[d]) / period).round() * period; - } - } - let cross = (prev[0] - origin[0]) * (p[1] - origin[1]) - (p[0] - origin[0]) * (prev[1] - origin[1]); - area += cross; - magnitude += cross.abs(); - } - previous = Some(p); - } - } - let (Some(first), Some(last)) = (first, previous) else { return false }; - if periods.iter().enumerate().any(|(d, p)| p.is_some_and(|p| (first[d] - last[d]).abs() > p * 0.5)) { - return false; - } - area < -16.0 * f64::EPSILON * magnitude -} - -impl Builder { - fn vertex(&mut self, cx: &Ctx, id: u64) -> R { - if let Some(v) = self.vertices.get(&id) { - return Ok(v.clone()); - } - let e = entity(cx, id)?; - if e.name() != "VERTEX_POINT" { - return Err(format!("#{id}: expected VERTEX_POINT, found {}", e.name())); - } - let p = geom::point(cx, rid(e.params().get(1), "VERTEX_POINT")?)?; - let v = mt::Vertex::new(p); - self.vertices.insert(id, v.clone()); - Ok(v) - } - - /// Kernel edges (start to end) of an EDGE_CURVE. - fn edge_curve(&mut self, cx: &Ctx, id: u64) -> R> { - if let Some(e) = self.edges.get(&id) { - return Ok(e.clone()); - } - let e = entity(cx, id)?; - if e.name() != "EDGE_CURVE" { - return Err(format!("#{id}: unsupported edge {}", e.name())); - } - let p = e.params(); - let (vs_id, ve_id) = (rid(p.get(1), "edge start")?, rid(p.get(2), "edge end")?); - let vs = self.vertex(cx, vs_id)?; - let ve = self.vertex(cx, ve_id)?; - let sense = p.get(4).and_then(Param::as_bool).unwrap_or(true); - let g = geom::curve(cx, rid(p.get(3), "edge geometry")?, 0)?; - let closed = vs_id == ve_id; - let pieces = - guard("step edge", || geom::edge_pieces(&g, vs.point(), ve.point(), sense, closed, cx.tol, cx.snap).map_err(crate::KernelError::Failed)) - .map_err(|e| e.to_string())?; - let n = pieces.len(); - let mut out = Vec::with_capacity(n); - let mut cur = vs.clone(); - for (i, c) in pieces.into_iter().enumerate() { - let next = if i + 1 == n { ve.clone() } else { mt::Vertex::new(c.back()) }; - out.push(mt::Edge::new_unchecked(&cur, &next, c)); - cur = next; - } - self.edges.insert(id, out.clone()); - Ok(out) - } - - /// Edges of an ORIENTED_EDGE (or a bare EDGE_CURVE) in loop order. - fn oriented_edge(&mut self, cx: &Ctx, id: u64, depth: usize) -> R> { - if depth > 4 { - return Err("oriented edges nested too deeply".into()); - } - let e = entity(cx, id)?; - match e.name() { - "ORIENTED_EDGE" => { - let p = e.params(); - let inner = self.oriented_edge(cx, rid(p.get(3), "ORIENTED_EDGE")?, depth + 1)?; - if p.get(4).and_then(Param::as_bool).unwrap_or(true) { Ok(inner) } else { Ok(inner.iter().rev().map(mt::Edge::inverse).collect()) } - } - _ => self.edge_curve(cx, id), - } - } - - fn poly_loop(&mut self, cx: &Ctx, pts: &[u64]) -> R> { - let n = pts.len(); - if !(3..=MAX_LOOP).contains(&n) { - return Err(format!("polygon loop with {n} points")); - } - let mut verts = Vec::with_capacity(n); - for &id in pts { - if let Some(v) = self.vertices.get(&id) { - verts.push(v.clone()); - } else { - let v = mt::Vertex::new(geom::point(cx, id)?); - self.vertices.insert(id, v.clone()); - verts.push(v); - } - } - let mut out = Vec::with_capacity(n); - for i in 0..n { - let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % n)) else { continue }; - if let Some(e) = self.poly_edges.get(&(b, a)) { - out.push(e.inverse()); - continue; - } - let (Some(va), Some(vb)) = (verts.get(i), verts.get((i + 1) % n)) else { continue }; - if va.point().distance(vb.point()) < 1e-12 { - return Err("polygon loop with repeated points".into()); - } - let e = mt::Edge::try_new(va, vb, mt::Curve::Line(mt::Line(va.point(), vb.point()))).map_err(|e| format!("polygon edge: {e}"))?; - self.poly_edges.insert((a, b), e.clone()); - out.push(e); - } - Ok(out) - } - - /// A face bound as a wire (oriented by the bound's orientation), or `None` for a vertex loop. - fn bound(&mut self, cx: &Ctx, id: u64) -> R> { - let b = entity(cx, id)?; - if !matches!(b.name(), "FACE_BOUND" | "FACE_OUTER_BOUND") { - return Err(format!("#{id}: unsupported face bound {}", b.name())); - } - let lp_id = rid(b.params().get(1), "face bound loop")?; - let orient = b.params().get(2).and_then(Param::as_bool).unwrap_or(true); - let lp = entity(cx, lp_id)?; - let edges = match lp.name() { - "EDGE_LOOP" => { - let ids = refs(lp.params().get(1)); - if ids.is_empty() || ids.len() > MAX_LOOP { - return Err(format!("edge loop with {} edges", ids.len())); - } - let mut v = Vec::new(); - for oe in ids { - v.extend(self.oriented_edge(cx, oe, 0)?); - } - v - } - "POLY_LOOP" => self.poly_loop(cx, &refs(lp.params().get(1)))?, - "VERTEX_LOOP" => return Ok(None), - n => return Err(format!("unsupported loop {n}")), - }; - let mut w: mt::Wire = edges.into(); - if !w.is_closed() { - return Err("face boundary is not a closed loop".into()); - } - if !orient { - w.invert(); - } - Ok(Some(w)) - } - - /// A face (ADVANCED_FACE, FACE_SURFACE, ORIENTED_FACE or a polygonal FACE). - fn face(&mut self, cx: &Ctx, id: u64, depth: usize) -> R { - if depth > 4 { - return Err("oriented faces nested too deeply".into()); - } - self.faces += 1; - if self.faces > MAX_FACES { - return Err(format!("more than {MAX_FACES} faces")); - } - let e = entity(cx, id)?; - let p = e.params(); - if e.name() == "ORIENTED_FACE" { - let mut f = self.face(cx, rid(p.get(2), "ORIENTED_FACE")?, depth + 1)?; - if !p.get(3).and_then(Param::as_bool).unwrap_or(true) { - f.invert(); - } - return Ok(f); - } - if !matches!(e.name(), "ADVANCED_FACE" | "FACE_SURFACE" | "FACE") { - return Err(format!("unsupported face {}", e.name())); - } - let bounds = refs(p.get(1)); - if bounds.len() > MAX_BOUNDS { - return Err(format!("a face with more than {MAX_BOUNDS} boundary loops")); - } - let mut wires = Vec::new(); - let mut outer = None; - let mut edges = 0usize; - for b in bounds { - if let Some(w) = self.bound(cx, b)? { - if entity(cx, b)?.name() == "FACE_OUTER_BOUND" { - outer = Some(wires.len()); - } - edges = edges.saturating_add(w.len()); - if edges > MAX_LOOP { - return Err(format!("a face with more than {MAX_LOOP} boundary edges")); - } - wires.push(w); - } - } - if wires.is_empty() { - return Err("face without boundary edges".into()); - } - let extent: Vec = wires - .iter() - .flat_map(|w| w.edge_iter()) - .flat_map(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=8).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 8.0)).collect::>() - }) - .collect(); - // Seam edges: used twice by the face's loops. - let mut uses: HashMap = HashMap::new(); - for e in wires.iter().flat_map(|w| w.edge_iter()) { - *uses.entry(e.id()).or_default() += 1; - } - let mut seen = std::collections::HashSet::new(); - let seam: Vec = wires - .iter() - .flat_map(|w| w.edge_iter()) - .filter(|e| uses.get(&e.id()).copied().unwrap_or(0) > 1 && seen.insert(e.id())) - .flat_map(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=8).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 8.0)).collect::>() - }) - .collect(); - let mut surface = if e.name() == "FACE" { - crate::plane_fit::plane_through(&extent).map(mt::Surface::Plane).ok_or("polygonal face without a plane")? - } else { - let sid = rid(p.get(2), "face geometry")?; - let sense = p.get(3).and_then(Param::as_bool).unwrap_or(true); - guard("step surface", || geom::surface(cx, sid, &extent, &seam, sense, 0).map_err(crate::KernelError::Failed)) - .map_err(|e| e.to_string())? - }; - // An explicit outer bound encloses the face. Some exporters give its surface the - // opposite sense; treating that loop as a hole meshes the rest of the supporting - // cylinder instead. Match the surface to the outer loop without reversing - // shared topological edges. Winding loops (bands and pole seams) are left alone. - if e.name() != "FACE" && seam.is_empty() && outer.and_then(|i| wires.get(i)).is_some_and(|w| reversed_outer(&surface, w, cx.tol)) { - let sid = rid(p.get(2), "face geometry")?; - let sense = p.get(3).and_then(Param::as_bool).unwrap_or(true); - 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 = 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. - let wires: Vec = match &surface { - mt::Surface::RevolutedCurve(rc) => { - let (o, a) = (rc.entity().origin(), rc.entity().axis()); - let dist = |e: &mt::Edge| { - let v = e.front().point() - o; - (v - a * v.dot(a)).magnitude() - }; - wires - .into_iter() - .map(|w| { - let edges: Vec = w.edge_iter().cloned().collect(); - let start = edges.iter().enumerate().max_by(|x, y| dist(x.1).total_cmp(&dist(y.1))).map(|(i, _)| i).unwrap_or(0); - edges.iter().skip(start).chain(edges.iter().take(start)).cloned().collect::>().into() - }) - .collect() - } - // A loop passing a vertex twice (a figure eight through a pole, as written for a - // torus whose tube touches its axis) starts at a vertex it passes once. - _ => wires - .into_iter() - .map(|w| { - let edges: Vec = w.edge_iter().cloned().collect(); - // Counted once: a loop may hold 100,000 edges, and asking per edge how - // often its front vertex appears would scan them all again each time. - let mut fronts: HashMap<_, usize> = HashMap::new(); - for e in &edges { - *fronts.entry(e.front().id()).or_default() += 1; - } - let passes = |e: &mt::Edge| fronts.get(&e.front().id()).copied().unwrap_or(0); - match edges.first().map(passes) { - Some(n) if n > 1 => { - let start = edges.iter().position(|e| passes(e) == 1).unwrap_or(0); - edges.iter().skip(start).chain(edges.iter().take(start)).cloned().collect::>().into() - } - _ => w, - } - }) - .collect(), - }; - match mt::Face::try_new(wires.clone(), surface.clone()) { - Ok(f) => Ok(f), - // Faces on periodic surfaces run along a seam edge twice: valid in STEP. - Err(truck_topology::errors::Error::NotSimpleWire) => Ok(mt::Face::new_unchecked(wires, surface)), - Err(e) => Err(format!("face: {e}")), - } - } - - fn shell(&mut self, cx: &Ctx, id: u64, failed: &mut Vec) -> R<(mt::Shell, bool, usize, Vec)> { - let e = entity(cx, id)?; - let p = e.params(); - let (faces, flip, closed) = match e.name() { - "CLOSED_SHELL" => (refs(p.get(1)), false, true), - "OPEN_SHELL" => (refs(p.get(1)), false, false), - "ORIENTED_CLOSED_SHELL" | "ORIENTED_OPEN_SHELL" => { - let inner = entity(cx, rid(p.get(2), "oriented shell")?)?; - (refs(inner.params().get(1)), !p.get(3).and_then(Param::as_bool).unwrap_or(true), e.name() == "ORIENTED_CLOSED_SHELL") - } - n => return Err(format!("unsupported shell {n}")), - }; - if faces.len() > MAX_FACES { - return Err(format!("shell with {} faces", faces.len())); - } - let mut out = Vec::with_capacity(faces.len()); - let mut origin = Vec::with_capacity(faces.len()); - for f in faces { - match self.face(cx, f, 0) { - Ok(mut face) => { - if flip { - face.invert(); - } - out.push(face); - origin.push(f); - } - Err(err) => { - if self.faces > MAX_FACES { - return Err(err); - } - failed.push(format!("face #{f}: {err}")); - } - } - } - if out.is_empty() { - return Err("no face could be imported".into()); - } - let read = out.len(); - let ball = match (out.as_slice(), origin.as_slice()) { - ([face], [file_face]) => whole_sphere(cx, *file_face, face).map(|patches| (*file_face, patches)), - _ => None, - }; - if let Some((file_face, patches)) = ball { - origin = vec![file_face; patches.len()]; - out = patches; - } - let out = super::split::split_bands(out, &mut origin, failed, cx.tol); - Ok((out.into(), closed, read, origin)) - } -} - -/// A ball written as one face on a sphere bounded only by its seam, run out and back from pole -/// to pole. Truck meshes a face on a revolved surface in parameter space, where that loop -/// encloses nothing, so the ball is built as the kernel's own sphere instead: six patches with -/// no pole or seam inside them (`build::sphere_patch_faces`), turned inside out for a void. -/// `None` for any other face. -fn whole_sphere(cx: &Ctx, file_face: u64, face: &mt::Face) -> Option> { - use mt::{ParametricSurface3D, SearchParameter}; - let surface = entity(cx, file_face).ok()?.params().get(2).and_then(Param::as_ref_id)?; - if entity(cx, surface).ok()?.name() != "SPHERICAL_SURFACE" { - return None; - } - let wires = face.boundaries(); - let edges: Vec<&mt::Edge> = wires.iter().flat_map(|w| w.edge_iter()).collect(); - let mut uses: HashMap = HashMap::new(); - let mut poles: Vec = Vec::new(); - for e in &edges { - *uses.entry(e.id()).or_default() += 1; - for v in [e.front(), e.back()] { - if !poles.iter().any(|p| p.id() == v.id()) { - poles.push(v.clone()); - } - } - } - // Every edge a seam (used once each way), and the two vertices it joins are the poles. - if uses.is_empty() || uses.values().any(|n| *n != 2) { - return None; - } - let [a, b] = poles.as_slice() else { return None }; - let (a, b) = (a.point(), b.point()); - let center = a + (b - a) * 0.5; - let radius = a.distance(b) * 0.5; - let tol = cx.tol.max(radius * 1e-6); - // The seam is a meridian: all of it on the sphere whose diameter joins the poles. - let samples = |e: &&mt::Edge| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=8).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 8.0)) - }; - if !(radius.is_finite() && radius > tol) || !edges.iter().flat_map(samples).all(|p| (p.distance(center) - radius).abs() <= tol) { - return None; - } - // Ball or void: the face's normal at the middle of the seam, against the way out of the centre. - let probe = edges.first().and_then(|e| samples(e).nth(4))?; - let oriented = face.oriented_surface(); - let (u, v) = oriented.search_parameter(probe, mt::SPHint2D::None, 100)?; - let outward = oriented.normal(u, v).dot(probe - center) > 0.0; - let z = (crate::body::from_p3(a) - crate::body::from_p3(b)).normalized()?; - let x = z.any_perp(); - let c = crate::body::from_p3(center); - let mut patches = guard("step sphere", || crate::build::sphere_patch_faces(c, radius, [x, z.cross(x), z])).ok()?; - if !outward { - for f in &mut patches { - f.invert(); - } - } - Some(patches) -} - -/// Read a solid-like representation item: MANIFOLD_SOLID_BREP, BREP_WITH_VOIDS, FACETED_BREP, -/// or a SHELL_BASED_SURFACE_MODEL (closed shells give solids, open ones open bodies). -pub(crate) fn read_item(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - let p = e.params(); - let mut b = Builder::default(); - let mut failed = Vec::new(); - let mut shells = Vec::new(); - let mut closed = true; - let mut file_faces = 0; - // The file face each kernel face comes from (in face order). - let mut face_origin = Vec::new(); - match e.name() { - "MANIFOLD_SOLID_BREP" | "FACETED_BREP" | "BREP_WITH_VOIDS" => { - let (s, c, n, o) = b.shell(cx, rid(p.get(1), "brep outer shell")?, &mut failed)?; - closed &= c; - file_faces += n; - shells.push(s); - face_origin.extend(o); - if e.name() == "BREP_WITH_VOIDS" { - for v in refs(p.get(2)) { - match b.shell(cx, v, &mut failed) { - Ok((s, c, n, o)) => { - closed &= c; - file_faces += n; - shells.push(s); - face_origin.extend(o); - } - Err(err) => failed.push(format!("void shell #{v}: {err}")), - } - } - } - } - "SHELL_BASED_SURFACE_MODEL" => { - for s in refs(p.get(1)) { - match b.shell(cx, s, &mut failed) { - Ok((s, c, n, o)) => { - closed &= c; - file_faces += n; - shells.push(s); - face_origin.extend(o); - } - Err(err) => failed.push(format!("shell #{s}: {err}")), - } - } - } - n => return Err(format!("unsupported item {n}")), - } - if shells.is_empty() { - return Err(failed.first().cloned().unwrap_or_else(|| "no shells".into())); - } - // `mt::Solid::try_new` only checks each shell (non-empty, connected, closed, no singular - // vertex) and hands the shells back unchanged (truck-topology 0.6.0), so the same checks run - // here on the borrowed shells. The successful path used to clone every face, edge, vertex, - // curve and surface to keep a copy that was then dropped. - let checked = guard("step solid", || { - for shell in &shells { - if shell.is_empty() { - return Err(crate::KernelError::Failed("empty shell".into())); - } - if !shell.is_connected() { - return Err(crate::KernelError::Failed("shell is not connected".into())); - } - if shell.shell_condition() != mt::ShellCondition::Closed { - return Err(crate::KernelError::Failed("shell is not closed".into())); - } - if !shell.singular_vertices().is_empty() { - return Err(crate::KernelError::Failed("shell is not manifold".into())); - } - } - Ok(()) - }); - 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 }) -} diff --git a/crates/kernel/src/step_in/conic_tests.rs b/crates/kernel/src/step_in/conic_tests.rs index 1f25923e8..abbe11896 100644 --- a/crates/kernel/src/step_in/conic_tests.rs +++ b/crates/kernel/src/step_in/conic_tests.rs @@ -4,10 +4,6 @@ use std::f64::consts::{FRAC_PI_4, PI}; -use mt::{BoundedCurve, InnerSpace, ParametricCurve}; -use truck_modeling as mt; - -use super::geom::{Frame, hyperbola_arc, parabola_arc}; use super::*; use crate::{measure, step_export}; @@ -18,47 +14,6 @@ const CONTEXT: &str = "#90=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#81),#91);\n#9 /// Height of the cone pieces: the 45° cone `x² + y² = z²` up to `z = H`. const H: f64 = 10.0; -#[test] -fn extruded_ellipse_seam_uses_profile_angles_for_oblique_sweeps() { - use mt::{MetricSpace, ParametricSurface}; - - let text = format!( - "{HEAD} -#1=CARTESIAN_POINT('',(10.,-20.,3.)); -#2=DIRECTION('',(0.,0.,1.)); -#3=DIRECTION('',(1.,0.,0.)); -#4=AXIS2_PLACEMENT_3D('',#1,#2,#3); -#5=ELLIPSE('',#4,9.,4.); -#6=DIRECTION('',(0.5,0.25,1.)); -#7=VECTOR('',#6,1.); -#8=SURFACE_OF_LINEAR_EXTRUSION('',#5,#7); -{TAIL}" - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let origin = mt::Point3::new(10.0, -20.0, 3.0); - let d = mt::Vector3::new(0.5, 0.25, 1.0).normalize(); - let point = |angle: f64, h: f64| origin + mt::Vector3::new(9.0 * angle.cos(), 4.0 * angle.sin(), 0.0) + d * h; - let extent: Vec<_> = [-0.04, 0.0, 0.04].into_iter().flat_map(|a| [point(a, 0.0), point(a, 10.0)]).collect(); - for seam in [Vec::new(), vec![point(-0.04, 0.0), point(-0.04, 10.0)]] { - let surface = geom::surface(&cx, 8, &extent, &seam, true, 0).unwrap(); - for i in 0..=16 { - for j in 0..=4 { - let q = surface.subs(i as f64 / 16.0, j as f64 / 4.0) - origin; - let q = q - d * (q.z / d.z); - assert!(((q.x / 9.0).powi(2) + (q.y / 4.0).powi(2) - 1.0).abs() < 1e-12); - } - } - let start = surface.subs(0.0, 0.5); - let q = start - d * ((start.z - origin.z) / d.z); - if seam.is_empty() { - assert!(q.distance(point(std::f64::consts::PI, 0.0)) < 1e-9); - } else { - assert!(q.distance(point(-0.04, 0.0)) < 1e-9); - } - } -} - fn rel(a: f64, b: f64) -> f64 { (a - b).abs() / b.abs().max(1e-9) } @@ -176,6 +131,8 @@ fn hyperbola_bounded_faces_import() { assert!(rel(want, 175.447_506_9) < 1e-9, "{want}"); let imp = import_piece(&hyperbola_piece(), want); round_trip(&imp, want); + let v = super::tests::schema_4_volume(&hyperbola_piece()); + assert!(rel(v, want) < 1e-4, "schema 4: {v} vs {want}"); } #[test] @@ -184,34 +141,8 @@ fn parabola_bounded_faces_import() { assert!(rel(want, 447.014_684_29) < 1e-9, "{want}"); let imp = import_piece(¶bola_piece(), want); round_trip(&imp, want); -} - -/// The kernel curves lie exactly on the conics, end to end, whichever way they run. -#[test] -fn conic_arcs_are_exact() { - let f = Frame { o: mt::Point3::new(1.0, 2.0, 3.0), x: mt::Vector3::unit_y(), y: mt::Vector3::unit_z(), z: mt::Vector3::unit_x() }; - let local = |p: mt::Point3| ((p - f.o).dot(f.x), (p - f.o).dot(f.y), (p - f.o).dot(f.z)); - for (t0, t1) in [(-1.5, 2.0), (3.0, -0.25), (0.0, 7.5)] { - let c = hyperbola_arc(&f, 3.0, 2.0, t0, t1); - let (s0, s1) = c.range_tuple(); - for i in 0..=200 { - let (x, y, z) = local(c.subs(s0 + (s1 - s0) * i as f64 / 200.0)); - assert!((x * x / 9.0 - y * y / 4.0 - 1.0).abs() < 1e-9 && x > 0.0 && z.abs() < 1e-12, "{x} {y}"); - } - let (x, y, _) = local(c.subs(s0)); - assert!((x - 3.0 * f64::cosh(t0)).abs() < 1e-9 && (y - 2.0 * f64::sinh(t0)).abs() < 1e-9); - let (x, y, _) = local(c.subs(s1)); - assert!((x - 3.0 * f64::cosh(t1)).abs() < 1e-9 && (y - 2.0 * f64::sinh(t1)).abs() < 1e-9); - - let c = parabola_arc(&f, 1.5, t0, t1); - let (s0, s1) = c.range_tuple(); - for i in 0..=200 { - let (x, y, z) = local(c.subs(s0 + (s1 - s0) * i as f64 / 200.0)); - assert!((y * y - 4.0 * 1.5 * x).abs() < 1e-9 * (1.0 + x.abs()) && z.abs() < 1e-12, "{x} {y}"); - } - let (x, y, _) = local(c.subs(s1)); - assert!((x - 1.5 * t1 * t1).abs() < 1e-9 && (y - 3.0 * t1).abs() < 1e-9); - } + let v = super::tests::schema_4_volume(¶bola_piece()); + assert!(rel(v, want) < 1e-4, "schema 4: {v} vs {want}"); } /// Hostile conics are errors (the face is reported and left out), never panics. @@ -269,7 +200,7 @@ fn a_cone_bounded_only_by_its_base_circle_reaches_its_point() { 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); + let top = body.mesh(&crate::MeshTolerance::chord(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}"); } } diff --git a/crates/kernel/src/step_in/geom.rs b/crates/kernel/src/step_in/geom.rs deleted file mode 100644 index e5f27f320..000000000 --- a/crates/kernel/src/step_in/geom.rs +++ /dev/null @@ -1,1237 +0,0 @@ -//! STEP geometry (ISO 10303-42 entities) to kernel curves and surfaces. -//! -//! Points, placements, lines, conics (ellipses, hyperbolas and parabolas), B-splines (plain and rational), elementary surfaces and -//! swept surfaces, with exact offsets of planes, cylinders, cones, spheres and regular tori. -//! Free-form offsets and offsets through collapsed radii remain explicit import warnings. -//! Edge curves are trimmed to their vertices here, so every kernel edge runs -//! exactly from its start vertex to its end vertex. Lengths are scaled to millimetres while -//! reading. - -use std::f64::consts::{FRAC_PI_2, PI, TAU}; - -use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::Ring; -use truck_modeling as mt; - -use super::Ctx; -use super::p21::{Entity, Param}; - -/// Geometry nesting we follow (trimmed curve of a surface curve of …). -const MAX_GEOM_DEPTH: usize = 8; -/// Most control points in one B-spline (per direction product for surfaces). -const MAX_CTRL: usize = 1_000_000; -const MAX_COORD: f64 = 1e9; - -pub(crate) type R = std::result::Result; - -/// An orthonormal frame (AXIS2_PLACEMENT_3D). -#[derive(Clone, Copy, Debug)] -pub(crate) struct Frame { - pub o: mt::Point3, - pub x: mt::Vector3, - pub y: mt::Vector3, - pub z: mt::Vector3, -} - -impl Frame { - pub fn matrix(&self) -> mt::Matrix4 { - mt::Matrix4::from_cols(self.x.extend(0.0), self.y.extend(0.0), self.z.extend(0.0), self.o.to_homogeneous()) - } - fn at(&self, cx: f64, cy: f64, cz: f64) -> mt::Point3 { - self.o + self.x * cx + self.y * cy + self.z * cz - } -} - -/// A curve before trimming. -#[derive(Clone, Debug)] -pub(crate) enum CurveGeo { - Line { - p: mt::Point3, - d: mt::Vector3, - }, - /// Ellipse (`a == b` for circles) in the frame's XY plane. - Conic { - f: Frame, - a: f64, - b: f64, - }, - /// Hyperbola branch `o + a·cosh t·x + b·sinh t·y` in the frame's XY plane. - Hyperbola { - f: Frame, - a: f64, - b: f64, - }, - /// Parabola `o + focal·(t²·x + 2t·y)` in the frame's XY plane. - Parabola { - f: Frame, - focal: f64, - }, - BSpline(mt::BSplineCurve), - Nurbs(mt::NurbsCurve), -} - -pub(crate) fn entity<'a>(cx: &Ctx<'a>, id: u64) -> R<&'a Entity> { - cx.ex.get(id).ok_or_else(|| format!("missing entity #{id}")) -} - -fn ent_of<'a>(cx: &Ctx<'a>, p: Option<&Param>, what: &str) -> R<(u64, &'a Entity)> { - let id = p.and_then(Param::as_ref_id).ok_or_else(|| format!("{what}: expected a reference"))?; - Ok((id, entity(cx, id)?)) -} - -fn num(p: Option<&Param>, what: &str) -> R { - let x = p.and_then(Param::as_f64).ok_or_else(|| format!("{what}: expected a number"))?; - if x.is_finite() && x.abs() < MAX_COORD { Ok(x) } else { Err(format!("{what}: {x} out of range")) } -} - -fn length(cx: &Ctx, p: Option<&Param>, what: &str) -> R { - Ok(num(p, what)? * cx.len) -} - -pub(crate) fn point(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - if e.name() != "CARTESIAN_POINT" { - return Err(format!("#{id}: expected CARTESIAN_POINT, found {}", e.name())); - } - let c = e.params().get(1).and_then(Param::as_list).ok_or("CARTESIAN_POINT without coordinates")?; - let g = |i: usize| -> R { if i < c.len() { num(c.get(i), "coordinate") } else { Ok(0.0) } }; - if c.is_empty() || c.len() > 3 { - return Err(format!("#{id}: point with {} coordinates", c.len())); - } - Ok(mt::Point3::new(g(0)?, g(1)?, g(2)?) * cx.len) -} - -pub(super) fn direction(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - if e.name() != "DIRECTION" { - return Err(format!("#{id}: expected DIRECTION, found {}", e.name())); - } - let c = e.params().get(1).and_then(Param::as_list).ok_or("DIRECTION without ratios")?; - let g = |i: usize| -> R { if i < c.len() { num(c.get(i), "direction") } else { Ok(0.0) } }; - let v = mt::Vector3::new(g(0)?, g(1)?, g(2)?); - let m = v.magnitude(); - if m > 1e-12 && m.is_finite() { Ok(v / m) } else { Err(format!("#{id}: zero direction")) } -} - -fn any_perpendicular(z: mt::Vector3) -> mt::Vector3 { - let a = if z.x.abs() < 0.9 { mt::Vector3::unit_x() } else { mt::Vector3::unit_y() }; - let x = a - z * a.dot(z); - x / x.magnitude() -} - -/// AXIS2_PLACEMENT_3D (or 2D, as a frame in the XY plane). -pub(crate) fn frame(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - let p = e.params(); - let o = point(cx, p.get(1).and_then(Param::as_ref_id).ok_or("placement without location")?)?; - let (z, rf) = match e.name() { - "AXIS2_PLACEMENT_3D" => { - let z = match p.get(2).and_then(Param::as_ref_id) { - Some(d) => direction(cx, d)?, - None => mt::Vector3::unit_z(), - }; - (z, p.get(3).and_then(Param::as_ref_id)) - } - "AXIS2_PLACEMENT_2D" => (mt::Vector3::unit_z(), p.get(2).and_then(Param::as_ref_id)), - n => return Err(format!("#{id}: expected AXIS2_PLACEMENT_3D, found {n}")), - }; - let x = match rf { - Some(d) => { - let r = direction(cx, d)?; - let x = r - z * r.dot(z); - if x.magnitude() > 1e-9 { x / x.magnitude() } else { any_perpendicular(z) } - } - None => any_perpendicular(z), - }; - Ok(Frame { o, x, y: z.cross(x), z }) -} - -/// AXIS1_PLACEMENT: origin and unit axis. -pub(crate) fn axis1(cx: &Ctx, id: u64) -> R<(mt::Point3, mt::Vector3)> { - let e = entity(cx, id)?; - let p = e.params(); - let o = point(cx, p.get(1).and_then(Param::as_ref_id).ok_or("axis without location")?)?; - let d = match p.get(2).and_then(Param::as_ref_id) { - Some(d) => direction(cx, d)?, - None => mt::Vector3::unit_z(), - }; - Ok((o, d)) -} - -/// `expected` is the knot count the control points and degree imply. Multiplicities are -/// expanded into one value each, so the sum has to be checked before the expansion: 20 million -/// knots of multiplicity 64 would build a 10 GB vector that the length check then rejects, and -/// an allocation failure aborts the process where an error does not. -fn knot_vec(mults: Option<&Param>, knots: Option<&Param>, expected: usize) -> R { - let m: Vec = mults - .and_then(Param::as_list) - .ok_or("B-spline without knot multiplicities")? - .iter() - .map(|x| x.as_i64().filter(|v| (1..=64).contains(v)).map(|v| v as usize).ok_or_else(|| "bad knot multiplicity".to_string())) - .collect::>()?; - let k: Vec = knots.and_then(Param::as_list).ok_or("B-spline without knots")?.iter().map(|x| num(Some(x), "knot")).collect::>()?; - if m.len() != k.len() || k.is_empty() || k.windows(2).any(|w| w.first() > w.get(1)) { - return Err("inconsistent knot vector".into()); - } - if m.len() > expected || m.iter().try_fold(0usize, |a, v| a.checked_add(*v)) != Some(expected) { - return Err("knot multiplicities do not match the control points".into()); - } - mt::KnotVec::from_single_multi(spanning_one(k), m).map_err(|e| format!("knot vector: {e}")) -} - -/// Shortest parameter range a spline is read with. -const MIN_KNOT_RANGE: f64 = 1.0; - -/// `knots` stretched, when they span less than [`MIN_KNOT_RANGE`], to span exactly that from the -/// same first knot. A STEP writer may parameterize a spline over any range (some write a few -/// millionths, as if in metres of a part drawn in millimetres), and the kernel tells parameters -/// apart only to a fixed tolerance (1e-6): over such a range it took distinct knots for one, and -/// trimming an edge to its vertices dropped a control point. Stretching the knots changes the -/// parameters, never the curve (every point is where it was), and nothing read from the file -/// refers to them: edges are trimmed by their vertices. -fn spanning_one(knots: Vec) -> Vec { - let (Some(&first), Some(&last)) = (knots.first(), knots.last()) else { return knots }; - let range = last - first; - if !(range > 0.0 && range < MIN_KNOT_RANGE) { - return knots; - } - let scale = MIN_KNOT_RANGE / range; - let mut out: Vec = knots.iter().map(|k| first + (k - first) * scale).collect(); - // The last knot exactly at the end of the range (the product can miss it by a rounding). - if let Some(k) = out.last_mut() { - *k = first + MIN_KNOT_RANGE; - } - out -} - -fn generated_knots(kind: &str, n_ctrl: usize, degree: usize) -> R { - if n_ctrl <= degree { - return Err("too few control points".into()); - } - let n = n_ctrl + degree + 1; - let v: Vec = match kind { - "BEZIER" => { - if n_ctrl != degree + 1 { - // Piecewise Bézier: segments of `degree` with full interior multiplicity. - let segs = (n_ctrl - 1) / degree.max(1); - if segs * degree + 1 != n_ctrl { - return Err("Bezier control point count".into()); - } - let mut v = vec![0.0; degree + 1]; - for s in 1..segs { - v.extend(std::iter::repeat_n(s as f64, degree)); - } - v.extend(std::iter::repeat_n(segs as f64, degree + 1)); - v - } else { - let mut v = vec![0.0; degree + 1]; - v.extend(std::iter::repeat_n(1.0, degree + 1)); - v - } - } - "UNIFORM" => (0..n).map(|i| i as f64 - degree as f64).collect(), - _ => { - // Quasi-uniform: clamped ends, uniform interior. - let inner = n_ctrl - degree; - let mut v = vec![0.0; degree + 1]; - v.extend((1..inner).map(|i| i as f64)); - v.extend(std::iter::repeat_n(inner as f64, degree + 1)); - v - } - }; - Ok(mt::KnotVec::from(v)) -} - -/// The ends of the part of a knot vector where a B-spline of `degree` is defined, when its end -/// knots repeat fewer than `degree + 1` times (an unclamped or periodic knot vector, as -/// OpenCascade writes closed B-splines and `UNIFORM_*` curves and surfaces have): only between -/// knot `degree` and knot `len - degree - 1` do the basis functions sum to one. `None` for a -/// clamped vector, whose whole range is the domain, and for one whose domain is a point. -fn unclamped_ends(kv: &mt::KnotVec, degree: usize) -> Option<(Option, Option)> { - let n = kv.len(); - if n < 2 * (degree + 1) || !(kv[n - 1 - degree] - kv[degree] > mt::TOLERANCE) { - return None; - } - let lo = (kv.multiplicity(0) <= degree).then(|| kv[degree]); - let hi = (kv.multiplicity(n - 1) <= degree).then(|| kv[n - 1 - degree]); - (lo.is_some() || hi.is_some()).then_some((lo, hi)) -} - -/// `c` restricted to its domain, with clamped ends (exact: knots are inserted at the domain's -/// ends and the control points beyond them dropped). The kernel takes a B-spline's whole knot -/// range as its parameter range, and an unclamped curve evaluated outside its domain leaves -/// its control polygon (a rational one divides by zero at the outermost knots). -fn clamped_curve + mt::Tolerance>(mut c: mt::BSplineCurve

) -> mt::BSplineCurve

{ - let Some((lo, hi)) = unclamped_ends(c.knot_vec(), c.degree()) else { return c }; - if let Some(lo) = lo { - c = c.cut(lo); - } - if let Some(hi) = hi { - let _ = c.cut(hi); - } - c -} - -/// [`clamped_curve`] for a surface, in each direction whose knot vector is unclamped. -fn clamped_surface + mt::Tolerance>(mut s: mt::BSplineSurface

) -> mt::BSplineSurface

{ - if let Some((lo, hi)) = unclamped_ends(s.uknot_vec(), s.udegree()) { - if let Some(lo) = lo { - s = s.ucut(lo); - } - if let Some(hi) = hi { - let _ = s.ucut(hi); - } - } - if let Some((lo, hi)) = unclamped_ends(s.vknot_vec(), s.vdegree()) { - if let Some(lo) = lo { - s = s.vcut(lo); - } - if let Some(hi) = hi { - let _ = s.vcut(hi); - } - } - s -} - -fn weights_list(p: Option<&Param>) -> R> { - p.and_then(Param::as_list) - .ok_or("rational B-spline without weights")? - .iter() - .map(|w| num(Some(w), "weight").and_then(|w| if w > 0.0 { Ok(w) } else { Err("non-positive weight".into()) })) - .collect() -} - -fn bspline_curve(cx: &Ctx, e: &Entity) -> R { - // Common part (B_SPLINE_CURVE): degree, control points, form, closed, self-intersect. - let (base, knots, kind): (Vec, Option<(Option<&Param>, Option<&Param>)>, &str) = if e.is_complex() { - let b = e.record("B_SPLINE_CURVE").ok_or("complex curve without B_SPLINE_CURVE")?; - let mut base = vec![Param::Str(String::new())]; - base.extend(b.iter().cloned()); - let k = e.record("B_SPLINE_CURVE_WITH_KNOTS").map(|k| (k.first(), k.get(1))); - let kind = if e.has("BEZIER_CURVE") { - "BEZIER" - } else if e.has("UNIFORM_CURVE") { - "UNIFORM" - } else { - "QUASI" - }; - (base, k, kind) - } else { - let p = e.params(); - let k = (e.name() == "B_SPLINE_CURVE_WITH_KNOTS").then(|| (p.get(6), p.get(7))); - let kind = match e.name() { - "BEZIER_CURVE" => "BEZIER", - "UNIFORM_CURVE" => "UNIFORM", - _ => "QUASI", - }; - (p.to_vec(), k, kind) - }; - let degree = base.get(1).and_then(Param::as_i64).filter(|d| (1..=32).contains(d)).ok_or("bad B-spline degree")? as usize; - let ctrl_ids = base.get(2).and_then(Param::as_list).ok_or("B-spline without control points")?; - if ctrl_ids.len() > MAX_CTRL { - return Err("B-spline with too many control points".into()); - } - let ctrl: Vec = ctrl_ids.iter().map(|c| point(cx, c.as_ref_id().ok_or("bad control point")?)).collect::>()?; - let kv = match knots { - Some((m, k)) => knot_vec(m, k, ctrl.len() + degree + 1)?, - None => generated_knots(kind, ctrl.len(), degree)?, - }; - if kv.len() != ctrl.len() + degree + 1 { - return Err(format!("B-spline knot count {} does not match {} control points of degree {degree}", kv.len(), ctrl.len())); - } - let bsp = mt::BSplineCurve::try_new(kv, ctrl).map_err(|e| format!("B-spline: {e}"))?; - match e.record("RATIONAL_B_SPLINE_CURVE") { - Some(r) => { - let w = weights_list(r.first())?; - let n = mt::NurbsCurve::::try_from_bspline_and_weights(bsp, w).map_err(|e| format!("rational B-spline: {e}"))?; - Ok(CurveGeo::Nurbs(mt::NurbsCurve::new(clamped_curve(n.into_non_rationalized())))) - } - None => Ok(CurveGeo::BSpline(clamped_curve(bsp))), - } -} - -/// A STEP curve entity (unbounded or bounded). -pub(crate) fn curve(cx: &Ctx, id: u64, depth: usize) -> R { - if depth > MAX_GEOM_DEPTH { - return Err("curve definitions nested too deeply".into()); - } - let e = entity(cx, id)?; - let p = e.params(); - if e.is_complex() { - return bspline_curve(cx, e); - } - match e.name() { - "LINE" => { - let pt = point(cx, p.get(1).and_then(Param::as_ref_id).ok_or("LINE without point")?)?; - let (_, v) = ent_of(cx, p.get(2), "LINE vector")?; - let d = direction(cx, v.params().get(1).and_then(Param::as_ref_id).ok_or("VECTOR without direction")?)?; - Ok(CurveGeo::Line { p: pt, d }) - } - "CIRCLE" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("CIRCLE without placement")?)?; - let r = length(cx, p.get(2), "radius")?; - if r <= 0.0 { - return Err("circle radius must be positive".into()); - } - Ok(CurveGeo::Conic { f, a: r, b: r }) - } - "ELLIPSE" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("ELLIPSE without placement")?)?; - let (a, b) = (length(cx, p.get(2), "semi axis")?, length(cx, p.get(3), "semi axis")?); - if a <= 0.0 || b <= 0.0 { - return Err("ellipse axes must be positive".into()); - } - Ok(CurveGeo::Conic { f, a, b }) - } - "HYPERBOLA" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("HYPERBOLA without placement")?)?; - let (a, b) = (length(cx, p.get(2), "semi axis")?, length(cx, p.get(3), "semi imaginary axis")?); - if a <= 0.0 || b <= 0.0 { - return Err("hyperbola axes must be positive".into()); - } - Ok(CurveGeo::Hyperbola { f, a, b }) - } - "PARABOLA" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("PARABOLA without placement")?)?; - let focal = length(cx, p.get(2), "focal distance")?; - if focal == 0.0 { - return Err("parabola focal distance must not be zero".into()); - } - Ok(CurveGeo::Parabola { f, focal }) - } - "B_SPLINE_CURVE_WITH_KNOTS" | "BEZIER_CURVE" | "UNIFORM_CURVE" | "QUASI_UNIFORM_CURVE" => bspline_curve(cx, e), - "POLYLINE" => { - let pts: Vec = p - .get(1) - .and_then(Param::as_list) - .ok_or("POLYLINE without points")? - .iter() - .map(|c| point(cx, c.as_ref_id().ok_or("bad polyline point")?)) - .collect::>()?; - if pts.len() < 2 || pts.len() > MAX_CTRL { - return Err("polyline point count".into()); - } - let mut k = vec![0.0]; - k.extend((0..pts.len()).map(|i| i as f64)); - k.push((pts.len() - 1) as f64); - Ok(CurveGeo::BSpline(mt::BSplineCurve::try_new(mt::KnotVec::from(k), pts).map_err(|e| format!("polyline: {e}"))?)) - } - "TRIMMED_CURVE" => curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("TRIMMED_CURVE without basis")?, depth + 1), - "SURFACE_CURVE" | "SEAM_CURVE" | "INTERSECTION_CURVE" | "BOUNDED_SURFACE_CURVE" => { - curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("surface curve without 3D curve")?, depth + 1) - } - n => Err(format!("unsupported curve {n}")), - } -} - -/// Rational quadratic NURBS arc of an ellipse from angle `t0` over `sweep > 0`. -pub(crate) fn conic_arc(f: &Frame, a: f64, b: f64, t0: f64, sweep: f64) -> mt::NurbsCurve { - let n = ((sweep / FRAC_PI_2).ceil() as usize).clamp(1, 8); - let dt = sweep / n as f64; - let w = (dt * 0.5).cos(); - let at = |c: f64, s: f64| f.at(a * c, b * s, 0.0); - let mut ctrl = Vec::with_capacity(2 * n + 1); - let p0 = at(t0.cos(), t0.sin()); - ctrl.push(p0.to_homogeneous()); - let mut knots = vec![0.0, 0.0, 0.0]; - for i in 0..n { - let ta = t0 + dt * i as f64; - let tm = ta + dt * 0.5; - let tb = ta + dt; - let m = at(tm.cos() / w, tm.sin() / w); - ctrl.push(mt::Vector4::new(m.x * w, m.y * w, m.z * w, w)); - ctrl.push(at(tb.cos(), tb.sin()).to_homogeneous()); - let k = (i + 1) as f64 / n as f64; - knots.push(k); - knots.push(k); - } - // Last knot pair becomes the clamped end (multiplicity 3). - knots.push(1.0); - mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::from(knots), ctrl)) -} - -/// Largest hyperbola parameter step one rational quadratic piece spans (keeps its weight -/// `cosh(step / 2)` near 1). -const HYPERBOLA_STEP: f64 = 1.0; - -/// Exact rational quadratic NURBS of the hyperbola branch from parameter `t0` to `t1` (either -/// order): pieces whose middle control point is the meeting point of the end tangents, weighted -/// `cosh` of the half step (the hyperbolic counterpart of [`conic_arc`]). -pub(crate) fn hyperbola_arc(f: &Frame, a: f64, b: f64, t0: f64, t1: f64) -> mt::NurbsCurve { - let n = (((t1 - t0).abs() / HYPERBOLA_STEP).ceil() as usize).clamp(1, 64); - let dt = (t1 - t0) / n as f64; - let w = (dt * 0.5).cosh(); - let at = |c: f64, s: f64| f.at(a * c, b * s, 0.0); - let mut ctrl = Vec::with_capacity(2 * n + 1); - ctrl.push(at(t0.cosh(), t0.sinh()).to_homogeneous()); - let mut knots = vec![0.0, 0.0, 0.0]; - for i in 0..n { - let ta = t0 + dt * i as f64; - let tm = ta + dt * 0.5; - let tb = ta + dt; - let m = at(tm.cosh() / w, tm.sinh() / w); - ctrl.push(mt::Vector4::new(m.x * w, m.y * w, m.z * w, w)); - ctrl.push(at(tb.cosh(), tb.sinh()).to_homogeneous()); - let k = (i + 1) as f64 / n as f64; - knots.push(k); - knots.push(k); - } - knots.push(1.0); - mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::from(knots), ctrl)) -} - -/// The parabola from parameter `t0` to `t1` (either order): one quadratic Bézier, exact. -pub(crate) fn parabola_arc(f: &Frame, focal: f64, t0: f64, t1: f64) -> mt::BSplineCurve { - let at = |t: f64| f.at(focal * t * t, 2.0 * focal * t, 0.0); - // The end tangents meet above the parameter midpoint: o + focal·(t0·t1, t0 + t1). - let mid = f.at(focal * t0 * t1, focal * (t0 + t1), 0.0); - mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![at(t0), mid, at(t1)]) -} - -/// Parameter of the open conic at `p`, a point on (or within `tol` of) the curve. -fn open_conic_param(g: &CurveGeo, p: mt::Point3, tol: f64) -> R { - let (t, q) = match g { - CurveGeo::Hyperbola { f, a, b } => { - let t = ((p - f.o).dot(f.y) / b).asinh(); - (t, f.at(a * t.cosh(), b * t.sinh(), 0.0)) - } - CurveGeo::Parabola { f, focal } => { - let t = (p - f.o).dot(f.y) / (2.0 * focal); - (t, f.at(focal * t * t, 2.0 * focal * t, 0.0)) - } - _ => return Err("not an open conic".into()), - }; - let d = q.distance(p); - if !t.is_finite() || !(d <= tol) { - return Err(format!( - "edge vertex is {d:.3e} mm off its {} curve", - if matches!(g, CurveGeo::Parabola { .. }) { "parabola" } else { "hyperbola" } - )); - } - Ok(t) -} - -/// The open conic between parameters `t0` and `t1` as a kernel curve. -fn open_conic_curve(g: &CurveGeo, t0: f64, t1: f64) -> R { - match g { - CurveGeo::Hyperbola { f, a, b } => Ok(mt::Curve::NurbsCurve(hyperbola_arc(f, *a, *b, t0, t1))), - CurveGeo::Parabola { f, focal } => Ok(mt::Curve::BSplineCurve(parabola_arc(f, *focal, t0, t1))), - _ => Err("not an open conic".into()), - } -} - -fn conic_angle(f: &Frame, a: f64, b: f64, p: mt::Point3) -> f64 { - let d = p - f.o; - (d.dot(f.y) / b).atan2(d.dot(f.x) / a) -} - -/// Parameter of the curve point nearest to `p`, and its distance. -fn nearest_param(c: &C, p: mt::Point3) -> Option<(f64, f64)> -where - C: ParametricCurve + BoundedCurve + SearchNearestParameter, -{ - let (t0, t1) = c.range_tuple(); - let n = 256; - let mut best = (t0, f64::INFINITY); - for i in 0..=n { - let t = t0 + (t1 - t0) * i as f64 / n as f64; - let d = c.subs(t).distance(p); - if d < best.1 { - best = (t, d); - } - } - if let Some(t) = c.search_nearest_parameter(p, best.0, 64) { - let t = t.clamp(t0, t1); - let d = c.subs(t).distance(p); - if d < best.1 { - best = (t, d); - } - } - best.1.is_finite().then_some(best) -} - -/// Sub-curve on `[a, b]` (inside the curve's range). -fn sub_curve(c: &C, a: f64, b: f64) -> C { - let (t0, t1) = c.range_tuple(); - let eps = (t1 - t0).abs() * 1e-9; - let mut out = c.clone(); - if a > t0 + eps { - out = out.cut(a); - } - if b < t1 - eps { - let _ = out.cut(b); - } - out -} - -/// Pieces of a spline edge from `ps` to `pe` (two pieces for a closed edge). The vertices may -/// be up to `snap` off the curve; `tol` decides whether the curve closes on itself. -fn spline_pieces(c: &C, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R> -where - C: ParametricCurve + BoundedCurve + SearchNearestParameter + Cut + Clone + Invertible, -{ - let (t0, t1) = c.range_tuple(); - let (ts, ds) = nearest_param(c, ps).ok_or("spline evaluation failed")?; - let (te, de) = nearest_param(c, pe).ok_or("spline evaluation failed")?; - if !(ds <= snap && de <= snap) { - return Err(format!("edge vertices are {:.3e} mm off their curve", ds.max(de))); - } - let span = t1 - t0; - let near = |a: f64, b: f64| (a - b).abs() <= span * 1e-7; - let mut pieces = if closed { - // Whole closed curve starting at the vertex. - if near(ts, t0) || near(ts, t1) { - let m = t0 + span * 0.5; - vec![sub_curve(c, t0, m), sub_curve(c, m, t1)] - } else { - vec![sub_curve(c, ts, t1), sub_curve(c, t0, ts)] - } - } else { - let (mut a, mut b) = if sense { (ts, te) } else { (te, ts) }; - // A closed curve traversed across its seam. - if a >= b && c.subs(t0).distance(c.subs(t1)) <= tol { - if near(b, t0) { - b = t1; - } else if near(a, t1) { - a = t0; - } else { - let mut v = vec![sub_curve(c, a, t1), sub_curve(c, t0, b)]; - if !sense { - v.reverse(); - v.iter_mut().for_each(|x| x.invert()); - } - return Ok(v); - } - } - if b - a <= span * 1e-9 { - return Err("degenerate spline edge".into()); - } - vec![sub_curve(c, a, b)] - }; - if !sense { - pieces.reverse(); - pieces.iter_mut().for_each(|x| x.invert()); - } - Ok(pieces) -} - -/// Moves one end of a spline piece (`back`: its end, else its start) onto its vertex `p` by -/// the control point that end sits on, so the piece meets the vertex exactly and keeps its -/// shape away from that end. A piece whose end is not a control point (an unclamped spline) is -/// left as it is. -fn pin_end(c: &mut mt::Curve, p: mt::Point3, back: bool) { - let end = if back { c.back() } else { c.front() }; - let d = p - end; - if !(d.magnitude2() > 0.0) { - return; - } - let at_end = |q: mt::Point3| q.distance(end) <= mt::TOLERANCE; - match c { - mt::Curve::BSplineCurve(b) => { - let cp = if back { b.control_points_mut().last() } else { b.control_points_mut().next() }; - if let Some(q) = cp.filter(|q| at_end(**q)) { - *q += d; - } - } - mt::Curve::NurbsCurve(n) => { - let cp = if back { n.control_points_mut().last() } else { n.control_points_mut().next() }; - if let Some(q) = cp.filter(|q| q.w != 0.0 && at_end(mt::Point3::from_homogeneous(**q))) { - *q = (mt::Point3::from_homogeneous(*q) + d).to_homogeneous() * q.w; - } - } - _ => {} - } -} - -/// Kernel curves for an edge from `ps` to `pe`: one piece, or two for a closed edge (so no -/// kernel edge starts and ends at the same vertex). A spline or open-conic edge's ends are -/// moved onto vertices up to `snap` off its curve, so the pieces meet the vertices exactly. -pub(crate) fn edge_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R> { - let mut pieces = curve_pieces(g, ps, pe, sense, closed, tol, snap)?; - if matches!(g, CurveGeo::BSpline(_) | CurveGeo::Nurbs(_) | CurveGeo::Hyperbola { .. } | CurveGeo::Parabola { .. }) { - if let Some(c) = pieces.first_mut() { - pin_end(c, ps, false); - } - if let Some(c) = pieces.last_mut() { - pin_end(c, pe, true); - } - } - Ok(pieces) -} - -fn curve_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R> { - match g { - CurveGeo::Line { .. } => { - if closed { - return Err("closed straight edge".into()); - } - Ok(vec![mt::Curve::Line(mt::Line(ps, pe))]) - } - CurveGeo::Conic { f, a, b } => { - let (a, b) = (*a, *b); - let ts = conic_angle(f, a, b, ps); - let te = conic_angle(f, a, b, pe); - let mut sweep = if sense { te - ts } else { ts - te }; - sweep = sweep.rem_euclid(TAU); - if closed || sweep < 1e-12 { - sweep = TAU; - } - let pieces: Vec<(f64, f64)> = if sweep > PI * 1.5 { vec![(0.0, sweep * 0.5), (sweep * 0.5, sweep)] } else { vec![(0.0, sweep)] }; - Ok(pieces - .into_iter() - .map(|(s0, s1)| { - if sense { - mt::Curve::NurbsCurve(conic_arc(f, a, b, ts + s0, s1 - s0)) - } else { - let mut c = conic_arc(f, a, b, ts - s1, s1 - s0); - c.invert(); - mt::Curve::NurbsCurve(c) - } - }) - .collect()) - } - CurveGeo::Hyperbola { .. } | CurveGeo::Parabola { .. } => { - if closed { - return Err("closed edge on an open conic".into()); - } - // The curve is open, so the edge is the parameters between its vertices: rising - // for the same sense, falling for the opposite one. - let (ts, te) = (open_conic_param(g, ps, snap)?, open_conic_param(g, pe, snap)?); - let scale = 1.0 + ts.abs().max(te.abs()); - if (te - ts).abs() <= 1e-9 * scale { - return Err("degenerate conic edge".into()); - } - Ok(vec![open_conic_curve(g, ts, te)?]) - } - CurveGeo::BSpline(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol, snap)?.into_iter().map(mt::Curve::BSplineCurve).collect()), - CurveGeo::Nurbs(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol, snap)?.into_iter().map(mt::Curve::NurbsCurve).collect()), - } -} - -/// A bounded kernel curve for a swept surface's profile (lines are bounded by `extent`). -fn bounded_curve(g: &CurveGeo, extent: &[mt::Point3]) -> R { - Ok(match g { - CurveGeo::Line { p, d } => { - let (lo, hi) = span_along(extent, *p, *d); - mt::Curve::Line(mt::Line(*p + *d * lo, *p + *d * hi)) - } - CurveGeo::Conic { f, a, b } => mt::Curve::NurbsCurve(conic_arc(f, *a, *b, 0.0, TAU)), - CurveGeo::Hyperbola { f, .. } | CurveGeo::Parabola { f, .. } => { - // Bounded by the face's points (their parameters along the curve), with a margin. - let along = |q: &mt::Point3| match g { - CurveGeo::Hyperbola { b, .. } => ((q - f.o).dot(f.y) / b).asinh(), - CurveGeo::Parabola { focal, .. } => (q - f.o).dot(f.y) / (2.0 * focal), - _ => 0.0, - }; - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for t in extent.iter().map(along).filter(|t| t.is_finite()) { - lo = lo.min(t); - hi = hi.max(t); - } - let (lo, hi) = if lo < hi { (lo - (hi - lo) * 0.25 - 1e-3, hi + (hi - lo) * 0.25 + 1e-3) } else { (-1.0, 1.0) }; - open_conic_curve(g, lo, hi)? - } - CurveGeo::BSpline(c) => mt::Curve::BSplineCurve(c.clone()), - CurveGeo::Nurbs(c) => mt::Curve::NurbsCurve(c.clone()), - }) -} - -/// Range of `(q - o)·d` over the points, widened by a margin. -fn span_along(pts: &[mt::Point3], o: mt::Point3, d: mt::Vector3) -> (f64, f64) { - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for q in pts { - let t = (q - o).dot(d); - lo = lo.min(t); - hi = hi.max(t); - } - if !(lo.is_finite() && hi.is_finite()) { - return (-1.0, 1.0); - } - let m = (hi - lo) * 0.25 + 1e-3; - (lo - m, hi + m) -} - -/// The angle shared by all the given angles (within 1e-4 rad), if there are any. -fn common_angle(angles: impl Iterator) -> Option { - let (mut sx, mut sy, mut n) = (0.0, 0.0, 0usize); - let mut all = Vec::new(); - for a in angles { - sx += a.cos(); - sy += a.sin(); - n += 1; - all.push(a); - } - if n == 0 { - return None; - } - let m = sy.atan2(sx); - let close = all.iter().all(|a| { - let d = (a - m).rem_euclid(TAU); - d.min(TAU - d) < 1e-4 - }); - close.then_some(m) -} - -/// Middle and width of the largest gap between angles (radians, any range). -fn largest_gap(angles: &[f64]) -> Option<(f64, f64)> { - let mut a: Vec = angles.iter().map(|x| x.rem_euclid(TAU)).filter(|x| x.is_finite()).collect(); - if a.is_empty() { - return None; - } - a.sort_by(f64::total_cmp); - let (mut best, mut mid) = (0.0, 0.0); - let a = Ring::new(a); - for (i, (&x, &y)) in a.edges().enumerate() { - let gap = if i + 1 == a.len() { y + TAU - x } else { y - x }; - if gap > best { - best = gap; - mid = x + gap * 0.5; - } - } - Some((mid, best)) -} - -/// The frame turned about its Z axis so that its X axis (the parameter seam of a revolved -/// surface) lies in the widest angular gap of the face boundary. -fn seam_frame(f: &Frame, extent: &[mt::Point3], seam: &[mt::Point3]) -> Frame { - // A seam edge of the face along the rotation: the parameter seam must be there. - if let Some(m) = common_angle(seam.iter().filter_map(|p| { - let d = p - f.o; - let (x, y) = (d.dot(f.x), d.dot(f.y)); - (x.hypot(y) > 1e-6 * (1.0 + d.magnitude())).then(|| y.atan2(x)) - })) { - let x = f.x * m.cos() + f.y * m.sin(); - return Frame { o: f.o, x, y: f.z.cross(x), z: f.z }; - } - let az: Vec = extent - .iter() - .filter_map(|p| { - let d = p - f.o; - let (x, y) = (d.dot(f.x), d.dot(f.y)); - (x.hypot(y) > 1e-9).then(|| y.atan2(x)) - }) - .collect(); - match largest_gap(&az) { - Some((m, gap)) if gap > 1e-3 => { - let x = f.x * m.cos() + f.y * m.sin(); - Frame { o: f.o, x, y: f.z.cross(x), z: f.z } - } - _ => *f, - } -} - -/// Length of the mean unit direction from the frame origin to the points (1: all in one -/// direction, 0: spread all round). -fn mean_direction(f: &Frame, pts: &[mt::Point3]) -> f64 { - let dirs: Vec = pts - .iter() - .filter_map(|p| { - let d = p - f.o; - let m = d.magnitude(); - (m > 1e-12).then(|| d / m) - }) - .collect(); - if dirs.is_empty() { - return 0.0; - } - (dirs.iter().fold(mt::Vector3::new(0.0, 0.0, 0.0), |a, d| a + d) / dirs.len() as f64).magnitude() -} - -/// Polar axis for a sphere: far from every boundary point, and (for a face concentrated on -/// one side) with both poles outside the face, so every loop closes in parameter space. -fn sphere_axis(f: &Frame, extent: &[mt::Point3]) -> mt::Vector3 { - let dirs: Vec = extent - .iter() - .filter_map(|p| { - let d = p - f.o; - let m = d.magnitude(); - (m > 1e-12).then(|| d / m) - }) - .collect(); - if dirs.is_empty() { - return f.z; - } - let mean = dirs.iter().fold(mt::Vector3::new(0.0, 0.0, 0.0), |a, d| a + d) / dirs.len() as f64; - let concentrated = mean.magnitude() > 0.3; - let mhat = if concentrated { mean / mean.magnitude() } else { mean }; - let n = 400; - let golden = PI * (3.0 - 5f64.sqrt()); - let mut best = (f64::NEG_INFINITY, f.z); - // Half of a Fibonacci sphere (an axis and its opposite are the same poles). - for i in 0..n { - let z = 1.0 - (i as f64 + 0.5) / n as f64; - let r = (1.0 - z * z).max(0.0).sqrt(); - let t = golden * i as f64; - let a = mt::Vector3::new(r * t.cos(), r * t.sin(), z); - if concentrated && a.dot(mhat).abs() > 0.35 { - continue; - } - let score = dirs.iter().map(|d| 1.0 - d.dot(a).abs()).fold(f64::INFINITY, f64::min); - if score > best.0 { - best = (score, a); - } - } - best.1 -} - -/// Tube angle of a point on a torus. -fn tube_angle(f: &Frame, big: f64, p: mt::Point3) -> f64 { - let d = p - f.o; - let z = d.dot(f.z); - let rho = (d - f.z * z).magnitude(); - z.atan2(rho - big) -} - -/// A straight profile of a surface of revolution, bounded by the face: boundary points are -/// turned into the profile's meridian plane and projected onto the line, and the line stops at -/// the axis (beyond it the surface would fold over itself). -fn revolved_line(p: mt::Point3, d: mt::Vector3, o: mt::Point3, axis: mt::Vector3, extent: &[mt::Point3]) -> R { - let radial = |q: mt::Point3| { - let v = q - o; - v - axis * v.dot(axis) - }; - // The meridian half-plane of the profile. - let e = { - let r = radial(p); - let r2 = radial(p + d); - let r = if r.magnitude() >= r2.magnitude() { r } else { r2 }; - if r.magnitude() < 1e-12 { - return Err("profile line on the axis".into()); - } - r / r.magnitude() - }; - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for q in extent { - let v = q - o; - let h = v.dot(axis); - let r = radial(*q).magnitude(); - let t = (o + axis * h + e * r - p).dot(d); - lo = lo.min(t); - hi = hi.max(t); - } - if !(lo.is_finite() && hi.is_finite()) { - return Err("surface of revolution without extent".into()); - } - let m = (hi - lo) * 0.02 + 1e-6; - let (mut lo, mut hi) = (lo - m, hi + m); - // Where the line meets the axis (radial component along e vanishes). - let de = d.dot(e); - if de.abs() > 1e-12 { - let t_axis = -(p - o).dot(e) / de; - // The meridian half-plane has a non-negative radius along `e`. - if de > 0.0 { - lo = lo.max(t_axis); - } else { - hi = hi.min(t_axis); - } - } - if hi - lo <= 1e-12 { - return Err("degenerate surface of revolution".into()); - } - Ok(mt::Curve::Line(mt::Line(p + d * lo, p + d * hi))) -} - -fn revolved(curve: mt::Curve, o: mt::Point3, axis: mt::Vector3) -> mt::Surface { - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(curve, o, axis))) -} - -/// A surface of revolution whose normal at the profile point `(u, 0)` points along `expected`. -/// The rotation is reversed rather than the surface inverted: truck's inverted `Processor` -/// swaps the parameters but not the search hints, which breaks meshing. -pub(crate) fn revolved_oriented(curve: mt::Curve, o: mt::Point3, axis: mt::Vector3, u: f64, expected: mt::Vector3) -> mt::Surface { - let s = revolved(curve.clone(), o, axis); - if s.normal(u, 0.0).dot(expected) >= 0.0 { - return s; - } - revolved(curve, o, -axis) -} - -pub(crate) fn bspline_surface(cx: &Ctx, e: &Entity) -> R { - let (base, knots, kind): (Vec, Option<[Option<&Param>; 4]>, &str) = if e.is_complex() { - let b = e.record("B_SPLINE_SURFACE").ok_or("complex surface without B_SPLINE_SURFACE")?; - let mut base = vec![Param::Str(String::new())]; - base.extend(b.iter().cloned()); - let k = e.record("B_SPLINE_SURFACE_WITH_KNOTS").map(|k| [k.first(), k.get(1), k.get(2), k.get(3)]); - let kind = if e.has("BEZIER_SURFACE") { - "BEZIER" - } else if e.has("UNIFORM_SURFACE") { - "UNIFORM" - } else { - "QUASI" - }; - (base, k, kind) - } else { - let p = e.params(); - let k = (e.name() == "B_SPLINE_SURFACE_WITH_KNOTS").then(|| [p.get(8), p.get(9), p.get(10), p.get(11)]); - let kind = match e.name() { - "BEZIER_SURFACE" => "BEZIER", - "UNIFORM_SURFACE" => "UNIFORM", - _ => "QUASI", - }; - (p.to_vec(), k, kind) - }; - let deg = |i: usize| base.get(i).and_then(Param::as_i64).filter(|d| (1..=32).contains(d)).map(|d| d as usize).ok_or("bad B-spline degree"); - let (du, dv) = (deg(1)?, deg(2)?); - let rows = base.get(3).and_then(Param::as_list).ok_or("B-spline surface without control points")?; - let mut ctrl: Vec> = Vec::with_capacity(rows.len()); - let mut total = 0usize; - for r in rows { - let r = r.as_list().ok_or("bad control point row")?; - total += r.len(); - if total > MAX_CTRL { - return Err("B-spline surface with too many control points".into()); - } - ctrl.push(r.iter().map(|c| point(cx, c.as_ref_id().ok_or("bad control point")?)).collect::>()?); - } - let nu = ctrl.len(); - let nv = ctrl.first().map(Vec::len).unwrap_or(0); - if nu == 0 || ctrl.iter().any(|r| r.len() != nv) { - return Err("ragged B-spline control net".into()); - } - let (ku, kv) = match knots { - Some([mu, mv, ku, kv]) => (knot_vec(mu, ku, nu + du + 1)?, knot_vec(mv, kv, nv + dv + 1)?), - None => (generated_knots(kind, nu, du)?, generated_knots(kind, nv, dv)?), - }; - if ku.len() != nu + du + 1 || kv.len() != nv + dv + 1 { - return Err("B-spline surface knot counts do not match the control net".into()); - } - let bsp = mt::BSplineSurface::try_new((ku, kv), ctrl).map_err(|e| format!("B-spline surface: {e}"))?; - match e.record("RATIONAL_B_SPLINE_SURFACE") { - Some(r) => { - let w: Vec> = r - .first() - .and_then(Param::as_list) - .ok_or("rational surface without weights")? - .iter() - .map(|row| weights_list(Some(row))) - .collect::>()?; - if w.len() != nu || w.iter().any(|r| r.len() != nv) { - return Err("weights do not match the control net".into()); - } - let n = mt::NurbsSurface::::try_from_bspline_and_weights(bsp, w).map_err(|e| format!("rational surface: {e}"))?; - Ok(mt::Surface::NurbsSurface(mt::NurbsSurface::new(clamped_surface(n.into_non_rationalized())))) - } - None => Ok(mt::Surface::BSplineSurface(clamped_surface(bsp))), - } -} - -/// Resolve exact analytic offsets. Each intermediate offset is checked: an invalid inner -/// offset must not become valid merely because an outer offset cancels its distance. -/// Entity attributes follow ISO 10303-42 (`basis_surface`, `distance`, `self_intersect`). -fn offset_basis(cx: &Ctx, id: u64, depth: usize) -> R<(u64, f64)> { - if depth > MAX_GEOM_DEPTH { - return Err("surface definitions nested too deeply".into()); - } - let e = entity(cx, id)?; - if e.name() != "OFFSET_SURFACE" { - return Ok((id, 0.0)); - } - let p = e.params(); - let basis = p.get(1).and_then(Param::as_ref_id).ok_or("offset surface without basis")?; - let distance = length(cx, p.get(2), "offset distance")?; - if !matches!(p.get(3).and_then(Param::as_enum), Some("T" | "F" | "U")) { - return Err("offset surface without a logical self_intersect flag".into()); - } - let (basis, inner) = offset_basis(cx, basis, depth + 1)?; - let offset = inner + distance; - if !offset.is_finite() || offset.abs() >= MAX_COORD { - return Err("offset distance out of range after unit conversion".into()); - } - let e = entity(cx, basis)?; - let p = e.params(); - match e.name() { - "PLANE" => {} - "CYLINDRICAL_SURFACE" | "SPHERICAL_SURFACE" => { - let radius = length(cx, p.get(2), "radius")?; - if radius <= 0.0 || !(1e-9..MAX_COORD).contains(&(radius + offset)) { - return Err("offset surface collapses or reverses its radius".into()); - } - } - "CONICAL_SURFACE" => { - let radius = length(cx, p.get(2), "radius")?; - let angle = num(p.get(3), "semi angle")? * cx.ang; - if radius < 0.0 || !(angle.abs() > 1e-9 && angle.abs() < FRAC_PI_2 - 1e-9) || !(0.0..MAX_COORD).contains(&(radius + offset / angle.cos())) - { - return Err("offset cone has an invalid reference radius or angle".into()); - } - } - "TOROIDAL_SURFACE" => { - let major = length(cx, p.get(2), "major radius")?; - let minor = length(cx, p.get(3), "minor radius")?; - if minor <= 0.0 || major <= minor || major >= MAX_COORD || !(1e-9..major).contains(&(minor + offset)) { - return Err("offset torus collapses or becomes self-intersecting".into()); - } - } - _ if offset == 0.0 => {} - n => return Err(format!("unsupported OFFSET_SURFACE basis surface {n}")), - } - Ok((basis, offset)) -} - -/// A STEP surface entity as a kernel surface whose normal is the STEP surface normal. -/// `extent` holds points of the face boundary (bounds the analytic surfaces' parameter ranges). -/// `sense` false gives the opposite normal (a face with `same_sense = .F.`). -/// `seam` holds points of the face's seam edges (edges its loops use twice). -pub(crate) fn surface(cx: &Ctx, id: u64, extent: &[mt::Point3], seam: &[mt::Point3], sense: bool, depth: usize) -> R { - let sign = if sense { 1.0 } else { -1.0 }; - let flip = |mut s: mt::Surface| { - if !sense { - s.invert(); - } - s - }; - if depth > MAX_GEOM_DEPTH { - return Err("surface definitions nested too deeply".into()); - } - let (id, offset) = offset_basis(cx, id, depth)?; - let e = entity(cx, id)?; - if e.is_complex() { - return bspline_surface(cx, e).map(flip); - } - let p = e.params(); - let placement = || -> R { frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("surface without placement")?) }; - match e.name() { - "PLANE" => { - let f = placement()?; - let o = f.o + f.z * offset; - Ok(flip(mt::Surface::Plane(mt::Plane::new(o, o + f.x, o + f.y)))) - } - "CYLINDRICAL_SURFACE" => { - let f = seam_frame(&placement()?, extent, seam); - let r = length(cx, p.get(2), "radius")? + offset; - if r <= 0.0 { - return Err("cylinder radius must be positive".into()); - } - let (lo, hi) = span_along(extent, f.o, f.z); - let line = mt::Curve::Line(mt::Line(f.at(r, 0.0, lo), f.at(r, 0.0, hi))); - Ok(revolved_oriented(line, f.o, f.z, 0.5, f.x * sign)) - } - "CONICAL_SURFACE" => { - let f = seam_frame(&placement()?, extent, seam); - let basis_r = length(cx, p.get(2), "radius")?; - let a = num(p.get(3), "semi angle")? * cx.ang; - let r = basis_r + offset / a.cos(); - if r < 0.0 || !(a.abs() > 1e-9 && a.abs() < FRAC_PI_2 - 1e-9) { - return Err("bad cone".into()); - } - let t = a.tan(); - let (mut lo, mut hi) = span_along(extent, f.o, f.z); - // Stop at the apex. - let apex = -r / t; - if t > 0.0 { - lo = lo.max(apex); - } else { - hi = hi.min(apex); - } - if hi - lo <= 1e-9 { - return Err("cone face has no extent".into()); - } - let line = mt::Curve::Line(mt::Line(f.at(r + lo * t, 0.0, lo), f.at(r + hi * t, 0.0, hi))); - Ok(revolved_oriented(line, f.o, f.z, 0.5, (f.x * a.cos() - f.z * a.sin()) * sign)) - } - "SPHERICAL_SURFACE" => { - let f = placement()?; - let r = length(cx, p.get(2), "radius")? + offset; - if r <= 0.0 { - return Err("sphere radius must be positive".into()); - } - // With seam edges the file's own parameterisation fits the loops; else pick poles - // away from the boundary. - // A small patch (a corner blend) gets poles away from it even when the file runs a - // seam through it: a seam ending at a pole on the patch boundary leaves the mesher - // no way to tell the patch from the rest of the sphere. - let f = if seam.is_empty() || mean_direction(&f, extent) > 0.3 { - let z = sphere_axis(&f, extent); - let x = any_perpendicular(z); - seam_frame(&Frame { o: f.o, x, y: z.cross(x), z }, extent, seam) - } else { - seam_frame(&f, extent, seam) - }; - let half = Frame { o: f.o, x: f.x, y: f.z, z: -f.y }; - let arc = conic_arc(&half, r, r, -FRAC_PI_2, PI); - let um = (arc.range_tuple().0 + arc.range_tuple().1) * 0.5; - Ok(revolved_oriented(mt::Curve::NurbsCurve(arc), f.o, f.z, um, f.x * sign)) - } - "TOROIDAL_SURFACE" => { - let f = placement()?; - let (big, small) = (length(cx, p.get(2), "major radius")?, length(cx, p.get(3), "minor radius")? + offset); - if small <= 0.0 || big < 0.0 { - return Err("bad torus radii".into()); - } - // Seam edges either run around the axis (constant tube angle) or around the tube - // (constant azimuth); each fixes one parameter seam. - let tube_seam: Vec = - seam.iter().copied().filter(|p| common_angle(std::iter::once(tube_angle(&f, big, *p))).is_some()).collect(); - let phis_seam = common_angle(tube_seam.iter().map(|p| tube_angle(&f, big, *p))); - let az_seam: Vec = if phis_seam.is_some() { Vec::new() } else { seam.to_vec() }; - let f = seam_frame(&f, extent, &az_seam); - let phis: Vec = extent.iter().map(|p| tube_angle(&f, big, *p)).collect(); - let phi0 = match (phis_seam, largest_gap(&phis)) { - (Some(m), _) => m, - (None, Some((m, _))) => m, - (None, None) => 0.0, - }; - let tube = Frame { o: f.at(big, 0.0, 0.0), x: f.x, y: f.z, z: -f.y }; - let circle = conic_arc(&tube, small, small, phi0, TAU); - let u0 = circle.range_tuple().0; - let outward = f.x * phi0.cos() + f.z * phi0.sin(); - Ok(revolved_oriented(mt::Curve::NurbsCurve(circle), f.o, f.z, u0, outward * sign)) - } - "B_SPLINE_SURFACE_WITH_KNOTS" | "BEZIER_SURFACE" | "UNIFORM_SURFACE" | "QUASI_UNIFORM_SURFACE" => bspline_surface(cx, e).map(flip), - "SURFACE_OF_REVOLUTION" => { - let g = curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("revolution without profile")?, depth + 1)?; - let (o, axis) = axis1(cx, p.get(2).and_then(Param::as_ref_id).ok_or("revolution without axis")?)?; - let profile = match &g { - CurveGeo::Line { p, d } => revolved_line(*p, *d, o, axis, extent)?, - _ => bounded_curve(&g, extent)?, - }; - // ISO 10303-42 parameterises a surface of revolution by the angle u and the profile - // v, so its normal is ∂S/∂angle × ∂S/∂profile: the opposite of truck's revolution - // (profile first). Strict readers take it this way. Reversed sense turns it back. - Ok(revolved(profile, o, -axis * sign)) - } - "SURFACE_OF_LINEAR_EXTRUSION" => { - let g = curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("extrusion without profile")?, depth + 1)?; - let (_, v) = ent_of(cx, p.get(2), "extrusion vector")?; - let d = direction(cx, v.params().get(1).and_then(Param::as_ref_id).ok_or("VECTOR without direction")?)?; - let profile = match &g { - CurveGeo::Conic { f, a, b } if d.dot(f.z).abs() > 1e-12 => { - // Keep the closed profile's parameter seam outside the trim. Otherwise a - // tooth tip crossing it can mesh as almost the whole extruded ellipse. - let dz = d.dot(f.z); - let angle = |p: &mt::Point3| { - let q = p - f.o; - let q = q - d * (q.dot(f.z) / dz); - (q.dot(f.y) / b).atan2(q.dot(f.x) / a) - }; - let start = common_angle(seam.iter().map(angle)) - .or_else(|| largest_gap(&extent.iter().map(angle).collect::>()).map(|(mid, _)| mid)) - .unwrap_or(0.0); - mt::Curve::NurbsCurve(conic_arc(f, *a, *b, start, TAU)) - } - _ => bounded_curve(&g, extent)?, - }; - let nurbs: mt::NurbsCurve = match profile { - mt::Curve::Line(l) => mt::BSplineCurve::new(mt::KnotVec::bezier_knot(1), vec![l.0, l.1]).into(), - mt::Curve::BSplineCurve(c) => c.into(), - mt::Curve::NurbsCurve(c) => c, - mt::Curve::IntersectionCurve(_) => return Err("unsupported extrusion profile".into()), - }; - let (t0, t1) = nurbs.range_tuple(); - let profile: Vec = (0..=32).map(|i| nurbs.subs(t0 + (t1 - t0) * i as f64 / 32.0)).collect(); - let (plo, phi) = span_along(&profile, mt::Point3::new(0.0, 0.0, 0.0), d); - let (elo, ehi) = span_along(extent, mt::Point3::new(0.0, 0.0, 0.0), d); - let (lo, hi) = (elo - phi, ehi - plo); - let bsp = nurbs.into_non_rationalized(); - let shift = |w: &mt::Vector4, s: f64| mt::Vector4::new(w.x + d.x * s * w.w, w.y + d.y * s * w.w, w.z + d.z * s * w.w, w.w); - let ctrl: Vec> = bsp.control_points().iter().map(|w| vec![shift(w, lo), shift(w, hi)]).collect(); - let s = - mt::BSplineSurface::try_new((bsp.knot_vec().clone(), mt::KnotVec::bezier_knot(1)), ctrl).map_err(|e| format!("extrusion: {e}"))?; - Ok(flip(mt::Surface::NurbsSurface(mt::NurbsSurface::new(s)))) - } - "RECTANGULAR_TRIMMED_SURFACE" | "CURVE_BOUNDED_SURFACE" => { - surface(cx, p.get(1).and_then(Param::as_ref_id).ok_or("trimmed surface without basis")?, extent, seam, sense, depth + 1) - } - n => Err(format!("unsupported surface {n}")), - } -} diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index 2454ce143..1a4c79961 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -1,28 +1,23 @@ //! STEP import (ISO 10303-21 files, AP203/AP214/AP242 geometry). //! //! Our own reader, written from the public standards: [`p21`] parses the exchange structure, -//! [`geom`] and [`brep`] turn geometry and topology into kernel solids, and this module walks -//! the product structure (products, shape representations, assemblies with their placements, -//! units, colours). STEP files are untrusted: every count and nesting depth is capped, every -//! truck call runs under [`guard`], and what cannot be read becomes a warning rather than a -//! failure wherever the rest of the file is still usable. +//! [`solidcraft_step::topology`] reads each solid into its schema 4 record, which SMLib takes +//! as the body ([`parallel`]), and this module walks the product structure (products, shape +//! representations, assemblies with their placements, units, colours). STEP files are +//! untrusted: every count and nesting depth is capped, and what cannot be read becomes a +//! warning rather than a failure wherever the rest of the file is still usable. -mod brep; -pub(crate) mod geom; pub(crate) mod p21; mod parallel; -pub(crate) mod split; use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; -use mt::EuclideanSpace as _; use serde::{Deserialize, Serialize}; -use truck_modeling as mt; +use solidcraft_step::read::R; use crate::body::Body; -use crate::{KernelError, Result, guard}; -use geom::R; +use crate::{KernelError, Result}; use p21::{Entity, Exchange, Param}; /// Deepest assembly nesting followed. @@ -58,9 +53,12 @@ pub struct ImportedBody { pub instance: Option, /// The body is a closed solid (false: faces were left out, or the file had a surface model). pub closed: bool, - /// Faces read from the file. The body can have more: a face that wraps all the way around - /// a closed surface is split in two for the kernel. + /// Faces read from the file (each body face is one of them: `face_origin`). pub file_faces: usize, + /// No B-rep could be made of the whole solid, and this is why (the import's warnings say so + /// too, naming each face left out): `body` is an open surface body of the solid's exact faces + /// but those. + pub refused: Option, } /// One product occurrence in the file's assembly tree. @@ -84,6 +82,8 @@ pub struct StepImport { pub tree: Vec, /// What could not be read (unsupported entities, faces left out…). pub warnings: Vec, + /// The same, by kind and part, with what came in of the file's parts: for a summary in words. + pub report: ImportReport, /// FILE_SCHEMA (e.g. `AUTOMOTIVE_DESIGN`, `CONFIG_CONTROL_DESIGN`, `AP242_…`). pub schema: String, /// FILE_NAME originating system. @@ -94,6 +94,70 @@ pub struct StepImport { pub description: String, } +/// What an import warning is about, so a window can word a summary of them (the warning's +/// text is the detail). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum IssueKind { + /// The part could not be read from the file: it is not in the design. + NotImported, + /// The kernel refuses the part's B-rep, its faces' too: it is not in the design, and the + /// warning gives the kernel's reason. + Refused, + /// No solid could be made of the part: it came in as surfaces of its faces. + ImportedAsSurfaces, + /// A face of the part could not be read or made, and is left out. + FaceLeftOut, + /// The part's shell is not closed: it came in as an open body. + OpenBody, + /// Faces of the part could not be meshed and are not shown. + FacesNotShown, + /// SMLib refuses the part: modelling operations on it fail until it is repaired. + NeedsRepair, + /// Something was repaired on the way (edges split at a pole, faces turned, gaps covered). + Repaired, + /// The file as a whole: its assembly structure, its limits, its entity ids. + File, +} + +/// One import warning: what it is about and the part it concerns. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImportIssue { + pub kind: IssueKind, + /// The STEP item of the part (`None`: the file as a whole). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub item: Option, + /// The part's name in the file (empty: it has none). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub part: String, + /// Faces it concerns: one for a face left out, the count for faces not shown, else 0. + #[serde(default)] + pub faces: usize, + /// How many times it came (a part not imported says so at each of its instances). + pub times: usize, + /// The warning as [`StepImport::warnings`] words it. + pub detail: String, +} + +/// What an import made of the file's parts, and its warnings by kind and part. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ImportReport { + /// Parts (distinct solid items) the file places. + pub parts: usize, + /// Parts that came in as closed solids. + pub solids: usize, + /// In the order of [`StepImport::warnings`]. + pub issues: Vec, +} + +/// A warning kept by [`Reader::note`]: what it is about and how often it came. +struct Noted { + kind: IssueKind, + item: Option, + faces: usize, + times: usize, +} + /// A solid the walk found, converted later. struct Planned { item: u64, @@ -103,142 +167,21 @@ struct Planned { /// Where the solids of a batch go: their placement and names. struct Batch { - m: mt::Matrix4, + m: M4, path: Vec, product: String, instance: Option, } -/// Reading context: the file and the units of the representation being read. -pub(crate) struct Ctx<'a> { - pub ex: &'a Exchange, - /// Millimetres per file length unit. - pub len: f64, - /// Radians per file angle unit. - pub ang: f64, - /// Vertex-on-curve tolerance (mm). - pub tol: f64, - /// Farthest an edge's vertex may sit off its curve and still be moved onto it (mm, at least - /// `tol`): see [`snap_limit`]. - pub snap: f64, -} +/// The units of a representation context (GLOBAL_UNIT_ASSIGNED_CONTEXT) and its distance +/// uncertainty (mm) as the file states it. +type Units = solidcraft_step::units::Context; -#[derive(Clone, Copy)] -struct Units { - len: f64, - ang: f64, - tol: f64, - snap: f64, -} - -const DEFAULT_UNITS: Units = Units { len: 1.0, ang: 1.0, tol: 0.01, snap: 0.01 }; - -/// Largest tolerance a file can ask for (mm), however coarse the accuracy it declares. -const MAX_TOL: f64 = 1.0; - -/// Gap between an edge's vertex and its curve that is still read as the same point, as a share -/// of the model's size: the chord error the kernel's own coarse meshes allow at that size -/// (`Body::size() * 1e-3`), so moving the vertex onto the curve changes the shape by less than -/// those meshes already do. -const SNAP_SHARE: f64 = 1e-3; - -/// Farthest a vertex may sit off its edge's curve and be moved onto it (mm): the file's own -/// tolerance `tol`, or up to [`SNAP_SHARE`] of the model's size `extent` (mm) when that is -/// larger. Some exporters write vertices further off than the accuracy they declare (a surface -/// export may declare 0.01 mm and join two curves 0.38 mm apart at a vertex between them). -/// Never more than [`MAX_TOL`], so a far stray point cannot turn the check off. -fn snap_limit(tol: f64, extent: f64) -> f64 { - let share = if extent.is_finite() { extent * SNAP_SHARE } else { 0.0 }; - tol.max(share.min(MAX_TOL)) -} - -fn si_prefix(p: Option<&Param>) -> f64 { - match p.and_then(Param::as_enum) { - Some("EXA") => 1e18, - Some("PETA") => 1e15, - Some("TERA") => 1e12, - Some("GIGA") => 1e9, - Some("MEGA") => 1e6, - Some("KILO") => 1e3, - Some("HECTO") => 1e2, - Some("DECA") => 1e1, - Some("DECI") => 1e-1, - Some("CENTI") => 1e-2, - Some("MILLI") => 1e-3, - Some("MICRO") => 1e-6, - Some("NANO") => 1e-9, - Some("PICO") => 1e-12, - Some("FEMTO") => 1e-15, - Some("ATTO") => 1e-18, - _ => 1.0, - } -} - -/// A unit's size: millimetres for lengths, radians for plane angles. -fn unit_factor(ex: &Exchange, id: u64, depth: usize) -> Option<(&'static str, f64)> { - if depth > 4 { - return None; - } - let e = ex.get(id)?; - let kind = if e.has("LENGTH_UNIT") { - "length" - } else if e.has("PLANE_ANGLE_UNIT") { - "angle" - } else { - "other" - }; - if let Some(si) = e.record("SI_UNIT") { - let base = match si.get(1).and_then(Param::as_enum) { - Some("METRE") => 1000.0, - Some("RADIAN") => 1.0, - _ => return Some((kind, 1.0)), - }; - return Some((kind, si_prefix(si.first()) * base)); - } - if let Some(cb) = e.record("CONVERSION_BASED_UNIT") { - let m = ex.get(cb.get(1)?.as_ref_id()?)?; - let mp = m.params(); - let v = mp.first()?.as_f64()?; - let (_, f) = unit_factor(ex, mp.get(1)?.as_ref_id()?, depth + 1)?; - let x = v * f; - return (x.is_finite() && x > 0.0).then_some((kind, x)); - } - Some((kind, 1.0)) -} - -/// Units of a representation context (GLOBAL_UNIT_ASSIGNED_CONTEXT, uncertainty). +/// Units of a representation context, read by [`solidcraft_step::units::context`] (millimetres +/// and radians when the file names none). fn context_units(ex: &Exchange, ctx: Option, cache: &mut HashMap) -> Units { - let Some(id) = ctx else { return DEFAULT_UNITS }; - if let Some(u) = cache.get(&id) { - return *u; - } - let mut u = DEFAULT_UNITS; - let mut tol_file = None; - if let Some(e) = ex.get(id) { - if let Some(units) = e.record("GLOBAL_UNIT_ASSIGNED_CONTEXT").and_then(|r| r.first()).and_then(Param::as_list) { - for uid in units.iter().filter_map(Param::as_ref_id) { - match unit_factor(ex, uid, 0) { - Some(("length", f)) if f.is_finite() && f > 0.0 => u.len = f, - Some(("angle", f)) if f.is_finite() && f > 0.0 => u.ang = f, - _ => {} - } - } - } - if let Some(unc) = e.record("GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT").and_then(|r| r.first()).and_then(Param::as_list) { - for uid in unc.iter().filter_map(Param::as_ref_id) { - if let Some(m) = ex.get(uid) - && let Some(v) = m.params().first().and_then(Param::as_f64) - { - let f = m.params().get(1).and_then(Param::as_ref_id).and_then(|x| unit_factor(ex, x, 0)).map(|x| x.1); - tol_file = Some(v * f.unwrap_or(u.len)); - } - } - } - } - u.tol = tol_file.filter(|t| t.is_finite() && *t > 0.0).map(|t| (t * 10.0).max(1e-3)).unwrap_or(u.len * 1e-2).clamp(1e-4, MAX_TOL); - u.snap = snap_limit(u.tol, ex.vertex_extent() * u.len); - cache.insert(id, u); - u + let Some(id) = ctx else { return Units::default() }; + *cache.entry(id).or_insert_with(|| solidcraft_step::units::context(ex, id)) } /// Items and context of a representation entity. @@ -255,24 +198,68 @@ fn representation(e: &Entity) -> Option<(Vec, Option)> { Some((items, p.get(2).and_then(Param::as_ref_id))) } -fn mat_mul(a: &mt::Matrix4, b: &mt::Matrix4) -> mt::Matrix4 { - a * b +/// A placement: a column-major 4×4 matrix (columns 0–2 the images of x, y and z, column 3 the +/// translation), millimetres. +type M4 = [[f64; 4]; 4]; + +const IDENTITY: M4 = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + +/// `a · b`. +fn mat_mul(a: &M4, b: &M4) -> M4 { + let mut out = [[0.0; 4]; 4]; + for (col, out_col) in out.iter_mut().enumerate() { + for (row, cell) in out_col.iter_mut().enumerate() { + *cell = (0..4).map(|k| a[k][row] * b[col][k]).sum(); + } + } + out } -fn to_array(m: &mt::Matrix4) -> [[f64; 4]; 4] { - [[m.x.x, m.x.y, m.x.z, m.x.w], [m.y.x, m.y.y, m.y.z, m.y.w], [m.z.x, m.z.y, m.z.z, m.z.w], [m.w.x, m.w.y, m.w.z, m.w.w]] +/// The determinant of a placement's linear part (its first three columns). +fn linear_det(m: &M4) -> f64 { + let [a, b, c] = [m[0], m[1], m[2]]; + a[0] * (b[1] * c[2] - b[2] * c[1]) - b[0] * (a[1] * c[2] - a[2] * c[1]) + c[0] * (a[1] * b[2] - a[2] * b[1]) } -/// Inverse of a rigid placement matrix (orthonormal rotation + translation). -fn rigid_inverse(m: &mt::Matrix4) -> mt::Matrix4 { - use mt::SquareMatrix; - m.invert().unwrap_or_else(mt::Matrix4::identity) +/// The inverse of a placement: a rotation, scaled (a transformation operator may scale), and a +/// translation. Its linear part is inverted by its adjugate, and the translation taken back +/// through that. Placements are checked non-singular where they are read +/// ([`Reader::placement_matrix`]; a frame's axes are orthonormal). +fn placement_inverse(m: &M4) -> M4 { + let det = linear_det(m); + let [a, b, c] = [m[0], m[1], m[2]]; + // The rows of the inverse are the cross products of the columns, over the determinant. + let cross = |u: [f64; 4], v: [f64; 4]| [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let rows = [cross(b, c), cross(c, a), cross(a, b)]; + let mut out = IDENTITY; + for (i, row) in rows.iter().enumerate() { + for (j, col) in out.iter_mut().take(3).enumerate() { + col[i] = row[j] / det; + } + } + // The translation taken back through the inverted linear part. + let back: [f64; 3] = std::array::from_fn(|i| -(0..3).map(|k| out[k][i] * m[3][k]).sum::()); + out[3][..3].copy_from_slice(&back); + out +} + +#[cfg(test)] +fn translation(t: [f64; 3]) -> M4 { + let mut m = IDENTITY; + m[3] = [t[0], t[1], t[2], 1.0]; + m +} + +/// The matrix of an AXIS2_PLACEMENT: its frame's axes and origin. +fn frame_matrix(p: &solidcraft_step::geom::Placement) -> M4 { + let (x, y, z, o) = (p.ref_direction, p.y(), p.axis, p.origin); + [[x[0], x[1], x[2], 0.0], [y[0], y[1], y[2], 0.0], [z[0], z[1], z[2], 0.0], [o[0], o[1], o[2], 1.0]] } struct Reader { ex: Arc, units: HashMap, - warnings: BTreeMap, + warnings: BTreeMap, /// Representation → its items and context. reps: HashMap, Option)>, /// Plain representation relationships (same product, no placement). @@ -295,7 +282,7 @@ struct Reader { once: HashSet, /// An item placed more than once: its first instance's display, shared by every instance /// (with the placement that first instance had), so the part is meshed once. - shown: HashMap, mt::Matrix4)>, + shown: HashMap, M4)>, /// How many planned solids place each item. uses: HashMap, /// An item placed more than once: read and oriented where the file defines it, so each @@ -308,6 +295,8 @@ struct Reader { visits: usize, /// Items whose meshing was checked. unmeshed_checked: HashSet, + /// Items sent into SMLib as an operation would send them, to say which need repair. + modelling_checked: HashSet, bodies: Vec, /// Solids the walk found, in file order, to be converted into bodies afterwards (so the /// conversion, the long part, can be done a piece at a time: [`StepReading`]). @@ -349,6 +338,7 @@ impl Reader { node_items: HashSet::new(), visits: 0, unmeshed_checked: HashSet::new(), + modelling_checked: HashSet::new(), bodies: Vec::new(), plan: Vec::new(), batches: Vec::new(), @@ -376,8 +366,26 @@ impl Reader { false } + /// `item`'s part is not in the design: the kernel refuses its B-rep, for `why`. + fn refused(&mut self, item: u64, why: &str) { + let label = self.label(item); + self.note(IssueKind::Refused, Some(item), 0, format!("{label}: not imported: {why}")); + } + + /// A warning about the file as a whole. fn warn(&mut self, msg: impl Into) { - *self.warnings.entry(msg.into()).or_default() += 1; + self.note(IssueKind::File, None, 0, msg); + } + + /// A warning of `kind` about `item`'s part (`faces`: the faces it concerns), counted when it + /// comes again. + fn note(&mut self, kind: IssueKind, item: Option, faces: usize, msg: impl Into) { + self.warnings.entry(msg.into()).or_insert(Noted { kind, item, faces, times: 0 }).times += 1; + } + + /// The part's own name in the file (empty: it has none). + fn part_name(&self, item: u64) -> String { + self.ex.get(item).and_then(|e| e.params().first()).and_then(Param::as_str).unwrap_or("").trim().to_string() } fn index(&mut self) { @@ -587,44 +595,44 @@ impl Reader { context_units(&self.ex, ctx, &mut self.units) } - fn placement_matrix(&mut self, item: u64, u: Units) -> R { - let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol, snap: u.snap }; - let e = geom::entity(&cx, item)?; + /// The placement an item states: an AXIS2_PLACEMENT's frame, or a + /// CARTESIAN_TRANSFORMATION_OPERATOR_3D, uniform or not: its axes, scales and origin (an + /// omitted axis is the global one, an omitted scale 1, an omitted second or third scale the + /// first). + fn placement_matrix(&mut self, item: u64, u: Units) -> R { + let reader = solidcraft_step::read::Reader::new(&self.ex, u.units); + let e = self.ex.get(item).ok_or_else(|| format!("missing entity #{item}"))?; if matches!(e.name(), "CARTESIAN_TRANSFORMATION_OPERATOR_3D" | "CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM") { 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 { + let o = reader.point(p.get(4).and_then(Param::as_ref_id).ok_or("transformation without origin")?)?; + let direction = |i: usize, global: [f64; 3]| -> R<[f64; 3]> { match p.get(i) { - None | Some(Param::Null) => Ok(fallback), - Some(Param::Ref(id)) => geom::direction(&cx, *id), + None | Some(Param::Null) => Ok(global), + Some(Param::Ref(id)) => reader.direction(*id), _ => Err("invalid transformation direction".into()), } }; - let scale = |i: usize, fallback: f64| -> R { + let scale = |i: usize, default: f64| -> R { match p.get(i) { - None | Some(Param::Null) => Ok(fallback), + None | Some(Param::Null) => Ok(default), 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()) { + let (x, y, z) = (direction(2, [1.0, 0.0, 0.0])?, direction(3, [0.0, 1.0, 0.0])?, direction(6, [0.0, 0.0, 1.0])?); + let col = |d: [f64; 3], s: f64| [d[0] * s, d[1] * s, d[2] * s, 0.0]; + let m = [col(x, sx), col(y, sy), col(z, sz), [o[0], o[1], o[2], 1.0]]; + if !m.iter().flatten().all(|x| x.is_finite()) { return Err("invalid transformation scale".into()); } - use mt::SquareMatrix as _; - let det = m.determinant(); + let det = linear_det(&m); if !det.is_finite() || det == 0.0 { return Err("singular transformation".into()); } return Ok(m); } - Ok(geom::frame(&cx, item)?.matrix()) + Ok(frame_matrix(&reader.frame(item)?)) } /// Representations of a product (its own shape representations and those linked to them). @@ -657,12 +665,12 @@ impl Reader { } fn label(&self, item: u64) -> String { - let name = self.ex.get(item).and_then(|e| e.params().first()).and_then(Param::as_str).unwrap_or("").trim().to_string(); + let name = self.part_name(item); if name.is_empty() { format!("solid #{item}") } else { format!("solid '{name}'") } } /// Bodies of a representation's items (following mapped items), placed by `m`. - fn rep_bodies(&mut self, rep: u64, m: &mt::Matrix4, path: &[String], product: &str, instance: Option<&str>, out: &mut Vec, depth: usize) { + fn rep_bodies(&mut self, rep: u64, m: &M4, path: &[String], product: &str, instance: Option<&str>, out: &mut Vec, depth: usize) { if depth > MAX_ASSEMBLY_DEPTH { self.warn("mapped items nested too deeply"); return; @@ -707,10 +715,22 @@ impl Reader { self.warn(format!("more than {MAX_BODIES} bodies: the rest are left out")); return; } - // The node lists the planned solid; it becomes a body index once converted. - out.push(self.plan.len()); - self.plan.push(Planned { item, units: u, batch: id }); - *self.uses.entry(item).or_default() += 1; + // The node lists the planned solids (a surface model's closed shells + // beside its sheet are solids of their own, in the model's colour); each + // becomes a body index once converted. + for piece in solidcraft_step::topology::items(&self.ex, item) { + if piece != item { + if let Some(c) = self.colors.get(&item).copied() { + self.colors.entry(piece).or_insert(c); + } + if let Some(o) = self.opacity.get(&item).copied() { + self.opacity.entry(piece).or_insert(o); + } + } + out.push(self.plan.len()); + self.plan.push(Planned { item: piece, units: u, batch: id }); + *self.uses.entry(piece).or_default() += 1; + } } } "MAPPED_ITEM" => { @@ -725,7 +745,7 @@ impl Reader { let mu = self.units_of(mapped); match (self.placement_matrix(target, u), self.placement_matrix(origin, mu)) { (Ok(t), Ok(o)) => { - let mm = mat_mul(m, &mat_mul(&t, &rigid_inverse(&o))); + let mm = mat_mul(m, &mat_mul(&t, &placement_inverse(&o))); for r in self.rep_closure(&[mapped]) { self.rep_bodies(r, &mm, path, product, instance, out, depth + 1); } @@ -755,45 +775,67 @@ impl Reader { let first = self.converted; // The next solids, across instances and parts, converted together: parts still to // orient are shared out between the workers. A part that comes back within the window - // waits for the next one, which places the orientation its first instance found. - let mut last = first + 1; - if !single { - let mut fresh: HashSet = self.plan.get(first).map(|p| p.item).into_iter().collect(); - while let Some(p) = self.plan.get(last) - && last - first < MAX_WINDOW - { - if !self.oriented.contains_key(&p.item) && !fresh.insert(p.item) { - break; - } - last += 1; - } - } + // is placed once its first instance is read, from the orientation that instance found. + let last = if single { first + 1 } else { (first + MAX_WINDOW).min(self.plan.len()) }; self.converted = last; let ex = self.ex.clone(); + // Each planned solid of the window, with its job (`None`: a later instance of a part an + // earlier job of the window reads, placed after it). let mut sources = Vec::new(); let mut jobs = Vec::new(); + let mut reading = HashSet::new(); for i in first..last { self.made.push(None); let Some(p) = self.plan.get(i) else { continue }; let (item, units) = (p.item, p.units); + let placement = self.batches.get(p.batch).map_or(IDENTITY, |b| b.m); + if reading.contains(&item) { + sources.push((i, item, placement, None)); + continue; + } if let Some(again) = self.unreadable.get(&item) { if let Some(msg) = again.clone() { - let label = self.label(item); - self.warn(format!("{label}: not imported: {msg}")); + self.refused(item, &msg); } continue; } let source = match self.oriented.get(&item) { Some(part) => parallel::Source::Oriented(part.clone()), - None => parallel::Source::Item { item, units }, + None => { + reading.insert(item); + parallel::Source::Item { item, units } + } }; - let placement = self.batches.get(p.batch).map_or(mt::Matrix4::from_scale(1.0), |b| b.m); - sources.push((i, item)); - jobs.push(parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item), tol: units.tol }); + sources.push((i, item, placement, Some(jobs.len()))); + jobs.push(parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item) }); } // Reading and orienting new parts is shared out between the workers. - let prepared = parallel::bodies(&ex, &jobs, self.workers); - for ((i, item), made) in sources.into_iter().zip(prepared) { + let mut prepared: Vec> = parallel::bodies(&ex, &jobs, self.workers).into_iter().map(Some).collect(); + for (i, item, placement, job) in sources { + let made = match job { + Some(j) => match prepared.get_mut(j).and_then(Option::take) { + Some(made) => made, + None => continue, + }, + // A later instance of a part read in this window: as it would be in the next + // window, after its first instance. + None => { + if let Some(again) = self.unreadable.get(&item) { + if let Some(msg) = again.clone() { + self.refused(item, &msg); + } + continue; + } + let source = match self.oriented.get(&item) { + Some(part) => parallel::Source::Oriented(part.clone()), + None => match self.plan.get(i) { + Some(p) => parallel::Source::Item { item, units: p.units }, + None => continue, + }, + }; + parallel::prepare(&ex, ¶llel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item) }) + } + }; let Some(e) = ex.get(item) else { continue }; let Some(batch) = self.plan.get(i).and_then(|p| self.batches.get(p.batch)) else { continue }; let (m, path, product, instance) = (batch.m, batch.path.clone(), batch.product.clone(), batch.instance.clone()); @@ -802,11 +844,18 @@ impl Reader { // What the read of the item found, reported once. if let Some(failed) = read { let label = self.label(item); - for f in &failed { - self.warn(format!("{label}: {f}")); + if let Some(why) = &part.refused { + self.note(IssueKind::ImportedAsSurfaces, Some(item), 0, format!("{label}: imported as surfaces: {why}")); } - if !part.closed { - self.warn(format!("{label}: imported as an open body (the shell is not closed)")); + for f in &failed { + let (kind, faces, f) = match f { + parallel::Note::LeftOut(f) => (IssueKind::FaceLeftOut, 1, f), + parallel::Note::Repaired(f) => (IssueKind::Repaired, 0, f), + }; + self.note(kind, Some(item), faces, format!("{label}: {f}")); + } + if !part.closed && part.refused.is_none() { + self.note(IssueKind::OpenBody, Some(item), 0, format!("{label}: imported as an open body (the shell is not closed)")); } } if !self.once.contains(&item) { @@ -817,7 +866,12 @@ impl Reader { let name = if own.is_empty() { product.clone() } else { own }; // Faces the mesher gives up on (or that the budget cut short) are reported. if self.unmeshed_checked.insert(item) && missing > 0 { - self.warn(format!("solid '{name}': {missing} face(s) could not be meshed and are not shown")); + self.note( + IssueKind::FacesNotShown, + Some(item), + missing, + format!("solid '{name}': {missing} face(s) could not be meshed and are not shown"), + ); } if let Some(slot) = self.made.get_mut(i) { *slot = Some(self.bodies.len()); @@ -842,14 +896,23 @@ impl Reader { // Every instance of a part placed more than once shows its first instance's // mesh, placed (the first one too: meshing its own would mesh the part twice). let body = match self.shown.get(&item) { - Some((shared, first)) => body.with_display_of(shared.clone(), to_array(&mat_mul(&m, &rigid_inverse(first)))), + Some((shared, first)) => body.with_display_of(shared.clone(), mat_mul(&m, &placement_inverse(first))), None if self.uses.get(&item).is_some_and(|n| *n > 1) => { let shared = Arc::new(crate::body::SharedDisplay::new(body.clone())); self.shown.insert(item, (shared.clone(), m)); - body.with_display_of(shared, to_array(&mt::Matrix4::from_scale(1.0))) + body.with_display_of(shared, IDENTITY) } None => body, }; + // A part SMLib refuses cannot be modelled on: found now (its first instance, + // sent as an operation would send it), not at the first operation. + if self.modelling_checked.insert(item) + && let Some(refused) = body.smlib_refusal() + { + let at = refused.face.map(|f| format!(" (face {})", f + 1)).unwrap_or_default(); + let msg = format!("solid '{name}': needs repair before it can be modelled: {}{at}", refused.why); + self.note(IssueKind::NeedsRepair, Some(item), usize::from(refused.face.is_some()), msg); + } self.bodies.push(ImportedBody { name, body, @@ -860,11 +923,16 @@ impl Reader { file_faces, source_item: item, face_origin, + refused: part.refused.clone(), }); } Err(parallel::Failure { read, msg }) => { - let label = self.label(item); - self.warn(format!("{label}: not imported: {msg}")); + if read { + let label = self.label(item); + self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}")); + } else { + self.refused(item, &msg); + } // Later instances don't read the item again. if !self.oriented.contains_key(&item) { self.unreadable.insert(item, (!read).then_some(msg)); @@ -875,6 +943,27 @@ impl Reader { true } + /// The warnings (worded as `warnings`, in their order) by kind and part, and how many of the + /// file's parts came in as closed solids. + fn report(&self, warnings: &[String]) -> ImportReport { + let parts = self.plan.iter().map(|p| p.item).collect::>().len(); + let solids = self.bodies.iter().filter(|b| b.closed && b.refused.is_none()).map(|b| b.source_item).collect::>().len(); + let issues = self + .warnings + .values() + .zip(warnings) + .map(|(n, detail)| ImportIssue { + kind: n.kind, + item: n.item, + part: n.item.map(|i| self.part_name(i)).unwrap_or_default(), + faces: n.faces, + times: n.times, + detail: detail.clone(), + }) + .collect(); + ImportReport { parts, solids, issues } + } + /// Planned-solid indices (a node's `bodies` after the walk) as body indices, leaving out /// the ones that failed. fn remap(&self, planned: &[usize]) -> Vec { @@ -907,10 +996,10 @@ impl Reader { } /// Placement of a child occurrence in its parent. - fn occurrence_matrix(&mut self, nauo: u64, child_reps: &[u64]) -> mt::Matrix4 { - let Some(&rel) = self.placements.get(&nauo) else { return mt::Matrix4::from_scale(1.0) }; + fn occurrence_matrix(&mut self, nauo: u64, child_reps: &[u64]) -> M4 { + let Some(&rel) = self.placements.get(&nauo) else { return IDENTITY }; let ex = self.ex.clone(); - let r = (|| -> R { + let r = (|| -> R { let e = ex.get(rel).ok_or("missing placement")?; let rr = e.record("REPRESENTATION_RELATIONSHIP").ok_or("placement without representations")?; let (r1, r2) = @@ -932,7 +1021,7 @@ impl Reader { let m2 = self.placement_matrix(i2, u2)?; // rep_1 is normally the component: map its item onto the assembly's item. let child_is_1 = child_reps.contains(&r1) || !child_reps.contains(&r2); - Ok(if child_is_1 { mat_mul(&m2, &rigid_inverse(&m1)) } else { mat_mul(&m1, &rigid_inverse(&m2)) }) + Ok(if child_is_1 { mat_mul(&m2, &placement_inverse(&m1)) } else { mat_mul(&m1, &placement_inverse(&m2)) }) } else { self.placement_matrix(op, u2) } @@ -941,23 +1030,14 @@ impl Reader { Ok(m) => m, Err(e) => { self.warn(format!("component placement #{rel}: {e} (placed at the origin)")); - mt::Matrix4::from_scale(1.0) + IDENTITY } } } - fn node( - &mut self, - pd: u64, - local: mt::Matrix4, - world: mt::Matrix4, - path: &[String], - instance: Option<&str>, - depth: usize, - stack: &mut Vec, - ) -> StepNode { + fn node(&mut self, pd: u64, local: M4, world: M4, path: &[String], instance: Option<&str>, depth: usize, stack: &mut Vec) -> StepNode { let name = self.product_name(pd); - let mut node = StepNode { name: name.clone(), transform: to_array(&local), bodies: Vec::new(), children: Vec::new() }; + let mut node = StepNode { name: name.clone(), transform: local, bodies: Vec::new(), children: Vec::new() }; if self.stop() { return node; } @@ -996,96 +1076,29 @@ impl Reader { } } -/// Check a STEP file's structure: it parses, no entity id is defined twice, every reference -/// names a defined entity, nothing but root entities (relationships, definitions, -/// presentation) is left unreferenced, and ids are dense (`#1`…`#n`). Returns the entity count. -/// Faces whose boundary runs the wrong way round their normal, as a strict reader -/// sees them: each face's normal is its surface's own parametric normal (∂S/∂u × ∂S/∂v, ISO -/// 10303-42), reversed when `same_sense` is false, and the outer loop must run counter-clockwise -/// seen from that side. Checked on faces whose loop spans a clear direction (patches, not bands -/// around a closed surface). Returns one message per bad face. +/// Faces whose boundary runs the wrong way round their normal, as a strict reader sees them: +/// each face's normal is its surface's own parametric normal (∂S/∂u × ∂S/∂v, ISO 10303-42), +/// reversed when `same_sense` is false, and the outer loop must run counter-clockwise seen from +/// that side. These are the faces the STEP reader turns over ([`solidcraft_step::topology`]), +/// numbered as the solid's body numbers them. Returns one message per bad face; an error when +/// the file does not parse or has no solid the reader can read. pub fn step_orientation_errors(text: &str) -> std::result::Result, String> { - use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; - let imp = step_import(text).map_err(|e| e.to_string())?; + let ex = p21::parse(text)?; + let read = solidcraft_step::topology::read_solids_with(&ex, &solidcraft_smlib::pcurves::SmlibTrims); + if read.solids.is_empty() { + return Err(read.failures.first().map_or_else(|| "the file has no solids".into(), |f| format!("solid #{}: {}", f.item, f.message))); + } let mut out = Vec::new(); - for b in &imp.bodies { - let r = guard("orientation check", || { - let mut bad = Vec::new(); - for (fi, f) in b.body.solid.face_iter().enumerate() { - let bounds = f.boundaries(); - // Patches only: a face with several loops (a band between two rings, a face with - // holes) has no single loop direction to compare. - let [w] = bounds.as_slice() else { continue }; - // Only revolutions (cylinders, cones, spheres, tori: closed surfaces, where a loop - // read the wrong way round silently gives the rest of the surface). On free-form - // strips the loop's normals vary too much for this test; the round trips' volume - // checks cover those. - if !matches!(f.surface(), mt::Surface::RevolutedCurve(_)) { - continue; - } - // A loop through a vertex twice (a figure eight round a pole) has no single direction. - let fronts: std::collections::HashSet<_> = w.edge_iter().map(|e| e.front().id()).collect(); - if fronts.len() != w.len() { - continue; - } - let pts: Vec = w - .edge_iter() - .flat_map(|e| { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - (0..16).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 16.0)).collect::>() - }) - .collect(); - let n = pts.len(); - if n < 3 { - continue; - } - let mut newell = mt::Vector3::new(0.0, 0.0, 0.0); - let mut c = mt::Vector3::new(0.0, 0.0, 0.0); - let mut span: f64 = 0.0; - for i in 0..n { - let (Some(a), Some(q)) = (pts.get(i), pts.get((i + 1) % n)) else { continue }; - newell += (a.to_vec()).cross(q.to_vec()); - c += a.to_vec(); - span = span.max((a - pts[0]).magnitude()); - } - let c = mt::Point3::from_vec(c / n as f64); - // Bands round a closed surface have no clear loop direction. - if !(newell.magnitude() > 0.05 * span * span) { - continue; - } - // The face normal averaged along the loop (each loop point is on the surface; - // the loop's centroid can be nearer the wrong side of a curved face). - let s = f.oriented_surface(); - let mut normal = mt::Vector3::new(0.0, 0.0, 0.0); - let mut count = 0usize; - for p in &pts { - if let Some(uv) = s.search_nearest_parameter(*p, None, 100) { - let n = s.normal(uv.0, uv.1); - if n.x.is_finite() && n.y.is_finite() && n.z.is_finite() { - normal += n; - count += 1; - } - } - } - let _ = c; - // Only patches clearly to one side of their loop are judged: a loop on a closed - // surface (a sphere's cube-face square) bounds either part. - if count == 0 || normal.magnitude() < 0.7 * count as f64 { - continue; - } - if normal.dot(newell) < 0.0 { - bad.push(format!("{}: face {fi} runs clockwise around its normal", b.name)); - } - } - Ok(bad) - }) - .map_err(|e| e.to_string())?; - out.extend(r); + for solid in &read.solids { + let name = if solid.name.trim().is_empty() { format!("solid #{}", solid.item) } else { solid.name.trim().to_string() }; + out.extend(solid.turned.iter().map(|f| format!("{name}: face {f} runs clockwise around its normal"))); } Ok(out) } +/// Check a STEP file's structure: it parses, no entity id is defined twice, every reference +/// names a defined entity, nothing but root entities (relationships, definitions, +/// presentation) is left unreferenced, and ids are dense (`#1`…`#n`). Returns the entity count. pub fn step_validate(text: &str) -> std::result::Result { let ex = p21::parse(text)?; if let Some(d) = ex.duplicates.first() { @@ -1208,6 +1221,7 @@ pub fn step_import(text: &str) -> Result { } fn step_import_with_workers(text: &str, workers: usize) -> Result { + let _span = solidcraft_profile::span("import", "step.import"); let mut reading = StepReading::with_workers(text, workers)?; while reading.step() {} reading.finish() @@ -1234,10 +1248,12 @@ impl StepReading { } fn with_workers(text: &str, workers: usize) -> Result { + let _span = solidcraft_profile::span("import", "step.read_structure"); let key = text_key(text); let watch = crate::watch::current(); let cancelled = || watch.as_ref().is_some_and(|w| w.cancelled()); - let ex = match p21::parse(text) { + let parsed = solidcraft_profile::scope("import", "step.parse", || p21::parse(text)); + let ex = match parsed { Ok(ex) => Arc::new(ex), Err(_) if cancelled() => return Err(crate::watch::cancelled_error("STEP import")), Err(e) => return Err(KernelError::Invalid(e)), @@ -1249,14 +1265,14 @@ impl StepReading { .filter(|e| matches!(e.name(), "MANIFOLD_SOLID_BREP" | "BREP_WITH_VOIDS" | "FACETED_BREP" | "SHELL_BASED_SURFACE_MODEL")) .count(); rd.watch = watch.clone(); - rd.index(); + solidcraft_profile::scope("import", "step.index", || rd.index()); // Roots: product definitions that are nobody's component. let child_pds: HashSet = rd.children.values().flatten().filter_map(|n| ex.get(*n).and_then(|e| e.params().get(4)).and_then(Param::as_ref_id)).collect(); let mut roots: Vec = ex.entities.iter().filter(|(id, e)| e.name() == "PRODUCT_DEFINITION" && !child_pds.contains(id)).map(|(id, _)| *id).collect(); roots.sort(); - let identity = mt::Matrix4::from_scale(1.0); + let identity = IDENTITY; let mut tree = Vec::new(); for pd in roots { tree.push(rd.node(pd, identity, identity, &[], None, 0, &mut Vec::new())); @@ -1282,7 +1298,7 @@ impl StepReading { for r in loose { rd.rep_bodies(r, &identity, &[], "Import", None, &mut bodies, 0); } - tree.push(StepNode { name: "Import".into(), transform: to_array(&identity), bodies, children: Vec::new() }); + tree.push(StepNode { name: "Import".into(), transform: identity, bodies, children: Vec::new() }); } let single = workers <= 1; Ok(StepReading { rd, tree, key, small: text.len() <= KEEP_SMALL_BYTES, single }) @@ -1291,6 +1307,7 @@ impl StepReading { /// Convert the next solid (or batch of solids); false once all are converted (or the /// watch cancelled the import). pub fn step(&mut self) -> bool { + let _span = solidcraft_profile::span("import", "step.convert_batch"); self.rd.convert_next(self.single) } @@ -1302,6 +1319,7 @@ impl StepReading { /// The import, once [`Self::step`] has converted every solid. pub fn finish(mut self) -> Result { while self.step() {} + let _span = solidcraft_profile::span("import", "step.finish"); let rd = &mut self.rd; // Cancelled: what was read so far is dropped here, not cached. if rd.cancelled || rd.watch.as_ref().is_some_and(|w| w.cancelled()) { @@ -1316,7 +1334,8 @@ impl StepReading { if let Some(first) = ex.duplicates.first() { rd.warn(format!("{} entity ids are defined twice (first #{first}); the first definitions were used", ex.duplicates.len())); } - let warnings: Vec = rd.warnings.iter().map(|(m, n)| if *n > 1 { format!("{m} (×{n})") } else { m.clone() }).collect(); + let warnings: Vec = rd.warnings.iter().map(|(m, n)| if n.times > 1 { format!("{m} (×{})", n.times) } else { m.clone() }).collect(); + let report = rd.report(&warnings); if rd.bodies.is_empty() { let why = warnings.first().cloned().unwrap_or_else(|| "the file has no solids".into()); return Err(KernelError::Failed(format!("STEP import: no bodies ({why})"))); @@ -1326,6 +1345,7 @@ impl StepReading { bodies, tree, warnings, + report, schema: ex.schemas.join(", "), system: ex.originating_system.clone(), preprocessor: ex.preprocessor.clone(), diff --git a/crates/kernel/src/step_in/p21.rs b/crates/kernel/src/step_in/p21.rs index e862774b3..fd850160f 100644 --- a/crates/kernel/src/step_in/p21.rs +++ b/crates/kernel/src/step_in/p21.rs @@ -1,601 +1,20 @@ -//! ISO 10303-21 ("Part 21") exchange structure parser: the HEADER and the DATA section's entity -//! instances, simple (`#1=NAME(...)`) and complex (`#2=(A(...) B(...))`). Written from the -//! public standard. Input is hostile: sizes, entity counts and nesting depth are capped and every -//! error is a message, never a panic. +//! The Part 21 parser lives in `solidcraft-step`; this reads with the kernel's progress watch. -use std::collections::HashMap; +pub use solidcraft_step::p21::{Entity, Exchange, Param}; -/// Largest STEP text we parse. -pub const MAX_BYTES: usize = 512 << 20; -/// Most entity instances in one file. -pub const MAX_ENTITIES: usize = 20_000_000; -/// Deepest parameter list nesting. -const MAX_DEPTH: usize = 64; +struct Watched(std::sync::Arc); -/// A parameter value. -#[derive(Clone, Debug, PartialEq)] -pub enum Param { - Int(i64), - Real(f64), - Str(String), - /// `.NAME.` (`.T.`/`.F.` included). - Enum(String), - Ref(u64), - List(Vec), - /// `NAME(params)` (a typed value such as `LENGTH_MEASURE(1.)`). - Typed(String, Vec), - Binary(String), - /// `$` - Null, - /// `*` - Derived, -} - -impl Param { - pub fn as_f64(&self) -> Option { - match self { - Param::Real(x) => Some(*x).filter(|x| x.is_finite()), - Param::Int(i) => Some(*i as f64), - Param::Typed(_, v) if v.len() == 1 => v.first().and_then(Param::as_f64), - _ => None, - } +impl solidcraft_step::p21::Progress for Watched { + fn cancelled(&self) -> bool { + self.0.cancelled() } - pub fn as_i64(&self) -> Option { - match self { - Param::Int(i) => Some(*i), - Param::Real(x) if x.fract() == 0.0 && x.abs() < 9e15 => Some(*x as i64), - _ => None, - } - } - pub fn as_ref_id(&self) -> Option { - match self { - Param::Ref(r) => Some(*r), - _ => None, - } - } - pub fn as_str(&self) -> Option<&str> { - match self { - Param::Str(s) => Some(s), - _ => None, - } - } - pub fn as_enum(&self) -> Option<&str> { - match self { - Param::Enum(s) => Some(s), - _ => None, - } - } - /// `.T.` → true, `.F.` → false (`.U.` and anything else → None). - pub fn as_bool(&self) -> Option { - match self.as_enum()? { - "T" => Some(true), - "F" => Some(false), - _ => None, - } - } - pub fn as_list(&self) -> Option<&[Param]> { - match self { - Param::List(v) => Some(v), - _ => None, - } + fn progress(&self, stage: &'static str, done: usize, total: usize) { + self.0.progress(stage, done, total); } } -/// One record of an entity instance: a simple instance has one, a complex one several. -#[derive(Clone, Debug, PartialEq)] -pub struct Record { - pub name: String, - pub params: Vec, -} - -/// An entity instance. -#[derive(Clone, Debug, PartialEq)] -pub struct Entity { - pub records: Vec, -} - -impl Entity { - pub fn is_complex(&self) -> bool { - self.records.len() > 1 - } - /// Name of a simple instance (the first record of a complex one). - pub fn name(&self) -> &str { - self.records.first().map(|r| r.name.as_str()).unwrap_or("") - } - /// Parameters of the record called `name`. - pub fn record(&self, name: &str) -> Option<&[Param]> { - self.records.iter().find(|r| r.name == name).map(|r| r.params.as_slice()) - } - pub fn has(&self, name: &str) -> bool { - self.records.iter().any(|r| r.name == name) - } - /// Parameters of a simple instance. - pub fn params(&self) -> &[Param] { - self.records.first().map(|r| r.params.as_slice()).unwrap_or(&[]) - } -} - -/// A parsed exchange file. -#[derive(Clone, Debug, Default)] -pub struct Exchange { - /// FILE_SCHEMA names. - pub schemas: Vec, - /// FILE_NAME originating system. - pub originating_system: String, - /// FILE_NAME preprocessor version. - pub preprocessor: String, - /// FILE_DESCRIPTION text, its lines joined by a space. - pub description: String, - pub entities: HashMap, - /// Ids defined more than once (the first definition is kept). - pub duplicates: Vec, - /// [`Exchange::vertex_extent`], worked out on first use. - extent: std::sync::OnceLock, -} - -impl Exchange { - pub fn get(&self, id: u64) -> Option<&Entity> { - self.entities.get(&id) - } - - /// The size of the model in the file's own coordinates: the diagonal of the box around every - /// VERTEX_POINT (0 for a file without one). Non-finite coordinates are skipped. - pub fn vertex_extent(&self) -> f64 { - *self.extent.get_or_init(|| { - let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); - for e in self.entities.values().filter(|e| e.name() == "VERTEX_POINT") { - let Some(p) = e.params().get(1).and_then(Param::as_ref_id).and_then(|id| self.get(id)) else { continue }; - let Some(xyz) = p.params().get(1).and_then(Param::as_list) else { continue }; - let c: Vec = xyz.iter().take(3).filter_map(Param::as_f64).collect(); - if c.len() != 3 || !c.iter().all(|x| x.is_finite()) { - continue; - } - for ((l, h), x) in lo.iter_mut().zip(hi.iter_mut()).zip(c) { - *l = l.min(x); - *h = h.max(x); - } - } - let d = lo.iter().zip(&hi).map(|(l, h)| (h - l).powi(2)).sum::().sqrt(); - if d.is_finite() { d } else { 0.0 } - }) - } -} - -struct Lexer<'a> { - s: &'a [u8], - i: usize, -} - -fn err(msg: impl Into) -> Result { - Err(msg.into()) -} - -impl<'a> Lexer<'a> { - fn line(&self) -> usize { - self.s.get(..self.i).map(|b| b.iter().filter(|c| **c == b'\n').count() + 1).unwrap_or(0) - } - fn fail(&self, msg: &str) -> Result { - err(format!("STEP syntax error at line {}: {msg}", self.line())) - } - fn peek(&self) -> Option { - self.s.get(self.i).copied() - } - /// Skip whitespace and comments. - fn ws(&mut self) -> Result<(), String> { - loop { - match self.peek() { - Some(c) if c.is_ascii_whitespace() => self.i += 1, - Some(b'/') if self.s.get(self.i + 1) == Some(&b'*') => { - let rest = self.s.get(self.i + 2..).unwrap_or(&[]); - match rest.windows(2).position(|w| w == b"*/") { - Some(p) => self.i += p + 4, - None => return self.fail("unterminated comment"), - } - } - _ => return Ok(()), - } - } - } - fn eat(&mut self, c: u8) -> Result { - self.ws()?; - if self.peek() == Some(c) { - self.i += 1; - Ok(true) - } else { - Ok(false) - } - } - fn expect(&mut self, c: u8) -> Result<(), String> { - if self.eat(c)? { Ok(()) } else { self.fail(&format!("expected `{}`", c as char)) } - } - fn keyword(&mut self) -> Result { - self.ws()?; - let st = self.i; - if self.peek() == Some(b'!') { - self.i += 1; - } - while let Some(c) = self.peek() { - if c.is_ascii_alphanumeric() || c == b'_' || c == b'-' { - self.i += 1; - } else { - break; - } - } - if self.i == st { - return self.fail("expected a keyword"); - } - Ok(String::from_utf8_lossy(self.s.get(st..self.i).unwrap_or(&[])).to_ascii_uppercase()) - } - fn number(&mut self) -> Result { - let st = self.i; - while let Some(c) = self.peek() { - if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.' | b'E' | b'e') { - self.i += 1; - } else { - break; - } - } - let t = std::str::from_utf8(self.s.get(st..self.i).unwrap_or(&[])).unwrap_or(""); - if !t.contains(['.', 'E', 'e']) - && let Ok(i) = t.parse::() - { - return Ok(Param::Int(i)); - } - // STEP allows `1.` and `1.E-3`. - let fixed = t.replace(".E", ".0E").replace(".e", ".0e"); - let fixed = if fixed.ends_with('.') { format!("{fixed}0") } else { fixed }; - match fixed.parse::() { - Ok(x) => Ok(Param::Real(x)), - Err(_) => self.fail(&format!("bad number `{t}`")), - } - } - fn string(&mut self) -> Result { - // Opening quote consumed by the caller. - let mut raw = Vec::new(); - loop { - match self.peek() { - None => return self.fail("unterminated string"), - Some(b'\'') => { - if self.s.get(self.i + 1) == Some(&b'\'') { - raw.push(b'\''); - self.i += 2; - } else { - self.i += 1; - break; - } - } - Some(b'\n') | Some(b'\r') => self.i += 1, - Some(c) => { - raw.push(c); - self.i += 1; - } - } - } - Ok(decode_string(&raw)) - } - fn param(&mut self, depth: usize) -> Result { - if depth > MAX_DEPTH { - return self.fail("parameters nested too deeply"); - } - self.ws()?; - let Some(c) = self.peek() else { return self.fail("unexpected end of file") }; - match c { - b'$' => { - self.i += 1; - Ok(Param::Null) - } - b'*' => { - self.i += 1; - Ok(Param::Derived) - } - b'\'' => { - self.i += 1; - Ok(Param::Str(self.string()?)) - } - b'"' => { - self.i += 1; - let st = self.i; - while self.peek().is_some_and(|c| c != b'"') { - self.i += 1; - } - let v = String::from_utf8_lossy(self.s.get(st..self.i).unwrap_or(&[])).to_string(); - self.expect(b'"')?; - Ok(Param::Binary(v)) - } - b'#' => { - self.i += 1; - let st = self.i; - while self.peek().is_some_and(|c| c.is_ascii_digit()) { - self.i += 1; - } - let t = std::str::from_utf8(self.s.get(st..self.i).unwrap_or(&[])).unwrap_or(""); - t.parse::().map(Param::Ref).or_else(|_| self.fail("bad entity reference")) - } - b'.' if self.s.get(self.i + 1).is_some_and(|c| c.is_ascii_alphabetic() || *c == b'_') => { - self.i += 1; - let st = self.i; - while self.peek().is_some_and(|c| c != b'.') { - self.i += 1; - } - let v = String::from_utf8_lossy(self.s.get(st..self.i).unwrap_or(&[])).trim().to_ascii_uppercase(); - self.expect(b'.')?; - Ok(Param::Enum(v)) - } - b'(' => { - self.i += 1; - Ok(Param::List(self.list_rest(depth + 1)?)) - } - c if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') => self.number(), - c if c.is_ascii_alphabetic() || c == b'!' => { - let name = self.keyword()?; - self.expect(b'(')?; - Ok(Param::Typed(name, self.list_rest(depth + 1)?)) - } - _ => self.fail(&format!("unexpected `{}`", c as char)), - } - } - /// Parameters after an opening `(` up to and including the `)`. - fn list_rest(&mut self, depth: usize) -> Result, String> { - let mut v = Vec::new(); - if self.eat(b')')? { - return Ok(v); - } - loop { - v.push(self.param(depth)?); - if self.eat(b',')? { - continue; - } - self.expect(b')')?; - return Ok(v); - } - } - fn record(&mut self) -> Result { - let name = self.keyword()?; - self.expect(b'(')?; - Ok(Record { name, params: self.list_rest(1)? }) - } -} - -/// Decode the Part 21 string escapes (`\X\hh`, `\X2\…\X0\`, `\X4\…\X0\`, `\S\c`, `\\`). -fn decode_string(raw: &[u8]) -> String { - let mut out = String::new(); - let mut i = 0; - let hex = |b: &[u8]| std::str::from_utf8(b).ok().and_then(|t| u32::from_str_radix(t, 16).ok()); - while let Some(&c) = raw.get(i) { - if c == b'\\' { - let rest = raw.get(i..).unwrap_or(&[]); - if rest.starts_with(b"\\\\") { - out.push('\\'); - i += 2; - continue; - } - if rest.starts_with(b"\\X\\") - && let Some(v) = rest.get(3..5).and_then(hex) - { - out.push(char::from_u32(v).unwrap_or('?')); - i += 5; - continue; - } - let mut run = false; - for (tag, width) in [(&b"\\X2\\"[..], 4usize), (&b"\\X4\\"[..], 8)] { - if rest.starts_with(tag) - && let Some(end) = rest.windows(4).position(|w| w == b"\\X0\\") - { - let body = rest.get(4..end).unwrap_or(&[]); - let units: Vec = body.chunks(width).filter_map(hex).collect(); - if width == 4 { - let u16s: Vec = units.iter().map(|u| *u as u16).collect(); - out.push_str(&String::from_utf16_lossy(&u16s)); - } else { - out.extend(units.iter().map(|u| char::from_u32(*u).unwrap_or('?'))); - } - i += end + 4; - run = true; - break; - } - } - // A run may be followed straight away by the backslash of the next escape (#2344). - if run { - continue; - } - if rest.starts_with(b"\\S\\") - && let Some(&ch) = rest.get(3) - { - out.push(char::from_u32(ch as u32 + 128).unwrap_or('?')); - i += 4; - continue; - } - out.push('\\'); - i += 1; - continue; - } - // Plain bytes: keep UTF-8 runs intact. - let st = i; - while raw.get(i).is_some_and(|c| *c != b'\\') { - i += 1; - } - out.push_str(&String::from_utf8_lossy(raw.get(st..i).unwrap_or(&[]))); - } - out -} - -/// Parse a Part 21 file. +/// [`solidcraft_step::p21::parse`] under the current [`crate::watch`]. pub fn parse(text: &str) -> Result { - if text.len() > MAX_BYTES { - return err(format!("STEP file too large ({} MB, limit {} MB)", text.len() >> 20, MAX_BYTES >> 20)); - } - let mut lx = Lexer { s: text.as_bytes(), i: 0 }; - let magic = lx.keyword()?; - if magic != "ISO-10303-21" { - return err("not a STEP file (no ISO-10303-21 header)"); - } - lx.expect(b';')?; - let mut ex = Exchange::default(); - let watch = crate::watch::current(); - loop { - lx.ws()?; - if lx.peek().is_none() { - return err("STEP file ends without END-ISO-10303-21"); - } - let kw = lx.keyword()?; - match kw.as_str() { - "HEADER" => { - lx.expect(b';')?; - loop { - let k = lx.keyword()?; - if k == "ENDSEC" { - lx.expect(b';')?; - break; - } - lx.expect(b'(')?; - let params = lx.list_rest(1)?; - lx.expect(b';')?; - match k.as_str() { - "FILE_SCHEMA" => { - if let Some(Param::List(v)) = params.first() { - ex.schemas = v.iter().filter_map(|p| p.as_str().map(str::to_string)).collect(); - } - } - "FILE_DESCRIPTION" => { - if let Some(Param::List(v)) = params.first() { - ex.description = v.iter().filter_map(|p| p.as_str()).collect::>().join(" "); - } - } - "FILE_NAME" => { - ex.preprocessor = params.get(4).and_then(Param::as_str).unwrap_or("").to_string(); - ex.originating_system = params.get(5).and_then(Param::as_str).unwrap_or("").to_string(); - } - _ => {} - } - } - } - "DATA" => { - // Optional `DATA('name', ('schema'));` - if lx.eat(b'(')? { - lx.list_rest(1)?; - } - lx.expect(b';')?; - loop { - lx.ws()?; - if lx.peek() != Some(b'#') { - let k = lx.keyword()?; - if k == "ENDSEC" { - lx.expect(b';')?; - break; - } - return lx.fail(&format!("unexpected `{k}` in DATA")); - } - lx.i += 1; - let st = lx.i; - while lx.peek().is_some_and(|c| c.is_ascii_digit()) { - lx.i += 1; - } - let id: u64 = match std::str::from_utf8(lx.s.get(st..lx.i).unwrap_or(&[])).ok().and_then(|t| t.parse().ok()) { - Some(id) => id, - None => return lx.fail("bad entity id"), - }; - lx.expect(b'=')?; - let records = if lx.eat(b'(')? { - let mut rs = Vec::new(); - while !lx.eat(b')')? { - if rs.len() > 64 { - return lx.fail("complex entity with too many parts"); - } - rs.push(lx.record()?); - } - rs - } else { - vec![lx.record()?] - }; - lx.expect(b';')?; - if ex.entities.len() % 4096 == 0 - && let Some(w) = &watch - { - if w.cancelled() { - return err("STEP import cancelled"); - } - w.progress("reading", lx.i, lx.s.len()); - } - if ex.entities.len() >= MAX_ENTITIES { - return err(format!("STEP file has more than {MAX_ENTITIES} entities")); - } - // A duplicate id is invalid; some writers emit them for geometry nobody - // reads. Keep the first definition and report it. - match ex.entities.entry(id) { - std::collections::hash_map::Entry::Occupied(_) => ex.duplicates.push(id), - std::collections::hash_map::Entry::Vacant(v) => { - v.insert(Entity { records }); - } - } - } - } - "END-ISO-10303-21" => { - lx.expect(b';')?; - return Ok(ex); - } - // ANCHOR / REFERENCE / SIGNATURE sections (Part 21 edition 3): skip to ENDSEC. - "ANCHOR" | "REFERENCE" | "SIGNATURE" => { - let rest = lx.s.get(lx.i..).unwrap_or(&[]); - match rest.windows(7).position(|w| w == b"ENDSEC;") { - Some(p) => lx.i += p + 7, - None => return lx.fail("unterminated section"), - } - } - _ => return lx.fail(&format!("unexpected `{kw}`")), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_simple_and_complex() { - let t = "ISO-10303-21;\nHEADER;FILE_DESCRIPTION((''),'2;1');\nFILE_NAME('a','',(''),(''),'','sys','');\nFILE_SCHEMA(('AUTOMOTIVE_DESIGN'));ENDSEC;\nDATA;\n#1=CARTESIAN_POINT('p',(0.,1.5E1,-2));\n/* c */ #2=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#3=X('it''s','\\X2\\00E9\\X0\\',$,#1,LENGTH_MEASURE(1.E-3),\"0F\");\nENDSEC;\nEND-ISO-10303-21;\n"; - let ex = parse(t).unwrap(); - assert_eq!(ex.schemas, vec!["AUTOMOTIVE_DESIGN"]); - assert_eq!(ex.originating_system, "sys"); - let p = ex.get(1).unwrap(); - assert_eq!(p.name(), "CARTESIAN_POINT"); - let xyz: Vec = p.params()[1].as_list().unwrap().iter().filter_map(Param::as_f64).collect(); - assert_eq!(xyz, vec![0.0, 15.0, -2.0]); - let u = ex.get(2).unwrap(); - assert!(u.is_complex() && u.has("SI_UNIT")); - assert_eq!(u.record("SI_UNIT").unwrap()[0].as_enum(), Some("MILLI")); - let x = ex.get(3).unwrap().params(); - assert_eq!(x[0].as_str(), Some("it's")); - assert_eq!(x[1].as_str(), Some("\u{e9}")); - assert_eq!(x[2], Param::Null); - assert_eq!(x[3].as_ref_id(), Some(1)); - assert_eq!(x[4].as_f64(), Some(1e-3)); - } - - #[test] - fn hostile_text_is_an_error() { - for t in [ - "", - "garbage", - "ISO-10303-21;", - "ISO-10303-21;DATA;#1=A(", - "ISO-10303-21;DATA;#1=A('x", - "ISO-10303-21;DATA;#1=A(/*", - "ISO-10303-21;DATA;#=A();ENDSEC;END-ISO-10303-21;", - "ISO-10303-21;DATA;#99999999999999999999999=A();ENDSEC;END-ISO-10303-21;", - "ISO-10303-21;DATA;#1=A(1e999999.);ENDSEC;END-ISO-10303-21;", - ] { - let _ = parse(t); - } - let deep = format!("ISO-10303-21;DATA;#1=A({}{});ENDSEC;END-ISO-10303-21;", "(".repeat(10_000), ")".repeat(10_000)); - assert!(parse(&deep).is_err()); - let dup = parse("ISO-10303-21;DATA;#1=A(1);#1=B();ENDSEC;END-ISO-10303-21;").unwrap(); - assert_eq!(dup.duplicates, vec![1]); - assert_eq!(dup.get(1).unwrap().name(), "A"); - assert_eq!(decode_string(b"\\X\\E9"), "\u{e9}"); - assert_eq!(decode_string(b"a\\X2\\00E900E8\\X0\\b"), "a\u{e9}\u{e8}b"); - assert_eq!(decode_string(b"\\"), "\\"); - // One run per character, as `step_out` writes them (#2344). - assert_eq!(decode_string(b"\\X2\\5706\\X0\\\\X2\\89D2\\X0\\20"), "\u{5706}\u{89d2}20"); - assert_eq!(decode_string(b"\\X4\\0001F600\\X0\\\\X2\\00E9\\X0\\\\S\\a"), "\u{1f600}\u{e9}\u{e1}"); - } + let watch = crate::watch::current().map(Watched); + solidcraft_step::p21::parse_with(text, watch.as_ref().map(|w| w as &dyn solidcraft_step::p21::Progress)) } diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rs index 42ec63f39..378324e92 100644 --- a/crates/kernel/src/step_in/parallel.rs +++ b/crates/kernel/src/step_in/parallel.rs @@ -1,18 +1,13 @@ //! Bounded desktop preparation of independent imported bodies, collected in file order. use std::sync::Arc; -use super::{Body, Ctx, Exchange, KernelError, Units, brep, guard, mt}; +use super::{Body, Exchange, IDENTITY, KernelError, M4, Units}; pub(super) struct Job { pub source: Source, /// Where the body goes (its instance's placement in the assembly). - pub placement: mt::Matrix4, + pub placement: M4, pub check_mesh: bool, - /// The file's point-on-surface tolerance (`super::Units::tol`) for the representation this - /// solid was read from: how far its boundaries may lie off their surfaces (mm). The body - /// keeps it, so the tessellator holds an imported boundary to the file's own uncertainty - /// rather than to a fraction of the part's size (see `crate::body::Body::boundary_tol`). - pub tol: f64, } /// What a job places: a solid item to read from the file (and orient), or a part an earlier @@ -31,6 +26,9 @@ pub(super) struct Part { pub file_faces: usize, /// The file face of each kernel face. pub face_origin: Vec, + /// No B-rep could be made of the whole solid, and this is why: the body is a surface body of + /// the faces that read ([`surface_part`]). + pub refused: Option, } /// A prepared instance. @@ -40,8 +38,16 @@ pub(super) struct Made { /// Faces the mesher missed (counted when the job asked). pub missing: usize, pub part: Arc, - /// This job read the item: the faces the read left out, with the reason. - pub read: Option>, + /// This job read the item: what the read repaired and the faces it left out. + pub read: Option>, +} + +/// What reading an item noted. +pub(super) enum Note { + /// Repaired on the way (the reader's notes). + Repaired(String), + /// A face left out, with the reason. + LeftOut(String), } /// Why a job made no body: the item could not be read (`read`), or its body not made. @@ -63,32 +69,223 @@ pub(super) fn workers() -> usize { } } -fn prepare(ex: &Exchange, job: &Job) -> Prepared { +pub(super) fn prepare(ex: &Exchange, job: &Job) -> Prepared { + let _span = solidcraft_profile::span("import", "step.body"); let (part, read) = match &job.source { Source::Oriented(part) => (part.clone(), None), Source::Item { item, units } => { - let cx = Ctx { ex, len: units.len, ang: units.ang, tol: units.tol, snap: units.snap }; - let out = guard("step brep", || brep::read_item(&cx, *item).map_err(KernelError::Failed)) - .map_err(|e| Failure { read: true, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() })?; - // Orient once where the file defines the solid; each placement then takes its - // orientation from the matrix instead of meshing the whole part again. - let body = guard("STEP body preparation", || Body::new(out.solid)).map_err(|e| Failure { read: false, msg: e.to_string() })?; - // The file's tolerance is set on the part itself, before anything meshes it: the - // unmeshed-face count below is the import's own warning and must judge the body by - // the file's uncertainty too, and every placement of the part carries the figure on. - let body = body.with_boundary_tol(Some(job.tol)); - (Arc::new(Part { body, closed: out.closed, file_faces: out.file_faces, face_origin: out.face_origin }), Some(out.failed)) + let (part, read) = smlib_part(ex, *item, *units).or_else(|refused| surface_part(ex, *item, *units, refused))?; + (Arc::new(part), Some(read)) } }; - guard("STEP body preparation", || { - let body = part.body.placed(&job.placement)?; - // Counted where the orientation mesh already counted them (a placement meshes the - // same faces), and on the part, which carries the file's tolerance. - let missing = if job.check_mesh { part.body.unmeshed_faces() } else { 0 }; - Ok((body, missing)) + let body = solidcraft_profile::scope("import", "step.place", || placed(&part.body, &job.placement)) + .map_err(|e| Failure { read: false, msg: e.to_string() })?; + // Counted on the part (a placement meshes the same faces). + let missing = if job.check_mesh { solidcraft_profile::scope("import", "step.mesh_check", || part.body.unmeshed_faces()) } else { 0 }; + Ok(Made { body, missing, part, read }) +} + +/// The part's body where its instance goes: the very same body at the identity (it keeps the +/// SMLib body the read made), else its record moved there. +fn placed(body: &Body, m: &M4) -> crate::Result { + if *m == IDENTITY { + return Ok(body.clone()); + } + Ok(crate::ops::transform_matrix(body, *m)?.without_history()) +} + +/// A solid item read with the STEP reader into its schema 4 record, then into SMLib as given, +/// and brought back as a body: the part SMLib made of the file. A solid the reader or SMLib +/// refuses fails with the reason ([`surface_part`] then imports what it can of it). +pub(super) fn smlib_part(ex: &Exchange, item: u64, units: Units) -> std::result::Result<(Part, Vec), Failure> { + let solid = solidcraft_profile::scope("import", "step.read_solid", || { + solidcraft_step::topology::read_solid_with(ex, item, units, &solidcraft_smlib::pcurves::SmlibTrims) }) - .map(|(body, missing)| Made { body, missing, part, read }) - .map_err(|e| Failure { read: false, msg: e.to_string() }) + .map_err(|msg| Failure { read: true, msg })?; + let part = solid_part(&solid)?; + Ok((part, solid.notes.into_iter().map(Note::Repaired).collect())) +} + +/// The part SMLib makes of a solid (or sheet) record the reader made. +/// +/// SMLib holds both sides of a sheet's faces and gives each back facing its surface's natural +/// normal, so a sheet whose file uses some faces the other way is given to SMLib with those faces +/// turned over (exactly, on the record) and they are turned back on SMLib's body: the body faces +/// as the file does, and each of its faces is known to be the record's face it was. +fn solid_part(solid: &solidcraft_step::topology::Solid) -> std::result::Result { + let failed = |e: KernelError| Failure { read: false, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() }; + let r = &solid.brep; + let mut reversed = vec![false; r.faces.len()]; + if solid.sheet { + for s in &r.shells { + if let solidcore_record::brep::Shell::Faces { faces, .. } = s { + for f in faces.iter().filter(|f| !f.forward) { + if let Some(slot) = reversed.get_mut(f.face as usize) { + *slot = true; + } + } + } + } + } + let (body, of_record) = if reversed.iter().any(|r| *r) { + let turn = |body: &Body, by: &dyn Fn(usize) -> bool| -> crate::Result<(Body, Vec)> { + let picked: Vec<(usize, bool)> = (0..body.face_count()).map(|f| (f, by(f))).collect(); + let turned = crate::surfaces::taken(body, body.record(), &picked)?; + let from = kept_faces(&turned).ok_or_else(|| KernelError::Failed("a face turned over from no one face".into()))?; + Ok((turned, from)) + }; + let as_read = Body::from_record(r.clone()).map_err(failed)?; + // `natural`'s face j is the record's `to_record[j]`; SMLib's body's face k is `natural`'s + // `of_natural[k]`; the body turned back's face i is SMLib's `back[i]`. + let (natural, to_record) = turn(&as_read, &|f| reversed.get(f).copied().unwrap_or(false)).map_err(failed)?; + let (smlib, of_natural) = smlib_body(natural.record())?; + let record_of = |k: usize| of_natural.get(k).and_then(|j| to_record.get(*j)).copied(); + let (back, from) = turn(&smlib, &|k| record_of(k).and_then(|f| reversed.get(f)).copied().unwrap_or(false)).map_err(failed)?; + let of_record = from.iter().map(|k| record_of(*k)).collect::>>().ok_or_else(renumbered)?; + (back.without_history(), of_record) + } else { + smlib_body(r)? + }; + let face_origin = of_record.iter().map(|f| solid.face_origin.get(*f).copied()).collect::>>().ok_or_else(renumbered)?; + Ok(Part { body, closed: !solid.sheet, file_faces: solid.face_origin.len(), face_origin, refused: None }) +} + +fn renumbered() -> Failure { + Failure { read: false, msg: "not supported yet: SMLib renumbered the solid's faces".into() } +} + +/// The body SMLib makes of `record` as given, and the record's face each of its faces is. +fn smlib_body(record: &solidcore_record::brep::Brep) -> std::result::Result<(Body, Vec), Failure> { + let failed = |e: KernelError| Failure { read: false, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() }; + let (brep, smlib_order) = crate::native::smlib_record_ordered(record).map_err(failed)?; + let (body, body_order) = crate::native::body_from_smlib_ordered(&brep).map_err(failed)?; + // SMLib's face i is the record's `smlib_order` face and the body's `body_order` face (an + // empty order is the same one). + let (Some(smlib_order), Some(body_order)) = (smlib_order, body_order) else { return Err(renumbered()) }; + let at = |order: &[usize], i: usize| if order.is_empty() { Some(i) } else { order.get(i).copied() }; + let faces = brep.counts().map_err(|e| failed(KernelError::Failed(format!("SMLib: {e}"))))?[0]; + let mut of_record = vec![usize::MAX; body.face_count()]; + for i in 0..faces { + match (at(&body_order.faces, i).and_then(|b| of_record.get_mut(b)), at(&smlib_order.faces, i).filter(|r| *r < record.faces.len())) { + (Some(slot), Some(r)) => *slot = r, + _ => return Err(renumbered()), + } + } + if of_record.contains(&usize::MAX) { + return Err(renumbered()); + } + Ok((body, of_record)) +} + +/// The face of its one operand each face of `body` is, from its history. +fn kept_faces(body: &Body) -> Option> { + let h = body.history()?; + let from: Vec = h + .faces + .iter() + .map(|f| match f.origins.as_slice() { + [crate::history::FaceOrigin::Face { operand: 0, face }] => Some(*face), + _ => None, + }) + .collect::>()?; + (from.len() == body.face_count()).then_some(from) +} + +/// Most reads of a refused solid without faces, each leaving out the face the refusal before names. +const MAX_LEFT_OUT_ROUNDS: usize = 8; + +/// A solid the reader or SMLib refuses, imported as an open surface body of its exact faces, the +/// faces that make it refused left out and named in the notes; `refused` says why the solid was. +/// Each face is read on its own first ([`solidcraft_step::topology::read_faces_with`]); then: +/// 1. the solid is read again without the faces that cannot be read alone and the face the +/// refusal names, as one sheet whose faces share their edges as the file has them, and made +/// by SMLib; a refusal of that naming another face of the solid leaves it out too (up to +/// [`MAX_LEFT_OUT_ROUNDS`] reads). A face is only ever left out where a refusal names it. +/// 2. Where a refusal names no face of the solid: the faces that read alone, stitched by SMLib +/// into one surface body (their edges sewn at ten times their tolerance). +/// +/// Where SMLib cannot stitch them either, or there is no face to import, the solid stays refused +/// with the reason it was: a B-rep SMLib refuses is never kept as a mesh of its faces. +fn surface_part(ex: &Exchange, item: u64, units: Units, refused: Failure) -> std::result::Result<(Part, Vec), Failure> { + let _span = solidcraft_profile::span("import", "step.refused_surfaces"); + let trims = &solidcraft_smlib::pcurves::SmlibTrims; + let Ok(faces) = solidcraft_step::topology::read_faces_with(ex, item, units, trims) else { return Err(refused) }; + let of_solid: std::collections::HashSet = faces.iter().map(|f| f.face).collect(); + // The faces left out, each with the refusal that names it, in the order they were found. + let mut left_out: Vec<(u64, String)> = faces.iter().filter_map(|f| f.record.as_ref().err().map(|m| (f.face, m.clone()))).collect(); + let mut why = refused.msg.clone(); + let mut rounds = 0; + loop { + // The face the last refusal names, if it is one of the solid's still in, is left out too. + let named = solidcraft_step::topology::named_face(&why).filter(|f| of_solid.contains(f) && !left_out.iter().any(|(g, _)| g == f)); + match named { + Some(f) => left_out.push((f, why.clone())), + None if rounds > 0 => break, + None => {} + } + if left_out.is_empty() || left_out.len() >= faces.len() || rounds >= MAX_LEFT_OUT_ROUNDS { + break; + } + rounds += 1; + let skip: std::collections::HashSet = left_out.iter().map(|(f, _)| *f).collect(); + let read = + solidcraft_profile::scope("import", "step.read_without", || solidcraft_step::topology::read_solid_without(ex, item, units, trims, &skip)); + match read + .map_err(|msg| Failure { read: true, msg }) + .and_then(|solid| Ok((solid_part(&solid)?, solid.notes.into_iter().map(Note::Repaired).collect::>()))) + { + Ok((mut part, mut notes)) => { + part.file_faces = faces.len(); + part.refused = Some(refused.msg); + notes.extend(left_out.iter().map(|(_, m)| Note::LeftOut(format!("left out: {m}")))); + return Ok((part, notes)); + } + Err(e) => { + log::debug!(target: "step", "item #{item}: read without {} faces, refused: {}", skip.len(), e.msg); + why = e.msg; + } + } + } + // The faces that read alone, each a one-face surface body. + let mut notes = Vec::new(); + let mut pieces = Vec::with_capacity(faces.len()); + for f in &faces { + match f.record.clone().map_err(KernelError::Failed).and_then(Body::from_record) { + Ok(b) => pieces.push((f.face, b)), + Err(e) => notes.push(Note::LeftOut(format!("left out: {}", e.to_string().trim_start_matches("the operation failed: ")))), + } + } + // Where SMLib cannot stitch them either, the solid is refused with the reason it was. + let part = stitched_part(&pieces, faces.len(), &refused.msg).map_err(|e| { + log::debug!(target: "step", "item #{item}: its faces not stitched ({e})"); + refused + })?; + Ok((part, notes)) +} + +/// The one-face surface bodies `pieces` (each with its file face) stitched by SMLib into one +/// surface body, where their edges coincide within ten times the pieces' tolerance. +fn stitched_part(pieces: &[(u64, Body)], file_faces: usize, refused: &str) -> crate::Result { + if pieces.is_empty() { + return Err(KernelError::Failed("no face read".into())); + } + let tol = 10.0 * pieces.iter().map(|(_, b)| b.record().tolerance).fold(0.0, f64::max); + let bodies: Vec<&Body> = pieces.iter().map(|(_, b)| b).collect(); + let body = crate::surfaces::stitch(&bodies, tol)?; + // Each stitched face is the one face of the piece it was sewn from. + let history = body.history().ok_or_else(|| KernelError::Failed("the stitch kept no history".into()))?; + let face_origin = history + .faces + .iter() + .map(|f| match f.origins.as_slice() { + [crate::history::FaceOrigin::Face { operand, .. }] => pieces.get(*operand).map(|(face, _)| *face), + _ => None, + }) + .collect::>>() + .filter(|o| o.len() == body.face_count()) + .ok_or_else(|| KernelError::Failed("a stitched face from no one face".into()))?; + let closed = !body.is_surface(); + Ok(Part { body, closed, file_faces, face_origin, refused: Some(refused.to_string()) }) } /// Prepare `jobs`, the results in the jobs' order. Solids still to read and orient (the slow diff --git a/crates/kernel/src/step_in/split.rs b/crates/kernel/src/step_in/split.rs deleted file mode 100644 index 509c046c1..000000000 --- a/crates/kernel/src/step_in/split.rs +++ /dev/null @@ -1,582 +0,0 @@ -//! Splitting band faces that wrap all the way around a closed, non-periodic parameter direction. -//! -//! A STEP face may run once around a closed surface and close its loop with a seam edge used -//! twice (a pipe segment of a torus, a revolved B-spline band). Truck meshes faces in parameter -//! space and only treats the rotation of a revolved surface as periodic, so such a face is cut -//! in two along the parameter line opposite its seam; the ring edges it crosses are cut in every -//! face that uses them. - -use std::collections::HashMap; - -use mt::{BoundedCurve, BoundedSurface, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface, SearchNearestParameter}; -use truck_modeling as mt; - -use super::geom::{Frame, R, conic_arc}; - -/// How far a band's ring edge may lie off its surface, as a fraction of the body, for a body that -/// declares no accuracy of its own. -const RING_OFF_SURFACE: f64 = 1e-3; - -/// Samples per edge when looking for the split crossing. -const SAMPLES: usize = 48; - -/// Which surface parameter wraps around. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Dir { - U, - V, -} - -fn uv_of(s: &mt::Surface, p: mt::Point3) -> Option<(f64, f64)> { - s.search_nearest_parameter(p, None, 100).filter(|(u, v)| u.is_finite() && v.is_finite()) -} - -fn coord(d: Dir, uv: (f64, f64)) -> f64 { - match d { - Dir::U => uv.0, - Dir::V => uv.1, - } -} - -/// The direction the split line runs along (the one that does not wrap). -fn along(d: Dir) -> Dir { - match d { - Dir::U => Dir::V, - Dir::V => Dir::U, - } -} - -/// The closed, non-periodic direction of a surface with its range; with `periodic`, a revolved -/// surface's turn around its axis too. -fn closed_dirs(s: &mt::Surface, periodic: bool) -> Vec<(Dir, f64, f64)> { - match s { - mt::Surface::RevolutedCurve(p) => { - let c = p.entity().entity_curve(); - let (t0, t1) = c.range_tuple(); - let mut out = Vec::new(); - if c.front().distance(c.back()) < 1e-7 * (1.0 + c.front().to_homogeneous().truncate().magnitude()) { - out.push((Dir::U, t0, t1)); - } - if periodic { - out.extend(turn_dir(s)); - } - out - } - mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => { - let ((u0, u1), (v0, v1)) = match s { - mt::Surface::BSplineSurface(b) => b.range_tuple(), - mt::Surface::NurbsSurface(n) => n.range_tuple(), - _ => return vec![], - }; - let size = (0..=4) - .flat_map(|i| (0..=4).map(move |j| (i, j))) - .map(|(i, j)| s.subs(u0 + (u1 - u0) * i as f64 / 4.0, v0 + (v1 - v0) * j as f64 / 4.0).to_homogeneous().truncate().magnitude()) - .fold(1.0, f64::max); - let tol = size * 1e-7; - let mut out = Vec::new(); - if (0..=8).all(|k| { - let v = v0 + (v1 - v0) * k as f64 / 8.0; - s.subs(u0, v).distance(s.subs(u1, v)) < tol - }) { - out.push((Dir::U, u0, u1)); - } - if (0..=8).all(|k| { - let u = u0 + (u1 - u0) * k as f64 / 8.0; - s.subs(u, v0).distance(s.subs(u, v1)) < tol - }) { - out.push((Dir::V, v0, v1)); - } - out - } - mt::Surface::Plane(_) => vec![], - } -} - -/// The parameter that turns a revolved surface around its axis, over one turn. -fn turn_dir(s: &mt::Surface) -> Option<(Dir, f64, f64)> { - let mt::Surface::RevolutedCurve(p) = s else { return None }; - let (t0, t1) = p.entity().entity_curve().range_tuple(); - let tau = std::f64::consts::TAU; - let ts: Vec = (0..=4).map(|i| t0 + (t1 - t0) * f64::from(i) / 4.0).collect(); - [Dir::V, Dir::U].into_iter().find_map(|d| { - let at = |w: f64, t: f64| match d { - Dir::V => s.subs(t, w), - Dir::U => s.subs(w, t), - }; - let scale = ts.iter().map(|t| at(0.0, *t).to_homogeneous().truncate().magnitude()).fold(1.0, f64::max); - let closes = ts.iter().all(|t| at(0.0, *t).distance(at(tau, *t)) < scale * 1e-9); - let turns = ts.iter().any(|t| at(0.0, *t).distance(at(std::f64::consts::PI, *t)) > scale * 1e-6); - (closes && turns).then_some((d, 0.0, tau)) - }) -} - -fn samples(c: &mt::Curve, n: usize) -> Vec<(f64, mt::Point3)> { - let (t0, t1) = c.range_tuple(); - (0..=n).map(|i| t0 + (t1 - t0) * i as f64 / n as f64).map(|t| (t, c.subs(t))).collect() -} - -/// Where a ring chain crosses `w = mid`: (edge index in the chain, parameter on the edge's -/// absolute curve, point). -fn crossing(s: &mt::Surface, d: Dir, chain: &[mt::Edge], mid: f64, period: f64) -> R<(usize, f64, mt::Point3)> { - for (k, e) in chain.iter().enumerate() { - let c = e.curve(); - let pts = samples(&c, SAMPLES); - let ws: Vec> = pts.iter().map(|(_, p)| uv_of(s, *p).map(|uv| coord(d, uv))).collect(); - for i in 0..SAMPLES { - let (Some(Some(wa)), Some(Some(wb)), Some((ta, _)), Some((tb, _))) = (ws.get(i), ws.get(i + 1), pts.get(i), pts.get(i + 1)) else { - continue; - }; - if (wb - wa).abs() > period * 0.5 || (wa - mid) * (wb - mid) > 0.0 { - continue; - } - // Bisection on the curve parameter. - let (mut lo, mut hi, mut flo) = (*ta, *tb, wa - mid); - for _ in 0..60 { - let m = 0.5 * (lo + hi); - let Some(w) = uv_of(s, c.subs(m)).map(|uv| coord(d, uv)) else { break }; - let f = w - mid; - if (f - flo).abs() > period * 0.5 { - break; - } - if f * flo <= 0.0 { - hi = m; - } else { - lo = m; - flo = f; - } - } - let t = 0.5 * (lo + hi); - return Ok((k, t, c.subs(t))); - } - } - Err("no crossing with the split line".into()) -} - -/// Iso-parameter edge curve `w = mid` from `q1` to `q2`. `tol` is how far a ring edge may lie off -/// the surface the split line lies on: a STEP file writes the surface and the curves bounding it -/// to the file's own declared uncertainty only, so the line is matched to the surface points -/// below `q1` and `q2`, not to them. -fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3, seam: &[mt::Point3], tol: f64) -> R { - match s { - // Across the turn of a cylinder or cone: a straight line along it. - mt::Surface::RevolutedCurve(_) if turn_dir(s).is_some_and(|t| t.0 == d) => { - let m = q1 + (q2 - q1) * 0.5; - let on = uv_of(s, m).is_some_and(|(u, v)| s.subs(u, v).distance(m) < 1e-7 * (1.0 + q1.distance(q2))); - if on && q1.distance(q2) > 1e-9 { - Ok(mt::Curve::Line(mt::Line(q1, q2))) - } else { - Err("a revolved face that is not straight along its axis".into()) - } - } - mt::Surface::RevolutedCurve(p) => { - // A circle around the axis, turning opposite to the seam (which runs from the q2 - // side to the q1 side). - let (o, a) = (p.entity().origin(), p.entity().axis()); - let az = |x: mt::Point3, f: &Frame| { - let v = x - f.o; - v.dot(f.y).atan2(v.dot(f.x)) - }; - let c = o + a * (q1 - o).dot(a); - let r = (q1 - c).magnitude(); - if !(r > 1e-9) { - return Err("split line on the axis".into()); - } - let x = (q1 - c) / r; - let f = Frame { o: c, x, y: a.cross(x), z: a }; - let mut seam_turn = 0.0; - for w in seam.windows(2) { - if let (Some(p0), Some(p1)) = (w.first(), w.get(1)) { - let d = az(*p1, &f) - az(*p0, &f); - seam_turn += (d + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; - } - } - let sweep = -seam_turn; - if sweep.abs() < 1e-9 { - return Err("degenerate split line".into()); - } - let f = if sweep > 0.0 { f } else { Frame { o: c, x, y: -a.cross(x), z: -a } }; - let arc = conic_arc(&f, r, r, 0.0, sweep.abs()); - if arc.back().distance(q2) > (1e-6 * (1.0 + r)).max(tol) { - return Err("split line does not reach the other ring".into()); - } - Ok(mt::Curve::NurbsCurve(arc)) - } - mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => { - let hom: mt::BSplineSurface = match s { - mt::Surface::BSplineSurface(b) => mt::BSplineSurface::new( - b.knot_vecs().clone(), - b.control_points().iter().map(|row| row.iter().map(|p| p.to_homogeneous()).collect()).collect(), - ), - mt::Surface::NurbsSurface(n) => n.non_rationalized().clone(), - _ => return Err("unsupported surface".into()), - }; - let iso = mt::Curve::NurbsCurve(iso_bsp(&hom, mid, d == Dir::V)?); - let (t0, t1) = iso.range_tuple(); - // Where the split line comes nearest `p`: the point on the surface below `p` (the - // line runs on the surface, `p` only within the file's tolerance of it), looked for - // from its own surface parameter and from a scan of the whole line. - let near = |p: mt::Point3| { - let foot = uv_of(s, p).filter(|uv| s.subs(uv.0, uv.1).distance(p) <= tol); - let target = foot.map_or(p, |uv| s.subs(uv.0, uv.1)); - let mut best = (t0, f64::INFINITY); - for i in 0..=256 { - let t = t0 + (t1 - t0) * i as f64 / 256.0; - let dd = iso.subs(t).distance(target); - if dd < best.1 { - best = (t, dd); - } - } - let seeds = foot.map(|uv| coord(along(d), uv)).into_iter().chain(iso.search_nearest_parameter(target, best.0, 64)); - for t in seeds { - let t = t.clamp(t0, t1); - let dd = iso.subs(t).distance(target); - if dd <= best.1 { - best = (t, dd); - } - } - best - }; - let ((ta, da), (tb, db)) = (near(q1), near(q2)); - let scale = 1.0 + q1.to_homogeneous().truncate().magnitude(); - if da > 1e-5 * scale || db > 1e-5 * scale || (ta - tb).abs() < 1e-12 { - return Err("split line does not reach the rings".into()); - } - let (lo, hi) = if ta < tb { (ta, tb) } else { (tb, ta) }; - let mut c = iso; - let eps = (t1 - t0) * 1e-9; - if lo > t0 + eps { - c = mt::Cut::cut(&mut c, lo); - } - if hi < t1 - eps { - let _ = mt::Cut::cut(&mut c, hi); - } - if ta > tb { - c.invert(); - } - Ok(c) - } - mt::Surface::Plane(_) => Err("planes do not wrap".into()), - } -} - -/// The iso-curve of a homogeneous B-spline surface at `v = w` (`along_u`) or `u = w`. -pub(crate) fn iso_bsp(b: &mt::BSplineSurface, w: f64, along_u: bool) -> R> { - let (ku, kv) = b.knot_vecs(); - let ctrl = b.control_points(); - let nu = ctrl.len(); - let nv = ctrl.first().map(Vec::len).unwrap_or(0); - let zero = mt::Vector4::new(0.0, 0.0, 0.0, 0.0); - let pts: Vec = if along_u { - let deg = kv.len().checked_sub(nv + 1).ok_or("bad knot vector")?; - let basis = kv.try_bspline_basis_functions(deg, w).map_err(|e| e.to_string())?; - ctrl.iter().map(|row| row.iter().zip(&basis).fold(zero, |acc, (p, f)| acc + *p * *f)).collect() - } else { - let deg = ku.len().checked_sub(nu + 1).ok_or("bad knot vector")?; - let basis = ku.try_bspline_basis_functions(deg, w).map_err(|e| e.to_string())?; - (0..nv).map(|j| ctrl.iter().zip(&basis).fold(zero, |acc, (row, f)| acc + row.get(j).copied().unwrap_or(zero) * *f)).collect() - }; - let knots = if along_u { ku.clone() } else { kv.clone() }; - mt::BSplineCurve::try_new(knots, pts).map(mt::NurbsCurve::new).map_err(|e| e.to_string()) -} - -type Cut = (mt::Edge, (mt::Edge, mt::Edge)); - -/// Split a chain at parameter `t` of its edge `k` (absolute curve): the edges before and after -/// the split point, the edge cut (unless the point is an existing vertex) and the split vertex. -fn split_chain(chain: &[mt::Edge], k: usize, t: f64, q: mt::Point3) -> R<(Vec, Vec, Option, mt::Vertex)> { - let e = chain.get(k).ok_or("bad crossing")?; - let (t0, t1) = e.curve().range_tuple(); - let eps = (t1 - t0).abs() * 1e-7; - let at_front = (t - t0).abs() <= eps; - let at_back = (t - t1).abs() <= eps; - if at_front || at_back { - // The split point is a vertex already: split the chain between edges. - let v = if at_front { e.absolute_front().clone() } else { e.absolute_back().clone() }; - let first_end = at_front != e.orientation(); // the point is this edge's end in loop order - let cut_at = if first_end { k + 1 } else { k }; - let before = chain.iter().take(cut_at).cloned().collect(); - let after = chain.iter().skip(cut_at).cloned().collect(); - return Ok((before, after, None, v)); - } - let v = mt::Vertex::new(q); - let (a, b) = e.cut_with_parameter(&v, t).ok_or("cannot cut a ring edge at the split line")?; - let mut before: Vec = chain.iter().take(k).cloned().collect(); - before.push(a.clone()); - let mut after = vec![b.clone()]; - after.extend(chain.iter().skip(k + 1).cloned()); - Ok((before, after, Some((e.clone(), (a, b))), v)) -} - -struct Plan { - /// Edge cuts: (edge as used in the band's loop, its two pieces in that loop's order). - cuts: Vec, - faces: (mt::Face, mt::Face), -} - -/// How to cut `face` in two along the line opposite its seam. `periodic` also cuts a face that -/// runs round the turn of a revolved surface (see [`closed_dirs`]). `tol` is how far a ring edge -/// of the face may lie off the surface it bounds (see [`iso_curve`]). -fn plan(face: &mt::Face, periodic: bool, tol: f64) -> R> { - let s = face.surface(); - let wires = face.absolute_boundaries().clone(); - let mut uses: HashMap = HashMap::new(); - for e in wires.iter().flat_map(|w| w.edge_iter()) { - *uses.entry(e.id()).or_default() += 1; - } - let is_seam = |e: &mt::Edge| uses.get(&e.id()).copied().unwrap_or(0) > 1; - if !wires.iter().flat_map(|w| w.edge_iter()).any(is_seam) { - return Ok(None); - } - // The closed direction whose boundary carries the seam. - let seam_pts: Vec = - wires.iter().flat_map(|w| w.edge_iter()).filter(|e| is_seam(e)).flat_map(|e| samples(&e.curve(), 4).into_iter().map(|x| x.1)).collect(); - let Some((d, w0, w1)) = closed_dirs(&s, periodic).into_iter().find(|(d, w0, w1)| { - let p = w1 - w0; - seam_pts.iter().all(|q| uv_of(&s, *q).map(|uv| coord(*d, uv)).is_some_and(|w| (w - w0).abs().min((w - w1).abs()) < p * 1e-4)) - }) else { - return Ok(None); - }; - let (period, mid) = (w1 - w0, 0.5 * (w0 + w1)); - let outer_idx = wires.iter().position(|w| w.edge_iter().any(is_seam)).ok_or("no seam loop")?; - if wires.iter().enumerate().any(|(i, w)| i != outer_idx && w.edge_iter().any(is_seam)) { - return Err("seam edges in several loops".into()); - } - let outer: Vec = wires.get(outer_idx).ok_or("no seam loop")?.edge_iter().cloned().collect(); - let n = outer.len(); - let start = (0..n) - .find(|&i| outer.get(i).is_some_and(is_seam) && outer.get((i + n - 1) % n).is_some_and(|e| !is_seam(e))) - .ok_or("loop made only of seam edges")?; - let rot: Vec = (0..n).filter_map(|i| outer.get((start + i) % n).cloned()).collect(); - let mut chains: Vec<(bool, Vec)> = Vec::new(); - for e in rot { - let seam = is_seam(&e); - match chains.last_mut() { - Some((s0, c)) if *s0 == seam => c.push(e), - _ => chains.push((seam, vec![e])), - } - } - // A cone's tip: the seam runs from the ring to the apex and straight back. - if let [(true, sm), (false, ring)] = chains.as_slice() { - return apex_plan(face, &s, (d, mid, period), sm, ring, &wires, outer_idx, tol).map(Some); - } - let [(true, s1), (false, r1), (true, s2), (false, r2)] = chains.as_slice() else { - return Err(format!("unsupported seam loop layout ({} runs)", chains.len())); - }; - let s2_ids: Vec = s2.iter().rev().map(mt::Edge::id).collect(); - if s1.iter().map(mt::Edge::id).collect::>() != s2_ids { - return Err("seam edges are not used back and forth".into()); - } - let (k1, t1, q1) = crossing(&s, d, r1, mid, period)?; - let (k2, t2, q2) = crossing(&s, d, r2, mid, period)?; - let seam_line: Vec = s1.iter().flat_map(|e| samples(&e.oriented_curve(), 16).into_iter().map(|x| x.1)).collect(); - let iso = iso_curve(&s, d, mid, q1, q2, &seam_line, tol)?; - let (r1a, r1b, c1, v1) = split_chain(r1, k1, t1, q1)?; - let (r2a, r2b, c2, v2) = split_chain(r2, k2, t2, q2)?; - let e_split = mt::Edge::new_unchecked(&v1, &v2, iso); - // Face A: split, rest of ring 2, seam, start of ring 1. Face B: the other half. - let mut wa: Vec = vec![e_split.clone()]; - wa.extend(r2b); - wa.extend(s1.iter().cloned()); - wa.extend(r1a.iter().cloned()); - let mut wb: Vec = vec![e_split.inverse()]; - wb.extend(r1b); - wb.extend(s2.iter().cloned()); - wb.extend(r2a); - let wire_a: mt::Wire = wa.into(); - let wire_b: mt::Wire = wb.into(); - if !wire_a.is_closed() || !wire_b.is_closed() { - return Err("split loops do not close".into()); - } - // Holes go to the half that holds them. - let side_a = r1a - .iter() - .flat_map(|e| samples(&e.oriented_curve(), 4)) - .filter_map(|(_, p)| uv_of(&s, p).map(|uv| coord(d, uv))) - .find(|w| (w - mid).abs() > period * 1e-3) - .map(|w| w < mid) - .ok_or("cannot place the split halves")?; - let (mut ha, mut hb) = (vec![wire_a], vec![wire_b]); - for (i, w) in wires.iter().enumerate() { - if i == outer_idx { - continue; - } - let ws: Vec = w.edge_iter().flat_map(|e| samples(&e.curve(), 4)).filter_map(|(_, p)| uv_of(&s, p).map(|uv| coord(d, uv))).collect(); - if ws.iter().all(|x| (*x < mid) == side_a) { - ha.push(w.clone()); - } else if ws.iter().all(|x| (*x < mid) != side_a) { - hb.push(w.clone()); - } else { - return Err("a hole crosses the split line".into()); - } - } - let mut fa = mt::Face::new_unchecked(ha, s.clone()); - let mut fb = mt::Face::new_unchecked(hb, s); - if !face.orientation() { - fa.invert(); - fb.invert(); - } - Ok(Some(Plan { cuts: c1.into_iter().chain(c2).collect(), faces: (fa, fb) })) -} - -/// Split a face closing at an apex (loop: seam out to the apex, seam back, the ring) along the -/// iso-line opposite the seam, from the ring to the apex. -fn apex_plan( - face: &mt::Face, - s: &mt::Surface, - (d, mid, period): (Dir, f64, f64), - sm: &[mt::Edge], - ring: &[mt::Edge], - wires: &[mt::Wire], - outer_idx: usize, - tol: f64, -) -> R { - let h = sm.len() / 2; - if !sm.len().is_multiple_of(2) || h == 0 { - return Err("seam edges are not used back and forth".into()); - } - let (out, back) = (sm.get(..h).ok_or("seam")?, sm.get(h..).ok_or("seam")?); - if out.iter().map(mt::Edge::id).collect::>() != back.iter().rev().map(mt::Edge::id).collect::>() { - return Err("seam edges are not used back and forth".into()); - } - let apex = out.last().ok_or("seam")?.back().clone(); - let (k, t, q) = crossing(s, d, ring, mid, period)?; - let seam_line: Vec = out.iter().flat_map(|e| samples(&e.oriented_curve(), 16).into_iter().map(|x| x.1)).collect(); - let iso = iso_curve(s, d, mid, q, apex.point(), &seam_line, tol)?; - let (ra, rb, c, vq) = split_chain(ring, k, t, q)?; - let e = mt::Edge::new_unchecked(&vq, &apex, iso); - // Face A: out to the apex, down the split line, the ring's second part; face B the rest. - let mut wa: Vec = out.to_vec(); - wa.push(e.inverse()); - wa.extend(rb.iter().cloned()); - let mut wb: Vec = vec![e]; - wb.extend(back.iter().cloned()); - wb.extend(ra); - let (wire_a, wire_b): (mt::Wire, mt::Wire) = (wa.into(), wb.into()); - if !wire_a.is_closed() || !wire_b.is_closed() { - return Err("split loops do not close".into()); - } - let side_a = rb - .iter() - .flat_map(|e| samples(&e.oriented_curve(), 4)) - .filter_map(|(_, p)| uv_of(s, p).map(|uv| coord(d, uv))) - .find(|w| (w - mid).abs() > period * 1e-3) - .map(|w| w < mid) - .ok_or("cannot place the split halves")?; - let (mut ha, mut hb) = (vec![wire_a], vec![wire_b]); - for (i, w) in wires.iter().enumerate() { - if i == outer_idx { - continue; - } - let ws: Vec = w.edge_iter().flat_map(|e| samples(&e.curve(), 4)).filter_map(|(_, p)| uv_of(s, p).map(|uv| coord(d, uv))).collect(); - if ws.iter().all(|x| (*x < mid) == side_a) { - ha.push(w.clone()); - } else if ws.iter().all(|x| (*x < mid) != side_a) { - hb.push(w.clone()); - } else { - return Err("a hole crosses the split line".into()); - } - } - let mut fa = mt::Face::new_unchecked(ha, s.clone()); - let mut fb = mt::Face::new_unchecked(hb, s.clone()); - if !face.orientation() { - fa.invert(); - fb.invert(); - } - Ok(Plan { cuts: c.into_iter().collect(), faces: (fa, fb) }) -} - -/// Replace cut edges in a face's loops. -fn recut(face: &mt::Face, cuts: &[(mt::Edge, (mt::Edge, mt::Edge))]) -> mt::Face { - let touches = face.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).any(|e| cuts.iter().any(|(c, _)| c.id() == e.id())); - if !touches { - return face.clone(); - } - let wires: Vec = face - .absolute_boundaries() - .iter() - .map(|w| { - let mut out: Vec = Vec::new(); - for e in w.edge_iter() { - match cuts.iter().find(|(c, _)| c.id() == e.id()) { - Some((c, (a, b))) if c.orientation() == e.orientation() => out.extend([a.clone(), b.clone()]), - Some((_, (a, b))) => out.extend([b.inverse(), a.inverse()]), - None => out.push(e.clone()), - } - } - out.into() - }) - .collect(); - let mut f = mt::Face::new_unchecked(wires, face.surface()); - if !face.orientation() { - f.invert(); - } - f -} - -/// A copy of `body` whose faces that run once round a cylinder or cone along a seam edge -/// (as STEP files have them) are each cut in two along the line opposite the seam, the way the -/// kernel builds such walls itself; the boolean cannot always intersect the whole ones. `None` -/// when the body has no such face, or one can't be cut. -pub(crate) fn split_seams(body: &crate::Body) -> Option { - let seamed = |f: &mt::Face| { - let mut seen = std::collections::HashSet::new(); - f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).any(|e| !seen.insert(e.id())) - }; - if !body.solid.face_iter().any(seamed) { - return None; - } - // How far a ring edge of such a face may lie off the surface it bounds (see `iso_curve`): - // the file's own declared uncertainty for a body read from one, else a thousandth of the body. - let tol = body.boundary_tol.unwrap_or(body.size() * RING_OFF_SURFACE).max(1e-6); - let mut shells: Vec = Vec::new(); - for sh in body.solid.boundaries() { - let mut faces: Vec = sh.face_iter().cloned().collect(); - let n = faces.len(); - for i in 0..n { - let Some(face) = faces.get(i).cloned() else { continue }; - if !seamed(&face) { - continue; - } - let p = crate::guard("seam split", || plan(&face, true, tol).map_err(crate::KernelError::Failed)).ok()??; - faces = faces.iter().map(|f| recut(f, &p.cuts)).collect(); - if let Some(slot) = faces.get_mut(i) { - *slot = p.faces.0; - } - faces.push(p.faces.1); - } - shells.push(faces.into()); - } - let solid = mt::Solid::try_new(shells).ok()?; - let b = crate::Body::new(solid).ok()?; - b.validity().is_empty().then_some(b) -} - -/// Split every band face of a shell (see the module docs). Faces that cannot be split stay as -/// they are and are reported. -/// -/// `tol` is the file's point-on-surface tolerance (`step_in::mod::Units::tol`): 10x the file's -/// declared uncertainty, floored at 1 µm and clamped to [1e-4, 1] mm. A ring edge is written to -/// within this distance of the surface it bounds, so it is how far `iso_curve` may accept a -/// crossing point as lying on the surface. -pub(crate) fn split_bands(mut faces: Vec, origin: &mut Vec, warnings: &mut Vec, tol: f64) -> Vec { - let n = faces.len(); - for i in 0..n { - let Some(face) = faces.get(i).cloned() else { continue }; - match crate::guard("step band split", || plan(&face, false, tol).map_err(crate::KernelError::Failed)) { - Ok(Some(p)) => { - faces = faces.iter().map(|f| recut(f, &p.cuts)).collect(); - if let Some(slot) = faces.get_mut(i) { - *slot = p.faces.0; - } - faces.push(p.faces.1); - // The second piece comes from the same file face. - let o = origin.get(i).copied().unwrap_or(0); - origin.push(o); - } - Ok(None) => {} - Err(e) => warnings - .push(format!("face wrapping around a closed surface kept whole: {}", e.to_string().trim_start_matches("the operation failed: "))), - } - } - faces -} diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index dfa51e3d6..e0972f14d 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -1,4 +1,5 @@ -use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use super::*; use crate::{BoolOp, boolean, box_solid, cylinder, extrude, fillet, measure, revolve, sphere, step_export, torus}; @@ -39,7 +40,7 @@ fn assert_seam_sphere(text: &str, radius: f64) { let want_area = 4.0 * std::f64::consts::PI * radius.powi(2); assert!(rel(m.volume, want_volume) < 1e-3, "volume {} vs {want_volume}", m.volume); assert!(rel(m.area, want_area) < 1e-3, "area {} vs {want_area}", m.area); - let mesh = body.body.display_mesh(radius * 1e-3).unwrap(); + let mesh = body.body.mesh(&crate::MeshTolerance::chord(radius * 1e-3)).unwrap(); assert!(!mesh.positions.is_empty() && !mesh.triangles.is_empty()); } @@ -135,11 +136,61 @@ fn a_void_reads_as_a_cavity_whichever_way_its_shell_flag_points() { } } +/// A ball whose one face is bounded by a meridian edge from the north pole that stops short of +/// the south pole (at 2.5 rad), run out and back: the face is the whole sphere less a slit of no +/// area, so it is the same 2 mm ball as when the seam runs pole to pole. #[test] -fn non_antipodal_seam_sphere_does_not_panic() { +fn non_antipodal_seam_sphere_imports_as_a_whole_ball() { let text = seam_sphere_step(Vec3::ZERO, 2.0, Vec3::Z, Vec3::X, 0.0, false, 2.5); - let result = std::panic::catch_unwind(|| step_import(&text)); - assert!(result.is_ok()); + assert_seam_sphere(&text, 2.0); +} + +/// A whole ring torus (major radius 10, minor 3, about Z) written as one face bounded only by +/// seams: its tube circle at u = 0 and its ring circle at v = 0, each run out and back, in +/// either order round the loop; or only a slit along the tube circle, from the outer equator 2.5 +/// rad towards the top and back, the torus less a slit of no area. Each is the whole torus, +/// volume 2π²Rr² and area 4π²Rr. +#[test] +fn seam_only_torus_imports_as_a_whole_ring() { + use std::f64::consts::PI; + let (major, minor) = (10.0_f64, 3.0_f64); + let outer = major + minor; + let (end_x, end_z) = (major + minor * 2.5_f64.cos(), minor * 2.5_f64.sin()); + let tube = format!( + "#14=CARTESIAN_POINT('',({major:.16},0.,0.));\n#15=DIRECTION('',(0.,-1.,0.));\n#16=AXIS2_PLACEMENT_3D('',#14,#15,#3);\n#17=CIRCLE('',#16,{minor:.16});\n" + ); + let ring = format!("#18=CIRCLE('',#4,{outer:.16});\n#19=EDGE_CURVE('',#11,#11,#18,.T.);\n"); + let cases = [ + ("tube then ring", format!("{tube}#20=EDGE_CURVE('',#11,#11,#17,.T.);\n{ring}#30=EDGE_LOOP('',(#21,#22,#23,#24));\n")), + ("ring then tube", format!("{tube}#20=EDGE_CURVE('',#11,#11,#17,.T.);\n{ring}#30=EDGE_LOOP('',(#22,#21,#24,#23));\n")), + ( + "a slit along the tube", + format!( + "#12=CARTESIAN_POINT('',({end_x:.16},0.,{end_z:.16}));\n#13=VERTEX_POINT('',#12);\n{tube}#20=EDGE_CURVE('',#11,#13,#17,.T.);\n#30=EDGE_LOOP('',(#21,#23));\n" + ), + ), + ]; + for (what, edges) in cases { + 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=TOROIDAL_SURFACE('',#4,{major:.16},{minor:.16});\n#10=CARTESIAN_POINT('',({outer:.16},0.,0.));\n#11=VERTEX_POINT('',#10);\n" + ); + t += &edges; + t += "#21=ORIENTED_EDGE('',*,*,#20,.T.);\n#22=ORIENTED_EDGE('',*,*,#19,.T.);\n#23=ORIENTED_EDGE('',*,*,#20,.F.);\n#24=ORIENTED_EDGE('',*,*,#19,.F.);\n"; + t += "#31=FACE_OUTER_BOUND('',#30,.T.);\n#32=ADVANCED_FACE('',(#31),#5,.T.);\n#33=CLOSED_SHELL('',(#32));\n#34=MANIFOLD_SOLID_BREP('Ring',#33);\n"; + t += "#35=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#34),#70);\n"; + t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += TAIL; + let imp = step_import(&t).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(imp.bodies.len(), 1, "{what}: {:?}", imp.warnings); + assert!(imp.warnings.is_empty(), "{what}: {:?}", imp.warnings); + assert!(imp.bodies[0].closed, "{what}"); + let m = measure(&imp.bodies[0].body).unwrap(); + let (volume, area) = (2.0 * PI * PI * major * minor * minor, 4.0 * PI * PI * major * minor); + assert!(rel(m.volume, volume) < 1e-3, "{what}: volume {} vs {volume}", m.volume); + assert!(rel(m.area, area) < 1e-3, "{what}: area {} vs {area}", m.area); + } } #[test] @@ -164,15 +215,14 @@ fn benchmark_independent_step_solids() { let start = std::time::Instant::now(); let ex = p21::parse(&text).unwrap(); let parse = start.elapsed(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 0.01, snap: 0.01 }; let mut items: Vec<_> = ex.entities.iter().filter(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| *id).collect(); items.sort(); let start = std::time::Instant::now(); - let solids: Vec<_> = items.iter().map(|id| guard("benchmark read", || brep::read_item(&cx, *id).map_err(KernelError::Failed)).unwrap()).collect(); + let solids: Vec<_> = items.iter().map(|id| solidcraft_step::topology::read_solid(&ex, *id, Units::default()).unwrap()).collect(); let read = start.elapsed(); let start = std::time::Instant::now(); for solid in solids { - std::hint::black_box(Body::new(solid.solid).unwrap().unmeshed_faces()); + std::hint::black_box(Body::from_record(solid.brep).unwrap().unmeshed_faces()); } println!( "STEP_PHASE parse_ms={:.3} brep_ms={:.3} body_ms={:.3}", @@ -214,7 +264,7 @@ fn assert_same_import(serial: &StepImport, parallel: &StepImport) { assert_eq!(a.body.paint(), b.body.paint()); assert_eq!(a.body.face_sources, b.body.face_sources); assert_same_measure(&measure(&a.body).unwrap(), &measure(&b.body).unwrap()); - let (a, b) = (a.body.display_mesh(0.05).unwrap(), b.body.display_mesh(0.05).unwrap()); + let (a, b) = (a.body.mesh(&crate::MeshTolerance::chord(0.05)).unwrap(), b.body.mesh(&crate::MeshTolerance::chord(0.05)).unwrap()); assert_eq!(a.positions, b.positions); assert_eq!(a.normals, b.normals); assert_eq!(a.triangles, b.triangles); @@ -266,12 +316,12 @@ fn parallel_body_preparation_reports_errors_in_place_and_preserves_placement() { let body = cylinder(Vec3::new(2.0, 2.0, 0.0), Vec3::Z, 2.0, 4.0).unwrap(); let ex = p21::parse(&step_export(&[&body], "test").unwrap()).unwrap(); let solid = *ex.entities.iter().find(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| id).unwrap(); - let units = DEFAULT_UNITS; - let placement = mt::Matrix4::from_translation(mt::Vector3::new(10.0, 20.0, 30.0)); + let units = Units::default(); + let placement = translation([10.0, 20.0, 30.0]); // The second item is not in the file. let jobs: Vec<_> = [solid, 999_999_999, solid, solid] .into_iter() - .map(|item| parallel::Job { source: parallel::Source::Item { item, units }, placement, check_mesh: true, tol: units.tol }) + .map(|item| parallel::Job { source: parallel::Source::Item { item, units }, placement, check_mesh: true }) .collect(); let serial = parallel::bodies(&ex, &jobs, 1); let threaded = parallel::bodies(&ex, &jobs, 4); @@ -329,7 +379,7 @@ fn parallel_import_does_not_prepare_past_body_budget_with_duplicates_or_mapped_i reader.bodies = vec![seed.clone(); MAX_BODIES - 2]; reader.node_items.insert(2000); let mut out = Vec::new(); - reader.rep_bodies(60, &mt::Matrix4::from_scale(1.0), &[], "Budget", None, &mut out, 0); + reader.rep_bodies(60, &IDENTITY, &[], "Budget", None, &mut out, 0); assert!(reader.oriented.is_empty() && reader.unreadable.is_empty(), "the walk only plans the solids"); while reader.convert_next(workers == 1) {} let out = reader.remap(&out); @@ -355,8 +405,8 @@ fn round_trip(b: &Body) -> StepImport { let (m0, m1) = (measure(b).unwrap(), measure(&imp.bodies[0].body).unwrap()); assert!(rel(m1.volume, m0.volume) < 1e-3, "volume {} vs {}", m1.volume, m0.volume); assert!(rel(m1.area, m0.area) < 1e-3, "area {} vs {}", m1.area, m0.area); - // Pieces of one analytic surface are written as one face (volume and area above check - // that nothing was lost). + // The file has no more faces than the body (volume and area above check that nothing was + // lost). assert!(imp.bodies[0].file_faces <= b.face_count()); assert!(imp.bodies[0].closed); imp @@ -383,11 +433,9 @@ fn round_trip_features() { round_trip(&donut[0]); } -/// Robustness seed 17: a thin three-quarter tube shelled with its bottom open. truck writes each -/// wall as three quarter-turn B-spline pieces; the export merges them into one 270° face and must -/// write that face's cylinder, not the first piece's quarter sheet. The seam direction came from -/// the mean direction of the face's vertices, which is zero at 0°, 90°, 180° and 270°, so the -/// merged face kept the quarter sheet and read back about 7% short with no warning. +/// Robustness seed 17: a thin three-quarter tube shelled with its bottom open reads back whole +/// (an export once wrote a 270° wall on a quarter of its surface, and the part read back about +/// 7% short with no warning). #[test] fn shelled_three_quarter_tube_round_trips() { let rect = @@ -397,6 +445,38 @@ fn shelled_three_quarter_tube_round_trips() { round_trip(&b); } +/// A half tube (half a torus's tube, half way round, closed by a flat annulus and +/// two flat ends) whose torus the file places 5 nm off the rest, well within the file's +/// accuracy: the torus face's boundary then projects a hair past both ends of its half of the +/// tube, and its NURBS form once took the quarter past each end too, going round the whole tube, +/// which SMLib does not take for a torus: the part came in as a mesh of its faces. +#[test] +fn half_tube_a_hair_off_its_torus_imports_as_a_solid() { + use solidcore_record::Seg2; + use std::f64::consts::PI; + let (major, minor) = (10.75, 1.25); + let d = Loop2 { + segs: vec![ + Seg2::Arc { center: Vec2::new(major, 0.0), radius: minor, start: 0.0, sweep: PI }, + Seg2::Line { a: Vec2::new(major - minor, 0.0), b: Vec2::new(major + minor, 0.0) }, + ], + }; + let tube = revolve(&Plane::XZ, &[Region2 { outer: d, holes: vec![] }], Vec2::ZERO, Vec2::Y, PI).unwrap().pop().unwrap(); + let text = step_export(&[&tube], "test").unwrap(); + // The torus's placement moved to a point of its own, 5 nm along the axis, off the face's side. + let torus = text.lines().find_map(|l| l.split_once("=TOROIDAL_SURFACE('',#")).unwrap().1.split(',').next().unwrap().to_string(); + let place = text.lines().find(|l| l.starts_with(&format!("#{torus}=AXIS2_PLACEMENT_3D('',#"))).unwrap(); + let (_, axes) = place.split_once("('',#").unwrap().1.split_once(',').unwrap(); + let mut low = text.replace(place, &format!("#{torus}=AXIS2_PLACEMENT_3D('',#900000,{axes}")); + let data_end = low.rfind("ENDSEC;").unwrap(); + low.insert_str(data_end, "#900000=CARTESIAN_POINT('',(0.0,0.0,-5.E-6));\n"); + let imp = step_import(&low).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + let b = &imp.bodies[0]; + assert!(b.refused.is_none() && b.closed && !b.body.is_mesh() && !b.body.is_surface(), "{:?} {:?}", b.refused, imp.warnings); + assert!(rel(measure(&b.body).unwrap().volume, measure(&tube).unwrap().volume) < 1e-3); +} + #[test] fn several_bodies_and_names() { let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); @@ -427,72 +507,6 @@ fn imported_bodies_take_features() { const HEAD: &str = "ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION((''),'2;1');\nFILE_NAME('t','',(''),(''),'','hand','');\nFILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\nENDSEC;\nDATA;\n"; const TAIL: &str = "ENDSEC;\nEND-ISO-10303-21;\n"; -/// Original fixtures: elementary basis surfaces plus offsets, with no external CAD files. -fn offset_geometry(definition: &str, offset: &str, len: f64, sense: bool, points: &[mt::Point3]) -> crate::Result { - let text = format!( - "{HEAD}#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=AXIS2_PLACEMENT_3D('',#1,$,$);\n#3={definition};\n#4=OFFSET_SURFACE('',#3,{offset},.U.);\n{TAIL}" - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - crate::guard("test offset surface", || geom::surface(&cx, 4, points, &[], sense, 0).map_err(KernelError::Failed)) -} - -#[test] -fn offset_surface_analytic_geometry_and_orientation() { - use mt::{InnerSpace, MetricSpace, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let angle: f64 = 0.4; - let cases = [ - ("PLANE('',#2)".to_string(), mt::Point3::new(2.0, 3.0, 1.0), mt::Vector3::unit_z()), - ("CYLINDRICAL_SURFACE('',#2,5.)".to_string(), mt::Point3::new(6.0, 0.0, 2.0), mt::Vector3::unit_x()), - ("SPHERICAL_SURFACE('',#2,5.)".to_string(), mt::Point3::new(6.0, 0.0, 0.0), mt::Vector3::unit_x()), - ("TOROIDAL_SURFACE('',#2,10.,2.)".to_string(), mt::Point3::new(13.0, 0.0, 0.0), mt::Vector3::unit_x()), - ( - format!("CONICAL_SURFACE('',#2,5.,{angle})"), - mt::Point3::new(5.0 + 1.0 / angle.cos() + 2.0 * angle.tan(), 0.0, 2.0), - mt::Vector3::new(angle.cos(), 0.0, -angle.sin()), - ), - ]; - for (definition, point, normal) in cases { - for sense in [true, false] { - let extent = [point, point + mt::Vector3::unit_z()]; - let surface = offset_geometry(&definition, "1.", 1.0, sense, &extent).unwrap(); - let uv = surface.search_nearest_parameter(point, None, 100).unwrap(); - assert!(surface.subs(uv.0, uv.1).distance(point) < 1e-6, "{definition}"); - assert!(surface.normal(uv.0, uv.1).dot(normal) * if sense { 1.0 } else { -1.0 } > 0.99, "{definition}, sense {sense}"); - } - } - let p = mt::Point3::new(40.0, 0.0, 2.0); - let surface = offset_geometry("CYLINDRICAL_SURFACE('',#2,5.)", "-1.", 10.0, true, &[p, p + mt::Vector3::unit_z()]).unwrap(); - let uv = surface.search_nearest_parameter(p, None, 100).unwrap(); - assert!(surface.subs(uv.0, uv.1).distance(p) < 1e-6); -} - -#[test] -fn offset_surfaces_nested_and_hostile() { - let points = [mt::Point3::new(0.0, 0.0, 0.0), mt::Point3::new(0.0, 0.0, 1.0)]; - for (basis, offset) in [ - ("CYLINDRICAL_SURFACE('',#2,5.)", "-5."), - ("SPHERICAL_SURFACE('',#2,5.)", "-6."), - ("TOROIDAL_SURFACE('',#2,10.,2.)", "8."), - ("TOROIDAL_SURFACE('',#2,10.,2.)", "-2."), - ("CONICAL_SURFACE('',#2,5.,0.4)", "-10."), - ("PLANE('',#2)", "1.E100"), - ("PLANE('',#2)", "$"), - ] { - assert!(offset_geometry(basis, offset, 1.0, true, &points).is_err(), "{basis}, {offset}"); - } - let text = format!("{HEAD}#1=OFFSET_SURFACE('',#1,1.,.F.);{TAIL}"); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - assert!(geom::surface(&cx, 1, &points, &[], true, 0).unwrap_err().contains("nested too deeply")); - let text = format!( - "{HEAD}#1=CARTESIAN_POINT('',(0.,0.,0.));#2=AXIS2_PLACEMENT_3D('',#1,$,$);#3=CYLINDRICAL_SURFACE('',#2,5.);#4=OFFSET_SURFACE('',#3,-6.,.F.);#5=OFFSET_SURFACE('',#4,6.,.F.);{TAIL}" - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - assert!(geom::surface(&cx, 5, &points, &[], true, 0).is_err()); -} - #[test] fn offset_surface_cube_import_is_closed_and_editable() { // Move each basis plane half a file unit inward; nested quarter-unit offsets @@ -534,11 +548,23 @@ fn cube_entities() -> String { for (i, (x, y, z)) in pts.iter().enumerate() { s += &format!("#{}=CARTESIAN_POINT('',({x}.,{y}.,{z}.));\n#{}=VERTEX_POINT('',#{});\n", 200 + i, 210 + i, 200 + i); } - // 12 edges as lines (direction vector filler; trimmed by vertices). + // 12 edges, each on the line through its two vertices (trimmed by them). Their directions + // and vectors are #340 to #363, clear of the ids the assembly fixtures add (#600 on). let edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)]; - s += "#290=DIRECTION('',(1.,0.,0.));\n#291=VECTOR('',#290,1.);\n"; for (k, (a, b)) in edges.iter().enumerate() { - s += &format!("#{}=LINE('',#{},#291);\n#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", 300 + k, 200 + a, 320 + k, 210 + a, 210 + b, 300 + k); + let (p, q) = (pts[*a], pts[*b]); + let d = (q.0 - p.0, q.1 - p.1, q.2 - p.2); + s += &format!("#{}=DIRECTION('',({}.,{}.,{}.));\n#{}=VECTOR('',#{},1.);\n", 340 + 2 * k, d.0, d.1, d.2, 341 + 2 * k, 340 + 2 * k); + s += &format!( + "#{}=LINE('',#{},#{});\n#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", + 300 + k, + 200 + a, + 341 + 2 * k, + 320 + k, + 210 + a, + 210 + b, + 300 + k + ); } // Faces: (edge, forward?) loops counter-clockwise seen from outside, and plane frames. let faces: [(&[(usize, bool)], (i32, i32, i32), (i32, i32, i32)); 6] = [ @@ -596,6 +622,46 @@ fn product(pd: u64, name: &str) -> String { ) } +/// A surface model of a closed shell and an open one beside it (Poppy Humanoid's thighs: the +/// part, and a sheet of two faces on it) comes in as two bodies: the closed shell a solid of its +/// own, the open one a surface body, each in the model's colour. It once came in as one body, +/// open for its sheet's edges. +#[test] +fn a_surface_models_closed_shell_beside_a_sheet_is_a_solid_of_its_own() { + let mut t = String::from(HEAD); + t += &cube_entities(); + // A unit square sheet at z = 5. + let corners = [(0, 0), (1, 0), (1, 1), (0, 1)]; + for (i, (x, y)) in corners.iter().enumerate() { + t += &format!("#{}=CARTESIAN_POINT('',({x}.,{y}.,5.));\n#{}=VERTEX_POINT('',#{});\n", 800 + i, 810 + i, 800 + i); + } + let mut oes = Vec::new(); + for i in 0..4 { + let (a, b) = (corners[i], corners[(i + 1) % 4]); + t += &format!("#{}=DIRECTION('',({}.,{}.,0.));\n#{}=VECTOR('',#{},1.);\n", 820 + 2 * i, b.0 - a.0, b.1 - a.1, 821 + 2 * i, 820 + 2 * i); + t += &format!("#{}=LINE('',#{},#{});\n", 830 + i, 800 + i, 821 + 2 * i); + t += &format!("#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", 840 + i, 810 + i, 810 + (i + 1) % 4, 830 + i); + t += &format!("#{}=ORIENTED_EDGE('',*,*,#{},.T.);\n", 850 + i, 840 + i); + oes.push(format!("#{}", 850 + i)); + } + t += &format!("#860=EDGE_LOOP('',({}));\n#861=FACE_OUTER_BOUND('',#860,.T.);\n", oes.join(",")); + t += "#862=CARTESIAN_POINT('',(0.,0.,5.));\n#863=DIRECTION('',(0.,0.,1.));\n#864=AXIS2_PLACEMENT_3D('',#862,#863,$);\n#865=PLANE('',#864);\n"; + t += "#866=ADVANCED_FACE('',(#861),#865,.T.);\n#130=OPEN_SHELL('',(#866));\n#110=SHELL_BASED_SURFACE_MODEL('Thigh',(#100,#130));\n"; + t += &context(20, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += "#60=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#110),#20);\n"; + t += "#70=STYLED_ITEM('',(#71),#110);\n#71=PRESENTATION_STYLE_ASSIGNMENT((#72));\n#72=SURFACE_STYLE_USAGE(.BOTH.,#73);\n#73=SURFACE_SIDE_STYLE('',(#74));\n#74=SURFACE_STYLE_FILL_AREA(#75);\n#75=FILL_AREA_STYLE('',(#76));\n#76=FILL_AREA_STYLE_COLOUR('',#77);\n#77=COLOUR_RGB('',1.,0.5,0.);\n"; + t += TAIL; + let imp = step_import(&t).unwrap(); + assert_eq!(imp.bodies.len(), 2, "{:?}", imp.warnings); + let (solid, sheet) = (&imp.bodies[0], &imp.bodies[1]); + assert!(solid.closed && solid.refused.is_none() && !solid.body.is_surface(), "{:?}", imp.warnings); + assert_eq!((solid.source_item, solid.file_faces), (100, 6)); + assert!(rel(measure(&solid.body).unwrap().volume, 1.0) < 1e-9); + assert!(!sheet.closed && sheet.body.is_surface() && sheet.body.face_count() == 1); + assert_eq!((sheet.source_item, sheet.name.as_str()), (110, "Thigh")); + assert!(imp.bodies.iter().all(|b| b.color == Some([1.0, 0.5, 0.0]))); +} + #[test] fn hand_written_part_in_inches_with_colour() { let mut t = String::from(HEAD); @@ -743,9 +809,7 @@ fn instanced_assembly_of(parts: u64, n: u64) -> String { fn instanced_parts_are_oriented_once() { let n = 24; let t = instanced_assembly(n); - crate::body::ORIENTED.with(|c| c.set(0)); let imp = step_import_with_workers(&t, 1).unwrap(); - assert_eq!(crate::body::ORIENTED.with(|c| c.get()), 1, "one distinct part"); assert_eq!(imp.bodies.len(), n as usize); assert!(imp.warnings.is_empty(), "{:?}", imp.warnings); for (k, b) in imp.bodies.iter().enumerate() { @@ -760,9 +824,9 @@ fn instanced_parts_are_oriented_once() { } /// Distinct parts are oriented together, not one occurrence at a time: an assembly placing -/// two parts in turn converts in a few steps of many solids (the first finds both parts' -/// orientations side by side on the workers, the next places every other instance), where -/// converting instance by instance took one step each. +/// two parts in turn converts in one step (both parts' orientations found side by side on the +/// workers, every other instance placed after its part's first), where converting instance by +/// instance took one step each, and stopping the step at a part's second instance two. #[test] fn distinct_parts_convert_together_across_instances() { let n = 24; @@ -772,13 +836,11 @@ fn distinct_parts_convert_together_across_instances() { while reading.step() { steps += 1; } - assert_eq!(steps, 2, "both parts in the first step, every other instance in the second"); + assert_eq!(steps, 1, "both parts and every other instance in one step"); let threaded = reading.finish().unwrap(); assert_eq!(threaded.bodies.len(), n as usize); assert!(threaded.warnings.is_empty(), "{:?}", threaded.warnings); - crate::body::ORIENTED.with(|c| c.set(0)); let serial = step_import_with_workers(&t, 1).unwrap(); - assert_eq!(crate::body::ORIENTED.with(|c| c.get()), 2, "two parts"); assert_same_import(&serial, &threaded); assert_eq!(threaded.bodies[1].name, "Cube1"); assert_eq!(threaded.bodies[1].path, vec!["Assembly".to_string(), "Block1".to_string()]); @@ -794,8 +856,8 @@ fn later_instances_show_the_first_instances_mesh_placed() { // The first instance shows the shared mesh as well (meshing its own would mesh the part twice). let (Some(a), Some(b)) = (first.display_of.as_deref(), second.display_of.as_deref()) else { panic!("both instances share a display") }; assert!(std::sync::Arc::ptr_eq(&a.0, &b.0)); - let a = first.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(); - let b = second.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(); + let a = first.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(); + let b = second.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(); assert_eq!(a.triangles, b.triangles); assert_eq!(a.tri_face, b.tri_face); assert_eq!(a.edges.len(), b.edges.len()); @@ -887,10 +949,13 @@ fn repeated_items_are_shared_and_one_use_items_are_not() { assert!(boxes[1].bbox.min.dist(Vec3::new(90.0, 0.0, 0.0)) < 1e-6, "{:?}", boxes[1].bbox); } +/// A face on a surface the reader does not know is left out and named; the rest of the solid +/// comes in as a surface body of the faces that read, with no "open body" warning on top (as +/// `a_refused_solid_comes_in_as_a_surface_body_of_the_faces_that_read`). #[test] fn unsupported_face_is_left_out_and_reported() { let mut t = String::from(HEAD); - let cube = cube_entities().replace("#410=PLANE('',#409);", "#410=OFFSET_SURFACE('',#409,1.,.F.);"); + let cube = cube_entities().replace("#410=PLANE('',#409);", "#410=CURVE_BOUNDED_SURFACE('',#409,(),.F.);"); t += &cube; t += "#60=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#101),#20);\n"; t += &context(20, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); @@ -899,77 +964,11 @@ fn unsupported_face_is_left_out_and_reported() { assert_eq!(imp.bodies.len(), 1); assert!(!imp.bodies[0].closed); assert_eq!(imp.bodies[0].body.face_count(), 5); - assert!(imp.warnings.iter().any(|w| w.contains("OFFSET_SURFACE")), "{:?}", imp.warnings); - assert!(imp.warnings.iter().any(|w| w.contains("open body")), "{:?}", imp.warnings); -} - -/// A flat square sheet `size` mm across in millimetres (declared accuracy 1e-6 mm) whose right -/// edge is a straight spline ending `gap` mm beside the corner vertex it runs to, as exporters -/// write two curves meeting at a vertex between them. `stray` adds an unused vertex that far -/// out, which makes the model look that large. -fn gapped_sheet(size: f64, gap: f64, stray: Option) -> String { - let mut t = String::from(HEAD); - for (k, (x, y)) in [(0.0, 0.0), (size, 0.0), (size, size), (0.0, size)].iter().enumerate() { - t += &format!("#{}=CARTESIAN_POINT('',({x:.6},{y:.6},0.));\n#{}=VERTEX_POINT('',#{});\n", 20 + k, 30 + k, 20 + k); - } - if let Some(far) = stray { - t += &format!("#38=CARTESIAN_POINT('',({far:.6},0.,0.));\n#39=VERTEX_POINT('',#38);\n"); - } - t += &format!( - "#46=CARTESIAN_POINT('',({:.6},{size:.6},0.));\n#47=B_SPLINE_CURVE_WITH_KNOTS('',1,(#21,#46),.UNSPECIFIED.,.F.,.F.,(2,2),(0.,1.),.UNSPECIFIED.);\n", - size + gap - ); - t += "#40=DIRECTION('',(1.,0.,0.));\n#41=VECTOR('',#40,1.);\n#50=LINE('',#20,#41);\n#52=LINE('',#22,#41);\n#53=LINE('',#23,#41);\n"; - for (k, curve) in [50, 47, 52, 53].iter().enumerate() { - t += &format!( - "#{}=EDGE_CURVE('',#{},#{},#{curve},.T.);\n#{}=ORIENTED_EDGE('',*,*,#{},.T.);\n", - 60 + k, - 30 + k, - 30 + (k + 1) % 4, - 70 + k, - 60 + k - ); - } - t += "#80=EDGE_LOOP('',(#70,#71,#72,#73));\n#81=FACE_OUTER_BOUND('',#80,.T.);\n#90=CARTESIAN_POINT('',(0.,0.,0.));\n#91=DIRECTION('',(0.,0.,1.));\n"; - t += "#92=AXIS2_PLACEMENT_3D('',#90,#91,#40);\n#93=PLANE('',#92);\n#82=ADVANCED_FACE('',(#81),#93,.T.);\n"; - t += "#110=OPEN_SHELL('',(#82));\n#111=SHELL_BASED_SURFACE_MODEL('Sheet',(#110));\n#112=SHAPE_REPRESENTATION('',(#111),#10);\n"; - t += &context(10, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); - t += TAIL; - t -} - -#[test] -fn a_vertex_off_its_curve_by_a_small_share_of_the_model_is_moved_onto_it() { - // 0.19 mm on a 1 m sheet: 190 000 times the file's declared accuracy, 1.3e-4 of its size. - let imp = step_import(&gapped_sheet(1000.0, 0.19, None)).unwrap(); - assert!(!imp.warnings.iter().any(|w| w.contains("off their curve")), "{:?}", imp.warnings); - assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); - let body = &imp.bodies[0].body; - assert_eq!(body.face_count(), 1); - // Every edge meets its vertices exactly: the spline's end was moved onto the corner. - use mt::{BoundedCurve as _, MetricSpace as _}; - for e in body.solid.edge_iter() { - let c = e.curve(); - assert!(c.front().distance(e.front().point()) < 1e-9 && c.back().distance(e.back().point()) < 1e-9); - } - let m = measure(body).unwrap(); - assert!(rel(m.area, 1e6) < 1e-4, "area {}", m.area); -} - -#[test] -fn a_vertex_further_off_its_curve_than_the_model_allows_leaves_the_face_out() { - // 0.19 mm on a 10 mm sheet is 1.3 % of the part; and a stray point a kilometre out cannot - // stretch the limit past 1 mm. - for text in [gapped_sheet(10.0, 0.19, None), gapped_sheet(1000.0, 2.0, Some(1e6))] { - let warnings = match step_import(&text) { - Ok(imp) => { - assert!(imp.bodies.is_empty()); - imp.warnings.join("\n") - } - Err(e) => e.to_string(), - }; - assert!(warnings.contains("off their curve"), "{warnings}"); - } + assert!(imp.bodies[0].body.is_surface() && !imp.bodies[0].body.is_mesh()); + let unsupported = "face #411: not supported yet: surface CURVE_BOUNDED_SURFACE"; + assert!(imp.warnings.iter().any(|w| w.contains("'Cube': imported as surfaces: ") && w.contains(unsupported)), "{:?}", imp.warnings); + assert!(imp.warnings.iter().any(|w| w.contains("'Cube': left out: ") && w.contains(unsupported)), "{:?}", imp.warnings); + assert!(!imp.warnings.iter().any(|w| w.contains("open body")), "{:?}", imp.warnings); } #[test] @@ -1057,238 +1056,6 @@ fn validator_catches_broken_files() { assert!(step_validate(&format!("{HEAD}#1=SHAPE_DEFINITION_REPRESENTATION(#5);\n#5=B();\n{TAIL}")).unwrap_err().contains("dense")); } -#[test] -fn split_band_edges_are_seams() { - // A quarter pipe (torus R 10, r 3) whose face wraps around the tube with a seam edge: it is - // split for the kernel, and the split edge is drawn as a seam. - 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 += "#5=TOROIDAL_SURFACE('',#4,10.,3.);\n"; - t += "#10=CARTESIAN_POINT('',(13.,0.,0.));\n#11=CARTESIAN_POINT('',(0.,13.,0.));\n#12=VERTEX_POINT('',#10);\n#13=VERTEX_POINT('',#11);\n"; - // Tube circles at azimuth 0 (plane XZ) and 90 degrees (plane YZ), the seam around Z. - t += "#20=CARTESIAN_POINT('',(10.,0.,0.));\n#21=DIRECTION('',(0.,-1.,0.));\n#22=AXIS2_PLACEMENT_3D('',#20,#21,#3);\n#23=CIRCLE('',#22,3.);\n"; - t += "#24=CARTESIAN_POINT('',(0.,10.,0.));\n#25=DIRECTION('',(1.,0.,0.));\n#26=DIRECTION('',(0.,1.,0.));\n#27=AXIS2_PLACEMENT_3D('',#24,#25,#26);\n#28=CIRCLE('',#27,3.);\n"; - t += "#29=CIRCLE('',#4,13.);\n"; - t += "#30=EDGE_CURVE('',#12,#12,#23,.T.);\n#31=EDGE_CURVE('',#13,#13,#28,.T.);\n#32=EDGE_CURVE('',#12,#13,#29,.T.);\n"; - t += "#40=ORIENTED_EDGE('',*,*,#30,.T.);\n#41=ORIENTED_EDGE('',*,*,#32,.T.);\n#42=ORIENTED_EDGE('',*,*,#31,.F.);\n#43=ORIENTED_EDGE('',*,*,#32,.F.);\n"; - t += "#44=EDGE_LOOP('',(#40,#41,#42,#43));\n#45=FACE_OUTER_BOUND('',#44,.T.);\n#46=ADVANCED_FACE('',(#45),#5,.F.);\n"; - t += "#47=PLANE('',#22);\n#48=ORIENTED_EDGE('',*,*,#30,.F.);\n#49=EDGE_LOOP('',(#48));\n#50=FACE_OUTER_BOUND('',#49,.T.);\n#51=ADVANCED_FACE('',(#50),#47,.T.);\n"; - t += "#52=PLANE('',#27);\n#53=ORIENTED_EDGE('',*,*,#31,.T.);\n#54=EDGE_LOOP('',(#53));\n#55=FACE_OUTER_BOUND('',#54,.T.);\n#56=ADVANCED_FACE('',(#55),#52,.T.);\n"; - t += "#60=CLOSED_SHELL('',(#46,#51,#56));\n#61=MANIFOLD_SOLID_BREP('Pipe',#60);\n#62=SHAPE_REPRESENTATION('',(#61),$);\n"; - t += TAIL; - let imp = step_import(&t).unwrap(); - let ib = &imp.bodies[0]; - assert_eq!(ib.file_faces, 3); - assert_eq!(ib.body.face_count(), 4, "{:?}", imp.warnings); - // The two halves of the tube face make a quarter torus: area π²·R·r. - let curved: f64 = ib.body.faces(1e-3).unwrap().iter().filter(|f| f.plane_normal.is_none()).map(|f| f.area).sum(); - let want = std::f64::consts::PI.powi(2) * 30.0; - assert!(rel(curved, want) < 2e-3, "{curved} vs {want}"); - let m = ib.body.display_mesh(ib.body.size() * 1e-3).unwrap(); - // Seams: the file's own seam (inside the tube face) and the split edge. - assert!(m.seams.iter().filter(|s| **s).count() >= 2, "{:?}", m.seams); -} - -/// A five-sided tube on a B-spline surface closed around (radius `r`, height `h`), as one band -/// face bounded by ring edges `off` mm outside the surface, with a seam edge up one corner used -/// both ways; plus the two flat ends on the planes the rings lie in. The file declares -/// `uncertainty` mm of uncertainty of its own, which is what tells a reader how far the rings -/// may lie off the surface. -/// -/// The part's size, the rings' off-surface distance and the declared uncertainty are separate on -/// purpose: a real file's slop stays a few micrometres whether the part is 20 mm or 2 m across -/// (see `off_surface_budget_follows_the_file_not_the_part_size`). -#[derive(Clone, Copy)] -struct RingEdgeTube { - /// Radius of the surface (mm). - r: f64, - /// Height of the tube (mm). - h: f64, - /// How far outside the surface the ring edges run (mm). - off: f64, - /// The uncertainty the file declares for itself (mm). - uncertainty: f64, -} - -impl RingEdgeTube { - /// A 20 mm part with a few micrometres of slop and a micrometre of declared uncertainty: - /// what a well-behaved writer puts out. - fn small() -> RingEdgeTube { - RingEdgeTube { r: 10.0, h: 8.0, off: 0.004, uncertainty: 1e-3 } - } - - /// The same part, and the same slop, scaled to about 2 m across. - fn large() -> RingEdgeTube { - RingEdgeTube { r: 1000.0, h: 800.0, ..RingEdgeTube::small() } - } - - /// The volume the closed pentagon prism encloses (mm³). - fn volume(&self) -> f64 { - 2.5 * self.r * self.r * (std::f64::consts::TAU / 5.0).sin() * self.h - } - - /// The area of the five sides and the two five-sided ends together (mm²). - fn area(&self) -> f64 { - let side = 2.0 * self.r * (std::f64::consts::TAU / 10.0).sin(); - 5.0 * side * self.h + 5.0 * side * self.r * (std::f64::consts::TAU / 10.0).cos() - } - - fn step(&self) -> String { - ring_edge_tube_step(self.r, self.h, self.off, self.uncertainty) - } -} - -fn ring_edge_tube_step(r: f64, h: f64, off: f64, uncertainty: f64) -> String { - let corner = |k: usize, radius: f64| { - let a = std::f64::consts::TAU * (k % 5) as f64 / 5.0; - (radius * a.cos(), radius * a.sin()) - }; - let mut t = String::from(HEAD); - // Control net: the corners around (the first repeated to close it) x the two ends. - let mut rows = Vec::new(); - for k in 0..=5 { - let (x, y) = corner(k, r); - let id = 100 + 2 * k as u64; - t += &format!("#{id}=CARTESIAN_POINT('',({x:.9},{y:.9},0.));\n#{}=CARTESIAN_POINT('',({x:.9},{y:.9},{h:.9}));\n", id + 1); - rows.push(format!("(#{id},#{})", id + 1)); - } - t += &format!( - "#200=B_SPLINE_SURFACE_WITH_KNOTS('',1,1,({}),.UNSPECIFIED.,.T.,.F.,.F.,(2,1,1,1,1,2),(2,2),(0.,1.,2.,3.,4.,5.),(0.,1.),.UNSPECIFIED.);\n", - rows.join(",") - ); - // The rings, `off` mm outside the surface: each is one closed polyline edge. - for k in 0..5u64 { - let (x, y) = corner(k as usize, r + off); - t += &format!("#{}=CARTESIAN_POINT('',({x:.9},{y:.9},0.));\n#{}=CARTESIAN_POINT('',({x:.9},{y:.9},{h:.9}));\n", 300 + k, 310 + k); - } - t += "#320=VERTEX_POINT('',#300);\n#321=VERTEX_POINT('',#310);\n"; - t += "#330=POLYLINE('',(#300,#301,#302,#303,#304,#300));\n#331=POLYLINE('',(#310,#311,#312,#313,#314,#310));\n"; - t += "#340=DIRECTION('',(0.,0.,1.));\n#341=VECTOR('',#340,1.);\n#342=LINE('',#300,#341);\n"; - t += "#350=EDGE_CURVE('',#320,#320,#330,.T.);\n#351=EDGE_CURVE('',#321,#321,#331,.T.);\n#352=EDGE_CURVE('',#320,#321,#342,.T.);\n"; - // The band's loop: around the bottom ring, up the seam, back around the top, down the seam. - t += "#360=ORIENTED_EDGE('',*,*,#350,.T.);\n#361=ORIENTED_EDGE('',*,*,#352,.T.);\n#362=ORIENTED_EDGE('',*,*,#351,.F.);\n#363=ORIENTED_EDGE('',*,*,#352,.F.);\n"; - t += "#364=EDGE_LOOP('',(#360,#361,#362,#363));\n#365=FACE_OUTER_BOUND('',#364,.T.);\n#366=ADVANCED_FACE('',(#365),#200,.T.);\n"; - // The two ends, on the planes the rings lie in. - t += "#370=CARTESIAN_POINT('',(0.,0.,0.));\n#371=DIRECTION('',(1.,0.,0.));\n#372=AXIS2_PLACEMENT_3D('',#370,#340,#371);\n#373=PLANE('',#372);\n"; - t += "#374=ORIENTED_EDGE('',*,*,#350,.F.);\n#375=EDGE_LOOP('',(#374));\n#376=FACE_OUTER_BOUND('',#375,.T.);\n#377=ADVANCED_FACE('',(#376),#373,.F.);\n"; - t += &format!("#380=CARTESIAN_POINT('',(0.,0.,{h:.9}));\n#381=AXIS2_PLACEMENT_3D('',#380,#340,#371);\n#382=PLANE('',#381);\n"); - t += "#383=ORIENTED_EDGE('',*,*,#351,.T.);\n#384=EDGE_LOOP('',(#383));\n#385=FACE_OUTER_BOUND('',#384,.T.);\n#386=ADVANCED_FACE('',(#385),#382,.T.);\n"; - t += "#390=CLOSED_SHELL('',(#366,#377,#386));\n#391=MANIFOLD_SOLID_BREP('Tube',#390);\n#392=SHAPE_REPRESENTATION('',(#391),#20);\n"; - // What the file declares about its own numbers. This, and not the part's size, is how far a - // reader may let the ring edges lie off the surface. - t += "#20=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#21))GLOBAL_UNIT_ASSIGNED_CONTEXT((#22,#23))REPRESENTATION_CONTEXT('',''));\n"; - t += &format!("#21=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({uncertainty:.9}),#22,'','');\n"); - t += "#22=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#23=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n"; - t += TAIL; - t -} - -/// Every check the split band must pass, at whatever size the part is: the band comes in as two -/// faces, every face has triangles at every chord tolerance from coarse to fine, and the four -/// faces together cover the tube once and close it. -/// -/// Every tolerance here is a fraction of the body, so the same mesh is asked for at every scale; -/// the rings' off-surface distance is the one thing that stays absolute. -fn assert_ring_edge_tube_meshes(tube: &RingEdgeTube) { - let imp = step_import(&tube.step()).unwrap(); - assert!(!imp.warnings.iter().any(|w| w.contains("kept whole")), "{:?}", imp.warnings); - let ib = &imp.bodies[0]; - assert_eq!(ib.file_faces, 3); - assert_eq!(ib.body.face_count(), 4, "the band face is split in two: {:?}", imp.warnings); - assert_eq!(ib.body.unmeshed_faces(), 0, "{:?}", imp.warnings); - let size = ib.body.size(); - // Every face is meshed, and the four together cover the tube once: five sides of - // 2*R*sin(36 deg) by the height, plus the two five-sided ends. - let m = ib.body.display_mesh(size * 2e-3).unwrap(); - let mut area = vec![0.0f64; ib.body.face_count()]; - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - let (a, b, c) = (m.positions[t[0] as usize], m.positions[t[1] as usize], m.positions[t[2] as usize]); - if let Some(sum) = area.get_mut(*f as usize) { - *sum += 0.5 * (b - a).cross(c - a).len(); - } - } - let side = 2.0 * tube.r * (std::f64::consts::TAU / 10.0).sin(); - let want = tube.area(); - assert!(rel(area.iter().sum::(), want) < 5e-3, "{area:?} sums to {} not {want}", area.iter().sum::()); - // Neither half of the split is a sliver: the split line runs from ring to ring. - assert!(area.iter().all(|a| *a > 0.2 * side * tube.h), "a face of the split tube is nearly empty: {area:?}"); - // The body closes: its volume is the pentagon prism's. `measure` tessellates far finer than - // any display does, and the planner used to give up on a boundary running off its surface - // once the chord tolerance came near the gap. One face without a plan costs the whole body - // its plan, and the reference mesher cannot mesh a face on a closed B-spline surface at all, - // so both halves of the band came out with no triangles: the volume was the top cap's alone. - let vol = measure(&ib.body).unwrap().volume; - let want_vol = tube.volume(); - assert!(rel(vol, want_vol) < 1e-3, "the split band does not close the body: {vol} not {want_vol}"); - // Every face keeps its triangles at every tolerance, coarse to fine. - for frac in [2e-3, 4e-4, 4e-5, 1.1e-5, 4e-6] { - let t = size * frac; - let plan = ib.body.display_plan(t).unwrap_or_else(|e| panic!("no display plan at tol {t}: {e}")); - let bare: Vec = plan.faces.iter().filter(|f| f.triangles.is_empty()).map(|f| f.face).collect(); - assert!(bare.is_empty(), "faces {bare:?} have no triangles at tol {t}"); - } - // What the viewport and a snapshot actually draw: the display tolerance with a facet angle. - // The angle divides an edge wherever it kinks, far below the chord tolerance, which is what - // used to crowd the boundary against a corner of the surface and leave the band undrawn. - let tol = (size * 1e-3).max(1e-3); - let shown = ib.body.reference_display_mesh_angular(tol, crate::DISPLAY_ANGLE).unwrap(); - let mut drawn = vec![0.0f64; ib.body.face_count()]; - for (t, f) in shown.triangles.iter().zip(&shown.tri_face) { - let (a, b, c) = (shown.positions[t[0] as usize], shown.positions[t[1] as usize], shown.positions[t[2] as usize]); - if let Some(sum) = drawn.get_mut(*f as usize) { - *sum += 0.5 * (b - a).cross(c - a).len(); - } - } - assert!(drawn.iter().all(|a| *a > 0.2 * side * tube.h), "a face of the split tube is not drawn: {drawn:?}"); - assert!(rel(drawn.iter().sum::(), want) < 5e-3, "{drawn:?} sums to {} not {want}", drawn.iter().sum::()); -} - -/// A band face is split although its ring edges run a little off its surface. A file writes -/// edges and surfaces to its own uncertainty, so the two disagree by a few micrometres; the -/// split line lies on the surface and can only reach the surface points below the rings. -#[test] -fn band_faces_split_when_ring_edges_run_off_their_surface() { - assert_ring_edge_tube_meshes(&RingEdgeTube::small()); -} - -/// The very same fixture, the very same few micrometres of slop in the file, scaled to a part -/// about 2 m across: it meshes the same way (#1721). -#[test] -fn band_faces_split_when_a_scaled_copy_runs_off_its_surface() { - assert_ring_edge_tube_meshes(&RingEdgeTube::large()); -} - -/// How far a boundary may lie off its surface is a hundredth of the part, at every chord -/// tolerance, and more only where the file declares more. A writer's declared accuracy is what it -/// aimed for, not a bound its edges keep (a robot assembly declaring 0.01 µm has edges 10 to -/// 30 µm off), so it never tightens the bound; and it must not depend on the mesh asked for, or a -/// face accepted while the model is far away would drop out when the user zooms in (#1721). -#[test] -fn off_surface_budget_is_a_hundredth_of_the_part_at_every_chord_tolerance() { - let accepted = |tube: &RingEdgeTube| -> bool { - let imp = step_import(&tube.step()).unwrap(); - let ib = &imp.bodies[0]; - let size = ib.body.size(); - [2e-3, 4e-6].iter().all(|fraction| ib.body.display_plan(size * fraction).is_ok()) - }; - // A few micrometres, whatever the file declares, at either size. - for uncertainty in [1e-3, 1e-5] { - for tube in [RingEdgeTube { uncertainty, ..RingEdgeTube::small() }, RingEdgeTube { uncertainty, ..RingEdgeTube::large() }] { - assert!(accepted(&tube), "a part {} mm across, {} mm off on {uncertainty} declared", 2.0 * tube.r, tube.off); - } - } - // Within a hundredth of the part: a 20 mm part takes 0.15 mm, a 2 m part 2 mm; past it, no. - assert!(accepted(&RingEdgeTube { off: 0.15, ..RingEdgeTube::small() })); - assert!(accepted(&RingEdgeTube { off: 2.0, ..RingEdgeTube::large() })); - assert!(!accepted(&RingEdgeTube { off: 2.0, ..RingEdgeTube::small() }), "a 20 mm part accepts a boundary 2 mm off its surface"); - assert!(!accepted(&RingEdgeTube { off: 100.0, ..RingEdgeTube::large() }), "a 2 m part accepts a boundary 100 mm off its surface"); - // A file declaring more raises it: half a millimetre on a 20 mm part, refused on a declared - // micrometre, accepted on a declared 60 µm (ten times which is 0.6 mm). - let tight = RingEdgeTube { off: 0.5, ..RingEdgeTube::small() }; - assert!(!accepted(&tight)); - assert!(accepted(&RingEdgeTube { uncertainty: 0.06, ..tight })); -} - /// Revolved faces of a mirrored tool keep their orientation through STEP (the writer used to /// drop an inverted or mirrored revolution's sense). #[test] @@ -1377,7 +1144,7 @@ fn hostile_boundaries_mesh_in_bounded_time() { /// A cylinder written as a surface of revolution, oriented the ISO 10303-42 way (normal /// ∂S/∂angle × ∂S/∂profile, outward here, so `same_sense` .T.). Strict readers read such faces this -/// way; reading them with truck's profile-first normal turned faces inside out. +/// way; reading them with the profile's parameter first turned faces inside out. #[test] fn surface_of_revolution_sense_follows_iso() { let mut t = String::from(HEAD); @@ -1399,6 +1166,9 @@ fn surface_of_revolution_sense_follows_iso() { let m = measure(&imp.bodies[0].body).unwrap(); let want = std::f64::consts::PI * 25.0 * 10.0; assert!(rel(m.volume, want) < 1e-3, "{} vs {want}", m.volume); + // Read into schema 4 (a placed revolution), the same cylinder, outward. + let v = schema_4_volume(&t); + assert!(rel(v, want) < 1e-3, "schema 4: {v} vs {want}"); // The same face with the opposite sense is inside out. let flipped = t.replace("#36=ADVANCED_FACE('',(#35),#8,.T.);", "#36=ADVANCED_FACE('',(#35),#8,.F.);"); let bad = step_import(&flipped).unwrap(); @@ -1408,7 +1178,8 @@ fn surface_of_revolution_sense_follows_iso() { /// A tube revolved about a line it touches (a horn torus, as a tight sweep makes) is written as /// one rational B-spline face whose loop passes the pole twice, with no zero-length edge there: -/// no TOROIDAL_SURFACE (it would be degenerate) and no surface of revolution. +/// no TOROIDAL_SURFACE (it would be degenerate) and no surface of revolution. (Its volume, built +/// and read back, is the rig's import/cov-step-horn-torus-quarter-round-trip.) #[test] fn horn_torus_written_as_one_spline_face() { let prof = Region2 { outer: Loop2::circle(Vec2::new(5.0, 0.0), 5.0), holes: vec![] }; @@ -1416,13 +1187,220 @@ fn horn_torus_written_as_one_spline_face() { let text = step_export(&[&b], "t").unwrap(); assert!(!text.contains("TOROIDAL_SURFACE") && !text.contains("SURFACE_OF_REVOLUTION")); assert_eq!(text.matches("ADVANCED_FACE(").count(), 3, "{text}"); - let imp = round_trip(&b); - let v = std::f64::consts::PI * 25.0 * std::f64::consts::TAU * 5.0 / 4.0; - assert!(rel(measure(&imp.bodies[0].body).unwrap().volume, v) < 1e-3); +} + +/// How a torus-capped cylinder ([`torus_capped_cylinder`]) ends. +enum Tip { + /// The tube's quarter from its outside over to its top, at `z`, and a disc there of radius `r`. + Disc { z: f64, r: f64 }, + /// The tube on to where it meets the axis: the pole, a vertex at height `apex` on the axis + /// reached by the tube's meridian as the torus face's seam, or (`seam` false) not, its one + /// bound the circle at z = 0. + Pole { apex: f64, seam: bool }, +} + +/// A cylinder about Z of radius `major + minor` from z = -2 to 0, its top a torus about Z with +/// those radii (`torus`: the surface entity at #5 on placement #4) ending as `tip` says. +fn torus_capped_cylinder(torus: &str, major: f64, minor: f64, tip: Tip) -> String { + let outer = major + minor; + 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!("{torus}\n#6=CYLINDRICAL_SURFACE('',#4,{outer:.16});\n"); + t += "#7=CARTESIAN_POINT('',(0.,0.,-2.));\n#8=AXIS2_PLACEMENT_3D('',#7,#2,#3);\n#9=PLANE('',#8);\n"; + t += &format!( + "#13=CARTESIAN_POINT('',({outer:.16},0.,-2.));\n#14=VERTEX_POINT('',#13);\n#15=CARTESIAN_POINT('',({outer:.16},0.,0.));\n#16=VERTEX_POINT('',#15);\n" + ); + t += &format!( + "#19=CIRCLE('',#8,{outer:.16});\n#20=EDGE_CURVE('',#14,#14,#19,.T.);\n#21=CIRCLE('',#4,{outer:.16});\n#22=EDGE_CURVE('',#16,#16,#21,.T.);\n" + ); + t += "#25=VECTOR('',#2,1.);\n#26=LINE('',#13,#25);\n#27=EDGE_CURVE('',#14,#16,#26,.T.);\n"; + t += "#40=ORIENTED_EDGE('',*,*,#20,.F.);\n#41=EDGE_LOOP('',(#40));\n#42=FACE_OUTER_BOUND('',#41,.T.);\n#43=ADVANCED_FACE('',(#42),#9,.F.);\n"; + t += "#44=ORIENTED_EDGE('',*,*,#20,.T.);\n#45=ORIENTED_EDGE('',*,*,#27,.T.);\n#46=ORIENTED_EDGE('',*,*,#22,.F.);\n#47=ORIENTED_EDGE('',*,*,#27,.F.);\n"; + t += "#48=EDGE_LOOP('',(#44,#45,#46,#47));\n#49=FACE_OUTER_BOUND('',#48,.T.);\n#50=ADVANCED_FACE('',(#49),#6,.T.);\n#51=ORIENTED_EDGE('',*,*,#22,.T.);\n"; + // The tube's meridian at u = 0 from (outer, 0, 0) to `end`, the torus face's seam: centre + // (major, 0, 0), angle from X towards Z (its axis -Y). + let meridian = |t: &mut String, end: [f64; 2]| { + *t += &format!("#17=CARTESIAN_POINT('',({:.16},0.,{:.16}));\n#18=VERTEX_POINT('',#17);\n", end[0], end[1]); + *t += &format!( + "#28=CARTESIAN_POINT('',({major:.16},0.,0.));\n#29=DIRECTION('',(0.,-1.,0.));\n#30=AXIS2_PLACEMENT_3D('',#28,#29,#3);\n#31=CIRCLE('',#30,{minor:.16});\n#32=EDGE_CURVE('',#16,#18,#31,.T.);\n" + ); + *t += "#52=ORIENTED_EDGE('',*,*,#32,.T.);\n#54=ORIENTED_EDGE('',*,*,#32,.F.);\n"; + }; + let faces = match tip { + Tip::Disc { z, r } => { + meridian(&mut t, [r, z]); + t += &format!("#10=CARTESIAN_POINT('',(0.,0.,{z:.16}));\n#11=AXIS2_PLACEMENT_3D('',#10,#2,#3);\n#12=PLANE('',#11);\n"); + t += &format!("#23=CIRCLE('',#11,{r:.16});\n#24=EDGE_CURVE('',#18,#18,#23,.T.);\n#53=ORIENTED_EDGE('',*,*,#24,.F.);\n"); + t += "#55=EDGE_LOOP('',(#51,#52,#53,#54));\n#56=FACE_OUTER_BOUND('',#55,.T.);\n#57=ADVANCED_FACE('',(#56),#5,.T.);\n"; + t += "#58=ORIENTED_EDGE('',*,*,#24,.T.);\n#59=EDGE_LOOP('',(#58));\n#60=FACE_OUTER_BOUND('',#59,.T.);\n#61=ADVANCED_FACE('',(#60),#12,.T.);\n"; + "#43,#50,#57,#61" + } + Tip::Pole { apex, seam } => { + if seam { + meridian(&mut t, [0.0, apex]); + t += "#55=EDGE_LOOP('',(#51,#52,#54));\n"; + } else { + t += "#55=EDGE_LOOP('',(#51));\n"; + } + t += "#56=FACE_OUTER_BOUND('',#55,.T.);\n#57=ADVANCED_FACE('',(#56),#5,.T.);\n"; + "#43,#50,#57" + } + }; + t += &format!("#62=CLOSED_SHELL('',({faces}));\n#63=MANIFOLD_SOLID_BREP('Pin',#62);\n#64=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#63),#70);\n"); + t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += TAIL; + t +} + +/// The one closed body of `text`, its volume and area against the closed forms; `warnings` +/// the import's warnings. +fn assert_closed_measures(text: &str, volume: f64, area: f64, warnings: &[&str]) { + let imp = step_import(text).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + assert_eq!(imp.warnings, warnings, "{:?}", imp.warnings); + assert!(imp.bodies[0].closed); + let m = measure(&imp.bodies[0].body).unwrap(); + assert!(rel(m.volume, volume) < 1e-3, "volume {} vs {volume}", m.volume); + assert!(rel(m.area, area) < 1e-3, "area {} vs {area}", m.area); +} + +/// A horn torus (major radius = minor, its tube touching its axis) as a round of radius 1 on a +/// cylinder of radius 2, from the cylinder's top edge over to a disc of radius 1 at z = 1 (a +/// round pin tip). Under the round, the solid's radius at height z is 1 + √(1 − z²): +/// V = 8π + π∫₀¹(1 + √(1 − z²))² dz = 8π + π(5/3 + π/2); the round's area is +/// 2π∫₀^{π/2}(1 + cos v) dv = π² + 2π, with the cylinder's 8π and the discs' 4π and π. +#[test] +fn horn_torus_round_on_a_pin_imports_whole() { + use std::f64::consts::PI; + let t = torus_capped_cylinder("#5=TOROIDAL_SURFACE('',#4,1.,1.);", 1.0, 1.0, Tip::Disc { z: 1.0, r: 1.0 }); + assert_closed_measures(&t, 8.0 * PI + PI * (5.0 / 3.0 + PI / 2.0), 15.0 * PI + PI * PI, &[]); +} + +/// The volume and area of a spindle torus's pin end ([`Tip::Pole`]): in the meridian plane the +/// disc of radius `r` about (`major`, 0) above z = 0 and right of the axis, which the tube meets +/// at z = c = √(r² − R²) (cos v = −R/r). With s = √(r² − z²) and S(a) = ∫₀^a s dz = +/// (a√(r² − a²) + r² asin(a/r))/2: V = π∫₀^c (R + s)² dz + π∫_c^r 4Rs dz = +/// π(R²c + r²c − c³/3 + 2R·S(c)) + 4πR(S(r) − S(c)); area 2πr(R·acos(−R/r) + c). +fn pin_end(major: f64, r: f64) -> (f64, f64) { + use std::f64::consts::PI; + let c = (r * r - major * major).sqrt(); + let s = |a: f64| 0.5 * (a * (r * r - a * a).max(0.0).sqrt() + r * r * (a / r).asin()); + let volume = PI * (major * major * c + r * r * c - c.powi(3) / 3.0 + 2.0 * major * s(c)) + 4.0 * PI * major * (s(r) - s(c)); + (volume, 2.0 * PI * r * (major * (-major / r).acos() + c)) +} + +/// A spindle torus (major radius below the minor, its tube across its axis) as a pin's end: the +/// apple's part from the cylinder at z = 0 up over the tube's top and down to where the tube +/// meets the axis, a pole in a dimple ([`pin_end`], with the cylinder's side and its disc). +/// Major 1, minor 2 (the tube meets the axis at z = √3: V = 3√3π + 8π²/3, area +/// 4π(2π/3 + √3)), written as a TOROIDAL_SURFACE (as SolidWorks writes it) and as the schema's +/// DEGENERATE_TOROIDAL_SURFACE, its apple selected; with a seam to the pole, and with the +/// circle at z = 0 its one bound (the reader adds the seam). +#[test] +fn spindle_torus_pin_tip_imports_whole() { + use std::f64::consts::PI; + let s3 = 3f64.sqrt(); + let (volume, area) = pin_with_cylinder(1.0, 2.0); + assert!(rel(volume, 18.0 * PI + 3.0 * s3 * PI + 8.0 * PI * PI / 3.0) < 1e-12 && rel(area, 21.0 * PI + 4.0 * PI * (2.0 * PI / 3.0 + s3)) < 1e-12); + for torus in ["#5=TOROIDAL_SURFACE('',#4,1.,2.);", "#5=DEGENERATE_TOROIDAL_SURFACE('',#4,1.,2.,.T.);"] { + for (seam, warnings) in [(true, &[][..]), (false, &["solid 'Pin': 1 seam edges added to faces that wind around their surface"][..])] { + let t = torus_capped_cylinder(torus, 1.0, 2.0, Tip::Pole { apex: s3, seam }); + assert_closed_measures(&t, volume, area, warnings); + } + } +} + +/// [`pin_end`] on its cylinder from z = -2 ([`torus_capped_cylinder`]): its volume and area. +fn pin_with_cylinder(major: f64, minor: f64) -> (f64, f64) { + use std::f64::consts::PI; + let (v, a) = pin_end(major, minor); + let outer = major + minor; + (v + 2.0 * PI * outer * outer, a + 4.0 * PI * outer + PI * outer * outer) +} + +/// A nearly round pin end as SolidWorks writes it: a spindle torus of major radius 0.005 and +/// minor 0.345 on a cylinder of radius 0.35, its apple's part in two halves (u in [0, π] and +/// [π, 2π]) between the meridians at u = 0 and π, which meet at an apex vertex written at the +/// tube's top, z = 0.345: 3.6e-5 mm above the pole (z = √(0.345² − 0.005²)), in a file of +/// uncertainty 1e-5 mm. The meridians end 1.7e-6 rad short of the pole, where the tube's +/// circle about the axis is 1.2e-6 mm across: a pole to within the uncertainty, so each half's +/// loop jumps from one meridian to the other there. Volume and area as [`pin_end`]. +#[test] +fn nearly_round_spindle_torus_pin_end_in_halves_imports_whole() { + let (major, minor) = (0.005, 0.345); + let outer = major + minor; + 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"; + // The torus's angle from 45° below X: the halves are u in [π/4, 5π/4] and [5π/4, 9π/4] on + // it, three quarters of its NURBS form each, the meridians two apart. + t += "#88=DIRECTION('',(0.7071067811865476,-0.7071067811865476,0.));\n#89=AXIS2_PLACEMENT_3D('',#1,#2,#88);\n"; + t += &format!("#5=TOROIDAL_SURFACE('',#89,{major:.16},{minor:.16});\n#6=CYLINDRICAL_SURFACE('',#4,{outer:.16});\n"); + t += "#7=CARTESIAN_POINT('',(0.,0.,-2.));\n#8=AXIS2_PLACEMENT_3D('',#7,#2,#3);\n#9=PLANE('',#8);\n"; + t += &format!( + "#13=CARTESIAN_POINT('',({outer:.16},0.,-2.));\n#14=VERTEX_POINT('',#13);\n#15=CARTESIAN_POINT('',({outer:.16},0.,0.));\n#16=VERTEX_POINT('',#15);\n" + ); + t += &format!( + "#65=CARTESIAN_POINT('',({:.16},0.,0.));\n#66=VERTEX_POINT('',#65);\n#17=CARTESIAN_POINT('',(0.,0.,{minor:.16}));\n#18=VERTEX_POINT('',#17);\n", + -outer + ); + t += &format!("#19=CIRCLE('',#8,{outer:.16});\n#20=EDGE_CURVE('',#14,#14,#19,.T.);\n#21=CIRCLE('',#4,{outer:.16});\n"); + t += "#22=EDGE_CURVE('',#16,#66,#21,.T.);\n#67=EDGE_CURVE('',#66,#16,#21,.T.);\n#25=VECTOR('',#2,1.);\n#26=LINE('',#13,#25);\n#27=EDGE_CURVE('',#14,#16,#26,.T.);\n"; + // The meridians, each angle from -Z: at u = 0 about (major, 0, 0) towards X (axis -Y); at + // u = π about (-major, 0, 0) towards -X (axis +Y). + t += "#82=DIRECTION('',(0.,0.,-1.));\n"; + t += &format!( + "#28=CARTESIAN_POINT('',({major:.16},0.,0.));\n#29=DIRECTION('',(0.,-1.,0.));\n#30=AXIS2_PLACEMENT_3D('',#28,#29,#82);\n#31=CIRCLE('',#30,{minor:.16});\n#32=EDGE_CURVE('',#16,#18,#31,.T.);\n" + ); + t += &format!( + "#80=CARTESIAN_POINT('',({:.16},0.,0.));\n#81=DIRECTION('',(0.,1.,0.));\n#83=AXIS2_PLACEMENT_3D('',#80,#81,#82);\n#84=CIRCLE('',#83,{minor:.16});\n#85=EDGE_CURVE('',#66,#18,#84,.T.);\n", + -major + ); + t += "#40=ORIENTED_EDGE('',*,*,#20,.F.);\n#41=EDGE_LOOP('',(#40));\n#42=FACE_OUTER_BOUND('',#41,.T.);\n#43=ADVANCED_FACE('',(#42),#9,.F.);\n"; + t += "#44=ORIENTED_EDGE('',*,*,#20,.T.);\n#45=ORIENTED_EDGE('',*,*,#27,.T.);\n#46=ORIENTED_EDGE('',*,*,#67,.F.);\n#47=ORIENTED_EDGE('',*,*,#22,.F.);\n#48=ORIENTED_EDGE('',*,*,#27,.F.);\n"; + t += "#49=EDGE_LOOP('',(#44,#45,#46,#47,#48));\n#50=FACE_OUTER_BOUND('',#49,.T.);\n#51=ADVANCED_FACE('',(#50),#6,.T.);\n"; + t += "#52=ORIENTED_EDGE('',*,*,#22,.T.);\n#53=ORIENTED_EDGE('',*,*,#85,.T.);\n#54=ORIENTED_EDGE('',*,*,#32,.F.);\n#55=EDGE_LOOP('',(#52,#53,#54));\n#56=FACE_OUTER_BOUND('',#55,.T.);\n#57=ADVANCED_FACE('',(#56),#5,.T.);\n"; + t += "#58=ORIENTED_EDGE('',*,*,#67,.T.);\n#59=ORIENTED_EDGE('',*,*,#32,.T.);\n#60=ORIENTED_EDGE('',*,*,#85,.F.);\n#61=EDGE_LOOP('',(#58,#59,#60));\n#62=FACE_OUTER_BOUND('',#61,.T.);\n#63=ADVANCED_FACE('',(#62),#5,.T.);\n"; + t += "#64=CLOSED_SHELL('',(#43,#51,#57,#63));\n#86=MANIFOLD_SOLID_BREP('Pin',#64);\n#87=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#86),#70);\n"; + t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))").replace("LENGTH_MEASURE(1.E-6)", "LENGTH_MEASURE(1.E-5)"); + t += TAIL; + let (volume, area) = pin_with_cylinder(major, minor); + assert_closed_measures(&t, volume, area, &[]); +} + +/// The lemon of a spindle torus (the tube's part across the axis: a closed surface with a pole +/// at each end), one face bounded by its meridian used both ways, written with a negative major +/// radius (-1, minor 2: the tube's centre on the other side of the axis, as some writers have +/// it) and as the schema's DEGENERATE_TOROIDAL_SURFACE with its lemon selected (major radius 1, +/// where the lemon is the tube's far side, R + r cos v < 0, and the surface's normal +/// ∂S/∂u × ∂S/∂v points into it: `same_sense` .F.). Its radius at height z is √(4 − z²) − 1 +/// for |z| ≤ √3: V = π∫(5 − z² − 2√(4 − z²)) dz = π(6√3 − 8π/3); area +/// 2π∫_{−π/3}^{π/3}(2 cos v − 1)·2 dv = 4π(2√3 − 2π/3). +#[test] +fn spindle_torus_lemon_with_a_negative_major_radius_imports_whole() { + use std::f64::consts::PI; + let s3 = 3f64.sqrt(); + for (torus, sense) in [("#5=TOROIDAL_SURFACE('',#4,-1.,2.);", "T"), ("#5=DEGENERATE_TOROIDAL_SURFACE('',#4,1.,2.,.F.);", "F")] { + 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 += torus; + // The meridian at u = 0: the circle about (-1, 0, 0) from v = -π/3 to π/3, angle from X + // towards Z (its axis -Y). + t += &format!( + "\n#6=CARTESIAN_POINT('',(0.,0.,{:.16}));\n#7=VERTEX_POINT('',#6);\n#8=CARTESIAN_POINT('',(0.,0.,{s3:.16}));\n#9=VERTEX_POINT('',#8);\n", + -s3 + ); + t += "#10=CARTESIAN_POINT('',(-1.,0.,0.));\n#11=DIRECTION('',(0.,-1.,0.));\n#12=AXIS2_PLACEMENT_3D('',#10,#11,#3);\n#13=CIRCLE('',#12,2.);\n#14=EDGE_CURVE('',#7,#9,#13,.T.);\n"; + t += "#15=ORIENTED_EDGE('',*,*,#14,.T.);\n#16=ORIENTED_EDGE('',*,*,#14,.F.);\n#17=EDGE_LOOP('',(#15,#16));\n#18=FACE_OUTER_BOUND('',#17,.T.);\n"; + t += &format!("#19=ADVANCED_FACE('',(#18),#5,.{sense}.);\n"); + t += "#20=CLOSED_SHELL('',(#19));\n#21=MANIFOLD_SOLID_BREP('Lemon',#20);\n#22=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#21),#70);\n"; + t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += TAIL; + assert_closed_measures(&t, PI * (6.0 * s3 - 8.0 * PI / 3.0), 4.0 * PI * (2.0 * s3 - 2.0 * PI / 3.0), &[]); + } } /// Booleans and blends build the same body every time, so an export is byte-identical from -/// run to run (truck used to emit a boolean's faces in hash order of their addresses). The +/// run to run (an export once listed a boolean's faces in hash order of their addresses). The /// tee of oracle 35 with its rolling-ball fillet round the junction. #[test] fn tee_fillet_exports_byte_identical() { @@ -1459,13 +1437,13 @@ fn glued_halves_export_as_whole_faces() { assert_eq!(imp.bodies[0].file_faces, 8); } -/// A slot plate with a round on its top outline (issue #612): the extruded arc ends and the -/// rounds along the straight edges are lone B-spline sheets, written as cylinders bounded by -/// their faces. The rounds' sheets reach far past their edges, and a reader bounding the part by -/// its surfaces saw a 60 mm part as 130 mm long. +/// A slot plate with a round on its top outline (issue #612): every surface the file writes is +/// bounded by its face, whatever kind it is written as. The rounds' sheets once reached far past +/// their edges, and a reader bounding the part by its surfaces saw a 60 mm part as 130 mm long. +/// Read back, the part has its exact volume. #[test] fn rounded_slot_exports_cylinders() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; use std::f64::consts::{FRAC_PI_2, PI}; let outer = Loop2 { segs: vec![ @@ -1479,10 +1457,7 @@ fn rounded_slot_exports_cylinders() { let edges = [Vec3::new(30.0, -10.0, 4.0), Vec3::new(30.0, 10.0, 4.0), Vec3::new(0.0, 0.0, 4.0), Vec3::new(60.0, 0.0, 4.0)]; let b = fillet(&plate, &edges, 1.0).unwrap(); let text = step_export(&[&b], "t").unwrap(); - assert!(!text.contains("B_SPLINE_SURFACE"), "{text}"); - assert_eq!(text.matches("CYLINDRICAL_SURFACE(").count(), 4); - assert_eq!(text.matches("TOROIDAL_SURFACE(").count(), 2); - // No point of the file (surface placements included) lies outside the part. + // No point of the file (control points and surface placements included) lies outside the part. let imp = round_trip(&b); for line in text.lines().filter(|l| l.contains("CARTESIAN_POINT")) { let Some(xyz) = line.split("((").nth(1).and_then(|r| r.split("))").next()) else { continue }; @@ -1498,13 +1473,12 @@ fn rounded_slot_exports_cylinders() { } /// A slot plate rounded along its top and bottom outlines, with a ramp cut across one end -/// (issue #1198). The other end's half turn is still written as a cylinder (its corners alone -/// point both ways: the seam comes from points along its edges). The faces the ramp crosses keep -/// their B-spline sheets, cut down to the faces: the rounds' sheets reached 35 mm past both ends, -/// and readers bounding the part by its surfaces saw a 60 mm part as 130 mm long. +/// (issue #1198): every surface the file writes is cut down to its face, so nothing reaches past +/// the part's ends (the rounds' sheets once reached 35 mm past both, and readers bounding the part +/// by its surfaces saw a 60 mm part as 130 mm long), and the part reads back whole. #[test] fn ramp_cut_slot_exports_sheets_bounded_by_their_faces() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; use std::f64::consts::{FRAC_PI_2, PI}; let outer = Loop2 { segs: vec![ @@ -1524,10 +1498,6 @@ fn ramp_cut_slot_exports_sheets_bounded_by_their_faces() { let tool = extrude(&side, &[ramp], -12.0, 0.0).unwrap().pop().unwrap(); let b = boolean(&rounded, &tool, BoolOp::Cut).unwrap().unwrap(); let text = step_export(&[&b], "t").unwrap(); - // Both ends' walls and the three rounds along the sides it leaves whole; the two the ramp - // crosses stay sheets. - assert_eq!(text.matches("CYLINDRICAL_SURFACE(").count(), 5, "{text}"); - assert_eq!(text.matches("B_SPLINE_SURFACE(").count(), 2, "{text}"); // No point of the file (control points and placements included) lies past the part's ends. for line in text.lines().filter(|l| l.contains("CARTESIAN_POINT")) { let Some(xyz) = line.split("((").nth(1).and_then(|r| r.split("))").next()) else { continue }; @@ -1549,7 +1519,7 @@ fn countersink_exports_one_cone() { // A 90° countersink, radius 4 at the top face, down from 1 mm above it to radius 1.8, and the // 2 mm drill through. let disc = Region2 { outer: Loop2::circle(Vec2::ZERO, 5.0), holes: vec![] }; - let cone = crate::extrude_tapered(&Plane::XY.offset(5.0), &disc, 3.2, -1.0, -FRAC_PI_4).unwrap(); + let cone = crate::extrude_tapered(&Plane::XY.offset(5.0), &disc, 3.2, -1.0, -FRAC_PI_4, crate::DraftCorner::default()).unwrap(); let drill = cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 2.0, 6.0).unwrap(); let b = boolean(&boolean(&plate, &cone, BoolOp::Cut).unwrap().unwrap(), &drill, BoolOp::Cut).unwrap().unwrap(); let text = step_export(&[&b], "t").unwrap(); @@ -1561,10 +1531,10 @@ fn countersink_exports_one_cone() { assert_eq!(imp.bodies[0].file_faces, 8); } -/// Knot multiplicities are expanded into one value each before the knot count is compared with -/// the control points, so the sum has to be checked first: 1,000,000 knots of multiplicity 64 -/// against two control points asked for a 500 MB vector (20,000,000 for 10 GB) only to reject -/// it afterwards, and an allocation failure aborts the process where an error does not. +/// Knot multiplicities are checked before anything is expanded: 1,000,000 knots of multiplicity +/// 64 against two control points asked for a 500 MB vector (20,000,000 for 10 GB) only to reject +/// it afterwards, and an allocation failure aborts the process where an error does not. A knot +/// above degree + 1 is refused on its own; knots each within it are refused by their sum. #[test] fn knot_multiplicities_are_checked_before_they_are_expanded() { let curve = |n: usize, mult: usize| { @@ -1579,11 +1549,12 @@ fn knot_multiplicities_are_checked_before_they_are_expanded() { }; let read = |text: &str| { let ex = p21::parse(text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - geom::curve(&cx, 3, 0) + solidcraft_step::read::Reader::new(&ex, Default::default()).curve(3).map(|_| ()) }; + // These diagnostics come from the checks before expansion; wall-clock time depends on CI load. let error = read(&curve(1_000_000, 64)).unwrap_err(); - // This diagnostic comes from the check before expansion; wall-clock time depends on CI load. + assert!(error.contains("bad knot multiplicity"), "{error}"); + let error = read(&curve(1_000_000, 2)).unwrap_err(); assert!(error.contains("knot multiplicities do not match"), "{error}"); // A degree-1 curve with two control points needs exactly four knot values. assert!(read(&curve(2, 2)).is_ok()); @@ -1591,50 +1562,6 @@ fn knot_multiplicities_are_checked_before_they_are_expanded() { assert!(read(&curve(2, 3)).is_err()); } -/// A spline written over a parameter range of a few millionths (as if in metres of a part drawn -/// in millimetres: piecewise cubic Bézier over 5.4e-6, as a STEP part of a humanoid robot -/// writes its edges) is read over a range of 1. Over the file's own range the kernel took knots -/// a millionth apart for one, so trimming an edge to its vertices dropped a control point and -/// left a curve no exact store could keep (every reopen of that design imported it again). -#[test] -fn a_spline_over_a_tiny_parameter_range_is_read_over_one() { - use mt::{BoundedCurve, Cut, MetricSpace, ParametricCurve}; - let a = 1.8024e-6; - let knots = [0.0, a, 3.0304e-6, 3.8749e-6, 4.7103e-6, 5.0653e-6, 5.4274e-6]; - let n = 3 * (knots.len() - 1) + 1; - let points: String = (0..n).map(|i| format!("#{}=CARTESIAN_POINT('',({}.,{}.,0.));\n", 10 + i, i, (i * i) % 7)).collect(); - let refs: Vec = (0..n).map(|i| format!("#{}", 10 + i)).collect(); - let mults: Vec = (0..knots.len()).map(|i| if i == 0 || i + 1 == knots.len() { "4".into() } else { "3".into() }).collect(); - let text = format!( - "{HEAD}{points}#3=B_SPLINE_CURVE_WITH_KNOTS('',3,({}),.UNSPECIFIED.,.F.,.F.,({}),({}),.UNSPECIFIED.);\n{TAIL}", - refs.join(","), - mults.join(","), - knots.iter().map(|k| format!("{k:e}")).collect::>().join(",") - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let Ok(geom::CurveGeo::BSpline(c)) = geom::curve(&cx, 3, 0) else { panic!("a B-spline") }; - let (t0, t1) = c.range_tuple(); - assert_eq!((t0, t1), (0.0, 1.0)); - // The same curve: its ends are the first and last control points. - assert!(c.subs(t0).distance(mt::Point3::new(0.0, 0.0, 0.0)) < 1e-12); - assert!(c.subs(t1).distance(mt::Point3::new((n - 1) as f64, ((n - 1) * (n - 1) % 7) as f64, 0.0)) < 1e-12); - // Cut between knots, as an edge is trimmed to its vertices: both pieces keep clamped ends - // and every control point, and meet where the curve was cut. - for t in [0.3, 0.33, 0.9, 0.95] { - let mut head = c.clone(); - let tail = head.cut(t); - for piece in [&head, &tail] { - let k: Vec = piece.knot_vec().iter().copied().collect(); - let d = piece.degree(); - assert_eq!(piece.control_points().len() + d + 1, k.len()); - assert!(k.iter().take(d + 1).all(|x| *x == k[0]) && k.iter().rev().take(d + 1).all(|x| Some(x) == k.last()), "{t}: {k:?}"); - } - assert!(head.subs(head.range_tuple().1).distance(c.subs(t)) < 1e-9); - assert!(tail.subs(tail.range_tuple().0).distance(c.subs(t)) < 1e-9); - } -} - /// One `ADVANCED_FACE` may list any number of bounds, and each one clones its edge handles into /// a new wire that the face extent then samples. A face naming the same loop a million times /// held 1e11 handles. @@ -1654,64 +1581,10 @@ fn faces_with_too_many_bounds_are_refused() { let start = std::time::Instant::now(); let imp = step_import(&text).unwrap(); - assert!(imp.warnings.iter().any(|w| w.contains("boundary loops")), "{:?}", imp.warnings); + assert!(imp.warnings.iter().any(|w| w.contains("face #900000 with 100000 bounds")), "{:?}", imp.warnings); assert!(start.elapsed() < std::time::Duration::from_secs(10), "took {:?}", start.elapsed()); } -/// A board-like assembly for issue #883: `SOLIDCRAFT_STEP_PCB_FIXTURE=path` writes it (with -/// `SOLIDCRAFT_STEP_PCB_COMPONENTS` and `SOLIDCRAFT_STEP_PCB_PINS`; 600 and 15 give 52 MB). Every component is -/// its own product with a package body and its own pins (nothing shared), the worst case for -/// a large import. -#[test] -#[ignore = "manual fixture generator for large STEP imports"] -fn generate_board_assembly_fixture() { - use crate::step_out::{ExportBody, ExportProduct, StepHeader, step_export_products}; - let count: usize = solidcraft_geom::env::var("STEP_PCB_COMPONENTS").map(|s| s.parse().unwrap()).unwrap_or(500); - let pins: usize = solidcraft_geom::env::var("STEP_PCB_PINS").map(|s| s.parse().unwrap()).unwrap_or(16); - let mut owned: Vec> = Vec::new(); - for c in 0..count { - let w = 4.0 + (c % 7) as f64 * 0.37; - let d = 3.0 + (c % 5) as f64 * 0.29; - let mut bodies = vec![fillet_box(w, d, 1.2 + (c % 3) as f64 * 0.1)]; - for p in 0..pins { - let side = if p % 2 == 0 { -0.6 } else { d + 0.6 }; - let x = 0.3 + (p / 2) as f64 * (w - 0.6) / (pins / 2).max(1) as f64 + c as f64 * 1e-4; - bodies.push(cylinder(Vec3::new(x, side, -1.5), Vec3::Z, 0.25, 2.0 + (p % 3) as f64 * 0.01).unwrap()); - } - owned.push(bodies); - } - let mut products: Vec = owned - .iter() - .enumerate() - .map(|(c, bodies)| ExportProduct { - name: format!("U{c}"), - bodies: bodies.iter().enumerate().map(|(k, b)| ExportBody { name: format!("U{c}_{k}"), body: b, color: Some([0.2, 0.2, 0.2]) }).collect(), - children: Vec::new(), - }) - .collect(); - let side = (count as f64).sqrt().ceil() as usize; - let children = (0..count) - .map(|c| { - let (x, y) = ((c % side) as f64 * 12.0, (c / side) as f64 * 10.0); - (c, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [x, y, 1.6, 1.0]], format!("U{c}")) - }) - .collect(); - products.push(ExportProduct { name: "Board".into(), bodies: Vec::new(), children }); - let root = products.len() - 1; - let text = step_export_products(&products, root, &StepHeader { file_name: "board.step".into(), ..Default::default() }).unwrap(); - let path = solidcraft_geom::env::var("STEP_PCB_FIXTURE").unwrap_or_else(|| "board.step".into()); - std::fs::write(&path, &text).unwrap(); - println!("wrote {path}: {} bytes, {} components", text.len(), count); -} - -fn fillet_box(w: f64, d: f64, h: f64) -> Body { - let b = box_solid(Vec3::ZERO, Vec3::new(w, d, h)).unwrap(); - let vertical = [Vec3::new(0.0, 0.0, h / 2.0), Vec3::new(w, 0.0, h / 2.0), Vec3::new(w, d, h / 2.0), Vec3::new(0.0, d, h / 2.0)]; - let top = [Vec3::new(w / 2.0, 0.0, h), Vec3::new(w, d / 2.0, h), Vec3::new(w / 2.0, d, h), Vec3::new(0.0, d / 2.0, h)]; - let b = fillet(&b, &vertical, 0.3).unwrap_or(b); - fillet(&b, &top, 0.1).unwrap_or(b) -} - /// Independent boxes as one STEP file (about 3 KB a box). fn boxes_step(count: usize, name: &str) -> String { let bodies: Vec<_> = (0..count) @@ -1774,189 +1647,6 @@ fn large_imports_are_freed_with_their_last_user() { assert!(weak.upgrade().is_none(), "the cache must not keep a large import alive after its design is gone"); } -/// A face that runs all the way around a closed (but not periodic) B-spline surface and carries -/// a zero-width slit of its own: a pair of curves a hundredth of a micrometre apart between the -/// same two vertices, which the loop walks up and straight back down. STEP writers leave such a -/// slit where two surfaces were trimmed apart. It stands away from the surface's join, so the -/// band splitter leaves the face whole and the mesher has to draw it; the boundary then runs -/// along itself in (u, v). That used to fail the planner, and with it the whole body's plan, so -/// the body fell back to the reference mesher, which drew bands folded over themselves and left -/// holes in others. -#[test] -fn band_face_with_a_zero_width_slit_is_still_meshed() { - const R: f64 = 10.0; - const H: f64 = 8.0; - /// How far the slit's two sides stand apart (a hundredth of a micrometre). - const LENS: f64 = 1.0e-5; - let corner = |k: usize, r: f64| { - let a = std::f64::consts::TAU * (k % 5) as f64 / 5.0; - (r * a.cos(), r * a.sin()) - }; - let mut t = String::from(HEAD); - // Control net: the five corners around (the first repeated to close it) × the two ends. - let mut rows = Vec::new(); - for k in 0..=5 { - let (x, y) = corner(k, R); - let id = 100 + 2 * k as u64; - t += &format!("#{id}=CARTESIAN_POINT('',({x:.12},{y:.12},0.));\n#{}=CARTESIAN_POINT('',({x:.12},{y:.12},{H:.1}));\n", id + 1); - rows.push(format!("(#{id},#{})", id + 1)); - } - t += &format!( - "#200=B_SPLINE_SURFACE_WITH_KNOTS('',1,1,({}),.UNSPECIFIED.,.T.,.F.,.F.,(2,1,1,1,1,2),(2,2),(0.,1.,2.,3.,4.,5.),(0.,1.),.UNSPECIFIED.);\n", - rows.join(",") - ); - // The seam runs up corner 0; the slit stands at corner 2, where each ring is cut in two. - let (mx, my) = corner(2, R + LENS); - t += &format!("#210=CARTESIAN_POINT('',({mx:.12},{my:.12},{:.1}));\n", H * 0.5); - t += "#300=VERTEX_POINT('',#100);\n#301=VERTEX_POINT('',#101);\n#302=VERTEX_POINT('',#104);\n#303=VERTEX_POINT('',#105);\n"; - t += "#310=DIRECTION('',(0.,0.,1.));\n#311=VECTOR('',#310,1.);\n#312=LINE('',#100,#311);\n"; - // The slit's two sides: straight up corner 2, and back down a hair outside it. - t += "#313=POLYLINE('',(#104,#105));\n#314=POLYLINE('',(#105,#210,#104));\n"; - t += "#320=POLYLINE('',(#100,#102,#104));\n#321=POLYLINE('',(#104,#106,#108,#100));\n"; - t += "#322=POLYLINE('',(#101,#103,#105));\n#323=POLYLINE('',(#105,#107,#109,#101));\n"; - t += "#330=EDGE_CURVE('',#300,#301,#312,.T.);\n"; - t += "#331=EDGE_CURVE('',#302,#303,#313,.T.);\n#332=EDGE_CURVE('',#303,#302,#314,.T.);\n"; - t += "#333=EDGE_CURVE('',#300,#302,#320,.T.);\n#334=EDGE_CURVE('',#302,#300,#321,.T.);\n"; - t += "#335=EDGE_CURVE('',#301,#303,#322,.T.);\n#336=EDGE_CURVE('',#303,#301,#323,.T.);\n"; - // The band: round the bottom to the slit, up one side of it and down the other, on round the - // bottom, up the seam, back along the top to the slit, down it and up again, on to the seam. - t += "#340=ORIENTED_EDGE('',*,*,#333,.T.);\n#341=ORIENTED_EDGE('',*,*,#331,.T.);\n#342=ORIENTED_EDGE('',*,*,#332,.T.);\n"; - t += "#343=ORIENTED_EDGE('',*,*,#334,.T.);\n#344=ORIENTED_EDGE('',*,*,#330,.T.);\n#345=ORIENTED_EDGE('',*,*,#336,.F.);\n"; - t += "#346=ORIENTED_EDGE('',*,*,#331,.F.);\n#347=ORIENTED_EDGE('',*,*,#332,.F.);\n#348=ORIENTED_EDGE('',*,*,#335,.F.);\n"; - t += "#349=ORIENTED_EDGE('',*,*,#330,.F.);\n"; - t += "#350=EDGE_LOOP('',(#340,#341,#342,#343,#344,#345,#346,#347,#348,#349));\n#351=FACE_OUTER_BOUND('',#350,.T.);\n"; - t += "#352=ADVANCED_FACE('',(#351),#200,.T.);\n"; - // The two ends, on the planes the rings lie in. - t += "#360=CARTESIAN_POINT('',(0.,0.,0.));\n#361=DIRECTION('',(1.,0.,0.));\n#362=AXIS2_PLACEMENT_3D('',#360,#310,#361);\n#363=PLANE('',#362);\n"; - t += "#364=ORIENTED_EDGE('',*,*,#334,.F.);\n#365=ORIENTED_EDGE('',*,*,#333,.F.);\n#366=EDGE_LOOP('',(#364,#365));\n"; - t += "#367=FACE_OUTER_BOUND('',#366,.T.);\n#368=ADVANCED_FACE('',(#367),#363,.F.);\n"; - t += &format!("#370=CARTESIAN_POINT('',(0.,0.,{H:.1}));\n#371=AXIS2_PLACEMENT_3D('',#370,#310,#361);\n#372=PLANE('',#371);\n"); - t += "#373=ORIENTED_EDGE('',*,*,#335,.T.);\n#374=ORIENTED_EDGE('',*,*,#336,.T.);\n#375=EDGE_LOOP('',(#373,#374));\n"; - t += "#376=FACE_OUTER_BOUND('',#375,.T.);\n#377=ADVANCED_FACE('',(#376),#372,.T.);\n"; - t += "#390=CLOSED_SHELL('',(#352,#368,#377));\n#391=MANIFOLD_SOLID_BREP('Slit tube',#390);\n#392=SHAPE_REPRESENTATION('',(#391),#20);\n"; - t += "#20=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#21))GLOBAL_UNIT_ASSIGNED_CONTEXT((#22,#23))REPRESENTATION_CONTEXT('',''));\n"; - t += "#21=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-3),#22,'','');\n"; - t += "#22=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#23=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n"; - t += TAIL; - let imp = step_import(&t).unwrap(); - assert!(imp.warnings.is_empty(), "{:?}", imp.warnings); - let ib = &imp.bodies[0]; - assert_eq!(ib.file_faces, 3); - assert_eq!(ib.body.unmeshed_faces(), 0); - // Every face is planned: one face the planner gives up on costs the whole body its plan. - let tol = 0.05; - assert!(ib.body.display_plan(tol).is_ok(), "{:?}", ib.body.display_plan(tol).err()); - // The mesh covers the tube once: five sides of 2·R·sin(36°) by the height, plus the ends. - let m = ib.body.display_mesh(tol).unwrap(); - let mut area = vec![0.0f64; ib.body.face_count()]; - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - let (a, b, c) = (m.positions[t[0] as usize], m.positions[t[1] as usize], m.positions[t[2] as usize]); - if let Some(sum) = area.get_mut(*f as usize) { - *sum += 0.5 * (b - a).cross(c - a).len(); - } - } - let side = 2.0 * R * (std::f64::consts::TAU / 10.0).sin(); - let want = 5.0 * side * H + 5.0 * side * R * (std::f64::consts::TAU / 10.0).cos(); - assert!(rel(area.iter().sum::(), want) < 5e-3, "{area:?} sums to {} not {want}", area.iter().sum::()); - // The band itself is drawn once over: not folded over itself, and with no gap left in it. - let band: f64 = (0..ib.body.face_count()).filter(|i| ib.face_origin.get(*i) == Some(&352)).map(|i| area[i]).sum(); - assert!(rel(band, 5.0 * side * H) < 5e-3, "the band covers {band} not {}", 5.0 * side * H); -} - -/// A face so thin that its whole boundary is two chords: a lens between a straight edge and an -/// arc that bows away from it by a ten-thousandth of a millimetre. The edge sampler rightly -/// leaves each side as one segment, so the boundary comes to two nodes — too few to hold a -/// triangle. The planner used to give up on such a face, and one face it gives up on costs the -/// whole body its plan, so every other face fell back to the reference mesher. STEP writers -/// leave these slivers where two surfaces were trimmed apart. -#[test] -fn a_sliver_face_too_thin_to_triangulate_does_not_cost_the_body_its_plan() { - /// The lens is shorter than one facet of the body it sits on: its whole boundary is then - /// two chords, however finely the rest of the body is meshed. - const L: f64 = 0.05; - const H: f64 = 60.0; - /// How far the arc bows away from the straight side, at its middle (above the file's own - /// uncertainty, so the two sides are not the same curve). - const BOW: f64 = 5.0e-3; - let mut t = String::from(HEAD); - // The lens lies in the xy plane: straight along y = 0, the arc bowing to y = BOW. - t += &format!("#100=CARTESIAN_POINT('',(0.,0.,0.));\n#101=CARTESIAN_POINT('',(0.,0.,{H:.1}));\n"); - t += &format!("#102=CARTESIAN_POINT('',({L:.6},0.,0.));\n#103=CARTESIAN_POINT('',({L:.6},0.,{H:.1}));\n"); - // A degree-2 spline through the ends with this middle control point bows by BOW (half of it). - t += &format!( - "#104=CARTESIAN_POINT('',({:.6},{:.9},0.));\n#105=CARTESIAN_POINT('',({:.6},{:.9},{H:.1}));\n", - L * 0.5, - 2.0 * BOW, - L * 0.5, - 2.0 * BOW - ); - t += "#110=VERTEX_POINT('',#100);\n#111=VERTEX_POINT('',#101);\n#112=VERTEX_POINT('',#102);\n#113=VERTEX_POINT('',#103);\n"; - t += "#114=DIRECTION('',(1.,0.,0.));\n#115=DIRECTION('',(0.,0.,1.));\n#116=DIRECTION('',(0.,1.,0.));\n"; - t += "#120=VECTOR('',#114,1.);\n#121=LINE('',#100,#120);\n#122=LINE('',#101,#120);\n"; - t += "#123=VECTOR('',#115,1.);\n#124=LINE('',#100,#123);\n#125=LINE('',#102,#123);\n"; - t += "#126=B_SPLINE_CURVE_WITH_KNOTS('',2,(#100,#104,#102),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.UNSPECIFIED.);\n"; - t += "#127=B_SPLINE_CURVE_WITH_KNOTS('',2,(#101,#105,#103),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.UNSPECIFIED.);\n"; - t += "#130=EDGE_CURVE('',#110,#112,#121,.T.);\n#131=EDGE_CURVE('',#111,#113,#122,.T.);\n"; - t += "#132=EDGE_CURVE('',#110,#112,#126,.T.);\n#133=EDGE_CURVE('',#111,#113,#127,.T.);\n"; - t += "#134=EDGE_CURVE('',#110,#111,#124,.T.);\n#135=EDGE_CURVE('',#112,#113,#125,.T.);\n"; - // The four surfaces: the two lens ends, the flat side and the bowed side. - t += "#140=AXIS2_PLACEMENT_3D('',#100,#115,#114);\n#141=PLANE('',#140);\n"; - t += &format!("#142=CARTESIAN_POINT('',(0.,0.,{H:.1}));\n#143=AXIS2_PLACEMENT_3D('',#142,#115,#114);\n#144=PLANE('',#143);\n"); - t += "#145=AXIS2_PLACEMENT_3D('',#100,#116,#114);\n#146=PLANE('',#145);\n"; - t += "#147=B_SPLINE_SURFACE_WITH_KNOTS('',2,1,((#100,#101),(#104,#105),(#102,#103)),.UNSPECIFIED.,.F.,.F.,.F.,(3,3),(2,2),(0.,1.),(0.,1.),.UNSPECIFIED.);\n"; - // The lens ends: two edges each, and so two nodes. Every edge of the shell is walked once - // each way, and each face's ring turns anticlockwise seen from outside the solid. - t += "#150=ORIENTED_EDGE('',*,*,#132,.T.);\n#151=ORIENTED_EDGE('',*,*,#130,.F.);\n#152=EDGE_LOOP('',(#150,#151));\n"; - t += "#153=FACE_OUTER_BOUND('',#152,.T.);\n#154=ADVANCED_FACE('',(#153),#141,.F.);\n"; - t += "#155=ORIENTED_EDGE('',*,*,#131,.T.);\n#156=ORIENTED_EDGE('',*,*,#133,.F.);\n#157=EDGE_LOOP('',(#155,#156));\n"; - t += "#158=FACE_OUTER_BOUND('',#157,.T.);\n#159=ADVANCED_FACE('',(#158),#144,.T.);\n"; - // The flat side and the bowed side, each a four-edge ring. - t += "#160=ORIENTED_EDGE('',*,*,#130,.T.);\n#161=ORIENTED_EDGE('',*,*,#135,.T.);\n#162=ORIENTED_EDGE('',*,*,#131,.F.);\n#163=ORIENTED_EDGE('',*,*,#134,.F.);\n"; - t += "#164=EDGE_LOOP('',(#160,#161,#162,#163));\n#165=FACE_OUTER_BOUND('',#164,.T.);\n#166=ADVANCED_FACE('',(#165),#146,.F.);\n"; - t += "#170=ORIENTED_EDGE('',*,*,#134,.T.);\n#171=ORIENTED_EDGE('',*,*,#133,.T.);\n#172=ORIENTED_EDGE('',*,*,#135,.F.);\n#173=ORIENTED_EDGE('',*,*,#132,.F.);\n"; - t += "#174=EDGE_LOOP('',(#170,#171,#172,#173));\n#175=FACE_OUTER_BOUND('',#174,.T.);\n#176=ADVANCED_FACE('',(#175),#147,.F.);\n"; - t += "#180=CLOSED_SHELL('',(#154,#159,#166,#176));\n#181=MANIFOLD_SOLID_BREP('Sliver lens',#180);\n#182=SHAPE_REPRESENTATION('',(#181),#20);\n"; - t += "#20=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#21))GLOBAL_UNIT_ASSIGNED_CONTEXT((#22,#23))REPRESENTATION_CONTEXT('',''));\n"; - t += "#21=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-3),#22,'','');\n"; - t += "#22=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#23=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n"; - t += TAIL; - let imp = step_import(&t).unwrap(); - assert!(imp.warnings.is_empty(), "{:?}", imp.warnings); - let ib = &imp.bodies[0]; - assert_eq!(ib.file_faces, 4); - // Nothing is left unshown, and the body keeps its plan although one face cannot hold a - // triangle until its boundary is sampled again. - assert_eq!(ib.body.unmeshed_faces(), 0); - let tol = 0.05; - let plan = ib.body.display_plan(tol).expect("a sliver face must not cost the body its plan"); - for f in &plan.faces { - assert!(!f.triangles.is_empty(), "face {} has no triangles", f.face); - } - // The sides carry the area: L by H flat, a shade more over the bow. The lens ends are - // slivers, so what matters is that they are drawn at all, not how wide they come out. - let m = ib.body.display_mesh(tol).unwrap(); - let mut area = vec![0.0f64; ib.body.face_count()]; - for (tri, f) in m.triangles.iter().zip(&m.tri_face) { - if let Some([p, q, r]) = m.tri(tri) - && let Some(sum) = area.get_mut(*f as usize) - { - *sum += 0.5 * (q - p).cross(r - p).len(); - } - } - let mut sides: Vec = area.iter().copied().filter(|a| *a > 0.1).collect(); - sides.sort_by(|a, b| a.total_cmp(b)); - assert_eq!(sides.len(), 2, "two sides carry the area: {area:?}"); - // The flat side is exactly L by H; the bowed one is longer by the bow, within a tenth. - assert!(rel(sides[0], L * H) < 1e-6, "the flat side covers {} not {}", sides[0], L * H); - assert!((1.0..1.1).contains(&(sides[1] / (L * H))), "the bowed side covers {}", sides[1]); - // Both lens ends are drawn, each a sliver no wider than its own bow. - let ends: Vec = area.iter().copied().filter(|a| *a <= 0.1).collect(); - assert_eq!(ends.len(), 2, "two lens ends: {area:?}"); - for e in ends { - assert!(e > 0.0 && e < L * BOW, "a lens end covers {e}, not a sliver under {}", L * BOW); - } -} - /// A three-quarter turn of a rectangle about Z: planar end caps, revolved cylinders and annuli. fn three_quarter_ring() -> Body { let rect = @@ -2052,51 +1742,12 @@ fn periodic_knot_tube(first: u64, x: f64, r: f64, h: f64) -> (String, u64) { (s, face) } -/// A B-spline whose end knots repeat fewer than degree + 1 times (an unclamped knot vector, -/// as OpenCascade writes closed curves and surfaces) is defined only between knot `degree` -/// and knot `len - degree - 1`. Read over the whole knot range, the circle and the tube went -/// on past their domain, and the rational ones divided by zero at the outermost knots. -#[test] -fn periodic_knot_bsplines_are_read_on_their_domain() { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface}; - let (r, h) = (1.7, 1.5); - let (tube, face) = periodic_knot_tube(100, 0.0, r, h); - let (circle, row) = circle_net(10, 0.0, r, 0.0); - let text = format!( - "{HEAD}{tube}{circle}#30=(BOUNDED_CURVE()B_SPLINE_CURVE(2,({}),.CIRCULAR_ARC.,.T.,.F.)B_SPLINE_CURVE_WITH_KNOTS(({PERIODIC_MULTS}),({PERIODIC_KNOTS}),.UNSPECIFIED.)CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE(({CIRCLE_WEIGHTS}))REPRESENTATION_ITEM(''));\n{TAIL}", - row.join(",") - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let pi = std::f64::consts::PI; - let on_tube = |p: mt::Point3| (p.x.hypot(p.y) - r).abs() < 1e-9 && p.z > -1e-9 && p.z < h + 1e-9; - - let surface_id = ex.get(face).and_then(|e| e.params().get(2)).and_then(Param::as_ref_id).unwrap(); - let surface = geom::bspline_surface(&cx, ex.get(surface_id).unwrap()).unwrap(); - let (Some((u0, u1)), Some((v0, v1))) = surface.try_range_tuple() else { panic!("unbounded surface") }; - // Along the tube the file's range (h / r) is shorter than one: it is read over one. - assert!(h / r < 1.0 && u0.abs() < 1e-12 && (u1 - 1.0).abs() < 1e-12, "u range {u0} .. {u1}"); - assert!((v0 + pi).abs() < 1e-9 && (v1 - pi).abs() < 1e-9, "v range {v0} .. {v1}"); - for i in 0..=8 { - for j in 0..=16 { - let (u, v) = (u0 + (u1 - u0) * i as f64 / 8.0, v0 + (v1 - v0) * j as f64 / 16.0); - assert!(on_tube(surface.subs(u, v)), "S({u}, {v}) = {:?}", surface.subs(u, v)); - } - } - - let geom::CurveGeo::Nurbs(curve) = geom::curve(&cx, 30, 0).unwrap() else { panic!("not a rational B-spline") }; - let (t0, t1) = curve.range_tuple(); - assert!((t0 + pi).abs() < 1e-9 && (t1 - pi).abs() < 1e-9, "curve range {t0} .. {t1}"); - for j in 0..=16 { - let t = t0 + (t1 - t0) * j as f64 / 16.0; - assert!(on_tube(curve.subs(t)), "C({t}) = {:?}", curve.subs(t)); - } -} - /// Two such tubes far apart in one body: the body's size sets a chord tolerance coarse beside /// the tubes, and meshing a face at it divided the surface's whole parameter box, whose /// corners lay outside the domain. The division never converged there (#1374's recursion), -/// and the import grew by gigabytes without end. +/// and the import grew by gigabytes without end. The sheet comes in as SMLib's B-rep of its two +/// faces, each the file's face (SMLib lists the seam edges in another canonical order than the +/// file, and keeps the file's own order), each a cylinder's side. #[test] fn periodic_knot_tube_faces_import_and_mesh() { let t0 = std::time::Instant::now(); @@ -2108,9 +1759,16 @@ fn periodic_knot_tube_faces_import_and_mesh() { ); let imp = step_import(&text).unwrap(); assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); - let m = measure(&imp.bodies[0].body).unwrap(); + let tubes = &imp.bodies[0]; + assert!(tubes.refused.is_none() && !tubes.body.is_mesh() && tubes.body.is_surface(), "{:?} {:?}", tubes.refused, imp.warnings); + assert_eq!(tubes.face_origin, vec![fa, fb], "{:?}", imp.warnings); + // Each face is the file's quadratic circle of radius r (corner weights √2/2 to 12 digits, + // a radius off by under 1e-12 of r) moved straight along its axis by h: a cylinder's side, + // 2π r h. SMLib integrates to 1e-8. + let m = measure(&tubes.body).unwrap(); let area = 2.0 * std::f64::consts::TAU * r * h; - assert!(rel(m.area, area) < 0.02, "area {} (expected {area})", m.area); + assert!(rel(m.area, area) < 1e-6, "area {} (expected {area})", m.area); + assert_eq!(tubes.body.unmeshed_faces(), 0); assert!(t0.elapsed().as_secs_f64() < 60.0, "took {:?}", t0.elapsed()); } @@ -2176,9 +1834,9 @@ fn explicit_outer_bound_keeps_shallow_cylinder_patch_trimmed() { assert_eq!(b.file_faces, 1); assert!(!b.closed); for mesh in [ - b.body.tessellate(0.01).unwrap(), - b.body.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(), - b.body.display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(), + b.body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(), + b.body.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(), + b.body.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(), ] { assert!(!mesh.triangles.is_empty()); assert!(mesh.bounds().diagonal() < 10.0, "sense={sense}: {:?}", mesh.bounds()); @@ -2188,11 +1846,17 @@ fn explicit_outer_bound_keeps_shallow_cylinder_patch_trimmed() { } } +/// The strip's one bound, not marked outer, on a face whose same_sense runs against it: the +/// loop bounds the face and the face is turned over. Its complement is no face: the cylinder is +/// unbounded along its axis, so the loop as a hole would leave a face with no outer boundary. #[test] -fn implicit_bound_can_still_describe_the_complement_of_a_patch() { +fn implicit_bound_against_its_face_sense_turns_the_face_over() { let imp = step_import(&shallow_cylinder_patch(false, false)).unwrap(); - let mesh = imp.bodies[0].body.tessellate(0.1).unwrap(); - assert!(mesh.bounds().diagonal() > 5000.0, "without an explicit outer bound the loop is a hole"); + assert!(imp.warnings.iter().any(|w| w.contains("1 faces turned over: their loops disagree with their same_sense")), "{:?}", imp.warnings); + let mesh = imp.bodies[0].body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); + assert!(mesh.bounds().diagonal() < 10.0, "{:?}", mesh.bounds()); + assert!((mesh.measure().area - 42.0).abs() < 0.01, "area {}", mesh.measure().area); + assert!(mesh.normals.iter().all(|n| n.x > 0.99), "the loop determines the face normal"); } #[test] @@ -2224,7 +1888,7 @@ fn explicit_outer_bound_crossing_a_closed_nurbs_seam_stays_trimmed() { let text = text.replacen(old, &surface, 1).replace(TAIL, &format!("{points}{TAIL}")); let imp = step_import(&text).unwrap(); let body = &imp.bodies[0].body; - let mesh = body.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(); assert!(!mesh.triangles.is_empty(), "{:?}", imp.warnings); assert!(mesh.bounds().diagonal() < 10.0, "sense={sense}: {:?}", mesh.bounds()); assert!((mesh.measure().area - 42.0).abs() < 0.01, "sense={sense}: area {}", mesh.measure().area); @@ -2249,16 +1913,20 @@ fn extruded_ellipse_patch_crossing_profile_seam_stays_trimmed() { assert!(text.contains(&old)); let text = text.replacen(&old, &surface, 1); let imported = step_import(&text).unwrap(); - assert_eq!(imported.warnings, ["solid 'Strip': imported as an open body (the shell is not closed)"]); + // Against its loop (same_sense false) the face is turned over, and the import says so. + let open = "solid 'Strip': imported as an open body (the shell is not closed)"; + let turned = "solid 'Strip': 1 faces turned over: their loops disagree with their same_sense"; + let want: &[&str] = if sense { &[open] } else { &[turned, open] }; + assert_eq!(imported.warnings, want, "sense={sense}, outer={outer}, radius={radius}"); assert_eq!(imported.bodies.len(), 1); let body = &imported.bodies[0].body; assert_eq!(imported.bodies[0].file_faces, 1); - let plan = body.display_plan(0.01).unwrap(); + let plan = body.mesh_plan(&crate::MeshTolerance::chord(0.01)).unwrap(); for mesh in [ plan.evaluate(), - body.display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(), - body.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(), - body.tessellate(0.01).unwrap(), + body.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(), + body.mesh(&crate::MeshTolerance { chord: 0.01, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(), + body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(), ] { assert!(!mesh.triangles.is_empty()); assert!(mesh.bounds().diagonal() < 10.0, "radius={radius}, sense={sense}, outer={outer}: {:?}", mesh.bounds()); @@ -2275,30 +1943,38 @@ fn extruded_ellipse_patch_crossing_profile_seam_stays_trimmed() { /// 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) + // (file, exact volume (mm³), box (min, max), kernel faces, bodies, seam edges the reader adds + // to the items it reads: `cylinder_twice` places one item twice) #[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), + let parts: [(&str, &str, f64, [f64; 6], usize, 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, 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, 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, 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, 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, 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, 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, 0), + ("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, 1), + ("dome", include_str!("../../../../tests/step-conformance/dome.step"), 16755.161, [-20.0, -20.0, 0.0, 20.0, 20.0, 20.0], 2, 1, 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, 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, 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, 0), + ("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, 0), + ("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, 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, 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, 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, 2), ]; - for (name, text, volume, bbox, faces, bodies) in parts { + for (name, text, volume, bbox, faces, bodies, seams) in parts { let imp = step_import(text).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!(imp.warnings.is_empty(), "{name}: {:?}", imp.warnings); + // A face that winds around its surface without a seam edge (a cone or a dome bounded by + // its base circle alone, a cylinder by its two rims) gets one, and the import says so. + let added: Option = imp + .warnings + .iter() + .map(|w| w.strip_suffix(" seam edges added to faces that wind around their surface")?.rsplit(": ").next()?.parse::().ok()) + .sum(); + assert_eq!(added, Some(seams), "{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; @@ -2318,15 +1994,880 @@ fn step_conformance_parts_read_back_their_exact_shape() { } } -/// #4598: a file whose bore rim runs back and forth across the bore (as main exported a moved -/// body's edge before) imports whole: the crossings of the rim's own pieces are left out of the -/// triangulation, not asserted on, so the face meshes a little off the exact rod. +/// The volume of the one solid `solidcraft_step::topology` reads from `text` into schema 4, +/// measured as the body of that record. +pub(super) fn schema_4_volume(text: &str) -> f64 { + let ex = solidcraft_step::p21::parse(text).unwrap(); + let r = solidcraft_step::topology::read_solids_with(&ex, &solidcraft_smlib::pcurves::SmlibTrims); + assert!(r.failures.is_empty() && r.solids.len() == 1, "{:?}", r.failures); + measure(&Body::from_record(r.solids[0].brep.clone()).unwrap()).unwrap().volume +} + +/// The step-conformance parts read into the kernel: the STEP reader's +/// schema 4 record, SMLib's body of it, back as a kernel body. Each has its exact volume and +/// face count, and every face is traced to a face of the file (the NURBS cylinder, dome and +/// torus ring among them: their faces wind around a spline closed on itself, and get a seam). #[test] -fn a_rim_that_runs_back_and_forth_imports_whole() { - let imp = step_import(include_str!("../../../../tests/step-regressions/rod_doubled_edge.step")).unwrap(); +fn step_conformance_parts_read_into_smlib() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/step-conformance"); + // (file, exact volume (mm³) and faces of its solid items: cylinder_twice places its one + // cylinder twice) + #[rustfmt::skip] + let parts: [(&str, f64, usize); 17] = [ + ("cone_point", 1000.0 * std::f64::consts::PI, 2), ("cone_point_vertex", 1000.0 * std::f64::consts::PI, 2), + ("cylinder", 9424.778, 3), ("cylinder_inch", 9424.778, 3), ("cylinder_nurbs", 9424.778, 3), + ("cylinder_placed", 9424.778, 3), ("cylinder_seam", 9424.778, 3), ("cylinder_twice", 9424.778, 3), + ("dome", 16755.161, 2), ("dome_nurbs", 16755.161, 2), ("far_cylinder", 9424.778, 3), + ("grooved_shaft", 153532.251, 753), ("plate_100_holes", 71588.321, 110), ("sheet_disc", 193396443.755, 3), + ("tiny_pin", std::f64::consts::FRAC_PI_8, 3), ("torus_ring_nurbs", 4934.802, 2), ("washer", 3534.292, 4), + ]; + for (name, volume, faces) in parts { + let text = std::fs::read_to_string(dir.join(format!("{name}.step"))).unwrap(); + let ex = solidcraft_step::p21::parse(&text).unwrap(); + // The file's one representation context, as the import reads it. + let ctx = ex.entities.iter().find(|(_, e)| e.record("GLOBAL_UNIT_ASSIGNED_CONTEXT").is_some()).map(|(id, _)| *id); + let units = context_units(&ex, ctx, &mut HashMap::new()); + let mut items: Vec = ex.entities.iter().filter(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| *id).collect(); + items.sort_unstable(); + let (mut v, mut n) = (0.0, 0); + for item in items { + let (part, _) = parallel::smlib_part(&ex, item, units).unwrap_or_else(|f| panic!("{name}: {}", f.msg)); + assert_eq!(part.face_origin.len(), part.body.face_count(), "{name}"); + assert!(part.face_origin.iter().all(|f| ex.get(*f).is_some_and(|e| e.name() == "ADVANCED_FACE")), "{name}: {:?}", part.face_origin); + let m = measure(&part.body).unwrap_or_else(|e| panic!("{name}: {e}")); + v += m.volume; + n += m.faces; + } + assert!(rel(v, volume) < 1e-3, "{name}: volume {v} vs {volume}"); + assert_eq!(n, faces, "{name}: faces"); + } +} + +/// A domed cubic patch 30 mm across whose four edges, cubic B-splines on its boundary rows, +/// are written `dz` mm above it, in a file that states 1e-6 mm: an intersection curve written +/// looser than its context. The patch has no closed-form pcurves for them, so SMLib makes them, +/// on the surface, and they lie `dz` from their edges. +fn dome_with_edges_raised(dz: f64) -> String { + patch_with_edges_raised(dz, false) +} + +/// [`dome_with_edges_raised`], or with `flat` the plane z = 0 in its place: its edges' pcurves +/// are then their control points' projections onto it, in closed form. +fn patch_with_edges_raised(dz: f64, flat: bool) -> String { + let z = |i: usize, j: usize| if !flat && (1..=2).contains(&i) && (1..=2).contains(&j) { 6.0 } else { 0.0 }; + let mut t = String::from(HEAD); + let mut rows = Vec::new(); + for i in 0..4 { + let row: Vec = (0..4).map(|j| format!("#{}", 100 + i * 4 + j)).collect(); + for j in 0..4 { + t += &format!("#{}=CARTESIAN_POINT('',({}.,{}.,{}));\n", 100 + i * 4 + j, i * 10, j * 10, z(i, j)); + } + rows.push(format!("({})", row.join(","))); + } + if flat { + t += "#10=PLANE('',#13);\n#11=CARTESIAN_POINT('',(0.,0.,0.));\n#12=DIRECTION('',(0.,0.,1.));\n#14=DIRECTION('',(1.,0.,0.));\n#13=AXIS2_PLACEMENT_3D('',#11,#12,#14);\n"; + } else { + t += &format!( + "#10=B_SPLINE_SURFACE_WITH_KNOTS('',3,3,({}),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.);\n", + rows.join(",") + ); + } + // The boundary, counter-clockwise from above: (i, j) runs i = 0 → 3 at j = 0, j = 0 → 3 at + // i = 3, then back; each side's control points are the patch's, raised. + let sides: [[(usize, usize); 4]; 4] = + [[(0, 0), (1, 0), (2, 0), (3, 0)], [(3, 0), (3, 1), (3, 2), (3, 3)], [(3, 3), (2, 3), (1, 3), (0, 3)], [(0, 3), (0, 2), (0, 1), (0, 0)]]; + let p = |(i, j): (usize, usize)| format!("({}.,{}.,{})", i * 10, j * 10, z(i, j) + dz); + for (k, side) in sides.iter().enumerate() { + t += &format!("#{}=CARTESIAN_POINT('',{});\n#{}=VERTEX_POINT('',#{});\n", 200 + k, p(side[0]), 210 + k, 200 + k); + let pts: Vec = (0..4).map(|m| format!("#{}", 300 + k * 4 + m)).collect(); + for (m, &q) in side.iter().enumerate() { + t += &format!("#{}=CARTESIAN_POINT('',{});\n", 300 + k * 4 + m, p(q)); + } + t += &format!("#{}=B_SPLINE_CURVE_WITH_KNOTS('',3,({}),.UNSPECIFIED.,.F.,.F.,(4,4),(0.,1.),.UNSPECIFIED.);\n", 400 + k, pts.join(",")); + } + for k in 0..4 { + t += &format!( + "#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n#{}=ORIENTED_EDGE('',*,*,#{},.T.);\n", + 500 + k, + 210 + k, + 210 + (k + 1) % 4, + 400 + k, + 510 + k, + 500 + k + ); + } + t += "#520=EDGE_LOOP('',(#510,#511,#512,#513));\n#521=FACE_OUTER_BOUND('',#520,.T.);\n#522=ADVANCED_FACE('',(#521),#10,.T.);\n"; + t += "#530=OPEN_SHELL('',(#522));\n#531=SHELL_BASED_SURFACE_MODEL('Dome',(#530));\n#532=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#531),#540);\n"; + t += &context(540, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += TAIL; + t +} + +#[test] +fn edges_written_off_their_spline_face_carry_their_gap_as_their_tolerance() { + // 0.2 µm off, 200 times the file's stated uncertainty: each edge's tolerance covers its + // gap and the face imports, its notes saying how many edges and how far. + let imp = step_import(&dome_with_edges_raised(2e-4)).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + assert!(imp.warnings.iter().any(|w| w.contains("4 edges lie off their faces' surfaces")), "{:?}", imp.warnings); + let r = imp.bodies[0].body.record(); + assert!(r.edges.iter().all(|e| e.tolerance >= 2e-4 && e.tolerance < 1e-3), "{:?}", r.edges.iter().map(|e| e.tolerance).collect::>()); + // Far off (1.5 mm) is refused, naming the gap. + let far = step_import(&dome_with_edges_raised(1.5)); + let refused = match &far { + Ok(i) => i.bodies.is_empty() && i.warnings.iter().any(|w| w.contains("off the face's surface")), + Err(e) => e.to_string().contains("off the face's surface"), + }; + assert!(refused, "{far:?}"); +} + +#[test] +fn spline_edges_off_their_plane_by_less_than_the_file_states_get_their_closed_form() { + // 0.8e-6 mm off, inside the file's 1e-6 mm but past the half of it a closed-form pcurve is + // checked within: each edge's distance from the plane, measured first, is its tolerance + // (with margin), and the face reads with its pcurves the edges' projections. A plane has no + // parameter box for SMLib to make pcurves in, so without them the face is refused. + let imp = step_import(&patch_with_edges_raised(0.8e-6, true)).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + assert!(imp.warnings.iter().any(|w| w.contains("4 edges lie off their faces' surfaces")), "{:?}", imp.warnings); + let m = measure(&imp.bodies[0].body).unwrap(); + assert!(rel(m.area, 900.0) < 1e-6, "{}", m.area); +} + +/// A spherical triangle (radius 0.5) whose edge runs from the equator over the sphere's pole to +/// a vertex 1.8° past it, as a corner ball meets its rounds (Poppy Humanoid writes one): on the +/// sphere's parameters the pole is a line where that edge's pcurve would jump half a turn. The +/// edge is split at the pole, and the face reads with its area by the spherical excess. +#[test] +fn an_edge_over_a_spheres_pole_is_split_there() { + let r = 0.5f64; + let over = (91.8f64).to_radians(); + let a = [r, 0.0, 0.0]; + let b = [0.0, r, 0.0]; + let p = [r * over.cos(), 0.0, r * over.sin()]; + let f = |x: f64| format!("{x:.17E}"); + let pt = |id: u64, q: [f64; 3]| format!("#{id}=CARTESIAN_POINT('',({},{},{}));\n", f(q[0]), f(q[1]), f(q[2])); + let dir = |id: u64, q: [f64; 3]| format!("#{id}=DIRECTION('',({},{},{}));\n", f(q[0]), f(q[1]), f(q[2])); + let mut t = String::from(HEAD); + t += &pt(1, [0.0; 3]); + t += &dir(2, [0.0, 0.0, 1.0]); + t += &dir(3, [1.0, 0.0, 0.0]); + t += "#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);\n#5=SPHERICAL_SURFACE('',#4,0.5);\n"; + t += &pt(10, a); + t += &pt(11, b); + t += &pt(12, p); + t += "#13=VERTEX_POINT('',#10);\n#14=VERTEX_POINT('',#11);\n#15=VERTEX_POINT('',#12);\n"; + // A to P in the x–z plane over the pole (normal −y, from x towards z); P to B (normal P × B, + // from P); B to A on the equator (normal −z, from y towards x). + let n = |u: [f64; 3], v: [f64; 3]| { + let c = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let l = (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]).sqrt(); + [c[0] / l, c[1] / l, c[2] / l] + }; + let unit = |u: [f64; 3]| [u[0] / r, u[1] / r, u[2] / r]; + t += &dir(20, [0.0, -1.0, 0.0]); + t += "#21=AXIS2_PLACEMENT_3D('',#1,#20,#3);\n#22=CIRCLE('',#21,0.5);\n#23=EDGE_CURVE('',#13,#15,#22,.T.);\n"; + t += &dir(30, n(p, b)); + t += &dir(31, unit(p)); + t += "#32=AXIS2_PLACEMENT_3D('',#1,#30,#31);\n#33=CIRCLE('',#32,0.5);\n#34=EDGE_CURVE('',#15,#14,#33,.T.);\n"; + t += &dir(40, [0.0, 0.0, -1.0]); + t += &dir(41, [0.0, 1.0, 0.0]); + t += "#42=AXIS2_PLACEMENT_3D('',#1,#40,#41);\n#43=CIRCLE('',#42,0.5);\n#44=EDGE_CURVE('',#14,#13,#43,.T.);\n"; + // Counter-clockwise seen from outside: A, B, P, so every edge the other way round. + t += "#50=ORIENTED_EDGE('',*,*,#44,.F.);\n#51=ORIENTED_EDGE('',*,*,#34,.F.);\n#52=ORIENTED_EDGE('',*,*,#23,.F.);\n"; + t += "#53=EDGE_LOOP('',(#50,#51,#52));\n#54=FACE_OUTER_BOUND('',#53,.T.);\n#55=ADVANCED_FACE('',(#54),#5,.T.);\n"; + t += "#60=OPEN_SHELL('',(#55));\n#61=SHELL_BASED_SURFACE_MODEL('Ball corner',(#60));\n#62=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#61),#70);\n"; + t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += TAIL; + let imp = step_import(&t).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + assert!(imp.warnings.iter().any(|w| w.contains("1 edges split where they pass through a face's pole")), "{:?}", imp.warnings); + // The spherical excess of the unit vectors' triangle, tan(E/2) = |a·(b×c)| / (1 + a·b + b·c + c·a). + let (ua, ub, up) = (unit(a), unit(b), unit(p)); + let dot = |u: [f64; 3], v: [f64; 3]| u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; + let triple = dot(ua, n(ub, up)) * (1.0 - dot(ub, up).powi(2)).sqrt(); + let excess = 2.0 * triple.abs().atan2(1.0 + dot(ua, ub) + dot(ub, up) + dot(up, ua)); + let m = measure(&imp.bodies[0].body).unwrap(); + assert!(rel(m.area, excess * r * r) < 1e-3, "{} vs {}", m.area, excess * r * r); +} + +/// A planar bicubic patch whose v = 0 side is shrunk to `side` mm (a corner of a round written as +/// a four-sided patch, Poppy Humanoid's connectors write them), bounded by three edges, its +/// boundary iso curves counter-clockwise in (u, v): up the u = 1 side, back across v = 1, down +/// the u = 0 side. The two side edges end `side` apart at one vertex, the end of the u = 0 side, +/// whose tolerance covers that gap; the face tolerance (the file's 1e-6 mm) does not. +fn patch_with_a_side_shrunk(side: f64) -> String { + let f = |x: f64| format!("{x:.17E}"); + // (i, j), i along u: the v = 0 row runs over `side`, the v = 1 row over 30 mm. + let p = |i: usize, j: usize| { + let v = j as f64 / 3.0; + [(1.0 - v) * side * i as f64 / 3.0 + v * 10.0 * i as f64, 30.0 * v, 0.0] + }; + let pt = |id: usize, q: [f64; 3]| format!("#{id}=CARTESIAN_POINT('',({},{},{}));\n", f(q[0]), f(q[1]), f(q[2])); + let mut t = String::from(HEAD); + let mut rows = Vec::new(); + for i in 0..4 { + rows.push(format!("({})", (0..4).map(|j| format!("#{}", 100 + i * 4 + j)).collect::>().join(","))); + for j in 0..4 { + t += &pt(100 + i * 4 + j, p(i, j)); + } + } + t += &format!( + "#10=B_SPLINE_SURFACE_WITH_KNOTS('',3,3,({}),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.);\n", + rows.join(",") + ); + // A at (0, 0), C at (1, 1), B at (0, 1). + for (k, q) in [p(0, 0), p(3, 3), p(0, 3)].into_iter().enumerate() { + t += &pt(200 + k, q); + t += &format!("#{}=VERTEX_POINT('',#{});\n", 210 + k, 200 + k); + } + let sides: [[(usize, usize); 4]; 3] = [[(3, 0), (3, 1), (3, 2), (3, 3)], [(3, 3), (2, 3), (1, 3), (0, 3)], [(0, 3), (0, 2), (0, 1), (0, 0)]]; + for (k, side) in sides.iter().enumerate() { + for (m, &(i, j)) in side.iter().enumerate() { + t += &pt(300 + k * 4 + m, p(i, j)); + } + let pts: Vec = (0..4).map(|m| format!("#{}", 300 + k * 4 + m)).collect(); + t += &format!("#{}=B_SPLINE_CURVE_WITH_KNOTS('',3,({}),.UNSPECIFIED.,.F.,.F.,(4,4),(0.,1.),.UNSPECIFIED.);\n", 400 + k, pts.join(",")); + t += &format!( + "#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n#{}=ORIENTED_EDGE('',*,*,#{},.T.);\n", + 500 + k, + 210 + k, + 210 + (k + 1) % 3, + 400 + k, + 510 + k, + 500 + k + ); + } + t += "#520=EDGE_LOOP('',(#510,#511,#512));\n#521=FACE_OUTER_BOUND('',#520,.T.);\n#522=ADVANCED_FACE('',(#521),#10,.T.);\n"; + t += "#530=OPEN_SHELL('',(#522));\n#531=SHELL_BASED_SURFACE_MODEL('Corner',(#530));\n#532=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#531),#540);\n"; + t += &context(540, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += TAIL; + t +} + +#[test] +fn a_patch_side_shrunk_within_its_vertexs_tolerance_is_a_pole_of_the_loop() { + // 4 µm: four times the face's tolerance, within the vertex's (1.5 × its 4 µm gap). The loop + // runs along the shrunk side between the side edges' ends, a pole for it, and the face reads + // with the patch's area: a trapezoid 30 mm high, 30 mm and `side` wide. + let side = 4e-3 * 1e-3; + let imp = step_import(&patch_with_a_side_shrunk(side)).unwrap(); assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); let m = measure(&imp.bodies[0].body).unwrap(); - // The exact rod is 74 898.5 mm³; the rim's crossings left out shave a little off. - assert!(rel(m.volume, 74_898.5) < 2e-3, "volume {}", m.volume); - assert_eq!(m.merged.faces, 5); + let area = 0.5 * (30.0 + side) * 30.0; + assert!(rel(m.area, area) < 1e-6, "{} vs {area}", m.area); +} + +/// A can of radius 5 and height 10: its bottom (on a plane facing up, the face against it), its +/// wall, and its lid on the plane `lid_z` (10 where the lid's rim lies on it). +fn can_with_its_lid_at(lid_z: f64) -> String { + format!( + "{HEAD} +#1=CARTESIAN_POINT('',(0.,0.,0.)); +#2=DIRECTION('',(0.,0.,1.)); +#3=DIRECTION('',(1.,0.,0.)); +#4=DIRECTION('',(0.,0.,-1.)); +#5=AXIS2_PLACEMENT_3D('',#1,#2,#3); +#6=AXIS2_PLACEMENT_3D('',#1,#4,#3); +#7=CARTESIAN_POINT('',(5.,0.,0.)); +#8=VERTEX_POINT('',#7); +#9=CIRCLE('',#5,5.); +#10=EDGE_CURVE('',#8,#8,#9,.T.); +#11=ORIENTED_EDGE('',*,*,#10,.F.); +#12=EDGE_LOOP('',(#11)); +#13=FACE_OUTER_BOUND('',#12,.T.); +#14=PLANE('',#5); +#15=ADVANCED_FACE('Bottom',(#13),#14,.F.); +#16=ORIENTED_EDGE('',*,*,#10,.T.); +#17=EDGE_LOOP('',(#16)); +#18=FACE_BOUND('',#17,.T.); +#19=CYLINDRICAL_SURFACE('',#5,5.); +#20=ADVANCED_FACE('Wall',(#18,#37),#19,.T.); +#30=CARTESIAN_POINT('',(0.,0.,10.)); +#31=AXIS2_PLACEMENT_3D('',#30,#2,#3); +#32=CARTESIAN_POINT('',(5.,0.,10.)); +#33=VERTEX_POINT('',#32); +#34=CIRCLE('',#31,5.); +#35=EDGE_CURVE('',#33,#33,#34,.T.); +#36=ORIENTED_EDGE('',*,*,#35,.F.); +#37=FACE_BOUND('',#38,.T.); +#38=EDGE_LOOP('',(#36)); +#39=ORIENTED_EDGE('',*,*,#35,.T.); +#40=EDGE_LOOP('',(#39)); +#41=FACE_OUTER_BOUND('',#40,.T.); +#42=CARTESIAN_POINT('',(0.,0.,{lid_z:?})); +#43=AXIS2_PLACEMENT_3D('',#42,#2,#3); +#44=PLANE('',#43); +#45=ADVANCED_FACE('Lid',(#41),#44,.T.); +#21=CLOSED_SHELL('',(#15,#20,#45)); +#22=MANIFOLD_SOLID_BREP('Can',#21); +#23=SHAPE_REPRESENTATION('',(#22),$); +{TAIL}" + ) +} + +/// A solid no B-rep can be made of comes in as an open surface body of its exact faces, the +/// faces that make it refused left out and named, as Poppy Humanoid's stock head (a face around +/// an open surface of revolution with one bound) and Congé19 (an edge further off its face than +/// any tolerance SMLib takes) do. A can whose lid lies 1.5 mm off its rim: the lid is left out, +/// the bottom and the wall come in sharing their rim, and the existing surface tools close the +/// can again (the rim patched, the patch stitched on): a solid with the can's volume. +#[test] +fn a_refused_solid_comes_in_as_a_surface_body_of_the_faces_that_read() { + let pi = std::f64::consts::PI; + let whole = step_import(&can_with_its_lid_at(10.0)).unwrap(); + assert_eq!(whole.bodies.len(), 1, "{:?}", whole.warnings); + assert!(whole.bodies[0].closed && whole.bodies[0].refused.is_none(), "{:?}", whole.warnings); + assert!(rel(measure(&whole.bodies[0].body).unwrap().volume, 250.0 * pi) < 1e-6); + + let imp = step_import(&can_with_its_lid_at(11.5)).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + let can = &imp.bodies[0]; + assert!(!can.body.is_mesh() && can.body.is_surface() && !can.closed, "{:?}", imp.warnings); + let why = can.refused.as_deref().unwrap_or_default(); + assert!(why.contains("face #45") && why.contains("off the face's surface"), "{why}"); + assert_eq!((can.file_faces, can.body.face_count()), (3, 2)); + assert_eq!(can.face_origin, [15, 20]); + // The bottom faces down as the file has it, against its plane's natural normal (SMLib gives + // a sheet's faces back on their natural side; the import turns it back). + let r = can.body.record(); + let bottom = can.face_origin.iter().position(|f| *f == 15).unwrap(); + let uses: Vec = r + .shells + .iter() + .flat_map(|s| match s { + solidcore_record::brep::Shell::Faces { faces, .. } => faces.iter().filter(|f| f.face as usize == bottom).map(|f| f.forward).collect(), + _ => Vec::new(), + }) + .collect(); + assert_eq!(uses, [false], "the bottom's use"); + // The report keeps the refusal and names the face left out; no "open body" warning on top. + assert!(imp.warnings.iter().any(|w| w.contains("'Can': imported as surfaces: ") && w.contains(why)), "{:?}", imp.warnings); + assert!(imp.warnings.iter().any(|w| w.contains("'Can': left out: ") && w.contains("face #45")), "{:?}", imp.warnings); + assert!(!imp.warnings.iter().any(|w| w.contains("open body")), "{:?}", imp.warnings); + // Exact: the bottom's disk and the wall's 10 mm of cylinder. + assert!(rel(measure(&can.body).unwrap().area, 125.0 * pi) < 1e-6, "{}", measure(&can.body).unwrap().area); + // Closed again with the existing tools. + let lid = crate::patch_edges(&can.body, &[Vec3::new(0.0, 5.0, 10.0)]).unwrap(); + let back = crate::stitch(&[&can.body, &lid], 0.0).unwrap(); + assert!(!back.is_surface(), "closed"); + assert!(rel(measure(&back).unwrap().volume, 250.0 * pi) < 1e-6, "{}", measure(&back).unwrap().volume); +} + +/// A sector of a cylinder (radius 5, height 10) about z, `sweep` radians from `start` on the +/// wall's frame: a pie slice of the cylinder, its two sides through the axis. +fn cylinder_sector(start: f64, sweep: f64) -> String { + let (r, h) = (5.0, 10.0); + let p = |x: f64, y: f64, z: f64| format!("({x:.17},{y:.17},{z:.17})"); + let (a0, a1) = (start, start + sweep); + let (c0, s0, c1, s1) = (a0.cos(), a0.sin(), a1.cos(), a1.sin()); + let line = |id: u32, from: (f64, f64, f64), to: (f64, f64, f64)| { + let d = Vec3::new(to.0 - from.0, to.1 - from.1, to.2 - from.2); + let u = d.normalized().unwrap(); + format!( + "#{id}=LINE('',#{},#{});\n#{}=CARTESIAN_POINT('',{});\n#{}=VECTOR('',#{},{:.17});\n#{}=DIRECTION('',{});\n", + id + 1, + id + 2, + id + 1, + p(from.0, from.1, from.2), + id + 2, + id + 3, + d.len(), + id + 3, + p(u.x, u.y, u.z) + ) + }; + let (a_0, a_1, p0, p1, q0, q1) = + ((0.0, 0.0, 0.0), (0.0, 0.0, h), (r * c0, r * s0, 0.0), (r * c0, r * s0, h), (r * c1, r * s1, 0.0), (r * c1, r * s1, h)); + let mut lines = String::new(); + for (id, from, to) in [(100, a_0, a_1), (110, a_0, p0), (120, a_0, q0), (130, a_1, p1), (140, a_1, q1), (150, p0, p1), (160, q0, q1)] { + lines.push_str(&line(id, from, to)); + } + format!( + "{HEAD} +#1=CARTESIAN_POINT('',(0.,0.,0.)); +#2=DIRECTION('',(0.,0.,1.)); +#3=DIRECTION('',(1.,0.,0.)); +#4=DIRECTION('',(0.,0.,-1.)); +#5=AXIS2_PLACEMENT_3D('',#1,#2,#3); +#6=AXIS2_PLACEMENT_3D('',#1,#4,#3); +#7=CARTESIAN_POINT('',(0.,0.,{h:?})); +#8=AXIS2_PLACEMENT_3D('',#7,#2,#3); +#10=VERTEX_POINT('',#11); +#11=CARTESIAN_POINT('',{}); +#12=VERTEX_POINT('',#13); +#13=CARTESIAN_POINT('',{}); +#14=VERTEX_POINT('',#15); +#15=CARTESIAN_POINT('',{}); +#16=VERTEX_POINT('',#17); +#17=CARTESIAN_POINT('',{}); +#18=VERTEX_POINT('',#19); +#19=CARTESIAN_POINT('',{}); +#20=VERTEX_POINT('',#21); +#21=CARTESIAN_POINT('',{}); +{lines}#30=CIRCLE('',#5,{r:?}); +#31=CIRCLE('',#8,{r:?}); +#40=EDGE_CURVE('',#10,#12,#100,.T.); +#41=EDGE_CURVE('',#10,#14,#110,.T.); +#42=EDGE_CURVE('',#10,#18,#120,.T.); +#43=EDGE_CURVE('',#12,#16,#130,.T.); +#44=EDGE_CURVE('',#12,#20,#140,.T.); +#45=EDGE_CURVE('',#14,#16,#150,.T.); +#46=EDGE_CURVE('',#18,#20,#160,.T.); +#47=EDGE_CURVE('',#14,#18,#30,.T.); +#48=EDGE_CURVE('',#16,#20,#31,.T.); +#50=CYLINDRICAL_SURFACE('',#5,{r:?}); +#51=EDGE_LOOP('',(#200,#201,#202,#203)); +#200=ORIENTED_EDGE('',*,*,#47,.T.); +#201=ORIENTED_EDGE('',*,*,#46,.T.); +#202=ORIENTED_EDGE('',*,*,#48,.F.); +#203=ORIENTED_EDGE('',*,*,#45,.F.); +#52=FACE_OUTER_BOUND('',#51,.T.); +#53=ADVANCED_FACE('Wall',(#52),#50,.T.); +#54=PLANE('',#6); +#55=EDGE_LOOP('',(#204,#205,#206)); +#204=ORIENTED_EDGE('',*,*,#42,.T.); +#205=ORIENTED_EDGE('',*,*,#47,.F.); +#206=ORIENTED_EDGE('',*,*,#41,.F.); +#56=FACE_OUTER_BOUND('',#55,.T.); +#57=ADVANCED_FACE('Bottom',(#56),#54,.T.); +#58=PLANE('',#8); +#59=EDGE_LOOP('',(#207,#208,#209)); +#207=ORIENTED_EDGE('',*,*,#43,.T.); +#208=ORIENTED_EDGE('',*,*,#48,.T.); +#209=ORIENTED_EDGE('',*,*,#44,.F.); +#60=FACE_OUTER_BOUND('',#59,.T.); +#61=ADVANCED_FACE('Top',(#60),#58,.T.); +#62=DIRECTION('',{}); +#63=AXIS2_PLACEMENT_3D('',#1,#62,#2); +#64=PLANE('',#63); +#65=EDGE_LOOP('',(#210,#211,#212,#213)); +#210=ORIENTED_EDGE('',*,*,#41,.T.); +#211=ORIENTED_EDGE('',*,*,#45,.T.); +#212=ORIENTED_EDGE('',*,*,#43,.F.); +#213=ORIENTED_EDGE('',*,*,#40,.F.); +#66=FACE_OUTER_BOUND('',#65,.T.); +#67=ADVANCED_FACE('Start',(#66),#64,.T.); +#68=DIRECTION('',{}); +#69=AXIS2_PLACEMENT_3D('',#1,#68,#2); +#70=PLANE('',#69); +#71=EDGE_LOOP('',(#214,#215,#216,#217)); +#214=ORIENTED_EDGE('',*,*,#40,.T.); +#215=ORIENTED_EDGE('',*,*,#44,.T.); +#216=ORIENTED_EDGE('',*,*,#46,.F.); +#217=ORIENTED_EDGE('',*,*,#42,.F.); +#72=FACE_OUTER_BOUND('',#71,.T.); +#73=ADVANCED_FACE('End',(#72),#70,.T.); +#80=CLOSED_SHELL('',(#53,#57,#61,#67,#73)); +#81=MANIFOLD_SOLID_BREP('Sector',#80); +#82=SHAPE_REPRESENTATION('',(#81),$); +{TAIL}", + p(a_0.0, a_0.1, a_0.2), + p(a_1.0, a_1.1, a_1.2), + p(p0.0, p0.1, p0.2), + p(p1.0, p1.1, p1.2), + p(q0.0, q0.1, q0.2), + p(q1.0, q1.1, q1.2), + p(s0, -c0, 0.0), + p(-s1, c1, 0.0), + ) +} + +/// A round face of less than one turn that does not start on a quarter line of its frame (a +/// 300° sector of a cylinder from 75°, or 350° from 200°) needed a fifth quarter on the frame's quarter grid, so its +/// form ran past one turn and SMLib refused the solid (it came in as surfaces, an edge "12 mm off +/// the face's surface"). Its frame is turned about its axis to start on a quarter line: the same +/// cylinder, a form of four quarters, and the solid with its exact volume and area. One that fits +/// in four quarters as it is (300° from 37°) keeps its frame. +#[test] +fn a_round_face_off_its_frames_quarter_lines_is_formed_within_one_turn() { + for (start, sweep) in + [(75f64.to_radians(), 300f64.to_radians()), (37f64.to_radians(), 300f64.to_radians()), (200f64.to_radians(), 350f64.to_radians())] + { + let imp = step_import(&cylinder_sector(start, sweep)).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + let b = &imp.bodies[0]; + assert!(b.closed && b.refused.is_none(), "{start} {sweep}: {:?} {:?}", b.refused, imp.warnings); + let wall = b.face_origin.iter().position(|f| *f == 53).unwrap(); + let Some(solidcore_record::brep::Surface::RationalSpline { u_knots, .. }) = &b.body.record().faces[wall].nurbs else { + panic!("the wall's form") + }; + assert!(u_knots[u_knots.len() - 1] - u_knots[0] <= 4.0, "{start}: the wall's form spans {u_knots:?}"); + let m = measure(&b.body).unwrap(); + let (volume, area) = (0.5 * sweep * 25.0 * 10.0, sweep * 25.0 + sweep * 5.0 * 10.0 + 2.0 * 5.0 * 10.0); + assert!(rel(m.volume, volume) < 1e-6, "{start}: volume {} vs {volume}", m.volume); + assert!(rel(m.area, area) < 1e-6, "{start}: area {} vs {area}", m.area); + } +} + +/// A ball (radius 10, axis z) between the planes y = -6 and y = 6, its two halves z > 0 and +/// z < 0 meeting on the equator, neither with a seam: each gets one from the first vertex of its +/// loop to the pole it covers. The upper loop starts at (8, -6, 0), the lower at (8, 6, 0) +/// (`lower_first` 0) or (-8, -6, 0) (2): the seams are 73.7 degrees apart, so no one turn of +/// the frames the equator joins puts both on a quarter line. The lower half was left past one +/// turn of its form, its trim across the form's end crossed the face, and its mesh had 15.6 +/// times its area, folded over the ball (a torn ball in a rotor's STEP file). Each half is +/// turned on its own: forms of four quarters, and each half's mesh has its area. +#[test] +fn a_balls_halves_with_seams_off_each_others_quarter_lines_each_form_within_one_turn() { + let (r, c) = (10.0f64, 6.0f64); + let rr = (r * r - c * c).sqrt(); + let p = |x: f64, y: f64, z: f64| format!("({x:.17},{y:.17},{z:.17})"); + for lower_first in [0usize, 2] { + let lower = [ + "#60=ORIENTED_EDGE('',*,*,#40,.F.)", + "#61=ORIENTED_EDGE('',*,*,#45,.F.)", + "#62=ORIENTED_EDGE('',*,*,#41,.F.)", + "#63=ORIENTED_EDGE('',*,*,#43,.T.)", + ]; + let order: Vec<&str> = (0..4).map(|k| lower[(lower_first + k) % 4].split('=').next().unwrap_or("")).collect(); + let text = format!( + "{HEAD}#1=CARTESIAN_POINT('',(0.,0.,0.)); +#2=DIRECTION('',(0.,0.,1.)); +#3=DIRECTION('',(1.,0.,0.)); +#4=AXIS2_PLACEMENT_3D('',#1,#2,#3); +#5=SPHERICAL_SURFACE('',#4,{r:?}); +#10=CARTESIAN_POINT('',{}); +#11=CARTESIAN_POINT('',{}); +#12=CARTESIAN_POINT('',{}); +#13=CARTESIAN_POINT('',{}); +#14=VERTEX_POINT('',#10); +#15=VERTEX_POINT('',#11); +#16=VERTEX_POINT('',#12); +#17=VERTEX_POINT('',#13); +#20=DIRECTION('',(0.,-1.,0.)); +#21=CARTESIAN_POINT('',(0.,{c:?},0.)); +#22=AXIS2_PLACEMENT_3D('',#21,#20,#3); +#23=CARTESIAN_POINT('',(0.,{:?},0.)); +#24=AXIS2_PLACEMENT_3D('',#23,#20,#3); +#30=CIRCLE('',#4,{r:?}); +#31=CIRCLE('',#22,{rr:.17}); +#32=CIRCLE('',#24,{rr:.17}); +#40=EDGE_CURVE('',#14,#15,#30,.T.); +#41=EDGE_CURVE('',#16,#17,#30,.T.); +#42=EDGE_CURVE('',#15,#16,#31,.T.); +#43=EDGE_CURVE('',#16,#15,#31,.T.); +#44=EDGE_CURVE('',#14,#17,#32,.T.); +#45=EDGE_CURVE('',#17,#14,#32,.T.); +#50=ORIENTED_EDGE('',*,*,#40,.T.); +#51=ORIENTED_EDGE('',*,*,#42,.T.); +#52=ORIENTED_EDGE('',*,*,#41,.T.); +#53=ORIENTED_EDGE('',*,*,#44,.F.); +#54=EDGE_LOOP('',(#50,#51,#52,#53)); +#55=FACE_OUTER_BOUND('',#54,.T.); +#56=ADVANCED_FACE('Upper',(#55),#5,.T.); +{}; +{}; +{}; +{}; +#64=EDGE_LOOP('',({})); +#65=FACE_OUTER_BOUND('',#64,.T.); +#66=ADVANCED_FACE('Lower',(#65),#5,.T.); +#70=DIRECTION('',(0.,1.,0.)); +#71=AXIS2_PLACEMENT_3D('',#21,#70,#3); +#72=PLANE('',#71); +#73=ORIENTED_EDGE('',*,*,#43,.F.); +#74=ORIENTED_EDGE('',*,*,#42,.F.); +#75=EDGE_LOOP('',(#73,#74)); +#76=FACE_OUTER_BOUND('',#75,.T.); +#77=ADVANCED_FACE('Top',(#76),#72,.T.); +#79=PLANE('',#24); +#80=ORIENTED_EDGE('',*,*,#44,.T.); +#81=ORIENTED_EDGE('',*,*,#45,.T.); +#82=EDGE_LOOP('',(#80,#81)); +#83=FACE_OUTER_BOUND('',#82,.T.); +#84=ADVANCED_FACE('Bottom',(#83),#79,.T.); +#90=CLOSED_SHELL('',(#56,#66,#77,#84)); +#91=MANIFOLD_SOLID_BREP('Ball',#90); +#92=SHAPE_REPRESENTATION('',(#91),$); +{TAIL}", + p(rr, -c, 0.0), + p(rr, c, 0.0), + p(-rr, c, 0.0), + p(-rr, -c, 0.0), + -c, + lower[0], + lower[1], + lower[2], + lower[3], + order.join(","), + ); + let imp = step_import(&text).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + let b = &imp.bodies[0]; + assert!(b.closed && b.refused.is_none(), "{lower_first}: {:?} {:?}", b.refused, imp.warnings); + let pi = std::f64::consts::PI; + let m = measure(&b.body).unwrap(); + let (volume, area) = (pi * (r * r * 2.0 * c - 2.0 * c.powi(3) / 3.0), 4.0 * pi * r * c + 2.0 * pi * rr * rr); + // Measured on the sphere to 1e-5. + assert!(rel(m.volume, volume) < 1e-4, "{lower_first}: volume {} vs {volume}", m.volume); + assert!(rel(m.area, area) < 1e-4, "{lower_first}: area {} vs {area}", m.area); + let meshed = b.body.faces(0.005).unwrap(); + for half in [56, 66] { + let fi = b.face_origin.iter().position(|f| *f == half).unwrap(); + let Some(solidcore_record::brep::Surface::RationalSpline { u_knots, .. }) = &b.body.record().faces[fi].nurbs else { + panic!("the half's form") + }; + assert!(u_knots[u_knots.len() - 1] - u_knots[0] <= 4.0, "{lower_first}: face #{half}'s form spans {u_knots:?}"); + // Each half is a zone of the sphere 2c high, halved: pi r 2c. + let want = pi * r * 2.0 * c; + assert!(rel(meshed[fi].area, want) < 1e-2, "{lower_first}: face #{half}'s mesh has area {} of {want}", meshed[fi].area); + } + } +} + +/// A circle edge between two vertices its file's uncertainty does not tell apart is the short arc +/// between them, not a full turn (the engine assembly's water pump housing has a 20.4 um arc +/// between two vertices in a part whose uncertainty is 20.5 um). A can whose wall is +/// split by two rulings 0.6 um apart, under the default 1 um: read as turns, the sliver of wall +/// between them wound once round the can with no second bound and the can came in as surfaces. +#[test] +fn a_circle_edge_between_two_vertices_closer_than_the_tolerance_is_the_arc_between_them() { + let (r, h) = (5.0f64, 10.0f64); + let delta = 0.6e-3 / r; + let (c, s) = (r * delta.cos(), r * delta.sin()); + let text = format!( + "{HEAD} +#1=CARTESIAN_POINT('',(0.,0.,0.)); +#2=DIRECTION('',(0.,0.,1.)); +#3=DIRECTION('',(1.,0.,0.)); +#5=AXIS2_PLACEMENT_3D('',#1,#2,#3); +#6=CARTESIAN_POINT('',(0.,0.,{h:?})); +#7=AXIS2_PLACEMENT_3D('',#6,#2,#3); +#10=CARTESIAN_POINT('',({r:?},0.,0.)); +#11=CARTESIAN_POINT('',({c:?},{s:?},0.)); +#12=CARTESIAN_POINT('',({r:?},0.,{h:?})); +#13=CARTESIAN_POINT('',({c:?},{s:?},{h:?})); +#14=VERTEX_POINT('',#10); +#15=VERTEX_POINT('',#11); +#16=VERTEX_POINT('',#12); +#17=VERTEX_POINT('',#13); +#20=CIRCLE('',#5,{r:?}); +#21=CIRCLE('',#7,{r:?}); +#22=VECTOR('',#2,1.); +#23=LINE('',#10,#22); +#24=LINE('',#11,#22); +#30=EDGE_CURVE('',#14,#15,#20,.T.); +#31=EDGE_CURVE('',#15,#14,#20,.T.); +#32=EDGE_CURVE('',#16,#17,#21,.T.); +#33=EDGE_CURVE('',#17,#16,#21,.T.); +#34=EDGE_CURVE('',#14,#16,#23,.T.); +#35=EDGE_CURVE('',#15,#17,#24,.T.); +#40=ORIENTED_EDGE('',*,*,#31,.F.); +#41=ORIENTED_EDGE('',*,*,#30,.F.); +#42=EDGE_LOOP('',(#40,#41)); +#43=FACE_OUTER_BOUND('',#42,.T.); +#44=PLANE('',#5); +#45=ADVANCED_FACE('Bottom',(#43),#44,.F.); +#50=ORIENTED_EDGE('',*,*,#32,.T.); +#51=ORIENTED_EDGE('',*,*,#33,.T.); +#52=EDGE_LOOP('',(#50,#51)); +#53=FACE_OUTER_BOUND('',#52,.T.); +#54=PLANE('',#7); +#55=ADVANCED_FACE('Top',(#53),#54,.T.); +#60=ORIENTED_EDGE('',*,*,#30,.T.); +#61=ORIENTED_EDGE('',*,*,#35,.T.); +#62=ORIENTED_EDGE('',*,*,#32,.F.); +#63=ORIENTED_EDGE('',*,*,#34,.F.); +#64=EDGE_LOOP('',(#60,#61,#62,#63)); +#65=FACE_OUTER_BOUND('',#64,.T.); +#66=CYLINDRICAL_SURFACE('',#5,{r:?}); +#67=ADVANCED_FACE('Sliver',(#65),#66,.T.); +#70=ORIENTED_EDGE('',*,*,#31,.T.); +#71=ORIENTED_EDGE('',*,*,#34,.T.); +#72=ORIENTED_EDGE('',*,*,#33,.F.); +#73=ORIENTED_EDGE('',*,*,#35,.F.); +#74=EDGE_LOOP('',(#70,#71,#72,#73)); +#75=FACE_OUTER_BOUND('',#74,.T.); +#77=ADVANCED_FACE('Wall',(#75),#66,.T.); +#80=CLOSED_SHELL('',(#45,#55,#67,#77)); +#81=MANIFOLD_SOLID_BREP('Can',#80); +#82=SHAPE_REPRESENTATION('',(#81),$); +{TAIL}" + ); + let imp = step_import(&text).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + let can = &imp.bodies[0]; + assert!(can.closed && can.refused.is_none() && !can.body.is_surface(), "{:?} {:?}", can.refused, imp.warnings); + let pi = std::f64::consts::PI; + let m = measure(&can.body).unwrap(); + assert!(rel(m.volume, pi * r * r * h) < 1e-6, "{}", m.volume); + assert!(rel(m.area, 2.0 * pi * r * r + 2.0 * pi * r * h) < 1e-6, "{}", m.area); +} + +/// A ring torus (R 10, r 3) about z, as a closed solid: with `tube` its whole turn about the axis +/// and its tube from `tube.0` for `tube.1` radians, the gap across the tube closed by a cone +/// through the two circles where the tube ends (face #53, its seam a tube arc, the cone #57); +/// without it the whole tube for `sweep` radians from `start` about the axis, closed by two discs +/// (its seam an arc of the outer equator). +fn torus_part(tube: Option<(f64, f64)>, (start, sweep): (f64, f64)) -> String { + let (big, small) = (10.0, 3.0); + let p = |x: f64, y: f64, z: f64| format!("({x:.17},{y:.17},{z:.17})"); + let head = format!( + "{HEAD}#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#50=TOROIDAL_SURFACE('',#4,{big:?},{small:?});\n" + ); + let tail = "#80=CLOSED_SHELL('',(#53,#57,#61));\n#81=MANIFOLD_SOLID_BREP('Torus part',#80);\n#82=SHAPE_REPRESENTATION('',(#81),$);\n"; + if let Some((v0, dv)) = tube { + // The circles about the axis at the tube's two ends, and the cone through them from the + // narrower one, its axis toward the wider; its sense outward from the tube. + let v1 = v0 + dv; + let ring = |v: f64| (big + small * v.cos(), small * v.sin()); + let ((ra, za), (rb, zb)) = (ring(v0), ring(v1)); + let ((r_near, z_near), (r_far, z_far)) = if ra < rb { ((ra, za), (rb, zb)) } else { ((rb, zb), (ra, za)) }; + let k = (z_far - z_near).signum(); + let semi = ((r_far - r_near) / (z_far - z_near).abs()).atan(); + // The cone's natural normal at u = 0, (1, 0, −k tan) in (radial, axial), against the way + // out of the tube at the chord's middle. + let (mx, mz) = (0.5 * (ra + rb) - big, 0.5 * (za + zb)); + let sense = if mx - k * semi.tan() * mz > 0.0 { "T" } else { "F" }; + format!( + "{head}#5=DIRECTION('',(0.,0.,{k:.1})); +#6=CARTESIAN_POINT('',{}); +#7=AXIS2_PLACEMENT_3D('',#6,#2,#3); +#8=CARTESIAN_POINT('',{}); +#9=AXIS2_PLACEMENT_3D('',#8,#2,#3); +#10=VERTEX_POINT('',#11); +#11=CARTESIAN_POINT('',{}); +#12=VERTEX_POINT('',#13); +#13=CARTESIAN_POINT('',{}); +#30=CIRCLE('',#7,{ra:.17}); +#31=CIRCLE('',#9,{rb:.17}); +#40=EDGE_CURVE('',#10,#10,#30,.T.); +#41=EDGE_CURVE('',#12,#12,#31,.T.); +#14=CARTESIAN_POINT('',({big:?},0.,0.)); +#15=DIRECTION('',(0.,-1.,0.)); +#16=AXIS2_PLACEMENT_3D('',#14,#15,#3); +#32=CIRCLE('',#16,{small:?}); +#42=EDGE_CURVE('',#10,#12,#32,.T.); +#200=ORIENTED_EDGE('',*,*,#40,.T.); +#201=ORIENTED_EDGE('',*,*,#41,.F.); +#204=ORIENTED_EDGE('',*,*,#42,.T.); +#205=ORIENTED_EDGE('',*,*,#42,.F.); +#51=EDGE_LOOP('',(#200,#204,#201,#205)); +#54=FACE_OUTER_BOUND('',#51,.T.); +#53=ADVANCED_FACE('Tube',(#54),#50,.T.); +#202=ORIENTED_EDGE('',*,*,#40,.F.); +#203=ORIENTED_EDGE('',*,*,#41,.T.); +#56=EDGE_LOOP('',(#202)); +#58=EDGE_LOOP('',(#203)); +#59=FACE_OUTER_BOUND('',#56,.T.); +#60=FACE_BOUND('',#58,.T.); +#62=CARTESIAN_POINT('',{}); +#63=AXIS2_PLACEMENT_3D('',#62,#5,#3); +#64=CONICAL_SURFACE('',#63,{r_near:.17},{semi:.17}); +#57=ADVANCED_FACE('Gap',(#59,#60),#64,.{sense}.); +#80=CLOSED_SHELL('',(#53,#57)); +#81=MANIFOLD_SOLID_BREP('Torus part',#80); +#82=SHAPE_REPRESENTATION('',(#81),$); +{TAIL}", + p(0.0, 0.0, za), + p(0.0, 0.0, zb), + p(ra, 0.0, za), + p(rb, 0.0, zb), + p(0.0, 0.0, z_near), + ) + } else { + // A tube circle in each end's meridian plane, run with the tube angle, and the discs. + let end = |u: f64| { + let (c, s) = (u.cos(), u.sin()); + ((big * c, big * s), (c, s), (s, -c)) + }; + let (((x0, y0), (c0, s0), (a0x, a0y)), ((x1, y1), (c1, s1), (a1x, a1y))) = (end(start), end(start + sweep)); + format!( + "{head}#6=CARTESIAN_POINT('',{}); +#7=DIRECTION('',{}); +#8=DIRECTION('',{}); +#9=AXIS2_PLACEMENT_3D('',#6,#7,#8); +#14=CARTESIAN_POINT('',{}); +#15=DIRECTION('',{}); +#16=DIRECTION('',{}); +#17=AXIS2_PLACEMENT_3D('',#14,#15,#16); +#10=VERTEX_POINT('',#11); +#11=CARTESIAN_POINT('',{}); +#12=VERTEX_POINT('',#13); +#13=CARTESIAN_POINT('',{}); +#30=CIRCLE('',#9,{small:?}); +#31=CIRCLE('',#17,{small:?}); +#40=EDGE_CURVE('',#10,#10,#30,.T.); +#41=EDGE_CURVE('',#12,#12,#31,.T.); +#32=CIRCLE('',#4,{:.17}); +#43=EDGE_CURVE('',#10,#12,#32,.T.); +#200=ORIENTED_EDGE('',*,*,#40,.F.); +#201=ORIENTED_EDGE('',*,*,#41,.T.); +#204=ORIENTED_EDGE('',*,*,#43,.T.); +#205=ORIENTED_EDGE('',*,*,#43,.F.); +#51=EDGE_LOOP('',(#204,#201,#205,#200)); +#54=FACE_OUTER_BOUND('',#51,.T.); +#53=ADVANCED_FACE('Tube',(#54),#50,.T.); +#202=ORIENTED_EDGE('',*,*,#40,.T.); +#56=EDGE_LOOP('',(#202)); +#59=FACE_OUTER_BOUND('',#56,.T.); +#64=PLANE('',#9); +#57=ADVANCED_FACE('Start',(#59),#64,.T.); +#203=ORIENTED_EDGE('',*,*,#41,.F.); +#58=EDGE_LOOP('',(#203)); +#60=FACE_OUTER_BOUND('',#58,.T.); +#65=DIRECTION('',{}); +#66=AXIS2_PLACEMENT_3D('',#14,#65,#16); +#67=PLANE('',#66); +#61=ADVANCED_FACE('End',(#60),#67,.T.); +{tail}{TAIL}", + p(x0, y0, 0.0), + p(a0x, a0y, 0.0), + p(c0, s0, 0.0), + p(x1, y1, 0.0), + p(a1x, a1y, 0.0), + p(c1, s1, 0.0), + p(x0 + small * c0, y0 + small * s0, 0.0), + p(x1 + small * c1, y1 + small * s1, 0.0), + big + small, + p(-a1x, -a1y, 0.0), + ) + } +} + +/// A torus face round most of its tube off the tube's quarter lines (326° of the tube from +/// −113.8°, as an exhaust collector has it) needed a fifth quarter along the tube: its form ran +/// past a full turn of the tube and SMLib refused the solid. Its tube start moves to where the +/// face's tube begins: the same torus, a form of four quarters along the tube, and the solid with +/// its exact volume and area. A face round the whole tube (300° about the axis from 75°, which +/// turns its frame instead) keeps its tube start and its four quarters. +#[test] +fn a_torus_face_round_most_of_its_tube_is_formed_within_one_turn_of_it() { + use std::f64::consts::PI; + let (big, small) = (10.0f64, 3.0f64); + let (v0, dv) = ((-113.8f64).to_radians(), 326f64.to_radians()); + for (tube, about) in [(Some((v0, dv)), (0.0, 2.0 * PI)), (None, (75f64.to_radians(), 300f64.to_radians()))] { + let imp = step_import(&torus_part(tube, about)).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + let b = &imp.bodies[0]; + assert!(b.closed && b.refused.is_none(), "{tube:?}: {:?} {:?}", b.refused, imp.warnings); + let face = b.face_origin.iter().position(|f| *f == 53).unwrap(); + let record = b.body.record(); + let Some(solidcore_record::brep::Surface::RationalSpline { v_knots, .. }) = &record.faces[face].nurbs else { panic!("the tube's form") }; + assert!(v_knots[v_knots.len() - 1] - v_knots[0] <= 4.0, "{tube:?}: the tube's form spans {v_knots:?}"); + let m = measure(&b.body).unwrap(); + let (volume, area) = match tube { + Some((v0, dv)) => { + // The whole torus less the segment of the tube the cone cuts off, revolved + // (Pappus); the tube's face and the cone's. + let gap = 2.0 * PI - dv; + let segment = 0.5 * small * small * (gap - gap.sin()); + let centroid = 4.0 * small * (0.5 * gap).sin().powi(3) / (3.0 * (gap - gap.sin())); + let middle = v0 + dv + 0.5 * gap; + let volume = 2.0 * PI * PI * big * small * small - segment * 2.0 * PI * (big + centroid * middle.cos()); + let ring = |v: f64| big + small * v.cos(); + let chord = 2.0 * small * (0.5 * gap).sin(); + let area = 2.0 * PI * small * (big * dv + small * ((v0 + dv).sin() - v0.sin())) + PI * (ring(v0) + ring(v0 + dv)) * chord; + (volume, area) + } + None => { + assert_eq!(v_knots[v_knots.len() - 1] - v_knots[0], 4.0, "a whole tube is four quarters"); + let sweep = about.1; + (PI * small * small * big * sweep, sweep * 2.0 * PI * small * big + 2.0 * PI * small * small) + } + }; + assert!(rel(m.volume, volume) < 1e-6, "{tube:?}: volume {} vs {volume}", m.volume); + assert!(rel(m.area, area) < 1e-6, "{tube:?}: area {} vs {area}", m.area); + } } diff --git a/crates/kernel/src/step_out.rs b/crates/kernel/src/step_out.rs index ce1851ce8..55f61abc4 100644 --- a/crates/kernel/src/step_out.rs +++ b/crates/kernel/src/step_out.rs @@ -1,20 +1,19 @@ //! STEP (ISO 10303-21) export: AP242 product structure, assemblies, names and colours. //! -//! Each body's B-rep is written by truck's STEP writer (geometry and topology only), read back -//! with our Part 21 parser and copied into a file we assemble ourselves: one header and -//! context, a product per part with its shape representation, named solids, surface colours, -//! and assemblies as next-assembly-usage occurrences placed by item-defined transformations -//! (the structure the CAx-IF recommends and our reader follows). Identical geometric entities -//! (points, directions, placements, curves, surfaces) are written once and referenced; ids are -//! dense from `#1`. +//! Each body's record is written as it is, the exact B-rep, by +//! [`solidcraft_step::write::topology`]: its material regions as solids, its open shells as a +//! surface model. Around it this writes one header and context, a product per part with its +//! shape representation, named solids, surface and face colours, and assemblies as +//! next-assembly-usage occurrences placed by item-defined transformations (the structure the +//! CAx-IF recommends and our reader follows). Identical geometric entities (points, directions, +//! placements, curves, surfaces) are written once and referenced; ids are dense from `#1`. -use std::collections::HashMap; use std::fmt::Write as _; -use solidcraft_geom::Vec3; +use solidcraft_step::p21::Param; +use solidcraft_step::write::{GeomWriter, Writer, string, topology}; use crate::body::Body; -use crate::step_in::p21::{self, Param}; use crate::{KernelError, Result}; /// A named, optionally coloured body to export (coordinates in its part's frame, mm). @@ -45,1547 +44,20 @@ pub struct StepHeader { pub description: String, } -/// Entities whose identity is topological: never merged even when their text is equal. -const TOPOLOGY: &[&str] = &[ - "VERTEX_POINT", - "EDGE_CURVE", - "ORIENTED_EDGE", - "EDGE_LOOP", - "FACE_BOUND", - "FACE_OUTER_BOUND", - "FACE_SURFACE", - "ADVANCED_FACE", - "ORIENTED_FACE", - "CLOSED_SHELL", - "OPEN_SHELL", - "ORIENTED_CLOSED_SHELL", - "MANIFOLD_SOLID_BREP", - "BREP_WITH_VOIDS", -]; +/// The least distance uncertainty written (mm). +const MIN_UNCERTAINTY: f64 = 1e-6; -fn real(x: f64) -> String { - if !x.is_finite() { - return "0.".into(); - } - let s = format!("{x:?}"); - match s.split_once('e') { - Some((m, e)) => { - let m = if m.contains('.') { m.to_string() } else { format!("{m}.") }; - format!("{m}E{e}") - } - None if s.contains('.') => s, - None => format!("{s}."), - } +fn s(text: &str) -> Param { + Param::Str(text.to_string()) +} +fn r(id: u64) -> Param { + Param::Ref(id) +} +fn refs(ids: &[u64]) -> Param { + Param::List(ids.iter().map(|i| r(*i)).collect()) } -/// A STEP string literal (quotes doubled, non-ASCII as `\X2\` UTF-16 runs). -fn string(s: &str) -> String { - let mut o = String::from("'"); - for c in s.chars() { - match c { - '\'' => o.push_str("''"), - '\\' => o.push_str("\\\\"), - c if c.is_ascii() && !c.is_ascii_control() => o.push(c), - c if c.is_ascii_control() => {} - c => { - o.push_str("\\X2\\"); - let mut buf = [0u16; 2]; - for u in c.encode_utf16(&mut buf) { - let _ = write!(o, "{u:04X}"); - } - o.push_str("\\X0\\"); - } - } - } - o.push('\''); - o -} - -fn param(p: &Param, map: &HashMap, o: &mut String) -> std::result::Result<(), String> { - match p { - Param::Int(i) => { - let _ = write!(o, "{i}"); - } - Param::Real(x) => o.push_str(&real(*x)), - Param::Str(s) => o.push_str(&string(s)), - Param::Enum(e) => { - let _ = write!(o, ".{e}."); - } - Param::Ref(r) => { - let n = map.get(r).ok_or_else(|| format!("dangling reference #{r}"))?; - let _ = write!(o, "#{n}"); - } - Param::List(v) => { - o.push('('); - params(v, map, o)?; - o.push(')'); - } - Param::Typed(name, v) => { - o.push_str(name); - o.push('('); - params(v, map, o)?; - o.push(')'); - } - Param::Binary(b) => { - let _ = write!(o, "\"{b}\""); - } - Param::Null => o.push('$'), - Param::Derived => o.push('*'), - } - Ok(()) -} - -fn params(v: &[Param], map: &HashMap, o: &mut String) -> std::result::Result<(), String> { - for (i, p) in v.iter().enumerate() { - if i > 0 { - o.push(','); - } - param(p, map, o)?; - } - Ok(()) -} - -/// The DATA section under construction. -#[derive(Default)] -struct Out { - lines: Vec, - /// Geometry text → id (shared entities). - shared: HashMap, - /// Surfaces written with the opposite normal to the one they replace. - flipped: std::collections::HashSet, - /// B-spline cylinder and cone sheets of the body being copied to write as analytic surfaces, - /// with the direction of their parameter seam. - merged: HashMap, - /// B-spline sheets of the body being copied to write cut down to their faces. - trimmed: HashMap, - /// Faces of the body being copied: exchange id → written id. - faces_out: HashMap, -} - -impl Out { - fn add(&mut self, text: impl Into) -> u64 { - self.lines.push(text.into()); - self.lines.len() as u64 - } - /// Add, or reuse an identical earlier entity (geometry only). - fn add_shared(&mut self, text: String) -> u64 { - if let Some(id) = self.shared.get(&text) { - return *id; - } - let id = self.add(text.clone()); - self.shared.insert(text, id); - id - } - fn point(&mut self, p: [f64; 3]) -> u64 { - self.add_shared(format!("CARTESIAN_POINT('',({},{},{}))", real(p[0]), real(p[1]), real(p[2]))) - } - fn direction(&mut self, d: [f64; 3]) -> u64 { - self.add_shared(format!("DIRECTION('',({},{},{}))", real(d[0]), real(d[1]), real(d[2]))) - } - fn write_analytic(&mut self, a: &Analytic) -> u64 { - match a.kind { - AnalyticKind::Plane { o, z, x } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("PLANE('',#{ax})")) - } - AnalyticKind::Cylinder { o, z, x, r } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("CYLINDRICAL_SURFACE('',#{ax},{})", real(r))) - } - AnalyticKind::Cone { o, z, x, r, angle } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("CONICAL_SURFACE('',#{ax},{},{})", real(r), real(angle))) - } - AnalyticKind::Sphere { o, z, x, r } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("SPHERICAL_SURFACE('',#{ax},{})", real(r))) - } - AnalyticKind::Torus { o, z, x, big, small } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("TOROIDAL_SURFACE('',#{ax},{},{})", real(big), real(small))) - } - AnalyticKind::HornTorus { o, z, x, big, small } => { - // Nine-point rational quadratic circles (quarter arcs, corner weights √½): the - // tube from the pole round and back, and the turn about z from x. - let y = cross(z, x); - let ring = |k: usize| { - let ang = std::f64::consts::FRAC_PI_4 * k as f64; - let (scale, w) = if k % 2 == 1 { (std::f64::consts::SQRT_2, std::f64::consts::FRAC_1_SQRT_2) } else { (1.0, 1.0) }; - (ang.cos() * scale, ang.sin() * scale, w) - }; - let (mut rows, mut weights) = (Vec::new(), Vec::new()); - for i in 0..9 { - let (ci, si, wi) = ring(i); - let (rho, h) = (big - small * ci, small * si); - let (mut row, mut wrow) = (Vec::new(), Vec::new()); - for j in 0..9 { - let (cj, sj, wj) = ring(j); - let pt = add(add(o, mul(z, h)), add(mul(x, rho * cj), mul(y, rho * sj))); - row.push(format!("#{}", self.point(pt))); - wrow.push(real(wi * wj)); - } - rows.push(format!("({})", row.join(","))); - weights.push(format!("({})", wrow.join(","))); - } - self.add_shared(format!( - "(BOUNDED_SURFACE()B_SPLINE_SURFACE(2,2,({}),.UNSPECIFIED.,.T.,.T.,.F.)B_SPLINE_SURFACE_WITH_KNOTS((3,2,2,2,3),(3,2,2,2,3),(0.,0.25,0.5,0.75,1.),(0.,0.25,0.5,0.75,1.),.UNSPECIFIED.)GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE(({}))REPRESENTATION_ITEM('')SURFACE())", - rows.join(","), - weights.join(",") - )) - } - } - } - /// A B-spline (or NURBS) surface; `None` for other surfaces. - fn write_sheet(&mut self, s: &truck_modeling::Surface) -> Option { - use truck_modeling::Surface; - let (rows, weights, (ku, kv), (du, dv)): (Vec>, Option>>, _, _) = match s { - Surface::BSplineSurface(b) => ( - b.control_points().iter().map(|r| r.iter().map(|p| [p.x, p.y, p.z]).collect()).collect(), - None, - b.knot_vecs().clone(), - (b.udegree(), b.vdegree()), - ), - Surface::NurbsSurface(n) => { - let b = n.non_rationalized(); - let rows: Option>> = b - .control_points() - .iter() - .map(|r| r.iter().map(|p| (p.w.abs() > 1e-300).then(|| [p.x / p.w, p.y / p.w, p.z / p.w])).collect()) - .collect(); - ( - rows?, - Some(b.control_points().iter().map(|r| r.iter().map(|p| p.w).collect()).collect()), - b.knot_vecs().clone(), - (b.udegree(), b.vdegree()), - ) - } - _ => return None, - }; - let net = rows - .iter() - .map(|r| format!("({})", r.iter().map(|p| format!("#{}", self.point(*p))).collect::>().join(","))) - .collect::>() - .join(","); - let list = |v: Vec| v.join(","); - let ((ku, mu), (kv, mv)) = (ku.to_single_multi(), kv.to_single_multi()); - let knots = format!( - "({}),({}),({}),({}),.UNSPECIFIED.", - list(mu.iter().map(|m| m.to_string()).collect()), - list(mv.iter().map(|m| m.to_string()).collect()), - list(ku.iter().map(|k| real(*k)).collect()), - list(kv.iter().map(|k| real(*k)).collect()), - ); - let base = format!("{du},{dv},({net}),.UNSPECIFIED.,.U.,.U.,.U."); - Some(match weights { - None => self.add_shared(format!("B_SPLINE_SURFACE_WITH_KNOTS('',{base},{knots})")), - Some(w) => { - let w = w.iter().map(|r| format!("({})", list(r.iter().map(|x| real(*x)).collect()))).collect::>().join(","); - self.add_shared(format!( - "(BOUNDED_SURFACE()B_SPLINE_SURFACE({base})B_SPLINE_SURFACE_WITH_KNOTS({knots})GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE(({w}))REPRESENTATION_ITEM('')SURFACE())" - )) - } - }) - } - fn placement(&mut self, o: [f64; 3], z: [f64; 3], x: [f64; 3]) -> u64 { - let (po, dz, dx) = (self.point(o), self.direction(z), self.direction(x)); - self.add_shared(format!("AXIS2_PLACEMENT_3D('',#{po},#{dz},#{dx})")) - } - - /// Copy a solid entity of a parsed file and everything it uses; returns its new id. - fn copy_solid(&mut self, ex: &p21::Exchange, root: u64, name: &str) -> std::result::Result { - let mut map: HashMap = HashMap::new(); - let seams = horn_seams(ex); - // Iterative post-order walk (children before parents). - let mut stack: Vec<(u64, bool)> = vec![(root, false)]; - let mut guard = 0usize; - while let Some((id, done)) = stack.pop() { - guard += 1; - if guard > 50_000_000 { - return Err("solid too large".into()); - } - if map.contains_key(&id) { - continue; - } - let e = ex.get(id).ok_or_else(|| format!("missing #{id}"))?; - // Revolutions with analytic profiles become cylinders, cones, spheres, tori and - // planes (what other systems recognise), with the face sense corrected. - if !done - && e.name() == "SURFACE_OF_REVOLUTION" - && let Some(mut a) = analytic_revolution(ex, e) - { - if let AnalyticKind::HornTorus { x, .. } = &mut a.kind - && let Some(s) = seams.get(&id) - { - *x = *s; - } - let new = self.write_analytic(&a); - if a.flip { - self.flipped.insert(new); - } - map.insert(id, new); - continue; - } - // Flat B-spline sheets are planes; ruled ones become cylinders and cones when - // `analytic_sheets` chose them (their pieces merged, or a lone piece's edges allow). - if !done - && let Some(a) = planar_bspline(ex, e).map(|kind| Analytic { kind, flip: false }).or_else(|| { - let seam = self.merged.get(&id)?; - let mut a = ruled_bspline(ex, e)?; - if let AnalyticKind::Cylinder { x, .. } | AnalyticKind::Cone { x, .. } = &mut a.kind { - *x = *seam; - } - Some(a) - }) - { - let new = self.write_analytic(&a); - if a.flip { - self.flipped.insert(new); - } - map.insert(id, new); - continue; - } - if !done && let Some(sheet) = self.trimmed.get(&id).cloned() { - let new = self.write_sheet(&sheet).ok_or_else(|| format!("cannot write the cut sheet #{id}"))?; - map.insert(id, new); - continue; - } - if !done { - stack.push((id, true)); - let mut refs = Vec::new(); - fn collect(p: &Param, out: &mut Vec) { - match p { - Param::Ref(r) => out.push(*r), - Param::List(v) | Param::Typed(_, v) => v.iter().for_each(|x| collect(x, out)), - _ => {} - } - } - e.records.iter().flat_map(|r| &r.params).for_each(|p| collect(p, &mut refs)); - stack.extend(refs.into_iter().filter(|r| !map.contains_key(r)).map(|r| (r, false))); - continue; - } - let mut text = String::new(); - let is_root = id == root; - if e.is_complex() { - text.push('('); - for r in &e.records { - text.push_str(&r.name); - text.push('('); - params(&r.params, &map, &mut text)?; - text.push(')'); - } - text.push(')'); - } else { - // Advanced breps use advanced faces (same attributes as truck's face surfaces). - let ename = if e.name() == "FACE_SURFACE" { "ADVANCED_FACE" } else { e.name() }; - text.push_str(ename); - text.push('('); - let mut ps = e.params().to_vec(); - if is_root && let Some(first) = ps.first_mut() { - *first = Param::Str(name.to_string()); - } - // A face on a surface written with the opposite normal flips its sense. - if ename == "ADVANCED_FACE" - && ps.get(2).and_then(Param::as_ref_id).and_then(|g| map.get(&g)).is_some_and(|g| self.flipped.contains(g)) - && let Some(Param::Enum(sense)) = ps.get_mut(3) - { - *sense = if sense == "T" { "F".into() } else { "T".into() }; - } - params(&ps, &map, &mut text)?; - text.push(')'); - } - let topo = TOPOLOGY.contains(&e.name()); - let new = if topo { self.add(text) } else { self.add_shared(text) }; - map.insert(id, new); - if matches!(e.name(), "FACE_SURFACE" | "ADVANCED_FACE") { - self.faces_out.insert(id, new); - } - } - map.get(&root).copied().ok_or_else(|| "solid not copied".into()) - } -} - -/// An analytic surface found behind a surface of revolution. -#[derive(Clone, Copy)] -struct Analytic { - kind: AnalyticKind, - /// The analytic surface's normal is opposite to the revolution's (ISO 10303-42 normals). - flip: bool, -} - -#[derive(Clone, Copy)] -enum AnalyticKind { - Plane { - o: V3, - z: V3, - x: V3, - }, - Cylinder { - o: V3, - z: V3, - x: V3, - r: f64, - }, - Cone { - o: V3, - z: V3, - x: V3, - r: f64, - angle: f64, - }, - Sphere { - o: V3, - z: V3, - x: V3, - r: f64, - }, - Torus { - o: V3, - z: V3, - x: V3, - big: f64, - small: f64, - }, - /// A torus whose tube reaches its axis (a horn torus, as a tight sweep makes): no valid - /// TOROIDAL_SURFACE, so a rational B-spline (tube angle from the pole at the axis, then the - /// turn from x), as other systems write it. x is the turn's parameter seam. - HornTorus { - o: V3, - z: V3, - x: V3, - big: f64, - small: f64, - }, -} - -type V3 = [f64; 3]; - -fn sub(a: V3, b: V3) -> V3 { - [a[0] - b[0], a[1] - b[1], a[2] - b[2]] -} -fn add(a: V3, b: V3) -> V3 { - [a[0] + b[0], a[1] + b[1], a[2] + b[2]] -} -fn mul(a: V3, k: f64) -> V3 { - [a[0] * k, a[1] * k, a[2] * k] -} -fn dot(a: V3, b: V3) -> f64 { - a[0] * b[0] + a[1] * b[1] + a[2] * b[2] -} -fn cross(a: V3, b: V3) -> V3 { - [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] -} -fn norm(a: V3) -> f64 { - dot(a, a).sqrt() -} -fn unit(a: V3) -> Option { - let n = norm(a); - (n > 1e-12 && n.is_finite()).then(|| mul(a, 1.0 / n)) -} - -/// Circle through three points: centre, radius, unit normal. -fn circle3(a: V3, b: V3, c: V3) -> Option<(V3, f64, V3)> { - let (ab, ac) = (sub(b, a), sub(c, a)); - let n = cross(ab, ac); - let n2 = dot(n, n); - if !(n2 > 1e-24) { - return None; - } - let t = add(mul(cross(n, ab), dot(ac, ac)), mul(cross(ac, n), dot(ab, ab))); - let center = add(a, mul(t, 0.5 / n2)); - Some((center, norm(sub(a, center)), unit(n)?)) -} - -/// The analytic surface a surface of revolution is, if its profile is a line or a circular arc -/// in a plane through the axis. -fn analytic_revolution(ex: &p21::Exchange, e: &p21::Entity) -> Option { - use crate::step_in::geom::{self, CurveGeo}; - use truck_modeling::{BoundedCurve, ParametricCurve}; - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let p = e.params(); - let (ao, ad) = geom::axis1(&cx, p.get(2)?.as_ref_id()?).ok()?; - let (oa, a) = ([ao.x, ao.y, ao.z], [ad.x, ad.y, ad.z]); - let g = geom::curve(&cx, p.get(1)?.as_ref_id()?, 0).ok()?; - let radial = |q: V3| { - let v = sub(q, oa); - sub(v, mul(a, dot(v, a))) - }; - let on_axis = |q: V3| add(oa, mul(a, dot(sub(q, oa), a))); - // Profile samples and tangents. - let eval: Box V3> = match &g { - CurveGeo::Line { p, d } => { - let (p, d) = ([p.x, p.y, p.z], [d.x, d.y, d.z]); - Box::new(move |t| add(p, mul(d, t))) - } - CurveGeo::BSpline(c) => { - let c = c.clone(); - let (t0, t1) = c.range_tuple(); - Box::new(move |s| { - let q = c.subs(t0 + (t1 - t0) * s); - [q.x, q.y, q.z] - }) - } - CurveGeo::Nurbs(c) => { - let c = c.clone(); - let (t0, t1) = c.range_tuple(); - Box::new(move |s| { - let q = c.subs(t0 + (t1 - t0) * s); - [q.x, q.y, q.z] - }) - } - CurveGeo::Conic { .. } | CurveGeo::Hyperbola { .. } | CurveGeo::Parabola { .. } => return None, - }; - // A sample point off the axis, its revolution normal (∂S/∂angle × ∂S/∂profile). - let sample = - [0.37, 0.61, 0.23, 0.79].into_iter().map(|t| (eval(t), sub(eval(t + 1e-4), eval(t - 1e-4)))).find(|(q, _)| norm(radial(*q)) > 1e-6)?; - let (q, dq) = sample; - let n_rev = cross(cross(a, sub(q, oa)), dq); - let eq = unit(radial(q))?; - let (kind, n_an) = match &g { - CurveGeo::Line { d, .. } => { - let d = unit([d.x, d.y, d.z])?; - // Coplanar with the axis? - if dot(cross(d, a), eq).abs() > 1e-9 { - return None; - } - let (da, dr) = (dot(d, a), dot(d, eq)); - if dr.abs() < 1e-12 { - let r = norm(radial(q)); - (AnalyticKind::Cylinder { o: oa, z: a, x: eq, r }, eq) - } else if da.abs() < 1e-12 { - (AnalyticKind::Plane { o: on_axis(q), z: a, x: eq }, a) - } else { - // Open the cone along +z: the radius grows that way. - let z = if dr * da > 0.0 { a } else { mul(a, -1.0) }; - let angle = (dr.abs() / da.abs()).atan(); - let r = norm(radial(q)); - let n = sub(mul(eq, angle.cos()), mul(z, angle.sin())); - (AnalyticKind::Cone { o: on_axis(q), z, x: eq, r, angle }, n) - } - } - _ => { - let (c, r, nc) = circle3(eval(0.0), eval(0.5), eval(1.0))?; - // Every sample on the circle, the circle's plane through the axis. - if (0..=8).any(|i| (norm(sub(eval(i as f64 / 8.0), c)) - r).abs() > 1e-7 * (1.0 + r)) { - return None; - } - if dot(nc, a).abs() > 1e-9 || dot(sub(c, oa), nc).abs() > 1e-7 * (1.0 + r) { - return None; - } - let big = norm(radial(c)); - if big < 1e-9 * (1.0 + r) { - (AnalyticKind::Sphere { o: c, z: a, x: eq, r }, sub(q, c)) - } else { - let ec = unit(radial(c))?; - let o = on_axis(c); - if (big - r).abs() <= 1e-6 * (1.0 + r) { - (AnalyticKind::HornTorus { o, z: a, x: mul(ec, -1.0), big: r, small: r }, sub(q, add(o, mul(eq, r)))) - } else if big < r { - // A spindle torus (tube crossing the axis) stays a surface of revolution. - return None; - } else { - (AnalyticKind::Torus { o, z: a, x: ec, big, small: r }, sub(q, add(o, mul(eq, big)))) - } - } - } - }; - let flip = dot(n_rev, n_an) < 0.0; - if !dot(n_rev, n_an).is_finite() || dot(n_rev, n_an).abs() < 1e-12 { - return None; - } - Some(Analytic { kind, flip }) -} - -/// Two analytic surfaces are the same surface (same kind, frame-independent parameters). -fn same_analytic(a: &AnalyticKind, b: &AnalyticKind) -> bool { - let close = |x: f64, y: f64| (x - y).abs() <= 1e-7 * (1.0 + x.abs().max(y.abs())); - let same_pt = |p: V3, q: V3| norm(sub(p, q)) <= 1e-7 * (1.0 + norm(p)); - let parallel = |p: V3, q: V3| norm(cross(p, q)) <= 1e-9; - let on_line = |p: V3, o: V3, d: V3| norm(cross(sub(p, o), d)) <= 1e-7 * (1.0 + norm(p)); - match (a, b) { - (AnalyticKind::Cylinder { o, z, r, .. }, AnalyticKind::Cylinder { o: o2, z: z2, r: r2, .. }) => { - parallel(*z, *z2) && on_line(*o2, *o, *z) && close(*r, *r2) - } - (AnalyticKind::Cone { o, z, r, angle, .. }, AnalyticKind::Cone { o: o2, z: z2, r: r2, angle: a2, .. }) => { - // Same apex, axis direction and angle. - let apex = |o: V3, z: V3, r: f64, an: f64| sub(o, mul(z, r / an.tan())); - dot(*z, *z2) > 1.0 - 1e-9 && close(*angle, *a2) && same_pt(apex(*o, *z, *r, *angle), apex(*o2, *z2, *r2, *a2)) - } - (AnalyticKind::Sphere { o, r, .. }, AnalyticKind::Sphere { o: o2, r: r2, .. }) => same_pt(*o, *o2) && close(*r, *r2), - (AnalyticKind::Torus { o, z, big, small, .. }, AnalyticKind::Torus { o: o2, z: z2, big: b2, small: s2, .. }) => { - same_pt(*o, *o2) && parallel(*z, *z2) && close(*big, *b2) && close(*small, *s2) - } - (AnalyticKind::HornTorus { o, z, big, .. }, AnalyticKind::HornTorus { o: o2, z: z2, big: b2, .. }) => { - same_pt(*o, *o2) && parallel(*z, *z2) && close(*big, *b2) - } - (AnalyticKind::Plane { o, z, .. }, AnalyticKind::Plane { o: o2, z: z2, .. }) => { - parallel(*z, *z2) && dot(sub(*o2, *o), *z).abs() <= 1e-7 * (1.0 + norm(*o)) - } - _ => false, - } -} - -/// The outward normal sign of a face relative to its analytic surface's normal. -fn face_normal_sign(a: &AnalyticKind, z_written: V3, flip: bool, sense: bool) -> f64 { - // Planes compare their written normal directly; the others are always outward-normal kinds. - let base = match a { - AnalyticKind::Plane { z, .. } => dot(*z, z_written).signum(), - _ => 1.0, - }; - base * if flip != sense { 1.0 } else { -1.0 } -} - -/// A B-spline surface that is flat (a sheet swept along a line, as truck makes for extrusions): -/// the plane with the surface's own normal, so it can be written as a PLANE. -fn planar_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option { - use truck_modeling::{BoundedSurface, ParametricSurface, ParametricSurface3D}; - if !(e.has("B_SPLINE_SURFACE") || e.name() == "B_SPLINE_SURFACE_WITH_KNOTS") { - return None; - } - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let s = crate::step_in::geom::bspline_surface(&cx, e).ok()?; - let (ctrl, (u0, u1), (v0, v1)) = match &s { - truck_modeling::Surface::BSplineSurface(b) => { - (b.control_points().iter().flatten().map(|p| [p.x, p.y, p.z]).collect::>(), b.range_tuple().0, b.range_tuple().1) - } - truck_modeling::Surface::NurbsSurface(n) => { - let pts = n.non_rationalized().control_points().iter().flatten().map(|p| [p.x / p.w, p.y / p.w, p.z / p.w]).collect::>(); - let (ru, rv) = n.range_tuple(); - (pts, ru, rv) - } - _ => return None, - }; - let (um, vm) = ((u0 + u1) / 2.0, (v0 + v1) / 2.0); - let n = s.normal(um, vm); - let z = unit([n.x, n.y, n.z])?; - let o = s.subs(um, vm); - let o = [o.x, o.y, o.z]; - let du = s.uder(um, vm); - let x = unit(sub([du.x, du.y, du.z], mul(z, dot([du.x, du.y, du.z], z))))?; - let size = ctrl.iter().map(|p| norm(sub(*p, o))).fold(0.0, f64::max); - // Every control point on the plane (a flat net gives a flat surface, rational or not). - if ctrl.iter().any(|p| dot(sub(*p, o), z).abs() > 1e-9 * (1.0 + size)) { - return None; - } - Some(AnalyticKind::Plane { o, z, x }) -} - -/// A B-spline surface that is a circular cylinder or cone: straight rulings between two coaxial -/// circles or arcs (or an arc and the cone's apex), as truck makes for extruded round profiles, -/// rounds along straight edges and countersinks. With its normal direction relative to the -/// surface's outward normal. -fn ruled_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option { - use truck_modeling::{ParametricSurface, ParametricSurface3D}; - if !(e.has("B_SPLINE_SURFACE") || e.name() == "B_SPLINE_SURFACE_WITH_KNOTS") { - return None; - } - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let s = crate::step_in::geom::bspline_surface(&cx, e).ok()?; - let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { return None }; - let at = |u: f64, v: f64| { - let p = s.subs(u, v); - [p.x, p.y, p.z] - }; - // Which parameter runs along the rulings: straight from one end to the other at every point - // of the profile. - for along_v in [true, false] { - let point = |t: f64, w: f64| if along_v { at(u0 + (u1 - u0) * t, v0 + (v1 - v0) * w) } else { at(u0 + (u1 - u0) * w, v0 + (v1 - v0) * t) }; - let grid: Vec> = (0..=4).map(|m| (0..=8).map(|k| point(k as f64 / 8.0, m as f64 / 4.0)).collect()).collect(); - let (Some(p0), Some(p1)) = (grid.first(), grid.last()) else { continue }; - let Some(&first) = p0.first() else { continue }; - let scale = grid.iter().flatten().map(|p| norm(sub(*p, first))).fold(0.0, f64::max); - let tol = 1e-7 * (1.0 + scale); - let straight = (0..=8).all(|k| { - let (Some(&a), Some(&b)) = (p0.get(k), p1.get(k)) else { return false }; - let Some(d) = unit(sub(b, a)) else { return false }; - grid.iter().all(|row| row.get(k).is_some_and(|q| norm(cross(sub(*q, a), d)) <= tol)) - }); - if !straight { - continue; - } - // Each end: a circle (centre, radius, axis) or a single point (a cone's apex). - let ring = |prof: &[V3]| -> Option<(V3, f64, Option)> { - let &a = prof.first()?; - if prof.iter().all(|p| norm(sub(*p, a)) <= tol) { - return Some((a, 0.0, None)); - } - let (&b, &c, &h) = (prof.get(4)?, prof.get(8)?, prof.get(2)?); - let (centre, r, n) = circle3(a, b, c).or_else(|| circle3(a, h, b))?; - prof.iter().all(|p| (norm(sub(*p, centre)) - r).abs() <= tol).then_some((centre, r, Some(n))) - }; - let ((c0, r0, n0), (c1, r1, n1)) = (ring(p0)?, ring(p1)?); - let axis = unit(sub(c1, c0))?; - if [n0, n1].iter().flatten().any(|n| norm(cross(*n, axis)) > 1e-7) || (n0.is_none() && n1.is_none()) { - return None; - } - let height = norm(sub(c1, c0)); - // The radius grows along z (a cylinder keeps the sweep's direction). - let (o, z, r, angle) = if (r1 - r0).abs() <= tol { - (c0, axis, r0, 0.0) - } else if r1 > r0 { - (c1, axis, r1, ((r1 - r0) / height).atan()) - } else { - (c0, mul(axis, -1.0), r0, ((r0 - r1) / height).atan()) - }; - let radius_at = |q: V3| r + dot(sub(q, o), z) * angle.tan(); - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - if grid.iter().flatten().any(|q| (norm(radial(*q)) - radius_at(*q)).abs() > tol) { - return None; - } - // The surface's own normal against the outward one, mid-face. - let (um, vm) = ((u0 + u1) / 2.0, (v0 + v1) / 2.0); - let nn = s.normal(um, vm); - let q = at(um, vm); - let eq = unit(radial(q))?; - let outward = sub(mul(eq, angle.cos()), mul(z, angle.sin())); - let flip = dot([nn.x, nn.y, nn.z], outward) < 0.0; - // The parameter seam opposite the middle of the sheet, away from its edges. - let x = mul(eq, -1.0); - let kind = if angle == 0.0 { AnalyticKind::Cylinder { o, z, x, r } } else { AnalyticKind::Cone { o, z, x, r, angle } }; - return Some(Analytic { kind, flip }); - } - None -} - -/// A B-spline surface that is really a plane, a cylinder or a cone. -fn analytic_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option { - planar_bspline(ex, e).map(|kind| Analytic { kind, flip: false }).or_else(|| ruled_bspline(ex, e)) -} - -/// Every edge of a face on a cylinder or cone is a circle square to its axis or one of its -/// rulings (a line along the axis, or through a cone's apex). Faces bounded by other curves (a -/// hole crossing a tube wall) keep their B-spline sheet: readers lay those curves out far more -/// slowly on the analytic surface than on the sheet they came with. -fn square_or_ruled(ex: &p21::Exchange, fe: &p21::Entity, kind: &AnalyticKind) -> bool { - let (z, apex) = match *kind { - AnalyticKind::Cylinder { z, .. } => (z, None), - AnalyticKind::Cone { o, z, r, angle, .. } if angle.tan() > 1e-12 => (z, Some(sub(o, mul(z, r / angle.tan())))), - _ => return false, - }; - face_edges(ex, fe).is_some_and(|ls| { - ls.iter().flatten().all(|(x, _)| { - edge_samples(ex, *x).is_some_and(|pts| { - let Some(&q0) = pts.first() else { return false }; - let tol = 1e-7 * (1.0 + norm(q0)); - let ruling = match apex { - None => pts.iter().all(|q| norm(cross(sub(*q, q0), z)) <= tol), - Some(a) => pts.iter().all(|q| norm(cross(sub(*q, a), sub(q0, a))) <= tol * (1.0 + norm(sub(q0, a)))), - }; - ruling || pts.iter().all(|q| dot(sub(*q, q0), z).abs() <= tol) - }) - }) - }) -} - -/// Points along an edge's curve (its ends for a line, None for a conic it cannot sample). -fn edge_samples(ex: &p21::Exchange, edge: u64) -> Option> { - edge_points(ex, edge, 4) -} - -/// `n + 1` points along an edge's curve, ends included (its ends for a line, None for a conic it -/// cannot sample). -fn edge_points(ex: &p21::Exchange, edge: u64, n: usize) -> Option> { - use truck_modeling::{BoundedCurve, ParametricCurve}; - let p = ex.get(edge)?.params(); - let ends = [vertex_point(ex, p.get(1)?.as_ref_id()?)?, vertex_point(ex, p.get(2)?.as_ref_id()?)?]; - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let sample = |f: &dyn Fn(f64) -> truck_modeling::Point3, (t0, t1): (f64, f64)| { - (0..=n).map(|k| f(t0 + (t1 - t0) * k as f64 / n.max(1) as f64)).map(|q| [q.x, q.y, q.z]).collect::>() - }; - match crate::step_in::geom::curve(&cx, p.get(3)?.as_ref_id()?, 0).ok()? { - crate::step_in::geom::CurveGeo::Line { .. } => Some(ends.to_vec()), - crate::step_in::geom::CurveGeo::BSpline(c) => Some(sample(&|t| c.subs(t), c.range_tuple())), - crate::step_in::geom::CurveGeo::Nurbs(c) => Some(sample(&|t| c.subs(t), c.range_tuple())), - crate::step_in::geom::CurveGeo::Conic { .. } - | crate::step_in::geom::CurveGeo::Hyperbola { .. } - | crate::step_in::geom::CurveGeo::Parabola { .. } => None, - } -} - -fn vertex_point(ex: &p21::Exchange, v: u64) -> Option { - let p = ex.get(ex.get(v)?.params().get(1)?.as_ref_id()?)?; - let c = p.params().get(1)?.as_list()?; - Some([c.first()?.as_f64()?, c.get(1)?.as_f64()?, c.get(2)?.as_f64()?]) -} - -/// For each horn torus revolution, a turn direction away from its faces (the B-spline's -/// parameter seam must not cross them): opposite their vertices' mean direction about the axis. -fn horn_seams(ex: &p21::Exchange) -> HashMap { - let mut out = HashMap::new(); - for fe in ex.entities.values() { - if !matches!(fe.name(), "FACE_SURFACE" | "ADVANCED_FACE") { - continue; - } - let Some(sid) = fe.params().get(2).and_then(Param::as_ref_id) else { continue }; - let Some(se) = ex.get(sid).filter(|e| e.name() == "SURFACE_OF_REVOLUTION") else { continue }; - let Some(Analytic { kind: AnalyticKind::HornTorus { o, z, .. }, .. }) = analytic_revolution(ex, se) else { continue }; - let Some(loops) = face_edges(ex, fe) else { continue }; - let mut mean = [0.0; 3]; - for (e, _) in loops.iter().flatten() { - for k in [1, 2] { - let Some(q) = ex.get(*e).and_then(|e| e.params().get(k)).and_then(Param::as_ref_id).and_then(|v| vertex_point(ex, v)) else { - continue; - }; - let v = sub(q, o); - if let Some(r) = unit(sub(v, mul(z, dot(v, z)))) { - mean = add(mean, r); - } - } - } - if let Some(m) = unit(mean) { - out.insert(sid, mul(m, -1.0)); - } - } - out -} - -/// Zero-length edges (truck sweeps a profile point on the axis into one) removed and their -/// vertices joined: other systems reject a pole written as an ordinary edge. -fn collapse_short_edges(ex: &mut p21::Exchange) { - let ends = |e: &p21::Entity| Some((e.params().get(1)?.as_ref_id()?, e.params().get(2)?.as_ref_id()?)); - let mut join: HashMap = HashMap::new(); - let mut dead = std::collections::HashSet::new(); - let mut ids: Vec = ex.entities.iter().filter(|(_, e)| e.name() == "EDGE_CURVE").map(|(i, _)| *i).collect(); - ids.sort(); - for id in ids { - let Some(e) = ex.get(id) else { continue }; - let Some((a, b)) = ends(e) else { continue }; - let (Some(pa), Some(pb)) = (vertex_point(ex, a), vertex_point(ex, b)) else { continue }; - if a == b || norm(sub(pa, pb)) > 1e-6 * (1.0 + norm(pa)) { - continue; - } - // The curve itself must be short too (not a whole circle between two coincident vertices). - let short = e.params().get(3).and_then(Param::as_ref_id).and_then(|c| { - use truck_modeling::{BoundedCurve, ParametricCurve}; - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let mid = match crate::step_in::geom::curve(&cx, c, 0).ok()? { - crate::step_in::geom::CurveGeo::Line { .. } => return Some(true), - crate::step_in::geom::CurveGeo::BSpline(c) => c.subs((c.range_tuple().0 + c.range_tuple().1) / 2.0), - crate::step_in::geom::CurveGeo::Nurbs(c) => c.subs((c.range_tuple().0 + c.range_tuple().1) / 2.0), - crate::step_in::geom::CurveGeo::Conic { .. } - | crate::step_in::geom::CurveGeo::Hyperbola { .. } - | crate::step_in::geom::CurveGeo::Parabola { .. } => return Some(false), - }; - Some(norm(sub([mid.x, mid.y, mid.z], pa)) <= 1e-6 * (1.0 + norm(pa))) - }); - if short != Some(true) { - continue; - } - let find = |join: &HashMap, mut v: u64| { - while let Some(n) = join.get(&v) { - v = *n; - } - v - }; - let (ra, rb) = (find(&join, a), find(&join, b)); - if ra != rb { - join.insert(rb, ra); - } - dead.insert(id); - } - if dead.is_empty() { - return; - } - // A loop made only of such edges (a pole loop) keeps them all. - let oe_edge = |ex: &p21::Exchange, oe: &Param| oe.as_ref_id().and_then(|o| ex.get(o)).and_then(|o| o.params().get(3)).and_then(Param::as_ref_id); - let loops: Vec = ex.entities.iter().filter(|(_, e)| e.name() == "EDGE_LOOP").map(|(i, _)| *i).collect(); - for l in &loops { - let Some(list) = ex.get(*l).and_then(|e| e.params().get(1)).and_then(Param::as_list) else { continue }; - if list.iter().all(|oe| oe_edge(ex, oe).is_some_and(|e| dead.contains(&e))) { - return; - } - } - for l in loops { - let Some(list) = ex.get(l).and_then(|e| e.params().get(1)).and_then(Param::as_list) else { continue }; - let kept: Vec = list.iter().filter(|oe| !oe_edge(ex, oe).is_some_and(|e| dead.contains(&e))).cloned().collect(); - if let Some(r) = ex.entities.get_mut(&l).and_then(|e| e.records.first_mut()) - && let Some(slot) = r.params.get_mut(1) - { - *slot = Param::List(kept); - } - } - let find = |mut v: u64| { - while let Some(n) = join.get(&v) { - v = *n; - } - v - }; - for e in ex.entities.values_mut() { - if e.name() != "EDGE_CURVE" { - continue; - } - if let Some(r) = e.records.first_mut() { - for k in [1, 2] { - if let Some(slot) = r.params.get_mut(k) - && let Some(v) = slot.as_ref_id() - { - *slot = Param::Ref(find(v)); - } - } - } - } -} - -/// Oriented edges (edge id, forward) of a face's bounds. -fn face_edges(ex: &p21::Exchange, face: &p21::Entity) -> Option>> { - let mut loops = Vec::new(); - for b in face.params().get(1)?.as_list()? { - let fb = ex.get(b.as_ref_id()?)?; - let lp = ex.get(fb.params().get(1)?.as_ref_id()?)?; - if lp.name() != "EDGE_LOOP" { - return None; - } - let orient = fb.params().get(2)?.as_bool()?; - let mut v = Vec::new(); - for oe in lp.params().get(1)?.as_list()? { - let oe = ex.get(oe.as_ref_id()?)?; - if oe.name() != "ORIENTED_EDGE" { - return None; - } - v.push((oe.params().get(3)?.as_ref_id()?, oe.params().get(4)?.as_bool()?)); - } - if !orient { - v.reverse(); - v.iter_mut().for_each(|e| e.1 = !e.1); - } - loops.push(v); - } - Some(loops) -} - -/// Faces that truck splits (a revolution in two or three turns) joined back into one face per -/// analytic surface, by dropping the edges between them. Faces whose union would lose all its -/// edges, or whose leftover edges do not close into loops, stay apart. Returns the surfaces of -/// merged faces. -fn merge_split_faces(ex: &mut p21::Exchange, paint: &mut HashMap, keep: &[Vec]) -> std::collections::HashSet { - // An edge on a line the user split along: every sample within a hair of the polyline. - let on_split = |ex: &p21::Exchange, e: u64| -> bool { - let Some(pts) = edge_samples(ex, e) else { return false }; - let pts: Vec = pts.iter().map(|q| Vec3::new(q[0], q[1], q[2])).collect(); - crate::heal::on_split_line(&pts, keep) - }; - let mut merged_surfaces = std::collections::HashSet::new(); - let mut next = ex.entities.keys().max().copied().unwrap_or(0) + 1; - let shells: Vec = ex.entities.iter().filter(|(_, e)| matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL")).map(|(i, _)| *i).collect(); - // Each surface's analytic form, worked out once (merged faces keep a piece's surface). - let mut cache: HashMap> = HashMap::new(); - for sh in shells { - for _round in 0..64 { - let Some(faces) = ex - .get(sh) - .and_then(|e| e.params().get(1)) - .and_then(Param::as_list) - .map(|l| l.iter().filter_map(Param::as_ref_id).collect::>()) - else { - break; - }; - // Analytic description and normal sign of each face on a revolution. - let info: Vec> = faces - .iter() - .map(|f| { - let fe = ex.get(*f)?; - if !matches!(fe.name(), "FACE_SURFACE" | "ADVANCED_FACE") { - return None; - } - let sid = fe.params().get(2)?.as_ref_id()?; - let an = (*cache.entry(sid).or_insert_with(|| { - let se = ex.get(sid)?; - match se.name() { - "SURFACE_OF_REVOLUTION" => analytic_revolution(ex, se), - // Coplanar pieces (a face split where a mirrored half was glued on). - "PLANE" => { - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let f = crate::step_in::geom::frame(&cx, se.params().get(1)?.as_ref_id()?).ok()?; - let v = |a: truck_modeling::Vector3| [a.x, a.y, a.z]; - Some(Analytic { kind: AnalyticKind::Plane { o: [f.o.x, f.o.y, f.o.z], z: v(f.z), x: v(f.x) }, flip: false }) - } - // Pieces of a B-spline cylinder or cone merge only when their edges - // are circles square to the axis and rulings (an extruded hole). - _ => analytic_bspline(ex, se).filter(|a| match a.kind { - AnalyticKind::Cylinder { .. } | AnalyticKind::Cone { .. } => square_or_ruled(ex, fe, &a.kind), - _ => true, - }), - } - }))?; - let sense = fe.params().get(3)?.as_bool()?; - let z = match an.kind { - AnalyticKind::Plane { z, .. } => z, - _ => [0.0; 3], - }; - let sign = face_normal_sign(&an.kind, z, an.flip, sense); - // Planes: normalise to one written direction for comparisons. - Some((an.kind, sign)) - }) - .collect(); - let mut merged = false; - 'pairs: for i in 0..faces.len() { - for j in (i + 1)..faces.len() { - let (Some(Some((ka, sa))), Some(Some((kb, sb)))) = (info.get(i), info.get(j)) else { continue }; - if !same_analytic(ka, kb) { - continue; - } - let plane_dir = |k: &AnalyticKind| match k { - AnalyticKind::Plane { z, .. } => *z, - _ => [0.0, 0.0, 1.0], - }; - let (na, nb) = (mul(plane_dir(ka), *sa), mul(plane_dir(kb), *sb)); - if dot(na, nb) <= 0.0 { - continue; - } - let (Some(&fa), Some(&fb)) = (faces.get(i), faces.get(j)) else { continue }; - // Faces of different colours stay apart. - if paint.get(&fa) != paint.get(&fb) { - continue; - } - let (Some(ea), Some(eb)) = (ex.get(fa).and_then(|f| face_edges(ex, f)), ex.get(fb).and_then(|f| face_edges(ex, f))) else { - continue; - }; - let all: Vec<(u64, bool)> = ea.into_iter().chain(eb).flatten().collect(); - let shared: std::collections::HashSet = - all.iter().filter(|(e, d)| all.iter().any(|(e2, d2)| e2 == e && d2 != d)).map(|(e, _)| *e).collect(); - if shared.is_empty() || shared.iter().any(|e| on_split(ex, *e)) { - continue; - } - // Chain oriented edges into loops by vertices (None: they do not close). - let ends = |(e, d): (u64, bool)| -> Option<(u64, u64)> { - let p = ex.get(e)?.params(); - let (s0, s1) = (p.get(1)?.as_ref_id()?, p.get(2)?.as_ref_id()?); - Some(if d { (s0, s1) } else { (s1, s0) }) - }; - let chain = |mut pool: Vec<(u64, bool)>| -> Option>> { - let mut loops = Vec::new(); - while let Some(first) = pool.pop() { - let (start, mut at) = ends(first)?; - let mut lp = vec![first]; - while at != start { - if lp.len() > 100_000 { - return None; - } - let k = pool.iter().position(|x| ends(*x).is_some_and(|(s, _)| s == at))?; - let x = pool.remove(k); - at = ends(x)?.1; - lp.push(x); - } - loops.push(lp); - } - Some(loops) - }; - // A full turn keeps one shared edge as the face's seam, used both ways (as other - // systems write cylinders and cone tips); otherwise the shared edges go. - // (A horn torus band needs no seam: its rings meet at the pole.) - let mut loops = None; - if shared.len() >= 2 && !matches!(ka, AnalyticKind::HornTorus { .. } | AnalyticKind::Plane { .. }) { - // Without the shared edges: one ring (a cone tip) or two (a band). The seam - // runs from a vertex on the first ring to the second ring (or the apex) and - // back: ring A, seam, ring B, seam reversed. - let rest: Vec<(u64, bool)> = all.iter().copied().filter(|(e, _)| !shared.contains(e)).collect(); - if let Some(rings) = chain(rest).filter(|r| matches!(r.len(), 1 | 2)) { - let starts_at = |ring: &Vec<(u64, bool)>, v: u64| ring.iter().position(|x| ends(*x).is_some_and(|(a, _)| a == v)); - let on_axis = |v: u64| { - let (o, z) = match ka { - AnalyticKind::Cone { o, z, .. } | AnalyticKind::Sphere { o, z, .. } => (*o, *z), - _ => return false, - }; - vertex_point(ex, v).is_some_and(|q| norm(cross(sub(q, o), z)) <= 1e-6 * (1.0 + norm(q))) - }; - let rotated = - |ring: &Vec<(u64, bool)>, k: usize| ring.iter().skip(k).chain(ring.iter().take(k)).copied().collect::>(); - // Whether a ring leaves its first vertex turning anticlockwise about a - // cylinder's or cone's axis (the way its angle parameter grows). - let turns_with_angle = |ring: &[(u64, bool)]| -> Option { - let (o, z) = match ka { - AnalyticKind::Cylinder { o, z, .. } | AnalyticKind::Cone { o, z, .. } => (*o, *z), - _ => return None, - }; - let &(edge, dir) = ring.first()?; - let start = vertex_point(ex, ends((edge, dir))?.0)?; - let mut pts = edge_points(ex, edge, 4)?; - if ex.get(edge)?.params().get(4)?.as_bool()? != dir { - pts.reverse(); - } - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - let turn = dot(cross(radial(start), radial(*pts.get(1)?)), z); - (turn != 0.0).then_some(turn > 0.0) - }; - let mut cands: Vec = shared.iter().copied().collect(); - cands.sort(); - 'seam: for keep in cands { - for &(e, d) in all.iter().filter(|(e, _)| *e == keep) { - let Some((a, b)) = ends((e, d)) else { continue }; - let (Some(ra), Some(ka0)) = (rings.first(), rings.first().and_then(|r| starts_at(r, a))) else { continue }; - let mut lp = rotated(ra, ka0); - let mut back = (e, !d); - match rings.get(1) { - Some(rb) => { - let Some(kb) = starts_at(rb, b) else { continue }; - let ring_b = rotated(rb, kb); - // Readers put a seam's first use on the side where the - // angle starts, so the ring after it must turn the way - // the angle grows; else that ring and the seam's other - // use go first (#3394). - if turns_with_angle(&ring_b) == Some(false) { - let ring_a = std::mem::replace(&mut lp, ring_b); - lp.push((e, !d)); - lp.extend(ring_a); - back = (e, d); - } else { - lp.push((e, d)); - lp.extend(ring_b); - } - } - // A cone tip (or a sphere's pole cap): the seam's far end is - // the apex on the axis, off the ring. - None if starts_at(ra, b).is_none() && on_axis(b) => lp.push((e, d)), - None => continue, - } - lp.push(back); - loops = Some(vec![lp]); - break 'seam; - } - } - } - } - let planar = matches!(ka, AnalyticKind::Plane { .. }); - if loops.is_none() && planar { - // A plane needs no seam: an annulus keeps its two rings, a face with a hole - // its hole. The largest loop goes first (the outer bound). - let rest: Vec<(u64, bool)> = all.iter().copied().filter(|(e, _)| !shared.contains(e)).collect(); - loops = chain(rest).map(|mut l| { - let size = |lp: &Vec<(u64, bool)>| { - let pts: Vec = lp.iter().filter_map(|x| ends(*x).and_then(|(a, _)| vertex_point(ex, a))).collect(); - let mut lo = [f64::INFINITY; 3]; - let mut hi = [f64::NEG_INFINITY; 3]; - for p in &pts { - for k in 0..3 { - lo[k] = lo[k].min(p[k]); - hi[k] = hi[k].max(p[k]); - } - } - norm(sub(hi, lo)) - }; - l.sort_by(|a, b| size(b).total_cmp(&size(a))); - l - }); - } - if loops.is_none() && !planar { - let rest: Vec<(u64, bool)> = all.iter().copied().filter(|(e, _)| !shared.contains(e)).collect(); - loops = chain(rest) - .map(|mut l| { - // Rings meeting at a vertex (both ends of a horn torus band meet at - // its pole) form one figure-eight loop through it. - while l.len() > 1 { - let Some(second) = l.pop() else { break }; - let at = l.iter().enumerate().find_map(|(li, lp)| { - lp.iter().enumerate().find_map(|(k, x)| { - let v = ends(*x)?.1; - let s = second.iter().position(|y| ends(*y).is_some_and(|(a, _)| a == v))?; - Some((li, k, s)) - }) - }); - let Some((li, k, s)) = at else { - l.push(second); - break; - }; - let mut second = second; - second.rotate_left(s); - if let Some(lp) = l.get_mut(li) { - for (n, x) in second.into_iter().enumerate() { - lp.insert(k + 1 + n, x); - } - } - } - l - }) - .filter(|l| l.len() == 1); - } - let Some(loops) = loops else { continue }; - // A loop of seams only (a whole sphere) bounds nothing: keep the faces apart. - if loops.iter().all(|l| l.iter().all(|(e, _)| l.iter().filter(|(e2, _)| e2 == e).count() > 1)) { - continue; - } - // Write the merged face. - let mut bounds = Vec::new(); - for lp in loops { - let mut oes = Vec::new(); - for (e, d) in lp { - let id = next; - next += 1; - ex.entities.insert( - id, - p21::Entity { - records: vec![p21::Record { - name: "ORIENTED_EDGE".into(), - params: vec![ - Param::Str(String::new()), - Param::Derived, - Param::Derived, - Param::Ref(e), - Param::Enum(if d { "T" } else { "F" }.into()), - ], - }], - }, - ); - oes.push(Param::Ref(id)); - } - let lid = next; - next += 1; - ex.entities.insert( - lid, - p21::Entity { - records: vec![p21::Record { name: "EDGE_LOOP".into(), params: vec![Param::Str(String::new()), Param::List(oes)] }], - }, - ); - let bid = next; - next += 1; - ex.entities.insert( - bid, - p21::Entity { - records: vec![p21::Record { - name: "FACE_BOUND".into(), - params: vec![Param::Str(String::new()), Param::Ref(lid), Param::Enum("T".into())], - }], - }, - ); - bounds.push(Param::Ref(bid)); - } - let Some(old) = ex.get(fa).cloned() else { continue }; - let mut params = old.params().to_vec(); - if let Some(slot) = params.get_mut(1) { - *slot = Param::List(bounds); - } - let nid = next; - next += 1; - if let Some(sid) = params.get(2).and_then(Param::as_ref_id) { - merged_surfaces.insert(sid); - } - ex.entities.insert(nid, p21::Entity { records: vec![p21::Record { name: old.name().to_string(), params }] }); - if let Some(look) = paint.remove(&fa) { - paint.remove(&fb); - paint.insert(nid, look); - } - let new_list: Vec = faces.iter().filter(|f| **f != fb).map(|f| Param::Ref(if *f == fa { nid } else { *f })).collect(); - if let Some(she) = ex.entities.get_mut(&sh) - && let Some(r) = she.records.first_mut() - && let Some(slot) = r.params.get_mut(1) - { - *slot = Param::List(new_list); - } - merged = true; - break 'pairs; - } - } - if !merged { - break; - } - } - } - merged_surfaces -} - -/// B-spline cylinder and cone sheets written as CYLINDRICAL_SURFACE and CONICAL_SURFACE (the -/// sheet covers only its own piece, and a fillet's may reach far past it), with the direction of -/// the parameter seam: on the face's seam edge for a full turn, else in the middle of the gap the -/// face leaves (`gap_middle`), else opposite the face's middle. -/// Sheets under faces merged from pieces always; a lone piece when its edges are circles square -/// to the axis and rulings. (Faces replaced by merges stay in the exchange unreferenced: only the -/// shells' faces count.) -fn analytic_sheets(ex: &p21::Exchange, merged_surfaces: &std::collections::HashSet) -> HashMap { - let live: Vec = ex - .entities - .values() - .filter_map(|e| if matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL") { e.params().get(1).and_then(Param::as_list) } else { None }) - .flatten() - .filter_map(Param::as_ref_id) - .collect(); - let mut out = HashMap::new(); - for e in live.iter().filter_map(|f| ex.get(*f)) { - let Some(sid) = e.params().get(2).and_then(Param::as_ref_id) else { continue }; - if out.contains_key(&sid) { - continue; - } - let Some(Analytic { kind, .. }) = ex.get(sid).and_then(|se| ruled_bspline(ex, se)) else { - continue; - }; - let (AnalyticKind::Cylinder { o, z, .. } | AnalyticKind::Cone { o, z, .. }) = kind else { continue }; - if !merged_surfaces.contains(&sid) && !square_or_ruled(ex, e, &kind) { - continue; - } - let Some(loops) = face_edges(ex, e) else { continue }; - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - let seam = loops - .iter() - .flat_map(|l| l.iter().map(move |(x, _)| (l, *x))) - .find(|(l, x)| l.iter().filter(|(y, _)| y == x).count() > 1) - .map(|(_, x)| x); - // (A cone tip's seam has one end at the apex, on the axis.) - let seam_dir = seam.and_then(|edge| { - let p = ex.get(edge)?.params(); - [p.get(1), p.get(2)].into_iter().filter_map(|v| vertex_point(ex, v?.as_ref_id()?)).find_map(|q| unit(radial(q))) - }); - let x = match seam_dir.or_else(|| gap_middle(ex, &loops, z, &radial)) { - Some(x) => Some(x), - None => { - // No single gap to find (a half turn has two corners, a tube cut in pieces - // several). Points along the edges, not just their ends: the corners of a half - // turn (a slot's round end) point both ways and cancel out (#1198). The sheet's - // own middle where even those do. - let mean = loops - .iter() - .flatten() - .filter_map(|(edge, _)| edge_samples(ex, *edge)) - .flatten() - .filter_map(|q| unit(radial(q))) - .fold([0.0; 3], add); - let (AnalyticKind::Cylinder { x: middle, .. } | AnalyticKind::Cone { x: middle, .. }) = kind else { continue }; - Some(unit(mul(mean, -1.0)).unwrap_or(middle)) - } - }; - if let Some(x) = x { - out.insert(sid, x); - } - } - out -} - -/// The middle of the one angular gap that a face on a cylinder or cone leaves around its axis -/// `z`. The face's boundary vertices are sorted by angle; each two neighbours are joined by one -/// of its edges except across the gap (a 270° face split at 0°, 90°, 180° and 270° leaves -/// 270°–360°). None unless there are three angles or more and exactly one gap: two vertices can -/// be joined either way round. -fn gap_middle(ex: &p21::Exchange, loops: &[Vec<(u64, bool)>], z: V3, radial: &impl Fn(V3) -> V3) -> Option { - use std::f64::consts::TAU; - let mut edges: Vec<(V3, V3)> = Vec::new(); - for (e, _) in loops.iter().flatten() { - let p = ex.get(*e)?.params(); - let (a, b) = (vertex_point(ex, p.get(1)?.as_ref_id()?)?, vertex_point(ex, p.get(2)?.as_ref_id()?)?); - edges.push((unit(radial(a))?, unit(radial(b))?)); - } - let e1 = edges.first()?.0; - let e2 = unit(cross(z, e1))?; - let angle = |d: V3| dot(d, e2).atan2(dot(d, e1)).rem_euclid(TAU); - let close = |a: f64, b: f64| { - let d = (a - b).rem_euclid(TAU); - d < 1e-6 || TAU - d < 1e-6 - }; - let mut angles: Vec = Vec::new(); - for (a, b) in &edges { - for t in [angle(*a), angle(*b)] { - if !angles.iter().any(|s| close(*s, t)) { - angles.push(t); - } - } - } - if angles.len() < 3 { - return None; - } - angles.sort_by(f64::total_cmp); - let joined = |s: f64, t: f64| { - edges.iter().any(|(a, b)| { - let (x, y) = (angle(*a), angle(*b)); - (close(x, s) && close(y, t)) || (close(x, t) && close(y, s)) - }) - }; - let n = angles.len(); - let gaps: Vec<(f64, f64)> = (0..n).filter_map(|i| Some((*angles.get(i)?, *angles.get((i + 1) % n)?))).filter(|(s, t)| !joined(*s, *t)).collect(); - let [(s, t)] = gaps[..] else { return None }; - let m = s + (t - s).rem_euclid(TAU) / 2.0; - unit(add(mul(e1, m.cos()), mul(e2, m.sin()))) -} - -/// Margin left round a face when its sheet is cut down to it, as a share of the face's own -/// parameter range on each side. -const SHEET_MARGIN: f64 = 0.02; - -/// B-spline sheets that reach well past the one face on them, cut down to that face's parameter -/// range (and a margin), so readers bound the part by its faces (#1198): a round's sheet runs on -/// past both ends of the edge it rounds, and when a later cut crosses the round, the crossing edge -/// keeps it from being written as a cylinder (see `square_or_ruled`). Sheets written as analytic -/// surfaces, flat ones, sheets under several faces, and those whose face's edges do not all lie -/// on the piece cut out (a face across a closed sheet's seam) are left alone. -fn trimmed_sheets(ex: &p21::Exchange, analytic: &HashMap) -> HashMap { - let live: Vec = ex - .entities - .values() - .filter_map(|e| if matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL") { e.params().get(1).and_then(Param::as_list) } else { None }) - .flatten() - .filter_map(Param::as_ref_id) - .collect(); - let mut users: HashMap = HashMap::new(); - for e in live.iter().filter_map(|f| ex.get(*f)) { - if let Some(sid) = e.params().get(2).and_then(Param::as_ref_id) { - *users.entry(sid).or_default() += 1; - } - } - let mut out = HashMap::new(); - for e in live.iter().filter_map(|f| ex.get(*f)) { - let Some(sid) = e.params().get(2).and_then(Param::as_ref_id) else { continue }; - if users.get(&sid) != Some(&1) || analytic.contains_key(&sid) { - continue; - } - let Some(se) = ex.get(sid) else { continue }; - if !(se.has("B_SPLINE_SURFACE") || se.name() == "B_SPLINE_SURFACE_WITH_KNOTS") || planar_bspline(ex, se).is_some() { - continue; - } - let Some(pts) = face_edges(ex, e).and_then(|ls| ls.iter().flatten().map(|(x, _)| edge_points(ex, *x, 16)).collect::>>()) else { - continue; - }; - let pts: Vec = pts.into_iter().flatten().collect(); - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let Ok(sheet) = crate::step_in::geom::bspline_surface(&cx, se) else { continue }; - if let Ok(Some(cut)) = crate::guard("STEP sheet trim", || Ok(trim_sheet(&sheet, &pts))) { - out.insert(sid, cut); - } - } - out -} - -/// `sheet` cut down to the parameter range `pts` (points on it) cover, with [`SHEET_MARGIN`]; -/// `None` when that would not make it much smaller, or when a point is not on the piece cut out. -fn trim_sheet(sheet: &truck_modeling::Surface, pts: &[V3]) -> Option { - use truck_modeling::{ParametricSurface, SearchNearestParameter, Surface}; - let (Some((u0, u1)), Some((v0, v1))) = sheet.try_range_tuple() else { return None }; - // Edges made by intersecting surfaces are fitted to them, a micron or so off the sheet; a - // point on the wrong piece of it is far further. - let (lo, hi) = pts.iter().fold(([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]), |(lo, hi), p| { - ([lo[0].min(p[0]), lo[1].min(p[1]), lo[2].min(p[2])], [hi[0].max(p[0]), hi[1].max(p[1]), hi[2].max(p[2])]) - }); - let tol = 1e-3 + 1e-4 * norm(sub(hi, lo)); - let near = |s: &Surface, p: V3| -> Option<(f64, f64)> { - let q = truck_modeling::Point3::new(p[0], p[1], p[2]); - let (u, v) = s.search_nearest_parameter(q, None, 100)?; - let r = s.subs(u, v); - (norm(sub([r.x, r.y, r.z], p)) <= tol).then_some((u, v)) - }; - let (mut ua, mut ub, mut va, mut vb) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); - for p in pts { - let (u, v) = near(sheet, *p)?; - (ua, ub, va, vb) = (ua.min(u), ub.max(u), va.min(v), vb.max(v)); - } - let (du, dv) = ((ub - ua) * SHEET_MARGIN, (vb - va) * SHEET_MARGIN); - let (ua, ub, va, vb) = ((ua - du).max(u0), (ub + du).min(u1), (va - dv).max(v0), (vb + dv).min(v1)); - // Worth it only where a parameter keeps less than four fifths of its range. - let keeps = |a: f64, b: f64, lo: f64, hi: f64| (b - a) / (hi - lo); - if !(ua < ub && va < vb) || (keeps(ua, ub, u0, u1) > 0.8 && keeps(va, vb, v0, v1) > 0.8) { - return None; - } - // The piece between the new ends: `ucut` keeps what lies before the cut and returns the rest. - macro_rules! cut { - ($s:expr) => {{ - let mut s = $s.clone(); - if ua > u0 { - s = s.ucut(ua); - } - if ub < u1 { - s.ucut(ub); - } - if va > v0 { - s = s.vcut(va); - } - if vb < v1 { - s.vcut(vb); - } - s - }}; - } - let piece = match sheet { - Surface::BSplineSurface(b) => Surface::BSplineSurface(cut!(b)), - Surface::NurbsSurface(n) => Surface::NurbsSurface(cut!(n)), - _ => return None, - }; - pts.iter().all(|p| near(&piece, *p).is_some()).then_some(piece) -} - -/// The B-rep entities of one body as truck writes them, parsed, the B-spline sheets to write -/// as cylinders and cones (see `analytic_sheets`) and those to write cut down to their faces -/// (see `trimmed_sheets`). Without `merge` the file is truck's, as is. -fn brep_exchange(b: &Body, merge: bool) -> Result<(p21::Exchange, HashMap, HashMap, HashMap)> { - let text = crate::step::truck_step(&[b], "SolidCraft")?; - let mut ex = p21::parse(&text).map_err(|e| KernelError::Failed(format!("STEP export: {e}")))?; - collapse_short_edges(&mut ex); - // Face colours by exchange face: truck writes each shell's faces in the body's face order. - let mut paint = HashMap::new(); - if let Some(p) = b.paint() - && !p.faces.is_empty() - { - let mut shells: Vec = ex.entities.iter().filter(|(_, e)| matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL")).map(|(i, _)| *i).collect(); - shells.sort(); - let faces: Vec = shells.iter().filter_map(|s| ex.get(*s)?.params().get(1)?.as_list()).flatten().filter_map(Param::as_ref_id).collect(); - for f in &p.faces { - if let Some(id) = faces.get(f.face) { - paint.insert(*id, (f.color, f.opacity)); - } - } - } - let before = shell_face_count(&ex); - let keep = b.split_lines().map(|l| l.as_slice()).unwrap_or(&[]); - let (sheets, trimmed) = if merge { - let merged = merge_split_faces(&mut ex, &mut paint, keep); - let sheets = analytic_sheets(&ex, &merged); - let trimmed = trimmed_sheets(&ex, &sheets); - // Lone sheets rewritten as analytic surfaces, or cut down, count as changes to check too. - MERGES.with(|m| m.set(m.get() + sheets.keys().filter(|s| !merged.contains(s)).count() + trimmed.len())); - (sheets, trimmed) - } else { - Default::default() - }; - MERGES.with(|m| m.set(m.get() + before.saturating_sub(shell_face_count(&ex)))); - Ok((ex, sheets, trimmed, paint)) -} - -/// The separate pieces of a body for export, each keeping its face colours: a body of several -/// lumps (a plate and the islands a cut left inside its holes, such as letter counters) is -/// several solids, never one solid whose other pieces are written as voids. A body in one -/// piece, or one whose pieces cannot be told apart, is itself. -fn export_lumps(b: &Body) -> Vec { - if b.mesh.is_some() || b.solid.boundaries().len() < 2 { - return vec![b.clone()]; - } - let lumps = match b.lumps() { - Ok(l) if l.len() > 1 => l, - _ => return vec![b.clone()], - }; - let index: HashMap<_, usize> = b.solid.face_iter().enumerate().map(|(i, f)| (f.id(), i)).collect(); - lumps - .into_iter() - .map(|lump| { - let paint = b.paint().map(|p| crate::body::Paint { - opacity: p.opacity, - faces: lump - .solid - .face_iter() - .enumerate() - .filter_map(|(k, f)| { - let i = index.get(&f.id())?; - p.faces.iter().find(|fp| fp.face == *i).map(|fp| crate::body::FacePaint { face: k, ..fp.clone() }) - }) - .collect(), - }); - lump.with_color(b.color()).with_split_lines(b.split_lines().cloned()).with_paint(paint) - }) - .collect() -} - -/// Faces in the exchange's shells (fewer after merging). -fn shell_face_count(ex: &p21::Exchange) -> usize { - ex.entities - .values() - .filter(|e| matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL")) - .filter_map(|e| e.params().get(1).and_then(Param::as_list)) - .map(<[Param]>::len) - .sum() -} - -/// A face's own colour (0..1) and opacity. -type FaceLook = ([f32; 3], f32); - +/// The placement's origin, z and x axes; refused unless it is a rotation and a translation. fn rigid_frame(m: &[[f64; 4]; 4]) -> Result<([f64; 3], [f64; 3], [f64; 3])> { let x = [m[0][0], m[0][1], m[0][2]]; let y = [m[1][0], m[1][1], m[1][2]]; @@ -1601,27 +73,7 @@ fn rigid_frame(m: &[[f64; 4]; 4]) -> Result<([f64; 3], [f64; 3], [f64; 3])> { /// STEP text (AP242) for products with bodies and assembly placements; `root` is the top product. pub fn step_export_products(products: &[ExportProduct], root: usize, header: &StepHeader) -> Result { - MERGES.with(|m| m.set(0)); - let text = products_text(products, root, header, true)?; - // Faces merged per surface, and sheets rewritten as cylinders and cones, must read back as - // cleanly as truck's pieces (a merge can leave a loop the reader cannot lay out); otherwise - // the pieces are written as truck made them. Without a change there is nothing to check. - let clean = |t: &str| crate::step_in::step_import(t).is_ok_and(|i| i.warnings.is_empty()); - if MERGES.with(|m| m.get()) > 0 && !clean(&text) { - let plain = products_text(products, root, header, false)?; - if clean(&plain) { - return Ok(plain); - } - } - Ok(text) -} - -thread_local! { - /// Faces merged and sheets rewritten while writing the current export. - static MERGES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -fn products_text(products: &[ExportProduct], root: usize, header: &StepHeader, merge: bool) -> Result { + let _span = solidcraft_profile::span("kernel", "step_export_products"); if products.is_empty() || root >= products.len() { return Err(KernelError::Invalid("nothing to export".into())); } @@ -1649,121 +101,131 @@ fn products_text(products: &[ExportProduct], root: usize, header: &StepHeader, m if cyclic(products, root, &mut Vec::new()) { return Err(KernelError::Invalid("the component tree is recursive".into())); } - - let mut o = Out::default(); - let app = o.add("APPLICATION_CONTEXT('managed model based 3d engineering')"); - o.add(format!("APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{app})")); - let pctx = o.add(format!("PRODUCT_CONTEXT('',#{app},'mechanical')")); - let pdctx = o.add(format!("PRODUCT_DEFINITION_CONTEXT('part definition',#{app},'design')")); - let mm = o.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); - let rad = o.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))"); - let sr = o.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())"); - let unc = o.add(format!("UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-06),#{mm},'distance_accuracy_value','confusion accuracy')")); - let ctx = o.add(format!( - "(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{unc}))GLOBAL_UNIT_ASSIGNED_CONTEXT((#{mm},#{rad},#{sr}))REPRESENTATION_CONTEXT('Context #1','3D Context with UNIT and UNCERTAINTY'))" - )); - let origin = o.placement([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); - - // Products (only those reachable from the root). + // Products reachable from the root. let mut reach = vec![false; products.len()]; let mut todo = vec![root]; while let Some(p) = todo.pop() { - if let Some(r) = reach.get_mut(p) - && !*r + if let Some(seen) = reach.get_mut(p) + && !*seen { - *r = true; + *seen = true; if let Some(x) = products.get(p) { todo.extend(x.children.iter().map(|(c, _, _)| *c)); } } } + let reached: Vec<(usize, &ExportProduct)> = products.iter().enumerate().filter(|(i, _)| reach.get(*i).copied().unwrap_or(false)).collect(); + // The context states the models' accuracy: the loosest of their records' tolerances. + let uncertainty = + reached.iter().flat_map(|(_, p)| &p.bodies).map(|b| b.body.record().tolerance).filter(|t| t.is_finite()).fold(MIN_UNCERTAINTY, f64::max); + + let mut w = Writer::new(); + let app = w.add_distinct("APPLICATION_CONTEXT", &[s("managed model based 3d engineering")]); + w.add_distinct( + "APPLICATION_PROTOCOL_DEFINITION", + &[s("international standard"), s("ap242_managed_model_based_3d_engineering"), Param::Int(2014), r(app)], + ); + let pctx = w.add_distinct("PRODUCT_CONTEXT", &[s(""), r(app), s("mechanical")]); + let pdctx = w.add_distinct("PRODUCT_DEFINITION_CONTEXT", &[s("part definition"), r(app), s("design")]); + let mm = w.add_complex(&[ + ("LENGTH_UNIT", vec![]), + ("NAMED_UNIT", vec![Param::Derived]), + ("SI_UNIT", vec![Param::Enum("MILLI".into()), Param::Enum("METRE".into())]), + ]); + let rad = w.add_complex(&[ + ("NAMED_UNIT", vec![Param::Derived]), + ("PLANE_ANGLE_UNIT", vec![]), + ("SI_UNIT", vec![Param::Null, Param::Enum("RADIAN".into())]), + ]); + let sr = w.add_complex(&[ + ("NAMED_UNIT", vec![Param::Derived]), + ("SI_UNIT", vec![Param::Null, Param::Enum("STERADIAN".into())]), + ("SOLID_ANGLE_UNIT", vec![]), + ]); + let unc = w.add_distinct( + "UNCERTAINTY_MEASURE_WITH_UNIT", + &[Param::Typed("LENGTH_MEASURE".into(), vec![Param::Real(uncertainty)]), r(mm), s("distance_accuracy_value"), s("confusion accuracy")], + ); + let ctx = w.add_complex(&[ + ("GEOMETRIC_REPRESENTATION_CONTEXT", vec![Param::Int(3)]), + ("GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT", vec![refs(&[unc])]), + ("GLOBAL_UNIT_ASSIGNED_CONTEXT", vec![refs(&[mm, rad, sr])]), + ("REPRESENTATION_CONTEXT", vec![s("Context #1"), s("3D Context with UNIT and UNCERTAINTY")]), + ]); + let origin = GeomWriter::new(&mut w).placement(&solidcraft_step::geom::Placement { + origin: [0.0; 3], + axis: [0.0, 0.0, 1.0], + ref_direction: [1.0, 0.0, 0.0], + }); + + // Placements of children inside each parent, made before the parent's representation. + let mut placements: Vec> = vec![Vec::new(); products.len()]; + for &(pi, p) in &reached { + for (_, m, _) in &p.children { + let (t, z, x) = rigid_frame(m)?; + let mut g = GeomWriter::new(&mut w); + let (pt, dz, dx) = (g.point(t), g.direction(z), g.direction(x)); + // Its own entity: it is an item of the parent's representation. + let a = w.add_distinct("AXIS2_PLACEMENT_3D", &[s(""), r(pt), r(dz), r(dx)]); + if let Some(v) = placements.get_mut(pi) { + v.push(a); + } + } + } let mut pd = vec![0u64; products.len()]; let mut shape_rep = vec![0u64; products.len()]; let mut product_ids = Vec::new(); let mut styled = Vec::new(); - let mut child_items: Vec> = vec![Vec::new(); products.len()]; - // Placements of children inside each parent, made before the parent's representation. - let mut placements: Vec> = vec![Vec::new(); products.len()]; - for (pi, p) in products.iter().enumerate() { - if !reach.get(pi).copied().unwrap_or(false) { - continue; - } - for (_, m, _) in &p.children { - let (t, z, x) = rigid_frame(m)?; - let (pt, dz, dx) = (o.point(t), o.direction(z), o.direction(x)); - // Its own entity: it is an item of the parent's representation. - let a = o.add(format!("AXIS2_PLACEMENT_3D('',#{pt},#{dz},#{dx})")); - if let Some(v) = placements.get_mut(pi) { - v.push(a); - } - if let Some(v) = child_items.get_mut(pi) { - v.push(a); - } - } - } - for (pi, p) in products.iter().enumerate() { - if !reach.get(pi).copied().unwrap_or(false) { - continue; - } + for &(pi, p) in &reached { let name = if p.name.trim().is_empty() { "Part".to_string() } else { p.name.clone() }; - let prod = o.add(format!("PRODUCT({},{},'',(#{pctx}))", string(&name), string(&name))); + let prod = w.add_distinct("PRODUCT", &[s(&name), s(&name), s(""), refs(&[pctx])]); product_ids.push(prod); - let pdf = o.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{prod})")); - let d = o.add(format!("PRODUCT_DEFINITION('design','',#{pdf},#{pdctx})")); - let pds = o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{d})")); + let pdf = w.add_distinct("PRODUCT_DEFINITION_FORMATION", &[s(""), s(""), r(prod)]); + let d = w.add_distinct("PRODUCT_DEFINITION", &[s("design"), s(""), r(pdf), r(pdctx)]); + let pds = w.add_distinct("PRODUCT_DEFINITION_SHAPE", &[s(""), s(""), r(d)]); let mut items = vec![origin]; - items.extend(child_items.get(pi).cloned().unwrap_or_default()); - let item_list = items.iter().map(|i| format!("#{i}")).collect::>().join(","); - let srep = o.add(format!("SHAPE_REPRESENTATION({},({item_list}),#{ctx})", string(&name))); - o.add(format!("SHAPE_DEFINITION_REPRESENTATION(#{pds},#{srep})")); + items.extend(placements.get(pi).into_iter().flatten().copied()); + let srep = w.add_distinct("SHAPE_REPRESENTATION", &[s(&name), refs(&items), r(ctx)]); + w.add_distinct("SHAPE_DEFINITION_REPRESENTATION", &[r(pds), r(srep)]); if let Some(slot) = pd.get_mut(pi) { *slot = d; } if let Some(slot) = shape_rep.get_mut(pi) { *slot = srep; } - if !p.bodies.is_empty() { - let mut solids = Vec::new(); - for b in &p.bodies { - for lump in export_lumps(b.body) { - let (ex, merged, trimmed, face_paint) = brep_exchange(&lump, merge)?; - o.merged = merged; - o.trimmed = trimmed; - o.faces_out.clear(); - let mut roots: Vec = - ex.entities.iter().filter(|(_, e)| matches!(e.name(), "MANIFOLD_SOLID_BREP" | "BREP_WITH_VOIDS")).map(|(i, _)| *i).collect(); - roots.sort(); - for r in roots { - let id = o.copy_solid(&ex, r, &b.name).map_err(|e| KernelError::Failed(format!("STEP export: {e}")))?; - solids.push(id); - let opacity = lump.paint().map(|p| p.opacity).unwrap_or(1.0); - if let Some(c) = b.color { - styled.push(style(&mut o, id, c, opacity)); - } - } - // Faces with colours of their own. - let mut painted: Vec<(u64, ([f32; 3], f32))> = - face_paint.into_iter().filter_map(|(f, look)| Some((*o.faces_out.get(&f)?, look))).collect(); - painted.sort_by_key(|(f, _)| *f); - for (f, (c, op)) in painted { - styled.push(style(&mut o, f, c, op)); - } + let (mut solids, mut sheets) = (Vec::new(), Vec::new()); + for b in &p.bodies { + let written = topology::brep(&mut GeomWriter::new(&mut w), b.body.record(), &b.name) + .map_err(|e| KernelError::Failed(format!("STEP export of '{}': {e}", b.name)))?; + let opacity = b.body.paint().map_or(1.0, |p| p.opacity); + let items: Vec = written.solids.iter().copied().chain(written.sheets).collect(); + if let Some(c) = b.color { + for item in &items { + styled.push(style(&mut w, *item, c, opacity)); } } - let list = solids.iter().chain(std::iter::once(&origin)).map(|i| format!("#{i}")).collect::>().join(","); - let absr = o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION({},({list}),#{ctx})", string(&name))); - o.add(format!("SHAPE_REPRESENTATION_RELATIONSHIP('','',#{srep},#{absr})")); + // Faces with colours of their own. + for f in b.body.paint().map(|p| p.faces.as_slice()).unwrap_or(&[]) { + if let Some(&face) = written.faces.get(f.face).filter(|id| **id != 0) { + styled.push(style(&mut w, face, f.color, f.opacity)); + } + } + solids.extend(written.solids); + sheets.extend(written.sheets); + } + for (kind, list) in [("ADVANCED_BREP_SHAPE_REPRESENTATION", solids), ("MANIFOLD_SURFACE_SHAPE_REPRESENTATION", sheets)] { + if list.is_empty() { + continue; + } + let rep = w.add_distinct(kind, &[s(&name), refs(&[list, vec![origin]].concat()), r(ctx)]); + w.add_distinct("SHAPE_REPRESENTATION_RELATIONSHIP", &[s(""), s(""), r(srep), r(rep)]); } } if !product_ids.is_empty() { - let list = product_ids.iter().map(|i| format!("#{i}")).collect::>().join(","); - o.add(format!("PRODUCT_RELATED_PRODUCT_CATEGORY('part','',({list}))")); + w.add_distinct("PRODUCT_RELATED_PRODUCT_CATEGORY", &[s("part"), s(""), refs(&product_ids)]); } // Assembly occurrences. - for (pi, p) in products.iter().enumerate() { - if !reach.get(pi).copied().unwrap_or(false) { - continue; - } + for &(pi, p) in &reached { for (k, (ci, _, oname)) in p.children.iter().enumerate() { let (Some(&parent_pd), Some(&child_pd), Some(&parent_sr), Some(&child_sr), Some(&target)) = (pd.get(pi), pd.get(*ci), shape_rep.get(pi), shape_rep.get(*ci), placements.get(pi).and_then(|v| v.get(k))) @@ -1775,61 +237,61 @@ fn products_text(products: &[ExportProduct], root: usize, header: &StepHeader, m } else { oname.clone() }; - let nauo = o.add(format!("NEXT_ASSEMBLY_USAGE_OCCURRENCE({},{},'',#{parent_pd},#{child_pd},$)", string(&nm), string(&nm))); - let pds = o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{nauo})")); - let idt = o.add(format!("ITEM_DEFINED_TRANSFORMATION('','',#{origin},#{target})")); - let rr = o.add(format!( - "(REPRESENTATION_RELATIONSHIP('','',#{child_sr},#{parent_sr})REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{idt})SHAPE_REPRESENTATION_RELATIONSHIP())" - )); - o.add(format!("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{rr},#{pds})")); + let nauo = w.add_distinct("NEXT_ASSEMBLY_USAGE_OCCURRENCE", &[s(&nm), s(&nm), s(""), r(parent_pd), r(child_pd), Param::Null]); + let pds = w.add_distinct("PRODUCT_DEFINITION_SHAPE", &[s(""), s(""), r(nauo)]); + let idt = w.add_distinct("ITEM_DEFINED_TRANSFORMATION", &[s(""), s(""), r(origin), r(target)]); + let rr = w.add_complex(&[ + ("REPRESENTATION_RELATIONSHIP", vec![s(""), s(""), r(child_sr), r(parent_sr)]), + ("REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION", vec![r(idt)]), + ("SHAPE_REPRESENTATION_RELATIONSHIP", vec![]), + ]); + w.add_distinct("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION", &[r(rr), r(pds)]); } } if !styled.is_empty() { - let list = styled.iter().map(|i| format!("#{i}")).collect::>().join(","); - o.add(format!("MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',({list}),#{ctx})")); + w.add_distinct("MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION", &[s(""), refs(&styled), r(ctx)]); } - let mut s = String::new(); - s.push_str("ISO-10303-21;\nHEADER;\n"); + let mut text = String::new(); + text.push_str("ISO-10303-21;\nHEADER;\n"); let description = if header.description.is_empty() { "SolidCraft model" } else { header.description.as_str() }; - let _ = writeln!(s, "FILE_DESCRIPTION(({}),'2;1');", string(description)); + let _ = writeln!(text, "FILE_DESCRIPTION(({}),'2;1');", string(description)); let _ = writeln!( - s, + text, "FILE_NAME({},{},({}),({}),'SolidCraft','SolidCraft','');", string(&header.file_name), string(&header.time_stamp), string(&header.author), string(&header.organization) ); - s.push_str("FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));\nENDSEC;\nDATA;\n"); - for (i, l) in o.lines.iter().enumerate() { - let _ = writeln!(s, "#{}={l};", i + 1); - } - s.push_str("ENDSEC;\nEND-ISO-10303-21;\n"); - Ok(s) + text.push_str("FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));\nENDSEC;\nDATA;\n"); + text.push_str(&w.data()); + text.push_str("ENDSEC;\nEND-ISO-10303-21;\n"); + Ok(text) } -/// A surface colour for a solid (STYLED_ITEM chain). -fn style(o: &mut Out, item: u64, c: [f32; 3], opacity: f32) -> u64 { - let rgb = o.add_shared(format!("COLOUR_RGB('',{},{},{})", real(c[0] as f64), real(c[1] as f64), real(c[2] as f64))); - let fasc = o.add_shared(format!("FILL_AREA_STYLE_COLOUR('',#{rgb})")); - let fas = o.add_shared(format!("FILL_AREA_STYLE('',(#{fasc}))")); - let ssfa = o.add_shared(format!("SURFACE_STYLE_FILL_AREA(#{fas})")); +/// A surface colour for an item (STYLED_ITEM chain; the styles are shared). +fn style(w: &mut Writer, item: u64, c: [f32; 3], opacity: f32) -> u64 { + let rgb = w.add("COLOUR_RGB", &[s(""), Param::Real(c[0] as f64), Param::Real(c[1] as f64), Param::Real(c[2] as f64)]); + let fasc = w.add("FILL_AREA_STYLE_COLOUR", &[s(""), r(rgb)]); + let fas = w.add("FILL_AREA_STYLE", &[s(""), refs(&[fasc])]); + let ssfa = w.add("SURFACE_STYLE_FILL_AREA", &[r(fas)]); // See-through looks add a transparency (1 = invisible) to the side style. let sides = if opacity < 1.0 { - let tr = o.add_shared(format!("SURFACE_STYLE_TRANSPARENT({})", real((1.0 - opacity as f64).clamp(0.0, 1.0)))); - format!("#{ssfa},#{tr}") + let tr = w.add("SURFACE_STYLE_TRANSPARENT", &[Param::Real((1.0 - opacity as f64).clamp(0.0, 1.0))]); + vec![ssfa, tr] } else { - format!("#{ssfa}") + vec![ssfa] }; - let sss = o.add_shared(format!("SURFACE_SIDE_STYLE('',({sides}))")); - let ssu = o.add_shared(format!("SURFACE_STYLE_USAGE(.BOTH.,#{sss})")); - let psa = o.add_shared(format!("PRESENTATION_STYLE_ASSIGNMENT((#{ssu}))")); - o.add(format!("STYLED_ITEM('color',(#{psa}),#{item})")) + let sss = w.add("SURFACE_SIDE_STYLE", &[s(""), refs(&sides)]); + let ssu = w.add("SURFACE_STYLE_USAGE", &[Param::Enum("BOTH".into()), r(sss)]); + let psa = w.add("PRESENTATION_STYLE_ASSIGNMENT", &[refs(&[ssu])]); + w.add_distinct("STYLED_ITEM", &[s("color"), refs(&[psa]), r(item)]) } /// STEP text for bodies of one part (names `Body1`…). pub fn step_export_bodies(bodies: &[ExportBody], header: &StepHeader) -> Result { + let _span = solidcraft_profile::span("kernel", "step_export_bodies"); let name = if header.file_name.is_empty() { "Part".to_string() } else { @@ -1846,10 +308,14 @@ pub fn step_export_bodies(bodies: &[ExportBody], header: &StepHeader) -> Result< #[cfg(test)] mod tests { use super::*; + use solidcore_record::Vec3; + use solidcraft_geom::prelude::*; + use solidcraft_step::p21; + use solidcraft_step::write::real; #[test] fn islands_are_solids_of_their_own_not_voids() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; let square = |a: f64, b: f64| Loop2::polygon(&[Vec2::new(a, a), Vec2::new(b, a), Vec2::new(b, b), Vec2::new(a, b)]); // A plate with a square hole, and an island inside the hole (a letter's counter). let plate = Region2 { outer: square(0.0, 30.0), holes: vec![square(10.0, 20.0).reversed()] }; @@ -1875,63 +341,6 @@ mod tests { assert_eq!(text.matches("BREP_WITH_VOIDS").count(), 1, "{text}"); } - /// #3394: a plate on four tapered legs and a straight peg. Each leg's cone and the peg's - /// cylinder are written as one face whose loop runs ring, seam, ring, seam. Readers put the - /// seam's first use on the side where the surface's angle starts and lay the next ring out - /// from there, so that ring must turn the way the angle grows (anticlockwise about the - /// written axis); three of the legs came out the other way and other readers dropped their - /// sides. - #[test] - fn seam_loops_turn_the_way_the_angle_grows() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let plate = crate::box_solid(Vec3::new(-60.0, -40.0, 0.0), Vec3::new(60.0, 40.0, 10.0)).unwrap(); - let mut b = plate; - for (x, y) in [(-45.0, -30.0), (45.0, -30.0), (45.0, 30.0), (-45.0, 30.0)] { - let disc = Region2 { outer: Loop2::circle(Vec2::new(x, y), 5.0), holes: vec![] }; - let leg = crate::extrude_tapered(&Plane::XY, &disc, 20.0, -1.0, 2f64.to_radians()).unwrap(); - b = crate::boolean(&b, &leg, crate::BoolOp::Union).unwrap().unwrap(); - } - let peg = crate::cylinder(Vec3::new(0.0, 0.0, 10.0), Vec3::Z, 4.0, 8.0).unwrap(); - b = crate::boolean(&b, &peg, crate::BoolOp::Union).unwrap().unwrap(); - let text = crate::step_export(&[&b], "test").unwrap(); - let ex = p21::parse(&text).unwrap(); - let mut seamed = 0; - for face in ex.entities.values().filter(|e| e.name() == "ADVANCED_FACE") { - let surface = ex.get(face.params().get(2).unwrap().as_ref_id().unwrap()).unwrap(); - if !matches!(surface.name(), "CONICAL_SURFACE" | "CYLINDRICAL_SURFACE") { - continue; - } - let frame = ex.get(surface.params().get(1).unwrap().as_ref_id().unwrap()).unwrap(); - let o = triple(&ex, frame.params().get(1).unwrap().as_ref_id().unwrap()); - let z = triple(&ex, frame.params().get(2).unwrap().as_ref_id().unwrap()); - for lp in face_edges(&ex, face).unwrap() { - let Some(i) = lp.iter().position(|(e, _)| lp.iter().filter(|(f, _)| f == e).count() == 2) else { continue }; - let &(edge, dir) = lp.get((i + 1) % lp.len()).unwrap(); - let p = ex.get(edge).unwrap().params(); - let (v0, v1) = (p.get(1).unwrap().as_ref_id().unwrap(), p.get(2).unwrap().as_ref_id().unwrap()); - let mut pts = edge_points(&ex, edge, 4).unwrap(); - if p.get(4).unwrap().as_bool().unwrap() != dir { - pts.reverse(); - } - let start = vertex_point(&ex, if dir { v0 } else { v1 }).unwrap(); - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - let turn = dot(cross(radial(start), radial(pts[1])), z); - assert!(turn > 0.0, "face #{:?}: the ring after the seam turns against the angle", face.params().first()); - seamed += 1; - } - } - assert_eq!(seamed, 5, "{text}"); - } - - /// A CARTESIAN_POINT's or DIRECTION's three numbers. - fn triple(ex: &p21::Exchange, id: u64) -> V3 { - let c = ex.get(id).unwrap().params().get(1).unwrap().as_list().unwrap(); - [c[0].as_f64().unwrap(), c[1].as_f64().unwrap(), c[2].as_f64().unwrap()] - } - #[test] fn numbers_and_strings() { assert_eq!(real(1.0), "1.0"); @@ -1954,8 +363,8 @@ mod tests { #[test] fn assembly_names_colours_round_trip() { use crate::{box_solid, cylinder, measure, step_import, step_validate}; - let bx = box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10.0, 20.0, 5.0)).unwrap(); - let pin = cylinder(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::Z, 2.0, 8.0).unwrap(); + let bx = box_solid(solidcore_record::Vec3::ZERO, solidcore_record::Vec3::new(10.0, 20.0, 5.0)).unwrap(); + let pin = cylinder(solidcore_record::Vec3::ZERO, solidcore_record::Vec3::Z, 2.0, 8.0).unwrap(); let rot90 = [[0.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [50.0, 0.0, 0.0, 1.0]]; let shift = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 5.0, 1.0]]; let products = vec![ @@ -1983,7 +392,7 @@ mod tests { let m: Vec<_> = imp.bodies.iter().map(|b| measure(&b.body).unwrap()).collect(); assert!((m[1].bbox.min.z - 5.0).abs() < 1e-6 && (m[1].bbox.max.z - 13.0).abs() < 1e-6); // Rotated 90° about Z and moved 50 along X: centre at (50, 0). - assert!(m[2].centroid.dist(solidcraft_geom::Vec3::new(50.0, 0.0, 4.0)) < 1e-3, "{:?}", m[2].centroid); + assert!(m[2].centroid.dist(solidcore_record::Vec3::new(50.0, 0.0, 4.0)) < 1e-3, "{:?}", m[2].centroid); // Recursion and bad placements are errors. let cyc = vec![ExportProduct { name: "A".into(), diff --git a/crates/kernel/src/surface_extend.rs b/crates/kernel/src/surface_extend.rs index 78931c3c3..e3ff4499a 100644 --- a/crates/kernel/src/surface_extend.rs +++ b/crates/kernel/src/surface_extend.rs @@ -1,58 +1,56 @@ //! Extend (Surface › Extend): boundary edges of a surface body pushed outward across their //! face, by a distance, up to a plane or a face, or (natural only) back to the surface's own -//! bounds. Three ways to continue past an edge: +//! bounds. Three ways to continue past an edge, each SMLib's extension of the surface +//! (`smlib_extend_sheet`, `SmBSplineSurface::CreateExtendedSurface`): //! -//! - natural: the face's own surface continued and the face bounded again on it. Exact for a -//! plane and a surface of revolution (cylinder, cone, sphere, torus); a B-spline surface's end -//! spans continue as their own polynomials. Each point of the edge moves along the parameter -//! line that leaves the edge square to it (in space), by the arc length asked for. -//! - tangent: a ruled run-off face along the edge, in the surface's tangent plane at each point -//! (tangent-continuous, G1). -//! - curvature: a run-off face that also keeps the surface's normal curvature across the edge -//! (curvature-continuous, G2): each section `C + s·R + ½·κ·s²·n`. +//! - natural: the surface itself continued (a B-spline's end spans as their own polynomials, +//! which keeps a plane, a cylinder or any conic section on itself); +//! - tangent: continued tangent to the surface across the edge (G1); +//! - curvature: continued keeping the surface's curvature across the edge too (G2). //! -//! The corners: where two extended edges meet, both run out along the bisector of their -//! outward directions (a mitre); next to an edge that is not extended, the extension's side -//! continues that neighbour (it is lengthened to meet the extension), or with `neighbours` off -//! runs straight out square to the edge, as it does where the edges meet smoothly. Along the -//! edge the run-out direction turns evenly between its ends, keeping the distance measured -//! square to the edge. Faces of one body extended at a corner they share use one side edge -//! there when their sides coincide, so the body's boundary stays closed. +//! The face is extended where it is its surface's whole parameter box and the edge is a whole +//! side of it: the box grows past that side, the sides next to it continue along the surface's +//! parameter lines, and the face stays one face on the extended surface. Edges picked on two +//! sides grow the box on both, meeting at the box's corner. //! -//! Refused rather than built: an extension that folds over (a concave edge pushed past its -//! centre of curvature), crosses itself, wraps all the way round its surface or runs into a -//! pole of it; edges between two faces, and edges of holes. +//! A body of several faces grows face by face, each extended alone as above and the faces sewn +//! back together. A side that lengthens is shared with the face next to it: that face grows too, +//! past its edge continuing the picked one, when the two meet tangent along the side (the faces +//! of one smooth surface, a spline's spans extruded, grow as one); across a crease it grows only +//! when that edge is picked as well, and otherwise the extension is refused (it would run past +//! the face beside it). The lengthened sides must meet again: faces whose extensions part are +//! refused. Up to a target, the face is extended +//! past it and trimmed back where the target meets it ([`crate::trim_keep`]: SMLib's exact +//! intersection). Back to the bounds is the face untrimmed to its surface's box +//! ([`crate::untrim`]). A plane's straight edges pushed out with their neighbours lengthened +//! keep the exact planar extension ([`crate::surfaces::extend`]). +//! +//! Refused rather than built: edges between two faces, edges of holes, and (not supported yet) +//! an edge that is not a whole side of its surface's box (a trimmed edge, whose extension is no +//! curve SMLib holds exactly). -use std::collections::HashMap; +use solidcraft_geom::prelude::*; +use std::collections::{BTreeMap, BTreeSet}; -use mt::{BoundedCurve, ParametricCurve, ParametricSurface}; -use solidcraft_geom::tess::EvalSurface; -use solidcraft_geom::{UnitVec3, Vec3}; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_smlib::trim::Continuation; -use crate::body::{Body, from_p3, p3}; -use crate::face_params::{FaceLoops, iso_curve, natural_span, parameters}; -use crate::record::{Rebuild, Was, rebuilt_body}; -use crate::splitface::ToolSide; -use crate::surfaces::{edge_near, surface_body}; -use crate::{KernelError, Result, SplitTool, guard}; +use crate::body::Body; +use crate::history::{Change, FaceOrigin}; +use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; +use crate::surface_trim::TrimKeep; +use crate::surfaces::Parts; +use crate::{KernelError, Result, SplitTool, record}; -/// Samples along an edge a fitted curve or run-off starts with, and the most it is refined to. -const START_SAMPLES: usize = 17; -const MAX_SAMPLES: usize = 257; /// Most edge picks. const MAX_PICKS: usize = 10_000; -/// The run-out direction may lean at most this far from square to its edge (its cosine; about -/// 84°): further, the extension would run nearly along the edge. -const MIN_COS: f64 = 0.1; -/// Edges whose directions agree this closely where they meet (about 2.6°) meet smoothly. -const SMOOTH_COS: f64 = 0.999; -/// Steps a march along the surface takes over the distance it is asked for, and the most it -/// takes. -const MARCH_STEPS: usize = 64; -const MAX_MARCH_STEPS: usize = 8192; -/// Bisection steps that place where a march meets its target. -const BISECT_STEPS: usize = 60; +/// How far past its edge, in body sizes, an extension up to a target runs before it is trimmed +/// back to the target: a target farther than that is not reached. +const REACH: f64 = 50.0; +/// Samples along an edge that find the edge nearest a pick. +const PICK_SAMPLES: usize = 32; /// How a surface continues past its edge. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -60,16 +58,16 @@ pub enum ExtendMode { /// The surface itself, continued. #[default] Natural, - /// A ruled run-off in the surface's tangent plane (G1). + /// Continued tangent to the surface across the edge (G1). Tangent, - /// A run-off following the surface's normal curvature across the edge (G2). + /// Continued keeping the surface's curvature across the edge (G2). Curvature, } /// How far an extension goes. #[derive(Clone, Copy, Debug)] pub enum ExtendLimit<'a> { - /// This far from the edge, measured across the surface square to it. + /// This far from the edge, measured across the surface. Distance(f64), /// To where it meets a plane, or the surface of a face (extended). UpTo(&'a SplitTool<'a>), @@ -83,16 +81,14 @@ pub enum ExtendLimit<'a> { pub struct ExtendOptions<'a> { pub mode: ExtendMode, pub limit: ExtendLimit<'a>, - /// Lengthen the edges next to an extended edge to meet the extension (else its sides run - /// square to the edge). + /// Lengthen the edges next to an extended edge to meet the extension. On a face that is its + /// surface's whole box those edges are parameter lines, which the extension continues. pub neighbours: bool, } -/// The boundary edges of `body` picked by points on them, extended as `opts` says. A natural -/// extension rebuilds each face on its continued surface; a run-off adds a face along each -/// edge. The result is a surface body whose history is over `[body]`: an extended face is the -/// face it was (trimmed differently) and its moved edges the edges they were moved from; a -/// run-off face is made from its edge. +/// The boundary edges of `body` picked by points on them, extended as `opts` says. The result is +/// a surface body whose history is over `[body]`: an extended face is the face it was (bounded +/// differently) and its edges the edges they continue. pub fn extend_surface(body: &Body, at: &[Vec3], opts: &ExtendOptions) -> Result { body.require_brep("extend")?; if at.is_empty() { @@ -113,1197 +109,295 @@ pub fn extend_surface(body: &Body, at: &[Vec3], opts: &ExtendOptions) -> Result< } _ => {} } + let record = crate::native::brep_record(body)?; // A plane's straight edges pushed out with their neighbours lengthened: the exact planar // extension (what designs saved before the other modes build). if let (ExtendMode::Natural, ExtendLimit::Distance(d), true) = (opts.mode, opts.limit, opts.neighbours) - && plain_planar(body) + && plain_planar(&record) { return crate::surfaces::extend(body, at, d); } - let side = match opts.limit { - ExtendLimit::UpTo(tool) => Some(ToolSide::of(tool)?), - _ => None, - }; - guard("extend", || Extension::new(body, opts, side).run(at)) + let picked = picked_edges(&record, body.size(), at)?; + match opts.limit { + ExtendLimit::Bounds => { + let faces: BTreeSet = picked.iter().map(|(_, f)| *f).collect(); + back_to_bounds(body, &faces.into_iter().collect::>()) + } + ExtendLimit::Distance(d) => continued(body, at, &picked, d, opts.mode).map(|(out, _)| out), + ExtendLimit::UpTo(tool) => up_to(body, at, &picked, tool, opts.mode), + } } /// One planar face, one loop of straight edges: what [`crate::surfaces::extend`] takes. -fn plain_planar(body: &Body) -> bool { - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); - let [face] = faces.as_slice() else { return false }; - let bounds = face.boundaries(); - let [outer] = bounds.as_slice() else { return false }; - matches!(crate::splitface::analytic_field(&face.oriented_surface()), Some(crate::splitface::Analytic::Plane { .. })) - && outer.edge_iter().all(|e| matches!(e.curve(), mt::Curve::Line(_))) +fn plain_planar(record: &brep::Brep) -> bool { + let [face] = record.faces.as_slice() else { return false }; + let [brep::Loop::Edges { edges }] = face.loops.as_slice() else { return false }; + matches!(face.surface, brep::Surface::Plane { .. } | brep::Surface::PlaneThrough { .. }) + && edges.iter().all(|u| record.edges.get(u.edge as usize).is_some_and(|e| matches!(e.curve, brep::Curve::Line { .. }))) } -/// A point of an edge with the surface's frame there. -#[derive(Clone, Copy, Debug)] -struct Local { - /// On the edge. - p: Vec3, - /// Its parameters on the surface (unwrapped along the loop). - q: [f64; 2], - /// The surface's unit normal (`S_u × S_v`, as the parameters run). - n: UnitVec3, - /// The edge's unit direction as the loop runs, in the tangent plane. - d: UnitVec3, - /// Unit, in the tangent plane, square to the edge, away from the face. - out: Vec3, - su: Vec3, - sv: Vec3, -} - -/// Where the extension of a point of an edge ends. -#[derive(Clone, Copy, Debug)] -struct Far { - /// The edge's point and frame. - at: Local, - /// The run-out direction (unit, in the tangent plane) and the run-off's length along it. - r: Vec3, - l: f64, - /// The surface's normal curvature along `r` (curvature mode). - kappa: f64, - /// The far point, and (natural) its parameters. - f: Vec3, - fq: [f64; 2], -} - -impl Far { - /// The run-off's section at `s` along it (tangent and curvature modes). - fn section(&self, s: f64) -> Vec3 { - self.at.p + self.r * s + self.at.n * (0.5 * self.kappa * s * s) - } -} - -/// A corner of the outer loop (where edge `i − 1` ends and edge `i` starts) next to an -/// extended edge: the direction the extension runs out along there, and the loop index of the -/// neighbouring edge it lengthens (when it does). -#[derive(Clone, Copy, Debug)] -struct Corner { - r: Vec3, - lengthens: Option, -} - -/// An extended edge: its loop index, curve range and the run-out angles (from square to the -/// edge, toward its direction) at its ends. -#[derive(Clone, Copy, Debug)] -struct Run { - i: usize, - t0: f64, - t1: f64, - phi0: f64, - phi1: f64, -} - -/// A face being extended: its loops in parameters and its outer loop's edges. -struct Frame { - face: mt::Face, - surface: mt::Surface, - loops: FaceLoops, - /// +1 when the outer loop runs counter-clockwise in the parameters, else −1. - ccw: f64, - edges: Vec, - chosen: Vec, -} - -impl Frame { - fn new(face: &mt::Face, ids: &[mt::EdgeID], accept: f64) -> Result { - let loops = FaceLoops::of(face, accept, "extending")?; - let outer = loops.wires.get(loops.outer).ok_or_else(|| KernelError::Invalid("the face has no boundary".into()))?; - let edges: Vec = outer.edge_iter().cloned().collect(); - let chosen: Vec = edges.iter().map(|e| ids.contains(&e.id())).collect(); - if ids.iter().any(|id| !edges.iter().any(|e| e.id() == *id)) { +/// The boundary edges the points pick, each with its face: for each point, the record edge +/// nearest it (by samples along each edge), within a twentieth of the body's size. An edge two +/// faces share, or one of a hole, is refused. +fn picked_edges(record: &brep::Brep, size: f64, at: &[Vec3]) -> Result> { + let curves: Vec = record + .edges + .iter() + .enumerate() + .map(|(i, e)| CurveEval::new(e.parameters()).map_err(|err| KernelError::Failed(format!("extend: edge {i}'s curve: {err}")))) + .collect::>()?; + let reach = size * 0.05 + 1e-6; + let mut picked = Vec::with_capacity(at.len()); + for p in at { + let mut best: Option<(f64, usize)> = None; + for (i, (e, c)) in record.edges.iter().zip(&curves).enumerate() { + let [t0, t1] = e.interval; + for k in 0..=PICK_SAMPLES { + let Some(q) = c.point(t0 + (t1 - t0) * k as f64 / PICK_SAMPLES as f64) else { continue }; + let d = q.dist(*p); + if best.is_none_or(|(b, _)| d < b) { + best = Some((d, i)); + } + } + } + let (index, edge) = match best { + Some((d, i)) if d <= reach => record.edges.get(i).map(|e| (i, e)), + _ => None, + } + .ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?; + let [only] = edge.uses.as_slice() else { + return Err(KernelError::Invalid("an edge between two faces can't be extended: pick edges on the surface's boundary".into())); + }; + // A face's first loop is its outer one (as SMLib keeps them). + if only.r#loop != 0 { return Err(KernelError::Invalid("not supported yet: extending an edge of a hole (Untrim takes holes away)".into())); } - let area = loops.loops.get(loops.outer).map_or(0.0, |l| l.area()); - if !(area.abs() > 0.0) { - return Err(KernelError::Invalid("the face has no area on its surface".into())); - } - Ok(Frame { face: face.clone(), surface: face.surface(), ccw: area.signum(), loops, edges, chosen }) - } - - fn m(&self) -> usize { - self.edges.len() - } - - /// The outer loop's edge `i` (as the loop runs) and its samples. - fn samples(&self, i: usize) -> Result<&(mt::Curve, Vec<(f64, Vec3, [f64; 2])>)> { - self.loops.loops.get(self.loops.outer).and_then(|l| l.edges.get(i)).ok_or_else(|| KernelError::Failed("extend: a loop edge".into())) - } - - /// The curve range of edge `i` (as the loop runs). - fn range(&self, i: usize) -> Result<(f64, f64)> { - Ok(self.samples(i)?.0.range_tuple()) - } - - /// The point of edge `i` at curve parameter `t`, with the surface's frame there. - fn local(&self, i: usize, t: f64, accept: f64) -> Result { - let (curve, samples) = self.samples(i)?; - let p = from_p3(curve.subs(t)); - let hint = samples.iter().min_by(|a, b| (a.0 - t).abs().total_cmp(&(b.0 - t).abs())).map(|s| s.2); - let q = parameters(&self.loops.eval, &self.loops.dom, p, hint, accept)?; - let (_, su, sv) = self.loops.eval.derivs(q[0], q[1]).ok_or_else(|| KernelError::Failed("extend: the surface at an edge".into()))?; - let n = normal(su, sv)?; - let dc = curve.der(t); - let dc = Vec3::new(dc.x, dc.y, dc.z); - let d = (dc - n * dc.dot(n)).unit().ok_or_else(|| KernelError::Invalid("an edge to extend has no direction".into()))?; - Ok(Local { p, q, n, d, out: d.cross(n) * self.ccw, su, sv }) - } - - /// The point of the surface at `q`. - fn at(&self, q: [f64; 2]) -> Result { - self.loops.eval.derivs(q[0], q[1]).map(|x| x.0).ok_or_else(|| KernelError::Failed("extend: the surface can't be evaluated there".into())) - } - - fn is_plane(&self) -> bool { - matches!(self.loops.eval, EvalSurface::Plane { .. }) + picked.push((index, only.face as usize)); } + Ok(picked) } -/// The unit normal from the parameter derivatives; refused at a pole (where it has none). -fn normal(su: Vec3, sv: Vec3) -> Result { - let c = su.cross(sv); - if !(c.len() > 1e-12 * (su.len2() + sv.len2())) { - return Err(KernelError::Invalid("the extension runs into a pole of the surface (a point with no normal)".into())); +/// The faces of `body` continued `distance` past the picked edges (`at`, which `picked` names +/// with their faces), as `mode` says, and the faces that grew. One face is extended by SMLib +/// ([`one_face`]); a body of several grows face by face ([`grown`] says which past which edges), +/// each face extended alone and the faces sewn back together, each the face it was. Faces whose +/// lengthened sides part (no longer one edge) are refused. +fn continued(body: &Body, at: &[Vec3], picked: &[(usize, usize)], distance: f64, mode: ExtendMode) -> Result<(Body, Vec)> { + if body.face_count() == 1 { + return Ok((one_face(body, at, distance, mode)?, vec![0])); } - c.unit().ok_or_else(|| KernelError::Invalid("the extension runs into a pole of the surface".into())) -} - -/// The parameter step `(a, b)` with `a·S_u + b·S_v = w` for `w` in the tangent plane, its -/// near-zero parts snapped to zero (a run along a parameter line stays on it). -fn tangent_coords(su: Vec3, sv: Vec3, w: Vec3) -> Result<[f64; 2]> { - let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv)); - let det = e * g - f * f; - if !(det.abs() > 1e-24 * (e * g).max(1e-300)) { - return Err(KernelError::Invalid("the extension runs into a pole of the surface".into())); + let r = body.record(); + let grow = grown(r, picked)?; + let mut pieces = Vec::with_capacity(grow.len() + 1); + for (&f, edges) in &grow { + let alone = crate::surfaces::taken(body, r, &[(f, false)])?; + let points = edges.iter().map(|e| edge_middle(r, *e)).collect::>>()?; + let longer = one_face(&alone, &points, distance, mode)?; + pieces.push((longer.record().clone(), vec![record::from_face(0, f, Change::Modified)])); } - let (x, y) = (w.dot(su), w.dot(sv)); - let mut ab = [(g * x - f * y) / det, (e * y - f * x) / det]; - let big = ab[0].abs().max(ab[1].abs()); - for c in &mut ab { - if c.abs() <= 1e-12 * big { - *c = 0.0; - } - } - Ok(ab) -} - -/// An extension in progress: the body, what to do, and what faces extended at shared corners -/// share. -struct Extension<'a> { - body: &'a Body, - opts: &'a ExtendOptions<'a>, - side: Option, - size: f64, - /// How far a fitted curve or run-off may stray. - tol: f64, - /// How far a boundary point may be from its surface. - accept: f64, - /// Faces using each edge. - users: HashMap, - /// The far corners made at each original vertex, and the side edges run out from it. - corners: HashMap>, - sides: HashMap>, - rec: Rebuild, -} - -impl<'a> Extension<'a> { - fn new(body: &'a Body, opts: &'a ExtendOptions<'a>, side: Option) -> Extension<'a> { - let size = body.size().max(1e-6); - let mut users: HashMap = HashMap::new(); - for f in body.solid.face_iter() { - for w in f.boundaries().iter() { - for e in w.edge_iter() { - *users.entry(e.id()).or_default() += 1; - } - } - } - Extension { - body, - opts, - side, - size, - tol: (size * 1e-6).max(1e-7), - accept: (size * 1e-5).max(1e-6), - users, - corners: HashMap::new(), - sides: HashMap::new(), - rec: Rebuild::default(), - } - } - - fn run(mut self, at: &[Vec3]) -> Result { - let faces: Vec = self.body.solid.face_iter().cloned().collect(); - // The picked edges, by the face they bound. - let mut picks: Vec<(usize, Vec)> = Vec::new(); - for p in at { - let e = edge_near(self.body, *p).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?; - if self.users.get(&e.id()).copied().unwrap_or(0) != 1 { - return Err(KernelError::Invalid("an edge between two faces can't be extended: pick edges on the surface's boundary".into())); - } - let fi = faces - .iter() - .position(|f| f.boundaries().iter().any(|w| w.edge_iter().any(|x| x.id() == e.id()))) - .ok_or_else(|| KernelError::Failed("extend: the face of an edge".into()))?; - match picks.iter_mut().find(|(f, _)| *f == fi) { - Some((_, ids)) if !ids.contains(&e.id()) => ids.push(e.id()), - Some(_) => {} - None => picks.push((fi, vec![e.id()])), - } - } - picks.sort_by_key(|(f, _)| *f); - let mut out = faces.clone(); - let mut added = Vec::new(); - for (fi, ids) in &picks { - let face = faces.get(*fi).ok_or_else(|| KernelError::Failed("extend: a face".into()))?; - let frame = Frame::new(face, ids, self.accept)?; - match self.opts.mode { - ExtendMode::Natural => { - let extended = self.natural(&frame)?; - if let Some(slot) = out.get_mut(*fi) { - *slot = extended; - } - } - ExtendMode::Tangent | ExtendMode::Curvature => added.extend(self.run_offs(&frame)?), - } - } - out.extend(added); - Ok(rebuilt_body(surface_body(out), &[&self.body.solid], &self.rec)) - } - - /// The corners of the frame's outer loop next to an extended edge (`None` elsewhere). - fn corners_of(&self, fr: &Frame) -> Result>> { - let m = fr.m(); - let mut out = Vec::with_capacity(m); - for i in 0..m { - let pi = (i + m - 1) % m; - let (pc, nc) = (fr.chosen.get(pi).copied().unwrap_or(false), fr.chosen.get(i).copied().unwrap_or(false)); - if !pc && !nc { - out.push(None); - continue; - } - let prev = fr.local(pi, fr.range(pi)?.1, self.accept)?; - let next = fr.local(i, fr.range(i)?.0, self.accept)?; - let smooth = prev.d.dot(next.d) >= SMOOTH_COS; - let (r, lengthens) = if pc && nc { - let r = (prev.out + next.out) - .normalized() - .ok_or_else(|| KernelError::Invalid("two extended edges turn back on each other at a corner".into()))?; - (r, None) - } else if pc { - if !self.opts.neighbours || smooth { (prev.out, None) } else { ((-next.d).vec(), Some(i)) } - } else if !self.opts.neighbours || smooth { - (next.out, None) - } else { - (prev.d.vec(), Some(pi)) - }; - for (chosen, l) in [(pc, &prev), (nc, &next)] { - if chosen && r.dot(l.out) < MIN_COS { - return Err(KernelError::Invalid(if lengthens.is_some() { - "an edge next to the extended edge meets it at too sharp an angle to be lengthened (extend without lengthening the neighbouring edges)".into() - } else { - "two extended edges meet at too sharp a corner".into() - })); - } - } - out.push(Some(Corner { r, lengthens })); - } - Ok(out) - } - - /// The extended edge `i` of the frame with its run-out angles from the corners at its ends. - fn run_of(&self, fr: &Frame, corners: &[Option], i: usize) -> Result { - let m = fr.m(); - let (t0, t1) = fr.range(i)?; - let (Some(Some(c0)), Some(Some(c1))) = (corners.get(i), corners.get((i + 1) % m)) else { - return Err(KernelError::Failed("extend: the corners of an edge".into())); - }; - let (a, b) = (fr.local(i, t0, self.accept)?, fr.local(i, t1, self.accept)?); - Ok(Run { i, t0, t1, phi0: c0.r.dot(a.d).atan2(c0.r.dot(a.out)), phi1: c1.r.dot(b.d).atan2(c1.r.dot(b.out)) }) - } - - /// Where the extension of edge `run` at curve parameter `t` ends. - fn far(&self, fr: &Frame, run: &Run, t: f64) -> Result { - let at = fr.local(run.i, t, self.accept)?; - let w = if run.t1 != run.t0 { (t - run.t0) / (run.t1 - run.t0) } else { 0.0 }; - let phi = run.phi0 + (run.phi1 - run.phi0) * w; - let r = at.out * phi.cos() + at.d * phi.sin(); - let reach = |cos: f64| -> f64 { - match self.opts.limit { - ExtendLimit::Distance(d) => d / cos.max(MIN_COS), - _ => 0.0, - } - }; - let ab = tangent_coords(at.su, at.sv, r)?; - match self.opts.mode { - ExtendMode::Tangent | ExtendMode::Curvature => { - let kappa = if self.opts.mode == ExtendMode::Curvature { normal_curvature(&fr.surface, at.q, ab, at.n) } else { 0.0 }; - let mut far = Far { at, r, l: 0.0, kappa, f: at.p, fq: at.q }; - far.l = match self.opts.limit { - ExtendLimit::Distance(_) => reach(phi.cos()), - ExtendLimit::UpTo(_) => self.meet(|s| Ok(far.section(s)), at.p)?, - ExtendLimit::Bounds => return Err(KernelError::Invalid("only a natural extension goes back to the surface's bounds".into())), - }; - far.f = far.section(far.l); - Ok(far) - } - ExtendMode::Natural => { - let line = |s: f64| [at.q[0] + ab[0] * s, at.q[1] + ab[1] * s]; - let s = match self.opts.limit { - ExtendLimit::Distance(_) => arc_param(fr, at.q, ab, reach(phi.cos()))?, - ExtendLimit::UpTo(_) => self.meet(|s| fr.at(line(s)), at.p)?, - ExtendLimit::Bounds => self.to_bounds(fr, at.q, ab)?, - }; - let fq = line(s); - let (f, su, sv) = - fr.loops.eval.derivs(fq[0], fq[1]).ok_or_else(|| KernelError::Failed("extend: the surface past its edge".into()))?; - normal(su, sv)?; - Ok(Far { at, r, l: s, kappa: 0.0, f, fq }) - } - } - } - - /// Where a run `point(s)` (s ≥ 0, from `start`) first crosses the target: stepped out until - /// it changes sides, then bisected; zero from a point on the target. Refused when the run - /// doesn't reach it within a generous length. - fn meet(&self, point: impl Fn(f64) -> Result, start: Vec3) -> Result { - let side = self.side.as_ref().ok_or_else(|| KernelError::Failed("extend: no target".into()))?; - let f0 = side.at(start); - if !f0.is_finite() { - return Err(KernelError::Invalid("the edge's side of the target can't be told".into())); - } - if f0.abs() <= self.tol { - return Ok(0.0); - } - let h = self.size / 16.0; - let reach = self.size * 50.0; - let (mut s, mut prev, mut walked) = (0.0, start, 0.0); - for _ in 0..MAX_MARCH_STEPS { - let next = point(s + h)?; - walked += next.dist(prev); - let f1 = side.at(next); - if f1.is_finite() && f1 * f0 <= 0.0 { - let (mut a, mut b) = (s, s + h); - for _ in 0..BISECT_STEPS { - let m = 0.5 * (a + b); - let fm = side.at(point(m)?); - if fm.is_finite() && fm * f0 > 0.0 { a = m } else { b = m } - } - return Ok(0.5 * (a + b)); - } - if walked > reach { - break; - } - (s, prev) = (s + h, next); - } - Err(KernelError::Invalid("the extension does not reach the target".into())) - } - - /// How far along the parameter line `q + s·ab` the surface's own bounds are (zero from a - /// point on them). - fn to_bounds(&self, fr: &Frame, q: [f64; 2], ab: [f64; 2]) -> Result { - let outer = fr.loops.loops.get(fr.loops.outer).ok_or_else(|| KernelError::Invalid("the face has no boundary".into()))?; - let analytic = crate::offset::surf_of(&fr.face, (self.size * 1e-7).max(1e-9) * 100.0).is_some(); - let span = natural_span(&fr.loops.eval, &fr.loops.dom, outer, analytic, self.accept)?; - let big = ab[0].abs().max(ab[1].abs()); - let mut exit = f64::INFINITY; - for (d, (lo, hi)) in span.iter().enumerate() { - let (Some(&x), Some(&dx)) = (q.get(d), ab.get(d)) else { continue }; - if dx.abs() <= 1e-9 * big { - continue; - } - let bound = if dx > 0.0 { *hi } else { *lo }; - exit = exit.min((bound - x) / dx); - } - if !exit.is_finite() { - return Err(KernelError::Invalid("the extension does not reach its surface's bounds".into())); - } - let scale = (span[0].1 - span[0].0).abs().max((span[1].1 - span[1].0).abs()) / big.max(1e-300); - Ok(if exit > 1e-9 * scale { exit } else { 0.0 }) - } - - /// The extension's far ends of edge `run` at `n` even curve parameters; refused when none - /// moves (the edge lies on its target already). - fn fars(&self, fr: &Frame, run: &Run, n: usize) -> Result> { - let fars: Vec = (0..n).map(|k| self.far(fr, run, run.t0 + (run.t1 - run.t0) * k as f64 / (n - 1) as f64)).collect::>()?; - if fars.iter().all(|f| !self.moved(f)) { - return Err(KernelError::Invalid(match self.opts.limit { - ExtendLimit::Bounds => "the edge already lies on its surface's bounds".into(), - _ => "the edge already lies on the target".into(), - })); - } - Ok(fars) - } - - /// Whether the extension moves the point at all. - fn moved(&self, f: &Far) -> bool { - f.f.dist(f.at.p) > self.tol * 10.0 - } - - /// The far corner vertex at `v` (an original vertex) for the point `p`: one made there - /// before (by this face or a neighbour) when it is at the same place. - fn corner_vertex(&mut self, v: &mt::Vertex, p: Vec3) -> mt::Vertex { - let near = self.tol * 10.0; - if from_p3(v.point()).dist(p) <= near { - return v.clone(); - } - let list = self.corners.entry(v.id()).or_default(); - if let Some(found) = list.iter().find(|x| from_p3(x.point()).dist(p) <= near) { - return found.clone(); - } - let made = mt::Vertex::new(p3(p)); - list.push(made.clone()); - made - } - - /// The side edge from the original vertex `v` to the far corner `f`, through `mid`: one made - /// before (by this face or a neighbour) along the same path, else `make`'s curve. - fn side_edge(&mut self, v: &mt::Vertex, f: &mt::Vertex, mid: Vec3, make: impl FnOnce() -> Result) -> Result { - let near = self.tol * 10.0; - if let Some(found) = self.sides.get(&v.id()).and_then(|list| { - list.iter().find(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - e.back().id() == f.id() && from_p3(c.subs(0.5 * (t0 + t1))).dist(mid) <= near * 10.0 - }) - }) { - return Ok(found.clone()); - } - let e = mt::Edge::try_new(v, f, make()?).map_err(|e| KernelError::Failed(format!("extend: a side edge: {e}")))?; - self.sides.entry(v.id()).or_default().push(e.clone()); - Ok(e) - } - - /// The face extended naturally: its surface continued and its outer loop bounded anew. - fn natural(&mut self, fr: &Frame) -> Result { - let m = fr.m(); - let corners = self.corners_of(fr)?; - let chosen = |i: usize| fr.chosen.get(i).copied().unwrap_or(false); - let runs: Vec> = - (0..m).map(|i| if chosen(i) { self.run_of(fr, &corners, i).map(Some) } else { Ok(None) }).collect::>()?; - // The far end at each corner next to an extended edge (from that edge's run). - let far_at: Vec> = (0..m) - .map(|i| match (runs.get(i).copied().flatten(), runs.get((i + m - 1) % m).copied().flatten()) { - (Some(r), _) => self.far(fr, &r, r.t0).map(Some), - (None, Some(r)) => self.far(fr, &r, r.t1).map(Some), - (None, None) => Ok(None), - }) - .collect::>()?; - // The new loop, piece by piece, in the old parameters; no side where a corner stays. - let moves = |i: usize| far_at.get(i).copied().flatten().is_some_and(|f| self.moved(&f)); - let mut pieces: Vec = Vec::new(); - for i in 0..m { - let ni = (i + 1) % m; - if chosen(i) { - if !chosen((i + m - 1) % m) && moves(i) { - pieces.push(Piece::Side { corner: i, out: true }); - } - pieces.push(Piece::Far(i)); - if !chosen(ni) && moves(ni) { - pieces.push(Piece::Side { corner: ni, out: false }); - } - } else { - pieces.push(Piece::Keep(i)); - } - } - // A kept edge on a parameter line, lengthened by the side next to it along that line, - // becomes one edge (unless another face shares it). - let mergeable = |i: usize| -> bool { - let Some(e) = fr.edges.get(i) else { return false }; - self.users.get(&e.id()).copied().unwrap_or(0) == 1 && straight(fr, i) - }; - let lengthens = |corner: usize, edge: usize| corners.get(corner).copied().flatten().and_then(|c| c.lengthens) == Some(edge); - let n = pieces.len(); - let mut dropped = vec![false; n]; - let mut merged: Vec> = vec![None; n]; - for (k, piece) in pieces.iter().enumerate() { - let Piece::Keep(i) = *piece else { continue }; - let (pk, nk) = ((k + n - 1) % n, (k + 1) % n); - if pk == k || !mergeable(i) { - continue; - } - let before = matches!(pieces.get(pk), Some(Piece::Side { corner, out: false }) if lengthens(*corner, i)); - let after = matches!(pieces.get(nk), Some(Piece::Side { corner, out: true }) if lengthens(*corner, i)); - if before || after { - for (at, yes) in [(pk, before), (nk, after)] { - if let Some(d) = dropped.get_mut(at) { - *d |= yes; - } - } - if let Some(slot) = merged.get_mut(k) { - *slot = Some(Piece::Merged { edge: i, from_far: before, to_far: after }); - } - } - } - let pieces: Vec = pieces + let rest: Vec<(usize, bool)> = (0..r.faces.len()).filter(|f| !grow.contains_key(f)).map(|f| (f, false)).collect(); + if !rest.is_empty() { + let c = Parts::of(r, &rest)?.canonical()?; + let kept = c + .faces .iter() - .enumerate() - .filter(|(k, _)| !dropped.get(*k).copied().unwrap_or(false)) - .map(|(k, p)| merged.get(k).copied().flatten().unwrap_or(*p)) - .collect(); - // Far samples of each extended edge (refined later where a curve is fitted). - let samples: Vec>> = runs - .iter() - .map(|r| match r { - Some(r) => { - let fars = self.fars(fr, r, START_SAMPLES)?; - check_no_fold(&fars)?; - Ok(Some(fars)) - } - None => Ok(None), - }) - .collect::>()?; - // The new loop as a polygon in the old parameters: checked before anything is built. - let corner_q = |i: usize| -> Result<[f64; 2]> { - far_at.get(i).copied().flatten().map(|f| f.fq).ok_or_else(|| KernelError::Failed("extend: a corner".into())) - }; - let vertex_q = |i: usize| -> Result<[f64; 2]> { - fr.samples(i).and_then(|s| s.1.first().map(|x| x.2).ok_or_else(|| KernelError::Failed("extend: a vertex".into()))) - }; - let mut poly: Vec<[f64; 2]> = Vec::new(); - for p in &pieces { - match *p { - Piece::Keep(i) => { - let s = &fr.samples(i)?.1; - poly.extend(s.iter().take(s.len().saturating_sub(1)).map(|x| x.2)); - } - Piece::Side { corner, out } => poly.push(if out { vertex_q(corner)? } else { corner_q(corner)? }), - Piece::Far(i) => { - let s = samples.get(i).and_then(|s| s.as_ref()).ok_or_else(|| KernelError::Failed("extend: far samples".into()))?; - poly.extend(s.iter().take(s.len().saturating_sub(1)).map(|f| f.fq)); - } - Piece::Merged { edge, from_far, .. } => poly.push(if from_far { corner_q(edge)? } else { vertex_q(edge)? }), - } - } - check_loop(fr, &poly)?; - // The surface continued over the new loop. - let ext = continued(&fr.surface, &fr.loops.eval, &bounds_of(&poly))?; - // The edges. - let mut wire: Vec = Vec::with_capacity(pieces.len()); - for p in &pieces { - match *p { - Piece::Keep(i) => wire.push(fr.edges.get(i).cloned().ok_or_else(|| KernelError::Failed("extend: an edge".into()))?), - Piece::Side { corner, out } => { - let far = far_at.get(corner).copied().flatten().ok_or_else(|| KernelError::Failed("extend: a corner".into()))?; - let v = fr.edges.get(corner).map(|e| e.front().clone()).ok_or_else(|| KernelError::Failed("extend: a vertex".into()))?; - let fv = self.corner_vertex(&v, far.f); - let (a, b) = (far.at.q, far.fq); - let mid = fr.at([0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1])])?; - let tol = self.tol; - let e = self.side_edge(&v, &fv, mid, || uv_line(fr, &ext, a, b, tol))?; - let lengthened = corners.get(corner).copied().flatten().and_then(|c| c.lengthens).and_then(|i| fr.edges.get(i)); - if let Some(old) = lengthened { - self.rec.piece(&e, old); - } - wire.push(if out { e } else { e.inverse() }); - } - Piece::Far(i) => { - let run = runs.get(i).copied().flatten().ok_or_else(|| KernelError::Failed("extend: a run".into()))?; - let old = fr.edges.get(i).ok_or_else(|| KernelError::Failed("extend: an edge".into()))?; - let (Some(a), Some(b)) = (far_at.get(i).copied().flatten(), far_at.get((i + 1) % m).copied().flatten()) else { - return Err(KernelError::Failed("extend: the corners of an edge".into())); - }; - let va = self.corner_vertex(old.front(), a.f); - let vb = self.corner_vertex(old.back(), b.f); - let first = samples.get(i).and_then(|s| s.as_ref()).ok_or_else(|| KernelError::Failed("extend: far samples".into()))?; - let curve = self.far_curve(fr, &ext, &run, first)?; - let e = mt::Edge::try_new(&va, &vb, curve).map_err(|e| KernelError::Failed(format!("extend: a moved edge: {e}")))?; - self.rec.piece(&e, old); - wire.push(e); - } - Piece::Merged { edge, from_far, to_far } => { - let old = fr.edges.get(edge).ok_or_else(|| KernelError::Failed("extend: an edge".into()))?; - let (a, va) = if from_far { - let f = far_at.get(edge).copied().flatten().ok_or_else(|| KernelError::Failed("extend: a corner".into()))?; - (f.fq, self.corner_vertex(old.front(), f.f)) - } else { - (vertex_q(edge)?, old.front().clone()) - }; - let (b, vb) = if to_far { - let f = far_at.get((edge + 1) % m).copied().flatten().ok_or_else(|| KernelError::Failed("extend: a corner".into()))?; - (f.fq, self.corner_vertex(old.back(), f.f)) - } else { - (vertex_q((edge + 1) % m)?, old.back().clone()) - }; - let b = unwrap_near(fr, b, a); - let curve = uv_line(fr, &ext, a, b, self.tol)?; - let e = mt::Edge::try_new(&va, &vb, curve).map_err(|e| KernelError::Failed(format!("extend: a lengthened edge: {e}")))?; - self.rec.piece(&e, old); - wire.push(e); - } - } - } - let holes = fr.loops.wires.iter().enumerate().filter(|(k, _)| *k != fr.loops.outer).map(|(_, w)| w.clone()); - let boundaries: Vec = std::iter::once(mt::Wire::from(wire)).chain(holes).collect(); - let mut f = mt::Face::try_new(boundaries, ext.surface).map_err(|e| KernelError::Failed(format!("extended face: {e}")))?; - if !fr.face.orientation() { - f.invert(); - } - self.rec.face(&f, &fr.face); - Ok(f) + .map(|p| rest.get(*p).map(|(f, _)| record::from_face(0, *f, Change::Kept))) + .collect::>>() + .ok_or_else(|| failed("sew", "a face of the rest of the body is missing"))?; + pieces.push((c.brep, kept)); } - - /// The far edge of a natural extension: exact on a parameter line (and straight on a plane), - /// else a cubic through the far points, refined until it follows them within the tolerance. - fn far_curve(&self, fr: &Frame, ext: &Continued, run: &Run, first: &[Far]) -> Result { - let (Some(a), Some(b)) = (first.first(), first.last()) else { return Err(KernelError::Failed("extend: far samples".into())) }; - if let Some(along_u) = iso(first.iter().map(|f| f.fq)) { - let (w, from, to) = if along_u { (a.fq[1], a.fq[0], b.fq[0]) } else { (a.fq[0], a.fq[1], b.fq[1]) }; - return ext.iso(along_u, w, from, to); - } - if fr.is_plane() && first.iter().all(|f| f.f.dist_to_segment(a.f, b.f) <= self.tol) { - return Ok(mt::Curve::Line(mt::Line(p3(a.f), p3(b.f)))); - } - self.fit(|t| self.far(fr, run, t).map(|f| f.f), run.t0, run.t1) - } - - /// A cubic through `point(t)` at even parameters from `t0` to `t1`, refined until it passes - /// within the tolerance of the points between its samples. - fn fit(&self, point: impl Fn(f64) -> Result, t0: f64, t1: f64) -> Result { - let mut n = START_SAMPLES; - loop { - let at = |k: f64| t0 + (t1 - t0) * k / (n - 1) as f64; - let pts: Vec = (0..n).map(|k| point(at(k as f64))).collect::>()?; - let c = crate::build::interpolate_cubic(&pts).ok_or_else(|| KernelError::Failed("extend: fitting an edge".into()))?; - let mut worst = 0.0f64; - for k in 0..n - 1 { - let u = (k as f64 + 0.5) / (n - 1) as f64; - worst = worst.max(from_p3(c.subs(u)).dist(point(at(k as f64 + 0.5))?)); - } - if worst <= self.tol { - return Ok(mt::Curve::BSplineCurve(c)); - } - if n >= MAX_SAMPLES { - return Err(KernelError::Invalid(format!("the extended edge can't be fitted closely enough (off by up to {worst:.6} mm)"))); - } - n = 2 * n - 1; - } - } - - /// The run-off faces of a tangent or curvature extension, one along each extended edge. - fn run_offs(&mut self, fr: &Frame) -> Result> { - let m = fr.m(); - let corners = self.corners_of(fr)?; - let mut out = Vec::new(); - for i in 0..m { - if !fr.chosen.get(i).copied().unwrap_or(false) { - continue; - } - let run = self.run_of(fr, &corners, i)?; - let edge = fr.edges.get(i).cloned().ok_or_else(|| KernelError::Failed("extend: an edge".into()))?; - let (surface, fars, far_curve) = self.run_off_surface(fr, &run)?; - let (Some(a), Some(b)) = (fars.first().copied(), fars.last().copied()) else { - return Err(KernelError::Failed("extend: run-off samples".into())); - }; - if !self.moved(&a) || !self.moved(&b) { - return Err(KernelError::Invalid("not supported yet: a run-off that ends at a corner already on its target".into())); - } - let (fa, fb) = (self.corner_vertex(edge.front(), a.f), self.corner_vertex(edge.back(), b.f)); - let curvature = self.opts.mode == ExtendMode::Curvature; - let side = |f: Far| -> mt::Curve { - if curvature { - let pts = vec![p3(f.at.p), p3(f.at.p + f.r * (0.5 * f.l)), p3(f.f)]; - mt::Curve::BSplineCurve(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), pts)) - } else { - mt::Curve::Line(mt::Line(p3(f.at.p), p3(f.f))) - } - }; - let start = self.side_edge(edge.front(), &fa, a.section(0.5 * a.l), || Ok(side(a)))?; - let end = self.side_edge(edge.back(), &fb, b.section(0.5 * b.l), || Ok(side(b)))?; - let far = mt::Edge::try_new(&fa, &fb, mt::Curve::BSplineCurve(far_curve)) - .map_err(|e| KernelError::Failed(format!("extend: a run-off edge: {e}")))?; - let wire: mt::Wire = vec![edge.clone(), end, far.inverse(), start.inverse()].into(); - let mut f = mt::Face::try_new(vec![wire], mt::Surface::BSplineSurface(surface.clone())) - .map_err(|e| KernelError::Failed(format!("run-off face: {e}")))?; - // Facing the way the face it runs off faces. - let mid = self.far(fr, &run, 0.5 * (run.t0 + run.t1))?; - let facing = mid.at.n * if fr.face.orientation() { 1.0 } else { -1.0 }; - let own = surface.uder(0.5, 0.0).cross(surface.vder(0.5, 0.0)); - if Vec3::new(own.x, own.y, own.z).dot(facing) < 0.0 { - f.invert(); - } - self.rec.made(&f, vec![Was::Edge(edge.id())]); - out.push(f); - } - Ok(out) - } - - /// The run-off along edge `run`: degree 1 (tangent) or 2 (curvature) across it, a cubic - /// through its sections along it, refined until it is within the tolerance of its exact - /// sections (its near side of the edge itself) between the samples; and its samples. - fn run_off_surface(&self, fr: &Frame, run: &Run) -> Result<(mt::BSplineSurface, Vec, mt::BSplineCurve)> { - let curvature = self.opts.mode == ExtendMode::Curvature; - let mut n = START_SAMPLES; - loop { - let fars = self.fars(fr, run, n)?; - check_no_fold(&fars)?; - let rows: Vec> = if curvature { - vec![ - fars.iter().map(|f| f.at.p).collect(), - fars.iter().map(|f| f.at.p + f.r * (0.5 * f.l)).collect(), - fars.iter().map(|f| f.f).collect(), - ] - } else { - vec![fars.iter().map(|f| f.at.p).collect(), fars.iter().map(|f| f.f).collect()] - }; - let curves: Vec> = rows - .iter() - .map(|r| crate::build::interpolate_cubic(r)) - .collect::>() - .ok_or_else(|| KernelError::Failed("extend: fitting a run-off".into()))?; - let ku = curves.first().map(|c| c.knot_vec().clone()).ok_or_else(|| KernelError::Failed("extend: a run-off".into()))?; - let count = curves.first().map_or(0, |c| c.control_points().len()); - let net: Vec> = (0..count).map(|k| curves.iter().filter_map(|c| c.control_points().get(k).copied()).collect()).collect(); - let surface = mt::BSplineSurface::try_new((ku, mt::KnotVec::bezier_knot(rows.len() - 1)), net) - .map_err(|e| KernelError::Failed(format!("extend: a run-off surface: {e}")))?; - let mut worst = 0.0f64; - for k in 0..n - 1 { - let u = (k as f64 + 0.5) / (n - 1) as f64; - let exact = self.far(fr, run, run.t0 + (run.t1 - run.t0) * u)?; - for sigma in [0.0, 0.5, 1.0] { - let want = exact.section(sigma * exact.l); - worst = worst.max(from_p3(surface.subs(u, sigma)).dist(want)); - } - } - if worst <= self.tol { - check_regular(&surface, n)?; - let far = curves.last().cloned().ok_or_else(|| KernelError::Failed("extend: a run-off".into()))?; - return Ok((surface, fars, far)); - } - if n >= MAX_SAMPLES { - return Err(KernelError::Invalid(format!("the run-off can't be fitted closely enough (off by up to {worst:.6} mm)"))); - } - n = 2 * n - 1; - } + let out = crate::surfaces::sheet_of(pieces, true, &[body])?; + if (out.face_count(), out.edge_count()) != (body.face_count(), body.edge_count()) { + return Err(KernelError::Invalid( + "the extended faces part along the sides they lengthen: their extensions don't meet again (extend each face on its own)".into(), + )); } + Ok((out, grow.into_keys().collect())) } -/// A piece of a naturally extended face's new outer loop. -#[derive(Clone, Copy, Debug)] -enum Piece { - /// Edge `i` of the old loop, kept. - Keep(usize), - /// The side from corner `corner`'s original vertex out to its far corner (`out`), or back. - Side { corner: usize, out: bool }, - /// Edge `i` moved out. - Far(usize), - /// Edge `edge` lengthened along its parameter line, from its start's far corner - /// (`from_far`) or vertex, to its end's far corner (`to_far`) or vertex. - Merged { edge: usize, from_far: bool, to_far: bool }, -} - -/// Whether edge `i` of the frame runs straight in the surface's parameters: along a parameter -/// line, or a straight line on a plane. -fn straight(fr: &Frame, i: usize) -> bool { - let Ok((curve, samples)) = fr.samples(i) else { return false }; - if fr.is_plane() { - return matches!(curve, mt::Curve::Line(_)); - } - iso(samples.iter().map(|s| s.2)).is_some() -} - -/// Whether the parameters all lie on one parameter line: `Some(true)` along u (v the same), -/// `Some(false)` along v. -fn iso(qs: impl Iterator + Clone) -> Option { - let span = |d: usize| -> (f64, f64) { qs.clone().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q[d]), hi.max(q[d]))) }; - let (su, sv) = (span(0), span(1)); - let (wu, wv) = (su.1 - su.0, sv.1 - sv.0); - let scale = wu.max(wv); - if !(scale > 0.0) { - return None; - } - let eps = 1e-9 * scale; - if wv <= eps && wu > eps { - Some(true) - } else if wu <= eps && wv > eps { - Some(false) - } else { - None - } -} - -/// `b` moved by whole periods to lie near `a`. -fn unwrap_near(fr: &Frame, b: [f64; 2], a: [f64; 2]) -> [f64; 2] { - [0, 1].map(|d| crate::tess::uv::unwrap(b[d], a[d], fr.loops.dom.period[d])) -} - -/// The curve along the straight parameter segment `a`–`b` (old parameters) on the continued -/// surface: exact along a parameter line or on a plane, else a fitted cubic. -fn uv_line(fr: &Frame, ext: &Continued, a: [f64; 2], b: [f64; 2], tol: f64) -> Result { - let dir = [b[0] - a[0], b[1] - a[1]]; - let big = dir[0].abs().max(dir[1].abs()); - if fr.is_plane() { - return Ok(mt::Curve::Line(mt::Line(p3(fr.at(a)?), p3(fr.at(b)?)))); - } - if dir[1].abs() <= 1e-9 * big { - return ext.iso(true, a[1], a[0], b[0]); - } - if dir[0].abs() <= 1e-9 * big { - return ext.iso(false, a[0], a[1], b[1]); - } - let point = |t: f64| fr.at([a[0] + dir[0] * t, a[1] + dir[1] * t]); - let mut n = START_SAMPLES; - loop { - let pts: Vec = (0..n).map(|k| point(k as f64 / (n - 1) as f64)).collect::>()?; - let c = crate::build::interpolate_cubic(&pts).ok_or_else(|| KernelError::Failed("extend: fitting a side edge".into()))?; - let mut worst = 0.0f64; - for k in 0..n - 1 { - let u = (k as f64 + 0.5) / (n - 1) as f64; - worst = worst.max(from_p3(c.subs(u)).dist(point(u)?)); - } - if worst <= tol { - return Ok(mt::Curve::BSplineCurve(c)); - } - if n >= MAX_SAMPLES { - return Err(KernelError::Invalid(format!("a side of the extension can't be fitted closely enough (off by up to {worst:.6} mm)"))); - } - n = 2 * n - 1; - } -} - -/// The parameter range `q + s·ab` covers from `q` for arc length `length` on the surface -/// (Simpson's rule over even steps, the last step bisected). -fn arc_param(fr: &Frame, q: [f64; 2], ab: [f64; 2], length: f64) -> Result { - let speed = |s: f64| -> Result { - let (_, su, sv) = fr - .loops - .eval - .derivs(q[0] + ab[0] * s, q[1] + ab[1] * s) - .ok_or_else(|| KernelError::Failed("extend: the surface past its edge".into()))?; - normal(su, sv)?; - Ok((su * ab[0] + sv * ab[1]).len()) - }; - // |S_u a + S_v b| = 1 at the start: steps of the length's share. - let h = length / MARCH_STEPS as f64; - let (mut s, mut walked, mut v0) = (0.0, 0.0, speed(0.0)?); - for _ in 0..MAX_MARCH_STEPS { - let (vm, v1) = (speed(s + 0.5 * h)?, speed(s + h)?); - let step = h / 6.0 * (v0 + 4.0 * vm + v1); - if walked + step >= length { - let part = |x: f64| -> Result { Ok(x / 6.0 * (v0 + 4.0 * speed(s + 0.5 * x)? + speed(s + x)?)) }; - let (mut a, mut b) = (0.0, h); - for _ in 0..BISECT_STEPS { - let mid = 0.5 * (a + b); - if walked + part(mid)? < length { a = mid } else { b = mid } - } - return Ok(s + 0.5 * (a + b)); - } - (s, walked, v0) = (s + h, walked + step, v1); - } - Err(KernelError::Invalid("the extension runs off its surface".into())) -} - -/// The surface's normal curvature along the tangent `a·S_u + b·S_v` (unit) at `q`, signed -/// toward `n`. -fn normal_curvature(s: &mt::Surface, q: [f64; 2], ab: [f64; 2], n: UnitVec3) -> f64 { - let (uu, uv, vv) = (s.uuder(q[0], q[1]), s.uvder(q[0], q[1]), s.vvder(q[0], q[1])); - let second = uu * (ab[0] * ab[0]) + uv * (2.0 * ab[0] * ab[1]) + vv * (ab[1] * ab[1]); - let k = Vec3::new(second.x, second.y, second.z).dot(n); - if k.is_finite() { k } else { 0.0 } -} - -/// Refused where the far ends run back against the edge: the extension folds over (a concave -/// edge pushed past its centre of curvature). -fn check_no_fold(fars: &[Far]) -> Result<()> { - for w in fars.windows(2) { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; - if (b.f - a.f).dot(b.at.p - a.at.p) <= 0.0 { - return Err(KernelError::Invalid( - "the extension folds over itself (a concave edge pushed past its centre of curvature): extend it less".into(), - )); - } - } - Ok(()) -} - -/// Refused where a run-off's normal turns over anywhere across it: it folds. -fn check_regular(s: &mt::BSplineSurface, n: usize) -> Result<()> { - for k in 0..n { - let u = k as f64 / (n - 1) as f64; - let base = s.uder(u, 0.0).cross(s.vder(u, 0.0)); - for j in 1..=4 { - let v = j as f64 / 4.0; - let here = s.uder(u, v).cross(s.vder(u, v)); - if !(here.x * base.x + here.y * base.y + here.z * base.z > 0.0) { - return Err(KernelError::Invalid("the extension folds over itself: extend it less".into())); - } - } - } - Ok(()) -} - -/// Refused where the new outer loop (a polygon in the old parameters) crosses itself or the -/// face's holes, or spans a whole turn of a periodic surface. -fn check_loop(fr: &Frame, poly: &[[f64; 2]]) -> Result<()> { - for d in 0..2 { - if let Some(p) = fr.loops.dom.period.get(d).copied().flatten() { - let (lo, hi) = poly.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q[d]), hi.max(q[d]))); - if hi - lo >= p * (1.0 - 1e-9) { - return Err(KernelError::Invalid("the extension would wrap all the way round its surface onto itself".into())); - } - } - } - let segs = |pts: &[[f64; 2]]| -> Vec<([f64; 2], [f64; 2])> { - let n = pts.len(); - (0..n).filter_map(|i| Some((*pts.get(i)?, *pts.get((i + 1) % n)?))).collect() - }; - let outer = segs(poly); - let n = outer.len(); - for i in 0..n { - for j in i + 2..n { - if i == 0 && j == n - 1 { - continue; - } - if let (Some(a), Some(b)) = (outer.get(i), outer.get(j)) - && crosses(*a, *b) - { - return Err(KernelError::Invalid("the extension crosses itself".into())); - } - } - } - for (k, lp) in fr.loops.loops.iter().enumerate() { - if k == fr.loops.outer { +/// The boundary edges each face grows past (by face): the `picked` ones (edge, face), and those +/// that continue a grown edge across a side it lengthens onto a face meeting its own tangent +/// there. A side lengthening along a crease onto a face that does not grow past the edge +/// continuing the grown one is refused: the extension would run past that face. +fn grown(r: &brep::Brep, picked: &[(usize, usize)]) -> Result>> { + let sides = crate::surfaces::face_sides(r); + let sign = |f: usize| sides.get(f).map(|forward| if *forward { 1.0 } else { -1.0 }); + let mut grow: BTreeMap> = BTreeMap::new(); + let mut todo = picked.to_vec(); + // (face, its edge that must grow, the creased side between): checked once all have grown. + let mut creased = Vec::new(); + let mut count = 0usize; + while let Some((e, f)) = todo.pop() { + if !grow.entry(f).or_default().insert(e) { continue; } - for h in segs(&lp.polygon()) { - if outer.iter().any(|o| crosses(*o, h)) { - return Err(KernelError::Invalid("the extension crosses a hole of its face".into())); - } + count += 1; + if count > MAX_PICKS { + return Err(KernelError::Invalid("too many edges to extend".into())); } - } - Ok(()) -} - -/// Whether two segments properly cross (touching ends don't). -fn crosses((a, b): ([f64; 2], [f64; 2]), (c, d): ([f64; 2], [f64; 2])) -> bool { - let orient = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); - let scale = [a, b, c, d].iter().map(|p| p[0].abs().max(p[1].abs())).fold(1e-300, f64::max); - let eps = 1e-12 * scale * scale; - let (o1, o2, o3, o4) = (orient(a, b, c), orient(a, b, d), orient(c, d, a), orient(c, d, b)); - ((o1 > eps && o2 < -eps) || (o1 < -eps && o2 > eps)) && ((o3 > eps && o4 < -eps) || (o3 < -eps && o4 > eps)) -} - -/// The parameter box of the points. -fn bounds_of(poly: &[[f64; 2]]) -> [(f64, f64); 2] { - let span = |d: usize| poly.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q[d]), hi.max(q[d]))); - [span(0), span(1)] -} - -/// A face's surface continued to cover a parameter box, and how its parameters relate to the -/// old ones (`new = old · scale + offset` per direction). -struct Continued { - surface: mt::Surface, - map: [(f64, f64); 2], -} - -impl Continued { - fn to_new(&self, d: usize, x: f64) -> f64 { - let (scale, offset) = self.map.get(d).copied().unwrap_or((1.0, 0.0)); - x * scale + offset - } - - /// The exact parameter line at `w` (old parameters; v = w when `along_u`) from `from` to `to`. - fn iso(&self, along_u: bool, w: f64, from: f64, to: f64) -> Result { - let (dw, dt) = if along_u { (1, 0) } else { (0, 1) }; - iso_curve(&self.surface, along_u, self.to_new(dw, w), self.to_new(dt, from), self.to_new(dt, to)) - } -} - -/// `surface` continued to cover `need` (old parameters, with a margin): a B-spline surface's -/// end spans continued as their own polynomials, a surface of revolution's profile continued -/// (a line lengthened, a B-spline profile's end spans continued); a plane as it is. Exact on the -/// old surface. -fn continued(surface: &mt::Surface, eval: &EvalSurface, need: &[(f64, f64); 2]) -> Result { - let identity = [(1.0, 0.0), (1.0, 0.0)]; - let dom = crate::tess::uv::domain(eval); - // The range each direction needs: `None` where the surface's own covers it. - let wanted = |d: usize| -> Option<(f64, f64)> { - let (lo, hi) = need.get(d).copied()?; - let (a, b) = dom.range.get(d).copied().flatten()?; - if dom.period.get(d).copied().flatten().is_some() { - return None; - } - let margin = 0.01 * (hi - lo).max(b - a); - let eps = 1e-12 * (b - a).abs().max(1e-300); - (lo < a - eps || hi > b + eps) - .then_some((lo.min(a) - if lo < a - eps { margin } else { 0.0 }, hi.max(b) + if hi > b + eps { margin } else { 0.0 })) - }; - let unsupported = || KernelError::Invalid("not supported yet: continuing this kind of surface past its bounds".into()); - match surface { - mt::Surface::Plane(_) => Ok(Continued { surface: surface.clone(), map: identity }), - mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => { - let (Some(EvalSurface::Nurbs { degree, knots, count, ctrl, .. }), rational) = - (Some(eval), matches!(surface, mt::Surface::NurbsSurface(_))) - else { - return Err(unsupported()); + for (side, at) in next_to(r, f, e)? { + let uses = &record_edge(r, side)?.uses; + let other = match uses.as_slice() { + [_] => continue, + [a, b] => [a.face, b.face].into_iter().map(|g| g as usize).find(|g| *g != f), + _ => return Err(KernelError::Invalid(format!("not supported yet: extending along edge {side}, which more than two faces share"))), }; - let [nu, nv] = *count; - // rows[i][j]: control point i along u, j along v. - let mut rows: Vec> = (0..nu).map(|i| (0..nv).filter_map(|j| ctrl.get(j * nu + i).copied()).collect()).collect(); - let [mut ku, mut kv] = knots.clone(); - if let Some(range) = wanted(0) { - (ku, rows) = continue_span(&ku, degree[0], &rows, range).ok_or_else(unsupported)?; + // A seam: the face lengthens along it on both sides at once. + let Some(g) = other else { continue }; + let cont = continuing(r, g, side, at)?; + if !matches!(record_edge(r, cont)?.uses.as_slice(), [only] if only.r#loop == 0) { + return Err(KernelError::Invalid(format!( + "not supported yet: extending past edge {e}, whose side {side} runs on into the inside of the face next to it" + ))); } - if let Some(range) = wanted(1) { - let cols = transpose(&rows); - let (k, cols) = continue_span(&kv, degree[1], &cols, range).ok_or_else(unsupported)?; - kv = k; - rows = transpose(&cols); - } - Ok(Continued { surface: nurbs_surface(ku, kv, rows, rational)?, map: identity }) - } - mt::Surface::RevolutedCurve(proc) => { - let pd = if proc.orientation() { 0 } else { 1 }; - let Some((lo, hi)) = wanted(pd) else { return Ok(Continued { surface: surface.clone(), map: identity }) }; - let rev = proc.entity(); - let (profile, map) = match rev.entity_curve() { - mt::Curve::Line(l) => { - let at = |t: f64| l.0 + (l.1 - l.0) * t; - let mut map = identity; - if let Some(slot) = map.get_mut(pd) { - *slot = (1.0 / (hi - lo), -lo / (hi - lo)); - } - (mt::Curve::Line(mt::Line(at(lo), at(hi))), map) - } - c @ (mt::Curve::BSplineCurve(_) | mt::Curve::NurbsCurve(_)) => { - let ec = crate::tess::surface::eval_curve(c).ok_or_else(unsupported)?; - let rows: Vec> = ec.ctrl.iter().map(|p| vec![*p]).collect(); - let (k, rows) = continue_span(&ec.knots, ec.degree, &rows, (lo, hi)).ok_or_else(unsupported)?; - (nurbs_curve(k, rows.iter().filter_map(|r| r.first().copied()).collect(), matches!(c, mt::Curve::NurbsCurve(_)))?, identity) - } - mt::Curve::IntersectionCurve(_) => return Err(unsupported()), - }; - let turned = proc.map_ref(|r| mt::RevolutedCurve::by_revolution(profile, r.origin(), r.axis())); - Ok(Continued { surface: mt::Surface::RevolutedCurve(turned), map }) - } - } -} - -fn transpose(rows: &[Vec<[f64; 4]>]) -> Vec> { - let width = rows.first().map_or(0, Vec::len); - (0..width).map(|j| rows.iter().filter_map(|r| r.get(j).copied()).collect()).collect() -} - -/// `a + (b − a)·t` on homogeneous points. -fn lerp4(a: [f64; 4], b: [f64; 4], t: f64) -> [f64; 4] { - [0, 1, 2, 3].map(|k| a[k] + (b[k] - a[k]) * t) -} - -/// A clamped B-spline (degree `p`, control `rows[i]` the points at index `i` along the -/// direction, across the other) continued to cover `(lo, hi)`: each end span's polynomial over -/// a longer span. `None` for one that is not clamped or malformed, or whose weights would not -/// stay positive. -fn continue_span(knots: &[f64], p: usize, rows: &[Vec<[f64; 4]>], (lo, hi): (f64, f64)) -> Option<(Vec, Vec>)> { - let (k, c) = continue_end(knots, p, rows, hi)?; - // The start: the same on the curve run backwards. - let k: Vec = k.iter().rev().map(|x| -x).collect(); - let c: Vec> = c.into_iter().rev().collect(); - let (k, c) = continue_end(&k, p, &c, -lo)?; - let k: Vec = k.iter().rev().map(|x| -x).collect(); - let c: Vec> = c.into_iter().rev().collect(); - c.iter().flatten().all(|x| x[3] > 0.0 && x.iter().all(|v| v.is_finite())).then_some((k, c)) -} - -/// [`continue_span`] at the end only: the last knot `a` below the end `b` repeated to the -/// degree (Boehm's knot insertion; the B-spline is unchanged), which leaves the last span's -/// own Bézier points; then de Casteljau's subdivision at `(to − a)/(b − a) > 1` gives the -/// Bézier points of the same polynomial over `a…to` (NURBS Book §5.2, A5.1; §1.4). -fn continue_end(knots: &[f64], p: usize, rows: &[Vec<[f64; 4]>], to: f64) -> Option<(Vec, Vec>)> { - let mut k = knots.to_vec(); - let mut c = rows.to_vec(); - if p == 0 || c.len() <= p || k.len() != c.len() + p + 1 || k.iter().any(|x| !x.is_finite()) { - return None; - } - let b = *k.last()?; - if !(to > b) { - return Some((k, c)); - } - if k.iter().rev().take(p + 1).any(|x| *x != b) || !(*k.get(c.len() - 1)? < b) { - return None; - } - let a = *k.get(c.len() - 1)?; - while k.iter().filter(|x| **x == a).count() < p { - let n = c.len(); - let span = n - 1; - let mut next = Vec::with_capacity(n + 1); - for i in 0..=n { - let row = if i + p <= span { - c.get(i)?.clone() - } else if i > span { - c.get(i - 1)?.clone() + if crate::tangent_edge::tangent_all_along(r, sign, side, crate::smooth_edges::ANGLE)? { + todo.push((cont, g)); } else { - let (ui, uip) = (*k.get(i)?, *k.get(i + p)?); - let alpha = if uip > ui { (a - ui) / (uip - ui) } else { 0.0 }; - let (pi, pm) = (c.get(i)?, c.get(i - 1)?); - pm.iter().zip(pi).map(|(y, x)| lerp4(*y, *x, alpha)).collect() - }; - next.push(row); - } - k.insert(span + 1, a); - c = next; - } - let n = c.len(); - let first = n - p - 1; - let tau = (to - a) / (b - a); - let width = c.first()?.len(); - for j in 0..width { - let mut pts: Vec<[f64; 4]> = (first..n).map(|i| c.get(i).and_then(|r| r.get(j)).copied()).collect::>()?; - let mut left = Vec::with_capacity(p + 1); - left.push(*pts.first()?); - for r in 1..=p { - for i in 0..=(p - r) { - let (x, y) = (*pts.get(i)?, *pts.get(i + 1)?); - *pts.get_mut(i)? = lerp4(x, y, tau); + creased.push((g, cont, side)); } - left.push(*pts.first()?); - } - for (i, x) in left.into_iter().enumerate() { - *c.get_mut(first + i)?.get_mut(j)? = x; } } - let len = k.len(); - for x in k.iter_mut().skip(len - p - 1) { - *x = to; + for (g, cont, side) in creased { + if !grow.get(&g).is_some_and(|edges| edges.contains(&cont)) { + return Err(KernelError::Invalid(format!( + "extending the edge lengthens its face along edge {side}, a crease with the face next to it: pick that face's edge {cont} too" + ))); + } } - Some((k, c)) + Ok(grow) } -/// A truck B-spline surface from knots and homogeneous control rows (rows[i][j], i along u): -/// rational when `rational`, else of plain points. -fn nurbs_surface(ku: Vec, kv: Vec, rows: Vec>, rational: bool) -> Result { - let kvs = (mt::KnotVec::from(ku), mt::KnotVec::from(kv)); - let bad = |e: String| KernelError::Failed(format!("extend: the continued surface: {e}")); - if rational { - let net: Vec> = rows.iter().map(|r| r.iter().map(|h| mt::Vector4::new(h[0], h[1], h[2], h[3])).collect()).collect(); - Ok(mt::Surface::NurbsSurface(mt::NurbsSurface::new(mt::BSplineSurface::try_new(kvs, net).map_err(|e| bad(e.to_string()))?))) +fn record_edge(r: &brep::Brep, e: usize) -> Result<&brep::Edge> { + r.edges.get(e).ok_or_else(|| failed("topology", format!("no edge {e}"))) +} + +/// The outer loop of face `f` and where edge `e` is in it. +fn in_outer_loop(r: &brep::Brep, f: usize, e: usize) -> Result<(&[brep::OrientedEdge], usize)> { + let face = r.faces.get(f).ok_or_else(|| failed("topology", format!("no face {f}")))?; + let Some(brep::Loop::Edges { edges }) = face.loops.first() else { return Err(failed("topology", format!("face {f} has no edge loop"))) }; + let i = edges.iter().position(|u| u.edge as usize == e).ok_or_else(|| failed("topology", format!("edge {e} is not on face {f}'s outer loop")))?; + Ok((edges, i)) +} + +/// The vertices edge use `u` runs from and to round its loop. +fn ends(r: &brep::Brep, u: &brep::OrientedEdge) -> Result<[u32; 2]> { + let [a, b] = record_edge(r, u.edge as usize)?.vertices; + Ok(if u.forward { [a, b] } else { [b, a] }) +} + +/// The sides of face `f` next to its edge `e` round its outer loop, each with the vertex it +/// shares with `e`: the edges an extension past `e` lengthens. +fn next_to(r: &brep::Brep, f: usize, e: usize) -> Result> { + let (edges, i) = in_outer_loop(r, f, e)?; + let n = edges.len(); + let (Some(prev), Some(this), Some(next)) = (edges.get((i + n - 1) % n), edges.get(i), edges.get((i + 1) % n)) else { return Ok(Vec::new()) }; + let [from, to] = ends(r, this)?; + let mut out = Vec::with_capacity(2); + for (u, v) in [(prev, from), (next, to)] { + if u.edge as usize != e && !out.iter().any(|(s, _)| *s == u.edge as usize) { + out.push((u.edge as usize, v)); + } + } + Ok(out) +} + +/// The edge of face `g`'s outer loop that meets its side `side` at vertex `at`. +fn continuing(r: &brep::Brep, g: usize, side: usize, at: u32) -> Result { + let (edges, i) = in_outer_loop(r, g, side)?; + let n = edges.len(); + let this = edges.get(i).ok_or_else(|| failed("topology", "a loop position"))?; + let [from, to] = ends(r, this)?; + let k = if from == at { + (i + n - 1) % n + } else if to == at { + (i + 1) % n } else { - let net: Vec> = - rows.iter().map(|r| r.iter().map(|h| mt::Point3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])).collect()).collect(); - Ok(mt::Surface::BSplineSurface(mt::BSplineSurface::try_new(kvs, net).map_err(|e| bad(e.to_string()))?)) + return Err(failed("topology", format!("edge {side} does not end at vertex {at}"))); + }; + match edges.get(k) { + Some(u) if u.edge as usize != side => Ok(u.edge as usize), + _ => Err(KernelError::Invalid(format!("not supported yet: extending along edge {side}, the only side of the face next to it"))), } } -/// A truck B-spline curve from knots and homogeneous control points. -fn nurbs_curve(knots: Vec, ctrl: Vec<[f64; 4]>, rational: bool) -> Result { - let kv = mt::KnotVec::from(knots); - let bad = |e: String| KernelError::Failed(format!("extend: the continued profile: {e}")); - if rational { - let pts: Vec = ctrl.iter().map(|h| mt::Vector4::new(h[0], h[1], h[2], h[3])).collect(); - Ok(mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::try_new(kv, pts).map_err(|e| bad(e.to_string()))?))) - } else { - let pts: Vec = ctrl.iter().map(|h| mt::Point3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])).collect(); - Ok(mt::Curve::BSplineCurve(mt::BSplineCurve::try_new(kv, pts).map_err(|e| bad(e.to_string()))?)) +/// The point halfway along record edge `e`. +fn edge_middle(r: &brep::Brep, e: usize) -> Result { + let edge = record_edge(r, e)?; + let c = CurveEval::new(edge.parameters()).map_err(|err| failed("edge", format!("edge {e}'s curve: {err}")))?; + c.point(0.5 * (edge.interval[0] + edge.interval[1])).ok_or_else(|| failed("edge", format!("edge {e} has no middle"))) +} + +/// The one face of `body` continued `distance` past each picked edge, as `mode` says. +fn one_face(body: &Body, at: &[Vec3], distance: f64, mode: ExtendMode) -> Result { + let how = match mode { + ExtendMode::Natural => Continuation::Natural, + ExtendMode::Tangent => Continuation::Tangent, + ExtendMode::Curvature => Continuation::Curvature, + }; + let reach = body.size() * 0.05 + 1e-6; + let (sb, ob) = smlib_body_ordered(body)?; + let mut sheet = sb.tagged(0).map_err(|e| failed("tag", e))?; + for p in at { + sheet = sheet.extend_sheet([p.x, p.y, p.z], reach, distance, how).map_err(|e| match e { + solidcraft_smlib::Error::Unsupported => KernelError::Invalid( + "not supported yet: extending an edge that is not a whole side of its surface's parameter box (a trimmed edge)".into(), + ), + solidcraft_smlib::Error::NotExact => KernelError::Invalid(format!( + "the surface cannot be extended exactly {distance} mm there: the extension would run past a pole of its surface, wrap round it, or not reach that length" + )), + solidcraft_smlib::Error::NoMatch { .. } => KernelError::Invalid(format!("no edge at {p:?}")), + e => failed("extend", e), + })?; } + let (out, order) = body_from_smlib_ordered(&sheet)?; + let history = match (ob, order) { + (Some(ob), Some(or)) => sheet.history().map_err(|e| failed("history", e))?.history(&[ob], &or).ok().map(|mut h| { + // The extended face is the face it was, bounded differently. + for f in &mut h.faces { + if f.origins.contains(&FaceOrigin::Face { operand: 0, face: 0 }) { + f.change = Change::Modified; + } + } + h + }), + _ => None, + }; + Ok(out.with_checked_history(history, &crate::record::counts(&[body]))) +} + +/// The faces extended past the target and trimmed back where the target meets them, keeping the +/// pieces the faces themselves lie in. +fn up_to(body: &Body, at: &[Vec3], picked: &[(usize, usize)], tool: &SplitTool, mode: ExtendMode) -> Result { + let (long, faces) = continued(body, at, picked, body.size().max(1e-6) * REACH, mode)?; + let inside = faces.iter().map(|f| crate::surface_untrim::face_point(body, *f)).collect::>>()?; + let cut = crate::trim_keep(&long, tool, TrimKeep::Regions(&inside))?; + Ok(crate::record::after(cut, &long, &crate::record::counts(&[body]))) +} + +/// The faces of the picked edges back on their surfaces' bounds: each untrimmed in place, its +/// holes kept. One already there is refused. +fn back_to_bounds(body: &Body, faces: &[usize]) -> Result { + let [face] = faces else { + return Err(KernelError::Invalid("not supported yet: going back to the bounds of more than one face at a time".into())); + }; + let before = crate::measure(body)?.area; + let back = crate::untrim(body, *face, crate::UntrimHoles::At(&[]), true, true)?; + let after = crate::measure(&back)?.area; + if (after - before).abs() <= 1e-9 * before.abs().max(1e-12) { + return Err(KernelError::Invalid("the edge already lies on its surface's bounds".into())); + } + Ok(back) +} + +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib extend: {what}"), e) } #[cfg(test)] mod tests { use super::*; use crate::{measure, patch_region}; - use mt::InnerSpace; - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; - use std::collections::HashSet; + use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI}; fn rel(a: f64, b: f64) -> f64 { @@ -1319,19 +413,7 @@ mod tests { with(ExtendMode::Natural, ExtendLimit::Distance(d), true) } fn edges(b: &Body) -> usize { - b.solid.edge_iter().map(|e| e.id()).collect::>().len() - } - /// Edges bounding two faces. - fn shared(b: &Body) -> usize { - let mut count: HashMap = HashMap::new(); - for f in b.solid.face_iter() { - for w in f.boundaries().iter() { - for e in w.edge_iter() { - *count.entry(e.id()).or_default() += 1; - } - } - } - count.values().filter(|n| **n == 2).count() + b.edge_count() } fn square() -> Body { let r = Region2 { @@ -1340,55 +422,22 @@ mod tests { }; patch_region(&Plane::XY, &r).unwrap() } - /// A strip of the cylinder of radius 10 about Z, heights 0…20, angles 0…`sweep`: one face on - /// an exact surface of revolution (a line turned about the axis), its edges two generators - /// and two arcs. + /// A strip of the cylinder of radius 10 about Z, heights 0…20, angles 0…`sweep`: the arc + /// extruded, one face, its edges two generators and two arcs. fn cylinder_strip(sweep: f64) -> Body { - let pt = mt::Point3::new; - let rev = mt::RevolutedCurve::by_revolution( - mt::Curve::Line(mt::Line(pt(10.0, 0.0, 0.0), pt(10.0, 0.0, 20.0))), - pt(0.0, 0.0, 0.0), - mt::Vector3::unit_z(), - ); - let s = mt::Surface::RevolutedCurve(mt::Processor::new(rev)); - // Counter-clockwise in (height, angle): up the first generator, along the top arc, down - // the last generator, back along the bottom arc. - let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, sweep), (0.0, sweep)]; - let v: Vec = corners.iter().map(|(u, a)| mt::Vertex::new(s.subs(*u, *a))).collect(); - let edges: Vec = (0..4) - .map(|i| { - let ((u0, a0), (u1, a1)) = (corners[i], corners[(i + 1) % 4]); - let c = if a0 == a1 { iso_curve(&s, true, a0, u0, u1) } else { iso_curve(&s, false, u0, a0, a1) }; - mt::Edge::new(&v[i], &v[(i + 1) % 4], c.unwrap()) - }) - .collect(); - surface_body(vec![mt::Face::new(vec![edges.into()], s)]) + let arc = vec![Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: 10.0, start: 0.0, sweep }]; + crate::extrude_sheet(&Plane::XY, &[arc], 0.0, 20.0).unwrap() } /// Arc length of z = x²/20 from 0 to x. fn parabola_arc(x: f64) -> f64 { 0.5 * x * (1.0 + (x / 10.0).powi(2)).sqrt() + 5.0 * (x / 10.0).asinh() } - /// The parabolic sheet z = x²/20 over 0 ≤ x, y ≤ 10: a B-spline quadratic along x (u), - /// straight along y (v), its four edges on its parameter lines. + /// The parabolic sheet z = x²/20 over 0 ≤ x, y ≤ 10: the parabola (a quadratic Bézier, + /// sketched on the plane y = 0 whose sketch y is −z) extruded 10 along y. fn parabola() -> Body { - let pt = mt::Point3::new; - let net = vec![ - vec![pt(0.0, 0.0, 0.0), pt(0.0, 10.0, 0.0)], - vec![pt(5.0, 0.0, 0.0), pt(5.0, 10.0, 0.0)], - vec![pt(10.0, 0.0, 5.0), pt(10.0, 10.0, 5.0)], - ]; - let s = mt::BSplineSurface::new((mt::KnotVec::bezier_knot(2), mt::KnotVec::bezier_knot(1)), net); - let v = [pt(0.0, 0.0, 0.0), pt(10.0, 0.0, 5.0), pt(10.0, 10.0, 5.0), pt(0.0, 10.0, 0.0)].map(mt::Vertex::new); - let bez = - |a: mt::Point3, m: mt::Point3, b: mt::Point3| mt::Curve::BSplineCurve(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![a, m, b])); - let edges = vec![ - mt::Edge::new(&v[0], &v[1], bez(pt(0.0, 0.0, 0.0), pt(5.0, 0.0, 0.0), pt(10.0, 0.0, 5.0))), - mt::Edge::new(&v[1], &v[2], mt::Curve::Line(mt::Line(v[1].point(), v[2].point()))), - mt::Edge::new(&v[2], &v[3], bez(pt(10.0, 10.0, 5.0), pt(5.0, 10.0, 0.0), pt(0.0, 10.0, 0.0))), - mt::Edge::new(&v[3], &v[0], mt::Curve::Line(mt::Line(v[3].point(), v[0].point()))), - ]; - surface_body(vec![mt::Face::new(vec![edges.into()], mt::Surface::BSplineSurface(s))]) + let p = vec![Seg2::Conic { a: Vec2::new(0.0, 0.0), apex: Vec2::new(5.0, 0.0), b: Vec2::new(10.0, -5.0), w: 1.0 }]; + crate::extrude_sheet(&Plane::XZ, &[p], 0.0, 10.0).unwrap() } /// The default (natural, by a distance, neighbours lengthened) on a plane's straight edges @@ -1414,34 +463,11 @@ mod tests { assert!((bb.max.x - 17.0).abs() < 1e-9, "{bb:?}"); } - /// A quadrilateral (0,0), (10,0), (10,10), (0,20) (area 150) with its right edge pushed out - /// by 5. Lengthening the neighbours follows the slanted top down to (15, 5): + 37.5. Without - /// them the extension is a 5 × 10 strip: + 50. A tangent run-off is the same trapezoid as a - /// face of its own, sharing the edge. - #[test] - fn neighbours_lengthened_or_square() { - let r = Region2 { - outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 20.0)]), - holes: vec![], - }; - let q = patch_region(&Plane::XY, &r).unwrap(); - let at = [Vec3::new(10.0, 5.0, 0.0)]; - let lengthened = extend_surface(&q, &at, &natural(5.0)).unwrap(); - assert!(rel(area(&lengthened), 187.5) < 1e-9, "{}", area(&lengthened)); - let square_ends = extend_surface(&q, &at, &with(ExtendMode::Natural, ExtendLimit::Distance(5.0), false)).unwrap(); - assert!(rel(area(&square_ends), 200.0) < 1e-9, "{}", area(&square_ends)); - let run_off = extend_surface(&q, &at, &with(ExtendMode::Tangent, ExtendLimit::Distance(5.0), true)).unwrap(); - assert_eq!((run_off.face_count(), shared(&run_off)), (2, 1)); - assert!(rel(area(&run_off), 187.5) < 1e-6, "{}", area(&run_off)); - let h = run_off.history().unwrap(); - assert_eq!(h.faces.iter().map(|f| f.change).collect::>(), vec![crate::history::Change::Kept, crate::history::Change::Generated]); - } - - /// A cylinder strip (radius 10, a quarter turn, heights 0…20), on an exact surface of - /// revolution: extended 5 along its axis (its top arc picked), 10 · π/2 · 25; 5 around its - /// circumference (a straight edge picked), 10 · (π/2 + ½) · 20; both, meeting at a mitre, - /// 10 · (π/2 + ½) · 25; up to the plane z = 30, 10 · π/2 · 30. Each stays one cylindrical - /// face; the sides along the extension are the old edges lengthened. + /// A cylinder strip (radius 10, a quarter turn, heights 0…20): extended 5 along its axis + /// (its top arc picked), 10 · π/2 · 25; 5 around its circumference (a straight edge + /// picked), 10 · (π/2 + ½) · 20; both, meeting at the box's corner, 10 · (π/2 + ½) · 25; up + /// to the plane z = 30, 10 · π/2 · 30. Each stays one cylindrical face; the sides along the + /// extension are the old edges lengthened. #[test] fn a_cylinder_strip_extended_along_its_axis_and_around() { let c = cylinder_strip(FRAC_PI_2); @@ -1483,8 +509,7 @@ mod tests { /// continue as themselves, so the extension stays on the cylinder. #[test] fn an_extruded_cylinder_strip_continues_on_its_cylinder() { - let arc = vec![Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: 10.0, start: 0.0, sweep: FRAC_PI_2 }]; - let sheet = crate::extrude_sheet(&Plane::XY, &[arc], 0.0, 20.0).unwrap(); + let sheet = cylinder_strip(FRAC_PI_2); let top = Vec3::new(10.0 * FRAC_PI_4.cos(), 10.0 * FRAC_PI_4.sin(), 20.0); let up = extend_surface(&sheet, &[top], &natural(5.0)).unwrap(); let want = 10.0 * FRAC_PI_2 * 25.0; @@ -1495,51 +520,15 @@ mod tests { assert!(matches!(crate::face_surface(&round, 0), Some(crate::FaceSurface::Cylinder { radius, .. }) if (radius - 10.0).abs() < 1e-6)); } - /// A half cylinder pushed round by 40 mm would close on itself (π + 4 > 2π): refused. So - /// is a concave edge pushed past its centre. + /// The parabolic B-spline sheet z = x²/20 (0 ≤ x, y ≤ 10) extended 5 past its edge x = 10, + /// naturally: the parabola itself continues, 5 mm of arc further (to x* where its arc + /// length grows by 5): area 10 · (s(10) + 5), reaching z = x*²/20. #[test] - fn self_intersecting_extensions_are_refused() { - let c = cylinder_strip(PI); - let side = Vec3::new(-10.0, 0.0, 10.0); - let e = extend_surface(&c, &[side], &natural(40.0)).unwrap_err().to_string(); - assert!(e.contains("wrap"), "{e}"); - // A 20 × 10 plate with a half-round notch of radius 5 in its top: the notch's edge - // pushed out by 2 leaves a notch of radius 3 (area 200 − 4.5π, the top edges - // lengthened into it); by 6, past the notch's centre, it folds and is refused. - let outer = Loop2 { - segs: vec![ - Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(20.0, 0.0) }, - Seg2::Line { a: Vec2::new(20.0, 0.0), b: Vec2::new(20.0, 10.0) }, - Seg2::Line { a: Vec2::new(20.0, 10.0), b: Vec2::new(15.0, 10.0) }, - Seg2::Arc { center: Vec2::new(10.0, 10.0), radius: 5.0, start: 0.0, sweep: -PI }, - Seg2::Line { a: Vec2::new(5.0, 10.0), b: Vec2::new(0.0, 10.0) }, - Seg2::Line { a: Vec2::new(0.0, 10.0), b: Vec2::new(0.0, 0.0) }, - ], - }; - let plate = patch_region(&Plane::XY, &Region2 { outer, holes: vec![] }).unwrap(); - assert!(rel(area(&plate), 200.0 - 12.5 * PI) < 1e-4); // (measured on meshes) - let notch = [Vec3::new(10.0, 5.0, 0.0)]; - let less = extend_surface(&plate, ¬ch, &natural(2.0)).unwrap(); - assert!(rel(area(&less), 200.0 - 4.5 * PI) < 1e-4, "{} vs {}", area(&less), 200.0 - 4.5 * PI); // (measured on meshes) - for mode in [ExtendMode::Natural, ExtendMode::Tangent, ExtendMode::Curvature] { - let e = extend_surface(&plate, ¬ch, &with(mode, ExtendLimit::Distance(6.0), true)).unwrap_err().to_string(); - assert!(e.contains("folds") || e.contains("crosses"), "{mode:?}: {e}"); - } - } - - /// The parabolic B-spline sheet z = x²/20 (0 ≤ x, y ≤ 10) extended 5 past its edge x = 10. - /// Natural: the parabola itself continues, 5 mm of arc further (to x* where its arc length - /// grows by 5): area 10 · (s(10) + 5), reaching z = x*²/20. Curvature: a run-off face along - /// the edge, its normal and its normal curvature across the edge those of the parabola - /// there (G1, G2: κ = 0.1 / 2^1.5), area 10 · ∫₀⁵ √(1 + κ²s²) ds more. Tangent: a plane - /// run-off, 50 more. - #[test] - fn a_bspline_extended_naturally_and_by_curvature() { + fn a_bspline_extended_naturally() { let p = parabola(); let base = 10.0 * parabola_arc(10.0); assert!(rel(area(&p), base) < 1e-4, "{} vs {base}", area(&p)); // (measured on meshes) let edge = [Vec3::new(10.0, 5.0, 5.0)]; - let nat = extend_surface(&p, &edge, &natural(5.0)).unwrap(); let (mut lo, mut hi) = (10.0, 20.0); for _ in 0..100 { @@ -1551,63 +540,6 @@ mod tests { assert!((bb.max.x - x).abs() < 1e-6 && (bb.max.z - x * x / 20.0).abs() < 1e-6, "{bb:?} vs x* = {x}"); assert!(rel(area(&nat), base + 50.0) < 1e-4, "{} vs {}", area(&nat), base + 50.0); // (measured on meshes) assert_eq!(nat.face_count(), 1); - // On the extended surface the parabola goes on: its height at x = 12, past the old edge. - let s = nat.solid.face_iter().next().unwrap().surface(); - let (u, v) = mt::SearchNearestParameter::::search_nearest_parameter(&s, mt::Point3::new(12.0, 5.0, 7.2), None, 100).unwrap(); - let off = from_p3(s.subs(u, v)).dist(Vec3::new(12.0, 5.0, 7.2)); - assert!(off < 1e-7, "{off}"); - - let kappa = 0.1 / 2f64.powf(1.5); - let curv = extend_surface(&p, &edge, &with(ExtendMode::Curvature, ExtendLimit::Distance(5.0), true)).unwrap(); - assert_eq!((curv.face_count(), shared(&curv)), (2, 1)); - let arc = 2.5 * (1.0 + 25.0 * kappa * kappa).sqrt() + (5.0 * kappa).asinh() / (2.0 * kappa); - assert!(rel(area(&curv), base + 10.0 * arc) < 1e-4, "{} vs {}", area(&curv), base + 10.0 * arc); // (measured on meshes) - // G1 and G2 at the old edge, measured on the run-off along its length. - let run = curv.solid.face_iter().nth(1).unwrap().surface(); - let up = mt::Vector3::new(-1.0, 0.0, 1.0) / 2f64.sqrt(); - for k in 0..=8 { - let u = k as f64 / 8.0; - let (su, sv) = (run.uder(u, 0.0), run.vder(u, 0.0)); - let n = su.cross(sv).normalize(); - let n = if n.dot(up) < 0.0 { -n } else { n }; - assert!((n - up).magnitude() < 1e-6, "normal {n:?} at {u}"); - let k_across = run.vvder(u, 0.0).dot(up) / sv.magnitude2(); - assert!(rel(k_across, kappa) < 1e-6, "κ {k_across} vs {kappa} at {u}"); - } - - let flat = extend_surface(&p, &edge, &with(ExtendMode::Tangent, ExtendLimit::Distance(5.0), true)).unwrap(); - assert!(rel(area(&flat), base + 50.0) < 1e-4, "{} vs {}", area(&flat), base + 50.0); // (measured on meshes) - let run = flat.solid.face_iter().nth(1).unwrap().surface(); - let n = run.uder(0.5, 0.0).cross(run.vder(0.5, 0.0)).normalize(); - assert!(n.cross(up).magnitude() < 1e-6, "G1: {n:?}"); - } - - /// A disc of radius 5 (two half-circle edges meeting smoothly) with both edges pushed out - /// by 2: naturally, one disc of radius 7 (49π); as tangent run-offs, an annulus of two - /// faces sharing their sides where the half circles meet (25π + 24π). - #[test] - fn a_disc_grows_by_its_curved_edges() { - let disc = patch_region(&Plane::XY, &Region2 { outer: Loop2::circle(Vec2::ZERO, 5.0), holes: vec![] }).unwrap(); - let both = [Vec3::new(0.0, 5.0, 0.0), Vec3::new(0.0, -5.0, 0.0)]; - let grown = extend_surface(&disc, &both, &natural(2.0)).unwrap(); - assert_eq!(grown.face_count(), 1); - assert!(rel(area(&grown), 49.0 * PI) < 1e-4, "{} vs {}", area(&grown), 49.0 * PI); // (measured on meshes) - let ring = extend_surface(&disc, &both, &with(ExtendMode::Tangent, ExtendLimit::Distance(2.0), true)).unwrap(); - assert_eq!((ring.face_count(), shared(&ring)), (3, 4)); - assert!(rel(area(&ring), 49.0 * PI) < 1e-4, "{} vs {}", area(&ring), 49.0 * PI); // (measured on meshes) - } - - /// Two faces of a box (its top and front, sharing their edge along x) with their edges at - /// x = 10 pushed out by 5: the shared edge is lengthened in both, as one edge, so the two - /// extensions stay joined: 150 + 150, two shared edges. - #[test] - fn neighbouring_faces_extend_together() { - let b = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); - let two = crate::copy_faces(&b, &[Vec3::new(5.0, 5.0, 10.0), Vec3::new(5.0, 0.0, 5.0)]).unwrap(); - assert_eq!((two.face_count(), shared(&two)), (2, 1)); - let out = extend_surface(&two, &[Vec3::new(10.0, 5.0, 10.0), Vec3::new(10.0, 0.0, 5.0)], &natural(5.0)).unwrap(); - assert!(rel(area(&out), 300.0) < 1e-9, "{}", area(&out)); - assert_eq!((out.face_count(), shared(&out)), (2, 2)); } /// Back to the surface's own bounds: the half saddle (a B-spline over 0…10 × 0…10, x from 0 @@ -1615,14 +547,11 @@ mod tests { /// from z = 15 down to 10 and back) goes back to its span, heights 0…15: 150π. #[test] fn extended_back_to_the_surfaces_bounds() { - let pt = |x: f64, y: f64| mt::Point3::new(x, y, x * y / 10.0); - let knots = mt::KnotVec::bezier_knot(1); - let saddle = mt::BSplineSurface::new((knots.clone(), knots), vec![vec![pt(0.0, 0.0), pt(0.0, 10.0)], vec![pt(10.0, 0.0), pt(10.0, 10.0)]]); - let corners = [pt(0.0, 0.0), pt(5.0, 0.0), pt(5.0, 10.0), pt(0.0, 10.0)]; - let v: Vec = corners.iter().map(|p| mt::Vertex::new(*p)).collect(); - let e: Vec = - (0..4).map(|i| mt::Edge::new(&v[i], &v[(i + 1) % 4], mt::Curve::Line(mt::Line(corners[i], corners[(i + 1) % 4])))).collect(); - let half = surface_body(vec![mt::Face::new(vec![e.into()], mt::Surface::BSplineSurface(saddle))]); + let front = (Plane::XZ, vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) }]); + let back = (Plane { origin: Vec3::new(0.0, 10.0, 0.0), ..Plane::XZ }, vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, -10.0) }]); + let saddle = crate::loft_sheet(&[front, back]).unwrap(); + let cut = SplitTool::Plane(Plane::from_normal(Vec3::new(5.0, 0.0, 0.0), Vec3::X).unwrap()); + let half = crate::trim(&saddle, &cut, Vec3::new(1.0, 5.0, 0.5)).unwrap(); let bounds = with(ExtendMode::Natural, ExtendLimit::Bounds, true); let whole = extend_surface(&half, &[Vec3::new(5.0, 5.0, 2.5)], &bounds).unwrap(); let bb = measure(&whole).unwrap().bbox; @@ -1640,6 +569,57 @@ mod tests { assert!((measure(&back).unwrap().bbox.max.z - 15.0).abs() < 1e-6); } + /// Three cubic spans of a spline meeting tangent, extruded 0…20 along Z: a sheet of three + /// faces, as a fit-point spline's surface is (#3830). + fn spline_spans() -> Body { + let v = Vec2::new; + let c = |p0, p1, p2, p3| Seg2::Cubic { p0, p1, p2, p3 }; + let chain = vec![ + c(v(0.0, 0.0), v(5.0, 0.0), v(10.0, 5.0), v(15.0, 5.0)), + c(v(15.0, 5.0), v(20.0, 5.0), v(25.0, 0.0), v(30.0, 0.0)), + c(v(30.0, 0.0), v(35.0, 0.0), v(40.0, 5.0), v(45.0, 5.0)), + ]; + crate::extrude_sheet(&Plane::XY, &[chain], 0.0, 20.0).unwrap() + } + + /// A sheet of several faces grows face by face (#3830): its end edge (the last span's + /// generator) 10 further, the last span continued, 10 · 20 more; the middle span's top edge + /// 5 up takes its tangent neighbours with it, the whole spline 25 tall. The faces stay three, + /// sewn as before, each the face it was. + #[test] + fn a_sheet_of_tangent_faces_grows_face_by_face() { + let s = spline_spans(); + assert_eq!(s.face_count(), 3); + let base = area(&s); + let end = extend_surface(&s, &[Vec3::new(45.0, 5.0, 10.0)], &natural(10.0)).unwrap(); + assert!(rel(area(&end), base + 200.0) < 1e-4, "{} vs {}", area(&end), base + 200.0); // (measured on meshes) + assert_eq!((end.face_count(), edges(&end)), (3, edges(&s))); + assert!(measure(&end).unwrap().bbox.max.x > 50.0, "{:?}", measure(&end).unwrap().bbox); + let h = end.history().unwrap(); + let changes: Vec = h.faces.iter().map(|f| f.change).collect(); + assert_eq!(changes.iter().filter(|c| **c == Change::Modified).count(), 1, "{changes:?}"); + + let up = extend_surface(&s, &[Vec3::new(22.5, 2.5, 20.0)], &natural(5.0)).unwrap(); + assert!(rel(area(&up), base * 25.0 / 20.0) < 1e-4, "{} vs {}", area(&up), base * 25.0 / 20.0); // (measured on meshes) + assert_eq!((up.face_count(), edges(&up)), (3, edges(&s))); + assert!((measure(&up).unwrap().bbox.max.z - 25.0).abs() < 1e-6); + } + + /// Across a crease the face next door grows only when its edge is picked too: an L of two + /// planes, one top edge refused (it would run past the other wall), both 5 up, 25 · 20. + #[test] + fn a_crease_grows_only_when_both_edges_are_picked() { + let l = + vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) }, Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 10.0) }]; + let s = crate::extrude_sheet(&Plane::XY, &[l], 0.0, 20.0).unwrap(); + assert_eq!(s.face_count(), 2); + let e = extend_surface(&s, &[Vec3::new(5.0, 0.0, 20.0)], &natural(5.0)).unwrap_err(); + assert!(e.to_string().contains("crease"), "{e}"); + let both = extend_surface(&s, &[Vec3::new(5.0, 0.0, 20.0), Vec3::new(10.0, 5.0, 20.0)], &natural(5.0)).unwrap(); + assert!(rel(area(&both), 500.0) < 1e-9, "{}", area(&both)); + assert_eq!((both.face_count(), edges(&both)), (2, edges(&s))); + } + /// Hostile and unsupported requests are refused, never panic. #[test] fn hostile_requests_are_refused() { @@ -1668,27 +648,4 @@ mod tests { let behind = SplitTool::Plane(Plane::from_normal(Vec3::new(-5.0, 0.0, 0.0), Vec3::X).unwrap()); assert!(extend_surface(&s, &at, &with(ExtendMode::Natural, ExtendLimit::UpTo(&behind), true)).is_err()); } - - /// Continuing a B-spline's end span leaves it the same on its old range. - #[test] - fn a_continued_bspline_is_unchanged_on_its_range() { - // A cubic with interior knots, rational weights. - let knots = vec![0.0, 0.0, 0.0, 0.0, 0.3, 0.6, 1.0, 1.0, 1.0, 1.0]; - let ctrl: Vec> = - [[0.0, 0.0, 0.0, 1.0], [1.0, 2.0, 0.0, 0.8], [2.0, -1.0, 1.0, 1.2], [3.0, 1.0, 0.5, 1.0], [4.0, 0.0, 2.0, 0.9], [5.0, 1.0, 0.0, 1.0]] - .iter() - .map(|p| vec![[p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]]) - .collect(); - let before = solidcraft_geom::tess::EvalCurve { degree: 3, knots: knots.clone(), ctrl: ctrl.iter().map(|r| r[0]).collect() }; - let (k, c) = continue_span(&knots, 3, &ctrl, (-0.2, 1.25)).unwrap(); - let after = solidcraft_geom::tess::EvalCurve { degree: 3, knots: k.clone(), ctrl: c.iter().map(|r| r[0]).collect() }; - assert_eq!((k.first().copied(), k.last().copied()), (Some(-0.2), Some(1.25))); - // The same curve on the old range, and past it the old end spans' own polynomials - // (which the evaluator also continues). - for i in -4..=25 { - let t = i as f64 / 20.0; - let (a, b) = (before.eval(t).unwrap().0, after.eval(t).unwrap().0); - assert!(a.dist(b) < 1e-9, "{t}: {a:?} vs {b:?}"); - } - } } diff --git a/crates/kernel/src/surface_kind.rs b/crates/kernel/src/surface_kind.rs index c601536a3..d7af0187b 100644 --- a/crates/kernel/src/surface_kind.rs +++ b/crates/kernel/src/surface_kind.rs @@ -1,12 +1,13 @@ //! What surface a face lies on (plane, cylinder, cone, sphere, torus), for construction //! geometry: axes through round faces, centres of spheres and tori. -use solidcraft_geom::{UnitVec3, Vec3}; - -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{Brep, Curve}; +use solidcraft_geom::UnitVec3; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::prelude::*; use crate::Body; -use crate::body::from_p3; use crate::offset::{Surf, surf_of}; /// A face's analytic surface. @@ -33,8 +34,6 @@ pub enum FaceSurface { radius: f64, }, /// Centre of the ring, its axis, the ring (major) and tube (minor) radii. - /// `major` is signed: negative on a spindle torus's inner sheet, whose tube centre - /// lies across the axis from the face (a revolved barrel). Torus { center: Vec3, axis: UnitVec3, @@ -45,13 +44,15 @@ pub enum FaceSurface { /// The surface of face `face` (in face order), if it is one of the analytic kinds. pub fn face_surface(b: &Body, face: usize) -> Option { - surface_of(b.solid.face_iter().nth(face)?, b.size()) + if b.is_mesh() { + return None; + } + surface_of(b.record(), face) } -/// The analytic surface of face `f` of a body whose box diagonal is `size`. -pub(crate) fn surface_of(f: &mt::Face, size: f64) -> Option { - let tol = (size * 1e-7).max(1e-9) * 100.0; - Some(match surf_of(f, tol)? { +/// The analytic surface of face `face` of the record `b`, as the record holds it. +pub(crate) fn surface_of(b: &Brep, face: usize) -> Option { + Some(match surf_of(b, face)? { Surf::Plane { n, d } => FaceSurface::Plane { normal: n.unit()?, point: n * d }, Surf::Cylinder { o, a, r, .. } => FaceSurface::Cylinder { origin: o, axis: a.unit()?, radius: r }, Surf::Cone { v, a, half, .. } => FaceSurface::Cone { apex: v, axis: a.unit()?, half_angle: half }, @@ -75,24 +76,30 @@ pub struct EdgeCircle { } /// The circle edge `edge` (in the order of [`Body::edges`] and the tessellated mesh's edges) -/// lies on, if its curve is a circle or an arc of one. `None` for other curves, mesh bodies -/// and an index out of range. +/// lies on, if its curve is a circle or an arc of one: exactly from a circle record, and for any +/// other curve when its points all lie on one circle (a circle held as a rational spline). `None` +/// for other curves, mesh bodies and an index out of range. pub fn edge_circle(b: &Body, edge: usize) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - if b.mesh.is_some() { + if b.is_mesh() { return None; } - let e = Body::unique_edges(&b.solid).into_iter().nth(edge)?; + let record = b.record(); + let e = record.edges.get(edge)?; + let c = CurveEval::new(e.parameters()).ok()?; + let [t0, t1] = e.interval; + let (start, end) = (c.point(t0)?, c.point(t1)?); + if let Curve::Circle { frame, radius } = &e.curve { + // The edge runs counter-clockwise about the frame's z from its start to its end, over the + // angles of its interval on the circle itself (a NURBS form is parameterised otherwise). + let axis = Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis)).unit()?; + let closed = e.vertices[0] == e.vertices[1]; + let [a0, a1] = solidcraft_geom::brep::label::edge_curve_interval(e)?; + let angle = if closed { std::f64::consts::TAU } else { (a1 - a0).min(std::f64::consts::TAU) }; + return Some(EdgeCircle { center: Vec3::from(frame.origin), axis, radius: *radius, start, end, angle }); + } let tol = (b.size() * 1e-7).max(1e-9) * 100.0; - crate::guard("edge circle", || { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let at = |f: f64| from_p3(c.subs(t0 + (t1 - t0) * f)); - let samples: Vec = (0..=24).map(|i| at(f64::from(i) / 24.0)).collect(); - Ok(circle_through(&samples, tol)) - }) - .ok() - .flatten() + let samples: Vec = (0..=24).map(|i| c.point(t0 + (t1 - t0) * f64::from(i) / 24.0)).collect::>()?; + circle_through(&samples, tol) } /// The circle through evenly spaced samples of a curve (first to last), if they all lie on one. diff --git a/crates/kernel/src/surface_offset.rs b/crates/kernel/src/surface_offset.rs index a4b523552..bbe565ab4 100644 --- a/crates/kernel/src/surface_offset.rs +++ b/crates/kernel/src/surface_offset.rs @@ -1,114 +1,17 @@ //! Offset surfaces (Surface › Offset): faces of a body copied out at a signed distance along -//! their normals, as a new surface body. Planes and circular cylinders move exactly (as Thicken -//! moves them); any other face gets a B-spline surface fitted through offset samples on a grid, -//! refined until it is within a tolerance of the true offset everywhere it is checked. An -//! offset as deep as a face's smallest concave radius would fold it over, and is refused, -//! naming that radius. Neighbouring faces moved to the same place along their shared edge -//! (meeting smoothly) keep sharing it; across a sharp edge they come apart. Faces that close up -//! make a solid. +//! their normals, as a new surface body. Each face goes onto its surface's offset, SMLib's exact +//! offset (`smlib_offset_sheet`) of the face on its own; the offsets are then stitched where they +//! meet within the tolerance, so neighbouring faces moved to the same place along their shared +//! edge (meeting smoothly) keep sharing it, and across a sharp edge they come apart. Faces that +//! close up make a solid. An offset SMLib cannot make (one that would fold a face over) is its +//! error, never a fitted surface. -use std::collections::HashMap; - -use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::{Grid, Vec3}; -use truck_modeling as mt; - -use crate::body::{Body, from_p3, p3}; -use crate::build::interpolate_net; -use crate::history::FaceOrigin; -use crate::surfaces::{Offset, map_curve, map_surface, surface_body}; -use crate::{KernelError, Result, guard}; - -/// Grid samples a side of a fitted offset starts with, and the most it is refined to. -const START_GRID: usize = 12; -const MAX_GRID: usize = 96; -/// Samples along an edge of a fitted offset. -const EDGE_SAMPLES: usize = 33; - -/// How one face moves along its normals: exactly (a plane, a circular cylinder) or onto -/// surfaces fitted for the distances it was made for. Shared by Offset Surface and Thicken. -pub(crate) struct FaceMover { - face: mt::Face, - how: How, -} - -enum How { - Exact(Offset), - /// Each fitted distance (by its bits) and its surface (absolute parameters of the face's own - /// surface); the face's outward sign (its orientation). - Fitted { - surfaces: Vec<(u64, mt::BSplineSurface)>, - sign: f64, - }, -} - -impl FaceMover { - /// A mover for `face` at each of `distances` (along its outward normal), refused where a - /// distance would fold it over; fitted faces within `tolerance`. - pub(crate) fn new(face: &mt::Face, distances: &[f64], tolerance: f64) -> Result { - let how = match Offset::of(face) { - Some(off) => { - if let Offset::Cylinder { r, out, .. } = off - && let Some(d) = distances.iter().find(|d| r + out * **d <= tolerance) - { - return Err(KernelError::Invalid(format!("{d} mm is as deep as the cylinder's radius ({r:.4} mm): it would fold the face over"))); - } - How::Exact(off) - } - None => { - let mut surfaces = Vec::new(); - for d in distances.iter().filter(|d| **d != 0.0) { - if !surfaces.iter().any(|(b, _)| *b == d.to_bits()) { - surfaces.push((d.to_bits(), fit(face, *d, tolerance)?)); - } - } - How::Fitted { surfaces, sign: if face.orientation() { 1.0 } else { -1.0 } } - } - }; - Ok(FaceMover { face: face.clone(), how }) - } - - /// Where the point `p` of the face goes at distance `d`. - pub(crate) fn point(&self, p: Vec3, d: f64) -> Result { - match &self.how { - How::Exact(off) => Ok(off.map(p, d)), - How::Fitted { .. } if d == 0.0 => Ok(p), - How::Fitted { sign, .. } => offset_point(&self.face.surface(), p, sign * d), - } - } - - /// An edge curve of the face moved by `d` (exact, or a cubic through moved samples). - pub(crate) fn curve(&self, c: &mt::Curve, d: f64) -> Result { - match &self.how { - How::Exact(off) => map_curve(off, c, d), - How::Fitted { .. } if d == 0.0 => Ok(c.clone()), - How::Fitted { .. } => { - let (t0, t1) = c.range_tuple(); - let pts: Vec = (0..EDGE_SAMPLES) - .map(|k| self.point(from_p3(c.subs(t0 + (t1 - t0) * k as f64 / (EDGE_SAMPLES - 1) as f64)), d)) - .collect::>()?; - Ok(mt::Curve::BSplineCurve(crate::build::interpolate_cubic(&pts).ok_or_else(|| KernelError::Failed("offset edge".into()))?)) - } - } - } - - /// The face's surface moved by `d` (absolute: the face's orientation is kept apart). - pub(crate) fn surface(&self, d: f64) -> Result { - match &self.how { - How::Exact(off) => map_surface(off, &self.face.surface(), d), - How::Fitted { .. } if d == 0.0 => Ok(self.face.surface()), - How::Fitted { surfaces, .. } => surfaces - .iter() - .find(|(b, _)| *b == d.to_bits()) - .map(|(_, s)| mt::Surface::BSplineSurface(s.clone())) - .ok_or_else(|| KernelError::Failed("offset: no surface fitted for that distance".into())), - } - } -} +use crate::body::Body; +use crate::{KernelError, Result}; /// The picked faces of `body` (indices in its face order) offset by `distance` along their -/// outward normals (negative: against them) into one surface body. `tolerance`: how far a -/// fitted face may stray from the true offset. A distance of zero copies the faces. The +/// outward normals (negative: against them) into one surface body. `tolerance`: how far apart +/// two offsets' edges may be and still be one edge. A distance of zero copies the faces. The /// history is over `[body]`: each face is the offset of the one it came from. pub fn offset_surface(body: &Body, faces: &[usize], distance: f64, tolerance: f64) -> Result { body.require_brep("offset")?; @@ -118,10 +21,10 @@ pub fn offset_surface(body: &Body, faces: &[usize], distance: f64, tolerance: f6 if !(tolerance.is_finite() && (1e-6..=10.0).contains(&tolerance)) { return Err(KernelError::Invalid("the offset tolerance must be 0.000001…10 mm".into())); } - let all: Vec = body.solid.face_iter().cloned().collect(); + let count = body.face_count(); let mut picked: Vec = Vec::new(); for &i in faces { - if i >= all.len() { + if i >= count { return Err(KernelError::Invalid("no such face".into())); } if !picked.contains(&i) { @@ -131,203 +34,15 @@ pub fn offset_surface(body: &Body, faces: &[usize], distance: f64, tolerance: f6 if picked.is_empty() { return Err(KernelError::Invalid("pick the faces to offset".into())); } - let chosen: Vec<(usize, &mt::Face)> = picked.iter().filter_map(|i| all.get(*i).map(|f| (*i, f))).collect(); - if distance == 0.0 { - let copy = surface_body(chosen.iter().map(|(_, f)| (*f).clone()).collect()); - return Ok(crate::record::rebuilt_body(copy, &[&body.solid], &crate::record::Rebuild::default())); - } - let size = body.size().max(1e-6); - let moves: Vec = chosen.iter().map(|(_, f)| FaceMover::new(f, &[distance], tolerance)).collect::>()?; - guard("offset surface", || { - let near = |a: Vec3, b: Vec3| a.dist(b) <= tolerance.max(size * 1e-7) * 4.0; - // Moved vertices and edges, shared while every face moves them to the same place. - let mut verts: HashMap> = HashMap::new(); - let mut edges: HashMap> = HashMap::new(); - let mut out = Vec::with_capacity(chosen.len()); - let mut history = Vec::with_capacity(chosen.len()); - for ((i, f), mv) in chosen.iter().zip(&moves) { - let map = |p: Vec3| mv.point(p, distance); - let mut vertex = |v: &mt::Vertex| -> Result { - let at = map(from_p3(v.point()))?; - let list = verts.entry(v.id()).or_default(); - if let Some(found) = list.iter().find(|m| near(from_p3(m.point()), at)) { - return Ok(found.clone()); - } - let nv = mt::Vertex::new(p3(at)); - list.push(nv.clone()); - Ok(nv) - }; - let mut wires = Vec::new(); - for w in f.absolute_boundaries() { - let mut wire = Vec::new(); - for e in w.edge_iter() { - let abs = if e.orientation() { e.clone() } else { e.inverse() }; - let (a, b) = (vertex(abs.front())?, vertex(abs.back())?); - let c = abs.curve(); - let (t0, t1) = c.range_tuple(); - let mid = map(from_p3(c.subs(0.5 * (t0 + t1))))?; - let list = edges.entry(abs.id()).or_default(); - let shared = list.iter().find(|m| { - m.front().id() == a.id() && m.back().id() == b.id() && { - let mc = m.curve(); - let (s0, s1) = mc.range_tuple(); - near(from_p3(mc.subs(0.5 * (s0 + s1))), mid) - } - }); - let moved = match shared { - Some(m) => m.clone(), - None => { - let curve = mv.curve(&c, distance)?; - let m = mt::Edge::new_unchecked(&a, &b, curve); - list.push(m.clone()); - m - } - }; - wire.push(if e.orientation() { moved } else { moved.inverse() }); - } - wires.push(mt::Wire::from(wire)); - } - let surface = mv.surface(distance)?; - let mut nf = mt::Face::new_unchecked(wires, surface); - if !f.orientation() { - nf.invert(); - } - out.push(nf); - history.push(crate::record::generated(vec![FaceOrigin::Offset { operand: 0, face: *i }])); - } - let operand = crate::record::Operand::new(body); - // Faces that close up (every face of a smooth closed body) make a solid, as Stitch makes - // one. - let shell = mt::Shell::from(out); - let result = match shell.shell_condition() { - mt::ShellCondition::Closed => match crate::body::Solid::try_new(vec![shell.clone()]) { - Ok(solid) => Body::new(solid)?, - Err(_) => surface_body(shell.into_iter().collect()), - }, - _ => surface_body(shell.into_iter().collect()), - }; - crate::record::attach(result, &[operand], Some(history), HashMap::new()) - }) -} - -/// The point `p` on `s` (absolute) moved by `d` along the surface's own normal there. -fn offset_point(s: &mt::Surface, p: Vec3, d: f64) -> Result { - let (u, v) = s.search_nearest_parameter(p3(p), None, 100).ok_or_else(|| KernelError::Failed("offset: a point off its face".into()))?; - let n = from_p3(mt::Point3::new(0.0, 0.0, 0.0) + s.normal(u, v)); - let n = - n.normalized().ok_or_else(|| KernelError::Invalid("the face has a point with no normal (a pole or a crease): not supported yet".into()))?; - Ok(from_p3(s.subs(u, v)) + n * d) -} - -/// The fitted offset of a face that is not a plane or a circular cylinder. -fn fit(f: &mt::Face, distance: f64, tolerance: f64) -> Result> { - let s = f.surface(); - let sign = if f.orientation() { 1.0 } else { -1.0 }; - let d = sign * distance; - // The face's span in its surface's parameters: its boundary, found on the surface. - let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); - for e in f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()) { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..=16 { - let q = c.subs(t0 + (t1 - t0) * k as f64 / 16.0); - if let Some((u, v)) = s.search_nearest_parameter(q, None, 100) { - (u0, u1, v0, v1) = (u0.min(u), u1.max(u), v0.min(v), v1.max(v)); - } - } - } - if !(u0.is_finite() && u1 > u0 && v0.is_finite() && v1 > v0) { - return Err(KernelError::Failed("offset: the face's span on its surface".into())); - } - let at = |a: f64, b: f64| -> Result { - let (u, v) = (u0 + (u1 - u0) * a, v0 + (v1 - v0) * b); - let n = from_p3(mt::Point3::new(0.0, 0.0, 0.0) + s.normal(u, v)); - let n = n - .normalized() - .ok_or_else(|| KernelError::Invalid("the face has a point with no normal (a pole or a crease): not supported yet".into()))?; - Ok(from_p3(s.subs(u, v)) + n * d) - }; - // Folding over: moving a point by d along its normal shrinks lengths along a principal - // direction by 1 - d·k (k > 0 where the surface bends toward its normal); at zero the - // offset reaches the centre of curvature and folds. Refused with a margin, naming the - // tightest radius on that side. - let mut tightest: Option = None; - for i in 0..=START_GRID { - for j in 0..=START_GRID { - let (u, v) = (u0 + (u1 - u0) * i as f64 / START_GRID as f64, v0 + (v1 - v0) * j as f64 / START_GRID as f64); - let Some((k1, k2)) = principal_curvatures(&s, u, v) else { continue }; - for k in [k1, k2] { - if d * k > 0.0 && 1.0 - d * k <= 0.05 { - let r = 1.0 / k.abs(); - tightest = Some(tightest.map_or(r, |t: f64| t.min(r))); - } - } - } - } - if let Some(r) = tightest { - return Err(KernelError::Invalid(format!( - "the offset is as deep as the face's smallest concave radius on that side ({r:.4} mm): it would fold the face over" - ))); - } - let mut n = START_GRID; - loop { - let grid = Grid::from_fn([n + 1, n + 1], |i, j| at(i as f64 / n as f64, j as f64 / n as f64)) - .ok_or_else(|| KernelError::TooLarge("offset: the sample grid".into()))? - .try_map(|p| p)?; - let surface = interpolate_net(&grid).map(|fit| fit.surface).ok_or_else(|| KernelError::Failed("offset: fitting the surface".into()))?; - // Checked between the samples, where a fit strays most. - let mut worst = 0.0f64; - for i in 0..n { - for j in 0..n { - let (a, b) = ((i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64); - worst = worst.max(from_p3(surface.subs(a, b)).dist(at(a, b)?)); - } - } - if worst <= tolerance { - // Re-parameterised to the face's own surface span, so boundary points found on the - // old surface map onto it. - return Ok(reparameterised(surface, (u0, u1), (v0, v1))); - } - if n >= MAX_GRID { - return Err(KernelError::Invalid(format!( - "the offset can't be fitted within {tolerance} mm (off by up to {worst:.4} mm): try a larger tolerance" - ))); - } - n = (n * 2).min(MAX_GRID); - } -} - -/// The principal curvatures of `s` at (u, v), signed: positive where the surface bends toward -/// its normal there. `None` where it has no normal. -fn principal_curvatures(s: &mt::Surface, u: f64, v: f64) -> Option<(f64, f64)> { - let (su, sv) = (s.uder(u, v), s.vder(u, v)); - let n = s.normal(u, v); - if !(n.magnitude2() > 0.5) { - return None; - } - let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv)); - let (l, m, nn) = (s.uuder(u, v).dot(n), s.uvder(u, v).dot(n), s.vvder(u, v).dot(n)); - let det = e * g - f * f; - if det.abs() < 1e-18 { - return None; - } - let k = (l * nn - m * m) / det; - let h = (e * nn - 2.0 * f * m + g * l) / (2.0 * det); - let disc = (h * h - k).max(0.0).sqrt(); - Some((h + disc, h - disc)) -} - -/// `s` (on [0, 1]²) with its knots stretched onto `u` × `v`. -fn reparameterised(s: mt::BSplineSurface, u: (f64, f64), v: (f64, f64)) -> mt::BSplineSurface { - let stretch = |kv: &mt::KnotVec, (a, b): (f64, f64)| mt::KnotVec::from(kv.iter().map(|k| a + (b - a) * k).collect::>()); - let (ku, kv) = (stretch(s.uknot_vec(), u), stretch(s.vknot_vec(), v)); - mt::BSplineSurface::new((ku, kv), s.control_points().clone()) + crate::surfaces::offset_faces(body, &picked, distance, tolerance) } #[cfg(test)] mod tests { use super::*; use crate::{box_solid, cylinder, measure, sphere}; + use solidcore_record::Vec3; + use solidcraft_geom::prelude::*; fn rel(a: f64, b: f64) -> f64 { (a - b).abs() / b.abs().max(1e-9) @@ -336,7 +51,7 @@ mod tests { crate::surfaces::nearest_face(b, p).unwrap() } fn edges(b: &Body) -> usize { - b.solid.edge_iter().map(|e| e.id()).collect::>().len() + b.edge_count() } /// Planes move exactly: a box's top 5 up is a 10 × 10 square at z = 15. Two faces across a @@ -355,24 +70,25 @@ mod tests { assert!(copy.face_count() == 2 && rel(measure(©).unwrap().area, 200.0) < 1e-9); } - /// A cylinder's side (two halves) moved out by 2 keeps its halves joined, with radius 12: - /// area 2π·12·20. Moved in past its axis, refused. + /// A cylinder's side (one face, closed round its seam) moved out by 2 keeps its seam joined, + /// with radius 12: area 2π·12·20. Moved in past its axis, refused. #[test] fn a_cylinder_side_changes_radius() { let c = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 20.0).unwrap(); let d = 10.0 / 2f64.sqrt(); - let halves = [face_at(&c, Vec3::new(d, d, 10.0)), face_at(&c, Vec3::new(-d, -d, 10.0))]; - let out = offset_surface(&c, &halves, 2.0, 0.01).unwrap(); - assert!(out.face_count() == 2); + let side = [face_at(&c, Vec3::new(d, d, 10.0))]; + assert_eq!(face_at(&c, Vec3::new(-d, -d, 10.0)), side[0], "the side is one face"); + let out = offset_surface(&c, &side, 2.0, 0.01).unwrap(); + assert!(out.face_count() == 1); let want = 2.0 * std::f64::consts::PI * 12.0 * 20.0; assert!(rel(measure(&out).unwrap().area, want) < 1e-3, "{} vs {want}", measure(&out).unwrap().area); // (measured on meshes) - let joined = offset_surface(&c, &halves, 0.0, 0.01).unwrap(); - assert_eq!(edges(&out), edges(&joined), "the halves still share their seams"); - assert!(offset_surface(&c, &halves, -10.5, 0.01).is_err()); + let joined = offset_surface(&c, &side, 0.0, 0.01).unwrap(); + assert_eq!(edges(&out), edges(&joined), "the side still closes on its seam"); + assert!(offset_surface(&c, &side, -10.5, 0.01).is_err()); } /// A sphere (fitted faces) moved out by 2: area 4π·12², within the tolerance; moved in to - /// its centre, refused with its radius named. + /// its centre, refused. #[test] fn a_sphere_is_fitted_and_refused_past_its_centre() { let s = sphere(Vec3::ZERO, 10.0).unwrap(); @@ -384,8 +100,7 @@ mod tests { assert_eq!(edges(&out), edges(&s)); assert!(!out.is_surface(), "the offset sphere closes into a solid"); assert!(rel(measure(&out).unwrap().volume, 4.0 / 3.0 * std::f64::consts::PI * 1728.0) < 2e-3, "outward"); // (measured on meshes) - let e = offset_surface(&s, &all, -10.0, 0.01).unwrap_err().to_string(); - assert!(e.contains("10.0000"), "{e}"); + assert!(offset_surface(&s, &all, -10.0, 0.01).is_err()); } /// A doubly curved patch (a saddle, a B-spline height field) moved by 1.5: every point of the @@ -398,13 +113,13 @@ mod tests { let z = |x: f64| 50.0 - (1600.0 - x * x).sqrt(); let rim = [Vec3::new(14.0, 0.0, z(14.0)), Vec3::new(0.0, 14.0, z(0.0)), Vec3::new(-14.0, 0.0, z(-14.0)), Vec3::new(0.0, -14.0, z(0.0))]; let cover = crate::patch_edges(&cup, &rim).unwrap(); - let face = cover.solid.face_iter().next().unwrap().clone(); + let record = cover.record(); + let s = solidcraft_geom::brep::eval::SurfaceEval::new(&record.faces[0].surface).unwrap(); let out = offset_surface(&cover, &[0], 1.5, 0.01).unwrap(); - let mesh = out.tessellate(0.05).unwrap(); - let s = face.surface(); + let mesh = out.mesh(&crate::MeshTolerance::chord(0.05)).unwrap(); for p in mesh.positions.iter().step_by(7) { - let (u, v) = s.search_nearest_parameter(p3(*p), None, 100).unwrap(); - let dist = from_p3(s.subs(u, v)).dist(*p); + let uv = s.project(*p, None, f64::INFINITY).unwrap(); + let dist = s.point(uv).unwrap().dist(*p); assert!((dist - 1.5).abs() < 0.03, "{dist} at {p:?}"); } } diff --git a/crates/kernel/src/surface_ruled.rs b/crates/kernel/src/surface_ruled.rs index c19a1ae98..475a398b7 100644 --- a/crates/kernel/src/surface_ruled.rs +++ b/crates/kernel/src/surface_ruled.rs @@ -3,31 +3,38 @@ //! lines from the edge in a direction set by the face beside it: along its normal, continuing //! it, at an angle from a reference direction (a draft), or along a fixed vector. //! -//! A strip is exact where the rulings move the edge by an affine map: a straight edge with a -//! constant ruling direction gives a plane, an arc whose rulings keep their angle to its axis -//! gives a plane (a ring), a cylinder or a cone. Any other strip is a ruled B-spline (degree 1 -//! across) fitted within [`FIT_TOLERANCE`]. Strips share their side edges where their rulings -//! agree; at a sharp corner of the chain they are mitred (each extended along its far edge -//! until the two meet, or cut back where they overlap) or rounded (a planar or conical sector -//! turning one ruling into the other; an inside corner is always cut back). The strips stand -//! on the body's own edges, so they come out stitched together. +//! A strip is exact where the rulings move the edge by an affine map: a constant ruling direction +//! (a plane, or the ruled NURBS between the edge and its translate), or an arc whose rulings keep +//! their angle to its axis (a plane ring, or the ruled NURBS of a cylinder or a cone, exactly). +//! Rulings that turn any other way along the edge (a normal turning along a free-form face, a +//! tangent continuing a face round a free-form curve) end on an offset curve, which has no exact +//! NURBS form in general; such a strip's far edge is a curve of its own instead ([`far_curves`]: +//! fair, near the rulings' ends, its handles movable), and the strip is exactly the ruled surface +//! between the edge and it. Strips share their side edges +//! where their rulings agree; at a sharp corner of the chain they are mitred (each extended along +//! its far edge until the two meet, or cut back where they overlap) or rounded (a planar or +//! conical sector SMLib revolves from one ruling to the other; an inside corner is always cut +//! back). +//! +//! Every strip and corner face is built on its own on the record (each edge a NURBS curve, the +//! edge's own curve as a NURBS where it stands on the body), and the faces are stitched by SMLib +//! along the side edges they share. +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::Vec3; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self as b, Brep}; +use solidcraft_geom::brep::eval::SurfaceEval; +use solidcraft_geom::bspline::{CurveN, HPoint, NurbsSurface}; -use crate::body::{Body, from_p3, p3, v3}; -use crate::record::{Rebuild, rebuilt_body}; -use crate::surfaces::{map_control_points, nearest_face, picked_chain, surface_body}; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::history::FaceOrigin; +use crate::surfaces::{Parts, nearest_face, picked_chain, sheet_of, spline_curve, spline_surface, uv_line}; +use crate::{KernelError, Result, record}; -/// How far a fitted strip may stray from the true ruled surface (mm). -const FIT_TOLERANCE: f64 = 1e-3; -/// Samples along an edge when classifying its strip, and the most a fitted strip is refined to. +/// Samples along an edge when classifying its strip. const SAMPLES: usize = 16; -const MAX_FIT_SAMPLES: usize = 513; /// Rulings closer than this (as unit vectors) agree: their strips share a side edge. const SAME_RULING: f64 = 1e-7; @@ -71,8 +78,104 @@ pub struct Ruled { /// A ruled surface hanging off the chain of `body`'s edges picked by the points `at` (open or /// closed), as one surface body. The history is over `[body]`: each strip is made in place of -/// the edge it stands on, a corner face in place of the two edges meeting there. +/// the edge it stands on, a corner face in place of the two edges meeting there. A strip whose +/// rulings turn freely along its edge gets the default far curve (see the notes at +/// [`far_curves`]). pub fn ruled_surface(body: &Body, at: &[Vec3], r: &Ruled) -> Result { + ruled_surface_with(body, at, r, &[]) +} + +/// The interior control points of each strip's far curve, in chain order: `None` for a strip that +/// is exact (its far edge is its edge's image), else the default curve's (see [`far_curves`]): +/// the handles a caller may move and give back to [`ruled_surface_with`]. +pub fn ruled_far_handles(body: &Body, at: &[Vec3], r: &Ruled) -> Result>>> { + let plan = planned(body, at, r, &[])?; + Ok(plan + .strips + .iter() + .zip(&plan.free) + .map(|(s, free)| { + free.then(|| { + s.top.ctrl.iter().skip(1).take(s.top.ctrl.len().saturating_sub(2)).map(|h| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])).collect() + }) + }) + .collect()) +} + +/// The strips and chain of a ruled surface, before its joints. +struct Plan { + chain: Vec<(usize, bool)>, + closed: bool, + mode: RuledMode, + eps: f64, + strips: Vec, + /// Whether each strip's far edge is a curve of our own (its rulings turn freely). + free: Vec, +} + +/// [`ruled_surface`] with the interior control points of free strips' far curves given (in chain +/// order, as [`ruled_far_handles`] lists them; `None` or missing: the default curve). A handle +/// list of the wrong length, or one for an exact strip, is refused. +pub fn ruled_surface_with(body: &Body, at: &[Vec3], r: &Ruled, handles: &[Option>]) -> Result { + let Plan { chain, closed, mode, eps, strips, .. } = planned(body, at, r, handles)?; + let n = chain.len(); + let rec = body.record(); + // Joints at the chain's vertices: joint j is where strip j starts (and strip j - 1 ends); an + // open chain has one more, at its far end. + let joints = (0..n + usize::from(!closed)) + .map(|j| { + let incoming = if j > 0 { + strips.get(j - 1) + } else if closed { + strips.last() + } else { + None + }; + let outgoing = strips.get(j).filter(|_| closed || j < n); + Joint::new(incoming, outgoing, &mode, r.corners, eps) + }) + .collect::>>()?; + let tolerance = (eps * 1e3).max(rec.tolerance); + let mut pieces = Vec::new(); + for (j, s) in strips.iter().enumerate() { + let start = joints.get(j).ok_or_else(|| KernelError::Failed("ruled surface: a joint".into()))?; + let end = joints.get(if closed { (j + 1) % n } else { j + 1 }).ok_or_else(|| KernelError::Failed("ruled surface: a joint".into()))?; + let (up_start, top_start) = start.side(Side::Out, s); + let (up_end, top_end) = end.side(Side::In, s); + if s.line && (top_end - top_start).dot(s.start.tangent) <= eps { + return Err(KernelError::Invalid("the corners cut a strip away entirely: try a shorter distance".into())); + } + let edge = chain.get(j).map_or(0, |(e, _)| *e); + let face = s.face(&up_start, &up_end, top_start, top_end, tolerance)?; + let h = vec![record::generated(vec![FaceOrigin::Edge { operand: 0, edge }]); face.faces.len()]; + pieces.push((face, h)); + } + // Corner faces are made in place of the two edges meeting at the corner. + for (j, jt) in joints.iter().enumerate() { + let before = if j > 0 { + Some(j - 1) + } else if closed { + n.checked_sub(1) + } else { + None + }; + let near: Vec = [before, (j < n).then_some(j)] + .into_iter() + .flatten() + .filter_map(|k| chain.get(k)) + .map(|(e, _)| FaceOrigin::Edge { operand: 0, edge: *e }) + .collect(); + for f in jt.corner_faces(tolerance)? { + let h = vec![record::generated(near.clone()); f.faces.len()]; + pieces.push((f, h)); + } + } + sheet_of(pieces, true, &[body]) +} + +/// The chain picked by `at`, each edge's rulings read, and its strips with their far edges (the +/// free ones solved with `handles` given; see [`ruled_surface_with`]). +fn planned(body: &Body, at: &[Vec3], r: &Ruled, handles: &[Option>]) -> Result { body.require_brep("ruled surface")?; let d = r.distance; if !(d.is_finite() && d > 0.0 && d < 1e6) { @@ -94,147 +197,643 @@ pub fn ruled_surface(body: &Body, at: &[Vec3], r: &Ruled) -> Result { m => m, }; let picked_face = r.face.map(|p| nearest_face(body, p)).transpose()?; + if handles.len() > 10_000 || handles.iter().flatten().any(|h| h.len() > 100_000 || h.iter().any(|p| !p.is_finite())) { + return Err(KernelError::Invalid("a ruled surface's far-curve handles must be finite points, a list per edge".into())); + } let eps = 1e-9 * (1.0 + body.size() + d); - guard("ruled surface", || { - let (chain, closed) = picked_chain(body, at)?; - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); - // The faces beside each chain edge (face index, the face's own use of the edge). - let mut beside: HashMap> = chain.iter().map(|e| (e.id(), Vec::new())).collect(); - for (i, f) in faces.iter().enumerate() { - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - if let Some(list) = beside.get_mut(&e.id()) { - list.push((i, e.clone())); + let rec = body.record(); + let (chain, closed) = picked_chain(body, at)?; + let n = chain.len(); + // The faces beside each chain edge: each use's face and whether that face's loop runs the + // edge the way the chain does. + let around: Vec> = chain + .iter() + .map(|&(e, forward)| { + let edge = rec.edges.get(e).ok_or_else(|| KernelError::Invalid("an edge reference".into()))?; + Ok(edge + .uses + .iter() + .filter_map(|u| { + let face = rec.faces.get(u.face as usize)?; + let b::Loop::Edges { edges } = face.loops.get(u.r#loop as usize)? else { return None }; + Some((u.face as usize, edges.get(u.position as usize)?.forward == forward)) + }) + .collect()) + }) + .collect::>()?; + let mut count: HashMap = HashMap::new(); + for list in &around { + for (i, _) in list { + *count.entry(*i).or_default() += 1; + } + } + let surfaces: Vec> = rec.faces.iter().map(|f| SurfaceEval::new(f.parameters()).ok()).collect(); + let normal = |face: usize, p: Vec3| normal_at(surfaces.get(face)?.as_ref()?, body.face_forward(face), p); + // The face each edge takes its directions from: the picked face where it borders the edge, + // carried on along the chain to the faces meeting it smoothly (a cylinder's halves); with no + // picked face beside the chain, the face beside the most edges. + let mut chosen: Vec> = around.iter().map(|list| list.iter().position(|(i, _)| Some(*i) == picked_face)).collect(); + if chosen.iter().all(Option::is_none) { + chosen = around + .iter() + .map(|list| { + (0..list.len()).max_by(|a, b| { + let key = |k: &usize| list.get(*k).map(|(i, _)| (count.get(i).copied().unwrap_or(0), std::cmp::Reverse(*i))); + key(a).cmp(&key(b)) + }) + }) + .collect(); + } + let bases: Vec> = chain.iter().map(|&(e, forward)| base_curve(rec, e, forward)).collect::>()?; + let ends = |k: usize| -> Option<(Vec3, Vec3)> { Some((point(bases.get(k)?, 0.0)?, point(bases.get(k)?, 1.0)?)) }; + // Carried on from a chosen neighbour across the vertex they share. + for _ in 0..n { + let mut changed = false; + for j in 0..n { + if chosen.get(j).copied().flatten().is_some() { + continue; + } + let Some((start, end)) = ends(j) else { continue }; + let neighbours = [(j.checked_sub(1).or(closed.then(|| n - 1)), start), ((j + 1 < n).then_some(j + 1).or(closed.then_some(0)), end)]; + let pick = neighbours.iter().find_map(|(k, p)| { + let k = (*k)?; + let (face, _) = around.get(k)?.get(chosen.get(k).copied().flatten()?)?; + let want = normal(*face, *p)?; + let list = around.get(j)?; + (0..list.len()).max_by(|a, b| { + let dot = |k: &usize| list.get(*k).and_then(|(i, _)| normal(*i, *p)).map_or(f64::NEG_INFINITY, |nn| nn.dot(want)); + dot(a).total_cmp(&dot(b)) + }) + }); + if let (Some(k), Some(slot)) = (pick, chosen.get_mut(j)) { + *slot = Some(k); + changed = true; + } + } + if !changed { + break; + } + } + let field = Field { mode, flip: r.flip, distance: d }; + // Each edge's face beside it (its surface, whether it is used along its natural normal, + // whether it lies left of the edge: the strip's tangent direction points away from it). + let mut sides = Vec::with_capacity(n); + for (j, k) in chosen.iter().enumerate() { + let (face, along) = + k.and_then(|k| around.get(j)?.get(k).copied()).ok_or_else(|| KernelError::Invalid("a picked edge has no face beside it".into()))?; + let surface = surfaces.get(face).and_then(Option::as_ref).ok_or_else(|| KernelError::Failed("ruled surface: a face's surface".into()))?; + let forward = body.face_forward(face); + sides.push((surface, forward, along == forward)); + } + fn rulings_on<'a>(bases: &'a [CurveN<4>], sides: &[(&'a SurfaceEval, bool, bool)], field: &'a Field) -> Vec> { + bases.iter().zip(sides).map(|(base, &(face, forward, face_left))| Rulings { base, face, forward, face_left, field }).collect() + } + let sampled: Vec = rulings_on(&bases, &sides, &field).iter().map(|r| Sampled::of(r, eps)).collect::>()?; + // A free strip's far curve lies in its edge's spline space: a straight edge's (one linear + // span) holds only the chord between the strip's corners, so its rulings' ends would not count. + // Such an edge is taken as the cubic it is too (exact degree elevation, the same points at the + // same parameters), the lowest degree whose interior control points set each end's tangent + // and let the curve pass near the rulings' ends. + let bases: Vec> = bases.into_iter().zip(&sampled).map(|(c, s)| if s.affine.is_none() { cubic_if_straight(c) } else { c }).collect(); + let rulings = rulings_on(&bases, &sides, &field); + // Exact strips' far edges are their edges' images; the rest are solved together. + let exact: Vec>> = sampled.iter().zip(&bases).map(|(s, base)| s.affine.as_ref().map(|m| mapped(base, |p| m.apply(p)))).collect(); + let corner = |r: &Reading| r.0 + r.3 * d; + let mut index = 0; + let mut fars = Vec::with_capacity(n); + for (k, (ru, s)) in rulings.into_iter().zip(&sampled).enumerate() { + let given = handles.get(k).cloned().flatten(); + if s.affine.is_some() { + if given.is_some() { + return Err(KernelError::Invalid(format!("edge {} of the chain has an exact strip: it takes no far-curve handles", k + 1))); + } + fars.push(None); + continue; + } + let count = ru.base.ctrl.len(); + if given.as_ref().is_some_and(|g| g.len() + 2 != count) { + return Err(KernelError::Invalid(format!("edge {} of the chain takes {} far-curve handles", k + 1, count.saturating_sub(2)))); + } + let start = index; + if given.is_none() { + index += count.saturating_sub(2); + } + fars.push(Some(Far { rulings: ru, a: corner(&s.first), b: corner(&s.last), given, index: start })); + } + // Smooth shared joints: the chain runs on (its tangents agree) and the rulings agree. + let smooth: Vec = (0..n) + .map(|k| { + let next = (k + 1) % n; + (closed || k + 1 < n) + && sampled + .get(k) + .zip(sampled.get(next)) + .is_some_and(|(a, b)| a.last.1.dot(b.first.1) > (1e-3f64).cos() && (a.last.3 - b.first.3).len() <= SAME_RULING) + }) + .collect(); + let tops = far_curves(&fars, &exact, &smooth)?; + let mut strips = Vec::with_capacity(n); + let mut free = Vec::with_capacity(n); + for (k, s) in sampled.iter().enumerate() { + let base = bases.get(k).cloned().ok_or_else(|| KernelError::Failed("ruled surface: an edge".into()))?; + let top = exact + .get(k) + .cloned() + .flatten() + .or_else(|| tops.get(k).cloned().flatten()) + .ok_or_else(|| KernelError::Failed("ruled surface: a far edge".into()))?; + free.push(s.affine.is_none()); + strips.push(Strip::new(base, top, s, d)); + } + Ok(Plan { chain, closed, mode, eps, strips, free }) +} + +/// The unit normal of a face (its surface, used along its natural normal when `forward`) at its +/// surface's point nearest `p`. +fn normal_at(surface: &SurfaceEval, forward: bool, p: Vec3) -> Option { + let [u, v] = surface.project(p, None, f64::INFINITY)?; + let (_, su, sv) = surface.derivs(u, v)?; + let n = su.cross(sv).normalized()?; + Some(if forward { n } else { n * -1.0 }) +} + +/// The edge `e` of `r` as a NURBS curve with homogeneous control points, run the way the chain +/// runs along it (`forward`), its parameter the curve's own (an arc's rational quadratic form, +/// one span per quarter turn or less). +fn base_curve(r: &Brep, e: usize, forward: bool) -> Result> { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid("an edge reference".into()))?; + // On the curve itself: a conic's angles (its NURBS form, if any, is parameterised otherwise). + let [t0, t1] = solidcraft_geom::brep::label::edge_curve_interval(edge) + .ok_or_else(|| KernelError::Invalid("an edge's NURBS form cannot be evaluated".into()))?; + let c = match &edge.curve { + b::Curve::Line { start, end } => { + let at = |t: f64| [start[0] + (end[0] - start[0]) * t, start[1] + (end[1] - start[1]) * t, start[2] + (end[2] - start[2]) * t, 1.0]; + CurveN { degree: 1, knots: vec![t0, t0, t1, t1], ctrl: vec![at(t0), at(t1)] } + } + b::Curve::Circle { frame, radius } => conic(frame, [*radius, *radius], [t0, t1]), + b::Curve::Ellipse { frame, radii } => conic(frame, *radii, [t0, t1]), + b::Curve::Polyline { points } => { + let n = points.len(); + let mut knots = vec![0.0]; + knots.extend((0..n).map(|i| i as f64)); + knots.push(n.saturating_sub(1) as f64); + CurveN { degree: 1, knots, ctrl: points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() } + } + b::Curve::Spline { knots, points } => { + CurveN { degree: degree(knots, points.len())?, knots: knots.clone(), ctrl: points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() } + } + b::Curve::RationalSpline { knots, homogeneous } => { + CurveN { degree: degree(knots, homogeneous.len())?, knots: knots.clone(), ctrl: homogeneous.clone() } + } + b::Curve::SurfaceIntersection { .. } => { + return Err(KernelError::Invalid("not supported yet: a ruled surface on a traced intersection edge".into())); + } + }; + Ok(if forward { c } else { reversed(&c) }) +} + +/// A straight edge's NURBS (degree 1, one span: its two ends) as the cubic Bézier it also is, +/// by exact degree elevation (control points at thirds of the way, weights kept equal); any other +/// curve as it is. +fn cubic_if_straight(c: CurveN<4>) -> CurveN<4> { + let ([p0, p1], [t0, t1]) = match (c.degree, c.ctrl.as_slice(), c.knots.as_slice()) { + (1, [p0, p1], [a, _, _, z]) => ([*p0, *p1], [*a, *z]), + _ => return c, + }; + let mix = |s: f64| std::array::from_fn::(|i| p0[i] * (1.0 - s) + p1[i] * s); + CurveN { degree: 3, knots: vec![t0, t0, t0, t0, t1, t1, t1, t1], ctrl: vec![p0, mix(1.0 / 3.0), mix(2.0 / 3.0), p1] } +} + +fn degree(knots: &[f64], n: usize) -> Result { + knots.len().checked_sub(n + 1).filter(|d| *d >= 1).ok_or_else(|| KernelError::Invalid("a spline's knots".into())) +} + +/// The arc of a circle or ellipse (its frame and radii) from angle `t0` to `t1` as a rational +/// quadratic on [t0, t1]: the same points, not the same parameterisation. +fn conic(frame: &b::Frame, radii: [f64; 2], [t0, t1]: [f64; 2]) -> CurveN<4> { + let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]); + let (o, x, y) = (v(frame.origin), v(frame.x_axis), v(frame.y_axis)); + let m = ((t1 - t0) / std::f64::consts::FRAC_PI_2 - 1e-9).ceil().max(1.0) as usize; + let step = (t1 - t0) / m as f64; + let w = (step / 2.0).cos(); + let at = |a: f64, s: f64| o + x * (radii[0] * a.cos() * s) + y * (radii[1] * a.sin() * s); + let h = |p: Vec3, w: f64| [p.x * w, p.y * w, p.z * w, w]; + let (mut ctrl, mut knots) = (vec![h(at(t0, 1.0), 1.0)], vec![t0; 3]); + for j in 0..m { + let a0 = t0 + step * j as f64; + ctrl.push(h(at(a0 + step / 2.0, 1.0 / w), w)); + ctrl.push(h(at(a0 + step, 1.0), 1.0)); + let u = t0 + step * (j + 1) as f64; + if j + 1 < m { + knots.extend([u, u]); + } else { + knots.extend([t1; 3]); + } + } + CurveN { degree: 2, knots, ctrl } +} + +/// `c` run the other way: the same points, its parameter t taken to (first + last knot) − t. +fn reversed(c: &CurveN<4>) -> CurveN<4> { + let (a, z) = (c.knots.first().copied().unwrap_or(0.0), c.knots.last().copied().unwrap_or(1.0)); + CurveN { degree: c.degree, knots: c.knots.iter().rev().map(|k| a + z - k).collect(), ctrl: c.ctrl.iter().rev().copied().collect() } +} + +/// A curve's parameter range. +fn range(c: &CurveN<4>) -> [f64; 2] { + [c.knots.get(c.degree).copied().unwrap_or(0.0), c.knots.get(c.ctrl.len()).copied().unwrap_or(1.0)] +} + +/// The point `f` (0…1) of the way along a curve's parameter range. +fn point(c: &CurveN<4>, f: f64) -> Option { + point_tangent(c, f).map(|(p, _)| p) +} + +/// The point `f` of the way along a curve's range and its derivative there (by the parameter). +fn point_tangent(c: &CurveN<4>, f: f64) -> Option<(Vec3, Vec3)> { + let [t0, t1] = range(c); + let ([x, y, z, w], [dx, dy, dz, dw]) = c.eval(t0 + (t1 - t0) * f)?; + if !(w.abs() > 1e-300) { + return None; + } + let p = Vec3::new(x / w, y / w, z / w); + Some((p, (Vec3::new(dx, dy, dz) - p * dw) * (1.0 / w))) +} + +/// `c` with its control points (Cartesian) moved by `f`, its weights kept: the exact image of the +/// curve under an affine `f`. +fn mapped(c: &CurveN<4>, f: impl Fn(Vec3) -> Vec3) -> CurveN<4> { + let ctrl = c + .ctrl + .iter() + .map(|h| { + let q = f(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])); + [q.x * h[3], q.y * h[3], q.z * h[3], h[3]] + }) + .collect(); + CurveN { degree: c.degree, knots: c.knots.clone(), ctrl } +} + +fn hpoints(c: &CurveN<4>) -> Vec { + c.ctrl.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect() +} + +/// A point of an edge with the rulings read there: the point, the edge's unit tangent (chain +/// direction), the face's normal and the unit ruling. +type Reading = (Vec3, Vec3, Vec3, Vec3); + +/// How the rulings are read along one chain edge: its NURBS, the face beside it (its surface, +/// whether it is used along its natural normal, whether it lies left of the edge) and the field. +struct Rulings<'a> { + base: &'a CurveN<4>, + face: &'a SurfaceEval, + forward: bool, + face_left: bool, + field: &'a Field, +} + +impl Rulings<'_> { + /// The reading a fraction `f` of the way along the edge's parameter. + fn at(&self, f: f64) -> Result { + let (p, der) = point_tangent(self.base, f).ok_or_else(|| KernelError::Invalid("a picked edge can't be evaluated".into()))?; + let tan = der.normalized().ok_or_else(|| KernelError::Invalid("a picked edge has a point with no direction".into()))?; + let n = normal_at(self.face, self.forward, p) + .ok_or_else(|| KernelError::Invalid("the face beside an edge has a point with no normal there: not supported yet".into()))?; + let out = if self.face_left { tan.cross(n) } else { n.cross(tan) }; + let out = out.normalized().ok_or_else(|| KernelError::Invalid("the face beside an edge runs along it".into()))?; + Ok((p, tan, n, self.field.ruling(tan, n, out)?)) + } + + /// Where the ruling at a fraction `f` of the way along the edge ends. + fn end_at(&self, f: f64) -> Result { + let (p, _, _, r) = self.at(f)?; + Ok(p + r * self.field.distance) + } +} + +/// What reading the rulings along an edge found: the first and last readings, whether the edge +/// and the rulings' ends lie in one plane, and the affine map the rulings make of the edge, if +/// any (the strip is then exact: its far edge is the edge's image). +struct Sampled { + first: Reading, + last: Reading, + planar: bool, + affine: Option, +} + +impl Sampled { + fn of(rulings: &Rulings, eps: f64) -> Result { + let d = rulings.field.distance; + let samples: Vec = (0..SAMPLES).map(|k| rulings.at(k as f64 / (SAMPLES - 1) as f64)).collect::>()?; + let (Some(first), Some(last)) = (samples.first().copied(), samples.last().copied()) else { + return Err(KernelError::Failed("ruled surface: samples".into())); + }; + let tops: Vec = samples.iter().map(|(p, _, _, r)| *p + *r * d).collect(); + // A plane through the edge and its rulings, when everything lies in one. + let plane_normal = first.1.cross(first.3).normalized(); + let planar = + plane_normal.is_some_and(|nn| samples.iter().map(|s| s.0).chain(tops.iter().copied()).all(|q| (q - first.0).dot(nn).abs() <= eps)); + Ok(Sampled { first, last, planar, affine: affine(&samples, d, eps) }) + } +} + +// ---- The far curve of a strip whose rulings turn freely ---------------------------------------- +// +// Rulings that turn along a free-form edge end on an offset curve, which has no exact NURBS form. +// Such a strip's far edge is a curve this module defines instead, and the strip is exactly the +// ruled surface between the edge and it: a B-spline on the edge's own degree, knots and weights +// (a straight edge's taken as its cubic, `cubic_if_straight`; only its control points are free), from the strip's start corner to its end corner (where the +// rulings at the edge's ends reach). Its interior control points are given (the doc's handles) +// or, by default, the least-squares solution of these weighted terms, the construction's +// parameters: +// - closeness [`W_CLOSE`]: at each Greville abscissa of the edge, the curve on the ruling's end; +// - fairness [`W_FAIR`]: the integral of the squared second derivative by the edge's arc length, +// made dimensionless by the edge's length; +// - end tangents [`W_TANGENT`]: each end leaving along the chord to the curve's other end +// ([`end_directions`]); +// - joints [`W_JOIN`]: at a joint where the chain runs on smoothly and the strips share their +// side, the first and second derivatives (by the edges' arc length) the same on both sides, in +// one solve along the chain: the neighbour's far edge is matched in tangent and curvature. + +/// Weight of the curve passing the rulings' ends. +const W_CLOSE: f64 = 1.0; +/// Weight of the fairness (bending) term. +const W_FAIR: f64 = 1e-2; +/// Weight of each end leaving along the chord. +const W_TANGENT: f64 = 1e-2; +/// Weight of matching a smooth neighbour's tangent and curvature at a shared joint. +const W_JOIN: f64 = 1e3; +/// Fairness samples per knot span. +const FAIR_PER_SPAN: usize = 4; +/// Most free control points one solve takes (a dense system). +const MAX_FREE: usize = 1200; + +/// Where each end of a far curve from `a` to `b` starts leaving: along the chord to its other end +/// (a unit direction at each end, the way the curve runs). +fn end_directions(a: Vec3, b: Vec3) -> Option<(Vec3, Vec3)> { + let chord = (b - a).normalized()?; + Some((chord, chord)) +} + +/// The rational basis of a curve with `c`'s knots and weights at `t`, and its first two +/// derivatives: the coefficients of each control point in the curve's point, first and second +/// derivative there (by its parameter), as (control point index, [R, R', R'']). +fn rational_basis(c: &CurveN<4>, t: f64) -> Option> { + let [t0, t1] = range(c); + let (first, n) = solidcraft_geom::bspline::basis_derivatives(&c.knots, c.degree, c.ctrl.len(), t.clamp(t0, t1), 2)?; + let w: Vec = (0..=c.degree).map(|j| c.ctrl.get(first + j).map_or(1.0, |h| h[3])).collect(); + let nd = |j: usize, k: usize| n.get(j).and_then(|d| d.get(k)).copied().unwrap_or(0.0); + let weight = |k: usize| (0..=c.degree).map(|j| nd(j, k) * w[j]).sum::(); + let (w0, w1, w2) = (weight(0), weight(1), weight(2)); + if !(w0.abs() > 1e-300) { + return None; + } + Some( + (0..=c.degree) + .map(|j| { + let r = nd(j, 0) * w[j] / w0; + let r1 = (nd(j, 1) * w[j] - r * w1) / w0; + let r2 = (nd(j, 2) * w[j] - 2.0 * r1 * w1 - r * w2) / w0; + (first + j, [r, r1, r2]) + }) + .collect(), + ) +} + +/// One strip's far curve in the solve: its edge's NURBS and readings, its corners, and its interior +/// control points: given (fixed) or unknowns starting at `index` in the solve's vector. +struct Far<'a> { + rulings: Rulings<'a>, + a: Vec3, + b: Vec3, + given: Option>, + index: usize, +} + +impl Far<'_> { + fn count(&self) -> usize { + self.rulings.base.ctrl.len() + } + + /// Control point `i` as an unknown's index, or its fixed position. + fn slot(&self, i: usize) -> Result> { + let n = self.count(); + Ok(if i == 0 { + Err(self.a) + } else if i + 1 == n { + Err(self.b) + } else if let Some(g) = &self.given { + Err(*g.get(i - 1).ok_or_else(|| KernelError::Invalid("a ruled surface's far-curve handles are fewer than its control points".into()))?) + } else { + Ok(self.index + i - 1) + }) + } + + /// The edge's speed (by its parameter) a fraction `f` of the way along. + fn speed(&self, f: f64) -> f64 { + point_tangent(self.rulings.base, f).map_or(1.0, |(_, d)| d.len().max(1e-12)) + } + + fn param(&self, f: f64) -> f64 { + let [t0, t1] = range(self.rulings.base); + t0 + (t1 - t0) * f + } +} + +/// A least-squares system over `m` unknown points: the normal equations, built row by row. +struct Normal { + m: usize, + a: Vec, + b: Vec<[f64; 3]>, +} + +impl Normal { + fn new(m: usize) -> Normal { + Normal { m, a: vec![0.0; m * m], b: vec![[0.0; 3]; m] } + } + + /// The row `Σ coefficient × point = target`, with weight `w` (its residual squared, times w): + /// fixed points move to the target's side. + fn row(&mut self, terms: &[(std::result::Result, f64)], target: Vec3, w: f64) { + let mut rhs = target; + let mut unknown: Vec<(usize, f64)> = Vec::with_capacity(terms.len()); + for (slot, c) in terms { + match slot { + Ok(i) => unknown.push((*i, *c)), + Err(p) => rhs -= *p * *c, + } + } + for &(i, ci) in &unknown { + for &(j, cj) in &unknown { + if let Some(x) = self.a.get_mut(i * self.m + j) { + *x += w * ci * cj; } } - } - let mut count: HashMap = HashMap::new(); - for list in beside.values() { - for (i, _) in list { - *count.entry(*i).or_default() += 1; + if let Some(x) = self.b.get_mut(i) { + x[0] += w * ci * rhs.x; + x[1] += w * ci * rhs.y; + x[2] += w * ci * rhs.z; } } - let empty = Vec::new(); - let around = |e: &mt::Edge| beside.get(&e.id()).unwrap_or(&empty); - // The face each edge takes its directions from: the picked face where it borders the - // edge, carried on along the chain to the faces meeting it smoothly (a cylinder's - // halves); with no picked face beside the chain, the face beside the most edges. - let n = chain.len(); - let mut chosen: Vec> = chain.iter().map(|e| around(e).iter().position(|(i, _)| Some(*i) == picked_face)).collect(); - if chosen.iter().all(Option::is_none) { - chosen = chain - .iter() - .map(|e| { - let list = around(e); - (0..list.len()).max_by(|a, b| { - let key = |k: &usize| list.get(*k).map(|(i, _)| (count.get(i).copied().unwrap_or(0), std::cmp::Reverse(*i))); - key(a).cmp(&key(b)) - }) - }) - .collect(); - } - // Carried on from a chosen neighbour across the vertex they share. - let normal = |face: usize, p: mt::Point3| faces.get(face).and_then(|f| normal_at(f, from_p3(p))); - for _ in 0..n { - let mut changed = false; - for j in 0..n { - if chosen.get(j).copied().flatten().is_some() { + } + + /// The unknowns (Gaussian elimination with partial pivoting). + fn solve(mut self) -> Result> { + let m = self.m; + let fail = || KernelError::Failed("ruled surface: the far curve's system is singular".into()); + for c in 0..m { + let pivot = (c..m).max_by(|&i, &j| self.a[i * m + c].abs().total_cmp(&self.a[j * m + c].abs())).ok_or_else(fail)?; + if !(self.a[pivot * m + c].abs() > 1e-300) { + return Err(fail()); + } + if pivot != c { + for k in 0..m { + self.a.swap(c * m + k, pivot * m + k); + } + self.b.swap(c, pivot); + } + let d = self.a[c * m + c]; + for r in c + 1..m { + let f = self.a[r * m + c] / d; + if f == 0.0 { continue; } - let Some(e) = chain.get(j) else { continue }; - let neighbours = [ - (j.checked_sub(1).or(closed.then(|| n - 1)), e.front().point()), - ((j + 1 < n).then_some(j + 1).or(closed.then_some(0)), e.back().point()), - ]; - let pick = neighbours.iter().find_map(|(k, p)| { - let k = (*k)?; - let (face, _) = around(chain.get(k)?).get(chosen.get(k).copied().flatten()?)?; - let want = normal(*face, *p)?; - let list = around(e); - (0..list.len()).max_by(|a, b| { - let dot = |k: &usize| list.get(*k).and_then(|(i, _)| normal(*i, *p)).map_or(f64::NEG_INFINITY, |nn| nn.dot(want)); - dot(a).total_cmp(&dot(b)) - }) - }); - if let (Some(k), Some(slot)) = (pick, chosen.get_mut(j)) { - *slot = Some(k); - changed = true; + for k in c..m { + self.a[r * m + k] -= f * self.a[c * m + k]; + } + let bc = self.b[c]; + for (x, y) in self.b[r].iter_mut().zip(bc) { + *x -= f * y; } } - if !changed { - break; + } + let mut x = vec![[0.0; 3]; m]; + for r in (0..m).rev() { + let mut s = self.b[r]; + for (k, xk) in x.iter().enumerate().skip(r + 1) { + for (sv, xv) in s.iter_mut().zip(xk) { + *sv -= self.a[r * m + k] * xv; + } + } + x[r] = s.map(|v| v / self.a[r * m + r]); + } + x.into_iter().map(|[a, b, c]| Vec3::new(a, b, c)).map(|p| if p.is_finite() { Ok(p) } else { Err(fail()) }).collect() + } +} + +/// The far curves of the chain's free strips (`None` for an exact strip, whose far edge is its +/// edge's image), solved together along the chain (see the notes above): `fars[k]` the free +/// strip on chain edge k; `smooth[k]` whether the chain runs on smoothly with shared sides from +/// edge k to the next (round a closed chain, the last to the first); `exact[k]` an exact strip's +/// far edge, matched by its free neighbours. +fn far_curves(fars: &[Option], exact: &[Option>], smooth: &[bool]) -> Result>>> { + let m = fars.iter().flatten().filter(|f| f.given.is_none()).map(|f| f.count().saturating_sub(2)).sum::(); + if m > MAX_FREE { + return Err(KernelError::TooLarge(format!("a ruled surface's free far curves have more than {MAX_FREE} control points"))); + } + let mut sys = Normal::new(m); + let n = fars.len(); + for far in fars.iter().flatten() { + let c = far.rulings.base; + let count = far.count(); + let length = (0..32).filter_map(|k| Some(point(c, k as f64 / 32.0)?.dist(point(c, (k + 1) as f64 / 32.0)?))).sum::().max(1e-12); + let terms = |t: f64, k: usize, scale: f64| -> Result, f64)>> { + rational_basis(c, t) + .ok_or_else(|| KernelError::Failed("ruled surface: the far curve's basis".into()))? + .into_iter() + .map(|(i, r)| Ok((far.slot(i)?, r[k] * scale))) + .collect() + }; + let [t0, t1] = range(c); + // Closeness at the Greville abscissae. + for i in 0..count { + let g = c.knots.iter().skip(i + 1).take(c.degree).sum::() / c.degree.max(1) as f64; + let f = ((g - t0) / (t1 - t0)).clamp(0.0, 1.0); + sys.row(&terms(g, 0, 1.0)?, far.rulings.end_at(f)?, W_CLOSE); + } + // Fairness: |F''|² by arc length, over each span, times length³ (dimensionless). + let spans: Vec<(f64, f64)> = c.knots.windows(2).filter(|w| w[1] > w[0] && w[0] >= t0 && w[1] <= t1).map(|w| (w[0], w[1])).collect(); + for (a, z) in spans { + for q in 0..FAIR_PER_SPAN { + let t = a + (z - a) * (q as f64 + 0.5) / FAIR_PER_SPAN as f64; + let f = (t - t0) / (t1 - t0); + let s = far.speed(f); + let w = W_FAIR * length.powi(3) * s * (z - a) / FAIR_PER_SPAN as f64; + sys.row(&terms(t, 2, 1.0 / (s * s))?, Vec3::ZERO, w); } } - let field = Field { mode, flip: r.flip, distance: d }; - let mut strips = Vec::with_capacity(n); - for (e, k) in chain.iter().zip(&chosen) { - let (i, own) = k.and_then(|k| around(e).get(k)).ok_or_else(|| KernelError::Invalid("a picked edge has no face beside it".into()))?; - let face = faces.get(*i).ok_or_else(|| KernelError::Failed("ruled surface: a face".into()))?; - // The face lies left of its own boundary (seen along its normal); the strip's - // tangent direction points away from it. - let face_left = own.orientation() == e.orientation(); - strips.push(Strip::new(e.clone(), face, face_left, &field, eps)?); + // Each end leaving along the chord, at the edge's speed there. + if let Some((d0, d1)) = end_directions(far.a, far.b) { + let (s0, s1) = (far.speed(0.0), far.speed(1.0)); + let reach = far.a.dist(far.b) / length; + sys.row(&terms(t0, 1, 1.0)?, d0 * (s0 * reach), W_TANGENT * length * length); + sys.row(&terms(t1, 1, 1.0)?, d1 * (s1 * reach), W_TANGENT * length * length); } - // Joints at the chain's vertices: joint j is where strip j starts (and strip j - 1 - // ends); an open chain has one more, at its far end. - let joints = (0..n + usize::from(!closed)) - .map(|j| { - let incoming = if j > 0 { - strips.get(j - 1) - } else if closed { - strips.last() - } else { - None - }; - let outgoing = strips.get(j).filter(|_| closed || j < n); - Joint::new(incoming, outgoing, &mode, r.corners, eps) - }) - .collect::>>()?; - let mut rec = Rebuild::default(); - let mut out = Vec::new(); - for (j, s) in strips.iter().enumerate() { - let start = joints.get(j).ok_or_else(|| KernelError::Failed("ruled surface: a joint".into()))?; - let end = joints.get(if closed { (j + 1) % n } else { j + 1 }).ok_or_else(|| KernelError::Failed("ruled surface: a joint".into()))?; - let (up_start, top_start) = start.side(Side::Out, s); - let (up_end, top_end) = end.side(Side::In, s); - let top = if s.line { - mt::Edge::new_unchecked(&top_start, &top_end, mt::Curve::Line(mt::Line(top_start.point(), top_end.point()))) - } else { - mt::Edge::new_unchecked(&top_start, &top_end, s.top.clone()) - }; - if s.line && (from_p3(top_end.point()) - from_p3(top_start.point())).dot(s.start.tangent) <= eps { - return Err(KernelError::Invalid("the corners cut a strip away entirely: try a shorter distance".into())); + } + // Joints: the first and second derivatives by arc length agree across a smooth shared joint. + for k in 0..n { + if !smooth.get(k).copied().unwrap_or(false) { + continue; + } + let next = (k + 1) % n; + let (left, right) = (fars.get(k).and_then(Option::as_ref), fars.get(next).and_then(Option::as_ref)); + if left.is_none() && right.is_none() { + continue; + } + for order in 1..=2usize { + let mut row: Vec<(std::result::Result, f64)> = Vec::new(); + let mut target = Vec3::ZERO; + // The left side at its end (+), the right side at its start (−). + for (side, sign) in [(k, 1.0), (next, -1.0)] { + let at_end = sign > 0.0; + match (fars.get(side).and_then(Option::as_ref), exact.get(side).and_then(Option::as_ref)) { + (Some(far), _) => { + let f = if at_end { 1.0 } else { 0.0 }; + let scale = sign / far.speed(f).powi(order as i32); + let basis = + rational_basis(far.rulings.base, far.param(f)).ok_or_else(|| KernelError::Failed("ruled surface: a joint".into()))?; + for (i, r) in basis { + row.push((far.slot(i)?, r[order] * scale)); + } + } + (None, Some(top)) => { + let f = if at_end { 1.0 } else { 0.0 }; + let [t0, t1] = range(top); + let t = t0 + (t1 - t0) * f; + let basis = rational_basis(top, t).ok_or_else(|| KernelError::Failed("ruled surface: a joint".into()))?; + let speed = point_tangent(top, f).map_or(1.0, |(_, d)| d.len().max(1e-12)); + let mut known = Vec3::ZERO; + for (i, r) in basis { + let h = top.ctrl.get(i).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]); + known += Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]) * r[order]; + } + target -= known * (sign / speed.powi(order as i32)); + } + (None, None) => {} + } } - let mut wire = vec![s.base.clone()]; - wire.extend(up_end.iter().cloned()); - wire.push(top.inverse()); - wire.extend(up_start.iter().rev().map(mt::Edge::inverse)); - let face = mt::Face::new_unchecked(vec![wire.into()], s.surface.clone()); - rec.blend(&face, [s.base.id()]); - out.push(face); - out.extend(end.corner_faces().into_iter().cloned()); + sys.row(&row, target, W_JOIN); } - // Corner faces are made in place of the two edges meeting at the corner. - for (j, jt) in joints.iter().enumerate() { - let near: Vec = [ - if j > 0 { - strips.get(j - 1) - } else if closed { - strips.last() - } else { - None - }, - strips.get(j), - ] - .into_iter() - .flatten() - .map(|s| s.base.id()) - .collect(); - for f in jt.corner_faces() { - rec.blend(f, near.iter().copied()); - } - } - Ok(rebuilt_body(surface_body(out), &[&body.solid], &rec)) - }) + } + let x = if m == 0 { Vec::new() } else { sys.solve()? }; + fars.iter() + .map(|far| { + let Some(far) = far else { return Ok(None) }; + let pts = (0..far.count()) + .map(|i| match far.slot(i)? { + Ok(j) => x.get(j).copied().ok_or_else(|| KernelError::Failed("ruled surface: the far curve".into())), + Err(p) => Ok(p), + }) + .collect::>>()?; + Ok(Some(with_points(far.rulings.base, &pts))) + }) + .collect() +} + +/// `c` with the control points `pts` (Cartesian), its knots and weights kept. +fn with_points(c: &CurveN<4>, pts: &[Vec3]) -> CurveN<4> { + let ctrl = pts.iter().zip(&c.ctrl).map(|(p, h)| [p.x * h[3], p.y * h[3], p.z * h[3], h[3]]).collect(); + CurveN { degree: c.degree, knots: c.knots.clone(), ctrl } } /// How the rulings are set at a point of an edge. @@ -257,13 +856,13 @@ impl Field { // Square to the reference and the edge, turned away from the face. let mut w = t.cross(r); if w.dot(out + n) < 0.0 { - w = -w; + w = w * -1.0; } r * angle.cos() + w * angle.sin() } RuledMode::Direction(v) => v, }; - let dir = if self.flip { -dir } else { dir }; + let dir = if self.flip { dir * -1.0 } else { dir }; if dir.cross(t).len() < 1e-6 { return Err(KernelError::Invalid("the strip would run along an edge: pick another direction".into())); } @@ -283,86 +882,264 @@ struct End { normal: Vec3, } +/// What a strip's surface is. +enum Kind { + /// The plane through a point spanned by the edge's direction and the ruling (normal t × r). + Plane { o: Vec3, t: Vec3, r: Vec3 }, + /// The ruled NURBS surface from the base curve (v = 0) to its image, the top (v = 1), on + /// their shared knots and weights. + Ruled, +} + /// The strip on one edge. struct Strip { - /// The body's edge, turned to run along the chain. - base: mt::Edge, - surface: mt::Surface, - /// The far edge's curve (from the start's ruling end to the end's). - top: mt::Curve, + /// The edge as a NURBS curve run along the chain. + base: CurveN<4>, + /// The far edge's curve (from the start's ruling end to the end's): the base's image. + top: CurveN<4>, + kind: Kind, /// A plane through a straight edge: its far edge is the line between its corners. line: bool, /// The strip lies in a plane. planar: bool, + /// The axis (a point on it, its direction) of a strip that is a piece of a cone: the edge an + /// arc, its rulings keeping their angle to the arc's axis, leaning in or out. + cone: Option<(Vec3, Vec3)>, start: End, end: End, } impl Strip { - fn new(base: mt::Edge, face: &mt::Face, face_left: bool, field: &Field, eps: f64) -> Result { - let c = base.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let d = field.distance; - // The point, unit tangent, face normal and ruling at a parameter of the edge. - let at = |t: f64| -> Result<(Vec3, Vec3, Vec3, Vec3)> { - let p = from_p3(c.subs(t)); - let tan = from_p3(mt::Point3::new(0.0, 0.0, 0.0) + c.der(t)) - .normalized() - .ok_or_else(|| KernelError::Invalid("a picked edge has a point with no direction".into()))?; - let n = normal_at(face, p) - .ok_or_else(|| KernelError::Invalid("the face beside an edge has a point with no normal there: not supported yet".into()))?; - let out = if face_left { tan.cross(n) } else { n.cross(tan) }; - let out = out.normalized().ok_or_else(|| KernelError::Invalid("the face beside an edge runs along it".into()))?; - Ok((p, tan, n, field.ruling(tan, n, out)?)) - }; - let param = |k: usize, m: usize| t0 + (t1 - t0) * k as f64 / (m - 1) as f64; - let samples: Vec<(Vec3, Vec3, Vec3, Vec3)> = (0..SAMPLES).map(|k| at(param(k, SAMPLES))).collect::>()?; - let (Some(first), Some(last)) = (samples.first().copied(), samples.last().copied()) else { - return Err(KernelError::Failed("ruled surface: samples".into())); - }; - let tops: Vec = samples.iter().map(|(p, _, _, r)| *p + *r * d).collect(); - // A plane through the edge and its rulings, when everything lies in one. - let plane_normal = first.1.cross(first.3).normalized(); - let planar = - plane_normal.is_some_and(|nn| samples.iter().map(|s| s.0).chain(tops.iter().copied()).all(|q| (q - first.0).dot(nn).abs() <= eps)); - let exact = affine(&samples, d, eps).and_then(|m| map_control_points(&c, |p| m.apply(p))); - let line = planar && matches!(c, mt::Curve::Line(_)) && exact.is_some(); - let (surface, top) = match (planar, exact) { - (true, Some(top)) => (plane(first.0, first.1, first.3), top), - (false, Some(top)) => { - let s = mt::BSplineSurface::homotopy(c.clone().lift_up(), top.clone().lift_up()); - (mt::Surface::NurbsSurface(mt::NurbsSurface::new(s)), top) - } - (planar, None) => { - let (s, top) = fitted(&at, ¶m, d)?; - (if planar { plane(first.0, first.1, first.3) } else { s }, top) - } - }; - let (s0, s1) = top.range_tuple(); - let tangent = |s: f64| from_p3(mt::Point3::new(0.0, 0.0, 0.0) + top.der(s)).normalized().unwrap_or(first.1); + /// The strip on `base` from its far curve `top` (on the base's knots and weights), as `sampled` + /// read the rulings along it. + fn new(base: CurveN<4>, top: CurveN<4>, sampled: &Sampled, d: f64) -> Strip { + let (first, last) = (sampled.first, sampled.last); + let kind = if sampled.planar { Kind::Plane { o: first.0, t: first.1, r: first.3 } } else { Kind::Ruled }; + let line = sampled.planar && base.degree == 1 && base.ctrl.len() == 2 && sampled.affine.is_some(); + let tangent = |f: f64| point_tangent(&top, f).and_then(|(_, t)| t.normalized()).unwrap_or(first.1); let end = |(p, _, n, r): (Vec3, Vec3, Vec3, Vec3), tan: Vec3| End { at: p, ruling: r, top: p + r * d, tangent: tan, normal: n }; - Ok(Strip { start: end(first, tangent(s0)), end: end(last, tangent(s1)), base, surface, top, line, planar }) + let cone = match sampled.affine { + Some(Affine::Radial { c, a, scale, .. }) if !sampled.planar && (scale - 1.0).abs() > 1e-12 => Some((c, a)), + _ => None, + }; + Strip { start: end(first, tangent(0.0)), end: end(last, tangent(1.0)), base, top, kind, line, planar: sampled.planar, cone } + } + + /// The strip's face on its own: the base edge, up the end side (`up_end`, points from the + /// edge's end to `top_end`), back along the far edge, down the start side (`up_start`, from + /// the edge's start to `top_start`). + fn face(&self, up_start: &[Vec3], up_end: &[Vec3], top_start: Vec3, top_end: Vec3, tolerance: f64) -> Result { + // A piece of a cone between straight rulings is the ruling at the start turned about the + // cone's axis through the arc's angle, by SMLib's revolve: a cone face, as a cone, where + // the ruled B-spline between the arc and its image is the same surface on no analytic. + if let (Some((c, axis)), [_, _], [_, _]) = (self.cone, up_start, up_end) + && let Some(f) = self.revolved(c, axis, top_start)? + { + return Ok(f); + } + let fail = || KernelError::Failed("ruled surface: a strip".into()); + let mut parts = Parts { tolerance, ..Parts::default() }; + let vertex = |p: Vec3, parts: &mut Parts| -> Result { + let i = u32::try_from(parts.vertices.len()).map_err(|_| fail())?; + parts.vertices.push(b::Vertex { point: [p.x, p.y, p.z], tolerance }); + Ok(i) + }; + let [u0, u1] = range(&self.base); + // The loop's corners and the curves between them, counter-clockwise about the strip's + // natural normal (t × r). + let (bs, be) = (point(&self.base, 0.0).ok_or_else(fail)?, point(&self.base, 1.0).ok_or_else(fail)?); + let corners: Vec = [bs, be].into_iter().map(|p| vertex(p, &mut parts)).collect::>()?; + let (base, base_iv) = spline_curve(&hpoints(&self.base), self.base.knots.clone())?; + let mut uses: Vec<(b::Curve, [f64; 2], [u32; 2], bool, Option)> = Vec::new(); + let ruled = matches!(self.kind, Kind::Ruled); + uses.push((base, base_iv, [corners[0], corners[1]], true, ruled.then_some(([u0, 0.0], [u1, 0.0])))); + let chain_up = |pts: &[Vec3], from: u32, u: f64, parts: &mut Parts, uses: &mut Vec<_>| -> Result { + let mut at = from; + for w in pts.windows(2) { + let next = vertex(w[1], parts)?; + let pc = ruled.then_some(([u, 0.0], [u, 1.0])); + uses.push((b::Curve::Line { start: [w[0].x, w[0].y, w[0].z], end: [w[1].x, w[1].y, w[1].z] }, [0.0, 1.0], [at, next], true, pc)); + at = next; + } + Ok(at) + }; + let end_top = chain_up(up_end, corners[1], u1, &mut parts, &mut uses)?; + // Down the start side, made from the bottom up and walked backwards. + let mut start_side = Vec::new(); + let start_top = chain_up(up_start, corners[0], u0, &mut parts, &mut start_side)?; + let (top, top_iv) = if self.line { + (b::Curve::Line { start: [top_start.x, top_start.y, top_start.z], end: [top_end.x, top_end.y, top_end.z] }, [0.0, 1.0]) + } else { + spline_curve(&hpoints(&self.top), self.top.knots.clone())? + }; + uses.push((top, top_iv, [start_top, end_top], false, ruled.then_some(([u0, 1.0], [u1, 1.0])))); + for (curve, iv, ends, _, pc) in start_side.into_iter().rev() { + uses.push((curve, iv, ends, false, pc)); + } + let surface = match self.kind { + Kind::Plane { o, t, r } => b::Surface::PlaneThrough { + origin: [o.x, o.y, o.z], + u_point: [o.x + t.x, o.y + t.y, o.z + t.z], + v_point: [o.x + r.x, o.y + r.y, o.z + r.z], + }, + Kind::Ruled => { + let mut ctrl = hpoints(&self.base); + ctrl.extend(hpoints(&self.top)); + // u along the edge (fastest), v across: the base row, then the top row. + spline_surface( + &NurbsSurface::from_homogeneous([self.base.degree, 1], [self.base.knots.clone(), vec![0.0, 0.0, 1.0, 1.0]], ctrl) + .map_err(|e| KernelError::Failed(format!("ruled surface: {e}")))?, + ) + } + }; + face_of(parts, surface, uses) + } + + /// [`Strip::face`] of a strip on a cone (`c`, `axis` its axis) bounded by straight rulings: + /// the start's ruling (from the edge's start to `top_start`) turned through the arc's angle, + /// right-handed about `axis` the way the edge runs; `None` where the edge's turn can't be read. + fn revolved(&self, c: Vec3, axis: Vec3, top_start: Vec3) -> Result> { + let (Some(bs), Some(be), Some((pm, _))) = (point(&self.base, 0.0), point(&self.base, 1.0), point_tangent(&self.base, 0.5)) else { + return Ok(None); + }; + let flat = |p: Vec3| { + let q = p - c; + q - axis * q.dot(axis) + }; + let angle_to = |p: Vec3| { + let (a, b) = (flat(bs), flat(p)); + a.cross(b).dot(axis).atan2(a.dot(b)) + }; + // The turn to the end, the way the edge runs (through its middle); a closed arc is a turn. + let half = angle_to(pm); + let mut turn = angle_to(be); + if bs.dist(be) <= 1e-9 * (1.0 + flat(bs).len()) { + turn = std::f64::consts::TAU.copysign(half); + } else if half > 0.0 && turn < 0.0 { + turn += std::f64::consts::TAU; + } else if half < 0.0 && turn > 0.0 { + turn -= std::f64::consts::TAU; + } + let side = top_start - bs; + let Some(x) = side.normalized() else { return Ok(None) }; + let Some(y) = (flat(bs) - x * flat(bs).dot(x)).normalized().or_else(|| (axis - x * axis.dot(x)).normalized()) else { return Ok(None) }; + let plane = solidcore_record::Plane { origin: bs, x, y }; + let line = solidcore_record::Seg2::Line { a: solidcore_record::Vec2::ZERO, b: solidcore_record::Vec2::new(side.len(), 0.0) }; + // SMLib turns right-handed about the axis it is given. + let (axis, turn) = if turn < 0.0 { (axis * -1.0, -turn) } else { (axis, turn) }; + Ok(Some(crate::surfaces::revolved_record(&plane, &[line], c, axis, turn)?)) } } -/// The unit normal of `face` (as it faces) at its point nearest `p`. -fn normal_at(face: &mt::Face, p: Vec3) -> Option { - let surface = face.oriented_surface(); - let (u, v) = surface.search_nearest_parameter(p3(p), None, 100)?; - from_p3(mt::Point3::new(0.0, 0.0, 0.0) + surface.normal(u, v)).normalized() +/// A pcurve given as a straight line between two (u, v) points over its edge's interval. +type Curve2Pair = ([f64; 2], [f64; 2]); + +/// One face of the record `parts` (whose vertices are in place) on `surface`, bounded by one loop +/// of `uses`: each edge's curve, interval, vertices, whether the loop runs along it, and its +/// straight pcurve where known (else the shared pcurve routine's, exact for lines and splines on +/// a plane). +fn face_of(mut parts: Parts, surface: b::Surface, uses: Vec<(b::Curve, [f64; 2], [u32; 2], bool, Option)>) -> Result { + let tolerance = parts.tolerance; + let mut given = Vec::with_capacity(uses.len()); + for (curve, interval, vertices, forward, pc) in uses { + parts.edges.push(b::Edge { nurbs: None, curve, interval, vertices, tolerance, uses: Vec::new() }); + given.push((forward, pc.map(|(a, z)| uv_line(a, z, interval)))); + } + let loop_uses = parts + .edges + .iter() + .zip(&given) + .enumerate() + .map(|(i, (e, (forward, pc)))| { + let edge = u32::try_from(i).map_err(|_| KernelError::Failed("ruled surface: an edge".into()))?; + Ok(solidcraft_geom::brep::pcurve::EdgeUse { + edge, + curve: e.parameters(), + interval: e.interval, + forward: *forward, + tolerance, + given: pc.as_ref(), + }) + }) + .collect::>>()?; + let pcurves = + solidcraft_geom::brep::pcurve::pcurves(&surface, &[loop_uses], tolerance).map_err(|e| KernelError::Failed(format!("ruled surface: {e}")))?; + let edges = given + .iter() + .zip(pcurves.into_iter().flatten()) + .enumerate() + .map(|(i, ((forward, _), pcurve))| { + Ok(b::OrientedEdge { + edge: u32::try_from(i).map_err(|_| KernelError::Failed("ruled surface: an edge".into()))?, + forward: *forward, + pcurve, + }) + }) + .collect::>>()?; + let loops = vec![b::Loop::Edges { edges }]; + let domain = match &surface { + b::Surface::Spline { u_knots, v_knots, points } => [natural(u_knots, points.len()), natural(v_knots, points.first().map_or(0, Vec::len))], + b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + [natural(u_knots, homogeneous.len()), natural(v_knots, homogeneous.first().map_or(0, Vec::len))] + } + _ => uv_bounds(&loops).ok_or_else(|| KernelError::Invalid("a ruled face encloses no area".into()))?, + }; + parts.faces.push((b::Face { nurbs: None, surface, domain, loops }, true)); + Ok(parts.canonical()?.brep) } -/// The plane through `o` spanned by the edge direction `t` and the ruling `r`, its normal t × r -/// (the strip's own orientation). -fn plane(o: Vec3, t: Vec3, r: Vec3) -> mt::Surface { - mt::Surface::Plane(mt::Plane::new(p3(o), p3(o + t), p3(o + r))) +/// A spline direction's knot domain. +fn natural(knots: &[f64], count: usize) -> [f64; 2] { + let p = knots.len().saturating_sub(count + 1); + [knots.get(p).copied().unwrap_or(0.0), knots.get(count).copied().unwrap_or(1.0)] +} + +/// The box of a face's pcurves' control points. +fn uv_bounds(loops: &[b::Loop]) -> Option<[[f64; 2]; 2]> { + let mut bx = [[f64::INFINITY, f64::NEG_INFINITY]; 2]; + for l in loops { + let b::Loop::Edges { edges } = l else { continue }; + for u in edges { + let pts: Vec<[f64; 2]> = match &u.pcurve { + b::Curve2::Spline { points, .. } => points.clone(), + b::Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().map(|h| [h[0] / h[2], h[1] / h[2]]).collect(), + }; + for p in pts { + for (d, x) in bx.iter_mut().zip(p) { + d[0] = d[0].min(x); + d[1] = d[1].max(x); + } + } + } + } + bx.iter().all(|d| d[0].is_finite() && d[1] > d[0]).then_some(bx) +} + +/// A flat polygon face through `pts` (three or more, in order), on the plane through its first +/// three points (its normal (b − a) × (c − a)). +fn polygon(pts: &[Vec3], tolerance: f64) -> Result { + let (Some(a), Some(bb), Some(c)) = (pts.first(), pts.get(1), pts.get(2)) else { + return Err(KernelError::Failed("ruled surface: a corner".into())); + }; + let mut parts = Parts { tolerance, ..Parts::default() }; + parts.vertices = pts.iter().map(|p| b::Vertex { point: [p.x, p.y, p.z], tolerance }).collect(); + let n = pts.len(); + let uses = (0..n) + .map(|i| { + let (p, q) = (pts[i], pts[(i + 1) % n]); + let ends = [u32::try_from(i).unwrap_or(0), u32::try_from((i + 1) % n).unwrap_or(0)]; + (b::Curve::Line { start: [p.x, p.y, p.z], end: [q.x, q.y, q.z] }, [0.0, 1.0], ends, true, None) + }) + .collect(); + let surface = b::Surface::PlaneThrough { origin: [a.x, a.y, a.z], u_point: [bb.x, bb.y, bb.z], v_point: [c.x, c.y, c.z] }; + face_of(parts, surface, uses) } /// An affine map taking each point of an edge to the end of its ruling. enum Affine { Translate(Vec3), - /// Points scaled by `scale` about the axis through `c` along `a` (in its square plane), - /// then moved by `shift`. + /// Points scaled by `scale` about the axis through `c` along `a` (in its square plane), then + /// moved by `shift`. Radial { c: Vec3, a: Vec3, @@ -400,7 +1177,7 @@ fn affine(samples: &[(Vec3, Vec3, Vec3, Vec3)], d: f64, eps: f64) -> Option 1e-24) { return None; } - let centre = a + (v.cross(w) * u.dot(u) + w.cross(u) * v.dot(v)) / (2.0 * ww); + let centre = a + (v.cross(w) * u.dot(u) + w.cross(u) * v.dot(v)) * (1.0 / (2.0 * ww)); let axis = w.normalized()?; let radius = (a - centre).len(); let (mut radial, mut along) = (None, None); @@ -420,35 +1197,6 @@ fn affine(samples: &[(Vec3, Vec3, Vec3, Vec3)], d: f64, eps: f64) -> Option Result<(Vec3, Vec3, Vec3, Vec3)>, param: &dyn Fn(usize, usize) -> f64, d: f64) -> Result<(mt::Surface, mt::Curve)> { - let mut m = SAMPLES + 1; - loop { - let pts: Vec<(Vec3, Vec3, Vec3, Vec3)> = (0..m).map(|k| at(param(k, m))).collect::>()?; - let near: Vec = pts.iter().map(|s| s.0).collect(); - let far: Vec = pts.iter().map(|s| s.0 + s.3 * d).collect(); - let fail = || KernelError::Failed("ruled surface: fitting a strip".into()); - let (base, top) = (crate::build::interpolate_cubic(&near).ok_or_else(fail)?, crate::build::interpolate_cubic(&far).ok_or_else(fail)?); - // Checked between the samples, where a fit strays most. - let mut worst = 0.0f64; - for k in 0..m - 1 { - let s = (k as f64 + 0.5) / (m - 1) as f64; - let (p, _, _, r) = at(param(2 * k + 1, 2 * m - 1))?; - worst = worst.max(from_p3(base.subs(s)).dist(p)).max(from_p3(top.subs(s)).dist(p + r * d)); - } - if worst <= FIT_TOLERANCE { - let surface = mt::Surface::BSplineSurface(mt::BSplineSurface::homotopy(base, top.clone())); - return Ok((surface, mt::Curve::BSplineCurve(top))); - } - if m >= MAX_FIT_SAMPLES { - return Err(KernelError::Invalid(format!("the strip can't be fitted within {FIT_TOLERANCE} mm (off by up to {worst:.4} mm)"))); - } - m = (2 * m - 1).min(MAX_FIT_SAMPLES); - } -} - /// Which strip of a joint: the one ending there or the one starting there. #[derive(Clone, Copy, PartialEq, Eq)] enum Side { @@ -458,37 +1206,32 @@ enum Side { /// How the strips meet at a vertex of the chain (or end at a free end of it). enum Joint { - /// One side edge from the vertex up the ruling: the strips' rulings agree, or a free end. - Shared(mt::Edge), - /// Mitred: the edge from the vertex to where the strips' far edges meet (`m`); a curved - /// strip keeps its own side edge and gets a triangle (`incoming`, `outgoing`) up to it. - Mitre { edge: mt::Edge, m: mt::Vertex, incoming: Option<(mt::Edge, mt::Face)>, outgoing: Option<(mt::Edge, mt::Face)> }, - /// Rounded: each strip's own side edge, and the sector turning one into the other (in - /// pieces of less than a half turn). - Round { incoming: mt::Edge, outgoing: mt::Edge, sector: Vec }, + /// One side edge from the vertex up the ruling to `top`: the strips' rulings agree, or a free + /// end. + Shared { at: Vec3, top: Vec3 }, + /// Mitred: the edge from the vertex to where the strips' far edges meet (`m`); a curved strip + /// keeps its own side edge and gets a triangle up to `m` (its own side's top given). + Mitre { at: Vec3, m: Vec3, incoming: Option, outgoing: Option }, + /// Rounded: each strip's own side edge (to `incoming`, `outgoing`), and the sector SMLib + /// revolves from one into the other about `axis` through the vertex by `turn`. + Round { at: Vec3, incoming: Vec3, outgoing: Vec3, axis: Vec3, turn: f64 }, } impl Joint { fn new(a: Option<&Strip>, b: Option<&Strip>, mode: &RuledMode, corners: RuledCorners, eps: f64) -> Result { - let side = |s: &Strip, e: &End, from_start: bool| { - let v = if from_start { s.base.front().clone() } else { s.base.back().clone() }; - let top = mt::Vertex::new(p3(e.top)); - mt::Edge::new_unchecked(&v, &top, mt::Curve::Line(mt::Line(v.point(), top.point()))) - }; let (a, b) = match (a, b) { (Some(a), Some(b)) => (a, b), - (Some(a), None) => return Ok(Joint::Shared(side(a, &a.end, false))), - (None, Some(b)) => return Ok(Joint::Shared(side(b, &b.start, true))), + (Some(a), None) => return Ok(Joint::Shared { at: a.end.at, top: a.end.top }), + (None, Some(b)) => return Ok(Joint::Shared { at: b.start.at, top: b.start.top }), (None, None) => return Err(KernelError::Failed("ruled surface: an empty joint".into())), }; let (ea, eb) = (&a.end, &b.start); - let vertex = a.base.back().clone(); + let vertex = ea.at; if (ea.ruling - eb.ruling).len() <= SAME_RULING { - let top = mt::Vertex::new(p3((ea.top + eb.top) * 0.5)); - return Ok(Joint::Shared(mt::Edge::new_unchecked(&vertex, &top, mt::Curve::Line(mt::Line(vertex.point(), top.point()))))); + return Ok(Joint::Shared { at: vertex, top: (ea.top + eb.top) * 0.5 }); } - // Where the far edges, carried on straight, meet: λ along the incoming one past its - // end, μ along the outgoing one past its start. + // Where the far edges, carried on straight, meet: λ along the incoming one past its end, + // μ along the outgoing one past its start. let meet = || -> Option<(Vec3, f64, f64)> { let (p, q, u, v) = (ea.top, eb.top, ea.tangent, eb.tangent); let w = p - q; @@ -504,8 +1247,7 @@ impl Joint { // An inside corner (the strips overlap) is cut back where the far edges meet; that needs // straight far edges. let inside = eb.ruling.dot(ea.tangent) - ea.ruling.dot(eb.tangent) < -1e-9; - let corner_at = vertex.point(); - let refuse = |what: &str| KernelError::Invalid(format!("{what} at the corner at {:?}", from_p3(corner_at))); + let refuse = |what: &str| KernelError::Invalid(format!("{what} at the corner at {vertex:?}")); if corners == RuledCorners::Mitre || inside { let (m, lam, mu) = meet().ok_or_else(|| refuse("the strips' far edges don't meet: try round corners,"))?; let convex = lam > 0.0 && mu < 0.0; @@ -516,31 +1258,13 @@ impl Joint { if concave && !(a.line && b.line) { return Err(refuse("not supported yet: cutting back a curved strip")); } - let mv = mt::Vertex::new(p3(m)); - let edge = mt::Edge::new_unchecked(&vertex, &mv, mt::Curve::Line(mt::Line(vertex.point(), mv.point()))); - // A strip that isn't a plane keeps its side edge and gets a triangle up to the - // mitre, in its tangent plane there. - let triangle = |s: &Strip, e: &End, from_start: bool| -> Option<(mt::Edge, mt::Face)> { - if s.planar { - return None; - } - let own = side(s, e, from_start); - let top = own.back().clone(); - let rim = mt::Edge::new_unchecked(&mv, &top, mt::Curve::Line(mt::Line(mv.point(), top.point()))); - let (wire, surface): (Vec, _) = if from_start { - (vec![own.clone(), rim.inverse(), edge.inverse()], plane_through(e.at, e.top, m)) - } else { - (vec![edge.clone(), rim, own.inverse()], plane_through(e.at, m, e.top)) - }; - Some((own, mt::Face::new_unchecked(vec![wire.into()], surface))) - }; - let incoming = triangle(a, ea, false); - let outgoing = triangle(b, eb, true); - return Ok(Joint::Mitre { edge, m: mv, incoming, outgoing }); + // A strip that isn't a plane keeps its side edge and gets a triangle up to the mitre. + let own = |s: &Strip, e: &End| (!s.planar).then_some(e.top); + return Ok(Joint::Mitre { at: vertex, m, incoming: own(a, ea), outgoing: own(b, eb) }); } - // Rounded: the incoming ruling turned into the outgoing one about an axis both keep - // the same angle to (the reference direction, or the faces' normal: a cone), else - // about the axis square to both (a flat sector). + // Rounded: the incoming ruling turned into the outgoing one about an axis both keep the + // same angle to (the reference direction, or the faces' normal: a cone), else about the + // axis square to both (a flat sector). let mut axes: Vec = Vec::new(); if let RuledMode::Angle { reference: Some(r), .. } = mode { axes.push(*r); @@ -558,78 +1282,70 @@ impl Joint { .ok_or_else(|| refuse("the strips turn back on each other"))?; let (pa, pb) = (flat(ea.ruling, axis), flat(eb.ruling, axis)); let turn = pa.cross(pb).dot(axis).atan2(pa.dot(pb)); - let (axis, turn) = if turn < 0.0 { (-axis, -turn) } else { (axis, turn) }; + let (axis, turn) = if turn < 0.0 { (axis * -1.0, -turn) } else { (axis, turn) }; if !(turn > 1e-9 && turn < std::f64::consts::PI - 1e-6) { return Err(refuse("the strips turn back on each other")); } - let incoming = side(a, ea, false); - // Swept about the vertex (on the axis, so the sector closes there in a point). - let mut sector: Vec = mt::builder::cone(&vec![incoming.clone()].into(), v3(axis), mt::Rad(turn)).into_iter().collect(); - let edges: Vec = - sector.iter().flat_map(|f| f.boundaries().into_iter().flat_map(|w| w.edge_iter().cloned().collect::>())).collect(); - // The sector runs down the incoming side (the strip runs up it). - if edges.iter().any(|e| e.id() == incoming.id() && e.front().id() == vertex.id()) { - for f in &mut sector { - f.invert(); - } - } - // Its other side: the edge from the vertex that only one piece of it has. - let uses = |id: mt::EdgeID| edges.iter().filter(|e| e.id() == id).count(); - let outgoing = edges - .iter() - .find(|e| e.id() != incoming.id() && uses(e.id()) == 1 && (e.front().id() == vertex.id() || e.back().id() == vertex.id())) - .map(|e| if e.front().id() == vertex.id() { e.clone() } else { e.inverse() }) - .ok_or_else(|| KernelError::Failed("ruled surface: a round corner's side".into()))?; - Ok(Joint::Round { incoming, outgoing, sector }) + Ok(Joint::Round { at: vertex, incoming: ea.top, outgoing: eb.top, axis, turn }) } - /// The edges a strip runs up from the joint's vertex (in order), and the vertex its far edge - /// starts or ends at. - fn side(&self, which: Side, s: &Strip) -> (Vec, mt::Vertex) { - match self { - Joint::Shared(e) => (vec![e.clone()], e.back().clone()), - Joint::Round { incoming, outgoing, .. } => { - let e = if which == Side::In { incoming } else { outgoing }; - (vec![e.clone()], e.back().clone()) + /// The points a strip's side runs through from the joint's vertex up (its edges are the lines + /// between them), and the point its far edge starts or ends at. + fn side(&self, which: Side, s: &Strip) -> (Vec, Vec3) { + match *self { + Joint::Shared { at, top } => (vec![at, top], top), + Joint::Round { at, incoming, outgoing, .. } => { + let top = if which == Side::In { incoming } else { outgoing }; + (vec![at, top], top) } - Joint::Mitre { edge, m, incoming, outgoing } => { - let own = if which == Side::In { incoming } else { outgoing }; - if let Some((e, _)) = own { - return (vec![e.clone()], e.back().clone()); + Joint::Mitre { at, m, incoming, outgoing } => { + if let Some(top) = if which == Side::In { incoming } else { outgoing } { + return (vec![at, top], top); } if s.line { - return (vec![edge.clone()], m.clone()); + return (vec![at, m], m); } // A plane under a curved far edge: on along the mitre's far edge to it. - let e = if which == Side::In { &s.end } else { &s.start }; - let top = mt::Vertex::new(p3(e.top)); - let rim = mt::Edge::new_unchecked(m, &top, mt::Curve::Line(mt::Line(m.point(), top.point()))); - (vec![edge.clone(), rim], top) + let top = if which == Side::In { s.end.top } else { s.start.top }; + (vec![at, m, top], top) } } } /// The joint's own faces: a round corner's sector, a mitre's triangles. - fn corner_faces(&self) -> Vec<&mt::Face> { - match self { - Joint::Shared(_) => Vec::new(), - Joint::Round { sector, .. } => sector.iter().collect(), - Joint::Mitre { incoming, outgoing, .. } => incoming.iter().chain(outgoing).map(|(_, f)| f).collect(), + fn corner_faces(&self, tolerance: f64) -> Result> { + match *self { + Joint::Shared { .. } => Ok(Vec::new()), + Joint::Mitre { at, m, incoming, outgoing } => { + let mut out = Vec::new(); + if let Some(top) = incoming { + out.push(polygon(&[at, m, top], tolerance)?); + } + if let Some(top) = outgoing { + out.push(polygon(&[at, top, m], tolerance)?); + } + Ok(out) + } + Joint::Round { at, incoming, axis, turn, .. } => { + // The incoming side as a line in the plane it spans with the axis, turned about the + // axis through the vertex (a cone with its apex there, or a flat sector). + let side = incoming - at; + let x = side.normalized().ok_or_else(|| KernelError::Failed("ruled surface: a round corner".into()))?; + let y = (axis - x * axis.dot(x)).normalized().ok_or_else(|| KernelError::Failed("ruled surface: a round corner".into()))?; + let plane = solidcore_record::Plane { origin: at, x, y }; + let line = solidcore_record::Seg2::Line { a: solidcore_record::Vec2::ZERO, b: solidcore_record::Vec2::new(side.len(), 0.0) }; + Ok(vec![crate::surfaces::revolved_record(&plane, &[line], at, axis, turn)?]) + } } } } -/// The plane through three points, its normal (b − a) × (c − a). -fn plane_through(a: Vec3, b: Vec3, c: Vec3) -> mt::Surface { - mt::Surface::Plane(mt::Plane::new(p3(a), p3(b), p3(c))) -} - #[cfg(test)] mod tests { use std::collections::HashMap; use std::f64::consts::{FRAC_1_SQRT_2, PI}; - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; use super::*; use crate::history::FaceOrigin; @@ -645,12 +1361,28 @@ mod tests { measure(b).unwrap().area } /// How many faces use each edge of a body. - fn uses(b: &Body) -> HashMap { - let mut m = HashMap::new(); - for e in b.solid.face_iter().flat_map(|f| f.boundaries().into_iter().flat_map(|w| w.edge_iter().map(|e| e.id()).collect::>())) { - *m.entry(e).or_default() += 1; - } - m + fn uses(b: &Body) -> HashMap { + b.record().edges.iter().enumerate().map(|(i, e)| (i, e.uses.len())).collect() + } + /// The edges of `s` that lie along a straight edge of `b` (their middles on it). + fn on_edges_of(s: &Body, b: &Body) -> usize { + let on = |p: Vec3| { + b.record().edges.iter().any(|e| match e.curve { + solidcore_record::brep::Curve::Line { start, end } => { + let (a, z) = (Vec3::new(start[0], start[1], start[2]), Vec3::new(end[0], end[1], end[2])); + p.dist_to_segment(a, z) < 1e-6 + } + _ => false, + }) + }; + s.record() + .edges + .iter() + .filter(|e| { + let c = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).unwrap(); + on(c.point(0.5 * (e.interval[0] + e.interval[1])).unwrap()) + }) + .count() } fn shared(b: &Body) -> usize { uses(b).values().filter(|n| **n == 2).count() @@ -754,17 +1486,18 @@ mod tests { let cases = [ (ruled(RuledMode::Normal, 2.0, top), 80.0, 4, 4), (ruled(RuledMode::Tangent, 2.0, top), 14.0 * 14.0 - 100.0, 4, 4), - (round(RuledMode::Tangent), 80.0 + PI * 4.0, 12, 12), + // Each round corner is one face, SMLib's revolve of a quarter turn (truck's cone + // builder split it in two): four strips and four sectors, each sharing its two sides. + (round(RuledMode::Tangent), 80.0 + PI * 4.0, 8, 8), (ruled(angle, 2.0, top), 80.0 + 4.0 * 2.0 * h, 4, 4), - (round(angle), 80.0 + PI * h * 2.0, 12, 12), + (round(angle), 80.0 + PI * h * 2.0, 8, 8), ]; for (r, want, faces, joins) in cases { let s = ruled_surface(&b, &rim, &r).unwrap(); assert!(rel(area(&s), want) < 2e-3, "{r:?}: {} vs {want}", area(&s)); // (measured on meshes) assert_eq!((s.face_count(), shared(&s)), (faces, joins), "{r:?}"); // The strips stand on the box's own edges. - let own: std::collections::HashSet = b.solid.edge_iter().map(|e| e.id()).collect(); - assert_eq!(uses(&s).keys().filter(|e| own.contains(e)).count(), 4); + assert_eq!(on_edges_of(&s, &b), 4); let sewn = crate::stitch(&[&s], 0.0).unwrap(); assert_eq!((sewn.face_count(), shared(&sewn), uses(&sewn).len()), (faces, joins, uses(&s).len()), "{r:?}"); } @@ -815,10 +1548,13 @@ mod tests { } /// Off a doubly curved face (a saddle patch over a cup's rim) its normal turns along a - /// straight edge: the strip is a fitted ruled B-spline, its rulings square to the edge, so - /// it reaches exactly 3 from the edge's line (within the fit) and covers it end to end. + /// straight edge: the strip is ruled to a far curve of its own, from corner to corner, which + /// its handles move. Lifting every handle (the far curve's interior control points) 1 mm in z + /// gives the far curve those control points and the same corners, so it rises by + /// 1 − R₀ − Rₙ (its end basis functions) inside and not at all at the corners; the strip built + /// with them has that curve for its far edge, away from where the default strip's runs. #[test] - fn a_strip_off_a_curved_face_is_fitted() { + fn a_strip_off_a_curved_face_is_ruled_to_its_far_curve() { let b = box_solid(Vec3::new(-14.0, -14.0, 0.0), Vec3::new(14.0, 14.0, 20.0)).unwrap(); let tool = cylinder(Vec3::new(0.0, -60.0, 50.0), Vec3::Y, 40.0, 120.0).unwrap(); let cup = crate::boolean(&b, &tool, crate::BoolOp::Cut).unwrap().unwrap(); @@ -826,14 +1562,34 @@ mod tests { let rim = [Vec3::new(14.0, 0.0, z(14.0)), Vec3::new(0.0, 14.0, z(0.0)), Vec3::new(-14.0, 0.0, z(-14.0)), Vec3::new(0.0, -14.0, z(0.0))]; let cover = crate::patch_edges(&cup, &rim).unwrap(); let edge = [Vec3::new(14.0, 0.0, z(14.0))]; - let s = ruled_surface(&cover, &edge, &ruled(RuledMode::Normal, 3.0, Vec3::new(0.0, 0.0, 12.0))).unwrap(); - assert!(s.face_count() == 1 && face_surface(&s, 0).is_none(), "{:?}", face_surface(&s, 0)); - let mesh = s.tessellate(0.01).unwrap(); - let from_line = |p: &Vec3| Vec3::new(p.x - 14.0, 0.0, p.z - z(14.0)).len(); - let far = mesh.positions.iter().map(from_line).fold(0.0, f64::max); - assert!((far - 3.0).abs() < 2e-3, "{far}"); - let bb = measure(&s).unwrap().bbox; - assert!((bb.min.y + 14.0).abs() < 1e-3 && (bb.max.y - 14.0).abs() < 1e-3, "{bb:?}"); + let r = ruled(RuledMode::Normal, 3.0, Vec3::new(0.0, 0.0, 12.0)); + let s = ruled_surface(&cover, &edge, &r).unwrap(); + assert!(s.is_surface() && s.face_count() == 1); + let handles = ruled_far_handles(&cover, &edge, &r).unwrap(); + let [Some(h)] = handles.as_slice() else { panic!("one free strip: {handles:?}") }; + assert!(!h.is_empty(), "the far curve has interior control points to move"); + let lifted: Vec = h.iter().map(|p| *p + Vec3::new(0.0, 0.0, 1.0)).collect(); + let moved = ruled_surface_with(&cover, &edge, &r, &[Some(lifted.clone())]).unwrap(); + // The plan takes the handles as they are, and keeps the corners. + let (plain, given) = (planned(&cover, &edge, &r, &[]).unwrap(), planned(&cover, &edge, &r, &[Some(lifted.clone())]).unwrap()); + let (far, far_moved) = (&plain.strips[0].top, &given.strips[0].top); + let ctrl = |c: &CurveN<4>| c.ctrl.iter().map(|h| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])).collect::>(); + let (before, after) = (ctrl(far), ctrl(far_moved)); + assert_eq!(after.len(), lifted.len() + 2); + assert!(after[1..after.len() - 1].iter().zip(&lifted).all(|(a, b)| a.dist(*b) < 1e-12), "{after:?} vs {lifted:?}"); + assert!(before[0].dist(after[0]) < 1e-12 && before[before.len() - 1].dist(after[after.len() - 1]) < 1e-12); + // The built strip's far edge is that curve (its edges' polylines within 1e-4 of their + // curves), and its middle is well off the default strip's edges. + let tol = 1e-4; + for i in 0..=32 { + let p = point(far_moved, f64::from(i) / 32.0).unwrap(); + let (_, d) = moved.nearest_edge(p, tol).unwrap().unwrap(); + assert!(d < 10.0 * tol, "the far curve at {i}/32, {p:?}, is {d} from the strip's edges"); + } + let (mid, rose) = (point(far_moved, 0.5).unwrap(), point(far_moved, 0.5).unwrap().dist(point(far, 0.5).unwrap())); + assert!(rose > 0.1, "the middle rose {rose}"); + let (_, d) = s.nearest_edge(mid, tol).unwrap().unwrap(); + assert!(d > 0.5 * rose, "the default strip has an edge {d} from the moved middle (it rose {rose})"); } /// Each strip is made in place of the edge it stands on; a corner face in place of the two diff --git a/crates/kernel/src/surface_second_derivative_tests.rs b/crates/kernel/src/surface_second_derivative_tests.rs index 76265437f..c28424396 100644 --- a/crates/kernel/src/surface_second_derivative_tests.rs +++ b/crates/kernel/src/surface_second_derivative_tests.rs @@ -1,36 +1,35 @@ -//! The vendored truck-geometry's second derivatives of B-spline and NURBS surfaces (`uuder`, -//! `vvder`) against finite differences of the surface itself, for degrees 2 to 5. Upstream's -//! were short of the factor p − 1, so every curvature read from a cubic surface came out half its -//! value (#763: a G2 boundary surface measured half the cylinder's curvature it does carry). -//! These pin the vendored fix, so a refresh of the crate can't quietly bring the error back. +//! The record evaluator's second derivatives of B-spline and NURBS surfaces +//! (`SurfaceEval::second`) against finite differences of the surface itself, for degrees 2 to 5: +//! every curvature the kernel reads (continuity, the G2 fill's frames) comes from them (#763: a G2 +//! boundary surface once measured half the cylinder's curvature it does carry). -use solidcraft_geom::Vec3; -use truck_modeling as mt; -use truck_modeling::ParametricSurface; +use solidcore_record::Vec3; +use solidcore_record::brep::Surface; +use solidcraft_geom::brep::eval::SurfaceEval; +use solidcraft_geom::prelude::*; -use crate::body::from_p3; - -/// A degree-`p` × degree-`q` surface on a 5 × 6 net with an interior knot each way, bent in z. -fn surface(p: usize, q: usize) -> mt::BSplineSurface { +/// A degree-`p` × degree-`q` surface on a net of `p + 3` × `q + 3` points with interior knots each +/// way, bent in z: its knots and points (`rows[i][j]`, i along u). +fn net(p: usize, q: usize) -> (Vec, Vec, Vec>) { let knots = |d: usize, n: usize| { let inner: Vec = (1..n - d).map(|k| k as f64 / (n - d) as f64).collect(); let mut k = vec![0.0; d + 1]; k.extend(inner); k.extend(vec![1.0; d + 1]); - mt::KnotVec::from(k) + k }; let (nu, nv) = (p + 3, q + 3); - let rows: Vec> = (0..nu) + let rows = (0..nu) .map(|i| { (0..nv) .map(|j| { let (x, y) = (i as f64 * 2.0, j as f64 * 1.5); - mt::Point3::new(x + 0.3 * y, y, 0.4 * x * x - 0.2 * y * y + 0.1 * x * y) + [x + 0.3 * y, y, 0.4 * x * x - 0.2 * y * y + 0.1 * x * y] }) .collect() }) .collect(); - mt::BSplineSurface::new((knots(p, nu), knots(q, nv)), rows) + (knots(p, nu), knots(q, nv), rows) } /// Second differences of `f` along the parameter line, central inside and one-sided at the ends. @@ -45,34 +44,35 @@ fn second(f: impl Fn(f64) -> Vec3, t: f64) -> Vec3 { } } -fn v3(x: mt::Vector3) -> Vec3 { - Vec3::new(x.x, x.y, x.z) +/// The surface's second derivatives along u and v at each `(u, v)` against finite differences. +fn check(s: &SurfaceEval, at: &[(f64, f64)], what: &str) { + for &(u, v) in at { + let uu = second(|t| s.point([t, v]).unwrap(), u); + let vv = second(|t| s.point([u, t]).unwrap(), v); + let (suu, _, svv) = s.second(u, v).unwrap(); + let scale = uu.len().max(vv.len()).max(1.0); + assert!(suu.dist(uu) < 1e-4 * scale, "{what}: S_uu at ({u}, {v}): {suu:?} vs {uu:?}"); + assert!(svv.dist(vv) < 1e-4 * scale, "{what}: S_vv at ({u}, {v}): {svv:?} vs {vv:?}"); + } } #[test] fn bspline_surface_second_derivatives_match_finite_differences() { for p in 2..=5 { for q in 2..=5 { - let s = surface(p, q); - for (u, v) in [(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2), (0.13, 1.0)] { - let uu = second(|t| from_p3(s.subs(t, v)), u); - let vv = second(|t| from_p3(s.subs(u, t)), v); - let scale = uu.len().max(vv.len()).max(1.0); - assert!(v3(s.uuder(u, v)).dist(uu) < 1e-4 * scale, "degree ({p}, {q}) uuder at ({u}, {v}): {:?} vs {uu:?}", s.uuder(u, v)); - assert!(v3(s.vvder(u, v)).dist(vv) < 1e-4 * scale, "degree ({p}, {q}) vvder at ({u}, {v}): {:?} vs {vv:?}", s.vvder(u, v)); - } + let (u_knots, v_knots, points) = net(p, q); + let s = SurfaceEval::new(&Surface::Spline { u_knots, v_knots, points }).unwrap(); + check(&s, &[(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2), (0.13, 1.0)], &format!("degree ({p}, {q})")); } } } -/// A rational surface's second derivatives come from its homogeneous B-spline's: they are right -/// too. +/// A rational surface's second derivatives come from its homogeneous B-spline's by the quotient +/// rule: they are right too. #[test] fn nurbs_surface_second_derivatives_match_finite_differences() { - let b = surface(3, 3); - let (ku, kv) = b.knot_vecs().clone(); - let rows: Vec> = b - .control_points() + let (u_knots, v_knots, points) = net(3, 3); + let homogeneous = points .iter() .enumerate() .map(|(i, row)| { @@ -80,17 +80,26 @@ fn nurbs_surface_second_derivatives_match_finite_differences() { .enumerate() .map(|(j, p)| { let w = 1.0 + 0.3 * ((i + 2 * j) % 3) as f64; - mt::Vector4::new(p.x * w, p.y * w, p.z * w, w) + [p[0] * w, p[1] * w, p[2] * w, w] }) .collect() }) .collect(); - let s = mt::NurbsSurface::new(mt::BSplineSurface::new((ku, kv), rows)); - for (u, v) in [(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2)] { - let uu = second(|t| from_p3(s.subs(t, v)), u); - let vv = second(|t| from_p3(s.subs(u, t)), v); - let scale = uu.len().max(vv.len()).max(1.0); - assert!(v3(s.uuder(u, v)).dist(uu) < 1e-4 * scale, "uuder at ({u}, {v}): {:?} vs {uu:?}", s.uuder(u, v)); - assert!(v3(s.vvder(u, v)).dist(vv) < 1e-4 * scale, "vvder at ({u}, {v}): {:?} vs {vv:?}", s.vvder(u, v)); + let s = SurfaceEval::new(&Surface::RationalSpline { u_knots, v_knots, homogeneous }).unwrap(); + check(&s, &[(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2)], "rational"); +} + +/// A boundary point a pcurve carries a rounding step past the knot range still has second +/// derivatives, those of the range's end, as it has a point and first derivatives; a parameter +/// well outside the range has none. +#[test] +fn second_derivatives_hold_at_a_boundary_carried_off_by_rounding() { + let (u_knots, v_knots, points) = net(3, 2); + let s = SurfaceEval::new(&Surface::Spline { u_knots, v_knots, points }).unwrap(); + for (u, v) in [(0.4f64, 1.0f64 + 1e-15), (0.4, -1e-16), (1.0 + 4e-16, 0.3), (-1e-15, 0.6)] { + let (cu, cv) = (u.clamp(0.0, 1.0), v.clamp(0.0, 1.0)); + assert_eq!(s.second(u, v), s.second(cu, cv), "({u}, {v})"); + assert!(s.second(u, v).is_some() && s.derivs(u, v).is_some(), "({u}, {v})"); } + assert!(s.second(0.4, 1.1).is_none()); } diff --git a/crates/kernel/src/surface_trim.rs b/crates/kernel/src/surface_trim.rs index 06b22abaa..a8eeec34d 100644 --- a/crates/kernel/src/surface_trim.rs +++ b/crates/kernel/src/surface_trim.rs @@ -3,15 +3,14 @@ //! Trim: two surfaces cut by each other, each keeping its picked side, extended to meet first //! when one stops short of the other. -use solidcraft_geom::Vec3; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::prelude::*; use crate::body::Body; -use crate::record::{Rebuild, rebuilt_body}; use crate::splitface::{SplitTool, ToolSide}; use crate::surface_extend::{ExtendLimit, ExtendMode, ExtendOptions}; -use crate::surfaces::surface_body; -use crate::{KernelError, Result, guard}; +use crate::{KernelError, Result}; /// Most points one trim picks with. const MAX_PICKS: usize = 10_000; @@ -58,58 +57,68 @@ pub fn trim(body: &Body, tool: &SplitTool, keep: Vec3) -> Result { /// A surface body trimmed by a tool, keeping what `keep` says. Each kept face is the face it is /// a piece of (its history is over `[body]`). +/// +/// The body is split where the tool meets it ([`crate::splitface::split_any`]), each piece's side +/// read at a point inside it ([`face_sides`]), and the pieces not kept are taken away ([`crate::remove_faces`]); both carry their history, so the kept +/// faces are the body's own, cut. pub fn trim_keep(body: &Body, tool: &SplitTool, keep: TrimKeep) -> Result { body.require_brep("trim")?; keep.check()?; - let total = body.solid.face_iter().count(); - let all: Vec = (0..total).collect(); + let all: Vec = (0..body.face_count()).collect(); let (split, _) = crate::splitface::split_any(body, &all, tool)?; - let one_side = match keep { - TrimKeep::Side(p) if crate::splitface::field_count(tool)? == 1 => Some(crate::splitface::side_of_point(tool, p)?), - _ => None, - }; - let picked = match one_side { - Some(_) => Vec::new(), - None => nearest_faces(&split, keep.points())?, - }; - guard("trim", || { - let mut kept = Vec::new(); - match one_side { - Some(side) => { - for f in split.solid.face_iter() { - let x = crate::splitface::face_side(f, tool, split.size())?; - if (x >= 0.0) == (side >= 0.0) { - kept.push(f.clone()); - } - } + let kept: Vec = match keep { + TrimKeep::Side(p) if crate::splitface::field_count(tool)? == 1 => { + let side = ToolSide::of(tool, body)?; + let want = side.at(p); + if !want.is_finite() { + return Err(KernelError::Invalid("the side of the tool the point is on can't be told".into())); } - None => { - let (region, count) = crate::splitface::regions(&split, tool)?; - let mut wanted = vec![false; count]; - for f in &picked { - if let Some(w) = region.get(*f).and_then(|r| wanted.get_mut(*r)) { - *w = true; - } - } - for (f, r) in split.solid.face_iter().zip(®ion) { - if wanted.get(*r).copied().unwrap_or(false) { - kept.push(f.clone()); - } + face_sides(&split, &side)?.into_iter().map(|x| (x >= 0.0) == (want >= 0.0)).collect() + } + _ => { + let picked = nearest_faces(&split, keep.points())?; + let (region, count) = crate::splitface::regions(&split, tool)?; + let mut wanted = vec![false; count]; + for f in &picked { + if let Some(w) = region.get(*f).and_then(|r| wanted.get_mut(*r)) { + *w = true; } } + region.iter().map(|r| wanted.get(*r).copied().unwrap_or(false)).collect() } - if kept.is_empty() { - return Err(KernelError::Invalid("nothing is left on that side of the tool".into())); - } - // The kept pieces are the split's own; its history carries them back to `body`. - let trimmed = rebuilt_body(surface_body(kept), &[&split.solid], &Rebuild::default()); - Ok(crate::record::after(trimmed, &split, &crate::record::counts(&[body]))) - }) + }; + if !kept.iter().any(|k| *k) { + return Err(KernelError::Invalid("nothing is left on that side of the tool".into())); + } + let dropped: Vec = kept.iter().enumerate().filter(|(_, k)| !**k).map(|(i, _)| i).collect(); + let trimmed = if dropped.is_empty() { split.clone() } else { crate::remove_faces(&split, &dropped)? }; + // The kept pieces are the split's own; its history carries them back to `body`. + Ok(crate::record::after(trimmed, &split, &crate::record::counts(&[body]))) +} + +/// The side of the tool each face of `body` (in its face order) lies on: the tool's field at a +/// point inside the face, on its surface and inside its trims (SMLib's +/// `CalculateAnInternalPoint`). Once the tool has cut the body each piece lies on one side, so +/// one such point says which. +fn face_sides(body: &Body, side: &ToolSide) -> Result> { + let (sm, order) = crate::native::smlib_body_ordered(body)?; + let order = order.ok_or_else(|| KernelError::Failed("trim: SMLib numbers the pieces' faces differently from their record".into()))?; + let points = sm.face_points().map_err(|e| KernelError::smlib("SMLib trim: a point inside each piece", e))?; + let mut sides = vec![f64::NAN; points.len()]; + for (i, p) in points.iter().enumerate() { + let face = if order.faces.is_empty() { i } else { order.faces.get(i).copied().unwrap_or(usize::MAX) }; + let slot = sides.get_mut(face).ok_or_else(|| KernelError::Failed("trim: a piece's face lies outside the body".into()))?; + *slot = side.at(Vec3::new(p[0], p[1], p[2])); + } + if sides.iter().any(|x| !x.is_finite()) { + return Err(KernelError::Failed("trim: the side of a piece can't be told".into())); + } + Ok(sides) } /// For each point, the face of `body` nearest it (over one tessellation). fn nearest_faces(body: &Body, at: &[Vec3]) -> Result> { - let m = body.tessellate(body.size() * 2e-3)?; + let m = body.mesh(&crate::MeshTolerance::chord(body.size() * 2e-3))?; at.iter() .map(|p| { let mut best: Option<(f64, u32)> = None; @@ -154,10 +163,10 @@ pub fn mutual_trim(a: &Body, b: &Body, keep_a: TrimKeep, keep_b: TrimKeep, exten /// `x` trimmed by `tool` where the tool crosses it; whole where it ends on the tool; extended to /// the tool first (when `extend`) where it stops short of it. fn cut_by(x: &Body, tool: &SplitTool, keep: TrimKeep, extend: bool, name: &str) -> Result { - let side = ToolSide::of(tool)?; + let side = ToolSide::of(tool, x)?; let size = x.size(); let touch = size * 1e-6 + 1e-9; - let m = x.tessellate(size * 2e-3)?; + let m = x.mesh(&crate::MeshTolerance::chord(size * 2e-3))?; let (mut lo, mut hi, mut near) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY); for p in &m.positions { let v = side.at(*p); @@ -182,31 +191,20 @@ fn cut_by(x: &Body, tool: &SplitTool, keep: TrimKeep, extend: bool, name: &str) crate::extend_surface(x, &[edge], &opts) } -/// A point in the middle of the boundary edge of `x` nearest the tool. +/// A point in the middle of the boundary edge of `x` nearest the tool: of the record's edges +/// that one face uses once, the one whose middle (half-way along its interval) is nearest. fn nearest_boundary_edge(x: &Body, side: &ToolSide) -> Result { - guard("trim", || { - let mut uses: std::collections::HashMap = std::collections::HashMap::new(); - for f in x.solid.face_iter() { - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - uses.entry(e.id()).or_insert((0, e.clone())).0 += 1; - } + let record = crate::native::brep_record(x)?; + let mut best: Option<(f64, Vec3)> = None; + for e in record.edges.iter().filter(|e| e.uses.len() == 1) { + let curve = CurveEval::new(e.parameters()).map_err(|err| KernelError::Failed(format!("trim: an edge's curve: {err}")))?; + let Some(mid) = curve.point(0.5 * (e.interval[0] + e.interval[1])) else { continue }; + let d = side.at(mid).abs(); + if d.is_finite() && best.is_none_or(|(b, _)| d < b) { + best = Some((d, mid)); } - let mut best: Option<(f64, Vec3)> = None; - for (count, e) in uses.values() { - if *count != 1 { - continue; - } - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let mid = crate::body::from_p3(c.subs(0.5 * (t0 + t1))); - let d = side.at(mid).abs(); - if d.is_finite() && best.is_none_or(|(b, _)| d < b) { - best = Some((d, mid)); - } - } - best.map(|(_, p)| p).ok_or_else(|| KernelError::Invalid("the surface has no boundary edge to extend".into())) - }) + } + best.map(|(_, p)| p).ok_or_else(|| KernelError::Invalid("the surface has no boundary edge to extend".into())) } #[cfg(test)] @@ -214,7 +212,7 @@ mod tests { use super::*; use crate::history::{Change, FaceOrigin}; use crate::{extrude_sheet, measure, patch_region, stitch}; - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; use std::f64::consts::PI; fn rel(a: f64, b: f64) -> f64 { diff --git a/crates/kernel/src/surface_untrim.rs b/crates/kernel/src/surface_untrim.rs index acc435bd8..717db115d 100644 --- a/crates/kernel/src/surface_untrim.rs +++ b/crates/kernel/src/surface_untrim.rs @@ -3,20 +3,24 @@ //! the surface's natural parameter bounds: a free-form surface's own parameter box, and for an //! analytic surface (a plane, cylinder, cone, sphere or torus, which has no natural bounds of //! its own, or bounds that go all the way round) the box of the face's own span. The restored -//! boundary runs along the surface's parameter lines, each edge exact: a line, an arc about a -//! revolved surface's axis, a rotated profile, or a B-spline iso-curve. +//! boundary runs along the surface's parameter lines. //! -//! Which loop is the outer one is worked out from the face's parameters ([`FaceLoops`]). +//! SMLib does it (`smlib_untrim_face`): holes are deleted from the face, the outer boundary is +//! the face SMLib makes from the surface over that box, the holes kept rebuilt in it from their +//! own edges. The body goes to SMLib tagged as operand 0, so the result's history comes from +//! SMLib's tags: the untrimmed face is the face it was, trimmed differently. -use mt::{BoundedCurve, MetricSpace, ParametricCurve, ParametricSurface}; -use solidcraft_geom::Vec3; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use solidcraft_smlib::trim::Holes; use crate::body::Body; -use crate::face_params::{FaceLoops, iso_curve, natural_span, passes}; -use crate::record::{Rebuild, rebuilt_body}; -use crate::surfaces::surface_body; -use crate::{KernelError, Result, guard}; +use crate::history::{Change, FaceOrigin}; +use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; +use crate::{KernelError, Result}; + +/// Most hole picks. +const MAX_PICKS: usize = 10_000; /// The inner loops Untrim takes away. #[derive(Clone, Copy, Debug, PartialEq)] @@ -36,135 +40,92 @@ pub enum UntrimHoles<'a> { pub fn untrim(body: &Body, face: usize, holes: UntrimHoles, outer: bool, in_place: bool) -> Result { body.require_brep("untrim")?; if let UntrimHoles::At(points) = holes { - if points.len() > 10_000 { + if points.len() > MAX_PICKS { return Err(KernelError::Invalid("too many holes picked".into())); } - if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) { + if points.iter().any(|p| !p.is_finite()) { return Err(KernelError::Invalid("a hole point is not finite".into())); } } - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); - let original = *faces.get(face).ok_or_else(|| KernelError::Invalid(format!("the body has no face {face}")))?; - let size = body.size().max(1e-6); - let untrimmed = guard("untrim", || untrimmed_face(original, holes, outer, size))?; - let mut rec = Rebuild::default(); - rec.face(&untrimmed, original); - let result = if in_place && body.is_surface() { - surface_body(faces.iter().map(|f| if f.id() == original.id() { untrimmed.clone() } else { (*f).clone() }).collect()) - } else { - surface_body(vec![untrimmed]) + let record = crate::native::brep_record(body)?; + let f = record.faces.get(face).ok_or_else(|| KernelError::Invalid(format!("the body has no face {face}")))?; + let inner = f.loops.len().saturating_sub(1); + let removes = match holes { + UntrimHoles::All => inner > 0, + UntrimHoles::At(points) => !points.is_empty(), }; - Ok(rebuilt_body(result, &[&body.solid], &rec)) -} - -/// The face untrimmed (see [`untrim`]). -fn untrimmed_face(face: &mt::Face, holes: UntrimHoles, outer: bool, size: f64) -> Result { - let surface = face.surface(); - let accept = (size * 1e-5).max(1e-6); - let FaceLoops { eval, dom, wires, loops, outer: outer_index } = FaceLoops::of(face, accept, "untrimming")?; - let inner: Vec = (0..wires.len()).filter(|i| *i != outer_index).collect(); - let removed: Vec = match holes { - UntrimHoles::All => inner.clone(), - UntrimHoles::At(points) => { - let mut picked = Vec::new(); - for p in points { - let (i, d) = inner - .iter() - .filter_map(|i| loops.get(*i).map(|l| (*i, l.dist(*p)))) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .ok_or_else(|| KernelError::Invalid("the face has no holes".into()))?; - if d > size * 0.05 + 1e-6 { - return Err(KernelError::Invalid(format!("no hole of the face at {p:?}"))); - } - if !picked.contains(&i) { - picked.push(i); - } - } - picked - } - }; - if !outer && removed.is_empty() { - return Err(KernelError::Invalid(if inner.is_empty() { + if !outer && !removes { + return Err(KernelError::Invalid(if inner == 0 { "the face has no holes to remove (restore its outer boundary instead)".into() } else { "nothing to untrim: pick holes to remove or restore the outer boundary".into() })); } - let (Some(outer_wire), Some(outer_loop)) = (wires.get(outer_index), loops.get(outer_index)) else { - return Err(KernelError::Invalid("the face has no boundary".into())); - }; - let first = if outer { - let analytic = crate::offset::surf_of(face, (size * 1e-7).max(1e-9) * 100.0).is_some(); - let span = natural_span(&eval, &dom, outer_loop, analytic, accept)?; - bounds_wire(&surface, span, outer_loop.area() > 0.0, size)? - } else { - outer_wire.clone() - }; - let kept = inner.iter().filter(|i| !removed.contains(i)).filter_map(|i| wires.get(*i).cloned()); - let boundaries: Vec = std::iter::once(first).chain(kept).collect(); - let mut f = mt::Face::try_new(boundaries, surface).map_err(|e| KernelError::Failed(format!("untrimmed face: {e}")))?; - if !face.orientation() { - f.invert(); + if matches!(holes, UntrimHoles::At(p) if !p.is_empty()) && inner == 0 { + return Err(KernelError::Invalid("the face has no holes".into())); } - Ok(f) + let size = body.size().max(1e-6); + let at = face_point(body, face)?; + let picks: Vec<[f64; 3]> = match holes { + UntrimHoles::All => Vec::new(), + UntrimHoles::At(points) => points.iter().map(|p| [p.x, p.y, p.z]).collect(), + }; + let which = match holes { + UntrimHoles::All => Holes::All, + UntrimHoles::At(_) => Holes::At(&picks), + }; + let in_place = in_place && body.is_surface(); + let (sb, ob) = smlib_body_ordered(body)?; + let tagged = sb.tagged(0).map_err(|e| failed("tag", e))?; + // A hole is picked within a twentieth of the body's size of its edges, the face by a point + // inside it. + let reach = size * 0.05 + 1e-6; + let r = tagged.untrim_face([at.x, at.y, at.z], reach, which, outer, in_place).map_err(|e| match e { + solidcraft_smlib::Error::NoMatch { .. } => KernelError::Invalid("no hole of the face at a picked point".into()), + solidcraft_smlib::Error::Unsupported => { + KernelError::Failed("not supported yet: untrimming this face in place (another face uses its hole's edges)".into()) + } + e => failed("untrim", e), + })?; + let (out, order) = body_from_smlib_ordered(&r)?; + let history = match (ob, order) { + (Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[ob], &or).ok().map(|mut h| { + // The untrimmed face is the face it was, bounded differently. + for p in &mut h.faces { + if p.origins.contains(&FaceOrigin::Face { operand: 0, face }) { + p.change = Change::Modified; + } + } + h + }), + _ => None, + }; + Ok(out.with_checked_history(history, &crate::record::counts(&[body]))) } -/// The closed boundary of the parameter box `span` on `surface`, counter-clockwise in its -/// parameters when `ccw`: four parameter-line edges, fewer where a side shrinks to a point (a -/// pole: the corners at its ends are one vertex). -fn bounds_wire(surface: &mt::Surface, span: [(f64, f64); 2], ccw: bool, size: f64) -> Result { - let [(u0, u1), (v0, v1)] = span; - let tol = size * 1e-6 + 1e-9; - // The corners counter-clockwise from (u0, v0); each side runs between two of them. - let mut corners = [(u0, v0), (u1, v0), (u1, v1), (u0, v1)]; - if !ccw { - corners.reverse(); - } - let points: Vec = corners.iter().map(|(u, v)| surface.subs(*u, *v)).collect(); - if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) { - return Err(KernelError::Failed("the surface cannot be evaluated at its bounds".into())); - } - // Corners at one point (a pole) are one vertex. - let mut vertices: Vec = Vec::with_capacity(4); - for (i, p) in points.iter().enumerate() { - let same = points.iter().take(i).position(|q| q.distance(*p) <= tol).and_then(|j| vertices.get(j).cloned()); - vertices.push(same.unwrap_or_else(|| mt::Vertex::new(*p))); - } - let mut edges = Vec::with_capacity(4); - for i in 0..4 { - let j = (i + 1) % 4; - let (Some(&(ua, va)), Some(&(ub, vb)), Some(a), Some(b)) = (corners.get(i), corners.get(j), vertices.get(i), vertices.get(j)) else { - continue; - }; - let along_u = va == vb; - let (w, from, to) = if along_u { (va, ua, ub) } else { (ua, va, vb) }; - let mid = if along_u { surface.subs(0.5 * (from + to), w) } else { surface.subs(w, 0.5 * (from + to)) }; - if a.id() == b.id() { - // A side shrunk to a pole is no edge; one that closes on itself can't be bounded. - if mid.distance(a.point()) > tol { - return Err(KernelError::TooLarge("a surface that closes on itself within the face's bounds".into())); - } - continue; - } - let curve = iso_curve(surface, along_u, w, from, to)?; - let close = |p: mt::Point3, q: mt::Point3| p.distance(q) <= tol * 10.0; - let (t0, t1) = curve.range_tuple(); - if !close(curve.subs(t0), a.point()) || !close(curve.subs(t1), b.point()) || !passes(&curve, mid, tol * 10.0) { - return Err(KernelError::Failed("a restored boundary edge does not follow its surface".into())); - } - edges.push(mt::Edge::try_new(a, b, curve).map_err(|e| KernelError::Failed(format!("restored boundary edge: {e}")))?); - } - if edges.len() < 2 { - return Err(KernelError::Invalid("the face's bounds shrink to a point".into())); - } - Ok(edges.into()) +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib untrim: {what}"), e) +} + +/// A point inside face `face` of `body`: the centre of its largest mesh triangle. +pub(crate) fn face_point(body: &Body, face: usize) -> Result { + let m = body.mesh(&crate::MeshTolerance::chord((body.size() * 1e-3).max(1e-3)))?; + let area = |[a, b, c]: &[Vec3; 3]| (*b - *a).cross(*c - *a).len(); + m.triangles + .iter() + .zip(&m.tri_face) + .filter(|(_, f)| **f as usize == face) + .filter_map(|(t, _)| m.tri(t)) + .max_by(|x, y| area(x).total_cmp(&area(y))) + .map(|[a, b, c]| (a + b + c) / 3.0) + .ok_or_else(|| KernelError::Failed(format!("untrim: face {face} has no triangles"))) } #[cfg(test)] mod tests { use super::*; use crate::{extrude, measure}; - use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; use std::f64::consts::PI; fn rel(a: f64, b: f64) -> f64 { @@ -172,7 +133,7 @@ mod tests { } fn inner_loops(b: &Body) -> usize { - b.solid.face_iter().map(|f| f.boundaries().len().saturating_sub(1)).sum() + crate::native::brep_record(b).unwrap().faces.iter().map(|f| f.loops.len().saturating_sub(1)).sum() } /// A 40 × 20 × 2 plate with three holes of radius 2 at x = 10, 20, 30 on y = 10. @@ -206,34 +167,13 @@ mod tests { let h = all.history().unwrap(); assert_eq!(h.faces.first().map(|f| f.change), Some(crate::history::Change::Modified)); // Nothing to do: a face without holes, a point on no hole, an empty pick. - let side = b.solid.face_iter().position(|f| f.boundaries().len() == 1).unwrap(); + let side = crate::native::brep_record(&b).unwrap().faces.iter().position(|f| f.loops.len() == 1).unwrap(); assert!(untrim(&b, side, UntrimHoles::All, false, false).is_err()); assert!(untrim(&b, top, UntrimHoles::At(&[Vec3::new(5.0, 5.0, 2.0)]), false, false).is_err()); assert!(untrim(&b, top, UntrimHoles::At(&[]), false, false).is_err()); assert!(untrim(&b, 99, UntrimHoles::All, false, false).is_err()); } - /// A face whose hole is stored before its outer loop (as an imported face may list them): - /// the outer loop is the one enclosing the most, so the 10 × 10 square comes back whole. - #[test] - fn the_outer_loop_is_found_whatever_order_the_loops_are_in() { - let r = Region2 { - outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)]), - holes: vec![Loop2::polygon(&[Vec2::new(4.0, 4.0), Vec2::new(4.0, 6.0), Vec2::new(6.0, 6.0), Vec2::new(6.0, 4.0)])], - }; - let sheet = crate::patch_region(&Plane::XY, &r).unwrap(); - let f = sheet.solid.face_iter().next().unwrap().clone(); - let mut loops = f.absolute_boundaries().clone(); - loops.reverse(); - let swapped = mt::Face::new_unchecked(loops, f.surface()); - let swapped = if f.orientation() { swapped } else { swapped.inverse() }; - let b = surface_body(vec![swapped]); - assert!(rel(measure(&b).unwrap().area, 96.0) < 1e-9); - let back = untrim(&b, 0, UntrimHoles::All, false, true).unwrap(); - assert!(back.face_count() == 1 && inner_loops(&back) == 0); - assert!(rel(measure(&back).unwrap().area, 100.0) < 1e-9, "{}", measure(&back).unwrap().area); - } - /// A half cylinder sheet (radius 10, angles 0…π, height 20) trimmed by the slanted plane /// z = 15 − y/2: its top edge runs from 15 down to 10 and back, its area ∫ (15 − 5 sin θ) r dθ /// = 150π − 100. Restored, it fills its own span again, angles 0…π and heights 0…15: 150π, @@ -262,10 +202,10 @@ mod tests { } /// A revolved face: the cone frustum swept by the line from radius 5 at z = 0 to radius 10 - /// at z = −10 (slant √125), its first face (angles 0…½), trimmed by the plane z = −8 + y/2. + /// at z = −10 (slant √125), one face over angles 0…1, trimmed by the plane z = −8 + y/2. /// The cut reaches lowest (profile parameter 0.8) at angle 0, so the face's own span is - /// angles 0…½ by parameters 0…0.8, restored with arcs about the axis and straight sides: - /// ½ · √125 · ∫₀^0.8 (5 + 5t) dt = ½ · √125 · 5.6. + /// angles 0…1 by parameters 0…0.8, restored with arcs about the axis and straight sides: + /// 1 · √125 · ∫₀^0.8 (5 + 5t) dt = √125 · 5.6. #[test] fn a_trimmed_cone_face_is_restored_to_its_span() { let line = vec![Seg2::Line { a: Vec2::new(5.0, 0.0), b: Vec2::new(10.0, 10.0) }]; @@ -275,7 +215,7 @@ mod tests { let cut = crate::trim(&sheet, &tool, Vec3::new(5.0 * c, 5.0 * s, 0.0)).unwrap(); let face = face_at(&cut, Vec3::new(5.5 * c, 5.5 * s, -1.0)); let restored = untrim(&cut, face, UntrimHoles::All, true, false).unwrap(); - let want = 0.5 * 125f64.sqrt() * 5.6; + let want = 125f64.sqrt() * 5.6; let a = measure(&restored).unwrap().area; assert!(rel(a, want) < 1e-3, "{a} vs {want}"); // (measured on meshes) let bb = measure(&restored).unwrap().bbox; @@ -283,14 +223,13 @@ mod tests { assert!(matches!(crate::face_surface(&restored, 0), Some(crate::FaceSurface::Cone { .. }))); } - /// A torus face (a revolved arc) with a piece of its outer equator cut off by the plane - /// x = 12: the cut touches one side of the face only, so its span is the face's whole span - /// and the restored face is the face as it was before the cut. + /// A torus face with a piece of its outer equator cut off by the plane x = 12: the cut + /// touches one side of the face only, so its span is the face's whole span and the restored + /// face is the face as it was before the cut. #[test] fn a_torus_face_cut_at_one_side_is_restored_whole() { let torus = crate::torus(Vec3::ZERO, 10.0, 3.0).unwrap(); - let f = torus.solid.face_iter().next().unwrap().clone(); - let face = surface_body(vec![f]); + let face = crate::copy_faces(&torus, &[Vec3::new(13.0, 0.0, 0.0)]).unwrap(); let before = measure(&face).unwrap().area; let tool = crate::SplitTool::Plane(Plane::from_normal(Vec3::new(12.0, 0.0, 0.0), Vec3::X).unwrap()); let cut = crate::trim(&face, &tool, Vec3::new(0.0, 13.0, 0.0)).unwrap(); @@ -305,26 +244,27 @@ mod tests { )); } - /// A free-form face goes back to its surface's own parameter box: half of the saddle - /// z = x y / 10 over 0…10 × 0…10 (a bilinear patch, its iso-lines straight), x from 0 to 5, + /// A free-form face goes back to its surface's own parameter box: the saddle z = x y / 10 + /// over 0…10 × 0…10 (ruled between two straight lines, sketched on planes y = 0 and 10 whose sketch y is −z: a + /// bilinear patch), cut at x = 5 and /// restored to the whole patch: x and y 0…10, z 0…10. #[test] fn a_free_form_face_is_restored_to_its_surfaces_bounds() { - let pt = |x: f64, y: f64| mt::Point3::new(x, y, x * y / 10.0); - let knots = mt::KnotVec::bezier_knot(1); - let saddle = mt::BSplineSurface::new((knots.clone(), knots), vec![vec![pt(0.0, 0.0), pt(0.0, 10.0)], vec![pt(10.0, 0.0), pt(10.0, 10.0)]]); - let corners = [pt(0.0, 0.0), pt(5.0, 0.0), pt(5.0, 10.0), pt(0.0, 10.0)]; - let v: Vec = corners.iter().map(|p| mt::Vertex::new(*p)).collect(); - let edges: Vec = - (0..4).map(|i| mt::Edge::new_unchecked(&v[i], &v[(i + 1) % 4], mt::Curve::Line(mt::Line(corners[i], corners[(i + 1) % 4])))).collect(); - let half = surface_body(vec![mt::Face::new_unchecked(vec![edges.into()], mt::Surface::BSplineSurface(saddle))]); + let front = (Plane::XZ, vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) }]); + let back = (Plane { origin: Vec3::new(0.0, 10.0, 0.0), ..Plane::XZ }, vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, -10.0) }]); + let saddle = crate::loft_sheet(&[front, back]).unwrap(); + let tool = crate::SplitTool::Plane(Plane::from_normal(Vec3::new(5.0, 0.0, 0.0), Vec3::X).unwrap()); + let half = crate::trim(&saddle, &tool, Vec3::new(1.0, 5.0, 0.5)).unwrap(); assert!(crate::face_surface(&half, 0).is_none(), "not analytic"); assert!((measure(&half).unwrap().bbox.max.x - 5.0).abs() < 1e-9); let whole = untrim(&half, 0, UntrimHoles::All, true, false).unwrap(); let bb = measure(&whole).unwrap().bbox; assert!(bb.min.x.abs() < 1e-9 && bb.min.y.abs() < 1e-9 && bb.min.z.abs() < 1e-9, "{bb:?}"); assert!((bb.max.x - 10.0).abs() < 1e-9 && (bb.max.y - 10.0).abs() < 1e-9 && (bb.max.z - 10.0).abs() < 1e-9, "{bb:?}"); - assert_eq!(whole.solid.face_iter().next().unwrap().boundaries().first().map(|w| w.len()), Some(4)); + let record = crate::native::brep_record(&whole).unwrap(); + assert!( + matches!(record.faces.first().and_then(|f| f.loops.first()), Some(solidcore_record::brep::Loop::Edges { edges }) if edges.len() == 4) + ); } /// The plate exported to STEP and read back: its imported top face untrims to the whole @@ -335,7 +275,7 @@ mod tests { let imported = crate::step_import(&text).unwrap(); let b = &imported.bodies.first().unwrap().body; let top = face_at(b, Vec3::new(5.0, 5.0, 2.0)); - assert_eq!(b.solid.face_iter().nth(top).unwrap().boundaries().len(), 4); + assert_eq!(crate::native::brep_record(b).unwrap().faces.get(top).unwrap().loops.len(), 4); let all = untrim(b, top, UntrimHoles::All, false, false).unwrap(); assert!(all.face_count() == 1 && inner_loops(&all) == 0); assert!(rel(measure(&all).unwrap().area, 800.0) < 1e-9); @@ -368,7 +308,7 @@ mod tests { let b = plate(); let top = face_at(&b, Vec3::new(5.0, 5.0, 2.0)); assert!(untrim(&b, top, UntrimHoles::At(&[Vec3::new(f64::NAN, 0.0, 0.0)]), false, false).is_err()); - let many = vec![Vec3::ZERO; 10_001]; + let many = vec![Vec3::ZERO; MAX_PICKS + 1]; assert!(untrim(&b, top, UntrimHoles::At(&many), false, false).is_err()); } } diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index e691332ee..53a65fa06 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -1,528 +1,548 @@ //! Surface bodies (open shells) and the operations that turn them into solids: Patch (a face //! filling a closed loop of edges — planar, or B-spline patches for a loop that is not — or a -//! planar sketch region), Stitch (surfaces sharing edges sewn -//! into one body, a solid when they close), Trim (a surface cut by a tool, one side kept), -//! Thicken (a surface offset along its normals into a solid), copying faces out of a body, and -//! sheets swept from sketch curves (surface extrude, revolve, sweep and loft). +//! planar sketch region), Stitch (surfaces sharing edges sewn into one body, a solid when they +//! close), Thicken (a surface offset along its normals into a solid), copying, removing, turning +//! over and taking apart faces of a body, extending a planar surface, and sheets swept from sketch +//! curves (surface extrude, revolve, sweep and loft). +//! +//! Everything works on the body's schema 4 record. Taking faces out of a body, turning them over +//! and making a flat face are exact on the record ([`Parts`] puts any set of faces, edges and +//! vertices into a record's canonical order). Sweeps, stitching and offsets are SMLib's: each piece +//! of a sheet goes to SMLib on its own (a chain of a sweep, a column of a loft, a face of an +//! offset), the pieces' records are joined, and where pieces share edges SMLib stitches them. +//! +//! History is exact. A face taken from a body is that face (Kept), its edges the body's; a sheet's +//! wall comes from the profile segments its edges in the start plane lie along; a stitched or +//! offset face carries the tag of the face it was made from through SMLib. -use std::collections::HashMap; +use solidcraft_geom::prelude::*; +use std::collections::BTreeSet; -use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::{Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; -use truck_modeling as mt; +use solidcore_record::brep::{self as b, Brep, Curve2}; +use solidcore_record::{Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::bspline::{HPoint, NurbsSurface}; -use crate::body::{Body, from_p3, p3}; -use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv}; -use crate::record::{self, Rebuild, Side, rebuilt_body}; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History}; +use crate::{KernelError, Result, record}; impl Body { - /// A surface body: some shell does not close. + /// A surface body: some shell does not close (an edge bounds a face on one side only). pub fn is_surface(&self) -> bool { - !self.is_mesh() && self.solid.boundaries().iter().any(|s| s.shell_condition() != mt::ShellCondition::Closed) + !self.is_mesh() && self.record().edges.iter().any(|e| e.uses.len() == 1) } } -/// A body of faces as they are (no orientation fix: a surface has no inside). -pub(crate) fn surface_body(faces: Vec) -> Body { - surface_of(mt::Shell::from(faces)) +fn invalid(what: impl Into) -> KernelError { + KernelError::Invalid(what.into()) } -/// A body of a shell as it is. -fn surface_of(shell: mt::Shell) -> Body { - Body { - solid: std::sync::Arc::new(mt::Solid::new_unchecked(vec![shell])), - size: 0.0, - boundary_tol: None, - volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: None, - mesh: None, - color: None, - paint: None, - splits: None, - face_sources: None, - history: None, - display_of: None, - meshes: None, - phased: false, - regularization_protected: false, +fn failed(what: impl Into) -> KernelError { + KernelError::Failed(what.into()) +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +fn a3(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +fn index(i: usize) -> Result { + u32::try_from(i).map_err(|_| KernelError::TooLarge("a record index".into())) +} + +// ---- Records of faces ------------------------------------------------------------------- + +/// Faces, edges and vertices to be put into one record: each face with whether its shell uses it +/// along its surface's natural normal, its loops naming `edges` and `vertices` by position here. +/// Edges' `uses` are ignored ([`Parts::canonical`] works them out). +#[derive(Clone, Debug, Default)] +pub(crate) struct Parts { + pub tolerance: f64, + pub vertices: Vec, + pub edges: Vec, + pub faces: Vec<(b::Face, bool)>, +} + +/// A record made by [`Parts::canonical`], with where each of its faces and edges came from +/// (`faces[i]`: the part face of record face i; `edges` likewise). Parts no face uses are left out. +pub(crate) struct Canonical { + pub brep: Brep, + pub faces: Vec, + pub edges: Vec, +} + +/// Where the parts of each record [`Parts::joined`] took begin: faces, edges, vertices. +type Offsets = Vec<[usize; 3]>; + +/// The record (by index) and its own index of a part numbered by `offsets` (`kind` 0 for faces, 1 +/// for edges). +fn owner(offsets: &Offsets, part: usize, kind: usize) -> Option<(usize, usize)> { + let k = offsets.iter().rposition(|o| o[kind] <= part)?; + Some((k, part - offsets.get(k)?[kind])) +} + +impl Parts { + /// Every face of `records` in one set of parts, each record's faces, edges and vertices after + /// the ones before it. + pub(crate) fn joined(records: &[&Brep]) -> Result<(Parts, Offsets)> { + let mut parts = Parts { tolerance: records.iter().map(|r| r.tolerance).fold(0.0, f64::max), ..Parts::default() }; + let mut offsets = Vec::with_capacity(records.len()); + for r in records { + offsets.push([parts.faces.len(), parts.edges.len(), parts.vertices.len()]); + let faces: Vec<(usize, bool)> = (0..r.faces.len()).map(|f| (f, false)).collect(); + parts.add(r, &faces)?; + } + Ok((parts, offsets)) + } + + /// The faces `picked` of `r` (each with whether to turn it over), on `r`'s own edges and + /// vertices. + pub(crate) fn of(r: &Brep, picked: &[(usize, bool)]) -> Result { + let mut parts = Parts { tolerance: r.tolerance, ..Parts::default() }; + parts.add(r, picked)?; + Ok(parts) + } + + /// Adds the faces `picked` of `r` with all of `r`'s edges and vertices, after the ones here. + fn add(&mut self, r: &Brep, picked: &[(usize, bool)]) -> Result<()> { + let (e0, v0) = (self.edges.len(), self.vertices.len()); + let sides = face_sides(r); + let shift = |i: u32, by: usize| index(i as usize + by); + self.vertices.extend(r.vertices.iter().cloned()); + for e in &r.edges { + let vertices = [shift(e.vertices[0], v0)?, shift(e.vertices[1], v0)?]; + self.edges.push(b::Edge { vertices, uses: Vec::new(), ..e.clone() }); + } + for &(f, turn) in picked { + let face = r.faces.get(f).ok_or_else(|| invalid(format!("no face {f}")))?; + let forward = sides.get(f).copied().unwrap_or(true) != turn; + let loops = face + .loops + .iter() + .map(|l| { + Ok(match l { + b::Loop::Edges { edges } => b::Loop::Edges { + edges: edges.iter().map(|u| Ok(b::OrientedEdge { edge: shift(u.edge, e0)?, ..u.clone() })).collect::>()?, + }, + b::Loop::Vertex { vertex } => b::Loop::Vertex { vertex: shift(*vertex, v0)? }, + }) + }) + .collect::>()?; + self.faces.push((b::Face { loops, ..face.clone() }, forward)); + } + Ok(()) + } + + /// The edges a face's loops use, in order. + fn uses_of(f: &b::Face) -> impl Iterator + '_ { + f.loops.iter().flat_map(|l| match l { + b::Loop::Edges { edges } => edges.iter().map(|u| u.edge).collect::>(), + b::Loop::Vertex { .. } => Vec::new(), + }) + } + + /// The faces in shells: faces joined by an edge are in one shell, shells in the order of their + /// first face, each shell's faces in part order. + fn shells(&self) -> Result>> { + let n = self.faces.len(); + let mut root: Vec = (0..n).collect(); + let find = |root: &[usize], mut i: usize| { + while let Some(&g) = root.get(i).filter(|g| **g != i) { + i = g; + } + i + }; + let mut first: Vec> = vec![None; self.edges.len()]; + for (fi, (f, _)) in self.faces.iter().enumerate() { + for e in Parts::uses_of(f) { + let slot = first.get_mut(e as usize).ok_or_else(|| invalid("an edge reference"))?; + match *slot { + None => *slot = Some(fi), + Some(other) => { + let (a, c) = (find(&root, other), find(&root, fi)); + if let Some(g) = root.get_mut(a.max(c)) { + *g = a.min(c); + } + } + } + } + } + let mut shells: Vec> = Vec::new(); + let mut shell_of: std::collections::HashMap = std::collections::HashMap::new(); + for fi in 0..n { + let s = *shell_of.entry(find(&root, fi)).or_insert_with(|| { + shells.push(Vec::new()); + shells.len() - 1 + }); + if let Some(list) = shells.get_mut(s) { + list.push(fi); + } + } + Ok(shells) + } + + /// The parts as one record in canonical order (docs/native-brep.md, "Canonical order"): shells + /// as [`Parts::shells`] groups them, a closed shell enclosing a region of its own; edges in + /// first appearance walking faces, loops and uses (backwards on a face used against its + /// natural normal), each edge's uses in that order; vertices in first appearance walking + /// edges, then vertex loops. + pub(crate) fn canonical(&self) -> Result { + if self.faces.is_empty() { + return Err(invalid("no faces")); + } + let shells = self.shells()?; + // The record as the parts stand (shell k as `shells` groups it), then in canonical order. + let mut regions = vec![b::Region { shells: Vec::new(), void: false }]; + let mut shell_records = Vec::with_capacity(shells.len()); + for (s, members) in shells.iter().enumerate() { + let mut count: std::collections::HashMap = std::collections::HashMap::new(); + let mut list = Vec::with_capacity(members.len()); + for &fi in members { + let (f, forward) = self.faces.get(fi).ok_or_else(|| invalid("a face reference"))?; + for e in Parts::uses_of(f) { + *count.entry(e).or_default() += 1; + } + list.push(b::OrientedFace { face: index(fi)?, forward: *forward }); + } + shell_records.push(b::Shell::Faces { faces: list, wires: Vec::new() }); + let s = index(s)?; + if let Some(infinite) = regions.first_mut() { + infinite.shells.push(s); + } + if count.values().all(|c| *c >= 2) { + regions.push(b::Region { shells: vec![s], void: false }); + } + } + let loose = Brep { + version: b::VERSION, + tolerance: self.tolerance, + regions, + shells: shell_records, + faces: self.faces.iter().map(|(f, _)| f.clone()).collect(), + edges: self.edges.iter().map(|e| b::Edge { uses: Vec::new(), ..e.clone() }).collect(), + vertices: self.vertices.clone(), + }; + let part = loose.canonical().map_err(|e| failed(format!("faces into a record: {e}")))?; + Ok(Canonical { + brep: part.brep, + faces: part.faces.iter().map(|f| *f as usize).collect(), + edges: part.edges.iter().map(|e| *e as usize).collect(), + }) } } -/// A body from faces: a solid when they close, else a surface; with the history of the -/// operation that made the faces from `operands` as `rec` records. -pub(crate) fn body_of(faces: Vec, operands: &[&mt::Solid], rec: &Rebuild) -> Result { - let shell = mt::Shell::from(faces); - if shell.shell_condition() == mt::ShellCondition::Closed { - crate::record::rebuilt(mt::Solid::new_unchecked(vec![shell]), operands, rec) +/// Whether each face of `r` is used along its surface's natural normal (by its first oriented +/// face). +pub(crate) fn face_sides(r: &Brep) -> Vec { + let mut side = vec![None; r.faces.len()]; + for s in &r.shells { + if let b::Shell::Faces { faces, .. } = s { + for f in faces { + if let Some(slot) = side.get_mut(f.face as usize) { + slot.get_or_insert(f.forward); + } + } + } + } + side.into_iter().map(|s| s.unwrap_or(true)).collect() +} + +/// The history of a record over `operands` operands: its faces' `faces`, each edge's origins as +/// `edge` gives them (from the edge's index, the faces it bounds, ascending, and `faces`). +fn record_history(r: &Brep, operands: usize, faces: Vec, edge: impl Fn(usize, &[usize], &[FaceProv]) -> Vec) -> History { + let between = r.edges.iter().map(|e| e.uses.iter().map(|u| u.face as usize).collect::>().into_iter().collect::>()); + let edges = between.enumerate().map(|(i, between)| EdgeProv { origins: edge(i, &between, &faces), faces: between }).collect(); + History { operands, faces, edges } +} + +/// The parameter box of a face's loops: the box of its pcurves' control points (each pcurve lies +/// within its control polygon). +fn uv_box(loops: &[b::Loop]) -> Option<[[f64; 2]; 2]> { + let mut bx = [[f64::INFINITY, f64::NEG_INFINITY]; 2]; + for l in loops { + let b::Loop::Edges { edges } = l else { continue }; + for u in edges { + let pts: Vec<[f64; 2]> = match &u.pcurve { + Curve2::Spline { points, .. } => points.clone(), + Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().map(|h| [h[0] / h[2], h[1] / h[2]]).collect(), + }; + for p in pts { + for (d, x) in bx.iter_mut().zip(p) { + d[0] = d[0].min(x); + d[1] = d[1].max(x); + } + } + } + } + bx.iter().all(|d| d[0].is_finite() && d[1] > d[0]).then_some(bx) +} + +/// A body of a record this module built, and whether it numbers its faces and edges as the +/// record does (so a history in the record's order is the body's): the record is the body's own. +fn record_body(r: &Brep) -> Result<(Body, bool)> { + Ok((Body::from_record(r.clone())?, true)) +} + +/// `body` with the history `h` over operands of `counts` faces and edges when its order is the +/// record's, else with none. +fn with_history(body: Body, same_order: bool, h: History, counts: &[(usize, usize)]) -> Result { + if same_order { body.with_history_counts(h, counts) } else { Ok(body.without_history()) } +} + +/// A surface body of the record `r` (faces another builder made) with no history. +pub(crate) fn surface_body(r: &Brep) -> Result { + record_body(r).map(|(body, _)| body.without_history()) +} + +/// `body` (made by an operation on `operands`) with the history that every face and edge is new to +/// it. +pub(crate) fn all_new(body: Body, operands: &[&Body]) -> Result { + let r = body.record(); + let faces = vec![record::generated(Vec::new()); r.faces.len()]; + let h = record_history(r, operands.len(), faces, |_, _, _| Vec::new()); + body.with_history_counts(h, &record::counts(operands)) +} + +/// The faces `picked` of `body` (its record `r`; each with whether to turn it over) as their own +/// body, each the body's face (Kept), every edge the body's. +pub(crate) fn taken(body: &Body, r: &Brep, picked: &[(usize, bool)]) -> Result { + let c = Parts::of(r, picked)?.canonical()?; + let faces = c.faces.iter().map(|p| picked.get(*p).map_or(0, |(f, _)| *f)).map(|f| record::from_face(0, f, Change::Kept)).collect(); + let h = record_history(&c.brep, 1, faces, |e, _, _| c.edges.get(e).map(|&edge| EdgeOrigin::Edge { operand: 0, edge }).into_iter().collect()); + let (result, same) = record_body(&c.brep)?; + with_history(result, same, h, &record::counts(&[body])) +} + +// ---- NURBS faces -------------------------------------------------------------------------- + +/// A NURBS surface as a record surface (a plain B-spline where every weight is 1). +pub(crate) fn spline_surface(n: &NurbsSurface) -> b::Surface { + let [nu, nv] = n.count(); + let [ku, kv] = n.knots().clone(); + if n.homogeneous().iter().all(|h| h.w == 1.0) { + let points = (0..nu).map(|i| (0..nv).map(|j| a3(n.point(i, j).xyz())).collect()).collect(); + return b::Surface::Spline { u_knots: ku, v_knots: kv, points }; + } + let homogeneous = (0..nu).map(|i| (0..nv).map(|j| n.point(i, j)).map(|h| [h.x, h.y, h.z, h.w]).collect()).collect(); + b::Surface::RationalSpline { u_knots: ku, v_knots: kv, homogeneous } +} + +/// The NURBS curve of homogeneous control points `ctrl` on `knots` as a record curve, and its +/// parameter interval. +pub(crate) fn spline_curve(ctrl: &[HPoint], knots: Vec) -> Result<(b::Curve, [f64; 2])> { + let degree = knots.len().checked_sub(ctrl.len() + 1).filter(|d| *d >= 1).ok_or_else(|| invalid("a spline's knots"))?; + let interval = [*knots.get(degree).ok_or_else(|| invalid("knots"))?, *knots.get(ctrl.len()).ok_or_else(|| invalid("knots"))?]; + let curve = if ctrl.iter().all(|h| h.w == 1.0) { + b::Curve::Spline { knots, points: ctrl.iter().map(|h| a3(h.xyz())).collect() } } else { - Ok(rebuilt_body(surface_of(shell), operands, rec)) - } + b::Curve::RationalSpline { knots, homogeneous: ctrl.iter().map(|h| [h.x, h.y, h.z, h.w]).collect() } + }; + Ok((curve, interval)) } +/// The pcurve of an edge along a straight line of its face's parameters: from `a` at the +/// interval's start to `z` at its end. +pub(crate) fn uv_line(a: [f64; 2], z: [f64; 2], [t0, t1]: [f64; 2]) -> Curve2 { + Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![a, z] } +} + +/// One face: the whole of the NURBS surface `n`, bounded by its four boundary curves (each the +/// boundary row or column of its net on its knots, exact for a clamped surface), as a surface +/// body with no history. +pub(crate) fn tensor_sheet(n: &NurbsSurface) -> Result { + let [nu, nv] = n.count(); + if nu < 2 || nv < 2 { + return Err(invalid("a face needs at least 2 x 2 control points")); + } + let [ku, kv] = n.knots().clone(); + let [[u0, u1], [v0, v1]] = n.domain(); + let corner = |i: usize, j: usize| n.point(i, j).project().ok_or_else(|| failed("a corner of the surface has no position")); + let corners = [corner(0, 0)?, corner(nu - 1, 0)?, corner(nu - 1, nv - 1)?, corner(0, nv - 1)?]; + let mut parts = Parts { tolerance: tolerance_of(corners.into_iter()), ..Parts::default() }; + parts.vertices = corners.iter().map(|p| b::Vertex { point: a3(*p), tolerance: parts.tolerance }).collect(); + let row = |j: usize| (0..nu).map(|i| n.point(i, j)).collect::>(); + let column = |i: usize| (0..nv).map(|j| n.point(i, j)).collect::>(); + // Bottom (v0) and top (v1) run along u, left (u0) and right (u1) along v; the loop goes bottom, + // right, top backwards, left backwards: counter-clockwise in (u, v). + let sides = [ + (row(0), ku.clone(), [0, 1], [[u0, v0], [u1, v0]], true), + (column(nu - 1), kv.clone(), [1, 2], [[u1, v0], [u1, v1]], true), + (row(nv - 1), ku, [3, 2], [[u0, v1], [u1, v1]], false), + (column(0), kv, [0, 3], [[u0, v0], [u0, v1]], false), + ]; + let mut uses = Vec::with_capacity(4); + for (i, (ctrl, knots, [a, z], [pa, pz], forward)) in sides.into_iter().enumerate() { + let (curve, interval) = spline_curve(&ctrl, knots)?; + parts.edges.push(b::Edge { nurbs: None, curve, interval, vertices: [index(a)?, index(z)?], tolerance: parts.tolerance, uses: Vec::new() }); + uses.push(b::OrientedEdge { edge: index(i)?, forward, pcurve: uv_line(pa, pz, interval) }); + } + parts.faces.push((b::Face { nurbs: None, surface: spline_surface(n), domain: n.domain(), loops: vec![b::Loop::Edges { edges: uses }] }, true)); + surface_body(&parts.canonical()?.brep) +} + +// ---- Patches ---------------------------------------------------------------------------- + /// A planar surface filling a sketch region. Its history has no operands: the face is new. pub fn patch_region(plane: &Plane, region: &Region2) -> Result { - let f = crate::build::face(plane, region)?; - let mut rec = Rebuild::default(); - rec.made(&f, Vec::new()); - Ok(rebuilt_body(surface_body(vec![f]), &[], &rec)) -} - -/// A chain's edge seeds numbered across all the chains: the segment at `i` of the chain that -/// starts at segment `offset` is segment `offset + i`. -fn numbered(seeds: &[(mt::EdgeID, usize)], offset: usize) -> Vec<(mt::EdgeID, Vec)> { - seeds.iter().map(|(id, i)| (*id, vec![offset + i])).collect() -} - -/// The faces truck swept from the edges `seeds`, each with the segments under the edge whose -/// column it lies in (none where the faces don't follow the pattern; see [`record::follow`]). -fn swept_sides(shell: &mt::Shell, seeds: &[(mt::EdgeID, Vec)], fixed: &[mt::VertexID]) -> Vec { - let provs = record::columns(shell.face_iter(), seeds, None, record::Column::ToEnd, fixed); - shell.face_iter().enumerate().map(|(k, f)| (f.clone(), provs.as_ref().and_then(|p| p.get(k).cloned().flatten()))).collect() -} - -/// A body of a sheet builder's faces: a surface, or a solid where they close; with the history -/// of a body built from the chains' segments (none unless every face's is known). -fn sheet_body(sides: Vec) -> Result { - let history: Option> = sides.iter().map(|(_, p)| p.clone()).collect(); - let shell = mt::Shell::from(sides.into_iter().map(|(f, _)| f).collect::>()); - if shell.shell_condition() == mt::ShellCondition::Closed { - return match crate::body::Solid::try_new(vec![shell.clone()]) { - Ok(solid) => record::attach(Body::new(solid)?, &[], history, Default::default()), - Err(_) => crate::record::rebuilt(mt::Solid::new_unchecked(vec![shell]), &[], &Rebuild::default()), - }; - } - record::attach(surface_of(shell), &[], history, Default::default()) -} - -/// Most curve chains one surface extrude takes. -const MAX_CHAINS: usize = 10_000; - -/// A surface extruded from chains of sketch segments on `plane`: each chain (open, or closed -/// such as a profile's boundary) moved straight from `start` to `end` along the plane normal -/// (offsets in mm). The walls it sweeps form one surface body with no caps. Its history has no -/// operands: every face is new. -pub fn extrude_sheet(plane: &Plane, chains: &[Vec], start: f64, end: f64) -> Result { if !crate::build::frame_ok(plane) { - return Err(KernelError::Invalid("extrude frame is not finite and orthonormal".into())); + return Err(invalid("patch frame is not finite and orthonormal")); } - if !(start.is_finite() && end.is_finite() && start.abs() < 1e7 && end.abs() < 1e7) { - return Err(KernelError::Invalid("extrude distance is not finite".into())); - } - let (lo, hi) = if end >= start { (start, end) } else { (end, start) }; - if hi - lo < 1e-6 { - return Err(KernelError::Invalid("extrude distance is zero".into())); - } - if chains.is_empty() || chains.len() > MAX_CHAINS { - return Err(KernelError::Invalid("pick the curves or profiles to extrude".into())); - } - let base = plane.offset(lo); - let along = crate::body::v3(plane.normal() * (hi - lo)); - let mut sides = Vec::new(); - let mut offset = 0; - for chain in chains { - let (wire, seeds) = crate::build::chain_wire_seeds(&base, chain)?; - let walls: mt::Shell = guard("surface extrude", || Ok(mt::builder::tsweep(&wire, along)))?; - sides.extend(swept_sides(&walls, &numbered(&seeds, offset), &[])); - offset += chain.len(); - } - sheet_body(sides) + let tolerance = tolerance_of(region.outer.segs.iter().map(|s| plane.to_world(s.start()))); + let mut parts = Parts { tolerance, ..Parts::default() }; + // Seen from the plane's normal the outer loop runs counter-clockwise, holes clockwise. + let holes = region.holes.iter().map(|h| h.ccw().reversed()); + let loops = std::iter::once(region.outer.ccw()).chain(holes).map(|lp| sketch_loop(&mut parts, plane, &lp.segs)).collect::>>()?; + let domain = uv_box(&loops).ok_or_else(|| invalid("the region has no area"))?; + parts.faces.push((b::Face { nurbs: None, surface: crate::freeform::plane_surface(plane), domain, loops }, true)); + let c = parts.canonical()?; + let h = record_history(&c.brep, 0, vec![record::generated(Vec::new())], |_, _, _| Vec::new()); + let (body, same) = record_body(&c.brep)?; + with_history(body, same, h, &[]) } -/// A surface revolved from chains of sketch segments on `plane` about the sketch line through -/// `axis_origin` along `axis_dir`: each chain turned from `start` through `sweep` radians (a -/// full turn at most), positive angles carrying it toward the sketch normal. A chain end on the -/// axis stays put there (a cone's apex, a sphere's pole). The walls form one surface body with -/// no caps, or a solid where they close (a full turn of a closed curve, or of a curve from the -/// axis back to it); its history has no operands: every face is new. -pub fn revolve_sheet(plane: &Plane, chains: &[Vec], axis_origin: Vec2, axis_dir: Vec2, start: f64, sweep: f64) -> Result { - use std::f64::consts::TAU; - if !crate::build::frame_ok(plane) || !axis_origin.is_finite() || !axis_dir.is_finite() { - return Err(KernelError::Invalid("revolve frame is not finite and orthonormal".into())); +/// A record tolerance for geometry spanning `points`: 10⁻⁶ of its size, at least 10⁻⁵ mm (the +/// kernel's working tolerance). +fn tolerance_of(points: impl Iterator) -> f64 { + let mut bx = solidcraft_geom::Aabb3::EMPTY; + for p in points { + bx.add(p); } - if !(start.is_finite() && sweep.is_finite() && start.abs() <= TAU && sweep.abs() <= TAU + 1e-9) { - return Err(KernelError::Invalid("revolve angles must be finite, a full turn at most".into())); - } - if sweep.abs() < 1e-6 { - return Err(KernelError::Invalid("revolve angle is zero".into())); - } - if chains.is_empty() || chains.len() > MAX_CHAINS { - return Err(KernelError::Invalid("pick the curves or profiles to revolve".into())); - } - let d = axis_dir.normalized().ok_or_else(|| KernelError::Invalid("revolve axis has no direction".into()))?; - let side = |p: Vec2| d.cross(p - axis_origin); - let on_axis = |p: Vec2| side(p).abs() < 1e-7; - let (origin, n) = (plane.to_world(axis_origin), plane.normal()); - let axis = plane.dir_to_world(d).normalized().ok_or_else(|| KernelError::Invalid("revolve frame has no axis".into()))?; - let mut sides = Vec::new(); - let mut offset = 0; - for chain in chains { - // On one side of the axis; the point farthest from it fixes the turning sense. - let pts: Vec = chain.iter().flat_map(|s| s.polyline(1e-3)).collect(); - if pts.iter().any(|p| side(*p) < -1e-7) && pts.iter().any(|p| side(*p) > 1e-7) { - return Err(KernelError::Invalid("the curves cross the revolve axis".into())); - } - let far = pts.iter().copied().max_by(|a, b| side(*a).abs().total_cmp(&side(*b).abs())).filter(|p| !on_axis(*p)); - let Some(far) = far else { return Err(KernelError::Invalid("the curves lie on the revolve axis".into())) }; - let radial = plane.to_world(far) - origin; - let a = if axis.cross(radial).dot(n) < 0.0 { -axis } else { axis }; - let (first, last) = match (chain.first(), chain.last()) { - (Some(f), Some(l)) => (f.start(), l.end()), - _ => return Err(KernelError::Invalid("an empty curve chain".into())), - }; - let closed = first.dist(last) <= 1e-6; - if closed && pts.iter().any(|p| on_axis(*p)) { - return Err(KernelError::Invalid("not supported yet: a closed curve touching the revolve axis".into())); - } - // The chain starts `start` round: its sketch frame turned there, so the wire's own edges - // are the ones swept (and its faces can be followed back to them). - let turn = |v: Vec3| crate::build::rotate_about(v, Vec3::ZERO, a, start); - let turned = Plane { origin: crate::build::rotate_about(plane.origin, origin, a, start), x: turn(plane.x), y: turn(plane.y) }; - let (wire, seeds) = crate::build::chain_wire_seeds(&turned, chain)?; - let fixed: Vec = [(on_axis(first), wire.front_vertex()), (on_axis(last), wire.back_vertex())] - .into_iter() - .filter_map(|(apex, v)| v.filter(|_| apex).map(|v| v.id())) - .collect(); - let walls: mt::Shell = guard("surface revolve", || { - Ok(match (on_axis(first), on_axis(last)) { - (true, _) => mt::builder::cone(&wire, crate::body::v3(a), mt::Rad(sweep)), - (false, true) => mt::builder::cone(&wire.inverse(), crate::body::v3(a), mt::Rad(sweep)), - (false, false) => mt::builder::rsweep(&wire, p3(origin), crate::body::v3(a), mt::Rad(sweep)), - }) - })?; - sides.extend(swept_sides(&walls, &numbered(&seeds, offset), &fixed)); - offset += chain.len(); - } - sheet_body(sides) + (bx.diagonal() * 1e-6).max(1e-5) } -/// A surface swept from chains of sketch segments on `plane` along a path that starts near -/// them. Along a path whose direction runs on across every joint, lines slide the chains and -/// arcs turn them, exactly; any other path (curves followed as polylines) goes through -/// [`sweep_sheet_points`]. The walls form one surface body with no caps (a solid where they -/// close); its history has no operands: every face is new. -pub fn sweep_sheet(plane: &Plane, chains: &[Vec], path: &[crate::PathSeg]) -> Result { - use crate::PathSeg; - if !crate::build::frame_ok(plane) { - return Err(KernelError::Invalid("sweep frame is not finite and orthonormal".into())); +/// One closed loop of sketch segments on `plane` added to `parts` as an edge loop on the plane's +/// surface: one edge per segment, each segment's start a vertex. +fn sketch_loop(parts: &mut Parts, plane: &Plane, segs: &[Seg2]) -> Result { + if segs.is_empty() || segs.len() > 100_000 { + return Err(invalid("a loop needs 1…100000 curves")); } - if chains.is_empty() || chains.len() > MAX_CHAINS { - return Err(KernelError::Invalid("pick the curves or profiles to sweep".into())); + let v0 = parts.vertices.len(); + for s in segs { + parts.vertices.push(b::Vertex { point: a3(plane.to_world(s.start())), tolerance: parts.tolerance }); } - if path.is_empty() || path.len() > 1000 { - return Err(KernelError::Invalid("the path needs 1…1000 segments".into())); + let mut edges = Vec::with_capacity(segs.len()); + for (i, s) in segs.iter().enumerate() { + let (curve, pcurve) = crate::freeform::segment(plane, s)?; + let vertices = [index(v0 + i)?, index(v0 + (i + 1) % segs.len())?]; + let edge = index(parts.edges.len())?; + parts.edges.push(b::Edge { nurbs: None, curve, interval: crate::freeform::INTERVAL, vertices, tolerance: parts.tolerance, uses: Vec::new() }); + edges.push(b::OrientedEdge { edge, forward: true, pcurve }); } - let ends: Vec<(Vec3, Vec3)> = - path.iter().map(PathSeg::tangents).collect::>().ok_or_else(|| KernelError::Invalid("a path segment has no direction".into()))?; - if ends.windows(2).any(|w| w[0].1.dot(w[1].0) < (1e-3f64).cos()) { - return sweep_sheet_points(plane, chains, &crate::build::path_polyline(path)?); - } - let mut sides = Vec::new(); - let mut offset = 0; - for chain in chains { - let (mut cur, seeds) = crate::build::chain_wire_seeds(plane, chain)?; - // Each edge's segments: the next stretch of the path starts from the edges the last one - // carried them onto, in the same order. - let mut seeds = numbered(&seeds, offset); - for seg in path { - let (part, map): (mt::Shell, Box Vec3>) = match *seg { - PathSeg::Line { a, b } => { - (guard("surface sweep", || Ok(mt::builder::tsweep(&cur, crate::body::v3(b - a))))?, Box::new(move |p| p + (b - a))) - } - PathSeg::Arc { center, axis, angle, .. } => { - let k = axis.normalized().ok_or_else(|| KernelError::Invalid("a path arc has no axis".into()))?; - let part = guard("surface sweep", || Ok(mt::builder::rsweep(&cur, p3(center), crate::body::v3(k), mt::Rad(angle))))?; - (part, Box::new(move |p| crate::build::rotate_about(p, center, k, angle))) - } - }; - let next = far_wire(&part, &cur, map.as_ref())?; - sides.extend(swept_sides(&part, &seeds, &[])); - seeds = next.edge_iter().map(|e| e.id()).zip(seeds.into_iter().map(|(_, n)| n)).collect(); - cur = next; - } - offset += chain.len(); - } - sheet_body(sides) + Ok(b::Loop::Edges { edges }) } -/// A surface swept from chains of sketch segments on `plane` along a 3D polyline path: one smooth -/// B-spline wall per segment where the path has no corners, else ruled walls between the path's -/// points, mitred at the corners (see [`sweep_sheet`]). -pub fn sweep_sheet_points(plane: &Plane, chains: &[Vec], path: &[Vec3]) -> Result { - sweep_sheet_points_with(plane, chains, path, &crate::SweepControl::default()) -} - -/// [`sweep_sheet`] with sweep options. The default options are exactly [`sweep_sheet`]; any -/// other orientation, a twist or an end scale follow the path as a polyline through stations -/// (see [`sweep_sheet_points_with`]). -pub fn sweep_sheet_with(plane: &Plane, chains: &[Vec], path: &[crate::PathSeg], ctl: &crate::SweepControl) -> Result { - if ctl.is_default() { - return sweep_sheet(plane, chains, path); - } - ctl.check()?; - if path.is_empty() || path.len() > 1000 { - return Err(KernelError::Invalid("the path needs 1…1000 segments".into())); - } - if path.iter().any(|s| s.tangents().is_none()) { - return Err(KernelError::Invalid("a path segment has no direction".into())); - } - sweep_sheet_points_with(plane, chains, &crate::build::path_polyline(path)?, ctl) -} - -/// [`sweep_sheet_points`] with sweep options: orientation, twist and end scale. -pub fn sweep_sheet_points_with(plane: &Plane, chains: &[Vec], path: &[Vec3], ctl: &crate::SweepControl) -> Result { - ctl.check()?; - if !crate::build::frame_ok(plane) { - return Err(KernelError::Invalid("sweep frame is not finite and orthonormal".into())); - } - if chains.is_empty() || chains.len() > MAX_CHAINS { - return Err(KernelError::Invalid("pick the curves or profiles to sweep".into())); - } - let ruled = sheet_body(crate::sweep_path::ruled_sheet(plane, chains, path, ctl)?)?; - // Smooth walls where the path has no corners, kept when their area agrees with the ruled - // walls' (a fit that went wrong falls back to those). - if let Ok(Some(sides)) = crate::sweep_path::smooth_sheet(plane, chains, path, ctl) - && let Ok(smooth) = sheet_body(sides) - && let (Ok(a), Ok(b)) = (crate::measure(&smooth), crate::measure(&ruled)) - && (a.area - b.area).abs() <= 0.02 * b.area.abs() - { - return Ok(smooth); - } - Ok(ruled) -} - -/// The far side of a sweep of the wire `start`: for each of its edges, in order and the same -/// way round, the edge of `swept` that `map` carries it onto (matched by its ends and middle). -fn far_wire(swept: &mt::Shell, start: &mt::Wire, map: &dyn Fn(Vec3) -> Vec3) -> Result { - let near = |p: Vec3, q: Vec3| p.dist(q) <= 1e-6 * (1.0 + p.len().max(q.len())); - let mid = |e: &mt::Edge| { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - from_p3(c.subs((t0 + t1) / 2.0)) - }; - let mut out = Vec::new(); - for e in start.edge_iter() { - let (a, b, m) = (map(from_p3(e.front().point())), map(from_p3(e.back().point())), map(mid(e))); - let found = swept.edge_iter().find_map(|f| { - let (fa, fb) = (from_p3(f.front().point()), from_p3(f.back().point())); - if !near(mid(&f), m) { - None - } else if near(fa, a) && near(fb, b) { - Some(f) - } else if near(fa, b) && near(fb, a) { - Some(f.inverse()) - } else { - None - } - }); - out.push(found.ok_or_else(|| KernelError::Failed("sweep: lost the curves along the path".into()))?); - } - Ok(out.into()) -} - -/// A surface lofted through two or more sections, each a chain of sketch segments on its plane, -/// all open or all closed: ruled between two sections, one smooth face per segment through -/// three or more. Closed sections are matched as the solid loft matches them; open ones are -/// split to the same number of segments (longest first) and each turned to run the way the one -/// before it does. Walls only, no caps; the history has no operands: every face is new. -pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { - loft_sheet_with_rails(sections, &[], crate::RailFit::Scale) -} - -/// [`loft_sheet`] following one or two guide rails (polylines from the first section to the last, -/// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the -/// sections between. Without rails, the plain sheet loft. -pub fn loft_sheet_with_rails(sections: &[(Plane, Vec)], rails: &[Vec], fit: crate::RailFit) -> Result { - if sections.len() < 2 || sections.len() > 50 { - return Err(KernelError::Invalid("a loft needs 2…50 sections".into())); - } - let closed: Vec = sections - .iter() - .map(|(_, c)| match (c.first(), c.last()) { - (Some(f), Some(l)) if c.len() <= 4096 => Ok(l.end().dist(f.start()) <= 1e-6), - _ => Err(KernelError::Invalid("a loft section has no curves, or too many".into())), - }) - .collect::>()?; - let all_closed = closed.iter().all(|c| *c); - if !all_closed && closed.iter().any(|c| *c) { - return Err(KernelError::Invalid("the loft sections must be all open or all closed".into())); - } - for (plane, chain) in sections { - // Checks the frame, the numbers and that each chain runs end to end. - if !crate::build::frame_ok(plane) { - return Err(KernelError::Invalid("a loft section's frame is not finite and orthonormal".into())); - } - crate::build::chain_wire(plane, chain)?; - } - let (wires, sources, reversed) = if all_closed { - let loops: Vec<(Plane, solidcraft_geom::Loop2)> = sections.iter().map(|(p, c)| (*p, solidcraft_geom::Loop2 { segs: c.clone() })).collect(); - crate::build::loft_wires(&loops)? - } else { - let n = sections.iter().map(|(_, c)| c.len()).max().unwrap_or(0); - let mut wires = Vec::with_capacity(sections.len()); - let mut sources = Vec::with_capacity(sections.len()); - let mut prev: Option<(Vec3, Vec3)> = None; - // Segments are numbered through the sections in the order given. - let mut offset = 0; - for (plane, chain) in sections { - // Each piece with the segment it is (part of). - let mut segs: Vec<(Seg2, usize)> = chain.iter().enumerate().map(|(i, s)| (*s, offset + i)).collect(); - offset += chain.len(); - // Split the longest segment in half until the counts match. - while segs.len() < n { - let Some(i) = segs.iter().enumerate().max_by(|a, b| a.1.0.length().total_cmp(&b.1.0.length())).map(|(i, _)| i) else { break }; - let (s, k) = segs[i]; - let (a, b) = s.split_half(); - segs.splice(i..=i, [(a, k), (b, k)]); - } - let ends = |c: &[(Seg2, usize)]| c.first().zip(c.last()).map(|(f, l)| (plane.to_world(f.0.start()), plane.to_world(l.0.end()))); - if let (Some((ps, pe)), Some((s, e))) = (prev, ends(&segs)) - && s.dist(ps) + e.dist(pe) > s.dist(pe) + e.dist(ps) - { - segs = segs.iter().rev().map(|(s, k)| (s.reversed(), *k)).collect(); - } - prev = ends(&segs); - let pieces: Vec = segs.iter().map(|(s, _)| *s).collect(); - wires.push(crate::build::uniform_chain_wire(plane, &pieces, false)?); - sources.push(segs.iter().map(|(_, k)| vec![*k]).collect::>()); - } - (wires, sources, false) - }; - let mut planes: Vec = sections.iter().map(|(p, _)| *p).collect(); - if reversed { - planes.reverse(); - } - let faces = guard("surface loft", || { - let all = crate::loft_rails::railed_wires(&planes, &wires, all_closed, rails, fit)?; - // A plain loft falls back to ruled faces where the smooth one fails; a railed one has to - // follow its rails. - let smooth = if all.len() >= 3 { Some(crate::build::smooth_loft_faces(&all, &sources, all_closed)) } else { None }; - match smooth { - Some(Ok(f)) => Ok(f), - Some(Err(e)) if !rails.is_empty() => Err(e), - _ => crate::build::ruled_loft_faces(&wires, &sources), - } - })?; - sheet_body(faces) -} - -/// The edge of a body nearest a point (by samples along each edge). -pub(crate) fn edge_near(body: &Body, p: Vec3) -> Option { - let mut best: Option<(f64, mt::Edge)> = None; - for e in body.solid.edge_iter() { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); +/// The edge of a body nearest a point (by samples along each edge), within 5% of the body's size: +/// its index in the body's edge order. +pub(crate) fn edge_near(body: &Body, p: Vec3) -> Option { + let r = body.record(); + let mut best: Option<(f64, usize)> = None; + for (i, e) in r.edges.iter().enumerate() { + let Ok(c) = CurveEval::new(e.parameters()) else { continue }; + let [t0, t1] = e.interval; for k in 0..=32 { - let d = from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 32.0)).dist(p); - if best.as_ref().is_none_or(|(bd, _)| d < *bd) { - best = Some((d, e.clone())); + let Some(q) = c.point(t0 + (t1 - t0) * k as f64 / 32.0) else { continue }; + let d = q.dist(p); + if best.is_none_or(|(bd, _)| d < bd) { + best = Some((d, i)); } } } best.filter(|(d, _)| *d <= body.size() * 0.05 + 1e-6).map(|(_, e)| e) } +/// A chain of a body's edges: each edge (its index in the body's edge order) and whether the +/// chain runs along it. +pub(crate) type Chain = Vec<(usize, bool)>; + /// A surface filling a closed loop of a body's edges (each picked by a point on it): one face on -/// the body's own edges, planar when the loop is certainly planar ([`crate::plane_fit`]), else a -/// B-spline height field over the loop's plane ([`crate::fill`]; loops that do not bound one are -/// refused). Its history is over `[body]`: the face is new, its edges the body's own. +/// the body's own edges, the loop's plane when it is certainly planar, else a B-spline patch +/// ([`crate::fill`], with no crown; loops that do not bound one are refused). Its history is over +/// `[body]`: the face is new, its edges the body's own. pub fn patch_edges(body: &Body, at: &[Vec3]) -> Result { body.require_brep("patch")?; if at.is_empty() || at.len() > 10_000 { - return Err(KernelError::Invalid("pick the edges of a closed loop".into())); + return Err(invalid("pick the edges of a closed loop")); } - guard("patch", || { - let chain = picked_loop(body, at)?; - let Some(face) = crate::plane_fit::planar_face(&chain, crate::fill::planarity_tolerance(body))? else { - // Not certainly planar: a fitted surface. - return crate::fill::fill_loop(body, &chain); - }; - // A new face on the body's own edges. - let mut rec = Rebuild::default(); - rec.made(&face, Vec::new()); - Ok(rebuilt_body(surface_body(vec![face]), &[&body.solid], &rec)) - }) + crate::fill::patch_loop(body, at, 0.0) } -/// The edges of `body` picked by points on them, chained into one closed loop (each turned to -/// run along it). Call it under [`guard`]: sampling an intersection curve can fail in truck. -pub(crate) fn picked_loop(body: &Body, at: &[Vec3]) -> Result> { - match picked_chain(body, at)? { - (chain, true) => Ok(chain), - (_, false) => Err(KernelError::Invalid("the edges do not form a closed loop".into())), - } -} - -/// The edges of `body` picked by points on them, chained end to end (each turned to run along -/// the chain), and whether the chain closes: a closed loop starts with the last edge picked; an -/// open chain runs from the free end met first in pick order. Edges that branch, or form more -/// than one chain, are refused. Call it under [`guard`], as [`picked_loop`]. -pub(crate) fn picked_chain(body: &Body, at: &[Vec3]) -> Result<(Vec, bool)> { - let mut edges: Vec = Vec::new(); +/// The edges of `body` picked by points on them, chained end to end (each turned to run along the +/// chain), and whether the chain closes: a closed loop starts with the last edge picked; an open +/// chain runs from the free end met first in pick order. Edges that branch, or form more than one +/// chain, are refused. +pub(crate) fn picked_chain(body: &Body, at: &[Vec3]) -> Result<(Chain, bool)> { + let r = body.record(); + let mut edges: Vec = Vec::new(); for p in at { - let e = edge_near(body, *p).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?; - if !edges.iter().any(|x| x.id() == e.id()) { + let e = edge_near(body, *p).ok_or_else(|| invalid(format!("no edge at {p:?}")))?; + if !edges.contains(&e) { edges.push(e); } } - let mut uses: HashMap = HashMap::new(); - for e in &edges { - *uses.entry(e.front().id()).or_default() += 1; - *uses.entry(e.back().id()).or_default() += 1; + let ends = |e: usize| r.edges.get(e).map(|x| x.vertices); + let mut uses: std::collections::HashMap = std::collections::HashMap::new(); + for &e in &edges { + for v in ends(e).ok_or_else(|| invalid("an edge reference"))? { + *uses.entry(v).or_default() += 1; + } } if uses.values().any(|n| *n > 2) { - return Err(KernelError::Invalid("the edges branch: pick one chain".into())); + return Err(invalid("the edges branch: pick one chain")); } - let free = |v: &mt::Vertex| uses.get(&v.id()) == Some(&1); - let open_end = edges.iter().find_map(|e| [e.front(), e.back()].into_iter().find(|v| free(v)).cloned()); + let open_end = edges.iter().find_map(|&e| ends(e)?.into_iter().find(|v| uses.get(v) == Some(&1))); let mut pool = edges; - let (first, closed) = match &open_end { + let (first, closed) = match open_end { Some(v) => { - let k = pool.iter().position(|e| e.front().id() == v.id() || e.back().id() == v.id()); - let e = k.map(|k| pool.remove(k)).ok_or_else(|| KernelError::Invalid("no edges".into()))?; - (if e.front().id() == v.id() { e } else { e.inverse() }, false) + let k = pool.iter().position(|&e| ends(e).is_some_and(|x| x.contains(&v))).ok_or_else(|| invalid("no edges"))?; + let e = pool.remove(k); + ((e, ends(e).is_some_and(|x| x[0] == v)), false) } - None => (pool.pop().ok_or_else(|| KernelError::Invalid("no edges".into()))?, true), + None => ((pool.pop().ok_or_else(|| invalid("no edges"))?, true), true), }; - let start = first.front().id(); - let mut at_v = first.back().clone(); + let head = |(e, forward): (usize, bool)| ends(e).map(|x| if forward { x[1] } else { x[0] }); + let start = ends(first.0).map(|x| if first.1 { x[0] } else { x[1] }); + let mut at_v = head(first); let mut chain = vec![first]; - while !(closed && at_v.id() == start) { - let Some(k) = pool.iter().position(|e| e.front().id() == at_v.id() || e.back().id() == at_v.id()) else { break }; + while !(closed && at_v == start) { + let Some(v) = at_v else { break }; + let Some(k) = pool.iter().position(|&e| ends(e).is_some_and(|x| x.contains(&v))) else { break }; let e = pool.remove(k); - let e = if e.front().id() == at_v.id() { e } else { e.inverse() }; - at_v = e.back().clone(); - chain.push(e); + let link = (e, ends(e).is_some_and(|x| x[0] == v)); + at_v = head(link); + chain.push(link); } if !pool.is_empty() { let what = if closed { "the edges form more than one loop" } else { "the edges form more than one chain" }; - return Err(KernelError::Invalid(what.into())); + return Err(invalid(what)); } Ok((chain, closed)) } -/// Faces of a body copied out as a surface body (faces picked by points on them). Its history is -/// over `[body]`: the faces and their edges are the body's. -pub fn copy_faces(body: &Body, at: &[Vec3]) -> Result { - body.require_brep("copy faces")?; - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); - let mut chosen = Vec::new(); - for p in at { - // The face whose mesh passes nearest the point. - let i = nearest_face(body, *p)?; - if !chosen.contains(&i) { - chosen.push(i); +// ---- Faces of a body -------------------------------------------------------------------- + +/// Index of the face nearest a point (over its mesh triangles). +pub(crate) fn nearest_face(body: &Body, p: Vec3) -> Result { + let m = body.mesh(&crate::MeshTolerance::chord(body.size() * 2e-3))?; + let mut best: Option<(f64, u32)> = None; + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + let Some([a, b, c]) = m.tri(t) else { continue }; + let d = ((a + b + c) / 3.0).dist(p).min(a.dist(p)).min(b.dist(p)).min(c.dist(p)); + if best.is_none_or(|(x, _)| d < x) { + best = Some((d, *f)); } } - let copied = surface_body(chosen.into_iter().filter_map(|i| faces.get(i).map(|f| (*f).clone())).collect()); - Ok(rebuilt_body(copied, &[&body.solid], &Rebuild::default())) + best.map(|(_, f)| f as usize).ok_or_else(|| invalid("no face there")) } -/// The faces picked by points on them (each once, in the order picked); every face when no -/// point is given. +/// The faces picked by points on them (each once, in the order picked); every face when no point +/// is given. fn picked_faces(body: &Body, at: &[Vec3]) -> Result> { if at.len() > 10_000 { - return Err(KernelError::Invalid("too many faces picked".into())); + return Err(invalid("too many faces picked")); } if at.is_empty() { return Ok((0..body.face_count()).collect()); @@ -537,659 +557,1064 @@ fn picked_faces(body: &Body, at: &[Vec3]) -> Result> { Ok(chosen) } -/// A body's faces taken apart: each picked face (by points on it; every face when none are -/// given) its own surface body, and the faces left, if any, one surface body. A solid comes -/// apart into surfaces. Histories are over `[body]`: each face is the body's. -pub fn unstitch(body: &Body, at: &[Vec3]) -> Result<(Vec, Option)> { - body.require_brep("unstitch")?; - let chosen = picked_faces(body, at)?; - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); - if faces.len() < 2 { - return Err(KernelError::Invalid("the body has one face: nothing to unstitch".into())); +/// Faces of a body copied out as a surface body (faces picked by points on them). Its history is +/// over `[body]`: the faces and their edges are the body's. +pub fn copy_faces(body: &Body, at: &[Vec3]) -> Result { + body.require_brep("copy faces")?; + if at.is_empty() { + return Err(invalid("pick the faces to copy")); } - let piece = |picked: Vec| rebuilt_body(surface_body(picked), &[&body.solid], &Rebuild::default()); - let pieces: Vec = chosen.iter().filter_map(|i| faces.get(*i)).map(|f| piece(vec![(*f).clone()])).collect(); - let rest: Vec = faces.iter().enumerate().filter(|(i, _)| !chosen.contains(i)).map(|(_, f)| (*f).clone()).collect(); - Ok((pieces, (!rest.is_empty()).then(|| piece(rest)))) + let chosen = picked_faces(body, at)?; + let r = body.record(); + taken(body, r, &chosen.into_iter().map(|f| (f, false)).collect::>()) } -/// A surface body with the picked faces (by points on them; every face when none are given) -/// turned over: their normals point the other way. A solid is refused (its faces face out). -/// The history is over `[body]`: each face is the body's, turned over or not. +/// A body's faces taken apart: each picked face (by points on it; every face when none are given) +/// its own surface body, and the faces left, if any, one surface body. A solid comes apart into +/// surfaces. Histories are over `[body]`: each face is the body's. +pub fn unstitch(body: &Body, at: &[Vec3]) -> Result<(Vec, Option)> { + body.require_brep("unstitch")?; + let r = body.record(); + if r.faces.len() < 2 { + return Err(invalid("the body has one face: nothing to unstitch")); + } + let chosen = picked_faces(body, at)?; + let pieces = chosen.iter().map(|f| taken(body, r, &[(*f, false)])).collect::>>()?; + let rest: Vec<(usize, bool)> = (0..r.faces.len()).filter(|f| !chosen.contains(f)).map(|f| (f, false)).collect(); + let rest = if rest.is_empty() { None } else { Some(taken(body, r, &rest)?) }; + Ok((pieces, rest)) +} + +/// A surface body with the picked faces (by points on them; every face when none are given) turned +/// over: their normals point the other way. A solid is refused (its faces face out). The history +/// is over `[body]`: each face is the body's, turned over or not. pub fn reverse_faces(body: &Body, at: &[Vec3]) -> Result { body.require_brep("reverse normal")?; if !body.is_surface() { - return Err(KernelError::Invalid("a solid's faces face out: unstitch it into surfaces first".into())); + return Err(invalid("a solid's faces face out: unstitch it into surfaces first")); } let chosen = picked_faces(body, at)?; - let mut rec = Rebuild::default(); - let faces: Vec = body - .solid - .face_iter() - .enumerate() - .map(|(i, f)| { - if !chosen.contains(&i) { - return f.clone(); - } - let turned = f.inverse(); - rec.whole(&turned, f); - turned - }) - .collect(); - Ok(rebuilt_body(surface_body(faces), &[&body.solid], &rec)) + let r = body.record(); + taken(body, r, &(0..r.faces.len()).map(|f| (f, chosen.contains(&f))).collect::>()) } -/// A body with some of its faces (indices in its face order) taken away and the gap left open: -/// a surface body of the faces left. Deleting every face is refused. The history is over -/// `[body]`: each face left is the body's. +/// A body with some of its faces (indices in its face order) taken away and the gap left open: a +/// surface body of the faces left. Deleting every face is refused. The history is over `[body]`: +/// each face left is the body's. pub fn remove_faces(body: &Body, faces: &[usize]) -> Result { body.require_brep("Delete Face")?; if faces.is_empty() { - return Err(KernelError::Invalid("no faces given".into())); + return Err(invalid("no faces given")); } - let left: Vec = body.solid.face_iter().enumerate().filter(|(i, _)| !faces.contains(i)).map(|(_, f)| f.clone()).collect(); + let r = body.record(); + let left: Vec<(usize, bool)> = (0..r.faces.len()).filter(|f| !faces.contains(f)).map(|f| (f, false)).collect(); if left.is_empty() { - return Err(KernelError::Invalid("that would delete every face of the body".into())); + return Err(invalid("that would delete every face of the body")); } - Ok(rebuilt_body(surface_body(left), &[&body.solid], &Rebuild::default())) + taken(body, r, &left) } -/// Index of the face nearest a point (over its mesh triangles). -pub(crate) fn nearest_face(body: &Body, p: Vec3) -> Result { - let m = body.tessellate(body.size() * 2e-3)?; - let mut best: Option<(f64, u32)> = None; - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - let Some([a, b, c]) = m.tri(t) else { continue }; - let d = ((a + b + c) / 3.0).dist(p).min(a.dist(p)).min(b.dist(p)).min(c.dist(p)); - if best.is_none_or(|(x, _)| d < x) { - best = Some((d, *f)); +/// `h`, a history over one record whose faces and edges came from the parts `c` numbers, carried +/// to the records `offsets` took them from: each face origin through `face`, each edge origin to +/// the record edge it was (`None` where an origin has no record behind it). +fn carried(h: &History, c: &Canonical, offsets: &Offsets, operands: usize, face: impl Fn(usize, usize) -> FaceOrigin) -> Option { + let back = |o: FaceOrigin| -> std::result::Result { + match o { + FaceOrigin::Face { face: f, .. } => c.faces.get(f).and_then(|p| owner(offsets, *p, 0)).map(|(k, i)| face(k, i)).ok_or(()), + other => Ok(other), + } + }; + let faces = h + .faces + .iter() + .map(|f| Some(FaceProv { origins: f.origins.iter().map(|o| back(*o).ok()).collect::>()?, change: f.change })) + .collect::>>()?; + let edges = h + .edges + .iter() + .map(|e| { + let origins = e + .origins + .iter() + .map(|o| match o { + EdgeOrigin::Edge { edge, .. } => { + let (operand, edge) = c.edges.get(*edge).and_then(|p| owner(offsets, *p, 1))?; + Some(EdgeOrigin::Edge { operand, edge }) + } + EdgeOrigin::Meet { a, b } => Some(EdgeOrigin::Meet { a: a.try_map(back).ok()?, b: b.try_map(back).ok()? }), + }) + .collect::>()?; + Some(EdgeProv { faces: e.faces.clone(), origins }) + }) + .collect::>>()?; + Some(History { operands, faces, edges }) +} + +/// The joined record `c` with each edge of one input split exactly at every vertex of another +/// input that lies on it within `tol` (away from the edge's own ends), so that a sheet's corner +/// on another's edge is a vertex of both and the sheets sew there (`Brep::split_edges`); `c`'s +/// maps carried through. +fn without_t_junctions(c: Canonical, offsets: &Offsets, tol: f64) -> Result { + let r = &c.brep; + let input_of_edge: Vec> = c.edges.iter().map(|p| owner(offsets, *p, 1).map(|(k, _)| k)).collect(); + let mut input_of_vertex: Vec> = vec![None; r.vertices.len()]; + for (e, k) in r.edges.iter().zip(&input_of_edge) { + for v in e.vertices { + if let Some(slot) = input_of_vertex.get_mut(v as usize) { + *slot = slot.or(*k); + } } } - best.map(|(_, f)| f as usize).ok_or_else(|| KernelError::Invalid("no face there".into())) + let point = |v: u32| r.vertices.get(v as usize).map(|x| Vec3::new(x.point[0], x.point[1], x.point[2])); + let mut splits: Vec<(u32, f64)> = Vec::new(); + for (e, (edge, ke)) in r.edges.iter().zip(&input_of_edge).enumerate() { + let Ok(curve) = CurveEval::new(edge.parameters()) else { continue }; + let ends: Vec = edge.vertices.iter().filter_map(|v| point(*v)).collect(); + // Only vertices within a chord's reach of the edge's samples can lie on it. + let [a, z] = edge.interval; + let samples: Vec = (0..=SAMPLES).filter_map(|k| curve.point(a + (z - a) * k as f64 / SAMPLES as f64)).collect(); + let chord = samples.windows(2).map(|w| w[0].dist(w[1])).fold(0.0, f64::max); + for (v, kv) in input_of_vertex.iter().enumerate() { + let Some(p) = point(index(v)?) else { continue }; + if kv == ke || ends.iter().any(|q| q.dist(p) <= tol) || samples.iter().all(|q| q.dist(p) > chord + tol) { + continue; + } + if let Some(t) = nearest_parameter(&curve, edge.interval, p).filter(|(_, d)| *d <= tol).map(|(t, _)| t) { + splits.push((index(e)?, t)); + } + } + } + if splits.is_empty() { + return Ok(c); + } + let split = + solidcraft_geom::brep::split_edges(r, &splits).map_err(|e| failed(format!("stitch: splitting edges at the other sheets' vertices: {e}")))?; + let faces = + split.faces.iter().map(|f| c.faces.get(*f as usize).copied().ok_or_else(|| failed("stitch: a face reference"))).collect::>()?; + let edges = + split.edges.iter().map(|e| c.edges.get(*e as usize).copied().ok_or_else(|| failed("stitch: an edge reference"))).collect::>()?; + Ok(Canonical { brep: split.brep, faces, edges }) } -/// Sew surface bodies along edges that coincide (within `tol`): one body, a solid when the -/// faces close up. Faces are turned so that neighbours agree. The result's history is over -/// `bodies`: each face the one it was sewn from, each edge the edges sewn into it. +/// Samples along an edge for finding the points of it near a vertex. +const SAMPLES: usize = 64; + +/// The parameter of the curve's point nearest `p` inside `interval`, and the distance: the +/// nearest of evenly spaced samples, then a golden-section search between its neighbours. +pub(crate) fn nearest_parameter(c: &CurveEval, [a, b]: [f64; 2], p: Vec3) -> Option<(f64, f64)> { + let dist = |t: f64| c.point(t).map_or(f64::INFINITY, |q| q.dist(p)); + let at = |k: usize| a + (b - a) * k as f64 / SAMPLES as f64; + let best = (0..=SAMPLES).min_by(|&i, &j| dist(at(i)).total_cmp(&dist(at(j))))?; + let (mut lo, mut hi) = (at(best.saturating_sub(1)), at((best + 1).min(SAMPLES))); + let ratio = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..80 { + let (x, y) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo)); + if dist(x) < dist(y) { + hi = y; + } else { + lo = x; + } + } + let t = 0.5 * (lo + hi); + (t > a && t < b).then(|| (t, dist(t))) +} + +/// Sew surface bodies along edges that coincide (within `tol`; the bodies' working tolerance when +/// not positive): one body, a solid when the faces close up. SMLib turns the faces so that +/// neighbours agree (outward on a solid). The result's history is over `bodies`: each face the one +/// it was sewn from, each edge the edges sewn into it. pub fn stitch(bodies: &[&Body], tol: f64) -> Result { if bodies.is_empty() { - return Err(KernelError::Invalid("nothing to stitch".into())); + return Err(invalid("nothing to stitch")); } for b in bodies { b.require_brep("stitch")?; } let size = bodies.iter().map(|b| b.size()).fold(0.0, f64::max); let tol = if tol.is_finite() && tol > 0.0 { tol } else { size * 1e-6 + 1e-6 }; - guard("stitch", || { - let faces: Vec = bodies.iter().flat_map(|b| b.solid.face_iter().cloned().collect::>()).collect(); - // Shared vertices by position, shared edges by their ends and middle. - let mut verts: Vec = Vec::new(); - let mut vmap: HashMap = HashMap::new(); - let mut canon = |v: &mt::Vertex, verts: &mut Vec| -> mt::Vertex { - if let Some(c) = vmap.get(&v.id()) { - return c.clone(); - } - let p = v.point(); - let c = match verts.iter().find(|u| u.point().distance(p) <= tol) { - Some(u) => u.clone(), - None => { - verts.push(v.clone()); - v.clone() - } - }; - vmap.insert(v.id(), c.clone()); - c - }; - let mut edges: Vec<(mt::Edge, mt::Point3)> = Vec::new(); - let mut out = Vec::with_capacity(faces.len()); - let mut rec = Rebuild::default(); - for f in &faces { - let mut wires = Vec::new(); - for w in f.absolute_boundaries() { - let mut nw = Vec::new(); - for e in w.edge_iter() { - let abs = if e.orientation() { e.clone() } else { e.inverse() }; - let (a, b) = (canon(abs.front(), &mut verts), canon(abs.back(), &mut verts)); - let c = abs.curve(); - let (t0, t1) = c.range_tuple(); - let mid = c.subs(0.5 * (t0 + t1)); - let found = edges.iter().find_map(|(x, m)| { - if m.distance(mid) > tol * 10.0 { - return None; - } - if x.front().id() == a.id() && x.back().id() == b.id() { - Some(x.clone()) - } else if x.front().id() == b.id() && x.back().id() == a.id() { - Some(x.inverse()) - } else { - None - } - }); - let ne = match found { - Some(x) => x, - None => { - let x = mt::Edge::new_unchecked(&a, &b, c); - edges.push((x.clone(), mid)); - x - } - }; - rec.piece(&ne, &abs); - nw.push(if e.orientation() { ne } else { ne.inverse() }); - } - wires.push(mt::Wire::from(nw)); - } - let mut nf = mt::Face::new_unchecked(wires, f.surface()); - if !f.orientation() { - nf.invert(); - } - rec.whole(&nf, f); - out.push(nf); - } - // Neighbours run their shared edges opposite ways. - let mut uses: HashMap> = HashMap::new(); - for (i, f) in out.iter().enumerate() { - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - uses.entry(e.id()).or_default().push((i, e.orientation())); - } - } - let mut flip: Vec> = vec![None; out.len()]; - for s in 0..out.len() { - if flip[s].is_some() { - continue; - } - flip[s] = Some(false); - let mut stack = vec![s]; - while let Some(i) = stack.pop() { - let fl = flip[i].unwrap_or(false); - let Some(f) = out.get(i) else { continue }; - for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { - let d = e.orientation() != fl; - for &(j, dj) in uses.get(&e.id()).into_iter().flatten() { - if j != i && flip[j].is_none() { - flip[j] = Some(dj == d); - stack.push(j); - } - } - } - } - } - let out: Vec = out.into_iter().zip(flip).map(|(f, fl)| if fl == Some(true) { f.inverse() } else { f }).collect(); - let operands: Vec<&mt::Solid> = bodies.iter().map(|b| &*b.solid).collect(); - body_of(out, &operands, &rec) - }) + let records: Vec<&Brep> = bodies.iter().map(|b| b.record()).collect(); + let (parts, offsets) = Parts::joined(&records)?; + let c = without_t_junctions(parts.canonical()?, &offsets, tol)?; + let (body, h) = imp::stitched(&c.brep, tol)?; + let h = h.and_then(|h| carried(&h, &c, &offsets, bodies.len(), |operand, face| FaceOrigin::Face { operand, face })); + Ok(body.with_checked_history(h, &record::counts(bodies))) } -/// How a face moves along its normal: a plane slides, a circular cylinder changes radius. -#[derive(Clone, Copy)] -pub(crate) enum Offset { - Plane { n: Vec3 }, - Cylinder { o: Vec3, axis: UnitVec3, r: f64, out: f64 }, -} - -impl Offset { - pub(crate) fn of(f: &mt::Face) -> Option { - match crate::splitface::analytic_field(&f.oriented_surface())? { - crate::splitface::Analytic::Plane { n } => Some(Offset::Plane { n }), - crate::splitface::Analytic::Cylinder { o, axis, r, out } => Some(Offset::Cylinder { o, axis, r, out }), - } +/// [`stitch`] at `tol` exactly, taking a result whose SMLib check fails no more tests than the +/// bodies' own records do, leaving out the tests `exempt` (by SMLib's test number): Repair Part +/// sews parts SMLib's check already finds fault with (an import's edges off their faces), and +/// an edge sewn across a gap carries that gap as its own tolerance. +pub(crate) fn stitch_no_worse(bodies: &[&Body], tol: f64, exempt: &[u32]) -> Result { + if bodies.is_empty() { + return Err(invalid("nothing to stitch")); } - pub(crate) fn map(&self, p: Vec3, d: f64) -> Vec3 { - match *self { - Offset::Plane { n } => p + n * d, - // Scaled about the axis (control points of a NURBS circle stay exact). - Offset::Cylinder { o, axis, r, out } => { - let v = p - o; - let radial = v - axis * v.dot(axis); - p + radial * (out * d / r) - } - } + for b in bodies { + b.require_brep("stitch")?; } -} - -fn map_pt(off: &Offset, p: mt::Point3, d: f64) -> mt::Point3 { - p3(off.map(from_p3(p), d)) -} - -/// A curve moved by an offset (control points mapped; exact for lines, and for circles square -/// to a cylinder's axis or in a plane). -pub(crate) fn map_curve(off: &Offset, c: &mt::Curve, d: f64) -> Result { - if let Some(moved) = map_control_points(c, |p| off.map(p, d)) { - return Ok(moved); + if !(tol.is_finite() && tol > 0.0) { + return Err(invalid("a stitch tolerance must be positive")); } - // Anything else: a cubic through moved samples. - let (t0, t1) = c.range_tuple(); - let pts: Vec = (0..=32).map(|k| off.map(from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 32.0)), d)).collect(); - Ok(mt::Curve::BSplineCurve(crate::build::interpolate_cubic(&pts).ok_or_else(|| KernelError::Failed("offset edge".into()))?)) + let records: Vec<&Brep> = bodies.iter().map(|b| b.record()).collect(); + let (parts, offsets) = Parts::joined(&records)?; + let c = without_t_junctions(parts.canonical()?, &offsets, tol)?; + let (body, h) = imp::stitched_no_worse(&c.brep, tol, exempt)?; + let h = h.and_then(|h| carried(&h, &c, &offsets, bodies.len(), |operand, face| FaceOrigin::Face { operand, face })); + Ok(body.with_checked_history(h, &record::counts(bodies))) } -/// A line, B-spline or NURBS curve with its control points mapped by `f` (the exact image of -/// the curve under an affine `f`); `None` for a curve without control points (an -/// intersection curve). -pub(crate) fn map_control_points(c: &mt::Curve, f: impl Fn(Vec3) -> Vec3) -> Option { - let map = |p: mt::Point3| p3(f(from_p3(p))); - Some(match c { - mt::Curve::Line(l) => mt::Curve::Line(mt::Line(map(l.0), map(l.1))), - mt::Curve::BSplineCurve(b) => { - let pts: Vec = b.control_points().iter().map(|p| map(*p)).collect(); - mt::Curve::BSplineCurve(mt::BSplineCurve::new(b.knot_vec().clone(), pts)) - } - mt::Curve::NurbsCurve(n) => { - let nb = n.non_rationalized(); - let pts: Vec = nb - .control_points() - .iter() - .map(|h| { - let w = h.w; - let q = map(mt::Point3::new(h.x / w, h.y / w, h.z / w)); - mt::Vector4::new(q.x * w, q.y * w, q.z * w, w) - }) - .collect(); - mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::new(nb.knot_vec().clone(), pts))) - } - mt::Curve::IntersectionCurve(_) => return None, - }) -} - -/// A surface moved by an offset (control points mapped; exact for planes and NURBS cylinders). -pub(crate) fn map_surface(off: &Offset, s: &mt::Surface, d: f64) -> Result { - Ok(match s { - mt::Surface::Plane(pl) => { - let (o, a, b) = (pl.origin(), pl.u_axis(), pl.v_axis()); - let o2 = map_pt(off, o, d); - mt::Surface::Plane(mt::Plane::new(o2, o2 + a, o2 + b)) - } - mt::Surface::BSplineSurface(b) => { - let rows: Vec> = b.control_points().iter().map(|r| r.iter().map(|p| map_pt(off, *p, d)).collect()).collect(); - mt::Surface::BSplineSurface(mt::BSplineSurface::new((b.uknot_vec().clone(), b.vknot_vec().clone()), rows)) - } - mt::Surface::NurbsSurface(n) => { - let nb = n.non_rationalized(); - let rows: Vec> = nb - .control_points() - .iter() - .map(|r| { - r.iter() - .map(|h| { - let w = h.w; - let q = map_pt(off, mt::Point3::new(h.x / w, h.y / w, h.z / w), d); - mt::Vector4::new(q.x * w, q.y * w, q.z * w, w) - }) - .collect() - }) - .collect(); - mt::Surface::NurbsSurface(mt::NurbsSurface::new(mt::BSplineSurface::new((nb.uknot_vec().clone(), nb.vknot_vec().clone()), rows))) - } - _ => return Err(KernelError::Invalid("not supported yet: thickening this kind of surface".into())), - }) -} - -/// How far Thicken's fitted faces may stray from the true offset (mm). -const THICKEN_TOLERANCE: f64 = 0.01; - /// A surface body thickened into a solid: offset along the faces' normals by `thickness` -/// (negative: against them), or by half each way when `symmetric`. Planes and circular -/// cylinders move exactly, other faces onto fitted surfaces (see `surface_offset`); a thickness -/// that would fold a face over is refused. Neighbouring faces must meet smoothly (their offsets -/// agree). +/// (negative: against them), or by half each way when `symmetric`, by SMLib's thicken +/// ([`crate::offset_backend::thicken`]). pub fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result { body.require_brep("thicken")?; - if !(thickness.is_finite() && thickness.abs() > 1e-9) { - return Err(KernelError::Invalid("thickness must be non-zero".into())); - } - let (d0, d1) = if symmetric { (-thickness / 2.0, thickness / 2.0) } else { (0.0, thickness) }; - let (lo, hi) = (d0.min(d1), d0.max(d1)); - let size = body.size(); - let tol = size * 1e-7 + 1e-9; - guard("thicken", || { - let faces: Vec = body.solid.face_iter().cloned().collect(); - if faces.is_empty() { - return Err(KernelError::Invalid("nothing to thicken".into())); - } - // Planes and circular cylinders move exactly; other faces onto surfaces fitted within the - // offset tolerance (Offset Surface's). - let offs: Vec = - faces.iter().map(|f| crate::surface_offset::FaceMover::new(f, &[lo, hi], THICKEN_TOLERANCE)).collect::>()?; - let near = |a: Vec3, b: Vec3| a.dist(b) <= tol * 1e3; - // Each side's copies of every vertex and edge. Faces that move one to the same place share - // the copy (they meet smoothly there); across a sharp edge each face has its own. - let mut vcopies: [HashMap>; 2] = [HashMap::new(), HashMap::new()]; - let mut ecopies: [HashMap>; 2] = [HashMap::new(), HashMap::new()]; - // Each face's copies, by side: (face, vertex) → vertex, (face, edge) → edge. - let mut vof: [HashMap<(usize, mt::VertexID), mt::Vertex>; 2] = [HashMap::new(), HashMap::new()]; - let mut eof: [HashMap<(usize, mt::EdgeID), mt::Edge>; 2] = [HashMap::new(), HashMap::new()]; - // The faces using each edge, in order. - let mut users: HashMap> = HashMap::new(); - let mut abs_edges: HashMap = HashMap::new(); - for (fi, (f, off)) in faces.iter().zip(&offs).enumerate() { - for e in f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()) { - let abs = if e.orientation() { e.clone() } else { e.inverse() }; - let list = users.entry(abs.id()).or_default(); - if !list.contains(&fi) { - list.push(fi); - } - abs_edges.entry(abs.id()).or_insert_with(|| abs.clone()); - for (side, d) in [lo, hi].into_iter().enumerate() { - for v in [abs.front(), abs.back()] { - if vof[side].contains_key(&(fi, v.id())) { - continue; - } - let at = off.point(from_p3(v.point()), d)?; - let list = vcopies[side].entry(v.id()).or_default(); - let copy = match list.iter().find(|c| near(from_p3(c.point()), at)) { - Some(c) => c.clone(), - None => { - let c = mt::Vertex::new(p3(at)); - list.push(c.clone()); - c - } - }; - vof[side].insert((fi, v.id()), copy); - } - let (Some(a), Some(b)) = (vof[side].get(&(fi, abs.front().id())).cloned(), vof[side].get(&(fi, abs.back().id())).cloned()) else { - continue; - }; - let c = abs.curve(); - let (t0, t1) = c.range_tuple(); - let mid = off.point(from_p3(c.subs(0.5 * (t0 + t1))), d)?; - let list = ecopies[side].entry(abs.id()).or_default(); - let shared = list.iter().find(|m| { - m.front().id() == a.id() && m.back().id() == b.id() && { - let mc = m.curve(); - let (s0, s1) = mc.range_tuple(); - near(from_p3(mc.subs(0.5 * (s0 + s1))), mid) - } - }); - let copy = match shared { - Some(m) => m.clone(), - None => { - let m = mt::Edge::new_unchecked(&a, &b, off.curve(&c, d)?); - list.push(m.clone()); - m - } - }; - eof[side].insert((fi, abs.id()), copy); - } - } - } - // Lines joining a vertex's copy on one side to its copy on the other, once each. - let mut risers: HashMap<(mt::VertexID, mt::VertexID), mt::Edge> = HashMap::new(); - let mut riser = |a: &mt::Vertex, b: &mt::Vertex| -> mt::Edge { - risers.entry((a.id(), b.id())).or_insert_with(|| mt::Edge::new_unchecked(a, b, mt::Curve::Line(mt::Line(a.point(), b.point())))).clone() - }; - let moved_face = |fi: usize, f: &mt::Face, off: &crate::surface_offset::FaceMover, side: usize, d: f64| -> Result { - let wires: Vec = f - .absolute_boundaries() - .iter() - .map(|w| { - w.edge_iter() - .filter_map(|e| { - let abs_id = if e.orientation() { e.id() } else { e.inverse().id() }; - let m = eof[side].get(&(fi, abs_id))?.clone(); - Some(if e.orientation() { m } else { m.inverse() }) - }) - .collect::>() - .into() - }) - .collect(); - let mut nf = mt::Face::new_unchecked(wires, off.surface(d)?); - if !f.orientation() { - nf.invert(); - } - Ok(nf) - }; - let mut out = Vec::new(); - // History (one operand, the surface): a copy at no distance is the face itself, a copy - // further out its offset, a wall is made along the edge it stands on, a corner patch from - // the sharp edges that meet at its corner. - let operand = crate::record::Operand::new(body); - let edge_index = &operand.edges; - let mut history = Vec::new(); - let copy = |i: usize, d: f64| { - if d == 0.0 { - crate::record::from_face(0, i, Change::Kept) - } else { - crate::record::generated(vec![FaceOrigin::Offset { operand: 0, face: i }]) - } - }; - let edge_origin = |id: &mt::EdgeID| -> Result { - let edge = edge_index.get(id).copied().ok_or_else(|| KernelError::Failed("thicken: an edge outside the surface".into()))?; - Ok(FaceOrigin::Edge { operand: 0, edge }) - }; - for (i, (f, off)) in faces.iter().zip(&offs).enumerate() { - // The lower copy faces back, the upper one forward. - out.push(moved_face(i, f, off, 0, lo)?.inverse()); - out.push(moved_face(i, f, off, 1, hi)?); - history.extend([copy(i, lo), copy(i, hi)]); - // Walls along free edges, outward across the edge. - for w in f.boundaries() { - for e in w.edge_iter() { - let abs_id = if e.orientation() { e.id() } else { e.inverse().id() }; - if users.get(&abs_id).map_or(0, Vec::len) != 1 { - continue; - } - let (Some(le), Some(he)) = (eof[0].get(&(i, abs_id)), eof[1].get(&(i, abs_id))) else { continue }; - let (le, he) = if e.orientation() { (le.clone(), he.clone()) } else { (le.inverse(), he.inverse()) }; - let (sa, sb) = (riser(le.front(), he.front()), riser(le.back(), he.back())); - // A → B low, B → B' up, B' → A' high back, A' → A down. - let wire: mt::Wire = vec![le.clone(), sb, he.inverse(), sa.inverse()].into(); - let ruled = mt::builder::homotopy(&le, &he); - let surf = ruled.surface(); - // The wall's outward normal: across the edge, away from the face. - let c = le.oriented_curve(); - let (t0, t1) = c.range_tuple(); - let tm = 0.5 * (t0 + t1); - let p = c.subs(tm); - let tangent = c.der(tm); - let n = - f.oriented_surface().search_nearest_parameter(p, None, 50).map(|(u, v)| f.oriented_surface().normal(u, v)).unwrap_or(tangent); - let outward = tangent.cross(n); - let sn = surf.search_nearest_parameter(p, None, 50).map(|(u, v)| surf.normal(u, v)).unwrap_or(outward); - let wall = if sn.dot(outward) >= 0.0 { - mt::Face::new_unchecked(vec![wire], surf) - } else { - let mut x = mt::Face::new_unchecked(vec![wire.inverse()], surf); - x.invert(); - x - }; - out.push(wall); - history.push(crate::record::generated(vec![edge_origin(&abs_id)?])); - } - } - } - // Sharp edges: where the two faces' copies of an edge part on a side, a wall closes the - // gap; where they would cross (an inside corner on that side), refused. - let mut sharp_at: HashMap> = HashMap::new(); - let mut gaps = Vec::new(); - for (id, fs) in &users { - let [fa, fb] = fs.as_slice() else { continue }; - let Some(abs) = abs_edges.get(id) else { continue }; - for (side, d) in [lo, hi].into_iter().enumerate() { - let (Some(ea), Some(eb)) = (eof[side].get(&(*fa, *id)), eof[side].get(&(*fb, *id))) else { continue }; - if ea.id() == eb.id() { - continue; - } - // Which way the faces bend across the edge: each lies behind the other's normal - // (convex toward the normals) or in front of it. - let c = abs.curve(); - let (t0, t1) = c.range_tuple(); - let p = from_p3(c.subs(0.5 * (t0 + t1))); - let normal = |fi: usize| -> Option { - let s = faces.get(fi)?.oriented_surface(); - let (u, v) = s.search_nearest_parameter(p3(p), None, 50)?; - Some(from_p3(mt::Point3::new(0.0, 0.0, 0.0) + s.normal(u, v))) - }; - let centre = |fi: usize| -> Option { - let pts: Vec = - faces.get(fi)?.absolute_boundaries().iter().flat_map(|w| w.vertex_iter().map(|v| from_p3(v.point()))).collect(); - Some(pts.iter().fold(Vec3::ZERO, |a, q| a + *q) * (1.0 / pts.len().max(1) as f64)) - }; - let (Some(na), Some(ca), Some(cb)) = (normal(*fa), centre(*fa), centre(*fb)) else { - return Err(KernelError::Failed("thicken: the faces at a sharp edge".into())); - }; - // Convex toward the normals: the other face falls away behind this one's normal. - let convex = na.dot(cb - p) < 0.0 && normal(*fb).is_some_and(|nb| nb.dot(ca - p) < 0.0); - if convex != (d > 0.0) { - return Err(KernelError::Invalid( - "not supported yet: thickening into an inside corner across a sharp edge (try the other side, or symmetric off)".into(), - )); - } - gaps.push((*id, side, ea.clone(), eb.clone())); - for v in [abs.front(), abs.back()] { - let list = sharp_at.entry(v.id()).or_default(); - if !list.contains(id) { - list.push(*id); - } - } - } - } - // Each gap wall runs along one face's copy of the edge and back along the other's, joined - // at the ends by lines between the two copies of each end vertex. It is turned so that it - // crosses the first face's copy the other way from that face. - let mut links: HashMap<(mt::VertexID, mt::VertexID), mt::Edge> = HashMap::new(); - let mut link = |a: &mt::Vertex, b: &mt::Vertex| -> mt::Edge { - if let Some(e) = links.get(&(b.id(), a.id())) { - return e.inverse(); - } - links.entry((a.id(), b.id())).or_insert_with(|| mt::Edge::new_unchecked(a, b, mt::Curve::Line(mt::Line(a.point(), b.point())))).clone() - }; - let used_forward = |faces: &[mt::Face], e: &mt::Edge| -> Option { - faces - .iter() - .flat_map(|f| f.boundaries().into_iter().flat_map(|w| w.edge_iter().cloned().collect::>())) - .find(|x| x.id() == e.id()) - .map(|x| x.front().id() == e.front().id()) - }; - for (id, _side, ea, eb) in gaps { - let wire: mt::Wire = vec![ea.clone(), link(ea.back(), eb.back()), eb.inverse(), link(eb.front(), ea.front())].into(); - let surf = mt::builder::homotopy(&ea, &eb).surface(); - let wall = mt::Face::new_unchecked(vec![wire], surf); - let wall = if used_forward(&out, &ea).unwrap_or(false) { wall.inverse() } else { wall }; - out.push(wall); - history.push(crate::record::generated(vec![edge_origin(&id)?])); - } - // Corners: whatever is left open is closed by plane patches (where three faces meet at a - // sharp corner, a triangle), each from the sharp edges meeting there. - let open = mt::Shell::from(out.clone()).extract_boundaries(); - for w in open { - let patch = mt::builder::try_attach_plane(&[w.inverse()]) - .map_err(|_| KernelError::Invalid("not supported yet: thickening a corner where the gap does not close flat".into()))?; - let mut origins = Vec::new(); - for v in w.vertex_iter() { - for (vid, list) in &sharp_at { - let at = vcopies.iter().flat_map(|m| m.get(vid).into_iter().flatten()).any(|c| c.id() == v.id()); - if at { - for e in list { - let o = edge_origin(e)?; - if !origins.contains(&o) { - origins.push(o); - } - } - } - } - } - if origins.is_empty() { - return Err(KernelError::Failed("the thickened surface does not close".into())); - } - out.push(patch); - history.push(crate::record::generated(origins)); - } - let shell = mt::Shell::from(out); - if shell.shell_condition() != mt::ShellCondition::Closed { - return Err(KernelError::Failed("the thickened surface does not close".into())); - } - // The edges copied at no distance are the surface's own edges, rebuilt. - let mut copies = HashMap::new(); - for (side, d) in [lo, hi].into_iter().enumerate() { - if d != 0.0 { - continue; - } - for (id, list) in &ecopies[side] { - if let Some(&edge) = edge_index.get(id) { - for c in list { - copies.insert(c.id(), EdgeOrigin::Edge { operand: 0, edge }); - } - } - } - } - crate::record::attach(Body::new(mt::Solid::new_unchecked(vec![shell]))?, &[operand], Some(history), copies) - }) + // SMLib holds a sheet's faces with both sides and thickens along their surfaces' natural + // normals; a sheet turned to its back (every face used against its natural normal) grows the + // other way. + let sides = face_sides(body.record()); + let turned = !sides.is_empty() && sides.iter().all(|forward| !forward); + imp::thicken(body, if turned { -thickness } else { thickness }, symmetric) } -/// A planar surface extended: the chosen straight edges (picked by points on them) move -/// outward in the face's plane by `distance`, their neighbours lengthened to meet them. The -/// result's history is over `[body]`: the face and each edge the one it was moved from. +/// The faces `picked` of `body` (indices in its face order) offset one by one by SMLib, each onto +/// its surface's offset by `distance` along its normal, and stitched where their offsets meet +/// within `tolerance` (neighbours meeting smoothly stay joined; across a sharp edge they come +/// apart): see [`crate::offset_surface`]. A distance of zero copies the faces. Each face is the +/// offset of the one it came from. +pub(crate) fn offset_faces(body: &Body, picked: &[usize], distance: f64, tolerance: f64) -> Result { + let r = body.record(); + if distance == 0.0 { + return taken(body, r, &picked.iter().map(|f| (*f, false)).collect::>()); + } + let moved = picked.iter().map(|f| imp::offset_face(r, *f, distance)).collect::>>()?; + let (parts, offsets) = Parts::joined(&moved.iter().collect::>())?; + let c = parts.canonical()?; + let (result, h) = imp::stitched(&c.brep, tolerance.max(c.brep.tolerance))?; + let offset = |k: usize, _: usize| FaceOrigin::Offset { operand: 0, face: picked.get(k).copied().unwrap_or(0) }; + let faces = h + .and_then(|h| carried(&h, &c, &offsets, 1, offset)) + .map(|h| h.faces.into_iter().map(|f| FaceProv { change: Change::Generated, ..f }).collect::>()); + let rec = result.record(); + let h = faces.map(|faces| record_history(rec, 1, faces, |_, between, faces| record::meeting(between, faces))); + Ok(result.with_checked_history(h, &record::counts(&[body]))) +} + +/// A planar surface extended: the chosen straight edges (picked by points on them) move outward in +/// the face's plane by `distance`, their neighbours lengthened to meet them. The result's history +/// is over `[body]`: the face is the body's face rebuilt, each edge the one it was moved from. pub fn extend(body: &Body, at: &[Vec3], distance: f64) -> Result { body.require_brep("extend")?; if !(distance.is_finite() && distance > 0.0) { - return Err(KernelError::Invalid("the extension distance must be positive".into())); + return Err(invalid("the extension distance must be positive")); } - let faces: Vec = body.solid.face_iter().cloned().collect(); - let [face] = faces.as_slice() else { return Err(KernelError::Invalid("not supported yet: extending a surface of more than one face".into())) }; - let Some(crate::splitface::Analytic::Plane { n }) = crate::splitface::analytic_field(&face.oriented_surface()) else { - return Err(KernelError::Invalid("not supported yet: extending a surface that is not planar".into())); + let r = body.record(); + let [face] = r.faces.as_slice() else { return Err(invalid("not supported yet: extending a surface of more than one face")) }; + let (origin, du, dv) = match face.surface { + b::Surface::Plane { origin, u_axis, v_axis } => (v3(origin), v3(u_axis), v3(v_axis)), + b::Surface::PlaneThrough { origin, u_point, v_point } => (v3(origin), v3(u_point) - v3(origin), v3(v_point) - v3(origin)), + _ => return Err(invalid("not supported yet: extending a surface that is not planar")), }; - let chosen: Vec = at + // The outer loop runs counter-clockwise about the surface's natural normal. + let n = du.cross(dv).normalized().ok_or_else(|| invalid("a planar face with no normal"))?; + let [b::Loop::Edges { edges: rim }] = face.loops.as_slice() else { return Err(invalid("not supported yet: extending a surface with holes")) }; + let chosen: Vec = at.iter().map(|p| edge_near(body, *p).ok_or_else(|| invalid(format!("no edge at {p:?}")))).collect::>()?; + let m = rim.len(); + // Each edge as a line (point, direction along the loop), moved outward when chosen. + let mut lines = Vec::with_capacity(m); + for u in rim { + let e = r.edges.get(u.edge as usize).ok_or_else(|| invalid("an edge reference"))?; + let b::Curve::Line { start, end } = e.curve else { return Err(invalid("not supported yet: extending a surface with curved edges")) }; + let at_t = |t: f64| v3(start) + (v3(end) - v3(start)) * t; + let (a, z) = if u.forward { (at_t(e.interval[0]), at_t(e.interval[1])) } else { (at_t(e.interval[1]), at_t(e.interval[0])) }; + let d = (z - a).normalized().ok_or_else(|| invalid("a zero-length edge"))?; + // Outward: right of the edge seen along the normal (the face is on its left). + let shift = if chosen.contains(&(u.edge as usize)) { distance } else { 0.0 }; + lines.push((a + d.cross(n) * shift, d)); + } + // Corners: where consecutive lines meet. + let meet = |(p, d): (Vec3, Vec3), (q, e): (Vec3, Vec3)| -> Option { + let c = d.cross(e); + let cc = c.dot(c); + (cc >= 1e-24).then(|| p + d * ((q - p).cross(e).dot(c) / cc)) + }; + let mut parts = Parts { tolerance: r.tolerance, ..Parts::default() }; + for i in 0..m { + let (Some(prev), Some(cur)) = (lines.get((i + m - 1) % m), lines.get(i)) else { continue }; + parts.vertices.push(b::Vertex { point: a3(meet(*prev, *cur).unwrap_or(cur.0)), tolerance: r.tolerance }); + } + for i in 0..m { + let (Some(a), Some(z)) = (parts.vertices.get(i), parts.vertices.get((i + 1) % m)) else { continue }; + let curve = b::Curve::Line { start: a.point, end: z.point }; + parts.edges.push(b::Edge { + nurbs: None, + curve, + interval: [0.0, 1.0], + vertices: [index(i)?, index((i + 1) % m)?], + tolerance: r.tolerance, + uses: Vec::new(), + }); + } + let uses = parts + .edges .iter() - .map(|p| edge_near(body, *p).map(|e| e.id()).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))) - .collect::>()?; - guard("extend", || { - let bounds = face.boundaries(); - let [outer] = bounds.as_slice() else { return Err(KernelError::Invalid("not supported yet: extending a surface with holes".into())) }; - let edges: Vec = outer.edge_iter().cloned().collect(); - let m = edges.len(); - // Each edge as a line (point, direction) moved outward when chosen. - let mut lines = Vec::with_capacity(m); - for e in &edges { - let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point())); - if !matches!(e.curve(), mt::Curve::Line(_)) { - return Err(KernelError::Invalid("not supported yet: extending a surface with curved edges".into())); - } - let d = (b - a).normalized().ok_or_else(|| KernelError::Invalid("a zero-length edge".into()))?; - // Outward: right of the edge seen along the normal (the face is on its left). - let out = d.cross(n); - let shift = if chosen.contains(&e.id()) || chosen.contains(&e.inverse().id()) { distance } else { 0.0 }; - lines.push((a + out * shift, d)); - } - // Corners: where consecutive lines meet. - let meet = |(p, d): (Vec3, Vec3), (q, e): (Vec3, Vec3)| -> Option { - let w = q - p; - let c = d.cross(e); - let cc = c.dot(c); - if cc < 1e-24 { - return None; - } - Some(p + d * (w.cross(e).dot(c) / cc)) - }; - let mut corners = Vec::with_capacity(m); - for i in 0..m { - let (Some(prev), Some(cur)) = (lines.get((i + m - 1) % m), lines.get(i)) else { continue }; - let p = meet(*prev, *cur).unwrap_or(cur.0); - corners.push(mt::Vertex::new(p3(p))); - } - let mut rec = Rebuild::default(); - let wire: mt::Wire = (0..m) - .filter_map(|i| { - let (a, b, old) = (corners.get(i)?, corners.get((i + 1) % m)?, edges.get(i)?); - let e = mt::Edge::new_unchecked(a, b, mt::Curve::Line(mt::Line(a.point(), b.point()))); - rec.piece(&e, old); - Some(e) + .enumerate() + .map(|(i, e)| { + Ok(solidcraft_geom::brep::pcurve::EdgeUse { + edge: index(i)?, + curve: e.parameters(), + interval: e.interval, + forward: true, + tolerance: e.tolerance, + given: None, }) - .collect::>() - .into(); - let mut f = mt::builder::try_attach_plane(&[wire]).map_err(|e| KernelError::Failed(format!("extend: {e}")))?; - if f.oriented_surface().normal(0.0, 0.0).dot(crate::body::v3(n)) < 0.0 { - f = f.inverse(); + }) + .collect::>>()?; + let surface = b::Surface::Plane { origin: a3(origin), u_axis: a3(du), v_axis: a3(dv) }; + let pcurves = solidcraft_geom::brep::pcurve::pcurves(&surface, &[uses], r.tolerance).map_err(|e| failed(format!("extend: {e}")))?; + let edges = pcurves + .into_iter() + .flatten() + .enumerate() + .map(|(i, pcurve)| Ok(b::OrientedEdge { edge: index(i)?, forward: true, pcurve })) + .collect::>>()?; + let loops = vec![b::Loop::Edges { edges }]; + let domain = uv_box(&loops).ok_or_else(|| invalid("the extended face has no area"))?; + let forward = face_sides(r).first().copied().unwrap_or(true); + parts.faces.push((b::Face { nurbs: None, surface, domain, loops }, forward)); + let c = parts.canonical()?; + let h = record_history(&c.brep, 1, vec![record::from_face(0, 0, Change::Modified)], |e, _, _| { + c.edges.get(e).and_then(|p| rim.get(*p)).map(|u| EdgeOrigin::Edge { operand: 0, edge: u.edge as usize }).into_iter().collect() + }); + let (result, same) = record_body(&c.brep)?; + with_history(result, same, h, &record::counts(&[body])) +} + +// ---- Sheets swept from sketch curves ------------------------------------------------------ + +/// Most curve chains one surface sweep takes. +const MAX_CHAINS: usize = 10_000; + +/// A sketch segment with its number across all the chains (chain after chain). +type Numbered = (Seg2, usize); + +/// The chains' segments, numbered on across the chains. +fn numbered(chains: &[Vec]) -> Vec> { + let mut next = 0; + chains + .iter() + .map(|c| { + c.iter() + .map(|s| { + next += 1; + (*s, next - 1) + }) + .collect() + }) + .collect() +} + +fn check_chains(chains: &[Vec], what: &str) -> Result<()> { + if chains.is_empty() || chains.len() > MAX_CHAINS { + return Err(invalid(format!("pick the curves or profiles to {what}"))); + } + for c in chains { + if c.is_empty() || c.len() > 4096 { + return Err(invalid("a curve chain has no curves, or too many")); } - rec.face(&f, face); - Ok(rebuilt_body(surface_body(vec![f]), &[&body.solid], &rec)) - }) + if c.iter().any(|s| !(s.start().is_finite() && s.end().is_finite())) { + return Err(invalid("a curve chain is not finite")); + } + if c.windows(2).any(|w| w[0].end().dist(w[1].start()) > 1e-6) { + return Err(invalid("a curve chain has a gap: its curves must run end to end")); + } + } + Ok(()) +} + +/// The faces of the sheet `r` swept from `pieces` that start on `start`: each face comes from the +/// pieces its edges lying in `start` run along (the edges' middles on the pieces' curves), none +/// where no edge does. +fn swept_from(r: &Brep, start: &Plane, pieces: &[Numbered]) -> Vec { + let mut from: Vec> = vec![BTreeSet::new(); r.faces.len()]; + for e in &r.edges { + let Some(mid) = CurveEval::new(e.parameters()).ok().and_then(|c| c.point(0.5 * (e.interval[0] + e.interval[1]))) else { continue }; + let near = 4.0 * e.tolerance.max(r.tolerance); + if start.height(mid).abs() > near { + continue; + } + let o = mid - start.origin; + let q = Vec2::new(o.dot(start.x), o.dot(start.y)); + for (s, number) in pieces { + if s.point_at(s.closest_param(q)).dist(q) <= near { + for u in &e.uses { + if let Some(set) = from.get_mut(u.face as usize) { + set.insert(*number); + } + } + } + } + } + from.iter().map(|set| if set.is_empty() { record::generated(Vec::new()) } else { record::profile(set.iter()) }).collect() +} + +/// A sheet of SMLib's pieces (each a record with its faces' history), joined into one record and, +/// with `stitch`, sewn where pieces share edges (at ten times the pieces' tolerance). +pub(crate) fn sheet_of(pieces: Vec<(Brep, Vec)>, stitch: bool, operands: &[&Body]) -> Result { + let counts = record::counts(operands); + let records: Vec<&Brep> = pieces.iter().map(|(r, _)| r).collect(); + let (parts, offsets) = Parts::joined(&records)?; + let c = parts.canonical()?; + let prov = |part: usize| owner(&offsets, part, 0).and_then(|(k, i)| pieces.get(k)?.1.get(i).cloned()); + let faces: Option> = c.faces.iter().map(|p| prov(*p)).collect(); + if !stitch { + let (body, same) = record_body(&c.brep)?; + return Ok(record::attach(body, &counts, faces.filter(|_| same), &[])); + } + let (body, h) = imp::stitched(&c.brep, c.brep.tolerance * 10.0)?; + // A stitched face keeps the tag of the joined record's face it was. + let sewn = h.zip(faces).and_then(|(h, faces)| { + h.faces + .iter() + .map(|f| match f.origins.as_slice() { + [FaceOrigin::Face { face, .. }] => faces.get(*face).cloned(), + _ => None, + }) + .collect::>>() + }); + Ok(record::attach(body, &counts, sewn, &[])) +} + +/// A surface extruded from chains of sketch segments on `plane`: each chain (open, or closed such +/// as a profile's boundary) moved straight from `start` to `end` along the plane normal (offsets in +/// mm). The walls it sweeps form one surface body with no caps. Its history has no operands: +/// every face is new, from the segments it was swept from. +pub fn extrude_sheet(plane: &Plane, chains: &[Vec], start: f64, end: f64) -> Result { + if !crate::build::frame_ok(plane) { + return Err(invalid("extrude frame is not finite and orthonormal")); + } + if !(start.is_finite() && end.is_finite() && start.abs() < 1e7 && end.abs() < 1e7) { + return Err(invalid("extrude distance is not finite")); + } + let (lo, hi) = if end >= start { (start, end) } else { (end, start) }; + if hi - lo < 1e-6 { + return Err(invalid("extrude distance is zero")); + } + check_chains(chains, "extrude")?; + let base = plane.offset(lo); + let n = plane.normal().normalized().ok_or_else(|| invalid("extrude frame has no normal"))?; + let pieces = numbered(chains) + .into_iter() + .map(|chain| { + let r = imp::extruded(&base, &chain, n, hi - lo)?; + let h = swept_from(&r, &base, &chain); + Ok((r, h)) + }) + .collect::>>()?; + sheet_of(pieces, false, &[]) +} + +/// The sheet SMLib revolves from the sketch segments `segs` on `plane` about the axis through +/// `origin` along the unit `axis` (in the plane) by `angle` radians (right-handed, up to a turn), +/// with no caps, as its record: a surface builder's sector. +pub(crate) fn revolved_record(plane: &Plane, segs: &[Seg2], origin: Vec3, axis: Vec3, angle: f64) -> Result { + let chain: Vec = segs.iter().copied().zip(0..).collect(); + imp::revolved(plane, &chain, origin, axis, angle) +} + +/// A surface revolved from chains of sketch segments on `plane` about the sketch line through +/// `axis_origin` along `axis_dir`: each chain turned from `start` through `sweep` radians (a full +/// turn at most), positive angles carrying it toward the sketch normal. A chain end on the axis +/// stays put there (a cone's apex, a sphere's pole). The walls form one surface body with no caps, +/// or a solid where they close (a full turn of a closed curve, or of a curve from the axis back to +/// it); its history has no operands: every face is new. +pub fn revolve_sheet(plane: &Plane, chains: &[Vec], axis_origin: Vec2, axis_dir: Vec2, start: f64, sweep: f64) -> Result { + use std::f64::consts::TAU; + if !crate::build::frame_ok(plane) || !axis_origin.is_finite() || !axis_dir.is_finite() { + return Err(invalid("revolve frame is not finite and orthonormal")); + } + if !(start.is_finite() && sweep.is_finite() && start.abs() <= TAU && sweep.abs() <= TAU + 1e-9) { + return Err(invalid("revolve angles must be finite, a full turn at most")); + } + if sweep.abs() < 1e-6 { + return Err(invalid("revolve angle is zero")); + } + check_chains(chains, "revolve")?; + let d = axis_dir.normalized().ok_or_else(|| invalid("revolve axis has no direction"))?; + let side = |p: Vec2| d.cross(p - axis_origin); + let on_axis = |p: Vec2| side(p).abs() < 1e-7; + let (origin, n) = (plane.to_world(axis_origin), plane.normal()); + let axis = plane.dir_to_world(d).normalized().ok_or_else(|| invalid("revolve frame has no axis"))?; + let mut pieces = Vec::with_capacity(chains.len()); + for chain in numbered(chains) { + // On one side of the axis; the point farthest from it fixes the turning sense. + let pts: Vec = chain.iter().flat_map(|(s, _)| s.polyline(1e-3)).collect(); + if pts.iter().any(|p| side(*p) < -1e-7) && pts.iter().any(|p| side(*p) > 1e-7) { + return Err(invalid("the curves cross the revolve axis")); + } + let far = pts.iter().copied().max_by(|a, c| side(*a).abs().total_cmp(&side(*c).abs())).filter(|p| !on_axis(*p)); + let Some(far) = far else { return Err(invalid("the curves lie on the revolve axis")) }; + let a = if axis.cross(plane.to_world(far) - origin).dot(n) < 0.0 { axis * -1.0 } else { axis }; + let (Some((first, _)), Some((last, _))) = (chain.first(), chain.last()) else { return Err(invalid("an empty curve chain")) }; + if first.start().dist(last.end()) <= 1e-6 && pts.iter().any(|p| on_axis(*p)) { + return Err(invalid("not supported yet: a closed curve touching the revolve axis")); + } + // The chain starts `start` round: its sketch frame turned there. + let turn = |v: Vec3| crate::build::rotate_about(v, Vec3::ZERO, a, start); + let turned = Plane { origin: crate::build::rotate_about(plane.origin, origin, a, start), x: turn(plane.x), y: turn(plane.y) }; + let (k, angle) = if sweep < 0.0 { (a * -1.0, -sweep) } else { (a, sweep) }; + let r = imp::revolved(&turned, &chain, origin, k, angle.min(TAU))?; + let h = swept_from(&r, &turned, &chain); + pieces.push((r, h)); + } + sheet_of(pieces, false, &[]) +} + +/// A surface swept from chains of sketch segments on `plane` along a path that starts near them, +/// turning with it (SMLib's curve sweep: along lines an extrusion, round arcs about one axis a +/// revolution, exactly); at a corner the walls meet in a mitre, as the solid sweep's do. The +/// walls form one surface body with no caps; its history has no operands: every face is new. +pub fn sweep_sheet(plane: &Plane, chains: &[Vec], path: &[crate::PathSeg]) -> Result { + sweep_sheet_with(plane, chains, path, &crate::SweepControl::default()) +} + +/// [`sweep_sheet`] with sweep options: orientation, twist, end scale and guide rails place the +/// chains at stations along the path by [`crate::sweep_path`]'s laws (each section the chain's +/// exact image) for SMLib to skin the walls through. +pub fn sweep_sheet_with(plane: &Plane, chains: &[Vec], path: &[crate::PathSeg], ctl: &crate::SweepControl) -> Result { + ctl.check()?; + if !crate::build::frame_ok(plane) { + return Err(invalid("sweep frame is not finite and orthonormal")); + } + check_chains(chains, "sweep")?; + if path.is_empty() || path.len() > 1000 { + return Err(invalid("the path needs 1…1000 segments")); + } + let runs = smooth_runs(path)?; + let controlled = ctl.varies() || matches!(ctl.orientation, crate::SweepOrientation::Direction(_)); + if controlled && runs.len() > 1 { + return Err(imp::refuse("sweep with a twist, an end scale, guide rails or an orientation direction along a path with corners")); + } + let translate = ctl.orientation == crate::SweepOrientation::Parallel; + let mut pieces = Vec::with_capacity(chains.len()); + for chain in numbered(chains) { + if runs.len() > 1 { + pieces.extend(imp::cornered(plane, &chain, path, &runs, translate)?); + continue; + } + let r = if controlled { imp::swept_stations(plane, &chain, path, ctl)? } else { imp::swept(plane, &chain, path, translate)? }; + let h = swept_from(&r, plane, &chain); + pieces.push((r, h)); + } + sheet_of(pieces, runs.len() > 1, &[]) +} + +/// The path's segments in runs along which its direction carries on (within a thousandth of a +/// radian across each joint): a new run starts at each corner. +fn smooth_runs(path: &[crate::PathSeg]) -> Result>> { + let ends: Vec<(Vec3, Vec3)> = + path.iter().map(crate::PathSeg::tangents).collect::>().ok_or_else(|| invalid("a path segment has no direction"))?; + let mut runs = Vec::new(); + let mut from = 0; + for (i, w) in ends.windows(2).enumerate() { + if w[0].1.dot(w[1].0) < (1e-3f64).cos() { + runs.push(from..i + 1); + from = i + 1; + } + } + runs.push(from..path.len()); + Ok(runs) +} + +/// A surface swept from chains of sketch segments on `plane` along a 3D polyline path: along the +/// lines between its points, as [`sweep_sheet`] sweeps them. +pub fn sweep_sheet_points(plane: &Plane, chains: &[Vec], path: &[Vec3]) -> Result { + sweep_sheet_points_with(plane, chains, path, &crate::SweepControl::default()) +} + +/// [`sweep_sheet_points`] with sweep options (see [`sweep_sheet_with`]). +pub fn sweep_sheet_points_with(plane: &Plane, chains: &[Vec], path: &[Vec3], ctl: &crate::SweepControl) -> Result { + let pts = crate::sweep_path::clean(path)?; + let segs: Vec = pts.windows(2).map(|w| crate::PathSeg::Line { a: w[0], b: w[1] }).collect(); + sweep_sheet_with(plane, chains, &segs, ctl) +} + +/// A surface lofted through two or more sections, each a chain of sketch segments on its plane, +/// all open or all closed: ruled between two sections, smooth through three or more. Closed +/// sections are matched as the solid loft matches them; open ones are split to the same number of +/// segments (longest first) and each turned to run the way the one before it does. Walls only, no +/// caps; the history has no operands: every face is new. +pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { + loft_sheet_with_rails(sections, &[], crate::RailFit::Scale) +} + +/// [`loft_sheet`] following one or two guide rails (polylines from the first section to the last, +/// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the +/// sections between. Without rails, the plain sheet loft. +/// +/// The k-th segments of every section make a column: SMLib lofts each column on its own (one wall +/// from the column's segments), and the columns are stitched along the edges they share. +pub fn loft_sheet_with_rails(sections: &[(Plane, Vec)], rails: &[Vec], fit: crate::RailFit) -> Result { + if sections.len() < 2 || sections.len() > 50 { + return Err(invalid("a loft needs 2…50 sections")); + } + let closed: Vec = sections + .iter() + .map(|(_, c)| match (c.first(), c.last()) { + (Some(f), Some(l)) if c.len() <= 4096 => Ok(l.end().dist(f.start()) <= 1e-6), + _ => Err(invalid("a loft section has no curves, or too many")), + }) + .collect::>()?; + let all_closed = closed.iter().all(|c| *c); + if !all_closed && closed.iter().any(|c| *c) { + return Err(invalid("the loft sections must be all open or all closed")); + } + for (plane, chain) in sections { + if !crate::build::frame_ok(plane) { + return Err(invalid("a loft section's frame is not finite and orthonormal")); + } + check_chains(std::slice::from_ref(chain), "loft")?; + } + let matched = if all_closed { closed_sections(sections)? } else { open_sections(sections)? }; + let lofted = crate::loft_rails::railed(&matched, all_closed, rails, fit)?; + let count = matched.first().map_or(0, |s| s.curves.len()); + let pieces = (0..count) + .map(|k| { + let column: Vec<&solidcraft_geom::bspline::CurveN<4>> = lofted.iter().filter_map(|s| s.get(k)).collect(); + let r = imp::lofted(&column)?; + let numbers: BTreeSet = matched.iter().filter_map(|s| s.numbers.get(k)).flatten().copied().collect(); + let h = vec![record::profile(numbers.iter()); r.faces.len()]; + Ok((r, h)) + }) + .collect::>>()?; + sheet_of(pieces, true, &[]) +} + +/// Closed sections matched as the solid loft matches them ([`crate::build::loft_numbered_loops`]), +/// in loft order. +fn closed_sections(sections: &[(Plane, Vec)]) -> Result> { + let loops: Vec<(Plane, solidcore_record::Loop2)> = sections.iter().map(|(p, c)| (*p, solidcore_record::Loop2 { segs: c.clone() })).collect(); + let reversed = crate::build::loft_reversed(&loops)?; + let numbered = loops.iter().map(|(p, _)| *p).zip(crate::numbered::number_loops(loops.iter().map(|(_, l)| l))).collect::>(); + crate::build::loft_numbered_loops(&numbered, reversed)? + .iter() + .map(|(plane, l)| crate::loft_rails::Section::of(plane, &l.lp.segs, (0..l.lp.segs.len()).map(|i| l.numbers(i).to_vec()).collect())) + .collect() +} + +/// Open sections split to the same number of segments (the longest in half until the counts +/// match), each turned to run the way the one before it does. +fn open_sections(sections: &[(Plane, Vec)]) -> Result> { + let n = sections.iter().map(|(_, c)| c.len()).max().unwrap_or(0); + let mut out = Vec::with_capacity(sections.len()); + let mut prev: Option<(Vec3, Vec3)> = None; + let mut offset = 0; + for (plane, chain) in sections { + // Each piece with the segment it is (part of). + let mut segs: Vec<(Seg2, usize)> = chain.iter().enumerate().map(|(i, s)| (*s, offset + i)).collect(); + offset += chain.len(); + while segs.len() < n { + let Some(i) = segs.iter().enumerate().max_by(|a, c| a.1.0.length().total_cmp(&c.1.0.length())).map(|(i, _)| i) else { break }; + let Some(&(s, k)) = segs.get(i) else { break }; + let (a, c) = s.split_half(); + segs.splice(i..=i, [(a, k), (c, k)]); + } + let ends = |c: &[(Seg2, usize)]| c.first().zip(c.last()).map(|(f, l)| (plane.to_world(f.0.start()), plane.to_world(l.0.end()))); + if let (Some((ps, pe)), Some((s, e))) = (prev, ends(&segs)) + && s.dist(ps) + e.dist(pe) > s.dist(pe) + e.dist(ps) + { + segs = segs.iter().rev().map(|(s, k)| (s.reversed(), *k)).collect(); + } + prev = ends(&segs); + let pieces: Vec = segs.iter().map(|(s, _)| *s).collect(); + out.push(crate::loft_rails::Section::of(plane, &pieces, segs.iter().map(|(_, k)| vec![*k]).collect())?); + } + Ok(out) +} + +/// SMLib's side of this module. +mod imp { + use solidcraft_smlib::sweeps::{Affine, Curve, Ends, SweepFrame}; + use solidcraft_smlib::{Brep as SmBrep, CheckLevel}; + + use super::*; + + fn sm(what: &'static str) -> impl Fn(solidcraft_smlib::Error) -> KernelError { + move |e| KernelError::smlib(format!("SMLib {what}"), e) + } + + pub(super) fn refuse(what: &str) -> KernelError { + crate::smlib_sweeps::refuse(what) + } + + /// A result SMLib's own check accepts, as its record. + fn checked(r: &SmBrep, what: &'static str) -> Result { + let check = r.check(CheckLevel::All).map_err(sm(what))?; + if !check.is_valid() { + return Err(failed(format!("SMLib {what}: SMLib's check refuses the result: {check}"))); + } + r.to_native().map_err(|e| failed(format!("SMLib {what}: {e}"))) + } + + /// Whether two records of one body number its faces, edges and vertices alike: the same + /// loops of the same edges, run the same ways, and each edge between the same vertices. + fn same_numbering(a: &Brep, b: &Brep) -> bool { + let loops = |f: &b::Face| -> Vec> { + f.loops + .iter() + .map(|l| match l { + b::Loop::Edges { edges } => edges.iter().map(|u| (u.edge, u.forward)).collect(), + b::Loop::Vertex { vertex } => vec![(*vertex, true)], + }) + .collect() + }; + a.faces.len() == b.faces.len() + && a.edges.len() == b.edges.len() + && a.vertices.len() == b.vertices.len() + && a.faces.iter().zip(&b.faces).all(|(x, y)| loops(x) == loops(y)) + && a.edges.iter().zip(&b.edges).all(|(x, y)| x.vertices == y.vertices) + } + + /// The record `r` sewn by SMLib at `tol` (`smlib_stitch`), with its history over `[r]` (faces + /// and edges by their index in `r`); none where SMLib's import of `r` does not number it as + /// `r` does. + pub(super) fn stitched(r: &Brep, tol: f64) -> Result<(Body, Option)> { + stitched_with(r, tol, |_, sewn| checked(sewn, "stitch").map(|_| ())) + } + + /// [`stitched`], taking a result whose check fails no more tests outside `exempt` than the + /// input's does. + pub(super) fn stitched_no_worse(r: &Brep, tol: f64, exempt: &[u32]) -> Result<(Body, Option)> { + stitched_with(r, tol, |input, sewn| { + let counted = |b: &SmBrep| -> Result { + let report = b.check(CheckLevel::All).map_err(sm("stitch"))?; + Ok(report.failed_tests().into_iter().filter(|t| !exempt.contains(t)).count()) + }; + let (was, now) = (counted(input)?, counted(sewn)?); + if now > was { + let check = sewn.check(CheckLevel::All).map_err(sm("stitch"))?; + return Err(failed(format!("SMLib stitch: SMLib's check finds the sewn part worse ({now} failed tests, {was} before): {check}"))); + } + Ok(()) + }) + } + + /// The record `r` sewn at `tol`, the result taken when `accept` (given SMLib's input and + /// result) does. + fn stitched_with(r: &Brep, tol: f64, accept: impl Fn(&SmBrep, &SmBrep) -> Result<()>) -> Result<(Body, Option)> { + let brep = SmBrep::from_record(r, true).map_err(sm("stitch"))?; + let (back, order) = brep.to_native_ordered().map_err(|e| failed(format!("SMLib stitch: {e}")))?; + let tagged = brep.tagged(0).map_err(sm("stitch"))?; + let (sewn, _closed) = tagged.stitch(tol).map_err(sm("stitch"))?; + accept(&brep, &sewn)?; + let (record, kept) = sewn.to_native_ordered().map_err(|e| failed(format!("SMLib stitch: {e}")))?; + let h = if same_numbering(r, &back) { sewn.history().ok().and_then(|raw| raw.history(&[order], &kept).ok()) } else { None }; + Ok((Body::from_smlib_record(record)?, h)) + } + + pub(super) fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result { + crate::offset_backend::thicken(body, thickness, symmetric) + } + + /// The face `f` of `r` alone, offset by `d` along its normal (`smlib_offset_sheet`). + pub(super) fn offset_face(r: &Brep, f: usize, d: f64) -> Result { + let one = Parts::of(r, &[(f, false)])?.canonical()?; + let sheet = SmBrep::from_record(&one.brep, true).map_err(sm("offset"))?; + checked(&sheet.offset_sheet(d).map_err(sm("offset"))?, "offset") + } + + fn curves(plane: &Plane, chain: &[Numbered]) -> Result> { + chain.iter().map(|(s, _)| crate::smlib_sweeps::curve(plane, s)).collect() + } + + pub(super) fn extruded(base: &Plane, chain: &[Numbered], n: Vec3, distance: f64) -> Result { + checked( + &SmBrep::extrude(&curves(base, chain)?, a3(n), distance, 0.0, solidcraft_smlib::sweeps::DraftCorner::default(), false) + .map_err(sm("surface extrude"))?, + "surface extrude", + ) + } + + pub(super) fn revolved(plane: &Plane, chain: &[Numbered], origin: Vec3, axis: Vec3, angle: f64) -> Result { + checked(&SmBrep::revolve(&curves(plane, chain)?, a3(origin), a3(axis), angle, false).map_err(sm("surface revolve"))?, "surface revolve") + } + + fn route(path: &[crate::PathSeg]) -> Result> { + path.iter().map(crate::smlib_sweeps::path_curve).collect() + } + + fn frame(translate: bool) -> SweepFrame { + if translate { SweepFrame::Translate } else { SweepFrame::Follow } + } + + /// The chain swept along the smooth `path`, turning with it, or only moving along it when + /// `translate`. + pub(super) fn swept(plane: &Plane, chain: &[Numbered], path: &[crate::PathSeg], translate: bool) -> Result { + checked(&SmBrep::sweep(&curves(plane, chain)?, &route(path)?, frame(translate), false).map_err(sm("surface sweep"))?, "surface sweep") + } + + /// `q` moved by the motion `a`. + fn apply(a: &Affine, q: Vec3) -> Vec3 { + let col = |i: usize| a.m.get(i).map_or(Vec3::ZERO, |c| v3(*c)); + col(0) * q.x + col(1) * q.y + col(2) * q.z + v3(a.t) + } + + /// `pl` carried by the rigid motion `a`. + fn placed(pl: &Plane, a: &Affine) -> Plane { + let o = apply(a, Vec3::ZERO); + Plane { origin: apply(a, pl.origin), x: apply(a, pl.x) - o, y: apply(a, pl.y) - o } + } + + /// The bisector of a corner from direction `t1` to `t2` (unit, the way the path runs) and the + /// turn there; a corner that turns the path back on itself is refused. + fn mitre(t1: Vec3, t2: Vec3) -> Result<(Vec3, f64)> { + let turn = t1.dot(t2).clamp(-1.0, 1.0).acos(); + if turn > std::f64::consts::PI - 1e-3 { + return Err(invalid("the path turns back on itself at a corner")); + } + Ok(((t1 + t2).normalized().ok_or_else(|| invalid("path corner"))?, turn)) + } + + /// A tool of square planar faces, one in each plane `cuts` (a point and its normal), `size` + /// across: what a run is imprinted with at its corners. + fn cutting_planes(cuts: &[(Vec3, Vec3)], size: f64) -> Result { + let mut parts = Parts { tolerance: (size * 1e-9).max(1e-6), ..Parts::default() }; + let h = size * 0.5; + let square = [Vec2::new(-h, -h), Vec2::new(h, -h), Vec2::new(h, h), Vec2::new(-h, h)]; + let segs: Vec = (0..4).map(|i| Seg2::Line { a: square[i], b: square[(i + 1) % 4] }).collect(); + for &(at, n) in cuts { + let u = n.cross(if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).normalized().ok_or_else(|| invalid("mitre plane"))?; + let pl = Plane { origin: at, x: u, y: n.cross(u) }; + let lp = sketch_loop(&mut parts, &pl, &segs)?; + let domain = uv_box(std::slice::from_ref(&lp)).ok_or_else(|| invalid("mitre plane"))?; + parts.faces.push((b::Face { nurbs: None, surface: crate::freeform::plane_surface(&pl), domain, loops: vec![lp] }, true)); + } + SmBrep::from_record(&parts.canonical()?.brep, true).map_err(sm("sweep mitre")) + } + + /// The faces of `sheet` (a run's walls, each from what `prov` says, in its record's order) + /// imprinted with `cuts` and kept where every cut's `keep` holds of a point inside them: the + /// piece between a run's mitres, each face from what its uncut face came from. + fn cut_back(sheet: &SmBrep, prov: &[FaceProv], cuts: &[(Vec3, Vec3)], size: f64) -> Result<(Brep, Vec)> { + let (_, order) = sheet.to_native_ordered().map_err(|e| failed(format!("SMLib sweep mitre: {e}")))?; + let tagged = sheet.tagged(0).map_err(sm("sweep mitre"))?; + let Some(cut) = tagged.imprint(&cutting_planes(cuts, size)?).map_err(sm("sweep mitre"))? else { + return Ok((checked(sheet, "sweep mitre")?, prov.to_vec())); + }; + let (record, kept_order) = cut.to_native_ordered().map_err(|e| failed(format!("SMLib sweep mitre: {e}")))?; + let h = cut.history().map_err(sm("sweep mitre"))?.history(&[order], &kept_order).map_err(|e| failed(format!("SMLib sweep mitre: {e}")))?; + // A point inside each face, from SMLib's face order to the record's. + let points = cut.face_points().map_err(sm("sweep mitre"))?; + let mut inside = vec![Vec3::ZERO; record.faces.len()]; + for (i, p) in points.iter().enumerate() { + let k = if kept_order.faces.is_empty() { i } else { kept_order.faces.get(i).copied().unwrap_or(i) }; + if let Some(slot) = inside.get_mut(k) { + *slot = v3(*p); + } + } + let keep: Vec<(usize, bool)> = (0..record.faces.len()) + .filter(|f| inside.get(*f).is_some_and(|p| cuts.iter().all(|(at, n)| (*p - *at).dot(*n) < 0.0))) + .map(|f| (f, false)) + .collect(); + let c = Parts::of(&record, &keep)?.canonical()?; + let faces = c + .faces + .iter() + .map(|p| { + let f = keep.get(*p).map_or(0, |(f, _)| *f); + match h.faces.get(f).map(|x| x.origins.as_slice()) { + Some([FaceOrigin::Face { face, .. }]) => prov.get(*face).cloned().unwrap_or_else(|| record::generated(Vec::new())), + _ => record::generated(Vec::new()), + } + }) + .collect(); + Ok((c.brep, faces)) + } + + /// A sheet swept along a path with corners, by the solid sweep's corner model with open ends: + /// each smooth run swept on its own, turning with the path, carried on straight past each + /// corner (by the profile's reach times the tangent of half the turn, and a little more) and + /// cut back to the plane halving the corner, where the next run, cut back the same way, meets + /// it; the profile turns at a corner about the line square to both directions. Each run's + /// walls come from the segments they are swept from, found where the run starts; the runs are + /// stitched by the caller. Only moving along the path (`translate`), the profile is the same at + /// a corner in both runs, which meet there as they are. + pub(super) fn cornered( + plane: &Plane, + chain: &[Numbered], + path: &[crate::PathSeg], + runs: &[std::ops::Range], + translate: bool, + ) -> Result)>> { + let bad = || invalid("a path segment has no direction"); + let start = path.first().map(crate::PathSeg::start).ok_or_else(|| invalid("empty path"))?; + let end = path.last().map(crate::PathSeg::end).ok_or_else(|| invalid("empty path"))?; + let reach = chain + .iter() + .flat_map(|(s, _)| (0..=8).map(move |i| s.point_at(f64::from(i) / 8.0))) + .map(|q| plane.to_world(q).dist(start)) + .fold(0.0f64, f64::max); + let size = 4.0 * (path.iter().map(length).sum::() + reach) + 1.0; + let (first_t, _) = path.first().and_then(crate::PathSeg::tangents).ok_or_else(bad)?; + let (_, last_t) = path.last().and_then(crate::PathSeg::tangents).ok_or_else(bad)?; + // A closed path ends where it starts; at a corner there the last run meets the first in a + // mitre too. + let closing = (end.dist(start) <= 1e-6 && last_t.dot(first_t) < (1e-3f64).cos()).then_some(first_t); + let over = |turn: f64| if translate { 0.0 } else { reach * (turn * 0.5).tan() * 1.1 + reach * 1e-3 + 1e-6 }; + let mut pose = *plane; + // The mitre the next run starts from: its point, its normal (along the run) and the turn. + let mut entry = closing.filter(|_| !translate).map(|t| mitre(last_t, t).map(|(m, turn)| (start, m, turn))).transpose()?; + let mut pieces = Vec::with_capacity(runs.len()); + for (ri, run) in runs.iter().enumerate() { + let segs = path.get(run.clone()).ok_or_else(|| invalid("path run"))?; + let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err(invalid("path run")) }; + let ((t0, _), (_, t1)) = (first.tangents().ok_or_else(bad)?, last.tangents().ok_or_else(bad)?); + let (a0, b1) = (first.start(), last.end()); + let next = match runs.get(ri + 1).and_then(|r| path.get(r.start)) { + Some(s) => Some(s.tangents().ok_or_else(bad)?.0), + None => closing, + }; + let exit = next.filter(|_| !translate).map(|t2| mitre(t1, t2)).transpose()?; + let pre = entry.map_or(0.0, |(_, _, turn)| over(turn)); + let post = exit.map_or(0.0, |(_, turn)| over(turn)); + let mut along = Vec::with_capacity(segs.len() + 2); + if pre > 0.0 { + along.push(crate::PathSeg::Line { a: a0 - t0 * pre, b: a0 }); + } + along.extend_from_slice(segs); + if post > 0.0 { + along.push(crate::PathSeg::Line { a: b1, b: b1 + t1 * post }); + } + let from = Plane { origin: pose.origin - t0 * pre, ..pose }; + let (sheet, [_, _, at_last]) = + SmBrep::sweep_placed(&curves(&from, chain)?, &route(&along)?, frame(translate), false).map_err(sm("surface sweep"))?; + let prov = swept_from(&sheet.to_native().map_err(|e| failed(format!("SMLib surface sweep: {e}")))?, &from, chain); + // Kept: after the entry mitre, before the exit one. + let cuts: Vec<(Vec3, Vec3)> = entry.map(|(at, m, _)| (at, m * -1.0)).into_iter().chain(exit.map(|(m, _)| (b1, m))).collect(); + pieces.push(cut_back(&sheet, &prov, &cuts, size)?); + // The profile at the run's end, turned through the corner onto the next run. + let at_end = placed(&from, &at_last); + pose = Plane { origin: at_end.origin - t1 * post, ..at_end }; + entry = None; + if let (Some(t2), Some((m, turn))) = (next, exit) { + let k = t1.cross(t2).normalized().ok_or_else(|| invalid("path corner"))?; + let turn_v = |v: Vec3| crate::build::rotate_about(v, Vec3::ZERO, k, turn); + pose = Plane { origin: crate::build::rotate_about(pose.origin, b1, k, turn), x: turn_v(pose.x), y: turn_v(pose.y) }; + entry = Some((b1, m, turn)); + } + } + Ok(pieces) + } + + /// Fewest and most stations of a sweep that twists, scales or follows rails. + const MIN_STATIONS: usize = 16; + const MAX_STATIONS: usize = 2048; + + /// The chain carried through stations along `path` placed by [`crate::sweep_path`]'s laws for + /// `ctl` (a station per degree the path and the twist turn), SMLib skinning its walls through + /// the sections with open ends (`smlib_sweep_stations`). + pub(super) fn swept_stations(plane: &Plane, chain: &[Numbered], path: &[crate::PathSeg], ctl: &crate::SweepControl) -> Result { + let turn: f64 = path.iter().map(turn_of).sum::() + ctl.twist.abs(); + let rail_points = ctl.rails.iter().map(Vec::len).max().unwrap_or(0); + let n = ((turn / 1f64.to_radians()).ceil() as usize).max(rail_points.saturating_sub(1)).clamp(MIN_STATIONS, MAX_STATIONS); + let (pts, tangents) = samples(path, n)?; + let st = crate::sweep_path::controlled_stations(plane, &pts, &tangents, &[], ctl)?; + let s0 = st.first().map(|s| s.at).ok_or_else(|| invalid("sweep path"))?; + let maps: Vec = st + .iter() + .map(|s| { + let [a, b, c] = s.m; + Affine { m: [a3(a), a3(b), a3(c)], t: a3(s.at - s.apply(s0)) } + }) + .collect(); + checked(&SmBrep::sweep_stations(&curves(plane, chain)?, &maps, Ends::Open).map_err(sm("surface sweep"))?, "surface sweep") + } + + /// Samples of a segment's parameter its turn and length are read from. + const TURN_SAMPLES: usize = 64; + + /// How far a path segment turns (radians): its tangent's turn through even steps of its + /// parameter. + fn turn_of(s: &crate::PathSeg) -> f64 { + match *s { + crate::PathSeg::Line { .. } => 0.0, + crate::PathSeg::Arc { angle, .. } => angle.abs(), + _ => (0..=TURN_SAMPLES) + .filter_map(|i| at(s, i as f64 / TURN_SAMPLES as f64).map(|(_, t)| t)) + .collect::>() + .windows(2) + .map(|w| w[0].cross(w[1]).len().atan2(w[0].dot(w[1]))) + .sum(), + } + } + + /// `n + 1` points spread along `path` (evenly by length from segment to segment, evenly in each + /// segment's parameter within it), with the path's unit tangent at each. + fn samples(path: &[crate::PathSeg], n: usize) -> Result<(Vec, Vec)> { + let bad = || invalid("a path segment has no direction"); + let lengths: Vec = path.iter().map(length).collect(); + let total: f64 = lengths.iter().sum(); + if !(total > 1e-12) { + return Err(invalid("the sweep path has no length")); + } + let (mut pts, mut tangents) = (Vec::with_capacity(n + 1), Vec::with_capacity(n + 1)); + for i in 0..=n { + let mut s = total * i as f64 / n as f64; + let mut k = 0; + while k + 1 < path.len() && s > lengths.get(k).copied().unwrap_or(0.0) { + s -= lengths.get(k).copied().unwrap_or(0.0); + k += 1; + } + let f = (s / lengths.get(k).copied().unwrap_or(1.0).max(1e-300)).clamp(0.0, 1.0); + let (p, t) = path.get(k).and_then(|seg| at(seg, f)).ok_or_else(bad)?; + pts.push(p); + tangents.push(t); + } + Ok((pts, tangents)) + } + + /// A path segment's length (an arc's exactly; a free-form one's by its spans' own lengths). + fn length(s: &crate::PathSeg) -> f64 { + match s { + crate::PathSeg::Line { a, b } => a.dist(*b), + crate::PathSeg::Arc { a, center, angle, .. } => a.dist(*center) * angle.abs(), + crate::PathSeg::Curve { seg, .. } => seg.length(), + crate::PathSeg::Bezier(b) => b.length().unwrap_or(0.0), + } + } + + /// The point `f` (0…1) of the way along a segment's parameter and its unit tangent there. + fn at(s: &crate::PathSeg, f: f64) -> Option<(Vec3, Vec3)> { + match s { + crate::PathSeg::Line { a, b } => Some((a.lerp(*b, f), (*b - *a).normalized()?)), + crate::PathSeg::Arc { a, center, axis, angle } => { + let k = axis.normalized()?; + let p = crate::build::rotate_about(*a, *center, k, angle * f); + Some((p, (k.cross(p - *center) * angle.signum()).normalized()?)) + } + crate::PathSeg::Curve { plane, seg } => Some((plane.to_world(seg.point_at(f)), plane.dir_to_world(seg.derivative(f)).normalized()?)), + crate::PathSeg::Bezier(b) => Some((b.point(f)?, b.derivative(f)?.normalized()?)), + } + } + + /// One column of a loft: its curve in each section (and station) in loft order, skinned by + /// SMLib with no caps (`smlib_loft`), ruled between two, cubic through four or more. + pub(super) fn lofted(column: &[&solidcraft_geom::bspline::CurveN<4>]) -> Result { + let sections: Vec> = column + .iter() + .map(|c| { + let points = c.ctrl.iter().map(|h| [h[0] / h[3], h[1] / h[3], h[2] / h[3], h[3]]).collect(); + vec![Curve::Nurbs { degree: c.degree, points, knots: c.knots.clone() }] + }) + .collect(); + let degree = u32::try_from(column.len().saturating_sub(1).clamp(1, 3)).unwrap_or(3); + checked(&SmBrep::loft(§ions, degree, false).map_err(sm("surface loft"))?, "surface loft") + } } #[cfg(test)] mod tests { use super::*; use crate::{box_solid, cylinder, measure, trim}; - use solidcraft_geom::{Loop2, Vec2}; + use solidcore_record::Loop2; fn rel(a: f64, b: f64) -> f64 { (a - b).abs() / b.abs().max(1e-9) @@ -1295,8 +1720,9 @@ mod tests { assert!(walls.is_surface() && walls.face_count() == 4 && rel(area(&walls), 80.0) < 1e-9); let pts: Vec = (0..=10).map(|i| Vec3::new(0.0, 0.0, i as f64)).collect(); assert!(rel(area(&sweep_sheet_points(&Plane::XY, std::slice::from_ref(&line), &pts).unwrap()), 100.0) < 1e-6); - // A smooth point path: a quarter circle of radius 30 in the YZ plane. One smooth wall (not - // forty ruled strips), a piece of cylinder: 10 × 15π. + // A point path through a quarter circle of radius 30 in the YZ plane: the path is its + // lines (no wall is fitted through the points), a wall along each of the 40, together + // 10 × the polyline's length, within 10⁻⁴ of the cylinder's 10 × 15π. let arc: Vec = (0..=40) .map(|i| { let t = i as f64 / 40.0 * FRAC_PI_2; @@ -1304,15 +1730,16 @@ mod tests { }) .collect(); let curved = sweep_sheet_points(&Plane::XY, std::slice::from_ref(&line), &arc).unwrap(); - assert_eq!(curved.face_count(), 1, "smooth wall"); + assert_eq!(curved.face_count(), 40, "a wall along each line"); let want = 10.0 * 30.0 * FRAC_PI_2; assert!(rel(area(&curved), want) < 2e-3, "{} vs {want}", area(&curved)); // (measured on meshes) - // A bent chain along the same path: two smooth walls joined by one shared seam edge. + // A bent chain along the same path: two walls along each line, sharing every seam: the + // profile's two segments at each of the 41 points and its three vertices along each of + // the 40 lines. let bent = vec![line[0], Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 5.0) }]; let two = sweep_sheet_points(&Plane::XY, &[bent], &arc).unwrap(); - assert_eq!(two.face_count(), 2); - let edges: std::collections::HashSet<_> = two.solid.edge_iter().map(|e| e.id()).collect(); - assert_eq!(edges.len(), 7, "the walls share their seam"); + assert_eq!(two.face_count(), 2 * 40); + assert_eq!(two.edge_count(), 2 * 41 + 3 * 40, "the walls share their seams"); } #[test] @@ -1436,29 +1863,38 @@ mod tests { assert!(remove_faces(&b, &[]).is_err()); } - /// Faces that are not planes or cylinders thicken onto fitted surfaces. A sixth of a sphere - /// (one of its six patches) thickened out by 1 is a sixth of the shell between radii 10 and - /// 11; a torus patch (a symmetric share of the torus, by its area) thickened out by 1 is that + /// Faces that are not planes or cylinders thicken onto fitted surfaces. A sphere's cap above + /// z = 5 (polar angles to 60°: solid angle π) thickened out by 1 is that sector of the shell + /// between radii 10 and 11, π/3·(11³ − 10³); a torus patch (a symmetric share of the torus, by its area) thickened out by 1 is that /// share of the shell 2π²R((r+1)² − r²); thickened in past the sphere's centre, refused. #[test] fn thicken_curved_faces_onto_fitted_surfaces() { use crate::{sphere, torus}; use std::f64::consts::PI; let ball = sphere(Vec3::ZERO, 10.0).unwrap(); - let patch = copy_faces(&ball, &[Vec3::new(0.0, 0.0, 10.0)]).unwrap(); - assert!(rel(measure(&patch).unwrap().area, 4.0 * PI * 100.0 / 6.0) < 2e-3, "one sixth"); + let caps = crate::split_by_plane(&ball, &Plane::from_normal(Vec3::new(0.0, 0.0, 5.0), Vec3::Z).unwrap()).unwrap(); + let cap = caps.into_iter().find(|b| measure(b).unwrap().bbox.min.z > 5.0 - 1e-6).unwrap(); + let patch = copy_faces(&cap, &[Vec3::new(0.0, 0.0, 10.0)]).unwrap(); + assert!(rel(measure(&patch).unwrap().area, 2.0 * PI * 10.0 * 5.0) < 2e-3, "the cap"); let shell = thicken(&patch, 1.0, false).unwrap(); assert!(!shell.is_surface()); - let want = 4.0 / 3.0 * PI * (1331.0 - 1000.0) / 6.0; + let want = PI / 3.0 * (1331.0 - 1000.0); let v = measure(&shell).unwrap().volume; assert!(rel(v, want) < 3e-3, "{v} vs {want}"); // (measured on meshes) assert!(thicken(&patch, -10.0, false).is_err()); // A torus patch (R 20, r 5): between the tube radii r and r + 1 over its own angles, θ round // the tube and φ round the axis (read off its mesh): the volume is // Δφ·[R((r+1)² − r²)/2·Δθ + ((r+1)³ − r³)/3·(sin θ1 − sin θ0)]. - let ring = torus(Vec3::ZERO, 20.0, 5.0).unwrap(); - let face = copy_faces(&ring, &[Vec3::new(25.0, 0.0, 0.0)]).unwrap(); - let mesh = face.tessellate(0.01).unwrap(); + // SMLib makes a torus one face: the patch is the piece of it with x, y > 0 and z > 1 + // (bounded by iso lines both ways: planes through the axis, and z = 1 round the tube). + let mut ring = torus(Vec3::ZERO, 20.0, 5.0).unwrap(); + for (o, n) in [(Vec3::ZERO, Vec3::X), (Vec3::ZERO, Vec3::Y), (Vec3::new(0.0, 0.0, 1.0), Vec3::Z)] { + let pieces = crate::split_by_plane(&ring, &Plane::from_normal(o, n).unwrap()).unwrap(); + ring = pieces.into_iter().find(|b| (measure(b).unwrap().bbox.min - o).dot(n) > -1e-6).unwrap(); + } + let (c, s) = (std::f64::consts::FRAC_PI_4.cos(), std::f64::consts::FRAC_PI_4.sin()); + let face = copy_faces(&ring, &[Vec3::new((20.0 + 5.0 * c) * c, (20.0 + 5.0 * c) * s, 5.0 * s)]).unwrap(); + let mesh = face.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); let angles: Vec<(f64, f64)> = mesh.positions.iter().map(|p| (p.z.atan2((p.x * p.x + p.y * p.y).sqrt() - 20.0), p.y.atan2(p.x))).collect(); let span = |f: &dyn Fn(&(f64, f64)) -> f64| { let (lo, hi) = angles.iter().map(f).fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), x| (a.min(x), b.max(x))); @@ -1472,9 +1908,12 @@ mod tests { assert!(rel(v, want) < 3e-3, "{v} vs {want}"); // (measured on meshes) } - /// Three faces of a box meeting at a corner (sharp edges), thickened out by 1: three slabs, - /// a wedge along each sharp edge and a corner tetrahedron, 3·100 + 3·(½·1²·10) + 1/6; a closed - /// solid that every check accepts. Thickened into the inside corner, refused. + /// Three faces of a box meeting at a corner (sharp edges), thickened out by 1: each face's + /// offset extended until the offsets meet, as SMLib thickens across a convex sharp edge (and + /// other CAD does): three slabs, a 1 × 1 × 10 block along each sharp edge and a unit cube at + /// the corner, 3·100 + 3·10 + 1 = 331 = 11³ − 10³; a closed solid that every check accepts. + /// Into the inside corner, and half each way, the same with the offsets trimmed where they + /// cross. #[test] fn thicken_a_box_corner_across_its_sharp_edges() { let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); @@ -1482,12 +1921,17 @@ mod tests { assert!(corner.is_surface() && corner.face_count() == 3); let t = thicken(&corner, 1.0, false).unwrap(); assert!(!t.is_surface()); - let want = 300.0 + 15.0 + 1.0 / 6.0; + let want = 300.0 + 30.0 + 1.0; let v = measure(&t).unwrap().volume; assert!(rel(v, want) < 1e-9, "{v} vs {want}"); - assert!(Body::new(t.solid.as_ref().clone()).is_ok()); - assert!(thicken(&corner, -1.0, false).is_err()); - assert!(thicken(&corner, 1.0, true).is_err(), "half of it goes into the inside corner"); + assert!(t.validity().is_empty(), "{:?}", t.validity()); + // Into the inside corner the offsets are trimmed where they meet: 10³ − 9³; half each way, + // 10.5³ − 9.5³. + for (t, symmetric, want) in [(-1.0, false, 1000.0 - 729.0), (1.0, true, 10.5f64.powi(3) - 9.5f64.powi(3))] { + let t = thicken(&corner, t, symmetric).unwrap(); + let v = measure(&t).unwrap().volume; + assert!(rel(v, want) < 1e-9 && t.validity().is_empty(), "{v} vs {want}"); + } } /// A saddle B-spline patch thickened by 1.5 holds the volume its offsets sweep: by Steiner, @@ -1549,24 +1993,28 @@ mod tests { #[test] fn thicken_a_cylinder_side_and_a_box_top() { let c = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 20.0).unwrap(); - // One half of the side, offset outward by 1: half of a ring. - let half = copy_faces(&c, &[Vec3::new(7.0, 7.0, 10.0)]).unwrap(); + // The side of the cylinder cut in half at x = 0, offset outward by 1: half of a ring. + let halves = crate::split_by_plane(&c, &Plane::from_normal(Vec3::ZERO, Vec3::X).unwrap()).unwrap(); + let cut = halves.into_iter().find(|b| measure(b).unwrap().bbox.min.x > -1e-6).unwrap(); + // (It comes in pieces round the axis: picked all the way round.) + let round: Vec = (-4..=4).map(|k| f64::from(k) * 0.35).map(|a| Vec3::new(10.0 * a.cos(), 10.0 * a.sin(), 10.0)).collect(); + let half = copy_faces(&cut, &round).unwrap(); + assert!(rel(measure(&half).unwrap().area, std::f64::consts::PI * 10.0 * 20.0) < 1e-3, "the half side"); let v = measure(&thicken(&half, 1.0, false).unwrap()).unwrap().volume; let want = std::f64::consts::PI * (121.0 - 100.0) / 2.0 * 20.0; assert!(rel(v, want) < 3e-4, "{v} vs {want}"); // (measured on meshes) - // Both halves (meeting smoothly): the whole ring, inward. - let d = 10.0 / 2f64.sqrt(); - let side = copy_faces(&c, &[Vec3::new(d, d, 10.0), Vec3::new(-d, -d, 10.0)]).unwrap(); - assert_eq!(side.face_count(), 2); + // The whole side (one face, closed round its seam): the whole ring, inward. + let side = copy_faces(&c, &[Vec3::new(7.0, 7.0, 10.0)]).unwrap(); + assert_eq!(side.face_count(), 1); let v = measure(&thicken(&side, -1.0, false).unwrap()).unwrap().volume; let want = std::f64::consts::PI * (100.0 - 81.0) * 20.0; assert!(rel(v, want) < 3e-4, "{v} vs {want}"); // (measured on meshes) - // Two faces meeting at a sharp edge: two slabs and the wedge closing the gap between - // them, its ends patched: 2·100 + ½·1²·10. + // Two faces meeting at a sharp edge: two slabs and, the offsets extended until they + // meet, the 1 × 1 × 10 block along the edge: 2·100 + 10. let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); let two = copy_faces(&b, &[Vec3::new(5.0, 5.0, 10.0), Vec3::new(5.0, 0.0, 5.0)]).unwrap(); let v = measure(&thicken(&two, 1.0, false).unwrap()).unwrap().volume; - assert!(rel(v, 205.0) < 1e-9, "{v}"); + assert!(rel(v, 210.0) < 1e-9, "{v}"); } #[test] diff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rs index 08fb3a95b..d0f98a809 100644 --- a/crates/kernel/src/sweep_path.rs +++ b/crates/kernel/src/sweep_path.rs @@ -1,40 +1,22 @@ -//! Sweeps along 3D point paths (3D sketch curves: projected, intersection and included curves). -//! The profile follows the path with a rotation-minimising frame. Smooth paths get one B-spline -//! wall per profile segment; paths with sharp corners (or profiles with holes) get ruled walls -//! between stations, mitred at the corners. Sweep options (orientation, twist, end scale, guide -//! rails; see [`SweepControl`]) reshape the stations; their default leaves them exactly as -//! described. +//! Sweeps along 3D point paths (3D sketch curves: projected, intersection and included curves) +//! and the laws that place a profile along a path: the rotation-minimising frame and the sweep +//! options (orientation, twist, end scale, guide rails; see [`SweepControl`]) give the stations +//! SMLib's controlled sweeps skin through ([`crate::smlib_sweeps`]). A solid along points is +//! SMLib's sweep along the lines between them ([`sweep_path_with`]). -use mt::builder; -use solidcraft_geom::{Grid, Plane, Region2, Seg2, Vec2, Vec3}; -use truck_modeling as mt; +use solidcore_record::{Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; -use crate::body::{Body, p3}; -use crate::build::{NetFit, cap_and_close, close_sweep, interpolate_net, smooth_loft_faces, uniform_wire}; -use crate::numbered::{NumberedLoop, NumberedRegion}; -use crate::record::{self, Side}; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::numbered::NumberedLoop; +use crate::{KernelError, Result}; /// Most path points accepted. const MAX_PATH_POINTS: usize = 100_000; -/// Stations of a smooth sweep (the B-spline walls interpolate them). -const MAX_SMOOTH_STATIONS: usize = 120; -/// Stations of a ruled sweep. -const MAX_RULED_STATIONS: usize = 2000; /// A turn sharper than this between path segments is a corner (radians). const CORNER: f64 = 0.35; -/// Samples per profile segment of the smooth walls. +/// Samples per profile segment where a closed sweep checks that its last section lands on its first. const SEG_SAMPLES: usize = 12; -/// Stations of a smooth sweep that twists or scales, at the least. -const MIN_CONTROLLED_STATIONS: usize = 16; -/// Stations of a smooth sweep that twists or scales, at the most. -const MAX_CONTROLLED_STATIONS: usize = 160; -/// Stations of a ruled sweep that twists or scales, at the least. -const MIN_CONTROLLED_RULED: usize = 64; -/// The most twist one station of a smooth sweep may carry (radians). -const SMOOTH_TWIST_STEP: f64 = std::f64::consts::PI / 18.0; -/// The most twist one station of a ruled sweep may carry (radians). -const RULED_TWIST_STEP: f64 = std::f64::consts::PI / 36.0; /// How the profile turns as it follows a sweep path. #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -104,7 +86,7 @@ impl SweepControl { } /// Whether the profile changes along the path (it twists, scales or follows rails). - fn varies(&self) -> bool { + pub(crate) fn varies(&self) -> bool { self.twist != 0.0 || self.scale != 1.0 || !self.rails.is_empty() } @@ -141,13 +123,13 @@ impl SweepControl { /// A linear map of world vectors (columns) plus the station it is centred at. #[derive(Clone, Copy)] -struct Station { - at: Vec3, - m: [Vec3; 3], +pub(crate) struct Station { + pub at: Vec3, + pub m: [Vec3; 3], } impl Station { - fn apply(&self, v: Vec3) -> Vec3 { + pub(crate) fn apply(&self, v: Vec3) -> Vec3 { self.m[0] * v.x + self.m[1] * v.y + self.m[2] * v.z } } @@ -171,13 +153,9 @@ pub(crate) fn clean(path: &[Vec3]) -> Result> { Ok(out) } -pub(crate) fn closed_path(pts: &[Vec3]) -> bool { - pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.dist(*b) <= 1e-7) -} - /// The cyclic correspondence of a loop's last section to its first. Matching whole curves /// (rather than vertices alone) prevents sewing an incompatible twist or scale shut. -fn closing_offset(plane: &Plane, profile: &NumberedLoop, st: &[Station]) -> Result { +pub(crate) fn closing_offset(plane: &Plane, profile: &NumberedLoop, st: &[Station]) -> Result { let fail = || KernelError::Invalid("a sweep along a closed path must return to its starting profile; adjust the twist, end scale or rails".into()); let (Some(first), Some(last)) = (st.first(), st.last()) else { return Err(fail()) }; @@ -204,39 +182,6 @@ fn closing_offset(plane: &Plane, profile: &NumberedLoop, st: &[Station]) -> Resu .ok_or_else(fail) } -fn rotated_wire(wire: &mt::Wire, offset: usize) -> mt::Wire { - wire.edge_iter().skip(offset).chain(wire.edge_iter().take(offset)).cloned().collect() -} - -fn turn(a: Vec3, b: Vec3) -> f64 { - match (a.normalized(), b.normalized()) { - (Some(a), Some(b)) => a.dot(b).clamp(-1.0, 1.0).acos(), - _ => 0.0, - } -} - -/// Points evenly spaced by arc length along the polyline (ends kept). -fn resample(p: &[Vec3], n: usize) -> Vec { - let mut cum = vec![0.0]; - for w in p.windows(2) { - let l = cum.last().copied().unwrap_or(0.0) + w[0].dist(w[1]); - cum.push(l); - } - let total = cum.last().copied().unwrap_or(0.0); - let mut out = Vec::with_capacity(n + 1); - let mut k = 0; - for i in 0..=n { - let s = total * i as f64 / n as f64; - while k + 2 < cum.len() && cum.get(k + 1).is_some_and(|c| *c < s) { - k += 1; - } - let (Some(a), Some(b), Some(ca), Some(cb)) = (p.get(k), p.get(k + 1), cum.get(k), cum.get(k + 1)) else { break }; - let t = if cb - ca > 1e-15 { ((s - ca) / (cb - ca)).clamp(0.0, 1.0) } else { 0.0 }; - out.push(*a + (*b - *a) * t); - } - out -} - /// Rotation-minimising frames (double reflection) at the points, for the given unit tangents; /// each station maps the first frame onto its own. fn frames(pts: &[Vec3], tangents: &[Vec3]) -> Option> { @@ -259,26 +204,6 @@ fn frames(pts: &[Vec3], tangents: &[Vec3]) -> Option> { Some(out) } -/// Stations: each maps a world vector at the first station to the same vector at its own, -/// optionally stretched across a corner (mitre). -fn stations(pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)>]) -> Result> { - let f = frames(pts, tangents).ok_or_else(|| KernelError::Invalid("the sweep path doubles back".into()))?; - let f0 = *f.first().ok_or_else(|| KernelError::Invalid("sweep path".into()))?; - let mut out = Vec::with_capacity(f.len()); - for (i, fi) in f.iter().enumerate() { - // Rotation taking f0 to fi: columns are the images of the world axes. - let col = |e: Vec3| fi[0] * f0[0].dot(e) + fi[1] * f0[1].dot(e) + fi[2] * f0[2].dot(e); - let mut m = [col(Vec3::X), col(Vec3::Y), col(Vec3::Z)]; - if let Some(Some((b, s))) = mitre.get(i) { - for c in &mut m { - *c += *b * ((s - 1.0) * c.dot(*b)); - } - } - out.push(Station { at: *pts.get(i).ok_or_else(|| KernelError::Invalid("sweep path".into()))?, m }); - } - Ok(out) -} - /// Frames square to the path whose turn about it keeps `d`'s projection: none where the path /// runs along `d`. fn frames_toward(tangents: &[Vec3], d: Vec3) -> Result> { @@ -297,11 +222,32 @@ fn frames_toward(tangents: &[Vec3], d: Vec3) -> Result> { .collect() } +/// Kept as drawn (parallel), the profile flattens to nothing where the path runs along its +/// plane: the path, by its directions of travel `tangents` (the first leaving the profile), has to +/// cross the plane at 5 degrees or more all the way. +pub(crate) fn crossing_check(plane: &Plane, tangents: &[Vec3]) -> Result<()> { + let n = plane.normal().normalized().ok_or_else(|| KernelError::Invalid("sweep frame".into()))?; + let t0 = *tangents.first().ok_or_else(|| KernelError::Invalid("sweep path".into()))?; + let axis = if n.dot(t0) < 0.0 { n * -1.0 } else { n }; + if tangents.iter().any(|t| t.dot(axis) < 5f64.to_radians().sin()) { + return Err(KernelError::Invalid( + "kept parallel, the profile would lie along the sweep path: the path must keep crossing the profile's plane (by 5 deg or more)".into(), + )); + } + Ok(()) +} + /// Stations shaped by sweep options: each maps a world vector at the first station to its image /// at its own (twisted and scaled about the profile's normal through the first station, then /// turned by the orientation's frames), optionally stretched across a corner (mitre). Twist and /// scale grow with the length run along `pts`. -fn controlled_stations(plane: &Plane, pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)>], ctl: &SweepControl) -> Result> { +pub(crate) fn controlled_stations( + plane: &Plane, + pts: &[Vec3], + tangents: &[Vec3], + mitre: &[Option<(Vec3, f64)>], + ctl: &SweepControl, +) -> Result> { if !ctl.rails.is_empty() { return railed_stations(pts, tangents, mitre, ctl); } @@ -316,12 +262,8 @@ fn controlled_stations(plane: &Plane, pts: &[Vec3], tangents: &[Vec3], mitre: &[ // Twist and scale act about the profile's normal, pointing the way the path leaves it. let n = plane.normal().normalized().ok_or_else(|| KernelError::Invalid("sweep frame".into()))?; let axis = if n.dot(t0) < 0.0 { n * -1.0 } else { n }; - // Kept as drawn, the profile flattens to nothing where the path runs along its plane: the - // path has to cross it at 5 degrees or more all the way. - if ctl.orientation == SweepOrientation::Parallel && tangents.iter().any(|t| t.dot(axis) < 5f64.to_radians().sin()) { - return Err(KernelError::Invalid( - "kept parallel, the profile would lie along the sweep path: the path must keep crossing the profile's plane (by 5 deg or more)".into(), - )); + if ctl.orientation == SweepOrientation::Parallel { + crossing_check(plane, tangents)?; } let mut run = Vec::with_capacity(pts.len()); let mut total = 0.0; @@ -470,385 +412,39 @@ pub(crate) fn rail_frame(along: Vec3, across: Vec3, along_to: Vec3, across_to: V [map(Vec3::X), map(Vec3::Y), map(Vec3::Z)] } -/// The volume a profile of `area` on `plane` sweeps through the stations: each station's -/// section area times how squarely the path crosses it, summed along the path (trapezoids). -fn swept_volume(plane: &Plane, area: f64, st: &[Station], tangents: &[Vec3]) -> f64 { - let rate = |i: usize| match (st.get(i), tangents.get(i)) { - (Some(s), Some(t)) => area * s.apply(plane.x).cross(s.apply(plane.y)).dot(*t).abs(), - _ => 0.0, - }; - st.windows(2).enumerate().map(|(i, w)| 0.5 * (rate(i) + rate(i + 1)) * w[0].at.dist(w[1].at)).sum() -} - -/// The stations of a smooth sweep: as many as the path has points (4…[`MAX_SMOOTH_STATIONS`]), -/// more when the profile twists or scales. -fn smooth_count(points: usize, ctl: &SweepControl) -> usize { - let n = points.saturating_sub(1).clamp(4, MAX_SMOOTH_STATIONS); - if !ctl.varies() { - return n; - } - let twist = (ctl.twist.abs() / SMOOTH_TWIST_STEP).ceil() as usize; - n.max(MIN_CONTROLLED_STATIONS).max(twist).min(MAX_CONTROLLED_STATIONS) -} - -/// The path with points added along its straight runs (its corners kept) when the profile -/// twists or scales, so ruled walls follow the change. -fn densify(pts: &[Vec3], ctl: &SweepControl) -> Vec { - if !ctl.varies() { - return pts.to_vec(); - } - let total: f64 = pts.windows(2).map(|w| w[0].dist(w[1])).sum(); - let want = MIN_CONTROLLED_RULED.max((ctl.twist.abs() / RULED_TWIST_STEP).ceil() as usize).min(MAX_RULED_STATIONS / 2); - let mut out = Vec::with_capacity(want + pts.len()); - out.extend(pts.first().copied()); - for w in pts.windows(2) { - let pieces = if total > 0.0 { ((w[0].dist(w[1]) / total) * want as f64).ceil() as usize } else { 1 }; - let pieces = pieces.clamp(1, want.max(1)); - out.extend((1..=pieces).map(|j| w[0].lerp(w[1], j as f64 / pieces as f64))); - } - out -} - -/// The profile plane carried to a station. -fn station_plane(plane: &Plane, s0: Vec3, st: &Station) -> Plane { - Plane { origin: st.at + st.apply(plane.origin - s0), x: st.apply(plane.x), y: st.apply(plane.y) } -} - /// Sweep a planar region along a 3D polyline path. The profile keeps its relation to the path /// (it need not touch it); the path should start near the profile. pub fn sweep_path(plane: &Plane, region: &Region2, path: &[Vec3]) -> Result { + let _span = solidcraft_profile::span("kernel", "sweep_path"); sweep_path_with(plane, region, path, &SweepControl::default()) } /// [`sweep_path`] with sweep options: orientation, twist and end scale. pub fn sweep_path_with(plane: &Plane, region: &Region2, path: &[Vec3], ctl: &SweepControl) -> Result { + let _span = solidcraft_profile::span("kernel", "sweep_path_with"); ctl.check()?; - if region.area().abs() < 1e-9 { - return Err(KernelError::Invalid("profile has no area".into())); - } - let pts = clean(path)?; - let corner = pts.windows(3).any(|w| turn(w[1] - w[0], w[2] - w[1]) > CORNER); - let profile = crate::numbered::number_regions(std::slice::from_ref(region)) - .pop() - .map(|r| r.oriented()) - .ok_or_else(|| KernelError::Invalid("profile".into()))?; - if !corner && region.holes.is_empty() { - // Smooth: evenly spaced stations, tangents from neighbours. - let len: f64 = pts.windows(2).map(|w| w[0].dist(w[1])).sum(); - let n = smooth_count(pts.len(), ctl); - let sp = resample(&pts, n); - let tangents = central_tangents(&sp)?; - let (st, expected) = if ctl.is_default() { - (stations(&sp, &tangents, &[])?, region.area().abs() * len * start_cos(plane, &tangents)) - } else { - let st = controlled_stations(plane, &sp, &tangents, &[], ctl)?; - let v = swept_volume(plane, region.area().abs(), &st, &tangents); - (st, v) - }; - if closed_path(&pts) { - let offset = closing_offset(plane, &profile.outer, &st)?; - if let Ok(b) = smooth_closed_walls(plane, &profile.outer, &st, offset, expected) { - return Ok(b); - } - } else if let Ok(b) = smooth_walls(plane, &profile.outer, &st, expected) { - return Ok(b); - } - } - ruled(plane, &profile, &pts, ctl) + smlib_sweep_points(plane, region, &crate::PointPath::polyline(path.to_vec()), ctl) } -fn central_tangents(p: &[Vec3]) -> Result> { - let n = p.len(); - let closed = closed_path(p); - (0..n) - .map(|i| { - let a = p.get(if closed && (i == 0 || i + 1 == n) { n - 2 } else { i.saturating_sub(1) }).copied().unwrap_or_default(); - let b = p.get(if closed && (i == 0 || i + 1 == n) { 1 } else { (i + 1).min(n - 1) }).copied().unwrap_or_default(); - (b - a).normalized().ok_or_else(|| KernelError::Invalid("the sweep path has no direction".into())) - }) - .collect() -} - -/// How squarely the path leaves the profile (volume = area × length × this). -fn start_cos(plane: &Plane, tangents: &[Vec3]) -> f64 { - tangents.first().map(|t| t.dot(plane.normal()).abs()).unwrap_or(1.0).max(1e-3) -} - -/// Stations at the path's points (at most [`MAX_RULED_STATIONS`]), mitred at corners, with the -/// points they stand at. -fn ruled_stations(plane: &Plane, pts: &[Vec3], ctl: &SweepControl) -> Result<(Vec, Vec)> { - let pts = densify(pts, ctl); - let pts: Vec = if pts.len() > MAX_RULED_STATIONS { resample(&pts, MAX_RULED_STATIONS) } else { pts }; - let n = pts.len(); - let closed = closed_path(&pts); - let seg_dir = |i: usize| -> Option { (*pts.get(i + 1)? - *pts.get(i)?).normalized() }; - let mut tangents = Vec::with_capacity(n); - let mut mitre = Vec::with_capacity(n); - for i in 0..n { - let d_in = if i > 0 { - seg_dir(i - 1) - } else if closed { - seg_dir(n - 2) - } else { - None - }; - let d_out = if i + 1 < n { - seg_dir(i) - } else if closed { - seg_dir(0) - } else { - None - }; - let (t, m) = match (d_in, d_out) { - (Some(a), Some(b)) => { - let t = (a + b).normalized().ok_or_else(|| KernelError::Invalid("the sweep path turns back on itself".into()))?; - let half = turn(a, b) / 2.0; - // Across the bend the section stretches by 1 / cos(half the turn). - let m = (b - a).normalized().map(|bend| (bend, 1.0 / half.cos().max(0.2))); - (t, m) - } - (Some(a), None) => (a, None), - (None, Some(b)) => (b, None), - (None, None) => return Err(KernelError::Invalid("sweep path".into())), - }; - tangents.push(t); - mitre.push(m); +/// [`crate::sweep_point_path_with`] through SMLib: each curve held exactly as its segments (a +/// drawn 3D spline's spans, a sketch curve's or an edge's curve), each polyline as the lines +/// between its points ([`crate::PointPath::segs`]), swept by [`crate::sweep_with`], which mitres +/// the corners. A polyline is the path its points make, however smooth they run: a curve that +/// reaches the kernel only as points is followed as those points. +pub(crate) fn smlib_sweep_points(plane: &Plane, region: &Region2, path: &crate::PointPath, ctl: &SweepControl) -> Result { + let segs = path.segs()?; + if segs.is_empty() || segs.len() > 1000 { + return Err(KernelError::Invalid("the path needs 1…1000 segments".into())); } - let st = if ctl.is_default() { stations(&pts, &tangents, &mitre)? } else { controlled_stations(plane, &pts, &tangents, &mitre, ctl)? }; - Ok((pts, st)) -} - -/// Walls of chains of sketch segments on `plane` (open, or closed) carried along a 3D polyline -/// path that starts near them: ruled between stations at the path's points, mitred at corners, -/// with no caps. Neighbouring walls share their edges. -pub(crate) fn ruled_sheet(plane: &Plane, chains: &[Vec], path: &[Vec3], ctl: &SweepControl) -> Result> { - ctl.check()?; - let (pts, st) = ruled_stations(plane, &clean(path)?, ctl)?; - let edges: usize = chains.iter().map(Vec::len).sum(); - if st.len().saturating_mul(edges) > 400_000 { - return Err(KernelError::Invalid("the sweep is too detailed (curves × path points)".into())); - } - let s0 = pts.first().copied().unwrap_or_default(); - // Each chain's segments are numbered on from the last chain's; every station's wire of a - // chain has the same edges, each over the same segment. - let offsets: Vec = chains.iter().scan(0, |o, c| Some(std::mem::replace(o, *o + c.len()))).collect(); - let mut wires: Vec> = Vec::with_capacity(st.len()); - let mut numbers: Vec>> = Vec::new(); - for s in &st { - let pl = station_plane(plane, s0, s); - let mut at = Vec::with_capacity(chains.len()); - for (c, offset) in chains.iter().zip(&offsets) { - let (wire, seeds) = crate::build::chain_wire_seeds(&pl, c)?; - if numbers.len() < chains.len() { - numbers.push(seeds.iter().map(|(_, i)| vec![offset + i]).collect()); - } - at.push(wire); - } - wires.push(at); - } - guard("path sweep", || { - let mut faces: Vec = Vec::new(); - for w in wires.windows(2) { - let (Some(w0), Some(w1)) = (w.first(), w.get(1)) else { continue }; - for ((a, b), n) in w0.iter().zip(w1).zip(&numbers) { - let sides: mt::Shell = builder::try_wire_homotopy(a, b).map_err(|e| KernelError::Failed(format!("path sweep: {e}")))?; - faces.extend(record::ruled(&sides, a, b, n, n)); - } - } - Ok(faces) - }) -} - -/// Walls of chains of sketch segments on `plane` carried along a smooth 3D polyline path (no -/// turn sharper than [`CORNER`]): one B-spline wall per segment through evenly spaced, -/// rotation-minimising stations, neighbouring walls sharing their seam edges; no caps. `None` -/// for a path with corners (see [`ruled_sheet`]). -pub(crate) fn smooth_sheet(plane: &Plane, chains: &[Vec], path: &[Vec3], ctl: &SweepControl) -> Result>> { - ctl.check()?; - let pts = clean(path)?; - if pts.windows(3).any(|w| turn(w[1] - w[0], w[2] - w[1]) > CORNER) { - return Ok(None); - } - let fail = |w: &str| KernelError::Failed(format!("path sweep: {w}")); - if chains.iter().map(Vec::len).sum::() > 4096 { - return Err(fail("too many curves for a smooth sweep")); - } - let n = smooth_count(pts.len(), ctl); - let sp = resample(&pts, n); - let tangents = central_tangents(&sp)?; - let st = if ctl.is_default() { stations(&sp, &tangents, &[])? } else { controlled_stations(plane, &sp, &tangents, &[], ctl)? }; - let s0 = st.first().map(|s| s.at).unwrap_or_default(); - let at = |i: usize, q: Vec2| st.get(i).map(|s| s.at + s.apply(plane.to_world(q) - s0)).unwrap_or_default(); - let n = st.len() - 1; - let mut faces: Vec = Vec::new(); - let mut offset = 0; - for chain in chains { - let closed = chain.first().zip(chain.last()).is_some_and(|(f, l)| l.end().dist(f.start()) <= 1e-6); - // Each segment: its curve at the first and last station, the columns through its start - // and end, and the wall surface. - let mut data = Vec::with_capacity(chain.len()); - for s in chain { - let samples = - Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?; - data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?); - } - let walls: Vec = guard("path sweep", || { - let m = chain.len(); - // Vertices along the chain (an open chain has one more than it has segments). - let corners: Vec = chain.iter().map(Seg2::start).chain(chain.last().map(Seg2::end).filter(|_| !closed)).collect(); - let start: Vec = corners.iter().map(|q| builder::vertex(p3(at(0, *q)))).collect(); - let end: Vec = corners.iter().map(|q| builder::vertex(p3(at(n, *q)))).collect(); - let next = |j: usize| if closed { (j + 1) % m } else { j + 1 }; - let mut seams = Vec::with_capacity(corners.len()); - for (k, (a, b)) in start.iter().zip(&end).enumerate() { - // The column through each corner: the start column of the segment leaving it, or - // the end column of the last segment. - let col = match data.get(k) { - Some(NetFit { v_ends: [first, _], .. }) => first, - None => data.last().map(|NetFit { v_ends: [_, last], .. }| last).ok_or_else(|| fail("seam"))?, - }; - seams.push(mt::Edge::try_new(a, b, mt::Curve::BSplineCurve(col.clone())).map_err(|e| fail(&e.to_string()))?); - } - let mut walls = Vec::with_capacity(m); - for (j, NetFit { surface: surf, u_ends: [c0, c1], .. }) in data.iter().enumerate() { - let (Some(a0), Some(b0), Some(a1), Some(b1), Some(sa), Some(sb)) = - (start.get(j), start.get(next(j)), end.get(j), end.get(next(j)), seams.get(j), seams.get(next(j))) - else { - return Err(fail("edges")); - }; - let e0 = mt::Edge::try_new(a0, b0, mt::Curve::BSplineCurve(c0.clone())).map_err(|e| fail(&e.to_string()))?; - let e1 = mt::Edge::try_new(a1, b1, mt::Curve::BSplineCurve(c1.clone())).map_err(|e| fail(&e.to_string()))?; - let w: mt::Wire = vec![sa.clone(), e1, sb.inverse(), e0.inverse()].into(); - walls.push(mt::Face::try_new(vec![w], mt::Surface::BSplineSurface(surf.clone())).map_err(|e| fail(&e.to_string()))?); - } - Ok(walls) - })?; - // Wall j comes from segment j of the chain. - faces.extend(walls.into_iter().enumerate().map(|(j, w)| (w, Some(record::profile(&[offset + j]))))); - offset += chain.len(); - } - Ok(Some(faces)) -} - -/// Ruled walls between stations at the path's points (mitred at corners), every loop of the -/// (oriented) profile. -fn ruled(plane: &Plane, profile: &NumberedRegion, pts: &[Vec3], ctl: &SweepControl) -> Result { - let (pts, st) = ruled_stations(plane, pts, ctl)?; - let s0 = pts.first().copied().unwrap_or_default(); - let loops: Vec<&NumberedLoop> = profile.loops().collect(); - let mut wires: Vec> = Vec::with_capacity(st.len()); - for s in &st { - let pl = station_plane(plane, s0, s); - wires.push(loops.iter().map(|l| uniform_wire(&pl, &l.lp)).collect::>>()?); - } - let closed = closed_path(&pts); - if closed { - let offsets = loops.iter().map(|l| closing_offset(plane, l, &st)).collect::>>()?; - let first = wires.first().ok_or_else(|| KernelError::Invalid("sweep path".into()))?; - let end: Vec = first.iter().zip(offsets).map(|(w, k)| rotated_wire(w, k)).collect(); - if let Some(last) = wires.last_mut() { - *last = end; - } - } - guard("path sweep", || { - // Every station's wires have the loops' segments, edge for edge. - let mut faces: Vec = Vec::new(); - for w in wires.windows(2) { - let (Some(w0), Some(w1)) = (w.first(), w.get(1)) else { continue }; - for ((a, b), l) in w0.iter().zip(w1).zip(&loops) { - let sides = builder::try_wire_homotopy(a, b).map_err(|e| KernelError::Failed(format!("path sweep: {e}")))?; - faces.extend(record::ruled(&sides, a, b, &l.from, &l.from)); - } - } - if closed { - return close_sweep(faces); - } - let (Some(first), Some(last)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("path sweep".into())) }; - cap_and_close(faces, first, last, false) - }) -} - -/// Two smooth runs share their middle section and the closing section. Splitting the run -/// avoids edges from a vertex back to itself when the profile returns without a permutation. -fn smooth_closed_walls(plane: &Plane, profile: &NumberedLoop, st: &[Station], offset: usize, expected: f64) -> Result { - let fail = || KernelError::Failed("closed path sweep: the walls do not close a solid".into()); - if profile.lp.segs.len() > 64 || st.len() < 7 { - return Err(fail()); - } - guard("closed path sweep", || { - let first = st.first().ok_or_else(fail)?; - let mut wires = st.iter().map(|s| uniform_wire(&station_plane(plane, first.at, s), &profile.lp)).collect::>>()?; - let end = rotated_wire(wires.first().ok_or_else(fail)?, offset); - if let Some(last) = wires.last_mut() { - *last = end; - } - let middle = (wires.len() - 1) / 2; - let numbers = vec![profile.from.clone(); wires.len()]; - let mut sides = smooth_loft_faces(wires.get(..=middle).ok_or_else(fail)?, numbers.get(..=middle).ok_or_else(fail)?, true)?; - sides.extend(smooth_loft_faces(wires.get(middle..).ok_or_else(fail)?, numbers.get(middle..).ok_or_else(fail)?, true)?); - let b = close_sweep(sides)?; - let tol = (profile.lp.signed_area().abs().sqrt() * 0.05).max(1e-3); - if b.tessellate(tol).is_ok_and(|m| (m.measure().volume - expected).abs() <= 0.15 * expected.abs()) { Ok(b) } else { Err(fail()) } - }) -} - -/// One B-spline wall per profile segment through the stations, capped; checked by volume. -fn smooth_walls(plane: &Plane, profile: &NumberedLoop, st: &[Station], expected: f64) -> Result { - let lp = &profile.lp; - let nseg = lp.segs.len(); - let fail = |w: &str| KernelError::Failed(format!("path sweep: {w}")); - if nseg == 0 || nseg > 64 || st.len() < 4 { - return Err(fail("profile")); - } - let s0 = st.first().map(|s| s.at).unwrap_or_default(); - let at = |i: usize, q: Vec2| st.get(i).map(|s| s.at + s.apply(plane.to_world(q) - s0)).unwrap_or_default(); - let n = st.len() - 1; - let mut data = Vec::with_capacity(nseg); - for s in &lp.segs { - let samples = - Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?; - data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?); - } - guard("path sweep", || { - let start: Vec = lp.segs.iter().map(|s| builder::vertex(p3(at(0, s.start())))).collect(); - let end: Vec = lp.segs.iter().map(|s| builder::vertex(p3(at(n, s.start())))).collect(); - let (mut e0, mut e1, mut seams) = (Vec::with_capacity(nseg), Vec::with_capacity(nseg), Vec::with_capacity(nseg)); - for (j, NetFit { u_ends: [c0, c1], v_ends: [seam, _], .. }) in data.iter().enumerate() { - let (Some(a0), Some(b0), Some(a1), Some(b1)) = (start.get(j), start.get((j + 1) % nseg), end.get(j), end.get((j + 1) % nseg)) else { - return Err(fail("vertices")); - }; - e0.push(mt::Edge::try_new(a0, b0, mt::Curve::BSplineCurve(c0.clone())).map_err(|e| fail(&e.to_string()))?); - e1.push(mt::Edge::try_new(a1, b1, mt::Curve::BSplineCurve(c1.clone())).map_err(|e| fail(&e.to_string()))?); - seams.push(mt::Edge::try_new(a0, a1, mt::Curve::BSplineCurve(seam.clone())).map_err(|e| fail(&e.to_string()))?); - } - let mut walls = Vec::with_capacity(nseg); - for (j, NetFit { surface: surf, .. }) in data.iter().enumerate() { - let (Some(a), Some(b), Some(sa), Some(sb)) = (e0.get(j), e1.get(j), seams.get(j), seams.get((j + 1) % nseg)) else { - return Err(fail("edges")); - }; - let w: mt::Wire = vec![sa.clone(), b.clone(), sb.inverse(), a.inverse()].into(); - let wall = mt::Face::try_new(vec![w], mt::Surface::BSplineSurface(surf.clone())).map_err(|e| fail(&e.to_string()))?; - walls.push((wall, Some(record::profile(profile.numbers(j))))); - } - let w0: mt::Wire = e0.iter().cloned().collect(); - let w1: mt::Wire = e1.iter().cloned().collect(); - let tol = (lp.signed_area().abs().sqrt() * 0.05).max(1e-3); - for ws in [walls.clone(), walls.iter().map(|(f, prov)| (f.inverse(), prov.clone())).collect()] { - if let Ok(b) = cap_and_close(ws, std::slice::from_ref(&w0), std::slice::from_ref(&w1), false) - && b.tessellate(tol).is_ok_and(|m| (m.measure().volume - expected).abs() <= 0.15 * expected.abs()) - { - return Ok(b); - } - } - Err(fail("the walls do not close a solid")) - }) + crate::sweep_with(plane, region, &segs, ctl) } #[cfg(test)] mod tests { + use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI}; - use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; + use solidcore_record::{Loop2, Plane, Region2, Vec2, Vec3}; use super::{SweepControl, SweepOrientation, sweep_path, sweep_path_with}; @@ -858,7 +454,8 @@ mod tests { #[test] fn sweeps_along_3d_paths() { - // A quarter of a helix-like 3D curve: a smooth wall, volume ≈ area × length. + // A polyline through 41 points of a quarter of a helix-like 3D curve: the profile swept + // along its 40 lines, mitred at each point, so volume = area × length. let path: Vec = (0..=40) .map(|i| { let t = i as f64 / 40.0 * std::f64::consts::FRAC_PI_2; @@ -869,24 +466,50 @@ mod tests { let plane = Plane::from_normal(path[0], t0).unwrap(); let b = sweep_path(&plane, &circle(2.0), &path).unwrap(); let len: f64 = path.windows(2).map(|w| w[0].dist(w[1])).sum(); - let v = b.tessellate(0.01).unwrap().measure().volume; + let v = b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().volume; let want = std::f64::consts::PI * 4.0 * len; assert!((v - want).abs() < 0.02 * want, "{v} vs {want}"); - // One wall per profile segment and two caps (ruled walls would give dozens). - assert!(b.faces(0.01).unwrap().len() <= 8, "smooth walls: {}", b.faces(0.01).unwrap().len()); + // The path is its lines (no wall is fitted through the points): a wall per profile + // segment (the circle is one closed arc, one edge in SMLib) along each of the 40 lines, + // and two caps. + assert_eq!(b.faces(0.01).unwrap().len(), 40 + 2, "walls along each line"); // An L-shaped path (a sharp corner) with a holed square: mitred ruled walls. let path = [Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::new(20.0, 0.0, 20.0)]; let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap(); let sq = |h: f64| Loop2::polygon(&[Vec2::new(-h, -h), Vec2::new(h, -h), Vec2::new(h, h), Vec2::new(-h, h)]); let region = Region2 { outer: sq(3.0), holes: vec![sq(1.0).reversed()] }; let b = sweep_path(&plane, ®ion, &path).unwrap(); - let v = b.tessellate(0.01).unwrap().measure().volume; + let v = b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().volume; let want = 32.0 * 40.0; assert!((v - want).abs() < 0.03 * want, "{v} vs {want}"); assert!(sweep_path(&plane, ®ion, &[Vec3::ZERO]).is_err()); assert!(sweep_path(&plane, ®ion, &[Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 0.0)]).is_err()); } + /// A profile at a slant to its path (drawn flat, the path rising steeply from it) swept + /// along a polyline whose lines are shorter than the slant: each section reaches past both + /// mitres of its line, so each line's walls are carried on far enough past the corner for + /// all of it to meet the mitre. The square's centre is on the path, so the volume is the + /// section square to the path times the path's length, `16 cos(slant) L`; a line carried + /// short of a mitre leaves a notch with a face of its section in it. Every face is named. + #[test] + fn a_slanted_profile_meets_itself_at_every_mitre() { + use crate::history::FaceOrigin; + let path: Vec = (0..=20).map(|i| Vec3::new((f64::from(i) * 0.2).sin() * 10.0, 0.0, f64::from(i))).collect(); + let b = sweep_path(&Plane::XY, &square(2.0), &path).unwrap(); + let len: f64 = path.windows(2).map(|w| w[0].dist(w[1])).sum(); + let slant = (path[1] - path[0]).normalized().unwrap().z; + let want = 16.0 * slant * len; + let v = b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().volume; + assert!((v - want).abs() < 1e-6 * want, "{v} vs {want}"); + let h = b.history().unwrap(); + let caps = |end: bool| h.faces.iter().filter(|f| f.origins == [FaceOrigin::Cap { end }]).count(); + assert_eq!((caps(false), caps(true)), (1, 1)); + for (i, f) in h.faces.iter().enumerate() { + assert!(matches!(f.origins[..], [FaceOrigin::Profile { .. }] | [FaceOrigin::Cap { .. }]), "face {i}: {f:?}"); + } + } + fn square(h: f64) -> Region2 { Region2 { outer: Loop2::polygon(&[Vec2::new(-h, -h), Vec2::new(h, -h), Vec2::new(h, h), Vec2::new(-h, h)]), holes: Vec::new() } } @@ -903,14 +526,21 @@ mod tests { let small = big * k; let ctl = SweepControl { scale: k, ..SweepControl::default() }; let b = crate::sweep_with(&Plane::XY, &circle(big), &up(h), &ctl).unwrap(); - let m = b.tessellate(0.005).unwrap().measure(); + let m = b.mesh(&crate::MeshTolerance::chord(0.005)).unwrap().measure(); let volume = PI * h * (big * big + big * small + small * small) / 3.0; let lateral = PI * (big + small) * (h * h + (big - small).powi(2)).sqrt(); let caps = PI * (big * big + small * small); assert!((m.volume - volume).abs() < 2e-3 * volume, "volume {} vs {volume}", m.volume); assert!((m.area - caps - lateral).abs() < 2e-3 * lateral, "lateral {} vs {lateral}", m.area - caps); // The end cap is the scaled circle. - let top = b.tessellate(0.005).unwrap().positions.iter().filter(|p| (p.z - h).abs() < 1e-6).map(|p| p.x.hypot(p.y)).fold(0.0, f64::max); + let top = b + .mesh(&crate::MeshTolerance::chord(0.005)) + .unwrap() + .positions + .iter() + .filter(|p| (p.z - h).abs() < 1e-6) + .map(|p| p.x.hypot(p.y)) + .fold(0.0, f64::max); assert!((top - small).abs() < 1e-3, "end radius {top}"); // The surface sweep of the circle's curve: the frustum's lateral face alone. let sheet = crate::sweep_sheet_with(&Plane::XY, std::slice::from_ref(&circle(big).outer.segs), &up(h), &ctl).unwrap(); @@ -920,7 +550,7 @@ mod tests { /// The corners of a twisted square: each seam edge's angle at `z`. fn corner_angles(b: &crate::Body, z: f64) -> Vec { - let mesh = b.tessellate(0.002).unwrap(); + let mesh = b.mesh(&crate::MeshTolerance::chord(0.002)).unwrap(); let mut out = Vec::new(); for e in &mesh.edges { for w in e.windows(2) { @@ -942,7 +572,7 @@ mod tests { let ctl = SweepControl { twist, ..SweepControl::default() }; let b = crate::sweep_with(&Plane::XY, &square(5.0), &up(h), &ctl).unwrap(); // Twisted walls are saddles: a fine mesh to measure them. - let v = b.tessellate(0.0005).unwrap().measure().volume; + let v = b.mesh(&crate::MeshTolerance::chord(0.0005)).unwrap().measure().volume; assert!((v - 100.0 * h).abs() < 2e-3 * 100.0 * h, "volume {v}"); // Corners start at 45 deg (and 135, -45, -135): each seam turns by the twist so far. let off = |a: f64, want: f64| { @@ -979,7 +609,7 @@ mod tests { let rise = r * FRAC_PI_4.sin(); let ctl = SweepControl { orientation: SweepOrientation::Parallel, ..SweepControl::default() }; let b = sweep_path_with(&Plane::XY, &square(3.0), &path, &ctl).unwrap(); - let mesh = b.tessellate(0.005).unwrap(); + let mesh = b.mesh(&crate::MeshTolerance::chord(0.005)).unwrap(); let v = mesh.measure().volume; let want = 36.0 * rise; assert!((v - want).abs() < 5e-3 * want, "volume {v} vs {want}"); @@ -1010,7 +640,7 @@ mod tests { .collect(); let ctl = SweepControl { orientation: SweepOrientation::Direction(Vec3::Y), ..SweepControl::default() }; let b = sweep_path_with(&Plane::XY, &square(3.0), &path, &ctl).unwrap(); - let mesh = b.tessellate(0.005).unwrap(); + let mesh = b.mesh(&crate::MeshTolerance::chord(0.005)).unwrap(); let len = r * FRAC_PI_2; assert!((mesh.measure().volume - 36.0 * len).abs() < 5e-3 * 36.0 * len); // The sides facing ±Y stay at y = ±3. diff --git a/crates/kernel/src/sweep_rails_tests.rs b/crates/kernel/src/sweep_rails_tests.rs index 4bc438e33..744e81ff5 100644 --- a/crates/kernel/src/sweep_rails_tests.rs +++ b/crates/kernel/src/sweep_rails_tests.rs @@ -5,9 +5,10 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use solidcraft_geom::prelude::*; use std::f64::consts::PI; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use crate::{RailFit, SweepControl, measure, sweep_path_with}; @@ -146,7 +147,8 @@ fn two_rails_carry_a_line_between_arcs() { /// Rails the sweep cannot follow are refused with a reason, never a panic: three rails, a rail /// with a bad point, a rail with a twist or scale besides, a rail starting on the path, a rail -/// that stops short, rails along a path with a corner. +/// that stops short, a straight rail along a path with a corner (a rail must turn with the path +/// at its corners). #[test] fn rails_the_sweep_cannot_follow_are_refused() { let rail = vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(5.0, 0.0, 40.0)]; @@ -162,5 +164,5 @@ fn rails_the_sweep_cannot_follow_are_refused() { refuse(railed(vec![vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(8.0, 0.0, 20.0)]], RailFit::Scale), &up(), "whole length"); refuse(railed(vec![rail.clone(), rail.clone()], RailFit::Scale), &up(), "start at the same point"); let bent = vec![Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::new(20.0, 0.0, 20.0)]; - refuse(railed(vec![vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 30.0)]], RailFit::Scale), &bent, "sharp corners"); + refuse(railed(vec![vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 30.0)]], RailFit::Scale), &bent, "the guide rails have to turn with it"); } diff --git a/crates/kernel/src/tangent_cylinders.rs b/crates/kernel/src/tangent_cylinders.rs deleted file mode 100644 index 7ade4ce60..000000000 --- a/crates/kernel/src/tangent_cylinders.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! Cylinders of one radius whose axes cross (#788: a second bore of the same size drilled across -//! a bore, a pipe tee of equal pipes). -//! -//! Two such cylinders meet in two ellipses that cross each other at two points, where the -//! surfaces touch along a common normal. A mesh intersection cannot trace the curves through -//! there, and a boolean with a crossing in the middle of a face has no way to tell which of the -//! curves' four arms lies in which sector of the face. With the touching points on the edges of -//! the faces instead, each arm is a curve running from an edge to an edge, which the boolean -//! takes. So before the boolean, each of the two faces is split along the line of its cylinder -//! through the touching points (the solids are unchanged), and the result's history is composed -//! back over the operands as they were given. - -use solidcraft_geom::{Plane, UnitVec3, Vec3}; -use truck_modeling::{ParametricCurve, SearchNearestParameter}; - -use crate::body::{Body, from_p3, p3}; -use crate::boolean_record as recorded; -use crate::history::History; -use crate::splitface::{SplitTool, split_any}; -use crate::{BoolOp, FaceSurface, Result, face_surface}; - -/// Most faces split before the boolean (a face crossing several cylinders is split for each). -const MAX_SPLITS: usize = 16; - -/// A cylindrical face and its cylinder. -#[derive(Clone, Copy, Debug)] -pub(crate) struct Cylinder { - face: usize, - origin: Vec3, - axis: UnitVec3, - radius: f64, -} - -impl Cylinder { - #[cfg(test)] - /// `None` for an axis with no direction. - pub(crate) fn new(face: usize, origin: Vec3, axis: Vec3, radius: f64) -> Option { - Some(Self { face, origin, axis: axis.unit()?, radius }) - } -} - -fn cylinders(body: &Body) -> Vec { - (0..body.face_count()) - .filter_map(|face| match face_surface(body, face)? { - FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() => { - Some(Cylinder { face, origin, axis, radius }) - } - _ => None, - }) - .collect() -} - -/// Where two cylinders of one radius with crossing axes touch, and the planes that hold the -/// touching points and one cylinder's axis each. -pub(crate) struct Crossing { - pub(crate) points: [Vec3; 2], - plane_x: Plane, - plane_y: Plane, -} - -pub(crate) fn crossing(x: &Cylinder, y: &Cylinder, tol: f64) -> Option { - let finite = [x, y].iter().all(|c| c.origin.is_finite() && c.radius.is_finite() && c.radius > 0.0); - if !finite || !tol.is_finite() || (x.radius - y.radius).abs() > tol { - return None; - } - let across = x.axis.cross(y.axis); - // Axes within a hair of parallel touch along a line, which is another matter. - let sine = across.len(); - if !(sine > 1e-4) { - return None; - } - // The closest points of the two axes, which meet in a point. - let (b, w) = (x.axis.dot(y.axis), x.origin - y.origin); - let (d, e) = (x.axis.dot(w), y.axis.dot(w)); - let denominator = 1.0 - b * b; - if !(denominator > 1e-12) { - return None; - } - let s = (b * e - d) / denominator; - let t = (e - b * d) / denominator; - let (on_x, on_y) = (x.origin + x.axis * s, y.origin + y.axis * t); - if !(on_x.dist(on_y) <= tol) { - return None; - } - let centre = (on_x + on_y) * 0.5; - // Both cylinders reach their common normal `c` at a radius from the crossing. - let c = across / sine; - let points = [centre + c * x.radius, centre - c * x.radius]; - Some(Crossing { points, plane_x: Plane::from_normal(centre, x.axis.cross(c))?, plane_y: Plane::from_normal(centre, y.axis.cross(c))? }) -} - -/// Whether `p` is on face `face` of the body whose mesh is `mesh`: within `reach` of one of the -/// face's triangles. -fn on_face(mesh: &solidcraft_geom::Mesh, face: usize, p: Vec3, reach: f64) -> bool { - mesh.triangles - .iter() - .zip(&mesh.tri_face) - .filter(|(_, f)| **f as usize == face) - .filter_map(|(t, _)| mesh.tri(t)) - .any(|[a, b, c]| crate::boolean_guard::point_triangle_dist(p, a, b, c) <= reach) -} - -/// Whether `p` lies on an edge of face `face` (within `margin`). -fn on_boundary(body: &Body, face: usize, p: Vec3, margin: f64) -> bool { - let Some(face) = body.solid.face_iter().nth(face) else { return false }; - face.absolute_boundaries().iter().any(|wire| { - wire.edge_iter().any(|edge| { - let curve = edge.curve(); - curve.search_nearest_parameter(p3(p), None, 100).is_some_and(|t| from_p3(curve.subs(t)).dist(p) <= margin) - }) - }) -} - -/// The split the bodies need next: `(whether in the first body, face, plane)`, if a touching -/// point of two cylinders lies on both their faces but on the edges of neither yet. -fn next_split(a: &Body, b: &Body, tol: f64) -> Option<(bool, usize, Plane)> { - let (in_b, in_a) = (cylinders(b), cylinders(a)); - if in_a.is_empty() || in_b.is_empty() { - return None; - } - let size = a.size().max(b.size()); - let (margin, chord) = ((size * 1e-6).max(1e-9), (size * 1e-3).max(1e-6)); - let mut meshes = None; - for x in &in_a { - for y in &in_b { - let Some(crossing) = crossing(x, y, tol) else { continue }; - if meshes.is_none() { - meshes = Some((a.tessellate(chord).ok()?, b.tessellate(chord).ok()?)); - } - let (ma, mb) = meshes.as_ref()?; - for p in crossing.points { - if !(on_face(ma, x.face, p, 3.0 * chord) && on_face(mb, y.face, p, 3.0 * chord)) { - continue; - } - if !on_boundary(a, x.face, p, margin) { - return Some((true, x.face, crossing.plane_x)); - } - if !on_boundary(b, y.face, p, margin) { - return Some((false, y.face, crossing.plane_y)); - } - } - } - } - None -} - -/// Whether the bodies have cylinders of one radius crossing each other that touch inside both -/// their faces, so that [`boolean`] has faces to split. -pub(crate) fn needed(a: &Body, b: &Body) -> bool { - !a.is_mesh() && !b.is_mesh() && !SPLITTING.with(|c| c.get()) && next_split(a, b, (a.size().max(b.size()) * 1e-7).max(1e-9) * 10.0).is_some() -} - -thread_local! { - /// Set while the boolean of the split bodies runs (no second round of splitting). - static SPLITTING: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// The boolean `op` of `a` and `b` with their faces split along the touching points of equal -/// cylinders crossing each other, `run` doing the boolean of the split bodies. `None` when the -/// bodies have no such cylinders, or the boolean of the split bodies gave no (checked) result: -/// the caller then takes its other ways. -pub(crate) fn boolean(a: &Body, b: &Body, op: BoolOp, run: &dyn Fn(&Body, &Body, BoolOp) -> Result>) -> Option>> { - if a.is_mesh() || b.is_mesh() || SPLITTING.with(|c| c.get()) { - return None; - } - let size = a.size().max(b.size()); - let tol = (size * 1e-7).max(1e-9) * 10.0; - let ((mut x, mut hx), (mut y, mut hy)) = ((a.clone(), Some(History::identity(a))), (b.clone(), Some(History::identity(b)))); - let mut split = false; - for _ in 0..MAX_SPLITS { - let Some((first, face, plane)) = next_split(&x, &y, tol) else { break }; - let (body, history) = if first { (&x, &hx) } else { (&y, &hy) }; - let (mut done, _) = split_any(body, &[face], &SplitTool::Plane(plane)).ok()?; - // The split is no authored boundary: a later feature may still merge what it separates. - done.regularization_protected = body.regularization_protected; - let through = recorded::through(&done, 0, history.as_ref()); - if first { - (x, hx) = (done, through); - } else { - (y, hy) = (done, through); - } - split = true; - } - if !split { - return None; - } - SPLITTING.with(|c| c.set(true)); - let result = crate::guard("boolean of split faces", || run(&x, &y, op)); - SPLITTING.with(|c| c.set(false)); - let Ok(result) = result else { return None }; - // Held to what a boolean can do, as a retry's result is (see `boolean_guard`). - crate::boolean_guard::check_retry(a, b, op, result.as_ref()).ok()?; - let counts = crate::record::counts(&[a, b]); - Some(Ok(result.map(|body| { - // Each step's history over the operands `[a, b]`. - let history = recorded::of_pair(&body, &recorded::placed(hx.clone(), 0, 2), &recorded::placed(hy.clone(), 1, 2)); - body.with_checked_history(history, &counts) - }))) -} diff --git a/crates/kernel/src/tangent_edge.rs b/crates/kernel/src/tangent_edge.rs new file mode 100644 index 000000000..fa687bc89 --- /dev/null +++ b/crates/kernel/src/tangent_edge.rs @@ -0,0 +1,382 @@ +//! Whether the two faces on either side of an edge meet tangentially all along it, decided +//! exactly from the record. +//! +//! Each use of the edge carries its pcurve `(u(t), v(t))` in its face's parameters +//! ([`Face::parameters`]: a plane, or the B-spline surface SMLib holds the face as), on the edge's +//! own parameter `t`, so the two uses' points at one `t` are one point of the edge. The face's +//! natural normal there is `S_u × S_v` at the pcurve's point. On a piece of `t` where the pcurve +//! stays within one span of its own knots and one knot cell of its surface, both are +//! polynomials: `S` of degree `(p, q)` in `(u, v)` (rational: its homogeneous form, of the same +//! degree), the pcurve of degree `r` in `t`. So `S_u × S_v`, scaled by a positive power of the +//! weights, is a polynomial in `t` of degree at most `(2p + 2q - 2) r` (rational: `(4p + 4q - 2) r`, +//! from `(A_u w - A w_u) × (A_v w - A w_v)`), and a plane's is constant. The cross product of the +//! two faces' normals is then a polynomial vector of degree at most the sum `D` of theirs, and a +//! polynomial of degree `D` that vanishes at `D + 1` points vanishes everywhere: the faces are +//! parallel all along the piece exactly when they are at `D + 1` of its points, its Chebyshev +//! points, and on one side (smooth, not folded back on each other) when their outward normals +//! point the same way there. No point is a guess at where the faces part: one where they do is +//! a witness of a crease (or a cusp, the faces folded back), and agreement at all of them is +//! a proof of tangency, within the angle the caller allows at each (between them, the cross +//! product is bounded by its largest value at them times the Lebesgue constant of `D + 1` +//! Chebyshev points, under `1 + (2/π) ln(D + 1)`). +//! +//! The pieces' ends are the pcurves' knots and the parameters where a pcurve crosses a knot line +//! of its surface (periodic copies included), each a root of `U(t) - k W(t)` on one Bézier span +//! of the pcurve, isolated by subdividing its Bernstein coefficients (no sign change: no root; +//! one: exactly one) and found to rounding by bisection. + +use solidcore_record::Vec3; +use solidcore_record::brep::{Brep, Curve2, Face, Surface}; +use solidcraft_geom::brep::eval::SurfaceEval; +use solidcraft_geom::bspline::{HPoint, segment}; +use solidcraft_geom::prelude::*; + +use crate::{KernelError, Result}; + +/// Most points one edge's decision evaluates. +const MAX_POINTS: usize = 1_000_000; +/// Largest degree of a piece's cross product the decision takes. +const MAX_DEGREE: usize = 4096; +/// Subdivisions of one Bernstein polynomial while isolating its roots: its pieces are then +/// 2⁻⁴⁸ of a pcurve span, where a root left unisolated (a pcurve touching a knot line) ends a +/// piece there. +const MAX_DEPTH: u32 = 48; +/// Subdivisions one root isolation may make: a root that touches its knot line (a double root, +/// the only kind that keeps two sign changes as the pieces shrink) costs one a level. +const MAX_SUBDIVISIONS: usize = 4096; +/// Below this sine of the angle between `S_u` and `S_v` a face's normal is undefined at that +/// point (a pole): the normal, and so the cross product, is zero there. +const DEGENERATE: f64 = 1e-9; + +/// One use of the edge: its face's surface, the sign turning its natural normal outward, its +/// pcurve and the degree of its normal along a piece. +struct Use<'a> { + surface: SurfaceEval, + sign: f64, + pcurve: &'a Curve2, + degree: usize, + /// The knot lines of the surface in u and v (its distinct knots over its domain) and its + /// periods: a polynomial cell's sides. + lines: [Vec; 2], + period: [Option; 2], +} + +fn failed(msg: String) -> KernelError { + KernelError::Failed(msg) +} + +/// A B-spline's degree from its knot and control point counts. +fn degree_of(knots: usize, count: usize) -> Option { + knots.checked_sub(count.checked_add(1)?) +} + +/// The distinct knots of a knot vector over its domain `[knots[p], knots[n]]`. +fn lines(knots: &[f64], count: usize) -> Option> { + let p = degree_of(knots.len(), count)?; + let mut out: Vec = knots.get(p..=count)?.to_vec(); + out.dedup(); + Some(out) +} + +impl<'a> Use<'a> { + fn new(face: &Face, sign: f64, pcurve: &'a Curve2) -> Result> { + let surface = face.parameters(); + let r = match pcurve { + Curve2::Spline { knots, points } => degree_of(knots.len(), points.len()), + Curve2::RationalSpline { knots, homogeneous } => degree_of(knots.len(), homogeneous.len()), + } + .ok_or_else(|| failed("a pcurve's degree".into()))?; + // The normal's degree in (u, v) and the knot lines. + let (uv_degree, lines) = match surface { + Surface::Plane { .. } | Surface::PlaneThrough { .. } => (0, [Vec::new(), Vec::new()]), + Surface::Spline { u_knots, v_knots, points } => { + let (nu, nv) = (points.len(), points.first().map_or(0, Vec::len)); + let (p, q) = (degree_of(u_knots.len(), nu), degree_of(v_knots.len(), nv)); + let (Some(p), Some(q), Some(lu), Some(lv)) = (p, q, lines(u_knots, nu), lines(v_knots, nv)) else { + return Err(failed("a spline face's degree".into())); + }; + ((2 * p + 2 * q).saturating_sub(2), [lu, lv]) + } + Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + let (nu, nv) = (homogeneous.len(), homogeneous.first().map_or(0, Vec::len)); + let (p, q) = (degree_of(u_knots.len(), nu), degree_of(v_knots.len(), nv)); + let (Some(p), Some(q), Some(lu), Some(lv)) = (p, q, lines(u_knots, nu), lines(v_knots, nv)) else { + return Err(failed("a spline face's degree".into())); + }; + ((4 * p + 4 * q).saturating_sub(2), [lu, lv]) + } + // SMLib gives every curved analytic face its NURBS form, which its pcurves are on. + _ => return Err(crate::blend::unsupported("deciding tangency along an edge of a face that is no plane and has no NURBS form")), + }; + let eval = SurfaceEval::new(surface).map_err(|e| failed(format!("a face's surface: {e}")))?; + let period = eval.domain().period; + Ok(Use { surface: eval, sign, pcurve, degree: uv_degree.saturating_mul(r), lines, period }) + } + + /// The outward unit normal at the pcurve's point at `t`; `Ok(None)` where it is undefined (a + /// pole: a zero of the normal). + fn normal(&self, t: f64) -> Result> { + let uv = solidcraft_geom::brep::pcurve::eval(self.pcurve, t).ok_or_else(|| failed(format!("a pcurve at {t}")))?; + let (_, su, sv) = self.surface.derivs(uv[0], uv[1]).ok_or_else(|| failed(format!("a face at ({}, {})", uv[0], uv[1])))?; + let n = su.cross(sv); + if !(n.len() > DEGENERATE * su.len() * sv.len()) { + return Ok(None); + } + Ok(n.normalized().map(|n| n * self.sign)) + } + + /// The parameters in `(t0, t1)` where the normal stops being one polynomial: the pcurve's + /// own knots, and where it crosses a knot line of the surface. + fn breaks(&self, [t0, t1]: [f64; 2], out: &mut Vec) -> Result<()> { + let (knots, ctrl): (&[f64], Vec) = match self.pcurve { + Curve2::Spline { knots, points } => (knots, points.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: 1.0 }).collect()), + Curve2::RationalSpline { knots, homogeneous } => { + (knots, homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: 0.0, w: h[2] }).collect()) + } + }; + let r = degree_of(knots.len(), ctrl.len()).ok_or_else(|| failed("a pcurve's degree".into()))?; + let mut spans: Vec = vec![t0]; + spans.extend(knots.iter().copied().filter(|k| *k > t0 && *k < t1)); + spans.push(t1); + spans.dedup(); + out.extend(spans.iter().copied()); + if self.lines.iter().all(Vec::is_empty) { + return Ok(()); + } + for w in spans.windows(2) { + let &[a, b] = w else { continue }; + let (_, bez) = segment(r, knots, &ctrl, a, b).map_err(|e| failed(format!("a pcurve span: {e}")))?; + if bez.len() != r + 1 { + return Err(failed("a pcurve span is no Bézier piece".into())); + } + for d in 0..2 { + let coord = |h: &HPoint| if d == 0 { h.x } else { h.y }; + // The span's range in this direction: its control points' hull (weights > 0). + let along: Vec = bez.iter().map(|h| coord(h) / h.w).collect(); + let lo = along.iter().copied().fold(f64::INFINITY, f64::min); + let hi = along.iter().copied().fold(f64::NEG_INFINITY, f64::max); + if !(lo.is_finite() && hi.is_finite()) { + return Err(failed("a pcurve's control points".into())); + } + for k in cell_sides(&self.lines[d], self.period[d], lo, hi)? { + // Coefficients within rounding of zero are zero: a pcurve running along + // the knot line (a seam, a boundary) crosses none there. + let scale = bez.iter().map(|h| coord(h).abs() + (k * h.w).abs()).fold(0.0, f64::max); + let floor = 64.0 * f64::EPSILON * scale; + let c: Vec = bez.iter().map(|h| coord(h) - k * h.w).map(|x| if x.abs() <= floor { 0.0 } else { x }).collect(); + if c.iter().all(|x| *x == 0.0) { + continue; + } + let mut roots = Vec::new(); + let mut work = MAX_SUBDIVISIONS; + bernstein_roots(&c, 0.0, 1.0, MAX_DEPTH, &mut work, &mut roots); + out.extend(roots.into_iter().map(|s| a + (b - a) * s)); + } + } + } + Ok(()) + } +} + +/// The knot lines `lines` (and, with a period, their copies a whole number of periods away) that +/// lie in `[lo, hi]`. +fn cell_sides(lines: &[f64], period: Option, lo: f64, hi: f64) -> Result> { + let Some(p) = period.filter(|p| *p > 0.0) else { + return Ok(lines.iter().copied().filter(|k| *k >= lo && *k <= hi).collect()); + }; + let (Some(&first), Some(&last)) = (lines.first(), lines.last()) else { return Ok(Vec::new()) }; + let (n0, n1) = (((lo - last) / p).floor(), ((hi - first) / p).ceil()); + if !(n1 - n0 <= 64.0) { + return Err(failed("a pcurve running round its surface too many times".into())); + } + let mut out = Vec::new(); + let mut n = n0; + while n <= n1 { + out.extend(lines.iter().map(|k| k + n * p).filter(|k| *k >= lo && *k <= hi)); + n += 1.0; + } + Ok(out) +} + +/// The value at `s` of the polynomial with Bernstein coefficients `c` on `[0, 1]` (de Casteljau). +fn bernstein_value(c: &[f64], s: f64) -> f64 { + let mut b = c.to_vec(); + while b.len() > 1 { + b = b.windows(2).map(|w| if let [x, y] = w { x * (1.0 - s) + y * s } else { 0.0 }).collect(); + } + b.first().copied().unwrap_or(0.0) +} + +/// The Bernstein coefficients of the polynomial `c` on `[0, ½]` and `[½, 1]`. +fn bernstein_halves(c: &[f64]) -> (Vec, Vec) { + let mut left = Vec::with_capacity(c.len()); + let mut right = Vec::with_capacity(c.len()); + let mut b = c.to_vec(); + while let (Some(&f), Some(&l)) = (b.first(), b.last()) { + left.push(f); + right.push(l); + b = b.windows(2).map(|w| if let [x, y] = w { 0.5 * (x + y) } else { 0.0 }).collect(); + } + right.reverse(); + (left, right) +} + +/// The roots in `[lo, hi]` of the polynomial with Bernstein coefficients `c` there, mapped +/// into `[lo, hi]`'s place in `[0, 1]`: none where the coefficients keep one sign, exactly one +/// where they change sign once (found by bisection to rounding), otherwise those of each half. +fn bernstein_roots(c: &[f64], lo: f64, hi: f64, depth: u32, work: &mut usize, out: &mut Vec) { + let (Some(&first), Some(&last)) = (c.first(), c.last()) else { return }; + if first == 0.0 { + out.push(lo); + } + if last == 0.0 { + out.push(hi); + } + let signs: Vec = c.iter().filter(|x| **x != 0.0).map(|x| *x > 0.0).collect(); + let changes = signs.windows(2).filter(|w| matches!(w, [x, y] if x != y)).count(); + if changes == 0 { + return; + } + if changes == 1 && first != 0.0 && last != 0.0 { + let (mut a, mut b) = (0.0, 1.0); + for _ in 0..64 { + let m = 0.5 * (a + b); + if !(m > a && m < b) { + break; + } + if (bernstein_value(c, m) > 0.0) == (first > 0.0) { + a = m; + } else { + b = m; + } + } + out.push(lo + (hi - lo) * 0.5 * (a + b)); + return; + } + let mid = 0.5 * (lo + hi); + // Out of depth or work, the roots are within this piece: it ends a piece of the edge at + // both its ends. + if depth == 0 || *work == 0 { + out.extend([lo, hi]); + return; + } + *work -= 1; + let (l, r) = bernstein_halves(c); + bernstein_roots(&l, lo, mid, depth - 1, work, out); + bernstein_roots(&r, mid, hi, depth - 1, work, out); +} + +/// Calls `visit` with the outward unit normals of edge `e`'s two uses' faces at one point of the +/// edge after another, `sign(f)` turning face `f`'s natural normal outward: on each piece of the +/// edge where both normals are polynomials, at the `D + 1` Chebyshev points the module +/// documentation describes, skipping a point where either is undefined (a pole). `visit` returns +/// whether to go on. `Ok(None)` for an edge with other than two uses; else whether some point had +/// both normals. +fn normal_pairs(rec: &Brep, sign: impl Fn(usize) -> Option, e: usize, mut visit: impl FnMut(Vec3, Vec3) -> bool) -> Result> { + let edge = rec.edges.get(e).ok_or_else(|| failed(format!("edge {e}")))?; + let [ua, ub] = edge.uses.as_slice() else { return Ok(None) }; + let use_of = |u: &solidcore_record::brep::EdgeUseRef| -> Result> { + let face = rec.faces.get(u.face as usize).ok_or_else(|| failed(format!("face {}", u.face)))?; + let oriented = match face.loops.get(u.r#loop as usize) { + Some(solidcore_record::brep::Loop::Edges { edges }) => edges.get(u.position as usize), + _ => None, + } + .ok_or_else(|| failed(format!("a use of edge {e}")))?; + let s = sign(u.face as usize).ok_or_else(|| failed(format!("face {} is in no shell", u.face)))?; + Use::new(face, s, &oriented.pcurve) + }; + let (a, b) = (use_of(ua)?, use_of(ub)?); + let degree = a.degree.saturating_add(b.degree); + if degree > MAX_DEGREE { + return Err(failed(format!("deciding tangency along edge {e}: its faces' normals are of degree {degree}"))); + } + let interval = edge.interval; + let mut breaks = Vec::new(); + a.breaks(interval, &mut breaks)?; + b.breaks(interval, &mut breaks)?; + breaks.retain(|t| *t >= interval[0] && *t <= interval[1]); + breaks.sort_by(f64::total_cmp); + breaks.dedup(); + let nodes = degree + 1; + if breaks.len().saturating_mul(nodes) > MAX_POINTS { + return Err(failed(format!("deciding tangency along edge {e}: {} pieces of degree {degree}", breaks.len()))); + } + let mut defined = false; + for w in breaks.windows(2) { + let &[t0, t1] = w else { continue }; + let (m, h) = (0.5 * (t0 + t1), 0.5 * (t1 - t0)); + if !(h > 0.0) { + continue; + } + for j in 0..nodes { + let t = m + h * ((2 * j + 1) as f64 * std::f64::consts::PI / (2 * nodes) as f64).cos(); + if let (Some(na), Some(nb)) = (a.normal(t)?, b.normal(t)?) { + defined = true; + if !visit(na, nb) { + return Ok(Some(true)); + } + } + } + } + Ok(Some(defined)) +} + +/// Whether edge `e`'s two uses' faces meet with outward normals within `max_angle` (radians) of +/// each other all along it, `sign(f)` turning face `f`'s natural normal outward. An edge with +/// other than two uses has no such pair: false. See the module documentation. +pub(crate) fn tangent_all_along(rec: &Brep, sign: impl Fn(usize) -> Option, e: usize, max_angle: f64) -> Result { + let cos = max_angle.cos(); + let mut tangent = true; + let Some(defined) = normal_pairs(rec, sign, e, |na, nb| { + tangent = na.dot(nb) >= cos; + tangent + })? + else { + return Ok(false); + }; + if !defined { + return Err(failed(format!("edge {e}: its faces' normals are undefined all along it"))); + } + Ok(tangent) +} + +/// The least angle (radians, 0 to π) between the outward normals of edge `e`'s two uses' faces +/// at the points [`normal_pairs`] visits: the edge's least angle where it is the same all along +/// the edge (two planes, a plane and a cylinder along a generator), at most a little above it +/// elsewhere. `None` for an edge with other than two uses, or whose normals are undefined +/// everywhere. +pub(crate) fn least_angle_along(rec: &Brep, sign: impl Fn(usize) -> Option, e: usize) -> Result> { + let mut least = f64::INFINITY; + let defined = normal_pairs(rec, sign, e, |na, nb| { + least = least.min(na.cross(nb).len().atan2(na.dot(nb))); + true + })?; + Ok(defined.filter(|d| *d).map(|_| least)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bernstein_roots_are_isolated_and_exact() { + // (s - 0.25)(s - 0.75) = s² - s + 3/16 in Bernstein form on [0, 1]: 3/16, 3/16 - 1/2, 3/16. + let c = [0.1875, 0.1875 - 0.5, 0.1875]; + let mut roots = Vec::new(); + let mut work = MAX_SUBDIVISIONS; + bernstein_roots(&c, 0.0, 1.0, MAX_DEPTH, &mut work, &mut roots); + roots.sort_by(f64::total_cmp); + assert_eq!(roots.len(), 2, "{roots:?}"); + assert!((roots[0] - 0.25).abs() < 1e-15 && (roots[1] - 0.75).abs() < 1e-15, "{roots:?}"); + // No sign change: no root. + let mut none = Vec::new(); + bernstein_roots(&[1.0, 0.5, 2.0], 0.0, 1.0, MAX_DEPTH, &mut work, &mut none); + assert!(none.is_empty()); + } + + #[test] + fn periodic_knot_lines_repeat_by_whole_periods() { + let sides = cell_sides(&[0.0, 1.0, 2.0], Some(2.0), 1.5, 4.5).unwrap(); + assert_eq!(sides, vec![2.0, 2.0, 3.0, 4.0, 4.0]); + } +} diff --git a/crates/kernel/src/taper_mesh_tests.rs b/crates/kernel/src/taper_mesh_tests.rs index 25c1aceae..9e0d754de 100644 --- a/crates/kernel/src/taper_mesh_tests.rs +++ b/crates/kernel/src/taper_mesh_tests.rs @@ -1,177 +1,45 @@ use super::*; -use mt::{ParameterDivision2D, ParametricSurface, ParametricSurface3D, SearchNearestParameter, SearchParameter}; -use truck_meshalgo::prelude::*; -fn wedge() -> (Body, RadiusSpline) { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; +/// A wedge 40 x 20, 15 high, its top front edge along x from 0 to 40. +fn wedge_body() -> Body { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; let outer = Loop2::polygon(&[Vec2::new(0., 0.), Vec2::new(40., 0.), Vec2::new(0., 20.)]); - let body = crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0., 15.).unwrap().pop().unwrap(); + crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0., 15.).unwrap().pop().unwrap() +} + +fn wedge() -> Body { + let body = wedge_body(); let at = Vec3::new(20., 0., 15.); - let (filleted, tapers) = fillet_tapered(&body, &[at], 16.).unwrap(); - let taper = tapers.into_iter().flatten().next().unwrap(); - (filleted, taper.spline) + // The room's taper, closing to zero at the wedge's tip, given as a spline fillet: R16 itself + // is built over the wedge's cliffs (the blend-overflow decision), so a tapered fillet no + // longer tapers it. + let t = taper(&body, at, 16.).unwrap(); + fillet_variable_spline(&body, at, t.start, &t.spline).unwrap() } -fn expected(law: &RadiusSpline) -> f64 { - let n = 20_000; - let integral = (0..n).map(|i| law.eval((i as f64 + 0.5) / n as f64).powi(2)).sum::() / n as f64; - 6000. - (1. - std::f64::consts::FRAC_PI_4) * 40. * integral -} - -fn mesh_volume(polygon: &PolygonMesh) -> f64 { - let positions = polygon.positions(); - polygon - .faces() - .triangle_iter() - .map(|t| { - let [a, b, c] = t.map(|v| positions[v.pos].to_vec()); - a.dot(b.cross(c)) / 6. - }) - .sum() +/// The wedge's variable round takes off the union of its balls (smlib#78, solidcore#2262): +/// `removed_by_balls` along the 40 mm edge, about 754.28, on whichever kernel the test runs. +#[test] +fn the_wedge_round_keeps_its_volume() { + let v = crate::measure(&wedge()).unwrap().volume; + let law = taper(&wedge_body(), Vec3::new(20., 0., 15.), 16.).unwrap().spline; + let want = 6000.0 - super::tests::removed_by_balls(40.0, &|u| law.eval(u), &|_, _| f64::INFINITY, &[]); + assert!(((v - want) / want).abs() < 1e-4, "{v} vs {want}"); } +/// The display mesh of a fillet tapering to zero at a wedge's tip converges to the B-rep: each +/// mesh lies within its chord tolerance of the faces, so its volume is within the body's area +/// times that tolerance of the exact one (SMLib's, integrated on the surfaces, to 1e-8). Only +/// the mesher is under test here; the taper's own law is `taper_follows_the_room_along_the_edge`'s. #[test] fn collapsed_taper_mesh_stays_accurate_as_tolerance_decreases() { - let (body, law) = wedge(); - let wanted = expected(&law); + let body = wedge(); + let exact = crate::measure(&body).unwrap(); for tol in [0.002, 0.001, 0.0005, 0.0002] { - for refine in [false, true] { - let mesh = body.tessellate_with(tol, refine).unwrap(); - assert!(mesh.positions.iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite())); - let got = mesh.measure().volume; - assert!((got - wanted).abs() / wanted < 1e-4, "tol={tol}, refine={refine}: {got} vs {wanted}"); - } + let mesh = body.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); + assert!(mesh.positions.iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite())); + let got = mesh.measure().volume; + let bound = exact.area * tol; + assert!((got - exact.volume).abs() <= bound, "tol={tol}: mesh {got} vs exact {} (within {bound})", exact.volume); } } - -/// A valid exact parameter search can choose any parameter along a collapsed -/// edge, even far outside its nominal range. Force that answer on every platform -/// instead of relying on the Windows Newton solve that originally exposed #796. -#[derive(Clone)] -struct ArbitraryPole(mt::Surface); -impl ParametricSurface for ArbitraryPole { - type Point = mt::Point3; - type Vector = mt::Vector3; - fn subs(&self, u: f64, v: f64) -> Self::Point { - self.0.subs(u, v) - } - fn uder(&self, u: f64, v: f64) -> Self::Vector { - self.0.uder(u, v) - } - fn vder(&self, u: f64, v: f64) -> Self::Vector { - self.0.vder(u, v) - } - fn uuder(&self, u: f64, v: f64) -> Self::Vector { - self.0.uuder(u, v) - } - fn uvder(&self, u: f64, v: f64) -> Self::Vector { - self.0.uvder(u, v) - } - fn vvder(&self, u: f64, v: f64) -> Self::Vector { - self.0.vvder(u, v) - } - fn parameter_range(&self) -> (mt::ParameterRange, mt::ParameterRange) { - self.0.parameter_range() - } - fn u_period(&self) -> Option { - self.0.u_period() - } - fn v_period(&self) -> Option { - self.0.v_period() - } -} -impl ParametricSurface3D for ArbitraryPole { - fn normal(&self, u: f64, v: f64) -> mt::Vector3 { - self.0.normal(u, v) - } -} -impl ParameterDivision2D for ArbitraryPole { - fn parameter_division(&self, range: ((f64, f64), (f64, f64)), tol: f64) -> (Vec, Vec) { - self.0.parameter_division(range, tol) - } -} -impl SearchParameter for ArbitraryPole { - type Point = mt::Point3; - fn search_parameter>(&self, point: mt::Point3, hint: H, trials: usize) -> Option<(f64, f64)> { - if matches!(self.0, mt::Surface::NurbsSurface(_)) && (point - mt::Point3::new(40., 0., 15.)).magnitude2() < 1e-20 { - Some((1., -1e14)) - } else { - self.0.search_parameter(point, hint, trials) - } - } -} -impl SearchNearestParameter for ArbitraryPole { - type Point = mt::Point3; - fn search_nearest_parameter>(&self, point: mt::Point3, hint: H, trials: usize) -> Option<(f64, f64)> { - self.0.search_nearest_parameter(point, hint, trials) - } -} - -#[test] -fn both_mesh_searches_keep_an_arbitrary_exact_pole_inside_the_domain() { - let (body, law) = wedge(); - let shell = body.solid.boundaries()[0].mapped(Clone::clone, Clone::clone, |s| ArbitraryPole(s.clone())); - for robust in [false, true] { - let mesh = if robust { shell.robust_triangulation(0.0005) } else { shell.triangulation(0.0005) }; - for (source, face) in shell.face_iter().zip(mesh.face_iter()) { - let polygon = face.surface().expect("valid pole must not discard its face"); - if matches!(source.surface().0, mt::Surface::NurbsSurface(_)) { - assert!(polygon.uv_coords().iter().all(|p| (-1e-6..=1. + 1e-6).contains(&p.x) && (-1e-6..=1. + 1e-6).contains(&p.y))); - } - } - let polygon = mesh.to_polygon(); - let volume = mesh_volume(&polygon); - assert!((volume - expected(&law)).abs() / expected(&law) < 1e-4, "robust={robust}: {volume}"); - } -} - -#[test] -fn bounded_projection_does_not_clip_a_planes_unbounded_support() { - let (body, law) = wedge(); - let shell = body.solid.boundaries()[0].mapped(Clone::clone, Clone::clone, |surface| { - if let mt::Surface::Plane(plane) = surface { - let origin = plane.subs(0., 0.); - mt::Surface::Plane(mt::Plane::new(origin, origin + plane.uder(0., 0.).normalize(), origin + plane.vder(0., 0.).normalize())) - } else { - surface.clone() - } - }); - for robust in [false, true] { - let mesh = if robust { shell.robust_triangulation(0.0005) } else { shell.triangulation(0.0005) }; - let mut outside = false; - for (source, face) in shell.face_iter().zip(mesh.face_iter()) { - let polygon = face.surface().unwrap(); - if matches!(source.surface(), mt::Surface::Plane(_)) { - outside |= polygon.uv_coords().iter().any(|p| p.x.abs() > 2. || p.y.abs() > 2.); - } - } - assert!(outside, "fixture must extend beyond the plane's nominal unit box"); - let got = mesh_volume(&mesh.to_polygon()); - assert!((got - expected(&law)).abs() / expected(&law) < 1e-4, "robust={robust}: {got}"); - } -} - -#[test] -fn provisional_preview_bounds_the_same_arbitrary_pole() { - use mt::{BoundedCurve, ParameterDivision1D, ParametricCurve}; - let (body, _) = wedge(); - let face = body.solid.face_iter().find(|f| matches!(f.surface(), mt::Surface::NurbsSurface(_))).unwrap(); - let loops: Vec> = face - .absolute_boundaries() - .iter() - .map(|wire| { - wire.edge_iter() - .flat_map(|edge| { - let curve = edge.oriented_curve(); - let (mut parameters, _) = curve.parameter_division(curve.range_tuple(), 0.01); - parameters.pop(); - parameters.into_iter().map(move |t| curve.subs(t)) - }) - .collect() - }) - .collect(); - let mesh = truck_meshalgo::tessellation::preview_face(&ArbitraryPole(face.surface()), &loops, 8).unwrap(); - assert!(mesh.faces().triangle_iter().next().is_some()); - assert!(mesh.positions().iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite())); - assert!(mesh.uv_coords().iter().all(|p| (-1e-6..=1. + 1e-6).contains(&p.x) && (-1e-6..=1. + 1e-6).contains(&p.y))); -} diff --git a/crates/kernel/src/tess/cdt.rs b/crates/kernel/src/tess/cdt.rs index c2d3c387e..465956ed6 100644 --- a/crates/kernel/src/tess/cdt.rs +++ b/crates/kernel/src/tess/cdt.rs @@ -5,13 +5,14 @@ //! the facet angle, then Ruppert refinement for shape. Constraint edges are never split, so the //! boundary stays exactly the shared edge nodes. +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use super::size::Turn; use spade::handles::FixedVertexHandle; -use spade::{AngleLimit, ConstrainedDelaunayTriangulation, Point2, RefinementParameters, Triangulation}; +use spade::{AngleLimit, ConstrainedDelaunayTriangulation, Point2, PositionInTriangulation, RefinementParameters, Triangulation}; type Cdt = ConstrainedDelaunayTriangulation>; @@ -50,8 +51,9 @@ pub(crate) struct Fill<'a> { /// varies: a plane is shaded the same by any triangles, so planar faces skip it (around many /// small holes it grades out from each rim and multiplies the triangles). pub shape: bool, - /// A side crossing one already kept is left out instead of refusing the loops (the last - /// resort for a boundary that crosses itself, see `fallback`). + /// A side crossing one already kept is left out instead of refusing the loops: the last + /// resort for a face whose boundary crosses itself in (u, v), so the display has no hole + /// (the planner names the face in its stats as a defect upstream). pub lenient: bool, } @@ -78,6 +80,16 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range index.entry(h).or_insert(u32::try_from(i).ok()?); handles.push(h); } + // A side the loops run along both ways (a slit, where a face's boundary goes out along a + // line its two sides share and back) bounds the face on neither. + let mut sides: Vec<(FixedVertexHandle, FixedVertexHandle)> = Vec::new(); + for r in loops { + let n = r.len(); + for k in 0..n { + sides.push((*handles.get(r.start + k)?, *handles.get(r.start + (k + 1) % n)?)); + } + } + let slits = slits(&sides); for r in loops { let n = r.len(); for k in 0..n { @@ -101,7 +113,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range } if let Some((sag, budget)) = &fill.refine { let constraints = cdt.num_constraints(); - let added = refine_sag(&mut cdt, sag, *budget, &from); + let added = refine_sag(&mut cdt, sag, *budget, &from, &slits); if fill.shape { let params = RefinementParameters::::new() .keep_constraint_edges() @@ -114,7 +126,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range // Shaping flips sides and adds points of its own; the triangles it leaves may // sag again (a long strip round a cylinder), so the sag is checked once more. if shaped > 0 { - refine_sag(&mut cdt, sag, budget.saturating_sub(added + shaped), &from); + refine_sag(&mut cdt, sag, budget.saturating_sub(added + shaped), &from, &slits); } } // A split constraint would put a point on the boundary the neighbour does not have. @@ -124,7 +136,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range } let mut uv: Vec<[f64; 2]> = boundary.to_vec(); let mut tris = Vec::new(); - let region = region(&cdt); + let region = region(&cdt, &slits); for face in cdt.inner_faces() { if !region.get(face.index()).copied().unwrap_or(false) { continue; @@ -184,6 +196,8 @@ pub(crate) fn band(points: &[[f64; 2]], n: usize, loops: &[std::ops::Range) -> [f64; 2]) -> usize { +/// `slits`: constraint sides the loops run along both ways, inside the region on both sides. +fn refine_sag( + cdt: &mut Cdt, + sag: &Sag, + budget: usize, + from: &dyn Fn(Point2) -> [f64; 2], + slits: &std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)>, +) -> usize { let mut added = 0; let mut cache: HashMap)>> = HashMap::new(); // The widest turn between two corner normals. @@ -231,7 +252,7 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2 (sag.eval)(q[0], q[1]) }) }; - let region = region(cdt); + let region = region(cdt, slits); for face in cdt.inner_faces() { if !region.get(face.index()).copied().unwrap_or(false) { continue; @@ -250,7 +271,22 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2 let off = |q: Point2, chord: Vec3| gap(q, chord) > sag.tol; let middle = gap(c, (a + b + d) * (1.0 / 3.0)); if middle > sag.tol || sag.turn.is_some_and(|t| t.exceeds(spread([na, nb, nd]), middle)) { - todo.push(c); + // A triangle's centroid is inside it, but for a sliver whose corners lie on one line + // to rounding: an ear on consecutive boundary nodes of a nearly straight stretch. Its + // centroid lies on the boundary chord, and inserting it there would split the + // boundary, which the neighbouring face shares. Such a sliver is split at the middles + // of its inner edges instead. + let on_boundary = matches!(cdt.locate(c), PositionInTriangulation::OnEdge(e) if cdt.is_constraint_edge(e.as_undirected())); + if !on_boundary { + todo.push(c); + continue; + } + for e in face.adjacent_edges() { + if !e.is_constraint_edge() { + let [p, q] = e.positions(); + todo.push(Point2::new(0.5 * (p.x + q.x), 0.5 * (p.y + q.y))); + } + } continue; } for (e, (pa, pb)) in face.adjacent_edges().into_iter().zip([(a, b), (b, d), (d, a)]) { @@ -273,7 +309,14 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2 if added >= budget { return added; } - if insert_off_boundary(cdt, p) { + // The boundary's nodes are its edges', shared with the neighbouring face: a point that + // lands on the boundary (a sliver's middle on a nearly straight stretch, on the chord to + // rounding) is no inner point, and inserting it would split the boundary. + let p = spade::mitigate_underflow(p); + if matches!(cdt.locate(p), PositionInTriangulation::OnEdge(e) if cdt.is_constraint_edge(e.as_undirected())) { + continue; + } + if cdt.insert(p).is_ok() { added += 1; } } @@ -281,34 +324,35 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2 added } -/// Insert `p` unless it lies exactly on a side of the boundary (the middle of a sliver along -/// it, at a cone's apex): that would split the side, while the face's boundary nodes are shared -/// with its neighbours, which would not have the new one, and the face lost its plan. -fn insert_off_boundary(cdt: &mut Cdt, p: Point2) -> bool { - let p = spade::mitigate_underflow(p); - if !(p.x.is_finite() && p.y.is_finite()) { - return false; +/// The sides a boundary runs along an even number of times (a slit: out along a line and back), +/// each as its vertices in index order: the region lies on both sides of them. +fn slits(sides: &[(FixedVertexHandle, FixedVertexHandle)]) -> std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)> { + let mut runs: HashMap<(FixedVertexHandle, FixedVertexHandle), usize> = HashMap::new(); + for &(a, b) in sides { + if a != b { + *runs.entry(if a.index() < b.index() { (a, b) } else { (b, a) }).or_insert(0) += 1; + } } - if let spade::PositionInTriangulation::OnEdge(e) = cdt.locate(p) - && cdt.is_constraint_edge(e.as_undirected()) - { - return false; - } - cdt.insert(p).is_ok() + runs.into_iter().filter(|(_, n)| n % 2 == 0).map(|(e, _)| e).collect() } /// Per face (by index): inside the region the constraint loops bound. A flood fill from the -/// outer face that flips parity each time it crosses a constraint edge (holes are out), linear -/// in the number of triangles. -fn region(cdt: &Cdt) -> Vec { +/// outer face that flips parity each time it crosses a constraint edge (holes are out), but for +/// the sides in `slits` (run along both ways, the region on both sides), linear in the number of +/// triangles. +fn region(cdt: &Cdt, slits: &std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)>) -> Vec { use spade::handles::{FixedFaceHandle, InnerTag}; + let counts = |e: spade::handles::DirectedEdgeHandle<'_, _, _, _, _>| { + let [a, b] = e.vertices().map(|v| v.fix()); + e.is_constraint_edge() && !slits.contains(&if a.index() < b.index() { (a, b) } else { (b, a) }) + }; let mut parity: Vec> = vec![None; cdt.num_all_faces()]; let mut todo: Vec<(FixedFaceHandle, bool)> = Vec::new(); for e in cdt.convex_hull() { // Hull edges have the outer face on one side; the other side is an inner face. for side in [e, e.rev()] { if let Some(inner) = side.face().as_inner() { - todo.push((inner.fix(), e.is_constraint_edge())); + todo.push((inner.fix(), counts(e))); } } } @@ -319,7 +363,7 @@ fn region(cdt: &Cdt) -> Vec { } for e in cdt.face(h).adjacent_edges() { if let Some(next) = e.rev().face().as_inner() { - todo.push((next.fix(), odd ^ e.is_constraint_edge())); + todo.push((next.fix(), odd ^ counts(e))); } } } @@ -332,13 +376,36 @@ fn region(cdt: &Cdt) -> Vec { /// out) and at least [`CLEARANCE`] of a side from the boundary in the metric `scale`. pub(crate) fn lattice(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2]]], scale: [f64; 2]) -> Vec<[f64; 2]> { let mut out = Vec::new(); + scan(bbox, step, polys, scale, &mut |q| { + out.push(q); + true + }); + out +} + +/// Whether the face has room for a seed of [`lattice`]: somewhere inside it lies a lattice point +/// clear of its boundary. A face narrower than the side everywhere (a thin strip) has none. +/// `true` too when the lattice is more than [`MAX_SEEDS`] points (or the box or step is not +/// finite), which [`lattice`] does not look through. +pub(crate) fn has_room(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2]]], scale: [f64; 2]) -> bool { + let mut found = false; + let scanned = scan(bbox, step, polys, scale, &mut |_| { + found = true; + false + }); + found || !scanned +} + +/// Visit the points of [`lattice`] in turn until `visit` returns `false`. Returns whether the +/// lattice was looked through (it is not when it is too large or ill-formed). +fn scan(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2]]], scale: [f64; 2], visit: &mut dyn FnMut([f64; 2]) -> bool) -> bool { if !step.iter().all(|s| s.is_finite() && *s > 0.0) || !bbox.iter().all(|(a, b)| a.is_finite() && b.is_finite() && b > a) { - return out; + return false; } let row = step[1] * 3f64.sqrt() * 0.5; let (rows, cols) = (((bbox[1].1 - bbox[1].0) / row).ceil(), ((bbox[0].1 - bbox[0].0) / step[0]).ceil()); if !(rows * cols <= MAX_SEEDS as f64) { - return out; + return false; } let near = Clearance::new(polys, scale, CLEARANCE * step[0] * scale[0]); let mut xs: Vec = Vec::new(); @@ -358,12 +425,12 @@ pub(crate) fn lattice(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2] let shift = if j % 2 == 1 { 0.5 * step[0] } else { 0.0 }; for i in 0..=cols as usize { let u = bbox[0].0 + shift + step[0] * i as f64; - if u < bbox[0].1 && xs.partition_point(|x| *x < u) % 2 == 1 && !near.within([u, v]) { - out.push([u, v]); + if u < bbox[0].1 && xs.partition_point(|x| *x < u) % 2 == 1 && !near.within([u, v]) && !visit([u, v]) { + return true; } } } - out + true } /// Most lattice seeds of one face. @@ -473,25 +540,15 @@ mod tests { } #[test] - fn a_point_on_a_boundary_side_is_not_inserted() { - let mut cdt = Cdt::new(); - let corners = [[0.0, 0.0], [4.0, 0.0], [4.0, 1.0], [0.0, 1.0]]; - let Ok(handles) = corners.iter().map(|p| cdt.insert(Point2::new(p[0], p[1]))).collect::, _>>() else { panic!("insert") }; - for k in 0..4 { - cdt.add_constraint(handles[k], handles[(k + 1) % 4]); - } - assert!(!insert_off_boundary(&mut cdt, Point2::new(2.0, 0.0))); - assert!(!insert_off_boundary(&mut cdt, Point2::new(f64::NAN, 0.5))); - assert_eq!((cdt.num_constraints(), cdt.num_vertices()), (4, 4)); - assert!(insert_off_boundary(&mut cdt, Point2::new(2.0, 0.5))); - assert_eq!((cdt.num_constraints(), cdt.num_vertices()), (4, 5)); - } - - #[test] - fn crossing_loops_are_refused() { + fn crossing_loops_are_refused_unless_lenient() { let b = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]]; let whole = std::slice::from_ref(&(0..4)); assert!(triangulate(&b, whole, Fill { seeds: &[], refine: None, shape: false, lenient: false }).is_none()); + // Lenient, the crossing side is left out and what the rest encloses is filled. + let Some((_, tris)) = triangulate(&b, whole, Fill { seeds: &[], refine: None, shape: false, lenient: true }) else { + panic!("a lenient fill") + }; + assert!(!tris.is_empty()); } #[test] diff --git a/crates/kernel/src/tess/coons.rs b/crates/kernel/src/tess/coons.rs index e803f7dc4..56d4ecee3 100644 --- a/crates/kernel/src/tess/coons.rs +++ b/crates/kernel/src/tess/coons.rs @@ -4,7 +4,8 @@ //! A blend that folds (a strongly non-convex boundary) is refused, and the face goes to the //! constrained Delaunay path. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; /// Smallest turn (radians) of the boundary at a corner, in the tolerance metric. const CORNER_TURN: f64 = 0.6; diff --git a/crates/kernel/src/tess/cutgrid.rs b/crates/kernel/src/tess/cutgrid.rs index 5c8f11099..64db1a54b 100644 --- a/crates/kernel/src/tess/cutgrid.rs +++ b/crates/kernel/src/tess/cutgrid.rs @@ -86,8 +86,20 @@ pub(crate) fn cut_grid( // Traces on u = c (axis 0) are lines in u; on v = c, lines in v. let tu: Vec<&Trace> = traces.iter().filter(|t| t.axis == 0).collect(); let tv: Vec<&Trace> = traces.iter().filter(|t| t.axis == 1).collect(); - let (lu, pu) = lines(us, &tu.iter().map(|t| t.at).collect::>())?; - let (lv, pv) = lines(vs, &tv.iter().map(|t| t.at).collect::>())?; + // Room for the traces' lines among the grid's: the full lines are thinned (as the face's + // grid is) until the cells fit, rather than the face falling through to Delaunay, whose + // refinement budget a grid this size is past. + let (mut us, mut vs) = (us.to_vec(), vs.to_vec()); + let cells = |us: &[f64], vs: &[f64]| (us.len() + tu.len()).saturating_sub(1).saturating_mul((vs.len() + tv.len()).saturating_sub(1)); + for _ in 0..64 { + if cells(&us, &vs) <= super::grid::MAX_FACE_GRID || (us.len() <= 2 && vs.len() <= 2) { + break; + } + let cap = us.len().saturating_mul(vs.len()).saturating_mul(9) / 10; + super::grid::thin(&mut us, &mut vs, cap); + } + let (lu, pu) = lines(&us, &tu.iter().map(|t| t.at).collect::>())?; + let (lv, pv) = lines(&vs, &tv.iter().map(|t| t.at).collect::>())?; let (nu, nv) = (lu.at.len(), lv.at.len()); let (cu, cv) = (nu - 1, nv - 1); let cells = cu.checked_mul(cv)?; diff --git a/crates/kernel/src/tess/edges.rs b/crates/kernel/src/tess/edges.rs index bccd3db5f..f67c4f28c 100644 --- a/crates/kernel/src/tess/edges.rs +++ b/crates/kernel/src/tess/edges.rs @@ -1,151 +1,212 @@ //! Edge nodes: every edge of a body sampled once, so the faces on either side share the very //! same boundary points (watertight by construction). -use solidcraft_geom::Vec3; -use truck_meshalgo::prelude::*; -use truck_modeling as mt; - -use solidcraft_geom::tess::EvalSurface; +use solidcore_record::Vec3; +use solidcore_record::brep::{self, Curve}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::prelude::*; use super::size::Rules; -use crate::body::from_p3; +use crate::{KernelError, Result}; /// Most nodes on one edge. pub(crate) const MAX_EDGE_NODES: usize = 20_000; /// Deepest bisection of one edge segment. const MAX_DEPTH: u32 = 24; +/// The most of its curve's turn one segment may span (a quarter turn, with rounding room): the +/// boundary of every face stays a polygon with the face's area, as a closed curve's first four +/// segments keep it. +pub(crate) const QUARTER_TURN: f64 = std::f64::consts::FRAC_PI_2 * (1.0 + 1e-9); -/// An edge's nodes, from its absolute front to its absolute back. +/// An edge's nodes, from its start vertex (interval min) to its end vertex (interval max). pub(crate) struct Nodes { pub points: Vec, - /// For an intersection edge: its two surfaces and, per node, both surfaces' parameters - /// (u1, v1, u2, v2) where Newton placed the node (`None` where truck's evaluation did). - pub on: Option<([EvalSurface; 2], Vec>)>, + /// The curve's parameter at each node (the edge's interval, ends included): where each + /// face's pcurve of the edge gives the node's (u, v). + pub params: Vec, + /// The parameters of the nodes that are another edge's node, where the two edges touch + /// within the chord tolerance (see [`snap`]): in a face that runs both edges such a node is + /// the other's point of the face, a pinch, not a crossing. + pub snapped: Vec, } -impl Nodes { - fn plain(points: Vec) -> Nodes { - Nodes { points, on: None } - } - - /// The parameters of each node on `surface`, where the edge knows them: `None` unless - /// `surface` is one of the edge's two surfaces. - pub(crate) fn params_on(&self, surface: &EvalSurface) -> Option>> { - let (surfaces, params) = self.on.as_ref()?; - let side = surfaces.iter().position(|s| s == surface)?; - Some(params.iter().map(|q| q.map(|q| [q[2 * side], q[2 * side + 1]])).collect()) - } -} - -/// Nodes of `edge` from its absolute front to its absolute back: every chord within the -/// tolerance of the curve (checked at the quarter points, so an S-bend in one segment is not -/// missed), at most `h` long, and within the rules' facet angle. The end nodes are the -/// vertices' own points, so edges meeting at a vertex meet exactly. -pub(crate) fn sample_edge(edge: &mt::Edge, rules: &Rules, h: f64) -> Nodes { +/// Nodes of edge `ei` of `b` from its start to its end: every chord within the tolerance of +/// the curve (checked at the quarter points, so an S-bend in one segment is not missed), at +/// most `h` long, within the rules' facet angle and never spanning more than a quarter turn of +/// the curve. The end nodes are the vertices' own points, so edges meeting at a vertex meet +/// exactly. A curve that does not evaluate somewhere on its interval is an error naming the +/// edge. +pub(crate) fn sample_edge(b: &brep::Brep, ei: usize, rules: &Rules, h: f64) -> Result { + let fail = |why: String| KernelError::Failed(format!("tessellation: edge {ei}: {why}")); + let edge = b.edges.get(ei).ok_or_else(|| fail("no such edge".into()))?; + let vertex = |k: usize| { + let v = edge.vertices.get(k).and_then(|&v| b.vertices.get(v as usize)).ok_or_else(|| fail("no such vertex".into()))?; + Ok::(Vec3::new(v.point[0], v.point[1], v.point[2])) + }; + let (front, back) = (vertex(0)?, vertex(1)?); let tol = rules.tol; - let front = from_p3(edge.absolute_front().point()); - let back = from_p3(edge.absolute_back().point()); - let curve = edge.curve(); - if matches!(curve, mt::Curve::Line(_)) { + let [t0, t1] = edge.interval; + if !(t0.is_finite() && t1.is_finite() && t1 > t0) { + return Err(fail(format!("interval [{t0}, {t1}]"))); + } + if matches!(edge.curve, Curve::Line { .. }) { // Evenly, as few segments as keep each at most `h`. The ends are the vertices' own // points: `front + (back − front) · 1` is not `back` to the last bit, and the face that // runs the edge backwards starts its loop with that node, where the face running it // forwards takes the next edge's first node (the vertex) — a crack. let n = if h > 0.0 { (front.dist(back) / h).ceil().clamp(1.0, (MAX_EDGE_NODES - 1) as f64) as usize } else { 1 }; let mut pts: Vec = (0..=n).map(|i| front + (back - front) * (i as f64 / n as f64)).collect(); - if let Some(p) = pts.last_mut() { + let mut params: Vec = (0..=n).map(|i| t0 + (t1 - t0) * (i as f64 / n as f64)).collect(); + if let (Some(p), Some(t)) = (pts.last_mut(), params.last_mut()) { *p = back; + *t = t1; } - return Nodes::plain(pts); + return Ok(Nodes { points: pts, params, snapped: Vec::new() }); } - let (t0, t1) = curve.range_tuple(); - if !(t0.is_finite() && t1.is_finite() && t1 > t0) { - return Nodes::plain(vec![front, back]); - } - // Our evaluators: the curve's own form where it has one (no allocation per point); for an - // intersection curve, Newton on both surfaces from seeded parameters (see `ssi`), which - // also gives each node's parameters on both faces; truck's evaluation only where that does - // not converge. - let fast = super::surface::eval_curve(&curve); - let ssi = if fast.is_none() { super::ssi::Intersection::new(&curve) } else { None }; - type Pt = (Vec3, Option<[f64; 4]>); - let at = |t: f64| -> Option { - match (&fast, &ssi) { - (Some(c), _) => c.eval(t).map(|(p, _)| (p, None)), - (None, Some(ix)) => ix.eval(t).map(|(p, q)| (p, Some(q))).or_else(|| Some((from_p3(curve.subs(t)), None))), - (None, None) => Some((from_p3(curve.subs(t)), None)), - } - .filter(|(p, _)| p.is_finite()) - }; - let fallback = || Nodes::plain(vec![front, back]); + let curve = CurveEval::new(edge.parameters()).map_err(|e| fail(e.to_string()))?; + let at = + |t: f64| -> Result { curve.point(t).filter(|p| p.is_finite()).ok_or_else(|| fail(format!("the curve does not evaluate at t = {t}"))) }; // A closed curve's chord between its ends is empty: start it from a few segments. An open // one starts whole, so an arc the tolerance leaves flat stays one segment. - let initial: u32 = if edge.absolute_front().id() == edge.absolute_back().id() { 4 } else { 1 }; + let initial: u32 = if edge.vertices[0] == edge.vertices[1] { 4 } else { 1 }; let t_at = |i: u32| t0 + (t1 - t0) * f64::from(i) / f64::from(initial); - let mut ends: Vec = Vec::with_capacity(initial as usize + 1); - for i in 0..=initial { - let Some(p) = at(t_at(i)) else { return fallback() }; - ends.push(p); - } + let ends: Vec = (0..=initial).map(|i| at(t_at(i))).collect::>()?; // Depth-first bisection, segment by segment, keeping the output ordered. Each segment // carries its end points and middle, so every parameter is evaluated once (an // intersection curve's point is a Newton solve). struct Seg { a: f64, b: f64, - pa: Pt, - pb: Pt, - mid: Option, + pa: Vec3, + pb: Vec3, + mid: Option, depth: u32, } - let Some(&first) = ends.first() else { return fallback() }; - let mut out: Vec = vec![(front, first.1)]; + let mut out: Vec<(f64, Vec3)> = vec![(t0, front)]; let mut stack: Vec = Vec::with_capacity(64); - for i in (0..initial).rev() { - let (Some(pa), Some(pb)) = (<[Pt]>::get(&ends, i as usize).copied(), <[Pt]>::get(&ends, i as usize + 1).copied()) else { - return fallback(); - }; + for (i, w) in ends.windows(2).enumerate().rev() { + let (Some(&pa), Some(&pb)) = (w.first(), w.get(1)) else { continue }; + let i = i as u32; stack.push(Seg { a: t_at(i), b: t_at(i + 1), pa, pb, mid: None, depth: 0 }); } while let Some(sg) = stack.pop() { let (a, b, pa, pb) = (sg.a, sg.b, sg.pa, sg.pb); let m = 0.5 * (a + b); let pm = match sg.mid { - Some(p) => Some(p), - None => at(m), + Some(p) => p, + None => at(m)?, }; - let (q1, q3) = (at(a + 0.25 * (b - a)), at(a + 0.75 * (b - a))); + let (q1, q3) = (at(a + 0.25 * (b - a))?, at(a + 0.75 * (b - a))?); let done = sg.depth >= MAX_DEPTH || out.len() + stack.len() >= MAX_EDGE_NODES; let fine = || { - let sag = [q1, pm, q3].iter().flatten().map(|q| q.0.dist_to_segment(pa.0, pb.0)).fold(0.0, f64::max); - let short = !(pa.0.dist(pb.0) > h * (1.0 + 1e-9)); + let sag = [q1, pm, q3].iter().map(|q| q.dist_to_segment(pa, pb)).fold(0.0, f64::max); + let short = !(pa.dist(pb) > h * (1.0 + 1e-9)); // The two half chords of an arc turning θ differ by θ/2. - let straight = match (rules.turn, pm) { - (Some(t), Some(q)) => !t.exceeds(2.0 * turn(q.0 - pa.0, pb.0 - q.0), sag), - _ => true, - }; - short && straight && sag <= tol + let bend = 2.0 * turn(pm - pa, pb - pm); + let straight = rules.turn.is_none_or(|t| !t.exceeds(bend, sag)); + // Whatever the tolerance, no segment spans more than a quarter turn of its curve: a + // small circle split into two half arcs would otherwise be two chords on one line, + // a hole of no area (the 1 mm hole of a 990 mm plate at its 2 mm chord). + let quarter = bend <= QUARTER_TURN; + short && straight && quarter && sag <= tol }; - match pm { - Some(pm) if !done && !fine() => { - stack.push(Seg { a: m, b, pa: pm, pb, mid: q3, depth: sg.depth + 1 }); - stack.push(Seg { a, b: m, pa, pb: pm, mid: q1, depth: sg.depth + 1 }); - } - _ => out.push(pb), + if !done && !fine() { + stack.push(Seg { a: m, b, pa: pm, pb, mid: Some(q3), depth: sg.depth + 1 }); + stack.push(Seg { a, b: m, pa, pb: pm, mid: Some(q1), depth: sg.depth + 1 }); + } else { + out.push((b, pb)); } } - if out.len() < 2 { - return fallback(); - } if let Some(p) = out.last_mut() { - p.0 = back; + *p = (t1, back); } - let on = ssi.map(|ix| (ix.surfaces().clone(), out.iter().map(|p| p.1).collect())); - Nodes { points: out.into_iter().map(|p| p.0).collect(), on } + Ok(Nodes { points: out.iter().map(|p| p.1).collect(), params: out.iter().map(|p| p.0).collect(), snapped: Vec::new() }) +} + +/// Edge `ei`'s nodes with each of its segments `segs` (counted from its start) halved at the +/// middle of its curve parameters, the new node on the curve (on a line, halfway between the two, +/// as [`sample_edge`] spaces a line's nodes). A segment too short to halve in floating point keeps +/// its two nodes. More than [`MAX_EDGE_NODES`] nodes, or a curve that does not evaluate there, is +/// an error naming the edge. +pub(crate) fn split_segments(b: &brep::Brep, ei: usize, nodes: &mut Nodes, segs: &[u32]) -> Result<()> { + let fail = |why: String| KernelError::Failed(format!("tessellation: edge {ei}: {why}")); + let edge = b.edges.get(ei).ok_or_else(|| fail("no such edge".into()))?; + let mut segs = segs.to_vec(); + segs.sort_unstable(); + segs.dedup(); + let n = nodes.points.len().min(nodes.params.len()); + if n + segs.len() > MAX_EDGE_NODES { + return Err(fail(format!("more than {MAX_EDGE_NODES} nodes"))); + } + let curve = match edge.curve { + Curve::Line { .. } => None, + _ => Some(CurveEval::new(edge.parameters()).map_err(|e| fail(e.to_string()))?), + }; + let (mut points, mut params) = (Vec::with_capacity(n + segs.len()), Vec::with_capacity(n + segs.len())); + let mut next = segs.iter().copied().peekable(); + for k in 0..n { + let (Some(&p), Some(&t)) = (nodes.points.get(k), nodes.params.get(k)) else { continue }; + points.push(p); + params.push(t); + if next.next_if_eq(&(k as u32)).is_none() { + continue; + } + let (Some(&q), Some(&u)) = (nodes.points.get(k + 1), nodes.params.get(k + 1)) else { continue }; + let m = 0.5 * (t + u); + if !(m > t.min(u) && m < t.max(u)) { + continue; + } + let pm = match &curve { + None => (p + q) * 0.5, + Some(c) => c.point(m).filter(|p| p.is_finite()).ok_or_else(|| fail(format!("the curve does not evaluate at t = {m}")))?, + }; + points.push(pm); + params.push(m); + } + nodes.points = points; + nodes.params = params; + Ok(()) +} + +/// Edge `ei`'s nodes with `add` (each a parameter strictly inside a segment and the point there) +/// put in, in order, each marked as snapped: the point is another edge's node within the chord +/// tolerance of this edge's chord there (the edges touch), so the two edges share it. A parameter +/// that is not strictly between its segment's two (a node already there) is left out. More than +/// [`MAX_EDGE_NODES`] nodes is an error naming the edge. +pub(crate) fn snap(ei: usize, nodes: &mut Nodes, add: &[(f64, Vec3)]) -> Result<()> { + let mut add: Vec<(f64, Vec3)> = add.iter().copied().filter(|(t, p)| t.is_finite() && p.is_finite()).collect(); + add.sort_by(|a, b| a.0.total_cmp(&b.0)); + add.dedup_by(|a, b| a.0 == b.0); + if nodes.points.len() + add.len() > MAX_EDGE_NODES { + return Err(KernelError::Failed(format!("tessellation: edge {ei}: more than {MAX_EDGE_NODES} nodes"))); + } + let n = nodes.points.len().min(nodes.params.len()); + let (mut points, mut params) = (Vec::with_capacity(n + add.len()), Vec::with_capacity(n + add.len())); + let mut next = add.iter().peekable(); + for k in 0..n { + let (Some(&p), Some(&t)) = (nodes.points.get(k), nodes.params.get(k)) else { continue }; + points.push(p); + params.push(t); + let Some(&u) = nodes.params.get(k + 1) else { continue }; + while let Some(&&(m, q)) = next.peek() { + if m >= u { + break; + } + next.next(); + if m > t { + points.push(q); + params.push(m); + nodes.snapped.push(m); + } + } + } + nodes.points = points; + nodes.params = params; + Ok(()) } /// Angle (radians) between two directions; zero when either is empty. -fn turn(a: Vec3, b: Vec3) -> f64 { +pub(crate) fn turn(a: Vec3, b: Vec3) -> f64 { let (la, lb) = (a.len(), b.len()); if !(la > 0.0 && lb > 0.0) { return 0.0; @@ -157,16 +218,38 @@ fn turn(a: Vec3, b: Vec3) -> f64 { mod tests { use super::*; + fn record(b: crate::Result) -> brep::Brep { + match b.and_then(|b| crate::brep_record(&b)) { + Ok(r) => r, + Err(e) => panic!("{e}"), + } + } + + fn sample(b: &brep::Brep, ei: usize, rules: &Rules, h: f64) -> Nodes { + match sample_edge(b, ei, rules, h) { + Ok(n) => n, + Err(e) => panic!("{e}"), + } + } + + fn ends(b: &brep::Brep, ei: usize) -> [Vec3; 2] { + b.edges[ei].vertices.map(|v| { + let p = b.vertices[v as usize].point; + Vec3::new(p[0], p[1], p[2]) + }) + } + #[test] fn circle_edges_are_within_tolerance_and_end_on_vertices() { - let Ok(cyl) = crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0) else { panic!("cylinder") }; + let cyl = record(crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0)); for tol in [0.1, 0.01, 0.001] { - for e in cyl.solid.edge_iter() { - let pts = sample_edge(&e, &Rules { tol, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, f64::INFINITY).points; + for (ei, e) in cyl.edges.iter().enumerate() { + let pts = sample(&cyl, ei, &Rules { tol, max_len: f64::INFINITY, turn: None }, f64::INFINITY).points; assert!(pts.len() >= 2); - assert_eq!(pts.first().copied(), Some(from_p3(e.absolute_front().point()))); - assert_eq!(pts.last().copied(), Some(from_p3(e.absolute_back().point()))); - if matches!(e.curve(), mt::Curve::Line(_)) { + let [front, back] = ends(&cyl, ei); + assert_eq!(pts.first().copied(), Some(front)); + assert_eq!(pts.last().copied(), Some(back)); + if matches!(e.curve, Curve::Line { .. }) { assert_eq!(pts.len(), 2); continue; } @@ -182,60 +265,61 @@ mod tests { #[test] fn edges_are_split_to_the_side_length_and_turn() { - let Ok(cyl) = crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0) else { panic!("cylinder") }; - for e in cyl.solid.edge_iter() { - let pts = sample_edge(&e, &Rules { tol: 1.0, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, 1.2).points; + let cyl = record(crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0)); + for (ei, e) in cyl.edges.iter().enumerate() { + let pts = sample(&cyl, ei, &Rules { tol: 1.0, max_len: f64::INFINITY, turn: None }, 1.2).points; for w in pts.windows(2) { assert!(w[0].dist(w[1]) <= 1.2 + 1e-9, "side {}", w[0].dist(w[1])); } - if matches!(e.curve(), mt::Curve::Line(_)) { + if matches!(e.curve, Curve::Line { .. }) { // 5 mm in sides of at most 1.2: five equal sides. assert_eq!(pts.len(), 6); } // The ends are the vertices' own points, to the last bit. - assert_eq!(pts.first().copied(), Some(from_p3(e.absolute_front().point()))); - assert_eq!(pts.last().copied(), Some(from_p3(e.absolute_back().point()))); + let [front, back] = ends(&cyl, ei); + assert_eq!(pts.first().copied(), Some(front)); + assert_eq!(pts.last().copied(), Some(back)); } // A coarse tolerance alone would leave a few long chords; a 30° facet angle keeps every // side within 30° of arc: at least 12 around each of the two circles. - let thirty = Rules { - tol: 5.0, - max_len: f64::INFINITY, - extent: 0.0, - turn: Some(crate::tess::size::Turn { angle: std::f64::consts::PI / 6.0, floor: 0.0 }), - boundary_tol: None, - }; - let mut seen = std::collections::HashSet::new(); - let sides: usize = cyl - .solid - .edge_iter() - .filter(|e| seen.insert(e.id()) && !matches!(e.curve(), mt::Curve::Line(_))) - .map(|e| sample_edge(&e, &thirty, f64::INFINITY).points.len() - 1) + let thirty = + Rules { tol: 5.0, max_len: f64::INFINITY, turn: Some(crate::tess::size::Turn { angle: std::f64::consts::PI / 6.0, floor: 0.0 }) }; + let sides: usize = (0..cyl.edges.len()) + .filter(|&ei| !matches!(cyl.edges[ei].curve, Curve::Line { .. })) + .map(|ei| sample(&cyl, ei, &thirty, f64::INFINITY).points.len() - 1) .sum(); assert!(sides >= 24, "{sides}"); } - /// An intersection edge's nodes carry their parameters on both faces: each face on one of - /// the edge's surfaces gets them, and the surface there is the node. + /// The nodes of every edge where two curved faces meet carry their curve parameters: each + /// face's pcurve of the edge puts each node on that face's surface, at the node. #[test] - fn intersection_nodes_carry_their_parameters_on_both_faces() { - let Ok(pin) = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 6.0) else { panic!("pin") }; - let Ok(cross) = crate::cylinder(Vec3::new(5.0, -1.0, 2.0), Vec3::Y, 1.0, 12.0) else { panic!("cross") }; - let Ok(Some(body)) = crate::boolean(&pin, &cross, crate::BoolOp::Cut) else { panic!("cut") }; - let rules = Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }; - let surfaces: Vec = body.solid.face_iter().filter_map(|f| super::super::surface::eval_surface(&f.surface())).collect(); + fn edge_nodes_carry_their_parameters_on_both_faces() { + let pin = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 6.0); + let cross = crate::cylinder(Vec3::new(5.0, -1.0, 2.0), Vec3::Y, 1.0, 12.0); + let body = record(pin.and_then(|pin| { + let cross = cross?; + crate::boolean(&pin, &cross, crate::BoolOp::Cut)?.ok_or_else(|| crate::KernelError::Failed("cut: nothing left".into())) + })); + let rules = Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }; + let curved = |f: u32| !matches!(body.faces[f as usize].surface, brep::Surface::Plane { .. } | brep::Surface::PlaneThrough { .. }); let (mut edges, mut checked) = (0, 0); - let mut seen = std::collections::HashSet::new(); - for e in body.solid.edge_iter().filter(|e| seen.insert(e.id()) && matches!(e.curve(), mt::Curve::IntersectionCurve(_))) { - let n = sample_edge(&e, &rules, f64::INFINITY); - let on: Vec<_> = surfaces.iter().filter_map(|s| n.params_on(s).map(|q| (s, q))).collect(); - assert_eq!(on.len(), 2, "both faces of an intersection edge know its parameters"); + for (ei, e) in body.edges.iter().enumerate() { + if e.uses.len() != 2 || !e.uses.iter().all(|u| curved(u.face)) { + continue; + } + let n = sample(&body, ei, &rules, f64::INFINITY); edges += 1; - for (s, q) in on { - for (p, uv) in n.points.iter().zip(q).skip(1).take(n.points.len().saturating_sub(2)) { - let Some(uv) = uv else { continue }; - let Some((at, _, _)) = s.derivs(uv[0], uv[1]) else { panic!("evaluates") }; - assert!(at.dist(*p) < 1e-7, "{at:?} vs {p:?}"); + for u in &e.uses { + let face = &body.faces[u.face as usize]; + let brep::Loop::Edges { edges: loop_edges } = &face.loops[u.r#loop as usize] else { panic!("an edge loop") }; + let oe = &loop_edges[u.position as usize]; + let Ok((s, map)) = crate::tess::surface::eval_surface(face.parameters(), face.domain) else { panic!("evaluates") }; + for (t, p) in n.params.iter().zip(&n.points) { + let Some(q) = solidcraft_geom::brep::pcurve::eval(&oe.pcurve, *t) else { panic!("pcurve at {t}") }; + let q = map.to_eval(q); + let Some((at, _, _)) = s.derivs(q[0], q[1]) else { panic!("evaluates") }; + assert!(at.dist(*p) < 1e-6 + e.tolerance, "{at:?} vs {p:?}"); checked += 1; } } diff --git a/crates/kernel/src/tess/fallback.rs b/crates/kernel/src/tess/fallback.rs deleted file mode 100644 index 4a6c59f14..000000000 --- a/crates/kernel/src/tess/fallback.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! The last resort for a face the planner cannot plan however finely its edges are divided: a -//! leftover of the file's own modelling, such as a cusp where two edges leave a point at a zero -//! angle, a sliver whose two sides sag across each other, or a small cap round a pole. Its -//! boundary is filled flat, so the rest of the body keeps its plan rather than the whole body -//! falling back to the reference mesh. -//! -//! The boundary nodes (the shared edge nodes, so the face still meets its neighbours exactly) -//! are laid onto the plane that best fits them and triangulated there (see `cdt::triangulate`): -//! every boundary side is kept as a constraint unless it crosses one already kept (the defect -//! itself), and a triangle is in the face when it lies inside an odd number of loops. The fill is -//! kept only where it stays within the chord tolerance of the surface, so a real curved face is -//! left to the body's reference mesh. The triangles turn the way the surface does, and each node -//! keeps its parameters on the surface for its normal. - -use solidcraft_geom::tess::{EvalSurface, FacePlan}; -use solidcraft_geom::{Plane, Vec3}; - -use super::{cdt, uv}; - -/// Most boundary nodes a face is filled at. -const MAX_NODES: usize = 50_000; -/// Nodes the surface's normal is sampled at to find which way it faces. -const NORMAL_SAMPLES: usize = 16; - -/// The face `fi` of surface `s`, bounded by the loops `loops` (in space), filled flat; `None` -/// when its nodes do not lie on the surface within `accept`, span no plane, enclose nothing, or -/// the flat fill strays from the surface by more than the chord tolerance `tol` (a real curved -/// face, which the body's reference mesh draws better). -pub(crate) fn fill(fi: usize, s: &EvalSurface, loops: &[Vec], accept: f64, tol: f64) -> Option { - let fixed: Vec = loops.iter().flatten().copied().collect(); - if fixed.len() < 3 || fixed.len() > MAX_NODES { - return None; - } - // Each node's parameters, for its normal (a projection from the previous node's). - let dom = uv::domain(s); - let mut params: Vec<[f64; 2]> = Vec::with_capacity(fixed.len()); - let mut ranges = Vec::with_capacity(loops.len()); - for l in loops { - let start = params.len(); - let mut prev = None; - for p in l { - let q = uv::project(s, &dom, *p, prev, accept)?; - params.push(q); - prev = Some(q); - } - ranges.push(start..params.len()); - } - // The plane: the loops' area vector (holes count against the outer loop) through their - // centroid. - let normal = loops.iter().fold(Vec3::ZERO, |n, l| n + crate::plane_fit::loop_area(l)); - let centre = fixed.iter().fold(Vec3::ZERO, |c, p| c + *p) * (1.0 / fixed.len() as f64); - let plane = Plane::from_normal(centre, normal)?; - let flat: Vec<[f64; 2]> = fixed.iter().map(|p| plane.to_local(*p)).map(|q| [q.x, q.y]).collect(); - let fill = cdt::Fill { seeds: &[], refine: None, shape: false, lenient: true }; - let (_, mut triangles) = cdt::triangulate(&flat, &ranges, fill)?; - if triangles.is_empty() { - return None; - } - // Flat only where flat is close enough: each triangle's middle within the chord tolerance of - // the surface (found from its first corner's parameters). - let off = |t: &[u32; 3]| -> Option { - let [a, b, c] = t.map(|i| fixed.get(i as usize).copied()); - let mid = (a? + b? + c?) * (1.0 / 3.0); - let q = uv::project(s, &dom, mid, params.get(t[0] as usize).copied(), f64::INFINITY)?; - Some(s.derivs(q[0], q[1])?.0.dist(mid)) - }; - if !triangles.iter().all(|t| off(t).is_some_and(|d| d <= tol)) { - return None; - } - // Counter-clockwise about the plane's normal; turned over where the surface faces the other way. - let step = (params.len() / NORMAL_SAMPLES).max(1); - let along: f64 = params.iter().step_by(step).filter_map(|q| s.derivs(q[0], q[1])).map(|(_, su, sv)| su.cross(sv).dot(plane.normal())).sum(); - if along < 0.0 { - for t in &mut triangles { - t.swap(1, 2); - } - } - Some(FacePlan { face: u32::try_from(fi).unwrap_or(u32::MAX), surface: None, uv: params, fixed, normals: Vec::new(), flip: false, triangles }) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A plane face whose right side folds back over itself at a zero angle (a cusp): no side - /// crossing another may be kept, yet the face is filled and turns the plane's way. - #[test] - fn a_cusp_is_filled_the_surfaces_way() { - let s = EvalSurface::Plane { origin: Vec3::ZERO, du: Vec3::X, dv: Vec3::Y }; - let corners = [[0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [3.0, 4.2], [3.8, 3.6], [0.0, 4.0]]; - let l: Vec = corners.iter().map(|q| Vec3::new(q[0], q[1], 0.0)).collect(); - let Some(f) = fill(0, &s, &[l], 1e-9, 1e-9) else { panic!("filled") }; - assert!(!f.triangles.is_empty()); - let area: f64 = f - .triangles - .iter() - .map(|t| { - let [a, b, c] = t.map(|i| f.fixed[i as usize]); - (b - a).cross(c - a).z * 0.5 - }) - .sum(); - assert!(area > 14.0 && area < 16.5, "area {area}"); - assert_eq!(f.uv.len(), f.fixed.len()); - } - - #[test] - fn a_boundary_enclosing_nothing_is_not_filled() { - let s = EvalSurface::Plane { origin: Vec3::ZERO, du: Vec3::X, dv: Vec3::Y }; - let l = vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(2.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0)]; - assert!(fill(0, &s, &[l], 1e-3, 1e-3).is_none()); - } -} diff --git a/crates/kernel/src/tess/grid.rs b/crates/kernel/src/tess/grid.rs index 9502a1a9b..b89ecd923 100644 --- a/crates/kernel/src/tess/grid.rs +++ b/crates/kernel/src/tess/grid.rs @@ -6,6 +6,37 @@ /// Most grid points of one face. pub(crate) const MAX_FACE_GRID: usize = 150_000; +/// Keep at most `cap` grid points (`us` × `vs`) by taking evenly spaced lines in both +/// directions, the ends kept. +pub(crate) fn thin(us: &mut Vec, vs: &mut Vec, cap: usize) { + let total = us.len().saturating_mul(vs.len()); + if total <= cap { + return; + } + let f = (total as f64 / cap.max(4) as f64).sqrt(); + // At least the two ends in each direction (never more lines than there are). + let keep = |len: usize| ((len as f64 / f).floor() as usize).max(2).min(len); + let (mut nu, mut nv) = (keep(us.len()), keep(vs.len())); + // Rounding can leave the product a little over: the longer direction gives up the rest. + while nu.saturating_mul(nv) > cap.max(4) { + if nu >= nv && nu > 2 { + nu -= 1; + } else if nv > 2 { + nv -= 1; + } else { + break; + } + } + let pick = |d: &mut Vec, n: usize| { + if d.len() > n && n >= 2 { + let len = d.len(); + *d = (0..n).filter_map(|i| d.get(i * (len - 1) / (n - 1)).copied()).collect(); + } + }; + pick(us, nu); + pick(vs, nv); +} + /// The four sides of a parameter box, in counter-clockwise order. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Side { @@ -292,8 +323,15 @@ mod tests { // A triangle-like patch whose top side is a pole (two copies of one point in 3D). let b = vec![[0.0, 0.0], [0.5, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; let Some(q) = quad(&b) else { panic!("a quad") }; - let Some((_, tris)) = structured(&b, &q, &[0.5], &[0.5]) else { panic!("meshes") }; - assert!(!tris.is_empty()); + let Some((extra, tris)) = structured(&b, &q, &[0.5], &[0.5]) else { panic!("meshes") }; + // One grid node, (0.5, 0.5), fanned to each of the five boundary segments: one triangle + // each, the pole's single segment among them, every one of positive area, tiling the box. + assert_eq!(extra, [[0.5, 0.5]]); + assert_eq!(tris.len(), 5); + let mut uv = b.clone(); + uv.extend(extra); + assert!(tris.iter().all(|t| signed_area(&uv, *t).is_some_and(|a| a > 0.0))); + assert!((area(&uv, &tris) - 1.0).abs() < 1e-12); } #[test] diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs index 63dd8c835..92824dfc6 100644 --- a/crates/kernel/src/tess/mod.rs +++ b/crates/kernel/src/tess/mod.rs @@ -1,53 +1,82 @@ -//! Display tessellation: each face's triangulation in its own parameters, with every edge -//! sampled once so neighbouring faces share their boundary points exactly, handed over as a -//! [`TessPlan`] for the CPU or GPU evaluator. +//! SolidCraft's mesher: each face of a schema 4 record ([`brep::Brep`]) triangulated in its own +//! parameters, with every edge sampled once so neighbouring faces share their boundary points +//! exactly, handed over as a [`TessPlan`] for the CPU or GPU evaluator. A boundary node's +//! parameters on each face come from that face's exact pcurve of the edge, at the node's curve +//! parameter: nothing is projected, and a seam's two sides are its two pcurves. //! -//! Per face, cheapest first: -//! - planar faces: a constrained Delaunay triangulation of the edge nodes alone (a plane needs -//! no interior points); -//! - faces whose boundary runs along their parameter box (cylinder halves, sphere and torus -//! patches, fillets): a structured grid zipped to the edge nodes; -//! - four-cornered faces whose sides are not parameter lines (mitred fillet strips, cross -//! hole walls): a Coons blend of the four sides, zipped the same way; -//! - anything else (trimmed faces, holes): constrained Delaunay with interior seeds and -//! Ruppert refinement. -//! -//! A face the planner cannot handle (its surface has no evaluable form, a boundary that does -//! not project or crosses itself) fails the whole plan, and the caller meshes the body the -//! old way. +//! Per face: +//! 1. a cheaper layout where the face suits one: planar faces whose boundary runs along their +//! parameter box, and curved ones, take a structured grid zipped to the edge nodes; a +//! four-cornered face whose sides are not parameter lines (mitred fillet strips, cross hole +//! walls) a Coons blend of its four sides; a trimmed face the patches of its cuts or the +//! iso-line grid cut along its motorcycle traces; +//! 2. otherwise, the general method for every face: constrained Delaunay in the face's (u, v), +//! with interior seeds and Ruppert refinement, every node then evaluated on the exact +//! surface (and refined where a triangle sags off it); +//! 3. a face even that refuses because its loops cross in (u, v) (a cusp, a sliver whose sides +//! sag across each other) is still a defect upstream, in the record's pcurves or seams, and is +//! named in the plan's stats ([`PlanStats::lenient`], with why it was refused) so it is +//! reported and fixed there; it is filled leniently in (u, v) (the sides crossing one already +//! kept are left out, see [`Lenient`]) so the display has no hole. A face that refuses even +//! that (its loops do not close in (u, v), or wind round a seam or pole) is left out of the +//! plan with no triangles and named in [`PlanStats::unmeshed`], and the rest of the body is +//! meshed; there is no other mesher to fall back to. A face whose pcurves do not lie on its edges is an error naming the face and +//! the edge, as is a body none of whose faces can be planned. pub(crate) mod cdt; pub(crate) mod collar; pub(crate) mod coons; pub(crate) mod cutgrid; pub(crate) mod edges; -pub(crate) mod fallback; pub(crate) mod grid; pub(crate) mod motorcycle; pub(crate) mod pieces; +pub(crate) mod sag; pub(crate) mod seam; pub(crate) mod size; -pub(crate) mod ssi; pub(crate) mod surface; +pub(crate) mod tangle; pub(crate) mod uv; +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcore_record::brep::{self, Curve, Loop, Shell}; use solidcraft_geom::tess::{EvalSurface, FacePlan, TessPlan}; -use truck_modeling as mt; -use crate::body::{Solid, edge_order}; use crate::{KernelError, Result}; +/// Whether [`plan_face`] may leave out of its constrained Delaunay the boundary sides that cross +/// a side already kept, and not hold the triangles to every side: the last resort for a face +/// that crosses itself in (u, v) (a cusp, a sliver whose sides sag across each other), so the +/// display has no hole. Its points stay in (u, v), so a curved face is still drawn on its +/// surface. Such a face is named in [`PlanStats::lenient`]: its pcurves or seams are wrong. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Lenient { + No, + Yes, +} + /// How the faces of a plan were meshed. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct PlanStats { pub planar: usize, pub structured: usize, pub delaunay: usize, - /// Faces no method could plan, filled flat from their boundary nodes. - pub filled: usize, + /// Faces every method refused, filled leniently in (u, v) (see [`Lenient`]) so the display + /// has no hole: each still a defect upstream, in its pcurves or seams. + pub lenient: Vec, + /// Faces even the lenient fill refused: left out of the plan (no triangles), so the rest of + /// the body is still meshed, each with why it could not be planned. + pub unmeshed: Vec, +} + +/// A face a method refused: its index in the record and why. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RefusedFace { + pub face: usize, + pub reason: String, } /// Curved faces from which their sizes are worked out on the worker pool. @@ -60,466 +89,878 @@ const PARALLEL_FACES: usize = 4; const PARALLEL_CURVES: usize = 2; const PARALLEL_EDGES: usize = 256; -/// Most lines a curved face's grid gets in one direction. -const MAX_LINES: usize = 1024; +/// Most lines a curved face's grid gets in one direction: a turn's worth for each of the many +/// turns a coil's or a thread's wall winds (the grid as a whole stays within +/// [`grid::MAX_FACE_GRID`]). +const MAX_LINES: usize = 8192; /// Most points Ruppert refinement may add to one face, beyond its seeds. const MAX_REFINE: usize = 20_000; -/// Two boundary nodes this close together on the surface (mm) are one node. Far below any -/// spacing a mesh can carry, and far above the parameters a projection tells apart. See -/// [`drop_collapsed`]. -const SAME_NODE: f64 = 1e-6; -/// How far a face's boundary may lie off its surface and still be planned on it, as a fraction of -/// the body's extent, at every display quality (ten chord tolerances at Normal). -const ON_SURFACE: f64 = 1e-2; -/// How much finer a refused face's edges are divided, retry by retry. -const REFINE_STEPS: [f64; 2] = [3.0, 10.0]; +/// Most rounds of splitting the edge segments where a face's sampled boundary crosses itself: +/// each round halves them, so their chords sag a quarter as far. +const MAX_UNTANGLE: u32 = 16; fn unsupported(what: impl std::fmt::Display) -> KernelError { KernelError::Failed(format!("not supported yet: tessellation: {what}")) } -/// Plan the display tessellation of `solid` with chord tolerance `tol` and, when given, a -/// facet angle no facet may turn more than (where it sags above the angle's floor). -/// `boundary_tol`: how far the body's boundaries may lie off their surfaces (mm) as the file it -/// was read from declares, `None` for a body this kernel built (see -/// [`crate::body::Body::boundary_tol`]). -pub(crate) fn plan(solid: &Solid, tol: f64, turn: Option, boundary_tol: Option) -> Result<(TessPlan, PlanStats)> { - let faces: Vec<&mt::Face> = solid.face_iter().collect(); - let (edges, edge_faces) = edge_order(faces.iter().copied()); - let rules = size::Rules::new(tol, size::extent(solid.vertex_iter().map(|v| crate::body::from_p3(v.point()))), turn, boundary_tol); +/// The surface kind of a face, for an error that names it. +fn kind(s: &brep::Surface) -> &'static str { + match s { + brep::Surface::Plane { .. } | brep::Surface::PlaneThrough { .. } => "plane", + brep::Surface::Cylinder { .. } => "cylinder", + brep::Surface::Cone { .. } => "cone", + brep::Surface::Sphere { .. } => "sphere", + brep::Surface::BallPatch { .. } => "ball patch", + brep::Surface::Torus { .. } => "torus", + brep::Surface::Spline { .. } => "spline", + brep::Surface::RationalSpline { .. } => "rational spline", + brep::Surface::PlacedRevolution { .. } => "revolution", + } +} + +/// Whether each face's normal is its surface's natural normal, as the shell that uses it says +/// (a face no shell lists keeps its surface's). +fn forward_faces(b: &brep::Brep) -> Vec { + let mut forward = vec![true; b.faces.len()]; + for shell in &b.shells { + if let Shell::Faces { faces, .. } = shell { + for f in faces { + if let Some(slot) = forward.get_mut(f.face as usize) { + *slot = f.forward; + } + } + } + } + forward +} + +/// The edges of each face's loops, in loop order. +fn face_edges(f: &brep::Face) -> impl Iterator { + f.loops.iter().flat_map(|l| match l { + Loop::Edges { edges } => edges.as_slice(), + Loop::Vertex { .. } => &[], + }) +} + +/// Plan the tessellation of `b` with chord tolerance `tol` and, when given, a facet angle no +/// facet may turn more than (where it sags above the angle's floor). Faces and edges are the +/// record's, in its order. +pub(crate) fn plan(b: &brep::Brep, tol: f64, turn: Option) -> Result<(TessPlan, PlanStats)> { + let faces = &b.faces; + let forward = forward_faces(b); + // The faces each edge bounds, each once, in the order of the edge's uses. + let edge_faces: Vec> = b + .edges + .iter() + .map(|e| { + let mut fs: Vec = Vec::with_capacity(e.uses.len()); + for u in &e.uses { + if !fs.contains(&(u.face as usize)) { + fs.push(u.face as usize); + } + } + fs + }) + .collect(); + let rules = size::Rules::new(tol, size::extent(b.vertices.iter().map(|v| Vec3::new(v.point[0], v.point[1], v.point[2]))), turn); // Each face's surface and target side length, then every edge once at the smaller size of // its faces; faces then read their nodes. A planar face costs microseconds and a curved // one about a hundred, so the pool is used only where curved faces (or intersection // curves) make up the work. - let evals: Vec> = faces.iter().map(|f| surface::eval_surface(&f.surface())).collect(); - let curved = evals.iter().filter(|e| !matches!(e, Some(EvalSurface::Plane { .. }))).count(); - let sizes = - crate::par::map("face sizes", &evals, curved >= PARALLEL_SIZES, |eval| Ok(eval.as_ref().map(|s| size::face_size(s, &uv::domain(s), &rules)))); - let sized: Vec<(Option, Option<(f64, [f64; 2])>)> = - evals.into_iter().zip(sizes).map(|(e, s)| s.map(|s| (e, s))).collect::>()?; - let face_h = |f: usize| sized.get(f).and_then(|(_, s)| s.map(|(h, _)| h)).unwrap_or(rules.max_len); + let evals: Vec<(EvalSurface, surface::Params)> = faces + .iter() + .enumerate() + .map(|(fi, f)| surface::eval_surface(f.parameters(), f.domain).map_err(|e| unsupported(format!("face {fi} ({}): {e}", kind(&f.surface))))) + .collect::>()?; + let (evals, params): (Vec, Vec) = evals.into_iter().unzip(); + let curved = evals.iter().filter(|e| !matches!(e, EvalSurface::Plane { .. })).count(); + let sizes: Vec<(f64, [f64; 2])> = + crate::par::map("face sizes", &evals, curved >= PARALLEL_SIZES, |s| Ok(size::face_size(s, &uv::domain(s), &rules))) + .into_iter() + .collect::>()?; + let face_h = |f: usize| sizes.get(f).map_or(rules.max_len, |(h, _)| *h); let edge_h: Vec = edge_faces.iter().map(|fs| fs.iter().map(|&f| face_h(f)).fold(rules.max_len, f64::min)).collect(); - let jobs: Vec<(&mt::Edge, f64)> = edges.iter().zip(edge_h).collect(); - let solved = edges.iter().filter(|e| matches!(e.curve(), mt::Curve::IntersectionCurve(_))).count(); - let sampled = crate::par::map("edge nodes", &jobs, solved >= PARALLEL_CURVES || edges.len() >= PARALLEL_EDGES, |(e, h)| { - Ok(edges::sample_edge(e, &rules, *h)) - }); - let mut nodes: HashMap<_, edges::Nodes> = HashMap::with_capacity(edges.len()); - for (e, n) in edges.iter().zip(sampled) { - nodes.insert(e.id(), n?); - } - relax_crowded_faces(&faces, &jobs, &rules, &mut nodes); - divide_collapsed_faces(&faces, &jobs, &rules, &mut nodes); - let indexed: Vec<(usize, &mt::Face)> = faces.iter().copied().enumerate().collect(); - // A face's boundary nodes, loop by loop (each edge's last node is the next edge's first), - // with their parameters on the face's surface where the edge knows them (an intersection - // edge on this face's surface). - type Boundary = (Vec>, Vec>>); - let boundary = |face: &mt::Face, eval: &EvalSurface, nodes: &HashMap| -> Result { - let mut loops3: Vec> = Vec::new(); - let mut known: Vec>> = Vec::new(); - for wire in face.absolute_boundaries() { - let (mut pts, mut uvs) = (Vec::new(), Vec::new()); - for e in wire.edge_iter() { - let n = nodes.get(&e.id()).ok_or_else(|| unsupported("edge without nodes"))?; - let (mut ep, mut eq) = (n.points.clone(), n.params_on(eval).unwrap_or_else(|| vec![None; n.points.len()])); - if !e.orientation() { - ep.reverse(); - eq.reverse(); - } - ep.pop(); - eq.pop(); - pts.extend(ep); - uvs.extend(eq); - } - if pts.len() >= 2 { - loops3.push(pts); - known.push(uvs); - } - } - Ok((loops3, known)) - }; - // A plan in the surface's orientation turned the face's way. - let oriented_face = |face: &mt::Face, fp: FacePlan| FacePlan { - flip: !face.orientation(), - triangles: if face.orientation() { fp.triangles } else { fp.triangles.into_iter().map(|[a, b, c]| [a, c, b]).collect() }, - ..fp - }; - let surface_of = |fi: usize| match sized.get(fi) { - Some((Some(eval), Some(size))) => Ok((eval.clone(), *size)), - _ => Err(unsupported(format!("face {fi}: surface not evaluable"))), - }; - // One face, from the edge nodes as they are and with the rules for its level of detail. - let plan_one = |fi: usize, face: &mt::Face, nodes: &HashMap, rules: &size::Rules| { - let (eval, size) = surface_of(fi)?; - let (loops3, known) = boundary(face, &eval, nodes)?; - let mut stats = PlanStats::default(); - let replan = |stats: &mut PlanStats| match plan_face(fi, &eval, &loops3, &known, rules, size, stats) { - Ok(fp) => Ok(fp), - // A boundary that doubles straight back on itself (a zero-width slit in the face, - // which some STEP writers leave where two surfaces were trimmed apart) encloses no - // area but crosses itself in (u, v). Dropping the slits leaves the same face. - Err(first) => { - let (slit3, slitq) = drop_slits(&loops3, &known, rules.tol * 1e-2); - if slit3 == loops3 { - return Err(first); - } - // Nothing left but slits: a sliver face (two edges between the same two vertices, - // as STEP files write one) encloses no area, and the faces on either side already - // meet along its nodes. - if slit3.iter().all(|l| l.len() < 3) { - return Ok(FacePlan { face: u32::try_from(fi).unwrap_or(u32::MAX), ..FacePlan::default() }); - } - *stats = PlanStats::default(); - plan_face(fi, &eval, &slit3, &slitq, rules, size, stats).map_err(|_| first) - } + let jobs: Vec<(usize, f64)> = edge_h.into_iter().enumerate().collect(); + let solved = b.edges.iter().filter(|e| matches!(e.curve, Curve::SurfaceIntersection { .. })).count(); + let mut nodes: Vec = crate::par::map("edge nodes", &jobs, solved >= PARALLEL_CURVES || jobs.len() >= PARALLEL_EDGES, |(e, h)| { + edges::sample_edge(b, *e, &rules, *h) + }) + .into_iter() + .collect::>()?; + relax_crowded_faces(b, &jobs, &rules, &mut nodes)?; + split_thin_loops(b, &mut nodes)?; + let indexed: Vec = (0..faces.len()).collect(); + let face_boundary = |fi: usize, nodes: &[edges::Nodes]| { + let (Some(face), Some(eval), Some(map)) = (faces.get(fi), evals.get(fi), params.get(fi)) else { + return Err(unsupported(format!("face {fi}: missing"))); }; - let fp = replan(&mut stats)?; - Ok((oriented_face(face, fp), eval, stats)) - }; - let mut planned = crate::par::map("face tessellation", &indexed, curved >= PARALLEL_FACES, |(fi, face)| plan_one(*fi, face, &nodes, &rules)); - // A face refused at this level of detail (a boundary that comes out degenerate, or that a - // triangulation cannot follow, between nodes too far apart) has its edges divided again, - // finer, and it and the faces beside those edges, which share their nodes, are planned - // again from them. - if planned.iter().any(Result::is_err) { - let index_of: HashMap = edges.iter().enumerate().map(|(i, e)| (e.id(), i)).collect(); - let face_edges: Vec> = faces - .iter() - .map(|f| f.absolute_boundaries().iter().flat_map(|w| w.edge_iter().filter_map(|e| index_of.get(&e.id()).copied())).collect()) - .collect(); - let mut finer: HashMap = HashMap::new(); - for factor in REFINE_STEPS { - let refused: Vec = planned.iter().enumerate().filter(|(_, r)| r.is_err()).map(|(i, _)| i).collect(); - if refused.is_empty() { - break; - } - let fine = rules.finer(factor); - let mut touched: Vec = refused.iter().filter_map(|f| face_edges.get(*f)).flatten().copied().collect(); - touched.sort_unstable(); - touched.dedup(); - let resampled = crate::par::map("edge nodes", &touched, touched.len() >= PARALLEL_EDGES, |i| { - Ok(jobs.get(*i).map(|(e, h)| (e.id(), edges::sample_edge(e, &fine, *h / factor)))) - }); - for (id, n) in resampled.into_iter().flatten().flatten() { - nodes.insert(id, n); - } - finer.extend(refused.iter().map(|f| (*f, fine))); - // The faces sharing a divided edge read its new nodes. - let mut again: Vec = touched.iter().filter_map(|i| edge_faces.get(*i)).flatten().copied().collect(); - again.sort_unstable(); - again.dedup(); - let again: Vec<(usize, &mt::Face)> = again.into_iter().filter_map(|f| faces.get(f).map(|face| (f, *face))).collect(); - let results = crate::par::map("face tessellation", &again, again.len() >= PARALLEL_FACES, |(fi, face)| { - plan_one(*fi, face, &nodes, finer.get(fi).unwrap_or(&rules)) - }); - for ((f, _), r) in again.iter().zip(results) { - if let Some(slot) = planned.get_mut(*f) { - *slot = r; - } - } - } - } - // A face refused however finely its edges are divided is filled flat from its boundary - // nodes (see `fallback`), so the rest of the body keeps its plan. - for (fi, slot) in planned.iter_mut().enumerate() { - if slot.is_ok() { - continue; - } - let (Some(face), Ok((eval, _))) = (faces.get(fi), surface_of(fi)) else { continue }; - let Ok((loops3, _)) = boundary(face, &eval, &nodes) else { continue }; - if let Some(fp) = fallback::fill(fi, &eval, &loops3, off_surface(&rules), rules.tol) { - *slot = Ok((oriented_face(face, fp), eval, PlanStats { filled: 1, ..PlanStats::default() })); - } - } - let oriented = |e: &mt::Edge| -> Option> { - let mut pts = nodes.get(&e.id())?.points.clone(); - if !e.orientation() { - pts.reverse(); - } - Some(pts) + boundary(b, fi, face, eval, map, nodes, &rules) }; + let mut boundaries: Vec = + crate::par::map("face boundaries", &indexed, curved >= PARALLEL_FACES, |&fi| face_boundary(fi, &nodes)).into_iter().collect::>()?; + let tangled = untangle(b, &evals, &edge_faces, rules.tol, &mut nodes, &mut boundaries, &face_boundary)?; + let planned = crate::par::map("face tessellation", &indexed, curved >= PARALLEL_FACES, |&fi| { + let (Some(face), Some(eval), Some(size), Some(fb)) = (faces.get(fi), evals.get(fi), sizes.get(fi), boundaries.get(fi)) else { + return Err(unsupported(format!("face {fi}: missing"))); + }; + let refused = tangled.iter().find(|(f, _)| *f == fi).map(|(_, why)| why.as_str()); + let (fp, stats) = plan_or_fill(fi, kind(face.parameters()), eval, &fb.loops, &rules, *size, fb.reach, refused)?; + let fwd = forward.get(fi).copied().unwrap_or(true); + let fp = + FacePlan { flip: !fwd, triangles: if fwd { fp.triangles } else { fp.triangles.into_iter().map(|[a, b, c]| [a, c, b]).collect() }, ..fp }; + Ok((fp, stats)) + }); let mut plan = TessPlan::default(); let mut stats = PlanStats::default(); - for r in planned { - let (fp, eval, s) = r?; + // A face no method plans is left out, named in the stats, and the rest of the body is + // meshed; a body none of whose faces plan is the first face's error. + let mut first_error: Option = None; + for (fi, (r, eval)) in planned.into_iter().zip(evals).enumerate() { let surface = u32::try_from(plan.surfaces.len()).map_err(|_| unsupported("too many faces"))?; plan.surfaces.push(eval); + let (fp, s) = match r { + Ok(done) => done, + Err(e) => { + stats.unmeshed.push(RefusedFace { face: fi, reason: e.to_string() }); + first_error.get_or_insert(e); + (FacePlan { face: u32::try_from(fi).unwrap_or(u32::MAX), ..FacePlan::default() }, PlanStats::default()) + } + }; plan.faces.push(FacePlan { surface: Some(surface), ..fp }); stats.planar += s.planar; stats.structured += s.structured; stats.delaunay += s.delaunay; - stats.filled += s.filled; + stats.lenient.extend(s.lenient); } - plan.edges = edges.iter().filter_map(oriented).collect(); + if let Some(e) = first_error + && stats.unmeshed.len() == faces.len() + { + return Err(e); + } + plan.edges = nodes.into_iter().map(|n| n.points).collect(); plan.edge_faces = edge_faces.into_iter().map(|fs| fs.into_iter().map(|f| u32::try_from(f).unwrap_or(u32::MAX)).collect()).collect(); Ok((plan, stats)) } -/// Whether every curved face's boundary lies on the face's surface, within `accept`: a point -/// off the surface's own parameter range is off it. The planner needs this of every face; a -/// blend that runs on past the end of a neighbouring round's surface does not have it. -pub(crate) fn boundaries_on_surfaces(solid: &Solid, accept: f64) -> bool { - use mt::{BoundedCurve, ParametricCurve}; - for face in solid.face_iter() { - let Some(eval) = surface::eval_surface(&face.surface()) else { continue }; - if matches!(eval, EvalSurface::Plane { .. }) { - continue; +/// Face `fi`'s boundary, loop by loop: the shared edge nodes (each edge's last node is the next +/// edge's first) and their parameters on the face's surface, from each edge use's exact pcurve +/// at the node's curve parameter. A seam edge's two uses on one face have their own pcurves, so +/// its two sides are told apart. A pcurve runs on continuously; where one edge meets the next, a +/// pcurve that starts a whole period along from where the previous one ended is moved back by +/// it, except in a direction the meeting point is a pole of (or lies on a patch side collapsed +/// to within its vertex's tolerance, see [`Boundary::reach`]): there the parameter is free, and +/// the two pcurves' own values are where the face's boundary runs along the pole from and to +/// (a meridian revolved half a turn meets the other at the pole half a period away; unwrapped, +/// its loop would wind round the surface). Each loop then starts at a node off every pole whose +/// predecessor is off them too, so the step from its last node to its first, which +/// [`seam::drift`] takes as the nearest copy, never crosses a pole. A vertex loop (a pole) +/// bounds no area and has no nodes of its own. Where the face's loops pass a vertex more than once +/// (two holes touching at a point, a loop through another's corner), the pcurves of the edges from +/// it give its parameters apart by their rounding, and two nodes 1e-14 apart put crossing +/// constraints into the triangulation: a pass whose parameters agree with the first pass's to +/// that rounding (1e-9 relative) takes the first's. Farther apart they are two places of the +/// surface (a seam's two sides, a closed spline's ends). A pcurve that does not cover its edge's +/// interval, or puts a node farther off the edge than the tolerances allow, is an error naming +/// the face and edge: the record is wrong there. +fn boundary( + b: &brep::Brep, + fi: usize, + face: &brep::Face, + s: &EvalSurface, + map: &surface::Params, + nodes: &[edges::Nodes], + rules: &size::Rules, +) -> Result { + let dom = uv::domain(s); + let fail = |e: u32, why: String| unsupported(format!("face {fi} ({}): edge {e}: {why}", kind(&face.surface))); + // How near a pole a node is one: the tolerance of a vertex of the face that lies on a patch + // side collapsed to within it, not to a point, as the record check takes a loop's pole; at + // most the chord tolerance, finer than which the mesh resolves nothing (a vertex tolerance + // as large as the surface's features would make a pole of every node near one). + let mut reach: f64 = 0.0; + for oe in face_edges(face) { + let (Some(edge), Some([p0, p1])) = (b.edges.get(oe.edge as usize), oe.pcurve.interval()) else { continue }; + let tol = edge.vertices.get(usize::from(!oe.forward)).and_then(|v| b.vertices.get(*v as usize)).map_or(0.0, |v| v.tolerance.min(rules.tol)); + let Some(q) = solidcraft_geom::brep::pcurve::eval(&oe.pcurve, if oe.forward { p0 } else { p1 }).map(|q| map.to_eval(q)) else { continue }; + if tol.is_finite() && tol > reach && (0..2).any(|d| uv::degenerate_within(s, &dom, q, d, tol)) { + reach = tol; } - let dom = uv::domain(&eval); - let mut prev: Option<[f64; 2]> = None; - for e in face.edge_iter() { - let c = e.oriented_curve(); - let (lo, hi) = c.range_tuple(); - for k in 0..=32 { - let p = crate::body::from_p3(c.subs(lo + (hi - lo) * f64::from(k) / 32.0)); - match uv::project(&eval, &dom, p, prev, accept) { - Some(uv) => prev = Some(uv), - None => return false, + } + let pole_along = |q: [f64; 2], d: usize| uv::degenerate_within(s, &dom, q, d, reach); + let mut out = Boundary { loops: Vec::with_capacity(face.loops.len()), segments: Vec::with_capacity(face.loops.len()), reach }; + // Each vertex's parameters, from the first edge use of the face to start there. + let mut at_vertex: std::collections::HashMap = std::collections::HashMap::new(); + // The vertex pairs an edge of the face joins. + let joined: std::collections::HashSet<(u32, u32)> = face_edges(face) + .filter_map(|oe| b.edges.get(oe.edge as usize)) + .map(|e| (e.vertices[0].min(e.vertices[1]), e.vertices[0].max(e.vertices[1]))) + .collect(); + let vertex_point = |v: u32| b.vertices.get(v as usize).map(|x| (Vec3::new(x.point[0], x.point[1], x.point[2]), x.tolerance.max(0.0))); + // Each loop's nodes that are another edge's node (see [`edges::snap`]). + let mut snapped: Vec> = Vec::with_capacity(face.loops.len()); + for l in &face.loops { + let Loop::Edges { edges } = l else { continue }; + let (mut pts, mut uvs): (Vec, Vec<[f64; 2]>) = (Vec::new(), Vec::new()); + let mut segs: Vec<(u32, u32)> = Vec::new(); + let mut shared: Vec = Vec::new(); + // Where the previous edge ended, and the periods its pcurve was moved by. + let (mut end, mut shift): (Option<[f64; 2]>, [f64; 2]) = (None, [0.0; 2]); + for oe in edges { + let n = nodes.get(oe.edge as usize).ok_or_else(|| fail(oe.edge, "no nodes".into()))?; + let edge = b.edges.get(oe.edge as usize).ok_or_else(|| fail(oe.edge, "no such edge".into()))?; + let [t0, t1] = edge.interval; + let [p0, p1] = oe.pcurve.interval().ok_or_else(|| fail(oe.edge, "a malformed pcurve".into()))?; + let slack = 1e-9 * (t1 - t0).abs().max(t0.abs()).max(t1.abs()).max(1.0); + if (p0 - t0).abs() > slack || (p1 - t1).abs() > slack { + return Err(fail(oe.edge, format!("its pcurve spans [{p0}, {p1}], the edge [{t0}, {t1}]"))); + } + // The edge's own tolerance: how far its curve may stand off the face. + let accept = (rules.tol * 10.0).max(1e-6) + edge.tolerance.max(0.0); + let mut ep: Vec = n.points.clone(); + let mut es: Vec = n.params.iter().map(|t| n.snapped.contains(t)).collect(); + let mut eq: Vec<[f64; 2]> = Vec::with_capacity(ep.len()); + for (k, (t, p)) in n.params.iter().zip(&n.points).enumerate() { + let q = solidcraft_geom::brep::pcurve::eval(&oe.pcurve, t.clamp(p0, p1)) + .ok_or_else(|| fail(oe.edge, format!("its pcurve does not evaluate at t = {t}")))?; + let q = map.to_eval(q); + let on = + s.derivs(q[0], q[1]).map(|d| d.0).ok_or_else(|| fail(oe.edge, format!("node {k}: the surface does not evaluate at {q:?}")))?; + if !(on.dist(*p) <= accept) { + return Err(fail(oe.edge, format!("node {k}: its pcurve is {} mm off the edge at t = {t}", on.dist(*p)))); + } + eq.push(q); + } + if !oe.forward { + ep.reverse(); + eq.reverse(); + es.reverse(); + } + if let (Some(e), Some(&start)) = (end, eq.first()) { + for d in 0..2 { + let Some(per) = dom.period[d] else { continue }; + if !(pole_along(e, d) || pole_along(start, d)) { + shift[d] = per * ((e[d] - start[d]) / per).round(); + } + } + } + for q in &mut eq { + q[0] += shift[0]; + q[1] += shift[1]; + } + if let (Some(&v), Some(q)) = (edge.vertices.get(usize::from(!oe.forward)), eq.first_mut()) { + match at_vertex.get(&v) { + Some(first) => { + if (0..2).all(|d| (first[d] - q[d]).abs() <= 1e-9 * first[d].abs().max(q[d].abs()).max(1.0)) { + *q = *first; + } + } + None => { + // Another vertex of the face within the tolerance of both (and of the + // chord tolerance), and not joined to this one by an edge (which makes + // them two points however near: a step that small), is the same point: + // the record's corners a hair apart (a planar boolean's, where a cut-out's + // corner touches another loop's corner) are one point of the face, so its + // loops touch there instead of crossing. + let same = vertex_point(v).and_then(|(p, tv)| { + at_vertex.iter().filter(|(w, _)| **w != v && !joined.contains(&(v.min(**w), v.max(**w)))).find_map(|(w, wq)| { + let (pw, tw) = vertex_point(*w)?; + (p.dist(pw) <= tv.max(tw).min(rules.tol)).then_some(*wq) + }) + }); + if let Some(mut w) = same.filter(|w| !(0..2).any(|d| pole_along(*w, d) || pole_along(*q, d))) { + for d in 0..2 { + w[d] = uv::unwrap(w[d], q[d], dom.period[d]); + } + *q = w; + } + at_vertex.insert(v, *q); + } + } + } + end = eq.last().copied(); + ep.pop(); + eq.pop(); + es.pop(); + // The segment from each node on: the edge's own, counted from its start. + let m = ep.len() as u32; + segs.extend((0..m).map(|j| (oe.edge, if oe.forward { j } else { m - 1 - j }))); + pts.extend(ep); + uvs.extend(eq); + shared.extend(es); + } + let n = uvs.len(); + let pole = |q: &[f64; 2]| (0..2).any(|d| pole_along(*q, d)); + let off = |k: usize| uvs.get(k).is_some_and(|q| !pole(q)); + // A node off the poles whose predecessor is off them too; failing that (a whole sphere's + // seam in two segments: pole, equator, pole), one whose predecessor is a pole on the same + // edge, so the step into it is the edge's own and the step into that pole, from the + // edge before, is in the loop where it is unwrapped like any other. + let same_edge = |k: usize| segs.get((k + n - 1) % n).zip(segs.get(k)).is_some_and(|(a, b)| a.0 == b.0); + let start = (0..n).find(|&k| off(k) && off((k + n - 1) % n)).or_else(|| (0..n).find(|&k| off(k) && same_edge(k))); + if let Some(k) = start { + uvs.rotate_left(k); + pts.rotate_left(k); + segs.rotate_left(k); + shared.rotate_left(k); + } + if pts.len() >= 2 { + out.loops.push(seam::Loop { uv: uvs, pts }); + out.segments.push(segs); + snapped.push(shared); + } + } + // A node snapped from another edge is that edge's node, the same point: where the face runs + // that edge too, the node takes the other's parameters, so the face's boundary passes one + // point of its (u, v) twice (a pinch) and does not cross itself there. Its own pcurve puts it + // within the chord tolerance of that point, not on it. + for (l, flags) in snapped.iter().enumerate() { + for (k, _) in flags.iter().enumerate().filter(|(_, f)| **f) { + let Some((&p, &q)) = out.loops.get(l).and_then(|lp| lp.pts.get(k).zip(lp.uv.get(k))) else { continue }; + let partner = out + .loops + .iter() + .zip(&snapped) + .flat_map(|(lp, fs)| lp.pts.iter().zip(&lp.uv).zip(fs)) + .filter(|((r, _), f)| !**f && **r == p) + .map(|((_, w), _)| *w) + .min_by(|a, b| (a[0] - q[0]).hypot(a[1] - q[1]).total_cmp(&(b[0] - q[0]).hypot(b[1] - q[1]))); + if let (Some(mut w), Some(slot)) = (partner, out.loops.get_mut(l).and_then(|lp| lp.uv.get_mut(k))) { + for d in 0..2 { + if dom.period[d].is_some() { + w[d] = uv::unwrap(w[d], q[d], dom.period[d]); + } + } + *slot = w; + } + } + } + Ok(out) +} + +/// A face's boundary loops, and for each loop node the edge segment that starts there: the +/// edge, and the segment's place along it from its start vertex. `reach`: how near a pole a +/// point of the face is taken as one (see [`uv::degenerate_within`]): the tolerance of a vertex +/// of it on a patch side collapsed to within that tolerance, else 0. +struct Boundary { + loops: Vec, + segments: Vec>, + reach: f64, +} + +/// Edges are sampled to the chord tolerance each on its own, so where two curves of one face +/// run closer than their chords sag (the two arcs of a thin lune, a sliver cap between two +/// cylinders), the chords may cross although the curves do not, and no triangulation follows +/// such a boundary. The edge segments whose chords cross another of the face (in its loop or +/// another, see [`tangle::crossing`]) are halved at their curve parameter's middle, on the edge, +/// so every face of the edge gets the new nodes; the faces of every edge split are checked again, +/// until no chords cross. Boundaries that still cross after [`MAX_UNTANGLE`] rounds, or would +/// put more than [`edges::MAX_EDGE_NODES`] on an edge, are an error naming the face and edges. +#[allow(clippy::too_many_arguments)] +fn untangle( + b: &brep::Brep, + evals: &[EvalSurface], + edge_faces: &[Vec], + tol: f64, + nodes: &mut [edges::Nodes], + boundaries: &mut [Boundary], + face_boundary: &(dyn Fn(usize, &[edges::Nodes]) -> Result + Sync), +) -> Result> { + let crossing = |fi: usize, fb: &Boundary| -> Vec<(u32, u32)> { + let Some(s) = evals.get(fi) else { return Vec::new() }; + tangle::crossing(s, fb.reach, &fb.loops).into_iter().filter_map(|(l, k)| fb.segments.get(l)?.get(k).copied()).collect() + }; + let indexed: Vec = (0..boundaries.len()).collect(); + let curved = evals.iter().filter(|e| !matches!(e, EvalSurface::Plane { .. })).count(); + let found: Vec> = crate::par::map("boundary crossings", &indexed, curved >= PARALLEL_FACES, |&fi| { + Ok(boundaries.get(fi).map_or_else(Vec::new, |fb| crossing(fi, fb))) + }) + .into_iter() + .collect::>()?; + let mut tangled: Vec<(usize, Vec<(u32, u32)>)> = found.into_iter().enumerate().filter(|(_, c)| !c.is_empty()).collect(); + for round in 0..=MAX_UNTANGLE { + if tangled.is_empty() { + return Ok(Vec::new()); + } + if round == MAX_UNTANGLE { + // Halving cannot part two curves that touch or cross: where they come within the chord + // tolerance of each other, they share nodes. + let faces: Vec = tangled.iter().map(|(fi, _)| *fi).collect(); + tangled = snap_touches(evals, edge_faces, tol, nodes, boundaries, face_boundary, &faces)?; + // Each face still crossing, with why: planned leniently, and named (`plan_or_fill`). + return Ok(tangled + .iter() + .map(|(fi, c)| { + let mut es: Vec = c.iter().map(|(e, _)| *e).collect(); + es.sort_unstable(); + es.dedup(); + let kind = b.faces.get(*fi).map_or("?", |f| kind(&f.surface)); + (*fi, format!("face {fi} ({kind}): boundary crosses itself: edges {es:?} run closer together than their chords can follow after {MAX_UNTANGLE} halvings")) + }) + .collect()); + } + let mut split: Vec<(u32, u32)> = tangled.iter().flat_map(|(_, c)| c.iter().copied()).collect(); + split.sort_unstable(); + split.dedup(); + let mut redo: Vec = Vec::new(); + for run in split.chunk_by(|a, c| a.0 == c.0) { + let Some(&(e, _)) = run.first() else { continue }; + let segs: Vec = run.iter().map(|(_, k)| *k).collect(); + let Some(slot) = nodes.get_mut(e as usize) else { continue }; + edges::split_segments(b, e as usize, slot, &segs)?; + redo.extend(edge_faces.get(e as usize).into_iter().flatten().copied()); + } + redo.sort_unstable(); + redo.dedup(); + tangled.clear(); + for fi in redo { + let fb = face_boundary(fi, nodes)?; + let c = crossing(fi, &fb); + if let Some(slot) = boundaries.get_mut(fi) { + *slot = fb; + } + if !c.is_empty() { + tangled.push((fi, c)); + } + } + } + Ok(Vec::new()) +} + +/// Rounds of [`snap_touches`] before a face that still crosses itself is refused. +const MAX_SNAP: u32 = 8; + +/// The faces `faces` whose boundaries cross themselves where two curves touch or cross (halving +/// their chords does not part them, see [`untangle`]), with every node that lies within the chord +/// tolerance `tol` of a crossing chord of another edge put onto that edge as well (see +/// [`edges::snap`]): the two edges share the point, the face's boundary passes it twice (a pinch, +/// as at a vertex two loops share), and the chords meet there instead of crossing. Where the +/// curves run within the tolerance of each other for a stretch (a sliver between two touches), +/// the nodes on either side are shared in turn, so the boundary runs out and back along one +/// polyline there: a slit, which bounds the face on neither side. A node is not snapped where the +/// pinch would turn part of its loop inside out by more than the tolerance (two curves crossing +/// at an angle: the boundary is wrong there, not within the tolerance). Every face of a changed +/// edge has its boundary built again. Returns the faces whose boundaries still cross, with the +/// crossing segments. +#[allow(clippy::too_many_arguments)] +fn snap_touches( + evals: &[EvalSurface], + edge_faces: &[Vec], + tol: f64, + nodes: &mut [edges::Nodes], + boundaries: &mut [Boundary], + face_boundary: &(dyn Fn(usize, &[edges::Nodes]) -> Result + Sync), + faces: &[usize], +) -> Result)>> { + let crossing = |fi: usize, fb: &Boundary| -> Vec<(usize, usize)> { + let Some(s) = evals.get(fi) else { return Vec::new() }; + tangle::crossing(s, fb.reach, &fb.loops) + }; + let mut tangled: Vec = faces.to_vec(); + for _ in 0..MAX_SNAP { + let mut add: HashMap> = HashMap::new(); + for &fi in &tangled { + let Some(fb) = boundaries.get(fi) else { continue }; + for (l, k) in crossing(fi, fb) { + let Some(&(e, j)) = fb.segments.get(l).and_then(|s| s.get(k)) else { continue }; + if let Some((t, p)) = touch(fb, nodes, (l, k), (e, j), tol) { + add.entry(e).or_default().push((t, p)); + } + } + } + if add.is_empty() { + break; + } + let mut redo: Vec = Vec::new(); + for (e, points) in &add { + let Some(slot) = nodes.get_mut(*e as usize) else { continue }; + edges::snap(*e as usize, slot, points)?; + redo.extend(edge_faces.get(*e as usize).into_iter().flatten().copied()); + } + redo.extend(tangled.iter().copied()); + redo.sort_unstable(); + redo.dedup(); + tangled.clear(); + for fi in redo { + let fb = face_boundary(fi, nodes)?; + let crosses = !crossing(fi, &fb).is_empty(); + if let Some(slot) = boundaries.get_mut(fi) { + *slot = fb; + } + if crosses { + tangled.push(fi); + } + } + if tangled.is_empty() { + return Ok(Vec::new()); + } + } + Ok(tangled + .into_iter() + .filter_map(|fi| { + let fb = boundaries.get(fi)?; + let c: Vec<(u32, u32)> = crossing(fi, fb).into_iter().filter_map(|(l, k)| fb.segments.get(l)?.get(k).copied()).collect(); + (!c.is_empty()).then_some((fi, c)) + }) + .collect()) +} + +/// The node of face boundary `fb` nearest the crossing chord `at` (loop, node) of its boundary, +/// segment `seg` (edge, segment from its start) of that edge, within `tol` of the chord strictly +/// between its ends, on another edge, and not yet on this one; with the parameter on the edge +/// where it projects onto the chord. `None` when there is none, or snapping it would turn part +/// of its loop inside out by more than the tolerance (see [`snap_touches`]). +fn touch(fb: &Boundary, nodes: &[edges::Nodes], at: (usize, usize), seg: (u32, u32), tol: f64) -> Option<(f64, Vec3)> { + let (e, j) = seg; + let n = nodes.get(e as usize)?; + let j = j as usize; + let (a, c) = (*n.points.get(j)?, *n.points.get(j + 1)?); + let (ta, tc) = (*n.params.get(j)?, *n.params.get(j + 1)?); + let ac = c - a; + let len2 = ac.dot(ac); + if !(len2 > 0.0) { + return None; + } + let mut best: Option<(f64, f64, Vec3)> = None; + for (l, lp) in fb.loops.iter().enumerate() { + let segs = fb.segments.get(l)?; + let m = lp.pts.len(); + for (k, &p) in lp.pts.iter().enumerate() { + // The node's edges: the segment starting at it and the one ending there. + let edges_at = [segs.get(k).map(|s| s.0), segs.get((k + m - 1) % m).map(|s| s.0)]; + if edges_at.contains(&Some(e)) || n.points.contains(&p) { + continue; + } + let f = (p - a).dot(ac) / len2; + let d = p.dist_to_segment(a, c); + if !(f > 1e-6 && f < 1.0 - 1e-6 && d <= tol) || best.is_some_and(|(bd, _, _)| bd <= d) { + continue; + } + if l == at.0 && inside_out(lp, at.1, k, tol) { + continue; + } + best = Some((d, ta + f * (tc - ta), p)); + } + } + best.map(|(_, t, p)| (t, p)) +} + +/// Whether pinching loop `lp` at node `k` and a new node (the same point) on its chord from node +/// `at` would turn either part inside out by more than `tol`: a part whose winding in (u, v) is +/// against the loop's, and whose area is more than `tol` across (twice its area in 3D over its +/// length). +fn inside_out(lp: &seam::Loop, at: usize, k: usize, tol: f64) -> bool { + let m = lp.uv.len(); + if m < 3 { + return false; + } + // The two parts: from the node after the chord's start round to `k`, and from `k` round to the + // chord's start. + let part = |from: usize, to: usize| -> Vec { + let mut out = Vec::new(); + let mut i = from % m; + loop { + out.push(i); + if i == to % m || out.len() > m { + break; + } + i = (i + 1) % m; + } + out + }; + let whole = area2(&lp.uv); + [part(at + 1, k), part(k, at)].iter().any(|ids| { + let uv: Vec<[f64; 2]> = ids.iter().filter_map(|&i| lp.uv.get(i).copied()).collect(); + let pts: Vec = ids.iter().filter_map(|&i| lp.pts.get(i).copied()).collect(); + if uv.len() < 3 || area2(&uv) * whole >= 0.0 { + return false; + } + // Newell's vector: twice the area of the polygon in 3D. + let twice = pts.iter().zip(pts.iter().cycle().skip(1)).fold(Vec3::ZERO, |acc, (p, q)| acc + p.cross(*q)).len(); + let length: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(p, q)| p.dist(*q)).sum(); + twice > tol * length + }) +} + +/// Bounded work for the facet angle: a face whose boundary would get more than +/// [`size::MAX_ANGLE_BOUNDARY`] segments has its curved edges sampled again at twice the angle, +/// as often as it takes, down to the tolerance alone (a plate with a thousand small holes is +/// not worth a hundred times the work to draw each hole round). An edge keeps one set of nodes +/// for both its faces, at the coarser of their levels, so every rim of a crowded face gets the +/// Segments an edge loop needs to enclose an area in its face's (u, v). +const MIN_LOOP_SEGMENTS: usize = 3; + +/// Every edge loop with fewer than [`MIN_LOOP_SEGMENTS`] segments has its edges' segments halved +/// until it has them: two short arcs (a lens), each within the chord tolerance and so one +/// segment, would otherwise be two chords on one line, a boundary of no area. The new nodes are +/// on the edges' curves and shared by every face that runs them, as all edge nodes are. +fn split_thin_loops(b: &brep::Brep, nodes: &mut [edges::Nodes]) -> Result<()> { + for f in &b.faces { + for l in &f.loops { + let brep::Loop::Edges { edges: uses } = l else { continue }; + let mut es: Vec = uses.iter().map(|u| u.edge as usize).collect(); + es.sort_unstable(); + es.dedup(); + let count = |nodes: &[edges::Nodes]| -> usize { + uses.iter().map(|u| nodes.get(u.edge as usize).map_or(0, |n| n.points.len().saturating_sub(1))).sum() + }; + // Each round at least doubles every edge's segments: a few rounds always do. + for _ in 0..MIN_LOOP_SEGMENTS { + if count(nodes) >= MIN_LOOP_SEGMENTS { + break; + } + for &e in &es { + let Some(slot) = nodes.get_mut(e) else { continue }; + let segs: Vec = (0..slot.points.len().saturating_sub(1)).filter_map(|k| u32::try_from(k).ok()).collect(); + edges::split_segments(b, e, slot, &segs)?; } } } } - true + Ok(()) } -/// Bounded work for the facet angle, as the reference mesher bounds it: a face whose boundary -/// would get more than `MAX_ANGLE_BOUNDARY` segments has its curved edges sampled again at twice -/// the angle, as often as it takes, down to the tolerance alone (a plate with a thousand small -/// holes is not worth a hundred times the work to draw each hole round). An edge keeps one set -/// of nodes for both its faces, at the coarser of their levels, so every rim of a crowded face -/// gets the same share whatever the order of the faces. -fn relax_crowded_faces(faces: &[&mt::Face], jobs: &[(&mt::Edge, f64)], rules: &size::Rules, nodes: &mut HashMap) { - use truck_meshalgo::tessellation::Deflection; - let Some(turn) = rules.turn else { return }; - let h_of: HashMap = jobs.iter().map(|(e, h)| (e.id(), (*e, *h))).collect(); - let boundaries: Vec> = - faces.iter().map(|f| f.absolute_boundaries().iter().flat_map(|w| w.edge_iter().map(|e| e.id())).collect()).collect(); - let mut level: HashMap = HashMap::new(); - for l in 1..=Deflection::MAX_RELAX { - let segments = |id: &mt::EdgeID| nodes.get(id).map_or(0, |n| n.points.len().saturating_sub(1)); - let mut crowded: Vec = boundaries +/// same share whatever the order of the faces. +fn relax_crowded_faces(b: &brep::Brep, jobs: &[(usize, f64)], rules: &size::Rules, nodes: &mut [edges::Nodes]) -> Result<()> { + let Some(turn) = rules.turn else { return Ok(()) }; + let boundaries: Vec> = b.faces.iter().map(|f| face_edges(f).map(|oe| oe.edge as usize).collect()).collect(); + let curved = |e: usize| b.edges.get(e).is_some_and(|e| !matches!(e.curve, Curve::Line { .. })); + let mut level: Vec = vec![0; nodes.len()]; + for l in 1..=size::MAX_RELAX { + let segments = |e: &usize| nodes.get(*e).map_or(0, |n| n.points.len().saturating_sub(1)); + let mut crowded: Vec = boundaries .iter() - .filter(|ids| ids.iter().map(segments).sum::() > Deflection::MAX_ANGLE_BOUNDARY) + .filter(|es| es.iter().map(segments).sum::() > size::MAX_ANGLE_BOUNDARY) .flatten() - .filter(|id| level.get(*id).copied().unwrap_or(0) < l) - .filter(|id| h_of.get(*id).is_some_and(|(e, _)| !matches!(e.curve(), mt::Curve::Line(_)))) + .filter(|e| level.get(**e).copied().unwrap_or(0) < l && curved(**e)) .copied() .collect(); - crowded.sort_unstable_by_key(|id| format!("{id:?}")); + crowded.sort_unstable(); crowded.dedup(); if crowded.is_empty() { break; } let relaxed = size::Rules { turn: turn.relaxed(l), ..*rules }; - for id in crowded { - if let Some((e, h)) = h_of.get(&id) { - nodes.insert(id, edges::sample_edge(e, &relaxed, *h)); - level.insert(id, l); + for e in crowded { + let Some(&(_, h)) = jobs.get(e) else { continue }; + if let Some(slot) = nodes.get_mut(e) { + *slot = edges::sample_edge(b, e, &relaxed, h)?; + } + if let Some(slot) = level.get_mut(e) { + *slot = l; } } } + Ok(()) } -/// Every loop with its zero-width slits removed: wherever the boundary steps out to a node and -/// straight back to where it came from, the pair is dropped. A slit encloses no area, so the -/// face is the same without it, and without it the boundary no longer runs along itself. The -/// two sides need only agree within `eps` (a hundredth of the chord tolerance): a STEP writer -/// may draw them as two curves a few nanometres apart, which no mesh could tell apart anyway. -fn drop_slits(loops3: &[Vec], known: &[Vec>], eps: f64) -> (Vec>, Vec>>) { - /// Slits dropped from one loop before giving up (the search is a scan per slit). - const MAX_SLITS: usize = 4096; - let mut out3: Vec> = Vec::with_capacity(loops3.len()); - let mut outq: Vec>> = Vec::with_capacity(loops3.len()); - for (li, pts) in loops3.iter().enumerate() { - let mut pts = pts.clone(); - let mut qs = known.get(li).cloned().unwrap_or_else(|| vec![None; pts.len()]); - qs.resize(pts.len(), None); - for _ in 0..MAX_SLITS { - let n = pts.len(); - if n < 3 { - break; - } - let same = |a: usize, b: usize| pts.get(a).zip(pts.get(b)).is_some_and(|(p, q)| p.dist(*q) <= eps); - let tip = (0..n).find(|&k| same((k + n - 1) % n, (k + 1) % n)); - let Some(k) = tip else { break }; - // Drop the tip and the node that repeats the one before it. - let mut drop = [k, (k + 1) % n]; - drop.sort_unstable(); - for &i in drop.iter().rev() { - if i < pts.len() { - pts.remove(i); - } - if i < qs.len() { - qs.remove(i); - } - } - } - if pts.len() >= 2 { - out3.push(pts); - outq.push(qs); - } - } - (out3, outq) +/// Twice the signed area of a parameter polygon. +fn area2(uv: &[[f64; 2]]) -> f64 { + let n = uv.len(); + (0..n).map(|k| uv.get(k).zip(uv.get((k + 1) % n)).map_or(0.0, |(a, b)| a[0] * b[1] - b[0] * a[1])).sum() } -/// Boundary nodes a loop keeps only one of: nodes whose parameters land on the node before them. -/// -/// A boundary that runs a little off its surface (a STEP file writes its curves and surfaces to -/// its own uncertainty, so an edge may lie micrometres off the face it bounds) projects onto the -/// nearest surface point. Around a convex corner of the surface every point of such an edge is -/// nearest that corner, so a whole run of nodes comes out with the corner's parameters. The finer -/// the chord tolerance, the more nodes the run holds, and a boundary that repeats a point in -/// (u, v) encloses no area there and cannot be triangulated (#1721). -/// -/// One node stands for the run. The nodes dropped are nearer to it than `SAME_NODE` on the -/// surface, so the face is the same without them. -fn drop_collapsed(l: &mut seam::Loop, speed: [f64; 2]) { - let eps = |d: usize| { - let s = speed.get(d).copied().unwrap_or(1.0); - if s.is_finite() && s > 0.0 { SAME_NODE / s } else { 0.0 } - }; - let (eu, ev) = (eps(0), eps(1)); - let same = |a: &[f64; 2], b: &[f64; 2]| (a[0] - b[0]).abs() <= eu && (a[1] - b[1]).abs() <= ev; - let (mut uv, mut pts) = (Vec::with_capacity(l.uv.len()), Vec::with_capacity(l.pts.len())); - for (q, p) in l.uv.iter().zip(&l.pts) { - if uv.last().is_some_and(|last| same(last, q)) { - continue; - } - uv.push(*q); - pts.push(*p); - } - // The loop is cyclic: its last node may land on its first. - while uv.len() > 2 && uv.last().zip(uv.first()).is_some_and(|(a, b)| same(a, b)) { - uv.pop(); - pts.pop(); - } - l.uv = uv; - l.pts = pts; -} - -/// Bring every loop of a face into the same period as its outer boundary. A loop is projected -/// on its own, and a periodic surface repeats, so a hole can come out a whole turn away from the -/// boundary it lies in — where it no longer cuts the face, and the face is drawn over its hole. -fn align_periods(loops: &mut [seam::Loop], dom: &uv::Domain) { +/// A loop through both poles that turns straight back at one of them (it runs along a seam +/// and back: a whole sphere bounded by its meridian, or a sphere face whose split meridian it +/// uses both ways) retraces that seam once projected, since the periodic parameter carries on +/// unchanged across the pole. Across a pole it may jump by any amount, so the run from the +/// second pole back to the first is moved one period along, whichever way keeps the loop +/// within one period with a positive area: the seam's two uses then lie a period apart. +fn open_pole_to_pole(s: &EvalSurface, dom: &uv::Domain, reach: f64, l: &mut seam::Loop) { + let n = l.uv.len(); + let poles: Vec = (0..n).filter(|&k| l.uv.get(k).is_some_and(|q| (0..2).any(|d| uv::degenerate_within(s, dom, *q, d, reach)))).collect(); + let [p0, p1] = poles.as_slice() else { return }; for d in 0..2 { - let Some(per) = dom.period.get(d).copied().flatten().filter(|p| *p > 0.0) else { continue }; - let middle = |l: &seam::Loop| { - let (lo, hi) = l.uv.iter().filter_map(|q| q.get(d)).fold((f64::MAX, f64::MIN), |(a, b), x| (a.min(*x), b.max(*x))); - 0.5 * (lo + hi) - }; - let Some(outer) = loops.first().map(middle) else { continue }; - if !outer.is_finite() { + let Some(per) = dom.period[d] else { continue }; + let near = + |a: Option<&[f64; 2]>, b: Option<&[f64; 2]>| a.zip(b).is_some_and(|(a, b)| (a[0] - b[0]).abs().max((a[1] - b[1]).abs()) <= 1e-9 * per); + let turns_back = [*p0, *p1].iter().any(|&p| near(l.uv.get((p + n - 1) % n), l.uv.get((p + 1) % n))); + if !turns_back { continue; } - for l in loops.iter_mut().skip(1) { - let shift = ((outer - middle(l)) / per).round() * per; - if shift != 0.0 && shift.is_finite() { - for q in l.uv.iter_mut() { - if let Some(x) = q.get_mut(d) { - *x += shift; - } + // Along the seam the periodic parameter is constant between the poles. + let second: Vec = (0..n).filter(|k| (k > p1 || k < p0) && *k != *p0 && *k != *p1).collect(); + if second.is_empty() { + continue; + } + for sign in [1.0, -1.0] { + let mut moved = l.uv.clone(); + for &k in &second { + if let Some(q) = moved.get_mut(k) { + q[d] += sign * per; } } + // The poles as the planner splits them: one copy at each neighbour's parameter. + let mut ring = Vec::with_capacity(n + 2); + for k in 0..n { + let (Some(q), Some(a), Some(b)) = (moved.get(k), moved.get((k + n - 1) % n), moved.get((k + 1) % n)) else { continue }; + if k == *p0 || k == *p1 { + let (mut qa, mut qb) = (*q, *q); + qa[d] = a[d]; + qb[d] = b[d]; + ring.extend([qa, qb]); + } else { + ring.push(*q); + } + } + let (lo, hi) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d]))); + if hi - lo <= per * (1.0 + 1e-9) && area2(&ring) > 0.0 { + l.uv = moved; + return; + } } } } -/// Nodes a face's boundary needs before it can hold a triangle. -const MIN_BOUNDARY_NODES: usize = 3; +/// The poles of a loop where it turns straight back along a seam: the nodes either side have +/// the same parameters. +fn turning_poles(s: &EvalSurface, dom: &uv::Domain, reach: f64, per: f64, uv: &[[f64; 2]]) -> Vec { + let n = uv.len(); + let near = |a: Option<&[f64; 2]>, b: Option<&[f64; 2]>| a.zip(b).is_some_and(|(a, b)| (a[0] - b[0]).abs().max((a[1] - b[1]).abs()) <= 1e-9 * per); + (0..n) + .filter(|&k| uv.get(k).is_some_and(|q| (0..2).any(|d| uv::degenerate_within(s, dom, *q, d, reach)))) + .filter(|&k| near(uv.get((k + n - 1) % n), uv.get((k + 1) % n))) + .collect() +} -/// A face whose whole boundary comes to fewer than three nodes has no triangle to stand on: it is -/// a sliver no wider than the tolerance (a chord with the shallow arc beside it, which the edge -/// sampler rightly leaves as one segment each). Its edges are sampled again, halved until the -/// boundary has nodes enough, so the sliver is drawn instead of failing the whole body's plan. -/// The nodes stay shared, so the faces beside it follow the same points. -fn divide_collapsed_faces(faces: &[&mt::Face], jobs: &[(&mt::Edge, f64)], rules: &size::Rules, nodes: &mut HashMap) { - /// Halvings before giving up (a boundary of two edges reaches four nodes in one). - const MAX_HALVINGS: usize = 8; - let h_of: HashMap = jobs.iter().map(|(e, h)| (e.id(), (*e, *h))).collect(); - for f in faces { - let ids: Vec = f.absolute_boundaries().iter().flat_map(|w| w.edge_iter().map(|e| e.id())).collect(); - let count = |nodes: &HashMap| { - ids.iter().map(|id| nodes.get(id).map_or(0, |n| n.points.len().saturating_sub(1))).sum::() - }; - if count(nodes) >= MIN_BOUNDARY_NODES { +/// A loop with one pole, where it turns straight back along a seam, that winds once around the +/// periodic direction as projected: a half sphere's rim, then its seam down to the pole and up +/// again. Unwrapped along the loop, both runs of the seam lie on one parameter line, and the +/// period the loop is short of is closed by the rim's jump back. The face lies between the +/// seam's two uses a period apart, so the loop is unwrapped from the node after the pole round +/// to the pole, and starts at the node before it: the seam's uses then bound the face's parameter box on either side, and share +/// their nodes as every other edge does. Kept as it was unless the opened loop spans at most a +/// period with a positive area. +fn open_at_pole(s: &EvalSurface, dom: &uv::Domain, reach: f64, l: &mut seam::Loop) { + let n = l.uv.len(); + if n < 4 || l.pts.len() != n { + return; + } + for d in 0..2 { + let Some(per) = dom.period[d] else { continue }; + if (seam::drift(l, d, per).abs() - per).abs() > per * 1e-6 { continue; } - for _ in 0..MAX_HALVINGS { - for id in &ids { - let Some((e, h)) = h_of.get(id) else { continue }; - let longest = - nodes.get(id).map_or(0.0, |n| n.points.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?))).fold(0.0, f64::max)); - let finer = if longest > 0.0 { (longest * 0.5).min(*h) } else { *h }; - nodes.insert(*id, edges::sample_edge(e, rules, finer)); + let [pole] = turning_poles(s, dom, reach, per, &l.uv)[..] else { continue }; + // From the node after the pole round to the pole, unwrapped along the way. + let order: Vec = (1..=n).map(|i| (pole + i) % n).collect(); + let mut uv: Vec<[f64; 2]> = Vec::with_capacity(n); + for &k in &order { + let Some(mut q) = l.uv.get(k).copied() else { return }; + if let Some(pr) = uv.last() { + for e in 0..2 { + q[e] = uv::unwrap(q[e], pr[e], dom.period[e]); + } } - if count(nodes) >= MIN_BOUNDARY_NODES { - break; + uv.push(q); + } + // The pole's free parameter: its predecessor's (the poles are split from it later). + if let (Some(prev), Some(q)) = (uv.len().checked_sub(2).and_then(|i| uv.get(i)).copied(), uv.last_mut()) { + q[d] = prev[d]; + } + let (lo, hi) = uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d]))); + // Started at the node before the pole, so the loop closes without a jump. + let mut opened = seam::Loop { uv, pts: order.iter().filter_map(|&k| l.pts.get(k).copied()).collect() }; + opened.uv.rotate_right(2); + opened.pts.rotate_right(2); + if opened.pts.len() == n && hi - lo <= per * (1.0 + 1e-9) && area2(&opened.uv) > 0.0 && !seam::winds(std::slice::from_ref(&opened), d, per) { + *l = opened; + return; + } + } +} + +/// Each loop is projected on its own, so along a closed direction a hole can come out a whole +/// period away from the outer loop: a dome's outer loop opened at its pole spans v in [-1, 0] +/// while the hole projects into [0, 1], outside it (tangency-labs/solidcore#433). Every other +/// loop is moved by whole periods to the copy whose middle is nearest the outer loop's (the +/// loop of largest area); a face that does not wind lies within one period, so that is the +/// copy inside it. +fn holes_beside_outer(dom: &uv::Domain, loops: &mut [seam::Loop]) { + let Some(outer) = loops.iter().map(|l| area2(&l.uv).abs()).enumerate().max_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) else { return }; + let middle = |l: &seam::Loop, d: usize| { + let (lo, hi) = l.uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d]))); + 0.5 * (lo + hi) + }; + for d in 0..2 { + let Some(per) = dom.period[d] else { continue }; + let Some(centre) = loops.get(outer).map(|l| middle(l, d)) else { continue }; + for (i, l) in loops.iter_mut().enumerate() { + let k = ((middle(l, d) - centre) / per).round(); + if i == outer || !k.is_finite() || k == 0.0 { + continue; + } + for q in &mut l.uv { + q[d] -= k * per; } } } } -/// How far a boundary node may lie off its surface and still be projected onto it (see the note -/// in [`plan_face`]). -fn off_surface(rules: &size::Rules) -> f64 { - (rules.extent * ON_SURFACE).max(rules.boundary_tol.unwrap_or(0.0)).max(1e-6) +/// One face, planned by [`plan_face`]; a face it refuses because its loops cross in (u, v) is +/// planned once more leniently (see [`Lenient`]) and named in the stats with the first refusal, +/// so the defect upstream is still reported. When the lenient fill refuses too, the first +/// refusal is the error (and [`plan`] leaves the face out, named). `refused`: a face whose +/// boundary still crosses itself after [`untangle`] (two edges meeting tangentially at a cusp, +/// whose chords cross however often they are halved), filled leniently straight away with that +/// reason. +fn plan_or_fill( + fi: usize, + kind: &str, + s: &EvalSurface, + loops: &[seam::Loop], + rules: &size::Rules, + size: (f64, [f64; 2]), + reach: f64, + refused: Option<&str>, +) -> Result<(FacePlan, PlanStats)> { + let mut stats = PlanStats::default(); + let strict = match refused { + Some(why) => Err(unsupported(why.to_string())), + None => plan_face(fi, kind, s, loops, rules, size, reach, &mut stats, Lenient::No), + }; + match strict { + Ok(fp) => Ok((fp, stats)), + Err(first) => { + let mut stats = PlanStats::default(); + match plan_face(fi, kind, s, loops, rules, size, reach, &mut stats, Lenient::Yes) { + Ok(fp) => { + stats.lenient.push(RefusedFace { face: fi, reason: first.to_string() }); + Ok((fp, stats)) + } + Err(_) => Err(first), + } + } + } } /// One face: boundary loops in 3D (shared edge nodes) to parameters and triangles. /// `size`: the face's target side length (mm) and the surface's mean speed along u and v. +/// `reach`: how near a pole a point is taken as one ([`Boundary::reach`]). `lenient`: the last resort +/// for a face no method could plan (see [`Lenient`]). +#[allow(clippy::too_many_arguments)] fn plan_face( fi: usize, + kind: &str, s: &EvalSurface, - loops3: &[Vec], - known: &[Vec>], + loops: &[seam::Loop], rules: &size::Rules, size: (f64, [f64; 2]), + reach: f64, stats: &mut PlanStats, + lenient: Lenient, ) -> Result { let tol = rules.tol; let (h, speed) = size; let dom = uv::domain(s); - // How far a boundary node may lie off its surface and still be projected onto it: a property - // of the body, not of the mesh asked for, so a finer chord tolerance never refuses a boundary - // a coarser one accepted, and zooming in never drops a face (#1721). A hundredth of the body, - // or more where the file it was read from declares more; a file's declared accuracy never - // lowers it, since writers' edges stray farther from their surfaces than they declare. - let accept = off_surface(rules); - let fail = |why: &str| unsupported(format!("face {fi}: {why}")); - // Project every loop, unwrapping periodic parameters along it. - let mut projected: Vec = Vec::with_capacity(loops3.len()); - for (li, pts) in loops3.iter().enumerate() { - let mut luv: Vec<[f64; 2]> = Vec::with_capacity(pts.len()); - let mut prev: Option<[f64; 2]> = None; - for (k, p) in pts.iter().enumerate() { - // Known parameters (an intersection edge's), else a projection seeded by the - // previous node. - let given = known.get(li).and_then(|l| l.get(k)).copied().flatten(); - let mut q = match given { - Some(q) => q, - None => uv::project(s, &dom, *p, prev, accept).ok_or_else(|| fail("boundary does not lie on the surface"))?, - }; - if let Some(pr) = prev { - for d in 0..2 { - q[d] = uv::unwrap(q[d], pr[d], dom.period[d]); - } - } - luv.push(q); - prev = Some(q); - } - let mut l = seam::Loop { uv: luv, pts: pts.clone() }; - drop_collapsed(&mut l, speed); - for (d, per) in dom.period.iter().enumerate() { - if let Some(per) = per { - seam::close_through_pole(s, &mut l, d, *per); - } - } - projected.push(l); - } - align_periods(&mut projected, &dom); + let fail = |why: &str| unsupported(format!("face {fi} ({kind}): {why}")); + let mut projected: Vec = loops.to_vec(); // A loop that winds around a periodic direction does not close in (u, v): the face is cut // along a parameter line into one period (a seamless cylinder face, a helical trim). + // A loop that runs up a seam from a pole and straight back down it (a half sphere bounded + // by its rim and its seam used both ways) winds once as projected: it is opened at the pole. + for l in projected.iter_mut() { + open_at_pole(s, &dom, reach, l); + } let wound: Vec = (0..2).filter(|&d| dom.period[d].is_some_and(|per| seam::winds(&projected, d, per))).collect(); // A face cut along a seam is a long winding strip whose sides are the cut lines and the // boundary in turn: Delaunay with sag refinement meshes it (the patch layouts below assume @@ -533,6 +974,14 @@ fn plan_face( } _ => return Err(fail("boundary winds around the surface both ways")), } + // A loop from pole to pole and back along one seam (a whole sphere as one face, as another + // kernel writes it) projects onto one parameter line: its second run is a period along. + if !seamed { + for l in projected.iter_mut() { + open_pole_to_pole(s, &dom, reach, l); + } + holes_beside_outer(&dom, &mut projected); + } // Split poles. let mut fixed: Vec = Vec::new(); let mut uvs: Vec<[f64; 2]> = Vec::new(); @@ -544,7 +993,7 @@ fn plan_face( // At a pole the parameter along the degenerate direction is free: one copy with // the previous node's value, one with the next node's. let (prev, next) = (luv.get((k + n - 1) % n).copied(), luv.get((k + 1) % n).copied()); - let pole = (0..2).find(|&d| uv::degenerate(s, *q, d)); + let pole = (0..2).find(|&d| uv::degenerate_within(s, &dom, *q, d, reach)); match (pole, prev, next) { (Some(d), Some(a), Some(b)) => { let mut qa = *q; @@ -566,7 +1015,7 @@ fn plan_face( } ranges.push(start..uvs.len()); } - if uvs.len() < MIN_BOUNDARY_NODES { + if uvs.len() < 3 { return Err(fail("degenerate boundary")); } let mut bbox = [(f64::MAX, f64::MIN); 2]; @@ -578,21 +1027,30 @@ fn plan_face( // Constrained Delaunay in (u, v) scaled to millimetres: equilateral seeds of side `h`, // refined where triangles leave the surface, are too long or bend too much, then shaped by // Ruppert refinement. + let polys: Vec<&[[f64; 2]]> = ranges.iter().filter_map(|r| uvs.get(r.clone())).collect(); + let step = [h / speed[0], h / speed[1]]; let delaunay = || { - let polys: Vec<&[[f64; 2]]> = ranges.iter().filter_map(|r| uvs.get(r.clone())).collect(); - let seeds = cdt::lattice(bbox, [h / speed[0], h / speed[1]], &polys, speed); + let seeds = cdt::lattice(bbox, step, &polys, speed); let eval = |u: f64, v: f64| s.derivs(u, v).map(|(p, su, sv)| (p, su.cross(sv).normalized())); let sag = cdt::Sag { eval: &eval, tol, h, turn: rules.turn, scale: speed }; - let fill = cdt::Fill { seeds: &seeds, refine: Some((sag, MAX_REFINE)), shape: !matches!(s, EvalSurface::Plane { .. }), lenient: false }; + let fill = cdt::Fill { + seeds: &seeds, + refine: Some((sag, MAX_REFINE)), + shape: !matches!(s, EvalSurface::Plane { .. }), + lenient: lenient == Lenient::Yes, + }; cdt::triangulate(&uvs, &ranges, fill).ok_or_else(|| fail("boundary crosses itself")) }; // Planar and curved faces alike: a structured grid where the boundary runs along the // parameter box (a rectangle, a cylinder half), a Coons grid on four corners, else Delaunay. let planar = matches!(s, EvalSurface::Plane { .. }); - let (extra, triangles) = { + // The lenient fill is the constrained Delaunay alone: the caller names the face in the stats. + let (extra, triangles) = if lenient == Lenient::Yes { + delaunay()? + } else { let mut us = uv::divide(s, 0, bbox[0], bbox[1], rules, h, MAX_LINES); let mut vs = uv::divide(s, 1, bbox[1], bbox[0], rules, h, MAX_LINES); - thin(&mut us, &mut vs, grid::MAX_FACE_GRID); + grid::thin(&mut us, &mut vs, grid::MAX_FACE_GRID); let structured = match (ranges.len(), if seamed { None } else { grid::quad(&uvs) }) { (1, Some(q)) => { // Interior lines: the boundary's own where opposite sides agree (refined where the @@ -638,8 +1096,16 @@ fn plan_face( // the iso-line grid cut along its motorcycle traces and trimmed by its boundary, // else Delaunay. A plane: the butterfly of a round face, else Delaunay (a plane // is shaded the same by any triangles, and its Delaunay needs no refinement). + // A curved strip, straight and within a side across one parameter (its division + // there has no line inside) and with no room for a point of its own (a thread's + // root band, which runs out obliquely so it has no four corners), is its boundary + // nodes alone, refined where the surface leaves them: patches and grid lines + // across it would only crowd it (the butterfly's cuts run lengthwise through a + // long strip, seeded the whole way). A strip curved across (a fillet narrower + // than a side) keeps the layouts that follow its curvature. let face = Region { s, uvs: &uvs, fixed: &fixed, ranges: &ranges, rules, h, speed, us: &us, vs: &vs }; - let trimmed = if seamed { + let strip = !planar && (us.len() <= 2 || vs.len() <= 2) && !cdt::has_room(bbox, step, &polys, speed); + let trimmed = if seamed || strip { None } else if planar { if ranges.len() == 1 { plan_pieces(&face) } else { None } @@ -671,11 +1137,21 @@ fn plan_face( let pole_pair = |i: u32, j: u32| i != j && fixed.get(i as usize).zip(fixed.get(j as usize)).is_some_and(|(p, q)| p == q); let mut triangles = triangles; triangles.retain(|t| !(pole_pair(t[0], t[1]) || pole_pair(t[1], t[2]) || pole_pair(t[2], t[0]))); - if !closed_boundary(&ranges, &fixed, &triangles) { + // A lenient fill leaves out the sides that cross: the boundary is followed everywhere else. + if lenient == Lenient::No && !closed_boundary(&ranges, &fixed, &uvs, &triangles) { return Err(fail("triangulation does not follow the boundary")); } let mut all = uvs; all.extend(extra); + // Whatever the layout, no triangle leaves the surface by more than the tolerance. + if !planar { + sag::refine(s, tol, reach, &fixed, &mut all, &mut triangles, MAX_REFINE); + sag::flip(s, tol, reach, &fixed, &all, &mut triangles); + } + // Both evaluators take a closed spline's parameters inside its active interval. + for q in &mut all { + *q = s.wrap(*q); + } Ok(FacePlan { face: u32::try_from(fi).unwrap_or(u32::MAX), surface: None, uv: all, fixed, normals: Vec::new(), flip: false, triangles }) } @@ -879,11 +1355,16 @@ fn graded(a: [f64; 2], b: [f64; 2], sa: f64, sb: f64, h: f64, speed: [f64; 2], f all.into_iter().filter(|t| *t > 0.0 && *t < 1.0).collect() } -/// Every boundary segment (consecutive nodes of a loop) is the side of exactly one triangle: +/// Every boundary segment (consecutive nodes of a loop) is the side of exactly one triangle (two +/// for a slit the loops run along both ways): /// the face covers its boundary with nothing missing or doubled, so it meets its neighbours -/// exactly. Pole copies of one node (consecutive in a loop, at one point) are one vertex: the -/// segment between them has no length, and a side ending on either copy is the same side. -fn closed_boundary(ranges: &[std::ops::Range], fixed: &[Vec3], triangles: &[[u32; 3]]) -> bool { +/// exactly. Some boundary nodes are one vertex, a side ending on any of them the same side: pole +/// copies of one node (consecutive in a loop, at one point, the segment between them of no +/// length), and nodes at the very same (u, v), which the triangulation takes as one point: two +/// loops touching at a vertex they share (a ring standing on a perforated plate, tangent to the +/// holes beside it). A seam's two uses are at one point in space but a period apart in (u, v), +/// and stay two. +fn closed_boundary(ranges: &[std::ops::Range], fixed: &[Vec3], uvs: &[[f64; 2]], triangles: &[[u32; 3]]) -> bool { let mut one: Vec = (0..fixed.len() as u32).collect(); let root = |one: &[u32], mut i: u32| { while let Some(&j) = one.get(i as usize).filter(|j| **j != i) { @@ -892,17 +1373,30 @@ fn closed_boundary(ranges: &[std::ops::Range], fixed: &[Vec3], triangles: i }; let segment = |r: &std::ops::Range, k: usize| ((r.start + k) as u32, (r.start + (k + 1) % r.len()) as u32); + let join = |one: &mut [u32], a: u32, b: u32| { + let (ra, rb) = (root(one, a), root(one, b)); + if let Some(x) = one.get_mut(rb.max(ra) as usize) { + *x = ra.min(rb); + } + }; for r in ranges { for k in 0..r.len() { let (a, b) = segment(r, k); if fixed.get(a as usize).zip(fixed.get(b as usize)).is_some_and(|(p, q)| p == q) { - let (ra, rb) = (root(&one, a), root(&one, b)); - if let Some(x) = one.get_mut(rb.max(ra) as usize) { - *x = ra.min(rb); - } + join(&mut one, a, b); } } } + // By value: −0.0 and 0.0 are one point. + let key = |q: &[f64; 2]| [(q[0] + 0.0).to_bits(), (q[1] + 0.0).to_bits()]; + let mut first: HashMap<[u64; 2], u32> = HashMap::with_capacity(uvs.len()); + for (i, q) in uvs.iter().enumerate().take(fixed.len()) { + let i = i as u32; + let f = *first.entry(key(q)).or_insert(i); + if f != i { + join(&mut one, f, i); + } + } let side = |a: u32, b: u32| { let (a, b) = (root(&one, a), root(&one, b)); (a != b).then_some((a.min(b), a.max(b))) @@ -915,30 +1409,19 @@ fn closed_boundary(ranges: &[std::ops::Range], fixed: &[Vec3], triangles: } } } - ranges.iter().all(|r| { - (0..r.len()).all(|k| { + // Each boundary side has a triangle for every time the loops run along it: one, or two for + // a slit (a side run out and back, where the face meets itself along a line: a hole's wall + // touching the wall round it), one triangle either side. + let mut runs: HashMap<(u32, u32), u32> = HashMap::new(); + for r in ranges { + for k in 0..r.len() { let (a, b) = segment(r, k); - side(a, b).is_none_or(|k| sides.get(&k).copied() == Some(1)) - }) - }) -} - -/// Keep at most `cap` grid points by taking every k-th line in both directions (ends kept). -fn thin(us: &mut Vec, vs: &mut Vec, cap: usize) { - let total = us.len().saturating_mul(vs.len()); - if total <= cap { - return; - } - let f = (total as f64 / cap.max(4) as f64).sqrt(); - let pick = |d: &mut Vec| { - let n = ((d.len() as f64 / f).ceil() as usize).max(2); - if d.len() > n { - let len = d.len(); - *d = (0..n).filter_map(|i| d.get(i * (len - 1) / (n - 1)).copied()).collect(); + if let Some(k) = side(a, b) { + *runs.entry(k).or_default() += 1; + } } - }; - pick(us); - pick(vs); + } + runs.iter().all(|(k, n)| sides.get(k).copied() == Some(*n)) } #[cfg(test)] diff --git a/crates/kernel/src/tess/sag.rs b/crates/kernel/src/tess/sag.rs new file mode 100644 index 000000000..b78616289 --- /dev/null +++ b/crates/kernel/src/tess/sag.rs @@ -0,0 +1,326 @@ +//! The chord tolerance over a face's finished triangulation, whatever layout made it. A grid +//! divides each parameter direction within the tolerance, but on a doubly curved surface the +//! two sags add up in the middle of a cell, along its diagonal; a patch blended from its sides +//! has no lines along the surface's own directions at all. Every triangle is checked against +//! the surface (at its centroid and at the middle of each side inside the face) and the sides +//! that leave it are split in two, both triangles on them together, so the face stays +//! conforming. Sides on the face's boundary are never split: they are the edges' own nodes, +//! which the neighbouring face shares. + +use solidcraft_geom::prelude::*; +use std::collections::HashMap; + +use solidcore_record::Vec3; +use solidcraft_geom::tess::EvalSurface; + +/// Split the triangles `tris` of a face (indices into `uv`; the first `fixed.len()` points sit +/// at `fixed`, the rest on the surface at their parameters) until none of them lies farther +/// than `tol` from the surface `s`, adding at most `max_points` points to `uv`. `reach`: how near +/// a pole a point is taken as one (see [`super::uv::degenerate_within`]). +pub(crate) fn refine(s: &EvalSurface, tol: f64, reach: f64, fixed: &[Vec3], uv: &mut Vec<[f64; 2]>, tris: &mut Vec<[u32; 3]>, max_points: usize) { + if !(tol.is_finite() && tol > 0.0) || tris.is_empty() { + return; + } + let at = |q: [f64; 2]| s.eval(q[0], q[1]).0; + let dom = super::uv::domain(s); + let mean = |qs: &[[f64; 2]]| mean(s, &dom, reach, qs); + // How far the flat point `c` lies from the surface, measured along the normal at the surface + // point of the same parameters: those parameters need not be the nearest (a straight line in + // the parameters is no geodesic near a pole), and only the departure across the surface + // counts. Where the normal is undefined (a pole), the whole distance. + let off = |q: [f64; 2], c: Vec3| match s.derivs(q[0], q[1]) { + Some((p, su, sv)) => su.cross(sv).normalized().map_or_else(|| p.dist(c), |n| (p - c).dot(n).abs()), + None => at(q).dist(c), + }; + let mut pos: Vec = uv.iter().enumerate().map(|(i, q)| fixed.get(i).copied().unwrap_or_else(|| at(*q))).collect(); + // No side is split below this length: a surface whose parameters bend sharply (at a pole) is + // not chased to the last bit. + let shortest = tol * 1e-3; + let mut sides: HashMap<(u32, u32), Vec> = HashMap::with_capacity(tris.len() * 2); + for (ti, t) in tris.iter().enumerate() { + for k in 0..3 { + sides.entry(key(t[k], t[(k + 1) % 3])).or_default().push(ti as u32); + } + } + let mut sag_of: HashMap<(u32, u32), f64> = HashMap::new(); + let limit = uv.len().saturating_add(max_points); + let mut queue: Vec = (0..tris.len() as u32).rev().collect(); + while let Some(ti) = queue.pop() { + if uv.len() >= limit { + break; + } + let Some(&t) = tris.get(ti as usize) else { continue }; + let p = |i: u32| pos.get(i as usize).copied(); + let q = |i: u32| uv.get(i as usize).copied(); + let (Some(pa), Some(pb), Some(pc), Some(qa), Some(qb), Some(qc)) = (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) else { + continue; + }; + // Sides inside the face (two triangles on them), long enough to split, with their sag. + let mut inner: Vec<(f64, f64, (u32, u32))> = Vec::with_capacity(3); + for k in 0..3 { + let (a, b) = (t[k], t[(k + 1) % 3]); + let e = key(a, b); + if sides.get(&e).is_none_or(|ts| ts.len() != 2) { + continue; + } + let (Some(xa), Some(xb), Some(ua), Some(ub)) = (p(a), p(b), q(a), q(b)) else { continue }; + let len = xa.dist(xb); + if len <= shortest { + continue; + } + let sag = *sag_of.entry(e).or_insert_with(|| off(mean(&[ua, ub]), (xa + xb) * 0.5)); + inner.push((sag, len, e)); + } + // The surface's departure from a flat triangle is about quadratic over it: at the + // centroid it is 4/9 of the sum of the sags at the sides' middles, which splitting a side + // inside the face divides by four. A triangle whose middle is off splits its side inside + // the face that sags most, while that side still contributes; what is left comes from + // its boundary sides, which the edges' own sampling keeps within the tolerance. + let centroid = mean(&[qa, qb, qc]); + let worst = inner.iter().max_by(|x, y| x.0.total_cmp(&y.0)).copied(); + let split = match worst { + Some((sag, _, e)) if sag > tol => e, + Some((sag, _, e)) if sag > 0.25 * tol && off(centroid, (pa + pb + pc) * (1.0 / 3.0)) > tol => e, + _ => continue, + }; + // Splitting a triangle's shorter side leaves a child with its long side and a wider + // angle, and where the long side's middle lies on the surface (a section with an + // inflection) the children flatten toward it without end. So a triangle flattened onto its + // longest side (its widest angle past 150 degrees) splits that side, and a split never + // goes across an obtuse triangle's shorter side: that triangle's longest side is split + // first, and so on along the path (Rivara's longest-edge propagation, its lengths growing, + // so it ends). Only sides inside the face are split. + let mut split = flat_long_side(&t, &pos, &sides, shortest, 150.0).unwrap_or(split); + let mut from = ti; + while let Some(&across) = sides.get(&split).and_then(|ts| ts.iter().find(|&&o| o != from)) { + match tris.get(across as usize).and_then(|o| flat_long_side(o, &pos, &sides, shortest, 90.0)) { + Some(long) if long != split => (split, from) = (long, across), + _ => break, + } + } + // The triangle is looked at again when the split was another's, on its way. + if from != ti { + queue.push(ti); + } + let (Some(ua), Some(ub)) = (q(split.0), q(split.1)) else { continue }; + let m = mean(&[ua, ub]); + let mi = uv.len() as u32; + uv.push(m); + pos.push(at(m)); + sag_of.remove(&split); + queue.extend(split_side(tris, &mut sides, split, mi)); + } +} + +/// The mean of parameter points, as the surface point between them: at a pole the parameter +/// along the degenerate direction is free (the pole copy carries a neighbour's), so there the +/// mean takes it from the other points alone. +fn mean(s: &EvalSurface, dom: &super::uv::Domain, reach: f64, qs: &[[f64; 2]]) -> [f64; 2] { + let mut out = [0.0; 2]; + for (d, slot) in out.iter_mut().enumerate() { + let free: Vec = qs.iter().filter(|q| !super::uv::degenerate_within(s, dom, **q, d, reach)).map(|q| q[d]).collect(); + let pick: Vec = if free.is_empty() { qs.iter().map(|q| q[d]).collect() } else { free }; + *slot = pick.iter().sum::() / pick.len().max(1) as f64; + } + out +} + +/// The longest side of triangle `t` when the angle opposite it is past `degrees` and the side lies +/// inside the face (two triangles on it) and is long enough to split. +fn flat_long_side(t: &[u32; 3], pos: &[Vec3], sides: &HashMap<(u32, u32), Vec>, shortest: f64, degrees: f64) -> Option<(u32, u32)> { + let p = |i: u32| pos.get(i as usize).copied(); + let len = |k: usize| p(t[k]).zip(p(t[(k + 1) % 3])).map(|(a, b)| a.dist(b)); + let lengths = [len(0)?, len(1)?, len(2)?]; + let k = (0..3).max_by(|&i, &j| lengths[i].total_cmp(&lengths[j]))?; + let (l, a, b) = (lengths[k], lengths[(k + 1) % 3], lengths[(k + 2) % 3]); + let side = key(t[k], t[(k + 1) % 3]); + let inside = sides.get(&side).is_some_and(|ts| ts.len() == 2) && l > shortest; + let flat = a > 0.0 && b > 0.0 && (a * a + b * b - l * l) / (2.0 * a * b) < degrees.to_radians().cos(); + (inside && flat).then_some(side) +} + +fn key(a: u32, b: u32) -> (u32, u32) { + (a.min(b), a.max(b)) +} + +/// Move triangle `from` to `to` in the list of side `(a, b)`. +fn retag(sides: &mut HashMap<(u32, u32), Vec>, a: u32, b: u32, from: u32, to: u32) { + if let Some(ts) = sides.get_mut(&key(a, b)) { + for t in ts.iter_mut().filter(|t| **t == from) { + *t = to; + } + } +} + +/// Split side `e` at the new point `m`: each triangle on it becomes two, in its own winding. +/// The triangles touched, old and new. +fn split_side(tris: &mut Vec<[u32; 3]>, sides: &mut HashMap<(u32, u32), Vec>, e: (u32, u32), m: u32) -> Vec { + let on = sides.remove(&e).unwrap_or_default(); + let mut touched = Vec::with_capacity(4); + for ti in on { + let Some(&t) = tris.get(ti as usize) else { continue }; + // Turn the triangle so the side comes first, as it winds: [a, b, c]. + let Some(k) = (0..3).find(|&k| key(t[k], t[(k + 1) % 3]) == e) else { continue }; + let (a, b, c) = (t[k], t[(k + 1) % 3], t[(k + 2) % 3]); + let new = tris.len() as u32; + if let Some(slot) = tris.get_mut(ti as usize) { + *slot = [a, m, c]; + } + tris.push([m, b, c]); + retag(sides, b, c, ti, new); + sides.entry(key(a, m)).or_default().push(ti); + sides.entry(key(m, b)).or_default().push(new); + let mc = sides.entry(key(m, c)).or_default(); + mc.push(ti); + mc.push(new); + touched.extend([ti, new]); + } + touched +} + +/// The sharpest corner (radians) a flip may make. +const MIN_FLIP_ANGLE: f64 = 1e-3; + +/// Flip the sides inside a face's triangulation (as [`refine`] takes it) where the two triangles +/// on a side lie closer along the surface the other way: their facets turn less from the surface +/// normal. A layout can leave +/// slivers standing on their long side across the surface (their corners on it, their plane across +/// it), which count several times the area under them and which no split repairs; the flip lays +/// them down. A side is flipped only when both new triangles keep the orientation of the old ones +/// in (u, v) and against the surface normal (nothing folds), and the new side and the new +/// triangles' middles stay within `tol` of the surface, or no farther than the old side's middle. +/// Sides with one triangle (the face's boundary) are never flipped. +pub(crate) fn flip(s: &EvalSurface, tol: f64, reach: f64, fixed: &[Vec3], uv: &[[f64; 2]], tris: &mut [[u32; 3]]) { + if !(tol.is_finite() && tol > 0.0) || tris.len() < 2 { + return; + } + let dom = super::uv::domain(s); + let mean = |qs: &[[f64; 2]]| mean(s, &dom, reach, qs); + let pos: Vec = uv.iter().enumerate().map(|(i, q)| fixed.get(i).copied().unwrap_or_else(|| s.eval(q[0], q[1]).0)).collect(); + let p = |i: u32| pos.get(i as usize).copied(); + let q = |i: u32| uv.get(i as usize).copied(); + let off = |m: [f64; 2], c: Vec3| match s.derivs(m[0], m[1]) { + Some((x, su, sv)) => su.cross(sv).normalized().map_or_else(|| x.dist(c), |n| (x - c).dot(n).abs()), + None => s.eval(m[0], m[1]).0.dist(c), + }; + // Twice the signed area in (u, v). + let area_uv = |t: [u32; 3]| match (q(t[0]), q(t[1]), q(t[2])) { + (Some(a), Some(b), Some(c)) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]), + _ => 0.0, + }; + // The triangle's smallest angle in 3D. + let min_angle = |t: [u32; 3]| -> f64 { + let (Some(a), Some(b), Some(c)) = (p(t[0]), p(t[1]), p(t[2])) else { return 0.0 }; + let angle = |o: Vec3, x: Vec3, y: Vec3| match ((x - o).normalized(), (y - o).normalized()) { + (Some(u), Some(v)) => u.dot(v).clamp(-1.0, 1.0).acos(), + _ => 0.0, + }; + angle(a, b, c).min(angle(b, c, a)).min(angle(c, a, b)) + }; + // How far a facet's normal turns from the surface normal at its middle (radians, 0 to pi/2). + let deviation = |t: [u32; 3]| -> f64 { + let (Some(a), Some(b), Some(c), Some(qa), Some(qb), Some(qc)) = (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) else { return 0.0 }; + let m = mean(&[qa, qb, qc]); + let facet = (b - a).cross(c - a).normalized(); + match (facet, s.derivs(m[0], m[1]).and_then(|(_, su, sv)| su.cross(sv).normalized())) { + (Some(f), Some(n)) => f.dot(n).abs().clamp(0.0, 1.0).acos(), + _ => 0.0, + } + }; + // Whether the facet's normal lies on the side of the surface normal that its (u, v) + // orientation `sign` says. + let upright = |t: [u32; 3], sign: f64| -> bool { + let (Some(a), Some(b), Some(c), Some(qa), Some(qb), Some(qc)) = (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) else { return false }; + let m = mean(&[qa, qb, qc]); + match s.derivs(m[0], m[1]) { + Some((_, su, sv)) => (b - a).cross(c - a).dot(su.cross(sv)) * sign > 0.0, + None => true, + } + }; + let centroid_off = |t: [u32; 3]| match (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) { + (Some(a), Some(b), Some(c), Some(qa), Some(qb), Some(qc)) => off(mean(&[qa, qb, qc]), (a + b + c) * (1.0 / 3.0)), + _ => f64::INFINITY, + }; + let mut sides: HashMap<(u32, u32), Vec> = HashMap::with_capacity(tris.len() * 2); + for (ti, t) in tris.iter().enumerate() { + for k in 0..3 { + sides.entry(key(t[k], t[(k + 1) % 3])).or_default().push(ti as u32); + } + } + let mut queue: Vec<(u32, u32)> = sides.iter().filter(|(_, ts)| ts.len() == 2).map(|(e, _)| *e).collect(); + queue.sort_unstable(); + let mut budget = tris.len().saturating_mul(8); + // Each triangle's deviation, until it is flipped. + let mut dev_of: Vec> = vec![None; tris.len()]; + while let Some(e) = queue.pop() { + if budget == 0 { + break; + } + let Some(&[t1, t2]) = sides.get(&e).map(|v| v.as_slice()) else { continue }; + let (Some(&ta), Some(&tb)) = (tris.get(t1 as usize), tris.get(t2 as usize)) else { continue }; + // [a, b, c] on one side of a -> b, [b, a, d] on the other. + let Some(k) = (0..3).find(|&k| key(ta[k], ta[(k + 1) % 3]) == e) else { continue }; + let (a, b, c) = (ta[k], ta[(k + 1) % 3], ta[(k + 2) % 3]); + let Some(d) = tb.iter().copied().find(|&v| v != a && v != b) else { continue }; + if c == d || sides.contains_key(&key(c, d)) { + continue; + } + let (n1, n2) = ([a, d, c], [d, b, c]); + let sign = area_uv(ta).signum(); + if sign == 0.0 || area_uv(tb).signum() != sign || area_uv(n1) * sign <= 0.0 || area_uv(n2) * sign <= 0.0 { + continue; + } + // The pair the other way must lie closer along the surface (its facets turn less from + // the surface normal), by more than a degree: a pair within a degree of the surface is + // left as the layout made it. + let mut cached = |ti: u32, t: [u32; 3]| match dev_of.get(ti as usize).copied().flatten() { + Some(d) => d, + None => { + let d = deviation(t); + if let Some(slot) = dev_of.get_mut(ti as usize) { + *slot = Some(d); + } + d + } + }; + let worse = cached(t1, ta).max(cached(t2, tb)); + let degree = 1f64.to_radians(); + if worse < degree || deviation(n1).max(deviation(n2)) >= worse - degree { + continue; + } + // ... and have area in 3D (three corners on one line of a cone have none, however they + // lie in (u, v)). + if min_angle(n1).min(min_angle(n2)) < MIN_FLIP_ANGLE { + continue; + } + if !(upright(n1, sign) && upright(n2, sign)) { + continue; + } + let (Some(pa), Some(pb), Some(pc), Some(pd), Some(qa), Some(qb), Some(qc), Some(qd)) = (p(a), p(b), p(c), p(d), q(a), q(b), q(c), q(d)) + else { + continue; + }; + let allowed = tol.max(off(mean(&[qa, qb]), (pa + pb) * 0.5)).max(centroid_off(ta)).max(centroid_off(tb)); + if off(mean(&[qc, qd]), (pc + pd) * 0.5) > allowed || centroid_off(n1) > allowed || centroid_off(n2) > allowed { + continue; + } + budget -= 1; + for ti in [t1, t2] { + if let Some(slot) = dev_of.get_mut(ti as usize) { + *slot = None; + } + } + if let Some(slot) = tris.get_mut(t1 as usize) { + *slot = n1; + } + if let Some(slot) = tris.get_mut(t2 as usize) { + *slot = n2; + } + sides.remove(&e); + sides.insert(key(c, d), vec![t1, t2]); + // a-d moves from t2 to t1, b-c from t1 to t2. + retag(&mut sides, a, d, t2, t1); + retag(&mut sides, b, c, t1, t2); + queue.extend([key(a, d), key(d, b), key(b, c), key(c, a)].into_iter().filter(|s| sides.get(s).is_some_and(|ts| ts.len() == 2))); + } +} diff --git a/crates/kernel/src/tess/seam.rs b/crates/kernel/src/tess/seam.rs index 1982cb67c..f1bc48e0e 100644 --- a/crates/kernel/src/tess/seam.rs +++ b/crates/kernel/src/tess/seam.rs @@ -7,7 +7,7 @@ //! the two lines inside the face join the pieces into closed loops. Both lines are one curve //! on the surface, so their nodes are made once and shared: the face stays closed across it. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_geom::tess::EvalSurface; use super::size::Rules; @@ -37,41 +37,6 @@ pub(crate) fn winds(loops: &[Loop], d: usize, per: f64) -> bool { loops.iter().any(|l| drift(l, d, per).abs() > per * 0.5) } -/// A loop through a pole of the closed direction `d` (a cone's apex or a sphere's pole on the -/// boundary): the parameter along `d` is free there, so the step into or out of the pole may be -/// any length. Unwrapped to the nearest copy at every step, a sector wider than half a turn, or -/// a cone face written as its rim, the seam up to the apex and the seam back (as STEP files -/// write a pointed end, a screw's tip), seems to wind around the surface, and the face cannot -/// be cut along a seam it does not have. The step out of the pole is made the one that closes -/// the loop. A loop that closes already, has no pole or passes more than one stays as it is. -pub(crate) fn close_through_pole(s: &EvalSurface, l: &mut Loop, d: usize, per: f64) { - let w = drift(l, d, per); - let n = l.uv.len(); - if w.abs() <= per * 0.5 || n < 3 || l.pts.len() != n { - return; - } - let pole: Vec = l.uv.iter().map(|q| super::uv::degenerate(s, *q, d)).collect(); - let Some(k) = pole.iter().position(|p| *p) else { return }; - // The node the loop leaves the pole for: the loop is turned to end there, so the step that - // closes it is an ordinary one, and the step from the pole takes what is left. A loop - // through a pole twice is left alone. - let Some(out) = (1..n).map(|i| (k + i) % n).find(|&i| !pole.get(i).copied().unwrap_or(true)) else { return }; - if pole.iter().enumerate().any(|(i, p)| *p && (i + n - out) % n < (k + n - out) % n) { - return; - } - let start = (out + 1) % n; - l.uv.rotate_left(start); - l.pts.rotate_left(start); - // Unwrapped again from the new start; the last node, where the loop leaves the pole, is - // taken next to the first instead of next to the pole. - for i in 1..n { - let near = if i + 1 == n { l.uv.first() } else { l.uv.get(i - 1) }.map(|q| q[d]); - if let (Some(near), Some(q)) = (near, l.uv.get_mut(i)) { - q[d] = super::uv::unwrap(q[d], near, Some(per)); - } - } -} - /// A point where the boundary crosses a cut line: its place along the line, its 3D point, and /// whether the face lies above it (towards larger parameters across the line) or below. #[derive(Clone, Copy, Debug)] @@ -384,65 +349,3 @@ fn seam_nodes(s: &EvalSurface, swap: bool, x: f64, y0: f64, y1: f64, rules: &Rul let inner = ys.get(1..ys.len() - 1)?; Some(inner.iter().map(|&y| (y, s.eval(uv(y)[0], uv(y)[1]).0)).collect()) } - -/// Whether a face of `solid` lies on a B-spline surface that joins itself (a lofted tube). -/// Truck meshes a face in its surface's parameters and treats only a revolved surface's -/// rotation as periodic, so a face that runs across such a join comes out folded over itself or -/// with a hole in it. The reference mesh of such a body is made from the display plan, -/// which knows the join is periodic. -pub(crate) fn closes_on_itself(solid: &crate::body::Solid) -> bool { - solid.face_iter().any(|f| matches!(super::surface::eval_surface(&f.surface()), Some(EvalSurface::Nurbs { closed, .. }) if closed[0] || closed[1])) -} - -/// Whether a face of `solid` lies on a surface of revolution and has a boundary loop turning -/// more than once around its axis (a helical trim). Truck's mesher cannot mesh such a face (its -/// triangles cut across the solid), so the reference mesh is made from the display plan instead. -pub(crate) fn turns_more_than_once(solid: &crate::body::Solid) -> bool { - use truck_meshalgo::prelude::*; - use truck_modeling as mt; - let tau = std::f64::consts::TAU; - for face in solid.face_iter() { - let mt::Surface::RevolutedCurve(proc) = face.surface() else { continue }; - let rev = proc.entity(); - let m = *proc.transform(); - let o = crate::body::from_p3(m.transform_point(rev.origin())); - let a = m.transform_vector(rev.axis()); - let Some(k) = Vec3::new(a.x, a.y, a.z).normalized() else { continue }; - let e1 = k.cross(if k.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).normalized().unwrap_or(Vec3::X); - let e2 = k.cross(e1); - let angle = |p: mt::Point3| { - let d = crate::body::from_p3(p) - o; - d.dot(e2).atan2(d.dot(e1)) - }; - for wire in face.boundaries() { - let (mut total, mut lo, mut hi) = (0.0f64, 0.0f64, 0.0f64); - let mut prev: Option = None; - for e in wire.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - // Samples dense enough that no step turns half way round. - let mut n = 16usize; - let steps = loop { - let xs: Vec = (0..=n).map(|i| angle(c.subs(t0 + (t1 - t0) * i as f64 / n as f64))).collect(); - let ok = xs.windows(2).all(|w| ((w[1] - w[0] + std::f64::consts::PI).rem_euclid(tau) - std::f64::consts::PI).abs() < 1.0); - if ok || n >= 4096 { - break xs; - } - n *= 4; - }; - for x in steps { - if let Some(p) = prev { - total += (x - p + std::f64::consts::PI).rem_euclid(tau) - std::f64::consts::PI; - lo = lo.min(total); - hi = hi.max(total); - } - prev = Some(x); - } - } - if hi - lo > tau * 1.01 { - return true; - } - } - } - false -} diff --git a/crates/kernel/src/tess/size.rs b/crates/kernel/src/tess/size.rs index 357a5b2a5..6fd8804e8 100644 --- a/crates/kernel/src/tess/size.rs +++ b/crates/kernel/src/tess/size.rs @@ -6,7 +6,8 @@ //! sags the tolerance; an edge takes the smaller size of its two faces, so a curved face and //! its flat neighbour meet at the same spacing. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_geom::tess::EvalSurface; use super::uv::Domain; @@ -26,6 +27,13 @@ const MIN_LEN_FRACTION: f64 = 1.0 / 4.0; /// Curvature samples per parameter direction. const SAMPLES: usize = 9; +/// Most segments a face's boundary may get from the facet angle: past it, the face's curved +/// edges are sampled again at twice the angle (a plate with a thousand small holes is not worth +/// a hundred times the work to draw each hole round). +pub(crate) const MAX_ANGLE_BOUNDARY: usize = 4096; +/// How often the angle is doubled for a crowded face before only the chord tolerance is left. +pub(crate) const MAX_RELAX: u8 = 4; + /// The most one facet may turn (radians): an edge segment's tangent or a cell's surface normal. /// The angle divides only where a facet would sag more than `floor` (mm), so a radius far below /// the tolerance keeps its chord facets. @@ -41,12 +49,11 @@ impl Turn { sag > self.floor && angle > self.angle } - /// The angle doubled `level` times, as the reference mesher relaxes it for a crowded face; - /// from its last level, or past half a turn, no angle at all (the tolerance alone). + /// The angle doubled `level` times, for a crowded face (see [`MAX_ANGLE_BOUNDARY`]); from + /// level [`MAX_RELAX`], or past half a turn, no angle at all (the tolerance alone). pub(crate) fn relaxed(&self, level: u8) -> Option { - use truck_meshalgo::tessellation::Deflection; - let angle = self.angle * f64::from(1u32 << u32::from(level.min(Deflection::MAX_RELAX))); - (level == 0 || (level < Deflection::MAX_RELAX && angle < std::f64::consts::PI)).then_some(Turn { angle, ..*self }) + let angle = self.angle * f64::from(1u32 << u32::from(level.min(MAX_RELAX))); + (level == 0 || (level < MAX_RELAX && angle < std::f64::consts::PI)).then_some(Turn { angle, ..*self }) } } @@ -55,35 +62,14 @@ impl Turn { pub(crate) struct Rules { pub tol: f64, pub max_len: f64, - /// The body's extent (see [`extent`]); 0 when it has none. Tolerances that measure the - /// body's own geometry rather than the mesh are fractions of it. - pub extent: f64, pub turn: Option, - /// How far the body's boundaries may lie off their surfaces (mm), as the file the body was - /// read from declares; `None` for a body this kernel built (see - /// [`crate::body::Body::boundary_tol`]). It raises the planner's bound (a hundredth of the - /// extent) where it is larger, never lowers it. - pub boundary_tol: Option, } impl Rules { - /// The same rules with a chord tolerance `k` times finer. - pub(crate) fn finer(self, k: f64) -> Rules { - Rules { tol: self.tol / k, ..self } - } - - /// Rules for a body of extent `extent` (see [`extent`]). `boundary_tol`: the body's declared - /// off-surface budget (mm), `None` for a body this kernel built. - pub(crate) fn new(tol: f64, extent: f64, turn: Option, boundary_tol: Option) -> Rules { - let sound = extent.is_finite() && extent > 0.0; - let max_len = if sound { extent * MAX_LEN_FRACTION } else { f64::INFINITY }; - Rules { - tol, - max_len: max_len.max(tol), - extent: if sound { extent } else { 0.0 }, - turn, - boundary_tol: boundary_tol.filter(|t| t.is_finite() && *t > 0.0), - } + /// Rules for a body of extent `extent` (see [`extent`]). + pub(crate) fn new(tol: f64, extent: f64, turn: Option) -> Rules { + let max_len = if extent.is_finite() && extent > 0.0 { extent * MAX_LEN_FRACTION } else { f64::INFINITY }; + Rules { tol, max_len: max_len.max(tol), turn } } /// The side length for a curvature `k` (1/mm): the chord sags at most the tolerance across @@ -193,36 +179,37 @@ mod tests { swap: false, }; // A 20 mm body: sides from 1 mm (the floor, a quarter of the longest) to 4 mm. - let rules = Rules::new(0.01, 20.0, THIRTY, None); + let rules = Rules::new(0.01, 20.0, THIRTY); let (h, speed) = face_size(&s, &super::super::uv::domain(&s), &rules); // r = 3: 30° of turn is 1.57 mm; the 0.01 mm sag chord is √(8·3·0.01) = 0.49 mm, times the // aspect, unless that is under the floor. assert!((h - (ASPECT * (8.0 * 3.0 * 0.01f64).sqrt()).max(20.0 * MAX_LEN_FRACTION * MIN_LEN_FRACTION)).abs() < 0.01, "{h}"); assert!((speed[0] - 40.0).abs() < 1e-6 && (speed[1] - 3.0).abs() < 1e-6, "{speed:?}"); // Coarser: the turn limit governs. - let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, THIRTY, None)); + let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, THIRTY)); assert!((h - (ASPECT * 3.0 * std::f64::consts::PI / 6.0).max(100.0 * MAX_LEN_FRACTION * MIN_LEN_FRACTION)).abs() < 0.01, "{h}"); // Without a facet angle the sag alone: √(8·3·0.5) = 3.46 mm, four times along. - let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, None, None)); + let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, None)); assert!((h - ASPECT * (8.0 * 3.0 * 0.5f64).sqrt()).abs() < 0.01, "{h}"); // A turn that sags below its floor does not divide. let floored = Some(Turn { angle: std::f64::consts::PI / 6.0, floor: 1.0 }); - let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, floored, None)); + let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, floored)); assert!((h - ASPECT * (8.0 * 3.0 * 0.5f64).sqrt()).abs() < 0.01, "{h}"); } #[test] fn a_flat_spline_is_planar_and_a_bent_one_is_not() { - let patch = |z: f64| EvalSurface::Nurbs { - degree: [1, 1], - knots: [vec![0.0, 0.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], - count: [2, 2], - ctrl: vec![[0.0, 0.0, 0.0, 1.0], [4.0, 0.0, 0.0, 1.0], [0.0, 3.0, 0.0, 1.0], [4.0, 3.0, z, 1.0]], - closed: [false, false], + let patch = |z: f64| { + EvalSurface::nurbs( + [1, 1], + [vec![0.0, 0.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], + [2, 2], + vec![[0.0, 0.0, 0.0, 1.0], [4.0, 0.0, 0.0, 1.0], [0.0, 3.0, 0.0, 1.0], [4.0, 3.0, z, 1.0]], + ) }; assert!(planar(&patch(0.0))); assert!(!planar(&patch(0.5))); - let rules = Rules::new(0.01, 100.0, THIRTY, None); + let rules = Rules::new(0.01, 100.0, THIRTY); let (h, speed) = face_size(&patch(0.0), &super::super::uv::domain(&patch(0.0)), &rules); assert_eq!(h, rules.max_len); assert!((speed[0] - 4.0).abs() < 1e-9 && (speed[1] - 3.0).abs() < 1e-9, "{speed:?}"); @@ -239,7 +226,7 @@ mod tests { transform: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], swap: false, }; - let rules = Rules::new(0.1, 100.0, THIRTY, None); + let rules = Rules::new(0.1, 100.0, THIRTY); let (h, _) = face_size(&s, &super::super::uv::domain(&s), &rules); assert!((h - rules.max_len * MIN_LEN_FRACTION).abs() < 1e-9, "{h}"); } @@ -247,7 +234,7 @@ mod tests { #[test] fn a_plane_takes_the_longest_side() { let s = EvalSurface::Plane { origin: Vec3::ZERO, du: Vec3::X, dv: Vec3::Y }; - let rules = Rules::new(0.01, 100.0, THIRTY, None); + let rules = Rules::new(0.01, 100.0, THIRTY); assert_eq!(face_size(&s, &super::super::uv::domain(&s), &rules).0, 20.0); } } diff --git a/crates/kernel/src/tess/ssi.rs b/crates/kernel/src/tess/ssi.rs deleted file mode 100644 index ca32e9487..000000000 --- a/crates/kernel/src/tess/ssi.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Points on a surface–surface intersection edge, on our own surface evaluators. -//! -//! truck stores an intersection edge as a leader curve (a polyline or B-spline near the -//! intersection) and its two surfaces, and finds each point by projecting the leader point onto -//! each surface in turn from no starting guess: a nearest-point search per surface per point. -//! Here the intersection is solved exactly at a set of leader parameters, and a cubic B-spline -//! is fitted through those points together with both surfaces' parameters there (a smooth -//! leader with its curves on both surfaces). The B-spline runs over the chord length of the -//! solved points, never over the curve's own parameter: truck's parameter can change speed -//! abruptly (a polyline leader with short and long spans), and a cubic interpolated over it -//! rings there, stepping back along the curve (Lee, "Choosing nodes in parametric curve -//! interpolation", CAD 21, 1989). The curve's parameter reaches the chord length through the -//! piecewise-linear map between the seeds, which is monotone. Each point is then refined from -//! the B-spline by Newton's method on the four unknowns (u1, v1, u2, v2): S1(u1, v1) = S2(u2, v2), held on the -//! plane through the B-spline point normal to the B-spline (Barnhill & Kersey, "A marching -//! method for parametric surface/surface intersection", CAGD 7, 1990; Patrikalakis & Maekawa, -//! "Shape Interrogation for CAD/CAM", 2002, ch. 5). Every point is independent once seeded. Where the surfaces are close to -//! tangent along the edge (the system becomes singular) or Newton does not converge, the caller -//! uses truck's evaluation. - -use solidcraft_geom::Vec3; -use solidcraft_geom::bspline::CurveN; -use solidcraft_geom::tess::EvalSurface; -use truck_meshalgo::prelude::*; -use truck_modeling as mt; - -use super::uv::{self, Domain}; -use crate::body::from_p3; - -/// Leader parameters at which both surfaces' parameters are found up front. -const SEEDS: usize = 32; -/// Newton iterations per point (two or three suffice from a seed). -const MAX_ITER: usize = 8; -/// Below this sine of the angle between the surface normals the intersection is treated as -/// near-tangent: points there are left to truck. -const MIN_SIN: f64 = 0.05; - -/// An intersection edge ready for point evaluation. -pub(crate) struct Intersection { - surfaces: [EvalSurface; 2], - domains: [Domain; 2], - /// The smooth leader over the chord length of the seeds: the intersection point (x, y, z) - /// and both surfaces' parameters (u1, v1, u2, v2), periodic directions unwrapped along it. - leader: CurveN<7>, - /// The curve's parameter at each seed and the chord length there, both increasing. - seeds: Vec<(f64, f64)>, - /// Convergence tolerance (mm). - eps: f64, -} - -impl Intersection { - /// `None` unless `curve` is an intersection curve whose surfaces have evaluators and whose - /// leader projects onto both. - pub(crate) fn new(curve: &mt::Curve) -> Option { - let mt::Curve::IntersectionCurve(ic) = curve else { return None }; - let surfaces = [super::surface::eval_surface(ic.surface0())?, super::surface::eval_surface(ic.surface1())?]; - let domains = [uv::domain(&surfaces[0]), uv::domain(&surfaces[1])]; - let (t0, t1) = curve.range_tuple(); - if !(t0.is_finite() && t1.is_finite() && t1 > t0) { - return None; - } - let leader = |t: f64| match ic.leader() { - mt::Leader::Polyline(l) => (from_p3(l.subs(t)), from_v3(l.der(t))), - mt::Leader::BSpline(l) => (from_p3(l.subs(t)), from_v3(l.der(t))), - }; - // The leader lies within the curve's tolerance of both surfaces. - let accept = (ic.tolerance() * 100.0).max(1e-6); - let scale = (0..=SEEDS).map(|k| leader(t0 + (t1 - t0) * k as f64 / SEEDS as f64).0.len()).fold(1.0, f64::max); - let mut it = Intersection { - surfaces, - domains, - leader: CurveN { degree: 1, knots: Vec::new(), ctrl: Vec::new() }, - seeds: Vec::new(), - eps: scale * 1e-10, - }; - let (mut params, mut points): (Vec, Vec<[f64; 7]>) = (Vec::with_capacity(SEEDS + 1), Vec::with_capacity(SEEDS + 1)); - let mut prev: Option<[f64; 4]> = None; - for k in 0..=SEEDS { - let t = t0 + (t1 - t0) * k as f64 / SEEDS as f64; - let (p, d) = leader(t); - let mut q = [0.0; 4]; - for (i, (s, dom)) in it.surfaces.iter().zip(&it.domains).enumerate() { - let hint = prev.map(|w| [w[2 * i], w[2 * i + 1]]); - let mut uv = uv::project(s, dom, p, hint, accept)?; - if let Some(h) = hint { - for d in 0..2 { - uv[d] = uv::unwrap(uv[d], h[d], dom.period[d]); - } - } - q[2 * i] = uv[0]; - q[2 * i + 1] = uv[1]; - } - // The fit takes only points exactly on the intersection: a leader point Newton - // cannot place (near-tangent, or the solution leaves a surface's domain where a - // polyline leader overshoots a vertex) is off the curve and would bend the fit back - // along it. The ends stay either way, so the fit spans the whole curve. - let solved = d.normalized().and_then(|dir| it.newton(p, dir, q)); - prev = Some(solved.map_or(q, |(_, q)| q)); - let (p, q) = match solved { - Some(x) => x, - None if k == 0 || k == SEEDS => (p, q), - None => continue, - }; - // A seed that lands on the previous one adds no chord and stays out of the fit - // (whose parameters must increase). - let s = match it.seeds.last().zip(points.last()) { - Some((&(_, s), &[x, y, z, ..])) => { - let chord = p.dist(Vec3::new(x, y, z)); - if !(chord > it.eps) { - continue; - } - s + chord - } - None => 0.0, - }; - it.seeds.push((t, s)); - params.push(s); - points.push([p.x, p.y, p.z, q[0], q[1], q[2], q[3]]); - } - let degree = points.len().checked_sub(1)?.min(3); - it.leader = CurveN::interpolate(¶ms, &points, degree).ok()?; - Some(it) - } - - /// The point at curve parameter `t` and both surfaces' parameters there, or `None` - /// (near-tangent, or Newton failed). - pub(crate) fn eval(&self, t: f64) -> Option<(Vec3, [f64; 4])> { - let (x, dx) = self.leader.eval(self.chord_at(t)?)?; - let dir = Vec3::new(dx[0], dx[1], dx[2]).normalized()?; - self.newton(Vec3::new(x[0], x[1], x[2]), dir, [x[3], x[4], x[5], x[6]]) - } - - /// The chord length at curve parameter `t`: linear between the seeds, clamped to the ends. - fn chord_at(&self, t: f64) -> Option { - let (&(ta, sa), &(tb, sb)) = (self.seeds.first()?, self.seeds.last()?); - if !(t > ta) { - return Some(sa); - } - if !(t < tb) { - return Some(sb); - } - let k = self.seeds.partition_point(|&(tk, _)| tk <= t); - let (Some(&(t0, s0)), Some(&(t1, s1))) = (<[_]>::get(&self.seeds, k.checked_sub(1)?), <[_]>::get(&self.seeds, k)) else { return None }; - Some(s0 + (s1 - s0) * (t - t0) / (t1 - t0)) - } - - /// The two surfaces, in the order of the parameters [`Intersection::eval`] gives. - pub(crate) fn surfaces(&self) -> &[EvalSurface; 2] { - &self.surfaces - } - - /// Newton from the parameters `x` on S1 = S2, held on the plane through `l` normal to `dir`: - /// the point and its parameters, or `None` (near-tangent, singular, or not converged). - fn newton(&self, l: Vec3, dir: Vec3, mut x: [f64; 4]) -> Option<(Vec3, [f64; 4])> { - for _ in 0..MAX_ITER { - let (Some((p1, u1, v1)), Some((p2, u2, v2))) = (self.surfaces[0].derivs(x[0], x[1]), self.surfaces[1].derivs(x[2], x[3])) else { - return None; - }; - let gap = p1 - p2; - let plane = dir.dot(p1 - l); - let n = u1.cross(v1).normalized()?.cross(u2.cross(v2).normalized()?); - if n.len() < MIN_SIN { - return None; - } - if gap.len() <= self.eps && plane.abs() <= self.eps { - return Some(((p1 + p2) * 0.5, x)); - } - // J · dx = −F, F = (S1 − S2, dir · (S1 − L)). - let j = [[u1.x, v1.x, -u2.x, -v2.x], [u1.y, v1.y, -u2.y, -v2.y], [u1.z, v1.z, -u2.z, -v2.z], [dir.dot(u1), dir.dot(v1), 0.0, 0.0]]; - let dx = solve4(j, [-gap.x, -gap.y, -gap.z, -plane])?; - for (xi, d) in x.iter_mut().zip(dx) { - *xi += d; - } - for i in 0..2 { - let [u, v] = self.domains[i].clamp([x[2 * i], x[2 * i + 1]]); - x[2 * i] = u; - x[2 * i + 1] = v; - } - } - None - } -} - -fn from_v3(v: mt::Vector3) -> Vec3 { - Vec3::new(v.x, v.y, v.z) -} - -/// `a · x = b` for a 4 × 4 system by Gaussian elimination with partial pivoting; `None` when -/// singular. -fn solve4(mut a: [[f64; 4]; 4], mut b: [f64; 4]) -> Option<[f64; 4]> { - let scale = a.iter().flatten().fold(0.0f64, |m, x| m.max(x.abs())); - if !(scale > 0.0) { - return None; - } - for c in 0..4 { - let p = (c..4).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?; - if !(a[p][c].abs() > 1e-12 * scale) { - return None; - } - a.swap(c, p); - b.swap(c, p); - let pivot = a[c]; - for r in c + 1..4 { - let f = a[r][c] / pivot[c]; - for (x, p) in a[r].iter_mut().zip(pivot).skip(c) { - *x -= f * p; - } - b[r] -= f * b[c]; - } - } - let mut x = [0.0; 4]; - for c in (0..4).rev() { - let s: f64 = (c + 1..4).map(|k| a[c][k] * x[k]).sum(); - x[c] = (b[c] - s) / a[c][c]; - } - x.iter().all(|v| v.is_finite()).then_some(x) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn solves_a_four_by_four_system() { - let a = [[2.0, 1.0, 0.0, 0.0], [1.0, 3.0, 1.0, 0.0], [0.0, 1.0, 4.0, 1.0], [0.0, 0.0, 1.0, 5.0]]; - let x = [1.0, -2.0, 0.5, 3.0]; - let b = [0, 1, 2, 3].map(|r| (0..4).map(|c| a[r][c] * x[c]).sum::()); - let Some(got) = solve4(a, b) else { panic!("solves") }; - for (g, w) in got.iter().zip(x) { - assert!((g - w).abs() < 1e-12); - } - assert!(solve4([[1.0; 4]; 4], [1.0; 4]).is_none(), "singular"); - } - - /// Points on the intersection edges of a boolean (a cross hole: two cylinders) lie on both - /// surfaces, on truck's curve (the parameterisation follows our smooth leader, so the same - /// parameter may sit at a slightly different place along it), and advance along it. - #[test] - fn intersection_points_lie_on_both_surfaces_and_on_truck_s_curve() { - let Ok(pin) = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 6.0) else { panic!("pin") }; - let Ok(cross) = crate::cylinder(Vec3::new(5.0, -1.0, 2.0), Vec3::Y, 1.0, 12.0) else { panic!("cross") }; - let Ok(Some(body)) = crate::boolean(&pin, &cross, crate::BoolOp::Cut) else { panic!("cut") }; - let mut checked = 0; - for e in body.solid.edge_iter() { - let curve = e.curve(); - let Some(ix) = Intersection::new(&curve) else { continue }; - let (t0, t1) = curve.range_tuple(); - let dense: Vec = (0..=1000).map(|k| from_p3(curve.subs(t0 + (t1 - t0) * f64::from(k) / 1000.0))).collect(); - let near = |p: Vec3| dense.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::MAX, f64::min); - // Arc length along truck's curve to the point nearest `p`. - let along = |p: Vec3| { - let (mut run, mut best) = (0.0, (f64::MAX, 0.0)); - for w in dense.windows(2) { - let (a, b) = (w[0], w[1]); - let len = a.dist(b); - let f = if len > 0.0 { ((p - a).dot(b - a) / (len * len)).clamp(0.0, 1.0) } else { 0.0 }; - let d = p.dist(a + (b - a) * f); - if d < best.0 { - best = (d, run + f * len); - } - run += len; - } - best.1 - }; - let mut last: Option = None; - for k in 0..=50 { - let t = t0 + (t1 - t0) * f64::from(k) / 50.0; - let Some((p, _)) = ix.eval(t) else { continue }; - for (s, dom) in ix.surfaces.iter().zip(&ix.domains) { - assert!(uv::project(s, dom, p, None, 1e-8).is_some(), "t {t}: {p:?} off a surface"); - } - assert!(near(p) < 1e-4, "t {t}: {p:?} is {} from truck's curve", near(p)); - if let Some(q) = last { - assert!(along(p) > along(q), "t {t}: the points advance along the curve"); - } - last = Some(p); - checked += 1; - } - } - assert!(checked > 100, "{checked} points checked"); - } -} diff --git a/crates/kernel/src/tess/surface.rs b/crates/kernel/src/tess/surface.rs index 86b254fb4..63851cecd 100644 --- a/crates/kernel/src/tess/surface.rs +++ b/crates/kernel/src/tess/surface.rs @@ -1,154 +1,204 @@ -//! Truck surfaces in the evaluator's form ([`EvalSurface`]), which the CPU and GPU evaluators -//! share. Surfaces the evaluators cannot express (a revolved intersection curve) or that are -//! too large for them give `None`; their faces are evaluated here instead. +//! Surface records ([`brep::Surface`]) in the evaluator's form ([`EvalSurface`]), which the +//! planner and the CPU and GPU evaluators share, and the map from the record's (u, v) to the +//! evaluator's, so a face's boundary takes its parameters from its edges' exact pcurves. +//! Planes, splines and revolutions keep their own parameters ([`SurfaceEval`] holds them in +//! that form already). A cylinder, cone, sphere or torus is the revolution it is, exactly: its +//! generator (a line, or a circle as an exact rational arc) turned about its axis by the +//! record's angle u; the generator's parameter is −v on a line and, on an arc, the rational +//! parameter of the record's angle v (closed form, [`Arc::param`]). -use solidcraft_geom::Vec3; -use solidcraft_geom::bspline::MAX_SPLINE_DEGREE; -use solidcraft_geom::tess::{EvalCurve, EvalSurface, MAX_EVAL_KNOTS, MAX_EVAL_POINTS}; -use truck_meshalgo::prelude::*; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{self, Frame}; +use solidcraft_geom::brep::eval::SurfaceEval; +use solidcraft_geom::prelude::*; +use solidcraft_geom::tess::{EvalCurve, EvalSurface}; -use crate::body::from_p3; +use crate::{KernelError, Result}; -/// `surface` in the evaluator's form, parameterised exactly as truck parameterises it. -pub(crate) fn eval_surface(surface: &mt::Surface) -> Option { - let s = match surface { - mt::Surface::Plane(p) => { - EvalSurface::Plane { origin: from_p3(p.subs(0.0, 0.0)), du: from_v3(p.uder(0.0, 0.0)), dv: from_v3(p.vder(0.0, 0.0)) } - } - mt::Surface::BSplineSurface(b) => { - let ctrl = b.control_points().iter().map(|row| row.iter().map(|p| [p.x, p.y, p.z, 1.0]).collect()).collect(); - nurbs(b.degrees(), b.knot_vecs(), ctrl)? - } - mt::Surface::NurbsSurface(n) => { - let ctrl = n.control_points().iter().map(|row| row.iter().map(|h| [h.x, h.y, h.z, h.w]).collect()).collect(); - nurbs((n.udegree(), n.vdegree()), n.knot_vecs(), ctrl)? - } - mt::Surface::RevolutedCurve(proc) => { - let rev = proc.entity(); - let profile = eval_curve(rev.entity_curve())?; - let axis = from_v3(rev.axis()).normalized()?; - let m = proc.transform(); - // cgmath is column-major: m[column][row]. - let transform = [0, 1, 2].map(|r| [m[0][r], m[1][r], m[2][r], m[3][r]]); - if transform.iter().flatten().any(|x| !x.is_finite()) { - return None; - } - EvalSurface::Revolved { profile, origin: from_p3(rev.origin()), axis, transform, swap: !proc.orientation() } +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// No transform: the revolution as it is. +const IDENTITY: [[f64; 4]; 3] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + +/// How a face's record parameters become its evaluator's. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Params { + /// The same parameters (planes, splines, revolutions). + Same, + /// A cylinder or cone: (angle, height) to (−height, angle). + Height, + /// A sphere or torus: (angle, meridian angle) to (the reversed arc's parameter, angle). + Meridian(Arc), +} + +impl Params { + /// The evaluator's parameters of the record's `uv`. + pub(crate) fn to_eval(self, uv: [f64; 2]) -> [f64; 2] { + let [u, v] = uv; + match self { + Params::Same => uv, + Params::Height => [-v, u], + Params::Meridian(a) => [1.0 - a.param(v), u], } + } +} + +/// The spans of a circular arc made by [`arc`]: from angle `start`, `count` spans of `step` +/// each, over the parameter [0, 1]; `periodic` for a whole turn. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Arc { + start: f64, + step: f64, + count: usize, + periodic: bool, +} + +impl Arc { + /// The arc's parameter at `angle`. On a rational quadratic span of half angle α with middle + /// weight cos α, tan(θ / 2) runs linearly from −tan(α / 2) to tan(α / 2) with the span's + /// own parameter (θ from the span's middle). A whole turn continues by whole parameters. + pub(crate) fn param(&self, angle: f64) -> f64 { + let total = self.step * self.count as f64; + let turns = if self.periodic { ((angle - self.start) / total).floor() } else { 0.0 }; + let a = angle - turns * total; + let i = (((a - self.start) / self.step).floor().max(0.0) as usize).min(self.count.saturating_sub(1)); + let half = 0.5 * self.step; + let local = a - (self.start + (i as f64 + 0.5) * self.step); + let s = 0.5 * ((0.5 * local).tan() / (0.5 * half).tan() + 1.0); + (i as f64 + s) / self.count as f64 + turns + } +} + +/// `surface` in the evaluator's form, and how the record's parameters map onto it. `domain` is +/// the face's parameter box in the record's parameters, `[[u0, u1], [v0, v1]]`: a cylinder's +/// or cone's generator spans the face's heights. +pub(crate) fn eval_surface(surface: &brep::Surface, domain: [[f64; 2]; 2]) -> Result<(EvalSurface, Params)> { + use std::f64::consts::{FRAC_PI_2, TAU}; + let invalid = |what: &str| KernelError::Invalid(format!("tessellation: {what}")); + let axes = |f: &Frame| { + let (o, x, y) = (v3(f.origin), v3(f.x_axis), v3(f.y_axis)); + (o, x, x.cross(y)) }; - Some(s) -} - -fn from_v3(v: mt::Vector3) -> Vec3 { - Vec3::new(v.x, v.y, v.z) -} - -fn knots(k: &mt::KnotVec) -> Option> { - let v: Vec = k.iter().copied().collect(); - (v.len() <= MAX_EVAL_KNOTS && v.iter().all(|x| x.is_finite())).then_some(v) -} - -/// Truck's `control_points[i][j]` (i along u) as the evaluator's u-fastest array. -fn nurbs((pu, pv): (usize, usize), kv: &(mt::KnotVec, mt::KnotVec), rows: Vec>) -> Option { - let nu = rows.len(); - let nv = rows.first()?.len(); - if pu == 0 || pv == 0 || pu > MAX_SPLINE_DEGREE || pv > MAX_SPLINE_DEGREE || nu.checked_mul(nv)? > MAX_EVAL_POINTS { - return None; - } - let mut ctrl = Vec::with_capacity(nu * nv); - for j in 0..nv { - for row in &rows { - ctrl.push(<[[f64; 4]]>::get(row, j).copied()?); - } - } - if ctrl.iter().flatten().any(|x| !x.is_finite()) { - return None; - } - let knots = [knots(&kv.0)?, knots(&kv.1)?]; - if !(knots[0].len() == nu + pu + 1 && knots[1].len() == nv + pv + 1) { - return None; - } - let closed = [closed_along(0, &ctrl, [nu, nv], [pu, pv], &knots), closed_along(1, &ctrl, [nu, nv], [pu, pv], &knots)]; - Some(EvalSurface::Nurbs { degree: [pu, pv], knots, count: [nu, nv], ctrl, closed }) -} - -/// Does the surface join itself along direction `d` (a tube's way round)? Its knots there must -/// be clamped, so the ends of the range are the first and last rows of control points, and -/// those two rows must be the same points: the join is then the parameter line `d = end`, and -/// the direction is periodic. -fn closed_along(d: usize, ctrl: &[[f64; 4]], count: [usize; 2], degree: [usize; 2], knots: &[Vec; 2]) -> bool { - let (n, p) = (count[d], degree[d]); - if n < 2 { - return false; - } - let Some(k) = knots.get(d) else { return false }; - let Some((&a, &b)) = k.first().zip(k.last()) else { return false }; - // Clamped: degree + 1 knots equal at each end, and a range to speak of. - if !(b > a && k.iter().take(p + 1).all(|x| *x == a) && k.iter().rev().take(p + 1).all(|x| *x == b)) { - return false; - } - // Control point `(i, j)` with `i` along u, as a point. - let at = - |i: usize, j: usize| ctrl.get(j * count[0] + i).and_then(|h| (h[3].abs() > 1e-300).then(|| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]))); - let along_d = |x: usize, t: usize| if d == 0 { at(x, t) } else { at(t, x) }; - let (mut extent, mut gap) = (0.0f64, 0.0f64); - for t in 0..count[1 - d] { - let (Some(first), Some(last)) = (along_d(0, t), along_d(n - 1, t)) else { return false }; - extent = extent.max(first.len()).max(last.len()); - gap = gap.max(first.dist(last)); - } - gap <= 1e-9 * extent.max(1.0) -} - -/// A profile curve in the evaluator's form (a line extends for ever, as truck's does). -pub(crate) fn eval_curve(c: &mt::Curve) -> Option { - let (degree, kv, ctrl): (usize, Vec, Vec<[f64; 4]>) = match c { - mt::Curve::Line(l) => (1, vec![0.0, 0.0, 1.0, 1.0], vec![[l.0.x, l.0.y, l.0.z, 1.0], [l.1.x, l.1.y, l.1.z, 1.0]]), - mt::Curve::BSplineCurve(b) => (b.degree(), knots(b.knot_vec())?, b.control_points().iter().map(|p| [p.x, p.y, p.z, 1.0]).collect()), - mt::Curve::NurbsCurve(n) => (n.degree(), knots(n.knot_vec())?, n.control_points().iter().map(|h| [h.x, h.y, h.z, h.w]).collect()), - mt::Curve::IntersectionCurve(_) => return None, + let revolved = |profile: EvalCurve, origin: Vec3, axis: Vec3| -> Result { + let axis = axis.normalized().ok_or_else(|| invalid("an analytic surface's frame"))?; + Ok(EvalSurface::Revolved { profile, origin, axis, transform: IDENTITY, swap: false }) }; - let ok = (1..=MAX_SPLINE_DEGREE).contains(°ree) - && ctrl.len() <= MAX_EVAL_POINTS - && kv.len() == ctrl.len() + degree + 1 - && ctrl.iter().flatten().all(|x| x.is_finite()); - ok.then_some(EvalCurve { degree, knots: kv, ctrl }) + // The generator of a cylinder or cone over the face's heights, run from the top down so the + // revolution's (generator, angle) normal is the record's natural normal (outward). + let generator = |at: &dyn Fn(f64) -> Vec3| -> Result { + let [h0, h1] = domain[1]; + if !(h0.is_finite() && h1.is_finite() && h1 > h0) { + return Err(invalid("a cylinder or cone face with no height")); + } + let (a, b) = (at(h1), at(h0)); + // Parameter −v: the generator at t is the surface at height −t. + Ok(EvalCurve { degree: 1, knots: vec![-h1, -h1, -h0, -h0], ctrl: vec![[a.x, a.y, a.z, 1.0], [b.x, b.y, b.z, 1.0]] }) + }; + // A meridian from the record's least angle to its greatest, reversed (so the normal is the + // record's natural one, outward), its angle measured from `x` toward `y` in the plane of `x` + // and the axis `z`. + let meridian = |centre: Vec3, [x, y]: [Vec3; 2], z: Vec3, r: f64, angle: [f64; 2], o: Vec3| -> Result<(EvalSurface, Params)> { + let (curve, spans) = arc(centre, x, y, r, angle); + Ok((revolved(curve.reversed(), o, z)?, Params::Meridian(spans))) + }; + match surface { + brep::Surface::Cylinder { frame, radius } => { + let (o, x, z) = axes(frame); + Ok((revolved(generator(&|h| o + x * *radius + z * h)?, o, z)?, Params::Height)) + } + brep::Surface::Cone { frame, radius_at_origin, half_angle } => { + let (o, x, z) = axes(frame); + let slope = half_angle.tan(); + Ok((revolved(generator(&|h| o + x * (radius_at_origin + h * slope) + z * h)?, o, z)?, Params::Height)) + } + brep::Surface::Sphere { frame, radius } => { + let (o, x, z) = axes(frame); + meridian(o, [x, z], z, *radius, [-FRAC_PI_2, FRAC_PI_2], o) + } + brep::Surface::Torus { frame, major_radius, minor_radius, tube_start } => { + let (o, x, z) = axes(frame); + // The tube angle counts from its start. + let (s, c) = tube_start.sin_cos(); + meridian(o + x * *major_radius, [x * c + z * s, z * c - x * s], z, *minor_radius, [0.0, TAU], o) + } + _ => match SurfaceEval::new(surface) { + Ok(SurfaceEval::Eval(e, _)) => Ok((e, Params::Same)), + Ok(_) => Err(invalid("an analytic surface out of place")), + Err(e) => Err(KernelError::Failed(format!("not supported yet: tessellation: {e}"))), + }, + } +} + +/// The circle `centre + r (cos t x + sin t y)` for t in `angle`, as an exact rational quadratic +/// spline over [0, 1], one span per quarter turn or less, and its spans. +fn arc(centre: Vec3, x: Vec3, y: Vec3, r: f64, angle: [f64; 2]) -> (EvalCurve, Arc) { + let span = angle[1] - angle[0]; + let count = (span / std::f64::consts::FRAC_PI_2).ceil().clamp(1.0, 4.0) as usize; + let step = span / count as f64; + let weight = (step / 2.0).cos(); + // A point at angle `t`, its radius divided by `scale` (the middle control point of a span + // lies 1 / cos(step / 2) out), as homogeneous coordinates of weight `w`. + let at = |t: f64, scale: f64, w: f64| { + let p = centre + x * (r * t.cos() / scale) + y * (r * t.sin() / scale); + [p.x * w, p.y * w, p.z * w, w] + }; + let mut ctrl = vec![at(angle[0], 1.0, 1.0)]; + let mut knots = vec![0.0; 3]; + for i in 0..count { + let start = angle[0] + i as f64 * step; + ctrl.push(at(start + step / 2.0, weight, weight)); + ctrl.push(at(start + step, 1.0, 1.0)); + knots.extend(std::iter::repeat_n((i + 1) as f64 / count as f64, if i + 1 == count { 3 } else { 2 })); + } + let periodic = (span - std::f64::consts::TAU).abs() < 1e-12; + (EvalCurve { degree: 2, knots, ctrl }, Arc { start: angle[0], step, count, periodic }) +} + +/// A curve on [0, 1] run the other way: t becomes 1 − t. +trait Reversed { + fn reversed(self) -> Self; +} + +impl Reversed for EvalCurve { + fn reversed(mut self) -> Self { + self.ctrl.reverse(); + self.knots = self.knots.iter().rev().map(|k| 1.0 - k).collect(); + self + } } #[cfg(test)] mod tests { use super::*; - use crate::body::Solid; - /// Every face of `solid` evaluates as truck evaluates it, over its own parameter box. - fn assert_matches_truck(solid: &Solid) -> [usize; 4] { - let mut kinds = [0; 4]; - for face in solid.face_iter() { - let surface = face.surface(); - let kind = match surface { - mt::Surface::Plane(_) => 0, - mt::Surface::BSplineSurface(_) => 1, - mt::Surface::NurbsSurface(_) => 2, - mt::Surface::RevolutedCurve(_) => 3, + /// Every face of `b` evaluates, through [`eval_surface`] and its [`Params`], as the record's + /// own evaluator ([`SurfaceEval`]) evaluates it, over the face's parameter box: the same + /// point and the same natural normal. Counts of planes, analytic surfaces and others. + fn assert_matches_the_record(b: &brep::Brep) -> [usize; 3] { + let mut kinds = [0; 3]; + for face in &b.faces { + let kind = match face.surface { + brep::Surface::Plane { .. } | brep::Surface::PlaneThrough { .. } => 0, + brep::Surface::Cylinder { .. } | brep::Surface::Cone { .. } | brep::Surface::Sphere { .. } | brep::Surface::Torus { .. } => 1, + _ => 2, }; - let Some(eval) = eval_surface(&surface) else { panic!("not evaluable: {surface:?}") }; - // Sample the face's parameter box from its boundary vertices. - let pts: Vec<(f64, f64)> = face.vertex_iter().filter_map(|v| surface.search_parameter(v.point(), None, 100)).collect(); - if pts.is_empty() { - continue; - } - let (u0, u1) = pts.iter().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.0), b.max(p.0))); - let (v0, v1) = pts.iter().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.1), b.max(p.1))); + let (eval, map) = match eval_surface(face.parameters(), face.domain) { + Ok(e) => e, + Err(e) => panic!("not evaluable: {e} ({:?})", face.surface), + }; + let Ok(reference) = SurfaceEval::new(face.parameters()) else { panic!("the record's evaluator: {:?}", face.surface) }; + let [[u0, u1], [v0, v1]] = face.domain; for i in 0..=6 { for j in 0..=6 { - let (u, v) = (u0 + (u1 - u0) * i as f64 / 6.0, v0 + (v1 - v0) * j as f64 / 6.0); - let (p, n) = eval.eval(u, v); - let want = from_p3(surface.subs(u, v)); - assert!(p.dist(want) < 1e-9 * (1.0 + want.len()), "point at ({u}, {v}): {p:?} vs {want:?}"); - let wn = from_v3(surface.normal(u, v)); - if wn.len() > 0.5 { - assert!(n.dist(wn) < 1e-6, "normal at ({u}, {v}): {n:?} vs {wn:?} ({surface:?})"); + let uv = [u0 + (u1 - u0) * i as f64 / 6.0, v0 + (v1 - v0) * j as f64 / 6.0]; + let q = map.to_eval(uv); + let (p, n) = eval.eval(q[0], q[1]); + let Some((want, su, sv)) = reference.derivs(uv[0], uv[1]) else { panic!("reference at {uv:?}") }; + assert!(p.dist(want) < 1e-9 * (1.0 + want.len()), "point at {uv:?}: {p:?} vs {want:?}"); + if let Some(wn) = su.cross(sv).normalized().filter(|_| su.cross(sv).len() > 1e-9 * (su.len() * sv.len()).max(1e-12)) { + assert!(n.dist(wn) < 1e-6, "normal at {uv:?}: {n:?} vs {wn:?} ({:?})", face.surface); } kinds[kind] += 1; } @@ -157,32 +207,36 @@ mod tests { kinds } - fn solid(b: crate::Body) -> Solid { - (*b.solid).clone() + fn record(b: crate::Result) -> brep::Brep { + match b.and_then(|b| crate::brep_record(&b)) { + Ok(r) => r, + Err(e) => panic!("{e}"), + } } #[test] - fn primitives_evaluate_like_truck() { - let Ok(bx) = crate::box_solid(Vec3::new(-1.0, -2.0, 0.0), Vec3::new(3.0, 4.0, 5.0)) else { panic!("box") }; - let Ok(cyl) = crate::cylinder(Vec3::new(1.0, 2.0, 3.0), Vec3::new(0.0, 1.0, 1.0), 2.5, 7.0) else { panic!("cylinder") }; - let Ok(sph) = crate::sphere(Vec3::new(0.0, 0.0, 1.0), 4.0) else { panic!("sphere") }; - let Ok(tor) = crate::torus(Vec3::ZERO, 6.0, 1.5) else { panic!("torus") }; - let mut kinds = [0; 4]; - for b in [bx, cyl, sph, tor] { - for (k, n) in kinds.iter_mut().zip(assert_matches_truck(&solid(b))) { + fn primitives_evaluate_like_the_record() { + let bodies = [ + crate::box_solid(Vec3::new(-1.0, -2.0, 0.0), Vec3::new(3.0, 4.0, 5.0)), + crate::cylinder(Vec3::new(1.0, 2.0, 3.0), Vec3::new(0.0, 1.0, 1.0), 2.5, 7.0), + crate::sphere(Vec3::new(0.0, 0.0, 1.0), 4.0), + crate::torus(Vec3::ZERO, 6.0, 1.5), + ]; + let mut kinds = [0; 3]; + for b in bodies { + for (k, n) in kinds.iter_mut().zip(assert_matches_the_record(&record(b))) { *k += n; } } - // Planes, rational patches (sphere) and revolved profiles (cylinder, torus) all covered. - assert!(kinds[0] > 0 && kinds[3] > 0 && kinds[1] + kinds[2] > 0, "{kinds:?}"); + // Planes and the analytic surfaces (cylinder, sphere, torus) all covered. + assert!(kinds[0] > 0 && kinds[1] > 0, "{kinds:?}"); } #[test] - fn transformed_and_mirrored_bodies_evaluate_like_truck() { + fn transformed_and_mirrored_bodies_evaluate_like_the_record() { let Ok(cyl) = crate::cylinder(Vec3::ZERO, Vec3::Z, 2.0, 5.0) else { panic!("cylinder") }; // Column-major: x → 3 − x, z → z + 1. let mirror = [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [3.0, 0.0, 1.0, 1.0]]; - let Ok(m) = crate::transform_matrix(&cyl, mirror) else { panic!("transform") }; - assert!(assert_matches_truck(&solid(m)).iter().sum::() > 0); + assert!(assert_matches_the_record(&record(crate::transform_matrix(&cyl, mirror))).iter().sum::() > 0); } } diff --git a/crates/kernel/src/tess/tangle.rs b/crates/kernel/src/tess/tangle.rs new file mode 100644 index 000000000..877b65627 --- /dev/null +++ b/crates/kernel/src/tess/tangle.rs @@ -0,0 +1,170 @@ +//! Where a face's sampled boundary crosses itself: chords of its loops, in the face's +//! parameters, that cross another chord of the face although the curves they stand for do not +//! (two curves running closer together than their chords sag). + +use solidcraft_geom::tess::EvalSurface; + +use super::seam; +use super::uv; + +/// Two chords cross only where each one's ends lie strictly either side of the other, by more +/// than this fraction of the product of their lengths (a chord ending on another, as at a +/// shared vertex or along a seam's two uses a period apart, is not a crossing). +const STRADDLE: f64 = 1e-10; + +/// One chord of a loop, or a copy of it whole periods along. +struct Chord { + /// The chord's place in the face: its loop and its first node. + at: (usize, usize), + a: [f64; 2], + b: [f64; 2], +} + +impl Chord { + fn lo(&self, d: usize) -> f64 { + self.a[d].min(self.b[d]) + } + fn hi(&self, d: usize) -> f64 { + self.a[d].max(self.b[d]) + } +} + +/// The chords (loop, first node) of `loops` that cross another chord of the face, in its loop or +/// another, each once and in order. On a closed surface the boundary crosses itself where any +/// copies of two chords, whole periods apart, cross; chords ending on a pole, where the +/// parameter along the pole is free, are left out. Adjacent chords of a loop share a node and +/// never cross. `reach`: how near a pole a node is taken as one (see [`uv::degenerate_within`]). +pub(crate) fn crossing(s: &EvalSurface, reach: f64, loops: &[seam::Loop]) -> Vec<(usize, usize)> { + let dom = uv::domain(s); + let pole = |q: [f64; 2]| (0..2).any(|d| uv::degenerate_within(s, &dom, q, d, reach)); + let mut chords: Vec = Vec::new(); + for (li, l) in loops.iter().enumerate() { + let n = l.uv.len(); + if n < 3 { + continue; + } + for k in 0..n { + let (Some(&a), Some(&b)) = (l.uv.get(k), l.uv.get((k + 1) % n)) else { continue }; + if !(a.iter().chain(&b).all(|x| x.is_finite())) || pole(a) || pole(b) { + continue; + } + // The loop's closing chord of a loop that winds round the surface ends at the copy of + // its first node nearest its last; every chord then starts in one period. + let (mut a, mut b) = (a, b); + for d in 0..2 { + let Some(per) = dom.period[d] else { continue }; + b[d] = uv::unwrap(b[d], a[d], Some(per)); + let back = (a[d].min(b[d]) / per).floor() * per; + a[d] -= back; + b[d] -= back; + } + chords.push(Chord { at: (li, k), a, b }); + } + } + // With every chord starting in one period, two chords' copies can only cross where one of + // them is moved a period along at most: each chord also as its copies a period along. + for d in 0..2 { + let Some(per) = dom.period[d] else { continue }; + let along: Vec = chords + .iter() + .map(|c| { + let (mut a, mut b) = (c.a, c.b); + a[d] += per; + b[d] += per; + Chord { at: c.at, a, b } + }) + .collect(); + chords.extend(along); + } + let adjacent = |p: (usize, usize), q: (usize, usize)| { + let n = loops.get(p.0).map_or(0, |l| l.uv.len()); + p == q || (p.0 == q.0 && ((p.1 + 1) % n == q.1 || (q.1 + 1) % n == p.1)) + }; + // Sweep along u: only chords whose u ranges overlap can cross. + chords.sort_by(|x, y| x.lo(0).total_cmp(&y.lo(0))); + let mut out: Vec<(usize, usize)> = Vec::new(); + for (i, x) in chords.iter().enumerate() { + for y in chords.iter().skip(i + 1) { + if y.lo(0) > x.hi(0) { + break; + } + if y.lo(1) > x.hi(1) || x.lo(1) > y.hi(1) || adjacent(x.at, y.at) { + continue; + } + if cross(x.a, x.b, y.a, y.b) { + out.push(x.at); + out.push(y.at); + } + // A node of one chord lying on the other (inside it, not at its ends) is no crossing, + // but no triangulation can keep both as constraints either: where two curves leave a + // vertex they touch at along one tangent (a circle touching another from inside), the + // inner one's node can fall on the outer one's chord (with the outer chord twice the + // inner, exactly so but for the next order). The chord the node lies on is halved. + // (Not where the two chords run along one line: a seam's two uses, a period apart, + // lie on each other as copies.) + if !along(x.a, x.b, y.a, y.b) && [y.a, y.b].iter().any(|q| on(x.a, x.b, *q)) { + out.push(x.at); + } + if !along(y.a, y.b, x.a, x.b) && [x.a, x.b].iter().any(|q| on(y.a, y.b, *q)) { + out.push(y.at); + } + } + } + out.sort_unstable(); + out.dedup(); + out +} + +/// Whether `q` lies on the segment `ab` within [`STRADDLE`] (of the segment's squared length, +/// off its line) strictly between its ends (not at either, by the same measure along it). +fn on(a: [f64; 2], b: [f64; 2], q: [f64; 2]) -> bool { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let len2 = dx * dx + dy * dy; + if !(len2 > 0.0) { + return false; + } + let (qx, qy) = (q[0] - a[0], q[1] - a[1]); + let off = (dx * qy - dy * qx).abs(); + let along = (dx * qx + dy * qy) / len2; + off <= 1e3 * STRADDLE * len2 && along > 1e-6 && along < 1.0 - 1e-6 +} + +/// Whether `c` and `d` both lie on the line of `ab` (within [`on`]'s measure). +fn along(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let len2 = dx * dx + dy * dy; + let off = |q: [f64; 2]| (dx * (q[1] - a[1]) - dy * (q[0] - a[0])).abs(); + len2 > 0.0 && off(c) <= 1e3 * STRADDLE * len2 && off(d) <= 1e3 * STRADDLE * len2 +} + +/// Whether the segments `ab` and `cd` cross: each one's ends strictly either side of the other. +fn cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool { + let orient = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + let len = |p: [f64; 2], q: [f64; 2]| (q[0] - p[0]).hypot(q[1] - p[1]); + let eps = STRADDLE * len(a, b) * len(c, d); + let side = |o: f64| { + if o > eps { + 1 + } else if o < -eps { + -1 + } else { + 0 + } + }; + let (s1, s2, s3, s4) = (side(orient(a, b, c)), side(orient(a, b, d)), side(orient(c, d, a)), side(orient(c, d, b))); + s1 * s2 < 0 && s3 * s4 < 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crossing_chords_are_found_and_touching_ones_are_not() { + assert!(cross([0.0, 0.0], [2.0, 2.0], [0.0, 2.0], [2.0, 0.0])); + // Ending on the other, sharing an end, collinear: no crossing. + assert!(!cross([0.0, 0.0], [2.0, 0.0], [1.0, 0.0], [1.0, 1.0])); + assert!(!cross([0.0, 0.0], [2.0, 0.0], [2.0, 0.0], [3.0, 1.0])); + assert!(!cross([0.0, 0.0], [2.0, 0.0], [1.0, 0.0], [3.0, 0.0])); + } +} diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rs index c103a7f1f..287bb9db2 100644 --- a/crates/kernel/src/tess/tests.rs +++ b/crates/kernel/src/tess/tests.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use super::*; use crate::{Body, BoolOp}; @@ -26,8 +27,13 @@ fn assert_watertight(m: &Mesh, name: &str) { assert!(open.is_empty(), "{name}: {} unmatched directed edges, e.g. {:?}", open.len(), open.first()); } +/// The body's schema 4 record, which the planner takes. +fn record(b: &Body) -> solidcore_record::brep::Brep { + ok(crate::brep_record(b)) +} + fn plan_body(b: &Body, tol: f64) -> (Mesh, PlanStats) { - match plan(&b.solid, tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 }), b.boundary_tol) { + match plan(&record(b), tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 })) { Ok((p, stats)) => (p.evaluate(), stats), Err(e) => panic!("plan: {e}"), } @@ -42,7 +48,7 @@ fn check(name: &str, b: &Body, tol: f64, volume: f64) -> PlanStats { assert!((got - volume).abs() <= area * tol * 1.5 + 1e-9, "{name}: volume {got} vs {volume} (area {area}, tol {tol})"); // Outward normals: the divergence theorem gives a positive volume only if they are. assert!(got > 0.0, "{name}: inside out"); - let faces = b.solid.face_iter().count(); + let faces = b.face_count(); assert_eq!(stats.planar + stats.structured + stats.delaunay, faces, "{name}: every face planned"); stats } @@ -94,7 +100,7 @@ fn a_box_is_a_regular_grid_on_every_face() { fn primitives_are_watertight_with_the_right_volume() { for tol in [0.05, 0.005] { let s = check("box", &ok(crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 6.0, 4.0))), tol, 240.0); - assert_eq!(s, PlanStats { planar: 6, structured: 0, delaunay: 0, filled: 0 }); + assert_eq!(s, PlanStats { planar: 6, ..PlanStats::default() }); let s = check("cylinder", &ok(crate::cylinder(Vec3::new(1.0, 2.0, 3.0), Vec3::new(0.0, 1.0, 1.0), 2.5, 7.0)), tol, PI * 2.5 * 2.5 * 7.0); assert_eq!(s.delaunay, 0, "cylinder walls are structured"); let s = check("torus", &ok(crate::torus(Vec3::ZERO, 6.0, 1.5)), tol, 2.0 * PI * PI * 6.0 * 1.5 * 1.5); @@ -116,20 +122,35 @@ fn holes_and_trimmed_faces_are_watertight() { let (m, stats) = plan_body(&body, tol); assert_watertight(&m, "cross hole"); assert_eq!(stats.delaunay, 0, "{stats:?}"); - // Against the reference mesher's volume (no closed form for the two-cylinder intersection). - let Ok(reference) = body.tessellate(tol * 0.2) else { panic!("reference mesh") }; + // Against the body's mesh at a fifth of the tolerance (no closed form for the two-cylinder + // intersection). + let Ok(reference) = body.mesh(&crate::MeshTolerance::chord(tol * 0.2)) else { panic!("finer mesh") }; let (a, b) = (m.measure().volume, reference.measure().volume); assert!((a - b).abs() < 0.01 * b, "cross hole volume {a} vs {b}"); } +/// Through holes in pairs whose circles touch at one point (rig booleans/307): the plate's faces +/// have one loop round each pair, through their common vertex twice. Both passes are one point of +/// the face's (u, v), not two nodes the pcurves put 1e-14 apart, whose constraints crossed +/// ("boundary crosses itself"). +#[test] +fn holes_touching_at_a_point_are_watertight() { + let mut body = ok(crate::box_solid(Vec3::new(-50.0, -50.0, 0.0), Vec3::new(50.0, 50.0, 5.0))); + for (x, y) in [(25.0, 0.0), (-25.0, 0.0), (0.0, 25.0), (0.0, -25.0), (15.0, 0.0), (-15.0, 0.0), (0.0, 15.0), (0.0, -15.0)] { + body = cut(&body, &ok(crate::cylinder(Vec3::new(x, y, -1.0), Vec3::Z, 5.0, 7.0))); + } + check("holes touching at a point", &body, 0.01, 10000.0 * 5.0 - 8.0 * PI * 25.0 * 5.0); +} + #[test] fn faces_and_edges_keep_the_body_order() { let body = ok(crate::cylinder(Vec3::ZERO, Vec3::Z, 2.0, 5.0)); let (m, _) = plan_body(&body, 0.01); - let Ok(reference) = body.tessellate(0.01) else { panic!("reference mesh") }; + // Body::mesh, which plans the body's own record: the same faces and edges, in its order. + let Ok(reference) = body.mesh(&crate::MeshTolerance::chord(0.01)) else { panic!("body mesh") }; assert_eq!(m.edges.len(), reference.edges.len()); assert_eq!(m.edge_faces, reference.edge_faces); - // Same faces in the same order: each face's area agrees with the reference mesher's. + // Same faces in the same order: each face's area agrees with the body mesh's. let face_area = |m: &Mesh, f: u32| -> f64 { m.triangles .iter() @@ -141,18 +162,19 @@ fn faces_and_edges_keep_the_body_order() { }) .sum() }; - for f in 0..body.solid.face_iter().count() as u32 { + for f in 0..body.face_count() as u32 { let (a, b) = (face_area(&m, f), face_area(&reference, f)); assert!((a - b).abs() < 0.01 * b.max(1e-9), "face {f}: {a} vs {b}"); } - // Each edge polyline ends on the same points as the reference's. + // Each edge polyline ends on the same points as the body mesh's. for (a, b) in m.edges.iter().zip(&reference.edges) { assert!(a.first().zip(b.first()).is_some_and(|(p, q)| p.dist(*q) < 1e-9)); assert!(a.last().zip(b.last()).is_some_and(|(p, q)| p.dist(*q) < 1e-9)); } } -/// Side-by-side wireframes, reference mesher (left) and plan (right): +/// Side-by-side wireframes, the body's mesh at the chord alone (left) and the plan at the +/// display angle (right): /// `SOLIDCRAFT_TESS_SVG=

cargo test -p solidcraft-kernel render_wireframes -- --ignored`. #[test] #[ignore] @@ -173,10 +195,10 @@ fn render_wireframes() { ]; for (name, body) in shapes { let t0 = std::time::Instant::now(); - let Ok(old) = body.tessellate(tol) else { panic!("reference") }; + let Ok(old) = body.mesh(&crate::MeshTolerance::chord(tol)) else { panic!("body mesh") }; let t_old = t0.elapsed().as_secs_f64() * 1e3; let t0 = std::time::Instant::now(); - let new = match plan(&body.solid, tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 }), body.boundary_tol) { + let new = match plan(&record(&body), tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 })) { Ok((p, st)) => Some((p.evaluate(), st)), Err(e) => { println!("{name}: no plan ({e})"); @@ -186,7 +208,7 @@ fn render_wireframes() { let t_new = t0.elapsed().as_secs_f64() * 1e3; let mut svg = String::from(""); let label = |x: f64, text: String| format!("{text}"); - svg += &label(20.0, format!("meshalgo (Delaunay): {} tris, {t_old:.1} ms", old.triangles.len())); + svg += &label(20.0, format!("chord alone: {} tris, {t_old:.1} ms", old.triangles.len())); svg += &draw(&old, 0.0); if let Some((m, st)) = &new { svg += &label( @@ -250,7 +272,7 @@ fn draw(m: &Mesh, x0: f64) -> String { /// such a triangle carried a boundary side of the cone. #[test] fn a_drill_point_apex_leaves_no_zero_area_triangles() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + use solidcore_record::{Loop2, Plane, Region2, Vec2}; // (box size, hole position, radius, depth) let cases = [(Vec3::new(40.0, 30.0, 15.0), Vec3::new(20.0, 15.0, 15.0), 3.4, 8.0), (Vec3::new(60.0, 40.0, 15.0), Vec3::new(50.0, 20.0, 15.0), 3.0, 10.0)]; @@ -297,155 +319,739 @@ fn trace_seeds_grade_from_one_end_to_the_other() { assert!(graded([0.0, 0.0], [0.5, 0.0], 1.0, 1.0, 10.0, [1.0, 1.0], &|_, _| true).is_empty()); } -/// A surface that joins itself along a direction is periodic there: its parameters repeat, so -/// the evaluator takes a parameter outside the range back into it. A boundary that runs across -/// the join is unwrapped past the range's end and must still land on the surface. +/// Distance of `p` from the analytic surface `fs`. +fn off_surface(fs: &crate::FaceSurface, p: Vec3) -> f64 { + use crate::FaceSurface as F; + match *fs { + F::Plane { normal, point } => (p - point).dot(normal.vec()).abs(), + F::Cylinder { origin, axis, radius } => { + let v = p - origin; + ((v - axis.vec() * v.dot(axis.vec())).len() - radius).abs() + } + F::Cone { apex, axis, half_angle } => { + let v = p - apex; + let h = v.dot(axis.vec()); + ((v - axis.vec() * h).len() * half_angle.cos() - h * half_angle.sin()).abs() + } + F::Sphere { center, radius } => ((p - center).len() - radius).abs(), + F::Torus { center, axis, major, minor } => { + let v = p - center; + let h = v.dot(axis.vec()); + (((v - axis.vec() * h).len() - major.abs()).hypot(h) - minor).abs() + } + } +} + +/// The farthest a triangle's centroid lies from its face's analytic surface, over the faces +/// that have one. +fn max_chord(b: &Body, m: &Mesh) -> f64 { + let surfs: Vec> = (0..b.face_count()).map(|f| crate::face_surface(b, f)).collect(); + m.triangles + .iter() + .zip(&m.tri_face) + .filter_map(|(t, f)| { + let fs = surfs.get(*f as usize).copied().flatten()?; + let [a, b, c] = t.map(|i| m.positions[i as usize]); + Some(off_surface(&fs, (a + b + c) * (1.0 / 3.0))) + }) + .fold(0.0, f64::max) +} + +/// The display plan of `b` at `tol` (and the display angle), evaluated: closed, with no +/// zero-area or needle triangle. +fn closed_display_mesh(name: &str, b: &Body, tol: f64) -> Mesh { + let plan = ok(b.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(crate::DISPLAY_ANGLE) })); + let m = ok(b.mesh_of(&plan)); + assert_watertight(&m, &format!("{name} at {tol}")); + for t in &m.triangles { + let [a, b, c] = t.map(|i| m.positions[i as usize]); + let longest = (b - a).len().max((c - b).len()).max((a - c).len()); + assert!((b - a).cross(c - a).len() > 1e-6 * longest * longest, "{name} at {tol}: degenerate triangle {a:?} {b:?} {c:?}"); + } + m +} + +/// A sphere from SMLib cut through its centre: the half sphere is bounded by its rim and its +/// seam from the pole up to the rim, used both ways. The seam's two uses share their nodes, so +/// the mesh has no crack along it and nothing degenerate at the pole. #[test] -fn a_closed_spline_surface_is_periodic_and_evaluates_outside_its_range() { - use solidcraft_geom::tess::EvalSurface; - // A five-sided tube: the control net's last column repeats its first. - let corner = |k: usize| { - let a = std::f64::consts::TAU * (k % 5) as f64 / 5.0; - (10.0 * a.cos(), 10.0 * a.sin()) +fn a_half_sphere_from_smlib_is_closed_along_its_seam() { + use solidcraft_smlib::{BooleanOp, Brep as S}; + let Ok(ball) = S::make_sphere([0.0; 3], 12.0) else { panic!("sphere") }; + let Ok(lid) = S::make_box([-20.0, -20.0, 0.0], [40.0, 40.0, 20.0]) else { panic!("box") }; + let Ok(Some(half)) = ball.boolean(&lid, BooleanOp::Subtract) else { panic!("cut") }; + let body = ok(crate::native::body_from_smlib(&half)); + for tol in [0.1, 0.01] { + let m = closed_display_mesh("half sphere", &body, tol); + let chord = max_chord(&body, &m); + assert!(chord <= tol * 1.05, "half sphere at {tol}: chord {chord}"); + } +} + +/// Every triangle of a display plan lies within the chord tolerance of its face, whatever +/// layout the face got: on a doubly curved grid the sags along both directions add up at a +/// cell's middle, and a trimmed sphere face round a pocket is not a grid at all. +#[test] +fn display_plans_stay_within_the_chord_tolerance() { + let ball = ok(crate::sphere(Vec3::ZERO, 12.0)); + let pocket = cut(&ok(crate::sphere(Vec3::ZERO, 10.0)), &ok(crate::box_solid(Vec3::new(-2.0, -2.0, 5.0), Vec3::new(2.0, 2.0, 11.0)))); + let ring = ok(crate::torus(Vec3::ZERO, 22.0, 4.0)); + for (name, body) in [("sphere", &ball), ("pocket in a sphere", &pocket), ("torus", &ring)] { + for tol in [0.1, 0.01] { + let m = closed_display_mesh(name, body, tol); + let chord = max_chord(body, &m); + assert!(chord <= tol * 1.05, "{name} at {tol}: chord {chord}"); + } + } +} + +/// SMLib's torus is one face bounded by its two seams: a grid over the whole parameter box. +#[test] +fn an_smlib_torus_stays_within_the_chord_tolerance() { + let Ok(ring) = solidcraft_smlib::Brep::make_torus([0.0; 3], 22.0, 4.0) else { panic!("torus") }; + let body = ok(crate::native::body_from_smlib(&ring)); + for tol in [0.1, 0.01] { + let m = closed_display_mesh("SMLib torus", &body, tol); + let chord = max_chord(&body, &m); + assert!(chord <= tol * 1.05, "SMLib torus at {tol}: chord {chord}"); + } +} + +// Modelled threads from SMLib: a screw-swept groove cut from a bore or a shaft. The groove's +// walls are splines winding once per pitch for the thread's whole length, and they split the +// bore or shaft into one face per turn. + +/// A groove of trapezoid `section` (radius, axial offset) in the plane through the z axis along +/// y, carried `turns` turns of `pitch` about z from `base`, as an SMLib solid. +fn smlib_groove(section: [(f64, f64); 4], base: f64, pitch: f64, turns: f64) -> solidcraft_smlib::Brep { + use solidcore_record::{Loop2, Vec2}; + smlib_screw(Loop2::polygon(§ion.map(|(r, z)| Vec2::new(r, z))), base, pitch, turns) +} + +/// The `section` (radius, axial offset) in the plane through the z axis along y, carried +/// `turns` turns of `pitch` about z from `base`, as an SMLib solid. +fn smlib_screw(section: solidcore_record::Loop2, base: f64, pitch: f64, turns: f64) -> solidcraft_smlib::Brep { + use solidcore_record::{Plane, Region2}; + let origin = Vec3::new(0.0, 0.0, base); + let plane = Plane { origin, x: Vec3::Y, y: Vec3::Z }; + let region = Region2 { outer: section, holes: Vec::new() }; + let Some(numbered) = crate::numbered::number_regions(std::slice::from_ref(®ion)).pop() else { panic!("profile") }; + let profile = numbered.outer.oriented(false); + let groove = ok(crate::smlib_sweeps::screw(&plane, &crate::smlib_sweeps::pieces([&profile]), origin, Vec3::Z, pitch, turns)); + ok(crate::native::smlib_body(&groove)) +} + +fn smlib_cut(a: &solidcraft_smlib::Brep, b: &solidcraft_smlib::Brep) -> solidcraft_smlib::Brep { + match a.boolean(b, solidcraft_smlib::BooleanOp::Subtract) { + Ok(Some(r)) => r, + other => panic!("cut: {other:?}"), + } +} + +/// The ISO basic profile's groove for pitch `p` and major diameter `d`: internal, from 0.1 p +/// inside the hole wall of radius `wall` out to the major radius; external, from the root out +/// past the shaft's surface (radius `wall`). +fn iso_groove(p: f64, d: f64, wall: f64, internal: bool) -> [(f64, f64); 4] { + let h = p * 3f64.sqrt() / 2.0; + let slope = (PI / 6.0).tan(); + let (r0, w0, r1, w1) = if internal { + let r_in = wall.min(d / 2.0 - 5.0 * h / 8.0) - 0.1 * p; + (r_in, (p / 8.0 + 2.0 * (d / 2.0 - r_in) * slope) / 2.0, d / 2.0, p / 16.0) + } else { + let (r_root, r_out) = (d / 2.0 - 5.0 * h / 8.0, wall.max(d / 2.0) + 0.05 * p); + (r_root, p / 8.0, r_out, (p / 4.0 + 2.0 * (r_out - r_root) * slope) / 2.0) }; + [(r0, -w0), (r1, -w1), (r1, w1), (r0, w0)] +} + +/// Each face's triangles, in 3D, cover as much area as its surface over the triangles' own +/// parameters, within 5% (a coarse tolerance on a small curved face, a few percent) and the +/// sails along its boundary: nothing zigzags across the face, which multiplies its area. The +/// surface's area by the midpoint rule on sixteen pieces of each parameter triangle. A face's +/// boundary sides are its edges' chords, each up to the chord tolerance `tol` off its edge, and +/// between a chord of length L and its edge lies a sail of surface of at most 2/3 L tol (a +/// parabolic segment) that flat triangles bridge rather than follow: a face no wider than its +/// chords sag (the thread's crest band where it runs out through the block's end, 0.06 mm sag +/// at 0.1) takes up to that much more or less area however it is triangulated inside. +fn assert_faces_lie_flat(name: &str, plan: &solidcraft_geom::tess::TessPlan, tol: f64) { + for fp in &plan.faces { + let Some(s) = fp.surface.and_then(|i| plan.surfaces.get(i as usize)) else { continue }; + let at = |i: u32| { + fp.fixed.get(i as usize).copied().unwrap_or_else(|| { + let q = fp.uv[i as usize]; + s.eval(q[0], q[1]).0 + }) + }; + let (mut flat, mut surface) = (0.0, 0.0); + for t in &fp.triangles { + let [a, b, c] = t.map(|i| fp.uv[i as usize]); + let area = 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])).abs(); + flat += 0.5 * (at(t[1]) - at(t[0])).cross(at(t[2]) - at(t[0])).len(); + const N: usize = 4; + for i in 0..N { + for j in 0..N - i { + // The upright piece, and the inverted one beside it where there is one. + let pieces: &[(f64, f64)] = + if i + j + 1 < N { &[(1.0 / 3.0, 1.0 / 3.0), (2.0 / 3.0, 2.0 / 3.0)] } else { &[(1.0 / 3.0, 1.0 / 3.0)] }; + for &(di, dj) in pieces { + let (x, y) = ((i as f64 + di) / N as f64, (j as f64 + dj) / N as f64); + let q = [a[0] + (b[0] - a[0]) * x + (c[0] - a[0]) * y, a[1] + (b[1] - a[1]) * x + (c[1] - a[1]) * y]; + if let Some((_, su, sv)) = s.derivs(q[0], q[1]) { + surface += su.cross(sv).len() * area / (N * N) as f64; + } + } + } + } + } + // The boundary: the sides of exactly one triangle. + let mut sides: HashMap<(u32, u32), u32> = HashMap::new(); + for t in &fp.triangles { + for k in 0..3 { + let (a, b) = (t[k], t[(k + 1) % 3]); + *sides.entry((a.min(b), a.max(b))).or_default() += 1; + } + } + let boundary: f64 = sides.iter().filter(|(_, n)| **n == 1).map(|((a, b), _)| at(*a).dist(at(*b))).sum(); + let sails = 2.0 / 3.0 * boundary * tol; + assert!( + (flat - surface).abs() <= 0.05 * surface + sails, + "{name}: face {} has {flat} mm² of triangles over {surface} mm² of surface (its boundary's sails {sails})", + fp.face + ); + } +} + +/// #1995: an M8x1 thread through a 7 mm hole in a 20 mm block, both ends open. Truck meshed the +/// groove's winding walls with triangles reaching past both ends of the block; the body's mesh +/// now comes from the display plan, inside the block and with the analytic volume. +#[test] +fn a_modelled_thread_in_a_bore_meshes_inside_its_block() { + use solidcraft_smlib::Brep as S; + let (Ok(block), Ok(bore)) = (S::make_box([-10.0, -10.0, 0.0], [20.0, 20.0, 10.0]), S::make_cylinder([0.0, 0.0, -1.0], 3.5, 12.0)) else { + panic!("stock") + }; + let threaded = smlib_cut(&smlib_cut(&block, &bore), &smlib_groove(iso_groove(1.0, 8.0, 3.5, true), -1.0, 1.0, 12.0)); + let body = ok(crate::native::body_from_smlib(&threaded)); + let m = ok(body.mesh(&crate::MeshTolerance::chord(0.01))); + let (lo, hi) = m + .positions + .iter() + .fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + assert!(lo.z > -1e-6 && hi.z < 10.0 + 1e-6 && lo.x > -10.0 - 1e-6 && hi.x < 10.0 + 1e-6, "mesh outside the block: {lo:?} {hi:?}"); + // Block less the bore less ten turns of the groove where it is in the material (as the + // kernel case works it out from the ISO profile). + let volume = m.measure().volume; + assert!((volume - 3567.1757).abs() < 0.002 * 3567.1757, "volume {volume}"); + for tol in [0.1, 0.01] { + let m = closed_display_mesh("thread in a bore", &body, tol); + let chord = max_chord(&body, &m); + assert!(chord <= tol * 1.05, "thread in a bore at {tol}: chord {chord}"); + assert_faces_lie_flat("thread in a bore", &ok(body.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(crate::DISPLAY_ANGLE) })), tol); + } +} + +/// An M10 thread over the lower half of a 30 mm shaft. The groove's root band leaves the shaft's +/// end face obliquely: a strip a quarter pitch wide winding ten turns, narrower everywhere than +/// a triangle's side, with no four corners to blend. The butterfly of a round face made it a +/// grid of ~200 000 points whose triangles zigzagged along the strip (six times the band's area, +/// and off the surface by more than the tolerance); it is its boundary nodes alone now. +#[test] +fn a_thread_root_band_running_out_through_an_end_face_lies_on_its_surface() { + let Ok(shaft) = solidcraft_smlib::Brep::make_cylinder([0.0; 3], 5.0, 30.0) else { panic!("shaft") }; + let threaded = smlib_cut(&shaft, &smlib_groove(iso_groove(1.5, 10.0, 5.0, false), -1.5, 1.5, 11.0)); + let body = ok(crate::native::body_from_smlib(&threaded)); + let m = ok(body.mesh(&crate::MeshTolerance::chord(0.01))); + let (lo, hi) = m + .positions + .iter() + .fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + assert!(lo.z > -1e-6 && hi.z < 30.0 + 1e-6 && hi.x < 5.0 + 1e-6, "mesh outside the shaft: {lo:?} {hi:?}"); + for tol in [0.1, 0.01] { + let m = closed_display_mesh("thread run out", &body, tol); + let chord = max_chord(&body, &m); + assert!(chord <= tol * 1.05, "thread run out at {tol}: chord {chord}"); + assert!(m.triangles.len() < 60_000, "thread run out at {tol}: {} triangles", m.triangles.len()); + assert_faces_lie_flat("thread run out", &ok(body.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(crate::DISPLAY_ANGLE) })), tol); + } +} + +/// #793: a coil (a 1 mm wire at 20 mm, six turns of pitch 4) cut in two across its axis. Its +/// halves go to the display plan for their mesh; at the measuring tolerance a half's wall wants +/// more cells than a grid may have, and its cut grid gave up for an under-refined Delaunay (the +/// halves measured 1.5% short of the whole). The cut grid now thins its lines to fit. +#[test] +fn the_halves_of_a_split_smlib_coil_measure_as_the_whole() { + use solidcore_record::{Loop2, Vec2}; + use solidcraft_smlib::{BooleanOp, Brep as S}; + let coil = smlib_screw(Loop2::circle(Vec2::new(20.0, 0.0), 1.0), 0.0, 4.0, 6.0); + let Ok(top) = S::make_box([-30.0, -30.0, 12.5], [60.0, 60.0, 30.0]) else { panic!("box") }; + let (Ok(Some(upper)), Ok(Some(lower))) = (coil.boolean(&top, BooleanOp::Intersect), coil.boolean(&top, BooleanOp::Subtract)) else { + panic!("split") + }; + let volume = |b: &S| ok(crate::measure(&ok(crate::native::body_from_smlib(b)))).volume; + // π r² · 2πR · turns; SMLib's wall is a spline within a ten-thousandth of the pitch. + let (whole, analytic) = (volume(&coil), PI * 2.0 * PI * 20.0 * 6.0); + assert!((whole - analytic).abs() < 3e-3 * analytic, "coil {whole} vs {analytic}"); + // The halves are held to the closed form itself: the whole coil's one wall is meshed + // within 3e-3 of it, which made the whole a looser yardstick than the truth. + let halves = volume(&upper) + volume(&lower); + assert!((halves - analytic).abs() < 1e-3 * analytic, "halves {halves} vs {analytic} (the whole measures {whole})"); +} + +/// Thinning keeps a grid within its cap whatever the rounding, both ends of each direction, +/// and never fewer than two lines a direction (a cap below four points takes four). +#[test] +fn thinned_grid_lines_stay_within_the_cap() { + let lines = |n: usize| (0..n).map(|i| i as f64 / (n - 1) as f64).collect::>(); + for (nu, nv, cap) in [(1237, 122, 150_000), (8192, 3, 1000), (3, 8192, 10), (2, 2, 1), (5000, 5000, 4)] { + let (mut us, mut vs) = (lines(nu), lines(nv)); + grid::thin(&mut us, &mut vs, cap); + assert!(us.len() * vs.len() <= cap.max(4), "{nu}x{nv} to {cap}: {}x{}", us.len(), vs.len()); + assert!(us.len() >= 2 && vs.len() >= 2); + assert!(us.first() == Some(&0.0) && us.last() == Some(&1.0) && vs.first() == Some(&0.0) && vs.last() == Some(&1.0)); + } +} + +/// Whatever the chord tolerance, no edge segment spans more than a quarter turn of its curve: +/// a 1 mm hole through a 990 mm plate, at a 2 mm chord and no facet angle, keeps a polygon with +/// area. Each half arc of the hole was one chord, two chords on one line: a hole of no area. +#[test] +fn a_hole_far_below_the_tolerance_keeps_its_area() { + let plate = ok(crate::box_solid(Vec3::ZERO, Vec3::new(990.0, 990.0, 10.0))); + let (axis, r) = (Vec3::new(495.0, 495.0, 0.0), 0.5); + let body = cut(&plate, &ok(crate::cylinder(axis - Vec3::Z, Vec3::Z, r, 12.0))); + let rec = record(&body); + let (p, _) = ok(plan(&rec, 2.0, None)); + let mut rims = 0; + for (ei, e) in rec.edges.iter().enumerate() { + if matches!(e.curve, Curve::Line { .. }) { + continue; + } + let pts = &p.edges[ei]; + // On the hole's rim: every chord at most a quarter turn's, r·√2. + let off = |q: &Vec3| (Vec3::new(q.x, q.y, 0.0).dist(axis) - r).abs(); + assert!(pts.iter().all(|q| off(q) < 1e-6), "edge {ei} is not on the hole"); + for w in pts.windows(2) { + assert!(w[0].dist(w[1]) <= r * 2f64.sqrt() * (1.0 + 1e-6), "edge {ei}: a chord of {} spans more than a quarter turn", w[0].dist(w[1])); + } + rims += 1; + } + assert!(rims >= 2, "{rims} rim edges"); + let m = p.evaluate(); + assert_watertight(&m, "plate with a small hole"); + // The hole's wall: π · 1 · 10 less its chords' shortfall (a square: 2√2 · 0.5 · 10 at least). + let wall = m.measure().area - 2.0 * (990.0 * 990.0 + 2.0 * 990.0 * 10.0) + 2.0 * PI * r * r; + assert!(wall > 4.0 * 2f64.sqrt() * r * 10.0 * 0.99, "the hole's wall measures {wall}"); +} + +/// Boundary nodes at the very same (u, v) are one vertex to the triangulation: two holes that +/// touch at a vertex they share (a ring standing on a perforated plate, tangent to the holes +/// beside it) bound a face the triangles follow, though each hole has its own copy of the node. +#[test] +fn loops_touching_at_a_shared_vertex_bound_the_face() { + let outer = [[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]]; + let left = [[1.0, 1.0], [1.0, 3.0], [2.0, 2.0]]; + let right = [[2.0, 2.0], [3.0, 3.0], [3.0, 1.0]]; + let uvs: Vec<[f64; 2]> = outer.iter().chain(&left).chain(&right).copied().collect(); + let fixed: Vec = uvs.iter().map(|q| Vec3::new(q[0], q[1], 0.0)).collect(); + let ranges = vec![0..4, 4..7, 7..10]; + let fill = cdt::Fill { seeds: &[], refine: None, shape: false, lenient: false }; + let Some((_, triangles)) = cdt::triangulate(&uvs, &ranges, fill) else { panic!("triangulates") }; + assert!(closed_boundary(&ranges, &fixed, &uvs, &triangles), "the triangles follow both holes through their shared vertex"); +} + +/// A face meeting itself along a line (a hole's wall tangent inside the wall round it, cut from +/// the boss side's top rim down to the hole's bottom): its loop runs up the slit and back down +/// it, with the face on both sides. The iso-line grid's band beside the slit is the face on +/// either side of it, and the triangles follow the slit both ways and cover the whole square. +#[test] +fn a_slit_in_a_trimmed_face_has_the_face_on_both_sides() { + // The square [0, 8] × [0, 4], its loop starting at the slit's tip (3, 1) up to the top, round + // the square and back down the slit. + let mut uvs: Vec<[f64; 2]> = (1..=4).map(|k| [3.0, k as f64]).collect(); + uvs.extend((0..3).rev().map(|k| [k as f64, 4.0])); + uvs.extend((0..4).rev().map(|k| [0.0, k as f64])); + uvs.extend((1..=8).map(|k| [k as f64, 0.0])); + uvs.extend((1..=4).map(|k| [8.0, k as f64])); + uvs.extend((3..8).rev().map(|k| [k as f64, 4.0])); + uvs.extend((2..4).rev().map(|k| [3.0, k as f64])); + let fixed: Vec = uvs.iter().map(|q| Vec3::new(q[0], q[1], 0.0)).collect(); + let ranges = [std::ops::Range { start: 0, end: uvs.len() }]; + let traces = motorcycle::traces(&uvs, &ranges, [1.0, 1.0], 0.0); + let lines = |n: usize, top: f64| (0..=n).map(|k| top * k as f64 / n as f64).collect::>(); + let Some((extra, triangles)) = cutgrid::cut_grid(&uvs, &ranges, &lines(16, 8.0), &lines(8, 4.0), &traces, [1.0, 1.0]) else { panic!("meshes") }; + assert!(closed_boundary(&ranges, &fixed, &uvs, &triangles), "the triangles follow the slit both ways"); + let mut all = uvs.clone(); + all.extend(extra); + let area: f64 = triangles + .iter() + .map(|t| { + let [a, b, c] = t.map(|i| all[i as usize]); + 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) + }) + .sum(); + assert!((area - 32.0).abs() < 1e-12, "area {area}"); +} + +/// A face whose loop is a thin lune meshes: a half disc of radius 2.5 less a circle through the +/// same ends 0.03 mm inside it at the middle, its inner side split at 11.25°. Each edge is +/// sampled to the 0.1 mm chord on its own: the outer arc's chords (every 22.5°) sag 0.048 mm, +/// more than the curves are apart, so the one from 0° to 22.5° passes inside the inner side's +/// node at 11.25° and crosses its chords; no triangulation follows a boundary that crosses +/// itself (the sliver caps of a joined ring of cylinder segments). The crossing chords are +/// halved on their edges until none cross. +#[test] +fn a_thin_lune_whose_chords_cross_meshes() { + use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; + let (r, gap, h, tol) = (2.5, 0.03, 5.0, 0.1); + // The inner circle: centre (−d, 0) and radius r + d·…, through (0, ±r), its middle at r − gap. + let d = (r * r - (r - gap) * (r - gap)) / (2.0 * (r - gap)); + let (centre, r2) = (Vec2::new(-d, 0.0), r - gap + d); + let top = r.atan2(d); + let split = 11.25f64.to_radians(); + let segs = vec![ + Seg2::Arc { center: Vec2::ZERO, radius: r, start: -0.5 * PI, sweep: PI }, + Seg2::Arc { center: centre, radius: r2, start: top, sweep: split - top }, + Seg2::Arc { center: centre, radius: r2, start: split, sweep: -top - split }, + ]; + let lune = Region2 { outer: Loop2 { segs }, holes: vec![] }; + let Some(body) = ok(crate::extrude(&Plane::XY, &[lune], 0.0, h)).pop() else { panic!("one body") }; + let rec = record(&body); + let (p, stats) = match plan(&rec, tol, None) { + Ok(r) => r, + Err(e) => panic!("lune: {e}"), + }; + assert_eq!(stats.planar + stats.structured + stats.delaunay, body.face_count(), "every face planned"); + let m = p.evaluate(); + assert_watertight(&m, "lune"); + assert!(m.measure().volume > 0.0, "inside out"); +} + +/// A doubly curved patch 40 mm across, and a loop on it in (u, v) whose right side folds back +/// past itself near the top: the last chord of the fold crosses the side, as a cusp or a sliver +/// whose sides sag across each other leaves a face's boundary. +fn a_face_crossing_itself() -> (EvalSurface, seam::Loop, size::Rules) { let mut ctrl = Vec::new(); - for j in 0..2 { - for k in 0..=5 { - let (x, y) = corner(k); - ctrl.push([x, y, f64::from(j) * 8.0, 1.0]); + for j in 0..3 { + for i in 0..3 { + let bump = if i == 1 && j == 1 { 12.0 } else { 0.0 }; + ctrl.push([20.0 * f64::from(i), 20.0 * f64::from(j), bump, 1.0]); } } let s = EvalSurface::Nurbs { - degree: [1, 1], - knots: [vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0], vec![0.0, 0.0, 1.0, 1.0]], - count: [6, 2], + degree: [2, 2], + knots: [vec![0., 0., 0., 1., 1., 1.], vec![0., 0., 0., 1., 1., 1.]], + count: [3, 3], ctrl, - closed: [true, false], + closed: [false, false], }; - let dom = uv::domain(&s); - assert_eq!(dom.period, [Some(5.0), None]); - assert_eq!(dom.range, [Some((0.0, 5.0)), Some((0.0, 1.0))]); - // A parameter a whole range below the start is the same point as one inside it. - for (a, b) in [(-0.5, 4.5), (-2.0, 3.0), (5.5, 0.5), (7.0, 2.0)] { - let (Some(out), Some(inside)) = (s.derivs(a, 0.25), s.derivs(b, 0.25)) else { panic!("evaluates") }; - assert!(out.0.dist(inside.0) < 1e-12, "u = {a} and u = {b}: {:?} vs {:?}", out.0, inside.0); + let corners = [[0.1, 0.1], [0.9, 0.1], [0.9, 0.7], [0.7, 0.95], [0.86, 0.8], [0.1, 0.9]]; + let mut uv: Vec<[f64; 2]> = Vec::new(); + for k in 0..corners.len() { + let (a, b) = (corners[k], corners[(k + 1) % corners.len()]); + for t in 0..8 { + let f = f64::from(t) / 8.0; + uv.push([a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f]); + } } - // The same net left open is not periodic, and keeps truck's end-span extension outside it. - let EvalSurface::Nurbs { degree, knots, count, ctrl, .. } = s else { panic!("nurbs") }; - let open = EvalSurface::Nurbs { degree, knots, count, ctrl, closed: [false, false] }; - assert_eq!(uv::domain(&open).period, [None, None]); - let (Some(out), Some(inside)) = (open.derivs(-0.5, 0.25), open.derivs(4.5, 0.25)) else { panic!("evaluates") }; - assert!(out.0.dist(inside.0) > 1.0, "an open surface does not wrap"); + let pts: Vec = uv.iter().filter_map(|q| s.derivs(q[0], q[1]).map(|(p, _, _)| p)).collect(); + assert_eq!(pts.len(), uv.len()); + (s, seam::Loop { uv, pts }, size::Rules::new(0.05, 40.0, None)) } -/// Each loop of a face is projected on its own, so on a periodic surface a hole can come out a -/// whole turn away from the boundary that holds it. Every loop is brought into the outer -/// boundary's period, where the hole cuts the face again. +/// A curved face crossing itself in (u, v) is refused by every method; the lenient fill leaves +/// the crossing side out and plans the rest in (u, v), with points inside the face on its surface +/// (the GPU evaluates them there), not flat between boundary nodes. #[test] -fn holes_are_brought_into_the_outer_boundarys_period() { - let tau = std::f64::consts::TAU; - let at = |u: f64, v: f64| seam::Loop { uv: vec![[u, v], [u + 0.2, v], [u + 0.2, v + 0.2], [u, v + 0.2]], pts: vec![Vec3::ZERO; 4] }; - let dom = uv::Domain { range: [Some((0.0, 1.0)), Some((0.0, tau))], period: [None, Some(tau)] }; - let mut loops = vec![at(0.0, -tau), at(0.4, 1.5), at(0.6, 1.5 - tau)]; - align_periods(&mut loops, &dom); - // The outer loop stays where it is; both holes land beside it, a whole turn moved or not. - assert_eq!(loops[0].uv[0], [0.0, -tau]); - assert!((loops[1].uv[0][1] - (1.5 - tau)).abs() < 1e-12, "{:?}", loops[1].uv[0]); - assert!((loops[2].uv[0][1] - (1.5 - tau)).abs() < 1e-12, "{:?}", loops[2].uv[0]); - // Nothing moves along a direction that does not repeat. - assert_eq!(loops[1].uv[0][0], 0.4); +fn a_curved_face_crossing_itself_is_filled_on_its_surface() { + let (s, l, rules) = a_face_crossing_itself(); + let size = size::face_size(&s, &uv::domain(&s), &rules); + let loops = std::slice::from_ref(&l); + let mut stats = PlanStats::default(); + assert!(plan_face(0, "spline", &s, loops, &rules, size, 0.0, &mut stats, Lenient::No).is_err()); + let Ok(fp) = plan_face(0, "spline", &s, loops, &rules, size, 0.0, &mut stats, Lenient::Yes) else { panic!("a lenient fill") }; + assert!(!fp.triangles.is_empty()); + assert!(fp.uv.len() > fp.fixed.len(), "{} points, {} on the boundary", fp.uv.len(), fp.fixed.len()); + // Each point inside the face on the surface where its parameters put it. + let mesh = TessPlan { surfaces: vec![s.clone()], faces: vec![FacePlan { surface: Some(0), ..fp.clone() }], ..TessPlan::default() }.evaluate(); + for (q, p) in fp.uv.iter().zip(&mesh.positions).skip(fp.fixed.len()) { + let Some((on, _, _)) = s.derivs(q[0], q[1]) else { panic!("evaluates at {q:?}") }; + assert!(on.dist(*p) < 1e-9, "{q:?}"); + } } -/// A boundary that steps out to a node and straight back encloses no area: the pair is dropped, -/// so what is left no longer runs along itself. The two sides need only agree within the given -/// distance — a STEP writer may draw them as two curves a hair apart. +/// The face filled leniently is named in the plan's stats with why the strict plan refused it, and +/// counted under no method: the display has no hole, and the defect is still reported. #[test] -fn zero_width_slits_are_dropped_from_a_boundary() { - let p = |x: f64| Vec3::new(x, 0.0, 0.0); - // A square with a slit poked into it from the corner (2, 1): out to (2, 2) and back. - let slit = vec![ - p(0.0), - p(1.0), - Vec3::new(2.0, 1.0, 0.0), - Vec3::new(2.0, 2.0, 0.0), - Vec3::new(2.0 + 1e-9, 1.0, 0.0), - p(3.0), - Vec3::new(3.0, 3.0, 0.0), - Vec3::new(0.0, 3.0, 0.0), +fn a_face_filled_leniently_is_named_in_the_stats() { + let (s, l, rules) = a_face_crossing_itself(); + let size = size::face_size(&s, &uv::domain(&s), &rules); + let Ok((fp, stats)) = plan_or_fill(7, "spline", &s, std::slice::from_ref(&l), &rules, size, 0.0, None) else { panic!("filled leniently") }; + assert!(!fp.triangles.is_empty()); + assert_eq!((stats.planar, stats.structured, stats.delaunay), (0, 0, 0)); + let [lenient] = stats.lenient.as_slice() else { panic!("one lenient face: {:?}", stats.lenient) }; + assert_eq!(lenient.face, 7); + assert!(lenient.reason.contains("face 7 (spline)"), "{}", lenient.reason); +} + +/// A face whose boundary still crosses itself after untangling (two edges leaving a vertex +/// tangentially: their chords cross however often they are halved, as on one of Poppy +/// Humanoid's faces) is filled leniently straight away with that reason, and named: the body's +/// other faces are planned as usual instead of the whole body failing with it. +#[test] +fn a_face_untangling_cannot_resolve_is_filled_leniently_and_named() { + let (s, l, rules) = a_face_crossing_itself(); + let size = size::face_size(&s, &uv::domain(&s), &rules); + let why = "face 7 (spline): boundary crosses itself: edges [1, 2] run closer together than their chords can follow"; + let Ok((fp, stats)) = plan_or_fill(7, "spline", &s, std::slice::from_ref(&l), &rules, size, 0.0, Some(why)) else { panic!("filled leniently") }; + assert!(!fp.triangles.is_empty()); + let [lenient] = stats.lenient.as_slice() else { panic!("one lenient face: {:?}", stats.lenient) }; + assert_eq!(lenient.face, 7); + assert!(lenient.reason.contains(why), "{}", lenient.reason); +} + +#[test] +fn a_face_bounded_by_two_short_arcs_keeps_an_area_to_mesh() { + // A lens on z = 0 between two radius-1000 circles crossing at (±10, 0), in a record whose + // other face, a 2 m square, sets the segment length: each arc sags 0.05 mm off its chord, + // inside a 0.5 mm tolerance, so each samples as one segment and the two chords lie on one + // line, a boundary of no area. Its loop's segments are split until it encloses one. + use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble}; + use solidcore_record::brep::{Curve, Frame, Surface}; + use std::f64::consts::{PI, TAU}; + let (r, half) = (1000.0f64, 10.0f64); + let c = (r * r - half * half).sqrt(); + let circle = |cy: f64| Curve::Circle { frame: Frame { origin: [0.0, cy, 0.0], x_axis: [1.0, 0.0, 0.0], y_axis: [0.0, 1.0, 0.0] }, radius: r }; + let top = c.atan2(half); + let line = |a: [f64; 3], z: [f64; 3]| Curve::Line { start: a, end: z }; + let sq = [[3000.0, 0.0, 0.0], [5000.0, 0.0, 0.0], [5000.0, 2000.0, 0.0], [3000.0, 2000.0, 0.0]]; + let plane = Surface::Plane { origin: [0.0; 3], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] }; + let mut edges = vec![ + PartEdge { nurbs: None, curve: circle(-c), interval: [top, PI - top], vertices: [0, 1] }, + PartEdge { nurbs: None, curve: circle(c), interval: [PI + top, TAU - top], vertices: [1, 0] }, ]; - let (out, known) = drop_slits(&[slit], &[Vec::new()], 1e-6); - assert_eq!(out.len(), 1); - assert_eq!(out[0], vec![p(0.0), p(1.0), Vec3::new(2.0, 1.0, 0.0), p(3.0), Vec3::new(3.0, 3.0, 0.0), Vec3::new(0.0, 3.0, 0.0)]); - assert_eq!(known[0].len(), out[0].len()); - // Too far apart to be one slit: the boundary is left as it is. - let wide = vec![p(0.0), p(1.0), Vec3::new(2.0, 1.0, 0.0), Vec3::new(2.0, 2.0, 0.0), Vec3::new(2.5, 1.0, 0.0), p(3.0)]; - let kept = drop_slits(std::slice::from_ref(&wide), &[Vec::new()], 1e-6).0; - assert_eq!(kept, vec![wide]); -} - -/// A pointed end read back from STEP (a screw's tip, a cone): its cone face is written as the -/// rim, the seam up to the apex and the seam back, and a sector of one as its rim and two -/// sides meeting at the apex. Unwrapped to the nearest copy at every step, the jump at the -/// apex made such a loop seem to wind around the cone; the face could not be cut along a seam -/// it did not have, and the whole body lost its display plan. -#[test] -fn a_pointed_end_read_back_from_step_is_planned() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let (r, tip, len) = (3.0, 4.0, 20.0); - let Some(axis) = Plane::new(Vec3::ZERO, Vec3::X, Vec3::Z) else { panic!("plane") }; - let pts = [Vec2::new(0.0, 0.0), Vec2::new(r, tip), Vec2::new(r, len), Vec2::new(0.0, len)]; - for turn in [360.0f64, 300.0, 270.0, 200.0] { - let region = Region2 { outer: Loop2::polygon(&pts), holes: vec![] }; - let Some(body) = ok(crate::revolve(&axis, &[region], Vec2::ZERO, Vec2::Y, turn.to_radians())).pop() else { panic!("revolve") }; - let imported = ok(crate::step_import(&ok(crate::step_export(&[&body], "pointed end")))); - let Some(copy) = imported.bodies.first() else { panic!("no body") }; - let volume = std::f64::consts::PI * r * r * (len - tip + tip / 3.0) * turn / 360.0; - check(&format!("pointed end turned {turn} deg"), ©.body, 0.02, volume); + for k in 0..4 { + edges.push(PartEdge { + nurbs: None, + curve: line(sq[k], sq[(k + 1) % 4]), + interval: [0.0, 1.0], + vertices: [2 + k as u32, 2 + ((k + 1) % 4) as u32], + }); } -} - -/// A point on a spline that turns many times (a thread's helical flank, as other CAD systems -/// write it to STEP, has hundreds of spans along the helix) is found from a hint a few turns -/// away: between 16 starts across the whole spline Newton settled on another turn, the point -/// was taken as off the surface and the body lost its display plan. -#[test] -fn a_point_on_a_long_helical_spline_projects() { - let (turns, per_turn, pitch) = (40usize, 24usize, 0.5); - let n = turns * per_turn + 1; - let at = |i: usize, r: f64| { - let t = std::f64::consts::TAU * i as f64 / per_turn as f64; - [r * t.cos(), r * t.sin(), pitch * t / std::f64::consts::TAU, 1.0] + let uses = |es: &[u32]| es.iter().map(|&edge| PartUse { edge, forward: true, given: None }).collect::>(); + let mut vertices = vec![[half, 0.0, 0.0], [-half, 0.0, 0.0]]; + vertices.extend(sq); + let parts = Parts { + vertices, + edges, + faces: vec![ + PartFace { surface: plane.clone(), forward: true, loops: vec![uses(&[0, 1])] }, + PartFace { surface: plane, forward: true, loops: vec![uses(&[2, 3, 4, 5])] }, + ], + tolerance: 1e-6, }; - let mut ctrl: Vec<[f64; 4]> = Vec::with_capacity(2 * n); - for i in 0..n { - ctrl.push(at(i, 0.7)); - ctrl.push(at(i, 0.55)); + let made = ok(assemble(parts, false)); + let (plan, _) = ok(plan(&made.brep, 0.5, None)); + let lens = made.faces.first().and_then(|&f| plan.faces.get(f)).expect("the lens's plan"); + // One round of halving puts a node at each arc's middle, (0, ±(r − c)) (the plane's (u, v) + // is its (x, y)): the triangles fill the rhombus with diagonals 2·half and 2(r − c). + let area: f64 = lens + .triangles + .iter() + .map(|t| { + let [a, b, c] = t.map(|i| lens.uv[i as usize]); + 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) + }) + .sum(); + let rhombus = 2.0 * half * (r - c); + assert!((area - rhombus).abs() < 1e-9 * rhombus, "{area} vs {rhombus}"); +} + +/// Half of a square pyramid's sides as one spline face: degree 1, closed round the square +/// (u in [0, 4], a corner at each whole u) and from the base (v = 0) up to a top side collapsed +/// to a square 1e-7 mm across, not to a point, as the patch's side in Poppy Humanoid's connector +/// a quarter of a sphere cap's corner sits on. Its loop runs down the side at u = 0, along the +/// base to u = 2 and up again, then across the top back to the corner it started at, half a +/// period along. Taken for no pole, that step is taken as the nearest copy, and the loop winds +/// once round the surface with no partner to cut it along. +fn pyramid_past_a_near_pole(pole_tolerance: f64) -> solidcore_record::brep::Brep { + use solidcore_record::brep::{self as b, Curve, Curve2, Surface}; + let top = 1e-7; + let corner = |u: usize, r: f64, z: f64| { + let [x, y] = [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.0, -1.0]][u % 4]; + [r * x, r * y, z] + }; + let points: Vec> = (0..5).map(|u| vec![corner(u, 1.0, 0.0), corner(u, top, 1.0)]).collect(); + let surface = Surface::Spline { u_knots: vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0], v_knots: vec![0.0, 0.0, 1.0, 1.0], points }; + let edge = + |curve: Curve, interval: [f64; 2], vertices: [u32; 2]| b::Edge { nurbs: None, curve, interval, vertices, tolerance: 1e-6, uses: Vec::new() }; + let edges = vec![ + edge(Curve::Line { start: corner(0, 1.0, 0.0), end: corner(0, top, 1.0) }, [0.0, 1.0], [1, 0]), + edge(Curve::Polyline { points: vec![corner(0, 1.0, 0.0), corner(1, 1.0, 0.0), corner(2, 1.0, 0.0)] }, [0.0, 2.0], [1, 2]), + edge(Curve::Line { start: corner(2, 1.0, 0.0), end: corner(2, top, 1.0) }, [0.0, 1.0], [2, 0]), + ]; + let line = |t: [f64; 2], a: [f64; 2], z: [f64; 2]| Curve2::Spline { knots: vec![t[0], t[0], t[1], t[1]], points: vec![a, z] }; + let uses = vec![ + b::OrientedEdge { edge: 0, forward: false, pcurve: line([0.0, 1.0], [0.0, 0.0], [0.0, 1.0]) }, + b::OrientedEdge { edge: 1, forward: true, pcurve: line([0.0, 2.0], [0.0, 0.0], [2.0, 0.0]) }, + b::OrientedEdge { edge: 2, forward: true, pcurve: line([0.0, 1.0], [2.0, 0.0], [2.0, 1.0]) }, + ]; + let face = b::Face { nurbs: None, surface, domain: [[0.0, 2.0], [0.0, 1.0]], loops: vec![b::Loop::Edges { edges: uses }] }; + let vertex = |point: [f64; 3], tolerance: f64| b::Vertex { point, tolerance }; + let loose = b::Brep { + version: b::VERSION, + tolerance: 1e-7, + regions: vec![b::Region { shells: vec![0], void: false }], + shells: vec![b::Shell::Faces { faces: vec![b::OrientedFace { face: 0, forward: true }], wires: Vec::new() }], + faces: vec![face], + edges, + vertices: vec![vertex([0.0, 0.0, 1.0], pole_tolerance), vertex(corner(0, 1.0, 0.0), 1e-7), vertex(corner(2, 1.0, 0.0), 1e-7)], + }; + ok(loose.canonical().map_err(|e| crate::KernelError::Invalid(format!("{e:?}")))).brep +} + +/// The corner of [`pyramid_past_a_near_pole`] within its vertex's tolerance of the collapsed top +/// side is a pole, and the face plans strictly over both its sides; with a tolerance short of +/// the top's size it is no pole, and the loop winds. +#[test] +fn a_loop_corner_within_its_tolerance_of_a_pole_is_a_pole() { + let (made, stats) = ok(plan(&pyramid_past_a_near_pole(1e-6), 0.01, None)); + assert!(stats.lenient.is_empty() && stats.unmeshed.is_empty(), "{stats:?}"); + // Two of the pyramid's sides, each a triangle of area √3 / 2. + let area = made.evaluate().measure().area; + assert!((area - 3f64.sqrt()).abs() < 0.01 * 3f64.sqrt(), "area {area}"); + let Err(e) = plan(&pyramid_past_a_near_pole(1e-8), 0.01, None) else { panic!("no pole without the tolerance") }; + assert!(e.to_string().contains("winds around the surface"), "{e}"); +} + +/// A whole sphere as one face (its seam the only edge) in a body many times its size: at the +/// body's chord the seam gets two segments, pole to equator to pole, and every node off the poles +/// follows a pole. The loop used to start at a pole and close across the other, which unwrapped +/// to a whole turn: "boundary winds around the surface", and the sphere was left out (a sealed +/// void r 2 in a 60 mm block). It meshes closed. +#[test] +fn a_small_sphere_void_in_a_large_block_meshes() { + let block = ok(crate::box_solid(Vec3::new(-30.0, -30.0, 0.0), Vec3::new(30.0, 30.0, 60.0))); + let ball = ok(crate::sphere(Vec3::new(0.0, 0.0, 30.0), 2.0)); + let hollow = cut(&block, &ball); + let tol = hollow.size() * 0.01; + let (m, stats) = match plan(&record(&hollow), tol, None) { + Ok((p, stats)) => (p.evaluate(), stats), + Err(e) => panic!("plan: {e}"), + }; + assert!(stats.unmeshed.is_empty(), "{:?}", stats.unmeshed.iter().map(|u| &u.reason).collect::>()); + assert_watertight(&m, "block with a sphere void"); + assert_eq!(hollow.unmeshed_faces(), 0); +} + +/// A sheet whose section is an S (a cubic 30 long, 1.5 off its chord each way, its middle on the +/// chord), straight across, meshed as fans with one triangle flat on the chord across its middle +/// (A, B at the sides, C a hair above the chord a third along). The chord's middle lies on the +/// surface while the triangle's short sides sag: splitting those left a child with the chord and +/// its vertex nearer to it, without end (a loft side of a bike frame refined to slivers until the +/// point budget ran out, its area counted three times). The flat triangle now splits the chord, +/// and refinement ends within its budget with no sliver. +#[test] +fn sag_refinement_across_an_inflection_ends_without_slivers() { + let mut ctrl = Vec::new(); + for j in 0..2 { + for (i, z) in [0.0, 4.0, -4.0, 0.0].into_iter().enumerate() { + ctrl.push([10.0 * i as f64, 10.0 * f64::from(j), z, 1.0]); + } } - let mut ku = vec![0.0; 3]; - ku.extend((1..n - 2).map(|i| i as f64 / (n - 2) as f64)); - ku.extend([1.0; 3]); - let s = EvalSurface::Nurbs { degree: [2, 1], knots: [ku, vec![0.0, 0.0, 1.0, 1.0]], count: [n, 2], ctrl, closed: [false, false] }; - let dom = uv::domain(&s); - for (target, hint) in [([0.5, 1.0], [0.488, 1.0]), ([0.2, 0.0], [0.23, 1.0]), ([0.9, 0.5], [0.1, 0.5])] { - let Some((p, _, _)) = s.derivs(target[0], target[1]) else { panic!("evaluate") }; - let Some(q) = uv::project(&s, &dom, p, Some(hint), 1e-4) else { panic!("{target:?} from {hint:?}: not found") }; - let Some((back, _, _)) = s.derivs(q[0], q[1]) else { panic!("evaluate") }; - assert!(back.dist(p) <= 1e-4, "{target:?} from {hint:?}: {q:?} is {} away", back.dist(p)); + let s = EvalSurface::Nurbs { + degree: [3, 1], + knots: [vec![0., 0., 0., 0., 1., 1., 1., 1.], vec![0., 0., 1., 1.]], + count: [4, 2], + ctrl, + closed: [false, false], + }; + // Boundary: bottom and top rows of n + 1 nodes (their sides within the tolerance, 0.5), A and + // B halfway up the ends. Inside: C. Bottom fan from A, the triangle A B C, top fan from C. + let n = 6u32; + let mut uv: Vec<[f64; 2]> = Vec::new(); + for i in 0..=n { + uv.push([f64::from(i) / f64::from(n), 0.0]); + } + for i in 0..=n { + uv.push([f64::from(i) / f64::from(n), 1.0]); + } + let (bottom, top) = (0u32, n + 1); + let (a, b, c) = (2 * n + 2, 2 * n + 3, 2 * n + 4); + uv.extend([[0.0, 0.5], [1.0, 0.5], [1.0 / 3.0, 0.5 + 1e-3]]); + let mut tris: Vec<[u32; 3]> = vec![[a, bottom, bottom + 1]]; + tris.extend((1..n).map(|i| [a, bottom + i, bottom + i + 1])); + tris.push([a, bottom + n, b]); + tris.push([a, b, c]); + tris.push([c, b, top + n]); + tris.extend((0..n).rev().map(|i| [c, top + i + 1, top + i])); + tris.push([c, top, a]); + // The sides along the ends are straight. + let fixed: Vec = Vec::new(); + let tol = 0.5; + let start = uv.len(); + super::sag::refine(&s, tol, 1e-9, &fixed, &mut uv, &mut tris, 20_000); + assert!(uv.len() - start < 1_000, "{} points added: refinement ran to its budget", uv.len() - start); + for t in &tris { + let [p, q, r] = t.map(|i| uv[i as usize]); + let area = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + let longest = [(p, q), (q, r), (r, p)].iter().map(|(x, y)| (x[0] - y[0]).hypot(x[1] - y[1])).fold(0.0, f64::max); + assert!(area > 1e-6 * longest * longest, "a sliver {t:?}: {p:?} {q:?} {r:?}"); } } -/// A sliver face as STEP files write one: two edges between the same two vertices, a rounding -/// apart, so its boundary runs out and back along itself. Its slits dropped, nothing is left to -/// bound a face (it is planned empty); a boundary enclosing anything keeps its loop. +/// A sheet curved across (a parabola 20 wide, 3.2 high at a tenth in from either side) and two +/// triangles standing on a chord across the curve: their corners on the surface, their planes +/// across it, so they count far more than the area under them. The flip lays them along the +/// sheet, on the straight side along it. #[test] -fn a_boundary_running_back_along_itself_is_all_slit() { - let out: Vec = (0..5).map(|i| Vec3::new(f64::from(i), 0.5 * f64::from(i), 0.0)).collect(); - let mut sliver = out.clone(); - sliver.extend(out.iter().rev().skip(1).take(3).map(|p| *p + Vec3::new(0.0, 1e-14, 0.0))); - let (left, _) = drop_slits(&[sliver], &[Vec::new()], 1e-9); - assert!(left.iter().all(|l| l.len() < 3), "{left:?}"); - let mut lens = out.clone(); - lens.extend(out.iter().rev().skip(1).take(3).map(|p| *p + Vec3::new(0.0, 1e-3, 0.0))); - let (kept, _) = drop_slits(std::slice::from_ref(&lens), &[Vec::new()], 1e-9); - assert_eq!(kept, vec![lens]); +fn triangles_standing_across_a_curved_sheet_are_flipped_along_it() { + let mut ctrl = Vec::new(); + for j in 0..2 { + for (i, z) in [5.0, -5.0, 5.0].into_iter().enumerate() { + ctrl.push([10.0 * i as f64 - 10.0, 10.0 * f64::from(j), z, 1.0]); + } + } + let s = EvalSurface::Nurbs { + degree: [2, 1], + knots: [vec![0., 0., 0., 1., 1., 1.], vec![0., 0., 1., 1.]], + count: [3, 2], + ctrl, + closed: [false, false], + }; + let uv = vec![[0.1, 0.5], [0.9, 0.5], [0.5, 0.52], [0.5, 0.48]]; + let mut tris = vec![[0, 1, 2], [1, 0, 3]]; + let area = |tris: &[[u32; 3]]| -> f64 { + tris.iter() + .map(|t| { + let [a, b, c] = t.map(|i| s.eval(uv[i as usize][0], uv[i as usize][1]).0); + (b - a).cross(c - a).len() / 2.0 + }) + .sum() + }; + let before = area(&tris); + super::sag::flip(&s, 0.1, 1e-9, &[], &uv, &mut tris); + let after = area(&tris); + let sides: Vec<(u32, u32)> = tris.iter().flat_map(|t| (0..3).map(move |k| (t[k].min(t[(k + 1) % 3]), t[k].max(t[(k + 1) % 3])))).collect(); + assert!(sides.contains(&(2, 3)) && !sides.contains(&(0, 1)), "{tris:?}"); + assert!(after < 0.5 * before, "{before} -> {after}"); +} + +/// A disc with a boss standing on it tangent inside its rim: the disc's top is a ring whose inner +/// circle touches the outer one, one loop through the touching vertex. There both circles leave +/// along one tangent, and with the outer chord twice the inner (as their samplings fall) the inner +/// circle's first node lies on the outer's last chord: no triangulation keeps both. That chord is +/// halved, and the ring meshes strictly, to its area (300 pi), not the inner disc's. +#[test] +fn a_ring_touching_itself_at_a_vertex_meshes_strictly() { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; + let prism = |c: Vec2, r: f64, z0: f64, z1: f64| { + ok(crate::extrude(&Plane::XY, &[Region2 { outer: Loop2::circle(c, r), holes: vec![] }], z0, z1)).pop().unwrap() + }; + let stepped = + ok(crate::boolean(&prism(Vec2::ZERO, 20.0, 0.0, 5.0), &prism(Vec2::new(10.0, 0.0), 10.0, 5.0, 15.0), crate::BoolOp::Union)).unwrap(); + let (_, stats) = ok(plan(&record(&stepped), 1e-4, None)); + assert!(stats.lenient.is_empty(), "{:?}", stats.lenient.iter().map(|r| &r.reason).collect::>()); + let ring = ok(stepped.faces(1e-4)).into_iter().find(|f| (f.centroid.z - 5.0).abs() < 1e-6).unwrap(); + assert!((ring.area - 300.0 * PI).abs() < 0.05, "ring area {}", ring.area); } diff --git a/crates/kernel/src/tess/uv.rs b/crates/kernel/src/tess/uv.rs index b74e7706e..8e72f0868 100644 --- a/crates/kernel/src/tess/uv.rs +++ b/crates/kernel/src/tess/uv.rs @@ -2,175 +2,13 @@ //! the plan stores are the ones the evaluators use), and the tolerance-driven divisions of a //! face's parameter box. -use solidcraft_geom::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_geom::tess::EvalSurface; +pub(crate) use solidcraft_geom::tess::uv::{Domain, degenerate_within, domain, unwrap}; +use super::edges::{QUARTER_TURN, turn}; use super::size::Rules; -/// The parameter box of a surface and its periods. -#[derive(Clone, Copy, Debug)] -pub(crate) struct Domain { - /// Bounded ranges (`None`: unbounded, as a plane's). - pub range: [Option<(f64, f64)>; 2], - pub period: [Option; 2], -} - -pub(crate) fn domain(s: &EvalSurface) -> Domain { - let tau = std::f64::consts::TAU; - match s { - EvalSurface::Plane { .. } => Domain { range: [None, None], period: [None, None] }, - EvalSurface::Nurbs { degree, knots, count, closed, .. } => { - let r = |d: usize| Some((*knots.get(d)?.get(*degree.get(d)?)?, *knots.get(d)?.get(*count.get(d)?)?)); - // A direction the surface joins itself along is periodic: a boundary that runs - // across the join is unwrapped past the range's end, and the evaluator wraps it back. - let p = |d: usize| closed.get(d).copied().unwrap_or(false).then(|| r(d).map(|(a, b)| b - a)).flatten().filter(|x| *x > 0.0); - Domain { range: [r(0), r(1)], period: [p(0), p(1)] } - } - EvalSurface::Revolved { profile, swap, .. } => { - let r = (|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?)))(); - let (a, b) = ((r, None), (Some((0.0, tau)), Some(tau))); - let (u, v) = if *swap { (b, a) } else { (a, b) }; - Domain { range: [u.0, v.0], period: [u.1, v.1] } - } - } -} - -impl Domain { - pub(crate) fn clamp(&self, uv: [f64; 2]) -> [f64; 2] { - let mut out = uv; - for (d, x) in out.iter_mut().enumerate() { - if let (Some((a, b)), None) = (self.range[d], self.period[d]) { - *x = x.clamp(a.min(b), a.max(b)); - } - } - out - } -} - -/// Damped Gauss–Newton (Levenberg–Marquardt) for the parameters nearest to `p`, from `start`. -/// Returns the parameters and their distance to `p`. -fn newton(s: &EvalSurface, dom: &Domain, p: Vec3, start: [f64; 2]) -> Option<([f64; 2], f64)> { - let mut uv = dom.clamp(start); - let (mut q, mut su, mut sv) = s.derivs(uv[0], uv[1])?; - let mut dist = q.dist(p); - let mut lambda = 1e-6; - for _ in 0..60 { - let r = p - q; - let (a, b, c) = (su.len2(), su.dot(sv), sv.len2()); - let (g0, g1) = (su.dot(r), sv.dot(r)); - let scale = a + c; - if !(scale > 0.0) || !scale.is_finite() { - break; - } - let (a2, c2) = (a + lambda * scale, c + lambda * scale); - let det = a2 * c2 - b * b; - if !(det.abs() > 0.0) { - break; - } - let step = [(c2 * g0 - b * g1) / det, (a2 * g1 - b * g0) / det]; - let next = dom.clamp([uv[0] + step[0], uv[1] + step[1]]); - let Some((nq, nsu, nsv)) = s.derivs(next[0], next[1]) else { break }; - let nd = nq.dist(p); - if nd <= dist { - let moved = (next[0] - uv[0]).abs() + (next[1] - uv[1]).abs(); - (uv, q, su, sv, dist) = (next, nq, nsu, nsv, nd); - lambda = (lambda * 0.1).max(1e-12); - if moved <= 1e-15 * (1.0 + uv[0].abs() + uv[1].abs()) { - break; - } - } else { - lambda *= 10.0; - if lambda > 1e8 { - break; - } - } - } - Some((uv, dist)) -} - -/// Parameters of `p` (a point on the surface within `accept`), from `hint` when that -/// converges, else from the best starts of a grid over the surface's domain. -pub(crate) fn project(s: &EvalSurface, dom: &Domain, p: Vec3, hint: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { - if let EvalSurface::Plane { origin, du, dv } = s { - let r = p - *origin; - let (a, b, c) = (du.len2(), du.dot(*dv), dv.len2()); - let det = a * c - b * b; - if !(det.abs() > 0.0) { - return None; - } - let (g0, g1) = (du.dot(r), dv.dot(r)); - let uv = [(c * g0 - b * g1) / det, (a * g1 - b * g0) / det]; - return (uv[0].is_finite() && uv[1].is_finite()).then_some(uv); - } - let mut best: Option<([f64; 2], f64)> = None; - if let Some(h) = hint - && let Some((uv, d)) = newton(s, dom, p, h) - { - if d <= accept { - return Some(uv); - } - best = Some((uv, d)); - } - let (ur, vr) = (dom.range[0]?, dom.range[1]?); - let [nu, nv] = start_lines(s); - let mut starts: Vec<(f64, [f64; 2])> = Vec::with_capacity((nu + 1) * (nv + 1)); - for i in 0..=nu { - for j in 0..=nv { - let uv = [ur.0 + (ur.1 - ur.0) * i as f64 / nu as f64, vr.0 + (vr.1 - vr.0) * j as f64 / nv as f64]; - if let Some((q, _, _)) = s.derivs(uv[0], uv[1]) { - starts.push(((q - p).len2(), uv)); - } - } - } - starts.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, start) in starts.iter().take(4) { - if let Some((uv, d)) = newton(s, dom, p, *start) - && best.is_none_or(|(_, bd)| d < bd) - { - best = Some((uv, d)); - } - } - best.filter(|(_, d)| *d <= accept).map(|(uv, _)| uv) -} - -/// Most starts [`project`] tries along one direction, and over the whole domain. -const MAX_START_LINES: usize = 4096; -const MAX_STARTS: usize = 16_384; - -/// How many divisions of each direction [`project`] starts from: 16, or two per span of a -/// spline with more. A long spline (a thread's helical flank, as other CAD systems write it to -/// STEP: hundreds of spans along the helix) turns many times between 16 starts, and from the -/// nearest of them Newton settles on another turn, so a point of its boundary was taken as off -/// the surface and the body lost its display plan. -fn start_lines(s: &EvalSurface) -> [usize; 2] { - const N: usize = 16; - let spans = |d: usize| match s { - EvalSurface::Nurbs { degree, count, .. } => count.get(d).zip(degree.get(d)).map_or(0, |(c, g)| c.saturating_sub(*g)), - _ => 0, - }; - let mut lines = [0, 1].map(|d| (2 * spans(d)).clamp(N, MAX_START_LINES)); - // The longer direction keeps its spans; the other gives way to the cap on starts. - let (long, short) = if lines[0] >= lines[1] { (0, 1) } else { (1, 0) }; - lines[short] = lines[short].min((MAX_STARTS / (lines[long] + 1)).max(N)); - lines -} - -/// `x` moved by whole periods to lie within half a period of `near`. -pub(crate) fn unwrap(x: f64, near: f64, period: Option) -> f64 { - match period { - Some(p) if p > 0.0 => x - ((x - near) / p).round() * p, - _ => x, - } -} - -/// Is the surface degenerate along direction `d` at `uv` (a pole: moving along `d` does not -/// move the point)? -pub(crate) fn degenerate(s: &EvalSurface, uv: [f64; 2], d: usize) -> bool { - let Some((_, su, sv)) = s.derivs(uv[0], uv[1]) else { return false }; - let (this, other) = if d == 0 { (su, sv) } else { (sv, su) }; - this.len() <= 1e-9 * other.len().max(1e-12) -} - /// Division of `range` along direction `d` so that between neighbouring lines the surface sags /// at most the tolerance from its chord, the chord is at most `h` long and the normal turns /// within the rules' facet angle, checked along iso-lines across `across`; at most `max_lines` @@ -180,19 +18,10 @@ pub(crate) fn divide(s: &EvalSurface, d: usize, range: (f64, f64), across: (f64, if !(a1 > a0) { return vec![a0, a1]; } - let flat = limits(s, d, across, rules, h); - // Start from quarter turns at most, so a closed iso-line is not taken for a flat one (a - // plane's parameters are lengths and its lines are never closed). - let initial = if matches!(s, EvalSurface::Plane { .. }) { 1 } else { ((a1 - a0) / std::f64::consts::FRAC_PI_2).ceil().clamp(1.0, 64.0) as u32 }; - // Both ends exactly (a0 + (a1 − a0) · 1 may round away from a1): the end lines are the - // face's own parameter box, which the boundary nodes sit on. - let starts: Vec = (0..=initial) - .map(|i| { - let t = f64::from(i) / f64::from(initial); - a0 * (1.0 - t) + a1 * t - }) - .collect(); - split(&starts, &flat, max_lines) + // The whole range first: the limits split it, and no interval spans more than a quarter + // turn of its iso-lines, so a closed iso-line is never taken for a flat one. Both ends + // exactly: the end lines are the face's own parameter box, which the boundary nodes sit on. + split(&[a0, a1], &limits(s, d, across, rules, h), max_lines) } /// `lines` (increasing, ends included) with every interval that fails the same limits as @@ -244,8 +73,14 @@ pub(crate) fn fine_between(s: &EvalSurface, rules: &Rules, h: f64, a: [f64; 2], } } +/// An iso-line's extent below which it is a point, as a fraction of the chord tolerance (which +/// is never finer than a millionth of the body, so this is far above rounding). +const POINT: f64 = 1e-6; + /// Whether the surface between the iso-lines at `a` and `b` (direction `d`, sampled along -/// iso-lines across `across`) is within the tolerance, the side length `h` and the facet angle. +/// iso-lines across `across`) is within the tolerance, the side length `h` and the facet angle, +/// and spans at most a quarter turn of each iso-line (as an edge segment does, see +/// [`QUARTER_TURN`]): a turn read from the points, since a spline's parameter is no angle. fn limits<'a>(s: &'a EvalSurface, d: usize, across: (f64, f64), rules: &'a Rules, h: f64) -> impl Fn(f64, f64) -> bool + 'a { let tol = rules.tol; let uv = move |x: f64, y: f64| if d == 0 { (x, y) } else { (y, x) }; @@ -269,6 +104,15 @@ fn limits<'a>(s: &'a EvalSurface, d: usize, across: (f64, f64), rules: &'a Rules if sag > tol { return false; } + // The two half chords of an arc turning θ differ by θ/2; a closed iso-line's by π. + // An iso-line within a millionth of the tolerance of one point (a pole) turns no + // amount: its directions are rounding. + if let Some(pm) = at(0.5 * (a + b), y) + && pa.dist(pm).max(pm.dist(pb)) > POINT * tol + && 2.0 * turn(pm - pa, pb - pm) > QUARTER_TURN + { + return false; + } // At a pole the normal is undefined: take it from just inside the segment. let na = normal(a, y).or_else(|| normal(a + 1e-4 * (b - a), y)); let nb = normal(b, y).or_else(|| normal(b - 1e-4 * (b - a), y)); @@ -283,6 +127,7 @@ fn limits<'a>(s: &'a EvalSurface, d: usize, across: (f64, f64), rules: &'a Rules #[cfg(test)] mod tests { use super::*; + use solidcore_record::Vec3; use solidcraft_geom::tess::EvalCurve; fn cylinder() -> EvalSurface { @@ -295,81 +140,49 @@ mod tests { } } - #[test] - fn projects_points_back_to_their_parameters() { - let s = cylinder(); - let dom = domain(&s); - for &(u, v) in &[(0.1, 0.2), (0.5, 3.0), (0.9, 6.0), (0.0, 1.0)] { - let (p, _) = s.eval(u, v); - let Some(uv) = project(&s, &dom, p, None, 1e-9) else { panic!("projects") }; - let (q, _) = s.eval(uv[0], uv[1]); - assert!(q.dist(p) < 1e-9); - assert!((uv[0] - u).abs() < 1e-9); - } - // Off the surface by more than `accept`: no parameters. - assert!(project(&s, &dom, Vec3::new(5.0, 0.0, 1.0), None, 1e-3).is_none()); - } - #[test] fn divides_the_turn_but_not_the_straight_direction() { let s = cylinder(); - let turn = divide( - &s, - 1, - (0.0, std::f64::consts::TAU), - (0.0, 1.0), - &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, - f64::INFINITY, - 10_000, - ); - let along = divide( - &s, - 0, - (0.0, 1.0), - (0.0, std::f64::consts::TAU), - &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, - f64::INFINITY, - 10_000, - ); + let turn = + divide(&s, 1, (0.0, std::f64::consts::TAU), (0.0, 1.0), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, f64::INFINITY, 10_000); + let along = + divide(&s, 0, (0.0, 1.0), (0.0, std::f64::consts::TAU), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, f64::INFINITY, 10_000); assert_eq!(along, vec![0.0, 1.0]); // Chord sag r(1 − cos(θ/2)) ≤ 0.01 with r = 3 needs θ ≤ 0.163: at least 39 segments. assert!(turn.len() >= 40 && turn.len() < 80, "{}", turn.len()); // With a longest side the straight direction is divided too: 4 mm in sides ≤ 0.5. - let along = divide( - &s, - 0, - (0.0, 1.0), - (0.0, std::f64::consts::TAU), - &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, - 0.5, - 10_000, - ); + let along = divide(&s, 0, (0.0, 1.0), (0.0, std::f64::consts::TAU), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, 0.5, 10_000); assert_eq!(along.len(), 9); } + /// A quarter of a cylinder as a rational quadratic spline (as SMLib holds a bend), its range a + /// rounding over π/2 as a boundary's pcurves give it: the quarter turn is read from the + /// surface, not the parameter, so at a tolerance above its sag it is one interval; and a whole + /// turn is still divided into quarters however coarse the tolerance. + #[test] + fn a_quarter_turn_is_read_from_the_surface_not_the_parameter() { + let w = std::f64::consts::FRAC_1_SQRT_2; + let q = std::f64::consts::FRAC_PI_2; + let s = EvalSurface::nurbs( + [1, 2], + [vec![0.0, 0.0, 40.0, 40.0], vec![0.0, 0.0, 0.0, q, q, q]], + [2, 3], + vec![[1.0, 0.0, 0.0, 1.0], [1.0, 0.0, 40.0, 1.0], [w, w, 0.0, w], [w, w, 40.0 * w, w], [0.0, 1.0, 0.0, 1.0], [0.0, 1.0, 40.0, 1.0]], + ); + let coarse = Rules { tol: 3.0, max_len: f64::INFINITY, turn: None }; + assert_eq!(divide(&s, 1, (-6.7e-13, q), (0.0, 40.0), &coarse, f64::INFINITY, 10_000), vec![-6.7e-13, q]); + let whole = divide(&cylinder(), 1, (0.0, std::f64::consts::TAU), (0.0, 1.0), &Rules { tol: 100.0, ..coarse }, f64::INFINITY, 10_000); + assert_eq!(whole.len(), 5, "{whole:?}"); + } + /// The first and last lines are the range's ends to the last bit: the boundary nodes sit on /// them, and a line a rounding inside would be taken for an interior one (a drill point's /// cone, where a0 + (a1 − a0) is not a1). #[test] fn divides_with_the_ends_exactly() { let (a0, a1) = (-1.010485317689877, 1.083909784703316); - let lines = divide( - &cylinder(), - 1, - (a0, a1), - (0.0, 1.0), - &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, - f64::INFINITY, - 10_000, - ); + let lines = divide(&cylinder(), 1, (a0, a1), (0.0, 1.0), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, f64::INFINITY, 10_000); assert_eq!(lines.first().copied(), Some(a0)); assert_eq!(lines.last().copied(), Some(a1)); } - - #[test] - fn unwraps_across_the_period() { - let tau = std::f64::consts::TAU; - assert!((unwrap(0.1, tau - 0.1, Some(tau)) - (tau + 0.1)).abs() < 1e-12); - assert_eq!(unwrap(0.1, 6.0, None), 0.1); - } } diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index 66a608e8a..cb0493222 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -1,6 +1,7 @@ +use solidcraft_geom::prelude::*; use std::f64::consts::PI; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use crate::*; @@ -31,7 +32,9 @@ fn cylinder_measures_match_analytic() { let a = 2.0 * PI * 225.0 + 2.0 * PI * 15.0 * 50.0; assert!(rel(m.volume, v) < 5e-4, "{} vs {v}", m.volume); assert!(rel(m.area, a) < 5e-4, "{} vs {a}", m.area); - assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (3, 2, 2), "{:?}", m.merged); + // Two closed circles and the side's seam (the ladder's count: each whole curve once, and each + // cylinder's seam); a vertex on each circle. + assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (3, 3, 2), "{:?}", m.merged); assert_eq!(m.merged.face_types.get("cylinder"), Some(&1)); } @@ -65,7 +68,7 @@ fn through_cut_preserves_a_larger_blind_pocket() { let m = measure(&result).unwrap(); assert!(rel(m.volume, expected) < 5e-4, "reverse={reverse}: {} vs {expected}", m.volume); assert_eq!(m.merged.faces, 9); - assert!(!result.tessellate(0.01).unwrap().contains(Vec3::new(10.0, 0.0, 3.0))); + assert!(!result.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().contains(Vec3::new(10.0, 0.0, 3.0))); } } @@ -285,41 +288,11 @@ fn fillet_ending_across_two_faces() { assert!((lost - removed).abs() < 0.07, "{lost} vs {removed}"); } -#[test] -fn loop_fillet_as_tall_as_its_wall_consumes_it() { - // The removed cross-section (a square of side r less a quarter disc) and its centroid's - // distance from the wall: r(10 − 3π) / (3(4 − π)). - let spandrel = |r: f64| ((1.0 - PI / 4.0) * r * r, r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI))); - // #190: a disc 13 in radius and 2 high, its top circle rounded by 2. Pappus for the ring. - let disc = cylinder(Vec3::ZERO, Vec3::Z, 13.0, 2.0).unwrap(); - let f = fillet(&disc, &[Vec3::new(0.0, 13.0, 2.0), Vec3::new(0.0, -13.0, 2.0)], 2.0).unwrap(); - let (a, c) = spandrel(2.0); - let want = PI * 169.0 * 2.0 - a * 2.0 * PI * (13.0 - c); - let m = measure(&f).unwrap(); - assert!(rel(m.volume, want) < 2e-4, "{} vs {want}", m.volume); - // Top, round and bottom: the wall is gone. - assert_eq!(m.merged.faces, 3, "{:?}", m.merged); - assert!(f.validity().is_empty(), "{:?}", f.validity()); - // A 40 x 30 x 5 plate, its whole top outline rounded by 5 (mitred at the corners). - let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 5.0)).unwrap(); - let top = [Vec3::new(20.0, 0.0, 5.0), Vec3::new(40.0, 15.0, 5.0), Vec3::new(20.0, 30.0, 5.0), Vec3::new(0.0, 15.0, 5.0)]; - let f = fillet(&plate, &top, 5.0).unwrap(); - let (a, c) = spandrel(5.0); - let want = 6000.0 - a * 2.0 * ((40.0 - 2.0 * c) + (30.0 - 2.0 * c)); - let m = measure(&f).unwrap(); - assert!(rel(m.volume, want) < 2e-4, "{} vs {want}", m.volume); - assert!(f.validity().is_empty(), "{:?}", f.validity()); - // Taller than the wall: still refused, the body unchanged. - for r in [2.0 + 1e-3, 2.5] { - let e = fillet(&disc, &[Vec3::new(0.0, 13.0, 2.0), Vec3::new(0.0, -13.0, 2.0)], r).unwrap_err(); - assert!(e.to_string().contains("taller than the walls"), "{r}: {e}"); - } -} - #[test] fn fillet_consuming_a_side_face_makes_a_full_round() { // 14 x 6 x 10: r = 3 on the four vertical edges uses up both 6 mm end faces (#199). let b = box_solid(Vec3::new(14.0, 0.0, 0.0), Vec3::new(28.0, 6.0, 10.0)).unwrap(); + let before = measure(&b).unwrap().volume; let mids = [Vec3::new(14.0, 0.0, 5.0), Vec3::new(28.0, 0.0, 5.0), Vec3::new(14.0, 6.0, 5.0), Vec3::new(28.0, 6.0, 5.0)]; let full = 840.0 - (4.0 - PI) * 9.0 * 10.0; for order in [mids.to_vec(), mids.iter().rev().copied().collect()] { @@ -341,12 +314,13 @@ fn fillet_consuming_a_side_face_makes_a_full_round() { let c = fillet(&post, &corners, 3.0).unwrap(); assert!(rel(measure(&c).unwrap().volume, PI * 9.0 * 10.0) < 2e-4, "{}", measure(&c).unwrap().volume); assert!(c.validity().is_empty()); - // Past the limit there is no face left to consume: still refused, the body unchanged. + // Past the limit the two rounds on each 6 mm end would cross: still refused as too large + // (SMLib's NO_ROOM), the body unchanged. for r in [3.0 + 1e-3, 3.5] { let e = fillet(&b, &mids, r).unwrap_err(); - assert!(e.to_string().contains("larger than the neighbouring faces"), "{r}: {e}"); + assert!(matches!(e, KernelError::TooLarge(_)), "{r}: {e}"); } - assert_eq!(measure(&b).unwrap().volume, 840.0); + assert_eq!(measure(&b).unwrap().volume, before); } #[test] @@ -357,29 +331,14 @@ fn fillet_max_finds_the_largest_radius_that_works() { let b = box_solid(Vec3::new(14.0, 0.0, 0.0), Vec3::new(28.0, 6.0, 10.0)).unwrap(); let mids = [Vec3::new(14.0, 0.0, 5.0), Vec3::new(28.0, 0.0, 5.0), Vec3::new(14.0, 6.0, 5.0), Vec3::new(28.0, 6.0, 5.0)]; assert!(too_large(&b, &mids, 3.5)); - let (r, body) = fillet_max(&b, &mids, 3.5).unwrap(); + let (r, body) = fillet_max(&b, &mids, 3.5, FilletTurn::Mitre).unwrap().unwrap(); assert_eq!(r, 3.0); assert!(rel(measure(&body).unwrap().volume, 840.0 - (4.0 - PI) * 90.0) < 2e-4); - // A 2 mm disc's top edge: up to 2 (the wall used up). - let disc = cylinder(Vec3::ZERO, Vec3::Z, 13.0, 2.0).unwrap(); - let top = [Vec3::new(0.0, 13.0, 2.0), Vec3::new(0.0, -13.0, 2.0)]; - assert!(too_large(&disc, &top, 2.5)); - assert_eq!(fillet_max(&disc, &top, 2.5).map(|x| x.0), Some(2.0)); - // Walls of different heights: at the shortest one's height only that wall would be used up, - // which is refused, so the largest radius is just below it (to the search's 3 digits). - let notched = boolean( - &box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(), - &box_solid(Vec3::new(35.0, -1.0, -1.0), Vec3::new(41.0, 5.0, 3.0)).unwrap(), - BoolOp::Cut, - ) - .unwrap() - .unwrap(); - let outline = [Vec3::new(20.0, 0.0, 10.0), Vec3::new(40.0, 15.0, 10.0), Vec3::new(20.0, 30.0, 10.0), Vec3::new(0.0, 15.0, 10.0)]; - assert!(too_large(¬ched, &outline, 8.0)); - let (r, _) = fillet_max(¬ched, &outline, 8.0).unwrap(); - assert!((r - 6.999).abs() < 1e-9, "{r}"); - // No edge there: no radius. - assert!(fillet_max(&b, &[Vec3::new(500.0, 0.0, 5.0)], 1.0).is_none()); + // No edge there: the fillet's own error, not a smaller radius (only a refusal as too large + // narrows the search). + let e = fillet(&b, &[Vec3::new(500.0, 0.0, 5.0)], 1.0).unwrap_err(); + assert!(!matches!(e, KernelError::TooLarge(_)), "{e}"); + assert_eq!(fillet_max(&b, &[Vec3::new(500.0, 0.0, 5.0)], 1.0, FilletTurn::Mitre).unwrap_err().to_string(), e.to_string()); } /// Edges that share no face get their own largest radius: a 2 mm fin's top edge takes at most @@ -396,43 +355,61 @@ fn fillet_max_each_reduces_only_where_the_radius_does_not_fit() { .unwrap() .unwrap(); let edges = [Vec3::new(21.0, 15.0, 30.0), Vec3::new(40.0, 0.0, 10.0)]; - assert!(matches!(fillet(&body, &edges, 4.0), Err(KernelError::TooLarge(_)))); - let (one, _) = fillet_max(&body, &edges, 4.0).unwrap(); - let (radii, b) = fillet_max_each(&body, &edges, 4.0).unwrap(); - assert_eq!(radii.get(1), Some(&4.0), "{radii:?}"); - let fin_r = radii.first().copied().unwrap(); - assert!(fin_r < 4.0 && (fin_r - one).abs() < 1e-9, "{radii:?}, one radius {one}"); + // R4 on the fin's top edge runs over the fin's 2 mm top, past its far edge (a cliff): it is + // cut as if the top went on, so both edges take 4. The fin's section loses the 4 x 4 square + // at its edge less the quarter disc about (17, 26), inside the fin (x >= 19): 2 x 4 less the + // disc's part, in closed form; the corner's round (1 − π/4)·16 along 20. + let both = fillet(&body, &edges, 4.0).unwrap(); + let (radii, b) = fillet_max_each(&body, &edges, 4.0, FilletTurn::Mitre).unwrap().unwrap(); + assert_eq!(radii, vec![4.0, 4.0], "{radii:?}"); assert!(b.validity().is_empty(), "{:?}", b.validity()); - // Each round takes (1 − π/4)·r² along its edge: the fin's 30 long, the corner's 20. - let removed = (1.0 - PI / 4.0) * (fin_r * fin_r * 30.0 + 16.0 * 20.0); - assert!(rel(measure(&b).unwrap().volume, block + fin - removed) < 2e-4); + let disc = |a: f64| 0.5 * (a * (16.0 - a * a).max(0.0).sqrt() + 16.0 * (a / 4.0).asin()); + let fin_section = 2.0 * 4.0 - (disc(4.0) - disc(2.0)); + let removed = fin_section * 30.0 + (1.0 - PI / 4.0) * 16.0 * 20.0; + assert!(rel(measure(&both).unwrap().volume, block + fin - removed) < 1e-6, "{}", measure(&both).unwrap().volume); + assert!(rel(measure(&b).unwrap().volume, block + fin - removed) < 1e-6); // The post's four edges limit each other: one radius, as `fillet_max`. let post = box_solid(Vec3::new(14.0, 0.0, 0.0), Vec3::new(28.0, 6.0, 10.0)).unwrap(); let mids = [Vec3::new(14.0, 0.0, 5.0), Vec3::new(28.0, 0.0, 5.0), Vec3::new(14.0, 6.0, 5.0), Vec3::new(28.0, 6.0, 5.0)]; - assert_eq!(fillet_max_each(&post, &mids, 3.5).map(|x| x.0), Some(vec![3.0; 4])); + assert_eq!(fillet_max_each(&post, &mids, 3.5, FilletTurn::Mitre).unwrap().map(|x| x.0), Some(vec![3.0; 4])); +} + +/// R21 on an edge of a 20 mm cube overflows on its tangent sides, which a round may, taking all +/// of both faces beside the edge: its circle about (y, z) = (21, 21) meets them only at 21, past +/// the cube. What is left is the square [0, 20]² inside that circle, with u = 21 − y, +/// ∫₁^√440 (√(441 − u²) − 1) du, along 20: 6107.529370. +fn round_wider_than_its_faces() -> f64 { + let f = |u: f64| 0.5 * (u * (441.0 - u * u).sqrt() + 441.0 * (u / 21.0).asin()); + let w = 440f64.sqrt(); + 20.0 * (f(w) - f(1.0) - (w - 1.0)) } -/// A corner's rounds too large for its faces are refused as too large, so a fit can reduce -/// them, also where only the corner build finds it (the edge-by-edge blend failing otherwise). #[test] -fn corner_rounds_larger_than_their_faces_are_too_large() { - let (l, eps) = (20.0, 1e-9); - let b = box_solid(Vec3::ZERO, Vec3::new(l, l, l)).unwrap(); +fn a_round_wider_than_its_faces_overflows_onto_its_tangent_sides() { + let want = round_wider_than_its_faces(); + assert!((want - 6107.529370).abs() < 1e-6, "{want}"); + let b = box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); + let out = fillet(&b, &[Vec3::new(10.0, 0.0, 0.0)], 21.0).unwrap(); + assert!(out.validity().is_empty(), "{:?}", out.validity()); + assert!(rel(measure(&out).unwrap().volume, want) < 1e-9, "{} vs {want}", measure(&out).unwrap().volume); +} + +/// A corner's rounds with a radius per edge, one wider than its faces: R21 with R5 on the other +/// two edges at the corner. The R21 overflows, so it goes first; it takes both faces beside its +/// edge, and with them the R5 edges, which lie on them and are gone: the body is R21's alone +/// ([`a_round_wider_than_its_faces_overflows_onto_its_tangent_sides`]). (The same corner at one +/// radius as wide as the faces, and its fit, are the rig's +/// fillets/477-fillet-cube-corner-rounds-as-wide-as-faces-* cases; no command takes a radius per +/// edge.) +#[test] +fn a_corner_round_wider_than_its_faces_overflows_and_takes_the_corners_other_edges() { + let b = box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); let corner = [Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 0.0, 10.0)]; - // As wide as the faces: the first edge's round uses up its neighbour, then the edge-by-edge - // blend can't find it; the corner build is what says the radius is too large. - let e = fillet(&b, &corner, l).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); - let (r, body) = fillet_max(&b, &corner, l).unwrap(); - assert!((r - 19.99).abs() < eps, "{r}"); - assert!(body.validity().is_empty(), "{:?}", body.validity()); - // Three rounds along the edges past the corner cube, and the cube less its sphere octant. - let removed = 3.0 * (1.0 - PI / 4.0) * r * r * (l - r) + r * r * r * (1.0 - PI / 6.0); - assert!(rel(measure(&body).unwrap().volume, l * l * l - removed) < 2e-4); - // Different radii per edge, one wider than its faces. let sel: Vec<(Vec3, f64)> = corner.iter().copied().zip([21.0, 5.0, 5.0]).collect(); - let e = crate::blend_corner::fillet_radii(&b, &sel).unwrap_err(); - assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); + let out = crate::blend_corner::fillet_radii(&b, &sel).unwrap(); + assert!(out.validity().is_empty(), "{:?}", out.validity()); + let want = round_wider_than_its_faces(); + assert!(rel(measure(&out).unwrap().volume, want) < 1e-9, "{} vs {want}", measure(&out).unwrap().volume); } #[test] @@ -442,7 +419,7 @@ fn tapered_extrudes() { outer: Loop2::polygon(&[Vec2::new(-20.0, -20.0), Vec2::new(20.0, -20.0), Vec2::new(20.0, 20.0), Vec2::new(-20.0, 20.0)]), holes: vec![], }; - let b = extrude_tapered(&Plane::XY, &sq, 30.0, 1.0, 10f64.to_radians()).unwrap(); + let b = extrude_tapered(&Plane::XY, &sq, 30.0, 1.0, 10f64.to_radians(), crate::DraftCorner::default()).unwrap(); let top = 40.0 + 2.0 * 30.0 * 10f64.to_radians().tan(); let v = 30.0 / 3.0 * (1600.0 + top * top + 40.0 * top); let m = measure(&b).unwrap(); @@ -450,17 +427,34 @@ fn tapered_extrudes() { assert_eq!(m.merged.faces, 6); // Inward taper on a circle (a cone frustum), downward. let c = Region2 { outer: Loop2::circle(Vec2::ZERO, 10.0), holes: vec![] }; - let b = extrude_tapered(&Plane::XY, &c, 10.0, -1.0, -20f64.to_radians()).unwrap(); + let b = extrude_tapered(&Plane::XY, &c, 10.0, -1.0, -20f64.to_radians(), crate::DraftCorner::default()).unwrap(); let r2 = 10.0 - 10.0 * 20f64.to_radians().tan(); let v = PI * 10.0 / 3.0 * (100.0 + r2 * r2 + 10.0 * r2); let m = measure(&b).unwrap(); assert!(rel(m.volume, v) < 5e-4, "{} vs {v}", m.volume); assert!(m.bbox.max.z < 1e-6 && m.bbox.min.z > -10.0 - 1e-6, "{:?}", m.bbox); - assert!(extrude_tapered(&Plane::XY, &c, 10.0, 1.0, -60f64.to_radians()).is_err(), "closes the profile"); + assert!(extrude_tapered(&Plane::XY, &c, 10.0, 1.0, -60f64.to_radians(), crate::DraftCorner::default()).is_err(), "closes the profile"); + // The square with a 10 × 10 square hole, 30 up, 5° inward: every wall leans in toward the + // material's outside, so the outer frustum narrows and the hole's widens; the solid is the + // one frustum less the other, with each wall a face of its own (four out, four in, two caps). + let t = 5f64.to_radians().tan(); + let hole = Loop2::polygon(&[Vec2::new(-5.0, -5.0), Vec2::new(-5.0, 5.0), Vec2::new(5.0, 5.0), Vec2::new(5.0, -5.0)]); + let ring = Region2 { outer: sq.outer.clone(), holes: vec![hole] }; + let b = extrude_tapered(&Plane::XY, &ring, 30.0, 1.0, -5f64.to_radians(), crate::DraftCorner::default()).unwrap(); + let frustum = |a0: f64, a1: f64| 30.0 / 3.0 * (a0 * a0 + a1 * a1 + a0 * a1); + let v = frustum(40.0, 40.0 - 60.0 * t) - frustum(10.0, 10.0 + 60.0 * t); + let m = measure(&b).unwrap(); + assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume); + assert_eq!(m.merged.faces, 10); + // At 30° the hole would grow past the outer wall: refused, saying why. + let e = extrude_tapered(&Plane::XY, &ring, 30.0, 1.0, -30f64.to_radians(), crate::DraftCorner::default()).unwrap_err(); + assert!(e.to_string().contains("hole"), "{e}"); } /// A slot (two lines and two half-circles, tangent) tapered inward: every edge moves in by -/// d = z · tan 8°, so A(d) = A₀ − P·d + π·d² (#546). An arc meeting a line at a corner is refused. +/// d = z · tan 8°, so A(d) = A₀ − P·d + π·d² (#546). A quarter disc, its arc meeting the lines at +/// corners, tapered outward: each wall continues as itself, so the section at d is the disc of +/// radius r + d over x ≥ −d, y ≥ −d. #[test] fn tapered_extrude_of_lines_and_arcs() { let (r, l, h, a) = (5.0, 20.0, 12.0, 8f64.to_radians()); @@ -472,7 +466,7 @@ fn tapered_extrude_of_lines_and_arcs() { Seg2::Arc { center: Vec2::ZERO, radius: r, start: PI / 2.0, sweep: PI }, ], }; - let b = extrude_tapered(&Plane::XY, &Region2 { outer: slot, holes: vec![] }, h, 1.0, -a).unwrap(); + let b = extrude_tapered(&Plane::XY, &Region2 { outer: slot, holes: vec![] }, h, 1.0, -a, crate::DraftCorner::default()).unwrap(); let (a0, p, t) = (2.0 * r * l + PI * r * r, 2.0 * l + 2.0 * PI * r, a.tan()); let v = a0 * h - p * t * h * h / 2.0 + PI * t * t * h.powi(3) / 3.0; let m = measure(&b).unwrap(); @@ -486,8 +480,34 @@ fn tapered_extrude_of_lines_and_arcs() { Seg2::Line { a: Vec2::new(0.0, r), b: Vec2::ZERO }, ], }; - let e = extrude_tapered(&Plane::XY, &Region2 { outer: quarter, holes: vec![] }, h, 1.0, a).unwrap_err(); - assert!(e.to_string().contains("arc meets another edge at a corner"), "{e}"); + let b = extrude_tapered(&Plane::XY, &Region2 { outer: quarter, holes: vec![] }, h, 1.0, a, crate::DraftCorner::default()).unwrap(); + // The section's area: under the circle of radius R = r + d down to y = −d from x = −d to + // x₁, where the circle meets y = −d, then the whole circle's width out to x = R; + // F(x) = ∫ √(R² − x²) dx. + let section = |d: f64| { + let big = r + d; + let f = |x: f64| 0.5 * (x * (big * big - x * x).max(0.0).sqrt() + big * big * (x / big).clamp(-1.0, 1.0).asin()); + let x1 = (big * big - d * d).sqrt(); + f(x1) - f(-d) + d * (x1 + d) + 2.0 * (f(big) - f(x1)) + }; + // Gauss–Legendre on 8 nodes over each of 16 pieces of the height: the area is smooth in d. + let (nodes, weights) = ( + [0.183_434_642_495_649_8, 0.525_532_409_916_329, 0.796_666_477_413_626_7, 0.960_289_856_497_536_3], + [0.362_683_783_378_362, 0.313_706_645_877_887_3, 0.222_381_034_453_374_5, 0.101_228_536_290_376_3], + ); + let pieces = 16; + let v: f64 = (0..pieces) + .map(|k| { + let (z0, dz) = (k as f64 * h / pieces as f64, h / pieces as f64); + let mid = z0 + 0.5 * dz; + nodes.iter().zip(weights).map(|(x, w)| w * (section((mid - 0.5 * dz * x) * t) + section((mid + 0.5 * dz * x) * t))).sum::() + * 0.5 + * dz + }) + .sum(); + let m = measure(&b).unwrap(); + assert!(rel(m.volume, v) < 1e-6, "quarter disc: {} vs {v}", m.volume); + assert_eq!(m.merged.faces, 5, "quarter disc: bottom, top, two flat walls and the cone"); } /// A circle with a lobe on each side (four arcs of three circles, meeting at corners: the outline of @@ -511,7 +531,7 @@ fn tapered_extrude_of_arcs_meeting_at_corners() { Seg2::Arc { center: Vec2::new(c, 0.0), radius: w0, start: at(c, x, -y), sweep: 2.0 * at(c, x, y) }, ], }; - let b = extrude_tapered(&Plane::XY, &Region2 { outer: lobed, holes: vec![] }, h, -1.0, -a).unwrap(); + let b = extrude_tapered(&Plane::XY, &Region2 { outer: lobed, holes: vec![] }, h, -1.0, -a, crate::DraftCorner::default()).unwrap(); // Union of the circle and two lobes: the circle plus each lobe less its lens with the circle. let area = |d: f64| { let (r, w) = (r0 - d, w0 - d); @@ -543,7 +563,7 @@ fn tapered_extrude_of_conics() { Seg2::Conic { a: p(0.0, -r), apex: p(r, -r), b: p(r, 0.0), w }, ], }; - let b = extrude_tapered(&Plane::XY, &Region2 { outer: disc, holes: vec![] }, h, 1.0, -a).unwrap(); + let b = extrude_tapered(&Plane::XY, &Region2 { outer: disc, holes: vec![] }, h, 1.0, -a, crate::DraftCorner::default()).unwrap(); let r1 = r - h * a.tan(); let v = PI * h / 3.0 * (r * r + r1 * r1 + r * r1); let m = measure(&b).unwrap(); @@ -569,62 +589,54 @@ fn tapered_extrude_of_cubics_is_close_to_the_true_offset() { ], }; let (area, perimeter) = (disc.signed_area().abs(), disc.segs.iter().map(|s| s.length()).sum::()); - let b = extrude_tapered(&Plane::XY, &Region2 { outer: disc, holes: vec![] }, h, 1.0, -a).unwrap(); + let b = extrude_tapered(&Plane::XY, &Region2 { outer: disc, holes: vec![] }, h, 1.0, -a, crate::DraftCorner::default()).unwrap(); let t = a.tan(); let v = area * h - perimeter * t * h * h / 2.0 + PI * t * t * h.powi(3) / 3.0; let m = measure(&b).unwrap(); assert!(rel(m.volume, v) < 5e-4, "{} vs {v}", m.volume); } -/// An S-shaped cubic (one curve turning both ways) has no moved cubic close to its offset: it is -/// cut into pieces until each piece's moved curve stays within 2 % of the offset of the true -/// one (or 10 µm), both ways. -#[test] -fn a_tapered_s_curve_is_cut_into_pieces_that_follow_its_offset() { - let s_curve = Seg2::Cubic { p0: Vec2::new(0.0, 0.0), p1: Vec2::new(5.0, 10.0), p2: Vec2::new(10.0, -10.0), p3: Vec2::new(15.0, 0.0) }; - let d = 0.5; - assert!(crate::build::offset_error(&s_curve, d).unwrap() > 0.05 * d, "one piece is far off"); - let lp = Loop2 { - segs: vec![ - s_curve, - Seg2::Line { a: Vec2::new(15.0, 0.0), b: Vec2::new(15.0, -20.0) }, - Seg2::Line { a: Vec2::new(15.0, -20.0), b: Vec2::new(0.0, -20.0) }, - Seg2::Line { a: Vec2::new(0.0, -20.0), b: Vec2::new(0.0, 0.0) }, - ], - }; - let (cut, from) = crate::build::offset_splits(&lp, d); - let pieces: Vec<&Seg2> = cut.segs.iter().zip(&from).filter(|(_, i)| **i == 0).map(|(s, _)| s).collect(); - assert!(pieces.len() > 1 && from.iter().filter(|i| **i > 0).count() == 3, "{} pieces", pieces.len()); - for p in pieces { - for d in [d, -d] { - let e = crate::build::offset_error(p, d).unwrap(); - assert!(e <= crate::build::offset_tolerance(d) + 1e-9, "{e}"); - } - } -} - -/// A wedge whose tip is a flat line far shorter than the taper moves its sides in: the tip line -/// goes, the two long sides meet, and its side is the flat triangle up to there. The solid is a -/// prismatoid, its volume h/6 · (A₀ + 4·A_mid + A₁). +/// A wedge whose tip is a flat line far shorter than the taper moves its sides in: every wall, +/// the tip's too, leans by the taper, so the tip's wall is a triangle that closes where the two +/// long sides meet across it (z* ≈ 0.126 of h = 2), and above that the long sides meet each +/// other along a ridge. The section at height z is the profile's lines moved in by z·tan(a): a +/// quadrilateral below z*, a triangle above, each with an area quadratic in z, so the volume is +/// exact as Simpson's rule on each of the two pieces. #[test] fn tapered_extrude_swallows_a_short_tip() { let (h, a) = (2.0, 5f64.to_radians()); - let d = h * a.tan(); let pts = [Vec2::new(0.0, -2.0), Vec2::new(20.0, -0.01), Vec2::new(20.0, 0.01), Vec2::new(0.0, 2.0)]; - let b = extrude_tapered(&Plane::XY, &Region2 { outer: Loop2::polygon(&pts), holes: vec![] }, h, 1.0, -a).unwrap(); - // The top: the three long lines moved in by d (to their left, the loop running - // counter-clockwise), meeting each other. - let moved = |p: Vec2, q: Vec2| { - let t = (q - p).normalized().unwrap(); - (p + t.perp() * d, t) + let b = extrude_tapered(&Plane::XY, &Region2 { outer: Loop2::polygon(&pts), holes: vec![] }, h, 1.0, -a, crate::DraftCorner::default()).unwrap(); + // Side i (from pts[i] to the next) moved in by t (to its left, the loop running + // counter-clockwise), as a point and its direction. + let moved = |i: usize, t: f64| { + let (p, q) = (pts[i], pts[(i + 1) % pts.len()]); + let u = (q - p).normalized().unwrap(); + (p + u.perp() * t, u) }; let meet = |(p0, t0): (Vec2, Vec2), (p1, t1): (Vec2, Vec2)| p0 + t0 * ((p1 - p0).cross(t1) / t0.cross(t1)); - let (low, high, left) = (moved(pts[0], pts[1]), moved(pts[2], pts[3]), moved(pts[3], pts[0])); - let top = [meet(left, low), meet(low, high), meet(high, left)]; - let area = |q: &[Vec2]| solidcraft_geom::Ring::from(q.to_vec()).signed_area(); - // Halfway up, each side edge's midpoint (the two tip corners both run to the top's tip). - let mid = [pts[0].lerp(top[0], 0.5), pts[1].lerp(top[1], 0.5), pts[2].lerp(top[1], 0.5), pts[3].lerp(top[2], 0.5)]; - let v = h / 6.0 * (area(&pts) + 4.0 * area(&mid) + area(&top)); + // Where the long sides meet, measured off the moved tip line (into the solid positive): it + // runs linearly with t, and its root is the offset at which the tip's wall closes. + let past_tip = |t: f64| { + let (q, u) = moved(1, t); + (meet(moved(0, t), moved(2, t)) - q).cross(u) + }; + let d = h * a.tan(); + let closes = d * past_tip(0.0) / (past_tip(0.0) - past_tip(d)); + let z_closes = closes / a.tan(); + assert!(z_closes > 0.0 && z_closes < h, "the tip's wall closes partway up, at {z_closes}"); + let section = |z: f64| -> Vec { + let t = z * a.tan(); + if t <= closes { + (0..4).map(|i| meet(moved((i + 3) % 4, t), moved(i, t))).collect() + } else { + let (low, high, left) = (moved(0, t), moved(2, t), moved(3, t)); + vec![meet(left, low), meet(low, high), meet(high, left)] + } + }; + let area = |z: f64| solidcraft_geom::Ring::from(section(z)).signed_area(); + let simpson = |z0: f64, z1: f64| (z1 - z0) / 6.0 * (area(z0) + 4.0 * area(0.5 * (z0 + z1)) + area(z1)); + let v = simpson(0.0, z_closes) + simpson(z_closes, h); let m = measure(&b).unwrap(); assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume); assert_eq!(m.merged.faces, 6, "bottom, top, three sides and the tip's triangle"); @@ -640,7 +652,7 @@ fn tapered_extrude_between_with_a_foot() { holes: vec![], }; let (from, to, foot) = (-2.0, 10.0, 0.5); - let b = extrude_tapered_between(&Plane::XY, &sq, from, to, foot, 1.0, a).unwrap(); + let b = extrude_tapered_between(&Plane::XY, &sq, from, to, foot, 1.0, a, crate::DraftCorner::default()).unwrap(); let side = |z: f64| 40.0 + 2.0 * z * a.tan(); let (s0, s1, rise) = (side(from), side(to), to - from - foot); let v = foot * s0 * s0 + rise / 3.0 * (s0 * s0 + s1 * s1 + s0 * s1); @@ -648,13 +660,17 @@ fn tapered_extrude_between_with_a_foot() { assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume); assert!((m.bbox.min.z - from).abs() < 1e-6 && (m.bbox.max.z - to).abs() < 1e-6, "{:?}", m.bbox); assert_eq!(m.merged.faces, 10); - assert!(extrude_tapered_between(&Plane::XY, &sq, from, to, 7.0, 1.0, a).is_err(), "a foot taller than half the solid"); + assert!( + extrude_tapered_between(&Plane::XY, &sq, from, to, 7.0, 1.0, a, crate::DraftCorner::default()).is_err(), + "a foot taller than half the solid" + ); } -/// A taper steeper than a profile's details is refused, and says why: a slot narrower than the -/// taper closes; a ring's hole smaller than it closes. +/// A taper steeper than a profile's details: a slot narrower than the taper closes partway up +/// and the solid builds, the slot's walls meeting above where its end wall closes to a point; a +/// ring's hole smaller than the taper closes the whole hole and is refused, saying why. #[test] -fn tapered_extrude_refuses_a_taper_steeper_than_the_details() { +fn tapered_extrude_closes_a_narrow_slot_and_refuses_a_closing_hole() { let slot = Loop2::polygon(&[ Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), @@ -665,10 +681,20 @@ fn tapered_extrude_refuses_a_taper_steeper_than_the_details() { Vec2::new(4.9, 10.0), Vec2::new(0.0, 10.0), ]); - let e = extrude_tapered(&Plane::XY, &Region2 { outer: slot, holes: vec![] }, 2.0, 1.0, 10f64.to_radians()).unwrap_err(); - assert!(e.to_string().contains("the taper closes the profile"), "{e}"); + let a = 10f64.to_radians(); + let b = extrude_tapered(&Plane::XY, &Region2 { outer: slot, holes: vec![] }, 2.0, 1.0, a, crate::DraftCorner::default()).unwrap(); + assert!(b.validity().is_empty(), "{:?}", b.validity()); + // Every wall moves out of the material by z·t at height z (t = tan 10°): the 10 mm square + // grows to 10 + 2zt, so the solid without the slot is ∫₀² (10 + 2zt)² dz + // = ((10 + 4t)³ − 1000) / (6t). The slot narrows to 0.2 − 2zt, its length staying 8 (its end + // wall and the square's side both move up by zt), and it closes at z = 0.1/t (0.567, below + // the top): it takes ∫ 8 (0.2 − 2zt) dz over 0..0.1/t = 0.08/t. + let t = a.tan(); + let v = ((10.0 + 4.0 * t).powi(3) - 1000.0) / (6.0 * t) - 0.08 / t; + let m = measure(&b).unwrap(); + assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume); let ring = Region2 { outer: Loop2::circle(Vec2::ZERO, 5.0), holes: vec![Loop2::circle(Vec2::ZERO, 0.3).reversed()] }; - let e = extrude_tapered(&Plane::XY, &ring, 2.0, 1.0, 10f64.to_radians()).unwrap_err(); + let e = extrude_tapered(&Plane::XY, &ring, 2.0, 1.0, 10f64.to_radians(), crate::DraftCorner::default()).unwrap_err(); assert!(e.to_string().contains("the taper closes the profile"), "{e}"); } @@ -701,9 +727,11 @@ fn loft_and_sweep() { let sq = Loop2::polygon(&[Vec2::new(-20.0, -20.0), Vec2::new(20.0, -20.0), Vec2::new(20.0, 20.0), Vec2::new(-20.0, 20.0)]); let top = Plane::XY.offset(40.0); let l = loft(&[(Plane::XY, sq), (top, Loop2::circle(Vec2::ZERO, 10.0))]).unwrap(); - let m = measure(&l).unwrap(); - println!("loft volume {} faces {:?}", m.volume, m.merged); - assert!(m.volume > 314.0 * 40.0 && m.volume < 1600.0 * 40.0); + // Ruled, each side on the rational quarter of the circle between its corners' directions: the + // section at t has area (1 − t)² A_S + t² A_C + t(1 − t) M, M = ½∮(S × C' + C × S'), so + // V = h (A_S/3 + A_C/3 + M/6) = 35080.725 (M = 1433.790 by quadrature; tests/oracle/17-loft). + let v = measure(&l).unwrap().volume; + assert!(rel(v, 35080.725116) < 1e-6, "{v}"); // A tube: up 30, quarter bend of radius 20, across 30. let disc = Region2 { outer: Loop2::circle(Vec2::ZERO, 3.0), holes: vec![] }; let path = [ @@ -717,9 +745,6 @@ fn loft_and_sweep() { PathSeg::Line { a: Vec3::new(20.0, 0.0, 50.0), b: Vec3::new(50.0, 0.0, 50.0) }, ]; let t = sweep(&Plane::XY, &disc, &path).unwrap(); - for tol in [0.1, 0.01, 0.003, 0.001] { - println!("tube tess {tol}: {}", t.tessellate(tol).unwrap().measure().volume); - } let area = PI * 9.0; let expect = area * (30.0 + 30.0 + 20.0 * std::f64::consts::FRAC_PI_2); assert!(rel(measure(&t).unwrap().volume, expect) < 1e-3, "{} vs {expect}", measure(&t).unwrap().volume); @@ -750,7 +775,13 @@ fn moving_a_body_with_an_intersection_curve_edge_ends() { let block = box_solid(Vec3::new(-20.0, -20.0, 20.0), Vec3::new(20.0, 20.0, 60.0)).unwrap(); let block = crate::ops::transform(&block, Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::X, 0.4).unwrap(); let cut = boolean(&cyl, &block, BoolOp::Cut).unwrap().unwrap(); - assert!(cut.solid.edge_iter().any(|e| matches!(e.curve(), truck_modeling::Curve::IntersectionCurve(_)))); + // The ellipse where the tilted plane meets the cylinder is an edge of its own. + assert!( + cut.record() + .edges + .iter() + .any(|e| !matches!(e.curve, solidcore_record::brep::Curve::Line { .. } | solidcore_record::brep::Curve::Circle { .. })) + ); let t = Vec3::new(0.6911, -0.3337, -0.6127) * 2.334; let moved = crate::ops::transform(&cut, t, Vec3::ZERO, Vec3::Z, 0.0).unwrap(); let (v0, v1) = (measure(&cut).unwrap().volume, measure(&moved).unwrap().volume); @@ -791,10 +822,7 @@ fn drain_pads_flush_under_a_floor_with_a_hole() { // The ring's part inside the floor adds nothing: 5 mm of ring below it either way. let v_ring = PI * (400.0 - 100.0) * 5.0; for (z0, z1) in [(-5.0, 0.0), (-5.0, 2.0)] { - let (result, diagnostics) = capture_boolean_diagnostics(|| boolean(&floor, &ring(z0, z1), BoolOp::Union)); - let u = result.unwrap().unwrap(); - assert!(diagnostics.events.iter().any(|event| event.strategy == BooleanStrategy::CommonBore), "{diagnostics:?}"); - assert!(diagnostics.events.iter().all(|event| event.translation_mm.is_finite() && event.face_shift_mm.is_finite())); + let u = boolean(&floor, &ring(z0, z1), BoolOp::Union).unwrap().unwrap(); let v = measure(&u).unwrap().volume; assert!(rel(v, v_floor + v_ring) < 2e-5, "ring {z0}..{z1}: {v} vs {}", v_floor + v_ring); assert!(u.validity().is_empty(), "{:?}", u.validity()); @@ -878,13 +906,10 @@ fn planar_booleans_with_coincident_faces() { // L-bracket: a wall flush with three sides of its base. let base = box_solid(Vec3::ZERO, Vec3::new(80.0, 50.0, 8.0)).unwrap(); let wall = box_solid(Vec3::new(0.0, 42.0, 8.0), Vec3::new(80.0, 50.0, 50.0)).unwrap(); - let u = planar_boolean(&base, &wall, BoolOp::Union).unwrap().unwrap(); - let m = measure(&u).unwrap(); + let u2 = boolean(&base, &wall, BoolOp::Union).unwrap().unwrap(); + let m = measure(&u2).unwrap(); assert!(rel(m.volume, 80.0 * 50.0 * 8.0 + 80.0 * 8.0 * 42.0) < 1e-9, "{}", m.volume); assert_eq!(m.merged.faces, 8, "{:?}", m.merged); - // Through the public boolean (B-rep first, polygon fallback). - let u2 = boolean(&base, &wall, BoolOp::Union).unwrap().unwrap(); - assert!(rel(measure(&u2).unwrap().volume, m.volume) < 1e-9); assert_eq!(u2.face_count(), 8, "coplanar wall and base faces must merge in the B-rep"); assert!(u2.validity().is_empty()); // Two boxes sharing a face, and a cut flush with a side. @@ -900,38 +925,6 @@ fn planar_booleans_with_coincident_faces() { assert!(rel(measure(&i).unwrap().volume, 250.0) < 1e-9); } -/// The planar fallback runs after any failed B-rep boolean, not only on coincident faces; when -/// it can't run it says which body has which curved faces (it used to blame "coincident faces -/// on curved bodies" whatever the cause). -#[test] -fn planar_fallback_names_the_curved_faces() { - let slab = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(); - let pad = cylinder(Vec3::new(20.0, 15.0, 5.0), Vec3::Z, 8.0, 10.0).unwrap(); - let e = planar_boolean(&slab, &pad, BoolOp::Union).unwrap_err().to_string(); - assert!(e.contains("not supported yet"), "{e}"); - assert!(e.contains("the tool has 2 curved faces (cylinder)"), "{e}"); - assert!(!e.contains("target"), "{e}"); - assert!(!e.contains("coincident faces on curved bodies"), "{e}"); - let ball = sphere(Vec3::new(20.0, 15.0, 10.0), 5.0).unwrap(); - let e = planar_boolean(&ball, &pad, BoolOp::Cut).unwrap_err().to_string(); - assert!(e.contains("the target has 6 curved faces (sphere) and the tool has 2 curved faces (cylinder)"), "{e}"); - // All-planar bodies, a face of one at a shallow angle (1°): the fallback takes them. - let slope = Vec3::new(-1f64.to_radians().tan(), 0.0, 1.0).normalized().unwrap(); - let wedge = convex_polyhedron(&[ - HalfSpace { n: Vec3::X, d: 30.0 }, - HalfSpace { n: -Vec3::X, d: -10.0 }, - HalfSpace { n: Vec3::Y, d: 20.0 }, - HalfSpace { n: -Vec3::Y, d: -10.0 }, - HalfSpace { n: -Vec3::Z, d: -5.0 }, - HalfSpace { n: slope, d: slope.dot(Vec3::new(10.0, 0.0, 11.0)) }, - ]) - .unwrap(); - let u = planar_boolean(&slab, &wedge, BoolOp::Union).unwrap().unwrap(); - let above = box_solid(Vec3::new(0.0, 0.0, 10.0), Vec3::new(40.0, 30.0, 20.0)).unwrap(); - let expect = 40.0 * 30.0 * 10.0 + measure(&boolean(&wedge, &above, BoolOp::Intersect).unwrap().unwrap()).unwrap().volume; - assert!(rel(measure(&u).unwrap().volume, expect) < 1e-6, "{} vs {expect}", measure(&u).unwrap().volume); -} - #[test] fn connected_logo_join_preserves_exact_faces_at_edge_contact() { let mut body = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 10.0)).unwrap(); @@ -1007,13 +1000,16 @@ fn sphere_booleans() { let s = sphere(Vec3::ZERO, 15.0).unwrap(); let m = measure(&s).unwrap(); assert!(rel(m.volume, 4.0 / 3.0 * PI * 3375.0) < 1e-3, "{}", m.volume); - assert_eq!((m.merged.faces, m.merged.edges), (1, 0)); + // One spherical face, closed along its seam from pole to pole. + assert_eq!((m.merged.faces, m.merged.edges), (1, 1)); // A ball cut out of the top face of a slab (oracle 14). let b = box_solid(Vec3::new(-25.0, -25.0, -20.0), Vec3::new(25.0, 25.0, 0.0)).unwrap(); let c = boolean(&b, &s, BoolOp::Cut).unwrap().unwrap(); let m = measure(&c).unwrap(); assert!(rel(m.volume, 50.0 * 50.0 * 20.0 - 2.0 / 3.0 * PI * 3375.0) < 1e-3, "{}", m.volume); - assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (7, 13, 9)); + // The box's 6 faces and the sphere's; its 12 edges, the rim circle and the sphere's seam down + // to its pole; its 8 corners, the rim's vertex and the pole. + assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (7, 14, 10)); } #[test] @@ -1027,102 +1023,6 @@ fn similar_spheres_meet() { } } -#[test] -#[ignore] -fn debug_convergence() { - let b = extrude(&Plane::XY, &[Region2 { outer: Loop2::circle(Vec2::ZERO, 15.0), holes: vec![] }], 0.0, 50.0).unwrap().pop().unwrap(); - for t in [0.1, 0.05, 0.02, 0.01, 0.005, 0.002] { - let m = b.tessellate(t).unwrap(); - let mm = m.measure(); - println!("tol {t}: tris {} vol {} err {:.3e}", m.triangles.len(), mm.volume, mm.volume / (PI * 225.0 * 50.0) - 1.0); - } - let m = b.tessellate(0.05).unwrap(); - for f in 0..4u32 { - let ns: Vec = - m.triangles.iter().zip(&m.tri_face).filter(|(_, ff)| **ff == f).flat_map(|(t, _)| t.iter().map(|k| m.normals[*k as usize])).collect(); - println!("face {f}: {} normals, first {:?}, max |n.z| {}", ns.len(), ns.first(), ns.iter().map(|n| n.z.abs()).fold(0.0, f64::max)); - } -} - -#[test] -#[ignore] -fn debug_coplanar() { - let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); - for (z0, z1) in [(0.0, 20.0), (-5.0, 20.0), (0.0, 25.0), (-5.0, 25.0), (5.0, 20.0), (5.0, 25.0)] { - let c = cylinder(Vec3::new(20.0, 15.0, z0), Vec3::Z, 5.0, z1 - z0).unwrap(); - let r = boolean(&b, &c, BoolOp::Cut); - println!("cut z {z0}..{z1}: {:?}", r.map(|o| o.map(|b| measure(&b).unwrap().volume))); - let r = boolean(&b, &c, BoolOp::Union); - println!("union z {z0}..{z1}: {:?}", r.map(|o| o.map(|b| measure(&b).unwrap().volume))); - } - let r = - Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), Vec2::new(40.0, 30.0), Vec2::new(0.0, 30.0)]), holes: vec![] }; - for ang in [PI / 2.0, PI, 1.5 * PI, 2.0 * PI] { - let q = revolve(&Plane::XY, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, ang).unwrap().pop().unwrap(); - let m = measure(&q).unwrap(); - println!("revolve {ang}: vol {} expect {} faces {}", m.volume, ang / 2.0 * 1600.0 * 30.0, m.faces); - } -} - -#[test] -#[ignore] -fn debug_blind() { - let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); - let t = box_solid(Vec3::new(10.0, 10.0, 5.0), Vec3::new(20.0, 20.0, 25.0)).unwrap(); - println!("box pocket: {:?}", boolean(&b, &t, BoolOp::Cut).map(|o| o.map(|b| measure(&b).unwrap().volume))); - let t = box_solid(Vec3::new(10.0, 10.0, 5.0), Vec3::new(20.0, 20.0, 15.0)).unwrap(); - println!("box void: {:?}", boolean(&b, &t, BoolOp::Cut).map(|o| o.map(|b| measure(&b).unwrap().volume))); - for r in [5.0, 4.3] { - for z in [5.0, 7.3, 13.1] { - let c = cylinder(Vec3::new(20.3, 15.1, z), Vec3::Z, r, 30.0).unwrap(); - println!("cyl r{r} z{z}: {:?}", boolean(&b, &c, BoolOp::Cut).map(|o| o.map(|b| measure(&b).unwrap().volume))); - } - } - let c = cylinder(Vec3::new(20.0, 15.0, 25.0), -Vec3::Z, 5.0, 20.0).unwrap(); - println!("cyl down: {:?}", boolean(&b, &c, BoolOp::Cut).map(|o| o.map(|b| measure(&b).unwrap().volume))); - let s = sphere(Vec3::new(20.0, 15.0, 20.0), 5.0).unwrap(); - println!("sphere: {:?}", boolean(&b, &s, BoolOp::Cut).map(|o| o.map(|b| measure(&b).unwrap().volume))); -} - -#[test] -#[ignore] -fn debug_revolve_doc_case() { - let r = - Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), Vec2::new(40.0, 30.0), Vec2::new(0.0, 30.0)]), holes: vec![] }; - for ang in [PI / 2.0, -PI / 2.0] { - let q = revolve(&Plane::XY, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, ang).unwrap().pop().unwrap(); - let m = measure(&q).unwrap(); - println!("ang {ang}: vol {} bbox {:?}", m.volume, m.bbox); - } - let r2 = Region2 { outer: r.outer.reversed(), holes: vec![] }; - let q = revolve(&Plane::XY, std::slice::from_ref(&r2), Vec2::ZERO, Vec2::Y, PI / 2.0).unwrap().pop().unwrap(); - println!("reversed: {}", measure(&q).unwrap().volume); -} - -#[test] -#[ignore] -fn debug_coplanar_union_rate() { - let a = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 20.0)).unwrap(); - let b = extrude(&Plane::XY, &[Region2 { outer: Loop2::circle(Vec2::new(40.0, 20.0), 12.0), holes: vec![] }], 0.0, 40.0).unwrap().pop().unwrap(); - let mut ok = 0; - for i in 0..20 { - let sh = Vec3::new(0.0137 * i as f64, 0.0291 * i as f64, -0.0173 * i as f64); - let (a2, b2) = (transform(&a, sh, Vec3::ZERO, Vec3::Z, 0.0).unwrap(), transform(&b, sh, Vec3::ZERO, Vec3::Z, 0.0).unwrap()); - for tol in [1e-3, 1e-2, 5e-2] { - let r = guard("t", || { - let (sa, sb) = (a2.deep_copy(), b2.deep_copy()); - Ok(truck_shapeops::or(&sa, &sb, tol)) - }); - let good = matches!(r, Ok(Some(_))); - if good { - ok += 1; - } - println!("shift {i} tol {tol}: {}", if good { "ok" } else { "fail" }); - } - } - println!("ok {ok}/60"); -} - #[test] fn chamfer_top_loop_mitres() { let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); @@ -1152,262 +1052,82 @@ fn chamfer_sloped_basin_rim() { assert_eq!(after.merged.faces, before.merged.faces + 1); assert_eq!(result.lumps().unwrap().len(), 1); assert!(result.validity().is_empty()); - let mesh = result.tessellate(0.01).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!(!mesh.contains(Vec3::new(50.0, 3.5, 29.9))); assert!(mesh.contains(Vec3::new(50.0, 3.5, 28.0))); } -#[test] -fn chamfer_wider_than_sloped_basin_rim_is_refused() { - for (margin, distance) in [(1.0, 2.0), (1.0, 3.0), (0.5, 4.0), (1.0, 1.0)] { - let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); - let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); - let pocket = - loft(&[(Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)), (Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0))]) - .unwrap(); - let basin = boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap(); - let before = measure(&basin).unwrap(); - let error = chamfer(&basin, &[Vec3::new(50.0, margin, 30.0)], distance).unwrap_err(); - assert!(error.to_string().contains("larger than the neighbouring faces"), "{margin}, {distance}: {error}"); - assert_eq!(measure(&basin).unwrap().volume, before.volume); - // A smaller chamfer on the same thin rim is still supported. - let smaller = chamfer(&basin, &[Vec3::new(50.0, margin, 30.0)], margin * 0.5).unwrap(); - assert!(smaller.validity().is_empty()); - assert!(measure(&smaller).unwrap().volume < before.volume); - } +/// `chamfer_sloped_basin_rim`'s basin with its front rim `margin` wide at the top. +fn sloped_basin(margin: f64) -> Body { + let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); + let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); + let pocket = + loft(&[(Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)), (Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0))]).unwrap(); + boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap() } -#[test] -#[ignore] -fn debug_chamfer_cut() { - let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); - // Prism along x: triangle in the YZ plane beyond the top-front edge. - let plane = Plane { origin: Vec3::new(-5.0, 0.0, 0.0), x: Vec3::Y, y: Vec3::Z }; - let tri = Loop2::polygon(&[Vec2::new(2.3, 20.3), Vec2::new(-0.3, 17.7), Vec2::new(10.0, 30.0)]); - let tri = if tri.signed_area() < 0.0 { tri.reversed() } else { tri }; - let tool = extrude(&plane, &[Region2 { outer: tri, holes: vec![] }], 0.0, 50.0).unwrap().pop().unwrap(); - println!("tool vol {}", measure(&tool).unwrap().volume); - let r = boolean(&b, &tool, BoolOp::Cut).unwrap().unwrap(); - let m = measure(&r).unwrap(); - println!("cut: {} faces {} {:?}", m.volume, m.faces, m.merged); - for f in r.faces(0.01).unwrap() { - println!("face {} area {:.3} c {:?} n {:?}", f.index, f.area, f.centroid, f.plane_normal); - } - for tol in [0.1, 0.01, 0.001] { - println!("tess {tol}: {}", r.tessellate(tol).unwrap().measure().volume); - } -} - -#[test] -#[ignore] -fn debug_revolved_hole_tool() { - let b = box_solid(Vec3::ZERO, Vec3::new(60.0, 40.0, 15.0)).unwrap(); - // Drill point profile in the XZ plane through x = 50: revolve about the vertical line x = 50. - let pl = Plane { origin: Vec3::new(50.0, 20.0, 0.0), x: Vec3::X, y: Vec3::Z }; - let r = 3.0; - let tip = r / 59f64.to_radians().tan(); - let prof = - Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 16.0), Vec2::new(0.0, 5.0 - tip), Vec2::new(r, 5.0), Vec2::new(r, 16.0)]), holes: vec![] }; - let tool = revolve(&pl, &[prof], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU).unwrap().pop().unwrap(); - println!("tool vol {}", measure(&tool).unwrap().volume); - let res = boolean(&b, &tool, BoolOp::Cut); - println!("cut: {:?}", res.map(|o| o.map(|x| measure(&x).unwrap().volume))); - let expect = 36000.0 - std::f64::consts::PI * 9.0 * 10.0 - std::f64::consts::PI * 9.0 * tip / 3.0; - println!("expect {expect}"); -} - -#[test] -#[ignore] -fn debug_sphere() { - let s = sphere(Vec3::new(1.0, 2.0, 3.0), 10.0).unwrap(); - let m = measure(&s).unwrap(); - println!("vol {} area {} faces {} bbox {:?}", m.volume, m.area, m.faces, m.bbox); - for f in s.faces(0.05).unwrap() { - println!("face {} area {:.3} c {:?}", f.index, f.area, f.centroid); - } - let b = box_solid(Vec3::new(-25.0, -25.0, -20.0), Vec3::new(25.0, 25.0, 0.0)).unwrap(); - for (name, c) in [("origin", Vec3::ZERO), ("up", Vec3::new(0.0, 0.0, 3.0)), ("off", Vec3::new(1.3, 2.1, 0.7))] { - let sp = sphere(c, 15.0).unwrap(); - println!("{name} cut {:?}", boolean(&b, &sp, BoolOp::Cut).map(|o| o.map(|x| measure(&x).unwrap().volume))); - println!("{name} and {:?}", boolean(&b, &sp, BoolOp::Intersect).map(|o| o.map(|x| measure(&x).unwrap().volume))); - } -} - -#[test] -#[ignore] -fn debug_countersink() { - let b = box_solid(Vec3::ZERO, Vec3::new(60.0, 40.0, 15.0)).unwrap(); - for (name, pts) in [ - ("csink", vec![Vec2::new(0.0, 0.6), Vec2::new(6.6, 0.6), Vec2::new(3.0, -3.0), Vec2::new(3.0, -31.0), Vec2::new(0.0, -31.0)]), - ("csink-thru-top", vec![Vec2::new(0.0, 0.6), Vec2::new(6.6, 0.6), Vec2::new(3.0, -3.0), Vec2::new(3.0, -16.3), Vec2::new(0.0, -16.3)]), - ( - "cbore", - vec![Vec2::new(0.0, 0.6), Vec2::new(7.0, 0.6), Vec2::new(7.0, -5.0), Vec2::new(4.0, -5.0), Vec2::new(4.0, -31.0), Vec2::new(0.0, -31.0)], - ), - ] { - for (pn, pl) in [ - ("xz@top", Plane::new(Vec3::new(35.0, 20.0, 15.0), Vec3::X, Vec3::Z).unwrap()), - ("yz@top", Plane::new(Vec3::new(35.0, 20.0, 15.0), Vec3::Y, Vec3::Z).unwrap()), - ("diag", Plane::new(Vec3::new(35.0, 20.0, 15.0), Vec3::new(0.6, 0.8, 0.0), Vec3::Z).unwrap()), - ] { - let tool = revolve(&pl, &[Region2 { outer: Loop2::polygon(&pts), holes: vec![] }], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU) - .unwrap() - .pop() - .unwrap(); - println!( - "{name} {pn}: tool {} cut {:?}", - measure(&tool).unwrap().volume, - boolean(&b, &tool, BoolOp::Cut).map(|o| o.map(|x| measure(&x).unwrap().volume)) - ); - } - } -} - -#[test] -#[ignore] -fn debug_cbore_seq() { - let b = box_solid(Vec3::ZERO, Vec3::new(60.0, 40.0, 15.0)).unwrap(); - let pl = Plane::from_normal(Vec3::new(15.0, 20.0, 15.0), Vec3::Z).unwrap(); - for (s1, s2, r2top) in [(0.0, 0.0, 0.6), (0.613, 1.226, 0.6), (0.3, 0.9, 2.37)] { - let t1 = extrude(&pl, &[Region2 { outer: Loop2::circle_from(Vec2::ZERO, 4.0, s1), holes: vec![] }], -31.0, 0.6).unwrap().pop().unwrap(); - let c1 = boolean(&b, &t1, BoolOp::Cut).unwrap().unwrap(); - let t2 = extrude(&pl, &[Region2 { outer: Loop2::circle_from(Vec2::ZERO, 7.0, s2), holes: vec![] }], -5.0, r2top).unwrap().pop().unwrap(); - println!( - "seams {s1} {s2}: first {} second {:?}", - measure(&c1).unwrap().volume, - boolean(&c1, &t2, BoolOp::Cut).map(|o| o.map(|x| measure(&x).unwrap().volume)) - ); - let c2 = boolean(&b, &t2, BoolOp::Cut).unwrap().unwrap(); - println!(" swapped: {:?}", boolean(&c2, &t1, BoolOp::Cut).map(|o| o.map(|x| measure(&x).unwrap().volume))); - } -} - -#[test] -#[ignore] -fn debug_truck_sphere() { - use truck_modeling::{self as mt, builder}; - let mk = |c: Vec3, r: f64, axis: Vec3| -> Body { - let ax = axis.normalized().unwrap(); - let side = ax.any_perp(); - let v0 = builder::vertex(crate::body::p3(c + ax * r)); - let arc = builder::rsweep(&v0, crate::body::p3(c), crate::body::v3(side), mt::Rad(PI)); - let shell = builder::rsweep(&arc, crate::body::p3(c), crate::body::v3(ax), mt::Rad(2.0 * PI)); - Body::new(mt::Solid::new(vec![shell])).unwrap() +/// What an equal-distance chamfer `d` of [`sloped_basin`]'s rim edge at y = `margin` takes, built +/// as if the top went on past the slab's front face y = 0 and then cut by it (the owner's ruling +/// of 2026-10-30, d7: a chamfer that reaches or runs past a rim builds). Its section in (y, z) is +/// the triangle of the edge (margin, 30), the top's contact (margin − d, 30) and the wall's +/// contact d down the wall towards (20, 10) (run 20 − margin over the drop 20), clipped to +/// y >= 0. At height z it runs between the sloped end walls x = 20 + (30 − z)/2 and +/// 80 − (30 − z)/2 (planar, x by z alone), which cut it, so its length there is 30 + z: it takes +/// ∬ (30 + z) dy dz over the clipped section, area · 30 + ∬ z, both exact by the shoelace sums +/// over the polygon (the first moment Σ (z₀ + z₁)(y₀ z₁ − y₁ z₀) / 6). +fn sloped_basin_rim_chamfer_removed(margin: f64, d: f64) -> f64 { + let len = ((20.0 - margin).powi(2) + 400.0).sqrt(); + let (e, t) = ((margin, 30.0), (margin - d, 30.0)); + let w = (margin + d * (20.0 - margin) / len, 30.0 - d * 20.0 / len); + let poly = if t.0 >= 0.0 { + vec![e, t, w] + } else { + let s = -t.0 / (w.0 - t.0); + vec![e, (0.0, 30.0), (0.0, t.1 + s * (w.1 - t.1)), w] }; - let b = box_solid(Vec3::new(-25.0, -25.0, -20.0), Vec3::new(25.0, 25.0, 0.0)).unwrap(); - for (name, axis) in [("z", Vec3::Z), ("x", Vec3::X), ("diag", Vec3::new(0.3, 0.5, 0.8))] { - let sp = mk(Vec3::ZERO, 15.0, axis); - println!("{name}: faces {} vol {}", sp.face_count(), measure(&sp).unwrap().volume); - for op in [BoolOp::Cut, BoolOp::Intersect, BoolOp::Union] { - let r = guard("t", || { - let (sa, mut sb) = (b.deep_copy(), sp.deep_copy()); - let res = match op { - BoolOp::Cut => { - sb.not(); - truck_shapeops::and(&sa, &sb, 0.01) - } - BoolOp::Intersect => truck_shapeops::and(&sa, &sb, 0.01), - BoolOp::Union => truck_shapeops::or(&sa, &sb, 0.01), - }; - Ok(res.map(|s| s.face_iter().count())) - }); - println!(" {op:?}: {r:?}"); - } + let (mut area, mut moment) = (0.0, 0.0); + for i in 0..poly.len() { + let ((y0, z0), (y1, z1)) = (poly[i], poly[(i + 1) % poly.len()]); + let c = y0 * z1 - y1 * z0; + area += c / 2.0; + moment += (z0 + z1) * c / 6.0; + } + area.abs() * 30.0 + moment.abs() +} + +/// A chamfer as wide as a basin's thin rim (`chamfer_sloped_basin_rim`'s basin with the rim +/// `margin` wide at the top) uses the rim's top up, its leg ending on the slab's front edge: +/// it builds (the owner's ruling of 2026-10-30, d7), taking the whole triangle +/// ([`sloped_basin_rim_chamfer_removed`]: unclipped, d · drop / 2 · (60 − drop / 3) with +/// drop = 20 d / √((20 − margin)² + 400)): 21.662379 at 1 on the 1 mm rim, 5.359321 at 0.5 on +/// the 0.5 mm one. +#[test] +fn chamfer_as_wide_as_sloped_basin_rim_builds() { + // The formula reads the fitting chamfer of `chamfer_sloped_basin_rim` as that test does. + let drop = 2.0 / (1.0 + 0.8f64.powi(2)).sqrt(); + assert!(rel(sloped_basin_rim_chamfer_removed(4.0, 2.0), drop * (60.0 - drop / 3.0)) < 1e-12); + for margin in [0.5, 1.0] { + let b = sloped_basin(margin); + let made = chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], margin).unwrap_or_else(|e| panic!("{margin}: {e}")); + assert!(made.validity().is_empty(), "{margin}: {:?}", made.validity()); + let want = measure(&b).unwrap().volume - sloped_basin_rim_chamfer_removed(margin, margin); + assert!(rel(measure(&made).unwrap().volume, want) < 1e-8, "{margin}: {} vs {want}", measure(&made).unwrap().volume); } } +/// A chamfer wider than a basin's thin rim runs its leg off the rim's top, over the slab's front +/// edge (a cliff): it builds as if the top went on and is cut by the front face (the owner's +/// ruling of 2026-10-30, d7), lowering the front face where it crosses it +/// ([`sloped_basin_rim_chamfer_removed`], clipped to y >= 0): 73.450475 for 2 and 142.112912 for +/// 3 on the 1 mm rim, 184.526613 for 4 on the 0.5 mm one. #[test] -#[ignore] -fn debug_sphere_patches() { - let sp = crate::build::sphere_patches(Vec3::ZERO, 15.0).unwrap(); - let m = measure(&sp).unwrap(); - println!("vol {} want {} area {} merged {:?}", m.volume, 4.0 / 3.0 * PI * 3375.0, m.area, m.merged); - let b = box_solid(Vec3::new(-25.0, -25.0, -20.0), Vec3::new(25.0, 25.0, 0.0)).unwrap(); - for op in [BoolOp::Cut, BoolOp::Intersect, BoolOp::Union] { - let r = boolean(&b, &sp, op).map(|o| { - o.map(|x| { - let m = measure(&x).unwrap(); - (m.volume, m.merged) - }) - }); - println!("{op:?}: {r:?}"); - } - let c = box_solid(Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0)).unwrap(); - let a = 0.3f64; - let (ca, sa) = (a.cos(), a.sin()); - let b2 = 0.5f64; - let (cb, sb) = (b2.cos(), b2.sin()); - // Rz(a) * Rx(b) - let rot = [Vec3::new(ca, sa, 0.0), Vec3::new(-sa * cb, ca * cb, sb), Vec3::new(sa * sb, -ca * sb, cb)]; - for (name, s2) in [ - ("plain", crate::build::sphere_patches(Vec3::ZERO, 25.0).unwrap()), - ("turned", crate::build::sphere_patches_rotated(Vec3::ZERO, 25.0, rot).unwrap()), - ] { - println!("{name} vol {}", measure(&s2).unwrap().volume); - println!( - "{name} cube and sphere: {:?}", - boolean(&c, &s2, BoolOp::Intersect).map(|o| o.map(|x| { - let m = measure(&x).unwrap(); - (m.volume, m.merged) - })) - ); - } -} - -#[test] -#[ignore] -fn debug_sphere_cases() { - let s = crate::build::sphere_patches(Vec3::ZERO, 25.0).unwrap(); - let cases = [ - ("one plane", Vec3::new(-100.0, -100.0, -100.0), Vec3::new(100.0, 100.0, 20.0)), - ("two planes", Vec3::new(-100.0, -100.0, -20.0), Vec3::new(100.0, 100.0, 20.0)), - ("three", Vec3::new(-100.0, -100.0, -20.0), Vec3::new(20.0, 100.0, 20.0)), - ("four", Vec3::new(-100.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0)), - ("five", Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 100.0)), - ("cube", Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0)), - ("cube big sphere-ish", Vec3::new(-24.0, -24.0, -24.0), Vec3::new(24.0, 24.0, 24.0)), - ("cube off", Vec3::new(-20.3, -19.7, -20.1), Vec3::new(19.9, 20.2, 19.8)), - ]; - for (name, lo, hi) in cases { - let b = box_solid(lo, hi).unwrap(); - for op in [BoolOp::Intersect, BoolOp::Cut] { - let r = boolean(&b, &s, op).map(|o| o.map(|x| measure(&x).unwrap().volume)); - println!("{name} {op:?}: {:?}", r.map_err(|e| e.to_string().chars().take(60).collect::())); - } - } -} - -#[test] -#[ignore] -fn debug_sphere_rotations() { - let b = box_solid(Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0)).unwrap(); - for k in 0..8 { - let (a, c) = (0.37 * k as f64 + 0.1, 0.61 * k as f64 + 0.2); - let (ca, sa, cc, sc) = (a.cos(), a.sin(), c.cos(), c.sin()); - let rot = [Vec3::new(ca, sa, 0.0), Vec3::new(-sa * cc, ca * cc, sc), Vec3::new(sa * sc, -ca * sc, cc)]; - let s = crate::build::sphere_patches_rotated(Vec3::ZERO, 25.0, rot).unwrap(); - let r = guard("t", || { - let res = truck_shapeops::and(&b.deep_copy(), &s.deep_copy(), 0.01); - Ok(res.map(|x| x.face_iter().count())) - }); - println!("rot {k}: {r:?}"); - } -} - -#[test] -#[ignore] -fn debug_cube_sphere_measure() { - let b = box_solid(Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0)).unwrap(); - let s = crate::build::sphere_patches(Vec3::ZERO, 25.0).unwrap(); - let r = guard("t", || Ok(truck_shapeops::and(&b.deep_copy(), &s.deep_copy(), 0.05))).unwrap().unwrap(); - let body = Body::new(r).unwrap(); - for tol in [0.5, 0.1, 0.02] { - let m = body.tessellate(tol).unwrap(); - let mm = m.measure(); - println!("tol {tol}: vol {} area {} tris {}", mm.volume, mm.area, m.triangles.len()); - } - for f in body.faces(0.05).unwrap() { - println!("face {} area {:.2} c {:?} planar {:?}", f.index, f.area, f.centroid, f.plane_normal.is_some()); +fn chamfer_wider_than_sloped_basin_rim_builds() { + for (margin, distance) in [(1.0, 2.0), (1.0, 3.0), (0.5, 4.0)] { + let b = sloped_basin(margin); + let made = chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], distance).unwrap_or_else(|e| panic!("{margin}, {distance}: {e}")); + assert!(made.validity().is_empty(), "{margin}, {distance}: {:?}", made.validity()); + let want = measure(&b).unwrap().volume - sloped_basin_rim_chamfer_removed(margin, distance); + assert!(rel(measure(&made).unwrap().volume, want) < 1e-8, "{margin}, {distance}: {} vs {want}", measure(&made).unwrap().volume); } } @@ -1434,17 +1154,6 @@ fn mesh_bodies_move_measure_and_refuse_solid_ops() { assert!((measure(&moved).unwrap().volume - 1000.0).abs() < 1e-9); let mirrored = crate::transform_matrix(&b, [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]).unwrap(); assert!((measure(&mirrored).unwrap().volume - 1000.0).abs() < 1e-9); - // Their size (the diagonal of the box around them) is measured once, when made: a large - // scan's size is asked for every frame. - for body in [&b, &moved, &mirrored] { - assert!(body.size > 0.0, "measured when made"); - let walked = body.mesh.as_ref().unwrap().positions.iter().fold(solidcraft_geom::Aabb3::EMPTY, |mut a, p| { - a.add(*p); - a - }); - assert!((body.size() - walked.diagonal()).abs() < 1e-9, "{} vs {}", body.size(), walked.diagonal()); - } - assert!((b.size() - 300.0f64.sqrt()).abs() < 1e-9); let solid = box_solid(Vec3::ZERO, Vec3::new(5.0, 5.0, 5.0)).unwrap(); assert!(fillet(&b, &[Vec3::new(5.0, 0.0, 0.0)], 1.0).unwrap_err().to_string().contains("mesh")); assert!(boolean(&solid, &b, BoolOp::Union).is_err()); @@ -1467,26 +1176,6 @@ fn concave_fillet() { assert_eq!(m.merged.face_types.get("cylinder"), Some(&1)); } -#[test] -#[ignore] -fn debug_pocket_corners() { - let b = box_solid(Vec3::ZERO, Vec3::new(80.0, 60.0, 20.0)).unwrap(); - let p = box_solid(Vec3::new(15.0, 15.0, 12.0), Vec3::new(65.0, 45.0, 25.0)).unwrap(); - let mut cur = boolean(&b, &p, BoolOp::Cut).unwrap().unwrap(); - for e in [Vec3::new(65.0, 15.0, 16.0), Vec3::new(15.0, 15.0, 16.0), Vec3::new(65.0, 45.0, 16.0), Vec3::new(15.0, 45.0, 16.0)] { - match fillet(&cur, &[e], 5.0) { - Ok(n) => { - println!("ok {e:?} vol {}", measure(&n).unwrap().volume); - cur = n; - } - Err(err) => { - println!("fail {e:?}: {err}"); - break; - } - } - } -} - #[test] fn pocket_floor_loop_fillet() { let b = box_solid(Vec3::ZERO, Vec3::new(80.0, 60.0, 20.0)).unwrap(); @@ -1495,18 +1184,23 @@ fn pocket_floor_loop_fillet() { cur = fillet(&cur, &[Vec3::new(65.0, 15.0, 16.0), Vec3::new(15.0, 15.0, 16.0), Vec3::new(65.0, 45.0, 16.0), Vec3::new(15.0, 45.0, 16.0)], 5.0) .unwrap(); let v1 = measure(&cur).unwrap().volume; + // The 50 x 30 x 8 pocket, less the four concave R5 rounds of its corners filling r²(1 − π/4) + // of section along their 8. + let want1 = 80.0 * 60.0 * 20.0 - 50.0 * 30.0 * 8.0 + 4.0 * 25.0 * (1.0 - PI / 4.0) * 8.0; + assert!(rel(v1, want1) < 1e-6, "{v1} vs {want1}"); let floor: Vec = [(40.0, 15.0), (65.0, 30.0), (40.0, 45.0), (15.0, 30.0)].iter().map(|(x, y)| Vec3::new(*x, *y, 12.0)).collect(); let mut pts = floor.clone(); let d = 5.0 - 5.0 / 2f64.sqrt(); pts.extend([(15.0 + d, 15.0 + d), (65.0 - d, 15.0 + d), (65.0 - d, 45.0 - d), (15.0 + d, 45.0 - d)].iter().map(|(x, y)| Vec3::new(*x, *y, 12.0))); let f = fillet(&cur, &pts, 2.0).unwrap(); let m = measure(&f).unwrap(); - // Added: the fillet profile (r²(1 − π/4)) swept along the floor outline (Pappus for the - // corners: the profile's centroid sits 2 − 4·2/(3(4 − π))·… inward; check loosely). - let straight = 2.0 * (40.0 + 20.0); - let added_lines = (4.0 - PI) * straight; - assert!(m.volume > v1 + added_lines && m.volume < v1 + added_lines + 4.0 * 2.0 * PI * 5.0, "{} {}", m.volume, v1); - println!("pocket: {:?} vol {}", m.merged, m.volume); + // Added: the R2 round's section, a = r²(1 − π/4), along the floor outline's straight 2(40 + 20), + // and round its four R5 corners by Pappus: a quarter turn each at the radius of the section's + // centroid, which sits r(10 − 3π)/(3(4 − π)) in from the wall, at 5 from the corner's axis. + let a = 4.0 * (1.0 - PI / 4.0); + let centroid = 5.0 - 2.0 * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)); + let want = v1 + a * 2.0 * (40.0 + 20.0) + 4.0 * a * (PI / 2.0) * centroid; + assert!(rel(m.volume, want) < 1e-6, "{} vs {want}", m.volume); } #[test] @@ -1526,50 +1220,6 @@ fn round_every_edge_of_a_box() { assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (26, 48, 24), "{:?}", m.merged); } -#[test] -#[ignore] -fn debug_heal_sphere_cut() { - let b = box_solid(Vec3::new(-25.0, -25.0, -20.0), Vec3::new(25.0, 25.0, 0.0)).unwrap(); - let s = sphere(Vec3::ZERO, 15.0).unwrap(); - let r = guard("t", || { - let mut sb = s.deep_copy(); - sb.not(); - Ok(truck_shapeops::and(&b.deep_copy(), &sb, 0.05)) - }) - .unwrap() - .unwrap(); - let raw = Body::new(r.clone()).unwrap(); - let healed = Body::new(crate::heal::heal(r, 60.0)).unwrap(); - for (name, x) in [("raw", raw), ("healed", healed)] { - println!("{name}: vol {} faces {}", measure(&x).unwrap().volume, x.face_count()); - for f in x.faces(0.05).unwrap() { - println!(" face {} area {:.2} c {:?}", f.index, f.area, f.centroid); - } - } -} - -#[test] -#[ignore] -fn debug_coplanar_cylinder_union() { - let a = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 20.0)).unwrap(); - let c = cylinder(Vec3::new(40.0, 20.0, 0.0), Vec3::Z, 12.0, 40.0).unwrap(); - for op in [BoolOp::Union, BoolOp::Cut, BoolOp::Intersect] { - let r = guard("t", || { - let (sa, mut sb) = (a.deep_copy(), c.deep_copy()); - Ok(match op { - BoolOp::Union => truck_shapeops::or(&sa, &sb, 0.05), - BoolOp::Cut => { - sb.not(); - truck_shapeops::and(&sa, &sb, 0.05) - } - BoolOp::Intersect => truck_shapeops::and(&sa, &sb, 0.05), - } - .map(|s| s.face_iter().count())) - }); - println!("{op:?}: {r:?}"); - } -} - #[test] fn coplanar_curved_booleans() { // A box and a cylinder standing on the same plane, the cylinder's axis on the box's side. @@ -1583,7 +1233,25 @@ fn coplanar_curved_booleans() { assert!(rel(measure(&cut).unwrap().volume, 32000.0 - half * 20.0) < 1e-3); let i = boolean(&a, &c, BoolOp::Intersect).unwrap().unwrap(); assert!(rel(measure(&i).unwrap().volume, half * 20.0) < 1e-3); - println!("union {:?}", m.merged); + // A cylinder of radius 5 through the middle of a 40 x 30 x 20 box, its caps flush with the + // box's top or bottom or past them: the cut takes the part inside, π·25 a mm of height, and + // the union adds the parts outside. A cylinder inside but for a flush cap adds nothing. + let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); + let disc = PI * 25.0; + for (z0, z1, inside, outside) in [ + (0.0, 20.0, 20.0, 0.0), + (-5.0, 20.0, 20.0, 5.0), + (0.0, 25.0, 20.0, 5.0), + (-5.0, 25.0, 20.0, 10.0), + (5.0, 20.0, 15.0, 0.0), + (5.0, 25.0, 15.0, 5.0), + ] { + let c = cylinder(Vec3::new(20.0, 15.0, z0), Vec3::Z, 5.0, z1 - z0).unwrap(); + let cut = measure(&boolean(&b, &c, BoolOp::Cut).unwrap().unwrap()).unwrap().volume; + assert!(rel(cut, 24000.0 - disc * inside) < 1e-6, "cut z {z0}..{z1}: {cut}"); + let union = measure(&boolean(&b, &c, BoolOp::Union).unwrap().unwrap()).unwrap().volume; + assert!(rel(union, 24000.0 + disc * outside) < 1e-6, "union z {z0}..{z1}: {union}"); + } } #[test] @@ -1600,103 +1268,43 @@ fn shell_non_convex() { assert!(rel(v, outer - cavity) < 1e-6, "{v} vs {}", outer - cavity); } -/// A basin: a slab with a tapered pocket and a 4 mm front rim, shelled from below. A wall -/// thicker than the rim (with the pocket's slope) would turn the top face inside out: refused, -/// not a body with wrong mass properties. +/// A basin: a 100 × 60 × 30 slab with a tapered pocket (60 × 46 at the top, 4 mm from the front, +/// 40 × 20 at its floor 20 down) shelled from below, each wall moved in by t with sharp edges. +/// The cavity is the slab shrunk by t (open at z = 0) less the pocket grown by t, each sloped side +/// moved out along its normal; the volume, slab − pocket − cavity, is a cubic in z integrated by +/// hand. From t ≈ 2.70 the front side's offset passes the front wall's below the 4 mm rim, and +/// the rim stays solid: the cavity's front stops at y = t (from z = (28 − (1 + √1.64) t)/0.8 up). #[test] -fn shell_thicker_than_a_rim_is_refused() { +fn shell_of_a_basin_past_its_rim_keeps_the_rim_solid() { let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); let rect = |x0: f64, y0: f64, x1: f64, y1: f64| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); let at = |z: f64| Plane::new(Vec3::new(0.0, 0.0, z), Vec3::X, Vec3::Y).unwrap(); let pocket = loft(&[(at(30.0), rect(20.0, 4.0, 80.0, 50.0)), (at(10.0), rect(30.0, 20.0, 70.0, 40.0))]).unwrap(); let basin = boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap(); let open = [Vec3::new(50.0, 30.0, 0.0)]; - let e = shell(&basin, &open, 6.0).unwrap_err().to_string(); - assert!(e.contains("rim or ledge"), "{e}"); - let (whole, thin) = (measure(&basin).unwrap(), measure(&shell(&basin, &open, 1.0).unwrap()).unwrap()); - assert!(thin.volume > 0.0 && thin.volume < whole.volume, "{} vs {}", thin.volume, whole.volume); - let (lo, hi) = (thin.bbox.min, thin.bbox.max); - let c = thin.centroid; - assert!(c.x > lo.x && c.x < hi.x && c.y > lo.y && c.y < hi.y && c.z > lo.z && c.z < hi.z, "{c:?}"); - assert!((c.x - 50.0).abs() < 1e-3, "{c:?}"); -} - -#[test] -#[ignore] -fn debug_drilled_hole() { - let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 15.0)).unwrap(); - let r = 3.4; - let half = (118f64 / 2.0).to_radians(); - let tip = r / half.tan(); - let (top, bottom) = (0.6, -12.0); - let a = std::env::var("ANG").ok().and_then(|x| x.parse::().ok()).unwrap_or(0.0); - let rp = Plane::new(Vec3::new(20.0, 15.0, 15.0), Vec3::new(a.cos(), a.sin(), 0.0), Vec3::Z).unwrap(); - let tipv = if std::env::var_os("NOTIP").is_some() { 0.0 } else { tip }; - let pts = [Vec2::new(0.0, top), Vec2::new(r, top), Vec2::new(r, bottom), Vec2::new(0.0, bottom - tipv)]; - let region = Region2 { outer: Loop2::polygon(&pts), holes: vec![] }; - let tool = revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU).unwrap().pop().unwrap(); - println!("tool faces {} vol {}", tool.face_count(), measure(&tool).unwrap().volume); - let r = guard("t", || { - let mut sb = tool.deep_copy(); - sb.not(); - Ok(truck_shapeops::and(&b.deep_copy(), &sb, 0.02).map(|s| s.face_iter().count())) - }); - println!("cut: {r:?}"); -} - -#[test] -#[ignore] -fn debug_face_param_areas() { - use truck_modeling::{BoundedCurve, ParametricCurve, SearchNearestParameter}; - let rp = Plane::new(Vec3::new(20.0, 15.0, 15.0), Vec3::X, Vec3::Z).unwrap(); - let pts = [Vec2::new(0.0, 0.6), Vec2::new(3.4, 0.6), Vec2::new(3.4, -12.0), Vec2::new(0.0, -12.0)]; - let region = Region2 { outer: Loop2::polygon(&pts), holes: vec![] }; - let tool = revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU).unwrap().pop().unwrap(); - let ex = cylinder(Vec3::new(20.0, 15.0, 3.0), Vec3::Z, 3.4, 12.6).unwrap(); - for (name, b) in [("revolve", &tool), ("extrude", &ex)] { - for f in b.solid.face_iter() { - let s = f.surface(); - let mut poly: Vec<(f64, f64)> = Vec::new(); - for w in f.absolute_boundaries() { - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..8 { - let p = c.subs(t0 + (t1 - t0) * k as f64 / 8.0); - if let Some(uv) = s.search_nearest_parameter(p, poly.last().copied(), 100) { - poly.push(uv); - } - } - } - } - let n = poly.len(); - let area: f64 = (0..n) - .map(|i| { - let (a, b) = (poly[i], poly[(i + 1) % n]); - a.0 * b.1 - b.0 * a.1 - }) - .sum::() - / 2.0; - println!("{name}: orientation {} param area {area:.4} wires {}", f.orientation(), f.absolute_boundaries().len()); - } - } -} - -#[test] -#[ignore] -fn debug_revolved_tube_cut() { - let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 15.0)).unwrap(); - let rp = Plane::new(Vec3::new(20.0, 15.0, 15.0), Vec3::X, Vec3::Z).unwrap(); - for (name, inner) in [("tube", 1.0), ("solid", 0.0)] { - let pts = [Vec2::new(inner, 0.6), Vec2::new(3.4, 0.6), Vec2::new(3.4, -12.0), Vec2::new(inner, -12.0)]; - let region = Region2 { outer: Loop2::polygon(&pts), holes: vec![] }; - let tool = revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU).unwrap().pop().unwrap(); - let r = guard("t", || { - let mut sb = tool.deep_copy(); - sb.not(); - Ok(truck_shapeops::and(&b.deep_copy(), &sb, 0.02).map(|s| s.face_iter().count())) - }); - println!("{name}: faces {} cut {r:?}", tool.face_count()); + // The pocket grown by t at height z: x from 35 − z/2 − t√5/2 to 65 + z/2 + t√5/2, y from + // 28 − 0.8 z − t√1.64 (or y = t, where that is less) to 35 + z/2 + t√5/2, for + // z = 10 − t … 30 − t; its sides stay inside the shrunk slab in x and at the back for t ≤ 6. + let (r5, r164) = (5f64.sqrt(), 1.64f64.sqrt()); + let integral = |c: [f64; 3], lo: f64, hi: f64| c[0] * (hi - lo) + c[1] * (hi * hi - lo * lo) / 2.0 + c[2] * (hi.powi(3) - lo.powi(3)) / 3.0; + // (w0 + z)(h0 + h1 z) as coefficients in z. + let product = |w0: f64, h0: f64, h1: f64| [w0 * h0, w0 * h1 + h0, h1]; + let grown = |t: f64| { + let (lo, hi, w0) = (10.0 - t, 30.0 - t, 30.0 + r5 * t); + let full = product(w0, 7.0 + t * (r5 / 2.0 + r164), 1.3); + let z0 = ((28.0 - r164 * t - t) / 0.8).clamp(lo, hi); + integral(full, lo, z0) + integral(product(w0, 35.0 + (r5 / 2.0 - 1.0) * t, 0.5), z0, hi) + }; + let volume = |t: f64| 100.0 * 60.0 * 30.0 - grown(0.0) - (100.0 - 2.0 * t) * (60.0 - 2.0 * t) * (30.0 - t) + grown(t); + let whole = measure(&basin).unwrap(); + assert!(rel(whole.volume, 180_000.0 - grown(0.0)) < 1e-9, "{}", whole.volume); + for (t, want) in [(1.0, 17_105.624_041_5), (4.0, 63_560.249_228_4), (6.0, 90_113.920_210_1)] { + assert!(rel(volume(t), want) < 1e-12, "the closed form at {t}: {}", volume(t)); + let m = measure(&shell(&basin, &open, t).unwrap()).unwrap(); + assert!(rel(m.volume, want) < 1e-6, "t {t}: {} vs {want}", m.volume); + let (lo, hi, c) = (m.bbox.min, m.bbox.max, m.centroid); + assert!(c.x > lo.x && c.x < hi.x && c.y > lo.y && c.y < hi.y && c.z > lo.z && c.z < hi.z, "{c:?}"); + assert!((c.x - 50.0).abs() < 1e-3, "{c:?}"); } } @@ -1721,7 +1329,7 @@ fn circle_loop_fillets_and_chamfers() { #[test] fn trimmed_revolved_faces_measure_exactly() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; use std::f64::consts::FRAC_PI_2; // A slot with concave ends sketched on the plane x = 12.5, cut 4 deep into a revolved shaft // of radius 12.5 (the cut faces' triangulation spans wide angles unless refined). @@ -1777,7 +1385,7 @@ fn shell_with_cylindrical_faces() { #[test] fn draft_of_a_round_ended_pocket() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; use std::f64::consts::FRAC_PI_2; let block = box_solid(Vec3::ZERO, Vec3::new(80.0, 60.0, 25.0)).unwrap(); let segs = vec![ @@ -1851,8 +1459,9 @@ fn rounded_corners_rounded_again_make_spheres() { let bx = box_solid(Vec3::ZERO, Vec3::new(a, b, c)).unwrap(); let vert: Vec = [(0.0, 0.0), (a, 0.0), (a, b), (0.0, b)].iter().map(|(x, y)| Vec3::new(*x, *y, c / 2.0)).collect(); let f = fillet(&bx, &vert, r).unwrap(); - let f = fillet(&f, &[Vec3::new(a / 2.0, 0.0, c)], r).unwrap(); - let f = fillet(&f, &[Vec3::new(a / 2.0, 0.0, 0.0)], r).unwrap(); + // Each loop by one pick and its tangent chain, as the Fillet feature asks for it. + let f = fillet(&f, &crate::tangent_chain(&f, &[Vec3::new(a / 2.0, 0.0, c)]).unwrap(), r).unwrap(); + let f = fillet(&f, &crate::tangent_chain(&f, &[Vec3::new(a / 2.0, 0.0, 0.0)]).unwrap(), r).unwrap(); let (ai, bi, ci) = (a - 2.0 * r, b - 2.0 * r, c - 2.0 * r); let area = 2.0 * (ai * bi + bi * ci + ai * ci) + PI * r * (ai + bi + ci) * 2.0 + 4.0 * PI * r * r; let vol = ai * bi * ci + 2.0 * r * (ai * bi + bi * ci + ai * ci) + PI * r * r * (ai + bi + ci) + 4.0 / 3.0 * PI * r * r * r; @@ -1910,7 +1519,9 @@ fn overlapping_holes_and_mirror_joins() { let both = boolean(&half, &other, BoolOp::Union).unwrap().unwrap(); let v = measure(&half).unwrap().volume; let mb = measure(&both).unwrap(); - assert!(rel(mb.volume, 2.0 * v) < 1e-9, "{} vs {}", mb.volume, 2.0 * v); + // Both volumes are SMLib's integrals, each good to its relative accuracy (1e-8, + // measure::ACCURACY): they agree to the two together. + assert!(rel(mb.volume, 2.0 * v) < 2e-8, "{} vs {}", mb.volume, 2.0 * v); // One body: the shared face is gone and the faces either side of it merged. assert_eq!(mb.merged.faces, 10, "{:?}", mb.merged); // Two equal cylinders on one axis, overlapping: one longer cylinder. @@ -1966,7 +1577,7 @@ fn fillet_where_a_branch_pipe_meets_a_main_pipe() { #[test] fn fillet_an_open_curved_edge() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; // A D-shaped block: the round top edge only, ending at the flat wall's sharp corners. let d = Loop2 { segs: vec![ @@ -1975,12 +1586,9 @@ fn fillet_an_open_curved_edge() { ], }; let b = extrude(&Plane::XY, &[Region2 { outer: d, holes: vec![] }], 0.0, 15.0).unwrap().pop().unwrap(); - let v0 = measure(&b).unwrap().volume; let f = fillet(&b, &[Vec3::new(0.0, 10.0, 15.0)], 2.0).unwrap(); - // (A fine tessellation: the difference of two measured volumes magnifies their error.) - let _ = v0; - let fine = |x: &Body| x.tessellate_with(0.002, true).unwrap().measure().volume; - let removed = fine(&b) - fine(&f); + // Exact volumes (SMLib's, to 1e-8): the difference of two mesh volumes magnifies their sag. + let removed = measure(&b).unwrap().volume - measure(&f).unwrap().volume; // Pappus: the corner's cross-section r²(1 − π/4), its centroid 0.2234 r in from the wall. let r = 2.0; let want = r * r * (1.0 - PI / 4.0) * (10.0 - r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI))) * PI; @@ -1988,7 +1596,7 @@ fn fillet_an_open_curved_edge() { } fn mixed_arc_and_line_prism() -> Body { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; let d = Loop2 { segs: vec![ Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: 0.0, sweep: PI }, @@ -2000,7 +1608,7 @@ fn mixed_arc_and_line_prism() -> Body { #[test] fn fillet_smooth_arc_and_line_loop_keeps_exact_removal() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; // A stadium: four tangent joints, none of which should use a sharp-corner mitre. let outline = Loop2 { segs: vec![ @@ -2019,7 +1627,7 @@ fn fillet_smooth_arc_and_line_loop_keeps_exact_removal() { let area = r * r * (1.0 - PI / 4.0); let centroid = r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)); let want = area * (40.0 + 2.0 * PI * (10.0 - centroid)); - let fine = |b: &Body| b.tessellate_with(1e-4, true).unwrap().measure().volume; + let fine = |b: &Body| b.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let removed = fine(&body) - fine(&blended); assert!(rel(removed, want) < 1e-3, "{removed} vs {want}"); } @@ -2057,11 +1665,11 @@ fn fillet_rounded_rectangle_with_tiny_end_edges() { let area = radius * radius * (1.0 - PI / 4.0); let centroid = radius * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)); let removed = area * (2.0 * (w + h - 4.0 * r) + 2.0 * PI * (r - centroid)); - let fine = |b: &Body| b.tessellate_with(1e-4, true).unwrap().measure().volume; + let fine = |b: &Body| b.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let initial = fine(&body); // Every rim edge, the tiny end alone (tangent chain), and the opposite selection order. for selection in [picks.to_vec(), vec![picks[3]], picks.into_iter().rev().collect()] { - let blended = fillet(&body, &selection, radius).unwrap(); + let blended = fillet(&body, &crate::tangent_chain(&body, &selection).unwrap(), radius).unwrap(); assert!(blended.validity().is_empty(), "{:?}", blended.validity()); assert_eq!(blended.crossed_face_loops().unwrap(), 0); assert_eq!((blended.face_count(), blended.edge_count(), blended.vertex_count()), (18, 40, 24)); @@ -2073,7 +1681,7 @@ fn fillet_rounded_rectangle_with_tiny_end_edges() { #[test] fn fillet_sharp_arc_and_arc_loop() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; // The intersection of two radius-10 disks whose centres are 10 mm apart. let outline = Loop2 { segs: vec![ @@ -2084,7 +1692,7 @@ fn fillet_sharp_arc_and_arc_loop() { let body = extrude(&Plane::XY, &[Region2 { outer: outline, holes: vec![] }], 0.0, 15.0).unwrap().pop().unwrap(); let blended = fillet(&body, &[Vec3::new(5.0, 0.0, 15.0), Vec3::new(-5.0, 0.0, 15.0)], 0.5).unwrap(); assert!(blended.validity().is_empty(), "{:?}", blended.validity()); - let mesh = blended.tessellate_with(1e-4, true).unwrap(); + let mesh = blended.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap(); for p in &mesh.positions { assert!((p.x - 5.0).hypot(p.y) <= 10.0 + 1e-3 && (p.x + 5.0).hypot(p.y) <= 10.0 + 1e-3, "outside the lens: {p:?}"); } @@ -2096,21 +1704,35 @@ fn fillet_sharp_arc_and_arc_loop() { (area(10.0) - area(10.0 - 0.5 * (1.0 - theta.cos()))) * 0.5 * theta.cos() * dt }) .sum(); - let removed = body.tessellate_with(1e-4, true).unwrap().measure().volume - mesh.measure().volume; + // Exact volumes (SMLib's, to 1e-8): the difference of two mesh volumes magnifies their sag. + let removed = measure(&body).unwrap().volume - measure(&blended).unwrap().volume; assert!(rel(removed, want) < 1e-3, "{removed} vs {want}"); } -#[test] -fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() { - use solidcraft_geom::Seg2; - // Reconstruct the outer outline from its seven public pick coordinates: - // R25 plate, x=+/-4 tab sides, R2 corners and a 4 mm straight top. - // The hole's dimensions come from the public reproduction, not an original design file. +/// The area of the tabbed plate's outline (`fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole`) +/// with the R25 arc moved in by `da` and the tab's run (its sides, R2 corners and top) by `dt`, +/// each element parallel to itself, by Green's theorem: an arc about c of radius ρ from a to b +/// gives ½ (ρ² (b − a) + ρ (cx (sin b − sin a) − cy (cos b − cos a))), a segment p→q ½ (p × q). +/// At the concave corners (±4, y) the moved elements meet where they cross: where one side moves +/// the round runs into the other wall, where both do the two rounds are mitred (the owner's +/// ruling for rounds meeting at a concave corner beside an unpicked sharp edge, 2026-10-30). +fn tabbed_plate_area(da: f64, dt: f64) -> f64 { + let cy = 280.0 / 9.0; + let (big, rho) = (25.0 - da, 2.0 - dt); + let tab = rho * rho * PI + 2.0 * rho * (2.0 + cy) + 4.0 * (cy + rho); + let yc = (big * big - (4.0 - dt).powi(2)).sqrt(); + let at = yc.atan2(4.0 - dt); + 0.5 * (big * big * (PI + 2.0 * at) + tab) + (4.0 - dt) * (cy - yc) +} + +/// The tabbed plate's outer outline, reconstructed from its seven public pick coordinates: an R25 +/// plate, x = ±4 tab sides, R2 corners centred at (±2, 280/9) and a 4 mm straight top. +fn tabbed_plate_outline() -> Loop2 { + use solidcore_record::Seg2; let theta = (4.0_f64 / 25.0).acos(); let y = (625.0_f64 - 16.0).sqrt(); let corner_y = 280.0 / 9.0; - let hole_y = 262.0 / 9.0; - let outline = Loop2 { + Loop2 { segs: vec![ Seg2::Arc { center: Vec2::ZERO, radius: 25.0, start: PI - theta, sweep: PI + 2.0 * theta }, Seg2::Line { a: Vec2::new(4.0, y), b: Vec2::new(4.0, corner_y) }, @@ -2119,10 +1741,60 @@ fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() { Seg2::Arc { center: Vec2::new(-2.0, corner_y), radius: 2.0, start: PI / 2.0, sweep: PI / 2.0 }, Seg2::Line { a: Vec2::new(-4.0, corner_y), b: Vec2::new(-4.0, y) }, ], - }; + } +} + +/// solidcore#2223: the tabbed plate's R25 rim and one R2 tab corner arc, which share no vertex, +/// rounded together at r 0.5 on the plate 2 high (no hole). Each rounds alone; together they +/// failed 1001 in cliff_overflow. They take off the sum: the rim alone's closed form, +/// 7.958672911836132 (its spandrel (1 − π/4) r² revolved about the disc's axis outside |x| < 4, +/// solidcore#2176's test; the rim's End, `fillet_blend_corner`, builds it to 5e-8), and the +/// corner arc's Pappus volume with flat ends, 0.15913583972191622 (the spandrel about the +/// corner's axis at 2 − its centroid over a quarter turn), 8.117808752. +#[test] +fn fillet_tabbed_plate_rim_and_one_corner_arc_together() { + let body = extrude(&Plane::XY, &[Region2 { outer: tabbed_plate_outline(), holes: vec![] }], 0.0, 2.0).unwrap().pop().unwrap(); + let r = 0.5; + let (spandrel, centroid) = ((1.0 - PI / 4.0) * r * r, r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI))); + let corner = spandrel * (PI / 2.0) * (2.0 - centroid); + assert!((corner - 0.159_135_839_721_916_22).abs() < 1e-12, "{corner}"); + let want = 7.958_672_911_836_132 + corner; + let picks = [ + Vec3::new(-24.91935125502191, -2.0064727829797544, 2.0), + Vec3::new(24.919351255429795, -2.006472777913911, 2.0), + Vec3::new(3.4142135598750105, 32.525324672801695, 2.0), + ]; + let blended = fillet(&body, &picks, r).unwrap_or_else(|e| panic!("rim and corner arc together: {e}")); + assert!(blended.validity().is_empty(), "{:?}", blended.validity()); + assert_eq!(blended.face_count(), 12); + let got = measure(&body).unwrap().volume - measure(&blended).unwrap().volume; + assert!((got - want).abs() < 1e-7, "removed {got}, expected {want}"); +} + +#[test] +fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() { + // The hole's dimensions come from the public reproduction, not an original design file. + let theta = (4.0_f64 / 25.0).acos(); + let y = (625.0_f64 - 16.0).sqrt(); + let corner_y = 280.0 / 9.0; + let hole_y = 262.0 / 9.0; + let outline = tabbed_plate_outline(); let body = extrude(&Plane::XY, &[Region2 { outer: outline, holes: vec![Loop2::circle(Vec2::new(0.0, hole_y), 1.5)] }], 0.0, 2.0).unwrap().pop().unwrap(); - let inner = fillet(&body, &[Vec3::new(1.5, hole_y, 2.0)], 0.5).unwrap(); + let r = 0.5; + // The section a round takes off, (1 − π/4) r², and its centroid's distance from both faces. + let (spandrel, centroid) = ((1.0 - PI / 4.0) * r * r, r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI))); + // The outline's area (Green's theorem, checked against the disc, the tab's rectangle and its + // two R2 corners), the plate its prism 2 high less the hole. + let outline_area = tabbed_plate_area(0.0, 0.0); + let parts = 312.5 * (PI + 2.0 * theta) + 4.0 * y + 8.0 * (corner_y - y) + 8.0 + 2.0 * PI; + assert!(rel(outline_area, parts) < 1e-14, "{outline_area} vs {parts}"); + assert!(rel(measure(&body).unwrap().volume, 2.0 * (outline_area - PI * 2.25)) < 1e-9); + // The hole's rim round (Pappus: the spandrel about the hole's axis at 1.5 + its centroid). + let inner = fillet(&body, &[Vec3::new(1.5, hole_y, 2.0)], r).unwrap(); + let rim = spandrel * 2.0 * PI * (1.5 + centroid); + let holed = measure(&inner).unwrap().volume; + assert!(rel(measure(&body).unwrap().volume - holed, rim) < 1e-5, "{} vs {rim}", measure(&body).unwrap().volume - holed); let edges = [ Vec3::new(-24.91935125502191, -2.0064727829797544, 2.0), Vec3::new(24.919351255429795, -2.006472777913911, 2.0), @@ -2132,13 +1804,37 @@ fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() { Vec3::new(-3.4142135648720653, 32.52532467287703, 2.0), Vec3::new(-4.0000000025087745, 27.89451823429679, 2.0), ]; + // The selections that end only at the sharp concave corners at (±4, y): the R25 arc (its two + // edges, tangent at the bottom), the tab's run (tangent through its R2 corners), and both. + // Each takes off the outline's section less the section moved in by d = r (1 − cos φ) at the + // height r sin φ into the round, integrated over that height (midpoint rule in φ). + let removed = |arc: bool, tab: bool, steps: u32| { + let dphi = (PI / 2.0) / f64::from(steps); + (0..steps) + .map(|i| { + let phi = (f64::from(i) + 0.5) * dphi; + let d = r * (1.0 - phi.cos()); + (outline_area - tabbed_plate_area(if arc { d } else { 0.0 }, if tab { d } else { 0.0 })) * r * phi.cos() * dphi + }) + .sum::() + }; + for (mask, arc, tab) in [(0b0000011_u32, true, false), (0b1111100, false, true), (0b1111111, true, true)] { + let want = removed(arc, tab, 8192); + assert!((want - removed(arc, tab, 4096)).abs() < 1e-7 * want, "the reference quadrature must converge"); + let picks: Vec<_> = edges.iter().enumerate().filter(|(i, _)| mask & (1 << i) != 0).map(|(_, p)| *p).collect(); + let blended = fillet(&inner, &picks, r).unwrap_or_else(|e| panic!("{picks:?}: {e}")); + assert!(blended.validity().is_empty(), "{picks:?}: {:?}", blended.validity()); + // Exact volumes (SMLib's, to 1e-8); the blend's surfaces are SMLib's fits. + let got = holed - measure(&blended).unwrap().volume; + assert!(rel(got, want) < 1e-5, "arc {arc}, tab {tab}: removed {got}, expected {want}"); + } // All 127 nonempty subsets: the whole rim, each individual edge, and every // contiguous or disjoint partial selection of the issue's seven picks. for mask in 1_u32..(1 << edges.len()) { let picks: Vec<_> = edges.iter().enumerate().filter(|(i, _)| mask & (1 << i) != 0).map(|(_, p)| *p).collect(); let blended = fillet(&inner, &picks, 0.5).unwrap_or_else(|e| panic!("{picks:?}: {e}")); assert!(blended.validity().is_empty(), "{:?}", blended.validity()); - let mesh = blended.display_mesh(0.01).unwrap(); + let mesh = blended.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); for p in &mesh.positions { let inside = p.x.hypot(p.y) <= 25.001 || (p.x.abs() <= 4.001 && p.y >= y - 0.001 && p.y <= corner_y) @@ -2151,7 +1847,7 @@ fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() { } fn partial_mixed_run_prism() -> Body { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; let outline = Loop2 { segs: vec![ Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(40.0, 0.0) }, @@ -2165,28 +1861,6 @@ fn partial_mixed_run_prism() -> Body { extrude(&Plane::XY, &[Region2 { outer: outline, holes: vec![] }], 0.0, 15.0).unwrap().pop().unwrap() } -#[test] -fn mixed_loop_blend_guards_selection_and_construction() { - let body = mixed_arc_and_line_prism(); - let solid = body.deep_copy(); - let top = solid - .boundaries() - .iter() - .flat_map(|shell| shell.face_iter()) - .find(|face| face.edge_iter().all(|edge| (edge.front().point().z - 15.0).abs() < 1e-9 && (edge.back().point().z - 15.0).abs() < 1e-9)) - .unwrap(); - let edges: Vec<_> = top.edge_iter().map(|edge| edge.id()).collect(); - // The internal test-only assertions check the active guard during both selection and build. - assert!(!crate::guarded()); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| crate::loopblend::loop_blend(&solid, &edges, body.size(), 0.5, true))); - assert!(matches!(result, Ok(Some(Ok(_)))), "{result:?}"); - assert!(!crate::guarded()); - // A degenerate profile still returns a clean error and restores the guard depth. - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| crate::loopblend::loop_blend(&solid, &edges, body.size(), 0.0, true))); - assert!(matches!(result, Ok(Some(Err(_)))), "{result:?}"); - assert!(!crate::guarded()); -} - #[test] fn fillet_mixed_arc_and_line_perimeter_edges() { let body = mixed_arc_and_line_prism(); @@ -2194,9 +1868,9 @@ fn fillet_mixed_arc_and_line_perimeter_edges() { assert!(blended.validity().is_empty(), "{:?}", blended.validity()); let display_tol = (blended.size() * 1e-3).max(1e-3); for mesh in [ - blended.tessellate_with(1e-4, true).unwrap(), - blended.display_mesh_angular(display_tol, crate::DISPLAY_ANGLE).unwrap(), - blended.reference_display_mesh_angular(display_tol, crate::DISPLAY_ANGLE).unwrap(), + blended.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap(), + blended.mesh(&crate::MeshTolerance { chord: display_tol, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(), + blended.mesh(&crate::MeshTolerance { chord: display_tol, angle: Some(crate::DISPLAY_ANGLE) }).unwrap(), ] { let bounds = mesh.bounds(); let tol = 1e-3; @@ -2234,9 +1908,9 @@ fn d_fillet_removed_reference(r: f64, steps: u32) -> f64 { #[test] fn fillet_mixed_arc_and_line_removed_volume_converges() { let body = mixed_arc_and_line_prism(); - let source_exact = PI * 100.0 * 15.0 / 2.0; let tolerances = [1e-4, 2.5e-5]; - let source_volumes = tolerances.map(|tol| body.tessellate_with(tol, true).unwrap().measure().volume); + let source_volumes = tolerances.map(|tol| body.mesh(&crate::MeshTolerance::chord(tol)).unwrap().measure().volume); + let source = measure(&body).unwrap(); for r in [0.5, 0.25] { let want = d_fillet_removed_reference(r, 8192); assert!((want - d_fillet_removed_reference(r, 4096)).abs() < 1e-7, "reference quadrature must converge"); @@ -2244,100 +1918,28 @@ fn fillet_mixed_arc_and_line_removed_volume_converges() { assert!((want - 2.715578447526581).abs() < 1e-7, "{want}"); } let blended = fillet(&body, &[Vec3::new(0.0, 10.0, 15.0), Vec3::new(5.0, 0.0, 15.0)], r).unwrap(); - let mut previous = None; - for (tol, source) in tolerances.into_iter().zip(source_volumes) { - let volume = blended.tessellate_with(tol, true).unwrap().measure().volume; - // Equal chord tolerances reduce (not necessarily cancel) the error from the - // unchanged walls. The convergence and exact-source checks below guard this. - let removed = source - volume; - assert!(rel(removed, want) < 1e-3, "r={r}, tol={tol}: removed {removed}, expected {want}"); - if let Some(coarser) = previous { - assert!(rel(removed, coarser) < 1e-3, "r={r}: removal has not converged: {coarser} -> {removed}"); - let exact_removed = source_exact - volume; - // The source's inscribed semicylinder loses at most pi*R*H*tol. - // Do not charge its chord error to the much smaller fillet volume. - let source_error = (source_exact - source).abs(); - assert!(source_error < PI * 10.0 * 15.0 * tol, "source chord error {source_error}"); - assert!((exact_removed - want).abs() < source_error + want * 1e-3, "r={r}: exact-source removal {exact_removed}, expected {want}"); - } - previous = Some(removed); + // The removal from the exact volumes (SMLib's, to 1e-8): the reference to a hundred + // thousandth (the blend's surfaces are SMLib's fits; the rig's + // fillets/485-fillet-d-prism-top-outline-arc-and-flat grades the same round). + let done = measure(&blended).unwrap(); + let exact = source.volume - done.volume; + assert!(rel(exact, want) < 1e-5, "r={r}: removed {exact}, expected {want}"); + // From meshes, the removal converges on it: each mesh lies within its chord of its + // faces, so the two differ from the exact removal by at most their areas times it. + for (tol, source_mesh) in tolerances.into_iter().zip(source_volumes) { + let removed = source_mesh - blended.mesh(&crate::MeshTolerance::chord(tol)).unwrap().measure().volume; + let bound = (source.area + done.area) * tol; + assert!((removed - exact).abs() <= bound, "r={r}, tol={tol}: mesh removal {removed}, exact {exact} (within {bound})"); } } } -#[test] -fn loop_chamfer_mixed_arc_and_line_uses_offset_intersections() { - let body = mixed_arc_and_line_prism(); - // Exercise the shared loop builder; public chamfer prefers boolean cutters first. - let solid = body.deep_copy(); - let top = solid - .face_iter() - .find(|face| face.edge_iter().all(|edge| (edge.front().point().z - 15.0).abs() < 1e-9 && (edge.back().point().z - 15.0).abs() < 1e-9)) - .unwrap(); - let edges: Vec<_> = top.edge_iter().map(|edge| edge.id()).collect(); - let (result, history) = crate::loopblend::loop_blend(&solid, &edges, body.size(), 0.5, false).unwrap().unwrap(); - let blended = crate::record::rebuilt(result, &[&solid], &history).unwrap(); - assert!(blended.validity().is_empty(), "{:?}", blended.validity()); - // A chamfer has a linear inset through its height instead of a circular section. - let step = 0.5 / 8192.0; - let want: f64 = (0..8192) - .map(|i| { - let d = (f64::from(i) + 0.5) * step; - let rho = 10.0 - d; - let remaining = rho * rho * (d / rho).acos() - d * (rho * rho - d * d).sqrt(); - (PI * 50.0 - remaining) * step - }) - .sum(); - // The cone's triangulation needs this chord tolerance for the small volume difference. - let fine = |b: &Body| b.tessellate_with(2.5e-5, true).unwrap().measure().volume; - let removed = fine(&body) - fine(&blended); - assert!(rel(removed, want) < 1e-3, "{removed} vs {want}"); -} - -#[test] -fn fillet_mixed_arc_and_line_joint_preserves_both_section_radii() { - use truck_modeling::{BoundedCurve, ParametricCurve}; - - let r = 0.5; - let body = mixed_arc_and_line_prism(); - let blended = fillet(&body, &[Vec3::new(0.0, 10.0, 15.0), Vec3::new(5.0, 0.0, 15.0)], r).unwrap(); - crate::guard("inspect mixed fillet mitres", || { - let solid = blended.deep_copy(); - let mut mitres = std::collections::HashSet::new(); - for edge in solid.boundaries().iter().flat_map(|shell| shell.edge_iter()) { - let a = crate::body::from_p3(edge.front().point()); - let b = crate::body::from_p3(edge.back().point()); - // Only the two corner profiles join the top contact to the wall contact. - if (a.z - b.z).abs() < r - 1e-8 || a.z.min(b.z) < 15.0 - r - 1e-8 || a.x * b.x <= 0.0 { - continue; - } - if !mitres.insert(edge.id()) { - continue; - } - let curve = edge.oriented_curve(); - let (lo, hi) = curve.range_tuple(); - for i in 0..=257 { - let p = crate::body::from_p3(curve.subs(lo + (hi - lo) * f64::from(i) / 257.0)); - // The joint lies on both the cylindrical line blend and the toroidal - // arc blend, not their tangent-plane approximation. - let radius2 = (p.y - r).powi(2) + (p.z - (15.0 - r)).powi(2); - assert!((radius2 - r * r).abs() < 1e-7, "distorted line section at {p:?}: radius squared {radius2}"); - let radius2 = (p.x.hypot(p.y) - (10.0 - r)).powi(2) + (p.z - (15.0 - r)).powi(2); - assert!((radius2 - r * r).abs() < 1e-7, "distorted arc section at {p:?}: radius squared {radius2}"); - } - } - assert_eq!(mitres.len(), 2, "both arc/line corners must be checked"); - Ok(()) - }) - .unwrap(); -} - #[test] fn fillet_partial_mixed_arc_and_line_perimeter_run() { let body = partial_mixed_run_prism(); let blended = fillet(&body, &[Vec3::new(35.0, 20.0, 15.0), Vec3::new(20.0, 30.0, 15.0), Vec3::new(5.0, 20.0, 15.0)], 0.5).unwrap(); assert!(blended.validity().is_empty(), "{:?}", blended.validity()); - let mesh = blended.tessellate_with(1e-4, true).unwrap(); + let mesh = blended.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap(); let bounds = mesh.bounds(); let tol = 1e-3; assert!( @@ -2356,57 +1958,6 @@ fn fillet_partial_mixed_arc_and_line_perimeter_run() { } } -/// Boolean survey: random boxes, cylinders and spheres combined every way; prints what fails. -#[test] -#[ignore] -fn boolean_survey() { - let mut seed: u64 = 0x2545_f491_4f6c_dd1d; - let mut rnd = || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed % 1_000_000) as f64 / 1_000_000.0 - }; - let mut shapes: Vec<(String, Body)> = Vec::new(); - for i in 0..40 { - let kind = i % 4; - let (x, y, z) = ((rnd() - 0.5) * 20.0, (rnd() - 0.5) * 20.0, (rnd() - 0.5) * 20.0); - // Snap some coordinates to a 5 mm grid: coincident faces and tangencies. - let snap = |v: f64, s: bool| if s { (v / 5.0).round() * 5.0 } else { v }; - let s = rnd() < 0.5; - let (x, y, z) = (snap(x, s), snap(y, s), snap(z, s)); - let a = 5.0 + snap(rnd() * 20.0, s); - let ax = (rnd() * 3.0) as usize % 3; - let b = match kind { - 0 => box_solid(Vec3::new(x, y, z), Vec3::new(x + a, y + a * 0.8, z + a * 0.6)), - 1 => cylinder(Vec3::new(x, y, z), [Vec3::X, Vec3::Y, Vec3::Z][ax], a * 0.4, a), - 2 => sphere(Vec3::new(x, y, z), a * 0.5), - _ => box_solid(Vec3::new(x, y, z), Vec3::new(x + a * 0.5, y + a, z + a * 0.3)), - }; - if let Ok(b) = b { - shapes.push((format!("{}{i}@({x:.3},{y:.3},{z:.3}) a={a:.3} ax={ax}", ["box", "cyl", "sph", "slab"][kind]), b)); - } - } - let (mut ok, mut empty, mut fail) = (0, 0, Vec::new()); - for i in 0..shapes.len() { - for j in i + 1..(i + 4).min(shapes.len()) { - for op in [BoolOp::Union, BoolOp::Cut, BoolOp::Intersect] { - let (na, a) = &shapes[i]; - let (nb, b) = &shapes[j]; - match boolean(a, b, op) { - Ok(Some(_)) => ok += 1, - Ok(None) => empty += 1, - Err(e) => fail.push(format!("{na} {op:?} {nb}: {}", e.to_string().chars().take(140).collect::())), - } - } - } - } - println!("ok {ok} empty {empty} failed {}", fail.len()); - for f in &fail { - println!(" {f}"); - } -} - #[test] fn booleans_found_by_the_survey() { // A tool wholly inside: a void (the solid keeps an inner shell). @@ -2458,14 +2009,21 @@ fn fillet_three_edges_at_a_corner() { let a = r * r * (1.0 - PI / 4.0); let want = a * (40.0 + 30.0 + 20.0) - 3.0 * a * r + (r * r * r - PI * r * r * r / 6.0); assert!(rel(removed, want) < 2e-3, "removed {removed} vs {want}"); + // The corner is one face: SMLib builds it as a rational patch exactly on the ball's sphere + // (a ball patch, not SMLib's sphere), between the three cylinders and the six planes; the + // record keeps its sphere, so it counts as one. let m = measure(&f).unwrap().merged; - assert_eq!(m.face_types.get("sphere"), Some(&1), "{m:?}"); + assert_eq!( + (m.faces, m.face_types.get("plane"), m.face_types.get("cylinder"), m.face_types.get("sphere")), + (10, Some(&6), Some(&3), Some(&1)), + "{m:?}" + ); } #[test] fn shell_with_spherical_and_conical_faces() { // A cylinder capped by a hemisphere (a dome), revolved, opened at the bottom. - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; let xz = Plane::new(Vec3::ZERO, Vec3::X, Vec3::new(0.0, 0.0, -1.0)).unwrap(); let segs = vec![ Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) }, @@ -2571,10 +2129,11 @@ fn tangent_holes_pinch_alike() { assert_eq!(m.merged.faces, 12, "{:?}", m.merged); } -/// A d10 tube bent at R5: the inside of the bend is a horn torus pinched to a point. One torus -/// face, with a degenerate loop at the pinch (5 faces, 6 edges, 4 vertices). +/// A d10 tube bent at R5: the inside of the bend is a horn torus pinched to a point, so the +/// sweep just doesn't fold over itself. It is a valid solid of Pappus' volume, πr² times the +/// path's length (20 + 5π/2 + 20). #[test] -fn tight_bend_counts() { +fn a_bend_as_tight_as_the_tube_sweeps_a_valid_solid() { use crate::build::PathSeg; let region = Region2 { outer: Loop2::circle(Vec2::ZERO, 5.0), holes: vec![] }; let path = [ @@ -2588,27 +2147,11 @@ fn tight_bend_counts() { PathSeg::Line { a: Vec3::new(5.0, 0.0, 25.0), b: Vec3::new(25.0, 0.0, 25.0) }, ]; let b = sweep(&Plane::XY, ®ion, &path).unwrap(); - let m = measure(&b).unwrap().merged; - assert_eq!((m.faces, m.edges, m.vertices), (5, 6, 4), "{m:?}"); -} - -#[test] -#[ignore] -fn boolean_identity_survey() { - let n: u64 = std::env::var("N").ok().and_then(|x| x.parse().ok()).unwrap_or(100); - let seeds: Vec = match std::env::var("SEEDS") { - Ok(s) => s.split(',').filter_map(|x| x.parse().ok()).collect(), - Err(_) => (0..n).collect(), - }; - let mut bad = 0; - for seed in seeds { - let c = crate::fuzz::boolean_case(seed); - if c.outcome != "ok" { - bad += 1; - println!("{seed}: {} {} | {:?} | {:?}", c.outcome, c.detail, c.a, c.b); - } - } - println!("{bad}/{n} failed"); + assert!(b.validity().is_empty(), "{:?}", b.validity()); + let pi = std::f64::consts::PI; + let want = pi * 25.0 * (40.0 + 2.5 * pi); + let v = measure(&b).unwrap().volume; + assert!(rel(v, want) < 1e-6, "{v} vs {want}"); } /// A quarter turn of a rectangle with an edge on the axis: no zero-area face along the axis, so @@ -2719,136 +2262,15 @@ fn orientation_mesh_reuses_missing_face_check_at_matching_tolerance() { for scale in [0.001, 1.0, 1000.0] { let body = box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.) * scale).unwrap(); let tol = (body.size() * 0.01).max(1e-3); - let mesh = body.tessellate(tol).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); let mut present = vec![false; body.face_count()]; for face in mesh.tri_face { present[face as usize] = true; } assert_eq!(body.unmeshed_faces(), present.iter().filter(|p| !**p).count()); - if scale == 1.0 { - assert_eq!(body.coarse_missing, Some((tol, 0))); - } } } -/// A trough whose floor falls about 1° toward a central drain, the fall starting right at the -/// trough edges: four faces meet at each bottom corner (two walls, two fall facets) and at the -/// drain (four facets). A tab on one end makes the body non-convex. The moved planes of four -/// faces don't meet at one point, so each such corner of the cavity becomes two corners joined -/// by a short edge. Checked against the volume integrated by hand. -#[test] -fn shell_where_four_faces_meet_at_a_corner() { - let (w, l, ht, t) = (100.0, 60.0, 40.0, 2.0); - // Drain depth: the long facets fall 1°. - let h = 30.0 * 1f64.to_radians().tan(); - let facet = |n: Vec3, p: Vec3| { - let n = n.normalized().unwrap(); - HalfSpace { n, d: n.dot(p) } - }; - let facets = [ - facet(Vec3::new(0.0, -h, -30.0), Vec3::ZERO), - facet(Vec3::new(0.0, h, -30.0), Vec3::new(0.0, l, 0.0)), - facet(Vec3::new(-h, 0.0, -50.0), Vec3::ZERO), - facet(Vec3::new(h, 0.0, -50.0), Vec3::new(w, 0.0, 0.0)), - ]; - let mut hs = vec![ - HalfSpace { n: -Vec3::X, d: 0.0 }, - HalfSpace { n: Vec3::X, d: w }, - HalfSpace { n: -Vec3::Y, d: 0.0 }, - HalfSpace { n: Vec3::Y, d: l }, - HalfSpace { n: Vec3::Z, d: ht }, - ]; - hs.extend(facets); - let trough = convex_polyhedron(&hs).unwrap(); - let pyramid = w * l * h / 3.0; - assert!(rel(measure(&trough).unwrap().volume, w * l * ht + pyramid) < 1e-9); - let tab = box_solid(Vec3::new(w, 20.0, 20.0), Vec3::new(w + 20.0, 40.0, ht)).unwrap(); - let body = boolean(&trough, &tab, BoolOp::Union).unwrap().unwrap(); - let s = shell(&body, &[Vec3::new(50.0, 30.0, ht)], t).unwrap(); - // The cavity: the walls in by t, above the floor facets moved in by t (midpoint rule; the - // floor is linear between its creases). - let floor = |x: f64, y: f64| facets.iter().map(|f| (f.d - t - f.n.x * x - f.n.y * y) / f.n.z).fold(f64::NEG_INFINITY, f64::max); - let (nx, ny) = (960, 560); - let (dx, dy) = ((w - 2.0 * t) / nx as f64, (l - 2.0 * t) / ny as f64); - let mut cavity = 0.0; - for i in 0..nx { - for j in 0..ny { - cavity += (ht - floor(t + (i as f64 + 0.5) * dx, t + (j as f64 + 0.5) * dy)) * dx * dy; - } - } - let tab_cavity = 20.0 * (20.0 - 2.0 * t) * (20.0 - t); - let want = w * l * ht + pyramid + 8000.0 - cavity - tab_cavity; - let m = measure(&s).unwrap(); - assert!(rel(m.volume, want) < 1e-5, "{} vs {want}", m.volume); -} - -/// The same trough cut as a pocket into a slab (four faces meet at each concave corner of the -/// pocket floor), shelled with its top open. -#[test] -fn shell_of_a_pocket_whose_floor_falls_to_a_drain() { - let (px, py, pw, pl, top, depth, t) = (20.0, 15.0, 100.0, 60.0, 50.0, 30.0, 3.0); - let h = 30.0 * 1f64.to_radians().tan(); - let z0 = top - depth; - let facet = |n: Vec3, p: Vec3| { - let n = n.normalized().unwrap(); - HalfSpace { n, d: n.dot(p) } - }; - let facets = [ - facet(Vec3::new(0.0, -h, -30.0), Vec3::new(px, py, z0)), - facet(Vec3::new(0.0, h, -30.0), Vec3::new(px, py + pl, z0)), - facet(Vec3::new(-h, 0.0, -50.0), Vec3::new(px, py, z0)), - facet(Vec3::new(h, 0.0, -50.0), Vec3::new(px + pw, py, z0)), - ]; - let mut hs = vec![ - HalfSpace { n: -Vec3::X, d: -px }, - HalfSpace { n: Vec3::X, d: px + pw }, - HalfSpace { n: -Vec3::Y, d: -py }, - HalfSpace { n: Vec3::Y, d: py + pl }, - HalfSpace { n: Vec3::Z, d: top + 10.0 }, - ]; - hs.extend(facets); - let pocket = convex_polyhedron(&hs).unwrap(); - let slab = box_solid(Vec3::ZERO, Vec3::new(140.0, 90.0, top)).unwrap(); - let basin = boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap(); - let pocket_vol = pw * pl * depth + pw * pl * h / 3.0; - assert!(rel(measure(&basin).unwrap().volume, 140.0 * 90.0 * top - pocket_vol) < 1e-9); - let s = shell(&basin, &[Vec3::new(5.0, 5.0, top)], t).unwrap(); - // The cavity's columns: from t up to the top, or up to the pocket floor moved down by t - // inside the pocket's walls moved out by t. - let floor = |x: f64, y: f64| facets.iter().map(|f| (f.d + t - f.n.x * x - f.n.y * y) / f.n.z).fold(f64::NEG_INFINITY, f64::max); - let (nx, ny) = (1340, 840); - let (dx, dy) = ((140.0 - 2.0 * t) / nx as f64, (90.0 - 2.0 * t) / ny as f64); - let mut cavity = 0.0; - for i in 0..nx { - for j in 0..ny { - let (x, y) = (t + (i as f64 + 0.5) * dx, t + (j as f64 + 0.5) * dy); - let inside = x > px - t && x < px + pw + t && y > py - t && y < py + pl + t; - let roof = if inside { floor(x, y) } else { top }; - cavity += (roof - t) * dx * dy; - } - } - let want = 140.0 * 90.0 * top - pocket_vol - cavity; - let m = measure(&s).unwrap(); - assert!(rel(m.volume, want) < 1e-4, "{} vs {want}", m.volume); -} - -#[test] -fn shell_open_beside_a_round_as_large_as_the_wall_is_refused() { - // Opening the bottom of a box whose bottom outline is rounded: the cavity's side walls stand - // the thickness in from the outside, where a round at least that large meets the bottom, so - // the rim would have no thickness. Smaller rounds leave a rim. - let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(); - let loop_ = [Vec3::new(20.0, 0.0, 0.0), Vec3::new(40.0, 15.0, 0.0), Vec3::new(20.0, 30.0, 0.0), Vec3::new(0.0, 15.0, 0.0)]; - let bottom = [Vec3::new(20.0, 15.0, 0.0)]; - for r in [2.0, 2.4] { - let f = fillet(&b, &loop_, r).unwrap(); - let e = shell(&f, &bottom, 2.0).unwrap_err(); - assert!(e.to_string().starts_with("the operation failed: not supported yet: the rim"), "{r}: {e}"); - } - let f = fillet(&b, &loop_, 1.5).unwrap(); - assert!(shell(&f, &bottom, 2.0).unwrap().validity().is_empty()); -} - #[test] fn loft_joined_onto_a_box_top_is_one_shell() { // #396: a loft from a Ø12 circle on the box top (z = 20) to a hexagon at z = 35. The union @@ -2872,7 +2294,7 @@ fn loft_joined_onto_a_box_top_is_one_shell() { // Overhanging the box edge (x = 20) the disc is not inside the top face: whatever the join // does, it never returns touching shells as one body. if let Ok(Some(r)) = boolean(&bx, &loft_at(17.0), BoolOp::Union) { - assert!(r.shell_count() == 1 || r.union_lumps().is_ok(), "{} touching shells", r.shell_count()); + assert!(r.shell_count() == 1 || r.lumps().is_ok(), "{} touching shells", r.shell_count()); } } @@ -2902,16 +2324,17 @@ fn shell_of_a_disc_rounded_smaller_than_the_wall() { } } -/// The cache-budget estimate counts edge and vertex uses on the borrowed boundaries; it must -/// equal what walking the cloned wires (`Solid::edge_iter`, `vertex_iter`) counts. +/// The cache-budget estimate counts faces and edge uses on the record: 2048 bytes a face and +/// 512 + 96 an edge use. #[test] fn retained_bytes_matches_the_iterator_counts() { let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(); let hole = cylinder(Vec3::new(20.0, 15.0, -5.0), Vec3::Z, 5.0, 30.0).unwrap(); let drilled = boolean(&block, &hole, BoolOp::Cut).unwrap().unwrap(); for body in [&block, &hole, &drilled] { - let s = &body.solid; - let walked = s.face_iter().count() * 2048 + s.edge_iter().count() * 512 + s.vertex_iter().count() * 96; + let r = body.record(); + let uses: usize = r.edges.iter().map(|e| e.uses.len()).sum(); + let walked = r.faces.len() * 2048 + uses * (512 + 96); assert_eq!(body.retained_bytes(), walked); } } @@ -2975,133 +2398,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 = 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. -#[test] -fn an_attempt_budget_stops_the_boolean_and_is_shared_by_nesting() { - let a = cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::Z, 3.0, 20.0).unwrap(); - let b = cylinder(Vec3::new(-10.0, 0.0, 0.0), Vec3::X, 2.0, 20.0).unwrap(); - assert!(with_attempt_budget(0, || boolean(&a, &b, BoolOp::Intersect)).is_err()); - // The inner budget asks for more than the outer has left: it gets what is left. - let (inner, after) = with_attempt_budget(1, || { - let inner = with_attempt_budget(10, || boolean(&a, &b, BoolOp::Intersect).is_ok()); - (inner, boolean(&a, &b, BoolOp::Intersect).is_ok()) - }); - assert!(inner && !after); - 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 = (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 = (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 -/// solid as placing a freshly turned one. -#[test] -fn placing_a_body_does_not_turn_its_revolved_faces_again() { - let body = cylinder(Vec3::new(1.0, 2.0, 0.0), Vec3::Z, 3.0, 5.0).unwrap(); - assert!(body.phased); - let m = [[0.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [10.0, 20.0, 30.0, 1.0]]; - crate::body::REPHASED.with(|c| c.set(0)); - let mut placed = body.clone(); - for _ in 0..10 { - placed = crate::place_matrix(&placed, m).unwrap(); - } - assert_eq!(crate::body::REPHASED.with(|c| c.get()), 0, "no placement searched the revolved faces again"); - // A modelling move (a pattern's copy, a hole's tool) still turns them in its own frame. - let _ = crate::transform_matrix(&body, m).unwrap(); - assert_eq!(crate::body::REPHASED.with(|c| c.get()), 1); - crate::body::REPHASED.with(|c| c.set(0)); - assert!(placed.phased); - let unphased = Body { phased: false, ..body.clone() }; - let mut turned = unphased; - for _ in 0..10 { - turned = crate::place_matrix(&turned, m).unwrap(); - } - assert!(crate::body::REPHASED.with(|c| c.get()) > 0, "a body not known to be turned still is"); - let (a, b) = (measure(&placed).unwrap(), measure(&turned).unwrap()); - assert!((a.volume - b.volume).abs() < 1e-9 * a.volume && (a.area - b.area).abs() < 1e-9 * a.area); - 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) { @@ -3137,29 +2433,9 @@ fn a_box_cut_round_a_small_hole_of_a_long_plate_keeps_the_hole() { 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(); + let holed = piece.record().faces.iter().filter(|f| f.loops.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:?}"); } } } - -/// A transform with a perspective term or a singular linear part is refused: placed into the -/// body, it built a revolved ring whose mesh measured hundreds of millions of mm³, and cutting -/// a pocket into it ran for over half an hour before failing. A translation still places it. -#[test] -fn transform_refuses_a_matrix_that_is_not_an_affine_placement() { - let rect = Loop2::polygon(&[Vec2::new(20.0, 0.0), Vec2::new(60.0, 0.0), Vec2::new(60.0, 10.0), Vec2::new(20.0, 10.0)]); - let ring = revolve(&Plane::XZ, &[Region2 { outer: rect, holes: vec![] }], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU).unwrap().remove(0); - // Column-major: the last entry of the third column is a perspective term. - let perspective = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 10.0], [0.0, 0.0, 0.0, 1.0]]; - let flat = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; - for m in [perspective, flat] { - assert!(matches!(crate::transform_matrix(&ring, m), Err(KernelError::Invalid(_))), "{m:?}"); - } - let lifted = crate::transform_matrix(&ring, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 10.0, 1.0]]).unwrap(); - let pocket = box_solid(Vec3::new(37.0, -3.0, 7.0), Vec3::new(43.0, 3.0, 12.0)).unwrap(); - let cut = boolean(&lifted, &pocket, BoolOp::Cut).unwrap().unwrap(); - let removed = measure(&lifted).unwrap().volume - measure(&cut).unwrap().volume; - assert!((removed - 6.0 * 6.0 * 3.0).abs() < 1.0, "{removed}"); -} diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs index 6107619a9..5b5d89bab 100644 --- a/crates/kernel/src/thin_face_tests.rs +++ b/crates/kernel/src/thin_face_tests.rs @@ -5,13 +5,14 @@ //! So does a face pinched to a point, where its boundary touches itself within the tolerance (a //! sphere touching a box's edge leaves one on the box, #1648). +use solidcraft_geom::prelude::*; use std::collections::HashMap; -use solidcraft_geom::Vec3; -use truck_meshalgo::prelude::*; -use truck_modeling as mt; +use solidcore_record::Vec3; +use solidcore_record::brep::{Curve, Loop, Surface}; -use crate::body::p3; +use crate::body::Body; +use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble}; use crate::{BoolOp, build::box_solid, build::sphere, ops::boolean}; /// Triangle sides in the mesh with no triangle on the other side of them, with the points @@ -41,7 +42,7 @@ fn a_lens_thinner_than_the_tolerance_is_meshed() { assert!(union.validity().is_empty(), "{:?}", union.validity()); let size = union.size(); for tol in [size * 1e-2, size * 2.5e-3, size * 1e-3] { - let mesh = union.tessellate(tol).unwrap(); + let mesh = union.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); let faces: std::collections::HashSet = mesh.tri_face.iter().copied().collect(); assert_eq!(faces.len(), union.face_count(), "faces with triangles at {tol}"); assert_eq!(open_sides(&mesh), 0, "open sides at {tol}"); @@ -49,7 +50,7 @@ fn a_lens_thinner_than_the_tolerance_is_meshed() { } /// Twice the signed area of a closed polyline in the XY plane. -fn area2(points: &[mt::Point3]) -> f64 { +fn area2(points: &[Vec3]) -> f64 { points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum() } @@ -59,26 +60,44 @@ fn area2(points: &[mt::Point3]) -> f64 { #[test] fn a_face_touching_its_own_edge_meshes() { let (h, dip) = (0.3175, 2.8e-7); - let v = |x: f64, y: f64| mt::builder::vertex(p3(Vec3::new(x, y, 0.0))); - let (lb, rb, rt, lt) = (v(0.0, 0.0), v(5.0, 0.0), v(5.0, h), v(0.0, h)); - let control = vec![p3(Vec3::new(5.0, h, 0.0)), p3(Vec3::new(2.5, -h - 2.0 * dip, 0.0)), p3(Vec3::new(0.0, h, 0.0))]; - let arch = mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), control); - let arch = mt::Edge::new(&rt, <, mt::Curve::BSplineCurve(arch)); - let wire: mt::Wire = vec![mt::builder::line(&lb, &rb), mt::builder::line(&rb, &rt), arch, mt::builder::line(<, &lb)].into(); - let plane = mt::Plane::new(p3(Vec3::ZERO), p3(Vec3::X), p3(Vec3::Y)); - let face = mt::Face::new(vec![wire], mt::Surface::Plane(plane)); - let shell: mt::Shell = vec![face].into(); + let vertices = vec![[0.0, 0.0, 0.0], [5.0, 0.0, 0.0], [5.0, h, 0.0], [0.0, h, 0.0]]; + let line = |a: usize, b: usize| PartEdge { + nurbs: None, + curve: Curve::Line { start: vertices[a], end: vertices[b] }, + interval: [0.0, 1.0], + vertices: [a as u32, b as u32], + }; + let arch = PartEdge { + nurbs: None, + curve: Curve::Spline { knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points: vec![[5.0, h, 0.0], [2.5, -h - 2.0 * dip, 0.0], [0.0, h, 0.0]] }, + interval: [0.0, 1.0], + vertices: [2, 3], + }; + let edges = vec![line(0, 1), line(1, 2), arch, line(3, 0)]; + let uses = (0..4).map(|e| PartUse { edge: e, forward: true, given: None }).collect(); + let surface = Surface::Plane { origin: [0.0; 3], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] }; + let made = + assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: 1e-7 }, false).unwrap(); + let body = Body::from_record(made.brep).unwrap(); for tol in [0.3, 0.08, 0.02, 0.005] { - let meshed = shell.robust_triangulation_within(Deflection { display: true, ..Deflection::chord(tol) }); - let face = meshed.face_iter().next().unwrap(); - let boundary: Vec = face.boundaries()[0].edge_iter().flat_map(|e| e.oriented_curve().0.into_iter().skip(1)).collect(); - let mesh = face.surface().unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); + // The face's boundary polygon: its edges' polylines round its loop. + let r = body.record(); + let Loop::Edges { edges } = &r.faces[0].loops[0] else { panic!("an edge loop") }; + let mut boundary: Vec = Vec::new(); + for u in edges { + let mut line = mesh.edges[u.edge as usize].clone(); + if !u.forward { + line.reverse(); + } + boundary.extend(line.into_iter().skip(1)); + } let area: f64 = mesh - .faces() - .triangle_iter() + .triangles + .iter() .map(|t| { - let [a, b, c] = [0, 1, 2].map(|i| mesh.positions()[t[i].pos]); - (b - a).cross(c - a).magnitude() / 2.0 + let [a, b, c] = mesh.tri(t).unwrap(); + (b - a).cross(c - a).len() / 2.0 }) .sum(); // The triangles cover the face's boundary polygon, the parts on both sides of the pinch. @@ -96,7 +115,7 @@ fn sphere_touching_a_box_edge_unites_soundly() { assert!(union.validity().is_empty(), "{:?}", union.validity()); let size = union.size(); for tol in [size * 1e-2, size * 2.5e-3, size * 6e-4] { - let faces: std::collections::HashSet = union.tessellate(tol).unwrap().tri_face.into_iter().collect(); + let faces: std::collections::HashSet = union.mesh(&crate::MeshTolerance::chord(tol)).unwrap().tri_face.into_iter().collect(); assert_eq!(faces.len(), union.face_count(), "at {tol}"); } } diff --git a/crates/kernel/src/thread_display_tests.rs b/crates/kernel/src/thread_display_tests.rs index 2e74a35ea..024ec5480 100644 --- a/crates/kernel/src/thread_display_tests.rs +++ b/crates/kernel/src/thread_display_tests.rs @@ -1,117 +1,36 @@ //! Issue 1289: the display mesh of a modelled screw thread (helical B-spline flanks). +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; +use solidcraft_geom::prelude::*; use solidcraft_geom::tess::TessPlan; -use solidcraft_geom::{Mesh, Vec3}; use std::f64::consts::{PI, TAU}; -use std::sync::Arc; -use crate::{Body, DISPLAY_ANGLE, EdgeSpec, FaceSpec, SurfSpec, sew}; +use crate::{Body, DISPLAY_ANGLE}; -/// A helix about Z of radius `r` from angle `a0` to `a1`, rising `pitch` per turn from `z0` at -/// angle 0, as cubic Bézier pieces of at most `TAU / 16`. -fn helix(r: f64, z0: f64, pitch: f64, a0: f64, a1: f64) -> EdgeSpec { - let n = (((a1 - a0).abs() / (TAU / 16.0)).ceil() as usize).max(1); - let h = (a1 - a0) / n as f64; - let k = 4.0 / 3.0 * (h / 4.0).tan(); - let at = |a: f64| Vec3::new(r * a.cos(), r * a.sin(), z0 + pitch * a / TAU); - let rise = Vec3::new(0.0, 0.0, pitch * h / TAU / 3.0); - let turn = |a: f64| Vec3::new(-a.sin(), a.cos(), 0.0) * (r * k); - let mut ctrl = vec![at(a0)]; - for i in 0..n { - let (s, e) = (a0 + h * i as f64, a0 + h * (i + 1) as f64); - ctrl.extend([at(s) + turn(s) + rise, at(e) - turn(e) - rise, at(e)]); - } - EdgeSpec::Chain { degree: 3, ctrl: ctrl.into() } -} - -fn rev(e: &EdgeSpec) -> EdgeSpec { - match e { - EdgeSpec::Chain { degree, ctrl } => EdgeSpec::Chain { degree: *degree, ctrl: ctrl.iter().rev().copied().collect::>() }, - EdgeSpec::Line { a, b } => EdgeSpec::Line { a: *b, b: *a }, - EdgeSpec::Arc { a, b, mid } => EdgeSpec::Arc { a: *b, b: *a, mid: *mid }, - } -} - -fn line(a: Vec3, b: Vec3) -> EdgeSpec { - EdgeSpec::Line { a, b } -} - -fn ends(e: &EdgeSpec) -> (Vec3, Vec3) { - match e { - EdgeSpec::Chain { ctrl, .. } => (ctrl[0], ctrl[ctrl.len() - 1]), - EdgeSpec::Line { a, b } | EdgeSpec::Arc { a, b, .. } => (*a, *b), - } -} - -/// A full circle about Z at height `z`, as two arcs. -fn circle(r: f64, z: f64) -> Vec { - let p = |a: f64| Vec3::new(r * a.cos(), r * a.sin(), z); - vec![EdgeSpec::Arc { a: p(0.3), b: p(0.3 + PI), mid: p(0.3 + PI / 2.0) }, EdgeSpec::Arc { a: p(0.3 + PI), b: p(0.3), mid: p(0.3 + 1.5 * PI) }] -} - -/// A threaded shaft the way a modelled thread usually comes out of a CAD system: an ISO metric -/// ridge (60° flanks, P/8 crest) of `turns` turns wound on a core of the minor diameter, the -/// flanks ruled B-spline surfaces between helices, the crest and the core cylinders trimmed by -/// those helices. +/// A threaded shaft the way the thread feature makes one: an ISO metric ridge (60° flanks, P/8 +/// crest) of `turns` turns wound on a core of the minor diameter, the ridge SMLib's screw sweep +/// of its section (exact helices, the flanks and crest its screw walls, flat ends in the planes +/// through the axis where it starts and stops) joined to the core cylinder, which the flanks then +/// trim along helices. The section reaches a tenth of a pitch into the core along its flanks, so +/// the join cuts it at the core rather than meeting it face to face. fn ridge_thread(major: f64, pitch: f64, turns: f64) -> Body { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; let h = pitch * 3f64.sqrt() / 2.0; let (rc, rm) = (major / 2.0 - 5.0 * h / 8.0, major / 2.0); let (foot, crest) = ((pitch - pitch / 4.0) / 2.0, pitch / 16.0); let z0 = pitch; let len = z0 + pitch * turns + pitch; - let end = TAU * turns; - let fl = helix(rc, z0 - foot, pitch, 0.0, end); - let fu = helix(rc, z0 + foot, pitch, 0.0, end); - let cl = helix(rm, z0 - crest, pitch, 0.0, end); - let cu = helix(rm, z0 + crest, pitch, 0.0, end); - let (fl0, fl1) = ends(&fl); - let (fu0, fu1) = ends(&fu); - let (cl0, cl1) = ends(&cl); - let (cu0, cu1) = ends(&cu); - let at = |r: f64, a: f64, z: f64| Vec3::new(r * a.cos(), r * a.sin(), z); - let mid = z0 + pitch / 2.0; - let out = |a: f64| Vec3::new(a.cos(), a.sin(), 0.0); - let flank = 0.5f64; - let faces = vec![ - FaceSpec { loops: vec![circle(rc, 0.0).iter().rev().map(rev).collect()], surface: SurfSpec::Plane, probe: None }, - FaceSpec { loops: vec![circle(rc, len)], surface: SurfSpec::Plane, probe: None }, - FaceSpec { - loops: vec![circle(rc, 0.0), circle(rc, len).iter().rev().map(rev).collect(), vec![line(fl0, fu0), fu.clone(), line(fu1, fl1), rev(&fl)]], - surface: SurfSpec::Revolved { - a: Vec3::new(rc, 0.0, -1.0), - b: Vec3::new(rc, 0.0, len + 1.0), - axis_origin: Vec3::ZERO, - axis: Vec3::Z, - angle: TAU, - }, - probe: Some((at(rc, PI, z0 * 0.5), out(PI))), - }, - FaceSpec { - loops: vec![vec![fl.clone(), line(fl1, cl1), rev(&cl), line(cl0, fl0)]], - surface: SurfSpec::Ruled { a: fl.clone(), b: cl.clone() }, - probe: Some((at((rc + rm) / 2.0, PI, mid - (foot + crest) / 2.0), out(PI) * flank - Vec3::Z * 0.866)), - }, - FaceSpec { - loops: vec![vec![cu.clone(), line(cu1, fu1), rev(&fu), line(fu0, cu0)]], - surface: SurfSpec::Ruled { a: fu.clone(), b: cu.clone() }, - probe: Some((at((rc + rm) / 2.0, PI, mid + (foot + crest) / 2.0), out(PI) * flank + Vec3::Z * 0.866)), - }, - FaceSpec { - loops: vec![vec![cl.clone(), line(cl1, cu1), rev(&cu), line(cu0, cl0)]], - surface: SurfSpec::Revolved { - a: Vec3::new(rm, 0.0, -1.0), - b: Vec3::new(rm, 0.0, len + 1.0), - axis_origin: Vec3::ZERO, - axis: Vec3::Z, - angle: TAU, - }, - probe: Some((at(rm, PI, mid), out(PI))), - }, - FaceSpec { loops: vec![vec![line(fl0, cl0), line(cl0, cu0), line(cu0, fu0), line(fu0, fl0)]], surface: SurfSpec::Plane, probe: None }, - FaceSpec { loops: vec![vec![line(fl1, fu1), line(fu1, cu1), line(cu1, cl1), line(cl1, fl1)]], surface: SurfSpec::Plane, probe: None }, - ]; - sew(&faces).unwrap() + // The ridge's half width at radius r, along its flanks. + let half = |r: f64| foot + (crest - foot) * (r - rc) / (rm - rc); + let r0 = rc - 0.1 * pitch; + let section = Loop2::polygon(&[Vec2::new(r0, -half(r0)), Vec2::new(rm, -crest), Vec2::new(rm, crest), Vec2::new(r0, half(r0))]); + let plane = Plane { origin: Vec3::new(0.0, 0.0, z0), x: Vec3::X, y: Vec3::Z }; + let ridge = crate::sweep_helix(&plane, &Region2 { outer: section, holes: Vec::new() }, Vec3::ZERO, Vec3::Z, pitch, turns).unwrap(); + let core = Region2 { outer: Loop2::circle(Vec2::ZERO, rc), holes: Vec::new() }; + let core = crate::extrude(&Plane::XY, &[core], 0.0, len).unwrap().pop().unwrap(); + crate::boolean(&core, &ridge, crate::BoolOp::Union).unwrap().unwrap() } fn tol(b: &Body) -> f64 { @@ -127,8 +46,10 @@ struct Quality { } /// Triangles thinner than 1e-3 of their longest side; triangles whose winding disagrees with -/// their vertex normals; the largest gap between a triangle's centre and the surface at the -/// centre's parameters. +/// their vertex normals; the largest gap between a triangle's centre and the surface, at the +/// surface point nearest the centre (a few Newton steps from a corner's parameters: a closed +/// surface's parameters are kept within one period, so a triangle across its seam has corners +/// whose parameters lie a period apart, and their mean is nowhere near the triangle). fn quality(plan: &TessPlan, mesh: &Mesh) -> Quality { let mut q = Quality { tris: mesh.triangles.len(), slivers: 0, flipped: 0, worst_sag: 0.0, min_angle: 180.0 }; for t in &mesh.triangles { @@ -155,8 +76,19 @@ fn quality(plan: &TessPlan, mesh: &Mesh) -> Quality { let Some(s) = f.surface.and_then(|i| plan.surfaces.get(i as usize)) else { continue }; let pos = |k: u32| f.fixed.get(k as usize).copied().unwrap_or_else(|| s.eval(f.uv[k as usize][0], f.uv[k as usize][1]).0); for t in &f.triangles { - let uv = t.iter().fold([0.0, 0.0], |m, &k| [m[0] + f.uv[k as usize][0] / 3.0, m[1] + f.uv[k as usize][1] / 3.0]); let mid = (pos(t[0]) + pos(t[1]) + pos(t[2])) * (1.0 / 3.0); + let mut uv = f.uv[t[0] as usize]; + for _ in 0..8 { + let Some((p, su, sv)) = s.derivs(uv[0], uv[1]) else { break }; + let d = mid - p; + let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv)); + let det = a * c - b * b; + if det.abs() < 1e-300 { + break; + } + let (x, y) = (su.dot(d), sv.dot(d)); + uv = [uv[0] + (c * x - b * y) / det, uv[1] + (a * y - b * x) / det]; + } let (on, n) = s.eval(uv[0], uv[1]); let sag = (on - mid).dot(n).abs(); q.worst_sag = q.worst_sag.max(sag); @@ -193,14 +125,15 @@ fn threads() -> Vec<(String, Body, f64, f64, f64)> { } /// Issue 1289: a modelled thread's faces turn several times around the shaft. The core and the -/// crest cylinders, trimmed by helices (and the core bounded by two circles without a seam -/// edge), had no display plan, and the reference mesher drew them with triangles across the -/// solid. They are now cut along a seam: the display mesh stays on the surfaces. +/// crest cylinders, trimmed by helices, had no display plan, and the reference mesher drew them +/// with triangles across the solid. They are now cut along a seam: the display mesh stays on +/// the surfaces. #[test] fn thread_display_mesh_stays_on_its_surfaces() { for (name, b, d, p, turns) in threads() { let tol = tol(&b); - let plan = b.display_plan_angular(tol, DISPLAY_ANGLE).unwrap_or_else(|e| panic!("{name}: no display plan: {e}")); + let plan = + b.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap_or_else(|e| panic!("{name}: no display plan: {e}")); let mesh = plan.evaluate(); let q = quality(&plan, &mesh); assert!(q.worst_sag <= 1.5 * tol, "{name}: a triangle lies {} mm off its surface (tolerance {tol})", q.worst_sag); @@ -213,12 +146,14 @@ fn thread_display_mesh_stays_on_its_surfaces() { let [a, b2, c] = t.map(|i| mesh.positions[i as usize]); let (ra, rb, rcn) = (r(a), r(b2), r(c)); let centre = r((a + b2 + c) * (1.0 / 3.0)); + // An end disc is flat: its triangles are its boundary's, and one with its three + // corners on the rim (at r = rc) lies on the disc, not on a cylinder. + let end_disc = [a, b2, c].iter().all(|v| v.z.abs() < 1e-9) || [a, b2, c].iter().all(|v| (v.z - (turns + 2.0) * p).abs() < 1e-9); for want in [rc, rm] { - if [ra, rb, rcn].iter().all(|x| (x - want).abs() < 1e-4) { + if !end_disc && [ra, rb, rcn].iter().all(|x| (x - want).abs() < 1e-4) { assert!(centre > want - 2.0 * tol, "{name}: triangle {ti} on the r = {want} cylinder cuts in to {centre}"); } } - let end_disc = [a, b2, c].iter().all(|v| v.z.abs() < 1e-9) || [a, b2, c].iter().all(|v| (v.z - (turns + 2.0) * p).abs() < 1e-9); assert!(end_disc || (centre > rc - 2.0 * tol && centre < rm + 1e-6), "{name}: triangle {ti} at radius {centre}, outside {rc}…{rm}"); } // A mesh within the tolerance of the surfaces is within area × tolerance of the volume. @@ -226,9 +161,9 @@ fn thread_display_mesh_stays_on_its_surfaces() { let want = ridge_volume(d, p, turns); assert!((m.volume - want).abs() < m.area * tol, "{name}: display mesh volume {}, the thread's {want}", m.volume); // The reference mesh (picking, measuring, the viewport without GPU tessellation) is the same. - let reference = b.reference_display_mesh_angular(tol, DISPLAY_ANGLE).unwrap(); + let reference = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap(); assert_eq!(reference.triangles.len(), mesh.triangles.len(), "{name}"); - let measured = b.tessellate(tol * 0.1).unwrap().measure().volume; + let measured = b.mesh(&crate::MeshTolerance::chord(tol * 0.1)).unwrap().measure().volume; assert!((measured - want).abs() < want * 1e-3, "{name}: measured volume {measured}, the thread's {want}"); } } @@ -238,7 +173,9 @@ fn thread_display_mesh_stays_on_its_surfaces() { #[test] fn thread_display_mesh_has_no_degenerate_or_flipped_triangles() { for (name, b, ..) in threads() { - let plan = b.display_plan_angular(tol(&b), DISPLAY_ANGLE).unwrap_or_else(|e| panic!("{name}: no display plan: {e}")); + let plan = b + .mesh_plan(&crate::MeshTolerance { chord: tol(&b), angle: Some(DISPLAY_ANGLE) }) + .unwrap_or_else(|e| panic!("{name}: no display plan: {e}")); let mesh = plan.evaluate(); let q = quality(&plan, &mesh); assert!(q.tris > 1000, "{name}: {} triangles", q.tris); diff --git a/crates/kernel/src/thread_tests.rs b/crates/kernel/src/thread_tests.rs index 38c53699c..ee1e76373 100644 --- a/crates/kernel/src/thread_tests.rs +++ b/crates/kernel/src/thread_tests.rs @@ -2,7 +2,7 @@ use std::f64::consts::PI; -use solidcraft_geom::{Plane, Vec2, Vec3}; +use solidcore_record::{Plane, Vec2, Vec3}; use crate::{BoolOp, cylinder, faceted_boolean, sweep_helix_mesh}; @@ -18,7 +18,9 @@ fn faceted_cut_of_a_helical_groove() { let section = [Vec2::new(1.2, -0.06), Vec2::new(1.6, -0.06), Vec2::new(1.6, 0.06), Vec2::new(1.2, 0.06)]; let groove = sweep_helix_mesh(&plane, §ion, base, k, p, 5.0, 48).unwrap(); let cut = faceted_boolean(&shaft, &groove, BoolOp::Cut, 1e-3).unwrap().unwrap(); - let m = cut.tessellate(0.01).unwrap().measure(); + // The cut's own volume (SMLib's, of its exact faces): a mesh's at 0.01 mm sags inside the + // shaft's round wall by 0.18 mm³, five times the 3 % the groove is held to. + let m = crate::measure(&cut).unwrap(); // In the shaft from z = 0: the section (r 1.2…1.5, 0.12 tall) for 4 turns, plus the part of // the first turn's section above z = 0 (its z range is ±0.06 about the turn's height). let per_turn = 2.0 * PI * 0.12 * (1.5f64.powi(2) - 1.2f64.powi(2)) / 2.0; @@ -32,14 +34,14 @@ fn faceted_cut_into_a_bore() { let nut = crate::box_solid(Vec3::new(-3.0, -3.0, 0.0), Vec3::new(3.0, 3.0, 2.0)).unwrap(); let bore = cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 1.0), 1.23, 4.0).unwrap(); let nut = crate::boolean(&nut, &bore, BoolOp::Cut).unwrap().unwrap(); - let v0 = nut.tessellate(1e-3).unwrap().measure().volume; + let v0 = nut.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume; let (p, k) = (0.5, Vec3::new(0.0, 0.0, 1.0)); let base = Vec3::new(0.0, 0.0, -p); let plane = Plane { origin: base, x: Vec3::new(1.0, 0.0, 0.0), y: k }; let section = [Vec2::new(1.1, -0.1), Vec2::new(1.5, -0.1), Vec2::new(1.5, 0.1), Vec2::new(1.1, 0.1)]; let groove = sweep_helix_mesh(&plane, §ion, base, k, p, 6.0, 48).unwrap(); let cut = faceted_boolean(&nut, &groove, BoolOp::Cut, 2.5e-3).unwrap().unwrap(); - let removed = v0 - cut.tessellate(1e-3).unwrap().measure().volume; + let removed = v0 - cut.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume; // Four turns of the section's part outside the bore (r 1.23…1.5, 0.2 tall). let want = 4.0 * PI * 0.2 * (1.5f64.powi(2) - 1.23f64.powi(2)); assert!((removed - want).abs() < 0.03 * want, "{removed} vs {want}"); @@ -58,7 +60,27 @@ fn a_long_thread_cuts_without_a_deep_tree() { let section = [Vec2::new(3.3, -0.08), Vec2::new(4.1, -0.5), Vec2::new(4.1, 0.5), Vec2::new(3.3, 0.08)]; let groove = sweep_helix_mesh(&plane, §ion, base, k, p, len / p + 2.0, 48).unwrap(); let cut = faceted_boolean(&shaft, &groove, BoolOp::Cut, p * 0.005).unwrap().unwrap(); - let v = cut.tessellate(0.01).unwrap().measure().volume; + let v = cut.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().volume; let v0 = PI * r * r * len; assert!(v < v0 * 0.95 && v > v0 * 0.6, "{v} of {v0}"); } + +/// What lies past each end of a shaft's face: the d16 collar under it, the air over its cap. +#[test] +fn material_past_the_ends_of_a_shaft_face() { + let k = Vec3::new(0.0, 0.0, 1.0); + let collar = cylinder(Vec3::ZERO, k, 8.0, 10.0).unwrap(); + let shaft = cylinder(Vec3::new(0.0, 0.0, 10.0), k, 5.0, 25.0).unwrap(); + let part = crate::boolean(&collar, &shaft, BoolOp::Union).unwrap().unwrap(); + let c = crate::cylinder_face_at(&part, Vec3::new(5.0, 0.0, 20.0)).unwrap(); + assert!((c.radius - 5.0).abs() < 1e-9 && c.start < c.end, "{c:?}"); + let at = |z: f64| (z - c.axis_point.z) / c.axis.z; + let (lo, hi) = (at(10.0).min(at(35.0)), at(10.0).max(at(35.0))); + assert!((lo - c.start).abs() < 1e-6 && (hi - c.end).abs() < 1e-6, "{c:?}"); + let below = if c.axis.z > 0.0 { (c.start - 2.25, c.start - 1.5) } else { (c.end + 1.5, c.end + 2.25) }; + let above = if c.axis.z > 0.0 { (c.end + 1.5, c.end + 2.25) } else { (c.start - 2.25, c.start - 1.5) }; + assert!(crate::material_in_ring(&part, &c, 4.19, 5.0, below).unwrap(), "the collar is past the shaft's bottom end"); + assert!(!crate::material_in_ring(&part, &c, 4.19, 5.0, above).unwrap(), "nothing is past its top end"); + // Along the face itself the ring is the shaft's own material. + assert!(crate::material_in_ring(&part, &c, 4.19, 4.99, (lo + 5.0, lo + 6.0)).unwrap()); +} diff --git a/crates/kernel/src/tool_reseam.rs b/crates/kernel/src/tool_reseam.rs deleted file mode 100644 index e0c09776c..000000000 --- a/crates/kernel/src/tool_reseam.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! Retry a failed cut with different boundaries between a round tool's faces (#2387). -//! Every curved support must be a revolution about the same axis and every planar support -//! perpendicular to it. Turning this closed solid about that axis changes only its seams. - -use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, InnerSpace, Transform}; - -use super::{BoolOp, boolean_via, boolean_whole, nudged, transform}; -use crate::body::{Body, from_p3}; -use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record}; -use crate::{guard, record}; - -thread_local! { - static ACTIVE: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// Exact revolution axes, rather than a fit to sampled normals: splines and affine -/// distortions of round tools must never be mistaken for rotational symmetry. -fn axis(body: &Body) -> Option<(Vec3, Vec3)> { - if body.is_mesh() || body.shell_count() != 1 || body.face_count() > 64 { - return None; - } - guard("round tool axis", || { - let mut axes = Vec::new(); - let mut normals = Vec::new(); - for face in body.solid.face_iter() { - match face.surface() { - mt::Surface::Plane(p) => { - let n = p.normal(); - let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return Ok(None) }; - normals.push(n); - } - mt::Surface::RevolutedCurve(s) => { - let m = s.transform(); - let (x, y, z) = (m.x.truncate(), m.y.truncate(), m.z.truncate()); - // Only rigid transforms: no elliptic scaling of the revolution. - if [x, y, z].iter().any(|v| (v.magnitude2() - 1.0).abs() > 1e-9) - || [x.dot(y), x.dot(z), y.dot(z)].iter().any(|v| v.abs() > 1e-9) - || m.x.w != 0.0 - || m.y.w != 0.0 - || m.z.w != 0.0 - || m.w.w != 1.0 - { - return Ok(None); - } - let o = from_p3(m.transform_point(s.entity().origin())); - let a = m.transform_vector(s.entity().axis()); - let Some(a) = Vec3::new(a.x, a.y, a.z).normalized() else { return Ok(None) }; - axes.push((o, a)); - } - _ => return Ok(None), - } - } - let Some(&(o, a)) = axes.first() else { return Ok(None) }; - let tol = (body.size() * 1e-9).max(1e-10); - let same = axes.iter().all(|(p, d)| a.cross(*d).len() < 1e-9 && (*p - o).cross(a).len() < tol); - // Surface orientation can reverse the same axis. Choose a stable direction for retries. - let first = [a.x, a.y, a.z].into_iter().find(|v| v.abs() > 1e-9).unwrap_or(1.0); - let a = if first < 0.0 { -a } else { a }; - Ok((same && normals.iter().all(|n| n.cross(a).len() < 1e-9)).then_some((o, a))) - }) - .ok() - .flatten() -} - -pub(super) fn cut(target: &Body, tool: &Body) -> Option { - if ACTIVE.with(|a| a.get()) { - return None; - } - let (origin, axis) = axis(tool)?; - ACTIVE.with(|a| a.set(true)); - let result = guard("cut with reseamed tool", || { - let counts = record::counts(&[target, tool]); - // Bounded exact retries. Keep the original error if neither can be verified. - for angle in [0.3, -0.3, 0.7, -0.7] { - let turned = transform(tool, Vec3::ZERO, origin, axis, angle)?; - let (result, diagnostics) = capture_boolean_diagnostics(|| boolean_via(target, &turned, BoolOp::Cut, &boolean_whole)); - if let Ok(Some(body)) = result - && crate::boolean_guard::check_retry(target, tool, BoolOp::Cut, Some(&body)).is_ok() - { - let body = nudged(body, &turned, &counts); - merge(diagnostics); - let mut event = BooleanFallback::new(BooleanStrategy::ToolReseam); - event.rotation_rad = angle; - record(event); - return Ok(Some(body)); - } - } - Ok(None) - }) - .ok() - .flatten(); - ACTIVE.with(|a| a.set(false)); - result -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::transform_matrix; - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - - fn drill(angle: f64) -> Body { - let profile = - Region2 { outer: Loop2::polygon(&[Vec2::new(0., 1.), Vec2::new(2.5, 1.), Vec2::new(2.5, -10.), Vec2::new(0., -11.5)]), holes: vec![] }; - crate::revolve(&Plane::XZ, &[profile], Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap() - } - - #[test] - fn only_complete_coaxial_revolutions_can_be_reseamed() { - let tool = drill(std::f64::consts::TAU); - assert!(axis(&tool).is_some()); - let placed = transform(&tool, Vec3::new(11., -7., 5.), Vec3::ZERO, Vec3::new(1., 2., 3.), 0.8).unwrap(); - let (o, a) = axis(&placed).unwrap(); - let turned = transform(&placed, Vec3::ZERO, o, a, 0.3).unwrap(); - assert!((crate::measure(&placed).unwrap().volume - crate::measure(&turned).unwrap().volume).abs() < 1e-6); - // A partial turn's radial caps would move; an affine scale can make the bore elliptic. - assert!(axis(&drill(std::f64::consts::PI)).is_none()); - let scaled = transform_matrix(&tool, [[2., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]).unwrap(); - assert!(axis(&scaled).is_none()); - let block = crate::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); - assert!(axis(&block).is_none()); - } -} diff --git a/crates/kernel/src/topo.rs b/crates/kernel/src/topo.rs index eb4dece08..0e0747416 100644 --- a/crates/kernel/src/topo.rs +++ b/crates/kernel/src/topo.rs @@ -1,17 +1,24 @@ //! Topology counts comparable with kernels that use periodic faces and closed edges. //! -//! Our kernel splits a full cylinder into two half faces and a circle into two arcs. Faces -//! are classified from their tessellation (plane, cylinder, sphere, other); adjacent faces on -//! the same analytic surface are merged, edges between merged faces disappear, and chains of -//! edges through vertices that only join two pieces of the same edge are counted once. +//! A body may hold a surface in several faces (a full cylinder as two half faces, a circle as two +//! arcs). Each face's surface is the record's own ([`crate::offset::surf_of`]: plane, cylinder, +//! sphere, cone, torus; free-form faces by their surface record); adjacent faces on one surface +//! are merged, edges between merged faces disappear, and chains of edges through vertices that +//! only join two pieces of one edge are counted once. -use std::collections::{BTreeMap, HashMap}; +use solidcraft_geom::prelude::*; +use std::collections::{BTreeMap, HashMap, HashSet}; use serde::Serialize; -use solidcraft_geom::{Mesh, UnitVec3, Vec3}; +use solidcore_record::Vec3; +use solidcore_record::brep::{Brep, Loop}; +use solidcraft_geom::{Mesh, UnitVec3}; use crate::Result; -use crate::body::{Body, from_p3}; +use crate::body::Body; +use crate::heal::{edge_points, find, on_split_line}; +use crate::history::edge_faces; +use crate::offset::{Surf, surf_of}; #[derive(Clone, Debug, Default, Serialize, PartialEq)] pub struct TopoCounts { @@ -21,399 +28,89 @@ pub struct TopoCounts { pub face_types: BTreeMap, } -#[derive(Clone, Copy, Debug, PartialEq)] -enum Surf { - Plane { n: Vec3, d: f64 }, - Cylinder { axis: UnitVec3, p: Vec3, r: f64 }, - Sphere { c: Vec3, r: f64 }, - Cone { axis: Vec3, apex: Vec3, cos: f64 }, - Other(usize), -} - -impl Surf { - fn name(&self) -> &'static str { - match self { - Surf::Plane { .. } => "plane", - Surf::Cylinder { .. } => "cylinder", - Surf::Sphere { .. } => "sphere", - Surf::Cone { .. } => "cone", - Surf::Other(_) => "other", - } - } - fn same(&self, o: &Surf, tol: f64) -> bool { - match (*self, *o) { - (Surf::Plane { n, d }, Surf::Plane { n: n2, d: d2 }) => n.dot(n2) > 1.0 - 1e-9 && (d - d2).abs() < tol, - (Surf::Cylinder { axis, p, r }, Surf::Cylinder { axis: a2, p: p2, r: r2 }) => { - let off = p2 - p; - axis.dot(a2).abs() > 1.0 - 1e-6 && (r - r2).abs() < tol && (off - axis * off.dot(axis)).len() < tol - } - (Surf::Sphere { c, r }, Surf::Sphere { c: c2, r: r2 }) => c.dist(c2) < tol && (r - r2).abs() < tol, - (Surf::Cone { axis, apex, cos }, Surf::Cone { axis: a2, apex: p2, cos: c2 }) => { - axis.dot(a2) > 1.0 - 1e-5 && (cos - c2).abs() < 1e-4 && apex.dist(p2) < tol * 10.0 - } - _ => false, - } +/// The kind of a face's surface, as counted. +fn name(s: Option<&Surf>) -> &'static str { + match s { + Some(Surf::Plane { .. }) => "plane", + Some(Surf::Cylinder { .. }) => "cylinder", + Some(Surf::Sphere { .. }) => "sphere", + Some(Surf::Cone { .. }) => "cone", + Some(Surf::Torus { .. }) | None => "other", } } -/// Least-squares circle through 2D points (Kåsa fit): centre and radius. -fn fit_circle(pts: &[(f64, f64)]) -> Option<(f64, f64, f64)> { - let n = pts.len() as f64; - if pts.len() < 3 { - return None; - } - let (mx, my) = pts.iter().fold((0.0, 0.0), |a, p| (a.0 + p.0 / n, a.1 + p.1 / n)); - let (mut suu, mut suv, mut svv, mut suuu, mut svvv, mut suvv, mut svuu) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); - for (x, y) in pts { - let (u, v) = (x - mx, y - my); - suu += u * u; - suv += u * v; - svv += v * v; - suuu += u * u * u; - svvv += v * v * v; - suvv += u * v * v; - svuu += v * u * u; - } - let det = suu * svv - suv * suv; - if det.abs() < 1e-18 { - return None; - } - let b1 = 0.5 * (suuu + suvv); - let b2 = 0.5 * (svvv + svuu); - let uc = (b1 * svv - b2 * suv) / det; - let vc = (suu * b2 - suv * b1) / det; - let r = (uc * uc + vc * vc + (suu + svv) / n).sqrt(); - Some((uc + mx, vc + my, r)) +/// The faces of a record with their surfaces, for telling which lie on one surface. +struct Faces<'a> { + record: &'a Brep, + surfs: Vec>, + tol: f64, } -fn classify(pts: &[Vec3], nrm: &[Vec3], tol: f64, id: usize) -> Surf { - let Some(&n0) = nrm.first() else { return Surf::Other(id) }; - let Some(&p0) = pts.first() else { return Surf::Other(id) }; - if nrm.iter().all(|n| n.dot(n0) > 1.0 - 1e-5) { - let n = n0.normalized().unwrap_or(Vec3::Z); - if pts.iter().all(|p| (p.dot(n) - p0.dot(n)).abs() < tol) { - return Surf::Plane { n, d: p0.dot(n) }; - } +impl<'a> Faces<'a> { + fn new(record: &'a Brep, tol: f64) -> Faces<'a> { + Faces { record, surfs: (0..record.faces.len()).map(|f| surf_of(record, f)).collect(), tol } } - // Cylinder: all normals perpendicular to one axis. - let far = nrm.iter().copied().min_by(|a, b| a.dot(n0).abs().total_cmp(&b.dot(n0).abs())).unwrap_or(n0); - if let Some(axis) = n0.cross(far).unit() - && nrm.iter().all(|n| n.dot(axis).abs() < 2e-3) - { - let u = axis.any_perp(); - let v = axis.cross(u); - let pl: Vec<(f64, f64)> = pts.iter().map(|p| (p.dot(u), p.dot(v))).collect(); - if let Some((cu, cv, r)) = fit_circle(&pl) - && pl.iter().all(|(x, y)| ((x - cu).hypot(y - cv) - r).abs() < tol.max(r * 2e-3)) - { - let axis = if axis.x + axis.y * 1e-3 + axis.z * 1e-6 < 0.0 { -axis } else { axis }; - return Surf::Cylinder { axis, p: u * cu + v * cv, r }; - } - } - // Cone: normals at a constant angle to one axis; the apex lies on every tangent plane. - if let Some((axis, cos)) = cone_signature(&pts.iter().copied().zip(nrm.iter().copied()).collect::>()) - && cos.abs() > 1e-3 - && cos.abs() < 1.0 - 1e-3 - { - // Least squares: n_i · v = n_i · p_i. - let mut m = [[0.0f64; 3]; 3]; - let mut r = [0.0f64; 3]; - for (p, n) in pts.iter().zip(nrm) { - let nv = [n.x, n.y, n.z]; - let k = n.dot(*p); - for i in 0..3 { - for j in 0..3 { - m[i][j] += nv[i] * nv[j]; - } - r[i] += nv[i] * k; - } - } - if let Some(v) = solve3(m, r) { - let apex = Vec3::new(v[0], v[1], v[2]); - if pts.iter().zip(nrm).all(|(p, n)| (*p - apex).dot(*n).abs() < tol.max(1e-6) * 10.0) { - return Surf::Cone { axis, apex, cos }; - } - } - } - // Sphere: algebraic least-squares fit |p|² = 2c·p + k, then every point at the same distance. - if let Some((c, r)) = fit_sphere(pts) { - let spread = pts.iter().map(|p| p.dist(p0)).fold(0.0, f64::max); - // Normals radial too (a torus strip can fit a sphere's points closely). - let radial = pts.iter().zip(nrm).all(|(p, n)| (*p - c).normalized().is_some_and(|d| d.dot(*n).abs() > 1.0 - 2e-3)); - if spread > tol && radial && pts.iter().all(|p| (p.dist(c) - r).abs() < tol.max(r * 2e-3)) && r < spread * 1e4 { - return Surf::Sphere { c, r }; - } - } - Surf::Other(id) -} -/// Per-face vertex samples (position, normal) from the tessellation. -/// -/// A vertex is listed once per face, where its first triangle lists it: the triangles around -/// it would repeat it about six times, and every reader (nearest normal, cone signature) gives -/// the same answer without the repeats, which only multiplied their work. -fn face_vertices(mesh: &Mesh, nf: usize) -> Vec> { - let mut out: Vec> = vec![Vec::new(); nf]; - // The face that last listed each vertex (a vertex shared by faces may be listed again). - let mut listed = vec![u32::MAX; mesh.positions.len()]; - for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) { - for &k in t { - if listed.get(k as usize) == Some(f) { - continue; - } - if let (Some(p), Some(n), Some(v)) = (mesh.positions.get(k as usize), mesh.normals.get(k as usize), out.get_mut(*f as usize)) { - v.push((*p, *n)); - if let Some(slot) = listed.get_mut(k as usize) { - *slot = *f; - } - } - } + fn surf(&self, f: usize) -> Option<&Surf> { + self.surfs.get(f).and_then(Option::as_ref) } - out -} -/// Normal of face `f` nearest to `p` (the first of equally near vertices). -fn normal_near(verts: &[(Vec3, Vec3)], p: Vec3) -> Option { - let mut best: Option<(f64, Vec3)> = None; - for (q, n) in verts { - let d = q.dist(p); - if best.is_none_or(|(b, _)| d.total_cmp(&b).is_lt()) { - best = Some((d, *n)); - } + fn planar(&self, f: usize) -> bool { + matches!(self.surf(f), Some(Surf::Plane { .. })) } - best.map(|(_, n)| n) -} -/// Cone signature of a non-analytic face: (axis, cos of the normal/axis angle) when all normals -/// make the same angle with one axis. -fn cone_signature(verts: &[(Vec3, Vec3)]) -> Option<(Vec3, f64)> { - let n0 = verts.first()?.1; - let n1 = verts.iter().map(|v| v.1).max_by(|a, b| (*a - n0).len().total_cmp(&(*b - n0).len()))?; - let n2 = verts.iter().map(|v| v.1).max_by(|a, b| (*a - n0).cross(n1 - n0).len().total_cmp(&(*b - n0).cross(n1 - n0).len()))?; - let mut a = (n1 - n0).cross(n2 - n0).normalized()?; - if a.x + a.y * 1e-3 + a.z * 1e-6 < 0.0 { - a = -a; - } - let c = n0.dot(a); - verts.iter().all(|v| (v.1.dot(a) - c).abs() < 2e-3).then_some((a, c)) -} - -/// Do adjacent faces `a` and `b` (sharing the edge polyline `edge`) lie on one surface? -/// Analytic classes compare parameters; other faces must join smoothly along the edge and have -/// the same cone signature (or both have none). -fn same_surface(surfs: &[Surf], verts: &[Vec<(Vec3, Vec3)>], edge: Option<&Vec>, a: usize, b: usize, tol: f64) -> bool { - let (Some(sa), Some(sb)) = (surfs.get(a), surfs.get(b)) else { return false }; - match (sa, sb) { - (Surf::Other(_), Surf::Other(_)) => {} - _ => return sa.same(sb, tol), - } - let (Some(va), Some(vb), Some(e)) = (verts.get(a), verts.get(b), edge) else { return false }; - let smooth = e.iter().all(|p| match (normal_near(va, *p), normal_near(vb, *p)) { - (Some(na), Some(nb)) => na.dot(nb) > 1.0 - 2e-3, - _ => false, - }); - if !smooth { - return false; - } - match (cone_signature(va), cone_signature(vb)) { - (Some((xa, ca)), Some((xb, cb))) => xa.dot(xb) > 1.0 - 1e-4 && (ca - cb).abs() < 1e-3, - (None, None) => true, - _ => false, - } -} - -/// Solve a 3×3 system (Cramer's rule). -fn solve3(m: [[f64; 3]; 3], r: [f64; 3]) -> Option<[f64; 3]> { - let det = |a: [[f64; 3]; 3]| { - a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) - + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) - }; - let d = det(m); - if d.abs() < 1e-12 { - return None; - } - let mut out = [0.0; 3]; - for (k, o) in out.iter_mut().enumerate() { - let mut mk = m; - for (row, rv) in mk.iter_mut().zip(r) { - row[k] = rv; - } - *o = det(mk) / d; - } - Some(out) -} - -fn find(p: &mut [usize], mut i: usize) -> usize { - while let Some(&q) = p.get(i) { - if q == i { - break; - } - i = q; - } - i -} - -/// Per edge (in `Body::edges` order): is it a seam between two pieces of the same surface? -pub fn seam_flags(b: &Body, mesh: &Mesh) -> Vec { - let solid = &*b.solid; - let nf = solid.face_iter().count(); - let tol = (b.size() * 1e-4).max(1e-6); - let surfs = classify_faces(b, mesh, nf, tol); - let verts = face_vertices(mesh, nf); - // Faces cut from one surface (an imported face split where it wraps around a closed - // surface) carry the very same surface: the edge between them is a seam. - let surf_keys: Vec = solid.face_iter().map(|f| format!("{:?}", f.surface())).collect(); - let mut faces_of: HashMap> = HashMap::new(); - let mut order: Vec = Vec::new(); - for (fi, f) in solid.face_iter().enumerate() { - for e in f.edge_iter() { - let k = format!("{:?}", e.id()); - let v = faces_of.entry(k.clone()).or_insert_with(|| { - order.push(k); - Vec::new() - }); - if !v.contains(&fi) { - v.push(fi); - } - } - } - order - .iter() - .enumerate() - .map(|(ei, k)| match faces_of.get(k).map(Vec::as_slice) { - Some([a, b2]) => { - (!matches!(surfs.get(*a), Some(Surf::Plane { .. })) && same_surface(&surfs, &verts, mesh.edges.get(ei), *a, *b2, tol * 10.0)) - || (surf_keys.get(*a).is_some_and(|k| Some(k) == surf_keys.get(*b2)) && !matches!(surfs.get(*a), Some(Surf::Plane { .. }))) - } - _ => false, - }) - .collect() -} - -/// Least-squares sphere through points: centre and radius. -fn fit_sphere(pts: &[Vec3]) -> Option<(Vec3, f64)> { - if pts.len() < 4 { - return None; - } - // Centre the data for conditioning. - let m = pts.iter().fold(Vec3::ZERO, |a, p| a + *p) / pts.len() as f64; - let mut a = [[0.0f64; 5]; 4]; - for p in pts { - let q = *p - m; - let row = [2.0 * q.x, 2.0 * q.y, 2.0 * q.z, 1.0]; - let rhs = q.dot(q); - for i in 0..4 { - for j in 0..4 { - a[i][j] += row[i] * row[j]; - } - a[i][4] += row[i] * rhs; - } - } - for col in 0..4 { - let piv = (col..4).max_by(|x, y| a[*x][col].abs().total_cmp(&a[*y][col].abs()))?; - if a[piv][col].abs() < 1e-18 { - return None; - } - a.swap(col, piv); - for r in 0..4 { - if r != col { - let f = a[r][col] / a[col][col]; - let prow = a[col]; - for (x, v) in a[r].iter_mut().zip(prow) { - *x -= f * v; - } - } - } - } - let c = Vec3::new(a[0][4] / a[0][0], a[1][4] / a[1][1], a[2][4] / a[2][2]); - let k = a[3][4] / a[3][3]; - let r2 = k + c.dot(c); - (r2 > 0.0 && r2.is_finite()).then(|| (c + m, r2.sqrt())) -} - -fn classify_faces(b: &Body, mesh: &Mesh, nf: usize, tol: f64) -> Vec { - let mut pts: Vec> = vec![Vec::new(); nf]; - let mut nrm: Vec> = vec![Vec::new(); nf]; - for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) { - for &k in t { - if let (Some(p), Some(n), Some(pv), Some(nv)) = - (mesh.positions.get(k as usize), mesh.normals.get(k as usize), pts.get_mut(*f as usize), nrm.get_mut(*f as usize)) - { - pv.push(*p); - nv.push(*n); - } - } - } - // A point where one face's corners disagree on the normal is singular (a cone's apex): - // leave it out of the fit. - for (pv, nv) in pts.iter_mut().zip(nrm.iter_mut()) { - let key = |p: &Vec3| ((p.x / tol).round() as i64, (p.y / tol).round() as i64, (p.z / tol).round() as i64); - let mut first: HashMap<(i64, i64, i64), Vec3> = HashMap::new(); - let mut bad: std::collections::HashSet<(i64, i64, i64)> = std::collections::HashSet::new(); - for (p, n) in pv.iter().zip(nv.iter()) { - let k = key(p); - match first.get(&k) { - Some(m) if m.dot(*n) < 0.999 => { - bad.insert(k); - } - Some(_) => {} - None => { - first.insert(k, *n); - } - } - } - if !bad.is_empty() && bad.len() * 4 < first.len() { - let keep: Vec = pv.iter().map(|p| !bad.contains(&key(p))).collect(); - let mut it = keep.iter(); - pv.retain(|_| it.next().copied().unwrap_or(true)); - let mut it = keep.iter(); - nv.retain(|_| it.next().copied().unwrap_or(true)); - } - } - let fitted = (0..nf).map(|i| classify(pts.get(i).map(Vec::as_slice).unwrap_or(&[]), nrm.get(i).map(Vec::as_slice).unwrap_or(&[]), tol * 10.0, i)); - // A sliver (a strip one triangle wide) has too few distinct samples to fit: its points - // can fit a sphere or nothing. Where the fit finds no plane or cylinder, take the face's - // exact surface when that is a plane, cylinder or sphere. - let exact_tol = (b.size() * 1e-7).max(1e-9) * 100.0; - let faces: Vec<_> = b.solid.face_iter().collect(); - fitted - .enumerate() - .map(|(i, fit)| match (fit, faces.get(i)) { - (Surf::Sphere { .. } | Surf::Other(_), Some(face)) => match crate::offset::surf_of(face, exact_tol) { - Some(crate::offset::Surf::Plane { n, d }) => Surf::Plane { n, d }, - Some(crate::offset::Surf::Cylinder { o, a, r, .. }) => match a.unit() { - Some(a) => Surf::Cylinder { axis: if a.x + a.y * 1e-3 + a.z * 1e-6 < 0.0 { -a } else { a }, p: o, r }, - None => fit, - }, - Some(crate::offset::Surf::Sphere { c, r, .. }) => Surf::Sphere { c, r }, - _ => fit, + /// Do faces `a` and `b` lie on one surface: the same analytic surface, or the very same + /// free-form surface record (pieces cut from one surface)? + fn same(&self, a: usize, b: usize) -> bool { + match (self.surf(a), self.surf(b)) { + (Some(x), Some(y)) => x.same(y, self.tol), + (None, None) => match (self.record.faces.get(a), self.record.faces.get(b)) { + (Some(x), Some(y)) => x.surface == y.surface, + _ => false, }, - _ => fit, + _ => false, + } + } + + /// The record vertices on face `f`'s loops. + fn vertices(&self, f: usize) -> Vec { + let Some(face) = self.record.faces.get(f) else { return Vec::new() }; + face.loops + .iter() + .flat_map(|l| match l { + Loop::Edges { edges } => edges.iter().filter_map(|u| self.record.edges.get(u.edge as usize)).flat_map(|e| e.vertices).collect(), + Loop::Vertex { vertex } => vec![*vertex], + }) + .filter_map(|v| self.record.vertices.get(v as usize).map(|v| Vec3::from(v.point))) + .collect() + } +} + +/// Per edge (in `Body::edges` order): is it a seam of a curved surface, between two pieces of it +/// or where one face of it meets itself (a whole turn of a cylinder, its seam used twice)? +/// `mesh` is the body's tessellation, whose edges are the record's. +pub fn seam_flags(b: &Body, _mesh: &Mesh) -> Vec { + let record = b.record(); + let faces = Faces::new(record, (b.size() * 1e-4).max(1e-6) * 10.0); + record + .edges + .iter() + .zip(edge_faces(record)) + .map(|(e, fs)| match fs[..] { + [x, y] => !faces.planar(x) && faces.same(x, y), + [x] => e.uses.len() == 2 && !faces.planar(x), + _ => false, }) .collect() } -/// Merged face/edge/vertex counts (see module docs). `mesh` must be `b.tessellate(..)`. -/// The point halfway along a polyline (by length). -fn halfway(pl: &[Vec3]) -> Option { - let total: f64 = pl.windows(2).map(|w| w[0].dist(w[1])).sum(); - let mut left = total * 0.5; - for w in pl.windows(2) { - let l = w[0].dist(w[1]); - if l >= left && l > 0.0 { - return Some(w[0] + (w[1] - w[0]) * (left / l)); - } - left -= l; - } - pl.first().copied() -} - +/// Merged face/edge/vertex counts (see module docs). `mesh` must be `b.mesh(..)`: faces of no +/// area in it don't count. pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result { - let solid = &*b.solid; - let nf = solid.face_iter().count(); + let record = b.record(); + let nf = record.faces.len(); let tol = (b.size() * 1e-4).max(1e-6); - let surfs = classify_faces(b, mesh, nf, tol); - let verts = face_vertices(mesh, nf); + let faces = Faces::new(record, tol * 10.0); // Zero-area faces (a revolved profile edge lying on the axis) don't count. let mut area = vec![0.0f64; nf]; for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) { @@ -422,111 +119,72 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result { } } let tiny = (b.size() * 1e-6).powi(2); - let degenerate: Vec = area.iter().map(|a| *a < tiny).collect(); - let is_deg = |f: usize| degenerate.get(f).copied().unwrap_or(false); + let is_deg = |f: usize| area.get(f).is_some_and(|a| *a < tiny); // Edge → faces, edge → vertices. Vertices and edges lying on each other count once (two // tangent holes touch along a line that both bodies' pieces carry): welded by position, - // edges by their ends and the point halfway along them. + // edges by their ends and their middle point. let q = (b.size() * 1e-6).max(1e-9); let cell = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64); - let mut edge_faces: HashMap> = HashMap::new(); - let mut edge_verts: HashMap = HashMap::new(); - // Welded edge → a truck edge index (for its sampled polyline in `mesh.edges`). - let mut edge_rep: HashMap = HashMap::new(); - let mut eid: HashMap = HashMap::new(); - let mut weld_e: HashMap<(usize, usize, (i64, i64, i64)), usize> = HashMap::new(); let mut weld_v: HashMap<(i64, i64, i64), usize> = HashMap::new(); - for (fi, f) in solid.face_iter().enumerate() { - for e in f.edge_iter() { - let key = format!("{:?}", e.id()); - let n = eid.len(); - let ei = *eid.entry(key).or_insert(n); - let mut vix = |v: &truck_modeling::Vertex| { - let n = weld_v.len(); - *weld_v.entry(cell(from_p3(v.point()))).or_insert(n) - }; - let (a, bb) = (vix(e.front()), vix(e.back())); - let mid = mesh.edges.get(ei).and_then(|pl| halfway(pl)).unwrap_or_else(|| (from_p3(e.front().point()) + from_p3(e.back().point())) * 0.5); - let n = weld_e.len(); - let we = *weld_e.entry((a.min(bb), a.max(bb), cell(mid))).or_insert(n); - edge_rep.entry(we).or_insert(ei); - let faces = edge_faces.entry(we).or_default(); - if !faces.contains(&fi) { - faces.push(fi); - } - edge_verts.insert(we, (a, bb)); - } - } - let poly = |we: usize| edge_rep.get(&we).and_then(|ei| mesh.edges.get(*ei)); - // Merge faces. Free-form faces meeting along an edge: smooth by their exact normals. - let flist: Vec<&truck_modeling::Face> = solid.face_iter().collect(); - let exact_smooth = |a: usize, b: usize, edge: Option<&Vec>| -> bool { - use truck_modeling::{ParametricSurface3D, SearchNearestParameter}; - let (Some(fa), Some(fb), Some(e)) = (flist.get(a), flist.get(b), edge) else { return false }; - let (sa, sb) = (fa.oriented_surface(), fb.oriented_surface()); - let step = (e.len() / 8).max(1); - // Points where a surface has no normal (a horn torus pinched to its axis) don't count; - // nor do an edge's ends when it has points between (they can be such a pinch). - let inner: &[Vec3] = if e.len() > 2 { e.get(1..e.len() - 1).unwrap_or(e) } else { e }; - let mut seen = 0; - let smooth = inner.iter().step_by(step).all(|p| { - let q = crate::body::p3(*p); - match (sa.search_nearest_parameter(q, None, 50), sb.search_nearest_parameter(q, None, 50)) { - (Some((u, v)), Some((s, t))) => { - let (x, y) = (sa.normal(u, v), sb.normal(s, t)); - let d = x.x * y.x + x.y * y.y + x.z * y.z; - if !d.is_finite() { - return true; - } - seen += 1; - d > 1.0 - 1e-3 - } - _ => false, - } - }); - smooth && seen > 0 + let mut vix = |v: u32| -> Option { + let p = Vec3::from(record.vertices.get(v as usize)?.point); + let n = weld_v.len(); + Some(*weld_v.entry(cell(p)).or_insert(n)) }; - // Pieces of a face split on purpose count apart. - let b_keep = b.split_keep(); - let keep_split = !b_keep.is_empty(); - let mut fp: Vec = (0..nf).collect(); - for (ei, faces) in &edge_faces { - let other = |f: usize| matches!(surfs.get(f), Some(Surf::Other(_))); - if let [a, b] = faces[..] - && !(keep_split && poly(*ei).is_some_and(|pl| crate::heal::on_split_line(pl, b_keep))) - && (same_surface(&surfs, &verts, poly(*ei), a, b, tol * 10.0) - || (other(a) && other(b) && exact_smooth(a, b, poly(*ei)) && { - let (Some(va), Some(vb)) = (verts.get(a), verts.get(b)) else { return Ok(TopoCounts::default()) }; - match (cone_signature(va), cone_signature(vb)) { - (Some((xa, ca)), Some((xb, cb))) => xa.dot(xb) > 1.0 - 1e-4 && (ca - cb).abs() < 1e-3, - (None, None) => true, - _ => false, - } - })) - { - let (ra, rb) = (find(&mut fp, a), find(&mut fp, b)); - if let Some(s) = fp.get_mut(ra) { - *s = rb; + let mut weld_e: HashMap<(usize, usize, (i64, i64, i64)), usize> = HashMap::new(); + let mut welded_faces: Vec> = Vec::new(); + let mut welded_ends: Vec<(usize, usize)> = Vec::new(); + // A record edge standing for each welded edge (for its points). + let mut rep: Vec = Vec::new(); + for (ei, (e, between)) in record.edges.iter().zip(edge_faces(record)).enumerate() { + let (Some(a), Some(z)) = (vix(e.vertices[0]), vix(e.vertices[1])) else { continue }; + let pts = edge_points(record, ei as u32); + let mid = pts.get(2).copied().unwrap_or(Vec3::ZERO); + let n = weld_e.len(); + let we = *weld_e.entry((a.min(z), a.max(z), cell(mid))).or_insert(n); + if we == welded_faces.len() { + welded_faces.push(Vec::new()); + welded_ends.push((a, z)); + rep.push(ei as u32); + } + if let Some(fs) = welded_faces.get_mut(we) { + for f in between { + if !fs.contains(&f) { + fs.push(f); + } } } } - // Two tangent holes touch along a line that both carry: there four faces meet, two on - // each hole's surface. Each surface's two pieces are one face, as for any other edge. - for (ei, faces) in &edge_faces { - if faces.len() <= 2 || faces.len() > 8 || (keep_split && poly(*ei).is_some_and(|pl| crate::heal::on_split_line(pl, b_keep))) { + let points = |we: usize| rep.get(we).map(|e| edge_points(record, *e)).unwrap_or_default(); + // Pieces of a face split on purpose count apart. + let keep = b.split_keep(); + let split = |we: usize| !keep.is_empty() && on_split_line(&points(we), keep); + let mut fp: Vec = (0..nf).collect(); + let union = |fp: &mut Vec, a: usize, b: usize| { + let (ra, rb) = (find(fp, a), find(fp, b)); + if let Some(s) = fp.get_mut(ra) { + *s = rb; + } + }; + for (we, fs) in welded_faces.iter().enumerate() { + if split(we) { continue; } - for (i, &a) in faces.iter().enumerate() { - for &b in faces.iter().skip(i + 1) { - let analytic = !matches!(surfs.get(a), Some(Surf::Other(_)) | None); - if analytic && same_surface(&surfs, &verts, poly(*ei), a, b, tol * 10.0) { - let (ra, rb) = (find(&mut fp, a), find(&mut fp, b)); - if let Some(s) = fp.get_mut(ra) { - *s = rb; + match fs[..] { + [a, b] if faces.same(a, b) => union(&mut fp, a, b), + // Two tangent holes touch along a line that both carry: there four faces meet, two + // on each hole's surface. Each surface's two pieces are one face. + _ if fs.len() > 2 && fs.len() <= 8 => { + for (i, &a) in fs.iter().enumerate() { + for &b in fs.iter().skip(i + 1) { + if faces.surf(a).is_some() && faces.same(a, b) { + union(&mut fp, a, b); + } } } } + _ => {} } } let mut groups: BTreeMap = BTreeMap::new(); @@ -536,31 +194,25 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result { continue; } let r = find(&mut fp, f); - if groups.insert(r, f).is_none() - && let Some(s) = surfs.get(f) - { - *face_types.entry(s.name().into()).or_insert(0) += 1; + if groups.insert(r, f).is_none() { + *face_types.entry(name(faces.surf(f)).into()).or_insert(0) += 1; } } // Remaining edges, keyed by merged face pair. - let mut remaining: Vec<(usize, (usize, usize), (usize, usize))> = Vec::new(); // (edge, verts, face pair) + let mut remaining: Vec<((usize, usize), (usize, usize))> = Vec::new(); // (verts, face pair) let mut pinches: Vec = Vec::new(); - let mut eids: Vec<&usize> = edge_faces.keys().collect(); - eids.sort(); - for e in eids { - let faces = edge_faces.get(e).cloned().unwrap_or_default(); - if faces.iter().any(|f| is_deg(*f)) { + for (we, fs) in welded_faces.iter().enumerate() { + if fs.iter().any(|f| is_deg(*f)) { continue; } - let gs: Vec = faces.iter().map(|f| find(&mut fp, *f)).collect(); + let gs: Vec = fs.iter().map(|f| find(&mut fp, *f)).collect(); // A free-form face pinched to a point (a horn torus at its axis): a zero-length edge // inside one face. A degenerate loop is kept there (two edges and a vertex). - if let Some(g) = gs.first() + let pts = points(we); + if let (Some(g), Some(p0)) = (gs.first(), pts.first()) && gs.iter().all(|x| x == g) - && matches!(surfs.get(*g), Some(Surf::Other(_))) - && let Some(pl) = poly(*e) - && let Some(p0) = pl.first() - && pl.iter().all(|p| p.dist(*p0) < tol * 10.0) + && faces.surf(*g).is_none() + && pts.iter().all(|p| p.dist(*p0) < tol * 10.0) { if !pinches.iter().any(|q: &Vec3| q.dist(*p0) < tol * 10.0) { pinches.push(*p0); @@ -573,38 +225,33 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result { [a] => (a, a), _ => (usize::MAX, usize::MAX), }; - if let Some(v) = edge_verts.get(e) { - remaining.push((*e, *v, pair)); + if let Some(v) = welded_ends.get(we) { + remaining.push((*v, pair)); } } // Vertex degree among remaining edges. let mut deg: HashMap> = HashMap::new(); - for (i, (_, (a, b), _)) in remaining.iter().enumerate() { + for (i, ((a, b), _)) in remaining.iter().enumerate() { deg.entry(*a).or_default().push(i); if b != a { deg.entry(*b).or_default().push(i); } } let mut ep: Vec = (0..remaining.len()).collect(); - let mut merge_vertex: std::collections::HashSet = std::collections::HashSet::new(); + let mut merge_vertex: HashSet = HashSet::new(); for (v, es) in ° { if let [i, j] = es[..] && let (Some(a), Some(b)) = (remaining.get(i), remaining.get(j)) - && a.2 == b.2 + && a.1 == b.1 { - let (ri, rj) = (find(&mut ep, i), find(&mut ep, j)); - if let Some(s) = ep.get_mut(ri) { - *s = rj; - } + union(&mut ep, i, j); merge_vertex.insert(*v); } } let mut edge_groups: BTreeMap = BTreeMap::new(); // root → has a real end vertex - for (i, (_, (a, b), _)) in remaining.iter().enumerate() { + for (i, ((a, b), _)) in remaining.iter().enumerate() { let r = find(&mut ep, i); - let real = !merge_vertex.contains(a) || !merge_vertex.contains(b); - let e = edge_groups.entry(r).or_insert(false); - *e |= real; + *edge_groups.entry(r).or_insert(false) |= !merge_vertex.contains(a) || !merge_vertex.contains(b); } let real_vertices = deg.keys().filter(|v| !merge_vertex.contains(v)).count(); let closed_loops = edge_groups.values().filter(|r| !**r).count(); @@ -612,10 +259,8 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result { // count them). let mut apexes = 0; for (root, f) in &groups { - if let Some(Surf::Cone { apex, .. }) = surfs.get(*f) { - let reaches = (0..nf) - .filter(|g| find(&mut fp.clone(), *g) == *root) - .any(|g| verts.get(g).is_some_and(|v| v.iter().any(|(p, _)| p.dist(*apex) < tol * 10.0))); + if let Some(Surf::Cone { v: apex, .. }) = faces.surf(*f) { + let reaches = (0..nf).filter(|g| find(&mut fp, *g) == *root).any(|g| faces.vertices(g).iter().any(|p| p.dist(*apex) < tol * 10.0)); if reaches { apexes += 1; } @@ -643,37 +288,46 @@ pub struct CylinderFace { pub internal: bool, } +/// A face's cylinder (its axis pointing the one way for every face of that cylinder), if it +/// lies on one. +fn cylinder_of(faces: &Faces, face: usize) -> Option<(UnitVec3, Vec3, f64, bool)> { + let Some(Surf::Cylinder { o, a, r, convex }) = faces.surf(face) else { return None }; + let a = a.unit()?; + let a = if a.x + a.y * 1e-3 + a.z * 1e-6 < 0.0 { -a } else { a }; + Some((a, *o, *r, !*convex)) +} + pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option { let size = b.size(); let tol = (size * 1e-3).max(1e-3); - let mesh = b.tessellate(tol).ok()?; + let mesh = b.mesh(&crate::MeshTolerance::chord(tol)).ok()?; // Each face's distance from the point (its nearest triangle). let mut near: HashMap = HashMap::new(); for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) { let Some([a, bb, c]) = mesh.tri(t) else { continue }; - let d = crate::boolean_guard::point_triangle_dist(p, a, bb, c); + let d = solidcraft_geom::compare::closest_on_triangle(p, a, bb, c).dist(p); near.entry(*f).and_modify(|x| *x = x.min(d)).or_insert(d); } let nearest = near.values().copied().fold(f64::INFINITY, f64::min); if nearest > size * 0.05 { return None; } - let surfs = classify_faces(b, &mesh, b.face_count(), (size * 1e-4).max(1e-6)); + let faces = Faces::new(b.record(), (size * 1e-4).max(1e-6) * 10.0); // The facets of a curved face lie off it by up to the mesh's tolerance, so the triangle // nearest a point on a hole's wall can be one of the face round its rim (they share the // rim's points; in a thin plate the wall is a few long facets). Of the faces within that // tolerance of the nearest, the point lies on the one whose own surface it is nearest (a // cylinder: within its extent). - let mut faces: Vec<(u32, f64)> = near.into_iter().filter(|(_, d)| *d <= nearest + tol).collect(); - faces.sort_by_key(|(f, _)| *f); + let mut candidates: Vec<(u32, f64)> = near.into_iter().filter(|(_, d)| *d <= nearest + tol).collect(); + candidates.sort_by_key(|(f, _)| *f); let mut best: Option<(f64, Option)> = None; - for (face, d) in faces { - let (off, cyl) = match surfs.get(face as usize) { - Some(Surf::Plane { n, d: k }) => (d.min((n.dot(p) - k).abs()), None), - Some(Surf::Cylinder { axis, p: ap, r }) => { - let c = cylinder_extent(&mesh, face, *axis, *ap, *r); + for (face, d) in candidates { + let (off, cyl) = match (faces.surf(face as usize), cylinder_of(&faces, face as usize)) { + (_, Some((axis, o, r, internal))) => { + let c = CylinderFace { internal, ..cylinder_extent(&mesh, face, axis, o, r) }; (d.min(c.off(p)), Some(c)) } + (Some(Surf::Plane { n, d: k }), None) => (d.min((n.dot(p) - k).abs()), None), _ => (d, None), }; if best.as_ref().is_none_or(|(bo, _)| off < *bo) { @@ -701,17 +355,38 @@ impl CylinderFace { } } +/// Whether any of `b`'s material lies in the ring between radii `r_in` and `r_out` about the +/// face's axis, over `along` (an interval of the axis coordinate the face's `start` and `end` +/// are in): the exact intersection of the body with that ring, by an SMLib boolean. +/// +/// A thread asks this past a face's end: a free end has nothing there (a cap, a chamfer the +/// groove runs out through), a shoulder, a head or a blind hole's bottom has. +pub fn material_in_ring(b: &Body, c: &CylinderFace, r_in: f64, r_out: f64, along: (f64, f64)) -> Result { + use solidcore_record::{Loop2, Plane, Region2, Vec2}; + let (a0, a1) = along; + if !(r_in >= 0.0 && r_out > r_in && a1 > a0 && r_out.is_finite() && a0.is_finite() && a1.is_finite()) { + return Err(crate::KernelError::Invalid(format!("ring r {r_in}..{r_out} over {a0}..{a1}"))); + } + let plane = Plane::from_normal(c.axis_point + c.axis * a0, *c.axis).ok_or_else(|| crate::KernelError::Invalid("ring axis".into()))?; + // Circles started at the primitives' odd seam angle, off the frame's axes (as `cylinder`). + let seam = crate::build::SEAM_ANGLE; + let holes = if r_in > 0.0 { vec![Loop2::circle_from(Vec2::ZERO, r_in, seam).reversed()] } else { Vec::new() }; + let region = Region2 { outer: Loop2::circle_from(Vec2::ZERO, r_out, seam), holes }; + let ring = crate::extrude(&plane, &[region], 0.0, a1 - a0)?.pop().ok_or_else(|| crate::KernelError::Failed("ring".into()))?; + Ok(crate::boolean(b, &ring, crate::BoolOp::Intersect)?.is_some()) +} + /// The cylindrical face one of whose end circles is centred at `p` (a circle given by its /// centre, where no face lies), the nearest when several are. pub fn cylinder_end_at(b: &Body, p: Vec3) -> Option { let size = b.size(); let tol = (size * 1e-3).max(1e-3); - let mesh = b.tessellate(tol).ok()?; - let surfs = classify_faces(b, &mesh, b.face_count(), (size * 1e-4).max(1e-6)); + let mesh = b.mesh(&crate::MeshTolerance::chord(tol)).ok()?; + let faces = Faces::new(b.record(), (size * 1e-4).max(1e-6) * 10.0); let mut best: Option<(f64, CylinderFace)> = None; - for (face, s) in surfs.iter().enumerate() { - let Surf::Cylinder { axis, p: ap, r } = *s else { continue }; - let c = cylinder_extent(&mesh, u32::try_from(face).ok()?, axis, ap, r); + for face in 0..b.record().faces.len() { + let Some((axis, o, r, internal)) = cylinder_of(&faces, face) else { continue }; + let c = CylinderFace { internal, ..cylinder_extent(&mesh, u32::try_from(face).ok()?, axis, o, r) }; let v = p - c.axis_point; let along = v.dot(c.axis); let off = (v - c.axis * along).len() + (along - c.start).abs().min((c.end - along).abs()); @@ -722,7 +397,8 @@ pub fn cylinder_end_at(b: &Body, p: Vec3) -> Option { best.map(|(_, c)| c) } -/// The extent along its axis, and the side, of a cylindrical face of a tessellated body. +/// The extent along its axis of a cylindrical face of a tessellated body, and its side as the +/// mesh's normals have it. fn cylinder_extent(mesh: &Mesh, face: u32, axis: UnitVec3, ap: Vec3, r: f64) -> CylinderFace { let mut lo = f64::INFINITY; let mut hi = f64::NEG_INFINITY; diff --git a/crates/kernel/src/touching_walls.rs b/crates/kernel/src/touching_walls.rs deleted file mode 100644 index 224f4f154..000000000 --- a/crates/kernel/src/touching_walls.rs +++ /dev/null @@ -1,181 +0,0 @@ -//! Cuts by a prism whose walls only touch the target. A corner of the tool's outline lies exactly -//! on the target's face (on a ring's bore, in its end face) with one wall going into the target -//! and the other staying outside it: both walls meet the target's face along the edge between -//! them, the loops the B-rep boolean finds there have no area, and it gives up on every try. Only -//! the last-resort nudge of the tool got through, after seconds, and left a face of no width at -//! the corner. -//! -//! A wall that lies outside the target takes nothing from it wherever it stands. Such walls are -//! pushed outward, past what the boolean takes for touching, their neighbours running on to meet -//! them, and the cut is taken with that tool: the same result, exactly, with the contact gone. A wall is pushed only where the -//! samples across its pushed place all lie outside the target's mesh, and the result is refused -//! if any of its faces lies on a pushed wall (that wall took material after all). - -use solidcraft_geom::{InsideIndex, Vec3}; -use truck_modeling as mt; - -use crate::body::{Body, from_p3}; - -/// Most walls a tool may have for this route. -const MAX_WALLS: usize = 256; - -/// Samples along and up each wall. -const SAMPLES: usize = 7; - -/// Where across the slab a wall sweeps it is sampled, as fractions of the push: the pushed -/// wall itself, and two layers between. -const LAYERS: [f64; 3] = [0.125, 0.5, 1.0]; - -/// How far a vertex may move, in pushes: a corner sharper than about six degrees moves farther, -/// and is left as it is. -const MAX_MOVE: f64 = 20.0; - -/// A tool with some of its walls pushed outward, and the planes they were pushed to (outward -/// unit normal and offset). -pub(crate) struct Pushed { - pub(crate) tool: Body, - planes: Vec<(Vec3, f64)>, -} - -impl Pushed { - /// Whether `result` has no face on a pushed wall's plane: the walls took nothing. - pub(crate) fn untouched(&self, result: &Body) -> bool { - let tol = (result.size() * 1e-9).max(1e-9); - result.solid.face_iter().all(|f| { - let mt::Surface::Plane(p) = f.oriented_surface() else { return true }; - let Some(n) = Vec3::new(p.normal().x, p.normal().y, p.normal().z).normalized() else { return true }; - !self.planes.iter().any(|(m, d)| n.dot(*m).abs() > 1.0 - 1e-9 && f.vertex_iter().all(|v| (m.dot(from_p3(v.point())) - d).abs() <= tol)) - }) - } -} - -/// `b` with each wall pushed outward by `by` whose pushed place lies outside the target -/// (`target`, an index of its mesh, meshed finer than `by`): `b` must be a prism with planar caps -/// and planar walls, every edge a line, every vertex on two walls. The faces, edges and vertices -/// keep their order, so a boolean's history over the pushed tool holds for `b`. `None` when `b` -/// is no such prism, no wall can be pushed, or a corner would move too far. -pub(crate) fn pushed_tool(b: &Body, target: &InsideIndex, by: f64) -> Option { - if !(by.is_finite() && by > 0.0) || b.solid.boundaries().len() != 1 { - return None; - } - let faces: Vec<&mt::Face> = b.solid.face_iter().collect(); - if faces.len() < 5 || faces.len() > MAX_WALLS + 2 { - return None; - } - let planes: Vec<(Vec3, f64)> = faces - .iter() - .map(|f| { - let mt::Surface::Plane(p) = f.oriented_surface() else { return None }; - let n = Vec3::new(p.normal().x, p.normal().y, p.normal().z).normalized()?; - Some((n, n.dot(from_p3(p.origin())))) - }) - .collect::>()?; - // The caps: a face whose normal every other face is square to, but for one facing away. - let square = |n: Vec3, m: Vec3| n.dot(m).abs() < 1e-9; - let caps = |i: usize| -> Option { - let n = planes.get(i)?.0; - let mut opposite = None; - for (j, (m, _)) in planes.iter().enumerate() { - if j == i || square(n, *m) { - continue; - } - if n.dot(*m) < -1.0 + 1e-9 && opposite.is_none() { - opposite = Some(j); - } else { - return None; - } - } - opposite - }; - let (top, bottom) = (0..planes.len()).find_map(|i| caps(i).map(|j| (i, j)))?; - let d = planes.get(top)?.0; - let size = b.size(); - let on = (size * 1e-9).max(1e-9); - let walls: Vec = (0..faces.len()).filter(|i| *i != top && *i != bottom).collect(); - // Which walls go: every sample across the pushed place outside the target. - let mut shift = vec![0.0; faces.len()]; - for &w in &walls { - let (face, (n, o)) = (faces.get(w)?, planes.get(w)?); - let corners: Vec = face.vertex_iter().map(|v| from_p3(v.point())).collect(); - if face.boundaries().len() != 1 || corners.len() != 4 { - return None; - } - // The wall's two ends along its cap edge and its two heights. - let along = d.cross(*n); - let (lo_u, hi_u) = corners.iter().map(|p| p.dot(along)).fold((f64::INFINITY, f64::NEG_INFINITY), |m, x| (m.0.min(x), m.1.max(x))); - let (lo_h, hi_h) = corners.iter().map(|p| p.dot(d)).fold((f64::INFINITY, f64::NEG_INFINITY), |m, x| (m.0.min(x), m.1.max(x))); - let base = *n * *o; - let clear = LAYERS.iter().all(|layer| { - (0..SAMPLES).all(|i| { - (0..SAMPLES).all(|j| { - let s = |k: usize, lo: f64, hi: f64| lo + (hi - lo) * (0.02 + 0.96 * k as f64 / (SAMPLES - 1) as f64); - let p = base + along * s(i, lo_u, hi_u) + d * s(j, lo_h, hi_h) + *n * (by * layer); - !target.contains(p) - }) - }) - }); - if clear && let Some(x) = shift.get_mut(w) { - *x = by; - } - } - if shift.iter().all(|x| *x == 0.0) { - return None; - } - let solid = b.deep_copy(); - let copied: Vec<&mt::Face> = solid.face_iter().collect(); - // Each vertex moves square to the walls so that it stays on both of its walls, pushed. - let mut moved = std::collections::HashMap::new(); - for face in &copied { - for v in face.vertex_iter() { - if moved.contains_key(&v.id()) { - continue; - } - let p = from_p3(v.point()); - let on_walls: Vec = walls.iter().copied().filter(|w| planes.get(*w).is_some_and(|(n, o)| (n.dot(p) - o).abs() <= on)).collect(); - let [i, j] = on_walls.as_slice() else { return None }; - let ((ni, _), (nj, _)) = (planes.get(*i)?, planes.get(*j)?); - let (di, dj) = (*shift.get(*i)?, *shift.get(*j)?); - let c = ni.dot(*nj); - let det = 1.0 - c * c; - let s = if di == 0.0 && dj == 0.0 { - Vec3::ZERO - } else if det < 1e-6 { - return None; - } else { - *ni * ((di - c * dj) / det) + *nj * ((dj - c * di) / det) - }; - if s.len() > MAX_MOVE * by { - return None; - } - moved.insert(v.id(), (v.clone(), p + s)); - } - } - for (v, p) in moved.values() { - v.set_point(mt::Point3::new(p.x, p.y, p.z)); - } - // Edges run between their moved ends; each pushed wall is its plane moved along its normal. - for face in &copied { - for wire in face.boundaries() { - for e in wire.edge_iter() { - let mt::Curve::Line(_) = e.curve() else { return None }; - e.set_curve(mt::Curve::Line(mt::Line(e.absolute_front().point(), e.absolute_back().point()))); - } - } - } - let mut pushed = Vec::new(); - for (k, face) in copied.iter().enumerate() { - let (Some(&x), Some((n, o))) = (shift.get(k), planes.get(k)) else { return None }; - if x == 0.0 { - continue; - } - let mt::Surface::Plane(p) = face.surface() else { return None }; - let t = mt::Vector3::new(n.x, n.y, n.z) * x; - face.set_surface(mt::Surface::Plane(mt::Plane::new(p.origin() + t, p.origin() + p.u_axis() + t, p.origin() + p.v_axis() + t))); - pushed.push((*n, o + x)); - } - let tool = Body::new(solid).ok()?; - if !tool.validity().is_empty() { - return None; - } - Some(Pushed { tool, planes: pushed }) -} diff --git a/crates/kernel/src/trimmed_face_mesh_tests.rs b/crates/kernel/src/trimmed_face_mesh_tests.rs index 248897d52..a83838be8 100644 --- a/crates/kernel/src/trimmed_face_mesh_tests.rs +++ b/crates/kernel/src/trimmed_face_mesh_tests.rs @@ -1,9 +1,10 @@ //! Tessellation of trimmed loft faces after a boolean: no triangle may leave the face. +use solidcraft_geom::prelude::*; use std::f64::consts::FRAC_PI_2; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; -use truck_modeling::{self as mt, SearchNearestParameter}; +use solidcore_record::{Loop2, Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::brep::eval::SurfaceEval; use crate::*; @@ -43,16 +44,14 @@ fn tube() -> Body { /// Each face's mesh area, and how far its triangles' centroids lie off its surface at most. fn per_face(body: &Body, mesh: &solidcraft_geom::Mesh) -> Vec<(f64, f64)> { - use mt::ParametricSurface; - let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); + let faces: Vec = body.record().faces.iter().map(|f| SurfaceEval::new(&f.surface).unwrap()).collect(); let mut out = vec![(0.0, 0.0f64); faces.len()]; for (t, &f) in mesh.triangles.iter().zip(&mesh.tri_face) { - let ([a, b, c], Some(face), Some(slot)) = (mesh.tri(t).unwrap(), faces.get(f as usize), out.get_mut(f as usize)) else { continue }; + let ([a, b, c], Some(surface), Some(slot)) = (mesh.tri(t).unwrap(), faces.get(f as usize), out.get_mut(f as usize)) else { continue }; slot.0 += (b - a).cross(c - a).len() / 2.0; let g = (a + b + c) / 3.0; - let surface = face.oriented_surface(); - let (u, v) = surface.search_nearest_parameter(mt::Point3::new(g.x, g.y, g.z), None, 50).unwrap(); - slot.1 = slot.1.max(crate::body::from_p3(surface.subs(u, v)).dist(g)); + let uv = surface.project(g, None, f64::INFINITY).unwrap(); + slot.1 = slot.1.max(surface.point(uv).unwrap().dist(g)); } out } @@ -67,8 +66,8 @@ fn trimmed_ruled_loft_faces_mesh_on_their_surfaces() { let shell = cylinder(Vec3::new(0.0, -36.5, 0.0), Vec3::Y, 23.0, 73.0).unwrap(); let joined = boolean(&tube, &shell, BoolOp::Union).unwrap().unwrap(); let tol = (joined.size() * 1e-3).max(1e-3); - let display = per_face(&joined, &joined.reference_display_mesh_angular(tol, DISPLAY_ANGLE).unwrap()); - let fine = per_face(&joined, &joined.tessellate(tol / 8.0).unwrap()); + let display = per_face(&joined, &joined.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap()); + let fine = per_face(&joined, &joined.mesh(&crate::MeshTolerance::chord(tol / 8.0)).unwrap()); for (fi, ((area, off), (fine_area, _))) in display.iter().zip(&fine).enumerate() { // A centroid sags at most about the chord tolerance (the bad sheet was 7 mm off at 0.6). assert!(*off < 2.0 * tol, "face {fi}: a triangle lies {off:.2} mm off the surface (tolerance {tol:.2})"); @@ -76,35 +75,3 @@ fn trimmed_ruled_loft_faces_mesh_on_their_surfaces() { assert!((area - fine_area).abs() < 0.02 * fine_area, "face {fi}: mesh area {area:.0} mm², finer mesh {fine_area:.0} mm²"); } } - -/// #4031: a join whose new face has a boundary segment crossing another in the triangulation's -/// parameters (a sketch point far out, inside the command cap) never reaches the triangulator's -/// assertion: it builds while the boolean's own precision holds, and fails cleanly beyond. -#[test] -fn a_crossing_boundary_segment_does_not_trip_the_triangulator() { - use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; - // The mesher runs on worker threads: count the assertion by its message. - let count = Arc::new(AtomicUsize::new(0)); - let c2 = count.clone(); - let prev = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |info| { - if info.to_string().contains("previous_region") { - c2.fetch_add(1, Ordering::SeqCst); - } - })); - let mut volumes = Vec::new(); - for far in [1e6, 3e6, 9.9e8] { - let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 20.0, 10.0)).unwrap(); - let outer = Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), Vec2::new(40.0, far), Vec2::new(0.0, 20.0)]); - let sliver = extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0.0, 10.0).unwrap().remove(0); - volumes.push(boolean(&block, &sliver, BoolOp::Union).ok().flatten().and_then(|b| measure(&b).ok()).map(|m| m.volume)); - } - std::panic::set_hook(prev); - assert_eq!(count.load(Ordering::SeqCst), 0, "the triangulator's assertion fired"); - // The sliver holds the block: its volume is the union's, (40 * (far + 20) / 2) * 10. - for (far, v) in [(1e6, volumes[0]), (3e6, volumes[1])] { - let exact = 40.0 * (far + 20.0) / 2.0 * 10.0; - assert!(v.is_some_and(|v| (v - exact).abs() < 1e-9 * exact), "far {far}: {v:?}"); - } -} diff --git a/crates/kernel/src/tspline.rs b/crates/kernel/src/tspline.rs index 7688c7208..0f1631fd9 100644 --- a/crates/kernel/src/tspline.rs +++ b/crates/kernel/src/tspline.rs @@ -2,29 +2,29 @@ //! faces. A T-mesh without T-junctions becomes one clamped tensor face; otherwise each Bézier //! element is a face, and the faces share their edges and vertices — a side that meets two //! neighbours is split at the T-point between them — so the sheet is one sewn open shell. +//! +//! Every edge is an exact piece of its patch's side (a Bézier segment of the side's control +//! points) and its pcurve on each face it bounds a straight line in that patch's parameters. -use std::collections::hash_map::Entry; use std::collections::{BTreeMap, BTreeSet, HashMap}; +use solidcore_record::brep as b; use solidcraft_geom::bspline::{BezierPatch, HPoint, NurbsSurface, SplineError, bezier_segment}; use solidcraft_geom::tspline::TSpline; -use truck_modeling as mt; use crate::body::Body; -use crate::spline_conv::{h4, nurbs_curve, nurbs_surface}; -use crate::{KernelError, Result, guard}; +use crate::surfaces::{Parts, spline_curve, spline_surface, surface_body, uv_line}; +use crate::{KernelError, Result}; /// A T-spline as a surface body (an open shell of NURBS faces whose normals follow /// `∂S/∂s × ∂S/∂t`). pub fn tspline_sheet(ts: &TSpline) -> Result { - let faces = if ts.mesh().is_regular() { + if ts.mesh().is_regular() { let n = ts.to_nurbs().and_then(|n| n.clamped()).map_err(spline_err)?; - guard("t-spline sheet", || tensor_face(&n).map(|f| vec![f]))? - } else { - let patches = ts.bezier_elements().map_err(spline_err)?; - guard("t-spline sheet", || patch_faces(&patches))? - }; - Ok(crate::surfaces::surface_body(faces)) + return crate::surfaces::tensor_sheet(&n); + } + let patches = ts.bezier_elements().map_err(spline_err)?; + surface_body(&patch_faces(&patches)?.canonical()?.brep) } fn spline_err(e: SplineError) -> KernelError { @@ -35,14 +35,8 @@ fn fail(m: impl std::fmt::Display) -> KernelError { KernelError::Failed(format!("t-spline sheet: {m}")) } -fn vertex(h: HPoint) -> Result { - let p = h.project().ok_or_else(|| fail("a corner has no position"))?; - Ok(mt::builder::vertex(crate::body::p3(p))) -} - -/// One face from a clamped tensor surface, bounded by its four boundary curves. -fn tensor_face(n: &NurbsSurface) -> Result { - crate::spline_conv::tensor_face(n) +fn index(i: usize) -> Result { + u32::try_from(i).map_err(|_| KernelError::TooLarge("t-spline sheet: too many patches".into())) } /// A parameter point, exact (knot values are shared, so equal points have equal bits). @@ -52,9 +46,13 @@ fn key(s: f64, t: f64) -> Key { ((s + 0.0).to_bits(), (t + 0.0).to_bits()) } -/// One face per Bézier patch, sharing vertices and edges; sides are split where a -/// neighbour's corner lands on them. -fn patch_faces(patches: &[BezierPatch]) -> Result> { +fn st(k: Key) -> [f64; 2] { + [f64::from_bits(k.0), f64::from_bits(k.1)] +} + +/// One face per Bézier patch, sharing vertices and edges; sides are split where a neighbour's +/// corner lands on them. +fn patch_faces(patches: &[BezierPatch]) -> Result { // Corner parameters on each line of constant t (their s values) and of constant s. let mut on_t: BTreeMap> = BTreeMap::new(); let mut on_s: BTreeMap> = BTreeMap::new(); @@ -67,14 +65,21 @@ fn patch_faces(patches: &[BezierPatch]) -> Result> { } } } - let mut verts: HashMap = HashMap::new(); - let mut edges: HashMap<(Key, Key), mt::Edge> = HashMap::new(); - let mut faces = Vec::with_capacity(patches.len()); + let mut parts = Parts::default(); + let mut verts: HashMap = HashMap::new(); + // Each edge by its ends' parameters, in the direction it was made. + let mut edges: HashMap<(Key, Key), u32> = HashMap::new(); + let mut corners: Vec<[f64; 3]> = Vec::new(); for p in patches { - let mut wire: Vec = Vec::new(); + // The patch's own (u, v) on [0, 1]² of a global (s, t). + let local = |k: Key| { + let [s, t] = st(k); + [(s - p.s[0]) / (p.s[1] - p.s[0]), (t - p.t[0]) / (p.t[1] - p.t[0])] + }; + let mut uses: Vec = Vec::new(); for side in 0..4 { - // Side 0: t = t₀, 1: s = s₁, 2: t = t₁, 3: s = s₀; each runs with its parameter - // rising, sides 2 and 3 are walked backwards. + // Side 0: t = t0, 1: s = s1, 2: t = t1, 3: s = s0; each runs with its parameter rising, + // sides 2 and 3 are walked backwards. let (along_s, fixed, [lo, hi]) = match side { 0 => (true, p.t[0], p.s), 1 => (false, p.s[1], p.t), @@ -91,47 +96,70 @@ fn patch_faces(patches: &[BezierPatch]) -> Result> { for w in breaks.windows(2) { let &[x0, x1] = w else { continue }; let (ka, kb) = (at(x0), at(x1)); - let e = if let Some(e) = edges.get(&(ka, kb)) { - e.clone() - } else if let Some(e) = edges.get(&(kb, ka)) { - e.inverse() - } else { - let seg = bezier_segment(&ctrl, (x0 - lo) / (hi - lo), (x1 - lo) / (hi - lo)).map_err(spline_err)?; - let (Some(&first), Some(&last)) = (seg.first(), seg.last()) else { return Err(fail("an empty side")) }; - let mut corner = |k: Key, h: HPoint| -> Result { - Ok(match verts.entry(k) { - Entry::Occupied(e) => e.get().clone(), - Entry::Vacant(e) => e.insert(vertex(h)?).clone(), - }) - }; - let (va, vb) = (corner(ka, first)?, corner(kb, last)?); - let curve = nurbs_curve(mt::KnotVec::bezier_knot(seg.len() - 1), &seg)?; - let e = mt::Edge::try_new(&va, &vb, curve).map_err(fail)?; - edges.insert((ka, kb), e.clone()); - e + // The edge as made (a to b with its parameter rising), and whether this side runs + // along it. + let (edge, made) = match (edges.get(&(ka, kb)), edges.get(&(kb, ka))) { + (Some(e), _) => (*e, (ka, kb)), + (None, Some(e)) => (*e, (kb, ka)), + (None, None) => { + let seg = bezier_segment(&ctrl, (x0 - lo) / (hi - lo), (x1 - lo) / (hi - lo)).map_err(spline_err)?; + let (Some(&first), Some(&last)) = (seg.first(), seg.last()) else { return Err(fail("an empty side")) }; + let mut corner = |k: Key, h: HPoint| -> Result { + if let Some(v) = verts.get(&k) { + return Ok(*v); + } + let q = h.project().ok_or_else(|| fail("a corner has no position"))?; + let v = index(corners.len())?; + corners.push([q.x, q.y, q.z]); + verts.insert(k, v); + Ok(v) + }; + let vertices = [corner(ka, first)?, corner(kb, last)?]; + let degree = seg.len().saturating_sub(1); + let knots = std::iter::repeat_n(0.0, degree + 1).chain(std::iter::repeat_n(1.0, degree + 1)).collect(); + let (curve, interval) = spline_curve(&seg, knots)?; + let e = index(parts.edges.len())?; + parts.edges.push(b::Edge { nurbs: None, curve, interval, vertices, tolerance: 0.0, uses: Vec::new() }); + edges.insert((ka, kb), e); + (e, (ka, kb)) + } }; - pieces.push(e); + let pcurve = uv_line(local(made.0), local(made.1), [0.0, 1.0]); + pieces.push(b::OrientedEdge { edge, forward: made == (ka, kb), pcurve }); } if side >= 2 { pieces.reverse(); - pieces.iter_mut().for_each(|e| *e = e.inverse()); + pieces.iter_mut().for_each(|u| u.forward = !u.forward); } - wire.extend(pieces); + uses.extend(pieces); } let [ps, pt] = p.degree; - let rows: Vec> = (0..=ps).map(|i| (0..=pt).map(|j| h4(p.point(i, j))).collect()).collect(); - let surf = nurbs_surface((mt::KnotVec::bezier_knot(ps), mt::KnotVec::bezier_knot(pt)), rows)?; - faces.push(mt::Face::try_new(vec![wire.into()], surf).map_err(fail)?); + let knots = |d: usize| std::iter::repeat_n(0.0, d + 1).chain(std::iter::repeat_n(1.0, d + 1)).collect::>(); + let ctrl: Vec = (0..=pt).flat_map(|j| (0..=ps).map(move |i| (i, j))).map(|(i, j)| p.point(i, j)).collect(); + let surface = NurbsSurface::from_homogeneous([ps, pt], [knots(ps), knots(pt)], ctrl).map_err(spline_err)?; + parts.faces.push(( + b::Face { nurbs: None, surface: spline_surface(&surface), domain: [[0.0, 1.0], [0.0, 1.0]], loops: vec![b::Loop::Edges { edges: uses }] }, + true, + )); } - Ok(faces) + let mut bounds = solidcraft_geom::Aabb3::EMPTY; + for c in &corners { + bounds.add(solidcore_record::Vec3::new(c[0], c[1], c[2])); + } + parts.tolerance = (bounds.diagonal() * 1e-6).max(1e-5); + parts.vertices = corners.into_iter().map(|point| b::Vertex { point, tolerance: parts.tolerance }).collect(); + for e in &mut parts.edges { + e.tolerance = parts.tolerance; + } + Ok(parts) } #[cfg(test)] mod tests { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; use solidcraft_geom::bspline::NurbsSurface; + use solidcraft_geom::prelude::*; use solidcraft_geom::tspline::{Cut, TSpline}; - use truck_modeling as mt; use super::tspline_sheet; use crate::fuzz::Rng; @@ -187,11 +215,14 @@ mod tests { assert!(body.is_surface()); assert_eq!(body.shell_count(), 1); assert_eq!(body.face_count(), faces); - let shell = &body.solid.boundaries()[0]; - assert_eq!(shell.shell_condition(), mt::ShellCondition::Oriented, "neighbours share edges, run opposite ways"); + let record = body.record(); + assert!( + record.edges.iter().all(|e| e.uses.len() == 1 || (e.uses.len() == 2 && e.uses[0].upper != e.uses[1].upper)), + "neighbours share edges, run opposite ways" + ); let euler = body.vertex_count() as i64 - body.edge_count() as i64 + body.face_count() as i64; assert_eq!(euler, 1, "one sewn sheet (a disc)"); - let mesh = body.tessellate(0.01).unwrap(); + let mesh = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); assert!(!mesh.triangles.is_empty()); // Mesh points lie on the surface (not merely within the tessellation tolerance). let step = (mesh.positions.len() / 300).max(1); @@ -227,12 +258,12 @@ mod tests { for pts in cases { let Ok(ts) = TSpline::new(mesh.clone(), [3, 3], &pts, &vec![1.0; n]) else { continue }; if let Ok(body) = tspline_sheet(&ts) { - let _ = body.tessellate(0.01); + let _ = body.mesh(&crate::MeshTolerance::chord(0.01)); } if let Ok(r) = ts.refine(&[Cut::S { s: 0.33, t0: 0.3, t1: 0.6 }]) && let Ok(body) = tspline_sheet(&r) { - let _ = body.tessellate(0.01); + let _ = body.mesh(&crate::MeshTolerance::chord(0.01)); } } } diff --git a/crates/kernel/src/untouched_faces_tests.rs b/crates/kernel/src/untouched_faces_tests.rs index a1e06bd04..0fe18a75e 100644 --- a/crates/kernel/src/untouched_faces_tests.rs +++ b/crates/kernel/src/untouched_faces_tests.rs @@ -1,7 +1,8 @@ //! A cut or a join never splits faces it doesn't touch: a flat wall with an opening cut into //! it stays one face with an inner loop, whatever is cut or joined elsewhere afterwards. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::{Body, BoolOp, FaceSurface, boolean, box_solid, face_surface, fillet, shell}; @@ -151,35 +152,27 @@ fn random_cuts_and_joins_never_split_other_faces() { /// The edges of `b` lying along the line through `a` and `z`. fn edges_along(b: &Body, a: Vec3, z: Vec3) -> usize { + let r = b.record(); let on = |p: Vec3| p.dist_to_segment(a, z) < 1e-6; - let edges: std::collections::HashSet<_> = b - .solid - .edge_iter() - .filter(|e| on(crate::body::from_p3(e.front().point())) && on(crate::body::from_p3(e.back().point()))) - .map(|e| e.id()) - .collect(); - edges.len() + let point = |v: u32| Vec3::from(r.vertices[v as usize].point); + r.edges.iter().filter(|e| on(point(e.vertices[0])) && on(point(e.vertices[1]))).count() } /// Vertices of `b` where just two straight edges meet in line (a straight edge split in two). fn stations(b: &Body) -> usize { - use std::collections::HashMap; - let mut at: HashMap> = HashMap::new(); - let mut seen = std::collections::HashSet::new(); - for e in b.solid.edge_iter() { - if seen.insert(e.id()) { - for v in [e.front(), e.back()] { - at.entry(v.id()).or_default().push(e.clone()); - } + let r = b.record(); + let mut at: Vec> = vec![Vec::new(); r.vertices.len()]; + for (i, e) in r.edges.iter().enumerate() { + for v in e.vertices { + at[v as usize].push(i); } } - at.values() + let point = |v: u32| Vec3::from(r.vertices[v as usize].point); + let dir = |e: usize| (point(r.edges[e].vertices[1]) - point(r.edges[e].vertices[0])).normalized(); + let line = |e: usize| matches!(r.edges[e].curve, solidcore_record::brep::Curve::Line { .. }); + at.iter() .filter(|es| match es.as_slice() { - [a, b] => { - let dir = |e: &truck_modeling::Edge| (crate::body::from_p3(e.back().point()) - crate::body::from_p3(e.front().point())).normalized(); - matches!((a.curve(), b.curve()), (truck_modeling::Curve::Line(_), truck_modeling::Curve::Line(_))) - && dir(a).zip(dir(b)).is_some_and(|(u, w)| u.dot(w).abs() > 1. - 1e-9) - } + [a, b] => line(*a) && line(*b) && dir(*a).zip(dir(*b)).is_some_and(|(u, w)| u.dot(w).abs() > 1. - 1e-9), _ => false, }) .count() diff --git a/crates/kernel/src/validation.rs b/crates/kernel/src/validation.rs new file mode 100644 index 000000000..d23f9f60d --- /dev/null +++ b/crates/kernel/src/validation.rs @@ -0,0 +1,260 @@ +//! How often SMLib's full check runs while a model is evaluated. Every sweep, boolean and blend +//! checks its result in SMLib before it is decoded ([`Validation::EachStep`]); an evaluation can +//! instead leave those checks to one check of the bodies each feature keeps +//! ([`Validation::EachFeature`]), or skip them ([`Validation::Off`]). A body kept straight from +//! a step is checked at the end as that step would have checked it, on the step's own result +//! (kept with the body until then): the record a result is decoded to can pass SMLib's check +//! where the result itself fails it (a surface of revolution's polar curve, rebuilt on import). +//! +//! The evaluation installs its mode around a feature with [`validating`], as [`crate::watch`] +//! installs a watch: the operations a feature runs are reached through hundreds of public kernel +//! functions, and the mode is the evaluation's, not each operation's. Outside [`validating`] +//! (the kernel called directly, a preview, a test) every step is checked, as it always was. The +//! worker threads the kernel starts for a step run under the same mode ([`crate::par`]). + +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde::{Deserialize, Serialize}; + +use crate::body::Body; +use crate::{KernelError, Result}; + +/// When SMLib's full check of a result runs during a model evaluation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Validation { + /// After every sweep, boolean and blend: a step whose result fails the check fails the + /// feature there (how every evaluation checked before the mode existed). + EachStep, + /// Once per feature: the steps inside a feature are not checked, and each body the feature + /// makes or changes is checked before it is kept, so a feature that makes a body the check + /// refuses still fails, with the check's reason. + #[default] + EachFeature, + /// Never (experimental): a body the check would refuse is kept. + Off, +} + +impl Validation { + pub const ALL: [Validation; 3] = [Validation::EachStep, Validation::EachFeature, Validation::Off]; + + /// The mode's name: `each_step`, `each_feature` or `off` (as it is saved and sent). + pub fn id(self) -> &'static str { + match self { + Validation::EachStep => "each_step", + Validation::EachFeature => "each_feature", + Validation::Off => "off", + } + } + + /// The mode named `id` ([`Validation::id`]), `None` for anything else. + pub fn parse(id: &str) -> Option { + Validation::ALL.into_iter().find(|v| v.id() == id) + } +} + +/// One feature's work under a mode, shared with the worker threads it starts. +#[derive(Debug)] +pub(crate) struct Scope { + mode: Validation, + /// A step's check was left for the end of the feature ([`Validation::EachFeature`]). + deferred: AtomicBool, +} + +thread_local! { + static CURRENT: RefCell>> = const { RefCell::new(None) }; +} + +/// Run `f` with `mode` deciding which checks the kernel work it does on this thread runs. Also +/// gives whether a step's check was left for later under [`Validation::EachFeature`]: the +/// caller then checks the bodies it keeps ([`check_kept`]). +pub fn validating(mode: Validation, f: impl FnOnce() -> R) -> (R, bool) { + let scope = Arc::new(Scope { mode, deferred: AtomicBool::new(false) }); + let r = within(Some(scope.clone()), f); + (r, scope.deferred.load(Ordering::Relaxed)) +} + +/// The scope this thread's work runs in, to hand to the worker threads it starts. +pub(crate) fn current() -> Option> { + CURRENT.with(|c| c.borrow().clone()) +} + +/// Run `f` in `scope` (one [`current`] gave on another thread), restoring this thread's own +/// afterwards, also when `f` panics. +pub(crate) fn within(scope: Option>, f: impl FnOnce() -> R) -> R { + struct Restore(Option>>); + impl Drop for Restore { + fn drop(&mut self) { + if let Some(previous) = self.0.take() { + CURRENT.with(|c| *c.borrow_mut() = previous); + } + } + } + let previous = CURRENT.with(|c| c.replace(scope)); + let _restore = Restore(Some(previous)); + f() +} + +/// What a step does with SMLib's check of its result ([`step`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Step { + /// Check it now (outside [`validating`], and under [`Validation::EachStep`]). + Check, + /// Leave it to the end of the feature (under [`Validation::EachFeature`]): the body decoded + /// from the result keeps it ([`Body::left_unchecked`]) for [`check_kept`]. + Defer, + /// Never check it (under [`Validation::Off`]). + Skip, +} + +/// What the step about to check its result does. [`Step::Defer`] also tells the feature a check +/// was left for its end. +pub(crate) fn step() -> Step { + CURRENT.with(|c| match c.borrow().as_deref() { + None | Some(Scope { mode: Validation::EachStep, .. }) => Step::Check, + Some(s @ Scope { mode: Validation::EachFeature, .. }) => { + s.deferred.store(true, Ordering::Relaxed); + Step::Defer + } + Some(Scope { mode: Validation::Off, .. }) => Step::Skip, + }) +} + +/// How a step's own check takes its result. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Checked { + /// As it is. + AsIs, + /// A boolean's: solids touching each other along an edge or at a vertex come back as one + /// non-manifold body, checked as the separate solids its export holds (the boolean's rule). + Combined, +} + +/// A step's SMLib result whose check was left to the end of its feature: kept with the body +/// decoded from it (and only for that body's record) until [`check_kept`] takes it, so the check +/// at the end is the step's own, of the result the step made. +#[derive(Debug)] +pub(crate) struct Unchecked { + record: std::sync::Weak, + /// The step, as its own refusal names it (`SMLib fillet`). + what: String, + how: Checked, + result: std::sync::Mutex>, +} + +impl Unchecked { + pub(crate) fn new(record: &Arc, what: &str, how: Checked, result: solidcraft_smlib::Brep) -> Unchecked { + Unchecked { record: Arc::downgrade(record), what: what.to_string(), how, result: std::sync::Mutex::new(Some(result)) } + } + + /// The step's result, taken (once), when this is `record`'s. + fn take(&self, record: &Arc) -> Option { + if !std::ptr::eq(self.record.as_ptr(), Arc::as_ptr(record)) { + return None; + } + self.result.lock().ok().and_then(|mut r| r.take()) + } +} + +/// SMLib's full check of `r` as a step takes it (`how`): the check's report. +pub(crate) fn check_result(r: &solidcraft_smlib::Brep, how: Checked) -> std::result::Result { + fn failed(what: &'static str) -> impl Fn(&dyn std::fmt::Display) -> String { + move |e| format!("{what}: {e}") + } + match how { + Checked::Combined if !r.is_manifold_solid().map_err(|e| failed("check")(&e))? => { + let record = r.to_native().map_err(|e| failed("export")(&e))?; + let split = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| failed("the separate solids")(&e))?; + split.check(solidcraft_smlib::CheckLevel::All).map_err(|e| failed("check")(&e)) + } + _ => r.check(solidcraft_smlib::CheckLevel::All).map_err(|e| failed("check")(&e)), + } +} + +/// SMLib's full check of a body a feature keeps, once a step of the feature left its check to +/// the end: an error with the check's reason unless it passes. A body decoded from a step's +/// result is checked as that step would have checked it, on its result; any other (a copy moved +/// into place, pieces joined without an operation) as SMLib takes it for the operations after it. +/// A mesh body has nothing to check. +pub fn check_kept(body: &Body) -> Result<()> { + if body.is_mesh() { + return Ok(()); + } + let step = body.unchecked.as_deref().and_then(|u| u.take(&body.record).map(|r| (u, r))); + let (what, check) = match &step { + Some((u, r)) => (u.what.as_str(), check_result(r, u.how)), + None => ("SMLib", body.smlib()?.check(solidcraft_smlib::CheckLevel::All).map_err(|e| format!("check: {e}"))), + }; + match check { + Ok(c) if c.is_valid() => Ok(()), + Ok(c) => Err(KernelError::Failed(format!("{what}: SMLib's check refuses the result: {c}"))), + Err(e) => Err(KernelError::Failed(format!("{what}: {e}"))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_step_is_checked_outside_an_evaluation_and_under_each_step() { + assert_eq!(step(), Step::Check); + assert_eq!(validating(Validation::EachStep, step), (Step::Check, false)); + assert_eq!(validating(Validation::EachFeature, step), (Step::Defer, true)); + assert_eq!(validating(Validation::Off, step), (Step::Skip, false)); + // The thread's own mode comes back, also after a nested scope. + let ((inner, outer), deferred) = validating(Validation::Off, || (validating(Validation::EachStep, step).0, step())); + assert!(inner == Step::Check && outer == Step::Skip && !deferred); + assert_eq!(step(), Step::Check); + } + + #[test] + fn the_mode_reaches_the_kernels_worker_threads() { + let items = [0, 1, 2, 3]; + let (checked, deferred) = validating(Validation::EachFeature, || { + crate::par::map("validation", &items, true, |_| Ok(step())).into_iter().collect::>>() + }); + assert_eq!(checked.ok(), Some(vec![Step::Defer; 4])); + assert!(deferred); + let (on_threads, deferred) = validating(Validation::EachFeature, || crate::par::map_on_threads(&items, 4, |_| step())); + assert_eq!(on_threads, vec![Some(Step::Defer); 4]); + assert!(deferred); + } + + /// A box with one corner moved off its three edges: SMLib's check refuses it. Under each_step + /// the boolean that takes it refuses its result there; under each_feature it is not checked, + /// says the check was left for later, and the check of the body kept refuses it. + #[test] + fn a_body_the_check_refuses_is_refused_at_the_step_or_at_the_end() { + use solidcore_record::Vec3; + let good = crate::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 10.0)).unwrap(); + assert!(check_kept(&good).is_ok()); + let mut record = good.record().clone(); + record.vertices[0].point[2] += 0.5; + let bad = Body::from_record(record).unwrap(); + let e = check_kept(&bad).unwrap_err().to_string(); + assert!(e.contains("SMLib's check refuses the result"), "{e}"); + let tool = crate::box_solid(Vec3::new(5.0, 5.0, 5.0), Vec3::new(20.0, 20.0, 20.0)).unwrap(); + let (step, deferred) = validating(Validation::EachStep, || crate::boolean(&bad, &tool, crate::BoolOp::Union)); + let e = step.unwrap_err().to_string(); + assert!(e.contains("SMLib's check refuses the result (the first operand already fails it)") && !deferred, "{e}"); + let (joined, deferred) = validating(Validation::EachFeature, || crate::boolean(&bad, &tool, crate::BoolOp::Union)); + assert!(deferred); + let joined = joined.unwrap().unwrap(); + assert!(check_kept(&joined).unwrap_err().to_string().contains("SMLib's check refuses the result")); + let (off, deferred) = validating(Validation::Off, || crate::boolean(&bad, &tool, crate::BoolOp::Union)); + assert!(off.is_ok_and(|b| b.is_some()) && !deferred); + } + + #[test] + fn modes_are_named_as_they_are_saved() { + for v in Validation::ALL { + assert_eq!(Validation::parse(v.id()), Some(v)); + assert_eq!(serde_json::to_value(v).ok(), Some(serde_json::json!(v.id()))); + } + assert_eq!(Validation::parse("each step"), None); + assert_eq!(Validation::default(), Validation::EachFeature); + } +} diff --git a/crates/kernel/src/validity.rs b/crates/kernel/src/validity.rs new file mode 100644 index 000000000..7bbb419d2 --- /dev/null +++ b/crates/kernel/src/validity.rs @@ -0,0 +1,62 @@ +//! Is a body one valid solid? The kernel regression rig (`tests/kernel-cases`) asks this of every +//! result: the schema 4 record's structure and geometry (`Brep::validate`, `check_geometry`), +//! and SMLib's own check of the same record. + +use crate::{Body, brep_record}; + +/// What the validity checks found for one body. `Err` holds why a check failed. +#[derive(Clone, Debug)] +pub struct Validity { + /// The record: structure, then geometry against topology within tolerances. + pub record: Result<(), String>, + /// SMLib's `check(All)` of the record. + pub smlib: Option, +} + +/// SMLib's verdict on a body. +#[derive(Clone, Debug)] +pub enum SmlibCheck { + Valid, + Invalid(String), + /// The record can't be built in SMLib yet (a geometry kind the conversion doesn't take): no + /// verdict, and no fault of the body's. + NotSupported(String), +} + +impl Validity { + pub fn ok(&self) -> bool { + self.record.is_ok() && !matches!(self.smlib, Some(SmlibCheck::Invalid(_))) + } +} + +/// Runs every validity check this build has on `body`. +pub fn validity(body: &Body) -> Validity { + let record = brep_record(body).map_err(|e| e.to_string()); + let checked = record.as_ref().map_err(Clone::clone).and_then(|r| { + solidcraft_geom::brep::check::validate_built(r).map_err(|e| format!("structure: {e}"))?; + solidcraft_geom::brep::geometry::check(r).map_err(|e| format!("geometry: {e}")) + }); + Validity { record: checked, smlib: smlib_validity(body) } +} + +fn smlib_validity(body: &Body) -> Option { + let b = match crate::smlib_body(body) { + Ok(b) => b, + Err(e) => { + let e = e.to_string(); + return Some(if e.contains("not supported yet") { SmlibCheck::NotSupported(e) } else { SmlibCheck::Invalid(e) }); + } + }; + Some(match b.check(solidcraft_smlib::CheckLevel::All) { + Ok(r) if r.is_valid() => SmlibCheck::Valid, + Ok(r) => SmlibCheck::Invalid(format!("SMLib check: {r}")), + Err(e) => SmlibCheck::Invalid(format!("SMLib check: {e}")), + }) +} + +/// Where every kernel call that fails from now on leaves its inputs for replay +/// (`solidcraft_smlib::set_dump_dir`: the call and its B-reps, which `Brep::read` reads back); +/// `None` stops it. +pub fn smlib_dump_dir(dir: Option<&std::path::Path>) { + solidcraft_smlib::set_dump_dir(dir); +} diff --git a/crates/kernel/src/whole_face.rs b/crates/kernel/src/whole_face.rs deleted file mode 100644 index 4d172fdb6..000000000 --- a/crates/kernel/src/whole_face.rs +++ /dev/null @@ -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 { - 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 = 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 = 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> { - 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 { - 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 { - 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 { - 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 { - 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::>()) - .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> { - 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::>()?; - // 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::>()) - .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::().signum(); - let mut out: Vec = Vec::new(); - let mut detours: Vec> = 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; diff --git a/crates/kernel/src/whole_face_tests.rs b/crates/kernel/src/whole_face_tests.rs deleted file mode 100644 index 28c0d902a..000000000 --- a/crates/kernel/src/whole_face_tests.rs +++ /dev/null @@ -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}"); -} diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs index 9d0703b70..2393c1417 100644 --- a/crates/kernel/tests/boolean_props.rs +++ b/crates/kernel/tests/boolean_props.rs @@ -13,7 +13,7 @@ //! copy the shrunk case into a `#[test]` below (ignored, with its issue, until the kernel is fixed). use proptest::prelude::*; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use solidcraft_kernel::{Body, BoolOp, boolean, box_solid, cylinder, measure, sphere, transform}; /// Relative volume tolerance. The same 0.2 % that `fuzz::boolean_case` uses. diff --git a/crates/kernel/tests/chamfer_curved_holder.rs b/crates/kernel/tests/chamfer_curved_holder.rs index b1616a372..7467f981d 100644 --- a/crates/kernel/tests/chamfer_curved_holder.rs +++ b/crates/kernel/tests/chamfer_curved_holder.rs @@ -3,8 +3,9 @@ //! meets the tangent junction of the bar's straight and round walls. The chamfer must trim //! against the round wall instead of extending that short seam outside the solid. -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; -use solidcraft_kernel::{Body, BoolOp, boolean, chamfer, cylinder, extrude}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; +use solidcraft_kernel::{Body, BoolOp, boolean, chamfer, cylinder, extrude, tangent_chain}; use std::f64::consts::PI; fn holder() -> Body { @@ -54,21 +55,28 @@ fn expected_removed(distance: f64) -> f64 { #[test] fn chamfer_the_top_lip_at_a_tangent_wall_junction() { let body = holder(); - let made = chamfer(&body, &[Vec3::new(10.0, 10.0, 60.0)], 2.0).unwrap(); + // The pick's tangent chain, as a chamfer feature selects it (the kernel blends the edges it + // is given). + let made = chamfer(&body, &tangent_chain(&body, &[Vec3::new(10.0, 10.0, 60.0)]).unwrap(), 2.0).unwrap(); assert!(made.validity().is_empty(), "{:?}", made.validity()); assert_eq!(made.crossed_face_loops().unwrap(), 0); let history = made.history().expect("the chamfer retains exact face provenance"); assert!(history.faces.iter().any(|f| f.origins.iter().any(|o| matches!(o, solidcraft_kernel::history::FaceOrigin::Edge { operand: 0, .. })))); - let mesh = |body: &Body| body.tessellate_with(0.0005, true).unwrap(); + // Fine enough that the meshes' chord error is below the tolerance: the removed volume + // measured on meshes is 37.404 at chord 0.002, 37.672 at 0.0005, 37.761 at 0.0001 and 37.759 + // at 0.00003, converged on the expected 37.762 (the chamfer as the chord between the contacts + // of a 2 mm ball). The planner's meshes of the two bodies differ, so their chord errors no + // longer cancel as truck's did. + let mesh = |body: &Body| body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.0001)).unwrap(); let before = mesh(&body).measure().volume; let after = mesh(&made); let removed = before - after.measure().volume; let expected = expected_removed(2.0); eprintln!("removed {removed:.8} mm³, expected {expected:.8} mm³"); assert!((removed - expected).abs() < 0.03, "removed {removed}, expected {expected}"); - assert!(!made.contains(Vec3::new(10.0, 9.5, 59.5)), "the old corner was removed"); - assert!(made.contains(Vec3::new(10.0, 7.0, 59.5)), "material behind the bevel remains"); - assert!(made.contains(Vec3::new(10.0, 10.0, 55.0)), "material below the bevel remains"); + assert_eq!(made.classify_point(Vec3::new(10.0, 9.5, 59.5)).unwrap(), solidcraft_kernel::PointClass::Outside, "the old corner was removed"); + assert_eq!(made.classify_point(Vec3::new(10.0, 7.0, 59.5)).unwrap(), solidcraft_kernel::PointClass::Inside, "material behind the bevel remains"); + assert_eq!(made.classify_point(Vec3::new(10.0, 10.0, 55.0)).unwrap(), solidcraft_kernel::PointClass::Inside, "material below the bevel remains"); // A closed mesh's signed volume is independent of the origin. let volume_about = |origin: Vec3| { after @@ -110,11 +118,11 @@ fn plate_with_stadium(plate: f64) -> Body { fn one_chamfer_pick_follows_the_tangent_chain_at_any_part_size() { for plate in [140.0, 145.0, 250.0] { let body = plate_with_stadium(plate); - let made = chamfer(&body, &[Vec3::new(0.0, 5.0, 20.0)], 1.0).unwrap(); + let made = chamfer(&body, &tangent_chain(&body, &[Vec3::new(0.0, 5.0, 20.0)]).unwrap(), 1.0).unwrap(); assert!(made.validity().is_empty(), "{:?}", made.validity()); // Two straight edges (c^2/2 * 40 each) and both end arcs (Pappus, c^2/2 * 2 pi (R - c/3)). let expected = 40.0 + 0.5 * 2.0 * PI * (5.0 - 1.0 / 3.0); - let volume = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; + let volume = |b: &Body| b.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; let removed = volume(&body) - volume(&made); assert!((removed - expected).abs() < 0.3, "plate {plate}: removed {removed}, expected {expected}"); assert_eq!(made.face_count(), body.face_count() + 4, "plate {plate}: one chamfer face per rim edge"); diff --git a/crates/kernel/tests/hidden_lines.rs b/crates/kernel/tests/hidden_lines.rs new file mode 100644 index 000000000..92bed7eca --- /dev/null +++ b/crates/kernel/tests/hidden_lines.rs @@ -0,0 +1,160 @@ +//! Hidden lines of bodies the kernel makes, through the production `prepare`, against closed forms. + +use solidcraft_geom::prelude::*; +use std::f64::consts::{FRAC_PI_3, PI}; + +use solidcore_record::brep; +use solidcore_record::{Seg2, Vec2, Vec3}; +use solidcraft_geom::hlr::{Line, Options, Placement, Source, View, Visibility, hidden_lines, prepare}; +use solidcraft_kernel::*; + +const TOLERANCE: f64 = 1e-3; + +/// Points along a drawn piece, a sixteenth of it apart. +fn points(s: &Seg2) -> Vec { + (0..=16).map(|i| s.point_at(f64::from(i) / 16.0)).collect() +} + +/// The lines of `body`, drawn looking along `d`, with the record they number into. +fn draw(body: &Body, d: Vec3, up: Vec3) -> (Vec, brep::Brep) { + let record = brep_record(body).unwrap(); + let o = Options::default(); + let def = prepare(&record, &o).unwrap(); + let placed = Placement { body: 0, rotation: [Vec3::new(1., 0., 0.), Vec3::new(0., 1., 0.), Vec3::new(0., 0., 1.)], translation: Vec3::ZERO }; + let view = View::new(d, up).unwrap(); + let drawing = hidden_lines(std::slice::from_ref(&def), &[placed], &view, &o, &|| false).unwrap(); + (drawing.lines, record) +} + +/// Whether a line is an edge whose record is a circle (`want`), or another edge. +fn is_circle(l: &Line, record: &brep::Brep, want: bool) -> bool { + matches!(l.source, Source::Edge { edge, .. } if matches!(record.edges.get(edge).map(|e| &e.curve), Some(brep::Curve::Circle { .. })) == want) +} + +/// Total drawn length of `lines` of a visibility. +fn total<'a>(lines: impl Iterator, v: Visibility) -> f64 { + lines.flat_map(|l| &l.pieces).filter(|p| p.visibility == v).flat_map(|p| &p.geometry).map(Seg2::length).sum() +} + +/// Total length of what lies under a visible line: seen straight along a wall, a far edge is at +/// best uncertain, and is not drawn because the near edge is. +fn under<'a>(lines: impl Iterator) -> f64 { + lines.flat_map(|l| &l.pieces).filter(|p| p.covered && p.visibility != Visibility::Visible).flat_map(|p| &p.geometry).map(Seg2::length).sum() +} + +fn uncovered_uncertain(lines: &[Line]) -> usize { + lines.iter().flat_map(|l| &l.pieces).filter(|p| p.visibility == Visibility::Uncertain && !p.covered).count() +} + +fn near(got: f64, want: f64, what: &str) { + assert!((got - want).abs() <= TOLERANCE, "{what}: {got} against {want}"); +} + +/// A cylinder of radius 10 cut by the plane x = 5: rims from -60 to 60 degrees. Seen along z each +/// rim is one arc of a third of a turn on the side x >= 5, the near one visible, the far one +/// behind it; a rim on the wrong angles would leave that side. +#[test] +fn a_cut_cylinders_rims_are_drawn_on_their_own_arc() { + let round = cylinder(Vec3::ZERO, Vec3::new(0., 0., 1.), 10., 20.).unwrap(); + let keep = box_solid(Vec3::new(5., -20., -5.), Vec3::new(25., 20., 25.)).unwrap(); + let body = boolean(&round, &keep, BoolOp::Intersect).unwrap().unwrap(); + let (lines, record) = draw(&body, Vec3::new(0., 0., -1.), Vec3::new(0., 1., 0.)); + let rim = 10. * 2. * FRAC_PI_3; + let rims = || lines.iter().filter(|l| is_circle(l, &record, true)); + near(total(rims(), Visibility::Visible), rim, "near rim"); + near(under(rims()), rim, "far rim"); + assert_eq!(uncovered_uncertain(&lines), 0, "{lines:?}"); + let drawn: Vec = rims().flat_map(|l| &l.pieces).flat_map(|p| &p.geometry).flat_map(points).collect(); + assert!(drawn.len() > 8, "{lines:?}"); + // Whichever way the view's x runs, the rims keep to one side of the axis, at the radius. + let side = drawn.iter().map(|p| p.x).fold(0., |a: f64, x| if x.abs() > a.abs() { x } else { a }).signum(); + for p in &drawn { + assert!((p.x.hypot(p.y) - 10.).abs() <= TOLERANCE && p.x * side >= 5. - TOLERANCE, "{p:?}"); + } + // The chord closes them: 2 * 10 * sin 60 on each end of the flat. + let flats = || lines.iter().filter(|l| is_circle(l, &record, false)); + let chord = 20. * FRAC_PI_3.sin(); + near(total(flats(), Visibility::Visible), chord, "near chord"); + near(under(flats()), chord, "far chord"); + // From the flat side, along x, the rims are level lines as wide as the chord. + let (lines, record) = draw(&body, Vec3::new(1., 0., 0.), Vec3::new(0., 0., 1.)); + let wide: Vec = + lines.iter().filter(|l| is_circle(l, &record, true)).flat_map(|l| &l.pieces).flat_map(|p| &p.geometry).flat_map(points).collect(); + let reach = wide.iter().map(|p| p.x.abs()).fold(0., f64::max); + near(reach, chord / 2., "rims from the flat side"); +} + +/// A hole of radius 5 through a 40 by 40 by 10 plate. Along z its near rim is a whole circle in +/// sight, the far one under it; from the side, its outline is two hidden lines the +/// plate's thickness long and 5 either side of the axis, and nothing of it shows. +#[test] +fn a_holes_rims_and_outline_are_drawn_where_they_are() { + let plate = box_solid(Vec3::new(-20., -20., 0.), Vec3::new(20., 20., 10.)).unwrap(); + let bore = cylinder(Vec3::new(0., 0., -5.), Vec3::new(0., 0., 1.), 5., 20.).unwrap(); + let body = boolean(&plate, &bore, BoolOp::Cut).unwrap().unwrap(); + let (lines, record) = draw(&body, Vec3::new(0., 0., -1.), Vec3::new(0., 1., 0.)); + let rims = || lines.iter().filter(|l| is_circle(l, &record, true)); + near(total(rims(), Visibility::Visible), 2. * PI * 5., "near rim"); + near(under(rims()), 2. * PI * 5., "far rim"); + assert_eq!(uncovered_uncertain(&lines), 0, "{lines:?}"); + let (lines, _) = draw(&body, Vec3::new(0., 1., 0.), Vec3::new(0., 0., 1.)); + let outline = || lines.iter().filter(|l| matches!(l.source, Source::Silhouette { .. })); + near(total(outline(), Visibility::Hidden), 2. * 10., "the outline's hidden length"); + near(total(outline(), Visibility::Visible), 0., "the outline in sight"); + for p in outline().flat_map(|l| &l.pieces).flat_map(|p| &p.geometry).flat_map(points) { + assert!((p.x.abs() - 5.).abs() <= TOLERANCE, "{p:?}"); + } +} + +/// The same hole seen at a slant, so the far rim is really part in sight and part behind the +/// plate: a point of it shows exactly where the near rim, an ellipse on screen, has it inside. +#[test] +fn a_holes_far_rim_shows_only_through_its_near_rim() { + let plate = box_solid(Vec3::new(-20., -20., 0.), Vec3::new(20., 20., 10.)).unwrap(); + let bore = cylinder(Vec3::new(0., 0., -5.), Vec3::new(0., 0., 1.), 5., 20.).unwrap(); + let body = boolean(&plate, &bore, BoolOp::Cut).unwrap().unwrap(); + let (d, up) = (Vec3::new(0., 0.25, -1.), Vec3::new(0., 1., 0.)); + let (lines, record) = draw(&body, d, up); + let view = View::new(d, up).unwrap(); + let screen = |p: Vec3| view.screen(p); + let (ax, by) = (screen(Vec3::new(5., 0., 0.)), screen(Vec3::new(0., 5., 0.))); + // Radius in the rim's own circle, of a screen point against that rim's centre. + let radial = |p: Vec2, z: f64| { + let c = screen(Vec3::new(0., 0., z)); + let (x, y) = (p.x - c[0], p.y - c[1]); + let det = ax[0] * by[1] - ax[1] * by[0]; + ((x * by[1] - y * by[0]) / det).hypot((ax[0] * y - ax[1] * x) / det) + }; + let (mut near_rim, mut far_shown, mut far_hidden) = (0., 0., 0.); + for p in lines.iter().filter(|l| is_circle(l, &record, true)).flat_map(|l| &l.pieces).filter(|p| !p.covered) { + let drawn: Vec = p.geometry.iter().flat_map(points).collect(); + let len: f64 = p.geometry.iter().map(Seg2::length).sum(); + if drawn.iter().all(|q| (radial(*q, 10.) - 1.).abs() <= 1e-3) { + assert_eq!(p.visibility, Visibility::Visible, "{p:?}"); + near_rim += len; + continue; + } + assert!(drawn.iter().all(|q| (radial(*q, 0.) - 1.).abs() <= 1e-3), "not on a rim: {p:?}"); + for q in &drawn { + let inside = radial(*q, 10.); + match p.visibility { + Visibility::Visible => assert!(inside <= 1. + 1e-3, "{q:?} shows, {inside} out of the near rim"), + Visibility::Hidden => assert!(inside >= 1. - 1e-3, "{q:?} hidden, {inside} in the near rim"), + Visibility::Uncertain => panic!("{p:?}"), + } + } + if p.visibility == Visibility::Visible { far_shown += len } else { far_hidden += len } + } + let ellipse: f64 = (0..4096) + .map(|i| { + let at = |k: f64| { + let t = k * std::f64::consts::TAU / 4096.; + Vec2::new(ax[0] * t.cos() + by[0] * t.sin(), ax[1] * t.cos() + by[1] * t.sin()) + }; + (at(f64::from(i) + 1.) - at(f64::from(i))).len() + }) + .sum(); + assert!((near_rim - ellipse).abs() <= 0.01, "near rim {near_rim} against {ellipse}"); + assert!((far_shown + far_hidden - ellipse).abs() <= 0.01, "far rim {far_shown} + {far_hidden} against {ellipse}"); + assert!(far_shown > 1. && far_hidden > 1., "{far_shown} {far_hidden}"); +} diff --git a/crates/kernel/tests/mesh_collision_equivalence.rs b/crates/kernel/tests/mesh_collision_equivalence.rs deleted file mode 100644 index 19d9051b7..000000000 --- a/crates/kernel/tests/mesh_collision_equivalence.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! Equivalence checks for SolidCraft's changes to the vendored truck crates. -//! -//! The vendored crates are outside the workspace, so their own tests never run in CI. Each -//! change that replaces an algorithm keeps the old one behind the crate's `test-hooks` feature -//! (on only for these tests) and these tests check the new one gives the same answers. - -use truck_meshalgo::analyzers::collision_test_hooks as collision; - -/// Mesh collision candidate search (sweep with per-triangle boxes): same collisions, same order. -#[test] -fn mesh_collision_same_as_before() { - match collision::same_collisions_in_the_same_order(0..200) { - Ok(n) => assert!(n > 0, "the random meshes produced no collisions to compare"), - Err(e) => panic!("{e}"), - } -} - -/// NaN coordinates in a mesh: the collision search goes on without a panic. -#[test] -fn mesh_collision_nan_triangles_do_not_panic() { - if let Err(e) = collision::nan_triangles_do_not_panic() { - panic!("{e}"); - } -} diff --git a/crates/kernel/tests/revolve_on_axis.rs b/crates/kernel/tests/revolve_on_axis.rs index c9439d827..2adc094c1 100644 --- a/crates/kernel/tests/revolve_on_axis.rs +++ b/crates/kernel/tests/revolve_on_axis.rs @@ -3,7 +3,7 @@ //! axis, a drill point whose tip does. Their volumes are analytic, and a half slot revolved about //! a centreline lying in a face of a plate, as a cut, takes what it should. -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use solidcraft_kernel::{BoolOp, boolean, box_solid, measure, revolve}; use std::f64::consts::{FRAC_PI_2, PI, TAU}; @@ -75,7 +75,7 @@ fn a_half_slot_revolved_about_a_centreline_in_a_face_cuts_it() { for turn in [PI, -PI, TAU] { let tool = revolve(&plane, std::slice::from_ref(&r), Vec2::ZERO, Vec2::new(1.0, 0.0), turn).unwrap().pop().unwrap(); // A half turn into the plate, or a full one, cuts a groove; a half turn out of it misses. - let into = turn.abs() > PI || tool.tessellate(0.01).unwrap().bounds().min.z < 9.0; + let into = turn.abs() > PI || tool.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().bounds().min.z < 9.0; let cut = boolean(&plate, &tool, BoolOp::Cut).unwrap().unwrap(); assert!(cut.validity().is_empty(), "flip {flip}, {turn}: {:?}", cut.validity()); let removed = whole - measure(&cut).unwrap().volume; diff --git a/crates/kernel/tests/shell_barrel.rs b/crates/kernel/tests/shell_barrel.rs index 718d626f3..957a99eb2 100644 --- a/crates/kernel/tests/shell_barrel.rs +++ b/crates/kernel/tests/shell_barrel.rs @@ -1,8 +1,9 @@ //! #2421: shelling a circular-meridian barrel must retain its curved wall through the rim. +use solidcraft_geom::prelude::*; use std::f64::consts::PI; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use solidcraft_kernel::history::FaceOrigin; use solidcraft_kernel::*; @@ -43,17 +44,26 @@ fn check_volume(body: &Body, lo: f64, hi: f64) { #[test] fn shell_of_a_revolved_barrel() { let barrel = barrel(); - let side = (0..barrel.face_count()) - .find_map(|i| match face_surface(&barrel, i) { - Some(s @ FaceSurface::Torus { major, minor, .. }) if (major - CENTRE).abs() < 1e-6 && (minor - RADIUS).abs() < 1e-6 => Some(s), - _ => None, - }) - .expect("barrel side is the inner sheet of a spindle torus"); - assert!(side.nearest(Vec3::new(15.0, 0.0, HALF_HEIGHT)).unwrap().dist(Vec3::new(14.0, 0.0, HALF_HEIGHT)) < 1e-6); + // The side is the inner (lemon) zone of a spindle torus: SMLib's torus describes only its + // outer zone, so the side is the exact rational surface of revolution of the arc. Two flat + // caps and that side; the solid is the closed-form barrel, 14 mm round at mid height (`contains` asks the display mesh, so a margin round it). + assert_eq!(barrel.face_count(), 3); + let planes = (0..barrel.face_count()).filter(|i| matches!(face_surface(&barrel, *i), Some(FaceSurface::Plane { .. }))).count(); + assert_eq!(planes, 2, "two caps and the curved side"); + let full = integral(RADIUS, 2.0 * HALF_HEIGHT) - integral(RADIUS, 0.0); + let volume = measure(&barrel).unwrap().volume; + assert!((volume - full).abs() < full * 1e-3, "{volume} vs {full}"); + for turn in [0.0, 1.0, 2.5, 4.0] { + let (c, s) = (f64::cos(turn), f64::sin(turn)); + assert!( + barrel.classify_point(Vec3::new(13.8 * c, 13.8 * s, HALF_HEIGHT)).unwrap() == solidcraft_kernel::PointClass::Inside + && barrel.classify_point(Vec3::new(14.2 * c, 14.2 * s, HALF_HEIGHT)).unwrap() == solidcraft_kernel::PointClass::Outside + ); + } let result = shell(&barrel, &[Vec3::new(0.0, 0.0, 2.0 * HALF_HEIGHT)], 2.0).unwrap(); assert!(result.validity().is_empty(), "{:?}", result.validity()); assert_eq!(result.shell_count(), 1); - let mesh = result.tessellate(0.005).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(0.005)).unwrap(); assert!(mesh.contains(Vec3::new(0.0, 0.0, 1.0)), "closed floor"); assert!(!mesh.contains(Vec3::new(0.0, 0.0, 3.0)), "open cavity"); assert!(mesh.contains(Vec3::new(13.0, 0.0, HALF_HEIGHT)), "barrel wall"); @@ -62,7 +72,8 @@ fn shell_of_a_revolved_barrel() { check_volume(&result, 2.0, 2.0 * HALF_HEIGHT); let history = result.history().expect("exact shell face history"); assert_eq!(history.operands, 1); - assert_eq!(history.faces.iter().filter(|f| matches!(f.origins.as_slice(), [FaceOrigin::Offset { operand: 0, .. }])).count(), 4); + // The inner wall and the inner floor, offsets of the barrel's side and bottom (the top opened). + assert_eq!(history.faces.iter().filter(|f| matches!(f.origins.as_slice(), [FaceOrigin::Offset { operand: 0, .. }])).count(), 2); let step = step_export(&[&result], "barrel shell").unwrap(); let imported = step_import(&step).unwrap(); assert_eq!(imported.bodies.len(), 1); @@ -81,7 +92,7 @@ fn barrel_shell_opens_either_or_both_caps_and_refuses_a_vanished_cavity() { } let result = shell(&barrel, &opened, 2.0).unwrap(); assert!(result.validity().is_empty()); - let mesh = result.tessellate(0.005).unwrap(); + let mesh = result.mesh(&crate::MeshTolerance::chord(0.005)).unwrap(); assert!(!mesh.contains(Vec3::new(0.0, 0.0, 1.0))); assert_eq!(mesh.contains(Vec3::new(0.0, 0.0, 25.8)), !both); check_volume(&result, 0.0, 2.0 * HALF_HEIGHT - if both { 0.0 } else { 2.0 }); diff --git a/crates/kernel/tests/tess_include_equivalence.rs b/crates/kernel/tests/tess_include_equivalence.rs deleted file mode 100644 index e6b946fdf..000000000 --- a/crates/kernel/tests/tess_include_equivalence.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Equivalence check for SolidCraft's change to the vendored tessellator's point-in-trim test. -//! -//! The vendored crates are outside the workspace, so their own tests never run in CI. The old -//! test is kept behind the crate's `test-hooks` feature (on only for kernel tests) and this -//! checks the faster one gives the same answer everywhere it is probed. - -use truck_meshalgo::tessellation::include_test_hooks; - -/// Point-in-trim with run boxes: same inside/outside answer as before on more than 100k points. -#[test] -fn tessellation_include_same_as_before() { - match include_test_hooks::include_answers_as_before(0..120) { - Ok(n) => assert!(n > 100_000, "only {n} points checked"), - Err(e) => panic!("{e}"), - } -} diff --git a/crates/kernel/tests/tess_loop_fill.rs b/crates/kernel/tests/tess_loop_fill.rs deleted file mode 100644 index 70055f52e..000000000 --- a/crates/kernel/tests/tess_loop_fill.rs +++ /dev/null @@ -1,121 +0,0 @@ -//! The fallback in the vendored tessellator that triangulates the boundary loop of a face that -//! came out with no triangle (a lens thinner than the tolerance). Its ear clipping is checked on -//! the polygons it can meet: convex, concave, either winding, with collinear points, and loops -//! it must refuse. -//! -//! The vendored crates are outside the workspace, so their own tests never run in CI; the -//! function is reached through the crate's `test-hooks` feature (on only for kernel tests). - -use truck_meshalgo::tessellation::loop_fill_test_hooks::ear_clipping; - -fn area2(points: &[[f64; 2]]) -> f64 { - points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum() -} - -/// The triangles turn the same way as the polygon, there are `n - 2` of them, and they add up to -/// its area: together they cover it once, with no overlap. -fn assert_covers_once(points: &[[f64; 2]]) { - let triangles = ear_clipping(points).expect("a simple polygon is triangulated"); - assert_eq!(triangles.len(), points.len() - 2); - let side = area2(points).signum(); - let mut sum = 0.0; - for t in &triangles { - let t = area2(&t.map(|i| points[i])); - assert!(t * side > 0.0, "a triangle turns the other way, or has no area: {t}"); - sum += t; - } - assert!((sum - area2(points)).abs() < 1e-9, "triangles cover {sum}, the polygon {}", area2(points)); -} - -#[test] -fn a_triangle_is_itself() { - let points = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; - assert_eq!(ear_clipping(&points), Some(vec![[0, 1, 2]])); -} - -#[test] -fn a_convex_polygon_either_way_round() { - let square = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]; - assert_covers_once(&square); - let mut reversed = square; - reversed.reverse(); - assert_covers_once(&reversed); -} - -#[test] -fn a_concave_polygon_either_way_round() { - // An L: the reflex corner is at (1, 1). - let l = [[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0], [1.0, 2.0], [0.0, 2.0]]; - assert_covers_once(&l); - let mut reversed = l; - reversed.reverse(); - assert_covers_once(&reversed); -} - -#[test] -fn a_thin_lens_made_of_an_arc_and_a_chord() { - let lens = [[0.0, 0.0], [1.0, -0.15], [2.0, 0.0]]; - assert_covers_once(&lens); - let more = [[0.0, 0.0], [0.5, -0.1], [1.0, -0.15], [1.5, -0.1], [2.0, 0.0]]; - assert_covers_once(&more); -} - -#[test] -fn collinear_points_on_a_side_are_kept_as_corners() { - let square = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]; - let triangles = ear_clipping(&square).expect("triangulated"); - assert_eq!(triangles.len(), 3); - let covered: f64 = triangles.iter().map(|t| area2(&t.map(|i| square[i]))).sum(); - assert!((covered - area2(&square)).abs() < 1e-9); -} - -#[test] -fn a_loop_without_area_is_refused() { - assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]), None, "three collinear points"); - assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 1.0], [0.0, 0.0], [1.0, 1.0]]), None, "a line walked twice"); -} - -#[test] -fn fewer_than_three_points_are_refused() { - assert_eq!(ear_clipping(&[]), None); - assert_eq!(ear_clipping(&[[0.0, 0.0]]), None); - assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 0.0]]), None); -} - -/// A loop that crosses itself (the #1648 face pinched to a point is one) would get overlapping -/// triangles, and so a wrong mesh that hides the problem. It is refused, symmetric or not. -#[test] -fn a_loop_crossing_itself_is_refused() { - let bowtie = [[0.0, 0.0], [2.0, 2.0], [2.0, 0.0], [0.0, 2.0]]; - assert_eq!(ear_clipping(&bowtie), None); - let lopsided = [[0.0, 0.0], [3.0, 2.0], [3.0, 0.0], [0.0, 1.0]]; - assert_eq!(ear_clipping(&lopsided), None); - let pinched = [[0.0, 0.0], [5.0, 0.0], [5.0, 0.3], [3.0, -0.1], [2.0, -0.1], [0.0, 0.3]]; - assert_eq!(ear_clipping(&pinched), None); -} - -/// The loop of a face closes on its first point: a point given twice in a row is a corner with no -/// area, and the polygon is still triangulated on the rest. -#[test] -fn a_repeated_point_is_handled_without_a_wrong_mesh() { - let points = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]]; - if let Some(triangles) = ear_clipping(&points) { - let covered: f64 = triangles.iter().map(|t| area2(&t.map(|i| points[i]))).sum(); - assert!((covered - area2(&points)).abs() < 1e-9, "triangles cover {covered}"); - } -} - -/// The largest loop the fallback takes, as a circle with a bite out of it: all of it is covered -/// exactly once. -#[test] -fn the_largest_loop_is_triangulated() { - let n = 256; - let points: Vec<[f64; 2]> = (0..n) - .map(|i| { - let t = std::f64::consts::TAU * i as f64 / n as f64; - let r = if i % 16 == 0 { 0.6 } else { 1.0 }; - [r * t.cos(), r * t.sin()] - }) - .collect(); - assert_covers_once(&points); -} diff --git a/crates/kernel/tests/trimmed_spline_projection.rs b/crates/kernel/tests/trimmed_spline_projection.rs deleted file mode 100644 index 26a63090a..000000000 --- a/crates/kernel/tests/trimmed_spline_projection.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! Original analytic surfaces exercising trim projection (#1974), without an external CAD fixture. -use truck_meshalgo::prelude::*; -use truck_modeling::{self as mt, BoundedCurve, InnerSpace}; - -fn mesh(surface: mt::Surface, curves: Vec) -> PolygonMesh { - let vertices: Vec<_> = curves.iter().map(|c| mt::Vertex::new(c.front())).collect(); - let count = vertices.len(); - let edges: Vec<_> = curves.into_iter().enumerate().map(|(i, c)| mt::Edge::new_unchecked(&vertices[i], &vertices[(i + 1) % count], c)).collect(); - let face = mt::Face::new_unchecked(vec![edges.into()], surface); - let shell = mt::Shell::from(vec![face]).robust_triangulation(0.001); - let polygon = shell.face_iter().next().unwrap().surface().unwrap(); - assert!(polygon.faces().triangle_iter().next().is_some(), "the trimmed face must remain visible"); - polygon -} - -#[test] -fn approximate_boundary_does_not_escape_a_bounded_spline() { - // S(u,v) = (50u + 10v, .001v, 10u² + 4v), 0 <= u,v <= 1. - // Near u=1 its tangents are almost parallel. A slightly approximate top edge - // sends an undamped search hinted from the preceding point to u>1. - let p = mt::Point3::new; - let surface = mt::BSplineSurface::new( - (mt::KnotVec::bezier_knot(2), mt::KnotVec::bezier_knot(1)), - vec![vec![p(0., 0., 0.), p(10., 0.001, 4.)], vec![p(25., 0., 0.), p(35., 0.001, 4.)], vec![p(50., 0., 10.), p(60., 0.001, 14.)]], - ); - let curves = vec![ - mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![p(60., 0.001, 14.), p(35., 0., 4.), p(10., 0.001, 4.)]).into(), - mt::Line(p(10., 0.001, 4.), p(0., 0., 0.)).into(), - mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![p(0., 0., 0.), p(25., 0., 0.), p(50., 0., 10.)]).into(), - mt::Line(p(50., 0., 10.), p(60., 0.001, 14.)).into(), - ]; - let mesh = mesh(mt::Surface::BSplineSurface(surface), curves); - for uv in mesh.uv_coords() { - assert!((-1e-6..=1. + 1e-6).contains(&uv.x) && (-1e-6..=1. + 1e-6).contains(&uv.y), "parameter {uv:?}"); - } - assert!(mesh.positions().iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite())); -} - -#[test] -fn a_trim_crossing_a_closed_nurbs_seam_is_a_small_cylinder_patch() { - let (radius, angle, bottom, top) = (10.0_f64, 0.1_f64, 2.0, 5.0); - let w = std::f64::consts::FRAC_1_SQRT_2; - let circle = [(1., 0., 1.), (1., 1., w), (0., 1., 1.), (-1., 1., w), (-1., 0., 1.), (-1., -1., w), (0., -1., 1.), (1., -1., w), (1., 0., 1.)]; - let ctrl = circle - .iter() - .map(|&(x, y, w)| vec![mt::Vector4::new(radius * x * w, radius * y * w, 0., w), mt::Vector4::new(radius * x * w, radius * y * w, 10. * w, w)]) - .collect(); - let surface = mt::NurbsSurface::new(mt::BSplineSurface::new( - (mt::KnotVec::from(vec![0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.]), mt::KnotVec::bezier_knot(1)), - ctrl, - )); - let at = |theta: f64, z| mt::Point3::new(radius * theta.cos(), radius * theta.sin(), z); - let arc = |z, reverse| { - let w = angle.cos(); - let mut ctrl = vec![at(-angle, z).to_homogeneous(), mt::Vector4::new(radius, 0., z * w, w), at(angle, z).to_homogeneous()]; - if reverse { - ctrl.reverse(); - } - mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), ctrl)).into() - }; - let curves = vec![ - arc(bottom, false), - mt::Line(at(angle, bottom), at(angle, top)).into(), - arc(top, true), - mt::Line(at(-angle, top), at(-angle, bottom)).into(), - ]; - let mesh = mesh(mt::Surface::NurbsSurface(surface), curves); - for p in mesh.positions() { - assert!(p.x >= radius * angle.cos() - 1e-6 && p.x <= radius + 1e-6, "{p:?}"); - assert!(p.y.abs() <= radius * angle.sin() + 1e-6 && (bottom - 1e-6..=top + 1e-6).contains(&p.z), "{p:?}"); - } - let area: f64 = mesh - .faces() - .triangle_iter() - .map(|t| { - let [a, b, c] = [0, 1, 2].map(|i| mesh.positions()[t[i].pos]); - (b - a).cross(c - a).magnitude() * 0.5 - }) - .sum(); - assert!((area - radius * 2.0 * angle * (top - bottom)).abs() < 0.01, "area {area}"); -} - -#[test] -fn an_affine_planes_unit_chart_does_not_clip_a_trim() { - let p = mt::Point3::new; - let points = [p(10., 20., 0.), p(13., 20., 0.), p(13., 22., 0.), p(10., 22., 0.)]; - let curves = (0..4).map(|i| mt::Line(points[i], points[(i + 1) % 4]).into()).collect(); - let mesh = mesh(mt::Plane::new(p(0., 0., 0.), p(1., 0., 0.), p(0., 1., 0.)).into(), curves); - for p in mesh.positions() { - assert!((10. - 1e-6..=13. + 1e-6).contains(&p.x) && (20. - 1e-6..=22. + 1e-6).contains(&p.y), "{p:?}"); - } -} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 057cca258..47c03f4da 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -15,3 +15,5 @@ serde_json = { workspace = true } [dev-dependencies] # The renderer `solidcraft-cli mcp` installs, so the tests' screenshots are drawn as the server's. solidcraft-gpu = { workspace = true } +# Synthetic reference pictures for the compare_picture test. +image = { workspace = true } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 2ad8d52ec..d84e36183 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -7,6 +7,8 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use solidcraft_engine::Session; use solidcraft_engine::control_pending; +use solidcraft_engine::panels::ActionSink; +use solidcraft_engine::panels::commands::LayoutCatalogue; use solidcraft_engine::render::StandardView; use solidcraft_engine::schema::ParamCheck; use solidcraft_engine::view::Guides; @@ -212,9 +214,13 @@ impl Remote { } } - /// Connect now, if the app is there (`new` does not); the error says why not. + /// See whether the app is there now (`new` does not); the error says why not. The connection + /// doesn't stay open: the app closes one that shows no token within a few seconds, and the + /// first call may be long away. That call connects again. pub fn try_connect(&mut self) -> std::io::Result<()> { - self.reconnect() + self.reconnect()?; + self.drop_conn(); + Ok(()) } /// Failing to reach the app at all is `NotConnected`, so [`Remote::explain`] can tell it from @@ -555,6 +561,11 @@ impl Remote { /// `strict` refuses a call that breaks its command's contract without sending it, and `warn` /// sends it and adds the issues to the app's reply. fn execute_checked(&mut self, params: Value) -> Result { + if let Some(id) = step_command(¶ms).filter(|id| solidcraft_engine::panels::commands::is_command(id)) { + let empty = json!({}); + solidcraft_engine::panels::commands::parse_command(id, params.get("params").filter(|p| !p.is_null()).unwrap_or(&empty)) + .map_err(solidcraft_engine::panels::commands::error_text)?; + } if self.app_checks() { let params = self.at_level(params); let reply = self.call_once("engine.execute", params, true); @@ -612,6 +623,7 @@ impl Backend for Remote { "control.pending" => self.pending_status(), "engine.execute" if self.param_check != ParamCheck::Off => self.execute_checked(params), "engine.batch" if self.param_check != ParamCheck::Off => self.batch_checked(params), + "engine.script" if self.param_check != ParamCheck::Off => self.call_once(method, self.at_level(params), true), _ => self.call_once(method, params, true), } } @@ -640,6 +652,8 @@ pub struct Headless { pub session: Session, /// Orientation for renders; the camera is refitted to the model every time. pub view: StandardView, + /// Application layout persists across calls, outside Session/document undo. + pub panels: solidcraft_engine::panels::PanelResult, } impl Default for Headless { @@ -658,16 +672,77 @@ impl Headless { } Err(e) => session.log.push(format!("image host unavailable: {e}")), } - Headless { session, view: StandardView::Iso } + Headless { session, view: StandardView::Iso, panels: solidcraft_engine::panels::commands::InMemoryPanelBackend::empty() } } + pub fn with_panels(mut self, panels: solidcraft_engine::panels::commands::InMemoryPanelBackend) -> Self { + self.panels = Ok(panels); + self + } + fn execute_command(&mut self, id: &str, params: &Value) -> Result { + use solidcraft_engine::panels::commands; + if commands::is_command(id) { + self.panels.as_mut().map_err(|reason| commands::error_text(reason.clone()))?.execute(id, params).map_err(commands::error_text) + } else { + self.session.execute(id, params).map_err(|e| e.to_string()) + } + } + fn panel_sequence(&mut self, method: &str, p: &Value, steps: &[Value]) -> Result { + use solidcraft_engine::panels::{Rule, commands, error}; + if steps.len() > 100_000 { + return Err("script too long".into()); + } + if method == "engine.batch" + && let Some(refusal) = solidcraft_engine::batch_preflight::check(steps, self.session.param_check, &[]) + { + return Ok(refusal.reply(steps.len())); + } + let panels = steps.iter().filter(|step| step_command(step).is_some_and(commands::is_command)).count(); + if method == "engine.batch" && p.get("rollback").and_then(Value::as_bool).unwrap_or(true) { + if panels != steps.len() { + return Err(commands::error_text(error( + Rule::Capability, + "atomic mixed document/layout batches are unavailable; use rollback:false or separate transactions", + ))); + } + return self.panels.as_mut().map_err(|reason| commands::error_text(reason.clone()))?.batch(steps).map_err(commands::error_text); + } + let mut results = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let empty = json!({}); + let params = step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty); + let result = step_command(step).ok_or_else(|| "missing command".to_string()).and_then(|id| self.execute_command(id, params)); + match result { + Ok(result) => results.push(result), + Err(error) if method == "engine.batch" => return Ok(commands::sequential_failure(i, step_command(step), error, results)), + Err(error) => return Err(error), + } + } + if method == "engine.batch" { Ok(json!({"completed":results.len(),"results":results,"undone":0})) } else { Ok(json!(results)) } + } +} + +fn step_command(step: &Value) -> Option<&str> { + step.get("command").or_else(|| step.get("id")).and_then(Value::as_str) } fn dim(p: &Value, k: &str, default: f64) -> u32 { p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(default).clamp(16.0, 4096.0) as u32 } -impl Backend for Headless { - fn call(&mut self, method: &str, p: Value) -> Result { +impl Headless { + fn call_at_current_level(&mut self, method: &str, p: Value) -> Result { + if matches!(method, "engine.execute" | "command") && step_command(&p).is_some_and(solidcraft_engine::panels::commands::is_command) { + let empty = json!({}); + return self.execute_command(step_command(&p).unwrap_or_default(), p.get("params").filter(|p| !p.is_null()).unwrap_or(&empty)); + } + if matches!(method, "engine.script" | "engine.batch") + && let Some(steps) = p + .as_array() + .or_else(|| p.get("commands").and_then(Value::as_array)) + .filter(|steps| steps.iter().any(|step| step_command(step).is_some_and(solidcraft_engine::panels::commands::is_command))) + { + return self.panel_sequence(method, &p, steps); + } let s = &mut self.session; let str_p = |k: &str| p.get(k).and_then(Value::as_str); match method { @@ -684,7 +759,7 @@ impl Backend for Headless { match v { // Fit keeps the orientation, also of a camera `view.apply` chose. "fit" => { - let b = solidcraft_engine::view::bounds(s); + let b = solidcraft_engine::view::bounds(s).map_err(|e| e.to_string())?; if let Some(c) = s.camera.as_mut() { c.fit(&b); } @@ -699,18 +774,21 @@ impl Backend for Headless { "ui.render" => { let (w, h) = (dim(&p, "width", 1280.0), dim(&p, "height", 800.0)); // The camera `view.apply` chose, else the standard view framing the model. - let cam = s.camera.unwrap_or_else(|| { - let mut cam = solidcraft_engine::view::home_camera(s); - cam.set_view(self.view); - cam - }); + let cam = match s.camera { + Some(cam) => cam, + None => { + let mut cam = solidcraft_engine::view::home_camera(s).map_err(|e| e.to_string())?; + cam.set_view(self.view); + cam + } + }; // The grid and the axes are drawn unless the request leaves them out. let shown = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(true); let guides = Guides { grid: shown("grid"), axes: shown("axes") }; let path = str_p("path").ok_or("missing `path`")?; // A path outside the agent's folders is refused before anything is drawn. solidcraft_engine::io::vfs::check(path).map_err(|e| format!("{path}: {e}"))?; - let scene = solidcraft_engine::view::scene_with_guides(s, &cam, s.section, guides); + let scene = solidcraft_engine::view::scene_with_guides(s, &cam, s.section, guides).map_err(|e| e.to_string())?; // Drawn on the GPU by the renderer the host installed (`solidcraft-cli mcp`). let png = solidcraft_engine::capture::png(&scene, &cam, w, h)?; solidcraft_engine::io::vfs::write(path, &png.bytes).map_err(|e| format!("{path}: {e}"))?; @@ -731,6 +809,19 @@ impl Backend for Headless { other => Err(format!("unknown method `{other}`")), } } +} +impl Backend for Headless { + fn call(&mut self, method: &str, p: Value) -> Result { + let own = self.session.param_check; + if matches!(method, "engine.execute" | "command" | "engine.batch" | "engine.script") + && let Some(value) = p.get("param_check") + { + self.session.param_check = value.as_str().and_then(ParamCheck::parse).ok_or("`param_check` must be off, warn or strict")?; + } + let reply = self.call_at_current_level(method, p); + self.session.param_check = own; + reply + } fn has_ui(&self) -> bool { false } @@ -766,7 +857,10 @@ impl Auto { /// Switch to the app when the session is still empty and one is running. fn look_for_app(&mut self) { - let empty = self.headless.as_ref().is_some_and(|h| h.session.doc.features.is_empty()); + let empty = self.headless.as_ref().is_some_and(|h| { + h.session.doc.features.is_empty() + && h.panels.as_ref().is_ok_and(|panels| panels.service.inspect().revision == 0 && panels.catalogue.state().user_count() == 0) + }); if !empty { return; } diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index f3e3c5407..f416daa29 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -48,25 +48,37 @@ pub fn agent_scope_with(recovery: Option, allowed: impl IntoIterator> = std::sync::OnceLock::new(); + /// This server's own folder for screenshots it reads back and deletes (`screenshot` without a -/// `path`): a new `/solidcraft-mcp--` made on first use (never one that was there -/// already, which could be someone else's), private to the user on Unix. `` is spelled with -/// long names (`vfs::temp_dir`), since the scope refuses short (8.3) ones. +/// `path`): a new `/solidcraft-mcp--` made when the path scope is built, or on the +/// first screenshot without a scope. Never reuse an existing folder, which could be someone +/// else's. It is private to the user on Unix. `` is spelled with long names (`vfs::temp_dir`), +/// since the scope refuses short (8.3) ones. pub fn scratch_dir() -> Option { - static DIR: std::sync::OnceLock> = std::sync::OnceLock::new(); - DIR.get_or_init(|| { - let b = std::fs::DirBuilder::new(); - #[cfg(unix)] - let mut b = b; - #[cfg(unix)] - std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); - let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0); - (0..16u32).find_map(|i| { - let d = vfs::temp_dir().join(format!("solidcraft-mcp-{}-{:x}", std::process::id(), seed.wrapping_add(i))); - b.create(&d).ok().map(|()| d) + SCRATCH_DIR + .get_or_init(|| { + let b = std::fs::DirBuilder::new(); + #[cfg(unix)] + let mut b = b; + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); + let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0); + (0..16u32).find_map(|i| { + let d = vfs::temp_dir().join(format!("solidcraft-mcp-{}-{:x}", std::process::id(), seed.wrapping_add(i))); + b.create(&d).ok().map(|()| d) + }) }) - }) - .clone() + .clone() +} + +/// Best-effort cleanup at process shutdown, after all MCP activity has stopped. Only remove +/// this process's empty scratch folder: saved files, other processes' folders and the recovery +/// folder must survive. Looking up the cached path never creates a folder just to clean it up. +pub fn cleanup_scratch_dir() { + if let Some(Some(dir)) = SCRATCH_DIR.get() { + let _ = std::fs::remove_dir(dir); + } } #[cfg(test)] diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 8f9fc4efe..b87cbef62 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -25,17 +25,37 @@ const RESOURCE_NOT_FOUND: i64 = -32002; /// Most messages in one JSON-RPC batch. const MAX_BATCH: usize = 1000; +/// What every MCP client is told at `initialize`: how to plan, build and verify a part. It stays +/// version-neutral (no workaround for a quirk of the current kernel or solver: those belong in +/// `skills/solidcraft-modeling/reference.md`, which `skill_reference` serves per release), and +/// `tests::instructions_name_only_real_tools` checks every tool and command id it names. const INSTRUCTIONS: &str = "SolidCraft is an independent parametric 3D CAD app, and these tools drive it: when its window is \ -open the user watches the model appear, otherwise a headless session builds it. When asked to design or build a part \ -(a bracket, an enclosure, a gear) do it with these tools straight away; nothing needs explaining first. Units are millimetres \ -and degrees in expressions (internally radians), Z is up. Model like this: `sketch.create {plane: XY}`, draw \ -(`sketch.rectangle.two_point {p0, p1}`, `sketch.circle.center {center, radius}`, `sketch.line {points, closed}`), constrain \ -and dimension (`sketch.dimension {entities, value}`; values may name parameters), `sketch.finish`, then features \ -(`solid.extrude {distance, operation?: new|join|cut|intersect}`, `solid.revolve`, `solid.fillet {edges: [[x,y,z] point on \ -edge], radius}`, `solid.chamfer`, patterns, mirror, primitives). Use `batch` for several steps at once, \ -`list_commands` for ids and parameter docs, `describe_command` for a command's schemas, `inspect_design` / `measure` to verify, \ -`body_topology` to find edge points, `set_parameter` to drive the design and `screenshot` to look at it. A call whose error \ -starts `still running:` was not cancelled: don't send it again; `pending` waits for its result."; +open the user watches the model appear, otherwise a headless session builds it. When asked to design or build a part, do it \ +with these tools straight away. Units are millimetres and degrees in expressions, Z is up.\n\n\ +Start: for anything beyond one primitive, call `skill_reference {\"skill\":\"solidcraft-modeling\"}` first (command shapes, \ +ids, plane axes, worked examples and the known traps of this version; `file: \"SKILL.md\"` has the workflow). Then \ +`inspect_design {\"measure\":false,\"sketches\":false}` to see what is already there.\n\n\ +Plan: work the numbers out first (the parameters, the expected volume and bounding box after each stage, the world point you \ +will use for each edge or face pick). Then build in a few `batch` calls (all-or-nothing; the reply names the failing step; \ +`save`, `measure` and `set_parameter` can be steps). Use `verbose: false`. Name every feature. `list_commands {\"filter\": word}` \ +gives ids and one-line parameter docs (never unfiltered: it also takes prefix, panel, compact: true and limit); `describe_command` gives one command's docs and schemas.\n\n\ +Routes: a plate, block, boss, standoff or hole is cheapest as a primitive with expression fields (`solid.box`, `solid.cylinder`, \ +`solid.hole`, `solid.fillet`, `solid.shell`, patterns and mirror), no sketch. Sketch when the profile is not a box or a circle. \ +Fillet outside edges before shelling, build inside features after the shell, then the holes and cuts through walls. Give a blind \ +hole or a hole through one wall of a hollow part its depth.\n\n\ +Parametric: a size or position that must follow a parameter is an expression in a feature field (`\"L/2 - 10\"`), a sketch \ +dimension to `\"origin\"` or an edge, or a pattern spacing; a plain number never follows a parameter. Every sketch must end at \ +dof 0 (`sketch.solve` reports it). A pick (`edges: [[x,y,z]]`, `faces: [[x,y,z]]`) is a number that snaps to the nearest edge \ +or face and follows it when parameters change.\n\n\ +Verify: `measure {}` after each stage and compare volume and bbox with your numbers; `ok: true` alone proves nothing: a cut \ +that leaves the volume unchanged has missed, a join that adds a body did not touch. Positions of holes and bosses come from \ +`body_topology` (cylinder origin, axis and radius), not from the volume or the centre of mass of a symmetric part. To check \ +that the design follows its parameters, `check_parameters {\"set\": {name: value}}` tries the values and puts the design \ +back (volume, errors, cylinder axes), or change them in one `batch` with `coalesce_parameters: true` (one rebuild), `measure`, \ +then set them back the same way before saving.\n\n\ +Fix, don't rebuild: a wrong number in a feature is changed with `timeline.edit` or `parameters.change` on its input \ +(`parameters.list {\"filter\":\"feature\"}` names them); `edit.checkpoint` and `edit.restore_checkpoint` go back exactly.\n\n\ +A call whose error starts `still running:` was not cancelled: don't send it again; `pending` waits for its result."; pub struct Server { backend: Box, diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6c897500e..54ad7d2b3 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -10,6 +10,315 @@ fn server() -> Server { Server::new(Box::new(Headless::default())) } +fn panel_headless() -> Headless { + Headless::new(solidcraft_engine::Session::default()).with_panels(solidcraft_engine::panels::fixture_command_backend().unwrap()) +} +fn panel_mcp_steps() -> Vec { + vec![ + json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"log","destination":{"type":"new_section","section":"logs","index":0, + "location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}), + json!({"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}), + ] +} +#[test] +fn headless_panel_single_batch_and_script_keep_one_backend_and_never_change_the_session() { + use crate::Backend; + let mut one = panel_headless(); + let mut batch = panel_headless(); + let mut script = panel_headless(); + let doc = one.session.doc.clone(); + let model = one.session.model.state(); + let before = (one.session.document_id.clone(), one.session.revision, one.session.undo.len(), one.session.is_dirty(), one.session.camera); + for step in panel_mcp_steps() { + one.call("engine.execute", step).unwrap(); + } + batch.call("engine.batch", json!({"commands":panel_mcp_steps()})).unwrap(); + script.call("engine.script", json!({"commands":panel_mcp_steps()})).unwrap(); + let state = one.call("engine.execute", json!({"command":"layout.get"})).unwrap(); + assert_eq!(batch.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]); + assert_eq!(script.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]); + assert_eq!(state["state"]["capabilities"]["native_windows"], false); + assert_eq!((one.session.document_id.clone(), one.session.revision, one.session.undo.len(), one.session.is_dirty(), one.session.camera), before); + assert!(std::sync::Arc::ptr_eq(&doc, &one.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &one.session.model.state())); + one.call("engine.script", json!({"commands":[{"command":"layout.save","params":{"name":"MCP saved"}},{"command":"layout.reset"}]})).unwrap(); + one.call("engine.execute", json!({"command":"layout.apply","params":{"name":"MCP saved"}})).unwrap(); + assert_eq!(one.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]); +} +#[test] +fn mcp_panel_tools_publish_structured_errors_and_committed_state_through_shared_backend() { + let mut s = Server::new(Box::new(panel_headless())); + let input = panel_mcp_steps()[0].clone(); + let result = tool(&mut s, "execute", input); + assert_eq!(result["layout"]["instances"][0]["id"], "log"); + let result = tool( + &mut s, + "batch", + json!({"commands":[ + {"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}, + {"command":"panel.peek","params":{"target":{"type":"instance","id":"log"}}}]}), + ); + assert_eq!(result["completed"], 2); + let result = raw_tool(&mut s, "execute", json!({"command":"panel.focus","params":{"id":"fixture.log"}})); + assert_eq!(result["result"]["isError"], true); + assert_eq!(result["result"]["structuredContent"]["panel_error"]["rule"], "exactly_once"); + let result = raw_tool(&mut s, "execute", json!({"command":"layout.get","params":{"unknown":true}})); + assert_eq!(result["result"]["structuredContent"]["panel_error"]["rule"], "schema"); +} +#[test] +fn headless_catalogue_atomic_batch_failure_keeps_presets_and_layout_and_session_only_is_truthful() { + use crate::Backend; + use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue}; + let mut h = panel_headless(); + let state = h.panels.as_ref().unwrap().service.inspect(); + let catalogue = h.panels.as_ref().unwrap().catalogue.state().clone(); + let error = h + .call( + "engine.batch", + json!({"commands":[ + {"command":"layout.save","params":{"name":"Not committed"}}, + {"command":"layout.workspace.select","params":{"workspace":"not-registered"}}]}), + ) + .unwrap_err(); + assert_eq!(solidcraft_engine::panels::commands::structured_error(&error).unwrap()["rule"], "missing_target"); + assert_eq!(h.panels.as_ref().unwrap().service.inspect(), state); + assert_eq!(h.panels.as_ref().unwrap().catalogue.state(), &catalogue); + let mut plain = Headless::default(); + let got = plain.call("engine.execute", json!({"command":"panel.list"})).unwrap(); + assert!(got["kinds"].as_array().unwrap().is_empty()); + assert_eq!(got["state"]["capabilities"]["native_windows"], false); + assert!(plain.call("engine.execute", json!({"command":"layout.reset"})).is_err()); + assert!(solidcraft_engine::Session::default().run_script(&json!({"commands":[{"command":"layout.get"}]})).is_err()); +} + +#[test] +fn auto_backend_keeps_headless_layout_work_even_without_document_features() { + use crate::Backend; + use std::cell::Cell; + use std::rc::Rc; + let mut headless = panel_headless(); + headless.call("engine.execute", json!({"command":"layout.save","params":{"name":"Owned headless layout"}})).unwrap(); + let discoveries = Rc::new(Cell::new(0)); + let seen = discoveries.clone(); + let mut auto = crate::Auto::new( + headless, + Box::new(move || { + seen.set(seen.get() + 1); + None + }), + None, + ); + assert_eq!(auto.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["workspace"], "fixture.workspace"); + assert_eq!(discoveries.get(), 0, "owned layout must not be discarded while probing for an app"); +} + +#[test] +fn remote_panel_single_batch_and_script_forward_to_one_authoritative_backend() { + use crate::Backend; + let authoritative = std::sync::Arc::new(std::sync::Mutex::new(solidcraft_engine::panels::fixture_command_backend().unwrap())); + let state = authoritative.clone(); + // This is an authored local transport fixture, never run during implementation. + let (addr, seen) = scripted_app(move |request| { + let mut backend = state.lock().unwrap(); + let params = &request["params"]; + let result = match request["method"].as_str() { + Some("engine.execute") => backend.execute(params["command"].as_str().unwrap(), params.get("params").unwrap_or(&json!({}))), + Some("engine.batch") => backend.batch(params["commands"].as_array().unwrap()), + Some("engine.script") => { + let mut replies = Vec::new(); + for step in params["commands"].as_array().unwrap() { + replies.push(backend.execute(step["command"].as_str().unwrap(), step.get("params").unwrap_or(&json!({}))).unwrap()); + } + Ok(json!(replies)) + } + _ => return json!({"ok":false,"error":"unknown method"}), + }; + match result { + Ok(result) => json!({"ok":true,"result":result}), + Err(reason) => json!({"ok":false,"error":solidcraft_engine::panels::commands::error_text(reason)}), + } + }); + let mut remote = crate::Remote::connect_with_token(&addr, Some("0123456789abcdef0123456789abcdef")).unwrap(); + remote.call("engine.execute", panel_mcp_steps()[0].clone()).unwrap(); + remote + .call( + "engine.batch", + json!({"commands":[panel_mcp_steps()[1].clone(),{"command":"panel.peek","params":{"target":{"type":"instance","id":"log"}}}]}), + ) + .unwrap(); + authoritative.lock().unwrap().execute("panel.collapse", &json!({"target":{"type":"instance","id":"log"},"collapsed":false})).unwrap(); + assert_eq!( + remote.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["sections"][0]["collapsed"], + false, + "remote reads external live changes" + ); + remote + .call("engine.script", json!({"commands":[{"command":"layout.save","params":{"name":"Remote saved"}},{"command":"layout.reset"}]})) + .unwrap(); + assert!(remote.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["instances"].as_array().unwrap().is_empty()); + let seen = seen.lock().unwrap(); + assert!(seen.1.iter().any(|method| method == "engine.batch")); + assert!(seen.1.iter().any(|method| method == "engine.script")); +} + +#[test] +fn headless_null_params_match_all_panel_routes_and_normal_document_sequences() { + use crate::Backend; + let mut headless = panel_headless(); + let expected = headless.call("engine.execute", json!({"command":"panel.list","params":null})).unwrap(); + for (method, rollback) in [("engine.batch", true), ("engine.batch", false), ("engine.script", false)] { + let reply = headless + .call( + method, + json!({"rollback":rollback,"commands":[ + {"command":"panel.list","params":null},{"command":"layout.get","params":null}, + ]}), + ) + .unwrap(); + let results = if method == "engine.script" { &reply } else { &reply["results"] }; + assert_eq!(results[0], expected); + assert_eq!(results[1]["state"], expected["state"]); + } + for method in ["engine.batch", "engine.script"] { + let previous = headless.session.document_id.clone(); + let reply = headless + .call( + method, + json!({"rollback":false,"commands":[ + {"command":"file.new","params":null},{"command":"panel.list","params":null},{"command":"parameters.list","params":null}, + ]}), + ) + .unwrap(); + assert!(reply.get("failed").is_none(), "{reply}"); + assert_ne!(headless.session.document_id, previous); + } +} + +struct LayoutFallbackBackend { + headless: Headless, + calls: Vec<(String, String)>, +} +impl LayoutFallbackBackend { + fn new() -> Self { + Self { headless: panel_headless(), calls: Vec::new() } + } +} +impl crate::Backend for LayoutFallbackBackend { + fn call(&mut self, method: &str, params: Value) -> Result { + self.calls.push((method.into(), params.get("command").and_then(Value::as_str).unwrap_or_default().into())); + if method == "engine.batch" { + return Err("engine.batch unavailable: fixture has no atomic endpoint".into()); + } + crate::Backend::call(&mut self.headless, method, params) + } + fn has_ui(&self) -> bool { + false + } + fn in_process(&self) -> bool { + true + } + fn describe(&self) -> String { + "synthetic layout fallback boundary".into() + } +} +fn fallback_tool_reply(backend: &mut LayoutFallbackBackend, args: Value) -> (Value, Value) { + let tool = crate::tools::call_tool(backend, "batch", &args); + let body = serde_json::from_str(tool["content"][0]["text"].as_str().unwrap()).unwrap(); + (tool, body) +} + +#[test] +fn atomic_tool_layout_batches_never_emulate_an_unavailable_backend_with_document_undo() { + use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue}; + let open = panel_mcp_steps()[0].clone(); + for steps in [ + json!([open.clone()]), + json!([open.clone(),{"command":"parameters.change","params":{"name":"broken","expression":"("}}]), + json!([{"command":"execute","params":{"command":"panel.open","params":open["params"]}}]), + ] { + let mut backend = LayoutFallbackBackend::new(); + let before = backend.headless.panels.as_ref().unwrap().service.inspect(); + let catalogue = backend.headless.panels.as_ref().unwrap().catalogue.state().clone(); + let document = backend.headless.session.doc.clone(); + let model = backend.headless.session.model.state(); + let session = (backend.headless.session.revision, backend.headless.session.undo.len(), backend.headless.session.is_dirty()); + let (tool, body) = fallback_tool_reply(&mut backend, json!({"commands":steps})); + assert_eq!(tool["isError"], true); + assert_eq!(tool["structuredContent"]["panel_error"]["rule"], "capability"); + assert_eq!(body["completed"], 0); + assert_eq!(body["applied"], json!([])); + assert_eq!(body["rolled_back"], false); + assert_eq!(backend.calls, vec![("engine.batch".into(), String::new())], "no checkpoint, inspection or single layout call"); + assert_eq!(backend.headless.panels.as_ref().unwrap().service.inspect(), before); + assert_eq!(backend.headless.panels.as_ref().unwrap().catalogue.state(), &catalogue); + assert!(std::sync::Arc::ptr_eq(&document, &backend.headless.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &backend.headless.session.model.state())); + assert_eq!((backend.headless.session.revision, backend.headless.session.undo.len(), backend.headless.session.is_dirty()), session); + } +} + +#[test] +fn oversized_atomic_tool_layout_batch_refuses_before_any_backend_or_checkpoint_call() { + use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue}; + let mut backend = LayoutFallbackBackend::new(); + let before = backend.headless.panels.as_ref().unwrap().service.inspect(); + let catalogue = backend.headless.panels.as_ref().unwrap().catalogue.state().clone(); + let document = backend.headless.session.doc.clone(); + let model = backend.headless.session.model.state(); + let args = json!({"commands":[panel_mcp_steps()[0],{"command":"parameters.change","params":{"name":"broken","expression":"x".repeat(solidcraft_engine::MAX_LINE-32768)}}]}); + assert!(args.to_string().len() < solidcraft_engine::MAX_LINE, "fixture fits the incoming line but exceeds the outgoing margin"); + let (tool, body) = fallback_tool_reply(&mut backend, args); + assert_eq!(tool["isError"], true); + assert_eq!(tool["structuredContent"]["panel_error"]["rule"], "collection_limit"); + assert_eq!(body["completed"], 0); + assert_eq!(body["applied"], json!([])); + assert!(backend.calls.is_empty()); + assert_eq!(backend.headless.panels.as_ref().unwrap().service.inspect(), before); + assert_eq!(backend.headless.panels.as_ref().unwrap().catalogue.state(), &catalogue); + assert!(std::sync::Arc::ptr_eq(&document, &backend.headless.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &backend.headless.session.model.state())); +} + +#[test] +fn sequential_tool_layout_fallback_truthfully_retains_completed_changes_without_checkpointing() { + use solidcraft_engine::panels::{ActionSink, InstanceId, commands::LayoutCatalogue}; + let mut backend = LayoutFallbackBackend::new(); + let (_, body) = fallback_tool_reply( + &mut backend, + json!({"rollback":false,"commands":[ + panel_mcp_steps()[0],{"command":"parameters.change","params":{"name":"broken","expression":"("}}, + ]}), + ); + assert_eq!(body["ok"], false); + assert_eq!(body["completed"], 1); + assert_eq!(body["applied"], json!([0])); + assert_eq!(body["rolled_back"], false); + assert_eq!(body["undone"], 0); + let panels = backend.headless.panels.as_ref().unwrap(); + assert!(panels.service.layout().instance(&InstanceId::new("log").unwrap()).unwrap().requested_open); + assert_eq!(panels.service.inspect().revision, 1); + assert!(panels.catalogue.state().remembered(&panels.service.layout().workspace).is_some()); + assert!(!backend.calls.iter().any(|(_, command)| command == "edit.checkpoint" || command == "edit.restore_checkpoint")); + assert_eq!(backend.calls.iter().filter(|(_, command)| command == "panel.open").count(), 1); +} + +#[test] +fn document_only_atomic_tool_fallback_keeps_existing_checkpoint_rollback_behavior() { + let mut backend = LayoutFallbackBackend::new(); + let (_, body) = fallback_tool_reply( + &mut backend, + json!({"commands":[ + {"command":"parameters.change","params":{"name":"temporary","expression":1}}, + {"command":"parameters.change","params":{"name":"broken","expression":"("}}, + ]}), + ); + assert_eq!(body["rolled_back"], true, "{body}"); + assert_eq!(body["applied"], json!([])); + assert!(backend.headless.session.doc.param("temporary").is_none()); + assert!(backend.calls.iter().any(|(_, command)| command == "edit.checkpoint")); + assert!(backend.calls.iter().any(|(_, command)| command == "edit.restore_checkpoint")); +} + /// Screenshots are drawn on the GPU by the renderer the host installs (`solidcraft-cli mcp`); the /// tests install the same one. `false`, with the reason printed, on a machine without a GPU /// adapter: the screenshots are then left out of the test. @@ -135,7 +444,9 @@ fn handshake_and_tools_list() { "measure", "body_topology", "set_parameter", + "check_parameters", "screenshot", + "compare_picture", "export", "undo", "redo", @@ -325,6 +636,115 @@ fn agent_builds_box_fillet_hole() { let _ = std::fs::remove_dir_all(&dir); } +/// A 60 × 40 × 10 plate with two Ø6 holes at x 15 and 45 and a Ø10 × 8 boss in the middle, all +/// on y 20 and along Z: three cylinders, the halves the kernel splits them into merged. +fn plate_with_holes_and_boss(s: &mut Server) { + let r = tool( + s, + "batch", + json!({"commands": [ + {"command": "sketch.create", "params": {"plane": "XY"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [0, 0], "p1": [60, 40]}}, + {"command": "sketch.finish"}, + {"command": "solid.extrude", "params": {"distance": 10}}, + {"command": "sketch.create", "params": {"plane": "XY"}}, + {"command": "sketch.circle.center", "params": {"center": [15, 20], "radius": 3}}, + {"command": "sketch.circle.center", "params": {"center": [45, 20], "radius": 3}}, + {"command": "sketch.finish"}, + {"command": "solid.extrude", "params": {"distance": 10, "operation": "cut"}}, + {"command": "solid.cylinder", "params": {"radius": 5, "height": 8, "base": [30, 20, 10], "operation": "join"}}, + ]}), + ); + assert_eq!(r["completed"], 10, "{r}"); +} + +/// `body_topology {faces: "cylinders"}` answers where the holes and bosses are in a few lines: +/// one entry per cylinder with its radius, axis line and extent, and no edges (#3380). +#[test] +fn body_topology_lists_merged_cylinders_with_their_extent() { + let mut s = server(); + plate_with_holes_and_boss(&mut s); + let full = tool(&mut s, "body_topology", json!({"body": "Body1"})); + let halves = full["faces"].as_array().unwrap().iter().filter(|f| f["cylinder"].is_object()).count(); + assert!(halves >= 3, "{full}"); + + let topo = tool(&mut s, "body_topology", json!({"body": "Body1", "faces": "cylinders"})); + assert_eq!(topo["body"], "Body1", "{topo}"); + assert!(topo.get("edges").is_none() && topo.get("faces").is_none(), "{topo}"); + let found = topo["cylinders"].as_array().unwrap(); + assert_eq!(found.len(), 3, "{topo}"); + assert_eq!(found.iter().map(|c| c["names"].as_array().unwrap().len()).sum::(), halves, "{topo}"); + assert!(topo.to_string().len() * 4 < full.to_string().len(), "{} vs {} bytes", topo.to_string().len(), full.to_string().len()); + // Each cylinder: (x of its axis, radius, the z its extent spans), its axis along Z. + let mut seen: Vec<(i64, i64, i64, i64)> = found + .iter() + .map(|c| { + let axis: Vec = c["axis"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let origin: Vec = c["origin"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!(axis[2].abs() > 1.0 - 1e-6, "{c}"); + assert!((origin[1] - 20.0).abs() < 1e-3, "{c}"); + let extent: Vec = c["extent"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let mut z: Vec = extent.iter().map(|t| origin[2] + t * axis[2]).collect(); + z.sort_by(|a, b| a.total_cmp(b)); + let mm = |v: f64| (v * 1000.0).round() as i64; + (mm(origin[0]), mm(c["radius"].as_f64().unwrap()), mm(z[0]), mm(z[1])) + }) + .collect(); + seen.sort_unstable(); + assert_eq!(seen, vec![(15000, 3000, 0, 10000), (30000, 5000, 10000, 18000), (45000, 3000, 0, 10000)], "{topo}"); + // Every merged half is a real face name, so the entry picks the face too. + let names: Vec<&str> = found.iter().flat_map(|c| c["names"].as_array().unwrap()).filter_map(Value::as_str).collect(); + let real: Vec<&str> = full["faces"].as_array().unwrap().iter().filter_map(|f| f["name"].as_str()).collect(); + assert!(!names.is_empty() && names.iter().all(|n| real.contains(n)), "{names:?} in {real:?}"); + + // The default is unchanged, and a value outside the enum is refused by argument checking. + let same = tool(&mut s, "body_topology", json!({"body": "Body1", "faces": "all"})); + assert_eq!(same, full); + let r = raw_tool(&mut s, "body_topology", json!({"body": "Body1", "faces": "planes"})); + assert_eq!(r["error"]["code"], -32602, "{r}"); + assert!(r["error"]["message"].as_str().unwrap().contains("cylinders"), "{r}"); +} + +/// `measure {summary: true}` keeps what a stage check needs, as a tool and as a batch step (#3380). +#[test] +fn measure_summary_keeps_only_the_check_fields() { + let mut s = server(); + plate_with_holes_and_boss(&mut s); + let full = tool(&mut s, "measure", json!({})); + let m = tool(&mut s, "measure", json!({"summary": true})); + let keys = |v: &Value| -> Vec { v.as_object().unwrap().keys().cloned().collect() }; + assert_eq!(keys(&m), ["bodies", "body_count", "total"], "{m}"); + assert_eq!(keys(&m["total"]), ["volume_mm3"], "{m}"); + assert_eq!(m["body_count"], 1, "{m}"); + let b = &m["bodies"][0]; + assert_eq!(keys(b), ["bbox", "closed", "faces", "name", "volume_mm3"], "{m}"); + assert_eq!(b["name"], "Body1"); + assert_eq!(b["closed"], true); + assert_eq!(b["faces"], full["bodies"][0]["faces"]); + assert_eq!(b["bbox"], full["bodies"][0]["bbox"]); + let expect = 60.0 * 40.0 * 10.0 - 2.0 * PI * 9.0 * 10.0 + PI * 25.0 * 8.0; + let v = m["total"]["volume_mm3"].as_f64().unwrap(); + assert_eq!(v, full["total"]["volume_mm3"].as_f64().unwrap(), "{m}"); + assert_eq!(b["volume_mm3"].as_f64().unwrap(), full["bodies"][0]["volume_mm3"].as_f64().unwrap(), "{m}"); + assert!(rel(v, expect) < 1e-3, "{v} vs {expect}"); + assert!(m.to_string().len() * 2 < full.to_string().len(), "{} vs {} bytes", m.to_string().len(), full.to_string().len()); + // One body by name, and the default unchanged. + let one = tool(&mut s, "measure", json!({"body": "Body1", "summary": true})); + assert_eq!(one, m); + assert_eq!(tool(&mut s, "measure", json!({"summary": false})), full); + + // As a batch step, the same reply. + let r = tool( + &mut s, + "batch", + json!({"commands": [{"command": "measure", "params": {"summary": true}}, {"command": "measure", "params": {"body": "Body1"}}]}), + ); + assert_eq!(r["completed"], 2, "{r}"); + assert_eq!(r["results"][0], m, "{r}"); + assert_eq!(r["results"][1], full, "{r}"); + assert_eq!(raw_tool(&mut s, "measure", json!({"summary": "yes"}))["error"]["code"], -32602); +} + /// `open` hands `up` and `names` to the STEP import, and the tool's schema refuses other values. #[test] fn open_stands_a_y_up_step_file_up() { @@ -451,6 +871,210 @@ fn set_parameter_takes_value_or_expression() { assert!(rel(volume(&mut s), 6000.0) < 1e-9); } +/// A box whose length is a parameter and a cylinder standing on it at `len / 2`, so a change +/// of `len` moves the cylinder's axis. +fn parametric_box_with_cylinder(s: &mut Server) { + tool(&mut *s, "set_parameter", json!({"name": "len", "value": "40 mm"})); + tool( + &mut *s, + "batch", + json!({"commands": [ + {"command": "solid.box", "params": {"length": "len", "width": 30, "height": 20, "corner": [0, 0, 0]}}, + {"command": "solid.cylinder", "params": {"radius": 5, "height": 10, "base": ["len / 2", 15, 20], "operation": "join"}}, + ]}), + ); +} + +fn box_with_cylinder_volume(len: f64) -> f64 { + len * 30.0 * 20.0 + PI * 25.0 * 10.0 +} + +/// `check_parameters` applies the values with one rebuild, reports the new volume, the +/// features' state and the moved cylinder axis (its two kernel halves as one cylinder), and +/// puts the design back: the parameter, the volume and the undo history are as before. +#[test] +fn check_parameters_tries_values_and_puts_the_design_back() { + let mut s = server(); + parametric_box_with_cylinder(&mut s); + assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4); + let before = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + let r = tool(&mut s, "check_parameters", json!({"set": {"len": "60 mm"}})); + assert_eq!(r["restored"], true, "{r}"); + assert_eq!(r["values"]["len"], 60.0, "{r}"); + assert!(r["recomputed"].as_u64().unwrap() >= 1, "{r}"); + let v = r["measure"]["total"]["volume_mm3"].as_f64().unwrap(); + assert!(rel(v, box_with_cylinder_volume(60.0)) < 5e-4, "{v}"); + assert_eq!(r["measure"]["body_count"], 1, "{r}"); + assert!(r["measure"]["bodies"][0]["faces"].as_u64().unwrap() >= 8, "{r}"); + assert_eq!((&r["errors"], &r["warnings"], &r["parameter_errors"]), (&json!([]), &json!([]), &json!([])), "{r}"); + let cyl = r["cylinders"].as_array().unwrap(); + assert_eq!(cyl.len(), 1, "one cylinder, halves merged: {r}"); + assert_eq!(cyl[0]["body"], "Body1", "{r}"); + assert!((cyl[0]["radius"].as_f64().unwrap() - 5.0).abs() < 1e-6, "{r}"); + let origin: Vec = cyl[0]["origin"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect(); + let axis: Vec = cyl[0]["axis"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect(); + assert!((origin[0] - 30.0).abs() < 1e-6 && (origin[1] - 15.0).abs() < 1e-6 && origin[2].abs() < 1e-6, "axis moved to len / 2 = 30: {r}"); + assert!(axis[0].abs() < 1e-9 && axis[1].abs() < 1e-9 && (axis[2] - 1.0).abs() < 1e-9, "{r}"); + assert!(!cyl[0]["faces"].as_array().unwrap().is_empty(), "{r}"); + // The halves' areas add up to the cylinder's (measured on its mesh). + assert!(rel(cyl[0]["area"].as_f64().unwrap(), 2.0 * PI * 5.0 * 10.0) < 1e-2, "{r}"); + // Back as it was: the value, the volume and the undo history (a checkpoint restores it). + assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4); + let after = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + assert!(after["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["value"] == 40.0 && p["expression"] == "40 mm"), "{after}"); + assert_eq!(after["undo"], before["undo"], "undo depth: {after}"); + assert_eq!(after["redo"], before["redo"], "{after}"); + // Only what was asked for. + let r = tool(&mut s, "check_parameters", json!({"set": {"len": 50}, "report": ["measure"]})); + assert!(rel(r["measure"]["total"]["volume_mm3"].as_f64().unwrap(), box_with_cylinder_volume(50.0)) < 5e-4, "{r}"); + assert!(r.get("cylinders").is_none() && r.get("errors").is_none(), "{r}"); + assert_eq!(r["restored"], true, "{r}"); + assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4); + // A value that breaks a feature is reported, not kept. + let r = tool(&mut s, "check_parameters", json!({"set": {"len": 0}, "report": ["errors"]})); + assert!(!r["errors"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(r["restored"], true, "{r}"); + assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4); + let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + assert!(d["timeline"].as_array().unwrap().iter().all(|f| f["error"].is_null()), "{d}"); +} + +/// An unknown parameter name, a bad expression or a bad report list is an error that leaves the +/// design untouched; `set` that is not an object is refused by argument checking; the tool is +/// annotated as an edit (it changes the design and puts it back) and is not a batch step. +#[test] +fn check_parameters_refuses_bad_input_and_changes_nothing() { + let mut s = server(); + parametric_box_with_cylinder(&mut s); + let before = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + let r = raw_tool(&mut s, "check_parameters", json!({"set": {"nope": 5}})); + assert_eq!(r["result"]["isError"], json!(true), "{r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("`nope`") && text.contains("`len`"), "{text}"); + let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + assert_eq!(d["undo"], before["undo"], "{d}"); + assert!(d["params"].as_array().unwrap().iter().all(|p| p["name"] != "nope"), "{d}"); + for args in [json!({"set": "len"}), json!({"set": [["len", 5]]}), json!({"set": 5}), json!({"set": {"len": 5}, "report": "measure"}), json!({})] { + let r = raw_tool(&mut s, "check_parameters", args.clone()); + assert_eq!(r["error"]["code"], -32602, "{args}: {r}"); + } + for (args, hint) in [ + (json!({"set": {}}), "empty"), + (json!({"set": {"len": true}}), "`set.len`"), + (json!({"set": {"len": null}}), "`set.len`"), + (json!({"set": {"": 5}}), "empty"), + (json!({"set": {"len": 5}, "report": ["volume"]}), "measure, cylinders, errors"), + (json!({"set": {"len": "1 +"}}), "len"), + (json!({"set": {"len": "a = 5"}}), "len"), + ] { + let r = raw_tool(&mut s, "check_parameters", args.clone()); + assert_eq!(r["result"]["isError"], json!(true), "{args}: {r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap_or_default(); + assert!(text.contains(hint), "{args}: {text}"); + } + assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4); + // Untouched: the undo depth and the parameter (the engine's `revision` moves even for a + // refused change, so it is not what tells). + let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + assert_eq!(d["undo"], before["undo"], "{d}"); + assert!(d["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["expression"] == "40 mm"), "{d}"); + // Not a batch step: refused before anything runs. + let r = raw_tool(&mut s, "batch", json!({"commands": [{"command": "check_parameters", "params": {"set": {"len": 5}}}]})); + let body: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); + assert_eq!(body["completed"], 0, "{body}"); + assert!(body["failed"]["error"].as_str().unwrap().contains("check_parameters"), "{body}"); + let def = tool_definitions().into_iter().find(|d| d["name"] == "check_parameters").unwrap(); + assert_eq!(def["inputSchema"]["required"], json!(["set"]), "{def}"); + assert_eq!(def["annotations"]["readOnlyHint"], false, "{def}"); + assert_eq!(def["annotations"]["destructiveHint"], false, "{def}"); +} + +/// A backend answering from a closure: what `check_parameters` sends, and what it does when an +/// app has no `parameters.change {changes}` or cannot restore the checkpoint. +struct Answers { + calls: Vec<(String, Value)>, + answer: Box Result>, +} + +impl crate::backend::Backend for Answers { + fn call(&mut self, method: &str, params: Value) -> Result { + self.calls.push((method.to_string(), params.clone())); + (self.answer)(method, ¶ms) + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "answers".into() + } +} + +/// An app without `parameters.change {changes}` gets one change per name; one that cannot +/// restore the checkpoint makes the call an error that says the values are still in. +#[test] +fn check_parameters_falls_back_per_name_and_says_when_the_restore_failed() { + let app = |restore_ok: bool| Answers { + calls: Vec::new(), + answer: Box::new(move |method, p| { + let command = p["command"].as_str().unwrap_or_default(); + match (method, command) { + ("engine.execute", "parameters.list") => Err("unknown command `parameters.list`".into()), + ("engine.execute", "edit.checkpoint") => Ok(json!({"checkpoint": 3})), + ("engine.execute", "edit.restore_checkpoint") if restore_ok => Ok(json!({"checkpoint": 3, "restored": true})), + ("engine.execute", "edit.restore_checkpoint") => Err("busy: request 9 is still running".into()), + ("engine.execute", "parameters.change") if p["params"].get("changes").is_some() => { + Err("parameters.change: `name` is required".into()) + } + ("engine.execute", "parameters.change") => Ok(json!({"name": p["params"]["name"], "value": 7.0, "recomputed": 1})), + ("engine.execute", "inspect.measure") => Ok(json!({"body_count": 1, "bodies": [], "total": {"volume_mm3": 12.5}})), + ("document.inspect", _) => { + Ok(json!({"timeline": [{"id": 1, "name": "Box", "error": null, "warning": "thin"}], "params": [], "bodies": [{"name": "B"}]})) + } + ("engine.execute", "model.faces") => Ok(json!({"faces": [ + {"index": 0, "name": "side", "area": 1.0, "cylinder": {"origin": [0, 0, 5], "axis": [0, 0, -1], "radius": 2}}, + {"index": 1, "name": "side", "area": 1.0, "cylinder": {"origin": [0, 0, -3], "axis": [0, 0, 1], "radius": 2}}, + {"index": 2, "name": "hole", "area": 1.0, "cylinder": {"origin": [9, 0, 0], "axis": [0, 0, 1], "radius": 2}}, + {"index": 3, "name": "top", "area": 4.0, "plane_normal": [0, 0, 1]}, + ]})), + (m, c) => Err(format!("unknown method `{m}` ({c})")), + } + }), + }; + let mut b = app(true); + let r = crate::tools::call_tool(&mut b, "check_parameters", &json!({"set": {"a": "1 mm", "b": 2}})); + assert_ne!(r["isError"], json!(true), "{r}"); + let body: Value = serde_json::from_str(r["content"][0]["text"].as_str().unwrap()).unwrap(); + assert_eq!(body["restored"], true, "{body}"); + assert_eq!(body["values"], json!({"a": 7.0, "b": 7.0}), "{body}"); + assert_eq!(body["recomputed"], 2, "{body}"); + assert_eq!(body["measure"]["total"]["volume_mm3"], 12.5, "{body}"); + assert_eq!(body["warnings"], json!([{"feature": 1, "name": "Box", "warning": "thin"}]), "{body}"); + assert_eq!(body["errors"], json!([]), "{body}"); + // Two halves on one axis, reported with opposite directions and different axis points, are + // one cylinder; the hole next to it is another. + let cyl = body["cylinders"].as_array().unwrap(); + assert_eq!(cyl.len(), 2, "{body}"); + assert_eq!((&cyl[0]["faces"], &cyl[0]["origin"], &cyl[0]["axis"]), (&json!([0, 1]), &json!([0.0, 0.0, 0.0]), &json!([0.0, 0.0, 1.0])), "{body}"); + assert_eq!((&cyl[1]["faces"], &cyl[1]["origin"], &cyl[1]["name"]), (&json!([2]), &json!([9.0, 0.0, 0.0]), &json!("hole")), "{body}"); + let changes: Vec<&Value> = b.calls.iter().filter(|(_, p)| p["command"] == "parameters.change").map(|(_, p)| &p["params"]).collect(); + assert_eq!(changes.len(), 3, "one combined change, then one per name: {changes:?}"); + assert_eq!(changes[0], &json!({"changes": {"a": "1 mm", "b": 2}}), "{changes:?}"); + assert_eq!((changes[1]["name"].as_str(), changes[2]["name"].as_str()), (Some("a"), Some("b")), "{changes:?}"); + let last = b.calls.last().unwrap(); + assert_eq!(last.1["command"], "edit.restore_checkpoint", "the restore is the last call: {last:?}"); + assert_eq!(last.1["params"]["checkpoint"], 3, "{last:?}"); + + // The restore fails: an error, loudly, with everything that was read. + let mut b = app(false); + let r = crate::tools::call_tool(&mut b, "check_parameters", &json!({"set": {"a": "1 mm"}, "report": ["measure"]})); + assert_eq!(r["isError"], json!(true), "{r}"); + let body: Value = serde_json::from_str(r["content"][0]["text"].as_str().unwrap()).unwrap(); + assert_eq!(body["restored"], false, "{body}"); + assert!(body["restore_error"].as_str().unwrap().contains("still running"), "{body}"); + assert!(body["note"].as_str().unwrap().contains("STILL HOLDS"), "{body}"); + assert_eq!(body["measure"]["total"]["volume_mm3"], 12.5, "{body}"); +} + /// Design properties (#1015) are set through `execute` and come back in `inspect_design`. #[test] fn design_properties_show_in_inspect_design() { @@ -495,6 +1119,13 @@ fn batch_stops_at_first_error_and_rolls_back() { assert_eq!(r["result"]["isError"], true); assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("solid.extrude")); assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 2); + // `names_only` passes through, directly and as a batch step. + let n = tool(&mut s, "measure", json!({"names_only": true})); + assert_eq!(n["body_count"], 2, "{n}"); + assert!(n["bodies"][0]["name"].is_string() && n["bodies"][0].get("volume_mm3").is_none(), "{n}"); + assert_eq!(tool(&mut s, "measure", json!({"names_only": true, "summary": true})), n, "summary has nothing to narrow in a names list"); + let r = tool(&mut s, "batch", json!({"commands": [{"command": "measure", "params": {"names_only": true, "summary": true}}]})); + assert!(r.to_string().contains("\"definition\""), "{r}"); } /// #5853: a misspelled command, however late in the batch, refuses the batch before its first @@ -514,6 +1145,23 @@ fn batch_refuses_an_unknown_command_before_the_first_step() { assert_eq!(tool(&mut s, "inspect_design", json!({"measure": false}))["undo"], 0); } +/// A step with its parameters under another key (`args`) refuses the batch before its first +/// step, naming the key, instead of running the command without them. +#[test] +fn batch_refuses_a_step_with_an_unknown_key() { + let mut s = server(); + let steps = json!([ + {"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}, + {"command": "sketch.create", "args": {"plane": "XY"}}, + ]); + let r = raw_tool(&mut s, "batch", json!({"commands": steps})); + 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["completed"].clone(), body["failed"]["index"].clone()), (json!(0), json!(1)), "{body}"); + assert!(body["failed"]["error"].as_str().is_some_and(|e| e.contains("unknown key `args`") && e.contains("`params`")), "{body}"); + assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 0, "no step ran"); +} + /// #5822: with `coalesce_parameters` a batch of parameter edits, one per step, rebuilds the /// design once for the run, and every step still has its own result. A run with an edit /// `changes` can't make (a new parameter) goes step by step, and a refused edit is still named @@ -640,6 +1288,216 @@ fn a_failed_batch_with_file_new_restores_the_original_design() { assert_eq!(d["name"], name, "{d}"); } +/// `expect` on a batch: the volume, body count and bounding box the agent computed beforehand +/// are measured and compared by the server once the batch went through, so no separate +/// `measure` call and no comparison by hand follow every stage. +#[test] +fn a_batch_with_a_matching_expect_reports_the_expectation_met() { + let mut s = server(); + let r = tool( + &mut s, + "batch", + json!({ + "commands": [ + {"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0]}}, + {"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": [15, 10, 5], "operation": "cut"}}, + ], + "expect": {"volume_mm3": 23000, "bodies": 1, "bbox": {"min": [0, 0, 0], "max": [40, 30, 20]}}, + }), + ); + assert_eq!(r["completed"], 2, "{r}"); + let e = &r["expectation"]; + assert_eq!(e["ok"], true, "{r}"); + assert_eq!(e["mismatch"], json!([]), "{r}"); + assert_eq!(e["measured"]["bodies"], 1, "{r}"); + assert!(rel(e["measured"]["volume_mm3"].as_f64().unwrap(), 23000.0) < 1e-6, "{r}"); + assert!(rel(e["measured"]["bbox"]["max"][0].as_f64().unwrap(), 40.0) < 1e-6, "{r}"); + assert_eq!( + e["expected"], + json!({"volume_mm3": 23000.0, "tol": 0.002, "bodies": 1, "bbox": {"min": [0.0, 0.0, 0.0], "max": [40.0, 30.0, 20.0]}}), + "{r}" + ); + // Without `expect` the reply is as before. + tool(&mut s, "new_design", json!({})); + let box40 = json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0]}}); + let r = tool(&mut s, "batch", json!({"commands": [box40]})); + assert!(r.get("expectation").is_none(), "{r}"); + // `expect` is the tool's argument, not a step key: a step carrying one is refused, as any step + // with a stray key is, saying where `expect` goes, instead of running with nothing checked. + let sphere = json!({"command": "solid.sphere", "params": {"radius": 5, "center": [100, 0, 0]}, "expect": {"bodies": 7}}); + let r = raw_tool(&mut s, "batch", json!({"commands": [sphere]})); + 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["completed"].clone(), body["failed"]["index"].clone()), (json!(0), json!(0)), "{body}"); + assert!(body["failed"]["error"].as_str().is_some_and(|e| e.contains("`expect` is the batch's argument")), "{body}"); + assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 1, "the sphere did not run"); +} + +/// A volume the design does not match flags the reply as an error that names the mismatch +/// first, and keeps the design as built: the agent decides what to do with it. +#[test] +fn a_batch_with_a_wrong_expected_volume_is_flagged_and_the_design_kept() { + let mut s = server(); + let box40 = json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0]}}); + let r = raw_tool(&mut s, "batch", json!({"commands": [box40], "expect": {"volume_mm3": 20000}})); + assert_eq!(r["result"]["isError"], true, "{r}"); + let content = r["result"]["content"].as_array().unwrap(); + let first = content[0]["text"].as_str().unwrap(); + assert!(first.starts_with("expectation not met: volume: measured 24000, expected 20000 (+20.00 %)."), "{first}"); + assert!(first.contains("kept as built"), "{first}"); + let body: Value = serde_json::from_str(content[1]["text"].as_str().unwrap()).unwrap(); + assert_eq!(body["ok"], true, "the batch itself went through: {body}"); + assert_eq!(body["completed"], 1, "{body}"); + assert_eq!(body["results"][0]["created_bodies"], json!(["Body1"]), "{body}"); + assert_eq!(body["expectation"]["ok"], false, "{body}"); + assert_eq!(body["expectation"]["mismatch"], json!(["volume: measured 24000, expected 20000 (+20.00 %)"]), "{body}"); + assert_eq!(body["expectation"]["expected"], json!({"volume_mm3": 20000.0, "tol": 0.002}), "{body}"); + // The design is kept as built, undoably. + assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 1); + assert!(rel(volume(&mut s), 24000.0) < 1e-9); + assert_eq!(tool(&mut s, "inspect_design", json!({"measure": false}))["undo"], 1); + // `tol` is relative to the expected volume: 0.5 % off passes at 1 %, not at the default 0.2 %. + let cube = json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": [100, 0, 0]}}); + let r = tool(&mut s, "batch", json!({"commands": [cube], "expect": {"volume_mm3": 25000.0 * 1.005, "tol": 0.01}})); + assert_eq!(r["expectation"]["ok"], true, "{r}"); + let r = raw_tool(&mut s, "batch", json!({"commands": [{"command": "undo"}], "expect": {"volume_mm3": 24000.0 * 1.005}})); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("volume: measured 24000, expected 24120 (-0.50 %)"), "{r}"); +} + +/// A wrong body count and a wrong bounding box are each named, with the coordinates that are +/// off; a bounding box within 0.05 mm matches. +#[test] +fn expect_names_body_count_and_bounding_box_mismatches() { + let mut s = server(); + let box40 = json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0]}}); + let cube = json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": [100, -5, -5]}}); + let r = raw_tool( + &mut s, + "batch", + json!({"commands": [box40, cube], "expect": {"volume_mm3": 25000, "bodies": 1, "bbox": {"min": [0, 0, 0], "max": [40, 30, 20]}}}), + ); + assert_eq!(r["result"]["isError"], true, "{r}"); + let body: Value = serde_json::from_str(r["result"]["content"][1]["text"].as_str().unwrap()).unwrap(); + let mismatch = body["expectation"]["mismatch"].as_array().unwrap(); + assert_eq!(mismatch.len(), 2, "the volume matches and is not named: {body}"); + assert_eq!(mismatch[0], "bodies: measured 2, expected 1", "{body}"); + let bbox = mismatch[1].as_str().unwrap(); + assert!(bbox.starts_with("bbox: measured min [0, -5, -5] max [110, 30, 20], expected min [0, 0, 0] max [40, 30, 20] ("), "{bbox}"); + assert!(bbox.contains("min y off by -5 mm") && bbox.contains("min z off by -5 mm") && bbox.contains("max x off by 70 mm"), "{bbox}"); + assert!(!bbox.contains("max y") && !bbox.contains("max z") && !bbox.contains("min x"), "{bbox}"); + assert_eq!(body["expectation"]["measured"]["bodies"], 2, "{body}"); + assert!(rel(body["expectation"]["measured"]["bbox"]["max"][0].as_f64().unwrap(), 110.0) < 1e-6, "{body}"); + assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 2, "the design is kept"); + // Within 0.05 mm the box matches; past it the coordinate is named. + tool(&mut s, "undo", json!({})); + let r = tool(&mut s, "batch", json!({"commands": [{"command": "redo"}], "expect": {"bbox": {"min": [0, -5, -5.04], "max": [110.04, 30, 20]}}})); + assert_eq!(r["expectation"]["ok"], true, "{r}"); + let r = raw_tool(&mut s, "batch", json!({"commands": [{"command": "undo"}], "expect": {"bbox": {"min": [0, 0, 0], "max": [40.1, 30, 20]}}})); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("(max x off by -0.1 mm)"), "{r}"); + // No body at all: the box can't be measured, and the count says so. + tool(&mut s, "new_design", json!({})); + let r = raw_tool( + &mut s, + "batch", + json!({"commands": [{"command": "parameters.add", "params": {"name": "w", "expression": "1 mm"}}], "expect": {"bodies": 1, "bbox": {"min": [0, 0, 0], "max": [1, 1, 1]}}}), + ); + assert_eq!(r["result"]["isError"], true, "{r}"); + let body: Value = serde_json::from_str(r["result"]["content"][1]["text"].as_str().unwrap()).unwrap(); + assert_eq!( + body["expectation"]["mismatch"], + json!(["bodies: measured 0, expected 1", "bbox: no body to measure, expected min [0, 0, 0] max [1, 1, 1]"]), + "{body}" + ); + assert!(body["expectation"]["measured"]["bbox"].is_null(), "{body}"); +} + +/// An `expect` that is not what the schema says is refused before anything runs: a typo never +/// builds a design that then goes unchecked. +#[test] +fn a_malformed_expect_is_refused_before_anything_runs() { + let mut s = server(); + let step = json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}); + for name in ["execute", "batch"] { + let args = |expect: Value| { + let mut a = if name == "batch" { json!({"commands": [step]}) } else { step.clone() }; + a["expect"] = expect; + a + }; + // Not an object: the argument check, as for every tool argument. + for bad in [json!(5), json!("24000"), json!([24000]), json!(true)] { + let r = raw_tool(&mut s, name, args(bad.clone())); + assert_eq!(r["error"]["code"], -32602, "{name} {bad}: {r}"); + assert!(r["error"]["message"].as_str().unwrap().contains("`expect` must be of type"), "{r}"); + } + // An object the tool can't use: a tool error naming the key, and nothing was run. + for (bad, says) in [ + (json!({}), "nothing to check"), + (json!({"volume": 24000}), "unknown key `volume`"), + (json!({"volume_mm3": "24000"}), "`volume_mm3` must be a number"), + (json!({"volume_mm3": -1}), "`volume_mm3` must not be negative"), + (json!({"volume_mm3": 1, "tol": -0.1}), "`tol` must not be negative"), + (json!({"bodies": 1.5}), "`bodies` must be a whole number"), + (json!({"bodies": -1}), "`bodies` must be a whole number"), + (json!({"bbox": [0, 0, 0]}), "`bbox` must be"), + (json!({"bbox": {"min": [0, 0], "max": [1, 1, 1]}}), "`bbox.min` must be [x, y, z]"), + (json!({"bbox": {"min": [0, 0, 0], "max": [1, "1", 1]}}), "`bbox.max` must be [x, y, z]"), + (json!({"bbox": {"min": [2, 0, 0], "max": [1, 1, 1]}}), "`bbox.min` must not exceed"), + (json!({"bbox": {"min": [0, 0, 0], "max": [1, 1, 1], "mid": [0, 0, 0]}}), "unknown key `bbox.mid`"), + ] { + let r = raw_tool(&mut s, name, args(bad.clone())); + assert_eq!(r["result"]["isError"], true, "{name} {bad}: {r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.starts_with("expect: ") && text.contains(says), "{name} {bad}: {text}"); + } + assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 0, "{name}: nothing ran"); + assert_eq!(tool(&mut s, "inspect_design", json!({"measure": false}))["undo"], 0, "{name}: nothing ran"); + } +} + +/// `execute` takes `expect` as `batch` does: met, the reply carries the expectation; not met, +/// the reply is an error naming it, and the command's result stays, as the design does. A +/// command that fails is the error it always was, with nothing measured. +#[test] +fn execute_checks_its_expect_like_batch() { + let mut s = server(); + let r = tool( + &mut s, + "execute", + json!({ + "command": "solid.box", "params": {"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0]}, + "expect": {"volume_mm3": 24000, "bodies": 1, "bbox": {"min": [0, 0, 0], "max": [40, 30, 20]}}, + }), + ); + assert_eq!(r["created_bodies"], json!(["Body1"]), "{r}"); + assert_eq!(r["expectation"]["ok"], true, "{r}"); + assert_eq!(r["expectation"]["mismatch"], json!([]), "{r}"); + let r = raw_tool( + &mut s, + "execute", + json!({ + "command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": [15, 10, 5], "operation": "cut"}, + "verbose": false, + "expect": {"volume_mm3": 24000, "bodies": 2}, + }), + ); + assert_eq!(r["result"]["isError"], true, "{r}"); + let content = r["result"]["content"].as_array().unwrap(); + let first = content[0]["text"].as_str().unwrap(); + assert!(first.starts_with("expectation not met: volume: measured 23000, expected 24000 (-4.17 %); bodies: measured 1, expected 2."), "{first}"); + let body: Value = serde_json::from_str(content[1]["text"].as_str().unwrap()).unwrap(); + assert_eq!(body["changed_bodies"], json!(["Body1"]), "the command's result stays: {body}"); + assert!(body.get("bodies").is_none(), "compact, as asked: {body}"); + assert_eq!(body["expectation"]["measured"]["bodies"], 1, "{body}"); + assert!(rel(volume(&mut s), 23000.0) < 1e-9, "the cut is kept"); + let r = raw_tool(&mut s, "execute", json!({"command": "solid.extrude", "params": {"distance": 10}, "expect": {"bodies": 1}})); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert_eq!(r["result"]["content"].as_array().map(Vec::len), Some(1), "{r}"); + assert!(!r["result"]["content"][0]["text"].as_str().unwrap().contains("expectation"), "{r}"); + assert!(rel(volume(&mut s), 23000.0) < 1e-9); +} + #[test] fn helper_sketches_can_be_hidden() { let mut s = server(); @@ -723,6 +1581,77 @@ fn tool_unknown_command_errors_explain_packed_params() { assert!(body["failed"]["error"].as_str().unwrap().contains("command ids have no parameters; pass them in `params`"), "{body}"); } +/// #10678: through direct `execute`, an unknown command id that is exactly a registered +/// MCP tool name gets the namespace hint instead of unrelated closest-command suggestions. +#[test] +fn tool_name_command_ids_get_namespace_hint_via_execute() { + let mut s = server(); + for id in ["execute", "list_commands", "describe_command", "screenshot"] { + let r = raw_tool(&mut s, "execute", json!({"command": id, "params": {}})); + assert_eq!(r["result"]["isError"], true, "{r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.starts_with(&format!("unknown command `{id}`")), "{text}"); + assert!(text.contains(&format!("`{id}` is an MCP tool, not an engine command id")), "{text}"); + assert!(text.contains("tools/list") && text.contains("list_commands"), "{text}"); + assert!(!text.contains("closest:"), "{text}"); + } +} + +/// #10678: the direct `describe_command` hint inspects the requested `id`, not the outer +/// `engine.describe` command `exec` sees. +#[test] +fn tool_name_command_ids_get_namespace_hint_via_describe_command() { + let mut s = server(); + for id in ["execute", "list_commands"] { + let r = raw_tool(&mut s, "describe_command", json!({"id": id})); + assert_eq!(r["result"]["isError"], true, "{r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.starts_with(&format!("unknown command `{id}`")), "{text}"); + assert!(text.contains(&format!("`{id}` is an MCP tool, not an engine command id")), "{text}"); + assert!(!text.contains("engine.describe"), "{text}"); + } + // Control: a valid engine command id still describes itself. + let r = raw_tool(&mut s, "describe_command", json!({"id": "solid.box"})); + assert_ne!(r["result"]["isError"], true, "{r}"); +} + +/// #10678: an engine-id typo keeps its closest-command suggestions; the tool-name hint is +/// only for exact registered tool names. +#[test] +fn engine_command_id_typo_still_gets_closest_suggestions() { + let mut s = server(); + let r = raw_tool(&mut s, "execute", json!({"command": "solid.bxo"})); + assert_eq!(r["result"]["isError"], true, "{r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("closest: `solid.box`"), "{text}"); + assert!(!text.contains("MCP tool"), "{text}"); +} + +/// #10678: a genuinely unknown id keeps the ordinary unknown-command error on both paths. +#[test] +fn genuinely_unknown_command_id_keeps_the_ordinary_error() { + let mut s = server(); + for (name, args) in [("execute", json!({"command": "madeup.thing"})), ("describe_command", json!({"id": "madeup.thing"}))] { + let r = raw_tool(&mut s, name, args); + assert_eq!(r["result"]["isError"], true, "{r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("unknown command `madeup.thing`"), "{text}"); + assert!(!text.contains("MCP tool"), "{text}"); + } +} + +/// #10678: a valid engine command id that overlaps a tool name resolves as a command — +/// the engine accepts it before any tool-name hint could apply. +#[test] +fn valid_engine_command_id_overlapping_a_tool_name_resolves_as_command() { + let mut b = Recorder { calls: Vec::new(), batch: Ok(json!({})) }; + let r = crate::tools::call_tool(&mut b, "execute", &json!({"command": "measure"})); + assert_ne!(r["isError"], json!(true), "{r}"); + assert!(r["content"][0]["text"].as_str().unwrap().contains("measure"), "{r}"); + let r = crate::tools::call_tool(&mut b, "describe_command", &json!({"id": "measure"})); + assert_ne!(r["isError"], json!(true), "{r}"); +} + fn hostile_values() -> Vec { vec![ Value::Null, @@ -812,6 +1741,75 @@ fn list_commands_filter_by_a_command_id_matches_ids() { assert!(ids.iter().all(|id| id.contains("sketch.delete")), "{} commands matched: {ids:?}", ids.len()); } +/// #11726: `list_commands` narrows by id prefix and by panel, shrinks each entry to id and label +/// or to chosen keys, and pages; with none of these the reply is the whole catalog as before. A +/// batch step narrows the same way, and a bad argument is a tool error that names it. +#[test] +fn list_commands_narrows_by_prefix_panel_fields_and_page() { + let mut s = server(); + let all = tool(&mut s, "list_commands", json!({})); + let all = all.as_array().unwrap(); + assert!(all.len() > 100 && all[0].get("params").is_some(), "the whole catalog, every key"); + let ids = |v: &Value| v.as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap().to_string()).collect::>(); + let sketch = tool(&mut s, "list_commands", json!({"prefix": "SKETCH."})); + assert!(!ids(&sketch).is_empty() && ids(&sketch).iter().all(|id| id.starts_with("sketch.")), "{:?}", ids(&sketch)); + let want = all.iter().filter(|c| c["id"].as_str().unwrap().starts_with("sketch.")).count(); + assert_eq!(ids(&sketch).len(), want, "every sketch command, not only those on a toolbar"); + let modify = tool(&mut s, "list_commands", json!({"panel": "modify"})); + assert!(!ids(&modify).is_empty(), "{modify}"); + assert!( + modify + .as_array() + .unwrap() + .iter() + .all(|c| c["panel"].as_str().unwrap().eq_ignore_ascii_case("modify") || c["tab"].as_str().unwrap().eq_ignore_ascii_case("modify")), + "only the whole panel name matches" + ); + let compact = tool(&mut s, "list_commands", json!({"compact": true})); + assert_eq!(ids(&compact), ids(&Value::Array(all.clone())), "compact keeps every command"); + assert!(compact.as_array().unwrap().iter().all(|c| c.as_object().unwrap().keys().eq(["id", "label"].iter())), "{}", compact[0]); + assert!(compact.to_string().len() * 5 < Value::Array(all.clone()).to_string().len(), "compact is far smaller"); + let picked = tool(&mut s, "list_commands", json!({"prefix": "solid.fillet", "fields": ["id", "enabled"], "compact": true})); + assert_eq!(picked[0], json!({"id": "solid.fillet", "enabled": picked[0]["enabled"]}), "fields wins over compact"); + // Pages: together they are the whole match list, in order. + let mut paged = Vec::new(); + let mut offset = json!(0); + while let Some(at) = offset.as_u64() { + let page = tool(&mut s, "list_commands", json!({"prefix": "sketch.", "compact": true, "limit": 7, "offset": at})); + assert_eq!(page["total"], want, "{page}"); + assert_eq!(page["offset"], at); + assert!(page["commands"].as_array().unwrap().len() <= 7); + paged.extend(ids(&page["commands"])); + offset = page["next_offset"].clone(); + } + assert_eq!(paged, ids(&sketch)); + let past = tool(&mut s, "list_commands", json!({"limit": 5, "offset": 1_000_000})); + assert_eq!((past["commands"].as_array().unwrap().len(), &past["next_offset"]), (0, &Value::Null), "{past}"); + // A batch step narrows as the tool does. + let r = tool(&mut s, "batch", json!({"commands": [{"command": "list_commands", "params": {"prefix": "sketch.", "compact": true, "limit": 3}}]})); + let step = r["results"][0].clone(); + assert_eq!(step["commands"].as_array().map(Vec::len), Some(3), "{r}"); + assert_eq!(step["total"], want, "{r}"); + for bad in [ + json!({"limit": 0}), + json!({"limit": -1}), + json!({"offset": "x"}), + json!({"fields": ["nope"]}), + json!({"fields": "id"}), + json!({"compact": 1}), + json!({"prefix": 3}), + ] { + // The argument schema refuses a wrong type before the tool runs; the tool refuses the rest. + let r = raw_tool(&mut s, "list_commands", bad.clone()); + let text = r["result"]["content"][0]["text"].as_str().or(r["error"]["message"].as_str()).unwrap_or_default().to_string(); + assert!(r["result"]["isError"] == json!(true) || r["error"]["code"].is_i64(), "{bad}: {r}"); + let key = bad.as_object().unwrap().keys().next().unwrap().clone(); + assert!(text.contains(&format!("`{key}`")), "{bad}: the error names the argument: {text}"); + let r = raw_tool(&mut s, "batch", json!({"commands": [{"command": "list_commands", "params": bad.clone()}]})); + assert!(r["result"]["isError"] == json!(true) || r.to_string().contains(&format!("`{key}`")), "{bad} as a step: {r}"); + } +} + /// Compatibility shims (docs/compatibility.md): a design saved before the rename (legacy /// extension and format tag) opens through MCP, and the legacy resource URIs still read. #[test] @@ -850,6 +1848,46 @@ fn legacy_design_files_and_resource_uris() { let _ = std::fs::remove_dir_all(&dir); } +/// `compare_picture` (#1486): the overlay comes back as an image block and the numbers as text. +#[test] +fn compare_picture_returns_the_overlay_as_an_image() { + use image::ImageEncoder as _; + use std::io::Cursor; + // A scoped server, like `solidcraft-cli mcp`: the reference must be inside the folders. + let base = solidcraft_engine::io::vfs::temp_dir().join(format!("solidcraft-mcp-compare-{}", std::process::id())); + let recovery = base.join("recovery"); + std::fs::create_dir_all(&recovery).unwrap(); + let scope = crate::agent_scope_with(Some(recovery.clone()), []); + let mut s = Server::new(Box::new(Headless::default())).with_path_scope(Some(scope)); + tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 20, "width": 10, "height": 30}})); + // A white rectangle on grey with the box's front-view proportions (20 x 30 mm). + let (w, h) = (200u32, 300u32); + let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 200, 200, 255])); + for y in 20..280 { + for x in 20..180 { + img.put_pixel(x, y, image::Rgba([255, 255, 255, 255])); + } + } + let mut png = Cursor::new(Vec::new()); + image::codecs::png::PngEncoder::new(&mut png).write_image(img.as_raw(), w, h, image::ExtendedColorType::Rgba8).unwrap(); + let path = recovery.join("target.png"); + std::fs::write(&path, png.into_inner()).unwrap(); + + let r = raw_tool(&mut s, "compare_picture", json!({"reference": path.to_string_lossy(), "view": "front"})); + assert_ne!(r["result"]["isError"], json!(true), "{r}"); + let content = r["result"]["content"].as_array().unwrap().clone(); + assert_eq!(content[0]["type"], "image", "{content:?}"); + assert_eq!(content[0]["mimeType"], "image/png"); + assert!(content[0]["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "not a PNG"); + let info: Value = serde_json::from_str(content[1]["text"].as_str().unwrap()).unwrap(); + assert!(info["overlap"].as_f64().unwrap() > 0.9, "{info}"); + assert!(info.get("overlay_png").is_none(), "the base64 blob belongs in the image block only"); + // A reference outside the server's folders is refused through the existing path rules. + let outside = raw_tool(&mut s, "compare_picture", json!({"reference": "/etc/hostname"})); + assert_eq!(outside["result"]["isError"], json!(true), "{outside}"); + let _ = std::fs::remove_dir_all(&base); +} + /// The default folders (#205): the recovery folder works out of the box, `screenshot` without a /// `path` uses the server's own scratch folder, and the open design's folder counts while the /// design is open there, without its hidden files. The working folder doesn't count at all. @@ -1094,6 +2132,39 @@ fn a_bridged_request_carries_the_agents_folders() { echo.join().unwrap(); } +/// A server started before its first tool call keeps no connection waiting (the app closes one +/// that shows no token in time), and a call on a connection the app has closed meanwhile goes out +/// on a new one without an error. +#[test] +fn a_bridge_holds_no_idle_connection_and_survives_one_closed_before_its_first_call() { + use std::io::{BufRead, Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let app = std::thread::spawn(move || { + let (mut probe, _) = listener.accept().unwrap(); + probe.set_read_timeout(Some(std::time::Duration::from_secs(10))).unwrap(); + assert_eq!(probe.read(&mut [0u8; 1]).unwrap(), 0, "the probe closes at once and sends nothing"); + // The connection the second bridge makes first: closed unanswered, as a timed-out one is. + drop(listener.accept().unwrap()); + for _ in 0..2 { + let (stream, _) = listener.accept().unwrap(); + let mut line = String::new(); + std::io::BufReader::new(stream.try_clone().unwrap()).read_line(&mut line).unwrap(); + let req: Value = serde_json::from_str(&line).unwrap(); + writeln!(&stream, "{}", json!({"id": req["id"], "ok": true, "result": {"method": req["method"]}})).unwrap(); + } + }); + let token = "0123456789abcdef0123456789abcdef"; + let mut early = crate::Remote::new(&addr, Some(token)); + early.try_connect().unwrap(); + let mut idle = crate::Remote::connect_with_token(&addr, Some(token)).unwrap(); + let got = crate::Backend::call(&mut early, "ui.view", json!({})).unwrap(); + assert_eq!(got["method"], "ui.view", "{got}"); + let got = crate::Backend::call(&mut idle, "ui.view", json!({})).unwrap(); + assert_eq!(got["method"], "ui.view", "{got}"); + app.join().unwrap(); +} + /// #7181, bridged: once the agent has saved a design through the app, that file's folder goes /// with every later request as `design_folders`, so the app counts it after the design moves on. /// Not before the save succeeded, not for one the app refused, not for a relative path (the app @@ -1508,6 +2579,100 @@ fn skill_reference_example_builds_as_documented() { holes_at(&mut s, 52.0); } +/// The server instructions' recipe (primitives with expression fields, fillet before the shell, +/// inside features after it, a blind hole with its depth, picks by world point, parameters +/// checked in one coalesced batch and set back) builds the part it describes, with the volume +/// worked out by hand, and follows its parameters, so the instructions and the engine stay in +/// step whatever the kernel does. +#[test] +fn instructions_recipe_builds_a_parametric_shelled_box() { + // A box L × W × H with its four vertical edges rounded r, shelled from the top with wall t + // (the inner corners are r - t), a boss of radius R from the floor to the rim, and a blind + // hole Ø d, depth hd, down the boss. + let (fr, t, big_r, d, hd) = (5.0, 2.0, 6.0, 5.0, 10.0); + let expected = |l: f64, w: f64, h: f64| { + let corner = 4.0 * (1.0 - PI / 4.0); + let outer = l * w * h - corner * fr * fr * h; + let cavity = (l - 2.0 * t) * (w - 2.0 * t) * (h - t) - corner * (fr - t) * (fr - t) * (h - t); + let boss = PI * big_r * big_r * (h - t); + let hole = PI * (d / 2.0) * (d / 2.0) * hd; + outer - cavity + boss - hole + }; + let mut s = server(); + let r = tool( + &mut s, + "batch", + json!({"verbose": false, "commands": [ + {"command": "parameters.add", "params": {"name": "L", "expression": "60 mm"}}, + {"command": "parameters.add", "params": {"name": "W", "expression": "40 mm"}}, + {"command": "parameters.add", "params": {"name": "H", "expression": "30 mm"}}, + {"command": "parameters.add", "params": {"name": "wall", "expression": "2 mm"}}, + {"command": "solid.box", "params": {"length": "L", "width": "W", "height": "H", "corner": [0, 0, 0], "name": "Block", "body_name": "Case"}}, + {"command": "solid.fillet", "params": {"edges": [[0, 0, 15], [60, 0, 15], [60, 40, 15], [0, 40, 15]], "radius": fr, "name": "Corners"}}, + {"command": "solid.shell", "params": {"faces": [[30, 20, 30]], "thickness": "wall", "name": "Hollow"}}, + {"command": "solid.cylinder", "params": {"radius": big_r, "height": "H - wall", "base": ["L/2", "W/2", "wall"], "operation": "join", "name": "Boss"}}, + {"command": "solid.hole", "params": {"position": ["L/2", "W/2", "H"], "diameter": d, "depth": hd, "name": "Pilot"}}, + {"command": "measure", "params": {}}, + ]}), + ); + let results = r["results"].as_array().unwrap(); + assert_eq!(results.len(), 10, "{r}"); + let m = &results[9]; + assert_eq!(m["bodies"].as_array().map(Vec::len), Some(1), "{m}"); + assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap(), expected(60.0, 40.0, 30.0)) < 1e-3, "{m}"); + let no_errors = |s: &mut Server| { + let d = tool(s, "inspect_design", json!({"measure": false, "sketches": false})); + let failed: Vec<&Value> = d["timeline"].as_array().unwrap().iter().filter(|f| !f["error"].is_null()).collect(); + assert!(failed.is_empty(), "{failed:?}"); + assert_eq!(d["timeline"].as_array().map(Vec::len), Some(5), "{d}"); + }; + no_errors(&mut s); + // The boss and the pilot hole are where the expressions put them. + let axes = |s: &mut Server, x: f64, y: f64| { + let topo = tool(s, "body_topology", json!({"body": "Case"})); + let cylinders: Vec<(f64, f64, f64)> = topo["faces"] + .as_array() + .unwrap() + .iter() + .filter_map(|f| f.get("cylinder")) + .map(|c| (c["origin"][0].as_f64().unwrap(), c["origin"][1].as_f64().unwrap(), c["radius"].as_f64().unwrap())) + .collect(); + for radius in [big_r, d / 2.0] { + assert!( + cylinders.iter().any(|&(cx, cy, cr)| (cx - x).abs() < 1e-6 && (cy - y).abs() < 1e-6 && (cr - radius).abs() < 1e-6), + "no cylinder r {radius} on ({x}, {y}): {cylinders:?}" + ); + } + }; + axes(&mut s, 30.0, 20.0); + // Two parameters changed in one coalesced batch (one rebuild per run), measured, set back. + let r = tool( + &mut s, + "batch", + json!({"verbose": false, "coalesce_parameters": true, "commands": [ + {"command": "parameters.change", "params": {"name": "L", "expression": "80 mm"}}, + {"command": "parameters.change", "params": {"name": "W", "expression": "50 mm"}}, + {"command": "measure", "params": {}}, + {"command": "parameters.change", "params": {"name": "L", "expression": "60 mm"}}, + {"command": "parameters.change", "params": {"name": "W", "expression": "40 mm"}}, + ]}), + ); + let results = r["results"].as_array().unwrap(); + assert_eq!(results.len(), 5, "{r}"); + assert_eq!(results[0]["coalesced"], 2, "{r}"); + assert_eq!(results[0]["errors"].as_array().map(Vec::len), Some(0), "{r}"); + let m = &results[2]; + assert_eq!(m["bodies"].as_array().map(Vec::len), Some(1), "{m}"); + assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap(), expected(80.0, 50.0, 30.0)) < 1e-3, "{m}"); + assert_eq!(results[3]["coalesced"], 2, "{r}"); + assert_eq!(results[4]["errors"].as_array().map(Vec::len), Some(0), "{r}"); + let m = tool(&mut s, "measure", json!({})); + assert_eq!(m["bodies"].as_array().map(Vec::len), Some(1), "{m}"); + assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap(), expected(60.0, 40.0, 30.0)) < 1e-3, "{m}"); + no_errors(&mut s); + axes(&mut s, 30.0, 20.0); +} + /// The skill reference's sketch-plane table: where sketch (10, 20) lands and which way +distance goes. #[test] fn sketch_plane_axes_match_the_skill_reference() { @@ -1633,18 +2798,29 @@ fn skills_name_only_real_tools_and_commands() { assert!(checked > 30, "only {checked} tool and command names found in the skills"); } -/// Every tool the server instructions name (a bare `snake_case` word in backticks) is a real tool. +/// Every tool and command the server instructions name is real: a backticked `snake_case` word +/// (bare or as a call, `measure {}`) is a tool, a dotted id (`solid.box`) a command in the +/// engine's registry. A rename or removal can't leave the instructions sending agents to names +/// the server no longer has. #[test] fn instructions_name_only_real_tools() { let mut s = server(); let init = call(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION, "capabilities": {}})); let text = init["result"]["instructions"].as_str().unwrap().to_owned(); let tools: Vec = tool_definitions().iter().map(|t| t["name"].as_str().unwrap().to_owned()).collect(); + let commands: Vec = + tool(&mut s, "list_commands", json!({})).as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).map(str::to_owned).collect(); + let ident = |w: &str| !w.is_empty() && w.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '.'); + // A span is `name`, `name {}` or `name {"json":…}`; `edges: [[x,y,z]]`, `verbose: false` and + // `"L/2 - 10"` are fields and values, not calls. let named: Vec<&str> = - text.split('`').skip(1).step_by(2).filter(|w| !w.is_empty() && w.chars().all(|c| c.is_ascii_lowercase() || c == '_')).collect(); - assert!(named.contains(&"body_topology"), "{named:?}"); + text.split('`').skip(1).step_by(2).map(|span| span.split_once(" {").map_or(span, |(head, _)| head)).filter(|w| ident(w)).collect(); + for must in ["skill_reference", "batch", "measure", "body_topology", "pending", "solid.box", "parameters.change", "edit.restore_checkpoint"] { + assert!(named.contains(&must), "{named:?}"); + } for name in named { - assert!(tools.iter().any(|t| t == name), "the instructions name `{name}`, which is not a tool"); + let known = if name.contains('.') { commands.iter().any(|c| c == name) } else { tools.iter().any(|t| t == name) }; + assert!(known, "the instructions name `{name}`, which is neither a tool nor a command"); } } @@ -1726,6 +2902,28 @@ fn batch_reports_a_failed_engine_batch_like_before() { ); } +/// Bridged, `expect` measures the app's design with one `inspect.measure` after the one +/// `engine.batch` request, and a batch that failed is not measured. +#[test] +fn a_bridged_batch_measures_its_expect_after_the_one_batch_call() { + let steps = json!([{"command": "a.one"}]); + let reply = json!({"completed": 1, "results": [{"x": 1}], "undone": 0}); + let mut b = Recorder { calls: Vec::new(), batch: Ok(reply.clone()) }; + let r = crate::tools::call_tool(&mut b, "batch", &json!({"commands": steps, "expect": {"bodies": 1}})); + assert_eq!(methods(&b), ["engine.batch", "engine.execute"]); + assert_eq!(b.calls[1].1, json!({"command": "inspect.measure", "params": {}})); + // The recorder's measure reply has no bodies: the mismatch comes first, the batch's reply after it. + assert_eq!(r["isError"], json!(true), "{r}"); + assert!(r["content"][0]["text"].as_str().unwrap().starts_with("expectation not met: bodies: measured 0, expected 1."), "{r}"); + let body: Value = serde_json::from_str(r["content"][1]["text"].as_str().unwrap()).unwrap(); + assert_eq!((body["ok"].clone(), body["completed"].clone(), body["expectation"]["ok"].clone()), (json!(true), json!(1), json!(false)), "{body}"); + let failed = json!({"completed": 0, "results": [], "failed": {"index": 0, "command": "a.one", "error": "boom"}, "undone": 0}); + let (b, body, is_error) = recorded_batch(Ok(failed), json!({"commands": steps, "expect": {"bodies": 1}})); + assert!(is_error); + assert_eq!(methods(&b), ["engine.batch"], "a failed batch is not measured"); + assert!(body.get("expectation").is_none(), "{body}"); +} + /// `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. @@ -1912,7 +3110,7 @@ fn tool_annotations_tell_the_whole_truth() { assert_eq!(hints(name), (true, false, false), "{name}"); } assert_eq!(hints("new_design"), (false, true, false)); - for name in ["set_parameter", "undo", "redo"] { + for name in ["set_parameter", "check_parameters", "undo", "redo"] { assert_eq!(hints(name), (false, false, false), "{name}"); } assert!(tools.iter().all(|t| t["annotations"]["readOnlyHint"].is_boolean()), "every tool is annotated"); @@ -2351,9 +3549,9 @@ fn a_bridged_server_checks_calls_at_its_param_check_level() { assert_eq!(r["result"]["isError"], json!(true), "{r}"); assert!(text(&r).contains(&format!("invalid parameters for `solid.box`: {warning}")), "{r}"); assert_eq!(sent("engine.execute solid.box"), 0, "refused unsent"); - let r = raw_tool(&mut s, "execute", json!({"command": "solid.fillet", "params": {"nonsense": 1}})); + let r = raw_tool(&mut s, "execute", json!({"command": "solid.chamfer", "params": {"nonsense": 1}})); assert_ne!(r["result"]["isError"], json!(true), "{r}"); - assert_eq!(sent("engine.execute solid.fillet"), 1, "no contract here: the app decides"); + assert_eq!(sent("engine.execute solid.chamfer"), 1, "no contract here: the app decides"); let r = raw_tool(&mut s, "batch", json!({"commands": [good, misspelt]})); assert_eq!(r["result"]["isError"], json!(true), "{r}"); let reply: Value = serde_json::from_str(&text(&r)).unwrap(); diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 9a673b1f6..056fb7095 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -13,8 +13,14 @@ use crate::backend::{Backend, STILL_RUNNING}; const MAX_BATCH: usize = 10_000; /// Largest image returned by `screenshot`. const MAX_IMAGE_BYTES: usize = 32 << 20; +/// Relative tolerance on an expected volume (`expect.tol`) when the call gives none. +const EXPECT_VOLUME_TOL: f64 = 0.002; +/// Absolute tolerance on each expected bounding-box coordinate, mm. +const EXPECT_BBOX_TOL_MM: f64 = 0.05; const VIEWS: &[&str] = &["iso", "home", "front", "back", "top", "bottom", "left", "right", "fit"]; +/// What `check_parameters` can report. +const REPORTS: &[&str] = &["measure", "cylinders", "errors"]; fn obj(props: Value, required: &[&str]) -> Value { let mut o = json!({"type": "object", "properties": props, "additionalProperties": false}); @@ -58,6 +64,34 @@ fn string(desc: &str) -> Value { json!({"type": "string", "description": desc}) } +/// The `expect` argument of `execute` and `batch`: what the design should measure once the +/// call has gone through. +fn expect_schema() -> Value { + json!({ + "type": "object", + "description": "Check the design after the call against the numbers you computed: {volume_mm3?, tol? (relative, default 0.002), \ + bodies?, bbox?: {min: [x,y,z], max: [x,y,z]} (each coordinate within 0.05 mm)}. The reply gains `expectation`: \ + {ok, measured: {volume_mm3, bodies, bbox}, expected, mismatch: [\"volume: measured X, expected Y (+Z %)\", ...]}. \ + A mismatch is a tool error that names it first; the design is kept as built, so inspect it and fix it or carry on", + "properties": { + "volume_mm3": {"type": "number", "description": "Total volume of the closed bodies, mm³"}, + "tol": {"type": "number", "description": "Relative tolerance on the volume (default 0.002)"}, + "bodies": {"type": "integer", "description": "Number of bodies"}, + "bbox": { + "type": "object", + "description": "Bounding box of all bodies together, mm, each coordinate within 0.05 mm", + "properties": { + "min": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + "max": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + }, + "required": ["min", "max"], + "additionalProperties": false, + }, + }, + "additionalProperties": false, + }) +} + /// Every tool, with its JSON schema. The same list serves the headless and the bridged backend. pub fn tool_definitions() -> Vec { vec![ @@ -68,8 +102,26 @@ pub fn tool_definitions() -> Vec { enabled right now. Ids are dotted and lower-case (solid.extrude, sketch.create, \ solid.fillet, sketch.inspect, timeline.rollback). Optional case-insensitive \ substring `filter` over id, label, tab and panel (not the parameter docs, so a command id \ - finds that command rather than every command whose docs mention it).", - obj(json!({"filter": string("Substring to match, e.g. \"sketch\", \"fillet\", \"pattern\"")}), &[]), + finds that command rather than every command whose docs mention it). Narrow it further with `prefix` \ + (start of the id) and `panel` (a whole panel or tab name); shrink each entry with `compact` (id and label) \ + or `fields`; page it with `limit` and `offset`, which make the reply {commands, total, offset, next_offset}. \ + With none of these the reply is the whole catalog, about 350 KB.", + obj( + json!({ + "filter": string("Substring to match, e.g. \"sketch\", \"fillet\", \"pattern\""), + "prefix": string("Case-insensitive start of the command id, e.g. \"sketch.\""), + "panel": string("A whole toolbar panel or tab name, case-insensitive, e.g. \"Modify\" or \"SKETCH\""), + "compact": {"type": "boolean", "description": "Each entry is only {id, label} (default false)"}, + "fields": { + "type": "array", + "items": {"type": "string", "enum": COMMAND_FIELDS}, + "description": "Keep only these keys of each entry; overrides `compact`", + }, + "limit": {"type": "integer", "minimum": 1, "description": "At most this many commands; the reply becomes {commands, total, offset, next_offset}"}, + "offset": {"type": "integer", "minimum": 0, "description": "Skip this many matches first (default 0); with it the reply is paged as with `limit`"}, + }), + &[], + ), Effect::ReadOnly, ), tool( @@ -93,12 +145,14 @@ pub fn tool_definitions() -> Vec { after a delete (undo rewinds the counters with the design), usable right away \ in sketch.dimension, sketch.constraint.* and sketch.delete. Feature commands return the feature's id \ and name, every body (bodies) and the bodies the feature created, changed and removed (created_bodies, changed_bodies, removed_bodies). \ - view.pick {pixels: [[x,y]…]} answers the body, face, exact world point, normal and depth under pixels of a screenshot (read-only; docs/control-protocol.md).", + view.pick {pixels: [[x,y]…]} answers the body, face, exact world point, normal and depth under pixels of a screenshot (read-only; docs/control-protocol.md). \ + `expect` {volume_mm3, tol, bodies, bbox} checks the design after the command (as `batch` does) and flags a mismatch.", obj( json!({ "command": string("Command id (see list_commands)"), "params": {"type": "object", "description": "The command's parameters"}, "verbose": {"type": "boolean", "description": "false: omit the full feature body list and sketch ids repeated outside `created`; keep created_bodies, changed_bodies and removed_bodies (default true)"}, + "expect": expect_schema(), }), &["command"], ), @@ -110,14 +164,16 @@ pub fn tool_definitions() -> Vec { "Run commands in order, stopping at the first error. Each step is {command, params}: an engine command id \ (as list_commands lists them). A step may also name one of these tools with that tool's arguments as params, \ and runs the engine command it stands for: set_parameter (parameters.change; `value` or `expression`), \ - list_commands (engine.commands, with `filter`), describe_command (engine.describe), execute ({command, params}), \ - measure (inspect.measure), \ + list_commands (engine.commands, narrowed by its arguments), describe_command (engine.describe), execute ({command, params}), \ + measure (inspect.measure), compare_picture (inspect.compare_picture, numbers only: no overlay PNG), \ inspect_design (document.inspect), undo, redo, export, save, open, new_design, crash_reports; screenshot, \ body_topology, batch and pending can't be steps. On an error the steps already run are undone (unless \ rollback: false), so the batch is all-or-nothing; the reply names the failing step (index from 0), its error, \ every result before it, whether the design really went back (rolled_back), the steps whose changes are in the \ design (applied) and those never sent (not_run). The usual way to build a part: sketch, draw, dimension, \ - finish, extrude, fillet… in one call.", + finish, extrude, fillet… in one call. Give `expect` {volume_mm3, tol, bodies, bbox} with the numbers you computed \ + beforehand: after the last step the design is measured and compared, so no separate measure call is needed; a \ + mismatch is flagged as an error naming it, and the design is kept as built.", obj( json!({ "commands": { @@ -130,6 +186,7 @@ pub fn tool_definitions() -> Vec { "timings": {"type": "boolean", "description": "Add `timings`: [{index, command, ms}] for every step run (the failing one included) and `total_ms` (default false)"}, "profile": {"type": "boolean", "description": "Like timings, and each step's `profile`: {boolean_ms, tessellate_ms, other_ms}, its time in kernel booleans, in tessellation and the rest (default false)"}, "verbose": {"type": "boolean", "description": "false: a compact reply. Feature steps leave out the full body list (created_bodies, changed_bodies and removed_bodies stay), sketch steps the ids they repeat outside `created` (default true)"}, + "expect": expect_schema(), }), &["commands"], ), @@ -161,11 +218,15 @@ pub fn tool_definitions() -> Vec { bodies, with totals. With `items` (one or two selections, as `execute` takes them: faces, edges, vertices, \ sketch curves, profiles): one item's length, area or position, a circle's, arc's or cylinder's `diameter` and \ `radius` (with `circumference`, or an arc's `arc_length` and `angle_deg`), a slot's `slot` sizes; two items' \ - `min` and `max` distance and, where one is round, `center_distance` (centre to centre, or from its axis).", + `min` and `max` distance and, where one is round, `center_distance` (centre to centre, or from its axis). \ + `summary: true` keeps one short object per body (name, volume_mm3, bbox, faces, closed) and the total volume: \ + enough to check a stage against the numbers you computed, at a fraction of the size.", obj( json!({ "body": string("Body name (default: all bodies)"), + "names_only": {"type": "boolean", "description": "Only each body's name (assembly occurrences included) and its definition's, without measuring (default false)"}, "items": {"type": "array", "items": {"type": "object"}, "description": "One or two selections to measure instead of bodies, e.g. {\"type\": \"face\", \"body\": \"Body1\", \"index\": 3, \"point\": [x,y,z]}"}, + "summary": {"type": "boolean", "description": "Per body only name, volume_mm3, bbox {min, max}, faces and closed, and total.volume_mm3 (default false: the full reply)"}, }), &[], ), @@ -176,8 +237,17 @@ pub fn tool_definitions() -> Vec { "List edges and faces", "The edges (index, midpoint, length, endpoints) and faces (index, name, area, centroid, plane normal, a `point` that lies \ on the face, and for a cylindrical face its `cylinder`: origin, axis, radius) of a body. Use an edge midpoint as the \ - [x,y,z] point that picks the edge for fillet and chamfer; a face's point or its name picks the face for the face commands.", - obj(json!({"body": string("Body name, e.g. \"Body1\"")}), &["body"]), + [x,y,z] point that picks the edge for fillet and chamfer; a face's point or its name picks the face for the face commands. \ + `faces: \"cylinders\"` lists only the cylindrical faces, as `cylinders`, with the halves the kernel splits one cylinder \ + into merged: {radius, origin, axis, extent, names}, `extent` the [min, max] distance along `axis` from `origin` that \ + the cylinder spans, and no edges. That is enough to check where every hole and boss is, at a fraction of the size.", + obj( + json!({ + "body": string("Body name, e.g. \"Body1\""), + "faces": {"type": "string", "enum": ["all", "cylinders"], "description": "\"all\" (default): every edge and face. \"cylinders\": only the cylindrical faces, merged, with their extent along the axis, and no edges"}, + }), + &["body"], + ), Effect::ReadOnly, ), tool( @@ -200,6 +270,34 @@ pub fn tool_definitions() -> Vec { ), Effect::Edits, ), + tool( + "check_parameters", + "Try parameter values", + "Try parameter values without keeping them: set every parameter in `set` with one rebuild, report what `report` \ + asks for, and put the design back exactly as it was (undo history included). `measure`: volume, bbox, bodies and \ + faces per body as the measure tool reports them; `errors`: the features that fail or warn and the parameters that \ + don't evaluate; `cylinders`: every cylindrical face as {body, radius, origin, axis, faces, name}, the halves the \ + kernel splits one cylinder into merged (origin is the axis point closest to the world origin). The reply ends with \ + `restored: true`; if the design could not be put back the call is an error with `restored: false` and the values \ + still applied. An unknown parameter name is an error and nothing changes. Replaces the loop set_parameter, \ + measure, body_topology, set_parameter back.", + obj( + json!({ + "set": { + "type": "object", + "description": "Values to try, by parameter name: a number (mm) or an expression (\"140 mm\", \"wall * 2\"), as set_parameter's `value`", + "additionalProperties": {"type": ["number", "string"]}, + }, + "report": { + "type": "array", + "items": {"type": "string", "enum": REPORTS}, + "description": "What to report: measure, cylinders, errors (default all three)", + }, + }), + &["set"], + ), + Effect::Edits, + ), tool( "screenshot", "Look at the design", @@ -227,6 +325,34 @@ pub fn tool_definitions() -> Vec { ), Effect::Files, ), + tool( + "compare_picture", + "Compare with a reference picture", + "Compare the model's outline with the part in a reference picture — a concept render, a product photo, one view off a design board. \ + The model's outline is `inspect.silhouette` from `view` (default front), `camera` and `bodies`; the picture's part is found by growing \ + the background in from the border, so a backdrop's gradual shading stays background. The compare is outline only: holes are not \ + compared — both the picture's and the model's holes are filled. `reference` is a PNG or JPEG inside the server's \ + folders. `crop_px` / `crop_fraction` take one view off a board: [x, y, w, h] in pixels or as fractions 0..1 of the picture; \ + `part_fills_crop: true` says the crop box is the part itself, for a crop that tightly frames it. `fit` names \ + the dimension the scale comes from (\"width\", \"height\", \"both\"; default \"width\") — one uniform scale, never stretched per axis; \ + \"both\" scales by width and reports `aspect_mismatch` when the shapes differ. Returns as text the overlap (0..1) and the model's top, \ + bottom, left and right edges against the picture's in mm at nine stations (positive where the model reaches past the picture), and as \ + an image the overlay PNG: model red, picture blue.", + obj( + json!({ + "reference": string("PNG or JPEG to match, inside the server's folders"), + "view": string("Standard view (front, top, right, iso, ...) the picture is seen from (default front)"), + "camera": {"type": "object", "description": "Look from this camera instead: {target: [x,y,z], yaw, pitch, distance, fov?} (radians, mm; as view.apply). A photo taken in perspective gets an fov"}, + "bodies": {"type": "array", "items": {"type": "string"}, "description": "Body names to outline (default: the visible bodies)"}, + "crop_px": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] in pixels"}, + "crop_fraction": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] as fractions 0..1 of the picture"}, + "fit": {"type": "string", "enum": ["width", "height", "both"], "description": "The dimension the one uniform scale comes from (default width); both scales by width and reports aspect_mismatch"}, + "rows": {"type": "integer", "description": "The model outline's height in pixels (default 240)"}, + }), + &["reference"], + ), + Effect::Files, + ), tool( "export", "Export", @@ -406,6 +532,13 @@ fn text_result(v: &Value, is_error: bool) -> Value { let mut r = json!({"content": [{"type": "text", "text": text}]}); if is_error { r["isError"] = json!(true); + if let Some(reason) = v + .as_str() + .and_then(solidcraft_engine::panels::commands::structured_error) + .or_else(|| v.get("failed").and_then(|failed| failed.get("panel_error")).cloned()) + { + r["structuredContent"] = json!({"panel_error":reason}); + } } r } @@ -417,7 +550,10 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value { let a = args.as_object().unwrap_or(&empty); let r = match name { "screenshot" => return screenshot(b, a), + "compare_picture" => return compare_picture(b, a), "batch" => return batch(b, a), + "check_parameters" => return check_parameters(b, a), + "execute" => return execute(b, a), _ => dispatch(b, name, a), }; match r { @@ -426,6 +562,213 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value { } } +/// `execute`: one command, then its `expect` checked against the design. +fn execute(b: &mut dyn Backend, a: &Map) -> Value { + let expect = match Expect::parse(a) { + Ok(e) => e, + Err(e) => return text_result(&Value::String(e), true), + }; + match dispatch(b, "execute", a) { + Ok(v) => with_expectation(b, v, expect), + Err(e) => text_result(&Value::String(e), true), + } +} + +/// What `execute` or `batch` was told the design would measure once the call went through +/// (`expect`): the numbers an agent computes before building, compared by the server instead +/// of by hand after a separate `measure` call. Volume and body count hold whatever kernel +/// builds the design. +struct Expect { + volume_mm3: Option, + tol: f64, + bodies: Option, + bbox: Option<([f64; 3], [f64; 3])>, +} + +impl Expect { + /// The tool's `expect` argument: `None` when it was not given. A malformed one is refused + /// before the call runs, so a typo never builds a design that then goes unchecked. + fn parse(a: &Map) -> Result, String> { + let Some(v) = a.get("expect").filter(|v| !v.is_null()) else { return Ok(None) }; + let Some(o) = v.as_object() else { return Err("expect: must be an object {volume_mm3?, tol?, bodies?, bbox?}".into()) }; + if let Some(k) = o.keys().find(|k| !["volume_mm3", "tol", "bodies", "bbox"].contains(&k.as_str())) { + let k: String = k.chars().take(64).collect(); + return Err(format!("expect: unknown key `{k}`; its keys are: volume_mm3, tol, bodies, bbox")); + } + let number = |k: &str| -> Result, String> { + match o.get(k) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_f64().filter(|x| x.is_finite()).map(Some).ok_or_else(|| format!("expect: `{k}` must be a number")), + } + }; + let volume_mm3 = number("volume_mm3")?; + if volume_mm3.is_some_and(|v| v < 0.0) { + return Err("expect: `volume_mm3` must not be negative".into()); + } + let tol = number("tol")?.unwrap_or(EXPECT_VOLUME_TOL); + if tol < 0.0 { + return Err("expect: `tol` must not be negative".into()); + } + let bodies = match o.get("bodies") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().ok_or("expect: `bodies` must be a whole number, 0 or more")?), + }; + let bbox = match o.get("bbox") { + None | Some(Value::Null) => None, + Some(v) => Some(Self::parse_bbox(v)?), + }; + if volume_mm3.is_none() && bodies.is_none() && bbox.is_none() { + return Err("expect: nothing to check; give volume_mm3, bodies or bbox".into()); + } + Ok(Some(Expect { volume_mm3, tol, bodies, bbox })) + } + + fn parse_bbox(v: &Value) -> Result<([f64; 3], [f64; 3]), String> { + let Some(o) = v.as_object() else { return Err("expect: `bbox` must be {min: [x,y,z], max: [x,y,z]} in mm".into()) }; + if let Some(k) = o.keys().find(|k| !["min", "max"].contains(&k.as_str())) { + let k: String = k.chars().take(64).collect(); + return Err(format!("expect: unknown key `bbox.{k}`; its keys are: min, max")); + } + let corner = |k: &str| -> Result<[f64; 3], String> { + let err = || format!("expect: `bbox.{k}` must be [x, y, z] in mm"); + let xyz = o.get(k).and_then(Value::as_array).filter(|a| a.len() == 3).ok_or_else(err)?; + let mut c = [0.0; 3]; + for (slot, x) in c.iter_mut().zip(xyz) { + *slot = x.as_f64().filter(|x| x.is_finite()).ok_or_else(err)?; + } + Ok(c) + }; + let (min, max) = (corner("min")?, corner("max")?); + if min.iter().zip(&max).any(|(lo, hi)| lo > hi) { + return Err("expect: `bbox.min` must not exceed `bbox.max`".into()); + } + Ok((min, max)) + } + + /// What was expected, for the reply. + fn expected(&self) -> Value { + let mut e = Map::new(); + if let Some(v) = self.volume_mm3 { + e.insert("volume_mm3".into(), json!(v)); + e.insert("tol".into(), json!(self.tol)); + } + if let Some(n) = self.bodies { + e.insert("bodies".into(), json!(n)); + } + if let Some((min, max)) = self.bbox { + e.insert("bbox".into(), json!({"min": min, "max": max})); + } + Value::Object(e) + } + + /// Measure the design (as the `measure` tool does) and compare: the reply's `expectation` + /// (`ok`, `measured`, `expected`, `mismatch`). + fn check(&self, b: &mut dyn Backend) -> Result { + let m = exec(b, "inspect.measure", json!({}))?; + let bodies = m["body_count"].as_u64().unwrap_or(0); + let volume = m["total"]["volume_mm3"].as_f64(); + let bbox = m["bodies"].as_array().into_iter().flatten().filter_map(|body| corners(&body["bbox"])).reduce(|(lo, hi), (min, max)| { + ([lo[0].min(min[0]), lo[1].min(min[1]), lo[2].min(min[2])], [hi[0].max(max[0]), hi[1].max(max[1]), hi[2].max(max[2])]) + }); + let mut mismatch: Vec = Vec::new(); + if let Some(e) = self.volume_mm3 { + match volume { + Some(v) if (v - e).abs() <= self.tol * e.abs() => {} + Some(v) => { + let pct = if e != 0.0 { format!(" ({:+.2} %)", (v - e) / e * 100.0) } else { String::new() }; + mismatch.push(format!("volume: measured {}, expected {}{pct}", num(v), num(e))); + } + None => mismatch.push(format!("volume: not measured (no closed body), expected {}", num(e))), + } + } + if let Some(e) = self.bodies + && bodies != e + { + mismatch.push(format!("bodies: measured {bodies}, expected {e}")); + } + if let Some((emin, emax)) = self.bbox { + let expected = format!("min {} max {}", xyz_text(emin), xyz_text(emax)); + match bbox { + Some((min, max)) => { + let off: Vec = [("min", min, emin), ("max", max, emax)] + .into_iter() + .flat_map(|(side, m, e)| { + ["x", "y", "z"] + .into_iter() + .zip(m) + .zip(e) + .filter(|&((_, m), e)| (m - e).abs() > EXPECT_BBOX_TOL_MM) + .map(move |((axis, m), e)| format!("{side} {axis} off by {} mm", num(m - e))) + }) + .collect(); + if !off.is_empty() { + mismatch.push(format!( + "bbox: measured min {} max {}, expected {expected} ({})", + xyz_text(min), + xyz_text(max), + off.join(", ") + )); + } + } + None => mismatch.push(format!("bbox: no body to measure, expected {expected}")), + } + } + Ok(json!({ + "ok": mismatch.is_empty(), + "measured": {"volume_mm3": volume, "bodies": bodies, "bbox": bbox.map(|(min, max)| json!({"min": min, "max": max}))}, + "expected": self.expected(), + "mismatch": mismatch, + })) + } +} + +/// `{min: [x,y,z], max: [x,y,z]}` as two corners. +fn corners(v: &Value) -> Option<([f64; 3], [f64; 3])> { + let xyz = |k: &str| -> Option<[f64; 3]> { + let a = v.get(k)?.as_array()?; + Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?]) + }; + Some((xyz("min")?, xyz("max")?)) +} + +/// A number in a mismatch message: at most four decimals, no trailing zeros. +fn num(x: f64) -> String { + let r = (x * 1e4).round() / 1e4; + // `-0` for a coordinate a hair under zero would read as a sign error. + format!("{}", if r == 0.0 { 0.0 } else { r }) +} + +fn xyz_text(c: [f64; 3]) -> String { + format!("[{}, {}, {}]", num(c[0]), num(c[1]), num(c[2])) +} + +/// A reply that went through, with its `expectation` when `expect` was given. A mismatch is a +/// tool error that names it first; the design stays as built (the agent decides what to do). +fn with_expectation(b: &mut dyn Backend, mut reply: Value, expect: Option) -> Value { + let Some(expect) = expect else { return text_result(&reply, false) }; + let expectation = match expect.check(b) { + Ok(e) => e, + Err(e) => json!({"ok": false, "expected": expect.expected(), "mismatch": [format!("the design could not be measured: {e}")]}), + }; + let mismatch: Vec<&str> = expectation["mismatch"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let note = (expectation["ok"] != true).then(|| { + format!( + "expectation not met: {}. The design is kept as built: inspect it, then fix it (timeline.edit, undo) or carry on.", + mismatch.join("; ") + ) + }); + if !reply.is_object() { + reply = json!({"result": reply}); + } + reply["expectation"] = expectation; + let Some(note) = note else { return text_result(&reply, false) }; + let mut r = text_result(&reply, true); + if let Some(content) = r["content"].as_array_mut() { + content.insert(0, json!({"type": "text", "text": note})); + } + r +} + fn exec(b: &mut dyn Backend, command: &str, params: Value) -> Result { b.call("engine.execute", json!({"command": command, "params": params})).map_err(|error| command_error(command, error)) } @@ -440,6 +783,11 @@ fn command_error(command: &str, error: String) -> String { return error; } let id = command.split(['{', '(']).next().unwrap_or(command).trim(); + // An id that is exactly a registered tool name confuses the two namespaces: name the + // distinction and its recovery instead of offering unrelated closest-command suggestions. + if id == command.trim() && is_tool_name(id) { + return tool_name_error(id); + } let packed = id != command.trim(); let normalize = |s: &str| s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect::(); let normalized = normalize(id); @@ -473,6 +821,29 @@ fn command_error(command: &str, error: String) -> String { message } +/// Whether `name` is exactly a registered MCP tool name, read from the tool definitions +/// themselves so the two namespaces can never drift apart. +fn is_tool_name(name: &str) -> bool { + tool_definitions().iter().any(|t| t["name"].as_str() == Some(name)) +} + +/// The reply when a rejected command id is exactly a tool name: the recovery belongs to the +/// tool namespace, not to a typo's closest-command suggestions. +fn tool_name_error(id: &str) -> String { + format!( + "unknown command `{id}`: `{id}` is an MCP tool, not an engine command id. Use MCP tools/list for its tool schema, or list_commands for engine command ids." + ) +} + +/// A `describe_command` rejection of an id that is exactly a tool name gets the namespace +/// hint; every other error is left exactly as the engine said it. +fn describe_error(id: &str, error: String) -> String { + if error.starts_with(&format!("unknown command `{id}`")) && is_tool_name(id) { + return tool_name_error(id); + } + error +} + fn command_distance(a: &str, b: &str) -> usize { let mut row: Vec = (1..=b.len()).collect(); for (i, ca) in a.bytes().enumerate() { @@ -496,15 +867,33 @@ fn str_arg<'a>(a: &'a Map, k: &str) -> Option<&'a str> { a.get(k).and_then(Value::as_str) } +/// `measure`'s arguments (without `items`) as `inspect.measure` takes them. +fn measure_params(a: &Map) -> Value { + let mut p = pick(a, &["names_only"]); + if let Some(body) = str_arg(a, "body") { + p["bodies"] = json!([body]); + } + p +} + +/// `summary` narrows measured bodies; a `names_only` list has nothing to narrow. +fn measure_summary_wanted(a: &Map) -> bool { + let flag = |k: &str| a.get(k).and_then(Value::as_bool).unwrap_or(false); + flag("summary") && !flag("names_only") +} + fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result { match name { "list_commands" => { + let query = CommandQuery::parse(a)?; let all = b.call("engine.commands", json!({}))?; - Ok(filter_commands(all, str_arg(a, "filter"))) + Ok(query.apply(all)) } "describe_command" => { let id = str_arg(a, "id").ok_or("`id` is required")?; - exec(b, "engine.describe", json!({"command": id})) + // The engine rejects the requested id inside its own error, so the tool-name + // hint must inspect the `id`, not the outer `engine.describe` command `exec` sees. + exec(b, "engine.describe", json!({"command": id})).map_err(|e| describe_error(id, e)) } "execute" => { let id = str_arg(a, "command").ok_or("`command` is required")?; @@ -536,17 +925,17 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result json!({"bodies": [body]}), - None => json!({}), - }; - exec(b, "inspect.measure", p) + let m = exec(b, "inspect.measure", measure_params(a))?; + Ok(if measure_summary_wanted(a) { measure_summary(m) } else { m }) } "body_topology" => { let p = pick(a, &["body"]); let edges = exec(b, "model.edges", p.clone())?; let faces = exec(b, "model.faces", p)?; - Ok(json!({"body": a.get("body"), "edges": edges["edges"], "faces": faces["faces"]})) + Ok(match str_arg(a, "faces") { + Some("cylinders") => json!({"body": a.get("body"), "cylinders": topology_cylinders(&faces["faces"], &edges["edges"])}), + _ => json!({"body": a.get("body"), "edges": edges["edges"], "faces": faces["faces"]}), + }) } "set_parameter" => { let mut p = pick(a, &["name", "unit", "comment"]); @@ -571,11 +960,100 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result) -> Value { - let Some(f) = filter.map(str::to_lowercase).filter(|f| !f.is_empty()) else { return all }; - let hit = - |c: &Value| ["id", "label", "panel", "tab"].iter().any(|k| c.get(*k).and_then(Value::as_str).is_some_and(|s| s.to_lowercase().contains(&f))); - Value::Array(all.as_array().map(|v| v.iter().filter(|c| hit(c)).cloned().collect()).unwrap_or_default()) +/// The keys of a `list_commands` entry, which `fields` may keep. +const COMMAND_FIELDS: &[&str] = &["id", "label", "tab", "panel", "icon", "shortcut", "params", "enabled", "disabled_reason", "planned"]; + +/// How `list_commands` narrows the catalog (#11726): which commands, which keys of each, and +/// which page. The default keeps the whole catalog as it is. +#[derive(Clone, Debug, Default, PartialEq)] +struct CommandQuery { + filter: Option, + prefix: Option, + panel: Option, + fields: Option>, + limit: Option, + offset: Option, +} + +impl CommandQuery { + fn parse(a: &Map) -> Result { + let text = |k: &str| -> Result, String> { + match a.get(k) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.to_lowercase()).filter(|s| !s.is_empty())), + Some(_) => Err(format!("`{k}` must be a string")), + } + }; + let count = |k: &str, least: u64| -> Result, String> { + match a.get(k) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_u64() + .filter(|n| *n >= least) + .map(|n| Some(usize::try_from(n).unwrap_or(usize::MAX))) + .ok_or_else(|| format!("`{k}` must be a whole number of at least {least}")), + } + }; + let compact = match a.get("compact") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or("`compact` must be true or false")?, + }; + let fields = match a.get("fields") { + None | Some(Value::Null) => compact.then(|| vec!["id".to_string(), "label".to_string()]), + Some(Value::Array(v)) => { + let mut keep = Vec::new(); + for f in v { + let name = f.as_str().filter(|n| COMMAND_FIELDS.contains(n)).ok_or_else(|| { + let shown: String = f.to_string().chars().take(64).collect(); + format!("`fields` takes the entry keys {}; not {shown}", COMMAND_FIELDS.join(", ")) + })?; + if !keep.iter().any(|k| k == name) { + keep.push(name.to_string()); + } + } + Some(keep) + } + Some(_) => return Err("`fields` must be a list of entry keys".into()), + }; + Ok(Self { + filter: text("filter")?, + prefix: text("prefix")?, + panel: text("panel")?, + fields, + limit: count("limit", 1)?, + offset: count("offset", 0)?, + }) + } + + fn matches(&self, c: &Value) -> bool { + let field = |k: &str| c.get(k).and_then(Value::as_str).map(str::to_lowercase).unwrap_or_default(); + self.filter.as_ref().is_none_or(|f| ["id", "label", "panel", "tab"].iter().any(|k| field(k).contains(f.as_str()))) + && self.prefix.as_ref().is_none_or(|p| field("id").starts_with(p.as_str())) + && self.panel.as_ref().is_none_or(|p| field("panel") == *p || field("tab") == *p) + } + + /// The catalog narrowed: a list, or `{commands, total, offset, next_offset}` when paged. + fn apply(&self, all: Value) -> Value { + let Value::Array(all) = all else { return all }; + let hits: Vec = all.into_iter().filter(|c| self.matches(c)).collect(); + let total = hits.len(); + let offset = self.offset.unwrap_or(0).min(total); + let take = self.limit.unwrap_or(usize::MAX); + let page: Vec = hits + .into_iter() + .skip(offset) + .take(take) + .map(|c| match (&self.fields, c) { + (Some(keep), Value::Object(m)) => Value::Object(m.into_iter().filter(|(k, _)| keep.contains(k)).collect()), + (_, c) => c, + }) + .collect(); + if self.limit.is_none() && self.offset.is_none() { + return Value::Array(page); + } + let end = offset + page.len(); + json!({"commands": page, "total": total, "offset": offset, "next_offset": (end < total).then_some(end)}) + } } /// `pending`: the end of a request still running when its call returned (bridged only; a @@ -603,18 +1081,47 @@ fn pending(b: &mut dyn Backend) -> Result { Ok(json!({"pending": what, "done": false, "running_s": p.get("running_s"), "note": "still running: call pending again to keep waiting"})) } +/// How a tool step's result is cut down to what the tool itself would reply. +enum Narrow { + /// A `list_commands` step's catalog, narrowed as the tool narrows it. + Commands(CommandQuery), + /// A `measure {summary: true}` step's reply, as `measure_summary` shapes it. + MeasureSummary, +} + +impl Narrow { + fn apply(&self, v: Value) -> Value { + match self { + Narrow::Commands(q) => q.apply(v), + Narrow::MeasureSummary => measure_summary(v), + } + } +} + /// A `batch` step as the engine command it runs: an engine command as it is, or one of these /// tools' names (an agent writes the tool it knows) with that tool's arguments as its params. -/// `Ok((command, params, filter))`: `filter` narrows a `list_commands` step's catalog; an empty +/// `Ok((command, params, narrow))`: `narrow` cuts the step's result down as the tool would; an empty /// `command` means the step is an engine command already. -fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { +fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or("missing `command`")?; + // Any other key would be dropped and the command run without its parameters, failing (if at + // all) with an error about a parameter that seems to be there: `args` for `params`. + if let Some(k) = step.as_object().into_iter().flat_map(Map::keys).find(|k| !matches!(k.as_str(), "command" | "id" | "params")) { + if k == "expect" { + return Err("unknown key `expect` in a step: `expect` is the batch's argument, checked after the last step".into()); + } + let k: String = k.chars().take(64).collect(); + return Err(format!("unknown key `{k}` in a step: a step is {{command, params}}, its parameters go in `params`")); + } let empty = Map::new(); let params = step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({})); let a = params.as_object().unwrap_or(&empty); let mapped = |c: &str, p: Value| Ok((c.to_string(), p, None)); match command { - "list_commands" => Ok(("engine.commands".into(), json!({}), str_arg(a, "filter").map(str::to_string))), + "list_commands" => { + let query = CommandQuery::parse(a)?; + Ok(("engine.commands".into(), json!({}), (query != CommandQuery::default()).then_some(Narrow::Commands(query)))) + } "set_parameter" => { let mut p = pick(a, &["name", "unit", "comment"]); p["expression"] = parameter_value(a)?; @@ -630,8 +1137,16 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { } "measure" => match a.get("items") { Some(items) => mapped("inspect.measure", json!({"items": items})), - None => mapped("inspect.measure", str_arg(a, "body").map_or(json!({}), |body| json!({"bodies": [body]}))), + None => Ok(("inspect.measure".into(), measure_params(a), measure_summary_wanted(a).then_some(Narrow::MeasureSummary))), }, + "compare_picture" => { + // A batch step gets the numbers; the overlay PNG would be a base64 blob in text. + let mut p = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]); + if let Some(obj) = p.as_object_mut() { + obj.entry("overlay".to_string()).or_insert(json!(false)); + } + mapped("inspect.compare_picture", p) + } "inspect_design" => mapped("document.inspect", json!({"measure": a.get("measure").and_then(Value::as_bool).unwrap_or(true)})), "undo" => mapped("edit.undo", json!({})), "redo" => mapped("edit.redo", json!({})), @@ -646,6 +1161,7 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { "body_topology" => Err("`body_topology` is a tool, not a command: in a batch use model.edges {body} and model.faces {body}".into()), "screenshot" => Err("`screenshot` is a tool, not a command: call it after the batch".into()), "batch" => Err("batches don't nest: put the steps in this batch".into()), + "check_parameters" => Err("`check_parameters` is a tool, not a command: call it on its own (it puts the design back itself)".into()), "pending" => Err("`pending` is a tool, not a command: call it on its own".into()), "running" => Err("`running` is a tool, not a command: call it on its own".into()), "skill_reference" => Err("`skill_reference` is a tool, not a command: call it on its own".into()), @@ -658,6 +1174,8 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { const TOOL_STEPS: &[&str] = &[ "batch", "body_topology", + "check_parameters", + "compare_picture", "crash_reports", "describe_command", "execute", @@ -748,13 +1266,50 @@ impl Undo { } /// `batch`: run steps in order, stop at the first failure and (by default) go back to the -/// design as it was before the batch. +/// design as it was before the batch. A batch that went through is then checked against its +/// `expect`. fn batch(b: &mut dyn Backend, a: &Map) -> Value { + let expect = match Expect::parse(a) { + Ok(e) => e, + Err(e) => return text_result(&Value::String(e), true), + }; + match batch_run(b, a) { + (reply, true) => text_result(&reply, true), + (reply, false) => with_expectation(b, reply, expect), + } +} + +fn layout_step(step: &Value) -> bool { + let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).unwrap_or_default(); + let command = if command == "execute" { + step.get("params").and_then(|params| params.get("command")).and_then(Value::as_str).unwrap_or_default() + } else { + command + }; + command.split('.').next().is_some_and(|area| area.eq_ignore_ascii_case("panel") || area.eq_ignore_ascii_case("layout")) +} + +fn atomic_layout_refusal(count: usize, rule: solidcraft_engine::panels::Rule, detail: &str) -> (Value, bool) { + use solidcraft_engine::panels::{commands, error}; + let mut reply = commands::sequential_failure(0, None, commands::error_text(error(rule, detail)), Vec::new()); + reply["ok"] = json!(false); + reply["applied"] = json!([]); + reply["not_run"] = if count <= MAX_BATCH { json!((0..count).collect::>()) } else { json!([]) }; + reply["not_run_count"] = json!(count); + reply["note"] = json!("nothing was run: atomic application layout requires the authoritative backend transaction"); + (reply, true) +} + +/// The batch itself: its reply and whether it failed. +fn batch_run(b: &mut dyn Backend, a: &Map) -> (Value, bool) { let Some(steps) = a.get("commands").and_then(Value::as_array) else { - return text_result(&json!("`commands` must be an array of {command, params}"), true); + return (json!("`commands` must be an array of {command, params}"), true); }; if steps.len() > MAX_BATCH { - return text_result(&json!(format!("batch too long ({} steps, at most {MAX_BATCH})", steps.len())), true); + if a.get("rollback").and_then(Value::as_bool).unwrap_or(true) && steps.iter().any(layout_step) { + return atomic_layout_refusal(steps.len(), solidcraft_engine::panels::Rule::CollectionLimit, "atomic layout batch step count cap"); + } + return (json!(format!("batch too long ({} steps, at most {MAX_BATCH})", steps.len())), true); } let rollback = a.get("rollback").and_then(Value::as_bool).unwrap_or(true); let verbose = a.get("verbose").and_then(Value::as_bool).unwrap_or(true); @@ -763,24 +1318,24 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { // Steps that name a tool run the engine command it stands for. One that can't be a step // fails the batch before anything is sent. let mut mapped: Vec = Vec::with_capacity(steps.len()); - let mut filters: Vec<(usize, String)> = Vec::new(); + let mut narrows: Vec<(usize, Narrow)> = Vec::new(); for (i, step) in steps.iter().enumerate() { // The window goes to another design's tab for these, however the step names them: the // batch's later steps and its rollback would land in the wrong design. - let step_result = batch_step(step).and_then(|(command, params, filter)| { + let step_result = batch_step(step).and_then(|(command, params, narrow)| { let id = if command.is_empty() { step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).unwrap_or("") } else { &command }; match solidcraft_engine::find_command(id).map(|spec| spec.id) { Some(c @ ("component.edit_in_place" | "component.finish_edit")) => { Err(format!("`{c}` goes to another design's tab: send it on its own, not in a batch")) } - _ => Ok((command, params, filter)), + _ => Ok((command, params, narrow)), } }); match step_result { Ok((command, _, _)) if command.is_empty() => mapped.push(step.clone()), - Ok((command, params, filter)) => { - if let Some(f) = filter { - filters.push((i, f)); + Ok((command, params, narrow)) => { + if let Some(n) = narrow { + narrows.push((i, n)); } mapped.push(json!({"command": command, "params": params})); } @@ -799,11 +1354,12 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { "results": [], "note": "nothing was run", }); - return text_result(&reply, true); + return (reply, true); } } } let steps = &mapped; + let atomic_layout = rollback && steps.iter().any(layout_step); // A step the batch would refuse at its turn refuses it now, before anything runs (#5853). // Only where the commands run in this process: a running app may be another version, with // commands this one lacks, and checks the batch against its own registry when it gets it. @@ -818,11 +1374,12 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { if let (Some(command), Some(failed)) = (refusal.command.as_deref(), reply.get_mut("failed").and_then(Value::as_object_mut)) { failed.insert("error".into(), Value::String(command_error(command, refusal.error.clone()))); } - return text_result(&reply, true); + return (reply, true); } - // A `list_commands` step's catalog, filtered as the tool filters it. - let narrow = |i: usize, v: Value| match filters.iter().find(|(j, _)| *j == i) { - Some((_, f)) => filter_commands(v, Some(f)), + // A tool step's result as the tool would reply it: a `list_commands` step's catalog filtered, + // a `measure {summary: true}` step's reply summarised. + let narrow = |i: usize, v: Value| match narrows.iter().find(|(j, _)| *j == i) { + Some((_, n)) => n.apply(v), None => v, }; // An app that runs batches itself answers the whole batch in one request, so one frame @@ -837,7 +1394,8 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { o.insert("timings".into(), Value::Bool(true)); o.insert("profile".into(), Value::Bool(profile)); } - if params.to_string().len() + 64 * 1024 <= solidcraft_engine::MAX_LINE { + let fits_transport = params.to_string().len().saturating_add(64 * 1024) <= solidcraft_engine::MAX_LINE; + if fits_transport { match b.call("engine.batch", params) { Ok(mut r) => { if let Some(failed) = r.get_mut("failed") @@ -852,18 +1410,33 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { } // Older apps and the headless session, or the app wants the steps one by one. Err(e) if e.starts_with("unknown method") || e.starts_with("engine.batch unavailable") => {} + Err(e) if solidcraft_engine::panels::commands::structured_error(&e).is_some() => return (Value::String(e), true), // Never sent: no app to send it to. Or sent and still running (it was not cancelled): // the `pending` tool gets its result. Err(e) if e.starts_with(crate::backend::NOT_RUNNING) || e.starts_with(STILL_RUNNING) => { - return text_result(&Value::String(e), true); + return (Value::String(e), true); } // The app may have run it: sending the steps again would apply them twice. Err(e) => { let msg = format!("the app did not answer engine.batch ({e}); it may have run: inspect the design before sending it again"); - return text_result(&Value::String(msg), true); + return (Value::String(msg), true); } } } + // Application layout is outside document checkpoints. Neither an unavailable + // batch endpoint nor an oversized transport request authorizes a sequential + // emulation of an atomic layout/mixed transaction. + if atomic_layout { + return atomic_layout_refusal( + steps.len(), + if fits_transport { solidcraft_engine::panels::Rule::Capability } else { solidcraft_engine::panels::Rule::CollectionLimit }, + if fits_transport { + "authoritative atomic layout batch capability is unavailable" + } else { + "atomic layout batch exceeds transport size cap" + }, + ); + } let start = if rollback { Undo::begin(b) } else { Undo::None }; let mut results = Vec::with_capacity(steps.len()); let mut rows = Vec::new(); @@ -930,14 +1503,14 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { "not_run": (i + 1..steps.len()).collect::>(), "results": results, }); - return text_result(&with_timings(reply, timed, rows, clock.ms()), true); + return (with_timings(reply, timed, rows, clock.ms()), true); } } } } start.finish(b); let reply = json!({"ok": true, "completed": results.len(), "results": results}); - text_result(&with_timings(reply, timed, rows, clock.ms()), false) + (with_timings(reply, timed, rows, clock.ms()), false) } /// `reply` with `timings` and `total_ms` when they were asked for. @@ -950,7 +1523,7 @@ fn with_timings(mut reply: Value, timed: bool, rows: Vec, total_ms: f64) } /// The `batch` reply from the app's `engine.batch` answer, shaped as the per-step path shapes it. -fn batch_reply(r: &Value, len: usize, rollback: bool, verbose: bool, narrow: &dyn Fn(usize, Value) -> Value) -> Value { +fn batch_reply(r: &Value, len: usize, rollback: bool, verbose: bool, narrow: &dyn Fn(usize, Value) -> Value) -> (Value, bool) { let results: Vec = r["results"] .as_array() .cloned() @@ -994,7 +1567,151 @@ fn batch_reply(r: &Value, len: usize, rollback: bool, verbose: bool, narrow: &dy } } } - text_result(&reply, error) + (reply, error) +} + +/// `measure {summary: true}`: an `inspect.measure` reply cut down to what checks a stage against +/// computed numbers: per body `name`, `volume_mm3`, `bbox`, `faces` and `closed` (a body that +/// could not be measured keeps its `error`), `body_count` and the total volume. An `items` +/// reply is small already and goes through as it is. +fn measure_summary(v: Value) -> Value { + let Some(o) = v.as_object() else { return v }; + if !o.contains_key("bodies") { + return v; + } + let bodies: Vec = o + .get("bodies") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|b| { + let mut s = Map::new(); + let keys: &[&str] = if b.get("error").is_some() { &["name", "error"] } else { &["name", "volume_mm3", "bbox", "faces", "closed"] }; + for k in keys { + s.insert((*k).to_string(), b.get(*k).cloned().unwrap_or(Value::Null)); + } + Value::Object(s) + }) + .collect(); + json!({ + "body_count": o.get("body_count").cloned().unwrap_or_else(|| json!(bodies.len())), + "bodies": bodies, + "total": {"volume_mm3": o.get("total").and_then(|t| t.get("volume_mm3")).cloned().unwrap_or(Value::Null)}, + }) +} + +/// A `[x, y, z]` JSON array as numbers. +fn xyz(v: &Value) -> Option<[f64; 3]> { + let a = v.as_array()?; + if a.len() != 3 { + return None; + } + let p = [a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?]; + p.iter().all(|c| c.is_finite()).then_some(p) +} + +fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +/// One cylinder as `body_topology {faces: "cylinders"}` reports it: the faces that lie on it, +/// merged by equal radius and the same axis line. +struct TopoCylinder { + radius: f64, + origin: [f64; 3], + /// Unit length. + axis: [f64; 3], + /// Distances along `axis` from `origin` of the points found on the cylinder so far. + extent: Option<(f64, f64)>, + names: Vec, +} + +/// How far a point lies from the cylinder's axis line, and how far along it from the origin. +fn axial(c: &TopoCylinder, p: [f64; 3]) -> (f64, f64) { + let d = sub(p, c.origin); + let along = dot(d, c.axis); + let off = cross(d, c.axis); + (dot(off, off).sqrt(), along) +} + +/// Does `p` lie on the cylinder's surface, within `tol`? +fn on_cylinder(c: &TopoCylinder, p: [f64; 3], tol: f64) -> bool { + (axial(c, p).0 - c.radius).abs() <= tol +} + +fn widen(c: &mut TopoCylinder, p: [f64; 3]) { + let t = axial(c, p).1; + c.extent = Some(match c.extent { + Some((lo, hi)) => (lo.min(t), hi.max(t)), + None => (t, t), + }); +} + +/// Positions and axes that agree within this are one cylinder (mm). +const CYLINDER_TOL: f64 = 1e-3; + +/// `body_topology {faces: "cylinders"}`: the cylindrical faces of `model.faces`, the halves the +/// kernel splits one cylinder into merged (equal radius, the same axis line: origin on the axis, +/// direction up to sign), each with the extent along its axis that the body's own points on the +/// cylinder span (the faces' `point`s and the ends and midpoints of the edges lying on it). Built +/// from what `model.faces` and `model.edges` already reply, so it needs nothing of the kernel. +fn topology_cylinders(faces: &Value, edges: &Value) -> Value { + let mut found: Vec = Vec::new(); + for f in faces.as_array().into_iter().flatten() { + let c = &f["cylinder"]; + let (Some(radius), Some(origin), Some(axis)) = (c["radius"].as_f64(), xyz(&c["origin"]), xyz(&c["axis"])) else { continue }; + let len = dot(axis, axis).sqrt(); + if !radius.is_finite() || radius <= 0.0 || !len.is_finite() || len < 1e-9 { + continue; + } + let axis = [axis[0] / len, axis[1] / len, axis[2] / len]; + // The same cylinder: the same radius and axis direction (either way round), and this + // face's origin on that axis line. + let same = |k: &TopoCylinder| { + let off = cross(sub(origin, k.origin), k.axis); + (k.radius - radius).abs() <= CYLINDER_TOL && dot(k.axis, axis).abs() >= 1.0 - 1e-6 && dot(off, off).sqrt() <= CYLINDER_TOL + }; + let name = f.get("name").cloned().unwrap_or(Value::Null); + let at = match found.iter().position(same) { + Some(i) => i, + None => { + found.push(TopoCylinder { radius, origin, axis, extent: None, names: Vec::new() }); + found.len() - 1 + } + }; + if let Some(k) = found.get_mut(at) { + k.names.push(name); + if let Some(p) = xyz(&f["point"]) { + widen(k, p); + } + } + } + // The ends of the cylinder: the vertices of the edges that lie on it (a circle's ends and + // midpoint are on it; an edge of another face at most touches it in two points). + for e in edges.as_array().into_iter().flatten() { + let (Some(start), Some(mid), Some(end)) = (xyz(&e["start"]), xyz(&e["mid"]), xyz(&e["end"])) else { continue }; + for c in &mut found { + let tol = CYLINDER_TOL.max(c.radius * 1e-4); + if [start, mid, end].iter().all(|p| on_cylinder(c, *p, tol)) { + widen(c, start); + widen(c, end); + } + } + } + found + .into_iter() + .map(|c| { + let mut v = json!({"radius": c.radius, "origin": c.origin, "axis": c.axis, "names": c.names}); + if let (Some((lo, hi)), Some(o)) = (c.extent, v.as_object_mut()) { + o.insert("extent".into(), json!([lo, hi])); + } + v + }) + .collect() } /// A command's result without what the design already had (`execute` or `batch` with `verbose: false`): a @@ -1015,6 +1732,235 @@ fn compact(mut v: Value) -> Value { v } +/// `check_parameters`: try parameter values and put the design back (#3380). The checkpoint is +/// taken before anything changes; whatever happens after it, the design is restored, and a +/// restore that fails is an error saying the values are still in. Every agent session that +/// changed a parameter to see its effect spent three to five calls on this loop, and one saved +/// the design with the test values still in it. +fn check_parameters(b: &mut dyn Backend, a: &Map) -> Value { + let (changes, reports) = match check_parameters_args(a) { + Ok(x) => x, + Err(e) => return text_result(&Value::String(e), true), + }; + // A name the design has no parameter of is refused before the checkpoint, so nothing + // changes: `parameters.change` would make one. + if let Err(e) = known_parameters(b, &changes) { + return text_result(&Value::String(e), true); + } + let Some(id) = exec(b, "edit.checkpoint", json!({})).ok().and_then(|v| v["checkpoint"].as_u64()) else { + let e = "check_parameters: this app has no edit.checkpoint to put the design back with; use set_parameter and measure, and set the values back yourself"; + return text_result(&json!(e), true); + }; + let outcome = try_parameters(b, &changes, &reports); + let restore = exec(b, "edit.restore_checkpoint", json!({"checkpoint": id})); + match (outcome, restore) { + (Ok(mut reply), Ok(_)) => { + reply["restored"] = json!(true); + text_result(&reply, false) + } + (Err(e), Ok(_)) => text_result(&json!({"error": e, "restored": true, "note": "the design is back as it was"}), true), + (outcome, Err(restore_error)) => { + let mut reply = match outcome { + Ok(r) => r, + Err(e) => json!({"error": e}), + }; + reply["restored"] = json!(false); + reply["restore_error"] = json!(restore_error); + reply["note"] = json!( + "THE DESIGN STILL HOLDS THE TRIED VALUES: the checkpoint could not be restored. Set them back with set_parameter (or undo) before saving" + ); + text_result(&reply, true) + } + } +} + +/// `check_parameters`'s arguments, checked before anything is sent: the values to try (a +/// number or an expression each, as `set_parameter` takes its `value`) and what to report. +fn check_parameters_args(a: &Map) -> Result<(Map, Vec<&'static str>), String> { + let set = a.get("set").and_then(Value::as_object).ok_or("check_parameters: `set` must be an object of parameter name: value")?; + if set.is_empty() { + return Err("check_parameters: `set` is empty; give at least one parameter name: value".into()); + } + let mut changes = Map::new(); + for (name, v) in set { + let name = name.trim(); + if name.is_empty() { + return Err("check_parameters: a parameter name in `set` is empty".into()); + } + if !matches!(v, Value::Number(_) | Value::String(_)) { + let shown: String = name.chars().take(64).collect(); + return Err(format!("check_parameters: `set.{shown}` must be a number (mm) or an expression, as set_parameter's `value`")); + } + changes.insert(name.to_string(), v.clone()); + } + let reports = match a.get("report").filter(|r| !r.is_null()) { + None => REPORTS.to_vec(), + Some(r) => { + let items = r.as_array().ok_or("check_parameters: `report` must be an array of measure, cylinders, errors")?; + let mut out: Vec<&'static str> = Vec::new(); + for item in items { + let Some(known) = item.as_str().and_then(|s| REPORTS.iter().copied().find(|r| *r == s)) else { + return Err(format!("check_parameters: `report` items must be one of {}", REPORTS.join(", "))); + }; + if !out.contains(&known) { + out.push(known); + } + } + out + } + }; + Ok((changes, reports)) +} + +/// Refuse a name the design has no parameter of, before anything changes. An app without +/// `parameters.list` is not asked; the change itself then tells. +fn known_parameters(b: &mut dyn Backend, changes: &Map) -> Result<(), String> { + let Ok(list) = exec(b, "parameters.list", json!({})) else { return Ok(()) }; + let Some(rows) = list["parameters"].as_array() else { return Ok(()) }; + let names: Vec<&str> = rows.iter().filter_map(|r| r["name"].as_str()).collect(); + let shown = |n: &str| format!("`{}`", n.chars().take(64).collect::()); + let unknown: Vec = changes.keys().filter(|n| !names.contains(&n.as_str())).map(|n| shown(n)).collect(); + if unknown.is_empty() { + return Ok(()); + } + let user: Vec = rows.iter().filter(|r| r["source"] == "user").filter_map(|r| r["name"].as_str()).take(40).map(shown).collect(); + let have = if user.is_empty() { "no user parameters".to_string() } else { format!("user parameters {}", user.join(", ")) }; + Err(format!("check_parameters: no parameter {}; the design has {have} (parameters.list shows every parameter)", unknown.join(", "))) +} + +/// Apply the values and read back what was asked for: what each parameter is now, the +/// features rebuilt, and the reports. +fn try_parameters(b: &mut dyn Backend, changes: &Map, reports: &[&str]) -> Result { + let (values, recomputed) = apply_parameters(b, changes)?; + let mut reply = json!({"set": changes, "values": values, "recomputed": recomputed}); + // The bodies and each feature's state: one cheap read serves `errors` and `cylinders`. + let design = if reports.iter().any(|r| *r != "measure") { Some(b.call("document.inspect", json!({"measure": false}))?) } else { None }; + for r in reports { + match *r { + "measure" => reply["measure"] = exec(b, "inspect.measure", json!({}))?, + "errors" => { + if let Some(d) = &design { + let pick = |key: &str| -> Value { + let rows = d["timeline"].as_array().into_iter().flatten().filter(|f| !f[key].is_null()); + Value::Array(rows.map(|f| json!({"feature": f["id"], "name": f["name"], key: f[key]})).collect()) + }; + reply["errors"] = pick("error"); + reply["warnings"] = pick("warning"); + let params = d["params"].as_array().into_iter().flatten().filter(|p| !p["error"].is_null()); + reply["parameter_errors"] = Value::Array(params.map(|p| json!({"name": p["name"], "error": p["error"]})).collect()); + } + } + "cylinders" => { + if let Some(d) = &design { + let bodies: Vec = + d["bodies"].as_array().into_iter().flatten().filter_map(|body| body["name"].as_str()).map(str::to_string).collect(); + reply["cylinders"] = Value::Array(cylinders(b, &bodies)); + } + } + _ => {} + } + } + Ok(reply) +} + +/// Set the values with one `parameters.change {changes}`, so the design rebuilds once. An app +/// without `changes` (it asks for `name`, or refuses the key) gets one `parameters.change` per +/// name instead; any other refusal (an expression that does not evaluate) is the error. Returns +/// each parameter's value now and the features rebuilt. +fn apply_parameters(b: &mut dyn Backend, changes: &Map) -> Result<(Map, Value), String> { + let combined = solidcraft_engine::batch_params::combined_params(changes); + match exec(b, "parameters.change", combined) { + Ok(v) => Ok((v["changed"].as_object().cloned().unwrap_or_default(), v["recomputed"].clone())), + Err(e) if e.contains("`name`") || e.contains("`changes`") => { + let mut values = Map::new(); + let mut recomputed = 0u64; + for (name, expression) in changes { + let v = exec(b, "parameters.change", json!({"name": name, "expression": expression}))?; + values.insert(name.clone(), v["value"].clone()); + recomputed += v["recomputed"].as_u64().unwrap_or(0); + } + Ok((values, json!(recomputed))) + } + Err(e) => Err(e), + } +} + +/// Every cylindrical face of these bodies (`model.faces`), the halves one cylinder is split +/// into merged. +fn cylinders(b: &mut dyn Backend, bodies: &[String]) -> Vec { + let mut out = Vec::new(); + for body in bodies { + match exec(b, "model.faces", json!({"body": body})) { + Ok(f) => out.extend(merge_cylinders(body, f["faces"].as_array().map(Vec::as_slice).unwrap_or(&[]))), + Err(e) => out.push(json!({"body": body, "error": e})), + } + } + out +} + +/// One cylinder of a body: the faces on it (one, or the halves a kernel splits it into). +struct Cylinder { + radius: f64, + origin: [f64; 3], + axis: [f64; 3], + faces: Vec, + name: Value, + area: f64, +} + +fn vec3(v: &Value) -> Option<[f64; 3]> { + let a = v.as_array()?; + match (a.first()?.as_f64(), a.get(1)?.as_f64(), a.get(2)?.as_f64()) { + (Some(x), Some(y), Some(z)) if x.is_finite() && y.is_finite() && z.is_finite() => Some([x, y, z]), + _ => None, + } +} + +fn dot(a: [f64; 3], b: [f64; 3]) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// The cylindrical faces of one body as cylinders: faces with the same radius on the same +/// axis line are one cylinder, whatever point on the axis and whichever direction each half +/// reports. The origin is the axis point closest to the world origin and the axis points so +/// that its first non-zero component is positive, so the same cylinder reads the same whichever +/// kernel built it. +fn merge_cylinders(body: &str, faces: &[Value]) -> Vec { + let mut found: Vec = Vec::new(); + for f in faces { + let c = &f["cylinder"]; + let (Some(radius), Some(origin), Some(axis)) = (c["radius"].as_f64(), vec3(&c["origin"]), vec3(&c["axis"])) else { continue }; + let len = dot(axis, axis).sqrt(); + if !(radius > 0.0) || !radius.is_finite() || !(len > 0.0) { + continue; + } + let mut axis = axis.map(|x| x / len); + if axis.iter().find(|x| x.abs() > 1e-9).is_some_and(|x| *x < 0.0) { + // A zero component stays 0.0, not -0.0. + axis = axis.map(|x| if x.abs() > 1e-9 { -x } else { 0.0 }); + } + let t = dot(origin, axis); + let origin = [origin[0] - t * axis[0], origin[1] - t * axis[1], origin[2] - t * axis[2]]; + let tol = 1e-4 * radius.max(1.0); + let area = f["area"].as_f64().unwrap_or(0.0); + let same = |k: &Cylinder| { + let d = [k.origin[0] - origin[0], k.origin[1] - origin[1], k.origin[2] - origin[2]]; + (k.radius - radius).abs() <= tol && dot(k.axis, axis) >= 1.0 - 1e-8 && dot(d, d).sqrt() <= tol + }; + match found.iter_mut().find(|k| same(k)) { + Some(k) => { + k.faces.push(f["index"].clone()); + k.area += area; + } + None => found.push(Cylinder { radius, origin, axis, faces: vec![f["index"].clone()], name: f["name"].clone(), area }), + } + } + found + .into_iter() + .map(|k| json!({"body": body, "radius": k.radius, "origin": k.origin, "axis": k.axis, "faces": k.faces, "name": k.name, "area": k.area})) + .collect() +} + static SHOT: AtomicU64 = AtomicU64::new(0); /// `screenshot`: render or capture to a file, return it as an MCP image content block. @@ -1028,6 +1974,28 @@ fn screenshot(b: &mut dyn Backend, a: &Map) -> Value { } } +/// `compare_picture`: run the engine comparison and hand the overlay PNG back as an MCP +/// image block, the numbers as text — an agent sees the picture, not a base64 blob. +fn compare_picture(b: &mut dyn Backend, a: &Map) -> Value { + let mut params = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]); + params["overlay"] = json!(true); + match exec(b, "inspect.compare_picture", params) { + Ok(v) => { + let overlay = v.get("overlay_png").and_then(Value::as_str).unwrap_or_default().to_string(); + let mut info = v; + if let Some(obj) = info.as_object_mut() { + obj.remove("overlay_png"); + } + let mut content = vec![json!({"type": "text", "text": info.to_string()})]; + if !overlay.is_empty() { + content.insert(0, json!({"type": "image", "data": overlay, "mimeType": "image/png"})); + } + json!({"content": content}) + } + Err(e) => text_result(&Value::String(e), true), + } +} + fn capture(b: &mut dyn Backend, a: &Map) -> Result<(Vec, Value), String> { // `grid` and `axes` shape a model render; the window shows what it shows. let guides: Vec<(&str, bool)> = ["grid", "axes"].into_iter().filter_map(|k| a.get(k).and_then(Value::as_bool).map(|v| (k, v))).collect(); diff --git a/crates/profile/Cargo.toml b/crates/profile/Cargo.toml new file mode 100644 index 000000000..40afdec98 --- /dev/null +++ b/crates/profile/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "solidcraft-profile" +description = "SolidCraft profiler: nested, per-thread timed spans of kernel calls, kernel operations, feature evaluation, commands and imports, as a table and a Chrome trace" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[features] +# Compile the profiler in. Every app turns it on by default (its `profile` feature); off, every +# call here is an empty inline function and the crate records nothing. On, recording still waits +# for `set_enabled(true)`, and a span costs one relaxed atomic load until then. +enabled = [] + +[dependencies] +serde_json = { workspace = true } +# Instant that also works in the browser (std's panics on wasm32-unknown-unknown). +web-time = { workspace = true } diff --git a/crates/profile/src/lib.rs b/crates/profile/src/lib.rs new file mode 100644 index 000000000..ae9779873 --- /dev/null +++ b/crates/profile/src/lib.rs @@ -0,0 +1,550 @@ +//! Where SolidCraft spends its time: nested, timed spans on every thread, for SMLib's C API +//! calls (timed by the C API itself), kernel operations, feature evaluation, commands and the +//! stages of a STEP or IGES import. +//! +//! - **Compiled in** with the `enabled` feature, which every app turns on by default (its own +//! `profile` feature), so a release can be profiled; a build without it records nothing and +//! every call here is an empty inline function. +//! - **Off at run time** until [`set_enabled`] (`SOLIDCRAFT_PROFILE=1`, the CLI's `--profile`, the +//! app's preference, the `diagnostics.profile` command). Off, a span costs one relaxed atomic +//! load. +//! - **Two outputs:** an aggregate per span name ([`report`]: count, total, self time, longest), +//! kept for the whole run, and the individual spans as a Chrome trace-event file +//! ([`write_chrome_trace`], for chrome://tracing or Perfetto), capped at [`MAX_EVENTS`] +//! (later spans still count in the aggregate; the report says how many were dropped). +//! +//! A span's self time is its time less its children's on the same thread. Its total counts only +//! its outermost occurrence on a thread's stack, so a command run by a command, or a boolean +//! inside a boolean, is not counted twice. Work a span hands to other threads shows there, under +//! those threads' own spans. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::time::Duration; + +/// The profiler is compiled into this build. +pub const COMPILED: bool = cfg!(any(feature = "enabled", test)); + +/// Spans kept for the trace; later ones count in the aggregate only. +pub const MAX_EVENTS: usize = 200_000; + +/// Distinct names [`intern`] keeps; later new names are all [`OTHER`]. +pub const MAX_NAMES: usize = 4096; + +/// The name of a span whose own name did not fit in [`MAX_NAMES`]. +pub const OTHER: &str = "other"; + +/// One span name's aggregate. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Row { + /// What the span is: `solidcore`, `kernel`, `feature`, `command`, `import`, … + pub category: &'static str, + pub name: &'static str, + /// Times the span ran. + pub count: u64, + /// Its time, counting only its outermost occurrence on each thread's stack. + pub total: Duration, + /// Its time less the time of the spans inside it. + pub self_time: Duration, + /// Its longest single run. + pub max: Duration, +} + +/// What the profiler has recorded since it was last reset. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Report { + /// The profiler is compiled in. + pub compiled: bool, + /// It is recording now. + pub enabled: bool, + /// Wall time since the last reset (or since recording first started). + pub wall: Duration, + /// One row per span name, in no particular order. + pub rows: Vec, + /// Spans kept for the trace. + pub events: usize, + /// Spans past [`MAX_EVENTS`], left out of the trace (they are in the rows). + pub dropped: u64, +} + +fn ms(d: Duration) -> f64 { + (d.as_secs_f64() * 1e6).round() / 1e3 +} + +impl Report { + /// The rows, the most self time first. + pub fn sorted(&self) -> Vec { + let mut rows = self.rows.clone(); + rows.sort_by(|a, b| b.self_time.cmp(&a.self_time).then(b.total.cmp(&a.total)).then(a.name.cmp(b.name))); + rows + } + + /// Self time per category, the most first: where the time went (SMLib or SolidCraft). + pub fn by_category(&self) -> Vec<(&'static str, Duration)> { + let mut out: Vec<(&'static str, Duration)> = Vec::new(); + for r in &self.rows { + match out.iter_mut().find(|(c, _)| *c == r.category) { + Some((_, d)) => *d += r.self_time, + None => out.push((r.category, r.self_time)), + } + } + out.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + out + } + + /// What was recorded after `earlier` (a report of the same run, taken before): counts and + /// times are the differences. `max` is the longest run of the whole recording, which may + /// be older than `earlier`. + pub fn since(&self, earlier: &Report) -> Report { + let rows = self + .rows + .iter() + .filter_map(|r| { + let before = earlier.rows.iter().find(|e| e.category == r.category && e.name == r.name); + let row = match before { + Some(e) => Row { + count: r.count.saturating_sub(e.count), + total: r.total.saturating_sub(e.total), + self_time: r.self_time.saturating_sub(e.self_time), + ..*r + }, + None => *r, + }; + (row.count > 0).then_some(row) + }) + .collect(); + Report { + compiled: self.compiled, + enabled: self.enabled, + wall: self.wall.saturating_sub(earlier.wall), + rows, + events: self.events.saturating_sub(earlier.events), + dropped: self.dropped.saturating_sub(earlier.dropped), + } + } + + /// The report as a text table with the `top` rows of most self time (0: all of them). + pub fn table(&self, top: usize) -> String { + use std::fmt::Write as _; + let mut s = String::new(); + if !self.compiled { + s.push_str("profile: not compiled into this build (the `profile` feature is off)\n"); + return s; + } + let spans = self.events as u64 + self.dropped; + let _ = writeln!(s, "profile: {:.1} ms wall, {spans} spans ({} not kept for the trace)", ms(self.wall), self.dropped); + let all: f64 = self.rows.iter().map(|r| r.self_time.as_secs_f64()).sum(); + let parts: Vec = self + .by_category() + .into_iter() + .map(|(c, d)| { + let share = if all > 0.0 { d.as_secs_f64() / all * 100.0 } else { 0.0 }; + format!("{c} {:.1} ms ({share:.1}%)", ms(d)) + }) + .collect(); + let _ = writeln!(s, "self time by category: {}", if parts.is_empty() { "nothing recorded".to_string() } else { parts.join(", ") }); + let sorted = self.sorted(); + let n = if top == 0 { sorted.len() } else { top.min(sorted.len()) }; + let _ = writeln!(s, "{:>11} {:>11} {:>8} {:>10} span", "self ms", "total ms", "count", "max ms"); + for r in sorted.iter().take(n) { + let _ = writeln!(s, "{:>11.3} {:>11.3} {:>8} {:>10.3} {} {}", ms(r.self_time), ms(r.total), r.count, ms(r.max), r.category, r.name); + } + if n < sorted.len() { + let _ = writeln!(s, "({} more span names)", sorted.len() - n); + } + s + } +} + +/// A point in the recording to report from ([`Mark::report`]): an import's own share. +#[derive(Clone, Debug)] +pub struct Mark(Report); + +/// Mark the recording here. +pub fn mark() -> Mark { + Mark(report()) +} + +impl Mark { + /// What was recorded since the mark (all threads: work running beside it counts too). + pub fn report(&self) -> Report { + report().since(&self.0) + } +} + +/// A running span; it ends when dropped (also while a panic unwinds). +#[must_use = "a span measures until it is dropped"] +pub struct Span { + #[cfg(any(feature = "enabled", test))] + open: Option, +} + +impl Drop for Span { + #[inline] + fn drop(&mut self) { + #[cfg(any(feature = "enabled", test))] + if let Some(open) = self.open.take() { + imp::close(&open); + } + } +} + +/// Start a span `name` of `category` on this thread, when recording. +#[inline] +pub fn span(category: &'static str, name: &'static str) -> Span { + #[cfg(any(feature = "enabled", test))] + { + Span { open: if enabled() { imp::open((category, name)) } else { None } } + } + #[cfg(not(any(feature = "enabled", test)))] + { + let _ = (category, name); + Span {} + } +} + +/// Run `f` as a span. +#[inline] +pub fn scope(category: &'static str, name: &'static str, f: impl FnOnce() -> T) -> T { + let _span = span(category, name); + f() +} + +/// Record a span that just ended after `took`, timed by someone else (SMLib's C API times its +/// own calls): a child of the span running on this thread. +#[inline] +pub fn record(category: &'static str, name: &'static str, took: Duration) { + #[cfg(any(feature = "enabled", test))] + if enabled() { + imp::record((category, name), u64::try_from(took.as_nanos()).unwrap_or(u64::MAX)); + } + #[cfg(not(any(feature = "enabled", test)))] + let _ = (category, name, took); +} + +/// `name` as a name a span can take, kept for the rest of the run (at most [`MAX_NAMES`] +/// distinct ones; after that [`OTHER`]). For names only known at run time, such as SMLib's C +/// function names; spans named in code use literals. +pub fn intern(name: &str) -> &'static str { + #[cfg(any(feature = "enabled", test))] + { + imp::intern(name) + } + #[cfg(not(any(feature = "enabled", test)))] + { + let _ = name; + OTHER + } +} + +/// Is the profiler recording? +#[inline] +pub fn enabled() -> bool { + #[cfg(any(feature = "enabled", test))] + { + imp::ON.load(std::sync::atomic::Ordering::Relaxed) + } + #[cfg(not(any(feature = "enabled", test)))] + { + false + } +} + +/// Start or stop recording (nothing happens when the profiler is not compiled in). What was +/// recorded stays until [`reset`]. +pub fn set_enabled(on: bool) { + #[cfg(any(feature = "enabled", test))] + imp::set_enabled(on); + #[cfg(not(any(feature = "enabled", test)))] + let _ = on; +} + +/// Forget what was recorded; the wall time starts again now. +pub fn reset() { + #[cfg(any(feature = "enabled", test))] + imp::reset(); +} + +/// What was recorded since the last reset. +pub fn report() -> Report { + #[cfg(any(feature = "enabled", test))] + { + imp::report() + } + #[cfg(not(any(feature = "enabled", test)))] + { + Report::default() + } +} + +/// Write the kept spans as a Chrome trace-event file (JSON object format: complete events, one +/// track per thread), for chrome://tracing or Perfetto. +pub fn write_chrome_trace(w: &mut dyn std::io::Write) -> std::io::Result<()> { + #[cfg(any(feature = "enabled", test))] + { + imp::write_chrome_trace(w) + } + #[cfg(not(any(feature = "enabled", test)))] + { + w.write_all(br#"{"displayTimeUnit":"ms","traceEvents":[]}"#) + } +} + +#[cfg(any(feature = "enabled", test))] +mod imp { + use std::cell::{Cell, RefCell}; + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{LazyLock, Mutex, MutexGuard, OnceLock, PoisonError}; + use std::time::Duration; + + use serde_json::json; + use web_time::Instant; + + use super::{MAX_EVENTS, MAX_NAMES, OTHER, Report, Row}; + + pub(super) static ON: AtomicBool = AtomicBool::new(false); + + type Key = (&'static str, &'static str); + + /// Deeper spans on one thread are not recorded (a runaway recursion stays bounded). + const MAX_DEPTH: usize = 512; + /// Threads named in the trace. + const MAX_THREADS: usize = 4096; + + #[derive(Clone, Copy, Default)] + struct Agg { + count: u64, + total_ns: u64, + self_ns: u64, + max_ns: u64, + } + + #[derive(Clone, Copy)] + struct Event { + key: Key, + tid: u32, + start_ns: u64, + dur_ns: u64, + } + + #[derive(Default)] + struct Global { + agg: HashMap, + events: Vec, + dropped: u64, + threads: Vec<(u32, String)>, + next_tid: u32, + since_ns: u64, + } + + static GLOBAL: LazyLock> = LazyLock::new(|| Mutex::new(Global::default())); + static NAMES: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); + + fn global() -> MutexGuard<'static, Global> { + // A panic while the lock was held leaves plain data behind: keep using it. + GLOBAL.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn epoch() -> Instant { + static EPOCH: OnceLock = OnceLock::new(); + *EPOCH.get_or_init(Instant::now) + } + + fn now_ns() -> u64 { + u64::try_from(epoch().elapsed().as_nanos()).unwrap_or(u64::MAX) + } + + struct Frame { + key: Key, + child_ns: u64, + } + + thread_local! { + static STACK: RefCell> = const { RefCell::new(Vec::new()) }; + /// This thread's number in the trace (0: not given one yet). + static TID: Cell = const { Cell::new(0) }; + } + + pub(super) struct Open { + key: Key, + start_ns: u64, + depth: usize, + } + + pub(super) fn open(key: Key) -> Option { + let depth = STACK + .try_with(|s| { + let mut s = s.try_borrow_mut().ok()?; + if s.len() >= MAX_DEPTH { + return None; + } + s.push(Frame { key, child_ns: 0 }); + Some(s.len() - 1) + }) + .ok() + .flatten()?; + Some(Open { key, start_ns: now_ns(), depth }) + } + + pub(super) fn close(o: &Open) { + let dur = now_ns().saturating_sub(o.start_ns); + let (child, outermost) = STACK + .try_with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return (0, true) }; + let child = s.get(o.depth).map_or(0, |f| f.child_ns); + // Spans opened inside this one and not closed yet (leaked) end with it. + s.truncate(o.depth); + let outermost = !s.iter().any(|f| f.key == o.key); + if let Some(parent) = s.last_mut() { + parent.child_ns = parent.child_ns.saturating_add(dur); + } + (child, outermost) + }) + .unwrap_or((0, true)); + add(o.key, o.start_ns, dur, dur.saturating_sub(child), outermost); + } + + pub(super) fn record(key: Key, dur: u64) { + let start = now_ns().saturating_sub(dur); + let outermost = STACK + .try_with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return true }; + let outermost = !s.iter().any(|f| f.key == key); + if let Some(parent) = s.last_mut() { + parent.child_ns = parent.child_ns.saturating_add(dur); + } + outermost + }) + .unwrap_or(true); + add(key, start, dur, dur, outermost); + } + + fn thread_id(g: &mut Global) -> u32 { + TID.try_with(|t| { + if t.get() == 0 { + g.next_tid = g.next_tid.saturating_add(1); + t.set(g.next_tid); + if g.threads.len() < MAX_THREADS { + g.threads.push((g.next_tid, thread_name(g.next_tid))); + } + } + t.get() + }) + .unwrap_or(0) + } + + #[cfg(not(target_arch = "wasm32"))] + fn thread_name(tid: u32) -> String { + std::thread::current().name().map_or_else(|| format!("thread {tid}"), str::to_string) + } + + #[cfg(target_arch = "wasm32")] + fn thread_name(_: u32) -> String { + "main".into() + } + + fn add(key: Key, start_ns: u64, dur_ns: u64, self_ns: u64, outermost: bool) { + let mut g = global(); + let tid = thread_id(&mut g); + let a = g.agg.entry(key).or_default(); + a.count = a.count.saturating_add(1); + if outermost { + a.total_ns = a.total_ns.saturating_add(dur_ns); + } + a.self_ns = a.self_ns.saturating_add(self_ns); + a.max_ns = a.max_ns.max(dur_ns); + if g.events.len() < MAX_EVENTS { + g.events.push(Event { key, tid, start_ns, dur_ns }); + } else { + g.dropped = g.dropped.saturating_add(1); + } + } + + pub(super) fn intern(name: &str) -> &'static str { + let mut names = NAMES.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(n) = names.get(name) { + return n; + } + if names.len() >= MAX_NAMES { + return OTHER; + } + let kept: &'static str = Box::leak(name.to_string().into_boxed_str()); + names.insert(name.to_string(), kept); + kept + } + + pub(super) fn set_enabled(on: bool) { + let was = ON.swap(on, Ordering::Relaxed); + if on && !was { + let now = now_ns(); + let mut g = global(); + // The wall time starts with the first recording. + if g.agg.is_empty() { + g.since_ns = now; + } + } + } + + pub(super) fn reset() { + let now = now_ns(); + let mut g = global(); + g.agg.clear(); + g.events = Vec::new(); + g.dropped = 0; + g.since_ns = now; + } + + pub(super) fn report() -> Report { + let now = now_ns(); + let g = global(); + let d = Duration::from_nanos; + let rows = g + .agg + .iter() + .map(|(k, a)| Row { category: k.0, name: k.1, count: a.count, total: d(a.total_ns), self_time: d(a.self_ns), max: d(a.max_ns) }) + .collect(); + Report { + compiled: true, + enabled: ON.load(Ordering::Relaxed), + wall: d(now.saturating_sub(g.since_ns)), + rows, + events: g.events.len(), + dropped: g.dropped, + } + } + + pub(super) fn write_chrome_trace(w: &mut dyn std::io::Write) -> std::io::Result<()> { + // Copied out, so spans closing on other threads don't wait for the file. + let (events, threads, dropped) = { + let g = global(); + (g.events.clone(), g.threads.clone(), g.dropped) + }; + let us = |ns: u64| ns as f64 / 1000.0; + write!(w, "{{\"displayTimeUnit\":\"ms\",\"otherData\":{{\"dropped\":{dropped}}},\"traceEvents\":[")?; + let mut first = true; + let mut sep = |w: &mut dyn std::io::Write| -> std::io::Result<()> { + if !first { + w.write_all(b",\n")?; + } + first = false; + Ok(()) + }; + sep(w)?; + serde_json::to_writer(&mut *w, &json!({"ph": "M", "name": "process_name", "pid": 1, "tid": 0, "args": {"name": "SolidCraft"}}))?; + for (tid, name) in &threads { + sep(w)?; + serde_json::to_writer(&mut *w, &json!({"ph": "M", "name": "thread_name", "pid": 1, "tid": tid, "args": {"name": name}}))?; + } + for e in &events { + sep(w)?; + serde_json::to_writer( + &mut *w, + &json!({"ph": "X", "cat": e.key.0, "name": e.key.1, "pid": 1, "tid": e.tid, "ts": us(e.start_ns), "dur": us(e.dur_ns)}), + )?; + } + w.write_all(b"]}\n") + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/profile/src/tests.rs b/crates/profile/src/tests.rs new file mode 100644 index 000000000..f6766e25a --- /dev/null +++ b/crates/profile/src/tests.rs @@ -0,0 +1,155 @@ +use super::*; + +/// The profiler is global: tests that switch it on and off run one at a time. +static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn serial() -> std::sync::MutexGuard<'static, ()> { + SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +fn spin(ms: u64) { + let t = web_time::Instant::now(); + while t.elapsed() < Duration::from_millis(ms) {} +} + +fn row(r: &Report, name: &str) -> Row { + r.rows.iter().find(|x| x.name == name).copied().unwrap_or_else(|| panic!("no row {name}: {r:?}")) +} + +#[test] +fn nothing_is_recorded_while_off() { + let _s = serial(); + set_enabled(false); + reset(); + { + let _a = span("test", "off"); + spin(1); + } + record("test", "off_record", Duration::from_millis(3)); + assert!(report().rows.is_empty()); +} + +#[test] +fn nested_spans_have_self_and_total_time() { + let _s = serial(); + reset(); + set_enabled(true); + { + let _outer = span("test", "outer"); + spin(4); + { + let _inner = span("test", "inner"); + spin(4); + } + // Timed by someone else: a child of `outer`. + record("external", "call", Duration::from_millis(2)); + } + set_enabled(false); + let r = report(); + let (outer, inner, call) = (row(&r, "outer"), row(&r, "inner"), row(&r, "call")); + assert_eq!((outer.count, inner.count, call.count), (1, 1, 1)); + assert!(outer.total >= Duration::from_millis(8), "{outer:?}"); + assert!(inner.self_time >= Duration::from_millis(4), "{inner:?}"); + assert_eq!(call.self_time, Duration::from_millis(2)); + // The outer span's self time leaves out both children. + assert_eq!(outer.self_time, outer.total - inner.total - call.total, "{r:?}"); + assert_eq!(r.events, 3); + let cats = r.by_category(); + assert_eq!(cats.iter().map(|c| c.0).collect::>().len(), 2); + let t = r.table(10); + assert!(t.contains("test outer") && t.contains("external call") && t.contains("self time by category"), "{t}"); +} + +#[test] +fn a_span_inside_one_of_the_same_name_counts_once_in_the_total() { + let _s = serial(); + reset(); + set_enabled(true); + { + let _a = span("command", "x"); + spin(2); + let _b = span("command", "x"); + spin(2); + } + set_enabled(false); + let x = row(&report(), "x"); + assert_eq!(x.count, 2); + assert!(x.total >= x.max && x.total <= x.max + Duration::from_micros(1), "only the outer one: {x:?}"); +} + +#[test] +fn a_mark_reports_only_what_came_after_it() { + let _s = serial(); + reset(); + set_enabled(true); + drop(span("test", "before")); + let m = mark(); + drop(span("test", "after")); + drop(span("test", "after")); + set_enabled(false); + let r = m.report(); + assert_eq!(r.rows.len(), 1, "{r:?}"); + assert_eq!(row(&r, "after").count, 2); +} + +#[test] +fn spans_on_other_threads_get_their_own_track() { + let _s = serial(); + reset(); + set_enabled(true); + let _main = span("test", "main"); + std::thread::Builder::new().name("worker".into()).spawn(|| drop(span("test", "on_worker"))).unwrap().join().unwrap(); + drop(_main); + set_enabled(false); + let mut out = Vec::new(); + write_chrome_trace(&mut out).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&out).unwrap(); + let events = v["traceEvents"].as_array().unwrap(); + let tid = |name: &str| events.iter().find(|e| e["name"] == name).map(|e| e["tid"].clone()).unwrap(); + assert_ne!(tid("main"), tid("on_worker")); + assert!(events.iter().any(|e| e["name"] == "thread_name" && e["args"]["name"] == "worker"), "{v}"); + let main = events.iter().find(|e| e["name"] == "main").unwrap(); + assert_eq!((main["ph"].as_str(), main["cat"].as_str()), (Some("X"), Some("test"))); + assert!(main["dur"].as_f64().is_some_and(|d| d >= 0.0)); +} + +#[test] +fn the_trace_is_capped_and_the_aggregate_is_not() { + let _s = serial(); + reset(); + set_enabled(true); + for _ in 0..MAX_EVENTS + 10 { + drop(span("test", "many")); + } + set_enabled(false); + let r = report(); + assert_eq!((r.events, r.dropped, row(&r, "many").count), (MAX_EVENTS, 10, MAX_EVENTS as u64 + 10)); + reset(); + assert_eq!(report().events, 0); +} + +#[test] +fn a_panic_inside_a_span_still_closes_it() { + let _s = serial(); + reset(); + set_enabled(true); + let _ = std::panic::catch_unwind(|| { + let _outer = span("test", "unwound"); + let _inner = span("test", "unwound_inner"); + std::panic::panic_any("kernel"); + }); + drop(span("test", "after_panic")); + set_enabled(false); + let r = report(); + assert_eq!(row(&r, "unwound").count, 1); + // The stack is clean again: the next span is a root, its total its own. + let after = row(&r, "after_panic"); + assert_eq!(after.total, after.self_time); +} + +#[test] +fn interned_names_are_kept_and_bounded() { + let a = intern("smlib_boolean"); + assert!(std::ptr::eq(a, intern("smlib_boolean"))); + assert_eq!(a, "smlib_boolean"); +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 56a544cd9..bb8d17aaa 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -13,12 +13,14 @@ default = [] raytrace-cpu = [] [dependencies] +solidcore-record = { workspace = true } solidcraft-geom = { workspace = true } serde = { workspace = true } image = { workspace = true, features = ["jpeg"] } moxcms = { workspace = true } png = { workspace = true } sha2 = { workspace = true } +web-time = { workspace = true } weezl = { workspace = true } [dev-dependencies] diff --git a/crates/render/examples/cpu_resource_smoke.rs b/crates/render/examples/cpu_resource_smoke.rs index 937585f72..0bff9d38a 100644 --- a/crates/render/examples/cpu_resource_smoke.rs +++ b/crates/render/examples/cpu_resource_smoke.rs @@ -1,7 +1,8 @@ //! Bounded native acceptance probe for explicit CPU profiles. This is not a speed //! benchmark or an application/UI test. Writes only to a new caller-selected folder. use serde_json::json; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use solidcraft_render::job::{CpuBudget, CpuHost, DirectionalLightOptions, ImageRequest, Integrator, JobId, JobOptions, Phase, RaytraceOptions}; use solidcraft_render::{Camera, ProductMesh, ProductScene, StandardView, surface::OpaqueSurface}; use std::{error::Error, fs, path::PathBuf, sync::Arc, time::Duration}; diff --git a/crates/render/examples/validate_starter.rs b/crates/render/examples/validate_starter.rs index c177e5bf8..7526755ff 100644 --- a/crates/render/examples/validate_starter.rs +++ b/crates/render/examples/validate_starter.rs @@ -6,7 +6,8 @@ use image::ImageDecoder; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use solidcraft_render::{ lighting::{DecodedHdr, HdrDecodeTask, HdrSource, HdrTaskPoll}, surface::unit_direction, diff --git a/crates/render/src/analysis.rs b/crates/render/src/analysis.rs index b4c49a7ba..d8cd1191a 100644 --- a/crates/render/src/analysis.rs +++ b/crates/render/src/analysis.rs @@ -1,6 +1,6 @@ //! Surface analysis as a view draws it: the shading mode and the colours it uses. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; /// Surface analysis colours, straight sRGB 0..1 as the shader takes them. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/render/src/anisotropic_surface.rs b/crates/render/src/anisotropic_surface.rs index 1b8746e1f..25dfb47c9 100644 --- a/crates/render/src/anisotropic_surface.rs +++ b/crates/render/src/anisotropic_surface.rs @@ -15,9 +15,10 @@ //! Consumers retain geometric normals for ray spawning and optical boundaries. //! No shading-normal energy correction, multiple scattering or transmission is modeled. +use solidcraft_geom::prelude::*; use std::f64::consts::{PI, TAU}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use crate::surface::{MIN_ROUGHNESS, OpaqueSurface, SurfaceError, unit_direction}; diff --git a/crates/render/src/camera.rs b/crates/render/src/camera.rs index f87407d48..0ba3aa5eb 100644 --- a/crates/render/src/camera.rs +++ b/crates/render/src/camera.rs @@ -1,5 +1,7 @@ use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Aabb3; +use solidcraft_geom::prelude::*; /// Column-major 4×4 matrix. #[derive(Clone, Copy, Debug, PartialEq)] @@ -502,6 +504,28 @@ impl Camera { let r = (b.diagonal() * 0.5).max(1.0); self.distance = if self.fov > 0.0 { r / (self.fov * 0.5).sin() * 1.1 } else { r / 0.4 * 1.15 }; } + /// [`Camera::fit`] for a picture of `aspect` (width over height). The fit frames the + /// bounding sphere by the picture's height; a picture taller than wide also needs it inside + /// the sides, so the camera moves back by the ratio (the orthographic width grows with the + /// distance; in perspective the sphere's angular radius shrinks with it, which the fit's + /// margin covers). A wide picture, or an aspect that is not a positive number, keeps the + /// plain fit. Returns false, leaving the camera alone, when there is nothing to fit or the + /// fitted camera would not be valid (a distance that overflows). + pub fn fit_aspect(&mut self, b: &Aabb3, aspect: f64) -> bool { + if b.is_empty() { + return false; + } + let mut fitted = *self; + fitted.fit(b); + if aspect.is_finite() && aspect > 0.0 && aspect < 1.0 { + fitted.distance /= aspect; + } + if !fitted.is_valid() { + return false; + } + *self = fitted; + true + } /// The same camera looking from direction `back` (target → eye). Straight up or down /// keeps the yaw, rounded to the nearest quarter turn so the view stays square. pub fn looking_from(&self, back: Vec3) -> Camera { @@ -863,6 +887,20 @@ mod tests { } } + /// A fit whose distance would overflow (a subnormal aspect, a huge product) is refused + /// and leaves the finite camera as it was. + #[test] + fn fit_aspect_refuses_an_overflowing_fit() { + let before = Camera { distance: 80.0, ..Default::default() }; + let small = Aabb3 { min: Vec3::ZERO, max: Vec3::new(40.0, 30.0, 20.0) }; + let huge = Aabb3 { min: Vec3::new(-1e307, -1e307, -1e307), max: Vec3::new(1e307, 1e307, 1e307) }; + for (b, aspect) in [(&small, 1e-320), (&huge, 1e-6)] { + let mut c = before; + assert!(!c.fit_aspect(b, aspect), "aspect {aspect}"); + assert_eq!(c, before); + } + } + #[test] fn fit_and_hostile() { let mut c = Camera::default(); diff --git a/crates/render/src/clear_coat.rs b/crates/render/src/clear_coat.rs index 4461d3d72..0d3929e15 100644 --- a/crates/render/src/clear_coat.rs +++ b/crates/render/src/clear_coat.rs @@ -3,7 +3,8 @@ //! and refraction of substrate directions are omitted. This is a bounded preview //! model, not a full layered random walk. See docs/render-clear-coat.md. use crate::surface::{MIN_ROUGHNESS, OpaqueSurface, SurfaceError, unit_direction}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use std::f64::consts::PI; #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/render/src/curve_display.rs b/crates/render/src/curve_display.rs index cd5a63cc9..31e754b21 100644 --- a/crates/render/src/curve_display.rs +++ b/crates/render/src/curve_display.rs @@ -1,12 +1,15 @@ //! Pixel-bounded display paths. CAD segments remain untouched; positive homogeneous //! control hulls bound perspective projection, including looping and rational curves. -use solidcraft_geom::{Plane, Seg2, Vec2, Vec3}; +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::prelude::*; use crate::Mat4; const MAX_VERTICES: usize = 4096; const MAX_DEPTH: u8 = 24; const PIXEL_ERROR: f64 = 0.5; +/// The vertices a new part has room for before it grows. +const PART_CAPACITY: usize = 8; #[derive(Clone, Copy, Debug, PartialEq)] pub struct PixelCurveView { @@ -54,20 +57,44 @@ fn mix(a: H, b: H, t: f64) -> H { std::array::from_fn(|i| a[i] * (1.0 - t) + b[i] * t) } -fn halves(c: &[H]) -> (Vec, Vec) { - let mut work = c.to_vec(); - let mut l = Vec::with_capacity(c.len()); - let mut r = Vec::with_capacity(c.len()); - while let (Some(a), Some(b)) = (work.first(), work.last()) { - l.push(*a); - r.push(*b); - if work.len() == 1 { - break; +/// The most control points of one span: a Bézier of the highest degree. +const MAX_CONTROLS: usize = solidcore_record::MAX_BEZIER_DEGREE + 1; + +/// One span's homogeneous control points, kept inline: the sampler splits and projects +/// thousands of them per curve and view, and a `Vec` each was most of its allocations. +#[derive(Clone, Copy)] +struct Hull { + len: usize, + p: [H; MAX_CONTROLS], +} + +impl Hull { + fn new(points: &[H]) -> Option { + let mut p = [[0.0; 4]; MAX_CONTROLS]; + p.get_mut(..points.len())?.copy_from_slice(points); + Some(Hull { len: points.len(), p }) + } + + fn points(&self) -> &[H] { + &self.p[..self.len] + } + + /// The two halves at t = 0.5 (de Casteljau), each level's midpoints worked out in place + /// with the same `mix` as one level at a time. + fn halves(&self) -> (Hull, Hull) { + let n = self.len; + let mut work = self.p; + let (mut l, mut r) = (Hull { len: n, p: [[0.0; 4]; MAX_CONTROLS] }, Hull { len: n, p: [[0.0; 4]; MAX_CONTROLS] }); + for level in 0..n { + let last = n - 1 - level; + l.p[level] = work[0]; + r.p[last] = work[last]; + for i in 0..last { + work[i] = mix(work[i], work[i + 1], 0.5); + } } - work = work.windows(2).map(|p| mix(p[0], p[1], 0.5)).collect(); + (l, r) } - r.reverse(); - (l, r) } fn world(h: H) -> Option { @@ -98,7 +125,7 @@ fn distance_segment(p: Vec2, a: Vec2, b: Vec2) -> f64 { p.dist(a + d * t) } -fn controls(segment: &Seg2, plane: &Plane) -> Option<(Vec>, H)> { +fn controls(segment: &Seg2, plane: &Plane) -> Option<(Vec, H)> { let mut terms: H = [0.0; 4]; let mut h = |p: Vec2, w: f64| { for (r, (o, x, y)) in [(plane.origin.x, plane.x.x, plane.y.x), (plane.origin.y, plane.x.y, plane.y.y), (plane.origin.z, plane.x.z, plane.y.z)] @@ -112,30 +139,34 @@ fn controls(segment: &Seg2, plane: &Plane) -> Option<(Vec>, H)> { [p.x * w, p.y * w, p.z * w, w] }; let spans = match *segment { - Seg2::Line { a, b } => vec![vec![h(a, 1.0), h(b, 1.0)]], - Seg2::Cubic { p0, p1, p2, p3 } => vec![vec![h(p0, 1.0), h(p1, 1.0), h(p2, 1.0), h(p3, 1.0)]], - Seg2::Conic { a, apex, b, w } if w > 0.0 => vec![vec![h(a, 1.0), h(apex, w), h(b, 1.0)]], - Seg2::Bezier { n, p } if (1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(&n) => { - vec![p[..=n as usize].iter().map(|p| h(*p, 1.0)).collect()] + Seg2::Line { a, b } => vec![Hull::new(&[h(a, 1.0), h(b, 1.0)])?], + Seg2::Cubic { p0, p1, p2, p3 } => vec![Hull::new(&[h(p0, 1.0), h(p1, 1.0), h(p2, 1.0), h(p3, 1.0)])?], + Seg2::Conic { a, apex, b, w } if w > 0.0 => vec![Hull::new(&[h(a, 1.0), h(apex, w), h(b, 1.0)])?], + Seg2::Bezier { n, p } if (1..=solidcore_record::MAX_BEZIER_DEGREE as u8).contains(&n) => { + let mut hull = Hull { len: n as usize + 1, p: [[0.0; 4]; MAX_CONTROLS] }; + for (out, p) in hull.p.iter_mut().zip(&p[..=n as usize]) { + *out = h(*p, 1.0); + } + vec![hull] } Seg2::Arc { center, radius, start, sweep } if radius > 0.0 && start.is_finite() && sweep.is_finite() && sweep.abs() <= std::f64::consts::TAU + 1e-9 => { let count = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize; - (0..count) - .map(|i| { - let a = start + sweep * i as f64 / count as f64; - let b = start + sweep * (i + 1) as f64 / count as f64; - let mid = (a + b) * 0.5; - let w = ((b - a) * 0.5).cos(); - let p = |t: f64, r: f64| center + Vec2::new(t.cos(), t.sin()) * r; - vec![h(p(a, radius), 1.0), h(p(mid, radius / w), w), h(p(b, radius), 1.0)] - }) - .collect() + let mut spans = Vec::with_capacity(count); + for i in 0..count { + let a = start + sweep * i as f64 / count as f64; + let b = start + sweep * (i + 1) as f64 / count as f64; + let mid = (a + b) * 0.5; + let w = ((b - a) * 0.5).cos(); + let p = |t: f64, r: f64| center + Vec2::new(t.cos(), t.sin()) * r; + spans.push(Hull::new(&[h(p(a, radius), 1.0), h(p(mid, radius / w), w), h(p(b, radius), 1.0)])?); + } + spans } _ => return None, }; - spans.iter().flatten().all(|p| p.iter().all(|x| x.is_finite()) && p[3] > 0.0).then_some((spans, terms)) + spans.iter().flat_map(Hull::points).all(|p| p.iter().all(|x| x.is_finite()) && p[3] > 0.0).then_some((spans, terms)) } /// Samples one exact segment to a conservative 0.5 physical-pixel control-hull @@ -168,29 +199,41 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam out.quality = SamplingQuality::Invalid; return out; }; - let mut stack: Vec<_> = spans - .into_iter() - .rev() - .map(|c| { - let magnitude: H = std::array::from_fn(|i| c.iter().map(|p| p[i].abs()).fold(source_terms[i], f64::max)); - let terms: H = std::array::from_fn(|r| (0..4).map(|i| view.vp.0[i][r].abs() * magnitude[i]).sum()); - (c, 0u8, terms) - }) - .collect(); + // Depth first: the spans not yet started, and one right half per level below. + let mut stack = Vec::with_capacity(spans.len() + usize::from(MAX_DEPTH) + 1); + for hull in spans.into_iter().rev() { + let c = hull.points(); + let magnitude: H = std::array::from_fn(|i| c.iter().map(|p| p[i].abs()).fold(source_terms[i], f64::max)); + let terms: H = std::array::from_fn(|r| (0..4).map(|i| view.vp.0[i][r].abs() * magnitude[i]).sum()); + stack.push((hull, 0u8, terms)); + } let mut connected = false; let mut nodes = 0usize; - while let Some((c, depth, terms)) = stack.pop() { + // Each point's projection and clip distances, worked out once per node (they were + // recomputed for every clip plane a test looked at). + let mut q: [H; MAX_CONTROLS] = [[0.0; 4]; MAX_CONTROLS]; + let mut dist = [[0.0; 7]; MAX_CONTROLS]; + while let Some((hull, depth, terms)) = stack.pop() { if budget.remaining_nodes == 0 || nodes == 32_768 { out.quality = SamplingQuality::BudgetLimited; break; } budget.remaining_nodes -= 1; nodes += 1; - let q: Vec = c.iter().map(|h| project_h(view.vp, *h)).collect(); + let c = hull.points(); + let n = c.len(); + for (q, h) in q.iter_mut().zip(c) { + *q = project_h(view.vp, *h); + } + let q = &q[..n]; if q.iter().flatten().any(|x| !x.is_finite()) { out.quality = SamplingQuality::Invalid; break; } + for (d, p) in dist.iter_mut().zip(q) { + *d = distances(*p, view, clip_xy); + } + let dist = &dist[..n]; let e: H = terms.map(|t| t * f64::EPSILON * (f64::from(depth) + 4.0) * 64.0); let clip_error = [ e[0] + e[3] * (1.0 + 2.0 / view.width_px), @@ -201,33 +244,61 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam e[2] + e[3], e[3], ]; - if (0..7).any(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] < -clip_error[i])) { + if (0..7).any(|i| dist.iter().all(|d| d[i] < -clip_error[i])) { connected = false; continue; } let positive = q.iter().all(|p| p[3] > 1e-12); - let depth_safe = c.len() == 2 || (4..7).all(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] >= 0.0)); + let depth_safe = n == 2 || (4..7).all(|i| dist.iter().all(|d| d[i] >= 0.0)); let flat = positive && q.first().zip(q.last()).is_some_and(|(a, b)| { let (a, b) = (screen(*a, view), screen(*b, view)); - let magnitude = q.iter().map(|p| screen(*p, view).len()).fold(1.0, f64::max); + let mut on_screen = [Vec2::ZERO; MAX_CONTROLS]; + for (s, p) in on_screen.iter_mut().zip(q) { + *s = screen(*p, view); + } + let on_screen = &on_screen[..n]; + let mut off_chord = [0.0; MAX_CONTROLS]; + for (d, s) in off_chord.iter_mut().zip(on_screen) { + *d = distance_segment(*s, a, b); + } + let off_chord = &off_chord[..n]; + // The allowance below is never negative (nor NaN), so a point already more than + // the bound off the chord fails the test whatever it is: most nodes the sampler + // visits are split, and this skips their roundoff estimate. + if off_chord.iter().any(|d| *d > PIXEL_ERROR) { + return false; + } + let magnitude = on_screen.iter().map(|s| s.len()).fold(1.0, f64::max); // Keep floating-point roundoff inside the advertised bound. // Absolute summands also cover cancellation in VP multiplication. // Subdivision propagates roundoff from the original homogeneous hull. - let projection_error = q - .iter() - .map(|p| { - let safe_w = p[3] - e[3]; - if safe_w <= 0.0 { - return f64::INFINITY; - } - let x = (e[0] + (p[0] / p[3]).abs() * e[3]) / safe_w * view.width_px * 0.5; - let y = (e[1] + (p[1] / p[3]).abs() * e[3]) / safe_w * view.height_px * 0.5; - x.hypot(y) - }) - .fold(0.0, f64::max); - let allowance = projection_error + magnitude * f64::EPSILON * 128.0; - allowance < PIXEL_ERROR && q.iter().all(|p| distance_segment(screen(*p, view), a, b) + allowance <= PIXEL_ERROR) + let mut roundoff = [(0.0, 0.0); MAX_CONTROLS]; + for (r, p) in roundoff.iter_mut().zip(q) { + let safe_w = p[3] - e[3]; + if safe_w <= 0.0 { + // An infinite allowance: never flat. + return false; + } + let x = (e[0] + (p[0] / p[3]).abs() * e[3]) / safe_w * view.width_px * 0.5; + let y = (e[1] + (p[1] / p[3]).abs() * e[3]) / safe_w * view.height_px * 0.5; + *r = (x, y); + } + let roundoff = &roundoff[..n]; + let margin = magnitude * f64::EPSILON * 128.0; + // |x| + |y| is never less than hypot(x, y), and twice it leaves far more room + // than the rounding of either. Rounding keeps sums in order, so when the test + // passes with this larger allowance it passes with the exact one too: the + // costly `hypot`s are only needed for nodes near the bound. + if roundoff.iter().all(|(x, y)| x.is_finite() && y.is_finite()) { + let upper = roundoff.iter().map(|(x, y)| (x.abs() + y.abs()) * 2.0).fold(0.0, f64::max) + margin; + if upper.is_finite() && upper < PIXEL_ERROR && off_chord.iter().all(|d| d + upper <= PIXEL_ERROR) { + return true; + } + } + let projection_error = roundoff.iter().map(|(x, y)| x.hypot(*y)).fold(0.0, f64::max); + let allowance = projection_error + margin; + allowance < PIXEL_ERROR && off_chord.iter().all(|d| d + allowance <= PIXEL_ERROR) }); if !flat || !depth_safe { if depth == MAX_DEPTH || out.vertex_count >= MAX_VERTICES { @@ -235,15 +306,15 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam connected = false; continue; } - let (l, r) = halves(&c); + let (l, r) = hull.halves(); stack.push((r, depth + 1, terms)); stack.push((l, depth + 1, terms)); continue; } - let (Some(a), Some(b), Some(qa), Some(qb)) = (c.first(), c.last(), q.first(), q.last()) else { continue }; + let (Some(a), Some(b), Some(da), Some(db)) = (c.first(), c.last(), dist.first(), dist.last()) else { continue }; let mut lo: f64 = 0.0; let mut hi: f64 = 1.0; - for (a, b) in distances(*qa, view, clip_xy).into_iter().zip(distances(*qb, view, clip_xy)) { + for (a, b) in da.iter().copied().zip(db.iter().copied()) { if a < 0.0 && b < 0.0 { hi = -1.0; break; @@ -276,7 +347,11 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam part.push(b); } } else { - out.parts.push(vec![a, b]); + // Room for a few chords: most visible pieces take several, and growing from two + // reallocated each part twice. + let mut part = Vec::with_capacity(PART_CAPACITY); + part.extend([a, b]); + out.parts.push(part); } connected = hi == 1.0; } diff --git a/crates/render/src/curve_display_tests.rs b/crates/render/src/curve_display_tests.rs index 8aa62e692..4ca741f28 100644 --- a/crates/render/src/curve_display_tests.rs +++ b/crates/render/src/curve_display_tests.rs @@ -27,7 +27,7 @@ fn dense_error(s: &Seg2, plane: &Plane, v: &PixelCurveView, path: &SampledPath) #[test] fn exact_arcs_ellipses_rational_and_looping_control_hulls_bound_pixels() { - let mut degree7 = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL]; + let mut degree7 = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; for (i, p) in degree7.iter_mut().enumerate() { *p = Vec2::new(i as f64 / 4.0 - 0.875, if i % 2 == 0 { -0.8 } else { 0.8 }); } @@ -119,3 +119,308 @@ fn invalid_weights_matrices_and_shared_frame_exhaustion_are_explicit() { assert_eq!(path.quality, SamplingQuality::BudgetLimited); assert!(path.vertex_count <= 16); } + +// The sampler as it was before its control points were kept inline and each point's +// projection and clip distances were worked out once per node, kept to compare against. +fn reference_controls(segment: &Seg2, plane: &Plane) -> Option<(Vec>, H)> { + let mut terms: H = [0.0; 4]; + let mut h = |p: Vec2, w: f64| { + for (r, (o, x, y)) in [(plane.origin.x, plane.x.x, plane.y.x), (plane.origin.y, plane.x.y, plane.y.y), (plane.origin.z, plane.x.z, plane.y.z)] + .into_iter() + .enumerate() + { + terms[r] = terms[r].max((o.abs() + x.abs() * p.x.abs() + y.abs() * p.y.abs()) * w.abs()); + } + terms[3] = terms[3].max(w.abs()); + let p = plane.to_world(p); + [p.x * w, p.y * w, p.z * w, w] + }; + let spans = match *segment { + Seg2::Line { a, b } => vec![vec![h(a, 1.0), h(b, 1.0)]], + Seg2::Cubic { p0, p1, p2, p3 } => vec![vec![h(p0, 1.0), h(p1, 1.0), h(p2, 1.0), h(p3, 1.0)]], + Seg2::Conic { a, apex, b, w } if w > 0.0 => vec![vec![h(a, 1.0), h(apex, w), h(b, 1.0)]], + Seg2::Bezier { n, p } if (1..=solidcore_record::MAX_BEZIER_DEGREE as u8).contains(&n) => { + vec![p[..=n as usize].iter().map(|p| h(*p, 1.0)).collect()] + } + Seg2::Arc { center, radius, start, sweep } + if radius > 0.0 && start.is_finite() && sweep.is_finite() && sweep.abs() <= std::f64::consts::TAU + 1e-9 => + { + let count = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize; + (0..count) + .map(|i| { + let a = start + sweep * i as f64 / count as f64; + let b = start + sweep * (i + 1) as f64 / count as f64; + let mid = (a + b) * 0.5; + let w = ((b - a) * 0.5).cos(); + let p = |t: f64, r: f64| center + Vec2::new(t.cos(), t.sin()) * r; + vec![h(p(a, radius), 1.0), h(p(mid, radius / w), w), h(p(b, radius), 1.0)] + }) + .collect() + } + _ => return None, + }; + spans.iter().flatten().all(|p| p.iter().all(|x| x.is_finite()) && p[3] > 0.0).then_some((spans, terms)) +} + +fn reference_halves(c: &[H]) -> (Vec, Vec) { + let mut work = c.to_vec(); + let mut l = Vec::with_capacity(c.len()); + let mut r = Vec::with_capacity(c.len()); + while let (Some(a), Some(b)) = (work.first(), work.last()) { + l.push(*a); + r.push(*b); + if work.len() == 1 { + break; + } + work = work.windows(2).map(|p| mix(p[0], p[1], 0.5)).collect(); + } + r.reverse(); + (l, r) +} + +fn reference_sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut SamplingBudget, clip_xy: bool) -> SampledPath { + let mut out = SampledPath { parts: Vec::new(), quality: SamplingQuality::Complete, vertex_count: 0 }; + if !view.width_px.is_finite() + || !view.height_px.is_finite() + || view.width_px <= 0.0 + || view.height_px <= 0.0 + || view.width_px > 1e7 + || view.height_px > 1e7 + || view.vp.0.iter().flatten().any(|x| !x.is_finite()) + { + out.quality = SamplingQuality::Invalid; + return out; + } + let Some((spans, source_terms)) = reference_controls(segment, plane) else { + out.quality = SamplingQuality::Invalid; + return out; + }; + let mut stack: Vec<_> = spans + .into_iter() + .rev() + .map(|c| { + let magnitude: H = std::array::from_fn(|i| c.iter().map(|p| p[i].abs()).fold(source_terms[i], f64::max)); + let terms: H = std::array::from_fn(|r| (0..4).map(|i| view.vp.0[i][r].abs() * magnitude[i]).sum()); + (c, 0u8, terms) + }) + .collect(); + let mut connected = false; + let mut nodes = 0usize; + while let Some((c, depth, terms)) = stack.pop() { + if budget.remaining_nodes == 0 || nodes == 32_768 { + out.quality = SamplingQuality::BudgetLimited; + break; + } + budget.remaining_nodes -= 1; + nodes += 1; + let q: Vec = c.iter().map(|h| project_h(view.vp, *h)).collect(); + if q.iter().flatten().any(|x| !x.is_finite()) { + out.quality = SamplingQuality::Invalid; + break; + } + let e: H = terms.map(|t| t * f64::EPSILON * (f64::from(depth) + 4.0) * 64.0); + let clip_error = [ + e[0] + e[3] * (1.0 + 2.0 / view.width_px), + e[0] + e[3] * (1.0 + 2.0 / view.width_px), + e[1] + e[3] * (1.0 + 2.0 / view.height_px), + e[1] + e[3] * (1.0 + 2.0 / view.height_px), + e[2], + e[2] + e[3], + e[3], + ]; + if (0..7).any(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] < -clip_error[i])) { + connected = false; + continue; + } + let positive = q.iter().all(|p| p[3] > 1e-12); + let depth_safe = c.len() == 2 || (4..7).all(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] >= 0.0)); + let flat = positive + && q.first().zip(q.last()).is_some_and(|(a, b)| { + let (a, b) = (screen(*a, view), screen(*b, view)); + let magnitude = q.iter().map(|p| screen(*p, view).len()).fold(1.0, f64::max); + // Keep floating-point roundoff inside the advertised bound. + // Absolute summands also cover cancellation in VP multiplication. + // Subdivision propagates roundoff from the original homogeneous hull. + let projection_error = q + .iter() + .map(|p| { + let safe_w = p[3] - e[3]; + if safe_w <= 0.0 { + return f64::INFINITY; + } + let x = (e[0] + (p[0] / p[3]).abs() * e[3]) / safe_w * view.width_px * 0.5; + let y = (e[1] + (p[1] / p[3]).abs() * e[3]) / safe_w * view.height_px * 0.5; + x.hypot(y) + }) + .fold(0.0, f64::max); + let allowance = projection_error + magnitude * f64::EPSILON * 128.0; + allowance < PIXEL_ERROR && q.iter().all(|p| distance_segment(screen(*p, view), a, b) + allowance <= PIXEL_ERROR) + }); + if !flat || !depth_safe { + if depth == MAX_DEPTH || out.vertex_count >= MAX_VERTICES { + out.quality = SamplingQuality::BudgetLimited; + connected = false; + continue; + } + let (l, r) = reference_halves(&c); + stack.push((r, depth + 1, terms)); + stack.push((l, depth + 1, terms)); + continue; + } + let (Some(a), Some(b), Some(qa), Some(qb)) = (c.first(), c.last(), q.first(), q.last()) else { continue }; + let mut lo: f64 = 0.0; + let mut hi: f64 = 1.0; + for (a, b) in distances(*qa, view, clip_xy).into_iter().zip(distances(*qb, view, clip_xy)) { + if a < 0.0 && b < 0.0 { + hi = -1.0; + break; + } + if a < 0.0 { + lo = lo.max(a / (a - b)); + } else if b < 0.0 { + hi = hi.min(a / (a - b)); + } + } + if lo > hi { + connected = false; + continue; + } + let (Some(a), Some(b)) = (world(mix(*a, *b, lo)), world(mix(*a, *b, hi))) else { + out.quality = SamplingQuality::Invalid; + break; + }; + // Exact consecutive subdivision endpoints share their homogeneous value. + let join = connected && lo == 0.0 && out.parts.last().and_then(|p| p.last()).is_some_and(|p| *p == a); + let need = if join { 1 } else { 2 }; + if need > budget.remaining_vertices || out.vertex_count + need > MAX_VERTICES { + out.quality = SamplingQuality::BudgetLimited; + break; + } + budget.remaining_vertices -= need; + out.vertex_count += need; + if join { + if let Some(part) = out.parts.last_mut() { + part.push(b); + } + } else { + out.parts.push(vec![a, b]); + } + connected = hi == 1.0; + } + out +} + +fn same_path(a: &SampledPath, b: &SampledPath) -> bool { + let bits = |p: &SampledPath| -> Vec> { + p.parts.iter().map(|part| part.iter().map(|v| [v.x, v.y, v.z].map(f64::to_bits)).collect()).collect() + }; + a.quality == b.quality && a.vertex_count == b.vertex_count && bits(a) == bits(b) +} + +/// The sampler gives the very same points, bit for bit, as before it was made quicker: every +/// kind of segment, on planes at a slant and far off, in orthographic and perspective views +/// zoomed from far out to far in, cut by the view's edges and the near plane, clipped and +/// unclipped, with ample and with nearly spent budgets. +#[test] +fn samples_the_same_points_bit_for_bit_as_the_reference() { + let mut degree9 = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; + for (i, p) in degree9.iter_mut().enumerate().take(10) { + let t = i as f64 / 9.0; + *p = Vec2::new(t * 2.0 - 1.0, ((i % 3) as f64 - 1.0) * 0.8); + } + let segments = [ + Seg2::Line { a: Vec2::new(-0.7, -0.3), b: Vec2::new(0.9, 0.4) }, + Seg2::Line { a: Vec2::new(-50.0, 0.1), b: Vec2::new(50.0, 0.2) }, + Seg2::Cubic { p0: Vec2::new(-0.9, 0.0), p1: Vec2::new(0.9, 1.0), p2: Vec2::new(-0.9, -1.0), p3: Vec2::new(0.9, 0.0) }, + Seg2::Cubic { p0: Vec2::new(0.0, 0.0), p1: Vec2::new(1.0, 1.0), p2: Vec2::new(0.0, 1.0), p3: Vec2::new(1.0, 0.0) }, + Seg2::Conic { a: Vec2::new(-0.5, 0.0), apex: Vec2::new(0.0, 0.6), b: Vec2::new(0.5, 0.0), w: 0.3 }, + Seg2::Conic { a: Vec2::new(-0.5, 0.0), apex: Vec2::new(0.0, 0.6), b: Vec2::new(0.5, 0.0), w: 4.0 }, + Seg2::Bezier { n: 9, p: degree9 }, + Seg2::Bezier { n: 4, p: degree9 }, + Seg2::Arc { center: Vec2::ZERO, radius: 0.4, start: 0.3, sweep: std::f64::consts::TAU }, + Seg2::Arc { center: Vec2::new(0.2, -0.1), radius: 3.0, start: -1.0, sweep: -2.5 }, + Seg2::Arc { center: Vec2::ZERO, radius: 0.2, start: std::f64::consts::PI, sweep: 0.001 }, + ]; + let planes = [ + plane(), + Plane::new(Vec3::new(0.0, 0.0, -2.0), Vec3::new(0.8, 0.0, 0.6), Vec3::Y).unwrap(), + Plane::new(Vec3::new(0.0, 0.0, -0.15), Vec3::new(0.6, 0.0, 0.8), Vec3::Y).unwrap(), + Plane::new(Vec3::new(1e6, -3e5, 2.0), Vec3::new(0.0, 0.6, 0.8), Vec3::new(1.0, 0.0, 0.0)).unwrap(), + ]; + let perspective = |s: f64| PixelCurveView { + vp: Mat4([[s, 0.0, 0.0, 0.0], [0.0, s, 0.0, 0.0], [0.0, 0.0, -1.01, -1.0], [0.0, 0.0, -0.101, 0.0]]), + width_px: 900.0, + height_px: 720.0, + }; + let mut far = view(0.2, 1.0); + far.vp.0[3][0] = -2e5; + let views = [ + view(0.003, 1.0), + view(0.31, 1.0), + view(3.0, 2.0), + view(400.0, 1.25), + view(1e9, 1.0), + far, + perspective(1.0), + perspective(7.5), + perspective(0.05), + ]; + let mut compared = 0; + for segment in &segments { + for plane in &planes { + for view in &views { + for clip in [true, false] { + for (vertices, nodes) in [(200_000, 400_000), (40, 1_000), (7, 9)] { + let (mut a, mut b) = (SamplingBudget::new(vertices, nodes), SamplingBudget::new(vertices, nodes)); + let new = sample(segment, plane, view, &mut a, clip); + let old = reference_sample(segment, plane, view, &mut b, clip); + assert!(same_path(&new, &old), "{segment:?} on {plane:?} in {view:?}, clipped {clip}, budget {vertices}/{nodes}"); + assert_eq!((a.remaining_vertices, a.remaining_nodes), (b.remaining_vertices, b.remaining_nodes)); + compared += new.vertex_count; + } + } + } + } + } + assert!(compared > 10_000, "the views sample in earnest: {compared} vertices"); +} + +/// Times the sampler against the reference on a few thousand cubic Béziers in a fitted view. +/// Run with `--ignored --nocapture` in a release build. +#[test] +#[ignore = "manual sampler measurement"] +fn sampler_cost_against_the_reference() { + let segments: Vec = (0..4096) + .map(|i| { + let (x, y) = ((i % 64) as f64 * 3.0, (i / 64) as f64 * 3.0); + Seg2::Cubic { p0: Vec2::new(x, y), p1: Vec2::new(x + 0.6, y - 0.5), p2: Vec2::new(x + 1.4, y - 0.5), p3: Vec2::new(x + 2.0, y) } + }) + .collect(); + let v = view(2.0 / 200.0, 1.0); + let time = |f: &dyn Fn(&Seg2, &mut SamplingBudget) -> SampledPath| { + let mut t: Vec = (0..5) + .map(|_| { + let start = std::time::Instant::now(); + let mut budget = SamplingBudget::new(1_000_000, 2_000_000); + let n: usize = segments.iter().map(|s| f(s, &mut budget).vertex_count).sum(); + std::hint::black_box(n); + start.elapsed().as_secs_f64() * 1000.0 + }) + .collect(); + t.sort_by(f64::total_cmp); + t[2] + }; + for clip in [true, false] { + let mut budget = SamplingBudget::new(1_000_000, 2_000_000); + let vertices: usize = segments.iter().map(|s| sample(s, &plane(), &v, &mut budget, clip).vertex_count).sum(); + println!("SAMPLER clip={clip} segments={} nodes={} vertices={vertices}", segments.len(), 2_000_000 - budget.remaining_nodes); + let (mut old, mut new) = (Vec::new(), Vec::new()); + for _ in 0..9 { + old.push(time(&|s, b| reference_sample(s, &plane(), &v, b, clip))); + new.push(time(&|s, b| sample(s, &plane(), &v, b, clip))); + } + old.sort_by(f64::total_cmp); + new.sort_by(f64::total_cmp); + println!("SAMPLER clip={clip} reference_ms={:.3} new_ms={:.3} ratio={:.3}", old[4], new[4], new[4] / old[4]); + } +} diff --git a/crates/render/src/film_png.rs b/crates/render/src/film_png.rs index c23227e0a..13a12057f 100644 --- a/crates/render/src/film_png.rs +++ b/crates/render/src/film_png.rs @@ -9,7 +9,8 @@ use super::{CompletePass, MAX_BYTES, invalid, limit}; use crate::job::encoding::PngEncoding; use crate::job::{CancelToken, CpuHost, ErrorCode, JobError, Phase, Progress, Reservation, Result}; -use solidcraft_geom::{Vec3, srgb::encode8}; +use solidcore_record::Vec3; +use solidcraft_geom::srgb::encode8; /// Encoded bytes retain the actual existing host lease. No detached byte getter. pub struct CompletedPng { diff --git a/crates/render/src/hatch.rs b/crates/render/src/hatch.rs new file mode 100644 index 000000000..b2efeb4ac --- /dev/null +++ b/crates/render/src/hatch.rs @@ -0,0 +1,246 @@ +//! The section hatch by part, as engineering section drawings tell parts apart: each body a +//! section cuts is hatched at 45 or 135 degrees in one of a few colours of one family, and bodies +//! whose cut faces touch or overlap never share a hatch (a map colouring of the cut, the angle +//! changed first, then the colour). Otherwise a body keeps the hatch its name seeds, so it stays +//! the same from frame to frame and as the plane moves. Spacing and line width are the same for +//! every hatch; only the angle and the colour change. + +use solidcraft_geom::prelude::*; +use std::collections::{HashMap, HashSet}; + +use solidcore_record::{Vec2, Vec3}; + +/// The colours a cut is hatched in: the section cap's own, then the others of its family. +pub const HATCH_COLOURS: usize = 3; + +/// The hatches a body may get: every colour at 45 and at 135 degrees. +pub const HATCHES: usize = 2 * HATCH_COLOURS; + +/// One of the [`HATCHES`]: colour `n / 2`, at 135 degrees when `n` is odd. Hatch 0 is the one a +/// section draws every body with when it does not hatch by part: the cap's colour at 45 degrees. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Hatch(pub u8); + +impl Hatch { + /// Which of the [`HATCH_COLOURS`] it is drawn in. + pub fn colour(self) -> usize { + usize::from(self.0 / 2) % HATCH_COLOURS + } + + /// Its lines run at 135 degrees on screen (else 45). + pub fn turned(self) -> bool { + self.0 % 2 == 1 + } + + fn of(colour: usize, turned: bool) -> Hatch { + Hatch(((colour % HATCH_COLOURS) * 2 + usize::from(turned)) as u8) + } +} + +/// A body's seed: its persistent name hashed (FNV-1a, the same on every platform and release). +pub fn seed(name: &str) -> u64 { + name.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)) +} + +/// A closed body the section cuts: its [`seed`] and where the plane cuts it, as segments in the +/// plane (one per crossed triangle, in world space). +pub struct CutPart<'a> { + pub seed: u64, + pub segments: &'a [(Vec3, Vec3)], +} + +/// Cut faces closer than this, as a share of the whole cut's size, touch: a pin in its bore, +/// tessellated each its own way, still reads as one contact. +const TOUCH: f64 = 1e-3; + +/// The hatch of each part (in order) cut by a plane with normal `normal`: the one its seed picks, +/// unless a part it touches or overlaps on the cut, taken first, has that one already; then the +/// same colour at the other angle, then the next colours. Parts are taken in the order of their +/// seeds, so the hatches depend only on which parts are cut and which of them touch. +pub fn hatches(parts: &[CutPart], normal: Vec3) -> Vec { + let neighbours = touching(parts, normal); + let mut order: Vec = (0..parts.len()).collect(); + order.sort_by_key(|&i| (parts.get(i).map_or(0, |p| p.seed), i)); + let mut out: Vec> = vec![None; parts.len()]; + for i in order { + let Some(part) = parts.get(i) else { continue }; + let taken: Vec = neighbours.get(&i).into_iter().flatten().filter_map(|j| out.get(*j).copied().flatten()).collect(); + let own = Hatch((mix(part.seed) % HATCHES as u64) as u8); + let candidates = (0..HATCH_COLOURS).flat_map(|k| { + let colour = own.colour() + k; + [Hatch::of(colour, own.turned()), Hatch::of(colour, !own.turned())] + }); + // The first free one; with every one taken, the one the fewest neighbours have. + let pick = candidates.clone().find(|h| !taken.contains(h)).or_else(|| candidates.min_by_key(|h| taken.iter().filter(|t| *t == h).count())); + if let Some(slot) = out.get_mut(i) { + *slot = pick; + } + } + out.into_iter().map(Option::unwrap_or_default).collect() +} + +/// The seed spread over all its bits (SplitMix64's finaliser), so names that differ in one +/// letter pick unrelated hatches. +fn mix(mut z: u64) -> u64 { + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +/// Which parts touch or overlap on the cut: per part, the others. +fn touching(parts: &[CutPart], normal: Vec3) -> HashMap> { + let u = normal.any_perp(); + let v = normal.cross(u).normalized().unwrap_or(Vec3::Y); + let flat = |p: Vec3| Vec2::new(p.dot(u), p.dot(v)); + let cuts: Vec> = parts + .iter() + .map(|p| p.segments.iter().map(|(a, b)| (flat(*a), flat(*b))).filter(|(a, b)| a.is_finite() && b.is_finite()).collect()) + .collect(); + let boxes: Vec> = cuts.iter().map(|c| bounds(c)).collect(); + let Some((lo, hi)) = boxes.iter().flatten().copied().reduce(|(a, b), (c, d)| (min2(a, c), max2(b, d))) else { + return HashMap::new(); + }; + let extent = (hi - lo).len(); + if !(extent.is_finite() && extent > 0.0) { + return HashMap::new(); + } + let eps = extent * TOUCH; + let mut pairs: HashSet<(usize, usize)> = HashSet::new(); + // Outlines closer than `eps`: through a grid of cells at least `eps` wide, each holding the + // pieces of segments (no longer than a cell) whose box, grown by half of `eps`, reaches it. + let cell = eps.max(extent / 1024.0); + let mut grid: HashMap<(i64, i64), Vec<(usize, usize)>> = HashMap::new(); + let at = |x: f64, o: f64| ((x - o) / cell).floor() as i64; + for (pi, cut) in cuts.iter().enumerate() { + for (si, (a, b)) in cut.iter().enumerate() { + let pieces = ((*b - *a).len() / cell).ceil().clamp(1.0, 4096.0) as usize; + let mut last = None; + for k in 0..pieces { + let (p, q) = (a.lerp(*b, k as f64 / pieces as f64), a.lerp(*b, (k + 1) as f64 / pieces as f64)); + let (x0, x1) = (at(p.x.min(q.x) - eps / 2.0, lo.x), at(p.x.max(q.x) + eps / 2.0, lo.x)); + let (y0, y1) = (at(p.y.min(q.y) - eps / 2.0, lo.y), at(p.y.max(q.y) + eps / 2.0, lo.y)); + for x in x0..=x1 { + for y in y0..=y1 { + // Consecutive pieces share cells: the segment goes in each cell once. + if last.is_some_and(|(lx0, lx1, ly0, ly1)| (lx0..=lx1).contains(&x) && (ly0..=ly1).contains(&y)) { + continue; + } + grid.entry((x, y)).or_default().push((pi, si)); + } + } + last = Some((x0, x1, y0, y1)); + } + } + } + for list in grid.values() { + for (k, &(pa, sa)) in list.iter().enumerate() { + for &(pb, sb) in list.iter().skip(k + 1) { + let pair = (pa.min(pb), pa.max(pb)); + if pa == pb || pairs.contains(&pair) { + continue; + } + let seg = |p: usize, s: usize| cuts.get(p).and_then(|c| c.get(s)).copied(); + if let (Some(x), Some(y)) = (seg(pa, sa), seg(pb, sb)) + && segment_distance(x, y) <= eps + { + pairs.insert(pair); + } + } + } + } + // Overlap without outlines that meet: one part's cut lies inside the other's material. + let mut rows: HashMap = HashMap::new(); + for a in 0..cuts.len() { + for b in a + 1..cuts.len() { + if pairs.contains(&(a, b)) { + continue; + } + let (Some(Some(ba)), Some(Some(bb))) = (boxes.get(a), boxes.get(b)) else { continue }; + if ba.1.x < bb.0.x || bb.1.x < ba.0.x || ba.1.y < bb.0.y || bb.1.y < ba.0.y { + continue; + } + let inside = |outer: usize, inner: usize, rows: &mut HashMap| { + let (Some(o), Some(Some(first))) = (cuts.get(outer), cuts.get(inner).map(|c| c.first())) else { return false }; + let r = rows.entry(outer).or_insert_with(|| Rows::new(o)); + r.contains(o, first.0.lerp(first.1, 0.5)) + }; + if inside(a, b, &mut rows) || inside(b, a, &mut rows) { + pairs.insert((a, b)); + } + } + } + let mut out: HashMap> = HashMap::new(); + for (a, b) in pairs { + out.entry(a).or_default().push(b); + out.entry(b).or_default().push(a); + } + out +} + +/// A part's cut segments sorted into rows across the plane's second axis, so a point-in-material +/// test looks at the segments of one row. +struct Rows { + lo: f64, + step: f64, + rows: Vec>, +} + +/// Rows a [`Rows`] makes, at most. +const ROWS: usize = 256; + +impl Rows { + fn new(cut: &[(Vec2, Vec2)]) -> Rows { + let (lo, hi) = cut.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), (a, b)| (l.min(a.y).min(b.y), h.max(a.y).max(b.y))); + let count = (cut.len() / 16).clamp(1, ROWS); + let step = if hi > lo { (hi - lo) / count as f64 } else { 1.0 }; + let mut rows = vec![Vec::new(); count]; + let row = |y: f64| (((y - lo) / step).floor().max(0.0) as usize).min(count - 1); + for (i, (a, b)) in cut.iter().enumerate() { + for r in rows.iter_mut().take(row(a.y.max(b.y)) + 1).skip(row(a.y.min(b.y))) { + r.push(i); + } + } + Rows { lo, step, rows } + } + + /// Whether `p` lies inside the material `cut` bounds: a ray along the first axis crosses its + /// outline an odd number of times. + fn contains(&self, cut: &[(Vec2, Vec2)], p: Vec2) -> bool { + let r = ((p.y - self.lo) / self.step).floor(); + let Some(row) = (r >= 0.0).then_some(r as usize).and_then(|r| self.rows.get(r)) else { return false }; + let crossings = row + .iter() + .filter_map(|i| cut.get(*i)) + .filter(|(a, b)| (a.y > p.y) != (b.y > p.y) && a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) > p.x) + .count(); + crossings % 2 == 1 + } +} + +fn min2(a: Vec2, b: Vec2) -> Vec2 { + Vec2::new(a.x.min(b.x), a.y.min(b.y)) +} + +fn max2(a: Vec2, b: Vec2) -> Vec2 { + Vec2::new(a.x.max(b.x), a.y.max(b.y)) +} + +fn bounds(cut: &[(Vec2, Vec2)]) -> Option<(Vec2, Vec2)> { + cut.iter().map(|(a, b)| (min2(*a, *b), max2(*a, *b))).reduce(|(a, b), (c, d)| (min2(a, c), max2(b, d))) +} + +/// The distance between two segments: zero where they cross, else the nearest end to the other. +fn segment_distance((a, b): (Vec2, Vec2), (c, d): (Vec2, Vec2)) -> f64 { + let side = |p: Vec2, q: Vec2, r: Vec2| (q - p).cross(r - p); + let (d1, d2, d3, d4) = (side(c, d, a), side(c, d, b), side(a, b, c), side(a, b, d)); + if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0)) { + return 0.0; + } + let to = |p: Vec2, s: Vec2, e: Vec2| { + let se = e - s; + let l2 = se.dot(se); + let t = if l2 > 0.0 { ((p - s).dot(se) / l2).clamp(0.0, 1.0) } else { 0.0 }; + (p - (s + se * t)).len() + }; + to(a, c, d).min(to(b, c, d)).min(to(c, a, b)).min(to(d, a, b)) +} diff --git a/crates/render/src/job/cpu_budget.rs b/crates/render/src/job/cpu_budget.rs index fa3cd6469..0494419f8 100644 --- a/crates/render/src/job/cpu_budget.rs +++ b/crates/render/src/job/cpu_budget.rs @@ -104,17 +104,54 @@ impl CpuBudget { Ok(()) } + /// The smallest profile that admits this image, to name in a refusal. It is never + /// selected automatically: the person chooses it. `None` when no profile admits it. + pub fn smallest_admitting(width: u32, height: u32, progressive: Option) -> Option { + Self::ALL.into_iter().find(|budget| budget.admits_image(width, height, progressive)) + } + + /// What `validate_image` accepts, without building its message (which names a profile). + fn admits_image(self, width: u32, height: u32, progressive: Option) -> bool { + let (w, h) = (u64::from(width), u64::from(height)); + let limits = self.image_limits(progressive.is_some()); + let Some(pixels) = w.checked_mul(h) else { return false }; + w > 0 + && h > 0 + && w <= limits.max_dimension + && h <= limits.max_dimension + && pixels <= limits.max_pixels + && progressive.is_none_or(|options| { + let samples = options.samples_per_pixel; + (1..=self.limits().max_samples_per_pixel).contains(&samples) + && pixels.checked_mul(u64::from(samples)).is_some_and(|n| n <= self.limits().max_camera_samples) + }) + } + + /// The way out of a size refusal, for English messages: the profile that can render + /// the image, or only a smaller size when none can. + pub fn size_advice(width: u32, height: u32, progressive: Option) -> String { + match Self::smallest_admitting(width, height, progressive) { + Some(budget) => format!("choose the {budget:?} CPU resource profile, or a smaller size"), + None => "no CPU resource profile accepts this size; choose a smaller size".into(), + } + } + /// No geometry reads or allocations. This also validates offline saved intent. pub fn validate_image(self, width: u32, height: u32, progressive: Option) -> Result<()> { let (w, h) = (u64::from(width), u64::from(height)); let limits = self.image_limits(progressive.is_some()); let pixels = w.checked_mul(h).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "CPU pixel count overflow"))?; - if w == 0 || h == 0 || w > limits.max_dimension || h > limits.max_dimension || pixels > limits.max_pixels { + if w == 0 || h == 0 { + return Err(JobError::new(ErrorCode::LimitExceeded, format!("CPU {self:?} accepts dimensions 1..{}", limits.max_dimension))); + } + if w > limits.max_dimension || h > limits.max_dimension || pixels > limits.max_pixels { return Err(JobError::new( ErrorCode::LimitExceeded, format!( - "CPU {self:?} accepts dimensions 1..{} and at most {} pixels; select a larger resource profile explicitly", - limits.max_dimension, limits.max_pixels + "CPU {self:?} accepts dimensions 1..{} and at most {} pixels; {}", + limits.max_dimension, + limits.max_pixels, + Self::size_advice(width, height, progressive) ), )); } @@ -173,4 +210,39 @@ mod tests { assert!(CpuBudget::Workstation.validate_image(8192, 8192, p).is_err()); assert!(CpuBudget::Workstation.validate_image(3840, 2160, p).is_ok()); } + + /// #8941: a size refusal names the smallest profile that admits the image, and none when + /// even Workstation refuses it. The profile is only named, never selected. + #[test] + fn a_size_refusal_names_the_smallest_profile_that_admits_it() { + assert_eq!(CpuBudget::smallest_admitting(1920, 1080, None), Some(CpuBudget::Compact)); + assert_eq!(CpuBudget::smallest_admitting(3840, 2160, None), Some(CpuBudget::Studio)); + assert_eq!(CpuBudget::smallest_admitting(15360, 4320, None), Some(CpuBudget::Workstation)); + assert_eq!(CpuBudget::smallest_admitting(16385, 1, None), None); + assert_eq!(CpuBudget::smallest_admitting(0, 1, None), None); + let message = CpuBudget::Compact.validate_image(3840, 2160, None).unwrap_err().to_string(); + assert!(message.contains("choose the Studio CPU resource profile, or a smaller size"), "{message}"); + let message = CpuBudget::Studio.validate_image(15360, 4320, None).unwrap_err().to_string(); + assert!(message.contains("choose the Workstation CPU resource profile"), "{message}"); + let message = CpuBudget::Workstation.validate_image(16384, 16384, None).unwrap_err().to_string(); + assert!(message.contains("no CPU resource profile accepts this size"), "{message}"); + assert!(!message.contains("Studio") && !message.contains("choose the"), "{message}"); + // The message-free check agrees with validate_image everywhere, progressive included. + let sizes = [(0, 1), (1, 1), (2048, 2048), (3840, 2160), (4096, 4096), (7680, 4320), (8192, 8192), (16384, 4096), (u32::MAX, 2)]; + for budget in CpuBudget::ALL { + for progressive in [ + None, + Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 0 }), + Some(CpuProgressiveOptions { samples_per_pixel: 4096, seed: 0 }), + ] { + for (w, h) in sizes { + assert_eq!( + budget.admits_image(w, h, progressive), + budget.validate_image(w, h, progressive).is_ok(), + "{budget:?} {w}x{h} {progressive:?}" + ); + } + } + } + } } diff --git a/crates/render/src/job/host.rs b/crates/render/src/job/host.rs index 8c06a153f..749421264 100644 --- a/crates/render/src/job/host.rs +++ b/crates/render/src/job/host.rs @@ -362,6 +362,7 @@ pub struct JobStatus { } struct Data { + completed_duration: Option, punctual_diagnostics: Option, sampling: Option, progress: Progress, @@ -370,6 +371,7 @@ struct Data { preview: Option>, } struct Record { + started: web_time::Instant, presentation: Option>, textures: Option, options: JobOptions, @@ -399,6 +401,10 @@ impl JobHandle { pub fn id(&self) -> JobId { self.0.id } + /// Submission-to-publication time, captured once by the host, independent of UI polling. + pub fn completed_duration(&self) -> Result> { + self.0.data.lock().map(|data| data.completed_duration).map_err(|_| JobError::new(ErrorCode::Internal, "render duration lock poisoned")) + } pub fn status(&self) -> Result { let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; Ok(JobStatus { @@ -861,6 +867,7 @@ impl Running { })); data.preview = None; data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; + data.completed_duration = Some(self.handle.0.started.elapsed()); self.handle.0.notify(); Ok(false) } @@ -1318,6 +1325,7 @@ impl ImageHost { (request, None) }; let handle = JobHandle(Arc::new(Record { + started: web_time::Instant::now(), presentation: None, textures, options, @@ -1329,6 +1337,7 @@ impl ImageHost { resolved, cancel: CancelToken::default(), data: Mutex::new(Data { + completed_duration: None, punctual_diagnostics: None, sampling: None, progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, @@ -1435,6 +1444,7 @@ impl ImageHost { let metadata = self.0.shared.budget.reserve(metadata_bytes)?; let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); let handle = JobHandle(Arc::new(Record { + started: web_time::Instant::now(), presentation: Some(origin), textures: None, options, @@ -1446,6 +1456,7 @@ impl ImageHost { resolved, cancel: CancelToken::default(), data: Mutex::new(Data { + completed_duration: None, punctual_diagnostics: None, sampling: None, progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, @@ -1589,8 +1600,8 @@ mod retained_request_tests { request.raytrace.as_mut().unwrap().emissions = Some(values); let expected = retained_request_bytes(&request).unwrap(); let mesh = solidcraft_geom::Mesh { - positions: vec![solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::X, solidcraft_geom::Vec3::Y], - normals: vec![solidcraft_geom::Vec3::Z; 3], + positions: vec![solidcore_record::Vec3::ZERO, solidcore_record::Vec3::X, solidcore_record::Vec3::Y], + normals: vec![solidcore_record::Vec3::Z; 3], triangles: vec![[0, 1, 2]], tri_face: vec![0], ..Default::default() @@ -1775,7 +1786,7 @@ mod surface_request_metadata_tests { bump_amplitude_mm: 0.0, }); } - let scene = ProductScene { meshes, bounds: Aabb3 { min: solidcraft_geom::Vec3::ZERO, max: solidcraft_geom::Vec3::ZERO } }; + let scene = ProductScene { meshes, bounds: Aabb3 { min: solidcore_record::Vec3::ZERO, max: solidcore_record::Vec3::ZERO } }; let mut request = request(); request.integrator = Integrator::Raytrace; request.raytrace = Some(super::super::RaytraceOptions { surface_effects: Some(effects), ..Default::default() }); diff --git a/crates/render/src/job/host_tests.rs b/crates/render/src/job/host_tests.rs index 62afa6298..e18a5cd6b 100644 --- a/crates/render/src/job/host_tests.rs +++ b/crates/render/src/job/host_tests.rs @@ -348,6 +348,25 @@ fn native_job_finishes_without_any_poll_or_ui_pump() { assert_eq!(frame.info.png_bytes, frame.png().len() as u64); assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256); + let duration = job.completed_duration().unwrap().unwrap(); + assert_eq!(job.completed_duration().unwrap(), Some(duration), "completed duration is independent of status polling"); +} + +#[test] +fn completed_duration_is_captured_at_publication_and_never_for_cancelled_work() { + let host = CpuHost::cooperative(); + let job = host.submit(id(1, 1), 12, empty(), request()).unwrap(); + assert!(job.completed_duration().unwrap().is_none()); + drain(&host); + let duration = job.completed_duration().unwrap().unwrap(); + assert!(duration.as_secs_f64().is_finite()); + job.status().unwrap(); + host.pump(1).unwrap(); + assert_eq!(job.completed_duration().unwrap(), Some(duration)); + let cancelled = host.submit(id(1, 2), 12, empty(), request()).unwrap(); + cancelled.cancel().unwrap(); + drain(&host); + assert!(cancelled.completed_duration().unwrap().is_none()); } /// Isolate the existing integrator-to-host completion boundary with a real PNG diff --git a/crates/render/src/job/image.rs b/crates/render/src/job/image.rs index b27b38d7e..7bc5daad9 100644 --- a/crates/render/src/job/image.rs +++ b/crates/render/src/job/image.rs @@ -5,12 +5,14 @@ //! pixel windows, each handed back as straight-alpha sRGB rows). It prepares once (appearances, //! projected triangles, glass sorted back to front) and then draws each tile. +use solidcraft_geom::prelude::*; use std::collections::BTreeMap; use std::sync::LazyLock; use serde::Serialize; +use solidcore_record::{Plane, Vec2, Vec3}; use solidcraft_geom::pixel_grid::{MAX_SIDE_PX, PixelGrid}; -use solidcraft_geom::{Plane, Vec2, Vec3, srgb}; +use solidcraft_geom::srgb; use super::{CancelToken, ErrorCode, ImageRequest, JobError, Phase, Progress, Result}; use crate::{Camera, FaceAppearance, Mat4, ProductScene, RenderFormat, RenderMode, RenderOperation, RenderRequest}; diff --git a/crates/render/src/job/led_strip.rs b/crates/render/src/job/led_strip.rs index 08becb5f2..8615d05ed 100644 --- a/crates/render/src/job/led_strip.rs +++ b/crates/render/src/job/led_strip.rs @@ -2,7 +2,8 @@ //! No source mesh, visible emission, spectral/CCT calibration or separate transport. use super::{ErrorCode, JobError, RaytraceOptions, RectangleLightOptions, Result}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; /// Illustrative linear RGB choices, not measured LED spectra or calibrated CCT. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/render/src/job/lighting.rs b/crates/render/src/job/lighting.rs index 11f483285..61ca559d1 100644 --- a/crates/render/src/job/lighting.rs +++ b/crates/render/src/job/lighting.rs @@ -2,7 +2,8 @@ //! world-space millimetres; radiance is linear RGB. Saved setups reuse these bounds. use super::{ErrorCode, JobError, Result}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; pub const MAX_AREA_LIGHTS: usize = 4; diff --git a/crates/render/src/job/mod.rs b/crates/render/src/job/mod.rs index a9849578a..351eeda8c 100644 --- a/crates/render/src/job/mod.rs +++ b/crates/render/src/job/mod.rs @@ -1,6 +1,7 @@ //! Product-image work and its device-independent, session-scoped protocol. //! Hosts own execution; documents and history never contain these values. +use solidcraft_geom::prelude::*; use std::fmt; use std::sync::{ Arc, @@ -966,7 +967,7 @@ impl RaytraceOptions { } if let Some(lights) = &self.area_lights { for light in lights { - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let vec = |v: [f64; 3]| Vec3::new(v[0], v[1], v[2]); let c = vec(light.center_mm); let u = vec(light.edge_u_mm); diff --git a/crates/render/src/job/punctual.rs b/crates/render/src/job/punctual.rs index 8e3549614..2f95a4e73 100644 --- a/crates/render/src/job/punctual.rs +++ b/crates/render/src/job/punctual.rs @@ -60,7 +60,7 @@ impl PunctualLightOptions { #[cfg(feature = "raytrace-cpu")] pub(crate) fn light(self) -> crate::raytrace::Result { use crate::raytrace::punctual::{PunctualLight, SpotCone}; - use solidcraft_geom::Vec3; + use solidcore_record::Vec3; let [x, y, z] = self.position_mm; let [r, g, b] = self.color; let cone = self diff --git a/crates/render/src/job/textures.rs b/crates/render/src/job/textures.rs index 24bd45619..210db6f1d 100644 --- a/crates/render/src/job/textures.rs +++ b/crates/render/src/job/textures.rs @@ -8,7 +8,8 @@ use crate::{ }; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; pub const MAX_TEXTURE_BINDINGS: usize = 128; pub const MAX_TEXTURE_PIXELS_BYTES: u64 = 96 * 1024 * 1024; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b68bec8fa..bd29b1417 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -12,6 +12,7 @@ pub mod clear_coat; mod curve_display; pub mod film; mod gif; +pub mod hatch; pub mod job; pub mod lighting; pub mod mapping; @@ -43,5 +44,5 @@ pub use curve_display::{PixelCurveView, SampledPath, SamplingBudget, SamplingQua pub use gif::gif; pub use product::{FaceAppearance, ProductMesh, ProductScene}; pub use raster::{Canvas, render, render_png, render_transparent}; -pub use scene::{MIN_ALPHA, Rgb, SECTION_CAP, SEE_THROUGH, Scene, SceneLine, SceneMesh, png}; +pub use scene::{MIN_ALPHA, Rgb, SECTION_CAP, SECTION_HATCH, SEE_THROUGH, Scene, SceneLine, SceneMesh, png}; pub use visual_style::VisualStyle; diff --git a/crates/render/src/lighting/environment.rs b/crates/render/src/lighting/environment.rs index 6b534ae39..099bb2401 100644 --- a/crates/render/src/lighting/environment.rs +++ b/crates/render/src/lighting/environment.rs @@ -4,7 +4,7 @@ use super::{HdrDecodeTask, HdrSource, HdrTaskPoll}; use crate::job::{CancelToken, ErrorCode, JobError, Result}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; use std::{ f64::consts::{PI, TAU}, sync::Arc, diff --git a/crates/render/src/lighting/environment_sampling.rs b/crates/render/src/lighting/environment_sampling.rs index 06e5c9187..251164336 100644 --- a/crates/render/src/lighting/environment_sampling.rs +++ b/crates/render/src/lighting/environment_sampling.rs @@ -2,7 +2,8 @@ //! Uniform solid-angle sampling deliberately has no luminance CDF or extra pixel copy. use super::{DecodedHdr, HdrError, HdrErrorCode, MAX_HDR_HEIGHT, MAX_HDR_PIXELS, MAX_HDR_WIDTH, Result}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use std::f64::consts::{PI, TAU}; fn invalid(message: &str) -> HdrError { diff --git a/crates/render/src/mapping.rs b/crates/render/src/mapping.rs index 4e34f4aae..cf20c21da 100644 --- a/crates/render/src/mapping.rs +++ b/crates/render/src/mapping.rs @@ -1,7 +1,9 @@ //! Definition-local visual coordinates, independent of geometry and engineering axes. //! This numerical foundation installs no texture sampler, shader or persistent record. -use solidcraft_geom::{Aabb3, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Aabb3; +use solidcraft_geom::prelude::*; /// Admission bounds, not a GPU precision or engineering applicability guarantee. pub const MAX_LOCAL_MM: f64 = 1e9; diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 1c1777747..f4fd729a2 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -1,7 +1,8 @@ //! CPU rasterizer for headless snapshots: z-buffered, smooth-shaded triangles and depth-tested //! lines, rendered at 2× and downsampled for anti-aliasing. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::Camera; use crate::scene::{Rgb, SECTION_CAP, Scene, png}; @@ -134,6 +135,11 @@ pub fn render(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Canvas { let alpha = sm.alpha(); let m = &sm.mesh; let body = sm.color.f(); + // The hatch of its cut face: its own by part, else the cap's at 45 degrees. + let (tint, turned) = match scene.part_hatch { + Some(colours) => (colours.get(sm.hatch.colour()).map_or(cap_tint, |c| c.f()), sm.hatch.turned()), + None => (cap_tint, false), + }; let pts: Vec> = m.positions.iter().map(|p| project(*p)).collect(); // 1 / clip w per vertex, for perspective-correct interpolation of world positions (so // the section cuts along the plane, not a curve, in perspective views). @@ -210,15 +216,16 @@ pub fn render(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Canvas { }; } if cut { - // The cut: the body's colour tinted toward the cap colour, hatched - // at 45 degrees (as the viewport draws it); a plain cap is the - // body's own colour. + // The cut: the body's colour tinted toward its hatch colour, hatched + // at 45 or 135 degrees (as the viewport draws it); a plain cap is + // the body's own colour. if scene.plain_cap { c.put(x, y, base, 1.0); continue; } - let tinted: [f64; 3] = std::array::from_fn(|k| base[k] + (cap_tint[k] - base[k]) * 0.35); - let k = if ((x + y) / SS) % 9 < 2 { 0.6 } else { 1.0 }; + let tinted: [f64; 3] = std::array::from_fn(|k| base[k] + (tint[k] - base[k]) * 0.35); + let along = if turned { x as i64 - y as i64 } else { (x + y) as i64 }; + let k = if along.div_euclid(SS as i64).rem_euclid(9) < 2 { 0.6 } else { 1.0 }; c.put(x, y, tinted.map(|v| v * k), 1.0); continue; } @@ -440,7 +447,14 @@ mod tests { /// A front panel over a back one, with a line between them, seen from the front. fn two_panels(front_opacity: f32) -> (Scene, Camera) { - let glass = SceneMesh { mesh: Arc::new(panel(-5.0)), color: Rgb(255, 0, 0), face_colors: Vec::new(), opacity: front_opacity }; + let glass = SceneMesh { + mesh: Arc::new(panel(-5.0)), + color: Rgb(255, 0, 0), + face_colors: Vec::new(), + opacity: front_opacity, + closed: true, + hatch: Default::default(), + }; let scene = Scene { meshes: vec![SceneMesh::solid(Arc::new(panel(5.0)), Rgb(0, 255, 0)), glass], lines: vec![SceneLine { diff --git a/crates/render/src/raytrace/anisotropic_faces.rs b/crates/render/src/raytrace/anisotropic_faces.rs index 6362304f5..729572490 100644 --- a/crates/render/src/raytrace/anisotropic_faces.rs +++ b/crates/render/src/raytrace/anisotropic_faces.rs @@ -2,7 +2,8 @@ //! Captured ordinal/name and mesh face tag must match. Strict plane equality is //! conservative: rotated or imported roundoff may refuse instead of guessing. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::{ ProductScene, diff --git a/crates/render/src/raytrace/area.rs b/crates/render/src/raytrace/area.rs index b58796082..76301aa25 100644 --- a/crates/render/src/raytrace/area.rs +++ b/crates/render/src/raytrace/area.rs @@ -2,7 +2,8 @@ //! Sampling estimates the area integral; it is not an exact solid-angle integral. //! No emitter geometry, indirect bounce or calibrated photometric units are implied. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::lighting::MAX_LINEAR_RADIANCE; use super::{MAX_COORDINATE_MM, MAX_DISTANCE_MM, Ray, Result, TraceError}; diff --git a/crates/render/src/raytrace/dielectric.rs b/crates/render/src/raytrace/dielectric.rs index f5c61b856..b12116ccd 100644 --- a/crates/render/src/raytrace/dielectric.rs +++ b/crates/render/src/raytrace/dielectric.rs @@ -2,7 +2,8 @@ //! Air is 1.0. Distances and absorption coefficients use millimetres. use super::{Bounds, Result, TraceError, Triangle, unit}; use crate::{ProductScene, job::DielectricOptions}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; pub const MAX_OVERRIDES: usize = 8; pub const MAX_BOUNDARIES: u8 = 8; @@ -104,8 +105,13 @@ pub enum Certificate { ClosedBox(Bounds), } -/// A strict geometric subset, never a trusted mesh.closed flag. Only twelve -/// outward corner triangles, two complementary halves per box face, qualify. +/// Most triangles a closed box's boundary may come in (its mesh is read in full, sorting its +/// edges). +pub const MAX_BOX_TRIANGLES: usize = 1 << 16; + +/// A strict geometric subset, never a trusted mesh.closed flag. A thin sheet is one or two +/// coplanar triangles; a closed box is a mesh that is exactly the boundary of an axis-aligned +/// box, in however many triangles ([`certify_box`]). pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result { let body = scene.meshes.get(input.body_index).ok_or(TraceError::InvalidInput("dielectric body ordinal"))?; if body.name != input.body_name { @@ -113,70 +119,105 @@ pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result 36 { - return Err(TraceError::InvalidInput("unsupported dielectric boundary tessellation")); + let unsupported = TraceError::InvalidInput("unsupported dielectric boundary tessellation"); + if closed { + if !(12..=MAX_BOX_TRIANGLES).contains(&mesh.triangles.len()) { + return Err(unsupported); + } + return certify_box(mesh); } - let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); - let mut hi = -lo; - let mut tris = [None; 12]; + if !(1..=2).contains(&mesh.triangles.len()) || mesh.positions.len() > 36 { + return Err(unsupported); + } + let mut tris = [None; 2]; for (slot, indices) in tris.iter_mut().zip(&mesh.triangles) { - let mut vertices = [Vec3::ZERO; 3]; - for (v, index) in vertices.iter_mut().zip(indices) { - *v = *mesh.positions.get(*index as usize).ok_or(TraceError::InvalidInput("dielectric vertex index"))?; - lo = lo.min(*v); - hi = hi.max(*v); - } - let triangle = Triangle::new(vertices)?; - if triangle.geometric_normal().is_none() { - return Err(TraceError::InvalidInput("degenerate dielectric boundary")); - } + let triangle = triangle(mesh, indices)?; *slot = Some(triangle); } - if !closed { - let first = tris.first().copied().flatten().ok_or(TraceError::InvalidInput("empty thin sheet"))?; - let normal = first.geometric_normal().ok_or(TraceError::InvalidInput("thin sheet normal"))?; - let [anchor, _, _] = first.vertices(); - for triangle in tris.into_iter().flatten() { - if triangle.geometric_normal() != Some(normal) || triangle.vertices().into_iter().any(|p| (p - anchor).dot(normal) != 0.0) { - return Err(TraceError::InvalidInput("thin sheet must be one planar consistently wound surface")); + let first = tris.first().copied().flatten().ok_or(TraceError::InvalidInput("empty thin sheet"))?; + let normal = first.geometric_normal().ok_or(TraceError::InvalidInput("thin sheet normal"))?; + let [anchor, _, _] = first.vertices(); + for triangle in tris.into_iter().flatten() { + if triangle.geometric_normal() != Some(normal) || triangle.vertices().into_iter().any(|p| (p - anchor).dot(normal) != 0.0) { + return Err(TraceError::InvalidInput("thin sheet must be one planar consistently wound surface")); + } + } + if let Some(second) = tris.get(1).copied().flatten() { + let first = first.vertices(); + let second = second.vertices(); + let mut shared = [Vec3::ZERO; 2]; + let mut shared_count = 0usize; + let mut other_first = None; + let mut other_second = None; + for p in first { + if second.contains(&p) { + *shared.get_mut(shared_count).ok_or(TraceError::InvalidInput("duplicate thin sheet triangle"))? = p; + shared_count += 1; + } else { + other_first = Some(p); } } - if let Some(second) = tris.get(1).copied().flatten() { - let first = first.vertices(); - let second = second.vertices(); - let mut shared = [Vec3::ZERO; 2]; - let mut shared_count = 0usize; - let mut other_first = None; - let mut other_second = None; - for p in first { - if second.contains(&p) { - *shared.get_mut(shared_count).ok_or(TraceError::InvalidInput("duplicate thin sheet triangle"))? = p; - shared_count += 1; - } else { - other_first = Some(p); - } - } - for p in second { - if !first.contains(&p) { - other_second = Some(p); - } - } - let [a, b] = shared; - let c = other_first.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; - let d = other_second.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; - if shared_count != 2 || (b - a).cross(c - a).dot(normal) * (b - a).cross(d - a).dot(normal) >= 0.0 { - return Err(TraceError::InvalidInput("thin sheet triangles overlap or have no unique shared edge")); + for p in second { + if !first.contains(&p) { + other_second = Some(p); } } - return Ok(Certificate::ThinSheet); + let [a, b] = shared; + let c = other_first.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; + let d = other_second.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; + if shared_count != 2 || (b - a).cross(c - a).dot(normal) * (b - a).cross(d - a).dot(normal) >= 0.0 { + return Err(TraceError::InvalidInput("thin sheet triangles overlap or have no unique shared edge")); + } + } + Ok(Certificate::ThinSheet) +} + +/// The mesh's triangle with these indices, refused where it is degenerate. +fn triangle(mesh: &solidcraft_geom::Mesh, indices: &[u32; 3]) -> Result { + let mut vertices = [Vec3::ZERO; 3]; + for (v, index) in vertices.iter_mut().zip(indices) { + *v = *mesh.positions.get(*index as usize).ok_or(TraceError::InvalidInput("dielectric vertex index"))?; + } + let triangle = Triangle::new(vertices)?; + if triangle.geometric_normal().is_none() { + return Err(TraceError::InvalidInput("degenerate dielectric boundary")); + } + Ok(triangle) +} + +/// A closed box: `mesh` is exactly the boundary of the axis-aligned box its points span, each +/// point of that boundary covered once, by exact tests on the mesh's coordinates: +/// - every triangle lies in the plane of one of the box's faces (its three corners on it, its +/// normal exactly that axis), facing out of the box; +/// - the triangles make a closed, consistently oriented surface: each edge, between two points +/// given by their exact coordinates, is run once each way. +/// +/// Such a surface is a 2-cycle on the box's boundary, a sphere, so it covers every point of the +/// boundary the same number of times k, with every triangle facing out (k ≥ 1), and its area is +/// k times the boundary's. k is 1 when the triangles' area is under 1.5 times the boundary's. +/// The count of triangles is no part of it: a face may come in any tiling. +fn certify_box(mesh: &solidcraft_geom::Mesh) -> Result { + let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); + let mut hi = -lo; + let mut tris = Vec::new(); + tris.try_reserve_exact(mesh.triangles.len()).map_err(|_| TraceError::AllocationFailed)?; + for indices in &mesh.triangles { + let triangle = triangle(mesh, indices)?; + for v in triangle.vertices() { + lo = lo.min(v); + hi = hi.max(v); + } + tris.push(triangle); } if lo.x >= hi.x || lo.y >= hi.y || lo.z >= hi.z { return Err(TraceError::InvalidInput("closed box needs positive extents")); } let bounds = Bounds::new(lo, hi)?; - let mut masks = [[0u8; 2]; 6]; - let mut counts = [0usize; 6]; - for triangle in tris.into_iter().flatten() { + let mut edges: Vec<([u64; 3], [u64; 3])> = Vec::new(); + edges.try_reserve_exact(tris.len() * 3).map_err(|_| TraceError::AllocationFailed)?; + let key = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]; + let mut area = 0.0; + for triangle in &tris { let vertices = triangle.vertices(); let n = triangle.geometric_normal().ok_or(TraceError::InvalidInput("box normal"))?; let axis = if n.x.abs() == 1.0 { @@ -190,41 +231,23 @@ pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result 0.0; let plane = super::component(if positive { hi } else { lo }, axis); - let face = axis * 2 + usize::from(positive); - let mut mask = 0u8; - for p in vertices { - if super::component(p, axis) != plane { - return Err(TraceError::InvalidInput("box winding or face plane")); - } - let mut corner = 0; - for (bit, a) in [(0, (axis + 1) % 3), (1, (axis + 2) % 3)] { - let value = super::component(p, a); - if value == super::component(hi, a) { - corner |= 1 << bit; - } else if value != super::component(lo, a) { - return Err(TraceError::InvalidInput("box vertex is not a corner")); - } - } - mask |= 1 << corner; + if vertices.iter().any(|p| super::component(*p, axis) != plane) { + return Err(TraceError::InvalidInput("box winding or face plane")); } - let count = counts.get_mut(face).ok_or(TraceError::Internal("box face count"))?; - let target = masks.get_mut(face).and_then(|pair| pair.get_mut(*count)).ok_or(TraceError::InvalidInput("too many box face triangles"))?; - *target = mask; - *count += 1; + let [a, b, c] = vertices; + area += (b - a).cross(c - a).len() * 0.5; + edges.extend([(key(a), key(b)), (key(b), key(c)), (key(c), key(a))]); } - for (count, [a, b]) in counts.into_iter().zip(masks) { - // Three distinct corners each; missing corners must be opposite. Thus - // both triangles share a diagonal and tile, rather than overlap. - let missing_a = (!a) & 15; - let missing_b = (!b) & 15; - if count != 2 - || a.count_ones() != 3 - || b.count_ones() != 3 - || (a | b) != 15 - || !matches!((missing_a, missing_b), (1, 8) | (8, 1) | (2, 4) | (4, 2)) - { - return Err(TraceError::InvalidInput("incomplete or ambiguous closed box face")); - } + // Each edge run once each way: sorted, every directed edge is there once and so is its + // reverse. + edges.sort_unstable(); + if edges.windows(2).any(|w| w[0] == w[1]) || edges.iter().any(|(a, b)| edges.binary_search(&(*b, *a)).is_err()) { + return Err(TraceError::InvalidInput("incomplete or ambiguous closed box face")); + } + let size = hi - lo; + let boundary = 2.0 * (size.x * size.y + size.y * size.z + size.z * size.x); + if !(area < 1.5 * boundary) { + return Err(TraceError::InvalidInput("closed box boundary covered more than once")); } Ok(Certificate::ClosedBox(bounds)) } diff --git a/crates/render/src/raytrace/dielectric_tests.rs b/crates/render/src/raytrace/dielectric_tests.rs index d6eb18bdf..3cfced34b 100644 --- a/crates/render/src/raytrace/dielectric_tests.rs +++ b/crates/render/src/raytrace/dielectric_tests.rs @@ -129,6 +129,31 @@ fn closed_box_certification_requires_complete_outward_boundary() { assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err()); } +/// A box's boundary in more triangles than two a face (its top fanned from a point in its +/// middle, as a mesher with interior points makes it) is the same box; the fan's middle off the +/// face's plane, or a face covered twice, is not. +#[test] +fn closed_box_certification_takes_any_tiling_of_the_faces() { + let fanned = |middle: Vec3| { + let mut body = box_body(2.0); + let mesh = Arc::make_mut(&mut body.mesh); + mesh.positions.push(middle); + mesh.triangles.retain(|t| *t != [4, 5, 7] && *t != [4, 7, 6]); + mesh.triangles.extend([[8, 4, 5], [8, 5, 7], [8, 7, 6], [8, 6, 4]]); + body + }; + let Ok(Certificate::ClosedBox(bounds)) = certify(&scene(fanned(Vec3::new(1.0, -3.0, 2.0))), &input(DielectricBoundary::ClosedBox)) else { + panic!("a fanned top is still the box") + }; + assert_eq!((bounds.min(), bounds.max()), (Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 2.0))); + assert!(certify(&scene(fanned(Vec3::new(1.0, -3.0, 2.0 - 1e-9))), &input(DielectricBoundary::ClosedBox)).is_err()); + // The top once more, split along its other diagonal: covered twice. + let mut body = box_body(2.0); + let mesh = Arc::make_mut(&mut body.mesh); + mesh.triangles.extend([[4, 5, 6], [5, 7, 6]]); + assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err()); +} + #[test] fn captured_occurrence_identity_and_unsupported_boundary_are_refused() { let scene = scene(box_body(2.0)); diff --git a/crates/render/src/raytrace/emission.rs b/crates/render/src/raytrace/emission.rs index ff08b10b3..883212ea4 100644 --- a/crates/render/src/raytrace/emission.rs +++ b/crates/render/src/raytrace/emission.rs @@ -1,6 +1,6 @@ //! Visible surface radiance only: no mesh-light sampling or neighboring illumination. use crate::job::{EmissionSides, SurfaceEmission}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; #[derive(Clone, Copy, Debug)] pub struct Emission { diff --git a/crates/render/src/raytrace/image.rs b/crates/render/src/raytrace/image.rs index 56787decc..eb3e12c40 100644 --- a/crates/render/src/raytrace/image.rs +++ b/crates/render/src/raytrace/image.rs @@ -13,7 +13,9 @@ use crate::{ film::primary::PrimaryFilm, surface::{OpaqueSurface, srgb8_to_linear}, }; -use solidcraft_geom::{Vec3, srgb::encode8}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use solidcraft_geom::srgb::encode8; #[cfg(test)] #[path = "environment_image_tests.rs"] @@ -471,8 +473,10 @@ pub struct ImageTask { looks: Vec, body: usize, triangle: usize, - face_cursor: usize, - chosen: Option, + /// The current body's face looks as (face, index into `faces`), sorted by + /// face with only the first entry per face, so each triangle is one lookup. + face_looks: Vec<(u32, usize)>, + face_looks_ready: bool, builder: Option, bvh: Option, build_used: u64, @@ -624,8 +628,8 @@ impl ImageTask { looks, body: 0, triangle: 0, - face_cursor: 0, - chosen: None, + face_looks: Vec::new(), + face_looks_ready: false, builder: None, bvh: None, build_used: 0, @@ -682,8 +686,20 @@ impl ImageTask { let Some(indices) = body.mesh.triangles.get(self.triangle) else { self.body += 1; self.triangle = 0; + self.face_looks_ready = false; return Ok(()); }; + if !self.face_looks_ready { + // Built once per body instead of scanning `faces` for every triangle. + // The first entry for a face wins, as the scan this replaces did. + self.work.charge(body.faces.len() as u64, &self.cancel).map_err(error)?; + self.face_looks.clear(); + self.face_looks.try_reserve_exact(body.faces.len()).map_err(|_| error(TraceError::AllocationFailed))?; + self.face_looks.extend(body.faces.iter().enumerate().map(|(index, look)| (look.face, index))); + self.face_looks.sort_unstable(); + self.face_looks.dedup_by_key(|entry| entry.0); + self.face_looks_ready = true; + } let mut vertices = [Vec3::ZERO; 3]; let mut normals = [Vec3::ZERO; 3]; for ((p, n), i) in vertices.iter_mut().zip(normals.iter_mut()).zip(indices) { @@ -693,20 +709,14 @@ impl ImageTask { let face = body.mesh.tri_face.get(self.triangle).copied(); let mut color = body.color; let mut surface = body.surface; - if let Some(look) = body.faces.get(self.face_cursor) { - self.face_cursor += 1; - if Some(look.face) == face { - self.chosen = Some(look.clone()); - self.face_cursor = body.faces.len(); - } else { - return Ok(()); - } - } - if let Some(look) = self.chosen.take() { + let look = face + .and_then(|face| self.face_looks.binary_search_by_key(&face, |entry| entry.0).ok()) + .and_then(|at| self.face_looks.get(at)) + .and_then(|entry| body.faces.get(entry.1)); + if let Some(look) = look { color = look.color; surface = look.surface; } - self.face_cursor = 0; let surface = match surface { Some(s) => s, None => OpaqueSurface::new(Vec3::new(srgb8_to_linear(color[0]), srgb8_to_linear(color[1]), srgb8_to_linear(color[2])), 0.0, 0.7, 1.5) diff --git a/crates/render/src/raytrace/image_tests.rs b/crates/render/src/raytrace/image_tests.rs index eda9e174d..66742ac37 100644 --- a/crates/render/src/raytrace/image_tests.rs +++ b/crates/render/src/raytrace/image_tests.rs @@ -351,6 +351,69 @@ fn triangle_task(cancel: CancelToken) -> ImageTask { ImageTask::new(scene, request, cancel, Default::default()).unwrap() } #[test] +fn face_looks_cost_one_unit_per_triangle_and_the_first_entry_wins() { + use std::sync::Arc; + let (columns, rows) = (8u32, 4u32); + let mut positions = Vec::new(); + for y in 0..=rows { + for x in 0..=columns { + positions.push(Vec3::new(f64::from(x) * 5.0 - 20.0, f64::from(y) * 5.0 - 10.0, 0.0)); + } + } + let (mut triangles, mut tri_face) = (Vec::new(), Vec::new()); + for y in 0..rows { + for x in 0..columns { + let a = y * (columns + 1) + x; + triangles.extend([[a, a + 1, a + columns + 2], [a, a + columns + 2, a + columns + 1]]); + tri_face.extend([y * columns + x; 2]); + } + } + let count = positions.len(); + let mesh = solidcraft_geom::Mesh { positions, normals: vec![Vec3::Z; count], triangles, tri_face, ..Default::default() }; + let look = |face: u32, color: [u8; 3]| crate::FaceAppearance { face, color, opacity: 1.0, surface: None, transmission: None }; + let mut faces: Vec<_> = (0..columns * rows).step_by(2).map(|face| look(face, [face as u8 * 8, 100, 200])).collect(); + // Later duplicates never replace the first entry for a face. + faces.extend([look(2, [1, 2, 3]), look(4, [4, 5, 6])]); + let entries = faces.len() as u64; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "face look fixture".into(), + mesh: Arc::new(mesh), + color: [220; 3], + opacity: 1.0, + surface: None, + faces, + }], + bounds, + }; + let mut request = request(); + request.camera.distance = 60.0; + request.camera.set_view(crate::StandardView::Top); + let mut task = ImageTask::new(scene, request, CancelToken::default(), Default::default()).unwrap(); + let before = task.work.used(); + for _ in 0..10_000 { + if task.builder.is_some() || task.bvh.is_some() { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(task.builder.is_some() || task.bvh.is_some(), "preparation did not finish"); + let triangles = u64::from(2 * columns * rows); + // One unit per triangle and per face entry, plus the end of the body and the + // hand-over to the BVH builder; scanning the entries per triangle cost ~T*F. + assert_eq!(task.work.used() - before, triangles + entries + 2); + let surface = + |c: [u8; 3]| OpaqueSurface::new(Vec3::new(srgb8_to_linear(c[0]), srgb8_to_linear(c[1]), srgb8_to_linear(c[2])), 0.0, 0.7, 1.5).unwrap(); + assert_eq!(task.looks.len() as u64, triangles); + for look in &task.looks { + let face = look.face.unwrap(); + let expected = if face % 2 == 0 { [face as u8 * 8, 100, 200] } else { [220; 3] }; + assert_eq!(look.surface, surface(expected), "face {face}"); + } +} +#[test] fn build_primary_and_shadows_share_cumulative_work_and_exhaust_atomically() { let mut task = triangle_task(CancelToken::default()); let mut previous = 0; diff --git a/crates/render/src/raytrace/lighting.rs b/crates/render/src/raytrace/lighting.rs index 0b9bdf1bf..a5ba5adcb 100644 --- a/crates/render/src/raytrace/lighting.rs +++ b/crates/render/src/raytrace/lighting.rs @@ -2,7 +2,8 @@ //! Colours are linear sRGB; intensity is relative radiance, not watts or illuminance. //! Visibility is supplied separately for every light by the ray-tracing consumer. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::surface::{OpaqueSurface, unit_direction}; diff --git a/crates/render/src/raytrace/mod.rs b/crates/render/src/raytrace/mod.rs index bce13e980..45a834fc1 100644 --- a/crates/render/src/raytrace/mod.rs +++ b/crates/render/src/raytrace/mod.rs @@ -5,7 +5,8 @@ //! or third-party ray-tracer implementation is used. See `docs/render-raytrace-core.md`. use crate::job::CancelToken; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; mod anisotropic_faces; pub mod area; diff --git a/crates/render/src/raytrace/prepared.rs b/crates/render/src/raytrace/prepared.rs index 14cd870ac..89bf9904d 100644 --- a/crates/render/src/raytrace/prepared.rs +++ b/crates/render/src/raytrace/prepared.rs @@ -1,7 +1,8 @@ //! Borrowed prepared-scene contract shared by bounded transport consumers. use super::{Bvh, Hit, MAX_DISTANCE_MM, Ray, Result, TraceError}; use crate::{ProductScene, surface::OpaqueSurface}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; #[derive(Clone, Copy)] pub struct PreparedPrimitive { diff --git a/crates/render/src/raytrace/punctual.rs b/crates/render/src/raytrace/punctual.rs index 4eed08f9e..5cc3201fb 100644 --- a/crates/render/src/raytrace/punctual.rs +++ b/crates/render/src/raytrace/punctual.rs @@ -1,7 +1,8 @@ //! Original relative point/spot response. Coordinates/reference distances are mm. //! No lumen, lux, watts, measured CCT, IES or glTF photometry is implied. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use super::{Ray, Result, TraceError, bounded, lighting::MAX_LIGHT_INTENSITY, prepared::SharedHit, unit}; diff --git a/crates/render/src/raytrace/reflection.rs b/crates/render/src/raytrace/reflection.rs index 1c04ca84c..958f36267 100644 --- a/crates/render/src/raytrace/reflection.rs +++ b/crates/render/src/raytrace/reflection.rs @@ -2,7 +2,8 @@ use super::{Result, TraceError}; use crate::anisotropic_surface::{AnisotropicSurface, VisualFrame}; use crate::surface::{OpaqueSurface, unit_direction}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; #[cfg(test)] use std::f64::consts::{PI, TAU}; #[derive(Clone, Copy, Debug)] @@ -133,6 +134,7 @@ mod vndf_tests; #[cfg(test)] mod tests { use super::{OpaqueSurface, PI, Vec3, hash_variates as variates, mirror, rough_specular}; + use solidcraft_geom::prelude::*; fn white() -> OpaqueSurface { OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap() } diff --git a/crates/render/src/scene.rs b/crates/render/src/scene.rs index 79744b516..f0699ebcd 100644 --- a/crates/render/src/scene.rs +++ b/crates/render/src/scene.rs @@ -4,9 +4,11 @@ use std::sync::Arc; -use solidcraft_geom::{Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; use crate::SceneAnalysis; +use crate::hatch::{HATCH_COLOURS, Hatch}; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Rgb(pub u8, pub u8, pub u8); @@ -27,12 +29,17 @@ pub struct SceneMesh { /// drawn see-through, so what lies inside it shows, as the viewport draws glass. A body /// without an appearance of its own is solid. pub opacity: f32, + /// The body encloses a volume (a solid, a closed mesh); an open one (a surface body, a solid + /// with faces left out) has no inside, so a section gives it no cap. + pub closed: bool, + /// The hatch of its cut face when the scene hatches by part ([`Scene::part_hatch`]). + pub hatch: Hatch, } impl SceneMesh { /// A solid body in `color`, with no face of its own look. pub fn solid(mesh: Arc, color: Rgb) -> SceneMesh { - SceneMesh { mesh, color, face_colors: Vec::new(), opacity: 1.0 } + SceneMesh { mesh, color, face_colors: Vec::new(), opacity: 1.0, closed: true, hatch: Hatch(0) } } /// Is the body drawn see-through? (Its opacity is below [`SEE_THROUGH`].) @@ -84,6 +91,9 @@ pub struct Scene { pub cap: Option, /// The section cap without its hatch: plain, in the body's own colour. pub plain_cap: bool, + /// Each cut body hatched its own way ([`SceneMesh::hatch`]), in these colours (the first + /// the cap's own); `None`: every cut face in [`Scene::cap`] at 45 degrees. + pub part_hatch: Option<[Rgb; HATCH_COLOURS]>, /// A surface analysis shading the meshes (zebra, draft, curvature map, ...). pub analysis: Option, } @@ -91,6 +101,10 @@ pub struct Scene { /// The section cap's default tint, as in the viewport. pub const SECTION_CAP: Rgb = Rgb(214, 128, 72); +/// The section hatch's other colours by default, as in the viewport: a steel and a sage that tint +/// a cut face about as strongly as the cap does, so the cut stays calm. +pub const SECTION_HATCH: [Rgb; HATCH_COLOURS - 1] = [Rgb(84, 138, 168), Rgb(108, 180, 126)]; + /// RGBA pixels (`w × h`) to PNG bytes. pub fn png(w: usize, h: usize, rgba: Vec) -> Option> { let img = image::RgbaImage::from_raw(u32::try_from(w).ok()?, u32::try_from(h).ok()?, rgba)?; diff --git a/crates/render/src/sheet_image_tests.rs b/crates/render/src/sheet_image_tests.rs index 58bee3a5e..658fcf79c 100644 --- a/crates/render/src/sheet_image_tests.rs +++ b/crates/render/src/sheet_image_tests.rs @@ -1,7 +1,7 @@ use std::io::Cursor; use image::{DynamicImage, ImageFormat, RgbaImage}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use super::*; diff --git a/crates/render/src/stage.rs b/crates/render/src/stage.rs index 56ec8808b..134860bc7 100644 --- a/crates/render/src/stage.rs +++ b/crates/render/src/stage.rs @@ -7,7 +7,9 @@ use crate::{ surface::OpaqueSurface, }; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use solidcraft_geom::{Aabb3, Mesh}; use std::{collections::BTreeSet, fmt, sync::Arc}; pub const MAX_STAGE_PANELS: usize = 32; diff --git a/crates/render/src/studio.rs b/crates/render/src/studio.rs index 435c5daaa..99c883db6 100644 --- a/crates/render/src/studio.rs +++ b/crates/render/src/studio.rs @@ -1,7 +1,8 @@ //! Original fixed direct-light studio used by opaque product preview consumers. //! Relative linear radiance, not a calibrated illuminance or an HDRI environment. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::surface::{OpaqueSurface, SurfaceError, unit_direction}; diff --git a/crates/render/src/surface.rs b/crates/render/src/surface.rs index 0ebb8612b..69a629b61 100644 --- a/crates/render/src/surface.rs +++ b/crates/render/src/surface.rs @@ -1,9 +1,10 @@ //! Bounded opaque metallic/roughness surfaces in linear sRGB. //! This numerical contract does not enable a renderer or persist appearances. +use solidcraft_geom::prelude::*; use std::f64::consts::PI; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; /// Lowest admitted perceptual roughness. Perfect delta mirrors need another integrator. pub const MIN_ROUGHNESS: f64 = 0.045; diff --git a/crates/render/src/surface_patterns.rs b/crates/render/src/surface_patterns.rs index cac18ae26..9f8c20da0 100644 --- a/crates/render/src/surface_patterns.rs +++ b/crates/render/src/surface_patterns.rs @@ -1,7 +1,8 @@ //! Original periodic preview fields in an explicit world-space millimetre frame. //! Only roughness and shading normals change; geometry and visibility do not. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use std::f64::consts::TAU; use crate::job::{ErrorCode, JobError, Result}; diff --git a/crates/render/src/transmission.rs b/crates/render/src/transmission.rs index d53ab1c61..895df0376 100644 --- a/crates/render/src/transmission.rs +++ b/crates/render/src/transmission.rs @@ -1,5 +1,6 @@ //! Bounded optical data and original f64 dielectric transport oracles. Units are mm. -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; #[path = "subsurface.rs"] pub mod subsurface; use subsurface::Subsurface; diff --git a/crates/sketch/Cargo.toml b/crates/sketch/Cargo.toml index e02582919..77b50ca8b 100644 --- a/crates/sketch/Cargo.toml +++ b/crates/sketch/Cargo.toml @@ -17,6 +17,7 @@ name = "solve_profile" required-features = ["solver-profiling"] [dependencies] +solidcore-record = { workspace = true } harfrust = "0.12" solidcraft-geom = { workspace = true } serde = { workspace = true } diff --git a/crates/sketch/examples/solve_bench.rs b/crates/sketch/examples/solve_bench.rs index cf31f9c78..c81595b65 100644 --- a/crates/sketch/examples/solve_bench.rs +++ b/crates/sketch/examples/solve_bench.rs @@ -5,8 +5,10 @@ use std::time::Instant; -use solidcraft_geom::Vec2; -use solidcraft_sketch::{Analysis, Budget, ConstraintKind, Hold, Sketch, SolveReport, solve, solve_with}; +use solidcore_record::Vec2; +use solidcraft_sketch::{ + Analysis, Budget, ConstraintKind, Hold, PatternAlignment, Sketch, SketchPattern, SketchPatternKind, SolveReport, solve, solve_with, +}; /// A small deterministic generator for the start offsets. struct Lcg(u64); @@ -66,6 +68,33 @@ fn strip(n: usize) -> Result<(Sketch, usize), Box> { Ok((sk, bottom[0])) } +/// A slot (two arcs joined by two lines) copied `count` times around the origin by a circular +/// pattern. Returns the sketch and the seed's first arc start point. +fn slot_pattern(count: usize) -> Result<(Sketch, usize), Box> { + let mut sk = Sketch::new(); + let center = sk.add_point(Vec2::ZERO, None)?; + sk.add_constraint(ConstraintKind::Fix { p: center }, None)?; + let (c0, c1) = (Vec2::new(200.0, 0.0), Vec2::new(210.0, 0.0)); + let p = [c0 + Vec2::new(0.0, -2.0), c0 + Vec2::new(0.0, 2.0), c1 + Vec2::new(0.0, -2.0), c1 + Vec2::new(0.0, 2.0)]; + let pts: Vec = p.iter().map(|q| sk.add_point(*q, None)).collect::>()?; + let left = sk.add_arc(c0, p[1], p[0], [None, Some(pts[1]), Some(pts[0])], None)?; + let right = sk.add_arc(c1, p[2], p[3], [None, Some(pts[2]), Some(pts[3])], None)?; + let bottom = sk.add_line_pts(pts[0], pts[2], None)?; + let top = sk.add_line_pts(pts[1], pts[3], None)?; + let entities = [left, right, bottom, top].iter().filter_map(|i| sk.curves.get(*i).map(|c| c.id.clone())).collect(); + let center_id = sk.points.get(center).map(|q| q.id.clone()).ok_or("missing center")?; + let kind = SketchPatternKind::Circular { center: center_id, count, angle: 360.0, alignment: PatternAlignment::Right, reversed: false }; + let id = sk.fresh("pat")?; + sk.patterns.push(SketchPattern { id, entities, kind: kind.clone(), count_expression: None, instances: vec![], expressions: Default::default() }); + sk.update_pattern(0, kind)?; + Ok((sk, pts[1])) +} + +/// A hash of the whole sketch, every number to the bit, to compare solver output between builds. +fn fingerprint(sk: &Sketch) -> u64 { + format!("{sk:?}").bytes().fold(0xcbf29ce484222325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3)) +} + /// Best of `reps` solves of a copy of `sk` (ms) and the last report. fn time(sk: &Sketch, reps: usize, f: impl Fn(&mut Sketch) -> SolveReport) -> (f64, SolveReport) { let mut best = f64::MAX; @@ -104,5 +133,30 @@ fn main() -> Result<(), Box> { let (full, _) = time(&sk, 5, solve); println!("| {n} rectangles | {} | {frame:.2} ({:?}) | {full:.2} |", sk.points.len(), rep.status); } + println!(); + println!("| circular slot pattern | curves | points | drag frame on another line ms | drag frame on the seed ms | output |"); + println!("|---|---|---|---|---|---|"); + for count in [100usize, 500] { + let (mut sk, seed) = slot_pattern(count)?; + let a = sk.add_point(Vec2::new(-500.0, -500.0), None)?; + let b = sk.add_point(Vec2::new(-480.0, -500.0), None)?; + let l = sk.add_line_pts(a, b, None)?; + sk.add_constraint(ConstraintKind::Horizontal { l }, None)?; + let drag = |point: usize| -> (f64, u64) { + let mut start = sk.clone(); + if let Some(p) = start.points.get_mut(point) { + p.pos += Vec2::new(0.5, 0.3); + } + let hold = Hold { points: vec![point], radii: vec![] }; + let frame = |k: &mut Sketch| solve_with(k, &hold, None, Analysis::StatusOnly, Some(&mut Budget::frame())); + let (ms, _) = time(&start, 5, frame); + frame(&mut start); + (ms, fingerprint(&start)) + }; + let (other, other_out) = drag(b); + // Solving the whole pattern takes seconds at 500 copies. + let (on_seed, seed_out) = if count <= 100 { drag(seed) } else { (f64::NAN, 0) }; + println!("| {count} slots | {} | {} | {other:.2} | {on_seed:.2} | {other_out:016x} {seed_out:016x} |", sk.curves.len(), sk.points.len()); + } Ok(()) } diff --git a/crates/sketch/examples/solve_profile.rs b/crates/sketch/examples/solve_profile.rs index f41e12af6..068b56a3d 100644 --- a/crates/sketch/examples/solve_profile.rs +++ b/crates/sketch/examples/solve_profile.rs @@ -3,7 +3,7 @@ use std::{error::Error, io::Write, path::PathBuf, time::Instant}; use serde::Serialize; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_sketch::{ Analysis, ConstraintKind, DrivingValues, Hold, Sketch, SolveReport, profiling::{Counters, SolveProfile, Timings, capture}, diff --git a/crates/sketch/src/circle_edge_tests.rs b/crates/sketch/src/circle_edge_tests.rs index 506c57f93..65184756a 100644 --- a/crates/sketch/src/circle_edge_tests.rs +++ b/crates/sketch/src/circle_edge_tests.rs @@ -2,7 +2,8 @@ //! arcs (#4064): solved numerically and by construction, measured, drawn between the edge points //! that face each other, saved, and refused on other kinds of curve. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::tests::v; use crate::*; diff --git a/crates/sketch/src/coincident_tangent_tests.rs b/crates/sketch/src/coincident_tangent_tests.rs index da4e15a2e..f865bda5e 100644 --- a/crates/sketch/src/coincident_tangent_tests.rs +++ b/crates/sketch/src/coincident_tangent_tests.rs @@ -3,7 +3,8 @@ //! (distance from the centre equals the radius) is a double root there, so it converged to only //! sqrt(residual) of tangent and lost a row of rank when the start already was tangent. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::tests::{Lcg, v}; use crate::*; diff --git a/crates/sketch/src/construct.rs b/crates/sketch/src/construct.rs index 53be92b62..80de1b8a0 100644 --- a/crates/sketch/src/construct.rs +++ b/crates/sketch/src/construct.rs @@ -40,7 +40,7 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use crate::decompose::{Budget, Decomposition, enqueue}; use crate::loci::{MAX_LOCI, Reading, Rel, View, place, radii, read}; diff --git a/crates/sketch/src/construct_rounds_tests.rs b/crates/sketch/src/construct_rounds_tests.rs index ec7442d99..566eeb633 100644 --- a/crates/sketch/src/construct_rounds_tests.rs +++ b/crates/sketch/src/construct_rounds_tests.rs @@ -5,7 +5,8 @@ //! and its sweep, every line its direction, every point its side of its lines. //! Deterministic (fixed LCG seeds), no timing. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::construct::{Placement, seed}; use crate::decompose::Budget; diff --git a/crates/sketch/src/construct_tests.rs b/crates/sketch/src/construct_tests.rs index 503a1152b..13e9e8d84 100644 --- a/crates/sketch/src/construct_tests.rs +++ b/crates/sketch/src/construct_tests.rs @@ -2,7 +2,8 @@ //! points that keep a degree of freedom, drag continuity, and hostile input. Deterministic //! (fixed LCG seeds), no timing. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::construct::{Placement, seed}; use crate::decompose::Budget; diff --git a/crates/sketch/src/continuation_tests.rs b/crates/sketch/src/continuation_tests.rs index 13c418058..4c530ed8e 100644 --- a/crates/sketch/src/continuation_tests.rs +++ b/crates/sketch/src/continuation_tests.rs @@ -2,7 +2,8 @@ //! triangles joined by three links, left to the iteration by the construction) under random //! dimension edits from its previous solved state, with every failure that remains proven //! infeasible; and the solve without continuation when nothing it could help with changed. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::construct::switch; use crate::model::{ConstraintKind, Sketch}; diff --git a/crates/sketch/src/cursor.rs b/crates/sketch/src/cursor.rs index 366f7c5d9..3a22b0dcc 100644 --- a/crates/sketch/src/cursor.rs +++ b/crates/sketch/src/cursor.rs @@ -9,7 +9,8 @@ use crate::{ linalg::{Mat, rref}, union_find::{find, union}, }; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; const MAX_VARIABLES: usize = 400; const MAX_STEPS: usize = 96; diff --git a/crates/sketch/src/curves.rs b/crates/sketch/src/curves.rs index 66a7fb272..0ef36d7f5 100644 --- a/crates/sketch/src/curves.rs +++ b/crates/sketch/src/curves.rs @@ -2,9 +2,10 @@ //! control points) and conics (rational quadratic Béziers). Evaluation works on positions so //! the solver can use it with trial values. +use solidcraft_geom::prelude::*; use std::f64::consts::TAU; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; /// Polyline samples per spline span / conic / ellipse quarter. const SPAN_SAMPLES: usize = 24; @@ -153,7 +154,7 @@ pub fn spline_point(p: &[Vec2], control: bool, degree: u8, t: f64) -> Vec2 { return p.first().copied().unwrap_or_default(); } if control { - return bspline_at(p, degree.clamp(1, solidcraft_geom::MAX_BEZIER_DEGREE as u8) as usize, t); + return bspline_at(p, degree.clamp(1, solidcore_record::MAX_BEZIER_DEGREE as u8) as usize, t); } let spans = fit_spans(p); let n = spans.len().max(1); @@ -190,7 +191,12 @@ pub fn fit_beziers(p: &[Vec2]) -> Vec<[Vec2; 4]> { pub fn fit_beziers_mode(p: &[Vec2], periodic: bool) -> crate::model::Result> { if periodic { crate::periodic_beziers(p) } else { Ok(fit_beziers(p)) } } -pub fn spline_point_mode(p: &[Vec2], control: bool, degree: u8, periodic: bool, t: f64) -> Vec2 { +/// Point of a spline at `t` in [0, 1]: through its points, over them as a clamped uniform +/// B-spline, or with its own knots and weights (`nurbs`). +pub fn spline_point_mode(p: &[Vec2], control: bool, degree: u8, periodic: bool, nurbs: Option<&crate::Nurbs>, t: f64) -> Vec2 { + if let Some(nurbs) = nurbs { + return nurbs.point(p, degree, t).unwrap_or_else(|| p.first().copied().unwrap_or_default()); + } if !periodic { return spline_point(p, control, degree, t); } @@ -211,7 +217,11 @@ pub fn spline_point_mode(p: &[Vec2], control: bool, degree: u8, periodic: bool, let t = (remaining / lengths[i]).clamp(0.0, 1.0); a * (1.0 - t).powi(3) + b * (3.0 * t * (1.0 - t).powi(2)) + c * (3.0 * t * t * (1.0 - t)) + d * t.powi(3) } -pub fn spline_polyline_mode(p: &[Vec2], control: bool, degree: u8, periodic: bool) -> Vec { +/// Polyline of a spline, as [`spline_point_mode`] reads it. +pub fn spline_polyline_mode(p: &[Vec2], control: bool, degree: u8, periodic: bool, nurbs: Option<&crate::Nurbs>) -> Vec { + if let Some(nurbs) = nurbs { + return nurbs.polyline(p, degree); + } if !periodic { return spline_polyline(p, control, degree); } @@ -292,7 +302,7 @@ pub fn spline_polyline(p: &[Vec2], control: bool, degree: u8) -> Vec { return p.to_vec(); } if control { - return bspline_polyline(p, degree.clamp(1, solidcraft_geom::MAX_BEZIER_DEGREE as u8) as usize); + return bspline_polyline(p, degree.clamp(1, solidcore_record::MAX_BEZIER_DEGREE as u8) as usize); } let mut out = Vec::new(); for (p0, p1, t0, t1) in fit_spans(p) { @@ -307,6 +317,7 @@ pub fn spline_polyline(p: &[Vec2], control: bool, degree: u8) -> Vec { } /// Unit tangent of a spline at its start (`at_end == false`) or end, pointing along the curve. +/// A control spline's runs along its end leg whatever its knots and (positive) weights. pub fn spline_end_tangent(p: &[Vec2], control: bool, at_end: bool) -> Option { let n = p.len(); if n < 2 { diff --git a/crates/sketch/src/decompose.rs b/crates/sketch/src/decompose.rs index 0e85462a0..859ab2868 100644 --- a/crates/sketch/src/decompose.rs +++ b/crates/sketch/src/decompose.rs @@ -55,10 +55,11 @@ //! down well and a branch the reference does not decide is unknown, so neither is merged //! (the solver starts those points where they are). +use solidcraft_geom::prelude::*; use std::collections::btree_map::Entry; use std::collections::{BTreeMap, BTreeSet, VecDeque}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use crate::loci::{Locus, Reading, Rel, Span, View, crossing, mag, place, side}; use crate::union_find::{find, union}; diff --git a/crates/sketch/src/degenerate_line_tests.rs b/crates/sketch/src/degenerate_line_tests.rs index 4ec991510..c96cabcd5 100644 --- a/crates/sketch/src/degenerate_line_tests.rs +++ b/crates/sketch/src/degenerate_line_tests.rs @@ -7,7 +7,8 @@ //! are ~1. Dragging an endpoint of `l1` must keep the sketch solved: the cursor may not leave the //! constraint manifold, and the rank analysis may not hide `l1`'s coupling below its tolerance. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::{Analysis, ConstraintKind, Hold, Sketch, move_point_towards, solve_with}; @@ -60,3 +61,41 @@ fn dragging_the_midpoint_line_end_keeps_the_sketch_solved() { let off = (at.y.atan2(at.x) - 50f64.to_radians()).abs(); assert!(off < 1e-3, "l1.end went to {at:?} (off its line by {off} rad)"); } + +/// An infinite reference can have very close defining points in a saved sketch. Its +/// horizontal/vertical constraint still fixes its visible direction, not just the tiny +/// distance between the defining points (#11001). +#[test] +fn an_angle_keeps_a_short_infinite_reference_horizontal_or_vertical() { + for (vertical, sign, origin) in [ + (false, 1.0, v(0.0, 0.0)), + (true, 1.0, v(0.0, 0.0)), + (false, -1.0, v(0.0, 0.0)), + (true, -1.0, v(0.0, 0.0)), + (false, 1.0, v(25.0, -17.0)), + (true, 1.0, v(25.0, -17.0)), + ] { + for length in [6.36e-8, 1.0] { + let mut sk = Sketch::new(); + sk.points[0].pos = origin; + let direction = (if vertical { v(0.0, 1.0) } else { v(1.0, 0.0) }) * sign; + let end = sk.add_point(origin + direction * length, None).unwrap(); + let arm_end = sk.add_point(origin + (if vertical { v(-10.0, 12.0) } else { v(12.0, 10.0) }) * sign, None).unwrap(); + let axis = sk.add_line_pts(0, end, Some("axis")).unwrap(); + sk.curves[axis].infinite = true; + sk.curves[axis].construction = true; + let arm = sk.add_line_pts(0, arm_end, Some("arm")).unwrap(); + let constraint = if vertical { ConstraintKind::Vertical { l: axis } } else { ConstraintKind::Horizontal { l: axis } }; + sk.add_constraint(constraint, None).unwrap(); + sk.add_constraint(ConstraintKind::Angle { a: axis, b: arm, value: 30f64.to_radians(), flip: false }, None).unwrap(); + + let report = crate::solve(&mut sk); + assert!(report.ok(), "vertical={vertical}, length={length}: {report:?}"); + let actual = (sk.points[end].pos - origin).normalized().expect("the reference retains a direction"); + assert!(actual.dist(direction) < 1e-6, "vertical={vertical}, length={length}: reference rotated to {actual:?}"); + let arm_direction = (sk.points[arm_end].pos - origin).normalized().unwrap(); + let angle = actual.cross(arm_direction).atan2(actual.dot(arm_direction)); + assert!((angle - 30f64.to_radians()).abs() < 1e-6, "the free line must satisfy the angle: {angle}"); + } + } +} diff --git a/crates/sketch/src/dims.rs b/crates/sketch/src/dims.rs index 050c1a356..059baf0fd 100644 --- a/crates/sketch/src/dims.rs +++ b/crates/sketch/src/dims.rs @@ -9,7 +9,8 @@ //! //! [`Constraint::text`]: crate::Constraint::text -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::model::{ConstraintKind, CurveKind, Sketch, TwoCircles}; use crate::union_find::{find, union}; @@ -122,7 +123,7 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option { } } ArcSweep { c, .. } => match sk.segs(c).first()? { - solidcraft_geom::Seg2::Arc { center, start, sweep, .. } => { + solidcore_record::Seg2::Arc { center, start, sweep, .. } => { DimFrame::Angular { vertex: *center, d0: Vec2::from_angle(*start), sweep: *sweep } } _ => return None, @@ -175,7 +176,7 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option { let (radius, arc) = match sk.curves.get(c)?.kind { CurveKind::Ellipse { r, .. } => (r, None), CurveKind::Arc { .. } => match sk.segs(c).first()? { - solidcraft_geom::Seg2::Arc { radius, start, sweep, .. } => (*radius, Some((*start, *sweep))), + solidcore_record::Seg2::Arc { radius, start, sweep, .. } => (*radius, Some((*start, *sweep))), _ => return None, }, _ => (sk.radius(c)?, None), @@ -183,7 +184,7 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option { DimFrame::Radial { center: sk.center(c)?, radius, diameter: matches!(k, Diameter { .. }), arc } } ArcLength { c, .. } => match sk.segs(c).first()? { - solidcraft_geom::Seg2::Arc { center, radius, start, sweep } => { + solidcore_record::Seg2::Arc { center, radius, start, sweep } => { DimFrame::ArcLength { center: *center, radius: *radius, start: *start, sweep: *sweep } } _ => return None, diff --git a/crates/sketch/src/ends.rs b/crates/sketch/src/ends.rs index f63328141..30dfa2eb7 100644 --- a/crates/sketch/src/ends.rs +++ b/crates/sketch/src/ends.rs @@ -9,7 +9,9 @@ //! An end is tied when it is shared with another curve's end, joined to one by coincident //! constraints, or held on a curve (point on curve, midpoint). -use solidcraft_geom::{Aabb2, Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::Aabb2; +use solidcraft_geom::prelude::*; use crate::model::{ConstraintKind, CurveKind, Sketch}; use crate::union_find::{find, union}; diff --git a/crates/sketch/src/ends_tests.rs b/crates/sketch/src/ends_tests.rs index 9cd7606ec..75f208e94 100644 --- a/crates/sketch/src/ends_tests.rs +++ b/crates/sketch/src/ends_tests.rs @@ -1,6 +1,6 @@ //! Open and untied ends of profile curves. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use crate::{ConstraintKind, EndTouch, Sketch, find_profiles, loose_ends}; diff --git a/crates/sketch/src/equation.rs b/crates/sketch/src/equation.rs index 90949072a..d36c3b5dc 100644 --- a/crates/sketch/src/equation.rs +++ b/crates/sketch/src/equation.rs @@ -5,17 +5,44 @@ //! still share its end points. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use crate::model::{CurveKind, Result, Sketch, SketchError}; /// Longest formula or range expression an equation curve takes (characters). pub const MAX_EQUATION_TEXT: usize = 1024; +/// What the variable of an equation curve is in its formulas (#9333). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum VariableUnit { + /// A plain number: `sin(t)` reads it in radians, and a range in a unit gives up that unit. + #[default] + Number, + /// A length, as the range is: `a ^ 2 / (4 * t)` is a length when `a` is one. + Range, +} + +impl VariableUnit { + /// The word a command or a design spells it with. + pub fn parse(word: &str) -> Option { + match word { + "number" => Some(VariableUnit::Number), + "range" => Some(VariableUnit::Range), + _ => None, + } + } + + fn is_number(&self) -> bool { + *self == VariableUnit::Number + } +} + /// A curve drawn from formulas: x(t) and y(t) over t from `start` to `end`, or (with `x` left /// out) the explicit y = f(x) over x from `start` to `end`. The formulas use the design's -/// expression language and parameters; the variable is a plain number, so `sin(t)` reads it in -/// radians, and a result without a unit is in the design's length unit. +/// expression language and parameters; the variable is a plain number unless `variable_unit` +/// says otherwise, so `sin(t)` reads it in radians, and a result without a unit is in the +/// design's length unit. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EquationCurve { /// The fit point spline it places (a curve id of the sketch). @@ -31,6 +58,9 @@ pub struct EquationCurve { /// How far (mm) the spline may stray from the formulas: the number of points was chosen for /// it when the curve was made or last edited. pub tolerance: f64, + /// What the variable is in the formulas. Left out of the file for a plain number. + #[serde(default, skip_serializing_if = "VariableUnit::is_number")] + pub variable_unit: VariableUnit, } impl EquationCurve { @@ -68,7 +98,7 @@ impl Sketch { /// `equation` kept beside it. Returns the curve's index. pub fn add_equation_curve(&mut self, at: &[Vec2], closed: bool, mut equation: EquationCurve) -> Result { let pts = self.equation_points(at, closed, None)?; - let curve = self.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: closed }, None)?; + let curve = self.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: closed, nurbs: None }, None)?; equation.curve = self.curves.get(curve).map(|c| c.id.clone()).ok_or_else(|| SketchError::Invalid("the new curve is missing".into()))?; self.equations.push(equation); Ok(curve) @@ -89,7 +119,7 @@ impl Sketch { let pts = self.equation_points(at, closed, Some((first, keep_end)))?; let unused: Vec = old.iter().copied().filter(|p| !pts.contains(p)).collect(); if let Some(c) = self.curves.get_mut(curve) { - c.kind = CurveKind::Spline { pts, control: false, degree: 3, periodic: closed }; + c.kind = CurveKind::Spline { pts, control: false, degree: 3, periodic: closed, nurbs: None }; } // The old points no other curve uses (the in-between points, and an end a closed curve // no longer has) go, with the constraints on them. diff --git a/crates/sketch/src/font_tests.rs b/crates/sketch/src/font_tests.rs index fc1c1ac46..1fd162d89 100644 --- a/crates/sketch/src/font_tests.rs +++ b/crates/sketch/src/font_tests.rs @@ -2,9 +2,10 @@ //! known by hand; the repository's second font (BIZ UDPGothic, `assets/fonts/biz-udp-gothic`) stands for //! a real one. +use solidcraft_geom::prelude::*; use std::path::PathBuf; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use crate::fonts::find_family_in; use crate::tests::v; diff --git a/crates/sketch/src/freeform_offset.rs b/crates/sketch/src/freeform_offset.rs index fde3254ae..5226d3e51 100644 --- a/crates/sketch/src/freeform_offset.rs +++ b/crates/sketch/src/freeform_offset.rs @@ -6,7 +6,8 @@ //! identical parameter speeds; stored nodes and interpolation remain unchanged. use crate::{CurveKind, Sketch, SketchError, fit_beziers_mode}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::prelude::*; mod trim; pub use trim::FreeformOffsetOutput; @@ -140,7 +141,7 @@ impl H { let (points, weights) = match *seg { Seg2::Line { a, b } => (vec![a, b], vec![1.0; 2]), Seg2::Cubic { p0, p1, p2, p3 } => (vec![p0, p1, p2, p3], vec![1.0; 4]), - Seg2::Bezier { n, p } if (1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(&n) => { + Seg2::Bezier { n, p } if (1..=solidcore_record::MAX_BEZIER_DEGREE as u8).contains(&n) => { (p[..=usize::from(n)].to_vec(), vec![1.0; usize::from(n) + 1]) } Seg2::Conic { a, apex, b, w } if w.is_finite() && w > 0.0 => (vec![a, apex, b], vec![1.0, w, 1.0]), @@ -439,7 +440,7 @@ impl Sketch { } let output = self.curve_index(&record.output).ok_or_else(|| bad("offset output vanished"))?; match &self.curves[output].kind { - CurveKind::Spline { pts, control: false, degree: 3, periodic } + CurveKind::Spline { pts, control: false, degree: 3, periodic, .. } if *periodic == (record.certificate == 2) && (record.certificate != 2 || record.closed) && pts.len() == record.pieces * record.divisions + 1 @@ -484,7 +485,7 @@ impl Sketch { p.fixed = true; } } - let output = candidate.add_curve(CurveKind::Spline { pts: indices, control: false, degree: 3, periodic: closed }, None)?; + let output = candidate.add_curve(CurveKind::Spline { pts: indices, control: false, degree: 3, periodic: closed, nurbs: None }, None)?; candidate.freeform_offsets.push(FreeformOffset { source: source_id, output: candidate.curves[output].id.clone(), @@ -551,7 +552,7 @@ impl Sketch { return Err(bad("offset source topology changed")); } let old_indices = match &candidate.curves[output].kind { - CurveKind::Spline { pts, control: false, degree: 3, periodic } + CurveKind::Spline { pts, control: false, degree: 3, periodic, .. } if *periodic == (record.certificate == 2) && (record.certificate != 2 || record.closed) && pts.len() == record.pieces * record.divisions + 1 => @@ -583,7 +584,8 @@ impl Sketch { p.pos = pos; p.fixed = true; } - candidate.curves[output].kind = CurveKind::Spline { pts: indices, control: false, degree: 3, periodic: record.certificate == 2 }; + candidate.curves[output].kind = + CurveKind::Spline { pts: indices, control: false, degree: 3, periodic: record.certificate == 2, nurbs: None }; candidate.freeform_offsets[record_index].divisions = divisions; candidate.freeform_offsets[record_index].pieces = pieces; } @@ -632,7 +634,7 @@ mod tests { .into_iter() .map(|(x, y)| sk.add_point(Vec2::new(x, y), None).unwrap()) .collect(); - let source = sk.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: true }, None).unwrap(); + let source = sk.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: true, nurbs: None }, None).unwrap(); let original = sk.clone(); for (forward, distance) in [(true, 2.0), (false, -2.0)] { let mut sk = original.clone(); diff --git a/crates/sketch/src/freeform_offset/trim.rs b/crates/sketch/src/freeform_offset/trim.rs index 380f7ec71..3939cf50b 100644 --- a/crates/sketch/src/freeform_offset/trim.rs +++ b/crates/sketch/src/freeform_offset/trim.rs @@ -12,7 +12,8 @@ //! to its source. use super::{Certificate, H, MAX_OFFSET_WORK, MAX_PIECES, OFFSET_TOLERANCE, Result, bad, certify, normal_point}; use crate::{CurveKind, Sketch, fit_beziers}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::prelude::*; /// Samples of the plain offset used to find its crossings (whole chain). const MAX_SAMPLES: usize = 32_768; @@ -1080,7 +1081,7 @@ impl Sketch { pts.push(candidate.add_point(*p, None)?); } pts.push(end); - CurveKind::Spline { pts, control: false, degree: 3, periodic: false } + CurveKind::Spline { pts, control: false, degree: 3, periodic: false, nurbs: None } } Out::Arc { center, sweep, .. } => { let c = candidate.add_point(*center, None)?; @@ -1111,7 +1112,7 @@ mod tests { fn spline(coords: &[(f64, f64)], periodic: bool) -> (Sketch, usize) { let mut sk = Sketch::new(); let pts = coords.iter().map(|(x, y)| sk.add_point(Vec2::new(*x, *y), None).unwrap()).collect(); - let source = sk.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic }, None).unwrap(); + let source = sk.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic, nurbs: None }, None).unwrap(); (sk, source) } @@ -1210,8 +1211,9 @@ mod tests { for (k, b) in beziers.iter().enumerate() { let mid = [1, 2].map(|i| sk.add_point(Vec2::new(b[i].0, b[i].1), None).unwrap()); let end = if k + 1 == beziers.len() { first } else { sk.add_point(Vec2::new(b[3].0, b[3].1), None).unwrap() }; - let c = - sk.add_curve(CurveKind::Spline { pts: vec![start, mid[0], mid[1], end], control: true, degree: 3, periodic: false }, None).unwrap(); + let c = sk + .add_curve(CurveKind::Spline { pts: vec![start, mid[0], mid[1], end], control: true, degree: 3, periodic: false, nurbs: None }, None) + .unwrap(); order.push((c, true)); start = end; } diff --git a/crates/sketch/src/least_motion_tests.rs b/crates/sketch/src/least_motion_tests.rs index 875c7cd71..396070169 100644 --- a/crates/sketch/src/least_motion_tests.rs +++ b/crates/sketch/src/least_motion_tests.rs @@ -1,6 +1,7 @@ //! A solve with geometry held moves the rest as little as it can. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::{Analysis, ConstraintKind, Hold, Sketch, solve_with}; diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 5d64e8575..4e03efb98 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -28,6 +28,7 @@ pub mod linalg; mod link; mod loci; mod model; +mod nurbs; mod offset; mod offset_topology; mod paper_text; @@ -54,7 +55,7 @@ pub use dims::{ dim_reach, encode_text, }; pub use ends::{END_TOL, EndReport, EndTouch, UntiedEnd, loose_ends}; -pub use equation::{EquationCurve, MAX_EQUATION_TEXT}; +pub use equation::{EquationCurve, MAX_EQUATION_TEXT, VariableUnit}; pub use fonts::{ DEFAULT_FONT_FAMILY, FontData, check_family, fallback, families_in, find_style_in, font_data, font_data_styled, font_dirs, font_override_dirs, installed_families, set_font_file_check, @@ -65,6 +66,7 @@ pub use model::{ Constraint, ConstraintKind, Curve, CurveKind, MAX_CONSTRAINTS, MAX_COORD, MAX_CURVES, MAX_POINTS, PointExprs, SPoint, Sketch, SketchError, SketchView, TwoCircles, }; +pub use nurbs::Nurbs; pub use offset::OffsetChain; pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRoleKind, OffsetTopology}; pub use paper_text::{paper_fallback_notes, paper_font_note, paper_text, paper_text_in, paper_text_now}; @@ -83,7 +85,7 @@ pub use solver::{ }; pub use text::{MAX_TEXT_CHARS, TextAlign, TextMetrics, TextStyle, text_geometry, text_geometry_in, text_geometry_styled}; pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions}; -pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, WireArc, WireSpace, arc_from_3_points, arc_polyline, arc_sweep, fit_polyline}; +pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, WireArc, WireCurve, WireSpace, arc_from_3_points, arc_polyline, arc_sweep, fit_polyline}; #[cfg(test)] mod circle_edge_tests; diff --git a/crates/sketch/src/line_circle_tests.rs b/crates/sketch/src/line_circle_tests.rs index 0acbc3b4d..73a728ed9 100644 --- a/crates/sketch/src/line_circle_tests.rs +++ b/crates/sketch/src/line_circle_tests.rs @@ -2,7 +2,8 @@ //! construction, measured, kept on its side of the line through edits, and refused on other //! kinds of curve. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::tests::v; use crate::*; diff --git a/crates/sketch/src/link.rs b/crates/sketch/src/link.rs index dbdb8cc5f..d048bbeb8 100644 --- a/crates/sketch/src/link.rs +++ b/crates/sketch/src/link.rs @@ -7,7 +7,9 @@ //! constants; they still bound profiles and take constraints and dimensions like any curve. use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Aabb2, Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; +use solidcraft_geom::Aabb2; +use solidcraft_geom::prelude::*; use crate::model::{Curve, CurveKind, Result, Sketch, SketchError, in_range, radius_in_range}; @@ -134,10 +136,10 @@ impl LinkSource { /// Short description for messages and the browser. pub fn describe(&self) -> String { match self { - LinkSource::Edge { body, .. } => format!("edge of {body}"), - LinkSource::Face { body, .. } => format!("face of {body}"), + LinkSource::Edge { body, .. } => of_body("edge", body), + LinkSource::Face { body, .. } => of_body("face", body), LinkSource::Body { body } => body.clone(), - LinkSource::Vertex { body, .. } => format!("vertex of {body}"), + LinkSource::Vertex { body, .. } => of_body("vertex", body), LinkSource::SketchCurve { curve, .. } => format!("sketch curve {curve}"), LinkSource::SketchPoint { point, .. } => format!("sketch point {point}"), LinkSource::Origin => "origin".into(), @@ -146,8 +148,8 @@ impl LinkSource { LinkSource::Plane { name } => format!("{name} plane"), LinkSource::OnSurface { curve, .. } => format!("{curve} on a face"), LinkSource::Intersection { a, b } => format!("intersection of {} and {}", a.describe(), b.describe()), - LinkSource::Spun { body, .. } => format!("spun profile of {body}"), - LinkSource::Iso { body, .. } => format!("isoparametric curve of {body}"), + LinkSource::Spun { body, .. } => of_body("spun profile", body), + LinkSource::Iso { body, .. } => of_body("isoparametric curve", body), LinkSource::Text { text, .. } => format!("text \"{}\"", text.chars().take(20).collect::()), } } @@ -178,6 +180,13 @@ impl LinkSource { } } +/// The description of a source that names a body: "face of Body1", or the kind alone when the +/// reference names no body (a picked face is found by its geometry, and the body it belongs +/// to is not named in the reference). +fn of_body(kind: &str, body: &str) -> String { + if body.is_empty() { kind.to_string() } else { format!("{kind} of {body}") } +} + /// Half length of the line a sketch axis link produces. pub const SKETCH_AXIS_HALF: f64 = 100.0; @@ -238,12 +247,14 @@ pub enum LinkGeom { major: Vec2, minor: f64, }, - /// Spline through (`control == false`) or over (`control`) the points. + /// Spline through (`control == false`) or over (`control`) the points; a control spline + /// with its own knots and weights where it has them ([`crate::Nurbs`]). Spline { pts: Vec, control: bool, degree: u8, periodic: bool, + nurbs: Option, }, } @@ -257,11 +268,12 @@ impl LinkGeom { LinkGeom::Arc { c, a, b } => ok(c) && ok(a) && ok(b) && c.dist(*a) > 1e-9 && a.dist(*b) > MERGE_TOL, LinkGeom::Conic { a, apex, b, rho } => ok(a) && ok(apex) && ok(b) && a.dist(*b) > MERGE_TOL && *rho > 1e-6 && *rho < 1.0 - 1e-6, LinkGeom::Ellipse { c, major, minor } => ok(c) && ok(major) && c.dist(*major) > 1e-9 && radius_in_range(*minor), - LinkGeom::Spline { pts, control, degree, periodic } => { + LinkGeom::Spline { pts, control, degree, periodic, nurbs } => { (!*periodic || (!*control && *degree == 3 && crate::periodic_beziers(pts).is_ok())) + && nurbs.as_ref().is_none_or(|k| *control && !*periodic && k.check(pts.len(), *degree).is_ok()) && (2..=crate::curves::MAX_SPLINE_POINTS).contains(&pts.len()) && pts.iter().all(ok) - && (1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(degree) + && (1..=solidcore_record::MAX_BEZIER_DEGREE as u8).contains(degree) } } } @@ -275,7 +287,7 @@ struct Layout { curves: Vec, } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] enum LCurve { Line(usize, usize), Circle(usize, f64), @@ -283,8 +295,8 @@ enum LCurve { Conic(usize, usize, usize, f64), Ellipse(usize, usize, f64), /// Start, end, first interior point and interior count (interior points are consecutive - /// and never shared), control flag, degree. - Spline(usize, usize, usize, usize, bool, u8, bool), + /// and never shared), control flag, degree, periodic, own knots and weights. + Spline(usize, usize, usize, usize, bool, u8, bool, Option), } fn layout(geom: &[LinkGeom]) -> Result { @@ -339,14 +351,14 @@ fn layout(geom: &[LinkGeom]) -> Result { l.curves.push(LCurve::Ellipse(c, m, minor)); } } - LinkGeom::Spline { pts, control, degree, periodic } => { + LinkGeom::Spline { pts, control, degree, periodic, nurbs } => { let (Some(first), Some(last)) = (pts.first(), pts.last()) else { continue }; let s0 = pt(&mut l.pts, *first); let first_in = l.pts.len(); let inner = pts.get(1..pts.len() - 1).unwrap_or_default(); l.pts.extend(inner.iter().copied()); let s1 = pt(&mut l.pts, *last); - l.curves.push(LCurve::Spline(s0, s1, first_in, inner.len(), control, degree, periodic)); + l.curves.push(LCurve::Spline(s0, s1, first_in, inner.len(), control, degree, periodic, nurbs)); } } } @@ -402,6 +414,16 @@ fn same_shape(a: &LCurve, b: &LCurve) -> bool { ) } +/// Whether two splines' own knots and weights ([`crate::Nurbs`]) are the same within `close`. +fn same_nurbs(a: Option<&crate::Nurbs>, b: Option<&crate::Nurbs>, close: impl Fn(f64, f64) -> bool) -> bool { + let all = |x: &[f64], y: &[f64]| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| close(*p, *q)); + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => all(&a.knots, &b.knots) && all(&a.weights, &b.weights), + _ => false, + } +} + /// Do two curve sets describe the same geometry, regardless of the order the curves come in or /// the direction a loop was walked? Lines match with either end first; circles by centre and /// radius; arcs by centre and their (start, end) pair; conics by all their points and rho. @@ -422,7 +444,9 @@ fn same_geometry(a: &[(LCurve, Vec)], b: &[(LCurve, Vec)]) -> bool { (LCurve::Arc(..), LCurve::Arc(..)) => all(), (LCurve::Conic(.., ra), LCurve::Conic(.., rb)) => all() && close(*ra, *rb), (LCurve::Ellipse(.., ra), LCurve::Ellipse(.., rb)) => all() && close(*ra, *rb), - (LCurve::Spline(.., ca, da, pa), LCurve::Spline(.., cb, db, pb)) => ca == cb && da == db && pa == pb && all(), + (LCurve::Spline(.., ca, da, pa, ka), LCurve::Spline(.., cb, db, pb, kb)) => { + ca == cb && da == db && pa == pb && same_nurbs(ka.as_ref(), kb.as_ref(), close) && all() + } _ => false, } }; @@ -670,10 +694,10 @@ impl Sketch { let at = |i: usize| self.points.get(i).map(|p| p.pos); let near = |i: usize, q: Option| lay.pts.get(i).zip(q).is_some_and(|(p, q)| p.dist(q) <= MERGE_TOL); let curve_present = |c: &LCurve| { - self.curves.iter().filter(|k| k.link.is_some()).any(|k| match (*c, &k.kind) { - (LCurve::Line(a, b), CurveKind::Line { a: p, b: q }) => (near(a, at(*p)) && near(b, at(*q))) || (near(a, at(*q)) && near(b, at(*p))), - (LCurve::Circle(c, r), CurveKind::Circle { c: p, r: s }) => near(c, at(*p)) && (r - s).abs() <= MERGE_TOL, - (LCurve::Arc(c, a, b), CurveKind::Arc { c: p, a: q, b: e }) => near(c, at(*p)) && near(a, at(*q)) && near(b, at(*e)), + self.curves.iter().filter(|k| k.link.is_some()).any(|k| match (c, &k.kind) { + (&LCurve::Line(a, b), CurveKind::Line { a: p, b: q }) => (near(a, at(*p)) && near(b, at(*q))) || (near(a, at(*q)) && near(b, at(*p))), + (&LCurve::Circle(c, r), CurveKind::Circle { c: p, r: s }) => near(c, at(*p)) && (r - s).abs() <= MERGE_TOL, + (&LCurve::Arc(c, a, b), CurveKind::Arc { c: p, a: q, b: e }) => near(c, at(*p)) && near(a, at(*q)) && near(b, at(*e)), _ => false, }) }; @@ -720,13 +744,13 @@ impl Sketch { LCurve::Arc(c, a, b) => (CurveKind::Arc { c: point(self, c)?, a: point(self, a)?, b: point(self, b)? }, "a"), LCurve::Conic(a, b, x, rho) => (CurveKind::Conic { a: point(self, a)?, b: point(self, b)?, apex: point(self, x)?, rho }, "n"), LCurve::Ellipse(c, m, r) => (CurveKind::Ellipse { c: point(self, c)?, m: point(self, m)?, r }, "e"), - LCurve::Spline(a, b, f, n, control, degree, periodic) => { + LCurve::Spline(a, b, f, n, control, degree, periodic, ref nurbs) => { let mut pts = vec![point(self, a)?]; for i in f..f + n { pts.push(point(self, i)?); } pts.push(point(self, b)?); - (CurveKind::Spline { pts, control, degree, periodic }, "s") + (CurveKind::Spline { pts, control, degree, periodic, nurbs: nurbs.clone() }, "s") } }; let cid = self.fresh(prefix)?; @@ -779,7 +803,7 @@ impl Sketch { Some(CurveKind::Arc { c, a, b }) => Some(LCurve::Arc(local(*c)?, local(*a)?, local(*b)?)), Some(CurveKind::Conic { a, b, apex, rho }) => Some(LCurve::Conic(local(*a)?, local(*b)?, local(*apex)?, *rho)), Some(CurveKind::Ellipse { c, m, r }) => Some(LCurve::Ellipse(local(*c)?, local(*m)?, *r)), - Some(CurveKind::Spline { pts, control, degree, periodic }) => { + Some(CurveKind::Spline { pts, control, degree, periodic, nurbs }) => { let (a, b) = (local(*pts.first()?)?, local(*pts.last()?)?); let inner: Vec = pts.get(1..pts.len().saturating_sub(1)).unwrap_or_default().iter().map(|q| local(*q)).collect::>()?; @@ -788,7 +812,7 @@ impl Sketch { if inner.iter().enumerate().any(|(k, x)| *x != f + k) { return None; } - Some(LCurve::Spline(a, b, f, inner.len(), *control, *degree, *periodic)) + Some(LCurve::Spline(a, b, f, inner.len(), *control, *degree, *periodic, nurbs.clone())) } _ => None, }) @@ -844,7 +868,7 @@ impl Sketch { LCurve::Arc(c, a, b) => LCurve::Arc(renum(c), renum(a), renum(b)), LCurve::Conic(a, b, x, r) => LCurve::Conic(renum(a), renum(b), renum(x), r), LCurve::Ellipse(c, m, r) => LCurve::Ellipse(renum(c), renum(m), r), - LCurve::Spline(a, b, f, n, ct, d, periodic) => LCurve::Spline(renum(a), renum(b), renum(f), n, ct, d, periodic), + LCurve::Spline(a, b, f, n, ct, d, periodic, ref k) => LCurve::Spline(renum(a), renum(b), renum(f), n, ct, d, periodic, k.clone()), }) .collect(); let same = match &cur { @@ -859,8 +883,15 @@ impl Sketch { (LCurve::Arc(a0, a1, a2), LCurve::Arc(b0, b1, b2)) => a0 == b0 && a1 == b1 && a2 == b2, (LCurve::Conic(a0, a1, a2, _), LCurve::Conic(b0, b1, b2, _)) => a0 == b0 && a1 == b1 && a2 == b2, (LCurve::Ellipse(a0, a1, _), LCurve::Ellipse(b0, b1, _)) => a0 == b0 && a1 == b1, - (LCurve::Spline(a0, a1, a2, a3, a4, a5, a6), LCurve::Spline(b0, b1, b2, b3, b4, b5, b6)) => { - a0 == b0 && a1 == b1 && (a2 == b2 || *a3 == 0) && a3 == b3 && a4 == b4 && a5 == b5 && a6 == b6 + (LCurve::Spline(a0, a1, a2, a3, a4, a5, a6, a7), LCurve::Spline(b0, b1, b2, b3, b4, b5, b6, b7)) => { + a0 == b0 + && a1 == b1 + && (a2 == b2 || *a3 == 0) + && a3 == b3 + && a4 == b4 + && a5 == b5 + && a6 == b6 + && a7.is_some() == b7.is_some() } _ => false, } @@ -877,12 +908,14 @@ impl Sketch { let pos = |pi: usize| self.points.get(pi).map(|p| p.pos); let old: Option)>> = cur .iter() - .map(|c| curve_points(c).into_iter().map(|li| points.get(li).and_then(|pi| pos(*pi))).collect::>>().map(|ps| (*c, ps))) + .map(|c| { + curve_points(c).into_iter().map(|li| points.get(li).and_then(|pi| pos(*pi))).collect::>>().map(|ps| (c.clone(), ps)) + }) .collect(); let fresh: Option)>> = lay .curves .iter() - .map(|c| curve_points(c).into_iter().map(|li| lay.pts.get(li).copied()).collect::>>().map(|ps| (*c, ps))) + .map(|c| curve_points(c).into_iter().map(|li| lay.pts.get(li).copied()).collect::>>().map(|ps| (c.clone(), ps))) .collect(); let lone_old: Vec = points.iter().filter_map(|pi| pos(*pi)).collect(); if let (Some(old), Some(fresh)) = (old, fresh) @@ -895,6 +928,7 @@ impl Sketch { } // A resized face can enumerate the same boundary in another order. Match the // shared-point graph in normalized sketch space before discarding its identity. + let mut same_order_agrees = false; if let Some(cur) = &cur && points.len() == lay.pts.len() && cur.len() == lay.curves.len() @@ -1032,14 +1066,42 @@ impl Sketch { { *r = *value; } + if let (Some(Curve { kind: CurveKind::Spline { nurbs, .. }, .. }), Some(LCurve::Spline(.., value))) = + (self.curves.get_mut(*ci), lay.curves.get(li)) + { + nurbs.clone_from(value); + } } return Ok(false); } + // A face resized by more than the match above allows (#9001: an angle's wall made + // thicker moves the inner corner by more than a tenth of the face) is still the same + // boundary when two witnesses agree: the new boundary was read in the same order + // with the same curves, and each point read in that order is, among the points on + // the same loop with lines the same way, clearly the nearest to where it was. + same_order_agrees = same + && loop_roles.as_ref().is_some_and(|roles| { + (0..points.len()).all(|k| { + let (Some(&fresh_i), Some(p)) = (order.get(k), a.get(k)) else { return false }; + let mut candidates: Vec<(usize, f64)> = b + .iter() + .enumerate() + .filter(|(i, _)| { + old_roles.get(k) == fresh_roles.get(*i) + && roles.old.get(k) == roles.fresh.get(*i) + && roles.old_lines.get(k).zip(roles.fresh_lines.get(*i)).is_some_and(|(x, y)| loops::same_lines(x, y)) + }) + .map(|(i, q)| (i, p.dist(*q))) + .collect(); + candidates.sort_by(|x, y| x.1.total_cmp(&y.1)); + matches!(candidates.first(), Some((i, d)) if *i == fresh_i && candidates.get(1).is_none_or(|(_, second)| *d < *second * 0.75)) + }) + }); } // Equal topology alone does not identify a face boundary: an outer rim and a // hole can have identical point graphs. Never move saved curve ids between them // when the geometric match is ambiguous; the document reports a lost link. - if same && self.link(id).is_some_and(|l| matches!(l.source, LinkSource::Face { .. })) { + if same && !same_order_agrees && self.link(id).is_some_and(|l| matches!(l.source, LinkSource::Face { .. })) { self.set_link_lost(id, true); return Err(SketchError::Invalid("projected face boundary identity is ambiguous; last geometry retained".into())); } @@ -1060,6 +1122,9 @@ impl Sketch { if let (LCurve::Ellipse(.., r), Some(Curve { kind: CurveKind::Ellipse { r: slot, .. }, .. })) = (c, self.curves.get_mut(*ci)) { *slot = *r; } + if let (LCurve::Spline(.., k), Some(Curve { kind: CurveKind::Spline { nurbs, .. }, .. })) = (c, self.curves.get_mut(*ci)) { + nurbs.clone_from(k); + } } return Ok(false); } @@ -1104,16 +1169,89 @@ impl Sketch { self.points.iter().zip(&was).any(|(p, w)| p.pos != *w).then_some(was) } + /// `stored` as this sketch has its entities, when they differ only by texts built anew + /// since (other words, from an expression, are other outlines with new points and curves): + /// those texts' entities as this sketch has them, every other point where `stored` has it, + /// every other circle and ellipse with its stored radius, arcs with their stored turn and + /// constraints with their stored values. Paired so entity by entity, a solve after the links + /// moved can walk from the stored state as it does when no text changed. `None` when the + /// two are the same entities or differ in anything else. + pub fn stored_with_rebuilt_texts(&self, stored: &Sketch) -> Option { + let texts: Vec<&str> = self.links.iter().filter(|l| matches!(l.source, LinkSource::Text { .. })).map(|l| l.id.as_str()).collect(); + let in_text = |link: &Option| link.as_deref().is_some_and(|l| texts.contains(&l)); + let same = self.points.len() == stored.points.len() + && self.curves.len() == stored.curves.len() + && self.points.iter().zip(&stored.points).all(|(p, q)| p.id == q.id) + && self.curves.iter().zip(&stored.curves).all(|(c, d)| c.id == d.id); + let ids = |sk: &Sketch| sk.links.iter().map(|l| l.id.clone()).collect::>(); + if same + || texts.is_empty() + || ids(self) != ids(stored) + || !self.points.iter().filter(|p| !in_text(&p.link)).map(|p| &p.id).eq(stored.points.iter().filter(|p| !in_text(&p.link)).map(|p| &p.id)) + || !self.curves.iter().filter(|c| !in_text(&c.link)).map(|c| &c.id).eq(stored.curves.iter().filter(|c| !in_text(&c.link)).map(|c| &c.id)) + || !self.constraints.iter().map(|c| &c.id).eq(stored.constraints.iter().map(|c| &c.id)) + { + return None; + } + let mut out = self.clone(); + let points: std::collections::BTreeMap<&str, Vec2> = + stored.points.iter().filter(|p| !in_text(&p.link)).map(|p| (p.id.as_str(), p.pos)).collect(); + for p in out.points.iter_mut().filter(|p| !in_text(&p.link)) { + if let Some(pos) = points.get(p.id.as_str()) { + p.pos = *pos; + } + } + let curves: std::collections::BTreeMap<&str, &Curve> = + stored.curves.iter().filter(|c| !in_text(&c.link)).map(|c| (c.id.as_str(), c)).collect(); + for c in out.curves.iter_mut().filter(|c| !in_text(&c.link)) { + let Some(d) = curves.get(c.id.as_str()) else { continue }; + match (&mut c.kind, &d.kind) { + (CurveKind::Circle { r, .. }, CurveKind::Circle { r: s, .. }) | (CurveKind::Ellipse { r, .. }, CurveKind::Ellipse { r: s, .. }) => { + *r = *s + } + (CurveKind::Conic { rho, .. }, CurveKind::Conic { rho: s, .. }) => *rho = *s, + _ => {} + } + c.reversed = d.reversed; + } + for (c, d) in out.constraints.iter_mut().zip(&stored.constraints) { + if let Some(v) = d.kind.value() { + c.kind.set_value(v); + } + } + Some(out) + } + fn drop_link_entities(&mut self, id: &str) { let curves = self.link_curves(id); let keep = self.links.clone(); self.remove_curves(&curves); let pts = self.link_points(id); + self.free_own_curves(&pts); self.remove_points(&pts); // Removal prunes empty links; this one stays. self.links = keep; } + /// The sketch's own curves that use one of `pts` (a circle drawn on a projected hole's + /// centre) move onto a free point of their own at the same place, so removing `pts` doesn't + /// delete them with the link (#5388). Constraints on `pts` still go with them. + fn free_own_curves(&mut self, pts: &[usize]) { + for &p in pts { + let own: Vec = self.curves.iter().enumerate().filter(|(_, c)| c.link.is_none() && c.kind.uses(p)).map(|(i, _)| i).collect(); + if own.is_empty() { + continue; + } + let Some(pos) = self.points.get(p).map(|q| q.pos) else { continue }; + let Ok(free) = self.add_point(pos, None) else { continue }; + for ci in own { + if let Some(c) = self.curves.get_mut(ci) { + c.kind.map_points(&|q| if q == p { free } else { q }); + } + } + } + } + /// Mark a link as lost (its reference was not found); its geometry stays as it was. pub fn set_link_lost(&mut self, id: &str, lost: bool) { if let Some(l) = self.links.iter_mut().find(|l| l.id == id) { diff --git a/crates/sketch/src/link_identity_tests.rs b/crates/sketch/src/link_identity_tests.rs index bfa511854..31c91d229 100644 --- a/crates/sketch/src/link_identity_tests.rs +++ b/crates/sketch/src/link_identity_tests.rs @@ -423,3 +423,38 @@ fn edge_on_face_saved_as_a_line_pair_keeps_the_line_an_offset_follows() { let end = sk.points[sk.link_points(&link)[1]].pos; assert_eq!(end, Vec2::new(17.0, 5.0), "the line moved to the new geometry"); } + +/// #5388: a circle the user drew on a projected hole's centre survives when the face changes +/// shape and its projection is rebuilt (a second hole added to the face). +#[test] +fn rebuilt_face_keeps_a_users_circle_on_its_projected_centre() { + let mut sk = Sketch::new(); + let hole = |c: Vec2| LinkGeom::Circle(c, 2.1); + let face_with = |holes: &[Vec2]| square(15.0).into_iter().chain(holes.iter().map(|c| hole(*c))).collect::>(); + let link = sk.add_link(LinkKind::Project, face(), &face_with(&[Vec2::ZERO])).unwrap(); + // The projected hole's centre point. + let centre = sk + .link_curves(&link) + .into_iter() + .find_map(|i| match sk.curves[i].kind { + CurveKind::Circle { c, .. } => Some(c), + _ => None, + }) + .unwrap(); + let mine = sk.add_curve(CurveKind::Circle { c: centre, r: 5.25 }, Some("c_mine")).unwrap(); + assert!(sk.curves[mine].link.is_none()); + // The face gains two more holes: the projection's shape changes, so it is rebuilt. + assert!(sk.update_link(&link, &face_with(&[Vec2::ZERO, Vec2::new(-10.0, 0.0), Vec2::new(10.0, 0.0)])).unwrap()); + let kept = sk.curves.iter().find(|c| c.id == "c_mine").expect("the user's circle survives the rebuild"); + assert!(kept.link.is_none()); + match kept.kind { + CurveKind::Circle { c, r } => { + assert_eq!(r, 5.25); + let p = &sk.points[c]; + assert!(p.link.is_none(), "it sits on a point of its own, not a projected one"); + assert!(p.pos.len() < 1e-9, "still at the hole's centre: {:?}", p.pos); + } + ref k => panic!("not a circle: {k:?}"), + } + assert_eq!(sk.link_curves(&link).len(), 4 + 3, "the projection is the new outline and holes"); +} diff --git a/crates/sketch/src/link_loops.rs b/crates/sketch/src/link_loops.rs index 0125ed95e..5c732652a 100644 --- a/crates/sketch/src/link_loops.rs +++ b/crates/sketch/src/link_loops.rs @@ -2,7 +2,9 @@ //! Endpoint walks exclude support centres. Crossings/touches refuse before nesting. use super::{LCurve, curve_points}; use crate::{Shape, intersections}; -use solidcraft_geom::{Aabb2, Vec2}; +use solidcore_record::Vec2; +use solidcraft_geom::Aabb2; +use solidcraft_geom::prelude::*; use std::f64::consts::TAU; struct Boundary { diff --git a/crates/sketch/src/loci.rs b/crates/sketch/src/loci.rs index b8215ecb3..353704877 100644 --- a/crates/sketch/src/loci.rs +++ b/crates/sketch/src/loci.rs @@ -32,7 +32,8 @@ //! Tolerances are relative to the loci's own size plus the rounding of the coordinates they //! are computed from, so a construction far from the origin behaves like the same one near it. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::model::{ConstraintKind, CurveKind, MAX_COORD, Sketch, in_range, radius_in_range}; use crate::union_find::{find, union}; diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index a5235407c..8a0f56248 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1,5 +1,7 @@ use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Aabb2, Seg2, Vec2, Vec3}; +use solidcore_record::{Seg2, Vec2, Vec3}; +use solidcraft_geom::Aabb2; +use solidcraft_geom::prelude::*; use crate::union_find::{find, union}; @@ -8,6 +10,8 @@ pub const MAX_POINTS: usize = 20_000; pub const MAX_CONSTRAINTS: usize = 40_000; /// Curves need points, so this follows the point cap. pub const MAX_CURVES: usize = MAX_POINTS; +// [`SketchError::TooLarge`]'s message names this number; keep them matched (#10874). +const _: () = assert!(MAX_POINTS == 20_000); /// Largest coordinate or dimension value (mm) a sketch accepts. pub const MAX_COORD: f64 = 1e9; @@ -37,7 +41,12 @@ pub enum SketchError { Duplicate(String), #[error("invalid value: {0}")] Invalid(String), - #[error("sketch is too large")] + /// Cap hit on points, curves or constraints ([`MAX_POINTS`], [`MAX_CURVES`], + /// [`MAX_CONSTRAINTS`]). Insert SVG/DXF of a dense drawing (a floorplan) often hits this; + /// scale alone does not reduce how many curves the file has (#10874). + #[error( + "sketch is too large (at most 20000 points or curves); simplify the drawing or split it across sketches — changing scale does not reduce how many curves it has" + )] TooLarge, /// Fonts this text falls back to are being looked for beside the window: ask again. #[error("the fonts for this text are still being looked for")] @@ -107,6 +116,10 @@ pub enum CurveKind { /// Explicit cyclic C2 fit interpolation; absent retains natural endpoints. #[serde(default, skip_serializing_if = "std::ops::Not::not")] periodic: bool, + /// A control spline's own knots and weights (a projected free-form edge as the exact + /// curve it is); none: the clamped uniform B-spline over its points, all weights 1. + #[serde(default, skip_serializing_if = "Option::is_none")] + nurbs: Option, }, /// Conic from `a` to `b` shaped by the `apex` point and `rho` in (0, 1) (0.5 parabola, /// less elliptical, more hyperbolic). @@ -830,9 +843,13 @@ impl Sketch { } pub fn point_index(&self, id: &str) -> Option { + #[cfg(test)] + crate::tests::count_id_search(); self.points.iter().position(|p| p.id == id) } pub fn curve_index(&self, id: &str) -> Option { + #[cfg(test)] + crate::tests::count_id_search(); self.curves.iter().position(|c| c.id == id) } pub fn point(&self, i: usize) -> Option { @@ -1484,7 +1501,7 @@ impl Sketch { _ => Vec::new(), }, CurveKind::Circle { c, r } => match self.point(c) { - Some(c) => solidcraft_geom::Loop2::circle(c, r).segs, + Some(c) => solidcore_record::Loop2::circle(c, r).segs, None => Vec::new(), }, CurveKind::Arc { c, a, b } => match (self.point(c), self.point(a), self.point(b)) { @@ -1503,8 +1520,9 @@ impl Sketch { } /// Exact boundary segments of a free-form curve: ellipses as four conics, conics, fit - /// splines and control splines up to `MAX_BEZIER_DEGREE` as Béziers. None for other curves - /// (and for higher-degree splines, which stay polylines). + /// splines and control splines up to `MAX_BEZIER_DEGREE` as Béziers (one a knot span for a + /// spline with its own knots, conics for a rational quadratic one). None for other curves + /// (and for higher-degree or other rational splines, which stay polylines). pub fn exact_segs(&self, ci: usize) -> Option> { let cu = self.curves.get(ci)?; let pt = |i: &usize| self.point(*i); @@ -1531,7 +1549,11 @@ impl Sketch { crate::curves::fit_beziers_mode(&p, *periodic).ok()?.into_iter().map(|[p0, p1, p2, p3]| Seg2::Cubic { p0, p1, p2, p3 }).collect(), ) } - CurveKind::Spline { pts, control: true, degree, .. } if (*degree as usize) <= solidcraft_geom::MAX_BEZIER_DEGREE => { + CurveKind::Spline { pts, control: true, degree, nurbs: Some(nurbs), .. } => { + let p: Vec = pts.iter().map(pt).collect::>()?; + nurbs.segs(&p, *degree) + } + CurveKind::Spline { pts, control: true, degree, nurbs: None, .. } if (*degree as usize) <= solidcore_record::MAX_BEZIER_DEGREE => { let p: Vec = pts.iter().map(pt).collect::>()?; let k = (*degree as usize).min(p.len().saturating_sub(1)).max(1); Some(crate::curves::bspline_beziers(&p, k).iter().filter_map(|c| solidcraft_geom::bezier(c)).collect()) @@ -1543,7 +1565,7 @@ impl Sketch { /// The exact [`Seg2`] pieces of a curve of any kind, in the curve's own direction of travel: /// lines, circles and arcs from their analytic form, free-form curves through /// [`Sketch::exact_segs`]. Empty for a curve with no exact pieces (a spline above - /// `solidcraft_geom::MAX_BEZIER_DEGREE`). + /// `solidcore_record::MAX_BEZIER_DEGREE`). pub fn exact_pieces(&self, ci: usize) -> Vec { match self.exact_segs(ci) { Some(segs) => segs, @@ -1561,9 +1583,9 @@ impl Sketch { (Some(c), Some(m)) => crate::curves::ellipse_polyline(c, m, *r), _ => Vec::new(), }, - CurveKind::Spline { pts, control, degree, periodic } => { + CurveKind::Spline { pts, control, degree, periodic, nurbs } => { let p: Option> = pts.iter().map(pt).collect(); - p.map(|p| crate::curves::spline_polyline_mode(&p, *control, *degree, *periodic)).unwrap_or_default() + p.map(|p| crate::curves::spline_polyline_mode(&p, *control, *degree, *periodic, nurbs.as_ref())).unwrap_or_default() } CurveKind::Conic { a, b, apex, rho } => match (pt(a), pt(apex), pt(b)) { (Some(a), Some(x), Some(b)) => crate::curves::conic_polyline(a, x, b, *rho), @@ -1599,11 +1621,18 @@ impl Sketch { } "e" } - CurveKind::Spline { pts, control, degree, periodic } => { - if pts.len() < 2 || pts.len() > crate::curves::MAX_SPLINE_POINTS || !(1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(degree) { + CurveKind::Spline { pts, control, degree, periodic, nurbs } => { + if let Some(nurbs) = nurbs { + if !*control || *periodic { + return Err(SketchError::Invalid("only an open control spline has its own knots".into())); + } + nurbs.check(pts.len(), *degree)?; + } + if pts.len() < 2 || pts.len() > crate::curves::MAX_SPLINE_POINTS || !(1..=solidcore_record::MAX_BEZIER_DEGREE as u8).contains(degree) + { return Err(SketchError::Invalid(format!( "a spline needs 2 to 500 points and degree 1 to {}", - solidcraft_geom::MAX_BEZIER_DEGREE + solidcore_record::MAX_BEZIER_DEGREE ))); } if *periodic { @@ -1687,7 +1716,7 @@ impl Sketch { /// Points held together only through points about to go stay together: two rectangles' /// corners made coincident with one arc end are tied to each other when a trim takes that /// end away, instead of coming apart where they still meet. - fn keep_ties_through(&mut self, gone: &[usize]) { + pub(crate) fn keep_ties_through(&mut self, gone: &[usize]) { if gone.is_empty() { return; } @@ -1724,7 +1753,7 @@ impl Sketch { } } - fn point_used_by_curve(&self, p: usize) -> bool { + pub(crate) fn point_used_by_curve(&self, p: usize) -> bool { self.curves.iter().any(|c| c.kind.uses(p)) } @@ -1834,9 +1863,29 @@ impl Sketch { } } - /// Axis-aligned bounds of all geometry (for views). + /// Axis-aligned bounds of all geometry (for views). An arc's are exact: its polyline's points + /// need not reach the circle's extremes (a whole circle is one arc, whose chords start at its + /// start angle), so the quarter points it sweeps through are added. pub fn bounds(&self) -> Option<(Vec2, Vec2)> { - let b: Aabb2 = (0..self.curves.len()).flat_map(|i| self.segs(i)).flat_map(|s| s.polyline(0.5)).collect(); + let extremes = |s: &Seg2| -> Vec { + let Seg2::Arc { center, radius, start, sweep } = *s else { return Vec::new() }; + let (lo, hi) = if sweep >= 0.0 { (start, start + sweep) } else { (start + sweep, start) }; + let quarter = std::f64::consts::FRAC_PI_2; + let first = (lo / quarter).ceil() as i64; + let last = (hi / quarter).floor() as i64; + if !(lo.is_finite() && hi.is_finite()) || last - first > 4 { + return Vec::new(); + } + (first..=last).map(|k| center + Vec2::from_angle(k as f64 * quarter) * radius).collect() + }; + let b: Aabb2 = (0..self.curves.len()) + .flat_map(|i| self.segs(i)) + .flat_map(|s| { + let mut pts = s.polyline(0.5); + pts.extend(extremes(&s)); + pts + }) + .collect(); (!b.is_empty()).then_some((b.min, b.max)) } } diff --git a/crates/sketch/src/nurbs.rs b/crates/sketch/src/nurbs.rs new file mode 100644 index 000000000..977854e80 --- /dev/null +++ b/crates/sketch/src/nurbs.rs @@ -0,0 +1,200 @@ +//! A control spline's own knots and weights ([`Nurbs`]): the exact form of a free-form edge a +//! sketch projects, whose knots need not be evenly spaced and whose weights need not be 1. A +//! control spline without them is the clamped uniform B-spline over its points. + +use serde::{Deserialize, Serialize}; +use solidcore_record::{Seg2, Vec2, Vec3}; +use solidcraft_geom::bspline::{self, HPoint}; + +use crate::model::{Result, SketchError}; + +/// Most knots a spline may have (its points are capped at [`crate::MAX_SPLINE_POINTS`]). +const MAX_KNOTS: usize = crate::curves::MAX_SPLINE_POINTS + solidcore_record::MAX_BEZIER_DEGREE + 1; +/// Most a weight may exceed another by: past it the curve is all but its heaviest points. +const MAX_WEIGHT_RATIO: f64 = 1e12; +/// Polyline samples per knot span. +const SPAN_SAMPLES: usize = 24; + +/// The knot vector and weights of a control spline of `degree` over `n` points: clamped (each +/// end knot `degree + 1` times, no interior knot more than `degree` times), `n + degree + 1` +/// non-decreasing knots, and one positive weight per point (none: all 1). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Nurbs { + pub knots: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub weights: Vec, +} + +fn bad(why: &str) -> Result { + Err(SketchError::Invalid(format!("spline knots: {why}"))) +} + +impl Nurbs { + /// Whether these knots and weights fit a control spline of `degree` over `n` points. + pub fn check(&self, n: usize, degree: u8) -> Result<()> { + let d = usize::from(degree); + if !(1..=solidcore_record::MAX_BEZIER_DEGREE).contains(&d) || n <= d || n > crate::curves::MAX_SPLINE_POINTS { + return bad("a knotted spline needs more points than its degree, 1 to 9"); + } + let k = &self.knots; + if k.len() != n + d + 1 || k.len() > MAX_KNOTS { + return bad("a spline needs its point count plus its degree plus one knots"); + } + if k.iter().any(|x| !x.is_finite()) || k.windows(2).any(|w| w[1] < w[0]) { + return bad("knots must be finite and never decrease"); + } + let (lo, hi) = (k[d], k[n]); + let span = hi - lo; + if !(span > 0.0 && span.is_finite()) || k[..=d].iter().any(|x| *x != lo) || k[n..].iter().any(|x| *x != hi) { + return bad("the knots must be clamped at both ends"); + } + let mut run = 0usize; + for (i, x) in k.iter().enumerate().take(n).skip(d + 1) { + run = if k.get(i - 1) == Some(x) { run + 1 } else { 1 }; + if *x == lo || *x == hi || run > d { + return bad("no knot inside the spline may repeat more than its degree"); + } + } + if !self.weights.is_empty() { + if self.weights.len() != n || self.weights.iter().any(|w| !(w.is_finite() && *w > 0.0)) { + return bad("a rational spline needs one positive weight per point"); + } + let (min, max) = self.weights.iter().fold((f64::INFINITY, 0.0f64), |(a, b), w| (a.min(*w), b.max(*w))); + if max / min > MAX_WEIGHT_RATIO { + return bad("the weights differ too much"); + } + } + Ok(()) + } + + fn weight(&self, i: usize) -> f64 { + self.weights.get(i).copied().unwrap_or(1.0) + } + + /// The control points `p` with their weights, homogeneous. + fn homogeneous(&self, p: &[Vec2]) -> Vec { + p.iter().enumerate().map(|(i, q)| HPoint::weighted(Vec3::new(q.x, q.y, 0.0), self.weight(i))).collect() + } + + /// The knot domain `[lo, hi]` for `n` points of `degree`. + fn domain(&self, n: usize, degree: usize) -> Option<(f64, f64)> { + Some((*self.knots.get(degree)?, *self.knots.get(n)?)) + } + + /// The same curve run the other way: the knots mirrored, the weights reversed (the points + /// reverse with them). + pub fn reversed(&self) -> Nurbs { + let sum = self.knots.first().copied().unwrap_or(0.0) + self.knots.last().copied().unwrap_or(0.0); + Nurbs { knots: self.knots.iter().rev().map(|k| sum - k).collect(), weights: self.weights.iter().rev().copied().collect() } + } + + /// The point of the spline over `p` (of `degree`) at `t` in [0, 1] across its knot domain. + /// `None` when the knots don't fit the points. + pub fn point(&self, p: &[Vec2], degree: u8, t: f64) -> Option { + self.check(p.len(), degree).ok()?; + let d = usize::from(degree); + let (lo, hi) = self.domain(p.len(), d)?; + self.eval(&self.homogeneous(p), d, lo + (hi - lo) * t.clamp(0.0, 1.0)) + } + + /// The point at knot parameter `u` of the spline of degree `d` over the homogeneous points + /// `h` (de Boor), the knots already checked. + fn eval(&self, h: &[HPoint], d: usize, u: f64) -> Option { + let k = &self.knots; + let n = h.len(); + // The span holding u: the last knot ≤ u that starts a non-empty span. + let mut s = d; + while s + 1 < n && k.get(s + 1).is_some_and(|x| *x <= u) { + s += 1; + } + let mut c: Vec = h.get(s - d..=s)?.to_vec(); + for r in 1..=d { + for j in (r..=d).rev() { + let i = s + j - d; + let (a, b) = (k.get(i).copied()?, k.get(i + d + 1 - r).copied()?); + let alpha = if b > a { (u - a) / (b - a) } else { 0.0 }; + c[j] = c[j - 1] * (1.0 - alpha) + c[j] * alpha; + } + } + let q = c.get(d)?.project()?; + Some(Vec2::new(q.x, q.y)) + } + + /// The Bézier spans of the spline over `p`, homogeneous, in parameter order: every + /// interior knot inserted until it repeats `degree` times (Boehm). Exact up to rounding. + fn spans(&self, p: &[Vec2], degree: u8) -> Option>> { + self.check(p.len(), degree).ok()?; + let d = usize::from(degree); + let (mut k, mut c) = (self.knots.clone(), self.homogeneous(p)); + let (lo, hi) = self.domain(p.len(), d)?; + let mut interior: Vec = self.knots.iter().copied().filter(|x| *x > lo && *x < hi).collect(); + interior.dedup(); + for u in interior { + while k.iter().filter(|x| **x == u).count() < d { + (k, c) = bspline::insert_knot(d, &k, &c, u).ok()?; + } + } + let mut spans = Vec::new(); + for i in d..c.len() { + if k.get(i)? < k.get(i + 1)? { + spans.push(c.get(i - d..=i)?.to_vec()); + } + } + Some(spans) + } + + /// The spline over `p` as its exact [`Seg2`] pieces, one a knot span: Béziers, or conics + /// for a rational quadratic. `None` for other rational splines, which have no such pieces. + pub fn segs(&self, p: &[Vec2], degree: u8) -> Option> { + let spans = self.spans(p, degree)?; + let rational = self.weights.windows(2).any(|w| w[0] != w[1]); + let flat = |q: &HPoint| q.project().map(|v| Vec2::new(v.x, v.y)); + spans + .iter() + .map(|span| { + let pts: Vec = span.iter().map(flat).collect::>()?; + match (rational, pts.as_slice()) { + (false, _) => solidcraft_geom::bezier(&pts), + (true, [a, apex, b]) => { + let w = span.get(1)?.w / (span.first()?.w * span.get(2)?.w).sqrt(); + (w.is_finite() && w > 0.0).then_some(Seg2::Conic { a: *a, apex: *apex, b: *b, w }) + } + _ => None, + } + }) + .collect() + } + + /// The spline over `p`, sampled evenly within each knot span. + pub fn polyline(&self, p: &[Vec2], degree: u8) -> Vec { + let d = usize::from(degree); + let Some((lo, hi)) = self.check(p.len(), degree).ok().and_then(|()| self.domain(p.len(), d)) else { return Vec::new() }; + let mut breaks: Vec = self.knots.iter().copied().filter(|x| *x >= lo && *x <= hi).collect(); + breaks.dedup(); + let h = self.homogeneous(p); + let mut out = Vec::with_capacity(breaks.len() * SPAN_SAMPLES + 1); + for w in breaks.windows(2) { + for i in 0..SPAN_SAMPLES { + out.extend(self.eval(&h, d, w[0] + (w[1] - w[0]) * i as f64 / SPAN_SAMPLES as f64)); + } + } + out.extend(self.eval(&h, d, hi)); + out + } +} + +impl crate::Sketch { + /// Every spline's own knots and weights fit it: on an open control spline, the right count, + /// clamped, with positive weights (a loaded design is checked before it is used). + pub fn validate_spline_knots(&self) -> Result<()> { + for curve in &self.curves { + if let crate::CurveKind::Spline { pts, control, degree, periodic, nurbs: Some(nurbs) } = &curve.kind { + if !*control || *periodic { + return bad("only an open control spline has its own knots"); + } + nurbs.check(pts.len(), *degree)?; + } + } + Ok(()) + } +} diff --git a/crates/sketch/src/offset.rs b/crates/sketch/src/offset.rs index 23b013dab..5fdda5589 100644 --- a/crates/sketch/src/offset.rs +++ b/crates/sketch/src/offset.rs @@ -1,7 +1,8 @@ //! Associative offsets keep their output entity ids while their source curves move. use crate::{ConstraintKind, CurveKind, Shape, Sketch, SketchError, intersections}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OffsetChain { @@ -67,6 +68,13 @@ impl Sketch { output(&arc.id) && self.curves.iter().enumerate().any(|(k, other)| k != curve && other.kind.uses(centre) && !output(&other.id)) } + /// A circle an offset made (#9264). The offset sets its radius from the source's after the + /// solve, so the solve holds that radius instead of counting it as a free unknown. + pub(crate) fn offset_circle_follows_source(&self, curve: usize) -> bool { + let Some(circle) = self.curves.get(curve) else { return false }; + matches!(circle.kind, CurveKind::Circle { .. }) && self.offsets.iter().any(|o| o.owns_output(&circle.id)) + } + /// Endpoints of a normal-distance annotation, evaluated from its source curve. pub fn offset_dimension_points(&self, output: &str) -> Option<(Vec2, Vec2)> { let (source, forward, distance) = self @@ -115,6 +123,80 @@ impl Sketch { } } + /// Retry a failed solve whose source edit was blocked by attachments to an offset's old + /// fixed points. Seed the sources without those attachments, rebuild the offsets, then + /// solve every attachment with the sources held. Nothing is adopted unless the complete + /// sketch solves with its original constraints and orientation. + pub fn solve_after_offset_edit( + &mut self, + old: &crate::DrivingValues, + reference: Option<&[Vec2]>, + analysis: crate::Analysis, + ) -> Option { + let source = + |id: &str| self.offsets.iter().any(|o| o.sources.iter().any(|(s, _)| s == id)) || self.freeform_offsets.iter().any(|o| o.source == id); + let output = |id: &str| self.offsets.iter().any(|o| o.owns_output(id)) || self.freeform_offsets.iter().any(|o| o.output == id); + let source_points: std::collections::BTreeSet = + self.curves.iter().filter(|c| source(&c.id)).flat_map(|c| c.kind.point_ids()).collect(); + let outputs: std::collections::BTreeSet = self.curves.iter().enumerate().filter(|(_, c)| output(&c.id)).map(|(i, _)| i).collect(); + let output_points: std::collections::BTreeSet = + outputs.iter().filter_map(|i| self.curves.get(*i)).flat_map(|c| c.kind.point_ids()).filter(|p| !source_points.contains(p)).collect(); + let mut candidate = self.clone(); + candidate.constraints.retain(|c| { + !c.kind.indices().1.iter().any(|i| outputs.contains(i)) && !self.constraint_points(&c.kind).iter().any(|p| output_points.contains(p)) + }); + if candidate.constraints.len() == self.constraints.len() { + return None; + } + let before: Vec = reference.map_or_else(|| self.points.iter().map(|p| p.pos).collect(), <[Vec2]>::to_vec); + if !crate::solve_after_edit_with_analysis(&mut candidate, old, Some(&before), crate::Analysis::StatusOnly).keeps_orientation() { + return None; + } + candidate.constraints.clone_from(&self.constraints); + candidate.refresh_offsets().ok()?; + // Keep the freshly rebuilt offset exact while its attached geometry catches up. + // Refresh may retire output curves or refine a dependent spline: resolve holds again. + let hold = crate::Hold { + points: candidate.curves.iter().filter(|c| source(&c.id)).flat_map(|c| c.kind.point_ids()).collect(), + radii: candidate.curves.iter().enumerate().filter(|(_, c)| source(&c.id) || output(&c.id)).map(|(i, _)| i).collect(), + }; + if !crate::solve_with(&mut candidate, &hold, Some(&before), crate::Analysis::StatusOnly, None).keeps_orientation() { + // A cap tangent to an arc can land on the other tangency branch after a large + // jump. Walk the held source and output points from their stored positions. + // Their own dimensions are restored after the walk, not imposed at each step. + let mut walking = candidate.clone(); + walking.constraints.retain(|c| candidate.constraint_points(&c.kind).iter().any(|p| !hold.points.contains(p))); + for i in &hold.points { + if let Some(p) = walking.points.get_mut(*i) { + p.fixed = true; + } + } + for i in &hold.radii { + if let Some(c) = walking.curves.get_mut(*i) { + c.fixed = true; + } + } + let mut from = walking.clone(); + for (p, pos) in from.points.iter_mut().zip(&before) { + p.pos = *pos; + } + crate::solve_after_link_move(&mut walking, &from, old, crate::Analysis::StatusOnly)?; + for (p, q) in candidate.points.iter_mut().zip(&walking.points) { + p.pos = q.pos; + } + for (c, d) in candidate.curves.iter_mut().zip(&walking.curves) { + c.kind.clone_from(&d.kind); + } + } + // Publish ordinary freedom/redundancy diagnostics, without the temporary holds. + let report = crate::solve_after_edit_with_analysis(&mut candidate, old, Some(&before), analysis); + if !report.keeps_orientation() { + return None; + } + *self = candidate; + Some(report) + } + pub fn refresh_offsets(&mut self) -> Result<(), SketchError> { if self.offsets.is_empty() && self.freeform_offsets.is_empty() { return Ok(()); @@ -166,7 +248,7 @@ impl Sketch { let (a, b) = (self.point(a).ok_or_else(bad)?, self.point(b).ok_or_else(bad)?); let (a, b) = if *forward { (a, b) } else { (b, a) }; let n = (b - a).normalized().ok_or_else(bad)?.perp() * offset.distance; - (Shape::Line { a: a + n, b: b + n }, a + n, b + n) + (Shape::Line { a: a + n, b: b + n }, a + n, b + n, None) } CurveKind::Arc { c, a, b } => { let (c, a, b) = (self.point(c).ok_or_else(bad)?, self.point(a).ok_or_else(bad)?, self.point(b).ok_or_else(bad)?); @@ -177,7 +259,7 @@ impl Sketch { let a = c + (a - c).normalized().ok_or_else(bad)? * r; let b = c + (b - c).normalized().ok_or_else(bad)? * r; let (a, b) = if *forward { (a, b) } else { (b, a) }; - (Shape::Round { c, r, start: 0.0, sweep: std::f64::consts::TAU }, a, b) + (Shape::Round { c, r, start: 0.0, sweep: std::f64::consts::TAU }, a, b, Some(*forward)) } CurveKind::Circle { c, r } => { let c = self.point(c).ok_or_else(bad)?; @@ -201,16 +283,32 @@ impl Sketch { if pieces.is_empty() { continue; } + // Which way a piece runs at `p`: a line along itself, an arc anticlockwise round its + // centre when it follows its source forward. + let along = |piece: &(Shape, Vec2, Vec2, Option), p: Vec2| match (&piece.0, piece.3) { + (Shape::Line { a, b }, _) => *b - *a, + (Shape::Round { c, .. }, Some(true)) => (p - *c).perp(), + (Shape::Round { c, .. }, Some(false)) => (*c - p).perp(), + _ => Vec2::new(0.0, 0.0), + }; let joint = |i: usize, j: usize| -> Result { let (x, y) = (pieces.get(i).ok_or_else(bad)?, pieces.get(j).ok_or_else(bad)?); if x.2.dist(y.1) < 1e-6 { return Ok(x.2); } let guess = (x.2 + y.1) * 0.5; - intersections(&x.0, &y.0) - .into_iter() - .min_by(|a, b| a.dist(guess).total_cmp(&b.dist(guess))) - .ok_or_else(|| SketchError::Invalid("the offset curves no longer meet".into())) + let mut found = intersections(&x.0, &y.0); + found.sort_by(|a, b| a.dist(guess).total_cmp(&b.dist(guess))); + // Where the sources touch, as two tangent arcs do at a dog bone's notch (#10984), + // both crossings are as far from the corner and rounding chose one. The pieces + // overlap there: they meet where both are cut short, not where both run on and + // cross into a loop. + let cut_short = |p: Vec2| (p - x.2).dot(along(x, x.2)) < 0.0 && (p - y.1).dot(along(y, y.1)) > 0.0; + match found.as_slice() { + [p, q, ..] if (q.dist(guess) - p.dist(guess)).abs() <= 1e-9 * (1.0 + p.dist(*q)) && !cut_short(*p) && cut_short(*q) => Ok(*q), + [p, ..] => Ok(*p), + [] => Err(SketchError::Invalid("the offset curves no longer meet".into())), + } }; let n = pieces.len(); let mut joints = vec![if offset.closed { joint(n - 1, 0)? } else { pieces.first().ok_or_else(bad)?.1 }]; diff --git a/crates/sketch/src/offset_topology.rs b/crates/sketch/src/offset_topology.rs index 2d04e071c..6467d42fc 100644 --- a/crates/sketch/src/offset_topology.rs +++ b/crates/sketch/src/offset_topology.rs @@ -1,9 +1,10 @@ //! Exact convex parallel boundaries with persistent extinct arc identities. +use solidcraft_geom::prelude::*; use std::collections::{BTreeMap, BTreeSet}; use std::f64::consts::TAU; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; use crate::{Curve, CurveKind, OffsetChain, Sketch, SketchError}; type Result = std::result::Result; diff --git a/crates/sketch/src/paper_text.rs b/crates/sketch/src/paper_text.rs index e9fffe33e..176d28e9f 100644 --- a/crates/sketch/src/paper_text.rs +++ b/crates/sketch/src/paper_text.rs @@ -41,10 +41,11 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; use sha2::{Digest, Sha256}; +use solidcore_record::{Loop2, Vec2}; use solidcraft_geom::paper::text::{ Cluster, Embed, Font, FontFlags, FontGlyph, FontMetrics, MAX_FONT_FAMILY, MAX_POSTSCRIPT_NAME, PlacedGlyph, TextRun, is_postscript_char, }; -use solidcraft_geom::{Loop2, Vec2}; +use solidcraft_geom::prelude::*; use crate::fonts::fallback::{self, Han, Query}; use crate::fonts::{DEFAULT_FONT_FAMILY, FontData, check_family, face_at, face_family, find_style_in, font_data, font_dirs, normalize}; diff --git a/crates/sketch/src/paper_text_tests.rs b/crates/sketch/src/paper_text_tests.rs index 1f31f7307..6cb51db7a 100644 --- a/crates/sketch/src/paper_text_tests.rs +++ b/crates/sketch/src/paper_text_tests.rs @@ -6,9 +6,10 @@ use std::path::PathBuf; use sha2::{Digest, Sha256}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_geom::paper::text::{Embed, Font, TextRun}; use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene}; +use solidcraft_geom::prelude::*; use crate::fonts::fallback::{Han, Query}; use crate::fonts::font_data; diff --git a/crates/sketch/src/pattern.rs b/crates/sketch/src/pattern.rs index 7f98347e4..ad2a9d98f 100644 --- a/crates/sketch/src/pattern.rs +++ b/crates/sketch/src/pattern.rs @@ -1,7 +1,8 @@ //! Stored parameters and stable entity ids for editing an existing sketch pattern. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::{ConstraintKind, Curve, CurveKind, Sketch, SketchError}; @@ -306,9 +307,9 @@ impl Sketch { if self.patterns.is_empty() { return; } - let curves: std::collections::BTreeSet<_> = self.curves.iter().map(|c| c.id.as_str()).collect(); - let points: std::collections::BTreeSet<_> = self.points.iter().map(|p| p.id.as_str()).collect(); - let constraint_ids: std::collections::BTreeSet<_> = self.constraints.iter().map(|c| c.id.as_str()).collect(); + let curves: std::collections::HashSet<_> = self.curves.iter().map(|c| c.id.as_str()).collect(); + let points: std::collections::HashSet<_> = self.points.iter().map(|p| p.id.as_str()).collect(); + let constraint_ids: std::collections::HashSet<_> = self.constraints.iter().map(|c| c.id.as_str()).collect(); let retired: Vec<_> = self .patterns .iter() @@ -334,15 +335,31 @@ impl Sketch { /// Conic rho is an authored shape parameter rather than a solver unknown. Like its /// defining points, the copies follow the seed's shape when that parameter is edited. pub(crate) fn refresh_pattern_shapes(&mut self) { - if !self.curves.iter().any(|c| matches!(c.kind, CurveKind::Conic { .. } | CurveKind::Arc { .. })) { + if self.patterns.is_empty() || !self.curves.iter().any(|c| matches!(c.kind, CurveKind::Conic { .. } | CurveKind::Arc { .. })) { return; } - for pattern in &self.patterns { - let sources: Vec<_> = pattern.entities.iter().filter_map(|id| self.curve_index(id)).collect(); - for instance in &pattern.instances { - for (seed, copy) in sources.iter().zip(&instance.curves) { + // This runs before every solve, drag frames included. Ids resolve through maps built + // once here: a linear search per copy cost patterns × copies × seeds × curves string + // comparisons, which dominated dragging anything in a sketch with a large pattern. + // Only curve shapes change below, so the indices stay valid throughout. + let (sources, copies): (Vec>, Vec>>>) = { + let curves = first_index(self.curves.iter().map(|c| c.id.as_str())); + self.patterns + .iter() + .map(|pattern| { + ( + pattern.entities.iter().filter_map(|id| curves.get(id.as_str()).copied()).collect(), + pattern.instances.iter().map(|i| i.curves.iter().map(|id| curves.get(id.as_str()).copied()).collect()).collect(), + ) + }) + .unzip() + }; + let points = first_index(self.points.iter().map(|p| p.id.as_str())); + for ((pattern, sources), copies) in self.patterns.iter().zip(&sources).zip(&copies) { + for (instance, copies) in pattern.instances.iter().zip(copies) { + for (seed, copy) in sources.iter().zip(copies) { if let Some(CurveKind::Conic { rho, .. }) = self.curves.get(*seed).map(|c| &c.kind) - && let Some(copy) = self.curve_index(copy) + && let Some(copy) = *copy { let rho = *rho; if let Some(CurveKind::Conic { rho: slot, .. }) = self.curves.get_mut(copy).map(|c| &mut c.kind) { @@ -355,9 +372,9 @@ impl Sketch { self.points .get(p) .and_then(|p| instance.points.iter().find(|(id, _)| *id == p.id)) - .and_then(|(_, id)| self.point_index(id)) + .and_then(|(_, id)| points.get(id.as_str()).copied()) }; - if let (Some(c), Some(a), Some(b), Some(copy)) = (mapped(c), mapped(a), mapped(b), self.curve_index(copy)) + if let (Some(c), Some(a), Some(b), Some(copy)) = (mapped(c), mapped(a), mapped(b), *copy) && let Some(curve) = self.curves.get_mut(copy) { curve.kind = CurveKind::Arc { c, a, b }; @@ -561,3 +578,12 @@ fn rotate(c: Vec2, ang: f64) -> impl Fn(Vec2) -> Vec2 { c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) } } + +/// Each id's first index, as `position` finds it. +fn first_index<'a>(ids: impl Iterator) -> std::collections::HashMap<&'a str, usize> { + let mut map = std::collections::HashMap::new(); + for (i, id) in ids.enumerate() { + map.entry(id).or_insert(i); + } + map +} diff --git a/crates/sketch/src/periodic.rs b/crates/sketch/src/periodic.rs index 698e58a58..614df9be1 100644 --- a/crates/sketch/src/periodic.rs +++ b/crates/sketch/src/periodic.rs @@ -1,7 +1,8 @@ //! Explicit cyclic C2 fit splines. Missing periodic markers retain natural interpolation. use crate::model::in_range; use crate::{MAX_SPLINE_POINTS, Sketch, SketchError}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; type Result = std::result::Result; fn bad() -> SketchError { @@ -102,7 +103,7 @@ impl Sketch { pub fn validate_periodic_splines(&self) -> Result<()> { let mut work = 0usize; for curve in &self.curves { - if let crate::CurveKind::Spline { pts, control, degree, periodic: true } = &curve.kind { + if let crate::CurveKind::Spline { pts, control, degree, periodic: true, .. } = &curve.kind { work = work.saturating_add(pts.len()); if *control || *degree != 3 || work > 1_000_000 || pts.len() > MAX_SPLINE_POINTS { return Err(bad()); @@ -136,7 +137,7 @@ mod tests { (legacy[0][1] - legacy[0][0]).normalized().unwrap().dist((legacy.last().unwrap()[3] - legacy.last().unwrap()[2]).normalized().unwrap()) > 0.01 ); - let global = |t| crate::spline_point_mode(&p, false, 3, true, t); + let global = |t| crate::spline_point_mode(&p, false, 3, true, None, t); let h = 1e-5; assert!(((global(h) - global(0.0)) / h - (global(1.0) - global(1.0 - h)) / h).len() < 0.002); } @@ -160,8 +161,9 @@ mod tests { let c = sk.add_point(Vec2::new(-4.0, 0.0), None).unwrap(); let d = sk.add_point(Vec2::new(-3.0, -2.0), None).unwrap(); let last = sk.add_point(Vec2::ZERO, None).unwrap(); - sk.add_curve(crate::CurveKind::Spline { pts: vec![first, a, b, seam], control: false, degree: 3, periodic: true }, None).unwrap(); - sk.add_curve(crate::CurveKind::Spline { pts: vec![seam, c, d, last], control: false, degree: 3, periodic: true }, None).unwrap(); + sk.add_curve(crate::CurveKind::Spline { pts: vec![first, a, b, seam], control: false, degree: 3, periodic: true, nurbs: None }, None) + .unwrap(); + sk.add_curve(crate::CurveKind::Spline { pts: vec![seam, c, d, last], control: false, degree: 3, periodic: true, nurbs: None }, None).unwrap(); sk.points[first].pos = Vec2::new(0.2, 0.1); assert!(crate::solve_with(&mut sk, &crate::Hold { points: vec![first], radii: vec![] }, None, crate::Analysis::Full, None).ok()); assert_eq!(sk.point(first), sk.point(seam)); @@ -186,7 +188,7 @@ mod tests { let p = vec![Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(3.0, 2.0), Vec2::new(-1.0, 1.0), Vec2::ZERO]; let mut sk = Sketch::new(); let source = crate::LinkSource::SketchCurve { sketch: 99, curve: "source".into() }; - let geometry = crate::LinkGeom::Spline { pts: p.clone(), control: false, degree: 3, periodic: true }; + let geometry = crate::LinkGeom::Spline { pts: p.clone(), control: false, degree: 3, periodic: true, nurbs: None }; let id = sk.add_link(crate::LinkKind::Project, source, &[geometry]).unwrap(); let curve = sk.link_curves(&id)[0]; assert!(matches!(sk.curves[curve].kind, crate::CurveKind::Spline { periodic: true, .. })); @@ -197,7 +199,8 @@ mod tests { let mut singular = Sketch::new(); let points = [Vec2::ZERO, Vec2::X, Vec2::ZERO, Vec2::new(0.0, 1.0), Vec2::ZERO].into_iter().map(|p| singular.add_point(p, None).unwrap()).collect(); - let curve = singular.add_curve(crate::CurveKind::Spline { pts: points, control: false, degree: 3, periodic: true }, None).unwrap(); + let curve = + singular.add_curve(crate::CurveKind::Spline { pts: points, control: false, degree: 3, periodic: true, nurbs: None }, None).unwrap(); let before = singular.clone(); assert!(singular.add_freeform_offset(curve, true, 0.1).is_err()); assert_eq!(singular, before); diff --git a/crates/sketch/src/profiles.rs b/crates/sketch/src/profiles.rs index 4a6da1d79..419c143a8 100644 --- a/crates/sketch/src/profiles.rs +++ b/crates/sketch/src/profiles.rs @@ -7,11 +7,13 @@ //! the innermost loop containing it, so a circle inside a rectangle gives two profiles: the //! rectangle with a hole, and the disc. +use solidcraft_geom::prelude::*; use std::f64::consts::TAU; use std::sync::Arc; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Loop2, Region2, Ring, Seg2, Vec2}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; +use solidcraft_geom::Ring; use crate::model::{CurveKind, Sketch}; use crate::shape::{Shape, intersections_within}; @@ -906,7 +908,7 @@ fn seg_boxes(s: &Seg2, out: &mut Vec) { } Seg2::Cubic { p0, p1, p2, p3 } => out.push(hull(&[p0, p1, p2, p3])), Seg2::Conic { a, apex, b, w } if w.is_finite() && w > 0.0 => out.push(hull(&[a, apex, b])), - Seg2::Bezier { n, ref p } if (1..=solidcraft_geom::MAX_BEZIER_DEGREE).contains(&(n as usize)) => { + Seg2::Bezier { n, ref p } if (1..=solidcore_record::MAX_BEZIER_DEGREE).contains(&(n as usize)) => { out.push(hull(p.get(..=n as usize).unwrap_or(p))); } // Anything else: the very points the search samples. diff --git a/crates/sketch/src/profiling.rs b/crates/sketch/src/profiling.rs index 667fddba1..dbb7dd190 100644 --- a/crates/sketch/src/profiling.rs +++ b/crates/sketch/src/profiling.rs @@ -63,6 +63,8 @@ pub enum StopReason { ResidualTolerance, NoImprovement, IterationLimit, + /// A status-only solve gave up: the iteration stalled far from a solution. + Stalled, /// The shared frame-work budget was exhausted after evaluating the initial residual. WorkBudget, } @@ -310,7 +312,7 @@ pub(crate) fn trial(record: Trial) { mod tests { use super::*; use crate::{Analysis, ConstraintKind, Hold, Sketch, solve_with}; - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; fn distance(x: f64) -> Sketch { let mut sk = Sketch::new(); diff --git a/crates/sketch/src/redundancy_tests.rs b/crates/sketch/src/redundancy_tests.rs index 3b284b52f..81feb2423 100644 --- a/crates/sketch/src/redundancy_tests.rs +++ b/crates/sketch/src/redundancy_tests.rs @@ -80,7 +80,7 @@ fn sparse_and_dense_rows_match_over_seeded_mixed_rank_matrices() { #[test] fn real_sketch_jacobians_keep_redundant_blocks_and_support() { use crate::ConstraintKind; - use solidcraft_geom::Vec2; + use solidcore_record::Vec2; for seed in 0..8 { let mut sk = Sketch::new(); diff --git a/crates/sketch/src/shape.rs b/crates/sketch/src/shape.rs index 92847d687..ae73cbc8a 100644 --- a/crates/sketch/src/shape.rs +++ b/crates/sketch/src/shape.rs @@ -1,8 +1,9 @@ //! Analytic curve shapes for geometry operations (profiles, trim, extend, fillet…). +use solidcraft_geom::prelude::*; use std::f64::consts::TAU; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; use crate::model::{CurveKind, Sketch}; @@ -141,14 +142,24 @@ const ON_CURVE: f64 = 1e-4; /// Curves considered for a snap, so a hostile sketch cannot stall the pointer. const MAX_INTERSECTION_CANDIDATES: usize = 256; +/// Infinite construction lines use their full support; all other curves keep their bounds. +fn snap_distance(shape: &Shape, infinite: bool, p: Vec2) -> f64 { + if infinite && matches!(shape, Shape::Line { .. }) { p.dist(shape.project(p)) } else { shape.dist(p) } +} + /// The crossing of `x` and `y` nearest `near` that lies on both bounded curves. pub fn nearest_crossing(x: &Shape, y: &Shape, near: Vec2) -> Option { + nearest_crossing_with_extents(x, y, near, [false; 2]) +} + +fn nearest_crossing_with_extents(x: &Shape, y: &Shape, near: Vec2, infinite: [bool; 2]) -> Option { if !near.is_finite() { return None; } let mut best: Option<(f64, Vec2)> = None; + let [infinite_x, infinite_y] = infinite; for q in intersections_within(x, y, 1e-6) { - if !q.is_finite() || x.dist(q) > ON_CURVE || y.dist(q) > ON_CURVE { + if !(q.is_finite() && snap_distance(x, infinite_x, q) <= ON_CURVE && snap_distance(y, infinite_y, q) <= ON_CURVE) { continue; } let d = q.dist(near); @@ -161,28 +172,29 @@ pub fn nearest_crossing(x: &Shape, y: &Shape, near: Vec2) -> Option { /// The nearest crossing of two lines, circles or arcs of `sk` to `p` within `tol`. /// -/// Skips a crossing that already has a sketch point. Curves whose bounded distance from `p` -/// is greater than `tol` cannot meet near the cursor and are ignored. +/// Skips a crossing that already has a sketch point. Curves farther than `tol` from `p` +/// cannot meet near the cursor and are ignored. Infinite lines use their full support; +/// ordinary segments and arcs keep their bounds. pub fn nearest_curve_intersection(sk: &Sketch, p: Vec2, tol: f64) -> Option<(Vec2, usize, usize)> { if !p.is_finite() || !tol.is_finite() || tol <= 0.0 { return None; } - let mut candidates: Vec<(usize, Shape)> = Vec::new(); - for i in 0..sk.curves.len() { + let mut candidates: Vec<(usize, Shape, bool)> = Vec::new(); + for (i, curve) in sk.curves.iter().enumerate() { if candidates.len() >= MAX_INTERSECTION_CANDIDATES { break; } let Some(sh) = sk.shape(i) else { continue }; - if sh.dist(p) <= tol { - candidates.push((i, sh)); + if snap_distance(&sh, curve.infinite, p) <= tol { + candidates.push((i, sh, curve.infinite)); } } let mut best: Option<(f64, Vec2, usize, usize)> = None; for a in 0..candidates.len() { for b in a + 1..candidates.len() { - let Some((ia, sa)) = candidates.get(a) else { continue }; - let Some((ib, sb)) = candidates.get(b) else { continue }; - let Some(q) = nearest_crossing(sa, sb, p) else { continue }; + let Some((ia, sa, infinite_a)) = candidates.get(a) else { continue }; + let Some((ib, sb, infinite_b)) = candidates.get(b) else { continue }; + let Some(q) = nearest_crossing_with_extents(sa, sb, p, [*infinite_a, *infinite_b]) else { continue }; let d = q.dist(p); if d > tol { continue; @@ -253,6 +265,12 @@ impl Shape { } impl Sketch { + /// The nearest crossing of two analytic curves, respecting infinite construction lines. + pub fn nearest_crossing(&self, a: usize, b: usize, near: Vec2) -> Option { + let infinite = [self.curves.get(a)?.infinite, self.curves.get(b)?.infinite]; + nearest_crossing_with_extents(&self.shape(a)?, &self.shape(b)?, near, infinite) + } + /// The analytic shape of a curve (arcs counter-clockwise from their stored start). pub fn shape(&self, ci: usize) -> Option { match self.curves.get(ci)?.kind { @@ -286,6 +304,51 @@ mod intersection_snap_tests { assert_eq!([i.min(j), i.max(j)], [a.min(b), a.max(b)]); } + #[test] + fn infinite_line_crossing_snaps_beyond_both_defining_segments() { + for reverse in [false, true] { + let mut sk = Sketch::new(); + let mut lines = [(v(20.0, 40.0), v(20.0, 50.0)), (v(40.0, 15.0), v(50.0, 15.0))]; + if reverse { + lines.reverse(); + } + for (a, b) in lines { + let i = sk.add_line(a, b, None, None, None).unwrap(); + sk.curves[i].construction = true; + } + let near = v(20.4, 15.4); + assert!(nearest_curve_intersection(&sk, near, 1.0).is_none(), "finite construction segments do not cross"); + for curve in &mut sk.curves { + curve.infinite = true; + } + let (at, a, b) = nearest_curve_intersection(&sk, near, 1.0).expect("infinite lines cross"); + assert!(at.dist(v(20.0, 15.0)) < 1e-9, "{at:?}"); + assert_ne!(a, b); + } + } + + #[test] + fn infinite_line_crossing_keeps_the_other_curves_bounds() { + let mut sk = Sketch::new(); + let line = sk.add_line(v(-6.0, 30.0), v(-6.0, 40.0), None, None, None).unwrap(); + sk.curves[line].infinite = true; + sk.curves[line].construction = true; + sk.add_arc(v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0), [None; 3], None).unwrap(); + assert!(nearest_curve_intersection(&sk, v(-6.0, 8.0), 1.0).is_none(), "the missing part of the arc is not a crossing"); + let CurveKind::Line { a, b } = sk.curves[line].kind else { panic!("line") }; + sk.points[a].pos.x = 6.0; + sk.points[b].pos.x = 6.0; + let (at, _, _) = nearest_curve_intersection(&sk, v(6.2, 8.2), 1.0).expect("the drawn arc crosses the infinite line"); + assert!(at.dist(v(6.0, 8.0)) < 1e-9, "{at:?}"); + + let mut sk = Sketch::new(); + let vertical = sk.add_line(v(20.0, 40.0), v(20.0, 50.0), None, None, None).unwrap(); + sk.curves[vertical].infinite = true; + sk.curves[vertical].construction = true; + sk.add_line(v(40.0, 15.0), v(50.0, 15.0), None, None, None).unwrap(); + assert!(nearest_curve_intersection(&sk, v(20.4, 15.4), 1.0).is_none(), "the finite line must not extend"); + } + #[test] fn nearest_curve_intersection_skips_a_crossing_that_already_has_a_point() { let mut sk = Sketch::new(); diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index 3e3ab9354..a6e2de8c2 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -14,7 +14,8 @@ //! analysis runs only on what remains. use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::prelude::*; use crate::decompose::Budget; use crate::linalg::{Mat, determined_vars, solve as lin_solve}; @@ -42,6 +43,19 @@ pub const MAX_COMPONENT_VARS: usize = 4_000; const TOL: f64 = 1e-9; /// A solution is accepted when every residual is below this (mm). const ACCEPT: f64 = 1e-6; +/// A solve that only asks whether it succeeds ([`Analysis::StatusOnly`], the held solves of a +/// drag) gives up on a component once LM has stalled far from a solution: over the last +/// `STALL_ITERS` iterations the sum of squared residuals fell by at most `STALL_DECREASE` of +/// itself, and the largest residual is still above `STALL_RESIDUAL` (mm). Such a run sits in a +/// least-squares valley of constraints that conflict, crawling until `MAX_ITERS`, and a held +/// solve runs LM up to three times (#6606). Measured on about 62,000 LM runs that succeeded +/// (the sketch and engine tests and 120 generated sketch scripts with 2,900 drags), the slowest +/// still fell by 1.4e-3 of itself over any 20 iterations while it was that far off: some cross +/// a plateau for dozens of iterations and then converge, so the threshold stays a hundred times +/// below that. Other solves keep iterating: their report names what a failure leaves violated. +const STALL_ITERS: usize = 20; +const STALL_DECREASE: f64 = 1e-5; +const STALL_RESIDUAL: f64 = 1e-4; /// How much less it costs a solve to move a point held on a curve than any other point: such a /// point is placed relative to the curve, so it follows the curve rather than the curve it. const SLIDE_WEIGHT: f64 = 0.01; @@ -183,7 +197,9 @@ fn layout(sk: &Sketch, hold: &Hold) -> Layout { .iter() .enumerate() .map(|(i, c)| match c.kind { - CurveKind::Circle { .. } | CurveKind::Ellipse { .. } if c.link.is_none() && !c.fixed && !hold.radii.contains(&i) => { + CurveKind::Circle { .. } | CurveKind::Ellipse { .. } + if c.link.is_none() && !c.fixed && !hold.radii.contains(&i) && !sk.offset_circle_follows_source(i) => + { n += 1; Some(n - 1) } @@ -258,9 +274,9 @@ impl State<'_> { }; crate::curves::ellipse_polyline(self.p(*ci), self.p(*m), r) } - Some(CurveKind::Spline { pts, control, degree, periodic }) => { + Some(CurveKind::Spline { pts, control, degree, periodic, nurbs }) => { let p = self.spline_points(pts, *periodic); - crate::curves::spline_polyline_mode(&p, *control, *degree, *periodic) + crate::curves::spline_polyline_mode(&p, *control, *degree, *periodic, nurbs.as_ref()) } Some(CurveKind::Conic { a, b, apex, rho }) => crate::curves::conic_polyline(self.p(*a), self.p(*apex), self.p(*b), *rho), _ => Vec::new(), @@ -293,13 +309,15 @@ impl State<'_> { let y = delta.cross(u) / (a * r); return (x.hypot(y) - 1.0) * a.min(r); } - Some(CurveKind::Spline { pts, control, degree, periodic }) => { + Some(CurveKind::Spline { pts, control, degree, periodic, nurbs }) => { let p = self.spline_points(pts, *periodic); if p.len() < 2 { return q.dist(p.first().copied().unwrap_or_default()); } - if *control { - let k = (*degree as usize).min(solidcraft_geom::MAX_BEZIER_DEGREE).min(p.len().saturating_sub(1)).max(1); + if let Some(nurbs) = nurbs { + nurbs.segs(&p, *degree).unwrap_or_default() + } else if *control { + let k = (*degree as usize).min(solidcore_record::MAX_BEZIER_DEGREE).min(p.len().saturating_sub(1)).max(1); crate::curves::bspline_beziers(&p, k).iter().filter_map(|span| solidcraft_geom::bezier(span)).collect() } else { crate::curves::fit_beziers_mode(&p, *periodic) @@ -393,10 +411,10 @@ impl State<'_> { let (cc, r) = self.round(c); (cc - self.p(p)) / (r * r).max(1e-24) } - CurveKind::Spline { pts, control, degree, periodic } => { + CurveKind::Spline { pts, control, degree, periodic, nurbs } => { let q = self.spline_points(pts, *periodic); let at_end = pts.last() == Some(&p) && pts.first() != Some(&p); - crate::curves::end_curvature(&|t| crate::curves::spline_point_mode(&q, *control, *degree, *periodic, t), at_end) + crate::curves::end_curvature(&|t| crate::curves::spline_point_mode(&q, *control, *degree, *periodic, nurbs.as_ref(), t), at_end) } CurveKind::Conic { a, b, apex, rho } => { let (pa, pb, px) = (self.p(*a), self.p(*b), self.p(*apex)); @@ -487,11 +505,16 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec) { } Horizontal { l } => { let (a, b) = s.line(l); - out.push(b.y - a.y); + let scale = if s.sk.curves.get(l).is_some_and(|c| c.infinite) { (b - a).len().max(1e-12) } else { 1.0 }; + // An infinite line's defining points may be very close together. Its visible + // direction must remain horizontal even when their separation is below the + // distance tolerance, so measure direction rather than endpoint distance. + out.push((b.y - a.y) / scale); } Vertical { l } => { let (a, b) = s.line(l); - out.push(b.x - a.x); + let scale = if s.sk.curves.get(l).is_some_and(|c| c.infinite) { (b - a).len().max(1e-12) } else { 1.0 }; + out.push((b.x - a.x) / scale); } HorizontalPoints { p, q } => out.push(s.p(q).y - s.p(p).y), VerticalPoints { p, q } => out.push(s.p(q).x - s.p(p).x), @@ -594,6 +617,13 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec) { LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value), PointCircleDistance { p, c, value, inside } => out.push(s.point_circle_gap(p, c, inside) - value), CircleCircleDistance { a, b, value, circles } => out.push(s.circle_circle_gap(a, b, circles) - value), + // A length within convergence tolerance of zero means the line's two ends meet: + // the component rows keep both directions constrained even when they do, the way a + // coincidence does (the same treatment a distance of zero gets above). + Length { l, value } if value.abs() <= TOL => { + let (a, b) = s.line(l); + out.extend([b.x - a.x, b.y - a.y]); + } Length { l, value } => { let (a, b) = s.line(l); out.push(a.dist(b) - value); @@ -1026,7 +1056,7 @@ fn system(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec)], x: &mut [f6 for &v in vars { let Some(x0) = x.get(v).copied() else { continue }; let opening = distance_opening_slope(&State { sk, lay, x }, b, v); - let h = 1e-7 * x0.abs().max(1.0); + let h = direction_difference_step(&State { sk, lay, x }, b, v, x0); if let Some(xv) = x.get_mut(v) { *xv = x0 + h; } @@ -1078,7 +1108,7 @@ fn local_system( let Some(c) = col.get(v).copied().filter(|c| *c < ncols) else { continue }; let Some(x0) = x.get(v).copied() else { continue }; let opening = distance_opening_slope(&State { sk, lay, x }, b, v); - let h = 1e-7 * x0.abs().max(1.0); + let h = direction_difference_step(&State { sk, lay, x }, b, v, x0); if let Some(xv) = x.get_mut(v) { *xv = x0 + h; } @@ -1102,6 +1132,32 @@ fn local_system( (r, j, owner) } +/// An infinite line's direction derivative must be sampled within its defining span. The +/// usual coordinate-sized step can cross its other end and measure a half-turn instead +/// of the local slope when the saved defining points are very close (#11001). +fn direction_difference_step(s: &State<'_>, block: &Block<'_>, variable: usize, value: f64) -> f64 { + let mut step = 1e-7 * value.abs().max(1.0); + let Block::User(_, kind) = block else { return step }; + let lines = match **kind { + ConstraintKind::Angle { a, b, .. } => [Some(a), Some(b)], + ConstraintKind::LineAngle { l, .. } => [Some(l), None], + ConstraintKind::Horizontal { l } | ConstraintKind::Vertical { l } if s.sk.curves.get(l).is_some_and(|c| c.infinite) => [Some(l), None], + _ => return step, + }; + for l in lines.into_iter().flatten() { + let Some(CurveKind::Line { a, b }) = s.sk.curves.get(l).filter(|c| c.infinite).map(|c| &c.kind) else { continue }; + let depends = [a, b].into_iter().any(|&p| s.lay.pvar.get(p).copied().flatten().is_some_and(|v| variable == v || variable == v + 1)); + if depends { + let length = (s.p(*b) - s.p(*a)).len(); + if length > 0.0 { + step = step.min(length * 1e-3); + } + } + } + // Keep both samples representable when the sketch is far from its origin. + step.max(value.abs() * f64::EPSILON * 8.0) +} + fn max_abs(v: &[f64]) -> f64 { v.iter().fold(0.0_f64, |m, x| if x.is_finite() { m.max(x.abs()) } else { f64::INFINITY }) } @@ -1110,13 +1166,11 @@ fn norm2(v: &[f64]) -> f64 { } /// Levenberg–Marquardt on one component (variables `vars`, blocks `blocks`). Returns the -/// iterations and the largest residual left. -fn lm(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec)], vars: &[usize], x: &mut Vec, col: &[usize]) -> (usize, f64) { - lm_capped(sk, lay, blocks, vars, x, col, MAX_ITERS) -} - -/// [`lm`], counting its work against a live drag frame's numerical allowance when `budget` has -/// one ([`Budget::frame`]). The solve itself runs as it would without it. +/// iterations and the largest residual left. Its work counts against a live drag frame's +/// numerical allowance when `budget` has one ([`Budget::frame`]); the solve itself runs as it +/// would without it. `give_up`: stop once +/// stalled (see [`STALL_ITERS`]); not in a live frame, whose allowance is measured in the work +/// the full iteration does. fn lm_in( sk: &Sketch, lay: &Layout, @@ -1125,9 +1179,10 @@ fn lm_in( x: &mut Vec, col: &[usize], budget: &mut Budget, + give_up: bool, ) -> (usize, f64) { if !budget.counts_numeric() { - return lm(sk, lay, blocks, vars, x, col); + return lm_run(sk, lay, blocks, vars, x, col, MAX_ITERS, None, give_up).unwrap_or((0, f64::INFINITY)); } let mut meter = Budget::new(usize::MAX); let out = lm_capped_with_budget(sk, lay, blocks, vars, x, col, MAX_ITERS, Some(&mut meter)).unwrap_or((0, f64::INFINITY)); @@ -1152,6 +1207,20 @@ fn lm_capped( /// Deterministic work units, shared with the frame's decomposition budget. Estimates bound /// dense arithmetic; they are not a wall-clock deadline. None means no residual was evaluated. fn lm_capped_with_budget( + sk: &Sketch, + lay: &Layout, + blocks: &[(Block, Vec)], + vars: &[usize], + x: &mut Vec, + col: &[usize], + max_iters: usize, + budget: Option<&mut Budget>, +) -> Option<(usize, f64)> { + lm_run(sk, lay, blocks, vars, x, col, max_iters, budget, false) +} + +/// [`lm_capped_with_budget`], giving up once stalled when `give_up` (see [`STALL_ITERS`]). +fn lm_run( sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec)], @@ -1160,6 +1229,7 @@ fn lm_capped_with_budget( col: &[usize], max_iters: usize, mut budget: Option<&mut Budget>, + give_up: bool, ) -> Option<(usize, f64)> { #[cfg(feature = "solver-profiling")] let _timer = profiling::timer(Phase::Lm); @@ -1175,12 +1245,25 @@ fn lm_capped_with_budget( let mut f = norm2(&r); #[cfg(feature = "solver-profiling")] let run = profiling::start_run(n, r.len(), max_iters, f); + // The sum of squares at the start of each iteration, while giving up is allowed. + let mut costs = Vec::new(); for it in 0..max_iters { if max_abs(&r) < TOL { #[cfg(feature = "solver-profiling")] profiling::finish_run(run, StopReason::ResidualTolerance, max_abs(&r)); return Some((it, max_abs(&r))); } + if give_up { + if let Some(&earlier) = it.checked_sub(STALL_ITERS).and_then(|k| costs.get(k)) + && max_abs(&r) > STALL_RESIDUAL + && earlier - f <= STALL_DECREASE * earlier + { + #[cfg(feature = "solver-profiling")] + profiling::finish_run(run, StopReason::Stalled, max_abs(&r)); + return Some((it, max_abs(&r))); + } + costs.push(f); + } let normal_work = n.saturating_mul(n).saturating_mul(r.len()).saturating_add(evaluation_work.saturating_mul(n.saturating_mul(2).saturating_add(1))); if !within_budget(&mut budget, normal_work) { @@ -1516,7 +1599,7 @@ fn accumulate(sk: &Sketch, lay: &Layout, b: &Block, unit: &[usize], x: &mut [f64 let (mut plus, mut minus) = (Vec::new(), Vec::new()); for (&v, dk) in unit.iter().zip(&mut d) { let Some(x0) = x.get(v).copied() else { continue }; - let h = 1e-7 * x0.abs().max(1.0); + let h = direction_difference_step(&State { sk, lay, x }, b, v, x0); for (at, out) in [(x0 + h, &mut plus), (x0 - h, &mut minus)] { if let Some(xv) = x.get_mut(v) { *xv = at; @@ -2726,6 +2809,10 @@ fn solve_inner( } // Column of each variable in the system being solved or analysed (usize::MAX outside it). let mut col = vec![usize::MAX; lay.n]; + // Only success matters to a status-only solve: a component LM cannot solve is left as soon + // as the iteration stalls (see `STALL_ITERS`). It fails either way, and a failed solve + // leaves the geometry as it was. + let give_up = analysis == Analysis::StatusOnly; let mut iterations = 0; let mut continuations = 0; @@ -2761,7 +2848,7 @@ fn solve_inner( let rest = unpinned(vars, &pin, None); let rest_blocks = blocks_reading(&sub, &rest); columns(&mut col, &rest, vars); - let (its, r) = if rest.is_empty() { (0, 0.0) } else { lm_in(sk, &lay, &rest_blocks, &rest, &mut x, &col, budget) }; + let (its, r) = if rest.is_empty() { (0, 0.0) } else { lm_in(sk, &lay, &rest_blocks, &rest, &mut x, &col, budget, give_up) }; iterations += its; residual = r; solved = residual < ACCEPT; @@ -2785,7 +2872,7 @@ fn solve_inner( // the seed did not move it. let reseeded = unseeded.as_ref().filter(|plain| vars.iter().any(|v| plain.get(*v).is_some_and(Option::is_some))); if !(solved || pinned_failed && reseeded.is_some()) { - let (its, r) = lm_in(sk, &lay, &sub, vars, &mut x, &col, budget); + let (its, r) = lm_in(sk, &lay, &sub, vars, &mut x, &col, budget, give_up); iterations += its; residual = r; } @@ -2799,7 +2886,7 @@ fn solve_inner( *s = plain.get(v).copied().flatten().unwrap_or(*s0); } } - let (its, r) = lm_in(sk, &lay, &sub, vars, &mut x, &col, budget); + let (its, r) = lm_in(sk, &lay, &sub, vars, &mut x, &col, budget, give_up); iterations += its; residual = r; } @@ -2830,7 +2917,7 @@ fn solve_inner( iterations += its; if !done { // The last sub-step's solution, solved for the new values in one jump. - let (its, r) = lm_in(sk, &lay, &sub, vars, &mut from, &col, budget); + let (its, r) = lm_in(sk, &lay, &sub, vars, &mut from, &col, budget, false); iterations += its; done = edit.holds(r, &State { sk, lay: &lay, x: &from }); } @@ -3031,7 +3118,7 @@ fn solve_inner( } } for curve in &sk.curves { - if let CurveKind::Spline { pts, control, degree, periodic: true } = &curve.kind { + if let CurveKind::Spline { pts, control, degree, periodic: true, .. } = &curve.kind { let points = pts.iter().map(|i| positions.get(*i).copied()).collect::>>(); if *control || *degree != 3 || points.as_ref().is_none_or(|p| crate::periodic::validate_periodic_points(p).is_err()) { valid = false; diff --git a/crates/sketch/src/spline_points.rs b/crates/sketch/src/spline_points.rs index a2ab1308e..57ecf8555 100644 --- a/crates/sketch/src/spline_points.rs +++ b/crates/sketch/src/spline_points.rs @@ -1,6 +1,6 @@ //! New points on an existing fit spline (#6533): a fit point inserted where the curve already -//! runs, or a new first or last point the spline runs on to. Also a spline's direction reversed -//! (#8224). +//! runs, or a new first or last point the spline runs on to. One point taken out of a spline +//! (#10783). Also a spline's direction reversed (#8224). //! //! The spline keeps its curve index and every point it had (the new point is appended to //! `Sketch::points`), so constraints on its points and on the curve stay as they were. @@ -8,7 +8,8 @@ //! Control point splines take no new points yet: their knots are uniform, so one more control //! point re-spreads every span and the whole curve moves, wherever the point goes. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use crate::model::{ConstraintKind, CurveKind, Result, Sketch, SketchError}; @@ -87,6 +88,77 @@ impl Sketch { Ok(p) } + /// Take point `p` out of spline `ci` (#10783), and return whether the point itself went too. + /// The spline runs through (or over) its other points, and keeps its curve index, so + /// constraints on the curve and on its other points stay. The point goes with the constraints + /// on it, unless another curve uses it (it stays, for that curve) or it is the origin. + /// + /// The spline keeps at least 2 points (a closed one 3 besides its closing point, which stays). + /// An end of an open spline joined to other geometry stays, as for [`Sketch::extend_spline`]: + /// the spline would no longer end where it is joined. + pub fn remove_spline_point(&mut self, ci: usize, p: usize) -> Result { + let curve = self.curves.get(ci).ok_or_else(|| SketchError::Unknown(format!("curve {ci}")))?; + let CurveKind::Spline { pts, periodic, .. } = &curve.kind else { + return Err(SketchError::WrongKind(curve.id.clone(), "only a spline has points to remove".into())); + }; + let (pts, periodic) = (pts.clone(), *periodic); + if curve.link.is_some() { + return Err(SketchError::Invalid("a projected spline follows its source; its points can't be removed".into())); + } + if self.freeform_offsets.iter().any(|o| o.output == curve.id) { + return Err(SketchError::Invalid("an offset spline follows its source; break the offset association first".into())); + } + if self.freeform_offsets.iter().any(|o| o.source == curve.id) { + return Err(SketchError::Invalid( + "not supported yet: removing a point from a spline that has an offset; break the offset association first".into(), + )); + } + if self.patterns.iter().any(|pattern| pattern.contains(&curve.id)) { + return Err(SketchError::Invalid("not supported yet: removing a point from a patterned spline".into())); + } + let at = match pts.iter().enumerate().filter(|(_, q)| **q == p).map(|(i, _)| i).collect::>().as_slice() { + [] => return Err(SketchError::Invalid(format!("that point isn't one of {}'s points", curve.id))), + [at] => *at, + _ => return Err(SketchError::Invalid("that point closes the spline; remove another one".into())), + }; + let last = pts.len().saturating_sub(1); + if periodic && (at == 0 || at == last) { + return Err(SketchError::Invalid("a closed spline's closing point stays; remove another one".into())); + } + if pts.len() < if periodic { 5 } else { 3 } { + return Err(SketchError::Invalid(format!("a spline keeps at least {} points", if periodic { 3 } else { 2 }))); + } + if !periodic && (at == 0 || at == last) { + let joined = self.curves.iter().enumerate().any(|(i, c)| i != ci && c.kind.uses(p)) + || self.constraints.iter().any(|k| { + let (points, curves) = k.kind.indices(); + points.contains(&p) || (curves.contains(&ci) && matches!(k.kind, ConstraintKind::Tangent { .. } | ConstraintKind::Smooth { .. })) + }); + if joined { + return Err(SketchError::Invalid( + "that end of the spline is joined to other geometry or held by a constraint; remove those first".into(), + )); + } + } + let mut left = pts; + left.remove(at); + if periodic { + let pos: Vec = + left.iter().map(|i| self.point(*i).ok_or_else(|| SketchError::Unknown(format!("point {i}")))).collect::>()?; + crate::periodic::validate_periodic_points(&pos)?; + } + if let Some(CurveKind::Spline { pts, .. }) = self.curves.get_mut(ci).map(|c| &mut c.kind) { + *pts = left; + } + // The origin (point 0) is never removed. + if p == 0 || self.point_used_by_curve(p) { + return Ok(false); + } + self.keep_ties_through(&[p]); + self.remove_points(&[p]); + Ok(true) + } + /// Reverse spline `ci`'s direction: its last point becomes its first and the curve runs the /// other way along the same path. Its points are reversed in place, so every point, and every /// constraint on them and on the curve, stays. The shape doesn't change: a fit spline's chord diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index d9347a939..fbc85c223 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -1,6 +1,7 @@ +use solidcraft_geom::prelude::*; use std::f64::consts::{FRAC_PI_2, PI}; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; use crate::*; @@ -25,6 +26,15 @@ impl Lcg { } } +thread_local! { + static ID_SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A linear search for a point or curve by id on this thread. +pub(crate) fn count_id_search() { + ID_SEARCHES.with(|c| c.set(c.get() + 1)); +} + /// Run `f` with the constructive seed on or off, without the seed-on/seed-off comparison (for /// tests that measure the difference). pub(crate) fn seeded(on: bool, f: impl FnOnce() -> T) -> T { @@ -201,6 +211,27 @@ fn zero_distance_edits_preserve_dimension_rank() { } } +/// A length dimension of zero still constrains the sketch: the two ends of the line meet, and +/// the dimension holds them together instead of leaving a degree of freedom behind (#5505). +#[test] +fn zero_length_keeps_the_line_constrained() { + for seed in [false, true] { + seeded(seed, || { + let mut sk = Sketch::new(); + let a = sk.add_point(v(0.0, 0.0), None).unwrap(); + let b = sk.add_point(v(10.0, 0.0), None).unwrap(); + let l = sk.add_line_pts(a, b, None).unwrap(); + sk.add_constraint(ConstraintKind::Fix { p: a }, None).unwrap(); + let id = sk.add_constraint(ConstraintKind::Length { l, value: 0.0 }, None).unwrap(); + let report = solve(&mut sk); + assert!(report.ok(), "{report:?}"); + assert_eq!(report.dof, 0, "a zero length holds the line's ends together: {report:?}"); + assert!(!report.redundant.contains(&id), "a zero length is not redundant: {report:?}"); + assert!(sk.point(b).unwrap().dist(v(0.0, 0.0)) < 1e-6, "{:?}", sk.point(b)); + }); + } +} + #[test] fn under_constrained_reports_dof() { let mut sk = Sketch::new(); @@ -679,7 +710,7 @@ fn near_overlaps_that_are_not_one_path_keep_their_regions() { .iter() .map(|p| sk.add_point(*p, None).unwrap()) .collect(); - sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: true, degree: 3, periodic: false }, None).unwrap(); + sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: true, degree: 3, periodic: false, nurbs: None }, None).unwrap(); sk.add_line_pts(ids[3], ids[0], None).unwrap(); let ps = find_profiles(&sk); assert_eq!(ps.len(), 1, "{:?}", ps.iter().map(|p| p.area).collect::>()); @@ -757,13 +788,15 @@ fn curves_lying_on_one_another_do_not_chain_past_the_tolerance() { #[test] fn merging_adjacent_regions() { - let a = - solidcraft_geom::Region2 { outer: solidcraft_geom::Loop2::polygon(&[v(0.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)]), holes: vec![] }; - let b = solidcraft_geom::Region2 { - outer: solidcraft_geom::Loop2::polygon(&[v(10.0, 0.0), v(20.0, 0.0), v(20.0, 10.0), v(10.0, 10.0)]), + let a = solidcore_record::Region2 { + outer: solidcore_record::Loop2::polygon(&[v(0.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)]), holes: vec![], }; - let c = solidcraft_geom::Region2 { outer: solidcraft_geom::Loop2::polygon(&[v(50.0, 0.0), v(60.0, 0.0), v(60.0, 10.0)]), holes: vec![] }; + let b = solidcore_record::Region2 { + outer: solidcore_record::Loop2::polygon(&[v(10.0, 0.0), v(20.0, 0.0), v(20.0, 10.0), v(10.0, 10.0)]), + holes: vec![], + }; + let c = solidcore_record::Region2 { outer: solidcore_record::Loop2::polygon(&[v(50.0, 0.0), v(60.0, 0.0), v(60.0, 10.0)]), holes: vec![] }; let m = merge_regions(&[a, b, c]); assert_eq!(m.len(), 2); let mut areas: Vec = m.iter().map(|r| r.area()).collect(); @@ -919,6 +952,25 @@ fn links_update_in_place_rebuild_and_break() { assert_eq!(back.link(&j3).unwrap().kind, LinkKind::Intersect); } +/// A reference that names no body describes itself by its kind alone: the message must not +/// end in "face of " with nothing after the "of" (#4929). +#[test] +fn a_source_without_a_body_name_names_its_kind_alone() { + use solidcore_record::Vec3; + let at = Vec3::ZERO; + for (source, expected) in [ + (LinkSource::Edge { body: String::new(), at }, "edge"), + (LinkSource::Face { body: String::new(), at }, "face"), + (LinkSource::Vertex { body: String::new(), at }, "vertex"), + (LinkSource::Iso { body: String::new(), at, dir: "u".into() }, "isoparametric curve"), + (LinkSource::Spun { body: String::new(), origin: at, dir: Vec3::X }, "spun profile"), + ] { + assert_eq!(source.describe(), expected, "{source:?}"); + } + // A named body keeps its name. + assert_eq!(LinkSource::Face { body: "Body1".into(), at }.describe(), "face of Body1"); +} + /// Many independent constrained rectangles solve quickly (per-component work). #[test] fn large_sketch_solves_fast() { @@ -968,7 +1020,7 @@ fn long_connected_chain_solves() { /// cut in two by a line through it (each side gets an exact sub-curve ending on the line). #[test] fn exact_profiles_for_high_degree_and_cut_free_form_curves() { - use solidcraft_geom::Seg2; + use solidcore_record::Seg2; let exact_loop = |p: &Profile| p.region.outer.segs.iter().all(|s| !matches!(s, Seg2::Line { .. }) || s.length() > 1.0); let closed = |p: &Profile| p.region.outer.joints().all(|(a, b)| a.end().dist(b.start()) < 1e-9); // Degree 5 over six points, closed by a line. @@ -977,7 +1029,7 @@ fn exact_profiles_for_high_degree_and_cut_free_form_curves() { .iter() .map(|p| sk.add_point(*p, None).unwrap()) .collect(); - sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: true, degree: 5, periodic: false }, None).unwrap(); + sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: true, degree: 5, periodic: false, nurbs: None }, None).unwrap(); sk.add_line_pts(ids[5], ids[0], None).unwrap(); let pr = find_profiles(&sk); assert_eq!(pr.len(), 1); @@ -986,7 +1038,7 @@ fn exact_profiles_for_high_degree_and_cut_free_form_curves() { // A fit spline arch over a base line, cut by a vertical line at x = 10. let mut sk = Sketch::default(); let ids: Vec = [v(0.0, 0.0), v(6.0, 9.0), v(14.0, 9.0), v(20.0, 0.0)].iter().map(|p| sk.add_point(*p, None).unwrap()).collect(); - sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: false, degree: 3, periodic: false }, None).unwrap(); + sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: false, degree: 3, periodic: false, nurbs: None }, None).unwrap(); sk.add_line_pts(ids[3], ids[0], None).unwrap(); let (a, b) = (sk.add_point(v(10.0, -5.0), None).unwrap(), sk.add_point(v(10.0, 20.0), None).unwrap()); sk.add_line_pts(a, b, None).unwrap(); @@ -1057,7 +1109,7 @@ fn a_degree_nine_control_spline_stays_exact_and_closes_a_profile_exactly() { let bump = [v(0.0, 0.0), v(1.5, 4.0), v(3.0, 7.0), v(5.0, 9.5), v(7.5, 11.0), v(12.5, 11.0), v(15.0, 9.5), v(17.0, 7.0), v(18.5, 4.0), v(20.0, 0.0)]; let pts: Vec = bump.iter().map(|q| sk.add_point(*q, None).unwrap()).collect(); - let s = sk.add_curve(CurveKind::Spline { pts: pts.clone(), control: true, degree: 9, periodic: false }, None).unwrap(); + let s = sk.add_curve(CurveKind::Spline { pts: pts.clone(), control: true, degree: 9, periodic: false, nurbs: None }, None).unwrap(); let pieces = sk.exact_pieces(s); assert_eq!(pieces.len(), 1, "{pieces:?}"); let Seg2::Bezier { n, p } = pieces[0] else { panic!("{:?}", pieces[0]) }; @@ -1092,7 +1144,7 @@ fn a_degree_nine_control_spline_stays_exact_and_closes_a_profile_exactly() { // A degree above the cap is still refused. let mut high: Vec = pts.clone(); high.push(sk.add_point(v(21.0, -2.0), None).unwrap()); - assert!(sk.add_curve(CurveKind::Spline { pts: high, control: true, degree: 10, periodic: false }, None).is_err()); + assert!(sk.add_curve(CurveKind::Spline { pts: high, control: true, degree: 10, periodic: false, nurbs: None }, None).is_err()); } /// How far apart two curves run: the largest distance from a sample of either to the other. @@ -1112,7 +1164,7 @@ fn wave_spline(sk: &mut Sketch, periodic: bool) -> (Vec, usize) { pts.pop(); pts.push(pts[0]); } - let s = sk.add_curve(CurveKind::Spline { pts: pts.clone(), control: false, degree: 3, periodic }, None).unwrap(); + let s = sk.add_curve(CurveKind::Spline { pts: pts.clone(), control: false, degree: 3, periodic, nurbs: None }, None).unwrap(); (pts, s) } @@ -1152,7 +1204,7 @@ fn a_fit_point_inserted_into_a_spline_keeps_the_curve_through_its_points() { assert!(k.insert_spline_point(s, old[2]).is_err()); assert_eq!(k, sk, "a refused insertion changes nothing"); let cv: Vec = old.iter().map(|q| k.add_point(*q + v(0.0, 30.0), None).unwrap()).collect(); - let c = k.add_curve(CurveKind::Spline { pts: cv, control: true, degree: 3, periodic: false }, None).unwrap(); + let c = k.add_curve(CurveKind::Spline { pts: cv, control: true, degree: 3, periodic: false, nurbs: None }, None).unwrap(); assert!(k.insert_spline_point(c, v(20.0, 38.0)).is_err()); let l = k.add_line(v(0.0, -10.0), v(50.0, -10.0), None, None, None).unwrap(); assert!(k.insert_spline_point(l, v(20.0, -10.0)).is_err()); @@ -1190,6 +1242,88 @@ fn a_spline_extends_to_a_new_end_unless_the_end_is_joined() { assert!(sk.extend_spline(s, v(-10.0, 5.0), true).is_err(), "already a point there"); } +/// Where spline `s`'s points are, in order. +fn spline_places(sk: &Sketch, s: usize) -> Vec { + let CurveKind::Spline { pts, .. } = &sk.curves[s].kind else { panic!("{s} is no spline") }; + pts.iter().map(|i| sk.point(*i).unwrap()).collect() +} + +/// #10783: a spline gives up one of its points. The curve runs through the others, in order, and +/// the point goes with the constraints on it; a point a line also ends at stays, for the line. +#[test] +fn a_point_removed_from_a_spline_goes_and_the_curve_keeps_the_others() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let mut others = spline_places(&sk, s); + let gone = others.remove(2); + // A free point held on the one that goes: the constraint goes, the free point stays. + let free = sk.add_point(gone, None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[2], q: free }, None).unwrap(); + let count = sk.points.len(); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(spline_places(&sk, s), others); + for q in &others { + assert!(off_curve(&sk, s, *q) < 1e-9, "the curve still runs through {q:?}"); + } + assert!(matches!(sk.curves[s].kind, CurveKind::Spline { control: false, periodic: false, .. })); + assert_eq!(sk.points.len(), count - 1, "the point went"); + assert!(sk.constraints.is_empty(), "the constraint on it went: {:?}", sk.constraints); + // A free end goes too: the spline starts at the next point. + let start = sk.curves[s].kind.ends().unwrap().0; + assert_eq!(sk.remove_spline_point(s, start), Ok(true)); + others.remove(0); + assert_eq!(spline_places(&sk, s), others); + // An inner point a line also ends at stays, for the line. + let CurveKind::Spline { pts: now, .. } = sk.curves[s].kind.clone() else { panic!() }; + let line = sk.add_line(others[1], v(40.0, 30.0), Some(now[1]), None, None).unwrap(); + assert_eq!(sk.remove_spline_point(s, now[1]), Ok(false)); + assert!(sk.curves[line].kind.uses(now[1]) && !sk.curves[s].kind.uses(now[1])); + others.remove(1); + assert_eq!(spline_places(&sk, s), others); + // Two points are as few as a spline keeps. + assert_eq!(others.len(), 2); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, sk.curves[s].kind.ends().unwrap().1).is_err()); + assert_eq!(sk, before, "a refused removal changes nothing"); +} + +/// #10783: what a spline keeps: an end joined to a line or held by a constraint, a closed +/// spline's closing point and its last three points. A control point spline gives up a point as a +/// fit point spline does. +#[test] +fn a_spline_keeps_its_joined_ends_and_closing_point() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let line = sk.add_line(sk.point(pts[4]).unwrap(), v(60.0, 0.0), Some(pts[4]), None, None).unwrap(); + let tied = sk.add_point(sk.point(pts[0]).unwrap(), None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[0], q: tied }, None).unwrap(); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, pts[4]).is_err(), "a line ends there"); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "a constraint holds the start"); + assert!(sk.remove_spline_point(s, tied).is_err(), "not one of the spline's points"); + assert!(sk.remove_spline_point(line, pts[4]).is_err(), "a line has no spline points"); + assert_eq!(sk, before, "a refused removal changes nothing"); + + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, true); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "the closing point"); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(sk.remove_spline_point(s, pts[1]), Ok(true)); + let CurveKind::Spline { pts: now, periodic, .. } = sk.curves[s].kind.clone() else { panic!() }; + assert!(periodic); + assert_eq!(now.len(), 4, "three points and the closing one: {now:?}"); + assert!(sk.remove_spline_point(s, now[1]).is_err(), "a closed spline keeps three points"); + sk.validate_periodic_splines().unwrap(); + + let mut sk = Sketch::new(); + let places = [v(0.0, 0.0), v(10.0, 10.0), v(20.0, -10.0), v(30.0, 0.0)]; + let cv: Vec = places.iter().map(|q| sk.add_point(*q, None).unwrap()).collect(); + let c = sk.add_curve(CurveKind::Spline { pts: cv.clone(), control: true, degree: 3, periodic: false, nurbs: None }, None).unwrap(); + assert_eq!(sk.remove_spline_point(c, cv[1]), Ok(true)); + assert!(matches!(sk.curves[c].kind, CurveKind::Spline { control: true, .. })); + assert_eq!(spline_places(&sk, c), vec![places[0], places[2], places[3]]); +} + /// #755: a line drawn through a junction of a loop, but 2e-5 off it, still splits the loop. The /// junction lies on the loop's two curves only, so it cuts neither of them where the line /// crosses, and that crossing, next to the junction, was taken for one already cut there: the @@ -1399,6 +1533,86 @@ fn a_fillet_folded_through_flat_is_refused_like_a_fold() { assert!(refused.is_some_and(|s| (7..=9).contains(&s)), "refused at {refused:?}"); } +/// A sketch's bounds reach a circle's and an arc's extremes, not only the points of their +/// polylines: a whole circle is one arc whose chords start at its start angle, and a circle of +/// radius 5 at (-300, 0) spans x from -305 exactly. +#[test] +fn bounds_reach_the_extremes_of_circles_and_arcs() { + let mut sk = Sketch::new(); + sk.add_circle(v(-300.0, 0.0), 5.0, None, None).unwrap(); + let (lo, hi) = sk.bounds().unwrap(); + assert!(lo.dist(v(-305.0, -5.0)) < 1e-9 && hi.dist(v(-295.0, 5.0)) < 1e-9, "{lo:?} {hi:?}"); + // A quarter arc from (10, 0) to (0, 10) about the origin: its corners, no more. + let mut sk = Sketch::new(); + sk.add_arc(v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0), [None; 3], None).unwrap(); + let (lo, hi) = sk.bounds().unwrap(); + assert!(lo.dist(v(0.0, 0.0)) < 1e-9 && hi.dist(v(10.0, 10.0)) < 1e-9, "{lo:?} {hi:?}"); +} + +/// A control spline with its own knots and weights (a projected free-form edge): its exact pieces +/// are its knot spans, a rational quadratic's are conics, its points follow its knots, it reads +/// back from a saved design the same, and knots that don't fit it are refused. +#[test] +fn a_spline_with_its_own_knots_is_its_spans_exactly() { + let mut sk = Sketch::new(); + // Two cubic Béziers end to end (the joint knot three times), the second twice as long in + // parameter: (0,0) (1,2) (2,2) (3,0) then (3,0) (4,-2) (5,-2) (6,0). + let ctrl = [v(0.0, 0.0), v(1.0, 2.0), v(2.0, 2.0), v(3.0, 0.0), v(4.0, -2.0), v(5.0, -2.0), v(6.0, 0.0)]; + let nurbs = Nurbs { knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0, 3.0], weights: Vec::new() }; + let pts: Vec = ctrl.iter().map(|q| sk.add_point(*q, None).unwrap()).collect(); + let kind = CurveKind::Spline { pts: pts.clone(), control: true, degree: 3, periodic: false, nurbs: Some(nurbs.clone()) }; + let s = sk.add_curve(kind.clone(), None).unwrap(); + let pieces = sk.exact_pieces(s); + assert_eq!(pieces.len(), 2, "{pieces:?}"); + let Seg2::Cubic { p0, p1, p2, p3 } = pieces[1] else { panic!("{:?}", pieces[1]) }; + for (got, want) in [(p0, ctrl[3]), (p1, ctrl[4]), (p2, ctrl[5]), (p3, ctrl[6])] { + assert!(got.dist(want) < 1e-12, "{got:?} {want:?}"); + } + // t runs over the knots: a third of the way is the joint, where the uniform spline over the + // same points would not be. + assert!(nurbs.point(&ctrl, 3, 1.0 / 3.0).unwrap().dist(ctrl[3]) < 1e-12); + assert!(crate::curves::spline_point(&ctrl, true, 3, 1.0 / 3.0).dist(ctrl[3]) > 1e-3); + let back = nurbs.reversed(); + let rev: Vec = ctrl.iter().rev().copied().collect(); + for k in 0..=12 { + let t = k as f64 / 12.0; + assert!(nurbs.point(&ctrl, 3, t).unwrap().dist(back.point(&rev, 3, 1.0 - t).unwrap()) < 1e-12, "t={t}"); + } + let poly = sk.polyline(s); + assert!(poly.first().unwrap().dist(ctrl[0]) < 1e-12 && poly.last().unwrap().dist(ctrl[6]) < 1e-12); + // Saved and read back: the same curve. + let json = serde_json::to_string(&kind).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), kind); + // A quarter circle of radius 2 as a rational quadratic: one conic, its middle point on the circle. + let w = std::f64::consts::FRAC_1_SQRT_2; + let quarter = Nurbs { knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], weights: vec![1.0, w, 1.0] }; + let arc = [v(2.0, 0.0), v(2.0, 2.0), v(0.0, 2.0)]; + let [Seg2::Conic { w: cw, .. }] = quarter.segs(&arc, 2).unwrap()[..] else { panic!("conic") }; + assert!((cw - w).abs() < 1e-12); + assert!((quarter.point(&arc, 2, 0.5).unwrap().len() - 2.0).abs() < 1e-12); + // Knots that don't fit: the wrong count, not clamped, decreasing, not finite, an interior knot + // past the degree, a weight that isn't positive; and knots on a fit spline. + let bad = [ + Nurbs { knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0], weights: Vec::new() }, + Nurbs { knots: vec![0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0, 3.0], weights: Vec::new() }, + Nurbs { knots: vec![0.0, 0.0, 0.0, 0.0, 2.0, 1.0, 1.0, 3.0, 3.0, 3.0, 3.0], weights: Vec::new() }, + Nurbs { knots: vec![0.0, 0.0, 0.0, 0.0, f64::NAN, 1.0, 1.0, 3.0, 3.0, 3.0, 3.0], weights: Vec::new() }, + Nurbs { knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0, 3.0], weights: Vec::new() }, + Nurbs { knots: nurbs.knots.clone(), weights: vec![1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0] }, + ]; + for (i, k) in bad.iter().enumerate() { + assert!(k.check(ctrl.len(), 3).is_err(), "{i}"); + assert!( + sk.add_curve(CurveKind::Spline { pts: pts.clone(), control: true, degree: 3, periodic: false, nurbs: Some(k.clone()) }, None).is_err(), + "{i}" + ); + assert!(k.point(&ctrl, 3, 0.5).is_none() && k.segs(&ctrl, 3).is_none() && k.polyline(&ctrl, 3).is_empty(), "{i}"); + } + let fourfold = Nurbs { knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0, 3.0], weights: Vec::new() }; + assert!(fourfold.check(8, 3).is_err()); + assert!(sk.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: false, nurbs: Some(nurbs) }, None).is_err()); +} + /// #8639: two rounded rectangles drawn as closed control-point splines with the same straight /// sides and different corners (as a DXF can carry an outline twice). Where the sides lie on each /// other the two curves' sampled pieces end a few millionths apart; every profile must still close @@ -1422,7 +1636,7 @@ fn rounded_rectangles_sharing_their_sides_leave_every_profile_closed() { } let mut ids: Vec = pts.iter().map(|p| sk.add_point(*p, None).unwrap()).collect(); ids.push(ids[0]); - sk.add_curve(CurveKind::Spline { pts: ids, control: true, degree: 3, periodic: false }, None).unwrap(); + sk.add_curve(CurveKind::Spline { pts: ids, control: true, degree: 3, periodic: false, nurbs: None }, None).unwrap(); } let mut sk = Sketch::new(); rounded(&mut sk, 0.55); @@ -1438,3 +1652,64 @@ fn rounded_rectangles_sharing_their_sides_leave_every_profile_closed() { } } } + +/// A drag step that cannot succeed gives up once the iteration has stalled (#6606). Holding +/// the two right corners of a rectangle further apart than its dimensioned left side leaves the +/// left corners a least-squares valley (the perpendicular repeats what horizontal and vertical +/// already say), along which the iteration crawled for its whole allowance. +#[test] +fn a_held_solve_that_cannot_succeed_stops_once_it_stalls() { + let mut sk = Sketch::new(); + let [bottom, right, top, left] = rect(&mut sk, [v(-6.0, -20.0), v(23.5, -20.8), v(23.5, 0.0), v(-6.0, 0.0)]); + for kind in [ + ConstraintKind::Horizontal { l: bottom }, + ConstraintKind::Horizontal { l: top }, + ConstraintKind::Vertical { l: right }, + ConstraintKind::Vertical { l: left }, + ConstraintKind::Length { l: left, value: 20.0 }, + ConstraintKind::Perpendicular { a: top, b: left }, + ] { + sk.add_constraint(kind, None).unwrap(); + } + let hold = Hold { points: sk.curves[right].kind.point_ids(), radii: vec![] }; + let reference: Vec = sk.points.iter().map(|p| p.pos).collect(); + let solve = |analysis| { + let mut moved = sk.clone(); + let rep = solve_with(&mut moved, &hold, Some(&reference), analysis, None); + assert!(!rep.ok()); + assert_eq!(moved.points, sk.points, "a failed solve leaves the geometry as it was"); + rep.iterations + }; + let stalled = solve(Analysis::StatusOnly); + assert!(stalled < 100, "a held solve gives up once stalled: {stalled} iterations"); + // A solve whose report names the violated constraints still iterates to the end. + assert!(solve(Analysis::Full) >= 500); +} + +/// Pattern upkeep runs before every solve, each drag frame included. It once looked up every +/// copy and its arc points by a linear search over all ids, so dragging anything in a sketch +/// with a large pattern of arcs spent most of each frame there; its searches must not grow +/// with the copies. The copies still follow their seed's arc direction. +#[test] +fn pattern_upkeep_does_not_search_ids_per_copy() { + let mut sk = Sketch::new(); + let center = sk.add_point(v(0.0, 0.0), None).unwrap(); + let arc = sk.add_arc(v(20.0, 0.0), v(23.0, 0.0), v(20.0, 3.0), [None, None, None], None).unwrap(); + let entities = vec![sk.curves[arc].id.clone()]; + let kind = SketchPatternKind::Circular { + center: sk.points[center].id.clone(), + count: 50, + angle: 360.0, + alignment: PatternAlignment::Right, + reversed: false, + }; + let id = sk.fresh("pat").unwrap(); + sk.patterns.push(SketchPattern { id, entities, kind: kind.clone(), count_expression: None, instances: vec![], expressions: Default::default() }); + sk.update_pattern(0, kind).unwrap(); + assert_eq!(sk.curves.len(), 50); + sk.curves[arc].reversed = true; + ID_SEARCHES.with(|c| c.set(0)); + sk.refresh_pattern_shapes(); + assert_eq!(ID_SEARCHES.with(std::cell::Cell::get), 0, "id searches in pattern upkeep"); + assert!(sk.curves.iter().all(|c| c.reversed)); +} diff --git a/crates/sketch/src/text.rs b/crates/sketch/src/text.rs index 526fd9473..85764d17c 100644 --- a/crates/sketch/src/text.rs +++ b/crates/sketch/src/text.rs @@ -13,7 +13,9 @@ use std::ops::Range; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Ring, Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; +use solidcraft_geom::Ring; +use solidcraft_geom::prelude::*; use crate::fonts::{FontData, font_data_styled}; use crate::link::{LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES}; @@ -77,7 +79,9 @@ fn link_geom(seg: Seg2) -> Option { match seg { Seg2::Line { a, b } => Some(LinkGeom::Line(a, b)), Seg2::Conic { a, apex, b, .. } => Some(LinkGeom::Conic { a, apex, b, rho: 0.5 }), - Seg2::Cubic { p0, p1, p2, p3 } => Some(LinkGeom::Spline { pts: vec![p0, p1, p2, p3], control: true, degree: 3, periodic: false }), + Seg2::Cubic { p0, p1, p2, p3 } => { + Some(LinkGeom::Spline { pts: vec![p0, p1, p2, p3], control: true, degree: 3, periodic: false, nurbs: None }) + } Seg2::Arc { .. } | Seg2::Bezier { .. } => None, } } diff --git a/crates/sketch/src/text_style_tests.rs b/crates/sketch/src/text_style_tests.rs index b44c7ee58..6a44786c0 100644 --- a/crates/sketch/src/text_style_tests.rs +++ b/crates/sketch/src/text_style_tests.rs @@ -1,7 +1,7 @@ //! Text styles: alignment, letter and line spacing, a made-up italic, a bold the font lacks, and //! text that follows a curve of its sketch; and text measured (`TextMetrics`) by the rule that draws it. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use super::*; use crate::{CurveKind, Sketch, font_data}; diff --git a/crates/sketch/src/thin.rs b/crates/sketch/src/thin.rs index 1d9fb5124..304966cc2 100644 --- a/crates/sketch/src/thin.rs +++ b/crates/sketch/src/thin.rs @@ -12,9 +12,10 @@ //! merged into regions. Walls that cross or meet (a honeycomb, a ring and a cross) come out as //! one region where they touch. +use solidcraft_geom::prelude::*; use std::f64::consts::{PI, TAU}; -use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; +use solidcore_record::{Loop2, Region2, Seg2, Vec2}; use crate::model::{CurveKind, Result, Sketch, SketchError}; use crate::profiles::{find_profiles, merge_regions}; @@ -378,7 +379,7 @@ fn outline_sketch(boundary: &[Seg2]) -> Result { } Seg2::Cubic { p0, p1, p2, p3 } => { let pts = [p0, p1, p2, p3].iter().map(|p| sk.add_point(*p, None)).collect::>>()?; - sk.add_curve(CurveKind::Spline { pts, control: true, degree: 3, periodic: false }, None)?; + sk.add_curve(CurveKind::Spline { pts, control: true, degree: 3, periodic: false, nurbs: None }, None)?; } _ => return Err(bad("not supported yet: this kind of wall curve")), } diff --git a/crates/sketch/src/thin_tests.rs b/crates/sketch/src/thin_tests.rs index 236a6254a..5391ee154 100644 --- a/crates/sketch/src/thin_tests.rs +++ b/crates/sketch/src/thin_tests.rs @@ -1,9 +1,10 @@ //! Thin walls against areas worked out by hand: a wall along a chain covers its length times //! the thickness, less what corners overlap and plus what mitres add. +use solidcraft_geom::prelude::*; use std::f64::consts::PI; -use solidcraft_geom::{Seg2, Vec2}; +use solidcore_record::{Seg2, Vec2}; use crate::thin_wall_regions; @@ -61,7 +62,7 @@ fn a_straight_wall_takes_its_side_from_the_drawn_direction() { #[test] fn a_circle_makes_an_exact_ring() { - let circle = solidcraft_geom::Loop2::circle(Vec2::new(3.0, 4.0), 10.0).segs; + let circle = solidcore_record::Loop2::circle(Vec2::new(3.0, 4.0), 10.0).segs; let regions = thin_wall_regions(std::slice::from_ref(&circle), 1.0, 1.0).unwrap(); assert_eq!(regions.len(), 1); assert_eq!(regions[0].holes.len(), 1); @@ -84,7 +85,7 @@ fn walls_that_cross_or_meet_are_one_region() { close(regions[0].area(), 4.0 * 10.0 * 2.0 - 4.0); } // A ring with a bar across it. - let mut ring = vec![solidcraft_geom::Loop2::circle(Vec2::ZERO, 10.0).segs]; + let mut ring = vec![solidcore_record::Loop2::circle(Vec2::ZERO, 10.0).segs]; ring.push(line([-10.0, 0.0], [10.0, 0.0])); let regions = thin_wall_regions(&ring, 1.0, 1.0).unwrap(); assert_eq!(regions.len(), 1); diff --git a/crates/sketch/src/virtual_corner_tests.rs b/crates/sketch/src/virtual_corner_tests.rs index 2103875c0..f1439ad45 100644 --- a/crates/sketch/src/virtual_corner_tests.rs +++ b/crates/sketch/src/virtual_corner_tests.rs @@ -1,7 +1,7 @@ #![allow(clippy::unwrap_used, clippy::panic)] use crate::{Constraint, ConstraintKind, CurveKind, Sketch}; -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; fn point(sk: &mut Sketch, x: f64, y: f64) -> usize { sk.add_point(Vec2::new(x, y), None).unwrap() @@ -51,7 +51,7 @@ fn curve_centres_and_spline_interior_points_are_used_and_invalid_incidence_is_sa let last = point(&mut sk, 21., 21.); let mut spline = sk.curves[a].clone(); spline.id = "interior_spline".into(); - spline.kind = CurveKind::Spline { pts: vec![first, interior, last], control: false, degree: 3, periodic: false }; + spline.kind = CurveKind::Spline { pts: vec![first, interior, last], control: false, degree: 3, periodic: false, nurbs: None }; sk.curves.push(spline); for p in [centre, interior] { for c in [a, b] { @@ -91,7 +91,7 @@ fn oversized_reference_input_is_refused_without_scanning_or_mutating_it() { let mut sk = Sketch::new(); let a = sk.add_line(Vec2::new(0., 1.), Vec2::new(2., 1.), None, None, None).unwrap(); let before = sk.points.clone(); - sk.curves[a].kind = CurveKind::Spline { pts: vec![usize::MAX; 1_000_001], control: false, degree: 3, periodic: false }; + sk.curves[a].kind = CurveKind::Spline { pts: vec![usize::MAX; 1_000_001], control: false, degree: 3, periodic: false, nurbs: None }; assert!(sk.virtual_corners().is_empty()); assert_eq!(sk.points, before); assert_eq!(sk.curves[a].kind.point_ids().len(), 1_000_001); diff --git a/crates/sketch/src/wire.rs b/crates/sketch/src/wire.rs index 462bc59ee..c5248b740 100644 --- a/crates/sketch/src/wire.rs +++ b/crates/sketch/src/wire.rs @@ -3,7 +3,8 @@ //! They are reference geometry: drawn and usable as paths, not part of profiles or the solver. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; use crate::link::{Link, LinkGeom, LinkKind, LinkSource}; use crate::model::{Result, Sketch, SketchError, in_range3, radius_in_range}; @@ -62,53 +63,80 @@ pub struct Wire { /// are its three defining points (start, through, end) and whose `pts` are its samples. #[serde(default, skip_serializing_if = "Option::is_none")] pub arc: Option, + /// A linked curve's exact geometry where its source has one (an included edge or sketch + /// curve, an intersection curve): record curves end to end along `pts`, in `space` + /// coordinates. Empty for a curve known only as its points (projected onto a face, iso + /// curves). Set when the link is resolved, with `pts`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub exact: Vec, +} + +/// One exact piece of a 3D sketch curve ([`Wire::exact`]): a record curve on its interval. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct WireCurve { + pub curve: solidcore_record::brep::Curve, + pub interval: [f64; 2], +} + +impl WireCurve { + /// The piece carried by the rigid motion `point` of points and `vector` of directions (a + /// placement). `None` for an intersection curve, whose surfaces are not carried here. + pub fn mapped(&self, point: &impl Fn(Vec3) -> Vec3, vector: &impl Fn(Vec3) -> Vec3) -> Option { + use solidcore_record::brep::{Curve, Frame}; + let a = |q: [f64; 3]| Vec3::new(q[0], q[1], q[2]); + let b = |v: Vec3| [v.x, v.y, v.z]; + let p = |q: [f64; 3]| b(point(a(q))); + let frame = |f: &Frame| Frame { origin: p(f.origin), x_axis: b(vector(a(f.x_axis))), y_axis: b(vector(a(f.y_axis))) }; + let curve = match &self.curve { + Curve::Line { start, end } => Curve::Line { start: p(*start), end: p(*end) }, + Curve::Circle { frame: f, radius } => Curve::Circle { frame: frame(f), radius: *radius }, + Curve::Ellipse { frame: f, radii } => Curve::Ellipse { frame: frame(f), radii: *radii }, + Curve::Polyline { points } => Curve::Polyline { points: points.iter().map(|q| p(*q)).collect() }, + Curve::Spline { knots, points } => Curve::Spline { knots: knots.clone(), points: points.iter().map(|q| p(*q)).collect() }, + Curve::RationalSpline { knots, homogeneous } => Curve::RationalSpline { + knots: knots.clone(), + homogeneous: homogeneous + .iter() + .map(|h| { + let q = point(a([h[0], h[1], h[2]]) * (1.0 / h[3])); + [q.x * h[3], q.y * h[3], q.z * h[3], h[3]] + }) + .collect(), + }, + Curve::SurfaceIntersection { .. } => return None, + }; + Some(WireCurve { curve, interval: self.interval }) + } +} + +impl Wire { + /// The wire carried by the rigid motion `point` of points and `vector` of directions: its + /// points, fit points and exact curves (dropped where one cannot be carried, leaving the + /// points). + pub fn map(&mut self, point: impl Fn(Vec3) -> Vec3, vector: impl Fn(Vec3) -> Vec3) { + for q in self.pts.iter_mut().chain(&mut self.fit) { + *q = point(*q); + } + if let Some(arc) = &mut self.arc { + let normal = vector(arc.normal); + arc.center = point(arc.center); + arc.start = point(arc.start); + arc.end = point(arc.end); + arc.normal = normal.normalized().unwrap_or(arc.normal); + arc.radius = arc.center.dist(arc.start); + } + self.exact = self.exact.iter().map(|c| c.mapped(&point, &vector)).collect::>().unwrap_or_default(); + } } /// Most fit points of a drawn 3D curve. pub const MAX_FIT_POINTS: usize = 500; -/// Samples per span of a drawn 3D spline. -const SPAN_SAMPLES: usize = 24; - -/// The polyline of a drawn 3D curve through `fit`: the point itself, the line, or a centripetal -/// Catmull–Rom spline through the points (smooth, no overshoot loops). +/// The polyline of a drawn 3D curve through `fit`: the point itself, the line, or the centripetal +/// Catmull–Rom spline through the points (smooth, no overshoot loops), sampled +/// ([`solidcraft_geom::catmull_rom`] has the curve itself, exactly). pub fn fit_polyline(fit: &[Vec3]) -> Vec { - if fit.len() <= 2 { - return fit.to_vec(); - } - let n = fit.len(); - // A curve that ends where it starts is smooth through that point (its neighbours wrap). - let closed = n > 3 && fit[0].dist(fit[n - 1]) < 1e-9; - let at = |i: isize| -> Vec3 { - match usize::try_from(i) { - Ok(i) if i < n => fit[i], - Ok(_) if closed => fit[1], - Err(_) if closed => fit[n - 2], - // Mirrored end tangents. - Ok(_) => fit[n - 1] * 2.0 - fit[n - 2], - Err(_) => fit[0] * 2.0 - fit[1], - } - }; - let mut out = vec![fit[0]]; - for k in 0..n - 1 { - let k = k as isize; - let (p0, p1, p2, p3) = (at(k - 1), at(k), at(k + 1), at(k + 2)); - let tj = |a: Vec3, b: Vec3| a.dist(b).sqrt().max(1e-9); - let t0 = 0.0; - let t1 = t0 + tj(p0, p1); - let t2 = t1 + tj(p1, p2); - let t3 = t2 + tj(p2, p3); - for s in 1..=SPAN_SAMPLES { - let t = t1 + (t2 - t1) * s as f64 / SPAN_SAMPLES as f64; - let a1 = p0 * ((t1 - t) / (t1 - t0)) + p1 * ((t - t0) / (t1 - t0)); - let a2 = p1 * ((t2 - t) / (t2 - t1)) + p2 * ((t - t1) / (t2 - t1)); - let a3 = p2 * ((t3 - t) / (t3 - t2)) + p3 * ((t - t2) / (t3 - t2)); - let b1 = a1 * ((t2 - t) / (t2 - t0)) + a2 * ((t - t0) / (t2 - t0)); - let b2 = a2 * ((t3 - t) / (t3 - t1)) + a3 * ((t - t1) / (t3 - t1)); - out.push(b1 * ((t2 - t) / (t2 - t1)) + b2 * ((t - t1) / (t2 - t1))); - } - } - out + solidcraft_geom::catmull_rom::samples(fit) } /// Chord-height tolerance (mm) when sampling a drawn 3D arc into `pts`. @@ -314,7 +342,30 @@ impl Sketch { Some(o) => o.clone(), None => self.fresh("w")?, }; - self.wires.push(Wire { id: wid, pts, space: WireSpace::Component, link: Some(id.to_string()), fit: Vec::new(), arc: None }); + self.wires.push(Wire { + id: wid, + pts, + space: WireSpace::Component, + link: Some(id.to_string()), + fit: Vec::new(), + arc: None, + exact: Vec::new(), + }); + } + Ok(()) + } + + /// Give a link's wires their exact curves ([`Wire::exact`]), one list per wire in the order + /// [`Self::set_link_wires`] took them (an empty list: known only as points). + pub fn set_link_wire_curves(&mut self, id: &str, exact: &[Vec]) -> Result<()> { + let wires = self.link_wires(id); + if wires.len() != exact.len() { + return Err(SketchError::Invalid(format!("link {id} has {} 3D curves, not {}", wires.len(), exact.len()))); + } + for (i, curves) in wires.into_iter().zip(exact) { + if let Some(w) = self.wires.get_mut(i) { + w.exact = curves.clone(); + } } Ok(()) } @@ -329,7 +380,7 @@ impl Sketch { let pts = drawn_polyline(fit)?; self.wire_budget(None, 1, pts.len() + fit.len())?; let id = self.fresh(if fit.len() == 1 { "q" } else { "w" })?; - self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec(), arc: None }); + self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec(), arc: None, exact: Vec::new() }); Ok(id) } @@ -349,7 +400,7 @@ impl Sketch { let pts = arc_polyline(&arc, ARC_TOL); self.wire_budget(None, 1, pts.len() + fit.len())?; let id = self.fresh("w")?; - self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec(), arc: Some(arc) }); + self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec(), arc: Some(arc), exact: Vec::new() }); Ok(id) } @@ -469,7 +520,12 @@ mod tests { let n = pts.len(); let (start, end) = (dir(pts[0], pts[1]), dir(pts[n - 2], pts[n - 1])); let mid = |i: usize| dir(pts[i - 1], pts[i]).dot(dir(pts[i], pts[i + 1])); - assert!(start.dot(end) >= mid(SPAN_SAMPLES) - 1e-9, "turn at the close {}, at a fit point {}", start.dot(end), mid(SPAN_SAMPLES)); + assert!( + start.dot(end) >= mid(solidcraft_geom::catmull_rom::SPAN_SAMPLES) - 1e-9, + "turn at the close {}, at a fit point {}", + start.dot(end), + mid(solidcraft_geom::catmull_rom::SPAN_SAMPLES) + ); let open = fit_polyline(&ring[..12]); assert_eq!(open.first(), ring.first()); assert_eq!(open.last(), ring.get(11)); diff --git a/crates/sketch/tests/analysis_levels.rs b/crates/sketch/tests/analysis_levels.rs index a65f76f2b..43dc1d385 100644 --- a/crates/sketch/tests/analysis_levels.rs +++ b/crates/sketch/tests/analysis_levels.rs @@ -1,6 +1,6 @@ //! Reduced diagnostics must preserve placement, rollback, feasibility and exact freedom results. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; use solidcraft_sketch::{Analysis, ConstraintKind, Hold, Sketch, solve_with}; fn compare(sketch: &Sketch, hold: &Hold) { diff --git a/crates/sketch/tests/cursor_target.rs b/crates/sketch/tests/cursor_target.rs index 1e15ee33a..2eb645ced 100644 --- a/crates/sketch/tests/cursor_target.rs +++ b/crates/sketch/tests/cursor_target.rs @@ -1,5 +1,6 @@ //! Analytic cursor oracle plus feasibility checks on every accepted continuation step. -use solidcraft_geom::Vec2; +use solidcore_record::Vec2; +use solidcraft_geom::prelude::*; use solidcraft_sketch::{ConstraintKind, Sketch, move_line_towards, move_point_towards, solve}; fn linkage() -> (Sketch, usize, usize) { diff --git a/crates/smlib/Cargo.toml b/crates/smlib/Cargo.toml new file mode 100644 index 000000000..9780c386e --- /dev/null +++ b/crates/smlib/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "solidcraft-smlib" +description = "SolidCraft: the B-rep kernel, solidcore (tangency-labs/solidcore, the Rust port of NVIDIA's SMLib, Apache-2.0), behind a safe wrapper" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +solidcore-record = { workspace = true } +log = { workspace = true } +serde_json = { workspace = true } +solidcraft-geom = { workspace = true } +solidcraft-profile = { workspace = true } +solidcore = { workspace = true } + +[dev-dependencies] +solidcraft-profile = { workspace = true, features = ["enabled"] } +flate2 = "1.1" diff --git a/crates/smlib/src/check.rs b/crates/smlib/src/check.rs new file mode 100644 index 000000000..21db7d05e --- /dev/null +++ b/crates/smlib/src/check.rs @@ -0,0 +1,105 @@ +//! SMLib's own validity check: `SmBrep::ValidatePointers`, then `AssertValid` over the whole +//! topology graph. Tests run it on every SMLib result and every import. + +use crate::{Brep, Result, core}; + +/// How many of SMLib's tests to run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CheckLevel { + /// The fewest: topology and pointers, no geometry. + Basic = 0, + /// Adds the geometry checks (gaps between vertices, edges and faces against tolerances). + Geometry = 1, + /// Every test, the slow ones too. + All = 2, +} + +/// What SMLib's check found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CheckReport { + /// Failed tests; 0 means SMLib finds the body valid. + pub failures: usize, + /// One line per failed test, such as + /// `SmBrep::Test #82 Tolerance: Vertex tolerance relative to brep tolerance (offset=2, tolerance=0.01) [owner SmVertex]`. + pub text: String, +} + +impl CheckReport { + pub fn is_valid(&self) -> bool { + self.failures == 0 + } + + /// The number of each failed test, line by line (`SmBrep::Test #82 …` is 82); a line without + /// one is left out. + pub fn failed_tests(&self) -> Vec { + self.text + .lines() + .filter_map(|l| { + let rest = l.split_once("Test #")?.1; + let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); + digits.parse().ok() + }) + .collect() + } +} + +impl std::fmt::Display for CheckReport { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.is_valid() { f.write_str("valid") } else { write!(f, "{} failed tests:\n{}", self.failures, self.text) } + } +} + +impl Brep { + /// Runs SMLib's validity check at `level`. A body that fails it is still `Ok`, with the + /// failures in the report; `Err` means the check could not run. + pub fn check(&self, level: CheckLevel) -> Result { + core::check(self.core(), level) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_box_is_valid_at_every_level() { + let b = Brep::make_box([1.0, 2.0, 3.0], [10.0, 20.0, 30.0]).unwrap(); + for level in [CheckLevel::Basic, CheckLevel::Geometry, CheckLevel::All] { + let r = b.check(level).unwrap(); + assert!(r.is_valid(), "{level:?}: {r}"); + assert_eq!(r.text, ""); + } + } + + #[test] + fn every_primitive_is_valid_at_every_level() { + let o = [1.0, 2.0, 3.0]; + let bodies = [ + ("cylinder", Brep::make_cylinder(o, 15.0, 50.0).unwrap()), + ("sphere", Brep::make_sphere(o, 12.0).unwrap()), + ("frustum", Brep::make_cone(o, 10.0, 4.0, 20.0).unwrap()), + ("cone", Brep::make_cone(o, 10.0, 0.0, 20.0).unwrap()), + ("torus", Brep::make_torus(o, 22.0, 4.0).unwrap()), + ]; + for (name, b) in &bodies { + for level in [CheckLevel::Basic, CheckLevel::Geometry, CheckLevel::All] { + let r = b.check(level).unwrap(); + assert!(r.is_valid(), "{name}, {level:?}: {r}"); + } + } + } + + #[test] + fn a_copy_and_a_native_file_round_trip_stay_valid() { + let b = Brep::make_box([0.0; 3], [2.0, 3.0, 4.0]).unwrap(); + assert!(b.try_clone().unwrap().check(CheckLevel::All).unwrap().is_valid()); + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-check-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("box.smb"); + b.write(&path, false).unwrap(); + let back = Brep::read(&path, false).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + let r = back.check(CheckLevel::All).unwrap(); + assert!(r.is_valid(), "{r}"); + } +} diff --git a/crates/smlib/src/core.rs b/crates/smlib/src/core.rs new file mode 100644 index 000000000..1644b68a0 --- /dev/null +++ b/crates/smlib/src/core.rs @@ -0,0 +1,657 @@ +//! The solidcore backend: one kernel for the process (SMLib's context is process-global too, and +//! some of its state, such as the fillet solver's latched step, lives for the whole process), +//! every call under its lock and a panic guard. +//! +//! Upstream fixes ([`fixes`]) are solidcore's opt-in corrections of SMLib defects that the C++ +//! fork fixed in its own sources; each one turned on here says which fork commit it matches. + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, PoisonError}; + +use solidcore::geom::attribute::{AttributeStore, ObjectKey}; +use solidcore::geom::vector3d::Vec3; +use solidcore::kernel::{Kernel, KernelOptions, UpstreamFixes}; +use solidcore::mass::integrator::properties::{PropertyAttributes, brep_volume}; +use solidcore::primitive::api_primitives as primitives; + +use crate::{Error, Result}; + +pub(crate) mod blend; +#[cfg(test)] +mod blend_tests; +pub(crate) mod boolean; +#[cfg(test)] +mod boolean_tests; +mod convert; +#[cfg(test)] +mod convert_tests; +pub(crate) mod dump; +pub(crate) mod file; +pub(crate) mod history; +mod measure; +#[cfg(test)] +mod measure_tests; +pub(crate) mod merge; +#[cfg(test)] +mod merge_tests; +pub(crate) mod offset; +#[cfg(test)] +mod offset_tests; +pub(crate) mod picked; +pub(crate) mod split; +#[cfg(test)] +mod split_tests; +pub(crate) mod ssi; +pub(crate) mod sweep; +#[cfg(test)] +mod sweep_tests; +pub(crate) mod transform; +#[cfg(test)] +mod transform_tests; +pub(crate) mod trim; +#[cfg(test)] +mod trim_tests; + +pub(crate) use convert::{from_arrays, to_arrays}; +pub(crate) use measure::{area, bounds, check, classify_point, edge_face_distance, is_manifold_solid, mass_properties, solid_count}; + +/// A solidcore body. Its own lock: solidcore's operations take `&mut Brep`, even to measure. +pub(crate) struct Body(pub(crate) Mutex); + +impl Body { + pub(crate) fn new(b: solidcore::topology::Brep) -> Body { + Body(Mutex::new(b)) + } +} + +/// The fixes this backend runs with: every one of solidcore's opt-in fixes of upstream SMLib +/// defects (`UpstreamFixes`, each naming its record and issue), whether or not the C++ fork has it, +/// unless it appears broken. A test checks none is left off but those in `HELD_BACK`, so moving the +/// solidcore pin to a rev with a new flag fails until it is added here. +pub(crate) fn fixes() -> UpstreamFixes { + let mut f = UpstreamFixes::default(); + f.fillet_retry_radius_as_first = true; + f.fillet_rail_rim_on_face = true; + f.fillet_refuse_rails_leaving_faces = true; + f.fillet_refuse_face_consuming_blends = true; + f.fillet_refuse_non_manifold_result = true; + f.fillet_vertex_error_diagnostics = true; + f.fillet_corner_ball_patch = true; + f.fillet_chamfer_cone_on_arc = true; + f.fillet_torus_center_on_axis = true; + f.offset_excess_faces_after_merge = true; + f.offset_clip_right_side_out = true; + f.revolution_offset_axis_both_sides = true; + f.offset_extended_edges_mated = true; + f.remove_slit_loops_where_solids_touch = true; + f.keep_operand_uv_trims = true; + f.proto_vertex_miss_is_false = true; + f.check_loop_vertex_tolerance = true; + f.check_loop_projected_seam_ends = true; + f.trim_boundary_seam_wrap = true; + f.bspline_check_min_radius = true; + f.oscillating_skips_failed_guesses = true; + f.refine_cc_range_ends = true; + f.flat_corners_test_bits = true; + f.cylinder_rebuild_mean_radius = true; + f.planar_path_uncapped_open_profiles = true; + f.revolve_analytic_profile_faces = true; + f.revolve_arc_centre_near_axis_is_sphere = true; + f.taper_pivot_nearest_corner = true; + f.taper_tangent_corner_planes = true; + f.revolve_nested_shells_as_cavities = true; + f.revolve_holed_profile_void = true; + f.curve_sweep_caps_at_sweep_ends = true; + f.join_touching_loops = true; + f.uv_trim_reversal_on_surface = true; + f.offset_resolve_crossing_loops = true; + f.offset_walls_touch_refused = true; + f.offset_analytic_mate_edges = true; + f.precise_properties_split_at_surface_knots = true; + f.nurb_cylinder_inside_out_frame = true; + f.shell_inner_shell_of_statuses = true; + f.local_operation_offset_status = true; + f.local_operation_refuses_loose_tangent_edges = true; + f.torus_major_radius_from_origin = true; + f.fillet_corner_sphere_from_four_arcs = true; + f.fillet_nx1_opposite_continuation_side_edge = true; + f.fillet_trace_rejects_short_step = true; + f.torus_iso_circle_axis_from_midpoint = true; + f.torus_keeps_inside_out = true; + f.internal_pole_row_through_knot = true; + f.extrusion_origin_scaled_zero = true; + f.transform_scales_each_tolerance = true; + f.transform_model_size_from_body_box = true; + f.offset_collapsed_rounds_mated = true; + f.offset_missing_surface_fails = true; + f.fillet_nx1_end_rib_global_merge = true; + f.uv_trim_corner_end_points_only = true; + f.bspline_trim_preserves_uv_spans = true; + f.cone_parallel_line_midpoint = true; + f.cone_parallel_line_domains = true; + f.proto_edge_self_loop_on_vertex_degenerate = true; + f.slice_coincident_faces_sheet_side = true; + f.boolean_outer_shell_first = true; + f.edge_reversal_keeps_failed_edge = true; + f.topology_failed_evaluations_propagate = true; + f.heal_stage3_failures_propagate = true; + f.sweep_frame_on_planar_path_normal = true; + f.cover_refuses_folded_continuation = true; + f.boolean_vertex_by_best_crossing = true; + f.boolean_cleanup_removes_slits = true; + f.classify_edge_interval = true; + f.ellipse_trim_seam_lines_span_cone_height = true; + f.degenerate_proto_edge_in_one_vertex = true; + f.new_edge_vertex_tolerance_covers_gap = true; + f.torus_signed_gen_curve_interval = true; + f.sheet_sweep_joins_profile_wires = true; + f.point_solve_keeps_triangle_guess = true; + f.fillet_setback_from_start_vertex = true; + f.imprint_trims_edge_to_proto_vertex = true; + f.imprint_extends_edge_to_proto_vertex = true; + f.fillet_point_step_per_point = true; + f.analytic_copy_keeps_parameterization = true; + f.fillet_point_bigger_step_retry = true; + f.fillet_through_extended_rail_end = true; + f.precise_properties_body_length_scale = true; + f.offset_extension_from_base = true; + f.corner_blend_stays_inside_neighbours = true; + f.fillet_cleanup_keeps_target_faces = true; + f.fillet_nx1_tangent_side_edge = true; + f.fillet_3x2_mixed_concave_side_edge = true; + f.offset_closed_curve_trim_arc = true; + f.offset_stitch_at_body_tolerance = true; + f.curve_contacts_at_curve_ends = true; + f.shell_empty_cavity_fails = true; + f.fillet_refuse_ball_not_fitting = true; + f.boolean_lists_virtual_surface_copies = true; + f.sphere_small_circle_not_touching = true; + f.ssi_tangent_contact_points = true; + f.ssi_trace_tangent_curves_once = true; + f.ssi_singular_start_inside_direction = true; + f.found_torus_sphere_keep_tested_nurb = true; + f.boolean_skips_faces_apart = true; + f.uv_trim_checks_on_surface = true; + f.loop_orientation_floor_from_loop_box = true; + f.offset_extends_cones_as_themselves = true; + f.local_operation_box_holds_new_surfaces = true; + f.uv_trim_joins_drop_pieces = true; + f.shell_edges_on_analytics_exact = true; + f.ssi_no_reverse_of_empty_trace = true; + f.ssi_pole_point_keeps_its_tangent = true; + f.iso_curve_sliver_domain_is_degenerate = true; + f.corner_blend_coons_patch_tangent_to_sides = true; + f.fillet_patch_keeps_fillet_edges = true; + f.fillet_corner_ball_center_from_axes = true; + f.seam_point_solutions_are_one = true; + f.boolean2d_plane_covers_far_faces = true; + f.brep_area_between_solid_and_void = true; + f.boolean_splits_definition_across_split = true; + f.curve_tight_box_interval_knots = true; + f.fillet_refuse_overlapping_bands = true; + f.ssi_tangent_curve_tracer = true; + f.torus_check_reads_v_interval = true; + f.torus_check_spindle_apex = true; + f.local_operation_step_walls = true; + f.edge_check_orders_tangent_faces = true; + f.revolve_arc_touching_axis_is_horn_torus = true; + f.thicken_planar_side_walls = true; + f.fillet_torus_span_from_start_section = true; + f.fillet_knife_edge_rounds = true; + f.taper_wall_closes_at_apex = true; + f.revolution_round_offset_collapses = true; + f.fillet_chamfer_cone_stored_as_cone = true; + f.offset_point_vertex_caps = true; + f.approximate_surface_bezier_starter = true; + f.proto_edge_splits_at_captured_vertices = true; + f.stitch_solid_nests_cavities = true; + f.local_operation_closes_walls_to_nothing = true; + f.linear_sweep_arc_to_cylinder_zero = true; + f.imprint_reuses_coincident_face_edge = true; + f.boolean_new_face_closure_both_sides = true; + f.linear_sweep_arc_is_cylinder = true; + f.offset_closes_loop_gaps = true; + f.cylinder_plane_tangent_within_tolerance = true; + f.boolean_wire_edge_keeps_faceuse_shell = true; + f.fillet_nx1_tangent_corner_edge = true; + f.fillet_torus_rail_on_axis = true; + f.loops_go_on_round_the_vertex = true; + f.revolve_splits_curves_on_axis = true; + f.cover_wraps_across_closed_seam = true; + f.imprint_extension_keeps_analytic_curve = true; + f.fillet_trace_from_tangent_point_toward_next = true; + f.fillet_tangent_point_one_sided_step = true; + f.fillet_rails_meet_at_one_end_point = true; + f.fillet_trace_reaches_rails = true; + f.delete_vertex_joins_seam_iso_curve = true; + f.box_face_failures_propagate = true; + f.ellipse_adjust_step_interval_keeps_turns = true; + f.fillet_cleanup_removes_input_slits = true; + f.fillet_rail_end_on_continued_surface = true; + f.glue_vertices_joins_every_region = true; + f.fillet_nx1_tangent_side_edge_same_convexity = true; + f.fillet_removal_takes_ring_fillets = true; + // The fork's commits that reached `SMLIB_REV` at eaa998a (tangency-labs/smlib#68, #69, #70). + f.fillet_trim_inside_by_best_dot = true; + f.fillet_half_degree_crease = true; + f.fillet_split_edge_keeps_near_half = true; + f.curve_loop_normal_from_area = true; + // The fork's commits in `SMLIB_REV` 2fc375f, ported to solidcore since. + f.fillet_cliff_overflow = true; + f.fillet_3x2_tangent_side_edge_roles = true; + f.offset_extension_as_itself = true; + f.fillet_mitre_concave_face_corners = true; + f.fillet_mitre_gap_patch = true; + f.fillet_run_on_past_far_end_only = true; + f.good_drop_result_distances_in_order = true; + f.face_tight_box_searches_trim = true; + f.ssi_low_angle_start_on_probation = true; + f.fillet_variable_span_follows_fillet = true; + f.simple_coincidence_crossing_is_point = true; + f.boolean_temporary_transform_statuses = true; + f.primitive_path_curve_statuses = true; + f.planar_path_sweep_statuses = true; + f.planar_path_profile_placement_statuses = true; + f.fillet_trim_status = true; + f.perspective_sphere_offsets = true; + f.plane_recognition_origin_after_axes = true; + f.fillet_corner_face_curve_halves = true; + f.brep_edit_statuses_pass_on = true; + f.fillet_run_on_bspline_trims = true; + f.offset_tangent_gap_statuses = true; + f.ssi_alignment_statuses = true; + f.fillet_corner_statuses = true; + f.fillet_edge_curve_domain_statuses = true; + f.query_statuses_pass_on = true; + f.sweep_statuses_pass_on = true; + f.ssi_proto_topology_statuses_pass_on = true; + f.analytic_inversion_answers_apart = true; + f.fillet_statuses_pass_on = true; + f.fillet_corner_per_vertex_fan = true; + f.fillet_rail_trim_at_near_knot = true; + f.offset_splits_corner_vertices = true; + f.offset_keep_cavity_regions = true; + f.offset_four_face_vertex_split = true; + f.gap_samples_non_bspline_v_stride = true; + f.gap_array_append_updates_longest = true; + f.imprint_skips_collapsed_definition = true; + f.precise_properties_trim_base_v = true; + f.fillet_blend_curve_revolved_on_arc = true; + f.temporary_radius_setup_errors = true; + f.ellipse_step_interval_checks = true; + f.corner_patch_face_side_twist = true; + f.boolean_union_refuses_solid_leak = true; + f.curve_loop_start_after_previous_end = true; + f.loop_use_reports_open_gaps = true; + f.face_points_span_domain = true; + f.drop_curve_v_domain_degeneracy = true; + f.mirror_curve_keeps_euclidean_control_points = true; + f.fillet_corner_variable_radius_rail_on_opposite_fillet = true; + f.sphere_from_arcs_common_centre = true; + f.dupin_bottom_hyperbola_axis = true; + f.extent3d_contains_both_segment_endpoints = true; + f.translation_sweep_regularize = true; + f.gap_samples_use_trimmed_spans = true; + f.twist_simple_duw_sign = true; + f.offset_swap_uv_extended_distance = true; + f.circumscribe_axis_map_by_basis = true; + f.planar_path_profile_in_path_frame = true; + f.validation_does_not_make_uv_trims = true; + f.iso_curve_uv_line_both_params = true; + f.extrusion_step_uses_clamped_uv = true; + f.analytic_corner_failure_is_false = true; + f.defeature_refuses_open_base = true; + f.ssi_start_loop_trace_budget = true; + f.fillet_refuse_crossing_rails = true; + f.proto_edge_split_upper_keeps_the_old_max = true; + f.point_on_start_point_squared_tolerance = true; + f.bspline_trim_keeps_rational_end_spans = true; + f.fillet_exact_round_classes = true; + f.curve_check_zero_speed_tangent_end = true; + f.cpoly_remove_poly_face_check_member = true; + f.check_seam_crossing_unclosed = true; + f.ascii_doubles_round_trip = true; + f.transform_aligned_bbox_image = true; + f.bspline_simple_offset_matches_parameterization = true; + f.offset_edges_keep_source_tolerance = true; + f.best_fit_line_largest_scatter_eigenvector = true; + f.circle_silhouette_perspective_center = true; + f.ellipse_convert_to_2d_uses_both_axes = true; + f.circle_offset_antiparallel_normal = true; + f.masked_array_uses_bit_shift = true; + f.global_solver_identical_prefers_larger_when_maximizing = true; + f.surface_continuity_checks_last_v_knot = true; + f.surface_point_solver_propagates_bbox_failure = true; + f.volume_lift_third_derivative_terms = true; + f.volume_discontinuity_checks_vw_unaligned = true; + f.periodic_extent_add_empty_interval = true; + f.stop_tracking_checks_own_callback = true; + f.plane_reparameterize_moves_origin = true; + f.crv_in_volume_mults_by_break_index = true; + f.curve_bounded_surface_read_uv_type_and_implicit_outer = true; + f.polar_box_region_to_arc_transposes_domain = true; + f.point_set_centroid_all_blocks = true; + f.local_solve1d_unbounded_newton_step = true; + f.composite_curve_bbox_segment_intervals = true; + f.knot_vector_valid_requires_span = true; + f.projected_curve_transform_when_owned = true; + f.curve_property_gs_branch_bounds = true; + f.volume_representational_end_continuities = true; + f.integrator_propagates_failure = true; + f.precise_properties_span_end_from_below = true; + f.offset_open_edge_second_trim_point = true; + f.close_loop_relates_only_coincident_edges = true; + f.ssi_split_curves_at_singular_points = true; + f.surface_parallel_to_vector_checks = true; + f.fillet_round_ends_at_tangent_continuation = true; + f.geometric_g2_continuity = true; + f.hash_table_grow_preserves_removed_records = true; + f.bend_volume_bbox_contains_wide_angle_and_inf_u = true; + f.bend_volume_trim_param_box_across_period = true; + f.point_set_tight_pbox_projects_points = true; + f.degen_param_tiebreak_uses_actual_param = true; + f.conic_evaluate_uses_computed_second_deriv = true; + f.cylinder_plane_section_trims_exact = true; + f.local_surface_intersect_guards_max_boundary_retry = true; + f.curve_max_distance_single_sample_midpoint = true; + f.curve_sweep_closed_path_joins_ends = true; + f.validate_tolerances_fixes_reported_gaps = true; + f.edgeuse_convexity_propagates_step_off_failure = true; + f.mark_lock_pair_advances_and_locks_second_context = true; + f.is_iso_curve_at_propagates_canonical_failure = true; + f.database_io_byte_swaps_read_boolean_and_u16 = true; + f.is_point_on_curve_propagates_eval_failure = true; + f.is_topological_vertex_rejects_cusps_and_tangent_errors = true; + f.cone_create_canonical_preserves_inside_out_and_checks_height = true; + f.point_class_gap_3d_propagates_no_drop_error = true; + f.fillet_surface_plane_curve_on_plane_equation = true; + f.fillet_gn_section_generator = true; + f.face_trim_curves_kept_where_exact = true; + f.swap_uv_keeps_analytic_definition = true; + f.face_shrink_bound_on_knot = true; + f.offset_updates_result_tolerances = true; + f.cone_iso_circle_at_axial_height = true; + f.boolean_coincident_strip_drops_crossing = true; + f.fillet_overflow_trim_at_creases = true; + f.fillet_section_end_trim_at_creases = true; + f.fillet_refuse_mixed_corner_crossing_rails = true; + f.fillet_keep_features = true; + f.fillet_blend_corner = true; + f.fillet_exact_arc_sections = true; + f.fillet_exact_arc_spans = true; + // Held back: see `HELD_BACK`. + f.fillet_refuse_rounds_breaking_through = false; + f.cone_unbounded_parameterized_as_nurb = true; + f.ellipse_open_arc_keeps_end_angle = true; + f.fillet_round_as_definition = true; + f.fillet_round_on_round_as_definition = true; + f.fillet_overflow_crease_along_edge = true; + f.plane_first_torus_section_exact = true; + f.keep_exact_pcurves = true; + f.shell_one_construction = true; + f +} + +/// The fixes held off, each with the case and the numbers that show it broken: a volume or topology +/// wrong against the analytic value, a check failure, a crash, sound geometry refused that builds +/// without the flag, or a large slowdown. Differing from the C++ kernel is no such evidence: a fix +/// the fork doesn't have stays on, and where solidcore builds what SMLib refuses, a result right +/// against its closed form is a win. +/// +/// `fillet_refuse_rounds_breaking_through` (WR-707, solidcore#2311): sound geometry refused. With it +/// on, 11 rig cases that pass with it off, each graded against its closed form or invariants, are +/// refused as breaking through the part (190-fillet-disc-rim-past-its-2mm-wall fails status 1001 +/// instead): every-hole-top-rim-r12-past-plate-bottom, 1080-chamfer-runs-into-openings-cut-by-them +/// (3350, its closed form), 1080-fillet-notched-block-top-outline-r8, +/// 324-fillet-over-hole-cut-by-overlong-cylinder, 324-fillet-over-hole-overlap, +/// 5158-fillet-adjacent-plate-edges-as-thick-as-plate and the sloped and equal-slope basin rims of +/// #1080 and #5835. A fix under the same flag is in progress on solidcore. +#[cfg(test)] +const HELD_BACK: &[&str] = &["fillet_refuse_rounds_breaking_through"]; + +/// How far apart two kernels' procedural blend serials start. A body keeps the serials of the +/// kernel that made it and may be used on any other, whose memo of solved stations is keyed by +/// serial alone: the ranges keep one definition's stations from answering for another's. +pub(crate) const BLEND_SERIALS_PER_KERNEL: u64 = 1 << 40; + +/// A new kernel. Each takes the next range of blend serials, the first starting at 0. +fn fresh() -> Kernel { + static MADE: AtomicU64 = AtomicU64::new(0); + let mut k = Kernel::new(&KernelOptions::default()); + k.fixes = fixes(); + k.blend_last_serial.set(MADE.fetch_add(1, Ordering::Relaxed).wrapping_mul(BLEND_SERIALS_PER_KERNEL)); + k +} + +/// Most kernels kept for later calls; those over it are dropped when their call ends. +const MOST_IDLE: usize = 8; + +/// The kernels no call is using, the last used on top. The lock is only held to take or put back +/// a kernel, never during a call: a call that runs long (or never returns) holds up nothing but +/// its own body, so one design's long operation never delays another's. Calls one after another +/// all get the same kernel, as a single kernel would serve them; one that starts while another +/// runs gets one of its own (solidcore keeps no global state, and a body's identities are valid +/// only in the kernel that issued them, so any kernel takes any body). +static IDLE: Mutex> = Mutex::new(Vec::new()); + +fn take_kernel() -> Kernel { + IDLE.lock().unwrap_or_else(PoisonError::into_inner).pop().unwrap_or_else(fresh) +} + +fn put_kernel(k: Kernel) { + let mut idle = IDLE.lock().unwrap_or_else(PoisonError::into_inner); + if idle.len() < MOST_IDLE { + idle.push(k); + } +} + +/// Runs `f` on a kernel of its own. A panic in solidcore is caught: the kernel, which it may have +/// left half-updated, is replaced by a fresh one and the call fails with [`Error::Internal`]. +pub(crate) fn run(call: &'static str, f: impl FnOnce(&mut Kernel) -> std::result::Result) -> Result { + run_on(call, &[], f) +} + +thread_local! { + /// How many solidcore calls this thread is inside: a panic now is caught ([`run_on`]). + static IN_CALL: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Is this thread inside a solidcore call, whose panic [`run_on`] catches? (Crash reports mark such +/// a panic recovered.) +pub(crate) fn in_call() -> bool { + IN_CALL.with(std::cell::Cell::get) > 0 +} + +/// [`run`] for a call that reads the bodies `inputs`: should it fail while a dump folder is set, +/// they are left there ([`dump::failed`]). +pub(crate) fn run_on( + call: &'static str, + inputs: dump::Inputs<'_>, + f: impl FnOnce(&mut Kernel) -> std::result::Result, +) -> Result { + let mut k = take_kernel(); + // A profiler span per call: where the kernel's time goes. + let _span = solidcraft_profile::span("solidcore", call); + let in_flight = dump::in_flight(call); + struct Depth; + impl Drop for Depth { + fn drop(&mut self) { + IN_CALL.with(|d| d.set(d.get().saturating_sub(1))); + } + } + IN_CALL.with(|d| d.set(d.get() + 1)); + let depth = Depth; + let caught = catch_unwind(AssertUnwindSafe(|| f(&mut k))); + drop(depth); + let r = match caught { + Ok(Ok(v)) => Ok(v), + Ok(Err(e)) => Err(Error::Solidcore(format!("{call}: {e}"))), + Err(p) => { + k = fresh(); + let why = p.downcast_ref::<&str>().map(|s| (*s).to_owned()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_default(); + log::warn!(target: "smlib", "solidcore panicked in {call}: {why}"); + Err(Error::Internal(format!("{call}: {why}"))) + } + }; + drop(in_flight); + let why = match &r { + Ok(v) => v.refusal(), + Err(e) => Some(e.to_string()), + }; + if let Some(why) = why { + // The kernel the call ran on, or the fresh one that replaced it after a panic. + dump::failed(&k, call, &why, inputs); + } + put_kernel(k); + r +} + +/// A call the capi checks for `SM_SUCCESS`, treating any other status as no answer: an error +/// that stands for an SMLib status exactly ([`SolidError::sm_status`](solidcore::SolidError::sm_status), +/// solidcore#1452) is `None`. Every other solidcore error +/// (unported code, invalid input to an adapter, a missing record...) is not a status the C++ +/// path returns, so it fails the call instead of hiding as a skipped entity. +pub(crate) fn answer(r: std::result::Result) -> std::result::Result, solidcore::SolidError> { + match r { + Ok(v) => Ok(Some(v)), + Err(e) if e.sm_status().is_some() => Ok(None), + Err(e) => Err(e), + } +} + +/// Runs `f` on a kernel and `body`, its lock held for the call. +pub(crate) fn with_body( + call: &'static str, + body: &Body, + f: impl FnOnce(&mut Kernel, &mut solidcore::topology::Brep) -> std::result::Result, +) -> Result { + // A body a panic interrupted may be half-edited: it is never used again. + if body.0.is_poisoned() { + return Err(Error::Internal(format!("{call}: the body was left unfinished by an earlier panic"))); + } + run_on(call, &[("brep", body)], |k| f(k, &mut body.0.lock().unwrap_or_else(PoisonError::into_inner))) +} + +/// An axis-aligned box from its lower corner (`SmApiCreateBox`, as `smlib_make_box` checks it: +/// every edge length positive). +pub(crate) fn make_box(origin: [f64; 3], size: [f64; 3]) -> Result { + if !origin.iter().chain(&size).all(|x| x.is_finite()) || !size.iter().all(|&s| s > 0.0) { + return Err(Error::Argument); + } + let [x, y, z] = size; + run("create_box", |k| primitives::create_box(k, Vec3::new(origin[0], origin[1], origin[2]), x, y, z)).map(Body::new) +} + +fn point(p: [f64; 3]) -> Result { + if !p.iter().all(|x| x.is_finite()) { + return Err(Error::Argument); + } + Ok(Vec3::new(p[0], p[1], p[2])) +} + +/// A cylinder about +Z from its base centre (`SmApiCreateCylinder`, as `smlib_make_cylinder` +/// checks it: radius and height positive). +pub(crate) fn make_cylinder(origin: [f64; 3], radius: f64, height: f64) -> Result { + let o = point(origin)?; + if !(radius > 0.0 && height > 0.0 && radius.is_finite() && height.is_finite()) { + return Err(Error::Argument); + } + run("create_cylinder", |k| primitives::create_cylinder(k, o, radius, height)).map(Body::new) +} + +/// A sphere (`SmApiCreateSphere`; radius positive). +pub(crate) fn make_sphere(center: [f64; 3], radius: f64) -> Result { + let o = point(center)?; + if !(radius > 0.0 && radius.is_finite()) { + return Err(Error::Argument); + } + run("create_sphere", |k| primitives::create_sphere(k, o, radius)).map(Body::new) +} + +/// A cone or frustum about +Z (`SmApiCreateCone`; `smlib_make_cone`'s checks: base radius and +/// height positive, top radius at least 0 and not the base radius). +pub(crate) fn make_cone(origin: [f64; 3], base_radius: f64, top_radius: f64, height: f64) -> Result { + let o = point(origin)?; + let ok = base_radius > 0.0 && top_radius >= 0.0 && height > 0.0 && top_radius != base_radius; + if !(ok && base_radius.is_finite() && top_radius.is_finite() && height.is_finite()) { + return Err(Error::Argument); + } + run("create_cone", |k| primitives::create_cone(k, o, base_radius, top_radius, height)).map(Body::new) +} + +/// A ring torus about +Z (`SmApiCreateTorus`; major radius > minor radius > 0). +pub(crate) fn make_torus(center: [f64; 3], major_radius: f64, minor_radius: f64) -> Result { + let o = point(center)?; + if !(minor_radius > 0.0 && minor_radius < major_radius && major_radius.is_finite()) { + return Err(Error::Argument); + } + run("create_torus", |k| primitives::create_torus(k, o, major_radius, minor_radius)).map(Body::new) +} + +/// The enclosed volume (`SmApiBrepComputeVolume`), its accuracy clamped as [`mass_properties`] +/// clamps it. +pub(crate) fn volume(body: &Body, relative_accuracy: f64) -> Result { + let relative_accuracy = measure::accuracy(relative_accuracy)?; + with_body("brep_volume", body, |k, b| { + let store = AttributeStore::default(); + let attrs = PropertyAttributes { store: &store, key_of: &|_| ObjectKey(0) }; + brep_volume(k, b, relative_accuracy, &attrs) + }) +} + +/// Face, edge and vertex counts. +pub(crate) fn counts(body: &Body) -> Result<[usize; 3]> { + with_body("counts", body, |_, b| Ok([b.face_list().len(), b.edge_list().len(), b.vertex_list().len()])) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_upstream_fix_is_on_unless_shown_broken() { + let f = fixes(); + let flags: Vec<(&str, bool)> = f.flags().collect(); + let off: Vec<&str> = flags.iter().filter(|(name, on)| !on && !HELD_BACK.contains(name)).map(|(name, _)| *name).collect(); + assert!(off.is_empty(), "UpstreamFixes flags are off: {off:?}"); + for name in HELD_BACK { + assert!(flags.contains(&(*name, false)), "{name} is on or gone: drop it from HELD_BACK"); + } + } + + #[test] + fn a_box_measures_exactly() { + let b = make_box([1.0, -2.0, 3.0], [10.0, 20.0, 30.0]).unwrap(); + assert_eq!(counts(&b).unwrap(), [6, 12, 8]); + let v = volume(&b, 1e-8).unwrap(); + assert!((v - 6000.0).abs() < 6000.0 * 1e-9, "{v}"); + } + + /// An accuracy finer than 1e-8 or not positive is 1e-8, as `mass_properties` takes it: a + /// sphere's volume at 0, -1 and 1e-15 is its volume at 1e-8, on its closed form. + #[test] + fn a_volume_accuracy_out_of_range_is_clamped() { + let ball = make_sphere([1.0, 2.0, 3.0], 5.0).unwrap(); + let at = volume(&ball, 1e-8).unwrap(); + assert!((at - 4.0 / 3.0 * std::f64::consts::PI * 125.0).abs() < 1e-6, "{at}"); + for acc in [0.0, -1.0, 1e-15] { + assert_eq!(volume(&ball, acc).ok(), Some(at), "accuracy {acc}"); + } + } + + #[test] + fn hostile_numbers_are_refused() { + assert!(make_box([f64::NAN, 0.0, 0.0], [1.0; 3]).is_err()); + assert!(make_box([0.0; 3], [1.0, -1.0, 1.0]).is_err()); + let b = make_box([0.0; 3], [1.0; 3]).unwrap(); + assert!(volume(&b, f64::INFINITY).is_err()); + } + + #[test] + fn a_panic_is_an_error_and_the_kernel_is_fresh_after() { + let r: Result<()> = run("test", |_| panic!("boom")); + assert!(matches!(r, Err(Error::Internal(ref m)) if m.contains("boom")), "{r:?}"); + assert!(make_box([0.0; 3], [1.0; 3]).is_ok()); + } +} diff --git a/crates/smlib/src/core/blend.rs b/crates/smlib/src/core/blend.rs new file mode 100644 index 000000000..930927751 --- /dev/null +++ b/crates/smlib/src/core/blend.rs @@ -0,0 +1,1452 @@ +//! Fillets and chamfers on solidcore: the C API's composition round SMLib's fillet executive, +//! ported from the fork's `capi/src/smlib_ops.cpp` (`blend_call`, `round_edges`, +//! `chamfer_offsets`, `chamfer_edges`, `chamfer_radius`, `outer_faceuse`, `face_frame`, +//! `sides_offsets`, `blend_failure`, `setbacks_fit`, `overflow_first`, `Picked`, +//! `size_ok`, `points_ok`, `tolerance_ok`, `law_ok`, `law_pinches`, `law_along`, `finish`, +//! `smlib_fillet`, `smlib_chamfer`, `smlib_blend`, `smlib_blend_dropping`, `smlib_blend_setback`, +//! `smlib_blend_setback_open`, `smlib_fillet_variable`, `smlib_chamfer_sides`) and +//! `capi/src/smlib_pick.h` (`pick`, `pick_edges`, `pick_vertices`). +//! +//! As there, every operation works on a copy of its body (`SmApiBrepCopy`), picks edges and +//! corners by point, and drives the executive step by step (`SetFilletParameters`, +//! `CreateFilletCorners`, the corners' bevels and setbacks, `DoFilleting`, `StitchAndOrient`). +//! +//! What the capi asks of fork-only SMLib code that solidcore does not have is +//! [`Error::Unsupported`], refused where the capi would first reach it, so every error before +//! it is the C++ path's: +//! - a variable radius whose law has a corner (`SplitFilletFacesAtRadiusCorners`, fork 6eecf04; solidcore#430, PR #1403). +//! +//! solidcore's own refusals of code it has not ported (`SolidError::Unported`) are +//! [`Error::Unsupported`] too. + +use std::collections::{HashMap, HashSet}; +use std::sync::PoisonError; + +use solidcore::EntityRef; +use solidcore::SolidError; +use solidcore::blend::blend_corner::BlendCornerEvent; +use solidcore::blend::fillet_corner::p3::MIXED_CORNER_RAILS_CROSS; +use solidcore::blend::fillet_executive::p1::{FilletLaw, FilletLawKind}; +use solidcore::blend::fillet_executive::p3::{ErrorInfo, FitKind, NoRoomReason}; +use solidcore::blend::fillet_executive::session::{FilletObject, FilletSession}; +use solidcore::blend::fillet_geom::p1::{FilletCornerType, FilletErrorType}; +use solidcore::blend::fillet_section::section::GN_THUMBWEIGHT_EQUAL_AREA; +use solidcore::blend::fillet_solver::p1::FilletSurfaceGeneratorType; +use solidcore::geom::attribute::{Attribute, AttributeHandlers, Behavior, ids as attribute_ids}; +use solidcore::geom::vector3d::{Point3, Vec3}; +use solidcore::kernel::Kernel; +use solidcore::mass::integrator::properties::edge_length; +use solidcore::nurbs::b_spline_curve::p1::{BSplineCurve, BSplineCurveForm, CanonicalData, KnotType}; +use solidcore::nurbs::b_spline_surface_n_lib::p2::OrientType; +use solidcore::query::api_queries::edge_closest_point; +use solidcore::query::brep::evaluate_surface_normal; +use solidcore::topology::brep::p1 as brep_p1; +use solidcore::topology::brep::p2 as brep_p2; +use solidcore::topology::brep::p2::ArenaNotifyState; +use solidcore::topology::brep::p3::{DeleteFaceOptions, delete_face}; +use solidcore::topology::brep::p5::{StitchAndOrientOptions, stitch_and_orient}; +use solidcore::topology::edgeuse::p1 as eu_p1; +use solidcore::topology::edgeuse::p3::{BinormalOptions, evaluate_binormal}; +use solidcore::topology::face::p2 as face_p2; +use solidcore::topology::face::p4 as face_p4; +use solidcore::topology::topology_traverser::Marks; +use solidcore::topology::{Brep, EdgeId, EdgeuseId, FaceId, FaceuseId, VertexId, edge, vertex}; + +use super::{Body, answer}; +use crate::{Blend, ChamferSecond, Error, Hole, HoleEdge, MAX_POINTS, Result, Turn}; + +/// Why solidcore refuses the 3x2 mixed-convexity corner whose rails cross +/// (`fixes.fillet_refuse_mixed_corner_crossing_rails`, [`MIXED_CORNER_RAILS_CROSS`]): it builds no +/// corner for it yet. +pub(crate) const MIXED_CORNER_UNSUPPORTED: &str = "a fillet corner where a convex and a concave round leave the vertex along one \ +tangent, so that their contact lines cross before the corner (https://github.com/tangency-labs/solidcore/issues/2256)"; +use solidcore::topology::brep::p3::brep_copy; + +/// The capi's statuses as SolidCraft errors: an operation's own result. +type Out = std::result::Result; + +/// `SM_ERR_INVALID_INPUT`. +const INVALID_INPUT: i32 = 1007; + +/// An SMLib status as the capi passes it on (`status`, smlib_shim.h): solidcore's upstream +/// status codes as they are; its refusals of code it has not ported as not supported. +pub(super) fn status(e: SolidError) -> Error { + match e { + SolidError::Upstream { code, .. } => Error::Status(code), + SolidError::InvalidInput { .. } => Error::Status(INVALID_INPUT), + SolidError::Unsupported { reason, .. } if reason == MIXED_CORNER_RAILS_CROSS => Error::Unported(MIXED_CORNER_UNSUPPORTED), + e if e.is_unported() => Error::Unsupported, + e => Error::Solidcore(e.to_string()), + } +} + +/// `size_ok`. +fn size_ok(x: f64) -> bool { + x.is_finite() && x > 0.0 && x <= 1e6 +} + +/// `tolerance_ok`. +pub(super) fn tolerance_ok(t: f64) -> bool { + t.is_finite() && t > 0.0 && t < 1e6 +} + +/// `points_ok`. +pub(super) fn points_ok(points: &[[f64; 3]], allow_none: bool) -> bool { + points.len() <= MAX_POINTS && (allow_none || !points.is_empty()) && points.iter().flatten().all(|x| x.is_finite()) +} + +pub(super) fn p3(p: [f64; 3]) -> Point3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// Why a pick failed: `SMLIB_ERR_PICK_NONE` or `SMLIB_ERR_PICK_AMBIGUOUS`, and the point. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Miss { + None(usize), + Ambiguous(usize), +} + +/// `smlib_pick::pick`: the entity nearest each point, each once, with the index of the point that +/// first picked it. A point picks none when the nearest is farther than `tol`, and is ambiguous +/// when the second nearest is within `tol` too and nearer than the first by at most `model_tol`. +/// An entity whose distance query returns a status other than success is skipped, as the capi +/// skips it ([`answer`]); any other solidcore error fails the pick. +pub(super) fn pick( + all: &[T], + points: &[[f64; 3]], + tol: f64, + model_tol: f64, + mut dist: impl FnMut(T, Point3) -> solidcore::Result>, +) -> solidcore::Result, Vec), Miss>> { + let (mut picked, mut first) = (Vec::new(), Vec::new()); + for (i, p) in points.iter().enumerate() { + let p = p3(*p); + let (mut best, mut d0, mut d1) = (None, f64::INFINITY, f64::INFINITY); + for &x in all { + let Some(d) = dist(x, p)? else { continue }; + if !d.is_finite() { + continue; + } + if d < d0 { + d1 = d0; + d0 = d; + best = Some(x); + } else if d < d1 { + d1 = d; + } + } + let Some(best) = best.filter(|_| d0 <= tol) else { + return Ok(Err(Miss::None(i))); + }; + if d1 <= tol && d1 - d0 <= model_tol { + return Ok(Err(Miss::Ambiguous(i))); + } + if !picked.contains(&best) { + picked.push(best); + first.push(i); + } + } + Ok(Ok((picked, first))) +} + +/// `pick_edges` (`edge_distance`: `SmApiEdgeClosestPoint`). +pub(super) fn pick_edges( + k: &Kernel, + b: &Brep, + points: &[[f64; 3]], + tol: f64, +) -> solidcore::Result, Vec), Miss>> { + let all = brep_p1::edges(b, None)?; + pick(&all, points, tol, b.tolerance(), |e, p| Ok(answer(edge_closest_point(k, b, e, p))?.map(|c| c.closest.distance))) +} + +/// `pick_vertices` (`vertex_distance`). +pub(super) fn pick_vertices(b: &Brep, points: &[[f64; 3]], tol: f64) -> solidcore::Result, Vec), Miss>> { + let all = brep_p1::vertices(b, None)?; + pick(&all, points, tol, b.tolerance(), |v, p| Ok(Some((b.vertex(v)?.point - p).length()))) +} + +/// An edge pick's failure as `pick_error` (ops.rs) reads it. +pub(super) fn edge_miss(m: Miss) -> Error { + match m { + Miss::None(point) => Error::NoMatch { point }, + Miss::Ambiguous(point) => Error::Ambiguous { point }, + } +} + +/// A corner pick's failure as `setback_error` (ops.rs) reads it: the capi writes the corner +/// point's index to `out_failed_corner` only, so the status comes back bare. +fn corner_miss(m: Miss) -> Error { + match m { + Miss::None(_) => Error::Status(ERR_PICK_NONE), + Miss::Ambiguous(_) => Error::Status(ERR_PICK_AMBIGUOUS), + } +} + +/// The capi's statuses for a pick that is near nothing, and for one equally near to two. +const ERR_PICK_NONE: i32 = -1101; +const ERR_PICK_AMBIGUOUS: i32 = -1102; + +/// A corner set back: its vertex and the setback along each of its edges (the capi's +/// `SetBack`; the entry points take no ease, which is 0). +struct SetBack { + vertex: VertexId, + distance: f64, +} + +/// `setbacks_fit`: each setback shorter than every edge at its corner, and where an edge's +/// other end is a setback corner too, the two together shorter than the edge. +fn setbacks_fit(k: &Kernel, b: &Brep, setbacks: &[SetBack]) -> solidcore::Result { + for sb in setbacks { + for e in vertex::edges(b, sb.vertex, None)? { + let Some(length) = answer(edge_length(k, b, e, 1e-6))? else { + return Ok(false); + }; + let far = edge::other_vertex(b, e, Some(sb.vertex))?; + let mut other = 0.0; + for o in setbacks { + if Some(o.vertex) == far && far != Some(sb.vertex) { + other = o.distance; + } + } + if sb.distance + other >= length { + return Ok(false); + } + } + } + Ok(true) +} + +/// The midpoint parameter of `e` (`GetInterval().Evaluate(0.5)`). +fn mid(b: &Brep, e: EdgeId) -> solidcore::Result { + Ok(b.edge(e)?.interval.evaluate(0.5)) +} + +/// `chamfer_radius`: the radius of the ball whose tangent points on the two faces of `e` lie +/// `distance` back from the edge at its midpoint, `distance * tan(a / 2)` with `a` the angle +/// between the directions into the faces; at a cusp (a knife edge) `distance` itself, the ball +/// whose contacts the chamfer joins. `None` where the capi's returns false. +fn chamfer_radius(k: &Kernel, b: &mut Brep, e: EdgeId, distance: f64) -> solidcore::Result> { + let Some(u0) = edge::blend_edgeuse(k, b, e)? else { return Ok(None) }; + let Some(u1) = eu_p1::radial(b, u0)? else { return Ok(None) }; + let t = mid(b, e)?; + let options = BinormalOptions::default(); + let Some(e0) = answer(evaluate_binormal(k, b, u0, t, false, &options))? else { return Ok(None) }; + let Some(e1) = answer(evaluate_binormal(k, b, u1, t, false, &options))? else { return Ok(None) }; + // Unitize's failure (a zero vector) is the capi's `return false`. + let (Ok(n0), Ok(b0), Ok(b1)) = (e0.face_normal.unitize(), e0.binormal.unitize(), e1.binormal.unitize()) else { return Ok(None) }; + let c = b0.dot(b1).clamp(-1.0, 1.0); + // At a cusp (a knife edge: the faces tangent within the half degree `GetBlendEdgeuse` calls + // tangent, folded back on each other, the binormals the same way) a is 0 and no ball lies + // `distance` back along both: the chamfer is the chord between the contacts of the ball of + // radius `distance` (fork e96898d). + let cusp = c > 0.0 && b1.dot(n0).abs() < (0.5 * std::f64::consts::PI / 180.0).sin(); + let radius = if cusp { distance } else { distance * ((1.0 - c) / (1.0 + c)).sqrt() }; + Ok((radius.is_finite() && radius > 0.0).then_some(radius)) +} + +/// What `round_edges` makes: the capi's kinds less the chamfer, which `chamfer_offsets` makes. +#[derive(Clone, Copy, PartialEq)] +enum Section<'a> { + /// A circular section of constant radius (or of a variable radius's law), the turns of two + /// such rounds at a side edge as the [`Turn`] says (`SetSweptTurns`). + Round(Turn), + /// The curvature-continuous section (`SM_FSG_BLEND_CURVE`): the Gⁿ generator's order 2 at the + /// equal-area thumbweight (`SMLIB_BLEND_THUMBWEIGHT`, fork 6148773; solidcore#2261 under + /// `fillet_gn_section_generator`), which takes off what the ball's circle does. + Curvature, + Chord, + /// A chamfer, with each edge's offset of its second surface (`chamfer_offsets`' `second`; + /// the sizes are the first's). + Chamfer(&'a [f64]), +} + +/// The faces of `b`, for `made_faces`: a face whose id is new after the operation was made by +/// it. (The capi marks faces with an attribute SMLib copies through every split; here a face +/// split by the operation counts as made, which only matters to a blend that made no blend +/// face but split one, never seen.) +fn face_set(b: &Brep) -> solidcore::Result> { + Ok(brep_p1::faces(b, None)?.into_iter().collect()) +} + +/// `blend_failure`: a blend the executive found larger than its faces allow +/// (`SM_FILERR_NO_ROOM`) is [`Error::NoRoom`]; a filleted vertex no corner type handles +/// (`SM_FILERR_CORNER_UNSUPPORTED`, which solidcore notes under +/// `fixes.fillet_vertex_error_diagnostics`) is [`Error::CornerUnsupported`]; any other failure +/// its status. `corner` says `CreateFilletCorners` noted such a vertex: the corner it could not +/// make is why a later step fails, so that note stands for it whatever the later step noted +/// (as solidcore's own `FilletSession::do_fillet` keeps it). +/// +/// Except a blend whose rail leaves its face refused as [`NoRoomReason::RailLeavesFace`]: that +/// is solidcore without `fixes.fillet_cliff_overflow`, refusing every such blend where the fork +/// decides between building it over the cliff (`SmFilletCliffOverflow.cpp`, fork 8ba4667) and +/// refusing it. Its answer is the fork's only by chance, so it is [`Error::Unsupported`]. With +/// the cliff overflow on, solidcore makes the fork's choice, and its refusals (each with its own +/// reason) are [`Error::NoRoom`] like the fork's. +/// +/// A blend too large that solidcore sizes (the session's fit, as the fork's capi reads it with +/// `smlib_blend_fit_size`, or [`SolidError::FilletRefused`] carrying it; under +/// `fixes.fillet_gn_section_generator`) is [`Error::TooLarge`] with that size, its edge's point +/// filled in by the caller from the edge returned with it ([`sized_on`]); a corner solidcore +/// refuses as not supported (the mixed corner whose rails cross, solidcore#2256) is +/// [`Error::Unported`] naming it. +fn blend_failure(s: &FilletSession<'_>, e: SolidError, corner: bool) -> (Error, Option) { + let info = s.error_info(); + let (fit, reason) = match &e { + SolidError::FilletRefused { fit, reason, .. } => (Some(*fit), reason.or(info.no_room_reason())), + _ if info.code == FilletErrorType::NoRoom as i32 => (s.fit_size(), info.no_room_reason()), + _ => (None, None), + }; + if e.is_unported() || matches!(e, SolidError::Unsupported { reason, .. } if reason == MIXED_CORNER_RAILS_CROSS) { + (status(e), None) + } else if let Some(fit) = fit + && !corner + && info.no_room_reason() != Some(NoRoomReason::RailLeavesFace) + && fit.size.is_finite() + && fit.size > 0.0 + { + let kind = match fit.kind { + FitKind::Radius => crate::FitKind::Radius, + FitKind::Scale => crate::FitKind::Scale, + FitKind::Chord => crate::FitKind::Chord, + }; + (Error::TooLarge { size: fit.size, kind, at: None, why: reason.and_then(room_reason) }, fit.edge) + } else { + (blend_failure_unsized(info, e, corner), None) + } +} + +/// solidcore's reason for a blend too large, as SolidCraft words it; `None` for the reasons it +/// does not name (the cliff overflow's own refusals). +fn room_reason(r: NoRoomReason) -> Option { + use crate::RoomReason as R; + Some(match r { + NoRoomReason::BallDoesNotFit => R::BallDoesNotFit, + NoRoomReason::RailLeavesFace + | NoRoomReason::ConcaveOverflow + | NoRoomReason::OverflowWithConcaveBlend + | NoRoomReason::OverflowWithRollover + | NoRoomReason::OverflowWithGlobalMerge => R::RailLeavesFace, + NoRoomReason::FaceConsumed => R::FaceConsumed, + NoRoomReason::BandsOverlap => R::BandsOverlap, + NoRoomReason::BallsFold => R::BallsFold, + NoRoomReason::OffsetFolds => R::OffsetFolds, + NoRoomReason::CutsThePart => R::CutsThePart, + NoRoomReason::BreaksThrough => R::BreaksThrough, + NoRoomReason::OffsetCollapses => R::OffsetCollapses, + NoRoomReason::CornersTakeWholeEdge => R::CornersTakeWholeEdge, + NoRoomReason::RoundIntoMaterial | NoRoomReason::RailRunsPastFaceIntoMaterial => R::RunsIntoMaterial, + _ => return None, + }) +} + +/// The refusal of a swept turn `CreateFilletCorners` noted at its vertex (`SmBlendCorner::Classify` +/// with `GetSweptTurns()`): [`Error::TurnRefused`] with solidcore's reason, without its "Fillet +/// Error: " prefix, and where it is; `None` for a note of another kind. +fn turn_refusal(info: &ErrorInfo) -> Option { + let room = match info.code { + c if c == FilletErrorType::NoRoom as i32 => true, + c if c == FilletErrorType::CornerUnsupported as i32 => false, + _ => return None, + }; + let why = info.comment.trim(); + if why.is_empty() { + return None; + } + let why = why.strip_prefix("Fillet Error:").map_or(why, str::trim_start).to_owned(); + Some(Error::TurnRefused { room, why, at: info.location.map(|p| [p.x, p.y, p.z]) }) +} + +/// [`blend_failure`] where solidcore gives no size. +fn blend_failure_unsized(info: &ErrorInfo, e: SolidError, corner: bool) -> Error { + if e.is_unported() { + status(e) + } else if corner || info.code == FilletErrorType::CornerUnsupported as i32 { + Error::CornerUnsupported + } else if info.code != FilletErrorType::NoRoom as i32 { + status(e) + } else if info.no_room_reason() == Some(NoRoomReason::RailLeavesFace) { + Error::Unsupported + } else { + Error::NoRoom + } +} + +/// `e` ([`Error::TooLarge`]) with the point at the middle of `edge` of `b`, the edge its size was +/// found for; an equal chamfer's size (its ball's radius, [`chamfer_radius`]) as its distance. +/// Where the edge or its point can't be read the size stays as it is, with no point (a chamfer's +/// size then is not a distance, so it is left a plain refusal). +fn sized_on(k: &Kernel, b: &mut Brep, edge: Option, section: Section<'_>, e: Error) -> solidcore::Result { + let Error::TooLarge { size, kind, why, .. } = e else { return Ok(e) }; + let Some(edge) = edge else { + return Ok(if matches!(section, Section::Chamfer(_)) && kind == crate::FitKind::Radius { Error::NoRoom } else { e }); + }; + let at = match b.edge(edge) { + Ok(rec) => match rec.curve.as_ref() { + Some(c) => answer(c.evaluate_point(k, rec.interval.evaluate(0.5)))?.map(|p| [p.x, p.y, p.z]), + None => None, + }, + Err(_) => None, + }; + if matches!(section, Section::Chamfer(_)) && kind == crate::FitKind::Radius { + // The ball's radius is linear in the chamfer's distance along an edge. + return Ok(match chamfer_radius(k, b, edge, 1.0)? { + Some(per_mm) => Error::TooLarge { size: size / per_mm, kind: crate::FitKind::Distance, at, why }, + None => Error::NoRoom, + }); + } + Ok(Error::TooLarge { size, kind, at, why }) +} + +/// `round_edges`' `overflow_first` argument: with it the session stops, nothing built, when blends +/// of several edges overflow their faces across cliffs (`SetOverflowFirst`) or (`classify_only`) +/// always (`SetClassifyOnly`), and `stopped` gets the edges whose blends overflow +/// (`GetOverflowEdges`; the capi's status `OVERFLOW_FIRST`, the call's failure then meaning only that) +/// and `mitred` the edges of each two rounds mitred at a face's concave corner, two by two +/// (`GetMitredEdges`), when the caller asks. +struct OverflowFirst<'a> { + classify_only: bool, + stopped: &'a mut Option>, + mitred: Option<&'a mut Vec>, +} + +/// `round_edges` and `chamfer_offsets` (with equal offsets): `edges` of `b` blended in place, +/// edge i at `sizes[i]`, the executive driven as `SmApiFilletEdgesPerEdge` drives it with the +/// corners' setbacks (`SmFilletCorner::SetSetBackDist`) set between making the corners and +/// filleting, or (a chamfer) every corner bevelled; then `StitchAndOrient`. A blend that made +/// no face is [`Error::NoEffect`]. A setback corner that is not SMLib's same-convexity N x N +/// corner is refused with its index in `setbacks` (`Err(Ok(j))`). +/// +/// With `patches`, the session marks the set-back corners' patches (`SetMarkCornerPatches`, fork +/// 60af574), and after the stitch `patches` gets each corner's, in `setbacks`' order: the faces +/// marked with its index, in the body's face order. A corner whose patch has no face is +/// [`Error::Unsupported`]. +fn blend_edges( + k: &mut Kernel, + b: &mut Brep, + edges: &[EdgeId], + sizes: &[f64], + section: Section<'_>, + law: Option, + setbacks: &[SetBack], + patches: Option<&mut Vec>>, +) -> solidcore::Result>> { + blend_edges_stopping(k, b, edges, sizes, section, law, setbacks, patches, None) +} + +/// [`blend_edges`], with `round_edges`' `overflow_first` argument. +#[allow(clippy::too_many_arguments)] // the capi's round_edges +fn blend_edges_stopping( + k: &mut Kernel, + b: &mut Brep, + edges: &[EdgeId], + sizes: &[f64], + section: Section<'_>, + law: Option, + setbacks: &[SetBack], + patches: Option<&mut Vec>>, + overflow_first: Option>, +) -> solidcore::Result>> { + let before = face_set(b)?; + // The edge a sized refusal names ([`blend_failure`]), read after the session lets `b` go. + let mut fit_edge = None; + let done = { + let mut s = FilletSession::new(k, b)?; + // `SetSweptTurns`: read as the corners are made (`fixes.fillet_blend_corner`). + let swept = section == Section::Round(Turn::Swept); + s.set_swept_turns(swept); + // `SetFilletParameters(b, es, sections, solvers, values, laws, -1, -1, -1, -1, + // continuity 1, thumbweight 1)`: the session sets the executive's global merge first, as + // `SmApiFilletEdges` does, and `SetFilletParameters` resets it, as in the capi. + let prepared = match (section, law) { + (Section::Round(_), None) => s.prepare_per_edge_constant_radius(k, edges, sizes, &[FilletSurfaceGeneratorType::Circular], 1, 1.0), + // The size is the start radius (`smlib_fillet_variable`). + (Section::Round(_), Some(law)) => match sizes.first() { + Some(&size) => s.prepare_variable_radius_edges(k, edges, size, law, 1, 1), + None => return Ok(Err(Err(Error::Argument))), + }, + // The equal-area thumbweight by solidcore's name, never its value: solidcore#2274 moves + // it from -2 to 2, after which -2 is an ordinary weight. + (Section::Curvature, _) => { + s.prepare_per_edge_constant_radius(k, edges, sizes, &[FilletSurfaceGeneratorType::BlendCurve], 2, GN_THUMBWEIGHT_EQUAL_AREA) + } + (Section::Chord, _) => s.prepare_per_edge_constant_distance(k, edges, sizes, &[FilletSurfaceGeneratorType::Circular], 1, 1.0), + (Section::Chamfer(second), _) => chamfer_parameters(k, &mut s, edges, sizes, second), + }; + // `AddSetBackVertex` for each set-back vertex, before the corners are made: a set-back + // vertex is no Ball (`IsSetBackVertex`, read by `ClassifyBall`), so its corner is the one + // the setback is set on. + if !matches!(section, Section::Chamfer(_)) { + for sb in setbacks { + s.add_set_back_vertex(sb.vertex); + } + } + let prepared_ok = prepared.is_ok(); + let mut step = prepared.and_then(|()| s.create_corners(k, None)).map(|()| Ok(Vec::new())); + // A swept turn `CreateFilletCorners` refused, with solidcore's reason ([`turn_refusal`]). + let refused_turn = if swept && prepared_ok && step.is_err() { turn_refusal(s.error_info()) } else { None }; + // A vertex `CreateFilletCorners` made no corner for, noted before a later step notes its + // own failure over it ([`blend_failure`]). + let corner = step.is_ok() && s.error_info().code == FilletErrorType::CornerUnsupported as i32; + s.set_overflow_first(overflow_first.is_some()); + s.set_classify_only(overflow_first.as_ref().is_some_and(|o| o.classify_only)); + if let Ok(Ok(_)) = step { + step = corners(&mut s, section, setbacks); + } + s.set_mark_corner_patches(patches.is_some()); + match step { + // The marks go with the session: read them before it drops. + Ok(Ok(set_back)) => match s.do_filleting(k, None) { + Ok(()) => s.corner_patch_faces().map(|marked| Ok((set_back, marked))), + Err(e) => { + if let Some(o) = overflow_first + && s.error_info().code == FilletErrorType::OverflowFirst as i32 + { + *o.stopped = Some(s.overflow_edges()); + if let Some(m) = o.mitred { + *m = s.mitred_edges(); + } + } + let (why, edge) = blend_failure(&s, e, corner); + fit_edge = edge; + Ok(Err(Err(why))) + } + }, + Ok(Err(refusal)) => Ok(Err(refusal)), + Err(e) => match refused_turn { + Some(why) => Ok(Err(Err(why))), + None => { + let (why, edge) = blend_failure(&s, e, corner); + fit_edge = edge; + Ok(Err(Err(why))) + } + }, + } + }; + let done: solidcore::Result, Vec<(usize, FaceId)>), std::result::Result>> = done; + let (set_back, marked) = match done? { + Ok(d) => d, + Err(refusal) => { + b.refresh_cached_topology(); + return Ok(Err(match refusal { + Err(e @ Error::TooLarge { .. }) => Err(sized_on(k, b, fit_edge, section, e)?), + r => r, + })); + } + }; + let stitched = stitch_and_orient(k, b, &StitchAndOrientOptions::default()).map_err(status); + // The port's cached topology, true again for what reads the body next (as solidcore's own + // fillet entry points do). + b.refresh_cached_topology(); + if let Err(e) = stitched { + return Ok(Err(Err(e))); + } + let made = face_set(b)?.difference(&before).count(); + if made == 0 { + return Ok(Err(Err(Error::NoEffect))); + } + if let Some(patches) = patches { + // The stitch keeps the faces filleting made: a corner's patch is the faces marked with + // its index. + let live = brep_p1::faces(b, None)?; + let marked: HashMap = marked.into_iter().map(|(i, f)| (f, i)).collect(); + for &index in &set_back { + let patch: Vec = live.iter().copied().filter(|f| marked.get(f) == Some(&index)).collect(); + if patch.is_empty() { + return Ok(Err(Err(Error::Unsupported))); + } + patches.push(patch); + } + // `RemoveAttributeFromTopology(SM_AI_FILLET_CORNER_FACE)`: the marks are the session's, + // and none is left on the body's own faces. + for f in live { + let at = EntityRef::Face(f); + let marks: Vec<_> = + b.entity_attributes(at).into_iter().filter(|(_, a)| a.attribute_id() == attribute_ids::FILLET_CORNER_FACE).map(|(h, _)| h).collect(); + for h in marks { + b.remove_attribute(at, h)?; + } + } + } + Ok(Ok(())) +} + +/// `chamfer_offsets`' `SetFilletParameters(b, es, kinds, solvers, first, NULL, -1, -1, -1, -1, +/// 1, 1.0, &second)` with every kind `SM_FSG_LINEAR` and every solver `SM_FS_CONST_RADIUS`, as the +/// fork's `SetFilletParameters` runs it (its `pOptSecondRadii`, fork f653ac9). +fn chamfer_parameters(k: &mut Kernel, s: &mut FilletSession<'_>, edges: &[EdgeId], first: &[f64], second: &[f64]) -> solidcore::Result<()> { + if edges.is_empty() { + return Ok(()); + } + s.prepare_per_edge_constant_radius_with_second(k, edges, first, second, &[FilletSurfaceGeneratorType::Linear], 1, 1.0) +} + +/// The corners' part of `round_edges` / `chamfer_offsets`: a chamfer's corners bevelled; each +/// setback set on its vertex's corner (`GetFilletCornerOfVertex`), which must be an +/// `SM_FCR_N_x_N_CONVEX` corner or a blend corner whose event is the setback (`SM_FCR_BLEND` with +/// `SM_BCE_SETBACK`, as the fork's capi `round_edges` takes it; `fixes.fillet_blend_corner`). +/// Each set-back corner's index in the session's corners, in `setbacks`' order. +fn corners( + s: &mut FilletSession<'_>, + section: Section<'_>, + setbacks: &[SetBack], +) -> solidcore::Result, std::result::Result>> { + let ids = s.fillet_corners()?; + if matches!(section, Section::Chamfer(_)) { + for id in ids { + s.set_corner_bevel(id, true)?; + } + return Ok(Ok(Vec::new())); + } + let mut set_back = Vec::with_capacity(setbacks.len()); + for (j, sb) in setbacks.iter().enumerate() { + let mut found = None; + for (i, &id) in ids.iter().enumerate() { + if s.corner(id)?.vertex == Some(sb.vertex) { + found = Some((i, id)); + break; + } + } + let Some((i, id)) = found else { + return Ok(Err(Err(Error::Argument))); + }; + let corner = s.corner(id)?; + let setback_blend = corner.blend.is_some_and(|b| b.event == BlendCornerEvent::Setback); + if corner.corner_type() != FilletCornerType::NByNConvex && !setback_blend { + return Ok(Err(Ok(j))); + } + s.set_corner_setback(id, sb.distance)?; + set_back.push(i); + } + Ok(Ok(set_back)) +} + +/// `finish`: the result must have faces, and a solid input must give a closed manifold solid. +pub(super) fn finish(b: Brep, solid_in: bool) -> solidcore::Result> { + if b.face_list().is_empty() { + return Ok(Err(Error::Empty)); + } + if solid_in && !brep_p2::is_manifold_solid(&b)? { + return Ok(Err(Error::NotSolid)); + } + Ok(Ok(b)) +} + +/// Runs `f` on a copy of `body` (`brep_copy`). +pub(super) fn on_copy(call: &'static str, body: &Body, f: impl FnOnce(&mut Kernel, Brep) -> solidcore::Result>) -> Result { + if body.0.is_poisoned() { + return Err(Error::Internal(format!("{call}: the body was left unfinished by an earlier panic"))); + } + super::run_on(call, &[("brep", body)], |k| { + let c = brep_copy(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner))?; + f(k, c) + })? + .map(Body::new) +} + +/// What [`blend`] does with the picked corners' patches. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Corners { + /// Filled, as SMLib builds them (`smlib_blend`, `smlib_blend_setback`). + Filled, + /// Removed, the holes listed (`smlib_blend_setback_open`). + Open, +} + +/// `Picked::ID`: above SMLib's own ids (`SM_AI_USER_1 + 9`). +const PICKED_ID: u64 = attribute_ids::USER_1 + 9; + +/// The capi's `Picked`: which picked edge an edge stands for, put on the picked edges before an +/// overflowing blend goes first, handed on through every split and copy (`SM_AB_COPY`), so +/// afterwards the edges carrying it are what the overflow left of that picked edge (none: it +/// removed the edge whole). +#[derive(Debug, Clone, PartialEq)] +struct Picked(usize); + +impl AttributeHandlers for Picked {} + +/// The attribute `Picked` on `e`, with its handle. +fn picked_on(b: &Brep, e: EdgeId) -> Option<(solidcore::geom::attribute::AttributeHandle, usize)> { + let (h, a) = b.entity_attributes(EntityRef::Edge(e)).into_iter().find(|(_, a)| a.attribute_id() == PICKED_ID)?; + a.application_value::().map(|p| (h, p.0)) +} + +/// Whether the rounds that overflow go first ([`overflow_first`]): on since solidcore#1980, which +/// keeps the attributes of the target edges the subtraction replaces, so a picked edge the overflow +/// only shortened still reads as picked. +const OVERFLOW_GOES_FIRST: bool = true; + +/// `overflow_first`: the rounds of [`blend_call`] when blends of several edges overflow their +/// faces (`round_edges` stopped in the copy `w` of `body`, `picked` its picked edges, `each` their +/// sizes). The blends that overflow on their own (each edge's alone, classified in `w`, which +/// nothing was built in) go first: on a fresh copy of `body`, the picked edges tagged with their +/// places ([`Picked`]), those are rounded, and each other picked edge is then what is left of it, +/// the edges carrying its tag, rounded at its size. A picked edge with nothing left is gone: its +/// points are flagged in `dropped`. Two rounds mitred at a face's concave corner (`mitred`, the edges +/// of each such pair two by two, as the stopped call found them in `w`) meet in their mitre, each run +/// on past the corner: one goes first with the other, so a round mitred to one that overflows goes +/// first too (fork 9ba2b12). Where none overflows on its own, or all go first, the edges are rounded +/// together as before. The result is the new body. Unlike the capi, the tags come off it +/// (nothing reads them after the call, and a later call's copy would carry them on). +#[allow(clippy::too_many_arguments)] // the capi's overflow_first +fn overflow_first( + k: &mut Kernel, + body: &Body, + points: &[[f64; 3]], + tolerance: f64, + section: Section<'_>, + picked: &[EdgeId], + mitred: &[EdgeId], + each: &[f64], + w: &mut Brep, + dropped: &mut [bool], +) -> solidcore::Result> { + /// A failure of `round_edges` on the fresh copy, which has no setback corners. + fn failed(e: std::result::Result) -> Error { + e.err().unwrap_or(Error::Unsupported) + } + let mut fresh = { + let g = body.0.lock().unwrap_or_else(PoisonError::into_inner); + brep_copy(k, &g)? + }; + let again = match pick_edges(k, &fresh, points, tolerance)? { + Ok((again, _)) if again.len() == picked.len() => again, + Ok(_) => return Ok(Err(Error::NoMatch { point: 0 })), + Err(m) => return Ok(Err(edge_miss(m))), + }; + let mut goes_first = vec![false; picked.len()]; + for (i, ((&e, &to), &size)) in picked.iter().zip(&again).zip(each).enumerate() { + let mut stopped = None; + let alone = OverflowFirst { classify_only: true, stopped: &mut stopped, mitred: None }; + match blend_edges_stopping(k, w, &[e], &[size], section, None, &[], None, Some(alone))? { + Err(Err(why)) if stopped.is_none() => return Ok(Err(why)), + Err(Ok(_)) => return Ok(Err(Error::Unsupported)), + Ok(()) => return Ok(Err(Error::Status(1001))), + Err(Err(_)) => {} + } + fresh.add_attribute(EntityRef::Edge(to), Attribute::application(PICKED_ID, Behavior::Copy, Picked(i)))?; + if let Some(flag) = goes_first.get_mut(i) { + *flag = stopped.is_some_and(|over| !over.is_empty()); + } + } + // A round mitred to one that goes first goes with it, through every mitre. + let place = |e: &EdgeId| picked.iter().position(|p| p == e); + let pairs: Vec<(usize, usize)> = mitred.as_chunks::<2>().0.iter().filter_map(|[a, b]| Some((place(a)?, place(b)?))).collect(); + let mut grew = true; + while grew { + grew = false; + for &(a, b) in &pairs { + if goes_first.get(a) != goes_first.get(b) { + for i in [a, b] { + if let Some(flag) = goes_first.get_mut(i) { + *flag = true; + } + } + grew = true; + } + } + } + let (mut lead, mut lead_sizes, mut rest) = (Vec::new(), Vec::new(), Vec::new()); + for (i, ((&to, &size), &first)) in again.iter().zip(each).zip(&goes_first).enumerate() { + if first { + lead.push(to); + lead_sizes.push(size); + } else { + rest.push(i); + } + } + if lead.is_empty() || rest.is_empty() { + return Ok(match blend_edges(k, &mut fresh, &again, each, section, None, &[], None)? { + Ok(()) => untagged(fresh), + Err(e) => Err(failed(e)), + }); + } + if let Err(e) = blend_edges(k, &mut fresh, &lead, &lead_sizes, section, None, &[], None)? { + return Ok(Err(failed(e))); + } + let edges = brep_p1::edges(&fresh, None)?; + let (mut rest_edges, mut rest_sizes) = (Vec::new(), Vec::new()); + for i in rest { + let mut left = false; + for &e in &edges { + if picked_on(&fresh, e).is_some_and(|(_, p)| p == i) { + rest_edges.push(e); + rest_sizes.push(each.get(i).copied().unwrap_or(0.0)); + left = true; + } + } + if !left { + // Every point that picked edge i (in `w`, which nothing was built in). + for (j, p) in points.iter().enumerate() { + if let (Ok((one, _)), Some(flag)) = (pick_edges(k, w, std::slice::from_ref(p), tolerance)?, dropped.get_mut(j)) + && one.as_slice() == picked.get(i..=i).unwrap_or_default() + { + *flag = true; + } + } + } + } + if !rest_edges.is_empty() + && let Err(e) = blend_edges(k, &mut fresh, &rest_edges, &rest_sizes, section, None, &[], None)? + { + return Ok(Err(failed(e))); + } + Ok(untagged(fresh)) +} + +/// `b` with [`Picked`] off its edges. +fn untagged(mut b: Brep) -> Out { + let edges = brep_p1::edges(&b, None).map_err(status)?; + for e in edges { + if let Some((h, _)) = picked_on(&b, e) { + b.remove_attribute(EntityRef::Edge(e), h).map_err(status)?; + } + } + Ok(b) +} + +/// Why a curvature fillet over edges of different wedge angles is refused. The equal-area +/// thumbweight is resolved once per call, from the first blend's wedge, and every edge takes it +/// (in the fork as in solidcore#2261): an edge of another wedge takes off another area than its +/// own, and which one depends on the edges' order. +pub(crate) const CURVATURE_MIXED_WEDGES: &str = "a curvature-continuous fillet on solidcore over edges whose faces meet at different \ +angles: every edge takes the equal-area thumbweight of the first one's angle, so the others take off the wrong area \ +(https://github.com/tangency-labs/solidcore/issues/2250#issuecomment-6563419897)"; + +/// How far apart, in radians, two edges' wedge angles may be and still share one equal-area +/// thumbweight. +const WEDGE_TOLERANCE: f64 = 1e-6; + +/// Whether the faces of every edge in `edges` meet at the same angle at its midpoint (the wedge the +/// equal-area thumbweight is resolved from), within [`WEDGE_TOLERANCE`]. An edge whose angle can't +/// be read counts as another wedge. +fn one_wedge(k: &Kernel, b: &mut Brep, edges: &[EdgeId]) -> solidcore::Result { + let mut first: Option = None; + for &e in edges { + let Some(u0) = edge::blend_edgeuse(k, b, e)? else { return Ok(false) }; + let Some(u1) = eu_p1::radial(b, u0)? else { return Ok(false) }; + let (Some((n0, _)), Some((n1, _))) = (face_frame(k, b, u0)?, face_frame(k, b, u1)?) else { return Ok(false) }; + let angle = n0.dot(n1).clamp(-1.0, 1.0).acos(); + match first { + None => first = Some(angle), + Some(a) if (a - angle).abs() > WEDGE_TOLERANCE => return Ok(false), + Some(_) => {} + } + } + Ok(true) +} + +/// [`blend_holes`] without its holes. +#[allow(clippy::too_many_arguments)] // the capi's blend_call +pub(crate) fn blend( + body: &Body, + kind: Blend, + points: &[[f64; 3]], + sizes: &[f64], + tolerance: f64, + corners: &[[f64; 3]], + setbacks: &[f64], + open: Corners, +) -> Result { + blend_holes(body, kind, points, sizes, tolerance, corners, setbacks, open).map(|(b, _)| b) +} + +/// `smlib_blend_dropping`: [`blend`] with one size per point, no corners, and per point whether it +/// picked an edge that a larger round, overflowing its faces, removed whole. +pub(crate) fn blend_dropping(body: &Body, kind: Blend, turn: Turn, points: &[[f64; 3]], sizes: &[f64], tolerance: f64) -> Result<(Body, Vec)> { + let mut dropped = vec![false; points.len()]; + let (b, _) = blend_call(body, kind, turn, points, sizes, tolerance, &[], &[], Corners::Filled, &mut dropped)?; + Ok((b, dropped)) +} + +/// `blend_call` (as `smlib_fillet`, `smlib_chamfer`, `smlib_blend`, `smlib_blend_setback` and +/// `smlib_blend_setback_open` call it): `sizes` one per point, or one for all; `corners` and +/// `setbacks` the corner setbacks. With [`Corners::Open`], the holes, one per point of +/// `corners` (none otherwise). +#[allow(clippy::too_many_arguments)] // the capi's blend_call +pub(crate) fn blend_holes( + body: &Body, + kind: Blend, + points: &[[f64; 3]], + sizes: &[f64], + tolerance: f64, + corners: &[[f64; 3]], + setbacks: &[f64], + open: Corners, +) -> Result<(Body, Vec)> { + blend_call(body, kind, Turn::Mitre, points, sizes, tolerance, corners, setbacks, open, &mut vec![false; points.len()]) +} + +/// `blend_call`: [`blend_holes`], with per point in `dropped` whether it picked an edge an +/// overflowing round removed whole ([`overflow_first`]), and the rounds' turns at side edges as +/// `turn` says (a swept turn is for [`Blend::Round`] only). +#[allow(clippy::too_many_arguments)] // the capi's blend_call +fn blend_call( + body: &Body, + kind: Blend, + turn: Turn, + points: &[[f64; 3]], + sizes: &[f64], + tolerance: f64, + corners: &[[f64; 3]], + setbacks: &[f64], + open: Corners, + dropped: &mut [bool], +) -> Result<(Body, Vec)> { + let one_size = sizes.len() == 1; + if !points_ok(points, false) + || !tolerance_ok(tolerance) + || !(one_size || sizes.len() == points.len()) + || !points_ok(corners, true) + || setbacks.len() != corners.len() + || (turn == Turn::Swept && kind != Blend::Round) + { + return Err(Error::Argument); + } + if !sizes.iter().all(|&s| size_ok(s)) || !setbacks.iter().all(|&s| size_ok(s)) { + return Err(Error::Argument); + } + // A chamfer's corners are bevelled, which builds no setback. + if !corners.is_empty() && kind == Blend::Chamfer { + return Err(Error::Unsupported); + } + let mut holes = Vec::new(); + let made = on_copy("blend_call", body, |k, mut w| { + let (picked, first) = match pick_edges(k, &w, points, tolerance)? { + Ok(p) => p, + Err(m) => return Ok(Err(edge_miss(m))), + }; + let each: Vec = first.iter().map(|&i| sizes.get(if one_size { 0 } else { i }).copied().unwrap_or(0.0)).collect(); + // Each corner point picks a vertex; a vertex picked twice takes the first point's setback. + let (at, first_corner) = match pick_vertices(&w, corners, tolerance)? { + Ok(p) => p, + Err(m) => return Ok(Err(corner_miss(m))), + }; + let back: Vec = + at.iter().zip(&first_corner).map(|(&vertex, &j)| SetBack { vertex, distance: setbacks.get(j).copied().unwrap_or(0.0) }).collect(); + if !setbacks_fit(k, &w, &back)? { + return Ok(Err(Error::NoRoom)); + } + let solid_in = brep_p2::is_manifold_solid(&w)?; + let section = match kind { + Blend::Round => Section::Round(turn), + // Every edge of one call takes the equal-area thumbweight of the first's wedge + // (solidcore#2250's comment 6563419897): edges of other wedges would take off another + // area than their own, so they are not built together. + Blend::Curvature if !one_wedge(k, &mut w, &picked)? => return Ok(Err(Error::Unported(CURVATURE_MIXED_WEDGES))), + Blend::Curvature => Section::Curvature, + Blend::Chord => Section::Chord, + // `chamfer_edges`: each edge's offsets from its setback at its midpoint. + Blend::Chamfer => { + let mut radii = Vec::with_capacity(picked.len()); + for (&e, &d) in picked.iter().zip(&each) { + match chamfer_radius(k, &mut w, e, d)? { + Some(r) => radii.push(r), + None => return Ok(Err(Error::Status(INVALID_INPUT))), + } + } + return Ok(match blend_edges(k, &mut w, &picked, &radii, Section::Chamfer(&radii), None, &[], None)? { + Ok(()) => finish(w, solid_in)?, + Err(Ok(_)) => Err(Error::Unsupported), + Err(Err(e)) => Err(e), + }); + } + }; + // The corners' places, read now: filleting deletes the vertices. + let at_points = at.iter().map(|&v| vertex::point(&w, v)).collect::>>()?; + let mut patches = Vec::new(); + // An overflow goes first (rounds without corner setbacks): when some of the rounds + // overflow their faces across cliffs and others fit, the overflowing ones are built + // first, on a fresh copy, and the others then round what is left of their edges. An edge + // the overflow removes whole is gone (`dropped`); one it cuts keeps the rest. + let may_go_first = OVERFLOW_GOES_FIRST && back.is_empty() && open == Corners::Filled && picked.len() > 1; + let (mut stopped, mut mitred) = (None, Vec::new()); + let first = may_go_first.then_some(OverflowFirst { classify_only: false, stopped: &mut stopped, mitred: Some(&mut mitred) }); + let done = blend_edges_stopping(k, &mut w, &picked, &each, section, None, &back, (open == Corners::Open).then_some(&mut patches), first)?; + if stopped.is_some() { + return Ok(match overflow_first(k, body, points, tolerance, section, &picked, &mitred, &each, &mut w, dropped)? { + Ok(fresh) => finish(fresh, solid_in)?, + Err(e) => Err(e), + }); + } + match done { + Ok(()) => {} + // A corner SMLib does not set back: the first of the caller's points that picked it. + Err(Ok(j)) => return Ok(Err(first_corner.get(j).map_or(Error::Unsupported, |&corner| Error::CornerRefused { corner }))), + Err(Err(e)) => return Ok(Err(e)), + } + if open == Corners::Filled { + return finish(w, solid_in); + } + // Each corner opened: its patch removed, the edges round its hole in the result's + // orders, once per corner point (a vertex picked twice gives its hole twice). + if !brep_p2::is_manifold_solid(&w)? { + return Ok(Err(Error::NotSolid)); + } + let rims = match open_corners(k, &mut w, &patches)? { + Ok(r) => r, + Err(e) => return Ok(Err(e)), + }; + let edge_index: HashMap = brep_p1::edges(&w, None)?.into_iter().enumerate().map(|(i, e)| (e, i)).collect(); + let face_index: HashMap = brep_p1::faces(&w, None)?.into_iter().enumerate().map(|(i, f)| (f, i)).collect(); + for c in corners { + let p = Point3::new(c[0], c[1], c[2]); + let mut which = None; + let mut best = f64::INFINITY; + for (j, q) in at_points.iter().enumerate() { + let d = (*q - p).length(); + if d < best { + best = d; + which = Some(j); + } + } + let Some(rim) = which.and_then(|j| rims.get(j)) else { return Ok(Err(Error::Argument)) }; + let mut edges = Vec::with_capacity(rim.len()); + for h in rim { + let (Some(&edge), Some(&face)) = (edge_index.get(&h.edge), face_index.get(&h.face)) else { return Ok(Err(Error::Unsupported)) }; + edges.push(HoleEdge { edge, face, forward: h.forward }); + } + holes.push(Hole { edges }); + } + finish(w, false) + })?; + Ok((made, holes)) +} + +/// One edge round an opened corner's hole (`HoleEdge`): the face beside it, and whether that +/// face's boundary, run counter-clockwise about its outward normal (the solid's), runs the edge +/// from its start vertex to its end. +#[derive(Clone, Copy)] +struct RimEdge { + edge: EdgeId, + face: FaceId, + forward: bool, +} + +/// `open_corners`: the faces of each patch in `patches` removed from the solid `b`, with the edges +/// and vertices only they used, and the edges round each patch's hole, as the faces beside it run +/// them, each edge's start the previous one's end. Read on the solid before anything is removed, +/// where each face's outward side is known. Each edge round a hole must lie between a face of its +/// patch and one other face, outside every patch, and the edges must close one loop (a patch that +/// is a disc), else [`Error::Unsupported`]. +fn open_corners(k: &mut Kernel, b: &mut Brep, patches: &[Vec]) -> solidcore::Result>>> { + let any: HashSet = patches.iter().flatten().copied().collect(); + let mut holes = Vec::with_capacity(patches.len()); + for patch in patches { + let mine: HashSet = patch.iter().copied().collect(); + let mut seen = HashSet::new(); + let mut rim: Vec = Vec::new(); + for &f in patch { + for e in face_p4::edges(b, f, None, false, None)? { + if !seen.insert(e) { + continue; + } + let beside = edge::faces(b, e, None)?; + let mut outside = beside.iter().copied().filter(|g| !mine.contains(g)); + let (Some(other), more) = (outside.next(), outside.next()) else { continue }; + if more.is_some() || beside.len() != 2 || any.contains(&other) { + return Ok(Err(Error::Unsupported)); + } + let Some(fu) = outer_faceuse(b, other)? else { return Ok(Err(Error::Unsupported)) }; + let mut used = None; + for u in edge::edgeuses(b, e, None, None)? { + if eu_p1::faceuse(b, u)? == Some(fu) { + used = Some(u); + } + } + let Some(u) = used else { return Ok(Err(Error::Unsupported)) }; + rim.push(RimEdge { edge: e, face: other, forward: b.edgeuse(u)?.orientation == OrientType::Same }); + } + } + let ends = |h: &RimEdge| -> solidcore::Result<(Option, Option)> { + let (s, t) = edge::start_end_vertices(b, h.edge)?; + Ok(if h.forward { (s, t) } else { (t, s) }) + }; + let Some(&front) = rim.first() else { return Ok(Err(Error::Unsupported)) }; + let start = ends(&front)?.0; + let mut used = vec![false; rim.len()]; + if let Some(u) = used.first_mut() { + *u = true; + } + let mut hole = vec![front]; + let mut end = ends(&front)?.1; + // Each turn takes a rim edge not yet in the hole, so it ends within the rim's length. + while end != start { + let mut next = None; + for (i, h) in rim.iter().enumerate() { + if !used.get(i).copied().unwrap_or(true) && ends(h)?.0 == end { + if next.is_some() { + return Ok(Err(Error::Unsupported)); + } + next = Some((i, *h)); + } + } + let Some((i, h)) = next else { return Ok(Err(Error::Unsupported)) }; + if let Some(u) = used.get_mut(i) { + *u = true; + } + hole.push(h); + end = ends(&h)?.1; + } + if hole.len() != rim.len() { + return Ok(Err(Error::Unsupported)); + } + holes.push(hole); + } + // `DeleteFace(f, TRUE)` with the B-rep open for editing, each face once, in the patches' + // order. + let mut order = Vec::with_capacity(any.len()); + let mut taken = HashSet::new(); + for &f in patches.iter().flatten() { + if taken.insert(f) { + order.push(f); + } + } + let editing = b.editing_enabled(); + b.set_editing_enabled(true); + let mut deleted = Ok(()); + { + let mut state = ArenaNotifyState::new(b); + let mut env = state.env(None); + let mut marks = Marks::default(); + for f in order { + let options = DeleteFaceOptions { delete_edges_vertices: true, ..DeleteFaceOptions::default() }; + if let Err(e) = delete_face(k, b, &mut env, &mut marks, f, options) { + deleted = Err(e); + break; + } + } + } + b.set_editing_enabled(editing); + b.refresh_cached_topology(); + Ok(match deleted { + Ok(()) => Ok(holes), + Err(e) => Err(status(e)), + }) +} + +/// The faceuse of `f` on the outside of its body (`outer_faceuse`): the one bounding the +/// infinite region (for a sheet, the upward one). +fn outer_faceuse(b: &Brep, f: FaceId) -> solidcore::Result> { + let Some(fu) = face_p2::upward_faceuse(b, f)? else { return Ok(None) }; + let shell = b.faceuse(fu)?.shell; + let region = match shell { + Some(sh) => b.shell(sh)?.region, + None => None, + }; + if shell.is_none() || region != b.infinite_region() { Ok(b.faceuse(fu)?.mate) } else { Ok(Some(fu)) } +} + +/// `face_frame`: the outward unit normal, at the edge's midpoint, of the face the edge use `u` +/// bounds, and the unit direction into that face square to the edge. +fn face_frame(k: &Kernel, b: &mut Brep, u: EdgeuseId) -> solidcore::Result> { + let Some(e) = b.edgeuse(u)?.edge else { return Ok(None) }; + let fu_of_lu = match eu_p1::loopuse(b, u)? { + Some(lu) => b.loopuse(lu)?.faceuse, + None => None, + }; + let f = match fu_of_lu { + Some(fu) => b.faceuse(fu)?.face, + None => None, + }; + let Some(f) = f else { return Ok(None) }; + let Some(fu) = outer_faceuse(b, f)? else { return Ok(None) }; + if b.face(f)?.surface.is_none() { + return Ok(None); + } + let t = mid(b, e)?; + let Some(at) = answer(evaluate_binormal(k, b, u, t, false, &BinormalOptions::default()))? else { return Ok(None) }; + let Some(normal) = answer(evaluate_surface_normal(k, b.face(f)?.surface.as_ref(), at.uv))? else { return Ok(None) }; + let len = normal.length(); + if !(len > 0.0 && len.is_finite()) { + return Ok(None); + } + let sign = if b.faceuse(fu)?.orientation == OrientType::Same { 1.0 } else { -1.0 }; + Ok(Some((normal * (sign / len), at.binormal))) +} + +/// `sides_offsets`: the surface offsets of `e` (its blend edge use's surface first) at which +/// `chamfer_offsets` cuts a chamfer `d1` back along the face whose outward normal at the edge's +/// midpoint leans most along `up`, and `second` back along the other (or at the angle `second` +/// to the first face). With b0, b1 the directions into the faces and θ the angle between them, +/// setbacks s0, s1 lie at offsets r0 = (s1 - s0 cos θ) / sin θ and r1 = (s0 - s1 cos θ) / sin θ; +/// an angle φ to the first face gives s1 = s0 sin φ / sin(θ + φ). +fn sides_offsets(k: &Kernel, b: &mut Brep, e: EdgeId, d1: f64, second: ChamferSecond, up: Vec3) -> solidcore::Result> { + let Some(u0) = edge::blend_edgeuse(k, b, e)? else { return Ok(None) }; + let Some(u1) = eu_p1::radial(b, u0)? else { return Ok(None) }; + let (Some((n0, b0)), Some((n1, b1))) = (face_frame(k, b, u0)?, face_frame(k, b, u1)?) else { return Ok(None) }; + let c = b0.dot(b1).clamp(-1.0, 1.0); + let sn = (1.0 - c * c).max(0.0).sqrt(); + if !(sn > 1e-6) { + return Ok(None); + } + let mut s0 = d1; + let mut s1 = match second { + ChamferSecond::Distance(d) => d, + ChamferSecond::Angle(phi) => { + let d = (c.acos() + phi).sin(); + if !(d > 1e-9) { + return Ok(None); + } + d1 * phi.sin() / d + } + }; + if n1.dot(up) > n0.dot(up) { + std::mem::swap(&mut s0, &mut s1); + } + let (r0, r1) = ((s1 - s0 * c) / sn, (s0 - s1 * c) / sn); + Ok((r0.is_finite() && r1.is_finite() && r0 > 0.0 && r1 > 0.0).then_some((r0, r1))) +} + +/// `smlib_chamfer_sides`: the edges nearest `points` chamfered `distance` back along the face +/// whose outward normal leans most along `first`, and by `second` on the other, with bevelled +/// corners. +pub(crate) fn chamfer_sides(body: &Body, points: &[[f64; 3]], tolerance: f64, distance: f64, second: ChamferSecond, first: [f64; 3]) -> Result { + let second_ok = match second { + ChamferSecond::Angle(a) => a.is_finite() && a > 1e-6 && a < std::f64::consts::PI - 1e-6, + ChamferSecond::Distance(d) => size_ok(d), + }; + if !points_ok(points, false) || !tolerance_ok(tolerance) || !size_ok(distance) || !second_ok || !first.iter().all(|x| x.is_finite()) { + return Err(Error::Argument); + } + let up = p3(first); + if !(up.length() > 0.0) { + return Err(Error::Argument); + } + on_copy("smlib_chamfer_sides", body, |k, mut w| { + let picked = match pick_edges(k, &w, points, tolerance)? { + Ok((p, _)) => p, + Err(m) => return Ok(Err(edge_miss(m))), + }; + let solid_in = brep_p2::is_manifold_solid(&w)?; + let (mut r0, mut r1) = (Vec::with_capacity(picked.len()), Vec::with_capacity(picked.len())); + for &e in &picked { + match sides_offsets(k, &mut w, e, distance, second, up)? { + Some((a, b)) => { + r0.push(a); + r1.push(b); + } + None => return Ok(Err(Error::Status(INVALID_INPUT))), + } + } + Ok(match blend_edges(k, &mut w, &picked, &r0, Section::Chamfer(&r1), None, &[], None)? { + Ok(()) => finish(w, solid_in)?, + Err(Ok(_)) => Err(Error::Unsupported), + Err(Err(e)) => Err(e), + }) + }) +} + +/// `law_ok`: a clamped B-spline of `degree` 1 to 3 from 0 to 1, 2 to 100 control radii, each +/// finite, at least 0 and at most 1e6. +fn law_ok(degree: usize, knots: &[f64], radii: &[f64]) -> bool { + let n = radii.len(); + if !(1..=3).contains(°ree) || !(2..=100).contains(&n) || n <= degree || knots.len() != n + degree + 1 { + return false; + } + if !knots.iter().chain(radii).all(|x| x.is_finite()) { + return false; + } + for (i, &k) in knots.iter().enumerate() { + let (low_end, high_end) = (i <= degree, i >= n); + if (low_end && k != 0.0) || (high_end && k != 1.0) || (i > 0 && knots.get(i - 1).is_some_and(|&p| k < p)) { + return false; + } + } + radii.iter().all(|&r| (0.0..=1e6).contains(&r)) +} + +/// `law_pinches`: whether the law's radius is zero somewhere inside (0, 1). +fn law_pinches(degree: usize, knots: &[f64], radii: &[f64]) -> bool { + let n = radii.len() as i64; + let p = degree as i64; + let all_zero = |from: i64, to: i64| -> bool { + let lo = from.max(0); + let mut j = lo; + while j <= to && j < n { + if radii.get(j as usize).is_some_and(|&r| r != 0.0) { + return false; + } + j += 1; + } + from <= to + }; + let kn = |i: i64| knots.get(i as usize).copied().unwrap_or(f64::NAN); + let n_knots = n + p + 1; + let mut i = p; + while i + 1 < n_knots && i < n { + if kn(i) < kn(i + 1) && all_zero(i - p, i) { + return true; + } + i += 1; + } + let mut s = p + 1; + while s < n { + let mut m = 1; + while s + m < n && kn(s + m) == kn(s) { + m += 1; + } + if all_zero(s + m - 1 - p, s - 1) { + return true; + } + s += m; + } + false +} + +/// Whether the law has a corner inside (0, 1) (`SmBSplineFilletLaw::GetCornerParameters`, fork +/// 6eecf04): an interior knot where the radius' slope from the left and from the right differ by +/// more than `SM_EFF_ZERO * (1 + |left| + |right|)`. The slope is the derivative B-spline's, +/// `Q_i = p (r_{i+1} - r_i) / (u_{i+p+1} - u_{i+1})`; it jumps only at a knot repeated `m >= p` +/// times, from `Q_{s-2}` to `Q_{s+m-1-p}` (`s` the knot's first index). +fn law_has_corner(degree: usize, knots: &[f64], radii: &[f64]) -> bool { + const EFF_ZERO: f64 = 1e-12; + let p = degree; + let q = |i: usize| -> Option { + let (r0, r1) = (radii.get(i)?, radii.get(i + 1)?); + let span = knots.get(i + p + 1)? - knots.get(i + 1)?; + Some(p as f64 * (r1 - r0) / span) + }; + let n = radii.len(); + let mut s = p + 1; + while s < n { + let Some(&u) = knots.get(s) else { break }; + let mut m = 1; + while knots.get(s + m) == Some(&u) { + m += 1; + } + if m >= p && u > 0.0 && u < 1.0 { + let (Some(left), Some(right)) = (s.checked_sub(2).and_then(q), q(s + m - 1 - p)) else { + return true; + }; + if (left - right).abs() > EFF_ZERO * (1.0 + left.abs() + right.abs()) { + return true; + } + } + s += m; + } + false +} + +/// `law_along`: the radius law along `e`, the B-spline with the radius as its x and its own +/// parameter as its y (control points at the Greville abscissae), reversed when `start` is +/// nearer the end of the edge's interval than its start. `None` where the capi's is null. +fn law_along(k: &Kernel, b: &Brep, e: EdgeId, start: [f64; 3], degree: usize, knots: &[f64], radii: &[f64]) -> solidcore::Result> { + let edge = b.edge(e)?; + let Some(curve) = edge.curve.as_ref() else { return Ok(None) }; + let ivl = edge.interval; + let (Some(lo), Some(hi)) = (answer(curve.evaluate_point(k, ivl.min()))?, answer(curve.evaluate_point(k, ivl.max()))?) else { + return Ok(None); + }; + let at = p3(start); + let reverse = (hi - at).length() < (lo - at).length(); + let (nk, nr) = (knots.len(), radii.len()); + let kv: Vec = (0..nk).map(|i| if reverse { 1.0 - knots[nk - 1 - i] } else { knots[i] }).collect(); + let mut cps = Vec::with_capacity(nr); + for i in 0..nr { + let g: f64 = (1..=degree).filter_map(|j| kv.get(i + j)).sum(); + let r = if reverse { radii[nr - 1 - i] } else { radii[i] }; + cps.push(Vec3::new(r, g / degree as f64, 0.0)); + } + let (mut unique, mut mults): (Vec, Vec) = (Vec::new(), Vec::new()); + for &x in &kv { + match (unique.last(), mults.last_mut()) { + (Some(&u), Some(m)) if u == x => *m += 1, + _ => { + unique.push(x); + mults.push(1); + } + } + } + let data = CanonicalData { + dim: 3, + degree, + control_points: &cps, + form: BSplineCurveForm::Unspecified, + knot_multiplicities: &mults, + knots: &unique, + knot_type: KnotType::Unspecified, + weights: None, + trim: None, + }; + let Some(c) = answer(BSplineCurve::create_canonical(&data))? else { return Ok(None) }; + // The law's map is the whole curve, 0 to 1 (`FilletLaw::new`'s). + Ok(Some(FilletLaw::new(FilletLawKind::BSpline { law_curve: c, extended_law: None }))) +} + +/// `smlib_fillet_variable`: the one edge nearest `point` rounded with the radius law of +/// `degree`, `knots` and `radii`, 0 at the end nearest `start`. +pub(crate) fn fillet_variable( + body: &Body, + point: [f64; 3], + tolerance: f64, + start: [f64; 3], + degree: usize, + knots: &[f64], + radii: &[f64], +) -> Result { + if !points_ok(&[point], false) || !start.iter().all(|x| x.is_finite()) || !tolerance_ok(tolerance) || !law_ok(degree, knots, radii) { + return Err(Error::Argument); + } + if law_pinches(degree, knots, radii) { + return Err(Error::Unsupported); + } + on_copy("smlib_fillet_variable", body, |k, mut w| { + let picked = match pick_edges(k, &w, &[point], tolerance)? { + Ok((p, _)) => p, + Err(m) => return Ok(Err(edge_miss(m))), + }; + let [e] = picked[..] else { return Ok(Err(Error::NoMatch { point: 0 })) }; + let Some(law) = law_along(k, &w, e, start, degree, knots, radii)? else { + return Ok(Err(Error::Status(INVALID_INPUT))); + }; + // A law with a corner splits the round's face there (`SplitFilletFacesAtRadiusCorners`, + // fork 6eecf04), which solidcore does not have. + if law_has_corner(degree, knots, radii) { + return Ok(Err(Error::Unsupported)); + } + // The round is the union of its balls (smlib#78, solidcore#2262 with + // `fillet_gn_section_generator`): each ball touches it along the circle shifted + // -r r'/|c'| from its great circle. A law whose balls fold over one another is refused + // (`NoRoomReason::BallsFold`), [`Error::NoRoom`]. + let solid_in = brep_p2::is_manifold_solid(&w)?; + let (r0, r1) = (radii.first().copied().unwrap_or(0.0), radii.last().copied().unwrap_or(0.0)); + Ok(match blend_edges(k, &mut w, &[e], &[r0.max(r1)], Section::Round(Turn::Mitre), Some(law), &[], None)? { + Ok(()) => finish(w, solid_in)?, + Err(Ok(_)) => Err(Error::Unsupported), + Err(Err(e)) => Err(e), + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn laws_are_checked_as_the_capi_checks_them() { + assert!(law_ok(1, &[0.0, 0.0, 1.0, 1.0], &[1.0, 2.0])); + assert!(!law_ok(1, &[0.0, 0.0, 1.0], &[1.0, 2.0])); + assert!(!law_ok(1, &[0.0, 0.5, 1.0, 1.0], &[1.0, 2.0])); + assert!(!law_ok(1, &[0.0, 0.0, 1.0, 1.0], &[-1.0, 2.0])); + assert!(!law_ok(4, &[0.0; 7], &[1.0, 2.0])); + assert!(law_pinches(1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[1.0, 0.0, 1.0])); + assert!(!law_pinches(1, &[0.0, 0.0, 1.0, 1.0], &[0.0, 1.0])); + // A straight law has no corner; a bent one does at its inner knot; a cubic none. + assert!(!law_has_corner(1, &[0.0, 0.0, 1.0, 1.0], &[1.0, 2.0])); + assert!(!law_has_corner(1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[1.0, 1.5, 2.0])); + assert!(law_has_corner(1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[1.0, 2.0, 1.0])); + assert!(!law_has_corner(3, &[0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0], &[1.0, 2.0, 1.0, 2.0, 1.0])); + } + + #[test] + fn picks_follow_the_capis_rule() { + let all = [0.0f64, 1.0, 3.0]; + let d = |x: f64, p: Point3| Ok(Some((x - p.x).abs())); + assert_eq!(pick(&all, &[[0.9, 0.0, 0.0]], 0.5, 1e-6, d).unwrap(), Ok((vec![1.0], vec![0]))); + assert_eq!(pick(&all, &[[2.0, 0.0, 0.0]], 0.5, 1e-6, d).unwrap(), Err(Miss::None(0))); + assert_eq!(pick(&all, &[[1.0, 0.0, 0.0], [0.5, 0.0, 0.0]], 1.0, 1e-6, d).unwrap(), Err(Miss::Ambiguous(1))); + // The same entity twice is picked once, by its first point. + assert_eq!(pick(&all, &[[3.1, 0.0, 0.0], [2.9, 0.0, 0.0]], 0.5, 1e-6, d).unwrap(), Ok((vec![3.0], vec![0]))); + } +} diff --git a/crates/smlib/src/core/blend_tests.rs b/crates/smlib/src/core/blend_tests.rs new file mode 100644 index 000000000..e620c1b3e --- /dev/null +++ b/crates/smlib/src/core/blend_tests.rs @@ -0,0 +1,957 @@ +//! Fillets and chamfers on solidcore, against closed forms: every result exports to a record that +//! validates. +//! +//! The bodies are solidcore's own boxes and cylinders. + +use std::collections::BTreeMap; +use std::f64::consts::PI; +use std::sync::mpsc; +use std::time::Duration; + +use super::blend::{Corners, blend, blend_dropping, blend_holes, chamfer_sides, fillet_variable}; +use super::boolean::boolean; +use super::{Body, counts, make_box, make_cylinder, to_arrays, volume}; +use crate::export::native; +use crate::{Blend, BooleanOp, ChamferSecond, Error, Turn}; + +/// A case longer than this is a hang. +const TIMEOUT: Duration = Duration::from_secs(300); + +/// How near a pick point must be. +const TOL: f64 = 0.01; + +#[derive(Clone, Copy, Debug)] +enum Shape { + Box([f64; 3], [f64; 3]), + Cylinder([f64; 3], f64, f64), + /// A box (corner, size) less a cylinder along z (base centre, radius, height). + Holed([f64; 3], [f64; 3], [f64; 3], f64, f64), +} + +impl Shape { + fn core(self) -> Body { + match self { + Shape::Box(o, s) => make_box(o, s), + Shape::Cylinder(o, r, h) => make_cylinder(o, r, h), + Shape::Holed(o, s, c, r, h) => { + boolean(&make_box(o, s).unwrap(), &make_cylinder(c, r, h).unwrap(), BooleanOp::Subtract).map(|b| b.unwrap()) + } + } + .unwrap() + } +} + +#[derive(Clone, Debug)] +enum Op { + /// `Brep::blend` of one kind, one size for every edge. + Blend(Shape, Blend, Vec<[f64; 3]>, f64), + /// `Brep::chamfer_sides`. + Sides(Shape, Vec<[f64; 3]>, f64, ChamferSecond, [f64; 3]), + /// `Brep::blend_setback` of rounds: edges, radius, corners, setbacks. + Setback(Shape, Vec<[f64; 3]>, f64, Vec<[f64; 3]>, Vec), + /// `Brep::fillet_variable`: edge point, start, degree, knots, radii. + Variable(Shape, [f64; 3], [f64; 3], usize, Vec, Vec), +} + +/// What a case must give. +#[derive(Clone, Debug)] +enum Expect { + /// A body of this volume (relative 1e-9). + Volume(f64), + /// A body of this volume to this relative accuracy. + Near(f64, f64), + /// A body whose volume lies strictly between these. + Between(f64, f64), + /// This error. + Fails(Error), +} + +struct Case { + op: Op, + expect: Expect, +} + +/// A 30 x 20 x 10 block from the origin. +const BLOCK: Shape = Shape::Box([0.0; 3], [30.0, 20.0, 10.0]); +const ABC: f64 = 6000.0; +/// Its top front edge, along x at y = 0, z = 10, 30 long. +const TOP_FRONT: [f64; 3] = [15.0, 0.0, 10.0]; + +/// The cross-section a round of radius r takes from a right-angled edge: (1 - π/4) r². +fn spandrel(r: f64) -> f64 { + (1.0 - PI / 4.0) * r * r +} + +fn case(name: &str) -> Case { + let c = |op, expect| Case { op, expect }; + let r = 2.0; + match name { + // abc - (1 - π/4) r² L. + "fillet_one_edge" => c(Op::Blend(BLOCK, Blend::Round, vec![TOP_FRONT], r), Expect::Volume(ABC - spandrel(r) * 30.0)), + // Every edge rounded at r, the corners spheres: (a-2r)(b-2r)(c-2r) + 2r Σ(faces less + // 2r) + πr² Σ(edges less 2r) + 4/3 πr³. + "fillet_all_edges" => { + let (a, b, h) = (30.0 - 2.0 * r, 20.0 - 2.0 * r, 10.0 - 2.0 * r); + let v = a * b * h + 2.0 * r * (a * b + b * h + h * a) + PI * r * r * (a + b + h) + 4.0 / 3.0 * PI * r * r * r; + let mut edges = Vec::new(); + for (y, z) in [(0.0, 0.0), (20.0, 0.0), (0.0, 10.0), (20.0, 10.0)] { + edges.push([15.0, y, z]); + } + for (x, z) in [(0.0, 0.0), (30.0, 0.0), (0.0, 10.0), (30.0, 10.0)] { + edges.push([x, 10.0, z]); + } + for (x, y) in [(0.0, 0.0), (30.0, 0.0), (0.0, 20.0), (30.0, 20.0)] { + edges.push([x, y, 5.0]); + } + c(Op::Blend(BLOCK, Blend::Round, edges, r), Expect::Volume(v)) + } + // The curvature section's default thumbweight is equal area (fork 6148773): on the + // round's rails it takes off what the ball's circle does, abc - (1 - π/4) r² L. + "fillet_curvature_one_edge" => { + c(Op::Blend(BLOCK, Blend::Curvature, vec![TOP_FRONT], r), Expect::Volume(ABC - (1.0 - PI / 4.0) * r * r * 30.0)) + } + // abc - d² L / 2. + "chamfer_one_edge" => c(Op::Blend(BLOCK, Blend::Chamfer, vec![TOP_FRONT], r), Expect::Volume(ABC - r * r * 30.0 / 2.0)), + // abc - d1 d2 L / 2: 2 back along the top (the face leaning most along +z), 3 down the + // front. + "chamfer_two_distances" => { + c(Op::Sides(BLOCK, vec![TOP_FRONT], 2.0, ChamferSecond::Distance(3.0), [0.0, 0.0, 1.0]), Expect::Volume(ABC - 2.0 * 3.0 * 30.0 / 2.0)) + } + // 2 back along the top, at 30° to it: d tan 30° down the front. + "chamfer_distance_angle" => c( + Op::Sides(BLOCK, vec![TOP_FRONT], 2.0, ChamferSecond::Angle(PI / 6.0), [0.0, 0.0, 1.0]), + Expect::Volume(ABC - 2.0 * 2.0 * (PI / 6.0).tan() * 30.0 / 2.0), + ), + // A 5 mm cylinder 10 high, its top rim rounded at 1. Pappus: the spandrel (1 - π/4) r², + // its centroid (10 - 3π)/(12 - 3π) r in from the rim, swept round the axis. + "fillet_cylinder_rim" => { + let (big, h, r) = (5.0, 10.0, 1.0); + let inset = (10.0 - 3.0 * PI) / (12.0 - 3.0 * PI) * r; + c( + Op::Blend(Shape::Cylinder([0.0; 3], big, h), Blend::Round, vec![[0.0, big, h]], r), + Expect::Volume(PI * big * big * h - 2.0 * PI * (big - inset) * spandrel(r)), + ) + } + // The three edges at the corner (30, 20, 10) rounded at r, the corner set back 4 along + // each. Without a setback the corner is a sphere's octant, and the block keeps + // abc - (1 - π/4) r² Σ(L - r) - (1 - π/6) r³; the setback changes only what lies within + // s + r of the corner, a cube of side s + r. + "setback_corner" => { + let s = 4.0; + let plain = ABC - spandrel(r) * (30.0 + 20.0 + 10.0 - 3.0 * r) - (1.0 - PI / 6.0) * r * r * r; + let near = (s + r) * (s + r) * (s + r); + c( + Op::Setback(BLOCK, vec![[15.0, 20.0, 10.0], [30.0, 10.0, 10.0], [30.0, 20.0, 5.0]], r, vec![[30.0, 20.0, 10.0]], vec![s]), + Expect::Between(plain - near, plain + near), + ) + } + // The top front edge rounded from 1 at x = 0 to 3 at x = 30, linearly, each section + // square to the edge a quarter circle: abc - (1 - π/4) ∫ r(x)² dx + // = abc - (1 - π/4) L (r0² + r0 r1 + r1²) / 3. The round is a B-spline surface fitted to + // those sections, which both kernels build 2.5e-7 short of it (and within 1e-9 of each + // other), within the solver's fitting tolerance. + // The union of the balls, r from 1 to 3 along the 30 mm edge: in each plane across the + // edge, the area between the corner and where each ray from it first enters a ball + // (Gauss-Legendre in the ray's angle, Simpson along the edge, converged to 1e-8 of the + // body), 27.857434; the balls' great circles would take (1 - π/4) L (r0² + r0 r1 + r1²) / 3, + // 27.898239. + "fillet_variable_linear" => { + c(Op::Variable(BLOCK, TOP_FRONT, [0.0, 0.0, 10.0], 1, vec![0.0, 0.0, 1.0, 1.0], vec![1.0, 3.0]), Expect::Near(ABC - 27.857434, 1e-6)) + } + // A round of 12 on a 10 mm cube's top front edge is larger than either face beside it: + // the fork builds it over the cliffs, on the faces' continuations, and cuts away all of + // the cube outside the round's cylinder (axis y = 12, z = -2, radius 12). What stays is + // 10 times the square's part inside that circle, ∫ (√(144 - u²) - 2) du over + // u = y - 12 from -√140 to -2: 72 (asin(√140/12) - asin(1/6)) - 2 (√140 - 2). + "fillet_over_a_cliff" => { + let w = 140f64.sqrt(); + let area = 72.0 * ((w / 12.0).asin() - (1.0f64 / 6.0).asin()) - 2.0 * (w - 2.0); + c(Op::Blend(Shape::Box([0.0; 3], [10.0; 3]), Blend::Round, vec![[5.0, 0.0, 10.0]], 12.0), Expect::Volume(10.0 * area)) + } + // A round of 6 on the top rim of a cylinder of radius 5 is wider than the cylinder. + "fillet_too_large" => { + c(Op::Blend(Shape::Cylinder([0.0; 3], 5.0, 10.0), Blend::Round, vec![[0.0, 5.0, 10.0]], 6.0), Expect::Fails(Error::NoRoom)) + } + "pick_near_nothing" => { + c(Op::Blend(BLOCK, Blend::Round, vec![TOP_FRONT, [100.0, 100.0, 100.0]], r), Expect::Fails(Error::NoMatch { point: 1 })) + } + // A 20 mm cube with a hole of radius 5 along z whose wall touches the face y = 0 along + // x = 10 (#1390): a 3 mm chamfer of the hole's top rim runs out of that face where the + // rim meets it tangentially, a vertex no blend corner handles. The tangent chain the app + // blends is picked: the rim at 135° and 315° round the hole (away from the cylinder's + // seam at 0° and the face at 270°), and the two pieces of the top's front edge, which the + // rim runs on tangentially into at (10, 0, 20). + "chamfer_hole_rim_touching_a_face" => { + let d = 5.0 * std::f64::consts::FRAC_1_SQRT_2; + c( + Op::Blend( + Shape::Holed([0.0; 3], [20.0; 3], [10.0, 5.0, -1.0], 5.0, 22.0), + Blend::Chamfer, + vec![[10.0 - d, 5.0 + d, 20.0], [10.0 + d, 5.0 - d, 20.0], [5.0, 0.0, 20.0], [15.0, 0.0, 20.0]], + 3.0, + ), + Expect::Fails(Error::CornerUnsupported), + ) + } + // √3 from all three edges at the corner (0, 0, 10). + "pick_ambiguous" => c(Op::Blend(BLOCK, Blend::Round, vec![[-1.0, -1.0, 11.0]], r), Expect::Fails(Error::Ambiguous { point: 0 })), + _ => panic!("{name}"), + } +} + +/// The tolerance a case picks with: the ambiguous point lies √3 from its edges. +fn tolerance(name: &str) -> f64 { + if name == "pick_ambiguous" { 5.0 } else { TOL } +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +#[derive(Debug, PartialEq)] +struct Measured { + volume: f64, + counts: [usize; 3], + kinds: BTreeMap, +} + +fn kinds(rec: &solidcore_record::brep::Brep) -> BTreeMap { + let mut out = BTreeMap::new(); + for f in &rec.faces { + let v = serde_json::to_value(&f.surface).unwrap(); + *out.entry(v["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1; + } + out +} + +fn on_core(name: &str, c: &Case) -> crate::Result { + let tol = tolerance(name); + match &c.op { + Op::Blend(s, kind, points, size) => blend(&s.core(), *kind, points, &[*size], tol, &[], &[], Corners::Filled), + Op::Sides(s, points, d, second, first) => chamfer_sides(&s.core(), points, tol, *d, *second, *first), + Op::Setback(s, points, size, corners, setbacks) => { + blend(&s.core(), Blend::Round, points, &vec![*size; points.len()], tol, corners, setbacks, Corners::Filled) + } + Op::Variable(s, point, start, degree, knots, radii) => fillet_variable(&s.core(), *point, tol, *start, *degree, knots, radii), + } +} + +/// Runs `f` on its own thread: a hang fails the test instead of stopping the run. +fn timed(name: &str, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let _ = tx.send(f()); + }); + match rx.recv_timeout(TIMEOUT) { + Ok(v) => v, + Err(mpsc::RecvTimeoutError::Disconnected) => match worker.join() { + Err(p) => std::panic::resume_unwind(p), + Ok(()) => panic!("{name}: no result"), + }, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("{name}: solidcore hung (no result after {TIMEOUT:?})"), + } +} + +type Got = std::result::Result; + +/// `e` without the size solidcore names for a blend too large ([`Error::TooLarge`]): the C++ +/// kernel's [`Error::NoRoom`], which the capi here does not size. +fn without_size(e: Error) -> Error { + if matches!(e, Error::TooLarge { .. }) { Error::NoRoom } else { e } +} + +/// Checks a kernel's result against the case's closed form; what it measured, or its error. +fn judge(name: &str, who: &str, expect: &Expect, got: Got) -> Got { + match (expect, &got) { + (Expect::Fails(e), Err(g)) => assert_eq!(&without_size(g.clone()), e, "{name}: {who} failed otherwise"), + (Expect::Fails(e), Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"), + (_, Err(g)) => panic!("{name}: {who} failed: {g}"), + (Expect::Volume(v), Ok(m)) => assert!(rel(m.volume, *v) < 1e-9, "{name}: {who} volume {} vs analytic {v}", m.volume), + (Expect::Near(v, within), Ok(m)) => assert!(rel(m.volume, *v) < *within, "{name}: {who} volume {} vs analytic {v}", m.volume), + (Expect::Between(lo, hi), Ok(m)) => assert!(*lo < m.volume && m.volume < *hi, "{name}: {who} volume {} not in ({lo}, {hi})", m.volume), + } + got +} + +fn solidcore_case(name: &'static str) -> Got { + timed(name, move || { + let c = case(name); + let got = on_core(name, &c).map(|body| { + let v = volume(&body, 1e-8).unwrap_or_else(|e| panic!("{name}: volume: {e}")); + let n = counts(&body).unwrap(); + let (rec, _) = native(&to_arrays(&body).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + Measured { volume: v, counts: n, kinds: kinds(&rec) } + }); + judge(name, "solidcore", &c.expect, got) + }) +} + +macro_rules! cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +cases!( + fillet_one_edge, + fillet_all_edges, + fillet_curvature_one_edge, + chamfer_one_edge, + chamfer_two_distances, + chamfer_distance_angle, + fillet_cylinder_rim, + setback_corner, + fillet_variable_linear, + fillet_over_a_cliff, + fillet_too_large, + chamfer_hole_rim_touching_a_face, + pick_near_nothing, + pick_ambiguous, +); + +/// What solidcore does not have yet is refused as not supported, after the capi's own checks. +#[test] +fn fork_only_blends_are_not_supported_yet() { + let r = timed("unsupported", || { + let b = BLOCK.core(); + // 1 to 2 and back to 1: a corner at the middle. + let bent = fillet_variable(&b, TOP_FRONT, TOL, [0.0, 0.0, 10.0], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[1.0, 2.0, 1.0]).err(); + // A pick that fails still says so first. + let far = chamfer_sides(&b, &[[100.0; 3]], TOL, 2.0, ChamferSecond::Distance(3.0), [0.0, 0.0, 1.0]).err(); + (bent, far) + }); + assert_eq!(r.0, Some(Error::Unsupported)); + assert_eq!(r.1, Some(Error::NoMatch { point: 0 })); +} + +/// #199's bar, 14 x 6 x 10, its four upright edges rounded: past r 3 (a full round of the 6 mm +/// ends) the two rounds on each end would cross. solidcore refuses it with the largest radius that +/// builds and its edge (`SolidError::FilletRefused`, `fixes.fillet_gn_section_generator`): 3, and a +/// point halfway up an upright edge; an equal chamfer of the 4 mm rib's top edges past 2, as its +/// distance. +#[test] +fn a_blend_too_large_is_refused_with_the_largest_size_that_fits() { + let bar = Shape::Box([14.0, 0.0, 0.0], [14.0, 6.0, 10.0]); + let uprights = [[14.0, 0.0, 5.0], [28.0, 0.0, 5.0], [14.0, 6.0, 5.0], [28.0, 6.0, 5.0]]; + for r in [3.001, 3.5] { + let e = timed("fit_199", move || blend(&bar.core(), Blend::Round, &uprights, &[r], TOL, &[], &[], Corners::Filled).map(|_| ()).unwrap_err()); + let Error::TooLarge { size, kind, at: Some(at), .. } = e else { panic!("{r}: {e:?}") }; + assert!((size - 3.0).abs() < 1e-9 && kind == crate::FitKind::Radius, "{r}: {size} {kind:?}"); + assert!(uprights.iter().any(|p| (0..3).all(|i| (p[i] - at[i]).abs() < 1e-9)), "{r}: {at:?}"); + } + let rib = Shape::Box([0.0; 3], [40.0, 4.0, 20.0]); + let top = [[20.0, 0.0, 20.0], [20.0, 4.0, 20.0]]; + let e = timed("fit_1080", move || blend(&rib.core(), Blend::Chamfer, &top, &[3.0], TOL, &[], &[], Corners::Filled).map(|_| ()).unwrap_err()); + let Error::TooLarge { size, kind, at: Some(_), .. } = e else { panic!("{e:?}") }; + assert!((size - 2.0).abs() < 1e-12 && kind == crate::FitKind::Distance, "{size} {kind:?}"); +} + +/// A cliff overflow the fork refuses too (`fixes.fillet_cliff_overflow`, solidcore#960): the +/// three edges at a 20 mm cube's corner rounded r20, their fillet's boundary on two faces' +/// surfaces, has no room, as on the fork, not "not supported": too large, the largest radius that +/// builds 19.99 (the whole edge less solidcore's fit margin), which builds. +#[test] +fn a_cliff_overflow_the_fork_refuses_has_no_room() { + let corner = [[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]; + let r = timed("cliff_refused", move || { + blend(&Shape::Box([0.0; 3], [20.0; 3]).core(), Blend::Round, &corner, &[20.0; 3], TOL, &[], &[], Corners::Filled).map(|_| ()).unwrap_err() + }); + let Error::TooLarge { size, kind: crate::FitKind::Radius, at: Some(_), .. } = r else { panic!("{r:?}") }; + assert!((size - 19.99).abs() < 1e-9, "{size}"); + timed("cliff_fit", move || { + blend(&Shape::Box([0.0; 3], [20.0; 3]).core(), Blend::Round, &corner, &[size; 3], TOL, &[], &[], Corners::Filled).unwrap() + }); +} + +/// The capi's `overflow_goes_first` (fork 241f7ba): R21 on a 20 cube's edge takes all of both faces +/// that edge lies on, and rounds with it on other edges go after it. With R5 on the corner's other +/// two edges those edges are gone (the two R5 points flagged) and the result is the R21's alone, +/// 20 (F(w) - F(1) - (w - 1)) with F the integral of sqrt(441 - u²) and w = sqrt(440). With R5 on +/// the back upright that upright's round runs above the R21 cylinder, taking the corner's piece +/// over it too (Simpson on 4000 spans, against a bound of its quartic end edge's tolerance). +#[test] +fn overflow_goes_first() { + let f = |u: f64| 0.5 * (u * (441.0 - u * u).sqrt() + 441.0 * (u / 21.0).asin()); + let w = 440f64.sqrt(); + let alone = 20.0 * (f(w) - f(1.0) - (w - 1.0)); + let strip = |t: f64| { + let y = 15.0 + 5.0 * t.sin(); + let zc = 21.0 - (441.0 - (y - 21.0) * (y - 21.0)).sqrt(); + 5.0 * (1.0 - t.cos()) * (20.0 - zc) * 5.0 * t.cos() + }; + let (n, h) = (4000, 0.5 * PI / 4000.0); + let mut sum = strip(0.0) + strip(0.5 * PI); + for i in 1..n { + sum += f64::from(if i % 2 == 1 { 4 } else { 2 }) * strip(f64::from(i) * h); + } + let corner = sum * h / 3.0; + assert!((corner - 106.612_300_588).abs() < 1e-6, "{corner}"); + let cases: [(&[[f64; 3]], &[f64], &[bool], f64, f64); 2] = [ + (&[[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]], &[21.0, 5.0, 5.0], &[false, true, true], alone, 1e-9 * alone), + (&[[10.0, 0.0, 0.0], [0.0, 20.0, 10.0]], &[21.0, 5.0], &[false, false], alone - corner, 0.02), + ]; + for (points, sizes, dropped, want, bound) in cases { + let got = timed("overflow_first", move || { + let (b, d) = blend_dropping(&Shape::Box([0.0; 3], [20.0; 3]).core(), Blend::Round, Turn::Mitre, points, sizes, 1.0).unwrap(); + native(&to_arrays(&b).unwrap()).unwrap(); + (volume(&b, 1e-8).unwrap(), d) + }); + println!("overflow first {sizes:?}: {:.9}, expected {want:.9}", got.0); + assert_eq!(got.1, dropped, "{sizes:?}"); + assert!((got.0 - want).abs() <= bound, "{sizes:?}: {} vs {want}", got.0); + } +} + +/// The capi's `rounds_at_a_concave_face_corner_are_mitred` (`fixes.fillet_mitre_concave_face_corners`, +/// fork 4f06e72): each edge loses (convex) or gains (concave) the spandrel r²(1 - π/4) along its +/// length, and in the quadrant beyond both walls the mitred rounds take or add r³(5/3 - π/2): a +/// 60 x 40 x 10 plate's 30 x 20 x 5 pocket rim at r2 (15 faces) and r5 (11), a 60 x 60 x 5 plate's +/// 20 x 20 x 15 boss root at r4 (15). And the pocket rim chamfered 5.5, past the pocket's depth: +/// 21000 - (50 d² + 4/3 d³). +#[test] +fn rounds_at_a_concave_face_corner_are_mitred() { + let made = |a: Body, b: Body, op| boolean(&a, &b, op).unwrap().unwrap(); + let pocket = + || made(make_box([0.0; 3], [60.0, 40.0, 10.0]).unwrap(), make_box([15.0, 10.0, 5.0], [30.0, 20.0, 6.0]).unwrap(), BooleanOp::Subtract); + let boss = || made(make_box([0.0; 3], [60.0, 60.0, 5.0]).unwrap(), make_box([20.0, 20.0, 5.0], [20.0, 20.0, 15.0]).unwrap(), BooleanOp::Union); + let rim = [[30.0, 10.0, 10.0], [30.0, 30.0, 10.0], [15.0, 20.0, 10.0], [45.0, 20.0, 10.0]]; + let root = [[30.0, 20.0, 5.0], [40.0, 30.0, 5.0], [30.0, 40.0, 5.0], [20.0, 30.0, 5.0]]; + let want = |v0: f64, length: f64, r: f64, sign: f64| v0 + sign * (length * r * r * (1.0 - PI / 4.0) + 4.0 * r * r * r * (5.0 / 3.0 - PI / 2.0)); + for (body, edges, r, v, faces) in [ + (pocket(), rim, 2.0, want(21000.0, 100.0, 2.0, -1.0), 15), + (pocket(), rim, 5.0, want(21000.0, 100.0, 5.0, -1.0), 11), + (boss(), root, 4.0, want(24000.0, 80.0, 4.0, 1.0), 15), + ] { + let b = blend(&body, Blend::Round, &edges, &[r], 0.1, &[], &[], Corners::Filled).unwrap(); + native(&to_arrays(&b).unwrap()).unwrap(); + let got = volume(&b, 1e-12).unwrap(); + println!("mitred r{r}: {} faces, {got:.9}, expected {v:.9}", counts(&b).unwrap()[0]); + assert_eq!(counts(&b).unwrap()[0], faces, "r{r}"); + assert!(rel(got, v) < 2e-8, "r{r}: {got} vs {v}"); + } + // Through the flat arrays, as bodies reach a blend in the app (pocket_chamfer_on_a_boolean_body). + let d = 5.5; + let flat = super::from_arrays(&to_arrays(&pocket()).unwrap()).unwrap(); + let b = blend(&flat, Blend::Chamfer, &rim, &[d], 0.1, &[], &[], Corners::Filled).unwrap(); + let (got, v) = (volume(&b, 1e-8).unwrap(), 21000.0 - (50.0 * d * d + 4.0 / 3.0 * d * d * d)); + println!("mitred chamfer {d}: {got:.9}, expected {v:.9}"); + assert!(rel(got, v) < 1e-8, "{got} vs {v}"); +} + +/// A 40 x 30 x 10 plate with a 10 x 10 x 5 boss on it (x 15..25, y 10..20), the boss's four base +/// edges rounded at r 1: at each upright boss edge two concave rounds turn round the sharp convex +/// edge. Each base edge gains the spandrel A = (1 - π/4) r² along its 10, and each corner the +/// rounds' part beyond both walls, whose section's first moment about the upright edge is +/// M = (5/6 - π/4) r³: mitred, 8 M in all; swept, the section revolved a quarter turn at each, +/// 2π M, the corner a horn torus of radii r, r. Swept with unequal radii, or along a pocket's floor +/// (its upright edges sharp and concave), is refused with solidcore's reason. +#[test] +fn rounds_turning_round_a_boss_edge_mitred_or_swept() { + let made = |a: Body, b: Body, op| boolean(&a, &b, op).unwrap().unwrap(); + let boss = + move || made(make_box([0.0; 3], [40.0, 30.0, 10.0]).unwrap(), make_box([15.0, 10.0, 10.0], [10.0, 10.0, 5.0]).unwrap(), BooleanOp::Union); + let pocket = + move || made(make_box([0.0; 3], [40.0, 30.0, 10.0]).unwrap(), make_box([10.0, 10.0, 5.0], [20.0, 10.0, 6.0]).unwrap(), BooleanOp::Subtract); + const BASE: [[f64; 3]; 4] = [[20.0, 10.0, 10.0], [25.0, 15.0, 10.0], [20.0, 20.0, 10.0], [15.0, 15.0, 10.0]]; + const RIM: [[f64; 3]; 4] = [[20.0, 10.0, 5.0], [30.0, 15.0, 5.0], [20.0, 20.0, 5.0], [10.0, 15.0, 5.0]]; + let r = 1.0; + let rounded = + move |body: Body, at: [[f64; 3]; 4], turn, sizes: [f64; 4]| blend_dropping(&body, Blend::Round, turn, &at, &sizes, 0.1).map(|(b, _)| b); + // solidcore's tori, and the record's kinds of surface: its torus is a ring torus, so a horn + // torus's face there is its exact rational form. + let measured = |b: &Body| { + use solidcore::surface::surface::p2::SurfaceKind; + let (rec, _) = native(&to_arrays(b).unwrap()).unwrap(); + rec.validate().unwrap(); + let mut tori = Vec::new(); + { + let g = b.0.lock().unwrap(); + for f in solidcore::query::api_queries::get_faces(&g).unwrap() { + if let Some(s) = solidcore::topology::face::p2::surface(&g, f).unwrap() + && let SurfaceKind::Torus(t) = s.kind() + { + tori.push((t.major_radius(), t.minor_radius())); + } + } + } + (volume(b, 1e-10).unwrap(), counts(b).unwrap()[0], tori, kinds(&rec)) + }; + let (mitre, swept) = + timed("turn", move || (rounded(boss(), BASE, Turn::Mitre, [r; 4]).unwrap(), rounded(boss(), BASE, Turn::Swept, [r; 4]).unwrap())); + let (vm, fm, tm, km) = measured(&mitre); + let (vs, fs, ts, ks) = measured(&swept); + println!("mitre: {vm:.9}, {fm} faces {km:?}; swept: {vs:.9}, {fs} faces {ks:?}, tori {ts:?}"); + let (a, m) = (spandrel(r), (5.0 / 6.0 - PI / 4.0) * r * r * r); + let base = 12500.0 + 40.0 * a; + assert!(rel(vm, base + 8.0 * m) < 1e-9, "mitre {vm} vs {}", base + 8.0 * m); + assert!(rel(vs, base + 2.0 * PI * m) < 1e-9, "swept {vs} vs {}", base + 2.0 * PI * m); + assert_eq!((fm, tm.len(), km.get("rational_spline")), (15, 0, None)); + assert_eq!((fs, ts.len(), ks.get("rational_spline")), (19, 4, Some(&4))); + assert!(ts.iter().all(|(major, minor)| (major - r).abs() < 1e-12 && (minor - r).abs() < 1e-12), "{ts:?}"); + // Swept is for rounds only. + assert_eq!(blend_dropping(&boss(), Blend::Chamfer, Turn::Swept, &BASE, &[r; 4], 0.1).err(), Some(Error::Argument)); + let unequal = timed("turn unequal", move || rounded(boss(), BASE, Turn::Swept, [1.0, 1.5, 1.0, 1.5]).err()); + let rim = timed("turn rim", move || rounded(pocket(), RIM, Turn::Swept, [r; 4]).err()); + println!("unequal: {unequal:?}\nrim: {rim:?}"); + assert!( + matches!(&unequal, Some(Error::TurnRefused { room: false, why, at: Some(_) }) if why.starts_with("a swept turn is built between constant rounds of one radius")), + "{unequal:?}" + ); + assert!( + matches!(&rim, Some(Error::TurnRefused { room: true, why, at: Some(_) }) if why.contains("round that edge at a radius of at least 1 first")), + "{rim:?}" + ); +} + +/// Solidcore alone: edge attributes across a cliff overflow. A 40 x 30 x 10 block notched below its +/// top at (40, 0), its front and right top edges rounded r8 (their rails run off over the notch). +/// The back and left top edges are each trimmed 8 by those rounds: (0, 30)-(32, 30) and (0, 8)-(0, 30) +/// at z = 10, and each piece keeps its edge's attribute (`Behavior::Copy`), as on the fork. +#[test] +fn an_edge_tag_crosses_a_cliff_overflow() { + use solidcore::blend::fillet_executive::session::FilletSession; + use solidcore::boolean::api_brep::boolean_difference; + use solidcore::geom::attribute::{Attribute, Behavior}; + use solidcore::primitive::api_primitives::create_box; + use solidcore::topology::{Brep, EdgeId, edge, vertex}; + use solidcore::{EntityRef, Kernel, Point3}; + fn between(b: &Brep, a: Point3, q: Point3) -> Option { + b.edges().ids().find(|&e| { + let (s, t) = edge::start_end_vertices(b, e).unwrap(); + let (s, t) = (vertex::point(b, s.unwrap()).unwrap(), vertex::point(b, t.unwrap()).unwrap()); + (s.distance(a) < 1e-6 && t.distance(q) < 1e-6) || (s.distance(q) < 1e-6 && t.distance(a) < 1e-6) + }) + } + let p = Point3::new; + let mut k = Kernel::default(); + k.fixes.fillet_refuse_rails_leaving_faces = true; + k.fixes.fillet_trace_reaches_rails = true; + k.fixes.fillet_rail_end_on_continued_surface = true; + k.fixes.fillet_cliff_overflow = true; + let block = create_box(&mut k, Point3::ZERO, 40.0, 30.0, 10.0).unwrap(); + let notch = create_box(&mut k, p(35.0, -1.0, -1.0), 6.0, 6.0, 4.0).unwrap(); + let mut b = boolean_difference(&mut k, block, notch).unwrap(); + const ID: u64 = 0x7000_0001; + let edge_at = |b: &Brep, a, q| between(b, a, q).unwrap(); + for (a, q, v) in [(p(0.0, 30.0, 10.0), p(40.0, 30.0, 10.0), 1), (p(0.0, 0.0, 10.0), p(0.0, 30.0, 10.0), 2)] { + let e = edge_at(&b, a, q); + b.add_attribute(EntityRef::Edge(e), Attribute::long(ID, v, Behavior::Copy)).unwrap(); + } + let rounds = [edge_at(&b, p(0.0, 0.0, 10.0), p(40.0, 0.0, 10.0)), edge_at(&b, p(40.0, 0.0, 10.0), p(40.0, 30.0, 10.0))]; + let mut s = FilletSession::new(&mut k, &mut b).unwrap(); + s.prepare_constant_radius_edges(&mut k, &rounds, 8.0, 1, 1, 1.0).unwrap(); + s.do_fillet(&mut k).unwrap(); + drop(s); + b.refresh_cached_topology(); + for (a, q, which) in [(p(0.0, 30.0, 10.0), p(32.0, 30.0, 10.0), "back"), (p(0.0, 8.0, 10.0), p(0.0, 30.0, 10.0), "left")] { + let e = edge_at(&b, a, q); + assert!(b.entity_attributes(EntityRef::Edge(e)).iter().any(|(_, x)| x.attribute_id() == ID), "the {which} edge lost its attribute"); + } +} + +/// Solidcore alone: the pocket rim chamfered 5.5, as `fillet_mitre_concave_face_corners`' own test +/// does it, with `keep_operand_uv_trims` on too, on the body the boolean gives: +/// 21000 - (50 d² + 4/3 d³) = 19265.666666667 (the fork, and the same body through the flat +/// arrays). Without `fillet_run_on_bspline_trims` it is refused: error 3, Corner Edge Computation +/// Failure (solidcore#1981). +#[test] +fn pocket_chamfer_on_a_boolean_body() { + use solidcore::blend::fillet_executive::session::FilletSession; + use solidcore::boolean::api_brep::boolean_difference; + use solidcore::primitive::api_primitives::create_box; + use solidcore::topology::{EdgeId, edge, vertex}; + use solidcore::{Kernel, Point3}; + let p = Point3::new; + let mut k = Kernel::default(); + k.fixes.fillet_refuse_rails_leaving_faces = true; + k.fixes.fillet_trace_reaches_rails = true; + k.fixes.fillet_rail_end_on_continued_surface = true; + k.fixes.fillet_cliff_overflow = true; + k.fixes.fillet_mitre_concave_face_corners = true; + k.fixes.keep_operand_uv_trims = true; + k.fixes.fillet_run_on_bspline_trims = true; + let plate = create_box(&mut k, Point3::ZERO, 60.0, 40.0, 10.0).unwrap(); + let cut = create_box(&mut k, p(15.0, 10.0, 5.0), 30.0, 20.0, 6.0).unwrap(); + let mut b = boolean_difference(&mut k, plate, cut).unwrap(); + let c = [p(15.0, 10.0, 10.0), p(45.0, 10.0, 10.0), p(45.0, 30.0, 10.0), p(15.0, 30.0, 10.0)]; + let on = |x: Point3, a: Point3, q: Point3| x.distance(a) < 1e-9 || x.distance(q) < 1e-9; + let ids: Vec = (0..4) + .map(|i| { + let (a, q) = (c[i], c[(i + 1) % 4]); + b.edges() + .ids() + .find(|&e| { + let (s, t) = edge::start_end_vertices(&b, e).unwrap(); + on(vertex::point(&b, s.unwrap()).unwrap(), a, q) && on(vertex::point(&b, t.unwrap()).unwrap(), a, q) && s != t + }) + .unwrap() + }) + .collect(); + let mut s = FilletSession::new(&mut k, &mut b).unwrap(); + s.prepare_constant_radius_edges(&mut k, &ids, 5.5, 0, 1, 1.0).unwrap(); + let r = s.do_fillet(&mut k); + assert!(r.is_ok(), "{} {}", s.error_info().code, s.error_info().comment); + drop(s); + b.refresh_cached_topology(); + let v = volume(&Body::new(b), 1e-8).unwrap(); + let d: f64 = 5.5; + assert!(rel(v, 21000.0 - (50.0 * d * d + 4.0 / 3.0 * d * d * d)) < 1e-8, "{v}"); +} + +/// The corner of r5 rounds at (60, 40, 20) on a 60 x 40 x 20 box, set back 8 and left open: the +/// box's six faces and the three rounds (9 faces, 30 edges, 22 vertices), a sheet, and one hole +/// of twelve edges (each section and face curve in two), chained end to start, each beside a face +/// of the sheet. +#[test] +fn a_setback_corner_left_open_returns_its_hole() { + let edges = [[30.0, 40.0, 20.0], [60.0, 20.0, 20.0], [60.0, 40.0, 10.0]]; + let (open, holes) = timed("setback_open", move || { + let b = Shape::Box([0.0; 3], [60.0, 40.0, 20.0]).core(); + blend_holes(&b, Blend::Round, &edges, &[5.0; 3], 0.1, &[[60.0, 40.0, 20.0]], &[8.0], Corners::Open).unwrap() + }); + assert_eq!(counts(&open).unwrap(), [9, 30, 22]); + assert!(!super::is_manifold_solid(&open).unwrap()); + let [hole] = holes.as_slice() else { panic!("one corner: {holes:?}") }; + assert_eq!(hole.edges.len(), 12); + let flat = to_arrays(&open).unwrap(); + let (rec, _) = native(&flat).unwrap(); + solidcraft_geom::brep::check::validate(&rec).unwrap(); + let ends = &flat.ints[&crate::flat::EDGE_VERTICES]; + let end = |h: &crate::HoleEdge, last: bool| ends[2 * h.edge + usize::from(h.forward == last)]; + for (k, h) in hole.edges.iter().enumerate() { + let next = &hole.edges[(k + 1) % 12]; + assert_eq!(end(h, true), end(next, false), "edge {k} ends where the next starts"); + assert!(h.face < 9); + } + // A corner where an edge is not rounded builds no setback, and the refusal names it. + let refused = timed("setback_open_refused", move || { + let b = Shape::Box([0.0; 3], [60.0, 40.0, 20.0]).core(); + blend_holes(&b, Blend::Round, &edges[..2], &[5.0; 2], 0.1, &[[60.0, 40.0, 20.0]], &[8.0], Corners::Open).err() + }); + assert_eq!(refused, Some(Error::CornerRefused { corner: 0 })); +} + +/// A curvature-continuous round at the equal-area thumbweight takes off what the ball's circle +/// does, r² (cot(α/2) - (π - α)/2) per unit length on a wedge α (solidcore#2261): on a 40 x 30 x 20 +/// box with its top back edge chamfered 5, r 2 along the chamfer's top edge (α 135°) takes +/// 0.0860579227 per mm, along the bottom front edge (α 90°) 0.8584073464. Both in one call are +/// refused: every edge takes the first one's thumbweight, so the other would take 17% too little +/// or 21% too much (solidcore#2250's comment 6563419897), whichever order they come in. +#[test] +fn a_curvature_round_takes_its_wedges_equal_area_and_mixed_wedges_are_refused() { + let r = 2.0; + let cut = |alpha: f64| r * r * (1.0 / (alpha / 2.0).tan() - (PI - alpha) / 2.0); + let chamfered = + blend(&Shape::Box([0.0; 3], [40.0, 30.0, 20.0]).core(), Blend::Chamfer, &[[20.0, 30.0, 20.0]], &[5.0], TOL, &[], &[], Corners::Filled) + .unwrap(); + let v0 = volume(&chamfered, 1e-8).unwrap(); + assert!(rel(v0, 23500.0) < 1e-9, "{v0}"); + let (a, b) = ([20.0, 25.0, 20.0], [20.0, 0.0, 0.0]); + for (at, alpha) in [(a, 0.75 * PI), (b, 0.5 * PI)] { + let round = blend(&chamfered, Blend::Curvature, &[at], &[r], TOL, &[], &[], Corners::Filled).unwrap(); + let (rec, _) = native(&to_arrays(&round).unwrap()).unwrap(); + solidcraft_geom::brep::check::validate(&rec).unwrap(); + let removed = v0 - volume(&round, 1e-8).unwrap(); + assert!(rel(removed, 40.0 * cut(alpha)) < 1e-6, "{removed} vs {}", 40.0 * cut(alpha)); + } + for both in [[a, b], [b, a]] { + let refused = blend(&chamfered, Blend::Curvature, &both, &[r], TOL, &[], &[], Corners::Filled).err(); + assert_eq!(refused, Some(Error::Unported(super::blend::CURVATURE_MIXED_WEDGES))); + assert!(refused.is_some_and(|e| e.to_string().contains("issuecomment-6563419897"))); + } + // Edges of one wedge go together. + let two = blend(&chamfered, Blend::Curvature, &[b, [20.0, 0.0, 20.0]], &[r], TOL, &[], &[], Corners::Filled).unwrap(); + assert!(rel(v0 - volume(&two, 1e-8).unwrap(), 80.0 * cut(0.5 * PI)) < 1e-6); + // A pick that misses is still named first. + assert_eq!(blend(&chamfered, Blend::Curvature, &[[90.0; 3]], &[r], TOL, &[], &[], Corners::Filled).err(), Some(Error::NoMatch { point: 0 })); +} + +/// A variable round is the union of its balls (solidcore#2262, `fillet_gn_section_generator`). +/// Along the 30 mm top front edge: a law of one radius 2 takes the constant round's +/// (1 - π/4) 4 · 30 = 25.752220; 1 to 3, the balls' union's 27.857434 (the great circles would take +/// 27.898239), either way along the edge. Both come out 5.3e-5 of that over, as on the C++ +/// kernel: the solver's surface fit. A law whose radius climbs faster than a rolling ball can +/// follow (1 to 4 within a mm) folds its balls over one another: refused, not built. +#[test] +fn a_variable_round_is_the_union_of_its_balls() { + let b = BLOCK.core(); + let removed = |radii: &[f64], start: [f64; 3]| { + let r = fillet_variable(&b, TOP_FRONT, TOL, start, 1, &[0.0, 0.0, 1.0, 1.0], radii).unwrap(); + let (rec, _) = native(&to_arrays(&r).unwrap()).unwrap(); + solidcraft_geom::brep::check::validate(&rec).unwrap(); + ABC - volume(&r, 1e-8).unwrap() + }; + let constant = removed(&[2.0, 2.0], [0.0, 0.0, 10.0]); + assert!(rel(constant, (1.0 - PI / 4.0) * 4.0 * 30.0) < 1e-4, "{constant}"); + let linear = removed(&[1.0, 3.0], [0.0, 0.0, 10.0]); + assert!(rel(linear, 27.857434) < 1e-4, "{linear}"); + assert!(rel(removed(&[1.0, 3.0], [30.0, 0.0, 10.0]), linear) < 1e-8); + let steep = [0.0, 0.0, 0.0, 0.0, 0.02, 0.04, 1.0, 1.0, 1.0, 1.0]; + let folds = fillet_variable(&b, TOP_FRONT, TOL, [0.0, 0.0, 10.0], 3, &steep, &[1.0, 1.0, 4.0, 4.0, 4.0, 4.0]).err(); + assert_eq!(folds, Some(Error::NoRoom)); + // A pick that misses is still named first. + assert_eq!(fillet_variable(&b, [90.0; 3], TOL, [0.0; 3], 1, &[0.0, 0.0, 1.0, 1.0], &[1.0, 3.0]).err(), Some(Error::NoMatch { point: 0 })); +} + +/// The capi's argument checks, before any kernel call. +#[test] +fn hostile_arguments_are_refused() { + let b = BLOCK.core(); + let none = Corners::Filled; + assert_eq!(blend(&b, Blend::Round, &[], &[1.0], TOL, &[], &[], none).err(), Some(Error::Argument)); + assert_eq!(blend(&b, Blend::Round, &[[f64::NAN; 3]], &[1.0], TOL, &[], &[], none).err(), Some(Error::Argument)); + assert_eq!(blend(&b, Blend::Round, &[TOP_FRONT], &[-1.0], TOL, &[], &[], none).err(), Some(Error::Argument)); + assert_eq!(blend(&b, Blend::Round, &[TOP_FRONT], &[1.0], 0.0, &[], &[], none).err(), Some(Error::Argument)); + assert_eq!(blend(&b, Blend::Round, &[TOP_FRONT], &[f64::INFINITY], TOL, &[], &[], none).err(), Some(Error::Argument)); + // A chamfer's corners are bevelled, which builds no setback. + assert_eq!(blend(&b, Blend::Chamfer, &[TOP_FRONT], &[1.0], TOL, &[[0.0, 0.0, 10.0]], &[1.0], none).err(), Some(Error::Unsupported)); + assert_eq!(fillet_variable(&b, TOP_FRONT, TOL, [0.0; 3], 1, &[0.0, 1.0], &[1.0, 2.0]).err(), Some(Error::Argument)); + // A radius that pinches to nothing inside the edge. + assert_eq!(fillet_variable(&b, TOP_FRONT, TOL, [0.0; 3], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[1.0, 0.0, 1.0]).err(), Some(Error::Unsupported)); + assert_eq!(chamfer_sides(&b, &[TOP_FRONT], TOL, 1.0, ChamferSecond::Angle(4.0), [0.0, 0.0, 1.0]).err(), Some(Error::Argument)); + assert_eq!(chamfer_sides(&b, &[TOP_FRONT], TOL, 1.0, ChamferSecond::Distance(1.0), [0.0; 3]).err(), Some(Error::Argument)); +} + +/// A setback longer than an edge at its corner leaves no room, before any blend is made. +#[test] +fn a_setback_past_an_edge_has_no_room() { + let r = timed("setback_long", || { + let b = BLOCK.core(); + let corner = [[15.0, 20.0, 10.0], [30.0, 10.0, 10.0], [30.0, 20.0, 5.0]]; + blend(&b, Blend::Round, &corner, &[2.0; 3], TOL, &[[30.0, 20.0, 10.0]], &[10.0], Corners::Filled).err() + }); + assert_eq!(r, Some(Error::NoRoom)); +} + +/// The body blended is never changed. +#[test] +fn the_body_stays_as_it_was() { + let r = timed("operand", || { + let b = BLOCK.core(); + let _ = blend(&b, Blend::Round, &[TOP_FRONT], &[2.0], TOL, &[], &[], Corners::Filled); + (counts(&b).unwrap(), volume(&b, 1e-8).unwrap()) + }); + assert_eq!(r.0, [6, 12, 8]); + assert!(rel(r.1, ABC) < 1e-12, "{}", r.1); +} + +/// The chamfer's first distance goes on the face leaning most along `first`: 2 along the top and +/// 3 down the front for +z, the other way round for -y. The volumes are the same; the centroid +/// tells them apart. The removed prism's section is the triangle with legs t (back along the +/// top, in y) and f (down the front, in z) at the edge (y = 0, z = 10), centroid +/// (t/3, 10 - f/3), area t f / 2: the block keeps ȳ = (6000·10 - 15 t f · t/3) / (6000 - 15 t f) +/// and z̄ = (6000·5 - 15 t f (10 - f/3)) / (6000 - 15 t f). +#[test] +fn the_first_distance_goes_on_the_face_along_first() { + for (first, top, front) in [([0.0, 0.0, 1.0], 2.0, 3.0), ([0.0, -1.0, 0.0], 3.0, 2.0)] { + let r = timed("sides_first", move || { + let b = BLOCK.core(); + chamfer_sides(&b, &[TOP_FRONT], TOL, 2.0, ChamferSecond::Distance(3.0), first).and_then(|c| super::mass_properties(&c, 1e-8)) + }); + let m = r.unwrap_or_else(|e| panic!("{first:?}: {e}")); + let cut = 15.0 * top * front; + let y = (6000.0 * 10.0 - cut * top / 3.0) / (6000.0 - cut); + let z = (6000.0 * 5.0 - cut * (10.0 - front / 3.0)) / (6000.0 - cut); + assert!(rel(m.volume, 6000.0 - cut) < 1e-9, "{first:?}: volume {}", m.volume); + assert!((m.centroid[1] - y).abs() < 1e-7 && (m.centroid[2] - z).abs() < 1e-7, "{first:?}: centroid {:?} vs ({y}, {z})", m.centroid); + } +} + +/// The capi's `knife_edge_chamfers` (fork e96898d): a 10 high extrusion of the profile whose arc +/// of radius R = 21 runs out tangent into its top line at the tip x = 62 1/6 (a knife edge, a +/// cusp), chamfered d at the tip. No ball lies d back along both faces there; the chamfer is the +/// chord between the contacts of the ball of radius d, sqrt(4 R d) back on the flat face and where +/// the line from the arc's axis to the ball's centre meets the wall. It takes the triangle flat +/// contact, tip, wall contact less the wall's circular segment R²/2 (b - sin b), +/// b = acos((R - d)/(R + d)): at d = 2 the chord is 3.822 wide and takes 159.23645 (each to +/// 1e-12). Mirrored in x too. +#[test] +fn knife_edge_chamfers() { + use super::sweep::extrude; + use super::transform::transform; + use crate::sweeps::{Curve, DraftCorner}; + + const R: f64 = 21.0; + const TIP: f64 = 62.0 + 1.0 / 6.0; + const H: f64 = 10.0; + let line = |a: [f64; 2], b: [f64; 2]| Curve::Line { start: [a[0], a[1], 0.0], end: [b[0], b[1], 0.0] }; + let profile = [ + line([0.0, 0.0], [0.0, -R]), + line([0.0, -R], [TIP - R, -R]), + Curve::Arc { center: [TIP, -R, 0.0], axis: [0.0, 0.0, -1.0], reference: [1.0, 0.0, 0.0], radius: R, start: PI, end: 1.5 * PI }, + line([TIP, 0.0], [0.0, 0.0]), + ]; + let part = extrude(&profile, [0.0, 0.0, 1.0], H, 0.0, DraftCorner::Curvature, true).unwrap(); + let before = (TIP - R) * R * H + R * R * (1.0 - PI / 4.0) * H; + assert!((volume(&part, 1e-8).unwrap() - before).abs() < 1e-9 * before); + for d in [1.0, 2.0, 5.0] { + let flat = TIP - (4.0 * R * d).sqrt(); + let (wx, wy) = (TIP - (4.0 * R * d).sqrt() * R / (R + d), -R + (R - d) * R / (R + d)); + let triangle = 0.5 * ((TIP - flat) * wy).abs(); + let b = ((R - d) / (R + d)).acos(); + let removed = (triangle - 0.5 * R * R * (b - b.sin())) * H; + if d == 2.0 { + assert!((removed - 159.236_450_742_901_18).abs() < 1e-12 * 159.24); + assert!(((wx - flat).hypot(wy) - 3.822_132_343_623_634_7).abs() < 1e-12 * 3.83); + } + for mirrored in [false, true] { + let sx = if mirrored { -1.0 } else { 1.0 }; + let m = [[sx, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let body = transform(&part, &m).unwrap(); + let tip = [sx * TIP, 0.0, H / 2.0]; + let cut = blend(&body, Blend::Chamfer, &[tip], &[d], TOL, &[], &[], Corners::Filled).unwrap(); + let v = volume(&cut, 1e-8).unwrap(); + let want = before - removed; + assert!((v - want).abs() < 1e-9 * want, "d {d} mirrored {mirrored}: {v} vs {want}"); + native(&to_arrays(&cut).unwrap()).unwrap(); + } + } +} + +/// The part from SolidCraft #871: a plate with a narrower block on top and a window through both. +fn part_871() -> Body { + let (a, b) = (12.74437365538526, 22.69275963366936); + let at = |lo: [f64; 3], hi: [f64; 3]| make_box(lo, [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]).unwrap(); + let joined = boolean(&at([9.5, 8.0, 0.0], [23.5, 29.5, 10.0]), &at([9.5, a, 10.0], [23.5, b, 20.0]), BooleanOp::Union).unwrap().unwrap(); + boolean(&joined, &at([9.5, 14.0, 7.0], [23.5, 19.2, 14.1]), BooleanOp::Subtract).unwrap().unwrap() +} + +/// The 12 edges round each of the part's two end faces. +fn edges_871() -> Vec<[f64; 3]> { + let yz = [ + (12.74437365538526, 15.0), + (10.37218682769263, 10.0), + (8.0, 5.0), + (18.75, 0.0), + (29.5, 5.0), + (26.09637981683468, 10.0), + (22.69275963366936, 15.0), + (17.71856664452731, 20.0), + (16.6, 7.0), + (14.0, 10.55), + (16.6, 14.100000000000001), + (19.200000000000003, 10.55), + ]; + [23.5, 9.5].iter().flat_map(|x| yz.iter().map(move |(y, z)| [*x, *y, *z])).collect() +} + +/// #871's rounds at r 0.5 fit (the wall between the window and the block's side is 1.26 thick): +/// 38 faces, and the closed form `issue_871_tests::rounds_that_fit_are_closed` derives. At r 1 they +/// overlap, which is refused. +#[test] +fn rounds_on_the_871_part() { + let p = part_871(); + let e = edges_871(); + let sizes = |r: f64| vec![r; e.len()]; + let part_volume = 14.0 * (21.5 * 10.0 + (22.69275963366936 - 12.74437365538526) * 10.0 - 5.2 * 7.1); + let exact = part_volume - 2.0 * (2.0 * (21.5 + 20.0) + 2.0 * (5.2 + 7.1)) * spandrel(0.5); + let fit = blend(&p, Blend::Round, &e, &sizes(0.5), TOL, &[], &[], Corners::Filled).unwrap(); + let (v, n) = (volume(&fit, 1e-8).unwrap(), counts(&fit).unwrap()); + let refused = blend(&p, Blend::Round, &e, &sizes(1.0), TOL, &[], &[], Corners::Filled).map(|_| ()).unwrap_err(); + assert_eq!(without_size(refused), Error::NoRoom); + assert_eq!(n[0], 38); + assert!((v - exact).abs() < 1e-3, "{v} vs {exact}"); +} + +/// The fork's `tabbed_plate_rounds_mitred_on_the_arcs_continuation`: a plate 2 thick, its outline an +/// R25 arc to the sides x = +-4 of a tab whose top is 4 wide with R2 corners, every top edge of the +/// outline rounded r 0.5. The arc's round and the tab side's are mitred on the arc wall's +/// continuation. Removed: the outline's area less the area of the outline moved in by +/// d = r (1 - cos phi), at the height r sin phi into the round (midpoint rule, 8192 steps; the area +/// by Green's theorem). +#[test] +fn tabbed_plate_rounds_mitred_on_the_arcs_continuation() { + use super::sweep::extrude; + use crate::sweeps::{Curve, DraftCorner}; + const Z: [f64; 3] = [0.0, 0.0, 1.0]; + let theta = (4.0_f64 / 25.0).acos(); + let y = 609.0_f64.sqrt(); + let cy = 280.0 / 9.0; + let line = |a: [f64; 2], b: [f64; 2]| Curve::Line { start: [a[0], a[1], 0.0], end: [b[0], b[1], 0.0] }; + let arc = |c: [f64; 2], radius, start, end| Curve::Arc { center: [c[0], c[1], 0.0], axis: Z, reference: [1.0, 0.0, 0.0], radius, start, end }; + let outline = [ + arc([0.0, 0.0], 25.0, PI - theta, 2.0 * PI + theta), + line([4.0, y], [4.0, cy]), + arc([2.0, cy], 2.0, 0.0, PI / 2.0), + line([2.0, cy + 2.0], [-2.0, cy + 2.0]), + arc([-2.0, cy], 2.0, PI / 2.0, PI), + line([-4.0, cy], [-4.0, y]), + ]; + let area = |da: f64, dt: f64| { + let (big, rho) = (25.0 - da, 2.0 - dt); + let tab = rho * rho * PI + 2.0 * rho * (2.0 + cy) + 4.0 * (cy + rho); + let yc = (big * big - (4.0 - dt) * (4.0 - dt)).sqrt(); + let at = yc.atan2(4.0 - dt); + 0.5 * (big * big * (PI + 2.0 * at) + tab) + (4.0 - dt) * (cy - yc) + }; + let (r, dphi) = (0.5, (PI / 2.0) / 8192.0); + let want: f64 = (0..8192) + .map(|i| { + let phi = (f64::from(i) + 0.5) * dphi; + let d = r * (1.0 - phi.cos()); + (area(0.0, 0.0) - area(d, d)) * r * phi.cos() * dphi + }) + .sum(); + let top = [ + [0.0, -25.0, 2.0], + [4.0, 27.8945, 2.0], + [3.41421356, 32.5253247, 2.0], + [0.0, cy + 2.0, 2.0], + [-3.41421356, 32.5253247, 2.0], + [-4.0, 27.8945, 2.0], + ]; + let plate = extrude(&outline, Z, 2.0, 0.0, DraftCorner::default(), true).unwrap(); + assert!(rel(volume(&plate, 1e-8).unwrap(), 2.0 * area(0.0, 0.0)) < 1e-10); + let round = blend(&plate, Blend::Round, &top, &[r; 6], TOL, &[], &[], Corners::Filled).unwrap(); + let removed = volume(&plate, 1e-8).unwrap() - volume(&round, 1e-8).unwrap(); + assert!(rel(removed, want) < 1e-6, "removed {removed}, expected {want}"); + let (rec, _) = native(&to_arrays(&round).unwrap()).unwrap(); + solidcraft_geom::brep::check::validate(&rec).unwrap(); + assert!(super::is_manifold_solid(&round).unwrap()); + assert!(super::check(&round, crate::check::CheckLevel::All).unwrap().is_valid()); +} + +/// Face and edge tags (`Brep::tagged`) through blends: a 20 x 30 x 10 box tagged as operand 0, +/// with one blend on its top front edge (y = 0, z = 10), leaves the bottom and back as they were, +/// trims the top, front and both sides, and makes the blend face. +mod history { + use solidcore_record::brep::history::Change; + + use crate::history::Raw; + use crate::{Blend, Brep}; + + fn one_edge(kind: Blend, size: f64) -> Raw { + let a = Brep::make_box([0.0; 3], [20.0, 30.0, 10.0]).unwrap().tagged(0).unwrap(); + let edge = [[10.0, 0.0, 10.0]]; + let core = super::blend(a.core(), kind, &edge, &[size], super::TOL, &[], &[], super::Corners::Filled).unwrap(); + Brep::made_core(core).history().unwrap() + } + + fn check(kind: Blend, size: f64) { + let h = one_edge(kind, size); + let mut changes: Vec = h.faces.iter().map(|f| f.change).collect(); + changes.sort_by_key(|c| *c as u8); + let want = [Change::Kept, Change::Kept, Change::Modified, Change::Modified, Change::Modified, Change::Modified, Change::Generated]; + assert_eq!(changes, want, "{kind:?}: {h:?}"); + } + + /// A 2 mm round on the top front edge of a box: the top and front are trimmed, the round is + /// new. + #[test] + fn tags_cross_a_fillet() { + check(Blend::Round, 2.0); + } + + /// A 2 mm chamfer on the same edge: the same faces kept, trimmed and made as the round. + #[test] + fn tags_cross_a_chamfer() { + check(Blend::Chamfer, 2.0); + } +} diff --git a/crates/smlib/src/core/boolean.rs b/crates/smlib/src/core/boolean.rs new file mode 100644 index 000000000..5f43279b7 --- /dev/null +++ b/crates/smlib/src/core/boolean.rs @@ -0,0 +1,245 @@ +//! Booleans on solidcore: the C API's own logic round `SM_API`, ported from the fork's +//! `capi/src/smlib_ops.cpp` (`smlib_boolean_with`, `smlib_boolean2d`, +//! `smlib_boolean_union_all`, `finish`, `closed_nonmanifold`) and +//! `capi/src/smlib_imprint.cpp` (`smlib_imprint`). +//! +//! As there, every operation works on copies of its operands (`SmApiBrepCopy`): `SM_API` edits +//! the first operand in place and consumes the second, and a SolidCraft body never changes. + +use std::sync::PoisonError; + +use solidcore::Result as SolidResult; +use solidcore::SolidError; +use solidcore::boolean::api_brep::{self as sm, Boolean2dOutcome}; +use solidcore::boolean::merge::MergeOptions; +use solidcore::geom::a_object::BooleanOperation; +use solidcore::kernel::Kernel; +use solidcore::primitive::primitive_creation::p1::Boolean2d; +use solidcore::topology::brep::p3::brep_copy; +use solidcore::topology::brep::{p1, p2}; +use solidcore::topology::{Brep, edge}; + +use super::{Body, run_on}; +use crate::{BooleanOp, Error, Result}; + +/// What an operation's `SM_API` call gave, before it is a SolidCraft result: the capi's +/// statuses besides success. +enum Done { + Body(Box), + /// `SMLIB_ERR_EMPTY`. + Empty, + /// `SMLIB_ERR_NOT_SOLID`. + NotSolid, + /// `SMLIB_ERR_NO_CUT` (`smlib_imprint`). + NoCut, +} + +impl super::dump::Answer for Done { + fn refusal(&self) -> Option { + matches!(self, Done::NotSolid).then(|| Error::NotSolid.to_string()) + } +} + +/// `GetNumFaces`. +fn num_faces(b: &Brep) -> usize { + b.face_list().len() +} + +/// `closed_nonmanifold` (smlib_ops.cpp): a closed body whose solids touch only along edges or at +/// vertices: at least two regions, no shell vertices, no wire edge, and four edgeuses (two faces, +/// both sides) per face round every edge. As there, an edge whose query fails (`e == nullptr`, a +/// failed `GetEdgeuses`) makes it false: [`edge_closes`]. +fn closed_nonmanifold(r: &Brep) -> SolidResult { + if p1::regions(r, None)?.len() < 2 { + return Ok(false); + } + if !p2::shell_vertices(r, None)?.is_empty() { + return Ok(false); + } + for e in p1::edges(r, None)? { + if !edge_closes(edge::is_wire(r, e), edge::edgeuses(r, e, None, None).map(|u| u.len())) { + return Ok(false); + } + } + Ok(true) +} + +/// The capi's test of one edge in `closed_nonmanifold`, given its `IsWire` and the count of its +/// `GetEdgeuses`: not a wire, and four edgeuses per face round it. Either query failing is +/// false, not an error: the capi returns false where `GetEdgeuses` fails. +pub(super) fn edge_closes(wire: SolidResult, uses: SolidResult) -> bool { + matches!(wire, Ok(false)) && matches!(uses, Ok(n) if n >= 4 && n % 4 == 0) +} + +/// `finish` (smlib_ops.cpp): the result must have faces, and a solid input must give a closed +/// manifold solid or (`nonmanifold`) a closed one whose solids touch along an edge or at a vertex. +fn finish(r: Brep, solid_in: bool, nonmanifold: bool) -> SolidResult { + if num_faces(&r) == 0 { + return Ok(Done::Empty); + } + if solid_in && !p2::is_manifold_solid(&r)? && !(nonmanifold && closed_nonmanifold(&r)?) { + return Ok(Done::NotSolid); + } + Ok(Done::Body(Box::new(r))) +} + +/// What a failing call's dump calls its first operands. +const OPERANDS: [&str; 4] = ["a", "b", "c", "d"]; + +/// `bodies` as a call's inputs, named as its dump names its operands. +fn operands<'a>(bodies: &[&'a Body]) -> Vec<(&'static str, &'a Body)> { + bodies.iter().enumerate().map(|(n, &b)| (OPERANDS.get(n).copied().unwrap_or("operand"), b)).collect() +} + +/// Copies of `bodies`, in order (a body given twice is copied twice, as the capi copies each +/// operand). +fn copies(k: &mut Kernel, bodies: &[&Body]) -> SolidResult> { + // One body's lock at a time, here as everywhere: two calls never deadlock on them. + let mut out = Vec::with_capacity(bodies.len()); + for b in bodies { + let c = brep_copy(k, &b.0.lock().unwrap_or_else(PoisonError::into_inner))?; + out.push(c); + } + Ok(out) +} + +fn result(d: Done, empty: Result>) -> Result> { + match d { + Done::Body(b) => Ok(Some(Body::new(*b))), + Done::Empty => empty, + Done::NotSolid => Err(Error::NotSolid), + Done::NoCut => Ok(None), + } +} + +fn operation(op: BooleanOp) -> BooleanOperation { + match op { + BooleanOp::Union => BooleanOperation::Union, + BooleanOp::Subtract => BooleanOperation::Difference, + BooleanOp::Intersect => BooleanOperation::Intersection, + } +} + +/// Whether every body is a manifold solid (`IsManifoldSolid` of each copy). +fn all_solid(bodies: &[Brep]) -> SolidResult { + for b in bodies { + if !p2::is_manifold_solid(b)? { + return Ok(false); + } + } + Ok(true) +} + +/// Fails when a panic left one of `bodies` half-edited: it is never used again. +fn usable(call: &'static str, bodies: &[&Body]) -> Result<()> { + if bodies.iter().any(|b| b.0.is_poisoned()) { + return Err(Error::Internal(format!("{call}: the body was left unfinished by an earlier panic"))); + } + Ok(()) +} + +/// `smlib_boolean` (`smlib_boolean_with` with `SMLIB_RESULT_NONMANIFOLD`): `SmApiBoolean` on +/// copies of `a` and `b`; `None` when the result is empty (`SMLIB_ERR_EMPTY`), and +/// [`Error::NotSolid`] when solid operands give a body that is not closed. +pub(crate) fn boolean(a: &Body, b: &Body, op: BooleanOp) -> Result> { + usable("SmApiBoolean", &[a, b])?; + let d = run_on("SmApiBoolean", &operands(&[a, b]), |k| { + let mut c = copies(k, &[a, b])?.into_iter(); + let (Some(ca), Some(cb)) = (c.next(), c.next()) else { + return Err(SolidError::invalid_input("smlib_boolean", "no operand")); + }; + let solid_in = p2::is_manifold_solid(&ca)? && p2::is_manifold_solid(&cb)?; + let r = sm::boolean(k, ca, cb, operation(op))?; + finish(r.result, solid_in, true) + })?; + result(d, Ok(None)) +} + +/// `smlib_boolean_union_all`: copies of `bodies` unioned pairwise, level by level (an odd one +/// carried to the next level as it is), each union `SmApiBoolean`'s; then `finish` with +/// non-manifold results allowed. An empty result is [`Error::Empty`]. +pub(crate) fn union_all(bodies: &[&Body]) -> Result { + if bodies.is_empty() || bodies.len() > crate::MAX_UNION_BREPS { + return Err(Error::Argument); + } + usable("smlib_boolean_union_all", bodies)?; + let d = run_on("smlib_boolean_union_all", &operands(bodies), |k| { + let mut level = copies(k, bodies)?; + let solid_in = all_solid(&level)?; + while level.len() > 1 { + let mut next = Vec::with_capacity(level.len().div_ceil(2)); + let mut it = level.into_iter(); + while let Some(a) = it.next() { + match it.next() { + Some(b) => next.push(sm::boolean(k, a, b, BooleanOperation::Union)?.result), + None => next.push(a), + } + } + level = next; + } + match level.pop() { + Some(r) => finish(r, solid_in, true), + None => Ok(Done::Empty), + } + })?; + result(d, Err(Error::Empty))?.ok_or(Error::Empty) +} + +/// `smlib_boolean2d`: `SmApiBoolean2d` (`SmPrimitiveCreation::Boolean2D`) on copies of `a` and +/// `b`, sheets of planar faces on one plane; `None` when either has no face (where +/// `SmApiBoolean2d` succeeds without a result) or the result is empty. +pub(crate) fn boolean2d(a: &Body, b: &Body, op: BooleanOp) -> Result> { + usable("SmApiBoolean2d", &[a, b])?; + let d = run_on("SmApiBoolean2d", &operands(&[a, b]), |k| { + let mut c = copies(k, &[a, b])?.into_iter(); + let (Some(ca), Some(cb)) = (c.next(), c.next()) else { + return Err(SolidError::invalid_input("smlib_boolean2d", "no operand")); + }; + if num_faces(&ca) == 0 || num_faces(&cb) == 0 { + return Ok(Done::Empty); + } + let kind = match op { + BooleanOp::Union => Boolean2d::Union, + BooleanOp::Subtract => Boolean2d::Difference, + BooleanOp::Intersect => Boolean2d::Intersection, + }; + match sm::boolean_2d(k, ca, cb, kind)? { + Boolean2dOutcome::Result(r) => finish(r, false, false), + Boolean2dOutcome::Unassigned { .. } => Ok(Done::Empty), + } + })?; + result(d, Ok(None)) +} + +/// `smlib_imprint`: `SmApiBooleanWithOptions(SM_BO_IMPRINT)` on copies of `body` and `tool`, +/// imprinting and keeping the tool (cookie cutter off, imprinting on, post-process off, +/// imprint-and-classify off, keep other on). `None` when no face was cut +/// (`SMLIB_ERR_NO_CUT`); an empty result is [`Error::Empty`]; the same body twice is +/// [`Error::Argument`]. +pub(crate) fn imprint(body: &Body, tool: &Body) -> Result> { + if std::ptr::eq(body, tool) { + return Err(Error::Argument); + } + usable("SmApiBooleanWithOptions", &[body, tool])?; + let d = run_on("SmApiBooleanWithOptions", &operands(&[body, tool]), |k| { + let mut c = copies(k, &[body, tool])?.into_iter(); + let (Some(a), Some(t)) = (c.next(), c.next()) else { + return Err(SolidError::invalid_input("smlib_imprint", "no operand")); + }; + let before = num_faces(&a); + let options = MergeOptions::new(false, true, false, false, true); + let r = sm::boolean_with_options(k, a, t, BooleanOperation::Imprint, options)?.result; + let after = num_faces(&r); + Ok(if after == 0 { + Done::Empty + } else if after == before { + Done::NoCut + } else { + Done::Body(Box::new(r)) + }) + })?; + match d { + Done::Empty => Err(Error::Empty), + d => result(d, Err(Error::Empty)), + } +} diff --git a/crates/smlib/src/core/boolean_tests.rs b/crates/smlib/src/core/boolean_tests.rs new file mode 100644 index 000000000..ddc8115ad --- /dev/null +++ b/crates/smlib/src/core/boolean_tests.rs @@ -0,0 +1,496 @@ +//! Booleans on solidcore, against analytic volumes: every result exports to a record that validates +//! and counts the solids it should. +//! +//! Curved operands are built on solidcore itself. + +use std::collections::BTreeMap; +use std::f64::consts::PI; +use std::sync::mpsc; +use std::time::Duration; + +use solidcore::geom::axis2_placement::Axis2Placement; +use solidcore::geom::vector3d::Vec3; +use solidcore::mass::integrator::properties::brep_area; +use solidcore::primitive::primitive_creation::p1::create_rectangle; + +use super::boolean::{boolean, boolean2d, edge_closes, imprint, union_all}; +use super::{Body, counts, make_box, make_cylinder, make_sphere, run, solid_count, to_arrays, volume, with_body}; +use crate::export::native; +use crate::{BooleanOp, Error}; + +/// A case longer than this is a hang. +const TIMEOUT: Duration = Duration::from_secs(300); + +/// An operand. +#[derive(Clone, Copy, Debug)] +enum Shape { + Box([f64; 3], [f64; 3]), + Cylinder([f64; 3], f64, f64), + Sphere([f64; 3], f64), +} + +impl Shape { + fn core(self) -> Body { + match self { + Shape::Box(o, s) => make_box(o, s), + Shape::Cylinder(o, r, h) => make_cylinder(o, r, h), + Shape::Sphere(c, r) => make_sphere(c, r), + } + .unwrap() + } +} + +/// What a case does. +#[derive(Clone, Debug)] +enum Op { + Boolean(Shape, Shape, BooleanOp), + UnionAll(Vec), + Imprint(Shape, Shape), +} + +/// A case: the operation, its analytic volume (`None`: the result is empty), the faces it +/// must have where they are known analytically, and its solids (`smlib_brep_solid_count`). +struct Case { + op: Op, + volume: Option, + faces: Option, + solids: usize, +} + +const A: Shape = Shape::Box([0.0; 3], [10.0; 3]); + +fn case(name: &str) -> Case { + let plain = |op, volume: Option, faces| Case { op, volume, faces, solids: 1 }; + match name { + // |A| + |B| - |A ∩ B|: two 10 mm cubes overlapping in a 5 mm cube. + "union_overlapping" => plain(Op::Boolean(A, Shape::Box([5.0; 3], [10.0; 3]), BooleanOp::Union), Some(1000.0 + 1000.0 - 125.0), Some(12)), + // Two 10 mm cubes 10 mm apart: one body of two solids, 12 faces. + "union_disjoint" => { + Case { solids: 2, ..plain(Op::Boolean(A, Shape::Box([20.0, 0.0, 0.0], [10.0; 3]), BooleanOp::Union), Some(2000.0), Some(12)) } + } + "intersect_overlapping" => plain(Op::Boolean(A, Shape::Box([5.0; 3], [10.0; 3]), BooleanOp::Intersect), Some(125.0), Some(6)), + // A slot 5 mm wide and 5 mm deep from the top, right through a 30 x 20 x 10 block. + "subtract_through_slot" => plain( + Op::Boolean(Shape::Box([0.0; 3], [30.0, 20.0, 10.0]), Shape::Box([10.0, -1.0, 5.0], [5.0, 22.0, 6.0]), BooleanOp::Subtract), + Some(6000.0 - 5.0 * 20.0 * 5.0), + Some(10), + ), + // A notch whose tool is flush with the block's front, back and top faces. + "subtract_flush_notch" => plain( + Op::Boolean(Shape::Box([0.0; 3], [30.0, 20.0, 10.0]), Shape::Box([10.0, 0.0, 5.0], [10.0, 20.0, 5.0]), BooleanOp::Subtract), + Some(6000.0 - 10.0 * 20.0 * 5.0), + Some(10), + ), + // A 4 mm cube inside a 10 mm one: a void, still one solid. + "subtract_inside_void" => plain(Op::Boolean(A, Shape::Box([3.0; 3], [4.0; 3]), BooleanOp::Subtract), Some(1000.0 - 64.0), Some(12)), + // abc - πr²c: a 3 mm hole through a 20 x 20 x 10 block. + "subtract_cylinder_hole" => plain( + Op::Boolean(Shape::Box([0.0; 3], [20.0, 20.0, 10.0]), Shape::Cylinder([10.0, 10.0, -1.0], 3.0, 12.0), BooleanOp::Subtract), + Some(4000.0 - PI * 9.0 * 10.0), + None, + ), + // Nine 10 mm cubes, each touching its neighbours face to face. + "union_all_grid" => plain( + Op::UnionAll((0..9).map(|i| Shape::Box([f64::from(i % 3) * 10.0, f64::from(i / 3) * 10.0, 0.0], [10.0; 3])).collect()), + Some(9000.0), + None, + ), + "intersect_disjoint" => plain(Op::Boolean(A, Shape::Box([20.0; 3], [10.0; 3]), BooleanOp::Intersect), None, None), + // A 10 mm sphere less a cap of height h = 5: 4/3 πr³ - πh²(3r - h)/3. + // (solidcore#1431, brep_volume of a whole sphere failing at 1e-8, does not touch the cut + // sphere: it measures at 1e-8.) + "sphere_minus_box" => plain( + Op::Boolean(Shape::Sphere([0.0; 3], 10.0), Shape::Box([-20.0, -20.0, 5.0], [40.0, 40.0, 20.0]), BooleanOp::Subtract), + Some(4.0 / 3.0 * PI * 1000.0 - PI * 25.0 * 25.0 / 3.0), + Some(2), + ), + // A 4 mm square tool through the cube's top face: that face is cut in two (a square and + // the ring round it), nothing else changes. + "imprint_top_face" => plain(Op::Imprint(A, Shape::Box([3.0, 3.0, 8.0], [4.0; 3])), Some(1000.0), Some(7)), + _ => panic!("{name}"), + } +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +/// What a kernel's result measures. +#[derive(Debug, PartialEq)] +struct Measured { + volume: f64, + counts: [usize; 3], + /// The record's faces by surface kind. + kinds: BTreeMap, + solids: usize, +} + +fn kinds(rec: &solidcore_record::brep::Brep) -> BTreeMap { + let mut out = BTreeMap::new(); + for f in &rec.faces { + let v = serde_json::to_value(&f.surface).unwrap(); + *out.entry(v["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1; + } + out +} + +/// The case on solidcore: `None` for an empty result. +fn on_core(c: &Case) -> crate::Result> { + match &c.op { + Op::Boolean(a, b, op) => boolean(&a.core(), &b.core(), *op), + Op::UnionAll(shapes) => { + let bodies: Vec = shapes.iter().map(|s| s.core()).collect(); + union_all(&bodies.iter().collect::>()).map(Some) + } + Op::Imprint(a, t) => imprint(&a.core(), &t.core()), + } +} + +/// Runs `f` on its own thread: a hang fails the test instead of stopping the run. +fn timed(name: &str, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let _ = tx.send(f()); + }); + match rx.recv_timeout(TIMEOUT) { + Ok(v) => v, + // The case panicked: its own message is the failure. + Err(mpsc::RecvTimeoutError::Disconnected) => match worker.join() { + Err(p) => std::panic::resume_unwind(p), + Ok(()) => panic!("{name}: no result"), + }, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("{name}: solidcore hung (no result after {TIMEOUT:?})"), + } +} + +/// Runs the case on solidcore and checks it against the analytic answer; what it measured. +fn solidcore_case(name: &'static str) -> Option { + timed(name, move || { + let c = case(name); + let r = on_core(&c).unwrap_or_else(|e| panic!("{name}: solidcore failed: {e}")); + let (Some(body), Some(expected)) = (&r, c.volume) else { + assert!(r.is_none() && c.volume.is_none(), "{name}: solidcore gave {}, expected {:?}", r.is_some(), c.volume); + return None; + }; + let v = volume(body, 1e-8).unwrap_or_else(|e| panic!("{name}: volume: {e}")); + assert!(rel(v, expected) < 1e-9, "{name}: solidcore volume {v} vs analytic {expected}"); + let n = counts(body).unwrap(); + if let Some(f) = c.faces { + assert_eq!(n[0], f, "{name}: faces {n:?}"); + } + let solids = solid_count(body).unwrap_or_else(|e| panic!("{name}: solid count: {e}")); + assert_eq!(solids, c.solids, "{name}: solids"); + let (rec, _) = native(&to_arrays(body).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + Some(Measured { volume: v, counts: n, kinds: kinds(&rec), solids }) + }) +} + +macro_rules! cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_analytic_volume() { + super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +cases!( + union_overlapping, + union_disjoint, + intersect_overlapping, + subtract_through_slot, + subtract_flush_notch, + subtract_inside_void, + subtract_cylinder_hole, + union_all_grid, + intersect_disjoint, + sphere_minus_box, + imprint_top_face, +); + +/// A `w` x `h` planar sheet on z = 0 from `(x, y)`, solidcore's `CreateRectangle`. +fn rectangle(x: f64, y: f64, w: f64, h: f64) -> Body { + let frame = Axis2Placement::new(Vec3::new(x, y, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)); + run("create_rectangle", |k| create_rectangle(k, 0.0, w, h, &frame)).map(Body::new).unwrap() +} + +fn area(b: &Body) -> f64 { + with_body("brep_area", b, |k, b| brep_area(k, b, 1e-8)).unwrap() +} + +/// Two 10 mm squares overlapping in a 5 mm one, as regions of their plane. +#[test] +fn boolean2d_combines_overlapping_squares() { + for (op, expected) in [(BooleanOp::Union, 175.0), (BooleanOp::Intersect, 25.0), (BooleanOp::Subtract, 75.0)] { + let (a, b) = (rectangle(0.0, 0.0, 10.0, 10.0), rectangle(5.0, 5.0, 10.0, 10.0)); + let r = timed("boolean2d", move || boolean2d(&a, &b, op).map(|r| r.map(|r| (area(&r), counts(&r).unwrap())))); + let (got, n) = r.unwrap_or_else(|e| panic!("{op:?}: {e}")).unwrap_or_else(|| panic!("{op:?}: empty")); + assert!(rel(got, expected) < 1e-9, "{op:?}: area {got} vs {expected}"); + assert_eq!(n[0], 1, "{op:?}: {n:?}"); + } + let (a, far) = (rectangle(0.0, 0.0, 10.0, 10.0), rectangle(20.0, 0.0, 10.0, 10.0)); + assert!(boolean2d(&a, &far, BooleanOp::Intersect).unwrap().is_none(), "disjoint squares intersected"); +} + +/// `closed_nonmanifold`'s test of an edge, as the capi's: an edge whose wire or edgeuse query +/// fails makes the body not closed non-manifold (false), never an error that fails the boolean. +#[test] +fn closed_nonmanifold_takes_a_failed_edge_query_as_false() { + let failed = || solidcore::SolidError::null_pointer("GetEdgeuses"); + assert!(edge_closes(Ok(false), Ok(4))); + assert!(edge_closes(Ok(false), Ok(8))); + assert!(!edge_closes(Ok(false), Ok(2))); + assert!(!edge_closes(Ok(false), Ok(6))); + assert!(!edge_closes(Ok(true), Ok(4))); + assert!(!edge_closes(Ok(false), Err(failed()))); + assert!(!edge_closes(Err(failed()), Ok(4))); +} + +/// Two 10 mm cubes touching along one edge, joined: a closed body whose two solids meet along +/// that edge (four edgeuses round it), 2000 mm³. +#[test] +fn cubes_touching_along_an_edge_join_closed_nonmanifold() { + let r = timed("edge_touching", || { + let a = Shape::Box([0.0; 3], [10.0; 3]).core(); + let b = Shape::Box([10.0, 10.0, 0.0], [10.0; 3]).core(); + boolean(&a, &b, BooleanOp::Union).map(|r| r.map(|r| (volume(&r, 1e-8).unwrap(), solid_count(&r).unwrap()))) + }); + let (v, solids) = r.unwrap().unwrap(); + assert!(rel(v, 2000.0) < 1e-9, "volume {v}"); + assert_eq!(solids, 2); +} + +/// The capi's argument checks: the same body imprinted on itself, an empty union. +#[test] +fn hostile_operands_are_refused() { + let a = A.core(); + assert_eq!(imprint(&a, &a).err(), Some(Error::Argument)); + assert_eq!(union_all(&[]).err(), Some(Error::Argument)); +} + +/// A tool that meets no face cuts none. +#[test] +fn imprint_of_a_far_tool_is_none() { + let r = timed("imprint_far", || imprint(&A.core(), &Shape::Box([20.0; 3], [1.0; 3]).core()).map(|r| r.is_none())); + assert!(r.unwrap()); +} + +/// An operand is never changed: the same body twice, and again after. +#[test] +fn operands_stay_as_they_were() { + let r = timed("operands", || { + let a = A.core(); + let b = Shape::Box([5.0; 3], [10.0; 3]).core(); + let u = boolean(&a, &b, BooleanOp::Union).map(|r| r.is_some()); + let same = boolean(&a, &a, BooleanOp::Union).map(|r| r.map(|r| volume(&r, 1e-8))); + (u, same, counts(&a).unwrap(), volume(&a, 1e-8).unwrap(), counts(&b).unwrap()) + }); + let (u, same, ca, va, cb) = r; + assert!(u.unwrap()); + assert_eq!(ca, [6, 12, 8]); + assert_eq!(cb, [6, 12, 8]); + assert!(rel(va, 1000.0) < 1e-12, "{va}"); + let v = same.unwrap().unwrap().unwrap(); + assert!(rel(v, 1000.0) < 1e-9, "A ∪ A: {v}"); +} + +/// `moved`: a closest-point query that fails, even with an error that is no SMLib status (an edge +/// without its curve here), counts as off the piece, as `SmApiEdgeClosestPoint` failing does in the +/// capi (smlib_history.cpp:246): the face is Modified, the operation stands. +#[test] +fn a_failed_closest_point_counts_as_off_the_piece() { + use solidcore::query::api_queries::edge_closest_point; + use solidcore::topology::edge; + let body = A.core(); + super::with_body("moved", &body, |k, b| { + let e = b.edge_list()[0]; + let (Some(s), Some(f)) = edge::start_end_vertices(b, e)? else { panic!("an edge with no ends") }; + let (s, f) = (b.vertex(s)?.point, b.vertex(f)?.point); + let at = [s, f, s + (f - s) * 0.5]; + let tol = b.tolerance(); + assert!(!super::history::moved(k, b, &[(e, &at)], tol)?, "still where it lay"); + b.edge_mut(e)?.curve = None; + assert!(edge_closest_point(k, b, e, at[2]).is_err_and(|e| e.sm_status().is_none()), "fails with no status"); + assert!(super::history::moved(k, b, &[(e, &at)], tol)?, "off the piece"); + Ok(()) + }) + .unwrap(); +} + +/// Rig case booleans/2928, reduced (fork c2e3d9d): a ring, r 3..5 about (0, 10), z 0..2, unioned +/// with a half annulus prism, r 4..5 about (e, 10), z 2..20, whose cap sits on the ring's top. Two +/// equal circles a little apart cross; they do not coincide over a tiny edge. The stack's volume +/// is 113 pi whatever e is. +/// This path passes with `simple_coincidence_crossing_is_point` off too, so the test holds the +/// result here and does not single out that flag (solidcore's own test does). +#[test] +fn a_ring_and_a_lip_with_walls_nearly_together() { + use super::sweep::extrude; + use crate::sweeps::Curve; + use crate::sweeps::DraftCorner; + const Z: [f64; 3] = [0.0, 0.0, 1.0]; + let up = |p: &[Curve], d| extrude(p, Z, d, 0.0, DraftCorner::default(), true).unwrap(); + let arc = |c: [f64; 3], radius, start, end| Curve::Arc { center: c, axis: Z, reference: [1.0, 0.0, 0.0], radius, start, end }; + let disc = |r| up(&[arc([0.0, 10.0, 0.0], r, 0.0, 2.0 * PI)], 2.0); + let ring = boolean(&disc(5.0), &disc(3.0), BooleanOp::Subtract).unwrap().unwrap(); + for e in [0.0, 1e-4, 1e-3, 1e-2] { + let c = [e, 10.0, 2.0]; + let lip = up( + &[ + arc(c, 5.0, 0.0, PI), + Curve::Line { start: [e - 5.0, 10.0, 2.0], end: [e - 4.0, 10.0, 2.0] }, + Curve::Arc { center: c, axis: [0.0, 0.0, -1.0], reference: [-1.0, 0.0, 0.0], radius: 4.0, start: 0.0, end: PI }, + Curve::Line { start: [e + 4.0, 10.0, 2.0], end: [e + 5.0, 10.0, 2.0] }, + ], + 18.0, + ); + let u = boolean(&ring, &lip, BooleanOp::Union).unwrap().unwrap(); + let v = volume(&u, 1e-8).unwrap(); + let report = super::check(&u, crate::check::CheckLevel::All).unwrap(); + assert!(report.is_valid(), "e {e}: {report}"); + assert_eq!(solid_count(&u).unwrap(), 1, "e {e}"); + assert!(super::is_manifold_solid(&u).unwrap(), "e {e}"); + assert!((v - 113.0 * PI).abs() < 1e-3, "e {e}: {v}"); + } +} + +/// Face and edge tags (`Brep::tagged`) through booleans: each operand tagged, the result's history +/// ([`Raw`]) read back. +mod history { + use solidcore_record::brep::history::Change; + + use crate::history::Raw; + use crate::{BooleanOp, Brep}; + + fn tagged_box(origin: [f64; 3], size: [f64; 3], operand: usize) -> Brep { + Brep::make_box(origin, size).unwrap().tagged(operand).unwrap() + } + + fn tagged_cylinder(origin: [f64; 3], radius: f64, height: f64, operand: usize) -> Brep { + Brep::make_cylinder(origin, radius, height).unwrap().tagged(operand).unwrap() + } + + /// A 40 x 40 x 10 plate with a round hole r 5 at (20, 20), made before tagging: its hole's rims + /// are whole circles, edges closed on themselves. + fn holed_plate(operand: usize) -> Brep { + let plate = Brep::make_box([0.0; 3], [40.0, 40.0, 10.0]).unwrap(); + let rod = Brep::make_cylinder([20.0, 20.0, -5.0], 5.0, 20.0).unwrap(); + plate.boolean(&rod, BooleanOp::Subtract).unwrap().unwrap().tagged(operand).unwrap() + } + + fn boolean(a: &Brep, b: &Brep, op: BooleanOp) -> Raw { + a.boolean(b, op).unwrap().unwrap().history().unwrap() + } + + fn imprint(a: &Brep, b: &Brep) -> Raw { + a.imprint(b).unwrap().unwrap().history().unwrap() + } + + /// Faces of operand 0 with this change. + fn of_first(h: &Raw, c: Change) -> usize { + h.faces.iter().filter(|f| !f.origins.is_empty() && f.origins.iter().all(|o| o.0 == 0) && f.change == c).count() + } + + /// Two 10 mm cubes overlapping in a 5 mm one (the capi's `overlapping_boxes_union`): 12 + /// faces, each from one face of one box, six from each. + #[test] + fn tags_cross_a_boolean() { + let h = boolean(&tagged_box([0.0; 3], [10.0; 3], 0), &tagged_box([5.0; 3], [10.0; 3], 1), BooleanOp::Union); + assert_eq!(h.faces.len(), 12, "{h:?}"); + assert!(h.faces.iter().all(|f| f.origins.len() == 1), "a face without exactly one origin: {h:?}"); + for operand in [0, 1] { + assert_eq!(h.faces.iter().filter(|f| f.origins[0].0 == operand).count(), 6, "operand {operand}: {h:?}"); + } + } + + /// `SmApiBrepCopy` (the copy every solidcore operation starts from) keeps every tag: the + /// copy's history is the operand's own, every face Kept. + #[test] + fn tags_cross_a_copy() { + let a = tagged_box([0.0; 3], [10.0, 20.0, 30.0], 0); + let h = a.try_clone().unwrap().history().unwrap(); + assert_eq!(h.faces.len(), 6, "{h:?}"); + assert!(h.faces.iter().all(|f| f.change == Change::Kept), "{h:?}"); + } + + /// A 10 mm wide bar laid across the top of a 40 x 30 x 20 block, overhanging its front and + /// back, imprinted on it: the bar's sides cut the top in three, and cut the top edges of the + /// faces y = 0 and y = 30 only by a vertex each (where they cross them at x = 10 and x = 20). + /// Those faces are still all of themselves, their boundaries where they were: Kept, as are + /// x = 0, x = 40 and the bottom. + #[test] + fn a_face_whose_edge_is_only_cut_by_a_vertex_is_kept() { + let h = imprint(&tagged_box([0.0; 3], [40.0, 30.0, 20.0], 0), &tagged_box([10.0, -5.0, 20.0], [10.0, 40.0, 10.0], 1)); + assert_eq!(of_first(&h, Change::Kept), 5, "{h:?}"); + assert_eq!(of_first(&h, Change::Modified), 0, "{h:?}"); + } + + /// A 10 mm post standing on a 20 mm cube's top against its x = 0 side, imprinted on it: the + /// post's foot cuts the top's edge along x = 0 by two vertices. Each piece of that edge is a + /// split child, standing for the edge and lying where it lay (the capi's Split gives an untagged + /// child the split edge's `at`), so the side x = 0 is still all of itself and Kept. + #[test] + fn an_imprint_split_edge_lies_where_the_edge_lay() { + let h = imprint(&tagged_box([0.0; 3], [20.0; 3], 0), &tagged_box([0.0, 5.0, 20.0], [10.0; 3], 1)); + // The top's edge along x = 0 is in three pieces, each standing for it alone. + let pieces = |e: usize| h.edges.iter().filter(|x| x.origins == [(0, e)]).count(); + assert!((0..12).any(|e| pieces(e) == 3), "{h:?}"); + assert_eq!(of_first(&h, Change::Kept), 5, "{h:?}"); + assert_eq!(of_first(&h, Change::Modified), 0, "{h:?}"); + assert_eq!(of_first(&h, Change::Split), 2, "{h:?}"); + } + + /// A 10 mm post standing on a 20 mm cube's top, subtracted from it: the post only touches the + /// top, which the boolean copies the post's foot onto (`SmAttribute::Copy`). SMLib's Copy + /// leaves a target that already has a tag alone, so the top stands for the cube's top only. + #[test] + fn a_copy_onto_a_tagged_face_keeps_its_own_tag() { + let h = boolean(&tagged_box([0.0; 3], [20.0; 3], 0), &tagged_box([5.0, 5.0, 20.0], [10.0; 3], 1), BooleanOp::Subtract); + assert_eq!(h.faces.len(), 6, "{h:?}"); + assert!(h.faces.iter().all(|f| f.change == Change::Kept && f.origins.len() == 1 && f.origins[0].0 == 0), "{h:?}"); + } + + /// A corner cut far from the hole: the hole's wall keeps its two whole circles, each a closed + /// edge still where it lay (`moved`'s `open.is_empty()`), so it is Kept, with the two sides the + /// corner misses. + #[test] + fn a_face_bounded_by_closed_edges_is_kept() { + let h = boolean(&holed_plate(0), &tagged_box([35.0, 35.0, -5.0], [10.0, 10.0, 20.0], 1), BooleanOp::Subtract); + assert_eq!(of_first(&h, Change::Kept), 3, "{h:?}"); + } + + /// A cylinder and a sphere cut by a slab across their seams (angle 0, along +x): each curved + /// face is split in two across its seam. + #[test] + fn a_curved_face_split_across_its_seam_is_split() { + let slab = || tagged_box([-20.0, -1.0, -20.0], [40.0, 2.0, 40.0], 1); + let sphere = Brep::make_sphere([0.0; 3], 7.0).unwrap().tagged(0).unwrap(); + for (name, a) in [("cylinder", tagged_cylinder([0.0, 0.0, -5.0], 5.0, 10.0, 0)), ("sphere", sphere)] { + let h = boolean(&a, &slab(), BooleanOp::Subtract); + assert!(of_first(&h, Change::Split) >= 2, "{name}: {h:?}"); + } + } + + /// A chain of three overlapping boxes in one `union_all`: the result names all three. + #[test] + fn a_union_of_three_names_each() { + let (a, b, c) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([5.0; 3], [10.0; 3], 1), tagged_box([10.0; 3], [10.0; 3], 2)); + let h = Brep::union_all(&[&a, &b, &c]).unwrap().history().unwrap(); + assert_eq!(h.faces.iter().flat_map(|f| f.origins.iter().map(|o| o.0)).max(), Some(2), "{h:?}"); + } + + /// A row of four boxes sharing their top and bottom planes, united in pairs and the pairs + /// united: each top merged with its neighbour's stands for two faces, and the merge of those + /// stands for all four. + #[test] + fn a_merge_of_several_origins_on_each_side_stands_for_all() { + let boxes: Vec = (0..4u32).map(|i| tagged_box([f64::from(i) * 10.0, 0.0, 0.0], [10.0; 3], i as usize)).collect(); + let u = |x: &Brep, y: &Brep| x.boolean(y, BooleanOp::Union).unwrap().unwrap(); + let h = u(&u(&boxes[0], &boxes[1]), &u(&boxes[2], &boxes[3])).history().unwrap(); + assert!(h.faces.iter().any(|f| f.origins.len() == 4), "{h:?}"); + } +} diff --git a/crates/smlib/src/core/convert.rs b/crates/smlib/src/core/convert.rs new file mode 100644 index 000000000..fa2e0789c --- /dev/null +++ b/crates/smlib/src/core/convert.rs @@ -0,0 +1,2629 @@ +//! solidcore's B-rep to and from the C API's flat arrays ([`crate::flat`]): ports of +//! `capi/src/smlib_flat.cpp`, so a body converts exactly as it does through the C++ kernel. +//! - [`to_arrays`]: `FlatFromBrep` (SmBrep, through `SmBrepData::FromBrep`, to arrays): the same +//! ids, the same face, edge and vertex order (`GetFaces`, `GetEdges`), analytic kinds with +//! ranges in radians, NURBS as splines, SMLib's own UV trims and tolerances. +//! - [`from_arrays`]: `BrepFromFlat` (`Validate`, `FlatToBrepData`, then +//! `SmBrep::MakeTopologyFromData`, healing unless the arrays say SMLib wrote them). +//! +//! Tolerances differ from the C++ on purpose: `to_arrays` writes the B-rep's own tolerance as +//! TOLERANCE, not the largest of its entities', and `from_arrays` takes the B-rep's and the faces' +//! from the edges' and vertices' own ([`own_tolerances`]). Each entity keeps its tolerance across +//! the kernels instead of every one taking the largest at each crossing. +//! +//! A face whose surface is not a B-spline kind (an offset) exports its approximation, as +//! `FlatFromBrep` does (`SmSurface::ApproximateSurface`). +//! +//! [`from_arrays`] also runs the capi's `PutEnclosingShellsFirst` ([`put_enclosing_shells_first`], +//! an addition to SmuConvert): a bounded region of several shells starts its list at the shell +//! `SmShell::IsInnerShellOf` shows enclosing the others, whatever order the arrays gave. + +// The SmBrepData records are filled field by field, as FlatToBrepData fills them after ReSet. +#![allow(clippy::field_reassign_with_default)] + +use std::borrow::Cow; +use std::collections::HashMap; + +use solidcore::curve::curve::p1::ApproximateCurveOptions; +use solidcore::curve::curve::{Curve, CurveKind}; +use solidcore::curve::ellipse::{Ellipse, EllipseOptions}; +use solidcore::curve::line::Line; +use solidcore::geom::attribute::{AttributeStore, ObjectKey}; +use solidcore::geom::axis2_placement::Axis2Placement; +use solidcore::geom::extent1d::Extent1d; +use solidcore::geom::extent2d::Extent2d; +use solidcore::geom::object::ObjectRef; +use solidcore::geom::tol::approx_tol3d; +use solidcore::nurbs::b_spline_curve::{BSplineCurve, BSplineCurveForm, CanonicalData, KnotType}; +use solidcore::nurbs::b_spline_surface::{BSplineSurface, BSplineSurfaceForm, CanonicalSurfaceData}; +use solidcore::nurbs::crv_basic::Curve as NurbCurve; +use solidcore::nurbs::math::{CPoint, NOW, NOZ}; +use solidcore::nurbs::srf_basic::Surface as NurbSurface; +use solidcore::query::brep::{BoundingBoxOptions, calculate_bounding_box}; +use solidcore::surface::ball_patch::BallPatch; +use solidcore::surface::cone::Cone; +use solidcore::surface::plane::Plane; +use solidcore::surface::sphere::Sphere; +use solidcore::surface::surface::{Surface, SurfaceKind}; +use solidcore::surface::torus::{Torus, TorusOptions}; +use solidcore::topology::brep::p1 as bl; +use solidcore::topology::brep::p10::{HEALER_VERSION, MakeTopologyOptions, TopologyEnv, make_topology_from_data}; +use solidcore::topology::brep_data::{ + BrepData, DataSourceType, EdgeData, EuData, FaceData, FaceuseData, Keyed, LoopData, NO_OBJECT, RegionData, ShellData, UNDEF_ULONG, UNSURE, + VertexData, +}; +use solidcore::topology::brep_data_write::FromBrepEnv; +use solidcore::topology::edgeuse::{p1 as eu1, p3 as eu3}; +use solidcore::topology::topology::NotifyRecords; +use solidcore::topology::{Brep, EdgeId, EdgeuseId, FaceId, ShellId, VertexId, edge, shell, vertex}; +use solidcore::{EntityRef, Kernel, Point2, Point3, SolidError, Vec3}; + +use crate::flat::*; +use crate::import::Arrays; +use crate::{Error, Result}; + +use super::{Body, answer, run, with_body}; + +// ---- shared ------------------------------------------------------------------------------------ + +/// A solidcore error from `call`. +fn sc(call: &'static str) -> impl Fn(SolidError) -> Error { + move |e| Error::Solidcore(format!("{call}: {e}")) +} + +/// The arrays (or the body) are not what the conversion can carry: SMLib's `SM_ERR`. +fn bad(what: &str) -> Error { + Error::Solidcore(format!("flat arrays: {what}")) +} + +fn get(v: &[T], i: usize) -> Result { + v.get(i).copied().ok_or_else(|| bad("index past its array")) +} + +fn get3(v: &[f64], i: usize) -> Result { + let at = |k: usize| i.checked_mul(3).and_then(|j| j.checked_add(k)).map_or_else(|| Err(bad("index past its array")), |j| get(v, j)); + Ok(Vec3::new(at(0)?, at(1)?, at(2)?)) +} + +fn idx(x: i64) -> Result { + usize::try_from(x).map_err(|_| bad("negative index")) +} + +fn count(n: usize) -> Result { + i64::try_from(n).map_err(|_| bad("count")) +} + +fn index_u64(x: u64) -> Result { + usize::try_from(x).map_err(|_| bad("index")) +} + +/// `SM_DEG2RAD`. +fn deg2rad(d: f64) -> f64 { + d * (std::f64::consts::PI / 180.0) +} + +/// `SM_RAD2DEG`. +fn rad2deg(r: f64) -> f64 { + r * (180.0 / std::f64::consts::PI) +} + +/// `SnapSMLibAngularBoundaryDeg`. +fn snap_angular_boundary_deg(degrees: f64) -> f64 { + for quarter in -4..=4 { + let boundary = 90.0 * f64::from(quarter); + if (degrees - boundary).abs() <= 1.0e-9 { + return boundary; + } + } + degrees +} + +/// `UsdRadiansToSMLibDegrees`. +fn radians_to_smlib_degrees(radians: f64) -> f64 { + snap_angular_boundary_deg(rad2deg(radians)) +} + +/// `SM_INFINITE_PARAMETER`. +const INFINITE_PARAMETER: f64 = 1_234_567.0; +/// `SM_EFF_ZERO`. +const EFF_ZERO: f64 = 1.0e-12; +/// `SM_IS_INFINITE`. +fn is_infinite(a: f64) -> bool { + a.abs() == INFINITE_PARAMETER || a.abs() == 1111.111 +} + +/// The flat arrays' writer: every array id, empty until written. +struct Out(Arrays); + +impl Out { + fn new() -> Out { + let mut a = Arrays::default(); + for id in 1..=WIRE_EDGE_NURBS_FORM { + a.ints.insert(id, Vec::new()); + } + for id in TOLERANCE..=VERTEX_TOLERANCE { + a.reals.insert(id, Vec::new()); + } + Out(a) + } + fn i(&mut self, id: i32) -> &mut Vec { + self.0.ints.entry(id).or_default() + } + fn r(&mut self, id: i32) -> &mut Vec { + self.0.reals.entry(id).or_default() + } + fn r3(&mut self, id: i32, p: Vec3) { + self.r(id).extend([p.x, p.y, p.z]); + } +} + +/// The arrays of one edge family (edges or wire edges), by id (`EdgeArraysOut`). +struct EdgeIds { + ty: i32, + range: i32, + count: i32, + order: i32, + cvs: i32, + knots: i32, + weights: i32, + circle_center: i32, + circle_axis: i32, + circle_ref: i32, + circle_radius: i32, + line_origin: i32, + line_direction: i32, + ellipse_center: i32, + ellipse_axis: i32, + ellipse_ref: i32, + ellipse_x: i32, + ellipse_y: i32, + form: i32, + vertices: i32, +} + +const EDGES: EdgeIds = EdgeIds { + ty: EDGE_CURVE_TYPE, + range: EDGE_RANGE, + count: EDGE_NURBS_VERTEX_COUNT, + order: EDGE_NURBS_ORDER, + cvs: EDGE_NURBS_CVS, + knots: EDGE_NURBS_KNOTS, + weights: EDGE_NURBS_WEIGHTS, + circle_center: EDGE_CIRCLE_CENTER, + circle_axis: EDGE_CIRCLE_AXIS, + circle_ref: EDGE_CIRCLE_REF_DIRECTION, + circle_radius: EDGE_CIRCLE_RADIUS, + line_origin: EDGE_LINE_ORIGIN, + line_direction: EDGE_LINE_DIRECTION, + ellipse_center: EDGE_ELLIPSE_CENTER, + ellipse_axis: EDGE_ELLIPSE_AXIS, + ellipse_ref: EDGE_ELLIPSE_REF_DIRECTION, + ellipse_x: EDGE_ELLIPSE_X_RADIUS, + ellipse_y: EDGE_ELLIPSE_Y_RADIUS, + form: EDGE_NURBS_FORM, + vertices: EDGE_VERTICES, +}; + +const WIRE_EDGES: EdgeIds = EdgeIds { + ty: WIRE_EDGE_CURVE_TYPE, + range: WIRE_EDGE_RANGE, + count: WIRE_EDGE_NURBS_VERTEX_COUNT, + order: WIRE_EDGE_NURBS_ORDER, + cvs: WIRE_EDGE_NURBS_CVS, + knots: WIRE_EDGE_NURBS_KNOTS, + weights: WIRE_EDGE_NURBS_WEIGHTS, + circle_center: WIRE_EDGE_CIRCLE_CENTER, + circle_axis: WIRE_EDGE_CIRCLE_AXIS, + circle_ref: WIRE_EDGE_CIRCLE_REF_DIRECTION, + circle_radius: WIRE_EDGE_CIRCLE_RADIUS, + line_origin: WIRE_EDGE_LINE_ORIGIN, + line_direction: WIRE_EDGE_LINE_DIRECTION, + ellipse_center: WIRE_EDGE_ELLIPSE_CENTER, + ellipse_axis: WIRE_EDGE_ELLIPSE_AXIS, + ellipse_ref: WIRE_EDGE_ELLIPSE_REF_DIRECTION, + ellipse_x: WIRE_EDGE_ELLIPSE_X_RADIUS, + ellipse_y: WIRE_EDGE_ELLIPSE_Y_RADIUS, + form: WIRE_EDGE_NURBS_FORM, + vertices: WIRE_EDGE_VERTICES, +}; + +const CURVE_NURBS_I: i64 = CURVE_NURBS as i64; +const CURVE_LINE_I: i64 = CURVE_LINE as i64; +const CURVE_CIRCLE_I: i64 = CURVE_CIRCLE as i64; +const CURVE_ELLIPSE_I: i64 = CURVE_ELLIPSE as i64; +const SURFACE_NURBS_I: i64 = SURFACE_NURBS as i64; +const SURFACE_PLANE_I: i64 = SURFACE_PLANE as i64; +const SURFACE_CYLINDER_I: i64 = SURFACE_CYLINDER as i64; +const SURFACE_CONE_I: i64 = SURFACE_CONE as i64; +const SURFACE_SPHERE_I: i64 = SURFACE_SPHERE as i64; +const SURFACE_TORUS_I: i64 = SURFACE_TORUS as i64; +const SURFACE_BALL_PATCH_I: i64 = SURFACE_BALL_PATCH as i64; + +/// The `SmBSplineCurve` part of a curve that is one (`IsKindOf(SmBSplineCurve_TYPE)`), with its +/// NURB (`GetOrCreateGwNurbPointer`: a lazy line or conic makes it on a copy); `None` for the +/// other kinds. +pub(super) fn bspline_curve_part<'c>(k: &Kernel, c: &'c Curve) -> Result>> { + Ok(Some(match c.kind() { + CurveKind::BSpline(b) => Cow::Borrowed(b), + CurveKind::Line(l) => l.base_with_nurb().map_err(sc("SmLine::GetOrCreateGwNurbPointer"))?, + CurveKind::Ellipse(e) if e.base().gw_nurb().is_none() => { + let mut made = e.clone(); + made.make_nurb(k).map_err(sc("SmEllipse::MakeNurb"))?; + Cow::Owned(made.base().clone_exact()) + } + CurveKind::Ellipse(e) => Cow::Borrowed(e.base()), + CurveKind::Hyperbola(h) if h.base().gw_nurb().is_none() => { + let mut made = h.clone(); + made.make_nurb(None).map_err(sc("SmHyperbola::MakeNurb"))?; + Cow::Owned(made.base().clone_exact()) + } + CurveKind::Hyperbola(h) => Cow::Borrowed(h.base()), + CurveKind::Parabola(p) if p.base().gw_nurb().is_none() => { + let mut made = p.clone(); + made.make_nurb(None).map_err(sc("SmParabola::MakeNurb"))?; + Cow::Owned(made.base().clone_exact()) + } + CurveKind::Parabola(p) => Cow::Borrowed(p.base()), + _ => return Ok(None), + })) +} + +/// The `SmBSplineSurface` part of a surface that is one (`IsKindOf(SmBSplineSurface_TYPE)`), its +/// NURB made first (`GetOrCreateGwNurbPointer`); `None` for the other kinds. +fn bspline_surface_part<'s>(k: &Kernel, s: &'s Surface) -> Result> { + Ok(match s.kind_with_nurb(k).map_err(sc("SmSurface::GetOrCreateGwNurbPointer"))? { + SurfaceKind::BSpline(b) => Some(b), + // A procedural round (solidcore#2274, `fixes.fillet_round_as_definition`) and a Ball corner's + // patch (solidcore#2319, `fixes.fillet_blend_corner`) are their nets, as the fork casts them + // to `SmBSplineSurface`: the face goes out as that NURBS, exactly. + SurfaceKind::BallPatch(bp) => Some(bp.net()), + SurfaceKind::ProceduralBlend(pb) => Some(pb.net()), + SurfaceKind::Plane(p) => Some(p.base()), + SurfaceKind::Cone(c) => Some(c.rev().base()), + SurfaceKind::Sphere(s) => Some(s.base().base()), + SurfaceKind::Torus(t) => Some(t.base().base()), + SurfaceKind::SurfOfRevolution(r) => Some(r.base()), + SurfaceKind::SurfOfExtrusion(e) => Some(e.base()), + _ => None, + }) +} + +// ---- export: FlatFromBrep ---------------------------------------------------------------------- + +/// `body` as the flat arrays the C API exports (`FlatFromBrep`). +pub(crate) fn to_arrays(body: &Body) -> Result { + with_body("FlatFromBrep", body, |k, b| Ok(flat_from_brep(k, b)))? +} + +/// One NURBS curve's arrays (`smu_AddSmBSplineCurve3d`, `smu_AddSmBSplineCurve2d`): counts and +/// orders, cartesian control points of `dim` coordinates, knots and weights. +struct NurbsOut<'a> { + count: &'a mut Vec, + order: &'a mut Vec, + cvs: &'a mut Vec, + knots: &'a mut Vec, + weights: &'a mut Vec, +} + +/// `smu_AddSmBSplineCurve3d`: the curve's NURB, its control points made cartesian. +fn add_bspline_curve_3d(nurb: &NurbCurve, o: NurbsOut<'_>) -> Result<()> { + o.count.push(count(nurb.cpts().len())?); + o.order.push(count(nurb.degree())?.saturating_add(1)); + o.knots.extend_from_slice(nurb.knots()); + for p in nurb.cpts() { + let (mut x, mut y, mut z, mut w) = (p.x, p.y, p.z, 1.0); + if p.w != NOW { + x /= p.w; + y /= p.w; + z /= p.w; + w = p.w; + } + o.cvs.extend([x, y, z]); + o.weights.push(w); + } + Ok(()) +} + +/// The NURB of a B-spline part (`GetOrCreateGwNurbPointer`, NULL being `SM_ERR`). +fn nurb_of(part: &BSplineCurve) -> Result<&NurbCurve> { + part.gw_nurb().ok_or_else(|| bad("a B-spline curve without its NURB")) +} + +/// `smu_AddSmBSplineCurve2d`: an edgeuse's UV trim, reversed when the edgeuse runs against its +/// edge; `None` appends the empty curve. `remap` maps the knots from the edge's interval +/// `[remap[0], remap[1]]` onto `[remap[2], remap[3]]`, `affine` the face's NURBS (u, v) onto the +/// arrays' plane (u, v). +fn add_bspline_curve_2d(o: &mut Out, trim: Option<&NurbCurve>, same: bool, remap: Option<[f64; 4]>, affine: Option<[f64; 6]>) -> Result<()> { + let Some(nurb) = trim else { + o.i(EDGEUSE_NURBS_VERTEX_COUNT).push(0); + o.i(EDGEUSE_NURBS_ORDER).push(0); + return Ok(()); + }; + let reversed; + let nurb = if same { + nurb + } else { + reversed = nurb.reversed().map_err(sc("N_CrvReverse"))?; + &reversed + }; + o.i(EDGEUSE_NURBS_VERTEX_COUNT).push(count(nurb.cpts().len())?); + o.i(EDGEUSE_NURBS_ORDER).push(count(nurb.degree())?.saturating_add(1)); + for &k in nurb.knots() { + let k = match remap { + Some(r) if k == r[1] => r[3], + Some(r) => r[2] + (k - r[0]) / (r[1] - r[0]) * (r[3] - r[2]), + None => k, + }; + o.r(EDGEUSE_NURBS_KNOTS).push(k); + } + for p in nurb.cpts() { + let (mut x, mut y, mut w) = (p.x, p.y, 1.0); + if p.w != NOW { + x /= p.w; + y /= p.w; + w = p.w; + } + if let Some(a) = affine { + let ax = a[0] + a[1] * x + a[2] * y; + y = a[3] + a[4] * x + a[5] * y; + x = ax; + } + o.r(EDGEUSE_NURBS_CVS).extend([x, y]); + o.r(EDGEUSE_NURBS_WEIGHTS).push(w); + } + Ok(()) +} + +/// `smu_AddSmBSplineSurface`: a surface's NURB, control points U-major and cartesian. A knot +/// vector without extent is `SM_ERR`. +fn add_bspline_surface(o: &mut Out, nurb: &NurbSurface) -> Result<()> { + let (u, v) = (nurb.u_knots(), nurb.v_knots()); + let spans = |k: &[f64]| matches!((k.first(), k.last()), (Some(a), Some(b)) if a < b); + if !spans(u) || !spans(v) { + return Err(bad("NURBS surface has degenerate knots and can't be converted")); + } + let (nu, nv) = (nurb.n().saturating_add(1), nurb.m().saturating_add(1)); + o.i(FACE_NURBS_U_VERTEX_COUNT).push(count(nu)?); + o.i(FACE_NURBS_V_VERTEX_COUNT).push(count(nv)?); + o.i(FACE_NURBS_U_ORDER).push(count(nurb.p())?.saturating_add(1)); + o.i(FACE_NURBS_V_ORDER).push(count(nurb.q())?.saturating_add(1)); + o.r(FACE_NURBS_U_KNOTS).extend_from_slice(u); + o.r(FACE_NURBS_V_KNOTS).extend_from_slice(v); + for row in nurb.rows() { + if row.len() != nv { + return Err(bad("NURBS surface net")); + } + for p in row { + let (mut x, mut y, mut z, mut w) = (p.x, p.y, p.z, 1.0); + if p.w != NOW { + w = p.w; + x /= w; + y /= w; + z /= w; + } + o.r3(FACE_NURBS_CVS, Vec3::new(x, y, z)); + o.r(FACE_NURBS_WEIGHTS).push(w); + } + } + Ok(()) +} + +/// `smu_CompactLocalIndex`: a BrepData index less the sorted removed indices below it. +fn compact_index(i: u64, removed: &[u64]) -> Result { + let below = removed.partition_point(|&r| r < i); + count(index_u64(i)?.saturating_sub(below)) +} + +/// `EdgeCurveAsBSpline`: an edge curve's B-spline part, else its approximation within +/// `approx_tol` over the edge interval (`ApproximateCurve`); `None` when it has neither. +fn edge_curve_as_bspline<'c>(k: &Kernel, c: &'c Curve, ivl: &Extent1d, approx_tol: f64) -> Result>> { + if let Some(part) = bspline_curve_part(k, c)? { + return Ok(Some(part)); + } + let Ok(approx) = c.approximate_curve(k, &[ivl.min(), ivl.max()], approx_tol, &ApproximateCurveOptions::default()) else { + return Ok(None); + }; + Ok(bspline_curve_part(k, &approx.curve)?.map(|p| Cow::Owned(p.clone_exact()))) +} + +/// `BuildAnalyticEdgeCurve`: the curve the import builds for a line (unbounded, +/// `center + s * axis`), circle or ellipse (over `[d_min, d_max]` degrees, its NURBS parameter +/// then set to that interval with its notification, `EditParameterization`). +fn build_analytic_edge_curve(k: &Kernel, ty: i64, d_min: f64, d_max: f64, center: Point3, axis: Vec3, refd: Vec3, r1: f64, r2: f64) -> Result { + analytic_edge_curve(k, ty, d_min, d_max, center, axis, refd, r1, r2).map_err(|(call, e)| sc(call)(e)) +} + +/// [`build_analytic_edge_curve`] with solidcore's own error, and the call that gave it. +#[allow(clippy::too_many_arguments)] // BuildAnalyticEdgeCurve's +fn analytic_edge_curve( + k: &Kernel, + ty: i64, + d_min: f64, + d_max: f64, + center: Point3, + axis: Vec3, + refd: Vec3, + r1: f64, + r2: f64, +) -> std::result::Result { + if ty == CURVE_LINE_I { + return Ok(Curve::from(Line::create_canonical(center, axis))); + } + let mut placement = Axis2Placement::default(); + placement.set_canonical(center, refd, axis.cross(refd)).map_err(|e| ("SmAxis2Placement::SetCanonical", e))?; + let degrees = Extent1d::from_min_max(d_min, d_max); + let mut e = if ty == CURVE_CIRCLE_I { + Ellipse::create_canonical_circle(k, &placement, r1, Some(°rees), None).map_err(|e| ("SmCircle::CreateCanonical", e))? + } else { + Ellipse::create_canonical(k, &placement, r1, r2, Some(°rees), None).map_err(|e| ("SmEllipse::CreateCanonical", e))? + }; + e.edit_parameterization(k, °rees, true, None).map_err(|e| ("SmEllipse::EditParameterization", e))?; + Ok(Curve::from(e)) +} + +/// How one edge's curve is exported (`EdgeExport`). +#[derive(Clone, Copy)] +struct EdgeExport { + ty: i64, + /// The exported range: radians for circles and ellipses. + lo: f64, + hi: f64, + /// The imported edge's interval, in SMLib units (degrees for circles and ellipses). + sm_lo: f64, + sm_hi: f64, + center: Point3, + axis: Vec3, + refd: Vec3, + r1: f64, + r2: f64, + /// The imported curve's parameter is an affine image of the edge's. + affine: bool, +} + +const NURBS_EXPORT: EdgeExport = EdgeExport { + ty: CURVE_NURBS_I, + lo: 0.0, + hi: 0.0, + sm_lo: 0.0, + sm_hi: 0.0, + center: Vec3::new(0.0, 0.0, 0.0), + axis: Vec3::new(0.0, 0.0, 0.0), + refd: Vec3::new(0.0, 0.0, 0.0), + r1: 0.0, + r2: 0.0, + affine: false, +}; + +/// `ClassifyEdgeCurve`: a circle, ellipse or line kept as its kind when the curve the import +/// builds from it ([`build_analytic_edge_curve`]) matches it pointwise at the edge's ends and +/// along the STEP parameter; anything else NURBS. A curve whose STEP parameter runs against its +/// NURBS one goes with its axis reversed and its range negated. A call that returns a status +/// other than success makes the edge NURBS, as there ([`answer`]); any other solidcore error +/// fails the export. +fn classify_edge_curve(k: &Kernel, c: Option<&Curve>, ivl: &Extent1d) -> Result { + let Some(c) = c else { return Ok(NURBS_EXPORT) }; + Ok(classify(k, c, ivl).map_err(sc("ClassifyEdgeCurve"))?.unwrap_or(NURBS_EXPORT)) +} + +fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> std::result::Result, SolidError> { + let mut e = NURBS_EXPORT; + match c.kind() { + CurveKind::Ellipse(el) => { + let can = el.canonical(); + e.ty = if el.is_circle_class() { CURVE_CIRCLE_I } else { CURVE_ELLIPSE_I }; + e.center = can.position.origin(); + e.axis = can.position.z_axis(); + e.refd = can.position.x_axis(); + e.r1 = can.radius_x; + e.r2 = if el.is_circle_class() { can.radius_x } else { can.radius_y }; + } + CurveKind::Line(l) => { + let can = l.canonical(); + e.ty = CURVE_LINE_I; + e.center = can.point; + e.axis = can.vector; + } + _ => return Ok(None), + } + let mut s0 = { + let Some(x) = answer(c.convert_t_from_nurbs_to_step(k, ivl.min()))? else { return Ok(None) }; + x + }; + let mut s1 = { + let Some(x) = answer(c.convert_t_from_nurbs_to_step(k, ivl.max()))? else { return Ok(None) }; + x + }; + if !s0.is_finite() || !s1.is_finite() { + return Ok(None); + } + // sNew = sign * sOld + shift + let (mut sign, mut shift) = (1.0, 0.0); + if s0 > s1 { + sign = -1.0; + s0 = -s0; + s1 = -s1; + e.axis = Vec3::new(-e.axis.x, -e.axis.y, -e.axis.z); + } + if !(s1 > s0) { + return Ok(None); + } + if e.ty == CURVE_LINE_I { + if s0.abs() > INFINITE_PARAMETER || s1.abs() > INFINITE_PARAMETER { + return Ok(None); + } + (e.lo, e.sm_lo, e.hi, e.sm_hi) = (s0, s0, s1, s1); + } else { + // SmCircle/SmEllipse::CreateCanonical take intervals within [-360, 360] degrees. (Not + // in the C++: angles past a million degrees are refused, bounding the loops below.) + if s1 - s0 > 360.0 + 1e-9 || s0.abs() > 1.0e6 || s1.abs() > 1.0e6 { + return Ok(None); + } + while s1 > 360.0 + 1e-9 { + s0 -= 360.0; + s1 -= 360.0; + shift -= 360.0; + } + while s0 < -360.0 - 1e-9 { + s0 += 360.0; + s1 += 360.0; + shift += 360.0; + } + if s1 > 360.0 + 1e-9 { + return Ok(None); + } + e.lo = deg2rad(s0); + e.hi = deg2rad(s1); + // exactly what the import computes + e.sm_lo = radians_to_smlib_degrees(e.lo); + e.sm_hi = radians_to_smlib_degrees(e.hi); + } + + let built = { + let Some(x) = answer(analytic_edge_curve(k, e.ty, e.sm_lo, e.sm_hi, e.center, e.axis, e.refd, e.r1, e.r2).map_err(|(_, e)| e))? else { + return Ok(None); + }; + x + }; + let a = { + let Some(x) = answer(c.evaluate_point(k, ivl.min()))? else { return Ok(None) }; + x + }; + let b = { + let Some(x) = answer(c.evaluate_point(k, ivl.max()))? else { return Ok(None) }; + x + }; + let tol = 1e-9 * (1.0 + e.r1 + e.r2 + a.max_dimension() + b.max_dimension()); + let mut affine = true; + for step in 0..=8 { + let f = f64::from(step) / 8.0; + // the same point by the STEP parameter of each curve + let s_new = e.sm_lo + f * (e.sm_hi - e.sm_lo); + let s_old = (s_new - shift) * sign; + let t_old = { + let Some(x) = answer(c.convert_t_from_step_to_nurbs(k, s_old))? else { return Ok(None) }; + x + }; + let t_new = { + let Some(x) = answer(built.convert_t_from_step_to_nurbs(k, s_new))? else { return Ok(None) }; + x + }; + let p_old = { + let Some(x) = answer(c.evaluate_point(k, t_old))? else { return Ok(None) }; + x + }; + let p_new = { + let Some(x) = answer(built.evaluate_point(k, t_new))? else { return Ok(None) }; + x + }; + if !(p_old.distance(p_new) <= tol) { + return Ok(None); + } + // the same point by each edge's NURBS parameter, affinely matched + let q_old = { + let Some(x) = answer(c.evaluate_point(k, ivl.min() + f * (ivl.max() - ivl.min())))? else { return Ok(None) }; + x + }; + let q_new = { + let Some(x) = answer(built.evaluate_point(k, e.sm_lo + f * (e.sm_hi - e.sm_lo)))? else { return Ok(None) }; + x + }; + let d = q_old.distance(q_new); + if (step == 0 || step == 8) && !(d <= tol) { + return Ok(None); // the ends must match exactly as the edge's vertices do + } + affine = affine && d <= tol; + } + e.affine = affine; + Ok(Some(e)) +} + +/// `WriteEdgeCurve`: one edge's kind, range and geometry. A circle or ellipse also goes with its +/// own NURBS form (`*_NURBS_FORM`), whose interval its range is. +fn write_edge_curve(k: &Kernel, o: &mut Out, ids: &EdgeIds, e: &EdgeExport, c: Option<&Curve>, ivl: &Extent1d, approx_tol: f64) -> Result<()> { + o.i(ids.ty).push(e.ty); + let form = e.ty == CURVE_CIRCLE_I || e.ty == CURVE_ELLIPSE_I; + o.i(ids.form).push(i64::from(form)); + let c = c.ok_or_else(|| bad("an edge without a curve"))?; + let nurbs = |o: &mut Out, part: &BSplineCurve| -> Result<()> { + let (mut count, mut order, mut cvs, mut knots, mut weights) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + add_bspline_curve_3d( + nurb_of(part)?, + NurbsOut { count: &mut count, order: &mut order, cvs: &mut cvs, knots: &mut knots, weights: &mut weights }, + )?; + o.i(ids.count).append(&mut count); + o.i(ids.order).append(&mut order); + o.r(ids.cvs).append(&mut cvs); + o.r(ids.knots).append(&mut knots); + o.r(ids.weights).append(&mut weights); + Ok(()) + }; + if e.ty == CURVE_NURBS_I { + o.r(ids.range).extend([ivl.min(), ivl.max()]); + // SmuConvert asserts and dereferences NULL + let part = edge_curve_as_bspline(k, c, ivl, approx_tol)?.ok_or_else(|| bad("an edge curve SMLib could not approximate"))?; + return nurbs(o, &part); + } + if form { + o.r(ids.range).extend([ivl.min(), ivl.max()]); + } else { + o.r(ids.range).extend([e.lo, e.hi]); + } + if e.ty == CURVE_LINE_I { + o.r3(ids.line_origin, e.center); + o.r3(ids.line_direction, e.axis); + return Ok(()); + } + if e.ty == CURVE_CIRCLE_I { + o.r3(ids.circle_center, e.center); + o.r3(ids.circle_axis, e.axis); + o.r3(ids.circle_ref, e.refd); + o.r(ids.circle_radius).push(e.r1); + } else { + o.r3(ids.ellipse_center, e.center); + o.r3(ids.ellipse_axis, e.axis); + o.r3(ids.ellipse_ref, e.refd); + o.r(ids.ellipse_x).push(e.r1); + o.r(ids.ellipse_y).push(e.r2); + } + // every SMLib conic is an SmBSplineCurve: its own NURBS, in edge order with the NURBS + // edges' curves + let part = bspline_curve_part(k, c)?.ok_or_else(|| bad("a conic that is not a B-spline"))?; + nurbs(o, &part) +} + +/// `ZoneTolWithFaces`: `own` or, where larger, the B-rep's tolerance or that of a face round it. +fn zone_tol_with_faces(b: &Brep, own: f64, brep_tol: f64, faces: &[FaceId]) -> Result { + let mut tol = own.max(brep_tol); + for &f in faces { + let t = solidcore::topology::face::p2::tolerance(b, f).map_err(sc("SmFace::GetTolerance"))?; + if t.is_finite() && t > tol { + tol = t; + } + } + Ok(tol) +} + +/// `GetMaxZoneTol3d`: the largest of the B-rep's, its faces', edges' and vertices' tolerances. +fn max_zone_tol(b: &Brep) -> Result { + let mut max = b.tolerance(); + let mut take = |t: f64| { + if t.is_finite() && t >= 0.0 && t > max { + max = t; + } + }; + for f in bl::faces(b, None).map_err(sc("GetFaces"))? { + take(solidcore::topology::face::p2::tolerance(b, f).map_err(sc("SmFace::GetTolerance"))?); + } + for e in bl::edges(b, None).map_err(sc("GetEdges"))? { + take(edge::tolerance(b, e).map_err(sc("SmEdge::GetTolerance"))?); + } + for v in bl::vertices(b, None).map_err(sc("GetVertices"))? { + take(vertex::tolerance(b, v).map_err(sc("SmVertex::GetTolerance"))?); + } + Ok(max) +} + +/// The shells in `SmBrepData::FromBrep`'s order: the regions, the infinite one first, each +/// region's shells in list order. +fn shells_in_order(b: &Brep) -> Result> { + let mut regions = bl::regions(b, None).map_err(sc("GetRegions"))?; + let infinite = b.infinite_region(); + if regions.len() > 1 + && regions.first().copied() != infinite + && let Some(i) = regions.iter().skip(1).position(|&r| Some(r) == infinite) + { + let r = regions.remove(i + 1); + regions.insert(0, r); + } + let mut shells = Vec::new(); + for r in regions { + shells.extend(b.region(r).map_err(sc("GetShells"))?.shells.iter().copied()); + } + Ok(shells) +} + +/// The topology identity [`BrepData::from_brep`] and [`make_topology_from_data`] name entities +/// by (upstream: their addresses): the type code and the entity's index. +pub(crate) fn key_of(e: EntityRef) -> ObjectRef { + let (type_code, kind, i) = match e { + EntityRef::Brep(x) => (16011, 0u64, x.index()), + EntityRef::Region(x) => (16012, 1, x.index()), + EntityRef::Shell(x) => (16013, 2, x.index()), + EntityRef::Faceuse(x) => (16022, 3, x.index()), + EntityRef::Face(x) => (16002, 4, x.index()), + EntityRef::Loopuse(x) => (16004, 5, x.index()), + EntityRef::Loop(x) => (16003, 6, x.index()), + EntityRef::Edgeuse(x) => (16005, 7, x.index()), + EntityRef::Edge(x) => (16016, 8, x.index()), + EntityRef::Vertexuse(x) => (16006, 9, x.index()), + EntityRef::Vertex(x) => (16021, 10, x.index()), + }; + ObjectRef { type_code, key: ObjectKey(((kind + 1) << 32) | u64::from(i)) } +} + +/// `FlatFromBrep`: `b` as flat arrays, through `SmBrepData::FromBrep`. Every edgeuse on a face +/// without a UV trim first gets SMLib's own (`GetOrCreateUVTrimCurve`); edges and wire edges, +/// vertices and point-shell vertices, edgeuses and wire edgeuses are split apart, every index +/// compacted for the split. +fn flat_from_brep(k: &mut Kernel, b: &mut Brep) -> Result { + for eu in solidcore::topology::brep::p2::edgeuses(b, None).map_err(sc("GetEdgeuses"))? { + if eu1::faceuse(b, eu).map_err(sc("GetFaceuse"))?.is_none() + || eu1::uv_trim_curve_pointer(b, eu).map_err(sc("GetUVTrimCurvePointer"))?.is_some() + { + continue; + } + let made = eu3::get_or_create_uv_trim_curve(k, b, eu, false, false, true).map_err(sc("GetOrCreateUVTrimCurve"))?; + made.status.map_err(sc("GetOrCreateUVTrimCurve"))?; + } + let b: &Brep = b; + + // the BrepData; its records keep the B-rep's lists' order + let store = AttributeStore::default(); + let records = NotifyRecords::new(); + let env = FromBrepEnv { + attributes: &store, + key_of: &key_of, + records: &records, + curve_key: &|_: EdgeId| ObjectKey(0), + uv_curve_key: &|_: EdgeuseId| ObjectKey(0), + surface_key: &|_: FaceId| ObjectKey(0), + }; + let bd = BrepData::from_brep(b, &env, &mut Vec::new()).map_err(sc("SmBrepData::FromBrep"))?; + let shell_ids = shells_in_order(b)?; + let face_ids = bl::faces(b, None).map_err(sc("GetFaces"))?; + let edge_ids = bl::edges(b, None).map_err(sc("GetEdges"))?; + let vertex_ids = bl::vertices(b, None).map_err(sc("GetVertices"))?; + if shell_ids.len() != bd.shells.len() + || face_ids.len() != bd.faces.len() + || edge_ids.len() != bd.edges.len() + || vertex_ids.len() != bd.vertices.len() + { + return Err(bad("SmBrepData::FromBrep's lists differ from the B-rep's")); + } + + // TOLERANCE is the B-rep's own tolerance, and each edge and vertex carries its own + // (EDGE_TOLERANCE, VERTEX_TOLERANCE). Writing the largest one there instead, as SMLib's + // `FlatFromBrep` does, makes it every entity's on import (MakeTopologyFromData raises each + // entity to the B-rep's), so every crossing between the kernels spread the largest tolerance + // over the body. Curves are still approximated to the largest. + let zone = max_zone_tol(b)?; + let brep_tol = b.tolerance(); + let xsect = 2.0 * if brep_tol.is_finite() && brep_tol > 0.0 && brep_tol < zone { brep_tol } else { zone }; + let approx_tol = zone / 2.0; + let bbox = calculate_bounding_box(k, b, BoundingBoxOptions { approx: false, tight: false, expand_by_zone_tol_3d: false }) + .map_err(sc("CalculateBoundingBox"))?; + + let mut o = Out::new(); + o.r(TOLERANCE).push(xsect); + let (lo, hi) = (bbox.min(), bbox.max()); + o.r(EXTENT).extend([lo.x, lo.y, lo.z, hi.x, hi.y, hi.z]); + o.i(SOURCE).push(1); + + let edge_index: HashMap = edge_ids.iter().enumerate().map(|(i, &e)| (e, i)).collect(); + let edge_curve = |i: usize| -> Result> { edge::curve(b, get(&edge_ids, i)?).map_err(sc("SmEdge::GetCurve")) }; + let mut exports = Vec::with_capacity(bd.edges.len()); + for (i, ed) in bd.edges.iter().enumerate() { + exports.push(classify_edge_curve(k, edge_curve(i)?, &ed.interval)?); + } + + // Regions + for r in &bd.regions { + o.i(REGION_SHELL_COUNT).push(i64::try_from(r.num_shells).map_err(|_| bad("count"))?); + o.i(REGION_TYPE).push(i64::from(r.is_void != 0)); + } + + // Shells, wire edges and their curves, point-shell points + let mut point_shell_vertices: Vec = Vec::new(); + let mut wire_edges: Vec = Vec::new(); + let mut wire_vertices_raw: Vec = Vec::new(); + for (sd, &s) in bd.shells.iter().zip(&shell_ids) { + let sh = b.shell(s).map_err(sc("GetShell"))?; + let faceuses = sh.get_faceuses().map_err(sc("SmShell::GetFaceuses"))?.len(); + let wires = shell::wire_edges(k, b, s).map_err(sc("SmShell::GetWireEdges"))?; + let point = faceuses == 0 && wires.is_empty(); + o.i(SHELL_FACEUSE_COUNT).push(count(faceuses)?); + o.i(SHELL_WIRE_EDGE_COUNT).push(count(wires.len())?); + o.i(SHELL_POINT_TYPE).push(i64::from(point)); + for w in wires { + let i = *edge_index.get(&w).ok_or_else(|| bad("a wire edge not in the B-rep"))?; + let wd = bd.edges.get(i).ok_or_else(|| bad("wire edge record"))?; + wire_edges.push(i as u64); + wire_vertices_raw.extend([wd.start_vertex, wd.end_vertex]); + write_edge_curve(k, &mut o, &WIRE_EDGES, &get(&exports, i)?, edge_curve(i)?, &wd.interval, approx_tol)?; + } + if point { + let v = sh.vertex(b).map_err(sc("SmShell::GetVertex"))?.ok_or_else(|| bad("a point shell without its vertex"))?; + point_shell_vertices.push(sd.vertex); + let p = vertex::point(b, v).map_err(sc("SmVertex::GetPoint"))?; + o.r3(SHELL_POINT_POSITION, p); + } + } + point_shell_vertices.sort_unstable(); + wire_edges.sort_unstable(); + for v in wire_vertices_raw { + let c = compact_index(v, &point_shell_vertices)?; + o.i(WIRE_EDGE_VERTICES).push(c); + } + + // Faceuses + for fu in &bd.faceuses { + o.i(FACEUSE_FACE).push(i64::try_from(fu.face).map_err(|_| bad("faceuse face"))?); + o.i(FACEUSE_ORIENTATION).push(i64::from(fu.orientation == 1)); + } + + // Faces and their surfaces + let n_loops = bd.loops.len(); + let mut loop_exports_uv = vec![false; n_loops]; + let mut loop_plane_map: Vec> = vec![None; n_loops]; + for (fd, &f) in bd.faces.iter().zip(&face_ids) { + let surface = b.face(f).map_err(sc("GetFace"))?.surface.as_ref().ok_or_else(|| bad("a face without a surface"))?; + // `m_lSurface >= m_vSurfaces.GetSize()`: a surface no face of the B-rep owns. + if !usize::try_from(fd.surface).is_ok_and(|s| s < bd.surfaces.len()) { + return Err(bad("a face whose surface its B-rep does not hold")); + } + let trim_type = i64::from(fd.rectangular_trim == 1); + let ty = match surface.kind() { + SurfaceKind::Sphere(_) => SURFACE_SPHERE_I, + SurfaceKind::Plane(_) => SURFACE_PLANE_I, + SurfaceKind::Cone(c) if c.is_cylinder_class() => SURFACE_CYLINDER_I, + SurfaceKind::Cone(_) => SURFACE_CONE_I, + SurfaceKind::Torus(_) => SURFACE_TORUS_I, + SurfaceKind::BallPatch(_) => SURFACE_BALL_PATCH_I, + _ => SURFACE_NURBS_I, + }; + // A ball patch is a NURBS face (its net, range and trims) with its sphere as its + // definition. + let nurbs_kind = ty == SURFACE_NURBS_I || ty == SURFACE_BALL_PATCH_I; + // A curved analytic face goes with its NURBS form, whose parameters its range and trims + // are in; a plane's (u, v) are distances along its unit axes, an affine image of its + // NURBS (u, v). + let nurbs_form = !nurbs_kind && ty != SURFACE_PLANE_I; + let mut plane_map = None; + if let SurfaceKind::Plane(p) = surface.kind() { + let scale = p.uv_scale(); + let mut q = [Point2::new(0.0, 0.0); 3]; + let mut ok = true; + for (qk, at) in q.iter_mut().zip([Point2::new(0.0, 0.0), Point2::new(1.0, 0.0), Point2::new(0.0, 1.0)]) { + match answer(surface.convert_uv_from_nurbs_to_step(k, at)).map_err(sc("SmSurface::ConvertUVFromNURBSToSTEP"))? { + Some(st) => *qk = Point2::new(st.x * scale.x, st.y * scale.y), + None => { + ok = false; + break; + } + } + } + if ok { + let [q0, q1, q2] = q; + plane_map = Some([q0.x, q1.x - q0.x, q2.x - q0.x, q0.y, q1.y - q0.y, q2.y - q0.y]); + } + } + for l in 0..fd.num_loops { + let li = index_u64(fd.start_loop.saturating_add(l))?; + let (Some(x), Some(m)) = (loop_exports_uv.get_mut(li), loop_plane_map.get_mut(li)) else { + return Err(bad("face loop index is out of bounds")); + }; + *x = nurbs_kind || nurbs_form || plane_map.is_some(); + *m = plane_map; + } + + // face range: a NURBS (or NURBS form) face's native (u, v); an analytic surface's STEP + // domain, angles in radians + let d = fd.uv_domain; + let (mut umin, mut vmin, mut umax, mut vmax) = (d.u_min(), d.v_min(), d.u_max(), d.v_max()); + if !nurbs_kind && !nurbs_form { + let step = surface.step_uv_domain(); + if ty == SURFACE_SPHERE_I || ty == SURFACE_TORUS_I { + (umin, vmin, umax, vmax) = (deg2rad(step.u_min()), deg2rad(step.v_min()), deg2rad(step.u_max()), deg2rad(step.v_max())); + } else if ty == SURFACE_CYLINDER_I || ty == SURFACE_CONE_I { + (umin, vmin, umax, vmax) = (deg2rad(step.u_min()), step.v_min(), deg2rad(step.u_max()), step.v_max()); + } else if let SurfaceKind::Plane(p) = surface.kind() { + // plane parameters are distances along unit placement axes (SmExtent2d::Scale) + let s = p.uv_scale(); + let scale = |x: f64, by: f64| if is_infinite(x) { x } else { x * by }; + (umin, vmin, umax, vmax) = (scale(step.u_min(), s.x), scale(step.v_min(), s.y), scale(step.u_max(), s.x), scale(step.v_max(), s.y)); + } + } + o.i(FACE_LOOP_COUNT).push(i64::try_from(fd.num_loops).map_err(|_| bad("count"))?); + o.i(FACE_SURFACE_TYPE).push(ty); + o.i(FACE_TRIM_TYPE).push(trim_type); + o.i(FACE_NURBS_FORM).push(i64::from(nurbs_form)); + o.r(FACE_RANGE).extend([umin, vmin, umax, vmax]); + + match surface.kind() { + SurfaceKind::Sphere(s) => { + let pos = s.base().position(); + o.r3(FACE_SPHERE_CENTER, pos.origin()); + o.r3(FACE_SPHERE_AXIS, pos.z_axis()); + o.r3(FACE_SPHERE_REF_DIRECTION, pos.x_axis()); + o.r(FACE_SPHERE_RADIUS).push(s.radius()); + } + SurfaceKind::Plane(p) => { + let pos = p.position(); + o.r3(FACE_PLANE_ORIGIN, pos.origin()); + o.r3(FACE_PLANE_AXIS, pos.z_axis()); + o.r3(FACE_PLANE_REF_DIRECTION, pos.x_axis()); + } + SurfaceKind::Cone(c) if c.is_cylinder_class() => { + let pos = c.canonical().origin; + o.r3(FACE_CYLINDER_ORIGIN, pos.origin()); + o.r3(FACE_CYLINDER_AXIS, pos.z_axis()); + o.r3(FACE_CYLINDER_REF_DIRECTION, pos.x_axis()); + o.r(FACE_CYLINDER_RADIUS).push(c.bot_radius()); + } + SurfaceKind::Cone(c) => { + let can = c.canonical(); + o.r3(FACE_CONE_ORIGIN, can.origin.origin()); + o.r3(FACE_CONE_AXIS, can.origin.z_axis()); + o.r3(FACE_CONE_REF_DIRECTION, can.origin.x_axis()); + o.r(FACE_CONE_RADIUS).push(can.radius); + o.r(FACE_CONE_SEMI_ANGLE).push(deg2rad(can.semi_angle_deg)); + } + SurfaceKind::Torus(t) => { + let pos = t.base().position(); + o.r3(FACE_TORUS_ORIGIN, pos.origin()); + o.r3(FACE_TORUS_AXIS, pos.z_axis()); + o.r3(FACE_TORUS_REF_DIRECTION, pos.x_axis()); + o.r(FACE_TORUS_MAJOR_RADIUS).push(t.major_radius()); + o.r(FACE_TORUS_MINOR_RADIUS).push(t.minor_radius()); + } + SurfaceKind::BallPatch(bp) => { + o.i(FACE_DEFINITION_REAL_COUNT).push(4); + o.r3(FACE_DEFINITION_REALS, bp.centre()); + o.r(FACE_DEFINITION_REALS).push(bp.radius()); + } + _ => {} + } + if nurbs_form || nurbs_kind { + // Every analytic class is an SmBSplineSurface: its own NURBS, in face order with the + // NURBS faces' surfaces. Another surface (an offset) is approximated within the + // curves' tolerance, splitting its spans up to 5 times; its status fails the export, + // as does no surface, which would leave the arrays without this face's NURBS. + let approximated; + let part = match bspline_surface_part(k, surface)? { + Some(part) => part, + None => { + approximated = surface + .approximate_surface(k, approx_tol3d(k, approx_tol), 5, true) + .map_err(sc("SmSurface::ApproximateSurface"))? + .surface + .ok_or_else(|| bad("a face surface SMLib could not convert to a B-spline"))?; + bspline_surface_part(k, &approximated)?.ok_or_else(|| bad("an approximated face surface that is not a B-spline"))? + } + }; + add_bspline_surface(&mut o, part.gw_nurb().ok_or_else(|| bad("a B-spline surface without its NURB"))?)?; + } + } + + // Loops + for l in &bd.loops { + if l.loop_type == 0 && l.num_eu > 0 { + o.i(LOOP_EDGEUSE_COUNT).push(i64::try_from(l.num_eu).map_err(|_| bad("count"))?); + o.i(LOOP_VERTEX).push(-1); + } else if l.loop_type == 1 && l.vertex != NO_OBJECT && l.vertex != UNDEF_ULONG { + o.i(LOOP_EDGEUSE_COUNT).push(0); + let c = compact_index(l.vertex, &point_shell_vertices)?; + o.i(LOOP_VERTEX).push(c); + } else { + return Err(bad("incorrect loop type")); + } + } + + // Edgeuses connecting edges to faces; wire edges' edgeuses are removed. A pair's radial + // entry: 1 when its top edgeuse's next is its own bottom one. + let non_face: Vec = bd.edgeuses.iter().enumerate().filter(|(_, e)| e.eu_type != 0).map(|(i, _)| i as u64).collect(); + for (j, eu) in bd.edgeuses.iter().enumerate() { + if eu.eu_type != 0 { + continue; + } + let j = count(j)?; + o.i(EDGEUSE_EDGE).push(compact_index(eu.edge, &wire_edges)?); + o.i(EDGEUSE_ORIENTATION).push(i64::from(eu.orientation == 1)); + let top_next = if eu.next_eu >= 0 { eu.next_eu } else { -eu.next_eu - 1 }; + let bot_next = if eu.mate_next_eu >= 0 { eu.mate_next_eu } else { -eu.mate_next_eu - 1 }; + let top_entry = top_next == j; + o.i(EDGEUSE_RADIAL_ENTRY).push(i64::from(top_entry)); + let next = u64::try_from(if top_entry { bot_next } else { top_next }).map_err(|_| bad("radial index"))?; + let next = compact_index(next, &non_face)?; + o.i(EDGEUSE_NEXT_RADIAL).push(next); + + // the UV trim, on faces whose loops carry them + let li = index_u64(eu.loop_)?; + let exports_uv = *loop_exports_uv.get(li).ok_or_else(|| bad("edgeuse loop index is out of bounds"))?; + let trim = if exports_uv && eu.uv_curve != NO_OBJECT { bd.uv_curves.get(index_u64(eu.uv_curve)?) } else { None }; + let part = match trim { + Some(t) => bspline_curve_part(k, &t.object)?, + None => None, + }; + let mut nurb = part.as_deref().map(nurb_of).transpose()?; + // On an edge exported as a line, the trim's knots follow the line's parameter, or the + // trim is dropped where that is not an affine image of the edge's (SMLib rebuilds it). + // Circles and ellipses go out on their NURBS form, whose parameter the trims are in. + let mut remap = None; + let ei = index_u64(eu.edge)?; + if nurb.is_some() + && let Some(ex) = exports.get(ei) + && ex.ty == CURVE_LINE_I + { + if ex.affine { + let ivl = bd.edges.get(ei).ok_or_else(|| bad("edge record"))?.interval; + remap = Some([ivl.min(), ivl.max(), ex.sm_lo, ex.sm_hi]); + } else { + nurb = None; + } + } + let affine = loop_plane_map.get(li).copied().flatten(); + let before = o.i(EDGEUSE_NURBS_VERTEX_COUNT).len(); + if add_bspline_curve_2d(&mut o, nurb, eu.orientation == 1, remap, affine).is_err() && o.i(EDGEUSE_NURBS_VERTEX_COUNT).len() == before { + // UV trims are optional: keep the edgeuse / trim records one to one + o.i(EDGEUSE_NURBS_VERTEX_COUNT).push(0); + o.i(EDGEUSE_NURBS_ORDER).push(0); + } + } + + // Edges (face edges; wire edges went with their shells) + for (j, ed) in bd.edges.iter().enumerate() { + if wire_edges.binary_search(&(j as u64)).is_ok() { + continue; + } + let e = get(&edge_ids, j)?; + let start = compact_index(ed.start_vertex, &point_shell_vertices)?; + let end = compact_index(ed.end_vertex, &point_shell_vertices)?; + o.i(EDGE_VERTICES).extend([start, end]); + let faces = edge::faces(b, e, None).map_err(sc("SmEdge::GetFaces"))?; + let own = edge::tolerance(b, e).map_err(sc("SmEdge::GetTolerance"))?; + o.r(EDGE_TOLERANCE).push(2.0 * zone_tol_with_faces(b, own, brep_tol, &faces)?); + write_edge_curve(k, &mut o, &EDGES, &get(&exports, j)?, edge_curve(j)?, &ed.interval, approx_tol)?; + } + + // Vertices (point-shell vertices went with their shells) + for (j, vd) in bd.vertices.iter().enumerate() { + if point_shell_vertices.binary_search(&(j as u64)).is_ok() { + continue; + } + o.i(VERTEX_POINT_TYPE).push(1); + o.r3(VERTEX_POSITION, vd.point); + let v: VertexId = get(&vertex_ids, j)?; + let faces = vertex::faces(b, v).map_err(sc("SmVertex::GetFaces"))?; + let own = vertex::tolerance(b, v).map_err(sc("SmVertex::GetTolerance"))?; + o.r(VERTEX_TOLERANCE).push(2.0 * zone_tol_with_faces(b, own, brep_tol, &faces)?); + } + Ok(o.0) +} + +// ---- import: Validate -------------------------------------------------------------------------- + +/// The arrays of one B-rep, read as hostile input. +struct In<'a>(&'a Arrays); + +impl<'a> In<'a> { + fn i(&self, id: i32) -> &'a [i64] { + self.0.ints.get(&id).map_or(&[], Vec::as_slice) + } + fn r(&self, id: i32) -> &'a [f64] { + self.0.reals.get(&id).map_or(&[], Vec::as_slice) + } +} + +/// What `Validate` learns about valid input (`Shape`). +#[derive(Default)] +struct Shape { + regions: usize, + shells: usize, + faceuses: usize, + faces: usize, + loops: usize, + edgeuses: usize, + edges: usize, + wire_edges: usize, + vertices: usize, + point_shells: usize, + uv_curves: bool, +} + +/// Below SMLib's index sentinels (`SM_NO_OBJECT`, `MakeTopologyFromData`'s 999999). +const MAX_TOPOLOGY: i64 = 999_000; +/// `NL_MAXDEG + 1`. +const MAX_ORDER: i64 = 18; +const MAX_VALUE: f64 = 1.0e9; +const MAX_FLAT_LEN: i64 = 1 << 27; + +fn bits(v: &[i64]) -> bool { + v.iter().all(|&x| x == 0 || x == 1) +} + +fn in_range(v: &[i64], lo: i64, hi: i64) -> bool { + v.iter().all(|&x| x >= lo && x <= hi) +} + +/// `SumCounts`: the sum of non-negative counts, `None` past [`MAX_TOPOLOGY`]. +fn sum_counts(v: &[i64]) -> Option { + let mut s = 0i64; + for &x in v { + if !(0..=MAX_TOPOLOGY).contains(&x) { + return None; + } + s += x; + if s > MAX_TOPOLOGY { + return None; + } + } + Some(s) +} + +fn has_form(form: &[i64], i: usize) -> bool { + form.get(i) == Some(&1) +} + +/// `GoodFrame`: an axis and a reference direction that span a plane. +fn good_frame(axis: &[f64], refd: &[f64], i: usize) -> bool { + let (Ok(a), Ok(r)) = (get3(axis, i), get3(refd, i)) else { return false }; + let (la, lr) = (a.length(), r.length()); + la > 1e-12 && lr > 1e-12 && a.cross(r).length() > 1e-9 * la * lr +} + +/// `GoodKnots`: `count + order` knots, non-decreasing, with a non-empty interval. +fn good_knots(k: &[f64], count: i64, order: i64) -> bool { + let (Ok(n), Ok(o)) = (usize::try_from(count), usize::try_from(order)) else { return false }; + let Some(k) = n.checked_add(o).and_then(|m| k.get(..m)) else { return false }; + if !k.windows(2).all(|w| matches!(w, [a, b] if b >= a)) { + return false; + } + matches!((o.checked_sub(1).and_then(|i| k.get(i)), k.get(n)), (Some(a), Some(b)) if a < b) +} + +fn good_weights(w: &[f64]) -> bool { + w.iter().all(|&x| x > 0.0) +} + +/// `GoodNurbsCurves`: one family of NURBS curves; with `optional`, a curve of count and order 0 +/// is none. +fn good_nurbs_curves(count: &[i64], order: &[i64], cvs: &[f64], knots: &[f64], weights: &[f64], dim: i64, optional: bool) -> bool { + if count.len() != order.len() { + return false; + } + let (mut points, mut knot_total) = (0i64, 0i64); + for (&c, &o) in count.iter().zip(order) { + if optional && c == 0 && o == 0 { + continue; + } + if !(2..=MAX_ORDER).contains(&o) || c < o || c > MAX_FLAT_LEN { + return false; + } + points += c; + knot_total += c + o; + if points > MAX_FLAT_LEN || knot_total > MAX_FLAT_LEN { + return false; + } + } + if i64::try_from(cvs.len()).ok() != Some(dim * points) || i64::try_from(knots.len()).ok() != Some(knot_total) { + return false; + } + if !weights.is_empty() && (i64::try_from(weights.len()).ok() != Some(points) || !good_weights(weights)) { + return false; + } + let mut k = 0usize; + for (&c, &o) in count.iter().zip(order) { + if optional && c == 0 { + continue; + } + if !knots.get(k..).is_some_and(|s| good_knots(s, c, o)) { + return false; + } + k += (c + o) as usize; + } + true +} + +/// One edge family's arrays (`GoodEdges`, `MakeEdgeCurve`). +struct EdgeIn<'a> { + ty: &'a [i64], + vertices: &'a [i64], + range: &'a [f64], + count: &'a [i64], + order: &'a [i64], + cvs: &'a [f64], + knots: &'a [f64], + weights: &'a [f64], + circle_center: &'a [f64], + circle_axis: &'a [f64], + circle_ref: &'a [f64], + circle_radius: &'a [f64], + line_origin: &'a [f64], + line_direction: &'a [f64], + ellipse_center: &'a [f64], + ellipse_axis: &'a [f64], + ellipse_ref: &'a [f64], + ellipse_x: &'a [f64], + ellipse_y: &'a [f64], + form: &'a [i64], +} + +impl<'a> EdgeIn<'a> { + fn new(f: &In<'a>, ids: &EdgeIds) -> EdgeIn<'a> { + EdgeIn { + ty: f.i(ids.ty), + vertices: f.i(ids.vertices), + range: f.r(ids.range), + count: f.i(ids.count), + order: f.i(ids.order), + cvs: f.r(ids.cvs), + knots: f.r(ids.knots), + weights: f.r(ids.weights), + circle_center: f.r(ids.circle_center), + circle_axis: f.r(ids.circle_axis), + circle_ref: f.r(ids.circle_ref), + circle_radius: f.r(ids.circle_radius), + line_origin: f.r(ids.line_origin), + line_direction: f.r(ids.line_direction), + ellipse_center: f.r(ids.ellipse_center), + ellipse_axis: f.r(ids.ellipse_axis), + ellipse_ref: f.r(ids.ellipse_ref), + ellipse_x: f.r(ids.ellipse_x), + ellipse_y: f.r(ids.ellipse_y), + form: f.i(ids.form), + } + } +} + +/// `GoodEdges`: an edge family's ranges against its curves. +fn good_edges(e: &EdgeIn<'_>, n: usize, n_vertices: usize) -> bool { + // a NURBS form is given for circles and ellipses only, one flag per edge, or for none + if !e.form.is_empty() && (e.form.len() != n || !bits(e.form)) { + return false; + } + if e.form.iter().zip(e.ty).any(|(&f, &t)| f == 1 && t != CURVE_CIRCLE_I && t != CURVE_ELLIPSE_I) { + return false; + } + let Ok(last_vertex) = i64::try_from(n_vertices).map(|v| v - 1) else { return false }; + if e.ty.len() != n + || Some(e.vertices.len()) != n.checked_mul(2) + || Some(e.range.len()) != n.checked_mul(2) + || !in_range(e.ty, CURVE_NURBS_I, CURVE_ELLIPSE_I) + || !in_range(e.vertices, 0, last_vertex) + { + return false; + } + let (mut n_n, mut n_c, mut n_l, mut n_e) = (0usize, 0usize, 0usize, 0usize); + for (i, &t) in e.ty.iter().enumerate() { + n_n += usize::from(t == CURVE_NURBS_I || has_form(e.form, i)); + n_c += usize::from(t == CURVE_CIRCLE_I); + n_l += usize::from(t == CURVE_LINE_I); + n_e += usize::from(t == CURVE_ELLIPSE_I); + } + if e.count.len() != n_n || !good_nurbs_curves(e.count, e.order, e.cvs, e.knots, e.weights, 3, false) { + return false; + } + if e.circle_center.len() != 3 * n_c + || e.circle_axis.len() != 3 * n_c + || e.circle_ref.len() != 3 * n_c + || e.circle_radius.len() != n_c + || e.line_origin.len() != 3 * n_l + || e.line_direction.len() != 3 * n_l + || e.ellipse_center.len() != 3 * n_e + || e.ellipse_axis.len() != 3 * n_e + || e.ellipse_ref.len() != 3 * n_e + || e.ellipse_x.len() != n_e + || e.ellipse_y.len() != n_e + { + return false; + } + for i in 0..n_c { + if !(e.circle_radius.get(i).is_some_and(|&r| r > 0.0)) || !good_frame(e.circle_axis, e.circle_ref, i) { + return false; + } + } + for i in 0..n_l { + if !get3(e.line_direction, i).is_ok_and(|d| d.length() > 1e-12) { + return false; + } + } + for i in 0..n_e { + if !(e.ellipse_x.get(i).is_some_and(|&r| r > 0.0) && e.ellipse_y.get(i).is_some_and(|&r| r > 0.0)) + || !good_frame(e.ellipse_axis, e.ellipse_ref, i) + { + return false; + } + } + // each edge's range: non-empty; inside its NURBS curve's knot interval; at most one turn + // for circles and ellipses (radians) + let (mut i_nurbs, mut knot) = (0usize, 0usize); + for i in 0..n { + let (Some(&lo), Some(&hi)) = (e.range.get(2 * i), e.range.get(2 * i + 1)) else { return false }; + let t = e.ty.get(i).copied().unwrap_or(-1); + if !(lo < hi) { + return false; + } + if t == CURVE_NURBS_I || has_form(e.form, i) { + let (Some(&c), Some(&o)) = (e.count.get(i_nurbs), e.order.get(i_nurbs)) else { return false }; + let (Ok(cu), Ok(ou)) = (usize::try_from(c), usize::try_from(o)) else { return false }; + let (Some(&k0), Some(&k1)) = (e.knots.get(knot + ou - 1), e.knots.get(knot + cu)) else { return false }; + let tol = 1e-9 * (k1 - k0).max(1.0); + if lo < k0 - tol || hi > k1 + tol { + return false; + } + knot += cu + ou; + i_nurbs += 1; + } else if (t == CURVE_CIRCLE_I || t == CURVE_ELLIPSE_I) + && (hi - lo > std::f64::consts::TAU + 1e-9 + || lo.abs() > std::f64::consts::TAU * (1.0 + 1e-9) + || hi.abs() > std::f64::consts::TAU * (1.0 + 1e-9)) + { + return false; // SmCircle/SmEllipse::CreateCanonical take [-360, 360] degrees + } else if t == CURVE_LINE_I && (lo.abs() > INFINITE_PARAMETER || hi.abs() > INFINITE_PARAMETER) { + return false; // an imported line is unbounded over +-SM_INFINITE_PARAMETER + } + } + true +} + +fn face_has_nurbs(f: &In<'_>, i: usize) -> bool { + matches!(f.i(FACE_SURFACE_TYPE).get(i), Some(&(SURFACE_NURBS_I | SURFACE_BALL_PATCH_I))) || has_form(f.i(FACE_NURBS_FORM), i) +} + +/// `Validate`: every check the build relies on; `None` on anything malformed. +fn validate(f: &In<'_>) -> Option { + let mut s = Shape::default(); + // every double is finite and of sane magnitude + if f.0.reals.values().flatten().any(|x| !x.is_finite() || x.abs() > MAX_VALUE) { + return None; + } + + // B-rep data + let tol = f.r(TOLERANCE); + if tol.len() != 1 || !tol.iter().all(|&t| t > 0.0 && t <= 1.0) { + return None; + } + if !f.r(EXTENT).is_empty() && f.r(EXTENT).len() != 6 { + return None; + } + if f.i(SOURCE).len() > 1 || !bits(f.i(SOURCE)) { + return None; + } + + // Regions + s.regions = f.i(REGION_SHELL_COUNT).len(); + let shells = sum_counts(f.i(REGION_SHELL_COUNT))?; + if s.regions < 1 || s.regions > MAX_TOPOLOGY as usize || f.i(REGION_TYPE).len() != s.regions || !bits(f.i(REGION_TYPE)) { + return None; + } + s.shells = shells as usize; + + // Shells: a faceuse shell, a wire-edge shell (one edge) or a point shell + let (fu_count, we_count, pt_type) = (f.i(SHELL_FACEUSE_COUNT), f.i(SHELL_WIRE_EDGE_COUNT), f.i(SHELL_POINT_TYPE)); + if fu_count.len() != s.shells || we_count.len() != s.shells || pt_type.len() != s.shells || !bits(we_count) || !bits(pt_type) { + return None; + } + let faceuses = sum_counts(fu_count)?; + if faceuses % 2 != 0 { + return None; + } + for i in 0..s.shells { + let (fu, we, pt) = (fu_count.get(i)?, we_count.get(i)?, pt_type.get(i)?); + if *fu > 0 { + if *we != 0 { + return None; + } + } else if *we == 0 { + if *pt != 1 { + return None; + } + s.point_shells += 1; + } + } + s.wire_edges = sum_counts(we_count)? as usize; + if f.r(SHELL_POINT_POSITION).len() != 3 * s.point_shells { + return None; + } + + // Faceuses: each face has exactly two, one on each side + s.faceuses = faceuses as usize; + s.faces = s.faceuses / 2; + let (fu_face, fu_orient) = (f.i(FACEUSE_FACE), f.i(FACEUSE_ORIENTATION)); + if fu_face.len() != s.faceuses || fu_orient.len() != s.faceuses || !bits(fu_orient) || !in_range(fu_face, 0, s.faces as i64 - 1) { + return None; + } + let mut sides = vec![0u8; s.faces]; + for (&face, &o) in fu_face.iter().zip(fu_orient) { + let bit = if o == 1 { 1 } else { 2 }; + let side = sides.get_mut(face as usize)?; + if *side & bit != 0 { + return None; + } + *side |= bit; + } + + // Faces + let (loop_count, surface_type, trim_type, range) = (f.i(FACE_LOOP_COUNT), f.i(FACE_SURFACE_TYPE), f.i(FACE_TRIM_TYPE), f.r(FACE_RANGE)); + if loop_count.len() != s.faces + || surface_type.len() != s.faces + || trim_type.len() != s.faces + || range.len() != 4 * s.faces + || !bits(trim_type) + || !in_range(surface_type, SURFACE_NURBS_I, SURFACE_BALL_PATCH_I) + || !in_range(loop_count, 1, MAX_TOPOLOGY) + { + return None; + } + // A ball patch's definition: four reals (its sphere's centre and radius) each, in face order. + let patches = surface_type.iter().filter(|&&t| t == SURFACE_BALL_PATCH_I).count(); + let definitions = f.i(FACE_DEFINITION_REAL_COUNT); + if definitions.len() != patches || definitions.iter().any(|&c| c != 4) || f.r(FACE_DEFINITION_REALS).len() != 4 * patches { + return None; + } + let form = f.i(FACE_NURBS_FORM); + if !form.is_empty() { + if form.len() != s.faces || !bits(form) { + return None; + } + if form.iter().zip(surface_type).any(|(&fm, &t)| fm == 1 && (t == SURFACE_NURBS_I || t == SURFACE_PLANE_I || t == SURFACE_BALL_PATCH_I)) { + return None; + } + } + for i in 0..s.faces { + let (u0, v0, u1, v1) = (*range.get(4 * i)?, *range.get(4 * i + 1)?, *range.get(4 * i + 2)?, *range.get(4 * i + 3)?); + if !(u0 < u1) || !(v0 < v1) { + return None; + } + // angular parameters (radians): at most one turn, near the principal range; a sphere's + // latitude within [-pi/2, pi/2]. A face given with its NURBS form has a NURBS range. + let t = if face_has_nurbs(f, i) { SURFACE_NURBS_I } else { *surface_type.get(i)? }; + let u_angle = t == SURFACE_SPHERE_I || t == SURFACE_TORUS_I || t == SURFACE_CYLINDER_I || t == SURFACE_CONE_I; + let v_angle = t == SURFACE_SPHERE_I || t == SURFACE_TORUS_I; + let pi = std::f64::consts::PI; + let (turn, far) = (2.0 * pi * (1.0 + 1e-9), 4.0 * pi); + if (u_angle && (u1 - u0 > turn || u0.abs() > far || u1.abs() > far)) + || (v_angle && (v1 - v0 > turn || v0.abs() > far || v1.abs() > far)) + || (t == SURFACE_SPHERE_I && (v0 < -0.5 * pi - 1e-9 || v1 > 0.5 * pi + 1e-9)) + { + return None; + } + } + s.loops = sum_counts(loop_count)? as usize; + + // Vertices + s.vertices = f.i(VERTEX_POINT_TYPE).len(); + if s.vertices > MAX_TOPOLOGY as usize + || s.vertices + s.point_shells > MAX_TOPOLOGY as usize + || !in_range(f.i(VERTEX_POINT_TYPE), 1, 1) + || f.r(VERTEX_POSITION).len() != 3 * s.vertices + { + return None; + } + // per-edge and per-vertex tolerances: none, or one each + let tolerances_ok = |t: &[f64], n: usize| t.is_empty() || (t.len() == n && t.iter().all(|&x| x.is_finite() && x > 0.0 && x <= 1.0)); + if !tolerances_ok(f.r(VERTEX_TOLERANCE), s.vertices) { + return None; + } + + // Loops + let (lp_count, lp_vertex) = (f.i(LOOP_EDGEUSE_COUNT), f.i(LOOP_VERTEX)); + if lp_count.len() != s.loops || lp_vertex.len() != s.loops { + return None; + } + s.edgeuses = sum_counts(lp_count)? as usize; + for (&n, &v) in lp_count.iter().zip(lp_vertex) { + if if n == 0 { !(v >= 0 && v < s.vertices as i64) } else { v != -1 } { + return None; + } + } + + // Edges and wire edges + s.edges = f.i(EDGE_CURVE_TYPE).len(); + if s.edges > MAX_TOPOLOGY as usize || s.edges + s.wire_edges > MAX_TOPOLOGY as usize || s.wire_edges + s.edgeuses > MAX_TOPOLOGY as usize { + return None; + } + if !tolerances_ok(f.r(EDGE_TOLERANCE), s.edges) { + return None; + } + if !good_edges(&EdgeIn::new(f, &EDGES), s.edges, s.vertices) || !good_edges(&EdgeIn::new(f, &WIRE_EDGES), s.wire_edges, s.vertices) { + return None; + } + + // Edgeuses + let (eu_edge, eu_orient, eu_next, eu_entry) = (f.i(EDGEUSE_EDGE), f.i(EDGEUSE_ORIENTATION), f.i(EDGEUSE_NEXT_RADIAL), f.i(EDGEUSE_RADIAL_ENTRY)); + if eu_edge.len() != s.edgeuses + || eu_orient.len() != s.edgeuses + || eu_next.len() != s.edgeuses + || eu_entry.len() != s.edgeuses + || !bits(eu_orient) + || !bits(eu_entry) + || !in_range(eu_edge, 0, s.edges as i64 - 1) + || !in_range(eu_next, 0, s.edgeuses as i64 - 1) + { + return None; + } + { + // the radial lists: NEXT_RADIAL is a permutation that stays on each edge and cycles once + // through all of each edge's edgeuses; every edge has at least one edgeuse + let mut per_edge = vec![0i64; s.edges]; + let mut hit = vec![false; s.edgeuses]; + let mut first = vec![-1i64; s.edges]; + for i in 0..s.edgeuses { + let e = *eu_edge.get(i)? as usize; + let n = *eu_next.get(i)? as usize; + if eu_edge.get(n)? != eu_edge.get(i)? || *hit.get(n)? { + return None; + } + *hit.get_mut(n)? = true; + *per_edge.get_mut(e)? += 1; + if *first.get(e)? < 0 { + *first.get_mut(e)? = i as i64; + } + } + for e in 0..s.edges { + let start = *first.get(e)?; + if start < 0 { + return None; + } + let (mut steps, mut cur) = (0i64, start); + loop { + cur = *eu_next.get(cur as usize)?; + steps += 1; + if cur == start || steps > *per_edge.get(e)? { + break; + } + } + if steps != *per_edge.get(e)? { + return None; + } + } + } + + // every vertex is used; every edgeuse loop is a closed chain of its edges' vertices + { + let ev = f.i(EDGE_VERTICES); + let mut used = vec![false; s.vertices]; + for &v in ev.iter().chain(f.i(WIRE_EDGE_VERTICES)) { + *used.get_mut(v as usize)? = true; + } + let mut eu = 0usize; + for l in 0..s.loops { + let n = *lp_count.get(l)? as usize; + if n == 0 { + *used.get_mut(*lp_vertex.get(l)? as usize)? = true; + continue; + } + for k in 0..n { + let (a, b) = (eu + k, eu + (k + 1) % n); + let (ea, eb) = (*eu_edge.get(a)? as usize, *eu_edge.get(b)? as usize); + let end_a = ev.get(2 * ea + usize::from(*eu_orient.get(a)? == 1))?; + let start_b = ev.get(2 * eb + usize::from(*eu_orient.get(b)? != 1))?; + if end_a != start_b { + return None; + } + } + eu += n; + } + if !used.iter().all(|&u| u) { + return None; + } + } + + // UV trim curves: none, or one record per edgeuse + let (uv_count, uv_order) = (f.i(EDGEUSE_NURBS_VERTEX_COUNT), f.i(EDGEUSE_NURBS_ORDER)); + if uv_count.len() != uv_order.len() || (!uv_count.is_empty() && uv_count.len() != s.edgeuses) { + return None; + } + s.uv_curves = !uv_count.is_empty(); + if uv_count.iter().zip(uv_order).any(|(&c, &o)| (c == 0) != (o == 0)) { + return None; + } + if !good_nurbs_curves(uv_count, uv_order, f.r(EDGEUSE_NURBS_CVS), f.r(EDGEUSE_NURBS_KNOTS), f.r(EDGEUSE_NURBS_WEIGHTS), 2, true) { + return None; + } + + // Surfaces + let mut n_t = [0usize; 7]; + for &t in surface_type { + *n_t.get_mut(t as usize)? += 1; + } + let n_n = (0..s.faces).filter(|&i| face_has_nurbs(f, i)).count(); + let [_, n_p, n_cy, n_co, n_s, n_to, _] = n_t; + let (cu_v, cv_v, ou_v, ov_v) = (f.i(FACE_NURBS_U_VERTEX_COUNT), f.i(FACE_NURBS_V_VERTEX_COUNT), f.i(FACE_NURBS_U_ORDER), f.i(FACE_NURBS_V_ORDER)); + if cu_v.len() != n_n || cv_v.len() != n_n || ou_v.len() != n_n || ov_v.len() != n_n { + return None; + } + { + let (uks, vks) = (f.r(FACE_NURBS_U_KNOTS), f.r(FACE_NURBS_V_KNOTS)); + let (mut points, mut uk, mut vk) = (0i64, 0i64, 0i64); + for i in 0..n_n { + let (cu, cv, ou, ov) = (*cu_v.get(i)?, *cv_v.get(i)?, *ou_v.get(i)?, *ov_v.get(i)?); + if !(2..=MAX_ORDER).contains(&ou) + || !(2..=MAX_ORDER).contains(&ov) + || cu < ou + || cv < ov + || cu > MAX_FLAT_LEN + || cv > MAX_FLAT_LEN + || cu * cv > MAX_FLAT_LEN + { + return None; + } + points += cu * cv; + uk += cu + ou; + vk += cv + ov; + if points > MAX_FLAT_LEN || uk > MAX_FLAT_LEN || vk > MAX_FLAT_LEN { + return None; + } + } + if f.r(FACE_NURBS_CVS).len() as i64 != 3 * points || uks.len() as i64 != uk || vks.len() as i64 != vk { + return None; + } + let w = f.r(FACE_NURBS_WEIGHTS); + if !w.is_empty() && (w.len() as i64 != points || !good_weights(w)) { + return None; + } + let (mut uk, mut vk) = (0usize, 0usize); + for i in 0..n_n { + let (cu, cv, ou, ov) = (*cu_v.get(i)?, *cv_v.get(i)?, *ou_v.get(i)?, *ov_v.get(i)?); + if !good_knots(uks.get(uk..)?, cu, ou) || !good_knots(vks.get(vk..)?, cv, ov) { + return None; + } + uk += (cu + ou) as usize; + vk += (cv + ov) as usize; + } + // each NURBS face's range overlaps its surface's knot domain (MakeTopologyFromData + // intersects the two) + let (mut i_n, mut uk, mut vk) = (0usize, 0usize, 0usize); + for i in 0..s.faces { + if !face_has_nurbs(f, i) { + continue; + } + let (cu, cv, ou, ov) = (*cu_v.get(i_n)? as usize, *cv_v.get(i_n)? as usize, *ou_v.get(i_n)? as usize, *ov_v.get(i_n)? as usize); + let (u_lo, u_hi) = (*uks.get(uk + ou - 1)?, *uks.get(uk + cu)?); + let (v_lo, v_hi) = (*vks.get(vk + ov - 1)?, *vks.get(vk + cv)?); + if !(range.get(4 * i + 2)?.min(u_hi) > range.get(4 * i)?.max(u_lo)) + || !(range.get(4 * i + 3)?.min(v_hi) > range.get(4 * i + 1)?.max(v_lo)) + { + return None; + } + uk += cu + ou; + vk += cv + ov; + i_n += 1; + } + } + let lens = |id: i32, n: usize| f.r(id).len() == n; + if !(lens(FACE_PLANE_ORIGIN, 3 * n_p) + && lens(FACE_PLANE_AXIS, 3 * n_p) + && lens(FACE_PLANE_REF_DIRECTION, 3 * n_p) + && lens(FACE_CYLINDER_ORIGIN, 3 * n_cy) + && lens(FACE_CYLINDER_AXIS, 3 * n_cy) + && lens(FACE_CYLINDER_REF_DIRECTION, 3 * n_cy) + && lens(FACE_CYLINDER_RADIUS, n_cy) + && lens(FACE_CONE_ORIGIN, 3 * n_co) + && lens(FACE_CONE_AXIS, 3 * n_co) + && lens(FACE_CONE_REF_DIRECTION, 3 * n_co) + && lens(FACE_CONE_RADIUS, n_co) + && lens(FACE_CONE_SEMI_ANGLE, n_co) + && lens(FACE_SPHERE_CENTER, 3 * n_s) + && lens(FACE_SPHERE_AXIS, 3 * n_s) + && lens(FACE_SPHERE_REF_DIRECTION, 3 * n_s) + && lens(FACE_SPHERE_RADIUS, n_s) + && lens(FACE_TORUS_ORIGIN, 3 * n_to) + && lens(FACE_TORUS_AXIS, 3 * n_to) + && lens(FACE_TORUS_REF_DIRECTION, 3 * n_to) + && lens(FACE_TORUS_MAJOR_RADIUS, n_to) + && lens(FACE_TORUS_MINOR_RADIUS, n_to)) + { + return None; + } + let positive = |id: i32, i: usize| f.r(id).get(i).is_some_and(|&r| r > 0.0); + for i in 0..n_p { + if !good_frame(f.r(FACE_PLANE_AXIS), f.r(FACE_PLANE_REF_DIRECTION), i) { + return None; + } + } + for i in 0..n_cy { + if !positive(FACE_CYLINDER_RADIUS, i) || !good_frame(f.r(FACE_CYLINDER_AXIS), f.r(FACE_CYLINDER_REF_DIRECTION), i) { + return None; + } + } + for i in 0..n_co { + let half = 0.5 * std::f64::consts::PI * (1.0 - 1e-9); + if !f.r(FACE_CONE_RADIUS).get(i).is_some_and(|&r| r >= 0.0) + || !f.r(FACE_CONE_SEMI_ANGLE).get(i).is_some_and(|a| a.abs() < half) + || !good_frame(f.r(FACE_CONE_AXIS), f.r(FACE_CONE_REF_DIRECTION), i) + { + return None; + } + } + for i in 0..n_s { + if !positive(FACE_SPHERE_RADIUS, i) || !good_frame(f.r(FACE_SPHERE_AXIS), f.r(FACE_SPHERE_REF_DIRECTION), i) { + return None; + } + } + for i in 0..n_to { + if !positive(FACE_TORUS_MAJOR_RADIUS, i) + || !positive(FACE_TORUS_MINOR_RADIUS, i) + || !good_frame(f.r(FACE_TORUS_AXIS), f.r(FACE_TORUS_REF_DIRECTION), i) + { + return None; + } + } + Some(s) +} + +// ---- import: FlatToBrepData -------------------------------------------------------------------- + +/// The running read positions in the packed geometry arrays (`Cursor`). +#[derive(Default)] +struct Cursor { + nurbs: usize, + cv: usize, + knot: usize, + vknot: usize, + circle: usize, + line: usize, + ellipse: usize, +} + +/// `smu_IsFlatKnotVectorClamped`: the first and last knots each repeat `degree + 1` times. +fn is_clamped(knots: &[f64], degree: usize) -> bool { + let n = knots.len(); + if n < 2 || degree > (n - 2) / 2 { + return false; + } + let (Some(&first), Some(&last)) = (knots.first(), knots.last()) else { return false }; + (1..=degree).all(|i| knots.get(i) == Some(&first) && knots.get(n - 1 - i) == Some(&last)) +} + +/// `smu_CompressFlatKnots`: the distinct knots and their multiplicities. +fn compress_knots(knots: &[f64]) -> (Vec, Vec) { + let (mut unique, mut mults): (Vec, Vec) = (Vec::new(), Vec::new()); + for &k in knots { + match (unique.last(), mults.last_mut()) { + (Some(&u), Some(m)) if u == k => *m += 1, + _ => { + unique.push(k); + mults.push(1); + } + } + } + (unique, mults) +} + +/// `smu_CreateSmBSplineCurve_FromArrays`: a curve of `dim` 2 or 3; an unclamped knot vector goes +/// through `SmBSplineCurve::CreateCanonical`, which clamps it. +fn bspline_curve_from_arrays(points: &[Point3], weights: &[f64], knots: &[f64], degree: usize, dim: u64) -> Result { + if !is_clamped(knots, degree) { + let (unique, mults) = compress_knots(knots); + let data = CanonicalData { + dim, + degree, + control_points: points, + form: BSplineCurveForm::Unspecified, + knot_multiplicities: &mults, + knots: &unique, + knot_type: KnotType::Unspecified, + weights: Some(weights), + trim: None, + }; + return BSplineCurve::create_canonical(&data).map_err(sc("SmBSplineCurve::CreateCanonical")); + } + let mut pw = Vec::with_capacity(points.len()); + for (p, &w) in points.iter().zip(weights) { + let z = if dim == 3 { if w == 1.0 { p.z } else { w * p.z } } else { NOZ }; + pw.push(if w == 1.0 { CPoint::new(p.x, p.y, z, 1.0) } else { CPoint::new(w * p.x, w * p.y, z, w) }); + } + let nurb = NurbCurve::new(pw, degree, knots.to_vec()).map_err(sc("sm_AllocateNurbCurve"))?; + let mut c = BSplineCurve::new(dim); + c.set_from_gw_nurb(Some(&nurb)).map_err(sc("SmBSplineCurve::SetFromGwNurb"))?; + Ok(c) +} + +/// `smu_CreateSmBSplineSurface_FromArrays`: control points U-major; an unclamped knot vector goes +/// through `SmBSplineSurface::CreateCanonical`. +fn bspline_surface_from_arrays( + points: &[Point3], + weights: &[f64], + u_knots: &[f64], + v_knots: &[f64], + u_degree: usize, + v_degree: usize, +) -> Result { + if !is_clamped(u_knots, u_degree) || !is_clamped(v_knots, v_degree) { + let (uu, um) = compress_knots(u_knots); + let (vu, vm) = compress_knots(v_knots); + let data = CanonicalSurfaceData { + u_degree, + v_degree, + control_points: points, + form: BSplineSurfaceForm::Unspecified, + u_multiplicities: &um, + v_multiplicities: &vm, + u_knots: &uu, + v_knots: &vu, + knot_type: KnotType::Unspecified, + weights: Some(weights), + uv_domain: None, + }; + return BSplineSurface::create_canonical(&data).map_err(sc("SmBSplineSurface::CreateCanonical")); + } + let nu = u_knots.len().checked_sub(u_degree + 1).ok_or_else(|| bad("u knots"))?; + let nv = v_knots.len().checked_sub(v_degree + 1).ok_or_else(|| bad("v knots"))?; + let mut net = Vec::with_capacity(nu); + for i in 0..nu { + let mut row = Vec::with_capacity(nv); + for j in 0..nv { + let at = i * nv + j; + let (p, w) = (get(points, at)?, get(weights, at)?); + row.push(CPoint::new(w * p.x, w * p.y, w * p.z, w)); + } + net.push(row); + } + let nurb = NurbSurface::new(net, u_degree, v_degree, u_knots.to_vec(), v_knots.to_vec()).map_err(sc("sm_AllocateNurbSurface"))?; + Ok(BSplineSurface::from_nurb(nurb, false)) +} + +/// The packed control points `[c, c + n)` of `dim` coordinates (z 0 for 2D) and their weights, +/// all 1 without a weight array. +fn packed_points(cvs: &[f64], weights: &[f64], c: usize, n: usize, dim: usize, reversed: bool) -> Result<(Vec, Vec)> { + let weighted = weights.len() * dim == cvs.len(); + let (mut pts, mut ws) = (Vec::with_capacity(n), Vec::with_capacity(n)); + for j in 0..n { + let src = c + if reversed { n - 1 - j } else { j }; + let p = if dim == 3 { get3(cvs, src)? } else { Vec3::new(get(cvs, 2 * src)?, get(cvs, 2 * src + 1)?, 0.0) }; + pts.push(p); + ws.push(if weighted { get(weights, src)? } else { 1.0 }); + } + Ok((pts, ws)) +} + +/// `smu_CreateSmBSplineCurve3d`: the next NURBS curve of an edge family. +fn bspline_curve_3d(e: &EdgeIn<'_>, c: &mut Cursor) -> Result { + let degree = idx(get(e.order, c.nurbs)? - 1)?; + let n = idx(get(e.count, c.nurbs)?)?; + let n_knots = n + degree + 1; + let (points, weights) = packed_points(e.cvs, e.weights, c.cv, n, 3, false)?; + let knots = e.knots.get(c.knot..c.knot + n_knots).ok_or_else(|| bad("edge knots"))?; + let curve = bspline_curve_from_arrays(&points, &weights, knots, degree, 3); + c.nurbs += 1; + c.cv += n; + c.knot += n_knots; + curve +} + +/// `smu_CreateSmBSplineCurve2d_ForEdgeuseIndex`: edgeuse `k`'s UV trim, reversed onto its edge's +/// direction and its knots mapped affinely onto the edge's range (in SMLib units); `None` when it +/// has none, or its face no NURBS block (an analytic face's trims are rebuilt from the edges). +fn bspline_curve_2d(f: &In<'_>, c: &mut Cursor, k: usize, face_has_nurbs: bool, same: bool) -> Result> { + let (order, n) = (get(f.i(EDGEUSE_NURBS_ORDER), k)?, get(f.i(EDGEUSE_NURBS_VERTEX_COUNT), k)?); + if order == 0 || n == 0 { + return Ok(None); + } + let degree = idx(order - 1)?; + let n = idx(n)?; + let n_knots = n + degree + 1; + let (cv, knot) = (c.cv, c.knot); + c.cv += n; + c.knot += n_knots; + if !face_has_nurbs { + return Ok(None); + } + let (points, weights) = packed_points(f.r(EDGEUSE_NURBS_CVS), f.r(EDGEUSE_NURBS_WEIGHTS), cv, n, 2, !same)?; + // SMLib requires every UV trim to run over its edge's interval: map the knots affinely onto + // the edge's range (degrees for an analytic circle or ellipse) + let e = idx(get(f.i(EDGEUSE_EDGE), k)?)?; + let (mut lo, mut hi) = (get(f.r(EDGE_RANGE), 2 * e)?, get(f.r(EDGE_RANGE), 2 * e + 1)?); + let ty = get(f.i(EDGE_CURVE_TYPE), e)?; + if (ty == CURVE_CIRCLE_I || ty == CURVE_ELLIPSE_I) && !has_form(f.i(EDGE_NURBS_FORM), e) { + lo = radians_to_smlib_degrees(lo); + hi = radians_to_smlib_degrees(hi); + } + let src = f.r(EDGEUSE_NURBS_KNOTS).get(knot..knot + n_knots).ok_or_else(|| bad("trim knots"))?; + let (s_lo, s_hi) = (get(src, degree)?, get(src, n)?); + let scale = (hi - lo) / (s_hi - s_lo); + let mut knots = Vec::with_capacity(n_knots); + for j in 0..n_knots { + let s = if same { get(src, j)? } else { s_lo + s_hi - get(src, n_knots - 1 - j)? }; + knots.push(lo + (s - s_lo) * scale); + } + bspline_curve_from_arrays(&points, &weights, &knots, degree, 2).map(Some) +} + +/// `smu_CreateSmBSplineSurface3d`: the next NURBS face's surface. +fn bspline_surface_3d(f: &In<'_>, c: &mut Cursor) -> Result { + let ud = idx(get(f.i(FACE_NURBS_U_ORDER), c.nurbs)? - 1)?; + let vd = idx(get(f.i(FACE_NURBS_V_ORDER), c.nurbs)? - 1)?; + let nu = idx(get(f.i(FACE_NURBS_U_VERTEX_COUNT), c.nurbs)?)?; + let nv = idx(get(f.i(FACE_NURBS_V_VERTEX_COUNT), c.nurbs)?)?; + let (nuk, nvk, n) = (nu + ud + 1, nv + vd + 1, nu * nv); + let (points, weights) = packed_points(f.r(FACE_NURBS_CVS), f.r(FACE_NURBS_WEIGHTS), c.cv, n, 3, false)?; + let uk = f.r(FACE_NURBS_U_KNOTS).get(c.knot..c.knot + nuk).ok_or_else(|| bad("u knots"))?; + let vk = f.r(FACE_NURBS_V_KNOTS).get(c.vknot..c.vknot + nvk).ok_or_else(|| bad("v knots"))?; + let s = bspline_surface_from_arrays(&points, &weights, uk, vk, ud, vd); + c.nurbs += 1; + c.cv += n; + c.knot += nuk; + c.vknot += nvk; + s +} + +/// `SameNurbs`: equal sizes and orders, knots and weights within rounding, control points within +/// `tol`. +fn same_nurbs(a: &NurbSurface, b: &NurbSurface, tol: f64) -> bool { + let (mut fa, mut fb) = (Out::new(), Out::new()); + if add_bspline_surface(&mut fa, a).is_err() || add_bspline_surface(&mut fb, b).is_err() { + return false; + } + for id in [FACE_NURBS_U_VERTEX_COUNT, FACE_NURBS_V_VERTEX_COUNT, FACE_NURBS_U_ORDER, FACE_NURBS_V_ORDER] { + if fa.i(id) != fb.i(id) { + return false; + } + } + let close = |x: &[f64], y: &[f64], t: f64| x.len() == y.len() && x.iter().zip(y).all(|(a, b)| (a - b).abs() <= t * a.abs().max(1.0)); + close(fa.r(FACE_NURBS_U_KNOTS), fb.r(FACE_NURBS_U_KNOTS), 1e-12) + && close(fa.r(FACE_NURBS_V_KNOTS), fb.r(FACE_NURBS_V_KNOTS), 1e-12) + && close(fa.r(FACE_NURBS_WEIGHTS), fb.r(FACE_NURBS_WEIGHTS), 1e-12) + && close(fa.r(FACE_NURBS_CVS), fb.r(FACE_NURBS_CVS), tol) +} + +/// `AnalyticOfNurbs`: the analytic surface of kind `ty` SMLib's own test finds in `nurbs`, kept +/// only when its NURBS is `nurbs` (the face's trims are in its parameters). +fn analytic_of_nurbs(k: &Kernel, nurbs: &BSplineSurface, ty: i64, tol: f64) -> Result> { + let found: Option = if ty == SURFACE_CONE_I { + answer(Cone::is_nurb_surface_cone(k, nurbs, 1.0)).map_err(sc("SmCone::IsNurbSurfaceCone"))?.flatten().map(Surface::from) + } else if ty == SURFACE_SPHERE_I { + answer(Sphere::is_nurb_surface_sphere(k, nurbs, 1.0)).map_err(sc("SmSphere::IsNurbSurfaceSphere"))?.flatten().map(Surface::from) + } else if ty == SURFACE_CYLINDER_I { + answer(Cone::is_nurb_surface_cylinder(k, nurbs, 1.0)).map_err(sc("SmCylinder::IsNurbSurfaceCylinder"))?.flatten().map(Surface::from) + } else if ty == SURFACE_TORUS_I { + answer(Torus::is_nurb_surface_torus(k, nurbs, 1.0)).map_err(sc("SmTorus::IsNurbSurfaceTorus"))?.flatten().map(Surface::from) + } else { + None + }; + let Some(found) = found else { return Ok(None) }; + let (Some(want), Some(part)) = (nurbs.gw_nurb(), bspline_surface_part(k, &found)?) else { return Ok(None) }; + Ok(part.gw_nurb().is_some_and(|got| same_nurbs(want, got, tol)).then_some(found)) +} + +/// `Placement`: X the reference direction, Y the axis cross it (`SetCanonical`). +fn placement(origin: Point3, z: Vec3, x: Vec3) -> Result { + let mut p = Axis2Placement::default(); + p.set_canonical(origin, x, z.cross(x)).map_err(|_| bad("a frame that spans no plane"))?; + Ok(p) +} + +/// `SameNurbsCurve`: equal counts and orders, knots and weights within rounding, control points +/// within rounding of the curve's size (`smu_AddSmBSplineCurve3d` of each). +fn same_nurbs_curve(a: &NurbCurve, b: &NurbCurve) -> bool { + let arrays = |n: &NurbCurve| { + let (mut count, mut order, mut cvs, mut knots, mut weights) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let o = NurbsOut { count: &mut count, order: &mut order, cvs: &mut cvs, knots: &mut knots, weights: &mut weights }; + add_bspline_curve_3d(n, o).ok().map(|()| (count, order, cvs, knots, weights)) + }; + let (Some((ac, ao, ap, ak, aw)), Some((bc, bo, bp, bk, bw))) = (arrays(a), arrays(b)) else { return false }; + if ac != bc || ao != bo || ap.len() != bp.len() || ak.len() != bk.len() || aw.len() != bw.len() { + return false; + } + let size = ap.iter().fold(1.0_f64, |m, x| m.max(x.abs())); + let near = |x: &[f64], y: &[f64]| x.iter().zip(y).all(|(a, b)| (a - b).abs() <= 1e-12 * a.abs().max(1.0)); + ap.iter().zip(&bp).all(|(a, b)| (a - b).abs() <= 1e-12 * size) && near(&ak, &bk) && near(&aw, &bw) +} + +/// `MakeEdgeCurve` (capi/src/smlib_flat.cpp): one edge's 3D curve, as its kind says; +/// `d_min`/`d_max` its range in SMLib units. A circle or ellipse with its NURBS form (`form`) is that NURBS as the conic of its +/// canonical entry (frame and radii; the domain from `ConicDomainOfNurbs`), keeping that NURBS. +/// A circle's NURBS must pass SMLib's own test (`SmCircle::IsNurbCurveCircle`), whose circle is +/// not the one kept (its frame has its x axis towards the NURBS's start), and the kept circle +/// must hold the same NURBS (`SameNurbsCurve`); either failing is `SM_ERR_INVALID_INPUT`. +fn make_edge_curve(k: &Kernel, ty: i64, d_min: f64, d_max: f64, e: &EdgeIn<'_>, c: &mut Cursor, form: bool) -> Result { + if form { + let circle = ty == CURVE_CIRCLE_I; + let i = if circle { + c.circle += 1; + c.circle - 1 + } else { + c.ellipse += 1; + c.ellipse - 1 + }; + let nurbs = bspline_curve_3d(e, c)?; + let (o, mut z, mut x, rx, ry) = if circle { + let r = get(e.circle_radius, i)?; + (get3(e.circle_center, i)?, get3(e.circle_axis, i)?, get3(e.circle_ref, i)?, r, r) + } else { + (get3(e.ellipse_center, i)?, get3(e.ellipse_axis, i)?, get3(e.ellipse_ref, i)?, get(e.ellipse_x, i)?, get(e.ellipse_y, i)?) + }; + if circle { + let test = Curve::from(nurbs.clone_exact()); + let is_circle = answer(Ellipse::is_nurb_curve_circle(k, &test, None)).map_err(sc("SmCircle::IsNurbCurveCircle"))?.flatten(); + if is_circle.is_none() { + return Err(bad("a circle NURBS SMLib's circle test rejects")); + } + } + let domain = conic_domain_of_nurbs(&nurbs, o, &mut z, &mut x, rx, ry).ok_or_else(|| bad("a conic NURBS off its conic"))?; + let opts = EllipseOptions { dim: 3, nurb: Some(&nurbs), inside_out: false }; + if circle { + let cir = Ellipse::new_circle(k, o, x, z.cross(x), domain, rx, &opts).map_err(sc("SmCircle::SmCircle"))?; + let kept = nurb_of(cir.base())?; + if !nurbs.gw_nurb().is_some_and(|want| same_nurbs_curve(want, kept)) { + return Err(bad("a circle that does not keep its NURBS")); + } + return Ok(Curve::from(cir)); + } + let el = Ellipse::new(k, o, x, z.cross(x), domain, rx, ry, &opts).map_err(sc("SmEllipse::SmEllipse"))?; + return Ok(Curve::from(el)); + } + if ty == CURVE_NURBS_I { + return bspline_curve_3d(e, c).map(Curve::from); + } + if ty == CURVE_CIRCLE_I { + let i = c.circle; + c.circle += 1; + let r = get(e.circle_radius, i)?; + return build_analytic_edge_curve(k, ty, d_min, d_max, get3(e.circle_center, i)?, get3(e.circle_axis, i)?, get3(e.circle_ref, i)?, r, r); + } + if ty == CURVE_LINE_I { + let i = c.line; + c.line += 1; + let zero = Vec3::new(0.0, 0.0, 0.0); + return build_analytic_edge_curve(k, ty, d_min, d_max, get3(e.line_origin, i)?, get3(e.line_direction, i)?, zero, 0.0, 0.0); + } + let i = c.ellipse; + c.ellipse += 1; + build_analytic_edge_curve( + k, + ty, + d_min, + d_max, + get3(e.ellipse_center, i)?, + get3(e.ellipse_axis, i)?, + get3(e.ellipse_ref, i)?, + get(e.ellipse_x, i)?, + get(e.ellipse_y, i)?, + ) +} + +/// `ConicDomainOfNurbs`: the domain in degrees of the conic (centre `o`, axis `z`, reference `x`, +/// radii `rx`, `ry`) the NURBS traces, `z` and `x` made an orthonormal frame; `None` when a point +/// is off that conic or the NURBS turns clockwise about `z`. +fn conic_domain_of_nurbs(nurbs: &BSplineCurve, o: Point3, z: &mut Vec3, x: &mut Vec3, rx: f64, ry: f64) -> Option { + *z = z.unitize().ok()?; + *x = (*x - *z * x.dot(*z)).unitize().ok()?; + if !(rx > 0.0 && ry > 0.0) { + return None; + } + let y = z.cross(*x); + let ivl = nurbs.natural_interval(); + let angle = |t: f64| -> Option { + let p = nurbs.evaluate_point(t).ok()?; + let d = p - o; + let (u, v) = (d.dot(*x) / rx, d.dot(y) / ry); + let on = ((u.hypot(v)) - 1.0).abs() <= 1e-9 && d.dot(*z).abs() <= 1e-9 * (1.0 + rx + ry); + on.then(|| v.atan2(u) * 180.0 / std::f64::consts::PI) + }; + let n = 16; + let (mut a0, mut prev) = (0.0, 0.0); + for step in 0..=n { + let a = angle(ivl.min() + (ivl.max() - ivl.min()) * f64::from(step) / f64::from(n))?; + if step == 0 { + a0 = a; + } else if !(ieee_remainder(a - prev, 360.0) > 0.0) { + return None; + } + prev = a; + } + let mut sweep = (prev - a0 + 720.0) % 360.0; + if sweep <= 1e-9 { + sweep = 360.0; + } + if a0 + sweep > 360.0 { Some(Extent1d::from_raw(a0 - 360.0, a0 - 360.0 + sweep)) } else { Some(Extent1d::from_raw(a0, a0 + sweep)) } +} + +/// `std::remainder`: `x - n * y` with `n` the integer nearest `x / y`, ties to even. +fn ieee_remainder(x: f64, y: f64) -> f64 { + let q = x / y; + let mut n = q.round(); + if (q - q.trunc()).abs() == 0.5 && n % 2.0 != 0.0 { + n -= q.signum(); + } + x - n * y +} + +/// `FlatToBrepData`: the validated arrays as `SmBrepData`. Edges are `[face edges, wire edges]`, +/// vertices `[point-shell vertices, vertices]`, edgeuses `[wire edgeuses, face edgeuses]`. +fn flat_to_brep_data(k: &Kernel, f: &In<'_>, s: &Shape) -> Result { + let xsect = get(f.r(TOLERANCE), 0)?; + let zone = xsect / 2.0; + let mut d = BrepData::new(UNSURE, DataSourceType::default()); + d.data_source_type = DataSourceType::Usd; + d.zone_tol_3d = zone; + d.approx_tol_3d = xsect / 4.0; + d.start_region = 0; + d.num_regions = s.regions as u64; + d.color = Vec3::new(0.0, 0.0, 0.0); + d.is_geom_borrowed = false; + let mut next_key = 1u64; + let mut key = || { + next_key += 1; + ObjectKey(next_key - 1) + }; + let (n_edges, n_wire, n_point) = (s.edges as u64, s.wire_edges as u64, s.point_shells as u64); + let undefined = |t: &mut solidcore::topology::brep_data::TopologyData| { + t.flags = 0; + t.user_index1 = 0; + t.user_index2 = 0; + }; + + // Regions + let mut start_shell = 0u64; + for i in 0..s.regions { + let mut r = RegionData::default(); + r.start_shell = start_shell; + r.num_shells = get(f.i(REGION_SHELL_COUNT), i)? as u64; + r.is_void = i32::from(get(f.i(REGION_TYPE), i)? == 1); + undefined(&mut r.topology); + start_shell += r.num_shells; + d.regions.push(r); + } + + // Shells, the wire edges' edgeuses (first in the edgeuse list) and point-shell vertices + let mut faceuse_start = 0u64; + let mut wire = 0u64; + let mut point = 0usize; + for i in 0..s.shells { + let mut sd = ShellData::default(); + let (n_fu, n_we) = (get(f.i(SHELL_FACEUSE_COUNT), i)? as u64, get(f.i(SHELL_WIRE_EDGE_COUNT), i)? as u64); + sd.shell_type = if n_fu > 0 { + 0 + } else if n_we > 0 { + 1 + } else { + 2 + }; + sd.num_faceuses = 0; + undefined(&mut sd.topology); + if n_fu > 0 { + sd.faceuse_start = faceuse_start; + sd.num_faceuses = n_fu; + faceuse_start += n_fu; + } + if n_we > 0 { + sd.edge = wire + n_edges; + for _ in 0..n_we { + let mut eu = EuData::default(); + eu.eu_type = 2; + eu.edge = n_edges + wire; + eu.shell = i as u64; + eu.orientation = 1; + undefined(&mut eu.topology); + eu.mate_flags = 0; + eu.mate_user_index1 = 0; + eu.mate_user_index2 = 0; + eu.uv_curve = NO_OBJECT; + d.edgeuses.push(eu); + wire += 1; + } + } + if sd.shell_type == 2 { + sd.vertex = point as u64; + let mut v = VertexData::default(); + v.zone_tol_3d = zone; + undefined(&mut v.topology); + v.point = get3(f.r(SHELL_POINT_POSITION), point)?; + d.vertices.push(v); + point += 1; + } + d.shells.push(sd); + } + + // Faceuses + for i in 0..s.faceuses { + let mut fu = FaceuseData::default(); + fu.face = get(f.i(FACEUSE_FACE), i)? as u64; + fu.orientation = i32::from(get(f.i(FACEUSE_ORIENTATION), i)? == 1); + undefined(&mut fu.topology); + d.faceuses.push(fu); + } + + // Faces and their surfaces + let mut start_loop = 0u64; + let mut nurbs_cursor = Cursor::default(); + let (mut i_sphere, mut i_plane, mut i_cyl, mut i_cone, mut i_torus, mut i_ball) = (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); + for i in 0..s.faces { + let ty = get(f.i(FACE_SURFACE_TYPE), i)?; + let form = ty != SURFACE_NURBS_I && ty != SURFACE_BALL_PATCH_I && face_has_nurbs(f, i); + // "rectangular" -> TRUE; "general" -> UNSURE (not determined) + let rectangular = if get(f.i(FACE_TRIM_TYPE), i)? == 1 { 1 } else { UNSURE }; + let r = f.r(FACE_RANGE); + let (mut u0, mut v0, mut u1, mut v1) = (get(r, 4 * i)?, get(r, 4 * i + 1)?, get(r, 4 * i + 2)?, get(r, 4 * i + 3)?); + // analytic angles: radians to SMLib's degrees (a NURBS form's range is its own) + if !form { + if ty == SURFACE_SPHERE_I || ty == SURFACE_TORUS_I { + (u0, v0, u1, v1) = + (radians_to_smlib_degrees(u0), radians_to_smlib_degrees(v0), radians_to_smlib_degrees(u1), radians_to_smlib_degrees(v1)); + } else if ty == SURFACE_CYLINDER_I || ty == SURFACE_CONE_I { + (u0, u1) = (radians_to_smlib_degrees(u0), radians_to_smlib_degrees(u1)); + } + } + let mut domain = extent2d(u0, v0, u1, v1)?; + let mut fd = FaceData::default(); + fd.zone_tol_3d = zone; + fd.surface = d.surfaces.len() as u64; + fd.start_loop = start_loop; + fd.num_loops = get(f.i(FACE_LOOP_COUNT), i)? as u64; + fd.uv_domain = domain; + fd.rectangular_trim = rectangular; + undefined(&mut fd.topology); + + let mut surface: Surface = if form { + // an analytic face with its NURBS form: that NURBS as the class the arrays name + i_sphere += usize::from(ty == SURFACE_SPHERE_I); + i_cyl += usize::from(ty == SURFACE_CYLINDER_I); + i_cone += usize::from(ty == SURFACE_CONE_I); + i_torus += usize::from(ty == SURFACE_TORUS_I); + let nurbs = bspline_surface_3d(f, &mut nurbs_cursor)?; + analytic_of_nurbs(k, &nurbs, ty, xsect)?.ok_or_else(|| bad("a NURBS form that is not its analytic surface"))? + } else if ty == SURFACE_SPHERE_I { + let j = i_sphere; + i_sphere += 1; + let p = placement(get3(f.r(FACE_SPHERE_CENTER), j)?, get3(f.r(FACE_SPHERE_AXIS), j)?, get3(f.r(FACE_SPHERE_REF_DIRECTION), j)?)?; + Surface::from(Sphere::create_canonical(k, &p, get(f.r(FACE_SPHERE_RADIUS), j)?).map_err(sc("SmSphere::CreateCanonical"))?) + } else if ty == SURFACE_PLANE_I { + let j = i_plane; + i_plane += 1; + let p = placement(get3(f.r(FACE_PLANE_ORIGIN), j)?, get3(f.r(FACE_PLANE_AXIS), j)?, get3(f.r(FACE_PLANE_REF_DIRECTION), j)?)?; + // its domain is restricted below without changing its parameterisation + Surface::from(Plane::create_canonical(&p).map_err(sc("SmPlane::CreateCanonical"))?) + } else if ty == SURFACE_CYLINDER_I { + let j = i_cyl; + i_cyl += 1; + let p = placement(get3(f.r(FACE_CYLINDER_ORIGIN), j)?, get3(f.r(FACE_CYLINDER_AXIS), j)?, get3(f.r(FACE_CYLINDER_REF_DIRECTION), j)?)?; + Surface::from(Cone::create_canonical_cylinder(k, &p, get(f.r(FACE_CYLINDER_RADIUS), j)?).map_err(sc("SmCylinder::CreateCanonical"))?) + } else if ty == SURFACE_CONE_I { + let j = i_cone; + i_cone += 1; + let mut origin = get3(f.r(FACE_CONE_ORIGIN), j)?; + let mut z = get3(f.r(FACE_CONE_AXIS), j)?; + let x = get3(f.r(FACE_CONE_REF_DIRECTION), j)?; + let radius = get(f.r(FACE_CONE_RADIUS), j)?; + let mut semi = rad2deg(get(f.r(FACE_CONE_SEMI_ANGLE), j)?); + // a negative semi-angle is the same cone with its axis and both parameters reversed + if semi < 0.0 { + semi = -semi; + z = Vec3::new(-z.x, -z.y, -z.z); + domain = extent2d(-domain.u_max(), -domain.v_max(), -domain.u_min(), -domain.v_min())?; + } + let mut cone = None; + if domain.is_bounded() { + // the finite segment, built at its bottom and its axial parameter then [0, height] + let (vmin, vmax) = (domain.v_min(), domain.v_max()); + let height = vmax - vmin; + let tan = deg2rad(semi).tan(); + let (bottom, top) = (radius + vmin * tan, radius + vmax * tan); + if height > EFF_ZERO && bottom >= -EFF_ZERO && top >= -EFF_ZERO { + origin += z * vmin; + let p = placement(origin, z, x)?; + cone = Some( + Cone::create_canonical(k, &p, bottom.max(0.0), top.max(0.0), height, false, false).map_err(sc("SmCone::CreateCanonical")), + ); + domain = extent2d(domain.u_min(), 0.0, domain.u_max(), height)?; + } + } else { + let p = placement(origin, z, x)?; + cone = Some(Cone::create_canonical_with_semi_angle(k, &p, radius, semi, None, false, false).map_err(sc("SmCone::CreateCanonical"))); + } + Surface::from(cone.ok_or_else(|| bad("a cone segment through its apex"))??) + } else if ty == SURFACE_TORUS_I { + let j = i_torus; + i_torus += 1; + let p = placement(get3(f.r(FACE_TORUS_ORIGIN), j)?, get3(f.r(FACE_TORUS_AXIS), j)?, get3(f.r(FACE_TORUS_REF_DIRECTION), j)?)?; + let (major, minor) = (get(f.r(FACE_TORUS_MAJOR_RADIUS), j)?, get(f.r(FACE_TORUS_MINOR_RADIUS), j)?); + Surface::from(Torus::create_canonical(k, &p, major, minor, TorusOptions::default(), None).map_err(sc("SmTorus::CreateCanonical"))?) + } else if ty == SURFACE_BALL_PATCH_I { + // its net, on the sphere of its definition (`SmBallPatch::Create`) + let j = i_ball; + i_ball += 1; + let net = bspline_surface_3d(f, &mut nurbs_cursor)?; + let reals = f.r(FACE_DEFINITION_REALS); + let at = |c: usize| j.checked_mul(4).and_then(|x| x.checked_add(c)).map_or_else(|| Err(bad("index past its array")), |x| get(reals, x)); + let (centre, radius) = (Point3::new(at(0)?, at(1)?, at(2)?), at(3)?); + Surface::from(BallPatch::create(&net, centre, radius).map_err(sc("SmBallPatch::Create"))?) + } else { + Surface::from(bspline_surface_3d(f, &mut nurbs_cursor)?) + }; + + // An analytic surface over its STEP range, and the face's domain its NURBS image (the + // natural domain the topology build intersects with). + if ty != SURFACE_NURBS_I && ty != SURFACE_BALL_PATCH_I && !form && domain.is_bounded() { + surface.adjust_step_uv_domain(k, &domain).map_err(sc("AdjustSTEPUVDomain"))?; + let nurbs_domain = surface.convert_domain_from_step_to_nurbs(k, &domain).map_err(sc("ConvertDomainFromSTEPToNURBS"))?; + fd.uv_domain = extent2d(nurbs_domain.u_min(), nurbs_domain.v_min(), nurbs_domain.u_max(), nurbs_domain.v_max())?; + } + d.surfaces.push(Keyed { key: key(), object: surface }); + start_loop += fd.num_loops; + d.faces.push(fd); + } + + // Loops; each edgeuse's loop and face follow from the loop counts + let mut eu_loop = vec![0u64; s.edgeuses]; + let mut eu_face = vec![0usize; s.edgeuses]; + // (face, vertex) of each vertex loop + let mut loop_vertices = Vec::new(); + { + let mut next_eu = n_wire; + let (mut eu, mut face) = (0usize, 0usize); + let mut face_loop_end = if s.faces > 0 { get(f.i(FACE_LOOP_COUNT), 0)? as usize } else { 0 }; + for l in 0..s.loops { + while l >= face_loop_end && face + 1 < s.faces { + face += 1; + face_loop_end += get(f.i(FACE_LOOP_COUNT), face)? as usize; + } + let n_eu = get(f.i(LOOP_EDGEUSE_COUNT), l)? as u64; + let mut ld = LoopData::default(); + ld.loop_type = if n_eu > 0 { 0 } else { 1 }; + ld.num_eu = n_eu; + undefined(&mut ld.topology); + if n_eu > 0 { + ld.start_eu = next_eu; + next_eu += n_eu; + for _ in 0..n_eu { + *eu_loop.get_mut(eu).ok_or_else(|| bad("edgeuse count"))? = l as u64; + *eu_face.get_mut(eu).ok_or_else(|| bad("edgeuse count"))? = face; + eu += 1; + } + } else { + // no SmEUData for a loop vertex + ld.vertex = n_point + get(f.i(LOOP_VERTEX), l)? as u64; + loop_vertices.push((face, ld.vertex)); + } + d.loops.push(ld); + } + } + + // Edgeuses (face edges; the wire edges' came with their shells) + let mut prim_eu = vec![NO_OBJECT as i64; s.edges]; + let mut uv_cursor = Cursor::default(); + let (eu_next, eu_entry) = (f.i(EDGEUSE_NEXT_RADIAL), f.i(EDGEUSE_RADIAL_ENTRY)); + for kk in 0..s.edgeuses { + let here = (n_wire + kk as u64) as i64; + let next = idx(get(eu_next, kk)?)?; + let next_index = (n_wire as i64) + next as i64; + let this_top = get(eu_entry, kk)? == 1; + let next_top = get(eu_entry, next)? == 1; + let next_flag = if next_top { next_index } else { -next_index - 1 }; + let same = get(f.i(EDGEUSE_ORIENTATION), kk)? == 1; + let mut eu = EuData::default(); + eu.eu_type = 0; + eu.edge = get(f.i(EDGEUSE_EDGE), kk)? as u64; + eu.loop_ = get(&eu_loop, kk)?; + eu.orientation = i32::from(same); + eu.downward_lu = false; + undefined(&mut eu.topology); + // topEntry: top -> bottom -> next; bottomEntry: bottom -> top -> next + if this_top { + eu.next_eu = -here - 1; + eu.mate_next_eu = next_flag; + } else { + eu.next_eu = next_flag; + eu.mate_next_eu = here; + } + eu.uv_curve = NO_OBJECT; + if s.uv_curves + && let Some(trim) = bspline_curve_2d(f, &mut uv_cursor, kk, face_has_nurbs(f, get(&eu_face, kk)?), same)? + { + eu.uv_curve = d.uv_curves.len() as u64; + d.uv_curves.push(Keyed { key: key(), object: Curve::from(trim) }); + } + // the primary edgeuse is the first on the radial list (its mate the second) + let slot = prim_eu.get_mut(index_u64(eu.edge)?).ok_or_else(|| bad("edgeuse edge"))?; + if *slot == NO_OBJECT as i64 { + *slot = if this_top { here } else { -here - 1 }; + } + d.edgeuses.push(eu); + } + + // Edges, then wire edges + for (family, n, offset) in [(&EDGES, s.edges, 0u64), (&WIRE_EDGES, s.wire_edges, n_edges)] { + let e = EdgeIn::new(f, family); + let tolerances = if offset == 0 { f.r(EDGE_TOLERANCE) } else { &[] }; + let mut c = Cursor::default(); + for i in 0..n { + let mut ed = EdgeData::default(); + ed.zone_tol_3d = if tolerances.is_empty() { zone } else { get(tolerances, i)? / 2.0 }; + let ty = get(e.ty, i)?; + let form = has_form(e.form, i); + let (mut lo, mut hi) = (get(e.range, 2 * i)?, get(e.range, 2 * i + 1)?); + // circle and ellipse ranges are radians; SMLib's circles and ellipses take degrees + if !form && (ty == CURVE_CIRCLE_I || ty == CURVE_ELLIPSE_I) { + (lo, hi) = (radians_to_smlib_degrees(lo), radians_to_smlib_degrees(hi)); + } + if !(lo <= hi) { + return Err(bad("edge range")); + } + ed.interval = Extent1d::from_raw(lo, hi); + ed.curve = d.curves_3d.len() as u64; + ed.start_vertex = n_point + get(e.vertices, 2 * i)? as u64; + ed.end_vertex = n_point + get(e.vertices, 2 * i + 1)? as u64; + // a wire edge's edgeuse index is its index among the wire edges + ed.prim_eu = if offset == 0 { get(&prim_eu, i)? } else { i as i64 }; + undefined(&mut ed.topology); + let curve = make_edge_curve(k, ty, lo, hi, &e, &mut c, form)?; + d.curves_3d.push(Keyed { key: key(), object: curve }); + d.edges.push(ed); + } + } + + // Vertices + for v in 0..s.vertices { + let mut vd = VertexData::default(); + vd.zone_tol_3d = match f.r(VERTEX_TOLERANCE) { + [] => zone, + t => get(t, v)? / 2.0, + }; + undefined(&mut vd.topology); + vd.point = get3(f.r(VERTEX_POSITION), v)?; + d.vertices.push(vd); + } + own_tolerances(&mut d, f, &eu_face, &loop_vertices, n_point)?; + Ok(d) +} + +/// The B-rep's and each face's tolerance from the edges' and vertices' own, when the arrays carry +/// them. TOLERANCE is the largest tolerance in arrays SMLib writes, and MakeTopologyFromData +/// raises every entity to the B-rep's: taken as the B-rep's, it would become every entity's, and +/// each crossing between the kernels spread the largest over the whole body. Each written edge or +/// vertex tolerance is at least the B-rep's and its faces' (`ZoneTolWithFaces`), so the B-rep's is +/// at most the least of them and a face's at most the least of its edges' and loop vertices'. +fn own_tolerances(d: &mut BrepData, f: &In<'_>, eu_face: &[usize], loop_vertices: &[(usize, u64)], n_point: u64) -> Result<()> { + if f.r(EDGE_TOLERANCE).is_empty() || f.r(VERTEX_TOLERANCE).is_empty() { + return Ok(()); + } + let zone = d.zone_tol_3d; + let mut faces = vec![f64::INFINITY; d.faces.len()]; + let mut lower = |face: usize, t: f64| -> Result<()> { + let slot = faces.get_mut(face).ok_or_else(|| bad("edgeuse face"))?; + *slot = slot.min(t); + Ok(()) + }; + for (kk, &face) in eu_face.iter().enumerate() { + let edge = index_u64(get(f.i(EDGEUSE_EDGE), kk)? as u64)?; + lower(face, d.edges.get(edge).ok_or_else(|| bad("edgeuse edge"))?.zone_tol_3d)?; + } + for &(face, vertex) in loop_vertices { + lower(face, d.vertices.get(index_u64(vertex)?).ok_or_else(|| bad("loop vertex"))?.zone_tol_3d)?; + } + let face_edges = d.edges.len().min(f.r(EDGE_TOLERANCE).len()); + let own_vertices = d.vertices.iter().skip(index_u64(n_point)?).map(|v| v.zone_tol_3d); + let least = d.edges.iter().take(face_edges).map(|e| e.zone_tol_3d).chain(own_vertices).fold(zone, f64::min); + if !(least.is_finite() && least > 0.0) { + return Ok(()); + } + d.zone_tol_3d = least; + for (fd, t) in d.faces.iter_mut().zip(faces) { + fd.zone_tol_3d = if t.is_finite() { t.min(zone) } else { zone }; + } + Ok(()) +} + +/// An `SmExtent2d` with its ends in order (`Set`, `SetMinMax`). +fn extent2d(u0: f64, v0: f64, u1: f64, v1: f64) -> Result { + if !(u0 <= u1 && v0 <= v1) { + return Err(bad("a domain with its ends reversed")); + } + Ok(Extent2d::from_bounds(u0, v0, u1, v1)) +} + +/// A body from the flat arrays the C API imports (`BrepFromFlat`): `Validate`, +/// `FlatToBrepData`, then `MakeTopologyFromData` with the B-rep's tolerance as it is ([`own_tolerances`]) and no UV +/// trims or analytic conversion made; it heals unless `SOURCE` says SMLib wrote the arrays. +pub(crate) fn from_arrays(a: &Arrays) -> Result { + let f = In(a); + let s = validate(&f).ok_or(Error::Record(crate::import::Unsupported::Invalid("flat arrays")))?; + let b = run("BrepFromFlat", |k| Ok(brep_from_flat(k, &f, &s)))??; + Ok(Body::new(b)) +} + +fn brep_from_flat(k: &mut Kernel, f: &In<'_>, s: &Shape) -> Result { + let mut data = flat_to_brep_data(k, f, s)?; + // no heal for B-reps SMLib wrote + let trusted = f.i(SOURCE).first() == Some(&1); + data.set_healer_version(if trusted { HEALER_VERSION } else { HEALER_VERSION - 2 }); + let mut b = Brep::new_with_infinite_region().map_err(sc("SmBrep::SmBrep"))?; + let mut store = AttributeStore::default(); + let mut records = NotifyRecords::new(); + let next_key = (data.uv_curves.len() + data.curves_3d.len() + data.surfaces.len()) as u64 + 1; + let mut env = TopologyEnv { all_attributes: &[], attributes: &mut store, key_of: &key_of, records: &mut records, next_key }; + let options = MakeTopologyOptions { + make_uv_trim_curves: false, + add_analytics: false, + force_same_tol: true, + check_uv_trim_curves: false, + always_heal: false, + healer_enabled: true, + }; + make_topology_from_data(k, &mut b, &mut data, &mut env, options).map_err(sc("SmBrep::MakeTopologyFromData"))?; + put_enclosing_shells_first(k, &mut b)?; + Ok(b) +} + +/// The most `SmShell::IsInnerShellOf` calls one conversion makes; a body that would need more +/// is refused instead of ray casting without end. +const MAX_CONTAINMENT_TESTS: usize = 1 << 16; + +/// `PutEnclosingShellsFirst` (capi `smlib_flat.cpp`): SMLib takes the first shell of every region +/// but the infinite one as the shell that encloses the region, the others lying inside it +/// (`SmBrep::AssertValid` test 12). The arrays may list a region's shells in any order, so the one +/// that encloses all the others is put first, decided by `SmShell::IsInnerShellOf` +/// ([`shell::is_inner_shell_of`]). Candidates are the closed face-use shells whose bounding box +/// can be computed, largest box first (a stable sort: equal boxes keep the arrays' order). Only +/// `SM_TRUE` counts as inside: `SM_FALSE` and `SM_UNSURE` rule the candidate out, as the capi's +/// `== TRUE`, and a region where no candidate is shown to enclose the others keeps its order. +/// solidcore errors the C++ has no counterpart for (a call without a port, a dangling id) refuse +/// the conversion, as does a body needing more than [`MAX_CONTAINMENT_TESTS`] containment tests. +fn put_enclosing_shells_first(k: &mut Kernel, b: &mut Brep) -> Result<()> { + use solidcore::query::face::p1::calculate_shell_bounding_box; + let infinite = b.infinite_region(); + let mut tests = 0usize; + for r in bl::regions(b, None).map_err(sc("GetRegions"))? { + if Some(r) == infinite { + continue; + } + let shells = b.region(r).map_err(sc("GetShells"))?.shells.clone(); + if shells.len() < 2 { + continue; + } + let mut candidates: Vec<(f64, ShellId)> = Vec::new(); + for &s in &shells { + let rec = b.shell(s).map_err(sc("GetShells"))?; + if !rec.is_faceuse_shell() || !rec.is_closed(b, s).map_err(sc("SmShell::IsClosed"))? { + continue; + } + match calculate_shell_bounding_box(k, b, s, false) { + Ok(bx) => { + let size = bx.size(); + candidates.push((size.x * size.y * size.z, s)); + } + Err(e) if e.is_unported() => return Err(sc("SmShell::CalculateBoundingBox")(e)), + // != SM_SUCCESS: not a candidate + Err(_) => {} + } + } + // stable: equal boxes keep the arrays' order + candidates.sort_by(|a, c| c.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); + for &(_, candidate) in &candidates { + let mut encloses = true; + for &s in &shells { + if s == candidate { + continue; + } + tests += 1; + if tests > MAX_CONTAINMENT_TESTS { + return Err(bad("too many shells to order (SmShell::IsInnerShellOf)")); + } + if shell::is_inner_shell_of(k, b, s, Some(candidate)).map_err(sc("SmShell::IsInnerShellOf"))? != shell::SM_TRUE { + encloses = false; + break; + } + } + if encloses { + // SmRegion::SetList(candidate): the circular list now starts at it + let list = &mut b.region_mut(r).map_err(sc("SmRegion::SetList"))?.shells; + if let Some(at) = list.iter().position(|&s| s == candidate) { + list.rotate_left(at); + } + break; + } + } + } + Ok(()) +} diff --git a/crates/smlib/src/core/convert_tests.rs b/crates/smlib/src/core/convert_tests.rs new file mode 100644 index 000000000..847f14392 --- /dev/null +++ b/crates/smlib/src/core/convert_tests.rs @@ -0,0 +1,284 @@ +//! solidcore's primitives through the flat arrays: each exports to a valid record of the right +//! volume, and the record comes back to an equal body. A body with a sealed void crosses with each region's enclosing shell first, +//! whatever order its arrays list the shells in (the capi's `PutEnclosingShellsFirst`). + +use std::f64::consts::PI; + +use solidcore_record::brep as b; + +use super::boolean::boolean; +use super::{Body, from_arrays, make_box, make_cone, make_cylinder, make_sphere, make_torus, to_arrays, volume}; +use crate::BooleanOp; +use crate::export::native; +use crate::import::{self, Arrays}; + +/// A primitive: solidcore's body and its analytic volume. +struct Case { + body: Body, + volume: f64, +} + +fn case(name: &str) -> Case { + let (body, volume) = match name { + "box" => (make_box([1.0, -2.0, 3.0], [10.0, 20.0, 30.0]), 6000.0), + "cylinder" => (make_cylinder([1.0, 2.0, -3.0], 5.0, 12.0), PI * 25.0 * 12.0), + "sphere" => (make_sphere([1.0, 2.0, 3.0], 7.0), 4.0 / 3.0 * PI * 343.0), + "cone" => (make_cone([0.0, 1.0, 2.0], 6.0, 0.0, 9.0), PI * 36.0 * 9.0 / 3.0), + "frustum" => (make_cone([0.0, 1.0, 2.0], 6.0, 2.0, 9.0), PI * 9.0 / 3.0 * (36.0 + 12.0 + 4.0)), + "torus" => (make_torus([1.0, -1.0, 0.5], 10.0, 3.0), 2.0 * PI * PI * 10.0 * 9.0), + _ => panic!("{name}"), + }; + Case { body: body.unwrap(), volume } +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +/// The record of solidcore's arrays, validated and its geometry checked. +fn record(a: &Arrays) -> b::Brep { + let (rec, _) = native(a).unwrap(); + solidcraft_geom::brep::check::validate(&rec).unwrap(); + solidcraft_geom::brep::geometry::check(&rec).unwrap(); + rec +} + +/// Every number in `a` within `tol` (relative past 1) of `b`'s, everything else equal. +fn close(a: &serde_json::Value, b: &serde_json::Value, tol: f64, at: &str) { + use serde_json::Value as V; + match (a, b) { + (V::Number(x), V::Number(y)) => { + let (x, y) = (x.as_f64().unwrap(), y.as_f64().unwrap()); + assert!((x - y).abs() <= tol * x.abs().max(1.0), "{at}: {x} vs {y}"); + } + (V::Array(x), V::Array(y)) => { + assert_eq!(x.len(), y.len(), "{at}: length"); + for (i, (x, y)) in x.iter().zip(y).enumerate() { + close(x, y, tol, &format!("{at}[{i}]")); + } + } + (V::Object(x), V::Object(y)) => { + assert_eq!(x.keys().collect::>(), y.keys().collect::>(), "{at}: keys"); + for (k, x) in x { + close(x, &y[k], tol, &format!("{at}.{k}")); + } + } + _ => assert_eq!(a, b, "{at}"), + } +} + +/// to_arrays gives a record that validates and whose geometry checks. +fn exports(name: &str) { + record(&to_arrays(&case(name).body).unwrap()); +} + +/// solidcore's body measures its analytic volume. +fn measures(name: &str) { + let c = case(name); + let v = volume(&c.body, 1e-8).unwrap(); + assert!(rel(v, c.volume) < 1e-9, "{name}: solidcore volume {v} vs {}", c.volume); +} + +/// record -> arrays -> from_arrays -> to_arrays -> record is the record, the volume exact. +fn round_trips(name: &str) { + let c = case(name); + let rec = record(&to_arrays(&c.body).unwrap()); + let back = from_arrays(&import::arrays(&rec, true).unwrap()).unwrap(); + let again = record(&to_arrays(&back).unwrap()); + close(&serde_json::to_value(&rec).unwrap(), &serde_json::to_value(&again).unwrap(), 1e-12, name); + let v = volume(&back, 1e-8).unwrap(); + assert!(rel(v, c.volume) < 1e-9, "{name}: {v} vs {}", c.volume); +} + +macro_rules! primitive { + ($m:ident, $name:literal $(, volume: $vol:meta)? $(, round_trip: $rt:meta)?) => { + mod $m { + #[test] + fn exports_a_valid_record() { + super::exports($name); + } + #[test] + $(#[$vol])? + fn measures_its_volume() { + super::measures($name); + } + #[test] + $(#[$rt])? + fn round_trips_through_the_record() { + super::round_trips($name); + } + } + }; +} + +primitive!(box_, "box"); +primitive!(cylinder, "cylinder"); +primitive!(sphere, "sphere"); +primitive!(cone, "cone"); +primitive!(frustum, "frustum"); +primitive!(torus, "torus"); + +#[test] +fn hostile_arrays_are_refused() { + let c = case("box"); + let good = to_arrays(&c.body).unwrap(); + assert!(from_arrays(&Arrays::default()).is_err()); + for id in good.ints.keys().copied().collect::>() { + let mut a = good.clone(); + if let Some(v) = a.ints.get_mut(&id) { + v.push(7); + } + let _ = from_arrays(&a); + let mut a = good.clone(); + if let Some(v) = a.ints.get_mut(&id).and_then(|v| v.first_mut()) { + *v = i64::MAX; + } + let _ = from_arrays(&a); + } + for id in good.reals.keys().copied().collect::>() { + let mut a = good.clone(); + if let Some(v) = a.reals.get_mut(&id).and_then(|v| v.first_mut()) { + *v = f64::NAN; + assert!(from_arrays(&a).is_err(), "NaN in {id}"); + } + } +} + +/// `GetOrCreateGwNurbPointer` on a parabola: the one with its NURB gives it; one built over an +/// interval too small for two end tangents to cross has none and makes none, an error naming +/// `MakeNurb`. +#[test] +fn a_parabola_gives_its_nurb_or_says_it_cannot() { + use solidcore::curve::curve::Curve; + use solidcore::curve::parabola::Parabola; + use solidcore::geom::extent1d::Extent1d; + use solidcore::geom::vector3d::{Point3, Vec3}; + let (x, y) = (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)); + let part = |lo: f64, hi: f64| -> crate::Result { + let c = Curve::from(Parabola::new(Point3::new(0.0, 0.0, 0.0), x, y, Extent1d::from_min_max(lo, hi), 1.0, 3)); + let k = solidcore::kernel::Kernel::default(); + Ok(super::convert::bspline_curve_part(&k, &c)?.is_some_and(|b| b.gw_nurb().is_some())) + }; + assert_eq!(part(-1.0, 1.0), Ok(true)); + let none = part(0.5, 0.5); + assert!(matches!(&none, Err(e) if e.to_string().contains("MakeNurb")), "{none:?}"); +} + +/// Each edge's and vertex's tolerance crosses the kernels as it is. One box edge given eight times +/// the box's tolerance, in arrays whose TOLERANCE is the largest (as SMLib's export wrote them), +/// keeps it round after round, and the B-rep and every other edge and vertex keep the box's. Every +/// crossing used to give every entity the largest, so a chain of blends on a mixed route grew the +/// whole body's tolerance fourfold per blend (fillets/2341). +#[test] +fn tolerances_cross_the_arrays_per_entity() { + use crate::flat::{EDGE_TOLERANCE, TOLERANCE, VERTEX_TOLERANCE}; + let mut a = to_arrays(&case("box").body).unwrap(); + let base = a.reals[&TOLERANCE][0]; + assert!(a.reals[&EDGE_TOLERANCE].iter().chain(&a.reals[&VERTEX_TOLERANCE]).all(|&t| t == base), "{a:?}"); + a.reals.get_mut(&EDGE_TOLERANCE).unwrap()[0] = 8.0 * base; + a.reals.get_mut(&TOLERANCE).unwrap()[0] = 8.0 * base; + for round in 0..3 { + let body = from_arrays(&a).unwrap(); + assert_eq!(body.0.lock().unwrap().tolerance(), base / 2.0, "round {round}"); + a = to_arrays(&body).unwrap(); + assert_eq!(a.reals[&TOLERANCE], [base], "round {round}"); + let edges = &a.reals[&EDGE_TOLERANCE]; + assert_eq!(edges[0], 8.0 * base, "round {round}"); + assert!(edges[1..].iter().chain(&a.reals[&VERTEX_TOLERANCE]).all(|&t| t == base), "round {round}: {a:?}"); + } +} + +/// A 20 mm box minus a centred 10 mm box: a sealed void, so its solid region has two shells. +fn sealed_void() -> Body { + boolean(&make_box([-10.0; 3], [20.0; 3]).unwrap(), &make_box([-5.0; 3], [10.0; 3]).unwrap(), BooleanOp::Subtract).unwrap().unwrap() +} + +/// 20³ − 10³. +const SEALED_VOID_VOLUME: f64 = 8000.0 - 1000.0; + +/// Each bounded region's shells, as each shell's reach: the largest |coordinate| of its vertices +/// (10 for the 20 mm box, 5 for the 10 mm one). +fn reaches(rec: &b::Brep) -> Vec> { + let reach = |s: u32| { + let Some(b::Shell::Faces { faces, .. }) = rec.shells.get(s as usize) else { panic!("shell {s}") }; + let mut r = 0.0f64; + for f in faces { + for l in &rec.faces[f.face as usize].loops { + let b::Loop::Edges { edges } = l else { continue }; + for e in edges { + for &v in &rec.edges[e.edge as usize].vertices { + r = rec.vertices[v as usize].point.iter().fold(r, |r, c| r.max(c.abs())); + } + } + } + } + r + }; + rec.regions.iter().skip(1).map(|r| r.shells.iter().map(|&s| reach(s)).collect()).collect() +} + +/// The sealed void's record: the solid region lists the outer box first, then the void's box; +/// the void region its box alone. +fn outer_first(a: &Arrays, at: &str) { + let mut got = reaches(&record(a)); + got.sort_by_key(|x| std::cmp::Reverse(x.len())); + assert_eq!(got, [vec![10.0, 5.0], vec![5.0]], "{at}"); +} + +/// The arrays with every region's shells listed in reverse: each shell's block (its counts and +/// its face uses) moved, nothing else touched. +fn shells_reversed(a: &Arrays) -> Arrays { + use crate::flat::{FACEUSE_FACE, FACEUSE_ORIENTATION, REGION_SHELL_COUNT, SHELL_FACEUSE_COUNT, SHELL_POINT_TYPE, SHELL_WIRE_EDGE_COUNT}; + let mut p = a.clone(); + let blocks = [SHELL_FACEUSE_COUNT, SHELL_WIRE_EDGE_COUNT, SHELL_POINT_TYPE, FACEUSE_FACE, FACEUSE_ORIENTATION]; + for id in blocks { + p.ints.get_mut(&id).unwrap().clear(); + } + let (mut shell, mut fu) = (0usize, 0usize); + for &n in &a.ints[®ION_SHELL_COUNT] { + let mut region = Vec::new(); + for _ in 0..n { + let uses = usize::try_from(a.ints[&SHELL_FACEUSE_COUNT][shell]).unwrap(); + region.push((shell, fu..fu + uses)); + shell += 1; + fu += uses; + } + for (s, uses) in region.into_iter().rev() { + for id in [SHELL_FACEUSE_COUNT, SHELL_WIRE_EDGE_COUNT, SHELL_POINT_TYPE] { + let v = a.ints[&id][s]; + p.ints.get_mut(&id).unwrap().push(v); + } + for id in [FACEUSE_FACE, FACEUSE_ORIENTATION] { + p.ints.get_mut(&id).unwrap().extend_from_slice(&a.ints[&id][uses.clone()]); + } + } + } + assert_ne!(p.ints, a.ints, "nothing to reverse"); + p +} + +/// solidcore's sealed void exports with its outer shell first, comes back through the arrays +/// with it first, and keeps its volume. +#[test] +fn a_sealed_void_crosses_the_arrays_outer_shell_first() { + let body = sealed_void(); + let v = volume(&body, 1e-9).unwrap(); + assert!(rel(v, SEALED_VOID_VOLUME) < 1e-9, "{v}"); + let a = to_arrays(&body).unwrap(); + outer_first(&a, "export"); + let back = from_arrays(&import::arrays(&record(&a), true).unwrap()).unwrap(); + outer_first(&to_arrays(&back).unwrap(), "round trip"); + let v = volume(&back, 1e-9).unwrap(); + assert!(rel(v, SEALED_VOID_VOLUME) < 1e-9, "round trip: {v}"); +} + +/// Arrays listing the solid region's void shell before the box around it import with the box +/// first (SMLib takes a region's first shell as its enclosing one), the volume unchanged. +#[test] +fn shells_listed_inner_first_import_outer_first() { + let a = shells_reversed(&to_arrays(&sealed_void()).unwrap()); + let back = from_arrays(&a).unwrap(); + outer_first(&to_arrays(&back).unwrap(), "inner first"); + let v = volume(&back, 1e-9).unwrap(); + assert!(rel(v, SEALED_VOID_VOLUME) < 1e-9, "inner first: {v}"); +} diff --git a/crates/smlib/src/core/dump.rs b/crates/smlib/src/core/dump.rs new file mode 100644 index 000000000..9bcefa30f --- /dev/null +++ b/crates/smlib/src/core/dump.rs @@ -0,0 +1,133 @@ +//! What a failing solidcore call leaves behind, and which one is running: `smlib_set_dump_dir` and +//! `smlib_current_call` for this kernel. While a folder is set, a call that fails leaves its B-rep +//! inputs in it: `-.txt`, what failed, and `--.smb`, each input as a +//! binary `.smb`, which `Brep::read` reads back. The inputs are the caller's bodies, which it keeps +//! until the call's result is known ([`super::run_on`]); they are serialised only when the call +//! fails, so a call that answers costs nothing more than it would with no folder. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, PoisonError}; + +use solidcore::kernel::Kernel; +use solidcore::topology::Brep; + +use super::Body; +use crate::{Error, Result}; + +static DIR: Mutex> = Mutex::new(None); +static SEQUENCE: AtomicU64 = AtomicU64::new(0); + +/// A call's B-rep inputs, by the names its dump gives them, in the order it takes them. +pub(crate) type Inputs<'a> = &'a [(&'static str, &'a Body)]; + +#[cfg(test)] +thread_local! { + /// How many inputs this thread's calls serialised, for the tests. + pub(crate) static SERIALISED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Where failing calls leave their inputs; `None` stops it. +pub(crate) fn set_dir(dir: Option) { + *DIR.lock().unwrap_or_else(PoisonError::into_inner) = dir; +} + +/// `b` as a binary `.smb`. +fn serialise(k: &Kernel, b: &Brep) -> std::result::Result, String> { + #[cfg(test)] + SERIALISED.with(|n| n.set(n.get() + 1)); + super::file::bytes(k, b, false).map_err(|e| e.to_string()) +} + +fn safe(call: &str) -> String { + call.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect() +} + +/// The running call failed: its `inputs` go to the folder, as they are now (a call that edits a +/// body in place, a query's caches, leaves it edited). Failing to write them fails nothing else. +pub(super) fn failed(k: &Kernel, call: &str, why: &str, inputs: Inputs<'_>) { + let Some(dir) = DIR.lock().unwrap_or_else(PoisonError::into_inner).clone() else { return }; + let n = SEQUENCE.fetch_add(1, Ordering::Relaxed); + let stem = format!("{n:06}-{}", safe(call)); + let mut text = format!("{call} -> {why}\nnumeric arguments are not recorded\n"); + for &(what, body) in inputs { + let bytes = serialise(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner)); + match bytes { + Ok(b) => { + let name = format!("{stem}-{what}.smb"); + if let Err(e) = std::fs::write(dir.join(&name), b) { + log::warn!(target: "smlib", "{name}: {e}"); + } + text.push_str(&format!("input {what}: {name}\n")); + } + Err(e) => text.push_str(&format!("input {what}: could not be written: {e}\n")), + } + } + if let Err(e) = std::fs::write(dir.join(format!("{stem}.txt")), text) { + log::warn!(target: "smlib", "{stem}.txt: {e}"); + } +} + +/// How a call's value reads: whether it is a refusal, for the calls that answer with one. +pub(crate) trait Answer { + fn refusal(&self) -> Option { + None + } +} + +impl Answer for Result { + fn refusal(&self) -> Option { + self.as_ref().err().map(Error::to_string) + } +} + +/// The values that are no refusal. +macro_rules! plain { + ($($t:ty),* $(,)?) => { $(impl Answer for $t {})* }; +} +plain!( + (), + bool, + f64, + usize, + [usize; 2], + [usize; 3], + ([f64; 3], [f64; 3]), + Vec, + Vec<[f64; 3]>, + Brep, + solidcore::geom::vector3d::Point3, + crate::history::Raw, + crate::MassProperties, + Vec +); + +impl Answer for Option {} + +/// The calls running now, in the order they started. +static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); + +/// A call in [`current`]'s list until dropped. +pub(super) struct InFlight(&'static str); + +impl Drop for InFlight { + fn drop(&mut self) { + let mut calls = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(at) = calls.iter().position(|c| *c == self.0) { + calls.remove(at); + } + } +} + +/// `call` is running from now until the answer is dropped. +pub(super) fn in_flight(call: &'static str) -> InFlight { + IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).push(call); + InFlight(call) +} + +/// The calls running now, joined by commas. Never waits, for crash reports: `None` as well if a +/// call is starting or ending at this very moment. +pub(crate) fn current() -> Option { + let calls = IN_FLIGHT.try_lock().ok()?; + (!calls.is_empty()).then(|| calls.join(", ")) +} diff --git a/crates/smlib/src/core/file.rs b/crates/smlib/src/core/file.rs new file mode 100644 index 000000000..2164ffee1 --- /dev/null +++ b/crates/smlib/src/core/file.rs @@ -0,0 +1,60 @@ +//! `.smb` files on solidcore (`smlib_brep_read`, `smlib_brep_write`): the B-rep's contents through +//! `SmApiReadBrepFromFile` and `SmApiWriteBrepToFile`, the file itself read and written here (the +//! library touches no files, so that it builds for the browser). + +use std::path::Path; + +use solidcore::geom::attribute::{AttributeStore, ObjectKey}; +use solidcore::kernel::Kernel; +use solidcore::topology::api_files::{read_brep_from_file, write_brep_to_file}; +use solidcore::topology::brep::p10::TopologyEnv; +use solidcore::topology::brep_data_write::FromBrepEnv; +use solidcore::topology::topology::NotifyRecords; +use solidcore::topology::{Brep, EdgeId, EdgeuseId, FaceId}; + +use super::convert::key_of; +use super::{Body, run, with_body}; +use crate::{Error, Result}; + +/// Where the keys of a file's curves and surfaces start, clear of [`key_of`]'s entity keys. +const FILE_KEYS: u64 = 1 << 50; + +fn io(what: &str, path: &Path, e: &std::io::Error) -> Error { + Error::Solidcore(format!("{what} {}: {e}", path.display())) +} + +/// The body in the file at `path`, ASCII or binary. Its UV trims are checked, not rebuilt, as the +/// C API reads them. +pub(crate) fn read(path: &Path, ascii: bool) -> Result { + let data = std::fs::read(path).map_err(|e| io("reading", path, &e))?; + let b = run("smlib_brep_read", |k| { + let mut attributes = AttributeStore::default(); + let mut records = NotifyRecords::new(); + let mut env = TopologyEnv { all_attributes: &[], attributes: &mut attributes, key_of: &key_of, records: &mut records, next_key: FILE_KEYS }; + let mut b = read_brep_from_file(k, Some(data), ascii, false, &mut env)?; + b.refresh_cached_topology(); + Ok(b) + })?; + Ok(Body::new(b)) +} + +/// `b` as the contents of a `.smb` file, ASCII or binary. +pub(super) fn bytes(k: &Kernel, b: &Brep, ascii: bool) -> solidcore::Result> { + let store = AttributeStore::default(); + let records = NotifyRecords::new(); + let env = FromBrepEnv { + attributes: &store, + key_of: &key_of, + records: &records, + curve_key: &|_: EdgeId| ObjectKey(0), + uv_curve_key: &|_: EdgeuseId| ObjectKey(0), + surface_key: &|_: FaceId| ObjectKey(0), + }; + write_brep_to_file(k, Some(b), &env, ascii) +} + +/// `body` written to the file at `path`, ASCII or binary. +pub(crate) fn write(body: &Body, path: &Path, ascii: bool) -> Result<()> { + let bytes = with_body("smlib_brep_write", body, |k, b| bytes(k, b, ascii))?; + std::fs::write(path, bytes).map_err(|e| io("writing", path, &e)) +} diff --git a/crates/smlib/src/core/history.rs b/crates/smlib/src/core/history.rs new file mode 100644 index 000000000..ba61e2fee --- /dev/null +++ b/crates/smlib/src/core/history.rs @@ -0,0 +1,330 @@ +//! Face and edge history on solidcore: a port of the fork's `capi/src/smlib_history.cpp` +//! (`smlib_history_tag`, `smlib_history_read`) onto solidcore's B-rep-owned attribute store +//! ([`Brep::add_attribute`]), which solidcore's operations carry through their edits as SMLib's +//! `SmAObject::Notify` does: Split when a face or edge is cut in two, Merge when two become one, +//! Copy when an object is copied (a boolean copies the second operand into the first), Coincident +//! where a boolean finds one operand's entity lying on the other's. New topology (a boolean's +//! intersection edges) is made without any. +//! +//! The capi's `Tag` is one application attribute ([`Attribute::application`]) per face or edge, +//! with the capi's own handlers ([`AttributeHandlers`]): a split child, a merge's result and the +//! entity a coincidence lands on join the origins in, where SMLib's defaults keep only one; a copy +//! is SMLib's default. The data, the handlers and the reading are the capi's. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use solidcore::geom::attribute::{ + ApplicationValue, Attribute, AttributeHandle, AttributeHandlers, AttributeValue, AttributeView, Behavior, ObjectKey, Placement, ids, +}; +use solidcore::kernel::Kernel; +use solidcore::query::api_queries::edge_closest_point; +use solidcore::topology::face::p4 as face4; +use solidcore::topology::{Brep, EdgeId, VertexId, edge}; +use solidcore::{EntityRef, Point3, SolidError}; +use solidcore_record::brep::history::Change; + +use super::{Body, answer, with_body}; +use crate::history::{Raw, RawEdge, RawFace}; +use crate::{Error, Result}; +use solidcore::topology::brep::p3::brep_copy; + +/// `TAG_ID`: above SMLib's own ids (all below `SM_AI_USER_1`). +const TAG_ID: u64 = ids::USER_1 + 7; + +/// Operand numbers and indices a tag accepts (`TAG_MAX`: keeps every value inside 30 bits). +const TAG_MAX: usize = 1 << 30; + +/// One (operand, index) pair a face or edge stands for. +type Origin = (usize, usize); + +/// The capi's `Tag`: what a face or edge stands for, the operand entities it came from, for a face +/// tagged directly its own boundary edges then (to tell a face that is still whole), and for an +/// edge tagged directly where it lay then (points along it, ends first: to tell an edge that +/// moved). Copy behaviour (`SM_AB_COPY`); a copy (`MakeCopy`) is the same data. +#[derive(Debug, Clone, PartialEq, Default)] +struct Tag { + origins: BTreeSet, + edges: BTreeSet, + at: Vec, +} + +impl Tag { + fn attribute(self) -> Attribute { + Attribute::application(TAG_ID, Behavior::Copy, self) + } +} + +/// `Tag::on`: the tag on `x`, if the attribute of its id there is a [`Tag`]. +fn on<'a>(view: &AttributeView<'a>, x: ObjectKey) -> Option<(AttributeHandle, &'a Tag)> { + let (h, a) = view.find_attribute(x, TAG_ID)?; + a.application_value::().map(|t| (h, t)) +} + +/// `Tag::join`: adds `o` and `e` to `x`'s tag (its `at` as it was), giving it one with no `at` if +/// it has none (an attribute of the tag's id that is no tag is replaced). Nothing for no `o`. +fn join(view: &AttributeView<'_>, x: ObjectKey, o: &BTreeSet, e: &BTreeSet) -> Vec { + if o.is_empty() { + return Vec::new(); + } + if let Some((handle, t)) = on(view, x) { + let mut t = t.clone(); + t.origins.extend(o.iter().copied()); + t.edges.extend(e.iter().copied()); + return vec![Placement::Edit { handle, value: AttributeValue::Application(ApplicationValue::new(t)) }]; + } + set(view, x, o.clone(), e.clone(), Vec::new()) +} + +/// `Tag::set`: replaces whatever tag `x` has (the attribute of the tag's id) with exactly `o`, `e` +/// and `p`. +fn set(view: &AttributeView<'_>, x: ObjectKey, o: BTreeSet, e: BTreeSet, p: Vec) -> Vec { + let mut out = Vec::with_capacity(2); + if let Some((handle, _)) = view.find_attribute(x, TAG_ID) { + out.push(Placement::Remove { on: x, handle }); + } + out.push(Placement::Add { on: x, attribute: Tag { origins: o, edges: e, at: p }.attribute() }); + out +} + +impl AttributeHandlers for Tag { + /// A split: both children stand for what the split object stood for, and lie where it lay + /// (each a piece of it): a child with no tag gets this one's `at` too. + fn split(&self, view: &AttributeView<'_>, split: ObjectKey, a: ObjectKey, b: ObjectKey) -> solidcore::Result> { + let mut out = Vec::new(); + for x in [a, b] { + if x == split { + continue; + } + if on(view, x).is_none() && !self.origins.is_empty() { + out.extend(set(view, x, self.origins.clone(), self.edges.clone(), self.at.clone())); + } else { + out.extend(join(view, x, &self.origins, &self.edges)); + } + } + Ok(out) + } + + /// A merge: the result stands for both (the tags on the sources other than the result). + fn merge(&self, view: &AttributeView<'_>, a: ObjectKey, b: ObjectKey, result: ObjectKey) -> solidcore::Result> { + let (mut o, mut e) = (BTreeSet::new(), BTreeSet::new()); + for x in [a, b] { + if x != result + && let Some((_, t)) = on(view, x) + { + o.extend(t.origins.iter().copied()); + e.extend(t.edges.iter().copied()); + } + } + Ok(join(view, result, &o, &e)) + } + + /// One operand's entity found lying on the other's, which survives: it stands for both. + fn coincident(&self, view: &AttributeView<'_>, _from: ObjectKey, to: ObjectKey) -> solidcore::Result> { + Ok(join(view, to, &self.origins, &self.edges)) + } +} + +/// `read`: what `e`'s tag says (the attribute of the tag's id, if it is a [`Tag`]). +fn tag_on(b: &Brep, e: EntityRef) -> Option<&Tag> { + let (_, a) = b.entity_attributes(e).into_iter().find(|(_, a)| a.attribute_id() == TAG_ID)?; + a.application_value::() +} + +/// `Tag::set` at tagging: replaces whatever tag `e` has with exactly origin `o`, the boundary +/// edges `edges` (a face's) and the points `at` (an edge's). +fn set_on(b: &mut Brep, e: EntityRef, o: Origin, edges: BTreeSet, at: Vec) -> std::result::Result<(), SolidError> { + let old = b.entity_attributes(e).into_iter().find(|(_, a)| a.attribute_id() == TAG_ID).map(|(h, _)| h); + if let Some(h) = old { + b.remove_attribute(e, h)?; + } + b.add_attribute(e, Tag { origins: BTreeSet::from([o]), edges, at }.attribute())?; + Ok(()) +} + +/// `samples`: points along `e`, its two ends, then three between, evenly in its parameter. Empty +/// where it can't be evaluated. +fn samples(k: &Kernel, b: &Brep, e: EdgeId) -> std::result::Result, SolidError> { + let edge = b.edge(e)?; + let Some(curve) = edge.curve.as_ref() else { return Ok(Vec::new()) }; + let (lo, hi) = (edge.interval.min(), edge.interval.max()); + let mut p = Vec::with_capacity(5); + for t in [0.0, 1.0, 0.25, 0.5, 0.75] { + let Some(v) = answer(curve.evaluate(k, lo + t * (hi - lo), 0, true, false))? else { return Ok(Vec::new()) }; + let Some(v) = v.first() else { return Ok(Vec::new()) }; + p.push(Point3::new(v.x, v.y, v.z)); + } + Ok(p) +} + +/// `moved`: have `pieces`, the result edges standing for one edge, moved from where its tag says +/// it lay (`at`, the first piece's record of at least two points)? Together they must run between +/// its ends (the vertices only one piece ends on; none for an edge closed on itself, whose end some +/// piece still ends on), and every point it ran through must lie on one of them (within `tol`). +/// One piece is the edge still whole; more, the edge cut by vertices. Pieces with no record of +/// where the edge lay have not moved. +pub(super) fn moved(k: &Kernel, b: &Brep, pieces: &[(EdgeId, &[Point3])], tol: f64) -> std::result::Result { + let Some(at) = pieces.iter().map(|(_, at)| *at).find(|at| at.len() >= 2) else { return Ok(false) }; + let [a, z, ..] = at else { return Ok(false) }; + let near = |p: &Point3, q: &Point3| p.distance(*q) <= tol; + let mut ends: BTreeMap = BTreeMap::new(); + for (e, _) in pieces { + let (Some(s), Some(f)) = edge::start_end_vertices(b, *e)? else { return Ok(true) }; + *ends.entry(s).or_default() += 1; + *ends.entry(f).or_default() += 1; + } + let mut open = Vec::new(); + for (v, n) in &ends { + if n % 2 == 1 { + open.push(b.vertex(*v)?.point); + } + } + let span = match open.as_slice() { + [p, q] => (near(p, a) && near(q, z)) || (near(p, z) && near(q, a)), + [] => { + let mut on_end = false; + for v in ends.keys() { + on_end = on_end || near(&b.vertex(*v)?.point, a); + } + near(a, z) && on_end + } + _ => false, + }; + if !span { + return Ok(true); + } + for q in at.iter().skip(2) { + // `SmApiEdgeClosestPoint` failing, however it fails, counts as off a piece, as a distance + // above `tol` does: the face is then Modified, and the operation stands. + if !pieces.iter().any(|(e, _)| edge_closest_point(k, b, *e, *q).is_ok_and(|c| c.closest.distance <= tol)) { + return Ok(true); + } + } + Ok(false) +} + +/// `smlib_history_tag`: a copy of `body` (`SmApiBrepCopy`) whose face i and edge i stand for face +/// i and edge i of operand `operand` (in its face and edge order, which the copy keeps), a face +/// also recording its boundary edges then, an edge the points it ran through. +pub(crate) fn tag(body: &Body, operand: usize) -> Result { + if operand >= TAG_MAX { + return Err(Error::Argument); + } + with_body("smlib_history_tag", body, |k, b| { + let mut r = brep_copy(k, b)?; + let faces = r.face_list().to_vec(); + let edges = r.edge_list().to_vec(); + if faces.len() >= TAG_MAX || edges.len() >= TAG_MAX { + return Ok(Err(Error::Argument)); + } + let edge_at: HashMap = edges.iter().enumerate().map(|(i, e)| (*e, i)).collect(); + for (i, f) in faces.iter().enumerate() { + let own: BTreeSet = + face4::edges(&r, *f, None, false, None)?.iter().filter_map(|e| edge_at.get(e).and_then(|j| i64::try_from(*j).ok())).collect(); + set_on(&mut r, EntityRef::Face(*f), (operand, i), own, Vec::new())?; + } + for (i, e) in edges.iter().enumerate() { + let at = samples(k, &r, *e)?; + set_on(&mut r, EntityRef::Edge(*e), (operand, i), BTreeSet::new(), at)?; + } + Ok(Ok(r)) + })? + .map(Body::new) +} + +/// `smlib_history_read`: each face's and edge's origins in `result`, a face's change from how +/// many origins it has, how many result faces share them and whether its boundary is still +/// exactly its origin's edges; each edge's faces. In the body's own face and edge order. +pub(crate) fn read(result: &Body) -> Result { + with_body("smlib_history_read", result, |k, b| { + let faces = b.face_list().to_vec(); + let edges = b.edge_list().to_vec(); + let face_at: HashMap<_, usize> = faces.iter().enumerate().map(|(i, f)| (*f, i)).collect(); + let edge_at: HashMap = edges.iter().enumerate().map(|(i, e)| (*e, i)).collect(); + let tol = b.tolerance(); + + // Each face's origins and the boundary edges they had; each edge's origins and points. + let mut fo: Vec> = Vec::with_capacity(faces.len()); + let mut fe: Vec> = Vec::with_capacity(faces.len()); + let mut eo: Vec> = Vec::with_capacity(edges.len()); + let mut at: Vec> = Vec::with_capacity(edges.len()); + let mut face_uses: BTreeMap = BTreeMap::new(); + let mut edge_uses: BTreeMap = BTreeMap::new(); + for f in &faces { + let (o, e) = tag_on(b, EntityRef::Face(*f)).map(|t| (t.origins.clone(), t.edges.clone())).unwrap_or_default(); + for x in &o { + *face_uses.entry(*x).or_default() += 1; + } + fe.push(e.into_iter().filter_map(|x| usize::try_from(x).ok()).collect()); + fo.push(o); + } + for e in &edges { + let (o, p) = tag_on(b, EntityRef::Edge(*e)).map(|t| (t.origins.clone(), t.at.clone())).unwrap_or_default(); + for x in &o { + *edge_uses.entry(*x).or_default() += 1; + } + at.push(p); + eo.push(o); + } + + let mut out_faces = Vec::with_capacity(faces.len()); + for (i, f) in faces.iter().enumerate() { + let (Some(o), Some(own)) = (fo.get(i), fe.get(i)) else { continue }; + let change = match o.iter().next() { + None => Change::Generated, + Some(_) if o.len() > 1 => Change::Merged, + Some(first) if face_uses.get(first).copied().unwrap_or(0) > 1 => Change::Split, + Some(first) => { + // Kept when its boundary is still exactly where the edges it had were: each + // boundary edge one of its own operand's, standing for one edge only, every + // piece of that edge on this face (an edge only cut by a vertex, as splitting + // the face beside it cuts it, is still all there), the pieces where it lay (an + // edge an operation moved, as a draft moves a tilted face's neighbours' edges, + // leaves those faces trimmed differently), and those edges exactly the ones it + // had. + let mut pieces: BTreeMap> = BTreeMap::new(); + let mut whole = true; + for e in face4::edges(b, *f, None, false, None)? { + let Some(j) = edge_at.get(&e).copied() else { + whole = false; + break; + }; + let (Some(origins), Some(points)) = (eo.get(j), at.get(j)) else { + whole = false; + break; + }; + let only = match origins.iter().next() { + Some(x) if origins.len() == 1 => *x, + _ => { + whole = false; + break; + } + }; + whole = only.0 == first.0; + if !whole { + break; + } + let p = pieces.entry(only.1).or_default(); + if !p.iter().any(|(x, _)| *x == e) { + p.push((e, points.as_slice())); + } + } + let mut now = BTreeSet::new(); + for (edge, p) in &pieces { + whole = whole && p.len() == edge_uses.get(&(first.0, *edge)).copied().unwrap_or(0) && !moved(k, b, p, tol)?; + now.insert(*edge); + } + if whole && now == *own { Change::Kept } else { Change::Modified } + } + }; + out_faces.push(RawFace { change, origins: o.iter().copied().collect() }); + } + + let mut out_edges = Vec::with_capacity(edges.len()); + for (i, e) in edges.iter().enumerate() { + let bounds: BTreeSet = edge::faces(b, *e, None)?.iter().filter_map(|f| face_at.get(f).copied()).collect(); + let origins = eo.get(i).map(|o| o.iter().copied().collect()).unwrap_or_default(); + out_edges.push(RawEdge { faces: bounds.into_iter().collect(), origins }); + } + Ok(Raw { faces: out_faces, edges: out_edges }) + }) +} diff --git a/crates/smlib/src/core/measure.rs b/crates/smlib/src/core/measure.rs new file mode 100644 index 000000000..012c23d1a --- /dev/null +++ b/crates/smlib/src/core/measure.rs @@ -0,0 +1,354 @@ +//! The Measure and Check families on solidcore: what `capi/src/smlib_measure.cpp`, +//! `smlib_brep_solid_count` (`smlib_ops.cpp`), `smlib_brep_is_manifold_solid` +//! (`smlib_flat_api.cpp`) and `smlib_brep_check` (`smlib_check.cpp`) do on the C++ kernel, here +//! composed from solidcore's ports of the same SMLib routines. +//! +//! [`check`] fails with "not supported yet" while a test it reaches is unported in solidcore. + +use solidcore::error::EntityRef; +use solidcore::geom::assert_array::{AssertArray, AssertReport, obj_type_string}; +use solidcore::geom::attribute::{AttributeStore, ObjectKey}; +use solidcore::geom::tol::{SmallTopoType, brep_zone_tol_3d, context_xsect_tol_3d}; +use solidcore::heal::gap::GapFunction; +use solidcore::intersect::point_class::PointClassType; +use solidcore::mass::integrator::properties::{MassPropertyBehavior, PropertyAttributes, brep_properties, face_properties}; +use solidcore::nurbs::b_spline_surface_n_lib::p2::OrientType; +use solidcore::query::api_queries::{brep_bounding_box, brep_is_manifold_solid, brep_material_census, face_bounding_box}; +use solidcore::query::brep::BrepClassifier; +use solidcore::topology::brep::p1 as bl; +use solidcore::topology::brep::validation::{CheckLevel as SolidcoreCheckLevel, check_brep}; +use solidcore::topology::face::p2::{PPF_AREA, PPF_AREA_FIRST_MOMENTS}; +use solidcore::topology::{FaceId, FaceuseId, NamingScheme}; +use solidcore::{Kernel, Point3, SolidError, Vec3}; + +use super::blend::status; +use super::{Body, with_body}; +use crate::check::{CheckLevel, CheckReport}; +use crate::measure::{MassProperties, PointClass}; +use crate::{Error, Result}; + +const OP: &str = "smlib_measure"; + +/// The accuracy the C API passes on: finite, clamped to [1e-8, 1e-1]. +pub(super) fn accuracy(relative_accuracy: f64) -> Result { + if !relative_accuracy.is_finite() { + return Err(Error::Argument); + } + Ok(relative_accuracy.clamp(1e-8, 1e-1)) +} + +fn invalid(why: &'static str) -> SolidError { + SolidError::invalid_input(OP, why) +} + +fn finite(v: &[f64]) -> bool { + v.iter().all(|x| x.is_finite()) +} + +/// `faces_area` of `smlib_measure.cpp`: every face counted once (SmApiBrepComputeArea, with the +/// [1e-8, 1e-1] envelope instead of its [1e-4, 1e-1]), the total area and, when `first` is set, +/// the area's first moments about `o`. With `only_sheets`, only [`sheet_face`]s (the capi's +/// `counted`). +fn faces_area(k: &Kernel, b: &mut solidcore::Brep, accuracy: f64, o: Point3, first: bool, only_sheets: bool) -> solidcore::Result<(f64, Vec3)> { + let mut area = 0.0; + let mut sum = Vec3::new(0.0, 0.0, 0.0); + let flags = if first { PPF_AREA | PPF_AREA_FIRST_MOMENTS } else { PPF_AREA }; + for f in bl::faces(b, None)? { + if only_sheets && !sheet_face(b, f)? { + continue; + } + let size = face_bounding_box(k, b, f, false)?.size(); + let edge = size.z.max(size.x.max(size.y)); + let p = face_properties(k, b, f, OrientType::Same, accuracy, o, edge * edge / 100.0, 0.0, flags)?; + // The area and its moments share one integrand, so a trim boundary integrated the other + // way round flips both. + let sign = if p.area < 0.0 { -1.0 } else { 1.0 }; + area += sign * p.area; + if first { + sum += p.moments[0] * sign; + } + } + if !area.is_finite() { + return Err(invalid("non-finite area")); + } + Ok((area, sum)) +} + +/// `sheet_face`: a face with material on neither side, standing free or hung on a solid (a blend +/// sheet stitched between two boxes). `SmBrep::ComputePreciseProperties` takes its area only from +/// faces between a solid region and a void, so such a face is counted on its own. +fn sheet_face(b: &solidcore::Brep, f: FaceId) -> solidcore::Result { + let void_side = |u: Option| -> solidcore::Result { + let Some(u) = u else { return Ok(true) }; + let Some(shell) = b.faceuse(u)?.shell else { return Ok(true) }; + let Some(region) = b.shell(shell)?.region else { return Ok(true) }; + // IsVoid's UNSURE (2) is true in C++: only FALSE is material. + Ok(b.region(region)?.is_void() != 0) + }; + let (x, y) = solidcore::topology::face::p2::faceuses(b, f)?; + Ok(void_side(x)? && void_side(y)?) +} + +/// `smlib_brep_mass_properties`: `SmBrep::ComputePreciseProperties` directly, as the C API calls +/// it (not `SmApiBrepComputeMassProperties`: the [1e-8, 1e-1] accuracy envelope, no manifold +/// refusal, the sum over material regions), the face-by-face area and its centroid for a body +/// with no material, and moments about the middle of the box moved to the centroid. A body's area +/// is every face's: the solid's boundary and its sheet faces (fork 9767916). +pub(crate) fn mass_properties(body: &Body, relative_accuracy: f64) -> Result { + let accuracy = accuracy(relative_accuracy)?; + with_body("mass_properties", body, |k, b| { + let mut material = false; + for r in bl::regions(b, None)? { + // IsVoid's UNSURE (2) is true in C++: only FALSE is material. + material |= b.region(r)?.is_void() == 0; + } + // The C API refuses a body with per-entity mass attributes (they would override the unit + // density). Bodies here carry none: the attribute store passed in is empty. + let store = AttributeStore::default(); + let attrs = PropertyAttributes { store: &store, key_of: &|_| ObjectKey(0) }; + // Moments about the middle of the box, moved to the centroid below: about the world + // origin, a body far from it would lose its inertia to cancellation. + let o = brep_bounding_box(k, b, false)?.mid(); + if !finite(&[o.x, o.y, o.z]) { + return Err(invalid("non-finite box")); + } + if !material { + let (area, first) = faces_area(k, b, accuracy, o, true, false)?; + if !(area > 0.0) { + return Err(invalid("no area")); + } + let c = [o.x + first.x / area, o.y + first.y / area, o.z + first.z / area]; + if !finite(&[area, c[0], c[1], c[2]]) { + return Err(invalid("non-finite result")); + } + return Ok(MassProperties { area, volume: 0.0, centroid: c, moments: [0.0; 3], products: [0.0; 3] }); + } + let p = brep_properties(k, b, accuracy, o, MassPropertyBehavior { density: 1.0, ..MassPropertyBehavior::default() }, &attrs)?; + let (mass, volume) = (p.mass, p.volume); + if !mass.is_finite() || !(mass > 0.0) || !(volume > 0.0) { + return Err(invalid("no mass")); + } + // m[4]: first moments about o; m[7]: (y²+z², z²+x², x²+y²) about o; m[6]: (yz, zx, xy) + // about o. Parallel axes from o to the centroid (unit density: mass = volume). + let [_, _, _, _, m4, _, m6, m7] = p.moments; + let d = [m4.x / mass, m4.y / mass, m4.z / mass]; + let (sheets, _) = faces_area(k, b, accuracy, o, false, true)?; + let r = MassProperties { + area: p.area + sheets, + volume, + centroid: [o.x + d[0], o.y + d[1], o.z + d[2]], + moments: [ + m7.x - mass * (d[1] * d[1] + d[2] * d[2]), + m7.y - mass * (d[0] * d[0] + d[2] * d[2]), + m7.z - mass * (d[0] * d[0] + d[1] * d[1]), + ], + products: [m6.x - mass * d[1] * d[2], m6.y - mass * d[2] * d[0], m6.z - mass * d[0] * d[1]], + }; + if !finite(&[r.area, r.volume]) || !finite(&r.centroid) || !finite(&r.moments) || !finite(&r.products) { + return Err(invalid("non-finite result")); + } + Ok(r) + }) +} + +/// `smlib_brep_area`: every face counted once. +pub(crate) fn area(body: &Body, relative_accuracy: f64) -> Result { + let accuracy = accuracy(relative_accuracy)?; + with_body("area", body, |k, b| faces_area(k, b, accuracy, Point3::new(0.0, 0.0, 0.0), false, false).map(|(a, _)| a)) +} + +/// `smlib_brep_bounds`: `SmBrep::CalculateTightBoundingBox`. +pub(crate) fn bounds(body: &Body) -> Result<([f64; 3], [f64; 3])> { + with_body("bounds", body, |k, b| { + let x = brep_bounding_box(k, b, true)?; + let (lo, hi) = (x.min(), x.max()); + let (lo, hi) = ([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]); + if !finite(&lo) || !finite(&hi) || lo.iter().zip(&hi).any(|(a, b)| a > b) { + return Err(invalid("no box")); + } + Ok((lo, hi)) + }) +} + +/// `smlib_brep_edge_face_distance`: SMLib's own edge/face gap (`SmEdgeuse::CalcMaxEdgeFaceGap`'s +/// `SmCrvSrfGapFunction` with 20 samples, its largest sample). Indices in the body's edge and +/// face order. +pub(crate) fn edge_face_distance(body: &Body, edge: usize, face: usize) -> Result { + let found = with_body("edge_face_distance", body, |k, b| { + let (Some(&e), Some(&f)) = (bl::edges(b, None)?.get(edge), bl::faces(b, None)?.get(face)) else { + return Ok(None); + }; + let interval = b.edge(e)?.interval; + let (Some(curve), Some(surface)) = (b.edge(e)?.curve.as_ref(), b.face(f)?.surface.as_ref()) else { + return Err(invalid("edge without curve or face without surface")); + }; + if !(interval.max() > interval.min()) { + return Err(invalid("empty edge interval")); + } + // SmTol::GetXSectTol3d(brep's context): the process context. The tolerance only + // classifies the samples; it does not change the distances. + let tol = context_xsect_tol_3d(k, None, SmallTopoType::NormalSize); + let mut gaps = GapFunction::crv_srf(tol, curve, &interval, surface, 20); + let d = gaps.max_gap_sample(k, false)?.length(); + if !d.is_finite() { + return Err(invalid("non-finite gap")); + } + Ok(Some(d)) + })?; + found.ok_or(Error::Argument) +} + +/// `smlib_brep_classify_point`: `SmBrep::Point3DClassify` at the body's own zone tolerance +/// (`SmTol::GetZoneTol3d` of the body), with boundary intersections, so a point within that +/// tolerance of a vertex, an edge or a face is on the boundary and never decided by a ray; else +/// the region it lies in, outside when that region is void (`IsVoid() == TRUE`; `UNSURE` is +/// material, as the capi compares with `TRUE`). Runs on a private copy when a solve needs one +/// (`BrepClassifier`): upstream's `const` method may add UV trim curves to the body. +pub(crate) fn classify_point(body: &Body, p: [f64; 3]) -> Result { + if !finite(&p) { + return Err(Error::Argument); + } + with_body("classify_point", body, |k, b| { + let tol = brep_zone_tol_3d(k, b, SmallTopoType::NormalSize); + let mut classifier = BrepClassifier::of_brep(b); + let pc = match classifier.point_3d_classify(k, Point3::new(p[0], p[1], p[2]), tol, true) { + Ok(pc) => pc, + // Its status, as the capi passes it on (no ray finding a region is SM_ERR). + Err(e) => return Ok(Err(status(e))), + }; + Ok(match (pc.point_class(), pc.object()) { + (PointClassType::Vertex | PointClassType::Edge | PointClassType::Face, _) => Ok(PointClass::OnBoundary), + (PointClassType::Region, Some(EntityRef::Region(r))) => { + Ok(if classifier.brep().region(r)?.is_void() == 1 { PointClass::Outside } else { PointClass::Inside }) + } + // Point3DClassify reports only the four classes above on success: SM_ERR. + _ => Err(Error::Status(SM_ERR)), + }) + })? +} + +/// `SM_ERR`. +const SM_ERR: i32 = 1001; + +/// `smlib_brep_is_manifold_solid`: `SmApiBrepIsManifoldSolid`. +pub(crate) fn is_manifold_solid(body: &Body) -> Result { + with_body("is_manifold_solid", body, |_, b| brep_is_manifold_solid(b)) +} + +/// `smlib_brep_solid_count`: the solids of `SmApiBrepMaterialCensus` (its voids are dropped). +pub(crate) fn solid_count(body: &Body) -> Result { + with_body("solid_count", body, |_, b| brep_material_census(b).map(|(solids, _voids)| solids)) +} + +/// SMLib's `SM_SUCCESS`, the status `SmBrep::ValidatePointers` returns when it finds nothing. +const SM_SUCCESS: i32 = 1000; + +/// The capi's `text()`: an empty string reads as `?`. +fn text(s: &str) -> &str { + if s.is_empty() { "?" } else { s } +} + +/// The capi's `line()`: `::Test # : [owner ]`, the owner +/// tag only when the report names the owner's type. +fn report_line(r: &AssertReport) -> String { + let msg = r.format_log_message(); + let mut s = format!("{}::Test #{} {}: {}", text(obj_type_string(r.reporting_type)), r.test_index, text(r.name), text(&msg)); + if let Some(owner) = r.owner_type_string.filter(|o| !o.is_empty()) { + s.push_str(" [owner "); + s.push_str(owner); + s.push(']'); + } + s +} + +/// The capi's `collect()`: appends the failed reports of `list`, one line each, and counts them; +/// SMLib's warnings ([`AssertReport::is_warning`]: `SmBrep` test 21, "Suspicious Shell Count", a +/// body of several faces with one shell each, is one) are neither. +fn collect(list: &AssertArray, out: &mut String, failures: &mut usize) { + for r in list.reports().iter().filter(|r| !r.ok && !r.is_warning()) { + *failures += 1; + out.push_str(&report_line(r)); + out.push('\n'); + } +} + +/// Why [`check`] could not run. +enum Refusal { + /// A test solidcore has not ported (its [`SolidError::Unported`]). + Unported(&'static str, &'static str), + /// A body whose geometry owners' identities the check cannot know: a + /// [`NamingScheme::Unknown`] body. + Naming(NamingScheme), +} + +impl super::dump::Answer for std::result::Result { + fn refusal(&self) -> Option { + self.is_err().then(|| "the check could not run".to_string()) + } +} + +/// `smlib_brep_check` (`smlib_check.cpp`): `SmBrep::ValidatePointers` at `level`, then, when it +/// failed nothing, `SmBrep::AssertValid` at `level` over the whole topology graph, with every +/// failed test as one line of the report and the capi's own lines for a failed status without a +/// report. solidcore's [`check_brep`] runs the same two calls. +/// +/// The geometry owners are named as the body's naming scheme names them: `check_brep` reads a +/// [`NamingScheme::Caller`] body's keys from where its maker recorded them (solidcore#1585: an +/// array import through `make_topology_from_data`, `api_brep_copy`); where it recorded none, the +/// arena identities the binders name such an entity by. A [`NamingScheme::Unknown`] body would be +/// checked under arena identities no maker uses: every edge would fail `SmBrep` test 61 on the +/// owner of its curve. +/// +/// A test solidcore has not ported yet (its [`SolidError::Unported`]), or a body whose geometry +/// owners' identities the check cannot know, fails the check with "not supported yet": the check +/// never reports a body valid on fewer tests than the C++ kernel runs. +pub(crate) fn check(body: &Body, level: CheckLevel) -> Result { + let lv = match level { + CheckLevel::Basic => SolidcoreCheckLevel::Level0, + CheckLevel::Geometry => SolidcoreCheckLevel::Level1, + CheckLevel::All => SolidcoreCheckLevel::Level2, + }; + let c = match with_body("check", body, |k, b| { + let naming = b.naming(); + if naming == NamingScheme::Unknown { + return Ok(Err(Refusal::Naming(naming))); + } + match check_brep(k, b, lv) { + Err(SolidError::Unported { upstream, unit }) => Ok(Err(Refusal::Unported(upstream, unit))), + r => r.map(Ok), + } + })? { + Ok(c) => c, + Err(Refusal::Unported(upstream, unit)) => { + return Err(Error::Solidcore(format!("smlib_brep_check: {upstream}: not supported yet: solidcore has not ported it (unit {unit})"))); + } + Err(Refusal::Naming(n)) => { + return Err(Error::Solidcore(format!( + "smlib_brep_check: not supported yet: the body names its geometry owners by its maker's keys (NamingScheme::{n:?}), which the check cannot know" + ))); + } + }; + let mut text = String::new(); + let mut failures = 0usize; + collect(&c.pointer_reports, &mut text, &mut failures); + if c.pointers_status != SM_SUCCESS && failures == 0 { + failures += 1; + text.push_str(&format!("SmBrep::ValidatePointers failed with status {}\n", c.pointers_status)); + } + if failures > 0 { + // The capi does not run AssertValid after a failed pointer check. check_brep runs it when + // the status failed without a report; that result is dropped here, as the capi never + // computes it. + text.push_str("AssertValid skipped: ValidatePointers failed\n"); + } else { + let Some(ok) = c.assert_valid else { + return Err(Error::Solidcore("smlib_brep_check: AssertValid did not run after a clean pointer check".into())); + }; + collect(&c.reports, &mut text, &mut failures); + if !ok && failures == 0 { + failures += 1; + text.push_str("SmBrep::AssertValid failed without a report\n"); + } + } + Ok(CheckReport { failures, text }) +} diff --git a/crates/smlib/src/core/measure_tests.rs b/crates/smlib/src/core/measure_tests.rs new file mode 100644 index 000000000..9a75a2729 --- /dev/null +++ b/crates/smlib/src/core/measure_tests.rs @@ -0,0 +1,309 @@ +//! The Measure and Check families on solidcore's primitives: mass properties, area and bounds +//! against their closed forms ([`crate::measure::closed`]), one solid each, edges on their faces. + +use super::{Body, area, bounds, check, edge_face_distance, is_manifold_solid, make_box, make_cone, make_cylinder, make_sphere, make_torus}; +use super::{counts, mass_properties, solid_count}; +use crate::check::CheckLevel; +use crate::measure::MEASURE_ACCURACY; +use crate::measure::closed::{self, Closed}; + +/// The tolerance every quantity meets, relative. +const TOL: f64 = 1e-9; + +/// The primitives, as `convert_tests` makes them, with their closed forms. +fn case(name: &str) -> (Body, Closed) { + let (body, c) = match name { + "box" => (make_box([1.0, -2.0, 3.0], [10.0, 20.0, 30.0]), closed::cuboid([1.0, -2.0, 3.0], [10.0, 20.0, 30.0])), + "cylinder" => (make_cylinder([1.0, 2.0, -3.0], 5.0, 12.0), closed::cylinder([1.0, 2.0, -3.0], 5.0, 12.0)), + "sphere" => (make_sphere([1.0, 2.0, 3.0], 7.0), closed::sphere([1.0, 2.0, 3.0], 7.0)), + "cone" => (make_cone([0.0, 1.0, 2.0], 6.0, 0.0, 9.0), closed::cone([0.0, 1.0, 2.0], 6.0, 0.0, 9.0)), + "frustum" => (make_cone([0.0, 1.0, 2.0], 6.0, 2.0, 9.0), closed::cone([0.0, 1.0, 2.0], 6.0, 2.0, 9.0)), + "torus" => (make_torus([1.0, -1.0, 0.5], 10.0, 3.0), closed::torus([1.0, -1.0, 0.5], 10.0, 3.0)), + _ => panic!("{name}"), + }; + (body.unwrap(), c) +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +/// The body's size: twice its largest radius of gyration, the scale of centroid errors. +fn size(c: &Closed) -> f64 { + 2.0 * (c.moments.iter().fold(0.0f64, |a, &b| a.max(b)) / c.volume).sqrt() +} + +fn mass_properties_match(name: &str) { + let (b, c) = case(name); + let m = mass_properties(&b, MEASURE_ACCURACY).unwrap(); + assert!(rel(m.area, c.area) < TOL, "{name}: area {} vs {}", m.area, c.area); + assert!(rel(m.volume, c.volume) < TOL, "{name}: volume {} vs {}", m.volume, c.volume); + let imax = c.moments.iter().fold(0.0f64, |a, &b| a.max(b)); + for i in 0..3 { + assert!((m.centroid[i] - c.centroid[i]).abs() < TOL * size(&c), "{name}: centroid {:?} vs {:?}", m.centroid, c.centroid); + assert!(rel(m.moments[i], c.moments[i]) < TOL, "{name}: moments {:?} vs {:?}", m.moments, c.moments); + assert!(m.products[i].abs() < TOL * imax, "{name}: products {:?}", m.products); + } +} + +fn area_matches(name: &str) { + let (b, c) = case(name); + let a = area(&b, MEASURE_ACCURACY).unwrap(); + assert!(rel(a, c.area) < TOL, "{name}: area {a} vs {}", c.area); +} + +fn bounds_match(name: &str) { + let (b, c) = case(name); + let (lo, hi) = bounds(&b).unwrap(); + let s = size(&c); + for i in 0..3 { + assert!((lo[i] - c.bounds.0[i]).abs() < TOL * s, "{name}: low {lo:?} vs {:?}", c.bounds.0); + assert!((hi[i] - c.bounds.1[i]).abs() < TOL * s, "{name}: high {hi:?} vs {:?}", c.bounds.1); + } +} + +fn one_solid(name: &str) { + let (b, _) = case(name); + assert_eq!(solid_count(&b).unwrap(), 1, "{name}"); +} + +fn manifold_solid(name: &str) { + let (b, _) = case(name); + assert!(is_manifold_solid(&b).unwrap(), "{name}"); +} + +/// Every edge lies on the faces it bounds: its distance to the nearest face is 0. +fn edges_lie_on_their_faces(name: &str) { + let (b, c) = case(name); + let [faces, edges, _] = counts(&b).unwrap(); + for e in 0..edges { + let mut d: Vec = (0..faces).filter_map(|f| edge_face_distance(&b, e, f).ok()).collect(); + d.sort_by(f64::total_cmp); + assert!(d.first().is_some_and(|&d| d < TOL * size(&c)), "{name}: edge {e}: {d:?}"); + } + assert!(edge_face_distance(&b, edges, 0).is_err() && edge_face_distance(&b, 0, faces).is_err()); +} + +fn checks_valid(name: &str) { + let (b, _) = case(name); + for level in [CheckLevel::Basic, CheckLevel::Geometry, CheckLevel::All] { + let r = check(&b, level).unwrap(); + assert!(r.is_valid(), "{name}, {level:?}: {r}"); + } +} + +/// Refusing is decided on the body's naming scheme alone. An Unknown body is refused rather than +/// reported invalid on every edge; a Caller one without recorded keys is checked under the arena +/// identities (`check_brep` has no error for it, so no error of its can turn into a refusal). +#[test] +fn check_refuses_only_an_unknown_naming() { + use solidcore::topology::NamingScheme; + let name = |naming| { + let (b, _) = case("box"); + b.0.lock().unwrap().set_naming(naming); + check(&b, CheckLevel::All) + }; + let refused = name(NamingScheme::Unknown).unwrap_err().to_string(); + assert!(refused.contains("not supported yet") && refused.contains("NamingScheme::Unknown"), "{refused}"); + name(NamingScheme::Caller).unwrap(); +} + +macro_rules! primitive { + ($m:ident, $name:literal $(, mass: $mass:meta)? $(, area: $area:meta)?) => { + mod $m { + use super::*; + #[test] + $(#[$mass])? + fn mass_properties_match_the_closed_forms() { + mass_properties_match($name); + } + #[test] + $(#[$area])? + fn area_matches_the_closed_form() { + area_matches($name); + } + #[test] + fn bounds_match_the_closed_form() { + bounds_match($name); + } + #[test] + fn is_one_solid() { + one_solid($name); + } + #[test] + fn is_a_manifold_solid() { + manifold_solid($name); + } + #[test] + fn edges_lie_on_their_faces() { + super::edges_lie_on_their_faces($name); + } + #[test] + fn checks_valid() { + super::checks_valid($name); + } + } + }; +} + +primitive!(box_, "box"); +primitive!(cylinder, "cylinder"); +primitive!(sphere, "sphere"); +primitive!(cone, "cone"); +primitive!(frustum, "frustum"); +primitive!(torus, "torus"); + +/// A valid box passes every test at level 2 (SolidCraft's level), with an empty report. +#[test] +fn a_valid_box_passes_level_2() { + let (b, _) = case("box"); + let r = check(&b, CheckLevel::All).unwrap(); + assert_eq!((r.failures, r.text.as_str()), (0, ""), "{r}"); +} + +/// A box with one corner moved 1 mm off its edges, through the arrays: the check finds it broken. +#[test] +fn a_vertex_off_its_edges_fails_the_check() { + use crate::flat::VERTEX_POSITION; + let (b, _) = case("box"); + let mut a = super::to_arrays(&b).unwrap(); + a.reals.get_mut(&VERTEX_POSITION).unwrap()[0] += 1.0; + let broken = super::from_arrays(&a).unwrap(); + let r = check(&broken, CheckLevel::All).unwrap(); + assert!(!r.is_valid(), "{r}"); + assert_eq!(r.failures, r.text.lines().filter(|l| l.contains("::Test #")).count(), "{r}"); +} + +#[test] +fn hostile_numbers_are_refused() { + let (b, _) = case("box"); + assert_eq!(mass_properties(&b, f64::NAN).unwrap_err(), crate::Error::Argument); + assert_eq!(area(&b, f64::INFINITY).unwrap_err(), crate::Error::Argument); + assert_eq!(edge_face_distance(&b, usize::MAX, 0).unwrap_err(), crate::Error::Argument); + // Out of range is clamped, not refused. + assert!(rel(mass_properties(&b, 1e-30).unwrap().volume, 6000.0) < TOL); + assert!(rel(mass_properties(&b, 10.0).unwrap().volume, 6000.0) < TOL); +} + +/// A 20 mm box minus a centred 10 mm box (a sealed void), as solidcore's boolean makes it and as +/// it comes back from arrays listing its solid region's shells inner first. +fn sealed_voids() -> [(&'static str, Body); 2] { + use crate::BooleanOp; + use crate::flat::{FACEUSE_FACE, FACEUSE_ORIENTATION, REGION_SHELL_COUNT, SHELL_FACEUSE_COUNT}; + let body = super::boolean::boolean(&make_box([-10.0; 3], [20.0; 3]).unwrap(), &make_box([-5.0; 3], [10.0; 3]).unwrap(), BooleanOp::Subtract) + .unwrap() + .unwrap(); + // The bounded solid region of two shells: swap their blocks (the shell counts match, as do + // the face-use counts, six faces each), so only the face uses move. + let mut a = super::to_arrays(&body).unwrap(); + let regions = &a.ints[®ION_SHELL_COUNT]; + let first = regions.iter().position(|&n| n == 2).unwrap(); + let shell: usize = regions[..first].iter().map(|&n| usize::try_from(n).unwrap()).sum(); + let counts = &a.ints[&SHELL_FACEUSE_COUNT]; + assert_eq!((counts[shell], counts[shell + 1]), (6, 6)); + let fu: usize = counts[..shell].iter().map(|&n| usize::try_from(n).unwrap()).sum(); + for id in [FACEUSE_FACE, FACEUSE_ORIENTATION] { + let v = a.ints.get_mut(&id).unwrap(); + let (x, y) = v[fu..fu + 12].split_at_mut(6); + x.swap_with_slice(y); + } + let reordered = super::from_arrays(&a).unwrap(); + [("solidcore's", body), ("inner first", reordered)] +} + +/// The sealed void's mass properties: 8000 − 1000 to 1e-9, centroid at the origin, one solid, +/// in either shell order. +#[test] +fn a_sealed_void_measures_its_volume() { + let want = 8000.0 - 1000.0; + // Ixx of a cube of side s about its centre: s⁵ / 6. + let moment = (20.0f64.powi(5) - 10.0f64.powi(5)) / 6.0; + for (at, b) in sealed_voids() { + let m = mass_properties(&b, MEASURE_ACCURACY).unwrap(); + assert!(rel(m.volume, want) < TOL, "{at}: volume {}", m.volume); + assert!(m.centroid.iter().all(|c| c.abs() < TOL * 20.0), "{at}: centroid {:?}", m.centroid); + assert!(m.moments.iter().all(|&i| rel(i, moment) < TOL), "{at}: moments {:?} vs {moment}", m.moments); + assert_eq!(solid_count(&b).unwrap(), 1, "{at}"); + } +} + +/// Two 10 mm squares apart in z = 0, one body of two faces with a shell each (as the top and +/// front of a box offset apart across their edge make, kernel case +/// `surfaces/cov-offset-two-faces-across-a-sharp-edge-come-apart`): `SmBrep` test 21, +/// "Suspicious Shell Count", warns of it, and the capi's check counts no warning. +#[test] +fn faces_apart_with_a_shell_each_check_valid() { + use solidcore::geom::axis2_placement::Axis2Placement; + use solidcore::geom::vector3d::Vec3; + use solidcore::primitive::primitive_creation::p1::create_rectangle; + + use super::boolean::boolean2d; + use super::run; + use crate::BooleanOp; + + let square = |x: f64| { + let frame = Axis2Placement::new(Vec3::new(x, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)); + run("create_rectangle", |k| create_rectangle(k, 0.0, 10.0, 10.0, &frame)).map(Body::new).unwrap() + }; + let b = boolean2d(&square(0.0), &square(20.0), BooleanOp::Union).unwrap().unwrap(); + assert_eq!(counts(&b).unwrap()[0], 2); + for level in [CheckLevel::Basic, CheckLevel::Geometry, CheckLevel::All] { + let r = check(&b, level).unwrap(); + assert!(r.is_valid(), "{level:?}: {r}"); + } +} + +/// `smlib_brep_classify_point` (fork 34d6b2b), the capi test's cases: a 10 x 20 x 30 box at +/// `(1, -2, 3)`: inside, outside, on a face, an edge and a vertex; the cylinder of radius 5 about +/// the z axis through `(1, 2)`: off its curved wall by 1e-8 on it (within the zone tolerance), by +/// 1e-4 inside or outside, on its axis inside, on its top's centre on it. +#[test] +fn points_classify_as_the_capi() { + use super::classify_point; + use crate::measure::PointClass::{Inside, OnBoundary, Outside}; + + let (bx, _) = case("box"); + let (cyl, _) = case("cylinder"); + let c45 = std::f64::consts::FRAC_1_SQRT_2; + let wall = |r: f64| [1.0 + r * c45, 2.0 + r * c45, 3.0]; + let cases = [ + ("box", [6.0, 8.0, 18.0], Inside), + ("box", [6.0, 8.0, 34.0], Outside), + ("box", [0.0, -3.0, 2.0], Outside), + ("box", [6.0, 8.0, 33.0], OnBoundary), + ("box", [11.0, 8.0, 33.0], OnBoundary), + ("box", [11.0, 18.0, 33.0], OnBoundary), + ("box", [1.0, -2.0, 3.0], OnBoundary), + ("cylinder", wall(5.0 + 1e-8), OnBoundary), + ("cylinder", wall(5.0 - 1e-8), OnBoundary), + ("cylinder", wall(5.0 + 1e-4), Outside), + ("cylinder", wall(5.0 - 1e-4), Inside), + ("cylinder", [1.0, 2.0, 3.0], Inside), + ("cylinder", [1.0, 2.0, 9.0], OnBoundary), + ]; + for (name, p, want) in cases { + let body = if name == "box" { &bx } else { &cyl }; + assert_eq!(classify_point(body, p).unwrap(), want, "{name} {p:?}"); + } + assert_eq!(classify_point(&bx, [f64::NAN, 0.0, 0.0]).unwrap_err(), crate::Error::Argument); + assert_eq!(classify_point(&bx, [0.0, f64::INFINITY, 0.0]).unwrap_err(), crate::Error::Argument); +} + +/// A sheet hung on a solid (fork 9767916's capi test): a 10 mm cube and a 10 x 10 sheet on from its +/// top front edge, merged into one body. Its area is every face's, the cube's 600 and the sheet's +/// 100, not the cube's boundary alone; its volume the cube's. +#[test] +fn a_sheet_hung_on_a_solid_counts_in_the_area() { + use solidcore::boolean::api_brep::boolean_merge; + use solidcore::geom::vector3d::Vec3; + use solidcore::primitive::api_primitives::{create_box, create_plane}; + let both = super::run("cube and flap", |k| { + let cube = create_box(k, Vec3::new(0.0, 0.0, 0.0), 10.0, 10.0, 10.0)?; + let flap = create_plane(k, Vec3::new(10.0, 0.0, 10.0), 10.0, 10.0)?; + boolean_merge(k, cube, flap) + }) + .map(Body::new) + .unwrap(); + let m = mass_properties(&both, 1e-8).unwrap(); + assert!((m.area - 700.0).abs() < 1e-6 && (m.volume - 1000.0).abs() < 1e-6, "{m:?}"); +} diff --git a/crates/smlib/src/core/merge.rs b/crates/smlib/src/core/merge.rs new file mode 100644 index 000000000..0590df93b --- /dev/null +++ b/crates/smlib/src/core/merge.rs @@ -0,0 +1,178 @@ +//! Sewing and merging on solidcore: the C API's `smlib_stitch` (the fork's +//! `capi/src/smlib_sheets.cpp`) and `smlib_merge_faces` (`capi/src/smlib_ops.cpp`, with +//! `capi/src/smlib_pick.h`'s `pick_edges`). +//! +//! As there, each works on a copy of its body (`SmApiBrepCopy`). A stitch is `SmBrep::StitchFaces` +//! at the caller's tolerance, once, then `SmBrep::OrientTrimmedSurfaces`: outward where the faces +//! close into a solid, else only made to agree across their shared edges. `StitchAndOrient` is not +//! used, as the capi does not use it: it caps the tolerance and stitches a second time, so the +//! caller's tolerance would not be the one that decides. +//! +//! `StitchFaces` glues an edge only to an edge one face uses: a sheet laid on edges two faces of +//! a solid already share (a cover over a box's cut top) is left beside the solid. As the fork's +//! e5d9bba, edges still lamina after that pass are glued at the same tolerance to the edges they +//! lie on whatever uses those (`bAllowSpineEdges`), on a copy ([`close_onto_shared_edges`]). + +use solidcore::kernel::Kernel; +use solidcore::topology::brep::p1 as bl; +use solidcore::topology::brep::p2::{ArenaNotifyState, is_manifold_solid}; +use solidcore::topology::brep::p3::{DeleteFaceOptions, delete_face, orient_trimmed_surfaces, with_kernel_callbacks}; +use solidcore::topology::brep::p4::stitch_faces; +use solidcore::topology::brep::p5::remove_topological_edges_and_vertices; +use solidcore::topology::face::p2 as face_p2; +use solidcore::topology::topology_traverser::Marks; +use solidcore::topology::{Brep, FaceId, RegionId, edge}; + +use super::Body; +use super::blend::{edge_miss, finish, on_copy, pick_edges, points_ok, status, tolerance_ok}; +use crate::{Error, Result}; +use solidcore::topology::brep::p3::brep_copy; + +type Out = std::result::Result; + +/// `smlib_stitch`: the faces of a copy of `body` sewn along the vertices and edges that coincide +/// within `tolerance` (finite, positive, at most 1e3), then oriented; with whether the result is a +/// closed solid (no lamina edge left and `IsManifoldSolid`). +pub(crate) fn stitch(body: &Body, tolerance: f64) -> Result<(Body, bool)> { + if !tolerance.is_finite() || !(tolerance > 0.0) || tolerance > 1e3 { + return Err(Error::Argument); + } + let mut closed = false; + let r = on_copy("SmBrep::StitchFaces", body, |k, mut b| { + let mut lamina = match stitch_faces(k, &mut b, tolerance, None, false) { + Ok(o) => o.lamina_edges, + Err(e) => return Ok(Err(status(e))), + }; + if lamina != 0 { + b = match close_onto_shared_edges(k, b, tolerance, &mut lamina)? { + Ok(b) => b, + Err(e) => return Ok(Err(e)), + }; + } + let oriented = with_kernel_callbacks(k, &mut b, |k, b, env| { + let mut marks = Marks::default(); + orient_trimmed_surfaces(k, b, env, &mut marks, true, lamina != 0, None) + }); + if let Err(e) = oriented { + return Ok(Err(status(e))); + } + b.refresh_cached_topology(); + closed = lamina == 0 && is_manifold_solid(&b)?; + Ok(Ok(b)) + })?; + Ok((r, closed)) +} + +/// How many regions of `b` are material: neither the infinite region nor a void (`IsVoid`'s +/// `UNSURE` counts as void, as the capi's `!IsVoid()`). +fn material_regions(b: &Brep) -> solidcore::Result { + let infinite = b.infinite_region(); + let mut n = 0; + for r in bl::regions(b, None)? { + n += usize::from(Some(r) != infinite && b.region(r)?.is_void() == 0); + } + Ok(n) +} + +/// The region on the side of `f`'s faceuse `fu` (its shell's), if any. +fn region_of(b: &Brep, fu: Option) -> solidcore::Result> { + let Some(fu) = fu else { return Ok(None) }; + match b.faceuse(fu)?.shell { + Some(sh) => Ok(b.shell(sh)?.region), + None => Ok(None), + } +} + +/// `remove_faces_inside`: every face of `b` lying between two material regions is inside the +/// part and removed (`DeleteFace(f, TRUE, TRUE)` with the B-rep open for editing): its regions +/// are joined, and its edges and vertices nothing else uses go with it. +fn remove_faces_inside(k: &mut Kernel, b: &mut Brep) -> solidcore::Result> { + let infinite = b.infinite_region(); + let mut inside: Vec = Vec::new(); + for f in bl::faces(b, None)? { + let (u1, u2) = face_p2::faceuses(b, f)?; + let (Some(r1), Some(r2)) = (region_of(b, u1)?, region_of(b, u2)?) else { continue }; + let material = |r: RegionId| -> solidcore::Result { Ok(Some(r) != infinite && b.region(r)?.is_void() == 0) }; + if r1 != r2 && material(r1)? && material(r2)? { + inside.push(f); + } + } + let editing = b.editing_enabled(); + b.set_editing_enabled(true); + let mut deleted = Ok(()); + { + let mut state = ArenaNotifyState::new(b); + let mut env = state.env(None); + let mut marks = Marks::default(); + for f in inside { + let options = DeleteFaceOptions { delete_edges_vertices: true, do_region_nesting: true, ..DeleteFaceOptions::default() }; + if let Err(e) = delete_face(k, b, &mut env, &mut marks, f, options) { + deleted = Err(e); + break; + } + } + } + b.set_editing_enabled(editing); + b.refresh_cached_topology(); + Ok(deleted.map_err(status)) +} + +/// `close_onto_shared_edges` (fork e5d9bba): `b`, stitched as a manifold with `lamina` edges +/// left free, those glued at `tolerance` to the edges they lie on whatever uses those +/// (`StitchFaces` with `bAllowSpineEdges`) on a copy. The copy is taken, with its count of +/// lamina edges, when the gluing closed a space (a new, material region) and, the faces then +/// between two material regions removed, no edge has more than two faces; a sheet that closes +/// nothing with the solid's faces stays as the manifold stitch left it. A gluing that leaves +/// fewer material regions than it found (a sheet with no sector between the faces at its rim: +/// glued elsewhere it joins the solid's inside to the outside) is refused, as the capi's +/// `SMLIB_ERR_UNSUPPORTED`. +fn close_onto_shared_edges(k: &mut Kernel, b: Brep, tolerance: f64, lamina: &mut u32) -> solidcore::Result> { + let mut c = brep_copy(k, &b)?; + let material = material_regions(&c)?; + let outcome = match stitch_faces(k, &mut c, tolerance, None, true) { + Ok(o) => o, + Err(e) => return Ok(Err(status(e))), + }; + if outcome.stitched_edges == 0 { + return Ok(Ok(b)); + } + if material_regions(&c)? < material { + return Ok(Err(Error::Unsupported)); + } + if let Err(e) = remove_faces_inside(k, &mut c)? { + return Ok(Err(e)); + } + for e in bl::edges(&c, None)? { + if edge::is_spine(&c, e)? { + return Ok(Ok(b)); + } + } + *lamina = outcome.lamina_edges; + Ok(Ok(c)) +} + +/// `smlib_merge_faces`: `SmBrep::RemoveTopologicalEdgesAndVertices` on a copy of `body`, keeping +/// the edges nearest `keep` (each within `tolerance`); then `finish` (faces left, and a solid in +/// gives a manifold solid). +pub(crate) fn merge_faces(body: &Body, keep: &[[f64; 3]], tolerance: f64) -> Result { + if !points_ok(keep, true) || !tolerance_ok(tolerance) { + return Err(Error::Argument); + } + on_copy("SmBrep::RemoveTopologicalEdgesAndVertices", body, |k, mut b| { + let kept = if keep.is_empty() { + Vec::new() + } else { + match pick_edges(k, &b, keep, tolerance)? { + Ok((edges, _)) => edges, + Err(m) => return Ok(Err(edge_miss(m))), + } + }; + let solid_in = is_manifold_solid(&b)?; + let keep_edges = (!kept.is_empty()).then_some(kept.as_slice()); + if let Err(e) = remove_topological_edges_and_vertices(k, &mut b, keep_edges, None) { + return Ok(Err(status(e))); + } + b.refresh_cached_topology(); + finish(b, solid_in) + }) +} diff --git a/crates/smlib/src/core/merge_tests.rs b/crates/smlib/src/core/merge_tests.rs new file mode 100644 index 000000000..23573197f --- /dev/null +++ b/crates/smlib/src/core/merge_tests.rs @@ -0,0 +1,356 @@ +//! Stitch and merge faces on solidcore, against closed forms: counts, volumes (or areas) and +//! whether the result closes, and every result exports to a record that validates. +//! +//! A stitch's input is six (or five) separate planar faces of a 10 mm cube, each its own face of +//! one body with its own edges, none shared; a merge's is a cube with four faces cut across, or +//! two boxes unioned, on solidcore. + +use std::collections::BTreeMap; + +use solidcore::curve::curve::Curve; +use solidcore::curve::line::Line; +use solidcore::geom::extent2d::Extent2d; +use solidcore::geom::vector2d::Vec2; +use solidcore::geom::vector3d::Vec3; +use solidcore::kernel::Kernel; +use solidcore::nurbs::b_spline_curve::p1::KnotType; +use solidcore::nurbs::b_spline_surface::p1::{BSplineSurface, BSplineSurfaceForm, CanonicalSurfaceData}; +use solidcore::primitive::api_primitives::{create_box, create_plane}; +use solidcore::primitive::api_trim_ops::trim_surface_with_3d_curves; +use solidcore::surface::plane::p1::Plane; +use solidcore::surface::surface::Surface; +use solidcore::topology::Brep; +use solidcore::topology::brep::p2::ArenaNotifyState; +use solidcore::topology::brep::p3::{merge_brep, new_brep}; +use solidcore::topology::brep::p8::create_face_from_surface; + +use super::merge::{merge_faces, stitch}; +use super::sweep::build_faces; +use super::{Body, area, bounds, counts, make_box, run, to_arrays, volume}; +use crate::export::native; +use crate::{BooleanOp, Error}; + +const TOL: f64 = 0.01; + +/// The sides of the cube [0, 10]^3 as (origin, u axis, v axis), each over [0, 10]^2. +const SIDES: [([f64; 3], [f64; 3], [f64; 3]); 6] = [ + ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), + ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]), + ([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), + ([10.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), + ([0.0, 10.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]), + ([0.0, 0.0, 10.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), +]; + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// The sides `sides` of the cube as separate faces of one body, the top lifted by `lift`. +fn loose_faces(sides: &[usize], lift: f64) -> Body { + run("loose faces", |k| { + let mut b = new_brep(k, solidcore::geom::tol::USE_DEFAULT, solidcore::geom::tol::USE_DEFAULT)?; + for &i in sides { + let Some(&(mut o, u, v)) = SIDES.get(i) else { continue }; + if i == 5 { + o[2] += lift; + } + let plane = Plane::new(v3(o), v3(u), v3(v), Vec2::new(1.0, 1.0), &Extent2d::from_bounds(0.0, 0.0, 10.0, 10.0)); + let domain = Extent2d::from_bounds(0.0, 0.0, 10.0, 10.0); + build_faces(&mut b, |b, fenv| create_face_from_surface(k, b, Some(Surface::from(plane)), &domain, fenv))?; + } + b.refresh_cached_topology(); + Ok(b) + }) + .map(Body::new) + .unwrap() +} + +/// Two 10 mm cubes side by side along x, unioned: one 20 x 10 x 10 block. +fn two_boxes() -> Body { + let a = make_box([0.0; 3], [10.0; 3]).unwrap(); + let b = make_box([10.0, 0.0, 0.0], [10.0; 3]).unwrap(); + super::boolean::boolean(&a, &b, BooleanOp::Union).unwrap().unwrap() +} + +/// The cube with its four faces across x = 5 cut there (`split_faces`): ten faces. +fn split_cube() -> Body { + let plane = crate::ssi::Spec::Plane { origin: [5.0, 0.0, 0.0], xaxis: [0.0, 1.0, 0.0], yaxis: [0.0, 0.0, 1.0], u: [-1.0, 11.0], v: [-1.0, 11.0] }; + let cube = make_box([0.0; 3], [10.0; 3]).unwrap(); + super::split::split_faces(&cube, &[0, 1, 2, 3, 4, 5], &[&plane]).unwrap().unwrap().0 +} + +#[derive(Clone, Copy, Debug)] +enum Input { + SplitCube, + /// [`loose_faces`]: which sides, the top's lift. + Loose(&'static [usize], f64), + TwoBoxes, + Box, +} + +impl Input { + fn core(self) -> Body { + match self { + Input::Loose(sides, lift) => loose_faces(sides, lift), + Input::TwoBoxes => two_boxes(), + Input::SplitCube => split_cube(), + Input::Box => make_box([0.0; 3], [10.0; 3]).unwrap(), + } + } +} + +#[derive(Clone, Copy, Debug)] +enum Op { + Stitch(Input, f64), + Merge(Input, &'static [[f64; 3]], f64), +} + +#[derive(Clone, Debug, PartialEq)] +enum Expect { + /// A solid: volume, counts, closed. + Solid(f64, [usize; 3], bool), + /// A sheet: area, counts, closed. + Sheet(f64, [usize; 3], bool), + Fails(Error), +} + +const ALL: &[usize] = &[0, 1, 2, 3, 4, 5]; +const OPEN: &[usize] = &[0, 1, 2, 3, 4]; + +fn case(name: &str) -> (Op, Expect) { + match name { + "stitch_six_faces_into_a_cube" => (Op::Stitch(Input::Loose(ALL, 0.0), TOL), Expect::Solid(1000.0, [6, 12, 8], true)), + "stitch_five_faces_into_an_open_box" => (Op::Stitch(Input::Loose(OPEN, 0.0), TOL), Expect::Sheet(500.0, [5, 12, 8], false)), + // The top 0.05 mm above the walls: farther than the tolerance, so it stays apart. + "stitch_leaves_a_gap_wider_than_the_tolerance" => (Op::Stitch(Input::Loose(ALL, 0.05), TOL), Expect::Sheet(600.0, [6, 16, 12], false)), + // Within a 0.1 mm tolerance, the same gap closes. + // (the top stays on its own plane, so the solid reaches up to it) + "stitch_closes_a_gap_within_the_tolerance" => (Op::Stitch(Input::Loose(ALL, 0.05), 0.1), Expect::Solid(1005.0, [6, 12, 8], true)), + "stitch_a_cube_already_sewn" => (Op::Stitch(Input::Box, TOL), Expect::Solid(1000.0, [6, 12, 8], true)), + "merge_two_boxes_into_one_block" => (Op::Merge(Input::TwoBoxes, &[], TOL), Expect::Solid(2000.0, [6, 12, 8], false)), + "merge_a_split_cube_into_one" => (Op::Merge(Input::SplitCube, &[], TOL), Expect::Solid(1000.0, [6, 12, 8], false)), + "merge_a_box_changes_nothing" => (Op::Merge(Input::Box, &[], TOL), Expect::Solid(1000.0, [6, 12, 8], false)), + "merge_keeps_a_picked_edge" => (Op::Merge(Input::SplitCube, &[[5.0, 5.0, 10.0]], TOL), Expect::Solid(1000.0, [7, 15, 10], false)), + "merge_picks_near_nothing" => { + (Op::Merge(Input::SplitCube, &[[5.0, 5.0, 10.0], [50.0, 50.0, 50.0]], TOL), Expect::Fails(Error::NoMatch { point: 1 })) + } + _ => panic!("no case {name}"), + } +} + +#[derive(Debug, PartialEq)] +struct Measured { + size: f64, + counts: [usize; 3], + closed: bool, + bounds: ([f64; 3], [f64; 3]), + kinds: BTreeMap, +} + +type Got = std::result::Result; + +fn kinds(rec: &solidcore_record::brep::Brep) -> BTreeMap { + let mut out = BTreeMap::new(); + for f in &rec.faces { + let v = serde_json::to_value(&f.surface).unwrap(); + *out.entry(v["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1; + } + out +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +fn judge(name: &str, who: &str, got: Got) -> Got { + let (op, expect) = case(name); + match (&expect, &got) { + (Expect::Fails(e), Err(g)) => assert_eq!(g, e, "{name}: {who} failed otherwise"), + (Expect::Fails(e), Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"), + (_, Err(g)) => panic!("{name}: {who} failed: {g}"), + (Expect::Solid(s, n, closed) | Expect::Sheet(s, n, closed), Ok(m)) => { + assert!(rel(m.size, *s) < 1e-9, "{name}: {who} size {} vs analytic {s}", m.size); + assert_eq!(m.counts, *n, "{name}: {who} counts"); + if matches!(op, Op::Stitch(..)) { + assert_eq!(m.closed, *closed, "{name}: {who} closed"); + } + } + } + got +} + +fn is_sheet(name: &str) -> bool { + matches!(case(name).1, Expect::Sheet(..)) +} + +fn solidcore_case(name: &str) -> Got { + let (op, _) = case(name); + let r = match op { + Op::Stitch(input, tol) => stitch(&input.core(), tol), + Op::Merge(input, keep, tol) => merge_faces(&input.core(), keep, tol).map(|b| (b, false)), + }; + let got = r.map(|(b, closed)| { + let (rec, _) = native(&to_arrays(&b).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + let size = if is_sheet(name) { area(&b, 1e-8) } else { volume(&b, 1e-8) }.unwrap(); + Measured { size, counts: counts(&b).unwrap(), closed, bounds: bounds(&b).unwrap(), kinds: kinds(&rec) } + }); + judge(name, "solidcore", got) +} + +macro_rules! cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +cases!( + stitch_six_faces_into_a_cube, + stitch_five_faces_into_an_open_box, + stitch_leaves_a_gap_wider_than_the_tolerance, + stitch_closes_a_gap_within_the_tolerance, + stitch_a_cube_already_sewn, + merge_two_boxes_into_one_block, + merge_a_split_cube_into_one, + merge_a_box_changes_nothing, + merge_keeps_a_picked_edge, + merge_picks_near_nothing, +); + +/// The capi's argument checks, before any kernel call. +#[test] +fn hostile_arguments_are_refused() { + let b = make_box([0.0; 3], [10.0; 3]).unwrap(); + for t in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e3 + 1.0] { + assert_eq!(stitch(&b, t).err(), Some(Error::Argument), "stitch tolerance {t}"); + } + for t in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e6] { + assert_eq!(merge_faces(&b, &[], t).err(), Some(Error::Argument), "merge tolerance {t}"); + } + assert_eq!(merge_faces(&b, &[[f64::NAN, 0.0, 0.0]], TOL).err(), Some(Error::Argument)); + let many = vec![[0.0; 3]; crate::MAX_POINTS + 1]; + assert_eq!(merge_faces(&b, &many, TOL).err(), Some(Error::Argument)); +} + +/// A 10 mm cube and, unsewn in the same body (`MergeBrep`), a sheet made on the kernel. +fn cube_and_sheet(sheet: impl FnOnce(&mut Kernel) -> solidcore::Result) -> Body { + run("cube and sheet", |k| { + let mut cube = create_box(k, Vec3::new(0.0, 0.0, 0.0), 10.0, 10.0, 10.0)?; + let sheet = sheet(k)?; + let mut state = ArenaNotifyState::new(&cube); + let mut env = state.env(None); + merge_brep(k, &mut env, &mut cube, &sheet, &solidcore::topology::brep::p2::copy_source_ref, None, None, true)?; + cube.refresh_cached_topology(); + Ok(cube) + }) + .map(Body::new) + .unwrap() +} + +/// The capi's `cube_and_cover` (capi/tests/sheets.cpp): the cube and a cover over its top, a +/// height field z(x, y) over [0, 10]^2 of `degree` and uniform `spans`, its control points at +/// their Greville abscissae (so its parameters are x and y), z = 10 but for the middle one, +/// 10 + `rise`, trimmed to the square by lines (`SmApiTrimSurfaceWith3dCurves`), so its rim is the +/// cube's top edges. +fn cube_and_cover(degree: usize, spans: usize, rise: f64) -> Body { + cube_and_sheet(|k| { + let n = spans + degree; + let step = 10.0 / spans as f64; + let unique: Vec = (0..=spans).map(|k| step * k as f64).collect(); + let mult: Vec = (0..=spans).map(|k| if k == 0 || k == spans { degree + 1 } else { 1 }).collect(); + let knots: Vec = unique.iter().zip(&mult).flat_map(|(&u, &m)| std::iter::repeat_n(u, m)).collect(); + let greville: Vec = (0..n).map(|i| knots[i + 1..=i + degree].iter().sum::() / degree as f64).collect(); + let mut net = Vec::with_capacity(n * n); + for i in 0..n { + for j in 0..n { + let z = if 2 * i + 1 == n && 2 * j + 1 == n { 10.0 + rise } else { 10.0 }; + net.push(Vec3::new(greville[i], greville[j], z)); + } + } + let surface = BSplineSurface::create_canonical(&CanonicalSurfaceData { + u_degree: degree, + v_degree: degree, + control_points: &net, + form: BSplineSurfaceForm::Unspecified, + u_multiplicities: &mult, + v_multiplicities: &mult, + u_knots: &unique, + v_knots: &unique, + knot_type: KnotType::Unspecified, + weights: None, + uv_domain: None, + })?; + let corner = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]].map(|[x, y]| Vec3::new(x, y, 10.0)); + let mut sides = Vec::with_capacity(4); + for i in 0..4 { + sides.push(Curve::from(Line::create_line_segment(3, corner[i], corner[(i + 1) % 4], None)?)); + } + trim_surface_with_3d_curves(k, Surface::from(surface), &[4], sides) + }) +} + +/// A biquadratic Bezier cover rising 9 at its middle control point, +/// z = 10 + 9 * 2s(1-s) * 2t(1-t) (s = x/10, t = y/10): the capi's cover. +fn cube_and_biquadratic_cover() -> Body { + cube_and_cover(2, 1, 9.0) +} + +/// A bicubic cover over 8 spans whose only raised control point is the middle one: the capi's +/// cover lying on the cube's top for 2.5 mm in from every edge. +fn cube_and_bicubic_cover() -> Body { + cube_and_cover(3, 8, 9.0) +} + +/// The capi's flap: a 10 x 10 sheet on from the cube's top edge at x = 10, in the plane z = 10. +fn cube_and_flap() -> Body { + cube_and_sheet(|k| create_plane(k, Vec3::new(10.0, 0.0, 10.0), 10.0, 10.0)) +} + +/// The space between the cover and the cube's top encloses 9 * (10/3)^2 = 100 mm^3: sewn, it is +/// part of the solid and the top, now inside it, goes. A closed solid of the cube's five other +/// faces and the cover, 1100 mm^3. +#[test] +fn a_cover_sews_onto_a_cube_into_a_closed_solid() { + let (sewn, closed) = stitch(&cube_and_biquadratic_cover(), 1e-6).unwrap(); + assert!(closed); + assert_eq!(counts(&sewn).unwrap()[0], 6); + let v = volume(&sewn, 1e-8).unwrap(); + assert!((v - 1100.0).abs() < 1e-6, "volume {v}"); +} + +/// The bicubic cover overlaps the top: no sector between the faces at the rim to sew it into, so +/// it is refused, not sewn so that the cube's inside joins the outside. +#[test] +fn a_cover_lying_on_the_cube_is_refused() { + assert_eq!(stitch(&cube_and_bicubic_cover(), 1e-6).err(), Some(Error::Unsupported)); +} + +/// The flap closes nothing with the cube: it stays the sheet beside it the manifold stitch +/// leaves, not glued into an edge three faces would share. +#[test] +fn a_flap_on_a_cube_edge_stays_beside_it() { + let (sewn, closed) = stitch(&cube_and_flap(), 1e-6).unwrap(); + assert!(!closed); + assert_eq!(counts(&sewn).unwrap()[0], 7); + let (v, a) = (volume(&sewn, 1e-8).unwrap(), area(&sewn, 1e-8).unwrap()); + assert!((v - 1000.0).abs() < 1e-6 && (a - 700.0).abs() < 1e-6, "volume {v}, area {a}"); +} + +/// The inputs are never changed. +#[test] +fn the_body_stays_as_it_was() { + let loose = loose_faces(ALL, 0.0); + let _ = stitch(&loose, TOL).unwrap(); + assert_eq!(counts(&loose).unwrap(), [6, 24, 24]); + let block = two_boxes(); + let was = counts(&block).unwrap(); + let _ = merge_faces(&block, &[], TOL).unwrap(); + assert_eq!(counts(&block).unwrap(), was); +} diff --git a/crates/smlib/src/core/offset.rs b/crates/smlib/src/core/offset.rs new file mode 100644 index 000000000..25d1d3a6f --- /dev/null +++ b/crates/smlib/src/core/offset.rs @@ -0,0 +1,664 @@ +//! Shells, face offsets, thickening, sheet offsets and drafts on solidcore: the C API's logic +//! round SMLib's offset executive, ported from the fork's `capi/src/smlib_ops.cpp` +//! (`smlib_shell`, `smlib_offset_faces`, `smlib_thicken`, `smlib_draft`, `leaves_cavity`, +//! `FaceSet`, `outer_faceuse`, `move_faces`, `draft_faces`), `capi/src/smlib_sheets.cpp` +//! (`smlib_offset_sheet`) and `capi/src/smlib_pick.h` (`pick_faces`). +//! +//! As there, every operation works on a copy of its body (`SmApiBrepCopy`) and picks faces by +//! point; the shell and the offsets are `SmApiShellBrepFull` and `SmApiOffsetBrepFull`, with +//! convex edges extended and the results merged. A sheet offset takes faces that close into a +//! solid as the capi does since tangency-labs/smlib#17. +//! +//! A draft tilts planes and, since tangency-labs/smlib#27, turns a cylinder about the pull into +//! a cone (solidcore's `Cone::lean_cylinder`, solidcore#1545), and since smlib#53 a cone about the +//! pull into the cone its generators turned make. A draft's tilted faces go in through solidcore's +//! `SmBrep::LocalOperation` ([`local_operation`]). The capi's check that it moved some face +//! (`moved_faces`) marks the replacement surfaces; solidcore names a surface by its owning face, so +//! the mark goes on the picked faces, which it stays with through the operation (solidcore#1875). + +use solidcore::EntityRef; +use solidcore::SolidError; +use solidcore::geom::attribute::{Attribute, Behavior, ids}; +use solidcore::geom::axis2_placement::Axis2Placement; +use solidcore::geom::object::Shape; +use solidcore::geom::vector3d::{Point3, Vec3}; +use solidcore::intersect::point_class::PointClassType; +use solidcore::kernel::Kernel; +use solidcore::math::Point2; +use solidcore::nurbs::b_spline_curve::ControlPointForm; +use solidcore::nurbs::b_spline_surface::p1::SurfParamType; +use solidcore::nurbs::b_spline_surface_n_lib::p2::OrientType; +use solidcore::nurbs::knots::Side; +use solidcore::offset::construction::ShellRefusal; +use solidcore::offset::offset_executive::p2::{OffsetOptions, ShellOptions, local_operation_simple, offset_brep_simple, shell_brep_simple}; +use solidcore::offset::offset_faces::{OffsetFacesExecutive, OffsetFacesRefusal}; +use solidcore::query::api_queries::{face_bounding_box, face_classify_uv, face_closest_point_in_shape, face_internal_point}; +use solidcore::query::brep::{BrepIdentity, BrepQuery, LiveBrepObjects}; +use solidcore::surface::cone::Cone; +use solidcore::surface::surface::{Surface, SurfaceKind}; +use solidcore::topology::brep::{p1 as brep_p1, p2 as brep_p2}; +use solidcore::topology::face::p2 as face_p2; +use solidcore::topology::{Brep, BrepId, FaceId, FaceuseId}; + +use super::blend::{Miss, on_copy, p3, pick, points_ok, status as blend_status, tolerance_ok}; +use super::{Body, answer}; +use crate::{Error, Result}; + +/// The capi's statuses as SolidCraft errors: an operation's own result. +type Out = std::result::Result; + +/// `SM_ERR_INVALID_INPUT`. +const INVALID_INPUT: i32 = 1007; + +/// `SM_ERR_OFFSET_WALLS_TOUCH` (fork a759622), which `status` (smlib_shim.h) reports as +/// `SMLIB_ERR_WALLS_TOUCH`. +const OFFSET_WALLS_TOUCH: i32 = 1042; + +/// `status` (smlib_shim.h): an offset whose walls touch is [`Error::WallsTouch`]; a vertex moved +/// past an edge's other end (`SM_ERR_OFFSET_EDGE_VANISHES`, fork 34318f4) is +/// `SMLIB_ERR_UNSUPPORTED`; a wall whose face's offset folds, which solidcore's one construction +/// refuses (`fixes.shell_one_construction`, solidcore#2367), is [`Error::WallFolds`] with the +/// largest wall it names; any other status as the blends pass it on. +fn status(e: SolidError) -> Error { + match e { + SolidError::Upstream { code: OFFSET_WALLS_TOUCH, .. } => Error::WallsTouch, + SolidError::ShellRefused { refusal: ShellRefusal::Fold, size, .. } => Error::WallFolds { largest: size }, + e if e.is_offset_edge_vanishes() => Error::Unsupported, + e => blend_status(e), + } +} + +/// `std::fabs(x) > 1e6` and the rest of the capi's size checks: finite, not zero, at most 1e6. +fn distance_ok(x: f64) -> bool { + x.is_finite() && x != 0.0 && x.abs() <= 1e6 +} + +/// The B-rep id every shape and face key in this module names the one body by. +const ONE: BrepId = BrepId::from_index(0); + +/// Faces with their loose bounding boxes, for nearest-face queries (`FaceSet`). +struct FaceSet { + faces: Vec, + boxes: Vec<(Point3, Point3)>, + /// Each face's shape (`SmApiFaceClosestPoint` makes one per query; it depends only on the + /// face, so it is made once). + shapes: Vec, +} + +impl FaceSet { + fn new() -> FaceSet { + FaceSet { faces: Vec::new(), boxes: Vec::new(), shapes: Vec::new() } + } + + /// `add`: false when the face's box cannot be measured. + fn add(&mut self, k: &mut Kernel, b: &Brep, f: FaceId) -> solidcore::Result { + let Some(bx) = answer(face_bounding_box(k, b, f, false))? else { return Ok(false) }; + let Some(shape) = answer(Shape::new(k, &(ONE, b), &[], &[(ONE, f)], &[], &[]))? else { return Ok(false) }; + self.faces.push(f); + self.boxes.push((bx.min(), bx.max())); + self.shapes.push(shape); + Ok(true) + } + + /// `nearest`: the distance from `p` to the nearest face, with the nearest point; infinite + /// when none answers. A face whose box is farther than the nearest face so far is skipped. + fn nearest(&self, k: &Kernel, live: &LiveBrepObjects<'_, '_>, p: Point3) -> solidcore::Result<(f64, Option)> { + let (mut best, mut at) = (f64::INFINITY, None); + for ((&f, (lo, hi)), shape) in self.faces.iter().zip(&self.boxes).zip(&self.shapes) { + let mut bx = 0.0; + for (l, (h, x)) in [lo.x, lo.y, lo.z].into_iter().zip([hi.x, hi.y, hi.z].into_iter().zip([p.x, p.y, p.z])) { + let out = (l - x).max((x - h).max(0.0)); + bx += out * out; + } + if f64::sqrt(bx) >= best { + continue; + } + if let Some(c) = answer(face_closest_point_in_shape(k, shape, live, (ONE, f), p))? + && c.distance.is_finite() + && c.distance < best + { + best = c.distance; + at = Some(c.point); + } + } + Ok((best, at)) + } +} + +/// The live view of `b` the closest-point solves read, under `identity`: `query`'s effective +/// identity ([`BrepQuery::effective_identity`]). +fn live<'a, 'i>(b: &'a mut Brep, identity: &'a BrepIdentity<'i>) -> solidcore::Result> { + LiveBrepObjects::new(b, identity, None) +} + +/// `pick_faces` (`face_distance`: `SmApiFaceClosestPoint`; a face whose query returns a status +/// other than success is skipped, [`answer`]). +pub(super) fn pick_faces(k: &mut Kernel, b: &mut Brep, points: &[[f64; 3]], tol: f64) -> solidcore::Result, Miss>> { + let all = brep_p1::faces(b, None)?; + let model_tol = b.tolerance(); + let mut shapes = Vec::with_capacity(all.len()); + for &f in &all { + shapes.push(answer(Shape::new(k, &(ONE, &*b), &[], &[(ONE, f)], &[], &[]))?); + } + let query = BrepQuery::of_brep(b); + let identity = query.effective_identity(); + let objects = live(b, &identity)?; + let k: &Kernel = k; + let indices: Vec = (0..all.len()).collect(); + let picked = pick(&indices, points, tol, model_tol, |i, p| { + let (Some(&f), Some(Some(shape))) = (all.get(i), shapes.get(i)) else { return Ok(None) }; + Ok(answer(face_closest_point_in_shape(k, shape, &objects, (ONE, f), p))?.map(|c| c.distance)) + })?; + Ok(picked.map(|(p, _)| p.iter().filter_map(|&i| all.get(i).copied()).collect())) +} + +/// A face pick's failure as `pick_error` (ops.rs) reads it. +pub(super) fn face_miss(m: Miss) -> Error { + match m { + Miss::None(point) => Error::NoMatch { point }, + Miss::Ambiguous(point) => Error::Ambiguous { point }, + } +} + +/// `outer_faceuse`: the faceuse of `f` on the outside of its body, the one bounding the infinite +/// region (for a sheet, both do; then the upward one). +fn outer_faceuse(b: &Brep, f: FaceId) -> solidcore::Result> { + let Some(fu) = face_p2::upward_faceuse(b, f)? else { return Ok(None) }; + let use_ = b.faceuse(fu)?; + let outside = match use_.shell { + Some(s) => b.shell(s)?.region.is_some() && b.shell(s)?.region == b.infinite_region(), + None => false, + }; + Ok(if outside { Some(fu) } else { use_.mate }) +} + +/// `leaves_cavity`: whether an inward offset of `wall` (> 0) from every face of the solid `b` +/// but `open` leaves a cavity: a point inside `b` farther than `wall`, and a margin, from every +/// face that is offset. A point counts only as the centre of a ball inside `b`, reached from a +/// face sample by stepping inward along the normal, then from ball to ball. The capi refuses a +/// wall this finds no room for before SMLib sees it (C++ SMLib corrupts memory there, +/// solidcore#380); the same refusal here keeps the C++ path's answer. +fn leaves_cavity(k: &mut Kernel, b: &mut Brep, open: &[FaceId], wall: f64) -> solidcore::Result { + let list = brep_p1::faces(b, None)?; + let (mut all, mut walls) = (FaceSet::new(), FaceSet::new()); + for &f in &list { + if !all.add(k, b, f)? { + return Ok(false); + } + if !open.contains(&f) && !walls.add(k, b, f)? { + return Ok(false); + } + } + if walls.faces.is_empty() { + return Ok(true); + } + let tol = b.tolerance(); + let margin = (10.0 * tol).max(1e-3 * wall); + let need = wall + margin; + // Face samples: a grid over each offset face's domain, the points inside its trims, each + // with the inward unit normal there. + const GRID: usize = 5; + const MAX_SAMPLES: usize = 2048; + let mut samples: Vec<(Point3, Vec3)> = Vec::new(); + for &f in &walls.faces { + let Some(fu) = outer_faceuse(b, f)? else { continue }; + let inward = if b.faceuse(fu)?.orientation == OrientType::Same { -1.0 } else { 1.0 }; + let dom = b.face(f)?.uv_domain; + for i in 0..GRID { + for j in 0..GRID { + if samples.len() >= MAX_SAMPLES { + break; + } + let uv: Point2 = dom.evaluate((i as f64 + 0.5) / GRID as f64, (j as f64 + 0.5) / GRID as f64); + if answer(face_classify_uv(k, b, f, uv))? != Some(PointClassType::Face) { + continue; + } + let Some(surf) = b.face(f)?.surface.as_ref() else { break }; + let (Some(at), Some(n)) = (answer(surf.evaluate_point(k, uv))?, answer(surf.evaluate_normal(k, uv, Side::Left, Side::Left))?) else { + continue; + }; + let len = n.length(); + if !(len > 0.0) || !len.is_finite() { + continue; + } + samples.push((at, n * (inward / len))); + } + } + } + let query = BrepQuery::of_brep(b); + let identity = query.effective_identity(); + let objects = live(b, &identity)?; + let k: &Kernel = k; + // A step of `h` inward from a sample ends at a ball's centre when no face is nearer to it + // than `h` (the step crossed none, and the ball touches only the sample's face). + let ball = |s: Point3, n: Vec3, h: f64| -> solidcore::Result<(bool, Point3, f64)> { + let c = s + n * h; + let (r, _) = all.nearest(k, &objects, c)?; + Ok((r.is_finite() && r >= h * (1.0 - 1e-9), c, r)) + }; + // First the direct step of `need` from each sample. + for &(s, n) in &samples { + let (inside, c, _) = ball(s, n, need)?; + if inside && walls.nearest(k, &objects, c)?.0 >= need { + return Ok(true); + } + } + // Then climbing, from a small ball at each sample: step away from the nearest offset face by + // most of the ball's radius (staying inside the ball, so inside the body) while the distance + // from the offset faces grows. + const STEPS: usize = 48; + for &(s, n) in &samples { + let (inside, mut c, mut r) = ball(s, n, margin.max(1e3 * tol))?; + if !inside { + continue; + } + for _ in 0..STEPS { + let (d, q) = walls.nearest(k, &objects, c)?; + if d >= need { + return Ok(true); + } + let Some(q) = q.filter(|_| d > 0.0 && d.is_finite()) else { break }; + let next = c + (c - q) * (0.9 * r / d); + let (rn, _) = all.nearest(k, &objects, next)?; + if !(rn > 0.0) || !rn.is_finite() || walls.nearest(k, &objects, next)?.0 <= d * (1.0 + 1e-9) { + break; + } + c = next; + r = rn; + } + } + Ok(false) +} + +/// `SmApiShellBrepFull(b, distance, TRUE, TRUE, TRUE, open, r)`: convex edges extended, results +/// merged, side walls made at a sheet's edges, and (as the fork does, 5448b9a) a thickened +/// sheet's coplanar side walls one face. +fn shell_brep_full(k: &mut Kernel, b: &Brep, distance: f64, open: &[FaceId]) -> solidcore::Result { + let options = ShellOptions { + offset: OffsetOptions { distance, extend_convex_edges: true, merge_results: true }, + create_offset_solid: true, + merge_sheet_side_walls: true, + }; + shell_brep_simple(k, b, options, open) +} + +/// `SmApiOffsetBrepFull(b, distance, TRUE, TRUE, r)`. +fn offset_brep_full(k: &mut Kernel, b: &mut Brep, distance: f64) -> solidcore::Result { + offset_brep_simple(k, b, OffsetOptions { distance, extend_convex_edges: true, merge_results: true }) +} + +/// `finish`: the result must have faces, and a solid input must give a closed manifold solid. +fn finish(b: Brep, solid_in: bool) -> solidcore::Result> { + if b.face_list().is_empty() { + return Ok(Err(Error::Empty)); + } + if solid_in && !brep_p2::is_manifold_solid(&b)? { + return Ok(Err(Error::NotSolid)); + } + Ok(Ok(b)) +} + +/// An SMLib call's own status passed on (`status(...)` in the capi), else the value. +fn called(r: solidcore::Result) -> solidcore::Result> { + match r { + Ok(v) => Ok(Ok(v)), + Err(e) => Ok(Err(status(e))), + } +} + +/// `smlib_shell`: the faces nearest `points` (each within `tolerance`) opened, the rest offset +/// by `thickness` (negative: inward) into a wall; none gives a closed hollow body. An inward +/// wall of a solid that leaves no cavity is [`Error::NoRoom`], refused before the shell. +pub(crate) fn shell(body: &Body, points: &[[f64; 3]], tolerance: f64, thickness: f64) -> Result { + if !points_ok(points, true) || !tolerance_ok(tolerance) || !distance_ok(thickness) { + return Err(Error::Argument); + } + on_copy("smlib_shell", body, |k, mut w| { + let picked = match pick_faces(k, &mut w, points, tolerance)? { + Ok(p) => p, + Err(m) => return Ok(Err(face_miss(m))), + }; + let solid_in = brep_p2::is_manifold_solid(&w)?; + if thickness < 0.0 && solid_in && !leaves_cavity(k, &mut w, &picked, -thickness)? { + return Ok(Err(Error::NoRoom)); + } + match called(shell_brep_full(k, &w, thickness, &picked))? { + Ok(r) => finish(r, solid_in), + Err(e) => Ok(Err(e)), + } + }) +} + +/// `smlib_offset_faces`: its checks, the pick, the solid check, (moving faces in) the cavity +/// check, then `move_faces`. +pub(crate) fn offset_faces(body: &Body, points: &[[f64; 3]], tolerance: f64, distance: f64) -> Result { + if !points_ok(points, false) || !tolerance_ok(tolerance) || !distance_ok(distance) { + return Err(Error::Argument); + } + on_copy("smlib_offset_faces", body, |k, mut w| { + let picked = match pick_faces(k, &mut w, points, tolerance)? { + Ok(p) => p, + Err(m) => return Ok(Err(face_miss(m))), + }; + if !brep_p2::is_manifold_solid(&w)? { + return Ok(Err(Error::Argument)); + } + // Faces moved in so far that no material is left behind them: the body must reach + // deeper than the move behind the moved faces. + if distance < 0.0 { + let others: Vec = brep_p1::faces(&w, None)?.into_iter().filter(|f| !picked.contains(f)).collect(); + if !leaves_cavity(k, &mut w, &others, -distance)? { + return Ok(Err(Error::NoRoom)); + } + } + match move_faces(k, &mut w, &picked, distance) { + Ok(()) => finish(w, true), + Err(e) => Ok(Err(e)), + } + }) +} + +/// `move_faces`: moves the picked faces of `b` (in place) `distance` along their outward normals: +/// each gets its surface's offset, and the local operation extends or trims the faces around them +/// to meet it; the tangent blends on them follow (`SmOffsetFacesExecutive`: taken off, the faces +/// moved, put back at their own sizes). A blend that no longer fits is [`Error::NoRoom`], one that +/// cannot be put back as it was [`Error::Unsupported`], one that would need a continuation that +/// cannot be made exactly [`Error::NotExact`], a move that moved nothing [`Error::NoEffect`]. +fn move_faces(k: &mut Kernel, b: &mut Brep, picked: &[FaceId], distance: f64) -> Out<()> { + let mut exec = OffsetFacesExecutive::new(); + exec.offset_faces(k, b, picked, distance).map_err(|e| match exec.refusal() { + OffsetFacesRefusal::NoRoom => Error::NoRoom, + OffsetFacesRefusal::Unsupported => Error::Unsupported, + OffsetFacesRefusal::NotExact => Error::NotExact, + OffsetFacesRefusal::NoEffect => Error::NoEffect, + // Not in the fork (solidcore#2020, #2027): the blends cannot be put back, the fillet's + // status kept. SolidCraft has no such error: a move solidcore does not make. + OffsetFacesRefusal::NotPutBack => Error::Unsupported, + OffsetFacesRefusal::None => status(e), + }) +} + +/// `smlib_thicken`: a sheet thickened by `thickness` along its normals, or (symmetric) moved back +/// by half first; a closed solid is [`Error::Argument`]. +pub(crate) fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result { + if !distance_ok(thickness) { + return Err(Error::Argument); + } + on_copy("smlib_thicken", body, |k, mut w| { + if brep_p2::is_manifold_solid(&w)? { + return Ok(Err(Error::Argument)); + } + if symmetric { + w = match called(offset_brep_full(k, &mut w, -0.5 * thickness))? { + Ok(moved) => moved, + Err(e) => return Ok(Err(e)), + }; + } + match called(shell_brep_full(k, &w, thickness, &[]))? { + Ok(r) => finish(r, true), + Err(e) => Ok(Err(e)), + } + }) +} + +/// `smlib_offset_sheet`: every face of a sheet moved onto its surface's offset by `distance` +/// along its normal; faces that close into a solid (a sphere's one face, a block's six) give the +/// offset solid (tangency-labs/smlib#17, which dropped the capi's refusal of a closed solid). +pub(crate) fn offset_sheet(body: &Body, distance: f64) -> Result { + if !distance_ok(distance) { + return Err(Error::Argument); + } + on_copy("smlib_offset_sheet", body, |k, mut w| { + // `take`: a result without faces (a sphere moved in to its centre) is SMLIB_ERR_EMPTY. + match called(offset_brep_full(k, &mut w, distance))? { + Ok(r) => finish(r, false), + Err(e) => Ok(Err(e)), + } + }) +} + +/// A unit vector from `v`, as `smlib_draft`'s `unit`; `None` for a vector too short or not +/// finite. +fn unit(v: [f64; 3]) -> Option { + if !v.iter().all(|x| x.is_finite()) { + return None; + } + let u = p3(v); + let len = u.length(); + (len > 1e-12 && len.is_finite()).then(|| u * (1.0 / len)) +} + +/// `outward_normal`: the outward normal of face `f` (its outer faceuse `fu`) at `at`, a point on +/// it: its surface's normal there, turned with the outer faceuse. `None` where SMLib cannot place +/// the point on the surface (the capi's `STEPInversionAnswered` also takes a point outside the +/// domain or off the surface by more than its tolerance; solidcore's inversion answers those with +/// a status, so they are `None` here: the face's own internal point is neither). +fn outward_normal(k: &Kernel, b: &Brep, f: FaceId, fu: FaceuseId, at: Point3) -> solidcore::Result> { + let Some(surf) = b.face(f)?.surface.as_ref() else { return Ok(None) }; + let Some((step, _)) = answer(surf.step_inversion(k, &surf.step_uv_domain(), at, 1e6, None))? else { return Ok(None) }; + let Some(nurb) = answer(surf.convert_uv_from_step_to_nurbs(k, step))? else { return Ok(None) }; + let Some(mut n) = answer(surf.evaluate_normal(k, nurb, Side::Left, Side::Left))? else { return Ok(None) }; + if b.faceuse(fu)?.orientation != OrientType::Same { + n = -n; + } + Ok(Some(n)) +} + +/// `drafted_cone` (tangency-labs/smlib#27, #53): the cone a face on the cone or cylinder `cyl` about +/// the pull (its outward normal `n` at `inside`) becomes drafted by `angle` about its circle on the +/// neutral plane (through `origin`, normal `normal`), so that it leans in going along `pull`: its +/// generators turned by `angle` in their planes through the axis, about that circle. With R0 the +/// radius on the neutral plane and t the slope of the radius going along the pull (0 for a +/// cylinder), the radius h along the pull from that circle is R0 + h tan(atan(t) - s angle), s = 1 +/// where the face looks away from the axis (a pin), -1 where it looks towards it (a hole). It is +/// the surface's own NURB with each control point moved radially by the new radius over the old at +/// its height, so it keeps the surface's parameters and the face's UV trims stay valid: for a +/// cylinder solidcore's `Cone::lean_cylinder` (solidcore#1545), for a cone the same edit on +/// [`Cone::base_mut`]. [`Error::Unsupported`] when the pull does not run along the axis, the axis +/// lies in the neutral plane, or the cone would close within the face's span. +#[allow(clippy::too_many_arguments)] // the capi's drafted_cone +fn drafted_cone( + k: &Kernel, + cyl: &Cone, + n: Vec3, + inside: Point3, + origin: Point3, + normal: Vec3, + pull: Vec3, + angle: f64, +) -> solidcore::Result> { + let frame = cyl.canonical().origin; + let z = frame.x_axis().cross(frame.y_axis()); + let len = z.length(); + if !(len > 0.0 && len.is_finite()) { + return Ok(Err(Error::Unsupported)); + } + let z = z * (1.0 / len); + let sense = z.dot(pull); + if (sense.abs() - 1.0).abs() > 1e-9 { + return Ok(Err(Error::Unsupported)); + } + let axis = frame.origin(); + let toward = z.dot(normal); + if toward.abs() < 1e-12 { + return Ok(Err(Error::Unsupported)); + } + // The hinge circle's centre: the axis on the neutral plane, at the cone's height v0. + let v0 = (origin - axis).dot(normal) / toward; + let centre = axis + z * v0; + let radial = (inside - centre) - pull * (inside - centre).dot(pull); + let s = if radial.dot(n) >= 0.0 { 1.0 } else { -1.0 }; + // The cone's radius is linear in its height along z; along the pull it changes by `slope` per + // unit, and drafted by `turned`. + let r0 = cyl.radius(v0); + let slope = (cyl.radius(1.0) - cyl.radius(0.0)) * sense; + let turned = (slope.atan() - s * angle).tan(); + if !(r0 > 0.0) || !turned.is_finite() { + return Ok(Err(Error::Unsupported)); + } + if cyl.is_cylinder() { + return Ok(answer(cyl.lean_cylinder(k, turned * sense, v0))?.ok_or(Error::Unsupported)); + } + let mut cone = cyl.clone(); + let net = cone.base_mut(); + let (nu, nv) = (net.number_control_points(SurfParamType::U), net.number_control_points(SurfParamType::V)); + for i in 0..nu { + for j in 0..nv { + let Some((p, w)) = answer(net.control_point(ControlPointForm::EuclideanRational, i, j))? else { + return Ok(Err(Error::Unsupported)); + }; + let h = (p - centre).dot(pull); + let (was, now) = (cyl.radius(v0 + h * sense), r0 + h * turned); + if !(was > 0.0 && now > 0.0) { + return Ok(Err(Error::Unsupported)); + } + let foot = centre + pull * h; + if answer(net.set_control_point(ControlPointForm::EuclideanRational, i, j, foot + (p - foot) * (now / was), w))?.is_none() { + return Ok(Err(Error::Unsupported)); + } + } + } + // `CopyAndAddAnalytics`: the cone's analytic data from its edited NURB. + if answer(cone.rebuild_step_from_nurb_parameters(k))?.is_none() { + return Ok(Err(Error::Unsupported)); + } + Ok(Ok(cone)) +} + +/// The capi's `Before` mark on what `SmBrep::LocalOperation` is to move: above the history's tag. +const MOVED_MARK: u64 = ids::USER_1 + 8; + +/// `Before::mark` on each replacement surface. A surface has no identity apart from its owning +/// face here, and `faces[i]`'s offset face takes `surfaces[i]`, so the mark goes on the picked face +/// and travels as the surface's does (Copy behaviour; solidcore#1875). The one difference, recorded +/// in solidcore's `topology.brep_local_operation--1875-face-mark-for-surface-mark` finding: a merge +/// keeping an unpicked face over a picked one hands that survivor the mark, where SMLib's survivor +/// keeps its own unmarked surface. +pub(super) fn mark_moved(w: &mut Brep, picked: &[FaceId]) -> solidcore::Result<()> { + for &f in picked { + w.add_attribute(EntityRef::Face(f), Attribute::long(MOVED_MARK, 0, Behavior::Copy))?; + } + Ok(()) +} + +/// `moved_faces`'s reading (`read_marks`): whether any face of `w` carries the mark, every mark +/// removed. +pub(super) fn moved_faces(w: &mut Brep) -> solidcore::Result { + let mut moved = false; + for f in w.face_list().to_vec() { + let e = EntityRef::Face(f); + let marks: Vec<_> = w.entity_attributes(e).into_iter().filter(|(_, a)| a.attribute_id() == MOVED_MARK).map(|(h, _)| h).collect(); + moved = moved || !marks.is_empty(); + for h in marks { + w.remove_attribute(e, h)?; + } + } + Ok(moved) +} + +/// `smlib_draft`: its checks, the solid check, the pick, then `draft_faces`: each picked face (a +/// plane parallel to the pull) gets a copy of its plane turned by `angle` about its line on the +/// neutral plane, and a cylinder about the pull the cone `drafted_cone` gives +/// (tangency-labs/smlib#27); `SmBrep::LocalOperation` extends or trims the faces around them to +/// meet the tilted surfaces. +pub(crate) fn draft( + body: &Body, + points: &[[f64; 3]], + tolerance: f64, + neutral_origin: [f64; 3], + neutral_normal: [f64; 3], + pull: [f64; 3], + angle: f64, +) -> Result { + let (Some(normal), Some(along)) = (unit(neutral_normal), unit(pull)) else { return Err(Error::Argument) }; + if !points_ok(points, false) + || !tolerance_ok(tolerance) + || !neutral_origin.iter().all(|x| x.is_finite() && x.abs() <= 1e9) + || !angle.is_finite() + || angle == 0.0 + || angle.abs() >= 1.5697963267948966 + { + return Err(Error::Argument); + } + on_copy("smlib_draft", body, |k, mut w| { + if !brep_p2::is_manifold_solid(&w)? { + return Ok(Err(Error::Argument)); + } + let picked = match pick_faces(k, &mut w, points, tolerance)? { + Ok(p) => p, + Err(m) => return Ok(Err(face_miss(m))), + }; + // `draft_faces`. + let mut surfaces = Vec::with_capacity(picked.len()); + for &f in &picked { + let fu = outer_faceuse(&w, f)?; + let face = w.face(f)?; + let (Some(surf), Some(fu)) = (face.surface.as_ref(), fu) else { + return Ok(Err(Error::Status(INVALID_INPUT))); + }; + // A cylinder about the pull drafted becomes a cone (`drafted_cone`). + if let SurfaceKind::Cone(c) = surf.kind_with_nurb(k)? { + let cyl = (**c).clone(); + let Some(inside) = answer(face_internal_point(k, &mut w, f))? else { + return Ok(Err(Error::Status(INVALID_INPUT))); + }; + let Some(n) = outward_normal(k, &w, f, fu, inside)? else { + return Ok(Err(Error::Status(INVALID_INPUT))); + }; + match drafted_cone(k, &cyl, n, inside, p3(neutral_origin), normal, along, angle)? { + Ok(cone) => surfaces.push(Surface::from(cone)), + Err(e) => return Ok(Err(e)), + } + continue; + } + let SurfaceKind::Plane(plane) = surf.kind_with_nurb(k)? else { + return Ok(Err(Error::Unsupported)); + }; + // The face's outward normal: the plane's, turned with the outer faceuse. + let mut n = plane.position().z_axis(); + if w.faceuse(fu)?.orientation != OrientType::Same { + n = -n; + } + if n.dot(along).abs() > 1e-6 { + return Ok(Err(Error::Unsupported)); + } + let Some(inside) = answer(face_internal_point(k, &mut w, f))? else { + return Ok(Err(Error::Status(INVALID_INPUT))); + }; + let toward = along.dot(normal); + if toward.abs() < 1e-12 { + return Ok(Err(Error::Argument)); + } + let hinge = inside + along * ((p3(neutral_origin) - inside).dot(normal) / toward); + // Turning n about n x pull by `angle` gives n cos(angle) + pull sin(angle). + let axis = n.cross(along); + let len = axis.length(); + if !(len > 0.5) { + return Ok(Err(Error::Unsupported)); + } + let axis = axis * (1.0 / len); + let Some(surf) = w.face(f)?.surface.as_ref() else { + return Ok(Err(Error::Status(INVALID_INPUT))); + }; + let Some(mut tilted) = answer(surf.copy(k))? else { + return Ok(Err(Error::Status(INVALID_INPUT))); + }; + let mut turn = Axis2Placement::IDENTITY; + turn.rotate_about_axis_at_point(angle, hinge, axis); + if answer(tilted.transform(k, &turn, None))?.is_none() { + return Ok(Err(Error::Status(INVALID_INPUT))); + } + surfaces.push(tilted); + } + // `moved_faces(b, status(b->LocalOperation(faces, surfaces)))`, its marks on the picked + // faces (`mark_moved`). + mark_moved(&mut w, &picked)?; + if let Err(e) = called(local_operation_simple(k, &mut w, &picked, surfaces))? { + return Ok(Err(e)); + } + if !moved_faces(&mut w)? { + return Ok(Err(Error::NoEffect)); + } + finish(w, true) + }) +} diff --git a/crates/smlib/src/core/offset_tests.rs b/crates/smlib/src/core/offset_tests.rs new file mode 100644 index 000000000..acfe8d055 --- /dev/null +++ b/crates/smlib/src/core/offset_tests.rs @@ -0,0 +1,665 @@ +//! Shells, face offsets, thickening, sheet offsets and drafts on solidcore, against closed forms: +//! every result exports to a record that validates. +//! +//! The bodies are solidcore's own boxes, cylinders and linear sweeps (and booleans of them). + +use std::collections::BTreeMap; +use std::f64::consts::PI; +use std::sync::mpsc; +use std::time::Duration; + +use solidcore::curve::curve::Curve; +use solidcore::curve::ellipse::Ellipse; +use solidcore::geom::axis2_placement::Axis2Placement; +use solidcore::geom::extent1d::Extent1d; +use solidcore::geom::vector3d::Vec3; +use solidcore::primitive::api_curves::create_line_segment; +use solidcore::sweep::api_brep::create_linear_sweep; + +use super::offset::{draft, mark_moved, moved_faces, offset_faces, offset_sheet, shell, thicken}; +use super::{Body, area, bounds, counts, make_box, make_cylinder, make_sphere, run, to_arrays, volume}; +use crate::export::native; +use crate::{BooleanOp, Error}; + +/// A case longer than this is a hang. +const TIMEOUT: Duration = Duration::from_secs(300); + +/// How near a pick point must be. +const TOL: f64 = 0.01; + +#[derive(Clone, Copy, Debug)] +enum Shape { + Box([f64; 3], [f64; 3]), + Cylinder([f64; 3], f64, f64), + Sphere([f64; 3], f64), + /// A frustum about +Z: base centre, base radius, top radius, height. + Frustum([f64; 3], f64, f64, f64), + /// A sheet: the line from the first point to the second swept along `dir` by `dist`. + LineSheet([f64; 3], [f64; 3], [f64; 3], f64), + /// A sheet: the arc about +Z through `center` of `radius` from 0 to `degrees`, swept along + /// +Z by `height`. + ArcSheet([f64; 3], f64, f64, f64), + /// Rig case shell/4711: a 60 x 40 x 10 block less an r3 through hole at (22.5, 7) and a + /// 10 x 10 notch on the front edge from x = 25 to 35. + Notched, +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +impl Shape { + fn core(self) -> Body { + match self { + Shape::Box(o, s) => make_box(o, s).unwrap(), + Shape::Cylinder(o, r, h) => make_cylinder(o, r, h).unwrap(), + Shape::Sphere(o, r) => make_sphere(o, r).unwrap(), + Shape::Frustum(o, a, b, h) => super::make_cone(o, a, b, h).unwrap(), + Shape::LineSheet(a, b, dir, dist) => run("sheet", |k| { + let c = Curve::from(create_line_segment(v3(a), v3(b))?); + create_linear_sweep(k, &[Some(&c)], v3(dir), dist, false) + }) + .map(Body::new) + .unwrap(), + Shape::ArcSheet(o, r, degrees, h) => run("sheet", |k| { + let frame = Axis2Placement::new(v3(o), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)); + let c = Curve::from(Ellipse::create_canonical_circle(k, &frame, r, Some(&Extent1d::from_min_max(0.0, degrees)), None)?); + create_linear_sweep(k, &[Some(&c)], Vec3::new(0.0, 0.0, 1.0), h, false) + }) + .map(Body::new) + .unwrap(), + Shape::Notched => { + let block = make_box([0.0; 3], [60.0, 40.0, 10.0]).unwrap(); + let pin = make_cylinder([22.5, 7.0, -5.0], 3.0, 20.0).unwrap(); + let notch = make_box([25.0, -5.0, -5.0], [10.0, 10.0, 20.0]).unwrap(); + let a = super::boolean::boolean(&block, &pin, BooleanOp::Subtract).unwrap().unwrap(); + super::boolean::boolean(&a, ¬ch, BooleanOp::Subtract).unwrap().unwrap() + } + } + } +} + +#[derive(Clone, Debug)] +enum Op { + /// `Brep::shell`: open faces, thickness. + Shell(Shape, Vec<[f64; 3]>, f64), + /// `Brep::offset_faces`: faces, distance. + OffsetFaces(Shape, Vec<[f64; 3]>, f64), + /// `Brep::thicken`: thickness, symmetric. + Thicken(Shape, f64, bool), + /// `Brep::offset_sheet`: distance. + OffsetSheet(Shape, f64), + /// `Brep::draft`: faces, neutral origin, neutral normal, pull, angle. + Draft(Shape, Vec<[f64; 3]>, [f64; 3], [f64; 3], [f64; 3], f64), +} + +/// What a case must give. +#[derive(Clone, Debug)] +enum Expect { + /// A solid of this volume (relative 1e-9). + Volume(f64), + /// A solid of this volume whose bounds along z are these. + Slab(f64, f64, f64), + /// A solid of this volume (relative 1e-9) whose bounds are these. + Solid(f64, [f64; 3], [f64; 3]), + /// A sheet of this area (relative 1e-9) whose bounds are these. + Sheet(f64, [f64; 3], [f64; 3]), + /// This error. + Fails(Error), +} + +struct Case { + op: Op, + expect: Expect, +} + +/// A 30 x 20 x 10 block from the origin. +const BLOCK: Shape = Shape::Box([0.0; 3], [30.0, 20.0, 10.0]); +const ABC: f64 = 6000.0; +/// A point on its top face. +const TOP: [f64; 3] = [15.0, 10.0, 10.0]; +/// A point on its front face (y = 0). +const FRONT: [f64; 3] = [15.0, 0.0, 5.0]; +/// The z axis: a neutral plane's normal and a pull. +const Z: [f64; 3] = [0.0, 0.0, 1.0]; +/// A 30 x 20 sheet in z = 0: the x axis from 0 to 30 swept 20 along y. +const PLATE: Shape = Shape::LineSheet([0.0; 3], [30.0, 0.0, 0.0], [0.0, 1.0, 0.0], 20.0); +/// A sphere of radius 10 about the origin. +const BALL: Shape = Shape::Sphere([0.0; 3], 10.0); +/// A quarter of a cylinder of radius 5 about the z axis, 10 high. +const QUARTER: Shape = Shape::ArcSheet([0.0; 3], 5.0, 90.0, 10.0); + +fn case(name: &str) -> Case { + let c = |op, expect| Case { op, expect }; + match name { + // abc - (a - 2t)(b - 2t)(c - t), t = 2. + "shell_box_open_top" => c(Op::Shell(BLOCK, vec![TOP], -2.0), Expect::Volume(ABC - 26.0 * 16.0 * 8.0)), + // A void: abc - (a - 2t)(b - 2t)(c - 2t). + "shell_box_closed" => c(Op::Shell(BLOCK, vec![], -2.0), Expect::Volume(ABC - 26.0 * 16.0 * 6.0)), + // Closed and outward, the convex edges extended: (a + 2t)(b + 2t)(c + 2t) - abc, t = 1. + "shell_box_closed_outward" => c(Op::Shell(BLOCK, vec![], 1.0), Expect::Volume(32.0 * 22.0 * 12.0 - ABC)), + // Outward, the convex edges extended: (a + 2t)(b + 2t)(c + t) - abc, t = 1. + "shell_box_outward" => c(Op::Shell(BLOCK, vec![TOP], 1.0), Expect::Volume(32.0 * 22.0 * 11.0 - ABC)), + // r = 5, h = 10, open at the top, t = 1: π r² h - π (r - t)² (h - t). + "shell_cylinder_open_top" => { + c(Op::Shell(Shape::Cylinder([0.0; 3], 5.0, 10.0), vec![[0.0, 2.0, 10.0]], -1.0), Expect::Volume(PI * 25.0 * 10.0 - PI * 16.0 * 9.0)) + } + // A wall of 15 inside a block 20 wide leaves no cavity. + "shell_too_thick" => c(Op::Shell(BLOCK, vec![TOP], -15.0), Expect::Fails(Error::NoRoom)), + // The hole's offset (r 3 + 2) is tangent to the front's (y = 2): the walls meet along a + // line, which bounds no solid. + "shell_walls_touch" => c(Op::Shell(Shape::Notched, vec![[50.0, 30.0, 0.0]], -2.0), Expect::Fails(Error::WallsTouch)), + "shell_pick_near_nothing" => c(Op::Shell(BLOCK, vec![TOP, [100.0; 3]], -2.0), Expect::Fails(Error::NoMatch { point: 1 })), + // The top front edge's midpoint is as near the top as the front. + "shell_pick_ambiguous" => c(Op::Shell(BLOCK, vec![[15.0, 0.0, 10.0]], -2.0), Expect::Fails(Error::Ambiguous { point: 0 })), + // A plate of 30 x 20 thickened 2: 1200, 2 thick along z; symmetric, from -1 to 1. + "thicken_plate" => c(Op::Thicken(PLATE, 2.0, false), Expect::Slab(1200.0, 0.0, 2.0)), + "thicken_plate_symmetric" => c(Op::Thicken(PLATE, 2.0, true), Expect::Slab(1200.0, -1.0, 1.0)), + "thicken_a_solid" => c(Op::Thicken(BLOCK, 2.0, false), Expect::Fails(Error::Argument)), + // The plate moved 3 along its normal (+z: the x axis swept along y): still 600, at z = 3. + "offset_sheet_plate" => c(Op::OffsetSheet(PLATE, 3.0), Expect::Sheet(600.0, [0.0, 0.0, 3.0], [30.0, 20.0, 3.0])), + // A sphere's one face closes on itself (tangency-labs/smlib fix #17): r = 10 moved out 2 is + // the ball of radius 12, (4/3) π 12³; moved in 10, to its centre, nothing is left. + "offset_sheet_a_sphere" => c(Op::OffsetSheet(BALL, 2.0), Expect::Volume(4.0 / 3.0 * PI * 12.0f64.powi(3))), + "offset_sheet_a_sphere_to_its_centre" => c(Op::OffsetSheet(BALL, -10.0), Expect::Fails(Error::Empty)), + // The quarter cylinder moved 2 along its normal (outward: the arc's tangent swept along + // z): radius 7, area (π/2) 7 · 10. + "offset_sheet_quarter_cylinder" => c(Op::OffsetSheet(QUARTER, 2.0), Expect::Sheet(PI / 2.0 * 7.0 * 10.0, [0.0, 0.0, 0.0], [7.0, 7.0, 10.0])), + // A closed sheet offsets as an open one (tangency-labs/smlib fix #17, develop 9d0fb564): + // each face moved out 1 along its normal, the convex edges extended, gives the block + // (a + 2d)(b + 2d)(c + 2d) of six planes, from -d to (a, b, c) + d. + "offset_sheet_a_solid" => c(Op::OffsetSheet(BLOCK, 1.0), Expect::Solid(32.0 * 22.0 * 12.0, [-1.0, -1.0, -1.0], [31.0, 21.0, 11.0])), + // The top moved out 2: abc + d·ab. + "offset_faces_top_out" => c(Op::OffsetFaces(BLOCK, vec![TOP], 2.0), Expect::Volume(ABC + 2.0 * 600.0)), + // The top moved in 10, as deep as the block: nothing left behind it. + "offset_faces_through" => c(Op::OffsetFaces(BLOCK, vec![TOP], -10.0), Expect::Fails(Error::NoRoom)), + // The four sides drafted θ = 5° about the bottom (z = 0), pulled along +z, leaning in: + // the section at height z is (a - 2 z tanθ)(b - 2 z tanθ), so + // V = abh - (a + b) h² tanθ + (4/3) h³ tan²θ. + "draft_box_sides" => { + let s = (5.0f64).to_radians().tan(); + let (a, b, h) = (30.0, 20.0, 10.0); + let sides = vec![[15.0, 0.0, 5.0], [30.0, 10.0, 5.0], [15.0, 20.0, 5.0], [0.0, 10.0, 5.0]]; + c( + Op::Draft(BLOCK, sides, [0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], 5f64.to_radians()), + Expect::Volume(a * b * h - (a + b) * h * h * s + 4.0 / 3.0 * h * h * h * s * s), + ) + } + // The front (y = 0) alone drafted θ = 5° about the bottom: a wedge of a h² tanθ / 2 + // comes off along its length. + "draft_one_side" => { + let s = (5.0f64).to_radians().tan(); + c(Op::Draft(BLOCK, vec![FRONT], [0.0; 3], Z, Z, 5f64.to_radians()), Expect::Volume(ABC - 30.0 * 100.0 * s / 2.0)) + } + // A negative angle leans it out: the same wedge goes on. + "draft_one_side_out" => { + let s = (5.0f64).to_radians().tan(); + c(Op::Draft(BLOCK, vec![FRONT], [0.0; 3], Z, Z, -5f64.to_radians()), Expect::Volume(ABC + 30.0 * 100.0 * s / 2.0)) + } + // Hinged at the top (z = 10) and leaning in going up, the face leans out below the + // hinge: the wedge goes on. + "draft_one_side_hinged_at_the_top" => { + let s = (5.0f64).to_radians().tan(); + c(Op::Draft(BLOCK, vec![FRONT], [0.0, 0.0, 10.0], Z, Z, 5f64.to_radians()), Expect::Volume(ABC + 30.0 * 100.0 * s / 2.0)) + } + // A cylinder along the pull drafts to a cone (tangency-labs/smlib fix #27, develop + // 9d0fb564): R = 5, h = 10, θ = 0.1 about the bottom, leaning in: a frustum of radii R + // and r = R - h tanθ (a cone and its two caps): V = π h (R² + R r + r²) / 3. + "draft_a_curved_face" => { + let (big, h) = (5.0, 10.0); + let small = big - h * 0.1f64.tan(); + c( + Op::Draft(Shape::Cylinder([0.0; 3], big, h), vec![[5.0, 0.0, 5.0]], [0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], 0.1), + Expect::Volume(PI * h * (big * big + big * small + small * small) / 3.0), + ) + } + // A cone r 10 at its base to 8 at its top, 20 tall, drafted 5° about its base turns its + // generators 5° more (fork d51a723): r 10 + 20 tan(atan(-0.1) - 5°) at the top. + "draft_a_cone_about_the_pull" => { + let (big, h, a) = (10.0, 20.0, 5f64.to_radians()); + let small = big + h * ((-0.1f64).atan() - a).tan(); + c( + Op::Draft(Shape::Frustum([0.0; 3], big, 8.0, h), vec![[0.0, 9.0, 10.0]], [0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], a), + Expect::Volume(PI * h * (big * big + big * small + small * small) / 3.0), + ) + } + // The top is square to the pull, not along it. + "draft_a_face_across_the_pull" => { + c(Op::Draft(BLOCK, vec![TOP], [0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], 0.1), Expect::Fails(Error::Unsupported)) + } + _ => panic!("{name}"), + } +} + +/// The tolerance a case picks with: the ambiguous point lies on its two faces. +fn tolerance(name: &str) -> f64 { + if name == "shell_pick_ambiguous" { 1.0 } else { TOL } +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +#[derive(Debug, PartialEq)] +struct Measured { + /// The volume of a solid, the area of a sheet. + size: f64, + bounds: ([f64; 3], [f64; 3]), + counts: [usize; 3], + kinds: BTreeMap, +} + +fn kinds(rec: &solidcore_record::brep::Brep) -> BTreeMap { + let mut out = BTreeMap::new(); + for f in &rec.faces { + let v = serde_json::to_value(&f.surface).unwrap(); + *out.entry(v["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1; + } + out +} + +fn is_sheet(e: &Expect) -> bool { + matches!(e, Expect::Sheet(..)) +} + +fn on_core(name: &str, c: &Case) -> crate::Result { + let tol = tolerance(name); + match &c.op { + Op::Shell(s, points, t) => shell(&s.core(), points, tol, *t), + Op::OffsetFaces(s, points, d) => offset_faces(&s.core(), points, tol, *d), + Op::Thicken(s, t, sym) => thicken(&s.core(), *t, *sym), + Op::OffsetSheet(s, d) => offset_sheet(&s.core(), *d), + Op::Draft(s, points, o, n, pull, angle) => draft(&s.core(), points, tol, *o, *n, *pull, *angle), + } +} + +/// Runs `f` on its own thread: a hang fails the test instead of stopping the run. +fn timed(name: &str, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let _ = tx.send(f()); + }); + match rx.recv_timeout(TIMEOUT) { + Ok(v) => v, + Err(mpsc::RecvTimeoutError::Disconnected) => match worker.join() { + Err(p) => std::panic::resume_unwind(p), + Ok(()) => panic!("{name}: no result"), + }, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("{name}: solidcore hung (no result after {TIMEOUT:?})"), + } +} + +type Got = std::result::Result; + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6) +} + +/// Checks a kernel's result against the case's closed form; what it measured, or its error. +fn judge(name: &str, who: &str, expect: &Expect, got: Got) -> Got { + match (expect, &got) { + (Expect::Fails(e), Err(g)) => assert_eq!(g, e, "{name}: {who} failed otherwise"), + (Expect::Fails(e), Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"), + (_, Err(g)) => panic!("{name}: {who} failed: {g}"), + (Expect::Volume(v), Ok(m)) => assert!(rel(m.size, *v) < 1e-9, "{name}: {who} volume {} vs analytic {v}", m.size), + (Expect::Slab(v, lo, hi), Ok(m)) => { + assert!(rel(m.size, *v) < 1e-9, "{name}: {who} volume {} vs analytic {v}", m.size); + let (a, b) = (m.bounds.0[2], m.bounds.1[2]); + assert!((a - lo).abs() < 1e-6 && (b - hi).abs() < 1e-6, "{name}: {who} z from {a} to {b}, expected {lo} to {hi}"); + } + (Expect::Solid(v, lo, hi), Ok(m)) => { + assert!(rel(m.size, *v) < 1e-9, "{name}: {who} volume {} vs analytic {v}", m.size); + assert!(near(m.bounds.0, *lo) && near(m.bounds.1, *hi), "{name}: {who} bounds {:?}, expected {lo:?} {hi:?}", m.bounds); + } + (Expect::Sheet(s, lo, hi), Ok(m)) => { + assert!(rel(m.size, *s) < 1e-9, "{name}: {who} area {} vs analytic {s}", m.size); + assert!(near(m.bounds.0, *lo) && near(m.bounds.1, *hi), "{name}: {who} bounds {:?}, expected {lo:?} {hi:?}", m.bounds); + } + } + got +} + +fn solidcore_case(name: &'static str) -> Got { + timed(name, move || { + let c = case(name); + let sheet = is_sheet(&c.expect); + let got = on_core(name, &c).map(|body| { + let size = if sheet { area(&body, 1e-8) } else { volume(&body, 1e-8) }.unwrap_or_else(|e| panic!("{name}: size: {e}")); + let n = counts(&body).unwrap(); + let (rec, _) = native(&to_arrays(&body).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + let bx = bounds(&body).unwrap(); + Measured { size, bounds: bx, counts: n, kinds: kinds(&rec) } + }); + judge(name, "solidcore", &c.expect, got) + }) +} + +macro_rules! cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +cases!( + shell_box_open_top, + shell_box_closed, + shell_box_closed_outward, + shell_box_outward, + shell_cylinder_open_top, + shell_too_thick, + shell_walls_touch, + shell_pick_near_nothing, + shell_pick_ambiguous, + thicken_plate, + thicken_plate_symmetric, + thicken_a_solid, + offset_sheet_plate, + offset_sheet_quarter_cylinder, + offset_sheet_a_solid, + offset_sheet_a_sphere, + offset_sheet_a_sphere_to_its_centre, + offset_faces_top_out, + offset_faces_through, + draft_box_sides, + draft_one_side, + draft_one_side_out, + draft_one_side_hinged_at_the_top, + draft_a_curved_face, + draft_a_cone_about_the_pull, + draft_a_face_across_the_pull, +); + +/// The capi's argument checks, before any kernel call. +#[test] +fn hostile_arguments_are_refused() { + let b = BLOCK.core(); + for t in [0.0, f64::NAN, -1e7, f64::INFINITY] { + assert_eq!(shell(&b, &[TOP], TOL, t).err(), Some(Error::Argument), "thickness {t}"); + assert_eq!(thicken(&b, t, false).err(), Some(Error::Argument), "thickness {t}"); + assert_eq!(offset_sheet(&b, t).err(), Some(Error::Argument), "distance {t}"); + assert_eq!(offset_faces(&b, &[TOP], TOL, t).err(), Some(Error::Argument), "distance {t}"); + } + assert_eq!(shell(&b, &[[f64::NAN; 3]], TOL, -1.0).err(), Some(Error::Argument)); + assert_eq!(shell(&b, &[TOP], 0.0, -1.0).err(), Some(Error::Argument)); + assert_eq!(offset_faces(&b, &[], TOL, 1.0).err(), Some(Error::Argument)); + let z = [0.0, 0.0, 1.0]; + assert_eq!(draft(&b, &[TOP], TOL, [0.0; 3], [0.0; 3], z, 0.1).err(), Some(Error::Argument), "no neutral normal"); + assert_eq!(draft(&b, &[TOP], TOL, [0.0; 3], z, z, 0.0).err(), Some(Error::Argument), "no angle"); + assert_eq!(draft(&b, &[TOP], TOL, [0.0; 3], z, z, PI / 2.0).err(), Some(Error::Argument), "a right angle"); + assert_eq!(draft(&b, &[TOP], TOL, [f64::NAN; 3], z, z, 0.1).err(), Some(Error::Argument)); +} + +/// The body offset is never changed. +#[test] +fn the_body_stays_as_it_was() { + let r = timed("operand", || { + let b = BLOCK.core(); + let _ = shell(&b, &[TOP], TOL, -2.0); + (counts(&b).unwrap(), volume(&b, 1e-8).unwrap()) + }); + assert_eq!(r.0, [6, 12, 8]); + assert!(rel(r.1, ABC) < 1e-12, "{}", r.1); +} + +/// The distance from `p` to each face of `b` (`SmApiFaceClosestPoint`), under `identity`. +fn face_distances( + k: &mut solidcore::kernel::Kernel, + b: &mut solidcore::topology::Brep, + identity: &solidcore::query::brep::BrepIdentity<'_>, + p: Vec3, +) -> solidcore::Result> { + use solidcore::geom::object::Shape as Sh; + use solidcore::query::api_queries::face_closest_point_in_shape; + use solidcore::query::brep::LiveBrepObjects; + use solidcore::topology::BrepId; + let one = BrepId::from_index(0); + let mut out = Vec::new(); + for f in solidcore::topology::brep::p1::faces(b, None)? { + let shape = Sh::new(k, &(one, &*b), &[], &[(one, f)], &[], &[])?; + let objects = LiveBrepObjects::new(b, identity, None)?; + let c = face_closest_point_in_shape(k, &shape, &objects, (one, f), p)?; + out.push((c.distance, c.point)); + } + Ok(out) +} + +/// The closed form for (15, 10, 20) above the 30 x 20 x 10 box at the origin, face by face of +/// `create_box`: bottom 20, top 10, the x sides sqrt(15^2 + 10^2), the y sides sqrt(10^2 + 10^2). +fn box_face_distances_are_exact(what: &str, d: &[(f64, Vec3)]) { + let want = [20.0, 10.0, 325f64.sqrt(), 325f64.sqrt(), 200f64.sqrt(), 200f64.sqrt()]; + assert_eq!(d.len(), want.len(), "{what}: faces"); + for (i, (&(got, _), want)) in d.iter().zip(want).enumerate() { + assert!((got - want).abs() < 1e-9, "{what}: face {i} at {got}, want {want}"); + } + let top = d[1].1; + assert!((top.x - 15.0).abs() < 1e-9 && (top.y - 10.0).abs() < 1e-9 && (top.z - 10.0).abs() < 1e-9, "{what}: top {top:?}"); +} + +/// Picking faces on a solidcore box: on the body itself, on the working copy every operation +/// makes (`brep_copy`), and by solidcore's recommended usage, each face's distance is the closed +/// form and the top face is picked. +#[test] +fn faces_are_picked_on_the_box_and_on_its_working_copy() { + use solidcore::query::brep::{BrepIdentity, BrepQuery}; + let p = Vec3::new(15.0, 10.0, 20.0); + let on_top = [[15.0, 10.0, 10.0]]; + run("pick", |k| { + let mut b = solidcore::primitive::api_primitives::create_box(k, Vec3::new(0.0, 0.0, 0.0), 30.0, 20.0, 10.0)?; + let mut w = solidcore::topology::brep::p3::brep_copy(k, &b)?; + let mut faces = Vec::new(); + for (what, x) in [("the body", &mut b), ("its copy", &mut w)] { + let query = BrepQuery::of_brep(x); + let identity = query.effective_identity(); + box_face_distances_are_exact(what, &face_distances(k, x, &identity, p)?); + let picked = super::offset::pick_faces(k, x, &on_top, TOL)?; + faces.push(picked.ok()); + } + assert!(faces[0].as_ref().is_some_and(|f| f.len() == 1), "the body: {faces:?}"); + assert_eq!(faces[0], faces[1], "the body and its copy pick the same face"); + // `BrepIdentity::of_brep` honours a copy's owner keys since solidcore#1445: the body + // and its copy both resolve. + for (what, x) in [("of_brep on the body", &mut b), ("of_brep on its copy", &mut w)] { + let proven = BrepIdentity::of_brep(x); + box_face_distances_are_exact(what, &face_distances(k, x, &proven.identity(), p)?); + } + Ok(()) + }) + .unwrap(); +} + +/// A pick skips an entity whose query returns an SMLib status, as the capi skips any status +/// other than `SM_SUCCESS`; any other solidcore error fails the pick. +#[test] +fn a_solidcore_error_in_a_pick_is_an_error() { + use super::answer; + use super::blend::pick; + use solidcore::SolidError; + let all = [0usize, 1]; + let points = [[0.0; 3]]; + let status = pick(&all, &points, 1.0, 1e-6, |i, _| answer(if i == 0 { Err(SolidError::sm_err("q")) } else { Ok(0.5) })); + assert_eq!(status.unwrap().unwrap().0, vec![1], "a status skips the entity"); + let other = pick(&all, &points, 1.0, 1e-6, |i, _| answer(if i == 0 { Err(SolidError::invalid_input("q", "owner")) } else { Ok(0.5) })); + assert!(matches!(other, Err(SolidError::InvalidInput { .. })), "{other:?}"); + let unported = pick(&all, &points, 1.0, 1e-6, |i, _| answer(if i == 0 { Err(SolidError::unported("Sm::X", "u")) } else { Ok(0.5) })); + assert!(matches!(unported, Err(SolidError::Unported { .. })), "{unported:?}"); +} + +/// The capi's `moved_faces` reading: no mark, no move (SMLIB_ERR_NO_EFFECT); a mark is read once, +/// and gone. +#[test] +fn a_draft_with_no_marked_face_left_has_no_effect() { + let body = make_box([0.0; 3], [10.0; 3]).unwrap(); + super::with_body("marks", &body, |_, w| { + assert!(!moved_faces(w)?, "no face marked"); + let f = w.face_list()[0]; + mark_moved(w, &[f])?; + assert!(moved_faces(w)?, "a face marked"); + assert!(!moved_faces(w)?, "the mark removed"); + Ok(()) + }) + .unwrap(); +} + +/// A draft leaves no mark of its own on what it returns, on a plane or on a cylinder turned cone. +#[test] +fn a_draft_leaves_no_mark() { + let z = [0.0, 0.0, 1.0]; + let bx = make_box([0.0; 3], [20.0, 30.0, 10.0]).unwrap(); + let plane = draft(&bx, &[[10.0, 0.0, 5.0]], TOL, [0.0; 3], z, z, 0.1).unwrap(); + let cyl = make_cylinder([0.0; 3], 5.0, 10.0).unwrap(); + let cone = draft(&cyl, &[[5.0, 0.0, 5.0]], TOL, [0.0; 3], z, z, 0.1).unwrap(); + for b in [plane, cone] { + super::with_body("marks", &b, |_, w| { + assert!(!moved_faces(w)?); + Ok(()) + }) + .unwrap(); + } +} + +/// A stepped block, 40 x 30 x 10 with its half x < 20 raised to 20 (rig case +/// shell/cov-replace-face-step-onto-the-higher-face, the fork's `offset_faces_close_a_step_wall`): +/// a top moved onto the other's plane closes the step wall between them to nothing, and the tops +/// are one face of a 6-faced box. +#[test] +fn offset_faces_close_a_step_wall() { + use super::boolean::boolean; + let stepped = boolean(&make_box([0.0; 3], [40.0, 30.0, 10.0]).unwrap(), &make_box([0.0; 3], [20.0, 30.0, 20.0]).unwrap(), BooleanOp::Union) + .unwrap() + .unwrap(); + assert_eq!(counts(&stepped).unwrap()[0], 8); + for (at, d, v, a) in [([30.0, 15.0, 10.0], 10.0, 24000.0, 5200.0), ([10.0, 15.0, 20.0], -10.0, 12000.0, 3800.0)] { + let r = offset_faces(&stepped, &[at], 0.1, d).unwrap(); + let (got, n, area) = (volume(&r, 1e-8).unwrap(), counts(&r).unwrap(), super::area(&r, 1e-8).unwrap()); + assert_eq!(n[0], 6, "d {d}"); + assert!(rel(got, v) < 1e-9 && rel(area, a) < 1e-9, "d {d}: V {got} A {area}"); + } +} + +/// Rig case shell/4492's rounded box: four mitred rounds, r 3, come off a 40 x 30 x 10 box's top +/// together and follow it. From height 0 the outline is the 34 x 24 top moved out by the round's +/// w(z) = sqrt(9 - (z - axis)^2), or 3 below the axis. With the fork's values at +19, and bodies +/// whose rounds go all the way down from -7 and are cut short from -7.5 (solidcore#2027). At -9 +/// solidcore refuses to put the rounds back (solidcore#2020, open): SolidCraft says it does not +/// make that move. +#[test] +fn mitred_rounds_follow_a_moved_top() { + use super::blend::{Corners, blend}; + use crate::Blend; + let edges = [[20.0, 0.0, 10.0], [20.0, 30.0, 10.0], [0.0, 15.0, 10.0], [40.0, 15.0, 10.0]]; + let top = [20.0, 15.0, 10.0]; + let rounded = blend(&make_box([0.0; 3], [40.0, 30.0, 10.0]).unwrap(), Blend::Round, &edges, &[3.0; 4], TOL, &[], &[], Corners::Filled).unwrap(); + let analytic = |d: f64| { + let (height, axis, n) = (10.0 + d, 7.0 + d, 20000); + (0..n) + .map(|i| { + let z = height * (f64::from(i) + 0.5) / f64::from(n); + let w = if z < axis { 3.0 } else { (9.0 - (z - axis) * (z - axis)).max(0.0).sqrt() }; + (34.0 + 2.0 * w) * (24.0 + 2.0 * w) * height / f64::from(n) + }) + .sum::() + }; + let moves = [ + (19.0, [10, 20, 12]), + (1.0, [10, 20, 12]), + (-1.0, [10, 20, 12]), + (-6.9, [10, 20, 12]), + (-7.0, [6, 12, 8]), + (-7.5, [6, 12, 8]), + (-8.0, [6, 12, 8]), + (-9.5, [6, 12, 8]), + ]; + for (d, n) in moves { + let moved = offset_faces(&rounded, &[top], 0.1, d).unwrap(); + let v = volume(&moved, 1e-8).unwrap(); + assert_eq!(counts(&moved).unwrap(), n, "d {d}"); + assert!(rel(v, analytic(d)) < 1e-6, "d {d}: {v} vs {}", analytic(d)); + } + assert!(matches!(offset_faces(&rounded, &[top], 0.1, -9.0), Err(Error::Unsupported))); +} + +/// `moved_faces`: drafts so small they leave a plane or cylinder where it was still moved a face +/// (solidcore's mark stays on it), and an angle that brings a wall onto the plane of the wall above +/// it leaves the two faces apart: every draft here builds, none is "no effect". +#[test] +fn a_draft_moves_a_face() { + use crate::sweeps::{Curve, DraftCorner}; + let z = [0.0, 0.0, 1.0]; + let plate = make_box([0.0; 3], [40.0, 40.0, 10.0]).unwrap(); + let rod = make_cylinder([20.0, 20.0, -5.0], 5.0, 30.0).unwrap(); + let holed = super::boolean::boolean(&plate, &rod, BooleanOp::Subtract).unwrap().unwrap(); + let pinned = super::boolean::boolean(&plate, &rod, BooleanOp::Union).unwrap().unwrap(); + let t = 5f64.to_radians().tan(); + // A wall x = 20 up to z = 10, then a wall leaning in 5 degrees: the lower wall turned 5 + // degrees about z = 10 lies on the upper one's plane. + let p = [[0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [20.0, 0.0, 10.0], [20.0 - 10.0 * t, 0.0, 20.0], [0.0, 0.0, 20.0]]; + let profile: Vec = (0..5).map(|i| Curve::Line { start: p[i], end: p[(i + 1) % 5] }).collect(); + let leaning = super::sweep::extrude(&profile, [0.0, 1.0, 0.0], 10.0, 0.0, DraftCorner::default(), true).unwrap(); + let five = 5f64.to_radians(); + let cases: [(&str, &Body, [f64; 3], [f64; 3], f64); 7] = [ + ("tiny on a plane", &plate, [20.0, 0.0, 5.0], [0.0; 3], 1e-14), + ("tiny on a hole", &holed, [25.0, 20.0, 5.0], [0.0, 0.0, 5.0], 1e-14), + ("tiny on a pin", &pinned, [25.0, 20.0, 20.0], [0.0, 0.0, 5.0], -1e-14), + ("small on a hole", &holed, [25.0, 20.0, 5.0], [0.0, 0.0, 5.0], 1e-6), + ("onto the wall above", &leaning, [20.0, 5.0, 5.0], [0.0, 0.0, 10.0], five), + ("away from the wall above", &leaning, [20.0, 5.0, 5.0], [0.0, 0.0, 10.0], -five), + ("hinged far off", &plate, [20.0, 0.0, 5.0], [0.0, 0.0, 1000.0], five), + ]; + for (name, b, at, origin, angle) in cases { + let r = draft(b, &[at], TOL, origin, z, z, angle).unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(volume(&r, 1e-8).unwrap() > 0.0, "{name}"); + } +} + +/// The tip cut off a triangular prism, drafted about a plane 100 mm off so that the whole face goes +/// out past where its neighbours meet: its edges vanish, `SM_ERR_OFFSET_EDGE_VANISHES` in SMLib, +/// which the capi's `status` answers as `SMLIB_ERR_UNSUPPORTED`. +#[test] +fn a_draft_past_the_neighbours_meeting_is_unsupported() { + use crate::sweeps::{Curve, DraftCorner}; + let p = [[0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [11.0, 18.0, 0.0], [9.0, 18.0, 0.0]]; + let profile: Vec = (0..4).map(|i| Curve::Line { start: p[i], end: p[(i + 1) % 4] }).collect(); + let prism = super::sweep::extrude(&profile, [0.0, 0.0, 1.0], 10.0, 0.0, DraftCorner::default(), true).unwrap(); + let (tip, z, origin, angle) = ([[10.0, 18.0, 5.0]], [0.0, 0.0, 1.0], [0.0, 0.0, -100.0], (-2f64).to_radians()); + assert_eq!(draft(&prism, &tip, TOL, origin, z, z, angle).err(), Some(Error::Unsupported)); +} + +/// A flat L of two faces thickened by 2 with mitred walls: 2 x 10 x (20 + 22). +#[test] +fn an_l_sheet_thickens() { + use crate::sweeps::{Curve, DraftCorner}; + let l = [Curve::Line { start: [0.0; 3], end: [20.0, 0.0, 0.0] }, Curve::Line { start: [20.0, 0.0, 0.0], end: [20.0, 20.0, 0.0] }]; + let sheet = super::sweep::extrude(&l, [0.0, 0.0, 1.0], 10.0, 0.0, DraftCorner::default(), false).unwrap(); + let core = thicken(&sheet, 2.0, false).unwrap(); + assert!(rel(volume(&core, 1e-8).unwrap(), 840.0) < 1e-9); +} + +/// solidcore#2350's parabolic sheet: the quadratic Bézier (-10, 0), (0, 10), (10, 0) lofted 20 +/// along z, a B-spline face whose radius of curvature at its apex is 10. Thickened 11 towards +/// its centre of curvature its offset folds there: solidcore's one construction refuses it +/// naming 10, the largest wall that works (`fixes.shell_one_construction`); 2 builds. +#[test] +fn a_wall_thicker_than_its_face_curves_is_refused_naming_the_largest() { + use crate::sweeps::Curve; + let parabola = |z: f64| Curve::Nurbs { + degree: 2, + points: vec![[-10.0, 0.0, z, 1.0], [0.0, 10.0, z, 1.0], [10.0, 0.0, z, 1.0]], + knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], + }; + let sheet = super::sweep::loft(&[vec![parabola(0.0)], vec![parabola(20.0)]], 1, false).unwrap(); + // Towards the centre is the side where an 11 wall folds; the other side takes any wall. + let folds: Vec = [11.0, -11.0].iter().filter_map(|&t| thicken(&sheet, t, false).err()).map(|e| e.to_string()).collect(); + let [why] = folds.as_slice() else { panic!("one side folds: {folds:?}") }; + let (words, largest) = why.split_once("; the largest wall that works is ").unwrap_or_else(|| panic!("{why}")); + assert_eq!(words, "the wall is thicker than a face curves, so the face's offset folds"); + let largest: f64 = largest.parse().unwrap(); + assert!((largest - 10.0).abs() < 1e-9, "{largest}"); + assert!(thicken(&sheet, 2.0, false).is_ok() && thicken(&sheet, -2.0, false).is_ok()); +} diff --git a/crates/smlib/src/core/picked.rs b/crates/smlib/src/core/picked.rs new file mode 100644 index 000000000..a7c6d5009 --- /dev/null +++ b/crates/smlib/src/core/picked.rs @@ -0,0 +1,100 @@ +//! What a pick by points chose, as indices into the body's own lists: for the operations a trace +//! records ([`crate::trace`]), so the corpus names its edges, faces and corners by topology +//! index as well as by the points the operation was given. Each point is picked alone, by the +//! picker the operation runs, on a copy of the body as the operation received it: a pick builds +//! query caches on the body it reads, and the body traced stays as an untraced run leaves it. + +use std::sync::PoisonError; + +use solidcore::geom::vector3d::Vec3; +use solidcore::topology::brep::p1 as brep_p1; +use solidcore::topology::brep::p3::brep_copy; +use solidcore::topology::{edge, vertex}; + +use super::Body; +use super::blend::{Miss, pick_edges, pick_vertices}; +use super::offset::pick_faces; +use super::trim::{face_at, nearest_edge}; +use crate::Result; +use crate::trace::{Pick, PickKind}; + +/// The entity each of `points` picks within `tolerance` on `body`, as [`Pick`]s: its index in +/// the body's list of that kind (`None` where the point picks none or is ambiguous) and, for an +/// edge, its end points; for a vertex, its point. +pub(crate) fn picks(body: &Body, kind: PickKind, points: &[[f64; 3]], tolerance: f64) -> Result> { + super::run_on("trace pick", &[], |k| { + let mut b = brep_copy(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner))?; + let mut out = Vec::with_capacity(points.len()); + for p in points { + let one = std::slice::from_ref(p); + let pick = match kind { + PickKind::Edge => { + let all = brep_p1::edges(&b, None)?; + match pick_edges(k, &b, one, tolerance)? { + Ok((es, _)) => match es.first() { + Some(&e) => Pick { index: all.iter().position(|&x| x == e), at: ends(&b, e)?, miss: None }, + None => Pick::missed("none"), + }, + Err(m) => Pick::missed(miss(m)), + } + } + PickKind::NearestEdge => { + let all = brep_p1::edges(&b, None)?; + match nearest_edge(k, &b, &all, Vec3::new(p[0], p[1], p[2])) { + (d, Some(e)) if d <= tolerance => Pick { index: all.iter().position(|&x| x == e), at: ends(&b, e)?, miss: None }, + _ => Pick::missed("none"), + } + } + PickKind::NearestFace => { + let all = brep_p1::faces(&b, None)?; + match face_at(k, &mut b, Vec3::new(p[0], p[1], p[2]), tolerance)? { + Some(f) => Pick { index: all.iter().position(|&x| x == f), at: Vec::new(), miss: None }, + None => Pick::missed("none"), + } + } + PickKind::Face => { + let all = brep_p1::faces(&b, None)?; + match pick_faces(k, &mut b, one, tolerance)? { + Ok(fs) => match fs.first() { + Some(&f) => Pick { index: all.iter().position(|&x| x == f), at: Vec::new(), miss: None }, + None => Pick::missed("none"), + }, + Err(m) => Pick::missed(miss(m)), + } + } + PickKind::Vertex => { + let all = brep_p1::vertices(&b, None)?; + match pick_vertices(&b, one, tolerance)? { + Ok((vs, _)) => match vs.first() { + Some(&v) => { + let q = vertex::point(&b, v)?; + Pick { index: all.iter().position(|&x| x == v), at: vec![[q.x, q.y, q.z]], miss: None } + } + None => Pick::missed("none"), + }, + Err(m) => Pick::missed(miss(m)), + } + } + }; + out.push(pick); + } + Ok(out) + }) +} + +/// Edge `e`'s end points. +fn ends(b: &solidcore::topology::Brep, e: solidcore::topology::EdgeId) -> solidcore::Result> { + let mut out = Vec::with_capacity(2); + for v in [edge::start_vertex(b, e)?, edge::end_vertex(b, e)?].into_iter().flatten() { + let q = vertex::point(b, v)?; + out.push([q.x, q.y, q.z]); + } + Ok(out) +} + +fn miss(m: Miss) -> &'static str { + match m { + Miss::None(_) => "none", + Miss::Ambiguous(_) => "ambiguous", + } +} diff --git a/crates/smlib/src/core/split.rs b/crates/smlib/src/core/split.rs new file mode 100644 index 000000000..6a9cb38ad --- /dev/null +++ b/crates/smlib/src/core/split.rs @@ -0,0 +1,507 @@ +//! Split Face and Split Body on solidcore: the C API's composition, ported from the fork's +//! `capi/src/smlib_split.cpp` (`smlib_split_faces`, `smlib_split_body`, `cut_face`, +//! `plane_covers`, `slice`, `both_sides`, `smlib_split_body_by_sheet`) and the tool surfaces of `capi/src/smlib_ssi.cpp` +//! (`smlib_surface_plane`, `_cylinder`, `_cone`, `_sphere`, `_torus`, `_nurbs`). +//! +//! As there, every operation works on copies of its body (`SmApiBrepCopy`). A face is cut where +//! a tool meets it the way SMLib's plane cutter cuts a subset of faces: the face's surface is +//! intersected with the tool over the face's UV domain (`CreatePlanarSectionCurves` for a plane +//! reaching over the face, `GlobalSurfaceIntersect` otherwise) and the untrimmed curves go to +//! `SmBrep::MergeCurvesOnSurface` with the tool as the intersecting surface. Unlike the plane +//! cutter, a failed merge fails the call. A body is split by slicing (`SM_BO_SLICE`) copies of it +//! with a one-face sheet on the tool surface, once with the surface turned over; or with a sheet +//! of several faces as it is, its surfaces first turned to agree. +//! +//! A tool is a [`crate::ssi::Surface`]; solidcore's own surface is made from its description +//! ([`Spec`]), as `smlib_ssi.cpp` makes SMLib's, over the surface's natural UV domain. + +use std::sync::PoisonError; + +use solidcore::EntityRef; +use solidcore::boolean::api_brep::boolean_with_options; +use solidcore::boolean::merge::MergeOptions; +use solidcore::geom::a_object::BooleanOperation; +use solidcore::geom::axis2_placement::Axis2Placement; +use solidcore::geom::extent2d::Extent2d; +use solidcore::geom::object::ObjectRef; +use solidcore::geom::tol::{USE_DEFAULT, approx_tol3d}; +use solidcore::geom::vector2d::Vec2; +use solidcore::geom::vector3d::{Point3, Vec3}; +use solidcore::kernel::Kernel; +use solidcore::nurbs::b_spline_curve::p1::KnotType; +use solidcore::nurbs::b_spline_surface::p1::{BSplineSurface, BSplineSurfaceForm, CanonicalSurfaceData}; +use solidcore::nurbs::math::CPoint; +use solidcore::query::brep::BrepFaceServices; +use solidcore::query::face::p1::calculate_bounding_box; +use solidcore::surface::cone::p1::Cone; +use solidcore::surface::plane::p1::Plane; +use solidcore::surface::sphere::{Sphere, SphereOptions}; +use solidcore::surface::surface::Surface; +use solidcore::surface::surface::p2::TsectCurveType; +use solidcore::surface::torus::{Torus, TorusOptions}; +use solidcore::topology::brep::p1 as brep_p1; +use solidcore::topology::brep::p2::{is_manifold_solid, is_sheet}; +use solidcore::topology::brep::p3::{new_brep, with_kernel_callbacks}; +use solidcore::topology::brep::p8::create_face_from_surface; +use solidcore::topology::brep::p9::orient_sheet_surfaces; +use solidcore::topology::brep::p10::merge_curves_on_surface_through_surface; +use solidcore::topology::brep::planar_section::face_planar_section_curves; +use solidcore::topology::brep_cache::CacheObject; +use solidcore::topology::edge::NotifyEnv; +use solidcore::topology::face::p2 as face_p2; +use solidcore::topology::{Brep, EdgeId, FaceId}; + +use super::Body; +use super::blend::status; +use super::sweep::build_faces; +use crate::ssi::Spec; +use crate::{Error, Result}; +use solidcore::topology::brep::p3::brep_copy; + +/// `SMLIB_SPLIT_MAX_FACES`, `SMLIB_SPLIT_MAX_TOOLS`. +pub(crate) const MAX_FACES: usize = 100_000; +pub(crate) const MAX_TOOLS: usize = 4096; + +/// `SM_ERR`. +const SM_ERR: i32 = 1001; + +/// The capi's statuses as SolidCraft errors: an operation's own result. +type Out = std::result::Result; + +/// A tool surface as solidcore holds it: the surface over its natural UV domain (`smlib_surface`'s +/// `s` and `domain`), and for a plane its point and unit normal (`IsPlanar`). +pub(crate) struct Tool { + pub(super) surface: Surface, + pub(super) domain: Extent2d, + plane: Option<(Point3, Vec3)>, +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// The runner's `unit_cross`. +fn unit_cross(a: Vec3, b: Vec3) -> Vec3 { + let c = a.cross(b); + let l = c.length(); + Vec3::new(c.x / l, c.y / l, c.z / l) +} + +/// `[k0, k0, k1, ...]` as unique values and their multiplicities (`unique_knots`). +fn unique_knots(k: &[f64]) -> (Vec, Vec) { + let (mut values, mut mults): (Vec, Vec) = (Vec::new(), Vec::new()); + for &x in k { + match (values.last(), mults.last_mut()) { + (Some(&last), Some(m)) if last == x => *m += 1, + _ => { + values.push(x); + mults.push(1); + } + } + } + (values, mults) +} + +/// `clamped`: the first and the last knot each p + 1 times. +fn clamped(k: &[f64], p: usize) -> bool { + match (k.first(), k.get(p), k.last(), k.len().checked_sub(1 + p).and_then(|i| k.get(i))) { + (Some(a), Some(b), Some(c), Some(d)) => a == b && c == d, + _ => false, + } +} + +/// The tool's surface as `smlib_ssi.cpp`'s constructors make it, then its natural UV domain +/// (`construct`: finite and not empty, else `SM_ERR_INVALID_INPUT`). +pub(super) fn tool(k: &Kernel, spec: &Spec) -> solidcore::Result> { + let mut plane = None; + let surface = match spec { + Spec::Plane { origin, xaxis, yaxis, u, v } => { + let dom = Extent2d::from_bounds(u[0], v[0], u[1], v[1]); + plane = Some((v3(*origin), unit_cross(v3(*xaxis), v3(*yaxis)))); + Surface::from(Plane::new(v3(*origin), v3(*xaxis), v3(*yaxis), Vec2::new(1.0, 1.0), &dom)) + } + Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height } => { + let (x, y) = (v3(*xaxis), v3(*yaxis)); + let o = v3(*origin) + unit_cross(x, y) * height[0]; + Surface::from(Cone::new_cylinder_bounded(o, x, y, *radius, angle_deg[0], angle_deg[1], height[1] - height[0], false, false, false)) + } + Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height } => { + let (x, y) = (v3(*xaxis), v3(*yaxis)); + let (h0, h1) = (height[0], height[1]); + let t = half_angle_deg.to_radians().tan(); + let o = v3(*apex) + unit_cross(x, y) * h0; + let pl = Axis2Placement::new(o, x, y); + Surface::from(Cone::create_canonical(k, &pl, h0 * t, h1 * t, h1 - h0, false, false)?) + } + Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg } => { + let anal = Extent2d::from_bounds(lon_deg[0], lat_deg[0], lon_deg[1], lat_deg[1]); + let opts = SphereOptions { swap_uv: false, inside_out: false, circle_nurb: None }; + Surface::from(Sphere::new(k, v3(*center), v3(*xaxis), v3(*yaxis), anal, *radius, opts)?) + } + Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg } => { + let anal = Extent2d::from_bounds(major_deg[0], minor_deg[0], major_deg[1], minor_deg[1]); + Surface::from(Torus::new(k, v3(*center), v3(*xaxis), v3(*yaxis), anal, *major_radius, *minor_radius, TorusOptions::default())?) + } + Spec::Nurbs { degree, nu, nv, knots_u, knots_v, points, weights } => { + let [p, q] = *degree; + let w = |i: usize| weights.as_ref().and_then(|w| w.get(i).copied()).unwrap_or(1.0); + if !clamped(knots_u, p) || !clamped(knots_v, q) { + // SMLib's component constructor clamps the surface to its domain. + let (ku, mu) = unique_knots(knots_u); + let (kv, mv) = unique_knots(knots_v); + let wts: Vec = (0..points.len()).map(w).collect(); + let pts: Vec = points.iter().map(|p| v3(*p)).collect(); + let data = CanonicalSurfaceData { + u_degree: p, + v_degree: q, + control_points: &pts, + form: BSplineSurfaceForm::Unspecified, + u_multiplicities: &mu, + v_multiplicities: &mv, + u_knots: &ku, + v_knots: &kv, + knot_type: KnotType::Unspecified, + weights: Some(&wts), + uv_domain: None, + }; + Surface::from(BSplineSurface::create_canonical(&data)?) + } else { + // The runner's way: the homogeneous net filled directly. + let mut pw = Vec::with_capacity(*nu); + for i in 0..*nu { + let mut row = Vec::with_capacity(*nv); + for j in 0..*nv { + let at = i * nv + j; + let (Some(pt), wt) = (points.get(at), w(at)) else { + return Ok(Err(Error::Argument)); + }; + row.push(CPoint::new(pt[0] * wt, pt[1] * wt, pt[2] * wt, wt)); + } + pw.push(row); + } + let (n, m) = (nu.saturating_sub(1), nv.saturating_sub(1)); + let (r, s) = (knots_u.len().saturating_sub(1), knots_v.len().saturating_sub(1)); + Surface::from(BSplineSurface::from_data(n, m, p, q, r, s, &pw, knots_u, knots_v)?) + } + } + }; + let domain = surface.natural_uv_domain_with_nurb(k)?; + let (lo, hi) = (domain.min(), domain.max()); + if !(lo.x.is_finite() && lo.y.is_finite() && hi.x.is_finite() && hi.y.is_finite() && lo.x < hi.x && lo.y < hi.y) { + return Ok(Err(Error::Status(1007))); + } + Ok(Ok(Tool { surface, domain, plane })) +} + +/// `plane_covers`: whether the plane `tool` reaches over all of `bx` (each corner's foot on the +/// plane lies in the tool's parameter box): then its section with a face in the box is the +/// infinite plane's. +fn plane_covers(k: &Kernel, tool: &Tool, bx: &solidcore::geom::extent3d::Extent3d, tol: f64) -> bool { + let (lo, hi) = (tool.domain.min(), tool.domain.max()); + let at = |u: f64, v: f64| tool.surface.evaluate_point(k, Vec2::new(u, v)).ok(); + let (Some(o), Some(pu), Some(pv)) = (at(lo.x, lo.y), at(hi.x, lo.y), at(lo.x, hi.y)) else { + return false; + }; + // The plane is affine in (u, v): P = o + (u - u0) X + (v - v0) Y. + let x = (pu - o) / (hi.x - lo.x); + let y = (pv - o) / (hi.y - lo.y); + let (a, b, c) = (x.dot(x), x.dot(y), y.dot(y)); + let det = a * c - b * b; + if !(det.abs() > 0.0) { + return false; + } + let (m, mm) = (bx.min(), bx.max()); + (0..8).all(|kk| { + let q = Vec3::new(if kk & 1 != 0 { mm.x } else { m.x }, if kk & 2 != 0 { mm.y } else { m.y }, if kk & 4 != 0 { mm.z } else { m.z }); + let r = q - o; + let (g0, g1) = (x.dot(r), y.dot(r)); + let u = lo.x + (c * g0 - b * g1) / det; + let v = lo.y + (a * g1 - b * g0) / det; + let (su, sv) = (tol / a.sqrt(), tol / c.sqrt()); + u >= lo.x - su && u <= hi.x + su && v >= lo.y - sv && v <= hi.y + sv + }) +} + +/// The name of each edge curve a merge makes (`SmApiCut`'s). +fn curve_ref(e: EdgeId, _type_code: i64) -> ObjectRef { + solidcore::topology::loopuse::notify_ref(EntityRef::Edge(e)) +} + +/// `cut_face`: cuts `face` where `tool` meets it; the faces it was split into besides itself. +fn cut_face(k: &mut Kernel, b: &mut Brep, env: &mut NotifyEnv<'_>, face: FaceId, tool: &Tool, tol: f64) -> solidcore::Result>> { + let Some(surface) = face_p2::surface(b, face)? else { + return Ok(Err(Error::Status(SM_ERR))); + }; + let surface = surface.clone_for_evaluation()?; + let domain = face_p2::uv_domain(b, face)?; + let approx = approx_tol3d(k, approx_tol3d(k, tol) / 4.0); + let bx = match calculate_bounding_box(k, &mut *b, face, false) { + Ok(bx) => bx, + Err(e) => return Ok(Err(status(e))), + }; + let merge = + |k: &mut Kernel, b: &mut Brep, env: &mut NotifyEnv<'_>, mut c3: Vec<_>, uv: Option>| match merge_curves_on_surface_through_surface( + k, + b, + env, + &curve_ref, + face, + tol, + &mut c3, + uv.as_deref(), + Some(tool.surface.clone()), + ) { + Ok((made, _)) => Ok(Ok(made)), + Err(e) => Ok(Err(status(e))), + }; + // A plane reaching over the face sections it exactly (SmPlaneCutter's way); a plane strip, + // like any other tool, is intersected over its own domain. + if let Some((at, normal)) = tool.plane + && plane_covers(k, tool, &bx, tol) + { + // As SmPlaneCutter: a face far from the plane is not sectioned. + if bx.distance_to_plane(at, normal).abs() > tol { + return Ok(Ok(Vec::new())); + } + let section = match face_planar_section_curves(k, b, face, &surface, &domain, at, normal, Some(approx), None) { + Ok(s) => s, + Err(e) => return Ok(Err(status(e))), + }; + if section.curves_3d.is_empty() { + return Ok(Ok(Vec::new())); + } + let uv = (section.uv_curves.len() == section.curves_3d.len()).then_some(section.uv_curves); + return merge(k, b, env, section.curves_3d, uv); + } + // `face->GetSurface()` reaches its face's trimmed cache: the solve runs through the B-rep's + // face services, as solidcore's own face intersections do (a face-owned surface has no cache + // of its own). + let mut services = BrepFaceServices::new(&mut *b); + let found = match surface.global_surface_intersect_with_context( + k, + [Some(CacheObject::Surface(face)), None], + &mut services, + &domain, + &tool.surface, + &tool.domain, + [true, true], + Some(approx), + None, + ) { + Ok(f) => f, + Err(e) => return Ok(Err(status(e))), + }; + // A single point of contact cuts nothing. + let (mut c3, mut uv1) = (Vec::new(), Vec::new()); + for (i, c) in found.curves_3d.into_iter().enumerate() { + if found.curve_types.get(i) == Some(&TsectCurveType::Touching) { + continue; + } + c3.push(c); + uv1.push(found.surface1_uv_curves.get(i).cloned().flatten()); + } + if c3.is_empty() { + return Ok(Ok(Vec::new())); + } + let all_uv = uv1.iter().all(Option::is_some); + merge(k, b, env, c3, all_uv.then_some(uv1)) +} + +/// `smlib_split_faces`: a copy of `body` with faces `faces` (indices in its face order, distinct) +/// cut where each tool meets them, the tools in turn, each cutting the pieces the earlier ones +/// left; and for each face how many faces it became besides itself. `None` when no face is split +/// (`SMLIB_ERR_NO_CUT`). +pub(crate) fn split_faces(body: &Body, faces: &[usize], tools: &[&Spec]) -> Result)>> { + if faces.is_empty() || faces.len() > MAX_FACES || tools.is_empty() || tools.len() > MAX_TOOLS { + return Err(Error::Argument); + } + if body.0.is_poisoned() { + return Err(Error::Internal("smlib_split_faces: the body was left unfinished by an earlier panic".to_owned())); + } + let r = super::run_on("smlib_split_faces", &[("brep", body)], |k| { + let mut a = { + let g = body.0.lock().unwrap_or_else(PoisonError::into_inner); + let count = brep_p1::faces(&g, None)?.len(); + let mut seen = std::collections::HashSet::new(); + if faces.iter().any(|&f| f >= count || !seen.insert(f)) { + return Ok(Err(Error::Argument)); + } + brep_copy(k, &g)? + }; + let all = brep_p1::faces(&a, None)?; + // Each chosen face and, as tools cut it, its pieces. + let mut pieces: Vec> = Vec::with_capacity(faces.len()); + for &f in faces { + let Some(&face) = all.get(f) else { return Ok(Err(Error::Status(SM_ERR))) }; + pieces.push(vec![face]); + } + let mut made = vec![0usize; faces.len()]; + let mut built = Vec::with_capacity(tools.len()); + for spec in tools { + match tool(k, spec)? { + Ok(t) => built.push(t), + Err(e) => return Ok(Err(e)), + } + } + let editing = a.editing_enabled(); + let doing = k.context.doing_boolean(); + a.set_editing_enabled(true); + k.context.set_doing_boolean(true); + let tol = a.tolerance(); + // The edits notify through the kernel's callbacks with the body's own attributes, so + // the history tags follow each cut (as SMLib's objects notify their attributes). + let cut = with_kernel_callbacks(k, &mut a, |k, a, env| { + let mut total = 0usize; + for t in &built { + for (i, list) in pieces.iter_mut().enumerate() { + let now = list.clone(); + for f in now { + let split = match cut_face(k, a, env, f, t, tol)? { + Ok(s) => s, + Err(e) => return Ok(Err(e)), + }; + if let Some(m) = made.get_mut(i) { + *m += split.len(); + } + total += split.len(); + list.extend(split); + } + } + } + Ok(Ok(total)) + }); + a.set_editing_enabled(editing); + k.context.set_doing_boolean(doing); + a.refresh_cached_topology(); + // The cut's new edges own their curves under the kernel's identities (it records them), + // not the copy's Notify ones, and the check reads the owners by the body's naming. + a.set_naming(solidcore::topology::NamingScheme::Caller); + Ok(match cut? { + Err(e) => Err(e), + Ok(0) => Ok(None), + Ok(_) => Ok(Some((a, made))), + }) + })??; + Ok(r.map(|(b, made)| (Body::new(b), made))) +} + +/// `slice`: a copy of `body` sliced by `sheet` (SMLib's slice reads the side from the surfaces, not +/// the faces' uses). `None` when nothing is left. +fn slice(k: &mut Kernel, body: &Body, sheet: Brep) -> solidcore::Result>> { + let a = { + let g = body.0.lock().unwrap_or_else(PoisonError::into_inner); + brep_copy(k, &g)? + }; + let options = MergeOptions::new(false, false, false, false, false); + let r = match boolean_with_options(k, a, sheet, BooleanOperation::Slice, options) { + Ok(r) => r.result, + Err(e) => return Ok(Err(status(e))), + }; + Ok(Ok((!r.face_list().is_empty()).then_some(r))) +} + +/// `both_sides`: both parts, `side` making each side's sheet (`true`: turned over, for the back). +/// A body that is no manifold solid is [`Error::NotSolid`]; a side left empty is `None` +/// (`SMLIB_ERR_NO_CUT`), and with `whole` so is a part that is no manifold solid: `SM_BO_SLICE` +/// with a sheet that only nicks a region behaves as a difference, leaving the sheet's piece as a +/// slit in the body and a lamina on the other side, which is no cut. +fn both_sides( + k: &mut Kernel, + body: &Body, + whole: bool, + mut side: impl FnMut(&mut Kernel, bool) -> solidcore::Result>, +) -> solidcore::Result>> { + let solid = { + let g = body.0.lock().unwrap_or_else(PoisonError::into_inner); + is_manifold_solid(&g)? + }; + if !solid { + return Ok(Err(Error::NotSolid)); + } + let mut parts = [None, None]; + for (part, flip) in parts.iter_mut().zip([true, false]) { + let sheet = match side(k, flip)? { + Ok(s) => s, + Err(e) => return Ok(Err(e)), + }; + *part = match slice(k, body, sheet)? { + Ok(p) => p, + Err(e) => return Ok(Err(e)), + }; + } + let [Some(back), Some(front)] = parts else { return Ok(Ok(None)) }; + if whole && !(is_manifold_solid(&back)? && is_manifold_solid(&front)?) { + return Ok(Ok(None)); + } + Ok(Ok(Some((back, front)))) +} + +/// One side of `smlib_split_body`: a one-face sheet on the tool's surface, turned over with `flip`. +fn side(k: &mut Kernel, body: &Body, spec: &Spec, flip: bool) -> solidcore::Result> { + let tolerance = body.0.lock().unwrap_or_else(PoisonError::into_inner).tolerance(); + let t = match tool(k, spec)? { + Ok(t) => t, + Err(e) => return Ok(Err(e)), + }; + let mut surface = t.surface.copy(k)?; + if flip && let Err(e) = surface.swap_uv(k) { + return Ok(Err(status(e))); + } + let mut sheet = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + sheet.set_tolerance(tolerance); + let natural = surface.natural_uv_domain_with_nurb(k)?; + if let Err(e) = build_faces(&mut sheet, |s, fenv| create_face_from_surface(k, s, Some(surface), &natural, fenv)) { + return Ok(Err(status(e))); + } + sheet.refresh_cached_topology(); + Ok(Ok(sheet)) +} + +/// `smlib_split_body`: the manifold solid `body` cut in two by the tool: the part behind the +/// surface (its normal points away) and the part in front. A side left empty is `None` +/// (`SMLIB_ERR_NO_CUT`); a body that is no manifold solid is [`Error::NotSolid`]. +pub(crate) fn split_body(body: &Body, spec: &Spec) -> Result> { + if body.0.is_poisoned() { + return Err(Error::Internal("smlib_split_body: the body was left unfinished by an earlier panic".to_owned())); + } + let r = super::run_on("smlib_split_body", &[("brep", body)], |k| both_sides(k, body, false, |k, flip| side(k, body, spec, flip)))??; + Ok(r.map(|(b, f)| (Body::new(b), Body::new(f)))) +} + +/// `smlib_split_body_by_sheet`: the manifold solid `body` cut in two by `sheet` as it is (one or +/// more faces joined edge to edge), its surfaces turned to agree with face `face`'s +/// (`SmBrep::OrientSheetSurfaces`), for the back all turned over: the part behind that normal and +/// the part in front. A sheet that does not divide the body is `None` (`SMLIB_ERR_NO_CUT`). A +/// `sheet` that is no sheet, or a `face` out of range, is [`Error::Argument`]. +pub(crate) fn split_body_by_sheet(body: &Body, sheet: &Body, face: usize) -> Result> { + if std::ptr::eq(body, sheet) { + return Err(Error::Argument); + } + if body.0.is_poisoned() || sheet.0.is_poisoned() { + return Err(Error::Internal("smlib_split_body_by_sheet: a body was left unfinished by an earlier panic".to_owned())); + } + let r = super::run_on("smlib_split_body_by_sheet", &[("brep", body), ("sheet", sheet)], |k| { + { + let g = sheet.0.lock().unwrap_or_else(PoisonError::into_inner); + if !is_sheet(k, &g)? || face >= g.face_list().len() { + return Ok(Err(Error::Argument)); + } + } + both_sides(k, body, true, |k, flip| { + let mut copy = { + let g = sheet.0.lock().unwrap_or_else(PoisonError::into_inner); + brep_copy(k, &g)? + }; + let Some(&f) = brep_p1::faces(©, None)?.get(face) else { return Ok(Err(Error::Argument)) }; + // The UV swaps notify as SMLib's objects do: through the kernel's callbacks, with + // the sheet's own attributes, so its faces' tags see each swap. + let turned = with_kernel_callbacks(k, &mut copy, |k, b, env| orient_sheet_surfaces(k, b, Some(f), !flip, env)); + copy.refresh_cached_topology(); + Ok(match turned { + Ok(()) => Ok(copy), + Err(e) => Err(status(e)), + }) + }) + })??; + Ok(r.map(|(b, f)| (Body::new(b), Body::new(f)))) +} diff --git a/crates/smlib/src/core/split_tests.rs b/crates/smlib/src/core/split_tests.rs new file mode 100644 index 000000000..5a55fca2c --- /dev/null +++ b/crates/smlib/src/core/split_tests.rs @@ -0,0 +1,315 @@ +//! Split Face and Split Body on solidcore, against closed forms: face, edge and vertex counts, +//! volumes, how many faces each chosen face became, and every result exports to a record that +//! validates. +//! +//! The body is a 10 mm cube [0, 10]^3 on solidcore; the tools are described as +//! [`crate::ssi::Surface`] describes them. + +use super::split::{split_body, split_body_by_sheet, split_faces}; +use super::{Body, area, counts, make_box, to_arrays, volume}; +use crate::Error; +use crate::export::native; +use crate::ssi::Spec; + +const X: [f64; 3] = [1.0, 0.0, 0.0]; +const Y: [f64; 3] = [0.0, 1.0, 0.0]; +const Z: [f64; 3] = [0.0, 0.0, 1.0]; + +fn cube() -> Body { + make_box([0.0; 3], [10.0; 3]).unwrap() +} + +/// The plane x = `at` over u (along y) and v (along z) in `[-1, 11]`: it reaches over the cube. +fn plane_x(at: f64) -> Spec { + Spec::Plane { origin: [at, 0.0, 0.0], xaxis: Y, yaxis: Z, u: [-1.0, 11.0], v: [-1.0, 11.0] } +} + +/// The cylinder of radius 3 about the vertical line through (5, 5), from z = -1 to 11. +fn cylinder() -> Spec { + Spec::Cylinder { origin: [5.0, 5.0, 0.0], xaxis: X, yaxis: Y, radius: 3.0, angle_deg: [0.0, 360.0], height: [-1.0, 11.0] } +} + +#[derive(Clone, Debug)] +enum Op { + /// Split the faces (all six when empty) by the tools. + Faces(Vec, Vec), + Body(Spec), +} + +#[derive(Clone, Debug, PartialEq)] +enum Expect { + /// Volume, counts, and the total of faces made. + Split(f64, [usize; 3], usize), + /// The two sides' volumes and counts. + Halves(f64, [usize; 3], f64, [usize; 3]), + NoCut, +} + +fn case(name: &str) -> (Op, Expect) { + let all: Vec = (0..6).collect(); + match name { + // Four faces cross x = 5, each cut in two; the four edges along x are cut at it. + "split_faces_by_a_plane" => (Op::Faces(all, vec![plane_x(5.0)]), Expect::Split(1000.0, [10, 20, 12], 4)), + // The cylinder meets the top and the bottom in a circle each: a disc and a holed face. + "split_faces_by_a_cylinder" => (Op::Faces(all, vec![cylinder()]), Expect::Split(1000.0, [8, 14, 10], 2)), + // Two planes in turn, the second cutting the first's pieces. + "split_faces_by_two_planes" => (Op::Faces(all, vec![plane_x(3.0), plane_x(7.0)]), Expect::Split(1000.0, [14, 28, 16], 8)), + "split_faces_missed_by_the_tool" => (Op::Faces(all, vec![plane_x(20.0)]), Expect::NoCut), + "split_body_by_a_plane" => (Op::Body(plane_x(3.0)), Expect::Halves(300.0, [6, 12, 8], 700.0, [6, 12, 8])), + // A tool that misses leaves both parts the whole body. + "split_body_missed_by_the_tool" => (Op::Body(plane_x(20.0)), Expect::Halves(1000.0, [6, 12, 8], 1000.0, [6, 12, 8])), + _ => panic!("no case {name}"), + } +} + +#[derive(Debug, PartialEq)] +enum Measured { + Split { volume: f64, counts: [usize; 3], made: Vec }, + Halves { volumes: [f64; 2], counts: [[usize; 3]; 2] }, + NoCut, +} + +type Got = std::result::Result; + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +fn valid(name: &str, b: &Body) { + let (rec, _) = native(&to_arrays(b).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); +} + +fn judge(name: &str, who: &str, got: Got) -> Got { + let (_, expect) = case(name); + match (&expect, &got) { + (_, Err(g)) => panic!("{name}: {who} failed: {g}"), + (Expect::NoCut, Ok(m)) => assert_eq!(*m, Measured::NoCut, "{name}: {who}"), + (Expect::Split(v, n, total), Ok(Measured::Split { volume, counts, made })) => { + assert!(rel(*volume, *v) < 1e-9, "{name}: {who} volume {volume} vs analytic {v}"); + assert_eq!(counts, n, "{name}: {who} counts"); + assert_eq!(made.iter().sum::(), *total, "{name}: {who} faces made {made:?}"); + } + (Expect::Halves(v0, n0, v1, n1), Ok(Measured::Halves { volumes, counts })) => { + assert!(rel(volumes[0], *v0) < 1e-9 && rel(volumes[1], *v1) < 1e-9, "{name}: {who} volumes {volumes:?} vs {v0} {v1}"); + assert_eq!(counts, &[*n0, *n1], "{name}: {who} counts"); + } + (e, Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"), + } + got +} + +fn solidcore_case(name: &str) -> Got { + let (op, _) = case(name); + let got = match &op { + Op::Faces(faces, tools) => { + let tools: Vec<&Spec> = tools.iter().collect(); + split_faces(&cube(), faces, &tools).map(|r| match r { + None => Measured::NoCut, + Some((b, made)) => { + valid(name, &b); + Measured::Split { volume: volume(&b, 1e-8).unwrap(), counts: counts(&b).unwrap(), made } + } + }) + } + Op::Body(tool) => split_body(&cube(), tool).map(|r| match r { + None => Measured::NoCut, + Some((b, f)) => { + valid(name, &b); + valid(name, &f); + Measured::Halves { + volumes: [volume(&b, 1e-8).unwrap(), volume(&f, 1e-8).unwrap()], + counts: [counts(&b).unwrap(), counts(&f).unwrap()], + } + } + }), + }; + judge(name, "solidcore", got) +} + +macro_rules! cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +cases!( + split_faces_by_a_plane, + split_faces_by_a_cylinder, + split_faces_by_two_planes, + split_faces_missed_by_the_tool, + split_body_by_a_plane, + split_body_missed_by_the_tool, +); + +/// The capi's argument checks, before any kernel call. +#[test] +fn hostile_arguments_are_refused() { + let b = cube(); + let p = plane_x(5.0); + assert_eq!(split_faces(&b, &[], &[&p]).err(), Some(Error::Argument), "no face"); + assert_eq!(split_faces(&b, &[0], &[]).err(), Some(Error::Argument), "no tool"); + assert_eq!(split_faces(&b, &[0, 0], &[&p]).err(), Some(Error::Argument), "a face twice"); + assert_eq!(split_faces(&b, &[6], &[&p]).err(), Some(Error::Argument), "no face 6"); + assert_eq!(split_faces(&b, &[usize::MAX], &[&p]).err(), Some(Error::Argument), "no face usize::MAX"); + let many = vec![&p; super::split::MAX_TOOLS + 1]; + assert_eq!(split_faces(&b, &[0], &many).err(), Some(Error::Argument), "too many tools"); + let faces: Vec = (0..=super::split::MAX_FACES).collect(); + assert_eq!(split_faces(&b, &faces, &[&p]).err(), Some(Error::Argument), "too many faces"); +} + +/// A sheet is no solid to split in two (`SMLIB_ERR_NOT_SOLID`). +#[test] +fn a_sheet_is_not_split_into_two_bodies() { + use solidcore::curve::curve::Curve; + use solidcore::geom::vector3d::Vec3; + use solidcore::primitive::api_curves::create_line_segment; + use solidcore::sweep::api_brep::create_linear_sweep; + let sheet = super::run("sheet", |k| { + let c = Curve::from(create_line_segment(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0))?); + create_linear_sweep(k, &[Some(&c)], Vec3::new(0.0, 1.0, 0.0), 10.0, false) + }) + .map(Body::new) + .unwrap(); + assert!(rel(area(&sheet, 1e-8).unwrap(), 100.0) < 1e-9); + assert_eq!(split_body(&sheet, &plane_x(5.0)).err(), Some(Error::NotSolid)); +} + +/// Faces of the box -20..5 x -20..20 x -20..5 copied off it into a sheet (`CopyFaces` with merge, +/// as the capi's test): the top z = 5 and, with `side`, the side x = 5 too. +fn lid(side: bool) -> Body { + use solidcore::EntityRef; + use solidcore::geom::tol::USE_DEFAULT; + use solidcore::query::api_queries::face_internal_point; + use solidcore::topology::brep::p1::faces; + use solidcore::topology::brep::p2::ArenaNotifyState; + use solidcore::topology::brep::p3::new_brep; + use solidcore::topology::brep::p7::copy_faces; + let slab = make_box([-20.0; 3], [25.0, 40.0, 25.0]).unwrap(); + super::run("sheet", |k| { + let mut whole = solidcore::topology::brep::p3::brep_copy(k, &slab.0.lock().unwrap())?; + let mut picked = Vec::new(); + for f in faces(&whole, None)? { + let p = face_internal_point(k, &mut whole, f)?; + if (p.z - 5.0).abs() < 1e-9 || (side && (p.x - 5.0).abs() < 1e-9) { + picked.push(f); + } + } + assert_eq!(picked.len(), if side { 2 } else { 1 }); + let mut w = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + w.set_tolerance(whole.tolerance()); + { + let mut state = ArenaNotifyState::new(&w); + let mut env = state.env(None); + let key_of = env.key_of; + let this_face = |f| key_of(EntityRef::Face(f)); + copy_faces(k, &mut whole, &picked, &mut w, true, &this_face, &mut env)?; + } + w.refresh_cached_topology(); + Ok(w) + }) + .map(Body::new) + .unwrap() +} + +/// The capi's test of `smlib_split_body_by_sheet` (fork 2fc375f): a cube 0..10 cut by an L of two +/// faces: the corner x < 5, z < 5 (250) on one side, the rest (750) on the other, whichever face +/// the sides are read from; on C++ too. +#[test] +fn split_body_by_an_l_sheet() { + let (c, sheet) = (cube(), lid(true)); + for face in 0..2 { + let (b, f) = split_body_by_sheet(&c, &sheet, face).unwrap().expect("the sheet divides the cube"); + valid("L sheet", &b); + valid("L sheet", &f); + let (vb, vf) = (volume(&b, 1e-8).unwrap(), volume(&f, 1e-8).unwrap()); + assert!(rel(vb.min(vf), 250.0) < 1e-9 && rel(vb.max(vf), 750.0) < 1e-9, "face {face}: {vb} + {vf}"); + } +} + +/// What `smlib_split_body_by_sheet` refuses: a body that is no sheet, a face out of range, the +/// sheet as its own body; a face that ends inside the cube only nicks it, which is no cut. +#[test] +fn split_by_a_sheet_refuses() { + let (c, sheet) = (cube(), lid(true)); + assert_eq!(split_body_by_sheet(&c, &make_box([-20.0; 3], [25.0, 40.0, 25.0]).unwrap(), 0).err(), Some(Error::Argument)); + assert_eq!(split_body_by_sheet(&c, &sheet, 2).err(), Some(Error::Argument)); + assert_eq!(split_body_by_sheet(&c, &c, 0).err(), Some(Error::Argument)); + assert!(split_body_by_sheet(&c, &lid(false), 0).unwrap().is_none()); + assert_eq!(split_body_by_sheet(&sheet, &lid(false), 0).err(), Some(Error::NotSolid)); +} + +/// The body split is never changed. +#[test] +fn the_body_stays_as_it_was() { + let b = cube(); + let _ = split_faces(&b, &[0, 1, 2, 3, 4, 5], &[&plane_x(5.0)]).unwrap(); + let _ = split_body(&b, &plane_x(5.0)).unwrap(); + assert_eq!(counts(&b).unwrap(), [6, 12, 8]); + assert!(rel(volume(&b, 1e-8).unwrap(), 1000.0) < 1e-12); +} + +/// A one-face sheet on a B-spline surface (as SolidCraft's extrude of a sketch spline makes it: +/// the cubic through (0, 0), (13, -8), (27, 8), (40, 0) in x and z, straight along y over +/// [0, 40]) cut by four plane strips standing on the square [12, 28]^2: the strips meet the +/// face inside its bounds, so the face's surface is intersected through its face's trimmed +/// cache. The square comes out as a face of its own, the sheet holed by it. +#[test] +fn a_spline_sheet_is_cut_by_strips_inside_it() { + use solidcore::geom::tol::USE_DEFAULT; + use solidcore::geom::vector3d::Vec3; + use solidcore::nurbs::b_spline_curve::p1::KnotType; + use solidcore::nurbs::b_spline_surface::p1::{BSplineSurface, BSplineSurfaceForm, CanonicalSurfaceData}; + use solidcore::surface::surface::Surface; + use solidcore::topology::brep::p3::new_brep; + use solidcore::topology::brep::p8::create_face_from_surface; + // Control points u-major: the curve's four, each at y = 0 and y = 40. + let curve = [[0.0, 0.0], [13.0, -8.0], [27.0, 8.0], [40.0, 0.0]]; + let pts: Vec = curve.iter().flat_map(|[x, z]| [Vec3::new(*x, 0.0, *z), Vec3::new(*x, 40.0, *z)]).collect(); + let sheet = super::run("sheet", |k| { + let surface = Surface::from(BSplineSurface::create_canonical(&CanonicalSurfaceData { + u_degree: 3, + v_degree: 1, + control_points: &pts, + form: BSplineSurfaceForm::Unspecified, + u_multiplicities: &[4, 4], + v_multiplicities: &[2, 2], + u_knots: &[0.0, 1.0], + v_knots: &[0.0, 40.0], + knot_type: KnotType::Unspecified, + weights: None, + uv_domain: None, + })?); + let mut b = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + let natural = surface.natural_uv_domain_with_nurb(k)?; + super::sweep::build_faces(&mut b, |s, fenv| create_face_from_surface(k, s, Some(surface), &natural, fenv))?; + b.refresh_cached_topology(); + Ok(b) + }) + .map(Body::new) + .unwrap(); + assert_eq!(counts(&sheet).unwrap(), [1, 4, 4]); + let whole = area(&sheet, 1e-8).unwrap(); + // The strip standing on the line from `o` along `d` (16 long), reaching past the sheet in z. + let strip = |o: [f64; 3], d: [f64; 3]| Spec::Plane { origin: o, xaxis: Z, yaxis: d, u: [-60.0, 60.0], v: [0.0, 16.0] }; + let tools = [ + strip([12.0, 12.0, 0.0], X), + strip([28.0, 12.0, 0.0], Y), + strip([28.0, 28.0, 0.0], [-1.0, 0.0, 0.0]), + strip([12.0, 28.0, 0.0], [0.0, -1.0, 0.0]), + ]; + let tools: Vec<&Spec> = tools.iter().collect(); + let (cut, made) = split_faces(&sheet, &[0], &tools).unwrap().expect("the strips cut the sheet"); + valid("spline sheet", &cut); + // The square's face and the holed sheet: four edges and vertices round each. + assert_eq!(counts(&cut).unwrap(), [2, 8, 8]); + assert_eq!(made, [1]); + // Cutting moves no surface: the pieces cover the sheet. + assert!(rel(area(&cut, 1e-8).unwrap(), whole) < 1e-9); +} diff --git a/crates/smlib/src/core/ssi.rs b/crates/smlib/src/core/ssi.rs new file mode 100644 index 000000000..230bd8e3b --- /dev/null +++ b/crates/smlib/src/core/ssi.rs @@ -0,0 +1,120 @@ +//! Surface/surface intersection on solidcore (`smlib_ssi.cpp`'s `smlib_ssi`, `smlib_surface_domain`, +//! `smlib_surface_evaluate`), on the surfaces [`crate::core::split`] makes from a [`Spec`]: +//! `SmSurface::GlobalSurfaceIntersect` and `SmAdvSurfaceIntersector`, whose results are read as the +//! capi reads them. + +use std::borrow::Cow; + +use solidcore::curve::curve::Curve; +use solidcore::geom::vector2d::Point2; +use solidcore::intersect::surface_intersector::p5::do_intersection; +use solidcore::kernel::Kernel; +use solidcore::nurbs::b_spline_curve::BSplineCurve; +use solidcore::surface::surface::p2::{SurfaceIntersection, TsectCurveType}; + +use super::convert::bspline_curve_part; +use super::run; +use super::split::{Tool, tool}; +use crate::ssi::{CurveType, Method, Nurbs, Spec, SsiCurve, SsiPoint, SsiResult, curve2, curve3}; +use crate::{Error, Result}; + +/// The surface of `spec` with its natural UV domain (`construct`). +pub(crate) fn surface(spec: &Spec) -> Result { + run("smlib_surface", |k| tool(k, spec))? +} + +/// `[u0, u1, v0, v1]`. +pub(crate) fn domain(s: &Tool) -> [f64; 4] { + let (lo, hi) = (s.domain.min(), s.domain.max()); + [lo.x, hi.x, lo.y, hi.y] +} + +/// The surface's point at (u, v): `smlib_surface_evaluate`, a non-finite point being `SM_ERR`. +pub(crate) fn evaluate(s: &Tool, u: f64, v: f64) -> Result<[f64; 3]> { + if !u.is_finite() || !v.is_finite() { + return Err(Error::Argument); + } + let p = run("smlib_surface_evaluate", |k| s.surface.evaluate_point(k, Point2::new(u, v)))?; + let r = [p.x, p.y, p.z]; + if r.iter().all(|x| x.is_finite()) { Ok(r) } else { Err(Error::Solidcore("smlib_surface_evaluate: not a finite point".into())) } +} + +fn curve_type(t: TsectCurveType) -> CurveType { + match t { + TsectCurveType::Unknown => CurveType::Unknown, + TsectCurveType::Touching => CurveType::Touching, + TsectCurveType::Crossing => CurveType::Crossing, + TsectCurveType::Tangent => CurveType::Tangent, + TsectCurveType::Coincident => CurveType::Coincident, + TsectCurveType::NearTangent => CurveType::NearTangent, + TsectCurveType::RegionBoundary => CurveType::RegionBoundary, + } +} + +/// The capi's `nurbs`: `c` as its B-spline, control points made cartesian in `dim` coordinates; +/// `None` for a curve that is not one, which is never approximated here. +fn nurbs(k: &Kernel, c: &Curve, dim: usize) -> Result> { + let Some(part): Option> = bspline_curve_part(k, c)? else { return Ok(None) }; + let Some(n) = part.gw_nurb() else { return Ok(None) }; + let mut out = Nurbs { points: Vec::with_capacity(n.cpts().len() * dim), weights: Vec::with_capacity(n.cpts().len()), knots: n.knots().to_vec() }; + for p in n.cpts() { + let w = if p.w != solidcore::nurbs::math::NOW { p.w } else { 1.0 }; + let q = [p.x / w, p.y / w, p.z / w]; + out.points.extend_from_slice(q.get(..dim).unwrap_or(&q)); + out.weights.push(w); + } + Ok(Some(out)) +} + +/// The capi's `start`: where `c` starts, NaN where there is no curve or it can't be evaluated. +fn start(k: &Kernel, c: Option<&Curve>) -> [f64; 3] { + c.and_then(|c| c.evaluate_point(k, c.natural_interval().min()).ok()).map_or([f64::NAN; 3], |p| [p.x, p.y, p.z]) +} + +fn read(k: &Kernel, r: &SurfaceIntersection) -> Result { + let mut out = SsiResult::default(); + for (i, c3) in r.curves_3d.iter().enumerate() { + let (ua, ub) = (r.surface1_uv_curves.get(i).and_then(Option::as_ref), r.surface2_uv_curves.get(i).and_then(Option::as_ref)); + let ty = r.curve_types.get(i).copied(); + let ivl = c3.natural_interval(); + let uv = |c: Option<&Curve>| -> Result<_> { Ok(c.map(|c| nurbs(k, c, 2)).transpose()?.flatten().map(curve2)) }; + out.curves.push(SsiCurve { + curve_type: ty.map_or(CurveType::None, curve_type), + deviation: r.deviations.get(i).copied().unwrap_or(f64::NAN), + interval: [ivl.min(), ivl.max()], + // A curve that is no B-spline is the one thing the result can't hold. + curve: curve3(nurbs(k, c3, 3)?.ok_or(Error::Unsupported)?), + uv_a: uv(ua)?, + uv_b: uv(ub)?, + }); + if ty == Some(TsectCurveType::Touching) { + let (a, b) = (start(k, ua), start(k, ub)); + out.points.push(SsiPoint { xyz: start(k, Some(c3)), uv_a: [a[0], a[1]], uv_b: [b[0], b[1]] }); + } + } + Ok(out) +} + +/// `smlib_ssi`: `a` and `b` within their domains, at approximation tolerance `approx_tol` (<= 0: +/// the kernel's default). +pub(crate) fn intersect(a: &Tool, b: &Tool, method: Method, approx_tol: f64) -> Result { + if !approx_tol.is_finite() { + return Err(Error::Argument); + } + let tol = (approx_tol > 0.0).then_some(approx_tol); + let edges = [true, true]; + run("smlib_ssi", |k| { + let found = match method { + Method::Global => a.surface.global_surface_intersect(k, &a.domain, &b.surface, &b.domain, edges, tol, None), + Method::Advanced => do_intersection(k, &a.surface, &a.domain, &b.surface, &b.domain, edges, tol, None), + }; + // An SMLib status is an answer, as the C API returns it. + match found { + Ok(found) => Ok(read(k, &found)), + Err(e) => match e.sm_status() { + Some(status) => Ok(Err(Error::Status(status))), + None => Err(e), + }, + } + })? +} diff --git a/crates/smlib/src/core/sweep.rs b/crates/smlib/src/core/sweep.rs new file mode 100644 index 000000000..c960549b2 --- /dev/null +++ b/crates/smlib/src/core/sweep.rs @@ -0,0 +1,1727 @@ +//! Extrusions, revolutions, sweeps, lofts and planar faces on solidcore: the C API's logic round +//! SM_API's sweeps, ported from the fork's `capi/src/smlib_sweeps.cpp` (`coord_ok`, `unit`, +//! `line`, `arc`, `nurbs`, `parse`, `finish`, `one_loop`, `FlatArc`, `one_circle`, `angle_on`, +//! `one_wall_per_circle`, `straight`, `circular`, `joined`, +//! `put_motion`, `turned`, `Rigid`, `Segment`, `segmented`, `carried`, `piecewise`, `maps_ok`, `placed`, `put_curve`, and the entry points +//! `smlib_planar_faces`, `smlib_extrude`, `smlib_revolve`, `smlib_sweep_placed`, `smlib_loft`, +//! `smlib_loft_to_point`, `smlib_sweep_stations`, `smlib_project_curves`, `smlib_face_section`, +//! and `smlib_screw_sweep` and `smlib_screw_sweep_radial` with `Screw`, `Stations`, +//! `lift_error`, `offset_error`, `path`, `path_curve`, `axial_radius`, `cylinder_piece`, +//! `screw_wall` and `screw_sweep`). +//! +//! As there, each call builds its own curves from the curve list, checks its numbers before the +//! kernel sees them, runs SM_API's sweep and hands the result over only when it is what was asked +//! for: a closed manifold solid when the ends are capped ([`Error::NotSolid`] otherwise), never a +//! body without faces ([`Error::Empty`]). +//! +//! The screw sweeps are the capi's own: it builds their walls from SMLib's B-spline surfaces, +//! cylinders and face builders (`Stations`, `screw_wall`, `cylinder_piece`), with no SM_API +//! sweep behind them, and solidcore leaves them to the capi (solidcore PR #1326, closed as +//! fork-only; #1162 and #1163 triaged not applicable). So they are ported here. + +use std::f64::consts::{PI, TAU}; + +use solidcore::curve::curve::p3::compute_crvs_normal; +use solidcore::curve::curve::{Curve, CurveKind}; +use solidcore::curve::ellipse::Ellipse; +use solidcore::curve::line::Line; +use solidcore::geom::axis2_placement::Axis2Placement; +use solidcore::geom::extent1d::Extent1d; +use solidcore::geom::tol::{SmallTopoType, USE_DEFAULT, context_zone_tol_3d}; +use solidcore::geom::vector3d::{Point3, Vec3}; +use solidcore::heal::stitch::p1::api_stitch_into_solid; +use solidcore::kernel::Kernel; +use solidcore::nurbs::b_spline_curve::{BSplineCurve, BSplineCurveForm, CanonicalData, CurveCanonical, KnotType}; +use solidcore::nurbs::b_spline_surface::{BSplineSurface, BSplineSurfaceForm, CanonicalSurfaceData}; +use solidcore::nurbs::b_spline_surface_n_lib::p2::OrientType; +use solidcore::primitive::primitive_creation::SweepOptions; +use solidcore::surface::cone::Cone; +use solidcore::surface::surface::Surface; +use solidcore::sweep::api_brep::{ + CornerRefusal, OffsetCornerType, TaperCornerRefusal, TaperExtrude, create_curve_sweep_with_placements, create_linear_sweep, + create_rotational_sweep, create_taper_extrude_with_corner, +}; +use solidcore::sweep::api_surfaces::create_skin_primitive; +use solidcore::topology::brep::p1 as brep_p1; +use solidcore::topology::brep::p1::{ParallelProjectionOptions, create_parallel_projection_curves}; +use solidcore::topology::brep::p2::{ArenaNotifyState, is_manifold_solid}; +use solidcore::topology::brep::p3::new_brep; +use solidcore::topology::brep::p4::stitch_faces; +use solidcore::topology::brep::p5::{StitchAndOrientOptions, stitch_and_orient}; +use solidcore::topology::brep::p7::copy_faces; +use solidcore::topology::brep::p8::{ + FaceBuildEnv, create_face_from_surface, create_faces_with_curves, create_planar_face_with_3d_curves, create_planar_faces_with_3d_curves, +}; +use solidcore::topology::brep::planar_section::{PlanarSectionOptions, SectionOutputs, create_planar_section_curves}; +use solidcore::topology::topology_traverser::Marks; +use solidcore::topology::{Brep, FaceId}; +use solidcore::{EntityRef, SolidError}; + +use super::blend::status; +use super::offset::{face_miss, pick_faces}; +use super::{Body, run, with_body}; +use crate::sweeps::{Affine, Curve as Profile, DraftCorner, Ends, MAX_CURVES, MAX_STATION_CURVES, MAX_STATIONS, SweepFrame}; +use crate::sweeps::{CURVE_MAX_DEGREE, CURVE_MAX_POINTS}; +use crate::{Error, Result}; + +/// The capi's statuses as SolidCraft errors: an operation's own result. +type Out = std::result::Result; + +/// A coordinate no larger than this (mm, 1000 km), so that SMLib's tolerances stay meaningful. +const MAX_COORD: f64 = 1e9; + +/// `SMLIB_FLAT_MAX_LEN`: most reals a curve list may hold. +const FLAT_MAX_LEN: usize = 1 << 27; + +/// `SMLIB_SCREW_MAX_TURNS`. +const SCREW_MAX_TURNS: f64 = 200.0; + +/// `SMLIB_SCREW_MAX_LAW`. +const SCREW_MAX_LAW: usize = 1024; + +/// `coord_ok`. +fn coord_ok(p: &[f64]) -> bool { + p.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// `unit`: a unit vector from `v`, or `None` when it has no usable length. +fn unit(v: [f64; 3]) -> Option { + if !v.iter().all(|x| x.is_finite()) { + return None; + } + let u = v3(v); + let n = u.length(); + (n > 1e-12 && n.is_finite()).then(|| u * (1.0 / n)) +} + +/// An SMLib call's own status passed on (`status(...)` in the capi), else the value. +fn called(r: solidcore::Result) -> Out { + r.map_err(status) +} + +/// `line`. +fn line(start: [f64; 3], end: [f64; 3]) -> Out { + if !coord_ok(&start) || !coord_ok(&end) { + return Err(Error::Argument); + } + let (a, b) = (v3(start), v3(end)); + if !((b - a).length() > 1e-9) { + return Err(Error::Argument); + } + called(Line::create_line_segment(3, a, b, None)).map(Curve::from) +} + +/// `arc`: centre, unit axis, unit reference direction (square to the axis), radius, start and +/// end angles (radians, counter-clockwise about the axis from the reference). +fn arc(k: &Kernel, center: [f64; 3], axis: [f64; 3], reference: [f64; 3], radius: f64, start: f64, end: f64) -> Out { + if !coord_ok(¢er) || ![radius, start, end].iter().all(|x| x.is_finite()) { + return Err(Error::Argument); + } + let (Some(axis), Some(r)) = (unit(axis), unit(reference)) else { return Err(Error::Argument) }; + if axis.dot(r).abs() > 1e-9 { + return Err(Error::Argument); + } + let sweep = end - start; + if !(radius > 1e-9 && radius < MAX_COORD) || start.abs() > 1e6 || !(sweep > 1e-9 && sweep <= TAU * (1.0 + 1e-12)) { + return Err(Error::Argument); + } + // The circle's own parameter starts at the arc's start: SMLib takes intervals in degrees + // within [-360, 360]. + let y = axis.cross(r); + let x0 = r * start.cos() + y * start.sin(); + let y0 = axis.cross(x0); + let frame = Axis2Placement::new(v3(center), x0, y0); + let degrees = Extent1d::from_min_max(0.0, (sweep * 180.0 / PI).min(360.0)); + called(Ellipse::create_canonical_circle(k, &frame, radius, Some(°rees), None)).map(Curve::from) +} + +/// `nurbs`: control points (x, y, z, weight), then points + degree + 1 knots, clamped (end +/// multiplicity degree + 1, inner ones at most degree), non-decreasing. +fn nurbs(degree: usize, points: &[[f64; 4]], knots: &[f64]) -> Out { + let count = points.len(); + if !(1..=CURVE_MAX_DEGREE).contains(°ree) || count < degree + 1 || count > CURVE_MAX_POINTS { + return Err(Error::Argument); + } + let mut ps = Vec::with_capacity(count); + let mut weights = Vec::with_capacity(count); + let mut rational = false; + for p in points { + if !coord_ok(&p[..3]) || !p[3].is_finite() || !(p[3] > 1e-12 && p[3] < 1e12) { + return Err(Error::Argument); + } + ps.push(Vec3::new(p[0], p[1], p[2])); + weights.push(p[3]); + rational = rational || p[3] != 1.0; + } + if knots.len() != count + degree + 1 || !knots.iter().all(|x| x.is_finite()) { + return Err(Error::Argument); + } + let (mut unique, mut mult): (Vec, Vec) = (Vec::new(), Vec::new()); + for (i, &u) in knots.iter().enumerate() { + match (i.checked_sub(1).and_then(|j| knots.get(j)), mult.last_mut()) { + (Some(&prev), _) if u < prev => return Err(Error::Argument), + (Some(&prev), Some(m)) if u == prev => *m += 1, + _ => { + unique.push(u); + mult.push(1); + } + } + } + let (Some(&first), Some(&last), Some(&m0), Some(&m1)) = (unique.first(), unique.last(), mult.first(), mult.last()) else { + return Err(Error::Argument); + }; + if unique.len() < 2 || m0 != degree + 1 || m1 != degree + 1 || !(last - first > 1e-12) { + return Err(Error::Argument); + } + if mult.iter().skip(1).take(mult.len() - 2).any(|&m| m > degree) { + return Err(Error::Argument); + } + let data = CanonicalData { + dim: 3, + degree, + control_points: &ps, + form: BSplineCurveForm::Unspecified, + knot_multiplicities: &mult, + knots: &unique, + knot_type: KnotType::Unspecified, + weights: rational.then_some(weights.as_slice()), + trim: None, + }; + called(BSplineCurve::create_canonical(&data)).map(Curve::from) +} + +/// `parse`: the curves of a curve list. A list of none, more than [`MAX_CURVES`] or more reals +/// than `SMLIB_FLAT_MAX_LEN` is [`Error::Argument`]. +fn parse(k: &Kernel, curves: &[Profile]) -> Out> { + if curves.is_empty() || curves.len() > MAX_CURVES { + return Err(Error::Argument); + } + let mut reals = 0usize; + let mut out = Vec::with_capacity(curves.len()); + for c in curves { + let made = match c { + Profile::Line { start, end } => { + reals += 6; + line(*start, *end)? + } + Profile::Arc { center, axis, reference, radius, start, end } => { + reals += 12; + arc(k, *center, *axis, *reference, *radius, *start, *end)? + } + Profile::Nurbs { degree, points, knots } => { + // `parse` reads the kinds first: at least two points. + if *degree < 1 || *degree > CURVE_MAX_DEGREE || points.len() < 2 || points.len() > CURVE_MAX_POINTS { + return Err(Error::Argument); + } + reals = reals.saturating_add(4 * points.len() + points.len() + degree + 1); + if reals > FLAT_MAX_LEN || knots.len() != points.len() + degree + 1 { + return Err(Error::Argument); + } + nurbs(*degree, points, knots)? + } + }; + if reals > FLAT_MAX_LEN { + return Err(Error::Argument); + } + out.push(made); + } + Ok(out) +} + +/// `finish`: the result must have faces, and be a closed manifold solid when `solid`. +fn finish(b: Brep, solid: bool) -> solidcore::Result> { + if b.face_list().is_empty() { + return Ok(Err(Error::Empty)); + } + if solid && !is_manifold_solid(&b)? { + return Ok(Err(Error::NotSolid)); + } + Ok(Ok(b)) +} + +/// Both ends of `c` (`GetEnds`). +fn ends(k: &Kernel, c: &Curve) -> solidcore::Result<(Point3, Point3)> { + let e = c.ends(k)?; + Ok((e.start, e.end)) +} + +/// `one_loop`: whether the curves, in order, run end to end round one closed loop (within `tol`). +fn one_loop(k: &Kernel, curves: &[Curve], tol: f64) -> solidcore::Result { + let (mut first, mut prev) = (None, None); + for c in curves { + let (a, b) = ends(k, c)?; + match prev { + None => first = Some(a), + Some(p) if (a - p).length() > tol => return Ok(false), + Some(_) => {} + } + prev = Some(b); + } + Ok(matches!((first, prev), (Some(f), Some(p)) if (p - f).length() <= tol)) +} + +/// `FlatArc`: an arc of a curve list as numbers, its frame, radius and angles. +#[derive(Clone, Copy)] +struct FlatArc { + centre: Vec3, + axis: Vec3, + reference: Vec3, + radius: f64, + start: f64, + sweep: f64, +} + +impl FlatArc { + /// `flat_arc`: the arc's numbers, its axis and reference made unit (`parse` has checked + /// that they can be); `None` for a curve that is no arc. + fn of(c: &Profile) -> Option { + let Profile::Arc { center, axis, reference, radius, start, end } = c else { return None }; + Some(FlatArc { + centre: v3(*center), + axis: unit(*axis).unwrap_or_else(|| v3(*axis)), + reference: unit(*reference).unwrap_or_else(|| v3(*reference)), + radius: *radius, + start: *start, + sweep: end - start, + }) + } + + /// The point at angle `t` (radians from the reference, counter-clockwise about the axis). + fn at(&self, t: f64) -> Point3 { + let y = self.axis.cross(self.reference); + self.centre + self.reference * (self.radius * t.cos()) + y * (self.radius * t.sin()) + } + + /// `angle_on`: the angle of `p` on this arc's circle, in its frame (radians, in [0, 2π)). + fn angle_on(&self, p: Point3) -> f64 { + let d = p - self.centre; + let y = self.axis.cross(self.reference); + let t = d.dot(y).atan2(d.dot(self.reference)); + if t < 0.0 { t + TAU } else { t } + } +} + +/// `one_circle`: whether arcs `a` and `b` lie on one circle to `tol`: centres and radii within +/// it, and the axes alike (the same way round) to within it at the rim. +fn one_circle(a: &FlatArc, b: &FlatArc, tol: f64) -> bool { + (a.centre - b.centre).length() <= tol + && (a.radius - b.radius).abs() <= tol + && a.axis.dot(b.axis) > 0.0 + && a.axis.cross(b.axis).length() * a.radius.max(b.radius) <= tol +} + +/// `one_wall_per_circle` (tangency-labs/smlib 7dee48f): the profile `curves` (parsed from +/// `given`) with each run of consecutive arcs on one circle within a loop made one arc, so that +/// the run's wall is one face as a single arc's is: a circle drawn in pieces (split where another +/// sketch curve ends on it) sweeps the one cylinder it lies on, not a face per piece meeting the +/// next along a line that is no edge of the shape. A run that is its whole loop is the full +/// circle, swept as a plain circle is: one periodic face, its seam the one edge it uses twice. +/// The seam goes where a plain circle has it: when the arcs are pieces of one drawn circle (they +/// share its frame, the reference direction their angles are measured from), at that circle's +/// own start, angle 0 of that frame; otherwise at the middle of the run's longest arc (the first +/// of equal ones, in profile order). `tol` is the model's zone tolerance, within which +/// consecutive curves already meet. +fn one_wall_per_circle(k: &Kernel, given: &[Profile], curves: Vec, tol: f64) -> solidcore::Result>> { + let n = curves.len(); + if given.len() != n { + return Ok(Err(Error::Argument)); + } + let arcs: Vec> = given.iter().map(FlatArc::of).collect(); + let (mut head, mut tail) = (Vec::with_capacity(n), Vec::with_capacity(n)); + for c in &curves { + let (a, b) = ends(k, c)?; + head.push(a); + tail.push(b); + } + // Whether the end of curve `i` meets the start of curve `j`; whether arc `j` goes on from + // arc `i`, on its circle. + let meets = |i: usize, j: usize| matches!((tail.get(i), head.get(j)), (Some(t), Some(h)) if (*t - *h).length() <= tol); + let arc_of = |i: usize| arcs.get(i).copied().flatten(); + let joins = |i: usize, j: usize| match (arc_of(i), arc_of(j)) { + (Some(a), Some(b)) => meets(i, j) && one_circle(&a, &b, tol), + _ => false, + }; + let mut taken: Vec> = curves.into_iter().map(Some).collect(); + let mut take = |i: usize| taken.get_mut(i).and_then(Option::take).ok_or(Error::Argument); + let mut out = Vec::with_capacity(n); + let mut first = 0; + while first < n { + // The loop from `first`: its curves run end to end until one ends at its start. + let mut last = first; + while last + 1 < n && !meets(last, first) && meets(last, last + 1) { + last += 1; + } + let len = last - first + 1; + let closed = meets(last, first); + // Whether two of the loop's arcs go on on one circle. + let mut any = false; + let mut j = 0; + while j + 1 < len || (closed && len > 1 && j < len) { + any = any || joins(first + j, first + (j + 1) % len); + j += 1; + } + if !any { + for i in first..=last { + match take(i) { + Ok(c) => out.push(c), + Err(e) => return Ok(Err(e)), + } + } + first = last + 1; + continue; + } + // A run starts where its curve does not go on from the one before it round the loop. + let mut begin = 0; + if closed { + while begin < len && joins(first + (begin + len - 1) % len, first + begin) { + begin += 1; + } + } + if begin == len { + // The whole loop is arcs of one circle: the full circle, its seam at the drawn + // circle's start when the arcs share its frame, else at the middle of the longest arc. + let Some(a) = arc_of(first) else { return Ok(Err(Error::Argument)) }; + let mut one_frame = true; + let mut longest = a; + for i in first..=last { + let Some(b) = arc_of(i) else { return Ok(Err(Error::Argument)) }; + one_frame = one_frame && (b.reference - a.reference).length() * a.radius <= tol; + if b.sweep > longest.sweep { + longest = b; + } + } + let seam = if one_frame { 0.0 } else { a.angle_on(longest.at(longest.start + 0.5 * longest.sweep)) }; + let p = |v: Vec3| [v.x, v.y, v.z]; + match arc(k, p(a.centre), p(a.axis), p(a.reference), a.radius, seam, seam + TAU) { + Ok(c) => out.push(c), + Err(e) => return Ok(Err(e)), + } + } else { + let mut kk = 0; + while kk < len { + let i = first + (begin + kk) % len; + // The arcs i, i + 1, ... round the loop that go on on its circle. + let mut m = 1; + while kk + m < len && joins(first + (begin + kk + m - 1) % len, first + (begin + kk + m) % len) { + m += 1; + } + if m == 1 { + match take(i) { + Ok(c) => out.push(c), + Err(e) => return Ok(Err(e)), + } + } else { + let (Some(a), Some(&h)) = (arc_of(i), head.get(i)) else { return Ok(Err(Error::Argument)) }; + let sweep: f64 = (0..m).filter_map(|j| arc_of(first + (begin + kk + j) % len)).map(|b| b.sweep).sum(); + let start = a.angle_on(h); + let p = |v: Vec3| [v.x, v.y, v.z]; + match arc(k, p(a.centre), p(a.axis), p(a.reference), a.radius, start, start + sweep) { + Ok(c) => out.push(c), + Err(e) => return Ok(Err(e)), + } + } + kk += m; + } + } + first = last + 1; + } + Ok(Ok(out)) +} + +/// Runs a call that makes a new body: the kernel locked, its own status as the capi passes it. +fn making(call: &'static str, f: impl FnOnce(&mut Kernel) -> solidcore::Result>) -> Result { + run(call, f)?.map(Body::new) +} + +/// `smlib_planar_faces`: a sheet of planar faces bounded by the closed `loops` +/// (`SmApiCreatePlanarFaces`: `CreatePlanarFacesWith3DCurves` into a new B-rep's infinite region). +pub(crate) fn planar_faces(loops: &[Profile]) -> Result { + making("smlib_planar_faces", |k| { + let curves = match parse(k, loops) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + let mut b = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + let region = b.infinite_region(); + let made = { + let mut state = ArenaNotifyState::new(&b); + let mut env = state.env(None); + let key_of = env.key_of; + let this_face = |f: FaceId| key_of(EntityRef::Face(f)); + let mut marks = Marks::default(); + let mut fenv = FaceBuildEnv { env: &mut env, marks: &mut marks, this_face: &this_face }; + // (the tolerance is not used: CreatePlanarFacesWith3DCurves takes the B-rep's) + create_planar_faces_with_3d_curves(k, &mut b, region, &curves, 0.01, &mut fenv) + }; + if let Err(e) = made { + return Ok(Err(status(e))); + } + b.refresh_cached_topology(); + finish(b, false) + }) +} + +/// `smlib_extrude`: the planar `profile` extruded `distance` along `direction`, straight +/// (`SmApiCreateLinearSweep`) or drafted (`SmApiCreateTaperExtrude`). +pub(crate) fn extrude(profile: &[Profile], direction: [f64; 3], distance: f64, draft: f64, corner: DraftCorner, cap: bool) -> Result { + if !distance.is_finite() || !(distance > 1e-9 && distance < MAX_COORD) || !draft.is_finite() || draft.abs() >= PI / 2.0 - 1e-6 { + return Err(Error::Argument); + } + making("smlib_extrude", |k| { + let Some(dir) = unit(direction) else { return Ok(Err(Error::Argument)) }; + let curves = match parse(k, profile) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + if draft == 0.0 { + // The fork's capi (7dee48f): arcs of a loop on one circle sweep one wall. + let tol = context_zone_tol_3d(k, None, SmallTopoType::NormalSize); + let walls = match one_wall_per_circle(k, profile, curves, tol)? { + Ok(w) => w, + Err(e) => return Ok(Err(e)), + }; + let refs: Vec> = walls.iter().map(Some).collect(); + return match create_linear_sweep(k, &refs, dir, distance, cap) { + Ok(r) => finish(r, cap), + Err(e) => Ok(Err(status(e))), + }; + } + let refs: Vec> = curves.iter().map(Some).collect(); + // SMLib's draft extrusion takes a single chain of curves, square to the extrusion: the + // height's sign picks the side, matched to `direction` here. + if !one_loop(k, &curves, 1e-6)? { + return Ok(Err(Error::Argument)); + } + let Ok(normal) = compute_crvs_normal(k, &curves) else { return Ok(Err(Error::Argument)) }; + let along = normal.dot(dir); + if along.abs() < 1.0 - 1e-9 { + return Ok(Err(Error::Argument)); + } + let height = if along > 0.0 { distance } else { -distance }; + let angle = draft * 180.0 / PI; + // The fork's corner rules (54148db, e8f23e0): the curvature rule continues each wall as + // itself, the tangent rule a profile of lines and arcs as their tangent planes + // (`fixes.taper_tangent_corner_planes`), and a corner either cannot close is refused, + // with why and where (`SmTaperCornerRefusal`, `pOptRefusedCorner`), as the capi passes it on. + let rule = match corner { + DraftCorner::Curvature => OffsetCornerType::CurveExtension, + DraftCorner::Tangent => OffsetCornerType::LinearExtension, + DraftCorner::Round => OffsetCornerType::FilletCorner, + }; + match create_taper_extrude_with_corner(k, &refs, height, angle, if cap { 3 } else { 0 }, rule) { + Ok(TaperExtrude::Solid(r)) => finish(r, cap), + Ok(TaperExtrude::Refused(r)) => Ok(Err(refused(r))), + Err(e) => Ok(Err(status(e))), + } + }) +} + +/// The capi's statuses for a draft corner whose continued curves do not meet, and for a wall that +/// closes before the far end. +const ERR_CORNER_APART: i32 = -1108; +const ERR_WALL_CLOSES: i32 = -1109; + +/// A refused draft corner as the capi reports it: the reason with the corner's point, +/// [`Error::Corner`] when the point is finite and the reason's own error otherwise. +fn refused(r: CornerRefusal) -> Error { + let (why, otherwise) = match r.reason { + TaperCornerRefusal::Apart => (crate::sweeps::CornerRefusal::Apart, Error::Status(ERR_CORNER_APART)), + TaperCornerRefusal::WallCloses => (crate::sweeps::CornerRefusal::WallCloses, Error::Status(ERR_WALL_CLOSES)), + TaperCornerRefusal::NotExact => (crate::sweeps::CornerRefusal::NotExact, Error::NotExact), + }; + let at = [r.corner.x, r.corner.y, r.corner.z]; + if at.iter().all(|x| x.is_finite()) { Error::Corner { why, at } } else { otherwise } +} + +/// `smlib_revolve`: the planar `profile` turned `angle` radians about the axis through `origin` +/// along `axis` (`SmApiCreateRotationalSweep`). +pub(crate) fn revolve(profile: &[Profile], origin: [f64; 3], axis: [f64; 3], angle: f64, cap: bool) -> Result { + if !coord_ok(&origin) || !angle.is_finite() || !(angle > 1e-9 && angle <= TAU * (1.0 + 1e-12)) { + return Err(Error::Argument); + } + making("smlib_revolve", |k| { + let Some(dir) = unit(axis) else { return Ok(Err(Error::Argument)) }; + let curves = match parse(k, profile) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + let refs: Vec> = curves.iter().map(Some).collect(); + let degrees = (angle * 180.0 / PI).min(360.0); + match create_rotational_sweep(k, &refs, v3(origin), dir, degrees, cap) { + Ok(r) => finish(r, cap), + Err(e) => Ok(Err(status(e))), + } + }) +} + +/// `straight`: whether the path is lines end to end along one direction; then that unit +/// direction and the path's length. +fn straight(k: &Kernel, path: &[Curve]) -> solidcore::Result> { + let (mut dir, mut distance, mut prev) = (None::, 0.0, None::); + for c in path { + if !matches!(c.kind(), CurveKind::Line(_)) { + return Ok(None); + } + let (a, b) = ends(k, c)?; + if prev.is_some_and(|p| (a - p).length() > 1e-9) { + return Ok(None); + } + prev = Some(b); + let d = b - a; + let l = d.length(); + if !(l > 1e-12) { + return Ok(None); + } + let d = d * (1.0 / l); + match dir { + None => dir = Some(d), + Some(u) if d.dot(u) < 1.0 - 1e-12 => return Ok(None), + Some(_) => {} + } + distance += l; + } + Ok(dir.map(|d| (d, distance))) +} + +/// `circular`: whether the path is arcs end to end about one axis; then the centre, the unit axis +/// they turn about counter-clockwise and the total angle (radians). +fn circular(k: &Kernel, given: &[Profile], path: &[Curve]) -> solidcore::Result> { + if given.len() != path.len() || path.is_empty() { + return Ok(None); + } + let (mut first, mut prev, mut angle) = (None::<(Point3, Vec3, f64)>, None::, 0.0); + for (g, c) in given.iter().zip(path) { + let Profile::Arc { center, axis, radius, start, end, .. } = g else { return Ok(None) }; + let (ctr, kv) = (v3(*center), v3(*axis)); + let kv = kv * (1.0 / kv.length()); + let (a, b) = ends(k, c)?; + match first { + None => first = Some((ctr, kv, *radius)), + Some((c0, k0, r0)) => { + if (ctr - c0).length() > 1e-9 + || kv.dot(k0) < 1.0 - 1e-12 + || (radius - r0).abs() > 1e-9 + || prev.is_none_or(|p| (a - p).length() > 1e-9) + { + return Ok(None); + } + } + } + prev = Some(b); + angle += end - start; + } + Ok(first.filter(|_| angle <= TAU * (1.0 + 1e-12)).map(|(c, kv, _)| (c, kv, angle))) +} + +/// A curve's B-spline (`SM_CAST_PTR(SmBSplineCurve, c)`: SMLib's lines and circles are +/// B-splines too); `None` for another kind. +fn bspline(c: &Curve) -> solidcore::Result> { + Ok(match c.kind() { + CurveKind::BSpline(b) => Some(b.clone()), + CurveKind::Line(l) => Some(l.base_with_nurb()?.into_owned()), + CurveKind::Ellipse(e) => Some(e.base().clone()), + _ => None, + }) +} + +/// `joined`: a path of end-to-end curves as one B-spline (`CreateCurveSweep` takes one curve). +fn joined(path: &[Curve]) -> solidcore::Result> { + let mut parts = Vec::with_capacity(path.len()); + for c in path { + let Some(b) = bspline(c)? else { return Ok(Err(Error::Argument)) }; + parts.push(b); + } + if parts.len() == 1 { + return Ok(parts.pop().ok_or(Error::Argument)); + } + Ok(called(BSplineCurve::create_by_joining(&mut parts, None))) +} + +/// `turned`: `v` turned `angle` right-handed about the unit `k` (Rodrigues). +fn turned(v: Vec3, k: Vec3, angle: f64) -> Vec3 { + v * angle.cos() + k.cross(v) * angle.sin() + k * (k.dot(v) * (1.0 - angle.cos())) +} + +/// `put_motion`: a placement as its columns and translation. +fn motion(x: Vec3, y: Vec3, z: Vec3, t: Vec3) -> Affine { + Affine { m: [[x.x, x.y, x.z], [y.x, y.y, y.z], [z.x, z.y, z.z]], t: [t.x, t.y, t.z] } +} + +/// A rigid motion p -> R p + t, R by its columns (`Rigid`). +#[derive(Clone, Copy)] +struct Rigid { + x: Vec3, + y: Vec3, + z: Vec3, + t: Vec3, +} + +impl Rigid { + const IDENTITY: Rigid = + Rigid { x: Vec3::new(1.0, 0.0, 0.0), y: Vec3::new(0.0, 1.0, 0.0), z: Vec3::new(0.0, 0.0, 1.0), t: Vec3::new(0.0, 0.0, 0.0) }; + + /// This motion, then a turn of `angle` right-handed about the unit `k` through `c`. + fn turned_by(&self, c: Vec3, k: Vec3, angle: f64) -> Rigid { + Rigid { x: turned(self.x, k, angle), y: turned(self.y, k, angle), z: turned(self.z, k, angle), t: c + turned(self.t - c, k, angle) } + } + + /// This motion, then a move by `d`. + fn moved_by(&self, d: Vec3) -> Rigid { + Rigid { t: self.t + d, ..*self } + } + + /// As the placement `SmCurve::Transform` takes: the world frame's image. + fn placement(&self) -> Axis2Placement { + Axis2Placement::new(self.t, self.x, self.y) + } + + fn motion(&self) -> Affine { + motion(self.x, self.y, self.z, self.t) + } +} + +/// One segment of a path of lines and arcs (`Segment`): a line from `a` along the unit `dir` for +/// `length`, or an arc turning `angle` (radians) right-handed about the unit `k` through `c`, +/// `length` along. +#[derive(Clone, Copy)] +struct Segment { + arc: bool, + dir: Vec3, + c: Vec3, + k: Vec3, + angle: f64, + length: f64, +} + +impl Segment { + /// The motion `m` carried `s` of the way along (0 <= s <= length). + fn carry(&self, m: &Rigid, s: f64) -> Rigid { + if self.arc { m.turned_by(self.c, self.k, self.angle * s / self.length) } else { m.moved_by(self.dir * s) } + } +} + +/// `segmented`: whether `path` (parsed from `given`) is two or more lines and arcs end to end, +/// each leaving in the direction the one before arrives in, and not closed: then its segments. +fn segmented(k: &Kernel, given: &[Profile], path: &[Curve]) -> solidcore::Result>> { + if given.len() != path.len() || path.len() < 2 { + return Ok(None); + } + let unit = |v: Vec3| v * (1.0 / v.length()); + let mut out = Vec::with_capacity(path.len()); + // The direction the path arrives in at the end of the segment before, and where it ends. + let (mut before, mut first, mut prev) = (None::, None::, None::); + for (g, c) in given.iter().zip(path) { + let (a, b) = ends(k, c)?; + let (seg, leaving, arriving) = match g { + Profile::Line { .. } => { + let length = (b - a).length(); + if !(length > 1e-12) { + return Ok(None); + } + let dir = (b - a) * (1.0 / length); + (Segment { arc: false, dir, c: Vec3::new(0.0, 0.0, 0.0), k: Vec3::new(0.0, 0.0, 0.0), angle: 0.0, length }, dir, dir) + } + Profile::Arc { center, axis, radius, start, end, .. } => { + let (ctr, kv) = (v3(*center), unit(v3(*axis))); + let angle = end - start; + let seg = Segment { arc: true, dir: Vec3::new(0.0, 0.0, 0.0), c: ctr, k: kv, angle, length: radius * angle }; + (seg, unit(kv.cross(a - ctr)), unit(kv.cross(b - ctr))) + } + _ => return Ok(None), + }; + match (first, prev, before) { + (None, ..) => first = Some(a), + (Some(_), Some(p), Some(d)) => { + if (a - p).length() > 1e-9 || leaving.dot(d) < 1.0 - 1e-12 { + return Ok(None); + } + } + _ => return Ok(None), + } + prev = Some(b); + before = Some(arriving); + out.push(seg); + } + match (first, prev) { + (Some(f), Some(p)) if (f - p).length() > 1e-6 => Ok(Some(out)), + _ => Ok(None), + } +} + +/// `carried`: copies of the profile's curves carried by `m`. +fn carried(k: &Kernel, profile: &[Curve], m: &Rigid) -> solidcore::Result> { + let at = m.placement(); + let mut out = Vec::with_capacity(profile.len()); + for c in profile { + let mut copy = c.clone(); + copy.transform(k, &at, None).map_err(|_| SolidError::sm_err("SmCurve::Transform"))?; + out.push(copy); + } + Ok(out) +} + +/// `piecewise`: the profile swept along a path of lines and arcs, turning with it: each segment +/// swept on its own, exactly (a line by SM_API's linear sweep, an arc by its rotational sweep), the +/// profile carried from each to the next, and the walls sewn along the sections they share; with +/// the motions to the first section, the one half-way along and the last. +fn piecewise(k: &mut Kernel, profile: &[Curve], segs: &[Segment], cap: bool) -> solidcore::Result> { + let mut b = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + let mut m = Rigid::IDENTITY; + let mut starts = Vec::with_capacity(segs.len()); + let mut total = 0.0; + for g in segs { + starts.push(m); + total += g.length; + let section = carried(k, profile, &m)?; + let refs: Vec> = section.iter().map(Some).collect(); + let piece = if g.arc { + create_rotational_sweep(k, &refs, g.c, g.k, g.angle * 180.0 / PI, false) + } else { + create_linear_sweep(k, &refs, g.dir, g.length, false) + }; + let mut piece = match piece { + Ok(p) => p, + Err(e) => return Ok(Err(status(e))), + }; + let faces = brep_p1::faces(&piece, None)?; + let mut state = ArenaNotifyState::new(&piece); + state.seed(&b); + let mut env = state.env(None); + let key_of = env.key_of; + let this_face = |f: FaceId| key_of(EntityRef::Face(f)); + match copy_faces(k, &mut piece, &faces, &mut b, false, &this_face, &mut env) { + Ok((_, true)) => {} + Ok((_, false)) => return Ok(Err(status(SolidError::sm_err("CopyFaces")))), + Err(e) => return Ok(Err(status(e))), + } + m = g.carry(&m, g.length); + } + let Some(&start) = starts.first() else { return Ok(Err(Error::Argument)) }; + if cap { + // The caps: the profile where the path starts and where it ends. + for at in [start, m] { + let section = carried(k, profile, &at)?; + let (region, tol) = (b.infinite_region(), b.tolerance()); + if let Err(e) = build_faces(&mut b, |b, fenv| create_planar_faces_with_3d_curves(k, b, region, §ion, tol, fenv)) { + return Ok(Err(status(e))); + } + } + } + if let Err(e) = stitch_and_orient(k, &mut b, &StitchAndOrientOptions::default()) { + return Ok(Err(status(e))); + } + b.refresh_cached_topology(); + let mut half = 0.5 * total; + let mut middle = m; + for (i, (g, from)) in segs.iter().zip(&starts).enumerate() { + if half <= g.length || i + 1 == segs.len() { + middle = g.carry(from, half.min(g.length)); + break; + } + half -= g.length; + } + Ok(Ok((b, [start.motion(), middle.motion(), m.motion()]))) +} + +/// `smlib_sweep_placed`: `profile` swept along `path`, with the rigid motions that placed it at +/// the start, half way and the end. Along a straight path the sweep is SM_API's linear sweep, and +/// turning with arcs about one axis its rotational sweep: both build the walls exactly, as the +/// sweep piece by piece does along lines and arcs that turn with the path ([`piecewise`]). +pub(crate) fn sweep_placed(profile: &[Profile], path: &[Profile], frame: SweepFrame, cap: bool) -> Result<(Body, [Affine; 3])> { + let mut placed = [motion(Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 0.0, 0.0)); 3]; + let body = making("smlib_sweep", |k| { + let (curves, along) = match (parse(k, profile), parse(k, path)) { + (Ok(c), Ok(p)) => (c, p), + (Err(e), _) | (_, Err(e)) => return Ok(Err(e)), + }; + let refs: Vec> = curves.iter().map(Some).collect(); + if let Some((dir, distance)) = straight(k, &along)? { + let r = match create_linear_sweep(k, &refs, dir, distance, cap) { + Ok(r) => r, + Err(e) => return Ok(Err(status(e))), + }; + for (j, m) in placed.iter_mut().enumerate() { + let t = dir * (distance * 0.5 * j as f64); + m.t = [t.x, t.y, t.z]; + } + return finish(r, cap); + } + if frame == SweepFrame::Follow + && let Some((centre, axis, angle)) = circular(k, path, &along)? + { + let degrees = (angle * 180.0 / PI).min(360.0); + let r = match create_rotational_sweep(k, &refs, centre, axis, degrees, cap) { + Ok(r) => r, + Err(e) => return Ok(Err(status(e))), + }; + let len = axis.length(); + if !(len > 0.0) { + return Ok(Err(Error::Argument)); + } + let kv = axis * (1.0 / len); + let turn = degrees * PI / 180.0; + for (j, m) in placed.iter_mut().enumerate() { + let a = turn * 0.5 * j as f64; + let t = centre - turned(centre, kv, a); + let [x, y, z] = [Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)].map(|e| turned(e, kv, a)); + *m = motion(x, y, z, t); + } + return finish(r, cap); + } + // Along lines and arcs, turning with the path, the sweep is exact piece by piece. + if frame == SweepFrame::Follow + && let Some(segs) = segmented(k, path, &along)? + { + return Ok(match piecewise(k, &curves, &segs, cap)? { + Ok((b, motions)) => { + placed = motions; + finish(b, cap)? + } + Err(e) => Err(e), + }); + } + let path_curve = match joined(&along)? { + Ok(b) => Curve::from(b), + Err(e) => return Ok(Err(e)), + }; + // Round a closed path the profile comes back onto itself: the walls close on each other + // there, where caps would lie on top of each other inside the solid. + let (Some(head), Some(tail)) = (along.first(), along.last()) else { return Ok(Err(Error::Argument)) }; + let closed = (ends(k, head)?.0 - ends(k, tail)?.1).length() <= 1e-6; + // `SmApiCreateCurveSweep` with `bProfileAtPathStart` (fork 2dd71a0), so the profile is + // swept where it lies, and the placements it reports (fork 5d3939e). + let options = SweepOptions { + cap_ends: cap && !closed, + translational_sweep: frame == SweepFrame::Translate, + profile_at_path_start: true, + ..SweepOptions::default() + }; + let r = match create_curve_sweep_with_placements(k, &refs, Some(&path_curve), None, None, Some(&options)) { + Ok(r) => r, + Err(e) => return Ok(Err(status(e))), + }; + for (m, p) in placed.iter_mut().zip(&r.placements) { + *m = motion(p.x_axis(), p.y_axis(), p.z_axis(), p.origin()); + } + let mut b = r.sweep.brep; + if closed { + let tol = b.tolerance(); + match stitch_faces(k, &mut b, tol, None, false) { + Ok(s) if s.lamina_edges != 0 => return Ok(Err(Error::NotSolid)), + Ok(_) => b.refresh_cached_topology(), + Err(e) => return Ok(Err(status(e))), + } + } + finish(b, cap) + })?; + Ok((body, placed)) +} + +/// `smlib_loft`: a skin through `sections` (`SmApiCreateSkinPrimitive`), `degree` across them. +pub(crate) fn loft(sections: &[Vec], degree: u32, cap: bool) -> Result { + if sections.len() < 2 || sections.len() > MAX_CURVES || !(1..=3).contains(°ree) { + return Err(Error::Argument); + } + let all: Vec = sections.iter().flatten().cloned().collect(); + making("smlib_loft", |k| { + let curves = match parse(k, &all) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + if sections.iter().any(|s| s.is_empty() || s.len() > MAX_CURVES) { + return Ok(Err(Error::Argument)); + } + let counts: Vec = sections.iter().map(Vec::len).collect(); + let refs: Vec> = curves.iter().map(Some).collect(); + match create_skin_primitive(k, &counts, &refs, degree as usize, cap) { + Ok(r) => finish(r.brep, cap), + Err(e) => Ok(Err(status(e))), + } + }) +} + +/// Each face's identity, for the face builders: their arena identity. +pub(super) fn build_faces(b: &mut Brep, f: impl FnOnce(&mut Brep, &mut FaceBuildEnv<'_, '_>) -> T) -> T { + let mut state = ArenaNotifyState::new(b); + let mut env = state.env(None); + let key_of = env.key_of; + let this_face = |f: FaceId| key_of(EntityRef::Face(f)); + let mut marks = Marks::default(); + let mut fenv = FaceBuildEnv { env: &mut env, marks: &mut marks, this_face: &this_face }; + f(b, &mut fenv) +} + +/// `smlib_loft_to_point`: a pyramid from the planar `section` (one closed loop of lines, in +/// order) to `apex`: the base and a triangle on each line, each `CreatePlanarFaceWith3DCurves` of +/// new lines, then `StitchAndOrient`. +pub(crate) fn loft_to_point(section: &[Profile], apex: [f64; 3]) -> Result { + if !coord_ok(&apex) { + return Err(Error::Argument); + } + making("smlib_loft_to_point", |k| { + let curves = match parse(k, section) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + if curves.len() < 3 || !one_loop(k, &curves, 1e-6)? { + return Ok(Err(Error::Argument)); + } + // The base's corners, each line's start. + let mut corners = Vec::with_capacity(curves.len()); + for c in &curves { + if !matches!(c.kind(), CurveKind::Line(_)) { + return Ok(Err(Error::Argument)); + } + corners.push(ends(k, c)?.0); + } + let Ok(normal) = compute_crvs_normal(k, &curves) else { return Ok(Err(Error::Argument)) }; + let top = v3(apex); + let Some(&c0) = corners.first() else { return Ok(Err(Error::Argument)) }; + let size = corners.iter().map(|q| (*q - c0).length()).fold(0.0, f64::max); + if !((top - c0).dot(normal).abs() > 1e-9 * size.max(1.0)) { + return Ok(Err(Error::Argument)); + } + let mut b = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + let region = b.infinite_region(); + let tol = 1e-6; + let made = build_faces(&mut b, |b, fenv| -> Out<()> { + let mut face = |b: &mut Brep, fenv: &mut FaceBuildEnv<'_, '_>, pts: &[Point3]| -> Out<()> { + let mut edges = Vec::with_capacity(pts.len()); + for (i, &p) in pts.iter().enumerate() { + let q = pts.get((i + 1) % pts.len()).copied().unwrap_or(p); + edges.push(Curve::from(called(Line::create_line_segment(3, p, q, None))?)); + } + called(create_planar_face_with_3d_curves(k, b, region, &edges, tol, fenv)).map(|_| ()) + }; + face(b, fenv, &corners)?; + for (i, &p) in corners.iter().enumerate() { + let q = corners.get((i + 1) % corners.len()).copied().unwrap_or(p); + face(b, fenv, &[p, q, top])?; + } + Ok(()) + }); + if let Err(e) = made { + return Ok(Err(e)); + } + if let Err(e) = stitch_and_orient(k, &mut b, &StitchAndOrientOptions::default()) { + return Ok(Err(status(e))); + } + b.refresh_cached_topology(); + finish(b, true) + }) +} + +/// `maps_ok`: each station map finite, of bounded size and far from singular, its translation +/// within `MAX_COORD`. +fn maps_ok(stations: &[Affine]) -> bool { + stations.iter().all(|s| { + let m = &s.m; + if !m.iter().flatten().chain(&s.t).all(|x| x.is_finite()) || !coord_ok(&s.t) { + return false; + } + let len = |c: &[f64; 3]| (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]).sqrt(); + let (c0, c1, c2) = (len(&m[0]), len(&m[1]), len(&m[2])); + if !(c0 < 1e6 && c1 < 1e6 && c2 < 1e6) { + return false; + } + let det = m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) - m[1][0] * (m[0][1] * m[2][2] - m[2][1] * m[0][2]) + + m[2][0] * (m[0][1] * m[1][2] - m[1][1] * m[0][2]); + det.abs() > 1e-9 * c0 * c1 * c2 + }) +} + +/// `placed`: a copy of `c` as a plain B-spline with every control point carried by `s`, the +/// weights unchanged (an affine map moves a NURBS curve exactly by its control points). +fn placed(c: &BSplineCurve, s: &Affine) -> Out { + let can = called(c.canonical())?; + if can.dim != 3 { + return Err(Error::Status(1001)); + } + let m = &s.m; + let points: Vec = can + .control_points + .iter() + .map(|p| { + Vec3::new( + m[0][0] * p.x + m[1][0] * p.y + m[2][0] * p.z + s.t[0], + m[0][1] * p.x + m[1][1] * p.y + m[2][1] * p.z + s.t[1], + m[0][2] * p.x + m[1][2] * p.y + m[2][2] * p.z + s.t[2], + ) + }) + .collect(); + let data = CanonicalData { + dim: 3, + degree: can.degree, + control_points: &points, + form: BSplineCurveForm::Unspecified, + knot_multiplicities: &can.knot_multiplicities, + knots: &can.knots, + knot_type: KnotType::Unspecified, + weights: (!can.weights.is_empty()).then_some(can.weights.as_slice()), + trim: None, + }; + called(BSplineCurve::create_canonical(&data)).map(Curve::from) +} + +/// `smlib_sweep_stations`: the profile placed by each station, its sections skinned through +/// (`SmApiCreateSkinPrimitive`, cubic across them or as high as their number allows), the ends +/// capped, or joined by `SmApiStitchIntoSolid`. +pub(crate) fn sweep_stations(profile: &[Profile], stations: &[Affine], end: Ends) -> Result { + if !(2..=MAX_STATIONS).contains(&stations.len()) { + return Err(Error::Argument); + } + making("smlib_sweep_stations", |k| { + if !maps_ok(stations) { + return Ok(Err(Error::Argument)); + } + let curves = match parse(k, profile) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + if curves.len() as f64 * stations.len() as f64 > MAX_STATION_CURVES as f64 { + return Ok(Err(Error::Argument)); + } + // Every section is the profile carried by its station's map: the sections share the + // profile's degrees and knots, which the skin interpolates control point by control point. + let mut sections = Vec::with_capacity(curves.len() * stations.len()); + let mut counts = Vec::with_capacity(stations.len()); + for s in stations { + for c in &curves { + let Some(b) = bspline(c)? else { return Ok(Err(Error::Argument)) }; + match placed(&b, s) { + Ok(p) => sections.push(p), + Err(e) => return Ok(Err(e)), + } + } + counts.push(curves.len()); + } + let degree = (stations.len() - 1).min(3); + let refs: Vec> = sections.iter().map(Some).collect(); + let mut r = match create_skin_primitive(k, &counts, &refs, degree, end == Ends::Capped) { + Ok(r) => r.brep, + Err(e) => return Ok(Err(status(e))), + }; + if end == Ends::Joined { + // The last section lies on the first: the walls' ends are glued to their starts. + match api_stitch_into_solid(k, Some(&mut r)) { + Ok(s) if s.produces_a_solid => {} + Ok(_) => return Ok(Err(Error::NotSolid)), + Err(e) => return Ok(Err(status(e))), + } + } + finish(r, end != Ends::Open) + }) +} + +/// The entry checks of `smlib_screw_sweep` and `smlib_screw_sweep_radial`. +fn screw_ok(origin: [f64; 3], pitch: f64, turns: f64, tolerance: f64) -> bool { + coord_ok(&origin) + && pitch.is_finite() + && pitch.abs() > 1e-6 + && pitch.abs() < MAX_COORD + && turns.is_finite() + && (1e-3..=SCREW_MAX_TURNS).contains(&turns) + && tolerance.is_finite() + && (1e-6..1e3).contains(&tolerance) +} + +/// `SMLIB_SCREW_MAX_STATIONS`: most spans of one screw sweep. +const SCREW_MAX_STATIONS: f64 = 12000.0; + +/// `Screw`: the screw motion about the axis through `o` along the unit `k`, rising `pitch` per +/// turn, the section carried by angle a (radians, right-handed about k) and first moved off the +/// axis by offset(a) along `e` (the radial sweep: the unit direction from the axis into the +/// profile's half-plane), offset(a) piecewise linear through (`angles`, `offsets`) and held +/// beyond them. No offsets: none. +struct Screw { + o: Point3, + k: Vec3, + e: Vec3, + pitch: f64, + angles: Vec, + offsets: Vec, +} + +impl Screw { + fn turn(&self, v: Vec3, a: f64) -> Vec3 { + turned(v, self.k, a) + } + + fn lift(&self, a: f64) -> f64 { + self.pitch * a / TAU + } + + fn offset(&self, a: f64) -> f64 { + let (Some(&a0), Some(&o0), Some(&on)) = (self.angles.first(), self.offsets.first(), self.offsets.last()) else { return 0.0 }; + if !(a > a0) { + return o0; + } + for i in 1..self.angles.len() { + let (Some(&ai), Some(&ap), Some(&oi), Some(&op)) = + (self.angles.get(i), self.angles.get(i - 1), self.offsets.get(i), self.offsets.get(i - 1)) + else { + break; + }; + if a <= ai { + return op + (oi - op) * (a - ap) / (ai - ap); + } + } + on + } + + /// The move off the axis at angle a, before the turn. + fn shift(&self, a: f64) -> Vec3 { + if self.offsets.is_empty() { Vec3::new(0.0, 0.0, 0.0) } else { self.e * self.offset(a) } + } + + /// Where p goes at angle a. + fn at(&self, p: Point3, a: f64) -> Point3 { + self.o + self.turn(p - self.o + self.shift(a), a) + self.k * self.lift(a) + } + + /// How far p lies from the axis. + fn reach(&self, p: Point3) -> f64 { + let w = p - self.o; + (w - self.k * w.dot(self.k)).length() + } +} + +/// `Stations`: n spans of h radians each, from t[0] to t[n]. Each span carries the profile round +/// as an exact rational quadratic arc carries a point (its middle control point at the span's +/// middle angle, out by 1 / cos(h / 2), weighted cos(h / 2)), and lifts it by the same rational +/// quadratic of the lifts at the span's ends and middle. +struct Stations { + t: Vec, + /// h / 2. + half: f64, +} + +impl Stations { + fn new(from: f64, to: f64, n: usize) -> Stations { + let t = (0..=n).map(|i| if i == n { to } else { from + (to - from) * i as f64 / n as f64 }).collect(); + Stations { t, half: 0.5 * (to - from) / n as f64 } + } + + fn spans(&self) -> usize { + self.t.len() - 1 + } + + fn first(&self) -> f64 { + self.t.first().copied().unwrap_or(0.0) + } + + fn last(&self) -> f64 { + self.t.last().copied().unwrap_or(0.0) + } + + /// The knots across the stations: double inside (the arcs meet tangent), triple at the ends. + fn knots(&self) -> (Vec, Vec) { + let n = self.t.len(); + (self.t.clone(), (0..n).map(|i| if i == 0 || i + 1 == n { 3 } else { 2 }).collect()) + } + + /// The weight of control point j (of 2 spans + 1) across the stations. + fn weight(&self, j: usize) -> f64 { + if j.is_multiple_of(2) { 1.0 } else { self.half.cos() } + } +} + +/// `lift_error`: how far, in radians of turn, the rational quadratic lift of a span of +/// half-angle `half` leads or lags the true lift, at most (about 0.008 h³). +fn lift_error(half: f64) -> f64 { + let mut worst: f64 = 0.0; + for i in 0..=2048 { + let s = i as f64 / 2048.0; + let lift = half * s / (1.0 - (1.0 - s * s) * (1.0 - half.cos()) / 2.0); + worst = worst.max((lift - 2.0 * ((half / 2.0).tan() * s).atan()).abs()); + } + worst +} + +/// `offset_error`: how far, per unit change of offset across a span of half-angle `half`, the +/// rational quadratic offset strays from the true offset turned with the profile, at most +/// (about h / 8). +fn offset_error(half: f64) -> f64 { + let (c, h) = (half.cos(), 2.0 * half); + let mut worst: f64 = 0.0; + for i in 0..=4096 { + let s = -1.0 + i as f64 / 2048.0; + let t = 0.5 * (s + 1.0); + let (b0, b1, b2) = ((1.0 - t) * (1.0 - t), 2.0 * t * (1.0 - t), t * t); + let den = b0 + c * b1 + b2; + let (ax, ay) = (0.5 * (b2 - b0) * c / den, 0.5 * (b2 + b0) * half.sin() / den); + let phi = 2.0 * ((half / 2.0).tan() * s).atan(); + worst = worst.max((ax - phi / h * phi.cos()).hypot(ay - phi / h * phi.sin())); + } + worst +} + +/// `path`: the control points of p's path under the screw motion over `st` (2 spans + 1). +fn screw_path(m: &Screw, p: Point3, st: &Stations) -> Vec { + let w = p - m.o; + let axial = w.dot(m.k); + let radial = w - m.k * axial; + let mut d = Vec::with_capacity(2 * st.spans() + 1); + for (i, &ti) in st.t.iter().enumerate() { + d.push(m.at(p, ti)); + if let Some(&tn) = st.t.get(i + 1) { + let mid = 0.5 * (ti + tn); + d.push(m.o + m.turn(radial + m.shift(mid), mid) * (1.0 / st.half.cos()) + m.k * (axial + m.lift(mid))); + } + } + d +} + +/// `path_curve`: the path of p over `st` as a curve, exactly as the walls either side have it. +fn path_curve(m: &Screw, p: Point3, st: &Stations) -> Out { + let points = screw_path(m, p, st); + let weights: Vec = (0..points.len()).map(|j| st.weight(j)).collect(); + let (knots, mult) = st.knots(); + let data = CanonicalData { + dim: 3, + degree: 2, + control_points: &points, + form: BSplineCurveForm::Unspecified, + knot_multiplicities: &mult, + knots: &knots, + knot_type: KnotType::Unspecified, + weights: Some(&weights), + trim: None, + }; + called(BSplineCurve::create_canonical(&data)).map(Curve::from) +} + +/// `axial_radius`: the radius of the cylinder a profile line parallel to the axis sweeps (within +/// a thousandth of `tolerance`, at least 1e-6 off it); 0 for any other curve. +fn axial_radius(k: &Kernel, m: &Screw, c: &Curve, tolerance: f64) -> solidcore::Result { + if !matches!(c.kind(), CurveKind::Line(_)) { + return Ok(0.0); + } + let (a, b) = ends(k, c)?; + // How far a point of the line strays from the axis lies between the ends' and the nearest + // point's (the distance is convex along the line). + let (w, d) = (a - m.o, b - a); + let (wp, dp) = (w - m.k * w.dot(m.k), d - m.k * d.dot(m.k)); + let t = if dp.dot(dp) > 0.0 { (-wp.dot(dp) / dp.dot(dp)).clamp(0.0, 1.0) } else { 0.0 }; + let (ra, rb, nearest) = (m.reach(a), m.reach(b), (wp + dp * t).length()); + let (far, near) = (ra.max(rb), nearest.min(ra.min(rb))); + Ok(if near >= 1e-6 && far - near <= 1e-3 * tolerance { 0.5 * (ra + rb) } else { 0.0 }) +} + +/// `cylinder_piece`: the piece of the cylinder of `radius` the profile line from `a` to `b` +/// sweeps over `st`: an exact cylinder about the axis, bounded by the line placed at both ends of +/// the piece and its ends' paths (`CreateFacesWithCurves`). The cylinder's own turn starts a +/// quarter turn before the piece and its height runs past it. +fn cylinder_piece(k: &mut Kernel, b: &mut Brep, m: &Screw, a: Point3, e: Point3, radius: f64, st: &Stations) -> solidcore::Result> { + let (a0, a1) = (st.first(), st.last()); + let w = a - m.o; + let r = w - m.k * w.dot(m.k); + let r = r * (1.0 / r.length()); + let x = m.turn(r, a0 - 0.25 * TAU); + let y = m.k.cross(x); + let (za, zb) = ((a - m.o).dot(m.k), (e - m.o).dot(m.k)); + let z0 = za.min(zb) + m.lift(a0).min(m.lift(a1)); + let z1 = za.max(zb) + m.lift(a0).max(m.lift(a1)); + let margin = 0.25 * (z1 - z0) + 1e-3; + let base = m.o + m.k * (z0 - margin); + let cylinder = Cone::new_cylinder_bounded(base, x, y, radius, 0.0, 360.0, z1 - z0 + 2.0 * margin, false, false, false); + let edge = |at: f64| called(Line::create_line_segment(3, m.at(a, at), m.at(e, at), None)).map(Curve::from); + let lp = || -> Out> { Ok(vec![edge(a0)?, path_curve(m, e, st)?, edge(a1)?, path_curve(m, a, st)?]) }; + let curves = match lp() { + Ok(c) => c, + Err(err) => return Ok(Err(err)), + }; + let orient = [OrientType::Same, OrientType::Same, OrientType::Opposite, OrientType::Opposite]; + let region = b.infinite_region(); + let made = build_faces(b, |b, fenv| { + create_faces_with_curves(k, b, region, &[4], Some(curves.into_iter().map(Some).collect()), &orient, Some(Surface::from(cylinder)), fenv) + }); + Ok(match made { + Ok(f) if f.faces.len() == 1 => Ok(()), + Ok(_) => Err(Error::Status(1001)), + Err(err) => Err(status(err)), + }) +} + +/// `screw_wall`: the wall one profile curve sweeps over `st`: across the curve its NURBS, across +/// the turns each control point's path, the weights the curve's times the arcs'. +fn screw_wall(m: &Screw, c: &CurveCanonical, st: &Stations) -> Out { + let across = 2 * st.spans() + 1; + let mut net = Vec::with_capacity(c.control_points.len() * across); + let mut weights = Vec::with_capacity(net.capacity()); + for (l, &p) in c.control_points.iter().enumerate() { + let w = c.weights.get(l).copied().unwrap_or(1.0); + for (j, q) in screw_path(m, p, st).into_iter().enumerate() { + net.push(q); + weights.push(w * st.weight(j)); + } + } + let (vknots, vmult) = st.knots(); + let data = CanonicalSurfaceData { + u_degree: c.degree, + v_degree: 2, + control_points: &net, + form: BSplineSurfaceForm::Unspecified, + u_multiplicities: &c.knot_multiplicities, + v_multiplicities: &vmult, + u_knots: &c.knots, + v_knots: &vknots, + knot_type: KnotType::Unspecified, + weights: Some(&weights), + uv_domain: None, + }; + called(BSplineSurface::create_canonical(&data)).map(Surface::from) +} + +/// The profile curve `c` carried by the screw motion's placement at angle `a` (`Copy`, then +/// `Transform`): a rigid motion, so a line stays a line and an arc an arc. +fn screw_placed(m: &Screw, c: &Profile, a: f64) -> Profile { + let p = |q: [f64; 3]| { + let r = m.at(v3(q), a); + [r.x, r.y, r.z] + }; + let d = |q: [f64; 3]| { + let r = m.turn(v3(q), a); + [r.x, r.y, r.z] + }; + match c { + Profile::Line { start, end } => Profile::Line { start: p(*start), end: p(*end) }, + Profile::Arc { center, axis, reference, radius, start, end } => { + Profile::Arc { center: p(*center), axis: d(*axis), reference: d(*reference), radius: *radius, start: *start, end: *end } + } + Profile::Nurbs { degree, points, knots } => Profile::Nurbs { + degree: *degree, + points: points + .iter() + .map(|q| { + let r = p([q[0], q[1], q[2]]); + [r[0], r[1], r[2], q[3]] + }) + .collect(), + knots: knots.clone(), + }, + } +} + +/// `screw_sweep` (smlib_sweeps.cpp): the profile's walls built from the screw motion itself, span +/// by span (SM_API's curve sweep carries the profile on its own frame, which along a helix turns +/// it away from the screw motion), lines parallel to the axis as exact cylinder pieces, the caps +/// where the motion starts and ends, all stitched and oriented. +fn screw(k: &mut Kernel, profile: &[Profile], mut m: Screw, turns: f64, tolerance: f64) -> solidcore::Result> { + let curves = match parse(k, profile) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + let mut walls = Vec::with_capacity(curves.len()); + let (mut reach, mut farthest) = (0.0, Vec3::new(0.0, 0.0, 0.0)); + for c in &curves { + let Some(b) = bspline(c)? else { return Ok(Err(Error::Status(1001))) }; + let can = b.canonical()?; + if can.dim != 3 { + return Ok(Err(Error::Status(1001))); + } + for &p in &can.control_points { + let v = p - m.o; + let v = v - m.k * v.dot(m.k); + if v.length() > reach { + reach = v.length(); + farthest = v; + } + } + walls.push(can); + } + if !(reach > 1e-6) { + return Ok(Err(Error::Argument)); + } + // An offset moves the profile within its half-plane: every control point must lie in the one + // the farthest of them spans with the axis, and stay off the axis moved. + if !m.offsets.is_empty() { + let mut nearest = reach; + m.e = farthest * (1.0 / reach); + for p in walls.iter().flat_map(|w| &w.control_points) { + let v = *p - m.o; + let v = v - m.k * v.dot(m.k); + let along = v.dot(m.e); + if !((v - m.e * along).length() <= 1e-9 * (1.0 + reach) && along >= -1e-9 * (1.0 + reach)) { + return Ok(Err(Error::Argument)); + } + nearest = nearest.min(along); + } + if m.offsets.iter().any(|d| !(nearest + d > 1e-6)) { + return Ok(Err(Error::Argument)); + } + } + // Walls of lines parallel to the axis are exact cylinders, which cannot turn on themselves: + // then every wall comes in pieces of half a turn (the last up to an eighth longer). + let mut radius = Vec::with_capacity(curves.len()); + for c in &curves { + radius.push(axial_radius(k, &m, c, tolerance)?); + } + let cylinders = radius.iter().any(|&r| r > 0.0); + // The offset changes slope only at its own angles: they bound pieces too, and a half turn + // within a sixteenth of a turn of one is left out. + let total = TAU * turns; + let mut breaks = vec![0.0]; + breaks.extend(m.angles.iter().copied().filter(|&a| a > 0.0 && a < total)); + let mut half = 0.5 * TAU; + while cylinders && half < total - TAU / 16.0 { + if !m.angles.iter().any(|a| (a - half).abs() < TAU / 16.0) { + breaks.push(half); + } + half += 0.5 * TAU; + } + breaks.push(total); + breaks.sort_by(f64::total_cmp); + let rise = m.pitch.abs() / TAU; + let mut h = (TAU / 8.0).min((tolerance / (0.008 * rise)).cbrt()); + // (bounded: a span this narrow would need more than SMLIB_SCREW_MAX_STATIONS) + let mut guard = 0; + while rise * lift_error(0.5 * h) > tolerance && guard < 10_000 { + h *= 0.99; + guard += 1; + } + let mut pieces = Vec::with_capacity(breaks.len()); + let mut spans = 0.0; + for pair in breaks.windows(2) { + let &[from, to] = pair else { continue }; + // Where the offset changes, its spans are narrower still. + let rate = (m.offset(to) - m.offset(from)).abs() / (to - from); + let mut piece = h; + while rise * lift_error(0.5 * piece) + rate * piece * offset_error(0.5 * piece) > tolerance && piece > 1e-4 { + piece *= 0.99; + } + let n = ((to - from) / piece).ceil(); + spans += n; + if !(spans <= SCREW_MAX_STATIONS) || !(n >= 1.0) { + return Ok(Err(Error::Argument)); + } + pieces.push(Stations::new(from, to, n as usize)); + } + let mut b = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + for st in &pieces { + for (i, (c, wall)) in curves.iter().zip(&walls).enumerate() { + let r = radius.get(i).copied().unwrap_or(0.0); + if r > 0.0 && m.offset(st.first()) == m.offset(st.last()) { + let (a, e) = ends(k, c)?; + if let Err(err) = cylinder_piece(k, &mut b, &m, a, e, r + m.offset(st.first()), st)? { + return Ok(Err(err)); + } + continue; + } + let surface = match screw_wall(&m, wall, st) { + Ok(s) => s, + Err(err) => return Ok(Err(err)), + }; + let domain = surface.natural_uv_domain_with_nurb(k)?; + if let Err(err) = build_faces(&mut b, |b, fenv| create_face_from_surface(k, b, Some(surface), &domain, fenv)) { + return Ok(Err(status(err))); + } + } + } + // The caps: the profile where the motion starts and where it ends, placed exactly. + for a in [0.0, total] { + let placed: Vec = profile.iter().map(|c| screw_placed(&m, c, a)).collect(); + let cap = match parse(k, &placed) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + let (region, tol) = (b.infinite_region(), b.tolerance()); + if let Err(err) = build_faces(&mut b, |b, fenv| create_planar_faces_with_3d_curves(k, b, region, &cap, tol, fenv)) { + return Ok(Err(status(err))); + } + } + if let Err(e) = stitch_and_orient(k, &mut b, &StitchAndOrientOptions::default()) { + return Ok(Err(status(e))); + } + b.refresh_cached_topology(); + finish(b, true) +} + +/// `smlib_screw_sweep` and `smlib_screw_sweep_radial` (`law`: the radial offset law, as +/// (turn, offset) pairs). +pub(crate) fn screw_sweep( + profile: &[Profile], + origin: [f64; 3], + axis: [f64; 3], + pitch: f64, + turns: f64, + law: Option<&[(f64, f64)]>, + tolerance: f64, +) -> Result { + if !screw_ok(origin, pitch, turns, tolerance) { + return Err(Error::Argument); + } + if let Some(law) = law { + if law.is_empty() || law.len() > SCREW_MAX_LAW || !law.iter().all(|(t, o)| t.is_finite() && o.is_finite()) { + return Err(Error::Argument); + } + for (i, (t, o)) in law.iter().enumerate() { + let ascending = i == 0 || law.get(i - 1).is_some_and(|(p, _)| t > p); + if !(*t >= 0.0 && *t <= turns) || !ascending || !(o.abs() < MAX_COORD) { + return Err(Error::Argument); + } + } + } + let call = if law.is_some() { "smlib_screw_sweep_radial" } else { "smlib_screw_sweep" }; + making(call, |k| { + let Some(axis) = unit(axis) else { return Ok(Err(Error::Argument)) }; + let law = law.unwrap_or_default(); + let m = Screw { + o: v3(origin), + k: axis, + e: Vec3::new(0.0, 0.0, 0.0), + pitch, + angles: law.iter().map(|(t, _)| TAU * t).collect(), + offsets: law.iter().map(|(_, o)| *o).collect(), + }; + screw(k, profile, m, turns, tolerance) + }) +} + +/// `put_curve`: `c` as the NURBS it is, with its interval; [`Error::Unsupported`] for a curve that +/// is no B-spline or whose knots are not clamped. +fn put_curve(c: &Curve) -> solidcore::Result> { + let Some(b) = bspline(c)? else { return Ok(Err(Error::Unsupported)) }; + let can = b.canonical()?; + let degree = can.degree; + let count = can.control_points.len(); + let mut knots = Vec::with_capacity(count + degree + 1); + for (&u, &m) in can.knots.iter().zip(&can.knot_multiplicities) { + knots.extend(std::iter::repeat_n(u, m)); + } + let clamped = can.knot_multiplicities.first().is_some_and(|&m| m > degree) && can.knot_multiplicities.last().is_some_and(|&m| m > degree); + if !(1..=CURVE_MAX_DEGREE).contains(°ree) || count < degree + 1 || count > CURVE_MAX_POINTS || knots.len() != count + degree + 1 || !clamped { + return Ok(Err(Error::Unsupported)); + } + let points = can.control_points.iter().enumerate().map(|(i, p)| [p.x, p.y, p.z, can.weights.get(i).copied().unwrap_or(1.0)]).collect(); + let ivl = c.natural_interval(); + Ok(Ok((Profile::Nurbs { degree, points, knots }, [ivl.min(), ivl.max()]))) +} + +/// The pick tolerance and the curve tolerance of `smlib_project_curves` and `smlib_face_section`. +fn tolerances_ok(pick: f64, tolerance: f64) -> bool { + pick.is_finite() && pick > 0.0 && pick < 1e6 && tolerance.is_finite() && (1e-9..1e3).contains(&tolerance) +} + +/// The face of `b` nearest `point` (`smlib_pick::pick_faces` of one point). +fn picked_face(k: &mut Kernel, b: &mut Brep, point: [f64; 3], tol: f64) -> solidcore::Result> { + Ok(match pick_faces(k, b, &[point], tol)? { + Ok(f) => f.first().copied().ok_or(Error::NoMatch { point: 0 }), + Err(m) => Err(face_miss(m)), + }) +} + +/// `smlib_project_curves`: `curves` projected along `direction` onto the face nearest +/// `face_point` (`SmBrep::CreateParallelProjectionCurves` on that face), as NURBS with their +/// intervals; none is [`Error::Empty`]. +pub(crate) fn project_curves( + body: &Body, + face_point: [f64; 3], + pick_tolerance: f64, + curves: &[Profile], + direction: [f64; 3], + tolerance: f64, +) -> Result> { + if !face_point.iter().chain(&direction).all(|x| x.is_finite()) || !tolerances_ok(pick_tolerance, tolerance) { + return Err(Error::Argument); + } + let len = v3(direction).length(); + if !(len > 1e-12) { + return Err(Error::Argument); + } + with_body("smlib_project_curves", body, |k, b| { + let given = match parse(k, curves) { + Ok(c) => c, + Err(e) => return Ok(Err(e)), + }; + let face = match picked_face(k, b, face_point, pick_tolerance)? { + Ok(f) => f, + Err(e) => return Ok(Err(e)), + }; + let dir = v3(direction) * (1.0 / len); + let faces = [face]; + let opts = ParallelProjectionOptions { + approx_tol_3d: Some(tolerance), + subset_faces: Some(&faces), + want_3d: true, + ..ParallelProjectionOptions::default() + }; + let mut out = Vec::new(); + for c in &given { + // curve->GetRootCurve(): a line, an arc and a B-spline are their own root, and + // go in as themselves + if !matches!(c.kind(), CurveKind::BSpline(_) | CurveKind::Line(_) | CurveKind::Ellipse(_)) { + return Ok(Err(Error::Argument)); + } + let made = match create_parallel_projection_curves(k, b, c, dir, &opts) { + Ok(m) => m.curves_3d.unwrap_or_default(), + Err(e) => return Ok(Err(status(e))), + }; + for m in &made { + match put_curve(m)? { + Ok(x) => out.push(x), + Err(e) => return Ok(Err(e)), + } + } + } + Ok(if out.is_empty() { Err(Error::Empty) } else { Ok(out) }) + })? +} + +/// `smlib_face_section`: the section of the face nearest `face_point` by the plane through +/// `plane_point` square to `plane_normal` (`SmBrep::CreatePlanarSectionCurves` over the whole +/// B-rep, keeping the curves of the picked face), as NURBS with their intervals; none is +/// [`Error::Empty`]. +pub(crate) fn face_section( + body: &Body, + face_point: [f64; 3], + pick_tolerance: f64, + plane_point: [f64; 3], + plane_normal: [f64; 3], + tolerance: f64, +) -> Result> { + if !face_point.iter().chain(&plane_point).chain(&plane_normal).all(|x| x.is_finite()) || !tolerances_ok(pick_tolerance, tolerance) { + return Err(Error::Argument); + } + let Some(normal) = unit(plane_normal) else { return Err(Error::Argument) }; + with_body("smlib_face_section", body, |k, b| { + let face = match picked_face(k, b, face_point, pick_tolerance)? { + Ok(f) => f, + Err(e) => return Ok(Err(e)), + }; + // UV curves are asked for, so the classify is forced: an analytic face's intersector + // makes none, and without it the trim drops the whole section (SmBrep.h documents the + // flag for this). The capi leaves it FALSE, so the C++ kernel answers Empty on planes, + // cylinders, cones and spheres (solidcore#1769). + let opts = PlanarSectionOptions { + approx_tol_3d: Some(tolerance), + outputs: SectionOutputs { curves_3d: true, uv_curves: true, faces: true }, + force_uv_classify: true, + ..PlanarSectionOptions::default() + }; + let made = match create_planar_section_curves(k, b, v3(plane_point), normal, &opts) { + Ok(m) => m, + Err(e) => return Ok(Err(status(e))), + }; + let curves = made.curves_3d.unwrap_or_default(); + let faces = made.faces.unwrap_or_default(); + // (each curve's face: without one apiece the picked face's curves are not known) + if faces.len() != curves.len() { + return Ok(Err(Error::Unsupported)); + } + let mut out = Vec::new(); + for (c, &f) in curves.iter().zip(&faces) { + if f == face { + match put_curve(c)? { + Ok(x) => out.push(x), + Err(e) => return Ok(Err(e)), + } + } + } + Ok(if out.is_empty() { Err(Error::Empty) } else { Ok(out) }) + })? +} diff --git a/crates/smlib/src/core/sweep_tests.rs b/crates/smlib/src/core/sweep_tests.rs new file mode 100644 index 000000000..6e98f8f80 --- /dev/null +++ b/crates/smlib/src/core/sweep_tests.rs @@ -0,0 +1,613 @@ +//! Extrusions, revolutions, sweeps, lofts and planar faces on solidcore, against closed forms: +//! every result exports to a record that validates. +//! +//! The profiles are built straight into solidcore curves from the curve lists. + +use std::collections::BTreeMap; +use std::f64::consts::{FRAC_PI_2, PI, TAU}; +use std::sync::mpsc; +use std::time::Duration; + +use super::sweep::{extrude, face_section, loft, loft_to_point, planar_faces, project_curves, revolve, screw_sweep, sweep_placed, sweep_stations}; +use super::{Body, area, bounds, counts, make_box, make_cylinder, to_arrays, volume}; +use crate::Error; +use crate::export::native; +use crate::sweeps::{Affine, CornerRefusal, Curve, DraftCorner, Ends, SweepFrame}; + +/// A case longer than this is a hang. +const TIMEOUT: Duration = Duration::from_secs(300); + +const Z: [f64; 3] = [0.0, 0.0, 1.0]; + +fn line(a: [f64; 3], b: [f64; 3]) -> Curve { + Curve::Line { start: a, end: b } +} + +/// The closed polygon through `pts`. +fn polygon(pts: &[[f64; 3]]) -> Vec { + (0..pts.len()).map(|i| line(pts[i], pts[(i + 1) % pts.len()])).collect() +} + +/// The square of side `s` from `(x, y)` in the plane z = `z`. +fn square(x: f64, y: f64, s: f64, z: f64) -> Vec { + polygon(&[[x, y, z], [x + s, y, z], [x + s, y + s, z], [x, y + s, z]]) +} + +/// The circle of `radius` about `axis` through `center`, from `reference`. +fn circle(center: [f64; 3], axis: [f64; 3], reference: [f64; 3], radius: f64) -> Curve { + Curve::Arc { center, axis, reference, radius, start: 0.0, end: TAU } +} + +/// An arc of radius 5 about the z axis from `reference`, from `start` to `end`. +fn arc5(reference: [f64; 3], start: f64, end: f64) -> Curve { + Curve::Arc { center: [0.0; 3], axis: Z, reference, radius: 5.0, start, end } +} + +/// The circle of radius 5 about the z axis as two half arcs in one frame. +fn halves() -> Vec { + vec![arc5([1.0, 0.0, 0.0], 0.0, PI), arc5([1.0, 0.0, 0.0], PI, TAU)] +} + +/// The circle of radius 5 about the z axis as a quarter from +x and three quarters from +y. +fn two_frames() -> Vec { + vec![arc5([1.0, 0.0, 0.0], 0.0, FRAC_PI_2), arc5([0.0, 1.0, 0.0], 0.0, 3.0 * FRAC_PI_2)] +} + +/// The upper half disc of radius 5 about the z axis, its arc in two quarters. +fn half_disc() -> Vec { + vec![arc5([1.0, 0.0, 0.0], 0.0, FRAC_PI_2), arc5([1.0, 0.0, 0.0], FRAC_PI_2, PI), line([-5.0, 0.0, 0.0], [5.0, 0.0, 0.0])] +} + +/// The rectangle from x = 5 to 8 and z = 0 to 4 in the plane y = 0: area 12, centroid at x 6.5. +fn ring_section() -> Vec { + polygon(&[[5.0, 0.0, 0.0], [8.0, 0.0, 0.0], [8.0, 0.0, 4.0], [5.0, 0.0, 4.0]]) +} + +fn translate(t: [f64; 3]) -> Affine { + Affine { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t } +} + +fn scale_up(s: f64, z: f64) -> Affine { + Affine { m: [[s, 0.0, 0.0], [0.0, s, 0.0], [0.0, 0.0, 1.0]], t: [0.0, 0.0, z] } +} + +#[derive(Clone, Debug)] +enum Op { + PlanarFaces(Vec), + Extrude(Vec, [f64; 3], f64, f64, DraftCorner, bool), + Revolve(Vec, [f64; 3], [f64; 3], f64, bool), + Sweep(Vec, Vec, SweepFrame, bool), + Loft(Vec>, u32, bool), + LoftToPoint(Vec, [f64; 3]), + Stations(Vec, Vec, Ends), + Screw(Vec, [f64; 3], [f64; 3], f64, f64, f64), + /// A screw sweep with a radial law. + ScrewRadial(Vec, [f64; 3], [f64; 3], f64, f64, Vec<(f64, f64)>, f64), +} + +/// What a case must give. +#[derive(Clone, Debug)] +enum Expect { + /// A solid of this volume (relative 1e-9). + Volume(f64), + /// A solid of this volume within this relative error (walls approximated within a tolerance). + About(f64, f64), + /// A sheet of this area (relative 1e-9). + Sheet(f64), + /// A drafted corner refused for this reason, wherever. + Corner(CornerRefusal), +} + +struct Case { + op: Op, + expect: Expect, +} + +/// The frustum of a pyramid or cone: h/3 (A1 + A2 + sqrt(A1 A2)). +fn frustum(a1: f64, a2: f64, h: f64) -> f64 { + h / 3.0 * (a1 + a2 + (a1 * a2).sqrt()) +} + +fn case(name: &str) -> Case { + let c = |op, expect| Case { op, expect }; + let rect = polygon(&[[0.0, 0.0, 0.0], [30.0, 0.0, 0.0], [30.0, 20.0, 0.0], [0.0, 20.0, 0.0]]); + let theta = 5f64.to_radians(); + let disc = || vec![circle([0.0; 3], Z, [1.0, 0.0, 0.0], 5.0)]; + match name { + // A square of 10 with a hole of radius 2: 100 - 4π. + "planar_faces_with_a_hole" => { + let mut loops = square(0.0, 0.0, 10.0, 0.0); + loops.push(circle([5.0, 5.0, 0.0], Z, [1.0, 0.0, 0.0], 2.0)); + c(Op::PlanarFaces(loops), Expect::Sheet(100.0 - 4.0 * PI)) + } + // V = A h. + "extrude_rectangle" => c(Op::Extrude(rect, Z, 10.0, 0.0, DraftCorner::default(), true), Expect::Volume(6000.0)), + // V = π r² h. + "extrude_circle" => c(Op::Extrude(disc(), Z, 10.0, 0.0, DraftCorner::default(), true), Expect::Volume(250.0 * PI)), + // A circle drawn in two halves (split where another sketch curve ends on it), the + // pieces in the circle's own frame: one wall, as the whole circle sweeps (smlib 7dee48f). + "extrude_circle_in_two_halves" => c(Op::Extrude(halves(), Z, 10.0, 0.0, DraftCorner::default(), true), Expect::Volume(250.0 * PI)), + // The same circle as a quarter and three quarters each in its own frame: one wall still, + // its seam in the middle of the longer piece. + "extrude_circle_in_two_frames" => c(Op::Extrude(two_frames(), Z, 10.0, 0.0, DraftCorner::default(), true), Expect::Volume(250.0 * PI)), + // A half disc whose arc is drawn in two quarters, closed by its diameter: the quarters + // sweep one wall. V = π r² h / 2. + "extrude_half_disc_split_arc" => c(Op::Extrude(half_disc(), Z, 10.0, 0.0, DraftCorner::default(), true), Expect::Volume(125.0 * PI)), + // Leaning in by θ, the walls' offsets overlap at the corners and are trimmed where they + // cross, under every rule: the frustum from side 20 to 20 - 2 h tanθ. + "extrude_square_drafted_round" => { + let top = 20.0 - 2.0 * 10.0 * theta.tan(); + c(Op::Extrude(square(0.0, 0.0, 20.0, 0.0), Z, 10.0, theta, DraftCorner::Round, true), Expect::Volume(frustum(400.0, top * top, 10.0))) + } + "extrude_square_drafted_curvature" => { + let top = 20.0 - 2.0 * 10.0 * theta.tan(); + c(Op::Extrude(square(0.0, 0.0, 20.0, 0.0), Z, 10.0, theta, DraftCorner::Curvature, true), Expect::Volume(frustum(400.0, top * top, 10.0))) + } + // No corner: the cone frustum from radius 5 to 5 - h tanθ. + "extrude_circle_drafted" => { + let r2 = 5.0 - 10.0 * theta.tan(); + c(Op::Extrude(disc(), Z, 10.0, theta, DraftCorner::default(), true), Expect::Volume(frustum(PI * 25.0, PI * r2 * r2, 10.0))) + } + // A strip 2 wide leaning in 10° over 10: the long walls meet across the short ones + // (10 tan 10° > 1) before the far end. + "extrude_draft_wall_closes" => c( + Op::Extrude( + polygon(&[[0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [20.0, 2.0, 0.0], [0.0, 2.0, 0.0]]), + Z, + 10.0, + 10f64.to_radians(), + DraftCorner::Curvature, + true, + ), + Expect::Corner(CornerRefusal::WallCloses), + ), + // Pappus: A · θ x̄ = 12 · θ · 6.5. + "revolve_rectangle_full" => c(Op::Revolve(ring_section(), [0.0; 3], Z, TAU, true), Expect::Volume(12.0 * TAU * 6.5)), + "revolve_rectangle_quarter" => c(Op::Revolve(ring_section(), [0.0; 3], Z, FRAC_PI_2, true), Expect::Volume(12.0 * FRAC_PI_2 * 6.5)), + // π r² L, along two lines end to end. + "sweep_circle_straight" => c( + Op::Sweep( + vec![circle([0.0; 3], Z, [1.0, 0.0, 0.0], 2.0)], + vec![line([0.0; 3], [0.0, 0.0, 6.0]), line([0.0, 0.0, 6.0], [0.0, 0.0, 10.0])], + SweepFrame::Follow, + true, + ), + Expect::Volume(PI * 4.0 * 10.0), + ), + // A quarter of a torus: π r² · R θ. + "sweep_circle_along_an_arc" => c( + Op::Sweep( + vec![circle([10.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1.0)], + vec![Curve::Arc { center: [0.0; 3], axis: Z, reference: [1.0, 0.0, 0.0], radius: 10.0, start: 0.0, end: FRAC_PI_2 }], + SweepFrame::Follow, + true, + ), + Expect::Volume(PI * 10.0 * FRAC_PI_2), + ), + // A bent path (a line, then a quarter arc) needs the curve sweep: π r² times the path's + // length, 10 + 10 π/2, within the walls' fit. + "sweep_along_a_bent_path" => c( + Op::Sweep( + vec![circle([0.0; 3], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], 1.0)], + vec![ + line([0.0; 3], [10.0, 0.0, 0.0]), + Curve::Arc { center: [10.0, 10.0, 0.0], axis: Z, reference: [0.0, -1.0, 0.0], radius: 10.0, start: 0.0, end: FRAC_PI_2 }, + ], + SweepFrame::Follow, + true, + ), + Expect::About(PI * (10.0 + 10.0 * FRAC_PI_2), 1e-4), + ), + // A 4 x 3 rectangle round a closed 60 x 40 rounded rectangle (corner radius 8), from the + // middle of its bottom line: no caps, the walls closing on each other. Pappus: A L, with + // A = 12 and L = 2 (44 + 24) + 4 (π/2) 8. + "sweep_round_a_closed_path" => { + let arc = |c: [f64; 3], r: [f64; 3]| Curve::Arc { center: c, axis: Z, reference: r, radius: 8.0, start: 0.0, end: FRAC_PI_2 }; + let path = vec![ + line([0.0, -20.0, 0.0], [22.0, -20.0, 0.0]), + arc([22.0, -12.0, 0.0], [0.0, -1.0, 0.0]), + line([30.0, -12.0, 0.0], [30.0, 12.0, 0.0]), + arc([22.0, 12.0, 0.0], [1.0, 0.0, 0.0]), + line([22.0, 20.0, 0.0], [-22.0, 20.0, 0.0]), + arc([-22.0, 12.0, 0.0], [0.0, 1.0, 0.0]), + line([-30.0, 12.0, 0.0], [-30.0, -12.0, 0.0]), + arc([-22.0, -12.0, 0.0], [-1.0, 0.0, 0.0]), + line([-22.0, -20.0, 0.0], [0.0, -20.0, 0.0]), + ]; + c( + Op::Sweep(polygon(&[[0.0, -22.0, -1.5], [0.0, -18.0, -1.5], [0.0, -18.0, 1.5], [0.0, -22.0, 1.5]]), path, SweepFrame::Follow, true), + Expect::About(12.0 * (2.0 * (44.0 + 24.0) + 16.0 * PI), 1e-4), + ) + } + // The frustum of a square pyramid: side 20 to 10 over 10. + "loft_two_squares" => { + c(Op::Loft(vec![square(0.0, 0.0, 20.0, 0.0), square(5.0, 5.0, 10.0, 10.0)], 1, true), Expect::Volume(frustum(400.0, 100.0, 10.0))) + } + // The cone frustum: radius 5 to 3 over 10. + "loft_two_circles" => c( + Op::Loft(vec![disc(), vec![circle([0.0, 0.0, 10.0], Z, [1.0, 0.0, 0.0], 3.0)]], 1, true), + Expect::Volume(frustum(25.0 * PI, 9.0 * PI, 10.0)), + ), + // A h / 3. + "loft_to_point_pyramid" => c(Op::LoftToPoint(square(0.0, 0.0, 10.0, 0.0), [5.0, 5.0, 6.0]), Expect::Volume(200.0)), + // A square of 2 carried up 10: 40. + "sweep_stations_prism" => c( + Op::Stations( + square(-1.0, -1.0, 2.0, 0.0), + vec![translate([0.0; 3]), translate([0.0, 0.0, 5.0]), translate([0.0, 0.0, 10.0])], + Ends::Capped, + ), + Expect::Volume(40.0), + ), + // Scaled by s = 1 + z/10 on the way: ∫ (2 s)² dz = 4 · 10 · (2³ - 1) / 3. + "sweep_stations_scaled" => c( + Op::Stations(square(-1.0, -1.0, 2.0, 0.0), vec![scale_up(1.0, 0.0), scale_up(1.5, 5.0), scale_up(2.0, 10.0)], Ends::Capped), + Expect::Volume(4.0 * 10.0 * 7.0 / 3.0), + ), + // A square thread 1 x 1 from radius 5 to 6, pitch 2, two turns: Pappus along the screw + // motion (its rise lies in the profile's plane), A · 2π x̄ · turns, the walls within the + // tolerance of the screw surfaces. + "screw_sweep_square_thread" => c( + Op::Screw(polygon(&[[5.0, 0.0, 0.0], [6.0, 0.0, 0.0], [6.0, 0.0, 1.0], [5.0, 0.0, 1.0]]), [0.0; 3], Z, 2.0, 2.0, 1e-5), + Expect::About(TAU * 5.5 * 2.0, 1e-5), + ), + // The same thread moved out by 0 to 1 over its two turns, linearly: Pappus with the + // centroid at 5.5 + t/2, A · 2π · turns · (5.5 + 1/2). + "screw_sweep_radial_taper" => c( + Op::ScrewRadial( + polygon(&[[5.0, 0.0, 0.0], [6.0, 0.0, 0.0], [6.0, 0.0, 1.0], [5.0, 0.0, 1.0]]), + [0.0; 3], + Z, + 2.0, + 2.0, + vec![(0.0, 0.0), (2.0, 1.0)], + 1e-5, + ), + Expect::About(TAU * 2.0 * 6.0, 1e-5), + ), + _ => panic!("{name}"), + } +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +#[derive(Debug, PartialEq)] +struct Measured { + /// The volume of a solid, the area of a sheet. + size: f64, + counts: [usize; 3], + kinds: BTreeMap, +} + +fn kinds(rec: &solidcore_record::brep::Brep) -> BTreeMap { + let mut out = BTreeMap::new(); + for f in &rec.faces { + let v = serde_json::to_value(&f.surface).unwrap(); + *out.entry(v["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1; + } + out +} + +fn on_core(op: &Op) -> crate::Result { + match op { + Op::PlanarFaces(l) => planar_faces(l), + Op::Extrude(p, d, dist, draft, corner, cap) => extrude(p, *d, *dist, *draft, *corner, *cap), + Op::Revolve(p, o, a, angle, cap) => revolve(p, *o, *a, *angle, *cap), + Op::Sweep(p, path, frame, cap) => sweep_placed(p, path, *frame, *cap).map(|(b, _)| b), + Op::Loft(s, d, cap) => loft(s, *d, *cap), + Op::LoftToPoint(s, apex) => loft_to_point(s, *apex), + Op::Stations(p, s, e) => sweep_stations(p, s, *e), + Op::Screw(p, o, a, pitch, turns, tol) => screw_sweep(p, *o, *a, *pitch, *turns, None, *tol), + Op::ScrewRadial(p, o, a, pitch, turns, law, tol) => screw_sweep(p, *o, *a, *pitch, *turns, Some(law), *tol), + } +} + +/// Runs `f` on its own thread: a hang fails the test instead of stopping the run. +fn timed(name: &str, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let _ = tx.send(f()); + }); + match rx.recv_timeout(TIMEOUT) { + Ok(v) => v, + Err(mpsc::RecvTimeoutError::Disconnected) => match worker.join() { + Err(p) => std::panic::resume_unwind(p), + Ok(()) => panic!("{name}: no result"), + }, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("{name}: solidcore hung (no result after {TIMEOUT:?})"), + } +} + +type Got = std::result::Result; + +/// Checks a kernel's result against the case's closed form; what it measured, or its error. +fn judge(name: &str, who: &str, expect: &Expect, got: Got) -> Got { + match (expect, &got) { + (Expect::Corner(why), Err(g)) => { + assert!( + matches!(g, Error::Corner { why: w, at } if w == why && at.iter().all(|x| x.is_finite())), + "{name}: {who} failed otherwise: {g:?}" + ) + } + (Expect::Corner(_), Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {expect:?}"), + (_, Err(g)) => panic!("{name}: {who} failed: {g}"), + (Expect::Volume(v) | Expect::Sheet(v), Ok(m)) => assert!(rel(m.size, *v) < 1e-9, "{name}: {who} {} vs analytic {v}", m.size), + (Expect::About(v, within), Ok(m)) => assert!(rel(m.size, *v) < *within, "{name}: {who} {} vs analytic {v}", m.size), + } + got +} + +fn solidcore_case(name: &'static str) -> Got { + timed(name, move || { + let c = case(name); + let sheet = matches!(c.expect, Expect::Sheet(_)); + let got = on_core(&c.op).map(|body| { + let size = if sheet { area(&body, 1e-8) } else { volume(&body, 1e-8) }.unwrap_or_else(|e| panic!("{name}: size: {e}")); + let n = counts(&body).unwrap(); + let (rec, _) = native(&to_arrays(&body).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + bounds(&body).unwrap(); + Measured { size, counts: n, kinds: kinds(&rec) } + }); + judge(name, "solidcore", &c.expect, got) + }) +} + +macro_rules! cases { + ($($m:ident $([$pign:meta])? $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +// `: ignore = …` cases fail on solidcore. +cases!( + planar_faces_with_a_hole, + extrude_rectangle, + extrude_circle, + extrude_circle_in_two_halves, + extrude_circle_in_two_frames, + extrude_half_disc_split_arc, + extrude_square_drafted_round, + extrude_square_drafted_curvature, + extrude_circle_drafted, + extrude_draft_wall_closes, + revolve_rectangle_full, + revolve_rectangle_quarter, + sweep_circle_straight, + sweep_circle_along_an_arc, + sweep_along_a_bent_path, + sweep_round_a_closed_path, + loft_two_squares, + loft_two_circles, + loft_to_point_pyramid, + sweep_stations_prism, + sweep_stations_scaled, + screw_sweep_square_thread, + screw_sweep_radial_taper, +); + +/// Arcs of a profile on one circle sweep one wall face (tangency-labs/smlib 7dee48f): a circle +/// in two pieces extrudes to the faces, edges and vertices of the whole circle (two caps and one +/// cylinder: 3 faces, 3 edges with the seam, 2 vertices) and the area 2πr² + 2πrh; a half disc +/// whose arc is in two quarters to its diameter's plane wall and one cylinder (4 faces, 6 edges, +/// 4 vertices) and the area πr² + πrh + 2rh. +#[test] +fn arcs_on_one_circle_sweep_one_wall() { + let cases = [ + ("extrude_circle_in_two_halves", [3, 3, 2], 50.0 * PI + 100.0 * PI, true), + ("extrude_circle_in_two_frames", [3, 3, 2], 50.0 * PI + 100.0 * PI, true), + // solidcore sweeps a partial arc, merged or drawn whole, to a surface of extrusion (a + // rational spline in the record) where SMLib made a cylinder: one wall still. + ("extrude_half_disc_split_arc", [4, 6, 4], 25.0 * PI + 50.0 * PI + 100.0, false), + ]; + let walls = |kinds: &BTreeMap| kinds.iter().filter(|(k, _)| !k.starts_with("plane")).map(|(_, n)| *n).sum::(); + for (name, want_counts, want_area, cylinder_on_core) in cases { + let (counts_got, kinds_got, area_got) = timed(name, move || { + let body = on_core(&case(name).op).unwrap_or_else(|e| panic!("{name}: {e}")); + let (rec, _) = native(&to_arrays(&body).unwrap()).unwrap(); + (counts(&body).unwrap(), kinds(&rec), area(&body, 1e-8).unwrap()) + }); + assert_eq!(counts_got, want_counts, "{name}: solidcore faces, edges, vertices"); + assert_eq!(walls(&kinds_got), 1, "{name}: solidcore curved walls {kinds_got:?}"); + if cylinder_on_core { + assert_eq!(kinds_got.get("cylinder"), Some(&1), "{name}: solidcore walls {kinds_got:?}"); + } + assert!(rel(area_got, want_area) < 1e-9, "{name}: solidcore area {area_got} vs analytic {want_area}"); + } +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +fn same_motion(a: &Affine, b: &Affine) -> bool { + a.m.iter().zip(&b.m).all(|(x, y)| near(*x, *y)) && near(a.t, b.t) +} + +/// The motions of a quarter turn about the z axis: by 0, π/4 and π/2. +fn quarter_turn() -> [Affine; 3] { + [0.0, FRAC_PI_2 / 2.0, FRAC_PI_2].map(|a: f64| { + let (c, s) = (a.cos(), a.sin()); + Affine { m: [[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] } + }) +} + +fn straight_up() -> (Vec, Vec) { + (vec![circle([0.0; 3], Z, [1.0, 0.0, 0.0], 2.0)], vec![line([0.0; 3], [0.0, 0.0, 10.0])]) +} + +fn round_z() -> (Vec, Vec) { + ( + vec![circle([10.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1.0)], + vec![Curve::Arc { center: [0.0; 3], axis: Z, reference: [1.0, 0.0, 0.0], radius: 10.0, start: 0.0, end: FRAC_PI_2 }], + ) +} + +fn check_motions(placed: &[Affine; 3], want: &[Affine; 3]) { + assert!(placed.iter().zip(want).all(|(a, b)| same_motion(a, b)), "{placed:?}, expected {want:?}"); +} + +/// `sweep_placed`: along a straight path the profile only moves, by none, half and all of the +/// path; along an arc about z it turns with it about the arc's centre, by none, half and all of +/// the arc's angle. +#[test] +fn sweep_placed_reports_the_motions() { + let (placed, turned) = timed("placed", || { + let (p, up) = straight_up(); + let (q, arc) = round_z(); + (sweep_placed(&p, &up, SweepFrame::Follow, true).unwrap().1, sweep_placed(&q, &arc, SweepFrame::Follow, true).unwrap().1) + }); + check_motions(&placed, &[0.0, 5.0, 10.0].map(|z| translate([0.0, 0.0, z]))); + check_motions(&turned, &quarter_turn()); +} + +/// A diagonal 10 above a 10 x 10 x 10 box's top, projected down onto the top: the same diagonal +/// at z = 10. +#[test] +fn project_a_line_onto_a_face() { + let got = timed("project", || { + let b = make_box([0.0; 3], [10.0; 3]).unwrap(); + project_curves(&b, [5.0, 5.0, 10.0], 0.01, &[line([1.0, 1.0, 20.0], [9.0, 9.0, 20.0])], [0.0, 0.0, -1.0], 1e-6) + }) + .unwrap(); + assert_eq!(got.len(), 1, "{got:?}"); + let Some((Curve::Nurbs { points, .. }, _)) = got.first() else { panic!("{got:?}") }; + let (a, b) = (points[0], points[points.len() - 1]); + let ends = [[a[0], a[1], a[2]], [b[0], b[1], b[2]]]; + let want = [[1.0, 1.0, 10.0], [9.0, 9.0, 10.0]]; + assert!((near(ends[0], want[0]) && near(ends[1], want[1])) || (near(ends[0], want[1]) && near(ends[1], want[0])), "{ends:?}"); +} + +/// A point of a section curve: the rational B-spline at `u` (de Boor on the weighted points). +fn at(c: &Curve, u: f64) -> [f64; 3] { + let Curve::Nurbs { degree, points, knots } = c else { panic!("{c:?}") }; + let p = *degree; + let span = (p..points.len()).rev().find(|&i| knots[i] <= u).unwrap_or(p); + let mut d: Vec<[f64; 4]> = (0..=p).map(|j| points[span - p + j]).map(|[x, y, z, w]| [x * w, y * w, z * w, w]).collect(); + for r in 1..=p { + for j in (r..=p).rev() { + let i = span - p + j; + let den = knots[i + p + 1 - r] - knots[i]; + let a = if den > 0.0 { (u - knots[i]) / den } else { 0.0 }; + let prev = d[j - 1]; + for (x, q) in d[j].iter_mut().zip(prev) { + *x = (1.0 - a) * q + a * *x; + } + } + } + let [x, y, z, w] = d[p]; + [x / w, y / w, z / w] +} + +/// `n + 1` points along each section curve over its interval. +fn samples(got: &[(Curve, [f64; 2])], n: usize) -> Vec> { + got.iter().map(|(c, [a, b])| (0..=n).map(|i| at(c, a + (b - a) * i as f64 / n as f64)).collect()).collect() +} + +/// The length of the section curves, from chords. +fn length(pts: &[Vec<[f64; 3]>]) -> f64 { + pts.iter().flat_map(|p| p.windows(2)).map(|w| (0..3).map(|i| (w[1][i] - w[0][i]).powi(2)).sum::().sqrt()).sum() +} + +/// A loft from a 10 x 10 square at z = 0 to a 6 x 6 one at z = 10 (degree 1): its front wall +/// runs from y = 0 up to y = 2, so the plane z = 5 cuts it in the line from (9, 1, 5) to +/// (1, 1, 5). +fn square_frustum() -> Vec> { + vec![square(0.0, 0.0, 10.0, 0.0), square(2.0, 2.0, 6.0, 10.0)] +} + +#[test] +fn a_lofted_wall_section_is_the_line_across_it() { + let got = timed("section", || { + let b = loft(&square_frustum(), 1, true).unwrap(); + face_section(&b, [5.0, 1.0, 5.0], 0.01, [0.0, 0.0, 5.0], [0.0, 0.0, 1.0], 1e-6) + }) + .unwrap(); + assert_eq!(got.len(), 1, "{got:?}"); + let p = samples(&got, 8); + let ends = [p[0][0], p[0][8]]; + let want = [[9.0, 1.0, 5.0], [1.0, 1.0, 5.0]]; + assert!((near(ends[0], want[0]) && near(ends[1], want[1])) || (near(ends[0], want[1]) && near(ends[1], want[0])), "{ends:?}"); + assert!(p[0].iter().all(|q| (q[1] - 1.0).abs() < 1e-9 && (q[2] - 5.0).abs() < 1e-9), "{p:?}"); +} + +/// The plane z = 3 through the side of a cylinder of radius 5 and height 10 on the xy plane: the +/// circle of radius 5 at z = 3, 2π·5 long. +#[test] +fn a_cylinder_side_section_is_its_circle() { + let got = timed("section", || { + let b = make_cylinder([0.0; 3], 5.0, 10.0).unwrap(); + face_section(&b, [5.0, 0.0, 5.0], 0.01, [0.0, 0.0, 3.0], [0.0, 0.0, 1.0], 1e-7) + }) + .unwrap(); + let p = samples(&got, 2000); + for q in p.iter().flatten() { + assert!(((q[0] * q[0] + q[1] * q[1]).sqrt() - 5.0).abs() < 1e-6 && (q[2] - 3.0).abs() < 1e-9, "{q:?}"); + } + let len = length(&p); + assert!((len - TAU * 5.0).abs() < 1e-4, "{len} against {}", TAU * 5.0); +} + +/// The plane x = 5 through the top of a 10 mm box: the line (5, 0, 10)-(5, 10, 10) across it. +#[test] +fn a_box_top_section_is_the_line_across_it() { + let got = timed("section", || { + let b = make_box([0.0; 3], [10.0; 3]).unwrap(); + face_section(&b, [5.0, 5.0, 10.0], 0.01, [5.0, 5.0, 5.0], [1.0, 0.0, 0.0], 1e-7) + }) + .unwrap(); + let p = samples(&got, 8); + assert!(p.iter().flatten().all(|q| (q[0] - 5.0).abs() < 1e-9 && (q[2] - 10.0).abs() < 1e-9), "{p:?}"); + let len = length(&p); + assert!((len - 10.0).abs() < 1e-6, "{len} against 10"); +} + +/// The capi's argument checks, before any kernel call. +#[test] +fn hostile_arguments_are_refused() { + let sq = square(0.0, 0.0, 1.0, 0.0); + let d = DraftCorner::default(); + for dist in [0.0, -1.0, f64::NAN, 1e10] { + assert_eq!(extrude(&sq, Z, dist, 0.0, d, true).err(), Some(Error::Argument), "distance {dist}"); + } + assert_eq!(extrude(&sq, Z, 1.0, FRAC_PI_2, d, true).err(), Some(Error::Argument), "a right-angled draft"); + assert_eq!(extrude(&sq, [0.0; 3], 1.0, 0.0, d, true).err(), Some(Error::Argument), "no direction"); + assert_eq!(extrude(&[], Z, 1.0, 0.0, d, true).err(), Some(Error::Argument), "no profile"); + assert_eq!(extrude(&[line([0.0; 3], [0.0; 3])], Z, 1.0, 0.0, d, true).err(), Some(Error::Argument), "a point"); + assert_eq!(extrude(&[line([f64::NAN; 3], [1.0; 3])], Z, 1.0, 0.0, d, true).err(), Some(Error::Argument)); + // A drafted profile is one loop, square to the direction. + assert_eq!(extrude(&sq[..3], Z, 1.0, 0.1, d, true).err(), Some(Error::Argument), "an open profile"); + assert_eq!(extrude(&sq, [1.0, 0.0, 0.0], 1.0, 0.1, d, true).err(), Some(Error::Argument), "along the profile"); + let bad_arc = Curve::Arc { center: [0.0; 3], axis: Z, reference: Z, radius: 1.0, start: 0.0, end: 1.0 }; + assert_eq!(extrude(&[bad_arc], Z, 1.0, 0.0, d, false).err(), Some(Error::Argument), "reference along the axis"); + let bad_nurbs = Curve::Nurbs { degree: 1, points: vec![[0.0; 4], [1.0, 0.0, 0.0, 1.0]], knots: vec![0.0, 0.0, 1.0, 1.0] }; + assert_eq!(extrude(&[bad_nurbs], Z, 1.0, 0.0, d, false).err(), Some(Error::Argument), "a zero weight"); + let unclamped = Curve::Nurbs { degree: 1, points: vec![[0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0]], knots: vec![0.0, 0.5, 1.0, 1.0] }; + assert_eq!(extrude(&[unclamped], Z, 1.0, 0.0, d, false).err(), Some(Error::Argument), "unclamped knots"); + assert_eq!(revolve(&sq, [0.0; 3], Z, 0.0, true).err(), Some(Error::Argument), "no angle"); + assert_eq!(revolve(&sq, [0.0; 3], Z, 7.0, true).err(), Some(Error::Argument), "more than a turn"); + assert_eq!(revolve(&sq, [f64::INFINITY; 3], Z, 1.0, true).err(), Some(Error::Argument)); + assert_eq!(loft(std::slice::from_ref(&sq), 1, true).err(), Some(Error::Argument), "one section"); + assert_eq!(loft(&[sq.clone(), sq.clone()], 4, true).err(), Some(Error::Argument), "degree 4"); + assert_eq!(loft_to_point(&sq, [0.5, 0.5, 0.0]).err(), Some(Error::Argument), "apex in the base's plane"); + assert_eq!(loft_to_point(&[circle([0.0; 3], Z, [1.0, 0.0, 0.0], 1.0)], Z).err(), Some(Error::Argument), "not lines"); + let flat = Affine { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], t: [0.0; 3] }; + assert_eq!(sweep_stations(&sq, &[translate([0.0; 3]), flat], Ends::Capped).err(), Some(Error::Argument), "a singular map"); + assert_eq!(sweep_stations(&sq, &[translate([0.0; 3])], Ends::Capped).err(), Some(Error::Argument), "one station"); + assert_eq!(screw_sweep(&sq, [0.0; 3], Z, 0.0, 1.0, None, 1e-3).err(), Some(Error::Argument), "no pitch"); + assert_eq!(screw_sweep(&sq, [0.0; 3], Z, 1.0, 300.0, None, 1e-3).err(), Some(Error::Argument), "too many turns"); + assert_eq!(screw_sweep(&sq, [0.0; 3], Z, 1.0, 1.0, Some(&[(0.5, 0.0), (0.2, 0.0)]), 1e-3).err(), Some(Error::Argument), "a law going back"); + assert_eq!(screw_sweep(&sq, [0.0; 3], Z, 1.0, 1.0, Some(&[]), 1e-3).err(), Some(Error::Argument), "an empty law"); + let b = make_box([0.0; 3], [1.0; 3]).unwrap(); + assert_eq!(project_curves(&b, [0.5; 3], 0.01, &sq, [0.0; 3], 1e-6).err(), Some(Error::Argument), "no direction"); + assert_eq!(project_curves(&b, [0.5; 3], 0.0, &sq, Z, 1e-6).err(), Some(Error::Argument), "no pick tolerance"); + assert_eq!(face_section(&b, [0.5; 3], 0.01, [0.5; 3], [0.0; 3], 1e-6).err(), Some(Error::Argument), "no plane normal"); +} diff --git a/crates/smlib/src/core/transform.rs b/crates/smlib/src/core/transform.rs new file mode 100644 index 000000000..2c28340a8 --- /dev/null +++ b/crates/smlib/src/core/transform.rs @@ -0,0 +1,32 @@ +//! Copies and affine transforms on solidcore: the C API's `smlib_brep_copy` and +//! `smlib_brep_transform`, ported from the fork's `capi/src/smlib_c.cpp`. +//! +//! As there, a transform works on a copy of its body (`SmApiBrepCopy`), which +//! `SmBrep::Transform(double[4][4], bScaleTol)` (solidcore's `transform_matrix`, solidcore#1570) +//! then moves in place, tolerances scaling with the model. The matrix is the capi's: rows 0-2 the +//! images of x, y and z, row 3 the translation (row-vector convention, `p' = p·A + t`); the +//! fourth column is not read. + +use super::Body; +use super::blend::{on_copy, status}; +use crate::{Error, Result}; +use solidcore::topology::brep::mirror::transform_matrix; + +/// `smlib_brep_copy`: `SmApiBrepCopy`. +pub(crate) fn copy(body: &Body) -> Result { + on_copy("SmApiBrepCopy", body, |_, b| Ok(Ok(b))) +} + +/// `smlib_brep_transform`: `SmBrep::Transform(matrix, TRUE)` on a copy of `body`. Every entry of +/// the matrix must be finite (`SMLIB_ERR_ARG`). +pub(crate) fn transform(body: &Body, matrix: &[[f64; 4]; 4]) -> Result { + if !matrix.iter().flatten().all(|x| x.is_finite()) { + return Err(Error::Argument); + } + on_copy("SmBrep::Transform", body, |k, mut b| { + Ok(match transform_matrix(k, &mut b, matrix, true) { + Ok(()) => Ok(b), + Err(e) => Err(status(e)), + }) + }) +} diff --git a/crates/smlib/src/core/transform_tests.rs b/crates/smlib/src/core/transform_tests.rs new file mode 100644 index 000000000..ee6c2754f --- /dev/null +++ b/crates/smlib/src/core/transform_tests.rs @@ -0,0 +1,240 @@ +//! Copies and affine transforms on solidcore, against closed forms: every result keeps its counts, +//! its volume scales by the matrix's |det|, its bounds are the moved box's, and it exports to a +//! record that validates. + +use std::collections::BTreeMap; +use std::f64::consts::PI; + +use super::transform::{copy, transform}; +use super::{Body, bounds, counts, make_box, make_cylinder, to_arrays, volume}; +use crate::Error; +use crate::export::native; + +/// The identity, as the capi reads a matrix: rows 0-2 the images of x, y and z, row 3 the move. +const ID: [[f64; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + +#[derive(Clone, Copy, Debug)] +enum Shape { + /// A box from its lower corner. + Box([f64; 3], [f64; 3]), + /// A cylinder about +Z from its base centre. + Cylinder([f64; 3], f64, f64), +} + +impl Shape { + fn core(self) -> Body { + match self { + Shape::Box(o, s) => make_box(o, s).unwrap(), + Shape::Cylinder(o, r, h) => make_cylinder(o, r, h).unwrap(), + } + } + + fn volume(self) -> f64 { + match self { + Shape::Box(_, s) => s[0] * s[1] * s[2], + Shape::Cylinder(_, r, h) => PI * r * r * h, + } + } + + fn counts(self) -> [usize; 3] { + match self { + Shape::Box(..) => [6, 12, 8], + Shape::Cylinder(..) => [3, 3, 2], + } + } + + /// The corners of its bounding box. + fn corners(self) -> Vec<[f64; 3]> { + let (lo, hi) = match self { + Shape::Box(o, s) => (o, [o[0] + s[0], o[1] + s[1], o[2] + s[2]]), + Shape::Cylinder(o, r, h) => ([o[0] - r, o[1] - r, o[2]], [o[0] + r, o[1] + r, o[2] + h]), + }; + (0..8) + .map(|k| [if k & 1 == 0 { lo[0] } else { hi[0] }, if k & 2 == 0 { lo[1] } else { hi[1] }, if k & 4 == 0 { lo[2] } else { hi[2] }]) + .collect() + } +} + +/// `p·A + t`. +fn apply(m: &[[f64; 4]; 4], p: [f64; 3]) -> [f64; 3] { + [0, 1, 2].map(|j| p[0] * m[0][j] + p[1] * m[1][j] + p[2] * m[2][j] + m[3][j]) +} + +fn det(m: &[[f64; 4]; 4]) -> f64 { + m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) +} + +fn rotation_z(a: f64) -> [[f64; 4]; 4] { + let (s, c) = a.sin_cos(); + [[c, s, 0.0, 0.0], [-s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] +} + +struct Case { + shape: Shape, + matrix: [[f64; 4]; 4], + /// `None`: the closed form (volume times |det|, the moved box, the same counts). + fails: Option, +} + +const BOX: Shape = Shape::Box([1.0, 2.0, 3.0], [10.0, 20.0, 30.0]); +const CYL: Shape = Shape::Cylinder([0.0, 0.0, 0.0], 5.0, 12.0); + +fn case(name: &str) -> Case { + let ok = |shape, matrix| Case { shape, matrix, fails: None }; + let mut moved = ID; + moved[3] = [5.0, -7.0, 11.0, 1.0]; + match name { + "identity" => ok(BOX, ID), + "translation" => ok(BOX, moved), + "rotation_about_z" => ok(BOX, rotation_z(PI / 2.0)), + "uniform_scale" => ok(BOX, [[2.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 0.0, 2.0, 0.0], [1.0, 1.0, 1.0, 1.0]]), + "mirror_in_x" => ok(BOX, [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0; 4]]), + "non_uniform_scale" => ok(BOX, [[2.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0], [0.0; 4]]), + "shear" => ok(BOX, [[1.0, 0.5, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [2.0, 3.0, 4.0, 1.0]]), + "cylinder_moved" => ok(CYL, moved), + "cylinder_rotated" => ok(CYL, rotation_z(0.3)), + "cylinder_mirrored" => ok(CYL, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0; 4]]), + "cylinder_scaled" => ok(CYL, [[3.0, 0.0, 0.0, 0.0], [0.0, 3.0, 0.0, 0.0], [0.0, 0.0, 3.0, 0.0], [0.0; 4]]), + _ => panic!("no case {name}"), + } +} + +#[derive(Debug, PartialEq)] +struct Measured { + volume: f64, + bounds: ([f64; 3], [f64; 3]), + counts: [usize; 3], + kinds: BTreeMap, +} + +type Got = std::result::Result; + +fn kinds(rec: &solidcore_record::brep::Brep) -> BTreeMap { + let mut out = BTreeMap::new(); + for f in &rec.faces { + let v = serde_json::to_value(&f.surface).unwrap(); + *out.entry(v["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1; + } + out +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +/// The moved shape's bounding box: a box's moved corners bound it exactly; a cylinder's only for +/// the matrices here (a rotation about its axis, a move, a mirror in z, a uniform scale), whose +/// moved circle's box is the moved square's turned back to the axes. +fn expected_bounds(c: &Case) -> ([f64; 3], [f64; 3]) { + let pts: Vec<[f64; 3]> = match c.shape { + Shape::Cylinder(o, r, h) => { + let s = (c.matrix[0][0] * c.matrix[0][0] + c.matrix[0][1] * c.matrix[0][1]).sqrt(); + let centre = [apply(&c.matrix, o), apply(&c.matrix, [o[0], o[1], o[2] + h])]; + centre.iter().flat_map(|p| [[p[0] - r * s, p[1] - r * s, p[2]], [p[0] + r * s, p[1] + r * s, p[2]]]).collect() + } + s => s.corners().into_iter().map(|p| apply(&c.matrix, p)).collect(), + }; + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for p in pts { + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + (lo, hi) +} + +fn judge(name: &str, who: &str, got: Got) -> Got { + let c = case(name); + match (&c.fails, &got) { + (Some(e), Err(g)) => assert_eq!(g, e, "{name}: {who} failed otherwise"), + (Some(e), Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"), + (None, Err(g)) => panic!("{name}: {who} failed: {g}"), + (None, Ok(m)) => { + let v = c.shape.volume() * det(&c.matrix).abs(); + assert!(rel(m.volume, v) < 1e-9, "{name}: {who} volume {} vs analytic {v}", m.volume); + assert_eq!(m.counts, c.shape.counts(), "{name}: {who} counts"); + let (lo, hi) = expected_bounds(&c); + let near = |a: [f64; 3], b: [f64; 3]| a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6); + assert!(near(m.bounds.0, lo) && near(m.bounds.1, hi), "{name}: {who} bounds {:?}, expected {lo:?} {hi:?}", m.bounds); + } + } + got +} + +fn solidcore_case(name: &str) -> Got { + let c = case(name); + let got = transform(&c.shape.core(), &c.matrix).map(|b| { + let (rec, _) = native(&to_arrays(&b).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + Measured { volume: volume(&b, 1e-8).unwrap(), bounds: bounds(&b).unwrap(), counts: counts(&b).unwrap(), kinds: kinds(&rec) } + }); + judge(name, "solidcore", got) +} + +macro_rules! cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +cases!( + identity, + translation, + rotation_about_z, + uniform_scale, + mirror_in_x, + non_uniform_scale, + shear, + cylinder_moved, + cylinder_rotated, + cylinder_mirrored, + cylinder_scaled, +); + +/// The capi's argument check, before any kernel call: every entry finite. +#[test] +fn hostile_matrices_are_refused() { + let b = BOX.core(); + for (i, j) in [(0, 0), (1, 2), (3, 1), (2, 3)] { + for x in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut m = ID; + m[i][j] = x; + assert_eq!(transform(&b, &m).err(), Some(Error::Argument), "m[{i}][{j}] = {x}"); + } + } +} + +/// A singular or huge matrix never panics: it gives a body or an error. +#[test] +fn degenerate_matrices_do_not_crash() { + let b = BOX.core(); + let zero = [[0.0; 4]; 4]; + let flat = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0; 4]]; + let huge = [[1e300, 0.0, 0.0, 0.0], [0.0, 1e300, 0.0, 0.0], [0.0, 0.0, 1e300, 0.0], [0.0; 4]]; + for m in [zero, flat, huge] { + let _ = transform(&b, &m); + } +} + +/// The body moved, and the body copied, are never changed. +#[test] +fn the_body_stays_as_it_was() { + let b = BOX.core(); + let moved = transform(&b, &rotation_z(1.0)).unwrap(); + let c = copy(&b).unwrap(); + drop(moved); + for x in [&b, &c] { + assert_eq!(counts(x).unwrap(), [6, 12, 8]); + assert!(rel(volume(x, 1e-8).unwrap(), 6000.0) < 1e-12); + assert_eq!(bounds(x).unwrap(), ([1.0, 2.0, 3.0], [11.0, 22.0, 33.0])); + } +} diff --git a/crates/smlib/src/core/trim.rs b/crates/smlib/src/core/trim.rs new file mode 100644 index 000000000..8d9d8d44b --- /dev/null +++ b/crates/smlib/src/core/trim.rs @@ -0,0 +1,854 @@ +//! Untrim and extend on solidcore: the C API's `smlib_untrim_face` and `smlib_extend_sheet`, +//! ported from the fork's `capi/src/smlib_untrim.cpp` (`face_at`, `loop_distance`, +//! `copy_attributes`, `analytic`, `span_of`, `pieces_of`, `is_disc`, `rebuild_hole`) and +//! `capi/src/smlib_extend.cpp` (`on_side`, `eval`, `nearest_edge`, `is_boundary`, `side_edge`, +//! `across`, `cone_continued`, `same_patch`). +//! +//! A face restored towards its surface. Picked inner loops (holes) are taken away with +//! `SmFace::DeleteInnerLoop` on a copy where they are lamina; the outer boundary goes back to a +//! parameter box of the surface (`SmBrep::CreateFaceFromSurface`), and the holes kept are rebuilt +//! in that face from their own edges' curves and intervals (`MakeVertexLoop`, `MakeEdgeInFace`: +//! closing a loop splits off the face inside it, which is deleted). The new face and the rebuilt +//! edges take the attributes of the face and edges they stand for, so the history tags carry +//! through. +//! +//! A sheet is extended by SMLib's extension of its surface (`CreateExtendedSurface`: its end +//! spans continued, or a G1 or G2 run-off), the distance asked of it corrected until the +//! extension measures the distance across the side's middle; `CopyAndAddAnalytics` gives the +//! result back its analytic kind, and a cone or cylinder continued naturally stays the analytic +//! widened. The new face and each of its sides take the attributes of the face and side they +//! continue. +//! +//! An untrim of a face out of its body (`in_place` false) copies the face into a body of its own +//! through `SmBrep::CopyFaces` with the merge (solidcore#1872), which keeps its attributes. + +use std::sync::PoisonError; + +use solidcore::EntityRef; +use solidcore::curve::curve::Curve; +use solidcore::geom::extent2d::Extent2d; +use solidcore::geom::geom_utility::p2::ContinuityType; +use solidcore::geom::object::Shape; +use solidcore::geom::tol::USE_DEFAULT; +use solidcore::geom::vector2d::Point2; +use solidcore::geom::vector3d::{Point3, Vec3}; +use solidcore::kernel::Kernel; +use solidcore::nurbs::b_spline_surface::p1::SurfParamType; +use solidcore::nurbs::b_spline_surface_n_lib::p2::EvaluateFlags; +use solidcore::nurbs::b_spline_surface_n_lib::p2::OrientType; +use solidcore::query::api_queries::{edge_closest_point, face_closest_point_in_shape, face_internal_point}; +use solidcore::query::brep::{BrepQuery, LiveBrepObjects}; +use solidcore::surface::cone::p1::Cone; +use solidcore::surface::surface::Surface; +use solidcore::surface::surface::SurfaceKind; +use solidcore::topology::brep::p1 as brep_p1; +use solidcore::topology::brep::p2::{CopyNotifyState, copy_source_ref}; +use solidcore::topology::brep::p3::{DeleteFaceOptions, delete_face, new_brep, with_kernel_callbacks}; +use solidcore::topology::brep::p5::{EdgeInFace, make_edge_in_face}; +use solidcore::topology::brep::p7::copy_faces_from; +use solidcore::topology::brep::p8::create_face_from_surface; +use solidcore::topology::brep::p9::make_vertex_loop; +use solidcore::topology::edgeuse::p1 as eu_p1; +use solidcore::topology::edgeuse::p3::get_or_create_uv_trim_curve; +use solidcore::topology::face::{p1 as face_p1, p2 as face_p2, p4 as face_p4}; +use solidcore::topology::loopuse::{loop_edges, loop_loopuses, notify_ref}; +use solidcore::topology::topology_traverser::Marks; +use solidcore::topology::{Brep, BrepId, EdgeId, FaceId, LoopId, edge}; + +use super::blend::{p3, status}; +use super::sweep::build_faces; +use super::{Body, answer}; +use crate::trim::Continuation; +use crate::{Error, Result}; +use solidcore::topology::brep::p3::brep_copy; + +/// `MAX_HOLE_POINTS`. +const MAX_HOLE_POINTS: usize = 10_000; + +/// `SMLIB_ERR_EXCEPTION`'s stand-in: a rebuilt hole that did not close as the capi expects. +fn hole_refused() -> Error { + Error::Exception +} + +/// The capi's statuses as SolidCraft errors: an operation's own result. +type Out = std::result::Result; + +const ONE: BrepId = BrepId::from_index(0); + +/// `face_at`: the face of `b` nearest `p`, within `tol` (`SmApiFaceClosestPoint`; a face whose +/// query fails is skipped). +pub(super) fn face_at(k: &mut Kernel, b: &mut Brep, p: Point3, tol: f64) -> solidcore::Result> { + let all = brep_p1::faces(b, None)?; + let mut shapes = Vec::with_capacity(all.len()); + for &f in &all { + shapes.push(answer(Shape::new(k, &(ONE, &*b), &[], &[(ONE, f)], &[], &[]))?); + } + let query = BrepQuery::of_brep(b); + let identity = query.effective_identity(); + let objects = LiveBrepObjects::new(b, &identity, None)?; + let (mut best, mut d0) = (None, f64::INFINITY); + for (&f, shape) in all.iter().zip(&shapes) { + let Some(shape) = shape else { continue }; + if let Some(c) = answer(face_closest_point_in_shape(k, shape, &objects, (ONE, f), p))? + && c.distance.is_finite() + && c.distance < d0 + { + d0 = c.distance; + best = Some(f); + } + } + Ok(best.filter(|_| d0 <= tol)) +} + +/// `loop_distance`: the distance from `p` to the nearest edge of loop `l`. +fn loop_distance(k: &Kernel, b: &Brep, l: LoopId, p: Point3) -> solidcore::Result { + let mut best = f64::INFINITY; + for e in loop_edges(b, l)?.into_iter().flatten() { + if let Some(c) = answer(edge_closest_point(k, b, e, p))? + && c.closest.distance.is_finite() + { + best = best.min(c.closest.distance); + } + } + Ok(best) +} + +/// `copy_attributes`: `to` (in `into`) takes a copy of each attribute of `from` (in `src`). +fn copy_attributes(src: &Brep, from: EntityRef, into: &mut Brep, to: EntityRef) -> solidcore::Result<()> { + let copies: Vec<_> = src.entity_attributes(from).into_iter().map(|(_, a)| a.make_copy()).collect(); + for a in copies { + into.add_attribute(to, a)?; + } + Ok(()) +} + +/// [`copy_attributes`] within one body. +fn copy_attributes_within(b: &mut Brep, from: EntityRef, to: EntityRef) -> solidcore::Result<()> { + let copies: Vec<_> = b.entity_attributes(from).into_iter().map(|(_, a)| a.make_copy()).collect(); + for a in copies { + b.add_attribute(to, a)?; + } + Ok(()) +} + +/// `span_of`: the box of the face's outer loop in the surface's parameters, the union of the +/// tight boxes of its edgeuses' UV trim curves (made where the face has none attached yet). +fn span_of(k: &Kernel, b: &mut Brep, outer: LoopId) -> solidcore::Result> { + let (lu, _) = loop_loopuses(b, outer)?; + let eus = eu_p1::loopuse_edgeuses(b, lu)?; + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + let mut any = false; + for eu in eus { + let fetched = get_or_create_uv_trim_curve(k, b, eu, false, false, true)?; + if fetched.status.is_err() { + return Ok(None); + } + let (Some(uv), _) = eu_p1::uv_trim_curve(b, eu)? else { return Ok(None) }; + let Some(e) = answer(uv.calculate_tight_bounding_box(k, &uv.natural_interval()))? else { return Ok(None) }; + let (mn, mx) = (e.min(), e.max()); + lo = [lo[0].min(mn.x), lo[1].min(mn.y)]; + hi = [hi[0].max(mx.x), hi[1].max(mx.y)]; + any = true; + } + if !any || !(hi[0] > lo[0]) || !(hi[1] > lo[1]) || !(lo[0] + lo[1] + hi[0] + hi[1]).is_finite() { + return Ok(None); + } + Ok(Some(Extent2d::from_bounds(lo[0], lo[1], hi[0], hi[1]))) +} + +/// One edge of a hole to rebuild: its edge, how the loop runs along it, its ends as the loop +/// runs, its curve and interval (`Piece`). +struct Piece { + edge: EdgeId, + orient: OrientType, + from: Point3, + to: Point3, + curve: Curve, + interval: solidcore::geom::extent1d::Extent1d, +} + +/// `pieces_of`; `None` where the capi gives up. +fn pieces_of(b: &Brep, l: LoopId) -> solidcore::Result>> { + let (lu, _) = loop_loopuses(b, l)?; + let mut out = Vec::new(); + for eu in eu_p1::loopuse_edgeuses(b, lu)? { + let Some(e) = eu_p1::edge(b, eu)? else { return Ok(None) }; + let ed = b.edge(e)?; + let Some(curve) = ed.curve.clone() else { return Ok(None) }; + let (Some(v0), Some(v1)) = edge::start_end_vertices(b, e)? else { return Ok(None) }; + let same = eu_p1::orientation(b, eu)? == OrientType::Same; + let (p0, p1) = (b.vertex(v0)?.point, b.vertex(v1)?.point); + let (from, to) = if same { (p0, p1) } else { (p1, p0) }; + out.push(Piece { edge: e, orient: if same { OrientType::Same } else { OrientType::Opposite }, from, to, curve, interval: ed.interval }); + } + Ok((!out.is_empty()).then_some(out)) +} + +/// `is_disc`: whether `f` is bounded by one loop of exactly the edges `made`. +fn is_disc(b: &Brep, f: FaceId, made: &[EdgeId]) -> solidcore::Result { + let loops = face_p2::loops(b, f, false, None)?; + let [l] = loops.as_slice() else { return Ok(false) }; + let edges: Vec = loop_edges(b, *l)?.into_iter().flatten().collect(); + Ok(edges.len() == made.len() && edges.iter().all(|e| made.contains(e))) +} + +/// `rebuild_hole`: the hole `pieces` (edges of `src`) rebuilt in `face` of `r`: vertices and +/// edges made in the face, the face the closed loop splits off inside it deleted. `face` is the +/// face that keeps the rest. +fn rebuild_hole(k: &mut Kernel, src: Option<&Brep>, r: &mut Brep, face: &mut FaceId, pieces: &[Piece]) -> solidcore::Result> { + let Some(first_piece) = pieces.first() else { return Ok(Err(hole_refused())) }; + let editing = r.editing_enabled(); + r.set_editing_enabled(true); + let tol = r.tolerance(); + // Each edit notifies through the kernel's callbacks with the body's own attributes + // (`MakeEdgeInFace` does so itself), so the history tags follow. + let vertex_loop = |k: &mut Kernel, r: &mut Brep, face: FaceId, at: Point3| { + with_kernel_callbacks(k, r, |_, r, env| make_vertex_loop(r, face, at, OrientType::Opposite, env)) + }; + let done = (|| -> solidcore::Result> { + let (_, first) = match vertex_loop(k, r, *face, first_piece.from) { + Ok(v) => v, + Err(e) => return Ok(Err(status(e))), + }; + let mut at = first; + let mut made = Vec::with_capacity(pieces.len()); + let mut split = None; + for (i, p) in pieces.iter().enumerate() { + let last = i + 1 == pieces.len(); + let next = if last { + first + } else { + match vertex_loop(k, r, *face, p.to) { + Ok((_, v)) => v, + Err(e) => return Ok(Err(status(e))), + } + }; + let curve = p.curve.copy(k)?; + let mut out = EdgeInFace::default(); + if let Err(e) = make_edge_in_face(k, r, true, Some(*face), Some(at), Some(next), curve, None, p.interval, p.orient, tol, &mut out, None) { + return Ok(Err(status(e))); + } + let Some(e) = out.edge else { return Ok(Err(Error::Empty)) }; + match src { + Some(s) => copy_attributes(s, EntityRef::Edge(p.edge), r, EntityRef::Edge(e))?, + None => copy_attributes_within(r, EntityRef::Edge(p.edge), EntityRef::Edge(e))?, + } + made.push(e); + if let Some(nf) = out.face { + if !last || split.is_some() { + return Ok(Err(hole_refused())); + } + split = Some(nf); + } + at = next; + } + let Some(split) = split else { return Ok(Err(hole_refused())) }; + // One of the two faces is the disc inside the hole: it goes, its edges stay on the other. + let disc = if is_disc(r, split, &made)? { + split + } else if is_disc(r, *face, &made)? { + *face + } else { + return Ok(Err(hole_refused())); + }; + let rest = if disc == split { *face } else { split }; + let deleted = with_kernel_callbacks(k, r, |k, r, env| { + let mut marks = Marks::default(); + let options = DeleteFaceOptions { delete_edges_vertices: false, ..DeleteFaceOptions::default() }; + delete_face(k, r, env, &mut marks, disc, options) + }); + if let Err(e) = deleted { + return Ok(Err(status(e))); + } + *face = rest; + Ok(Ok(())) + })(); + r.set_editing_enabled(editing); + r.refresh_cached_topology(); + done +} + +/// The orientation of `f`'s upward faceuse. +fn upward(b: &Brep, f: FaceId) -> solidcore::Result> { + Ok(match face_p2::upward_faceuse(b, f)? { + Some(fu) => Some(b.faceuse(fu)?.orientation), + None => None, + }) +} + +/// `smlib_untrim_face`: the face of `body` nearest `point` (within `tol`) restored towards its +/// surface: the holes nearest `holes` (all of them for `None`) taken away and, with `outer`, its +/// outer boundary back on the surface's parameter box. The face alone, or with `in_place` the +/// whole body with it replaced. +pub(crate) fn untrim_face(body: &Body, point: [f64; 3], tol: f64, holes: Option<&[[f64; 3]]>, outer: bool, in_place: bool) -> Result { + let n_holes = holes.map(<[_]>::len); + if !point.iter().all(|x| x.is_finite()) + || !tol.is_finite() + || !(tol > 0.0) + || n_holes.is_some_and(|n| n > MAX_HOLE_POINTS) + || holes.is_some_and(|h| !h.iter().flatten().all(|x| x.is_finite())) + || (n_holes == Some(0) && !outer) + { + return Err(Error::Argument); + } + if body.0.is_poisoned() { + return Err(Error::Internal("smlib_untrim_face: the body was left unfinished by an earlier panic".to_owned())); + } + let at = p3(point); + super::run_on("smlib_untrim_face", &[("brep", body)], |k| { + let mut whole = brep_copy(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner))?; + // The face to untrim, in a body of its own (its hole edges lamina there) or in the copy + // of the whole body. + let (mut w, f) = if in_place { + let f = face_at(k, &mut whole, at, tol)?; + (whole, f) + } else { + let Some(src) = face_at(k, &mut whole, at, tol)? else { return Ok(Err(Error::NoMatch { point: 0 })) }; + let mut w = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + w.set_tolerance(whole.tolerance()); + // Through SmMerge, with both bodies' attributes in the notifications, so the copy + // carries its source's history tags (`SM_NO_COPY`). + let copied = { + let mut state = CopyNotifyState::with_attributes_of(&mut whole, &mut w)?; + let this_face = |f: FaceId| notify_ref(EntityRef::Face(f)); + let copied = copy_faces_from(k, &mut whole, &[src], &mut w, true, ©_source_ref, &this_face, &mut state.env(None)); + state.restore_attributes(&mut whole, &mut w)?; + copied + }; + let copied = match copied { + Ok((c, _)) => c, + Err(e) => return Ok(Err(status(e))), + }; + // The capi's `copied.GetSize() != 1`: `SMLIB_ERR_EMPTY`. + let [f] = copied.as_slice() else { return Ok(Err(Error::Empty)) }; + w.refresh_cached_topology(); + (w, Some(*f)) + }; + let Some(f) = f else { return Ok(Err(Error::NoMatch { point: 0 })) }; + let loops = face_p2::loops(&w, f, false, None)?; + if loops.is_empty() { + return Ok(Err(Error::Unsupported)); + } + let inner = loops.get(1..).unwrap_or_default(); + // The holes taken away: all of them, or the one nearest each point. + let mut removed: Vec = Vec::new(); + match holes { + None => removed.extend_from_slice(inner), + Some(points) => { + for p in points { + let p = p3(*p); + let (mut best, mut d0) = (None, f64::INFINITY); + for &l in inner { + let d = loop_distance(k, &w, l, p)?; + if d < d0 { + d0 = d; + best = Some(l); + } + } + let Some(best) = best.filter(|_| d0 <= tol) else { return Ok(Err(Error::NoMatch { point: 0 })) }; + if !removed.contains(&best) { + removed.push(best); + } + } + } + } + if !outer { + for &l in &removed { + // A hole whose edges another face of the body uses is no hole of a sheet. + let deleted = face_p1::delete_inner_loop_with_kernel_callbacks(k, &mut w, f, l); + if deleted.is_err() { + return Ok(Err(Error::Unsupported)); + } + } + w.refresh_cached_topology(); + return Ok(Ok(w)); + } + // The outer boundary: the surface's parameter box (a free-form surface's own, an + // analytic one's the span of the face). + let Some(surf) = face_p2::surface(&w, f)?.cloned() else { return Ok(Err(Error::Unsupported)) }; + let mut bx = surf.natural_uv_domain_with_nurb(k)?; + if !matches!(surf.kind(), SurfaceKind::BSpline(_)) { + let Some(outer_loop) = loops.first() else { return Ok(Err(Error::Unsupported)) }; + match span_of(k, &mut w, *outer_loop)? { + Some(s) => bx = s, + None => return Ok(Err(Error::Unsupported)), + } + } + let mut kept = Vec::new(); + for &l in inner { + if removed.contains(&l) { + continue; + } + match pieces_of(&w, l)? { + Some(p) => kept.push(p), + None => return Ok(Err(Error::Unsupported)), + } + } + let copy = surf.copy(k)?; + let was = upward(&w, f)?; + let mut r = if in_place { + None + } else { + let mut r = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + r.set_tolerance(w.tolerance()); + Some(r) + }; + let target: &mut Brep = match r.as_mut() { + Some(r) => r, + None => &mut w, + }; + let mut nf = match build_faces(target, |t, fenv| create_face_from_surface(k, t, Some(copy), &bx, fenv)) { + Ok(nf) => nf, + Err(e) => return Ok(Err(status(e))), + }; + target.refresh_cached_topology(); + let _ = target; + for hole in &kept { + let done = match r.as_mut() { + Some(r) => rebuild_hole(k, Some(&w), r, &mut nf, hole)?, + None => rebuild_hole(k, None, &mut w, &mut nf, hole)?, + }; + if let Err(e) = done { + return Ok(Err(e)); + } + } + match r.as_mut() { + Some(r) => copy_attributes(&w, EntityRef::Face(f), r, EntityRef::Face(nf))?, + None => copy_attributes_within(&mut w, EntityRef::Face(f), EntityRef::Face(nf))?, + } + // The face faces the way the old one did. + let target: &mut Brep = match r.as_mut() { + Some(r) => r, + None => &mut w, + }; + let now = upward(target, nf)?; + if let (Some(a), Some(b)) = (was, now) + && a != b + && let Err(e) = face_p1::flip_face_orientation(target, nf) + { + return Ok(Err(status(e))); + } + if let Some(r) = r { + return Ok(Ok(r)); + } + // The old face goes, with the edges and vertices only it used: an edit of the brep, + // which SMLib allows only in edit mode. + let editing = w.editing_enabled(); + w.set_editing_enabled(true); + let deleted = with_kernel_callbacks(k, &mut w, |k, w, env| { + let mut marks = Marks::default(); + let options = DeleteFaceOptions { delete_edges_vertices: true, ..DeleteFaceOptions::default() }; + delete_face(k, w, env, &mut marks, f, options) + }); + w.set_editing_enabled(editing); + w.refresh_cached_topology(); + if let Err(e) = deleted { + return Ok(Err(status(e))); + } + Ok(Ok(w)) + })? + .map(Body::new) +} + +/// One side of a face's parameter box (`Side`): which, whether it is a u = const line (the face +/// grows in u), and whether it is at the box's max. +#[derive(Clone, Copy)] +struct Side { + which: SurfParamType, + u: bool, + high: bool, +} + +/// `SIDES`. +const SIDES: [Side; 4] = [ + Side { which: SurfParamType::UMin, u: true, high: false }, + Side { which: SurfParamType::UMax, u: true, high: true }, + Side { which: SurfParamType::VMin, u: false, high: false }, + Side { which: SurfParamType::VMax, u: false, high: true }, +]; + +/// `SAMPLES`. +const SAMPLES: usize = 9; + +/// `on_side`: the point of side `s` of `dom` at `t` in [0, 1] along it, in UV. +fn on_side(dom: &Extent2d, s: Side, t: f64) -> Point2 { + let (lo, hi) = (dom.min(), dom.max()); + if s.u { + Point2::new(if s.high { hi.x } else { lo.x }, lo.y + t * (hi.y - lo.y)) + } else { + Point2::new(lo.x + t * (hi.x - lo.x), if s.high { hi.y } else { lo.y }) + } +} + +/// `eval`: the point at `uv` with its u and v derivatives; `None` where it does not evaluate or +/// is not finite. +fn eval(k: &Kernel, surf: &Surface, uv: Point2) -> Option<(Vec3, Vec3, Vec3)> { + let d = surf.evaluate(k, uv, 1, 1, EvaluateFlags::default()).ok()?; + let p = *d.first()?.first()?; + let du = *d.get(1)?.first()?; + let dv = *d.first()?.get(1)?; + (p.length().is_finite() && du.length().is_finite() && dv.length().is_finite()).then_some((p, du, dv)) +} + +fn point_at(k: &Kernel, surf: &Surface, uv: Point2) -> Option { + eval(k, surf, uv).map(|(p, _, _)| p) +} + +/// `edge_distance`. +fn edge_distance(k: &Kernel, b: &Brep, e: EdgeId, p: Vec3) -> f64 { + match edge_closest_point(k, b, e, p) { + Ok(c) if c.closest.distance.is_finite() => c.closest.distance, + _ => f64::INFINITY, + } +} + +/// `nearest_edge`: the distance to the nearest of `edges`, with that edge. +pub(super) fn nearest_edge(k: &Kernel, b: &Brep, edges: &[EdgeId], p: Vec3) -> (f64, Option) { + let (mut best, mut which) = (f64::INFINITY, None); + for &e in edges { + let d = edge_distance(k, b, e, p); + if d < best { + best = d; + which = Some(e); + } + } + (best, which) +} + +/// `is_boundary`: whether side `s` of the face's box is a side of the face (its samples on the +/// face's edges), and whether it collapses to a point (a pole). +fn is_boundary(k: &Kernel, b: &Brep, surf: &Surface, dom: &Extent2d, s: Side, edges: &[EdgeId], tol: f64) -> (bool, bool) { + let (Some(a), Some(z), Some(m)) = + (point_at(k, surf, on_side(dom, s, 0.0)), point_at(k, surf, on_side(dom, s, 1.0)), point_at(k, surf, on_side(dom, s, 0.5))) + else { + return (false, false); + }; + if (a - z).length() <= tol && (a - m).length() <= tol { + return (true, true); + } + let all = (0..=SAMPLES).all(|i| match point_at(k, surf, on_side(dom, s, i as f64 / SAMPLES as f64)) { + Some(p) => nearest_edge(k, b, edges, p).0 <= tol, + None => false, + }); + (all, false) +} + +/// `side_edge`: the edge of `edges` side `s` of `dom` runs along (nearest the side's middle), or +/// `None` for a side collapsed to a point. +fn side_edge(k: &Kernel, b: &Brep, surf: &Surface, dom: &Extent2d, s: Side, edges: &[EdgeId], on: f64) -> Option { + let a = point_at(k, surf, on_side(dom, s, 0.0))?; + let z = point_at(k, surf, on_side(dom, s, 1.0))?; + let m = point_at(k, surf, on_side(dom, s, 0.5))?; + if (a - z).length() <= on && (a - m).length() <= on { + return None; + } + let (d, e) = nearest_edge(k, b, edges, m); + e.filter(|_| d <= on) +} + +/// `across`: how far `ext` (the face's surface extended past side `s` of its box `dom`, on the +/// same parameters) runs past that side, measured across it through the side's middle, by +/// 16-point Gauss-Legendre quadrature on 64 pieces. Negative when it can't be evaluated. +fn across(k: &Kernel, ext: &Surface, dom: &Extent2d, s: Side) -> f64 { + const X: [f64; 8] = [ + 0.0950125098376374, + 0.2816035507792589, + 0.4580167776572274, + 0.6178762444026438, + 0.755404408355003, + 0.8656312023878318, + 0.9445750230732326, + 0.9894009349916499, + ]; + const W: [f64; 8] = [ + 0.1894506104550685, + 0.1826034150449236, + 0.1691565193950025, + 0.1495959888165767, + 0.1246289712555339, + 0.0951585116824928, + 0.0622535239386479, + 0.0271524594117541, + ]; + const PIECES: usize = 64; + let Ok(bx) = ext.natural_uv_domain_with_nurb(k) else { return -1.0 }; + let mid = on_side(dom, s, 0.5); + let from = if s.u { mid.x } else { mid.y }; + let to = match (s.u, s.high) { + (true, true) => bx.max().x, + (true, false) => bx.min().x, + (false, true) => bx.max().y, + (false, false) => bx.min().y, + }; + let h = (to - from) / PIECES as f64; + let mut length = 0.0; + for piece in 0..PIECES { + let c = from + (piece as f64 + 0.5) * h; + for i in 0..16 { + let (x, w) = if i < 8 { (-X[i], W[i]) } else { (X[i - 8], W[i - 8]) }; + let t = c + 0.5 * h * x; + let uv = if s.u { Point2::new(t, mid.y) } else { Point2::new(mid.x, t) }; + let Some((_, du, dv)) = eval(k, ext, uv) else { return -1.0 }; + length += 0.5 * h.abs() * w * if s.u { du } else { dv }.length(); + } + } + length +} + +/// `cone_continued`: a cone's or cylinder's face continued naturally `distance` past side `s` of +/// its box `dom`, as the analytic itself over a wider STEP domain (degrees round the axis, +/// height along it). `None` where the cone can't be widened so (more than a turn, or past the +/// apex). +fn cone_continued(k: &Kernel, surf: &Surface, dom: &Extent2d, s: Side, distance: f64) -> Option { + let SurfaceKind::Cone(cone) = surf.kind() else { return None }; + let mut cone: Cone = cone.as_ref().clone(); + let step = |uv: Point2| cone.convert_uv_from_nurbs_to_step(k, uv).ok(); + let (a, z, m) = (step(on_side(dom, s, 0.0))?, step(on_side(dom, s, 1.0))?, step(on_side(dom, s, 0.5))?); + let (lo, hi) = (step(dom.min())?, step(dom.max())?); + let semi = cone.canonical().semi_angle_deg; + let mut bx = [[lo.x.min(hi.x), lo.x.max(hi.x)], [lo.y.min(hi.y), lo.y.max(hi.y)]]; + let eps = 1e-9 * (1.0 + m.x.abs() + m.y.abs()); + // The STEP coordinate constant along the side is the one the face grows in. + let c = if (a.x - z.x).abs() <= eps { + 0 + } else if (a.y - z.y).abs() <= eps { + 1 + } else { + return None; + }; + let at = if c == 0 { m.x } else { m.y }; + let row = bx.get_mut(c)?; + let end = if (at - row[1]).abs() <= (at - row[0]).abs() { 1 } else { 0 }; + let by = if c == 0 { + let r = cone.radius(m.y); + if !(r > 0.0) { + return None; + } + (distance / r).to_degrees() + } else { + distance * semi.to_radians().cos() + }; + if end == 1 { + row[1] += by; + } else { + row[0] -= by; + } + if bx[0][1] - bx[0][0] > 360.0 + 1e-9 { + return None; + } + let wider = Extent2d::from_bounds(bx[0][0], bx[1][0], bx[0][1], bx[1][1]); + cone.adjust_step_uv_domain(k, &wider).ok()?; + Some(Surface::from(cone)) +} + +/// `same_patch`: whether `p` and `q` span the same patch: their boxes' corners the same points, +/// in any order, within `tol`. +fn same_patch(k: &Kernel, p: &Surface, q: &Surface, tol: f64) -> bool { + let (Ok(bp), Ok(bq)) = (p.natural_uv_domain_with_nurb(k), q.natural_uv_domain_with_nurb(k)) else { return false }; + let corners = |b: &Extent2d| { + let (lo, hi) = (b.min(), b.max()); + [lo, Point2::new(hi.x, lo.y), hi, Point2::new(lo.x, hi.y)] + }; + corners(&bp).into_iter().all(|u| { + let Some(x) = point_at(k, p, u) else { return false }; + corners(&bq).into_iter().any(|v| point_at(k, q, v).is_some_and(|y| (x - y).length() <= tol)) + }) +} + +/// `extended_by`: the surface `surf` (whose face is its whole box `dom`) extended past side `s` as +/// `ct` says, so that it runs `distance` past that side measured across it ([`across`]), within +/// 1e-9 of it. `CreateExtendedSurface` takes its distance as an estimate, and how far it then runs +/// is increasing in what it is asked: a bracketed solve on that (each ask scaled by the distance +/// over what it gave until two asks fall either side, then Illinois false position). An extension +/// that moves the face's side off its parameters, or a target not met, is [`Error::NotExact`], +/// never the surface as it came out. +fn extended_by(k: &Kernel, surf: &Surface, dom: &Extent2d, s: Side, ct: ContinuityType, distance: f64, model_tol: f64) -> Result { + const BRACKET_TRIES: usize = 40; + const SOLVE_TRIES: usize = 100; + let tol = 1e-9 * distance; + // How far asking `ask` runs, and the surface it makes. + let try_ask = |ask: f64| -> Result<(Surface, f64)> { + let tried = surf.create_extended_surface_dir(k, s.which, ask, ct).map_err(status)?; + // The face's side stays where it was on the extended surface's parameters. + let mid = on_side(dom, s, 0.5); + let stays = matches!((point_at(k, surf, mid), point_at(k, &tried, mid)), (Some(was), Some(now)) if (was - now).length() <= model_tol); + if !stays { + return Err(Error::NotExact); + } + let got = across(k, &tried, dom, s); + if got.is_finite() && got > 0.0 { Ok((tried, got)) } else { Err(Error::NotExact) } + }; + // Asks that run short of and past `distance`, by f = got - distance. + let (mut short, mut past) = (None, None); + let mut ask = distance; + for _ in 0..BRACKET_TRIES { + let (made, got) = try_ask(ask)?; + let f = got - distance; + if f.abs() <= tol { + return Ok(made); + } + if f < 0.0 { + short = Some((ask, f)); + } else { + past = Some((ask, f)); + } + if short.is_some() && past.is_some() { + break; + } + ask *= distance / got; + } + let (Some((mut lo, mut flo)), Some((mut hi, mut fhi))) = (short, past) else { return Err(Error::NotExact) }; + // Illinois: false position, halving the value at the end that stays when the same end moves + // twice running. + #[derive(PartialEq)] + enum Moved { + Neither, + Lo, + Hi, + } + let mut moved = Moved::Neither; + for _ in 0..SOLVE_TRIES { + let x = hi - fhi * (hi - lo) / (fhi - flo); + if !(x > lo.min(hi) && x < lo.max(hi)) { + break; + } + let (made, got) = try_ask(x)?; + let f = got - distance; + if f.abs() <= tol { + return Ok(made); + } + if f < 0.0 { + (lo, flo) = (x, f); + if moved == Moved::Lo { + fhi *= 0.5; + } + moved = Moved::Lo; + } else { + (hi, fhi) = (x, f); + if moved == Moved::Hi { + flo *= 0.5; + } + moved = Moved::Hi; + } + } + Err(Error::NotExact) +} + +/// `smlib_extend_sheet`: the one-face sheet `sheet`, whose face is its surface's whole parameter +/// box, continued `distance` past the side its edge nearest `point` (within `tol`) runs along, +/// as `how` says. A sheet of another shape is [`Error::Unsupported`]; an extension that cannot be +/// made `distance` long across the side (within 1e-9 of it) is [`Error::NotExact`]. +pub(crate) fn extend_sheet(sheet: &Body, point: [f64; 3], tol: f64, distance: f64, how: Continuation) -> Result { + if !point.iter().all(|x| x.is_finite()) || !tol.is_finite() || !(tol > 0.0) || !distance.is_finite() || !(distance > 0.0) { + return Err(Error::Argument); + } + if sheet.0.is_poisoned() { + return Err(Error::Internal("smlib_extend_sheet: the body was left unfinished by an earlier panic".to_owned())); + } + super::run_on("smlib_extend_sheet", &[("sheet", sheet)], |k| { + let b = brep_copy(k, &sheet.0.lock().unwrap_or_else(PoisonError::into_inner))?; + let faces = brep_p1::faces(&b, None)?; + let [f] = faces.as_slice() else { return Ok(Err(Error::Unsupported)) }; + let f = *f; + let Some(surf) = face_p2::surface(&b, f)?.cloned() else { return Ok(Err(Error::Unsupported)) }; + if face_p2::loops(&b, f, false, None)?.len() != 1 { + return Ok(Err(Error::Unsupported)); + } + let edges = face_p4::edges(&b, f, None, false, None)?; + let (d, picked) = nearest_edge(k, &b, &edges, p3(point)); + let Some(picked) = picked.filter(|_| d <= tol) else { return Ok(Err(Error::NoMatch { point: 0 })) }; + let model_tol = b.tolerance().max(1e-9); + let on = 10.0 * model_tol; + let dom = face_p2::uv_domain(&b, f)?; + // Every side of the box is a side of the face (the face is its whole box), and the picked + // edge is all of one side. + let mut grow = None; + for s in SIDES { + let (boundary, collapsed) = is_boundary(k, &b, &surf, &dom, s, &edges, on); + if !boundary { + return Ok(Err(Error::Unsupported)); + } + if collapsed { + continue; + } + let all = (0..=SAMPLES).all(|i| match point_at(k, &surf, on_side(&dom, s, i as f64 / SAMPLES as f64)) { + Some(p) => edge_distance(k, &b, picked, p) <= on, + None => false, + }); + if all { + grow = Some(s); + } + } + let Some(grow) = grow else { return Ok(Err(Error::Unsupported)) }; + // SMLib extends the whole surface; the face must be all of it. + let natural = surf.natural_uv_domain_with_nurb(k)?; + let (nl, nh, dl, dh) = (natural.min(), natural.max(), dom.min(), dom.max()); + let ptol = 1e-9 * 1f64.max((nh.x - nl.x).max(nh.y - nl.y)); + if (nl.x - dl.x).abs() > ptol || (nl.y - dl.y).abs() > ptol || (nh.x - dh.x).abs() > ptol || (nh.y - dh.y).abs() > ptol { + return Ok(Err(Error::Unsupported)); + } + let ct = match how { + Continuation::Tangent => ContinuityType::G1, + Continuation::Curvature => ContinuityType::G1G2, + Continuation::Natural => ContinuityType::CInfinity, + }; + // CreateExtendedSurface takes its distance as an estimate (a natural parabola falls 2.5% + // short, a G2 run-off of a circle runs more than twice as far): the distance asked of it + // is solved for until the extension measures `distance` across the side's middle. + let extended = match extended_by(k, &surf, &dom, grow, ct, distance, model_tol) { + Ok(e) => e, + Err(e) => return Ok(Err(e)), + }; + // A cone or cylinder continued naturally stays one, as the analytic widened, else SMLib + // gives it back its analytic kind where it can. + let grown = match how { + Continuation::Natural => cone_continued(k, &surf, &dom, grow, distance).filter(|g| same_patch(k, g, &extended, 10.0 * model_tol)), + _ => None, + }; + let grown = match grown { + Some(g) => g, + None => match extended.copy_and_add_analytics(k) { + Ok(g) => g, + Err(e) => return Ok(Err(status(e))), + }, + }; + let bx = grown.natural_uv_domain_with_nurb(k)?; + let mut r = new_brep(k, USE_DEFAULT, USE_DEFAULT)?; + r.set_tolerance(b.tolerance()); + let grown_eval = grown.copy(k)?; + let nf = match build_faces(&mut r, |t, fenv| create_face_from_surface(k, t, Some(grown), &bx, fenv)) { + Ok(nf) => nf, + Err(e) => return Ok(Err(status(e))), + }; + r.refresh_cached_topology(); + // The face and each side stand for the face and side they continue. + copy_attributes(&b, EntityRef::Face(f), &mut r, EntityRef::Face(nf))?; + let made = face_p4::edges(&r, nf, None, false, None)?; + let new_on = 10.0 * r.tolerance().max(1e-9); + for s in SIDES { + let from = side_edge(k, &b, &surf, &dom, s, &edges, on); + let to = side_edge(k, &r, &grown_eval, &bx, s, &made, new_on); + if let (Some(from), Some(to)) = (from, to) { + copy_attributes(&b, EntityRef::Edge(from), &mut r, EntityRef::Edge(to))?; + } + } + // The new face faces the way the old one did. + if let (Some(was), Some(now)) = (upward(&b, f)?, upward(&r, nf)?) + && was != now + && let Err(e) = face_p1::flip_face_orientation(&mut r, nf) + { + return Ok(Err(status(e))); + } + Ok(Ok(r)) + })? + .map(Body::new) +} + +/// A point inside each face, in the body's face order (`smlib_brep_face_points`: +/// `SmFace::CalculateAnInternalPoint`). +pub(crate) fn face_points(body: &Body) -> Result> { + super::with_body("smlib_brep_face_points", body, |k, b| { + let faces = b.face_list().to_vec(); + faces.into_iter().map(|f| face_internal_point(k, b, f).map(|p| [p.x, p.y, p.z])).collect() + }) +} diff --git a/crates/smlib/src/core/trim_tests.rs b/crates/smlib/src/core/trim_tests.rs new file mode 100644 index 000000000..f3c68de35 --- /dev/null +++ b/crates/smlib/src/core/trim_tests.rs @@ -0,0 +1,313 @@ +//! Untrim and extend on solidcore, against closed forms: areas and counts, and every result exports +//! to a record that validates. +//! +//! An untrim's body is a 20 x 20 x 5 plate with a 3 mm through hole at (10, 10), made on +//! solidcore; its top face is a square with a round hole. An extend's is a one-face sheet that is +//! its surface's whole parameter box: a 10 mm square, or a quarter of a cylinder of radius 10 and +//! height 10. + +use std::f64::consts::{FRAC_1_SQRT_2, PI}; + +use super::trim::{extend_sheet, untrim_face}; +use super::{Body, area, counts, make_box, make_cylinder, to_arrays}; +use crate::export::native; +use crate::trim::Continuation; +use crate::{BooleanOp, Error}; + +const TOL: f64 = 0.01; +/// A point on the top face, away from the hole. +const TOP: [f64; 3] = [2.0, 2.0, 5.0]; +/// A point on the hole's rim on the top face. +const RIM: [f64; 3] = [13.0, 10.0, 5.0]; + +/// The plate's top as a sheet of its own: a 20 mm square at z = 0 with a 3 mm hole at (10, 10). +fn holed_sheet() -> Body { + use crate::sweeps::Curve; + let line = |a: [f64; 3], b: [f64; 3]| Curve::Line { start: a, end: b }; + let (a, b, c, d) = ([0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [20.0, 20.0, 0.0], [0.0, 20.0, 0.0]); + let hole = Curve::Arc { center: [10.0, 10.0, 0.0], axis: [0.0, 0.0, 1.0], reference: [1.0, 0.0, 0.0], radius: 3.0, start: 0.0, end: 2.0 * PI }; + super::sweep::planar_faces(&[line(a, b), line(b, c), line(c, d), line(d, a), hole]).unwrap() +} + +/// On the sheet: a point away from the hole, and one on the hole's rim. +const SHEET: [f64; 3] = [2.0, 2.0, 0.0]; +const SHEET_RIM: [f64; 3] = [13.0, 10.0, 0.0]; + +#[derive(Clone, Copy, Debug)] +enum Input { + Plate, + Sheet, +} + +impl Input { + fn core(self) -> Body { + match self { + Input::Plate => plate(), + Input::Sheet => holed_sheet(), + } + } +} + +fn plate() -> Body { + let block = make_box([0.0; 3], [20.0, 20.0, 5.0]).unwrap(); + let pin = make_cylinder([10.0, 10.0, -1.0], 3.0, 7.0).unwrap(); + super::boolean::boolean(&block, &pin, BooleanOp::Subtract).unwrap().unwrap() +} + +#[derive(Clone, Copy, Debug)] +struct Case { + input: Input, + point: [f64; 3], + /// `None`: every hole. + holes: Option<&'static [[f64; 3]]>, + outer: bool, + in_place: bool, +} + +#[derive(Clone, Debug, PartialEq)] +enum Expect { + /// A sheet: its area and face count. + Sheet(f64, usize), + Fails(Error), +} + +fn case(name: &str) -> (Case, Expect) { + let c = |input, point, holes, outer, in_place| Case { input, point, holes, outer, in_place }; + let square = 400.0; + let holed = 400.0 - 9.0 * PI; + let (plate, sheet) = (Input::Plate, Input::Sheet); + match name { + // The plate's top face, alone. + "every_hole_taken_away" => (c(plate, TOP, None, false, false), Expect::Sheet(square, 1)), + "the_hole_at_a_point_taken_away" => (c(plate, TOP, Some(&[RIM]), false, false), Expect::Sheet(square, 1)), + // The outer boundary back on the plane's box of the face's span, the hole kept. + "outer_boundary_back_hole_kept" => (c(plate, TOP, Some(&[]), true, false), Expect::Sheet(holed, 1)), + "outer_boundary_back_holes_gone" => (c(plate, TOP, None, true, false), Expect::Sheet(square, 1)), + // In the solid, the hole's edges are the bore's too: no hole of a sheet. + "a_hole_of_a_solid_in_place" => (c(plate, TOP, None, false, true), Expect::Fails(Error::Unsupported)), + "a_point_near_no_face" => (c(plate, [50.0, 50.0, 50.0], None, false, false), Expect::Fails(Error::NoMatch { point: 0 })), + // The holed sheet, in place. + "sheet_every_hole_taken_away" => (c(sheet, SHEET, None, false, true), Expect::Sheet(square, 1)), + "sheet_the_hole_at_a_point_taken_away" => (c(sheet, SHEET, Some(&[SHEET_RIM]), false, true), Expect::Sheet(square, 1)), + "sheet_outer_boundary_back_hole_kept" => (c(sheet, SHEET, Some(&[]), true, true), Expect::Sheet(holed, 1)), + "sheet_outer_boundary_back_holes_gone" => (c(sheet, SHEET, None, true, true), Expect::Sheet(square, 1)), + "sheet_a_point_near_no_hole" => (c(sheet, SHEET, Some(&[SHEET]), false, true), Expect::Fails(Error::NoMatch { point: 0 })), + _ => panic!("no case {name}"), + } +} + +#[derive(Debug, PartialEq)] +struct Measured { + area: f64, + counts: [usize; 3], +} + +type Got = std::result::Result; + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs() +} + +fn judge(name: &str, who: &str, got: Got) -> Got { + let (_, expect) = case(name); + match (&expect, &got) { + (Expect::Fails(e), Err(g)) => assert_eq!(g, e, "{name}: {who} failed otherwise"), + (Expect::Fails(e), Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"), + (_, Err(g)) => panic!("{name}: {who} failed: {g}"), + (Expect::Sheet(a, faces), Ok(m)) => { + assert!(rel(m.area, *a) < 1e-9, "{name}: {who} area {} vs analytic {a}", m.area); + assert_eq!(m.counts[0], *faces, "{name}: {who} faces"); + } + } + got +} + +fn solidcore_case(name: &str) -> Got { + let (c, _) = case(name); + let got = untrim_face(&c.input.core(), c.point, TOL, c.holes, c.outer, c.in_place).map(|b| { + let (rec, _) = native(&to_arrays(&b).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + Measured { area: area(&b, 1e-8).unwrap(), counts: counts(&b).unwrap() } + }); + judge(name, "solidcore", got) +} + +macro_rules! cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::solidcore_case(stringify!($m)); + } + } + )*}; +} + +cases!( + every_hole_taken_away, + the_hole_at_a_point_taken_away, + outer_boundary_back_hole_kept, + outer_boundary_back_holes_gone, + a_hole_of_a_solid_in_place, + a_point_near_no_face, + sheet_every_hole_taken_away, + sheet_the_hole_at_a_point_taken_away, + sheet_outer_boundary_back_hole_kept, + sheet_outer_boundary_back_holes_gone, + sheet_a_point_near_no_hole, +); + +/// The capi's argument checks, before any kernel call. +#[test] +fn hostile_arguments_are_refused() { + let b = make_box([0.0; 3], [10.0; 3]).unwrap(); + let p = [5.0, 5.0, 10.0]; + assert_eq!(untrim_face(&b, [f64::NAN, 0.0, 0.0], TOL, None, true, false).err(), Some(Error::Argument)); + for t in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(untrim_face(&b, p, t, None, true, false).err(), Some(Error::Argument), "tolerance {t}"); + } + assert_eq!(untrim_face(&b, p, TOL, Some(&[]), false, false).err(), Some(Error::Argument), "nothing to do"); + assert_eq!(untrim_face(&b, p, TOL, Some(&[[f64::INFINITY; 3]]), false, false).err(), Some(Error::Argument)); + let many = vec![p; 10_001]; + assert_eq!(untrim_face(&b, p, TOL, Some(&many), false, false).err(), Some(Error::Argument)); +} + +/// The body untrimmed is never changed. +#[test] +fn the_body_stays_as_it_was() { + let b = plate(); + let was = counts(&b).unwrap(); + let _ = untrim_face(&b, TOP, TOL, None, true, false); + let _ = untrim_face(&b, TOP, TOL, None, false, true); + assert_eq!(counts(&b).unwrap(), was); +} + +/// A one-face sheet on `surface` over `domain`, the face its whole box. +fn whole_face(surface: solidcore::surface::surface::Surface) -> Body { + use solidcore::topology::brep::p3::new_brep; + use solidcore::topology::brep::p8::create_face_from_surface; + super::run("sheet", |k| { + let mut b = new_brep(k, solidcore::geom::tol::USE_DEFAULT, solidcore::geom::tol::USE_DEFAULT)?; + let domain = surface.natural_uv_domain_with_nurb(k)?; + super::sweep::build_faces(&mut b, |b, fenv| create_face_from_surface(k, b, Some(surface), &domain, fenv))?; + b.refresh_cached_topology(); + Ok(b) + }) + .map(Body::new) + .unwrap() +} + +#[derive(Clone, Copy, Debug)] +enum Sheet { + /// [0, 10]^2 at z = 0. + Square, + /// Radius 10 about +Z, from 0 to 90 degrees, z from 0 to 10. + QuarterCylinder, +} + +impl Sheet { + fn core(self) -> Body { + use solidcore::geom::extent2d::Extent2d; + use solidcore::geom::vector2d::Vec2; + use solidcore::geom::vector3d::Vec3; + use solidcore::surface::cone::p1::Cone; + use solidcore::surface::plane::p1::Plane; + use solidcore::surface::surface::Surface; + let (o, x, y) = (Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)); + match self { + Sheet::Square => whole_face(Surface::from(Plane::new(o, x, y, Vec2::new(1.0, 1.0), &Extent2d::from_bounds(0.0, 0.0, 10.0, 10.0)))), + Sheet::QuarterCylinder => whole_face(Surface::from(Cone::new_cylinder_bounded(o, x, y, 10.0, 0.0, 90.0, 10.0, false, false, false))), + } + } +} + +fn extend_case(name: &str) -> (Sheet, [f64; 3], f64, Continuation, Expect) { + let quarter = 5.0 * PI; + match name { + "extend_a_square" => (Sheet::Square, [10.0, 5.0, 0.0], 5.0, Continuation::Natural, Expect::Sheet(150.0, 1)), + "extend_a_square_tangent" => (Sheet::Square, [5.0, 10.0, 0.0], 5.0, Continuation::Tangent, Expect::Sheet(150.0, 1)), + "extend_a_square_curvature" => (Sheet::Square, [0.0, 5.0, 0.0], 2.0, Continuation::Curvature, Expect::Sheet(120.0, 1)), + "extend_a_cylinder_along_its_axis" => { + (Sheet::QuarterCylinder, [FRAC_1_SQRT_2 * 10.0, FRAC_1_SQRT_2 * 10.0, 10.0], 5.0, Continuation::Natural, Expect::Sheet(quarter * 15.0, 1)) + } + "extend_a_cylinder_round_its_axis" => { + (Sheet::QuarterCylinder, [10.0, 0.0, 5.0], 5.0, Continuation::Natural, Expect::Sheet(10.0 * (quarter + 5.0), 1)) + } + // Run-offs 5 long across the surface whatever their curvature: the strip stays its section + // swept 10 along z. A circle's G2 run-off runs about 2.3 times what it is asked and more + // than doubles with it (fork 0f7b209), so the ask must be solved for. + "extend_a_cylinder_tangent_run_off" => { + (Sheet::QuarterCylinder, [10.0, 0.0, 5.0], 5.0, Continuation::Tangent, Expect::Sheet(10.0 * (quarter + 5.0), 1)) + } + "extend_a_cylinder_curvature_run_off" => { + (Sheet::QuarterCylinder, [10.0, 0.0, 5.0], 5.0, Continuation::Curvature, Expect::Sheet(10.0 * (quarter + 5.0), 1)) + } + "extend_picks_near_no_edge" => (Sheet::Square, [50.0, 50.0, 0.0], 5.0, Continuation::Natural, Expect::Fails(Error::NoMatch { point: 0 })), + _ => panic!("no case {name}"), + } +} + +fn extend_judge(name: &str, who: &str, got: Got) -> Got { + let (.., expect) = extend_case(name); + match (&expect, &got) { + (Expect::Fails(e), Err(g)) => assert_eq!(g, e, "{name}: {who} failed otherwise"), + (Expect::Fails(e), Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"), + (_, Err(g)) => panic!("{name}: {who} failed: {g}"), + (Expect::Sheet(a, faces), Ok(m)) => { + assert!(rel(m.area, *a) < 1e-6, "{name}: {who} area {} vs analytic {a}", m.area); + assert_eq!(m.counts[0], *faces, "{name}: {who} faces"); + } + } + got +} + +fn extend_solidcore(name: &str) -> Got { + let (sheet, point, distance, how, _) = extend_case(name); + let got = extend_sheet(&sheet.core(), point, TOL, distance, how).map(|b| { + let (rec, _) = native(&to_arrays(&b).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}")); + solidcraft_geom::brep::check::validate(&rec).unwrap_or_else(|e| panic!("{name}: record: {e}")); + Measured { area: area(&b, 1e-8).unwrap(), counts: counts(&b).unwrap() } + }); + extend_judge(name, "solidcore", got) +} + +macro_rules! extend_cases { + ($($m:ident $(: $ign:meta)?),* $(,)?) => {$( + mod $m { + #[test] + $(#[$ign])? + fn solidcore_matches_the_closed_form() { + let _ = super::extend_solidcore(stringify!($m)); + } + } + )*}; +} + +extend_cases!( + extend_a_square, + extend_a_square_tangent, + extend_a_square_curvature, + extend_a_cylinder_along_its_axis, + extend_a_cylinder_round_its_axis, + extend_a_cylinder_tangent_run_off, + extend_a_cylinder_curvature_run_off, + extend_picks_near_no_edge, +); + +/// The capi's argument checks for an extend, before any kernel call, and a body of more than +/// one face. +#[test] +fn hostile_extend_arguments_are_refused() { + let s = Sheet::Square.core(); + let p = [10.0, 5.0, 0.0]; + assert_eq!(extend_sheet(&s, [f64::NAN; 3], TOL, 5.0, Continuation::Natural).err(), Some(Error::Argument)); + for t in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(extend_sheet(&s, p, t, 5.0, Continuation::Natural).err(), Some(Error::Argument), "tolerance {t}"); + assert_eq!(extend_sheet(&s, p, TOL, t, Continuation::Natural).err(), Some(Error::Argument), "distance {t}"); + } + let cube = make_box([0.0; 3], [10.0; 3]).unwrap(); + assert_eq!(extend_sheet(&cube, p, TOL, 5.0, Continuation::Natural).err(), Some(Error::Unsupported)); + // A face that is not its surface's whole box: a square with a hole. + assert_eq!(extend_sheet(&holed_sheet(), [20.0, 5.0, 0.0], TOL, 5.0, Continuation::Natural).err(), Some(Error::Unsupported)); +} diff --git a/crates/smlib/src/export.rs b/crates/smlib/src/export.rs new file mode 100644 index 000000000..473634c96 --- /dev/null +++ b/crates/smlib/src/export.rs @@ -0,0 +1,1638 @@ +//! SMLib B-reps out to SolidCraft's schema 4 B-rep (`solidcraft_geom::brep`, docs/native-brep.md), +//! and the primitive solids beyond the box. +//! +//! The C API hands out SMLib's B-rep as flat arrays (`smlib_brep_export`, laid out like USD's +//! BrepArray: analytic surfaces as their kinds, ranges in radians, converted end by end from +//! SMLib's NURB parameters). This module reads them as hostile input and maps them to schema 4: +//! - **Geometry:** each analytic surface to its schema kind (SMLib's cone of semi-angle 0 is its +//! cylinder), NURBS as splines. Edge curves come as their own kinds, or as NURBS where SMLib +//! holds the edge as one; nothing is recognised. The report counts the NURBS edges. +//! - **Sides:** SMLib keeps a face's loops relative to its own natural normal, which may be +//! opposite the STEP form's (a surface with SMLib's `insideOut` or `swapUV`). Schema 4 keeps +//! them relative to the record's normal, outer loop counter-clockwise: a face whose outer loop +//! comes out clockwise in the record's parameters has its loops reversed and its sides flipped. +//! - **Shells and regions:** SMLib keeps a closed boundary as two runtime shells, one per side, +//! each face's use in a shell facing into that shell's region; schema 4 keeps one record, its +//! oriented faces as the side in the region that is not material uses them (out of the +//! material). A sheet's one shell holds both uses of each face: the `same` one is kept. The +//! infinite region is never a void (SMLib marks it one). +//! - **Touching:** an edge or vertex solids touching each other share is copied once per solid; +//! an edge one solid touches itself along (four or more uses in a shell) is copied once per +//! pair of faces SMLib's radial order puts across one sector round it, so every edge bounds +//! two faces. +//! - **Order:** faces, edges and vertices renumbered in the canonical walk; each edge's uses +//! from that walk (`upper = !forward`), never SMLib's radial entry flags. +//! - **Pcurves:** on a B-spline face, SMLib's own UV trims, exactly: the face's parameters are +//! SMLib's, and each trim's knots are moved onto its edge record's parameter where that is an +//! affine image of SMLib's (a spline edge's is SMLib's own; a line's the line's STEP +//! parameter, which the C side maps the trims onto). SMLib keeps an analytic surface's trims +//! on the surface's internal rational B-spline, whose angular parameter is not the angle +//! (SmCylinder.h: "the map from one to the other is not linear"), and a circle's or ellipse's +//! on its NURBS parameter, not its angle; those pcurves are computed from the edge record on +//! the face's surface record (`solidcraft_geom::brep::pcurve`). Every loop is moved by whole +//! periods into the face's domain. +//! - **Tolerances:** each edge's and vertex's own as SMLib reports it (`EDGE_TOLERANCE`, +//! `VERTEX_TOLERANCE`), never below a floor of 10⁻⁶ of the body's size (at least 10⁻⁵ mm), +//! which is the body's; from a library without them, SMLib's intersection tolerance (or the +//! floor where larger) for the body, every edge and every vertex. +use solidcraft_geom::prelude::*; +use std::f64::consts::TAU; + +use std::collections::HashMap; + +use solidcore_record::Vec3; +use solidcore_record::brep as b; + +use crate::flat::{self, *}; +use crate::history::{Order, Piece}; +use crate::import::Arrays; +use crate::{Brep, Result}; + +impl Brep { + /// A cylinder about +Z: base centre, radius and height (mm, > 0). + pub fn make_cylinder(origin: [f64; 3], radius: f64, height: f64) -> Result { + let r = crate::core::make_cylinder(origin, radius, height).map(Brep::made_core); + crate::trace::made("make_cylinder", &[], &r, || serde_json::json!({"origin": origin, "radius": radius, "height": height})); + r + } + + /// A sphere: centre and radius (mm, > 0). + pub fn make_sphere(center: [f64; 3], radius: f64) -> Result { + let r = crate::core::make_sphere(center, radius).map(Brep::made_core); + crate::trace::made("make_sphere", &[], &r, || serde_json::json!({"center": center, "radius": radius})); + r + } + + /// A cone or frustum about +Z: base centre, base radius (> 0), top radius (≥ 0, not the base + /// radius) and height (> 0), in mm. + pub fn make_cone(origin: [f64; 3], base_radius: f64, top_radius: f64, height: f64) -> Result { + let r = crate::core::make_cone(origin, base_radius, top_radius, height).map(Brep::made_core); + crate::trace::made( + "make_cone", + &[], + &r, + || serde_json::json!({"origin": origin, "base_radius": base_radius, "top_radius": top_radius, "height": height}), + ); + r + } + + /// A ring torus about +Z: centre, major radius > minor radius > 0 (mm). + pub fn make_torus(center: [f64; 3], major_radius: f64, minor_radius: f64) -> Result { + let r = crate::core::make_torus(center, major_radius, minor_radius).map(Brep::made_core); + crate::trace::made( + "make_torus", + &[], + &r, + || serde_json::json!({"center": center, "major_radius": major_radius, "minor_radius": minor_radius}), + ); + r + } + + /// The flat arrays of this body that the mapping reads. + pub fn arrays(&self) -> Result { + crate::core::to_arrays(self.core()) + } + + /// This body as a schema 4 B-rep, validated. + pub fn to_native(&self) -> std::result::Result { + self.to_native_report().map(|(brep, _)| brep) + } + + /// [`Brep::to_native`], with what the mapping kept as SMLib wrote it. + pub fn to_native_report(&self) -> std::result::Result<(b::Brep, Report), ExportError> { + let arrays = self.arrays().map_err(ExportError::Smlib)?; + let r = native(&arrays); + if let Ok((record, _)) = &r { + crate::trace::exported(self, record); + } + r + } + + /// [`Brep::to_native`], with where each of SMLib's faces and edges went in the record's + /// canonical order: what [`crate::history::Raw::history`] renumbers this body's history with. + /// SMLib's export lists faces and edges in the body's own order (`SmBrep::GetFaces`, + /// `GetEdges`), the order its history uses. + pub fn to_native_ordered(&self) -> std::result::Result<(b::Brep, Order), ExportError> { + let arrays = self.arrays().map_err(ExportError::Smlib)?; + let r = native_ordered(&arrays).map(|(brep, _, order)| (brep, order)); + if let Ok((record, _)) = &r { + crate::trace::exported(self, record); + } + r + } +} + +/// What the mapping could not put in its own kind, or turned. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Report { + /// NURBS edge curves kept as splines (neither a line nor a circular arc). + pub nurbs_edges: usize, + /// Faces whose loops were reversed (SMLib's natural normal against the record's). + pub reversed_faces: usize, +} + +/// Why an SMLib body has no schema 4 record. +#[derive(Clone, Debug, PartialEq)] +pub enum ExportError { + /// The SMLib call failed. + Smlib(super::Error), + /// SMLib holds something schema 4 (or this mapping) has no record for, named. + Unsupported(String), + /// The arrays are malformed or inconsistent. + Invalid(String), +} + +impl std::fmt::Display for ExportError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ExportError::Smlib(e) => write!(f, "SMLib export: {e}"), + ExportError::Unsupported(what) => write!(f, "SMLib export: not supported yet: {what}"), + ExportError::Invalid(what) => write!(f, "SMLib export: {what}"), + } + } +} + +impl std::error::Error for ExportError {} + +type Res = std::result::Result; + +fn invalid(what: impl std::fmt::Display) -> ExportError { + ExportError::Invalid(what.to_string()) +} +fn unsupported(what: impl std::fmt::Display) -> ExportError { + ExportError::Unsupported(what.to_string()) +} + +// ---- The arrays (ids and kinds from `crate::flat`, as in capi/include/smlib.h) ------------ + +// The kind values as the arrays hold them (int64); a local item shadows the glob import. +const SURFACE_NURBS: i64 = flat::SURFACE_NURBS as i64; +const SURFACE_PLANE: i64 = flat::SURFACE_PLANE as i64; +const SURFACE_CYLINDER: i64 = flat::SURFACE_CYLINDER as i64; +const SURFACE_CONE: i64 = flat::SURFACE_CONE as i64; +const SURFACE_SPHERE: i64 = flat::SURFACE_SPHERE as i64; +const SURFACE_TORUS: i64 = flat::SURFACE_TORUS as i64; +const SURFACE_BALL_PATCH: i64 = flat::SURFACE_BALL_PATCH as i64; +const CURVE_NURBS: i64 = flat::CURVE_NURBS as i64; +const CURVE_LINE: i64 = flat::CURVE_LINE as i64; +const CURVE_CIRCLE: i64 = flat::CURVE_CIRCLE as i64; +const CURVE_ELLIPSE: i64 = flat::CURVE_ELLIPSE as i64; + +/// Read access to the arrays: a missing array reads as empty. +#[derive(Clone, Copy)] +struct View<'a>(&'a Arrays); + +impl View<'_> { + fn i(&self, id: i32) -> &[i64] { + self.0.ints.get(&id).map_or(&[], Vec::as_slice) + } + fn f(&self, id: i32) -> &[f64] { + self.0.reals.get(&id).map_or(&[], Vec::as_slice) + } +} + +fn at(a: &[T], k: usize, what: &str) -> Res { + a.get(k).copied().ok_or_else(|| invalid(format!("{what}: index {k} out of range"))) +} +fn idx(x: i64, n: usize, what: &str) -> Res { + usize::try_from(x).ok().filter(|i| *i < n).ok_or_else(|| invalid(format!("{what}: {x} out of range"))) +} +/// A count in the arrays: at most SMLib's longest array ([`flat::MAX_LEN`], checked on entry), as +/// no block is longer than the array it lies in, so offsets worked out from counts cannot overflow. +fn count(x: i64, what: &str) -> Res { + usize::try_from(x).ok().filter(|n| *n <= flat::MAX_LEN).ok_or_else(|| invalid(format!("{what}: count {x}"))) +} +fn index(i: usize) -> Res { + u32::try_from(i).map_err(|_| invalid("index")) +} +fn v3(a: &[f64], k: usize, what: &str) -> Res<[f64; 3]> { + Ok([at(a, 3 * k, what)?, at(a, 3 * k + 1, what)?, at(a, 3 * k + 2, what)?]) +} +/// Consecutive blocks of `counts` covering `0..total`. +fn blocks(counts: &[i64], total: usize, what: &str) -> Res>> { + let mut start = 0usize; + let mut out = Vec::with_capacity(counts.len()); + for &c in counts { + let end = start.checked_add(count(c, what)?).filter(|e| *e <= total).ok_or_else(|| invalid(format!("{what}: blocks overrun")))?; + out.push(start..end); + start = end; + } + if start != total { + return Err(invalid(format!("{what}: blocks do not cover the array"))); + } + Ok(out) +} + +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} +/// A frame from an origin, z axis and x axis (y = z × x). +fn frame(origin: [f64; 3], axis: [f64; 3], x: [f64; 3]) -> b::Frame { + b::Frame { origin, x_axis: x, y_axis: cross(axis, x) } +} + +// ---- Geometry --------------------------------------------------------------------------- + +/// The schema record of each face's surface, in face order, and its NURBS form when the arrays give +/// one (`FACE_NURBS_FORM`: an analytic face with the NURBS SMLib holds it as; a ball patch: its +/// net, the face's own NURBS block, with its sphere from `FACE_DEFINITION_REALS`). +fn surfaces(flat: View, n_faces: usize) -> Res)>> { + let kinds = flat.i(FACE_SURFACE_TYPE); + if kinds.len() != n_faces { + return Err(invalid("face surface kinds")); + } + // The NURBS blocks, in face order: each NURBS face's surface and each face's NURBS form. + struct At { + j: usize, + cv: usize, + uk: usize, + vk: usize, + w: usize, + } + let next_nurbs = |at_: &mut At| -> Res { + let j = at_.j; + let nu = count(at(flat.i(FACE_NURBS_U_VERTEX_COUNT), j, "NURBS face")?, "NURBS face")?; + let nv = count(at(flat.i(FACE_NURBS_V_VERTEX_COUNT), j, "NURBS face")?, "NURBS face")?; + let ou = count(at(flat.i(FACE_NURBS_U_ORDER), j, "NURBS face")?, "NURBS face")?; + let ov = count(at(flat.i(FACE_NURBS_V_ORDER), j, "NURBS face")?, "NURBS face")?; + let n = nu.checked_mul(nv).filter(|n| *n <= flat::MAX_LEN).ok_or_else(|| invalid("NURBS face size"))?; + let slice = |v: &[f64], from: usize, len: usize| v.get(from..from + len).map(<[f64]>::to_vec).ok_or_else(|| invalid("NURBS face arrays")); + let pts = slice(flat.f(FACE_NURBS_CVS), 3 * at_.cv, 3 * n)?; + let u_knots = slice(flat.f(FACE_NURBS_U_KNOTS), at_.uk, nu + ou)?; + let v_knots = slice(flat.f(FACE_NURBS_V_KNOTS), at_.vk, nv + ov)?; + let weights = if flat.f(FACE_NURBS_WEIGHTS).is_empty() { vec![1.0; n] } else { slice(flat.f(FACE_NURBS_WEIGHTS), at_.w, n)? }; + *at_ = At { j: j + 1, cv: at_.cv + n, uk: at_.uk + nu + ou, vk: at_.vk + nv + ov, w: at_.w + n }; + let point = |p: usize| -> [f64; 3] { [pts[3 * p], pts[3 * p + 1], pts[3 * p + 2]] }; + Ok(if weights.iter().all(|x| *x == 1.0) { + b::Surface::Spline { u_knots, v_knots, points: (0..nu).map(|r| (0..nv).map(|c| point(r * nv + c)).collect()).collect() } + } else { + let h = |p: usize| { + let (q, wt) = (point(p), weights[p]); + [q[0] * wt, q[1] * wt, q[2] * wt, wt] + }; + b::Surface::RationalSpline { u_knots, v_knots, homogeneous: (0..nu).map(|r| (0..nv).map(|c| h(r * nv + c)).collect()).collect() } + }) + }; + let mut nurbs_at = At { j: 0, cv: 0, uk: 0, vk: 0, w: 0 }; + let forms = flat.i(FACE_NURBS_FORM); + if !forms.is_empty() && forms.len() != n_faces { + return Err(invalid("face NURBS forms")); + } + // The definitions, face by face: each defined face's count, then its reals from `defined`. + let (counts, reals) = (flat.i(FACE_DEFINITION_REAL_COUNT), flat.f(FACE_DEFINITION_REALS)); + let mut defined = 0usize; + let mut k = [0usize; 7]; + let mut out = Vec::with_capacity(n_faces); + for (f, &kind) in kinds.iter().enumerate() { + let slot = usize::try_from(kind).ok().filter(|s| *s < 7).ok_or_else(|| unsupported(format!("SMLib surface kind {kind}")))?; + let i = at(&k, slot, "kind")?; + if let Some(c) = k.get_mut(slot) { + *c += 1; + } + let surface = match kind { + SURFACE_PLANE => { + let f = frame( + v3(flat.f(FACE_PLANE_ORIGIN), i, "plane")?, + v3(flat.f(FACE_PLANE_AXIS), i, "plane")?, + v3(flat.f(FACE_PLANE_REF_DIRECTION), i, "plane")?, + ); + b::Surface::Plane { origin: f.origin, u_axis: f.x_axis, v_axis: f.y_axis } + } + SURFACE_CYLINDER => b::Surface::Cylinder { + frame: frame( + v3(flat.f(FACE_CYLINDER_ORIGIN), i, "cylinder")?, + v3(flat.f(FACE_CYLINDER_AXIS), i, "cylinder")?, + v3(flat.f(FACE_CYLINDER_REF_DIRECTION), i, "cylinder")?, + ), + radius: at(flat.f(FACE_CYLINDER_RADIUS), i, "cylinder")?, + }, + SURFACE_CONE => { + let f = frame( + v3(flat.f(FACE_CONE_ORIGIN), i, "cone")?, + v3(flat.f(FACE_CONE_AXIS), i, "cone")?, + v3(flat.f(FACE_CONE_REF_DIRECTION), i, "cone")?, + ); + let (radius, half) = (at(flat.f(FACE_CONE_RADIUS), i, "cone")?, at(flat.f(FACE_CONE_SEMI_ANGLE), i, "cone")?); + // SMLib's cone of semi-angle 0 is its cylinder, and one within rounding of it (a thread's + // cone of 1e-13 comes out of the trims) is too: the portable record refuses it as a cone. + if half.abs() < 1e-12 { + b::Surface::Cylinder { frame: f, radius } + } else { + b::Surface::Cone { frame: f, radius_at_origin: radius, half_angle: half } + } + } + SURFACE_SPHERE => b::Surface::Sphere { + frame: frame( + v3(flat.f(FACE_SPHERE_CENTER), i, "sphere")?, + v3(flat.f(FACE_SPHERE_AXIS), i, "sphere")?, + v3(flat.f(FACE_SPHERE_REF_DIRECTION), i, "sphere")?, + ), + radius: at(flat.f(FACE_SPHERE_RADIUS), i, "sphere")?, + }, + SURFACE_TORUS => b::Surface::Torus { + frame: frame( + v3(flat.f(FACE_TORUS_ORIGIN), i, "torus")?, + v3(flat.f(FACE_TORUS_AXIS), i, "torus")?, + v3(flat.f(FACE_TORUS_REF_DIRECTION), i, "torus")?, + ), + major_radius: at(flat.f(FACE_TORUS_MAJOR_RADIUS), i, "torus")?, + minor_radius: at(flat.f(FACE_TORUS_MINOR_RADIUS), i, "torus")?, + // SMLib's torus has no tube start: the face's form carries where its tube begins. + tube_start: 0.0, + }, + SURFACE_NURBS => next_nurbs(&mut nurbs_at)?, + SURFACE_BALL_PATCH => { + if at(counts, i, "ball patch definition")? != 4 { + return Err(invalid("ball patch definition")); + } + let d = reals.get(defined..defined + 4).ok_or_else(|| invalid("ball patch definition"))?; + defined += 4; + b::Surface::BallPatch { center: [d[0], d[1], d[2]], radius: d[3] } + } + other => return Err(unsupported(format!("SMLib surface kind {other}"))), + }; + // A NURBS face's or a ball patch's own block came first (the patch's is its form); a form + // follows the analytic face's canonical entry. + let form = match kind { + SURFACE_NURBS => None, + SURFACE_BALL_PATCH if forms.get(f) == Some(&1) => return Err(invalid("ball patch with a NURBS form")), + SURFACE_BALL_PATCH => Some(next_nurbs(&mut nurbs_at)?), + _ if forms.get(f) == Some(&1) => Some(next_nurbs(&mut nurbs_at)?), + _ => None, + }; + // The record's torus is a ring torus. SMLib keeps horn and spindle tori too (a half disc + // revolved about a line through its rim's end, its tube touching the axis, the major + // radius a rounding below the minor): such a face is its NURBS form, unlabelled. + let (surface, form) = match (surface, form) { + (b::Surface::Torus { major_radius, minor_radius, .. }, Some(n)) if !(major_radius > minor_radius) => (n, None), + other => other, + }; + out.push((surface, form)); + } + Ok(out) +} + +/// A circle's or ellipse's frame turned (y reversed) where needed so that its angle grows along +/// `form`, the NURBS the edge runs on over `range`: what [`b::Edge::curve_interval`] reads (an +/// ellipse's radii scale its axes, not the way its angle turns). +fn along(f: b::Frame, form: &b::Curve, range: [f64; 2]) -> Res { + let eval = solidcraft_geom::brep::eval::CurveEval::new(form).map_err(|e| invalid(format!("circle NURBS form: {e}")))?; + let [t0, t1] = range; + let (p, q) = (eval.point(t0), eval.point(t0 + 1e-3 * (t1 - t0))); + let (Some(p), Some(q)) = (p, q) else { return Err(invalid("circle NURBS form")) }; + let (o, x, y) = (Vec3::from(f.origin), Vec3::from(f.x_axis), Vec3::from(f.y_axis)); + let angle = |s: Vec3| (s - o).dot(y).atan2((s - o).dot(x)); + let step = (angle(q) - angle(p)).rem_euclid(TAU); + Ok(if step > std::f64::consts::PI { b::Frame { y_axis: [-f.y_axis[0], -f.y_axis[1], -f.y_axis[2]], ..f } } else { f }) +} + +/// A NURBS curve: full knots, cartesian control points and weights. +struct Nurbs { + knots: Vec, + points: Vec<[f64; 3]>, + weights: Vec, +} + +impl Nurbs { + fn record(&self) -> b::Curve { + if self.weights.iter().all(|w| *w == 1.0) { + b::Curve::Spline { knots: self.knots.clone(), points: self.points.clone() } + } else { + b::Curve::RationalSpline { + knots: self.knots.clone(), + homogeneous: self.points.iter().zip(&self.weights).map(|(p, w)| [p[0] * w, p[1] * w, p[2] * w, *w]).collect(), + } + } + } +} + +/// How a UV trim's parameter (SMLib's edge parameter, as the arrays carry it) becomes the edge +/// record's: t ↦ scale · t + offset, scale > 0. None where the record's parameter is not an +/// affine image of SMLib's (a circle or ellipse, whose angle is not its NURBS parameter). +type TrimMap = Option<[f64; 2]>; + +/// Each edge's record and interval (in SMLib's direction along it) and its [`TrimMap`], and how +/// many edges are NURBS. +fn curves(flat: View, n_edges: usize) -> Res<(Vec<(b::Curve, Option, [f64; 2], TrimMap)>, usize)> { + let kinds = flat.i(EDGE_CURVE_TYPE); + let range = flat.f(EDGE_RANGE); + if kinds.len() != n_edges || range.len() != 2 * n_edges { + return Err(invalid("edge kinds or ranges")); + } + let forms = flat.i(EDGE_NURBS_FORM); + if !forms.is_empty() && forms.len() != n_edges { + return Err(invalid("edge NURBS forms")); + } + let (mut nurbs, mut lines, mut circles, mut ellipses) = (0usize, 0usize, 0usize, 0usize); + let (mut cv, mut kn) = (0usize, 0usize); + // The next NURBS block, in edge order: a NURBS edge's curve or a circle's or ellipse's form. + let mut next_nurbs = || -> Res { + let n = count(at(flat.i(EDGE_NURBS_VERTEX_COUNT), nurbs, "NURBS edge")?, "NURBS edge")?; + let o = count(at(flat.i(EDGE_NURBS_ORDER), nurbs, "NURBS edge")?, "NURBS edge")?; + let cvs = flat.f(EDGE_NURBS_CVS).get(3 * cv..3 * (cv + n)).ok_or_else(|| invalid("NURBS edge points"))?; + let knots = flat.f(EDGE_NURBS_KNOTS).get(kn..kn + n + o).ok_or_else(|| invalid("NURBS edge knots"))?.to_vec(); + let weights = match flat.f(EDGE_NURBS_WEIGHTS) { + [] => vec![1.0; n], + w => w.get(cv..cv + n).ok_or_else(|| invalid("NURBS edge weights"))?.to_vec(), + }; + nurbs += 1; + cv += n; + kn += n + o; + Ok(Nurbs { knots, points: cvs.as_chunks::<3>().0.to_vec(), weights }) + }; + let mut kept = 0usize; + let mut out = Vec::with_capacity(n_edges); + for (e, &kind) in kinds.iter().enumerate() { + let r = [at(range, 2 * e, "edge range")?, at(range, 2 * e + 1, "edge range")?]; + out.push(match kind { + CURVE_LINE => { + let (o, d) = (v3(flat.f(EDGE_LINE_ORIGIN), lines, "line")?, v3(flat.f(EDGE_LINE_DIRECTION), lines, "line")?); + lines += 1; + // The C side maps a line's trims onto the line's STEP parameter, the record's. + (b::Curve::Line { start: o, end: [o[0] + d[0], o[1] + d[1], o[2] + d[2]] }, None, r, Some([1.0, 0.0])) + } + CURVE_CIRCLE => { + let f = frame( + v3(flat.f(EDGE_CIRCLE_CENTER), circles, "circle")?, + v3(flat.f(EDGE_CIRCLE_AXIS), circles, "circle")?, + v3(flat.f(EDGE_CIRCLE_REF_DIRECTION), circles, "circle")?, + ); + let radius = at(flat.f(EDGE_CIRCLE_RADIUS), circles, "circle")?; + circles += 1; + // A circle with its NURBS form is parameterised on it: its range and the trims + // on it are that NURBS's, so the trims carry over as they are. + if forms.get(e) == Some(&1) { + let form = next_nurbs()?.record(); + (b::Curve::Circle { frame: along(f, &form, r)?, radius }, Some(form), r, Some([1.0, 0.0])) + } else { + (b::Curve::Circle { frame: f, radius }, None, r, None) + } + } + CURVE_ELLIPSE => { + let f = frame( + v3(flat.f(EDGE_ELLIPSE_CENTER), ellipses, "ellipse")?, + v3(flat.f(EDGE_ELLIPSE_AXIS), ellipses, "ellipse")?, + v3(flat.f(EDGE_ELLIPSE_REF_DIRECTION), ellipses, "ellipse")?, + ); + let radii = [at(flat.f(EDGE_ELLIPSE_X_RADIUS), ellipses, "ellipse")?, at(flat.f(EDGE_ELLIPSE_Y_RADIUS), ellipses, "ellipse")?]; + ellipses += 1; + // Like a circle: on its NURBS form, the trims on it carry over as they are. + if forms.get(e) == Some(&1) { + let form = next_nurbs()?.record(); + (b::Curve::Ellipse { frame: along(f, &form, r)?, radii }, Some(form), r, Some([1.0, 0.0])) + } else { + (b::Curve::Ellipse { frame: f, radii }, None, r, None) + } + } + CURVE_NURBS => { + let c = next_nurbs()?.record(); + // A NURBS edge stays the NURBS SMLib holds, its trims on its own parameter: SMLib + // gives lines, circles and ellipses as their own kinds, and nothing is recognised here. + // SMLib's interval may start or end a rounding past its knots (a variable round's + // end trimmed by a cylinder, ladder 07-fillets/012: 7e-15 before the first knot). + kept += 1; + let r = onto(r, c.natural()); + (c, None, r, Some([1.0, 0.0])) + } + other => return Err(unsupported(format!("SMLib curve kind {other}"))), + }); + } + Ok((out, kept)) +} + +/// Each edgeuse record's UV trim as SMLib holds it (`EDGEUSE_NURBS_*`), along its edgeuse (the +/// C side writes a trim whose edgeuse runs against its edge reversed, on the reversed parameter +/// a + b − t of the edge's interval [a, b]); none where the arrays carry none for it (an analytic +/// face's, or an analytic edge's). +fn trims(flat: View, n_edgeuses: usize) -> Res>> { + let (counts, orders) = (flat.i(EDGEUSE_NURBS_VERTEX_COUNT), flat.i(EDGEUSE_NURBS_ORDER)); + if counts.is_empty() && orders.is_empty() { + return Ok(vec![None; n_edgeuses]); + } + if counts.len() != n_edgeuses || orders.len() != n_edgeuses { + return Err(invalid("UV trim arrays")); + } + let (cvs, knots, weights) = (flat.f(EDGEUSE_NURBS_CVS), flat.f(EDGEUSE_NURBS_KNOTS), flat.f(EDGEUSE_NURBS_WEIGHTS)); + let (mut cv, mut kn) = (0usize, 0usize); + let mut out = Vec::with_capacity(n_edgeuses); + for (&n, &o) in counts.iter().zip(orders) { + let (n, o) = (count(n, "UV trim")?, count(o, "UV trim")?); + if n == 0 || o == 0 { + out.push(None); + continue; + } + if o < 2 || n < o { + return Err(invalid("UV trim order")); + } + let pts = cvs.get(2 * cv..2 * (cv + n)).ok_or_else(|| invalid("UV trim points"))?; + let k = knots.get(kn..kn + n + o).ok_or_else(|| invalid("UV trim knots"))?.to_vec(); + let w = match weights { + [] => vec![1.0; n], + w => w.get(cv..cv + n).ok_or_else(|| invalid("UV trim weights"))?.to_vec(), + }; + cv += n; + kn += n + o; + let pts = pts.as_chunks::<2>().0; + out.push(Some(if w.iter().all(|x| *x == 1.0) { + b::Curve2::Spline { knots: k, points: pts.to_vec() } + } else { + b::Curve2::RationalSpline { knots: k, homogeneous: pts.iter().zip(&w).map(|(p, w)| [p[0] * w, p[1] * w, *w]).collect() } + })); + } + if 2 * cv != cvs.len() || kn != knots.len() { + return Err(invalid("UV trim arrays: blocks do not cover them")); + } + Ok(out) +} + +/// A trim along its edge, its parameter moved onto the edge record's ([`TrimMap`]): one whose +/// edgeuse runs against the edge (`same` false) reversed exactly (control points in reverse +/// order, knots t ↦ a + b − t), then the knots mapped. SMLib keeps a trim on its edge's +/// interval; where the two ends differ by the rounding of SMLib's own or this remap (within the +/// schema's 10⁻⁹ of the interval's magnitude, at least 1), the knots at the trim's ends are the +/// edge record's interval ends, so the pcurve is defined there; farther apart is an error. +fn mapped(trim: &b::Curve2, same: bool, [scale, offset]: [f64; 2], [t0, t1]: [f64; 2]) -> Res { + fn along(knots: &[f64], points: &[T], same: bool) -> (Vec, Vec) { + if same { + return (knots.to_vec(), points.to_vec()); + } + let (a, b) = (knots.first().copied().unwrap_or(0.0), knots.last().copied().unwrap_or(0.0)); + (knots.iter().rev().map(|t| a + b - t).collect(), points.iter().rev().cloned().collect()) + } + let map = |k: Vec, n: usize| -> Res> { + let mut k: Vec = k.into_iter().map(|t| scale * t + offset).collect(); + let degree = k.len().checked_sub(n + 1).ok_or_else(|| invalid("UV trim knots"))?; + let (a, z) = (at(&k, degree, "UV trim knots")?, at(&k, n, "UV trim knots")?); + let slack = 1e-9 * t0.abs().max(t1.abs()).max(1.0); + if (a - t0).abs() > slack || (z - t1).abs() > slack { + return Err(invalid(format!("a UV trim on [{a}, {z}], its edge on [{t0}, {t1}]"))); + } + k.iter_mut().filter(|x| **x == a).for_each(|x| *x = t0); + k.iter_mut().filter(|x| **x == z).for_each(|x| *x = t1); + Ok(k) + }; + Ok(match trim { + b::Curve2::Spline { knots, points } => { + let (k, points) = along(knots, points, same); + b::Curve2::Spline { knots: map(k, points.len())?, points } + } + b::Curve2::RationalSpline { knots, homogeneous } => { + let (k, homogeneous) = along(knots, homogeneous, same); + b::Curve2::RationalSpline { knots: map(k, homogeneous.len())?, homogeneous } + } + }) +} + +/// A domain side or an edge's interval moved onto the natural range where it overshoots it by +/// rounding (a sphere's latitudes, a cone's apex, a NURBS edge's end knots). +fn onto(r: [f64; 2], natural: b::Natural) -> [f64; 2] { + match natural { + b::Natural::Range(lo, hi) => { + let slack = 1e-12 * (1.0 + r[0].abs().max(r[1].abs())); + let snap = |x: f64| { + if x < lo && x >= lo - slack { + lo + } else if x > hi && x <= hi + slack { + hi + } else { + x + } + }; + [snap(r[0]), snap(r[1])] + } + b::Natural::Periodic => r, + } +} + +// ---- The mapping ---------------------------------------------------------------------------- + +/// One face before renumbering: loops relative to the record's normal, as (edge, forward). +#[derive(Clone)] +struct Face { + /// The NURBS form the face's (u, v) are on (`FACE_NURBS_FORM`), when it differs from `surface`. + nurbs: Option, + surface: b::Surface, + domain: [[f64; 2]; 2], + /// SMLib's natural normal is the record's. + agrees: bool, + loops: Vec, + /// The array edgeuse record of each use, loop by loop as `loops` (none for a vertex loop). + records: Vec>, + /// Each use's pcurve, SMLib's own UV trim on the record's parameters, loop by loop as + /// `loops`: on a B-spline face, for an edge whose record's parameter is an affine image of + /// SMLib's; none elsewhere. + given: Vec>>, +} + +#[derive(Clone)] +enum Loop { + Edges(Vec<(u32, bool)>), + Vertex(u32), +} + +/// One edge before renumbering, along its record's parameter. +#[derive(Clone)] +struct Edge { + curve: b::Curve, + /// The NURBS form the edge's parameter is on (`EDGE_NURBS_FORM`), when it differs from `curve`. + nurbs: Option, + interval: [f64; 2], + vertices: [u32; 2], + /// The record's parameter runs against SMLib's edge direction. + reversed: bool, + /// How SMLib's UV trims of this edge map onto the record's parameter. + trim_map: TrimMap, +} + +/// The schema 4 B-rep of SMLib's flat arrays: mapped, renumbered canonically and validated. +pub fn native(arrays: &Arrays) -> Res<(b::Brep, Report)> { + native_ordered(arrays).map(|(brep, report, _)| (brep, report)) +} + +/// [`native`], with the canonical place of each array face and edge. +fn native_ordered(arrays: &Arrays) -> Res<(b::Brep, Report, Order)> { + let flat = View(arrays); + let mut report = Report::default(); + if arrays.ints.values().map(Vec::len).chain(arrays.reals.values().map(Vec::len)).any(|n| n > flat::MAX_LEN) { + return Err(invalid("array too long")); + } + + // Tolerances exactly as SMLib gives them: each edge's and vertex's own, the body's the smallest + // of them (only what needs more carries more). Without per-item tolerances, every tolerance is + // the largest SMLib reports for the body. Nothing of ours is added: the record's tolerances go + // back into SMLib, which makes its approximations to them. + let largest = match flat.f(TOLERANCE) { + [t] if t.is_finite() && *t > 0.0 => *t, + _ => return Err(invalid("tolerance")), + }; + let own = |id: i32, n: usize| -> Res>> { + match flat.f(id) { + [] => Ok(None), + t if t.len() == n && t.iter().all(|x| x.is_finite() && *x > 0.0) => Ok(Some(t.to_vec())), + _ => Err(invalid("edge or vertex tolerances")), + } + }; + let n_vertex_points = flat.f(VERTEX_POSITION).len() / 3; + let edge_tolerances = own(EDGE_TOLERANCE, flat.i(EDGE_CURVE_TYPE).len())?; + let vertex_tolerances = own(VERTEX_TOLERANCE, n_vertex_points)?; + let tolerance = match (&edge_tolerances, &vertex_tolerances) { + (Some(e), Some(v)) => e.iter().chain(v).copied().fold(largest, f64::min), + _ => largest, + }; + let tolerances = Tolerances { body: tolerance, edges: edge_tolerances, vertices: vertex_tolerances }; + + // Topology blocks. + let n_faceuses = flat.i(FACEUSE_FACE).len(); + let n_faces = flat.i(FACE_LOOP_COUNT).len(); + let n_loops = flat.i(LOOP_EDGEUSE_COUNT).len(); + let n_edgeuses = flat.i(EDGEUSE_EDGE).len(); + let n_edges = flat.i(EDGE_CURVE_TYPE).len(); + let n_vertices = flat.f(VERTEX_POSITION).len() / 3; + if flat.f(VERTEX_POSITION).len() != 3 * n_vertices + || flat.i(FACEUSE_ORIENTATION).len() != n_faceuses + || flat.i(EDGEUSE_ORIENTATION).len() != n_edgeuses + || flat.i(LOOP_VERTEX).len() != n_loops + || flat.i(EDGE_VERTICES).len() != 2 * n_edges + { + return Err(invalid("array lengths")); + } + let n_shells = flat.i(SHELL_FACEUSE_COUNT).len(); + if n_shells > 2 * b::MAX_SHELLS || flat.i(SHELL_WIRE_EDGE_COUNT).len() != n_shells || flat.i(SHELL_POINT_TYPE).len() != n_shells { + return Err(invalid("shell arrays")); + } + if flat.i(SHELL_WIRE_EDGE_COUNT).iter().any(|c| *c != 0) || flat.i(SHELL_POINT_TYPE).iter().any(|c| *c != 0) { + return Err(unsupported("wire and point shells from SMLib")); + } + let region_shells = blocks(flat.i(REGION_SHELL_COUNT), n_shells, "region shells")?; + if region_shells.is_empty() || flat.i(REGION_TYPE).len() != region_shells.len() { + return Err(invalid("regions")); + } + let shell_faceuses = blocks(flat.i(SHELL_FACEUSE_COUNT), n_faceuses, "shell faceuses")?; + let face_loops = blocks(flat.i(FACE_LOOP_COUNT), n_loops, "face loops")?; + let loop_edgeuses = blocks(flat.i(LOOP_EDGEUSE_COUNT), n_edgeuses, "loop edgeuses")?; + + // Edges along their records' parameters. + let (records, kept) = curves(flat, n_edges)?; + report.nurbs_edges = kept; + let mut edges = Vec::with_capacity(n_edges); + for (e, (curve, nurbs, [a, z], trim_map)) in records.into_iter().enumerate() { + if !(a.is_finite() && z.is_finite()) || a == z { + return Err(invalid("edge interval")); + } + let start = index(idx(at(flat.i(EDGE_VERTICES), 2 * e, "edge vertices")?, n_vertices, "edge vertex")?)?; + let end = index(idx(at(flat.i(EDGE_VERTICES), 2 * e + 1, "edge vertices")?, n_vertices, "edge vertex")?)?; + let reversed = a > z; + edges.push(Edge { + curve, + nurbs, + interval: if reversed { [z, a] } else { [a, z] }, + vertices: if reversed { [end, start] } else { [start, end] }, + reversed, + trim_map, + }); + } + + // Faces: loops as SMLib keeps them, then turned where SMLib's normal is not the record's. + let surfaces = surfaces(flat, n_faces)?; + let trims = trims(flat, n_edgeuses)?; + let range = flat.f(FACE_RANGE); + if range.len() != 4 * n_faces { + return Err(invalid("face ranges")); + } + let mut faces = Vec::with_capacity(n_faces); + for (f, ((surface, nurbs), loops)) in surfaces.into_iter().zip(&face_loops).enumerate() { + let r = range.get(4 * f..4 * f + 4).ok_or_else(|| invalid("face range"))?; + // A face with a NURBS form is parameterised on it: its range and trims are that NURBS's. + let params = nurbs.as_ref().unwrap_or(&surface); + let natural = solidcraft_geom::brep::label::surface_natural(params); + let domain = [onto([r[0], r[2]], natural[0]), onto([r[1], r[3]], natural[1])]; + // SMLib's own trims are taken where the arrays carry them: B-spline faces, NURBS forms, and + // planes (mapped onto the plane's own (u, v) by the export). + let spline = matches!(params, b::Surface::Spline { .. } | b::Surface::RationalSpline { .. } | b::Surface::Plane { .. }); + let mut out = Vec::with_capacity(loops.len()); + let mut records = Vec::with_capacity(loops.len()); + let mut given = Vec::with_capacity(loops.len()); + for l in loops.clone() { + let uses = loop_edgeuses.get(l).ok_or_else(|| invalid("loop"))?; + if uses.is_empty() { + let v = idx(at(flat.i(LOOP_VERTEX), l, "loop vertex")?, n_vertices, "loop vertex")?; + out.push(Loop::Vertex(index(v)?)); + records.push(Vec::new()); + given.push(Vec::new()); + continue; + } + let mut l = Vec::with_capacity(uses.len()); + let mut g = Vec::with_capacity(uses.len()); + records.push(uses.clone().collect()); + for u in uses.clone() { + let e = idx(at(flat.i(EDGEUSE_EDGE), u, "edgeuse")?, n_edges, "edgeuse edge")?; + let same = at(flat.i(EDGEUSE_ORIENTATION), u, "edgeuse")? == 1; + let edge = edges.get(e).ok_or_else(|| invalid("edge"))?; + l.push((index(e)?, same != edge.reversed)); + let trim = trims.get(u).ok_or_else(|| invalid("edgeuse"))?.as_ref(); + g.push(match (spline, edge.trim_map, trim) { + (true, Some(map), Some(trim)) => Some(mapped(trim, same, map, edge.interval)?), + _ => None, + }); + } + out.push(Loop::Edges(l)); + given.push(g); + } + faces.push(Face { nurbs, surface, domain, agrees: true, loops: out, records, given }); + } + for face in &mut faces { + if outer_area(face, &edges, largest)? < 0.0 { + face.agrees = false; + for l in &mut face.loops { + if let Loop::Edges(uses) = l { + uses.reverse(); + uses.iter_mut().for_each(|u| u.1 = !u.1); + } + } + face.records.iter_mut().for_each(|r| r.reverse()); + face.given.iter_mut().for_each(|g| g.reverse()); + report.reversed_faces += 1; + } + } + + // Shells: SMLib's two runtime sides of a closed boundary become one record, its faces as the + // side in the region that is not material uses them. + let material = |r: usize| r > 0 && flat.i(REGION_TYPE).get(r) == Some(&0); + let mut region_of = vec![0usize; n_shells]; + for (r, shells) in region_shells.iter().enumerate() { + for s in shells.clone() { + if let Some(slot) = region_of.get_mut(s) { + *slot = r; + } + } + } + let faceuse = |fu: usize| -> Res<(usize, bool)> { + Ok((idx(at(flat.i(FACEUSE_FACE), fu, "faceuse")?, n_faces, "faceuse face")?, at(flat.i(FACEUSE_ORIENTATION), fu, "faceuse")? == 1)) + }; + let mut face_uses: Vec> = vec![Vec::new(); n_faces]; + for (s, uses) in shell_faceuses.iter().enumerate() { + for fu in uses.clone() { + let (f, same) = faceuse(fu)?; + face_uses.get_mut(f).ok_or_else(|| invalid("face"))?.push((s, same)); + } + } + // Each record shell is one closed boundary of material: the faces of one runtime shell on the + // material side, as the empty side uses them. Solids touching along an edge or at a vertex + // share their empty side's runtime shell but not their material side's, so each gets its own + // record shell (the edges and vertices they share are split below). A sheet's one shell holds + // both uses of each face: the `same` one is kept. + let mut groups: Vec = Vec::new(); + for (s, uses) in shell_faceuses.iter().enumerate() { + for fu in uses.clone() { + let (f, same) = faceuse(fu)?; + let key = match face_uses.get(f).map(Vec::as_slice) { + Some([(a, _), (b, _)]) if a == b => { + if !same { + continue; + } + Side::Sheet(*a) + } + Some([(a, _), (b, _)]) => { + let other = if *a == s { *b } else { *a }; + let (here, there) = (region_of.get(s).copied().unwrap_or(0), region_of.get(other).copied().unwrap_or(0)); + match (material(here), material(there)) { + (false, true) => Side::Solid(other), + (true, false) => continue, + _ => return Err(unsupported("a face between two material regions or two empty ones")), + } + } + _ => return Err(invalid("a face without its two uses")), + }; + let agrees = faces.get(f).ok_or_else(|| invalid("face"))?.agrees; + let at = match groups.iter().position(|g| g.side == key) { + Some(at) => at, + None => { + groups.push(Group { side: key, empty: Vec::new(), faces: Vec::new() }); + groups.len() - 1 + } + }; + let group = groups.get_mut(at).ok_or_else(|| invalid("shell"))?; + if !group.empty.contains(&s) { + group.empty.push(s); + } + group.faces.push((index(f)?, same == agrees)); + } + } + let mut regions = record_regions(®ion_shells, ®ion_of, &groups, material)?; + let shells: Vec> = groups.into_iter().map(|g| g.faces).collect(); + // Shells renumbered in first appearance walking the regions. + let mut order: Vec = Vec::new(); + for r in ®ions { + for s in &r.shells { + if !order.contains(s) { + order.push(*s); + } + } + } + let renumber: HashMap = order.iter().enumerate().map(|(new, old)| Ok((*old, index(new)?))).collect::>()?; + for r in &mut regions { + r.shells.iter_mut().for_each(|s| *s = renumber.get(s).copied().unwrap_or(*s)); + } + let shells: Vec> = order.iter().filter_map(|s| shells.get(*s as usize).cloned()).collect(); + + // Round each edge: SMLib's radial order of its uses, and the side of each face the material + // is on, which say which faces bound the same material where a solid touches itself. + let material_same = + face_uses.iter().map(|uses| uses.iter().find(|(s, _)| material(region_of.get(*s).copied().unwrap_or(0))).map(|(_, same)| *same)).collect(); + let radial = radial(flat, n_edgeuses, n_edges, material_same)?; + + let parts = Parts { faces, edges, shells, regions, radial }; + let made = match canonical(parts.clone(), n_vertices, flat, &tolerances) { + // SMLib's own tolerance for an edge or vertex can understate what its approximated + // geometry needs here (a blend's end curve 2.3e-5 mm off its plane at 2e-5): then the + // largest SMLib reports for the body, everywhere, as without per-edge tolerances. + Err(e) if tolerances.edges.is_some() || tolerances.vertices.is_some() => { + let uniform = Tolerances { body: largest, edges: None, vertices: None }; + canonical(parts, n_vertices, flat, &uniform).map_err(|_| e) + } + other => other, + }; + made.map(|(brep, order)| (brep, report, order)) +} + +/// Which runtime shell a record shell is made from. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Side { + /// The material side of a closed boundary. + Solid(usize), + /// A sheet's one shell, both uses of each face in it. + Sheet(usize), +} + +/// One record shell: its runtime shell, the runtime shells on its empty side, and its faces as +/// the empty side uses them. +struct Group { + side: Side, + empty: Vec, + faces: Vec<(u32, bool)>, +} + +/// The record's regions, each listing its record shells (`groups` by index), outer first. +/// +/// A material region is SMLib's own. An empty one is too, except where solids touch along a +/// closed chain of edges round a pocket of empty space (a loft whose wide end is flush with a +/// block's sides cuts the slab above it loose): SMLib keeps the pocket as a void of its own, +/// bounded by faces of more than one solid, or of one solid on both sides of where it touches +/// itself. The record splits what the solids share, so no shell bounds the pocket on its own: +/// each solid's one closed boundary faces both the pocket and the empty space round the solids, +/// and the pocket is part of that space. Empty regions a solid's boundary faces together are one +/// record region: the infinite region where it is among them, otherwise the void whose outer +/// shell bounds it alone (its solids face no other region of the set). +fn record_regions( + region_shells: &[std::ops::Range], + region_of: &[usize], + groups: &[Group], + material: impl Fn(usize) -> bool, +) -> Res> { + let n = region_shells.len(); + let region = |s: usize| region_of.get(s).copied().ok_or_else(|| invalid("shell region")); + // The empty regions each solid's boundary faces, joined (each set's root its lowest region). + let mut root: Vec = (0..n).collect(); + fn find(root: &[usize], mut r: usize) -> usize { + while let Some(&up) = root.get(r).filter(|up| **up != r) { + r = up; + } + r + } + for g in groups { + let mut it = g.empty.iter(); + let Some(&first) = it.next() else { continue }; + let mut a = find(&root, region(first)?); + for &s in it { + let b = find(&root, region(s)?); + let (lo, hi) = (a.min(b), a.max(b)); + if let Some(slot) = root.get_mut(hi) { + *slot = lo; + } + a = lo; + } + } + let set: Vec = (0..n).map(|r| find(&root, r)).collect(); + // A region's outer runtime shell bounds it alone when every solid it faces faces no region + // but this one. + let alone = |r: usize| -> Res { + let Some(outer) = region_shells.get(r).and_then(|b| (b.start < b.end).then_some(b.start)) else { return Ok(false) }; + for g in groups.iter().filter(|g| g.empty.contains(&outer)) { + for &s in &g.empty { + if region(s)? != r { + return Ok(false); + } + } + } + Ok(true) + }; + // The record region of each set of empty regions. + let mut kept = vec![None; n]; + for r in 0..n { + let s = set.get(r).copied().unwrap_or(r); + if material(r) || s != r { + continue; + } + let members: Vec = (0..n).filter(|q| set.get(*q) == Some(&r)).collect(); + let keep = if members.len() == 1 || members.contains(&0) { + r + } else { + let mut candidates = Vec::new(); + for &q in &members { + if alone(q)? { + candidates.push(q); + } + } + match candidates.as_slice() { + [q] => *q, + _ => return Err(unsupported("solids touching round pockets of empty space that no one shell bounds")), + } + }; + if let Some(slot) = kept.get_mut(r) { + *slot = Some(keep); + } + } + let mut regions = Vec::with_capacity(n); + for (r, block) in region_shells.iter().enumerate() { + let mut listed: Vec = Vec::new(); + let list = |s: usize, listed: &mut Vec| -> Res<()> { + for (g, group) in groups.iter().enumerate() { + let here = match group.side { + Side::Solid(m) => m == s || group.empty.contains(&s), + Side::Sheet(a) => a == s, + }; + let id = index(g)?; + if here && !listed.contains(&id) { + listed.push(id); + } + } + Ok(()) + }; + if material(r) { + for s in block.clone() { + list(s, &mut listed)?; + } + } else { + let s = set.get(r).copied().unwrap_or(r); + if kept.get(s).copied().flatten() != Some(r) { + continue; + } + // This region's shells first, its outer shell the record region's, then the pockets'. + let members = std::iter::once(r).chain((0..n).filter(|q| *q != r && set.get(*q) == Some(&s))); + for q in members { + for s in region_shells.get(q).cloned().unwrap_or_default() { + list(s, &mut listed)?; + } + } + } + regions.push(b::Region { shells: listed, void: r > 0 && !material(r) }); + } + Ok(regions) +} + +/// The mapped records before renumbering. +#[derive(Clone)] +struct Parts { + faces: Vec, + edges: Vec, + shells: Vec>, + regions: Vec, + radial: Option, +} + +/// SMLib's order of the faces round each edge (`EDGEUSE_NEXT_RADIAL`, `EDGEUSE_RADIAL_ENTRY`), +/// read where the arrays have it. Each edgeuse record is a face's two sides along the edge; a +/// right-hand traversal round the edge meets one side of each record, then its other side, then +/// the next record. Between two records lies one sector of space round the edge, empty or +/// material. +#[derive(Clone)] +struct Radial { + /// The next record round the edge. + next: Vec, + /// The traversal enters the record from its face's `same` side (SMLib's top edgeuse, the + /// one on the faceuse the surface normal points out of) and leaves from the other. + top_entry: Vec, + /// Per array face: whether the material is on its `same` side; none for a face with no + /// material on either side (a sheet's). + material_same: Vec>, +} + +/// The radial arrays, checked: in range, entries 0 or 1, each edge's records one cycle or more. +/// None where the arrays have neither (the export of a library without them). +fn radial(flat: View, n_edgeuses: usize, n_edges: usize, material_same: Vec>) -> Res> { + let (next, entry) = (flat.i(EDGEUSE_NEXT_RADIAL), flat.i(EDGEUSE_RADIAL_ENTRY)); + if next.is_empty() && entry.is_empty() { + return Ok(None); + } + if next.len() != n_edgeuses || entry.len() != n_edgeuses { + return Err(invalid("radial arrays")); + } + let edge = flat.i(EDGEUSE_EDGE).iter().map(|e| idx(*e, n_edges, "edgeuse edge")).collect::>>()?; + let next = next.iter().map(|n| idx(*n, n_edgeuses, "next radial edgeuse")).collect::>>()?; + // Each record is some record's next (the lists are cycles), on its own edge. + let mut reached = vec![false; n_edgeuses]; + for (u, n) in next.iter().enumerate() { + let slot = reached.get_mut(*n).ok_or_else(|| invalid("next radial edgeuse"))?; + if *slot || edge.get(u) != edge.get(*n) { + return Err(invalid("a radial list that is not a cycle round its edge")); + } + *slot = true; + } + let top_entry = entry + .iter() + .map(|x| match x { + 0 => Ok(false), + 1 => Ok(true), + _ => Err(invalid("radial entry")), + }) + .collect::>>()?; + Ok(Some(Radial { next, top_entry, material_same })) +} + +/// The record in canonical order: faces in first appearance through the shells, edges through +/// the faces (a face whose first oriented face is reversed walked backwards), vertices through +/// the edges and then the vertex loops, with each face's pcurves; validated. With it, the +/// canonical index of each array face and edge. +/// The record's tolerances: the body's, and each array edge's and vertex's own where given. +struct Tolerances { + body: f64, + edges: Option>, + vertices: Option>, +} + +impl Tolerances { + fn edge(&self, e: usize) -> f64 { + self.edges.as_ref().and_then(|t| t.get(e)).copied().unwrap_or(self.body) + } + + fn vertex(&self, v: usize) -> f64 { + self.vertices.as_ref().and_then(|t| t.get(v)).copied().unwrap_or(self.body) + } +} + +fn canonical(parts: Parts, n_vertices: usize, flat: View, tolerances: &Tolerances) -> Res<(b::Brep, Order)> { + let tolerance = tolerances.body; + let Parts { mut faces, mut edges, shells, regions, radial } = parts; + let n_edges = edges.len(); + // A copy made by the splits keeps the tolerance of the array edge or vertex it copies. + let (mut edge_source, vertex_source) = split_shared(&mut faces, &mut edges, &shells, n_vertices)?; + split_touching(&mut faces, &mut edges, &mut edge_source, radial.as_ref())?; + let n_vertices = vertex_source.len(); + let mut face_new: Vec> = vec![None; faces.len()]; + let (mut face_order, mut direction) = (Vec::new(), Vec::new()); + for shell in &shells { + for &(f, forward) in shell { + let slot = face_new.get_mut(f as usize).ok_or_else(|| invalid("face"))?; + if slot.is_none() { + *slot = Some(index(face_order.len())?); + face_order.push(f); + direction.push(forward); + } + } + } + if face_order.len() != faces.len() { + return Err(invalid("a face no shell uses")); + } + let mut edge_new: Vec> = vec![None; edges.len()]; + let mut edge_order = Vec::new(); + let mut edge_uses: Vec> = Vec::new(); + for (fi, (&f, &forward)) in face_order.iter().zip(&direction).enumerate() { + let face = faces.get(f as usize).ok_or_else(|| invalid("face"))?; + for (li, l) in face.loops.iter().enumerate() { + let Loop::Edges(uses) = l else { continue }; + let n = uses.len(); + for k in 0..n { + let p = if forward { k } else { n - 1 - k }; + let &(e, fwd) = uses.get(p).ok_or_else(|| invalid("loop"))?; + let slot = edge_new.get_mut(e as usize).ok_or_else(|| invalid("edge"))?; + let id = match slot { + Some(id) => *id, + None => { + let id = index(edge_order.len())?; + *slot = Some(id); + edge_order.push(e); + edge_uses.push(Vec::new()); + id + } + }; + let at = b::EdgeUseRef { face: index(fi)?, r#loop: index(li)?, position: index(p)?, upper: !fwd }; + edge_uses.get_mut(id as usize).ok_or_else(|| invalid("edge"))?.push(at); + } + } + } + if edge_order.len() != edges.len() { + return Err(unsupported("wire edges from SMLib")); + } + if edge_uses.iter().any(|u| u.len() > 2) { + return Err(unsupported("a solid touching itself along an edge")); + } + let mut vertex_new: Vec> = vec![None; n_vertices]; + let mut vertex_order = Vec::new(); + let mut visit = |v: u32| -> Res { + let slot = vertex_new.get_mut(v as usize).ok_or_else(|| invalid("vertex"))?; + Ok(match slot { + Some(id) => *id, + None => { + let id = index(vertex_order.len())?; + *slot = Some(id); + vertex_order.push(v); + id + } + }) + }; + let mut edge_vertices = Vec::with_capacity(edge_order.len()); + for &e in &edge_order { + let [a, z] = edges.get(e as usize).ok_or_else(|| invalid("edge"))?.vertices; + edge_vertices.push([visit(a)?, visit(z)?]); + } + let mut loop_vertices: HashMap<(usize, usize), u32> = HashMap::new(); + for (fi, &f) in face_order.iter().enumerate() { + for (li, l) in faces.get(f as usize).ok_or_else(|| invalid("face"))?.loops.iter().enumerate() { + if let Loop::Vertex(v) = l { + loop_vertices.insert((fi, li), visit(*v)?); + } + } + } + if vertex_order.len() != n_vertices { + return Err(unsupported("vertices no edge or vertex loop uses")); + } + let edge_id = |e: u32| edge_new.get(e as usize).copied().flatten().ok_or_else(|| invalid("edge")); + + let mut edge_records = Vec::with_capacity(edge_order.len()); + for ((&e, vertices), uses) in edge_order.iter().zip(edge_vertices).zip(edge_uses) { + let edge = edges.get(e as usize).ok_or_else(|| invalid("edge"))?; + let source = edge_source.get(e as usize).copied().ok_or_else(|| invalid("edge"))?; + edge_records.push(b::Edge { + nurbs: edge.nurbs.clone(), + curve: edge.curve.clone(), + interval: edge.interval, + vertices, + tolerance: tolerances.edge(source), + uses, + }); + } + let record_geometry = |e: u32| { + let edge = edge_records.get(e as usize)?; + Some(EdgeGeometry { curve: edge.nurbs.as_ref().unwrap_or(&edge.curve), interval: edge.interval, tolerance: edge.tolerance }) + }; + let mut face_records = Vec::with_capacity(face_order.len()); + for (fi, &f) in face_order.iter().enumerate() { + let face = faces.get(f as usize).ok_or_else(|| invalid("face"))?; + let renumbered: Vec = face + .loops + .iter() + .map(|l| match l { + Loop::Edges(u) => u.iter().map(|&(e, fw)| Ok((edge_id(e)?, fw))).collect::>>().map(Loop::Edges), + Loop::Vertex(v) => Ok(Loop::Vertex(*v)), + }) + .collect::>()?; + let mut curves = + pcurves(face.nurbs.as_ref().unwrap_or(&face.surface), face.domain, &renumbered, &face.given, record_geometry, tolerance)?.into_iter(); + let mut loops = Vec::with_capacity(renumbered.len()); + for (li, l) in renumbered.iter().enumerate() { + loops.push(match l { + Loop::Vertex(_) => b::Loop::Vertex { vertex: *loop_vertices.get(&(fi, li)).ok_or_else(|| invalid("vertex loop"))? }, + Loop::Edges(uses) => { + let pcs = curves.next().ok_or_else(|| invalid("pcurves"))?; + if pcs.len() != uses.len() { + return Err(invalid("pcurves")); + } + b::Loop::Edges { + edges: uses.iter().zip(pcs).map(|(&(edge, forward), pcurve)| b::OrientedEdge { edge, forward, pcurve }).collect(), + } + } + }); + } + face_records.push(b::Face { nurbs: face.nurbs.clone(), surface: face.surface.clone(), domain: face.domain, loops }); + } + let positions = flat.f(VERTEX_POSITION); + let vertices = vertex_order + .iter() + .map(|&v| { + let at = vertex_source.get(v as usize).copied().ok_or_else(|| invalid("vertex"))?; + Ok(b::Vertex { point: v3(positions, at, "vertex")?, tolerance: tolerances.vertex(at) }) + }) + .collect::>>()?; + let shells = shells + .into_iter() + .map(|s| { + let faces = s + .into_iter() + .map(|(f, forward)| { + Ok(b::OrientedFace { face: face_new.get(f as usize).copied().flatten().ok_or_else(|| invalid("face"))?, forward }) + }) + .collect::>>()?; + Ok(b::Shell::Faces { faces, wires: Vec::new() }) + }) + .collect::>>()?; + let brep = b::Brep { version: b::VERSION, tolerance, regions, shells, faces: face_records, edges: edge_records, vertices }; + solidcraft_geom::brep::check::validate_built(&brep).map_err(|e| invalid(format!("the mapped B-rep does not validate: {e}")))?; + let placed = |new: &[Option]| { + new.iter().map(|i| i.map(|i| i as usize).ok_or_else(|| invalid("an entity outside the canonical walk"))).collect::>>() + }; + let edge_new = placed(&edge_new)?; + // SMLib's edges split where solids touch: every piece, with the faces it bounds. + let mut pieces = Vec::new(); + for (e, &canonical) in edge_new.iter().enumerate() { + let edge = edge_source.get(e).copied().ok_or_else(|| invalid("edge"))?; + if edge_source.iter().filter(|s| **s == edge).count() > 1 { + let record = brep.edges.get(canonical).ok_or_else(|| invalid("edge"))?; + let faces: std::collections::BTreeSet = record.uses.iter().map(|u| u.face as usize).collect(); + pieces.push(Piece { edge, canonical, faces: faces.into_iter().collect() }); + } + } + pieces.sort_by_key(|p| (p.edge, p.canonical)); + let mut edges_out = Vec::with_capacity(n_edges); + for e in 0..n_edges { + edges_out + .push(pieces.iter().find(|p| p.edge == e).map_or_else(|| edge_new.get(e).copied().ok_or_else(|| invalid("edge")), |p| Ok(p.canonical))?); + } + let order = Order { faces: placed(&face_new)?, edges: edges_out, pieces }; + Ok((brep, order)) +} + +/// Edges and vertices that solids touching each other share (faces of more than one shell use +/// them), split into one copy per shell, so each shell is a closed manifold boundary of its own. +/// The geometry is unchanged. Returns, for every edge and vertex after the split, the array edge +/// and vertex it is (a copy's original). +fn split_shared(faces: &mut [Face], edges: &mut Vec, shells: &[Vec<(u32, bool)>], n_vertices: usize) -> Res<(Vec, Vec)> { + let mut shell_of = vec![None; faces.len()]; + for (k, shell) in shells.iter().enumerate() { + for &(f, _) in shell { + *shell_of.get_mut(f as usize).ok_or_else(|| invalid("face"))? = Some(k); + } + } + let mut edge_source: Vec = (0..edges.len()).collect(); + // Edges: the first shell to use one keeps it, every other gets a copy. + let mut edge_shell: Vec> = vec![None; edges.len()]; + let mut copies: HashMap<(u32, usize), u32> = HashMap::new(); + for (f, face) in faces.iter_mut().enumerate() { + let Some(k) = shell_of.get(f).copied().flatten() else { continue }; + for l in &mut face.loops { + let Loop::Edges(uses) = l else { continue }; + for (e, _) in uses.iter_mut() { + let slot = edge_shell.get_mut(*e as usize).ok_or_else(|| invalid("edge"))?; + match slot { + None => *slot = Some(k), + Some(owner) if *owner == k => {} + Some(_) => { + let copy = match copies.get(&(*e, k)) { + Some(c) => *c, + None => { + let c = index(edges.len())?; + edges.push(edges.get(*e as usize).ok_or_else(|| invalid("edge"))?.clone()); + edge_source.push(*e as usize); + edge_shell.push(Some(k)); + copies.insert((*e, k), c); + c + } + }; + *e = copy; + } + } + } + } + } + // Vertices: likewise, through the edges (each now in one shell) and the vertex loops. + let mut vertex_source: Vec = (0..n_vertices).collect(); + let mut vertex_shell: Vec> = vec![None; n_vertices]; + let mut vertex_copies: HashMap<(u32, usize), u32> = HashMap::new(); + let mut place = |v: &mut u32, k: usize| -> Res<()> { + let slot = vertex_shell.get_mut(*v as usize).ok_or_else(|| invalid("vertex"))?; + match slot { + None => *slot = Some(k), + Some(owner) if *owner == k => {} + Some(_) => { + let copy = match vertex_copies.get(&(*v, k)) { + Some(c) => *c, + None => { + let c = index(vertex_source.len())?; + vertex_source.push(*v as usize); + vertex_shell.push(Some(k)); + vertex_copies.insert((*v, k), c); + c + } + }; + *v = copy; + } + } + Ok(()) + }; + for (e, edge) in edges.iter_mut().enumerate() { + let Some(k) = edge_shell.get(e).copied().flatten() else { continue }; + for v in &mut edge.vertices { + place(v, k)?; + } + } + for (f, face) in faces.iter_mut().enumerate() { + let Some(k) = shell_of.get(f).copied().flatten() else { continue }; + for l in &mut face.loops { + if let Loop::Vertex(v) = l { + place(v, k)?; + } + } + } + Ok((edge_source, vertex_source)) +} + +/// Edges one shell uses more than twice, where a solid touches itself along a line (a hole +/// tangent to its outline, holes touching each other), split so that every edge bounds two faces: +/// SMLib's radial order round the edge pairs each record with the next one across a sector, and +/// each pair gets its own copy of the edge. The pairs are those across a material sector, so the +/// surface is cut apart along the line round each wedge of material, unless that would give one +/// face two copies (a face on both sides of the line, its loop running along one copy and back +/// along the other), which SMLib refuses (its check's tests 33 and 34, coincident edges in a +/// face): then the pairs across the empty sectors, so that face meets itself across the line as +/// SMLib's crack edges do, one edge used twice. The vertices at the ends stay shared, the points +/// where the boundary meets itself: copies would give a face whose loop passes the point twice two +/// coincident vertices, which SMLib also refuses (test 32). The geometry is unchanged; each copy +/// is added to `edge_source` with its original's source. +fn split_touching(faces: &mut [Face], edges: &mut Vec, edge_source: &mut Vec, radial: Option<&Radial>) -> Res<()> { + // The records using each edge, and where each record is: (face, loop, position). + let mut records_of: Vec> = vec![Vec::new(); edges.len()]; + let mut place: HashMap = HashMap::new(); + for (f, face) in faces.iter().enumerate() { + for (li, (l, records)) in face.loops.iter().zip(&face.records).enumerate() { + let Loop::Edges(uses) = l else { continue }; + if records.len() != uses.len() { + return Err(invalid("loop records")); + } + for (p, (&(e, _), &r)) in uses.iter().zip(records).enumerate() { + records_of.get_mut(e as usize).ok_or_else(|| invalid("edge"))?.push(r); + if place.insert(r, (f, li, p)).is_some() { + return Err(invalid("an edgeuse record in two loops")); + } + } + } + } + let crowded: Vec = (0..edges.len()).filter(|e| records_of.get(*e).is_some_and(|r| r.len() > 2)).collect(); + if crowded.is_empty() { + return Ok(()); + } + let radial = radial.ok_or_else(|| unsupported("a solid touching itself along an edge, without SMLib's radial order"))?; + let face_of = |r: usize| place.get(&r).map(|p| p.0).ok_or_else(|| invalid("edgeuse record")); + let material_same = |r: usize| -> Res { + radial.material_same.get(face_of(r)?).copied().flatten().ok_or_else(|| unsupported("a sheet touching itself along an edge")) + }; + let top_entry = |r: usize| radial.top_entry.get(r).copied().ok_or_else(|| invalid("radial entry")); + // Whether the sector the traversal leaves a record into, and the one it enters a record + // from, is material: it leaves from the side it did not enter. + let after = |r: usize| -> Res { Ok(material_same(r)? != top_entry(r)?) }; + let before = |r: usize| -> Res { Ok(material_same(r)? == top_entry(r)?) }; + + for e in crowded { + let mine = records_of.get(e).cloned().unwrap_or_default(); + let start = *mine.first().ok_or_else(|| invalid("edge"))?; + // The edge's radial list from one of its records, keeping this edge's (another solid's + // faces may lie between them where solids touch each other too). + let mut cycle = Vec::with_capacity(mine.len()); + let mut r = start; + for _ in 0..radial.next.len() { + if mine.contains(&r) { + cycle.push(r); + } + r = radial.next.get(r).copied().ok_or_else(|| invalid("next radial edgeuse"))?; + if r == start { + break; + } + } + if r != start || cycle.len() != mine.len() { + return Err(invalid("a radial list that does not go once round its edge's uses")); + } + let k = cycle.len(); + let at = |i: usize| cycle.get(i % k).copied().ok_or_else(|| invalid("radial list")); + // Sectors alternate material and space, each seen alike from the records on its sides. + let mut alternate = k % 2 == 0; + for i in 0..k { + let (a, b) = (at(i)?, at(i + 1)?); + alternate &= after(a)? == before(b)? && after(a)? != after(b)?; + } + if !alternate { + return Err(unsupported("a solid touching itself along an edge whose faces do not alternate between material and space round it")); + } + // The pairs across material sectors, unless one face would get two copies; then those + // across empty sectors, unless that does too. + let material = if after(at(0)?)? { 0 } else { 1 }; + let one_copy_per_face = |first: usize| -> Res { + let mut pair_of: HashMap = HashMap::new(); + for i in 0..k { + let f = face_of(at(first + i)?)?; + if *pair_of.entry(f).or_insert(i / 2) != i / 2 { + return Ok(false); + } + } + Ok(true) + }; + let first = if one_copy_per_face(material)? || !one_copy_per_face(1 - material)? { material } else { 1 - material }; + for pair in 0..k / 2 { + let (a, b) = (at(first + 2 * pair)?, at(first + 2 * pair + 1)?); + let copy = if pair == 0 { + e + } else { + let c = edges.len(); + edges.push(edges.get(e).ok_or_else(|| invalid("edge"))?.clone()); + edge_source.push(edge_source.get(e).copied().ok_or_else(|| invalid("edge"))?); + c + }; + for r in [a, b] { + let (f, li, p) = place.get(&r).copied().ok_or_else(|| invalid("edgeuse record"))?; + let slot = faces + .get_mut(f) + .and_then(|face| face.loops.get_mut(li)) + .and_then(|l| if let Loop::Edges(u) = l { u.get_mut(p) } else { None }) + .ok_or_else(|| invalid("edgeuse record"))?; + slot.0 = index(copy)?; + } + } + } + Ok(()) +} + +/// What the pcurve routine needs of one edge: the curve its parameter is on, its interval and its +/// tolerance. +struct EdgeGeometry<'a> { + curve: &'a b::Curve, + interval: [f64; 2], + tolerance: f64, +} + +/// A face's pcurves, edge loop by edge loop: SMLib's own UV trims where `given` (loop by loop as +/// `loops`) has them, the plain-record routine on the face's records for the rest; each loop moved +/// by whole periods into the face's domain. `edge` looks up an edge of `loops` by its index. +fn pcurves<'a>( + surface: &b::Surface, + domain: [[f64; 2]; 2], + loops: &[Loop], + given: &'a [Vec>], + edge: impl Fn(u32) -> Option>, + tolerance: f64, +) -> Res>> { + if given.len() != loops.len() { + return Err(invalid("UV trims of a face")); + } + let mut uses = Vec::new(); + for (l, g) in loops.iter().zip(given) { + let Loop::Edges(l) = l else { continue }; + if g.len() != l.len() { + return Err(invalid("UV trims of a loop")); + } + let mut loop_uses = Vec::with_capacity(l.len()); + for (&(e, forward), given) in l.iter().zip(g) { + let geometry = edge(e).ok_or_else(|| invalid("edge"))?; + loop_uses.push(solidcraft_geom::brep::pcurve::EdgeUse { + edge: e, + curve: geometry.curve, + interval: geometry.interval, + forward, + tolerance: geometry.tolerance, + given: given.as_ref(), + }); + } + uses.push(loop_uses); + } + let mut curves = + solidcraft_geom::brep::pcurve::pcurves_within(surface, &uses, tolerance, Some(domain)).map_err(|e| invalid(format!("pcurve: {e}")))?; + into_domain(surface, domain, &mut curves); + Ok(curves) +} + +/// The signed area of a face's outer loop in the record's parameters, from its pcurves +/// (positive: counter-clockwise, the record's convention); 0 where it has no edge loop. +fn outer_area(face: &Face, edges: &[Edge], tolerance: f64) -> Res { + let Some(Loop::Edges(outer)) = face.loops.first() else { return Ok(0.0) }; + let geometry = |e: u32| { + let edge = edges.get(e as usize)?; + Some(EdgeGeometry { curve: edge.nurbs.as_ref().unwrap_or(&edge.curve), interval: edge.interval, tolerance }) + }; + let given = face.given.first().map(std::slice::from_ref).unwrap_or(&[]); + let curves = pcurves(face.nurbs.as_ref().unwrap_or(&face.surface), face.domain, &[Loop::Edges(outer.clone())], given, geometry, tolerance)?; + let mut pts: Vec<[f64; 2]> = Vec::new(); + for (pc, &(e, forward)) in curves.first().map(Vec::as_slice).unwrap_or(&[]).iter().zip(outer) { + let edge = edges.get(e as usize).ok_or_else(|| invalid("edge"))?; + let [a, z] = edge.interval; + let mut run: Vec<[f64; 2]> = (0..=32).filter_map(|i| point2(pc, a + (z - a) * f64::from(i) / 32.0)).collect(); + if !forward { + run.reverse(); + } + pts.extend(run); + } + let n = pts.len(); + Ok(0.5 * (0..n).filter_map(|k| Some((pts.get(k)?, pts.get((k + 1) % n)?))).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum::()) +} + +/// A pcurve's point at `t` (de Boor on the homogeneous coefficients). +fn point2(c: &b::Curve2, t: f64) -> Option<[f64; 2]> { + let (knots, pts): (&[f64], Vec<[f64; 3]>) = match c { + b::Curve2::Spline { knots, points } => (knots, points.iter().map(|p| [p[0], p[1], 1.0]).collect()), + b::Curve2::RationalSpline { knots, homogeneous } => (knots, homogeneous.clone()), + }; + let n = pts.len(); + let p = knots.len().checked_sub(n + 1)?; + let t = t.clamp(*knots.get(p)?, *knots.get(n)?); + let mut s = p; + while s + 1 < n && *knots.get(s + 1)? <= t { + s += 1; + } + let mut d: Vec<[f64; 3]> = (0..=p).map(|j| pts.get(s + j - p).copied()).collect::>()?; + for r in 1..=p { + for j in (r..=p).rev() { + let i = s + j - p; + let den = knots.get(i + p + 1 - r)? - knots.get(i)?; + let a = if den == 0.0 { 0.0 } else { (t - knots.get(i)?) / den }; + let (lo, hi) = (*d.get(j - 1)?, *d.get(j)?); + *d.get_mut(j)? = [0, 1, 2].map(|c| (1.0 - a) * lo[c] + a * hi[c]); + } + } + let q = d.get(p)?; + (q[2] != 0.0).then(|| [q[0] / q[2], q[1] / q[2]]) +} + +/// Moves each loop's pcurves by whole periods so the loop's middle is nearest the domain's. +fn into_domain(surface: &b::Surface, domain: [[f64; 2]; 2], curves: &mut [Vec]) { + for (d, natural) in solidcraft_geom::brep::label::surface_natural(surface).into_iter().enumerate() { + if natural != b::Natural::Periodic { + continue; + } + let [lo, hi] = domain.get(d).copied().unwrap_or([0.0, TAU]); + for l in curves.iter_mut() { + let (mut a, mut z) = (f64::INFINITY, f64::NEG_INFINITY); + for x in l.iter().flat_map(|c| coordinates(c, d)) { + a = a.min(x); + z = z.max(x); + } + if !(a.is_finite() && z.is_finite()) { + continue; + } + let k = ((0.5 * (lo + hi) - 0.5 * (a + z)) / TAU).round(); + if k != 0.0 && k.is_finite() { + l.iter_mut().for_each(|c| shift(c, d, k * TAU)); + } + } + } +} + +fn coordinates(c: &b::Curve2, d: usize) -> Vec { + match c { + b::Curve2::Spline { points, .. } => points.iter().filter_map(|p| p.get(d).copied()).collect(), + b::Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().filter_map(|p| Some(p.get(d)? / p[2])).collect(), + } +} + +fn shift(c: &mut b::Curve2, d: usize, by: f64) { + match c { + b::Curve2::Spline { points, .. } => points.iter_mut().for_each(|p| { + if let Some(x) = p.get_mut(d) { + *x += by; + } + }), + b::Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter_mut().for_each(|p| { + let w = p[2]; + if let Some(x) = p.get_mut(d) { + *x += by * w; + } + }), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/smlib/src/export/tests.rs b/crates/smlib/src/export/tests.rs new file mode 100644 index 000000000..21f283ce0 --- /dev/null +++ b/crates/smlib/src/export/tests.rs @@ -0,0 +1,455 @@ +use super::*; + +mod native_tests { + use super::*; + use crate::{CheckLevel, MEASURE_ACCURACY}; + use std::f64::consts::PI; + + /// SMLib's primitives with their closed-form volumes. + #[allow(clippy::unwrap_used)] // test fixture + fn primitives() -> Vec<(&'static str, Brep, f64)> { + vec![ + ("box", Brep::make_box([1.0, 2.0, 3.0], [10.0, 20.0, 30.0]).unwrap(), 6000.0), + ("cylinder", Brep::make_cylinder([1.0, 2.0, 3.0], 5.0, 10.0).unwrap(), PI * 25.0 * 10.0), + ("sphere", Brep::make_sphere([1.0, 2.0, 3.0], 5.0).unwrap(), 4.0 / 3.0 * PI * 125.0), + ("frustum", Brep::make_cone([0.0; 3], 5.0, 2.0, 10.0).unwrap(), PI * 10.0 / 3.0 * (25.0 + 10.0 + 4.0)), + ("widening frustum", Brep::make_cone([0.0; 3], 2.0, 5.0, 10.0).unwrap(), PI * 10.0 / 3.0 * (25.0 + 10.0 + 4.0)), + ("cone", Brep::make_cone([0.0; 3], 5.0, 0.0, 10.0).unwrap(), PI * 10.0 / 3.0 * 25.0), + ("torus", Brep::make_torus([0.0; 3], 10.0, 3.0).unwrap(), 2.0 * PI * PI * 10.0 * 9.0), + ] + } + + #[test] + fn every_primitive_exports_validates_and_keeps_its_volume() { + for (name, b, exact) in primitives() { + let check = b.check(CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{name}: {check}"); + let v = b.mass_properties(MEASURE_ACCURACY).unwrap().volume; + assert!((v - exact).abs() < 1e-6 * exact, "{name}: SMLib volume {v}, closed form {exact}"); + let (native, report) = b.to_native_report().unwrap_or_else(|e| panic!("{name}: {e}")); + solidcraft_geom::brep::check::validate(&native).unwrap(); + solidcraft_geom::brep::geometry::check(&native).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(report, Report { nurbs_edges: report.nurbs_edges, ..Report::default() }, "{name}: every face agrees"); + let [f, e, n] = b.counts().unwrap(); + assert_eq!((native.faces.len(), native.edges.len(), native.vertices.len()), (f, e, n), "{name}"); + // One closed shell bounding one material region; no NURBS edges left. + assert_eq!(native.shells.len(), 1, "{name}"); + assert_eq!(native.regions.len(), 2, "{name}"); + assert!(!native.regions[0].void && !native.regions[1].void, "{name}"); + assert!(native.edges.iter().all(|e| matches!(e.curve, b::Curve::Line { .. } | b::Curve::Circle { .. })), "{name}"); + } + } + + #[test] + fn every_primitive_goes_round_through_schema_4_unchanged() { + for (name, s, _) in primitives() { + let record = s.to_native().unwrap_or_else(|e| panic!("{name}: {e}")); + let back = Brep::from_record(&record, true).unwrap_or_else(|e| panic!("{name}: {e}")); + let check = back.check(CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{name}: {check}"); + assert_eq!(back.counts().unwrap(), s.counts().unwrap(), "{name}"); + let (v0, v1) = (s.mass_properties(MEASURE_ACCURACY).unwrap().volume, back.mass_properties(MEASURE_ACCURACY).unwrap().volume); + assert!((v1 - v0).abs() < 1e-7 * v0, "{name}: volume {v0} -> {v1}"); + } + } + + /// A 20 mm cube with every edge rounded r 2: each of its eight corners is a sphere of radius 2 + /// about the corner pulled in by 2 along each axis. The record keeps each corner on that + /// sphere; imported back, the body is valid and keeps its closed-form volume. + #[test] + fn a_rounded_cubes_corners_go_round_on_their_spheres() { + let (a, r) = (20.0, 2.0); + let h = a / 2.0; + let mids: Vec<[f64; 3]> = [(0.0, 0.0), (a, 0.0), (0.0, a), (a, a)].iter().flat_map(|&(p, q)| [[h, p, q], [p, h, q], [p, q, h]]).collect(); + let f = Brep::make_box([0.0; 3], [a; 3]).unwrap().fillet(&mids, 0.1, r).unwrap(); + let record = f.to_native().unwrap(); + solidcraft_geom::brep::check::validate(&record).unwrap(); + let corners: Vec<([f64; 3], f64)> = record + .faces + .iter() + .filter_map(|face| match &face.surface { + b::Surface::Sphere { frame, radius } => Some((frame.origin, *radius)), + b::Surface::BallPatch { center, radius } => Some((*center, *radius)), + _ => None, + }) + .collect(); + assert_eq!(corners.len(), 8, "one sphere per corner"); + // Each corner's sphere is about the corner pulled in by r along each axis: one sphere each. + let inset = [r, a - r]; + for i in 0..8 { + let want = [inset[i >> 2], inset[(i >> 1) & 1], inset[i & 1]]; + let at = corners.iter().filter(|(c, _)| (0..3).all(|k| (c[k] - want[k]).abs() < 1e-9)).count(); + assert_eq!(at, 1, "spheres about {want:?}: {corners:?}"); + } + for (_, radius) in &corners { + assert!((radius - r).abs() < 1e-12, "radius {radius}"); + } + let back = Brep::from_record(&record, true).unwrap(); + let check = back.check(CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{check}"); + let b = a - 2.0 * r; + let want = b.powi(3) + 6.0 * b * b * r + 3.0 * PI * r * r * b + 4.0 / 3.0 * PI * r.powi(3); + for (name, body) in [("as built", &f), ("through the record", &back)] { + let got = body.mass_properties(MEASURE_ACCURACY).unwrap().volume; + assert!((got - want).abs() < 1e-6 * want, "{name}: volume {got} vs {want}"); + } + } + + /// A tagged body's own history, renumbered with its export's order on both sides, is the + /// identity in canonical order: the order says where each SMLib face and edge went. + #[test] + fn the_export_order_renumbers_a_history_into_the_record() { + for (name, s, _) in primitives() { + let t = s.tagged(0).unwrap(); + let (record, order) = t.to_native_ordered().unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!((order.faces.len(), order.edges.len()), (record.faces.len(), record.edges.len()), "{name}"); + let h = t.history().unwrap().history(std::slice::from_ref(&order), &order).unwrap(); + for (i, f) in h.faces.iter().enumerate() { + assert_eq!(f.origins, vec![solidcore_record::brep::history::FaceOrigin::Face { operand: 0, face: i }], "{name}: face {i}"); + } + for (i, e) in h.edges.iter().enumerate() { + assert_eq!(e.origins, vec![solidcore_record::brep::history::EdgeOrigin::Edge { operand: 0, edge: i }], "{name}: edge {i}"); + // The faces it bounds, as the record's uses say. + let mut faces: Vec = record.edges[i].uses.iter().map(|u| u.face as usize).collect(); + faces.sort(); + faces.dedup(); + assert_eq!(e.faces, faces, "{name}: edge {i}"); + } + } + } + + #[test] + fn edges_are_on_smlibs_curves() { + let cyl = Brep::make_cylinder([0.0; 3], 5.0, 10.0).unwrap().to_native().unwrap(); + let side = cyl.faces.iter().find(|f| matches!(f.surface, b::Surface::Cylinder { .. })).unwrap(); + // The side is on SMLib's NURBS form of the cylinder (its domain is the form's): the whole + // turn, so its domain's two u ends meet, from the base to the top. + let form = solidcraft_geom::brep::eval::SurfaceEval::new(side.parameters()).unwrap(); + let [[u0, u1], [v0, v1]] = side.domain; + for v in [v0, v1] { + let (a, z) = (form.point([u0, v]).unwrap(), form.point([u1, v]).unwrap()); + assert!(a.dist(z) < 1e-9, "{a:?} {z:?}"); + } + let heights = [form.point([u0, v0]).unwrap().z, form.point([u0, v1]).unwrap().z]; + assert!(heights.iter().any(|h| h.abs() < 1e-9) && heights.iter().any(|h| (h - 10.0).abs() < 1e-9), "{heights:?}"); + for e in &cyl.edges { + // Evaluated on the curve its interval is on (a circle's NURBS form). + let eval = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).unwrap(); + let [a, z] = e.interval; + // Ends on the edge's vertices. + for (t, v) in [(a, e.vertices[0]), (z, e.vertices[1])] { + let p = eval.point(t).unwrap(); + let q = cyl.vertices[v as usize].point; + assert!((p - Vec3::new(q[0], q[1], q[2])).len() < 1e-9, "{:?} at {t}", e.curve); + } + if let b::Curve::Circle { radius, .. } = e.curve { + let [a, z] = solidcraft_geom::brep::label::edge_curve_interval(e).unwrap(); + assert!((radius - 5.0).abs() < 1e-12 && (z - a - TAU).abs() < 1e-9); + } + } + // The narrowing cone keeps SMLib's negative half angle. + let cone = Brep::make_cone([0.0; 3], 5.0, 0.0, 10.0).unwrap().to_native().unwrap(); + let half = cone.faces.iter().find_map(|f| if let b::Surface::Cone { half_angle, .. } = f.surface { Some(half_angle) } else { None }); + assert!((half.unwrap() + 0.5f64.atan()).abs() < 1e-12); + } + + /// A cone whose half angle is within rounding of zero (a52's thread bosses: 1e-13) is exported as + /// a cylinder; as a cone the portable record's validation refuses it. + #[test] + fn a_cone_of_rounding_angle_is_exported_as_a_cylinder() { + let near = Brep::make_cone([0.0; 3], 4.0, 4.0 - 1e-12, 10.0).unwrap().to_native().unwrap(); + assert!(near.faces.iter().any(|f| matches!(f.surface, b::Surface::Cylinder { .. }))); + assert!(!near.faces.iter().any(|f| matches!(f.surface, b::Surface::Cone { .. }))); + solidcraft_geom::brep::check::validate(&near).unwrap(); + } + + /// A hole tangent to the block's outline from inside: the material touches itself along the + /// tangent line, where SMLib's one shell uses the edge four times. The record has two copies + /// of that edge, each bounding one wedge of material (a face of the side and the half of the + /// hole on the same side of the line), so every edge has two uses; the line's two vertices + /// stay shared. The record goes back into SMLib as a valid solid of the same volume. + #[test] + fn a_hole_tangent_to_the_outline_comes_back_as_a_manifold_boundary() { + let block = Brep::make_box([0.0; 3], [31.0, 29.0, 10.0]).unwrap(); + let hole = Brep::make_cylinder([5.0, 14.5, -1.0], 5.0, 12.0).unwrap(); + let r = block.boolean(&hole, crate::BooleanOp::Subtract).unwrap().unwrap(); + assert!(!r.is_manifold_solid().unwrap(), "SMLib keeps the touching boundary as one non-manifold shell"); + let (record, order) = r.to_native_ordered().unwrap(); + let [f, e, v] = r.counts().unwrap(); + assert_eq!((record.faces.len(), record.edges.len(), record.vertices.len()), (f, e + 1, v)); + assert_eq!((record.shells.len(), record.regions.len()), (1, 2)); + assert!(record.edges.iter().all(|e| e.uses.len() == 2)); + solidcraft_geom::brep::geometry::check(&record).unwrap(); + let on_line = |e: &b::Edge| { + e.vertices.iter().all(|v| { + let p = record.vertices[*v as usize].point; + p[0].abs() < 1e-9 && (p[1] - 14.5).abs() < 1e-9 + }) + }; + // On the curve the interval is on (a circle's NURBS form). + let middle = + |e: &b::Edge| solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap(); + let copies: Vec<&b::Edge> = record.edges.iter().filter(|e| on_line(e)).collect(); + assert_eq!(copies.len(), 2); + for copy in copies { + // Each face's other edges lie on one side of y = 14.5: the same side for both faces. + let sides: Vec = copy + .uses + .iter() + .map(|u| { + let b::Loop::Edges { edges } = &record.faces[u.face as usize].loops[u.r#loop as usize] else { panic!("vertex loop") }; + let others: Vec = + edges.iter().map(|o| &record.edges[o.edge as usize]).filter(|o| !on_line(o)).map(|o| middle(o).y - 14.5).collect(); + others.iter().sum::() / others.len() as f64 + }) + .collect(); + assert!(sides[0] * sides[1] > 0.0, "the copy joins faces on opposite sides of the line: {sides:?}"); + } + // SMLib's history of the tangent line goes to both copies. + assert_eq!(order.pieces.len(), 2); + let back = Brep::from_record(&record, true).unwrap(); + let check = back.check(CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{check}"); + let want = 31.0 * 29.0 * 10.0 - PI * 25.0 * 10.0; + let got = back.mass_properties(MEASURE_ACCURACY).unwrap().volume; + assert!((got - want).abs() < 1e-6 * want, "volume {got} vs {want}"); + } + + /// A blind hole from z = 2 tangent to the block's side y = 20 from inside: the side is one + /// face on both sides of the tangent line (joined below the hole), so pairing the faces round + /// the line across the material would give it two coincident copies of the line, which + /// SMLib refuses. The line is then copied across the empty sectors: the side uses one copy + /// twice (a crack, as SMLib keeps a face meeting itself), the hole's two halves the other. + #[test] + fn a_blind_hole_tangent_to_a_side_leaves_the_side_a_crack() { + let block = Brep::make_box([0.0; 3], [30.0, 20.0, 10.0]).unwrap(); + let hole = Brep::make_cylinder([10.0, 15.0, 2.0], 5.0, 9.0).unwrap(); + let r = block.boolean(&hole, crate::BooleanOp::Subtract).unwrap().unwrap(); + let (record, _) = r.to_native_ordered().unwrap(); + assert!(record.edges.iter().all(|e| e.uses.len() == 2)); + solidcraft_geom::brep::geometry::check(&record).unwrap(); + let on_line = |e: &b::Edge| { + e.vertices.iter().all(|v| { + let p = record.vertices[*v as usize].point; + (p[0] - 10.0).abs() < 1e-9 && (p[1] - 20.0).abs() < 1e-9 + }) + }; + let copies: Vec<&b::Edge> = record.edges.iter().filter(|e| on_line(e)).collect(); + assert_eq!(copies.len(), 2); + let kinds: Vec<(bool, bool)> = copies + .iter() + .map(|e| { + let faces: Vec<&b::Face> = e.uses.iter().map(|u| &record.faces[u.face as usize]).collect(); + let side = |f: &b::Face| matches!(f.surface, b::Surface::Plane { .. }); + (faces.iter().all(|f| side(f)), e.uses[0].face == e.uses[1].face) + }) + .collect(); + assert!(kinds.contains(&(true, true)), "one copy is the side's crack: {kinds:?}"); + assert!(kinds.contains(&(false, false)), "the other joins the hole's halves: {kinds:?}"); + let back = Brep::from_record(&record, true).unwrap(); + let check = back.check(CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{check}"); + let want = 6000.0 - PI * 25.0 * 8.0; + let got = back.mass_properties(MEASURE_ACCURACY).unwrap().volume; + assert!((got - want).abs() < 1e-6 * want, "volume {got} vs {want}"); + } + + /// A 100 x 60 x 30 block less a loft from its whole 100 x 60 outline at z = 20 (flush with its + /// sides) down to a 10 x 10 pad at z = 11: the slab above z = 20 is cut loose, touching the + /// rest along the outline's four edges round the pocket the loft leaves. SMLib keeps the + /// pocket as a void of its own, bounded by the slab's underside and the loft's faces, so each + /// solid's one boundary faces both the void and the space round the solids. The record has + /// the two solids' closed shells, each listed by its solid and by the infinite region (the + /// pocket is part of the empty space once the solids' shared edges are split), and no void. + #[test] + fn solids_touching_round_a_pocket_have_one_shell_each_and_no_void() { + use crate::sweeps::Curve; + let block = Brep::make_box([0.0; 3], [100.0, 60.0, 30.0]).unwrap(); + let rect = |pts: [[f64; 3]; 4]| -> Vec { (0..4).map(|i| Curve::Line { start: pts[i], end: pts[(i + 1) % 4] }).collect() }; + let pad = rect([[2.0, 2.0, 11.0], [12.0, 2.0, 11.0], [12.0, 12.0, 11.0], [2.0, 12.0, 11.0]]); + let top = rect([[0.0, 0.0, 20.0], [100.0, 0.0, 20.0], [100.0, 60.0, 20.0], [0.0, 60.0, 20.0]]); + let tool = Brep::loft(&[pad, top], 1, true).unwrap(); + let r = block.boolean(&tool, crate::BooleanOp::Subtract).unwrap().unwrap(); + assert!(r.check(CheckLevel::All).unwrap().is_valid()); + let arrays = r.arrays().unwrap(); + let types = arrays.ints.get(&crate::flat::REGION_TYPE).cloned().unwrap_or_default(); + assert_eq!(types.iter().skip(1).filter(|t| **t != 0).count(), 1, "SMLib keeps the pocket as a void: {types:?}"); + let record = r.to_native().unwrap(); + assert_eq!(record.shells.len(), 2); + assert_eq!(record.regions.len(), 3); + assert!(record.regions.iter().all(|g| !g.void)); + assert_eq!(record.regions[0].shells.len(), 2, "the infinite region lists both solids"); + solidcraft_geom::brep::geometry::check(&record).unwrap(); + // V = 180000 - h/6 (A0 + 4 Am + A1), h = 9, Am = 55 x 35. + let want = 180000.0 - 9.0 / 6.0 * (100.0 + 4.0 * 55.0 * 35.0 + 6000.0); + let back = Brep::from_record(&record, true).unwrap(); + let check = back.check(CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{check}"); + let got = back.mass_properties(MEASURE_ACCURACY).unwrap().volume; + assert!((got - want).abs() < 1e-6 * want, "volume {got} vs {want}"); + } + + /// The variable round r1 -> r5 along a box's top back edge run on into the R5 round of its + /// corner (ladder 07-fillets/012): its end trimmed by the R5 cylinder is a NURBS edge, whose + /// interval SMLib gave 7e-15 before the first knot. The record's interval is the NURBS's own + /// where it overshoots it by rounding, and the record validates; farther past it stays an error. + #[test] + fn a_nurbs_edge_interval_a_rounding_past_its_knots_is_moved_onto_them() { + let block = Brep::make_box([0.0; 3], [60.0, 40.0, 20.0]).unwrap(); + let rounded = block.fillet(&[[60.0, 40.0, 10.0]], 0.1, 5.0).unwrap(); + let r = rounded.fillet_variable([27.5, 40.0, 20.0], 0.1, [0.0, 40.0, 20.0], 1, &[0.0, 0.0, 1.0, 1.0], &[1.0, 5.0]).unwrap(); + let arrays = r.arrays().unwrap(); + let kinds = arrays.ints.get(&EDGE_CURVE_TYPE).cloned().unwrap_or_default(); + let counts = arrays.ints.get(&EDGE_NURBS_VERTEX_COUNT).cloned().unwrap_or_default(); + let orders = arrays.ints.get(&EDGE_NURBS_ORDER).cloned().unwrap_or_default(); + let forms = arrays.ints.get(&EDGE_NURBS_FORM).cloned().unwrap_or_default(); + let knots = arrays.reals.get(&EDGE_NURBS_KNOTS).cloned().unwrap_or_default(); + // Each NURBS block's first and last knots of its domain, in edge order. + let (mut at, mut block_of) = (0usize, Vec::new()); + for (n, o) in counts.iter().zip(&orders) { + let (n, o) = (*n as usize, *o as usize); + block_of.push((knots[at + o - 1], knots[at + n])); + at += n + o; + } + let mut nurbs = 0usize; + let mut edge = None; + for (e, kind) in kinds.iter().enumerate() { + let has_block = *kind == CURVE_NURBS || forms.get(e) == Some(&1); + if *kind == CURVE_NURBS && edge.is_none() { + edge = Some((e, block_of[nurbs])); + } + nurbs += usize::from(has_block); + } + let (e, (first, last)) = edge.expect("the round's end on the cylinder is a NURBS edge"); + let shifted = |by: f64| { + let mut a = arrays.clone(); + a.reals.get_mut(&EDGE_RANGE).unwrap()[2 * e] = first - by; + a + }; + let (record, _) = native(&shifted(7e-15)).unwrap(); + solidcraft_geom::brep::check::validate(&record).unwrap(); + assert!(record.edges.iter().any(|x| x.interval[0] == first && x.interval[1] <= last), "an interval on the NURBS's first knot"); + assert!( + native(&shifted(1e-3)).map(|(r, _)| solidcraft_geom::brep::check::validate(&r)).map_or(true, |v| v.is_err()), + "a real overshoot is not moved" + ); + } + + /// [`outer_area`] as it was: every edge of the body copied into a record for each face. + #[allow(clippy::unwrap_used)] // test reference + fn outer_area_copying_every_edge(face: &Face, edges: &[Edge], tolerance: f64) -> Res { + let Some(Loop::Edges(outer)) = face.loops.first() else { return Ok(0.0) }; + let records: Vec = edges + .iter() + .map(|e| b::Edge { + nurbs: e.nurbs.clone(), + curve: e.curve.clone(), + interval: e.interval, + vertices: e.vertices, + tolerance, + uses: Vec::new(), + }) + .collect(); + let lookup = |e: u32| { + let edge = records.get(e as usize)?; + Some(EdgeGeometry { curve: edge.nurbs.as_ref().unwrap_or(&edge.curve), interval: edge.interval, tolerance: edge.tolerance }) + }; + let given = face.given.first().map(std::slice::from_ref).unwrap_or(&[]); + let curves = pcurves(face.nurbs.as_ref().unwrap_or(&face.surface), face.domain, &[Loop::Edges(outer.clone())], given, lookup, tolerance)?; + let mut pts: Vec<[f64; 2]> = Vec::new(); + for (pc, &(e, forward)) in curves.first().map(Vec::as_slice).unwrap_or(&[]).iter().zip(outer) { + let [a, z] = edges.get(e as usize).unwrap().interval; + let mut run: Vec<[f64; 2]> = (0..=32).filter_map(|i| point2(pc, a + (z - a) * f64::from(i) / 32.0)).collect(); + if !forward { + run.reverse(); + } + pts.extend(run); + } + let n = pts.len(); + Ok(0.5 * (0..n).map(|k| (pts[k], pts[(k + 1) % n])).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum::()) + } + + /// A face's outer area reads only its own loop's edges, and is bit for bit what copying every + /// edge of the body gave: the export's face turns, and so its records and numbering, are + /// unchanged. Each body's record faces are counter-clockwise by convention, so positive. + #[test] + fn a_faces_outer_area_reads_only_its_own_loop_and_is_unchanged() { + let block = Brep::make_box([0.0; 3], [31.0, 29.0, 10.0]).unwrap(); + let hole = Brep::make_cylinder([12.0, 14.5, -1.0], 5.0, 12.0).unwrap(); + let rounded = Brep::make_box([0.0; 3], [60.0, 40.0, 20.0]).unwrap().fillet(&[[60.0, 40.0, 10.0]], 0.1, 5.0).unwrap(); + let mut bodies: Vec<(&str, Brep)> = primitives().into_iter().map(|(name, b, _)| (name, b)).collect(); + bodies.push(("box minus cylinder", block.boolean(&hole, crate::BooleanOp::Subtract).unwrap().unwrap())); + bodies.push(("rounded box", rounded)); + for (name, body) in bodies { + let record = body.to_native().unwrap_or_else(|e| panic!("{name}: {e}")); + let edges: Vec = record + .edges + .iter() + .map(|e| Edge { + curve: e.curve.clone(), + nurbs: e.nurbs.clone(), + interval: e.interval, + vertices: e.vertices, + reversed: false, + trim_map: None, + }) + .collect(); + for (f, rf) in record.faces.iter().enumerate() { + // Without SMLib's trims (the pcurve routine) and with the record's pcurves as them. + for with_given in [false, true] { + let loops: Vec = rf + .loops + .iter() + .map(|l| match l { + b::Loop::Edges { edges } => Loop::Edges(edges.iter().map(|u| (u.edge, u.forward)).collect()), + b::Loop::Vertex { vertex } => Loop::Vertex(*vertex), + }) + .collect(); + let given = rf + .loops + .iter() + .map(|l| match l { + b::Loop::Edges { edges } => edges.iter().map(|u| with_given.then(|| u.pcurve.clone())).collect(), + b::Loop::Vertex { .. } => Vec::new(), + }) + .collect(); + let records = loops.iter().map(|_| Vec::new()).collect(); + let face = Face { nurbs: rf.nurbs.clone(), surface: rf.surface.clone(), domain: rf.domain, agrees: true, loops, records, given }; + let now = outer_area(&face, &edges, record.tolerance).unwrap_or_else(|e| panic!("{name}: face {f}: {e}")); + let before = outer_area_copying_every_edge(&face, &edges, record.tolerance).unwrap(); + assert_eq!(now.to_bits(), before.to_bits(), "{name}: face {f}, trims given {with_given}: {now} != {before}"); + assert!(now > 0.0, "{name}: face {f}, trims given {with_given}: area {now}"); + } + } + } + } + + #[test] + fn hostile_arrays_are_errors_never_panics() { + let good = Brep::make_box([0.0; 3], [1.0, 2.0, 3.0]).unwrap().arrays().unwrap(); + assert!(native(&good).is_ok()); + assert!(native(&Arrays::default()).is_err()); + let ids: Vec = good.ints.keys().copied().collect(); + for id in ids { + for edit in 0..4 { + let mut f = good.clone(); + let a = f.ints.get_mut(&id).unwrap(); + match edit { + 0 => a.clear(), + 1 => a.iter_mut().for_each(|x| *x = 1 << 40), + 2 => a.iter_mut().for_each(|x| *x = -1), + _ => a.push(7), + } + let _ = native(&f); + } + } + let ids: Vec = good.reals.keys().copied().collect(); + for id in ids { + for x in [f64::NAN, f64::INFINITY, 1e300, 0.0] { + let mut f = good.clone(); + f.reals.get_mut(&id).unwrap().iter_mut().for_each(|v| *v = x); + let _ = native(&f); + } + } + } +} diff --git a/crates/smlib/src/flat.rs b/crates/smlib/src/flat.rs new file mode 100644 index 000000000..08a471dd2 --- /dev/null +++ b/crates/smlib/src/flat.rs @@ -0,0 +1,137 @@ +//! SMLib's flat B-rep arrays (`capi/include/smlib.h`, "Flat B-rep arrays"): a B-rep as plain +//! int64 and double arrays laid out like a member of USD's BrepArray schema, which solidcore's body +//! is converted to and from ([`crate::import::Arrays`]). + +use crate::{Brep, Result}; + +// Array ids and kind values, as in smlib.h. +pub const REGION_SHELL_COUNT: i32 = 1; +pub const REGION_TYPE: i32 = 2; +pub const SHELL_FACEUSE_COUNT: i32 = 3; +pub const SHELL_WIRE_EDGE_COUNT: i32 = 4; +pub const SHELL_POINT_TYPE: i32 = 5; +pub const FACEUSE_FACE: i32 = 6; +pub const FACEUSE_ORIENTATION: i32 = 7; +pub const FACE_LOOP_COUNT: i32 = 8; +pub const FACE_SURFACE_TYPE: i32 = 9; +pub const FACE_TRIM_TYPE: i32 = 10; +pub const LOOP_EDGEUSE_COUNT: i32 = 11; +pub const LOOP_VERTEX: i32 = 12; +pub const EDGEUSE_EDGE: i32 = 13; +pub const EDGEUSE_ORIENTATION: i32 = 14; +pub const EDGEUSE_NEXT_RADIAL: i32 = 15; +pub const EDGEUSE_RADIAL_ENTRY: i32 = 16; +pub const EDGE_CURVE_TYPE: i32 = 17; +pub const EDGE_VERTICES: i32 = 18; +pub const WIRE_EDGE_CURVE_TYPE: i32 = 19; +pub const WIRE_EDGE_VERTICES: i32 = 20; +pub const VERTEX_POINT_TYPE: i32 = 21; +pub const EDGE_NURBS_VERTEX_COUNT: i32 = 22; +pub const EDGE_NURBS_ORDER: i32 = 23; +pub const WIRE_EDGE_NURBS_VERTEX_COUNT: i32 = 24; +pub const WIRE_EDGE_NURBS_ORDER: i32 = 25; +pub const EDGEUSE_NURBS_VERTEX_COUNT: i32 = 26; +pub const EDGEUSE_NURBS_ORDER: i32 = 27; +pub const FACE_NURBS_U_VERTEX_COUNT: i32 = 28; +pub const FACE_NURBS_V_VERTEX_COUNT: i32 = 29; +pub const FACE_NURBS_U_ORDER: i32 = 30; +pub const FACE_NURBS_V_ORDER: i32 = 31; +pub const SOURCE: i32 = 32; +pub const FACE_NURBS_FORM: i32 = 33; +pub const EDGE_NURBS_FORM: i32 = 34; +pub const WIRE_EDGE_NURBS_FORM: i32 = 35; +/// Per face whose kind carries a definition (a ball patch), in face order: how many reals of +/// `FACE_DEFINITION_REALS` are its definition (a ball patch: 4). +pub const FACE_DEFINITION_REAL_COUNT: i32 = 36; +pub const TOLERANCE: i32 = 101; +pub const EXTENT: i32 = 102; +pub const FACE_RANGE: i32 = 103; +pub const EDGE_RANGE: i32 = 104; +pub const WIRE_EDGE_RANGE: i32 = 105; +pub const SHELL_POINT_POSITION: i32 = 106; +pub const VERTEX_POSITION: i32 = 107; +pub const EDGE_NURBS_CVS: i32 = 108; +pub const EDGE_NURBS_KNOTS: i32 = 109; +pub const EDGE_NURBS_WEIGHTS: i32 = 110; +pub const EDGE_CIRCLE_CENTER: i32 = 111; +pub const EDGE_CIRCLE_AXIS: i32 = 112; +pub const EDGE_CIRCLE_REF_DIRECTION: i32 = 113; +pub const EDGE_CIRCLE_RADIUS: i32 = 114; +pub const EDGE_LINE_ORIGIN: i32 = 115; +pub const EDGE_LINE_DIRECTION: i32 = 116; +pub const EDGE_ELLIPSE_CENTER: i32 = 117; +pub const EDGE_ELLIPSE_AXIS: i32 = 118; +pub const EDGE_ELLIPSE_REF_DIRECTION: i32 = 119; +pub const EDGE_ELLIPSE_X_RADIUS: i32 = 120; +pub const EDGE_ELLIPSE_Y_RADIUS: i32 = 121; +pub const WIRE_EDGE_NURBS_CVS: i32 = 122; +pub const WIRE_EDGE_NURBS_KNOTS: i32 = 123; +pub const WIRE_EDGE_NURBS_WEIGHTS: i32 = 124; +pub const WIRE_EDGE_CIRCLE_CENTER: i32 = 125; +pub const WIRE_EDGE_CIRCLE_AXIS: i32 = 126; +pub const WIRE_EDGE_CIRCLE_REF_DIRECTION: i32 = 127; +pub const WIRE_EDGE_CIRCLE_RADIUS: i32 = 128; +pub const WIRE_EDGE_LINE_ORIGIN: i32 = 129; +pub const WIRE_EDGE_LINE_DIRECTION: i32 = 130; +pub const WIRE_EDGE_ELLIPSE_CENTER: i32 = 131; +pub const WIRE_EDGE_ELLIPSE_AXIS: i32 = 132; +pub const WIRE_EDGE_ELLIPSE_REF_DIRECTION: i32 = 133; +pub const WIRE_EDGE_ELLIPSE_X_RADIUS: i32 = 134; +pub const WIRE_EDGE_ELLIPSE_Y_RADIUS: i32 = 135; +pub const EDGEUSE_NURBS_CVS: i32 = 136; +pub const EDGEUSE_NURBS_KNOTS: i32 = 137; +pub const EDGEUSE_NURBS_WEIGHTS: i32 = 138; +pub const FACE_NURBS_CVS: i32 = 139; +pub const FACE_NURBS_U_KNOTS: i32 = 140; +pub const FACE_NURBS_V_KNOTS: i32 = 141; +pub const FACE_NURBS_WEIGHTS: i32 = 142; +pub const FACE_SPHERE_CENTER: i32 = 143; +pub const FACE_SPHERE_AXIS: i32 = 144; +pub const FACE_SPHERE_REF_DIRECTION: i32 = 145; +pub const FACE_SPHERE_RADIUS: i32 = 146; +pub const FACE_PLANE_ORIGIN: i32 = 147; +pub const FACE_PLANE_AXIS: i32 = 148; +pub const FACE_PLANE_REF_DIRECTION: i32 = 149; +pub const FACE_CYLINDER_ORIGIN: i32 = 150; +pub const FACE_CYLINDER_AXIS: i32 = 151; +pub const FACE_CYLINDER_REF_DIRECTION: i32 = 152; +pub const FACE_CYLINDER_RADIUS: i32 = 153; +pub const FACE_CONE_ORIGIN: i32 = 154; +pub const FACE_CONE_AXIS: i32 = 155; +pub const FACE_CONE_REF_DIRECTION: i32 = 156; +pub const FACE_CONE_RADIUS: i32 = 157; +pub const FACE_CONE_SEMI_ANGLE: i32 = 158; +pub const FACE_TORUS_ORIGIN: i32 = 159; +pub const FACE_TORUS_AXIS: i32 = 160; +pub const FACE_TORUS_REF_DIRECTION: i32 = 161; +pub const FACE_TORUS_MAJOR_RADIUS: i32 = 162; +pub const FACE_TORUS_MINOR_RADIUS: i32 = 163; +pub const EDGE_TOLERANCE: i32 = 164; +pub const VERTEX_TOLERANCE: i32 = 165; +/// The definitions counted in `FACE_DEFINITION_REAL_COUNT`, packed in face order: a ball patch's +/// sphere's centre x, y, z and radius. +pub const FACE_DEFINITION_REALS: i32 = 166; +/// The largest EDGE_TOLERANCE or VERTEX_TOLERANCE import takes (smlib.h: "at most 1"). +pub const MAX_TOLERANCE: f64 = 1.0; +/// `SMLIB_FLAT_MAX_LEN`: no array is longer. +pub const MAX_LEN: usize = 1 << 27; +pub const SURFACE_NURBS: u8 = 0; +pub const SURFACE_PLANE: u8 = 1; +pub const SURFACE_CYLINDER: u8 = 2; +pub const SURFACE_CONE: u8 = 3; +pub const SURFACE_SPHERE: u8 = 4; +pub const SURFACE_TORUS: u8 = 5; +/// A rational patch on a sphere (SMLib's `SmBallPatch`): its NURBS block, range and trims as a +/// NURBS face's, and its sphere in `FACE_DEFINITION_REALS`. +pub const SURFACE_BALL_PATCH: u8 = 6; +pub const CURVE_NURBS: u8 = 0; +pub const CURVE_LINE: u8 = 1; +pub const CURVE_CIRCLE: u8 = 2; +pub const CURVE_ELLIPSE: u8 = 3; + +impl Brep { + /// Whether SMLib finds this body one closed, manifold solid. + pub fn is_manifold_solid(&self) -> Result { + crate::core::is_manifold_solid(self.core()) + } +} diff --git a/crates/smlib/src/history.rs b/crates/smlib/src/history.rs new file mode 100644 index 000000000..dd9294a91 --- /dev/null +++ b/crates/smlib/src/history.rs @@ -0,0 +1,228 @@ +//! Face and edge history out of SMLib operations, in [`solidcore_record::brep::history`]'s terms. +//! +//! SMLib carries identity through its own edits: every split, merge, copy and coincidence an +//! operation makes passes the attributes of what it changes on to what it makes. So each operand +//! is tagged ([`Brep::tagged`]: face i and edge i become operand k's face i and edge i), the +//! operation runs on the tagged copies, and the result's tags say where each face and edge came +//! from ([`Brep::history`]). Nothing is sampled or guessed. +//! +//! Indices here are SMLib's own: positions in a body's face and edge lists, which a copy keeps. +//! [`Raw::history`] renumbers them into canonical order (docs/native-brep.md) with the +//! [`Order`] the export gives each body. + +use std::collections::BTreeSet; + +use solidcore_record::brep::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, Failed, History, Side}; + +use crate::{Brep, Result, core}; + +/// A result face as SMLib reports it: how it relates to its origins, and the (operand, face) +/// pairs it came from, sorted. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RawFace { + pub change: Change, + pub origins: Vec<(usize, usize)>, +} + +/// A result edge as SMLib reports it: the result faces it bounds (ascending) and the (operand, +/// edge) pairs it came from, sorted; none where it is new (where its faces meet). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RawEdge { + pub faces: Vec, + pub origins: Vec<(usize, usize)>, +} + +/// A result's history in SMLib's own face and edge order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Raw { + pub faces: Vec, + pub edges: Vec, +} + +/// Where one body's faces and edges go in canonical order: `faces[i]` is the canonical index of +/// SMLib's face i, likewise for edges. Empty means SMLib's order is the canonical one. +/// +/// An SMLib edge solids touch along (non-manifold) becomes one record edge per solid: +/// `edges[i]` is the first of them, and `pieces` lists every piece of such an edge, the first +/// too, with the canonical faces it bounds. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Order { + pub faces: Vec, + pub edges: Vec, + pub pieces: Vec, +} + +/// One record edge of an SMLib edge split where solids touch along it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Piece { + /// The SMLib edge. + pub edge: usize, + /// The record edge. + pub canonical: usize, + /// The canonical faces it bounds, ascending. + pub faces: Vec, +} + +impl Brep { + /// A copy whose face i and edge i are tagged as face i and edge i of operand `operand` (in + /// SMLib's order, which the copy keeps). Run an operation on tagged copies, then read its + /// result's [`Brep::history`]. + pub fn tagged(&self, operand: usize) -> Result { + let r = core::history::tag(self.core(), operand).map(Brep::made_core); + crate::trace::made("tagged", &[self], &r, || serde_json::json!({"operand": operand})); + r + } + + /// The history of this body, made by an operation from tagged operands: each face's and + /// edge's origins among them. Faces and edges no tag reached have none. + pub fn history(&self) -> Result { + core::history::read(self.core()) + } +} + +impl Raw { + /// As a [`History`] over `operands.len()` operands, every index renumbered into canonical + /// order: operand k's through `operands[k]`, the result's through `result`. An edge with no + /// origin is where its two faces meet; one bounding other than two faces, or a face new to + /// the operation, has no origin at all. + pub fn history(&self, operands: &[Order], result: &Order) -> std::result::Result { + let bad = |what: &'static str| Failed(what); + let map = |order: &[usize], i: usize| -> std::result::Result { + if order.is_empty() { Ok(i) } else { order.get(i).copied().ok_or(bad("an index lies outside its body's order")) } + }; + let operand = |k: usize| operands.get(k).ok_or(bad("an origin lies on no operand")); + let face_origin = |(k, f): (usize, usize)| -> std::result::Result { + let o = operand(k)?; + Ok(FaceOrigin::Face { operand: k, face: map(&o.faces, f)? }) + }; + // The result's faces and edges, each at its canonical place. + let place = |order: &[usize], n: usize| -> std::result::Result, Failed> { + let at: Vec = (0..n).map(|i| map(order, i)).collect::>()?; + let distinct: BTreeSet = at.iter().copied().collect(); + if distinct.len() != n || at.iter().any(|c| *c >= n) { + return Err(bad("the result's order is no permutation")); + } + Ok(at) + }; + let fat = place(&result.faces, self.faces.len())?; + // Each raw edge's record edges with the faces each bounds where it is split (`None`: as + // SMLib has them); together a permutation of the result's edges. + let n_edges = self.edges.len() + result.pieces.len() - result.pieces.iter().map(|p| p.edge).collect::>().len(); + let mut targets: Vec<(usize, usize, Option<&[usize]>)> = Vec::with_capacity(n_edges); + for i in 0..self.edges.len() { + let mut split = result.pieces.iter().filter(|p| p.edge == i).peekable(); + if split.peek().is_none() { + targets.push((i, map(&result.edges, i)?, None)); + } else { + targets.extend(split.map(|p| (i, p.canonical, Some(p.faces.as_slice())))); + } + } + let distinct: BTreeSet = targets.iter().map(|t| t.1).collect(); + if targets.len() != n_edges || distinct.len() != n_edges || targets.iter().any(|t| t.1 >= n_edges) { + return Err(bad("the result's order is no permutation")); + } + + let mut faces: Vec> = vec![None; self.faces.len()]; + for (f, at) in self.faces.iter().zip(&fat) { + let origins: BTreeSet = f.origins.iter().map(|o| face_origin(*o)).collect::>()?; + faces[*at] = Some(FaceProv { origins: origins.into_iter().collect(), change: f.change }); + } + let faces: Vec = faces.into_iter().collect::>().ok_or(bad("the result's order is no permutation"))?; + + let mut edges: Vec> = vec![None; n_edges]; + for &(i, at, split) in &targets { + let e = self.edges.get(i).ok_or(bad("an edge lies outside the result"))?; + let bounds: Vec = match split { + Some(faces) => faces.to_vec(), + None => { + let bounds: BTreeSet = e + .faces + .iter() + .map(|f| fat.get(*f).copied().ok_or(bad("an edge lies on a face outside the result"))) + .collect::>()?; + bounds.into_iter().collect() + } + }; + let origins = if e.origins.is_empty() { + // New: where its two faces meet, each side what that face came from. Between two + // pieces of one face (a split line) nothing met: it comes from nothing. + let side = |f: usize| faces.get(f).and_then(|p| Side::new(p.origins.iter().copied())); + match bounds.as_slice() { + [a, b] => side(*a).zip(side(*b)).filter(|(a, b)| a != b).map(|(a, b)| EdgeOrigin::meet(a, b)).into_iter().collect(), + _ => Vec::new(), + } + } else { + let set: BTreeSet = e + .origins + .iter() + .map(|(k, i)| { + let o = operand(*k)?; + Ok(EdgeOrigin::Edge { operand: *k, edge: map(&o.edges, *i)? }) + }) + .collect::>()?; + set.into_iter().collect() + }; + *edges.get_mut(at).ok_or(bad("the result's order is no permutation"))? = Some(EdgeProv { faces: bounds, origins }); + } + let edges: Vec = edges.into_iter().collect::>().ok_or(bad("the result's order is no permutation"))?; + Ok(History { operands: operands.len(), faces, edges }) + } +} + +/// A blend's faces (fillet, chamfer) in `h`, the history of a blend of edges `picked` of its +/// one operand (operand 0), whose own edges `operand` lists (the faces each bounds, as in the +/// operand's identity history), which also took up edges `taken_up` (no result edge comes from +/// them: a corner's short edge, or an edge the blend ran over): SMLib makes a blend face with no +/// tag, so each Generated face is given [`FaceOrigin::Edge`] for every picked edge whose two +/// faces both lie under faces next to it and no longer meet each other directly, and only where +/// no picked edge is such, every taken-up edge that is. A chamfer running up past the end of the +/// face beside it takes up that face's side edge and lies between its faces too: it is made from +/// the picked edge alone. A corner patch between several blends matches none of them and stays +/// without origin. +pub fn blends(h: &mut History, operand: &[EdgeProv], picked: &[usize], taken_up: &[usize]) { + let mut next_to: Vec> = vec![BTreeSet::new(); h.faces.len()]; + for e in &h.edges { + for f in &e.faces { + for g in &e.faces { + if let (Some(set), Some(p)) = (next_to.get_mut(*f), h.faces.get(*g)) + && f != g + { + set.extend(p.origins.iter().copied()); + } + } + } + } + // Pairs of operand faces whose result faces still meet along an edge. + let mut meeting: BTreeSet<(FaceOrigin, FaceOrigin)> = BTreeSet::new(); + for e in &h.edges { + if let [a, b] = e.faces.as_slice() + && let (Some(a), Some(b)) = (h.faces.get(*a), h.faces.get(*b)) + { + for x in &a.origins { + for y in &b.origins { + meeting.insert((*x.min(y), *x.max(y))); + } + } + } + } + for (f, around) in h.faces.iter_mut().zip(&next_to) { + if f.change != Change::Generated || !f.origins.is_empty() { + continue; + } + let under = |e: &&usize| { + operand.get(**e).is_some_and(|p| { + let [a, b] = p.faces.as_slice() else { return false }; + let (a, b) = (FaceOrigin::Face { operand: 0, face: *a }, FaceOrigin::Face { operand: 0, face: *b }); + around.contains(&a) && around.contains(&b) && !meeting.contains(&(a.min(b), a.max(b))) + }) + }; + let mut edges: Vec = picked.iter().filter(under).copied().collect(); + if edges.is_empty() { + edges = taken_up.iter().filter(under).copied().collect(); + } + f.origins = edges.into_iter().map(|e| FaceOrigin::Edge { operand: 0, edge: e }).collect(); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/smlib/src/history/tests.rs b/crates/smlib/src/history/tests.rs new file mode 100644 index 000000000..7fd479fe3 --- /dev/null +++ b/crates/smlib/src/history/tests.rs @@ -0,0 +1,117 @@ +use super::*; +use crate::Error; +use solidcore_record::brep::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History}; + +fn face(operand: usize, face: usize) -> FaceOrigin { + FaceOrigin::Face { operand, face } +} + +/// Two boxes joined across a face: face 0 is operand 0's face 2 kept, face 1 operand 1's face 4 +/// trimmed, face 2 both boxes' coplanar faces 0 merged. Edge 0 is new between faces 0 and 1, edge +/// 1 is operand 0's edge 7, edge 2 joins edge 3 of each box and bounds faces 1 and 2. +fn joined() -> Raw { + Raw { + faces: vec![ + RawFace { change: Change::Kept, origins: vec![(0, 2)] }, + RawFace { change: Change::Modified, origins: vec![(1, 4)] }, + RawFace { change: Change::Merged, origins: vec![(0, 0), (1, 0)] }, + ], + edges: vec![ + RawEdge { faces: vec![0, 1], origins: vec![] }, + RawEdge { faces: vec![0, 2], origins: vec![(0, 7)] }, + RawEdge { faces: vec![1, 2], origins: vec![(0, 3), (1, 3)] }, + ], + } +} + +#[test] +fn new_edges_are_where_their_faces_meet() { + let raw = joined(); + let h = raw.history(&[Order::default(), Order::default()], &Order::default()).unwrap(); + assert_eq!(h.operands, 2); + assert_eq!(h.faces[0].origins, vec![face(0, 2)]); + assert_eq!(h.faces[0].change, Change::Kept); + assert_eq!(h.edges[0].origins, vec![EdgeOrigin::meet(face(0, 2), face(1, 4))]); + assert_eq!(h.edges[1].origins, vec![EdgeOrigin::Edge { operand: 0, edge: 7 }]); + assert_eq!(h.edges[2].origins, vec![EdgeOrigin::Edge { operand: 0, edge: 3 }, EdgeOrigin::Edge { operand: 1, edge: 3 }]); + assert_eq!(h.edges[2].faces, vec![1, 2]); + h.check_counts((3, 3), &[(3, 8), (5, 4)]).unwrap(); +} + +/// A face split in two (a split line across operand 0's face 0): the new edge lies between two +/// pieces of one face, where nothing met, so it comes from nothing. +#[test] +fn a_split_line_comes_from_nothing() { + let piece = RawFace { change: Change::Split, origins: vec![(0, 0)] }; + let raw = Raw { faces: vec![piece.clone(), piece], edges: vec![RawEdge { faces: vec![0, 1], origins: vec![] }] }; + let h = raw.history(&[Order::default()], &Order::default()).unwrap(); + assert_eq!(h.faces.iter().map(|f| (f.origins.clone(), f.change)).collect::>(), vec![(vec![face(0, 0)], Change::Split); 2]); + assert_eq!(h.edges[0].faces, vec![0, 1]); + assert!(h.edges[0].origins.is_empty(), "{:?}", h.edges[0].origins); +} + +#[test] +fn renumbers_into_canonical_order() { + let raw = joined(); + // Operand 0's SMLib face 2 is its canonical face 5, edge 7 its edge 0; the result's faces + // and edges are listed backwards. + let a = Order { faces: vec![1, 2, 5, 0, 3, 4], edges: vec![1, 2, 3, 4, 5, 6, 7, 0], pieces: vec![] }; + let b = Order { faces: vec![0, 1, 2, 3, 4], edges: vec![0, 1, 2, 3], pieces: vec![] }; + let result = Order { faces: vec![2, 1, 0], edges: vec![2, 1, 0], pieces: vec![] }; + let h = raw.history(&[a, b], &result).unwrap(); + assert_eq!(h.faces[2].origins, vec![face(0, 5)]); + assert_eq!(h.faces[0].origins, vec![face(0, 1), face(1, 0)]); + assert_eq!(h.edges[1].origins, vec![EdgeOrigin::Edge { operand: 0, edge: 0 }]); + // The new edge now bounds result faces 2 and 1, and meets the renumbered origins. + assert_eq!(h.edges[2].faces, vec![1, 2]); + assert_eq!(h.edges[2].origins, vec![EdgeOrigin::meet(face(0, 5), face(1, 4))]); +} + +#[test] +fn bad_orders_are_errors() { + let raw = joined(); + let ok = Order::default(); + // An origin on an operand that isn't there. + assert!(raw.history(std::slice::from_ref(&ok), &ok).is_err()); + // An operand order too short for an origin. + assert!(raw.history(&[Order { faces: vec![0], edges: vec![], pieces: vec![] }, ok.clone()], &ok).is_err()); + // A result order that isn't a permutation. + assert!(raw.history(&[ok.clone(), ok.clone()], &Order { faces: vec![0, 0, 1], edges: vec![], pieces: vec![] }).is_err()); + assert!(raw.history(&[ok.clone(), ok.clone()], &Order { faces: vec![0, 1, 3], edges: vec![], pieces: vec![] }).is_err()); +} + +/// A box with its edge 0 (between faces 4 and 5) filleted, as SMLib reports it: the fillet face +/// (6) has no tag; it lies between faces from 4 and 5 and two end faces. +#[test] +fn a_fillet_face_comes_from_its_edge() { + let kept = |i: usize| FaceProv { origins: vec![face(0, i)], change: Change::Modified }; + let mut faces: Vec = (0..6).map(kept).collect(); + faces.push(FaceProv { origins: vec![], change: Change::Generated }); + let edge = |a: usize, b: usize| EdgeProv { faces: vec![a, b], origins: vec![] }; + let mut h = History { operands: 1, faces, edges: vec![edge(4, 6), edge(5, 6), edge(0, 6), edge(2, 6), edge(0, 4)] }; + // The operand's own edges: edge 0 between faces 4 and 5, edge 1 between 0 and 4. + let operand = vec![edge(4, 5), edge(0, 4)]; + blends(&mut h, &operand, &[0], &[1]); + assert_eq!(h.faces[6].origins, vec![FaceOrigin::Edge { operand: 0, edge: 0 }]); + assert!(h.faces[..6].iter().all(|f| f.origins.len() == 1)); +} + +#[test] +fn a_tagged_body_is_its_own_history() { + let b = Brep::make_box([0.0; 3], [1.0, 2.0, 3.0]).unwrap(); + let raw = b.tagged(4).unwrap().history().unwrap(); + assert_eq!((raw.faces.len(), raw.edges.len()), (6, 12)); + for (i, f) in raw.faces.iter().enumerate() { + assert_eq!(f, &RawFace { change: Change::Kept, origins: vec![(4, i)] }); + } + for (i, e) in raw.edges.iter().enumerate() { + assert_eq!(e.origins, vec![(4, i)]); + assert_eq!(e.faces.len(), 2); + } + // Untagged: every face new, every edge where two of them meet. + let raw = b.history().unwrap(); + assert!(raw.faces.iter().all(|f| f.change == Change::Generated && f.origins.is_empty())); + let h = raw.history(&[], &Order::default()).unwrap(); + assert!(h.edges.iter().all(|e| e.origins.is_empty())); + assert_eq!(b.tagged(usize::MAX).unwrap_err(), Error::Argument); +} diff --git a/crates/smlib/src/import.rs b/crates/smlib/src/import.rs new file mode 100644 index 000000000..af64c049f --- /dev/null +++ b/crates/smlib/src/import.rs @@ -0,0 +1,687 @@ +//! Schema 4 records (`solidcore_record::brep::Brep`) into SMLib: the record is laid out as the C +//! API's flat arrays (`capi/include/smlib.h`, "Flat B-rep arrays"), which solidcore builds into +//! its B-rep ([`crate::core::from_arrays`]). +//! +//! The two models differ in four places, and the mapping takes care of each: +//! - A closed shell is one record listed by the two regions it separates; SMLib keeps one shell +//! per region, the face used on opposite sides. A sheet's shell holds both sides of its faces. +//! - The infinite region is never a void here; SMLib marks it as one. +//! - Pcurves run along the edge (interval min → max) here; SMLib's UV trims run along their +//! edgeuse. They are carried on B-spline faces only: on analytic faces SMLib keeps its trims in +//! its own parameterisation and rebuilds them from the 3D edges. +//! - Every end value (edge intervals, face domains) is already in the flat arrays' units, radians +//! for angles; the C side converts them to SMLib's own pointwise. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use solidcore_record::brep as b; + +use crate::flat; + +/// Why a record cannot go to SMLib. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Unsupported { + /// The record failed `Brep::validate`. + Invalid(&'static str), + /// A part of schema 4 this mapping does not carry yet. + NotYet(&'static str), +} + +impl std::fmt::Display for Unsupported { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Unsupported::Invalid(w) => write!(f, "invalid B-rep record: {w}"), + Unsupported::NotYet(w) => write!(f, "not supported yet: {w} in SMLib"), + } + } +} + +type R = std::result::Result; + +/// The flat arrays of one B-rep, by array id. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Arrays { + pub ints: BTreeMap>, + pub reals: BTreeMap>, +} + +impl Arrays { + fn i(&mut self, id: i32) -> &mut Vec { + self.ints.entry(id).or_default() + } + fn r(&mut self, id: i32) -> &mut Vec { + self.reals.entry(id).or_default() + } + fn r3(&mut self, id: i32, p: [f64; 3]) { + self.r(id).extend(p); + } +} + +fn int(n: usize) -> R { + i64::try_from(n).map_err(|_| Unsupported::Invalid("count")) +} + +fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} +fn dot(a: [f64; 3], b: [f64; 3]) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} +fn add(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} +fn scale(a: [f64; 3], s: f64) -> [f64; 3] { + [a[0] * s, a[1] * s, a[2] * s] +} +fn z_axis(f: &b::Frame) -> [f64; 3] { + cross(f.x_axis, f.y_axis) +} + +/// The record as flat arrays. `trusted`: the record comes from a modeller that keeps SMLib's +/// rules (SMLib then skips its healer); otherwise SMLib heals it on import. +pub fn arrays(brep: &b::Brep, trusted: bool) -> R { + solidcraft_geom::brep::check::validate_built(brep).map_err(|e| Unsupported::Invalid(e.0))?; + let brep = analytic::analytic(brep)?; + laid_out(brep.as_ref(), trusted, true, &HashSet::new()) +} + +/// [`arrays`] with every surface as the record holds it: a round face truck holds as a rational +/// spline (an extruded circle) stays one, and a plane off unit orthogonal axes goes as its +/// bilinear patch, to compare what SMLib makes of splines with what it makes of its own analytic +/// surfaces. A revolution is still refused (SMLib has no such surface). +pub fn arrays_keeping_splines(brep: &b::Brep, trusted: bool) -> R { + solidcraft_geom::brep::check::validate_built(brep).map_err(|e| Unsupported::Invalid(e.0))?; + laid_out(brep, trusted, false, &HashSet::new()) +} + +/// The flat arrays of a record whose uses in `bare` (face, loop, position) go without their +/// UV trims, for SMLib to make (their pcurves in the record are not read): what +/// [`crate::pcurves`] hands SMLib. Not validated, as its bare uses have no pcurves. +pub(crate) fn arrays_with_bare_uses(brep: &b::Brep, bare: &HashSet<(u32, u32, u32)>) -> R { + laid_out(brep, true, true, bare) +} + +/// The flat arrays; `analytic`: a plane on any axes goes as SMLib's plane (else, off unit +/// orthogonal axes, as the bilinear patch it is). The uses in `bare` go without UV trims. +fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool, bare: &HashSet<(u32, u32, u32)>) -> R { + let mut a = Arrays::default(); + + // Regions and shells. Each region gets its own copy of each shell it lists. + let enclosed_by: HashMap = + brep.regions.iter().enumerate().skip(1).filter_map(|(r, region)| region.shells.first().map(|&s| (s, r))).collect(); + let listed = |s: u32| brep.regions.iter().filter(|r| r.shells.contains(&s)).count(); + for (r, region) in brep.regions.iter().enumerate() { + a.i(flat::REGION_SHELL_COUNT).push(int(region.shells.len())?); + // SMLib marks the infinite region as a void. + a.i(flat::REGION_TYPE).push(i64::from(r == 0 || region.void)); + for (k, &s) in region.shells.iter().enumerate() { + let Some(b::Shell::Faces { faces, wires }) = brep.shells.get(s as usize) else { + return Err(Unsupported::NotYet("wire and vertex shells")); + }; + if !wires.is_empty() { + return Err(Unsupported::NotYet("wire edges embedded in a shell")); + } + let uses: Vec<(u32, bool)> = if listed(s) == 2 { + // A closed shell: the outward normals (out of the material) point into the + // region that is not material. As the outer shell of region r (k == 0) the shell + // encloses r; as an inner shell r lies outside it. + let inside = enclosed_by.get(&s).copied().ok_or(Unsupported::Invalid("closed shell encloses no region"))?; + let inside_is_void = brep.regions.get(inside).is_some_and(|e| e.void); + let normals_into_this = if k == 0 && r > 0 { inside_is_void } else { !inside_is_void }; + faces.iter().map(|f| (f.face, f.forward == normals_into_this)).collect() + } else { + // An open shell lies in one region and holds both sides of each face. + faces.iter().flat_map(|f| [(f.face, true), (f.face, false)]).collect() + }; + a.i(flat::SHELL_FACEUSE_COUNT).push(int(uses.len())?); + a.i(flat::SHELL_WIRE_EDGE_COUNT).push(0); + a.i(flat::SHELL_POINT_TYPE).push(0); + for (face, same) in uses { + a.i(flat::FACEUSE_FACE).push(i64::from(face)); + a.i(flat::FACEUSE_ORIENTATION).push(i64::from(same)); + } + } + } + + // Edgeuses are numbered face → loop → position. + let mut eu_index: HashMap<(u32, u32, u32), i64> = HashMap::new(); + let mut n = 0i64; + for (fi, f) in brep.faces.iter().enumerate() { + for (li, l) in f.loops.iter().enumerate() { + if let b::Loop::Edges { edges } = l { + for p in 0..edges.len() { + eu_index.insert((idx(fi)?, idx(li)?, idx(p)?), n); + n += 1; + } + } + } + } + let mut next = vec![-1i64; usize::try_from(n).unwrap_or(0)]; + let mut entry = vec![0i64; next.len()]; + for e in &brep.edges { + let at = |u: &b::EdgeUseRef| eu_index.get(&(u.face, u.r#loop, u.position)).copied().ok_or(Unsupported::Invalid("edge use")); + for (k, u) in e.uses.iter().enumerate() { + let here = at(u)?; + let after = e.uses.get((k + 1) % e.uses.len()).ok_or(Unsupported::Invalid("edge use"))?; + let slot = usize::try_from(here).map_err(|_| Unsupported::Invalid("edge use"))?; + *next.get_mut(slot).ok_or(Unsupported::Invalid("edge use"))? = at(after)?; + *entry.get_mut(slot).ok_or(Unsupported::Invalid("edge use"))? = i64::from(u.upper); + } + } + + // Each edge's interval as SMLib takes it, and how far it moved (see `turned`). + // An edge on its NURBS form keeps that NURBS's interval. + let intervals: Vec<([f64; 2], f64)> = + brep.edges.iter().map(|e| if e.nurbs.is_some() { (e.interval, 0.0) } else { turned(&e.curve, e.interval) }).collect(); + + // Faces, loops and edgeuses, with the surfaces and, on B-spline faces, the trims. + let any_spline_face = + brep.faces.iter().any(|f| f.nurbs.is_some() || matches!(f.surface, b::Surface::Spline { .. } | b::Surface::RationalSpline { .. })); + let any_form = brep.faces.iter().any(|f| f.nurbs.is_some()); + for (fi, f) in brep.faces.iter().enumerate() { + a.i(flat::FACE_LOOP_COUNT).push(int(f.loops.len())?); + a.i(flat::FACE_TRIM_TYPE).push(0); + // A face with a NURBS form: what it is (its analytic entry), then the NURBS it is + // parameterised on, whose range and trims these are (FACE_NURBS_FORM). A revolution + // (SMLib has no class for one) is that form alone, a NURBS face. A ball patch is its form + // too, as a NURBS face's block under its own kind, with its sphere as its definition. + let form_is_face = f.nurbs.is_some() && matches!(f.surface, b::Surface::PlacedRevolution { .. } | b::Surface::BallPatch { .. }); + let spline = match (&f.nurbs, &f.surface) { + (Some(n), b::Surface::BallPatch { center, radius }) => ball_patch(&mut a, n, *center, *radius, f.domain)?, + (Some(n), _) if form_is_face => surface(&mut a, n, f.domain, analytic)?, + (Some(n), _) => { + surface(&mut a, &f.surface, f.domain, analytic)?; + nurbs_block(&mut a, n)?; + true + } + // SMLib's tube angle counts from the outer equator, the record's from its tube start. + (None, _) => match f.surface { + b::Surface::Torus { tube_start, .. } => { + let [u, v] = f.domain; + surface(&mut a, &f.surface, [u, v.map(|t| t + tube_start)], analytic)? + } + _ => surface(&mut a, &f.surface, f.domain, analytic)?, + }, + }; + if any_form { + a.i(flat::FACE_NURBS_FORM).push(i64::from(f.nurbs.is_some() && !form_is_face)); + } + for (li, l) in f.loops.iter().enumerate() { + match l { + b::Loop::Vertex { vertex } => { + a.i(flat::LOOP_EDGEUSE_COUNT).push(0); + a.i(flat::LOOP_VERTEX).push(i64::from(*vertex)); + } + b::Loop::Edges { edges } => { + a.i(flat::LOOP_EDGEUSE_COUNT).push(int(edges.len())?); + a.i(flat::LOOP_VERTEX).push(-1); + for (p, u) in edges.iter().enumerate() { + a.i(flat::EDGEUSE_EDGE).push(i64::from(u.edge)); + a.i(flat::EDGEUSE_ORIENTATION).push(i64::from(u.forward)); + if any_spline_face { + if spline && !bare.contains(&(idx(fi)?, idx(li)?, idx(p)?)) { + let shift = intervals.get(u.edge as usize).map_or(0.0, |i| i.1); + trim(&mut a, &u.pcurve, u.forward, shift)?; + } else { + a.i(flat::EDGEUSE_NURBS_VERTEX_COUNT).push(0); + a.i(flat::EDGEUSE_NURBS_ORDER).push(0); + } + } + } + } + } + } + } + a.i(flat::EDGEUSE_NEXT_RADIAL).extend(next); + a.i(flat::EDGEUSE_RADIAL_ENTRY).extend(entry); + + let any_edge_form = brep.edges.iter().any(|e| e.nurbs.is_some()); + for (e, (interval, _)) in brep.edges.iter().zip(&intervals) { + // A circle or ellipse on its NURBS form: what it is (its conic entry), then the NURBS it + // is parameterised on (EDGE_NURBS_FORM). Another curve on a NURBS form is written as that + // NURBS, whose parameter the edge's interval and trims are in. + let form = match (&e.curve, &e.nurbs) { + (b::Curve::Circle { .. } | b::Curve::Ellipse { .. }, Some(n)) => { + curve(&mut a, &e.curve)?; + edge_nurbs_block(&mut a, n)?; + true + } + (_, Some(n)) => { + curve(&mut a, n)?; + false + } + (_, None) => { + curve(&mut a, &e.curve)?; + false + } + }; + if any_edge_form { + a.i(flat::EDGE_NURBS_FORM).push(i64::from(form)); + } + a.i(flat::EDGE_VERTICES).extend([i64::from(e.vertices[0]), i64::from(e.vertices[1])]); + a.r(flat::EDGE_RANGE).extend(*interval); + // Each edge's own tolerance, never below the body's, and never past what SMLib takes. + let tolerance = e.tolerance.max(brep.tolerance); + if !(tolerance <= flat::MAX_TOLERANCE) { + return Err(Unsupported::NotYet("an edge tolerance over 1 mm")); + } + a.r(flat::EDGE_TOLERANCE).push(tolerance); + } + + let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); + for v in &brep.vertices { + a.i(flat::VERTEX_POINT_TYPE).push(1); + a.r3(flat::VERTEX_POSITION, v.point); + let tolerance = v.tolerance.max(brep.tolerance); + if !(tolerance <= flat::MAX_TOLERANCE) { + return Err(Unsupported::NotYet("a vertex tolerance over 1 mm")); + } + a.r(flat::VERTEX_TOLERANCE).push(tolerance); + for k in 0..3 { + lo[k] = lo[k].min(v.point[k]); + hi[k] = hi[k].max(v.point[k]); + } + } + if brep.vertices.is_empty() { + (lo, hi) = ([0.0; 3], [0.0; 3]); + } + a.r(flat::EXTENT).extend(lo.into_iter().chain(hi)); + a.r(flat::TOLERANCE).push(brep.tolerance); + a.i(flat::SOURCE).push(i64::from(trusted)); + Ok(a) +} + +fn idx(i: usize) -> R { + u32::try_from(i).map_err(|_| Unsupported::Invalid("index")) +} + +/// A NURBS net's control points and weights, cartesian, U-major. +fn net(a: &mut Arrays, rows: impl Iterator) { + for (p, w) in rows { + a.r3(flat::FACE_NURBS_CVS, p); + a.r(flat::FACE_NURBS_WEIGHTS).push(w); + } +} + +fn nurbs_face(a: &mut Arrays, u_knots: &[f64], v_knots: &[f64], nu: usize, nv: usize) -> R<()> { + a.i(flat::FACE_SURFACE_TYPE).push(i64::from(flat::SURFACE_NURBS)); + nurbs_sizes(a, u_knots, v_knots, nu, nv) +} + +/// A NURBS block's sizes, orders and knots. +fn nurbs_sizes(a: &mut Arrays, u_knots: &[f64], v_knots: &[f64], nu: usize, nv: usize) -> R<()> { + let order = |k: &[f64], n: usize| k.len().checked_sub(n).filter(|o| *o >= 2).ok_or(Unsupported::Invalid("spline order")); + a.i(flat::FACE_NURBS_U_VERTEX_COUNT).push(int(nu)?); + a.i(flat::FACE_NURBS_V_VERTEX_COUNT).push(int(nv)?); + a.i(flat::FACE_NURBS_U_ORDER).push(int(order(u_knots, nu)?)?); + a.i(flat::FACE_NURBS_V_ORDER).push(int(order(v_knots, nv)?)?); + a.r(flat::FACE_NURBS_U_KNOTS).extend_from_slice(u_knots); + a.r(flat::FACE_NURBS_V_KNOTS).extend_from_slice(v_knots); + Ok(()) +} + +/// The NURBS block of a face's NURBS form, with no surface kind or range of its own. +fn nurbs_block(a: &mut Arrays, s: &b::Surface) -> R<()> { + match s { + b::Surface::Spline { u_knots, v_knots, points } => { + nurbs_sizes(a, u_knots, v_knots, points.len(), points.first().map_or(0, Vec::len))?; + net(a, points.iter().flatten().map(|p| (*p, 1.0))); + } + b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + nurbs_sizes(a, u_knots, v_knots, homogeneous.len(), homogeneous.first().map_or(0, Vec::len))?; + net(a, homogeneous.iter().flatten().map(|h| ([h[0] / h[3], h[1] / h[3], h[2] / h[3]], h[3]))); + } + _ => return Err(Unsupported::Invalid("NURBS form is not a NURBS")), + } + Ok(()) +} + +/// A ball patch's face: its net `n` as a NURBS face's block and range under the ball patch's kind, +/// and its sphere as its definition (SMLib checks the net is on it). True: it carries trims. +fn ball_patch(a: &mut Arrays, n: &b::Surface, center: [f64; 3], radius: f64, domain: [[f64; 2]; 2]) -> R { + let [[u0, u1], [v0, v1]] = domain; + a.i(flat::FACE_SURFACE_TYPE).push(i64::from(flat::SURFACE_BALL_PATCH)); + nurbs_block(a, n)?; + a.r(flat::FACE_RANGE).extend([u0, v0, u1, v1]); + a.i(flat::FACE_DEFINITION_REAL_COUNT).push(4); + a.r3(flat::FACE_DEFINITION_REALS, center); + a.r(flat::FACE_DEFINITION_REALS).push(radius); + Ok(true) +} + +/// The face's surface and range; true for a B-spline surface (which carries trims). +fn surface(a: &mut Arrays, s: &b::Surface, domain: [[f64; 2]; 2], analytic_planes: bool) -> R { + let [[u0, u1], [v0, v1]] = domain; + let analytic = |a: &mut Arrays, kind: u8, ids: [i32; 3], f: &b::Frame| { + a.i(flat::FACE_SURFACE_TYPE).push(i64::from(kind)); + a.r3(ids[0], f.origin); + a.r3(ids[1], z_axis(f)); + a.r3(ids[2], f.x_axis); + a.r(flat::FACE_RANGE).extend([u0, v0, u1, v1]); + }; + match s { + b::Surface::Plane { origin, u_axis, v_axis } => plane(a, *origin, *u_axis, *v_axis, domain, analytic_planes)?, + b::Surface::PlaneThrough { origin, u_point, v_point } => { + plane(a, *origin, sub(*u_point, *origin), sub(*v_point, *origin), domain, analytic_planes)? + } + b::Surface::Cylinder { frame, radius } => { + analytic(a, flat::SURFACE_CYLINDER, [flat::FACE_CYLINDER_ORIGIN, flat::FACE_CYLINDER_AXIS, flat::FACE_CYLINDER_REF_DIRECTION], frame); + a.r(flat::FACE_CYLINDER_RADIUS).push(*radius); + } + b::Surface::Cone { frame, radius_at_origin, half_angle } => { + analytic(a, flat::SURFACE_CONE, [flat::FACE_CONE_ORIGIN, flat::FACE_CONE_AXIS, flat::FACE_CONE_REF_DIRECTION], frame); + a.r(flat::FACE_CONE_RADIUS).push(*radius_at_origin); + a.r(flat::FACE_CONE_SEMI_ANGLE).push(*half_angle); + } + b::Surface::Sphere { frame, radius } => { + analytic(a, flat::SURFACE_SPHERE, [flat::FACE_SPHERE_CENTER, flat::FACE_SPHERE_AXIS, flat::FACE_SPHERE_REF_DIRECTION], frame); + a.r(flat::FACE_SPHERE_RADIUS).push(*radius); + } + b::Surface::Torus { frame, major_radius, minor_radius, .. } => { + analytic(a, flat::SURFACE_TORUS, [flat::FACE_TORUS_ORIGIN, flat::FACE_TORUS_AXIS, flat::FACE_TORUS_REF_DIRECTION], frame); + a.r(flat::FACE_TORUS_MAJOR_RADIUS).push(*major_radius); + a.r(flat::FACE_TORUS_MINOR_RADIUS).push(*minor_radius); + } + b::Surface::Spline { u_knots, v_knots, points } => { + let nv = points.first().map_or(0, Vec::len); + nurbs_face(a, u_knots, v_knots, points.len(), nv)?; + net(a, points.iter().flatten().map(|p| (*p, 1.0))); + a.r(flat::FACE_RANGE).extend([u0, v0, u1, v1]); + return Ok(true); + } + b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + let nv = homogeneous.first().map_or(0, Vec::len); + nurbs_face(a, u_knots, v_knots, homogeneous.len(), nv)?; + net(a, homogeneous.iter().flatten().map(|h| ([h[0] / h[3], h[1] / h[3], h[2] / h[3]], h[3]))); + a.r(flat::FACE_RANGE).extend([u0, v0, u1, v1]); + return Ok(true); + } + b::Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => revolution(a, profile, *origin, *axis, matrix, *forward, domain)?, + b::Surface::BallPatch { .. } => return Err(Unsupported::Invalid("a ball patch without its NURBS form")), + } + Ok(false) +} + +/// The quarter-circle arc's rational parameter `s` in [0, 1] at angle `phi` in [0, π/2]: the +/// circle NURBS below is not linear in the angle, so end values are converted pointwise. +fn quarter_param(phi: f64) -> f64 { + let c = std::f64::consts::FRAC_1_SQRT_2; + let angle = |s: f64| { + let (b0, b1, b2) = ((1.0 - s) * (1.0 - s), 2.0 * s * (1.0 - s) * c, s * s); + (b1 + b2).atan2(b0 + b1) + }; + let (mut lo, mut hi) = (0.0f64, 1.0f64); + for _ in 0..64 { + let mid = 0.5 * (lo + hi); + if angle(mid) < phi { + lo = mid; + } else { + hi = mid; + } + } + 0.5 * (lo + hi) +} + +/// The circle NURBS's parameter (knots 0..4, one quarter turn per span) at `angle` after its start. +fn circle_param(angle: f64) -> f64 { + let q = std::f64::consts::FRAC_PI_2; + let a = angle.clamp(0.0, 4.0 * q); + let k = (a / q).floor().min(3.0); + k + quarter_param(a - k * q) +} + +/// A revolution, exactly, as a rational B-spline surface: each profile control point swept round +/// the axis by a full circle of four rational quadratic quarters starting at the face's first +/// angle, then mapped by the placement. The circle's parameter is not the angle, so the face's +/// angle range is converted pointwise and its pcurves are not carried (SMLib rebuilds the trims). +/// Where the placement mirrors, the record's natural normal is the opposite of the map's +/// (`brep::eval`), so the B-spline takes the two directions the other way round. +fn revolution( + a: &mut Arrays, + profile: &b::Curve, + origin: [f64; 3], + axis: [f64; 3], + m: &[[f64; 4]; 4], + forward: bool, + domain: [[f64; 2]; 2], +) -> R<()> { + let (knots, pts): (Vec, Vec<([f64; 3], f64)>) = match profile { + b::Curve::Line { start, end } => (vec![0.0, 0.0, 1.0, 1.0], vec![(*start, 1.0), (*end, 1.0)]), + b::Curve::Spline { knots, points } => (knots.clone(), points.iter().map(|p| (*p, 1.0)).collect()), + b::Curve::RationalSpline { knots, homogeneous } => { + (knots.clone(), homogeneous.iter().map(|h| ([h[0] / h[3], h[1] / h[3], h[2] / h[3]], h[3])).collect()) + } + _ => return Err(Unsupported::NotYet("revolutions of conic, polyline or intersection profiles")), + }; + let len = dot(axis, axis).sqrt(); + if !(len > 0.0) { + return Err(Unsupported::Invalid("revolution axis")); + } + let z = scale(axis, 1.0 / len); + // The record's u and v: the profile's parameter and the angle, or the other way round. + let ([p0, p1], [a0, a1]) = if forward { (domain[0], domain[1]) } else { (domain[1], domain[0]) }; + let t1 = circle_param(a1 - a0); + // Column-major placement: point' = M · (p, 1). + let place = |p: [f64; 3]| [0, 1, 2].map(|r| m[0][r] * p[0] + m[1][r] * p[1] + m[2][r] * p[2] + m[3][r]); + let det = { + let col = |c: usize| [m[c][0], m[c][1], m[c][2]]; + dot(cross(col(0), col(1)), col(2)) + }; + let c = std::f64::consts::FRAC_1_SQRT_2; + // net[i][k]: profile point i at circle control point k. + let mut net: Vec> = Vec::with_capacity(pts.len()); + for (p, w) in &pts { + let r = sub(*p, origin); + let centre = add(origin, scale(z, dot(r, z))); + let x0 = sub(*p, centre); + let y0 = cross(z, x0); + // Start at the face's first angle. + let (s0, c0) = a0.sin_cos(); + let (x, y) = (add(scale(x0, c0), scale(y0, s0)), sub(scale(y0, c0), scale(x0, s0))); + let row = (0..9) + .map(|k| { + let (sk, ck) = (k as f64 * std::f64::consts::FRAC_PI_4).sin_cos(); + let (f, wk) = if k % 2 == 1 { (1.0 / c, c) } else { (1.0, 1.0) }; + (place(add(centre, scale(add(scale(x, ck), scale(y, sk)), f))), w * wk) + }) + .collect(); + net.push(row); + } + let circle_knots = [0.0, 0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 4.0]; + // Profile along the B-spline's first direction when the record's u is the profile and the + // placement keeps orientation, or the angle is u and it mirrors; else the angle goes first. + let profile_first = forward == (det > 0.0); + if profile_first { + nurbs_face(a, &knots, &circle_knots, pts.len(), 9)?; + net_rows(a, net.iter().flatten().copied()); + a.r(flat::FACE_RANGE).extend([p0, 0.0, p1, t1]); + } else { + nurbs_face(a, &circle_knots, &knots, 9, pts.len())?; + net_rows(a, (0..9).flat_map(|k| net.iter().filter_map(move |row| row.get(k).copied()))); + a.r(flat::FACE_RANGE).extend([0.0, p0, t1, p1]); + } + Ok(()) +} + +fn net_rows(a: &mut Arrays, cps: impl Iterator) { + net(a, cps); +} + +/// A plane `origin + u·U + v·V` as SMLib's plane, whose (u, v) are distances along unit, +/// orthogonal axes: U's direction, and the one at a right angle to it in the plane, the normal +/// U × V as the record's. The range is the record's domain mapped onto those axes (its bounding +/// box: a face's range need not be tight, and SMLib rebuilds an analytic face's trims from its +/// edges). Truck's planes run through three points, their axes the face's own sides. +/// Off unit orthogonal axes and not `analytic`, it goes as the exact bilinear patch over the +/// domain instead. +fn plane(a: &mut Arrays, origin: [f64; 3], u: [f64; 3], v: [f64; 3], domain: [[f64; 2]; 2], analytic: bool) -> R<()> { + let [[u0, u1], [v0, v1]] = domain; + let unit = |x: [f64; 3]| (dot(x, x).sqrt() - 1.0).abs() <= 1e-12; + if !analytic && !(unit(u) && unit(v) && dot(u, v).abs() <= 1e-12) { + nurbs_face(a, &[u0, u0, u1, u1], &[v0, v0, v1, v1], 2, 2)?; + let at = |s: f64, t: f64| add(origin, add(scale(u, s), scale(v, t))); + net(a, [at(u0, v0), at(u0, v1), at(u1, v0), at(u1, v1)].into_iter().map(|p| (p, 1.0))); + a.r(flat::FACE_RANGE).extend([u0, v0, u1, v1]); + return Ok(()); + } + let n = cross(u, v); + let (lu, ln) = (dot(u, u).sqrt(), dot(n, n).sqrt()); + if !(lu > 0.0 && ln > 0.0 && lu.is_finite() && ln.is_finite()) { + return Err(Unsupported::Invalid("plane axes")); + } + let (x, z) = (scale(u, 1.0 / lu), scale(n, 1.0 / ln)); + let y = cross(z, x); + let corners = [[u0, v0], [u0, v1], [u1, v0], [u1, v1]].map(|[s, t]| { + let d = add(scale(u, s), scale(v, t)); + [dot(d, x), dot(d, y)] + }); + let lo = |k: usize| corners.iter().map(|c| c[k]).fold(f64::INFINITY, f64::min); + let hi = |k: usize| corners.iter().map(|c| c[k]).fold(f64::NEG_INFINITY, f64::max); + a.i(flat::FACE_SURFACE_TYPE).push(i64::from(flat::SURFACE_PLANE)); + a.r3(flat::FACE_PLANE_ORIGIN, origin); + a.r3(flat::FACE_PLANE_AXIS, z); + a.r3(flat::FACE_PLANE_REF_DIRECTION, x); + a.r(flat::FACE_RANGE).extend([lo(0), lo(1), hi(0), hi(1)]); + Ok(()) +} + +/// A circle's or ellipse's interval (radians) as SMLib takes it, within [-2π, 2π]: schema 4 +/// lets one run past a full turn (a quarter arc after the seam, [2π, 2.5π]), SMLib's circles +/// take angles up to one turn either way. The same arc a whole turn back, and that shift, by +/// which the edge's pcurves move too (their parameter is the edge's). +fn turned(c: &b::Curve, interval: [f64; 2]) -> ([f64; 2], f64) { + use std::f64::consts::TAU; + if !matches!(c, b::Curve::Circle { .. } | b::Curve::Ellipse { .. }) { + return (interval, 0.0); + } + let [lo, hi] = interval; + let shift = if hi > TAU { + -TAU * ((hi - TAU) / TAU).ceil() + } else if lo < -TAU { + TAU * ((-TAU - lo) / TAU).ceil() + } else { + 0.0 + }; + ([lo + shift, hi + shift], shift) +} + +/// A pcurve as the edgeuse's UV trim, its parameter moved by `shift` (the edge's, see +/// [`turned`]): reversed when the loop runs against the edge. +fn trim(a: &mut Arrays, c: &b::Curve2, forward: bool, shift: f64) -> R<()> { + let (knots, mut pts): (&[f64], Vec<([f64; 2], f64)>) = match c { + b::Curve2::Spline { knots, points } => (knots, points.iter().map(|p| (*p, 1.0)).collect()), + b::Curve2::RationalSpline { knots, homogeneous } => (knots, homogeneous.iter().map(|h| ([h[0] / h[2], h[1] / h[2]], h[2])).collect()), + }; + let order = knots.len().checked_sub(pts.len()).filter(|o| *o >= 2).ok_or(Unsupported::Invalid("pcurve order"))?; + let mut k: Vec = knots.iter().map(|t| t + shift).collect(); + if !forward { + pts.reverse(); + k = k.iter().rev().map(|t| -t).collect(); + } + a.i(flat::EDGEUSE_NURBS_VERTEX_COUNT).push(int(pts.len())?); + a.i(flat::EDGEUSE_NURBS_ORDER).push(int(order)?); + for (p, w) in pts { + a.r(flat::EDGEUSE_NURBS_CVS).extend(p); + a.r(flat::EDGEUSE_NURBS_WEIGHTS).push(w); + } + a.r(flat::EDGEUSE_NURBS_KNOTS).extend(k); + Ok(()) +} + +fn nurbs_curve(a: &mut Arrays, knots: &[f64], pts: impl ExactSizeIterator) -> R<()> { + a.i(flat::EDGE_CURVE_TYPE).push(i64::from(flat::CURVE_NURBS)); + nurbs_curve_block(a, knots, pts) +} + +/// An edge NURBS block (counts, points, weights, knots) with no curve kind of its own. +fn nurbs_curve_block(a: &mut Arrays, knots: &[f64], pts: impl ExactSizeIterator) -> R<()> { + let n = pts.len(); + let order = knots.len().checked_sub(n).filter(|o| *o >= 2).ok_or(Unsupported::Invalid("spline order"))?; + a.i(flat::EDGE_NURBS_VERTEX_COUNT).push(int(n)?); + a.i(flat::EDGE_NURBS_ORDER).push(int(order)?); + for (p, w) in pts { + a.r3(flat::EDGE_NURBS_CVS, p); + a.r(flat::EDGE_NURBS_WEIGHTS).push(w); + } + a.r(flat::EDGE_NURBS_KNOTS).extend_from_slice(knots); + Ok(()) +} + +/// The NURBS block of an edge's NURBS form. +fn edge_nurbs_block(a: &mut Arrays, c: &b::Curve) -> R<()> { + match c { + b::Curve::Spline { knots, points } => nurbs_curve_block(a, knots, points.iter().map(|p| (*p, 1.0))), + b::Curve::RationalSpline { knots, homogeneous } => { + nurbs_curve_block(a, knots, homogeneous.iter().map(|h| ([h[0] / h[3], h[1] / h[3], h[2] / h[3]], h[3]))) + } + _ => Err(Unsupported::Invalid("NURBS form is not a NURBS")), + } +} + +fn curve(a: &mut Arrays, c: &b::Curve) -> R<()> { + match c { + b::Curve::Line { start, end } => { + a.i(flat::EDGE_CURVE_TYPE).push(i64::from(flat::CURVE_LINE)); + a.r3(flat::EDGE_LINE_ORIGIN, *start); + a.r3(flat::EDGE_LINE_DIRECTION, sub(*end, *start)); + } + b::Curve::Circle { frame, radius } => { + a.i(flat::EDGE_CURVE_TYPE).push(i64::from(flat::CURVE_CIRCLE)); + a.r3(flat::EDGE_CIRCLE_CENTER, frame.origin); + a.r3(flat::EDGE_CIRCLE_AXIS, z_axis(frame)); + a.r3(flat::EDGE_CIRCLE_REF_DIRECTION, frame.x_axis); + a.r(flat::EDGE_CIRCLE_RADIUS).push(*radius); + } + b::Curve::Ellipse { frame, radii } => { + a.i(flat::EDGE_CURVE_TYPE).push(i64::from(flat::CURVE_ELLIPSE)); + a.r3(flat::EDGE_ELLIPSE_CENTER, frame.origin); + a.r3(flat::EDGE_ELLIPSE_AXIS, z_axis(frame)); + a.r3(flat::EDGE_ELLIPSE_REF_DIRECTION, frame.x_axis); + a.r(flat::EDGE_ELLIPSE_X_RADIUS).push(radii[0]); + a.r(flat::EDGE_ELLIPSE_Y_RADIUS).push(radii[1]); + } + b::Curve::Polyline { points } => { + // Segment i spans [i, i + 1]: a degree-1 B-spline with those knots. + let n = points.len(); + let mut k = vec![0.0]; + k.extend((0..n).map(|i| i as f64)); + k.push(n.saturating_sub(1) as f64); + nurbs_curve(a, &k, points.iter().map(|p| (*p, 1.0)))?; + } + b::Curve::Spline { knots, points } => nurbs_curve(a, knots, points.iter().map(|p| (*p, 1.0)))?, + b::Curve::RationalSpline { knots, homogeneous } => { + nurbs_curve(a, knots, homogeneous.iter().map(|h| ([h[0] / h[3], h[1] / h[3], h[2] / h[3]], h[3])))? + } + b::Curve::SurfaceIntersection { .. } => return Err(Unsupported::NotYet("traced intersection curves")), + } + Ok(()) +} + +mod analytic; + +#[cfg(test)] +mod tests; + +impl crate::Brep { + /// A body from flat arrays. + pub(crate) fn from_arrays(a: &Arrays) -> crate::Result { + crate::core::from_arrays(a).map(crate::Brep::made_core) + } + + /// The SMLib B-rep of a schema 4 record. `trusted` as in [`arrays`]. + pub fn from_record(brep: &b::Brep, trusted: bool) -> crate::Result { + let r = arrays(brep, trusted).map_err(crate::Error::Record).and_then(|a| crate::Brep::from_arrays(&a)); + crate::trace::imported(&r, brep, trusted, false); + r + } + + /// [`crate::Brep::from_record`] through [`arrays_keeping_splines`]. + pub fn from_record_keeping_splines(brep: &b::Brep, trusted: bool) -> crate::Result { + let r = arrays_keeping_splines(brep, trusted).map_err(crate::Error::Record).and_then(|a| crate::Brep::from_arrays(&a)); + crate::trace::imported(&r, brep, trusted, true); + r + } +} diff --git a/crates/smlib/src/import/analytic.rs b/crates/smlib/src/import/analytic.rs new file mode 100644 index 000000000..b996c0331 --- /dev/null +++ b/crates/smlib/src/import/analytic.rs @@ -0,0 +1,580 @@ +//! Revolutions and extruded circles as SMLib's analytic surfaces. +//! +//! A `placed_revolution` record holds a surface the way truck does (a profile turned about an +//! axis, then placed); SMLib has no such surface, but every one truck makes for a plane, cylinder, cone, +//! sphere or torus is one of those exactly: a line square to the axis, a line along it, a line in a plane through it, a +//! circle centred on it, a circle in a plane through it. A rational spline that is a circular arc +//! swept straight along its axis (truck's extruded circles) is a cylinder. Each such face becomes +//! that analytic surface with the face's range on it, checked point by point over the face's +//! domain; where the analytic surface's natural normal is the other way round, the face is turned +//! over (its loops reversed, its uses in the shells flipped), which leaves the solid as it was. +//! +//! A revolution of any other profile, or one placed by a matrix that is not a rigid motion, +//! stays a revolution, which the import sends as its exact rational B-spline; any other spline +//! stays a spline. + +use solidcraft_geom::prelude::*; +use std::borrow::Cow; +use std::f64::consts::{FRAC_PI_2, TAU}; + +use solidcore_record::Vec3; +use solidcore_record::brep as b; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; + +use super::{R, Unsupported}; + +/// Halvings one span's extent may take. +const MAX_EXTENT_PIECES: usize = 4096; + +const NOT_ANALYTIC: Unsupported = Unsupported::NotYet("revolved surfaces other than planes, cylinders, cones, spheres and tori"); + +/// `brep` with every revolution and extruded circle replaced by its analytic surface (borrowed +/// when it has none). +pub(super) fn analytic(brep: &b::Brep) -> R> { + let size = extent(brep); + let tol = brep.tolerance.max(1e-9 * size); + let mut out: Option = None; + let mut turned = Vec::new(); + for (i, f) in brep.faces.iter().enumerate() { + let found = match &f.surface { + // One that is none of the analytic kinds goes as its exact rational B-spline + // (`super::revolution`). + b::Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => { + match Revolution::new(profile, *origin, *axis, matrix, *forward).and_then(|r| r.analytic(f.domain)) { + Ok(found) => Some(found), + Err(Unsupported::NotYet(_)) => None, + Err(e) => return Err(e), + } + } + b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + let found = extruded_circle(u_knots, v_knots, homogeneous, trimmed(brep, f)?, 1e-9 * size.max(1.0)); + // A face's trims run at most one turn round a cylinder (SMLib refuses more). + if found.as_ref().is_some_and(|(_, range)| range[0][1] - range[0][0] > TAU * (1.0 + 1e-9)) { + return Err(Unsupported::Invalid("a cylinder's face whose trims run more than one turn round")); + } + found + } + _ => None, + }; + let Some((mut surface, mut range)) = found else { continue }; + // The angle about the axis starts at 0: the frame turns to the face's first angle (SMLib + // refuses an analytic range past 360°). A torus's tube angle can't turn so: it starts + // within the first turn, where SMLib's degree domains are at home. + if !matches!(surface, b::Surface::Plane { .. }) { + turn_frame(&mut surface, range[0][0]); + range[0] = [0.0, range[0][1] - range[0][0]]; + } + if matches!(surface, b::Surface::Torus { .. }) { + range[1] = first_turn(range[1]); + } + let flip = agree((&f.surface, f.domain), (&surface, range), tol)?; + let face = out.get_or_insert_with(|| brep.clone()).faces.get_mut(i).ok_or(Unsupported::Invalid("face"))?; + face.surface = surface; + face.domain = range; + if flip { + turned.push(i); + } + } + let Some(mut out) = out else { return Ok(Cow::Borrowed(brep)) }; + for i in turned { + turn_over(&mut out, i)?; + } + Ok(Cow::Owned(out)) +} + +/// A rational spline that is a circular arc swept straight along the arc's axis, as a cylinder +/// with the face's range on it: one direction linear (two rows of control points), the second +/// row the first moved by one vector at right angles to the circle the first row runs on, the +/// weights alike. `None` where it is not. The range is the face's own, its trims' box `trims` +/// ([`trimmed`]), not the spline's: SMLib's spline of a cylinder's wall may run on past the face, +/// more than a turn round (a blend's support surface extended past the face's ends). +fn extruded_circle(u_knots: &[f64], v_knots: &[f64], net: &[Vec<[f64; 4]>], trims: [[f64; 2]; 2], tol: f64) -> Option<(b::Surface, [[f64; 2]; 2])> { + let linear = |k: &[f64]| k.len() == 4 && k[0] == k[1] && k[2] == k[3] && k[1] < k[2]; + let (rows, arc_knots, arc_range, line_knots, line_range): ([Vec<[f64; 4]>; 2], &[f64], [f64; 2], &[f64], [f64; 2]) = + if net.iter().all(|r| r.len() == 2) && linear(v_knots) && !linear(u_knots) { + ([net.iter().map(|r| r[0]).collect(), net.iter().map(|r| r[1]).collect()], u_knots, trims[0], v_knots, trims[1]) + } else if net.len() == 2 && linear(u_knots) && !linear(v_knots) { + ([net.first()?.clone(), net.get(1)?.clone()], v_knots, trims[1], u_knots, trims[0]) + } else { + return None; + }; + let cart = |h: &[f64; 4]| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]); + let (first, second) = (&rows[0], &rows[1]); + let d = cart(second.first()?) - cart(first.first()?); + let alike = first.iter().zip(second).all(|(p, q)| (p[3] - q[3]).abs() <= 1e-12 * p[3].abs() && (cart(q) - cart(p) - d).len() <= tol); + if !alike || first.len() != second.len() || !(d.len() > tol) { + return None; + } + let arc = CurveEval::new(&b::Curve::RationalSpline { knots: arc_knots.to_vec(), homogeneous: first.clone() }).ok()?; + // The circle from the arc's widest span, not from the face's range: three points on a + // face a small part of a turn round (6 mm of a 3000 mm radius) put the centre off the + // circle's plane and the radius off by 1e-8 mm, which SMLib does not take back as a cylinder. + let (center, radius, normal) = circle(&arc, widest_span(arc_knots, first.len())?, arc_range)?; + let z = d.normalized()?; + if normal.cross(z).len() > 1e-9 { + return None; + } + let x = (arc.point(arc_range[0])? - center).normalized()?; + let y = z.cross(x); + // The arc's angles from x, unwrapped along its range. + let mut angle = 0.0; + let mut prev = 0.0; + for i in 1..=32 { + let q = arc.point(arc_range[0] + (arc_range[1] - arc_range[0]) * f64::from(i) / 32.0)? - center; + let mut a = q.dot(y).atan2(q.dot(x)); + while a - prev > std::f64::consts::PI { + a -= TAU; + } + while a - prev < -std::f64::consts::PI { + a += TAU; + } + prev = a; + angle = a; + } + let height = |s: f64| (s - line_knots[1]) / (line_knots[2] - line_knots[1]) * d.len(); + let sorted = |a: f64, b: f64| if a <= b { [a, b] } else { [b, a] }; + let frame = b::Frame { origin: arr(center), x_axis: arr(x), y_axis: arr(y) }; + Some((b::Surface::Cylinder { frame, radius }, [sorted(0.0, angle), sorted(height(line_range[0]), height(line_range[1]))])) +} + +/// The box in its surface's parameters round face `f`'s loops: each use's pcurve over its edge's +/// interval, its least and greatest u and v ([`pcurve_box`]). The range the face takes of its +/// surface, which may run on past it. +fn trimmed(brep: &b::Brep, f: &b::Face) -> R<[[f64; 2]; 2]> { + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for l in &f.loops { + let b::Loop::Edges { edges } = l else { return Err(Unsupported::Invalid("a vertex loop on a cylinder's face")) }; + for u in edges { + let interval = brep.edges.get(u.edge as usize).ok_or(Unsupported::Invalid("edge"))?.interval; + let [ru, rv] = pcurve_box(&u.pcurve, interval).ok_or(Unsupported::Invalid("a pcurve that does not evaluate"))?; + for (k, r) in [ru, rv].into_iter().enumerate() { + lo[k] = lo[k].min(r[0]); + hi[k] = hi[k].max(r[1]); + } + } + } + if !(lo.iter().chain(&hi).all(|x| x.is_finite()) && lo[0] <= hi[0] && lo[1] <= hi[1]) { + return Err(Unsupported::Invalid("a face without trims")); + } + Ok([[lo[0], hi[0]], [lo[1], hi[1]]]) +} + +/// A pcurve's least and greatest u and v over `interval`, to rounding: on each Bézier span, the +/// greatest value found at a span's points (its ends, then the ends of its halves) bounds the +/// greatest from below, and its control points' (weights positive) from above; halves whose +/// control points can't beat the best found are dropped, the others halved, until the two meet. +fn pcurve_box(c: &b::Curve2, interval: [f64; 2]) -> Option<[[f64; 2]; 2]> { + use solidcraft_geom::bspline::{HPoint, bezier_segment, segment}; + let (knots, ctrl): (&[f64], Vec) = match c { + b::Curve2::Spline { knots, points } => (knots, points.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: 1.0 }).collect()), + b::Curve2::RationalSpline { knots, homogeneous } => { + (knots, homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: 0.0, w: h[2] }).collect()) + } + }; + let p = knots.len().checked_sub(ctrl.len() + 1)?; + let [t0, t1] = interval; + let mut ends: Vec = vec![t0]; + ends.extend(knots.iter().copied().filter(|k| *k > t0 && *k < t1)); + ends.push(t1); + ends.dedup(); + let mut out = [[f64::INFINITY, f64::NEG_INFINITY]; 2]; + for w in ends.windows(2) { + let &[a, z] = w else { continue }; + let (_, span) = segment(p, knots, &ctrl, a, z).ok()?; + if span.len() != p + 1 { + return None; + } + for (k, r) in out.iter_mut().enumerate() { + let along = |h: &HPoint| if k == 0 { h.x / h.w } else { h.y / h.w }; + for sign in [1.0, -1.0] { + let value = |piece: &[HPoint]| -> Option<[f64; 2]> { + let (first, last) = (piece.first()?, piece.last()?); + let at = (sign * along(first)).max(sign * along(last)); + let hull = piece.iter().map(|h| sign * along(h)).fold(f64::NEG_INFINITY, f64::max); + Some([at, hull]) + }; + let [mut best, _] = value(&span)?; + let mut pieces = vec![span.clone()]; + let mut work = 0usize; + while let Some(piece) = pieces.pop() { + let [at, hull] = value(&piece)?; + best = best.max(at); + if hull <= best + 64.0 * f64::EPSILON * (1.0 + best.abs()) { + continue; + } + // Out of work (a pcurve running along its extreme to rounding), the piece's + // control points bound it: the box still holds the curve. + work += 1; + if work > MAX_EXTENT_PIECES { + best = hull; + continue; + } + pieces.push(bezier_segment(&piece, 0.0, 0.5).ok()?); + pieces.push(bezier_segment(&piece, 0.5, 1.0).ok()?); + } + if !best.is_finite() { + return None; + } + if sign > 0.0 { + r[1] = r[1].max(best); + } else { + r[0] = r[0].min(-best); + } + } + } + } + Some(out) +} + +/// An analytic surface's frame turned by `angle` about its axis: u then counts from there. +fn turn_frame(s: &mut b::Surface, angle: f64) { + if let b::Surface::Cylinder { frame, .. } | b::Surface::Cone { frame, .. } | b::Surface::Sphere { frame, .. } | b::Surface::Torus { frame, .. } = + s + { + let (x, y) = (v3(frame.x_axis), v3(frame.y_axis)); + let (sin, cos) = angle.sin_cos(); + frame.x_axis = arr(x * cos + y * sin); + frame.y_axis = arr(y * cos - x * sin); + } +} + +/// An angle range moved by whole turns to start in [0, 2π). +fn first_turn([a, z]: [f64; 2]) -> [f64; 2] { + let shift = (a / TAU).floor() * TAU; + [a - shift, z - shift] +} + +/// The body's size from its vertices (1 where it has none). +fn extent(brep: &b::Brep) -> f64 { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for v in &brep.vertices { + for k in 0..3 { + lo[k] = lo[k].min(v.point[k]); + hi[k] = hi[k].max(v.point[k]); + } + } + let d = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::().sqrt(); + if d.is_finite() && d > 0.0 { d } else { 1.0 } +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} +fn arr(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +/// A revolution in world space: its profile placed, its axis placed, the turning sense. +struct Revolution { + profile: CurveEval, + line: Option<[Vec3; 2]>, + /// A point on the axis and the axis, oriented so that the revolution's angle turns about it + /// by the right-hand rule. + o: Vec3, + z: Vec3, + /// The record's (u, v) is (profile, angle). + forward: bool, +} + +impl Revolution { + fn new(profile: &b::Curve, origin: [f64; 3], axis: [f64; 3], m: &[[f64; 4]; 4], forward: bool) -> R { + // Column-major: m[column][row]. A rigid motion only (a mirror reverses the turning). + let col = |c: usize| Vec3::new(m[c][0], m[c][1], m[c][2]); + let (c0, c1, c2, t) = (col(0), col(1), col(2), col(3)); + let unit = |v: Vec3| (v.len() - 1.0).abs() <= 1e-9; + if !(m[0][3] == 0.0 && m[1][3] == 0.0 && m[2][3] == 0.0 && m[3][3] == 1.0) + || !(unit(c0) && unit(c1) && unit(c2)) + || c0.dot(c1).abs() > 1e-9 + || c0.dot(c2).abs() > 1e-9 + || c1.dot(c2).abs() > 1e-9 + { + return Err(Unsupported::NotYet("revolved surfaces placed by a matrix that is no rigid motion")); + } + let det = c0.dot(c1.cross(c2)); + let place = |p: Vec3| c0 * p.x + c1 * p.y + c2 * p.z + t; + let turn = |d: Vec3| c0 * d.x + c1 * d.y + c2 * d.z; + let z = turn(v3(axis)).normalized().ok_or(Unsupported::Invalid("revolution axis"))? * det.signum(); + let placed_curve = |c: &b::Curve| -> R { + let p = |q: [f64; 3]| arr(place(v3(q))); + Ok(match c { + b::Curve::Line { start, end } => b::Curve::Line { start: p(*start), end: p(*end) }, + b::Curve::Circle { frame, radius } => b::Curve::Circle { + frame: b::Frame { origin: p(frame.origin), x_axis: arr(turn(v3(frame.x_axis))), y_axis: arr(turn(v3(frame.y_axis))) }, + radius: *radius, + }, + b::Curve::Spline { knots, points } => b::Curve::Spline { knots: knots.clone(), points: points.iter().map(|q| p(*q)).collect() }, + b::Curve::RationalSpline { knots, homogeneous } => b::Curve::RationalSpline { + knots: knots.clone(), + homogeneous: homogeneous + .iter() + .map(|h| { + let w = h[3]; + let q = place(Vec3::new(h[0], h[1], h[2]) * (1.0 / w)); + [q.x * w, q.y * w, q.z * w, w] + }) + .collect(), + }, + _ => return Err(NOT_ANALYTIC), + }) + }; + let world = placed_curve(profile)?; + let line = match &world { + b::Curve::Line { start, end } => Some([v3(*start), v3(*end)]), + _ => None, + }; + let profile = CurveEval::new(&world).map_err(|_| Unsupported::Invalid("revolution profile"))?; + Ok(Revolution { profile, line, o: place(v3(origin)), z, forward }) + } + + /// The profile's parameter range and the angle range of a face's domain. + fn ranges(&self, domain: [[f64; 2]; 2]) -> ([f64; 2], [f64; 2]) { + if self.forward { (domain[0], domain[1]) } else { (domain[1], domain[0]) } + } + + /// `p` relative to the axis: its foot on the axis, its height along z and its radial part. + fn split(&self, p: Vec3) -> (Vec3, f64, Vec3) { + let h = (p - self.o).dot(self.z); + let foot = self.o + self.z * h; + (foot, h, p - foot) + } + + /// The analytic surface and the face's range on it: u the angle about z from the profile's + /// half-plane, v as the surface's kind has it. + fn analytic(&self, domain: [[f64; 2]; 2]) -> R<(b::Surface, [[f64; 2]; 2])> { + let (t, angle) = self.ranges(domain); + let at = |s: f64| self.profile.point(s).ok_or(Unsupported::Invalid("revolution profile")); + let samples: Vec = (0..=16).map(|i| at(t[0] + (t[1] - t[0]) * f64::from(i) / 16.0)).collect::>()?; + // The profile's half-plane: the radial direction of its point farthest from the axis. + let far = samples.iter().map(|p| self.split(*p).2).fold(Vec3::ZERO, |best, r| if r.len() > best.len() { r } else { best }); + let x = far.normalized().ok_or(NOT_ANALYTIC)?; + let y = self.z.cross(x); + let frame = |o: Vec3| b::Frame { origin: arr(o), x_axis: arr(x), y_axis: arr(y) }; + let sorted = |a: f64, b: f64| if a <= b { [a, b] } else { [b, a] }; + if let Some([s, e]) = self.line { + let d = e - s; + let len = d.len(); + if !(len > 0.0) { + return Err(NOT_ANALYTIC); + } + // In a plane through the axis: no component out of the (z, x) plane. + if (s - self.o).dot(y).abs() > 1e-9 * len.max(1.0) || d.dot(y).abs() > 1e-9 * len { + return Err(NOT_ANALYTIC); + } + let (foot, _, _) = self.split(s); + let height = |p: Vec3| (p - foot).dot(self.z); + let radial = |p: Vec3| (p - foot).dot(x); + let (h0, h1) = (height(at(t[0])?), height(at(t[1])?)); + let (dh, dr) = (d.dot(self.z), d.dot(x)); + if dh.abs() <= 1e-12 * len { + // A disc or an annulus: the plane square to the axis, its range the box round the + // sector the line sweeps (each end's radius at both end angles and every quarter + // turn between: in the plane a point is linear in the radius). + let (ra, rb) = (radial(at(t[0])?), radial(at(t[1])?)); + let mut angles = vec![angle[0], angle[1]]; + let mut q = (angle[0] / FRAC_PI_2).ceil() * FRAC_PI_2; + while q < angle[1] && angles.len() < 16 { + angles.push(q); + q += FRAC_PI_2; + } + let corners: Vec<[f64; 2]> = angles.iter().flat_map(|a| [ra, rb].map(|r| [r * a.cos(), r * a.sin()])).collect(); + let lo = |k: usize| corners.iter().map(|c| c[k]).fold(f64::INFINITY, f64::min); + let hi = |k: usize| corners.iter().map(|c| c[k]).fold(f64::NEG_INFINITY, f64::max); + let plane = b::Surface::Plane { origin: arr(foot), u_axis: arr(x), v_axis: arr(y) }; + return Ok((plane, [[lo(0), hi(0)], [lo(1), hi(1)]])); + } + let r0 = radial(s) - dr / dh * height(s); + let v = sorted(h0, h1); + if dr.abs() <= 1e-12 * len { + if !(r0 > 0.0) { + return Err(NOT_ANALYTIC); + } + return Ok((b::Surface::Cylinder { frame: frame(foot), radius: r0 }, [angle, v])); + } + // A cone on one side of its apex only. + let r = |h: f64| r0 + h * dr / dh; + if r(v[0]) < 0.0 || r(v[1]) < 0.0 { + return Err(NOT_ANALYTIC); + } + let cone = b::Surface::Cone { frame: frame(foot), radius_at_origin: r0, half_angle: (dr / dh).atan() }; + return Ok((cone, [angle, v])); + } + // A circular profile. + let (center, radius, normal) = circle(&self.profile, t, t).ok_or(NOT_ANALYTIC)?; + let slack = 1e-9 * radius.max(1.0); + if normal.dot(self.z).abs() > 1e-9 || normal.dot(x).abs() > 1e-9 || (center - self.o).dot(y).abs() > slack { + return Err(NOT_ANALYTIC); + } + let (foot, _, off) = self.split(center); + // The meridian angle of each sample about the circle's centre in the (x, z) plane, unwrapped. + let meridian = |p: Vec3| { + let q = p - center; + q.dot(self.z).atan2(q.dot(x)) + }; + let mut angles = Vec::with_capacity(samples.len()); + for p in &samples { + let mut a = meridian(*p); + if let Some(prev) = angles.last().copied() { + while a - prev > std::f64::consts::PI { + a -= TAU; + } + while a - prev < -std::f64::consts::PI { + a += TAU; + } + } + angles.push(a); + } + let (first, last) = (angles.first().copied().ok_or(NOT_ANALYTIC)?, angles.last().copied().ok_or(NOT_ANALYTIC)?); + if off.len() <= slack { + // A sphere: the latitude is the meridian angle, within the half-plane's [-π/2, π/2]. + let v = sorted(first, last); + if v[0] < -FRAC_PI_2 - 1e-9 || v[1] > FRAC_PI_2 + 1e-9 { + return Err(NOT_ANALYTIC); + } + let v = [v[0].max(-FRAC_PI_2), v[1].min(FRAC_PI_2)]; + return Ok((b::Surface::Sphere { frame: frame(foot), radius }, [angle, v])); + } + // A ring torus only (SMLib has no other): a tube that reaches the axis to rounding (a + // horn torus, major = minor) is none. + let major = off.dot(x); + if !(major > radius + slack) { + return Err(NOT_ANALYTIC); + } + let torus = b::Surface::Torus { frame: frame(foot), major_radius: major, minor_radius: radius, tube_start: 0.0 }; + Ok((torus, [angle, sorted(first, last)])) + } +} + +/// The (u, v) of point `p` on an analytic surface, angles unwrapped to within half a turn of +/// `near`. +fn analytic_uv(s: &b::Surface, p: Vec3, near: [f64; 2]) -> Option<[f64; 2]> { + let unwrap = |mut a: f64, n: f64| { + while a - n > std::f64::consts::PI { + a -= TAU; + } + while a - n < -std::f64::consts::PI { + a += TAU; + } + a + }; + if let b::Surface::Plane { origin, u_axis, v_axis } = s { + let q = p - v3(*origin); + return Some([q.dot(v3(*u_axis)), q.dot(v3(*v_axis))]); + } + let (frame, round, tube) = match s { + b::Surface::Cylinder { frame, .. } | b::Surface::Cone { frame, .. } | b::Surface::Sphere { frame, .. } => (frame, 0.0, 0.0), + b::Surface::Torus { frame, major_radius, tube_start, .. } => (frame, *major_radius, *tube_start), + _ => return None, + }; + let (x, y) = (v3(frame.x_axis), v3(frame.y_axis)); + let z = x.cross(y); + let q = p - v3(frame.origin); + let (qx, qy, qz) = (q.dot(x), q.dot(y), q.dot(z)); + let u = unwrap(qy.atan2(qx), near[0]); + let r = qx.hypot(qy); + Some(match s { + b::Surface::Sphere { .. } => [u, qz.atan2(r)], + b::Surface::Torus { .. } => [u, unwrap(qz.atan2(r - round) - tube, near[1])], + _ => [u, qz], + }) +} + +/// Checks the analytic surface against the record's over the face's domain, 5 × 5 points within +/// `tol`, and says whether their natural normals are opposite (the face must be turned over), +/// read at the domain's middle. +fn agree((record, domain): (&b::Surface, [[f64; 2]; 2]), (analytic, range): (&b::Surface, [[f64; 2]; 2]), tol: f64) -> R { + let bad = Unsupported::Invalid("a surface its analytic form does not match"); + let s = SurfaceEval::new(record).map_err(|_| bad.clone())?; + let a = SurfaceEval::new(analytic).map_err(|_| bad.clone())?; + let [[u0, u1], [v0, v1]] = domain; + let near = [0.5 * (range[0][0] + range[0][1]), 0.5 * (range[1][0] + range[1][1])]; + let normals = |u: f64, w: f64| -> R { + let (p, du, dv) = s.derivs(u, w).ok_or(bad.clone())?; + let uv = analytic_uv(analytic, p, near).ok_or(bad.clone())?; + let (q, au, av) = a.derivs(uv[0], uv[1]).ok_or(bad.clone())?; + if !((p - q).len() <= tol) { + return Err(bad.clone()); + } + Ok(du.cross(dv).dot(au.cross(av))) + }; + for i in 0..=4 { + for j in 0..=4 { + normals(u0 + (u1 - u0) * f64::from(i) / 4.0, v0 + (v1 - v0) * f64::from(j) / 4.0)?; + } + } + let d = normals(0.5 * (u0 + u1), 0.5 * (v0 + v1))?; + if !(d.abs() > 0.0) { + return Err(bad); + } + Ok(d < 0.0) +} + +/// The widest knot span of a B-spline with `points` control points on `knots`. +fn widest_span(knots: &[f64], points: usize) -> Option<[f64; 2]> { + let degree = knots.len().checked_sub(points + 1)?; + knots.get(degree..=points)?.windows(2).map(|w| [w[0], w[1]]).max_by(|a, b| (a[1] - a[0]).total_cmp(&(b[1] - b[0]))) +} + +/// The circle a curve runs along over `t`, through its points at `fit` (a range of it on that +/// circle a good part of a turn round, where three points fix the circle to rounding): centre, +/// radius and unit normal (its turning sense over `fit`), checked at 65 points over `t` within +/// 10⁻⁹ of the radius (at least 1 mm). +fn circle(c: &CurveEval, fit: [f64; 2], t: [f64; 2]) -> Option<(Vec3, f64, Vec3)> { + let on = |s: f64| c.point(fit[0] + (fit[1] - fit[0]) * s); + let at = |s: f64| c.point(t[0] + (t[1] - t[0]) * s); + let (p, q, r) = (on(0.0)?, on(1.0 / 3.0)?, on(2.0 / 3.0)?); + let (u, w) = (q - p, r - p); + let normal = u.cross(w); + let nn = normal.dot(normal); + if !(nn > 0.0) { + return None; + } + let center = p + (normal.cross(u) * w.dot(w) + w.cross(normal) * u.dot(u)) * (0.5 / nn); + let radius = (p - center).len(); + let k = normal.normalized()?; + let slack = 1e-9 * radius.max(1.0); + for i in 0..=64 { + let s = at(f64::from(i) / 64.0)?; + if ((s - center).len() - radius).abs() > slack || (s - center).dot(k).abs() > slack { + return None; + } + } + Some((center, radius, k)) +} + +/// Face `face` turned over: its loops run the other way, each use of it in a shell flips, and +/// each of its edges' uses names its new place. The solid is unchanged. +fn turn_over(brep: &mut b::Brep, face: usize) -> R<()> { + use std::collections::HashMap; + let index = |x: usize| u32::try_from(x).map_err(|_| Unsupported::Invalid("index")); + let fi = index(face)?; + let f = brep.faces.get_mut(face).ok_or(Unsupported::Invalid("face"))?; + // (loop, old position) -> (new position, the use's new direction). + let mut moved: HashMap<(u32, u32), (u32, bool)> = HashMap::new(); + for (li, l) in f.loops.iter_mut().enumerate() { + if let b::Loop::Edges { edges } = l { + let n = edges.len(); + edges.reverse(); + for (p, e) in edges.iter_mut().enumerate() { + e.forward = !e.forward; + moved.insert((index(li)?, index(n - 1 - p)?), (index(p)?, e.forward)); + } + } + } + for e in &mut brep.edges { + for u in e.uses.iter_mut().filter(|u| u.face == fi) { + let &(position, forward) = moved.get(&(u.r#loop, u.position)).ok_or(Unsupported::Invalid("edge use"))?; + u.position = position; + u.upper = !forward; + } + } + for s in &mut brep.shells { + if let b::Shell::Faces { faces, .. } = s { + for o in faces.iter_mut().filter(|o| o.face == fi) { + o.forward = !o.forward; + } + } + } + Ok(()) +} diff --git a/crates/smlib/src/import/tests.rs b/crates/smlib/src/import/tests.rs new file mode 100644 index 000000000..29092c5a1 --- /dev/null +++ b/crates/smlib/src/import/tests.rs @@ -0,0 +1,319 @@ +use super::*; +use solidcore_record::brep::{ + Brep as Record, Curve, Curve2, Edge, EdgeUseRef, Face, Loop, OrientedEdge, OrientedFace, Region, Shell, Surface, Vertex, +}; +use solidcraft_geom::prelude::*; + +/// A closed polyhedron record from its corner points and its faces, each a cycle of corner +/// indices counter-clockwise seen from outside: planar faces, straight edges, canonical order. +fn polyhedron(corners: &[[f64; 3]], cycles: &[&[usize]]) -> Record { + let unit = |a: [f64; 3]| { + let n = dot(a, a).sqrt(); + scale(a, 1.0 / n) + }; + let mut edge_of: HashMap<(usize, usize), u32> = HashMap::new(); + let mut ends: Vec<(usize, usize)> = Vec::new(); + let mut uses: Vec> = Vec::new(); + let mut faces = Vec::new(); + for (fi, cycle) in cycles.iter().enumerate() { + let o = corners[cycle[0]]; + let x = unit(sub(corners[cycle[1]], o)); + let z = unit(cross(x, sub(corners[cycle[cycle.len() - 1]], o))); + let y = cross(z, x); + let uv = |p: [f64; 3]| [dot(sub(p, o), x), dot(sub(p, o), y)]; + let mut edges = Vec::new(); + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for k in 0..cycle.len() { + let (a, b) = (cycle[k], cycle[(k + 1) % cycle.len()]); + let (e, forward) = match edge_of.get(&(b, a)) { + Some(&e) => (e, false), + None => { + let e = ends.len() as u32; + edge_of.insert((a, b), e); + ends.push((a, b)); + uses.push(Vec::new()); + (e, true) + } + }; + uses[e as usize].push(EdgeUseRef { face: fi as u32, r#loop: 0, position: k as u32, upper: !forward }); + let (s, t) = ends[e as usize]; + for p in [uv(corners[s]), uv(corners[t])] { + for i in 0..2 { + lo[i] = lo[i].min(p[i]); + hi[i] = hi[i].max(p[i]); + } + } + edges.push(OrientedEdge { + edge: e, + forward, + pcurve: Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![uv(corners[s]), uv(corners[t])] }, + }); + } + faces.push(Face { + nurbs: None, + surface: Surface::Plane { origin: o, u_axis: x, v_axis: y }, + domain: [[lo[0], hi[0]], [lo[1], hi[1]]], + loops: vec![Loop::Edges { edges }], + }); + } + // Vertices in first appearance along the edges. + let mut vertex_of: HashMap = HashMap::new(); + let mut vertices = Vec::new(); + let mut number = |c: usize, vertices: &mut Vec| { + *vertex_of.entry(c).or_insert_with(|| { + vertices.push(Vertex { point: corners[c], tolerance: 1e-6 }); + vertices.len() as u32 - 1 + }) + }; + let edges = ends + .iter() + .zip(uses) + .map(|(&(s, t), uses)| { + let vs = [number(s, &mut vertices), number(t, &mut vertices)]; + Edge { nurbs: None, curve: Curve::Line { start: corners[s], end: corners[t] }, interval: [0.0, 1.0], vertices: vs, tolerance: 1e-6, uses } + }) + .collect(); + Record { + version: solidcore_record::brep::VERSION, + tolerance: 1e-6, + regions: vec![Region { shells: vec![0], void: false }, Region { shells: vec![0], void: false }], + shells: vec![Shell::Faces { faces: (0..cycles.len() as u32).map(|face| OrientedFace { face, forward: true }).collect(), wires: vec![] }], + faces, + edges, + vertices, + } +} + +fn cube(s: f64) -> Record { + let c = [[0., 0., 0.], [s, 0., 0.], [s, s, 0.], [0., s, 0.], [0., 0., s], [s, 0., s], [s, s, s], [0., s, s]]; + polyhedron(&c, &[&[0, 3, 2, 1], &[4, 5, 6, 7], &[0, 1, 5, 4], &[1, 2, 6, 5], &[2, 3, 7, 6], &[3, 0, 4, 7]]) +} + +#[test] +fn a_cube_record_is_valid_and_maps_to_two_shells() { + let r = cube(10.0); + solidcraft_geom::brep::check::validate(&r).unwrap(); + let a = arrays(&r, true).unwrap(); + // The infinite region (a void in SMLib) and the solid, one shell each, every face once per side. + assert_eq!(a.ints[&flat::REGION_SHELL_COUNT], vec![1, 1]); + assert_eq!(a.ints[&flat::REGION_TYPE], vec![1, 0]); + assert_eq!(a.ints[&flat::SHELL_FACEUSE_COUNT], vec![6, 6]); + assert_eq!(a.ints[&flat::FACEUSE_ORIENTATION], [vec![1; 6], vec![0; 6]].concat()); + assert_eq!(a.ints[&flat::EDGE_CURVE_TYPE], vec![i64::from(flat::CURVE_LINE); 12]); + assert_eq!(a.ints[&flat::FACE_SURFACE_TYPE], vec![i64::from(flat::SURFACE_PLANE); 6]); + // Each edge's two uses cycle into each other; no trims on analytic faces. + let next = &a.ints[&flat::EDGEUSE_NEXT_RADIAL]; + assert_eq!(next.len(), 24); + assert!(next.iter().enumerate().all(|(i, &n)| n != i as i64 && next[n as usize] == i as i64)); + assert!(!a.ints.contains_key(&flat::EDGEUSE_NURBS_VERTEX_COUNT)); +} + +#[test] +fn records_smlib_cannot_take_are_errors() { + let mut r = cube(1.0); + r.version = 3; + assert!(matches!(arrays(&r, true), Err(Unsupported::Invalid(_)))); + let mut r = cube(1.0); + r.shells = vec![Shell::Vertex { vertex: 0 }]; + assert!(arrays(&r, true).is_err()); +} + +#[test] +fn a_cube_record_imports_into_smlib() { + let b = crate::Brep::from_record(&cube(10.0), true).unwrap(); + assert!((b.volume(1e-7).unwrap() - 1000.0).abs() < 1e-6); + assert_eq!(b.counts().unwrap(), [6, 12, 8]); + assert!(b.is_manifold_solid().unwrap()); +} + +#[test] +fn a_plane_on_other_axes_goes_as_smlibs_plane() { + // A tetrahedron: its faces' natural frames are unit and orthogonal, so make one plane's axes + // non-unit and check it still goes as SMLib's plane, the volume unchanged. + let c = [[0., 0., 0.], [6., 0., 0.], [0., 6., 0.], [0., 0., 6.]]; + let mut r = polyhedron(&c, &[&[0, 2, 1], &[0, 1, 3], &[1, 2, 3], &[2, 0, 3]]); + if let Some(Face { nurbs: None, surface: Surface::Plane { u_axis, v_axis, .. }, domain, loops }) = r.faces.get_mut(0) { + *u_axis = scale(*u_axis, 2.0); + *v_axis = scale(*v_axis, 2.0); + *domain = domain.map(|d| d.map(|x| x / 2.0)); + if let Some(Loop::Edges { edges }) = loops.get_mut(0) { + for e in edges { + if let Curve2::Spline { points, .. } = &mut e.pcurve { + points.iter_mut().for_each(|p| *p = p.map(|x| x / 2.0)); + } + } + } + } + solidcraft_geom::brep::check::validate(&r).unwrap(); + let a = arrays(&r, true).unwrap(); + assert_eq!(a.ints[&flat::FACE_SURFACE_TYPE][0], i64::from(flat::SURFACE_PLANE)); + let b = crate::Brep::from_record(&r, true).unwrap(); + assert!((b.volume(1e-7).unwrap() - 36.0).abs() < 1e-6, "{:?}", b.volume(1e-7)); +} + +/// The surface `arrays` wrote for the first face, back as a schema 4 rational spline, with its range. +fn first_nurbs(a: &Arrays) -> (Surface, [f64; 4]) { + let (nu, nv) = (a.ints[&flat::FACE_NURBS_U_VERTEX_COUNT][0] as usize, a.ints[&flat::FACE_NURBS_V_VERTEX_COUNT][0] as usize); + let cvs = &a.reals[&flat::FACE_NURBS_CVS]; + let w = &a.reals[&flat::FACE_NURBS_WEIGHTS]; + let homogeneous = (0..nu) + .map(|i| { + (0..nv) + .map(|j| { + let k = i * nv + j; + [cvs[3 * k] * w[k], cvs[3 * k + 1] * w[k], cvs[3 * k + 2] * w[k], w[k]] + }) + .collect() + }) + .collect(); + let r = &a.reals[&flat::FACE_RANGE]; + ( + Surface::RationalSpline { + u_knots: a.reals[&flat::FACE_NURBS_U_KNOTS].clone(), + v_knots: a.reals[&flat::FACE_NURBS_V_KNOTS].clone(), + homogeneous, + }, + [r[0], r[1], r[2], r[3]], + ) +} + +#[test] +fn revolutions_become_the_same_surface_as_a_rational_spline() { + use solidcraft_geom::brep::eval::SurfaceEval; + // A quarter-circle profile (rational) away from the axis, so the surface is a torus piece. + let s = std::f64::consts::FRAC_1_SQRT_2; + let profile = Curve::RationalSpline { + knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], + homogeneous: vec![[3.0, 0.0, 0.0, 1.0], [3.0 * s, 0.0, 1.0 * s, s], [2.0, 0.0, 1.0, 1.0]], + }; + let identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let mirror = [[0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 2.0, 0.0], [1.0, -2.0, 3.0, 1.0]]; + for matrix in [identity, mirror] { + for forward in [true, false] { + let rev = + Surface::PlacedRevolution { profile: Box::new(profile.clone()), origin: [0.0, 0.0, 0.0], axis: [0.0, 0.0, 1.0], matrix, forward }; + let (angles, prof) = ([0.4, 0.4 + 1.9 * std::f64::consts::PI], [0.0, 1.0]); + let domain = if forward { [prof, angles] } else { [angles, prof] }; + let mut a = Arrays::default(); + surface(&mut a, &rev, domain, true).unwrap(); + let (nurbs, range) = first_nurbs(&a); + let (re, ne) = (SurfaceEval::new(&rev).unwrap(), SurfaceEval::new(&nurbs).unwrap()); + let det = { + let col = |c: usize| [matrix[c][0], matrix[c][1], matrix[c][2]]; + dot(cross(col(0), col(1)), col(2)) + }; + for i in 0..=6 { + for j in 0..=6 { + let (sp, ang) = (i as f64 / 6.0, angles[0] + (angles[1] - angles[0]) * j as f64 / 6.0); + let uv = if forward { [sp, ang] } else { [ang, sp] }; + let (p, du, dv) = re.derivs(uv[0], uv[1]).unwrap(); + let n = du.cross(dv) * det.signum(); + let t = circle_param(ang - angles[0]); + let profile_first = forward == (det > 0.0); + let q = if profile_first { [sp, t] } else { [t, sp] }; + assert!(q[0] >= range[0] - 1e-12 && q[0] <= range[2] + 1e-12 && q[1] >= range[1] - 1e-12 && q[1] <= range[3] + 1e-12); + let (pn, nu_, nv_) = ne.derivs(q[0], q[1]).unwrap(); + assert!((pn - p).len() < 1e-12, "forward {forward} det {det}: {p:?} vs {pn:?}"); + assert!(nu_.cross(nv_).dot(n) > 0.0, "normal flipped: forward {forward} det {det}"); + } + } + } + } +} + +/// A circle or ellipse edge past a full turn (schema 4 allows up to one turn past the seam) +/// goes to SMLib a whole turn back, within [-2π, 2π]; other curves keep their interval. +#[test] +fn arcs_past_a_turn_come_a_turn_back() { + use std::f64::consts::{FRAC_PI_2, TAU}; + let frame = solidcore_record::brep::Frame { origin: [0.0; 3], x_axis: [1.0, 0.0, 0.0], y_axis: [0.0, 1.0, 0.0] }; + let circle = Curve::Circle { frame, radius: 2.0 }; + assert_eq!(turned(&circle, [TAU, TAU + FRAC_PI_2]), ([0.0, FRAC_PI_2], -TAU)); + assert_eq!(turned(&circle, [-TAU - FRAC_PI_2, -TAU]), ([-FRAC_PI_2, 0.0], TAU)); + let (i, s) = turned(&circle, [5.0, 5.0 + TAU]); + assert!(s == -TAU && i[0] >= -TAU && i[1] <= TAU, "{i:?}"); + assert_eq!(turned(&circle, [0.5, 2.0]), ([0.5, 2.0], 0.0)); + let line = Curve::Line { start: [0.0; 3], end: [1.0, 0.0, 0.0] }; + assert_eq!(turned(&line, [7.0, 9.0]), ([7.0, 9.0], 0.0)); +} + +/// A revolved circle is SMLib's ring torus only where its tube stays off the axis: a tube that +/// reaches it to rounding (a horn torus, its centre as far from the axis as its radius, give or +/// take an ulp) and one across it (a spindle) go as their rational B-splines. +#[test] +fn only_a_tube_clear_of_its_axis_is_a_ring_torus() { + let ring = |major: f64| { + let frame = solidcore_record::brep::Frame { origin: [major, 0.0, 0.0], x_axis: [1.0, 0.0, 0.0], y_axis: [0.0, 0.0, 1.0] }; + let (profile, _) = solidcraft_geom::brep::form::curve(&Curve::Circle { frame, radius: 1.0 }, [-1.0, 1.0]).unwrap(); + let identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let surface = + Surface::PlacedRevolution { profile: Box::new(profile), origin: [0.0; 3], axis: [0.0, 0.0, 1.0], matrix: identity, forward: false }; + let face = Face { surface, nurbs: None, domain: [[0.0, 1.0], [-0.5, 0.5]], loops: Vec::new() }; + let record = Record { + version: b::VERSION, + tolerance: 1e-6, + regions: Vec::new(), + shells: Vec::new(), + faces: vec![face], + edges: Vec::new(), + vertices: Vec::new(), + }; + let made = analytic::analytic(&record).unwrap(); + made.faces[0].surface.clone() + }; + assert!(matches!(ring(1.5), Surface::Torus { .. })); + for major in [1.0, 1.0 + 4.0 * f64::EPSILON, 0.5] { + assert!(matches!(ring(major), Surface::PlacedRevolution { .. }), "major {major}"); + } +} + +/// A 6 mm wide patch of an extruded circle of radius 3000 whose trims straddle the knot where +/// the profile's seam lies (u = 4 of a half circle in two quarter spans): the cylinder takes the +/// patch's own range, 0.002 rad round and 7 high, on the circle exactly. Fitted on the patch's +/// range (three points 2 mm apart) the centre came off the circle's plane by 2.5e-10 mm and the +/// radius off by 8e-9 mm, a cylinder SMLib did not take back from its own NURBS of it. +#[test] +fn a_patch_across_an_extruded_circles_seam_is_its_exact_cylinder() { + let (r, h, half) = (3000.0, 7.0, 0.001); + let c = [10.0 - r, 0.0, 0.0]; + let w = std::f64::consts::FRAC_1_SQRT_2; + let profile = [([c[0], -r], 1.0), ([c[0] + r, -r], w), ([c[0] + r, 0.0], 1.0), ([c[0] + r, r], w), ([c[0], r], 1.0)]; + let homogeneous = profile.iter().map(|&([x, y], wt)| vec![[x * wt, y * wt, 0.0, wt], [x * wt, y * wt, h * wt, wt]]).collect(); + let surface = Surface::RationalSpline { u_knots: vec![3.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0, 5.0], v_knots: vec![0.0, 0.0, h, h], homogeneous }; + // The quarter span after the seam reaches `half` at quarter_param(half); the one before it + // ends there, so the trims run symmetrically round the knot. + let (u0, u1) = (4.0 - quarter_param(half), 4.0 + quarter_param(half)); + let corners = [[u0, 0.0], [u1, 0.0], [u1, h], [u0, h]]; + let edges: Vec = (0..4) + .map(|k| OrientedEdge { + edge: k as u32, + forward: true, + pcurve: Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![corners[k], corners[(k + 1) % 4]] }, + }) + .collect(); + let line = Curve::Line { start: [0.0; 3], end: [1.0, 0.0, 0.0] }; + let record = Record { + version: b::VERSION, + tolerance: 1e-6, + regions: Vec::new(), + shells: Vec::new(), + faces: vec![Face { surface, nurbs: None, domain: [[3.0, 5.0], [0.0, h]], loops: vec![Loop::Edges { edges }] }], + edges: (0..4) + .map(|_| Edge { nurbs: None, curve: line.clone(), interval: [0.0, 1.0], vertices: [0, 0], tolerance: 1e-6, uses: Vec::new() }) + .collect(), + vertices: Vec::new(), + }; + let made = analytic::analytic(&record).unwrap(); + let f = &made.faces[0]; + let Surface::Cylinder { frame, radius } = &f.surface else { panic!("{:?}", f.surface) }; + assert!((radius - r).abs() <= 1e-10, "radius {radius}"); + let z = cross(frame.x_axis, frame.y_axis); + assert!(z[0].abs() <= 1e-15 && z[1].abs() <= 1e-15 && frame.x_axis[2].abs() <= 1e-15, "axis {z:?}, x {:?}", frame.x_axis); + assert!(frame.origin[2].abs() <= 1e-12 && (frame.origin[0] - c[0]).abs() <= 1e-9 && frame.origin[1].abs() <= 1e-9, "centre {:?}", frame.origin); + // u from the patch's first edge, 2 * half round; v its height. + let [[a0, a1], [v0, v1]] = f.domain; + assert!(a0 == 0.0 && (a1 - 2.0 * half).abs() <= 1e-12, "{:?}", f.domain); + assert!(v0.abs() <= 1e-12 && (v1 - h).abs() <= 1e-12, "{:?}", f.domain); + let start = (-half).sin_cos(); + assert!((frame.x_axis[0] - start.1).abs() <= 1e-12 && (frame.x_axis[1] - start.0).abs() <= 1e-12, "x {:?}", frame.x_axis); +} diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs new file mode 100644 index 000000000..3a29a19a7 --- /dev/null +++ b/crates/smlib/src/lib.rs @@ -0,0 +1,333 @@ +//! The B-rep kernel, solidcore (tangency-labs/solidcore, the Rust port of NVIDIA's SMLib, +//! Apache-2.0), behind a safe wrapper. Only `crates/kernel` uses this crate (ADR 0002). +//! +//! Every call runs in a solidcore kernel of its own, never changes its inputs, turns solidcore's +//! errors into [`Error`] and catches its panics ([`Error::Internal`]). +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::path::Path; + +mod check; +mod core; +pub mod export; +pub mod flat; +pub mod history; +pub mod import; +mod measure; +mod ops; +pub mod pcurves; +mod sheets; +mod split; +pub mod ssi; +pub mod sweeps; +pub mod trace; +pub mod trim; + +pub use check::{CheckLevel, CheckReport}; +pub use measure::{MEASURE_ACCURACY, MassProperties, PointClass}; +pub use ops::{Blend, BooleanOp, ChamferSecond, Hole, HoleEdge, MAX_POINTS, MAX_UNION_BREPS, Turn}; + +/// Why an SMLib call failed. +#[derive(Clone, Debug, PartialEq)] +pub enum Error { + /// SMLib's own status (1001 `SM_ERR`, 1007 `SM_ERR_INVALID_INPUT`, …). + Status(i32), + /// An argument the C API rejected before SMLib saw it. + Argument, + /// SMLib reported success but returned no body (for a boolean: the result is empty). + Empty, + /// SMLib reported success, but a solid input gave a result that is not a closed solid. + NotSolid, + /// Selection point `point` is farther than the tolerance from every edge (face). + NoMatch { point: usize }, + /// Selection point `point` is equally near to two edges (faces). + Ambiguous { point: usize }, + /// No room for the operation: an inward offset (a shell's wall, faces moved in) leaves none + /// inside the body, or a blend is larger than the faces it rolls on allow. + NoRoom, + /// An offset whose walls would meet (a shell's): the offsets of two faces touch without + /// crossing, a hole's wall offset just reaching a side's, so the result would pinch to + /// nothing along a line. A thinner or a thicker wall builds. + WallsTouch, + /// A blend larger than its faces allow, refused with the largest size that builds it + /// (solidcore's fit, `SolidError::FilletRefused`): the size, what it sizes, a point at the + /// middle of the edge it was found for, and why there is no room, when the refusal names them. + TooLarge { size: f64, kind: FitKind, at: Option<[f64; 3]>, why: Option }, + /// A shell, offset or thicken whose wall is thicker than a face curves: the face's offset + /// folds (solidcore's `ShellRefused`, `ShellRefusal::Fold`). The largest wall that works, + /// when solidcore names one. + WallFolds { largest: Option }, + /// SMLib cannot build this exactly yet (a variable radius whose law has a corner). + Unsupported, + /// A blend's edges meet at a vertex of a kind no SMLib blend corner handles yet. + CornerUnsupported, + /// A swept turn ([`Turn::Swept`]) solidcore does not build at the corner `at`: `room` where + /// no radius builds it (a sharp concave side edge between the rounds, solidcore's `NoRoom`), + /// else not supported there (`CornerUnsupported`: unequal or variable rounds, a corner of + /// four edges, a curved, drafted or tangent side edge); `why` is solidcore's reason. + TurnRefused { room: bool, why: String, at: Option<[f64; 3]> }, + /// SMLib does not set back the corner of corner point `corner`: SMLib sets back a corner + /// only where every edge meeting it is blended and they are all convex or all concave. + CornerRefused { corner: usize }, + /// SMLib reported success but the operation did nothing: a blend that made no face, a face + /// move or draft that moved no face. + NoEffect, + /// The answer is not exact in the input's geometry (a box that would wrap round its + /// surface, an analytic surface whose speed across a side varies along it). + NotExact, + /// A drafted extrusion could not close the corner (or wall) at `at` on its profile, for `why`. + Corner { why: sweeps::CornerRefusal, at: [f64; 3] }, + /// solidcore found its own state inconsistent part way through a call (a hole it rebuilt did + /// not close). + Exception, + /// A B-rep record SMLib cannot take (see [`import::Unsupported`]). + Record(import::Unsupported), + /// solidcore reported an error (the call, then its message). + Solidcore(String), + /// solidcore panicked; the guard caught it (the call, then the panic's message). + Internal(String), + /// A step of SMLib solidcore has not ported yet, refused rather than built another way: what + /// is missing, and the solidcore issue that ports it. + Unported(&'static str), +} + +/// Why a blend has no room, as solidcore names its refusal (`NoRoomReason`): the reasons a +/// refusal with a size gives ([`Error::TooLarge`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RoomReason { + /// The rolling ball does not fit a face it rolls on. + BallDoesNotFit, + /// A contact line leaves the face it rolls on. + RailLeavesFace, + /// The blends take the whole of a face they roll on. + FaceConsumed, + /// One blend's contact line runs inside the band another takes off a face they share. + BandsOverlap, + /// The balls fold over one another along the edge. + BallsFold, + /// A face curves tighter than a chamfer's offset along it. + OffsetFolds, + /// The blend would take all of the part between its contact lines and cut it in pieces. + CutsThePart, + /// The blend's section would break through a wall into the hollow behind it. + BreaksThrough, + /// The ball is as wide as a face it rolls on (a cylinder or sphere of its radius), so its + /// centre stays put and no round ends at an end of the edge. + OffsetCollapses, + /// The blend's corners take the whole of its edge. + CornersTakeWholeEdge, + /// A blend past its faces runs off a face into the material. + RunsIntoMaterial, +} + +impl RoomReason { + /// The reason in words, as a fillet's message gives it. + pub fn words(self) -> &'static str { + match self { + RoomReason::BallDoesNotFit => "the rolling ball does not fit a face it rolls on", + RoomReason::RailLeavesFace => "a contact line leaves the face it rolls on", + RoomReason::FaceConsumed => "the blends take the whole of a face they roll on", + RoomReason::BandsOverlap => "one blend runs inside the band another takes off a face they share", + RoomReason::BallsFold => "the rolling ball folds over itself along the edge", + RoomReason::OffsetFolds => "a face curves tighter than the offset along it", + RoomReason::CutsThePart => "the blend would cut the part in pieces", + RoomReason::BreaksThrough => "the blend would break through a wall into the hollow behind it", + RoomReason::OffsetCollapses => { + "the ball is as wide as a face it rolls on, so its centre stays put and the round cannot end at the edge's end" + } + RoomReason::CornersTakeWholeEdge => "its corners take the whole of the edge", + RoomReason::RunsIntoMaterial => "the blend runs off a face into the material", + } + } +} + +/// What the largest size that builds a refused blend ([`Error::TooLarge`]) sizes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FitKind { + /// A round's radius. + Radius, + /// An equal chamfer's distance. + Distance, + /// A factor on a chamfer's two distances. + Scale, + /// A chord round's width. + Chord, +} + +impl FitKind { + /// The size's name, as a fillet's message names it ("the largest radius that fits"). + pub fn word(self) -> &'static str { + match self { + FitKind::Radius => "radius", + FitKind::Distance => "distance", + FitKind::Scale => "scale", + FitKind::Chord => "chord width", + } + } +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Status(1007) => write!(f, "SMLib rejected the input (SM_ERR_INVALID_INPUT)"), + Error::Status(s) => write!(f, "SMLib failed (status {s})"), + Error::Argument => write!(f, "invalid argument for SMLib"), + Error::Empty => write!(f, "SMLib returned an empty body"), + Error::NotSolid => write!(f, "SMLib's result is not a closed solid"), + Error::NoMatch { point } => write!(f, "selection point {} is not near any edge or face", point + 1), + Error::Ambiguous { point } => write!(f, "selection point {} is equally near to two edges or faces", point + 1), + Error::NoRoom => write!(f, "there is no room for it: an offset leaves none inside the body, or a blend is larger than its faces allow"), + Error::WallsTouch => write!(f, "the offset's walls would meet along a line, which leaves no solid there"), + Error::TooLarge { size, kind, at, why } => { + write!(f, "the blend is larger than its faces allow")?; + if let Some([x, y, z]) = at { + write!(f, " at the edge at ({x:.3}, {y:.3}, {z:.3})")?; + } + if let Some(why) = why { + write!(f, ": {}", why.words())?; + } + write!(f, "; the largest {} that fits is {size}", kind.word()) + } + Error::WallFolds { largest } => { + write!(f, "the wall is thicker than a face curves, so the face's offset folds")?; + match largest { + Some(w) => write!(f, "; the largest wall that works is {w}"), + None => Ok(()), + } + } + Error::Unsupported => write!(f, "not supported yet: SMLib cannot build this exactly"), + Error::CornerUnsupported => write!(f, "not supported yet: a corner of this kind is not supported yet by SMLib's blends"), + Error::TurnRefused { why, at, .. } => { + write!(f, "the swept corner is not built")?; + if let Some([x, y, z]) = at { + write!(f, " at ({x:.3}, {y:.3}, {z:.3})")?; + } + write!(f, ": {why}") + } + Error::CornerRefused { corner } => write!( + f, + "not supported yet: SMLib does not set back corner {}: it sets back a corner only where every edge meeting it is blended, all convex or all concave", + corner + 1 + ), + Error::NoEffect => write!(f, "SMLib made no change: it reported success, but the operation did nothing"), + Error::NotExact => write!(f, "SMLib cannot build this exactly in the input's geometry"), + Error::Corner { why, at } => { + let at = format!("({:.4}, {:.4}, {:.4})", at[0], at[1], at[2]); + match why { + sweeps::CornerRefusal::Apart => write!(f, "the draft's continued curves do not meet at the corner at {at}"), + sweeps::CornerRefusal::WallCloses => write!(f, "the draft closes the wall at {at} before the far end"), + sweeps::CornerRefusal::NotExact => { + write!(f, "the draft cannot continue the walls exactly: the curve from {at} is neither a line nor an arc") + } + } + } + Error::Exception => write!(f, "SMLib raised an internal exception"), + Error::Record(u) => write!(f, "{u}"), + Error::Solidcore(e) => write!(f, "solidcore: {e}"), + Error::Internal(e) => write!(f, "solidcore failed internally in {e}"), + Error::Unported(what) => write!(f, "not supported yet: {what}"), + } + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +/// Where failing calls leave their inputs for replay ([`core::dump`]); `None` turns that off. +pub fn set_dump_dir(dir: Option<&Path>) { + core::dump::set_dir(dir.map(Path::to_path_buf)); +} + +/// The kernel call running right now, if any: for crash reports. Takes no lock. +pub fn current_call() -> Option { + core::dump::current() +} + +/// Is this thread inside a solidcore call? A panic there is caught and becomes +/// [`Error::Internal`]; crash reports mark it recovered. +pub fn in_call() -> bool { + core::in_call() +} + +/// A panic inside a solidcore call, which the call catches as it catches any +/// ([`Error::Internal`], the kernel replaced by a fresh one): the crash-report check +/// (`diagnostics.crash_test`'s kernel mode). The crate's one deliberate panic. +#[allow(clippy::panic)] +pub fn crash_test() -> Result<()> { + core::run("crash test", |_| -> std::result::Result<(), solidcore::SolidError> { + std::panic::panic_any(String::from("crash test: an internal error in the kernel")) + }) +} + +/// A B-rep. Immutable: operations return new bodies. +pub struct Brep { + body: core::Body, + /// The body's number in a trace ([`trace`]). + id: u64, +} + +impl std::fmt::Debug for Brep { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("smlib::Brep") + } +} + +impl Brep { + /// A body solidcore made. + fn made_core(body: core::Body) -> Brep { + Brep { body, id: trace::next_id() } + } + + /// solidcore's body. + fn core(&self) -> &core::Body { + &self.body + } + + /// An axis-aligned box from its lower corner, with positive edge lengths (mm). + pub fn make_box(origin: [f64; 3], size: [f64; 3]) -> Result { + let r = core::make_box(origin, size).map(Brep::made_core); + trace::made("make_box", &[], &r, || serde_json::json!({"origin": origin, "size": size})); + r + } + + /// Reads a native SMLib `.smb` file. + pub fn read(path: &Path, ascii: bool) -> Result { + core::file::read(path, ascii).map(Brep::made_core) + } + + /// Writes this body to a native SMLib `.smb` file. + pub fn write(&self, path: &Path, ascii: bool) -> Result<()> { + core::file::write(self.core(), path, ascii) + } + + /// A deep copy. + pub fn try_clone(&self) -> Result { + let r = core::transform::copy(self.core()).map(Brep::made_core); + trace::made("copy", &[self], &r, || serde_json::json!({})); + r + } + + /// This body moved by the affine `matrix` (column-major: columns 0–2 the images of x, y and + /// z, column 3 the translation), as SMLib's `SmBrep::Transform` takes a matrix: reflections + /// mirror it, a non-uniform scale or a shear turns its geometry into NURBS, tolerances scale + /// with it. + pub fn transformed(&self, matrix: &[[f64; 4]; 4]) -> Result { + let r = core::transform::transform(self.core(), matrix).map(Brep::made_core); + trace::made("transform", &[self], &r, || serde_json::json!({"matrix": matrix})); + r + } + + /// The enclosed volume (mm³) at `relative_accuracy` (SMLib clamps it to [1e-8, 1e-1]). + pub fn volume(&self, relative_accuracy: f64) -> Result { + core::volume(self.core(), relative_accuracy) + } + + /// Face, edge and vertex counts. + pub fn counts(&self) -> Result<[usize; 3]> { + core::counts(self.core()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/smlib/src/measure.rs b/crates/smlib/src/measure.rs new file mode 100644 index 000000000..71e2b664b --- /dev/null +++ b/crates/smlib/src/measure.rs @@ -0,0 +1,344 @@ +//! Exact mass properties from SMLib: area, volume, centroid and inertia, integrated on the exact +//! surfaces rather than a tessellation; the exact box; how far an edge lies from a face's surface; +//! where a point lies against a body. + +use crate::{Brep, Result, core}; + +/// The accuracy [`Brep::mass_properties`] and [`Brep::area`] use unless told otherwise: the +/// finest SMLib allows. Analytic primitives then come out within 2e-7 of their closed forms. +pub const MEASURE_ACCURACY: f64 = 1e-8; + +/// Mass properties of a body at unit density (mm, mm², mm³, mm⁵). For a density ρ the +/// mass is ρ·`volume` and the inertia scales by ρ. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MassProperties { + pub area: f64, + pub volume: f64, + pub centroid: [f64; 3], + /// Ixx, Iyy, Izz about axes through the centroid parallel to the world axes: + /// ∫(y²+z²), ∫(z²+x²), ∫(x²+y²) dV. + pub moments: [f64; 3], + /// Iyz, Izx, Ixy about the centroid: ∫yz, ∫zx, ∫xy dV relative to it. + pub products: [f64; 3], +} + +impl MassProperties { + /// The inertia tensor about the centroid (row-major), whose off-diagonal terms are the + /// negated products. + pub fn inertia_tensor(&self) -> [[f64; 3]; 3] { + let [ixx, iyy, izz] = self.moments; + let [iyz, izx, ixy] = self.products; + [[ixx, -ixy, -izx], [-ixy, iyy, -iyz], [-izx, -iyz, izz]] + } +} + +/// Where a point lies against a body ([`Brep::classify_point`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PointClass { + /// In a void region: outside the material, or in a cavity. + Outside, + /// In a material region. + Inside, + /// Within the body's tolerance of a face, an edge or a vertex. + OnBoundary, +} + +impl Brep { + /// Where `p` (mm) lies against this body, decided exactly on its curves and surfaces (no + /// tessellation) by SMLib's `SmBrep::Point3DClassify` at the body's own zone tolerance: on + /// the boundary when within that tolerance of a face, an edge or a vertex (sheet faces too), + /// else inside a material region or outside. A body with no material (a sheet, an open shell) + /// has no inside. A non-finite coordinate is [`Error::Argument`](crate::Error::Argument). + pub fn classify_point(&self, p: [f64; 3]) -> Result { + core::classify_point(self.core(), p) + } + + /// Mass properties at `relative_accuracy` (clamped to [1e-8, 1e-1]; [`MEASURE_ACCURACY`] is + /// the finest): the sum over the body's material regions, so several lumps, or lumps + /// touching along edges or at points, measure too. A body with no material (a sheet, an open + /// shell) has volume 0 and no inertia, its faces' area and the centroid of that area. + pub fn mass_properties(&self, relative_accuracy: f64) -> Result { + core::mass_properties(self.core(), relative_accuracy) + } + + /// The exact axis-aligned box, least corner then greatest: the extrema of every vertex, edge + /// and face on its exact curve or surface, not grown by tolerances or control hulls. + pub fn bounds(&self) -> Result<([f64; 3], [f64; 3])> { + core::bounds(self.core()) + } + + /// How far edge `edge` (its curve over its interval) lies from the surface of face `face`, + /// over that surface's own domain and not beyond it, in mm: SMLib's own edge/face gap, the + /// one it sizes an edge's tolerance by. Indices are in the body's edge and face order (as + /// it was imported and is exported). An edge run past its face's patch measures how far it + /// goes; SMLib keeps such an edge whole when making its UV trim only when its zone tolerance + /// (half the flat arrays' `EDGE_TOLERANCE`) covers this. + pub fn edge_face_distance(&self, edge: usize, face: usize) -> Result { + core::edge_face_distance(self.core(), edge, face) + } + + /// Total area of every face, each counted once, so sheets and open shells too. + pub fn area(&self, relative_accuracy: f64) -> Result { + core::area(self.core(), relative_accuracy) + } +} + +/// The closed forms of the primitives' measures, for the tests. +#[cfg(test)] +pub(crate) mod closed { + use std::f64::consts::PI; + + /// Area, volume, centroid, Ixx, Iyy, Izz about it (products are 0 for all), and the exact box. + pub(crate) struct Closed { + pub area: f64, + pub volume: f64, + pub centroid: [f64; 3], + pub moments: [f64; 3], + pub bounds: ([f64; 3], [f64; 3]), + } + + /// An axis-aligned box from its lower corner. + pub(crate) fn cuboid(o: [f64; 3], size: [f64; 3]) -> Closed { + let [a, b, c] = size; + let v = a * b * c; + Closed { + area: 2.0 * (a * b + b * c + c * a), + volume: v, + centroid: [o[0] + a / 2.0, o[1] + b / 2.0, o[2] + c / 2.0], + moments: [v * (b * b + c * c) / 12.0, v * (a * a + c * c) / 12.0, v * (a * a + b * b) / 12.0], + bounds: (o, [o[0] + a, o[1] + b, o[2] + c]), + } + } + + /// A cylinder about +Z on its base centre. + pub(crate) fn cylinder(o: [f64; 3], r: f64, h: f64) -> Closed { + let v = PI * r * r * h; + let ixx = v * (3.0 * r * r + h * h) / 12.0; + Closed { + area: 2.0 * PI * r * r + 2.0 * PI * r * h, + volume: v, + centroid: [o[0], o[1], o[2] + h / 2.0], + moments: [ixx, ixx, v * r * r / 2.0], + bounds: ([o[0] - r, o[1] - r, o[2]], [o[0] + r, o[1] + r, o[2] + h]), + } + } + + pub(crate) fn sphere(o: [f64; 3], r: f64) -> Closed { + let v = 4.0 / 3.0 * PI * r * r * r; + let i = 0.4 * v * r * r; + Closed { + area: 4.0 * PI * r * r, + volume: v, + centroid: o, + moments: [i; 3], + bounds: ([o[0] - r, o[1] - r, o[2] - r], [o[0] + r, o[1] + r, o[2] + r]), + } + } + + /// A frustum (a cone when `rt` is 0) about +Z on its base centre. Its volume integrals are + /// polynomials in z of degree at most 4, so three-point Gauss-Legendre gives them exactly. + pub(crate) fn cone(o: [f64; 3], rb: f64, rt: f64, h: f64) -> Closed { + let (x, w) = ([-(0.6f64).sqrt(), 0.0, (0.6f64).sqrt()], [5.0 / 9.0, 8.0 / 9.0, 5.0 / 9.0]); + let (mut v, mut mz, mut zz, mut izz) = (0.0, 0.0, 0.0, 0.0); + for (xi, wi) in x.iter().zip(w) { + let (z, wi) = (h / 2.0 * (1.0 + xi), wi * h / 2.0); + let rho = rb + (rt - rb) * z / h; + let disc = PI * rho * rho; + v += wi * disc; + mz += wi * disc * z; + zz += wi * disc * z * z; + izz += wi * disc * rho * rho / 2.0; + } + let zc = mz / v; + let ixx = izz / 2.0 + zz - v * zc * zc; + let s = ((rb - rt).powi(2) + h * h).sqrt(); + let m = rb.max(rt); + Closed { + area: PI * (rb * rb + rt * rt + (rb + rt) * s), + volume: v, + centroid: [o[0], o[1], o[2] + zc], + moments: [ixx, ixx, izz], + bounds: ([o[0] - m, o[1] - m, o[2]], [o[0] + m, o[1] + m, o[2] + h]), + } + } + + /// A ring torus about +Z (Pappus for area and volume). + pub(crate) fn torus(o: [f64; 3], big: f64, r: f64) -> Closed { + let v = 2.0 * PI * PI * big * r * r; + let ixx = v * (big * big / 2.0 + 5.0 * r * r / 8.0); + let m = big + r; + Closed { + area: 4.0 * PI * PI * big * r, + volume: v, + centroid: o, + moments: [ixx, ixx, v * (big * big + 0.75 * r * r)], + bounds: ([o[0] - m, o[1] - m, o[2] - r], [o[0] + m, o[1] + m, o[2] + r]), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Error; + fn rel(a: f64, b: f64) -> f64 { + if b == 0.0 { a.abs() } else { (a / b - 1.0).abs() } + } + + /// tests/oracle/01-box: the analytic values its expected.json gives, plus the box's inertia. + #[test] + fn the_oracle_box_measures_exactly() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/oracle/01-box/expected.json"); + let expected: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir).unwrap()).unwrap(); + assert_eq!(expected["source"], "analytic"); + let max = &expected["bbox"]["max"]; + let size = [0, 1, 2].map(|i| max[i].as_f64().unwrap()); + let b = Brep::make_box([0.0; 3], size).unwrap(); + let m = b.mass_properties(MEASURE_ACCURACY).unwrap(); + assert!(rel(m.volume, expected["volume_mm3"].as_f64().unwrap()) < 1e-12, "{m:?}"); + assert!(rel(m.area, expected["area_mm2"].as_f64().unwrap()) < 1e-12, "{m:?}"); + assert!(rel(b.area(MEASURE_ACCURACY).unwrap(), expected["area_mm2"].as_f64().unwrap()) < 1e-12); + for i in 0..3 { + assert!((m.centroid[i] - expected["center_of_mass"][i].as_f64().unwrap()).abs() < 1e-9, "{m:?}"); + } + let [a, bb, c] = size; + let v = a * bb * c; + let want = [v * (bb * bb + c * c) / 12.0, v * (a * a + c * c) / 12.0, v * (a * a + bb * bb) / 12.0]; + for i in 0..3 { + assert!(rel(m.moments[i], want[i]) < 1e-12, "{m:?}"); + assert!(m.products[i].abs() < 1e-9 * want[2], "{m:?}"); + } + } + + /// Far from the origin the inertia is still taken about the centroid, without cancellation. + #[test] + fn a_box_far_from_the_origin_keeps_its_inertia() { + let b = Brep::make_box([1.0e5, -2.0e5, 3.0e4], [3.0, 50.0, 0.5]).unwrap(); + let m = b.mass_properties(MEASURE_ACCURACY).unwrap(); + let v = 75.0; + assert!(rel(m.volume, v) < 1e-12); + assert!(rel(m.centroid[0], 1.0e5 + 1.5) < 1e-14 && rel(m.centroid[1], -2.0e5 + 25.0) < 1e-14); + assert!(rel(m.moments[0], v * (2500.0 + 0.25) / 12.0) < 1e-9, "{m:?}"); + assert!(rel(m.moments[1], v * (9.0 + 0.25) / 12.0) < 1e-9, "{m:?}"); + assert!(rel(m.moments[2], v * (9.0 + 2500.0) / 12.0) < 1e-9, "{m:?}"); + let t = m.inertia_tensor(); + assert_eq!(t[0][1], t[1][0]); + assert!(t[0][1].abs() < 1e-9 * m.moments[2]); + } + + /// Reads `tests/oracle//expected.json`. + #[allow(clippy::unwrap_used)] // test fixture + fn oracle(case: &str) -> serde_json::Value { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/oracle").join(case).join("expected.json"); + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + assert_eq!(v["source"], "analytic", "{case}"); + v + } + + use closed::Closed; + + /// A primitive with its closed forms. + struct Expected { + name: &'static str, + body: Brep, + area: f64, + volume: f64, + centroid: [f64; 3], + moments: [f64; 3], + } + + #[allow(clippy::unwrap_used)] // test fixture + fn expected(name: &'static str, body: Result, c: Closed) -> Expected { + Expected { name, body: body.unwrap(), area: c.area, volume: c.volume, centroid: c.centroid, moments: c.moments } + } + + fn cylinder(name: &'static str, o: [f64; 3], r: f64, h: f64) -> Expected { + expected(name, Brep::make_cylinder(o, r, h), closed::cylinder(o, r, h)) + } + + fn sphere(name: &'static str, o: [f64; 3], r: f64) -> Expected { + expected(name, Brep::make_sphere(o, r), closed::sphere(o, r)) + } + + fn cone(name: &'static str, o: [f64; 3], rb: f64, rt: f64, h: f64) -> Expected { + expected(name, Brep::make_cone(o, rb, rt, h), closed::cone(o, rb, rt, h)) + } + + fn torus(name: &'static str, o: [f64; 3], big: f64, r: f64) -> Expected { + expected(name, Brep::make_torus(o, big, r), closed::torus(o, big, r)) + } + + /// Every primitive against its closed form, at the origin and 2e5 mm out, to 1e-6 (tests/oracle + /// accepts 1e-3). Cylinders as oracle 02 and 38 give them, against their expected.json too. + #[test] + fn primitives_match_their_closed_forms() { + for (case, r) in [("02-cylinder", 15.0), ("38-coincident-cylinders", 10.0)] { + let e = oracle(case); + let m = Brep::make_cylinder([0.0; 3], r, 50.0).unwrap().mass_properties(MEASURE_ACCURACY).unwrap(); + assert!(rel(m.volume, e["volume_mm3"].as_f64().unwrap()) < 1e-6, "{case}: {m:?}"); + assert!(rel(m.area, e["area_mm2"].as_f64().unwrap()) < 1e-6, "{case}: {m:?}"); + for i in 0..3 { + assert!((m.centroid[i] - e["center_of_mass"][i].as_f64().unwrap()).abs() < 1e-6, "{case}: {m:?}"); + } + } + let far = [1.0e5, -2.0e5, 3.0e4]; + let cases = [ + cylinder("cylinder r15 h50", [0.0; 3], 15.0, 50.0), + cylinder("cylinder r0.25 h80, far", far, 0.25, 80.0), + // The primitives of oracle 40-box-sphere-torus, whole. + sphere("sphere r12", [0.0; 3], 12.0), + sphere("sphere r7, far", far, 7.0), + torus("torus R22 r4", [0.0; 3], 22.0, 4.0), + torus("torus R30 r0.5, far", far, 30.0, 0.5), + cone("frustum r10..4 h20", [0.0; 3], 10.0, 4.0, 20.0), + cone("cone r10 h20", [0.0; 3], 10.0, 0.0, 20.0), + cone("inverted frustum r3..9 h7", [0.0; 3], 3.0, 9.0, 7.0), + cone("frustum r6..2 h9, far", far, 6.0, 2.0, 9.0), + ]; + for e in &cases { + let m = e.body.mass_properties(MEASURE_ACCURACY).unwrap(); + let name = e.name; + assert!(rel(m.area, e.area) < 1e-6, "{name}: {m:?}"); + assert!(rel(e.body.area(MEASURE_ACCURACY).unwrap(), e.area) < 1e-6, "{name}"); + assert!(rel(m.volume, e.volume) < 1e-6, "{name}: {m:?}"); + // The centroid against the body's size: twice its largest radius of gyration. + let size = 2.0 * e.moments.iter().fold(0.0f64, |a, &b| a.max(b)).sqrt() / e.volume.sqrt(); + let imax = e.moments.iter().fold(0.0f64, |a, &b| a.max(b)); + for i in 0..3 { + assert!((m.centroid[i] - e.centroid[i]).abs() < 1e-6 * size, "{name}: {m:?}"); + assert!(rel(m.moments[i], e.moments[i]) < 1e-6, "{name}: {m:?}"); + assert!(m.products[i].abs() < 1e-6 * imax, "{name}: {m:?}"); + } + } + } + + /// A 10 × 20 × 30 box: inside, outside, on a face, an edge and a vertex; a cylinder of radius + /// 5 just off its curved wall, within the tolerance (on it) and beyond (inside or outside). + #[test] + fn points_classify_exactly() { + let b = Brep::make_box([0.0; 3], [10.0, 20.0, 30.0]).unwrap(); + assert_eq!(b.classify_point([5.0, 10.0, 15.0]).unwrap(), PointClass::Inside); + assert_eq!(b.classify_point([5.0, 10.0, 30.0 + 1e-4]).unwrap(), PointClass::Outside); + assert_eq!(b.classify_point([5.0, 10.0, 30.0 - 1e-4]).unwrap(), PointClass::Inside); + assert_eq!(b.classify_point([5.0, 10.0, 30.0]).unwrap(), PointClass::OnBoundary); + assert_eq!(b.classify_point([10.0, 10.0, 30.0]).unwrap(), PointClass::OnBoundary); + assert_eq!(b.classify_point([10.0, 20.0, 30.0]).unwrap(), PointClass::OnBoundary); + assert_eq!(b.classify_point([5.0, 10.0, f64::NAN]).unwrap_err(), Error::Argument); + let c = Brep::make_cylinder([0.0; 3], 5.0, 10.0).unwrap(); + let at = |r: f64| [r * std::f64::consts::FRAC_1_SQRT_2, r * std::f64::consts::FRAC_1_SQRT_2, 5.0]; + assert_eq!(c.classify_point(at(5.0 + 1e-8)).unwrap(), PointClass::OnBoundary); + assert_eq!(c.classify_point(at(5.0 - 1e-8)).unwrap(), PointClass::OnBoundary); + assert_eq!(c.classify_point(at(5.0 + 1e-4)).unwrap(), PointClass::Outside); + assert_eq!(c.classify_point(at(5.0 - 1e-4)).unwrap(), PointClass::Inside); + } + + #[test] + fn bad_accuracies_are_errors() { + let b = Brep::make_box([0.0; 3], [1.0; 3]).unwrap(); + assert_eq!(b.mass_properties(f64::NAN).unwrap_err(), Error::Argument); + assert_eq!(b.area(f64::INFINITY).unwrap_err(), Error::Argument); + // Out of range is clamped, not refused. + assert!(rel(b.mass_properties(1e-30).unwrap().volume, 1.0) < 1e-12); + assert!(rel(b.mass_properties(10.0).unwrap().volume, 1.0) < 1e-12); + } +} diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs new file mode 100644 index 000000000..bbe352d92 --- /dev/null +++ b/crates/smlib/src/ops.rs @@ -0,0 +1,414 @@ +//! SMLib's modelling operations: booleans, fillet, chamfer, shell, offset faces and thicken. +//! Each returns a new body +//! and leaves its inputs unchanged. +//! +//! Edges and faces are chosen by points, never by SMLib's internal order: each point selects the +//! edge (face) nearest to it, which must lie within `tolerance` of it and be nearer than any other +//! by more than the body's modelling tolerance ([`Error::NoMatch`], [`Error::Ambiguous`]). + +use serde_json::json; + +use crate::trace::{self, PickKind}; +use crate::{Brep, Error, Result, core}; + +/// How [`Brep::boolean`] combines two bodies. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BooleanOp { + Union, + /// The first body minus the second. + Subtract, + Intersect, +} + +impl BooleanOp { + /// The operation's name in a trace ([`crate::trace`]). + pub fn word(self) -> &'static str { + match self { + BooleanOp::Union => "union", + BooleanOp::Subtract => "subtract", + BooleanOp::Intersect => "intersect", + } + } +} + +/// What [`Brep::blend`] makes of each selected edge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Blend { + /// A circular cross-section at a constant radius ([`Brep::fillet`]). + Round, + /// A curvature-continuous (G2) cross-section between the contact lines of the round of + /// that radius. + Curvature, + /// A circular cross-section of constant width from contact line to contact line: the size + /// is that width. + Chord, + /// An equal-distance chamfer ([`Brep::chamfer`]): the size is the setback along each face. + Chamfer, +} + +impl Blend { + /// The section's name in a trace ([`crate::trace`]). + pub fn word(self) -> &'static str { + match self { + Blend::Round => "round", + Blend::Curvature => "curvature", + Blend::Chord => "chord", + Blend::Chamfer => "chamfer", + } + } +} + +/// How two constant rounds of one radius turn round a sharp, straight, convex side edge square to +/// both on a plane (the rounds along a boss's base, at its upright edges): the turn of +/// [`Brep::blend_dropping`]'s rounds ([`Blend::Round`] only). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Turn { + /// The rounds run on to where they cross and meet in a mitre, the plane section of the two. + #[default] + Mitre, + /// The rounds end on their sections at the side edge, and the corner's face is that section + /// revolved about the side edge, an exact torus tangent to both rounds. A corner where this + /// is not built is [`Error::TurnRefused`]. + Swept, +} + +impl Turn { + /// The turn's name in a trace ([`crate::trace`]). + pub fn word(self) -> &'static str { + match self { + Turn::Mitre => "mitre", + Turn::Swept => "swept", + } + } +} + +/// The second side of [`Brep::chamfer_sides`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ChamferSecond { + /// The setback along the other face. + Distance(f64), + /// The angle (radians) the chamfer makes with the first face. + Angle(f64), +} + +/// Most bodies [`Brep::union_all`] takes. +pub const MAX_UNION_BREPS: usize = 100_000; + +/// Most points one selection may hold. +pub const MAX_POINTS: usize = 4096; + +/// One edge round an opened corner's hole ([`Brep::blend_setback_open`]): its index in the +/// sheet's edge order, the face beside it in its face order, and whether that face, run +/// counter-clockwise about its outward normal, runs the edge from its start vertex to its end. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HoleEdge { + pub edge: usize, + pub face: usize, + pub forward: bool, +} + +/// The edges round an opened corner's hole, in order: each starts where the one before it ends. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Hole { + pub edges: Vec, +} + +impl Brep { + /// `self` and `other` combined by `op`: `None` when the result is empty (disjoint bodies + /// intersected, a body subtracted by one that encloses it). Several separate solids come back + /// as one body, counted by [`Brep::solid_count`]. Tagged operands ([`Brep::tagged`]) give a + /// result whose [`Brep::history`] says where each face and edge came from. + pub fn boolean(&self, other: &Brep, op: BooleanOp) -> Result> { + let r = core::boolean::boolean(self.core(), other.core(), op).map(|r| r.map(Brep::made_core)); + trace::maybe("boolean", &[self, other], &r, || json!({"op": op.word()})); + r + } + + /// The union of `breps` in one call: they are unioned pairwise, level by level, so none takes + /// part in more than about log2(n) unions. The result is as [`Brep::boolean`]'s; operands + /// tagged each with its own number ([`Brep::tagged`]) give a result whose [`Brep::history`] + /// names them. At least one body and at most [`MAX_UNION_BREPS`]. + pub fn union_all(breps: &[&Brep]) -> Result { + if breps.is_empty() || breps.len() > MAX_UNION_BREPS { + return Err(Error::Argument); + } + let bodies: Vec<&core::Body> = breps.iter().map(|b| b.core()).collect(); + let r = core::boolean::union_all(&bodies).map(Brep::made_core); + trace::made("union_all", breps, &r, || json!({})); + r + } + + /// `self` and `other`, sheets of planar faces on one plane ([`Brep::planar_faces`]), combined + /// as regions of that plane by `op`: `None` when the result is empty. The result's edges are + /// the inputs' own curves, split where they cross. + pub fn boolean2d(&self, other: &Brep, op: BooleanOp) -> Result> { + let r = core::boolean::boolean2d(self.core(), other.core(), op).map(|r| r.map(Brep::made_core)); + trace::maybe("boolean2d", &[self, other], &r, || json!({"op": op.word()})); + r + } + + /// `self` with each face `tool` meets cut along the intersection, the pieces kept as faces of + /// one body: `None` when the tool meets no face. Tagged operands give the pieces' history + /// (each piece is a split of the face it was cut from). + pub fn imprint(&self, tool: &Brep) -> Result> { + let r = core::boolean::imprint(self.core(), tool.core()).map(|r| r.map(Brep::made_core)); + trace::maybe("imprint", &[self, tool], &r, || json!({})); + r + } + + /// The number of separate solid regions (voids not counted). + pub fn solid_count(&self) -> Result { + crate::core::solid_count(self.core()) + } + + /// The edges nearest to `edges` (each within `tolerance`), exactly those, rounded + /// at `radius`. + pub fn fillet(&self, edges: &[[f64; 3]], tolerance: f64, radius: f64) -> Result { + let r = self.core_blend(Blend::Round, edges, &[radius], tolerance, &[], &[], core::blend::Corners::Filled); + trace::made("fillet", &[self], &r, || json!({"edges": trace::picks(self, PickKind::Edge, edges, tolerance), "radius": radius})); + r + } + + /// The edges nearest to `edges` (each within `tolerance`), exactly those, cut by + /// an equal-distance chamfer `distance` back along each face (measured at each edge's + /// midpoint), with bevelled corners. + pub fn chamfer(&self, edges: &[[f64; 3]], tolerance: f64, distance: f64) -> Result { + let r = self.core_blend(Blend::Chamfer, edges, &[distance], tolerance, &[], &[], core::blend::Corners::Filled); + trace::made("chamfer", &[self], &r, || json!({"edges": trace::picks(self, PickKind::Edge, edges, tolerance), "distance": distance})); + r + } + + /// The edges nearest to `edges` (each within `tolerance`), exactly those, blended + /// as `kind`, edge i at `sizes[i]`. + pub fn blend(&self, kind: Blend, edges: &[[f64; 3]], sizes: &[f64], tolerance: f64) -> Result { + if edges.len() > MAX_POINTS || edges.is_empty() || sizes.len() != edges.len() { + return Err(Error::Argument); + } + let r = self.core_blend(kind, edges, sizes, tolerance, &[], &[], core::blend::Corners::Filled); + trace::made( + "blend", + &[self], + &r, + || json!({"kind": kind.word(), "edges": trace::picks(self, PickKind::Edge, edges, tolerance), "sizes": sizes}), + ); + r + } + + /// [`Brep::blend`], with whether each point picked an edge that a larger round, overflowing + /// its faces, removed whole: that edge is gone and not rounded (SMLib rounds the edges whose + /// blends overflow first, then what is left of the others). Two rounds turn at a side edge as + /// `turn` says; [`Turn::Swept`] is for [`Blend::Round`] only ([`Error::Argument`] otherwise). + pub fn blend_dropping(&self, kind: Blend, turn: Turn, edges: &[[f64; 3]], sizes: &[f64], tolerance: f64) -> Result<(Brep, Vec)> { + if edges.len() > MAX_POINTS || edges.is_empty() || sizes.len() != edges.len() { + return Err(Error::Argument); + } + let r = core::blend::blend_dropping(self.core(), kind, turn, edges, sizes, tolerance).map(|(b, d)| (Brep::made_core(b), d)); + trace::call( + "blend_dropping", + &[self], + &r, + |(b, _)| vec![b.id], + || json!({"kind": kind.word(), "turn": turn.word(), "edges": trace::picks(self, PickKind::Edge, edges, tolerance), "sizes": sizes}), + ); + r + } + + /// [`Brep::blend`] with corner setbacks: each of `corners` picks the vertex nearest it + /// (within `tolerance`), a corner where every edge is blended, and that corner's patch starts + /// `setbacks[j]` along each of its edges from the vertex (one distance per corner, as SMLib + /// keeps it). A corner SMLib builds no setback on (some edge there not blended, a chamfer) is + /// [`Error::Unsupported`]; a setback as long as an edge there, [`Error::NoRoom`]. + pub fn blend_setback( + &self, + kind: Blend, + edges: &[[f64; 3]], + sizes: &[f64], + corners: &[[f64; 3]], + setbacks: &[f64], + tolerance: f64, + ) -> Result { + if edges.len() > MAX_POINTS + || edges.is_empty() + || sizes.len() != edges.len() + || corners.is_empty() + || corners.len() > MAX_POINTS + || setbacks.len() != corners.len() + { + return Err(Error::Argument); + } + let r = self.core_blend(kind, edges, sizes, tolerance, corners, setbacks, core::blend::Corners::Filled); + trace::made("blend_setback", &[self], &r, || { + json!({"kind": kind.word(), "edges": trace::picks(self, PickKind::Edge, edges, tolerance), "sizes": sizes, + "corners": trace::picks(self, PickKind::Vertex, corners, tolerance), "setbacks": setbacks}) + }); + r + } + + /// [`Brep::blend_setback`] with each set-back corner left open: SMLib's patch between the + /// corner's setback sections is removed, so the result is a sheet whose only free edges are + /// the holes', one [`Hole`] per corner in `corners`' order (a vertex picked twice gives its + /// hole twice). A corner whose patch SMLib does not build as a disc of faces of its own is + /// [`Error::Unsupported`]. + pub fn blend_setback_open( + &self, + kind: Blend, + edges: &[[f64; 3]], + sizes: &[f64], + corners: &[[f64; 3]], + setbacks: &[f64], + tolerance: f64, + ) -> Result<(Brep, Vec)> { + if edges.len() > MAX_POINTS + || edges.is_empty() + || sizes.len() != edges.len() + || corners.is_empty() + || corners.len() > MAX_POINTS + || setbacks.len() != corners.len() + { + return Err(Error::Argument); + } + let r = core::blend::blend_holes(self.core(), kind, edges, sizes, tolerance, corners, setbacks, core::blend::Corners::Open) + .map(|(b, holes)| (Brep::made_core(b), holes)); + trace::call( + "blend_setback_open", + &[self], + &r, + |(b, _)| vec![b.id], + || { + json!({"kind": kind.word(), "edges": trace::picks(self, PickKind::Edge, edges, tolerance), "sizes": sizes, + "corners": trace::picks(self, PickKind::Vertex, corners, tolerance), "setbacks": setbacks}) + }, + ); + r + } + + /// The one edge nearest to `edge` (within `tolerance`) rounded with a radius + /// that varies along it: a clamped B-spline of `degree` (1 to 3) with `knots` and control + /// `radii` over the position along the edge, 0 at its end nearest `start` and 1 at the other + /// (the edge curve's parameter scaled to 0..1). + pub fn fillet_variable(&self, edge: [f64; 3], tolerance: f64, start: [f64; 3], degree: usize, knots: &[f64], radii: &[f64]) -> Result { + let r = core::blend::fillet_variable(self.core(), edge, tolerance, start, degree, knots, radii).map(Brep::made_core); + trace::made( + "fillet_variable", + &[self], + &r, + || json!({"edge": trace::picks(self, PickKind::Edge, &[edge], tolerance), "start": start, "degree": degree, "knots": knots, "radii": radii}), + ); + r + } + + /// The edges nearest to `edges` (each within `tolerance`), exactly those, cut by + /// a chamfer `distance` back along the face whose outward normal leans most along `first`, + /// and by `second` on the other, with bevelled corners (setbacks measured at each edge's + /// midpoint). + pub fn chamfer_sides(&self, edges: &[[f64; 3]], tolerance: f64, distance: f64, second: ChamferSecond, first: [f64; 3]) -> Result { + if edges.is_empty() || edges.len() > MAX_POINTS { + return Err(Error::Argument); + } + let r = core::blend::chamfer_sides(self.core(), edges, tolerance, distance, second, first).map(Brep::made_core); + trace::made("chamfer_sides", &[self], &r, || { + let second = match second { + ChamferSecond::Distance(d) => json!({"distance": d}), + ChamferSecond::Angle(a) => json!({"angle": a}), + }; + json!({"edges": trace::picks(self, PickKind::Edge, edges, tolerance), "distance": distance, "second": second, "first": first}) + }); + r + } + + /// Hollowed to a wall of `thickness` (negative: inside the original surface, positive: + /// outside), open at the faces nearest to `open_faces` (each within `tolerance`); none gives + /// a closed hollow body. An inward wall that leaves no room inside is [`Error::NoRoom`]; one + /// whose walls would just meet (a hole exactly twice the wall from a side) is + /// [`Error::WallsTouch`]. + pub fn shell(&self, open_faces: &[[f64; 3]], tolerance: f64, thickness: f64) -> Result { + let r = core::offset::shell(self.core(), open_faces, tolerance, thickness).map(Brep::made_core); + trace::made( + "shell", + &[self], + &r, + || json!({"open_faces": trace::picks(self, PickKind::Face, open_faces, tolerance), "thickness": thickness}), + ); + r + } + + /// The solid with the faces nearest to `faces` (each within `tolerance`) moved `distance` + /// along their outward normals (negative: into the body), onto their surfaces' offsets, the + /// faces around them extended or trimmed to meet them. Faces moved in past all of the body + /// behind them are [`Error::NoRoom`]. + pub fn offset_faces(&self, faces: &[[f64; 3]], tolerance: f64, distance: f64) -> Result { + let r = core::offset::offset_faces(self.core(), faces, tolerance, distance).map(Brep::made_core); + trace::made("offset_faces", &[self], &r, || json!({"faces": trace::picks(self, PickKind::Face, faces, tolerance), "distance": distance})); + r + } + + /// A sheet thickened into a solid by `thickness` along its surfaces' normals (negative: + /// against them), or by half each way when `symmetric`, with ruled walls along its open + /// edges. A closed solid is [`Error::Argument`]. + pub fn thicken(&self, thickness: f64, symmetric: bool) -> Result { + let r = core::offset::thicken(self.core(), thickness, symmetric).map(Brep::made_core); + trace::made("thicken", &[self], &r, || json!({"thickness": thickness, "symmetric": symmetric})); + r + } + + /// This body with its topological edges and vertices removed (SMLib's + /// `SmBrep::RemoveTopologicalEdgesAndVertices`): faces on one surface meeting along an edge + /// become one, and two edges on one curve meeting at a vertex nothing else uses become one. + /// The edges nearest to `keep` (each within `tolerance`) stay. The shape is unchanged, and + /// SMLib's history tags follow the merge. + pub fn merge_faces(&self, keep: &[[f64; 3]], tolerance: f64) -> Result { + if keep.len() > MAX_POINTS { + return Err(Error::Argument); + } + let r = core::merge::merge_faces(self.core(), keep, tolerance).map(Brep::made_core); + trace::made("merge_faces", &[self], &r, || json!({"keep": trace::picks(self, PickKind::Edge, keep, tolerance)})); + r + } + + /// The flat faces nearest to `faces` (each within `tolerance`) tilted by `angle` radians + /// (0 < |angle| < 89.94 degrees) about the line where each meets the neutral plane through + /// `neutral_origin` with normal `neutral_normal`, a positive angle leaning them in going along + /// `pull`; the faces around them extended or trimmed to meet them. A face that isn't flat, or + /// isn't parallel to `pull`, is [`Error::Unsupported`]. + pub fn draft( + &self, + faces: &[[f64; 3]], + tolerance: f64, + neutral_origin: [f64; 3], + neutral_normal: [f64; 3], + pull: [f64; 3], + angle: f64, + ) -> Result { + if faces.is_empty() || faces.len() > MAX_POINTS { + return Err(Error::Argument); + } + let r = core::offset::draft(self.core(), faces, tolerance, neutral_origin, neutral_normal, pull, angle).map(Brep::made_core); + trace::made("draft", &[self], &r, || { + json!({"faces": trace::picks(self, PickKind::Face, faces, tolerance), "neutral_origin": neutral_origin, + "neutral_normal": neutral_normal, "pull": pull, "angle": angle}) + }); + r + } + + /// [`Brep::blend`] and its kin on solidcore (`core::blend::blend`). + #[allow(clippy::too_many_arguments)] + fn core_blend( + &self, + kind: Blend, + edges: &[[f64; 3]], + sizes: &[f64], + tolerance: f64, + corners: &[[f64; 3]], + setbacks: &[f64], + open: core::blend::Corners, + ) -> Result { + if edges.len() > MAX_POINTS || edges.is_empty() { + return Err(Error::Argument); + } + core::blend::blend(self.core(), kind, edges, sizes, tolerance, corners, setbacks, open).map(Brep::made_core) + } +} + +#[cfg(test)] +#[path = "ops_tests.rs"] +mod tests; diff --git a/crates/smlib/src/ops_tests.rs b/crates/smlib/src/ops_tests.rs new file mode 100644 index 000000000..f52e242b4 --- /dev/null +++ b/crates/smlib/src/ops_tests.rs @@ -0,0 +1,418 @@ +//! The operations against analytic volumes and topology counts. `SMLIB_OPS_SHOTS=` also +//! writes every result there as a native `.smb`, to render. + +use super::*; +use crate::CheckLevel; + +/// Relative accuracy of SMLib's volume integration in these tests. +const ACC: f64 = 1e-7; + +fn cube(a: f64) -> Brep { + Brep::make_box([0.0; 3], [a; 3]).unwrap() +} + +fn volume(b: &Brep) -> f64 { + b.volume(ACC).unwrap() +} + +fn assert_close(got: f64, want: f64, rel: f64, what: &str) { + assert!((got - want).abs() <= rel * want.abs(), "{what}: {got} vs analytic {want} (rel {:.3e})", (got - want).abs() / want.abs()); +} + +/// SMLib's own check, every test, finds nothing wrong with `b`; then, when `SMLIB_OPS_SHOTS` is +/// set, `b` is written there as `.smb`. +fn shot(b: &Brep, name: &str) { + let report = b.check(CheckLevel::All).unwrap(); + assert!(report.is_valid(), "{name}: {} failed validity tests:\n{}", report.failures, report.text); + if let Some(dir) = std::env::var_os("SMLIB_OPS_SHOTS") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + b.write(&dir.join(format!("{name}.smb")), false).unwrap(); + } +} + +/// The midpoints of the 12 edges of the cube [0, a]³. +fn cube_edge_midpoints(a: f64) -> Vec<[f64; 3]> { + let h = a / 2.0; + let mut v = Vec::new(); + for (p, q) in [(0.0, 0.0), (a, 0.0), (0.0, a), (a, a)] { + v.push([h, p, q]); + v.push([p, h, q]); + v.push([p, q, h]); + } + v +} + +/// The inputs of an operation are left as they were. +fn assert_untouched(b: &Brep, vol: f64, counts: [usize; 3]) { + assert_close(volume(b), vol, 1e-9, "input volume"); + assert_eq!(b.counts().unwrap(), counts, "input counts"); +} + +#[test] +fn union_of_overlapping_boxes() { + let a = cube(20.0); + let b = Brep::make_box([10.0, 5.0, 5.0], [20.0, 10.0, 10.0]).unwrap(); + let u = a.boolean(&b, BooleanOp::Union).unwrap().unwrap(); + shot(&u, "union"); + // 20³ + 20·10·10 − the 10·10·10 overlap. + assert_close(volume(&u), 9000.0, 1e-9, "union volume"); + // A's 6 faces (+x now with a hole) and B's 5 outside it; A's 12 edges, B's 8 outside and the + // 4 where B passes through +x; A's 8 vertices and B's 8 outside. + assert_eq!(u.counts().unwrap(), [11, 24, 16]); + assert_eq!(u.solid_count().unwrap(), 1); + assert_untouched(&a, 8000.0, [6, 12, 8]); + assert_untouched(&b, 2000.0, [6, 12, 8]); +} + +#[test] +fn subtract_cuts_a_slot() { + let a = cube(20.0); + // A 10 mm wide, 10 mm deep slot across the top, from y = −1 to 21. + let tool = Brep::make_box([5.0, -1.0, 10.0], [10.0, 22.0, 15.0]).unwrap(); + let s = a.boolean(&tool, BooleanOp::Subtract).unwrap().unwrap(); + shot(&s, "subtract_slot"); + assert_close(volume(&s), 8000.0 - 10.0 * 20.0 * 10.0, 1e-9, "slot volume"); + // A prism over a U of 8 corners: 8 sides + 2 ends, 24 edges, 16 vertices. + assert_eq!(s.counts().unwrap(), [10, 24, 16]); + assert_eq!(s.solid_count().unwrap(), 1); + assert_untouched(&a, 8000.0, [6, 12, 8]); +} + +#[test] +fn intersect_keeps_the_overlap() { + let a = cube(20.0); + let b = Brep::make_box([10.0, 5.0, 5.0], [20.0, 10.0, 10.0]).unwrap(); + let i = a.boolean(&b, BooleanOp::Intersect).unwrap().unwrap(); + shot(&i, "intersect"); + assert_close(volume(&i), 1000.0, 1e-9, "intersection volume"); + assert_eq!(i.counts().unwrap(), [6, 12, 8]); +} + +#[test] +fn empty_and_split_boolean_results() { + let a = cube(10.0); + let far = Brep::make_box([50.0, 0.0, 0.0], [10.0, 10.0, 10.0]).unwrap(); + assert!(a.boolean(&far, BooleanOp::Intersect).unwrap().is_none(), "disjoint intersection"); + let big = Brep::make_box([-5.0; 3], [20.0; 3]).unwrap(); + assert!(a.boolean(&big, BooleanOp::Subtract).unwrap().is_none(), "subtracting an enclosing body"); + let two = a.boolean(&far, BooleanOp::Union).unwrap().unwrap(); + shot(&two, "union_disjoint"); + assert_eq!(two.solid_count().unwrap(), 2, "a union of disjoint boxes is two solids in one body"); + assert_close(volume(&two), 2000.0, 1e-9, "disjoint union volume"); + // A body through a slot splits in two. + let bar = cube(20.0); + let cut = Brep::make_box([8.0, -1.0, -1.0], [4.0, 22.0, 22.0]).unwrap(); + let halves = bar.boolean(&cut, BooleanOp::Subtract).unwrap().unwrap(); + shot(&halves, "subtract_split"); + assert_eq!(halves.solid_count().unwrap(), 2); + assert_close(volume(&halves), 8000.0 - 4.0 * 400.0, 1e-9, "split volume"); +} + +#[test] +fn fillet_every_edge_of_a_cube() { + let (a, r) = (20.0, 2.0); + let c = cube(a); + let f = c.fillet(&cube_edge_midpoints(a), 0.1, r).unwrap(); + shot(&f, "fillet_all_edges"); + // The rounded cube is the Minkowski sum of the inner cube b = a − 2r with a ball of radius r: + // b³ (core) + 6·b²·r (face slabs) + 12·(π r²/4)·b (quarter cylinders on the edges) + // + 8·(π r³/6) (sphere octants at the corners) = 7804.6961… for a = 20, r = 2. + let b = a - 2.0 * r; + let pi = std::f64::consts::PI; + let want = b.powi(3) + 6.0 * b * b * r + 3.0 * pi * r * r * b + 4.0 / 3.0 * pi * r.powi(3); + let got = volume(&f); + eprintln!("filleted cube: volume {got} (analytic {want}), counts {:?}", f.counts().unwrap()); + assert_close(got, want, 1e-6, "rounded cube volume"); + // 6 planar faces, 12 edge rounds, 8 corner patches. + assert_eq!(f.counts().unwrap()[0], 26); + assert_untouched(&c, 8000.0, [6, 12, 8]); +} + +#[test] +fn chamfer_one_edge() { + let c = cube(20.0); + // The edge y = 20, z = 20, set back 3 mm along both faces: a prism of 3·3/2 × 20 goes. + let ch = c.chamfer(&[[10.0, 20.0, 20.0]], 0.1, 3.0).unwrap(); + shot(&ch, "chamfer_one_edge"); + assert_close(volume(&ch), 8000.0 - 4.5 * 20.0, 1e-9, "chamfered volume"); + // One face more; the edge becomes two edges joined by two new ones; 2 vertices more. + assert_eq!(ch.counts().unwrap(), [7, 15, 10]); + assert_untouched(&c, 8000.0, [6, 12, 8]); +} + +#[test] +fn shell_a_box_open_at_the_top() { + let c = cube(20.0); + let top = [[10.0, 10.0, 20.0]]; + let inward = c.shell(&top, 0.1, -2.0).unwrap(); + shot(&inward, "shell_inward"); + // The cavity is 16 × 16 × 18 (the floor is 2 thick, the top open). + assert_close(volume(&inward), 8000.0 - 16.0 * 16.0 * 18.0, 1e-9, "inward shell volume"); + // Outside 5, inside 5, the rim 1. + assert_eq!(inward.counts().unwrap()[0], 11); + let outward = c.shell(&top, 0.1, 2.0).unwrap(); + shot(&outward, "shell_outward"); + // The outside grows to [−2, 22]² × [−2, 20] around the original box, which becomes the cavity. + assert_close(volume(&outward), 24.0 * 24.0 * 22.0 - 8000.0, 1e-9, "outward shell volume"); + let closed = c.shell(&[], 0.1, -2.0).unwrap(); + shot(&closed, "shell_closed"); + assert_close(volume(&closed), 8000.0 - 16.0f64.powi(3), 1e-9, "closed hollow volume"); + assert_untouched(&c, 8000.0, [6, 12, 8]); +} + +#[test] +fn fillet_takes_exactly_the_picked_edges() { + // Round the vertical edge x = y = 20 first (r = 5): the top rim is then line, arc, line, + // meeting tangentially. + let c = cube(20.0); + let round = c.fillet(&[[20.0, 20.0, 10.0]], 0.1, 5.0).unwrap(); + shot(&round, "fillet_one_edge"); + let pi = std::f64::consts::PI; + assert_close(volume(&round), 8000.0 - (1.0 - pi / 4.0) * 25.0 * 20.0, 1e-6, "one rounded edge"); + // One point on the straight part of the rim rounds that edge only; the chain is rounded when + // all of its edges are picked. + let one = round.fillet(&[[7.5, 20.0, 20.0]], 0.1, 1.0).unwrap(); + shot(&one, "fillet_one_of_a_chain"); + let arc = [15.0 + 5.0 * (pi / 4.0).cos(), 15.0 + 5.0 * (pi / 4.0).sin(), 20.0]; + let all = round.fillet(&[[7.5, 20.0, 20.0], arc, [20.0, 7.5, 20.0]], 0.1, 1.0).unwrap(); + shot(&all, "fillet_chain_picked"); + assert_eq!(one.counts().unwrap()[0], round.counts().unwrap()[0] + 1, "one round on the picked edge"); + assert_eq!(all.counts().unwrap()[0], round.counts().unwrap()[0] + 3, "three rounds on the chain"); + assert!(volume(&all) < volume(&one), "the chain takes more than its one edge"); +} + +#[test] +fn hostile_inputs_are_errors() { + let c = cube(20.0); + let mid = [[10.0, 20.0, 20.0]]; + for r in [f64::NAN, f64::INFINITY, -1.0, 0.0, 1e7] { + assert_eq!(c.fillet(&mid, 0.1, r).unwrap_err(), Error::Argument, "radius {r}"); + assert_eq!(c.chamfer(&mid, 0.1, r).unwrap_err(), Error::Argument, "distance {r}"); + } + for t in [f64::NAN, 0.0, -1.0, f64::INFINITY] { + assert_eq!(c.fillet(&mid, t, 1.0).unwrap_err(), Error::Argument, "tolerance {t}"); + } + assert_eq!(c.fillet(&[[f64::NAN, 0.0, 0.0]], 0.1, 1.0).unwrap_err(), Error::Argument); + assert_eq!(c.fillet(&[], 0.1, 1.0).unwrap_err(), Error::Argument); + assert_eq!(c.fillet(&vec![[10.0, 20.0, 20.0]; MAX_POINTS + 1], 0.1, 1.0).unwrap_err(), Error::Argument); + // A second point far from every edge. + assert_eq!(c.fillet(&[mid[0], [100.0, 100.0, 100.0]], 0.1, 1.0).unwrap_err(), Error::NoMatch { point: 1 }); + assert_eq!(c.shell(&[[10.0, 10.0, 25.0]], 0.1, -1.0).unwrap_err(), Error::NoMatch { point: 0 }); + // A corner is equally near three edges, an edge equally near two faces. + assert_eq!(c.fillet(&[[20.0, 20.0, 20.0]], 0.1, 1.0).unwrap_err(), Error::Ambiguous { point: 0 }); + assert_eq!(c.shell(&mid, 0.1, -1.0).unwrap_err(), Error::Ambiguous { point: 0 }); + for t in [0.0, f64::NAN, -1e7] { + assert_eq!(c.shell(&[[10.0, 10.0, 20.0]], 0.1, t).unwrap_err(), Error::Argument, "thickness {t}"); + } + // A round larger than the cube overflows its faces' far edges, convex, so it is cut as if the + // faces went on: the r50 cylinder about y = z = -30 uses up both faces of the edge and leaves + // the part of the cube's 20 x 20 section inside it, from (0, 10) to (10, 0), along x: 20 x + // that area, 20 (F(40) - F(30) - 300) with F(u) = (u sqrt(2500 - u^2) + 2500 asin(u / 50)) / 2. + let over = c.fillet(&mid, 0.1, 50.0).unwrap(); + let f = |u: f64| 0.5 * (u * (2500.0 - u * u).sqrt() + 2500.0 * (u / 50.0).asin()); + let want = 20.0 * (f(40.0) - f(30.0) - 300.0); + assert!((volume(&over) - want).abs() < 1e-6 * want, "radius larger than the cube: {} vs {want}", volume(&over)); + assert_eq!(over.counts().unwrap(), [5, 9, 6], "the two ends, the two far faces and the round"); + // A chamfer past the faces runs over their far edges, cliffs: it is cut as if the faces went + // on (the plane y + z = 10 through the setbacks 30 back from the edge y = z = 20), leaving the + // triangle y + z <= 10 of the cube's section along x: 50 x 20. + let past = c.chamfer(&mid, 0.1, 30.0).unwrap(); + assert!((volume(&past) - 1000.0).abs() < 1e-6 * 1000.0, "{}", volume(&past)); + // A wall with no room inside it never reaches SMLib's offset. + assert_eq!(c.shell(&[[10.0, 10.0, 20.0]], 0.1, -15.0).unwrap_err(), Error::NoRoom); + assert_eq!(c.offset_faces(&[[10.0, 10.0, 20.0]], 0.1, -20.0).unwrap_err(), Error::NoRoom); + assert_eq!(c.thicken(1.0, false).unwrap_err(), Error::Argument, "a solid is no sheet"); + assert_untouched(&c, 8000.0, [6, 12, 8]); +} + +/// Rig case shell/4711: a 60 x 40 x 10 block with an r3 through hole at (22.5, 7), 4 from the +/// front face, and a 10 x 10 notch on that edge, shelled 2 inward open at the bottom: the hole's +/// offset (r5) is tangent to the front's (y = 2), so the walls meet along a line and the offset +/// bounds no solid there. Refused as such; 1.5 (the walls apart) and 2.5 (crossing, merged) +/// build. +#[test] +fn a_shell_whose_walls_would_meet_is_refused_as_such() { + let block = Brep::make_box([0.0; 3], [60.0, 40.0, 10.0]).unwrap(); + let pin = Brep::make_cylinder([22.5, 7.0, -5.0], 3.0, 20.0).unwrap(); + let notch = Brep::make_box([25.0, -5.0, -5.0], [10.0, 10.0, 20.0]).unwrap(); + let part = block.boolean(&pin, BooleanOp::Subtract).unwrap().unwrap().boolean(¬ch, BooleanOp::Subtract).unwrap().unwrap(); + let bottom = [[50.0, 30.0, 0.0]]; + assert_eq!(part.shell(&bottom, 0.1, -2.0).unwrap_err(), Error::WallsTouch); + for t in [1.5, 2.5] { + shot(&part.shell(&bottom, 0.1, -t).unwrap(), &format!("shell-4711-{t}")); + } +} + +#[test] +fn boolean_history_through_tagged_operands() { + // A slot across the top of the cube: the cube's 6 faces give 7 result faces (the top is cut + // in two), the tool gives the slot's 2 walls and floor; no face is new. + let a = cube(20.0).tagged(0).unwrap(); + let tool = Brep::make_box([5.0, -1.0, 10.0], [10.0, 22.0, 15.0]).unwrap().tagged(1).unwrap(); + let s = a.boolean(&tool, BooleanOp::Subtract).unwrap().unwrap(); + shot(&s, "subtract_slot_tagged"); + let h = s.history().unwrap(); + assert_eq!(h.faces.len(), 10); + let mut from = [0usize; 2]; + for f in &h.faces { + assert!(!f.origins.is_empty(), "{f:?}"); + for &(operand, _) in &f.origins { + from[operand.min(1)] += 1; + } + } + assert_eq!(from, [7, 3], "{h:?}"); + // The 8 edges where the slot's walls and floor meet the top, front and back are new. + assert_eq!(h.edges.iter().filter(|e| e.origins.is_empty()).count(), 8, "{h:?}"); +} + +/// `blend` gives each picked edge its own size: two parallel top edges of a 20 mm cube rounded at +/// 2 and 3 lose (1 - pi/4) r^2 L each, chamfered r^2 L / 2 each; a chord of 2 sqrt 2 on a right +/// angle is the round of radius 2. +#[test] +fn blends_take_a_size_per_edge() { + let c = cube(20.0); + let tops = [[10.0, 20.0, 20.0], [10.0, 0.0, 20.0]]; + let q = 1.0 - std::f64::consts::FRAC_PI_4; + let r = c.blend(Blend::Round, &tops, &[2.0, 3.0], 0.1).unwrap(); + shot(&r, "blend-round-2-3"); + assert_close(volume(&r), 8000.0 - q * 13.0 * 20.0, 1e-6, "rounds 2 and 3"); + let ch = c.blend(Blend::Chamfer, &tops, &[2.0, 3.0], 0.1).unwrap(); + shot(&ch, "blend-chamfer-2-3"); + assert_close(volume(&ch), 8000.0 - 0.5 * 13.0 * 20.0, 1e-6, "chamfers 2 and 3"); + let chord = c.blend(Blend::Chord, &tops[..1], &[2.0 * 2f64.sqrt()], 0.1).unwrap(); + assert_close(volume(&chord), 8000.0 - q * 4.0 * 20.0, 2e-6, "chord"); + assert!(c.blend(Blend::Round, &tops, &[2.0], 0.1).is_err()); +} + +/// A variable round is the union of its balls: in each plane square to the edge, the corner cut off +/// by rays from it, each meeting the union first at the least entry over the balls, integrated +/// along the edge (a linear law's balls envelop a cone). The balls' great circles, (1 - pi/4) r² +/// per unit length, take more: 18.5988 for 3 -> 1, 39.0796 for 4, 1, 4 and 22.8945 for 4 -> 0. +/// On the 20 cube's edge y = z = 20, 3 -> 1 takes 18.5377834 whichever end is the start. +#[test] +fn a_variable_round_follows_its_law() { + let c = cube(20.0); + let knots = [0.0, 0.0, 1.0, 1.0]; + let r = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &knots, &[3.0, 1.0]).unwrap(); + shot(&r, "variable-3-1"); + assert_close(volume(&r), 8000.0 - 18.5377834, 1e-5, "linear law"); + let back = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [20.0, 20.0, 20.0], 1, &knots, &[1.0, 3.0]).unwrap(); + assert_close(volume(&back), volume(&r), 1e-7, "reversed"); + assert!(c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.5, 1.0, 1.0], &[3.0, 1.0]).is_err()); + assert!(matches!(c.fillet_variable([90.0, 90.0, 90.0], 0.1, [0.0; 3], 1, &knots, &[3.0, 1.0]), Err(Error::NoMatch { .. }))); + // A quadratic law with control radii 4, 1, 4, r(t) = 4(1 − t)² + 2t(1 − t) + 4t²: 39.019820. + let quad = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 2, &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &[4.0, 1.0, 4.0]).unwrap(); + shot(&quad, "variable-quadratic"); + assert_close(volume(&quad), 8000.0 - 39.019820, 1e-5, "quadratic law"); + // Down to zero at the far end: the round closes to the edge's end point, 22.594877. + let zero = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &knots, &[4.0, 0.0]).unwrap(); + shot(&zero, "variable-to-zero"); + assert_close(volume(&zero), 8000.0 - 22.594877, 1e-5, "down to zero"); + // A law down to zero inside the edge would pinch the round to a point: refused. + let pinch = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[4.0, 0.0, 4.0]); + assert!(pinch.is_err(), "a law pinching to zero inside the edge"); + let smooth_knots = [0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0]; + let smooth = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 3, &smooth_knots, &[4.0, 10.0 / 3.0, 2.0, 2.0, 2.0, 10.0 / 3.0, 4.0]); + shot(&smooth.unwrap(), "variable-smooth-4-2-4"); +} + +/// A law with a corner (4 → 2 → 4, straight on both halves) on the 20 cube's edge y = z = 20: the +/// union of the balls, with the corner ball's sphere between the halves' touch circles, takes +/// 39.542073 (the halves' great circles would take 40.0590). +#[test] +fn a_variable_round_with_a_corner_in_its_law_is_its_balls_union() { + let c = cube(20.0); + let corner = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[4.0, 2.0, 4.0]).unwrap(); + shot(&corner, "variable-corner-4-2-4"); + assert_close(volume(&corner), 8000.0 - 39.542073, 1e-5, "corner law"); +} + +/// Unequal chamfers of a cube's top edge y = 20: 5 back along the face facing `first` most and 2 +/// along the other take away a triangle 5 × 2 / 2 along the 20 mm edge, either way round; 5 at +/// 30° to the first face is 5 and 5 tan 30°. +#[test] +fn chamfers_with_two_setbacks() { + let c = cube(20.0); + let top = [[10.0, 20.0, 20.0]]; + let up = c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(2.0), [0.0, 0.0, 1.0]).unwrap(); + shot(&up, "chamfer-5-2"); + assert_close(volume(&up), 8000.0 - 5.0 * 20.0, 1e-9, "5 and 2"); + let flipped = c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(2.0), [0.0, 0.0, -1.0]).unwrap(); + assert_close(volume(&flipped), volume(&up), 1e-9, "flipped"); + // Which face took the 5: the removed prism's centroid lies a third of each setback in from + // the edge, so the result's centroid moves away from it. + let centroid = |b: &Brep| b.mass_properties(ACC).unwrap().centroid; + let left = |dy: f64, dz: f64| [10.0, (8000.0 * 10.0 - 100.0 * (20.0 - dy / 3.0)) / 7900.0, (8000.0 * 10.0 - 100.0 * (20.0 - dz / 3.0)) / 7900.0]; + for (b, want, what) in [(&up, left(5.0, 2.0), "5 along the top"), (&flipped, left(2.0, 5.0), "5 down the side")] { + let got = centroid(b); + assert!((0..3).all(|i| (got[i] - want[i]).abs() < 1e-6), "{what}: centroid {got:?}, want {want:?}"); + } + let angle = c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Angle(30f64.to_radians()), [0.0, 0.0, 1.0]).unwrap(); + shot(&angle, "chamfer-5-at-30"); + assert_close(volume(&angle), 8000.0 - 5.0 * 5.0 * 30f64.to_radians().tan() / 2.0 * 20.0, 1e-9, "5 at 30 degrees"); + assert_eq!(c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Angle(4.0), [0.0, 0.0, 1.0]).unwrap_err(), Error::Argument); + assert_eq!(c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(2.0), [0.0; 3]).unwrap_err(), Error::Argument); + assert_eq!(c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(-2.0), [0.0, 0.0, 1.0]).unwrap_err(), Error::Argument); +} + +#[test] +fn imprint_cuts_faces_where_a_tool_meets_them() { + // A box half sunk into the cube cuts the four side faces it crosses and the top it lies in. + let cube = cube(20.0); + let tool = Brep::make_box([5.0, -1.0, 10.0], [10.0, 22.0, 15.0]).unwrap(); + let cut = cube.imprint(&tool).unwrap().unwrap(); + assert!(cut.counts().unwrap()[0] > 6); + assert!((cut.volume(1e-7).unwrap() - 8000.0).abs() < 1e-6); + assert_eq!(cube.counts().unwrap()[0], 6); + // A tool that misses cuts nothing. + let far = Brep::make_box([50.0, 0.0, 0.0], [10.0, 10.0, 10.0]).unwrap(); + assert!(cube.imprint(&far).unwrap().is_none()); +} + +#[test] +fn draft_tilts_a_side_about_its_line_on_the_neutral_plane() { + let c = cube(20.0); + let deg = std::f64::consts::PI / 180.0; + let wedge = 0.5 * 20.0 * 20.0 * (5.0 * deg).tan() * 20.0; + let side = [[20.0, 10.0, 10.0]]; + let up = [0.0, 0.0, 1.0]; + let leaned = c.draft(&side, 0.1, [0.0; 3], up, up, 5.0 * deg).unwrap(); + assert!((leaned.volume(ACC).unwrap() - (8000.0 - wedge)).abs() < 1e-6); + let out = c.draft(&side, 0.1, [0.0; 3], up, up, -5.0 * deg).unwrap(); + assert!((out.volume(ACC).unwrap() - (8000.0 + wedge)).abs() < 1e-6); + // The top isn't parallel to the pull. + assert_eq!(c.draft(&[[10.0, 10.0, 20.0]], 0.1, [0.0; 3], up, up, 5.0 * deg).unwrap_err(), Error::Unsupported); + assert_eq!(c.draft(&side, 0.1, [0.0; 3], up, up, 0.0).unwrap_err(), Error::Argument); + assert_eq!(c.draft(&[], 0.1, [0.0; 3], up, up, 5.0 * deg).unwrap_err(), Error::Argument); + assert_untouched(&c, 8000.0, [6, 12, 8]); +} + +/// The corner of r5 rounds at (60, 40, 20) on a 60 x 40 x 20 box, set back 8 and left open: the +/// box's six faces and the three rounds (9 faces, 30 edges, 22 vertices), a sheet SMLib's check +/// passes, and one hole of twelve edges (each section and face curve in two), chained end to +/// start, each bounding a different face than the patch's neighbours across it. +#[test] +fn a_setback_corner_left_open_returns_its_hole() { + let b = Brep::make_box([0.0; 3], [60.0, 40.0, 20.0]).unwrap(); + let edges = [[30.0, 40.0, 20.0], [60.0, 20.0, 20.0], [60.0, 40.0, 10.0]]; + let (open, holes) = b.blend_setback_open(Blend::Round, &edges, &[5.0; 3], &[[60.0, 40.0, 20.0]], &[8.0], 0.1).unwrap(); + shot(&open, "setback_open"); + assert_eq!(open.counts().unwrap(), [9, 30, 22]); + assert!(!open.is_manifold_solid().unwrap()); + let [hole] = holes.as_slice() else { panic!("one corner: {holes:?}") }; + assert_eq!(hole.edges.len(), 12); + let arrays = open.arrays().unwrap(); + let ends = &arrays.ints[&crate::flat::EDGE_VERTICES]; + let end = |h: &HoleEdge, last: bool| ends[2 * h.edge + usize::from(h.forward == last)]; + for (k, h) in hole.edges.iter().enumerate() { + let next = &hole.edges[(k + 1) % 12]; + assert_eq!(end(h, true), end(next, false), "edge {k} ends where the next starts"); + assert!(h.face < 9); + } + // A corner where an edge is not rounded builds no setback, and the refusal names it. + let refused = b.blend_setback_open(Blend::Round, &edges[..2], &[5.0; 2], &[[60.0, 40.0, 20.0]], &[8.0], 0.1); + assert!(matches!(refused, Err(Error::CornerRefused { corner: 0 })), "{refused:?}"); + let refused = b.blend_setback(Blend::Round, &edges[..2], &[5.0; 2], &[[60.0, 40.0, 20.0]], &[8.0], 0.1); + assert!(matches!(refused, Err(Error::CornerRefused { corner: 0 })), "{refused:?}"); +} diff --git a/crates/smlib/src/pcurves.rs b/crates/smlib/src/pcurves.rs new file mode 100644 index 000000000..ccafeddd5 --- /dev/null +++ b/crates/smlib/src/pcurves.rs @@ -0,0 +1,192 @@ +//! SMLib's own pcurves for a face's uses that have no closed form (an approximated intersection +//! curve on a cone, a file's spline edge on a spline surface): the face goes to SMLib alone, an +//! open sheet, with the trims it has and without the others, and SMLib makes those as it makes +//! every trim it needs (`SmEdgeuse::GetOrCreateUVTrimCurve`, when the body is exported). They are +//! SMLib's, relayed as it holds them on the record's parameters; nothing here fits a curve. + +use solidcraft_geom::prelude::*; +use std::collections::HashSet; + +use solidcore_record::brep::{self as b, Curve2, EdgeUseRef, Loop, OrientedEdge, OrientedFace, Region, Shell, Vertex}; +use solidcraft_geom::brep::pcurve::{SURFACE_GAP_MARGIN, TrimFace, Trims}; + +/// [`Trims`] by SMLib. +#[derive(Clone, Copy, Debug, Default)] +pub struct SmlibTrims; + +impl Trims for SmlibTrims { + fn trims(&self, face: &TrimFace<'_>) -> Result>, String> { + trims(face).map_err(|e| format!("SMLib pcurves: {e}")) + } +} + +fn trims(face: &TrimFace<'_>) -> Result>, String> { + let (record, bare) = sheet(face)?; + let mut arrays = crate::import::arrays_with_bare_uses(&record, &bare).map_err(|e| e.to_string())?; + let import = |a: &crate::import::Arrays| crate::Brep::from_arrays(a).map_err(|e| e.to_string()); + let mut body = import(&arrays)?; + if cover_gaps(&body, face, &bare, &mut arrays)? { + body = import(&arrays)?; + } + let (out, order) = body.to_native_ordered().map_err(|e| e.to_string())?; + let [made] = out.faces.as_slice() else { return Err(format!("SMLib made {} faces of one", out.faces.len())) }; + let made_uses: Vec<&OrientedEdge> = made + .loops + .iter() + .flat_map(|l| match l { + Loop::Edges { edges } => edges.as_slice(), + Loop::Vertex { .. } => &[], + }) + .collect(); + // SMLib keeps the edges in the order they came; the record renumbers them. + let edge_of = |u: u32| order.edges.get(u as usize).copied().ok_or("an edge SMLib lost"); + // A sheet's loops come back the way SMLib runs them, which may be against ours: a use is the + // same pcurve either way (on its edge's interval in its curve's direction), and the loop's + // way round is read from an edge the face uses once. + let ours = face.loops.iter().flatten(); + let once = ours.clone().find(|u| ours.clone().filter(|v| v.edge == u.edge).count() == 1).ok_or("a face of seam edges only")?; + let at = edge_of(once.edge)?; + let reversed = made_uses.iter().find(|m| m.edge as usize == at).ok_or("a use SMLib did not keep")?.forward != once.forward; + // Each edge's tolerance as SMLib held it (raised where it lies off the surface). + let held = arrays.reals.get(&crate::flat::EDGE_TOLERANCE).ok_or("edge tolerances")?; + let mut result = Vec::with_capacity(face.loops.len()); + for l in &face.loops { + let mut pcs = Vec::with_capacity(l.len()); + for u in l { + let e = edge_of(u.edge)?; + let edge = out.edges.get(e).ok_or("an edge SMLib lost")?; + let ours = face.edges.get(u.edge as usize).ok_or("edge reference")?; + let found = made_uses.iter().find(|m| m.edge as usize == e && m.forward == (u.forward != reversed)); + let pc = found.ok_or("a use SMLib did not keep")?.pcurve.clone(); + let tolerance = held.get(u.edge as usize).copied().unwrap_or(ours.tolerance).max(ours.tolerance); + pcs.push(on_our_interval(pc, ours, edge.interval, tolerance)?); + } + result.push(pcs); + } + Ok(result) +} + +/// Each bare use's edge measured against the face's surface as SMLib measures it (over the +/// surface's own domain: an edge run a few um past its patch measures how far), and its +/// `EDGE_TOLERANCE` in `arrays` raised to cover that gap with [`SURFACE_GAP_MARGIN`]: SMLib keeps +/// an edge whole when making its trim only when its zone tolerance (half that) covers the gap, and +/// otherwise trims the edge back to the patch. Whether any was raised; an edge farther off than +/// SMLib's tolerances reach is refused with how far. +fn cover_gaps(body: &crate::Brep, face: &TrimFace<'_>, bare: &HashSet<(u32, u32, u32)>, arrays: &mut crate::import::Arrays) -> Result { + let mut edges: Vec = Vec::new(); + for (li, l) in face.loops.iter().enumerate() { + for (p, u) in l.iter().enumerate() { + let (Ok(li), Ok(p)) = (u32::try_from(li), u32::try_from(p)) else { return Err("too many uses".into()) }; + if bare.contains(&(0, li, p)) && !edges.contains(&(u.edge as usize)) { + edges.push(u.edge as usize); + } + } + } + let mut raised = false; + for e in edges { + let gap = body.edge_face_distance(e, 0).map_err(|e| e.to_string())?; + let need = SURFACE_GAP_MARGIN * gap; + let tolerances = arrays.reals.get_mut(&crate::flat::EDGE_TOLERANCE).ok_or("edge tolerances")?; + let given = tolerances.get_mut(e).ok_or("edge reference")?; + if need <= *given { + continue; + } + if !(need <= crate::flat::MAX_TOLERANCE) { + return Err(format!("an edge lies {gap} mm off the face's surface")); + } + *given = need; + raised = true; + } + Ok(raised) +} + +/// A pcurve SMLib made on its edge's interval `theirs`, on ours. SMLib may set an edge's end to +/// a parameter of its own (a knot its vertex lies at, the end of the part on the face: where an +/// edge runs past its face's patch, SMLib ends it where its drop onto the patch ends, when that +/// is within the edge's cross-section tolerance of its vertex): where each end it chose is +/// within `tolerance` of ours on the edge's curve (the edge's tolerance as SMLib held it, +/// [`cover_gaps`]), the pcurve is mapped onto our interval by the affine change of parameter +/// (exact for a B-spline: its knots move), and the record's check measures it against the edge +/// as any pcurve. Farther is SMLib trimming the edge, refused with how far. +pub(crate) fn on_our_interval( + pc: Curve2, + ours: &solidcraft_geom::brep::pcurve::TrimEdge<'_>, + theirs: [f64; 2], + tolerance: f64, +) -> Result { + let [a, b] = ours.interval; + let [c, d] = theirs; + if a == c && b == d { + return Ok(pc); + } + let curve = solidcraft_geom::brep::eval::CurveEval::new(ours.nurbs.unwrap_or(ours.curve)).map_err(|e| e.to_string())?; + let at = |t: f64| curve.point(t).ok_or_else(|| format!("the edge's curve has no point at {t}")); + let shift = at(a)?.dist(at(c)?).max(at(b)?.dist(at(d)?)); + if !(shift <= tolerance) || !(d > c) { + return Err(format!( + "SMLib moved an edge's interval from {:?} to {:?}, its ends {shift} mm along its curve (tolerance {tolerance} mm)", + ours.interval, theirs + )); + } + let map = |k: f64| { + if k == c { + a + } else if k == d { + b + } else { + a + (k - c) * ((b - a) / (d - c)) + } + }; + Ok(match pc { + Curve2::Spline { knots, points } => Curve2::Spline { knots: knots.into_iter().map(map).collect(), points }, + Curve2::RationalSpline { knots, homogeneous } => Curve2::RationalSpline { knots: knots.into_iter().map(map).collect(), homogeneous }, + }) +} + +/// The face as a one-face open sheet, and its uses that go without trims. +fn sheet(face: &TrimFace<'_>) -> Result<(b::Brep, HashSet<(u32, u32, u32)>), String> { + let mut edges: Vec = face + .edges + .iter() + .map(|e| b::Edge { + curve: e.curve.clone(), + nurbs: e.nurbs.cloned(), + interval: e.interval, + vertices: e.vertices, + tolerance: e.tolerance, + uses: Vec::new(), + }) + .collect(); + let mut bare = HashSet::new(); + let mut loops = Vec::with_capacity(face.loops.len()); + for (li, l) in face.loops.iter().enumerate() { + let li = u32::try_from(li).map_err(|_| "too many loops")?; + let mut uses = Vec::with_capacity(l.len()); + for (p, u) in l.iter().enumerate() { + let p = u32::try_from(p).map_err(|_| "too many uses")?; + let edge = edges.get_mut(u.edge as usize).ok_or("edge reference")?; + edge.uses.push(EdgeUseRef { face: 0, r#loop: li, position: p, upper: !u.forward }); + let pcurve = match &u.pcurve { + Some(pc) => pc.clone(), + None => { + bare.insert((0, li, p)); + // Not read: the use goes without a trim (`arrays_with_bare_uses`). + Curve2::Spline { knots: vec![edge.interval[0], edge.interval[0], edge.interval[1], edge.interval[1]], points: vec![[0.0; 2]; 2] } + } + }; + uses.push(OrientedEdge { edge: u.edge, forward: u.forward, pcurve }); + } + loops.push(Loop::Edges { edges: uses }); + } + let vertices = face.vertices.iter().map(|&point| Vertex { point, tolerance: face.tolerance }).collect(); + let record = b::Brep { + version: b::VERSION, + tolerance: face.tolerance, + regions: vec![Region { shells: vec![0], void: false }], + shells: vec![Shell::Faces { faces: vec![OrientedFace { face: 0, forward: true }], wires: Vec::new() }], + faces: vec![b::Face { surface: face.surface.clone(), nurbs: face.nurbs.cloned(), domain: face.domain, loops }], + edges, + vertices, + }; + Ok((record, bare)) +} diff --git a/crates/smlib/src/sheets.rs b/crates/smlib/src/sheets.rs new file mode 100644 index 000000000..f3d2b1b6e --- /dev/null +++ b/crates/smlib/src/sheets.rs @@ -0,0 +1,28 @@ +//! SMLib's sheet operations: sewing a body's faces along the edges that coincide, and a sheet's +//! offset along its faces' normals. Each returns a new body and leaves its input unchanged; +//! tagged inputs ([`Brep::tagged`]) give results whose [`Brep::history`] says where each face and +//! edge came from. + +use serde_json::json; + +use crate::trace; +use crate::{Brep, Result, core}; + +impl Brep { + /// The faces sewn along the vertices and edges that coincide within `tolerance` mm, oriented + /// outward where they close into a solid, else only made to agree across their shared edges; + /// with whether the result is a closed solid. + pub fn stitch(&self, tolerance: f64) -> Result<(Brep, bool)> { + let r = core::merge::stitch(self.core(), tolerance).map(|(b, closed)| (Brep::made_core(b), closed)); + trace::call("stitch", &[self], &r, |(b, _)| vec![b.id], || json!({"tolerance": tolerance})); + r + } + + /// This sheet with every face moved onto its surface's offset by `distance` along its normal + /// (negative: against it). A closed solid is [`crate::Error::Argument`]. + pub fn offset_sheet(&self, distance: f64) -> Result { + let r = core::offset::offset_sheet(self.core(), distance).map(Brep::made_core); + trace::made("offset_sheet", &[self], &r, || json!({"distance": distance})); + r + } +} diff --git a/crates/smlib/src/split.rs b/crates/smlib/src/split.rs new file mode 100644 index 000000000..7be2caeca --- /dev/null +++ b/crates/smlib/src/split.rs @@ -0,0 +1,59 @@ +//! Split Face and Split Body (`capi/include/smlib.h`, "Split"): faces cut where tool surfaces +//! meet them, and a solid cut in two by a surface. Tools are [`crate::ssi::Surface`]s, each +//! taken over its whole domain. + +use crate::ssi::Surface; +use serde_json::json; + +use crate::trace; +use crate::{Brep, Error, Result, core}; + +impl Brep { + /// `self` with faces `faces` (indices in SMLib's face order, distinct) cut where each of + /// `tools` meets them, the tools in turn, each cutting the pieces the earlier ones left; and + /// for each face how many faces it became besides itself (0: no tool split it). `None` when + /// no face is split. Tagged operands ([`Brep::tagged`]) give the pieces' history. + pub fn split_faces(&self, faces: &[usize], tools: &[&Surface]) -> Result)>> { + if faces.is_empty() || faces.len() > core::split::MAX_FACES || tools.is_empty() || tools.len() > core::split::MAX_TOOLS { + return Err(Error::Argument); + } + let specs: Vec<&crate::ssi::Spec> = tools.iter().map(|t| t.spec()).collect(); + let r = core::split::split_faces(self.core(), faces, &specs).map(|r| r.map(|(b, made)| (Brep::made_core(b), made))); + trace::call( + "split_faces", + &[self], + &r, + |o| o.iter().map(|(b, _)| b.id).collect(), + || json!({"faces": faces, "tools": specs.iter().map(|s| trace::surface(s)).collect::>()}), + ); + r + } + + /// The manifold solid `self` cut in two by `tool` (whose domain must reach past it): the + /// part behind the surface (its normal points away) and the part in front, each closed by + /// the tool's piece inside the body and each possibly several solids. A tool that misses + /// leaves both parts the whole body, with no face from the tool (tag `self` to tell); `None` + /// when a side is left empty. + pub fn split_body(&self, tool: &Surface) -> Result> { + let r = core::split::split_body(self.core(), tool.spec()).map(|r| r.map(|(b, f)| (Brep::made_core(b), Brep::made_core(f)))); + trace::call( + "split_body", + &[self], + &r, + |o| o.iter().flat_map(|(b, f)| [b.id, f.id]).collect(), + || json!({"tool": trace::surface(tool.spec())}), + ); + r + } + + /// The manifold solid `self` cut in two by the sheet `sheet` as it is (its faces joined edge + /// to edge; it must cross the body to cut it), as [`Brep::split_body`] cuts it: its faces' + /// surfaces turned to agree with face `face`'s (in SMLib's face order), the part behind that + /// normal and the part in front. A `sheet` that is no sheet, or a `face` it does not have, is + /// [`Error::Argument`]. + pub fn split_body_by_sheet(&self, sheet: &Brep, face: usize) -> Result> { + let r = core::split::split_body_by_sheet(self.core(), sheet.core(), face).map(|r| r.map(|(b, f)| (Brep::made_core(b), Brep::made_core(f)))); + trace::call("split_body_by_sheet", &[self, sheet], &r, |o| o.iter().flat_map(|(b, f)| [b.id, f.id]).collect(), || json!({"face": face})); + r + } +} diff --git a/crates/smlib/src/ssi.rs b/crates/smlib/src/ssi.rs new file mode 100644 index 000000000..99ee64397 --- /dev/null +++ b/crates/smlib/src/ssi.rs @@ -0,0 +1,418 @@ +//! Surface/surface intersection (`capi/include/smlib.h`, "Surface/surface intersection"): two +//! surfaces described in plain numbers, intersected by one of SMLib's SSI entry points, each +//! intersection curve exactly as SMLib holds it: schema 4 B-splines (`solidcraft_geom::brep`). +//! +//! The constructors take exactly the fields of an SSI corpus case (`tests/ssi-corpus`), angles in +//! degrees. Each surface's UV domain is SMLib's natural one ([`Surface::domain`]): (u, v) itself +//! for planes, the parameterisation of SMLib's internal NURBS form for the other analytic kinds. + +use solidcore_record::brep as b; + +use std::sync::OnceLock; + +use crate::{Error, Result}; + +/// A surface with its UV domain: the description it was made from, from which solidcore makes its +/// own ([`crate::core::split`]). +pub struct Surface { + /// solidcore's, made when it is first needed. + core: OnceLock>, + spec: Spec, +} + +/// What a [`Surface`] was made from: its constructor's arguments, checked as the C API checks them +/// ([`Spec::check`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Spec { + Plane { origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], u: [f64; 2], v: [f64; 2] }, + Cylinder { origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, angle_deg: [f64; 2], height: [f64; 2] }, + Cone { apex: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], half_angle_deg: f64, height: [f64; 2] }, + Sphere { center: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, lon_deg: [f64; 2], lat_deg: [f64; 2] }, + Torus { center: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], major_radius: f64, minor_radius: f64, major_deg: [f64; 2], minor_deg: [f64; 2] }, + Nurbs { degree: [usize; 2], nu: usize, nv: usize, knots_u: Vec, knots_v: Vec, points: Vec<[f64; 3]>, weights: Option> }, +} + +impl std::fmt::Debug for Surface { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("smlib::ssi::Surface") + } +} + +/// The largest coordinate, degree and control net a surface may have (`SMLIB_SURFACE_MAX_*`). +const MAX_COORD: f64 = 1e8; +const MAX_DEGREE: usize = 25; +const MAX_POLES: usize = 1_000_000; + +fn bounded(v: &[f64]) -> bool { + v.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) +} + +/// Two non-zero axes that are not (nearly) parallel. +fn axes(x: &[f64; 3], y: &[f64; 3]) -> bool { + let len = |a: &[f64; 3]| (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt(); + let c = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]]; + bounded(x) && bounded(y) && len(x) > 1e-12 && len(y) > 1e-12 && len(&c) > 1e-9 * len(x) * len(y) +} + +/// An increasing interval inside `[lo, hi]` spanning at most `span`. +fn range(r: &[f64; 2], lo: f64, hi: f64, span: f64) -> bool { + bounded(r) && r[0] < r[1] && r[0] >= lo && r[1] <= hi && r[1] - r[0] <= span +} + +fn length(x: f64) -> bool { + x.is_finite() && x > 1e-9 && x <= MAX_COORD +} + +/// A knot vector of n + p + 1 non-decreasing values with a non-empty domain `[k[p], k[n]]`, no +/// interior knot repeated more than p times and no end knot more than p + 1. +fn knots(k: &[f64], n: usize, p: usize) -> bool { + if k.len() != n + p + 1 || !bounded(k) || k.windows(2).any(|w| w[1] < w[0]) { + return false; + } + let (Some(lo), Some(hi)) = (k.get(p).copied(), k.get(n).copied()) else { return false }; + let mut run = 1; + for w in k.windows(2) { + run = if w[1] == w[0] { run + 1 } else { 1 }; + if run > p + 1 || (run > p && w[1] > lo && w[1] < hi) { + return false; + } + } + lo < hi +} + +impl Spec { + /// The checks each of the C API's constructors makes of its arguments, so that a surface is + /// refused before solidcore sees it. + fn check(&self) -> Result<()> { + let whole = |r: &[f64; 2]| range(r, -MAX_COORD, MAX_COORD, 2.0 * MAX_COORD); + let turn = |r: &[f64; 2]| range(r, -360.0, 360.0, 360.0); + let ok = match self { + Spec::Plane { origin, xaxis, yaxis, u, v } => bounded(origin) && axes(xaxis, yaxis) && whole(u) && whole(v), + Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height } => { + bounded(origin) && axes(xaxis, yaxis) && length(*radius) && turn(angle_deg) && range(height, -MAX_COORD, MAX_COORD, MAX_COORD) + } + Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height } => { + bounded(apex) + && axes(xaxis, yaxis) + && (0.01..=89.0).contains(half_angle_deg) + && range(height, 0.0, MAX_COORD, MAX_COORD) + && height[1] - height[0] > 1e-9 + } + Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg } => { + bounded(center) && axes(xaxis, yaxis) && length(*radius) && turn(lon_deg) && range(lat_deg, -90.0, 90.0, 180.0) + } + Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg } => { + bounded(center) + && axes(xaxis, yaxis) + && length(*major_radius) + && length(*minor_radius) + && minor_radius < major_radius + && turn(major_deg) + && turn(minor_deg) + } + Spec::Nurbs { degree: [p, q], nu, nv, knots_u, knots_v, points, weights } => { + (1..=MAX_DEGREE).contains(p) + && (1..=MAX_DEGREE).contains(q) + && *nu > *p + && *nv > *q + && nu.checked_mul(*nv).is_some_and(|n| n <= MAX_POLES && points.len() == n) + && knots(knots_u, *nu, *p) + && knots(knots_v, *nv, *q) + && points.iter().all(|c| bounded(c)) + && weights.as_ref().is_none_or(|w| w.len() == points.len() && w.iter().all(|x| (1e-6..=1e6).contains(x))) + } + }; + if ok { Ok(()) } else { Err(Error::Argument) } + } +} + +impl Surface { + /// solidcore's surface, made the first time it is needed. + fn core(&self) -> Result<&crate::core::split::Tool> { + self.core.get_or_init(|| crate::core::ssi::surface(&self.spec)).as_ref().map_err(Clone::clone) + } + + pub(crate) fn spec(&self) -> &Spec { + &self.spec + } + + /// A surface from its checked description. + fn made(spec: Spec) -> Result { + spec.check()?; + Ok(Surface { core: OnceLock::new(), spec }) + } + + /// `origin + u*x + v*y` (x, y the axes made unit), for u in `u`, v in `v`. + pub fn plane(origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], u: [f64; 2], v: [f64; 2]) -> Result { + Surface::made(Spec::Plane { origin, xaxis, yaxis, u, v }) + } + + /// A cylinder of `radius` about the axis through `origin` along `xaxis × yaxis`, angle + /// `angle_deg` from `xaxis` towards `yaxis`, for heights `height` measured from `origin`. + pub fn cylinder(origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, angle_deg: [f64; 2], height: [f64; 2]) -> Result { + Surface::made(Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height }) + } + + /// A full cone with its apex at `apex` along `xaxis × yaxis`, radius `h * tan(half_angle_deg)` + /// at distance h along the axis, for h in `height` (from 0: through the apex). + pub fn cone(apex: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], half_angle_deg: f64, height: [f64; 2]) -> Result { + Surface::made(Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height }) + } + + /// A sphere of `radius` at `center`, over longitudes `lon_deg` and latitudes `lat_deg`. + pub fn sphere(center: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, lon_deg: [f64; 2], lat_deg: [f64; 2]) -> Result { + Surface::made(Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg }) + } + + /// A ring torus at `center` about `xaxis × yaxis`, `major_deg` round the axis and `minor_deg` + /// round the tube. + pub fn torus( + center: [f64; 3], + xaxis: [f64; 3], + yaxis: [f64; 3], + major_radius: f64, + minor_radius: f64, + major_deg: [f64; 2], + minor_deg: [f64; 2], + ) -> Result { + Surface::made(Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg }) + } + + /// A (rational) B-spline surface: `nu × nv` control points, point (i, j) (i along u) at + /// `points[i * nv + j]`; `weights` likewise, or `None` for all 1. + pub fn nurbs( + degree: [usize; 2], + nu: usize, + nv: usize, + knots_u: &[f64], + knots_v: &[f64], + points: &[[f64; 3]], + weights: Option<&[f64]>, + ) -> Result { + Surface::made(Spec::Nurbs { + degree, + nu, + nv, + knots_u: knots_u.to_vec(), + knots_v: knots_v.to_vec(), + points: points.to_vec(), + weights: weights.map(<[f64]>::to_vec), + }) + } + + /// A schema 4 record surface over the parameter box `domain` (`[[u0, u1], [v0, v1]]`, the + /// record's own parameters: radians for angles), with the record's parameterisation and + /// normal. A spline is taken over its whole knot domain. A cone only as a whole turn, widening + /// along its axis; a revolution not at all ([`Error::Unsupported`]). + pub fn from_record(surface: &solidcore_record::brep::Surface, domain: [[f64; 2]; 2]) -> Result { + use solidcore_record::brep::Surface as S; + let [u, v] = domain; + let deg = |r: [f64; 2]| r.map(f64::to_degrees); + let sub = |a: [f64; 3], b: [f64; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + let len = |a: [f64; 3]| (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt(); + let cross = |a: [f64; 3], b: [f64; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + // SMLib's plane runs along its axes made unit: the record's parameters scale by their lengths. + let plane = |origin: [f64; 3], du: [f64; 3], dv: [f64; 3]| { + let (a, b) = (len(du), len(dv)); + Surface::plane(origin, du, dv, [u[0] * a, u[1] * a], [v[0] * b, v[1] * b]) + }; + match surface { + S::Plane { origin, u_axis, v_axis } => plane(*origin, *u_axis, *v_axis), + S::PlaneThrough { origin, u_point, v_point } => plane(*origin, sub(*u_point, *origin), sub(*v_point, *origin)), + S::Cylinder { frame, radius } => Surface::cylinder(frame.origin, frame.x_axis, frame.y_axis, *radius, deg(u), v), + S::Cone { frame, radius_at_origin, half_angle } => { + let t = half_angle.tan(); + if !(t > 0.0) || !(u[1] - u[0] >= std::f64::consts::TAU * (1.0 - 1e-12)) { + return Err(Error::Unsupported); + } + // The apex lies where the radius is 0; heights run from it along the axis. + let at = -radius_at_origin / t; + let z = cross(frame.x_axis, frame.y_axis); + let apex = [0, 1, 2].map(|k| frame.origin[k] + z[k] * at); + Surface::cone(apex, frame.x_axis, frame.y_axis, half_angle.to_degrees(), [(v[0] - at).max(0.0), v[1] - at]) + } + S::Sphere { frame, radius } => Surface::sphere(frame.origin, frame.x_axis, frame.y_axis, *radius, deg(u), deg(v)), + S::Torus { frame, major_radius, minor_radius, tube_start } => { + // SMLib's tube angle counts from the outer equator. + Surface::torus(frame.origin, frame.x_axis, frame.y_axis, *major_radius, *minor_radius, deg(u), deg(v.map(|a| a + tube_start))) + } + S::Spline { u_knots, v_knots, points } => { + let (nu, nv) = (points.len(), points.first().map_or(0, Vec::len)); + let flat: Vec<[f64; 3]> = points.iter().flatten().copied().collect(); + let degree = [u_knots.len().checked_sub(nu + 1).ok_or(Error::Argument)?, v_knots.len().checked_sub(nv + 1).ok_or(Error::Argument)?]; + Surface::nurbs(degree, nu, nv, u_knots, v_knots, &flat, None) + } + S::RationalSpline { u_knots, v_knots, homogeneous } => { + let (nu, nv) = (homogeneous.len(), homogeneous.first().map_or(0, Vec::len)); + let all: Vec<[f64; 4]> = homogeneous.iter().flatten().copied().collect(); + let flat: Vec<[f64; 3]> = all.iter().map(|h| [h[0] / h[3], h[1] / h[3], h[2] / h[3]]).collect(); + let weights: Vec = all.iter().map(|h| h[3]).collect(); + let degree = [u_knots.len().checked_sub(nu + 1).ok_or(Error::Argument)?, v_knots.len().checked_sub(nv + 1).ok_or(Error::Argument)?]; + Surface::nurbs(degree, nu, nv, u_knots, v_knots, &flat, Some(&weights)) + } + // A ball patch's label has no (u, v): its face's NURBS form is the surface. + S::PlacedRevolution { .. } | S::BallPatch { .. } => Err(Error::Unsupported), + } + } + + /// The UV domain the intersection runs within, as `[u0, u1, v0, v1]`. + pub fn domain(&self) -> Result<[f64; 4]> { + self.core().map(crate::core::ssi::domain) + } + + /// The surface's point at (u, v). + pub fn evaluate(&self, u: f64, v: f64) -> Result<[f64; 3]> { + crate::core::ssi::evaluate(self.core()?, u, v) + } +} + +/// Which of SMLib's intersectors runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Method { + /// `SmSurface::GlobalSurfaceIntersect`: analytic special cases, else [`Method::Advanced`]. + Global, + /// `SmAdvSurfaceIntersector`, the general NURBS path. + Advanced, +} + +/// A curve's type, SMLib's `SmTsectCurveType`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CurveType { + /// The method reported no type. + None, + Unknown, + /// Degenerate: one point where the surfaces touch. + Touching, + /// Transversal. + Crossing, + /// The surfaces are tangent along it. + Tangent, + /// Where the surfaces butt up against each other. + Coincident, + /// A small angle of intersection. + NearTangent, + /// Bounds a region where the surfaces coincide. + RegionBoundary, +} + +/// One intersection curve as SMLib returned it: its 3D curve and, where the method returned +/// them, its curves in each surface's UV, each the (rational) B-spline SMLib holds (its lines, +/// circles and ellipses are B-splines too; an intersection curve one SMLib fitted within the +/// approximation tolerance). +#[derive(Clone, Debug)] +pub struct SsiCurve { + pub curve_type: CurveType, + /// SMLib's deviation estimate (NaN: none). + pub deviation: f64, + /// The 3D curve's natural parameter interval. + pub interval: [f64; 2], + pub curve: b::Curve, + /// On surface a, in a's UV. + pub uv_a: Option, + /// On surface b, in b's UV. + pub uv_b: Option, +} + +/// An isolated point: where a [`CurveType::Touching`] curve starts. +#[derive(Clone, Copy, Debug)] +pub struct SsiPoint { + pub xyz: [f64; 3], + pub uv_a: [f64; 2], + pub uv_b: [f64; 2], +} + +/// What an intersection found. +#[derive(Clone, Debug, Default)] +pub struct SsiResult { + pub curves: Vec, + pub points: Vec, +} + +/// A (rational) B-spline's coordinates, weights and knots, as the capi hands an intersection curve +/// out: `points` 3 (or 2, in UV) reals each. +pub(crate) struct Nurbs { + pub points: Vec, + pub weights: Vec, + pub knots: Vec, +} + +/// The 3D B-spline: polynomial where every weight is 1. +pub(crate) fn curve3(c: Nurbs) -> b::Curve { + let points = c.points.as_chunks::<3>().0; + if c.weights.iter().all(|w| *w == 1.0) { + b::Curve::Spline { knots: c.knots, points: points.to_vec() } + } else { + b::Curve::RationalSpline { + knots: c.knots, + homogeneous: points.iter().zip(&c.weights).map(|(p, w)| [p[0] * w, p[1] * w, p[2] * w, *w]).collect(), + } + } +} + +/// A UV B-spline, as [`curve3`]. +pub(crate) fn curve2(c: Nurbs) -> b::Curve2 { + let points = c.points.as_chunks::<2>().0; + if c.weights.iter().all(|w| *w == 1.0) { + b::Curve2::Spline { knots: c.knots, points: points.to_vec() } + } else { + b::Curve2::RationalSpline { knots: c.knots, homogeneous: points.iter().zip(&c.weights).map(|(p, w)| [p[0] * w, p[1] * w, *w]).collect() } + } +} + +/// Intersects `a` and `b` within their domains with `method` at approximation tolerance +/// `approx_tol` (<= 0: SMLib's default, 1/1000 of the surfaces' size). An intersector failure is +/// SMLib's status; a curve SMLib does not hold as a B-spline is [`Error::Unsupported`]. +pub fn intersect(a: &Surface, b: &Surface, method: Method, approx_tol: f64) -> Result { + crate::core::ssi::intersect(a.core()?, b.core()?, method, approx_tol) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Refused here, before solidcore sees the surface. + #[test] + fn bad_input_is_an_argument_error() { + let (x, y) = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]); + let refused = [ + Surface::plane([0.0; 3], x, x, [0.0, 1.0], [0.0, 1.0]), + Surface::plane([0.0; 3], x, y, [1.0, 0.0], [0.0, 1.0]), + Surface::plane([f64::NAN; 3], x, y, [0.0, 1.0], [0.0, 1.0]), + Surface::cylinder([0.0; 3], x, y, 0.0, [0.0, 360.0], [0.0, 1.0]), + Surface::cone([0.0; 3], x, y, f64::NAN, [0.0, 1.0]), + Surface::sphere([0.0; 3], x, y, 1.0, [0.0, 360.0], [-91.0, 90.0]), + Surface::torus([0.0; 3], x, y, 1.0, 2.0, [0.0, 360.0], [0.0, 360.0]), + Surface::nurbs([1, 1], 2, 2, &[0.0, 0.0, 1.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 3], None), + Surface::nurbs([1, 1], 2, 2, &[0.0, 0.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 4], None), + Surface::nurbs([1, 1], 2, 2, &[0.0, 0.0, 1.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 4], Some(&[0.0; 4])), + Surface::nurbs([0, 1], 2, 2, &[0.0, 0.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 4], None), + ]; + for (i, r) in refused.iter().enumerate() { + assert_eq!(r.as_ref().err(), Some(&Error::Argument), "{i}"); + } + } + + /// A plane's domain and points are its own parameters; a plane through a sphere's centre meets + /// it in one great circle, by either method. + #[test] + fn a_plane_through_a_spheres_centre_is_a_great_circle() { + let (x, y, z) = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]); + let plane = Surface::plane([0.0; 3], x, y, [-2.0, 2.0], [-3.0, 3.0]).unwrap(); + assert_eq!(plane.domain().unwrap(), [-2.0, 2.0, -3.0, 3.0]); + assert_eq!(plane.evaluate(1.0, -2.0).unwrap(), [1.0, -2.0, 0.0]); + assert_eq!(plane.evaluate(f64::NAN, 0.0).unwrap_err(), Error::Argument); + let sphere = Surface::sphere([0.0; 3], x, z, 1.0, [0.0, 360.0], [-90.0, 90.0]).unwrap(); + for method in [Method::Global, Method::Advanced] { + let r = intersect(&plane, &sphere, method, 1e-6).unwrap(); + assert!(!r.curves.is_empty(), "{method:?}"); + for c in &r.curves { + let eval = solidcraft_geom::brep::eval::CurveEval::new(&c.curve).unwrap(); + let [t0, t1] = c.interval; + for k in 0..=100 { + let p = eval.point(t0 + (t1 - t0) * f64::from(k) / 100.0).unwrap(); + assert!((p.x.hypot(p.y) - 1.0).abs() < 1e-5 && p.z.abs() < 1e-5, "{method:?}: {p:?}"); + } + } + } + } +} diff --git a/crates/smlib/src/sweeps.rs b/crates/smlib/src/sweeps.rs new file mode 100644 index 000000000..8f7b01891 --- /dev/null +++ b/crates/smlib/src/sweeps.rs @@ -0,0 +1,294 @@ +//! SMLib's sweeps: extrusion (straight or drafted), revolution, sweep along a path, loft through +//! sections or to a point, the screw sweep of a thread or coil, and the sweep of a profile placed +//! at stations (one that twists, scales or follows guide rails along its path). Profiles, paths and +//! sections are lists of [`Curve`]s; each sweep returns a new body. +//! +//! With `cap`, the profile's loops close the ends and the result must be a closed manifold solid +//! ([`Error::NotSolid`] otherwise); without, it is the swept sheet. + +use serde_json::json; + +use crate::trace; +use crate::{Brep, Result, core}; + +/// A 3D curve of a profile, path or section. +#[derive(Clone, Debug, PartialEq)] +pub enum Curve { + Line { + start: [f64; 3], + end: [f64; 3], + }, + /// Counter-clockwise about the unit `axis` from angle `start` to `end` (radians, + /// 0 < end - start <= 2 pi), angle 0 along the unit `reference` (square to `axis`). + Arc { + center: [f64; 3], + axis: [f64; 3], + reference: [f64; 3], + radius: f64, + start: f64, + end: f64, + }, + /// Control points (x, y, z, weight > 0) and the clamped knot vector (points + degree + 1 + /// knots). + Nurbs { + degree: usize, + points: Vec<[f64; 4]>, + knots: Vec, + }, +} + +/// How a drafted [`Brep::extrude`] closes the gap its offset opens at a sharp corner of the +/// profile. Where the offsets overlap instead, all three trim them where they cross. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum DraftCorner { + /// Each wall continues as itself (a line's plane, an arc's cone) until it meets its + /// neighbour: every section is the profile's curves offset and continued as themselves. + #[default] + Curvature, + /// Each offset curve continues straight along its end tangent: a flat face each side. + Tangent, + /// An arc about the corner: a cone about it. + Round, +} + +/// Why [`DraftCorner::Curvature`] could not close a corner ([`Error::Corner`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CornerRefusal { + /// The continued curves do not meet (two parallel lines, two circles that part). + Apart, + /// A wall closes before the far end: its neighbours meet across it, or its arc shrinks to its + /// centre. + WallCloses, + /// A curve there is neither a line nor an arc: its wall has no exact continuation. + NotExact, +} + +/// How the profile is carried along a [`Brep::sweep`] path. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SweepFrame { + /// It turns with the path, keeping its attitude to the path's tangent. + Follow, + /// It only moves along the path, keeping its orientation. + Translate, +} + +/// How the ends of a [`Brep::sweep_stations`] close. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ends { + /// Left open: the swept sheet. + Open, + /// Capped by the first and last sections: a closed solid. + Capped, + /// Joined: the last section lies on the first (a sweep round a closed path), the walls' ends + /// glued to their starts into a closed solid. + Joined, +} + +/// An affine map of a [`Brep::sweep_stations`] station: a point `x` goes to `m · x + t`, `m` +/// given by its columns. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Affine { + pub m: [[f64; 3]; 3], + pub t: [f64; 3], +} + +/// Most stations of one [`Brep::sweep_stations`]. +pub const MAX_STATIONS: usize = 4096; +/// Most profile curves times stations of one [`Brep::sweep_stations`]. +pub const MAX_STATION_CURVES: usize = 400_000; + +/// Most curves one list may hold. +pub const MAX_CURVES: usize = 16_384; +/// Highest degree of a [`Curve::Nurbs`]. +pub(crate) const CURVE_MAX_DEGREE: usize = 25; +/// Most control points of a [`Curve::Nurbs`]. +pub(crate) const CURVE_MAX_POINTS: usize = 100_000; + +impl Brep { + /// A sheet of planar faces bounded by `loops`: closed loops of curves in one plane, in any + /// order, nested as outer loops, their holes and islands in the holes. + pub fn planar_faces(loops: &[Curve]) -> Result { + let r = core::sweep::planar_faces(loops).map(Brep::made_core); + trace::made("planar_faces", &[], &r, || json!({"loops": trace::curves(loops)})); + r + } + + /// The planar `profile` extruded `distance` along the unit `direction` (square to its plane). + /// `draft` (radians) leans the walls: positive inward, negative outward; a drafted profile is + /// one closed loop, its curves in order, and `direction` is its normal (either way round). + /// `corner` closes a drafted profile's sharp corners; a corner it cannot close is + /// [`Error::Corner`] (with [`CornerRefusal::NotExact`] where, under + /// [`DraftCorner::Curvature`], a curve of a profile with a sharp corner is neither a line nor + /// an arc). + pub fn extrude(profile: &[Curve], direction: [f64; 3], distance: f64, draft: f64, corner: DraftCorner, cap: bool) -> Result { + let r = core::sweep::extrude(profile, direction, distance, draft, corner, cap).map(Brep::made_core); + trace::made("extrude", &[], &r, || { + let corner = match corner { + DraftCorner::Curvature => "curvature", + DraftCorner::Tangent => "tangent", + DraftCorner::Round => "round", + }; + json!({"profile": trace::curves(profile), "direction": direction, "distance": distance, "draft": draft, "corner": corner, "cap": cap}) + }); + r + } + + /// The planar `profile` turned `angle` radians (0 < angle <= 2 pi) right-handed about the + /// axis through `origin` along `direction`, in the profile's plane (touching it at most). + pub fn revolve(profile: &[Curve], origin: [f64; 3], direction: [f64; 3], angle: f64, cap: bool) -> Result { + let r = core::sweep::revolve(profile, origin, direction, angle, cap).map(Brep::made_core); + trace::made( + "revolve", + &[], + &r, + || json!({"profile": trace::curves(profile), "origin": origin, "direction": direction, "angle": angle, "cap": cap}), + ); + r + } + + /// `profile` swept along `path` (end-to-end curves), carried with the path's start: the + /// profile keeps its place relative to it. The walls are B-spline approximations, one per + /// stretch of profile between tangent breaks. + pub fn sweep(profile: &[Curve], path: &[Curve], frame: SweepFrame, cap: bool) -> Result { + let r = core::sweep::sweep_placed(profile, path, frame, cap).map(|(b, _)| Brep::made_core(b)); + trace::made( + "sweep", + &[], + &r, + || json!({"profile": trace::curves(profile), "path": trace::curves(path), "frame": frame_word(frame), "cap": cap}), + ); + r + } + + /// [`Brep::sweep`], with where the sweep placed the profile: the rigid motions carrying the + /// profile as given onto its first section, a section about half way along and its last + /// section. Only the sweep knows them (the curve sweep turns the profile on a frame it works + /// out from point to point along the path); a sweep that carries on from where this one left + /// the profile starts from the last. + pub fn sweep_placed(profile: &[Curve], path: &[Curve], frame: SweepFrame, cap: bool) -> Result<(Brep, [Affine; 3])> { + let r = core::sweep::sweep_placed(profile, path, frame, cap).map(|(b, m)| (Brep::made_core(b), m)); + trace::call( + "sweep", + &[], + &r, + |(b, _)| vec![b.id], + || json!({"profile": trace::curves(profile), "path": trace::curves(path), "frame": frame_word(frame), "cap": cap}), + ); + r + } + + /// The `curves` projected along `direction` (pointing from them toward the face) onto the + /// face nearest `face_point` (within `pick_tolerance`; [`Error::NoMatch`] or + /// [`Error::Ambiguous`] otherwise): SMLib's parallel projection onto the face's surface, + /// trimmed to the face, each curve within `tolerance` of the true projection, as the NURBS + /// SMLib made with its interval. No projection at all is [`Error::Empty`]. + pub fn project_curves( + &self, + face_point: [f64; 3], + pick_tolerance: f64, + curves: &[Curve], + direction: [f64; 3], + tolerance: f64, + ) -> Result> { + core::sweep::project_curves(self.core(), face_point, pick_tolerance, curves, direction, tolerance) + } + + /// The section of the face nearest `face_point` by the plane through `plane_point` square to + /// `plane_normal`, as the NURBS SMLib made with their intervals. None is [`Error::Empty`]. + pub fn face_section( + &self, + face_point: [f64; 3], + pick_tolerance: f64, + plane_point: [f64; 3], + plane_normal: [f64; 3], + tolerance: f64, + ) -> Result> { + core::sweep::face_section(self.core(), face_point, pick_tolerance, plane_point, plane_normal, tolerance) + } + + /// A loft (skin) through `sections` (at least two closed loops), `degree` (1 ruled, 2 or 3) + /// across them. + pub fn loft(sections: &[Vec], degree: u32, cap: bool) -> Result { + let r = core::sweep::loft(sections, degree, cap).map(Brep::made_core); + trace::made( + "loft", + &[], + &r, + || json!({"sections": sections.iter().map(|s| trace::curves(s)).collect::>(), "degree": degree, "cap": cap}), + ); + r + } + + /// The planar `profile` placed by each of `stations` in turn (2…[`MAX_STATIONS`], each + /// section exactly the profile's image), its walls skinned through the sections, cubic + /// across them: one wall per profile curve. `ends` says how the ends close. + pub fn sweep_stations(profile: &[Curve], stations: &[Affine], ends: Ends) -> Result { + let r = core::sweep::sweep_stations(profile, stations, ends).map(Brep::made_core); + trace::made("sweep_stations", &[], &r, || { + let ends = match ends { + Ends::Open => "open", + Ends::Capped => "capped", + Ends::Joined => "joined", + }; + json!({"profile": trace::curves(profile), "stations": stations.iter().map(trace::affine).collect::>(), "ends": ends}) + }); + r + } + + /// A loft from the planar `section` (one closed loop of lines, in order) to the point `apex` + /// off its plane: a pyramid, its base the section and a triangle on each line. + pub fn loft_to_point(section: &[Curve], apex: [f64; 3]) -> Result { + let r = core::sweep::loft_to_point(section, apex).map(Brep::made_core); + trace::made("loft_to_point", &[], &r, || json!({"section": trace::curves(section), "apex": apex})); + r + } + + /// `profile` carried by a screw motion about the axis through `origin` along `direction`: + /// `turns` right-handed turns about it, rising `pitch` (signed) per turn, capped at both ends, + /// its walls within about `tolerance` of the true screw surfaces. + pub fn screw_sweep(profile: &[Curve], origin: [f64; 3], direction: [f64; 3], pitch: f64, turns: f64, tolerance: f64) -> Result { + let r = core::sweep::screw_sweep(profile, origin, direction, pitch, turns, None, tolerance).map(Brep::made_core); + trace::made( + "screw_sweep", + &[], + &r, + || json!({"profile": trace::curves(profile), "origin": origin, "direction": direction, "pitch": pitch, "turns": turns, "tolerance": tolerance}), + ); + r + } + + /// [`screw_sweep`](Self::screw_sweep) with the profile moved off the axis as it turns: at turn + /// t every point of it first moves `offset(t)` mm away from the axis (negative: towards it) + /// in its half-plane, `offset` piecewise linear through the `(turn, offset)` pairs of `law` + /// (turns strictly ascending within [0, `turns`], held before the first and after the last). + /// A thread's groove fading in or out over a runout, or a taper. The profile must lie in a + /// half-plane bounded by the axis. + pub fn screw_sweep_radial( + profile: &[Curve], + origin: [f64; 3], + direction: [f64; 3], + pitch: f64, + turns: f64, + law: &[(f64, f64)], + tolerance: f64, + ) -> Result { + let r = core::sweep::screw_sweep(profile, origin, direction, pitch, turns, Some(law), tolerance).map(Brep::made_core); + trace::made("screw_sweep", &[], &r, || { + json!({"profile": trace::curves(profile), "origin": origin, "direction": direction, "pitch": pitch, "turns": turns, + "law": law, "tolerance": tolerance}) + }); + r + } +} + +/// A sweep frame's name in a trace. +fn frame_word(f: SweepFrame) -> &'static str { + match f { + SweepFrame::Follow => "follow", + SweepFrame::Translate => "translate", + } +} + +#[cfg(test)] +#[path = "sweeps_tests.rs"] +mod tests; diff --git a/crates/smlib/src/sweeps_tests.rs b/crates/smlib/src/sweeps_tests.rs new file mode 100644 index 000000000..34e3971cd --- /dev/null +++ b/crates/smlib/src/sweeps_tests.rs @@ -0,0 +1,145 @@ +//! The sweeps against analytic volumes, each result a valid closed solid. + +use std::f64::consts::{PI, TAU}; + +use super::*; +use crate::{CheckLevel, Error}; + +fn solid_volume(b: &Brep, what: &str) -> f64 { + let report = b.check(CheckLevel::All).unwrap(); + assert!(report.is_valid(), "{what}: {} failed validity tests:\n{}", report.failures, report.text); + b.volume(1e-7).unwrap() +} + +fn assert_close(got: f64, want: f64, rel: f64, what: &str) { + assert!((got - want).abs() <= rel * want.abs(), "{what}: {got} vs analytic {want}"); +} + +fn polygon(pts: &[[f64; 3]]) -> Vec { + (0..pts.len()).map(|i| Curve::Line { start: pts[i], end: pts[(i + 1) % pts.len()] }).collect() +} + +fn circle(center: [f64; 3], radius: f64) -> Curve { + Curve::Arc { center, axis: [0.0, 0.0, 1.0], reference: [1.0, 0.0, 0.0], radius, start: 0.0, end: TAU } +} + +#[test] +fn extrusions_straight_and_drafted() { + let rect = polygon(&[[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 6.0, 0.0], [0.0, 6.0, 0.0]]); + let b = Brep::extrude(&rect, [0.0, 0.0, 1.0], 5.0, 0.0, DraftCorner::default(), true).unwrap(); + assert_close(solid_volume(&b, "prism"), 300.0, 1e-9, "prism"); + // A disc drafted 5 degrees in over 4 mm: a frustum of radii 5 and 5 - 4 tan 5. + let r2 = 5.0 - 4.0 * 5f64.to_radians().tan(); + let b = Brep::extrude(&[circle([0.0; 3], 5.0)], [0.0, 0.0, 1.0], 4.0, 5f64.to_radians(), DraftCorner::default(), true).unwrap(); + assert_close(solid_volume(&b, "frustum"), PI * 4.0 / 3.0 * (25.0 + r2 * r2 + 5.0 * r2), 1e-6, "drafted disc"); +} + +#[test] +fn revolutions_whole_and_partial() { + // A half disc on the z axis, in the xz plane: a sphere; a quarter turn of a square off it. + let half = vec![ + Curve::Line { start: [0.0, 0.0, -5.0], end: [0.0, 0.0, 5.0] }, + Curve::Arc { center: [0.0; 3], axis: [0.0, -1.0, 0.0], reference: [0.0, 0.0, 1.0], radius: 5.0, start: 0.0, end: PI }, + ]; + let b = Brep::revolve(&half, [0.0; 3], [0.0, 0.0, 1.0], TAU, true).unwrap(); + assert_close(solid_volume(&b, "sphere"), 4.0 / 3.0 * PI * 125.0, 1e-5, "sphere"); + let sq = polygon(&[[6.0, 0.0, 0.0], [8.0, 0.0, 0.0], [8.0, 0.0, 2.0], [6.0, 0.0, 2.0]]); + let b = Brep::revolve(&sq, [0.0; 3], [0.0, 0.0, 1.0], PI / 2.0, true).unwrap(); + assert_close(solid_volume(&b, "quarter ring"), PI / 2.0 * 7.0 * 4.0, 1e-6, "quarter ring"); +} + +/// A half disc of radius 14 centred 14 off the axis, its rim outward, three quarters of a turn +/// (rig sweeps/4007): a horn torus, which SMLib gives a major radius a rounding below its minor. +/// The record's torus is a ring torus, so the face comes out as its NURBS form, unlabelled, and +/// the record validates. Pappus: 3/4 turn · 2π (14 + 4·14 / 3π) · π 14² / 2. +#[test] +fn a_horn_torus_comes_out_as_its_nurbs() { + let half = vec![ + Curve::Arc { center: [14.0, 0.0, 0.0], axis: [0.0, -1.0, 0.0], reference: [1.0, 0.0, 0.0], radius: 14.0, start: -PI / 2.0, end: PI / 2.0 }, + Curve::Line { start: [14.0, 0.0, 14.0], end: [14.0, 0.0, -14.0] }, + ]; + let b = Brep::revolve(&half, [0.0; 3], [0.0, 0.0, 1.0], 1.5 * PI, true).unwrap(); + let want = 1.5 * PI * (14.0 + 56.0 / (3.0 * PI)) * PI * 98.0; + assert_close(solid_volume(&b, "horn torus"), want, 1e-6, "horn torus"); + let record = b.to_native().unwrap(); + solidcraft_geom::brep::check::validate(&record).unwrap(); + assert!(record.faces.iter().all(|f| !matches!(f.surface, solidcore_record::brep::Surface::Torus { .. })), "a torus label on a horn torus"); +} + +#[test] +fn sweeps_lofts_and_screws() { + let disc = [circle([5.0, 0.0, 0.0], 2.0)]; + let bend = + [Curve::Arc { center: [-20.0, 0.0, 0.0], axis: [0.0, -1.0, 0.0], reference: [1.0, 0.0, 0.0], radius: 20.0, start: 0.0, end: PI / 2.0 }]; + // The disc keeps its 5 mm offset from the path: Pappus about the arc's centre at 25. + let b = Brep::sweep(&disc, &bend, SweepFrame::Follow, true).unwrap(); + assert_close(solid_volume(&b, "bent tube"), PI * 4.0 * (PI / 2.0 * 25.0), 1e-4, "bent tube"); + let sections = vec![vec![circle([0.0; 3], 5.0)], vec![circle([0.0, 0.0, 6.0], 3.0)]]; + let b = Brep::loft(§ions, 1, true).unwrap(); + assert_close(solid_volume(&b, "frustum"), PI * 2.0 * (25.0 + 9.0 + 15.0), 1e-5, "lofted frustum"); + // A ring lofted to a ring: the outline and the hole are one section, lofted loop to loop. + let ring = |z: f64| { + let hole = Curve::Arc { center: [0.0, 0.0, z], axis: [0.0, 0.0, -1.0], reference: [1.0, 0.0, 0.0], radius: 12.0, start: 0.0, end: TAU }; + vec![circle([0.0, 0.0, z], 20.0), hole] + }; + let b = Brep::loft(&[ring(0.0), ring(20.0)], 1, true).unwrap(); + assert_close(solid_volume(&b, "tube"), PI * (400.0 - 144.0) * 20.0, 1e-5, "lofted tube"); + // A square to a point 15 above it: a pyramid, A h / 3. + let base = polygon(&[[-10.0, -10.0, 0.0], [10.0, -10.0, 0.0], [10.0, 10.0, 0.0], [-10.0, 10.0, 0.0]]); + let b = Brep::loft_to_point(&base, [0.0, 0.0, 15.0]).unwrap(); + assert_close(solid_volume(&b, "pyramid"), 2000.0, 1e-9, "pyramid"); + assert_eq!(Brep::loft_to_point(&base, [3.0, 4.0, 0.0]).err(), Some(Error::Argument), "apex in the base's plane"); + assert_eq!(Brep::loft_to_point(&[circle([0.0; 3], 5.0)], [0.0, 0.0, 5.0]).err(), Some(Error::Argument), "curved base"); + let tooth = polygon(&[[4.0, 0.0, 0.0], [4.4, 0.0, 0.0], [4.4, 0.0, 0.4], [4.0, 0.0, 0.4]]); + let b = Brep::screw_sweep(&tooth, [0.0; 3], [0.0, 0.0, 1.0], 1.0, 3.0, 1e-4).unwrap(); + assert_close(solid_volume(&b, "screw"), 0.16 * TAU * 4.2 * 3.0, 1e-4, "screw sweep"); + // The tooth moved out 1 mm over its three turns, linearly: A 2 pi (c turns + int offset dt). + let b = Brep::screw_sweep_radial(&tooth, [0.0; 3], [0.0, 0.0, 1.0], 1.0, 3.0, &[(0.0, 0.0), (3.0, 1.0)], 1e-4).unwrap(); + assert_close(solid_volume(&b, "radial screw"), 0.16 * TAU * (4.2 * 3.0 + 1.5), 1e-4, "radial screw sweep"); + assert_eq!(Brep::screw_sweep_radial(&tooth, [0.0; 3], [0.0, 0.0, 1.0], 1.0, 3.0, &[(2.0, 0.0), (1.0, 1.0)], 1e-4).err(), Some(Error::Argument)); +} + +/// `x` turned by `a` about z, then lifted `z`. +fn turn_up(a: f64, k: f64, z: f64) -> Affine { + let (s, c) = a.sin_cos(); + Affine { m: [[k * c, k * s, 0.0], [-k * s, k * c, 0.0], [0.0, 0.0, 1.0]], t: [0.0, 0.0, z] } +} + +#[test] +fn sweeps_through_stations() { + // A 10 x 10 square up 40, turning 90 degrees: the section area stays, V = 100 * 40. + let sq = polygon(&[[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]); + // Stations 1.4 degrees of twist apart: the skin's free ends keep it within 2e-7 of V = A L. + let n = 65; + let f = |i: usize| i as f64 / (n - 1) as f64; + let twist: Vec = (0..n).map(|i| turn_up(PI / 2.0 * f(i), 1.0, 40.0 * f(i))).collect(); + let b = Brep::sweep_stations(&sq, &twist, Ends::Capped).unwrap(); + assert_close(solid_volume(&b, "twisted square"), 4000.0, 1e-6, "twisted square"); + // A disc of radius 5 grown to 10 over 30: a cone frustum. + let grow: Vec = (0..n).map(|i| turn_up(0.0, 1.0 + f(i), 30.0 * f(i))).collect(); + let b = Brep::sweep_stations(&[circle([0.0; 3], 5.0)], &grow, Ends::Capped).unwrap(); + assert_close(solid_volume(&b, "frustum"), 10.0 * PI * 175.0, 1e-6, "scaled disc"); + // The square turned a quarter about z at every station: it ends on itself, joined. + let ring = polygon(&[[26.0, 0.0, -4.0], [34.0, 0.0, -4.0], [34.0, 0.0, 4.0], [26.0, 0.0, 4.0]]); + let m = 97; + let round: Vec = (0..m).map(|i| turn_up(TAU * i as f64 / (m - 1) as f64, 1.0, 0.0)).collect(); + let b = Brep::sweep_stations(&ring, &round, Ends::Joined).unwrap(); + assert_close(solid_volume(&b, "ring"), 64.0 * TAU * 30.0, 1e-5, "joined ring"); + // A singular station, too few stations. + let mut flat = twist.clone(); + flat[4].m[0] = [0.0; 3]; + assert_eq!(Brep::sweep_stations(&sq, &flat, Ends::Capped).err(), Some(Error::Argument)); + assert_eq!(Brep::sweep_stations(&sq, &twist[..1], Ends::Capped).err(), Some(Error::Argument)); +} + +#[test] +fn hostile_curve_lists_are_refused() { + let nan = [Curve::Line { start: [0.0, f64::NAN, 0.0], end: [1.0, 0.0, 0.0] }]; + assert_eq!(Brep::extrude(&nan, [0.0, 0.0, 1.0], 1.0, 0.0, DraftCorner::default(), true).err(), Some(Error::Argument)); + let bad = [Curve::Nurbs { degree: 3, points: vec![[0.0, 0.0, 0.0, 1.0]; 2], knots: vec![0.0; 6] }]; + assert_eq!(Brep::extrude(&bad, [0.0, 0.0, 1.0], 1.0, 0.0, DraftCorner::default(), true).err(), Some(Error::Argument)); + assert_eq!(Brep::loft(&[vec![circle([0.0; 3], 1.0)]], 1, true).err(), Some(Error::Argument)); + let sq = polygon(&[[0.0; 3], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]); + assert_eq!(Brep::revolve(&sq, [0.0; 3], [0.0, 1.0, 0.0], 7.0, true).err(), Some(Error::Argument)); + assert_eq!(Brep::screw_sweep(&sq, [0.0; 3], [0.0, 0.0, 1.0], 0.0, 1.0, 1e-4).err(), Some(Error::Argument)); +} diff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rs new file mode 100644 index 000000000..aaafbcdd3 --- /dev/null +++ b/crates/smlib/src/tests.rs @@ -0,0 +1,512 @@ +use super::*; + +#[test] +fn box_end_to_end() { + let b = Brep::make_box([1.0, 2.0, 3.0], [10.0, 20.0, 30.0]).unwrap(); + assert!((b.volume(1e-7).unwrap() - 6000.0).abs() < 1e-6); + assert_eq!(b.counts().unwrap(), [6, 12, 8]); + let c = b.try_clone().unwrap(); + drop(b); + assert!((c.volume(1e-7).unwrap() - 6000.0).abs() < 1e-6); +} + +#[test] +fn bad_arguments_are_errors() { + assert_eq!(Brep::make_box([0.0; 3], [1.0, -1.0, 1.0]).unwrap_err(), Error::Argument); + assert_eq!(Brep::make_box([f64::NAN, 0.0, 0.0], [1.0; 3]).unwrap_err(), Error::Argument); + for size in [[1.0, -1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, f64::NAN]] { + assert_eq!(core::make_box([0.0; 3], size).err(), Some(Error::Argument), "{size:?}"); + } + let b = Brep::make_box([0.0; 3], [1.0; 3]).unwrap(); + assert_eq!(b.volume(f64::INFINITY).unwrap_err(), Error::Argument); +} + +/// `.smb` files on solidcore, in both forms and with a curved body, and a missing or corrupt file +/// is an error, not a panic. +#[test] +fn solidcore_reads_back_the_files_it_writes() { + use std::f64::consts::PI; + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-core-file-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cylinder = core::make_cylinder([1.0, 2.0, 3.0], 2.0, 5.0).map(Brep::made_core).unwrap(); + for ascii in [false, true] { + let path = dir.join(format!("cylinder-{ascii}.smb")); + core::file::write(cylinder.core(), &path, ascii).unwrap(); + let back = core::file::read(&path, ascii).map(Brep::made_core).unwrap(); + let v = core::volume(back.core(), 1e-7).unwrap(); + assert!((v - PI * 4.0 * 5.0).abs() < 1e-5, "ascii {ascii}: {v}"); + assert_eq!(core::counts(back.core()).unwrap(), core::counts(cylinder.core()).unwrap(), "ascii {ascii}"); + } + let body = cylinder.core(); + assert!(core::file::write(body, &dir.join("missing/x.smb"), false).is_err()); + assert!(core::file::read(&dir.join("missing.smb"), false).is_err()); + let junk = dir.join("junk.smb"); + std::fs::write(&junk, b"not a B-rep file").unwrap(); + assert!(core::file::read(&junk, false).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// ASCII that is no B-rep file is refused like binary. It comes back as an empty body today: +/// default-solidcore/bugs/ascii-junk-reads-as-empty.md. +#[test] +#[ignore = "solidcore: an ASCII file of junk reads as an empty B-rep instead of an error"] +fn solidcore_refuses_an_ascii_file_of_junk() { + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-core-junk-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let junk = dir.join("junk.smb"); + std::fs::write(&junk, b"not a B-rep file").unwrap(); + let r = core::file::read(&junk, true); + let _ = std::fs::remove_dir_all(&dir); + assert!(r.is_err()); +} + +#[test] +fn calls_from_many_threads_are_serialised() { + let handles: Vec<_> = (0..8) + .map(|i| { + std::thread::spawn(move || { + let s = 1.0 + i as f64; + let b = Brep::make_box([0.0; 3], [s; 3]).unwrap(); + (b.volume(1e-7).unwrap() - s * s * s).abs() < 1e-9 * s * s * s + }) + }) + .collect(); + assert!(handles.into_iter().all(|h| h.join().unwrap())); +} + +/// The dump folder is process-wide: the tests that set it take turns. +static DUMP_DIR_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Entry points that ask no kernel, so have nothing to say here. +const NO_KERNEL: [&str; 13] = [ + "inertia_tensor", + "is_valid", + "failed_tests", + "native", + "arrays_keeping_splines", + "from_arrays", + "from_record_keeping_splines", + "to_native_report", + "to_native_ordered", + "blends", + "word", + "words", + "in_call", +]; + +const ANSWERING: [&str; 63] = [ + "set_dump_dir", + "current_call", + "crash_test", + "make_box", + "read", + "write", + "try_clone", + "transformed", + "volume", + "counts", + "boolean", + "union_all", + "boolean2d", + "imprint", + "solid_count", + "fillet", + "chamfer", + "blend", + "blend_dropping", + "blend_setback", + "blend_setback_open", + "fillet_variable", + "chamfer_sides", + "shell", + "offset_faces", + "thicken", + "merge_faces", + "draft", + "split_faces", + "split_body", + "split_body_by_sheet", + "untrim_face", + "extend_sheet", + "face_points", + "stitch", + "offset_sheet", + "classify_point", + "mass_properties", + "bounds", + "edge_face_distance", + "area", + "is_manifold_solid", + "tagged", + "history", + "check", + "make_cylinder", + "make_sphere", + "make_cone", + "make_torus", + "arrays", + "to_native", + "planar_faces", + "extrude", + "revolve", + "sweep", + "sweep_placed", + "project_curves", + "face_section", + "loft", + "sweep_stations", + "loft_to_point", + "screw_sweep", + "screw_sweep_radial", +]; + +/// Every `pub fn` of the files that hold the crate's kernel entry points is accounted for. +#[test] +fn every_entry_point_is_in_the_guard() { + let files = [ + include_str!("lib.rs"), + include_str!("ops.rs"), + include_str!("split.rs"), + include_str!("trim.rs"), + include_str!("sheets.rs"), + include_str!("measure.rs"), + include_str!("flat.rs"), + include_str!("history.rs"), + include_str!("check.rs"), + include_str!("sweeps.rs"), + include_str!("export.rs"), + ]; + for file in files { + for line in file.lines() { + let Some(rest) = line.trim_start().strip_prefix("pub fn ") else { continue }; + let name = rest.split(['(', '<']).next().unwrap_or(rest); + assert!(ANSWERING.contains(&name) || NO_KERNEL.contains(&name), "`{name}` is in neither list"); + } + } +} + +/// Each entry point answers, with its result or its own refusal, on a body of the right kind or the +/// wrong one: none panics. +#[test] +fn every_entry_point_answers() { + use crate::sweeps::{Affine, Curve, DraftCorner, Ends, SweepFrame}; + use crate::trim::{Continuation, Holes}; + use crate::{Blend, BooleanOp, ChamferSecond, CheckLevel, Turn}; + fn says(_name: &str, r: Result) -> Option { + r.ok() + } + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-guard-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + { + let _dumps = DUMP_DIR_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + set_dump_dir(None); + } + let _ = current_call(); + let a = says("make_box", Brep::make_box([0.0; 3], [10.0; 3])).unwrap(); + let t = says("make_box", Brep::make_box([5.0; 3], [10.0; 3])).unwrap(); + let p = |x: f64, y: f64, z: f64| [x, y, z]; + let edge = [p(5.0, 10.0, 10.0)]; + let top = [p(5.0, 5.0, 10.0)]; + let path = dir.join("a.smb"); + says("write", a.write(&path, false)); + says("read", Brep::read(&path, false)); + says("try_clone", a.try_clone()); + says("transformed", a.transformed(&[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])); + says("volume", a.volume(1e-6)); + says("counts", a.counts()); + says("boolean", a.boolean(&t, BooleanOp::Union)); + says("union_all", Brep::union_all(&[&a, &t])); + says("boolean2d", a.boolean2d(&t, BooleanOp::Union)); + says("imprint", a.imprint(&t)); + says("solid_count", a.solid_count()); + says("fillet", a.fillet(&edge, 0.1, 1.0)); + says("chamfer", a.chamfer(&edge, 0.1, 1.0)); + says("blend", a.blend(Blend::Round, &edge, &[1.0], 0.1)); + says("blend_dropping", a.blend_dropping(Blend::Round, Turn::Mitre, &edge, &[1.0], 0.1)); + let corner = [p(10.0, 10.0, 10.0)]; + let three = [p(5.0, 10.0, 10.0), p(10.0, 5.0, 10.0), p(10.0, 10.0, 5.0)]; + says("blend_setback", a.blend_setback(Blend::Round, &three, &[1.0; 3], &corner, &[2.0], 0.1)); + says("blend_setback_open", a.blend_setback_open(Blend::Round, &three, &[1.0; 3], &corner, &[2.0], 0.1)); + says("fillet_variable", a.fillet_variable(edge[0], 0.1, p(0.0, 10.0, 10.0), 1, &[0.0, 0.0, 1.0, 1.0], &[2.0, 1.0])); + says("chamfer_sides", a.chamfer_sides(&edge, 0.1, 1.0, ChamferSecond::Distance(2.0), p(0.0, 0.0, 1.0))); + says("shell", a.shell(&top, 0.1, 1.0)); + says("offset_faces", a.offset_faces(&top, 0.1, 1.0)); + says("thicken", a.thicken(1.0, false)); + says("merge_faces", a.merge_faces(&top, 0.1)); + says("draft", a.draft(&[p(5.0, 10.0, 5.0)], 0.1, [0.0; 3], p(0.0, 0.0, 1.0), p(0.0, 0.0, 1.0), 0.1)); + let tool = + says("Surface::plane", ssi::Surface::plane(p(0.0, 0.0, 5.0), p(1.0, 0.0, 0.0), p(0.0, 1.0, 0.0), [-50.0, 50.0], [-50.0, 50.0])).unwrap(); + says("split_faces", a.split_faces(&[0], &[&tool])); + says("split_body", a.split_body(&tool)); + let square = [p(0.0, 0.0, 5.0), p(10.0, 0.0, 5.0), p(10.0, 10.0, 5.0), p(0.0, 10.0, 5.0)]; + let lines: Vec = (0..4).map(|i| Curve::Line { start: square[i], end: square[(i + 1) % 4] }).collect(); + let sheet = says("planar_faces", Brep::planar_faces(&lines)).unwrap(); + says("split_body_by_sheet", a.split_body_by_sheet(&sheet, 0)); + says("untrim_face", sheet.untrim_face(p(5.0, 5.0, 5.0), 0.1, Holes::All, true, false)); + says("extend_sheet", sheet.extend_sheet(p(5.0, 5.0, 5.0), 0.1, 1.0, Continuation::Natural)); + says("face_points", a.face_points()); + says("stitch", sheet.stitch(0.1)); + says("offset_sheet", sheet.offset_sheet(1.0)); + says("classify_point", a.classify_point([1.0; 3])); + says("mass_properties", a.mass_properties(1e-6)); + says("bounds", a.bounds()); + says("edge_face_distance", a.edge_face_distance(0, 0)); + says("area", a.area(1e-6)); + says("is_manifold_solid", a.is_manifold_solid()); + says("history", says("tagged", a.tagged(0)).unwrap().history()); + says("check", a.check(CheckLevel::All)); + says("make_cylinder", Brep::make_cylinder([0.0; 3], 1.0, 1.0)); + says("make_sphere", Brep::make_sphere([0.0; 3], 1.0)); + says("make_cone", Brep::make_cone([0.0; 3], 2.0, 1.0, 1.0)); + says("make_torus", Brep::make_torus([0.0; 3], 2.0, 1.0)); + says("arrays", a.arrays()); + says("to_native", a.to_native().map_err(|_| Error::Argument)); + says("extrude", Brep::extrude(&lines, p(0.0, 0.0, 1.0), 1.0, 0.0, DraftCorner::Curvature, true)); + says("revolve", Brep::revolve(&lines, p(20.0, 0.0, 0.0), p(0.0, 1.0, 0.0), 1.0, true)); + let run = [Curve::Line { start: p(5.0, 5.0, 5.0), end: p(5.0, 5.0, 15.0) }]; + says("sweep", Brep::sweep(&lines, &run, SweepFrame::Follow, true)); + says("sweep_placed", Brep::sweep_placed(&lines, &run, SweepFrame::Follow, true)); + says("project_curves", a.project_curves(top[0], 0.1, &lines, p(0.0, 0.0, -1.0), 0.01)); + says("face_section", a.face_section(top[0], 0.1, top[0], p(1.0, 0.0, 0.0), 0.01)); + let lifted: Vec = (0..4) + .map(|i| Curve::Line { start: [square[i][0], square[i][1], 9.0], end: [square[(i + 1) % 4][0], square[(i + 1) % 4][1], 9.0] }) + .collect(); + says("loft", Brep::loft(&[lines.clone(), lifted], 1, true)); + let i3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + says("sweep_stations", Brep::sweep_stations(&lines, &[Affine { m: i3, t: [0.0; 3] }, Affine { m: i3, t: [0.0, 0.0, 2.0] }], Ends::Capped)); + says("loft_to_point", Brep::loft_to_point(&lines, p(5.0, 5.0, 12.0))); + says("screw_sweep", Brep::screw_sweep(&lines, p(30.0, 0.0, 0.0), p(0.0, 0.0, 1.0), 12.0, 1.0, 0.01)); + says("screw_sweep_radial", Brep::screw_sweep_radial(&lines, p(30.0, 0.0, 0.0), p(0.0, 0.0, 1.0), 12.0, 1.0, &[(0.0, 0.0), (1.0, 0.0)], 0.01)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// While a dump folder is set, a call that answers serialises none of its inputs, and one that +/// fails serialises each once: the rig's timings, taken with a folder set, are the kernel's. +#[test] +fn only_a_failing_call_serialises_its_inputs() { + let _dumps = DUMP_DIR_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-core-dump-lazy-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + core::dump::set_dir(Some(dir.clone())); + let serialised = || core::dump::SERIALISED.with(std::cell::Cell::get); + let a = core::make_box([0.0; 3], [10.0; 3]).unwrap(); + let b = core::make_box([5.0; 3], [10.0; 3]).unwrap(); + let before = serialised(); + let v = core::volume(&a, 1e-8); + let u = core::boolean::boolean(&a, &b, BooleanOp::Union); + let answered = serialised() - before; + let r: Result<()> = core::with_body("smlib_test_failure", &a, |_, _| Err(solidcore::SolidError::invalid_input("test", "refused"))); + let failed = serialised() - before - answered; + core::dump::set_dir(None); + let _ = std::fs::remove_dir_all(&dir); + assert!(v.is_ok() && matches!(u, Ok(Some(_))) && r.is_err()); + assert_eq!((answered, failed), (0, 1)); +} + +/// A failing solidcore call leaves its inputs and what failed, and an answered one leaves nothing; +/// the call in flight is named, and gone after. A folder is process-wide, so this test is the one +/// that sets it. +#[test] +fn a_failing_solidcore_call_leaves_a_dump_and_names_itself() { + let _dumps = DUMP_DIR_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-core-dump-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + core::dump::set_dir(Some(dir.clone())); + let a = core::make_box([0.0; 3], [10.0; 3]).unwrap(); + let seen: std::sync::Mutex> = std::sync::Mutex::new(None); + let r: Result<()> = core::with_body("smlib_test_failure", &a, |_, _| { + *seen.lock().unwrap() = core::dump::current(); + Err(solidcore::SolidError::invalid_input("test", "refused")) + }); + core::dump::set_dir(None); + assert!(r.is_err()); + assert!(seen.lock().unwrap().as_deref().is_some_and(|c| c.contains("smlib_test_failure")), "{seen:?}"); + assert!(!core::dump::current().is_some_and(|c| c.contains("smlib_test_failure")), "no longer in flight"); + let got: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + let text = got.iter().find(|n| n.ends_with("-smlib_test_failure.txt")).unwrap_or_else(|| panic!("{got:?}")); + assert!(std::fs::read_to_string(dir.join(text)).unwrap().contains("refused")); + let smb = got.iter().find(|n| n.ends_with("-smlib_test_failure-brep.smb")).unwrap_or_else(|| panic!("{got:?}")); + let back = core::file::read(&dir.join(smb), false).unwrap(); + assert!((core::volume(&back, 1e-7).unwrap() - 1000.0).abs() < 1e-6); + let _ = std::fs::remove_dir_all(&dir); +} + +/// SMLib may end an edge at a parameter of its own (a knot its vertex lies at, where its drop onto +/// the patch ends): within the edge's tolerance as SMLib held it, on its curve, the pcurve is +/// mapped onto our interval exactly; farther is SMLib trimming the edge, refused with how far. An +/// edge whose gap from its surface raised its tolerance (two of Poppy Humanoid's left thigh, SMLib +/// ending them 0.1 um short) is held at that tolerance. +#[test] +fn a_pcurve_smlib_ends_within_the_edges_tolerance_is_mapped_onto_our_interval() { + use solidcore_record::brep::{Curve, Curve2}; + use solidcraft_geom::brep::pcurve::TrimEdge; + let line = Curve::Line { start: [0.0, 0.0, 0.0], end: [2.0, 0.0, 0.0] }; + let edge = TrimEdge { curve: &line, nurbs: None, interval: [0.0, 1.0], vertices: [0, 1], tolerance: 1e-5 }; + let theirs = [0.0, 1.0 - 2e-8]; + let pc = Curve2::Spline { knots: vec![0.0, 0.0, theirs[1], theirs[1]], points: vec![[0.0, 0.0], [1.0, 0.0]] }; + let mapped = crate::pcurves::on_our_interval(pc.clone(), &edge, theirs, edge.tolerance).unwrap(); + assert_eq!(mapped.interval(), Some([0.0, 1.0])); + assert_eq!(solidcraft_geom::brep::pcurve::eval(&mapped, 1.0), Some([1.0, 0.0])); + // 0.02 mm along the edge is past its 1e-5 mm. + let err = crate::pcurves::on_our_interval(pc, &edge, [0.0, 0.99], edge.tolerance).unwrap_err(); + assert!(err.contains("SMLib moved an edge's interval") && err.contains("tolerance"), "{err}"); + // Held at 0.03 mm, as an edge 0.01 mm off its surface is, the same end is within it. + let short = Curve2::Spline { knots: vec![0.0, 0.0, 0.99, 0.99], points: vec![[0.0, 0.0], [1.0, 0.0]] }; + let held = crate::pcurves::on_our_interval(short, &edge, [0.0, 0.99], 0.03).unwrap(); + assert_eq!(held.interval(), Some([0.0, 1.0])); + assert_eq!(solidcraft_geom::brep::pcurve::eval(&held, 1.0), Some([1.0, 0.0])); +} + +/// An edge whose curve runs 2.5 um past its vertex and its face's patch (as Poppy Humanoid's +/// Congé19 has them), with a tolerance of 0.5 um: SMLib trims such an edge back to the patch +/// when it makes its trim, unless the edge's tolerance covers its gap. The gap is measured +/// (SMLib's own, over the patch) and covered, so the face's pcurves come back on the edge's +/// own interval, ending at the patch's corner. +#[test] +fn an_edge_a_few_um_past_its_patch_keeps_its_interval() { + use solidcore_record::brep::{Curve, Surface}; + use solidcraft_geom::brep::pcurve::{TrimEdge, TrimFace, TrimUse, Trims}; + // S(u, v) = (10u, 10v, 2v^2), bicubic + let g = [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]; + let z = [0.0, 0.0, 2.0 / 3.0, 2.0]; + let bezier = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + let points: Vec> = (0..4).map(|i| (0..4).map(|j| [10.0 * g[i], 10.0 * g[j], z[j]]).collect()).collect(); + let surface = Surface::Spline { u_knots: bezier.clone(), v_knots: bezier.clone(), points: points.clone() }; + let past = 2.5e-3; + let spline = |p: Vec<[f64; 3]>| Curve::Spline { knots: bezier.clone(), points: p }; + let curves = [ + spline((0..4).map(|i| [(10.0 + past) * g[i], 0.0, 0.0]).collect()), + spline((0..4).map(|j| points[3][j]).collect()), + spline((0..4).map(|i| points[3 - i][3]).collect()), + spline((0..4).map(|j| points[0][3 - j]).collect()), + ]; + let ends = [[0, 1], [1, 2], [2, 3], [3, 0]]; + let edges = (0..4) + .map(|k| TrimEdge { curve: &curves[k], nurbs: None, interval: [0.0, 1.0], vertices: ends[k], tolerance: if k == 0 { 1e-3 } else { 1e-5 } }) + .collect(); + let face = TrimFace { + surface: &surface, + nurbs: None, + domain: [[0.0, 1.0], [0.0, 1.0]], + edges, + vertices: vec![[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 10.0, 2.0], [0.0, 10.0, 2.0]], + loops: vec![(0..4).map(|k| TrimUse { edge: k, forward: true, pcurve: None }).collect()], + tolerance: 1e-5, + }; + let pcs = crate::pcurves::SmlibTrims.trims(&face).unwrap(); + let pc = &pcs[0][0]; + assert_eq!(pc.interval(), Some([0.0, 1.0])); + let [u, v] = solidcraft_geom::brep::pcurve::eval(pc, 1.0).unwrap(); + assert!((u - 1.0).abs() < 1e-9 && v.abs() < 1e-9, "{u} {v}"); +} + +/// A solidcore call blocked on a channel until `release`, on its own thread: a call that runs long +/// or never returns, as one design's slow operation does. +fn call_held_open(body: &str) -> (std::sync::mpsc::Sender<()>, std::thread::JoinHandle>) { + let call: &'static str = Box::leak(body.to_owned().into_boxed_str()); + let (started, is_started) = std::sync::mpsc::channel(); + let (release, released) = std::sync::mpsc::channel::<()>(); + let held = std::thread::spawn(move || { + core::run(call, |_| { + let _ = started.send(()); + let _ = released.recv(); + Ok(()) + }) + }); + is_started.recv().unwrap(); + (release, held) +} + +/// Runs `f` on another thread and gives its answer; a failure here rather than a test that hangs +/// when `f` waits for a call that does not end. The limit is no measure of speed: `f` is free to +/// take all of it, and only a wait with no end fails. +fn answered(f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(f()); + }); + rx.recv_timeout(std::time::Duration::from_secs(120)).expect("this call waited for a call on another thread that has not ended") +} + +/// One design's long kernel call must never hold up another's: the kernel call of a design closed +/// or still open, blocked here on a channel, while another makes and measures a body of its own. +#[test] +fn a_kernel_call_that_does_not_end_holds_up_no_other_call() { + let (release, held) = call_held_open("held_open"); + let volume = answered(|| { + let a = Brep::make_box([0.0; 3], [10.0; 3]).unwrap(); + let b = Brep::make_box([5.0, 0.0, 0.0], [10.0; 3]).unwrap(); + a.boolean(&b, BooleanOp::Union).unwrap().unwrap().volume(1e-7).unwrap() + }); + assert!((volume - 1500.0).abs() < 1e-6, "{volume}"); + assert!(current_call().is_some_and(|c| c.contains("held_open")), "the call still runs"); + // And one holds up no other held open beside it. + let (release_too, held_too) = call_held_open("held_open_too"); + assert!(current_call().is_some_and(|c| c.contains("held_open") && c.contains("held_open_too"))); + for (release, held) in [(release, held), (release_too, held_too)] { + release.send(()).unwrap(); + held.join().unwrap().unwrap(); + } + assert!(!current_call().is_some_and(|c| c.contains("held_open")), "neither is in flight any more"); +} + +/// Bodies are made and used on whichever kernel is free, at the same time on several threads, and +/// each answer is the one a single kernel gives: a body made while another call held the first +/// kernel is used once it is free, and two bodies from different kernels go into one boolean. +#[test] +fn bodies_move_between_kernels_and_calls_run_side_by_side() { + let (release, held) = call_held_open("held_open"); + let on_second = answered(|| Brep::make_box([5.0, 0.0, 0.0], [10.0; 3]).unwrap()); + release.send(()).unwrap(); + held.join().unwrap().unwrap(); + let first = Brep::make_box([0.0; 3], [10.0; 3]).unwrap(); + let v = first.boolean(&on_second, BooleanOp::Subtract).unwrap().unwrap().volume(1e-7).unwrap(); + assert!((v - 500.0).abs() < 1e-6, "{v}"); + + let shared = std::sync::Arc::new(Brep::make_box([0.0; 3], [10.0; 3]).unwrap()); + let workers: Vec<_> = (0..8) + .map(|n| { + let shared = shared.clone(); + std::thread::spawn(move || { + for i in 0..20 { + let side = 2.0 + f64::from((n + i) % 5); + let tool = Brep::make_box([10.0 - side; 3], [side + 1.0; 3]).unwrap(); + let cut = shared.boolean(&tool, BooleanOp::Subtract).unwrap().unwrap(); + let rounded = Brep::make_box([0.0; 3], [10.0; 3]).unwrap().fillet(&[[5.0, 0.0, 0.0]], 1e-6, 1.0).unwrap(); + let lost = (1.0 - std::f64::consts::FRAC_PI_4) * 10.0; + assert!((cut.volume(1e-7).unwrap() - (1000.0 - side.powi(3))).abs() < 1e-5); + assert!((rounded.volume(1e-7).unwrap() - (1000.0 - lost)).abs() < 1e-4); + } + }) + }) + .collect(); + for worker in workers { + answered(move || worker.join().unwrap()); + } +} + +/// Each kernel has its own range of blend serials: a body keeps the serials of the kernel that +/// made it, and another kernel's memo of solved stations must not take them for its own. +#[test] +fn kernels_never_issue_the_same_blend_serial() { + let range = core::BLEND_SERIALS_PER_KERNEL as usize; + let ranges = core::run("outer", |outer| { + let inner = core::run("inner", |inner| Ok(inner.blend_last_serial.get() as usize)).unwrap_or_default(); + Ok([outer.blend_last_serial.get() as usize / range, inner / range]) + }); + let [outer, inner] = ranges.unwrap(); + assert_ne!(outer, inner); +} + +/// A panic in a call running beside another costs neither: the panicking call's kernel is thrown +/// away and the other call and later ones go on. +#[test] +fn a_panic_beside_a_running_call_costs_only_its_own_kernel() { + let (release, held) = call_held_open("held_open"); + let r: Result<()> = core::run("panicking", |_| panic!("on purpose")); + assert!(matches!(r, Err(Error::Internal(_))), "{r:?}"); + let v = answered(|| Brep::make_box([0.0; 3], [2.0; 3]).unwrap().volume(1e-7).unwrap()); + assert!((v - 8.0).abs() < 1e-6, "{v}"); + release.send(()).unwrap(); + held.join().unwrap().unwrap(); +} diff --git a/crates/smlib/src/trace.rs b/crates/smlib/src/trace.rs new file mode 100644 index 000000000..56c642da4 --- /dev/null +++ b/crates/smlib/src/trace.rs @@ -0,0 +1,232 @@ +//! A trace of the operations a run makes on this crate's bodies, for the kernel rig's corpus +//! (`solidcraft-cli kernel-cases --export`): each body taken from a record (its record), each +//! operation (its name, its operand bodies, its parameters with every pick by points also given +//! as the topology index it picked, and the bodies it made or why it failed), and each body +//! written back as a record. Off unless [`start`]ed; while off it costs an atomic load per +//! operation. +//! +//! Bodies are named by a number each gets when it is made ([`crate::Brep`]'s id), so a trace +//! says which operation's output went into which operation, and which record each became. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, PoisonError}; + +use serde_json::{Value, json}; +use solidcore_record::brep as b; + +use crate::sweeps::{Affine, Curve}; +use crate::{Brep, Result}; + +static ON: AtomicBool = AtomicBool::new(false); +static NEXT: AtomicU64 = AtomicU64::new(1); +static LOG: Mutex> = Mutex::new(Vec::new()); + +/// One thing a traced run did, in the order it happened. +#[derive(Clone, Debug)] +pub enum Event { + /// Body `id` was made from `record` ([`Brep::from_record`]). + Import { id: u64, record: Box, trusted: bool, keeping_splines: bool }, + /// An operation: its name, its operand bodies, its parameters, and the bodies it made + /// (`Ok`) or its error's message (`Err`). + Call { op: &'static str, inputs: Vec, params: Value, outputs: std::result::Result, String> }, + /// Body `id` was written as `record` ([`Brep::to_native`] and its kin). + Export { id: u64, record: Box }, +} + +/// Starts a trace, dropping anything an earlier one left. +pub fn start() { + LOG.lock().unwrap_or_else(PoisonError::into_inner).clear(); + ON.store(true, Ordering::SeqCst); +} + +/// Stops the trace and hands over what it recorded. +pub fn finish() -> Vec { + ON.store(false, Ordering::SeqCst); + std::mem::take(&mut *LOG.lock().unwrap_or_else(PoisonError::into_inner)) +} + +/// The names of solidcore's upstream fixes this crate turns on: the fix set every traced +/// operation ran with. +pub fn fixes() -> Vec<&'static str> { + crate::core::fixes().flags().filter(|&(_, on)| on).map(|(name, _)| name).collect() +} + +pub(crate) fn on() -> bool { + ON.load(Ordering::Relaxed) +} + +/// A new body's number. +pub(crate) fn next_id() -> u64 { + NEXT.fetch_add(1, Ordering::Relaxed) +} + +fn push(e: Event) { + LOG.lock().unwrap_or_else(PoisonError::into_inner).push(e); +} + +pub(crate) fn imported(r: &Result, record: &b::Brep, trusted: bool, keeping_splines: bool) { + if !on() { + return; + } + if let Ok(body) = r { + push(Event::Import { id: body.id, record: Box::new(record.clone()), trusted, keeping_splines }); + } +} + +pub(crate) fn exported(body: &Brep, record: &b::Brep) { + if on() { + push(Event::Export { id: body.id, record: Box::new(record.clone()) }); + } +} + +/// Records operation `op` on `inputs`, whose result `r` made the bodies `outputs` reads from it. +/// `params` is only built while tracing, after the operation ran. +pub(crate) fn call(op: &'static str, inputs: &[&Brep], r: &Result, outputs: impl FnOnce(&T) -> Vec, params: impl FnOnce() -> Value) { + if !on() { + return; + } + let outputs = match r { + Ok(v) => Ok(outputs(v)), + Err(e) => Err(e.to_string()), + }; + push(Event::Call { op, inputs: inputs.iter().map(|b| b.id).collect(), params: params(), outputs }); +} + +/// [`call`] for an operation that makes one body. +pub(crate) fn made(op: &'static str, inputs: &[&Brep], r: &Result, params: impl FnOnce() -> Value) { + call(op, inputs, r, |b| vec![b.id], params); +} + +/// [`call`] for an operation that may make no body. +pub(crate) fn maybe(op: &'static str, inputs: &[&Brep], r: &Result>, params: impl FnOnce() -> Value) { + call(op, inputs, r, |b| b.iter().map(|b| b.id).collect(), params); +} + +/// What a pick by points is of. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PickKind { + /// The edge nearest each point, unambiguous (`pick_edges`, the blends' picker). + Edge, + /// The face nearest each point, unambiguous (`pick_faces`, the offsets' picker). + Face, + /// The vertex nearest each point, unambiguous (`pick_vertices`, the setbacks' picker). + Vertex, + /// The nearest edge (`nearest_edge`, an extension's picker). + NearestEdge, + /// The nearest face (`face_at`, an untrim's picker). + NearestFace, +} + +/// What one point picked: the entity's index in the body's list of its kind, and where it is +/// (an edge's end points, a vertex's point), or why it picked none. +#[derive(Clone, Debug, PartialEq)] +pub struct Pick { + pub index: Option, + pub at: Vec<[f64; 3]>, + pub miss: Option<&'static str>, +} + +impl Pick { + pub(crate) fn missed(why: &'static str) -> Pick { + Pick { index: None, at: Vec::new(), miss: Some(why) } + } +} + +/// The points of a pick on `body` and what each picked: `{"points", "tolerance", "picked"}`, +/// each of `picked` `{"index", "at"}` or `{"miss"}`. +pub(crate) fn picks(body: &Brep, kind: PickKind, points: &[[f64; 3]], tolerance: f64) -> Value { + let picked = match crate::core::picked::picks(body.core(), kind, points, tolerance) { + Ok(p) => Value::Array( + p.into_iter() + .map(|p| match (p.index, p.miss) { + (Some(i), _) => json!({"index": i, "at": p.at}), + (None, why) => json!({"miss": why.unwrap_or("none")}), + }) + .collect(), + ), + Err(e) => json!({"error": e.to_string()}), + }; + let kind = match kind { + PickKind::Edge | PickKind::NearestEdge => "edge", + PickKind::Face | PickKind::NearestFace => "face", + PickKind::Vertex => "vertex", + }; + json!({"kind": kind, "points": points, "tolerance": tolerance, "picked": picked}) +} + +/// A profile, path or section curve as data. +pub(crate) fn curve(c: &Curve) -> Value { + match c { + Curve::Line { start, end } => json!({"line": {"start": start, "end": end}}), + Curve::Arc { center, axis, reference, radius, start, end } => { + json!({"arc": {"center": center, "axis": axis, "reference": reference, "radius": radius, "start": start, "end": end}}) + } + Curve::Nurbs { degree, points, knots } => json!({"nurbs": {"degree": degree, "points": points, "knots": knots}}), + } +} + +pub(crate) fn curves(cs: &[Curve]) -> Value { + Value::Array(cs.iter().map(curve).collect()) +} + +pub(crate) fn affine(a: &Affine) -> Value { + json!({"m": a.m, "t": a.t}) +} + +/// A split tool's surface as data. +pub(crate) fn surface(s: &crate::ssi::Spec) -> Value { + use crate::ssi::Spec; + match s { + Spec::Plane { origin, xaxis, yaxis, u, v } => json!({"plane": {"origin": origin, "xaxis": xaxis, "yaxis": yaxis, "u": u, "v": v}}), + Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height } => { + json!({"cylinder": {"origin": origin, "xaxis": xaxis, "yaxis": yaxis, "radius": radius, "angle_deg": angle_deg, "height": height}}) + } + Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height } => { + json!({"cone": {"apex": apex, "xaxis": xaxis, "yaxis": yaxis, "half_angle_deg": half_angle_deg, "height": height}}) + } + Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg } => { + json!({"sphere": {"center": center, "xaxis": xaxis, "yaxis": yaxis, "radius": radius, "lon_deg": lon_deg, "lat_deg": lat_deg}}) + } + Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg } => json!({"torus": { + "center": center, "xaxis": xaxis, "yaxis": yaxis, "major_radius": major_radius, "minor_radius": minor_radius, + "major_deg": major_deg, "minor_deg": minor_deg}}), + Spec::Nurbs { degree, nu, nv, knots_u, knots_v, points, weights } => json!({"nurbs": { + "degree": degree, "nu": nu, "nv": nv, "knots_u": knots_u, "knots_v": knots_v, "points": points, "weights": weights}}), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A traced fillet names its operand, its output and the edge its point picked, by index and + /// end points; the record its output was written as and the body read back from it are + /// traced under their own numbers. Other tests' operations may land in the trace too: only + /// these bodies' events are read. + #[test] + fn a_fillet_is_traced_with_its_pick_and_records() { + let block = Brep::make_box([0.0; 3], [10.0, 20.0, 30.0]).unwrap(); + start(); + let round = block.fillet(&[[10.0, 10.0, 30.0]], 1e-3, 2.0).unwrap(); + let record = round.to_native().unwrap(); + let again = Brep::from_record(&record, true).unwrap(); + let events = finish(); + let call = events + .iter() + .find_map(|e| match e { + Event::Call { op: "fillet", inputs, params, outputs } if inputs == &vec![block.id] => Some((params, outputs)), + _ => None, + }) + .unwrap(); + assert_eq!(call.1, &Ok(vec![round.id])); + let picked = &call.0["edges"]["picked"][0]; + assert!(picked["index"].as_u64().is_some(), "{picked}"); + // The point (10, 10, 30) is on the top edge x = 10, z = 30, from y = 0 to y = 20. + let mut ends: Vec> = picked["at"].as_array().unwrap().iter().map(|p| serde_json::from_value(p.clone()).unwrap()).collect(); + ends.sort_by(|a, b| a[1].total_cmp(&b[1])); + assert_eq!(ends, vec![vec![10.0, 0.0, 30.0], vec![10.0, 20.0, 30.0]]); + assert!(events.iter().any(|e| matches!(e, Event::Export { id, record: r } if *id == round.id && **r == record))); + assert!(events.iter().any(|e| matches!(e, Event::Import { id, record: r, trusted: true, .. } if *id == again.id && **r == record))); + assert_ne!(again.id, round.id); + } +} diff --git a/crates/smlib/src/trim.rs b/crates/smlib/src/trim.rs new file mode 100644 index 000000000..715776235 --- /dev/null +++ b/crates/smlib/src/trim.rs @@ -0,0 +1,71 @@ +//! Untrim and extend of a sheet's faces. Each returns a new body and leaves its input unchanged; +//! faces and holes are chosen by points, as [`crate::ops`] chooses them. + +use serde_json::json; + +use crate::trace; +use crate::{Brep, Result, core}; + +/// How [`Brep::extend_sheet`] continues a surface past its side. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Continuation { + /// The surface's own geometry (a B-spline's end spans continued). + Natural, + /// A run-off tangent to the surface across the side (G1). + Tangent, + /// A run-off that also keeps the surface's curvature across the side (G2). + Curvature, +} + +/// The inner loops [`Brep::untrim_face`] takes away. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Holes<'a> { + All, + /// The inner loop nearest each point (within the tolerance, else [`crate::Error::NoMatch`]). + At(&'a [[f64; 3]]), +} + +impl Brep { + /// The face nearest `point` (within `tolerance`) restored towards its surface: the holes + /// `holes` names taken away and, with `outer`, its outer boundary back on the surface's + /// parameter box (a free-form surface's own, an analytic one's the box of the face's span; one + /// all the way round closes on the surface's seam). The face alone, or + /// with `in_place` the whole body with it replaced. Tags follow the face and its edges. + pub fn untrim_face(&self, point: [f64; 3], tolerance: f64, holes: Holes, outer: bool, in_place: bool) -> Result { + let holes = match holes { + Holes::All => None, + Holes::At(at) => Some(at), + }; + let r = core::trim::untrim_face(self.core(), point, tolerance, holes, outer, in_place).map(Brep::made_core); + trace::made( + "untrim_face", + &[self], + &r, + || json!({"face": trace::picks(self, trace::PickKind::NearestFace, &[point], tolerance), "holes": holes, "outer": outer, "in_place": in_place}), + ); + r + } + + /// The one-face sheet `self`, whose face is its surface's whole parameter box, continued + /// `distance` past the side its edge nearest `point` (within `tolerance`) runs along, as + /// `how` says: SMLib's extended surface over the grown box, the face and its sides carrying + /// the tags of those they continue. A sheet of another shape is [`crate::Error::Unsupported`]. + pub fn extend_sheet(&self, point: [f64; 3], tolerance: f64, distance: f64, how: Continuation) -> Result { + let r = core::trim::extend_sheet(self.core(), point, tolerance, distance, how).map(Brep::made_core); + trace::made("extend_sheet", &[self], &r, || { + let how = match how { + Continuation::Natural => "natural", + Continuation::Tangent => "tangent", + Continuation::Curvature => "curvature", + }; + json!({"edge": trace::picks(self, trace::PickKind::NearestEdge, &[point], tolerance), "distance": distance, "how": how}) + }); + r + } + + /// A point inside each face, in SMLib's face order: on the face's surface, inside its trims + /// (`SmFace::CalculateAnInternalPoint`). + pub fn face_points(&self) -> Result> { + core::trim::face_points(self.core()) + } +} diff --git a/crates/smlib/tests/ssi_corpus.rs b/crates/smlib/tests/ssi_corpus.rs new file mode 100644 index 000000000..90632852a --- /dev/null +++ b/crates/smlib/tests/ssi_corpus.rs @@ -0,0 +1,634 @@ +//! The SSI corpus (`tests/ssi-corpus`) and its scorer (`ssi_score`, a port of the corpus's +//! `scoring/score.py`). +//! +//! The parity check against the Python scorer is ignored by default; it needs the corpus +//! runner's raw outputs and score.py's scores for the same run: +//! +//! ```text +//! SSI_PARITY_RAW=/results/raw/gsi_1e-6 \ +//! SSI_PARITY_SCORES=/results/score_gsi_1e-6.json \ +//! SSI_PARITY_TOL=1e-6 SSI_SM_MESSAGES=/source/SMLib/inc/SmMessages.h \ +//! cargo test -p solidcraft-smlib --test ssi_corpus -- --ignored --nocapture +//! ``` +//! +//! [`solidcore_global_intersect_at_1e_6`] runs every case through solidcore's +//! GlobalSurfaceIntersect (via `solidcraft_smlib::ssi`, as the corpus runner calls it) and checks +//! that every case SMLib passed passes. + +mod ssi_score; + +use serde_json::Value; +use ssi_score::geom::{Nurbs, V3, linspace, np_max}; +use ssi_score::{Case, Coverage, EngineCurve, EngineResult, Outcome, Score, Tolerances, Verdict, case_ids, fmt_e, load_case, score_case}; + +fn all_cases() -> Vec { + let ids = case_ids(); + assert_eq!(ids.len(), 119, "corpus case count"); + ids.iter().map(|id| load_case(id).unwrap_or_else(|e| panic!("{id}: {e}"))).collect() +} + +/// `f` over `items` on a few threads, results in order. +fn par_map(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec { + let n = std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 8); + let next = std::sync::atomic::AtomicUsize::new(0); + let mut out: Vec<(usize, R)> = std::thread::scope(|s| { + let workers: Vec<_> = (0..n) + .map(|_| { + s.spawn(|| { + let mut mine = Vec::new(); + loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some(item) = items.get(i) else { break }; + mine.push((i, f(item))); + } + mine + }) + }) + .collect(); + workers.into_iter().flat_map(|w| w.join().unwrap()).collect() + }); + out.sort_by_key(|(i, _)| *i); + out.into_iter().map(|(_, r)| r).collect() +} + +/// The expected intersection itself, as an engine answer. +fn truth_as_output(case: &Case) -> EngineResult { + let curve = |p: &Vec| EngineCurve { curve_type: "CROSSING".into(), xyz: p.clone(), ..EngineCurve::default() }; + EngineResult { + status: ssi_score::SM_SUCCESS, + status_name: None, + time_ms: 0.0, + curves: case.expected.branches.iter().chain(&case.expected.coincident_regions).map(curve).collect(), + points: case.expected.isolated_points.clone(), + } +} + +#[test] +fn every_case_parses_and_cites_its_source() { + let cases = all_cases(); + let y23: Vec<&Case> = cases.iter().filter(|c| c.id.starts_with("y23_")).collect(); + assert_eq!(y23.len(), 25); + for c in &y23 { + let src = c.json.get("source").and_then(Value::as_str).unwrap_or_default(); + assert!(src.contains("Yang, Jia & Yan 2023"), "{}: source {src:?}", c.id); + } + for c in &cases { + assert_eq!(c.surfaces.len(), 2, "{}", c.id); + assert!(c.cov_tol > 0.0, "{}", c.id); + } +} + +/// Every NURBS surface of the corpus lies on its exact truth (the corpus's own self-check): this +/// checks the NURBS evaluation and the distance functions against each other. +#[test] +fn nurbs_surfaces_lie_on_their_truths() { + let mut checked = 0; + for case in all_cases() { + for (k, spec) in case.surfaces.iter().enumerate() { + if spec.get("type").and_then(Value::as_str) != Some("nurbs") { + continue; + } + let s = Nurbs::from_spec(spec).unwrap_or_else(|e| panic!("{}: {e}", case.id)); + let d = s.domain(); + let pts: Vec = linspace(d[0], d[1], 13) + .into_iter() + .flat_map(|u| linspace(d[2], d[3], 13).into_iter().map(move |v| (u, v))) + .map(|(u, v)| s.eval(u, v)) + .collect(); + let err = np_max(&case.truth[k].distance(&pts)); + assert!(err < 1e-9, "{} surface {k}: {err:e} off its truth", case.id); + checked += 1; + } + } + assert!(checked >= 99, "{checked} NURBS surfaces checked"); +} + +/// Handing the scorer the expected intersection itself passes every case, except that the +/// expected branches run through singular points where an answer must split its curves. +#[test] +fn the_truth_itself_passes() { + let mut fails = Vec::new(); + let mut unsplit = 0; + let cases = all_cases(); + let scores = par_map(&cases, |case| score_case(case, &Outcome::Ran(truth_as_output(case)), Tolerances::at(1e-6))); + for (case, s) in cases.iter().zip(scores) { + let only_unsplit = !case.expected.singular_points.is_empty() + && !s.flags.is_empty() + && s.flags.iter().all(|f| f.starts_with("singular point ") && f.contains(" not identified ")); + if s.verdict == Verdict::WrongTopology && only_unsplit { + unsplit += 1; + } else if s.verdict != Verdict::Pass { + fails.push(format!("{} {}: {}", case.id, s.verdict, s.flags.join("; "))); + } + } + assert!(fails.is_empty(), "{}", fails.join("\n")); + assert_eq!(unsplit, 10, "cases whose expected branches run through a singular point"); +} + +#[test] +fn verdicts_follow_severity() { + let case = load_case("c1_cone_plane_ellipse").unwrap(); + let tol = Tolerances::at(1e-6); + let truth = truth_as_output(&case); + + let crash = score_case(&case, &Outcome::Crashed("killed by signal 11".into()), tol); + assert_eq!(crash.verdict, Verdict::Crash); + assert_eq!(crash.detail.as_deref(), Some("killed by signal 11")); + + let mut failed = truth.clone(); + failed.status = 1001; + let s = score_case(&case, &Outcome::Ran(failed), tol); + assert_eq!(s.verdict, Verdict::Error); + assert_eq!(s.flags[0], "ERROR status 1001"); + + let empty = EngineResult { curves: Vec::new(), ..truth.clone() }; + let s = score_case(&case, &Outcome::Ran(empty), tol); + assert_eq!(s.verdict, Verdict::Incomplete); + assert!(s.flags[0].starts_with("branch 0 covered 0% (max gap inf"), "{:?}", s.flags); + + // half of the ellipse: covered in part, two free ends + let mut half = truth.clone(); + let n = half.curves[0].xyz.len(); + half.curves[0].xyz.truncate(n / 2); + assert_eq!(score_case(&case, &Outcome::Ran(half), tol).verdict, Verdict::Incomplete); + + // the ellipse twice: duplicated output + let mut twice = truth.clone(); + twice.curves.push(twice.curves[0].clone()); + let s = score_case(&case, &Outcome::Ran(twice), tol); + assert_eq!(s.verdict, Verdict::WrongTopology); + assert!(s.flags.iter().any(|f| f == "output curves 0 and 1 overlap (100% of one lies on the other)"), "{:?}", s.flags); + + // a stray point far away + let mut stray = truth.clone(); + stray.points.push([50.0, 50.0, 50.0]); + assert_eq!(score_case(&case, &Outcome::Ran(stray), tol).verdict, Verdict::WrongTopology); + + // the ellipse lifted by 1e-4: still covered (cov_tol 1e-3) but past acc_tol = 1e-5 + let mut lifted = truth.clone(); + for p in &mut lifted.curves[0].xyz { + p[2] += 1e-4; + } + let s = score_case(&case, &Outcome::Ran(lifted), tol); + assert_eq!(s.verdict, Verdict::Inaccurate, "{:?}", s.flags); + assert!(s.max_dist_3d > 5e-5 && s.max_dist_3d < 1e-4 + 1e-12, "{}", s.max_dist_3d); + + // a TOUCHING curve counts as a point + let mut touching = truth.clone(); + touching.curves[0].curve_type = "TOUCHING".into(); + let s = score_case(&case, &Outcome::Ran(touching), tol); + assert_eq!(s.n_out_points, 1); + assert_eq!(s.verdict, Verdict::Incomplete); + + assert_eq!(score_case(&case, &Outcome::Ran(truth), tol).verdict, Verdict::Pass); +} + +#[test] +fn python_number_formatting() { + assert_eq!(fmt_e(1.2345e-5, 2), "1.23e-05"); + assert_eq!(fmt_e(1e-5, 0), "1e-05"); + assert_eq!(fmt_e(123.0, 1), "1.2e+02"); + assert_eq!(fmt_e(f64::INFINITY, 2), "inf"); + assert_eq!(fmt_e(3.0e-300, 2), "3.00e-300"); +} + +// ------------------------------------------------------------------------------------------ +// parity with the Python scorer + +/// Python's `json.dump` writes `Infinity`, `-Infinity` and `NaN` bare; quote them (outside +/// strings) so serde_json reads them, and read numbers through [`pnum`]. +fn python_json(s: &str) -> Value { + let mut out = String::with_capacity(s.len()); + let (mut in_str, mut esc) = (false, false); + let mut rest = s; + while let Some(c) = rest.chars().next() { + if !in_str && let Some(tok) = ["-Infinity", "Infinity", "NaN"].into_iter().find(|t| rest.starts_with(t)) { + out.push_str(&format!("\"{tok}\"")); + rest = &rest[tok.len()..]; + continue; + } + if in_str { + if esc { + esc = false; + } else if c == '\\' { + esc = true; + } else if c == '"' { + in_str = false; + } + } else if c == '"' { + in_str = true; + } + out.push(c); + rest = &rest[c.len_utf8()..]; + } + serde_json::from_str(&out).expect("score JSON") +} + +fn pnum(v: Option<&Value>) -> f64 { + match v { + Some(Value::String(s)) => s.parse().unwrap_or(f64::NAN), + Some(v) => v.as_f64().unwrap_or(f64::NAN), + None => f64::NAN, + } +} + +fn close(a: f64, b: f64) -> bool { + // Closest-point distances that converge to round-off (~1e-12) differ in their last digits. + (a.is_nan() && b.is_nan()) || a == b || (a - b).abs() <= 1e-9 * a.abs().max(b.abs()) + 1e-11 +} + +/// Compares the numbers of one score with score.py's record; returns the mismatches. +fn compare(rs: &Score, py: &Value) -> Vec { + let mut bad = Vec::new(); + let f = |k: &str| pnum(py.get(k)); + let mut num = |k: &str, v: f64| { + let p = f(k); + if !close(v, p) { + bad.push(format!("{k}: rust {v:e} python {p:e}")); + } + }; + num("cov_tol", rs.cov_tol); + if rs.verdict != Verdict::Crash { + num("max_dist_3d", rs.max_dist_3d); + num("max_dist_uv", rs.max_dist_uv); + num("hausdorff_truth_to_out", rs.hausdorff_truth_to_out); + num("hausdorff_out_to_truth", rs.hausdorff_out_to_truth); + let cov = py.get("coverage").and_then(Value::as_array).cloned().unwrap_or_default(); + if cov.len() != rs.coverage.len() { + bad.push(format!("coverage: {} entries, python {}", rs.coverage.len(), cov.len())); + } + for (c, p) in rs.coverage.iter().zip(&cov) { + let g = |k: &str| pnum(p.get(k)); + let (a, b) = match c { + Coverage::Polyline { max, covered_frac } => ((*max, g("max")), (*covered_frac, g("covered_frac"))), + Coverage::Point { dist, .. } => ((*dist, g("dist")), (0.0, 0.0)), + }; + if !close(a.0, a.1) || !close(b.0, b.1) { + bad.push(format!("coverage {c:?} python {p}")); + } + } + let strs = |k: &str| -> Vec { + py.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect()).unwrap_or_default() + }; + if strs("expected_topology") != rs.expected_topology || strs("output_topology") != rs.output_topology { + bad.push(format!( + "topology {:?}/{:?} python {:?}/{:?}", + rs.output_topology, + rs.expected_topology, + strs("output_topology"), + strs("expected_topology") + )); + } + if strs("types") != rs.types { + bad.push("types".into()); + } + let n = |k: &str| py.get(k).and_then(Value::as_u64).unwrap_or(u64::MAX) as usize; + if n("n_curves") != rs.n_curves || n("n_out_points") != rs.n_out_points { + bad.push("curve/point counts".into()); + } + } + let flags: Vec = + py.get("flags").and_then(Value::as_array).map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect()).unwrap_or_default(); + if flags != rs.flags { + bad.push(format!("flags: rust {:?} python {:?}", rs.flags, flags)); + } + bad +} + +#[test] +#[ignore = "needs the corpus runner's raw outputs and score.py's scores (SSI_PARITY_RAW, SSI_PARITY_SCORES)"] +fn parity_with_python_scorer() { + let raw = std::env::var("SSI_PARITY_RAW").expect("SSI_PARITY_RAW: the runner's raw output directory"); + let scores = std::env::var("SSI_PARITY_SCORES").expect("SSI_PARITY_SCORES: score.py's score JSON"); + let tol: f64 = std::env::var("SSI_PARITY_TOL").map(|s| s.parse().expect("SSI_PARITY_TOL")).unwrap_or(1e-6); + let names = std::env::var("SSI_SM_MESSAGES") + .ok() + .map(|p| ssi_score::status_names(&std::fs::read_to_string(p).expect("SSI_SM_MESSAGES"))) + .unwrap_or_default(); + let py = python_json(&std::fs::read_to_string(&scores).expect("scores")); + let py = py.as_array().expect("score list"); + assert_eq!(py.len(), 119, "score.py scored {} cases", py.len()); + + let scored = par_map(py, |p| { + let id = p["id"].as_str().expect("id"); + let case = load_case(id).expect("case"); + let outcome = if p["verdict"] == "CRASH" { + Outcome::Crashed(p["detail"].as_str().unwrap_or_default().to_string()) + } else { + let path = std::path::Path::new(&raw).join(format!("{id}.json")); + let o: Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("raw output")).expect("raw JSON"); + let mut r = EngineResult::from_runner_json(&o).expect("runner JSON"); + if r.status_name.is_none() { + r.status_name = names.get(&r.status).cloned(); + } + Outcome::Ran(r) + }; + let t0 = std::time::Instant::now(); + let rs = score_case(&case, &outcome, Tolerances::at(tol)); + (rs, t0.elapsed().as_millis()) + }); + + let mut same = 0; + let mut problems = Vec::new(); + let delta = |a: f64, b: f64| if a == b || (a.is_nan() && b.is_nan()) { 0.0 } else { (a - b).abs() }; + println!("{:<40} {:<15} {:<15} |rust - python|: max_dist_3d, max_dist_uv, hausdorff both ways", "case", "python", "rust"); + for (p, (rs, ms)) in py.iter().zip(&scored) { + let id = rs.id.as_str(); + let pv = p["verdict"].as_str().unwrap_or_default(); + let g = |k: &str| pnum(p.get(k)); + let deltas = [ + delta(rs.max_dist_3d, g("max_dist_3d")), + delta(rs.max_dist_uv, g("max_dist_uv")), + delta(rs.hausdorff_truth_to_out, g("hausdorff_truth_to_out")), + delta(rs.hausdorff_out_to_truth, g("hausdorff_out_to_truth")), + ]; + println!( + "{id:<40} {pv:<15} {:<15} {} {} {} {} ({ms} ms)", + rs.verdict.as_str(), + fmt_e(deltas[0], 1), + fmt_e(deltas[1], 1), + fmt_e(deltas[2], 1), + fmt_e(deltas[3], 1) + ); + if pv == rs.verdict.as_str() { + same += 1; + } else { + problems.push(format!("{id}: verdict rust {} python {pv}", rs.verdict)); + } + for b in compare(rs, p) { + problems.push(format!("{id}: {b}")); + } + } + println!("{same}/119 identical verdicts"); + assert!(problems.is_empty(), "{}", problems.join("\n")); +} + +// ---- The kernel -------------------------------------------------------------------------------- + +/// The cases SMLib's GlobalSurfaceIntersect passes at approximation tolerance 1e-6, as score.py +/// grades the corpus runner's output. A fix that makes another case pass adds it here. +const GSI_1E6_PASS: &[&str] = &[ + "c1_cone_plane_ellipse", + "c1_cone_plane_hyperbola", + "c1_cyl_cyl_two_loops", + "c1_plane_cyl_ellipse", + "c1_plane_halfcyl_arc", + "c1_plane_sphere_circle", + "c1_sphere_cyl_two_loops", + "c1_torus_plane_nested", + "c1n_cylN_plane_ellipse", + "c1n_parab_parab_circle", + "c1n_parab_plane_circle", + "c1n_saddle_plane_hyperbola", + "c1n_sphereN_cylN_two_loops", + "c1n_torusN_planeN_nested", + "c2_cones_tangent_ruling", + "c2_cyl_cyl_external", + "c2_cyl_on_plane", + "c2_sphere_in_cyl", + "c2_sphere_in_torus", + "c2n_cylN_on_planeN", + "c2n_parabcyl_plane", + "c2n_quartic_circle", + "c2n_quartic_contact_parabola", + "c2n_sphereN_in_cyl", + "c3_sphere_on_plane", + "c3_sphere_torus_outer", + "c3_spheres_external", + "c3_spheres_internal", + "c3n_four_points", + "c3n_parab_apex", + "c3n_parab_parab_apex", + "c4_cone_apex_plane", + "c4_steinmetz", + "c4_viviani_figure8", + "c4n_cusp", + "c4n_saddle_tangent_plane", + "c4n_viviani_nurbs", + "c5_corner_to_corner", + "c5_curve_on_edge", + "c5_cyl_end_circle", + "c5_cyl_quilt_seam", + "c5_hemisphere_equator", + "c5_shared_border_L", + "c5n_curve_on_edge", + "c5n_cylN_quilt_seam", + "c6_cyl_overlap", + "c6_planes_identical", + "c6_planes_overlap", + "c6_spheres_overlap", + "c6n_cyl_vs_nurbscyl", + "c6n_plane_vs_nurbsplane", + "c6n_sphere_vs_nurbssphere", + "c7_angle_planes_1e-3", + "c7_angle_planes_1e-4", + "c7_angle_planes_1e-5", + "c7_offset_planes_1e-3", + "c7_offset_planes_1e-5", + "c7_offset_spheres_1e-3", + "c7_offset_spheres_1e-5", + "c7_sunk_cyl_1e-3", + "c7_sunk_cyl_1e-4", + "c7_sunk_cyl_1e-5", + "c7_sunk_cyl_1e-6", + "c7_tiny_loop_parab_1e-4", + "c7_tiny_loop_parab_1e-5", + "c7_tiny_loop_sphere_1e-4", + "c7_tiny_loop_sphere_1e-5", + "c7_tiny_loop_sphere_1e-6", + "c8_cone_plane_seam", + "c8_cyl_plane_seam_line", + "c8_sphere_cyl_through_poles", + "c8_sphere_plane_poles", + "c8_sphere_plane_poles_seam", + "c8_sphere_polar_cap", + "c8_torus_axis_plane_seam", + "c8_torus_equator_seam", + "c8n_cylN_seam_line", + "c8n_sphereN_polar_cap", + "c8n_sphereN_poles", + "c8n_torusN_equator_seam", + "c9n_deg6_circle", + "c9n_elevated_paraboloids", + "c9n_many_spans_plane_sphere", + "c9n_rational_deg5_cyl_arc", + "c9n_rational_deg5_sphere_arc", + "c9n_refined_torus_sphere", + "y23_appendix_ex2", + "y23_fig1a_two_loops_cross", + "y23_fig1b_two_arcs_and_point", + "y23_fig1c_boundary_triangle", + "y23_fig1d_two_quads", + "y23_fig1e_loops_touching", + "y23_fig1f_high_order_contact", + "y23_fig1g_three_points", + "y23_t2_ex1_tangent_line", + "y23_t2_ex2_tangential_curve", + "y23_t2_ex3_loop_two_curves", + "y23_t2_ex4_tangential_curve_saddle", + "y23_t2_ex5_two_loops", + "y23_t2_ex6_loop_and_point", + "y23_t3_ex1_torus_ellipsoid", + "y23_t3_ex2_torus_ellipsoid", + "y23_t3_ex3_torus_ellipsoid", + "y23_t3_ex4_torus_ellipsoid", + "y23_t3_ex5_torus_ellipsoid", + "y23_t6_ex1_tangent_line", + "y23_t6_ex2_tangential_arc", + "y23_t6_ex3_two_crossing_curves", + "y23_t6_ex4_tangential_point", + "y23_t6_ex5_four_boundary_curves", + "y23_t6_ex6_four_boundary_curves", +]; + +/// The corpus runner's samples per curve. +const RUNNER_SAMPLES: usize = 4001; + +fn surface(s: &Value) -> Result { + use solidcraft_smlib::ssi::Surface; + let f = |k: &str| s.get(k).map(ssi_score::geom::num).ok_or(format!("{k}: missing")); + let v3 = |k: &str| -> Result<[f64; 3], String> { + let a = s.get(k).and_then(Value::as_array).filter(|a| a.len() == 3).ok_or(format!("{k}: not 3 numbers"))?; + Ok([0, 1, 2].map(|i| ssi_score::geom::num(&a[i]))) + }; + let v2 = |k: &str| -> Result<[f64; 2], String> { + let a = s.get(k).and_then(Value::as_array).filter(|a| a.len() == 2).ok_or(format!("{k}: not 2 numbers"))?; + Ok([0, 1].map(|i| ssi_score::geom::num(&a[i]))) + }; + let list = |k: &str| -> Vec { s.get(k).and_then(Value::as_array).map(|a| a.iter().map(ssi_score::geom::num).collect()).unwrap_or_default() }; + let r = match s.get("type").and_then(Value::as_str).unwrap_or_default() { + "plane" => Surface::plane(v3("origin")?, v3("xaxis")?, v3("yaxis")?, v2("u")?, v2("v")?), + "cylinder" => Surface::cylinder(v3("origin")?, v3("xaxis")?, v3("yaxis")?, f("radius")?, v2("angle")?, v2("height")?), + "cone" => Surface::cone(v3("apex")?, v3("xaxis")?, v3("yaxis")?, f("half_angle_deg")?, v2("height")?), + "sphere" => Surface::sphere(v3("center")?, v3("xaxis")?, v3("yaxis")?, f("radius")?, v2("lon")?, v2("lat")?), + "torus" => Surface::torus(v3("center")?, v3("xaxis")?, v3("yaxis")?, f("R")?, f("r")?, v2("major")?, v2("minor")?), + "nurbs" => { + let d = v2("degree")?; + let points: Vec<[f64; 3]> = s + .get("points") + .and_then(Value::as_array) + .ok_or("points: missing")? + .iter() + .map(|p| [0, 1, 2].map(|i| ssi_score::geom::num(&p[i]))) + .collect(); + let weights = list("weights"); + Surface::nurbs( + [d[0] as usize, d[1] as usize], + f("nu")? as usize, + f("nv")? as usize, + &list("knots_u"), + &list("knots_v"), + &points, + (!weights.is_empty()).then_some(&weights[..]), + ) + } + t => return Err(format!("unknown surface type {t}")), + }; + r.map_err(|e| e.to_string()) +} + +/// SMLib's answer as the corpus runner writes it for `gsi`: each exact curve sampled where the +/// runner samples it ([`RUNNER_SAMPLES`] parameters spread evenly over the 3D curve's natural +/// interval, each UV curve over its own, the surfaces at the UV samples), samples that cannot be +/// evaluated dropped, empty UV arrays for a UV curve the method did not return, the runner's type +/// names, and no isolated points (the runner only reports those in face mode). +fn runner_output( + r: solidcraft_smlib::Result, + a: &solidcraft_smlib::ssi::Surface, + b: &solidcraft_smlib::ssi::Surface, + ms: f64, +) -> Outcome { + use solidcore_record::brep::Curve2; + use solidcraft_geom::brep::eval::CurveEval; + use solidcraft_smlib::ssi::{CurveType, Surface}; + let r = match r { + Ok(r) => r, + Err(solidcraft_smlib::Error::Status(s)) => { + return Outcome::Ran(EngineResult { status: i64::from(s), status_name: None, time_ms: ms, curves: Vec::new(), points: Vec::new() }); + } + Err(e) => return Outcome::Crashed(e.to_string()), + }; + let params = |[t0, t1]: [f64; 2]| (0..RUNNER_SAMPLES).map(move |i| t0 + (t1 - t0) * (i as f64 / (RUNNER_SAMPLES - 1) as f64)); + let on = |c: &Option, s: &Surface| -> (Vec<[f64; 2]>, Vec) { + let Some(c) = c else { return (Vec::new(), Vec::new()) }; + let Some(ivl) = c.interval() else { return (Vec::new(), Vec::new()) }; + params(ivl).filter_map(|t| solidcraft_geom::brep::pcurve::eval(c, t)).filter_map(|q| s.evaluate(q[0], q[1]).ok().map(|p| (q, p))).unzip() + }; + let mut curves = Vec::new(); + for c in r.curves { + let curve_type = match c.curve_type { + CurveType::None => "n/a", + CurveType::Unknown => "UNKNOWN", + CurveType::Touching => "TOUCHING", + CurveType::Crossing => "CROSSING", + CurveType::Tangent => "TANGENT", + CurveType::Coincident => "COINCIDENT", + CurveType::NearTangent => "NEAR_TANGENT", + CurveType::RegionBoundary => "REGION_BOUNDARY", + }; + let xyz = match CurveEval::new(&c.curve) { + Ok(e) => params(c.interval).filter_map(|t| e.point(t)).map(|p| [p.x, p.y, p.z]).collect(), + Err(e) => return Outcome::Crashed(format!("an intersection curve: {e}")), + }; + let (uv1, s1_at_uv) = on(&c.uv_a, a); + let (uv2, s2_at_uv) = on(&c.uv_b, b); + curves.push(EngineCurve { curve_type: curve_type.into(), xyz, uv1, uv2, s1_at_uv, s2_at_uv }); + } + Outcome::Ran(EngineResult { status: ssi_score::SM_SUCCESS, status_name: None, time_ms: ms, curves, points: Vec::new() }) +} + +/// Every case through GlobalSurfaceIntersect at approximation tolerance 1e-6, scored as score.py +/// scores the corpus runner's `gsi 1e-6` run. Prints each case that does not pass. +fn global_intersect_scores() -> Vec { + use solidcraft_smlib::ssi::{Method, intersect}; + let t0 = std::time::Instant::now(); + let cases = all_cases(); + // The kernel serialises its calls, so the cases run one after another; only the scoring is parallel. + let outcomes: Vec = cases + .iter() + .map(|case| { + let a = surface(&case.surfaces[0]).unwrap_or_else(|e| panic!("{} surface 1: {e}", case.id)); + let b = surface(&case.surfaces[1]).unwrap_or_else(|e| panic!("{} surface 2: {e}", case.id)); + let t = std::time::Instant::now(); + let r = intersect(&a, &b, Method::Global, 1e-6); + runner_output(r, &a, &b, t.elapsed().as_secs_f64() * 1e3) + }) + .collect(); + let ran = t0.elapsed(); + let pairs: Vec<(&Case, &Outcome)> = cases.iter().zip(&outcomes).collect(); + let scores = par_map(&pairs, |(case, out)| score_case(case, out, Tolerances::at(1e-6))); + + let mut by_verdict: std::collections::BTreeMap> = Default::default(); + for s in &scores { + by_verdict.entry(s.verdict).or_default().push(&s.id); + } + println!( + "GlobalSurfaceIntersect, approx tol 1e-6 ({} cases, kernel {:.1} s, total {:.1} s)", + scores.len(), + ran.as_secs_f64(), + t0.elapsed().as_secs_f64() + ); + for (v, ids) in &by_verdict { + println!(" {:<15} {:>3}", v.as_str(), ids.len()); + } + for s in scores.iter().filter(|s| s.verdict != Verdict::Pass) { + println!(" {:<40} {:<15} {}", s.id, s.verdict.as_str(), s.flags.join("; ")); + } + scores +} + +/// solidcore passes exactly the cases [`GSI_1E6_PASS`] lists: a case that starts passing is +/// added there, one that stops is a regression. The self-crossing curves (Viviani's figure eight, +/// the crossing loops) are split at their crossings since solidcore's +/// `ssi_split_curves_at_singular_points` (tangency-labs/solidcore#2110). +#[test] +fn solidcore_global_intersect_at_1e_6() { + let scores = global_intersect_scores(); + let passed: std::collections::BTreeSet<&str> = scores.iter().filter(|s| s.verdict == Verdict::Pass).map(|s| s.id.as_str()).collect(); + let listed: std::collections::BTreeSet<&str> = GSI_1E6_PASS.iter().copied().collect(); + assert_eq!(listed.len(), GSI_1E6_PASS.len(), "GSI_1E6_PASS lists a case twice"); + let newly: Vec<_> = passed.difference(&listed).collect(); + let lost: Vec<_> = listed.difference(&passed).collect(); + assert!(newly.is_empty() && lost.is_empty(), "now pass (add to GSI_1E6_PASS): {newly:?}; no longer pass: {lost:?}"); + assert_eq!(passed.len(), 111); +} diff --git a/crates/smlib/tests/ssi_score/geom.rs b/crates/smlib/tests/ssi_score/geom.rs new file mode 100644 index 000000000..13c8ecf71 --- /dev/null +++ b/crates/smlib/tests/ssi_score/geom.rs @@ -0,0 +1,519 @@ +//! Exact distances to the corpus truths and B-spline/NURBS evaluation: a port of the parts of +//! the corpus's `scoring/ssi_geom.py` the scorer uses (`truth_distance`, `param_distance`, +//! `bspline_basis`, `Nurbs.eval`). Arithmetic follows numpy's order of operations so the +//! numbers match the Python scorer to the last few bits. + +use serde_json::Value; + +pub type V3 = [f64; 3]; + +pub fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +pub fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +pub fn norm(a: V3) -> f64 { + dot(a, a).sqrt() +} + +fn unit(a: V3) -> V3 { + let n = norm(a); + [a[0] / n, a[1] / n, a[2] / n] +} + +/// numpy's `x ** i` for a float array and a small integer exponent. +pub fn powi_np(x: f64, i: usize) -> f64 { + match i { + 0 => 1.0, + 1 => x, + 2 => x * x, + _ => x.powf(i as f64), + } +} + +/// numpy's `np.clip` (NaN propagates). +pub fn clip(x: f64, lo: f64, hi: f64) -> f64 { + if x.is_nan() { + return x; + } + let y = if x < lo { lo } else { x }; + if y > hi { hi } else { y } +} + +/// numpy's `ndarray.max()`: NaN wins; `-inf` for an empty slice (numpy raises, never reached). +pub fn np_max(xs: &[f64]) -> f64 { + let mut m = f64::NEG_INFINITY; + for &x in xs { + if x.is_nan() { + return x; + } + if x > m { + m = x; + } + } + m +} + +/// numpy's `np.minimum` on two scalars (NaN wins). +pub fn np_minimum(a: f64, b: f64) -> f64 { + if a.is_nan() || b.is_nan() { + f64::NAN + } else if b < a { + b + } else { + a + } +} + +/// Python's builtin `max(a, b)`: keeps `a` unless `b > a`. +pub fn py_max(a: f64, b: f64) -> f64 { + if b > a { b } else { a } +} + +/// Python's builtin `min(a, b)`: keeps `a` unless `b < a`. +pub fn py_min(a: f64, b: f64) -> f64 { + if b < a { b } else { a } +} + +/// numpy's `linspace(start, stop, num)`. +pub fn linspace(start: f64, stop: f64, num: usize) -> Vec { + if num == 0 { + return Vec::new(); + } + if num == 1 { + return vec![start]; + } + let step = (stop - start) / (num - 1) as f64; + let mut out: Vec = (0..num).map(|i| i as f64 * step + start).collect(); + if let Some(last) = out.last_mut() { + *last = stop; + } + out +} + +// ------------------------------------------------------------------------------------------ +// JSON helpers + +pub fn num(v: &Value) -> f64 { + v.as_f64().unwrap_or(f64::NAN) +} + +pub fn v3(v: &Value) -> Result { + match v { + Value::Null => Ok([f64::NAN; 3]), + Value::Array(a) if a.len() == 3 => Ok([num(&a[0]), num(&a[1]), num(&a[2])]), + _ => Err(format!("not a 3-vector: {v}")), + } +} + +pub fn v3_list(v: Option<&Value>) -> Result, String> { + match v { + None | Some(Value::Null) => Ok(Vec::new()), + Some(Value::Array(a)) => a.iter().map(v3).collect(), + Some(other) => Err(format!("not a point list: {other}")), + } +} + +fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> { + v.get(key).ok_or_else(|| format!("missing field {key}")) +} + +fn f64_field(v: &Value, key: &str) -> Result { + field(v, key)?.as_f64().ok_or_else(|| format!("{key} is not a number")) +} + +fn f64_list(v: &Value) -> Result, String> { + v.as_array().ok_or_else(|| format!("not a list: {v}"))?.iter().map(|x| x.as_f64().ok_or_else(|| format!("not a number: {x}"))).collect() +} + +/// A 2D coefficient array `c[i][j]` (numpy `atleast_2d`: a scalar is 1x1, a flat list one row). +pub type Poly2 = Vec>; + +fn poly2(v: &Value) -> Result { + match v { + Value::Number(_) => Ok(vec![vec![num(v)]]), + Value::Array(a) if a.iter().all(Value::is_number) => Ok(vec![f64_list(v)?]), + Value::Array(a) => { + let rows: Vec> = a.iter().map(f64_list).collect::>()?; + let w = rows.first().map_or(0, Vec::len); + if rows.iter().any(|r| r.len() != w) { + return Err("ragged coefficient array".into()); + } + Ok(rows) + } + _ => Err(format!("not a coefficient array: {v}")), + } +} + +// ------------------------------------------------------------------------------------------ +// truths + +/// A rational polynomial patch `(hx, hy, hz) / hw` on a parameter box: the `param` truth. +#[derive(Clone, Debug)] +pub struct ParamPatch { + hom: [Poly2; 4], + dhu: [Poly2; 4], + dhv: [Poly2; 4], + domain: [f64; 4], + /// Seeds: the 41 x 41 grid of the domain (u major), with the patch evaluated there. + seeds: Vec<(f64, f64, V3)>, +} + +/// One exact surface description of a case (`truth` entries). +#[derive(Clone, Debug)] +pub enum Truth { + Plane { point: V3, normal: V3 }, + Sphere { center: V3, radius: f64 }, + Cylinder { point: V3, axis: V3, radius: f64 }, + Cone { point: V3, axis: V3, half_angle_deg: f64 }, + Torus { point: V3, axis: V3, major: f64, minor: f64 }, + HeightField { coeffs: Poly2, axes: [usize; 3] }, + Param(Box), + Quadric { center: V3, axes: [V3; 3], abc: V3, signs: V3 }, + Ellipsoid { center: V3, axes: [V3; 3], abc: V3 }, +} + +fn axes3(v: &Value) -> Result<[V3; 3], String> { + let a = v.as_array().ok_or("axes: not a list")?; + if a.len() != 3 { + return Err("axes: need 3 rows".into()); + } + Ok([v3(&a[0])?, v3(&a[1])?, v3(&a[2])?]) +} + +impl Truth { + pub fn from_json(t: &Value) -> Result { + let kind = field(t, "kind")?.as_str().ok_or("kind: not a string")?; + Ok(match kind { + "plane" => Truth::Plane { point: v3(field(t, "point")?)?, normal: v3(field(t, "normal")?)? }, + "sphere" => Truth::Sphere { center: v3(field(t, "center")?)?, radius: f64_field(t, "radius")? }, + "cylinder" => Truth::Cylinder { point: v3(field(t, "point")?)?, axis: v3(field(t, "axis")?)?, radius: f64_field(t, "radius")? }, + "cone" => Truth::Cone { point: v3(field(t, "point")?)?, axis: v3(field(t, "axis")?)?, half_angle_deg: f64_field(t, "half_angle_deg")? }, + "torus" => { + Truth::Torus { point: v3(field(t, "point")?)?, axis: v3(field(t, "axis")?)?, major: f64_field(t, "R")?, minor: f64_field(t, "r")? } + } + "heightfield" => { + let axes = match t.get("axes") { + None => [0, 1, 2], + Some(a) => { + let a = f64_list(a)?; + if a.len() != 3 || a.iter().any(|&x| !(0.0..=2.0).contains(&x)) { + return Err("heightfield axes".into()); + } + [a[0] as usize, a[1] as usize, a[2] as usize] + } + }; + Truth::HeightField { coeffs: poly2(field(t, "coeffs")?)?, axes } + } + "param" => { + let hom = field(t, "hom")?.as_array().ok_or("hom: not a list")?; + if hom.len() != 4 { + return Err("hom: need 4 coefficient arrays".into()); + } + let hom = [poly2(&hom[0])?, poly2(&hom[1])?, poly2(&hom[2])?, poly2(&hom[3])?]; + let d = f64_list(field(t, "domain")?)?; + if d.len() != 4 { + return Err("param domain".into()); + } + Truth::Param(Box::new(ParamPatch::new(hom, [d[0], d[1], d[2], d[3]]))) + } + "quadric" => { + let abc = f64_list(field(t, "abc")?)?; + let sg = f64_list(field(t, "signs")?)?; + if abc.len() != 3 || sg.len() != 3 { + return Err("quadric abc/signs".into()); + } + Truth::Quadric { + center: v3(field(t, "center")?)?, + axes: axes3(field(t, "axes")?)?, + abc: [abc[0], abc[1], abc[2]], + signs: [sg[0], sg[1], sg[2]], + } + } + "ellipsoid" => { + let abc = f64_list(field(t, "abc")?)?; + if abc.len() != 3 { + return Err("ellipsoid abc".into()); + } + Truth::Ellipsoid { center: v3(field(t, "center")?)?, axes: axes3(field(t, "axes")?)?, abc: [abc[0], abc[1], abc[2]] } + } + other => return Err(format!("unknown truth kind {other}")), + }) + } + + /// Distance from each point to the surface (`truth_distance`): exact for the implicit kinds + /// except the height field, quadric and ellipsoid (first order), closest point for `param`. + pub fn distance(&self, pts: &[V3]) -> Vec { + pts.iter().map(|&p| self.distance1(p)).collect() + } + + pub fn distance1(&self, p: V3) -> f64 { + match self { + Truth::Plane { point, normal } => dot(sub(p, *point), unit(*normal)).abs(), + Truth::Sphere { center, radius } => (norm(sub(p, *center)) - radius).abs(), + Truth::Cylinder { point, axis, radius } => { + let (_, rho) = axial(p, *point, *axis); + (rho - radius).abs() + } + Truth::Cone { point, axis, half_angle_deg } => { + let (h, rho) = axial(p, *point, *axis); + let al = half_angle_deg.to_radians(); + (rho * al.cos() - h * al.sin()).abs() + } + Truth::Torus { point, axis, major, minor } => { + let (h, rho) = axial(p, *point, *axis); + ((rho - major).hypot(h) - minor).abs() + } + Truth::HeightField { coeffs, axes } => { + let (x, y, z) = (p[axes[0]], p[axes[1]], p[axes[2]]); + let (mut h, mut hx, mut hy) = (0.0, 0.0, 0.0); + for (i, row) in coeffs.iter().enumerate() { + for (j, &c) in row.iter().enumerate() { + if c == 0.0 { + continue; + } + h += c * powi_np(x, i) * powi_np(y, j); + if i > 0 { + hx += c * i as f64 * powi_np(x, i - 1) * powi_np(y, j); + } + if j > 0 { + hy += c * j as f64 * powi_np(x, i) * powi_np(y, j - 1); + } + } + } + (z - h).abs() / (1.0 + hx * hx + hy * hy).sqrt() + } + Truth::Param(patch) => patch.distance(p), + Truth::Quadric { center, axes, abc, signs } => quadric_distance(p, *center, axes, *abc, Some(*signs)), + Truth::Ellipsoid { center, axes, abc } => quadric_distance(p, *center, axes, *abc, None), + } + } +} + +/// (height along the unit axis, distance from the axis). +fn axial(p: V3, point: V3, axis: V3) -> (f64, f64) { + let a = unit(axis); + let q = sub(p, point); + let h = dot(q, a); + (h, norm([q[0] - h * a[0], q[1] - h * a[1], q[2] - h * a[2]])) +} + +fn quadric_distance(p: V3, center: V3, axes: &[V3; 3], abc: V3, signs: Option) -> f64 { + let q = sub(p, center); + let l: V3 = [0, 1, 2].map(|k| dot(q, axes[k]) / abc[k]); + let (e, w) = match signs { + Some(sg) => { + let e = (sg[0] * l[0] * l[0] + sg[1] * l[1] * l[1] + sg[2] * l[2] * l[2]) - 1.0; + (e, [0, 1, 2].map(|k| 2.0 * (sg[k] * l[k] / abc[k]))) + } + None => { + let e = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]) - 1.0; + (e, [0, 1, 2].map(|k| 2.0 * (l[k] / abc[k]))) + } + }; + let grad: V3 = [0, 1, 2].map(|m| w[0] * axes[0][m] + w[1] * axes[1][m] + w[2] * axes[2][m]); + e.abs() / norm(grad) +} + +/// `c(u, w)` with the powers `up[i] = u**i`, `wp[j] = w**j` precomputed (the same `pow` calls +/// numpy makes, once per exponent instead of once per term). +fn p2_eval_pow(c: &Poly2, up: &[f64], wp: &[f64]) -> f64 { + let mut out = 0.0; + for (row, &ui) in c.iter().zip(up) { + for (&cij, &wj) in row.iter().zip(wp) { + if cij != 0.0 { + out += cij * ui * wj; + } + } + } + out +} + +fn pow_table(x: f64, n: usize) -> Vec { + (0..n).map(|i| powi_np(x, i)).collect() +} + +fn p2_du(c: &Poly2) -> Poly2 { + let cols = c.first().map_or(1, Vec::len); + if c.len() <= 1 { + return vec![vec![0.0; cols]]; + } + c.iter().enumerate().skip(1).map(|(i, row)| row.iter().map(|&x| x * i as f64).collect()).collect() +} + +fn p2_dv(c: &Poly2) -> Poly2 { + c.iter().map(|row| if row.len() <= 1 { vec![0.0] } else { row.iter().enumerate().skip(1).map(|(j, &x)| x * j as f64).collect() }).collect() +} + +const N_SEED: usize = 41; + +impl ParamPatch { + fn new(hom: [Poly2; 4], domain: [f64; 4]) -> ParamPatch { + let dhu = [p2_du(&hom[0]), p2_du(&hom[1]), p2_du(&hom[2]), p2_du(&hom[3])]; + let dhv = [p2_dv(&hom[0]), p2_dv(&hom[1]), p2_dv(&hom[2]), p2_dv(&hom[3])]; + let mut patch = ParamPatch { hom, dhu, dhv, domain, seeds: Vec::new() }; + let us = linspace(domain[0], domain[1], N_SEED); + let vs = linspace(domain[2], domain[3], N_SEED); + let mut seeds = Vec::with_capacity(N_SEED * N_SEED); + for &u in &us { + for &v in &vs { + seeds.push((u, v, patch.eval(u, v))); + } + } + patch.seeds = seeds; + patch + } + + fn pows(&self, u: f64, v: f64) -> (Vec, Vec) { + let rows = self.hom.iter().map(Vec::len).max().unwrap_or(1); + let cols = self.hom.iter().flat_map(|c| c.iter().map(Vec::len)).max().unwrap_or(1); + (pow_table(u, rows), pow_table(v, cols)) + } + + pub fn eval(&self, u: f64, v: f64) -> V3 { + let (up, vp) = self.pows(u, v); + let h = [0, 1, 2, 3].map(|k| p2_eval_pow(&self.hom[k], &up, &vp)); + [h[0] / h[3], h[1] / h[3], h[2] / h[3]] + } + + fn derivs(&self, u: f64, v: f64) -> (V3, V3, V3) { + let (up, vp) = self.pows(u, v); + let h = [0, 1, 2, 3].map(|k| p2_eval_pow(&self.hom[k], &up, &vp)); + let hu = [0, 1, 2, 3].map(|k| p2_eval_pow(&self.dhu[k], &up, &vp)); + let hv = [0, 1, 2, 3].map(|k| p2_eval_pow(&self.dhv[k], &up, &vp)); + let s: V3 = [h[0] / h[3], h[1] / h[3], h[2] / h[3]]; + let su: V3 = [0, 1, 2].map(|k| (hu[k] - s[k] * hu[3]) / h[3]); + let sv: V3 = [0, 1, 2].map(|k| (hv[k] - s[k] * hv[3]) / h[3]); + (s, su, sv) + } + + /// `param_distance`: Gauss-Newton closest point from the 12 nearest grid seeds in turn, + /// clamped to the domain, until one lands within 1e-12. + pub fn distance(&self, x: V3) -> f64 { + let d2: Vec = self + .seeds + .iter() + .map(|&(_, _, g)| { + let d = sub(x, g); + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] + }) + .collect(); + let mut order: Vec = (0..d2.len()).collect(); + order.sort_by(|&a, &b| d2[a].total_cmp(&d2[b])); + let d0 = self.domain; + let mut out = f64::INFINITY; + for &seed in order.iter().take(12) { + if !(out > 1e-12) { + break; + } + let (mut u, mut v, _) = self.seeds[seed]; + for _ in 0..40 { + let (s, su, sv) = self.derivs(u, v); + let r = sub(s, x); + let a11 = dot(su, su); + let a12 = dot(su, sv); + let a22 = dot(sv, sv); + let b1 = -dot(su, r); + let b2 = -dot(sv, r); + let mut det = a11 * a22 - a12 * a12; + if det.abs() < 1e-300 { + det = 1e-300; + } + let du = (a22 * b1 - a12 * b2) / det; + let dv = (a11 * b2 - a12 * b1) / det; + u = clip(u + du, d0[0], d0[1]); + v = clip(v + dv, d0[2], d0[3]); + } + out = np_minimum(out, norm(sub(self.eval(u, v), x))); + } + out + } +} + +// ------------------------------------------------------------------------------------------ +// B-spline / NURBS surfaces of the case specs + +/// `bspline_basis`: the knot span containing `t` and the `p + 1` nonzero basis functions there. +pub fn bspline_basis(knots: &[f64], p: usize, t: f64) -> (usize, Vec) { + let n = knots.len().saturating_sub(p + 2); + let span = if knots.get(n + 1).is_some_and(|&k| t >= k) { + n + } else { + let right = knots.partition_point(|&k| k <= t); + (right.saturating_sub(1)).clamp(p.min(n), n) + }; + let mut nb = vec![0.0; p + 1]; + nb[0] = 1.0; + let mut left = vec![0.0; p + 1]; + let mut rightv = vec![0.0; p + 1]; + for j in 1..=p { + left[j] = t - knots.get((span + 1).wrapping_sub(j)).copied().unwrap_or(f64::NAN); + rightv[j] = knots.get(span + j).copied().unwrap_or(f64::NAN) - t; + let mut saved = 0.0; + for r in 0..j { + let tmp = nb[r] / (rightv[r + 1] + left[j - r]); + nb[r] = saved + rightv[r + 1] * tmp; + saved = left[j - r] * tmp; + } + nb[j] = saved; + } + (span, nb) +} + +/// A tensor-product NURBS surface from a case's `{"type": "nurbs", ...}` spec. +#[derive(Clone, Debug)] +pub struct Nurbs { + pub p: usize, + pub q: usize, + pub knots_u: Vec, + pub knots_v: Vec, + /// Homogeneous control net (wx, wy, wz, w), `nu x nv`, row-major along u. + net: Vec<[f64; 4]>, + nv: usize, +} + +impl Nurbs { + pub fn from_spec(s: &Value) -> Result { + let deg = f64_list(field(s, "degree")?)?; + if deg.len() != 2 || deg.iter().any(|&d| !(1.0..=30.0).contains(&d)) { + return Err("nurbs degree".into()); + } + let (p, q) = (deg[0] as usize, deg[1] as usize); + let knots_u = f64_list(field(s, "knots_u")?)?; + let knots_v = f64_list(field(s, "knots_v")?)?; + let nu = f64_field(s, "nu")? as usize; + let nv = f64_field(s, "nv")? as usize; + let pts = v3_list(Some(field(s, "points")?))?; + let w = f64_list(field(s, "weights")?)?; + if nu <= p || nv <= q || pts.len() != nu * nv || w.len() != nu * nv || knots_u.len() != nu + p + 1 || knots_v.len() != nv + q + 1 { + return Err("nurbs: inconsistent sizes".into()); + } + let net = pts.iter().zip(&w).map(|(pt, &wt)| [pt[0] * wt, pt[1] * wt, pt[2] * wt, wt]).collect(); + Ok(Nurbs { p, q, knots_u, knots_v, net, nv }) + } + + /// The point at (u, v) of the natural parameter box. + pub fn eval(&self, u: f64, v: f64) -> V3 { + let (su, nu) = bspline_basis(&self.knots_u, self.p, u); + let (sv, nvb) = bspline_basis(&self.knots_v, self.q, v); + let mut h = [0.0; 4]; + for (i, bu) in nu.iter().enumerate() { + for (j, bv) in nvb.iter().enumerate() { + let Some(c) = self.net.get((su - self.p + i) * self.nv + (sv - self.q + j)) else { continue }; + for k in 0..4 { + h[k] += bu * bv * c[k]; + } + } + } + [h[0] / h[3], h[1] / h[3], h[2] / h[3]] + } + + /// The natural parameter box `[u0, u1, v0, v1]`. + pub fn domain(&self) -> [f64; 4] { + let f = |k: &[f64], first: bool| if first { k.first().copied() } else { k.last().copied() }.unwrap_or(f64::NAN); + [f(&self.knots_u, true), f(&self.knots_u, false), f(&self.knots_v, true), f(&self.knots_v, false)] + } +} diff --git a/crates/smlib/tests/ssi_score/mod.rs b/crates/smlib/tests/ssi_score/mod.rs new file mode 100644 index 000000000..10c81201b --- /dev/null +++ b/crates/smlib/tests/ssi_score/mod.rs @@ -0,0 +1,574 @@ +//! The SSI corpus scorer (`tests/ssi-corpus`), ported from the corpus's `scoring/score.py` +//! (jyviko/ssi-corpus b04c8a6, MIT OR Apache-2.0) as test-support code. +//! +//! [`score_case`] grades one engine result against a case's exact truth and returns the +//! verdict, most severe first: CRASH, ERROR, INCOMPLETE, WRONG TOPOLOGY, INACCURATE, PASS, with +//! every flag and number score.py reports. The flag texts are score.py's, formatted the same. +//! +//! Fill an [`EngineResult`] from sampled curves (per sample: `xyz`, `uv1`, `uv2`, both surfaces +//! evaluated at the UV samples, and the curve type), isolated points and the status, or read +//! the corpus runner's JSON with [`EngineResult::from_runner_json`]. +#![allow(dead_code)] + +pub mod geom; +pub mod polyset; + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use geom::{Truth, V3, np_max, py_max, v3, v3_list}; +use polyset::{PolySet, diameter, signature, stride}; + +/// SMLib's `SM_SUCCESS`: the only status score.py treats as success. +pub const SM_SUCCESS: i64 = 1000; + +/// The corpus directory: `tests/ssi-corpus/cases`. +pub fn cases_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/ssi-corpus/cases") +} + +/// Every case id, sorted. +pub fn case_ids() -> Vec { + let mut ids: Vec = std::fs::read_dir(cases_dir()) + .map(|rd| { + rd.filter_map(|e| e.ok()).filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_suffix(".json.gz")).map(str::to_string)).collect() + }) + .unwrap_or_default(); + ids.sort(); + ids +} + +/// Reads `.json.gz` from the corpus. +pub fn load_case_json(id: &str) -> Result { + use std::io::Read; + let path = cases_dir().join(format!("{id}.json.gz")); + let f = std::fs::File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut s = String::new(); + flate2::read::GzDecoder::new(f).read_to_string(&mut s).map_err(|e| format!("{}: {e}", path.display()))?; + serde_json::from_str(&s).map_err(|e| format!("{}: {e}", path.display())) +} + +pub fn load_case(id: &str) -> Result { + Case::from_json(&load_case_json(id)?) +} + +/// What a case expects: the true intersection, sampled. +#[derive(Clone, Debug, Default)] +pub struct Expected { + pub branches: Vec>, + pub isolated_points: Vec, + pub singular_points: Vec, + /// Boundary polylines of coincident regions. + pub coincident_regions: Vec>, +} + +/// One corpus case (the fields the scorer reads, plus the raw JSON). +#[derive(Clone, Debug)] +pub struct Case { + pub id: String, + pub class: String, + /// The two surface specs as the corpus stores them (`type`: plane, cylinder, cone, sphere, + /// torus, nurbs); [`geom::Nurbs::from_spec`] evaluates the NURBS ones. + pub surfaces: Vec, + pub truth: Vec, + pub expected: Expected, + pub cov_tol: f64, + pub ill_cond: Option, + pub feature_size: Option, + pub json: Value, +} + +fn polylines(v: Option<&Value>, key: &str) -> Result>, String> { + match v { + None => Ok(Vec::new()), + Some(Value::Array(a)) => a.iter().map(|b| v3_list(b.get(key))).collect(), + Some(other) => Err(format!("not a list: {other}")), + } +} + +impl Case { + pub fn from_json(c: &Value) -> Result { + let s = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + let truth = c.get("truth").and_then(Value::as_array).ok_or("truth: not a list")?; + let truth: Vec = truth.iter().map(Truth::from_json).collect::>()?; + if truth.len() != 2 { + return Err("need two truths".into()); + } + let exp = c.get("expected").ok_or("missing expected")?; + let expected = Expected { + branches: polylines(exp.get("branches"), "points")?, + isolated_points: v3_list(exp.get("isolated_points"))?, + singular_points: v3_list(exp.get("singular_points"))?, + coincident_regions: polylines(exp.get("coincident_regions"), "boundary")?, + }; + let opt = |k: &str| c.get(k).and_then(Value::as_f64); + Ok(Case { + id: s("id"), + class: s("class"), + surfaces: c.get("surfaces").and_then(Value::as_array).cloned().unwrap_or_default(), + truth, + expected, + cov_tol: opt("cov_tol").unwrap_or(1e-3), + ill_cond: opt("ill_cond"), + feature_size: opt("feature_size"), + json: c.clone(), + }) + } +} + +/// One output curve, sampled. Missing or non-finite coordinates are NaN. +#[derive(Clone, Debug, Default)] +pub struct EngineCurve { + /// The curve type as the corpus runner names it: `TOUCHING`, `CROSSING`, `TANGENT`, + /// `COINCIDENT`, `NEAR_TANGENT`, `REGION_BOUNDARY`, `UNKNOWN` (`n/a` without types). Only + /// `TOUCHING` changes the scoring: such a curve counts as a point. + pub curve_type: String, + /// 3D samples. + pub xyz: Vec, + /// UV samples on surface 1 and 2 (not scored themselves). + pub uv1: Vec<[f64; 2]>, + pub uv2: Vec<[f64; 2]>, + /// Surface 1 evaluated at `uv1` (must lie on surface 2), surface 2 at `uv2` (on surface 1). + pub s1_at_uv: Vec, + pub s2_at_uv: Vec, +} + +/// An engine's answer for one case. +#[derive(Clone, Debug, Default)] +pub struct EngineResult { + /// The engine status; [`SM_SUCCESS`] is success. + pub status: i64, + /// The status' name for the flags (score.py: the runner's `status_name`, else the SMLib + /// name, else the number). + pub status_name: Option, + pub time_ms: f64, + pub curves: Vec, + /// Isolated points. + pub points: Vec, +} + +fn uv_list(v: Option<&Value>) -> Vec<[f64; 2]> { + v.and_then(Value::as_array).map(|a| a.iter().map(|p| [geom::num(&p[0]), geom::num(&p[1])]).collect()).unwrap_or_default() +} + +impl EngineResult { + /// Reads the corpus runner's output JSON (`runner/ssi_runner.cpp`). + pub fn from_runner_json(o: &Value) -> Result { + let curves = match o.get("curves") { + Some(Value::Array(a)) => a + .iter() + .map(|c| { + Ok(EngineCurve { + curve_type: c.get("type").and_then(Value::as_str).unwrap_or_default().to_string(), + xyz: v3_list(c.get("xyz"))?, + uv1: uv_list(c.get("uv1")), + uv2: uv_list(c.get("uv2")), + s1_at_uv: v3_list(c.get("s1_at_uv"))?, + s2_at_uv: v3_list(c.get("s2_at_uv"))?, + }) + }) + .collect::, String>>()?, + _ => return Err("curves: not a list".into()), + }; + Ok(EngineResult { + status: o.get("status").and_then(Value::as_i64).ok_or("status: not an integer")?, + status_name: o.get("status_name").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string), + time_ms: o.get("time_ms").map(geom::num).unwrap_or(f64::NAN), + curves, + points: v3_list(o.get("points"))?, + }) + } +} + +/// The engine ran and answered, or it did not (died, timed out, unreadable output). +#[derive(Clone, Debug)] +pub enum Outcome { + Ran(EngineResult), + Crashed(String), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Verdict { + Crash, + Error, + Incomplete, + WrongTopology, + Inaccurate, + Pass, + /// Default-tolerance runs only: the case's feature size is under the judging floor. + NotApplicable, +} + +impl Verdict { + pub fn as_str(self) -> &'static str { + match self { + Verdict::Crash => "CRASH", + Verdict::Error => "ERROR", + Verdict::Incomplete => "INCOMPLETE", + Verdict::WrongTopology => "WRONG TOPOLOGY", + Verdict::Inaccurate => "INACCURATE", + Verdict::Pass => "PASS", + Verdict::NotApplicable => "N/A", + } + } +} + +impl std::fmt::Display for Verdict { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +/// How well one expected branch / region boundary, or one isolated point, is covered. +#[derive(Clone, Debug, PartialEq)] +pub enum Coverage { + Polyline { max: f64, covered_frac: f64 }, + Point { point: usize, dist: f64 }, +} + +/// The tolerances of a run. +#[derive(Clone, Copy, Debug)] +pub struct Tolerances { + /// `10 * approx_tol`; `None` for a run at the engine's default tolerance. + pub acc_tol: Option, + /// Coverage and join floor: 5e-3 for default-tolerance runs, else 0. + pub cov_floor: f64, +} + +impl Tolerances { + /// A run at approximation tolerance `tol` (score.py: `acc_tol = 10 * tol`, no floor). + pub fn at(tol: f64) -> Tolerances { + Tolerances { acc_tol: Some(10.0 * tol), cov_floor: 0.0 } + } + + /// A run at the engine's default tolerance. + pub fn default_tol() -> Tolerances { + Tolerances { acc_tol: None, cov_floor: 5e-3 } + } +} + +/// The score of one case (score.py's result record). +#[derive(Clone, Debug)] +pub struct Score { + pub id: String, + pub class: String, + pub verdict: Verdict, + pub flags: Vec, + /// The effective coverage tolerance. + pub cov_tol: f64, + /// The crash description (CRASH only). + pub detail: Option, + pub status: Option, + pub status_name: Option, + pub time_ms: Option, + pub n_curves: usize, + pub n_out_points: usize, + pub types: Vec, + pub max_dist_3d: f64, + pub max_dist_uv: f64, + pub coverage: Vec, + pub hausdorff_truth_to_out: f64, + pub hausdorff_out_to_truth: f64, + pub expected_topology: Vec, + pub output_topology: Vec, +} + +/// Python's `"%.e" % x`. +pub fn fmt_e(x: f64, prec: usize) -> String { + if x.is_nan() { + return "nan".into(); + } + if x.is_infinite() { + return if x > 0.0 { "inf".into() } else { "-inf".into() }; + } + let s = format!("{x:.prec$e}"); + let Some((m, e)) = s.split_once('e') else { return s }; + let (sign, digits) = match e.strip_prefix('-') { + Some(d) => ('-', d), + None => ('+', e), + }; + format!("{m}e{sign}{digits:0>2}") +} + +/// Python's `"%.0f" % x`. +fn fmt_f0(x: f64) -> String { + format!("{x:.0}") +} + +/// Python's `str(list_of_str)`. +fn py_list(v: &[String]) -> String { + format!("[{}]", v.iter().map(|s| format!("'{s}'")).collect::>().join(", ")) +} + +fn finite(p: &[V3]) -> Vec { + p.iter().copied().filter(|q| q.iter().all(|c| c.is_finite())).collect() +} + +/// Scores one engine outcome against a case (score.py's `score_case`). +pub fn score_case(case: &Case, outcome: &Outcome, tol: Tolerances) -> Score { + let exp = &case.expected; + let cov_tol = case.cov_tol; + let mut cov_eff = cov_tol; + if let (Some(ill), Some(acc)) = (case.ill_cond, tol.acc_tol) + && ill != 0.0 + && acc != 0.0 + { + cov_eff = py_max(cov_tol, geom::py_min(0.5, 2.0 * acc * ill)); + } + cov_eff = py_max(cov_eff, tol.cov_floor); + let join_tol = py_max(cov_tol, tol.cov_floor); + let mut r = Score { + id: case.id.clone(), + class: case.class.clone(), + verdict: Verdict::Crash, + flags: Vec::new(), + cov_tol: cov_eff, + detail: None, + status: None, + status_name: None, + time_ms: None, + n_curves: 0, + n_out_points: 0, + types: Vec::new(), + max_dist_3d: 0.0, + max_dist_uv: 0.0, + coverage: Vec::new(), + hausdorff_truth_to_out: 0.0, + hausdorff_out_to_truth: 0.0, + expected_topology: Vec::new(), + output_topology: Vec::new(), + }; + let out = match outcome { + Outcome::Crashed(why) => { + r.detail = Some(why.clone()); + return r; + } + Outcome::Ran(out) => out, + }; + let status_name = out.status_name.clone().unwrap_or_else(|| out.status.to_string()); + r.status = Some(out.status); + r.status_name = Some(status_name.clone()); + r.time_ms = Some(out.time_ms); + + let mut out_curves: Vec> = Vec::new(); + let mut out_points: Vec = Vec::new(); + let mut nonfinite = 0; + for c in &out.curves { + let p = finite(&c.xyz); + nonfinite += c.xyz.len() - p.len(); + if p.is_empty() { + continue; + } + if c.curve_type == "TOUCHING" || diameter(&p) <= cov_tol { + let n = p.len() as f64; + let s = p.iter().fold([0.0; 3], |a, q| [a[0] + q[0], a[1] + q[1], a[2] + q[2]]); + out_points.push([s[0] / n, s[1] / n, s[2] / n]); + } else { + out_curves.push(p); + } + r.types.push(c.curve_type.clone()); + } + out_points.extend(out.points.iter().copied()); + r.n_curves = out.curves.len(); + r.n_out_points = out_points.len(); + + // accuracy against the exact surfaces + let worst = |pts: &[V3]| -> f64 { + let mut m = np_max(&case.truth[0].distance(pts)); + for t in &case.truth[1..] { + m = py_max(m, np_max(&t.distance(pts))); + } + m + }; + let (mut acc3d, mut accuv) = (0.0_f64, 0.0_f64); + for c in &out.curves { + let p = finite(&c.xyz); + if !p.is_empty() { + acc3d = py_max(acc3d, worst(&p)); + } + // S1(uv1) must lie on surface 2, S2(uv2) on surface 1. + for (k, q) in [(1, &c.s1_at_uv), (0, &c.s2_at_uv)] { + let q = finite(q); + if !q.is_empty() { + accuv = py_max(accuv, np_max(&case.truth[k].distance(&q))); + } + } + } + if !out_points.is_empty() { + acc3d = py_max(acc3d, worst(&out_points)); + } + r.max_dist_3d = acc3d; + r.max_dist_uv = accuv; + + let truth_polys: Vec<&[V3]> = exp.branches.iter().map(Vec::as_slice).chain(exp.coincident_regions.iter().map(Vec::as_slice)).collect(); + let truth_pts = &exp.isolated_points; + let expected_any = !truth_polys.is_empty() || !truth_pts.is_empty(); + + let ok_status = out.status == SM_SUCCESS; + if !ok_status { + if !expected_any && out.curves.is_empty() && out_points.is_empty() { + r.flags.push(format!("status {status_name} with empty output (expected empty)")); + } else { + r.flags.push(format!("ERROR status {status_name}")); + } + } + + // coverage truth -> output + let curve_refs: Vec<&[V3]> = out_curves.iter().map(Vec::as_slice).collect(); + let outset = PolySet::new(&curve_refs, &out_points); + let mut missed = Vec::new(); + for (k, p) in truth_polys.iter().enumerate() { + let d = outset.query(&stride(p, p.len() / 1000)); + let frac = d.iter().filter(|&&x| x <= cov_eff).count() as f64 / d.len() as f64; + let dmax = np_max(&d); + r.coverage.push(Coverage::Polyline { max: dmax, covered_frac: frac }); + if dmax > cov_eff { + let kind = if k >= exp.branches.len() { "region boundary".to_string() } else { format!("branch {k}") }; + missed.push(format!("{kind} covered {}% (max gap {})", fmt_f0(100.0 * frac), fmt_e(dmax, 2))); + } + } + for (k, &p) in truth_pts.iter().enumerate() { + let d = outset.query1(p); + r.coverage.push(Coverage::Point { point: k, dist: d }); + if d > cov_eff { + missed.push(format!("isolated point {k} not found (nearest output {})", fmt_e(d, 2))); + } + } + let mut h = 0.0; + for (i, c) in r.coverage.iter().enumerate() { + let x = match c { + Coverage::Polyline { max, .. } => *max, + Coverage::Point { dist, .. } => *dist, + }; + h = if i == 0 { x } else { py_max(h, x) }; + } + r.hausdorff_truth_to_out = h; + + // output -> truth (spurious output) + let tset = PolySet::new(&truth_polys, truth_pts); + let mut spurious = Vec::new(); + let mut h_out = 0.0; + for (k, p) in out_curves.iter().enumerate() { + let d = tset.query(&stride(p, p.len() / 1000)); + let dmax = np_max(&d); + h_out = py_max(h_out, dmax); + if dmax > cov_eff { + let off = d.iter().filter(|&&x| x > cov_eff).count() as f64 / d.len() as f64; + spurious.push(format!("output curve {k} off the true intersection by up to {} ({}% of it)", fmt_e(dmax, 2), fmt_f0(100.0 * off))); + } + } + for (k, &p) in out_points.iter().enumerate() { + let d = tset.query1(p); + h_out = py_max(h_out, d); + if d > cov_eff { + spurious.push(format!("output point {k} off the true intersection by {}", fmt_e(d, 2))); + } + } + r.hausdorff_out_to_truth = h_out; + + // topology signature + let truth_owned: Vec> = truth_polys.iter().map(|p| p.to_vec()).collect(); + let sig_exp = signature(&truth_owned, truth_pts, join_tol); + let sig_out = signature(&out_curves, &out_points, join_tol); + let mut topo = Vec::new(); + if nonfinite > 0 { + topo.push(format!("{nonfinite} non-finite output sample(s)")); + } + // duplicated / overlapping output curves + let osets: Vec = out_curves.iter().map(|c| PolySet::new(&[c], &[])).collect(); + for i in 0..out_curves.len() { + for j in i + 1..out_curves.len() { + let (ci, cj) = (&out_curves[i], &out_curves[j]); + let di = osets[j].query(&stride(ci, ci.len() / 500)); + let dj = osets[i].query(&stride(cj, cj.len() / 500)); + let fi = di.iter().filter(|&&x| x <= join_tol).count() as f64 / di.len() as f64; + let fj = dj.iter().filter(|&&x| x <= join_tol).count() as f64 / dj.len() as f64; + let frac = py_max(fi, fj); + if frac > 0.2 { + topo.push(format!("output curves {i} and {j} overlap ({}% of one lies on the other)", fmt_f0(100.0 * frac))); + } + } + } + if sig_exp != sig_out { + topo.push(format!("topology {}, expected {}", py_list(&sig_out), py_list(&sig_exp))); + } + for (k, &s) in exp.singular_points.iter().enumerate() { + let ends = out_curves.iter().filter_map(|c| c.first()).chain(out_curves.iter().filter_map(|c| c.last())).chain(out_points.iter()); + let mut d = f64::INFINITY; + for (n, &e) in ends.enumerate() { + let x = geom::norm(geom::sub(e, s)); + d = if n == 0 { x } else { geom::py_min(d, x) }; + } + if d > cov_eff { + topo.push(format!("singular point {k} not identified (no curve end/point within {}; nearest {})", fmt_e(cov_eff, 1), fmt_e(d, 2))); + } + } + let mut inacc = Vec::new(); + if let Some(acc) = tol.acc_tol { + if acc3d > acc { + inacc.push(format!("3D output up to {} from a surface (acc_tol {})", fmt_e(acc3d, 2), fmt_e(acc, 0))); + } + if accuv > acc { + inacc.push(format!("surface at output UV up to {} from the other surface", fmt_e(accuv, 2))); + } + } + + let has_output = !out.curves.is_empty() || !out_points.is_empty(); + let verdict = if !ok_status && (expected_any || has_output) { + Verdict::Error + } else if !missed.is_empty() { + Verdict::Incomplete + } else if !spurious.is_empty() || !topo.is_empty() { + Verdict::WrongTopology + } else if !inacc.is_empty() { + Verdict::Inaccurate + } else { + Verdict::Pass + }; + r.flags.extend(missed); + r.flags.extend(spurious); + r.flags.extend(topo); + r.flags.extend(inacc); + r.expected_topology = sig_exp; + r.output_topology = sig_out; + r.verdict = verdict; + if tol.cov_floor != 0.0 + && let Some(fs) = case.feature_size + && fs < tol.cov_floor + { + r.flags.insert(0, format!("feature size {} below the {} judging floor of default-tolerance runs", fmt_e(fs, 1), fmt_e(tol.cov_floor, 0))); + r.verdict = Verdict::NotApplicable; + } + r +} + +/// Parses `#define SM_NAME 1234L` lines of SMLib's `SmMessages.h` (first name per number), for +/// status names in flags as score.py prints them. +pub fn status_names(sm_messages_h: &str) -> std::collections::HashMap { + let mut names = std::collections::HashMap::new(); + for line in sm_messages_h.lines() { + let Some(rest) = line.strip_prefix("#define") else { continue }; + if !rest.starts_with(char::is_whitespace) { + continue; + } + let mut it = rest.split_whitespace(); + let (Some(name), Some(val)) = (it.next(), it.next()) else { continue }; + let Some(digits) = val.strip_suffix('L') else { continue }; + if !name.starts_with("SM_") || !name[3..].chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || name.len() == 3 { + continue; + } + if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) { + continue; + } + if let Ok(n) = digits.parse::() { + names.entry(n).or_insert_with(|| name.to_string()); + } + } + names +} + +/// `v3` re-exported for callers building points from JSON. +pub fn point(v: &Value) -> Result { + v3(v) +} diff --git a/crates/smlib/tests/ssi_score/polyset.rs b/crates/smlib/tests/ssi_score/polyset.rs new file mode 100644 index 000000000..e9e0c8ad4 --- /dev/null +++ b/crates/smlib/tests/ssi_score/polyset.rs @@ -0,0 +1,350 @@ +//! Point-to-polyline distances and the topology signature: a port of `PolySet`, +//! `polyline_distance`, `components`, `free_ends` and `signature` of the corpus's +//! `scoring/score.py`, with the same segment hash (exact below the cell size, the nearest +//! decimated vertex above it), so the numbers the verdicts depend on are the same. + +use std::collections::HashMap; + +use super::geom::{V3, linspace, norm, py_max, py_min, sub}; + +/// numpy's `np.percentile(xs, q)` (linear interpolation). +fn percentile(xs: &[f64], q: f64) -> f64 { + let mut s = xs.to_vec(); + s.sort_by(f64::total_cmp); + let Some(&last) = s.last() else { return f64::NAN }; + let vi = (s.len() - 1) as f64 * (q / 100.0); + let lo = vi.floor(); + let i = lo as usize; + let a = s.get(i).copied().unwrap_or(last); + let b = s.get(i + 1).copied().unwrap_or(last); + let t = vi - lo; + let d = b - a; + if t >= 0.5 { b - d * (1.0 - t) } else { a + d * t } +} + +fn key(p: V3, cell: f64) -> [i64; 3] { + [(p[0] / cell).floor() as i64, (p[1] / cell).floor() as i64, (p[2] / cell).floor() as i64] +} + +/// A set of polylines and points, hashed by segment for nearest-distance queries. +pub struct PolySet { + a: Vec, + b: Vec, + cell: f64, + table: HashMap<[i64; 3], Vec>, + coarse: Vec, +} + +impl PolySet { + pub fn new(polylines: &[&[V3]], points: &[V3]) -> PolySet { + let (mut a, mut b) = (Vec::new(), Vec::new()); + for p in polylines { + if p.len() == 1 { + a.push(p[0]); + b.push(p[0]); + } + for w in p.windows(2) { + a.push(w[0]); + b.push(w[1]); + } + } + for &p in points { + a.push(p); + b.push(p); + } + let mut set = PolySet { a, b, cell: 0.0, table: HashMap::new(), coarse: Vec::new() }; + if set.a.is_empty() { + return set; + } + let lens: Vec = set.a.iter().zip(&set.b).map(|(&a, &b)| norm(sub(b, a))).collect(); + let lmax = lens.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let mut cell = percentile(&lens, 95.0) * 2.0; + if 1e-300 > cell { + cell = 1e-300; + } + let alt = if lmax > 0.0 { lmax / 50.0 } else { cell }; + if alt > cell { + cell = alt; + } + set.cell = cell; + for (i, (&a, &b)) in set.a.iter().zip(&set.b).enumerate() { + let n = ((lens[i] / cell).ceil() as usize * 2).max(1); + let d = sub(b, a); + for t in linspace(0.0, 1.0, n + 1) { + let k = key([a[0] + t * d[0], a[1] + t * d[1], a[2] + t * d[2]], cell); + let e = set.table.entry(k).or_default(); + if e.last() != Some(&(i as u32)) { + e.push(i as u32); + } + } + } + let step = (set.a.len() / 4000).max(1); + set.coarse = set.a.iter().step_by(step).copied().collect(); + set + } + + pub fn is_empty(&self) -> bool { + self.a.is_empty() + } + + fn seg_dist(&self, q: V3, i: usize) -> f64 { + let (a, b) = (self.a[i], self.b[i]); + let d = sub(b, a); + let dd = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + let qa = sub(q, a); + let t = if dd > 0.0 { (qa[0] * d[0] + qa[1] * d[1] + qa[2] * d[2]) / dd } else { 0.0 }; + let t = super::geom::clip(t, 0.0, 1.0); + norm(sub(q, [a[0] + t * d[0], a[1] + t * d[1], a[2] + t * d[2]])) + } + + /// Distance from one point to the set (infinite for an empty set). + pub fn query1(&self, q: V3) -> f64 { + if self.is_empty() { + return f64::INFINITY; + } + let k = key(q, self.cell); + let mut best = f64::INFINITY; + let mut any = false; + for i in -1..=1 { + for j in -1..=1 { + for l in -1..=1 { + if let Some(c) = self.table.get(&[k[0].wrapping_add(i), k[1].wrapping_add(j), k[2].wrapping_add(l)]) { + for &s in c { + let d = self.seg_dist(q, s as usize); + if !any || d < best { + best = d; + } + any = true; + } + } + } + } + } + if best > self.cell { + let m = self.coarse.iter().map(|&c| norm(sub(c, q))).fold(f64::INFINITY, f64::min); + best = py_min(best, m); + } + best + } + + pub fn query(&self, qs: &[V3]) -> Vec { + qs.iter().map(|&q| self.query1(q)).collect() + } +} + +/// Every `step`-th point (`P[::step]`). +pub fn stride(p: &[V3], step: usize) -> Vec { + p.iter().step_by(step.max(1)).copied().collect() +} + +/// The largest extent along x, y or z (`np.ptp(P, axis=0).max()`). +pub fn diameter(p: &[V3]) -> f64 { + if p.is_empty() { + return 0.0; + } + (0..3) + .map(|k| { + let lo = p.iter().map(|q| q[k]).fold(f64::INFINITY, f64::min); + let hi = p.iter().map(|q| q[k]).fold(f64::NEG_INFINITY, f64::max); + hi - lo + }) + .fold(f64::NEG_INFINITY, f64::max) +} + +/// Exact distance between segments p1q1 and p2q2. +pub fn seg_seg(p1: V3, q1: V3, p2: V3, q2: V3) -> f64 { + let dt = |x: V3, y: V3| x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; + let (d1, d2, r) = (sub(q1, p1), sub(q2, p2), sub(p1, p2)); + let (a, e, f) = (dt(d1, d1), dt(d2, d2), dt(d2, r)); + if a <= 1e-300 && e <= 1e-300 { + return norm(r); + } + let cl = |x: f64| py_min(py_max(x, 0.0), 1.0); + let (s, t); + if a <= 1e-300 { + s = 0.0; + t = cl(f / e); + } else { + let c = dt(d1, r); + if e <= 1e-300 { + t = 0.0; + s = cl(-c / a); + } else { + let b = dt(d1, d2); + let den = a * e - b * b; + let s0 = if den > 1e-300 { cl((b * f - c * e) / den) } else { 0.0 }; + let t0 = (b * s0 + f) / e; + if t0 < 0.0 { + t = 0.0; + s = cl(-c / a); + } else if t0 > 1.0 { + t = 1.0; + s = cl((b - c) / a); + } else { + t = t0; + s = s0; + } + } + } + norm(sub([p1[0] + d1[0] * s, p1[1] + d1[1] * s, p1[2] + d1[2] * s], [p2[0] + d2[0] * t, p2[1] + d2[1] * t, p2[2] + d2[2] * t])) +} + +fn max_seg(p: &[V3]) -> f64 { + p.windows(2).map(|w| norm(sub(w[1], w[0]))).fold(0.0, |m, x| if x > m { x } else { m }) +} + +/// Min distance between polylines A and B: vertex query first, exact segment-segment distance +/// around the closest approach when it matters. +pub fn polyline_distance(a: &[V3], b: &[V3], set_b: &PolySet, tol: f64) -> f64 { + let dv = set_b.query(a); + let mut k = 0; + for (i, &d) in dv.iter().enumerate() { + if d.is_nan() { + k = i; + break; + } + if d < dv[k] { + k = i; + } + } + let Some(&d) = dv.get(k) else { return f64::INFINITY }; + if d <= tol { + return d; + } + let (sa, sb) = (max_seg(a), max_seg(b)); + if d > tol + sa.max(sb) { + return d; + } + let mut best = d; + let lim = tol + sa + sb; + // the nearest vertex of B to each vertex of A, computed once (np.argmin: the first minimum) + let mut nearest: Vec> = vec![None; a.len()]; + for (i, &di) in dv.iter().enumerate() { + if !(di <= lim) { + continue; + } + for ia in [i as isize - 1, i as isize] { + if ia < 0 || ia as usize + 1 >= a.len() { + continue; + } + let ia = ia as usize; + let jb = *nearest[ia].get_or_insert_with(|| { + let (mut jb, mut dj) = (0, f64::INFINITY); + for (j, &q) in b.iter().enumerate() { + let x = norm(sub(q, a[ia])); + if x.is_nan() { + jb = j; + break; + } + if j == 0 || x < dj { + dj = x; + jb = j; + } + } + jb + }); + for j in jb.saturating_sub(3)..(jb + 3).min(b.len().saturating_sub(1)) { + best = py_min(best, seg_seg(a[ia], a[ia + 1], b[j], b[j + 1])); + } + } + } + best +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Item { + Curve(usize), + Point(usize), +} + +/// Connected components of curves and points joined within `join_tol`. +pub fn components(curves: &[Vec], points: &[V3], join_tol: f64) -> Vec> { + let items: Vec = (0..curves.len()).map(Item::Curve).chain((0..points.len()).map(Item::Point)).collect(); + let mut parent: Vec = (0..items.len()).collect(); + fn find(parent: &mut [usize], mut x: usize) -> usize { + while parent[x] != x { + parent[x] = parent[parent[x]]; + x = parent[x]; + } + x + } + let sets: Vec = curves.iter().map(|c| PolySet::new(&[c], &[])).collect(); + for i in 0..items.len() { + for j in i + 1..items.len() { + let d = match (items[i], items[j]) { + (Item::Point(a), Item::Point(b)) => norm(sub(points[a], points[b])), + (Item::Curve(a), Item::Curve(b)) => polyline_distance(&curves[a], &curves[b], &sets[b], join_tol), + (Item::Curve(c), Item::Point(p)) | (Item::Point(p), Item::Curve(c)) => sets[c].query1(points[p]), + }; + if d <= join_tol { + let (ri, rj) = (find(&mut parent, i), find(&mut parent, j)); + parent[ri] = rj; + } + } + } + let mut groups: Vec<(usize, Vec)> = Vec::new(); + for (i, &it) in items.iter().enumerate() { + let r = find(&mut parent, i); + match groups.iter_mut().find(|(g, _)| *g == r) { + Some((_, v)) => v.push(it), + None => groups.push((r, vec![it])), + } + } + groups.into_iter().map(|(_, v)| v).collect() +} + +/// Number of free endpoints of each curve. +pub fn free_ends(curves: &[Vec], join_tol: f64) -> Vec { + let sets: Vec = curves.iter().map(|c| PolySet::new(&[c], &[])).collect(); + let mut res = Vec::with_capacity(curves.len()); + for (i, c) in curves.iter().enumerate() { + let (Some(&first), Some(&last)) = (c.first(), c.last()) else { + res.push(0); + continue; + }; + if norm(sub(first, last)) <= join_tol && diameter(c) > 2.0 * join_tol { + res.push(0); + continue; + } + let mut s = Vec::with_capacity(c.len()); + let mut acc = 0.0; + s.push(0.0); + for w in c.windows(2) { + acc += norm(sub(w[1], w[0])); + s.push(acc); + } + let mut n = 0; + for (end, si) in [(first, 0.0), (last, acc)] { + let mut glued = (0..curves.len()).any(|j| j != i && sets[j].query1(end) <= join_tol); + if !glued { + let m = c + .iter() + .zip(&s) + .filter(|(_, sk)| (*sk - si).abs() > 3.0 * join_tol) + .map(|(&p, _)| norm(sub(p, end))) + .fold(None, |m: Option, x| Some(m.map_or(x, |m| m.min(x)))); + glued = m.is_some_and(|m| m <= join_tol); + } + if !glued { + n += 1; + } + } + res.push(n); + } + res +} + +/// The sorted component signature: `point` or `curve(free_ends=N)` per component. +pub fn signature(curves: &[Vec], points: &[V3], join_tol: f64) -> Vec { + let comps = components(curves, points, join_tol); + let fe = if curves.is_empty() { Vec::new() } else { free_ends(curves, join_tol) }; + let mut sig: Vec = comps + .iter() + .map(|comp| { + let cs: Vec = comp.iter().filter_map(|it| if let Item::Curve(k) = it { Some(*k) } else { None }).collect(); + if cs.is_empty() { "point".to_string() } else { format!("curve(free_ends={})", cs.iter().map(|&k| fe[k]).sum::()) } + }) + .collect(); + sig.sort(); + sig +} diff --git a/crates/step/Cargo.toml b/crates/step/Cargo.toml new file mode 100644 index 000000000..3dfc57cdb --- /dev/null +++ b/crates/step/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "solidcraft-step" +description = "SolidCraft STEP (ISO 10303) exchange: the Part 21 exchange structure and Part 42 geometry as plain data, with no modelling backend" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +solidcore-record = { workspace = true } +solidcraft-geom = { workspace = true } +solidcraft-profile = { workspace = true } diff --git a/crates/step/src/eval.rs b/crates/step/src/eval.rs new file mode 100644 index 000000000..b55eba410 --- /dev/null +++ b/crates/step/src/eval.rs @@ -0,0 +1,193 @@ +//! Points on STEP curves and surfaces, in STEP's own parameterisation (ISO 10303-42), so tests +//! and the topology reader can check that vertices lie on their curves. `None` for a parameter +//! the geometry is not defined at, or for geometry too inconsistent to evaluate. + +use crate::geom::{BSplineCurve, BSplineSurface, Curve, P3, Surface, add, cross, dot, norm, scale, sub}; + +/// Every knot repeated by its multiplicity. +fn expanded(knots: &[f64], mults: &[usize]) -> Option> { + if knots.len() != mults.len() { + return None; + } + let total = mults.iter().try_fold(0usize, |a, m| a.checked_add(*m))?; + let mut v = Vec::with_capacity(total); + for (k, m) in knots.iter().zip(mults) { + v.extend(std::iter::repeat_n(*k, *m)); + } + Some(v) +} + +/// Index `i` of the knot span `[U[i], U[i+1])` holding `t`, with `degree <= i < n` for `n` +/// control points (the last span takes the domain's upper end). +fn span(u: &[f64], degree: usize, n: usize, t: f64) -> Option { + let lo = *u.get(degree)?; + let hi = *u.get(n)?; + if !(t >= lo - 1e-12 * (1.0 + lo.abs()) && t <= hi + 1e-12 * (1.0 + hi.abs())) { + return None; + } + let mut i = degree; + while i + 1 < n && *u.get(i + 1)? <= t { + i += 1; + } + Some(i) +} + +/// De Boor on homogeneous points `[x·w, y·w, z·w, w]`. +fn de_boor(u: &[f64], degree: usize, ctrl: &[[f64; 4]], t: f64) -> Option<[f64; 4]> { + let k = span(u, degree, ctrl.len(), t)?; + let mut d: Vec<[f64; 4]> = (0..=degree).map(|j| ctrl.get(j + k - degree).copied()).collect::>()?; + for r in 1..=degree { + for j in (r..=degree).rev() { + let i = j + k - degree; + let a = *u.get(i)?; + let b = *u.get(i + 1 + degree - r)?; + let alpha = if b - a > 0.0 { (t - a) / (b - a) } else { 0.0 }; + let p = *d.get(j - 1)?; + let q = *d.get(j)?; + *d.get_mut(j)? = [0, 1, 2, 3].map(|c| (1.0 - alpha) * p[c] + alpha * q[c]); + } + } + d.get(degree).copied() +} + +fn from_homogeneous(h: [f64; 4]) -> Option { + (h[3].abs() > 1e-300).then(|| [h[0] / h[3], h[1] / h[3], h[2] / h[3]]).filter(|p| p.iter().all(|x| x.is_finite())) +} + +fn homogeneous(p: P3, w: f64) -> [f64; 4] { + [p[0] * w, p[1] * w, p[2] * w, w] +} + +impl BSplineCurve { + /// Parameter range: from knot `degree` to knot `n` of the expanded knot vector. + pub fn domain(&self) -> Option<(f64, f64)> { + let u = expanded(&self.knots, &self.multiplicities)?; + Some((*u.get(self.degree)?, *u.get(self.points.len())?)) + } + pub fn point(&self, t: f64) -> Option { + let u = expanded(&self.knots, &self.multiplicities)?; + if u.len() != self.points.len() + self.degree + 1 { + return None; + } + let ctrl: Vec<[f64; 4]> = match &self.weights { + Some(w) if w.len() == self.points.len() => self.points.iter().zip(w).map(|(p, w)| homogeneous(*p, *w)).collect(), + Some(_) => return None, + None => self.points.iter().map(|p| homogeneous(*p, 1.0)).collect(), + }; + from_homogeneous(de_boor(&u, self.degree, &ctrl, t)?) + } +} + +impl BSplineSurface { + pub fn point(&self, s: f64, t: f64) -> Option { + let uk = expanded(&self.u_knots, &self.u_multiplicities)?; + let vk = expanded(&self.v_knots, &self.v_multiplicities)?; + let nu = self.points.len(); + let nv = self.points.first()?.len(); + if uk.len() != nu + self.u_degree + 1 || vk.len() != nv + self.v_degree + 1 { + return None; + } + // Each u row evaluated along v, then the column of results along u. + let mut column = Vec::with_capacity(nu); + for (i, row) in self.points.iter().enumerate() { + if row.len() != nv { + return None; + } + let ctrl: Vec<[f64; 4]> = match &self.weights { + Some(w) => { + let w = w.get(i).filter(|w| w.len() == nv)?; + row.iter().zip(w).map(|(p, w)| homogeneous(*p, *w)).collect() + } + None => row.iter().map(|p| homogeneous(*p, 1.0)).collect(), + }; + column.push(de_boor(&vk, self.v_degree, &ctrl, t)?); + } + from_homogeneous(de_boor(&uk, self.u_degree, &column, s)?) + } +} + +impl Curve { + /// The point at parameter `t`. + pub fn point(&self, t: f64) -> Option { + self.point_at(t, 0) + } + + fn point_at(&self, t: f64, depth: usize) -> Option { + if depth > 16 || !t.is_finite() { + return None; + } + let p = match self { + Curve::Line { origin, direction, magnitude } => add(*origin, scale(*direction, t * magnitude)), + Curve::Circle { position, radius } => position.at(radius * t.cos(), radius * t.sin(), 0.0), + Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => position.at(semi_axis_1 * t.cos(), semi_axis_2 * t.sin(), 0.0), + Curve::Hyperbola { position, semi_axis, semi_imag_axis } => position.at(semi_axis * t.cosh(), semi_imag_axis * t.sinh(), 0.0), + Curve::Parabola { position, focal_dist } => position.at(focal_dist * t * t, 2.0 * focal_dist * t, 0.0), + Curve::BSpline(b) => b.point(t)?, + Curve::Polyline(pts) => { + if pts.len() < 2 || t < 0.0 || t > (pts.len() - 1) as f64 { + return None; + } + let i = (t.floor() as usize).min(pts.len() - 2); + let (a, b) = (*pts.get(i)?, *pts.get(i + 1)?); + add(a, scale(sub(b, a), t - i as f64)) + } + Curve::Trimmed { basis, .. } => basis.point_at(t, depth + 1)?, + Curve::SurfaceCurve { curve_3d, .. } => curve_3d.point_at(t, depth + 1)?, + // Needs the basis curve's derivative; not evaluated yet. + Curve::OffsetCurve3d { .. } => return None, + }; + p.iter().all(|x| x.is_finite()).then_some(p) + } +} + +impl Surface { + /// The point at parameters `(u, v)`. + pub fn point(&self, u: f64, v: f64) -> Option { + self.point_at(u, v, 0) + } + + /// The unit normal `∂S/∂u × ∂S/∂v` at `(u, v)`, by central differences. + pub fn normal(&self, u: f64, v: f64) -> Option { + self.normal_at(u, v, 0) + } + + fn normal_at(&self, u: f64, v: f64, depth: usize) -> Option { + let h = 1e-6; + let du = sub(self.point_at(u + h, v, depth)?, self.point_at(u - h, v, depth)?); + let dv = sub(self.point_at(u, v + h, depth)?, self.point_at(u, v - h, depth)?); + let n = cross(du, dv); + let m = norm(n); + (m > 1e-30 && m.is_finite()).then(|| scale(n, 1.0 / m)) + } + + fn point_at(&self, u: f64, v: f64, depth: usize) -> Option { + if depth > 16 || !u.is_finite() || !v.is_finite() { + return None; + } + let p = match self { + Surface::Plane { position } => position.at(u, v, 0.0), + Surface::Cylinder { position, radius } => position.at(radius * u.cos(), radius * u.sin(), v), + Surface::Cone { position, radius, semi_angle } => { + let r = radius + v * semi_angle.tan(); + position.at(r * u.cos(), r * u.sin(), v) + } + Surface::Sphere { position, radius } => position.at(radius * v.cos() * u.cos(), radius * v.cos() * u.sin(), radius * v.sin()), + Surface::Torus { position, major_radius, minor_radius } | Surface::DegenerateTorus { position, major_radius, minor_radius, .. } => { + let r = major_radius + minor_radius * v.cos(); + position.at(r * u.cos(), r * u.sin(), minor_radius * v.sin()) + } + Surface::BSpline(b) => b.point(u, v)?, + Surface::Revolution { profile, axis } => { + // Rodrigues: the profile point turned by u about the axis. + let q = sub(profile.point_at(v, depth + 1)?, axis.origin); + let k = axis.direction; + let (s, c) = u.sin_cos(); + add(axis.origin, add(add(scale(q, c), scale(cross(k, q), s)), scale(k, dot(k, q) * (1.0 - c)))) + } + Surface::Extrusion { profile, direction, magnitude } => add(profile.point_at(u, depth + 1)?, scale(*direction, v * magnitude)), + Surface::Offset { basis, distance, .. } => add(basis.point_at(u, v, depth + 1)?, scale(basis.normal_at(u, v, depth + 1)?, *distance)), + Surface::RectangularTrimmed { basis, .. } => basis.point_at(u, v, depth + 1)?, + }; + p.iter().all(|x| x.is_finite()).then_some(p) + } +} diff --git a/crates/step/src/geom.rs b/crates/step/src/geom.rs new file mode 100644 index 000000000..25844f764 --- /dev/null +++ b/crates/step/src/geom.rs @@ -0,0 +1,307 @@ +//! STEP geometry (ISO 10303-42) as plain data: the curves and surfaces a file defines, exactly +//! as it defines them, in millimetres and radians. Nothing is approximated, bounded or turned +//! into another kind on the way in: a circle stays a circle with its placement, an unbounded +//! cylinder stays unbounded, and a B-spline keeps its own knots and form. Every curve and surface +//! keeps STEP's own parameterisation, so a 2D curve in a surface's parameter space means the same +//! thing here as in the file (SMLib's `SmSTEPSurface` evaluates the same parameterisation, with +//! angles in degrees where we use radians). +//! +//! Entities the file shares (one surface under many edges' pcurves) are shared here too, through +//! `Arc`, so reading is linear in the file however often an entity is referenced. + +use std::sync::Arc; + +/// A point or vector. +pub type P3 = [f64; 3]; + +/// AXIS2_PLACEMENT_3D (or _2D, with `axis` = +Z): an origin and two orthogonal unit directions. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Placement { + pub origin: P3, + /// Local Z. + pub axis: P3, + /// Local X (`ref_direction`, made orthogonal to `axis`). + pub ref_direction: P3, +} + +impl Placement { + /// Local Y (`axis` × `ref_direction`). + pub fn y(&self) -> P3 { + cross(self.axis, self.ref_direction) + } + /// `origin + x·X + y·Y + z·Z`. + pub fn at(&self, x: f64, y: f64, z: f64) -> P3 { + let yy = self.y(); + add(self.origin, add(scale(self.ref_direction, x), add(scale(yy, y), scale(self.axis, z)))) + } +} + +/// AXIS1_PLACEMENT: an origin and a unit direction. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Axis1 { + pub origin: P3, + pub direction: P3, +} + +/// A STEP LOGICAL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Logical { + True, + False, + Unknown, +} + +/// `b_spline_curve_form`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CurveForm { + PolylineForm, + CircularArc, + EllipticArc, + ParabolicArc, + HyperbolicArc, + Unspecified, +} + +/// `b_spline_surface_form`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SurfaceForm { + PlaneSurf, + CylindricalSurf, + ConicalSurf, + SphericalSurf, + ToroidalSurf, + SurfOfRevolution, + RuledSurf, + GeneralisedCone, + QuadricSurf, + SurfOfLinearExtrusion, + Unspecified, +} + +/// `knot_type`. A curve given without knots (BEZIER_CURVE, UNIFORM_CURVE, QUASI_UNIFORM_CURVE) +/// has them worked out on reading, and keeps the matching type here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KnotSpec { + UniformKnots, + QuasiUniformKnots, + PiecewiseBezierKnots, + Unspecified, +} + +/// A B-spline curve: distinct knots with their multiplicities, as STEP writes them. +#[derive(Clone, Debug, PartialEq)] +pub struct BSplineCurve { + pub degree: usize, + pub points: Vec, + /// Present for a rational curve, one positive weight per point. + pub weights: Option>, + pub knots: Vec, + pub multiplicities: Vec, + pub form: CurveForm, + pub closed: Logical, + pub self_intersect: Logical, + pub knot_spec: KnotSpec, +} + +/// A B-spline surface; `points[i][j]` runs along u with `i`, along v with `j`. +#[derive(Clone, Debug, PartialEq)] +pub struct BSplineSurface { + pub u_degree: usize, + pub v_degree: usize, + pub points: Vec>, + pub weights: Option>>, + pub u_knots: Vec, + pub u_multiplicities: Vec, + pub v_knots: Vec, + pub v_multiplicities: Vec, + pub form: SurfaceForm, + pub u_closed: Logical, + pub v_closed: Logical, + pub self_intersect: Logical, + pub knot_spec: KnotSpec, +} + +/// One end of a TRIMMED_CURVE: a point on the basis curve, its parameter, or both. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Trim { + Point(P3), + Parameter(f64), +} + +/// `trimming_preference`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TrimPreference { + Cartesian, + Parameter, + Unspecified, +} + +/// `preferred_surface_curve_representation`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreferredRep { + Curve3d, + PcurveS1, + PcurveS2, +} + +/// Which SURFACE_CURVE subtype. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SurfaceCurveKind { + Surface, + Seam, + Intersection, + BoundedSurface, +} + +/// PCURVE: a 2D curve in the parameter space of `surface`. Its coordinates are the surface's +/// own parameters (lengths in mm, angles in radians). +#[derive(Clone, Debug, PartialEq)] +pub struct Pcurve { + pub surface: Arc, + /// A 2D curve: every point and placement has z = 0 and every placement axis is +Z. + pub curve: Arc, +} + +/// An item of a SURFACE_CURVE's `associated_geometry`. +#[derive(Clone, Debug, PartialEq)] +pub enum Associated { + Pcurve(Pcurve), + Surface(Arc), +} + +/// A STEP curve. +#[derive(Clone, Debug, PartialEq)] +pub enum Curve { + /// `origin + t·magnitude·direction`. + Line { + origin: P3, + direction: P3, + magnitude: f64, + }, + /// Parameter: the angle from `ref_direction`. + Circle { + position: Placement, + radius: f64, + }, + Ellipse { + position: Placement, + semi_axis_1: f64, + semi_axis_2: f64, + }, + /// `origin + a·cosh t·X + b·sinh t·Y`. + Hyperbola { + position: Placement, + semi_axis: f64, + semi_imag_axis: f64, + }, + /// `origin + f·t²·X + 2f·t·Y`. + Parabola { + position: Placement, + focal_dist: f64, + }, + BSpline(Box), + /// Segment `i` (from 0) is the parameters `[i, i + 1]`. + Polyline(Vec), + Trimmed { + basis: Arc, + trim_1: Vec, + trim_2: Vec, + sense: bool, + preference: TrimPreference, + }, + SurfaceCurve { + kind: SurfaceCurveKind, + curve_3d: Arc, + associated: Vec, + master: PreferredRep, + }, + OffsetCurve3d { + basis: Arc, + distance: f64, + self_intersect: Logical, + ref_direction: P3, + }, +} + +/// A STEP surface. +#[derive(Clone, Debug, PartialEq)] +pub enum Surface { + /// `origin + u·X + v·Y`. + Plane { + position: Placement, + }, + /// `origin + r·(cos u·X + sin u·Y) + v·Z`. + Cylinder { + position: Placement, + radius: f64, + }, + /// `origin + (r + v·tan a)·(cos u·X + sin u·Y) + v·Z`. + Cone { + position: Placement, + radius: f64, + semi_angle: f64, + }, + /// `origin + r·cos v·(cos u·X + sin u·Y) + r·sin v·Z`. + Sphere { + position: Placement, + radius: f64, + }, + /// `origin + (R + r·cos v)·(cos u·X + sin u·Y) + r·sin v·Z`. + Torus { + position: Placement, + major_radius: f64, + minor_radius: f64, + }, + /// A torus whose minor radius reaches the axis; `select_outer` keeps the outer part. + DegenerateTorus { + position: Placement, + major_radius: f64, + minor_radius: f64, + select_outer: bool, + }, + BSpline(Box), + /// The profile at `v` turned by the angle `u` about the axis. + Revolution { + profile: Arc, + axis: Axis1, + }, + /// `profile(u) + v·magnitude·direction`. + Extrusion { + profile: Arc, + direction: P3, + magnitude: f64, + }, + Offset { + basis: Arc, + distance: f64, + self_intersect: Logical, + }, + RectangularTrimmed { + basis: Arc, + u1: f64, + u2: f64, + v1: f64, + v2: f64, + u_sense: bool, + v_sense: bool, + }, +} + +pub(crate) fn add(a: P3, b: P3) -> P3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} +pub(crate) fn sub(a: P3, b: P3) -> P3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +pub(crate) fn scale(a: P3, s: f64) -> P3 { + [a[0] * s, a[1] * s, a[2] * s] +} +pub(crate) fn dot(a: P3, b: P3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} +pub(crate) fn cross(a: P3, b: P3) -> P3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} +pub(crate) fn norm(a: P3) -> f64 { + dot(a, a).sqrt() +} diff --git a/crates/step/src/geom_tests.rs b/crates/step/src/geom_tests.rs new file mode 100644 index 000000000..244aa2aee --- /dev/null +++ b/crates/step/src/geom_tests.rs @@ -0,0 +1,492 @@ +//! STEP geometry, one entity at a time: reading (values, units, evaluation in STEP's own +//! parameterisation), writing, and read → write → read round trips. Expected values are +//! analytic. + +use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI}; +use std::sync::Arc; + +use crate::geom::{Associated, Curve, CurveForm, KnotSpec, Logical, P3, PreferredRep, Surface, SurfaceCurveKind, Trim}; +use crate::p21::{self, Exchange}; +use crate::read::{Reader, Units}; +use crate::write::{GeomWriter, Writer, real}; + +const MM: Units = Units { len: 1.0, ang: 1.0 }; + +fn file(data: &str) -> Exchange { + let t = format!("ISO-10303-21;\nHEADER;FILE_SCHEMA(('AUTOMOTIVE_DESIGN'));ENDSEC;\nDATA;\n{data}\nENDSEC;\nEND-ISO-10303-21;\n"); + match p21::parse(&t) { + Ok(ex) => ex, + Err(e) => panic!("{e}\n{t}"), + } +} + +/// Common entities: #1 origin, #2 +Z, #3 +X, #4 the world placement, #5 +Y. +const BASE: &str = "#1=CARTESIAN_POINT('',(0.,0.,0.));#2=DIRECTION('',(0.,0.,1.));#3=DIRECTION('',(1.,0.,0.));\ +#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);#5=DIRECTION('',(0.,1.,0.));"; + +fn curve(data: &str, id: u64, units: Units) -> Arc { + let ex = file(&format!("{BASE}{data}")); + match Reader::new(&ex, units).curve(id) { + Ok(c) => c, + Err(e) => panic!("{e}"), + } +} + +fn surface(data: &str, id: u64, units: Units) -> Arc { + let ex = file(&format!("{BASE}{data}")); + match Reader::new(&ex, units).surface(id) { + Ok(s) => s, + Err(e) => panic!("{e}"), + } +} + +fn close(a: P3, b: P3) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-9 * (1.0 + y.abs())) +} + +#[track_caller] +fn at_curve(c: &Curve, t: f64, want: P3) { + let got = c.point(t); + assert!(got.is_some_and(|g| close(g, want)), "at {t}: got {got:?}, want {want:?}"); +} + +#[track_caller] +fn at_surface(s: &Surface, u: f64, v: f64, want: P3) { + let got = s.point(u, v); + assert!(got.is_some_and(|g| close(g, want)), "at ({u}, {v}): got {got:?}, want {want:?}"); +} + +/// Writes a curve or surface, reads it back, writes it again: the second file must equal the +/// first, and the geometry read back must evaluate like the original. +fn round_trip_curve(c: &Curve, params: &[f64]) { + let mut w = Writer::new(); + let id = GeomWriter::new(&mut w).curve(c); + let text = w.file("t", "AUTOMOTIVE_DESIGN"); + let ex = p21::parse(&text).unwrap_or_else(|e| panic!("{e}\n{text}")); + let back = Reader::new(&ex, MM).curve(id).unwrap_or_else(|e| panic!("{e}\n{text}")); + assert_eq!(std::mem::discriminant(c), std::mem::discriminant(&*back), "{text}"); + for &t in params { + let (a, b) = (c.point(t), back.point(t)); + assert!(matches!((a, b), (Some(a), Some(b)) if close(a, b)) || (a.is_none() && b.is_none()), "at {t}: {a:?} vs {b:?}\n{text}"); + } + let mut w2 = Writer::new(); + GeomWriter::new(&mut w2).curve(&back); + assert_eq!(w2.data(), w.data(), "a second write differs"); +} + +fn round_trip_surface(s: &Surface, params: &[(f64, f64)]) { + let mut w = Writer::new(); + let id = GeomWriter::new(&mut w).surface(s); + let text = w.file("t", "AUTOMOTIVE_DESIGN"); + let ex = p21::parse(&text).unwrap_or_else(|e| panic!("{e}\n{text}")); + let back = Reader::new(&ex, MM).surface(id).unwrap_or_else(|e| panic!("{e}\n{text}")); + assert_eq!(std::mem::discriminant(s), std::mem::discriminant(&*back), "{text}"); + for &(u, v) in params { + let (a, b) = (s.point(u, v), back.point(u, v)); + assert!(matches!((a, b), (Some(a), Some(b)) if close(a, b)), "at ({u}, {v}): {a:?} vs {b:?}\n{text}"); + } + let mut w2 = Writer::new(); + GeomWriter::new(&mut w2).surface(&back); + assert_eq!(w2.data(), w.data(), "a second write differs"); +} + +const TS: [f64; 5] = [0.0, 0.3, 1.0, FRAC_PI_2, 2.5]; +const UVS: [(f64, f64); 4] = [(0.0, 0.0), (0.4, 0.2), (FRAC_PI_2, 1.0), (2.0, -0.5)]; + +#[test] +fn line() { + let c = curve("#10=CARTESIAN_POINT('',(1.,2.,3.));#11=VECTOR('',#3,5.);#12=LINE('',#10,#11);", 12, MM); + assert!(matches!(*c, Curve::Line { magnitude, .. } if magnitude == 5.0)); + at_curve(&c, 2.0, [11.0, 2.0, 3.0]); + round_trip_curve(&c, &TS); +} + +#[test] +fn circle_and_ellipse() { + let c = curve("#10=CIRCLE('',#4,10.);", 10, MM); + at_curve(&c, 0.0, [10.0, 0.0, 0.0]); + at_curve(&c, FRAC_PI_2, [0.0, 10.0, 0.0]); + round_trip_curve(&c, &TS); + let e = curve("#10=ELLIPSE('',#4,10.,4.);", 10, MM); + at_curve(&e, FRAC_PI_2, [0.0, 4.0, 0.0]); + at_curve(&e, PI, [-10.0, 0.0, 0.0]); + round_trip_curve(&e, &TS); +} + +#[test] +fn hyperbola_and_parabola() { + let h = curve("#10=HYPERBOLA('',#4,2.,3.);", 10, MM); + at_curve(&h, 1.0, [2.0 * 1f64.cosh(), 3.0 * 1f64.sinh(), 0.0]); + round_trip_curve(&h, &TS); + let p = curve("#10=PARABOLA('',#4,0.5);", 10, MM); + at_curve(&p, 2.0, [2.0, 2.0, 0.0]); + round_trip_curve(&p, &TS); +} + +#[test] +fn bspline_curve_with_knots() { + // A quadratic Bézier from (0,0) through control (1,2) to (2,0): its middle is (1, 1). + let c = curve( + "#10=CARTESIAN_POINT('',(0.,0.,0.));#11=CARTESIAN_POINT('',(1.,2.,0.));#12=CARTESIAN_POINT('',(2.,0.,0.));\ + #13=B_SPLINE_CURVE_WITH_KNOTS('',2,(#10,#11,#12),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.PIECEWISE_BEZIER_KNOTS.);", + 13, + MM, + ); + let Curve::BSpline(b) = &*c else { panic!("{c:?}") }; + assert_eq!((b.degree, b.multiplicities.clone(), b.knot_spec), (2, vec![3, 3], KnotSpec::PiecewiseBezierKnots)); + assert_eq!(b.domain(), Some((0.0, 1.0))); + at_curve(&c, 0.5, [1.0, 1.0, 0.0]); + round_trip_curve(&c, &[0.0, 0.25, 0.5, 1.0]); +} + +#[test] +fn rational_bspline_curve_is_an_exact_quarter_circle() { + let w = std::f64::consts::FRAC_1_SQRT_2; + let c = curve( + &format!( + "#10=CARTESIAN_POINT('',(1.,0.,0.));#11=CARTESIAN_POINT('',(1.,1.,0.));#12=CARTESIAN_POINT('',(0.,1.,0.));\ + #13=(BOUNDED_CURVE()B_SPLINE_CURVE(2,(#10,#11,#12),.CIRCULAR_ARC.,.F.,.F.)B_SPLINE_CURVE_WITH_KNOTS((3,3),(0.,1.),.UNSPECIFIED.)\ + CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE((1.,{},1.))REPRESENTATION_ITEM(''));", + real(w) + ), + 13, + MM, + ); + let Curve::BSpline(b) = &*c else { panic!("{c:?}") }; + assert_eq!(b.form, CurveForm::CircularArc); + assert!(b.weights.is_some()); + for t in [0.1, 0.5, 0.9] { + let p = c.point(t).unwrap_or_default(); + assert!((p[0].hypot(p[1]) - 1.0).abs() < 1e-12, "{p:?}"); + } + round_trip_curve(&c, &[0.0, 0.3, 0.7, 1.0]); +} + +#[test] +fn implied_knots_and_repeated_knots() { + let pts = "#10=CARTESIAN_POINT('',(0.,0.,0.));#11=CARTESIAN_POINT('',(1.,1.,0.));#12=CARTESIAN_POINT('',(2.,0.,0.));#13=CARTESIAN_POINT('',(3.,1.,0.));"; + let q = curve(&format!("{pts}#14=QUASI_UNIFORM_CURVE('',2,(#10,#11,#12,#13),.UNSPECIFIED.,.F.,.F.);"), 14, MM); + let Curve::BSpline(b) = &*q else { panic!("{q:?}") }; + assert_eq!((b.knots.clone(), b.multiplicities.clone()), (vec![0.0, 1.0, 2.0], vec![3, 1, 3])); + at_curve(&q, 0.0, [0.0, 0.0, 0.0]); + at_curve(&q, 2.0, [3.0, 1.0, 0.0]); + let bez = curve(&format!("{pts}#14=BEZIER_CURVE('',3,(#10,#11,#12,#13),.UNSPECIFIED.,.F.,.F.);"), 14, MM); + let Curve::BSpline(b) = &*bez else { panic!("{bez:?}") }; + assert_eq!((b.knots.clone(), b.multiplicities.clone()), (vec![0.0, 1.0], vec![4, 4])); + // A knot written twice is one knot. + let rep = curve( + &format!("{pts}#14=B_SPLINE_CURVE_WITH_KNOTS('',2,(#10,#11,#12,#13),.UNSPECIFIED.,.F.,.F.,(3,1,1,2),(0.,1.,1.,2.),.UNSPECIFIED.);"), + 14, + MM, + ); + let Curve::BSpline(b) = &*rep else { panic!("{rep:?}") }; + assert_eq!((b.knots.clone(), b.multiplicities.clone()), (vec![0.0, 1.0, 2.0], vec![3, 2, 2])); + assert_eq!(b.domain(), Some((0.0, 1.0))); + round_trip_curve(&rep, &[0.0, 0.5, 1.0]); +} + +#[test] +fn polyline_and_trimmed_curve() { + let pl = curve( + "#10=CARTESIAN_POINT('',(0.,0.,0.));#11=CARTESIAN_POINT('',(4.,0.,0.));#12=CARTESIAN_POINT('',(4.,2.,0.));#13=POLYLINE('',(#10,#11,#12));", + 13, + MM, + ); + at_curve(&pl, 0.5, [2.0, 0.0, 0.0]); + at_curve(&pl, 1.5, [4.0, 1.0, 0.0]); + round_trip_curve(&pl, &[0.0, 0.5, 1.0, 1.5, 2.0]); + // A circle trimmed in degrees: the parameters become radians. + let deg = Units { len: 1.0, ang: PI / 180.0 }; + let t = curve( + "#10=CIRCLE('',#4,10.);#11=CARTESIAN_POINT('',(10.,0.,0.));#12=TRIMMED_CURVE('',#10,(#11,PARAMETER_VALUE(0.)),(PARAMETER_VALUE(90.)),.T.,.PARAMETER.);", + 12, + deg, + ); + let Curve::Trimmed { trim_1, trim_2, sense, .. } = &*t else { panic!("{t:?}") }; + assert_eq!(trim_1.first(), Some(&Trim::Point([10.0, 0.0, 0.0]))); + assert!(matches!(trim_2.first(), Some(Trim::Parameter(a)) if (a - FRAC_PI_2).abs() < 1e-15)); + assert!(*sense); + round_trip_curve(&t, &TS); +} + +#[test] +fn surface_curve_with_pcurves_shares_its_surface() { + // A seam on a cylinder of radius 5: the line x = 5 with pcurves u = 0 on both sides. + let c = curve( + "#10=CYLINDRICAL_SURFACE('',#4,5.);#11=CARTESIAN_POINT('',(5.,0.,0.));#12=VECTOR('',#2,1.);#13=LINE('',#11,#12);\ + #20=CARTESIAN_POINT('',(0.,0.));#21=DIRECTION('',(0.,1.));#22=VECTOR('',#21,1.);#23=LINE('',#20,#22);\ + #24=(GEOMETRIC_REPRESENTATION_CONTEXT(2)PARAMETRIC_REPRESENTATION_CONTEXT()REPRESENTATION_CONTEXT('2D SPACE',''));\ + #25=DEFINITIONAL_REPRESENTATION('',(#23),#24);#26=PCURVE('',#10,#25);\ + #27=CARTESIAN_POINT('',(6.28318530717959,0.));#28=LINE('',#27,#22);#29=DEFINITIONAL_REPRESENTATION('',(#28),#24);#30=PCURVE('',#10,#29);\ + #31=SEAM_CURVE('',#13,(#26,#30),.PCURVE_S1.);", + 31, + MM, + ); + let Curve::SurfaceCurve { kind, associated, master, curve_3d } = &*c else { panic!("{c:?}") }; + assert_eq!((*kind, *master), (SurfaceCurveKind::Seam, PreferredRep::PcurveS1)); + at_curve(curve_3d, 3.0, [5.0, 0.0, 3.0]); + let [Associated::Pcurve(a), Associated::Pcurve(b)] = associated.as_slice() else { panic!("{associated:?}") }; + assert!(Arc::ptr_eq(&a.surface, &b.surface), "one surface entity, read once"); + // Each pcurve, lifted onto the surface, is the 3D curve. + for t in [0.0, 2.0] { + for pc in [a, b] { + let uv = pc.curve.point(t).unwrap_or_default(); + let p = pc.surface.point(uv[0], uv[1]).unwrap_or_default(); + assert!(close(p, curve_3d.point(t).unwrap_or_default()), "{p:?}"); + } + } + round_trip_curve(&c, &[0.0, 1.0, 4.0]); +} + +#[test] +fn pcurves_scale_with_the_surface_parameters() { + // Inches and degrees: a cylinder pcurve's u is an angle, v a length. + let units = Units { len: 25.4, ang: PI / 180.0 }; + let c = curve( + "#10=CYLINDRICAL_SURFACE('',#4,1.);#11=CARTESIAN_POINT('',(1.,0.,0.));#12=VECTOR('',#2,1.);#13=LINE('',#11,#12);\ + #20=CARTESIAN_POINT('',(90.,0.));#21=DIRECTION('',(0.,1.));#22=VECTOR('',#21,1.);#23=LINE('',#20,#22);\ + #24=(GEOMETRIC_REPRESENTATION_CONTEXT(2)PARAMETRIC_REPRESENTATION_CONTEXT()REPRESENTATION_CONTEXT('2D SPACE',''));\ + #25=DEFINITIONAL_REPRESENTATION('',(#23),#24);#26=PCURVE('',#10,#25);#27=SURFACE_CURVE('',#13,(#26),.CURVE_3D.);", + 27, + units, + ); + let Curve::SurfaceCurve { associated, .. } = &*c else { panic!("{c:?}") }; + let Some(Associated::Pcurve(pc)) = associated.first() else { panic!("{associated:?}") }; + let uv = pc.curve.point(2.0).unwrap_or_default(); + assert!((uv[0] - FRAC_PI_2).abs() < 1e-12 && (uv[1] - 2.0 * 25.4).abs() < 1e-9, "{uv:?}"); + at_surface(&pc.surface, uv[0], uv[1], [0.0, 25.4, 50.8]); +} + +#[test] +fn analytic_surfaces() { + let p = surface("#10=PLANE('',#4);", 10, MM); + at_surface(&p, 2.0, 3.0, [2.0, 3.0, 0.0]); + round_trip_surface(&p, &UVS); + let c = surface("#10=CYLINDRICAL_SURFACE('',#4,5.);", 10, MM); + at_surface(&c, FRAC_PI_2, 7.0, [0.0, 5.0, 7.0]); + round_trip_surface(&c, &UVS); + let k = surface("#10=CONICAL_SURFACE('',#4,5.,0.785398163397448);", 10, MM); + at_surface(&k, 0.0, 2.0, [7.0, 0.0, 2.0]); + round_trip_surface(&k, &UVS); + let s = surface("#10=SPHERICAL_SURFACE('',#4,3.);", 10, MM); + at_surface(&s, 0.0, FRAC_PI_2, [0.0, 0.0, 3.0]); + at_surface(&s, PI, 0.0, [-3.0, 0.0, 0.0]); + round_trip_surface(&s, &UVS); + let t = surface("#10=TOROIDAL_SURFACE('',#4,10.,2.);", 10, MM); + at_surface(&t, FRAC_PI_2, PI, [0.0, 8.0, 0.0]); + round_trip_surface(&t, &UVS); + let d = surface("#10=DEGENERATE_TOROIDAL_SURFACE('',#4,1.,2.,.T.);", 10, MM); + assert!(matches!(*d, Surface::DegenerateTorus { select_outer: true, .. })); + round_trip_surface(&d, &UVS); +} + +#[test] +fn units_scale_lengths_and_angles() { + let units = Units { len: 25.4, ang: PI / 180.0 }; + let k = surface("#10=CONICAL_SURFACE('',#4,1.,45.);", 10, units); + let Surface::Cone { radius, semi_angle, .. } = *k else { panic!("{k:?}") }; + assert!((radius - 25.4).abs() < 1e-12 && (semi_angle - FRAC_PI_4).abs() < 1e-15); + let c = curve("#10=CARTESIAN_POINT('',(1.,0.,0.));#11=VECTOR('',#3,2.);#12=LINE('',#10,#11);", 12, units); + at_curve(&c, 1.0, [76.2, 0.0, 0.0]); +} + +#[test] +fn placement_axes_are_made_orthonormal() { + // A reference direction not perpendicular to the axis is projected; the axis is unit. + let s = surface("#10=DIRECTION('',(0.,0.,2.));#11=DIRECTION('',(1.,0.,1.));#12=AXIS2_PLACEMENT_3D('',#1,#10,#11);#13=PLANE('',#12);", 13, MM); + let Surface::Plane { position } = *s else { panic!("{s:?}") }; + assert_eq!((position.axis, position.ref_direction), ([0.0, 0.0, 1.0], [1.0, 0.0, 0.0])); +} + +#[test] +fn bspline_surfaces() { + // A bilinear patch over the unit square, then the same as a rational complex entity. + let pts = "#10=CARTESIAN_POINT('',(0.,0.,0.));#11=CARTESIAN_POINT('',(0.,1.,0.));#12=CARTESIAN_POINT('',(1.,0.,0.));#13=CARTESIAN_POINT('',(1.,1.,1.));"; + let s = surface( + &format!( + "{pts}#14=B_SPLINE_SURFACE_WITH_KNOTS('',1,1,((#10,#11),(#12,#13)),.UNSPECIFIED.,.F.,.F.,.F.,(2,2),(2,2),(0.,1.),(0.,1.),.UNSPECIFIED.);" + ), + 14, + MM, + ); + at_surface(&s, 0.5, 0.5, [0.5, 0.5, 0.25]); + at_surface(&s, 1.0, 0.0, [1.0, 0.0, 0.0]); + round_trip_surface(&s, &[(0.0, 0.0), (0.3, 0.7), (1.0, 1.0)]); + let r = surface( + &format!( + "{pts}#14=(BOUNDED_SURFACE()B_SPLINE_SURFACE(1,1,((#10,#11),(#12,#13)),.UNSPECIFIED.,.F.,.F.,.F.)\ + B_SPLINE_SURFACE_WITH_KNOTS((2,2),(2,2),(0.,1.),(0.,1.),.UNSPECIFIED.)GEOMETRIC_REPRESENTATION_ITEM()\ + RATIONAL_B_SPLINE_SURFACE(((1.,1.),(1.,1.)))REPRESENTATION_ITEM('')SURFACE());" + ), + 14, + MM, + ); + let Surface::BSpline(b) = &*r else { panic!("{r:?}") }; + assert!(b.weights.is_some()); + at_surface(&r, 0.5, 0.5, [0.5, 0.5, 0.25]); + round_trip_surface(&r, &[(0.0, 0.0), (0.3, 0.7), (1.0, 1.0)]); +} + +#[test] +fn swept_surfaces() { + // A circle of radius 2 about the Z axis, centred at x = 10: revolved, a torus. + let rev = surface( + "#10=CARTESIAN_POINT('',(10.,0.,0.));#11=AXIS2_PLACEMENT_3D('',#10,#5,#3);#12=CIRCLE('',#11,2.);\ + #13=AXIS1_PLACEMENT('',#1,#2);#14=SURFACE_OF_REVOLUTION('',#12,#13);", + 14, + MM, + ); + at_surface(&rev, 0.0, 0.0, [12.0, 0.0, 0.0]); + at_surface(&rev, FRAC_PI_2, 0.0, [0.0, 12.0, 0.0]); + round_trip_surface(&rev, &UVS); + let ext = surface("#10=CIRCLE('',#4,3.);#11=VECTOR('',#2,4.);#12=SURFACE_OF_LINEAR_EXTRUSION('',#10,#11);", 12, MM); + at_surface(&ext, FRAC_PI_2, 0.5, [0.0, 3.0, 2.0]); + round_trip_surface(&ext, &UVS); +} + +#[test] +fn offset_and_trimmed_surfaces() { + let o = surface("#10=CYLINDRICAL_SURFACE('',#4,5.);#11=OFFSET_SURFACE('',#10,1.5,.F.);", 11, MM); + at_surface(&o, 0.0, 1.0, [6.5, 0.0, 1.0]); + round_trip_surface(&o, &UVS); + let deg = Units { len: 1.0, ang: PI / 180.0 }; + let t = surface("#10=CYLINDRICAL_SURFACE('',#4,5.);#11=RECTANGULAR_TRIMMED_SURFACE('',#10,0.,90.,0.,10.,.T.,.T.);", 11, deg); + let Surface::RectangularTrimmed { u2, v2, .. } = *t else { panic!("{t:?}") }; + assert!((u2 - FRAC_PI_2).abs() < 1e-15 && v2 == 10.0, "{u2} {v2}"); + round_trip_surface(&t, &UVS); +} + +#[test] +fn offset_curve_reads_and_round_trips() { + let c = curve("#10=CIRCLE('',#4,10.);#11=OFFSET_CURVE_3D('',#10,1.,.F.,#2);", 11, MM); + assert!(matches!(*c, Curve::OffsetCurve3d { distance, self_intersect: Logical::False, .. } if distance == 1.0)); + round_trip_curve(&c, &[]); +} + +#[test] +fn shared_entities_are_written_once() { + let c = Arc::new(Curve::Circle { + position: crate::geom::Placement { origin: [0.0; 3], axis: [0.0, 0.0, 1.0], ref_direction: [1.0, 0.0, 0.0] }, + radius: 1.0, + }); + let mut w = Writer::new(); + let mut g = GeomWriter::new(&mut w); + let a = g.curve(&c); + let b = g.curve(&c); + assert_eq!(a, b); + // Point, two directions, placement, circle. + assert_eq!(w.len(), 5); +} + +#[test] +fn hostile_geometry_is_an_error_never_a_panic() { + let cases = [ + "#10=CIRCLE('',#4,-1.);", + "#10=CIRCLE('',#99,1.);", + "#10=CIRCLE('',#4,1.E300);", + "#10=LINE('',#1,#1);", + "#10=DIRECTION('',(0.,0.,0.));#11=VECTOR('',#10,1.);#12=LINE('',#1,#11);", + "#10=B_SPLINE_CURVE_WITH_KNOTS('',2,(#1,#1),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.UNSPECIFIED.);", + "#10=B_SPLINE_CURVE_WITH_KNOTS('',99,(#1,#1),.UNSPECIFIED.,.F.,.F.,(1,1),(0.,1.),.UNSPECIFIED.);", + "#10=B_SPLINE_CURVE_WITH_KNOTS('',1,(#1,#1),.UNSPECIFIED.,.F.,.F.,(4000000000000,1),(0.,1.),.UNSPECIFIED.);", + "#10=B_SPLINE_CURVE_WITH_KNOTS('',1,(#1,#1),.UNSPECIFIED.,.F.,.F.,(2,2),(1.,0.),.UNSPECIFIED.);", + "#10=(B_SPLINE_CURVE(1,(#1,#1),.UNSPECIFIED.,.F.,.F.)B_SPLINE_CURVE_WITH_KNOTS((2,2),(0.,1.),.UNSPECIFIED.)RATIONAL_B_SPLINE_CURVE((1.,-1.)));", + "#10=TRIMMED_CURVE('',#10,(PARAMETER_VALUE(0.)),(PARAMETER_VALUE(1.)),.T.,.PARAMETER.);", + "#10=SURFACE_CURVE('',#10,(),.CURVE_3D.);", + "#10=POLYLINE('',(#1));", + "#10=UNKNOWN_CURVE('');", + ]; + for c in cases { + let ex = file(&format!("{BASE}{c}")); + assert!(Reader::new(&ex, MM).curve(10).is_err(), "{c}"); + } + let surfaces = [ + "#10=CYLINDRICAL_SURFACE('',#4,0.);", + "#10=CONICAL_SURFACE('',#4,1.,2.);", + "#10=TOROIDAL_SURFACE('',#4,1.,-2.);", + "#10=OFFSET_SURFACE('',#10,1.,.F.);", + "#10=B_SPLINE_SURFACE_WITH_KNOTS('',1,1,((#1,#1),(#1)),.UNSPECIFIED.,.F.,.F.,.F.,(2,2),(2,2),(0.,1.),(0.,1.),.UNSPECIFIED.);", + "#10=SURFACE_OF_REVOLUTION('',#10,#4);", + "#10=PLANE('',#3);", + ]; + for s in surfaces { + let ex = file(&format!("{BASE}{s}")); + assert!(Reader::new(&ex, MM).surface(10).is_err(), "{s}"); + } +} + +/// Every edge curve and face surface of every STEP file in `SOLIDCRAFT_STEP_CORPUS` (the +/// tangency-labs/models files): read, written, read back. Run with `--ignored`. +#[test] +#[ignore = "needs SOLIDCRAFT_STEP_CORPUS"] +fn corpus_geometry_reads_and_round_trips() { + let Ok(dir) = std::env::var("SOLIDCRAFT_STEP_CORPUS") else { return }; + let mut paths: Vec<_> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).collect(); + paths.sort(); + let mut failed = 0; + for path in paths.iter().filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("step") || e.eq_ignore_ascii_case("stp"))) { + let text = std::fs::read_to_string(path).unwrap_or_default(); + let t0 = std::time::Instant::now(); + let ex = p21::parse(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let mut reader = Reader::new(&ex, MM); + let (mut curves, mut surfaces) = (Vec::new(), Vec::new()); + let mut errors: std::collections::BTreeMap = Default::default(); + let mut ids: Vec = ex.entities.keys().copied().collect(); + ids.sort_unstable(); + for id in ids { + let Some(e) = ex.get(id) else { continue }; + let (r, is_curve) = match e.name() { + "EDGE_CURVE" => (e.params().get(3).and_then(p21::Param::as_ref_id), true), + "ADVANCED_FACE" | "FACE_SURFACE" => (e.params().get(2).and_then(p21::Param::as_ref_id), false), + _ => continue, + }; + let Some(r) = r else { continue }; + let got = if is_curve { reader.curve(r).map(|c| curves.push(c)) } else { reader.surface(r).map(|s| surfaces.push(s)) }; + if let Err(e) = got { + *errors.entry(e).or_default() += 1; + } + } + let read = t0.elapsed(); + let mut w = Writer::new(); + let mut g = GeomWriter::new(&mut w); + let cids: Vec = curves.iter().map(|c| g.curve(c)).collect(); + let sids: Vec = surfaces.iter().map(|s| g.surface(s)).collect(); + let out = w.file("corpus", "AUTOMOTIVE_DESIGN"); + let back = p21::parse(&out).unwrap_or_else(|e| panic!("{}: written file: {e}", path.display())); + let mut again = Reader::new(&back, MM); + let mut mismatched = 0; + for (c, id) in curves.iter().zip(&cids) { + match again.curve(*id) { + Ok(b) + if (0..=4).map(|i| i as f64 * 0.25).all(|t| match (c.point(t), b.point(t)) { + (Some(x), Some(y)) => close(x, y), + (x, y) => x.is_none() && y.is_none(), + }) => {} + _ => mismatched += 1, + } + } + for (s, id) in surfaces.iter().zip(&sids) { + match again.surface(*id) { + Ok(b) + if [(0.0, 0.0), (0.3, 0.6)].iter().all(|&(u, v)| match (s.point(u, v), b.point(u, v)) { + (Some(x), Some(y)) => close(x, y), + (x, y) => x.is_none() && y.is_none(), + }) => {} + _ => mismatched += 1, + } + } + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + println!( + "{name}: {} edge curves, {} face surfaces read in {:.0} ms; {} unread; {mismatched} differ after a round trip", + curves.len(), + surfaces.len(), + read.as_secs_f64() * 1e3, + errors.values().sum::() + ); + for (e, n) in &errors { + println!(" {n} × {e}"); + } + failed += mismatched + errors.values().sum::(); + } + assert_eq!(failed, 0); +} diff --git a/crates/step/src/lib.rs b/crates/step/src/lib.rs new file mode 100644 index 000000000..3a6c4720a --- /dev/null +++ b/crates/step/src/lib.rs @@ -0,0 +1,18 @@ +//! STEP (ISO 10303) for SolidCraft, independent of any modelling backend. [`p21`] reads the +//! exchange structure, [`read`] turns its geometry entities into the plain curves and surfaces +//! of [`geom`], and [`write`] writes them back. Written from the public ISO 10303-21 and -42 +//! specifications. [`topology`] reads solids (vertices to shells) into the kernel-neutral B-rep, +//! schema 4, and [`units`] the units of a representation context. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +mod eval; +pub mod geom; +pub mod p21; +pub mod read; +pub mod topology; +pub mod units; +pub mod write; + +#[cfg(test)] +mod geom_tests; diff --git a/crates/step/src/p21.rs b/crates/step/src/p21.rs new file mode 100644 index 000000000..fec135fec --- /dev/null +++ b/crates/step/src/p21.rs @@ -0,0 +1,590 @@ +//! ISO 10303-21 ("Part 21") exchange structure parser: the HEADER and the DATA section's entity +//! instances, simple (`#1=NAME(...)`) and complex (`#2=(A(...) B(...))`). Written from the +//! public standard. Input is hostile: sizes, entity counts and nesting depth are capped and every +//! error is a message, never a panic. + +use std::collections::HashMap; + +/// Largest STEP text we parse. +pub const MAX_BYTES: usize = 512 << 20; +/// Most entity instances in one file. +pub const MAX_ENTITIES: usize = 20_000_000; +/// Deepest parameter list nesting. +const MAX_DEPTH: usize = 64; + +/// A parameter value. +#[derive(Clone, Debug, PartialEq)] +pub enum Param { + Int(i64), + Real(f64), + Str(String), + /// `.NAME.` (`.T.`/`.F.` included). + Enum(String), + Ref(u64), + List(Vec), + /// `NAME(params)` (a typed value such as `LENGTH_MEASURE(1.)`). + Typed(String, Vec), + Binary(String), + /// `$` + Null, + /// `*` + Derived, +} + +impl Param { + pub fn as_f64(&self) -> Option { + match self { + Param::Real(x) => Some(*x).filter(|x| x.is_finite()), + Param::Int(i) => Some(*i as f64), + Param::Typed(_, v) if v.len() == 1 => v.first().and_then(Param::as_f64), + _ => None, + } + } + pub fn as_i64(&self) -> Option { + match self { + Param::Int(i) => Some(*i), + Param::Real(x) if x.fract() == 0.0 && x.abs() < 9e15 => Some(*x as i64), + _ => None, + } + } + pub fn as_ref_id(&self) -> Option { + match self { + Param::Ref(r) => Some(*r), + _ => None, + } + } + pub fn as_str(&self) -> Option<&str> { + match self { + Param::Str(s) => Some(s), + _ => None, + } + } + pub fn as_enum(&self) -> Option<&str> { + match self { + Param::Enum(s) => Some(s), + _ => None, + } + } + /// `.T.` → true, `.F.` → false (`.U.` and anything else → None). + pub fn as_bool(&self) -> Option { + match self.as_enum()? { + "T" => Some(true), + "F" => Some(false), + _ => None, + } + } + pub fn as_list(&self) -> Option<&[Param]> { + match self { + Param::List(v) => Some(v), + _ => None, + } + } +} + +/// One record of an entity instance: a simple instance has one, a complex one several. +#[derive(Clone, Debug, PartialEq)] +pub struct Record { + pub name: String, + pub params: Vec, +} + +/// An entity instance. +#[derive(Clone, Debug, PartialEq)] +pub struct Entity { + pub records: Vec, +} + +impl Entity { + pub fn is_complex(&self) -> bool { + self.records.len() > 1 + } + /// Name of a simple instance (the first record of a complex one). + pub fn name(&self) -> &str { + self.records.first().map(|r| r.name.as_str()).unwrap_or("") + } + /// Parameters of the record called `name`. + pub fn record(&self, name: &str) -> Option<&[Param]> { + self.records.iter().find(|r| r.name == name).map(|r| r.params.as_slice()) + } + pub fn has(&self, name: &str) -> bool { + self.records.iter().any(|r| r.name == name) + } + /// Parameters of a simple instance. + pub fn params(&self) -> &[Param] { + self.records.first().map(|r| r.params.as_slice()).unwrap_or(&[]) + } +} + +/// A parsed exchange file. +#[derive(Clone, Debug, Default)] +pub struct Exchange { + /// FILE_SCHEMA names. + pub schemas: Vec, + /// FILE_NAME originating system. + pub originating_system: String, + /// FILE_NAME preprocessor version. + pub preprocessor: String, + /// FILE_DESCRIPTION text, its lines joined by a space. + pub description: String, + pub entities: HashMap, + /// Ids defined more than once (the first definition is kept). + pub duplicates: Vec, +} + +impl Exchange { + pub fn get(&self, id: u64) -> Option<&Entity> { + self.entities.get(&id) + } +} + +struct Lexer<'a> { + s: &'a [u8], + i: usize, +} + +fn err(msg: impl Into) -> Result { + Err(msg.into()) +} + +impl<'a> Lexer<'a> { + fn line(&self) -> usize { + self.s.get(..self.i).map(|b| b.iter().filter(|c| **c == b'\n').count() + 1).unwrap_or(0) + } + fn fail(&self, msg: &str) -> Result { + err(format!("STEP syntax error at line {}: {msg}", self.line())) + } + fn peek(&self) -> Option { + self.s.get(self.i).copied() + } + /// Skip whitespace and comments. + fn ws(&mut self) -> Result<(), String> { + loop { + match self.peek() { + Some(c) if c.is_ascii_whitespace() => self.i += 1, + Some(b'/') if self.s.get(self.i + 1) == Some(&b'*') => { + let rest = self.s.get(self.i + 2..).unwrap_or(&[]); + match rest.windows(2).position(|w| w == b"*/") { + Some(p) => self.i += p + 4, + None => return self.fail("unterminated comment"), + } + } + _ => return Ok(()), + } + } + } + fn eat(&mut self, c: u8) -> Result { + self.ws()?; + if self.peek() == Some(c) { + self.i += 1; + Ok(true) + } else { + Ok(false) + } + } + fn expect(&mut self, c: u8) -> Result<(), String> { + if self.eat(c)? { Ok(()) } else { self.fail(&format!("expected `{}`", c as char)) } + } + fn keyword(&mut self) -> Result { + self.ws()?; + let st = self.i; + if self.peek() == Some(b'!') { + self.i += 1; + } + while let Some(c) = self.peek() { + if c.is_ascii_alphanumeric() || c == b'_' || c == b'-' { + self.i += 1; + } else { + break; + } + } + if self.i == st { + return self.fail("expected a keyword"); + } + Ok(String::from_utf8_lossy(self.s.get(st..self.i).unwrap_or(&[])).to_ascii_uppercase()) + } + fn number(&mut self) -> Result { + let st = self.i; + while let Some(c) = self.peek() { + if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.' | b'E' | b'e') { + self.i += 1; + } else { + break; + } + } + let t = std::str::from_utf8(self.s.get(st..self.i).unwrap_or(&[])).unwrap_or(""); + if !t.contains(['.', 'E', 'e']) + && let Ok(i) = t.parse::() + { + return Ok(Param::Int(i)); + } + // STEP allows `1.` and `1.E-3`. + let fixed = t.replace(".E", ".0E").replace(".e", ".0e"); + let fixed = if fixed.ends_with('.') { format!("{fixed}0") } else { fixed }; + match fixed.parse::() { + Ok(x) => Ok(Param::Real(x)), + Err(_) => self.fail(&format!("bad number `{t}`")), + } + } + fn string(&mut self) -> Result { + // Opening quote consumed by the caller. + let mut raw = Vec::new(); + loop { + match self.peek() { + None => return self.fail("unterminated string"), + Some(b'\'') => { + if self.s.get(self.i + 1) == Some(&b'\'') { + raw.push(b'\''); + self.i += 2; + } else { + self.i += 1; + break; + } + } + Some(b'\n') | Some(b'\r') => self.i += 1, + Some(c) => { + raw.push(c); + self.i += 1; + } + } + } + Ok(decode_string(&raw)) + } + fn param(&mut self, depth: usize) -> Result { + if depth > MAX_DEPTH { + return self.fail("parameters nested too deeply"); + } + self.ws()?; + let Some(c) = self.peek() else { return self.fail("unexpected end of file") }; + match c { + b'$' => { + self.i += 1; + Ok(Param::Null) + } + b'*' => { + self.i += 1; + Ok(Param::Derived) + } + b'\'' => { + self.i += 1; + Ok(Param::Str(self.string()?)) + } + b'"' => { + self.i += 1; + let st = self.i; + while self.peek().is_some_and(|c| c != b'"') { + self.i += 1; + } + let v = String::from_utf8_lossy(self.s.get(st..self.i).unwrap_or(&[])).to_string(); + self.expect(b'"')?; + Ok(Param::Binary(v)) + } + b'#' => { + self.i += 1; + let st = self.i; + while self.peek().is_some_and(|c| c.is_ascii_digit()) { + self.i += 1; + } + let t = std::str::from_utf8(self.s.get(st..self.i).unwrap_or(&[])).unwrap_or(""); + t.parse::().map(Param::Ref).or_else(|_| self.fail("bad entity reference")) + } + b'.' if self.s.get(self.i + 1).is_some_and(|c| c.is_ascii_alphabetic() || *c == b'_') => { + self.i += 1; + let st = self.i; + while self.peek().is_some_and(|c| c != b'.') { + self.i += 1; + } + let v = String::from_utf8_lossy(self.s.get(st..self.i).unwrap_or(&[])).trim().to_ascii_uppercase(); + self.expect(b'.')?; + Ok(Param::Enum(v)) + } + b'(' => { + self.i += 1; + Ok(Param::List(self.list_rest(depth + 1)?)) + } + c if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') => self.number(), + c if c.is_ascii_alphabetic() || c == b'!' => { + let name = self.keyword()?; + self.expect(b'(')?; + Ok(Param::Typed(name, self.list_rest(depth + 1)?)) + } + _ => self.fail(&format!("unexpected `{}`", c as char)), + } + } + /// Parameters after an opening `(` up to and including the `)`. + fn list_rest(&mut self, depth: usize) -> Result, String> { + let mut v = Vec::new(); + if self.eat(b')')? { + return Ok(v); + } + loop { + v.push(self.param(depth)?); + if self.eat(b',')? { + continue; + } + self.expect(b')')?; + return Ok(v); + } + } + fn record(&mut self) -> Result { + let name = self.keyword()?; + self.expect(b'(')?; + Ok(Record { name, params: self.list_rest(1)? }) + } +} + +/// Decode the Part 21 string escapes (`\X\hh`, `\X2\…\X0\`, `\X4\…\X0\`, `\S\c`, `\\`). +fn decode_string(raw: &[u8]) -> String { + let mut out = String::new(); + let mut i = 0; + let hex = |b: &[u8]| std::str::from_utf8(b).ok().and_then(|t| u32::from_str_radix(t, 16).ok()); + while let Some(&c) = raw.get(i) { + if c == b'\\' { + let rest = raw.get(i..).unwrap_or(&[]); + if rest.starts_with(b"\\\\") { + out.push('\\'); + i += 2; + continue; + } + if rest.starts_with(b"\\X\\") + && let Some(v) = rest.get(3..5).and_then(hex) + { + out.push(char::from_u32(v).unwrap_or('?')); + i += 5; + continue; + } + let mut run = false; + for (tag, width) in [(&b"\\X2\\"[..], 4usize), (&b"\\X4\\"[..], 8)] { + if rest.starts_with(tag) + && let Some(end) = rest.windows(4).position(|w| w == b"\\X0\\") + { + let body = rest.get(4..end).unwrap_or(&[]); + let units: Vec = body.chunks(width).filter_map(hex).collect(); + if width == 4 { + let u16s: Vec = units.iter().map(|u| *u as u16).collect(); + out.push_str(&String::from_utf16_lossy(&u16s)); + } else { + out.extend(units.iter().map(|u| char::from_u32(*u).unwrap_or('?'))); + } + i += end + 4; + run = true; + break; + } + } + // A run may be followed straight away by the backslash of the next escape (#2344). + if run { + continue; + } + if rest.starts_with(b"\\S\\") + && let Some(&ch) = rest.get(3) + { + out.push(char::from_u32(ch as u32 + 128).unwrap_or('?')); + i += 4; + continue; + } + out.push('\\'); + i += 1; + continue; + } + // Plain bytes: keep UTF-8 runs intact. + let st = i; + while raw.get(i).is_some_and(|c| *c != b'\\') { + i += 1; + } + out.push_str(&String::from_utf8_lossy(raw.get(st..i).unwrap_or(&[]))); + } + out +} + +/// Parse a Part 21 file. +/// Someone waiting for a long parse: told how far it is, and able to stop it. +pub trait Progress { + /// Stop at the next check. + fn cancelled(&self) -> bool; + /// `done` of `total` bytes read. + fn progress(&self, stage: &'static str, done: usize, total: usize); +} + +/// Parse an exchange structure. +pub fn parse(text: &str) -> Result { + parse_with(text, None) +} + +/// [`parse`], reporting progress to `watch` and stopping when it cancels. +pub fn parse_with(text: &str, watch: Option<&dyn Progress>) -> Result { + if text.len() > MAX_BYTES { + return err(format!("STEP file too large ({} MB, limit {} MB)", text.len() >> 20, MAX_BYTES >> 20)); + } + let mut lx = Lexer { s: text.as_bytes(), i: 0 }; + let magic = lx.keyword()?; + if magic != "ISO-10303-21" { + return err("not a STEP file (no ISO-10303-21 header)"); + } + lx.expect(b';')?; + let mut ex = Exchange::default(); + loop { + lx.ws()?; + if lx.peek().is_none() { + return err("STEP file ends without END-ISO-10303-21"); + } + let kw = lx.keyword()?; + match kw.as_str() { + "HEADER" => { + lx.expect(b';')?; + loop { + let k = lx.keyword()?; + if k == "ENDSEC" { + lx.expect(b';')?; + break; + } + lx.expect(b'(')?; + let params = lx.list_rest(1)?; + lx.expect(b';')?; + match k.as_str() { + "FILE_SCHEMA" => { + if let Some(Param::List(v)) = params.first() { + ex.schemas = v.iter().filter_map(|p| p.as_str().map(str::to_string)).collect(); + } + } + "FILE_DESCRIPTION" => { + if let Some(Param::List(v)) = params.first() { + ex.description = v.iter().filter_map(|p| p.as_str()).collect::>().join(" "); + } + } + "FILE_NAME" => { + ex.preprocessor = params.get(4).and_then(Param::as_str).unwrap_or("").to_string(); + ex.originating_system = params.get(5).and_then(Param::as_str).unwrap_or("").to_string(); + } + _ => {} + } + } + } + "DATA" => { + // Optional `DATA('name', ('schema'));` + if lx.eat(b'(')? { + lx.list_rest(1)?; + } + lx.expect(b';')?; + loop { + lx.ws()?; + if lx.peek() != Some(b'#') { + let k = lx.keyword()?; + if k == "ENDSEC" { + lx.expect(b';')?; + break; + } + return lx.fail(&format!("unexpected `{k}` in DATA")); + } + lx.i += 1; + let st = lx.i; + while lx.peek().is_some_and(|c| c.is_ascii_digit()) { + lx.i += 1; + } + let id: u64 = match std::str::from_utf8(lx.s.get(st..lx.i).unwrap_or(&[])).ok().and_then(|t| t.parse().ok()) { + Some(id) => id, + None => return lx.fail("bad entity id"), + }; + lx.expect(b'=')?; + let records = if lx.eat(b'(')? { + let mut rs = Vec::new(); + while !lx.eat(b')')? { + if rs.len() > 64 { + return lx.fail("complex entity with too many parts"); + } + rs.push(lx.record()?); + } + rs + } else { + vec![lx.record()?] + }; + lx.expect(b';')?; + if ex.entities.len() % 4096 == 0 + && let Some(w) = watch + { + if w.cancelled() { + return err("STEP import cancelled"); + } + w.progress("reading", lx.i, lx.s.len()); + } + if ex.entities.len() >= MAX_ENTITIES { + return err(format!("STEP file has more than {MAX_ENTITIES} entities")); + } + // A duplicate id is invalid; some writers emit them for geometry nobody + // reads. Keep the first definition and report it. + match ex.entities.entry(id) { + std::collections::hash_map::Entry::Occupied(_) => ex.duplicates.push(id), + std::collections::hash_map::Entry::Vacant(v) => { + v.insert(Entity { records }); + } + } + } + } + "END-ISO-10303-21" => { + lx.expect(b';')?; + return Ok(ex); + } + // ANCHOR / REFERENCE / SIGNATURE sections (Part 21 edition 3): skip to ENDSEC. + "ANCHOR" | "REFERENCE" | "SIGNATURE" => { + let rest = lx.s.get(lx.i..).unwrap_or(&[]); + match rest.windows(7).position(|w| w == b"ENDSEC;") { + Some(p) => lx.i += p + 7, + None => return lx.fail("unterminated section"), + } + } + _ => return lx.fail(&format!("unexpected `{kw}`")), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_simple_and_complex() { + let t = "ISO-10303-21;\nHEADER;FILE_DESCRIPTION((''),'2;1');\nFILE_NAME('a','',(''),(''),'','sys','');\nFILE_SCHEMA(('AUTOMOTIVE_DESIGN'));ENDSEC;\nDATA;\n#1=CARTESIAN_POINT('p',(0.,1.5E1,-2));\n/* c */ #2=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#3=X('it''s','\\X2\\00E9\\X0\\',$,#1,LENGTH_MEASURE(1.E-3),\"0F\");\nENDSEC;\nEND-ISO-10303-21;\n"; + let ex = parse(t).unwrap(); + assert_eq!(ex.schemas, vec!["AUTOMOTIVE_DESIGN"]); + assert_eq!(ex.originating_system, "sys"); + let p = ex.get(1).unwrap(); + assert_eq!(p.name(), "CARTESIAN_POINT"); + let xyz: Vec = p.params()[1].as_list().unwrap().iter().filter_map(Param::as_f64).collect(); + assert_eq!(xyz, vec![0.0, 15.0, -2.0]); + let u = ex.get(2).unwrap(); + assert!(u.is_complex() && u.has("SI_UNIT")); + assert_eq!(u.record("SI_UNIT").unwrap()[0].as_enum(), Some("MILLI")); + let x = ex.get(3).unwrap().params(); + assert_eq!(x[0].as_str(), Some("it's")); + assert_eq!(x[1].as_str(), Some("\u{e9}")); + assert_eq!(x[2], Param::Null); + assert_eq!(x[3].as_ref_id(), Some(1)); + assert_eq!(x[4].as_f64(), Some(1e-3)); + } + + #[test] + fn hostile_text_is_an_error() { + for t in [ + "", + "garbage", + "ISO-10303-21;", + "ISO-10303-21;DATA;#1=A(", + "ISO-10303-21;DATA;#1=A('x", + "ISO-10303-21;DATA;#1=A(/*", + "ISO-10303-21;DATA;#=A();ENDSEC;END-ISO-10303-21;", + "ISO-10303-21;DATA;#99999999999999999999999=A();ENDSEC;END-ISO-10303-21;", + "ISO-10303-21;DATA;#1=A(1e999999.);ENDSEC;END-ISO-10303-21;", + ] { + let _ = parse(t); + } + let deep = format!("ISO-10303-21;DATA;#1=A({}{});ENDSEC;END-ISO-10303-21;", "(".repeat(10_000), ")".repeat(10_000)); + assert!(parse(&deep).is_err()); + let dup = parse("ISO-10303-21;DATA;#1=A(1);#1=B();ENDSEC;END-ISO-10303-21;").unwrap(); + assert_eq!(dup.duplicates, vec![1]); + assert_eq!(dup.get(1).unwrap().name(), "A"); + assert_eq!(decode_string(b"\\X\\E9"), "\u{e9}"); + assert_eq!(decode_string(b"a\\X2\\00E900E8\\X0\\b"), "a\u{e9}\u{e8}b"); + assert_eq!(decode_string(b"\\"), "\\"); + // One run per character, as `step_out` writes them (#2344). + assert_eq!(decode_string(b"\\X2\\5706\\X0\\\\X2\\89D2\\X0\\20"), "\u{5706}\u{89d2}20"); + assert_eq!(decode_string(b"\\X4\\0001F600\\X0\\\\X2\\00E9\\X0\\\\S\\a"), "\u{1f600}\u{e9}\u{e1}"); + } +} diff --git a/crates/step/src/read.rs b/crates/step/src/read.rs new file mode 100644 index 000000000..f9c9c11fa --- /dev/null +++ b/crates/step/src/read.rs @@ -0,0 +1,772 @@ +//! STEP geometry entities to [`crate::geom`]. Written from ISO 10303-42 (geometry) and +//! ISO 10303-21 (the exchange structure). Input is hostile: every count, number and reference is +//! checked, nesting is capped, and shared entities are read once. + +use std::collections::HashMap; +use std::sync::Arc; + +use crate::geom::{ + Associated, Axis1, BSplineCurve, BSplineSurface, Curve, CurveForm, KnotSpec, Logical, P3, Pcurve, Placement, PreferredRep, Surface, + SurfaceCurveKind, SurfaceForm, Trim, TrimPreference, dot, norm, scale, sub, +}; +use crate::p21::{Entity, Exchange, Param}; + +pub type R = Result; + +/// Geometry nesting we follow (a trimmed curve of a surface curve of …). +pub const MAX_GEOM_DEPTH: usize = 12; +/// Most control points in one B-spline (the whole net for a surface). +pub const MAX_CTRL: usize = 1_000_000; +/// Largest coordinate or length, in file units. +pub const MAX_COORD: f64 = 1e9; +/// Highest B-spline degree. +pub const MAX_DEGREE: usize = 32; + +/// The units of a representation context. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Units { + /// Millimetres per file length unit. + pub len: f64, + /// Radians per file plane angle unit. + pub ang: f64, +} + +impl Default for Units { + fn default() -> Self { + Units { len: 1.0, ang: 1.0 } + } +} + +/// How a parameter of a curve or surface scales from file units: angles by the angle unit, +/// lengths by the length unit, anything else (B-spline knots, ratios) not at all. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ParamKind { + Length, + Angle, + Plain, +} + +/// Reads geometry from one exchange structure, in one context's units. +pub struct Reader<'a> { + ex: &'a Exchange, + units: Units, + curves: HashMap>, + curves_2d: HashMap<(u64, [u64; 2]), Arc>, + surfaces: HashMap>, +} + +fn entity(ex: &Exchange, id: u64) -> R<&Entity> { + ex.get(id).ok_or_else(|| format!("missing entity #{id}")) +} + +fn reference(p: Option<&Param>, what: &str) -> R { + p.and_then(Param::as_ref_id).ok_or_else(|| format!("{what}: expected a reference")) +} + +fn num(p: Option<&Param>, what: &str) -> R { + let x = p.and_then(Param::as_f64).ok_or_else(|| format!("{what}: expected a number"))?; + if x.is_finite() && x.abs() < MAX_COORD { Ok(x) } else { Err(format!("{what}: {x} out of range")) } +} + +fn logical(p: Option<&Param>, what: &str) -> R { + match p.and_then(Param::as_enum) { + Some("T") => Ok(Logical::True), + Some("F") => Ok(Logical::False), + Some("U") => Ok(Logical::Unknown), + _ => Err(format!("{what}: expected a logical")), + } +} + +fn boolean(p: Option<&Param>, what: &str) -> R { + p.and_then(Param::as_bool).ok_or_else(|| format!("{what}: expected a boolean")) +} + +fn unit(v: P3, what: &str) -> R { + let m = norm(v); + if m > 1e-12 && m.is_finite() { Ok(scale(v, 1.0 / m)) } else { Err(format!("{what}: zero direction")) } +} + +fn any_perpendicular(z: P3) -> P3 { + let a = if z[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + let x = sub(a, scale(z, dot(a, z))); + scale(x, 1.0 / norm(x)) +} + +fn curve_form(p: Option<&Param>) -> CurveForm { + match p.and_then(Param::as_enum) { + Some("POLYLINE_FORM") => CurveForm::PolylineForm, + Some("CIRCULAR_ARC") => CurveForm::CircularArc, + Some("ELLIPTIC_ARC") => CurveForm::EllipticArc, + Some("PARABOLIC_ARC") => CurveForm::ParabolicArc, + Some("HYPERBOLIC_ARC") => CurveForm::HyperbolicArc, + _ => CurveForm::Unspecified, + } +} + +fn surface_form(p: Option<&Param>) -> SurfaceForm { + match p.and_then(Param::as_enum) { + Some("PLANE_SURF") => SurfaceForm::PlaneSurf, + Some("CYLINDRICAL_SURF") => SurfaceForm::CylindricalSurf, + Some("CONICAL_SURF") => SurfaceForm::ConicalSurf, + Some("SPHERICAL_SURF") => SurfaceForm::SphericalSurf, + Some("TOROIDAL_SURF") => SurfaceForm::ToroidalSurf, + Some("SURF_OF_REVOLUTION") => SurfaceForm::SurfOfRevolution, + Some("RULED_SURF") => SurfaceForm::RuledSurf, + Some("GENERALISED_CONE") => SurfaceForm::GeneralisedCone, + Some("QUADRIC_SURF") => SurfaceForm::QuadricSurf, + Some("SURF_OF_LINEAR_EXTRUSION") => SurfaceForm::SurfOfLinearExtrusion, + _ => SurfaceForm::Unspecified, + } +} + +fn knot_spec(p: Option<&Param>) -> KnotSpec { + match p.and_then(Param::as_enum) { + Some("UNIFORM_KNOTS") => KnotSpec::UniformKnots, + Some("QUASI_UNIFORM_KNOTS") => KnotSpec::QuasiUniformKnots, + Some("PIECEWISE_BEZIER_KNOTS") => KnotSpec::PiecewiseBezierKnots, + _ => KnotSpec::Unspecified, + } +} + +/// Distinct knots and multiplicities, checked against `n_ctrl` points of `degree` before +/// anything is expanded (a file can claim multiplicities that would need gigabytes). +fn knots(mults: Option<&Param>, values: Option<&Param>, n_ctrl: usize, degree: usize) -> R<(Vec, Vec)> { + let m: Vec = mults + .and_then(Param::as_list) + .ok_or("B-spline without knot multiplicities")? + .iter() + .map(|x| x.as_i64().filter(|v| *v >= 1 && *v as usize <= degree + 1).map(|v| v as usize).ok_or_else(|| "bad knot multiplicity".to_string())) + .collect::>()?; + let raw: Vec = values.and_then(Param::as_list).ok_or("B-spline without knots")?.iter().map(|x| num(Some(x), "knot")).collect::>()?; + if m.len() != raw.len() || raw.windows(2).any(|w| w.first() > w.get(1)) { + return Err("knots must not decrease, one multiplicity each".into()); + } + // Some writers list a knot twice; that is one knot with both multiplicities. + let (mut k, mut mm): (Vec, Vec) = (Vec::with_capacity(raw.len()), Vec::with_capacity(raw.len())); + for (x, n) in raw.into_iter().zip(m) { + match (k.last(), mm.last_mut()) { + (Some(last), Some(lm)) if *last == x => *lm += n, + _ => { + k.push(x); + mm.push(n); + } + } + } + let m = mm; + if k.len() < 2 || m.iter().any(|v| *v > degree + 1) { + return Err("bad knot vector".into()); + } + if m.iter().try_fold(0usize, |a, v| a.checked_add(*v)) != Some(n_ctrl + degree + 1) { + return Err("knot multiplicities do not match the control points".into()); + } + Ok((k, m)) +} + +/// Knots of a B-spline given by its type alone (BEZIER_, UNIFORM_, QUASI_UNIFORM_CURVE). +fn implied_knots(spec: KnotSpec, n_ctrl: usize, degree: usize) -> R<(Vec, Vec)> { + if n_ctrl <= degree { + return Err("too few control points".into()); + } + match spec { + KnotSpec::PiecewiseBezierKnots => { + // Segments of `degree`, full interior multiplicity. + let segs = (n_ctrl - 1) / degree; + if segs * degree + 1 != n_ctrl { + return Err("Bezier control point count".into()); + } + let k = (0..=segs).map(|s| s as f64).collect(); + let mut m = vec![degree; segs + 1]; + if let Some(f) = m.first_mut() { + *f = degree + 1; + } + if let Some(l) = m.last_mut() { + *l = degree + 1; + } + Ok((k, m)) + } + KnotSpec::UniformKnots => { + let n = n_ctrl + degree + 1; + Ok(((0..n).map(|i| i as f64 - degree as f64).collect(), vec![1; n])) + } + _ => { + // Quasi-uniform: clamped ends, uniform interior. + let inner = n_ctrl - degree; + let k = (0..=inner).map(|i| i as f64).collect(); + let mut m = vec![1; inner + 1]; + if let Some(f) = m.first_mut() { + *f = degree + 1; + } + if let Some(l) = m.last_mut() { + *l = degree + 1; + } + Ok((k, m)) + } + } +} + +fn weights(p: Option<&Param>, n: usize) -> R> { + let w: Vec = p + .and_then(Param::as_list) + .ok_or("rational B-spline without weights")? + .iter() + .map(|w| num(Some(w), "weight").and_then(|w| if w > 0.0 { Ok(w) } else { Err("non-positive weight".into()) })) + .collect::>()?; + if w.len() != n { Err("weights do not match the control points".into()) } else { Ok(w) } +} + +fn degree(p: Option<&Param>) -> R { + p.and_then(Param::as_i64).filter(|d| (1..=MAX_DEGREE as i64).contains(d)).map(|d| d as usize).ok_or_else(|| "bad B-spline degree".into()) +} + +/// The knot type a B-spline entity's (sub)type implies when it lists no knots. +fn spec_of_type(e: &Entity) -> KnotSpec { + let has = |n: &str| e.name() == n || e.has(n); + if has("BEZIER_CURVE") || has("BEZIER_SURFACE") { + KnotSpec::PiecewiseBezierKnots + } else if has("UNIFORM_CURVE") || has("UNIFORM_SURFACE") { + KnotSpec::UniformKnots + } else { + KnotSpec::QuasiUniformKnots + } +} + +/// The parameters of a simple or complex B-spline entity, as the simple form lays them out: +/// the name first, then the `B_SPLINE_*` attributes, then the `*_WITH_KNOTS` ones. +fn bspline_params(e: &Entity, base: &str, with_knots: &str) -> R<(Vec, Option>)> { + if e.is_complex() { + let b = e.record(base).ok_or_else(|| format!("complex entity without {base}"))?; + let mut p = vec![Param::Str(String::new())]; + p.extend(b.iter().cloned()); + Ok((p, e.record(with_knots).map(<[Param]>::to_vec))) + } else { + let p = e.params(); + let n = if base == "B_SPLINE_CURVE" { 6 } else { 8 }; + let k = (e.name() == with_knots).then(|| p.get(n..).map(<[Param]>::to_vec).unwrap_or_default()); + Ok((p.to_vec(), k)) + } +} + +impl<'a> Reader<'a> { + pub fn new(ex: &'a Exchange, units: Units) -> Self { + Reader { ex, units, curves: HashMap::new(), curves_2d: HashMap::new(), surfaces: HashMap::new() } + } + + pub fn units(&self) -> Units { + self.units + } + + fn length(&self, p: Option<&Param>, what: &str) -> R { + Ok(num(p, what)? * self.units.len) + } + + fn angle(&self, p: Option<&Param>, what: &str) -> R { + Ok(num(p, what)? * self.units.ang) + } + + /// A CARTESIAN_POINT, scaled per coordinate (`s` are the factors). + fn point_scaled(&self, id: u64, s: [f64; 3], dim: usize) -> R { + let e = entity(self.ex, id)?; + if e.name() != "CARTESIAN_POINT" { + return Err(format!("#{id}: expected CARTESIAN_POINT, found {}", e.name())); + } + let c = e.params().get(1).and_then(Param::as_list).ok_or("CARTESIAN_POINT without coordinates")?; + if c.is_empty() || c.len() > dim { + return Err(format!("#{id}: point with {} coordinates", c.len())); + } + let g = |i: usize| -> R { if i < c.len() { num(c.get(i), "coordinate") } else { Ok(0.0) } }; + Ok([g(0)? * s[0], g(1)? * s[1], if dim == 3 { g(2)? * s[2] } else { 0.0 }]) + } + + /// A CARTESIAN_POINT in millimetres. + pub fn point(&self, id: u64) -> R { + let l = self.units.len; + self.point_scaled(id, [l, l, l], 3) + } + + /// A DIRECTION, as a unit vector (with 2D axes scaled by `s` first). + fn direction_scaled(&self, id: u64, s: [f64; 3], dim: usize) -> R { + let e = entity(self.ex, id)?; + if e.name() != "DIRECTION" { + return Err(format!("#{id}: expected DIRECTION, found {}", e.name())); + } + let c = e.params().get(1).and_then(Param::as_list).ok_or("DIRECTION without ratios")?; + if c.is_empty() || c.len() > dim { + return Err(format!("#{id}: direction with {} ratios", c.len())); + } + let g = |i: usize| -> R { if i < c.len() { num(c.get(i), "direction ratio") } else { Ok(0.0) } }; + unit([g(0)? * s[0], g(1)? * s[1], if dim == 3 { g(2)? * s[2] } else { 0.0 }], &format!("#{id}")) + } + + pub fn direction(&self, id: u64) -> R { + self.direction_scaled(id, [1.0; 3], 3) + } + + /// AXIS2_PLACEMENT_3D, or AXIS2_PLACEMENT_2D as a placement in the XY plane. + fn placement_scaled(&self, id: u64, s: [f64; 3], dim: usize) -> R { + let e = entity(self.ex, id)?; + let p = e.params(); + let origin = self.point_scaled(reference(p.get(1), "placement location")?, s, dim)?; + let (axis, rf) = match (e.name(), dim) { + ("AXIS2_PLACEMENT_3D", 3) => { + let z = match p.get(2).and_then(Param::as_ref_id) { + Some(d) => self.direction_scaled(d, s, dim)?, + None => [0.0, 0.0, 1.0], + }; + (z, p.get(3).and_then(Param::as_ref_id)) + } + ("AXIS2_PLACEMENT_2D", 2) => ([0.0, 0.0, 1.0], p.get(2).and_then(Param::as_ref_id)), + (n, _) => return Err(format!("#{id}: unexpected placement {n} in {dim}D")), + }; + let x = match rf { + Some(d) => { + let r = self.direction_scaled(d, s, dim)?; + let x = sub(r, scale(axis, dot(r, axis))); + if norm(x) > 1e-9 { scale(x, 1.0 / norm(x)) } else { any_perpendicular(axis) } + } + None => any_perpendicular(axis), + }; + Ok(Placement { origin, axis, ref_direction: x }) + } + + pub fn placement(&self, id: u64) -> R { + let l = self.units.len; + self.placement_scaled(id, [l, l, l], 3) + } + + /// A placement in 3D space (an assembly's or a mapped item's): AXIS2_PLACEMENT_3D, or an + /// AXIS2_PLACEMENT_2D as the placement in the XY plane it describes. + pub fn frame(&self, id: u64) -> R { + let l = self.units.len; + let dim = if entity(self.ex, id)?.name() == "AXIS2_PLACEMENT_2D" { 2 } else { 3 }; + self.placement_scaled(id, [l, l, l], dim) + } + + pub fn axis1(&self, id: u64) -> R { + let e = entity(self.ex, id)?; + if e.name() != "AXIS1_PLACEMENT" { + return Err(format!("#{id}: expected AXIS1_PLACEMENT, found {}", e.name())); + } + let p = e.params(); + let origin = self.point(reference(p.get(1), "axis location")?)?; + let direction = match p.get(2).and_then(Param::as_ref_id) { + Some(d) => self.direction(d)?, + None => [0.0, 0.0, 1.0], + }; + Ok(Axis1 { origin, direction }) + } + + /// A VECTOR: unit direction and magnitude (scaled as a length by `len`). + fn vector_scaled(&self, id: u64, s: [f64; 3], dim: usize) -> R<(P3, f64)> { + let e = entity(self.ex, id)?; + if e.name() != "VECTOR" { + return Err(format!("#{id}: expected VECTOR, found {}", e.name())); + } + let p = e.params(); + // Scaling a 2D direction unevenly changes the magnitude too. + let raw = self.direction_scaled(reference(p.get(1), "vector orientation")?, [1.0; 3], dim)?; + let m = num(p.get(2), "vector magnitude")?; + if m < 0.0 { + return Err("negative vector magnitude".into()); + } + let v = [raw[0] * s[0] * m, raw[1] * s[1] * m, raw[2] * s[2] * m]; + let len = norm(v); + if !(len > 0.0) { + return Err("zero vector".into()); + } + Ok((scale(v, 1.0 / len), len)) + } + + /// A 3D curve entity. + pub fn curve(&mut self, id: u64) -> R> { + self.curve_in(id, 0) + } + + fn curve_in(&mut self, id: u64, depth: usize) -> R> { + if let Some(c) = self.curves.get(&id) { + return Ok(c.clone()); + } + if depth > MAX_GEOM_DEPTH { + return Err("curve definitions nested too deeply".into()); + } + let l = self.units.len; + let c = Arc::new(self.read_curve(id, [l, l, l], 3, depth)?); + self.curves.insert(id, c.clone()); + Ok(c) + } + + /// A 2D curve in a surface's parameter space, scaled by the surface's parameter units. + fn curve_2d(&mut self, id: u64, kinds: (ParamKind, ParamKind), depth: usize) -> R> { + let s = [self.factor(kinds.0), self.factor(kinds.1), 1.0]; + let key = (id, [s[0].to_bits(), s[1].to_bits()]); + if let Some(c) = self.curves_2d.get(&key) { + return Ok(c.clone()); + } + if depth > MAX_GEOM_DEPTH { + return Err("curve definitions nested too deeply".into()); + } + let c = Arc::new(self.read_curve(id, s, 2, depth)?); + self.curves_2d.insert(key, c.clone()); + Ok(c) + } + + fn factor(&self, k: ParamKind) -> f64 { + match k { + ParamKind::Length => self.units.len, + ParamKind::Angle => self.units.ang, + ParamKind::Plain => 1.0, + } + } + + /// A conic radius: a length, scaled evenly (`s` must be even for a conic). + fn conic_scale(s: [f64; 3]) -> R { + if (s[0] - s[1]).abs() > 1e-12 * s[0].abs().max(s[1].abs()) { + return Err("not supported yet: a conic in a parameter space with mixed units".into()); + } + Ok(s[0]) + } + + fn read_curve(&mut self, id: u64, s: [f64; 3], dim: usize, depth: usize) -> R { + let e = entity(self.ex, id)?; + if e.is_complex() { + return self.bspline_curve(e, s, dim); + } + let p = e.params(); + let positive = |x: f64, what: &str| if x > 0.0 { Ok(x) } else { Err(format!("{what} must be positive")) }; + match e.name() { + "LINE" => { + let origin = self.point_scaled(reference(p.get(1), "line point")?, s, dim)?; + let (direction, magnitude) = self.vector_scaled(reference(p.get(2), "line vector")?, s, dim)?; + Ok(Curve::Line { origin, direction, magnitude }) + } + "CIRCLE" => { + let k = Self::conic_scale(s)?; + let position = self.placement_scaled(reference(p.get(1), "circle placement")?, s, dim)?; + Ok(Curve::Circle { position, radius: positive(num(p.get(2), "radius")? * k, "circle radius")? }) + } + "ELLIPSE" => { + let k = Self::conic_scale(s)?; + let position = self.placement_scaled(reference(p.get(1), "ellipse placement")?, s, dim)?; + Ok(Curve::Ellipse { + position, + semi_axis_1: positive(num(p.get(2), "semi axis")? * k, "ellipse axis")?, + semi_axis_2: positive(num(p.get(3), "semi axis")? * k, "ellipse axis")?, + }) + } + "HYPERBOLA" => { + let k = Self::conic_scale(s)?; + let position = self.placement_scaled(reference(p.get(1), "hyperbola placement")?, s, dim)?; + Ok(Curve::Hyperbola { + position, + semi_axis: positive(num(p.get(2), "semi axis")? * k, "hyperbola axis")?, + semi_imag_axis: positive(num(p.get(3), "semi imaginary axis")? * k, "hyperbola axis")?, + }) + } + "PARABOLA" => { + let k = Self::conic_scale(s)?; + let position = self.placement_scaled(reference(p.get(1), "parabola placement")?, s, dim)?; + let focal_dist = num(p.get(2), "focal distance")? * k; + if focal_dist == 0.0 { + return Err("parabola focal distance must not be zero".into()); + } + Ok(Curve::Parabola { position, focal_dist }) + } + "B_SPLINE_CURVE_WITH_KNOTS" | "BEZIER_CURVE" | "UNIFORM_CURVE" | "QUASI_UNIFORM_CURVE" => self.bspline_curve(e, s, dim), + "POLYLINE" => { + let ids = p.get(1).and_then(Param::as_list).ok_or("POLYLINE without points")?; + if ids.len() < 2 || ids.len() > MAX_CTRL { + return Err("polyline point count".into()); + } + let pts = ids.iter().map(|c| self.point_scaled(reference(Some(c), "polyline point")?, s, dim)).collect::>()?; + Ok(Curve::Polyline(pts)) + } + "TRIMMED_CURVE" => { + let b = reference(p.get(1), "trimmed curve basis")?; + let basis = if dim == 3 { self.curve_in(b, depth + 1)? } else { Arc::new(self.read_curve(b, s, dim, depth + 1)?) }; + // Conic parameters are angles; every other basis curve's are plain numbers. + let kind = match &*basis { + Curve::Circle { .. } | Curve::Ellipse { .. } => ParamKind::Angle, + _ => ParamKind::Plain, + }; + let trim_1 = self.trims(p.get(2), kind, s, dim)?; + let trim_2 = self.trims(p.get(3), kind, s, dim)?; + let sense = boolean(p.get(4), "trimmed curve sense")?; + let preference = match p.get(5).and_then(Param::as_enum) { + Some("CARTESIAN") => TrimPreference::Cartesian, + Some("PARAMETER") => TrimPreference::Parameter, + _ => TrimPreference::Unspecified, + }; + Ok(Curve::Trimmed { basis, trim_1, trim_2, sense, preference }) + } + "SURFACE_CURVE" | "SEAM_CURVE" | "INTERSECTION_CURVE" | "BOUNDED_SURFACE_CURVE" if dim == 3 => { + let kind = match e.name() { + "SEAM_CURVE" => SurfaceCurveKind::Seam, + "INTERSECTION_CURVE" => SurfaceCurveKind::Intersection, + "BOUNDED_SURFACE_CURVE" => SurfaceCurveKind::BoundedSurface, + _ => SurfaceCurveKind::Surface, + }; + let curve_3d = self.curve_in(reference(p.get(1), "surface curve 3D curve")?, depth + 1)?; + let items = p.get(2).and_then(Param::as_list).ok_or("surface curve without associated geometry")?; + if items.len() > 2 { + return Err("surface curve with more than two associated items".into()); + } + let mut associated = Vec::with_capacity(items.len()); + for item in items { + associated.push(self.associated(reference(Some(item), "associated geometry")?, depth + 1)?); + } + let master = match p.get(3).and_then(Param::as_enum) { + Some("PCURVE_S1") => PreferredRep::PcurveS1, + Some("PCURVE_S2") => PreferredRep::PcurveS2, + _ => PreferredRep::Curve3d, + }; + Ok(Curve::SurfaceCurve { kind, curve_3d, associated, master }) + } + "OFFSET_CURVE_3D" if dim == 3 => { + let basis = self.curve_in(reference(p.get(1), "offset curve basis")?, depth + 1)?; + let distance = self.length(p.get(2), "offset distance")?; + let self_intersect = logical(p.get(3), "offset curve self_intersect")?; + let ref_direction = self.direction(reference(p.get(4), "offset curve direction")?)?; + Ok(Curve::OffsetCurve3d { basis, distance, self_intersect, ref_direction }) + } + n => Err(format!("not supported yet: curve {n}{}", if dim == 2 { " in parameter space" } else { "" })), + } + } + + fn trims(&self, p: Option<&Param>, kind: ParamKind, s: [f64; 3], dim: usize) -> R> { + let items = p.and_then(Param::as_list).ok_or("trimmed curve without trims")?; + if items.is_empty() || items.len() > 2 { + return Err("trimmed curve trim count".into()); + } + items + .iter() + .map(|t| match t { + Param::Ref(r) => Ok(Trim::Point(self.point_scaled(*r, s, dim)?)), + Param::Typed(name, v) if name == "PARAMETER_VALUE" => Ok(Trim::Parameter(num(v.first(), "trim parameter")? * self.factor(kind))), + Param::Real(_) | Param::Int(_) => Ok(Trim::Parameter(num(Some(t), "trim parameter")? * self.factor(kind))), + _ => Err("bad trim".into()), + }) + .collect() + } + + fn associated(&mut self, id: u64, depth: usize) -> R { + let e = entity(self.ex, id)?; + if e.name() != "PCURVE" { + return Ok(Associated::Surface(self.surface_in(id, depth)?)); + } + let p = e.params(); + let surface = self.surface_in(reference(p.get(1), "pcurve surface")?, depth)?; + let rep = entity(self.ex, reference(p.get(2), "pcurve representation")?)?; + if rep.name() != "DEFINITIONAL_REPRESENTATION" { + return Err(format!("pcurve representation is {}", rep.name())); + } + let items = rep.params().get(1).and_then(Param::as_list).ok_or("pcurve representation without items")?; + let [item] = items else { return Err("pcurve representation must hold one curve".into()) }; + let kinds = Self::param_kinds(&surface); + let curve = self.curve_2d(reference(Some(item), "pcurve curve")?, kinds, depth)?; + Ok(Associated::Pcurve(Pcurve { surface, curve })) + } + + /// How a surface's (u, v) parameters scale from file units. + fn param_kinds(s: &Surface) -> (ParamKind, ParamKind) { + use ParamKind::*; + match s { + Surface::Plane { .. } => (Length, Length), + Surface::Cylinder { .. } | Surface::Cone { .. } => (Angle, Length), + Surface::Sphere { .. } | Surface::Torus { .. } | Surface::DegenerateTorus { .. } => (Angle, Angle), + Surface::Revolution { profile, .. } => (Angle, Self::curve_param_kind(profile)), + Surface::Extrusion { profile, .. } => (Self::curve_param_kind(profile), Plain), + Surface::BSpline(_) => (Plain, Plain), + Surface::Offset { basis, .. } | Surface::RectangularTrimmed { basis, .. } => Self::param_kinds(basis), + } + } + + fn curve_param_kind(c: &Curve) -> ParamKind { + match c { + Curve::Circle { .. } | Curve::Ellipse { .. } => ParamKind::Angle, + Curve::Trimmed { basis, .. } | Curve::OffsetCurve3d { basis, .. } => Self::curve_param_kind(basis), + Curve::SurfaceCurve { curve_3d, .. } => Self::curve_param_kind(curve_3d), + _ => ParamKind::Plain, + } + } + + fn bspline_curve(&mut self, e: &Entity, s: [f64; 3], dim: usize) -> R { + let (base, with_knots) = bspline_params(e, "B_SPLINE_CURVE", "B_SPLINE_CURVE_WITH_KNOTS")?; + let degree = degree(base.get(1))?; + let ids = base.get(2).and_then(Param::as_list).ok_or("B-spline without control points")?; + if ids.len() > MAX_CTRL { + return Err("B-spline with too many control points".into()); + } + let points: Vec = ids.iter().map(|c| self.point_scaled(reference(Some(c), "control point")?, s, dim)).collect::>()?; + let (knots, multiplicities, knot_spec) = match &with_knots { + Some(k) => { + let (kv, m) = knots(k.first(), k.get(1), points.len(), degree)?; + (kv, m, knot_spec(k.get(2))) + } + None => { + let spec = spec_of_type(e); + let (kv, m) = implied_knots(spec, points.len(), degree)?; + (kv, m, spec) + } + }; + let weights = match e.record("RATIONAL_B_SPLINE_CURVE") { + Some(r) => Some(weights(r.first(), points.len())?), + None => None, + }; + Ok(Curve::BSpline(Box::new(BSplineCurve { + degree, + points, + weights, + knots, + multiplicities, + form: curve_form(base.get(3)), + closed: logical(base.get(4), "B-spline closed_curve").unwrap_or(Logical::Unknown), + self_intersect: logical(base.get(5), "B-spline self_intersect").unwrap_or(Logical::Unknown), + knot_spec, + }))) + } + + /// A surface entity. + pub fn surface(&mut self, id: u64) -> R> { + self.surface_in(id, 0) + } + + fn surface_in(&mut self, id: u64, depth: usize) -> R> { + if let Some(s) = self.surfaces.get(&id) { + return Ok(s.clone()); + } + if depth > MAX_GEOM_DEPTH { + return Err("surface definitions nested too deeply".into()); + } + let s = Arc::new(self.read_surface(id, depth)?); + self.surfaces.insert(id, s.clone()); + Ok(s) + } + + fn read_surface(&mut self, id: u64, depth: usize) -> R { + let e = entity(self.ex, id)?; + if e.is_complex() { + return self.bspline_surface(e); + } + let p = e.params(); + let position = |r: &Self| r.placement(reference(p.get(1), "surface placement")?); + let positive = |x: f64, what: &str| if x > 0.0 { Ok(x) } else { Err(format!("{what} must be positive")) }; + match e.name() { + "PLANE" => Ok(Surface::Plane { position: position(self)? }), + "CYLINDRICAL_SURFACE" => { + Ok(Surface::Cylinder { position: position(self)?, radius: positive(self.length(p.get(2), "radius")?, "cylinder radius")? }) + } + "CONICAL_SURFACE" => { + let radius = self.length(p.get(2), "radius")?; + let semi_angle = self.angle(p.get(3), "semi angle")?; + if radius < 0.0 || !(semi_angle.abs() > 1e-12 && semi_angle.abs() < std::f64::consts::FRAC_PI_2 - 1e-12) { + return Err("cone with a negative radius or a semi angle outside (0, 90°)".into()); + } + Ok(Surface::Cone { position: position(self)?, radius, semi_angle }) + } + "SPHERICAL_SURFACE" => { + Ok(Surface::Sphere { position: position(self)?, radius: positive(self.length(p.get(2), "radius")?, "sphere radius")? }) + } + "TOROIDAL_SURFACE" | "DEGENERATE_TOROIDAL_SURFACE" => { + let major_radius = self.length(p.get(2), "major radius")?; + let minor_radius = positive(self.length(p.get(3), "minor radius")?, "torus minor radius")?; + // A negative major radius (outside the schema, which some writers use for a + // spindle torus) is the same formula: its tube on the other side of the axis. + if !major_radius.is_finite() { + return Err("torus major radius must be finite".into()); + } + let position = position(self)?; + if e.name() == "DEGENERATE_TOROIDAL_SURFACE" { + let select_outer = boolean(p.get(4), "degenerate torus select_outer")?; + Ok(Surface::DegenerateTorus { position, major_radius, minor_radius, select_outer }) + } else { + Ok(Surface::Torus { position, major_radius, minor_radius }) + } + } + "B_SPLINE_SURFACE_WITH_KNOTS" | "BEZIER_SURFACE" | "UNIFORM_SURFACE" | "QUASI_UNIFORM_SURFACE" => self.bspline_surface(e), + "SURFACE_OF_REVOLUTION" => { + let profile = self.curve_in(reference(p.get(1), "revolution profile")?, depth + 1)?; + let axis = self.axis1(reference(p.get(2), "revolution axis")?)?; + Ok(Surface::Revolution { profile, axis }) + } + "SURFACE_OF_LINEAR_EXTRUSION" => { + let profile = self.curve_in(reference(p.get(1), "extrusion profile")?, depth + 1)?; + let l = self.units.len; + let (direction, magnitude) = self.vector_scaled(reference(p.get(2), "extrusion vector")?, [l, l, l], 3)?; + Ok(Surface::Extrusion { profile, direction, magnitude }) + } + "OFFSET_SURFACE" => { + let basis = self.surface_in(reference(p.get(1), "offset basis")?, depth + 1)?; + let distance = self.length(p.get(2), "offset distance")?; + let self_intersect = logical(p.get(3), "offset self_intersect")?; + Ok(Surface::Offset { basis, distance, self_intersect }) + } + "RECTANGULAR_TRIMMED_SURFACE" => { + let basis = self.surface_in(reference(p.get(1), "trimmed surface basis")?, depth + 1)?; + let (ku, kv) = Self::param_kinds(&basis); + let (fu, fv) = (self.factor(ku), self.factor(kv)); + Ok(Surface::RectangularTrimmed { + u1: num(p.get(2), "u1")? * fu, + u2: num(p.get(3), "u2")? * fu, + v1: num(p.get(4), "v1")? * fv, + v2: num(p.get(5), "v2")? * fv, + u_sense: boolean(p.get(6), "usense")?, + v_sense: boolean(p.get(7), "vsense")?, + basis, + }) + } + n => Err(format!("not supported yet: surface {n}")), + } + } + + fn bspline_surface(&mut self, e: &Entity) -> R { + let (base, with_knots) = bspline_params(e, "B_SPLINE_SURFACE", "B_SPLINE_SURFACE_WITH_KNOTS")?; + let (u_degree, v_degree) = (degree(base.get(1))?, degree(base.get(2))?); + let rows = base.get(3).and_then(Param::as_list).ok_or("B-spline surface without control points")?; + let mut points: Vec> = Vec::with_capacity(rows.len().min(MAX_CTRL)); + let mut total = 0usize; + for r in rows { + let r = r.as_list().ok_or("bad control point row")?; + total = total.saturating_add(r.len()); + if total > MAX_CTRL { + return Err("B-spline surface with too many control points".into()); + } + points.push(r.iter().map(|c| self.point(reference(Some(c), "control point")?)).collect::>()?); + } + let nu = points.len(); + let nv = points.first().map(Vec::len).unwrap_or(0); + if nu == 0 || nv == 0 || points.iter().any(|r| r.len() != nv) { + return Err("ragged B-spline control net".into()); + } + let ((u_knots, u_multiplicities), (v_knots, v_multiplicities), knot_spec) = match &with_knots { + Some(k) => (knots(k.first(), k.get(2), nu, u_degree)?, knots(k.get(1), k.get(3), nv, v_degree)?, knot_spec(k.get(4))), + None => { + let spec = spec_of_type(e); + (implied_knots(spec, nu, u_degree)?, implied_knots(spec, nv, v_degree)?, spec) + } + }; + let weights = match e.record("RATIONAL_B_SPLINE_SURFACE") { + Some(r) => { + let w = r.first().and_then(Param::as_list).ok_or("rational surface without weights")?; + if w.len() != nu { + return Err("weights do not match the control net".into()); + } + Some(w.iter().map(|row| weights(Some(row), nv)).collect::>()?) + } + None => None, + }; + Ok(Surface::BSpline(Box::new(BSplineSurface { + u_degree, + v_degree, + points, + weights, + u_knots, + u_multiplicities, + v_knots, + v_multiplicities, + form: surface_form(base.get(4)), + u_closed: logical(base.get(5), "u_closed").unwrap_or(Logical::Unknown), + v_closed: logical(base.get(6), "v_closed").unwrap_or(Logical::Unknown), + self_intersect: logical(base.get(7), "self_intersect").unwrap_or(Logical::Unknown), + knot_spec, + }))) + } +} diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rs new file mode 100644 index 000000000..fa693f7bc --- /dev/null +++ b/crates/step/src/topology.rs @@ -0,0 +1,1928 @@ +//! STEP topology (ISO 10303-42 topology and geometric model entities) into the kernel-neutral +//! B-rep, schema 4 ([`solidcraft_geom::brep`], docs/native-brep.md). Written from the public +//! ISO 10303-42 specification. +//! +//! Each MANIFOLD_SOLID_BREP, BREP_WITH_VOIDS and SHELL_BASED_SURFACE_MODEL becomes one +//! [`Brep`]: a closed shell separates the infinite region from a solid (or, as a void, a solid +//! from its cavity); an open shell lies in the infinite region. A solid that cannot be read is +//! skipped with its reason and the rest of the file is still read. +//! +//! Geometry: LINE, CIRCLE, ELLIPSE, B-spline curves and POLYLINE map to the schema's curve kinds +//! (SURFACE_CURVE and its subtypes by their 3D curve, TRIMMED_CURVE by its basis: the edge's +//! vertices bound it); PLANE, CYLINDRICAL_, CONICAL_, SPHERICAL_ and (ring) TOROIDAL_SURFACE and +//! B-spline surfaces map to the surface kinds (RECTANGULAR_TRIMMED_SURFACE by its basis). Anything +//! else refuses its solid ("not supported yet: …"). +//! +//! Orientation: an EDGE_CURVE's interval is the parameters of its vertices on its curve, from +//! min to max; the schema edge runs with the STEP edge or against it (`same_sense` .F. on a +//! closed curve, or vertices in decreasing parameter order on an open one), and each oriented +//! edge's `forward` says how the loop runs along the schema edge. Loops are stored relative to +//! the surface's natural normal: FACE_BOUND orientation and ADVANCED_FACE same_sense both +//! reverse a loop, and same_sense (with ORIENTED_FACE and ORIENTED_CLOSED_SHELL orientation) +//! gives the oriented face's side. +//! +//! Tolerances: the representation context's distance uncertainty (default [`DEFAULT_TOLERANCE`] +//! when the file has none, never below [`MIN_TOLERANCE`]) is the brep's tolerance and every +//! vertex's and edge's to start with. A vertex measurably off its curve or surface, or an edge +//! whose curve lies measurably off a face's surface, gets that distance (with margin) as its +//! tolerance, and the solid's notes say how many and how far. +//! +//! Pcurves are the closed forms the 3D edges have on our surfaces ([`pcurve::exact_pcurves`]); a +//! use with none gets its pcurve from the kernel ([`read_solids_with`], SMLib's own trims). The +//! file's own PCURVE entities are not used. +//! +//! Input is hostile: every reference is checked, nesting and counts are capped, and the work of +//! a whole file is bounded (shared shells count each time a solid uses them). + +use solidcraft_geom::prelude::*; +use std::collections::{HashMap, HashSet}; +use std::f64::consts::TAU; + +use solidcore_record::Vec3; +use solidcore_record::brep::{ + self, Brep, Curve as BCurve, Curve2, Edge, EdgeUseRef, Face, Frame, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell, + Surface as BSurface, Vertex, +}; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval, face_flux}; +use solidcraft_geom::brep::pcurve::{self, EdgeUse, TrimEdge, TrimFace, TrimUse, Trims}; + +use crate::geom::{BSplineCurve, BSplineSurface, Curve, P3, Placement, dot, scale, sub}; +use crate::p21::{Entity, Exchange, Param}; +use crate::read::{R, Reader}; +use crate::units; + +mod frames; +mod seams; +mod swept; + +/// Tolerance (mm) when the file states no uncertainty. +pub const DEFAULT_TOLERANCE: f64 = 1e-3; +/// The least tolerance (mm) a record gets, whatever the file states. +pub const MIN_TOLERANCE: f64 = 1e-7; +/// The loosest tolerance (mm) a face's pcurves are fitted at before the solid is refused. +pub const MAX_FIT_TOLERANCE: f64 = 1.0; +/// Most faces in one solid. +pub const MAX_FACES: usize = 500_000; +/// Most edges in one loop, and in all of one face's loops. +pub const MAX_LOOP: usize = 100_000; +/// Most bounds of one face. +pub const MAX_BOUNDS: usize = 10_000; +/// Most faces read in one file, counting a shell again for each solid that uses it. +pub const MAX_FILE_FACES: usize = 5_000_000; +/// Most solid items read from one file. +pub const MAX_SOLIDS: usize = 100_000; +/// Deepest nesting of ORIENTED_EDGE in ORIENTED_EDGE, ORIENTED_FACE in ORIENTED_FACE. +const MAX_NESTING: usize = 4; +/// Most control points in one direction of a schema spline. +const MAX_SPLINE_POINTS: usize = 4096; +/// Highest schema spline degree. +const MAX_SPLINE_DEGREE: usize = 16; +/// Samples along a curve when projecting a vertex onto it. +const MAX_SAMPLES: usize = 4096; +/// The largest tolerance (mm) an edge or vertex is given: SMLib takes none larger (smlib.h's +/// EDGE_TOLERANCE and VERTEX_TOLERANCE, `solidcraft_smlib::flat::MAX_TOLERANCE`). Geometry that +/// would need more is refused, with how far off it lies. +const MAX_TOLERANCE: f64 = 1.0; +/// A vertex's tolerance over its largest gap from its curves and surfaces. +const VERTEX_GAP_MARGIN: f64 = 1.5; +/// Intervals an edge's curve is measured over against each face's surface it bounds. +const EDGE_GAP_SAMPLES: usize = 16; +/// An edge's tolerance over the largest gap measured between its pcurves and its curve, as the +/// record check measures it: with margin, as a vertex's. +const EDGE_GAP_MARGIN: f64 = 1.5; +/// A solid (or sheet) read from the file. +#[derive(Clone, Debug)] +pub struct Solid { + /// The STEP item (MANIFOLD_SOLID_BREP, BREP_WITH_VOIDS or SHELL_BASED_SURFACE_MODEL). + pub item: u64, + /// The item's own name, else its product's. + pub name: String, + /// The name of the product whose shape holds the item, when the file says. + pub product: Option, + /// In the coordinates of the item's own representation (assembly placements not applied). + pub brep: Brep, + /// The file's face entity (ADVANCED_FACE, FACE_SURFACE) of each of the record's faces, in + /// the record's face order. + pub face_origin: Vec, + /// No closed shell: a surface model of open shells only. + pub sheet: bool, + /// What was repaired or noted on the way (faces whose same_sense disagreed with their + /// loops, edges whose same_sense disagreed with their vertices, raised tolerances). + pub notes: Vec, + /// The record faces turned over because their loops disagree with their same_sense (their + /// outer loop runs clockwise about the normal the file gives them), in increasing order. + pub turned: Vec, +} + +/// A solid item that could not be read, and why. +#[derive(Clone, Debug, PartialEq)] +pub struct Failure { + pub item: u64, + pub message: String, +} + +/// Every solid of a file: those read and those refused. +#[derive(Clone, Debug, Default)] +pub struct Solids { + pub solids: Vec, + pub failures: Vec, +} + +fn entity(ex: &Exchange, id: u64) -> R<&Entity> { + ex.get(id).ok_or_else(|| format!("missing entity #{id}")) +} + +fn rid(p: Option<&Param>, what: &str) -> R { + p.and_then(Param::as_ref_id).ok_or_else(|| format!("{what}: expected a reference")) +} + +fn refs(p: Option<&Param>, what: &str) -> R> { + let list = p.and_then(Param::as_list).ok_or_else(|| format!("{what}: expected a list"))?; + list.iter().map(|x| x.as_ref_id().ok_or_else(|| format!("{what}: expected references"))).collect() +} + +fn flag(p: Option<&Param>, what: &str) -> R { + p.and_then(Param::as_bool).ok_or_else(|| format!("{what}: expected a boolean")) +} + +fn unsupported(what: impl std::fmt::Display) -> String { + format!("not supported yet: {what}") +} + +fn index(i: usize) -> R { + u32::try_from(i).map_err(|_| "too many items".to_string()) +} + +fn v3(p: P3) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// Items and context of a representation entity (plain or complex). +fn representation(e: &Entity) -> Option<(Vec, Option)> { + let p = if e.is_complex() { + e.record("REPRESENTATION") + .or_else(|| e.records.iter().find(|r| r.name.ends_with("REPRESENTATION") && r.params.len() >= 3).map(|r| r.params.as_slice()))? + } else if e.name().ends_with("REPRESENTATION") { + e.params() + } else { + return None; + }; + let items = p.get(1)?.as_list()?.iter().filter_map(Param::as_ref_id).collect(); + Some((items, p.get(2).and_then(Param::as_ref_id))) +} + +const SOLID_ITEMS: [&str; 4] = ["MANIFOLD_SOLID_BREP", "BREP_WITH_VOIDS", "SHELL_BASED_SURFACE_MODEL", "FACETED_BREP"]; + +/// Where each solid item sits: its representation's context, and the product that representation +/// (or one related to it) is the shape of. +struct Index { + context: HashMap, + product: HashMap, +} + +impl Index { + fn new(ex: &Exchange) -> Index { + let mut ids: Vec = ex.entities.keys().copied().collect(); + ids.sort_unstable(); + let mut context = HashMap::new(); + let mut rep_of: HashMap = HashMap::new(); + let mut shape_of: HashMap = HashMap::new(); // representation → PRODUCT_DEFINITION_SHAPE + let mut links: HashMap> = HashMap::new(); + for &id in &ids { + let Some(e) = ex.get(id) else { continue }; + if let Some((items, ctx)) = representation(e) { + for item in items { + if let Some(c) = ctx { + context.entry(item).or_insert(c); + } + rep_of.entry(item).or_insert(id); + } + } + let p = e.params(); + let rf = |i: usize| p.get(i).and_then(Param::as_ref_id); + match e.name() { + "SHAPE_DEFINITION_REPRESENTATION" => { + if let (Some(d), Some(r)) = (rf(0), rf(1)) { + shape_of.entry(r).or_insert(d); + } + } + "SHAPE_REPRESENTATION_RELATIONSHIP" | "REPRESENTATION_RELATIONSHIP" if !e.is_complex() => { + if let (Some(a), Some(b)) = (rf(2), rf(3)) { + links.entry(a).or_default().push(b); + links.entry(b).or_default().push(a); + } + } + _ => {} + } + } + let name_of = |pds: u64| -> Option { + let pd = ex.get(pds)?.params().get(2)?.as_ref_id()?; + let pdf = ex.get(pd)?.params().get(2)?.as_ref_id()?; + let product = ex.get(pdf)?.params().get(2)?.as_ref_id()?; + let p = ex.get(product)?; + (p.name() == "PRODUCT").then(|| p.params().get(1).or(p.params().first())).flatten()?.as_str().map(str::to_string) + }; + let mut product = HashMap::new(); + for (&item, &rep) in &rep_of { + if !ex.get(item).is_some_and(|e| SOLID_ITEMS.contains(&e.name())) { + continue; + } + let direct = shape_of.get(&rep).copied(); + let linked = || links.get(&rep).into_iter().flatten().find_map(|r| shape_of.get(r).copied()); + if let Some(name) = direct.or_else(linked).and_then(name_of) { + product.insert(item, name); + } + } + Index { context, product } + } +} + +/// Read every solid of the file. A solid that cannot be read is listed in +/// [`Solids::failures`] with its reason; the others are still read. A face's use with no +/// closed-form pcurve refuses its solid: [`read_solids_with`] has a kernel make those. +pub fn read_solids(ex: &Exchange) -> Solids { + read_solids_in(ex, None) +} + +/// [`read_solids`], with `trims` making the pcurves of uses that have no closed form. +pub fn read_solids_with(ex: &Exchange, trims: &dyn Trims) -> Solids { + read_solids_in(ex, Some(trims)) +} + +fn read_solids_in(ex: &Exchange, trims: Option<&dyn Trims>) -> Solids { + let mut solids: Vec = ex.entities.iter().filter(|(_, e)| SOLID_ITEMS.contains(&e.name())).map(|(id, _)| *id).collect(); + solids.sort_unstable(); + let mut index = Index::new(ex); + // A surface model's closed shells read on their own sit where the model does. + let mut items = Vec::with_capacity(solids.len()); + for solid in solids { + for piece in self::items(ex, solid) { + if piece != solid { + if let Some(c) = index.context.get(&solid).copied() { + index.context.insert(piece, c); + } + if let Some(p) = index.product.get(&solid).cloned() { + index.product.insert(piece, p); + } + } + items.push(piece); + } + } + let mut out = Solids::default(); + let mut budget = MAX_FILE_FACES; + let mut readers: HashMap, units::Context)> = HashMap::new(); + for (n, item) in items.into_iter().enumerate() { + if n >= MAX_SOLIDS { + out.failures.push(Failure { item, message: format!("more than {MAX_SOLIDS} solids in one file") }); + continue; + } + let ctx = index.context.get(&item).copied(); + let key = ctx.unwrap_or(0); + let (reader, context) = readers.entry(key).or_insert_with(|| { + let c = ctx.map(|c| units::context(ex, c)).unwrap_or_default(); + (Reader::new(ex, c.units), c) + }); + let context = *context; + match read_with(ex, reader, item, context, &mut budget, trims, &HashSet::new()) { + Ok(mut s) => { + s.product = index.product.get(&item).cloned(); + if s.name.is_empty() + && let Some(p) = &s.product + { + s.name = p.clone(); + } + out.solids.push(s); + } + Err(message) => out.failures.push(Failure { item, message }), + } + } + out +} + +/// Read one solid item in the given context. +pub fn read_solid(ex: &Exchange, item: u64, context: units::Context) -> R { + let mut reader = Reader::new(ex, context.units); + let mut budget = MAX_FILE_FACES; + read_with(ex, &mut reader, item, context, &mut budget, None, &HashSet::new()) +} + +/// [`read_solid`], with `trims` making the pcurves of uses that have no closed form. +pub fn read_solid_with(ex: &Exchange, item: u64, context: units::Context, trims: &dyn Trims) -> R { + let mut reader = Reader::new(ex, context.units); + let mut budget = MAX_FILE_FACES; + read_with(ex, &mut reader, item, context, &mut budget, Some(trims), &HashSet::new()) +} + +/// [`read_solid_with`] with the faces `left_out` (file face entities: the ADVANCED_FACE or +/// FACE_SURFACE, or the ORIENTED_FACE a shell lists) left out of their shells: what is left of a +/// solid that cannot be read or made whole, its faces still sharing their edges. With any face +/// left out it is a surface model of open shells (`sheet`), none of them bounding a region. +pub fn read_solid_without(ex: &Exchange, item: u64, context: units::Context, trims: &dyn Trims, left_out: &HashSet) -> R { + let mut reader = Reader::new(ex, context.units); + let mut budget = MAX_FILE_FACES; + read_with(ex, &mut reader, item, context, &mut budget, Some(trims), left_out) +} + +/// The file face a refusal of the reader names first (its "face #id"), if it names one. +pub fn named_face(message: &str) -> Option { + message.match_indices("face #").find_map(|(at, m)| { + let rest = message.get(at + m.len()..)?; + let digits = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()); + rest.get(..digits)?.parse().ok() + }) +} + +/// The base tolerance of a context. +pub fn tolerance(context: &units::Context) -> f64 { + context.uncertainty.unwrap_or(DEFAULT_TOLERANCE).clamp(MIN_TOLERANCE, MAX_FIT_TOLERANCE) +} + +fn read_with<'a>( + ex: &'a Exchange, + reader: &mut Reader<'a>, + item: u64, + context: units::Context, + budget: &mut usize, + trims: Option<&dyn Trims>, + left_out: &HashSet, +) -> R { + let e = entity(ex, item)?; + let name = e.params().first().and_then(Param::as_str).unwrap_or("").to_string(); + let mut b = Builder::new(ex, reader, tolerance(&context), budget, trims); + // The file's faces, edges, vertices and their geometry read into the builder. + let topology = solidcraft_profile::span("import", "step.topology"); + let (ids, kind) = item_shells(ex, item)?; + let mut shells = Vec::with_capacity(ids.len()); + let mut skipped = false; + for s in ids { + let (faces, any) = b.shell(s, left_out)?; + skipped |= any; + shells.push(faces); + } + drop(topology); + b.finish(item, name, shells, if skipped { Kind::Open } else { kind }) +} + +/// A face of a solid read on its own ([`read_faces_with`]). +#[derive(Clone, Debug)] +pub struct FaceRead { + /// The face's entity in the file (the ADVANCED_FACE or FACE_SURFACE, or the ORIENTED_FACE + /// the shell lists when it could not be read). + pub face: u64, + /// The face as a one-face surface body, facing as its shell uses it; else why it could not + /// be read (naming the face). + pub record: R, +} + +/// Each face of a solid item read on its own, as a one-face surface body: what can still be +/// shown of a solid that cannot be read whole, or whose body the kernel refuses. A face is read +/// as [`read_solid_with`] reads it, with its own edges and vertices (so its tolerances cover its +/// own gaps only); a face that cannot be read on its own says why and the others are still read. +pub fn read_faces_with(ex: &Exchange, item: u64, context: units::Context, trims: &dyn Trims) -> R> { + let (shells, _) = item_shells(ex, item)?; + let mut reader = Reader::new(ex, context.units); + let mut budget = MAX_FILE_FACES; + let mut out = Vec::new(); + for s in shells { + let (faces, flip) = shell_faces(ex, s)?; + for f in faces { + if out.len() >= MAX_FACES { + return Err(format!("more than {MAX_FACES} faces")); + } + let mut b = Builder::new(ex, &mut reader, tolerance(&context), &mut budget, Some(trims)); + let read = b.face(f, 0).and_then(|(face, forward)| b.finish(item, String::new(), vec![vec![(face, forward != flip)]], Kind::Model)); + let named = |m: String| if m.starts_with(&format!("face #{f}")) { m } else { format!("face #{f}: {m}") }; + out.push(match read { + Ok(s) => FaceRead { face: s.face_origin.first().copied().unwrap_or(f), record: Ok(s.brep) }, + Err(m) => FaceRead { face: f, record: Err(named(m)) }, + }); + } + } + Ok(out) +} + +/// A surface model's shells the file calls closed and the others, in its order. +fn model_shells(ex: &Exchange, shells: &[u64]) -> (Vec, Vec) { + shells.iter().partition(|s| ex.get(**s).is_some_and(|e| matches!(e.name(), "CLOSED_SHELL" | "ORIENTED_CLOSED_SHELL"))) +} + +/// The items a solid item is read as, each one body: the item itself, but for a surface model +/// with both closed and open shells (a part with a sheet beside it) each closed shell on its own +/// (a solid), then the model (its open shells, a sheet). +pub fn items(ex: &Exchange, item: u64) -> Vec { + let shells = match ex.get(item) { + Some(e) if e.name() == "SHELL_BASED_SURFACE_MODEL" => { + e.params().get(1).and_then(Param::as_list).unwrap_or(&[]).iter().filter_map(Param::as_ref_id).collect() + } + _ => Vec::new(), + }; + let (closed, open) = model_shells(ex, &shells); + if closed.is_empty() || open.is_empty() { + return vec![item]; + } + closed.into_iter().chain([item]).collect() +} + +/// The shells of a solid item (the outer shell first, then its voids), and what kind it is. +fn item_shells(ex: &Exchange, item: u64) -> R<(Vec, Kind)> { + let e = entity(ex, item)?; + let p = e.params(); + match e.name() { + "MANIFOLD_SOLID_BREP" => Ok((vec![rid(p.get(1), "outer shell")?], Kind::Solid)), + "BREP_WITH_VOIDS" => { + let mut shells = vec![rid(p.get(1), "outer shell")?]; + let voids = refs(p.get(2), "voids")?; + if voids.len() >= brep::MAX_SHELLS { + return Err(format!("{} voids", voids.len())); + } + shells.extend(voids); + Ok((shells, Kind::Voids)) + } + "SHELL_BASED_SURFACE_MODEL" => { + let ids = refs(p.get(1), "surface model shells")?; + if ids.is_empty() || ids.len() > brep::MAX_SHELLS { + return Err(format!("a surface model with {} shells", ids.len())); + } + // Its closed shells, where it has open ones too, are items of their own ([`items`]). + let (closed, open) = model_shells(ex, &ids); + Ok((if closed.is_empty() || open.is_empty() { ids } else { open }, Kind::Model)) + } + // A closed shell of a surface model that has open shells too ([`items`]). + "CLOSED_SHELL" | "ORIENTED_CLOSED_SHELL" => Ok((vec![item], Kind::Model)), + n => Err(unsupported(n)), + } +} + +/// The faces a shell lists, and whether the shell turns them over (an oriented shell used +/// against its faces). +fn shell_faces(ex: &Exchange, id: u64) -> R<(Vec, bool)> { + let e = entity(ex, id)?; + let p = e.params(); + let (faces, flip) = match e.name() { + "CLOSED_SHELL" | "OPEN_SHELL" => (refs(p.get(1), "shell faces")?, false), + "ORIENTED_CLOSED_SHELL" | "ORIENTED_OPEN_SHELL" => { + let inner = rid(p.get(2), "oriented shell element")?; + let inner_e = entity(ex, inner)?; + if !matches!(inner_e.name(), "CLOSED_SHELL" | "OPEN_SHELL") { + return Err(format!("#{inner}: {}", unsupported(format!("shell {}", inner_e.name())))); + } + (refs(inner_e.params().get(1), "shell faces")?, !flag(p.get(3), "oriented shell orientation")?) + } + n => return Err(format!("#{id}: {}", unsupported(format!("shell {n}")))), + }; + if faces.is_empty() { + return Err(format!("shell #{id} has no faces")); + } + if faces.len() > MAX_FACES { + return Err(format!("shell #{id} with {} faces", faces.len())); + } + Ok((faces, flip)) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Solid, + Voids, + Model, + /// A solid with faces left out ([`read_solid_without`]): its shells are sheets only. + Open, +} + +/// A curve the edge can be read on, and how its parameter relates to its vertices. +struct EdgeB { + curve: BCurve, + interval: [f64; 2], + vertices: [u32; 2], + tolerance: f64, + /// The curve's NURBS form and its interval there (`form::edge`), set before the pcurves. + form: Option<(BCurve, [f64; 2])>, +} + +enum LoopB { + Edges(Vec<(u32, bool)>), + Vertex(u32), +} + +struct FaceB { + step: u64, + surface: BSurface, + /// Relative to the surface's natural normal. + loops: Vec, + /// The index in `loops` of the FACE_OUTER_BOUND, if one is marked. + outer: Option, + /// The face's normal is the surface's natural normal. + forward: bool, + /// A round face's box on its label (`solidcraft_geom::brep::form::extent`), once measured. + extent: Option<[[f64; 2]; 2]>, +} + +struct Builder<'b, 'a> { + ex: &'a Exchange, + reader: &'b mut Reader<'a>, + tol: f64, + budget: &'b mut usize, + /// Makes the pcurves of uses that have no closed form; without it such a face is refused. + trims: Option<&'b dyn Trims>, + vertex_ids: HashMap, + vertices: Vec, + /// STEP edge → schema edge, and whether the schema edge runs with the STEP edge. + edge_ids: HashMap, + edges: Vec, + face_ids: HashSet, + faces: Vec, + sense_mismatches: usize, + /// Edges whose tolerance was raised to the gap their curve has to a face's surface. + raised_edges: HashSet, +} + +impl<'b, 'a> Builder<'b, 'a> { + fn new(ex: &'a Exchange, reader: &'b mut Reader<'a>, tol: f64, budget: &'b mut usize, trims: Option<&'b dyn Trims>) -> Self { + Builder { + ex, + reader, + tol, + budget, + trims, + vertex_ids: HashMap::new(), + vertices: Vec::new(), + edge_ids: HashMap::new(), + edges: Vec::new(), + face_ids: HashSet::new(), + faces: Vec::new(), + sense_mismatches: 0, + raised_edges: HashSet::new(), + } + } + + fn vertex(&mut self, id: u64) -> R { + if let Some(v) = self.vertex_ids.get(&id) { + return Ok(*v); + } + let e = entity(self.ex, id)?; + if e.name() != "VERTEX_POINT" { + return Err(format!("#{id}: {}", unsupported(format!("vertex {}", e.name())))); + } + let point = self.reader.point(rid(e.params().get(1), "vertex point")?)?; + let i = index(self.vertices.len())?; + self.vertices.push(Vertex { point, tolerance: self.tol }); + self.vertex_ids.insert(id, i); + Ok(i) + } + + fn point(&self, v: u32) -> R { + self.vertices.get(v as usize).map(|v| v.point).ok_or_else(|| "vertex reference".to_string()) + } + + /// A vertex `gap` mm from where its edge's curve puts it: refused if far off, else its + /// tolerance covers the gap. + fn raise_vertex(&mut self, v: u32, gap: f64, edge: u64) -> R<()> { + if !(VERTEX_GAP_MARGIN * gap <= MAX_TOLERANCE) { + return Err(format!("edge #{edge}: a vertex lies {gap} mm off its curve")); + } + if let Some(x) = self.vertices.get_mut(v as usize) { + x.tolerance = x.tolerance.max(VERTEX_GAP_MARGIN * gap); + } + Ok(()) + } + + /// An edge's curve as the file has it may lie off a face's surface by more than the file's + /// uncertainty states (a B-spline edge whose control points stand 9 µm off its plane, in a + /// file that states 10 µm, gets no closed-form pcurve, which is checked within half that). + /// On a surface whose nearest point is in closed form (a plane, cylinder, cone, sphere or + /// torus) the edge's distance from it is measured along the edge before its pcurve is made, + /// and the edge's tolerance covers it. A spline face's gaps are measured on the pcurves its + /// kernel makes (`raise_edges`): an iterative nearest point may settle elsewhere on it. + fn measure_edges(&mut self, surface: &BSurface, edge_loops: &[Vec<(u32, bool)>]) -> R<()> { + // Only where the nearest point is in closed form: on a spline the search may settle on + // another part of the surface, or on its boundary for a point a hair past it, and report a + // gap the edge does not have (2.9 mm on Poppy Humanoid's leg shells, whose edges lie within + // 0.003 mm), widening tolerances past what SMLib takes. A spline face's gaps are measured + // on the pcurves its kernel makes (`raise_edges`). + if !matches!( + surface, + BSurface::Plane { .. } + | BSurface::PlaneThrough { .. } + | BSurface::Cylinder { .. } + | BSurface::Cone { .. } + | BSurface::Sphere { .. } + | BSurface::Torus { .. } + ) { + return Ok(()); + } + let on = SurfaceEval::new(surface).map_err(|m| m.to_string())?; + let starts = solidcraft_geom::tess::uv::Starts::default(); + for l in edge_loops { + for &(e, _) in l { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let (curve, [t0, t1]) = match &edge.form { + Some((c, i)) => (c, *i), + None => (&edge.curve, edge.interval), + }; + let eval = CurveEval::new(curve).map_err(|m| m.to_string())?; + let mut gap = 0.0f64; + for k in 0..=EDGE_GAP_SAMPLES { + let t = if k == EDGE_GAP_SAMPLES { t1 } else { t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64) }; + let Some(p) = eval.point(t) else { continue }; + // A point with no nearest point is the pcurves' to refuse, with why. + let Some(s) = on.project_with(&starts, p, None, f64::INFINITY).and_then(|q| on.point(q)) else { continue }; + gap = gap.max(s.dist(p)); + } + self.cover_edge(e, gap, pcurve::SURFACE_GAP_MARGIN)?; + } + } + Ok(()) + } + + /// Edge `e`'s tolerance covers `gap` with `margin`: refused if far off. + fn cover_edge(&mut self, e: u32, gap: f64, margin: f64) -> R<()> { + let Some(x) = self.edges.get_mut(e as usize) else { return Err("edge reference".into()) }; + if margin * gap <= x.tolerance { + return Ok(()); + } + if !(margin * gap <= MAX_TOLERANCE) { + return Err(format!("an edge lies {gap} mm off the face's surface")); + } + x.tolerance = margin * gap; + let (tolerance, ends) = (x.tolerance, x.vertices); + self.raised_edges.insert(e); + // A vertex's tolerance covers every edge that meets it, as in any tolerant record. + for v in ends { + if let Some(vx) = self.vertices.get_mut(v as usize) { + vx.tolerance = vx.tolerance.max(tolerance); + } + } + Ok(()) + } + + /// An edge's curve as the file has it may lie off a face's surface by more than the file's + /// uncertainty states (an intersection curve written looser than its context). Each use's + /// gap, between its pcurve on the surface and its edge's curve, is measured along the edge as + /// the record check measures it, and the edge's tolerance covers it, as a vertex's covers its + /// gap: the pcurves are as made and the record says how far its geometry agrees. + fn raise_edges(&mut self, surface: &BSurface, edge_loops: &[Vec<(u32, bool)>], pcs: &[Vec]) -> R<()> { + let on = SurfaceEval::new(surface).map_err(|m| m.to_string())?; + for (l, pc) in edge_loops.iter().zip(pcs) { + for (&(e, _), c) in l.iter().zip(pc) { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let (curve, [t0, t1]) = match &edge.form { + Some((c, i)) => (c, *i), + None => (&edge.curve, edge.interval), + }; + let eval = CurveEval::new(curve).map_err(|m| m.to_string())?; + let mut gap = 0.0f64; + for k in 0..=EDGE_GAP_SAMPLES { + let t = if k == EDGE_GAP_SAMPLES { t1 } else { t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64) }; + // A point a pcurve or surface lacks is the record check's to name. + let (Some(q), Some(p)) = (solidcraft_geom::brep::pcurve::eval(c, t), eval.point(t)) else { continue }; + if let Some(s) = on.point(q) { + gap = gap.max(s.dist(p)); + } + } + self.cover_edge(e, gap, EDGE_GAP_MARGIN)?; + } + } + Ok(()) + } + + /// The schema edge of an EDGE_CURVE, and whether it runs with the STEP edge. + fn edge(&mut self, id: u64) -> R<(u32, bool)> { + if let Some(e) = self.edge_ids.get(&id) { + return Ok(*e); + } + let e = entity(self.ex, id)?; + if e.name() != "EDGE_CURVE" { + return Err(format!("#{id}: {}", unsupported(format!("edge {}", e.name())))); + } + let p = e.params(); + let (vs_id, ve_id) = (rid(p.get(1), "edge start")?, rid(p.get(2), "edge end")?); + let (vs, ve) = (self.vertex(vs_id)?, self.vertex(ve_id)?); + let same_sense = flag(p.get(4), "edge same_sense")?; + let curve = self.edge_geometry(rid(p.get(3), "edge geometry")?, 0)?; + let (ps, pe) = (self.point(vs)?, self.point(ve)?); + let closed = vs == ve; + // A full turn when the edge has one vertex, or two at one point. Two vertices apart bound + // the arc between them, however short: a 20.4 um arc between vertices a 20.5 um uncertainty + // does not tell apart is that arc, not a turn around its face. + let full = closed || ps == pe; + let mapped = map_edge(&curve, ps, pe, same_sense, closed, full, self.tol).map_err(|m| format!("edge #{id}: {m}"))?; + if mapped.sense_mismatch { + self.sense_mismatches += 1; + } + let vertices = if mapped.with_step { [vs, ve] } else { [ve, vs] }; + // The gaps as the record will be read: its curve at its interval's ends. + let eval = CurveEval::new(&mapped.curve).map_err(|m| format!("edge #{id}: {m}"))?; + for (t, v) in mapped.interval.into_iter().zip(vertices) { + let at = eval.point(t).ok_or_else(|| format!("edge #{id}: no point at {t}"))?; + let gap = at.dist(v3(self.point(v)?)); + self.raise_vertex(v, gap, id)?; + } + let i = index(self.edges.len())?; + self.edges.push(EdgeB { curve: mapped.curve, interval: mapped.interval, vertices, tolerance: self.tol, form: None }); + self.edge_ids.insert(id, (i, mapped.with_step)); + Ok((i, mapped.with_step)) + } + + /// An edge's curve: SURFACE_CURVE and its subtypes by their 3D curve, TRIMMED_CURVE by its + /// basis (the edge's vertices bound it). + fn edge_geometry(&mut self, id: u64, depth: usize) -> R { + if depth > MAX_NESTING { + return Err("edge geometry nested too deeply".into()); + } + let e = entity(self.ex, id)?; + if !e.is_complex() { + match e.name() { + "SURFACE_CURVE" | "SEAM_CURVE" | "INTERSECTION_CURVE" | "BOUNDED_SURFACE_CURVE" => { + return self.edge_geometry(rid(e.params().get(1), "surface curve 3D curve")?, depth + 1); + } + "TRIMMED_CURVE" => return self.edge_geometry(rid(e.params().get(1), "trimmed curve basis")?, depth + 1), + _ => {} + } + } + let c = self.reader.curve(id)?; + let mut c: &Curve = &c; + // Already read as part of something else: unwrap the same way. + for _ in 0..=MAX_NESTING { + match c { + Curve::SurfaceCurve { curve_3d, .. } => c = curve_3d, + Curve::Trimmed { basis, .. } => c = basis, + _ => return Ok(c.clone()), + } + } + Err("edge geometry nested too deeply".into()) + } + + /// An ORIENTED_EDGE (or a bare EDGE_CURVE) as a loop uses it: its schema edge and whether + /// the loop runs along it. + fn oriented_edge(&mut self, id: u64, depth: usize) -> R<(u32, bool)> { + if depth > MAX_NESTING { + return Err("oriented edges nested too deeply".into()); + } + let e = entity(self.ex, id)?; + if e.name() == "ORIENTED_EDGE" { + let p = e.params(); + let (edge, along) = self.oriented_edge(rid(p.get(3), "oriented edge element")?, depth + 1)?; + let orientation = flag(p.get(4), "oriented edge orientation")?; + return Ok((edge, along == orientation)); + } + let (edge, with_step) = self.edge(id)?; + Ok((edge, with_step)) + } + + fn ends(&self, (edge, forward): (u32, bool)) -> R<[u32; 2]> { + let e = self.edges.get(edge as usize).ok_or("edge reference")?; + let [a, z] = e.vertices; + Ok(if forward { [a, z] } else { [z, a] }) + } + + /// A face bound: its loop as the face uses it (bound orientation applied), and whether it + /// is the FACE_OUTER_BOUND. + fn bound(&mut self, id: u64, edges_so_far: &mut usize) -> R<(LoopB, bool)> { + let b = entity(self.ex, id)?; + let outer = match b.name() { + "FACE_OUTER_BOUND" => true, + "FACE_BOUND" => false, + n => return Err(format!("#{id}: {}", unsupported(format!("face bound {n}")))), + }; + let p = b.params(); + let lp_id = rid(p.get(1), "face bound loop")?; + let orientation = flag(p.get(2), "face bound orientation")?; + let lp = entity(self.ex, lp_id)?; + match lp.name() { + "EDGE_LOOP" => { + let ids = refs(lp.params().get(1), "edge loop")?; + *edges_so_far = edges_so_far.saturating_add(ids.len()); + if ids.is_empty() || *edges_so_far > MAX_LOOP { + return Err(format!("edge loop #{lp_id} with {} edges", ids.len())); + } + let mut uses = Vec::with_capacity(ids.len()); + for oe in ids { + uses.push(self.oriented_edge(oe, 0)?); + } + // Connected and closed, as the loop is written. + let mut last = None; + for u in &uses { + let [s, e] = self.ends(*u)?; + if last.is_some_and(|l| l != s) { + return Err(format!("edge loop #{lp_id} is not connected")); + } + last = Some(e); + } + if let (Some(first), Some(last)) = (uses.first(), last) + && self.ends(*first)?[0] != last + { + return Err(format!("edge loop #{lp_id} is not closed")); + } + if !orientation { + reverse(&mut uses); + } + Ok((LoopB::Edges(uses), outer)) + } + "VERTEX_LOOP" => Ok((LoopB::Vertex(self.vertex(rid(lp.params().get(1), "vertex loop")?)?), outer)), + n => Err(format!("#{lp_id}: {}", unsupported(format!("loop {n}")))), + } + } + + /// A face as a shell uses it: its index and whether its normal there is its surface's + /// natural normal. + fn face(&mut self, id: u64, depth: usize) -> R<(u32, bool)> { + if depth > MAX_NESTING { + return Err("oriented faces nested too deeply".into()); + } + let e = entity(self.ex, id)?; + let p = e.params(); + if e.name() == "ORIENTED_FACE" { + let (f, forward) = self.face(rid(p.get(2), "oriented face element")?, depth + 1)?; + return Ok((f, forward == flag(p.get(3), "oriented face orientation")?)); + } + if !matches!(e.name(), "ADVANCED_FACE" | "FACE_SURFACE") { + return Err(format!("#{id}: {}", unsupported(format!("face {}", e.name())))); + } + if !self.face_ids.insert(id) { + return Err(format!("face #{id} is used twice")); + } + *self.budget = self.budget.checked_sub(1).ok_or_else(|| format!("more than {MAX_FILE_FACES} faces in one file"))?; + if self.faces.len() >= MAX_FACES { + return Err(format!("more than {MAX_FACES} faces")); + } + let step_surface = self.reader.surface(rid(p.get(2), "face geometry")?).map_err(|m| format!("face #{id}: {m}"))?; + let same_sense = flag(p.get(3), "face same_sense")?; + let bounds = refs(p.get(1), "face bounds")?; + if bounds.len() > MAX_BOUNDS { + return Err(format!("face #{id} with {} bounds", bounds.len())); + } + let mut loops = Vec::with_capacity(bounds.len()); + let mut outer = None; + let mut edges = 0; + for b in bounds { + let (l, is_outer) = self.bound(b, &mut edges).map_err(|m| format!("face #{id}: {m}"))?; + if is_outer && outer.is_none() { + outer = Some(loops.len()); + } + loops.push(l); + } + if !loops.iter().any(|l| matches!(l, LoopB::Edges(_))) { + return Err(format!("face #{id}: {}", unsupported("a face without an edge loop"))); + } + let extent = self.extent(&loops)?; + let (surface, reversed) = swept::map_surface(&step_surface, &extent, self.tol).map_err(|m| format!("face #{id}: {m}"))?; + // Loops relative to the record's natural normal: the face's normal is STEP's surface + // normal when same_sense, and the record's is STEP's unless `reversed`. + let sense = same_sense != reversed; + if !sense { + for l in &mut loops { + if let LoopB::Edges(uses) = l { + reverse(uses); + } + } + } + let i = index(self.faces.len())?; + self.faces.push(FaceB { step: id, surface, loops, outer, forward: sense, extent: None }); + Ok((i, sense)) + } + + /// Points along a face's loops (each edge at nine points, and its vertex loops), and along + /// the edges its loops use twice (its seams). + fn extent(&self, loops: &[LoopB]) -> R { + let mut ext = swept::Extent::default(); + let mut count: HashMap = HashMap::new(); + for l in loops { + match l { + LoopB::Edges(es) => { + for (e, _) in es { + *count.entry(*e).or_default() += 1; + } + } + LoopB::Vertex(v) => ext.points.push(v3(self.point(*v)?)), + } + } + let mut edges: Vec = count.keys().copied().collect(); + edges.sort_unstable(); + for e in edges { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let [lo, hi] = edge.interval; + for k in 0..=8 { + let p = c.point(lo + (hi - lo) * f64::from(k) / 8.0).ok_or("edge point")?; + ext.points.push(p); + if count.get(&e).is_some_and(|n| *n > 1) { + ext.seam.push(p); + } + } + } + Ok(ext) + } + + /// The faces of shell `id` but those `left_out`, and whether any was left out. + fn shell(&mut self, id: u64, left_out: &HashSet) -> R<(Vec<(u32, bool)>, bool)> { + let (faces, flip) = shell_faces(self.ex, id)?; + let mut out = Vec::with_capacity(faces.len()); + let mut skipped = false; + for f in faces { + if !left_out.is_empty() && (left_out.contains(&f) || left_out.contains(&self.face_entity(f, 0)?)) { + skipped = true; + continue; + } + let (face, forward) = self.face(f, 0)?; + out.push((face, forward != flip)); + } + Ok((out, skipped)) + } + + /// The ADVANCED_FACE or FACE_SURFACE a shell's face `id` is (through its ORIENTED_FACEs). + fn face_entity(&self, id: u64, depth: usize) -> R { + if depth > MAX_NESTING { + return Err("oriented faces nested too deeply".into()); + } + let e = entity(self.ex, id)?; + if e.name() == "ORIENTED_FACE" { + return self.face_entity(rid(e.params().get(2), "oriented face element")?, depth + 1); + } + Ok(id) + } + + /// Pcurves, outer loops, domains and the canonical order: the finished record. + fn finish(mut self, item: u64, name: String, shells: Vec>, kind: Kind) -> R { + let _span = solidcraft_profile::span("import", "step.solid_record"); + let mut notes = Vec::new(); + // A face bounded by a slit alone is the whole of its closed surface, closed by its seams + // (a sphere's frame put on the slit), before anything is measured on the frame or split + // at its poles. + self.complete_slits()?; + let at_poles = self.split_at_poles()?; + if at_poles > 0 { + notes.push(format!("{at_poles} edges split where they pass through a face's pole")); + } + self.start_splines_clear_of_faces()?; + let seams = self.add_seams()?; + if seams > 0 { + notes.push(format!("{seams} seam edges added to faces that wind around their surface")); + } + if self.sense_mismatches > 0 { + notes.push(format!("{} edges run against their same_sense (read by their vertices)", self.sense_mismatches)); + } + // Round faces whose forms would run past one turn start on a quarter line of their + // frames, before their edges are labelled on them. + self.turn_frames()?; + // Each edge's label and NURBS form: a circle about a revolved face's axis labelled on that + // face's frame, so its form lies on the face's quarter grid. + // A circle round a torus face's tube is labelled from its tube start likewise. + let mut frames: Vec> = vec![Vec::new(); self.edges.len()]; + let mut tori: Vec> = vec![Vec::new(); self.edges.len()]; + for f in &self.faces { + let Some(frame) = solidcraft_geom::brep::form::frame_of(&f.surface) else { continue }; + let torus = matches!(f.surface, BSurface::Torus { .. }); + for l in &f.loops { + if let LoopB::Edges(es) = l { + for (e, _) in es { + if let Some(slot) = frames.get_mut(*e as usize) { + slot.push(frame.clone()); + } + if torus && let Some(slot) = tori.get_mut(*e as usize) { + slot.push(f.surface.clone()); + } + } + } + } + } + for ((edge, fr), tr) in self.edges.iter_mut().zip(&frames).zip(&tori) { + let (label, interval, form) = solidcraft_geom::brep::form::edge_on(&edge.curve, edge.interval, fr, tr, self.tol) + .ok_or_else(|| unsupported("an arc of more than one turn"))?; + (edge.curve, edge.interval, edge.form) = (label, interval, form); + } + // Each face's pcurves; a face whose loops disagree with its same_sense is turned over. + let mut pcs: Vec>> = Vec::with_capacity(self.faces.len()); + let mut face_forms: Vec> = Vec::with_capacity(self.faces.len()); + let mut domains = Vec::with_capacity(self.faces.len()); + let mut turned = vec![false; self.faces.len()]; + let (mut failed, mut first_failure) = (0usize, None); + for fi in 0..self.faces.len() { + match self.face_pcurves(fi) { + Ok((pc, domain, flipped, form)) => { + face_forms.push(form); + if flipped && let Some(t) = turned.get_mut(fi) { + *t = true; + } + pcs.push(pc); + domains.push(domain); + } + Err(m) => { + failed += 1; + first_failure.get_or_insert_with(|| format!("face #{}: {m}", self.faces.get(fi).map_or(0, |f| f.step))); + pcs.push(Vec::new()); + domains.push([[0.0; 2]; 2]); + face_forms.push(None); + } + } + } + if let Some(first) = first_failure { + return Err(format!("pcurves failed on {failed} of {} faces; first: {first}", self.faces.len())); + } + if !self.raised_edges.is_empty() { + let most = self.raised_edges.iter().filter_map(|&e| self.edges.get(e as usize)).map(|e| e.tolerance).fold(0.0, f64::max); + notes.push(format!( + "{} edges lie off their faces' surfaces by more than {} mm: their tolerances are the gaps they have (up to {most:.3e} mm)", + self.raised_edges.len(), + self.tol + )); + } + let flipped = turned.iter().filter(|t| **t).count(); + if flipped > 0 { + notes.push(format!("{flipped} faces turned over: their loops disagree with their same_sense")); + } + let shells: Vec> = shells + .into_iter() + .map(|s| s.into_iter().map(|(f, fwd)| (f, if turned.get(f as usize).copied().unwrap_or(false) { !fwd } else { fwd })).collect()) + .collect(); + + // Regions: which shells are closed (every edge used at least twice among its faces). + let closed: Vec = shells.iter().map(|s| self.closed(s)).collect(); + // A void's faces face into the cavity, out of the material: it encloses volume of the + // opposite sign to the outer shell's. The ORIENTED_CLOSED_SHELL flag alone doesn't say + // so: some exporters write .F. over a shell already facing into the cavity (#3730), + // SolidCraft .T.; read by the flag, such a void added its cavity's volume to the solid's. + // A void enclosing volume of the outer shell's sign is turned inside out, the signs the + // faces' own surfaces and pcurves give (`face_flux` of p / 3, the divergence theorem). + let shells = if kind == Kind::Voids && closed.iter().all(|c| *c) { + let volume = |s: &[(u32, bool)]| -> Option { + let mut sum = 0.0; + for &(f, forward) in s { + let face = self.faces.get(f as usize)?; + let on = face_forms.get(f as usize)?.as_ref().unwrap_or(&face.surface); + let eval = SurfaceEval::new(on).ok()?; + let edge_loops = face.loops.iter().filter_map(|l| match l { + LoopB::Edges(es) => Some(es), + LoopB::Vertex(_) => None, + }); + let uses: Vec> = + edge_loops.zip(pcs.get(f as usize)?).map(|(es, pc)| pc.iter().zip(es).map(|(c, (_, fwd))| (c, *fwd)).collect()).collect(); + let flux = face_flux(&eval, domains.get(f as usize)?[1][0], &uses, &|p| p * (1.0 / 3.0))?; + sum += if forward { flux } else { -flux }; + } + sum.is_finite().then_some(sum) + }; + let outside = shells.first().and_then(|s| volume(s)); + shells + .into_iter() + .enumerate() + .map(|(k, s)| match (outside, k > 0) { + (Some(o), true) if volume(&s).is_some_and(|v| v * o > 0.0) => s.into_iter().map(|(f, fwd)| (f, !fwd)).collect(), + _ => s, + }) + .collect() + } else { + shells + }; + let mut regions = vec![Region { shells: Vec::new(), void: false }]; + match kind { + Kind::Solid | Kind::Voids => { + if let Some(k) = closed.iter().position(|c| !c) { + return Err(format!("{} shell is not closed", if k == 0 { "the outer" } else { "a void" })); + } + regions[0].shells.push(0); + regions.push(Region { shells: (0..index(shells.len())?).collect(), void: false }); + for v in 1..shells.len() { + regions.push(Region { shells: vec![index(v)?], void: true }); + } + } + Kind::Open => regions[0].shells = (0..index(shells.len())?).collect(), + Kind::Model => { + regions[0].shells = (0..index(shells.len())?).collect(); + for (k, c) in closed.iter().enumerate() { + if *c { + regions.push(Region { shells: vec![index(k)?], void: false }); + } + } + } + } + let sheet = kind == Kind::Open || !closed.iter().any(|c| *c); + + // Canonical order: faces walking regions → shells → oriented faces. + let nf = self.faces.len(); + let mut face_new = vec![u32::MAX; nf]; + let mut face_order = Vec::with_capacity(nf); + let mut direction = vec![true; nf]; + let mut seen_shell = vec![false; shells.len()]; + for r in ®ions { + for &s in &r.shells { + let Some(seen) = seen_shell.get_mut(s as usize) else { continue }; + if std::mem::replace(seen, true) { + continue; + } + for &(f, fwd) in shells.get(s as usize).into_iter().flatten() { + let slot = face_new.get_mut(f as usize).ok_or("face reference")?; + if *slot == u32::MAX { + *slot = index(face_order.len())?; + face_order.push(f); + if let Some(d) = direction.get_mut(f as usize) { + *d = fwd; + } + } + } + } + } + // Edges walking faces → loops (outer first) → oriented edges, backwards in a face whose + // first side is reversed; their uses in that order. + let outer_first: Vec> = (0..nf).map(|f| self.loop_order(f)).collect(); + let mut edge_new = vec![u32::MAX; self.edges.len()]; + let mut edge_order = Vec::with_capacity(self.edges.len()); + let mut uses: Vec> = vec![Vec::new(); self.edges.len()]; + for (fnew, &f) in face_order.iter().enumerate() { + let face = self.faces.get(f as usize).ok_or("face reference")?; + let forward = direction.get(f as usize).copied().unwrap_or(true); + for (lnew, &l) in outer_first.get(f as usize).into_iter().flatten().enumerate() { + let Some(LoopB::Edges(es)) = face.loops.get(l) else { continue }; + let n = es.len(); + for k in 0..n { + let p = if forward { k } else { n - 1 - k }; + let &(e, fwd) = es.get(p).ok_or("edge reference")?; + let slot = edge_new.get_mut(e as usize).ok_or("edge reference")?; + if *slot == u32::MAX { + *slot = index(edge_order.len())?; + edge_order.push(e); + } + let at = EdgeUseRef { face: index(fnew)?, r#loop: index(lnew)?, position: index(p)?, upper: !fwd }; + uses.get_mut(e as usize).ok_or("edge reference")?.push(at); + } + } + } + // Vertices walking edges (start, end), then vertex loops. + let mut vertex_new = vec![u32::MAX; self.vertices.len()]; + let mut vertex_order = Vec::with_capacity(self.vertices.len()); + let mut visit = |v: u32, vertex_new: &mut Vec| -> R { + let slot = vertex_new.get_mut(v as usize).ok_or("vertex reference")?; + if *slot == u32::MAX { + *slot = index(vertex_order.len())?; + vertex_order.push(v); + } + Ok(*slot) + }; + for &e in &edge_order { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + for v in edge.vertices { + visit(v, &mut vertex_new)?; + } + } + for &f in &face_order { + for &l in outer_first.get(f as usize).into_iter().flatten() { + if let Some(LoopB::Vertex(v)) = self.faces.get(f as usize).and_then(|x| x.loops.get(l)) { + visit(*v, &mut vertex_new)?; + } + } + } + let vmap = |v: u32| vertex_new.get(v as usize).copied().filter(|x| *x != u32::MAX).ok_or("vertex reference".to_string()); + let emap = |e: u32| edge_new.get(e as usize).copied().filter(|x| *x != u32::MAX).ok_or("edge reference".to_string()); + let fmap = |f: u32| face_new.get(f as usize).copied().filter(|x| *x != u32::MAX).ok_or("face reference".to_string()); + let mut turned_faces = Vec::with_capacity(flipped); + for (f, t) in turned.iter().enumerate() { + if *t { + turned_faces.push(fmap(index(f)?)?); + } + } + turned_faces.sort_unstable(); + + // Vertex loops: their vertex's distance from the surface is its tolerance. + for &f in &face_order { + let Some(face) = self.faces.get(f as usize) else { continue }; + let surface = SurfaceEval::new(&face.surface).map_err(|m| m.to_string())?; + for l in &face.loops { + if let LoopB::Vertex(v) = l + && let Some(x) = self.vertices.get_mut(*v as usize) + { + let p = v3(x.point); + let gap = surface.project(p, None, f64::INFINITY).and_then(|q| surface.point(q)).map_or(f64::INFINITY, |s| s.dist(p)); + if !(VERTEX_GAP_MARGIN * gap <= MAX_TOLERANCE) { + return Err(format!("face #{}: a vertex loop's vertex lies {gap} mm off its surface", face.step)); + } + x.tolerance = x.tolerance.max(VERTEX_GAP_MARGIN * gap); + } + } + } + + let mut vertices = Vec::with_capacity(vertex_order.len()); + for &v in &vertex_order { + vertices.push(self.vertices.get(v as usize).cloned().ok_or("vertex reference")?); + } + let mut edges = Vec::with_capacity(edge_order.len()); + for &e in &edge_order { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let (nurbs, interval) = match &edge.form { + Some((c, i)) => (Some(c.clone()), *i), + None => (None, edge.interval), + }; + edges.push(Edge { + nurbs, + curve: edge.curve.clone(), + interval, + vertices: [vmap(edge.vertices[0])?, vmap(edge.vertices[1])?], + tolerance: edge.tolerance, + uses: uses.get(e as usize).cloned().unwrap_or_default(), + }); + } + let mut faces = Vec::with_capacity(face_order.len()); + let mut face_origin = Vec::with_capacity(face_order.len()); + for &f in &face_order { + let face = self.faces.get(f as usize).ok_or("face reference")?; + face_origin.push(face.step); + let pc = pcs.get(f as usize).ok_or("face reference")?; + let mut loops = Vec::with_capacity(face.loops.len()); + let mut edge_loop = 0; + // pcurves come in the face's edge-loop order; loops go out outer first. + let mut fitted: Vec>> = Vec::with_capacity(face.loops.len()); + for l in &face.loops { + fitted.push(match l { + LoopB::Edges(_) => { + edge_loop += 1; + pc.get(edge_loop - 1) + } + LoopB::Vertex(_) => None, + }); + } + for &l in outer_first.get(f as usize).into_iter().flatten() { + match face.loops.get(l) { + Some(LoopB::Edges(es)) => { + let curves = fitted.get(l).copied().flatten().ok_or("pcurves")?; + let mut out = Vec::with_capacity(es.len()); + for (&(e, forward), c) in es.iter().zip(curves) { + out.push(OrientedEdge { edge: emap(e)?, forward, pcurve: c.clone() }); + } + loops.push(Loop::Edges { edges: out }); + } + Some(LoopB::Vertex(v)) => loops.push(Loop::Vertex { vertex: vmap(*v)? }), + None => return Err("loop reference".into()), + } + } + let domain = *domains.get(f as usize).ok_or("face reference")?; + let nurbs = face_forms.get(f as usize).cloned().flatten(); + faces.push(Face { nurbs, surface: face.surface.clone(), domain, loops }); + } + let mut out_shells = Vec::with_capacity(shells.len()); + for s in &shells { + let mut faces = Vec::with_capacity(s.len()); + for &(f, forward) in s { + faces.push(OrientedFace { face: fmap(f)?, forward }); + } + out_shells.push(Shell::Faces { faces, wires: Vec::new() }); + } + let brep = Brep { version: brep::VERSION, tolerance: self.tol, regions, shells: out_shells, faces, edges, vertices }; + solidcraft_geom::brep::check::validate(&brep).map_err(|e| format!("the record is invalid: {e}"))?; + solidcraft_geom::brep::geometry::check(&brep).map_err(|e| format!("the record's geometry disagrees: {e}"))?; + Ok(Solid { item, name, product: None, brep, face_origin, sheet, notes, turned: turned_faces }) + } + + /// Every edge of the shell's faces used at least twice among them. + fn closed(&self, shell: &[(u32, bool)]) -> bool { + let mut count: HashMap = HashMap::new(); + for &(f, _) in shell { + for l in self.faces.get(f as usize).map(|f| f.loops.as_slice()).unwrap_or(&[]) { + if let LoopB::Edges(es) = l { + for (e, _) in es { + *count.entry(*e).or_default() += 1; + } + } + } + } + count.values().all(|n| *n >= 2) + } + + /// The face's loops, outer first (the rest in the file's order). + fn loop_order(&self, f: usize) -> Vec { + let Some(face) = self.faces.get(f) else { return Vec::new() }; + let outer = face.outer.unwrap_or(0); + std::iter::once(outer).chain((0..face.loops.len()).filter(|l| *l != outer)).collect() + } + + /// A face's box on its label over its edge loops (`solidcraft_geom::brep::form::extent`); `None` where the + /// boundary does not project onto it. + fn face_extent(&self, fi: usize) -> R> { + let face = self.faces.get(fi).ok_or("face reference")?; + let mut boundary = Vec::with_capacity(face.loops.len()); + for l in &face.loops { + let LoopB::Edges(es) = l else { continue }; + let mut b = Vec::with_capacity(es.len()); + for &(e, forward) in es { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + b.push((&edge.curve, edge.interval, forward)); + } + boundary.push(b); + } + Ok(solidcraft_geom::brep::form::extent(&face.surface, &boundary)) + } + + /// The pcurves of a face's edge loops (in its edge-loop order), its domain, whether it was + /// turned over, and its NURBS form. Picks the outer loop when the file + /// marks none (or marks one that another loop encloses), and turns the face over when its + /// outer loop runs clockwise about the natural normal on a surface where that cannot be a + /// face's outer boundary. + fn face_pcurves(&mut self, fi: usize) -> R<(Vec>, [[f64; 2]; 2], bool, Option)> { + let _span = solidcraft_profile::span("import", "step.face_pcurves"); + let face = self.faces.get(fi).ok_or("face reference")?; + let label = face.surface.clone(); + let edge_loops: Vec> = face + .loops + .iter() + .filter_map(|l| match l { + LoopB::Edges(es) => Some(es.clone()), + LoopB::Vertex(_) => None, + }) + .collect(); + // Which loop index in `face.loops` each edge loop is. + let positions: Vec = face.loops.iter().enumerate().filter(|(_, l)| matches!(l, LoopB::Edges(_))).map(|(i, _)| i).collect(); + let tol = self.tol; + // A cylinder, cone, sphere, torus or revolution on its NURBS form, over the extent of its + // boundary on its label; then every pcurve on the forms. + let form = match solidcraft_geom::brep::form::frame_of(&label) { + Some(_) => { + let extent = match face.extent { + Some(e) => Some(e), + None => self.face_extent(fi)?, + }; + let extent = extent.ok_or_else(|| unsupported("a face whose boundary does not lie on its surface"))?; + Some(solidcraft_geom::brep::form::surface_within(&label, extent, tol).ok_or_else(|| unsupported("a face of more than one turn"))?) + } + None => None, + }; + let (form, box_on_form) = match form { + Some((f, d)) => (Some(f), Some(d)), + None => (None, None), + }; + let surface = form.clone().unwrap_or_else(|| label.clone()); + // How far each edge lies off this surface, so its closed form is checked at that. + self.measure_edges(&label, &edge_loops)?; + // Closed forms where the geometry has them; the kernel makes the rest (`trims`). + let exact = pcurve::exact_pcurves(&surface, &uses_of(&self.edges, &edge_loops, None)?, tol, box_on_form).map_err(|e| e.to_string())?; + // Without a kernel, a use with neither is refused below with why. + let made = match self.trims { + Some(trims) if exact.iter().flatten().any(Option::is_none) => { + let domain = match box_on_form { + Some(d) => d, + None => natural_box(&surface).ok_or_else(|| unsupported("a face on an unbounded surface without closed-form pcurves"))?, + }; + Some(trims.trims(&self.trim_face(&label, form.as_ref(), domain, &edge_loops, exact)?)?) + } + _ => None, + }; + let pcs = + pcurve::pcurves_within(&surface, &uses_of(&self.edges, &edge_loops, made.as_ref())?, tol, box_on_form).map_err(|e| e.to_string())?; + self.raise_edges(&surface, &edge_loops, &pcs)?; + // Signed areas of the loops that close in (u, v). + let periods = natural_periods(&surface); + // Each use starts near where the one before it ends, along a bounded direction that + // does not wrap: a loop around a closed spline surface without a seam edge jumps across + // its domain. + let natural = solidcraft_geom::brep::label::surface_natural(&surface); + // At a pole (where the surface collapses to a point across a direction, to within the + // tolerance of the vertex the two uses meet at) a loop may jump in that direction: the + // seam's two uses meet there a period apart, and a side collapsed to within the vertex's + // tolerance (a corner patch with one side shrunk to a few µm) is run along between them, + // its boundary iso line. As the record check (`brep::geometry`) takes it. + let poles = SurfaceEval::new(&surface).ok(); + let at_pole = |uv: [f64; 2], reach: f64| poles.as_ref().is_some_and(|e| e.pole_within(uv, reach).iter().any(|p| *p)); + for (l, pc) in edge_loops.iter().zip(&pcs) { + let mut ends = Vec::with_capacity(l.len()); + for (&(_, forward), c) in l.iter().zip(pc) { + let [a, b] = c.interval().ok_or("pcurve interval")?; + let (s, e) = ( + solidcraft_geom::brep::pcurve::eval(c, a).ok_or("pcurve start")?, + solidcraft_geom::brep::pcurve::eval(c, b).ok_or("pcurve end")?, + ); + ends.push(if forward { (s, e) } else { (e, s) }); + } + for k in 0..ends.len() { + let (Some((start, _)), Some((_, end))) = (ends.get(k), ends.get(if k == 0 { ends.len() - 1 } else { k - 1 })) else { continue }; + // The vertex use k starts at, where the one before it ends. + let &(e, forward) = l.get(k).ok_or("edge use")?; + let v = self.edges.get(e as usize).ok_or("edge reference")?.vertices[if forward { 0 } else { 1 }]; + let reach = self.vertices.get(v as usize).ok_or("vertex reference")?.tolerance.max(tol); + if at_pole(*start, reach) || at_pole(*end, reach) { + continue; + } + for d in 0..2 { + // Only a bounded direction has a seam to jump; half its width is no gap. + let Some(Natural::Range(a, b)) = natural.get(d) else { continue }; + if !(b - a).is_finite() { + continue; + } + if !((start[d] - end[d]).abs() <= 0.5 * (b - a)) { + // Whether the surface closes across `d` there: its two boundaries meet. + let ends_at = |x: f64| { + let mut q = *start; + q[d] = x; + poles.as_ref().and_then(|s| s.point(q)) + }; + let closed = matches!((ends_at(*a), ends_at(*b)), (Some(p), Some(q)) if p.dist(q) <= reach); + return Err(unsupported(if closed { + "a loop across a closed spline surface's seam without a seam edge".to_string() + } else { + format!( + "a loop that jumps across its spline surface's {} range where the surface neither closes nor collapses to a point", + if d == 0 { "u" } else { "v" } + ) + })); + } + } + } + } + let shapes: Vec> = edge_loops.iter().zip(&pcs).map(|(l, pc)| loop_area(l, pc, periods)).collect(); + let face = self.faces.get_mut(fi).ok_or("face reference")?; + let marked = face.outer.and_then(|o| positions.iter().position(|p| *p == o)); + let largest = shapes.iter().enumerate().filter_map(|(i, a)| a.map(|a| (i, a.abs()))).max_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i); + let outer = match (marked, largest) { + // A marked outer loop that closes in (u, v) but another encloses more: that one. + (Some(m), Some(l)) if shapes.get(m).copied().flatten().is_some() => l, + (Some(m), _) => m, + (None, Some(l)) if shapes.iter().all(Option::is_some) => l, + (None, _) => 0, + }; + face.outer = positions.get(outer).copied(); + let can_turn = matches!( + surface, + BSurface::Plane { .. } | BSurface::Cylinder { .. } | BSurface::Cone { .. } | BSurface::Spline { .. } | BSurface::RationalSpline { .. } + ); + let clockwise = shapes.get(outer).copied().flatten().is_some_and(|a| a < 0.0); + // A face bounded by seam uses alone (a whole torus within its two seams) has loops that + // run each edge both ways: run backwards they are the same uses, so they say nothing of + // the face's side. One running clockwise is run the other way; the face keeps its side. + let seams_only = edge_loops.iter().all(|l| seam_only(l)); + let flip = can_turn && clockwise && !seams_only; + let rerun = flip || (clockwise && seams_only); + if rerun { + for l in &mut face.loops { + if let LoopB::Edges(es) = l { + reverse(es); + } + } + } + if flip { + face.forward = !face.forward; + } + let pcs: Vec> = if rerun { pcs.into_iter().map(|l| l.into_iter().rev().collect()).collect() } else { pcs }; + let domain = face_domain(&surface, &pcs)?; + Ok((pcs, domain, flip, form)) + } +} + +impl Builder<'_, '_> { + /// The face as a kernel takes it to make its missing pcurves: its edges and vertices + /// numbered within it, each use with its closed-form pcurve where `exact` has one. + fn trim_face<'s>( + &'s self, + surface: &'s BSurface, + nurbs: Option<&'s BSurface>, + domain: [[f64; 2]; 2], + edge_loops: &[Vec<(u32, bool)>], + exact: Vec>>, + ) -> R> { + let _span = solidcraft_profile::span("import", "step.trim_face"); + let (mut edge_at, mut vertex_at) = (HashMap::new(), HashMap::new()); + let (mut edges, mut vertices) = (Vec::new(), Vec::new()); + let mut loops = Vec::with_capacity(edge_loops.len()); + for (l, pcs) in edge_loops.iter().zip(exact) { + let mut uses = Vec::with_capacity(l.len()); + for (&(e, forward), pcurve) in l.iter().zip(pcs) { + let local = match edge_at.get(&e) { + Some(i) => *i, + None => { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let mut ends = [0u32; 2]; + for (end, v) in ends.iter_mut().zip(edge.vertices) { + *end = match vertex_at.get(&v) { + Some(i) => *i, + None => { + let i = index(vertices.len())?; + vertices.push(self.point(v)?); + vertex_at.insert(v, i); + i + } + }; + } + let (curve, nurbs, interval) = match &edge.form { + Some((n, i)) => (&edge.curve, Some(n), *i), + None => (&edge.curve, None, edge.interval), + }; + let i = index(edges.len())?; + edges.push(TrimEdge { curve, nurbs, interval, vertices: ends, tolerance: edge.tolerance }); + edge_at.insert(e, i); + i + } + }; + uses.push(TrimUse { edge: local, forward, pcurve }); + } + loops.push(uses); + } + Ok(TrimFace { surface, nurbs, domain, edges, vertices, loops, tolerance: self.tol }) + } +} + +/// A face's uses on their edges' NURBS forms, with `given` pcurves where a kernel made them. +fn uses_of<'e>(edges: &'e [EdgeB], edge_loops: &[Vec<(u32, bool)>], given: Option<&'e Vec>>) -> R>>> { + let mut uses = Vec::with_capacity(edge_loops.len()); + for (li, l) in edge_loops.iter().enumerate() { + let mut u = Vec::with_capacity(l.len()); + for (p, &(e, forward)) in l.iter().enumerate() { + let edge = edges.get(e as usize).ok_or("edge reference")?; + let (curve, interval) = match &edge.form { + Some((c, i)) => (c, *i), + _ => (&edge.curve, edge.interval), + }; + let given = match given { + Some(g) => Some(g.get(li).and_then(|l| l.get(p)).ok_or("a pcurve the kernel did not make")?), + None => None, + }; + u.push(EdgeUse { edge: e, curve, interval, forward, tolerance: edge.tolerance, given }); + } + uses.push(u); + } + Ok(uses) +} + +/// A spline surface's parameter box: its knot ranges. +fn natural_box(s: &BSurface) -> Option<[[f64; 2]; 2]> { + match solidcraft_geom::brep::label::surface_natural(s) { + [Natural::Range(a, b), Natural::Range(c, d)] if [a, b, c, d].iter().all(|x| x.is_finite()) => Some([[a, b], [c, d]]), + _ => None, + } +} + +/// Every edge of the loop is used in it exactly twice, once each way: a loop of seam uses alone. +fn seam_only(uses: &[(u32, bool)]) -> bool { + let mut ways: HashMap = HashMap::with_capacity(uses.len() / 2); + for &(e, forward) in uses { + if let Some(n) = ways.entry(e).or_default().get_mut(usize::from(forward)) { + *n += 1; + } + } + !uses.is_empty() && ways.values().all(|n| *n == [1, 1]) +} + +/// The loop run the other way. +fn reverse(uses: &mut [(u32, bool)]) { + uses.reverse(); + for u in uses { + u.1 = !u.1; + } +} + +fn natural_periods(s: &BSurface) -> [bool; 2] { + solidcraft_geom::brep::label::surface_natural(s).map(|n| matches!(n, Natural::Periodic)) +} + +/// The signed area a loop encloses in (u, v) (positive counter-clockwise), or `None` when it +/// does not close there (it winds around a periodic direction) or is degenerate. +fn loop_area(l: &[(u32, bool)], pcs: &[Curve2], periodic: [bool; 2]) -> Option { + let mut pts: Vec<[f64; 2]> = Vec::new(); + for (&(_, forward), c) in l.iter().zip(pcs) { + let [a, b] = c.interval()?; + for k in 0..=16 { + let s = f64::from(k) / 16.0; + let t = if forward { a + (b - a) * s } else { b - (b - a) * s }; + pts.push(solidcraft_geom::brep::pcurve::eval(c, t)?); + } + } + let (first, last) = (*pts.first()?, *pts.last()?); + for d in 0..2 { + if periodic.get(d).copied().unwrap_or(false) && (first.get(d)? - last.get(d)?).abs() > 1.0 { + return None; + } + } + let mut area = 0.0; + let mut magnitude = 0.0; + for w in pts.windows(2) { + let (p, q) = (w.first()?, w.get(1)?); + let c = (p[0] - first[0]) * (q[1] - first[1]) - (q[0] - first[0]) * (p[1] - first[1]); + area += c; + magnitude += c.abs(); + } + (area.abs() > 1e-9 * magnitude && magnitude > 0.0).then_some(0.5 * area) +} + +/// The parameter box around every pcurve's control points, padded a little, within the +/// surface's natural domain (at most one turn where periodic). +fn face_domain(surface: &BSurface, pcs: &[Vec]) -> R<[[f64; 2]; 2]> { + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for c in pcs.iter().flatten() { + let pts: Vec<[f64; 2]> = match c { + Curve2::Spline { points, .. } => points.clone(), + Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().filter(|h| h[2] > 0.0).map(|h| [h[0] / h[2], h[1] / h[2]]).collect(), + }; + for p in pts { + for d in 0..2 { + lo[d] = lo[d].min(p[d]); + hi[d] = hi[d].max(p[d]); + } + } + } + let natural = solidcraft_geom::brep::label::surface_natural(surface); + let mut out = [[0.0; 2]; 2]; + for d in 0..2 { + let (a, b) = (lo[d], hi[d]); + if !(a.is_finite() && b.is_finite() && a <= b) { + return Err("a face without pcurves".into()); + } + let pad = 1e-6 * (1.0 + (b - a)) + 1e-9 * a.abs().max(b.abs()); + let (mut x, mut y) = (a - pad, b + pad); + match natural.get(d) { + Some(Natural::Periodic) => { + if y - x > TAU { + x = a; + y = a + TAU; + } + } + Some(Natural::Range(n0, n1)) => { + x = x.max(*n0); + y = y.min(*n1); + } + None => {} + } + if !(x < y) { + return Err("an empty face domain".into()); + } + if let Some(slot) = out.get_mut(d) { + *slot = [x, y]; + } + } + Ok(out) +} + +fn frame(p: &Placement) -> Frame { + Frame { origin: p.origin, x_axis: p.ref_direction, y_axis: p.y() } +} + +/// Knots repeated by their multiplicities, for a spline of `count` points and `degree`. +fn full_knots(knots: &[f64], mults: &[usize], count: usize, degree: usize) -> R> { + if !(1..=MAX_SPLINE_DEGREE).contains(°ree) { + return Err(unsupported(format!("a B-spline of degree {degree}"))); + } + if !(2..=MAX_SPLINE_POINTS).contains(&count) { + return Err(unsupported(format!("a B-spline with {count} control points"))); + } + if knots.len() != mults.len() { + return Err("B-spline knots and multiplicities differ in number".into()); + } + let total = mults.iter().try_fold(0usize, |a, m| a.checked_add(*m)).ok_or("B-spline knot count")?; + if total != count + degree + 1 { + return Err(format!("B-spline with {total} knots for {count} points of degree {degree}")); + } + let mut v = Vec::with_capacity(total); + for (k, m) in knots.iter().zip(mults) { + v.extend(std::iter::repeat_n(*k, *m)); + } + Ok(v) +} + +fn map_bspline_curve(b: &BSplineCurve) -> R { + let knots = full_knots(&b.knots, &b.multiplicities, b.points.len(), b.degree)?; + Ok(match &b.weights { + None => BCurve::Spline { knots, points: b.points.clone() }, + Some(w) => { + if w.len() != b.points.len() { + return Err("B-spline weights and points differ in number".into()); + } + BCurve::RationalSpline { knots, homogeneous: b.points.iter().zip(w).map(|(p, w)| [p[0] * w, p[1] * w, p[2] * w, *w]).collect() } + } + }) +} + +fn map_bspline_surface(b: &BSplineSurface) -> R { + let nu = b.points.len(); + let nv = b.points.first().map_or(0, Vec::len); + let u_knots = full_knots(&b.u_knots, &b.u_multiplicities, nu, b.u_degree)?; + let v_knots = full_knots(&b.v_knots, &b.v_multiplicities, nv, b.v_degree)?; + if b.points.iter().any(|r| r.len() != nv) { + return Err("ragged B-spline surface".into()); + } + Ok(match &b.weights { + None => BSurface::Spline { u_knots, v_knots, points: b.points.clone() }, + Some(w) => { + if w.len() != nu || w.iter().any(|r| r.len() != nv) { + return Err("B-spline surface weights and points differ in number".into()); + } + let homogeneous = + b.points.iter().zip(w).map(|(row, wr)| row.iter().zip(wr).map(|(p, w)| [p[0] * w, p[1] * w, p[2] * w, *w]).collect()).collect(); + BSurface::RationalSpline { u_knots, v_knots, homogeneous } + } + }) +} + +/// An edge on its schema curve. +#[derive(Debug)] +struct Mapped { + curve: BCurve, + interval: [f64; 2], + /// The schema edge (interval min → max) runs from the STEP edge's start to its end. + with_step: bool, + /// The file's same_sense disagrees with the vertices' order on an open curve. + sense_mismatch: bool, +} + +fn angle_of(a: f64, b: f64) -> f64 { + let t = b.atan2(a); + if t < 0.0 { t + TAU } else { t } +} + +/// `x` reduced to [0, 2π). +fn turn(x: f64) -> f64 { + let r = x.rem_euclid(TAU); + if r >= TAU { 0.0 } else { r } +} + +/// The edge from `ps` to `pe` on `curve`: its schema curve and interval (min → max) and which +/// way it runs. `closed`: the same vertex at both ends; `full`: the ends are one point (a full +/// turn on a periodic curve). +fn map_edge(curve: &Curve, ps: P3, pe: P3, same_sense: bool, closed: bool, full: bool, tol: f64) -> R { + match curve { + Curve::Line { origin, direction, magnitude } => { + if closed { + return Err("a closed edge on a line".into()); + } + let m = *magnitude; + let param = |p: P3| dot(sub(p, *origin), *direction) / m; + let (ts, te) = (param(ps), param(pe)); + if !((te - ts).abs() * m > 1e-12 * (1.0 + ts.abs().max(te.abs()) * m)) { + return Err("a degenerate edge on a line".into()); + } + let with_step = ts < te; + let (lo, hi) = if with_step { (ts, te) } else { (te, ts) }; + let start = crate::geom::add(*origin, scale(*direction, lo * m)); + let end = crate::geom::add(start, scale(*direction, m)); + Ok(Mapped { curve: BCurve::Line { start, end }, interval: [0.0, hi - lo], with_step, sense_mismatch: with_step != same_sense }) + } + Curve::Circle { position, radius } => { + conic(BCurve::Circle { frame: frame(position), radius: *radius }, position, [*radius; 2], ps, pe, same_sense, full) + } + Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => { + let radii = [*semi_axis_1, *semi_axis_2]; + conic(BCurve::Ellipse { frame: frame(position), radii }, position, radii, ps, pe, same_sense, full) + } + Curve::BSpline(b) => open_or_closed(map_bspline_curve(b)?, ps, pe, same_sense, closed, tol), + Curve::Polyline(points) => { + if points.windows(2).any(|w| w.first() == w.get(1)) { + return Err("a polyline with a repeated point".into()); + } + if !(2..=MAX_SPLINE_POINTS * 16).contains(&points.len()) { + return Err(unsupported(format!("a polyline of {} points", points.len()))); + } + open_or_closed(BCurve::Polyline { points: points.clone() }, ps, pe, same_sense, closed, tol) + } + Curve::Hyperbola { position, semi_axis, semi_imag_axis } => { + open_conic(curve, ps, pe, same_sense, closed, |lo, hi| swept::hyperbola_spline(position, *semi_axis, *semi_imag_axis, lo, hi)) + } + Curve::Parabola { position, focal_dist } => { + open_conic(curve, ps, pe, same_sense, closed, |lo, hi| swept::parabola_spline(position, *focal_dist, lo, hi)) + } + Curve::OffsetCurve3d { .. } => Err(unsupported("OFFSET_CURVE_3D")), + Curve::Trimmed { .. } | Curve::SurfaceCurve { .. } => Err(unsupported("nested trimmed or surface curves")), + } +} + +/// A hyperbola or parabola: the vertices' parameters in closed form, the edge running the way +/// they go, as an exact spline over just that interval. +fn open_conic(curve: &Curve, ps: P3, pe: P3, same_sense: bool, closed: bool, spline: impl Fn(f64, f64) -> BCurve) -> R { + if closed { + return Err("a closed edge on an open conic".into()); + } + let (ts, te) = swept::open_conic_params(curve, ps, pe)?; + if !((te - ts).abs() > 1e-12 * (1.0 + ts.abs().max(te.abs()))) { + return Err("a degenerate edge on an open conic".into()); + } + if (ts - te).abs() > 64.0 { + return Err(unsupported("a hyperbola or parabola edge that long")); + } + let with_step = ts < te; + let (lo, hi) = if with_step { (ts, te) } else { (te, ts) }; + Ok(Mapped { curve: spline(lo, hi), interval: [lo, hi], with_step, sense_mismatch: with_step != same_sense }) +} + +/// A circle or ellipse: the vertices' angles, the arc between them in the edge's sense (a full +/// turn when they coincide). +fn conic(curve: BCurve, position: &Placement, radii: [f64; 2], ps: P3, pe: P3, same_sense: bool, full: bool) -> R { + let y = position.y(); + let param = |p: P3| { + let q = sub(p, position.origin); + angle_of(dot(q, position.ref_direction) / radii[0], dot(q, y) / radii[1]) + }; + let (ts, te) = (param(ps), param(pe)); + // Along the curve from `from` to `to`, increasing. + let span = |from: f64, to: f64| if full { TAU } else { turn(to - from) }; + let (lo, d) = if same_sense { (ts, span(ts, te)) } else { (te, span(te, ts)) }; + if !(d > 0.0) { + return Err("a degenerate edge on a conic".into()); + } + Ok(Mapped { curve, interval: [lo, lo + d], with_step: same_sense, sense_mismatch: false }) +} + +/// A spline or polyline: the vertices' parameters by projection. On an open curve the edge runs +/// the way its vertices go; on a closed one (its ends coincide) the edge's sense decides, and a +/// vertex at the seam takes whichever end the sense needs. +fn open_or_closed(curve: BCurve, ps: P3, pe: P3, same_sense: bool, closed: bool, tol: f64) -> R { + let eval = CurveEval::new(&curve).map_err(|e| e.to_string())?; + let Natural::Range(a, b) = curve.natural() else { return Err("a periodic spline".into()) }; + if !(a < b) { + return Err("an empty spline domain".into()); + } + let (pa, pb) = (eval.point(a).ok_or("spline start")?, eval.point(b).ok_or("spline end")?); + let curve_closed = pa.dist(pb) <= tol.max(1e-9 * (1.0 + pa.len())); + if closed { + if !curve_closed { + return Err("a closed edge on an open curve".into()); + } + return Ok(Mapped { curve, interval: [a, b], with_step: true, sense_mismatch: false }); + } + let knots = match &curve { + BCurve::Spline { knots, .. } | BCurve::RationalSpline { knots, .. } => knots.clone(), + BCurve::Polyline { points } => (0..points.len()).map(|i| i as f64).collect(), + _ => Vec::new(), + }; + let ts = project(&eval, a, b, &knots, v3(ps)).ok_or("no parameter for the edge's start")?; + let te = project(&eval, a, b, &knots, v3(pe)).ok_or("no parameter for the edge's end")?; + let eps = 1e-9 * (b - a); + if !curve_closed { + if !((te - ts).abs() > eps) { + return Err("a degenerate edge on a spline".into()); + } + let with_step = ts < te; + let interval = if with_step { [ts, te] } else { [te, ts] }; + return Ok(Mapped { curve, interval, with_step, sense_mismatch: with_step != same_sense }); + } + let (mut from, mut to) = if same_sense { (ts, te) } else { (te, ts) }; + let at_seam = |t: f64| t - a <= eps || b - t <= eps; + if !(from + eps < to) { + if at_seam(from) && b - from <= eps { + from = a; + } + if at_seam(to) && to - a <= eps { + to = b; + } + } + if !(from + eps < to) { + return Err(unsupported("an edge across a closed spline's seam")); + } + Ok(Mapped { curve, interval: [from, to], with_step: same_sense, sense_mismatch: false }) +} + +/// The parameter in [a, b] of the curve's point nearest `p`: the nearest of samples along each +/// knot span, refined by golden-section search between its neighbours. +fn project(c: &CurveEval, a: f64, b: f64, knots: &[f64], p: Vec3) -> Option { + let mut breaks: Vec = knots.iter().copied().filter(|k| *k > a && *k < b).collect(); + breaks.dedup(); + let spans = breaks.len() + 1; + let per = (MAX_SAMPLES / spans).clamp(1, 8); + let mut ts = Vec::with_capacity(spans * per + 1); + let mut lo = a; + for hi in breaks.into_iter().chain(std::iter::once(b)) { + for k in 0..per { + ts.push(lo + (hi - lo) * k as f64 / per as f64); + } + lo = hi; + } + ts.push(b); + if ts.len() > MAX_SAMPLES { + let stride = ts.len().div_ceil(MAX_SAMPLES); + let last = *ts.last()?; + ts = ts.into_iter().step_by(stride).collect(); + ts.push(last); + } + let dist = |t: f64| c.point(t).map_or(f64::INFINITY, |q| q.dist(p)); + let (best, _) = ts.iter().enumerate().map(|(i, t)| (i, dist(*t))).min_by(|x, y| x.1.total_cmp(&y.1))?; + let mut x0 = *ts.get(best.saturating_sub(1))?; + let mut x1 = *ts.get((best + 1).min(ts.len() - 1))?; + let g = 0.5 * (5f64.sqrt() - 1.0); + let (mut c1, mut c2) = (x1 - g * (x1 - x0), x0 + g * (x1 - x0)); + let (mut f1, mut f2) = (dist(c1), dist(c2)); + for _ in 0..200 { + if x1 - x0 <= 1e-15 * (1.0 + x0.abs().max(x1.abs())) { + break; + } + if f1 < f2 { + x1 = c2; + c2 = c1; + f2 = f1; + c1 = x1 - g * (x1 - x0); + f1 = dist(c1); + } else { + x0 = c1; + c1 = c2; + f1 = f2; + c2 = x0 + g * (x1 - x0); + f2 = dist(c2); + } + } + let t = 0.5 * (x0 + x1); + // The ends themselves when they are as near (a vertex at the end of the curve). + let t = [a, b, t].into_iter().min_by(|x, y| dist(*x).total_cmp(&dist(*y)))?; + let near_end = |e: f64| (dist(e) - dist(t)).abs() <= 1e-12 * (1.0 + p.len()); + Some( + if near_end(a) { + a + } else if near_end(b) { + b + } else { + t + } + .clamp(a, b), + ) +} + +#[cfg(test)] +#[path = "topology_tests.rs"] +mod tests; diff --git a/crates/step/src/topology/frames.rs b/crates/step/src/topology/frames.rs new file mode 100644 index 000000000..e9721b917 --- /dev/null +++ b/crates/step/src/topology/frames.rs @@ -0,0 +1,277 @@ +//! Frames turned so that a round face's form covers its face once. A cylinder, cone, sphere or +//! torus face's NURBS form spans the quarters of its frame's quarter grid that its angle interval +//! needs (`brep::form`); a face of less than one turn that does not start on a quarter line and +//! has more than three quarters left spills into a fifth, so its form runs past one turn and +//! covers part of its surface twice, which no kernel takes as a face. A whole turn whose seam is +//! off a quarter line spills the same way: its form is the four quarters from the one it starts +//! in, and the seam's second use lies past their end, off the form. The file's reference +//! direction is the writer's: the face's frame is turned about its own axis (the same surface, +//! its angle parameter measured from further on) so that the face starts on a quarter line, and +//! its form spans the four quarters (or fewer) it covers. +//! +//! A circle edge about the axis of the round faces it bounds is labelled on one of their frames +//! (`solidcraft_geom::brep::form::edge`), so its form and theirs share one quarter grid and its pcurves are +//! straight lines; the faces joined that way (a cylinder and the coaxial fillet beside it) are +//! turned together, by one angle about their common axis, and keep that. They are turned only +//! when one of them spills and one angle puts every one of them within four quarters (a start +//! on a quarter line, or where two of them spill, maybe an end); a face +//! whose frame cannot be turned (a placed revolution, its angle zero at its profile) keeps its +//! group as the file has it. +//! +//! A torus face's tube spills the same way along its tube angle, which STEP counts from the outer +//! equator: its tube start moves to where the face's tube begins, or a turn before where it ends +//! (`solidcraft_geom::brep::form::tube_turned`), the same surface. Its circles round the tube are labelled from +//! the tube start (`solidcraft_geom::brep::form::on_tube`), unless one is about another round face's axis (a +//! pipe's cylinder meeting the tube), which labels it on its own grid: the tube start is then +//! the one of the two that puts the tube's grid on that face's. + +use solidcraft_geom::prelude::*; +use std::f64::consts::TAU; + +use solidcore_record::Vec3; +use solidcore_record::brep::{self, Curve as BCurve}; + +use super::{Builder, LoopB, R}; + +/// A circle edge bounds a face about the circle's own axis: the faces it joins share a grid. +fn about_axis(edge: &BCurve, interval: [f64; 2], frame: &brep::Frame, tol: f64) -> bool { + matches!(edge, BCurve::Circle { .. }) && solidcraft_geom::brep::form::on_frame(edge, interval, frame, tol).is_some() +} + +/// The face's quarters about the axis with its frame turned by `angle` (its box shifted to +/// match), or `None` when its form cannot be measured. +fn quarters_turned(surface: &brep::Surface, [u, v]: [[f64; 2]; 2], angle: f64, tol: f64) -> Option { + solidcraft_geom::brep::form::turn_quarters(surface, [[u[0] - angle, u[1] - angle], v], tol) +} + +/// Union-find root of `i`. +fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i) { + if p == i { + break; + } + let up = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = up; + } + i = p; + } + i +} + +impl Builder<'_, '_> { + /// Measure every round face's box on its label, and turn the frames of the faces whose + /// forms would run past one turn, with the faces their circle edges join them to, so that + /// each starts on a quarter line; a torus face whose tube would, its tube start too. Returns + /// how many faces were turned. + pub(super) fn turn_frames(&mut self) -> R { + let about_axis = self.turn_about_axes()?; + Ok(about_axis + self.turn_tubes()) + } + + /// The torus faces whose forms would run past one turn of the tube start it where their + /// tube begins, or a turn before where it ends (either fits it in four quarters): the one that + /// puts its tube circles on the quarter grid of the round faces they are about the axes of + /// (a pipe's cylinder meeting the tube), so those circles' pcurves are exact on both; where + /// neither does, where it begins. + fn turn_tubes(&mut self) -> usize { + let tol = self.tol; + let frames: Vec> = self.faces.iter().map(|f| solidcraft_geom::brep::form::frame_of(&f.surface)).collect(); + // The round faces each edge bounds. + let mut bounding: Vec> = vec![Vec::new(); self.edges.len()]; + for (fi, f) in self.faces.iter().enumerate() { + for l in &f.loops { + if let LoopB::Edges(es) = l { + for (e, _) in es { + if frames.get(fi).is_some_and(Option::is_some) + && let Some(b) = bounding.get_mut(*e as usize) + && !b.contains(&fi) + { + b.push(fi); + } + } + } + } + } + let mut turned = 0; + for fi in 0..self.faces.len() { + let Some(face) = self.faces.get(fi) else { continue }; + let Some(e) = face.extent else { continue }; + if solidcraft_geom::brep::form::tube_quarters(&face.surface, e, tol).is_none_or(|q| q <= 4) { + continue; + } + // Its tube circles about another round face's axis, with that face's frame. + let mut joined = Vec::new(); + for l in &face.loops { + let LoopB::Edges(es) = l else { continue }; + for (ei, _) in es { + let Some(edge) = self.edges.get(*ei as usize) else { continue }; + for other in bounding.get(*ei as usize).into_iter().flatten().filter(|o| **o != fi) { + if let Some(Some(fr)) = frames.get(*other) { + joined.push((&edge.curve, edge.interval, fr)); + } + } + } + } + let on_grid = |start: f64| { + solidcraft_geom::brep::form::tube_turned(&face.surface, start).is_some_and(|torus| { + joined.iter().all(|(c, iv, fr)| solidcraft_geom::brep::form::tube_on_grid(c, *iv, fr, &torus, tol).is_none_or(|on| on)) + }) + }; + let (begin, end) = (e[1][0], e[1][1] - TAU); + let start = if !on_grid(begin) && on_grid(end) { end } else { begin }; + let Some(surface) = solidcraft_geom::brep::form::tube_turned(&face.surface, start) else { continue }; + if let Some(face) = self.faces.get_mut(fi) { + face.surface = surface; + if let Some(e) = face.extent.as_mut() { + e[1] = [e[1][0] - start, e[1][1] - start]; + } + turned += 1; + } + } + turned + } + + /// Measure the round faces' boxes and turn the groups that spill about their axes. + fn turn_about_axes(&mut self) -> R { + let n = self.faces.len(); + let frames: Vec> = self.faces.iter().map(|f| solidcraft_geom::brep::form::frame_of(&f.surface)).collect(); + for fi in 0..n { + if frames.get(fi).is_some_and(Option::is_some) { + let extent = self.face_extent(fi)?; + if let Some(f) = self.faces.get_mut(fi) { + f.extent = extent; + } + } + } + // Each face's quarters about its axis as the file frames it: a spill is five. + let spills: Vec = + self.faces.iter().map(|f| f.extent.and_then(|e| quarters_turned(&f.surface, e, 0.0, self.tol)).is_some_and(|q| q > 4)).collect(); + if !spills.iter().any(|s| *s) { + return Ok(0); + } + // Round faces a circle edge about both their axes joins. + let mut parent: Vec = (0..n).collect(); + let mut bounding: Vec> = vec![Vec::new(); self.edges.len()]; + for (fi, f) in self.faces.iter().enumerate() { + if frames.get(fi).is_none_or(Option::is_none) { + continue; + } + for l in &f.loops { + if let LoopB::Edges(es) = l { + for (e, _) in es { + if let Some(b) = bounding.get_mut(*e as usize) + && !b.contains(&fi) + { + b.push(fi); + } + } + } + } + } + for (edge, faces) in self.edges.iter().zip(&bounding) { + let joined: Vec = faces + .iter() + .copied() + .filter(|fi| frames.get(*fi).and_then(Option::as_ref).is_some_and(|fr| about_axis(&edge.curve, edge.interval, fr, self.tol))) + .collect(); + for w in joined.windows(2) { + let (a, b) = (root(&mut parent, w[0]), root(&mut parent, w[1])); + if a != b + && let Some(slot) = parent.get_mut(a) + { + *slot = b; + } + } + } + let mut groups: Vec> = Vec::new(); + let mut group_of: Vec> = vec![None; n]; + for fi in 0..n { + if frames.get(fi).is_none_or(Option::is_none) { + continue; + } + let r = root(&mut parent, fi); + let g = match group_of.get(r).copied().flatten() { + Some(g) => g, + None => { + groups.push(Vec::new()); + if let Some(slot) = group_of.get_mut(r) { + *slot = Some(groups.len() - 1); + } + groups.len() - 1 + } + }; + if let Some(members) = groups.get_mut(g) { + members.push(fi); + } + } + let mut turned = 0; + for g in &groups { + if !g.iter().any(|fi| spills.get(*fi).copied().unwrap_or(false)) { + continue; + } + let Some(lead) = g.first().and_then(|fi| frames.get(*fi)).and_then(Option::as_ref) else { continue }; + let axis = Vec3::from(lead.x_axis).cross(Vec3::from(lead.y_axis)); + // Each face's turn about its own axis for a turn `phi` about the lead's: its axis + // along the lead's or against it. + let mut members = Vec::with_capacity(g.len()); + for &fi in g { + let (Some(face), Some(Some(fr))) = (self.faces.get(fi), frames.get(fi)) else { continue }; + let sign = Vec3::from(fr.x_axis).cross(Vec3::from(fr.y_axis)).dot(axis).signum(); + members.push((fi, sign, face.extent)); + } + // A face that cannot be turned, or measured, keeps its group's frames. + if members.len() != g.len() + || members + .iter() + .any(|(fi, _, e)| e.is_none() || self.faces.get(*fi).and_then(|f| solidcraft_geom::brep::form::turned(&f.surface, 0.0)).is_none()) + { + continue; + } + let fits = |phi: f64| { + members.iter().all(|(fi, sign, e)| match (self.faces.get(*fi), e) { + (Some(f), Some(e)) => quarters_turned(&f.surface, *e, sign * phi, self.tol).is_some_and(|q| q <= 4), + _ => false, + }) + }; + // Each face fits for the turns that leave its start no further past a quarter line + // than the room its sweep leaves in four quarters: an arc of turns from the one that + // puts its start on a quarter line to the one that puts its end on one. Where the + // group's arcs meet, the ends of their meeting are among those turns: a spilling + // face's start on its frame's x axis first, then any face's start, then any's end. + let spilling = |fi: &usize| spills.get(*fi).copied().unwrap_or(false); + let starts = + |all: bool| members.iter().filter(move |(fi, _, _)| all || spilling(fi)).filter_map(|(_, sign, e)| e.map(|e| sign * e[0][0])); + let ends = members.iter().filter_map(|(_, sign, e)| e.map(|e| sign * e[0][1])); + let turns: Vec<(usize, f64)> = match starts(false).chain(starts(true)).chain(ends).find(|phi| fits(*phi)) { + Some(phi) => members.iter().map(|(fi, sign, _)| (*fi, sign * phi)).collect(), + // No one turn fits them all: two whole turns whose seams are not a whole number + // of quarters apart (a ball's two halves, each with its seam from a different + // vertex to its pole). Each spilling face is turned on its own to start on a + // quarter line; the circles between them are then on one face's grid only, and + // their pcurves on the other are made as any other trim's. Left spilling, the + // face's form ran past one turn, and a trim across the form's end crossed the + // face (a torn ball on screen). + None => members + .iter() + .filter(|(fi, _, _)| spilling(fi)) + .filter_map(|(fi, _, e)| { + let (f, e) = (self.faces.get(*fi)?, (*e)?); + let fits_alone = |angle: &f64| quarters_turned(&f.surface, e, *angle, self.tol).is_some_and(|q| q <= 4); + [e[0][0], e[0][1]].into_iter().find(fits_alone).map(|angle| (*fi, angle)) + }) + .collect(), + }; + for (fi, angle) in turns { + let Some(face) = self.faces.get_mut(fi) else { continue }; + let Some(surface) = solidcraft_geom::brep::form::turned(&face.surface, angle) else { continue }; + face.surface = surface; + if let Some(e) = face.extent.as_mut() { + e[0] = [e[0][0] - angle, e[0][1] - angle]; + } + turned += 1; + } + } + Ok(turned) + } +} diff --git a/crates/step/src/topology/seams.rs b/crates/step/src/topology/seams.rs new file mode 100644 index 000000000..cd5a4a482 --- /dev/null +++ b/crates/step/src/topology/seams.rs @@ -0,0 +1,1059 @@ +//! Seam edges for faces that wind around a periodic surface without one. STEP lets a face on a +//! cylinder, cone or sphere be bounded by loops that go once around the axis (a band between +//! two circles, a cap bounded by one circle, a cone bounded by its base and a vertex loop at its +//! apex); schema 4 keeps every loop closed in the surface's (u, v), so such a face gets a seam: +//! a ruling line on a cylinder or cone, a meridian arc on a sphere, from a vertex of one loop to +//! the other loop (split there when it has no vertex at that angle) or to the pole the face +//! covers; on a surface of revolution, its profile turned to the vertex's angle. The loops merge into one: the first, the seam out, the second (or nothing at a pole), +//! the seam back. A face on a B-spline surface that closes on itself around u (its first and +//! last control columns the same) gets a seam the same way, along the surface's own boundary +//! column (u at the start of its knots), the loops split there where they have no vertex on it; +//! the period is the width of its knots. A torus face winding without a seam, and a spline +//! closed in v or both ways, are refused for now. +//! +//! A face bounded by a slit alone (a loop out along edges and straight back, of no (u, v) area) +//! on a closed surface is all of that surface less a cut of none: its slit is made its seams +//! ([`Builder::complete_slits`]), so the loop bounds the surface's whole (u, v) domain. + +use solidcraft_geom::prelude::*; +use std::f64::consts::{PI, TAU}; + +use solidcore_record::Vec3; +use solidcore_record::brep::{Curve as BCurve, Frame, Surface as BSurface, Vertex}; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; + +use super::{Builder, EdgeB, LoopB, R, index, unsupported}; + +/// Samples per edge when following a loop around the axis. +const SAMPLES: usize = 16; +/// Edges split to place seams, per solid. +const MAX_SPLITS: usize = 10_000; + +fn arr(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +fn wrap(x: f64) -> f64 { + wrap_by(x, TAU) +} + +/// `x` wrapped into (−period/2, period/2]. +fn wrap_by(x: f64, period: f64) -> f64 { + x - (x / period).round() * period +} + +/// The path a slit runs out along: a loop that runs out along a chain of edges and straight back +/// along it, each edge used once each way, started at one of its two turns; `None` for any +/// other loop. +pub(super) fn slit_path(es: &[(u32, bool)]) -> Option> { + let n = es.len(); + if n < 2 || !n.is_multiple_of(2) || !super::seam_only(es) { + return None; + } + // A turn: a use followed by its edge the other way. + let k = (0..n).find(|&k| matches!((es.get((k + n - 1) % n), es.get(k)), (Some(a), Some(b)) if a.0 == b.0))?; + let ring: Vec<(u32, bool)> = es.iter().skip(k).chain(es.iter().take(k)).copied().collect(); + let (out, back) = ring.split_at(n / 2); + back.iter().rev().zip(out).all(|(b, o)| b.0 == o.0 && b.1 != o.1).then(|| out.to_vec()) +} + +/// The axis frame of a surface of revolution: origin, unit axis, and the pole points at the +/// ends of its v range that have one (min v, max v). +struct Axis { + origin: Vec3, + z: Vec3, + kind: Kind, + poles: [Option; 2], + /// The period around (2π, or a closed spline's knot width). + period: f64, +} + +#[derive(Clone, PartialEq)] +enum Kind { + Ruled, + Sphere(f64), + /// A placed revolution with u the angle: its profile. + Revolved(BCurve), + /// A B-spline surface closed on itself around u: its boundary column at u = `u0` (the start + /// of its knots), a curve in v, along which every seam runs. + Iso { + u0: f64, + column: BCurve, + }, +} + +fn axis(s: &BSurface) -> Option { + let frame = |f: &Frame| { + let (o, x, y) = (Vec3::from(f.origin), Vec3::from(f.x_axis), Vec3::from(f.y_axis)); + (o, x.cross(y)) + }; + match s { + BSurface::Cylinder { frame: f, .. } => { + let (origin, z) = frame(f); + Some(Axis { origin, z, kind: Kind::Ruled, poles: [None, None], period: TAU }) + } + BSurface::Cone { frame: f, radius_at_origin, half_angle } => { + let (origin, z) = frame(f); + let apex = origin + z * (-radius_at_origin / half_angle.tan()); + let poles = if *half_angle > 0.0 { [Some(apex), None] } else { [None, Some(apex)] }; + Some(Axis { origin, z, kind: Kind::Ruled, poles, period: TAU }) + } + BSurface::Sphere { frame: f, radius } => { + let (origin, z) = frame(f); + Some(Axis { origin, z, kind: Kind::Sphere(*radius), poles: [Some(origin - z * *radius), Some(origin + z * *radius)], period: TAU }) + } + BSurface::PlacedRevolution { profile, origin, axis, matrix, forward: false } if *matrix == IDENTITY => { + let (origin, z) = (Vec3::from(*origin), Vec3::from(*axis)); + let c = CurveEval::new(profile).ok()?; + let solidcore_record::brep::Natural::Range(a, b) = profile.natural() else { return None }; + // A profile end on the axis is a pole. + let pole = |t: f64| { + c.point(t).filter(|p| { + let d = *p - origin; + (d - z * d.dot(z)).len() <= 1e-9 * (1.0 + d.len()) + }) + }; + Some(Axis { origin, z, kind: Kind::Revolved((**profile).clone()), poles: [pole(a), pole(b)], period: TAU }) + } + _ => None, + } +} + +/// The seam frame of a B-spline surface closed around u only ([`Kind::Iso`]): its column at the +/// start of its u knots, and the points its v ends collapse to (a pole), if they do. +fn spline_axis(s: &BSurface, eval: &SurfaceEval) -> Option { + let dom = eval.domain(); + let (Some(period), None) = (dom.period[0], dom.period[1]) else { return None }; + let ((u0, u1), (v0, v1)) = (dom.range[0]?, dom.range[1]?); + let column = match s { + BSurface::Spline { v_knots, points, .. } => BCurve::Spline { knots: v_knots.clone(), points: points.first()?.clone() }, + BSurface::RationalSpline { v_knots, homogeneous, .. } => { + BCurve::RationalSpline { knots: v_knots.clone(), homogeneous: homogeneous.first()?.clone() } + } + _ => return None, + }; + // A v end is a pole where the surface's points across u there are one point. + let pole = |v: f64| { + let p = eval.point([u0, v])?; + let across = (1..8).filter_map(|k| eval.point([u0 + (u1 - u0) * k as f64 / 8.0, v])).map(|q| q.dist(p)).fold(0.0, f64::max); + (across <= 1e-9 * (1.0 + p.len())).then_some(p) + }; + Some(Axis { origin: Vec3::new(0.0, 0.0, 0.0), z: Vec3::new(0.0, 0.0, 1.0), kind: Kind::Iso { u0, column }, poles: [pole(v0), pole(v1)], period }) +} + +const IDENTITY: [[f64; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + +/// `p` turned by `angle` about the axis through `o` along unit `k` (right-handed). +fn turned(p: Vec3, o: Vec3, k: Vec3, angle: f64) -> Vec3 { + let (s, c) = angle.sin_cos(); + let x = p - o; + o + x * c + k.cross(x) * s + k * (k.dot(x) * (1.0 - c)) +} + +/// A revolution's profile turned by `angle`: the meridian there, with the profile's parameter. +fn meridian(profile: &BCurve, o: Vec3, k: Vec3, angle: f64) -> R { + let turn = |h: &[f64; 4]| { + let w = h[3]; + let p = turned(Vec3::new(h[0] / w, h[1] / w, h[2] / w), o, k, angle); + [p.x * w, p.y * w, p.z * w, w] + }; + Ok(match profile { + BCurve::Spline { knots, points } => { + BCurve::Spline { knots: knots.clone(), points: points.iter().map(|p| arr(turned(Vec3::from(*p), o, k, angle))).collect() } + } + BCurve::RationalSpline { knots, homogeneous } => { + BCurve::RationalSpline { knots: knots.clone(), homogeneous: homogeneous.iter().map(turn).collect() } + } + BCurve::Line { start, end } => { + BCurve::Line { start: arr(turned(Vec3::from(*start), o, k, angle)), end: arr(turned(Vec3::from(*end), o, k, angle)) } + } + _ => return Err(unsupported("a revolution of this profile")), + }) +} + +/// A B-spline surface closed around u (its first and last control columns the same, `period` +/// its knot width) started at `s` instead, exactly: `s` inserted to full multiplicity, then the +/// piece from `s` to the end followed by the piece from the start to `s`, moved on by a period. +/// The same points at parameters a period apart before `s`; `None` for another surface or an `s` +/// outside the open domain. +fn restarted(surface: &BSurface, s: f64, period: f64) -> Option { + use solidcraft_geom::bspline::{HPoint, segment}; + let (u_knots, v_knots, rows): (&Vec, &Vec, Vec>) = match surface { + BSurface::Spline { u_knots, v_knots, points } => { + (u_knots, v_knots, points.iter().map(|r| r.iter().map(|p| HPoint { x: p[0], y: p[1], z: p[2], w: 1.0 }).collect()).collect()) + } + BSurface::RationalSpline { u_knots, v_knots, homogeneous } => { + (u_knots, v_knots, homogeneous.iter().map(|r| r.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect()).collect()) + } + _ => return None, + }; + let n = rows.len(); + let p = u_knots.len().checked_sub(n + 1)?; + let (u0, u1) = (*u_knots.get(p)?, *u_knots.get(n)?); + if !(u0 < s && s < u1) || !((u1 - u0 - period).abs() <= 1e-9 * period.max(1.0)) { + return None; + } + // Each v column of control points across u is a curve along u. + let columns = rows.first()?.len(); + let column = |j: usize| rows.iter().map(|r| r.get(j).copied()).collect::>>(); + let mut knots: Option> = None; + let mut out: Vec> = Vec::with_capacity(columns); + for j in 0..columns { + let c = column(j)?; + let (ka, a) = segment(p, u_knots, &c, s, u1).ok()?; + let (kb, b) = segment(p, u_knots, &c, u0, s).ok()?; + // The piece after the seam starts where the one before it ends (the closed surface's + // last column is its first): joined there with multiplicity p. + let mut k = ka.get(..ka.len() - 1)?.to_vec(); + k.extend(kb.get(p + 1..)?.iter().map(|x| x + period)); + let mut pts = a; + pts.extend(b.get(1..)?.iter().copied()); + if k.len() != pts.len() + p + 1 || knots.as_ref().is_some_and(|x| *x != k) { + return None; + } + knots = Some(k); + out.push(pts); + } + let u_knots = knots?; + // Back to rows along u. + let rows: Vec> = + (0..out.first()?.len()).map(|i| out.iter().map(|c| c.get(i).copied()).collect::>>()).collect::>()?; + Some(match surface { + BSurface::Spline { .. } => BSurface::Spline { + u_knots, + v_knots: v_knots.clone(), + points: rows.iter().map(|r| r.iter().map(|h| [h.x / h.w, h.y / h.w, h.z / h.w]).collect()).collect(), + }, + _ => BSurface::RationalSpline { + u_knots, + v_knots: v_knots.clone(), + homogeneous: rows.iter().map(|r| r.iter().map(|h| [h.x, h.y, h.z, h.w]).collect()).collect(), + }, + }) +} + +impl Builder<'_, '_> { + /// Start every B-spline surface closed around u that a face lies across the start of, without + /// winding round it, in the middle of the widest stretch of u the face leaves free: the face's + /// pcurves then run inside the surface's knots, as a kernel's trims have to (one crossing the + /// start had its pcurve clamped there, mm off its edge). Exact ([`restarted`]). Returns how + /// many surfaces were started anew. + pub(super) fn start_splines_clear_of_faces(&mut self) -> R { + let mut turned = 0; + for fi in 0..self.faces.len() { + let Some(face) = self.faces.get(fi) else { continue }; + if !matches!(face.surface, BSurface::Spline { .. } | BSurface::RationalSpline { .. }) { + continue; + } + let eval = SurfaceEval::new(&face.surface).map_err(|e| e.to_string())?; + let dom = eval.domain(); + let (Some(period), None, Some((u0, _))) = (dom.period[0], dom.period[1], dom.range[0]) else { continue }; + // How far along u each loop of the face reaches, followed round from its first point + // (unwrapped across the start); a face winding round is the seams' to handle. The + // widest loop bounds the face. + let mut widest: Option<(f64, f64)> = None; + let mut winds = false; + for l in &face.loops { + let LoopB::Edges(es) = l else { continue }; + winds |= self.winding(&eval, es, [Some(period), None])?[0] != 0; + let mut last: Option = None; + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for &(e, _) in es { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let [a, b] = edge.interval; + for k in 0..=SAMPLES { + let t = a + (b - a) * k as f64 / SAMPLES as f64; + let Some(q) = c.point(t).and_then(|p| eval.project(p, None, f64::INFINITY)) else { continue }; + let u = last.map_or(q[0], |x| x + wrap_by(q[0] - x, period)); + (lo, hi) = (lo.min(u), hi.max(u)); + last = Some(u); + } + } + if hi - lo > widest.map_or(f64::NEG_INFINITY, |(a, b)| b - a) { + widest = Some((lo, hi)); + } + } + let Some((lo, hi)) = widest else { continue }; + // Across the start: a whole number of periods from it lies inside the reach, clear of + // its ends (a face that only meets the start there runs inside the knots already). + let start = u0 + ((hi - u0) / period).floor() * period; + let clear = 1e-9 * period; + let crossing = hi - start > clear && start - lo > clear; + if winds || !crossing || !(hi - lo < period) { + continue; + } + // The middle of the stretch the face leaves free. + let free = hi + 0.5 * (period - (hi - lo)); + let at = u0 + (free - u0).rem_euclid(period); + let Some(surface) = restarted(&face.surface, at, period) else { continue }; + if let Some(f) = self.faces.get_mut(fi) { + f.surface = surface; + f.extent = None; + } + turned += 1; + } + Ok(turned) + } + + /// Give every face that winds around its surface without a seam one. Returns how many + /// seams were added. + pub(super) fn add_seams(&mut self) -> R { + let mut added = 0; + let mut splits = 0; + for fi in 0..self.faces.len() { + let Some(face) = self.faces.get(fi) else { continue }; + let surface = face.surface.clone(); + let natural = super::natural_periods(&surface); + let eval = SurfaceEval::new(&surface).map_err(|e| e.to_string())?; + // Periodic as the surface is, or as a spline closed on itself is (its knot width). + let periods = [0, 1].map(|d| if natural[d] { Some(TAU) } else { eval.domain().period[d] }); + if periods.iter().all(Option::is_none) { + continue; + } + let found = axis(&surface).or_else(|| spline_axis(&surface, &eval)); + let mut up = Vec::new(); + let mut down = Vec::new(); + for (li, l) in face.loops.iter().enumerate() { + let LoopB::Edges(es) = l else { continue }; + let w = self.winding(&eval, es, periods)?; + if w[1] != 0 || w[0].abs() > 1 { + return Err(format!("face #{}: {}", face.step, unsupported("a loop winding around a surface more than once or in v"))); + } + // A loop through a pole turns once round the axis and closes there, where every + // angle is one point: a cone's base circle with its seam out to the apex and + // back. It has its seam; another one doubled it, a sliver the face crossed. + if w[0] != 0 && found.as_ref().is_some_and(|ax| self.through_pole(es, ax)) { + continue; + } + match w[0] { + 1 => up.push(li), + -1 => down.push(li), + _ => {} + } + } + if up.is_empty() && down.is_empty() { + continue; + } + let step = face.step; + let Some(ax) = found else { + return Err(format!("face #{step}: {}", unsupported("a face winding around a torus or a spline closed in v without a seam edge"))); + }; + match (up.as_slice(), down.as_slice()) { + // The face lies to the left of its loops in (u, v): above a loop running +u. + ([l], []) => self.pole_seam(fi, *l, &ax, ax.poles[1], &eval)?, + ([], [l]) => self.pole_seam(fi, *l, &ax, ax.poles[0], &eval)?, + ([a], [b]) => self.band_seam(fi, *a, *b, &ax, &eval, &mut splits)?, + _ => return Err(format!("face #{step}: {}", unsupported("a face with several loops around its axis"))), + } + added += 1; + } + Ok(added) + } + + /// Split every edge that passes through a pole of a face it bounds (a sphere's, a revolved + /// face's on its axis) inside its interval: a great circle from the equator over the pole to a + /// vertex just past it. On the face's parameters the pole is a line, along which the edge's + /// pcurve would have to jump half a turn; split there, the jump is at a vertex on the pole, + /// where a loop may run along the pole's line. Returns how many edges were split. + pub(super) fn split_at_poles(&mut self) -> R { + let mut splits = 0; + for fi in 0..self.faces.len() { + let Some(face) = self.faces.get(fi) else { continue }; + let Some(ax) = axis(&face.surface) else { continue }; + let poles: Vec = ax.poles.iter().flatten().copied().collect(); + if poles.is_empty() { + continue; + } + let mut edges: Vec = + face.loops.iter().filter_map(|l| if let LoopB::Edges(es) = l { Some(es) } else { None }).flatten().map(|u| u.0).collect(); + edges.sort_unstable(); + edges.dedup(); + for e in edges { + for pole in &poles { + let Some(t) = self.through_at(e, *pole)? else { continue }; + splits += 1; + if splits > MAX_SPLITS { + return Err(format!("more than {MAX_SPLITS} edges split at poles")); + } + let v = self.split_edge(e, t)?; + // The new vertex is the pole, as the face's parameters have it. + if let Some(x) = self.vertices.get_mut(v as usize) { + let gap = Vec3::from(x.point).dist(*pole); + x.point = arr(*pole); + x.tolerance = x.tolerance.max(1.5 * gap); + } + } + } + } + Ok(splits) + } + + /// Where edge `e` passes through `pole` inside its interval (within the tolerance, away from + /// its ends), if it does: its nearest point to the pole, refined by golden-section search. + fn through_at(&self, e: u32, pole: Vec3) -> R> { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let [lo, hi] = edge.interval; + let reach = self.tol.max(edge.tolerance); + let d = |t: f64| c.point(t).map_or(f64::INFINITY, |p| p.dist(pole)); + let step = (hi - lo) / SAMPLES as f64; + let k = (0..=SAMPLES).min_by(|&i, &j| d(lo + step * i as f64).total_cmp(&d(lo + step * j as f64))).unwrap_or(0); + let (mut a, mut b) = (lo + step * k.saturating_sub(1) as f64, (lo + step * (k + 1) as f64).min(hi)); + let g = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..100 { + let (x, y) = (b - g * (b - a), a + g * (b - a)); + if d(x) < d(y) { + b = y; + } else { + a = x; + } + } + let t = 0.5 * (a + b); + let ends = [lo, hi].map(|s| c.point(s).map_or(0.0, |p| p.dist(pole))); + Ok((d(t) <= reach && ends.iter().all(|x| *x > reach) && t > lo && t < hi).then_some(t)) + } + + /// Turns (in u, in v) a loop makes around a periodic surface. + fn winding(&self, eval: &SurfaceEval, es: &[(u32, bool)], periods: [Option; 2]) -> R<[i64; 2]> { + let mut last: Option<[f64; 2]> = None; + let mut total = [0.0; 2]; + for &(e, forward) in es { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let [lo, hi] = edge.interval; + for k in 0..=SAMPLES { + let s = k as f64 / SAMPLES as f64; + let t = if forward { lo + (hi - lo) * s } else { hi - (hi - lo) * s }; + let p = c.point(t).ok_or("edge point")?; + let Some(q) = eval.project(p, last, f64::INFINITY) else { continue }; + if let Some(l) = last { + for d in 0..2 { + if let Some(p) = periods[d] { + total[d] += wrap_by(q[d] - l[d], p) / p; + } + } + } + last = Some(q); + } + } + Ok(total.map(|x| x.round() as i64)) + } + + /// A vertex of the loop is on one of the axis's poles (within its tolerance). + fn through_pole(&self, es: &[(u32, bool)], ax: &Axis) -> bool { + es.iter().any(|&u| { + self.start(u) + .ok() + .and_then(|v| self.vertices.get(v as usize)) + .is_some_and(|x| ax.poles.iter().flatten().any(|p| Vec3::from(x.point).dist(*p) <= self.tol.max(x.tolerance))) + }) + } + + /// The vertex where use `k` of a loop starts. + fn start(&self, (e, forward): (u32, bool)) -> R { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + Ok(if forward { edge.vertices[0] } else { edge.vertices[1] }) + } + + fn vpoint(&self, v: u32) -> R { + self.vertices.get(v as usize).map(|v| Vec3::from(v.point)).ok_or_else(|| "vertex reference".to_string()) + } + + /// Edge loop `li` of face `fi`, rotated to start at its use `k`. + fn rotated(&self, fi: usize, li: usize, k: usize) -> R> { + let Some(LoopB::Edges(es)) = self.faces.get(fi).and_then(|f| f.loops.get(li)) else { return Err("loop reference".into()) }; + Ok(es.iter().skip(k).chain(es.iter().take(k)).copied().collect()) + } + + /// A seam edge from vertex `a` to vertex `b` on the surface: a ruling line, a meridian arc + /// of a sphere, or a revolution's profile turned to their angle. Returns the edge and + /// whether it runs from `a` to `b`. + fn seam_edge(&mut self, a: u32, b: u32, ax: &Axis, eval: &SurfaceEval, check: bool) -> R<(u32, bool)> { + let (pa, pb) = (self.vpoint(a)?, self.vpoint(b)?); + if pa.dist(pb) <= self.tol { + return Err("a seam of no length".into()); + } + let (curve, interval, along) = match &ax.kind { + Kind::Ruled => (BCurve::Line { start: arr(pa), end: arr(pb) }, [0.0, 1.0], true), + Kind::Sphere(r) => { + // The sphere's own meridian through the end further from the axis: angle 0 on the + // equator, π/2 at the upper pole, so its angle is the surface's latitude and its + // quarters the surface's. + let (da, db) = (pa - ax.origin, pb - ax.origin); + let (ra, rb) = (da - ax.z * da.dot(ax.z), db - ax.z * db.dot(ax.z)); + let x = if ra.len() >= rb.len() { ra } else { rb }.normalized().ok_or("a seam along the sphere's axis")?; + let latitude = |d: Vec3| d.dot(ax.z).atan2(d.dot(x)); + let (ta, tb) = (latitude(da), latitude(db)); + if !(ta.abs() <= 0.5 * PI + 1e-9 && tb.abs() <= 0.5 * PI + 1e-9) { + return Err(unsupported("a seam between loops at opposite angles")); + } + let along = ta < tb; + ( + BCurve::Circle { frame: Frame { origin: arr(ax.origin), x_axis: arr(x), y_axis: arr(ax.z) }, radius: *r }, + if along { [ta, tb] } else { [tb, ta] }, + along, + ) + } + Kind::Iso { column, .. } => { + // Each vertex's v on the surface (a pole's from its end of the v range). + let Some((v0, v1)) = eval.domain().range[1] else { return Err("a closed spline with no v range".into()) }; + let v_of = |p: Vec3| -> R { + Ok(match ax.poles { + [Some(q), _] if q.dist(p) <= self.tol => v0, + [_, Some(q)] if q.dist(p) <= self.tol => v1, + _ => eval.project(p, None, f64::INFINITY).ok_or("a seam vertex off its surface")?[1], + }) + }; + let (va, vb) = (v_of(pa)?, v_of(pb)?); + let along = va < vb; + (column.clone(), if along { [va, vb] } else { [vb, va] }, along) + } + Kind::Revolved(profile) => { + // a's angle; each vertex's profile parameter (a pole's from the profile's end). + let qa = eval.project(pa, None, f64::INFINITY).ok_or("a seam vertex off its surface")?; + let qb = eval.project(pb, Some(qa), f64::INFINITY).ok_or("a seam vertex off its surface")?; + let solidcore_record::brep::Natural::Range(lo, hi) = profile.natural() else { return Err("a periodic profile".into()) }; + let vb = match ax.poles { + [Some(p), _] if p.dist(pb) <= self.tol => lo, + [_, Some(p)] if p.dist(pb) <= self.tol => hi, + _ => qb[1], + }; + let curve = meridian(profile, ax.origin, ax.z, qa[0])?; + let along = qa[1] < vb; + (curve, if along { [qa[1], vb] } else { [vb, qa[1]] }, along) + } + }; + if !(interval[0] < interval[1]) { + return Err("a degenerate seam".into()); + } + // On the surface: its middle within the tolerance (a ruling, a meridian). + let c = CurveEval::new(&curve).map_err(|m| m.to_string())?; + if check { + let m = c.point(0.5 * (interval[0] + interval[1])).ok_or("seam point")?; + let off = eval.project(m, None, f64::INFINITY).and_then(|q| eval.point(q)).map_or(f64::INFINITY, |s| s.dist(m)); + if !(off <= self.tol) { + return Err(unsupported("a seam off its surface: loops with no vertices at one angle")); + } + } + let i = self.new_edge(curve, interval, if along { [a, b] } else { [b, a] })?; + Ok((i, along)) + } + + /// A new edge on `curve` over `interval` between `vertices`, each vertex's tolerance raised to + /// cover its gap to the curve's end. + fn new_edge(&mut self, curve: BCurve, interval: [f64; 2], vertices: [u32; 2]) -> R { + let c = CurveEval::new(&curve).map_err(|m| m.to_string())?; + for (t, v) in interval.into_iter().zip(vertices) { + let gap = c.point(t).ok_or("seam point")?.dist(self.vpoint(v)?); + if let Some(x) = self.vertices.get_mut(v as usize) { + x.tolerance = x.tolerance.max(1.5 * gap); + } + } + let i = index(self.edges.len())?; + self.edges.push(EdgeB { curve, interval, vertices, tolerance: self.tol, form: None }); + Ok(i) + } + + /// Complete every face bounded by a slit alone into the whole of its surface. A slit is a + /// loop that runs out along a chain of edges and straight back ([`slit_path`]): it encloses + /// no (u, v) area, yet on a closed surface it bounds all of it less a cut of none (a ball + /// whose one face is bounded by part of a meridian, out and back). Schema 4 keeps that face + /// as the surface's whole (u, v) domain, closed by its seams, so the slit is made one: on a + /// surface of revolution closed at both poles (a sphere, a revolution whose profile ends on + /// its axis, a spline closed round u that collapses at both v ends), the meridian the slit + /// lies along is run on from its ends to the poles, out and back; on a torus, the circle the + /// slit lies along (round the tube or round the axis) is closed and the other circle through + /// its start is the second seam. Returns how many faces were completed. + pub(super) fn complete_slits(&mut self) -> R { + let mut completed = 0; + for fi in 0..self.faces.len() { + let Some(face) = self.faces.get(fi) else { continue }; + let [LoopB::Edges(es)] = face.loops.as_slice() else { continue }; + let Some(path) = slit_path(es) else { continue }; + let (step, surface) = (face.step, face.surface.clone()); + let (merged, seated) = match &surface { + BSurface::Torus { frame, major_radius, .. } => (self.torus_slit(&path, frame, *major_radius)?, None), + _ => match self.closed_at_poles(&path, &surface)? { + // An open surface: the slit bounds nothing, and is refused for that later. + None => continue, + Some(Some(m)) => (Some(m), None), + // A sphere's frame is the writer's choice (any right-handed frame about its + // centre is the same surface, its natural normal outward): one whose + // meridians miss the slit has its pole put at the slit's start instead, its x + // axis through the slit's middle. + Some(None) => match &surface { + BSurface::Sphere { frame, radius } => match self.seated(&path, frame, *radius)? { + Some(s) => (self.closed_at_poles(&path, &s)?.flatten(), Some(s)), + None => (None, None), + }, + _ => (None, None), + }, + }, + }; + let merged = merged.ok_or_else(|| format!("face #{step}: {}", unsupported("a face bounded by a slit off its surface's seam lines")))?; + let Some(face) = self.faces.get_mut(fi) else { continue }; + if let Some(s) = seated { + face.surface = s; + face.extent = None; + } + if let Some(LoopB::Edges(es)) = face.loops.first_mut() { + *es = merged; + } + completed += 1; + } + Ok(completed) + } + + /// The slit made the meridian seam of `surface` when it is a surface of revolution closed + /// at both poles ([`Builder::meridian_slit`]); `None` for any other surface. + fn closed_at_poles(&mut self, path: &[(u32, bool)], surface: &BSurface) -> R>>> { + let eval = SurfaceEval::new(surface).map_err(|e| e.to_string())?; + match axis(surface).or_else(|| spline_axis(surface, &eval)) { + Some(ax) if ax.poles.iter().all(Option::is_some) => Ok(Some(self.meridian_slit(path, &ax, &eval)?)), + _ => Ok(None), + } + } + + /// The sphere about `frame`'s centre with its upper pole at the slit's start and its x axis + /// through the middle of the slit's middle edge; `None` where those coincide. + fn seated(&self, path: &[(u32, bool)], frame: &Frame, radius: f64) -> R> { + let centre = Vec3::from(frame.origin); + let first = *path.first().ok_or("empty slit")?; + let Some(z) = (self.vpoint(self.start(first)?)? - centre).normalized() else { return Ok(None) }; + let &(e, _) = path.get(path.len() / 2).ok_or("empty slit")?; + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let middle = + CurveEval::new(&edge.curve).map_err(|m| m.to_string())?.point(0.5 * (edge.interval[0] + edge.interval[1])).ok_or("edge point")?; + let off = middle - centre; + let Some(x) = (off - z * off.dot(z)).normalized() else { return Ok(None) }; + Ok(Some(BSurface::Sphere { frame: Frame { origin: frame.origin, x_axis: arr(x), y_axis: arr(z.cross(x)) }, radius })) + } + + /// The vertex use `u` ends at. + fn end(&self, (e, forward): (u32, bool)) -> R { + self.start((e, !forward)) + } + + /// Vertex `v` is at `p`, within its tolerance. + fn at(&self, v: u32, p: Vec3) -> R { + let x = self.vertices.get(v as usize).ok_or("vertex reference")?; + Ok(Vec3::from(x.point).dist(p) <= self.tol.max(x.tolerance)) + } + + /// Every point of the path's edges lies on one meridian of the surface (the spline's + /// boundary column for [`Kind::Iso`]), the poles apart. + fn on_meridian(&self, path: &[(u32, bool)], ax: &Axis, eval: &SurfaceEval) -> R { + let mut u_ref = match ax.kind { + Kind::Iso { u0, .. } => Some(u0), + _ => None, + }; + for &(e, _) in path { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let ([lo, hi], reach) = (edge.interval, self.tol.max(edge.tolerance)); + for k in 0..=SAMPLES { + let p = c.point(lo + (hi - lo) * k as f64 / SAMPLES as f64).ok_or("edge point")?; + if ax.poles.iter().flatten().any(|q| q.dist(p) <= reach) { + continue; + } + let Some(q) = eval.project(p, None, f64::INFINITY) else { return Ok(false) }; + let u = *u_ref.get_or_insert(q[0]); + if !eval.point([u, q[1]]).is_some_and(|m| m.dist(p) <= reach) { + return Ok(false); + } + } + } + Ok(u_ref.is_some()) + } + + /// A slit along a meridian of a surface closed at both poles, run on to them: the meridian + /// from the lower pole to the upper (the slit's path, with a seam edge from each end of it + /// that is not at its pole), then back. `None` when the slit is off every meridian. + fn meridian_slit(&mut self, path: &[(u32, bool)], ax: &Axis, eval: &SurfaceEval) -> R>> { + let (Some(south), Some(north)) = (ax.poles[0], ax.poles[1]) else { return Ok(None) }; + if !self.on_meridian(path, ax, eval)? { + return Ok(None); + } + // How far up the meridian a vertex is: a pole's from its end, else its v. + let height = |s: &Self, v: u32| -> R { + Ok(if s.at(v, south)? { + f64::NEG_INFINITY + } else if s.at(v, north)? { + f64::INFINITY + } else { + eval.project(s.vpoint(v)?, None, f64::INFINITY).ok_or("a slit vertex off its surface")?[1] + }) + }; + let (first, last) = (*path.first().ok_or("empty slit")?, *path.last().ok_or("empty slit")?); + let (ha, hb) = (height(self, self.start(first)?)?, height(self, self.end(last)?)?); + if !(ha != hb) { + return Ok(None); + } + // Up the meridian. + let mut up = path.to_vec(); + if ha > hb { + super::reverse(&mut up); + } + let (a, b) = (self.start(*up.first().ok_or("empty slit")?)?, self.end(*up.last().ok_or("empty slit")?)?); + let pole_vertex = |s: &mut Self, p: Vec3| -> R { + let v = index(s.vertices.len())?; + s.vertices.push(Vertex { point: arr(p), tolerance: s.tol }); + Ok(v) + }; + let mut merged = Vec::with_capacity(2 * up.len() + 4); + if !self.at(a, south)? { + let s = pole_vertex(self, south)?; + let (seam, along) = self.seam_edge(a, s, ax, eval, true)?; + merged.push((seam, !along)); + } + merged.extend(up); + if !self.at(b, north)? { + let n = pole_vertex(self, north)?; + merged.push(self.seam_edge(b, n, ax, eval, true)?); + } + let mut back = merged.clone(); + super::reverse(&mut back); + merged.extend(back); + Ok(Some(merged)) + } + + /// A slit along a circle of a torus (round its tube, or round its axis) made the torus's two + /// seams: that circle closed from the slit's end round to its start, the way the slit runs, + /// and the other circle through the start; the loop runs round the first, the second, the + /// first back and the second back. `None` when the slit is off both circles. + fn torus_slit(&mut self, path: &[(u32, bool)], frame: &Frame, major: f64) -> R>> { + let (o, z) = (Vec3::from(frame.origin), Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis))); + let (first, last) = (*path.first().ok_or("empty slit")?, *path.last().ok_or("empty slit")?); + let (a, b) = (self.start(first)?, self.end(last)?); + let (pa, pb) = (self.vpoint(a)?, self.vpoint(b)?); + let off = pa - o; + let h = off.dot(z); + let Some(radial) = (off - z * h).normalized() else { return Ok(None) }; + // The circles through the slit's start, as centre and unit normal: round the tube in the + // plane through the axis, and round the axis at the start's height. + let tube = (o + radial * major, radial.cross(z)); + let ring = (o + z * h, z); + let along = |s: &Self, (c, n): (Vec3, Vec3)| -> R { + let r = (pa - c).len(); + for &(e, _) in path { + let edge = s.edges.get(e as usize).ok_or("edge reference")?; + let curve = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let ([lo, hi], reach) = (edge.interval, s.tol.max(edge.tolerance)); + for k in 0..=SAMPLES { + let d = curve.point(lo + (hi - lo) * k as f64 / SAMPLES as f64).ok_or("edge point")? - c; + if !(d.dot(n).abs() <= reach && (d.len() - r).abs() <= reach) { + return Ok(false); + } + } + } + Ok(true) + }; + let (circle, other) = if along(self, tube)? { + (tube, ring) + } else if along(self, ring)? { + (ring, tube) + } else { + return Ok(None); + }; + let mut round = path.to_vec(); + if a != b { + // On from the slit's end the way it arrives there, from a point of its last edge + // just before. + let (c, n) = circle; + let edge = self.edges.get(last.0 as usize).ok_or("edge reference")?; + let [lo, hi] = edge.interval; + let t = if last.1 { hi - (hi - lo) / SAMPLES as f64 } else { lo + (hi - lo) / SAMPLES as f64 }; + let before = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?.point(t).ok_or("edge point")?; + let Some(x) = (pb - c).normalized() else { return Ok(None) }; + let y = n.cross(x); + let y = if (pb - before).dot(y) >= 0.0 { y } else { -y }; + let d = pa - c; + let theta = d.dot(y).atan2(d.dot(x)).rem_euclid(TAU); + let radius = (pb - c).len(); + if !(theta * radius > self.tol) { + return Ok(None); + } + let rest = BCurve::Circle { frame: Frame { origin: arr(c), x_axis: arr(x), y_axis: arr(y) }, radius }; + round.push((self.new_edge(rest, [0.0, theta], [b, a])?, true)); + } + let (c, n) = other; + let Some(x) = (pa - c).normalized() else { return Ok(None) }; + let full = BCurve::Circle { frame: Frame { origin: arr(c), x_axis: arr(x), y_axis: arr(n.cross(x)) }, radius: (pa - c).len() }; + let second = self.new_edge(full, [0.0, TAU], [a, a])?; + let mut back = round.clone(); + super::reverse(&mut back); + let mut merged = round; + merged.push((second, true)); + merged.extend(back); + merged.push((second, false)); + Ok(Some(merged)) + } + + /// Join loop `li` of face `fi` to the pole the face covers: seam out and back. + fn pole_seam(&mut self, fi: usize, li: usize, ax: &Axis, pole: Option, eval: &SurfaceEval) -> R<()> { + let step = self.faces.get(fi).map_or(0, |f| f.step); + let Some(p) = pole else { + return Err(format!("face #{step}: a face around an open surface of revolution with one bound")); + }; + let Some(LoopB::Edges(es)) = self.faces.get(fi).and_then(|f| f.loops.get(li)) else { return Err("loop reference".into()) }; + let es = es.clone(); + // Start at a vertex off the pole. + let mut k = None; + for (i, u) in es.iter().enumerate() { + if self.vpoint(self.start(*u)?)?.dist(p) > self.tol { + k = Some(i); + break; + } + } + let k = k.ok_or_else(|| format!("face #{step}: a loop around the axis on its pole"))?; + let k = match ax.kind { + Kind::Iso { u0, .. } => self.seam_start(fi, li, u0, ax, eval)?, + _ => k, + }; + let ring = self.rotated(fi, li, k)?; + let a = self.start(*ring.first().ok_or("empty loop")?)?; + // The face's vertex loop at the pole, if it has one, else a new vertex there. + let face = self.faces.get(fi).ok_or("face reference")?; + let at_pole = face.loops.iter().enumerate().find_map(|(i, l)| match l { + LoopB::Vertex(v) => self.vertices.get(*v as usize).filter(|x| Vec3::from(x.point).dist(p) <= self.tol.max(x.tolerance)).map(|_| (i, *v)), + LoopB::Edges(_) => None, + }); + let b = match at_pole { + Some((_, v)) => v, + None => { + let v = index(self.vertices.len())?; + self.vertices.push(Vertex { point: arr(p), tolerance: self.tol }); + v + } + }; + let (seam, along) = self.seam_edge(a, b, ax, eval, false)?; + let mut merged = ring; + merged.push((seam, along)); + merged.push((seam, !along)); + let face = self.faces.get_mut(fi).ok_or("face reference")?; + if let Some(l) = face.loops.get_mut(li) { + *l = LoopB::Edges(merged); + } + if let Some((i, _)) = at_pole { + remove_loop(face, i, li); + } + Ok(()) + } + + /// Join loops `la` (running +u) and `lb` (running −u) of face `fi` by a seam. + fn band_seam(&mut self, fi: usize, la: usize, lb: usize, ax: &Axis, eval: &SurfaceEval, splits: &mut usize) -> R<()> { + let angle = |s: &Self, v: u32| -> R { + let p = s.vpoint(v)?; + eval.project(p, None, f64::INFINITY).map(|q| q[0]).ok_or_else(|| "a vertex off its surface".to_string()) + }; + let (Some(LoopB::Edges(a_es)), Some(LoopB::Edges(b_es))) = + (self.faces.get(fi).and_then(|f| f.loops.get(la)), self.faces.get(fi).and_then(|f| f.loops.get(lb))) + else { + return Err("loop reference".into()); + }; + let (a_es, b_es) = (a_es.clone(), b_es.clone()); + // Angles agree within the tolerance at the radius they are at. + let close = |s: &Self, va: u32, vb: u32| -> R { + let (ua, ub) = (angle(s, va)?, angle(s, vb)?); + let r = { + let p = s.vpoint(va)? - ax.origin; + (p - ax.z * p.dot(ax.z)).len() + }; + Ok(wrap(ua - ub).abs() * r <= s.tol) + }; + if let Kind::Iso { u0, .. } = ax.kind { + // Both loops start on the spline's boundary column, split there where they don't. + let i = self.seam_start(fi, la, u0, ax, eval)?; + let j = self.seam_start(fi, lb, u0, ax, eval)?; + *splits += 2; + if *splits > MAX_SPLITS { + return Err(format!("more than {MAX_SPLITS} edges split for seams")); + } + return self.join_by_seam(fi, la, lb, i, j, ax, eval); + } + let mut pair = None; + 'search: for (i, ua) in a_es.iter().enumerate().take(100) { + for (j, ub) in b_es.iter().enumerate().take(100) { + if close(self, self.start(*ua)?, self.start(*ub)?)? { + pair = Some((i, j)); + break 'search; + } + } + } + let (i, j) = match pair { + Some(p) => p, + None => { + // Split loop B where the ruling (or meridian) through A's first vertex meets it. + *splits += 1; + if *splits > MAX_SPLITS { + return Err(format!("more than {MAX_SPLITS} edges split for seams")); + } + let target = angle(self, self.start(*a_es.first().ok_or("empty loop")?)?)?; + let mut found = None; + for &(e, _) in &b_es { + if let Some(t) = self.crossing(e, target, ax.period, eval)? { + found = Some((e, t)); + break; + } + } + let (e, t) = found.ok_or_else(|| unsupported("a band whose bounds share no angle"))?; + let v = self.split_edge(e, t)?; + let Some(LoopB::Edges(b_now)) = self.faces.get(fi).and_then(|f| f.loops.get(lb)) else { return Err("loop reference".into()) }; + let mut j = None; + for (k, u) in b_now.iter().enumerate() { + if self.start(*u)? == v { + j = Some(k); + break; + } + } + (0, j.ok_or("the split vertex is not on its loop")?) + } + }; + self.join_by_seam(fi, la, lb, i, j, ax, eval) + } + + /// Join loops `la` and `lb` of face `fi`, from their uses `i` and `j`, by a seam between + /// the vertices those uses start at: loop A, the seam out, loop B, the seam back. + #[allow(clippy::too_many_arguments)] + fn join_by_seam(&mut self, fi: usize, la: usize, lb: usize, i: usize, j: usize, ax: &Axis, eval: &SurfaceEval) -> R<()> { + let a_ring = self.rotated(fi, la, i)?; + let b_ring = self.rotated(fi, lb, j)?; + let va = self.start(*a_ring.first().ok_or("empty loop")?)?; + let vb = self.start(*b_ring.first().ok_or("empty loop")?)?; + let (seam, along) = self.seam_edge(va, vb, ax, eval, true)?; + let mut merged = a_ring; + merged.push((seam, along)); + merged.extend(b_ring); + merged.push((seam, !along)); + let face = self.faces.get_mut(fi).ok_or("face reference")?; + if let Some(l) = face.loops.get_mut(la) { + *l = LoopB::Edges(merged); + } + remove_loop(face, lb, la); + Ok(()) + } + + /// The parameter inside edge `e`'s interval where its curve reaches the angle `target` + /// about the axis, if it does. + fn crossing(&self, e: u32, target: f64, period: f64, eval: &SurfaceEval) -> R> { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let [lo, hi] = edge.interval; + let d = |t: f64| c.point(t).and_then(|p| eval.project(p, None, f64::INFINITY)).map(|q| wrap_by(q[0] - target, period)); + // A jump across the half period is the wrap, not a crossing. + let near = period / TAU; + let n = 64; + let mut prev: Option<(f64, f64)> = None; + for k in 0..=n { + let t = lo + (hi - lo) * k as f64 / n as f64; + let Some(x) = d(t) else { continue }; + if let Some((t0, x0)) = prev + && x0.signum() != x.signum() + && x0.abs() < near + && x.abs() < near + { + let (mut a, mut b, mut fa) = (t0, t, x0); + for _ in 0..100 { + let m = 0.5 * (a + b); + let Some(fm) = d(m) else { break }; + if fm.signum() == fa.signum() { + a = m; + fa = fm; + } else { + b = m; + } + } + let t = 0.5 * (a + b); + let eps = 1e-9 * (hi - lo); + return Ok((t > lo + eps && t < hi - eps).then_some(t)); + } + prev = Some((t, x)); + } + Ok(None) + } + + /// The use of loop `li` of face `fi` that starts on the surface's column at u = `u0`: a + /// vertex there within the tolerance, else one made by splitting the loop's edge that + /// crosses it. + fn seam_start(&mut self, fi: usize, li: usize, u0: f64, ax: &Axis, eval: &SurfaceEval) -> R { + let Some(LoopB::Edges(es)) = self.faces.get(fi).and_then(|f| f.loops.get(li)) else { return Err("loop reference".into()) }; + let es = es.clone(); + let on_seam = |s: &Self, v: u32| -> R { + let p = s.vpoint(v)?; + let Some(q) = eval.project(p, None, f64::INFINITY) else { return Ok(false) }; + Ok(eval.point([u0, q[1]]).is_some_and(|c| c.dist(p) <= s.tol)) + }; + for (k, u) in es.iter().enumerate() { + if on_seam(self, self.start(*u)?)? { + return Ok(k); + } + } + for &(e, _) in &es { + if let Some(t) = self.crossing(e, u0, ax.period, eval)? { + let v = self.split_edge(e, t)?; + let Some(LoopB::Edges(now)) = self.faces.get(fi).and_then(|f| f.loops.get(li)) else { return Err("loop reference".into()) }; + for (k, u) in now.iter().enumerate() { + if self.start(*u)? == v { + return Ok(k); + } + } + return Err("the split vertex is not on its loop".into()); + } + } + Err(unsupported("a loop around a closed spline that never reaches its boundary column")) + } + + /// Split edge `e` at `t` inside its interval: it keeps [min, t], a new edge takes + /// [t, max], and every loop using it uses both. Returns the new vertex. + fn split_edge(&mut self, e: u32, t: f64) -> R { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let p = c.point(t).ok_or("split point")?; + let (curve, [lo, hi], [a, b], tolerance) = (edge.curve.clone(), edge.interval, edge.vertices, edge.tolerance); + if !(t > lo && t < hi) { + return Err("a split outside its edge".into()); + } + let v = index(self.vertices.len())?; + self.vertices.push(Vertex { point: arr(p), tolerance: self.tol }); + let e2 = index(self.edges.len())?; + if let Some(x) = self.edges.get_mut(e as usize) { + x.interval = [lo, t]; + x.vertices = [a, v]; + } + self.edges.push(EdgeB { curve, interval: [t, hi], vertices: [v, b], tolerance, form: None }); + for f in &mut self.faces { + for l in &mut f.loops { + let LoopB::Edges(es) = l else { continue }; + if !es.iter().any(|u| u.0 == e) { + continue; + } + let mut out = Vec::with_capacity(es.len() + 1); + for &(x, forward) in es.iter() { + if x != e { + out.push((x, forward)); + } else if forward { + out.extend([(e, true), (e2, true)]); + } else { + out.extend([(e2, false), (e, false)]); + } + } + *es = out; + } + } + Ok(v) + } +} + +/// Remove loop `gone` from a face whose loop `kept` absorbed it, keeping its outer loop marked. +fn remove_loop(face: &mut super::FaceB, gone: usize, kept: usize) { + if gone >= face.loops.len() { + return; + } + face.loops.remove(gone); + face.outer = match face.outer { + Some(o) if o == gone => Some(if kept > gone { kept - 1 } else { kept }), + Some(o) if o > gone => Some(o - 1), + o => o, + }; +} diff --git a/crates/step/src/topology/swept.rs b/crates/step/src/topology/swept.rs new file mode 100644 index 000000000..c9e447f4a --- /dev/null +++ b/crates/step/src/topology/swept.rs @@ -0,0 +1,700 @@ +//! Swept, offset and open-conic geometry as exact schema 4 kinds. STEP's SURFACE_OF_REVOLUTION +//! becomes a `placed_revolution` (u the angle, v the profile's parameter, as STEP has them); +//! SURFACE_OF_LINEAR_EXTRUSION becomes a spline surface, the profile as an exact (rational) +//! B-spline times degree 1 along the extrusion vector (a circle extruded along its axis, and a +//! circle revolved in a plane through the axis, become the cylinder and ring torus they are, so +//! whole turns keep a periodic parameter); OFFSET_SURFACE of an analytic surface +//! becomes that surface moved along its normal; HYPERBOLA and PARABOLA become exact rational +//! quadratic and quadratic splines. +//! +//! Profiles are bounded where the face needs them: a line, a conic or an open conic over the +//! parameters of the face's boundary points (with a margin), a closed conic starting at the +//! face's seam or in the widest gap between them, so its seam lies outside the face. A +//! revolved profile stops where it meets the axis (beyond it the surface would fold over). The +//! surfaces' parameters may differ from STEP's (an extrusion's v, a conic's rational +//! parameter); pcurves and domains come from the records, never from STEP's parameters. + +use solidcraft_geom::prelude::*; +use std::f64::consts::{FRAC_PI_2, TAU}; + +use solidcore_record::Vec3; +use solidcore_record::brep::{Curve as BCurve, Surface as BSurface}; + +use super::{MAX_NESTING, R, frame, map_bspline_curve, unsupported, v3}; +use crate::geom::{Axis1, Curve, P3, Placement, Surface}; + +/// Margin around a face's parameters on a profile, as a fraction of their span. +const MARGIN: f64 = 0.1; +/// Most parameter step of one rational quadratic hyperbola piece (its weight `cosh(step / 2)` +/// stays near 1). +const HYPERBOLA_STEP: f64 = 1.0; +/// Most hyperbola pieces. +const MAX_PIECES: usize = 64; +/// Samples when looking for where a revolved profile meets its axis. +const AXIS_SAMPLES: usize = 128; + +/// Points of a face's boundary (its edges sampled) and of its seam edges (used twice). +#[derive(Default)] +pub(super) struct Extent { + pub points: Vec, + pub seam: Vec, +} + +fn p3(v: Vec3) -> P3 { + [v.x, v.y, v.z] +} + +/// The hyperbola branch `a cosh t X + b sinh t Y` from `t0` to `t1` (t0 < t1) as rational +/// quadratic pieces whose knots are the pieces' end parameters. +pub(super) fn hyperbola_spline(p: &Placement, a: f64, b: f64, t0: f64, t1: f64) -> BCurve { + let n = (((t1 - t0) / HYPERBOLA_STEP).ceil() as usize).clamp(1, MAX_PIECES); + let dt = (t1 - t0) / n as f64; + let w = (0.5 * dt).cosh(); + let at = |c: f64, s: f64| p.at(a * c, b * s, 0.0); + let mut knots = vec![t0; 3]; + let first = at(t0.cosh(), t0.sinh()); + let mut homogeneous = vec![[first[0], first[1], first[2], 1.0]]; + for i in 0..n { + let ta = t0 + dt * i as f64; + let (tm, tb) = (ta + 0.5 * dt, ta + dt); + let m = at(tm.cosh() / w, tm.sinh() / w); + homogeneous.push([m[0] * w, m[1] * w, m[2] * w, w]); + let e = at(tb.cosh(), tb.sinh()); + homogeneous.push([e[0], e[1], e[2], 1.0]); + let k = if i + 1 == n { t1 } else { tb }; + knots.extend([k, k]); + } + knots.push(t1); + BCurve::RationalSpline { knots, homogeneous } +} + +/// The parabola `f t² X + 2 f t Y` from `t0` to `t1` (t0 < t1): one quadratic Bézier on knots +/// `t0, t1`, so its parameter is STEP's t exactly. +pub(super) fn parabola_spline(p: &Placement, f: f64, t0: f64, t1: f64) -> BCurve { + let at = |t: f64| p.at(f * t * t, 2.0 * f * t, 0.0); + // The end tangents meet at f·(t0·t1, t0 + t1). + let mid = p.at(f * t0 * t1, f * (t0 + t1), 0.0); + BCurve::Spline { knots: vec![t0, t0, t0, t1, t1, t1], points: vec![at(t0), mid, at(t1)] } +} + +/// The STEP line from `t0` to `t1` as a degree-1 spline on knots `t0, t1`: STEP's parameter. +fn line_spline(origin: P3, direction: P3, magnitude: f64, t0: f64, t1: f64) -> BCurve { + let at = |t: f64| [0, 1, 2].map(|i| origin[i] + direction[i] * magnitude * t); + BCurve::Spline { knots: vec![t0, t0, t1, t1], points: vec![at(t0), at(t1)] } +} + +/// A polyline as a degree-1 spline: segment i on [i, i + 1], as STEP has it. +fn polyline_spline(points: &[P3]) -> BCurve { + let n = points.len(); + let mut knots = vec![0.0]; + knots.extend((0..n).map(|i| i as f64)); + knots.push(n.saturating_sub(1) as f64); + BCurve::Spline { knots, points: points.to_vec() } +} + +/// A curve under its SURFACE_CURVE and TRIMMED_CURVE wrappers. +fn basis(c: &Curve) -> R<&Curve> { + let mut c = c; + for _ in 0..=MAX_NESTING { + match c { + Curve::SurfaceCurve { curve_3d, .. } => c = curve_3d, + Curve::Trimmed { basis, .. } => c = basis, + _ => return Ok(c), + } + } + Err("profile curves nested too deeply".into()) +} + +/// The conic angle of a point in the conic's plane. +fn conic_angle(p: &Placement, radii: [f64; 2], q: Vec3) -> f64 { + let d = q - v3(p.origin); + (d.dot(v3(p.y())) / radii[1]).atan2(d.dot(v3(p.ref_direction)) / radii[0]) +} + +/// The STEP parameter of `q` (a point on, or projected into the plane of, a planar curve): +/// angle, hyperbola or parabola parameter, or line parameter. +fn planar_param(c: &Curve, q: Vec3) -> Option { + let local = |p: &Placement| { + let d = q - v3(p.origin); + (d.dot(v3(p.ref_direction)), d.dot(v3(p.y()))) + }; + let t = match c { + Curve::Line { origin, direction, magnitude } => (q - v3(*origin)).dot(v3(*direction)) / magnitude, + Curve::Circle { position, radius } => conic_angle(position, [*radius; 2], q), + Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => conic_angle(position, [*semi_axis_1, *semi_axis_2], q), + Curve::Hyperbola { position, semi_imag_axis, .. } => (local(position).1 / semi_imag_axis).asinh(), + Curve::Parabola { position, focal_dist } => local(position).1 / (2.0 * focal_dist), + _ => return None, + }; + t.is_finite().then_some(t) +} + +/// [min, max] of the parameters, or `None` without any. +fn range(ts: &[f64]) -> Option<(f64, f64)> { + let (lo, hi) = ts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), t| (a.min(*t), b.max(*t))); + (lo.is_finite() && hi.is_finite()).then_some((lo, hi)) +} + +/// Middle-free description of the widest gap between angles: (where it starts, its width). +fn widest_gap(angles: &[f64]) -> Option<(f64, f64)> { + let mut a: Vec = angles.iter().map(|x| x.rem_euclid(TAU)).filter(|x| x.is_finite()).collect(); + a.sort_by(f64::total_cmp); + let (first, last) = (*a.first()?, *a.last()?); + let mut best = (last, first + TAU - last); + for w in a.windows(2) { + if let [x, y] = w + && y - x > best.1 + { + best = (*x, y - x); + } + } + Some(best) +} + +/// The angle all the given angles share (within 1e-6 rad), if there are any. +fn common_angle(angles: &[f64]) -> Option { + let first = *angles.first()?; + let off = |a: f64| ((a - first) + 0.5 * TAU).rem_euclid(TAU) - 0.5 * TAU; + angles.iter().all(|a| off(*a).abs() < 1e-6).then_some(first) +} + +/// A profile's parameter range: where the face is (`inner`) and the bounded range with its +/// margin (`outer`), or a whole closed conic from a start angle. +enum Span { + Open { inner: (f64, f64), outer: (f64, f64) }, + Turn { start: f64 }, +} + +/// The range a profile is built over, from the parameters of the face's points on it and of its +/// seam points; `closed` for a circle or ellipse. +fn span(ts: &[f64], seam: &[f64], closed: bool) -> R { + if closed { + if let Some(s) = common_angle(seam) { + return Ok(Span::Turn { start: s }); + } + let (gap_start, gap) = widest_gap(ts).ok_or("a face without boundary points")?; + let covered = TAU - gap; + if gap < 1e-3 { + return Ok(Span::Turn { start: gap_start + gap }); + } + let start = gap_start + gap; + let m = (MARGIN * covered + 1e-3).min(0.25 * gap); + return Ok(Span::Open { inner: (start, start + covered), outer: (start - m, start + covered + m) }); + } + let (lo, hi) = range(ts).ok_or("a face without boundary points")?; + let m = MARGIN * (hi - lo) + 1e-3 * (1.0 + lo.abs().max(hi.abs())); + Ok(Span::Open { inner: (lo, hi), outer: (lo - m, hi + m) }) +} + +/// A conic's NURBS form over `[lo, hi]` in angle. +fn form(c: BCurve, lo: f64, hi: f64) -> R { + Ok(solidcraft_geom::brep::form::curve(&c, [lo, hi]).ok_or_else(|| unsupported("a conic profile of more than one turn"))?.0) +} + +/// The profile over its span as an exact spline (B-spline and polyline profiles whole). +fn bounded(c: &Curve, s: Span) -> R { + let (lo, hi) = match s { + Span::Open { outer, .. } => outer, + Span::Turn { start } => (start, start + TAU), + }; + if !(lo < hi && lo.is_finite() && hi.is_finite()) { + return Err("a profile without extent".into()); + } + Ok(match c { + Curve::Line { origin, direction, magnitude } => line_spline(*origin, *direction, *magnitude, lo, hi), + // A circle or ellipse as its NURBS form (`form::curve`), the one its edges carry: the swept + // surface's parameter along the profile is then theirs, and their pcurves are straight. + Curve::Circle { position, radius } => form(BCurve::Circle { frame: super::frame(position), radius: *radius }, lo, hi)?, + Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => { + form(BCurve::Ellipse { frame: super::frame(position), radii: [*semi_axis_1, *semi_axis_2] }, lo, hi)? + } + Curve::Hyperbola { position, semi_axis, semi_imag_axis } => { + if hi - lo > HYPERBOLA_STEP * MAX_PIECES as f64 { + return Err(unsupported("a hyperbola profile that long")); + } + hyperbola_spline(position, *semi_axis, *semi_imag_axis, lo, hi) + } + Curve::Parabola { position, focal_dist } => parabola_spline(position, *focal_dist, lo, hi), + _ => return Err(unsupported("this profile curve")), + }) +} + +/// A profile that needs no bounds (a B-spline, a polyline), if it is one. +fn whole(c: &Curve) -> R> { + Ok(match c { + Curve::BSpline(b) => Some(map_bspline_curve(b)?), + Curve::Polyline(points) => { + if points.len() < 2 || points.len() > super::MAX_SPLINE_POINTS || points.windows(2).any(|w| w.first() == w.get(1)) { + return Err(unsupported(format!("a polyline profile of {} points", points.len()))); + } + Some(polyline_spline(points)) + } + Curve::Line { .. } | Curve::Circle { .. } | Curve::Ellipse { .. } | Curve::Hyperbola { .. } | Curve::Parabola { .. } => None, + Curve::OffsetCurve3d { .. } => return Err(unsupported("an OFFSET_CURVE_3D profile")), + Curve::Trimmed { .. } | Curve::SurfaceCurve { .. } => return Err(unsupported("nested profile curves")), + }) +} + +/// The middle parameter of a TRIMMED_CURVE trimmed by parameters (on a closed conic, the +/// middle of the arc its sense runs over). +fn trimmed_middle(c: &Curve) -> Option { + let (a, b) = trimmed_range(c)?; + let m = 0.5 * (a + b); + m.is_finite().then_some(m) +} + +/// A trimmed profile's range on its basis, low end first, where both trims are parameters: on +/// a closed basis (a circle, an ellipse) the way round `sense` gives. +fn trimmed_range(c: &Curve) -> Option<(f64, f64)> { + let Curve::Trimmed { basis, trim_1, trim_2, sense, .. } = c else { return None }; + let param = |t: &[crate::geom::Trim]| { + t.iter().find_map(|x| match x { + crate::geom::Trim::Parameter(p) => Some(*p), + crate::geom::Trim::Point(_) => None, + }) + }; + let (a, mut b) = (param(trim_1)?, param(trim_2)?); + if is_closed(basis) { + b = if *sense { a + (b - a).rem_euclid(TAU) } else { a - (a - b).rem_euclid(TAU) }; + } + let (lo, hi) = (a.min(b), a.max(b)); + (lo.is_finite() && hi.is_finite() && lo < hi).then_some((lo, hi)) +} + +fn is_closed(c: &Curve) -> bool { + matches!(c, Curve::Circle { .. } | Curve::Ellipse { .. }) +} + +/// SURFACE_OF_REVOLUTION: the profile turned about the axis, u the angle and v the profile's +/// parameter (`forward: false`), so the natural normal is ∂S/∂angle × ∂S/∂profile, STEP's. +fn revolution(profile: &Curve, axis: &Axis1, ext: &Extent) -> R { + let c = basis(profile)?; + let (o, k) = (v3(axis.origin), v3(axis.direction)); + let k = k.normalized().ok_or("a revolution about no direction")?; + let curve = match whole(c)? { + Some(curve) => curve, + None => { + // The meridian half-plane the profile lies in: the radial direction of its point + // farthest from the axis among a few. + let radial = |q: Vec3| { + let d = q - o; + d - k * d.dot(k) + }; + let probe = |t: f64| c.point(t).map(v3); + let mut e = None::; + let mut best = 0.0; + // A trimmed profile's own middle says which side of the axis it is on (a profile + // across the axis covers the surface twice, once each way round). + let probes = match trimmed_middle(profile) { + Some(t) => vec![t], + None => vec![-1.0, 0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0], + }; + for t in probes { + if let Some(r) = probe(t).map(radial) + && r.len() > best + { + best = r.len(); + e = r.normalized(); + } + } + let e = e.ok_or_else(|| unsupported("a profile on its axis"))?; + // Each boundary point turned into the meridian plane, then its profile parameter: + // on whichever side of the axis the profile has a point where it lands. + let meridian = |q: Vec3| ((q - o).dot(k), radial(q).len()); + let param = |q: Vec3| { + let (h, r) = meridian(q); + [e, -e] + .into_iter() + .filter_map(|side| { + let at = o + k * h + side * r; + let t = planar_param(c, at)?; + Some((t, probe(t)?.dist(at))) + }) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(t, _)| t) + }; + let ts: Vec = ext.points.iter().filter_map(|q| param(*q)).collect(); + let seam: Vec = ext.seam.iter().filter_map(|q| param(*q)).collect(); + // The profile's side of the axis where the face is. + let mid = ts.get(ts.len() / 2).copied().ok_or("a face without boundary points")?; + let e = probe(mid).map(radial).and_then(|r| r.normalized()).unwrap_or(e); + // A trimmed profile is the file's range of its basis exactly; otherwise the face's + // reach along it. + let s = match trimmed_range(profile) { + Some(r) => Span::Open { inner: r, outer: r }, + None => span(&ts, &seam, is_closed(c))?, + }; + // Stop where the profile meets the axis outside the face: a circle or ellipse that + // meets it is its whole arc on the face's side, pole to pole (closed form), so a face + // with one bound around the axis reaches its pole and nothing folds over; another + // profile stops where it crosses. + let face_mid = match s { + Span::Open { inner, .. } => 0.5 * (inner.0 + inner.1), + Span::Turn { start } => start + (mid - start).rem_euclid(TAU), + }; + let arc = conic_side_arc(c, o, e, face_mid); + let side = |t: f64| probe(t).map(|q| (q - o).dot(e)); + let s = match (s, arc) { + (_, Some(arc)) => Span::Open { inner: arc, outer: arc }, + (Span::Open { inner, outer }, None) => { + let lo = crossing(&side, inner.0, outer.0).unwrap_or(outer.0); + let hi = crossing(&side, inner.1, outer.1).unwrap_or(outer.1); + Span::Open { inner, outer: (lo, hi) } + } + (turn, None) => turn, + }; + let curve = bounded(c, s)?; + match arc { + Some(arc) => clip_form(curve, arc)?, + None => curve, + } + } + }; + let identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + Ok(BSurface::PlacedRevolution { profile: Box::new(curve), origin: p3(o), axis: p3(k), matrix: identity, forward: false }) +} + +/// A torus whose tube reaches its axis (a spindle or horn torus: major radius at most the +/// minor, or written with a negative major radius, its tube on the other side of the axis) as +/// what it is, its tube's meridian circle revolved about its axis: ISO 10303-42 gives the torus +/// `C + (R + r cos v)(cos u X + sin u Y) + r sin v Z`, the revolution of the circle about `C`'s +/// Z through `C + R X` with the same normal (∂S/∂u × ∂S/∂v). The revolution keeps the tube's +/// arc on the face's side of the axis, pole to pole (`revolution`): the face's boundary, not a +/// degenerate torus's `select_outer`, says which part (the apple or the lemon) it is on. +fn torus_revolved(position: &Placement, major: f64, minor: f64, ext: &Extent) -> R { + // The circle in the X–Z half-plane: its parameter from X towards Z, as the torus's v. + let circle = Curve::Circle { + position: Placement { + origin: crate::geom::add(position.origin, crate::geom::scale(position.ref_direction, major)), + axis: crate::geom::scale(position.y(), -1.0), + ref_direction: position.ref_direction, + }, + radius: minor, + }; + revolution(&circle, &Axis1 { origin: position.origin, direction: position.axis }, ext) +} + +/// The arc of a circle or ellipse profile on the positive side of the plane through the axis +/// point `o` square to `e` (the face's side of its axis), as angles: the one round `near`, its +/// ends where the profile meets that plane; `None` for another profile, or one that does not +/// meet it. On the conic `O + a cos t X + b sin t Y` the side is `s₀ + A cos t + B sin t = +/// s₀ + M cos(t − φ)`, zero at `φ ± acos(−s₀/M)`; a profile that only touches the axis (a horn +/// torus's tube) has its arc a whole turn, both ends at the touching point. +fn conic_side_arc(c: &Curve, o: Vec3, e: Vec3, near: f64) -> Option<(f64, f64)> { + let (position, a, b) = match c { + Curve::Circle { position, radius } => (position, *radius, *radius), + Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => (position, *semi_axis_1, *semi_axis_2), + _ => return None, + }; + let s0 = (v3(position.origin) - o).dot(e); + let (ca, cb) = (a * v3(position.ref_direction).dot(e), b * v3(position.y()).dot(e)); + let m = ca.hypot(cb); + let ratio = -s0 / m; + if !(m > 0.0 && (-1.0..=1.0).contains(&ratio)) { + return None; + } + let half = ratio.acos(); + let phi = cb.atan2(ca); + let centre = phi + ((near - phi) / TAU).round() * TAU; + (centre.is_finite() && half > 0.0).then_some((centre - half, centre + half)) +} + +/// A conic's NURBS form (on its quarter grid) cut to the angles `arc` where it reaches past +/// them: the same curve at the same parameters (`bspline::segment`, exact knot insertion), so +/// it keeps the grid its edges' forms share and stops where the profile meets the axis. +fn clip_form(curve: BCurve, (a0, a1): (f64, f64)) -> R { + use solidcraft_geom::bspline::{HPoint, segment}; + let BCurve::RationalSpline { knots, homogeneous } = curve else { return Ok(curve) }; + let (Some(&k0), Some(&k1)) = (knots.first(), knots.last()) else { return Err("a profile without knots".into()) }; + let (lo, hi) = (solidcraft_geom::brep::form::param(a0).max(k0), solidcraft_geom::brep::form::param(a1).min(k1)); + if lo <= k0 && hi >= k1 { + return Ok(BCurve::RationalSpline { knots, homogeneous }); + } + if !(lo < hi) { + return Err(unsupported("a revolved profile on its axis")); + } + let degree = knots.len().checked_sub(homogeneous.len() + 1).ok_or("a profile's knots")?; + let ctrl: Vec = homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(); + let (knots, ctrl) = segment(degree, &knots, &ctrl, lo, hi).map_err(|e| format!("a revolved profile cut at its axis: {e}"))?; + Ok(BCurve::RationalSpline { knots, homogeneous: ctrl.iter().map(|h| [h.x, h.y, h.z, h.w]).collect() }) +} + +/// Going from `from` (where `side` is positive or zero) towards `to`, the first parameter +/// where `side` reaches zero, if it does. +fn crossing(side: &dyn Fn(f64) -> Option, from: f64, to: f64) -> Option { + let s0 = side(from)?; + let mut prev = (from, s0); + for i in 1..=AXIS_SAMPLES { + let t = from + (to - from) * i as f64 / AXIS_SAMPLES as f64; + let s = side(t)?; + if s.signum() != prev.1.signum() || s == 0.0 { + let (mut a, mut b, fa) = (prev.0, t, prev.1); + for _ in 0..100 { + let m = 0.5 * (a + b); + let fm = side(m)?; + if fm.signum() == fa.signum() && fm != 0.0 { + a = m; + } else { + b = m; + } + } + return Some(b); + } + prev = (t, s); + } + None +} + +/// SURFACE_OF_LINEAR_EXTRUSION: the profile as an exact spline along u, degree 1 along the +/// vector in v, over the face's reach along it. +fn extrusion(profile: &Curve, direction: P3, magnitude: f64, ext: &Extent) -> R { + let c = basis(profile)?; + let d = v3(direction) * magnitude; + let dd = d.len2(); + if !(dd > 0.0 && dd.is_finite()) { + return Err("an extrusion of no length".into()); + } + let curve = match whole(c)? { + Some(curve) => curve, + None => { + // Each boundary point slid along the vector onto the profile. + let onto = |q: Vec3| -> Option { + match c { + Curve::Line { origin, direction: e, magnitude: m } => { + // q − origin = s·m·e + v·d, least squares in (s, v). + let (e, r) = (v3(*e) * *m, q - v3(*origin)); + let (a, b, cc) = (e.len2(), e.dot(d), dd); + let det = a * cc - b * b; + (det.abs() > 1e-12 * a * cc).then(|| (r.dot(e) * cc - r.dot(d) * b) / det) + } + Curve::Circle { position, .. } + | Curve::Ellipse { position, .. } + | Curve::Hyperbola { position, .. } + | Curve::Parabola { position, .. } => { + let n = v3(position.axis); + let dn = d.dot(n); + if !(dn.abs() > 1e-9 * d.len()) { + return None; + } + planar_param(c, q - d * ((q - v3(position.origin)).dot(n) / dn)) + } + _ => None, + } + }; + let ts: Vec = ext.points.iter().filter_map(|q| onto(*q)).collect(); + if ts.len() < ext.points.len() { + return Err(unsupported("an extrusion along its profile's plane")); + } + let seam: Vec = ext.seam.iter().filter_map(|q| onto(*q)).collect(); + let s = match trimmed_range(profile) { + Some(r) => Span::Open { inner: r, outer: r }, + None => span(&ts, &seam, is_closed(c))?, + }; + bounded(c, s)? + } + }; + let (knots, homogeneous, rational) = match curve { + BCurve::Spline { knots, points } => (knots, points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect::>(), false), + BCurve::RationalSpline { knots, homogeneous } => (knots, homogeneous, true), + _ => return Err("an extrusion profile".into()), + }; + // v: the face's points' reach along the vector, less the profile's (its control points + // bound it), with a margin. + let along = |p: Vec3| p.dot(d) / dd; + let (plo, phi) = range(&ext.points.iter().map(|p| along(*p)).collect::>()).ok_or("a face without boundary points")?; + let cs: Vec = homogeneous.iter().filter(|h| h[3] > 0.0).map(|h| along(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]))).collect(); + let (clo, chi) = range(&cs).ok_or("an extrusion profile")?; + let (lo, hi) = (plo - chi, phi - clo); + let m = MARGIN * (hi - lo) + 1e-3 / dd.sqrt(); + let (lo, hi) = (lo - m, hi + m); + let shift = |h: &[f64; 4], s: f64| [h[0] + d.x * s * h[3], h[1] + d.y * s * h[3], h[2] + d.z * s * h[3], h[3]]; + let rows: Vec> = homogeneous.iter().map(|h| vec![shift(h, lo), shift(h, hi)]).collect(); + let v_knots = vec![lo, lo, hi, hi]; + Ok(if rational { + BSurface::RationalSpline { u_knots: knots, v_knots, homogeneous: rows } + } else { + BSurface::Spline { u_knots: knots, v_knots, points: rows.into_iter().map(|r| r.into_iter().map(|h| [h[0], h[1], h[2]]).collect()).collect() } + }) +} + +/// An analytic surface moved `d` along its natural normal (every analytic kind's natural +/// normal points out of its axis, or along z × … for a plane): checked at each level. +fn offset(s: BSurface, d: f64) -> R { + let bad = |what: &str| Err(format!("an offset {what}")); + Ok(match s { + BSurface::Plane { origin, u_axis, v_axis } => { + let n = v3(u_axis).cross(v3(v_axis)).normalized().ok_or("a degenerate plane")?; + BSurface::Plane { origin: p3(v3(origin) + n * d), u_axis, v_axis } + } + BSurface::Cylinder { frame, radius } => { + if !(radius + d > 1e-9) { + return bad("cylinder that collapses or turns inside out"); + } + BSurface::Cylinder { frame, radius: radius + d } + } + BSurface::Sphere { frame, radius } => { + if !(radius + d > 1e-9) { + return bad("sphere that collapses or turns inside out"); + } + BSurface::Sphere { frame, radius: radius + d } + } + BSurface::Cone { frame, radius_at_origin, half_angle } => { + // The normal is (cos a, −sin a) in (radial, axial): the reference radius grows by + // d / cos a, the angle stays. + let r = radius_at_origin + d / half_angle.cos(); + if !(r >= 0.0 && r.is_finite()) { + return bad("cone whose reference radius turns negative"); + } + BSurface::Cone { frame, radius_at_origin: r, half_angle } + } + BSurface::Torus { frame, major_radius, minor_radius, tube_start } => { + let r = minor_radius + d; + if !(r > 1e-9 && r < major_radius) { + return bad("torus that collapses or meets its axis"); + } + BSurface::Torus { frame, major_radius, minor_radius: r, tube_start } + } + _ => return Err(unsupported("an OFFSET_SURFACE of a spline or swept surface")), + }) +} + +/// A face's surface as a schema surface, and whether the record's natural normal is opposite +/// STEP's surface normal (an extruded circle or revolved circle read as a cylinder or torus, +/// whose natural normals point away from their axes); `ext` bounds swept surfaces' profiles, +/// and a cone that stays within `tol` (the file's distance uncertainty) of its limit plane +/// over `ext` is read as that plane. +pub(super) fn map_surface(s: &Surface, ext: &Extent, tol: f64) -> R<(BSurface, bool)> { + let mut reversed = false; + let s = map_surface_in(s, ext, tol, 0, &mut reversed)?; + Ok((s, reversed)) +} + +/// An extruded circle along its axis is a cylinder; a circle in a plane through the axis, +/// revolved, a ring torus. `None` for anything else. +fn canonical(s: &Surface, reversed: &mut bool) -> Option { + let c = match s { + Surface::Extrusion { profile, .. } | Surface::Revolution { profile, .. } => basis(profile).ok()?, + _ => return None, + }; + let Curve::Circle { position, radius } = c else { return None }; + let n = v3(position.axis); + match s { + Surface::Extrusion { direction, .. } => { + let d = v3(*direction); + if d.cross(n).len() > 1e-12 { + return None; + } + // STEP's normal is the profile's tangent × the vector: out of the axis when the + // vector runs along the circle's axis. + *reversed = d.dot(n) < 0.0; + Some(BSurface::Cylinder { frame: frame(position), radius: *radius }) + } + Surface::Revolution { axis, .. } => { + let (o, k) = (v3(axis.origin), v3(axis.direction).normalized()?); + let centre = v3(position.origin); + let scale = 1.0 + (centre - o).len() + radius; + if n.dot(k).abs() > 1e-12 || (centre - o).dot(n).abs() > 1e-12 * scale { + return None; + } + let foot = o + k * (centre - o).dot(k); + let big = (centre - foot).len(); + if !(big > *radius * (1.0 + 1e-9)) { + return None; + } + let x = (centre - foot).normalized()?; + // STEP's normal at the circle's angle 0: ∂angle × ∂profile; the torus's points out + // of the tube. + let (cx, cy) = (v3(position.ref_direction), v3(position.y())); + let at = centre + cx * *radius; + let step_normal = k.cross(at - o).cross(cy * *radius); + *reversed = step_normal.dot(cx) < 0.0; + Some(BSurface::Torus { + frame: solidcore_record::brep::Frame { origin: p3(foot), x_axis: p3(x), y_axis: p3(k.cross(x)) }, + major_radius: big, + minor_radius: *radius, + tube_start: 0.0, + }) + } + _ => None, + } +} + +fn map_surface_in(s: &Surface, ext: &Extent, tol: f64, depth: usize, reversed: &mut bool) -> R { + if depth > MAX_NESTING { + return Err("surfaces nested too deeply".into()); + } + if let Some(c) = canonical(s, reversed) { + return Ok(c); + } + Ok(match s { + Surface::Plane { position } => BSurface::Plane { origin: position.origin, u_axis: position.ref_direction, v_axis: position.y() }, + Surface::Cylinder { position, radius } => BSurface::Cylinder { frame: frame(position), radius: *radius }, + Surface::Cone { position, radius, semi_angle } => { + if let Some(plane) = flat_cone(position, *radius, *semi_angle, ext, tol, reversed) { + return Ok(plane); + } + if !(*radius >= 0.0) || !(semi_angle.abs() > 1e-12 && semi_angle.abs() < FRAC_PI_2) { + return Err(unsupported(format!("a cone of radius {radius} and semi-angle {semi_angle}"))); + } + BSurface::Cone { frame: frame(position), radius_at_origin: *radius, half_angle: *semi_angle } + } + Surface::Sphere { position, radius } => BSurface::Sphere { frame: frame(position), radius: *radius }, + Surface::Torus { position, major_radius, minor_radius } => { + if !(major_radius > minor_radius) { + return torus_revolved(position, *major_radius, *minor_radius, ext); + } + BSurface::Torus { frame: frame(position), major_radius: *major_radius, minor_radius: *minor_radius, tube_start: 0.0 } + } + Surface::DegenerateTorus { position, major_radius, minor_radius, .. } => { + return torus_revolved(position, *major_radius, *minor_radius, ext); + } + Surface::BSpline(b) => super::map_bspline_surface(b)?, + Surface::RectangularTrimmed { basis, .. } => map_surface_in(basis, ext, tol, depth + 1, reversed)?, + Surface::Revolution { profile, axis } => revolution(profile, axis, ext)?, + Surface::Extrusion { profile, direction, magnitude } => extrusion(profile, *direction, *magnitude, ext)?, + Surface::Offset { basis, distance, .. } => { + // Along STEP's normal: the record's, or its opposite. + let b = map_surface_in(basis, ext, tol, depth + 1, reversed)?; + offset(b, if *reversed { -*distance } else { *distance })? + } + }) +} + +/// A cone written for a plane (a semi-angle a whisker short of 90°, as exporters write one) as +/// that plane: the plane through the placement's origin across its axis, the cone's limit as +/// its angle opens to 90°. The cone's height above it is `(rho - radius) cot a` at parameter +/// radius `rho`, monotone in `rho` away from the apex: over the face it stays within the +/// heights of the boundary points and, should the face hold the axis, the apex's +/// (`radius cot a`). `None` unless that deviation is within `tol`. STEP's normal there is +/// `-rho tan a` along the axis, so the record's (the axis) is opposite STEP's where +/// `rho tan a > 0`. +fn flat_cone(position: &Placement, radius: f64, semi_angle: f64, ext: &Extent, tol: f64, reversed: &mut bool) -> Option { + let (o, k) = (v3(position.origin), v3(position.axis).normalized()?); + let cot = semi_angle.cos() / semi_angle.sin(); + let mut deviation = (radius * cot).abs(); + let mut widest: Option<(f64, f64)> = None; + for p in &ext.points { + let d = *p - o; + let h = d.dot(k); + deviation = deviation.max(h.abs()); + let r = (d - k * h).len(); + if widest.is_none_or(|(w, _)| r > w) { + widest = Some((r, h)); + } + } + let (_, h) = widest?; + if !(deviation <= tol) { + return None; + } + // The parameter radius at the widest boundary point (it keeps one sign off the apex). + *reversed ^= (radius + h * semi_angle.tan()) * semi_angle.tan() > 0.0; + Some(BSurface::Plane { origin: position.origin, u_axis: position.ref_direction, v_axis: position.y() }) +} + +/// The STEP parameters of `ps` and `pe` on a hyperbola or parabola. +pub(super) fn open_conic_params(c: &Curve, ps: P3, pe: P3) -> R<(f64, f64)> { + match (planar_param(c, v3(ps)), planar_param(c, v3(pe))) { + (Some(a), Some(b)) => Ok((a, b)), + _ => Err("no parameter on the conic".into()), + } +} diff --git a/crates/step/src/topology_tests.rs b/crates/step/src/topology_tests.rs new file mode 100644 index 000000000..6f810e883 --- /dev/null +++ b/crates/step/src/topology_tests.rs @@ -0,0 +1,1239 @@ +//! STEP topology into schema 4: small solids written here entity by entity (boxes, a cylinder +//! with its seam, a plate with a through hole, sheets, a void, faces and edges written against +//! their geometry's sense), each read, validated, spot-checked and its faces' sides checked +//! against the material; hostile files are errors, never panics. Expected values are analytic. + +use std::fmt::Write as _; + +use super::*; +use crate::p21; + +type V = [f64; 3]; + +fn real(x: f64) -> String { + format!("{x:.17E}") +} +fn sub3(a: V, b: V) -> V { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn len3(a: V) -> f64 { + (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt() +} +fn neg(a: V) -> V { + [-a[0], -a[1], -a[2]] +} + +/// Writes a STEP data section one entity at a time. +#[derive(Default)] +struct W { + s: String, + n: u64, +} + +impl W { + fn add(&mut self, body: impl AsRef) -> u64 { + self.n += 1; + let _ = writeln!(self.s, "#{}={};", self.n, body.as_ref()); + self.n + } + fn pt(&mut self, p: V) -> u64 { + self.add(format!("CARTESIAN_POINT('',({},{},{}))", real(p[0]), real(p[1]), real(p[2]))) + } + fn dir(&mut self, d: V) -> u64 { + self.add(format!("DIRECTION('',({},{},{}))", real(d[0]), real(d[1]), real(d[2]))) + } + fn axis(&mut self, o: V, z: V, x: V) -> u64 { + let (o, z, x) = (self.pt(o), self.dir(z), self.dir(x)); + self.add(format!("AXIS2_PLACEMENT_3D('',#{o},#{z},#{x})")) + } + fn vertex(&mut self, p: V) -> u64 { + let p = self.pt(p); + self.add(format!("VERTEX_POINT('',#{p})")) + } + /// A line edge from `a` to `b`; with `same_sense` false its LINE runs from b to a. + fn line_edge(&mut self, (va, pa): (u64, V), (vb, pb): (u64, V), same_sense: bool, magnitude: f64) -> u64 { + let (o, d) = if same_sense { (pa, sub3(pb, pa)) } else { (pb, sub3(pa, pb)) }; + let (o, d) = (self.pt(o), self.dir(d)); + let v = self.add(format!("VECTOR('',#{d},{})", real(magnitude))); + let l = self.add(format!("LINE('',#{o},#{v})")); + self.add(format!("EDGE_CURVE('',#{va},#{vb},#{l},{})", b(same_sense))) + } + fn circle(&mut self, c: V, z: V, x: V, r: f64) -> u64 { + let a = self.axis(c, z, x); + self.add(format!("CIRCLE('',#{a},{})", real(r))) + } + fn oe(&mut self, edge: u64, orientation: bool) -> u64 { + self.add(format!("ORIENTED_EDGE('',*,*,#{edge},{})", b(orientation))) + } + fn bound(&mut self, oes: &[u64], outer: bool, orientation: bool) -> u64 { + let l = self.add(format!("EDGE_LOOP('',({}))", list(oes))); + self.add(format!("{}('',#{l},{})", if outer { "FACE_OUTER_BOUND" } else { "FACE_BOUND" }, b(orientation))) + } + fn plane(&mut self, o: V, z: V, x: V) -> u64 { + let a = self.axis(o, z, x); + self.add(format!("PLANE('',#{a})")) + } + fn face(&mut self, bounds: &[u64], surface: u64, same_sense: bool) -> u64 { + self.add(format!("ADVANCED_FACE('',({}),#{surface},{})", list(bounds), b(same_sense))) + } + /// The file: millimetres, radians, an uncertainty of 1e-7 mm, every item in one + /// representation. + fn file(mut self, items: &[u64]) -> p21::Exchange { + let l = self.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + let a = self.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))"); + let s = self.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())"); + let u = self.add(format!("UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-07),#{l},'distance_accuracy_value','')")); + let c = self.add(format!( + "(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{u}))GLOBAL_UNIT_ASSIGNED_CONTEXT((#{l},#{a},#{s}))REPRESENTATION_CONTEXT('',''))" + )); + self.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',({}),#{c})", list(items))); + parse(&self.s) + } +} + +fn parse(data: &str) -> p21::Exchange { + let t = format!("ISO-10303-21;\nHEADER;FILE_SCHEMA(('AUTOMOTIVE_DESIGN'));ENDSEC;\nDATA;\n{data}ENDSEC;\nEND-ISO-10303-21;\n"); + match p21::parse(&t) { + Ok(ex) => ex, + Err(e) => panic!("{e}\n{t}"), + } +} + +fn b(x: bool) -> &'static str { + if x { ".T." } else { ".F." } +} +fn list(ids: &[u64]) -> String { + ids.iter().map(|i| format!("#{i}")).collect::>().join(",") +} + +/// How a box is written. +#[derive(Clone, Copy, Default)] +struct BoxStyle { + /// Every other face on a plane facing into the box, with same_sense .F. + flip_faces: bool, + /// Every other edge with same_sense .F. (its line running from its end to its start). + flip_edges: bool, + /// Every face's bound written the other way round with orientation .F. + flip_bounds: bool, + /// One face's same_sense written wrong (its plane facing in, same_sense .T.). + wrong_face: bool, + /// One edge's same_sense written wrong (its line running from start to end, same_sense .F.). + wrong_edge: bool, +} + +/// The box from `lo` to `hi`: its faces (outward normals) and its top and bottom faces' +/// extra inner bounds' places (written by `inner`, given the face's axis sign). +fn box_faces(w: &mut W, lo: V, hi: V, style: BoxStyle, inner: &mut dyn FnMut(&mut W, f64) -> Vec) -> Vec { + let corner = |i: usize| [if i & 1 == 0 { lo[0] } else { hi[0] }, if i & 2 == 0 { lo[1] } else { hi[1] }, if i & 4 == 0 { lo[2] } else { hi[2] }]; + let vs: Vec<(u64, V)> = (0..8).map(|i| (w.vertex(corner(i)), corner(i))).collect(); + let mut edges: std::collections::HashMap<(usize, usize), u64> = Default::default(); + let mut faces = Vec::new(); + let mut count = 0; + for a in 0..3 { + for side in [false, true] { + let (bx, cx) = ((a + 1) % 3, (a + 2) % 3); + let bit = |axis: usize| 1usize << axis; + let base = if side { bit(a) } else { 0 }; + let mut ring = [base, base | bit(bx), base | bit(bx) | bit(cx), base | bit(cx)]; + if !side { + ring.reverse(); + } + let mut oes = Vec::new(); + for k in 0..4 { + let (p, q) = (ring[k], ring[(k + 1) % 4]); + let key = (p.min(q), p.max(q)); + let e = match edges.get(&key) { + Some(e) => *e, + None => { + let n = edges.len(); + let flip = style.flip_edges && n % 2 == 1; + let e = if style.wrong_edge && n == 3 { + // Its line runs from start to end, but it says it runs against it. + let (va, pa) = vs[key.0]; + let (vb, pb) = vs[key.1]; + let (o, d) = (w.pt(pa), w.dir(sub3(pb, pa))); + let v = w.add(format!("VECTOR('',#{d},1.)")); + let l = w.add(format!("LINE('',#{o},#{v})")); + w.add(format!("EDGE_CURVE('',#{va},#{vb},#{l},.F.)")) + } else { + w.line_edge(vs[key.0], vs[key.1], !flip, if n.is_multiple_of(3) { 1.0 } else { 2.5 }) + }; + edges.insert(key, e); + e + } + }; + oes.push(w.oe(e, p == key.0)); + } + let mut normal = [0.0; 3]; + normal[a] = if side { 1.0 } else { -1.0 }; + let mut x = [0.0; 3]; + x[bx] = 1.0; + let center = { + let mut c = [0.5 * (lo[0] + hi[0]), 0.5 * (lo[1] + hi[1]), 0.5 * (lo[2] + hi[2])]; + c[a] = if side { hi[a] } else { lo[a] }; + c + }; + let mut bounds = if style.flip_bounds { + let rev: Vec = oes + .iter() + .rev() + .map(|&oe| { + // The same edges, the other way round. + let line = w.s.lines().find(|l| l.starts_with(&format!("#{oe}="))).map(str::to_string).unwrap_or_default(); + let flipped = if line.ends_with(".T.);") { line.replace(".T.);", ".F.);") } else { line.replace(".F.);", ".T.);") }; + let body = flipped.split_once('=').map(|(_, b)| b.trim_end_matches(';').to_string()).unwrap_or_default(); + w.add(body) + }) + .collect(); + vec![w.bound(&rev, true, false)] + } else { + vec![w.bound(&oes, true, true)] + }; + if a == 2 { + bounds.extend(inner(w, normal[2])); + } + let flip = style.flip_faces && count % 2 == 1; + let wrong = style.wrong_face && count == 4; + let plane = w.plane(center, if flip || wrong { neg(normal) } else { normal }, x); + faces.push(w.face(&bounds, plane, !flip)); + count += 1; + } + } + faces +} + +fn closed_shell(w: &mut W, faces: &[u64]) -> u64 { + w.add(format!("CLOSED_SHELL('',({}))", list(faces))) +} + +fn one_solid(ex: &p21::Exchange) -> Solid { + let r = read_solids(ex); + assert!(r.failures.is_empty(), "{:?}", r.failures); + assert_eq!(r.solids.len(), 1); + let s = r.solids.into_iter().next().unwrap(); + solidcraft_geom::brep::check::validate(&s.brep).unwrap(); + solidcraft_geom::brep::geometry::check(&s.brep).unwrap(); + s +} + +fn counts(b: &Brep) -> [usize; 5] { + [b.regions.len(), b.shells.len(), b.faces.len(), b.edges.len(), b.vertices.len()] +} + +/// Each oriented face of each shell: a point inside it and its normal there in that shell. +fn sides(b: &Brep) -> Vec<(usize, V, V)> { + let mut out = Vec::new(); + for (si, s) in b.shells.iter().enumerate() { + let Shell::Faces { faces, .. } = s else { continue }; + for of in faces { + let f = &b.faces[of.face as usize]; + let eval = SurfaceEval::new(&f.surface).unwrap(); + // Inside the outer loop: its first use's middle, nudged to its left. + let Loop::Edges { edges } = &f.loops[0] else { panic!("outer vertex loop") }; + let u = &edges[0]; + let [t0, t1] = u.pcurve.interval().unwrap(); + let m = 0.5 * (t0 + t1); + let (a, c) = ( + solidcraft_geom::brep::pcurve::eval(&u.pcurve, m).unwrap(), + solidcraft_geom::brep::pcurve::eval(&u.pcurve, m + 1e-4 * (t1 - t0)).unwrap(), + ); + let along = if u.forward { [c[0] - a[0], c[1] - a[1]] } else { [a[0] - c[0], a[1] - c[1]] }; + let n = (along[0].hypot(along[1])).max(1e-300); + let left = [-along[1] / n, along[0] / n]; + let uv = [a[0] + 1e-3 * left[0], a[1] + 1e-3 * left[1]]; + let (p, su, sv) = eval.derivs(uv[0], uv[1]).unwrap(); + let mut nn = su.cross(sv); + if !of.forward { + nn = nn * -1.0; + } + out.push((si, [p.x, p.y, p.z], [nn.x, nn.y, nn.z])); + } + } + out +} + +/// Every face of shell `shell` faces away from `inside(p)`. +#[track_caller] +fn faces_away(b: &Brep, shell: usize, inside: impl Fn(V) -> V) { + for (s, p, n) in sides(b) { + if s == shell { + let i = inside(p); + let d = sub3(p, i); + assert!(d[0] * n[0] + d[1] * n[1] + d[2] * n[2] > 0.0, "shell {shell}: face at {p:?} has normal {n:?}"); + } + } +} + +fn cube(style: BoxStyle) -> p21::Exchange { + let mut w = W::default(); + let faces = box_faces(&mut w, [0.0; 3], [10.0, 20.0, 30.0], style, &mut |_, _| Vec::new()); + let shell = closed_shell(&mut w, &faces); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('cube',#{shell})")); + w.file(&[solid]) +} + +#[test] +fn a_cube_is_two_regions_six_faces_twelve_edges_eight_vertices() { + for style in [ + BoxStyle::default(), + BoxStyle { flip_faces: true, ..Default::default() }, + BoxStyle { flip_edges: true, ..Default::default() }, + BoxStyle { flip_bounds: true, ..Default::default() }, + BoxStyle { flip_faces: true, flip_edges: true, flip_bounds: true, ..Default::default() }, + ] { + let s = one_solid(&cube(style)); + assert_eq!(s.name, "cube"); + assert!(!s.sheet); + assert!(s.notes.is_empty(), "{:?}", s.notes); + assert_eq!(counts(&s.brep), [2, 1, 6, 12, 8]); + assert_eq!(s.brep.regions[0].shells, [0]); + assert_eq!(s.brep.regions[1].shells, [0]); + assert!((s.brep.tolerance - 1e-7).abs() < 1e-20); + // Same_sense .F. faces are the reversed sides of their planes. + let reversed = match &s.brep.shells[0] { + Shell::Faces { faces, .. } => faces.iter().filter(|f| !f.forward).count(), + _ => panic!(), + }; + assert_eq!(reversed, if style.flip_faces { 3 } else { 0 }); + faces_away(&s.brep, 0, |_| [5.0, 10.0, 15.0]); + // Every edge is a line on [0, length / magnitude], used twice, once each way. + for e in &s.brep.edges { + assert_eq!(e.uses.len(), 2); + let BCurve::Line { start, end } = &e.curve else { panic!("{:?}", e.curve) }; + let [a, z] = e.vertices.map(|v| s.brep.vertices[v as usize].point); + assert!(len3(sub3(*start, a)) < 1e-12, "{start:?} {a:?}"); + let m = len3(sub3(*end, *start)); + assert!((e.interval[1] * m - len3(sub3(z, a))).abs() < 1e-9 && e.interval[0] == 0.0); + // Once each way about the faces' normals in the shell. + let Shell::Faces { faces, .. } = &s.brep.shells[0] else { panic!() }; + let side = |u: &EdgeUseRef| u.upper == faces.iter().find(|f| f.face == u.face).unwrap().forward; + assert_ne!(side(&e.uses[0]), side(&e.uses[1])); + } + } +} + +#[test] +fn faces_and_edges_written_against_their_sense_are_read_by_their_loops_and_vertices() { + let s = one_solid(&cube(BoxStyle { wrong_face: true, wrong_edge: true, ..Default::default() })); + assert_eq!(counts(&s.brep), [2, 1, 6, 12, 8]); + assert!(s.notes.iter().any(|n| n.contains("1 faces turned over")), "{:?}", s.notes); + assert!(s.notes.iter().any(|n| n.contains("1 edges run against")), "{:?}", s.notes); + faces_away(&s.brep, 0, |_| [5.0, 10.0, 15.0]); +} + +/// The cylinder of radius `r` from z = z0 to z1 about (cx, cy): its vertices on the seam at +/// angle 0, its circles (counter-clockwise about +z) and its seam line (upwards). +struct Cyl { + circles: [u64; 2], + seam: u64, + surface: u64, +} + +fn cylinder(w: &mut W, c: [f64; 2], r: f64, z: [f64; 2]) -> Cyl { + let p = |h: f64| [c[0] + r, c[1], h]; + let (v0, v1) = (w.vertex(p(z[0])), w.vertex(p(z[1]))); + let circle = |w: &mut W, v: u64, h: f64| { + let k = w.circle([c[0], c[1], h], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], r); + w.add(format!("EDGE_CURVE('',#{v},#{v},#{k},.T.)")) + }; + let circles = [circle(w, v0, z[0]), circle(w, v1, z[1])]; + let seam = w.line_edge((v0, p(z[0])), (v1, p(z[1])), true, 1.0); + let a = w.axis([c[0], c[1], 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let surface = w.add(format!("CYLINDRICAL_SURFACE('',#{a},{})", real(r))); + Cyl { circles, seam, surface } +} + +/// The cylinder's side as a face whose normal points out of the cylinder (`outward`) or into it. +fn side(w: &mut W, c: &Cyl, outward: bool) -> u64 { + let [b, t] = c.circles; + // Counter-clockwise in (angle, height): about the outward normal. + let ring = [(b, true), (c.seam, true), (t, false), (c.seam, false)]; + let oes: Vec = + if outward { ring.iter().map(|&(e, o)| w.oe(e, o)).collect() } else { ring.iter().rev().map(|&(e, o)| w.oe(e, !o)).collect() }; + let bound = w.bound(&oes, true, true); + w.face(&[bound], c.surface, outward) +} + +#[test] +fn a_cylinder_has_a_seam_used_twice_by_its_side() { + let mut w = W::default(); + let c = cylinder(&mut w, [1.0, 2.0], 5.0, [0.0, 10.0]); + let side_face = side(&mut w, &c, true); + let ob = w.oe(c.circles[0], false); + let bottom_bound = w.bound(&[ob], true, true); + let bottom_plane = w.plane([1.0, 2.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let bottom = w.face(&[bottom_bound], bottom_plane, false); + let ot = w.oe(c.circles[1], true); + let top_bound = w.bound(&[ot], true, true); + let top_plane = w.plane([1.0, 2.0, 10.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let top = w.face(&[top_bound], top_plane, true); + let shell = closed_shell(&mut w, &[bottom, side_face, top]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('',#{shell})")); + let s = one_solid(&w.file(&[solid])); + assert_eq!(counts(&s.brep), [2, 1, 3, 3, 2]); + let seam = s.brep.edges.iter().find(|e| matches!(e.curve, BCurve::Line { .. })).unwrap(); + assert_eq!(seam.uses.len(), 2); + assert_eq!(seam.uses[0].face, seam.uses[1].face); + for e in &s.brep.edges { + if matches!(e.curve, BCurve::Circle { .. }) { + // On its NURBS form: a whole turn in angle, its interval in the form's parameter. + let [a0, a1] = solidcraft_geom::brep::label::edge_curve_interval(e).unwrap(); + assert!(e.nurbs.is_some() && (a1 - a0 - TAU).abs() < 1e-12); + assert_eq!(e.vertices[0], e.vertices[1]); + } + } + faces_away(&s.brep, 0, |p| [1.0, 2.0, p[2].clamp(1.0, 9.0)]); + // The side face spans one turn of the cylinder (four quarters of its NURBS form) and its height. + let f = s.brep.faces.iter().find(|f| matches!(f.surface, BSurface::Cylinder { .. })).unwrap(); + assert!( + f.nurbs.is_some() && (f.domain[0][1] - f.domain[0][0] - 4.0).abs() < 1e-9 && f.domain[1][0] < 1e-6 && f.domain[1][1] > 10.0 - 1e-6, + "{:?}", + f.domain + ); +} + +#[test] +fn a_ball_bounded_by_its_seam_alone() { + for same_sense in [true, false] { + let mut w = W::default(); + let (n, south) = ([0.0, 0.0, 5.0], [0.0, 0.0, -5.0]); + let (vn, vs) = (w.vertex(n), w.vertex(south)); + // The meridian through +x: angle 0 at the north pole, π at the south. + let k = w.circle([0.0; 3], if same_sense { [0.0, 1.0, 0.0] } else { [0.0, -1.0, 0.0] }, [0.0, 0.0, 1.0], 5.0); + let e = w.add(format!("EDGE_CURVE('',#{vn},#{vs},#{k},{})", b(same_sense))); + let (o1, o2) = (w.oe(e, true), w.oe(e, false)); + let bound = w.bound(&[o1, o2], true, true); + let a = w.axis([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let sphere = w.add(format!("SPHERICAL_SURFACE('',#{a},5.)")); + let face = w.face(&[bound], sphere, true); + let shell = closed_shell(&mut w, &[face]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('ball',#{shell})")); + let s = one_solid(&w.file(&[solid])); + assert_eq!(counts(&s.brep), [2, 1, 1, 1, 2]); + let e = &s.brep.edges[0]; + let [a0, a1] = solidcraft_geom::brep::label::edge_curve_interval(e).unwrap(); + assert!((a1 - a0 - PI).abs() < 1e-12, "{:?}", e.interval); + faces_away(&s.brep, 0, |_| [0.0; 3]); + } +} + +#[test] +fn a_cone_reaches_its_apex_through_a_vertex_loop() { + let mut w = W::default(); + let v = w.vertex([5.0, 0.0, 0.0]); + let apex = w.vertex([0.0, 0.0, 10.0]); + let k = w.circle([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 5.0); + let e = w.add(format!("EDGE_CURVE('',#{v},#{v},#{k},.T.)")); + // The cone widens down -z from its apex at z = 10 to radius 5 at z = 0. + let a = w.axis([0.0; 3], [0.0, 0.0, -1.0], [1.0, 0.0, 0.0]); + let cone = w.add(format!("CONICAL_SURFACE('',#{a},5.,{})", real(0.5f64.atan()))); + let o = w.oe(e, true); + let outer = w.bound(&[o], true, true); + let vl = w.add(format!("VERTEX_LOOP('',#{apex})")); + let point = w.add(format!("FACE_BOUND('',#{vl},.T.)")); + let side = w.face(&[outer, point], cone, true); + let o = w.oe(e, false); + let base_bound = w.bound(&[o], true, true); + let plane = w.plane([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let base = w.face(&[base_bound], plane, false); + let shell = closed_shell(&mut w, &[side, base]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('cone',#{shell})")); + let s = one_solid(&w.file(&[solid])); + // A seam from the base circle's vertex to the apex replaces the vertex loop. + assert_eq!(counts(&s.brep), [2, 1, 2, 2, 2]); + assert!(s.notes.iter().any(|n| n.contains("1 seam edges added")), "{:?}", s.notes); + let f = &s.brep.faces[0]; + assert_eq!(f.loops.len(), 1); + assert!((f.domain[1][0] + 10.0).abs() < 1e-9, "{:?}", f.domain); + faces_away(&s.brep, 0, |p| [0.0, 0.0, p[2].clamp(1.0, 2.0)]); +} + +/// The same cone written with its seam: the base circle, then the seam out to the apex and back. +/// The loop turns once round the axis and closes at the apex, so it has its seam; reading it as +/// a loop without one gave the face a second seam, a sliver out and back the face's boundary +/// crossed (#5193: a turned pin's drill point after a STEP round trip did not tessellate). +#[test] +fn a_cone_with_its_seam_to_the_apex_gets_no_other() { + let mut w = W::default(); + let (p, top) = ([5.0, 0.0, 0.0], [0.0, 0.0, 10.0]); + let (v, apex) = (w.vertex(p), w.vertex(top)); + let k = w.circle([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 5.0); + let e = w.add(format!("EDGE_CURVE('',#{v},#{v},#{k},.T.)")); + let seam = w.line_edge((v, p), (apex, top), true, len3(sub3(top, p))); + let a = w.axis([0.0; 3], [0.0, 0.0, -1.0], [1.0, 0.0, 0.0]); + let cone = w.add(format!("CONICAL_SURFACE('',#{a},5.,{})", real(0.5f64.atan()))); + let uses = [w.oe(e, true), w.oe(seam, true), w.oe(seam, false)]; + let outer = w.bound(&uses, true, true); + let side = w.face(&[outer], cone, true); + let o = w.oe(e, false); + let base_bound = w.bound(&[o], true, true); + let plane = w.plane([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let base = w.face(&[base_bound], plane, false); + let shell = closed_shell(&mut w, &[side, base]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('cone',#{shell})")); + let s = one_solid(&w.file(&[solid])); + assert_eq!(counts(&s.brep), [2, 1, 2, 2, 2]); + assert!(!s.notes.iter().any(|n| n.contains("seam edges added")), "{:?}", s.notes); + faces_away(&s.brep, 0, |p| [0.0, 0.0, p[2].clamp(1.0, 2.0)]); +} + +/// A tube (radius 5 outside, 3 inside, from z = 0 to 4) whose cylinders carry no seam edges: +/// each side is bounded by two circles whose vertices sit at different angles. +#[test] +fn bands_and_caps_without_seams_get_one() { + let mut w = W::default(); + let ring = |w: &mut W, r: f64, z: f64, at: f64| { + let v = w.vertex([r * at.cos(), r * at.sin(), z]); + let k = w.circle([0.0, 0.0, z], [0.0, 0.0, 1.0], [at.cos(), at.sin(), 0.0], r); + w.add(format!("EDGE_CURVE('',#{v},#{v},#{k},.T.)")) + }; + let (ob, ot, ib, it) = (ring(&mut w, 5.0, 0.0, 0.0), ring(&mut w, 5.0, 4.0, 1.0), ring(&mut w, 3.0, 0.0, 2.0), ring(&mut w, 3.0, 4.0, 3.0)); + let a = w.axis([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let (outer_cyl, inner_cyl) = (w.add(format!("CYLINDRICAL_SURFACE('',#{a},5.)")), w.add(format!("CYLINDRICAL_SURFACE('',#{a},3.)"))); + // Outside: normal out; its bottom circle runs +u, its top −u. + let (x, y) = (w.oe(ob, true), w.oe(ot, false)); + let (bx, by) = (w.bound(&[x], true, true), w.bound(&[y], false, true)); + let outside = w.face(&[bx, by], outer_cyl, true); + // Inside: normal towards the axis (same_sense .F.): about it, the bottom runs −u. + let (x, y) = (w.oe(ib, false), w.oe(it, true)); + let (bx, by) = (w.bound(&[x], true, true), w.bound(&[y], false, true)); + let inside = w.face(&[bx, by], inner_cyl, false); + // Annuli: the bottom faces −z, the top +z. + let plane_b = w.plane([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let (x, y) = (w.oe(ob, false), w.oe(ib, true)); + let (bx, by) = (w.bound(&[x], true, true), w.bound(&[y], false, true)); + let bottom = w.face(&[bx, by], plane_b, false); + let plane_t = w.plane([0.0, 0.0, 4.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let (x, y) = (w.oe(ot, true), w.oe(it, false)); + let (bx, by) = (w.bound(&[x], true, true), w.bound(&[y], false, true)); + let top = w.face(&[bx, by], plane_t, true); + let shell = closed_shell(&mut w, &[outside, inside, bottom, top]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('tube',#{shell})")); + let s = one_solid(&w.file(&[solid])); + // Each band's top circle split where the seam from its bottom vertex meets it. + assert_eq!(counts(&s.brep), [2, 1, 4, 4 + 2 + 2, 4 + 2]); + assert!(s.notes.iter().any(|n| n.contains("2 seam edges added")), "{:?}", s.notes); + faces_away(&s.brep, 0, |p| { + let r = p[0].hypot(p[1]); + let k = 4.0 / r.max(1e-9); + [p[0] * k, p[1] * k, p[2].clamp(1.0, 3.0)] + }); + + // A dome: a hemisphere bounded by its equator alone, closed by a disk. + let mut w = W::default(); + let e = ring(&mut w, 5.0, 0.0, 0.5); + let a = w.axis([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let sphere = w.add(format!("SPHERICAL_SURFACE('',#{a},5.)")); + let x = w.oe(e, true); + let bx = w.bound(&[x], true, true); + let dome = w.face(&[bx], sphere, true); + let plane = w.plane([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let x = w.oe(e, false); + let bx = w.bound(&[x], true, true); + let disk = w.face(&[bx], plane, false); + let shell = closed_shell(&mut w, &[dome, disk]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('dome',#{shell})")); + let s = one_solid(&w.file(&[solid])); + // A meridian from the equator's vertex to a new vertex at the north pole. + assert_eq!(counts(&s.brep), [2, 1, 2, 2, 2]); + let pole = s.brep.vertices.iter().find(|v| (v.point[2] - 5.0).abs() < 1e-9); + assert!(pole.is_some(), "{:?}", s.brep.vertices); + faces_away(&s.brep, 0, |p| [0.0, 0.0, p[2].clamp(1.0, 2.0)]); +} + +/// A 20 × 20 × 5 plate with a hole of radius 3 through it; with `marked`, its square bounds are +/// FACE_OUTER_BOUNDs, otherwise every bound is a FACE_BOUND and the hole is listed first. +fn plate(marked: bool) -> p21::Exchange { + let mut w = W::default(); + let c = cylinder(&mut w, [10.0, 10.0], 3.0, [0.0, 5.0]); + let mut inner = |w: &mut W, up: f64| { + // About the face's outward normal the hole runs clockwise. + let oe = if up > 0.0 { w.oe(c.circles[1], false) } else { w.oe(c.circles[0], true) }; + vec![w.bound(&[oe], false, true)] + }; + let mut faces = box_faces(&mut w, [0.0; 3], [20.0, 20.0, 5.0], BoxStyle::default(), &mut inner); + if !marked { + let text = w.s.replace("FACE_OUTER_BOUND", "FACE_BOUND"); + w.s = text; + // The hole first. + let mut lines: Vec = w.s.lines().map(str::to_string).collect(); + for l in &mut lines { + if l.contains("ADVANCED_FACE") && l.matches('#').count() == 4 { + let (head, rest) = l.split_once("',(").unwrap(); + let (bounds, tail) = rest.split_once(')').unwrap(); + let parts: Vec<&str> = bounds.split(',').rev().collect(); + *l = format!("{head}',({}){tail}", parts.join(",")); + } + } + w.s = lines.join("\n") + "\n"; + } + faces.push(side(&mut w, &c, false)); + let shell = closed_shell(&mut w, &faces); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('plate',#{shell})")); + w.file(&[solid]) +} + +#[test] +fn a_plate_with_a_through_hole() { + for marked in [true, false] { + let s = one_solid(&plate(marked)); + assert_eq!(counts(&s.brep), [2, 1, 7, 15, 10], "marked {marked}"); + let holed: Vec<&Face> = s.brep.faces.iter().filter(|f| f.loops.len() == 2).collect(); + assert_eq!(holed.len(), 2); + for f in holed { + let Loop::Edges { edges } = &f.loops[0] else { panic!() }; + assert_eq!(edges.len(), 4, "the square is the outer loop"); + } + faces_away(&s.brep, 0, |p| { + let r = ((p[0] - 10.0).powi(2) + (p[1] - 10.0).powi(2)).sqrt(); + if (r - 3.0).abs() < 1e-6 { + // On the hole: material lies away from the axis. + [10.0 + (p[0] - 10.0) * 2.0, 10.0 + (p[1] - 10.0) * 2.0, p[2]] + } else { + [p[0].clamp(0.5, 19.5), p[1].clamp(0.5, 19.5), 2.5] + } + }); + } +} + +#[test] +fn a_surface_model_of_open_shells_is_a_sheet() { + let mut w = W::default(); + let mut faces = box_faces(&mut w, [0.0; 3], [1.0, 1.0, 1.0], BoxStyle::default(), &mut |_, _| Vec::new()); + faces.pop(); + let open = w.add(format!("OPEN_SHELL('',({}))", list(&faces))); + let single = box_faces(&mut w, [5.0; 3], [6.0; 3], BoxStyle::default(), &mut |_, _| Vec::new()); + let one = w.add(format!("OPEN_SHELL('',(#{}))", single[0])); + let model = w.add(format!("SHELL_BASED_SURFACE_MODEL('sheet',(#{open},#{one}))")); + let s = one_solid(&w.file(&[model])); + assert!(s.sheet); + assert_eq!(counts(&s.brep), [1, 2, 6, 12 + 4, 8 + 4]); + assert_eq!(s.brep.regions[0].shells, [0, 1]); + let once = s.brep.edges.iter().filter(|e| e.uses.len() == 1).count(); + assert_eq!(once, 4 + 4); + + // A closed shell in a surface model encloses a region of its own. + let mut w = W::default(); + let faces = box_faces(&mut w, [0.0; 3], [1.0; 3], BoxStyle::default(), &mut |_, _| Vec::new()); + let shell = closed_shell(&mut w, &faces); + let model = w.add(format!("SHELL_BASED_SURFACE_MODEL('',(#{shell}))")); + let s = one_solid(&w.file(&[model])); + assert!(!s.sheet); + assert_eq!(counts(&s.brep), [2, 1, 6, 12, 8]); +} + +#[test] +fn a_solid_with_a_void() { + let mut w = W::default(); + let outer = box_faces(&mut w, [0.0; 3], [10.0; 3], BoxStyle::default(), &mut |_, _| Vec::new()); + let outer = closed_shell(&mut w, &outer); + let inner = box_faces(&mut w, [4.0; 3], [6.0; 3], BoxStyle { flip_faces: true, ..Default::default() }, &mut |_, _| Vec::new()); + let inner = closed_shell(&mut w, &inner); + let void = w.add(format!("ORIENTED_CLOSED_SHELL('',*,#{inner},.F.)")); + let solid = w.add(format!("BREP_WITH_VOIDS('',#{outer},(#{void}))")); + let s = one_solid(&w.file(&[solid])); + assert_eq!(counts(&s.brep), [3, 2, 12, 24, 16]); + assert_eq!(s.brep.regions[0], Region { shells: vec![0], void: false }); + assert_eq!(s.brep.regions[1], Region { shells: vec![0, 1], void: false }); + assert_eq!(s.brep.regions[2], Region { shells: vec![1], void: true }); + faces_away(&s.brep, 0, |_| [5.0; 3]); + // The void's faces face into the cavity, out of the material around it. + for (shell, p, n) in sides(&s.brep) { + if shell == 1 { + let d = sub3([5.0; 3], p); + assert!(d[0] * n[0] + d[1] * n[1] + d[2] * n[2] > 0.0, "{p:?} {n:?}"); + } + } +} + +/// A unit square sheet on z = 0 whose edge from (1, 0) to (1, 1) is a B-spline (quadratic, its +/// middle point off centre so its parameter is not proportional to length), written along or +/// against its curve. +fn spline_sheet(same_sense: bool, closed_basis: bool) -> p21::Exchange { + let mut w = W::default(); + let ps = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]; + let vs: Vec<(u64, V)> = ps.iter().map(|p| (w.vertex(*p), *p)).collect(); + let e0 = w.line_edge(vs[0], vs[1], true, 1.0); + let e1 = if closed_basis { + // A closed polygon spline with its seam halfway up x = 1: the edge from (1, 0) to + // (1, 1) along it crosses the seam. + let pts: Vec = + [[1.0, 0.5, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0]].iter().map(|p| w.pt(*p)).collect(); + let c = w + .add(format!("B_SPLINE_CURVE_WITH_KNOTS('',1,({}),.POLYLINE_FORM.,.T.,.F.,(2,1,1,1,1,2),(0.,1.,2.,3.,4.,5.),.UNSPECIFIED.)", list(&pts))); + w.add(format!("EDGE_CURVE('',#{},#{},#{c},.T.)", vs[1].0, vs[2].0)) + } else { + let order: [V; 3] = + if same_sense { [[1.0, 0.0, 0.0], [1.0, 0.2, 0.0], [1.0, 1.0, 0.0]] } else { [[1.0, 1.0, 0.0], [1.0, 0.8, 0.0], [1.0, 0.0, 0.0]] }; + let pts: Vec = order.iter().map(|p| w.pt(*p)).collect(); + let c = w.add(format!("B_SPLINE_CURVE_WITH_KNOTS('',2,({}),.UNSPECIFIED.,.F.,.F.,(3,3),(2.,5.),.UNSPECIFIED.)", list(&pts))); + let sc = w.add(format!("SURFACE_CURVE('',#{c},(),.CURVE_3D.)")); + w.add(format!("EDGE_CURVE('',#{},#{},#{sc},{})", vs[1].0, vs[2].0, b(same_sense))) + }; + let e2 = w.line_edge(vs[2], vs[3], false, 1.0); + let e3 = w.line_edge(vs[3], vs[0], true, 1.0); + let oes: Vec = [e0, e1, e2, e3].iter().map(|e| w.oe(*e, true)).collect(); + let bound = w.bound(&oes, true, true); + let plane = w.plane([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let face = w.face(&[bound], plane, true); + let shell = w.add(format!("OPEN_SHELL('',(#{face}))")); + let model = w.add(format!("SHELL_BASED_SURFACE_MODEL('',(#{shell}))")); + w.file(&[model]) +} + +#[test] +fn spline_edges_get_their_vertices_parameters() { + for same_sense in [true, false] { + let s = one_solid(&spline_sheet(same_sense, false)); + assert_eq!(counts(&s.brep), [1, 1, 1, 4, 4]); + let e = s.brep.edges.iter().find(|e| matches!(e.curve, BCurve::Spline { .. })).unwrap(); + assert_eq!(e.interval, [2.0, 5.0]); + let BCurve::Spline { knots, .. } = &e.curve else { panic!() }; + assert_eq!(knots, &[2.0, 2.0, 2.0, 5.0, 5.0, 5.0]); + let [a, z] = e.vertices.map(|v| s.brep.vertices[v as usize].point); + assert_eq!((a, z), if same_sense { ([1.0, 0.0, 0.0], [1.0, 1.0, 0.0]) } else { ([1.0, 1.0, 0.0], [1.0, 0.0, 0.0]) }); + } + // An edge across a closed spline's seam is refused, for now. + let r = read_solids(&spline_sheet(true, true)); + assert_eq!(r.solids.len(), 0); + assert!(r.failures[0].message.contains("across a closed spline's seam"), "{:?}", r.failures); +} + +#[test] +fn vertex_parameters_on_lines_conics_and_splines() { + let tol = 1e-7; + // A line written with magnitude 2: the record's line spans one magnitude, the interval is + // in its parameter. + let line = Curve::Line { origin: [1.0, 0.0, 0.0], direction: [0.0, 1.0, 0.0], magnitude: 2.0 }; + let m = map_edge(&line, [1.0, 7.0, 0.0], [1.0, 3.0, 0.0], true, false, false, tol).unwrap(); + assert_eq!(m.interval, [0.0, 2.0]); + assert!(!m.with_step && m.sense_mismatch); + assert_eq!(m.curve, BCurve::Line { start: [1.0, 3.0, 0.0], end: [1.0, 5.0, 0.0] }); + assert!(map_edge(&line, [1.0, 7.0, 0.0], [1.0, 7.0, 0.0], true, true, true, tol).is_err()); + // A circle, either way round, and a full turn. + let position = Placement { origin: [0.0; 3], axis: [0.0, 0.0, 1.0], ref_direction: [1.0, 0.0, 0.0] }; + let circle = Curve::Circle { position, radius: 2.0 }; + let (s, e) = ([0.0, 2.0, 0.0], [-2.0, 0.0, 0.0]); + let m = map_edge(&circle, s, e, true, false, false, tol).unwrap(); + assert!((m.interval[0] - FRAC_PI_2).abs() < 1e-15 && (m.interval[1] - PI).abs() < 1e-15 && m.with_step); + let m = map_edge(&circle, s, e, false, false, false, tol).unwrap(); + assert!((m.interval[0] - PI).abs() < 1e-15 && (m.interval[1] - (TAU + FRAC_PI_2)).abs() < 1e-14 && !m.with_step, "{:?}", m.interval); + let m = map_edge(&circle, e, e, false, true, true, tol).unwrap(); + assert!((m.interval[1] - m.interval[0] - TAU).abs() < 1e-15); + // An ellipse's parameter is not the polar angle. + let ellipse = Curve::Ellipse { position, semi_axis_1: 4.0, semi_axis_2: 1.0 }; + let t: f64 = 0.7; + let p = [4.0 * t.cos(), t.sin(), 0.0]; + let m = map_edge(&ellipse, [4.0, 0.0, 0.0], p, true, false, false, tol).unwrap(); + assert!(m.interval[0].abs() < 1e-15 && (m.interval[1] - t).abs() < 1e-14, "{:?}", m.interval); + // A hyperbola edge: rational quadratic pieces on the STEP parameters of its ends, through + // the hyperbola's points; a parabola: one Bézier whose parameter is STEP's. + let (a, b) = (3.0, 2.0); + let hyperbola = Curve::Hyperbola { position, semi_axis: a, semi_imag_axis: b }; + let at = |t: f64| [a * t.cosh(), b * t.sinh(), 0.0]; + let m = map_edge(&hyperbola, at(1.5), at(-2.5), true, false, false, tol).unwrap(); + assert_eq!(m.interval, [-2.5, 1.5]); + assert!(!m.with_step && m.sense_mismatch); + let c = CurveEval::new(&m.curve).unwrap(); + for k in 0..=40 { + let p = c.point(-2.5 + 4.0 * f64::from(k) / 40.0).unwrap(); + assert!(((p.x / a).powi(2) - (p.y / b).powi(2) - 1.0).abs() < 1e-12 && p.x > 0.0, "{p:?}"); + } + for t in [-2.5, -0.5, 0.5, 1.5] { + assert!(c.point(t).unwrap().dist(v3(at(t))) < 1e-12, "{t}"); + } + let parabola = Curve::Parabola { position, focal_dist: 0.5 }; + let at = |t: f64| [0.5 * t * t, t, 0.0]; + let m = map_edge(¶bola, at(-1.0), at(3.0), true, false, false, tol).unwrap(); + assert_eq!(m.interval, [-1.0, 3.0]); + let c = CurveEval::new(&m.curve).unwrap(); + for k in 0..=8 { + let t = -1.0 + 0.5 * f64::from(k); + assert!(c.point(t).unwrap().dist(v3(at(t))) < 1e-12, "{t}"); + } + // Unsupported curves. + let offset = Curve::OffsetCurve3d { + basis: std::sync::Arc::new(line), + distance: 1.0, + self_intersect: crate::geom::Logical::False, + ref_direction: [0.0, 0.0, 1.0], + }; + assert!(map_edge(&offset, s, e, true, false, false, tol).unwrap_err().contains("not supported yet: OFFSET_CURVE_3D")); +} + +use std::f64::consts::{FRAC_PI_2, PI}; + +/// The file's solids: `cube` with `edit` applied to its text. +fn edited(edit: impl Fn(&str) -> String) -> Solids { + let mut w = W::default(); + let faces = box_faces(&mut w, [0.0; 3], [1.0; 3], BoxStyle::default(), &mut |_, _| Vec::new()); + let shell = closed_shell(&mut w, &faces); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('',#{shell})")); + let mut extra = W { s: String::new(), n: w.n }; + extra.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',(#{solid}),#{})", w.n + 100)); + let text = edit(&(w.s + &extra.s)); + read_solids(&parse(&text)) +} + +#[test] +fn hostile_topology_is_an_error_never_a_panic() { + // Sanity: unedited, the cube reads. + assert_eq!(edited(str::to_string).solids.len(), 1); + let cases: Vec<(&str, Box String>)> = vec![ + ("missing shell", Box::new(|t: &str| t.replace("MANIFOLD_SOLID_BREP('',#", "MANIFOLD_SOLID_BREP('',#9999"))), + ("missing face", Box::new(|t: &str| t.replacen("CLOSED_SHELL('',(#", "CLOSED_SHELL('',(#9999,#", 1))), + ( + "a face twice", + Box::new(|t: &str| { + let (head, rest) = t.split_once("CLOSED_SHELL('',(#").unwrap(); + let first: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + format!("{head}CLOSED_SHELL('',(#{first},#{rest}") + }), + ), + ( + "a face missing", + Box::new(|t: &str| { + let (head, rest) = t.split_once("CLOSED_SHELL('',(#").unwrap(); + let (_, rest) = rest.split_once(',').unwrap(); + format!("{head}CLOSED_SHELL('',({rest}") + }), + ), + ( + "a cycle of oriented faces", + Box::new(|t: &str| format!("{t}#9000=ORIENTED_FACE('',*,#9000,.T.);").replacen("CLOSED_SHELL('',(#", "CLOSED_SHELL('',(#9000,#", 1)), + ), + ( + "a cycle of oriented edges", + Box::new(|t: &str| format!("{t}#9000=ORIENTED_EDGE('',*,*,#9000,.T.);").replacen("EDGE_LOOP('',(#", "EDGE_LOOP('',(#9000,#", 1)), + ), + ( + "an open loop", + Box::new(|t: &str| { + let (head, rest) = t.split_once("EDGE_LOOP('',(#").unwrap(); + let (_, rest) = rest.split_once(',').unwrap(); + format!("{head}EDGE_LOOP('',({rest}") + }), + ), + ("an unsupported vertex", Box::new(|t: &str| t.replacen("=VERTEX_POINT(", "=VERTEX_X(", 1))), + ("an unsupported edge", Box::new(|t: &str| t.replacen("=EDGE_CURVE(", "=SUBEDGE(", 1))), + ( + "a vertex that is a direction", + Box::new(|t: &str| { + let (head, rest) = t.split_once("VERTEX_POINT('',#").unwrap(); + let (_, rest) = rest.split_once(')').unwrap(); + let d: String = t.split_once("=DIRECTION").unwrap().0.rsplit('#').next().unwrap().to_string(); + format!("{head}VERTEX_POINT('',#{d}){rest}") + }), + ), + ("a face on a hyperbola's plane", Box::new(|t: &str| t.replacen("PLANE('',", "HYPERBOLA('',", 1))), + ( + "a huge loop", + Box::new(|t: &str| { + let (head, rest) = t.split_once("EDGE_LOOP('',(#").unwrap(); + let first: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + let many = format!("#{first},").repeat(MAX_LOOP + 1); + format!("{head}EDGE_LOOP('',({many}#{rest}") + }), + ), + ( + "a degenerate torus", + Box::new(|t: &str| { + let (head, rest) = t.split_once("PLANE('',#").unwrap(); + let a: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + let (_, rest) = rest.split_once(')').unwrap(); + format!("{head}DEGENERATE_TOROIDAL_SURFACE('',#{a},1.,2.,.T.){rest}") + }), + ), + ( + "a non-boolean same_sense", + Box::new(|t: &str| { + let (head, rest) = t.split_once("ADVANCED_FACE(").unwrap(); + format!("{head}ADVANCED_FACE({}", rest.replacen(",.T.);", ",.U.);", 1)) + }), + ), + ("an unsupported loop", Box::new(|t: &str| t.replacen("EDGE_LOOP(", "POLY_LOOP(", 1))), + ("an unsupported solid", Box::new(|t: &str| t.replace("MANIFOLD_SOLID_BREP", "FACETED_BREP"))), + ]; + for (what, edit) in cases { + let r = edited(edit); + assert!(r.solids.is_empty() && r.failures.len() == 1, "{what}: {:?} {}", r.failures, r.solids.len()); + eprintln!("{what}: {}", r.failures[0].message); + } +} + +/// The step-conformance parts (tests/step-conformance, CC0): every one reads, its faces facing +/// out of its material; the NURBS cylinder, dome and torus ring, whose faces wind around a +/// spline closed on itself in u without a seam edge, get one along its boundary column. +#[test] +fn step_conformance_parts() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/step-conformance"); + let mut paths: Vec<_> = + std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "step")).collect(); + paths.sort(); + assert_eq!(paths.len(), 17); + for path in paths { + let name = path.file_stem().unwrap().to_string_lossy().into_owned(); + let r = read_solids(&p21::parse(&std::fs::read_to_string(&path).unwrap()).unwrap()); + assert!(r.failures.is_empty() && r.solids.len() == 1, "{name}: {:?}", r.failures); + let b = &r.solids[0].brep; + solidcraft_geom::brep::check::validate(b).unwrap(); + solidcraft_geom::brep::geometry::check(b).unwrap(); + assert_eq!(b.regions.len(), 2, "{name}"); + } +} + +/// Every solid of every STEP file in `SOLIDCRAFT_STEP_CORPUS` (the tangency-labs/models files) +/// read into schema 4: solids read and refused (by reason), faces, edges, time. Run with +/// `--ignored --nocapture`. +#[test] +#[ignore = "needs SOLIDCRAFT_STEP_CORPUS"] +fn corpus_solids_read_into_schema_4() { + let Ok(dir) = std::env::var("SOLIDCRAFT_STEP_CORPUS") else { return }; + let mut paths: Vec<_> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).collect(); + paths.sort(); + for path in paths.iter().filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("step") || e.eq_ignore_ascii_case("stp"))) { + let text = std::fs::read_to_string(path).unwrap_or_default(); + let t0 = std::time::Instant::now(); + let ex = p21::parse(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let parsed = t0.elapsed(); + let r = read_solids(&ex); + let read = t0.elapsed() - parsed; + let faces: usize = r.solids.iter().map(|s| s.brep.faces.len()).sum(); + let edges: usize = r.solids.iter().map(|s| s.brep.edges.len()).sum(); + let sheets = r.solids.iter().filter(|s| s.sheet).count(); + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + println!( + "{name}: {} solids read ({sheets} sheets), {} refused; {faces} faces, {edges} edges; parse {:.0} ms, read {:.0} ms", + r.solids.len(), + r.failures.len(), + parsed.as_secs_f64() * 1e3, + read.as_secs_f64() * 1e3 + ); + let mut reasons: std::collections::BTreeMap = Default::default(); + for f in &r.failures { + // Group by the message without entity numbers. + let key: String = f.message.split('#').map(|s| s.trim_start_matches(|c: char| c.is_ascii_digit())).collect::>().join("#"); + *reasons.entry(key).or_default() += 1; + } + for (m, n) in &reasons { + println!(" {n} × {m}"); + } + let mut notes: std::collections::BTreeMap = Default::default(); + for s in &r.solids { + for n in &s.notes { + let key: String = n.chars().skip_while(|c| c.is_ascii_digit()).collect(); + *notes.entry(key).or_default() += 1; + } + } + for (m, n) in ¬es { + println!(" note in {n} solids: …{m}"); + } + } +} + +/// One STEP surface (entity #10 of `data`, after the common placements) sampled over a box of +/// its own parameters: the mapped record passes through every sample, and its natural normal is +/// STEP's (or its opposite where the mapping says so). +#[track_caller] +fn same_surface(data: &str, us: (f64, f64), vs: (f64, f64)) -> BSurface { + const BASE: &str = "#1=CARTESIAN_POINT('',(0.,0.,0.));#2=DIRECTION('',(0.,0.,1.));#3=DIRECTION('',(1.,0.,0.));\ +#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);#5=DIRECTION('',(0.,1.,0.));#6=AXIS1_PLACEMENT('',#1,#2);"; + let ex = parse(&format!("{BASE}{data}\n")); + let s = crate::read::Reader::new(&ex, crate::read::Units::default()).surface(10).unwrap(); + let n = 8; + let grid: Vec<(f64, f64)> = (0..=n) + .flat_map(|i| (0..=n).map(move |j| (us.0 + (us.1 - us.0) * i as f64 / n as f64, vs.0 + (vs.1 - vs.0) * j as f64 / n as f64))) + .collect(); + let ext = swept::Extent { points: grid.iter().map(|&(u, v)| v3(s.point(u, v).unwrap())).collect(), seam: Vec::new() }; + let (record, reversed) = swept::map_surface(&s, &ext, DEFAULT_TOLERANCE).unwrap(); + solidcraft_geom::brep::label::surface_natural(&record); + let eval = SurfaceEval::new(&record).unwrap(); + for &(u, v) in &grid { + let p = v3(s.point(u, v).unwrap()); + let q = eval.project(p, None, f64::INFINITY).unwrap_or_else(|| panic!("{data}: no parameters at ({u}, {v})")); + let (at, su, sv) = eval.derivs(q[0], q[1]).unwrap(); + assert!(at.dist(p) < 1e-8, "{data}: ({u}, {v}) {p:?} is {} off", at.dist(p)); + let mine = su.cross(sv).normalized().unwrap(); + let theirs = v3(s.normal(u, v).unwrap()); + let agree = mine.dot(theirs) * if reversed { -1.0 } else { 1.0 }; + assert!(agree > 0.999, "{data}: ({u}, {v}) normal {mine:?} vs {theirs:?} (reversed {reversed})"); + } + record +} + +#[test] +fn swept_and_offset_surfaces_are_the_files_own() { + // Revolutions: a slanted line (a cone's frustum), a ball's half circle, an ellipse off the + // axis, a B-spline profile; a circle in a plane through the axis is the ring torus it is. + let line = "#7=CARTESIAN_POINT('',(5.,0.,0.));#8=DIRECTION('',(-2.,0.,4.));#9=VECTOR('',#8,4.47213595499958);#11=LINE('',#7,#9);"; + let r = same_surface(&format!("{line}#10=SURFACE_OF_REVOLUTION('',#11,#6);"), (0.0, 6.0), (0.0, 1.0)); + assert!(matches!(r, BSurface::PlacedRevolution { forward: false, .. })); + // A circle across the axis covers the ball twice, once each way round: its trims say which + // half the surface is. + for (half, vs) in [ + ("(PARAMETER_VALUE(0.)),(PARAMETER_VALUE(3.14159265358979))", (0.2, 3.0)), + ("(PARAMETER_VALUE(3.14159265358979)),(PARAMETER_VALUE(0.))", (3.3, 6.0)), + ] { + let ball = format!( + "#7=AXIS2_PLACEMENT_3D('',#1,#5,#2);#12=CIRCLE('',#7,5.);#11=TRIMMED_CURVE('',#12,{half},.T.,.PARAMETER.);#10=SURFACE_OF_REVOLUTION('',#11,#6);" + ); + assert!(matches!(same_surface(&ball, (0.0, 6.0), vs), BSurface::PlacedRevolution { .. })); + } + let tilted = + "#7=CARTESIAN_POINT('',(10.,0.,1.));#8=AXIS2_PLACEMENT_3D('',#7,#5,#3);#11=ELLIPSE('',#8,3.,2.);#10=SURFACE_OF_REVOLUTION('',#11,#6);"; + same_surface(tilted, (-1.0, 2.0), (-1.0, 1.5)); + let spline = "#7=CARTESIAN_POINT('',(4.,0.,0.));#8=CARTESIAN_POINT('',(6.,0.,2.));#9=CARTESIAN_POINT('',(5.,0.,5.));\ +#11=B_SPLINE_CURVE_WITH_KNOTS('',2,(#7,#8,#9),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.UNSPECIFIED.);#10=SURFACE_OF_REVOLUTION('',#11,#6);"; + same_surface(spline, (0.0, 6.0), (0.05, 0.95)); + for axis in ["#5", "#12"] { + let torus = format!( + "#12=DIRECTION('',(0.,-1.,0.));#7=CARTESIAN_POINT('',(10.,0.,0.));#8=AXIS2_PLACEMENT_3D('',#7,{axis},#3);#11=CIRCLE('',#8,2.);#10=SURFACE_OF_REVOLUTION('',#11,#6);" + ); + assert!(matches!(same_surface(&torus, (0.0, 6.0), (0.0, 6.0)), BSurface::Torus { .. })); + } + // Extrusions: an ellipse askew, a line (a plane strip), a B-spline, a parabola, a hyperbola; + // a circle along its axis either way is a cylinder. + let askew = "#7=ELLIPSE('',#4,9.,4.);#8=DIRECTION('',(0.5,0.25,1.));#9=VECTOR('',#8,2.);#10=SURFACE_OF_LINEAR_EXTRUSION('',#7,#9);"; + assert!(matches!(same_surface(askew, (-1.0, 1.0), (0.0, 5.0)), BSurface::RationalSpline { .. })); + let strip = "#7=VECTOR('',#3,2.);#8=LINE('',#1,#7);#9=VECTOR('',#5,1.);#10=SURFACE_OF_LINEAR_EXTRUSION('',#8,#9);"; + assert!(matches!(same_surface(strip, (-1.0, 3.0), (0.0, 5.0)), BSurface::Spline { .. })); + let spline = "#7=CARTESIAN_POINT('',(4.,0.,0.));#8=CARTESIAN_POINT('',(6.,1.,0.));#9=CARTESIAN_POINT('',(5.,3.,0.));\ +#11=B_SPLINE_CURVE_WITH_KNOTS('',2,(#7,#8,#9),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.UNSPECIFIED.);#12=VECTOR('',#2,3.);#10=SURFACE_OF_LINEAR_EXTRUSION('',#11,#12);"; + same_surface(spline, (0.05, 0.95), (-1.0, 1.0)); + let parabola = "#7=PARABOLA('',#4,0.5);#8=VECTOR('',#2,1.);#10=SURFACE_OF_LINEAR_EXTRUSION('',#7,#8);"; + same_surface(parabola, (-2.0, 3.0), (0.0, 4.0)); + let hyperbola = "#7=HYPERBOLA('',#4,3.,2.);#8=VECTOR('',#2,1.);#10=SURFACE_OF_LINEAR_EXTRUSION('',#7,#8);"; + same_surface(hyperbola, (-2.0, 1.5), (0.0, 4.0)); + for (dir, reversed) in [("#2", false), ("#7", true)] { + let tube = format!("#7=DIRECTION('',(0.,0.,-1.));#8=CIRCLE('',#4,5.);#9=VECTOR('',{dir},3.);#10=SURFACE_OF_LINEAR_EXTRUSION('',#8,#9);"); + assert!(matches!(same_surface(&tube, (0.0, 6.0), (0.0, 2.0)), BSurface::Cylinder { radius: 5.0, .. })); + // Offset along STEP's normal: outward one way, inward the other. + let off = tube.replace("#10=SURFACE", "#11=SURFACE").replace("#10=", "#11=") + "#10=OFFSET_SURFACE('',#11,1.,.F.);"; + let want = if reversed { 4.0 } else { 6.0 }; + assert!(matches!(same_surface(&off, (0.0, 6.0), (0.0, 2.0)), BSurface::Cylinder { radius, .. } if (radius - want).abs() < 1e-12), "{dir}"); + } + // Offsets of each analytic kind, nested ones too. + for (basis, d) in [ + ("PLANE('',#4)", 2.0), + ("CYLINDRICAL_SURFACE('',#4,5.)", -2.0), + ("CONICAL_SURFACE('',#4,5.,0.3)", 1.5), + ("CONICAL_SURFACE('',#4,5.,-0.3)", -1.0), + ("SPHERICAL_SURFACE('',#4,5.)", 1.0), + ("TOROIDAL_SURFACE('',#4,10.,2.)", 1.0), + ] { + let one = format!("#11={basis};#10=OFFSET_SURFACE('',#11,{},.F.);", real(d)); + same_surface(&one, (0.1, 2.0), (0.1, 1.2)); + let two = format!("#12={basis};#11=OFFSET_SURFACE('',#12,{},.F.);#10=OFFSET_SURFACE('',#11,0.5,.U.);", real(d)); + same_surface(&two, (0.1, 2.0), (0.1, 1.2)); + } + // Refused: offsets that collapse or of other kinds, an extrusion in its profile's plane. + let ext = swept::Extent { points: vec![Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 1.0)], seam: Vec::new() }; + for (data, why) in [ + ("#11=CYLINDRICAL_SURFACE('',#4,5.);#10=OFFSET_SURFACE('',#11,-5.,.F.);", "collapses"), + ("#11=TOROIDAL_SURFACE('',#4,10.,2.);#10=OFFSET_SURFACE('',#11,9.,.F.);", "meets its axis"), + ("#11=CYLINDRICAL_SURFACE('',#4,5.);#12=OFFSET_SURFACE('',#11,-6.,.F.);#10=OFFSET_SURFACE('',#12,6.,.F.);", "collapses"), + ("#7=ELLIPSE('',#4,9.,4.);#8=VECTOR('',#3,1.);#10=SURFACE_OF_LINEAR_EXTRUSION('',#7,#8);", "profile's plane"), + ( + "#7=ELLIPSE('',#4,9.,4.);#8=VECTOR('',#2,1.);#11=SURFACE_OF_LINEAR_EXTRUSION('',#7,#8);#10=OFFSET_SURFACE('',#11,1.,.F.);", + "not supported yet", + ), + ] { + let exch = parse(&format!( + "#1=CARTESIAN_POINT('',(0.,0.,0.));#2=DIRECTION('',(0.,0.,1.));#3=DIRECTION('',(1.,0.,0.));#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);{data}\n" + )); + let s = crate::read::Reader::new(&exch, crate::read::Units::default()).surface(10).unwrap(); + let e = swept::map_surface(&s, &ext, DEFAULT_TOLERANCE).unwrap_err(); + assert!(e.contains(why), "{data}: {e}"); + } +} + +/// A frustum (radius 5 at z = 0 to radius 3 at z = 4) whose side is a SURFACE_OF_REVOLUTION of +/// its slanted profile line, with the profile as a seam edge or without one, about +z or −z +/// (STEP's normal ∂angle × ∂profile then points in, and the face says same_sense .F.). +fn frustum(seam: bool, down: bool) -> p21::Exchange { + let mut w = W::default(); + let (pb, pt) = ([5.0, 0.0, 0.0], [3.0, 0.0, 4.0]); + let (vb, vt) = (w.vertex(pb), w.vertex(pt)); + let kb = w.circle([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 5.0); + let kt = w.circle([0.0, 0.0, 4.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 3.0); + let cb = w.add(format!("EDGE_CURVE('',#{vb},#{vb},#{kb},.T.)")); + let ct = w.add(format!("EDGE_CURVE('',#{vt},#{vt},#{kt},.T.)")); + let (o, d) = (w.pt(pb), w.dir([-2.0, 0.0, 4.0])); + let vec = w.add(format!("VECTOR('',#{d},{})", real(20f64.sqrt()))); + let profile = w.add(format!("LINE('',#{o},#{vec})")); + let origin = w.pt([0.0; 3]); + let z = w.dir([0.0, 0.0, if down { -1.0 } else { 1.0 }]); + let axis = w.add(format!("AXIS1_PLACEMENT('',#{origin},#{z})")); + let surface = w.add(format!("SURFACE_OF_REVOLUTION('',#{profile},#{axis})")); + let bounds = if seam { + let s = w.add(format!("EDGE_CURVE('',#{vb},#{vt},#{profile},.T.)")); + let ring = [(cb, true), (s, true), (ct, false), (s, false)]; + let oes: Vec = ring.iter().map(|&(e, o)| w.oe(e, o)).collect(); + vec![w.bound(&oes, true, true)] + } else { + let (x, y) = (w.oe(cb, true), w.oe(ct, false)); + vec![w.bound(&[x], true, true), w.bound(&[y], false, true)] + }; + let side = w.face(&bounds, surface, !down); + let x = w.oe(cb, false); + let bb = w.bound(&[x], true, true); + let plane = w.plane([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let bottom = w.face(&[bb], plane, false); + let x = w.oe(ct, true); + let tb = w.bound(&[x], true, true); + let plane = w.plane([0.0, 0.0, 4.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let top = w.face(&[tb], plane, true); + let shell = closed_shell(&mut w, &[side, bottom, top]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('frustum',#{shell})")); + w.file(&[solid]) +} + +#[test] +fn surfaces_of_revolution_read_as_placed_revolutions() { + for seam in [true, false] { + for down in [false, true] { + let s = one_solid(&frustum(seam, down)); + assert_eq!(counts(&s.brep), [2, 1, 3, 3, 2], "seam {seam} down {down}"); + assert!(s.brep.faces.iter().any(|f| matches!(f.surface, BSurface::PlacedRevolution { forward: false, .. }))); + assert_eq!(s.notes.iter().any(|n| n.contains("seam edges added")), !seam, "{:?}", s.notes); + faces_away(&s.brep, 0, |p| [0.0, 0.0, p[2].clamp(1.0, 3.0)]); + } + } + + // A ball: a half circle (trimmed from the north pole to the south through +x) revolved, + // bounded by its seam meridian alone. STEP's normal there points in: same_sense .F. + let mut w = W::default(); + let (vn, vs) = (w.vertex([0.0, 0.0, 5.0]), w.vertex([0.0, 0.0, -5.0])); + let k = w.circle([0.0; 3], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], 5.0); + let half = w.add(format!("TRIMMED_CURVE('',#{k},(PARAMETER_VALUE(0.)),(PARAMETER_VALUE({})),.T.,.PARAMETER.)", real(PI))); + let e = w.add(format!("EDGE_CURVE('',#{vn},#{vs},#{k},.T.)")); + let (o1, o2) = (w.oe(e, true), w.oe(e, false)); + let bound = w.bound(&[o1, o2], true, true); + let (origin, z) = (w.pt([0.0; 3]), w.dir([0.0, 0.0, 1.0])); + let axis = w.add(format!("AXIS1_PLACEMENT('',#{origin},#{z})")); + let surface = w.add(format!("SURFACE_OF_REVOLUTION('',#{half},#{axis})")); + let face = w.face(&[bound], surface, false); + let shell = closed_shell(&mut w, &[face]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('ball',#{shell})")); + let s = one_solid(&w.file(&[solid])); + assert_eq!(counts(&s.brep), [2, 1, 1, 1, 2]); + faces_away(&s.brep, 0, |_| [0.0; 3]); +} + +#[test] +fn surfaces_of_extrusion_read_as_splines_or_cylinders() { + // A half elliptic prism: the ellipse (6 by 3) from −y round +x to +y, extruded 5 up, cut + // by the plane x = 0. + let mut w = W::default(); + let p = |y: f64, z: f64| [0.0, y, z]; + let v: Vec<(u64, V)> = [p(-3.0, 0.0), p(3.0, 0.0), p(-3.0, 5.0), p(3.0, 5.0)].iter().map(|q| (w.vertex(*q), *q)).collect(); + let ellipse = |w: &mut W, z: f64| { + let a = w.axis([0.0, 0.0, z], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + w.add(format!("ELLIPSE('',#{a},6.,3.)")) + }; + let (eb, et) = (ellipse(&mut w, 0.0), ellipse(&mut w, 5.0)); + let arc_b = w.add(format!("EDGE_CURVE('',#{},#{},#{eb},.T.)", v[0].0, v[1].0)); + let arc_t = w.add(format!("EDGE_CURVE('',#{},#{},#{et},.T.)", v[2].0, v[3].0)); + let up_m = w.line_edge(v[0], v[2], true, 1.0); + let up_p = w.line_edge(v[1], v[3], true, 1.0); + let low = w.line_edge(v[1], v[0], true, 1.0); + let high = w.line_edge(v[2], v[3], true, 1.0); + let z = w.dir([0.0, 0.0, 1.0]); + let vec = w.add(format!("VECTOR('',#{z},2.)")); + let surface = w.add(format!("SURFACE_OF_LINEAR_EXTRUSION('',#{eb},#{vec})")); + let face = |w: &mut W, ring: &[(u64, bool)], surface: u64, sense: bool| { + let oes: Vec = ring.iter().map(|&(e, o)| w.oe(e, o)).collect(); + let b = w.bound(&oes, true, true); + w.face(&[b], surface, sense) + }; + let curved = face(&mut w, &[(arc_b, true), (up_p, true), (arc_t, false), (up_m, false)], surface, true); + let flat_plane = w.plane([0.0; 3], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]); + let flat = face(&mut w, &[(low, true), (up_m, true), (high, true), (up_p, false)], flat_plane, true); + let bottom_plane = w.plane([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let bottom = face(&mut w, &[(arc_b, false), (low, false)], bottom_plane, false); + let top_plane = w.plane([0.0, 0.0, 5.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let top = face(&mut w, &[(arc_t, true), (high, false)], top_plane, true); + let shell = closed_shell(&mut w, &[curved, flat, bottom, top]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('half',#{shell})")); + let s = one_solid(&w.file(&[solid])); + assert_eq!(counts(&s.brep), [2, 1, 4, 6, 4]); + assert!(s.brep.faces.iter().any(|f| matches!(f.surface, BSurface::RationalSpline { .. }))); + faces_away(&s.brep, 0, |q| [q[0].clamp(0.5, 2.0), q[1].clamp(-1.0, 1.0), q[2].clamp(1.0, 4.0)]); + + // A cylinder whose side is its bottom circle extruded up (or down, STEP's normal then + // pointing in), or a narrower cylinder offset out by 1. + for variant in ["up", "down", "offset"] { + let mut w = W::default(); + let c = cylinder(&mut w, [1.0, 2.0], 5.0, [0.0, 10.0]); + let side_face = side(&mut w, &c, true); + let bottom_bound = { + let ob = w.oe(c.circles[0], false); + w.bound(&[ob], true, true) + }; + let bottom_plane = w.plane([1.0, 2.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let bottom = w.face(&[bottom_bound], bottom_plane, false); + let top_bound = { + let ot = w.oe(c.circles[1], true); + w.bound(&[ot], true, true) + }; + let top_plane = w.plane([1.0, 2.0, 10.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let top = w.face(&[top_bound], top_plane, true); + let k = w.circle([1.0, 2.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 5.0); + let d = w.dir([0.0, 0.0, if variant == "down" { -1.0 } else { 1.0 }]); + let vec = w.add(format!("VECTOR('',#{d},1.)")); + let a = w.axis([1.0, 2.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let narrow = w.add(format!("CYLINDRICAL_SURFACE('',#{a},4.)")); + let shell = closed_shell(&mut w, &[bottom, side_face, top]); + let solid = w.add(format!("MANIFOLD_SOLID_BREP('',#{shell})")); + let old = format!("#{}=CYLINDRICAL_SURFACE", c.surface); + let text = w.s.lines().map(|l| { + if l.starts_with(&old) { + match variant { + "offset" => format!("#{}=OFFSET_SURFACE('',#{narrow},1.,.F.);", c.surface), + _ => format!("#{}=SURFACE_OF_LINEAR_EXTRUSION('',#{k},#{vec});", c.surface), + } + } else if variant == "down" && l.starts_with(&format!("#{side_face}=")) { + l.replace(",.T.);", ",.F.);") + } else { + l.to_string() + } + }); + w.s = text.collect::>().join("\n") + "\n"; + assert!(!w.s.contains(&old) && w.s.contains(if variant == "offset" { "OFFSET_SURFACE" } else { "LINEAR_EXTRUSION" })); + assert_eq!(w.s.contains(&format!("#{side_face}=ADVANCED_FACE('',(#{}),#{},.F.)", side_face - 1, c.surface)), variant == "down"); + let s = one_solid(&w.file(&[solid])); + assert_eq!(counts(&s.brep), [2, 1, 3, 3, 2], "{variant}"); + assert!(s.brep.faces.iter().any(|f| matches!(f.surface, BSurface::Cylinder { radius, .. } if (radius - 5.0).abs() < 1e-12)), "{variant}"); + faces_away(&s.brep, 0, |q| [1.0, 2.0, q[2].clamp(1.0, 9.0)]); + } +} + +#[test] +fn parabola_and_hyperbola_edges_bound_faces() { + for kind in ["PARABOLA('',#{a},0.5)", "HYPERBOLA('',#{a},1.,1.)"] { + let mut w = W::default(); + let at = |t: f64| if kind.starts_with("PARABOLA") { [0.5 * t * t, t, 0.0] } else { [t.cosh(), t.sinh(), 0.0] }; + let (p1, p2) = (at(-1.5), at(1.5)); + let (v1, v2) = (w.vertex(p1), w.vertex(p2)); + let a = w.axis([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); + let conic = w.add(kind.replace("{a}", &a.to_string())); + let e1 = w.add(format!("EDGE_CURVE('',#{v1},#{v2},#{conic},.T.)")); + let e2 = w.line_edge((v2, p2), (v1, p1), true, 1.0); + let (o1, o2) = (w.oe(e1, true), w.oe(e2, true)); + let bound = w.bound(&[o1, o2], true, true); + let plane = w.plane([0.0; 3], [0.0, 0.0, -1.0], [1.0, 0.0, 0.0]); + let face = w.face(&[bound], plane, true); + let shell = w.add(format!("OPEN_SHELL('',(#{face}))")); + let model = w.add(format!("SHELL_BASED_SURFACE_MODEL('',(#{shell}))")); + let s = one_solid(&w.file(&[model])); + assert_eq!(counts(&s.brep), [1, 1, 1, 2, 2], "{kind}"); + let e = s.brep.edges.iter().find(|e| !matches!(e.curve, BCurve::Line { .. })).unwrap(); + assert_eq!(e.interval, [-1.5, 1.5]); + let c = CurveEval::new(&e.curve).unwrap(); + for k in 0..=12 { + let p = c.point(-1.5 + 0.25 * f64::from(k)).unwrap(); + let on = if kind.starts_with("PARABOLA") { p.y * p.y - 2.0 * p.x } else { p.x * p.x - p.y * p.y - 1.0 }; + assert!(on.abs() < 1e-12, "{kind}: {p:?}"); + } + } +} diff --git a/crates/step/src/units.rs b/crates/step/src/units.rs new file mode 100644 index 000000000..55caf4603 --- /dev/null +++ b/crates/step/src/units.rs @@ -0,0 +1,109 @@ +//! The units of a representation context (ISO 10303-41 measures and units, ISO 10303-43 +//! representation contexts): GLOBAL_UNIT_ASSIGNED_CONTEXT's length and plane angle units and +//! GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT's distance uncertainty. Missing or malformed units read +//! as millimetres and radians; nothing here fails. + +use crate::p21::{Exchange, Param}; +use crate::read::Units; + +/// What a representation context says about its numbers. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Context { + pub units: Units, + /// The context's distance uncertainty in millimetres (the last UNCERTAINTY_MEASURE_WITH_UNIT + /// it lists), if any. + pub uncertainty: Option, +} + +fn si_prefix(p: Option<&Param>) -> f64 { + match p.and_then(Param::as_enum) { + Some("EXA") => 1e18, + Some("PETA") => 1e15, + Some("TERA") => 1e12, + Some("GIGA") => 1e9, + Some("MEGA") => 1e6, + Some("KILO") => 1e3, + Some("HECTO") => 1e2, + Some("DECA") => 1e1, + Some("DECI") => 1e-1, + Some("CENTI") => 1e-2, + Some("MILLI") => 1e-3, + Some("MICRO") => 1e-6, + Some("NANO") => 1e-9, + Some("PICO") => 1e-12, + Some("FEMTO") => 1e-15, + Some("ATTO") => 1e-18, + _ => 1.0, + } +} + +/// What a unit measures. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnitKind { + Length, + Angle, + Other, +} + +/// A unit's kind and size: millimetres for lengths, radians for plane angles (1 for anything +/// else, or a unit that cannot be read). +pub fn unit_factor(ex: &Exchange, id: u64) -> Option<(UnitKind, f64)> { + factor(ex, id, 0) +} + +fn factor(ex: &Exchange, id: u64, depth: usize) -> Option<(UnitKind, f64)> { + if depth > 4 { + return None; + } + let e = ex.get(id)?; + let kind = if e.has("LENGTH_UNIT") { + UnitKind::Length + } else if e.has("PLANE_ANGLE_UNIT") { + UnitKind::Angle + } else { + UnitKind::Other + }; + if let Some(si) = e.record("SI_UNIT") { + let base = match si.get(1).and_then(Param::as_enum) { + Some("METRE") => 1000.0, + Some("RADIAN") => 1.0, + _ => return Some((kind, 1.0)), + }; + return Some((kind, si_prefix(si.first()) * base)); + } + if let Some(cb) = e.record("CONVERSION_BASED_UNIT") { + let m = ex.get(cb.get(1)?.as_ref_id()?)?; + let mp = m.params(); + let v = mp.first()?.as_f64()?; + let (_, f) = factor(ex, mp.get(1)?.as_ref_id()?, depth + 1)?; + let x = v * f; + return (x.is_finite() && x > 0.0).then_some((kind, x)); + } + Some((kind, 1.0)) +} + +/// The units and uncertainty of the representation context `id`. +pub fn context(ex: &Exchange, id: u64) -> Context { + let mut c = Context::default(); + let Some(e) = ex.get(id) else { return c }; + if let Some(units) = e.record("GLOBAL_UNIT_ASSIGNED_CONTEXT").and_then(|r| r.first()).and_then(Param::as_list) { + for uid in units.iter().filter_map(Param::as_ref_id) { + match unit_factor(ex, uid) { + Some((UnitKind::Length, f)) if f.is_finite() && f > 0.0 => c.units.len = f, + Some((UnitKind::Angle, f)) if f.is_finite() && f > 0.0 => c.units.ang = f, + _ => {} + } + } + } + if let Some(unc) = e.record("GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT").and_then(|r| r.first()).and_then(Param::as_list) { + for uid in unc.iter().filter_map(Param::as_ref_id) { + if let Some(m) = ex.get(uid) + && let Some(v) = m.params().first().and_then(Param::as_f64) + { + let f = m.params().get(1).and_then(Param::as_ref_id).and_then(|x| unit_factor(ex, x)).map(|x| x.1); + c.uncertainty = Some(v * f.unwrap_or(c.units.len)).filter(|t| t.is_finite() && *t > 0.0); + } + } + } + c +} diff --git a/crates/step/src/write.rs b/crates/step/src/write.rs new file mode 100644 index 000000000..44c123545 --- /dev/null +++ b/crates/step/src/write.rs @@ -0,0 +1,521 @@ +//! Writing ISO 10303-21: a DATA section built entity by entity, and [`crate::geom`] curves and +//! surfaces as ISO 10303-42 entities. Identical geometric entities are written once and shared, +//! as the reader shares them; topological ones are distinct ([`Writer::add_distinct`]). +//! [`topology`] writes a schema 4 record's solids. + +use std::collections::HashMap; +use std::fmt::Write as _; + +use crate::geom::{ + Associated, Axis1, BSplineCurve, BSplineSurface, Curve, CurveForm, KnotSpec, Logical, P3, Placement, PreferredRep, Surface, SurfaceCurveKind, + SurfaceForm, Trim, TrimPreference, +}; +use crate::p21::Param; + +pub mod topology; + +/// A real as Part 21 writes it: always with a decimal point, exponent as `E`. +pub fn real(x: f64) -> String { + if !x.is_finite() { + return "0.".into(); + } + let s = format!("{x:?}"); + match s.split_once('e') { + Some((m, e)) => { + let m = if m.contains('.') { m.to_string() } else { format!("{m}.") }; + format!("{m}E{e}") + } + None if s.contains('.') => s, + None => format!("{s}."), + } +} + +/// A string literal: quotes doubled, non-ASCII as `\X2\` UTF-16 runs. +pub fn string(s: &str) -> String { + let mut o = String::from("'"); + for c in s.chars() { + match c { + '\'' => o.push_str("''"), + '\\' => o.push_str("\\\\"), + c if c.is_ascii() && !c.is_ascii_control() => o.push(c), + c if c.is_ascii_control() => {} + c => { + o.push_str("\\X2\\"); + let mut buf = [0u16; 2]; + for u in c.encode_utf16(&mut buf) { + let _ = write!(o, "{u:04X}"); + } + o.push_str("\\X0\\"); + } + } + } + o.push('\''); + o +} + +fn param(p: &Param, o: &mut String) { + match p { + Param::Int(i) => { + let _ = write!(o, "{i}"); + } + Param::Real(x) => o.push_str(&real(*x)), + Param::Str(s) => o.push_str(&string(s)), + Param::Enum(e) => { + let _ = write!(o, ".{e}."); + } + Param::Ref(r) => { + let _ = write!(o, "#{r}"); + } + Param::List(v) => { + o.push('('); + params(v, o); + o.push(')'); + } + Param::Typed(name, v) => { + o.push_str(name); + o.push('('); + params(v, o); + o.push(')'); + } + Param::Binary(b) => { + let _ = write!(o, "\"{b}\""); + } + Param::Null => o.push('$'), + Param::Derived => o.push('*'), + } +} + +fn params(v: &[Param], o: &mut String) { + for (i, p) in v.iter().enumerate() { + if i > 0 { + o.push(','); + } + param(p, o); + } +} + +/// A DATA section under construction. Entities are numbered from 1 in the order they are added; +/// adding an entity identical to an earlier one returns the earlier one's id. +#[derive(Default)] +pub struct Writer { + lines: Vec, + shared: HashMap, +} + +impl Writer { + pub fn new() -> Self { + Self::default() + } + + fn push(&mut self, body: String) -> u64 { + if let Some(id) = self.shared.get(&body) { + return *id; + } + let id = self.push_distinct(&body); + self.shared.insert(body, id); + id + } + + fn push_distinct(&mut self, body: &str) -> u64 { + let id = self.lines.len() as u64 + 1; + self.lines.push(format!("#{id}={body};")); + id + } + + fn simple(name: &str, p: &[Param]) -> String { + let mut body = format!("{name}("); + params(p, &mut body); + body.push(')'); + body + } + + /// A simple entity instance, shared with an identical earlier one. + pub fn add(&mut self, name: &str, p: &[Param]) -> u64 { + self.push(Self::simple(name, p)) + } + + /// A simple entity instance of its own, even when an identical one exists: an entity whose + /// identity matters (two vertices at one point are two vertices; a product is one product). + pub fn add_distinct(&mut self, name: &str, p: &[Param]) -> u64 { + self.push_distinct(&Self::simple(name, p)) + } + + /// A complex entity instance; its records are written in alphabetical order, as Part 21 asks. + pub fn add_complex(&mut self, records: &[(&str, Vec)]) -> u64 { + let mut sorted: Vec<&(&str, Vec)> = records.iter().collect(); + sorted.sort_by(|a, b| a.0.cmp(b.0)); + let mut body = String::from("("); + for (name, p) in sorted { + body.push_str(name); + body.push('('); + params(p, &mut body); + body.push(')'); + } + body.push(')'); + self.push(body) + } + + /// Entities added so far. + pub fn len(&self) -> usize { + self.lines.len() + } + + pub fn is_empty(&self) -> bool { + self.lines.is_empty() + } + + /// The DATA section's entity lines. + pub fn data(&self) -> String { + let mut o = String::new(); + for l in &self.lines { + o.push_str(l); + o.push('\n'); + } + o + } + + /// A whole exchange file around the entities written so far. + pub fn file(&self, name: &str, schema: &str) -> String { + format!( + "ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION((''),'2;1');\nFILE_NAME({},'',(''),(''),'SolidCraft','SolidCraft','');\nFILE_SCHEMA(({}));\nENDSEC;\nDATA;\n{}ENDSEC;\nEND-ISO-10303-21;\n", + string(name), + string(schema), + self.data() + ) + } +} + +fn s() -> Param { + Param::Str(String::new()) +} +fn r(id: u64) -> Param { + Param::Ref(id) +} +fn f(x: f64) -> Param { + Param::Real(x) +} +fn e(name: &str) -> Param { + Param::Enum(name.into()) +} +fn list(v: Vec) -> Param { + Param::List(v) +} +fn reals(v: &[f64]) -> Param { + list(v.iter().map(|x| f(*x)).collect()) +} +fn ints(v: &[usize]) -> Param { + list(v.iter().map(|x| Param::Int(*x as i64)).collect()) +} +fn logical(l: Logical) -> Param { + e(match l { + Logical::True => "T", + Logical::False => "F", + Logical::Unknown => "U", + }) +} +fn boolean(b: bool) -> Param { + e(if b { "T" } else { "F" }) +} + +fn curve_form(f: CurveForm) -> Param { + e(match f { + CurveForm::PolylineForm => "POLYLINE_FORM", + CurveForm::CircularArc => "CIRCULAR_ARC", + CurveForm::EllipticArc => "ELLIPTIC_ARC", + CurveForm::ParabolicArc => "PARABOLIC_ARC", + CurveForm::HyperbolicArc => "HYPERBOLIC_ARC", + CurveForm::Unspecified => "UNSPECIFIED", + }) +} + +fn surface_form(f: SurfaceForm) -> Param { + e(match f { + SurfaceForm::PlaneSurf => "PLANE_SURF", + SurfaceForm::CylindricalSurf => "CYLINDRICAL_SURF", + SurfaceForm::ConicalSurf => "CONICAL_SURF", + SurfaceForm::SphericalSurf => "SPHERICAL_SURF", + SurfaceForm::ToroidalSurf => "TOROIDAL_SURF", + SurfaceForm::SurfOfRevolution => "SURF_OF_REVOLUTION", + SurfaceForm::RuledSurf => "RULED_SURF", + SurfaceForm::GeneralisedCone => "GENERALISED_CONE", + SurfaceForm::QuadricSurf => "QUADRIC_SURF", + SurfaceForm::SurfOfLinearExtrusion => "SURF_OF_LINEAR_EXTRUSION", + SurfaceForm::Unspecified => "UNSPECIFIED", + }) +} + +fn knot_spec(k: KnotSpec) -> Param { + e(match k { + KnotSpec::UniformKnots => "UNIFORM_KNOTS", + KnotSpec::QuasiUniformKnots => "QUASI_UNIFORM_KNOTS", + KnotSpec::PiecewiseBezierKnots => "PIECEWISE_BEZIER_KNOTS", + KnotSpec::Unspecified => "UNSPECIFIED", + }) +} + +/// Writes geometry into a [`Writer`]. Lengths are written in millimetres and angles in radians: +/// the representation context the caller writes must say so. +pub struct GeomWriter<'w> { + pub w: &'w mut Writer, + /// The 2D parameter-space context pcurves refer to, once written. + pcurve_context: Option, +} + +impl<'w> GeomWriter<'w> { + pub fn new(w: &'w mut Writer) -> Self { + GeomWriter { w, pcurve_context: None } + } + + fn coords(p: P3, dim: usize) -> Param { + reals(p.get(..dim).unwrap_or(&p)) + } + + pub fn point(&mut self, p: P3) -> u64 { + self.point_in(p, 3) + } + + fn point_in(&mut self, p: P3, dim: usize) -> u64 { + self.w.add("CARTESIAN_POINT", &[s(), Self::coords(p, dim)]) + } + + fn direction_in(&mut self, d: P3, dim: usize) -> u64 { + self.w.add("DIRECTION", &[s(), Self::coords(d, dim)]) + } + + pub fn direction(&mut self, d: P3) -> u64 { + self.direction_in(d, 3) + } + + fn vector_in(&mut self, d: P3, magnitude: f64, dim: usize) -> u64 { + let d = self.direction_in(d, dim); + self.w.add("VECTOR", &[s(), r(d), f(magnitude)]) + } + + fn placement_in(&mut self, p: &Placement, dim: usize) -> u64 { + let o = self.point_in(p.origin, dim); + let x = self.direction_in(p.ref_direction, dim); + if dim == 2 { + self.w.add("AXIS2_PLACEMENT_2D", &[s(), r(o), r(x)]) + } else { + let z = self.direction_in(p.axis, dim); + self.w.add("AXIS2_PLACEMENT_3D", &[s(), r(o), r(z), r(x)]) + } + } + + pub fn placement(&mut self, p: &Placement) -> u64 { + self.placement_in(p, 3) + } + + pub fn axis1(&mut self, a: &Axis1) -> u64 { + let o = self.point(a.origin); + let d = self.direction(a.direction); + self.w.add("AXIS1_PLACEMENT", &[s(), r(o), r(d)]) + } + + /// A 3D curve. + pub fn curve(&mut self, c: &Curve) -> u64 { + self.curve_in(c, 3) + } + + fn curve_in(&mut self, c: &Curve, dim: usize) -> u64 { + match c { + Curve::Line { origin, direction, magnitude } => { + let p = self.point_in(*origin, dim); + let v = self.vector_in(*direction, *magnitude, dim); + self.w.add("LINE", &[s(), r(p), r(v)]) + } + Curve::Circle { position, radius } => { + let p = self.placement_in(position, dim); + self.w.add("CIRCLE", &[s(), r(p), f(*radius)]) + } + Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => { + let p = self.placement_in(position, dim); + self.w.add("ELLIPSE", &[s(), r(p), f(*semi_axis_1), f(*semi_axis_2)]) + } + Curve::Hyperbola { position, semi_axis, semi_imag_axis } => { + let p = self.placement_in(position, dim); + self.w.add("HYPERBOLA", &[s(), r(p), f(*semi_axis), f(*semi_imag_axis)]) + } + Curve::Parabola { position, focal_dist } => { + let p = self.placement_in(position, dim); + self.w.add("PARABOLA", &[s(), r(p), f(*focal_dist)]) + } + Curve::BSpline(b) => self.bspline_curve(b, dim), + Curve::Polyline(pts) => { + let ids = pts.iter().map(|p| r(self.point_in(*p, dim))).collect(); + self.w.add("POLYLINE", &[s(), list(ids)]) + } + Curve::Trimmed { basis, trim_1, trim_2, sense, preference } => { + let b = self.curve_in(basis, dim); + let t1 = self.trims(trim_1, dim); + let t2 = self.trims(trim_2, dim); + let pref = e(match preference { + TrimPreference::Cartesian => "CARTESIAN", + TrimPreference::Parameter => "PARAMETER", + TrimPreference::Unspecified => "UNSPECIFIED", + }); + self.w.add("TRIMMED_CURVE", &[s(), r(b), t1, t2, boolean(*sense), pref]) + } + Curve::SurfaceCurve { kind, curve_3d, associated, master } => { + let c3 = self.curve_in(curve_3d, 3); + let items = associated + .iter() + .map(|a| match a { + Associated::Pcurve(pc) => { + let surf = self.surface(&pc.surface); + let c2 = self.curve_in(&pc.curve, 2); + let ctx = self.pcurve_context(); + let rep = self.w.add("DEFINITIONAL_REPRESENTATION", &[s(), list(vec![r(c2)]), r(ctx)]); + r(self.w.add("PCURVE", &[s(), r(surf), r(rep)])) + } + Associated::Surface(sf) => r(self.surface(sf)), + }) + .collect(); + let name = match kind { + SurfaceCurveKind::Surface => "SURFACE_CURVE", + SurfaceCurveKind::Seam => "SEAM_CURVE", + SurfaceCurveKind::Intersection => "INTERSECTION_CURVE", + SurfaceCurveKind::BoundedSurface => "BOUNDED_SURFACE_CURVE", + }; + let m = e(match master { + PreferredRep::Curve3d => "CURVE_3D", + PreferredRep::PcurveS1 => "PCURVE_S1", + PreferredRep::PcurveS2 => "PCURVE_S2", + }); + self.w.add(name, &[s(), r(c3), list(items), m]) + } + Curve::OffsetCurve3d { basis, distance, self_intersect, ref_direction } => { + let b = self.curve_in(basis, 3); + let d = self.direction(*ref_direction); + self.w.add("OFFSET_CURVE_3D", &[s(), r(b), f(*distance), logical(*self_intersect), r(d)]) + } + } + } + + fn pcurve_context(&mut self) -> u64 { + if let Some(c) = self.pcurve_context { + return c; + } + let c = self.w.add_complex(&[ + ("GEOMETRIC_REPRESENTATION_CONTEXT", vec![Param::Int(2)]), + ("PARAMETRIC_REPRESENTATION_CONTEXT", vec![]), + ("REPRESENTATION_CONTEXT", vec![Param::Str("2D SPACE".into()), s()]), + ]); + self.pcurve_context = Some(c); + c + } + + fn trims(&mut self, t: &[Trim], dim: usize) -> Param { + list( + t.iter() + .map(|t| match t { + Trim::Point(p) => r(self.point_in(*p, dim)), + Trim::Parameter(x) => Param::Typed("PARAMETER_VALUE".into(), vec![f(*x)]), + }) + .collect(), + ) + } + + fn bspline_curve(&mut self, b: &BSplineCurve, dim: usize) -> u64 { + let ctrl = list(b.points.iter().map(|p| r(self.point_in(*p, dim))).collect()); + let common = vec![Param::Int(b.degree as i64), ctrl, curve_form(b.form), logical(b.closed), logical(b.self_intersect)]; + let knots = vec![ints(&b.multiplicities), reals(&b.knots), knot_spec(b.knot_spec)]; + match &b.weights { + None => { + let mut p = vec![s()]; + p.extend(common); + p.extend(knots); + self.w.add("B_SPLINE_CURVE_WITH_KNOTS", &p) + } + Some(w) => self.w.add_complex(&[ + ("BOUNDED_CURVE", vec![]), + ("B_SPLINE_CURVE", common), + ("B_SPLINE_CURVE_WITH_KNOTS", knots), + ("CURVE", vec![]), + ("GEOMETRIC_REPRESENTATION_ITEM", vec![]), + ("RATIONAL_B_SPLINE_CURVE", vec![reals(w)]), + ("REPRESENTATION_ITEM", vec![s()]), + ]), + } + } + + /// A surface. + pub fn surface(&mut self, sf: &Surface) -> u64 { + match sf { + Surface::Plane { position } => { + let p = self.placement(position); + self.w.add("PLANE", &[s(), r(p)]) + } + Surface::Cylinder { position, radius } => { + let p = self.placement(position); + self.w.add("CYLINDRICAL_SURFACE", &[s(), r(p), f(*radius)]) + } + Surface::Cone { position, radius, semi_angle } => { + let p = self.placement(position); + self.w.add("CONICAL_SURFACE", &[s(), r(p), f(*radius), f(*semi_angle)]) + } + Surface::Sphere { position, radius } => { + let p = self.placement(position); + self.w.add("SPHERICAL_SURFACE", &[s(), r(p), f(*radius)]) + } + Surface::Torus { position, major_radius, minor_radius } => { + let p = self.placement(position); + self.w.add("TOROIDAL_SURFACE", &[s(), r(p), f(*major_radius), f(*minor_radius)]) + } + Surface::DegenerateTorus { position, major_radius, minor_radius, select_outer } => { + let p = self.placement(position); + self.w.add("DEGENERATE_TOROIDAL_SURFACE", &[s(), r(p), f(*major_radius), f(*minor_radius), boolean(*select_outer)]) + } + Surface::BSpline(b) => self.bspline_surface(b), + Surface::Revolution { profile, axis } => { + let c = self.curve(profile); + let a = self.axis1(axis); + self.w.add("SURFACE_OF_REVOLUTION", &[s(), r(c), r(a)]) + } + Surface::Extrusion { profile, direction, magnitude } => { + let c = self.curve(profile); + let v = self.vector_in(*direction, *magnitude, 3); + self.w.add("SURFACE_OF_LINEAR_EXTRUSION", &[s(), r(c), r(v)]) + } + Surface::Offset { basis, distance, self_intersect } => { + let b = self.surface(basis); + self.w.add("OFFSET_SURFACE", &[s(), r(b), f(*distance), logical(*self_intersect)]) + } + Surface::RectangularTrimmed { basis, u1, u2, v1, v2, u_sense, v_sense } => { + let b = self.surface(basis); + self.w.add("RECTANGULAR_TRIMMED_SURFACE", &[s(), r(b), f(*u1), f(*u2), f(*v1), f(*v2), boolean(*u_sense), boolean(*v_sense)]) + } + } + } + + fn bspline_surface(&mut self, b: &BSplineSurface) -> u64 { + let ctrl = list(b.points.iter().map(|row| list(row.iter().map(|p| r(self.point(*p))).collect())).collect()); + let common = vec![ + Param::Int(b.u_degree as i64), + Param::Int(b.v_degree as i64), + ctrl, + surface_form(b.form), + logical(b.u_closed), + logical(b.v_closed), + logical(b.self_intersect), + ]; + let knots = vec![ints(&b.u_multiplicities), ints(&b.v_multiplicities), reals(&b.u_knots), reals(&b.v_knots), knot_spec(b.knot_spec)]; + match &b.weights { + None => { + let mut p = vec![s()]; + p.extend(common); + p.extend(knots); + self.w.add("B_SPLINE_SURFACE_WITH_KNOTS", &p) + } + Some(w) => self.w.add_complex(&[ + ("BOUNDED_SURFACE", vec![]), + ("B_SPLINE_SURFACE", common), + ("B_SPLINE_SURFACE_WITH_KNOTS", knots), + ("GEOMETRIC_REPRESENTATION_ITEM", vec![]), + ("RATIONAL_B_SPLINE_SURFACE", vec![list(w.iter().map(|row| reals(row)).collect())]), + ("REPRESENTATION_ITEM", vec![s()]), + ("SURFACE", vec![]), + ]), + } + } +} diff --git a/crates/step/src/write/topology.rs b/crates/step/src/write/topology.rs new file mode 100644 index 000000000..eb3574999 --- /dev/null +++ b/crates/step/src/write/topology.rs @@ -0,0 +1,646 @@ +//! A schema 4 record ([`solidcraft_geom::brep`]) as ISO 10303-42 topology, the inverse of +//! [`crate::topology`]. Each bounded material region becomes a MANIFOLD_SOLID_BREP, or a +//! BREP_WITH_VOIDS when voids lie inside it (each void's CLOSED_SHELL through an +//! ORIENTED_CLOSED_SHELL); the open shells become one SHELL_BASED_SURFACE_MODEL. Faces are ADVANCED_FACEs on their +//! exact surface, bounded by a FACE_OUTER_BOUND (the loop that runs counter-clockwise in (u, v)) +//! and FACE_BOUNDs of EDGE_LOOPs of ORIENTED_EDGEs, or of VERTEX_LOOPs. Each EDGE_CURVE runs on +//! its exact curve from the record edge's start vertex (interval min) to its end (max), its +//! same_sense .T.; an edge one or two faces use is a SURFACE_CURVE (SEAM_CURVE when one face +//! uses it twice) carrying the PCURVEs of its uses: the record's exact pcurves, in the STEP +//! surface's parameters. Nothing is approximated: what STEP cannot state exactly is refused +//! ("not supported yet: …"). +//! +//! Parameters: every record curve keeps its parameter in STEP (a line's runs from its start to +//! its end as the record's does). A record surface's (u, v) is a linear image of its STEP +//! surface's ([`Map`]): a plane is written on the orthonormal frame of its axes, a cone that +//! narrows along its axis (negative half angle) with its axis turned over, a revolution with the +//! angle first; pcurves go through the same map. Where the map reverses orientation, the +//! record's natural normal is STEP's reversed, and the faces' same_sense says so. +//! +//! Sides: every face's normal points out of the material, as the record's shells have them (a +//! void's faces into the void, its ORIENTED_CLOSED_SHELL orientation .T.). A face is written with +//! the side its first use needs (its same_sense, and its loops run counter-clockwise about that +//! side's normal); a later use of the other side refers to it through an ORIENTED_FACE. + +use solidcraft_geom::prelude::*; +use std::sync::Arc; + +use solidcore_record::brep::{Brep, Curve as BCurve, Curve2, Edge, Face, Frame, Loop, Shell, Surface as BSurface}; + +use super::{GeomWriter, boolean, list, r, s}; +use crate::geom::{ + Associated, Axis1, BSplineCurve, BSplineSurface, Curve, CurveForm, KnotSpec, Logical, P3, Pcurve, Placement, PreferredRep, Surface, + SurfaceCurveKind, SurfaceForm, cross, dot, norm, scale, sub, +}; +use crate::p21::Param; +use crate::read::R; + +/// Points of each use's pcurve the loops' (u, v) areas are taken over. +const AREA_SAMPLES: usize = 16; +/// How far (relative to its scales) a revolution's placement may be from one that keeps it a +/// revolution, or from a similarity. +const SIMILAR: f64 = 1e-9; + +fn unsupported(what: impl std::fmt::Display) -> String { + format!("not supported yet: STEP export of {what}") +} + +/// The record's surface parameters as the STEP surface's: `(u', v') = m · (u, v)`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Map { + pub m: [[f64; 2]; 2], +} + +impl Map { + pub const IDENTITY: Map = Map { m: [[1.0, 0.0], [0.0, 1.0]] }; + + pub fn apply(&self, [u, v]: [f64; 2]) -> [f64; 2] { + let [a, b] = self.m; + [a[0] * u + a[1] * v, b[0] * u + b[1] * v] + } + + /// The record's natural normal is the STEP surface's (both are ∂S/∂u × ∂S/∂v, so they differ + /// by the sign of the map's determinant). + pub fn keeps_normal(&self) -> bool { + let [a, b] = self.m; + a[0] * b[1] - a[1] * b[0] > 0.0 + } +} + +fn placement(f: &Frame) -> Placement { + Placement { origin: f.origin, axis: cross(f.x_axis, f.y_axis), ref_direction: f.x_axis } +} + +fn unit(a: P3, what: &str) -> R { + let n = norm(a); + if n.is_finite() && n > 0.0 { Ok(scale(a, 1.0 / n)) } else { Err(format!("a degenerate {what}")) } +} + +/// Full knots (each repeated by its multiplicity) as STEP's distinct knots and multiplicities. +fn knots_of(full: &[f64]) -> (Vec, Vec) { + let (mut knots, mut mults) = (Vec::new(), Vec::::new()); + for &k in full { + match (knots.last(), mults.last_mut()) { + (Some(last), Some(m)) if *last == k => *m += 1, + _ => { + knots.push(k); + mults.push(1); + } + } + } + (knots, mults) +} + +fn degree(knots: &[f64], count: usize) -> R { + knots.len().checked_sub(count + 1).filter(|d| *d >= 1).ok_or_else(|| "a B-spline whose knots do not fit its points".to_string()) +} + +fn bspline_curve(full: &[f64], points: Vec, weights: Option>) -> R { + let degree = degree(full, points.len())?; + let (knots, multiplicities) = knots_of(full); + Ok(Curve::BSpline(Box::new(BSplineCurve { + degree, + points, + weights, + knots, + multiplicities, + form: CurveForm::Unspecified, + closed: Logical::Unknown, + self_intersect: Logical::Unknown, + knot_spec: KnotSpec::Unspecified, + }))) +} + +/// Homogeneous `[x w, y w, z w, w]` as the point and its weight. +fn rational(h: &[f64; 4]) -> R<(P3, f64)> { + let w = h[3]; + if w > 0.0 { Ok(([h[0] / w, h[1] / w, h[2] / w], w)) } else { Err("a non-positive rational weight".into()) } +} + +/// A record curve as the STEP curve with the same parameter. +pub fn curve(c: &BCurve) -> R { + Ok(match c { + BCurve::Line { start, end } => { + let d = sub(*end, *start); + Curve::Line { origin: *start, direction: unit(d, "line")?, magnitude: norm(d) } + } + BCurve::Circle { frame, radius } => Curve::Circle { position: placement(frame), radius: *radius }, + BCurve::Ellipse { frame, radii } => Curve::Ellipse { position: placement(frame), semi_axis_1: radii[0], semi_axis_2: radii[1] }, + BCurve::Polyline { points } => Curve::Polyline(points.clone()), + BCurve::Spline { knots, points } => bspline_curve(knots, points.clone(), None)?, + BCurve::RationalSpline { knots, homogeneous } => { + let (points, weights): (Vec, Vec) = homogeneous.iter().map(rational).collect::>>()?.into_iter().unzip(); + bspline_curve(knots, points, Some(weights))? + } + BCurve::SurfaceIntersection { .. } => return Err(unsupported("a traced intersection curve")), + }) +} + +fn bspline_surface(u_knots: &[f64], v_knots: &[f64], points: Vec>, weights: Option>>) -> R { + let (u_degree, v_degree) = (degree(u_knots, points.len())?, degree(v_knots, points.first().map_or(0, Vec::len))?); + let ((u_knots, u_multiplicities), (v_knots, v_multiplicities)) = (knots_of(u_knots), knots_of(v_knots)); + Ok(Surface::BSpline(Box::new(BSplineSurface { + u_degree, + v_degree, + points, + weights, + u_knots, + u_multiplicities, + v_knots, + v_multiplicities, + form: SurfaceForm::Unspecified, + u_closed: Logical::Unknown, + v_closed: Logical::Unknown, + self_intersect: Logical::Unknown, + knot_spec: KnotSpec::Unspecified, + }))) +} + +/// The plane `origin + u a + v b` on the orthonormal frame of `a` and the normal `a × b`: the +/// record's (u, v) map linearly onto STEP's, keeping the normal. +fn plane(origin: P3, a: P3, b: P3) -> R<(Surface, Map)> { + let x = unit(a, "plane")?; + let z = unit(cross(a, b), "plane")?; + let y = cross(z, x); + let m = [[dot(a, x), dot(b, x)], [dot(a, y), dot(b, y)]]; + Ok((Surface::Plane { position: Placement { origin, axis: z, ref_direction: x } }, Map { m })) +} + +/// A column-major affine matrix as its linear part (columns) and translation. +type Affine = ([P3; 3], P3); + +fn affine(m: &[[f64; 4]; 4]) -> Affine { + let col = |c: usize| [m[c][0], m[c][1], m[c][2]]; + ([col(0), col(1), col(2)], col(3)) +} + +fn linear(l: &[P3; 3], p: P3) -> P3 { + let [a, b, c] = l; + [0, 1, 2].map(|i| a[i] * p[0] + b[i] * p[1] + c[i] * p[2]) +} + +fn moved((l, t): &Affine, p: P3) -> P3 { + let q = linear(l, p); + [q[0] + t[0], q[1] + t[1], q[2] + t[2]] +} + +/// A record curve mapped by an affine map: the same kind of curve on the same parameter. A +/// circle or ellipse stays one only under a similarity (`similarity`: its scale). +fn placed_curve(c: &BCurve, a: &Affine, similarity: Option) -> R { + let (l, _) = a; + let conic = |f: &Frame| -> R<(Frame, f64)> { + let k = similarity.ok_or_else(|| unsupported("a revolution of a conic under a non-uniform placement"))?; + Ok((Frame { origin: moved(a, f.origin), x_axis: unit(linear(l, f.x_axis), "frame")?, y_axis: unit(linear(l, f.y_axis), "frame")? }, k)) + }; + Ok(match c { + BCurve::Line { start, end } => BCurve::Line { start: moved(a, *start), end: moved(a, *end) }, + BCurve::Circle { frame, radius } => { + let (frame, k) = conic(frame)?; + BCurve::Circle { frame, radius: radius * k } + } + BCurve::Ellipse { frame, radii } => { + let (frame, k) = conic(frame)?; + BCurve::Ellipse { frame, radii: radii.map(|r| r * k) } + } + BCurve::Polyline { points } => BCurve::Polyline { points: points.iter().map(|p| moved(a, *p)).collect() }, + BCurve::Spline { knots, points } => BCurve::Spline { knots: knots.clone(), points: points.iter().map(|p| moved(a, *p)).collect() }, + BCurve::RationalSpline { knots, homogeneous } => BCurve::RationalSpline { + knots: knots.clone(), + homogeneous: homogeneous + .iter() + .map(|h| { + let (p, w) = rational(h)?; + let q = moved(a, p); + Ok([q[0] * w, q[1] * w, q[2] * w, w]) + }) + .collect::>()?, + }, + BCurve::SurfaceIntersection { .. } => return Err(unsupported("a revolution of a traced intersection curve")), + }) +} + +/// `profile` revolved about `origin` and `axis`, then placed by `matrix`, as a +/// SURFACE_OF_REVOLUTION. Exact when the placement maps revolutions about the axis onto +/// revolutions: a rotation (or reflection, which turns the angle back) after one scale across +/// the axis and another along it. STEP's u is the angle, v the profile's parameter. +fn revolution(profile: &BCurve, origin: P3, axis: P3, matrix: &[[f64; 4]; 4], forward: bool) -> R<(Surface, Map)> { + let a = affine(matrix); + let l = &a.0; + let k = unit(axis, "revolution axis")?; + // An orthonormal frame (e1, e2, k): the placement scales e1 and e2 alike, keeps them + // orthogonal to each other and to the image of k. + let e1 = unit(if k[0].abs() < 0.9 { cross(k, [1.0, 0.0, 0.0]) } else { cross(k, [0.0, 1.0, 0.0]) }, "revolution axis")?; + let e2 = cross(k, e1); + let (le1, le2, lk) = (linear(l, e1), linear(l, e2), linear(l, k)); + let (across, along) = (norm(le1), norm(lk)); + let near = |x: f64, y: f64| (x - y).abs() <= SIMILAR * across.max(along); + let keeps_revolutions = across > 0.0 + && along > 0.0 + && near(norm(le2), across) + && [dot(le1, le2), dot(le1, lk), dot(le2, lk)].iter().all(|d| near(*d / across.max(along), 0.0)); + if !keeps_revolutions { + return Err(unsupported("a revolution under a placement that does not keep it one")); + } + let turn = if dot(cross(l[0], l[1]), l[2]) > 0.0 { 1.0 } else { -1.0 }; + let similarity = near(across, along).then_some(across); + let profile = curve(&placed_curve(profile, &a, similarity)?)?; + let axis = Axis1 { origin: moved(&a, origin), direction: scale(lk, 1.0 / along) }; + // Record (u, v) is (profile, angle) when `forward`, else (angle, profile). + let m = if forward { [[0.0, turn], [1.0, 0.0]] } else { [[turn, 0.0], [0.0, 1.0]] }; + Ok((Surface::Revolution { profile: Arc::new(profile), axis }, Map { m })) +} + +/// A record surface as a STEP surface, and how the record's (u, v) map onto STEP's. +pub fn surface(s: &BSurface) -> R<(Surface, Map)> { + Ok(match s { + BSurface::Plane { origin, u_axis, v_axis } => plane(*origin, *u_axis, *v_axis)?, + BSurface::PlaneThrough { origin, u_point, v_point } => plane(*origin, sub(*u_point, *origin), sub(*v_point, *origin))?, + BSurface::Cylinder { frame, radius } => (Surface::Cylinder { position: placement(frame), radius: *radius }, Map::IDENTITY), + BSurface::Cone { frame, radius_at_origin, half_angle } => { + // STEP's semi-angle is positive: a cone narrowing along z is the one widening along −z, + // its frame turned over about x, (u, v) → (−u, −v). + let k = half_angle.signum(); + let mut position = placement(frame); + position.axis = scale(position.axis, k); + (Surface::Cone { position, radius: *radius_at_origin, semi_angle: half_angle.abs() }, Map { m: [[k, 0.0], [0.0, k]] }) + } + BSurface::Sphere { frame, radius } => (Surface::Sphere { position: placement(frame), radius: *radius }, Map::IDENTITY), + BSurface::Torus { frame, major_radius, minor_radius, .. } => { + (Surface::Torus { position: placement(frame), major_radius: *major_radius, minor_radius: *minor_radius }, Map::IDENTITY) + } + BSurface::Spline { u_knots, v_knots, points } => (bspline_surface(u_knots, v_knots, points.clone(), None)?, Map::IDENTITY), + BSurface::RationalSpline { u_knots, v_knots, homogeneous } => { + let mut points = Vec::with_capacity(homogeneous.len()); + let mut weights = Vec::with_capacity(homogeneous.len()); + for row in homogeneous { + let (p, w): (Vec, Vec) = row.iter().map(rational).collect::>>()?.into_iter().unzip(); + points.push(p); + weights.push(w); + } + (bspline_surface(u_knots, v_knots, points, Some(weights))?, Map::IDENTITY) + } + BSurface::PlacedRevolution { profile, origin, axis, matrix, forward } => revolution(profile, *origin, *axis, matrix, *forward)?, + BSurface::BallPatch { .. } => return Err("a ball patch's label (its face is written as its NURBS form)".into()), + }) +} + +/// Whether a face is written as its NURBS form, pcurves and all: a ball patch, which STEP has no +/// entity for, is the B-spline surface it is parameterised on. +fn as_form(face: &Face) -> bool { + face.nurbs.is_some() && matches!(face.surface, BSurface::BallPatch { .. }) +} + +/// A record pcurve in the STEP surface's parameters: its control points through `map` (a linear +/// map, exact on a B-spline and on a NURBS's homogeneous coefficients). +pub fn pcurve(c: &Curve2, map: Map) -> R { + let lift = |p: [f64; 2]| { + let [u, v] = map.apply(p); + [u, v, 0.0] + }; + match c { + Curve2::Spline { knots, points } => bspline_curve(knots, points.iter().map(|p| lift(*p)).collect(), None), + Curve2::RationalSpline { knots, homogeneous } => { + let mut points = Vec::with_capacity(homogeneous.len()); + let mut weights = Vec::with_capacity(homogeneous.len()); + for h in homogeneous { + let w = h[2]; + if !(w > 0.0) { + return Err("a pcurve with a non-positive rational weight".into()); + } + points.push(lift([h[0] / w, h[1] / w])); + weights.push(w); + } + bspline_curve(knots, points, Some(weights)) + } + } +} + +/// The STEP items a record became. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Written { + /// The MANIFOLD_SOLID_BREP or BREP_WITH_VOIDS of each material region, in region order. + pub solids: Vec, + /// The SHELL_BASED_SURFACE_MODEL of the open shells, if there are any. + pub sheets: Option, + /// The ADVANCED_FACE of each record face, in the record's face order (0 for a face no shell + /// lists, which a valid record has none of). + pub faces: Vec, +} + +/// A solid of a record: the outer shell of a material region and the shells of the voids inside it. +#[derive(Clone, Debug, PartialEq)] +pub struct SolidShells { + pub outer: u32, + pub voids: Vec, +} + +/// How a record's shells make up exchange items: a solid per material region, in region order, +/// and the open shells (sheets), in shell order. Wire and vertex shells, and material regions +/// that meet across a shell, have no exchange form here and are refused. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Layout { + pub solids: Vec, + pub sheets: Vec, +} + +/// The record's [`Layout`]. +pub fn layout(b: &Brep) -> R { + // The bounded region each closed shell is the outer shell of. + let mut outer_of: Vec> = vec![None; b.shells.len()]; + for (ri, region) in b.regions.iter().enumerate().skip(1) { + if let Some(slot) = region.shells.first().and_then(|s| outer_of.get_mut(*s as usize)) { + *slot = Some(ri); + } + } + let mut out = Layout::default(); + for region in b.regions.iter().skip(1).filter(|r| !r.void) { + let (Some(&outer), inner) = (region.shells.first(), region.shells.get(1..).unwrap_or(&[])) else { continue }; + let mut voids = Vec::new(); + for &shell in inner { + match outer_of.get(shell as usize).copied().flatten() { + Some(v) if b.regions.get(v).is_some_and(|r| r.void) => voids.push(shell), + Some(_) => return Err(unsupported("material regions that meet across a shell")), + // An open shell inside the material: one of the sheets. + None => {} + } + } + out.solids.push(SolidShells { outer, voids }); + } + for (si, shell) in b.shells.iter().enumerate() { + match shell { + Shell::Faces { .. } if outer_of.get(si).copied().flatten().is_none() => out.sheets.push(index(si)?), + Shell::Faces { .. } => {} + Shell::Wire { .. } | Shell::Vertex { .. } => return Err(unsupported("wire and vertex shells")), + } + } + Ok(out) +} + +/// Write `b`'s solids and sheets, each item named `name`. +pub fn brep(g: &mut GeomWriter<'_>, b: &Brep, name: &str) -> R { + let layout = layout(b)?; + let mut w = BrepWriter { + g, + b, + surfaces: vec![None; b.faces.len()], + vertices: vec![None; b.vertices.len()], + edges: vec![None; b.edges.len()], + faces: vec![None; b.faces.len()], + }; + let item_name = Param::Str(name.to_string()); + let mut out = Written::default(); + for solid in &layout.solids { + let shell = w.shell(solid.outer, true)?; + let mut voids = Vec::with_capacity(solid.voids.len()); + for &v in &solid.voids { + let void = w.shell(v, true)?; + voids.push(r(w.g.w.add_distinct("ORIENTED_CLOSED_SHELL", &[s(), Param::Derived, r(void), boolean(true)]))); + } + out.solids.push(if voids.is_empty() { + w.g.w.add_distinct("MANIFOLD_SOLID_BREP", &[item_name.clone(), r(shell)]) + } else { + w.g.w.add_distinct("BREP_WITH_VOIDS", &[item_name.clone(), r(shell), list(voids)]) + }); + } + let mut sheets = Vec::with_capacity(layout.sheets.len()); + for &si in &layout.sheets { + sheets.push(r(w.shell(si, false)?)); + } + if !sheets.is_empty() { + out.sheets = Some(w.g.w.add_distinct("SHELL_BASED_SURFACE_MODEL", &[item_name, list(sheets)])); + } + out.faces = w.faces.iter().map(|f| f.map_or(0, |(id, _)| id)).collect(); + Ok(out) +} + +/// The face's outer loop: the one edge loop whose pcurves run counter-clockwise in (u, v) about +/// the natural normal (the record's loop convention); `None` when no single loop does. +pub fn outer_loop(b: &Brep, face: &Face) -> Option { + let mut ccw = face.loops.iter().enumerate().filter_map(|(li, l)| match l { + Loop::Edges { edges } => { + let mut ring = Vec::with_capacity(edges.len() * AREA_SAMPLES); + for u in edges { + let [t0, t1] = edge_of(b, u.edge).ok()?.interval; + for k in 0..AREA_SAMPLES { + let f = k as f64 / AREA_SAMPLES as f64; + ring.push(solidcraft_geom::brep::pcurve::eval(&u.pcurve, if u.forward { t0 + (t1 - t0) * f } else { t1 - (t1 - t0) * f })?); + } + } + (signed_area(&ring) > 0.0).then_some(li) + } + Loop::Vertex { .. } => None, + }); + let first = ccw.next(); + if ccw.next().is_some() { None } else { first } +} + +fn index(i: usize) -> R { + u32::try_from(i).map_err(|_| "too many items".to_string()) +} + +struct BrepWriter<'g, 'w, 'b> { + g: &'g mut GeomWriter<'w>, + b: &'b Brep, + /// Each face's STEP surface and parameter map, once worked out. + surfaces: Vec, Map)>>, + vertices: Vec>, + edges: Vec>, + /// Each face's ADVANCED_FACE and the side it was written with (true: the natural normal). + faces: Vec>, +} + +fn face_of(b: &Brep, f: u32) -> R<&Face> { + b.faces.get(f as usize).ok_or_else(|| format!("face {f}: no such face")) +} + +fn edge_of(b: &Brep, e: u32) -> R<&Edge> { + b.edges.get(e as usize).ok_or_else(|| format!("edge {e}: no such edge")) +} + +impl BrepWriter<'_, '_, '_> { + fn surface(&mut self, f: u32) -> R<(Arc, Map)> { + if let Some(Some(s)) = self.surfaces.get(f as usize) { + return Ok(s.clone()); + } + let face = face_of(self.b, f)?; + if as_form(face) { + let s = (Arc::new(surface(face.parameters()).map_err(|m| format!("face {f}: {m}"))?.0), Map::IDENTITY); + if let Some(slot) = self.surfaces.get_mut(f as usize) { + *slot = Some(s.clone()); + } + return Ok(s); + } + let (s, map) = surface(&face.surface).map_err(|m| format!("face {f}: {m}"))?; + // A face on its NURBS form is written as the analytic surface it is, with no pcurves + // (STEP's are in the angle); only which way its normal points carries over. + let map = match &face.nurbs { + Some(n) => form_map(&face.surface, n, face.domain, map).ok_or_else(|| format!("face {f}: its NURBS form has no normal"))?, + // STEP's torus has no tube start: its pcurves would be off by it. + None if matches!(face.surface, BSurface::Torus { tube_start, .. } if tube_start != 0.0) => { + return Err(format!("face {f}: a torus with a tube start and no NURBS form")); + } + None => map, + }; + let s = (Arc::new(s), map); + if let Some(slot) = self.surfaces.get_mut(f as usize) { + *slot = Some(s.clone()); + } + Ok(s) + } + + fn vertex(&mut self, v: u32) -> R { + if let Some(Some(id)) = self.vertices.get(v as usize) { + return Ok(*id); + } + let point = self.b.vertices.get(v as usize).ok_or_else(|| format!("vertex {v}: no such vertex"))?.point; + let p = self.g.point(point); + let id = self.g.w.add_distinct("VERTEX_POINT", &[s(), r(p)]); + if let Some(slot) = self.vertices.get_mut(v as usize) { + *slot = Some(id); + } + Ok(id) + } + + fn edge(&mut self, e: u32) -> R { + if let Some(Some(id)) = self.edges.get(e as usize) { + return Ok(*id); + } + let edge = edge_of(self.b, e)?; + let (start, end) = (self.vertex(edge.vertices[0])?, self.vertex(edge.vertices[1])?); + let geometry = self.edge_geometry(edge).map_err(|m| format!("edge {e}: {m}"))?; + let id = self.g.w.add_distinct("EDGE_CURVE", &[s(), r(start), r(end), r(geometry), boolean(true)]); + if let Some(slot) = self.edges.get_mut(e as usize) { + *slot = Some(id); + } + Ok(id) + } + + /// The edge's curve, with the pcurves of its uses when it has one or two (a SURFACE_CURVE + /// holds at most two). + fn edge_geometry(&mut self, edge: &Edge) -> R { + let curve_3d = curve(&edge.curve)?; + if !(1..=2).contains(&edge.uses.len()) { + return Ok(self.g.curve(&curve_3d)); + } + let b = self.b; + let mut associated = Vec::with_capacity(edge.uses.len()); + for u in &edge.uses { + let face = face_of(b, u.face)?; + if face.nurbs.is_some() && !as_form(face) { + continue; + } + let Some(Loop::Edges { edges }) = face.loops.get(u.r#loop as usize) else { + return Err(format!("face {}: loop {} is no edge loop", u.face, u.r#loop)); + }; + let used = edges.get(u.position as usize).ok_or_else(|| format!("face {}: no use at {}", u.face, u.position))?; + let (surface, map) = self.surface(u.face)?; + associated.push(Associated::Pcurve(Pcurve { surface, curve: Arc::new(pcurve(&used.pcurve, map)?) })); + } + if associated.is_empty() { + return Ok(self.g.curve(&curve_3d)); + } + let seam = associated.len() == 2 && matches!(edge.uses.as_slice(), [a, b] if a.face == b.face); + let kind = if seam { SurfaceCurveKind::Seam } else { SurfaceCurveKind::Surface }; + Ok(self.g.curve(&Curve::SurfaceCurve { kind, curve_3d: Arc::new(curve_3d), associated, master: PreferredRep::Curve3d })) + } + + /// The face as a shell uses it, `side` true where its normal there is its surface's natural + /// normal: its ADVANCED_FACE, or an ORIENTED_FACE of the other side of it. + fn face(&mut self, f: u32, side: bool) -> R { + if let Some(Some((id, written))) = self.faces.get(f as usize).copied() { + return Ok(if written == side { id } else { self.g.w.add_distinct("ORIENTED_FACE", &[s(), Param::Derived, r(id), boolean(false)]) }); + } + let face = face_of(self.b, f)?; + let (surface, map) = self.surface(f)?; + let geometry = self.g.surface(&surface); + let outer = outer_loop(self.b, face); + let mut bounds = Vec::with_capacity(face.loops.len()); + for (li, l) in face.loops.iter().enumerate() { + let lp = match l { + Loop::Edges { edges } => { + // Counter-clockwise about the side's normal: the record's order on the natural + // side, reversed on the other. + let mut oriented = Vec::with_capacity(edges.len()); + let uses: Box> = if side { Box::new(edges.iter()) } else { Box::new(edges.iter().rev()) }; + for u in uses { + let e = self.edge(u.edge)?; + let along = boolean(u.forward == side); + oriented.push(r(self.g.w.add_distinct("ORIENTED_EDGE", &[s(), Param::Derived, Param::Derived, r(e), along]))); + } + self.g.w.add_distinct("EDGE_LOOP", &[s(), list(oriented)]) + } + Loop::Vertex { vertex } => { + let v = self.vertex(*vertex)?; + self.g.w.add_distinct("VERTEX_LOOP", &[s(), r(v)]) + } + }; + let kind = if outer == Some(li) { "FACE_OUTER_BOUND" } else { "FACE_BOUND" }; + bounds.push(r(self.g.w.add_distinct(kind, &[s(), r(lp), boolean(true)]))); + } + let same_sense = side == map.keeps_normal(); + let id = self.g.w.add_distinct("ADVANCED_FACE", &[s(), list(bounds), r(geometry), boolean(same_sense)]); + if let Some(slot) = self.faces.get_mut(f as usize) { + *slot = Some((id, side)); + } + Ok(id) + } + + /// A face shell: CLOSED_SHELL when it bounds a region, else OPEN_SHELL. + fn shell(&mut self, si: u32, closed: bool) -> R { + let b = self.b; + let Some(Shell::Faces { faces, wires }) = b.shells.get(si as usize) else { + return Err(format!("shell {si}: not a face shell")); + }; + if !wires.is_empty() { + return Err(unsupported("wire edges inside a face shell")); + } + let mut entries = Vec::with_capacity(faces.len()); + for of in faces { + entries.push(r(self.face(of.face, of.forward)?)); + } + let kind = if closed { "CLOSED_SHELL" } else { "OPEN_SHELL" }; + Ok(self.g.w.add_distinct(kind, &[s(), list(entries)])) + } +} + +/// Signed area of a closed polygon in (u, v): positive counter-clockwise. +fn signed_area(ring: &[[f64; 2]]) -> f64 { + let n = ring.len(); + 0.5 * (0..n).filter_map(|i| Some((ring.get(i)?, ring.get((i + 1) % n)?))).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum::() +} + +/// The map of a face on its NURBS form `n`: no pcurve goes through it, so it only says whether +/// the face's natural normal (the NURBS's, which the loops follow) is the STEP surface's. The +/// record's cylinder, cone, sphere and torus have their natural normal pointing away from the +/// axis (the sphere's centre, the torus's centre circle); `None` when the NURBS has no normal at +/// its domain's centre. +fn form_map(analytic: &BSurface, n: &BSurface, domain: [[f64; 2]; 2], map: Map) -> Option { + let eval = solidcraft_geom::brep::eval::SurfaceEval::new(n).ok()?; + let (p, su, sv) = eval.derivs(0.5 * (domain[0][0] + domain[0][1]), 0.5 * (domain[1][0] + domain[1][1]))?; + let normal = su.cross(sv); + let away = |f: &Frame| { + let o = solidcore_record::Vec3::new(f.origin[0], f.origin[1], f.origin[2]); + let z = solidcore_record::Vec3::new(f.x_axis[0], f.x_axis[1], f.x_axis[2]).cross(solidcore_record::Vec3::new( + f.y_axis[0], + f.y_axis[1], + f.y_axis[2], + )); + let d = p - o; + (o, z, d - z * d.dot(z)) + }; + let outward = match analytic { + BSurface::Cylinder { frame, .. } | BSurface::Cone { frame, .. } => away(frame).2, + BSurface::Sphere { frame, .. } => p - away(frame).0, + BSurface::Torus { frame, major_radius, .. } => { + let (o, _, radial) = away(frame); + p - (o + radial.normalized()? * *major_radius) + } + _ => return None, + }; + let along = normal.dot(outward); + if !(along.abs() > 0.0) { + return None; + } + let keeps = (along > 0.0) == map.keeps_normal(); + Some(Map { m: [[1.0, 0.0], [0.0, if keeps { 1.0 } else { -1.0 }]] }) +} diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml new file mode 100644 index 000000000..118c436d2 --- /dev/null +++ b/crates/testkit/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "solidcraft-testkit" +description = "SolidCraft test tooling: deterministic mutations of valid files and the no-panic check run over them (a dev-dependency only)" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs new file mode 100644 index 000000000..60ba9eccc --- /dev/null +++ b/crates/testkit/src/lib.rs @@ -0,0 +1,294 @@ +//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of +//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten +//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and +//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an +//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a +//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any +//! panic, so a caught one on the desktop is a crash there. +//! +//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces. +//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and +//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a +//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino +//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::time::{Duration, Instant}; + +/// A deterministic xorshift64 stream. +struct Rng(u64); + +impl Rng { + fn new(seed: u64) -> Rng { + Rng(seed | 1) + } + + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// A value in `0..n` (0 when `n` is 0). + fn below(&mut self, n: usize) -> usize { + if n == 0 { 0 } else { (self.next() % n as u64) as usize } + } +} + +/// Numbers a hostile file might hold in place of a real one. +const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"]; + +/// Most truncations of one file (every length up to this, evenly spaced beyond). +const MAX_TRUNCATIONS: usize = 1024; + +/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number +/// mutations (the file is UTF-8 text). +pub fn mutations(good: &[u8], text: bool, seed: u64) -> Vec> { + let mut out: Vec> = Vec::new(); + let n = good.len(); + let mut rng = Rng::new(seed); + // Truncations: every length of a short file; of a long one, its first and last 64 lengths + // (headers, final records) and evenly spaced ones between. + if n <= MAX_TRUNCATIONS { + out.extend((0..n).map(|k| good[..k].to_vec())); + } else { + let mut cuts: Vec = (0..64).chain(n - 64..n).collect(); + cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128))); + cuts.sort_unstable(); + cuts.dedup(); + out.extend(cuts.into_iter().map(|k| good[..k].to_vec())); + } + if n == 0 { + return out; + } + // Bytes flipped, zeroed and saturated at seeded places. + for i in 0..384 { + let at = rng.below(n); + let mut b = good.to_vec(); + b[at] = match i % 3 { + 0 => b[at] ^ ((rng.next() >> 32) as u8 | 1), + 1 => 0x00, + _ => 0xff, + }; + out.push(b); + } + // Runs of bytes dropped, repeated and swapped with their neighbour. + for _ in 0..96 { + let at = rng.below(n); + let len = 1 + rng.below(64.min(n - at)); + let end = at + len; + let mut dropped = good[..at].to_vec(); + dropped.extend_from_slice(&good[end..]); + out.push(dropped); + let mut repeated = good[..end].to_vec(); + repeated.extend_from_slice(&good[at..]); + out.push(repeated); + if end + len <= n { + let mut swapped = good[..at].to_vec(); + swapped.extend_from_slice(&good[end..end + len]); + swapped.extend_from_slice(&good[at..end]); + swapped.extend_from_slice(&good[end + len..]); + out.push(swapped); + } + } + // The whole file: with garbage after it, twice over, reversed. + let mut tail = good.to_vec(); + tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8)); + out.push(tail); + out.push([good, good].concat()); + out.push(good.iter().rev().copied().collect()); + if text && let Ok(s) = std::str::from_utf8(good) { + out.extend(text_mutations(s, &mut rng)); + } + out +} + +/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies. +fn text_mutations(s: &str, rng: &mut Rng) -> Vec> { + let mut out = Vec::new(); + let lines: Vec<&str> = s.split_inclusive('\n').collect(); + let join = |v: &[&str]| v.concat().into_bytes(); + let picked: Vec = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() }; + for &i in &picked { + let mut v = lines.clone(); + v.remove(i); + out.push(join(&v)); + let mut v = lines.clone(); + v.insert(i, lines[i]); + out.push(join(&v)); + if i + 1 < lines.len() { + let mut v = lines.clone(); + v.swap(i, i + 1); + out.push(join(&v)); + } + } + // A line in place of another (a block that inserts itself, a count where a coordinate was). + for _ in 0..200.min(lines.len() * lines.len()) { + let (i, j) = (rng.below(lines.len()), rng.below(lines.len())); + let mut v = lines.clone(); + v[i] = lines[j]; + out.push(join(&v)); + } + // A word in place of another of the file's own words: a renamed block, a swapped keyword, a + // block that now inserts itself. Every pair in a small file, a sample in a large one. + let words = word_spans(s); + let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect(); + vocab.sort_unstable(); + vocab.dedup(); + let pairs = words.len().saturating_mul(vocab.len()); + let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes(); + if pairs <= 3000 { + for &span in &words { + for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) { + out.push(swap(span, w)); + } + } + } else { + for _ in 0..400 { + out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())])); + } + } + // Numbers: each of up to 200 of them, in turn, becomes one of the liars. + let numbers = number_spans(s); + let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() }; + for (k, (a, b)) in chosen.into_iter().enumerate() { + let liar = LIARS[k % LIARS.len()]; + out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes()); + } + // Every number lying at once (two counts that are only harmless one at a time). + let all = number_spans(s); + for liar in LIARS { + let mut t = String::with_capacity(s.len()); + let mut at = 0; + for &(a, b) in &all { + t.push_str(&s[at..a]); + t.push_str(liar); + at = b; + } + t.push_str(&s[at..]); + out.push(t.into_bytes()); + } + out +} + +/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a +/// letter). +fn word_spans(s: &str) -> Vec<(usize, usize)> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) { + i += 1; + continue; + } + let a = i; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { + i += 1; + } + out.push((a, i)); + } + out +} + +/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent). +fn number_spans(s: &str) -> Vec<(usize, usize)> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit)); + let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); + if !starts || after_word { + i += 1; + continue; + } + let a = i; + i += 1; + while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) { + if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') { + i += 1; + } + i += 1; + } + out.push((a, i)); + } + out +} + +thread_local! { + /// Panics on this thread so far, caught or not ([`count_panics`]). + static PANICS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Count every panic per thread (tests run on several), then run the hook that was there. +fn count_panics() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + PANICS.with(|p| p.set(p.get() + 1)); + previous(info); + })); + }); +} + +/// The time any one reader call may take on a mutated file (a debug build on a loaded machine: +/// generous, but far below what unbounded work on a lying count would take). +pub const BUDGET: Duration = Duration::from_secs(2); + +/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles, +/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming +/// the first case that breaks a rule. +// Failing the calling test is this function's job; it only ever runs inside tests. +#[allow(clippy::panic)] +pub fn survives(what: &str, inputs: &[Vec], cap: usize, mut read: impl FnMut(&[u8]) -> Option) { + count_panics(); + let mut slowest = (Duration::ZERO, 0); + let mut read_ok = 0; + for (i, input) in inputs.iter().enumerate() { + let before = PANICS.with(std::cell::Cell::get); + let t = Instant::now(); + let r = catch_unwind(AssertUnwindSafe(|| read(input))); + let took = t.elapsed(); + let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned(); + let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) }; + let caught = PANICS.with(std::cell::Cell::get) - before; + assert!( + caught == 0, + "{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}", + input.len() + ); + assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len()); + if let Some(count) = r { + assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})"); + read_ok += 1; + } + slowest = slowest.max((took, i)); + } + eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mutations_are_deterministic_and_cover_the_file() { + let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n"; + let a = mutations(good, true, 7); + assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases"); + assert_ne!(a, mutations(good, true, 8)); + assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing"); + assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar"); + assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]); + // A long file: bounded truncations, kept to the first and last bytes and spaced between. + let long = vec![b'a'; 100_000]; + let m = mutations(&long, false, 1); + assert!(m.len() < 3000, "{} cases", m.len()); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 6afabfdf7..294892313 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +solidcore-record = { workspace = true } solidcraft-engine = { workspace = true } egui = { workspace = true } egui-wgpu = { workspace = true } @@ -25,6 +26,9 @@ ttf-parser = { workspace = true } # Right-to-left interface text (Hebrew): the Unicode Bidirectional Algorithm puts translated # strings in display order, which egui does not do itself (MIT OR Apache-2.0). unicode-bidi = "0.3" +# The system's preferred languages on a first start (MIT OR Apache-2.0, maintained by +# 1Password): the OS locale on desktop and, with `js`, `navigator.languages` in the browser (#10138). +sys-locale = { version = "0.3.2", features = ["js"] } semver = { workspace = true } # Updates: the downloaded package's SHA-256 (against the release's SHA256SUMS.txt), its optional # minisign signature (MIT), and the portable .zip's executables. @@ -44,7 +48,7 @@ nix = { workspace = true } winreg = "0.56" [dev-dependencies] -solidcraft-engine = { workspace = true, features = ["bundled-render-library"] } +solidcraft-engine = { workspace = true, features = ["bundled-render-library", "profile"] } # Parse the source guard structurally, including code after inline test modules. syn = { workspace = true, features = ["visit"] } # The catalog guard reads every UI source file as Rust tokens; already in the tree through diff --git a/crates/ui-egui/examples/acp_test_agent.rs b/crates/ui-egui/examples/acp_test_agent.rs index 95c625e7f..58b48bd0d 100644 --- a/crates/ui-egui/examples/acp_test_agent.rs +++ b/crates/ui-egui/examples/acp_test_agent.rs @@ -177,7 +177,7 @@ fn main() { send(&json!({"jsonrpc": "2.0", "id": 900, "method": "session/request_permission", "params": { "sessionId": session, // Named as the Claude Code adapter names an MCP tool. - "toolCall": {"toolCallId": "t1", "title": "mcp__solidcraft__batch"}, + "toolCall": {"toolCallId": "t1", "title": "mcp__solidcraft-app__batch", "kind": "other"}, "options": [{"optionId": "allow", "name": "Allow", "kind": "allow_once"}, {"optionId": "reject", "name": "Reject", "kind": "reject_once"}], }})); // Wait for the answer (other lines are not expected meanwhile). diff --git a/crates/ui-egui/src/access.rs b/crates/ui-egui/src/access.rs index 19bdc8ea8..1522337e6 100644 --- a/crates/ui-egui/src/access.rs +++ b/crates/ui-egui/src/access.rs @@ -21,8 +21,8 @@ pub fn map(app: &SolveApp) -> Option { if let Some(m) = CACHE.with(|c| c.borrow().as_ref().filter(|(k, _)| *k == key).map(|(_, m)| m.clone())) { return Some(m); } - let st = app.session.world_state(); - let meshes: Vec<_> = st.bodies.iter().filter(|b| app.session.body_visible(&b.name)).map(|b| b.mesh()).collect(); + let st = crate::open_meshing::session_world(&app.session); + let meshes: Vec<_> = st.bodies.iter().filter(|b| app.body_visible(&b.name)).map(|b| b.mesh()).collect(); // Every new map gets a new version (the GPU uploads it once). let version = VERSION.with(|v| { v.set(v.get() + 1); diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 092c36616..efffaf331 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -7,8 +7,119 @@ //! reaches the design through SolidCraft's MCP server instead), and terminal login, so an agent //! that needs one describes a command for the user to run rather than asking for a key. +use serde::Serialize; use serde_json::{Value, json}; +/// One advertised value, with an optional human-readable group label. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigChoice { + pub value: String, + pub name: String, + pub description: String, + pub group: Option, +} +/// A supported ACP select option; identifiers and categories belong to the agent. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigOption { + pub id: String, + pub name: String, + pub description: String, + pub category: String, + pub current_value: String, + pub options: Vec, +} + +/// Parse ACP select options as a bounded authoritative snapshot. +#[derive(Debug, PartialEq, Eq)] +pub enum ConfigParse { + Absent, + Invalid, + Snapshot(Vec), +} +pub fn config_options(v: &Value) -> ConfigParse { + let Some(raw_list) = v.get("configOptions") else { + return ConfigParse::Absent; + }; + let Some(list) = raw_list.as_array() else { + return ConfigParse::Invalid; + }; + let mut out = Vec::new(); + let mut ids = std::collections::HashSet::new(); + for x in list.iter().take(64) { + match x.get("type").and_then(Value::as_str) { + Some("select") => {} + Some(_) => continue, + None => return ConfigParse::Invalid, + } + let Some(id) = x.get("id").and_then(Value::as_str).filter(|s| !s.is_empty() && s.len() <= 256) else { + return ConfigParse::Invalid; + }; + let Some(current_value) = x.get("currentValue").and_then(Value::as_str).filter(|s| s.len() <= 256) else { + return ConfigParse::Invalid; + }; + let Some(raw) = x.get("options").and_then(Value::as_array) else { + return ConfigParse::Invalid; + }; + if !ids.insert(id.to_string()) { + continue; + } + let mut choices = Vec::new(); + let mut values = std::collections::HashSet::new(); + 'items: for item in raw.iter().take(128) { + if choices.len() >= 128 { + break; + } + let group = + item.get("name").and_then(Value::as_str).or_else(|| item.get("group").and_then(Value::as_str)).map(|s| s.chars().take(256).collect()); + if let Some(cs) = item.get("options").and_then(Value::as_array) { + for c in cs.iter().take(128) { + if choices.len() >= 128 { + break 'items; + } + let Some(value) = c.get("value").and_then(Value::as_str).filter(|s| !s.is_empty() && s.len() <= 256) else { + continue; + }; + if !values.insert(value.to_string()) { + continue; + } + choices.push(ConfigChoice { + value: value.into(), + name: c.get("name").and_then(Value::as_str).unwrap_or(value).chars().take(256).collect(), + description: c.get("description").and_then(Value::as_str).unwrap_or("").chars().take(1024).collect(), + group: group.clone(), + }); + } + } else { + let Some(value) = item.get("value").and_then(Value::as_str).filter(|s| !s.is_empty() && s.len() <= 256) else { + continue; + }; + if values.insert(value.to_string()) { + choices.push(ConfigChoice { + value: value.into(), + name: item.get("name").and_then(Value::as_str).unwrap_or(value).chars().take(256).collect(), + description: item.get("description").and_then(Value::as_str).unwrap_or("").chars().take(1024).collect(), + group: None, + }); + } + } + } + if choices.is_empty() { + return ConfigParse::Invalid; + } + out.push(ConfigOption { + id: id.into(), + name: x.get("name").and_then(Value::as_str).unwrap_or(id).chars().take(256).collect(), + description: x.get("description").and_then(Value::as_str).unwrap_or("").chars().take(1024).collect(), + category: x.get("category").and_then(Value::as_str).unwrap_or("").chars().take(128).collect(), + current_value: current_value.into(), + options: choices, + }); + } + ConfigParse::Snapshot(out) +} + /// The protocol version we speak. pub const PROTOCOL_VERSION: u64 = 1; @@ -49,6 +160,19 @@ pub fn initialize_params(version: &str) -> Value { /// keeps its own entry on a clash) can't shadow the bridge with a headless session. pub const BRIDGE_NAME: &str = "solidcraft-app"; +/// Whether a permission question is about a tool of the chat's own MCP server, whose calls +/// SolidCraft's gate checks. The agent writes both values and ACP has nothing better to go on, so +/// the test is strict: the whole title is the tool's name as the Claude adapter forms it +/// (`mcp__solidcraft-app__batch`), one word with no room for a command line, a path or other free +/// text, and the kind is `other` (the kind an MCP tool has) or not given. Any other title goes +/// through the user's mode and remembered answers: agents that word their MCP tools differently, +/// and a user's own MCP server, which the gate doesn't see. +pub fn is_bridge_tool(title: &str, kind: Option<&str>) -> bool { + let tool = title.strip_prefix("mcp__").and_then(|t| t.strip_prefix(BRIDGE_NAME)).and_then(|t| t.strip_prefix("__")); + let named = tool.is_some_and(|t| !t.is_empty() && t.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')); + named && matches!(kind, None | Some("other")) +} + /// The MCP server the agent starts to reach the design: `solidcraft-cli mcp --connect` bridged to /// this app's control port. The server finds the port's token in the token file the app wrote /// (docs/control-protocol.md), so the token never travels through the agent, and it keeps its @@ -100,11 +224,14 @@ pub fn wsl_path(path: &std::path::Path) -> std::path::PathBuf { } } -/// What every session is told about where it is. Agents that don't read `_meta` ignore it. +/// What every session is told about where it is. An agent with no route for it in +/// [`session_new_params`] doesn't get it. pub const SYSTEM_NOTE: &str = "You are running inside SolidCraft, a parametric 3D CAD application, as the user's assistant. \ The open design is reachable through the `solidcraft-app` MCP server: use its tools (list_commands, batch, execute, inspect_design, \ -measure, screenshot, set_parameter, undo) to read and change the design the user is looking at, and verify with measure or \ -inspect_design. Prefer one `batch` over many small calls. Saving, opening or exporting files waits for the user's approval in \ +measure, screenshot, set_parameter, undo, skill_reference) to read and change the design the user is looking at, and verify with \ +measure or inspect_design. Before building anything beyond one primitive, read `skill_reference` for `solidcraft-modeling` (its \ +SKILL.md has the workflow, its reference.md the command shapes and this version's traps), work the numbers out first, and after \ +each stage compare `measure` with them. Prefer one `batch` over many small calls. Saving, opening or exporting files waits for the user's approval in \ the chat, and each message allows a limited number of changes. Don't use shell or file tools: work through the SolidCraft tools. \ Keep answers short."; @@ -113,19 +240,44 @@ Keep answers short."; pub const CLAUDE_DISALLOWED_TOOLS: &[&str] = &["Bash", "BashOutput", "KillShell", "Read", "Write", "Edit", "MultiEdit", "NotebookEdit", "Glob", "Grep", "WebFetch", "WebSearch", "Task"]; -pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>) -> Value { +/// The `session/new` parameters. `init` is the agent's `initialize` reply: agents read the system +/// note from different places (#9811), and the standard field may only go to an agent offering it. +pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, init: &Value) -> Value { let servers: Vec = bridge.map(McpBridge::to_json).into_iter().collect(); - json!({ + let mut meta = json!({ + // The Claude adapter's own key, for its versions without the standard field. + "systemPrompt": {"append": SYSTEM_NOTE}, + // Hosts may opt a session out of "bypass permissions" (the Claude adapter reads it): + // every tool call the agent asks about reaches the panel. + // Its own shell and file tools are off: the agent works through SolidCraft's tools. + "claudeCode": {"options": {"allowDangerouslySkipPermissions": false, "disallowedTools": CLAUDE_DISALLOWED_TOOLS}}, + }); + if takes_antigravity_note(init) + && let Some(meta) = meta.as_object_mut() + { + meta.insert("antigravity".into(), json!({"systemPrompt": {"append": SYSTEM_NOTE}})); + } + let mut params = json!({ "cwd": cwd.to_string_lossy(), "mcpServers": servers, - "_meta": { - "systemPrompt": {"append": SYSTEM_NOTE}, - // Hosts may opt a session out of "bypass permissions" (the Claude adapter reads it): - // every tool call the agent asks about reaches the panel. - // Its own shell and file tools are off: the agent works through SolidCraft's tools. - "claudeCode": {"options": {"allowDangerouslySkipPermissions": false, "disallowedTools": CLAUDE_DISALLOWED_TOOLS}}, - }, - }) + "_meta": meta, + }); + if takes_standard_note(init) + && let Some(params) = params.as_object_mut() + { + params.insert("systemPrompt".into(), json!({"mode": "append", "content": [{"type": "text", "text": SYSTEM_NOTE}]})); + } + params +} + +/// The agent offers ACP's `systemPrompt` field on its sessions. +fn takes_standard_note(init: &Value) -> bool { + init.pointer("/agentCapabilities/sessionCapabilities/systemPrompt").is_some_and(|offer| !offer.is_null()) +} + +/// Antigravity offers its own key under `_meta` and doesn't read the Claude adapter's. +fn takes_antigravity_note(init: &Value) -> bool { + init.pointer("/agentCapabilities/_meta/antigravity/systemPrompt/append").and_then(Value::as_bool).unwrap_or(false) } pub fn prompt_params(session: &str, parts: &[super::backend::PromptPart]) -> Value { @@ -183,6 +335,9 @@ pub fn models(session: &Value) -> Option<(String, Vec)> { pub fn set_model_params(session: &str, model: &str) -> Value { json!({"sessionId": session, "modelId": model}) } +pub fn set_config_option_params(session: &str, id: &str, value: &str) -> Value { + json!({"sessionId": session, "configId": id, "value": value}) +} /// Whether the agent takes embedded documents in a message /// (`agentCapabilities.promptCapabilities.embeddedContext`: it reads `resource` blocks). @@ -307,23 +462,49 @@ pub struct PermissionOption { #[derive(Clone, Debug, PartialEq)] pub enum Incoming { /// The reply to one of our requests. - Reply { id: u64, result: Result }, + Reply { + id: u64, + result: Result, + }, /// Text the agent streams (`thought`: its reasoning, shown dimmed). - Text { thought: bool, text: String }, + Text { + thought: bool, + text: String, + }, /// A new tool call, or news about one (`title`/`status` when they changed). - Tool { id: String, title: Option, kind: Option, status: Option, input: Option, output: Option }, + Tool { + id: String, + title: Option, + kind: Option, + status: Option, + input: Option, + output: Option, + }, /// The agent's plan: each entry with its status. Plan(Vec<(String, String)>), /// The agent asks before running a tool call; answered with [`permission_reply`]. - Permission { rpc: Value, title: String, options: Vec }, + Permission { + rpc: Value, + title: String, + /// The tool call's kind (`execute`, `edit`, `other`, …), as the agent gives it. + kind: Option, + options: Vec, + }, /// The agent says whether it is logged in (an extension both adapters send). AuthStatus(String), /// The agent switched to another of its modes. ModeChanged(String), /// The agent switched to another model. ModelChanged(String), + ConfigOptions { + session: String, + options: Vec, + }, /// A request we don't serve (file system, terminal, …): answer "method not found". - Unsupported { rpc: Value, method: String }, + Unsupported { + rpc: Value, + method: String, + }, /// Anything else (mode and command lists, usage): nothing to show. Ignored, } @@ -380,6 +561,7 @@ pub fn parse(line: &str) -> Option { (Some("session/request_permission"), Some(id)) => { let call = params.get("toolCall"); let title = call.and_then(|c| c.get("title")).and_then(Value::as_str).unwrap_or("").to_string(); + let kind = call.and_then(|c| c.get("kind")).and_then(Value::as_str).map(str::to_string); let options = params .get("options") .and_then(Value::as_array) @@ -396,10 +578,10 @@ pub fn parse(line: &str) -> Option { .collect() }) .unwrap_or_default(); - Some(Incoming::Permission { rpc: id.clone(), title, options }) + Some(Incoming::Permission { rpc: id.clone(), title, kind, options }) } (Some(m), Some(id)) => Some(Incoming::Unsupported { rpc: id.clone(), method: m.to_string() }), - (Some("session/update"), None) => Some(update(params.get("update")?)), + (Some("session/update"), None) => Some(update(params.get("update")?, params.get("sessionId").and_then(Value::as_str).unwrap_or(""))), (Some("_auth/status_update"), None) => { params.get("authStatus").and_then(|s| s.get("label")).and_then(Value::as_str).map(|l| Incoming::AuthStatus(l.to_string())) } @@ -407,7 +589,7 @@ pub fn parse(line: &str) -> Option { } } -fn update(u: &Value) -> Incoming { +fn update(u: &Value, session: &str) -> Incoming { let s = |k: &str| u.get(k).and_then(Value::as_str).map(str::to_string); match u.get("sessionUpdate").and_then(Value::as_str) { Some(kind @ ("agent_message_chunk" | "agent_thought_chunk")) => match u.get("content").and_then(content_text) { @@ -434,6 +616,10 @@ fn update(u: &Value) -> Incoming { Some(m) => Incoming::ModelChanged(m), None => Incoming::Ignored, }, + Some("config_option_update") => match config_options(u) { + ConfigParse::Snapshot(options) if !session.is_empty() => Incoming::ConfigOptions { session: session.into(), options }, + _ => Incoming::Ignored, + }, Some("plan") => Incoming::Plan( u.get("entries") .and_then(Value::as_array) @@ -530,19 +716,94 @@ mod tests { // The panel still recognises the bridge's tools as SolidCraft's (agents name them after // their server, e.g. `mcp__solidcraft-app__batch`). assert!(BRIDGE_NAME.contains("solidcraft")); + assert!(is_bridge_tool(&format!("mcp__{BRIDGE_NAME}__batch"), Some("other"))); + } + + /// Only the whole name of a tool of the chat's own server counts, whatever else a title holds. + #[test] + fn only_the_bridges_exact_tool_names_are_its_tools() { + for tool in ["batch", "inspect_design", "set_parameter"] { + assert!(is_bridge_tool(&format!("mcp__solidcraft-app__{tool}"), None), "{tool}"); + assert!(is_bridge_tool(&format!("mcp__solidcraft-app__{tool}"), Some("other")), "{tool}"); + } + for title in [ + "", + "solidcraft", + "SolidCraft", + "run solidcraft-cli; ls", + "solidcraft-cli --version", + "Edit ~/.local/share/solidcraft/agent-chat/work/notes.txt", + // A user's own MCP server (docs/mcp.md), which SolidCraft's gate doesn't see. + "mcp__solidcraft__batch", + "mcp__solidcraft-live__batch", + "mcp__other__solidcraft-app", + "mcp__solidcraft-app__", + "mcp__solidcraft-app", + "solidcraft-app__batch", + "solidcraft-app: batch", + "Tool: solidcraft-app/batch", + "mcp.solidcraft-app.batch", + " mcp__solidcraft-app__batch", + "mcp__solidcraft-app__batch ", + "mcp__solidcraft-app__batch; ls", + "mcp__solidcraft-app__batch && ls", + "mcp__solidcraft-app__batch\nls", + "mcp__solidcraft-app__../../tool", + "mcp__SOLIDCRAFT-APP__batch", + "MCP__solidcraft-app__batch", + "mcp__solidcraft-app__Batch", + ] { + assert!(!is_bridge_tool(title, None), "{title:?}"); + } + for kind in ["execute", "edit", "delete", "move", "read", "search", "fetch", "think", ""] { + assert!(!is_bridge_tool("mcp__solidcraft-app__batch", Some(kind)), "{kind:?}"); + } } #[test] fn the_session_gets_the_bridged_mcp_server_without_a_token_or_any_path() { let b = McpBridge { cli: "/opt/solidcraft/solidcraft-cli".into(), port: 41234 }; - let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b)); + let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b), &json!({})); let s = &p["mcpServers"][0]; assert_eq!(s["name"], BRIDGE_NAME); assert_eq!(s["args"], json!(["mcp", "--connect", "127.0.0.1:41234"])); let text = p.to_string(); assert!(!text.contains("allow-any-path") && !text.contains("TOKEN") && !text.contains("token"), "{text}"); assert!(p["_meta"]["claudeCode"]["options"]["disallowedTools"].as_array().is_some_and(|t| t.iter().any(|x| x == "Bash"))); - assert_eq!(session_new_params(std::path::Path::new("/tmp"), None)["mcpServers"], json!([])); + assert_eq!(session_new_params(std::path::Path::new("/tmp"), None, &json!({}))["mcpServers"], json!([])); + } + + /// #9811: the note goes by the routes an agent's `initialize` reply offers, and the standard + /// field never goes to an agent that doesn't offer it, as the protocol asks. + #[test] + fn the_system_note_takes_every_route_the_agent_offers() { + let params = |init: Value| session_new_params(std::path::Path::new("/tmp"), None, &init); + let standard = json!({"mode": "append", "content": [{"type": "text", "text": SYSTEM_NOTE}]}); + + let offers_standard = params(json!({"agentCapabilities": {"sessionCapabilities": {"systemPrompt": {}}}})); + assert_eq!(offers_standard["systemPrompt"], standard); + assert!(offers_standard["_meta"].get("antigravity").is_none()); + + let offers_antigravity = params(json!({"agentCapabilities": {"_meta": {"antigravity": {"systemPrompt": {"append": true}}}}})); + assert_eq!(offers_antigravity["_meta"]["antigravity"]["systemPrompt"]["append"], SYSTEM_NOTE); + assert!(offers_antigravity.get("systemPrompt").is_none()); + + for none in [ + json!({}), + json!({"agentCapabilities": {"sessionCapabilities": {"systemPrompt": null}}}), + json!({"agentCapabilities": {"_meta": {"antigravity": {"systemPrompt": {"append": false}}}}}), + ] { + let p = params(none); + assert!(p.get("systemPrompt").is_none(), "{p}"); + assert!(p["_meta"].get("antigravity").is_none(), "{p}"); + } + + // Every session keeps the key older Claude adapters read, and the tools they turn off. + for init in [json!({}), json!({"agentCapabilities": {"sessionCapabilities": {"systemPrompt": {}}}})] { + let p = params(init); + assert_eq!(p["_meta"]["systemPrompt"]["append"], SYSTEM_NOTE); + assert!(p["_meta"]["claudeCode"]["options"]["disallowedTools"].is_array()); + } } /// #5546: an agent started through `wsl.exe` gets the session's paths as WSL shows them. @@ -565,7 +826,7 @@ mod tests { assert_eq!(wsl(r"\\server\share\x"), r"\\server\share\x"); let b = McpBridge { cli: r"C:\Program Files\SolidCraft\solidcraft-cli.exe".into(), port: 41234 }; - let p = session_new_params(&wsl_path(std::path::Path::new(r"C:\Users\u\work")), Some(&b.in_wsl())); + let p = session_new_params(&wsl_path(std::path::Path::new(r"C:\Users\u\work")), Some(&b.in_wsl()), &json!({})); assert_eq!(p["cwd"], "/mnt/c/Users/u/work"); assert_eq!(p["mcpServers"][0]["command"], "/mnt/c/Program Files/SolidCraft/solidcraft-cli.exe"); assert_eq!(p["mcpServers"][0]["args"], json!(["mcp", "--connect", "127.0.0.1:41234"])); @@ -610,8 +871,9 @@ mod tests { }) ); let perm = r#"{"jsonrpc":"2.0","id":7,"method":"session/request_permission","params":{"sessionId":"s","toolCall":{"toolCallId":"t1","title":"batch"},"options":[{"optionId":"allow","name":"Allow","kind":"allow_once"},{"optionId":"reject","name":"Reject","kind":"reject_once"}]}}"#; - let Some(Incoming::Permission { rpc, title, options }) = parse(perm) else { panic!() }; + let Some(Incoming::Permission { rpc, title, kind, options }) = parse(perm) else { panic!() }; assert_eq!((title.as_str(), options.len(), options[1].kind.as_str()), ("batch", 2, "reject_once")); + assert_eq!(kind, None); assert_eq!(permission_reply(rpc.clone(), Some("allow"))["result"]["outcome"], json!({"outcome": "selected", "optionId": "allow"})); assert_eq!(permission_reply(rpc, None)["result"]["outcome"]["outcome"], "cancelled"); let fs = r#"{"jsonrpc":"2.0","id":8,"method":"fs/read_text_file","params":{}}"#; @@ -629,7 +891,7 @@ mod tests { fn long_tool_output_is_cut_on_a_character_boundary() { let long = "é".repeat(3000); let u = json!({"sessionUpdate": "tool_call", "toolCallId": "t", "content": [{"type": "content", "content": {"type": "text", "text": long}}]}); - let Incoming::Tool { output: Some(o), .. } = update(&u) else { panic!() }; + let Incoming::Tool { output: Some(o), .. } = update(&u, "s") else { panic!() }; assert!(o.len() <= MAX_OUTPUT + 3 && o.ends_with('…')); } @@ -650,5 +912,42 @@ mod tests { let changed = r#"{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"current_model_update","currentModelId":"haiku"}}}"#; assert_eq!(parse(changed), Some(Incoming::ModelChanged("haiku".into()))); assert_eq!(set_model_params("s", "opus"), json!({"sessionId": "s", "modelId": "opus"})); + assert_eq!(set_config_option_params("s1", "vendor.model", "smart"), json!({"sessionId":"s1","configId":"vendor.model","value":"smart"})); + } + + #[test] + fn config_options_parse_flat_and_grouped_selects_and_ignore_unsupported() { + let v = json!({"configOptions":[ + {"id":"arbitrary","name":"Model","category":"model","type":"select","currentValue":"a","options":[{"value":"a","name":"A"}]}, + {"id":"effort","category":"thought_level","type":"select","currentValue":"high","options":[{"group":"Reasoning","options":[{"value":"high","name":"High"}]}]}, + {"id":"bad","type":"boolean"}]}); + let ConfigParse::Snapshot(options) = config_options(&v) else { panic!() }; + assert_eq!(options.len(), 2); + assert_eq!(options[0].id, "arbitrary"); + assert_eq!(options[1].options[0].group.as_deref(), Some("Reasoning")); + assert!(matches!( + config_options(&json!({"configOptions":[{"type":"select","id":"broken","currentValue":"x","options":[]}]})), + ConfigParse::Invalid + )); + assert_eq!(config_options(&json!({"configOptions":[]})), ConfigParse::Snapshot(vec![])); + let notification = json!({"sessionUpdate":"config_option_update","configOptions":[]}); + assert_eq!(update(¬ification, "s"), Incoming::ConfigOptions { session: "s".into(), options: vec![] }); + } + + #[test] + fn config_snapshots_bound_choices_and_preserve_unknown_categories() { + let choices: Vec<_> = (0..300).map(|n| json!({"value":n.to_string(),"name":"Choice"})).collect(); + let option = json!({"id":"custom","name":"Custom","type":"select","currentValue":"0","options":[ + {"group":"internal-id","name":"Readable group","options":choices}, + {"value":"extra","name":"Extra"} + ]}); + let ConfigParse::Snapshot(options) = config_options(&json!({"configOptions":[option.clone(),option]})) else { panic!() }; + assert_eq!(options.len(), 1, "duplicate IDs do not produce duplicate controls"); + assert_eq!(options[0].options.len(), 128, "the choice cap spans groups and flat entries"); + assert_eq!(options[0].options[0].group.as_deref(), Some("Readable group")); + assert_eq!(options[0].category, "", "categories are optional metadata"); + assert_eq!(config_options(&json!({})), ConfigParse::Absent); + assert_eq!(config_options(&json!({"configOptions":null})), ConfigParse::Invalid); + assert_eq!(config_options(&json!({"configOptions":[{"type":"select","id":"broken"}]})), ConfigParse::Invalid); } } diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index d1c91ae1a..7255dab25 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -3,6 +3,7 @@ //! sign-in). The panel sees only [`Event`]s. use std::collections::HashMap; +use std::time::{Duration, Instant}; use serde_json::{Value, json}; @@ -18,8 +19,12 @@ enum Pending { Authenticate, SetMode, SetModel, + SetConfig, } +/// Give a cancelled prompt time to finish before disconnecting an unresponsive agent. +const CANCEL_GRACE: Duration = Duration::from_secs(5); + /// Variables the agent doesn't inherit: a control token set for the app's own `--control` port /// would otherwise reach the agent and outrank the chat endpoint's own token file. const ENV_REMOVE: &[&str] = &["SOLIDCRAFT_CONTROL_TOKEN"]; @@ -28,6 +33,8 @@ pub struct AcpBackend { proc: AgentProcess, cwd: std::path::PathBuf, bridge: Option, + /// The agent's `initialize` reply: which routes the system note can take into a session. + init: Value, next_id: u64, pending: HashMap, session: Option, @@ -38,7 +45,10 @@ pub struct AcpBackend { /// Open permission questions: our key → the agent's request id. permissions: HashMap, next_key: u64, + cancelling: Option<(u64, Instant)>, exited: bool, + config_pending: Option<(u64, String)>, + modern_config: bool, } impl AcpBackend { @@ -53,6 +63,7 @@ impl AcpBackend { proc, cwd, bridge, + init: Value::Null, next_id: 0, pending: HashMap::new(), session: None, @@ -62,7 +73,10 @@ impl AcpBackend { auth: Vec::new(), permissions: HashMap::new(), next_key: 0, + cancelling: None, exited: false, + config_pending: None, + modern_config: false, }; b.request(Pending::Initialize, "initialize", acp::initialize_params(env!("CARGO_PKG_VERSION"))); Ok(b) @@ -75,7 +89,9 @@ impl AcpBackend { } fn new_session(&mut self) { - let params = acp::session_new_params(&self.cwd, self.bridge.as_ref()); + self.config_pending = None; + self.pending.retain(|_, request| *request != Pending::SetConfig); + let params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init); self.request(Pending::SessionNew, "session/new", params); } @@ -83,22 +99,41 @@ impl AcpBackend { match msg { Incoming::Reply { id, result } => { let Some(what) = self.pending.remove(&id) else { return }; + if self.cancelling.is_some_and(|(request, _)| request == id) { + self.cancelling = None; + } match (what, result) { (Pending::Initialize, Ok(v)) => { self.agent = acp::agent_info(&v); self.images = acp::takes_images(&v); self.documents = acp::takes_documents(&v); self.auth = acp::auth_methods(&v); + self.init = v; self.new_session(); } (Pending::SessionNew, Ok(v)) => match v.get("sessionId").and_then(Value::as_str) { Some(s) => { - self.session = Some(s.to_string()); - if let Some((current, available)) = acp::modes(&v) { - out.push(Event::Modes { current, available }); + // New chat has opened successfully: retire the old turn before Ready. + // Its late reply and cancellation deadline must not end the new turn. + if let Some((request, _)) = self.cancelling.take() { + self.pending.remove(&request); + out.push(Event::TurnEnded { reason: "cancelled".into() }); } - if let Some((current, available)) = acp::models(&v) { - out.push(Event::Models { current, available }); + self.session = Some(s.to_string()); + match acp::config_options(&v) { + acp::ConfigParse::Snapshot(options) => { + self.modern_config = true; + out.push(Event::ConfigOptions(options)); + } + _ => { + self.modern_config = false; + if let Some((current, available)) = acp::modes(&v) { + out.push(Event::Modes { current, available }); + } + if let Some((current, available)) = acp::models(&v) { + out.push(Event::Models { current, available }); + } + } } out.push(Event::Documents(self.documents)); out.push(Event::Ready { agent: self.agent.clone(), images: self.images }); @@ -112,15 +147,43 @@ impl AcpBackend { // Signed in: try the session again. (Pending::Authenticate, Ok(_)) => self.new_session(), (Pending::SetMode | Pending::SetModel, Ok(_)) => {} + (Pending::SetConfig, Ok(v)) => { + if let Some((request_id, config_id)) = self.config_pending.take() + && request_id == id + { + let result = match acp::config_options(&v) { + acp::ConfigParse::Snapshot(o) => Ok(o), + _ => Err("The agent returned no valid configuration options.".into()), + }; + out.push(Event::ConfigOptionFinished { id: config_id, result }); + } + } + // `session/set_model` is still unstable in ACP: an agent can list `models` and + // still not serve it (#9970). It keeps its own model; that is no error to show. + (Pending::SetModel, Err((acp::METHOD_NOT_FOUND, message))) => { + log::debug!("agent does not serve session/set_model: {message}"); + } (what, Err((code, message))) => { + let config_error = what == Pending::SetConfig; + if what == Pending::SetConfig + && let Some((request_id, config_id)) = self.config_pending.take() + && request_id == id + { + out.push(Event::ConfigOptionFinished { id: config_id, result: Err(message.clone()) }); + } let auth = code == acp::AUTH_REQUIRED || message.to_ascii_lowercase().contains("auth"); if auth { self.session = None; + self.modern_config = false; + self.config_pending = None; + self.pending.retain(|_, request| *request != Pending::SetConfig); if what == Pending::Prompt { out.push(Event::TurnEnded { reason: "auth".into() }); } out.push(Event::AuthRequired { methods: self.auth.clone() }); - } else { + } else if what == Pending::SetModel { + out.push(Event::ModelRejected(message)); + } else if !config_error { if what == Pending::Prompt { out.push(Event::TurnEnded { reason: "error".into() }); } @@ -132,24 +195,35 @@ impl AcpBackend { Incoming::Text { thought, text } => out.push(Event::Text { thought, text }), Incoming::Tool { id, title, kind, status, input, output } => out.push(Event::Tool { id, title, kind, status, input, output }), Incoming::Plan(p) => out.push(Event::Plan(p)), - Incoming::Permission { rpc, title, options } => { + Incoming::Permission { rpc, title, kind, options } => { self.next_key += 1; self.permissions.insert(self.next_key, rpc); - out.push(Event::Permission { key: self.next_key, title, options }); + out.push(Event::Permission { key: self.next_key, title, kind, options }); } Incoming::AuthStatus(s) => out.push(Event::AuthStatus(s)), - Incoming::ModeChanged(m) => out.push(Event::Modes { current: m, available: Vec::new() }), - Incoming::ModelChanged(m) => out.push(Event::Models { current: m, available: Vec::new() }), + Incoming::ModeChanged(m) if !self.modern_config => out.push(Event::Modes { current: m, available: Vec::new() }), + Incoming::ModelChanged(m) if !self.modern_config => out.push(Event::Models { current: m, available: Vec::new() }), + Incoming::ConfigOptions { session, options } if self.session.as_deref() == Some(session.as_str()) => { + out.push(Event::ConfigOptions(options)) + } + Incoming::ModeChanged(_) | Incoming::ModelChanged(_) | Incoming::ConfigOptions { .. } => {} Incoming::Unsupported { rpc, method } => { self.proc.send(&acp::reply_error(rpc, acp::METHOD_NOT_FOUND, &format!("SolidCraft does not serve `{method}`"))); } Incoming::Ignored => {} } } -} -impl ChatBackend for AcpBackend { - fn poll(&mut self) -> Vec { + fn finish_exit(&mut self, tail: Vec) -> Event { + self.exited = true; + self.session = None; + self.pending.clear(); + self.cancelling = None; + self.config_pending = None; + Event::Exited { tail } + } + + fn poll_at(&mut self, now: Instant) -> Vec { let mut out = Vec::new(); if self.exited { return out; @@ -162,17 +236,25 @@ impl ChatBackend for AcpBackend { } } Ok(FromAgent::Exited(tail)) => { - self.exited = true; - self.session = None; - self.pending.clear(); - out.push(Event::Exited { tail }); + out.push(self.finish_exit(tail)); break; } Err(_) => break, } } + // Drain replies first: an acknowledgement already waiting must keep the connection. + if self.cancelling.is_some_and(|(_, started)| now.saturating_duration_since(started) >= CANCEL_GRACE) { + self.proc.shutdown(false); + out.push(self.finish_exit(vec![crate::i18n::tr("ui.agent_chat_cancel_timeout").to_string()])); + } out } +} + +impl ChatBackend for AcpBackend { + fn poll(&mut self) -> Vec { + self.poll_at(Instant::now()) + } fn prompt(&mut self, parts: &[PromptPart]) { if let Some(s) = self.session.clone() { @@ -187,6 +269,11 @@ impl ChatBackend for AcpBackend { } if let Some(s) = &self.session { self.proc.send(&acp::notification("session/cancel", json!({"sessionId": s}))); + // Repeated Stop presses must not postpone the fallback. An idle session needs none. + if self.cancelling.is_none() { + self.cancelling = + self.pending.iter().find_map(|(&id, request)| (*request == Pending::Prompt).then_some(id)).map(|id| (id, Instant::now())); + } } } @@ -195,6 +282,9 @@ impl ChatBackend for AcpBackend { self.cancel(); } self.session = None; + self.modern_config = false; + self.config_pending = None; + self.pending.retain(|_, request| *request != Pending::SetConfig); self.new_session(); } @@ -220,6 +310,16 @@ impl ChatBackend for AcpBackend { } } + fn set_config_option(&mut self, id: &str, value: &str) { + if self.config_pending.is_some() { + return; + } + if let Some(s) = self.session.clone() { + self.request(Pending::SetConfig, "session/set_config_option", acp::set_config_option_params(&s, id, value)); + self.config_pending = Some((self.next_id, id.to_string())); + } + } + fn pid(&self) -> Option { self.proc.pid() } @@ -262,7 +362,7 @@ pub fn test_agent(argv: &[String], cwd: &std::path::Path) -> Result Result Result { + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx)?; + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); + backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + Ok(backend) + } + + #[test] + fn an_unresponsive_cancel_disconnects_the_agent() { + let mut backend = ready_backend().unwrap(); + backend.prompt(&[PromptPart::Text("stalled search".into())]); + backend.cancel(); + let started = backend.cancelling.unwrap().1; + assert!(backend.poll_at(started + CANCEL_GRACE - Duration::from_millis(1)).is_empty()); + backend.cancel(); + let events = backend.poll_at(started + CANCEL_GRACE); + assert!(matches!(events.as_slice(), [Event::Exited { .. }]), "Stop must not wait indefinitely: {events:?}"); + assert!(backend.pid().is_none()); + assert!(backend.session.is_none() && backend.pending.is_empty()); + assert!(backend.poll().is_empty(), "the exit is reported only once"); + } + + #[test] + fn a_cancelled_prompt_reply_keeps_the_connection() { + for reply in [Ok(json!({"stopReason":"cancelled"})), Err((-32603, "operation aborted".into()))] { + let mut backend = ready_backend().unwrap(); + backend.prompt(&[PromptPart::Text("search".into())]); + let request = backend.next_id; + backend.cancel(); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: request, result: reply }, &mut events); + assert!(events.iter().any(|e| matches!(e, Event::TurnEnded { .. }))); + assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty()); + assert!(backend.pid().is_some() && !backend.exited); + backend.shutdown(true); + } + } + + #[test] + fn cancelling_an_idle_session_does_not_disconnect_it() { + let mut backend = ready_backend().unwrap(); + backend.cancel(); + assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty()); + assert!(backend.pid().is_some() && !backend.exited); + backend.shutdown(true); + } + + #[test] + fn a_new_session_retires_the_old_cancelled_prompt() { + let mut backend = ready_backend().unwrap(); + backend.prompt(&[PromptPart::Text("old search".into())]); + let old_prompt = backend.next_id; + backend.cancel(); + ChatBackend::new_session(&mut backend); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({"sessionId":"s2"})) }, &mut events); + assert!(matches!(events.first(), Some(Event::TurnEnded { reason }) if reason == "cancelled")); + assert!(matches!(events.last(), Some(Event::Ready { .. }))); + backend.prompt(&[PromptPart::Text("new search".into())]); + assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty(), "a new session has no stale cancellation deadline"); + backend.cancel(); + events.clear(); + backend.handle(Incoming::Reply { id: old_prompt, result: Ok(json!({"stopReason":"cancelled"})) }, &mut events); + assert!(events.is_empty(), "an old reply must not end the new turn or clear its cancellation deadline"); + assert!(matches!(backend.poll_at(Instant::now() + CANCEL_GRACE).as_slice(), [Event::Exited { .. }])); + } + + fn snapshot(session: &str, value: &str) -> Value { + json!({"sessionId":session,"configOptions":[{"id":"provider.model","category":"model","name":"Model","type":"select","currentValue":value,"options":[{"value":"fast","name":"Fast"},{"value":"smart","name":"Smart"}]}]}) + } + + #[test] + fn config_updates_and_replies_are_isolated_to_the_active_session() { + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap(); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); + backend.handle(Incoming::Reply { id: 2, result: Ok(snapshot("s1", "fast")) }, &mut events); + assert_eq!(backend.session.as_deref(), Some("s1")); + events.clear(); + backend.set_config_option("provider.model", "smart"); + let old_request = backend.config_pending.as_ref().map(|p| p.0).unwrap(); + ChatBackend::new_session(&mut backend); + let new_session_request = backend.next_id; + assert!(backend.config_pending.is_none()); + let old_notification = r#"{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"config_option_update","configOptions":[]}}}"#; + backend.handle(acp::parse(old_notification).unwrap(), &mut events); + assert!(events.is_empty()); + backend.handle(Incoming::Reply { id: new_session_request, result: Ok(snapshot("s2", "fast")) }, &mut events); + assert_eq!(backend.session.as_deref(), Some("s2")); + events.clear(); + backend.set_config_option("provider.model", "smart"); + let new_request = backend.config_pending.as_ref().map(|p| p.0).unwrap(); + backend.handle(Incoming::Reply { id: old_request, result: Ok(snapshot("s1", "smart")) }, &mut events); + backend.handle(Incoming::Reply { id: old_request, result: Err((-32001, "old rejected request".into())) }, &mut events); + backend.handle(acp::parse(old_notification).unwrap(), &mut events); + assert!(events.is_empty(), "old requests and session notifications are ignored"); + assert_eq!(backend.config_pending.as_ref().map(|p| p.0), Some(new_request), "an old reply cannot clear the new session's pending request"); + let new_notification = r#"{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s2","update":{"sessionUpdate":"config_option_update","configOptions":[]}}}"#; + backend.handle(acp::parse(new_notification).unwrap(), &mut events); + assert!(matches!(events.as_slice(), [Event::ConfigOptions(options)] if options.is_empty())); + assert_eq!(backend.config_pending.as_ref().map(|p| p.0), Some(new_request), "a notification is not an acknowledgement"); + events.clear(); + backend.handle(Incoming::Reply { id: new_request, result: Ok(snapshot("s2", "smart")) }, &mut events); + assert!(backend.config_pending.is_none()); + assert!(matches!(events.as_slice(), [Event::ConfigOptionFinished { result: Ok(options), .. }] if options[0].current_value == "smart")); + backend.shutdown(true); + } + + /// A refused model is the picker's business, not an error of the chat; signing in stays as it was. + #[test] + fn a_refused_model_is_reported_as_such() { + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap(); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); + backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + events.clear(); + backend.set_model("zzz"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Err((-32602, "no such model".into())) }, &mut events); + assert!(matches!(events.as_slice(), [Event::ModelRejected(message)] if message == "no such model"), "{events:?}"); + events.clear(); + backend.set_model("fast"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({})) }, &mut events); + assert!(events.is_empty(), "{events:?}"); + backend.set_model("zzz"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Err((acp::AUTH_REQUIRED, "sign in".into())) }, &mut events); + assert!(matches!(events.as_slice(), [Event::AuthRequired { .. }]), "{events:?}"); + backend.shutdown(true); + } +} diff --git a/crates/ui-egui/src/agent_chat/agents.rs b/crates/ui-egui/src/agent_chat/agents.rs index c05102b8d..145b94579 100644 --- a/crates/ui-egui/src/agent_chat/agents.rs +++ b/crates/ui-egui/src/agent_chat/agents.rs @@ -76,7 +76,7 @@ impl Kind { } /// The wire protocol of an endpoint the user added. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Protocol { /// `{base}/chat/completions`, as Ollama, LM Studio, OpenAI and their kin speak. #[default] @@ -113,6 +113,9 @@ pub struct AgentConfig { /// API: how long one model request may take, in seconds (clamped to /// [`MIN_REQUEST_TIMEOUT_S`]..=[`MAX_REQUEST_TIMEOUT_S`] where it is used). pub request_timeout_s: u64, + /// API: the reasoning effort to send as `reasoning_effort`; empty sends nothing and the + /// provider's own default applies (trimmed and length-capped by [`reasoning_effort`]). + pub reasoning_effort: String, } impl Default for AgentConfig { @@ -127,6 +130,7 @@ impl Default for AgentConfig { ollama: false, key: false, request_timeout_s: DEFAULT_REQUEST_TIMEOUT_S, + reasoning_effort: String::new(), } } } @@ -148,6 +152,15 @@ pub fn request_timeout_s(secs: f64) -> u64 { secs.round().clamp(MIN_REQUEST_TIMEOUT_S as f64, MAX_REQUEST_TIMEOUT_S as f64) as u64 } +/// The longest reasoning effort an endpoint can be given (no provider names one near this). +pub const MAX_REASONING_EFFORT_LEN: usize = 64; + +/// A reasoning effort as stored: trimmed, and capped so a hand-edited preferences file or the +/// control channel cannot carry an absurd value into every request. Empty means "send nothing". +pub fn reasoning_effort(raw: &str) -> String { + raw.trim().chars().take(MAX_REASONING_EFFORT_LEN).collect() +} + /// An agent as the picker and the switcher show it. #[derive(Clone, Debug, PartialEq)] pub struct Entry { @@ -167,6 +180,12 @@ pub struct Entry { pub key: bool, /// API: seconds one model request may take (in range). pub request_timeout_s: u64, + /// API: the reasoning effort to send, empty for none (trimmed, in length). + pub reasoning_effort: String, + /// Found installed, but its program didn't start when asked its version: why (#9034). + pub problem: Option, + /// Found installed: the command that installs it again. + pub install: &'static str, } impl Entry { @@ -183,18 +202,32 @@ impl Entry { model: c.model.clone(), key: c.key, request_timeout_s: c.request_timeout_s.clamp(MIN_REQUEST_TIMEOUT_S, MAX_REQUEST_TIMEOUT_S), + reasoning_effort: reasoning_effort(&c.reasoning_effort), + problem: None, + install: "", } } - /// A short line under the name: the version, the model, or the command. + /// A short line under the name: the version, the model, the command, or why it can't start. pub fn detail(&self) -> String { match self.kind { Kind::Api | Kind::Anthropic => format!("{} · {}", self.model, self.base_url), - Kind::Acp => match &self.version { - Some(v) => v.clone(), - None => super::panel::short_command(&self.argv.join(" ")), + Kind::Acp => match (&self.problem, &self.version) { + (Some(p), _) => crate::i18n::format("ui.agent_chat_cannot_start", &[("error", p)]), + (None, Some(v)) => v.clone(), + (None, None) => super::panel::short_command(&self.argv.join(" ")), }, } } + /// What to tell someone starting an agent that was found but didn't start (#9034): the reason, + /// and how to install it again. `None` when nothing was seen wrong. + pub fn problem_hint(&self) -> Option { + let problem = self.problem.as_deref()?; + let program = self.argv.first().map(String::as_str).unwrap_or_default(); + Some(crate::i18n::format( + "ui.agent_chat_reinstall", + &[("agent", &self.name), ("program", program), ("error", problem), ("install", self.install)], + )) + } } /// Every agent the chat can use: the installed ones found, then the ones the user added. @@ -214,6 +247,9 @@ pub fn entries(app: &crate::SolveApp) -> Vec { model: String::new(), key: false, request_timeout_s: DEFAULT_REQUEST_TIMEOUT_S, + reasoning_effort: String::new(), + problem: f.problem.clone(), + install: f.install, })); } out.extend(app.preferences.agents.iter().map(Entry::from_config)); @@ -267,9 +303,11 @@ pub struct ApiPreset { pub const OPENAI_PRESETS: &[ApiPreset] = &[ ApiPreset { name: "Ollama", base_url: "http://localhost:11434/v1" }, ApiPreset { name: "LM Studio", base_url: "http://localhost:1234/v1" }, + ApiPreset { name: "OpenClaw", base_url: "http://localhost:18789/v1" }, ApiPreset { name: "OpenAI", base_url: "https://api.openai.com/v1" }, ApiPreset { name: "Mammouth AI", base_url: "https://api.mammouth.ai/v1" }, ApiPreset { name: "OpenCode Go", base_url: "https://opencode.ai/zen/go/v1" }, + ApiPreset { name: "OpenRouter", base_url: "https://openrouter.ai/api/v1" }, ]; /// Anthropic-compatible endpoints people use. The base URL is the one their documentation calls @@ -291,14 +329,32 @@ pub fn key_safe_for(url: &str) -> bool { return true; } let Some(rest) = u.strip_prefix("http://") else { return false }; - let host = rest.split(['/', '?']).next().unwrap_or(""); - let host = host.rsplit_once('@').map_or(host, |(_, h)| h); - let name = if host.starts_with('[') { - host.split(']').next().map(|h| format!("{h}]")).unwrap_or_default() - } else { - host.split(':').next().unwrap_or("").to_string() + // The host part ends where the HTTP client ends it, at the first `/`, `?` or `#`. + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + local_authority(authority) +} + +/// `authority` is exactly this computer's name with at most a port. No user name goes before it +/// and no stray character after it, as URL parsers don't all read those the same way. +fn local_authority(authority: &str) -> bool { + let (host, port) = match authority.strip_prefix('[') { + Some(inner) => { + let Some((ip, after)) = inner.split_once(']') else { return false }; + if ip != "::1" { + return false; + } + ("[::1]", after) + } + None => { + let end = authority.find(':').unwrap_or(authority.len()); + authority.split_at(end) + } }; - matches!(name.as_str(), "localhost" | "127.0.0.1" | "[::1]") + let port_ok = match port.strip_prefix(':') { + Some(digits) => digits.bytes().all(|b| b.is_ascii_digit()) && digits.parse::().is_ok(), + None => port.is_empty(), + }; + port_ok && matches!(host, "localhost" | "127.0.0.1" | "[::1]") } /// A base URL the API backend accepts: `http(s)://host…`, without a trailing slash. @@ -328,6 +384,56 @@ mod tests { assert!(!key_safe_for("ftp://x")); } + /// Plain HTTP only reaches this computer: the check reads the host where the HTTP client does, + /// and takes nothing around the name that URL parsers could read differently. + #[test] + fn a_key_over_http_needs_a_url_that_can_only_mean_this_computer() { + for url in [ + "http://localhost", + "HTTP://LOCALHOST:11434/v1", + " http://localhost:11434/v1/ ", + "http://127.0.0.1:1234/v1?x=1", + "http://[::1]/v1", + "http://[::1]:8080/v1", + "http://localhost:65535/@models", + ] { + assert!(key_safe_for(url), "{url}"); + } + for url in [ + "http://evil.example#@localhost/v1", + "http://evil.example?@localhost/v1", + "http://evil.example/@localhost/v1", + "http://evil.example\\@localhost/v1", + "http://localhost\\@evil.example/v1", + "http://localhost\\.evil.example/v1", + "http://localhost@evil.example/v1", + "http://localhost:1234@evil.example/v1", + "http://user@localhost/v1", + "http://user:secret@localhost:1234/v1", + "http://[::1]@evil.example/v1", + "http://[::1].evil.example/v1", + "http://[::1]evil.example/v1", + "http://[::2]/v1", + "http://[::1/v1", + "http://127.0.0.1.evil.example/v1", + "http://localhost.evil.example:1234/v1", + "http://localhost:80.evil.example/v1", + "http://localhost:abc/v1", + "http://localhost:/v1", + "http://localhost:65536/v1", + "http://local\thost.evil.example/v1", + "http://localhost evil.example/v1", + "http://localhost%2eevil.example/v1", + "http://", + "http:///localhost/v1", + "http:/localhost/v1", + "//localhost/v1", + "localhost:1234/v1", + ] { + assert!(!key_safe_for(url), "{url}"); + } + } + #[test] fn modes_and_ids_round_trip() { for m in Mode::ALL { @@ -364,6 +470,18 @@ mod tests { assert!(presets(Protocol::Anthropic).iter().any(|p| p.base_url == "https://api.anthropic.com/v1")); } + /// The first preset is the one an Add dialog opens with, and the one taken for Ollama. + #[test] + fn ollama_stays_the_first_preset_and_every_preset_can_take_a_key() { + assert_eq!(OPENAI_PRESETS.first().map(|p| p.name), Some("Ollama")); + assert_eq!(OPENAI_PRESETS.last().map(|p| p.name), Some("OpenRouter")); + assert!(OPENAI_PRESETS.iter().any(|p| p.name == "OpenClaw")); + for preset in OPENAI_PRESETS.iter().chain(ANTHROPIC_PRESETS) { + assert_eq!(normalize_url(preset.base_url).as_deref(), Ok(preset.base_url), "{}", preset.name); + assert!(key_safe_for(preset.base_url), "{}", preset.name); + } + } + #[test] fn request_timeouts_default_to_300_s_and_stay_between_30_s_and_an_hour() { assert_eq!(AgentConfig::default().request_timeout_s, 300); @@ -382,4 +500,23 @@ mod tests { let back: AgentConfig = serde_json::from_value(serde_json::to_value(&saved).unwrap()).unwrap(); assert_eq!(back, saved); } + + #[test] + fn reasoning_effort_defaults_to_empty_and_is_trimmed_and_capped() { + assert!(AgentConfig::default().reasoning_effort.is_empty()); + // An older preferences file has no effort: empty, so nothing is sent. + let old: AgentConfig = serde_json::from_str(r#"{"id":"api-1","kind":"api","base_url":"http://localhost:11434/v1","model":"m"}"#).unwrap(); + assert!(old.reasoning_effort.is_empty()); + assert_eq!(reasoning_effort(" high "), "high"); + assert!(reasoning_effort(" ").is_empty()); + let long = reasoning_effort(&"x".repeat(500)); + assert_eq!(long.chars().count(), MAX_REASONING_EFFORT_LEN); + let saved = AgentConfig { id: "api-2".into(), kind: Kind::Api, reasoning_effort: "max".into(), ..Default::default() }; + let back: AgentConfig = serde_json::from_value(serde_json::to_value(&saved).unwrap()).unwrap(); + assert_eq!(back, saved); + // The entry carries it trimmed; a hand-edited over-long one is capped where used. + assert_eq!(Entry::from_config(&saved).reasoning_effort, "max"); + let wild: AgentConfig = serde_json::from_str(&format!(r#"{{"id":"api-3","kind":"api","reasoning_effort":"{}"}}"#, "y".repeat(500))).unwrap(); + assert_eq!(Entry::from_config(&wild).reasoning_effort.chars().count(), MAX_REASONING_EFFORT_LEN); + } } diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 2c9b57150..e3bc37ecb 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -15,6 +15,7 @@ use std::time::Duration; use serde_json::{Map, Value, json}; +use super::MODEL_LIST_CAP; use super::acp::ModelInfo; use super::agents::Protocol; use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus}; @@ -22,6 +23,8 @@ use super::process::{AgentProcess, FromAgent, ProcessHandle}; /// Longest tool result handed back to the model. const MAX_TOOL_TEXT: usize = 20_000; +/// Longest name kept for a listed model. +const MODEL_NAME_CAP: usize = 256; /// Messages kept in the conversation (the system note stays). const MAX_HISTORY: usize = 240; /// Pictures of the view kept in the conversation. The whole history goes with every request @@ -30,6 +33,7 @@ const MAX_HISTORY: usize = 240; const MAX_HISTORY_IMAGES: usize = 2; /// What an older view becomes in the history. const DROPPED_VIEW_NOTE: &str = "[an earlier picture of the view, removed to keep the request small]"; +const DROPPED_THINKING_NOTE: &str = "[earlier reasoning, removed with older history]"; /// How long one tool call may take (it may wait for the user's Allow, declined after four /// minutes). It does not depend on the endpoint's request timeout: a tool call is SolidCraft's own /// work and the user's answer, never a wait for the model, so a longer request timeout does not @@ -503,7 +507,7 @@ fn go_reply_from_parts(text: Vec<(bool, String)>, calls: Vec, kept_calls: if !kept_calls.is_empty() { assistant["tool_calls"] = Value::Array(kept_calls); } - Reply { text, calls, assistant } + Reply { text, calls, assistant, stop: "" } } /// Shared text + capped tool-call accumulator for the three Go reply parsers. @@ -642,6 +646,10 @@ pub struct ApiConfig { pub http: HttpFn, /// How long one model request may take, in seconds (the endpoint's setting). pub request_timeout_s: u64, + /// The reasoning effort to send as `reasoning_effort`; empty sends nothing and the + /// provider's own default applies. A set value wins over the `none` retry (#3817): that + /// retry only runs when no effort was chosen. + pub reasoning_effort: String, } enum Cmd { @@ -649,6 +657,7 @@ enum Cmd { NewChat, SetModel(String), SetRequestTimeout(u64), + SetReasoningEffort(String), } pub struct ApiBackend { @@ -723,6 +732,11 @@ impl ChatBackend for ApiBackend { let _ = c.send(Cmd::SetRequestTimeout(secs)); } } + fn set_reasoning_effort(&mut self, effort: &str) { + if let Some(c) = &self.cmds { + let _ = c.send(Cmd::SetReasoningEffort(effort.to_string())); + } + } fn new_session(&mut self) { // A running turn is cancelled; the worker resets the history once it has ended. self.cancel.store(true, Ordering::Relaxed); @@ -784,21 +798,36 @@ impl Worker { } self.emit(Event::ToolsAvailable(!self.tools.is_empty())); self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true }); - // The endpoint's models for the picker; an endpoint that does not list them shows none. - if let Ok(list) = self.model_list() { - let mut available = list; - if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) { - available.insert(0, ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }); + // The endpoint's models for the picker. An endpoint that does not list them still shows the + // configured model, and says why there are no others. + let configured = ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }; + let available = match self.model_list() { + Ok(mut list) => { + self.emit(Event::ModelsNote(None)); + if !self.cfg.model.is_empty() && !list.iter().any(|m| m.id == self.cfg.model) { + list.insert(0, configured); + } + list } - if !available.is_empty() { - self.emit(Event::Models { current: self.cfg.model.clone(), available }); + Err(e) => { + self.emit(Event::ModelsNote(Some(e))); + if self.cfg.model.is_empty() { Vec::new() } else { vec![configured] } } + }; + if !available.is_empty() { + self.emit(Event::Models { current: self.cfg.model.clone(), available }); } for cmd in cmds { match cmd { Cmd::Prompt(parts) => self.turn(parts), Cmd::SetModel(m) => self.cfg.model = m, Cmd::SetRequestTimeout(secs) => self.cfg.request_timeout_s = secs, + Cmd::SetReasoningEffort(effort) => { + self.cfg.reasoning_effort = super::agents::reasoning_effort(&effort); + // A new choice starts the refusal dance again: an earlier `none` answer was + // the endpoint's, not the user's, and must not silently override the choice. + self.no_reasoning.set(false); + } Cmd::NewChat => { self.history.clear(); // A new conversation gets a fresh Go session ID for routing and caching. @@ -876,8 +905,11 @@ impl Worker { fn turn(&mut self, parts: Vec) { self.history.push(user_message(self.cfg.protocol, &parts)); - drop_old_views(&mut self.history, MAX_HISTORY_IMAGES); - self.trim_history(); + let dropped = drop_old_views(&mut self.history, MAX_HISTORY_IMAGES); + let trimmed = self.trim_history(); + if (dropped || trimmed) && self.cfg.protocol == Protocol::Anthropic { + drop_thinking(&mut self.history); + } // No cap on requests: Stop sets `cancel`, checked at the top of every round. loop { // The history as of here is complete (every tool call answered): a cancelled request @@ -910,7 +942,7 @@ impl Worker { } self.history.push(reply.assistant); if reply.calls.is_empty() { - self.emit(Event::TurnEnded { reason: String::new() }); + self.emit(Event::TurnEnded { reason: reply.stop.into() }); return; } // Anthropic takes every result of a round in one user message; OpenAI takes one @@ -964,14 +996,22 @@ impl Worker { } /// Keep the conversation bounded and starting at a user message, so neither protocol sees a - /// reply or a tool result without the message it answers. - fn trim_history(&mut self) { + /// reply or a tool result without the message it answers. True when a message was removed. + fn trim_history(&mut self) -> bool { + let before = self.history.len(); while self.history.len() > MAX_HISTORY { self.history.remove(0); } while self.history.first().is_some_and(|m| !starts_a_turn(m)) { self.history.remove(0); } + self.history.len() != before + } + + /// The reasoning effort the user chose for this endpoint, or `None` to send nothing and let + /// the provider apply its own default. + fn reasoning_effort(&self) -> Option<&str> { + (!self.cfg.reasoning_effort.trim().is_empty()).then(|| self.cfg.reasoning_effort.trim()) } fn request(&self) -> Result { @@ -983,11 +1023,13 @@ impl Worker { let (status, v) = self.post(&body)?; // Some OpenAI models refuse function tools on this endpoint unless the reasoning effort is // "none" (HTTP 400 naming `reasoning_effort`): ask again once with it, and keep it for the - // next requests. Anthropic has no such parameter. + // next requests. Anthropic has no such parameter. A reasoning effort the user chose wins: + // the refusal is shown instead of being replaced silently (#10241). let refused = self.cfg.protocol == Protocol::OpenAi && status == 400 && !self.tools.is_empty() && !self.no_reasoning.get() + && self.reasoning_effort().is_none() && http_error(status, &v).contains("reasoning_effort"); if refused { self.no_reasoning.set(true); @@ -1015,15 +1057,19 @@ impl Worker { let mut first_err: Option = None; for protocol in order { let mut body = self.go_body(protocol); - if protocol == GoProtocol::Chat && !self.tools.is_empty() && self.no_reasoning.get() { + if protocol == GoProtocol::Chat && !self.tools.is_empty() && self.no_reasoning.get() && self.reasoning_effort().is_none() { body["reasoning_effort"] = json!("none"); } let (status, v) = self.go_post(protocol, &body)?; if protocol == GoProtocol::Chat { // As on plain OpenAI endpoints: ask again once with reasoning effort - // "none" when the refusal names it. - let refused = - status == 400 && !self.tools.is_empty() && !self.no_reasoning.get() && http_error(status, &v).contains("reasoning_effort"); + // "none" when the refusal names it — unless the user chose an effort, whose + // refusal is shown instead (#10241). + let refused = status == 400 + && !self.tools.is_empty() + && !self.no_reasoning.get() + && self.reasoning_effort().is_none() + && http_error(status, &v).contains("reasoning_effort"); if refused { self.no_reasoning.set(true); body["reasoning_effort"] = json!("none"); @@ -1137,9 +1183,14 @@ impl Worker { messages.push(json!({"role": "system", "content": super::acp::SYSTEM_NOTE})); messages.extend(self.history.iter().cloned()); let mut body = json!({"model": self.cfg.model, "messages": messages}); + if let Some(effort) = self.reasoning_effort() { + // The user's choice goes out on every request, ahead of any `none` the + // endpoint once asked for (#10241). + body["reasoning_effort"] = json!(effort); + } if !self.tools.is_empty() { body["tools"] = Value::Array(self.tools.clone()); - if self.no_reasoning.get() { + if self.no_reasoning.get() && self.reasoning_effort().is_none() { body["reasoning_effort"] = json!("none"); } } @@ -1326,6 +1377,19 @@ struct Reply { /// The assistant message to keep in the history, in the endpoint's own shape. Tool calls are /// capped to the ones the loop answers, so every call kept here gets a result. assistant: Value, + /// Why the answer stopped, as the turn-end reason the chat knows: empty for a normal end, + /// `max_tokens` for an answer cut off at its length limit, `refusal` when the model declined. + stop: &'static str, +} + +/// The turn-end reason for an Anthropic `stop_reason` or an OpenAI `finish_reason`. Anything +/// else, including a value a server made up, is a normal end. +fn stop_reason(reason: Option<&str>) -> &'static str { + match reason { + Some("max_tokens" | "length") => "max_tokens", + Some("refusal" | "content_filter") => "refusal", + _ => "", + } } /// The answer in the endpoint's shape. @@ -1357,8 +1421,16 @@ fn sanitize_reasoning_details(details: Option<&Value>) -> Option { fn openai_reply(body: &Value) -> Reply { let message = body.pointer("/choices/0/message").cloned().unwrap_or(Value::Null); let text = message.get("content").and_then(Value::as_str).filter(|t| !t.is_empty()).map(|t| vec![(false, t.to_string())]).unwrap_or_default(); - // No more than the loop answers: every call kept here must get a `tool` message. - let raw: Vec = message.get("tool_calls").and_then(Value::as_array).map(|a| a.iter().take(32).cloned().collect()).unwrap_or_default(); + let refused = message.get("refusal").and_then(Value::as_str).is_some_and(|r| !r.trim().is_empty()); + let stop = if refused { "refusal" } else { stop_reason(body.pointer("/choices/0/finish_reason").and_then(Value::as_str)) }; + // No more than the loop answers: every call kept here must get a `tool` message. A call cut + // off at the length limit is incomplete, so none is run or kept. + let raw: Vec = message + .get("tool_calls") + .and_then(Value::as_array) + .filter(|_| stop != "max_tokens") + .map(|a| a.iter().take(32).cloned().collect()) + .unwrap_or_default(); let calls = raw .iter() .enumerate() @@ -1384,11 +1456,12 @@ fn openai_reply(body: &Value) -> Reply { if !raw.is_empty() { assistant["tool_calls"] = Value::Array(raw); } - Reply { text, calls, assistant } + Reply { text, calls, assistant, stop } } fn anthropic_reply(body: &Value) -> Reply { let content = body.get("content").cloned().unwrap_or(Value::Null); + let stop = stop_reason(body.get("stop_reason").and_then(Value::as_str)); let mut text = Vec::new(); let mut calls = Vec::new(); let assistant = match &content { @@ -1411,6 +1484,8 @@ fn anthropic_reply(body: &Value) -> Reply { } kept.push(block.clone()); } + // A call cut off at the length limit has incomplete input: not run, not kept. + Some("tool_use") if stop == "max_tokens" => {} Some("tool_use") if calls.len() < 32 => { calls.push(Call { id: block.get("id").and_then(Value::as_str).map_or_else(|| format!("toolu-{i}"), str::to_string), @@ -1438,14 +1513,16 @@ fn anthropic_reply(body: &Value) -> Reply { } _ => json!({"role": "assistant", "content": content.clone()}), }; - Reply { text, calls, assistant } + Reply { text, calls, assistant, stop } } /// Keeps the newest `keep` pictures of the view in the history and swaps every older one for a /// short note, so the model still knows a view was shown. Text is never touched. Pictures come -/// as OpenAI `image_url` parts or Anthropic `image` blocks, depending on the endpoint. -fn drop_old_views(history: &mut [Value], keep: usize) { +/// as OpenAI `image_url` parts or Anthropic `image` blocks, depending on the endpoint. True when +/// a picture was swapped. +fn drop_old_views(history: &mut [Value], keep: usize) -> bool { let mut seen = 0; + let mut dropped = false; for msg in history.iter_mut().rev() { let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; for part in content.iter_mut().rev() { @@ -1455,9 +1532,26 @@ fn drop_old_views(history: &mut [Value], keep: usize) { seen += 1; if seen > keep { *part = json!({"type": "text", "text": DROPPED_VIEW_NOTE}); + dropped = true; } } } + dropped +} + +/// Takes Anthropic thinking blocks out of every earlier reply. Each one is signed against all +/// the conversation before it, so once a dropped view or trimmed message changes that, the API +/// refuses the whole request (#9417); leaving earlier thinking out is allowed. A reply that was +/// only thinking keeps a note, as the API takes no assistant message without content. +fn drop_thinking(history: &mut [Value]) { + for msg in history.iter_mut().filter(|m| m["role"] == "assistant") { + let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; + let before = content.len(); + content.retain(|b| !matches!(b.get("type").and_then(Value::as_str), Some("thinking" | "redacted_thinking"))); + if content.is_empty() && before > 0 { + content.push(json!({"type": "text", "text": DROPPED_THINKING_NOTE})); + } + } } /// MCP `tools/list` as OpenAI function tools (the hidden ones left out). @@ -1546,7 +1640,7 @@ fn anthropic_headers(base_url: &str, key: Option<&str>) -> Result) -> Result, String> { let req = HttpRequest { method: "GET", url: endpoint(base_url, "models"), headers: anthropic_headers(base_url, key)?, body: None, timeout_s: 15 }; let (status, bytes) = http(&req)?; @@ -1554,19 +1648,10 @@ pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> if status != 200 { return Err(http_error(status, &v)); } - Ok(v.get("data") - .and_then(Value::as_array) - .map(|a| { - a.iter() - .take(500) - .filter_map(|m| { - let id = m.get("id").and_then(Value::as_str)?.to_string(); - let name = m.get("display_name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| id.clone()); - Some(ModelInfo { id, name, description: String::new() }) - }) - .collect() - }) - .unwrap_or_default()) + Ok(listed_models(&v, "display_name")? + .into_iter() + .map(|(id, name)| ModelInfo { name: name.unwrap_or_else(|| id.clone()), id, description: String::new() }) + .collect()) } /// Test an Anthropic-compatible endpoint: send the smallest message there is, so the check covers @@ -1639,18 +1724,35 @@ fn tool_title(name: &str, args: &Value) -> String { } } -/// `GET {base_url}/models`: the model ids, in the order the endpoint lists them. -fn model_ids(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result, String> { +/// The ids of a `/models` body and the names the endpoint gives them (when not just the id), in +/// its order. The body is the endpoint's to write: an id that could not be sent back is left out, +/// and a name is cut. A body without a `data` array is no model list (a web page where the +/// endpoint should be, say): an error, so the picker says so and asks again later. +fn listed_models(body: &Value, name_key: &str) -> Result)>, String> { + let Some(entries) = body.get("data").and_then(Value::as_array) else { + return Err(crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string()); + }; + Ok(entries + .iter() + .filter_map(|m| { + let id = m.get("id").and_then(Value::as_str).filter(|id| super::model_id_valid(id))?; + let name = m.get(name_key).and_then(Value::as_str).filter(|name| *name != id).map(|name| name.chars().take(MODEL_NAME_CAP).collect()); + Some((id.to_string(), name)) + }) + .take(MODEL_LIST_CAP) + .collect()) +} + +/// `GET {base_url}/models`: the models, in the order the endpoint lists them. The picker shows the +/// ids, so an endpoint's own name for a model is its description. +fn model_entries(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result, String> { let req = HttpRequest { method: "GET", url: format!("{base_url}/models"), headers, body: None, timeout_s: 15 }; let (status, bytes) = http(&req)?; let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); if status != 200 { return Err(http_error(status, &v)); } - Ok(v.get("data") - .and_then(Value::as_array) - .map(|a| a.iter().take(500).filter_map(|m| m.get("id").and_then(Value::as_str).map(String::from)).collect()) - .unwrap_or_default()) + Ok(listed_models(&v, "name")?.into_iter().map(|(id, name)| ModelInfo { name: id.clone(), id, description: name.unwrap_or_default() }).collect()) } /// The endpoint's models for the picker. @@ -1662,7 +1764,7 @@ pub fn model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result, model: &s } headers.push(("Authorization".to_string(), format!("Bearer {k}"))); } - let ids = model_ids(http, base_url, headers)?; - let ids: Vec<&str> = ids.iter().map(String::as_str).collect(); - let found = model.is_empty() || ids.contains(&model); - Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &ids.len().to_string()), ("model", model)])) + let models = model_entries(http, base_url, headers)?; + let found = model.is_empty() || models.iter().any(|m| m.id == model); + Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &models.len().to_string()), ("model", model)])) } #[cfg(test)] @@ -1731,12 +1832,12 @@ mod tests { #[test] fn only_the_newest_views_stay_in_the_history_and_older_ones_become_a_note() { let mut h = vec![json!({"role": "system", "content": "note"}), view(1), json!({"role": "assistant", "content": "ok"}), view(2)]; - drop_old_views(&mut h, 2); + assert!(!drop_old_views(&mut h, 2)); assert_eq!(pictures(&h).len(), 2, "two views fit, nothing is dropped"); h.push(json!({"role": "user", "content": "plain text"})); h.push(view(3)); - drop_old_views(&mut h, 2); + assert!(drop_old_views(&mut h, 2)); assert_eq!(pictures(&h), vec!["data:image/png;base64,V2", "data:image/png;base64,V3"]); // The oldest view is a note now; the words sent with it, and every other message, stay. assert_eq!(h[1]["content"][0]["text"], "look 1"); @@ -1812,6 +1913,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); @@ -1862,6 +1964,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); @@ -1915,6 +2018,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); @@ -1961,6 +2065,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); @@ -1973,6 +2078,7 @@ mod tests { let Some(Event::Models { current, available }) = events.iter().find(|e| matches!(e, Event::Models { .. })) else { panic!("{events:?}") }; assert_eq!(current, "local"); assert_eq!(available.iter().map(|m| m.id.as_str()).collect::>(), ["local", "big", "small"]); + assert!(events.iter().any(|e| matches!(e, Event::ModelsNote(None))), "{events:?}"); b.set_model("big"); b.prompt(&[PromptPart::Text("hi".into())]); wait_for_seen(&seen); @@ -2044,6 +2150,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), } } @@ -2117,6 +2224,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let mut b = ApiBackend::start(cfg, go_ctx()).unwrap(); b.prompt(&[PromptPart::Text("hi".into())]); @@ -2435,6 +2543,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let mut b = ApiBackend::start(cfg, go_ctx()).unwrap(); b.prompt(&[PromptPart::Text("hi".into())]); @@ -2472,6 +2581,87 @@ mod tests { assert!(tools[0].pointer("/parameters/additionalProperties").is_none(), "{tools:?}"); } + /// An endpoint that refuses the listing still shows the configured model, and says why first. + #[test] + fn a_refused_listing_keeps_the_configured_model_and_says_why() { + let http: HttpFn = Arc::new(|r: &HttpRequest| { + assert_eq!(r.method, "GET"); + Ok((401, json!({"error": {"message": "No auth credentials"}}).to_string().into_bytes())) + }); + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "local".into(), + key: None, + http, + request_timeout_s: 300, + reasoning_effort: String::new(), + }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + let mut events = Vec::new(); + let start = std::time::Instant::now(); + while !events.iter().any(|e| matches!(e, Event::Models { .. })) && start.elapsed() < Duration::from_secs(10) { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + let listing: Vec<&Event> = events.iter().filter(|e| matches!(e, Event::Models { .. } | Event::ModelsNote(_))).collect(); + let [Event::ModelsNote(Some(note)), Event::Models { current, available }] = listing[..] else { panic!("{events:?}") }; + assert!(note.contains("No auth credentials"), "{note}"); + assert_eq!(current, "local"); + assert_eq!(available.iter().map(|m| m.id.as_str()).collect::>(), ["local"]); + b.shutdown(true); + } + + /// OpenRouter's shape: the name is the description, whatever else an entry holds is ignored, an + /// id that could not be sent back is left out, and the list stays within its caps. + #[test] + fn a_listing_keeps_the_names_and_stays_within_its_caps() { + let mut data = vec![ + json!({"id": "openai/gpt-x", "name": "OpenAI: GPT X", "description": "Long text", "supported_parameters": ["tools"]}), + json!({"id": "same", "name": "same", "display_name": "Same One"}), + json!({"id": "long", "name": "n".repeat(MODEL_NAME_CAP + 10), "display_name": "d".repeat(MODEL_NAME_CAP + 10)}), + json!({"id": "x".repeat(super::super::MODEL_ID_CAP + 1)}), + json!({"id": "bell\u{7}"}), + json!({"id": ""}), + json!({"id": 7}), + json!({"name": "no id"}), + ]; + data.extend((0..MODEL_LIST_CAP + 500).map(|i| json!({"id": format!("m{i}")}))); + let body = json!({"data": data}).to_string().into_bytes(); + let http: HttpFn = Arc::new(move |_: &HttpRequest| Ok((200, body.clone()))); + let list = model_list(&http, "https://openrouter.ai/api/v1", None).unwrap(); + assert_eq!(list.len(), MODEL_LIST_CAP); + let [first, same, long, next] = &list[..4] else { panic!("{}", list.len()) }; + assert_eq!((first.id.as_str(), first.name.as_str(), first.description.as_str()), ("openai/gpt-x", "openai/gpt-x", "OpenAI: GPT X")); + assert_eq!((same.id.as_str(), same.description.as_str()), ("same", "")); + assert_eq!(long.description.chars().count(), MODEL_NAME_CAP); + assert_eq!(next.id, "m0"); + let list = anthropic_model_list(&http, "https://openrouter.ai/api/v1", None).unwrap(); + assert_eq!(list.len(), MODEL_LIST_CAP); + let [first, same, long] = &list[..3] else { panic!("{}", list.len()) }; + assert_eq!(first.name, "openai/gpt-x"); + assert_eq!(same.name, "Same One"); + assert_eq!(long.name.chars().count(), MODEL_NAME_CAP); + assert!(test_endpoint(&http, "https://openrouter.ai/api/v1", None, "openai/gpt-x").unwrap().contains(&MODEL_LIST_CAP.to_string())); + } + + /// A 200 that is no model list (a web page where the endpoint should be) is an error, so the + /// picker says why and asks again later; a list with nothing in it is a list. + #[test] + fn an_answer_that_is_no_model_list_is_an_error() { + let expected = crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string(); + let page: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, b"Control UI".to_vec()))); + assert_eq!(model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected); + assert_eq!(anthropic_model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected); + assert_eq!(test_endpoint(&page, "http://localhost:18789/v1", None, "").unwrap_err(), expected); + let object: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"object": "list"}).to_string().into_bytes()))); + assert_eq!(model_list(&object, "http://localhost:18789/v1", None).unwrap_err(), expected); + let empty: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"data": []}).to_string().into_bytes()))); + assert!(model_list(&empty, "http://localhost:18789/v1", None).unwrap().is_empty()); + } + #[test] fn tool_arguments_are_an_object_or_an_error() { assert_eq!(tool_arguments(None), Ok(json!({}))); @@ -2507,6 +2697,7 @@ mod tests { key: None, http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); @@ -2536,6 +2727,7 @@ mod tests { key: Some("k".into()), http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; assert!(ApiBackend::start(cfg, ctx).is_err()); @@ -2544,6 +2736,11 @@ mod tests { /// A worker with one function tool whose endpoint answers each POST with the next scripted /// (status, body); the requests it received are returned too. fn scripted_worker(answers: Vec<(u16, Value)>) -> (Worker, Arc>>) { + scripted_worker_effort(answers, "") + } + + /// [`scripted_worker`] with the endpoint's reasoning effort set (empty: send nothing). + fn scripted_worker_effort(answers: Vec<(u16, Value)>, effort: &str) -> (Worker, Arc>>) { let answers = std::sync::Mutex::new(answers.into_iter().rev().collect::>()); let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); let log = seen.clone(); @@ -2560,6 +2757,7 @@ mod tests { key: Some("sk-secret".into()), http, request_timeout_s: 300, + reasoning_effort: effort.to_string(), }; let (events, _rx) = channel(); let w = Worker { @@ -2611,6 +2809,37 @@ mod tests { assert_eq!(seen.lock().unwrap().len(), 1); } + /// A reasoning effort the user chose goes out as `reasoning_effort` on every request; empty + /// sends nothing, so existing agents are untouched (#10241). + #[test] + fn a_chosen_reasoning_effort_goes_out_on_every_request() { + let ok = json!({"choices": [{"message": {"role": "assistant", "content": "Done."}}]}); + let (w, seen) = scripted_worker_effort(vec![(200, ok.clone()), (200, ok.clone())], "high"); + assert_eq!(w.request().unwrap().assistant, ok["choices"][0]["message"]); + assert_eq!(w.request().unwrap().assistant, ok["choices"][0]["message"]); + let sent = seen.lock().unwrap(); + assert_eq!(sent.len(), 2); + assert_eq!(sent[0]["reasoning_effort"], "high"); + assert_eq!(sent[1]["reasoning_effort"], "high"); + drop(sent); + // Empty effort: nothing is sent at all. + let (w, seen) = scripted_worker(vec![(200, ok)]); + assert!(w.request().is_ok()); + assert!(seen.lock().unwrap()[0].get("reasoning_effort").is_none()); + } + + /// A chosen effort wins over the #3817 `none` retry: the endpoint's refusal of the effort is + /// shown to the user after exactly one request, never silently replaced by `none` (#10241). + #[test] + fn a_chosen_reasoning_effort_wins_over_the_none_retry() { + let (w, seen) = scripted_worker_effort(vec![refusal()], "max"); + let e = w.request().unwrap_err(); + assert!(e.starts_with("HTTP 400") && e.contains("reasoning_effort"), "{e}"); + let sent = seen.lock().unwrap(); + assert_eq!(sent.len(), 1, "the refusal is shown, not replayed with none"); + assert_eq!(sent[0]["reasoning_effort"], "max"); + } + #[test] fn mcp_tools_become_anthropic_tools_without_crash_reports() { let list = json!({"tools": [ @@ -2649,6 +2878,60 @@ mod tests { assert_eq!(capped.assistant["content"].as_array().unwrap().len(), 32); } + /// Why an answer stopped reaches the turn's end: cut off at the length limit, or declined, + /// in either protocol (#9495). A call cut off mid-way is neither run nor kept in the history. + #[test] + fn answers_say_why_they_stopped() { + let thinking = json!({"type": "thinking", "thinking": "", "signature": "s"}); + let call = json!({"type": "tool_use", "id": "t1", "name": "measure", "input": {}}); + for (reason, stop) in [("end_turn", ""), ("tool_use", ""), ("max_tokens", "max_tokens"), ("refusal", "refusal"), ("made_up", "")] { + assert_eq!(anthropic_reply(&json!({"content": [thinking], "stop_reason": reason})).stop, stop, "{reason}"); + } + assert_eq!(anthropic_reply(&json!({"content": [thinking]})).stop, ""); + let cut = anthropic_reply(&json!({"content": [thinking, call], "stop_reason": "max_tokens"})); + assert!(cut.calls.is_empty()); + assert_eq!(cut.assistant["content"], json!([thinking])); + + let openai = |finish: &str, message: Value| openai_reply(&json!({"choices": [{"message": message, "finish_reason": finish}]})); + let calls = json!([{"id": "c1", "type": "function", "function": {"name": "measure", "arguments": "{\"a\""}}]); + assert_eq!(openai("stop", json!({"content": "Hi"})).stop, ""); + assert_eq!(openai("content_filter", json!({"content": null})).stop, "refusal"); + assert_eq!(openai("stop", json!({"content": null, "refusal": "I can't help with that."})).stop, "refusal"); + let cut = openai("length", json!({"content": null, "tool_calls": calls})); + assert_eq!(cut.stop, "max_tokens"); + assert!(cut.calls.is_empty()); + assert!(cut.assistant.get("tool_calls").is_none()); + } + + /// The loop ends the turn with the reason: an answer that is only thinking, cut off at the + /// length limit, ends as `max_tokens`, not as a normal end with nothing said. + #[test] + fn a_cut_off_answer_ends_the_turn_as_max_tokens() { + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } + let body = json!({"content": [{"type": "thinking", "thinking": "", "signature": "s"}], "stop_reason": "max_tokens"}); + Ok((200, body.to_string().into_bytes())) + }); + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::Anthropic, + base_url: "http://localhost:1".into(), + model: "m".into(), + key: Some("sk-secret".into()), + http, + request_timeout_s: 300, + reasoning_effort: String::new(), + }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + b.prompt(&[PromptPart::Text("look closer".into())]); + let events = wait_for_turn(&mut b); + b.shutdown(true); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "max_tokens"), "{events:?}"); + } + #[test] fn anthropic_urls_take_the_base_with_or_without_v1() { assert_eq!(endpoint("https://api.anthropic.com", "messages"), "https://api.anthropic.com/v1/messages"); @@ -2689,6 +2972,7 @@ mod tests { key: Some("sk-secret".into()), http, request_timeout_s: 300, + reasoning_effort: String::new(), }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); @@ -2708,6 +2992,67 @@ mod tests { b.shutdown(true); } + /// Thinking blocks are signed against the conversation before them: once an older view is + /// dropped, the earlier ones go too, or Claude refuses the request (#9417). Until then, and + /// for replies after the drop, they are sent back as they came. + #[test] + fn a_dropped_view_takes_earlier_thinking_with_it() { + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } + let n = { + let mut l = log.lock().unwrap(); + l.push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + l.len() + }; + let content = if n == 2 { + json!([{"type": "redacted_thinking", "data": "r2"}]) + } else { + json!([{"type": "thinking", "thinking": "", "signature": format!("s{n}")}, {"type": "text", "text": format!("Seen {n}.")}]) + }; + Ok((200, json!({"content": content, "stop_reason": "end_turn"}).to_string().into_bytes())) + }); + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::Anthropic, + base_url: "http://localhost:1".into(), + model: "m".into(), + key: Some("sk-secret".into()), + http, + request_timeout_s: 300, + reasoning_effort: String::new(), + }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + for n in 1..=3 { + b.prompt(&[PromptPart::Text(format!("look {n}")), PromptPart::Image { mime: "image/png".into(), base64: format!("V{n}") }]); + wait_for_turn(&mut b); + } + b.prompt(&[PromptPart::Text("and now?".into())]); + wait_for_turn(&mut b); + b.shutdown(true); + let sent = seen.lock().unwrap(); + assert_eq!(sent.len(), 4); + let replies = |i: usize| -> Vec { + sent[i]["messages"].as_array().unwrap().iter().filter(|m| m["role"] == "assistant").map(|m| m["content"].clone()).collect() + }; + // Two views fit: the reply goes back untouched, signature and all. + assert_eq!(replies(1)[0][0]["signature"], "s1"); + // The third view drops the first: no earlier thinking is left, a thinking-only reply + // keeps a note, and the words stay. + let third = replies(2); + assert_eq!(sent[2]["messages"][0]["content"][1]["text"], DROPPED_VIEW_NOTE); + assert_eq!(third[0], json!([{"type": "text", "text": "Seen 1."}])); + assert_eq!(third[1], json!([{"type": "text", "text": DROPPED_THINKING_NOTE}])); + // Nothing is dropped for the next message, so the reply after the drop keeps its thinking. + let fourth = replies(3); + assert_eq!(fourth[..2], third[..]); + assert_eq!(fourth[2][0]["signature"], "s3"); + } + #[test] fn the_anthropic_test_sends_one_small_message_and_checks_the_key_rule() { let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index 98f5ad246..51d88f0e4 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -9,6 +9,7 @@ use serde_json::Value; pub use super::acp::{AuthMethod, PermissionOption, ToolStatus}; +pub use super::acp::{ConfigChoice, ConfigOption}; /// A connection test keeps authentication failures distinct from transport or protocol errors. #[derive(Clone, Debug, PartialEq, Eq)] @@ -53,29 +54,70 @@ pub enum Event { /// Whether SolidCraft tools were offered by the backend. ToolsAvailable(bool), /// Ready for a message. `agent`: its name and version; `images`: it takes pictures. - Ready { agent: String, images: bool }, + Ready { + agent: String, + images: bool, + }, /// Text it streams (`thought`: its reasoning, shown dimmed). - Text { thought: bool, text: String }, + Text { + thought: bool, + text: String, + }, /// A new tool call, or news about one (`input`: its arguments, when the agent says). - Tool { id: String, title: Option, kind: Option, status: Option, input: Option, output: Option }, + Tool { + id: String, + title: Option, + kind: Option, + status: Option, + input: Option, + output: Option, + }, /// Its plan, replaced whole: each entry with its status. Plan(Vec<(String, String)>), /// It asks before running something of its own; answered with [`ChatBackend::answer_permission`]. - Permission { key: u64, title: String, options: Vec }, + Permission { + key: u64, + title: String, + /// The tool call's kind, as the agent gives it. + kind: Option, + options: Vec, + }, /// It needs the user to sign in; `methods` are its own ways to do so. - AuthRequired { methods: Vec }, + AuthRequired { + methods: Vec, + }, /// What it says about its login. AuthStatus(String), /// Its own modes (an ACP agent's `modes`: ask, accept edits, plan, …) and the current one. - Modes { current: String, available: Vec<(String, String)> }, + Modes { + current: String, + available: Vec<(String, String)>, + }, /// Its models (empty `available`: only the current one changed). - Models { current: String, available: Vec }, + Models { + current: String, + available: Vec, + }, + /// Why an endpoint's models could not be listed (`None`: they could). It comes before the + /// [`Event::Models`] of that listing, which then holds only the configured model. + ModelsNote(Option), + /// The agent refused the model it was just sent, and says why. + ModelRejected(String), + ConfigOptions(Vec), + ConfigOptionFinished { + id: String, + result: Result, String>, + }, /// The message is answered (`reason`: why it stopped, empty for a normal end). - TurnEnded { reason: String }, + TurnEnded { + reason: String, + }, /// Something failed; the backend is still running unless [`Event::Exited`] follows. Error(String), /// It ended; its last error output. - Exited { tail: Vec }, + Exited { + tail: Vec, + }, } /// What a backend gets to start. @@ -112,6 +154,9 @@ pub trait ChatBackend { fn set_mode(&mut self, _mode: &str) {} /// An endpoint's new request timeout, in seconds, from the next request on. fn set_request_timeout(&mut self, _secs: u64) {} + /// An endpoint's new reasoning effort (empty: send nothing), from the next request on. + fn set_reasoning_effort(&mut self, _effort: &str) {} + fn set_config_option(&mut self, _id: &str, _value: &str) {} /// Its process, for status and tests. fn pid(&self) -> Option { None diff --git a/crates/ui-egui/src/agent_chat/context.rs b/crates/ui-egui/src/agent_chat/context.rs index d93c5a55f..256a5a32b 100644 --- a/crates/ui-egui/src/agent_chat/context.rs +++ b/crates/ui-egui/src/agent_chat/context.rs @@ -7,7 +7,7 @@ use std::collections::HashMap; use serde_json::{Value, json}; -use solidcraft_engine::geom::Vec3; +use solidcore_record::Vec3; use solidcraft_engine::{Sel, Session}; /// The most items one message carries; the rest are counted, not dropped silently. diff --git a/crates/ui-egui/src/agent_chat/discover.rs b/crates/ui-egui/src/agent_chat/discover.rs index cf9490f1e..cec01600e 100644 --- a/crates/ui-egui/src/agent_chat/discover.rs +++ b/crates/ui-egui/src/agent_chat/discover.rs @@ -3,6 +3,7 @@ //! or a session: each agent found is asked for `--version` (with a time limit), and whether it //! looks logged in comes only from whether its own credentials file exists. +use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; @@ -186,6 +187,11 @@ pub struct Found { pub argv: Vec, pub version: Option, pub login: Login, + /// Why its program doesn't start (#9034): asked for `--version`, it failed without printing + /// one, as the `opencode.exe` of an npm install whose setup script didn't run does on Windows. + pub problem: Option, + /// Its one-line install hint, to reinstall it with. + pub install: &'static str, } #[derive(Clone, Debug, Default)] @@ -200,13 +206,20 @@ fn home() -> Option { std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).filter(|p| p.is_absolute()) } -/// PATH, then the usual places npm, Homebrew, nvm, Volta, bun, pipx and Grok put commands. +/// PATH, then the usual places npm, Homebrew, nvm, Volta, bun, pipx and Grok put commands, and on +/// Windows Node's own install folders: a launcher can start SolidCraft with a PATH that lacks +/// them, and an npm agent's `.cmd` shim then can't find `node` (#9297). pub fn search_dirs() -> Vec { - let mut dirs: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); - if let Some(prefix) = std::env::var_os("NPM_CONFIG_PREFIX").map(PathBuf::from) { - dirs.push(if cfg!(windows) { prefix.clone() } else { prefix.join("bin") }); + search_dirs_in(&|name| std::env::var_os(name), cfg!(windows)) +} + +/// [`search_dirs`] in the environment `var` reads, on Windows or not. +fn search_dirs_in(var: &dyn Fn(&str) -> Option, windows: bool) -> Vec { + let mut dirs: Vec = var("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); + if let Some(prefix) = var("NPM_CONFIG_PREFIX").map(PathBuf::from) { + dirs.push(if windows { prefix.clone() } else { prefix.join("bin") }); } - if let Some(h) = home() { + if let Some(h) = var(if windows { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).filter(|p| p.is_absolute()) { for d in [".local/bin", ".npm-global/bin", ".npm-packages/bin", ".volta/bin", ".bun/bin", ".cargo/bin", ".grok/bin", "bin"] { dirs.push(h.join(d)); } @@ -217,10 +230,15 @@ pub fn search_dirs() -> Vec { dirs.extend(v.into_iter().rev()); } } - if cfg!(windows) { - if let Some(a) = std::env::var_os("APPDATA") { + if windows { + if let Some(a) = var("APPDATA") { dirs.push(PathBuf::from(a).join("npm")); } + // Node's installers (64-bit and 32-bit), and nvm-windows' link to the version in use. + for program_files in ["ProgramFiles", "ProgramFiles(x86)"] { + dirs.extend(var(program_files).map(|d| PathBuf::from(d).join("nodejs"))); + } + dirs.extend(var("NVM_SYMLINK").map(PathBuf::from)); } else { for d in ["/opt/homebrew/bin", "/usr/local/bin", "/home/linuxbrew/.linuxbrew/bin", "/usr/bin"] { dirs.push(PathBuf::from(d)); @@ -257,7 +275,9 @@ pub fn runnable_sibling(program: &Path) -> Option { /// Start probes and sessions with the same PATH used for discovery. Desktop launchers often /// omit Node's install folder even when we found an adapter with a `#!/usr/bin/env node` shebang. -/// Only the child's environment changes; inherited absolute PATH entries keep precedence. +/// Only the child's environment changes. An explicitly selected Node also takes precedence for +/// its descendants; otherwise inherited absolute PATH entries keep precedence. No probes here: +/// starting a session calls this on the UI thread. pub(super) fn command_for(program: &Path) -> Command { // Older saved Windows commands may name npm's bare Unix script rather than its .cmd shim. let shim = if cfg!(windows) { runnable_sibling(program) } else { None }; @@ -269,38 +289,141 @@ pub(super) fn command_for(program: &Path) -> Command { } else { Command::new(program) }; - if let Ok(path) = std::env::join_paths(search_dirs()) { + let mut dirs = search_dirs(); + if program.is_absolute() + && program.file_name().is_some_and(|n| n == "node" || n == "node.exe") + && let Some(parent) = program.parent() + { + dirs.retain(|d| d != parent); + dirs.insert(0, parent.to_path_buf()); + } + if let Ok(path) = std::env::join_paths(dirs) { cmd.env("PATH", path); } cmd } -/// `program --version`'s first line, or `None` after `limit` (the probe is then stopped). -fn version(program: &Path, limit: Duration) -> Option { - let mut cmd = command_for(program); +/// What `program --version` showed. +#[derive(Debug, Default, PartialEq)] +struct Probe { + /// Its version number, from the first line it printed. + version: Option, + /// Why it can't start: the system refused to start it, or it failed and printed nothing but + /// an error. A probe that runs out of time says nothing either way (a slow machine). + problem: Option, + /// A failed JSON import-attributes parse on a Node version that cannot support it. + old_node: Option, +} + +/// How long an agent is given to answer `--version`. +const PROBE_LIMIT: Duration = Duration::from_secs(3); + +/// The longest reason kept from a failed probe. +const PROBLEM_CHARS: usize = 300; + +/// Ask `program --version`; it is stopped after `limit`. +fn probe(program: &Path, limit: Duration) -> Probe { + probe_command(program, command_for(program), limit) +} + +fn probe_command(program: &Path, mut cmd: Command, limit: Duration) -> Probe { #[cfg(windows)] { use std::os::windows::process::CommandExt; // CREATE_NO_WINDOW: probing a console agent doesn't flash a terminal window. cmd.creation_flags(0x0800_0000); } - let mut child = cmd.arg("--version").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; + let mut child = match cmd.arg("--version").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() { + Ok(child) => child, + // Windows: "not a valid Win32 application" (193), "not compatible with the version of + // Windows you're running" (216); elsewhere: not allowed to run it, an unknown format. + // Windows leaves the program's place in its message as `%1`. + Err(e) => return Probe { problem: Some(cut(&e.to_string().replace("%1", &program.display().to_string()))), ..Probe::default() }, + }; let start = Instant::now(); - loop { + let status = loop { match child.try_wait() { - Ok(Some(_)) => break, + Ok(Some(status)) => break status, Ok(None) if start.elapsed() < limit => std::thread::sleep(Duration::from_millis(20)), _ => { let _ = child.kill(); let _ = child.wait(); - return None; + return Probe::default(); } } + }; + let out = read_capped(child.stdout.take()); + if let Some(line) = out.lines().map(str::trim).find(|l| !l.is_empty()) { + return Probe { version: Some(version_of(line)), ..Probe::default() }; } - let mut out = String::new(); - std::io::Read::read_to_string(&mut child.stdout.take()?, &mut out).ok()?; - let line = out.lines().map(str::trim).find(|l| !l.is_empty())?; - Some(version_of(line)) + if status.success() { + return Probe::default(); + } + // Through a `.cmd` shim, Windows' own refusal arrives on stderr with a failing exit code. + let err = read_capped(child.stderr.take()); + let reason = err.lines().map(str::trim).find(|l| !l.is_empty()).map(str::to_string).unwrap_or_else(|| status.to_string()); + let old_node = err + .contains("SyntaxError: Unexpected token 'with'") + .then(|| { + err.lines().find_map(|line| { + let version = line.trim().strip_prefix("Node.js ")?; + (node_import_attributes(version) == Some(false)).then(|| version.to_string()) + }) + }) + .flatten(); + Probe { version: None, problem: Some(cut(&reason)), old_node } +} + +/// Node added import attributes in 18.20, 20.10 and 21.0. Reject unrecognised versions. +fn node_import_attributes(version: &str) -> Option { + let mut parts = version.strip_prefix('v')?.split('.'); + let major = parts.next()?.parse::().ok()?; + let minor = parts.next()?.parse::().ok()?; + let _patch = parts.next()?.parse::().ok()?; + if parts.next().is_some() { + return None; + } + Some(major >= 21 || (major == 20 && minor >= 10) || (major == 18 && minor >= 20)) +} + +/// Only replace an unambiguous env-node shebang, never a shell shim or a pinned interpreter. +fn uses_env_node(program: &Path) -> bool { + use std::io::Read; + let Ok(file) = std::fs::File::open(program) else { return false }; + let mut header = String::new(); + if file.take(256).read_to_string(&mut header).is_err() { + return false; + } + let words: Vec<_> = header.lines().next().unwrap_or_default().split_whitespace().collect(); + matches!(words.as_slice(), ["#!/usr/bin/env" | "#!/bin/env", "node"] | ["#!/usr/bin/env" | "#!/bin/env", "-S", "node"]) +} + +/// These checks run only after the adapter fails on an old Node, on the discovery worker. +/// All candidate probes share one time budget, so many installed versions cannot stall Refresh. +fn compatible_node(dirs: &[PathBuf], limit: Duration) -> Option { + let start = Instant::now(); + for dir in dirs.iter().take(64) { + let Some(node) = find_in("node", std::slice::from_ref(dir)) else { continue }; + let remaining = limit.checked_sub(start.elapsed()).filter(|d| !d.is_zero())?; + if probe(&node, remaining).version.as_deref().and_then(node_import_attributes) == Some(true) { + return Some(node); + } + } + None +} + +/// What a finished probe wrote on a pipe, up to 64 KiB. +fn read_capped(pipe: Option) -> String { + let mut bytes = Vec::new(); + if let Some(p) = pipe { + let _ = std::io::Read::read_to_end(&mut p.take(64 * 1024), &mut bytes); + } + String::from_utf8_lossy(&bytes).into_owned() +} + +/// `text`, cut short. +fn cut(text: &str) -> String { + text.chars().take(PROBLEM_CHARS).collect() } /// The version number in a `--version` line (`codex-cli 0.162.1`, `2.1.295 (Claude Code)`, @@ -329,10 +452,10 @@ fn login_of(k: &Known, home: Option<&Path>) -> Login { /// Look for every known agent. Blocking (each probe has a time limit): run it off the UI thread. pub fn detect() -> Detection { - detect_in(&search_dirs(), home().as_deref()) + detect_in(&search_dirs(), home().as_deref(), PROBE_LIMIT) } -fn detect_in(dirs: &[PathBuf], home: Option<&Path>) -> Detection { +fn detect_in(dirs: &[PathBuf], home: Option<&Path>, limit: Duration) -> Detection { let t0 = Instant::now(); let mut d = Detection::default(); for k in KNOWN { @@ -345,8 +468,21 @@ fn detect_in(dirs: &[PathBuf], home: Option<&Path>) -> Detection { let login = login_of(k, home); let mut argv = vec![path.to_string_lossy().into_owned()]; argv.extend(k.args.iter().map(|a| a.to_string())); - let version = if k.reports_version { version(&path, Duration::from_secs(3)) } else { None }; - d.found.push(Found { id: k.id, name: k.name, version, argv, login }); + let mut result = if k.reports_version { probe(&path, limit) } else { Probe::default() }; + if let Some(version) = result.old_node.as_deref() { + result.problem = Some(crate::i18n::format("ui.agent_chat_node_too_old", &[("version", version)])); + if uses_env_node(&path) + && let Some(node) = compatible_node(dirs, limit) + { + let mut cmd = command_for(&node); + cmd.arg(&path); + result = probe_command(&node, cmd, limit); + // Keep this interpreter for the live session as well as the version check. + argv.insert(0, node.to_string_lossy().into_owned()); + } + } + let Probe { version, problem, .. } = result; + d.found.push(Found { id: k.id, name: k.name, version, argv, login, problem, install: k.install }); } d.took_ms = u64::try_from(t0.elapsed().as_millis()).unwrap_or(u64::MAX); d @@ -407,6 +543,111 @@ pub(super) fn tools_capability(value: &serde_json::Value) -> Option { mod tests { use super::*; + /// A desktop PATH can name an old Node before the runtime installed with an npm adapter. + /// Both the version probe and the live session must use the recovered interpreter. + #[test] + #[cfg(unix)] + fn a_node_adapter_recovers_from_an_incompatible_desktop_runtime() { + use super::super::process::{AgentProcess, FromAgent}; + use std::os::unix::fs::PermissionsExt; + + const CHILD: &str = "SOLIDCRAFT_NODE_COMPAT_TEST"; + const BROKEN_NODE: &str = "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo v18.19.1; else echo \"SyntaxError: Unexpected token 'with'\" >&2; echo 'Node.js v18.19.1' >&2; exit 1; fi\n"; + if let Some(root) = std::env::var_os(CHILD) { + let root = PathBuf::from(root); + let old = root.join("old"); + let newer = root.join("modern/bin"); + let dirs = [old.clone(), newer.clone()]; + let find = || detect_in(&dirs, None, Duration::from_secs(20)).found.into_iter().find(|f| f.id == "claude").unwrap(); + let inherited_path = std::env::var_os("PATH"); + let found = find(); + assert_eq!(found.version.as_deref(), Some("1.2.3"), "{found:?}"); + assert_eq!(found.problem, None); + assert_eq!(found.argv.first(), Some(&newer.join("node").to_string_lossy().into_owned())); + assert_eq!(found.argv.get(1), Some(&old.join("claude-agent-acp").to_string_lossy().into_owned())); + assert_eq!(std::env::var_os("PATH"), inherited_path, "only the child's PATH may change"); + + let mut process = AgentProcess::spawn(&found.argv, &root, &[], || {}).unwrap(); + let message = serde_json::json!({"id": 1, "method": "initialize"}); + process.send(&message); + let reply = process.from_agent.recv_timeout(Duration::from_secs(20)).unwrap(); + process.shutdown(true); + match reply { + FromAgent::Line(line) => assert_eq!(serde_json::from_str::(&line).unwrap(), message), + FromAgent::Exited(tail) => panic!("the recovered adapter did not start: {tail:?}"), + } + + // An older runtime that already runs the adapter is left alone. + std::fs::write(old.join("node"), "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo v18.19.1; else echo adapter 9.9.9; fi\n").unwrap(); + let working = find(); + assert_eq!(working.version.as_deref(), Some("9.9.9")); + assert_eq!(working.argv.first(), Some(&old.join("claude-agent-acp").to_string_lossy().into_owned())); + + // Without a compatible runtime the reason must name Node and the remedy. + std::fs::write(old.join("node"), BROKEN_NODE).unwrap(); + std::fs::remove_file(newer.join("node")).unwrap(); + let unavailable = find(); + assert_eq!(unavailable.version, None); + let reason = unavailable.problem.unwrap(); + assert!(reason.contains("18.19.1") && reason.contains("20.10") && reason.contains("Refresh"), "{reason}"); + return; + } + + let root = std::env::temp_dir().join(format!("sc agent node compat-{}", std::process::id())); + let old = root.join("old"); + let newer = root.join("modern/bin"); + std::fs::create_dir_all(&old).unwrap(); + std::fs::create_dir_all(&newer).unwrap(); + for (path, script) in [ + (old.join("claude-agent-acp"), "#!/usr/bin/env node\n"), + (old.join("node"), BROKEN_NODE), + ( + newer.join("node"), + "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo v22.0.0; elif [ \"$2\" = \"--version\" ]; then echo adapter 1.2.3; elif [ \"$(node --version)\" = v22.0.0 ]; then /bin/cat; else exit 1; fi\n", + ), + ] { + std::fs::write(&path, script).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let output = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "agent_chat::discover::tests::a_node_adapter_recovers_from_an_incompatible_desktop_runtime", "--nocapture"]) + .env(CHILD, &root) + .env("PATH", std::env::join_paths([old, PathBuf::from("/usr/bin"), PathBuf::from("/bin")]).unwrap()) + .env("NPM_CONFIG_PREFIX", root.join("modern")) + .output() + .unwrap(); + let _ = std::fs::remove_dir_all(root); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + } + + #[test] + fn node_import_attributes_require_a_supported_release() { + for version in ["v18.20.0", "v18.20.8", "v20.10.0", "v20.19.0", "v21.0.0", "v22.0.0"] { + assert_eq!(node_import_attributes(version), Some(true), "{version}"); + } + for version in ["v16.20.2", "v18.19.1", "v19.9.0", "v20.9.0"] { + assert_eq!(node_import_attributes(version), Some(false), "{version}"); + } + for version in ["", "node", "v20", "v20.10", "v22.0.0-rc.1", "v22.0.0.1", "v18446744073709551616.0.0"] { + assert_eq!(node_import_attributes(version), None, "{version}"); + } + } + + #[test] + fn node_recovery_does_not_rewrite_shell_shims_or_pinned_interpreters() { + let path = std::env::temp_dir().join(format!("sc-agent-shebang-{}", std::process::id())); + for header in ["#!/usr/bin/env node\n", "#!/bin/env node\r\n", "#!/usr/bin/env -S node\n"] { + std::fs::write(&path, header).unwrap(); + assert!(uses_env_node(&path), "{header}"); + } + for header in ["#!/bin/sh\n", "#!/opt/node/bin/node\n", "#!/usr/bin/env -S node --experimental-modules\n", "@echo off\r\n", "node\n"] { + std::fs::write(&path, header).unwrap(); + assert!(!uses_env_node(&path), "{header}"); + } + std::fs::remove_file(&path).unwrap(); + assert!(!uses_env_node(&path)); + } + #[test] fn ollama_capabilities_distinguish_tools_chat_and_unknown() { use serde_json::json; @@ -531,7 +772,7 @@ mod tests { }; let ids = |d: &Detection| (d.found.iter().map(|f| f.id).collect::>(), d.missing.iter().map(|m| m.id).collect::>()); - let none = detect_in(std::slice::from_ref(&root), None); + let none = detect_in(std::slice::from_ref(&root), None, PROBE_LIMIT); let (found, missing) = ids(&none); assert!(found.is_empty()); assert!(missing.contains(&"antigravity") && !missing.contains(&"gemini"), "{missing:?}"); @@ -541,7 +782,7 @@ mod tests { run("gemini", "echo gemini 0.64.0"); // A server that would take seconds to answer `--version`, which Antigravity is never asked. run("agy_acp_server.par", "sleep 30"); - let both = detect_in(std::slice::from_ref(&root), None); + let both = detect_in(std::slice::from_ref(&root), None, PROBE_LIMIT); let (found, missing) = ids(&both); assert_eq!(found, ["antigravity", "gemini"]); assert!(!missing.contains(&"antigravity") && !missing.contains(&"gemini"), "{missing:?}"); @@ -560,6 +801,109 @@ mod tests { assert_eq!(KNOWN.first().map(|k| k.id), Some("claude"), "the Claude Code adapter is the default"); } + /// #9034: npm installed OpenCode without running its setup script, so the `opencode.exe` its + /// `.cmd` shim starts is one Windows refuses. It is still found (its shim is there), with + /// the system's reason and the command to install it again, while an agent that answers + /// `--version`, or ends without a word but successfully, has no problem. + #[test] + fn an_agent_that_does_not_start_is_found_with_the_reason() { + let root = std::env::temp_dir().join(format!("sc-agent-broken-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + #[cfg(windows)] + { + // npm's layout: the shim in the prefix, the program under node_modules. + let bin = root.join("node_modules").join("opencode-ai").join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join("opencode.exe"), "not a program for this computer").unwrap(); + std::fs::write(root.join("opencode.cmd"), "@ECHO off\r\n\"%~dp0\\node_modules\\opencode-ai\\bin\\opencode.exe\" %*\r\n").unwrap(); + // Started directly, the system itself refuses it. + std::fs::write(root.join("copilot.exe"), "not a program either").unwrap(); + std::fs::write(root.join("grok.cmd"), "@echo off\r\nexit /b 3\r\n").unwrap(); + std::fs::write(root.join("qwen.cmd"), "@echo off\r\necho 0.1.2\r\n").unwrap(); + std::fs::write(root.join("goose.cmd"), "@echo off\r\n").unwrap(); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let run = |name: &str, body: &str| { + let path = root.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + }; + run("opencode", "echo 'cannot execute binary file: Exec format error' >&2; exit 126"); + // Not allowed to run: the system refuses it. + std::fs::write(root.join("copilot"), "not a program").unwrap(); + std::fs::set_permissions(root.join("copilot"), std::fs::Permissions::from_mode(0o644)).unwrap(); + run("grok", "exit 3"); + run("qwen", "echo 0.1.2"); + run("goose", "true"); + } + // A generous limit: on a loaded machine `cmd` alone can take longer than three seconds to + // start, and a probe that runs out of time reports nothing. + let d = detect_in(std::slice::from_ref(&root), None, Duration::from_secs(60)); + let found = |id: &str| d.found.iter().find(|f| f.id == id).unwrap_or_else(|| panic!("{id} not found: {:?}", d.found)); + + let opencode = found("opencode"); + assert_eq!(opencode.version, None); + assert!(opencode.problem.as_deref().is_some_and(|p| !p.trim().is_empty()), "{opencode:?}"); + assert_eq!(opencode.install, "npm install -g opencode-ai"); + assert_eq!(opencode.argv.get(1).map(String::as_str), Some("acp"), "still offered with its ACP arguments"); + let copilot = found("copilot"); + assert!(copilot.problem.as_deref().is_some_and(|p| !p.trim().is_empty()), "{copilot:?}"); + #[cfg(windows)] + assert!( + copilot.problem.as_deref().is_some_and(|p| (p.contains("216") || p.contains("193")) && p.contains("copilot.exe") && !p.contains("%1")), + "the system's reason, naming the program: {copilot:?}" + ); + // Silent but failing: the exit status is the reason. + let grok = found("grok"); + assert!(grok.problem.as_deref().is_some_and(|p| p.contains('3')), "{grok:?}"); + + let qwen = found("qwen"); + assert_eq!((qwen.version.as_deref(), qwen.problem.as_deref()), (Some("0.1.2"), None)); + let goose = found("goose"); + assert_eq!((goose.version.as_deref(), goose.problem.as_deref()), (None, None)); + assert!(d.found.iter().all(|f| f.problem.as_ref().is_none_or(|p| p.chars().count() <= PROBLEM_CHARS))); + let _ = std::fs::remove_dir_all(root); + } + + /// A launcher can start SolidCraft with a PATH that lacks Node (#9297). On Windows, Node's + /// install folders are searched after it, so `node` is found, and an agent started with these + /// folders as its PATH (`command_for`) finds it too. + #[test] + fn on_windows_nodes_install_folders_are_searched() { + let root = std::env::temp_dir().join(format!("sc-agent-node-{}", std::process::id())); + let system = root.join("Windows"); + let program_files = root.join("Program Files"); + let x86 = root.join("Program Files (x86)"); + let nvm = root.join("nvm4w").join("nodejs"); + let env = |name: &str| -> Option { + match name { + "PATH" => Some(system.clone().into()), + "ProgramFiles" => Some(program_files.clone().into()), + "ProgramFiles(x86)" => Some(x86.clone().into()), + "NVM_SYMLINK" => Some(nvm.clone().into()), + _ => None, + } + }; + let dirs = search_dirs_in(&env, true); + assert_eq!(dirs.first(), Some(&system), "the PATH SolidCraft was given comes first"); + for node in [program_files.join("nodejs"), x86.join("nodejs"), nvm.clone()] { + assert!(dirs.contains(&node), "{} in {dirs:?}", node.display()); + } + std::fs::create_dir_all(program_files.join("nodejs")).unwrap(); + for name in ["node.exe", "node"] { + std::fs::write(program_files.join("nodejs").join(name), "").unwrap(); + } + assert_eq!(find_in("node", std::slice::from_ref(&system)), None, "not on the PATH the launcher gave"); + assert!(find_in("node", &dirs).is_some_and(|p| p.starts_with(program_files.join("nodejs"))), "{dirs:?}"); + // Nothing is made up where the variables are missing, and elsewhere they mean nothing. + assert_eq!(search_dirs_in(&|name| (name == "PATH").then(|| system.clone().into()), true), std::slice::from_ref(&system)); + assert!(!search_dirs_in(&env, false).iter().any(|d| d.ends_with("nodejs"))); + let _ = std::fs::remove_dir_all(root); + } + /// Finder's PATH lacks user-installed runtimes. Discovery, the version probe and a live /// agent must all work with an env shebang whose interpreter is in ~/.local/bin. #[test] @@ -574,7 +918,7 @@ mod tests { let agent = find_in("solidcraft-test-agent", &search_dirs()).unwrap(); // Generous limits: both answer at once, but a whole test run on a loaded machine // can keep `env`, the shell and the script from starting within 3 s. - assert_eq!(version(&agent, Duration::from_secs(20)).as_deref(), Some("1.2.3")); + assert_eq!(probe(&agent, Duration::from_secs(20)).version.as_deref(), Some("1.2.3")); let mut p = AgentProcess::spawn(&[agent.to_string_lossy().into_owned()], &root, &[], || {}).unwrap(); let message = serde_json::json!({"id": 1, "method": "initialize"}); p.send(&message); diff --git a/crates/ui-egui/src/agent_chat/markdown_view.rs b/crates/ui-egui/src/agent_chat/markdown_view.rs index 4b8dfed14..a2174ea83 100644 --- a/crates/ui-egui/src/agent_chat/markdown_view.rs +++ b/crates/ui-egui/src/agent_chat/markdown_view.rs @@ -6,6 +6,7 @@ //! changes. use crate::fonts::RichTextExt as _; +use crate::ui_kit::BackingTooltipExt as _; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -59,10 +60,33 @@ fn host(url: &str) -> &str { rest.split(['/', '?', '#']).next().unwrap_or(rest) } +/// A selectable label of the conversation. egui leaves a label scrolled out of view out of the +/// text selection, so a selection whose start had scrolled away was dropped, and Copy missed the +/// hidden text (#11527). Out of view this one still takes part: it keeps its end of the selection +/// and gives its text to Copy, clipped to nothing so it is not drawn and never moves the selection. +pub(super) fn selectable(ui: &mut egui::Ui, label: egui::Label) -> egui::Response { + use egui::text_selection::LabelSelectionState; + let (pos, galley, response) = label.selectable(true).layout_in_ui(ui); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), galley.text())); + // As `egui::Label` draws a label that is not a button. + let colour = ui.visuals().text_color(); + if ui.is_rect_visible(response.rect) { + let underline = if response.has_focus() || response.highlighted() { Stroke::new(1.0, colour) } else { Stroke::NONE }; + LabelSelectionState::label_text_selection(ui, &response, pos, galley, colour, underline); + } else if ui.ctx().plugin::().lock().has_selection() { + let clip = ui.clip_rect(); + ui.set_clip_rect(egui::Rect::NOTHING); + LabelSelectionState::label_text_selection(ui, &response, pos, galley, colour, Stroke::NONE); + ui.set_clip_rect(clip); + } + response +} + /// A paragraph's text, then its links as buttons (a laid-out text cannot be clicked in parts). fn spans(ui: &mut egui::Ui, spans: &[Span], size: f32, color: Color32) { let t = Tokens::get(); - ui.add(egui::Label::new(job(ui, spans, size, color)).selectable(true).wrap()); + let text = job(ui, spans, size, color); + selectable(ui, egui::Label::new(text).wrap()); let links: Vec<(&str, &str)> = spans.iter().filter_map(|s| if let Span::Link { label, url } = s { Some((label.as_str(), url.as_str())) } else { None }).collect(); if !links.is_empty() { @@ -70,7 +94,7 @@ fn spans(ui: &mut egui::Ui, spans: &[Span], size: f32, color: Color32) { for (label, url) in links { // The text above already shows the label; the button says where it goes. let to = format!("↗ {}", host(url)); - ui.hyperlink_to(RichText::new(to).size(size - (t.font_button - t.font_body)), url).on_hover_text(format!("{label}: {url}")); + ui.hyperlink_to(RichText::new(to).size(size - (t.font_button - t.font_body)), url).backing_on_hover_text(format!("{label}: {url}")); } }); } @@ -91,20 +115,23 @@ pub fn show(ui: &mut egui::Ui, slot: usize, src: &str) { _ => t.font_heading, }; ui.add_space(4.0); - ui.add(egui::Label::new(RichText::new(markdown::plain(s)).size(size).semibold().color(t.text)).selectable(true).wrap()); + selectable(ui, egui::Label::new(RichText::new(markdown::plain(s)).size(size).semibold().color(t.text)).wrap()); } Block::Code { text, .. } => { - egui::Frame::NONE.fill(t.field).corner_radius(t.radius_sm).inner_margin(Margin::same(6)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.add( - egui::Label::new(RichText::new(text).monospace().size(size - (t.font_button - t.font_body)).color(t.text)) - .selectable(true) - .wrap(), - ); - if crate::ui_kit::button(ui, tr("ui.agent_chat_copy"), crate::ui_kit::Button::Small).clicked() { - ui.ctx().copy_text(text.clone()); - } - }); + crate::ui_kit::Container::show_backing( + ui, + egui::Frame::NONE.fill(t.field).corner_radius(t.radius_sm).inner_margin(Margin::same(6)), + |ui| { + ui.set_width(ui.available_width()); + selectable( + ui, + egui::Label::new(RichText::new(text).monospace().size(size - (t.font_button - t.font_body)).color(t.text)).wrap(), + ); + if crate::ui_kit::button(ui, tr("ui.agent_chat_copy"), crate::ui_kit::Button::Small).clicked() { + ui.ctx().copy_text(text.clone()); + } + }, + ); } Block::List { ordered, start, items } => { for (i, item) in items.iter().enumerate() { @@ -124,7 +151,7 @@ pub fn show(ui: &mut egui::Ui, slot: usize, src: &str) { } Block::Pre(text) => { egui::ScrollArea::horizontal().id_salt(("agent_chat_pre", slot, text.len())).show(ui, |ui| { - ui.add(egui::Label::new(RichText::new(text).monospace().size(t.font_small).color(t.text)).selectable(true)); + selectable(ui, egui::Label::new(RichText::new(text).monospace().size(t.font_small).color(t.text))); }); } Block::Rule => { diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 6733f937e..7503fa6b7 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -49,8 +49,8 @@ use crate::i18n::{format as trf, tr}; use crate::{ControlRequest, SolveApp}; use backend::{ChatBackend, Event, PermissionOption, PromptPart, ToolStatus}; -pub(crate) use panel::{left_inset, tool_space}; -pub use panel::{show, tip as panel_tip, toggle}; +pub(crate) use panel::{left_inset, owns_keyboard_input, tool_space}; +pub use panel::{show, tip as panel_tip, toggle, toggle_shortcut}; /// Most entries kept in the conversation; older ones are dropped. const MAX_ITEMS: usize = 2000; @@ -316,10 +316,22 @@ impl Loading { } } +/// The model before an ACP agent was sent another, for when it refuses that one. +struct ModelRevert { + model: String, + /// The one sent was not listed, so it leaves the list again. + unlisted: bool, + /// The model remembered for this agent. + saved: Option, +} + #[derive(Default)] pub struct AgentChat { /// The panel is shown (View menu, the application bar's chat button, Ctrl+Shift+A). pub open: bool, + /// Only while dispatching this conversation's own admitted tool request. Window state: + /// creating/opening a design may carry the conversation, but a person's tab switch may not. + pub(crate) following_document: bool, pub items: Vec, pub input: String, /// The viewer, open on one message's pictures. @@ -363,6 +375,8 @@ pub struct AgentChat { pub confirm_new: bool, /// Where the panel was drawn last (for its shortcuts). pub panel_rect: Option, + /// A pointer press in the transcript owns keys just like a focused text editor. + keyboard_owned: bool, /// Unreserved sheet space, shared by the actual dock and its drag preview. pub(crate) dock_space: Option, /// The last message sent, kept to send again after a sign-in (its files too). @@ -399,6 +413,14 @@ pub struct AgentChat { /// The provider picked in the header when the models come from several providers (`None`: the /// current model's). It only narrows the model list; the agent keeps its model until one is chosen. pub model_provider: Option, + /// Why the running endpoint's models could not be listed, for the picker. + pub models_note: Option, + /// What to put back if the running ACP agent refuses the model it was last sent. + model_revert: Option, + /// The typed model an agent's model option was sent, until it answers. + typed_model: Option, + pub config_options: Option>, + pub config_pending: bool, /// An API endpoint's models, kept per endpoint (its base URL) for the next connection. models_cache: std::collections::HashMap>, /// The running API agent's endpoint (empty for other agents). @@ -417,6 +439,7 @@ pub struct AgentChat { /// Settings → AI: the Add agent dialog and connection tests. pub settings: settings::State, /// Latest authentication evidence from a connection test or a chat, per agent; never saved. + /// It belongs to the window, not to one tab's conversation. login_results: std::collections::HashMap, /// Desktop host hook: start the endpoint on demand. pub control_starter: Option, @@ -441,11 +464,14 @@ impl AgentChat { pub(crate) fn swap_document(&mut self, other: &mut Self) { std::mem::swap(self, other); std::mem::swap(&mut self.open, &mut other.open); + std::mem::swap(&mut self.following_document, &mut other.following_document); std::mem::swap(&mut self.settings, &mut other.settings); std::mem::swap(&mut self.control_starter, &mut other.control_starter); std::mem::swap(&mut self.models_cache, &mut other.models_cache); std::mem::swap(&mut self.window_placed, &mut other.window_placed); std::mem::swap(&mut self.connect_at_start, &mut other.connect_at_start); + // A sign-in proven in one tab holds for that agent in every tab (#9293). + std::mem::swap(&mut self.login_results, &mut other.login_results); #[cfg(not(target_arch = "wasm32"))] { std::mem::swap(&mut self.detection, &mut other.detection); @@ -453,18 +479,49 @@ impl AgentChat { } // Hit regions must be measured again for the incoming conversation. self.panel_rect = None; + self.keyboard_owned = false; self.dock_space = None; self.drop_rect = None; } pub(crate) fn disconnect_document(&mut self, session: &mut solidcraft_engine::Session, wait: bool) { finish_turn(self, session); + self.clear_config(); self.stop_backend(wait); if self.state.is_some() { self.state = Some(State::Off); } } + fn clear_config(&mut self) { + if self.config_options.take().is_some() { + self.models.clear(); + self.model.clear(); + self.modes.clear(); + self.mode.clear(); + self.model_provider = None; + } + self.config_pending = false; + self.typed_model = None; + } + + fn apply_config_snapshot(&mut self, options: Vec) { + self.config_options = Some(options.clone()); + let model = options.iter().find(|o| o.category == "model"); + self.models = model + .map(|o| { + o.options.iter().map(|x| acp::ModelInfo { id: x.value.clone(), name: x.name.clone(), description: x.description.clone() }).collect() + }) + .unwrap_or_default(); + let current = model.map_or_else(String::new, |o| o.current_value.clone()); + if current != self.model { + self.model_provider = None; + } + self.model = current; + let mode = options.iter().find(|o| o.category == "mode"); + self.modes = mode.map(|o| o.options.iter().map(|x| (x.value.clone(), x.name.clone())).collect()).unwrap_or_default(); + self.mode = mode.map_or_else(String::new, |o| o.current_value.clone()); + } /// Put a file on the next message with an id of its own; its name back. fn add_file(&mut self, file: attach::Attachment) -> String { let id = self.next_file_id(); @@ -537,6 +594,11 @@ impl AgentChat { pictures.push(Picture::shared(Arc::new(png), "", true)); } } + /// Say that the agent refused a model, and in its words why. + fn model_refused(&mut self, model: &str, error: &str) { + let text = trf("ui.agent_chat_model_rejected", &[("model", model), ("error", error)]); + self.notice(text.chars().take(MODELS_NOTE_CAP).collect::(), true); + } fn notice(&mut self, text: impl Into, error: bool) { self.push(Item::Notice { text: text.into(), error }); } @@ -610,7 +672,8 @@ impl AgentChat { self.state = Some(State::Ready); self.picking = Some(false); // Keep the mode across a new chat. - if let Some(m) = self.restore_mode.take() + if self.config_options.is_none() + && let Some(m) = self.restore_mode.take() && self.modes.iter().any(|(id, _)| *id == m) && let Some(b) = self.backend.as_mut() { @@ -669,26 +732,73 @@ impl AgentChat { self.push(Item::Plan(entries)); } } - Event::Permission { key, title, options } => return Some(Outcome::Permission { key, title, options }), + Event::Permission { key, title, kind, options } => return Some(Outcome::Permission { key, title, kind, options }), Event::Modes { current, available } => { - if !available.is_empty() { + if self.config_options.is_none() && !available.is_empty() { self.modes = available; } - self.mode = current; + if self.config_options.is_none() { + self.mode = current; + } } Event::Models { current, available } => { - if !available.is_empty() { - if !self.running_endpoint.is_empty() { - self.models_cache.insert(self.running_endpoint.clone(), available.clone()); + self.model_revert = None; + if self.config_options.is_none() && !available.is_empty() { + if self.models_note.is_some() { + // The listing failed: last time's list stays, with the configured model in it. + for model in available { + if !self.models.iter().any(|m| m.id == model.id) { + self.models.insert(0, model); + } + } + } else { + if !self.running_endpoint.is_empty() { + self.models_cache.insert(self.running_endpoint.clone(), available.clone()); + } + self.models = available; } - self.models = available; } - if current != self.model { + if self.config_options.is_none() { + if current != self.model { + self.model_provider = None; + } + self.model = current; + } + } + // Formatted here: the listing's thread has no language of its own. + Event::ModelsNote(error) => { + self.models_note = + error.map(|error| trf("ui.agent_chat_models_failed", &[("error", &error)]).chars().take(MODELS_NOTE_CAP).collect()); + } + Event::ModelRejected(message) => { + let refused = self.model.clone(); + self.model_refused(&refused, &message); + if let Some(revert) = self.model_revert.take() { + if revert.unlisted { + let refused = std::mem::take(&mut self.model); + self.models.retain(|m| m.id != refused); + } + self.model = revert.model; self.model_provider = None; } - self.model = current; + } + Event::ConfigOptions(options) => { + self.apply_config_snapshot(options); + } + Event::ConfigOptionFinished { result, .. } => { + self.config_pending = false; + let typed = self.typed_model.take(); + match (result, typed) { + (Ok(options), _) => { + self.apply_config_snapshot(options); + } + // An agent's own words may not say what it refused ("Internal error"). + (Err(message), Some(model)) => self.model_refused(&model, &message), + (Err(message), None) => self.notice(message, true), + } } Event::AuthRequired { methods } => { + self.clear_config(); self.auth = methods; self.state = Some(State::NeedsAuth); self.picking = Some(false); @@ -706,8 +816,12 @@ impl AgentChat { if std::mem::take(&mut self.discard_end) { return Some(Outcome::TurnEnd); } - if !matches!(reason.as_str(), "" | "auth" | "error") { - self.notice(format!("({reason})"), false); + match reason.as_str() { + "" | "auth" | "error" => {} + // Not a missing tool: the answer ran out of room, or the model declined (#9495). + "max_tokens" => self.notice(tr("ui.agent_chat_reply_cut_off").to_string(), false), + "refusal" => self.notice(tr("ui.agent_chat_reply_declined").to_string(), false), + _ => self.notice(format!("({reason})"), false), } return Some(Outcome::TurnEnd); } @@ -720,8 +834,16 @@ impl AgentChat { } } Event::Exited { tail } => { + self.clear_config(); self.state = Some(if matches!(self.state(), State::Starting | State::Failed) { State::Failed } else { State::Exited }); self.steering = false; + for item in &mut self.items { + if let Item::Tool { status, .. } = item + && !matches!(status, Some(ToolStatus::Completed | ToolStatus::Failed)) + { + *status = Some(ToolStatus::Failed); + } + } let last: Vec = tail.into_iter().rev().take(6).collect::>().into_iter().rev().collect(); let detail = if last.is_empty() { String::new() } else { format!("\n{}", last.join("\n")) }; self.notice(format!("{}{detail}", tr("ui.agent_chat_exited")), true); @@ -738,7 +860,7 @@ enum Outcome { /// A message was answered (or the agent stopped): the turn's bookkeeping ends. TurnEnd, /// The agent asks before running something of its own: answered by the mode, or asked. - Permission { key: u64, title: String, options: Vec }, + Permission { key: u64, title: String, kind: Option, options: Vec }, } /// The AI features are on (the master switch in Settings → AI) and this is the desktop app. @@ -795,7 +917,7 @@ pub(crate) fn assistant_mark(app: &SolveApp) -> AssistantMark { ) } -pub(crate) fn assistant_tip(mark: AssistantMark) -> String { +pub(crate) fn assistant_tip(app: &SolveApp, mark: AssistantMark) -> String { let state = match mark { AssistantMark::Quiet => tr("ui.agent_chat_state_off").to_string(), AssistantMark::Ready => tr("ui.agent_chat_state_ready").to_string(), @@ -804,13 +926,11 @@ pub(crate) fn assistant_tip(mark: AssistantMark) -> String { AssistantMark::Stopped => tr("ui.agent_chat_state_exited").to_string(), AssistantMark::Waiting(count) => trf("ui.assistant_waiting", &[("count", &count.to_string())]), }; - format!("{} (Ctrl+Shift+A) — {state}", tr("ui.assistant")) -} - -/// Whether a permission question is about one of SolidCraft's own tools (which SolidCraft's own -/// gate checks): the agents name MCP tools after their server. -fn solidcraft_tool(title: &str) -> bool { - title.to_ascii_lowercase().contains("solidcraft") + let name = match crate::keymap::display_for(app, "ui.assistant") { + Some(key) => format!("{} ({key})", tr("ui.assistant")), + None => tr("ui.assistant").to_string(), + }; + format!("{name} — {state}") } /// `solidcraft-cli` next to this program, else on the search path. @@ -882,6 +1002,11 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { } else if cli.is_none() { chat.notice(tr("ui.agent_chat_no_cli"), true); } + // Found, but it failed when asked its version (#9034): say why and how to reinstall it before + // the system's own message arrives. It is still started, in case it only lacks `--version`. + if let Some(hint) = entry.problem_hint() { + chat.notice(hint, true); + } let bridge = cli.zip(chat.tools_port).map(|(cli, port)| acp::McpBridge { cli, port }); chat.tools_available = Some(bridge.is_some()); let wake = ctx.clone(); @@ -901,6 +1026,7 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { key, http, request_timeout_s: entry.request_timeout_s, + reasoning_effort: entry.reasoning_effort.clone(), }, start, ) @@ -919,6 +1045,8 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { chat.mode.clear(); chat.models.clear(); chat.model.clear(); + chat.models_note = None; + chat.model_revert = None; chat.running_endpoint = if entry.kind.is_api() { entry.base_url.clone() } else { String::new() }; // An endpoint's models from the last time, until the new list arrives. if let Some(list) = chat.models_cache.get(&chat.running_endpoint) { @@ -990,6 +1118,66 @@ pub fn shutdown(app: &mut SolveApp) { crate::documents::disconnect_background_chats(app, true); } +/// Mark the origin only for this synchronous dispatch. Deferred work carries the same trusted +/// turn flag and enters here when it applies; JSON parameters cannot opt into continuation. +pub(crate) fn with_tool_request( + app: &mut SolveApp, + active: Option<&Arc>, + run: impl FnOnce(&mut SolveApp) -> T, +) -> T { + let own = active.is_some_and(|active| { + active.load(std::sync::atomic::Ordering::Relaxed) && app.agent_chat.turn.as_ref().is_some_and(|turn| Arc::ptr_eq(active, &turn.active)) + }); + // A batch may replace the design and then roll back to its checkpoint. Keep the turn's + // original undo boundary when that happens, including edits made before the batch. + let before = app.agent_chat.turn.as_ref().filter(|_| own).map(|t| (app.session.doc.clone(), t.start_doc.clone(), t.start_undo)); + let previous = std::mem::replace(&mut app.agent_chat.following_document, own); + let result = run(app); + app.agent_chat.following_document = previous; + if let Some((doc, start_doc, start_undo)) = before + && Arc::ptr_eq(&doc, &app.session.doc) + && let Some(turn) = app.agent_chat.turn.as_mut() + && active.is_some_and(|active| Arc::ptr_eq(active, &turn.active)) + { + turn.start_doc = start_doc; + turn.start_undo = start_undo; + } + result +} + +/// The agent's replacement succeeded. Keep its backend, transcript, queue, limits and validity +/// flag; subsequent edits undo in this design and picked geometry belongs to the old one. +pub(crate) fn continue_in_document(app: &mut SolveApp) { + if let Some(turn) = app.agent_chat.turn.as_mut() { + turn.start_doc = app.session.doc.clone(); + turn.start_undo = app.session.undo.len(); + } + app.agent_chat.picked.clear(); + app.agent_chat.picked_context = Context::default(); + app.agent_chat.selected_count = None; +} + +/// A newly opened tab has no conversation to displace. Move the initiating chat into it, +/// grouping the previous design's completed edits before its session is parked. +pub(crate) fn follow_new_tab(app: &mut SolveApp, switch: impl FnOnce(&mut SolveApp)) { + if !app.agent_chat.following_document { + switch(app); + return; + } + if let Some(turn) = app.agent_chat.turn.as_ref() { + let steps = + merge_undo(&mut app.session.undo, &turn.start_doc, turn.start_undo, &trf("ui.agent_chat_undo_label", &[("message", &turn.label)])); + if steps > 0 { + app.agent_chat.push(Item::Changes { steps, doc: app.session.doc.clone(), undone: false }); + } + } + let mut chat = AgentChat::default(); + app.agent_chat.swap_document(&mut chat); + switch(app); + app.agent_chat.swap_document(&mut chat); + continue_in_document(app); +} + /// A tab switch stops this turn before its session leaves the app. Keep the backend's own /// conversation, drafts and queue, but do not send that queue automatically on returning. pub(crate) fn leave_document(app: &mut SolveApp) { @@ -1225,6 +1413,7 @@ pub fn new_chat(app: &mut SolveApp) { chat.stopped = false; chat.ended = None; chat.discard_end = running; + chat.model_revert = None; if matches!(chat.state(), State::Ready | State::Busy) { chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty()); chat.state = Some(State::Starting); @@ -1232,6 +1421,7 @@ pub fn new_chat(app: &mut SolveApp) { b.new_session(); } } + chat.clear_config(); } /// Whether New chat would throw something away that the user may want (so it asks first). @@ -1472,14 +1662,15 @@ pub fn answer_permission(app: &mut SolveApp, index: usize, option: Option<&str>) app.agent_chat.answer(index, option); } -/// The agent asks before running something of its own. SolidCraft's own tools are checked by -/// SolidCraft's gate, so they're allowed here (no double question); otherwise the mode or an -/// earlier "always allow" may answer, and the chat says so; otherwise the user is asked. -fn on_permission(app: &mut SolveApp, key: u64, title: String, options: Vec) { +/// The agent asks before running something of its own. The chat's own MCP tools are checked by +/// SolidCraft's gate, so they're allowed here (no double question, see [`acp::is_bridge_tool`]); +/// otherwise the mode or an earlier "always allow" may answer, and the chat says so; otherwise the +/// user is asked. +fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str>, options: Vec) { let agent = app.agent_chat.running_id.clone(); let mode = agents::mode_for(&app.preferences, &agent); let remembered = agents::always_allowed(&app.preferences, &agent, &title); - let why = if solidcraft_tool(&title) { + let why = if acp::is_bridge_tool(&title, kind) { Some("ui.ai_auto_ours") } else if remembered { Some("ui.ai_auto_remembered") @@ -1750,6 +1941,14 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { let events = app.agent_chat.backend.as_mut().map(|b| b.poll()).unwrap_or_default(); for e in events { let ready = matches!(e, Event::Ready { .. }); + let configured = matches!(e, Event::ConfigOptionFinished { .. }); + let confirmed_model = match &e { + Event::ConfigOptionFinished { id, result: Ok(options) } => { + options.iter().find(|o| o.category == "model").filter(|o| o.id == *id).map(|o| o.current_value.clone()) + } + _ => None, + }; + let refused = if matches!(e, Event::ModelRejected(_)) { app.agent_chat.model_revert.as_ref().map(|r| r.saved.clone()) } else { None }; match app.agent_chat.on_event(e) { Some(Outcome::TurnEnd) => { end_turn(app); @@ -1760,19 +1959,45 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { b.answer_permission(key, None); } } - Some(Outcome::Permission { key, title, options }) => on_permission(app, key, title, options), + Some(Outcome::Permission { key, title, kind, options }) => on_permission(app, key, title, kind.as_deref(), options), + None => {} + } + if let Some(model) = confirmed_model { + app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), model.clone()); + if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind.is_api()) { + a.model = model; + } + } + match refused { + Some(Some(saved)) => { + app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), saved); + } + Some(None) => { + app.preferences.agent_models.remove(&app.agent_chat.running_id); + } None => {} } if ready { apply_saved_model(app); } - if ready && let Some((text, image, at, files)) = app.agent_chat.queued.take() { - start_turn(app, text, image, at, files); + if (ready || configured) && !app.agent_chat.config_pending { + if app.agent_chat.config_options.is_some() + && let Some(mode) = app.agent_chat.restore_mode.take() + && mode != app.agent_chat.mode + { + set_mode(app, &mode); + } + if !app.agent_chat.config_pending + && let Some((text, image, at, files)) = app.agent_chat.queued.take() + { + start_turn(app, text, image, at, files); + } } } #[cfg(not(target_arch = "wasm32"))] { settings::poll_capabilities(app, ctx); + settings::poll_listing(app, ctx); connect_at_start(app, ctx); } pump_tools(app); @@ -1799,15 +2024,74 @@ pub fn refresh(app: &mut SolveApp, ctx: &egui::Context) { /// Choose the model for this chat (the header's model picker): the agent switches to it, and it is /// remembered for this agent; an API endpoint's agent also keeps it as its default model. pub fn set_model(app: &mut SolveApp, model: &str) { - if !app.agent_chat.models.iter().any(|m| m.id == model) { + if let Some(options) = app.agent_chat.config_options.as_ref() { + let Some(option) = options.iter().find(|x| x.category == "model") else { + return; + }; + let id = option.id.clone(); + set_config_option(app, &id, model); return; } - if let Some(b) = app.agent_chat.backend.as_mut() { + if app.agent_chat.models.iter().any(|m| m.id == model) { + send_model(app, model); + } +} + +/// Whether a model the agent did not list can be sent: an endpoint, an ACP agent with a model +/// option, or a legacy ACP agent that listed models. +pub fn custom_models_accepted(app: &SolveApp) -> bool { + let chat = &app.agent_chat; + if chat.backend.is_none() || !chat.state().running() { + return false; + } + match chat.config_options.as_ref() { + Some(options) => options.iter().any(|o| o.category == "model"), + None => !chat.running_endpoint.is_empty() || !chat.models.is_empty(), + } +} + +/// A typed model (the pickers' custom row). A listed id goes the usual way, others by the agent's +/// kind; an agent that refuses it keeps its model and the chat says so. Returns whether it was sent. +pub fn set_custom_model(app: &mut SolveApp, text: &str) -> bool { + let model = text.trim(); + if !model_id_valid(model) || !custom_models_accepted(app) { + return false; + } + let option = app.agent_chat.config_options.as_ref().and_then(|options| options.iter().find(|o| o.category == "model")); + if let Some(id) = option.map(|o| o.id.clone()) { + let sent = set_config_option_checked(app, &id, model, false); + if sent { + app.agent_chat.typed_model = Some(model.to_string()); + } + return sent; + } + send_model(app, model); + true +} + +/// Switch a legacy ACP agent or an endpoint to `model`: it shows as current at once and is +/// remembered for this agent; an endpoint also keeps it as its default model. +fn send_model(app: &mut SolveApp, model: &str) { + let agent = app.agent_chat.running_id.clone(); + let chat = &mut app.agent_chat; + let unlisted = !chat.models.iter().any(|m| m.id == model); + let entry = || acp::ModelInfo { id: model.to_string(), name: model.to_string(), description: String::new() }; + if unlisted { + chat.models.insert(0, entry()); + chat.models.truncate(MODEL_LIST_CAP); + } + if chat.running_endpoint.is_empty() { + chat.model_revert = Some(ModelRevert { model: chat.model.clone(), unlisted, saved: app.preferences.agent_models.get(&agent).cloned() }); + } else if unlisted { + let cached = chat.models_cache.entry(chat.running_endpoint.clone()).or_default(); + cached.insert(0, entry()); + cached.truncate(MODEL_LIST_CAP); + } + if let Some(b) = chat.backend.as_mut() { b.set_model(model); } - app.agent_chat.model = model.to_string(); - app.agent_chat.model_provider = None; - let agent = app.agent_chat.running_id.clone(); + chat.model = model.to_string(); + chat.model_provider = None; if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind.is_api()) { a.model = model.to_string(); } @@ -1830,10 +2114,22 @@ pub fn models_shown(app: &SolveApp) -> bool { /// Longest provider name kept from an agent's model list. const PROVIDER_NAME_CAP: usize = 128; +/// Most models kept for a picker, whether listed or typed. +const MODEL_LIST_CAP: usize = 2000; +/// Longest model id kept from a listing or sent to an agent. +pub const MODEL_ID_CAP: usize = 256; +/// Longest note about a listing that failed or a model the agent refused. +const MODELS_NOTE_CAP: usize = 1024; + +/// Whether a model id can go to an agent: not empty, not too long, no control characters. +fn model_id_valid(id: &str) -> bool { + !id.is_empty() && id.chars().count() <= MODEL_ID_CAP && !id.chars().any(char::is_control) +} /// A model's provider and its name at that provider, when the agent says which provider serves it: -/// a name `Provider · model` (Hermes, OpenCode) or a description `Provider: …` (up to a ` • `). -/// `None`: the agent names no provider. +/// a name `Provider · model` (Hermes, OpenCode), a description `Provider: …` (up to a ` • `), or +/// an endpoint's listing whose id reads `vendor/model` and whose description (the endpoint's own +/// name for it) reads `Vendor: Model` (OpenRouter). `None`: the agent names no provider. pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> { let cap = |s: &str| s.trim().chars().take(PROVIDER_NAME_CAP).collect::(); if let Some((provider, name)) = m.name.split_once(" · ") @@ -1842,9 +2138,48 @@ pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> { { return Some((cap(provider), name.trim().to_string())); } - let rest = m.description.strip_prefix("Provider:")?; - let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or(""); - (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone())) + if let Some(rest) = m.description.strip_prefix("Provider:") { + let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or(""); + return (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone())); + } + let first_line = m.description.lines().next().unwrap_or(""); + if m.id.contains('/') + && let Some((vendor, name)) = first_line.split_once(": ") + && !vendor.trim().is_empty() + && vendor.chars().count() <= PROVIDER_NAME_CAP + && !name.trim().is_empty() + { + return Some((cap(vendor), name.trim().to_string())); + } + None +} + +/// How a picker shows `models`: each one's label, the group it folds under and its tooltip. With +/// models from two or more providers the label is the name at the provider, the group the +/// provider and the tooltip the id (or the description where the label already is the id); +/// otherwise the name as it is, no group, and the description. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub fn model_rows(models: &[acp::ModelInfo]) -> Vec<(String, Option, String)> { + let mut providers: Vec = Vec::new(); + for m in models { + let p = provider_of(m); + if !providers.contains(&p) { + providers.push(p); + } + } + let grouped = providers.len() >= 2; + models + .iter() + .map(|m| { + if grouped { + let (provider, name) = model_provider(m).unwrap_or_else(|| (provider_of(m), m.name.clone())); + let tip = if name == m.id { m.description.clone() } else { m.id.clone() }; + (name, Some(provider), tip) + } else { + (m.name.clone(), None, m.description.clone()) + } + }) + .collect() } /// The provider a model is listed under: its own, or "Other" when the agent names none. @@ -1897,8 +2232,17 @@ pub fn listed_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String)> { .collect() } -/// Show one provider's models in the model picker (the header's provider picker). The agent keeps -/// its model until one of them is chosen. A provider the agent does not offer is ignored. +/// Every model the header's picker lists, with its label, the group it folds under and its tooltip +/// ([`model_rows`]). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub fn grouped_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String, Option, String)> { + let rows = model_rows(&app.agent_chat.models); + app.agent_chat.models.iter().cloned().zip(rows).map(|(m, (label, group, tip))| (m, label, group, tip)).collect() +} + +/// The provider whose group the header's model picker opens first (the control channel's +/// `provider`). The agent keeps its model until one is chosen. A provider the agent does not offer +/// is ignored. pub fn set_model_provider(app: &mut SolveApp, provider: &str) { if model_providers(app).iter().any(|(n, _)| n == provider) { app.agent_chat.model_provider = Some(provider.to_string()); @@ -1907,6 +2251,14 @@ pub fn set_model_provider(app: &mut SolveApp, provider: &str) { /// Switch the agent to one of its own modes (the header's mode picker). pub fn set_mode(app: &mut SolveApp, mode: &str) { + if let Some(options) = app.agent_chat.config_options.as_ref() { + let Some(option) = options.iter().find(|x| x.category == "mode") else { + return; + }; + let id = option.id.clone(); + set_config_option(app, &id, mode); + return; + } if app.agent_chat.modes.iter().any(|(id, _)| id == mode) && let Some(b) = app.agent_chat.backend.as_mut() { @@ -1915,6 +2267,29 @@ pub fn set_mode(app: &mut SolveApp, mode: &str) { } } +/// Change a reported modern ACP configuration option; only acknowledged snapshots change state. +pub fn set_config_option(app: &mut SolveApp, id: &str, value: &str) { + set_config_option_checked(app, id, value, true); +} + +/// [`set_config_option`], with a choice the agent did not list (`listed_only` false: a typed +/// model, which the agent may refuse). Returns whether it was sent. +fn set_config_option_checked(app: &mut SolveApp, id: &str, value: &str, listed_only: bool) -> bool { + let Some(option) = app.agent_chat.config_options.as_ref().and_then(|xs| xs.iter().find(|x| x.id == id)) else { + return false; + }; + if app.agent_chat.config_pending + || !matches!(app.agent_chat.state(), State::Ready | State::Busy) + || (listed_only && !option.options.iter().any(|x| x.value == value)) + { + return false; + } + let Some(b) = app.agent_chat.backend.as_mut() else { return false }; + b.set_config_option(id, value); + app.agent_chat.config_pending = true; + true +} + /// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`, /// `connect_at_start` and `open_at_start` (the launch preferences), `open`, /// `side`, `minimized`, `width`, `refresh`, `connect`, `stop`, `attach` (a file's path, for the @@ -1990,6 +2365,13 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result app.agent_chat.settings.add = None, } } + // The same dialog on an agent you added (by id), filled with what it holds; its key stays hidden. + if let Some(id) = p.get("edit_dialog") { + let id = id.as_str().ok_or("edit_dialog must be the id of an agent you added")?; + if !settings::open_edit(app, id) { + return Err(format!("edit_dialog: no added agent `{id}`")); + } + } if let Some(id) = p.get("default_agent").and_then(Value::as_str) { app.preferences.agent_default = id.to_string(); } @@ -2000,7 +2382,16 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Value { #[cfg(not(target_arch = "wasm32"))] let detection = c.detection.as_ref().map(|d| { json!({ - "found": d.found.iter().map(|f| json!({"id": f.id, "name": f.name, "argv": f.argv, "version": f.version, "login": f.login.id()})).collect::>(), + "found": d.found.iter().map(|f| json!({"id": f.id, "name": f.name, "argv": f.argv, "version": f.version, "login": f.login.id(), "problem": f.problem})).collect::>(), "missing": d.missing.iter().map(|m| json!({"id": m.id, "install": m.install})).collect::>(), "ms": d.took_ms, }) @@ -2122,14 +2513,16 @@ pub fn status(app: &SolveApp) -> Value { #[cfg(target_arch = "wasm32")] let detection: Option = None; let pid = c.backend.as_ref().and_then(|b| b.pid()); - json!({ + let mut state = json!({ "features": app.preferences.ai_features, + "configOptions": c.config_options, + "configPending": c.config_pending, "toolbarButton": app.preferences.ai_toolbar_button, "connectAtStart": app.preferences.agent_connect_at_start, "openAtStart": app.preferences.agent_chat_open_at_start, "lastAgent": app.preferences.agent_last, "permissions": app.preferences.ai_permissions.id(), - "agents": agents::entries(app).iter().map(|e| json!({"id": e.id, "name": e.name, "kind": e.kind.id(), "found": e.found, "version": e.version, "login": e.login, "request_timeout_s": e.kind.is_api().then_some(e.request_timeout_s)})).collect::>(), + "agents": agents::entries(app).iter().map(|e| json!({"id": e.id, "name": e.name, "kind": e.kind.id(), "found": e.found, "version": e.version, "login": e.login, "problem": e.problem, "request_timeout_s": e.kind.is_api().then_some(e.request_timeout_s)})).collect::>(), "currentAgent": agents::current(app).map(|e| e.id), "models": c.models.iter().map(|m| json!({"id": m.id, "name": m.name, "description": m.description})).collect::>(), "model": c.model, @@ -2162,7 +2555,13 @@ pub fn status(app: &SolveApp) -> Value { "turnWarning": c.turn_warning, "detection": detection, "items": items, - }) + }); + // Added apart: `json!` has reached the compiler's recursion limit above. + if let Some(state) = state.as_object_mut() { + state.insert("modelsNote".into(), json!(c.models_note)); + state.insert("customModels".into(), json!(custom_models_accepted(app))); + } + state } #[cfg(test)] diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 88c0fcaf3..30002a73c 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -3,6 +3,7 @@ //! width and fold are preferences, so they come back next time. use crate::fonts::RichTextExt as _; +use crate::ui_kit::BackingTooltipExt as _; use crate::ui_kit::{Container, Edge, Surface}; use egui::{Align, Align2, Color32, Id, Layout, Rect, RichText, Sense, Stroke, pos2, vec2}; @@ -14,8 +15,34 @@ pub const MIN_WIDTH: f32 = 280.0; pub const MAX_WIDTH: f32 = 760.0; /// The folded panel's width. const STRIP: f32 = 30.0; -/// The keyboard shortcut that shows and hides the panel (also from its own text field). -pub const SHORTCUT: egui::KeyboardShortcut = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), egui::Key::A); +/// Consume the configured toggle before CAD shortcuts, including in the chat's own window. +/// Bare character keys remain text while a field owns the keyboard; chords still hide chat. +pub fn toggle_shortcut(app: &mut SolveApp, ctx: &egui::Context) { + if !shown(app) || crate::keymap::capturing(app) { + return; + } + let keys = crate::keymap::keys(app, "ui.assistant"); + let typing = ctx.egui_wants_keyboard_input(); + let pressed = ctx.input_mut(|input| { + let mut pressed = false; + input.events.retain(|event| { + if let egui::Event::Key { key, modifiers, pressed: true, repeat, .. } = event { + if typing && !modifiers.command && !modifiers.ctrl && !modifiers.alt { + return true; + } + if keys.contains(&crate::keymap::key_name(*key, *modifiers)) { + pressed |= !repeat; + return false; + } + } + true + }); + pressed + }); + if pressed { + toggle(app); + } +} fn panel_id(left: bool) -> Id { Id::new(if left { "sc_agent_chat_left" } else { "sc_agent_chat_right" }) @@ -50,9 +77,31 @@ pub fn toggle(app: &mut SolveApp) { } /// The tooltip of the chat's buttons: its name and shortcut. -pub fn tip() -> String { - let key = if cfg!(target_os = "macos") { "Cmd+Shift+A" } else { "Ctrl+Shift+A" }; - format!("{} ({key})", tr("ui.agent_chat")) +pub fn tip(app: &SolveApp) -> String { + match crate::keymap::display_for(app, "ui.assistant") { + Some(key) => format!("{} ({key})", tr("ui.agent_chat")), + None => tr("ui.agent_chat").to_string(), + } +} + +/// Selectable transcript labels do not take egui keyboard focus. Keep their keys out of +/// CAD until a pointer press outside the chat, not merely a move of the pointer. Use the +/// panel in this window, never label selections belonging to another native viewport. +/// Called before layout so even a click and a shortcut in the same frame are routed here. +pub(crate) fn owns_keyboard_input(app: &mut SolveApp, ctx: &egui::Context) -> bool { + let rect = app.agent_chat.panel_rect.filter(|_| shown(app) && app.agent_chat.open && !app.preferences.agent_chat_minimized); + let Some(rect) = rect else { + app.agent_chat.keyboard_owned = false; + return false; + }; + ctx.input(|input| { + for event in &input.events { + if let egui::Event::PointerButton { pos, pressed: true, .. } = event { + app.agent_chat.keyboard_owned = rect.contains(*pos); + } + } + }); + app.agent_chat.keyboard_owned } /// The panel, when the chat is turned on and open. Call before the central viewport is laid out. @@ -69,9 +118,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if !shown(app) { return; } - if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) { - toggle(app); - } // A window that isn't drawn this frame closes; the next one opens at the saved place. if !(app.agent_chat.open && app.preferences.agent_chat_popped) { app.agent_chat.window_placed = false; @@ -106,24 +152,22 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { app.agent_chat.dock_space = Some(Rect::from_x_y_ranges(screen.x_range(), available.y_range())); let t = Tokens::get(); let left = app.preferences.agent_chat_side == "left"; - let side = |id: Id| Container::new(ui.ctx(), Surface::Panel).edge(id, if left { Edge::Left } else { Edge::Right }); + let host = Container::new(ui.ctx(), Surface::Panel); + let side = |id: Id| host.edge(id, if left { Edge::Left } else { Edge::Right }); if app.preferences.agent_chat_minimized { - let r = side(Id::new("sc_agent_chat_strip")) - .exact_size(STRIP) - .resizable(false) - .frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.panel)) - .show(ui, |ui| strip(app, ui)); + let r = host + .show_edge(ui, side(Id::new("sc_agent_chat_strip")).exact_size(STRIP).resizable(false), host.edge_frame(t.panel), |ui| strip(app, ui)); app.agent_chat.drop_rect = Some(r.response.rect); show_drop_hint(app, &ctx); return; } let width = app.preferences.agent_chat_width.clamp(MIN_WIDTH, MAX_WIDTH); - let r = side(panel_id(left)) - .default_size(width) - .size_range(MIN_WIDTH..=MAX_WIDTH) - .resizable(true) - .frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.dialog_body)) - .show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, left))); + let r = host.show_edge( + ui, + side(panel_id(left)).default_size(width).size_range(MIN_WIDTH..=MAX_WIDTH).resizable(true), + host.edge_frame(t.dialog_body), + |ui| ui_kit::scope(ui, |ui| body(app, ui, left)), + ); crate::scenario::publish_rect("agent_chat:panel", r.response.rect); app.agent_chat.panel_rect = Some(r.response.rect); #[cfg(not(target_arch = "wasm32"))] @@ -161,9 +205,9 @@ pub(crate) fn tool_space(app: &SolveApp, mut available: Rect) -> Rect { && let Some(chat) = app.agent_chat.panel_rect.filter(|r| r.is_finite() && r.is_positive()) { if app.preferences.agent_chat_side == "left" { - available.min.x = (chat.right() + crate::shell::SHELL_GAP).clamp(available.left(), available.right()); + available.min.x = crate::shell::within(chat.right() + crate::shell::SHELL_GAP, available.left(), available.right()); } else { - available.max.x = (chat.left() - crate::shell::SHELL_GAP).clamp(available.left(), available.right()); + available.max.x = crate::shell::within(chat.left() - crate::shell::SHELL_GAP, available.left(), available.right()); } } available @@ -211,7 +255,7 @@ fn floating(app: &mut SolveApp, ui: &mut egui::Ui) { let frame = ui_kit::Panel::feature_frame(&ctx, app.ui.layout, side); let inner = (vec2(width, height) - frame.total_margin().sum()).max(egui::Vec2::ZERO); let panel = ui_kit::Panel::new(tr("ui.assistant"), Id::new("sc_agent_chat_floating"), anchor, available, side, frame).width(width); - if let Some(card) = panel.window(&ctx).fixed_size(inner).show(&ctx, |ui| { + if let Some(card) = panel.fixed_window(&ctx, inner).show(&ctx, |ui| { ui.set_min_size(inner); ui.set_max_size(inner); ui.set_clip_rect(ui.clip_rect().intersect(Rect::from_min_size(ui.max_rect().min, inner))); @@ -336,7 +380,7 @@ fn context_chips(ui: &mut egui::Ui, context: &Context, removable: bool) -> Optio }) .response; if !item.detail.is_empty() { - chip.on_hover_text(&item.detail); + chip.backing_on_hover_text(&item.detail); } } } @@ -382,7 +426,7 @@ fn picture_strip(ui: &mut egui::Ui, n: usize, pictures: &[Picture]) -> Option egui::Response { } crate::scenario::publish_rect(&format!("agent_chat:{kind}"), r); crate::scenario::publish_handle(&format!("agent_chat:{kind}"), r.center()); - resp.on_hover_text(tip) + resp.backing_on_hover_text(tip) } fn state_color(state: State) -> Color32 { @@ -669,8 +716,8 @@ fn strip(app: &mut SolveApp, ui: &mut egui::Ui) { if app.preferences.agent_chat_side == "left" { [r.right_top(), r.right_bottom()] } else { [r.left_top(), r.left_bottom()] }, t.primary_border(t.border), ); - let tip = format!("{} · {}", tip(), state.label()); - if resp.on_hover_text(tip).clicked() { + let tip = format!("{} · {}", tip(app), state.label()); + if resp.backing_on_hover_text(tip).clicked() { app.preferences.agent_chat_minimized = false; } } @@ -804,17 +851,19 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { let state = app.agent_chat.state(); if app.agent_chat.confirm_new { ui_kit::scope(ui, |ui| { - ui.set_width(ui.available_width()); - ui_kit::text(ui, tr("ui.agent_chat_new_confirm"), ui_kit::Text::Report("new_chat", false)); - ui.horizontal(|ui| { - let yes = ui_kit::button(ui, tr("ui.agent_chat_new"), ui_kit::Button::Normal); - crate::scenario::publish_handle("agent_chat:new_confirm", yes.rect.center()); - if yes.clicked() { - new_chat(app); - } - if ui_kit::button(ui, tr("ui.agent_chat_cancel"), ui_kit::Button::Normal).clicked() { - app.agent_chat.confirm_new = false; - } + inset(ui, |ui| { + ui.set_width(ui.available_width()); + ui_kit::text(ui, tr("ui.agent_chat_new_confirm"), ui_kit::Text::Report("new_chat", false)); + ui.horizontal(|ui| { + let yes = ui_kit::button(ui, tr("ui.agent_chat_new"), ui_kit::Button::Normal); + crate::scenario::publish_handle("agent_chat:new_confirm", yes.rect.center()); + if yes.clicked() { + new_chat(app); + } + if ui_kit::button(ui, tr("ui.agent_chat_cancel"), ui_kit::Button::Normal).clicked() { + app.agent_chat.confirm_new = false; + } + }); }); }); } @@ -826,7 +875,7 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { .auto_shrink([false, true]) .show(ui, |ui| picker(app, ui)); if state == State::NeedsAuth { - auth_box(app, ui); + inset(ui, |ui| auth_box(app, ui)); } // The input sits at the bottom of the panel and grows upwards: a long message makes its box // taller up to `edit_max`, then it scrolls, and the conversation takes what is left above. It @@ -847,8 +896,8 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { let frame = Container::new(ui.ctx(), Surface::Viewport).edge_frame(egui::Color32::TRANSPARENT); let composer = Container::new(ui.ctx(), Surface::Viewport).edge(Id::new("sc_agent_chat_composer"), Edge::Bottom); composer.resizable(false).show_separator_line(false).frame(frame).show(ui, |ui| { - ui_kit::assistant_composer_footer(ui, |ui| { - ui_kit::assistant_composer(ui, focused, |ui| { + let footer = ui_kit::assistant_composer_footer(ui, |ui| { + let boxed = ui_kit::assistant_composer(ui, focused, |ui| { // What Pick context chose for this message, each item with an ×. if !app.agent_chat.picked_context.is_empty() { let tray = app.agent_chat.picked_context.clone(); @@ -920,7 +969,7 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { ) }) .inner; - let permissions = permissions.on_hover_text(mode.label()); + let permissions = permissions.backing_on_hover_text(mode.label()); crate::scenario::publish_rect("agent_chat:permissions", permissions.rect); crate::scenario::publish_handle("agent_chat:permissions", permissions.rect.center()); // A message waits for files still being read. @@ -957,8 +1006,8 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { let attach = ui .add_enabled_ui(images, |ui| ui_kit::checkbox(ui, tr("ui.agent_chat_attach_view"), &mut app.agent_chat.attach_view)) .inner - .on_hover_text(tr("ui.agent_chat_attach_view_tip")) - .on_disabled_hover_text(tr("ui.agent_chat_no_images")); + .backing_on_hover_text(tr("ui.agent_chat_attach_view_tip")) + .backing_on_disabled_hover_text(tr("ui.agent_chat_no_images")); crate::scenario::publish_handle("agent_chat:attach", attach.rect.center()); // What is selected in the model goes with the message: text for the agent, // chips in the conversation. @@ -969,11 +1018,11 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { tr("ui.agent_chat_attach_selection").to_string() }; let pick = ui_kit::checkbox(ui, &label, &mut app.agent_chat.attach_selection) - .on_hover_text(tr("ui.agent_chat_attach_selection_tip")); + .backing_on_hover_text(tr("ui.agent_chat_attach_selection_tip")); crate::scenario::publish_handle("agent_chat:attach_selection", pick.rect.center()); // Choose faces, edges, features and bodies on purpose, then OK. let picker = ui_kit::button(ui, tr("ui.agent_chat_pick_context"), ui_kit::Button::Enabled(app.dialog.is_none())) - .on_hover_text(tr("ui.agent_chat_pick_context_tip")); + .backing_on_hover_text(tr("ui.agent_chat_pick_context_tip")); crate::scenario::publish_handle("agent_chat:pick_context", picker.rect.center()); pick_clicked = picker.clicked(); if let Some(turn) = &app.agent_chat.turn { @@ -987,7 +1036,9 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { }, ); }); + crate::scenario::publish_rect("agent_chat:composer_box", boxed.response.rect); }); + crate::scenario::publish_rect("agent_chat:composer_footer", footer.response.rect); }); if let Some(at) = remove_picked_at { remove_picked(app, at); @@ -1005,6 +1056,8 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = Tokens::get().space_10; conversation(app, ui); }); + // Last, so the scroll goes to this area and not to one nested in the conversation. + scroll_while_selecting(ui); }); if esc || stop_clicked { cancel(app); @@ -1033,18 +1086,17 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); let all = agents::entries(app); let current = agents::current(app); + // An advertised (even empty) config list replaces the older ACP model/mode pickers. + let modern = app.agent_chat.config_options.is_some(); ui.horizontal_wrapped(|ui| { let label = current.as_ref().map_or_else( || tr(if app.agent_chat.detecting.is_some() { "ui.agent_chat_detecting" } else { "ui.agent_chat_none_found_short" }).to_string(), |e| e.name.clone(), ); - let models = models_shown(app); + let models = !modern && models_shown(app); let providers = if models { model_providers(app) } else { Vec::new() }; - let w = (ui.available_width() - - if app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - - if models { 146.0 } else { 0.0 } - - if providers.is_empty() { 0.0 } else { 146.0 }) - .clamp(90.0, 260.0); + let w = (ui.available_width() - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - if models { 146.0 } else { 0.0 }) + .clamp(90.0, 260.0); let mut picked: Option = None; let mut add = false; let combo = ui @@ -1053,7 +1105,7 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::dropdown_menu(ui, "sc_agent_switch", &label, |ui| { for e in &all { let sel = current.as_ref().is_some_and(|c| c.id == e.id); - let r = ui_kit::list_picker(ui, &e.id, &e.name, sel).on_hover_text(format!("{} {}", e.detail(), e.login)); + let r = ui_kit::list_picker(ui, &e.id, &e.name, sel).backing_on_hover_text(format!("{} {}", e.detail(), e.login)); crate::scenario::publish_handle(&format!("agent_chat:agent:{}", e.id), r.rect.center()); if r.clicked() { picked = Some(e.id.clone()); @@ -1064,14 +1116,14 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { add = true; } if ui_kit::list_picker(ui, "settings", tr("ui.ai_settings"), false).clicked() { - crate::prefs::open_at(app, crate::prefs::PAGE_AI); + crate::prefs::open_at(app, crate::prefs::PAGE_ASSISTANT); } }) }) .inner; crate::scenario::publish_rect("agent_chat:switcher", combo.rect); crate::scenario::publish_handle("agent_chat:switcher", combo.rect.center()); - combo.on_hover_text(tr("ui.ai_switch_tip")); + combo.backing_on_hover_text(tr("ui.ai_switch_tip")); if add { super::settings::open_add(app); } @@ -1082,7 +1134,7 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { app.agent_chat.agent_id = Some(id); } // The agent's own modes (ACP `modes`): its own tools follow them. - if !app.agent_chat.modes.is_empty() { + if !modern && !app.agent_chat.modes.is_empty() { let modes = app.agent_chat.modes.clone(); let cur = modes.iter().find(|(id, _)| *id == app.agent_chat.mode).map_or_else(|| app.agent_chat.mode.clone(), |(_, n)| n.clone()); let mut pick: Option = None; @@ -1100,75 +1152,64 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { .inner; crate::scenario::publish_rect("agent_chat:mode", r.rect); crate::scenario::publish_handle("agent_chat:mode", r.rect.center()); - r.on_hover_text(tr("ui.ai_agent_mode_tip")); + r.backing_on_hover_text(tr("ui.ai_agent_mode_tip")); if let Some(m) = pick { set_mode(app, &m); } } - // Models from several providers: pick the provider first, then one of its models. - if let Some(shown) = shown_provider(app).filter(|_| !providers.is_empty()) { - let mut pick: Option = None; - let width = picker_width(ui, &shown); - let r = ui - .allocate_ui(vec2(width, t.control_height), |ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - ui_kit::dropdown_menu(ui, "sc_agent_provider", &shown, |ui| { - for (name, count) in &providers { - let row = ui_kit::list_picker(ui, &format!("provider:{name}"), name, *name == shown) - .on_hover_text(trf("ui.agent_chat_provider_models", &[("count", &count.to_string())])); - crate::scenario::publish_handle(&format!("agent_chat:provider:{name}"), row.rect.center()); - if row.clicked() { - pick = Some(name.clone()); - } - } - }) - }) - .inner; - crate::scenario::publish_rect("agent_chat:provider", r.rect); - crate::scenario::publish_handle("agent_chat:provider", r.rect.center()); - r.on_hover_text(tr("ui.agent_chat_provider_tip")); - if let Some(p) = pick { - set_model_provider(app, &p); - } - } // The agent's models (ACP `models`, or an endpoint's list): shown only when it reports some. if models { - let list = listed_models(app); - let cur = list.iter().find(|(m, _)| m.id == app.agent_chat.model).map_or_else( - || if providers.is_empty() { app.agent_chat.model.clone() } else { tr("ui.agent_chat_choose_model").to_string() }, - |(_, name)| name.clone(), - ); - let mut pick: Option = None; + // Models from several providers fold under their providers inside the picker, the + // current model's provider open. + let list = grouped_models(app); + let open = shown_provider(app).filter(|_| !providers.is_empty()); + let cur = list + .iter() + .find(|(m, _, _, _)| m.id == app.agent_chat.model) + .map_or_else(|| app.agent_chat.model.clone(), |(_, name, _, _)| name.clone()); let width = if providers.is_empty() { t.form_label_width } else { picker_width(ui, &cur) }; - let r = ui + let choices: Vec> = + list.iter().map(|(m, name, group, tip)| ui_kit::SearchChoice { value: &m.id, label: name, tip, group: group.as_deref() }).collect(); + let custom = custom_models_accepted(app); + let picker = ui .allocate_ui(vec2(width, t.control_height), |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - ui_kit::dropdown_menu(ui, "sc_agent_model", &cur, |ui| { - for (m, name) in &list { - let row = ui_kit::list_picker(ui, &m.id, name, m.id == app.agent_chat.model); - let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) }; - crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center()); - if row.clicked() { - pick = Some(m.id.clone()); - } - } - }) + ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: "sc_agent_model", + handles: "agent_chat:model", + current: &cur, + current_value: &app.agent_chat.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom, + note: app.agent_chat.models_note.as_deref(), + open_group: open.as_deref(), + enabled: true, + }, + ) }) .inner; - crate::scenario::publish_rect("agent_chat:model", r.rect); - crate::scenario::publish_handle("agent_chat:model", r.rect.center()); - r.on_hover_text(tr("ui.agent_chat_model_tip")); - if let Some(m) = pick { - set_model(app, &m); + picker.response.backing_on_hover_text(tr("ui.agent_chat_model_tip")); + match picker.inner { + Some(ui_kit::Picked::Listed(m)) => set_model(app, &m), + Some(ui_kit::Picked::Custom(m)) => { + set_custom_model(app, &m); + } + None => {} } } }); if let Some(warning) = settings::model_warning(app) { ui.add(egui::Label::new(RichText::new(warning).color(t.warning).size(t.font_small)).wrap()); } + if let Some(options) = app.agent_chat.config_options.clone() { + config_selects(app, ui, &options); + } ui.horizontal(|ui| { let b = if app.agent_chat.state().running() { - ui_kit::button(ui, tr("ui.agent_chat_stop"), ui_kit::Button::Normal).on_hover_text(tr("ui.agent_chat_stop_tip")) + ui_kit::button(ui, tr("ui.agent_chat_stop"), ui_kit::Button::Normal).backing_on_hover_text(tr("ui.agent_chat_stop_tip")) } else { let label = if app.agent_chat.state() == State::Failed { "ui.agent_chat_retry" } else { "ui.agent_chat_connect" }; ui_kit::button(ui, tr(label), ui_kit::Button::Normal) @@ -1222,6 +1263,271 @@ fn picker_width(ui: &egui::Ui, label: &str) -> f32 { text.clamp(t.form_label_width, most) } +/// An agent's select options are authoritative. Compact value pickers share a strip below the +/// agent switcher; only a narrow chat wraps them, rather than spending two full rows per option. +#[cfg(not(target_arch = "wasm32"))] +fn config_selects(app: &mut SolveApp, ui: &mut egui::Ui, options: &[acp::ConfigOption]) { + let t = Tokens::get(); + let pending = app.agent_chat.config_pending; + let strip_width = ui.available_width().min(ui.max_rect().width()).max(0.0); + let mut row = Vec::new(); + let mut used = 0.0; + for option in options { + let current = option.options.iter().find(|choice| choice.value == option.current_value); + let selected = current.map_or(option.current_value.as_str(), |choice| choice.name.as_str()); + let preview = compact_text(selected, 32); + let preferred = ui.painter().layout_no_wrap(preview, egui::FontId::proportional(t.font_label), t.text).size().x + 34.0; + let width = preferred.clamp(76.0, strip_width.clamp(76.0, 200.0)); + let spacing = if row.is_empty() { 0.0 } else { ui.spacing().item_spacing.x }; + if !row.is_empty() && used + spacing + width > strip_width { + ui.horizontal(|ui| { + for (option, width) in row.drain(..) { + config_select(app, ui, option, width, pending); + } + }); + used = 0.0; + } + used += if used == 0.0 { width } else { spacing + width }; + row.push((option, width)); + } + if !row.is_empty() { + ui.horizontal(|ui| { + for (option, width) in row { + config_select(app, ui, option, width, pending); + } + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn config_select(app: &mut SolveApp, ui: &mut egui::Ui, option: &acp::ConfigOption, width: f32, pending: bool) { + let t = Tokens::get(); + let current = option.options.iter().find(|choice| choice.value == option.current_value); + let selected = current.map_or(option.current_value.as_str(), |choice| choice.name.as_str()); + // Bound both the measurement and the visible label: agent-provided text may be huge. + // Width follows the current value, leaving short choices room to sit on one line. + let font = egui::FontId::proportional(t.font_label); + let mut chars = 32; + let displayed = loop { + let text = compact_text(selected, chars); + if chars == 1 || ui.painter().layout_no_wrap(text.clone(), font.clone(), t.text).size().x <= width - 36.0 { + break text; + } + chars -= 1; + }; + let name = if option.name.is_empty() { &option.id } else { &option.name }; + let tip = [name.as_str(), option.description.as_str(), current.map_or("", |choice| choice.description.as_str())] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join("\n"); + let mut picked = None; + let enabled = !pending && !option.options.is_empty(); + let handles = format!("agent_chat:config:{}", option.id); + let response = if option.category == "model" { + let choices: Vec> = option + .options + .iter() + .map(|choice| ui_kit::SearchChoice { + value: &choice.value, + label: &choice.name, + tip: &choice.description, + group: choice.group.as_deref(), + }) + .collect(); + let id = format!("sc_agent_config:{}", option.id); + let picker = ui + .allocate_ui(vec2(width, t.control_height), |ui| { + ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: &id, + handles: &handles, + current: &displayed, + current_value: &option.current_value, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: None, + open_group: None, + enabled, + }, + ) + }) + .inner; + picked = picker.inner; + // Under the names every kind of agent's model picker goes by. + let rows = format!("{handles}:"); + for (name, at) in crate::scenario::handles(&rows) { + if let Some(row) = name.strip_prefix(&rows) { + crate::scenario::publish_handle(&format!("agent_chat:model:{row}"), at); + } + } + crate::scenario::publish_target("agent_chat:model", picker.response.rect); + picker.response + } else { + let response = ui + .add_enabled_ui(enabled, |ui| { + ui.allocate_ui(vec2(width, t.control_height), |ui| { + ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| { + let mut previous_group: Option<&str> = None; + for choice in &option.options { + let group = choice.group.as_deref().filter(|g| !g.is_empty()); + if let Some(group) = group + && previous_group != Some(group) + { + ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).backing_on_hover_text(group); + } + previous_group = group; + let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value); + let row = row.backing_on_hover_text( + [choice.name.as_str(), choice.description.as_str()] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join("\n"), + ); + crate::scenario::publish_handle(&format!("{handles}:{}", choice.value), row.rect.center()); + if row.clicked() { + picked = Some(ui_kit::Picked::Listed(choice.value.clone())); + } + } + }) + }) + .inner + }) + .inner; + crate::scenario::publish_target(&handles, response.rect); + if option.category == "mode" { + crate::scenario::publish_handle("agent_chat:mode", response.rect.center()); + } + response + }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, enabled, format!("{name}: {selected}"))); + response.backing_on_hover_text(tip); + match picked { + Some(ui_kit::Picked::Listed(value)) => super::set_config_option(app, &option.id, &value), + Some(ui_kit::Picked::Custom(value)) => { + super::set_custom_model(app, &value); + } + None => {} + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn compact_text(text: &str, max_chars: usize) -> String { + let mut chars = text.chars(); + let short: String = chars.by_ref().take(max_chars).collect(); + if chars.next().is_some() { format!("{short}…") } else { short } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod config_ui_tests { + use super::*; + + fn option(id: &str, category: &str, choices: &[(&str, &str, Option<&str>)]) -> acp::ConfigOption { + acp::ConfigOption { + id: id.into(), + name: id.into(), + description: format!("Choose {id}"), + category: category.into(), + current_value: choices.first().map_or("", |choice| choice.0).into(), + options: choices + .iter() + .map(|(value, name, group)| acp::ConfigChoice { + value: (*value).into(), + name: (*name).into(), + description: format!("Description for {name}"), + group: group.map(str::to_owned), + }) + .collect(), + } + } + + fn draw_switcher(app: &mut SolveApp, ctx: &egui::Context, width: f32) { + crate::scenario::clear_handles(); + let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(width, 700.0)); + let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + ui.allocate_ui(vec2(width - 16.0, 600.0), |ui| { + ui_kit::scope(ui, |ui| switcher(app, ui)); + }); + }); + } + + #[test] + fn config_options_share_one_row_when_they_fit_and_wrap_without_legacy_duplicates() { + assert_eq!(compact_text("Énergie très élevée", 7), "Énergie…"); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + // Make legacy provider/model pickers eligible so their absence is meaningful. + app.agent_chat.state = Some(State::Ready); + app.agent_chat.modes = vec![("legacy".into(), "Legacy mode".into())]; + app.agent_chat.models = vec![ + acp::ModelInfo { id: "old".into(), name: "North · Old model".into(), description: String::new() }, + acp::ModelInfo { id: "other".into(), name: "South · Other model".into(), description: String::new() }, + ]; + assert!(models_shown(&app)); + assert_eq!(model_providers(&app).len(), 2); + app.agent_chat.config_options = Some(vec![ + option( + "engine", + "model", + &[("fast", "Énergie très élevée pour une conception détaillée", Some("Standard")), ("large", "Large", Some("Advanced"))], + ), + option("thought", "thought_level", &[("low", "Max", None), ("high", "High", None)]), + option("workflow", "mode", &[("plan", "Build", None)]), + ]); + let ctx = crate::fonts::test_context(); + draw_switcher(&mut app, &ctx, 760.0); + let at = |name| crate::scenario::handle_at(name).expect("config picker handle"); + let agent = at("agent_chat:switcher"); + let model = at("agent_chat:config:engine"); + let effort = at("agent_chat:config:thought"); + let mode = at("agent_chat:config:workflow"); + assert!(agent.y < model.y && (model.y - effort.y).abs() < 2.0 && (effort.y - mode.y).abs() < 2.0); + assert!(model.x < effort.x && effort.x < mode.x && mode.x < 760.0); + assert_eq!(at("agent_chat:model"), model); + assert_eq!(at("agent_chat:mode"), mode); + assert_eq!(crate::scenario::handles("agent_chat:mode").iter().filter(|(name, _)| name == "agent_chat:mode").count(), 1); + assert_eq!(crate::scenario::handles("agent_chat:model").iter().filter(|(name, _)| name == "agent_chat:model").count(), 1); + assert!(crate::scenario::handle_at("agent_chat:provider").is_none()); + assert!(crate::scenario::handle_at("agent_chat:model:old").is_none()); + assert!(crate::scenario::handle_at("agent_chat:model:other").is_none()); + + draw_switcher(&mut app, &ctx, 280.0); + let model = at("agent_chat:config:engine"); + let effort = at("agent_chat:config:thought"); + let mode = at("agent_chat:config:workflow"); + assert!(model.y < effort.y && (effort.y - mode.y).abs() < 2.0, "only the long model needs its own line: {model:?}, {effort:?}, {mode:?}"); + for id in ["engine", "thought", "workflow"] { + let rect = crate::scenario::rect_of(&format!("agent_chat:config:{id}")).expect("config control bounds"); + assert!(rect.left() >= 0.0 && rect.right() <= 280.0, "{id} exceeds the narrow panel: {rect:?}"); + } + + app.agent_chat.config_options = Some(vec![option("engine", "model", &[("fast", "Fast", None)])]); + app.agent_chat.config_pending = true; + draw_switcher(&mut app, &ctx, 280.0); + assert!(crate::scenario::handle_at("agent_chat:config:engine").is_some()); + assert!(crate::scenario::handle_at("agent_chat:config:thought").is_none()); + assert!(crate::scenario::handle_at("agent_chat:config:workflow").is_none()); + assert!(crate::scenario::handle_at("agent_chat:switcher").is_some()); + + app.agent_chat.config_options = Some(vec![]); + draw_switcher(&mut app, &ctx, 280.0); + assert!(crate::scenario::handle_at("agent_chat:switcher").is_some()); + assert!(crate::scenario::handle_at("agent_chat:config:engine").is_none()); + assert!(crate::scenario::handle_at("agent_chat:mode").is_none()); + assert!(crate::scenario::handle_at("agent_chat:provider").is_none()); + assert!(crate::scenario::handle_at("agent_chat:model").is_none()); + } +} + +/// What is drawn under the agent switcher keeps the switcher's side margin (#10172): it starts +/// where the switcher's fields start, not at the panel's edge. +#[cfg(not(target_arch = "wasm32"))] +fn inset(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(Tokens::get().space_12 as i8, 0)).show(ui, add).inner +} + /// Before the first connection: what's installed, how to install the rest, and Add agent. #[cfg(not(target_arch = "wasm32"))] fn picker(app: &mut SolveApp, ui: &mut egui::Ui) { @@ -1229,6 +1535,12 @@ fn picker(app: &mut SolveApp, ui: &mut egui::Ui) { if !open { return; } + inset(ui, |ui| agent_list(app, ui)); +} + +/// [`picker`]'s content: the agents found, Refresh and Add agent, and what isn't installed. +#[cfg(not(target_arch = "wasm32"))] +fn agent_list(app: &mut SolveApp, ui: &mut egui::Ui) { let all = agents::entries(app); let current = agents::current(app); ui.horizontal(|ui| { @@ -1248,7 +1560,7 @@ fn picker(app: &mut SolveApp, ui: &mut egui::Ui) { } for e in &all { let selected = current.as_ref().is_some_and(|c| c.id == e.id); - let resp = ui_kit::list_picker(ui, &e.id, &e.name, selected).on_hover_text(format!("{} {}", e.detail(), e.login)); + let resp = ui_kit::list_picker(ui, &e.id, &e.name, selected).backing_on_hover_text(format!("{} {}", e.detail(), e.login)); crate::scenario::publish_handle(&format!("agent_chat:pick:{}", e.id), resp.rect.center()); if resp.clicked() { app.agent_chat.agent_id = Some(e.id.clone()); @@ -1267,7 +1579,7 @@ fn picker(app: &mut SolveApp, ui: &mut egui::Ui) { for m in missing { ui.horizontal(|ui| { ui_kit::text(ui, m.name, ui_kit::Text::Inline); - if ui_kit::button(ui, tr("ui.agent_chat_copy"), ui_kit::Button::Small).on_hover_text(m.install).clicked() { + if ui_kit::button(ui, tr("ui.agent_chat_copy"), ui_kit::Button::Small).backing_on_hover_text(m.install).clicked() { ui.ctx().copy_text(m.install.to_string()); } }); @@ -1325,6 +1637,83 @@ fn auth_box(app: &mut SolveApp, ui: &mut egui::Ui) { }); } +/// The visible **Copy message** button of one transcript message (#10675): copies the whole +/// message — the prompt as entered, or the assistant's original Markdown — and nothing else. +/// A streaming reply copies the stable text received so far, which is what `text` holds. +#[cfg(not(target_arch = "wasm32"))] +fn copy_message_button(ui: &mut egui::Ui, n: usize, text: &str) { + let b = ui_kit::button(ui, tr("ui.agent_chat_copy_message"), ui_kit::Button::Small); + crate::scenario::publish_handle(&format!("agent_chat:copy:{n}"), b.rect.center()); + if b.clicked() { + ui.ctx().copy_text(text.to_owned()); + } +} + +/// The right-click menu of one transcript message (#10675): the same single action as the +/// visible button, on the whole message area, beside the composer's own text menu. +/// The area stays hover-only so partial text selection keeps working, so the menu opens on a +/// right-click released over it rather than on a click the response itself would report. +#[cfg(not(target_arch = "wasm32"))] +fn copy_message_menu(ui: &egui::Ui, response: &egui::Response, n: usize, text: &str) { + crate::scenario::publish_rect(&format!("agent_chat:msg:{n}"), response.rect); + let opened = ui + .input(|i| i.pointer.button_released(egui::PointerButton::Secondary) && i.pointer.interact_pos().is_some_and(|p| response.rect.contains(p))); + let mut copy = false; + Container::new(ui.ctx(), Surface::Popup) + .menu(response) + .at_pointer_fixed() + .frame(ui_kit::Menu::frame()) + .open_memory(if opened { Some(egui::SetOpenCommand::Bool(true)) } else { None }) + .show(|ui| { + ui_kit::Menu::show(ui, crate::context_menu::LIST_W, |ui| { + let item = ui_kit::MenuItem::new("copy_message", tr("ui.agent_chat_copy_message"), "copy"); + let row = item.show(ui); + crate::scenario::publish_handle(&format!("agent_chat:copy_menu:{n}"), row.rect.center()); + if row.clicked() { + copy = true; + ui.close(); + } + }); + }); + if copy { + ui.ctx().copy_text(text.to_owned()); + } +} + +/// A text selection dragged near or past the top or bottom of the conversation scrolls it, faster +/// the further out, so a long answer can be selected in one drag (#11527). Only a drag towards +/// that edge does: a click, a double click or a held press on a line by the edge, or a drag from +/// there into the conversation, scrolls nothing. `ui`: the conversation's scroll area, once its +/// content is drawn. +#[cfg(not(target_arch = "wasm32"))] +fn scroll_while_selecting(ui: &egui::Ui) { + // Scrolling starts this far inside the edge, and goes this many points a second for each + // point further out, up to four times as far out; once the pointer has moved more than + // `TOWARDS` that way since the press. + const EDGE: f32 = 32.0; + const SPEED: f32 = 16.0; + const TOWARDS: f32 = 8.0; + let view = ui.clip_rect(); + let pointer = ui.input(|i| i.pointer.press_origin().filter(|p| i.pointer.primary_down() && view.contains(*p)).zip(i.pointer.latest_pos())); + let Some((from, at)) = pointer else { + return; + }; + if !ui.ctx().plugin::().lock().has_selection() { + return; + } + let content = ui.min_rect(); + let out = if at.y < view.top() + EDGE && from.y - at.y > TOWARDS && content.top() < view.top() - 0.5 { + at.y - (view.top() + EDGE) + } else if at.y > view.bottom() - EDGE && at.y - from.y > TOWARDS && content.bottom() > view.bottom() + 0.5 { + at.y - (view.bottom() - EDGE) + } else { + return; + }; + let step = out.clamp(-4.0 * EDGE, 4.0 * EDGE) * SPEED * ui.input(|i| i.stable_dt).min(0.1); + // A positive delta moves the content down, showing what is above. + ui.scroll_with_delta_animation(vec2(0.0, -step), egui::style::ScrollAnimation::none()); +} + #[cfg(not(target_arch = "wasm32"))] fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -1338,9 +1727,12 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { for (n, item) in app.agent_chat.items.iter().enumerate() { match item { Item::User { text, image, pictures, context, files } => { + // A picture-only prompt has no text to copy: no action rather than an empty copy (#10675). + let copyable = !text.is_empty(); + let before = ui.cursor(); ui_kit::assistant_bubble(ui, |ui| { if !text.is_empty() { - ui.add(egui::Label::new(RichText::new(text).color(t.text)).selectable(true).wrap()); + super::markdown_view::selectable(ui, egui::Label::new(RichText::new(text).color(t.text)).wrap()); } if !pictures.is_empty() { if let Some(at) = picture_strip(ui, n, pictures) { @@ -1352,13 +1744,28 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { } context_chips(ui, context, false); files_line(ui, files.iter().map(String::as_str)); + if copyable { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| copy_message_button(ui, n, text)); + } }); + if copyable { + let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y); + let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover()); + copy_message_menu(ui, &resp, n, text); + } } Item::Agent { thought, text } => { if *thought { - ui.add(egui::Label::new(RichText::new(text).italics().color(t.text_dim)).selectable(true).wrap()); + super::markdown_view::selectable(ui, egui::Label::new(RichText::new(text).italics().color(t.text_dim)).wrap()); } else { + let before = ui.cursor(); ui_kit::assistant_prose(ui, |ui| super::markdown_view::show(ui, n, text)); + if !text.is_empty() { + copy_message_button(ui, n, text); + let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y); + let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover()); + copy_message_menu(ui, &resp, n, text); + } } } Item::Tool { .. } => { @@ -1430,7 +1837,7 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { Item::Approval { id, title, tool, answer: given } => { ui_kit::assistant_approval(ui, tr("ui.agent_chat_approval"), |ui| { ui_kit::assistant_tool_detail(ui, |ui| { - ui.add(egui::Label::new(RichText::new(title).monospace().size(t.font_caption)).selectable(true).wrap()); + super::markdown_view::selectable(ui, egui::Label::new(RichText::new(title).monospace().size(t.font_caption)).wrap()); }); match given { Some(true) => { @@ -1443,7 +1850,7 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::assistant_actions(ui, |ui| { let allow = ui_kit::primary_button(ui, tr("ui.agent_chat_allow_once")); let always = ui_kit::button(ui, tr("ui.ai_always_allow"), ui_kit::Button::Normal) - .on_hover_text(trf("ui.ai_always_allow_tip", &[("tool", tool)])); + .backing_on_hover_text(trf("ui.ai_always_allow_tip", &[("tool", tool)])); let deny = ui .with_layout(Layout::left_to_right(Align::Center), |ui| { ui_kit::button(ui, tr("ui.agent_chat_deny"), ui_kit::Button::Normal) @@ -1473,7 +1880,8 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { if *undone { ui.label(RichText::new(tr("ui.agent_chat_undone")).color(t.text_dim).size(crate::theme::Tokens::get().font_caption)); } else if Arc::ptr_eq(doc, ¤t_doc) { - let b = ui_kit::button(ui, tr("ui.agent_chat_undo_changes"), ui_kit::Button::Normal).on_hover_text(tr("ui.ai_undo_tip")); + let b = + ui_kit::button(ui, tr("ui.agent_chat_undo_changes"), ui_kit::Button::Normal).backing_on_hover_text(tr("ui.ai_undo_tip")); crate::scenario::publish_handle("agent_chat:undo", b.rect.center()); if b.clicked() { undo = Some(n); @@ -1498,61 +1906,62 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { let mut edit_buf = editing.as_ref().map(|(_, b)| b.clone()); for (n, p) in app.agent_chat.pending.iter().enumerate() { ui.add_space(6.0); - Container::new(ui.ctx(), Surface::Panel) + let frame = Container::new(ui.ctx(), Surface::Panel) .edge_frame(t.panel) .stroke(Stroke::new(1.0, t.accent)) .corner_radius(t.control_radius) - .inner_margin(egui::Margin::same(6)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - let tag = if stopped && !busy { "ui.agent_chat_queued_stopped" } else { "ui.agent_chat_queued" }; - ui.label(RichText::new(tr(tag)).color(t.accent).semibold().size(crate::theme::Tokens::get().font_small)); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let x = ui_kit::button(ui, "×", ui_kit::Button::Small).on_hover_text(tr("ui.agent_chat_remove")); - crate::scenario::publish_handle(&format!("agent_chat:pending_remove:{n}"), x.rect.center()); - if x.clicked() { - remove = Some(n); + .inner_margin(egui::Margin::same(6)); + Container::show_backing(ui, frame, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + let tag = if stopped && !busy { "ui.agent_chat_queued_stopped" } else { "ui.agent_chat_queued" }; + ui.label(RichText::new(tr(tag)).color(t.accent).semibold().size(crate::theme::Tokens::get().font_small)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let x = ui_kit::button(ui, "×", ui_kit::Button::Small).backing_on_hover_text(tr("ui.agent_chat_remove")); + crate::scenario::publish_handle(&format!("agent_chat:pending_remove:{n}"), x.rect.center()); + if x.clicked() { + remove = Some(n); + } + if editing.as_ref().is_none_or(|(i, _)| *i != n) { + let e = ui_kit::button(ui, tr("ui.agent_chat_edit"), ui_kit::Button::Small); + crate::scenario::publish_handle(&format!("agent_chat:pending_edit:{n}"), e.rect.center()); + if e.clicked() { + start_edit = Some((n, p.text.clone())); } - if editing.as_ref().is_none_or(|(i, _)| *i != n) { - let e = ui_kit::button(ui, tr("ui.agent_chat_edit"), ui_kit::Button::Small); - crate::scenario::publish_handle(&format!("agent_chat:pending_edit:{n}"), e.rect.center()); - if e.clicked() { - start_edit = Some((n, p.text.clone())); - } + } + }); + }); + match (&editing, edit_buf.as_mut()) { + (Some((i, _)), Some(buf)) if *i == n => { + let te = ui_kit::message_field(ui, Id::new(("sc_agent_pending_input", n)), buf, ""); + crate::scenario::publish_rect("agent_chat:pending_input", te.rect); + ui.horizontal(|ui| { + if ui_kit::button(ui, tr("ui.agent_chat_save"), ui_kit::Button::Normal).clicked() { + edit_done = Some((n, Some(buf.clone()))); + } + if ui_kit::button(ui, tr("ui.agent_chat_cancel"), ui_kit::Button::Normal).clicked() { + edit_done = Some((n, None)); } }); - }); - match (&editing, edit_buf.as_mut()) { - (Some((i, _)), Some(buf)) if *i == n => { - let te = ui_kit::message_field(ui, Id::new(("sc_agent_pending_input", n)), buf, ""); - crate::scenario::publish_rect("agent_chat:pending_input", te.rect); - ui.horizontal(|ui| { - if ui_kit::button(ui, tr("ui.agent_chat_save"), ui_kit::Button::Normal).clicked() { - edit_done = Some((n, Some(buf.clone()))); - } - if ui_kit::button(ui, tr("ui.agent_chat_cancel"), ui_kit::Button::Normal).clicked() { - edit_done = Some((n, None)); - } - }); - } - _ => { - if !p.text.is_empty() { - ui.add(egui::Label::new(RichText::new(&p.text).color(t.text)).selectable(true).wrap()); - } - if p.image { - ui.label(RichText::new(tr("ui.agent_chat_view_attached")).color(t.text_dim).size(crate::theme::Tokens::get().font_small)); - } - context_chips(ui, &p.context, false); - files_line(ui, p.files.iter().map(|f| f.name.as_str())); - } } - }); + _ => { + if !p.text.is_empty() { + super::markdown_view::selectable(ui, egui::Label::new(RichText::new(&p.text).color(t.text)).wrap()); + } + if p.image { + ui.label(RichText::new(tr("ui.agent_chat_view_attached")).color(t.text_dim).size(crate::theme::Tokens::get().font_small)); + } + context_chips(ui, &p.context, false); + files_line(ui, p.files.iter().map(|f| f.name.as_str())); + } + } + }); } if !app.agent_chat.pending.is_empty() && editing.is_none() { ui.horizontal(|ui| { if busy { - let b = ui_kit::button(ui, tr("ui.agent_chat_send_now"), ui_kit::Button::Normal).on_hover_text(tr("ui.agent_chat_send_now_tip")); + let b = + ui_kit::button(ui, tr("ui.agent_chat_send_now"), ui_kit::Button::Normal).backing_on_hover_text(tr("ui.agent_chat_send_now_tip")); crate::scenario::publish_handle("agent_chat:send_now", b.rect.center()); send_now_clicked = b.clicked(); } else { @@ -1571,7 +1980,7 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { if agents::entries(app).is_empty() && app.agent_chat.detecting.is_none() { ui_kit::assistant_empty(ui, tr("ui.agent_chat_setup_title"), tr("ui.agent_chat_setup_body"), |ui| { if ui_kit::primary_button(ui, tr("ui.agent_chat_open_settings")).clicked() { - crate::prefs::open_at(app, crate::prefs::PAGE_AI); + crate::prefs::open_at(app, crate::prefs::PAGE_ASSISTANT); } }); } else { @@ -1685,34 +2094,38 @@ pub(super) fn remove_tip(f: &attach::Attachment) -> &'static str { fn loading_chip(ui: &mut egui::Ui, name: &str, importing: bool, i: usize, w: f32) -> bool { let t = Tokens::get(); let mut clicked = false; - let r = egui::Frame::NONE - .fill(t.toolbar) - .stroke(t.control_border_stroke(t.border)) - .corner_radius(t.control_radius) - .inner_margin(egui::Margin::symmetric(4, 3)) - .show(ui, |ui| { + let r = crate::ui_kit::Container::show_backing( + ui, + egui::Frame::NONE + .fill(t.toolbar) + .stroke(t.control_border_stroke(t.border)) + .corner_radius(t.control_radius) + .inner_margin(egui::Margin::symmetric(4, 3)), + |ui| { let inner = (w - 10.0).max(40.0); ui.set_width(inner); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; let doing = tr(if importing { "ui.agent_chat_file_importing" } else { "ui.agent_chat_file_loading" }); - let mark = ui.add(egui::Spinner::new().size(t.form_icon_size)).on_hover_text(doing).rect.width(); + let mark = ui.add(egui::Spinner::new().size(t.form_icon_size)).backing_on_hover_text(doing).rect.width(); let name_w = (inner - mark - 18.0 - 8.0).max(8.0); ui.allocate_ui(vec2(name_w, 20.0), |ui| { ui.set_width(name_w); ui.add(egui::Label::new(RichText::new(name).size(t.font_small).color(t.text_dim)).truncate()) }) .inner - .on_hover_text(name); + .backing_on_hover_text(name); let (r, x) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click()); let c = r.center(); let s = Stroke::new(1.3, if x.hovered() { t.text } else { t.text_dim }); ui.painter().line_segment([c + vec2(-3.5, -3.5), c + vec2(3.5, 3.5)], s); ui.painter().line_segment([c + vec2(-3.5, 3.5), c + vec2(3.5, -3.5)], s); crate::scenario::publish_handle(&format!("agent_chat:file_loading_remove:{i}"), c); - clicked = x.on_hover_text(tr(if importing { "ui.agent_chat_remove_imported" } else { "ui.agent_chat_remove_file" })).clicked(); + clicked = + x.backing_on_hover_text(tr(if importing { "ui.agent_chat_remove_imported" } else { "ui.agent_chat_remove_file" })).clicked(); }); - }); + }, + ); crate::scenario::publish_handle(&format!("agent_chat:file_loading:{i}"), r.response.rect.center()); clicked } @@ -1722,12 +2135,14 @@ fn loading_chip(ui: &mut egui::Ui, name: &str, importing: bool, i: usize, w: f32 fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap, f: &attach::Attachment, i: usize, w: f32) -> bool { let t = Tokens::get(); let mut clicked = false; - let r = egui::Frame::NONE - .fill(t.toolbar) - .stroke(t.control_border_stroke(t.border)) - .corner_radius(t.control_radius) - .inner_margin(egui::Margin::symmetric(4, 3)) - .show(ui, |ui| { + let r = crate::ui_kit::Container::show_backing( + ui, + egui::Frame::NONE + .fill(t.toolbar) + .stroke(t.control_border_stroke(t.border)) + .corner_radius(t.control_radius) + .inner_margin(egui::Margin::symmetric(4, 3)), + |ui| { let inner = (w - 10.0).max(40.0); ui.set_width(inner); ui.horizontal(|ui| { @@ -1761,16 +2176,17 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap RichText::new(words).size(t.font_caption).color(t.text), None => RichText::new(summary::plain_title(call.title)).monospace().size(t.font_caption).color(t.text), }; - ui.add(egui::Label::new(text).truncate().selectable(false)).on_hover_text(call.title); + ui.add(egui::Label::new(text).truncate().selectable(false)).backing_on_hover_text(call.title); }); }); }); @@ -1873,7 +2289,7 @@ fn tool_card(ui: &mut egui::Ui, n: usize, call: &ToolCall) { state_.toggle(ui); } if details { - click.on_hover_text(tr("ui.ai_tool_unfold")); + click.backing_on_hover_text(tr("ui.ai_tool_unfold")); } state_.show_body_unindented(ui, |ui| { ui.indent(id.with("detail"), |ui| { @@ -2112,7 +2528,7 @@ mod tests { ui_kit::scope(ui, |ui| switcher(&mut app, ui)); }); output.textures_delta.clear(); - let rects: Vec<_> = ["switcher", "mode", "provider", "model"] + let rects: Vec<_> = ["switcher", "mode", "model"] .into_iter() .map(|name| { let rect = crate::scenario::rect_of(&format!("agent_chat:{name}")).expect("picker retained"); diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs index 86b78a01e..0ddbdda92 100644 --- a/crates/ui-egui/src/agent_chat/settings.rs +++ b/crates/ui-egui/src/agent_chat/settings.rs @@ -7,6 +7,7 @@ use super::agents::{self, AgentConfig, Kind, Mode, Protocol}; use super::backend::TestError; use super::*; use crate::ui_kit; +use crate::ui_kit::BackingTooltipExt as _; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum AddKind { @@ -30,8 +31,18 @@ pub struct AddState { pub key: String, /// Seconds one model request may take. pub request_timeout_s: u64, + /// Optional reasoning effort sent as `reasoning_effort`; empty sends nothing. + pub reasoning_effort: String, pub error: Option, + /// Editing this added agent (its id) instead of adding a new one. + pub editing: Option, + /// Editing an endpoint whose key is in the keychain: an empty key field keeps it. + pub saved_key: bool, test: Option, + /// The endpoint the model picker lists: what the fields said when they were last left. + listing: Option, + /// The fields were left, or the picker opened: take what they say now. + list_again: bool, } /// A connection test running or done. @@ -74,6 +85,147 @@ pub struct State { capabilities: std::collections::HashMap<(String, String), Option>, #[cfg(not(target_arch = "wasm32"))] checking: Option, + /// Endpoints' models as they were last listed here, or why they could not be. + endpoint_models: std::collections::HashMap, String>>, + #[cfg(not(target_arch = "wasm32"))] + listing: Option, + /// An agent card's picker asked for this listing (with the agent whose key goes along). + #[cfg(not(target_arch = "wasm32"))] + card_listing: Option<(ListingKey, String)>, +} + +/// What an endpoint's models are listed by: its protocol, its base URL, and whether a key goes along. +type ListingKey = (Protocol, String, bool); + +/// Most endpoints' listings kept. +const ENDPOINT_LISTINGS_CAP: usize = 128; + +/// The listing of `base_url`, if that is an address. A key goes along only where it may be sent. +fn listing_key(protocol: Protocol, base_url: &str, with_key: bool) -> Option { + let url = agents::normalize_url(base_url).ok().filter(|url| url.len() <= 4096)?; + let with_key = with_key && agents::key_safe_for(&url); + Some((protocol, url, with_key)) +} + +/// The models listed for `key`, and the note for under them: still listing, or why it could not. +fn listed_for<'a>( + listings: &'a std::collections::HashMap, String>>, + key: Option<&ListingKey>, +) -> (&'a [acp::ModelInfo], Option) { + match key.and_then(|key| listings.get(key)) { + Some(Ok(models)) if models.is_empty() => (&[], Some(tr("ui.agent_chat_models_none").to_string())), + Some(Ok(models)) => (models, None), + Some(Err(error)) => (&[], Some(trf("ui.agent_chat_models_failed", &[("error", error)]))), + None => (&[], key.map(|_| tr("ui.agent_chat_models_listing").to_string())), + } +} + +/// Whether a listing is worth asking for again: it failed, or it listed nothing. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn listing_wants_retry(listing: Option<&Result, String>>) -> bool { + match listing { + Some(Err(_)) => true, + Some(Ok(models)) => models.is_empty(), + None => false, + } +} + +/// `models` as a model picker's rows: the id chooses, the endpoint's name for it is searched too. +fn model_choices<'a>(models: &'a [acp::ModelInfo], rows: &'a [(String, Option, String)]) -> Vec> { + models.iter().zip(rows).map(|(m, (label, group, tip))| ui_kit::SearchChoice { value: &m.id, label, tip, group: group.as_deref() }).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +struct ModelListing { + key: ListingKey, + rx: std::sync::mpsc::Receiver, String>>, +} + +/// List an endpoint's models in the background, one listing at a time; a finished one stays until +/// it is asked for again. `secret` runs on that thread too: a keychain may take its time to answer. +#[cfg(not(target_arch = "wasm32"))] +fn start_listing(app: &mut SolveApp, ctx: &egui::Context, key: ListingKey, secret: impl FnOnce() -> Result, String> + Send + 'static) { + let state = &mut app.agent_chat.settings; + if state.listing.is_some() || state.endpoint_models.contains_key(&key) { + return; + } + if state.endpoint_models.len() >= ENDPOINT_LISTINGS_CAP { + state.endpoint_models.clear(); + } + let Some(http) = app.services.agent_http.clone() else { + state.endpoint_models.insert(key, Err(tr("ui.ai_no_http").to_string())); + return; + }; + let (tx, rx) = std::sync::mpsc::channel(); + let (protocol, url) = (key.0, key.1.clone()); + let language = crate::i18n::language(); + let wake = ctx.clone(); + let spawned = std::thread::Builder::new().name("endpoint-models".into()).spawn(move || { + let _language = crate::i18n::scope(language); + let list = secret().and_then(|secret| match protocol { + Protocol::OpenAi => super::api_client::model_list(&http, &url, secret.as_deref()), + Protocol::Anthropic => super::api_client::anthropic_model_list(&http, &url, secret.as_deref()), + }); + let _ = tx.send(list); + wake.request_repaint(); + }); + match spawned { + Ok(_) => state.listing = Some(ModelListing { key, rx }), + Err(e) => { + state.endpoint_models.insert(key, Err(e.to_string())); + } + } +} + +/// Take in a finished listing, and start the one an agent card asked for. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn poll_listing(app: &mut SolveApp, ctx: &egui::Context) { + use std::sync::mpsc::TryRecvError; + let state = &mut app.agent_chat.settings; + if let Some(listing) = &state.listing { + let result = match listing.rx.try_recv() { + Ok(result) => result, + Err(TryRecvError::Disconnected) => Err(tr("ui.ai_no_answer").to_string()), + Err(TryRecvError::Empty) => return, + }; + state.endpoint_models.insert(listing.key.clone(), result); + state.listing = None; + } + let Some((key, agent)) = state.card_listing.take() else { return }; + let secrets = app.services.secrets.clone().filter(|_| key.2); + start_listing(app, ctx, key, move || match secrets { + Some(secrets) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + None => Ok(None), + }); +} + +/// The Add dialog's listing, of what its fields said when last left, never of a half-typed address. +#[cfg(not(target_arch = "wasm32"))] +fn list_for_dialog(app: &mut SolveApp, ctx: &egui::Context) { + let state = &mut app.agent_chat.settings; + let Some(s) = state.add.as_mut().filter(|s| s.kind == AddKind::Api) else { return }; + let typed = Some(s.key.trim().to_string()).filter(|typed| !typed.is_empty()); + // Editing an agent whose key is kept: the listing goes with that key, read on its thread. + let stored = s.editing.clone().filter(|_| s.saved_key && typed.is_none()); + if std::mem::take(&mut s.list_again) { + s.listing = listing_key(s.protocol, &s.base_url, typed.is_some() || stored.is_some()); + // Asked again: what failed may work now, with another key or the server back up. + if let Some(key) = &s.listing + && listing_wants_retry(state.endpoint_models.get(key)) + { + state.endpoint_models.remove(key); + } + } + let Some(key) = s.listing.clone() else { return }; + if state.listing.is_some() || state.endpoint_models.contains_key(&key) { + return; + } + let typed = typed.filter(|_| key.2); + let stored = stored.filter(|_| key.2).and_then(|agent| app.services.secrets.clone().map(|secrets| (secrets, agent))); + start_listing(app, ctx, key, move || match stored { + Some((secrets, agent)) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + None => Ok(typed), + }); } #[cfg(not(target_arch = "wasm32"))] @@ -165,10 +317,47 @@ pub fn open_add(app: &mut SolveApp) { base_url: preset.map(|p| p.base_url.to_string()).unwrap_or_default(), name: preset.map(|p| p.name.to_string()).unwrap_or_default(), request_timeout_s: agents::DEFAULT_REQUEST_TIMEOUT_S, + list_again: true, ..Default::default() }); } +/// Open the agent dialog on an agent you added, filled with what it holds. The key is never read +/// back: its field stays empty, and saving with it empty keeps the stored key. Returns false when +/// `id` is not an added agent (found agents have nothing of yours to edit). +pub fn open_edit(app: &mut SolveApp, id: &str) -> bool { + let Some(c) = app.preferences.agents.iter().find(|c| c.id == id) else { return false }; + let mut s = AddState { + name: c.name.clone(), + request_timeout_s: c.request_timeout_s.clamp(agents::MIN_REQUEST_TIMEOUT_S, agents::MAX_REQUEST_TIMEOUT_S), + reasoning_effort: c.reasoning_effort.clone(), + editing: Some(c.id.clone()), + list_again: true, + ..Default::default() + }; + if c.kind.is_api() { + let protocol = if c.kind == Kind::Anthropic { Protocol::Anthropic } else { Protocol::OpenAi }; + let presets = agents::presets(protocol); + // The Ollama preset stays chosen even if its URL was changed, as `ollama` records. + let preset = if protocol == Protocol::OpenAi && c.ollama { + Some(0) + } else { + presets.iter().position(|p| agents::normalize_url(p.base_url).ok().as_deref() == Some(c.base_url.as_str())) + }; + s.kind = AddKind::Api; + s.protocol = protocol; + s.preset = preset.unwrap_or(presets.len()); + s.base_url = c.base_url.clone(); + s.model = c.model.clone(); + s.saved_key = c.key; + } else { + s.kind = AddKind::Custom; + s.command = c.command.clone(); + } + app.agent_chat.settings.add = Some(s); + true +} + /// Take `index` from the protocol's presets, or make the URL empty for a custom endpoint. pub(super) fn choose_preset(s: &mut AddState, protocol: Protocol, index: usize) { s.protocol = protocol; @@ -181,6 +370,7 @@ pub(super) fn choose_preset(s: &mut AddState, protocol: Protocol, index: usize) } s.error = None; s.test = None; + s.list_again = true; } /// Run a connection test in the background (it starts the agent briefly, or asks the endpoint @@ -215,12 +405,26 @@ fn start_test(app: &SolveApp, e: &agents::Entry, key: Option) -> Test { /// An endpoint's request timeout field: seconds, 30 s to an hour. fn timeout_field(ui: &mut egui::Ui, secs: &mut u64, handle: &str) -> bool { - let r = ui_kit::number_field(ui, secs, agents::MIN_REQUEST_TIMEOUT_S..=agents::MAX_REQUEST_TIMEOUT_S, 5.0, " s") - .on_hover_text(tr("ui.ai_request_timeout_hint")); + let r = ui_kit::number_field(ui, secs, agents::MIN_REQUEST_TIMEOUT_S..=agents::MAX_REQUEST_TIMEOUT_S, 5.0, "") + .backing_on_hover_text(tr("ui.ai_request_timeout_hint")); + r.widget_info(|| { + let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), *secs as f64); + info.label = Some(tr("prefs.assistant_seconds_aria").to_owned()); + info + }); + ui.label(tr("prefs.assistant_seconds")); crate::scenario::publish_target(handle, r.rect); r.changed() } +/// The free-text reasoning effort field with its hover hint; true when the text changed. +fn effort_field(ui: &mut egui::Ui, effort: &mut String, handle: &str) -> bool { + let response = ui_kit::cell_editor(ui, ui.id().with("ai_reasoning_effort"), effort, tr("ui.ai_reasoning_effort_field_hint"), false) + .backing_on_hover_text(tr("ui.ai_reasoning_effort_hint")); + crate::scenario::publish_target(handle, response.rect); + response.changed() +} + fn test_line(ui: &mut egui::Ui, test: &Option<&Test>) { match test { Some(Test::Running(_)) => { @@ -239,73 +443,84 @@ fn test_line(ui: &mut egui::Ui, test: &Option<&Test>) { /// The Assistant page of Settings. Copy stays close to its control; full security details /// remain accessible on hover, and high-risk permissions always retain a visible warning. pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { - ui_kit::settings_heading(ui, tr("prefs.assistant"), tr("ai.prefs.intro")); - ui_kit::settings_section(ui, "assistant_availability", tr("ai.prefs.availability"), |ui| { - let response = - ui_kit::checkbox(ui, tr("ui.ai_show_features"), &mut app.preferences.ai_features).on_hover_text(tr("ui.ai_show_features_note")); - crate::scenario::publish_handle("prefs:ai_features", response.rect.center()); - if !cfg!(target_arch = "wasm32") { - if app.preferences.ai_features { + ui_kit::settings_page(ui, |ui| { + ui_kit::settings_heading(ui, tr("prefs.assistant"), tr("ai.prefs.intro")); + ui_kit::settings_section(ui, "assistant_availability", tr("ai.prefs.availability"), |ui| { + ui.horizontal(|ui| { + let response = ui_kit::checkbox(ui, tr("ui.ai_show_features"), &mut app.preferences.ai_features) + .backing_on_hover_text(tr("ui.ai_show_features_note")); + crate::scenario::publish_handle("prefs:ai_features", response.rect.center()); + ui_kit::help_icon(ui, tr("ui.ai_show_features_note")); + }); + ui.add_enabled_ui(app.preferences.ai_features && !cfg!(target_arch = "wasm32"), |ui| { let response = ui_kit::checkbox(ui, tr("ui.ai_toolbar_button"), &mut app.preferences.ai_toolbar_button) - .on_hover_text(tr("ui.ai_toolbar_button_note")); + .backing_on_hover_text(tr("ui.ai_toolbar_button_note")); crate::scenario::publish_handle("prefs:ai_toolbar_button", response.rect.center()); - let response = ui_kit::checkbox(ui, tr("ai.prefs.connect_at_start"), &mut app.preferences.agent_connect_at_start) - .on_hover_text(tr("ai.prefs.connect_at_start_note")); - crate::scenario::publish_handle("prefs:agent_connect_at_start", response.rect.center()); - let response = ui_kit::checkbox(ui, tr("ai.prefs.open_at_start"), &mut app.preferences.agent_chat_open_at_start) - .on_hover_text(tr("ai.prefs.open_at_start_note")); - crate::scenario::publish_handle("prefs:agent_chat_open_at_start", response.rect.center()); + }); + if cfg!(target_arch = "wasm32") { + ui_kit::text(ui, tr("ui.agent_chat_desktop_only"), ui_kit::Text::Hint("desktop")); } - let response = ui_kit::checkbox(ui, tr("ai.prefs.background_commands"), &mut app.preferences.agent_off_thread) - .on_hover_text(tr("ui.agent_off_thread_note")); - crate::scenario::publish_handle("prefs:agent_off_thread", response.rect.center()); - let response = ui_kit::checkbox(ui, tr("ai.prefs.allow_control"), &mut app.preferences.agent_control) - .on_hover_text(tr("ai.prefs.allow_control_note")); - crate::scenario::publish_handle("prefs:agent_control", response.rect.center()); - let response = ui_kit::checkbox(ui, tr("ai.prefs.connect_apps"), &mut app.preferences.connect_ai_apps) - .on_hover_text(tr("ai.prefs.connect_apps_note")); - crate::scenario::publish_handle("prefs:connect_ai_apps", response.rect.center()); - } - if cfg!(target_arch = "wasm32") { - ui_kit::text(ui, tr("ui.agent_chat_desktop_only"), ui_kit::Text::Hint("desktop")); + }); + ui.add_enabled_ui(app.preferences.ai_features && !cfg!(target_arch = "wasm32"), |ui| { + permissions_section(app, ui); + #[cfg(not(target_arch = "wasm32"))] + { + let browsing = !crate::prefs_search::querying(ui) || app.prefs_window.section == crate::prefs::PAGE_ASSISTANT; + if app.preferences.ai_features && browsing && app.agent_chat.detection.is_none() && app.agent_chat.detecting.is_none() { + refresh(app, &ui.ctx().clone()); + } + agents_section(app, ui); + } + panel_section(app, ui); + connecting_section(app, ui); + }); + ui.add_enabled_ui(app.preferences.ai_features, |ui| pointer_section(app, ui)); + }); +} + +fn connecting_section(app: &mut SolveApp, ui: &mut egui::Ui) { + ui_kit::settings_section(ui, "assistant_connecting", tr("prefs.assistant_connecting"), |ui| { + for (label, help, handle, value) in [ + ("ai.prefs.allow_control", "ai.prefs.allow_control_note", "agent_control", &mut app.preferences.agent_control), + ("ai.prefs.connect_apps", "ai.prefs.connect_apps_note", "connect_ai_apps", &mut app.preferences.connect_ai_apps), + ("ai.prefs.background_commands", "ui.agent_off_thread_note", "agent_off_thread", &mut app.preferences.agent_off_thread), + ("ai.prefs.connect_at_start", "ai.prefs.connect_at_start_note", "agent_connect_at_start", &mut app.preferences.agent_connect_at_start), + ("ai.prefs.open_at_start", "ai.prefs.open_at_start_note", "agent_chat_open_at_start", &mut app.preferences.agent_chat_open_at_start), + ] { + ui.horizontal(|ui| { + let response = ui_kit::checkbox(ui, tr(label), value).backing_on_hover_text(tr(help)); + crate::scenario::publish_handle(&format!("prefs:{handle}"), response.rect.center()); + ui_kit::help_icon(ui, tr(help)); + }); } }); - if !cfg!(target_arch = "wasm32") && app.preferences.ai_features { - #[cfg(not(target_arch = "wasm32"))] - { - let browsing = !crate::prefs_search::querying(ui) || app.prefs_window.section == crate::prefs::PAGE_AI; - if browsing && app.agent_chat.detection.is_none() && app.agent_chat.detecting.is_none() { - refresh(app, &ui.ctx().clone()); - } - agents_section(app, ui); - } - permissions_section(app, ui); - panel_section(app, ui); - } - pointer_section(app, ui); } fn permissions_section(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::settings_section(ui, "permissions", tr("ui.ai_permissions"), |ui| { let mut selected = Mode::ALL.iter().position(|mode| *mode == app.preferences.ai_permissions).unwrap_or(0); + let all_help = format!("{}\n\n{}", tr("prefs.assistant_use_care"), tr("ui.ai_mode_all_note")); let choices = [ ui_kit::SettingsChoice { + icon: None, key: "prefs:ai_mode:ask", title: tr("ai.prefs.permission_ask"), summary: tr("ai.prefs.permission_ask_summary"), detail: tr("ui.ai_mode_ask_note"), }, ui_kit::SettingsChoice { + icon: None, key: "prefs:ai_mode:edits", title: tr("ai.prefs.permission_edits"), summary: tr("ai.prefs.permission_edits_summary"), detail: tr("ui.ai_mode_edits_note"), }, ui_kit::SettingsChoice { + icon: Some("warning"), key: "prefs:ai_mode:all", title: tr("ai.prefs.permission_all"), summary: tr("ai.prefs.permission_all_summary"), - detail: tr("ui.ai_mode_all_note"), + detail: &all_help, }, ]; if ui_kit::settings_choices(ui, &choices, &mut selected) @@ -316,7 +531,7 @@ fn permissions_section(app: &mut SolveApp, ui: &mut egui::Ui) { if app.preferences.ai_permissions == Mode::All { ui_kit::text(ui, tr("ui.ai_mode_all_warning"), ui_kit::Text::Report("permissions_warning", true)); } - ui_kit::text(ui, tr("ai.prefs.permission_scope"), ui_kit::Text::Hint("scope")).on_hover_text(tr("ui.ai_modes_scope")); + ui_kit::text(ui, tr("ui.ai_modes_scope"), ui_kit::Text::Hint("permissions_scope")); let remembered: Vec<_> = app .preferences .agent_always_allow @@ -326,14 +541,17 @@ fn permissions_section(app: &mut SolveApp, ui: &mut egui::Ui) { .collect(); ui_kit::section_count(ui, "always_allowed", tr("ui.ai_always_allowed"), false, Some(remembered.len()), |ui| { if remembered.is_empty() { - ui_kit::text(ui, tr("ai.prefs.no_saved_approvals"), ui_kit::Text::Hint("none")).on_hover_text(tr("ui.ai_always_allowed_none")); + ui_kit::text(ui, tr("ai.prefs.no_saved_approvals"), ui_kit::Text::Hint("none")) + .backing_on_hover_text(tr("ui.ai_always_allowed_none")); } let names: std::collections::HashMap<_, _> = agents::entries(app).into_iter().map(|entry| (entry.id, entry.name)).collect(); for (agent, tools) in remembered { let t = crate::theme::Tokens::get(); ui_kit::settings_block(ui, names.get(&agent).unwrap_or(&agent), t.space_24 * 6.0 + t.space_6, |ui| { ui.horizontal(|ui| { - if ui_kit::button(ui, tr("ui.ai_reset"), ui_kit::Button::Small).clicked() { + let reset = ui_kit::button(ui, tr("ui.ai_reset"), ui_kit::Button::Small); + crate::scenario::publish_target(&format!("prefs:ai_approvals_reset:{agent}"), reset.rect); + if reset.clicked() { app.preferences.agent_always_allow.remove(&agent); } ui_kit::settings_short_note(ui, &tools.join(", ")); @@ -347,7 +565,11 @@ fn permissions_section(app: &mut SolveApp, ui: &mut egui::Ui) { fn panel_section(app: &mut SolveApp, ui: &mut egui::Ui) { let t = crate::theme::Tokens::get(); ui_kit::settings_section(ui, "panel", tr("ui.ai_panel"), |ui| { - ui_kit::settings_form(ui, t.space_24 * 6.0 + t.space_6, |ui| { + let label_width = [tr("ui.agent_chat_side"), tr("ui.agent_chat_turn_limit")] + .iter() + .map(|label| ui_kit::ContentWidth::label(ui, label) + t.space_4) + .fold(0.0, f32::max); + ui_kit::settings_form(ui, label_width, |ui| { ui_kit::row(ui, tr("ui.agent_chat_side"), |ui| { let p = &mut app.preferences; let mut selected = if p.agent_chat_popped { 2 } else { usize::from(p.agent_chat_side != "left") }; @@ -361,16 +583,41 @@ fn panel_section(app: &mut SolveApp, ui: &mut egui::Ui) { }); ui_kit::row(ui, tr("ui.agent_chat_turn_limit"), |ui| { let p = &mut app.preferences; - let mut unlimited = p.agent_chat_turn_limit == 0; - if ui_kit::checkbox(ui, tr("ui.agent_chat_turn_unlimited"), &mut unlimited).changed() { - p.agent_chat_turn_limit = if unlimited { 0 } else { gate::SEEDED_TURN_LIMIT }; + let previous = usize::from(p.agent_chat_turn_limit != 0); + let mut limit = previous; + let options = [tr("ui.agent_chat_turn_unlimited"), tr("prefs.assistant_limited")]; + crate::prefs_search::note_current(ui, &options.join(" ")); + let dropdown_width = ui_kit::ContentWidth::dropdown(ui, &options); + let response = + ui_kit::settings_control_width(ui, dropdown_width, |ui| ui_kit::dropdown(ui, "assistant_turn_limit", &mut limit, &options)); + let query = crate::prefs_search::query(ui); + if let Some(option) = options + .iter() + .find(|option| option.to_lowercase() == query) + .or_else(|| options.iter().find(|option| crate::prefs_search::texts_hit(ui, &[*option]))) + { + crate::prefs_search::remember(ui, option, response.rect); } - if !unlimited { - ui_kit::settings_number(ui, &mut p.agent_chat_turn_limit, 1..=200, 1.0).on_hover_text(tr("ai.prefs.turn_limit_hint")); + for option in options { + crate::prefs_search::follow(ui, option, response.rect); + } + crate::scenario::publish_target("prefs:agent_chat_turn_limit:mode", response.rect); + if limit != previous { + p.agent_chat_turn_limit = if limit == 0 { 0 } else { gate::SEEDED_TURN_LIMIT }; + } + if limit != 0 { + let response = + ui_kit::settings_number(ui, &mut p.agent_chat_turn_limit, 1..=200, 1.0).backing_on_hover_text(tr("ai.prefs.turn_limit_hint")); + response.widget_info(|| { + let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), f64::from(p.agent_chat_turn_limit)); + info.label = Some(tr("prefs.assistant_limit").to_owned()); + info + }); + crate::scenario::publish_target("prefs:agent_chat_turn_limit:value", response.rect); } }); }); - ui_kit::text(ui, tr("ai.prefs.privacy_note"), ui_kit::Text::Hint("privacy")); + ui_kit::text(ui, tr("ai.prefs.privacy_note"), ui_kit::Text::Hint("privacy_note")); }); } @@ -379,15 +626,39 @@ fn pointer_section(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::settings_pair( ui, |ui| { - ui_kit::checkbox(ui, tr("ai.prefs.show_pointer"), &mut app.ui.agent_cursor.show) - .on_hover_text(crate::i18n::tr_label("Show the pointer an AI agent moves (#35)")); + let response = ui_kit::checkbox(ui, tr("ai.prefs.show_pointer"), &mut app.ui.agent_cursor.show) + .backing_on_hover_text(crate::i18n::tr_label("Show the pointer an AI agent moves (#35)")); + crate::scenario::publish_target("prefs:agent_pointer_show", response.rect); ui.add_enabled_ui(app.ui.agent_cursor.show, |ui| { let speed_label_width = ui_kit::ContentWidth::label(ui, tr("ai.prefs.pointer_speed")) + crate::theme::Tokens::get().space_4; - ui_kit::settings_block(ui, tr("ai.prefs.pointer_speed"), speed_label_width, |ui| { - crate::agent_cursor::speed_slider(ui, &mut app.ui.agent_cursor.speed); + ui_kit::settings_form(ui, speed_label_width, |ui| { + ui_kit::row(ui, tr("ai.prefs.pointer_speed"), |ui| { + let name = tr("prefs.assistant_pointer_speed"); + crate::prefs_search::note_current(ui, name); + let response = + ui_kit::named_control(ui, name, |ui| crate::agent_cursor::speed_slider(ui, &mut app.ui.agent_cursor.speed)); + crate::scenario::publish_target("prefs:agent_pointer_speed", response.rect); + let value = match app.ui.agent_cursor.speed { + crate::agent_cursor::Speed::Times(value) => value, + crate::agent_cursor::Speed::Instant => 5.5, + }; + response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), value, name)); + // The visible row owns Speed and its legacy Motion speed alias. The + // native editor's name owns queries that only match Pointer speed. + if !crate::prefs_search::texts_hit(ui, &[tr("ai.prefs.pointer_speed")]) { + crate::prefs_search::remember(ui, name, response.rect); + } + for label in [tr("ai.prefs.pointer_speed"), name] { + crate::prefs_search::follow(ui, label, response.rect); + } + }); + }); + ui.horizontal(|ui| { + let response = ui_kit::checkbox(ui, tr("ai.prefs.follow_camera"), &mut app.ui.agent_cursor.follow_camera) + .backing_on_hover_text(tr("prefs.assistant_follow_help")); + crate::scenario::publish_target("prefs:agent_pointer_follow", response.rect); + ui_kit::help_icon(ui, tr("prefs.assistant_follow_help")); }); - ui_kit::checkbox(ui, tr("ai.prefs.follow_camera"), &mut app.ui.agent_cursor.follow_camera) - .on_hover_text(crate::i18n::tr_label("Follow the camera (Look At sketches)")); }); (app.ui.agent_cursor.show, app.ui.agent_cursor.speed.label(), app.ui.agent_cursor.follow_camera) }, @@ -404,9 +675,12 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { let default = if all.iter().any(|e| &e.id == d) { Some(d.clone()) } else { all.first().map(|e| e.id.clone()) }; let mut remove: Option = None; let mut test: Option = None; + let mut edit: Option = None; let mut retimed: Option<(String, u64)> = None; + let mut reeffort: Option<(String, String)> = None; + let mut picked_model: Option<(String, ui_kit::Picked)> = None; let t = crate::theme::Tokens::get(); - ui_kit::settings_section(ui, "agents", tr("ui.ai_agents"), |ui| { + ui_kit::settings_section_count(ui, "agents", tr("ui.ai_agents"), Some(&all.len().to_string()), |ui| { if app.agent_chat.detecting.is_some() { ui_kit::text(ui, tr("ui.agent_chat_detecting"), ui_kit::Text::Hint("detecting")); } else if all.is_empty() { @@ -416,95 +690,211 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::empty_box(ui, "assistant_agents", tr("ai.prefs.no_agents")); } } - for (index, entry) in all.iter().enumerate() { + for entry in &all { ui.push_id(&entry.id, |ui| { - if index > 0 { - ui_kit::divider(ui, "agent_divider"); - } - ui_kit::settings_block(ui, &entry.name, t.space_24 * 6.0 + t.space_6, |ui| { - ui.horizontal_wrapped(|ui| { - let is_default = default.as_deref() == Some(entry.id.as_str()); - let choice = ui_kit::button( - ui, - tr(if is_default { "ui.ai_default" } else { "ai.prefs.make_default" }), - if is_default { ui_kit::Button::SmallSelected } else { ui_kit::Button::Small }, - ); - crate::scenario::publish_target(&format!("dialog:list:{}", entry.id), choice.rect); - if choice.clicked() { - app.preferences.agent_default = entry.id.clone(); - } - let test_button = ui_kit::button(ui, tr("ui.ai_test"), ui_kit::Button::Small); - crate::scenario::publish_handle(&format!("prefs:ai_test:{}", entry.id), test_button.rect.center()); - let tip = match entry.kind { - Kind::Acp => "ui.ai_test_acp_tip", - Kind::Api => "ui.ai_test_api_tip", - Kind::Anthropic => "ui.ai_test_anthropic_tip", - }; - if test_button.on_hover_text(tr(tip)).clicked() { - test = Some(entry.clone()); - } - if !entry.found && ui_kit::button(ui, tr("ui.ai_remove"), ui_kit::Button::Ghost).clicked() { - remove = Some(entry.id.clone()); - } - match entry.login { - "login_found" => ui_kit::settings_badge(ui, tr("ui.agent_chat_login_found"), false), - "signed_in" => ui_kit::settings_badge(ui, tr("ui.agent_chat_signed_in"), false), - "key" => ui_kit::settings_badge(ui, tr("ui.agent_chat_key_in_env"), false), - "signed_out" => ui_kit::settings_badge(ui, tr("ui.agent_chat_not_signed_in"), true), - _ => {} - } - if !entry.found { - ui_kit::settings_badge(ui, tr("ui.ai_added"), false); - } - }); - ui_kit::settings_short_note(ui, &entry.detail()); - // Wide enough for an endpoint's "Request timeout" too, so both rows line up. - let label_w = (t.form_label_width + t.space_16).max(ui_kit::ContentWidth::label(ui, tr("ui.ai_request_timeout")) + t.space_16); - ui_kit::settings_form(ui, label_w, |ui| { - ui_kit::row(ui, tr("ui.ai_permissions"), |ui| { - let current = app.preferences.agent_permissions.get(&entry.id).copied(); - let shown = current.map_or_else(|| tr("ui.ai_mode_global").to_owned(), |mode| mode.label().to_owned()); - let mut pick: Option> = None; - ui_kit::dropdown_menu(ui, ("sc_ai_mode", &entry.id), &shown, |ui| { - if ui_kit::list_picker(ui, "global", tr("ui.ai_mode_global"), current.is_none()).clicked() { - pick = Some(None); - } - for mode in Mode::ALL { - if ui_kit::list_picker(ui, mode.id(), mode.label(), current == Some(mode)).clicked() { - pick = Some(Some(mode)); + let detail = entry.detail(); + let gate = crate::prefs_search::block_gate(ui, &entry.name, Some(&format!("{} {detail}", entry.id))); + let before = crate::prefs_search::hits(ui); + let mut paint = |ui: &mut egui::Ui| { + let card = ui_kit::settings_card(ui, |ui| { + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + crate::prefs_search::visible(ui, &[&entry.name, &entry.id, &detail]); + ui.label(egui::RichText::new(&entry.name).strong().size(t.font_label).color(t.form_ink)); + ui.allocate_ui_with_layout( + egui::vec2(ui.available_width(), t.control_height), + egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), + |ui| { + let is_default = default.as_deref() == Some(entry.id.as_str()); + let choice = ui_kit::button( + ui, + tr(if is_default { "ui.ai_default" } else { "ai.prefs.make_default" }), + if is_default { ui_kit::Button::SmallSelected } else { ui_kit::Button::Small }, + ); + crate::scenario::publish_target(&format!("dialog:list:{}", entry.id), choice.rect); + if choice.clicked() { + app.preferences.agent_default = entry.id.clone(); } - } + let test_button = ui_kit::button(ui, tr("ui.ai_test"), ui_kit::Button::Small); + crate::scenario::publish_handle(&format!("prefs:ai_test:{}", entry.id), test_button.rect.center()); + let tip = match entry.kind { + Kind::Acp => "ui.ai_test_acp_tip", + Kind::Api => "ui.ai_test_api_tip", + Kind::Anthropic => "ui.ai_test_anthropic_tip", + }; + if test_button.backing_on_hover_text(tr(tip)).clicked() { + test = Some(entry.clone()); + } + if !entry.found { + let edit_button = ui_kit::button(ui, tr("ui.ai_edit"), ui_kit::Button::Small); + crate::scenario::publish_handle(&format!("prefs:ai_edit:{}", entry.id), edit_button.rect.center()); + if edit_button.backing_on_hover_text(tr("ui.ai_edit_tip")).clicked() { + edit = Some(entry.id.clone()); + } + } + if !entry.found { + let button = ui_kit::button(ui, tr("ui.ai_remove"), ui_kit::Button::Ghost); + crate::scenario::publish_target(&format!("prefs:ai_remove:{}", entry.id), button.rect); + if button.clicked() { + remove = Some(entry.id.clone()); + } + } + match entry.login { + "login_found" => ui_kit::settings_badge(ui, tr("ui.agent_chat_login_found"), false), + "signed_in" => ui_kit::settings_badge(ui, tr("ui.agent_chat_signed_in"), false), + "key" => ui_kit::settings_badge(ui, tr("ui.agent_chat_key_in_env"), false), + "signed_out" => ui_kit::settings_badge(ui, tr("ui.agent_chat_not_signed_in"), true), + _ => {} + } + if !entry.found { + ui_kit::settings_badge(ui, tr("ui.ai_added"), false); + } + }, + ); + ui_kit::settings_short_note(ui, &detail).backing_on_hover_text(&entry.id); + // Wide enough for an endpoint's "Request timeout" or "Reasoning effort" too, + // so all rows line up. + let label_w = [tr("ui.ai_permissions"), tr("ui.ai_request_timeout"), tr("ui.ai_reasoning_effort")] + .iter() + .map(|label| ui_kit::ContentWidth::label(ui, label) + t.space_4) + .fold(0.0, f32::max); + ui_kit::settings_form(ui, label_w, |ui| { + ui_kit::row(ui, tr("ui.ai_permissions"), |ui| { + let current = app.preferences.agent_permissions.get(&entry.id).copied(); + let shown = current.map_or_else(|| tr("ui.ai_mode_global").to_owned(), |mode| mode.label().to_owned()); + let mut pick: Option> = None; + let options: Vec<_> = std::iter::once(tr("ui.ai_mode_global")).chain(Mode::ALL.map(Mode::label)).collect(); + crate::prefs_search::note_current(ui, &options.join(" ")); + let response = ui_kit::settings_control_width(ui, t.space_24 * 9.0 + t.space_4, |ui| { + ui_kit::dropdown_menu(ui, ("sc_ai_mode", &entry.id), &shown, |ui| { + if ui_kit::list_picker(ui, "global", tr("ui.ai_mode_global"), current.is_none()).clicked() { + pick = Some(None); + } + for mode in Mode::ALL { + if ui_kit::list_picker(ui, mode.id(), mode.label(), current == Some(mode)).clicked() { + pick = Some(Some(mode)); + } + } + }) + }); + let query = crate::prefs_search::query(ui); + if let Some(option) = options + .iter() + .find(|option| option.to_lowercase() == query) + .or_else(|| options.iter().find(|option| crate::prefs_search::texts_hit(ui, &[*option]))) + { + crate::prefs_search::remember(ui, option, response.rect); + } + for option in options { + crate::prefs_search::follow(ui, option, response.rect); + } + match pick { + Some(Some(mode)) => { + app.preferences.agent_permissions.insert(entry.id.clone(), mode); + } + Some(None) => { + app.preferences.agent_permissions.remove(&entry.id); + } + None => {} + } + }); }); - match pick { - Some(Some(mode)) => { - app.preferences.agent_permissions.insert(entry.id.clone(), mode); - } - Some(None) => { - app.preferences.agent_permissions.remove(&entry.id); - } - None => {} + if entry.kind == Kind::Api + && let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == entry.id) + { + ui_kit::settings_form(ui, label_w, |ui| { + ui_kit::row(ui, tr("ui.ai_request_timeout"), |ui| { + let mut secs = entry.request_timeout_s; + if timeout_field(ui, &mut secs, &format!("prefs:ai_timeout:{}", entry.id)) { + c.request_timeout_s = secs; + retimed = Some((entry.id.clone(), secs)); + } + }); + ui_kit::row(ui, tr("ui.ai_reasoning_effort"), |ui| { + let mut effort = c.reasoning_effort.clone(); + if effort_field(ui, &mut effort, &format!("prefs:ai_reasoning:{}", entry.id)) { + let effort = agents::reasoning_effort(&effort); + c.reasoning_effort = effort.clone(); + reeffort = Some((entry.id.clone(), effort)); + } + }); + }); } + if app.preferences.agent_permissions.get(&entry.id) == Some(&Mode::All) { + ui_kit::text(ui, tr("ai.prefs.override_all_warning"), ui_kit::Text::Report("agent_permissions_warning", true)) + .backing_on_hover_text(tr("ui.ai_mode_all_warning")); + } + test_line(ui, &app.agent_chat.settings.tests.get(&entry.id)); }); - }); - if entry.kind == Kind::Api - && let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == entry.id) - { - ui_kit::settings_form(ui, label_w, |ui| { - ui_kit::row(ui, tr("ui.ai_request_timeout"), |ui| { - let mut secs = entry.request_timeout_s; - if timeout_field(ui, &mut secs, &format!("prefs:ai_timeout:{}", entry.id)) { - c.request_timeout_s = secs; - retimed = Some((entry.id.clone(), secs)); + if let Some(protocol) = entry.kind.protocol() { + ui_kit::row(ui, tr("ui.ai_model"), |ui| { + let chat = &mut app.agent_chat; + let running = chat.running_id == entry.id && chat.backend.is_some(); + let key = listing_key(protocol, &entry.base_url, entry.key); + let (models, note) = if running { + (chat.models.as_slice(), chat.models_note.clone()) + } else if let Some(models) = chat.models_cache.get(&entry.base_url).filter(|models| !models.is_empty()) { + (models.as_slice(), None) + } else { + listed_for(&chat.settings.endpoint_models, key.as_ref()) + }; + let listed = !models.is_empty(); + let rows = super::model_rows(models); + let choices = model_choices(models, &rows); + let id = format!("sc_ai_model:{}", entry.id); + let handles = format!("prefs:ai_model:{}", entry.id); + let picker = ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: &id, + handles: &handles, + current: &entry.model, + current_value: &entry.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: note.as_deref(), + open_group: None, + enabled: true, + }, + ); + // Nobody is asked until the picker opens: not for looking at this page. + if picker.response.clicked() + && !running + && !listed + && let Some(key) = key + { + // Asked again: what failed may work now. + if listing_wants_retry(chat.settings.endpoint_models.get(&key)) { + chat.settings.endpoint_models.remove(&key); + } + chat.settings.card_listing = Some((key, entry.id.clone())); + } + if let Some(pick) = picker.inner { + picked_model = Some((entry.id.clone(), pick)); } }); - }); + } + }); + crate::scenario::publish_rect(&format!("prefs:ai_card:{}", entry.id), card.response.rect); + let metadata = [&entry.name, &entry.id, &detail]; + if let Some(text) = metadata.iter().find(|text| crate::prefs_search::texts_hit(ui, &[*text])) { + crate::prefs_search::remember(ui, text, card.response.rect); } - if app.preferences.agent_permissions.get(&entry.id) == Some(&Mode::All) { - ui_kit::text(ui, tr("ai.prefs.override_all_warning"), ui_kit::Text::Report("agent_permissions_warning", true)) - .on_hover_text(tr("ui.ai_mode_all_warning")); + for text in metadata { + crate::prefs_search::follow(ui, text, card.response.rect); } - test_line(ui, &app.agent_chat.settings.tests.get(&entry.id)); - }); + }; + let show = gate.as_ref().is_none_or(|gate| gate.show); + if show { + paint(ui); + } else { + crate::prefs_search::run_hidden(ui, &entry.id, |ui| { + paint(ui); + }); + } + if let Some(gate) = gate { + crate::prefs_search::block_finish(ui, &gate, show, before); + } }); } ui.horizontal_wrapped(|ui| { @@ -523,6 +913,28 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { let started = start_test(app, &e, key); app.agent_chat.settings.tests.insert(e.id.clone(), started); } + if let Some(id) = edit { + open_edit(app, &id); + } + if let Some((id, pick)) = picked_model { + if app.agent_chat.running_id == id && app.agent_chat.backend.is_some() { + match pick { + ui_kit::Picked::Listed(model) => set_model(app, &model), + ui_kit::Picked::Custom(model) => { + set_custom_model(app, &model); + } + } + } else { + let (ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = pick; + let model = model.trim(); + if model_id_valid(model) { + if let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == id) { + c.model = model.to_string(); + } + app.preferences.agent_models.insert(id, model.to_string()); + } + } + } // The running conversation uses a new timeout from its next request on. if let Some((id, secs)) = retimed && app.agent_chat.running_id == id @@ -530,6 +942,13 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { { b.set_request_timeout(secs); } + // A new reasoning effort likewise takes effect from the next request on. + if let Some((id, effort)) = reeffort + && app.agent_chat.running_id == id + && let Some(b) = app.agent_chat.backend.as_mut() + { + b.set_reasoning_effort(&effort); + } if let Some(id) = remove { app.agent_chat.login_results.remove(&id); app.agent_chat.settings.tests.remove(&id); @@ -565,32 +984,37 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { let mut open = true; let mut add = false; let mut test = false; - let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_ai_add"), "settings", tr("ui.ai_add_agent_title")) + // Editing keeps the agent's kind: the kind switch is for adding only. + let editing = app.agent_chat.settings.add.as_ref().is_some_and(|s| s.editing.is_some()); + let (title, ok) = if editing { ("ui.ai_edit_agent_title", "ui.ai_save") } else { ("ui.ai_add_agent_title", "ui.ai_add") }; + let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_ai_add"), "settings", tr(title)) .cards(2.0) .fields() - .actions(tr("ui.ai_add"), "Cancel", None) + .actions(tr(ok), "Cancel", None) .show(ctx, true, |ui| { let Some(s) = app.agent_chat.settings.add.as_mut() else { return }; if let Some(test) = s.test.as_mut() { let _ = test.poll(); } let kinds = [(AddKind::Installed, "ui.ai_add_installed"), (AddKind::Custom, "ui.ai_add_custom"), (AddKind::Api, "ui.ai_add_endpoint")]; - ui_kit::row(ui, tr("ui.ai_kind"), |ui| { - let mut selected = kinds.iter().position(|(k, _)| *k == s.kind).unwrap_or(0); - let labels = kinds.map(|(_, key)| tr(key)); - if ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments { compact: true, ..Default::default() }) - && let Some((kind, _)) = kinds.get(selected) - { - s.kind = *kind; - s.error = None; - s.test = None; - } - for (_, key) in kinds { - if let Some(at) = crate::scenario::handle_at(&format!("dialog:{}:{}", tr("ui.ai_kind"), tr(key))) { - crate::scenario::publish_handle(&format!("ai_add:{key}"), at); + if !editing { + ui_kit::row(ui, tr("ui.ai_kind"), |ui| { + let mut selected = kinds.iter().position(|(k, _)| *k == s.kind).unwrap_or(0); + let labels = kinds.map(|(_, key)| tr(key)); + if ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments { compact: true, ..Default::default() }) + && let Some((kind, _)) = kinds.get(selected) + { + s.kind = *kind; + s.error = None; + s.test = None; } - } - }); + for (_, key) in kinds { + if let Some(at) = crate::scenario::handle_at(&format!("dialog:{}:{}", tr("ui.ai_kind"), tr(key))) { + crate::scenario::publish_handle(&format!("ai_add:{key}"), at); + } + } + }); + } match s.kind { AddKind::Installed => { ui_kit::row(ui, tr("ui.agent_chat_pick"), |ui| { @@ -665,18 +1089,47 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { ui_kit::text_field(ui, &mut s.name, ""); }); ui_kit::row(ui, tr("ui.ai_base_url"), |ui| { - ui_kit::text_field(ui, &mut s.base_url, tr("ui.ai_url_hint")); + s.list_again |= + ui_kit::cell_editor(ui, egui::Id::new("sc_ai_add_url"), &mut s.base_url, tr("ui.ai_url_hint"), false).lost_focus(); }); ui_kit::row(ui, tr("ui.ai_model"), |ui| { - ui_kit::text_field(ui, &mut s.model, tr("ui.ai_model_hint")); + let (models, note) = listed_for(&app.agent_chat.settings.endpoint_models, s.listing.as_ref()); + let rows = super::model_rows(models); + let choices = model_choices(models, &rows); + let current = if s.model.is_empty() { tr("ui.agent_chat_choose_model") } else { s.model.as_str() }; + let picker = ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: "sc_ai_add_model", + handles: "ai_add:model", + current, + current_value: &s.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: note.as_deref(), + open_group: None, + enabled: true, + }, + ); + s.list_again |= picker.response.clicked(); + if let Some(ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = picker.inner { + s.model = model; + s.error = None; + } }); ui_kit::row(ui, tr("ui.ai_request_timeout"), |ui| { timeout_field(ui, &mut s.request_timeout_s, "ai_add:request_timeout"); }); + ui_kit::row(ui, tr("ui.ai_reasoning_effort"), |ui| { + effort_field(ui, &mut s.reasoning_effort, "ai_add:reasoning_effort"); + }); ui_kit::row(ui, tr("ui.ai_key"), |ui| { ui.add_enabled_ui(has_keychain, |ui| { - let r = ui_kit::password_field(ui, egui::Id::new("sc_ai_add_key"), &mut s.key, tr("ui.ai_key_hint")); + let hint = tr(if s.saved_key { "ui.ai_key_keep_hint" } else { "ui.ai_key_hint" }); + let r = ui_kit::password_field(ui, egui::Id::new("sc_ai_add_key"), &mut s.key, hint); crate::scenario::publish_target("ai_add:key", r.rect); + s.list_again |= r.lost_focus(); }); }); ui_kit::text(ui, tr(if has_keychain { "ui.ai_key_note" } else { "ui.ai_no_keychain" }), ui_kit::Text::Note("keychain")); @@ -695,6 +1148,8 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { } add |= action == ui_kit::Action::Ok; open &= !closed && action != ui_kit::Action::Cancel; + #[cfg(not(target_arch = "wasm32"))] + list_for_dialog(app, ctx); if test { #[cfg(not(target_arch = "wasm32"))] if let Some(s) = app.agent_chat.settings.add.as_ref() { @@ -711,8 +1166,16 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { model: s.model.trim().to_string(), key: false, request_timeout_s: s.request_timeout_s, + reasoning_effort: agents::reasoning_effort(&s.reasoning_effort), + problem: None, + install: "", }; - let key = Some(s.key.trim().to_string()).filter(|k| !k.is_empty()); + // Editing with the key field left empty tests with the stored key, which is only ever + // sent where a saved key may go (HTTPS or this computer). + let key = Some(s.key.trim().to_string()).filter(|k| !k.is_empty()).or_else(|| { + let id = s.editing.as_deref().filter(|_| s.saved_key && url.as_deref().is_ok_and(agents::key_safe_for))?; + app.services.secrets.as_ref().and_then(|store| store.get(id).ok().flatten()) + }); let result = match url { Ok(_) => start_test(app, &e, key), Err(err) => Test::Done(Err(TestError::Other(err))), @@ -740,9 +1203,14 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { } } -/// Add what the dialog holds; its key goes to the keychain. +/// Add what the dialog holds, or save it over the agent being edited; its key goes to the keychain. fn add_agent(app: &mut SolveApp) -> Result<(), String> { let Some(s) = app.agent_chat.settings.add.as_ref() else { return Ok(()) }; + // The agent being edited must still be there (it may have been removed meanwhile). + let editing = match &s.editing { + Some(id) => Some(app.preferences.agents.iter().position(|c| &c.id == id).ok_or_else(|| tr("ui.ai_edit_gone").to_string())?), + None => None, + }; let name = s.name.trim().chars().take(80).collect::(); let mut c = AgentConfig { name, ..Default::default() }; let mut key: Option = None; @@ -762,16 +1230,23 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { c.base_url = agents::normalize_url(&s.base_url)?; c.model = s.model.trim().to_string(); c.request_timeout_s = s.request_timeout_s.clamp(agents::MIN_REQUEST_TIMEOUT_S, agents::MAX_REQUEST_TIMEOUT_S); + c.reasoning_effort = agents::reasoning_effort(&s.reasoning_effort); if c.model.is_empty() { return Err(tr("ui.ai_need_model").to_string()); } key = Some(s.key.trim().to_string()).filter(|k| !k.is_empty()); - if key.is_some() && !agents::key_safe_for(&c.base_url) { + // Editing with the key field left empty keeps the stored key. + let kept = key.is_none() && editing.is_some() && s.saved_key; + if (key.is_some() || kept) && !agents::key_safe_for(&c.base_url) { return Err(tr("ui.ai_key_needs_https").to_string()); } + c.key = kept; c.id = agents::new_id(&app.preferences, c.kind.id()); } } + if let Some(id) = &s.editing { + c.id = id.clone(); + } if c.name.is_empty() { c.name = c.id.clone(); } @@ -780,16 +1255,378 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { store.set(&c.id, &k).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)]))?; c.key = true; } - app.preferences.agents.push(c); + let Some(at) = editing else { + app.preferences.agents.push(c); + return Ok(()); + }; + match app.preferences.agents.get_mut(at) { + None => return Err(tr("ui.ai_edit_gone").to_string()), + Some(old) => { + // An endpoint edited into a program (or one whose key was dropped) leaves no key behind. + if old.key + && !c.key + && let Some(store) = &app.services.secrets + { + let _ = store.delete(&c.id); + } + *old = c; + let id = old.id.clone(); + let secs = old.request_timeout_s; + let effort = old.reasoning_effort.clone(); + // A new command, endpoint or key has not been tested or signed in yet. + app.agent_chat.settings.tests.remove(&id); + app.agent_chat.login_results.remove(&id); + // The running conversation takes a new timeout from its next request on; the rest + // applies the next time the agent connects. + if app.agent_chat.running_id == id + && let Some(b) = app.agent_chat.backend.as_mut() + { + b.set_request_timeout(secs); + b.set_reasoning_effort(&effort); + } + } + } Ok(()) } #[cfg(all(test, not(target_arch = "wasm32")))] mod card_tests { + use super::super::backend::Secrets; use super::*; use crate::scenario::{self, Harness}; use serde_json::json; + /// The fixed Preferences window scrolls even on a tall desktop. Use actual wheel input + /// before clicking a card action whose published geometry may be outside the viewport. + fn reveal_card_action(h: &mut Harness, handle: &str) -> Result<(), String> { + for _ in 0..32 { + let at = scenario::handle_at(handle).ok_or_else(|| format!("{handle}: the real card action is not published"))?; + let body = scenario::rect_of("prefs:page_body").ok_or("Preferences has no scroll viewport")?; + if body.contains(at) { + return Ok(()); + } + h.call("ui.scroll", json!({"x":body.center().x,"y":body.center().y,"delta":if at.y < body.top() {100} else {-100}})); + h.frames(30); + } + Err(format!("{handle} could not be scrolled into the Preferences viewport")) + } + + #[test] + fn assistant_production_heading_and_sections_use_page_metrics() { + for theme in ["light", "dark"] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = false; + h.app.agent_chat.detection = Some(Default::default()); + h.call("ui.resize", json!({"width":1600,"height":4000})); + h.call("ui.prefs", json!({"open":"Assistant","theme":theme})); + h.frames(4); + let warning = scenario::rect_of("prefs:ai_mode:all:icon").unwrap(); + assert!(scenario::rect_of("prefs:ai_mode:all").unwrap().contains_rect(warning)); + let heading = scenario::rect_of("prefs:page_heading").unwrap(); + let body = scenario::rect_of("prefs:page_body").unwrap(); + assert!(body.contains_rect(heading)); + let mut page_font = false; + let mut scope_visible = false; + let mut privacy_visible = false; + for _ in 0..24 { + for shape in &h.shapes { + crate::test_support::each_shape(&shape.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape { + scope_visible |= text.galley.job.text == tr("ui.ai_modes_scope"); + privacy_visible |= text.galley.job.text == tr("ai.prefs.privacy_note"); + page_font |= text.galley.job.text == "Assistant" + && text + .galley + .job + .sections + .iter() + .all(|section| section.format.font_id.size == crate::theme::Tokens::get().font_page_heading); + } + }); + } + if scope_visible && privacy_visible { + break; + } + h.call("ui.scroll", json!({"x":body.center().x,"y":body.center().y,"delta":-160})); + h.frames(30); + } + assert!(page_font, "the production heading uses the page font"); + assert!(scope_visible, "the full localized permission scope remains visible without hovering, including with AI off"); + assert!(privacy_visible, "the localized privacy note remains visible without hovering, including with AI off"); + let mut previous: Option = None; + for key in ["assistant_availability", "permissions", "agents", "panel", "assistant_connecting", "agent_pointer"] { + let section = scenario::rect_of(&format!("prefs:section:{key}")).unwrap(); + assert!((section.left() - body.left()).abs() <= 1.0 && (section.right() - body.right()).abs() <= 1.0); + assert!((section.height() - (crate::theme::Tokens::get().control_height + crate::theme::Tokens::get().space_2)).abs() <= 1.0); + if let Some(bottom) = previous { + assert!((section.top() - bottom - 38.0).abs() <= 1.0, "{theme}: {key} retains the page section rhythm"); + } + previous = Some(scenario::rect_of(&format!("prefs:section:{key}:body")).unwrap().bottom()); + } + } + } + + #[test] + fn pointer_speed_search_reveals_one_real_slider_in_all_enablement_states() { + use crate::prefs_search::{nav, set_cursor}; + for theme in ["light", "dark"] { + for (ai, show) in [(true, true), (true, false), (false, true), (false, false)] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.agent_chat.detection = Some(Default::default()); + h.app.preferences.ai_features = ai; + h.app.ui.agent_cursor.show = show; + h.app.ui.agent_cursor.speed = crate::agent_cursor::Speed::Times(3.5); + h.call("ui.resize", json!({"width":1600,"height":1400})); + h.call("ui.prefs", json!({"open":"General","theme":theme})); + for query in ["Speed", "Pointer speed", "Motion speed"] { + h.app.prefs_window.filter = query.into(); + h.frames(6); + let (_, _, hits) = nav(&h.ctx); + let matches: Vec<_> = hits.iter().enumerate().filter(|(_, hit)| hit.page == crate::prefs::PAGE_ASSISTANT).collect(); + assert_eq!(matches.len(), 1, "{theme} AI={ai} show={show}: {query} owns one editor"); + set_cursor(&h.ctx, matches[0].0); + h.frames(2); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(30); + assert_eq!(h.app.prefs_window.section, crate::prefs::PAGE_ASSISTANT); + assert!(h.app.prefs_window.filter.is_empty()); + let slider = scenario::rect_of("prefs:agent_pointer_speed").unwrap(); + assert_eq!(slider, scenario::rect_of("dialog:slider:Pointer speed").unwrap()); + let body = scenario::rect_of("dialog:page_body").unwrap(); + assert!(body.contains_rect(slider), "{query} reveals the editor inside the page"); + assert!(scenario::handle_at("prefs:revealed").unwrap().distance(slider.center()) <= 1.0, "{query} reveals the slider itself"); + let tree = h.output.accesskit_update.as_ref().unwrap(); + let sliders: Vec<_> = tree + .nodes + .iter() + .filter(|(_, node)| node.role() == egui::accesskit::Role::Slider && node.label() == Some("Pointer speed")) + .collect(); + assert_eq!(sliders.len(), 1); + assert_eq!(sliders[0].1.is_disabled(), !(ai && show)); + assert_eq!(h.app.ui.agent_cursor.speed, crate::agent_cursor::Speed::Times(3.5)); + assert_eq!((h.app.preferences.ai_features, h.app.ui.agent_cursor.show), (ai, show)); + } + } + } + } + + #[test] + fn overlapping_agent_metadata_has_one_card_target_and_keeps_fields_indexed() { + use crate::prefs_search::{nav, set_cursor}; + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + for theme in ["light", "dark"] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.agent_chat.detection = Some(Default::default()); + h.app.preferences.agent_connect_at_start = false; + h.app.preferences.agents = vec![ + AgentConfig { + id: "acp-current".into(), + name: "Current fixture".into(), + command: "solidcraft-fixture-agent --acp".into(), + ..Default::default() + }, + AgentConfig { + id: "api-public".into(), + name: "Public endpoint".into(), + kind: Kind::Api, + base_url: "https://example.com/v1".into(), + model: "public-model".into(), + reasoning_effort: "high".into(), + ..Default::default() + }, + ]; + h.app.preferences.agent_default = "acp-current".into(); + h.app.agent_chat.agent_id = Some("acp-current".into()); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = calls.clone(); + h.app.services.agent_http = Some(Arc::new(move |_| { + seen.fetch_add(1, Ordering::SeqCst); + Err("fixture must not be queried".into()) + })); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.call("ui.prefs", json!({"open":"General","theme":theme})); + for query in ["public", "api-public", "public-model"] { + h.app.prefs_window.filter = query.into(); + h.frames(6); + let (_, _, hits) = nav(&h.ctx); + let matches: Vec<_> = hits.iter().enumerate().filter(|(_, hit)| hit.page == crate::prefs::PAGE_ASSISTANT).collect(); + assert_eq!(matches.len(), 1, "{query}: overlapping name/id/detail own one card stop"); + set_cursor(&h.ctx, matches[0].0); + h.frames(2); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(30); + assert_eq!(h.app.prefs_window.section, crate::prefs::PAGE_ASSISTANT); + assert!(h.app.prefs_window.filter.is_empty()); + let card = scenario::rect_of("prefs:ai_card:api-public").unwrap(); + assert!(scenario::rect_of("dialog:page_body").unwrap().contains_rect(card)); + assert!(scenario::handle_at("prefs:revealed").unwrap().distance(card.center()) <= 1.0, "{query} reveals the same complete card"); + } + for (query, handle) in [("Request timeout", "prefs:ai_timeout:api-public"), ("Reasoning effort", "prefs:ai_reasoning:api-public")] { + h.app.prefs_window.filter = query.into(); + h.frames(6); + let (_, _, hits) = nav(&h.ctx); + let matches: Vec<_> = + hits.iter().enumerate().filter(|(_, hit)| hit.page == crate::prefs::PAGE_ASSISTANT && hit.label == query).collect(); + assert_eq!(matches.len(), 1, "{query} keeps its independent setting target"); + set_cursor(&h.ctx, matches[0].0); + h.frames(2); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(30); + assert!(h.app.prefs_window.filter.is_empty()); + assert!(scenario::rect_of("dialog:page_body").unwrap().contains_rect(scenario::rect_of(handle).unwrap())); + } + h.app.prefs_window.filter = "Permissions".into(); + h.frames(6); + let (_, _, hits) = nav(&h.ctx); + assert!( + hits.iter().filter(|hit| hit.page == crate::prefs::PAGE_ASSISTANT && hit.label == "Permissions").count() >= 2, + "real per-agent Permissions remain independently indexed" + ); + assert_eq!(calls.load(Ordering::SeqCst), 0, "ACP-current/API-noncurrent search never probes or tests an endpoint"); + } + } + + #[test] + fn assistant_off_keeps_dependent_controls_disabled_and_cancel_restores_the_pointer() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.agent_chat.detection = Some(Default::default()); + h.app.ui.agent_cursor.speed = crate::agent_cursor::Speed::Times(3.5); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.call("ui.prefs", json!({"open":"Assistant"})); + h.app.preferences.ai_features = false; + h.app.ui.agent_cursor.speed = crate::agent_cursor::Speed::Instant; + h.frames(4); + let tree = h.output.accesskit_update.as_ref().unwrap(); + for label in [ + tr("ui.ai_toolbar_button"), + tr("ai.prefs.allow_control"), + tr("ai.prefs.connect_apps"), + tr("ai.prefs.background_commands"), + tr("ai.prefs.connect_at_start"), + tr("ai.prefs.open_at_start"), + tr("ai.prefs.show_pointer"), + tr("ai.prefs.follow_camera"), + ] { + let nodes: Vec<_> = + tree.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::CheckBox && node.label() == Some(label)).collect(); + assert_eq!(nodes.len(), 1, "{label} is retained exactly once"); + assert!(nodes[0].1.is_disabled(), "{label} dims when AI is off"); + } + assert!(tree.nodes.iter().any(|(_, node)| node.label() == Some(tr("ui.ai_show_features")) && !node.is_disabled())); + assert!(h.app.agent_chat.detecting.is_none() && h.app.agent_chat.backend.is_none()); + h.step(&json!({"click":{"handle":"prefs:cancel"}})).unwrap(); + assert!(h.app.preferences.ai_features); + assert_eq!(h.app.ui.agent_cursor.speed, crate::agent_cursor::Speed::Times(3.5)); + } + + #[test] + fn assistant_limit_dropdown_preserves_values_and_seeds_only_on_transition() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.agent_chat.detection = Some(Default::default()); + h.app.preferences.agent_chat_turn_limit = 37; + h.call("ui.resize", json!({"width":1600,"height":1400})); + h.call("ui.prefs", json!({"open":"Assistant"})); + h.app.prefs_window.filter = tr("ui.agent_chat_turn_limit").into(); + h.frames(4); + for limit in [1, 37, 199, 200] { + h.app.preferences.agent_chat_turn_limit = limit; + h.frames(3); + assert_eq!(h.app.preferences.agent_chat_turn_limit, limit, "rendering preserves every supported value"); + } + h.step(&json!({"click":{"handle":"prefs:agent_chat_turn_limit:mode"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:{}:{}", tr("ui.agent_chat_turn_limit"), tr("ui.agent_chat_turn_unlimited"))}})).unwrap(); + assert_eq!(h.app.preferences.agent_chat_turn_limit, 0); + h.step(&json!({"click":{"handle":"prefs:agent_chat_turn_limit:mode"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:{}:{}", tr("ui.agent_chat_turn_limit"), tr("prefs.assistant_limited"))}})).unwrap(); + assert_eq!(h.app.preferences.agent_chat_turn_limit, gate::SEEDED_TURN_LIMIT); + h.step(&json!({"click":{"handle":"prefs:cancel"}})).unwrap(); + assert_eq!(h.app.preferences.agent_chat_turn_limit, 37); + } + + #[test] + fn agent_card_reads_the_key_only_for_test_and_removal_clears_remembered_state() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + #[derive(Default)] + struct Keys { + values: MemoryKeys, + reads: AtomicUsize, + } + impl Secrets for Keys { + fn get(&self, id: &str) -> Result, String> { + self.reads.fetch_add(1, Ordering::SeqCst); + self.values.get(id) + } + fn set(&self, id: &str, secret: &str) -> Result<(), String> { + self.values.set(id, secret) + } + fn delete(&self, id: &str) -> Result<(), String> { + self.values.delete(id) + } + } + let mut h = Harness::new(); + h.app.home.open = false; + h.app.agent_chat.detection = Some(Default::default()); + let keys = Arc::new(Keys::default()); + keys.set("api-public", "render-fixture-key").unwrap(); + h.app.services.secrets = Some(keys.clone()); + let (tx, rx) = std::sync::mpsc::channel(); + h.app.services.agent_http = Some(Arc::new(move |_| { + let _ = tx.send(()); + Ok((200, br#"{"data":[{"id":"public-model"}]}"#.to_vec())) + })); + // An ACP default keeps the API fixture noncurrent; baseline capability polling is unchanged. + h.app.preferences.agents = vec![ + AgentConfig { + id: "acp-public".into(), + name: "Public ACP".into(), + command: "solidcraft-fixture-agent --acp".into(), + ..Default::default() + }, + AgentConfig { + id: "api-public".into(), + name: "Public endpoint".into(), + kind: Kind::Api, + base_url: "https://example.com/v1".into(), + model: "public-model".into(), + key: true, + ..Default::default() + }, + ]; + h.app.preferences.agent_default = "acp-public".into(); + h.app.preferences.agent_last = "api-public".into(); + h.app.preferences.agent_permissions.insert("api-public".into(), Mode::Ask); + h.app.preferences.agent_always_allow.insert("api-public".into(), vec!["view.fit".into()]); + h.call("ui.resize", json!({"width":1600,"height":1400})); + h.call("ui.prefs", json!({"open":"Assistant"})); + h.app.prefs_window.filter = "Public endpoint".into(); + h.frames(4); + assert_eq!(keys.reads.load(Ordering::SeqCst), 0, "rendering never retrieves a stored key"); + assert!(rx.try_recv().is_err(), "a noncurrent card does not probe or test its endpoint"); + assert!(h.widget("render-fixture-key").is_none()); + h.step(&json!({"click":{"handle":"prefs:ai_test:api-public"}})).unwrap(); + rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(); + assert_eq!(keys.reads.load(Ordering::SeqCst), 1, "only the explicit Test action retrieves the key"); + h.step(&json!({"click":{"handle":"prefs:ai_remove:api-public"}})).unwrap(); + assert!(!h.app.preferences.agents.iter().any(|agent| agent.id == "api-public")); + assert!(!h.app.preferences.agent_permissions.contains_key("api-public")); + assert!(!h.app.preferences.agent_always_allow.contains_key("api-public")); + assert!(!h.app.agent_chat.settings.tests.contains_key("api-public")); + assert!(!h.app.agent_chat.login_results.contains_key("api-public")); + assert!(h.app.preferences.agent_last.is_empty()); + assert_eq!(keys.values.get("api-public").unwrap(), None); + } + #[test] fn cached_model_warning_follows_endpoint_model_and_agent_selection() { let mut h = Harness::new(); @@ -885,4 +1722,425 @@ mod card_tests { assert_eq!(saved.base_url, "https://api.anthropic.com/v1"); assert_eq!(saved.model, "claude-opus-5-5"); } + + /// A keychain in memory, for tests. + #[derive(Default)] + struct MemoryKeys(std::sync::Mutex>); + + impl Secrets for MemoryKeys { + fn get(&self, id: &str) -> Result, String> { + Ok(self.0.lock().map_err(|e| e.to_string())?.get(id).cloned()) + } + fn set(&self, id: &str, secret: &str) -> Result<(), String> { + self.0.lock().map_err(|e| e.to_string())?.insert(id.into(), secret.into()); + Ok(()) + } + fn delete(&self, id: &str) -> Result<(), String> { + self.0.lock().map_err(|e| e.to_string())?.remove(id); + Ok(()) + } + } + + /// Edit on an added agent reopens the dialog filled in; Save changes it in place, keeping its + /// id, its permission override and its always-allowed tools (#9619). + #[test] + fn edit_reopens_an_added_agent_and_saves_it_in_place() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width": 1600.0, "height": 1000.0})); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + h.app.preferences.agents.push(AgentConfig { + id: "custom-1".into(), + name: "Mine".into(), + command: "my-agent --acp".into(), + ..Default::default() + }); + h.app.preferences.agent_permissions.insert("custom-1".into(), Mode::Edits); + h.app.preferences.agent_always_allow.insert("custom-1".into(), vec!["read".into()]); + h.call("ui.prefs", json!({"open": "AI"})); + h.frames(4); + reveal_card_action(&mut h, "prefs:ai_edit:custom-1").unwrap(); + let edit = scenario::handle_at("prefs:ai_edit:custom-1").expect("an added agent has Edit"); + h.call("ui.click", json!({"x": edit.x, "y": edit.y})); + h.frames(4); + { + let s = h.app.agent_chat.settings.add.as_ref().expect("Edit opened the dialog"); + assert_eq!(s.editing.as_deref(), Some("custom-1")); + assert_eq!(s.kind, AddKind::Custom); + assert_eq!((s.name.as_str(), s.command.as_str()), ("Mine", "my-agent --acp")); + } + assert!(scenario::handle_at("ai_add:ui.ai_add_custom").is_none(), "editing keeps the agent's kind"); + let s = h.app.agent_chat.settings.add.as_mut().unwrap(); + s.name = "Mine, verbose".into(); + s.command = "my-agent --acp --verbose".into(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap(); + assert!(h.app.agent_chat.settings.add.is_none(), "Save closed the dialog"); + assert_eq!(h.app.preferences.agents.len(), 1, "saved in place, not added"); + let saved = &h.app.preferences.agents[0]; + assert_eq!((saved.id.as_str(), saved.name.as_str(), saved.command.as_str()), ("custom-1", "Mine, verbose", "my-agent --acp --verbose")); + assert_eq!(h.app.preferences.agent_permissions.get("custom-1"), Some(&Mode::Edits)); + assert!(h.app.preferences.agent_always_allow.contains_key("custom-1")); + // An empty command is refused as when adding. + assert!(open_edit(&mut h.app, "custom-1")); + h.app.agent_chat.settings.add.as_mut().unwrap().command = " ".into(); + assert_eq!(add_agent(&mut h.app), Err(tr("ui.ai_need_command").to_string())); + assert_eq!(h.app.preferences.agents[0].command, "my-agent --acp --verbose"); + } + + /// Editing an endpoint never shows its stored key: an empty key field keeps it, a new one + /// replaces it, and a kept key still only goes to HTTPS or this computer (#9619). + #[test] + fn edit_keeps_or_replaces_a_stored_key_without_showing_it() { + let mut h = Harness::new(); + let keys = std::sync::Arc::new(MemoryKeys::default()); + h.app.services.secrets = Some(keys.clone()); + keys.set("api-1", "test-key-1").unwrap(); + h.app.preferences.agents.push(AgentConfig { + id: "api-1".into(), + name: "OpenAI".into(), + kind: Kind::Api, + base_url: "https://api.openai.com/v1".into(), + model: "model-a".into(), + key: true, + request_timeout_s: 600, + reasoning_effort: "high".into(), + ..Default::default() + }); + assert!(open_edit(&mut h.app, "api-1")); + { + let s = h.app.agent_chat.settings.add.as_ref().unwrap(); + assert!(s.key.is_empty(), "the stored key is never read back into the dialog"); + assert!(s.saved_key); + assert_eq!((s.kind, s.protocol), (AddKind::Api, Protocol::OpenAi)); + assert_eq!(agents::presets(Protocol::OpenAi).get(s.preset).map(|p| p.name), Some("OpenAI")); + assert_eq!((s.base_url.as_str(), s.model.as_str(), s.request_timeout_s), ("https://api.openai.com/v1", "model-a", 600)); + assert_eq!(s.reasoning_effort, "high", "the chosen effort comes back into the dialog"); + } + h.app.agent_chat.settings.add.as_mut().unwrap().model = "model-b".into(); + add_agent(&mut h.app).unwrap(); + let saved = &h.app.preferences.agents[0]; + assert_eq!((saved.id.as_str(), saved.model.as_str(), saved.key, saved.request_timeout_s), ("api-1", "model-b", true, 600)); + assert_eq!(saved.reasoning_effort, "high", "the effort survives an edit"); + assert_eq!(keys.get("api-1").unwrap().as_deref(), Some("test-key-1"), "an empty field keeps the key"); + // A kept key does not go to a plain-HTTP address elsewhere. + assert!(open_edit(&mut h.app, "api-1")); + h.app.agent_chat.settings.add.as_mut().unwrap().base_url = "http://example.com/v1".into(); + assert_eq!(add_agent(&mut h.app), Err(tr("ui.ai_key_needs_https").to_string())); + assert_eq!(h.app.preferences.agents[0].base_url, "https://api.openai.com/v1"); + // A new key replaces the stored one. + assert!(open_edit(&mut h.app, "api-1")); + h.app.agent_chat.settings.add.as_mut().unwrap().key = "test-key-2".into(); + add_agent(&mut h.app).unwrap(); + assert_eq!(keys.get("api-1").unwrap().as_deref(), Some("test-key-2")); + assert_eq!(h.app.preferences.agents.len(), 1); + // Custom URLs and the Ollama preset come back as they were chosen. + h.app.preferences.agents.push(AgentConfig { + id: "api-2".into(), + kind: Kind::Api, + base_url: "http://192.168.1.20:11434/v1".into(), + model: "m".into(), + ollama: true, + ..Default::default() + }); + h.app.preferences.agents.push(AgentConfig { + id: "anthropic-1".into(), + kind: Kind::Anthropic, + base_url: "https://example.com/anthropic/v1".into(), + model: "m".into(), + ..Default::default() + }); + assert!(open_edit(&mut h.app, "api-2")); + assert_eq!(h.app.agent_chat.settings.add.as_ref().map(|s| (s.preset, s.saved_key)), Some((0, false))); + add_agent(&mut h.app).unwrap(); + assert!(h.app.preferences.agents.iter().any(|c| c.id == "api-2" && c.ollama && c.base_url == "http://192.168.1.20:11434/v1")); + assert!(open_edit(&mut h.app, "anthropic-1")); + let s = h.app.agent_chat.settings.add.as_ref().unwrap(); + assert_eq!((s.protocol, s.preset), (Protocol::Anthropic, agents::ANTHROPIC_PRESETS.len()), "a custom URL"); + add_agent(&mut h.app).unwrap(); + assert!(h.app.preferences.agents.iter().any(|c| c.id == "anthropic-1" && c.kind == Kind::Anthropic)); + assert_eq!(h.app.preferences.agents.len(), 3); + } + + /// Only added agents can be edited, and an agent removed while its dialog is open is not + /// brought back by Save; the control channel opens the same dialog (#9619). + #[test] + fn edit_only_for_added_agents_and_not_after_removal() { + let mut h = Harness::new(); + assert!(!open_edit(&mut h.app, "claude"), "a found agent has nothing of yours to edit"); + assert!(h.app.agent_chat.settings.add.is_none()); + h.app.preferences.agents.push(AgentConfig { id: "custom-1".into(), command: "a --acp".into(), ..Default::default() }); + let err = control(&mut h.app, &h.ctx, &json!({"edit_dialog": "nope"})).unwrap_err(); + assert!(err.contains("nope"), "{err}"); + control(&mut h.app, &h.ctx, &json!({"edit_dialog": "custom-1"})).unwrap(); + assert_eq!(h.app.agent_chat.settings.add.as_ref().and_then(|s| s.editing.as_deref()), Some("custom-1")); + h.app.preferences.agents.clear(); + assert_eq!(add_agent(&mut h.app), Err(tr("ui.ai_edit_gone").to_string())); + assert!(h.app.preferences.agents.is_empty()); + } + + /// An `agent_http` that may not be called on the window's thread: it answers `/models` as + /// OpenRouter does, or 401 for an address with `refused` in it, and records what it was asked. + fn listing_http(h: &mut Harness) -> std::sync::Arc>> { + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = seen.clone(); + let ui_thread = std::thread::current().id(); + h.app.services.agent_http = Some(std::sync::Arc::new(move |request: &super::super::backend::HttpRequest| { + assert_ne!(std::thread::current().id(), ui_thread); + // The running agent's capability check goes through here too. + if request.url.ends_with("/models") + && let Ok(mut log) = log.lock() + { + log.push((request.url.clone(), request.headers.iter().any(|(name, _)| name == "Authorization"))); + } + if request.url.contains("refused") { + return Ok((401, br#"{"error":{"message":"no such key"}}"#.to_vec())); + } + if request.url.contains("/page/") { + return Ok((200, b"Control UI".to_vec())); + } + if request.url.contains("/empty/") { + return Ok((200, br#"{"data":[]}"#.to_vec())); + } + Ok((200, json!({"data": [{"id": "vendor/big", "name": "Vendor: Big"}, {"id": "vendor/small"}]}).to_string().into_bytes())) + })); + seen + } + + /// A web page where the models should be, or a list with nothing in it, says so under the + /// picker, and is asked for again the next time. + #[test] + fn a_listing_that_is_no_list_or_lists_nothing_says_so_and_is_asked_again() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().len(); + open_add(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests(), 1); + let note = |h: &Harness| { + let add = h.app.agent_chat.settings.add.as_ref().unwrap(); + listed_for(&h.app.agent_chat.settings.endpoint_models, add.listing.as_ref()).1.unwrap_or_default() + }; + // What the dialog's listing holds for the fields as they are (the words are the language's). + let listing = |h: &Harness| { + let add = h.app.agent_chat.settings.add.as_ref().unwrap(); + add.listing.as_ref().and_then(|key| h.app.agent_chat.settings.endpoint_models.get(key)).cloned() + }; + let ask = |h: &mut Harness, url: &str| { + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = url.into(); + add.list_again = true; + list_settled(h); + }; + ask(&mut h, "http://localhost:18789/page/v1"); + assert_eq!(requests(), 2); + assert!(matches!(listing(&h), Some(Err(_))), "a page where the list should be is an error: {:?}", listing(&h)); + assert!(!note(&h).is_empty(), "and the picker says so"); + ask(&mut h, "http://localhost:18789/page/v1"); + assert_eq!(requests(), 3, "a page where the list should be is asked for again"); + ask(&mut h, "http://localhost:18789/empty/v1"); + assert_eq!(requests(), 4); + assert!(matches!(listing(&h), Some(Ok(models)) if models.is_empty()), "{:?}", listing(&h)); + assert!(!note(&h).is_empty(), "an empty list is said so too"); + ask(&mut h, "http://localhost:18789/empty/v1"); + assert_eq!(requests(), 5, "an empty list is asked for again"); + ask(&mut h, "http://localhost:11434/v1"); + assert_eq!(requests(), 5, "a list that had models is kept"); + assert_eq!(note(&h), ""); + } + + /// Editing an endpoint whose key is kept lists its models at once, with that key from the + /// keychain (never shown). + #[test] + fn editing_an_endpoint_lists_with_its_stored_key() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let keys = std::sync::Arc::new(MemoryKeys::default()); + h.app.services.secrets = Some(keys.clone()); + keys.set("api-1", "test-key-1").unwrap(); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().clone(); + h.app.preferences.agents.push(AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: Kind::Api, + base_url: "https://openrouter.ai/api/v1".into(), + model: "vendor/big".into(), + key: true, + ..Default::default() + }); + h.call("ui.prefs", json!({"open": "AI"})); + h.frames(3); + assert!(open_edit(&mut h.app, "api-1")); + list_settled(&mut h); + assert_eq!(requests(), [("https://openrouter.ai/api/v1/models".to_string(), true)], "listed on opening, with the kept key"); + assert!(h.app.agent_chat.settings.add.as_ref().unwrap().key.is_empty(), "the kept key stays out of the field"); + } + + fn list_settled(h: &mut Harness) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + h.frames(2); + while (h.app.agent_chat.settings.listing.is_some() || h.app.agent_chat.settings.card_listing.is_some()) + && std::time::Instant::now() < deadline + { + std::thread::sleep(std::time::Duration::from_millis(1)); + h.frames(1); + } + assert!(h.app.agent_chat.settings.listing.is_none()); + h.frames(2); + } + + /// The dialog lists an endpoint's models off the window's thread, once per endpoint and key, of + /// what the fields say when they are left and not while they are typed in; a key goes only + /// where it may. A row and a typed model both fill the field, and Add takes either. + #[test] + fn the_add_dialog_lists_an_endpoints_models_once_and_takes_a_row_or_a_typed_model() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().clone(); + open_add(&mut h.app); + h.frames(3); + assert!(requests().is_empty(), "no endpoint chosen yet"); + h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests(), [("http://localhost:11434/v1/models".to_string(), false)]); + h.frames(5); + assert_eq!(requests().len(), 1, "once"); + + h.step(&json!({"click":{"handle":"ai_add:preset"}})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:preset:OpenRouter"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), false))); + + // Typed in: no request until the field is left, which here the flag stands for. + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "http://10.0.0.2:1234/v1".into(); + add.key = "not-a-real-key".into(); + h.frames(5); + assert_eq!(requests().len(), 2, "not while it is typed"); + h.app.agent_chat.settings.add.as_mut().unwrap().list_again = true; + list_settled(&mut h); + assert_eq!( + requests().last().cloned(), + Some(("http://10.0.0.2:1234/v1/models".to_string(), false)), + "no key over plain http to another computer" + ); + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://openrouter.ai/api/v1".into(); + add.list_again = true; + list_settled(&mut h); + assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), true)), "with a key is another listing"); + + // A row and a typed model. + assert!(scenario::handle_at("ai_add:model").is_some()); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + h.frames(3); + assert!(scenario::handle_at("ai_add:model:search").is_some()); + assert!(scenario::handle_at("ai_add:model:group:Vendor").is_some(), "an endpoint's vendors are the groups"); + h.step(&json!({"click":{"handle":"ai_add:model:vendor/big"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/big"); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text":"vendor/own:free"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/own:free"); + assert_eq!(requests().len(), 4, "opening the picker asks nobody again"); + + // A refusal shows in the popup, and opening it again asks again. + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://refused.example/v1".into(); + add.key.clear(); + add.list_again = true; + list_settled(&mut h); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests().len(), 6, "asked again on opening"); + let listing = h.app.agent_chat.settings.add.as_ref().unwrap().listing.clone(); + let (models, note) = listed_for(&h.app.agent_chat.settings.endpoint_models, listing.as_ref()); + assert!(models.is_empty()); + assert!(note.as_deref().is_some_and(|note| note.contains("no such key")), "{note:?}"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(3); + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://openrouter.ai/api/v1".into(); + h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap(); + assert!(h.app.agent_chat.settings.add.is_none()); + assert_eq!(h.app.preferences.agents.last().map(|a| a.model.as_str()), Some("vendor/own:free")); + } + + /// The keychain answers on the listing's thread, not on the window's. + struct KeyOffTheWindow(std::thread::ThreadId); + impl super::super::backend::Secrets for KeyOffTheWindow { + fn get(&self, _: &str) -> Result, String> { + assert_ne!(std::thread::current().id(), self.0); + Ok(Some("not-a-real-key".into())) + } + fn set(&self, _: &str, _: &str) -> Result<(), String> { + Ok(()) + } + fn delete(&self, _: &str) -> Result<(), String> { + Ok(()) + } + } + + /// An endpoint's card has a model row. The page asks nobody; opening the picker lists, with the + /// agent's key from the keychain, and a row or a typed model becomes an idle agent's model. + #[test] + fn the_card_lists_when_its_picker_opens_and_changes_an_idle_endpoints_model() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + h.app.services.secrets = Some(std::sync::Arc::new(KeyOffTheWindow(std::thread::current().id()))); + let seen = listing_http(&mut h); + h.app.preferences.agents.push(AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: Kind::Api, + base_url: "http://localhost:1/v1".into(), + model: "local".into(), + key: true, + ..Default::default() + }); + h.step(&json!({"call":"ui.prefs","params":{"open":"AI"}})).unwrap(); + h.frames(4); + reveal_card_action(&mut h, "prefs:ai_model:api-1").unwrap(); + assert!(scenario::handle_at("prefs:ai_model:api-1").is_some()); + assert!(seen.lock().unwrap().is_empty(), "looking at the page asks nobody"); + + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap(); + list_settled(&mut h); + assert_eq!(*seen.lock().unwrap(), [("http://localhost:1/v1/models".to_string(), true)]); + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:vendor/big"}})).unwrap(); + h.frames(3); + let model = |h: &Harness| h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.clone()); + assert_eq!(model(&h).as_deref(), Some("vendor/big")); + assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/big")); + + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + h.step(&json!({"text":" vendor/own "})).unwrap(); + h.frames(3); + assert!(h.ctx.memory(|m| m.has_focus(egui::Id::new("sc_ai_model:api-1").with("search"))), "the box keeps the focus over Preferences"); + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:custom"}})).unwrap(); + h.frames(3); + assert_eq!(model(&h).as_deref(), Some("vendor/own")); + assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/own")); + assert_eq!(seen.lock().unwrap().len(), 1, "listed once"); + } } diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index ee92a9cff..d57ac6929 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1,6 +1,126 @@ use super::*; use std::sync::mpsc::channel; +fn transcript_clipboard_harness(layout: crate::shell::LayoutMode) -> crate::scenario::Harness { + let mut h = narrow_chat(); + h.app.ui.layout = layout; + h.app.preferences.agent_chat_width = 500.0; + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "Transcript clipboard sentinel".into() }); + h.app.run("solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})).unwrap(); + h.app.run("select.set", json!({"items": [{"type": "body", "name": "Cube"}]})).unwrap(); + h.frames(4); + h +} + +fn transcript_text_position(h: &crate::scenario::Harness) -> egui::Pos2 { + let mut at = None; + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape + && text.galley.text() == "Transcript clipboard sentinel" + { + at = Some(text.pos + egui::vec2(15.0, 7.0)); + } + }); + } + at.expect("the assistant message is visible") +} + +fn transcript_click(h: &mut crate::scenario::Harness, pos: egui::Pos2) { + h.frame_with(vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + ]); + h.frame_with(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }]); +} + +#[test] +fn transcript_copy_and_cut_do_not_touch_the_cad_clipboard() { + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + let mut h = transcript_clipboard_harness(layout); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + assert!(h.ctx.plugin::().lock().has_selection(), "select real label text"); + assert!(!h.ctx.egui_wants_keyboard_input(), "a selectable label is not a text editor"); + // Moving the mouse away does not transfer the keyboard back to the model. + h.frame_with(vec![egui::Event::PointerMoved(egui::pos2(500.0, 500.0))]); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::Copy]); + assert!(h.output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(text) if text == "Transcript")), "copy selected text"); + assert!(h.app.copied_bodies.is_empty(), "{layout:?}: copying text must not copy a CAD body"); + h.frame_with(vec![egui::Event::Cut]); + assert!(h.app.cut.is_empty(), "{layout:?}: cutting read-only text must not cut a CAD body"); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn transcript_paste_does_not_insert_a_previously_copied_body() { + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + let mut h = transcript_clipboard_harness(layout); + h.frame_with(vec![egui::Event::Copy]); + assert!(!h.app.copied_bodies.is_empty(), "prime the real CAD clipboard"); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::Paste("text from another app".into())]); + assert_eq!(h.app.session.model.state().bodies.len(), 1, "{layout:?}: text paste must not paste CAD geometry"); + assert_eq!(h.app.session.undo.len(), undo); + // A deliberate click outside the panel returns ownership to CAD. + transcript_click(&mut h, egui::pos2(700.0, 500.0)); + h.frame_with(vec![egui::Event::Paste("SolidCraft bodies".into())]); + assert_eq!(h.app.session.model.state().bodies.len(), 2, "{layout:?}: CAD paste still works after returning to the model"); + } +} + +#[test] +fn transcript_key_events_do_not_run_cad_shortcuts() { + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + let mut h = transcript_clipboard_harness(layout); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + let key = |key| egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::CTRL | egui::Modifiers::COMMAND, + }; + h.frame_with(vec![key(egui::Key::C)]); + assert!(h.app.copied_bodies.is_empty(), "{layout:?}: key-event copy also belongs to the chat"); + h.frame_with(vec![key(egui::Key::X)]); + assert!(h.app.cut.is_empty(), "{layout:?}: key-event cut also belongs to the chat"); + assert!(crate::edit_clipboard::copy(&mut h.app)); + h.frame_with(vec![key(egui::Key::V)]); + assert_eq!(h.app.session.model.state().bodies.len(), 1, "{layout:?}: key-event paste stays out of CAD"); + // A quick tap can have no modifiers held by the end of the frame. It must not + // fall through to the plain A (Appearance) shortcut while selecting chat text. + h.frame_with(vec![key(egui::Key::A)]); + assert!(h.app.dialog.is_none(), "{layout:?}: selecting text must not open Appearance"); + } +} + +#[test] +fn transcript_shortcut_ownership_ends_when_the_panel_is_hidden() { + for hidden in ["closed", "minimized", "disabled"] { + let mut h = transcript_clipboard_harness(crate::shell::LayoutMode::Floating); + h.frame_with(vec![egui::Event::Copy]); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + match hidden { + "closed" => h.app.agent_chat.open = false, + "minimized" => h.app.preferences.agent_chat_minimized = true, + _ => h.app.preferences.ai_features = false, + } + h.frame_with(vec![egui::Event::Paste("SolidCraft bodies".into())]); + assert_eq!(h.app.session.model.state().bodies.len(), 2, "{hidden}: the invisible panel must not retain CAD keys"); + } +} + fn chat() -> AgentChat { let mut c = AgentChat::default(); c.state = Some(State::Ready); @@ -17,6 +137,8 @@ fn app_with_discovered_login() -> SolveApp { argv: vec!["qwen".into(), "--acp".into()], version: None, login: discover::Login::LooksLoggedIn, + problem: None, + install: "npm install -g @qwen-code/qwen-code", }], ..Default::default() }); @@ -98,6 +220,38 @@ fn agent_login_refresh_returns_to_unverified_discovery() { assert!(!app.agent_chat.settings.tests.contains_key("qwen")); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_sign_in_proven_in_one_tab_holds_in_every_tab() { + // #9293: discovery found no login file before the user signed in from the panel. The chat's + // proof of the sign-in belongs to the window, so a new tab doesn't ask for it again. + let mut app = app_with_discovered_login(); + if let Some(d) = app.agent_chat.detection.as_mut() { + d.found[0].login = discover::Login::NotLoggedIn; + } + assert_eq!(assistant_mark(&app), AssistantMark::NeedsAuth); + app.agent_chat.on_event(Event::Ready { agent: "Qwen Code".into(), images: false }); + assert_eq!(agents::current(&app).unwrap().login, "signed_in"); + + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + assert_eq!(app.agent_chat.state(), State::Off, "a new tab starts its own conversation"); + assert_eq!(agents::current(&app).unwrap().login, "signed_in"); + assert_eq!(assistant_mark(&app), AssistantMark::Ready, "no sign-in mark in the new tab"); + + // Evidence from the new tab is the newest, also back in the first one. + app.agent_chat.running_id = "qwen".into(); + app.agent_chat.on_event(Event::AuthRequired { methods: vec![] }); + crate::documents::switch(&mut app, 0); + assert_eq!(agents::current(&app).unwrap().login, "signed_out"); + app.agent_chat.on_event(Event::Ready { agent: "Qwen Code".into(), images: false }); + + // A replacement design starts a fresh conversation, not a fresh sign-in. + crate::documents::reset_chat(&mut app); + assert_eq!(agents::current(&app).unwrap().login, "signed_in"); + crate::documents::close(&mut app, 0, true); + assert_eq!(agents::current(&app).unwrap().login, "signed_in", "closing a tab keeps the window's evidence"); +} + #[test] fn streamed_text_joins_and_tool_updates_change_their_call() { let mut c = chat(); @@ -504,17 +658,48 @@ fn the_agents_own_questions_are_answered_by_the_mode_or_asked() { PermissionOption { id: "no".into(), name: "Reject".into(), kind: "reject_once".into() }, ] }; - on_permission(&mut app, 1, "mcp__solidcraft__batch".into(), opts()); - assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, .. }) if text.contains("mcp__solidcraft__batch"))); - on_permission(&mut app, 2, "Run ls".into(), opts()); + on_permission(&mut app, 1, "mcp__solidcraft-app__batch".into(), Some("other"), opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, .. }) if text.contains("mcp__solidcraft-app__batch"))); + on_permission(&mut app, 2, "Run ls".into(), None, opts()); assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. }))); let n = app.agent_chat.items.len() - 1; answer_permission(&mut app, n, Some("always")); assert!(agents::always_allowed(&app.preferences, "claude", "Run ls")); - on_permission(&mut app, 3, "Run ls".into(), opts()); + on_permission(&mut app, 3, "Run ls".into(), None, opts()); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "remembered"); } +/// A title that only mentions SolidCraft is no tool of SolidCraft's: in every mode but Allow +/// everything the user is asked, and the mode still answers when it says to. +#[test] +fn a_title_that_mentions_solidcraft_goes_through_the_users_mode() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.running_id = "codex".into(); + let opts = || vec![PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }]; + let titles = [ + ("run solidcraft-cli; ls", Some("execute")), + ("run solidcraft-cli; ls", None), + ("Edit ~/.local/share/solidcraft/agent-chat/work/notes.txt", Some("edit")), + ("mcp__solidcraft__batch", Some("other")), + ("mcp__solidcraft-app__batch", Some("execute")), + ]; + for mode in [agents::Mode::Ask, agents::Mode::Edits] { + app.preferences.agent_permissions.insert("codex".into(), mode); + for (title, kind) in titles { + on_permission(&mut app, 1, title.into(), kind, opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })), "{mode:?}: {title}"); + app.agent_chat.items.clear(); + } + // The chat's own tool stays a single question, the gate's. + on_permission(&mut app, 2, "mcp__solidcraft-app__batch".into(), Some("other"), opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "{mode:?}"); + app.agent_chat.items.clear(); + } + app.preferences.agent_permissions.insert("codex".into(), agents::Mode::All); + on_permission(&mut app, 3, titles[0].0.into(), titles[0].1, opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "Allow everything answers it"); +} + // ---- Messages typed while the agent works ---- use std::sync::Mutex; @@ -561,6 +746,9 @@ impl ChatBackend for Script { fn answer_permission(&mut self, key: u64, option: Option<&str>) { self.calls.lock().unwrap().push(format!("permission: {key} {option:?}")); } + fn set_config_option(&mut self, id: &str, value: &str) { + self.calls.lock().unwrap().push(format!("set_config_option: {id}={value}")); + } fn authenticate(&mut self, _: &str) {} fn shutdown(&mut self, _: bool) {} } @@ -667,7 +855,8 @@ fn a_late_sign_in_retry_or_permission_cannot_restart_a_departed_turn() { crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); script.report(Event::Permission { key: 7, - title: "mcp__solidcraft__batch".into(), + title: "mcp__solidcraft-app__batch".into(), + kind: None, options: vec![PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }], }); ended(&script, "auth"); @@ -681,6 +870,203 @@ fn a_late_sign_in_retry_or_permission_cannot_restart_a_departed_turn() { assert!(app.agent_chat.turn.is_none() && app.agent_chat.queued.is_none()); } +/// Exercise the chat endpoint's gate and the real dispatch paths, including the animated +/// pointer and asynchronous file loads. The scripted backend never needs a model account. +fn chat_tool(app: &mut SolveApp, tx: &Sender, ctx: &egui::Context, method: &str, params: Value) -> Value { + let reply = ask(tx, method, params); + pump_tools(app); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + app.drain_control(ctx); + app.now += 1.0; + crate::agent_cursor::step(app, ctx); + crate::file_load::tick(app, ctx); + app.poll_control_jobs(ctx); + match reply.try_recv() { + Ok(response) => return response, + Err(std::sync::mpsc::TryRecvError::Disconnected) => panic!("the chat's tool reply was dropped"), + Err(std::sync::mpsc::TryRecvError::Empty) => {} + } + assert!(std::time::Instant::now() < deadline, "the chat's tool did not finish"); + std::thread::yield_now(); + } +} + +#[test] +fn an_agents_new_design_keeps_its_conversation_and_continues() { + // #7526: the old reset disconnected the backend inside its own file.new request. + for (method, params, animate) in [ + ("engine.execute", json!({"command": "file.new"}), false), + ("engine.execute", json!({"command": "FILE.NEW"}), false), + ("engine.execute", json!({"command": "file.new"}), true), + ("engine.batch", json!({"commands": [{"command": "file.new"}, boxed(0.0)]}), false), + ("engine.batch", json!({"commands": [{"command": "file.new"}, boxed(0.0)]}), true), + ] { + let (mut app, script, ctx) = app_with_script(); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + app.preferences.ai_permissions = agents::Mode::All; + app.run("solid.box", boxed(0.0)["params"].clone()).unwrap(); + send(&mut app, &ctx, "create another design".into()); + let active = app.agent_chat.turn.as_ref().unwrap().active.clone(); + app.ui.agent_cursor.show = animate; + crate::scenario::publish_handle("toolbar:file.new", egui::pos2(80.0, 100.0)); + crate::scenario::publish_handle("toolbar:solid.box", egui::pos2(100.0, 100.0)); + let response = chat_tool(&mut app, &tx, &ctx, method, params); + assert_eq!(response["ok"], true, "{response}"); + assert!(app.agent_chat.backend.is_some(), "the agent must receive its own replacement's reply"); + assert!(active.load(std::sync::atomic::Ordering::Relaxed)); + assert!(app.agent_chat.items.iter().any(|i| matches!(i, Item::User { text, .. } if text == "create another design"))); + assert!(!script.calls().iter().any(|call| matches!(call.as_str(), "cancel" | "new_session"))); + let response = chat_tool(&mut app, &tx, &ctx, "engine.execute", boxed(30.0)); + assert_eq!(response["ok"], true, "the same agent continues: {response}"); + assert_eq!(app.agent_chat.turn.as_ref().unwrap().changes, 2, "a replacement does not reset the turn's change budget"); + let count = if method == "engine.batch" { 2 } else { 1 }; + assert_eq!(app.session.doc.features.len(), count); + ended(&script, ""); + poll(&mut app, &ctx); + assert_eq!(app.session.undo.len(), 1, "only the new design's edits form this turn's undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.doc.features.is_empty(), "undo must not resurrect the previous design"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_agents_opened_design_keeps_its_conversation_and_undo_ownership() { + for blank in [true, false] { + let dir = std::env::temp_dir().join(format!("solidcraft-chat-open-{}-{blank}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("next.solidcraft"); + let mut next = solidcraft_engine::Session::default(); + next.execute("solid.box", &boxed(100.0)["params"]).unwrap(); + next.execute("file.save_as", &json!({"path": path})).unwrap(); + let (mut app, script, ctx) = app_with_script(); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + app.preferences.ai_permissions = agents::Mode::All; + if !blank { + app.run("solid.box", boxed(0.0)["params"].clone()).unwrap(); + app.run("file.save_as", json!({"path": dir.join("first.solidcraft")})).unwrap(); + } + send(&mut app, &ctx, "open another design and add a box".into()); + let active = app.agent_chat.turn.as_ref().unwrap().active.clone(); + if !blank { + assert_eq!(chat_tool(&mut app, &tx, &ctx, "engine.execute", boxed(20.0))["ok"], true); + assert_eq!(chat_tool(&mut app, &tx, &ctx, "engine.execute", boxed(40.0))["ok"], true); + } + let response = + chat_tool(&mut app, &tx, &ctx, "engine.execute", json!({"command": "doc.open", "params": {"path": path}, "allow_paths": [dir]})); + assert_eq!(response["ok"], true, "{response}"); + assert!(app.agent_chat.backend.is_some(), "opening the file must carry the initiating chat"); + assert!(active.load(std::sync::atomic::Ordering::Relaxed)); + assert_eq!(app.docs.count(), if blank { 1 } else { 2 }); + if !blank { + let response = chat_tool( + &mut app, + &tx, + &ctx, + "engine.execute", + json!({ + "command": "doc.open", "params": {"path": dir.join("first.solidcraft")}, "allow_paths": [dir] + }), + ); + assert_eq!(response["ok"], false, "another tab must keep its own conversation: {response}"); + assert!(response["error"].as_str().unwrap().contains("already open in another tab")); + assert_eq!(app.docs.active, 1); + } + assert_eq!(chat_tool(&mut app, &tx, &ctx, "engine.execute", boxed(130.0))["ok"], true); + assert_eq!(chat_tool(&mut app, &tx, &ctx, "engine.execute", boxed(150.0))["ok"], true); + assert_eq!(app.session.doc.features.len(), 3); + ended(&script, ""); + poll(&mut app, &ctx); + assert!(!script.calls().iter().any(|call| matches!(call.as_str(), "cancel" | "new_session"))); + assert_eq!(app.session.undo.len(), 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc.features.len(), 1, "the opened design's existing body survives undo"); + if !blank { + crate::documents::switch(&mut app, 0); + assert_eq!(app.session.doc.features.len(), 3); + assert_eq!(app.session.undo.len(), 2, "the first design keeps its own grouped agent edits"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc.features.len(), 1); + assert!(app.agent_chat.backend.is_none(), "the endpoint moved with the conversation"); + crate::documents::switch(&mut app, 1); + assert!(app.agent_chat.backend.is_some()); + } + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[test] +fn an_agents_failed_new_design_batch_restores_its_undo_boundary() { + let (mut app, script, ctx) = app_with_script(); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + app.preferences.ai_permissions = agents::Mode::All; + app.run("solid.box", boxed(0.0)["params"].clone()).unwrap(); + send(&mut app, &ctx, "try another design".into()); + assert_eq!(chat_tool(&mut app, &tx, &ctx, "engine.execute", boxed(20.0))["ok"], true); + let before = app.session.doc.clone(); + let response = chat_tool( + &mut app, + &tx, + &ctx, + "engine.batch", + json!({"commands": [ + {"command": "file.new"}, + {"command": "sketch.line", "params": {"points": [[0, 0], [10, 10]]}} + ]}), + ); + assert_eq!(response["result"]["completed"], 1, "the new design ran before the failure: {response}"); + assert_eq!(response["result"]["rolled_back"], true); + assert!(Arc::ptr_eq(&app.session.doc, &before)); + assert!(app.agent_chat.backend.is_some()); + assert_eq!(chat_tool(&mut app, &tx, &ctx, "engine.execute", boxed(40.0))["ok"], true); + ended(&script, ""); + poll(&mut app, &ctx); + assert_eq!(app.session.undo.len(), 2, "edits before and after the failed batch share one turn"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc.features.len(), 1); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_agents_cancelled_open_cannot_replace_the_design_later() { + let dir = std::env::temp_dir().join(format!("solidcraft-chat-cancel-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("next.solidcraft"); + solidcraft_engine::Session::default().execute("file.save_as", &json!({"path": path})).unwrap(); + let (mut app, script, ctx) = app_with_script(); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + app.preferences.ai_permissions = agents::Mode::All; + app.run("solid.box", boxed(0.0)["params"].clone()).unwrap(); + let original = app.session.doc.clone(); + send(&mut app, &ctx, "open another design".into()); + let (started_tx, started_rx) = channel(); + let (release_tx, release_rx) = channel(); + app.file_load.worker_gate = Some((started_tx, release_rx)); + let reply = ask(&tx, "engine.execute", json!({"command": "doc.open", "params": {"path": path}, "allow_paths": [dir]})); + pump_tools(&mut app); + app.drain_control(&ctx); + started_rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + cancel(&mut app); + ended(&script, "cancelled"); + poll(&mut app, &ctx); + release_tx.send(()).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !app.file_load.idle() && std::time::Instant::now() < deadline { + crate::file_load::tick(&mut app, &ctx); + std::thread::yield_now(); + } + assert!(app.file_load.idle()); + assert_eq!(reply.try_recv().unwrap()["ok"], false, "a stopped turn cannot finish its pending open"); + assert!(Arc::ptr_eq(&app.session.doc, &original)); + assert_eq!(app.docs.count(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn programmatic_replacement_clears_the_conversation_and_invalidates_its_requests() { for command in ["file.new", "FILE.NEW"] { @@ -899,6 +1285,51 @@ fn stop_keeps_the_queue() { assert!(app.agent_chat.pending.is_empty()); } +#[test] +fn an_unresponsive_cancel_exit_keeps_the_queue_and_completed_changes() { + let (mut app, script, ctx) = app_with_script(); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + let before = app.session.doc.clone(); + send(&mut app, &ctx, "two boxes".into()); + let replies: Vec<_> = [0.0, 20.0].into_iter().map(|x| ask(&tx, "engine.execute", boxed(x))).collect(); + frame(&mut app); + for reply in replies { + assert_eq!(reply.recv_timeout(std::time::Duration::from_secs(30)).unwrap()["ok"], true); + } + let completed = app.session.doc.clone(); + let statuses = [Some(ToolStatus::Completed), Some(ToolStatus::Failed), Some(ToolStatus::Pending), Some(ToolStatus::InProgress), None]; + for (id, status) in statuses.into_iter().enumerate() { + script.report(Event::Tool { id: id.to_string(), title: Some("search".into()), kind: None, status, input: None, output: None }); + } + poll(&mut app, &ctx); + send(&mut app, &ctx, "later".into()); + cancel(&mut app); + script.report(Event::Exited { tail: vec![tr("ui.agent_chat_cancel_timeout").to_string()] }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.state(), State::Exited); + assert!(app.agent_chat.backend.is_none() && app.agent_chat.turn.is_none()); + assert_eq!(texts(&app), ["later"]); + assert_eq!(script.prompts().len(), 1, "disconnect must not send the queue"); + assert!(Arc::ptr_eq(&app.session.doc, &completed), "completed changes stay in the design"); + let statuses: Vec<_> = app + .agent_chat + .items + .iter() + .filter_map(|item| match item { + Item::Tool { status, .. } => Some(*status), + _ => None, + }) + .collect(); + assert_eq!( + statuses, + [Some(ToolStatus::Completed), Some(ToolStatus::Failed), Some(ToolStatus::Failed), Some(ToolStatus::Failed), Some(ToolStatus::Failed)] + ); + let changes = app.agent_chat.items.iter().rposition(|i| matches!(i, Item::Changes { steps: 2, .. })).expect("the completed changes are grouped"); + undo_changes(&mut app, changes); + assert!(Arc::ptr_eq(&app.session.doc, &before), "the completed changes still undo together"); +} + /// Send now: cancel first, the prompt only after the agent has ended the cancelled turn, with a /// note that the previous step was interrupted (shown without it in the conversation). #[test] @@ -1117,11 +1548,138 @@ done let _ = std::fs::remove_dir_all(&dir); } +/// #9811: an agent that offers the standard `systemPrompt` field gets the note in it, on the first +/// session and on the one New chat opens. +#[cfg(unix)] +#[test] +fn an_acp_agent_offering_the_standard_field_gets_the_system_note_in_every_session() { + let dir = std::env::temp_dir().join(format!("sc-agent-chat-note-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = dir.join("received.log"); + let script = r#" +log="$1"; n=0 +while IFS= read -r line; do + printf '%s\n' "$line" >> "$log" + id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"agentCapabilities":{"sessionCapabilities":{"systemPrompt":{}}},"agentInfo":{"name":"fake","version":"1"}}}\n' "$id" ;; + *'"method":"session/new"'*) n=$((n+1)); printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s%s"}}\n' "$id" "$n" ;; + esac +done +"#; + let argv = vec!["sh".to_string(), "-c".to_string(), script.to_string(), "fake-agent".to_string(), log.to_string_lossy().into_owned()]; + let start = backend::StartContext { cwd: dir.clone(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.backend = Some(Box::new(acp_client::AcpBackend::start(&argv, start).unwrap())); + app.agent_chat.state = Some(State::Starting); + let ctx = crate::fonts::test_context(); + let until = |app: &mut SolveApp, done: &dyn Fn(&SolveApp) -> bool| { + let t = std::time::Instant::now(); + while !done(app) { + assert!(t.elapsed() < std::time::Duration::from_secs(20), "timed out"); + poll(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + }; + until(&mut app, &|a| a.agent_chat.state() == State::Ready); + new_chat(&mut app); + until(&mut app, &|a| a.agent_chat.state() == State::Ready); + let sessions: Vec = std::fs::read_to_string(&log) + .unwrap() + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter(|v| v["method"] == "session/new") + .collect(); + assert_eq!(sessions.len(), 2); + for session in &sessions { + assert_eq!(session.pointer("/params/systemPrompt/content/0/text").and_then(Value::as_str), Some(acp::SYSTEM_NOTE)); + } + disconnect(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} + fn models_reply(current: &str) -> Event { let m = |id: &str| acp::ModelInfo { id: id.into(), name: id.to_uppercase(), description: String::new() }; Event::Models { current: current.into(), available: vec![m("fast"), m("smart")] } } +/// An endpoint's listing whose ids read `vendor/model` and whose names (the descriptions here) read +/// `Vendor: Model`, as OpenRouter's, names its providers; the rows then read the model's name with +/// the id as the tooltip. One vendor is one flat list. +#[test] +fn an_endpoints_vendor_named_listing_names_its_providers() { + let m = |id: &str, description: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: description.into() }; + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), Some(("OpenAI".into(), "GPT-6.1 Terra".into()))); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra\nmore")), Some(("OpenAI".into(), "GPT-6.1 Terra".into()))); + assert_eq!(model_provider(&m("gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), None, "no vendor in the id"); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: ")), None, "no name"); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "")), None); + assert_eq!( + model_provider(&m("openai/gpt-6.1-terra", "Provider: Host • current")), + Some(("Host".into(), "openai/gpt-6.1-terra".into())), + "an agent's own word first" + ); + let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("qwen/qwen3.8-flash", "Qwen: Qwen3.8 Flash"), m("free-model", "")]); + assert_eq!( + rows, + [ + ("GPT-6.1 Terra".to_string(), Some("OpenAI".to_string()), "openai/gpt-6.1-terra".to_string()), + ("Qwen3.8 Flash".to_string(), Some("Qwen".to_string()), "qwen/qwen3.8-flash".to_string()), + ("free-model".to_string(), Some(tr("ui.agent_chat_provider_other").to_string()), String::new()), + ] + ); + let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("openai/gpt-5.6-luna", "OpenAI: GPT-5.6 Luna")]); + assert_eq!(rows[0], ("openai/gpt-6.1-terra".to_string(), None, "OpenAI: GPT-6.1 Terra".to_string()), "one vendor is one flat list"); +} + +/// Models from several providers fold under their providers inside the picker: the current model's +/// provider is open and the others folded; a header opens or folds its group; a typed search opens +/// every group with a match but one folded by hand; the provider asked for over the control channel +/// is open at the next opening. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_header_groups_models_by_provider_and_folds_them() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "claude".into(); + let m = |id: &str, name: &str| acp::ModelInfo { id: id.into(), name: name.into(), description: String::new() }; + script.report(Event::Models { + current: "a".into(), + available: vec![m("a", "Host · Alpha"), m("c", "Nous Portal · Gamma"), m("b", "Host · Beta"), m("d", "Nous Portal · Delta")], + }); + h.frames(4); + assert!(handle_at("agent_chat:provider").is_none(), "no provider drop-down of its own"); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:group:Host").is_some() && handle_at("agent_chat:model:group:Nous Portal").is_some()); + assert!(handle_at("agent_chat:model:a").is_some() && handle_at("agent_chat:model:b").is_some(), "the current model's provider is open"); + assert!(handle_at("agent_chat:model:c").is_none() && handle_at("agent_chat:model:d").is_none(), "the other provider is folded"); + h.step(&json!({"click": {"handle": "agent_chat:model:group:Nous Portal"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:c").is_some(), "a header opens its group"); + h.step(&json!({"click": {"handle": "agent_chat:model:group:Host"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:a").is_none(), "and folds it"); + h.step(&json!({"text": "ta"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:b").is_none(), "a fold made by hand stays while searching, Beta or not"); + assert!(handle_at("agent_chat:model:d").is_some() && handle_at("agent_chat:model:c").is_none(), "Delta matches, Gamma does not"); + h.step(&json!({"click": {"handle": "agent_chat:model:d"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: d"]); + assert_eq!(h.app.agent_chat.model, "d"); + assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it"); + + control(&mut h.app, &h.ctx, &json!({"provider": "Host"})).unwrap(); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:a").is_some(), "the provider asked for is open"); + assert!(handle_at("agent_chat:model:d").is_some(), "and the current model's"); +} + /// Choosing a model tells the agent, shows it as current and remembers it for this agent; a model /// the agent did not offer is ignored. #[test] @@ -1145,6 +1703,399 @@ fn choosing_a_model_sets_it_and_remembers_it() { assert_eq!(app.agent_chat.models.len(), 2, "the list stays"); } +/// A scripted endpoint: its agent is configured, and it is running with these models. +#[cfg(not(target_arch = "wasm32"))] +fn endpoint_with_script() -> (SolveApp, Script, egui::Context) { + let (mut app, script, ctx) = app_with_script(); + let endpoint = "http://localhost:11434/v1"; + app.agent_chat.running_id = "api-1".into(); + app.agent_chat.running_endpoint = endpoint.into(); + app.preferences.agents.push(agents::AgentConfig { + id: "api-1".into(), + kind: agents::Kind::Api, + base_url: endpoint.into(), + model: "fast".into(), + ..Default::default() + }); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + (app, script, ctx) +} + +/// A typed model goes straight to an endpoint, joins the list for the next connection and becomes +/// the agent's default. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_typed_model_goes_to_an_endpoint_and_is_remembered() { + let (mut app, script, _ctx) = endpoint_with_script(); + assert!(custom_models_accepted(&app)); + assert!(set_custom_model(&mut app, " openai/gpt-x ")); + assert_eq!(script.calls(), ["set_model: openai/gpt-x"]); + assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("openai/gpt-x")); + assert_eq!(app.agent_chat.models_cache.get("http://localhost:11434/v1").and_then(|l| l.first()).map(|m| m.id.as_str()), Some("openai/gpt-x")); + assert_eq!(app.preferences.agents.iter().find(|a| a.id == "api-1").unwrap().model, "openai/gpt-x"); + assert_eq!(app.preferences.agent_models.get("api-1").map(String::as_str), Some("openai/gpt-x")); + assert_eq!(status(&app)["model"], "openai/gpt-x"); + assert_eq!(status(&app)["customModels"], true); + let listed = app.agent_chat.models.len(); + assert!(set_custom_model(&mut app, "smart")); + assert_eq!(app.agent_chat.models.len(), listed, "a listed id goes the usual way"); + assert_eq!(app.agent_chat.model, "smart"); +} + +/// A typed model is only sent when it could be a model at all, and the list stays within its cap. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_typed_model_that_cannot_be_one_is_not_sent() { + let (mut app, script, _ctx) = endpoint_with_script(); + for text in ["", " ", "x".repeat(MODEL_ID_CAP + 1).as_str(), "bell\u{7}", "two\nlines"] { + assert!(!set_custom_model(&mut app, text), "{text:?}"); + } + assert!(script.calls().is_empty()); + assert!(set_custom_model(&mut app, &"x".repeat(MODEL_ID_CAP))); + app.agent_chat.models = + (0..MODEL_LIST_CAP).map(|i| acp::ModelInfo { id: format!("m{i}"), name: String::new(), description: String::new() }).collect(); + assert!(set_custom_model(&mut app, "one-more")); + assert_eq!(app.agent_chat.models.len(), MODEL_LIST_CAP); + assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("one-more")); +} + +/// An agent with a model option gets a typed model through it. Nothing changes until it answers, +/// and a refusal leaves the old model with the agent's reason in the chat. +#[test] +fn a_typed_model_is_sent_to_a_modern_agent_and_a_rejection_keeps_the_old_one() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "modern".into(); + script.report(Event::ConfigOptions(modern_options("fast"))); + poll(&mut app, &ctx); + assert!(custom_models_accepted(&app)); + assert!(set_custom_model(&mut app, "claude-x")); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=claude-x"]); + assert!(app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert!(!set_custom_model(&mut app, "claude-y"), "one request at a time"); + + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Err("no such model".into()) }); + poll(&mut app, &ctx); + assert!(!app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert!( + app.agent_chat + .items + .iter() + .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("claude-x") && text.contains("no such model"))), + "the notice names the model and the reason" + ); + assert!(!app.preferences.agent_models.contains_key("modern")); + assert_eq!(app.agent_chat.typed_model, None); + + // An agent that takes it says so in its snapshot, and that is what is remembered. + assert!(set_custom_model(&mut app, "claude-x")); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("claude-x")) }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "claude-x"); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("claude-x")); +} + +/// A legacy agent shows a typed model at once; a refusal puts everything back and says why. +#[test] +fn a_typed_model_is_sent_to_a_legacy_agent_and_a_rejection_reverts_it() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "claude".into(); + app.preferences.agent_models.insert("claude".into(), "fast".into()); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert!(set_custom_model(&mut app, "zzz")); + assert_eq!(script.calls(), ["set_model: zzz"]); + assert_eq!(app.agent_chat.model, "zzz"); + assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("zzz")); + + script.report(Event::ModelRejected("no such model".into())); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.agent_chat.models.iter().map(|m| m.id.as_str()).collect::>(), ["fast", "smart"]); + assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("fast")); + assert!( + app.agent_chat + .items + .iter() + .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("zzz") && text.contains("no such model"))), + "the notice names the model and the reason" + ); + + // A listed model the agent refuses goes back too, and nothing was remembered before it here. + app.preferences.agent_models.remove("claude"); + set_model(&mut app, "smart"); + script.report(Event::ModelRejected("x".repeat(MODELS_NOTE_CAP * 2))); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.agent_chat.models.len(), 2); + assert!(!app.preferences.agent_models.contains_key("claude")); + let Some(Item::Notice { text, .. }) = app.agent_chat.items.last() else { panic!("no notice") }; + assert_eq!(text.chars().count(), MODELS_NOTE_CAP); + + // The agent confirming its model ends the wait: a later refusal has nothing to put back. + assert!(set_custom_model(&mut app, "zzz")); + script.report(Event::Models { current: "zzz".into(), available: vec![] }); + script.report(Event::ModelRejected("late".into())); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "zzz"); +} + +/// An agent that lists no models and has no model option cannot be sent one; a stopped one neither. +#[test] +fn an_agent_without_models_takes_no_typed_model() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "other".into(); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + assert!(!custom_models_accepted(&app)); + assert_eq!(status(&app)["customModels"], false); + assert!(!set_custom_model(&mut app, "zzz")); + assert!(script.calls().is_empty()); + script.report(Event::ConfigOptions(vec![])); + poll(&mut app, &ctx); + assert!(!custom_models_accepted(&app), "its options name no model"); + + let (mut app, script, ctx) = app_with_script(); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert!(custom_models_accepted(&app)); + app.agent_chat.backend = None; + assert!(!custom_models_accepted(&app)); + assert!(!set_custom_model(&mut app, "zzz")); +} + +/// The control channel's `model`: a listed one as before, an unlisted one when the agent takes +/// typed models, otherwise ignored as before. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_control_channel_sends_an_unlisted_model_where_it_can_go() { + let (mut app, script, ctx) = endpoint_with_script(); + let reply = control(&mut app, &ctx, &json!({"model": "smart"})).unwrap(); + assert_eq!(reply["model"], "smart"); + let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap(); + assert_eq!(reply["model"], "unlisted"); + assert_eq!(reply["customModels"], true); + assert_eq!(reply["modelsNote"], Value::Null); + assert_eq!(script.calls(), ["set_model: smart", "set_model: unlisted"]); + + let (mut app, script, ctx) = app_with_script(); + let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap(); + assert_eq!(reply["model"], ""); + assert_eq!(reply["customModels"], false); + assert!(script.calls().is_empty()); +} + +/// The header's picker on an agent that lists models: it searches, a row chooses, and what was typed +/// can be chosen too. The control and the popup stay in a narrow chat's window. +#[test] +fn the_header_model_picker_searches_and_takes_a_typed_model() { + use crate::scenario::{handle_at, rect_of}; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "claude".into(); + script.report(models_reply("fast")); + h.frames(4); + let panel = rect_of("agent_chat:panel").expect("the panel"); + let control = rect_of("agent_chat:model").expect("the picker"); + assert!(control.left() >= panel.left() && control.right() <= panel.right(), "{control:?} in {panel:?}"); + assert!(handle_at("agent_chat:model:search").is_none(), "closed"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + for name in ["search", "fast", "smart"] { + assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}"); + } + assert!(handle_at("agent_chat:model:custom").is_none(), "nothing typed"); + let search = rect_of("agent_chat:model:search").expect("the search box"); + assert!(search.left() >= 0.0 && search.right() <= 1600.0, "inside the harness's window: {search:?}"); + + h.step(&json!({"text": "SMA"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:fast").is_none() && handle_at("agent_chat:model:smart").is_some()); + assert!(handle_at("agent_chat:model:custom").is_some(), "the typed text is not a listed model"); + h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(h.app.agent_chat.model, "smart"); + assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]); + assert_eq!(h.app.agent_chat.model, "zzz"); + disconnect(&mut h.app); +} + +/// The picker on an agent with a model option goes by the same names. A row and a typed model both +/// go through the option, and other options stay plain dropdowns. +#[test] +fn the_header_model_option_searches_and_takes_a_typed_model() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + script.report(Event::ConfigOptions(modern_options("fast"))); + h.frames(4); + assert_eq!(handle_at("agent_chat:model"), handle_at("agent_chat:config:some.provider.model")); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + for name in ["search", "fast", "smart"] { + assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}"); + assert_eq!(handle_at(&format!("agent_chat:model:{name}")), handle_at(&format!("agent_chat:config:some.provider.model:{name}"))); + } + h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=smart"]); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + h.frames(3); + assert_eq!(h.app.agent_chat.model, "smart"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:custom").is_some()); + h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls().last().map(String::as_str), Some("set_config_option: some.provider.model=zzz")); + assert_eq!(h.app.agent_chat.model, "smart", "not until the agent says so"); + assert!(h.app.agent_chat.config_pending); + disconnect(&mut h.app); +} + +/// Nothing typed can be chosen where it could not be sent, and the reason a listing failed shows +/// in the popup. +#[test] +fn the_header_model_picker_offers_no_typed_model_it_cannot_send_and_shows_why_listing_failed() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.models = vec![acp::ModelInfo { id: "fast".into(), name: "fast".into(), description: String::new() }]; + h.app.agent_chat.model = "fast".into(); + h.app.agent_chat.models_note = Some("Couldn't list models: offline".into()); + h.frames(4); + assert!(!custom_models_accepted(&h.app)); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(h.widget("Couldn't list models: offline").is_some()); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:search").is_some()); + assert!(handle_at("agent_chat:model:custom").is_none()); +} + +/// A running endpoint's card uses the chat's list and changes the chat's model. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_card_of_a_running_endpoint_changes_the_chats_model() { + use crate::scenario::handle_at; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "api-1".into(); + h.app.agent_chat.running_endpoint = "http://localhost:1/v1".into(); + h.app.preferences.agents.push(agents::AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: agents::Kind::Api, + base_url: "http://localhost:1/v1".into(), + model: "fast".into(), + ..Default::default() + }); + script.report(models_reply("fast")); + h.step(&json!({"call": "ui.prefs", "params": {"open": "AI"}})).unwrap(); + h.frames(4); + // The permission cards put endpoint controls below the fixed page's viewport. + for _ in 0..32 { + let at = handle_at("prefs:ai_model:api-1").unwrap(); + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + if body.contains(at) { + break; + } + h.call("ui.scroll", json!({"x":body.center().x,"y":body.center().y,"delta":if at.y < body.top() {100} else {-100}})); + h.frames(30); + } + assert!(crate::scenario::rect_of("prefs:page_body").unwrap().contains(handle_at("prefs:ai_model:api-1").unwrap())); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + assert!(handle_at("prefs:ai_model:api-1:smart").is_some()); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(h.app.agent_chat.model, "smart"); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]); + assert_eq!(h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.as_str()), Some("zzz")); + disconnect(&mut h.app); +} + +/// A listing that fails says why and leaves last time's list, with the configured model in it; the +/// next connection starts without the note. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_listing_that_fails_says_why_and_keeps_the_list_of_last_time() { + let (mut app, script, ctx) = app_with_script(); + let endpoint = "http://localhost:11434/v1"; + app.agent_chat.running_endpoint = endpoint.into(); + script.report(Event::ModelsNote(None)); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.models_note, None); + let ids = |app: &SolveApp| app.agent_chat.models.iter().map(|m| m.id.clone()).collect::>(); + assert_eq!(ids(&app), ["fast", "smart"]); + + let only = |id: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: String::new() }; + script.report(Event::ModelsNote(Some("x".repeat(MODELS_NOTE_CAP + 10)))); + script.report(Event::Models { current: "local".into(), available: vec![only("local")] }); + poll(&mut app, &ctx); + let note = app.agent_chat.models_note.clone().unwrap(); + assert!(note.starts_with(&trf("ui.agent_chat_models_failed", &[("error", "x")])), "{note}"); + assert_eq!(note.chars().count(), MODELS_NOTE_CAP); + assert_eq!(ids(&app), ["local", "fast", "smart"]); + assert_eq!(app.agent_chat.model, "local"); + assert_eq!(app.agent_chat.models_cache.get(endpoint).map(Vec::len), Some(2), "the failed listing is not remembered"); + + script.report(Event::ModelsNote(Some("again".into()))); + script.report(Event::Models { current: "fast".into(), available: vec![only("fast")] }); + poll(&mut app, &ctx); + assert_eq!(ids(&app), ["local", "fast", "smart"], "a model already listed is not listed twice"); + + // A real listing on an endpoint that cannot be reached. + let mut app = app_with_endpoints(); + app.agent_chat.models_note = Some("from before".into()); + app.agent_chat.agent_id = Some("api-1".into()); + connect(&mut app, &ctx); + assert_eq!(app.agent_chat.models_note, None); + let start = std::time::Instant::now(); + while app.agent_chat.models.is_empty() && start.elapsed() < std::time::Duration::from_secs(10) { + poll(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(app.agent_chat.models_note.as_deref().is_some_and(|note| note.contains("offline")), "{:?}", app.agent_chat.models_note); + assert_eq!(ids(&app), ["m"]); + assert!(models_shown(&app)); + disconnect(&mut app); +} + /// The next session puts back the model chosen last time, when the agent offers it. #[test] fn the_remembered_model_is_set_on_the_next_session() { @@ -1239,6 +2190,367 @@ fn hostile_provider_names_are_bounded() { assert_eq!(model_provider(&m("model".into(), "Provider: A\nsecond line • current")).map(|p| p.0), Some("A".into())); } +fn modern_options(model: &str) -> Vec { + vec![ + acp::ConfigOption { + id: "some.provider.model".into(), + name: "Model".into(), + description: String::new(), + category: "model".into(), + current_value: model.into(), + options: ["fast", "smart"] + .into_iter() + .map(|v| acp::ConfigChoice { value: v.into(), name: v.into(), description: String::new(), group: None }) + .collect(), + }, + acp::ConfigOption { + id: "custom-mode-key".into(), + name: "Mode".into(), + description: String::new(), + category: "mode".into(), + current_value: "ask".into(), + options: ["ask", "plan"] + .into_iter() + .map(|v| acp::ConfigChoice { value: v.into(), name: v.into(), description: String::new(), group: None }) + .collect(), + }, + ] +} + +#[test] +fn modern_snapshots_replace_provider_choices_and_ignore_legacy_updates() { + let (mut app, script, ctx) = app_with_script(); + script.report(Event::Models { current: "plain".into(), available: provider_models() }); + poll(&mut app, &ctx); + set_model_provider(&mut app, "Host"); + script.report(Event::ConfigOptions(modern_options("smart"))); + script.report(Event::Models { current: "plain".into(), available: provider_models() }); + script.report(Event::Modes { current: "old-mode".into(), available: vec![("old-mode".into(), "Old mode".into())] }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "smart"); + assert_eq!(app.agent_chat.mode, "ask"); + assert!(app.agent_chat.model_provider.is_none()); + assert!(model_providers(&app).is_empty()); + assert_eq!(listed_models(&app).into_iter().map(|(m, _)| m.id).collect::>(), ["fast", "smart"]); + script.report(Event::ConfigOptions(vec![])); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.config_options, Some(vec![])); + assert!(app.agent_chat.models.is_empty() && app.agent_chat.modes.is_empty()); + set_model(&mut app, "plain"); + set_mode(&mut app, "old-mode"); + assert!(script.calls().is_empty(), "an empty modern snapshot never falls back to stale legacy choices"); +} + +#[test] +fn modern_acknowledgements_stay_with_their_document_without_resuming_its_queue() { + let (mut app, first, ctx) = app_with_script(); + app.agent_chat.running_id = "first-modern".into(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + app.preferences.agent_models.insert("first-modern".into(), "smart".into()); + new_chat(&mut app); + send(&mut app, &ctx, "first request".into()); + first.report(Event::ConfigOptions(modern_options("fast"))); + first.report(Event::Ready { agent: "first-modern".into(), images: false }); + poll(&mut app, &ctx); + assert!(app.agent_chat.config_pending && app.agent_chat.queued.is_some()); + + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + assert!(app.agent_chat.config_options.is_none() && !app.agent_chat.config_pending); + let second = Script::default(); + app.agent_chat.backend = Some(Box::new(second.clone())); + app.agent_chat.state = Some(State::Ready); + app.agent_chat.running_id = "second-modern".into(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + set_model(&mut app, "smart"); + first.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + poll(&mut app, &ctx); + assert!(app.agent_chat.config_pending, "the hidden tab's acknowledgement cannot unlock this one"); + assert_eq!(app.agent_chat.model, "fast"); + assert!(!app.preferences.agent_models.contains_key("second-modern")); + second.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + poll(&mut app, &ctx); + assert_eq!(app.preferences.agent_models.get("second-modern").map(String::as_str), Some("smart")); + + crate::documents::switch(&mut app, 0); + assert!(app.agent_chat.config_pending, "pending configuration belongs to the conversation"); + poll(&mut app, &ctx); + assert!(!app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "smart"); + assert_eq!(app.preferences.agent_models.get("first-modern").map(String::as_str), Some("smart")); + assert_eq!(texts(&app), ["first request"]); + assert!(app.agent_chat.queued.is_none() && app.agent_chat.stopped); + assert!(first.prompts().is_empty() && second.prompts().is_empty(), "a late configuration reply cannot resume a departed tab's prompt"); +} + +#[test] +fn closing_a_pending_modern_chat_preserves_the_surviving_api_endpoint_and_saved_models() { + for close_active in [false, true] { + let (mut app, modern, ctx) = app_with_script(); + app.agent_chat.running_id = "modern".into(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + app.preferences.agent_models.insert("modern".into(), "fast".into()); + set_model(&mut app, "smart"); + assert!(app.agent_chat.config_pending); + + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + let endpoint = "http://127.0.0.1:12345/v1"; + let api = Script::default(); + app.agent_chat.backend = Some(Box::new(api.clone())); + app.agent_chat.state = Some(State::Ready); + app.agent_chat.running_id = "endpoint-agent".into(); + app.agent_chat.running_endpoint = endpoint.into(); + app.preferences.agents.push(agents::AgentConfig { + id: "endpoint-agent".into(), + kind: agents::Kind::Api, + base_url: endpoint.into(), + model: "fast".into(), + ..Default::default() + }); + api.report(models_reply("fast")); + poll(&mut app, &ctx); + set_model(&mut app, "smart"); + let cached = app.agent_chat.models_cache.get(endpoint).cloned().unwrap(); + modern.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + modern.report(Event::ConfigOptions(vec![])); + if close_active { + crate::documents::switch(&mut app, 0); + assert!(app.agent_chat.config_pending); + } + crate::documents::close(&mut app, 0, true); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.running_id, "endpoint-agent"); + assert_eq!(app.agent_chat.running_endpoint, endpoint); + assert!(app.agent_chat.config_options.is_none() && !app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "smart"); + assert_eq!(app.agent_chat.models_cache.get(endpoint), Some(&cached)); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("fast")); + assert_eq!(app.preferences.agent_models.get("endpoint-agent").map(String::as_str), Some("smart")); + assert_eq!(app.preferences.agents.iter().find(|a| a.id == "endpoint-agent").unwrap().model, "smart"); + assert_eq!(api.calls(), ["set_model: smart"], "the closed chat's events cannot reach the surviving backend"); + + // Reusing the same agent in a fresh design must restore only the last confirmed model. + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + assert!(app.agent_chat.config_options.is_none() && !app.agent_chat.config_pending); + let fresh = Script::default(); + app.agent_chat.backend = Some(Box::new(fresh.clone())); + app.agent_chat.state = Some(State::Starting); + app.agent_chat.running_id = "modern".into(); + fresh.report(Event::ConfigOptions(modern_options("fast"))); + fresh.report(Event::Ready { agent: "modern".into(), images: false }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert!(!app.agent_chat.config_pending); + assert!(fresh.calls().is_empty(), "an unacknowledged choice from the closed chat is not restored"); + assert_eq!(app.agent_chat.models_cache.get(endpoint), Some(&cached)); + } +} + +#[test] +fn document_disconnect_paths_clear_modern_configuration_and_pending_requests() { + let assert_cleared = |app: &SolveApp| { + assert!(app.agent_chat.backend.is_none()); + assert!(app.agent_chat.config_options.is_none() && !app.agent_chat.config_pending); + assert!(app.agent_chat.models.is_empty() && app.agent_chat.modes.is_empty()); + assert!(app.agent_chat.model.is_empty() && app.agent_chat.mode.is_empty()); + assert!(app.agent_chat.model_provider.is_none()); + assert_eq!(app.agent_chat.state(), State::Off); + }; + let (mut app, _, _) = app_with_script(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + set_model(&mut app, "smart"); + disconnect(&mut app); + assert_cleared(&app); + + for quitting in [false, true] { + let (mut app, first, ctx) = app_with_script(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + set_model(&mut app, "smart"); + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + app.agent_chat.backend = Some(Box::new(Script::default())); + app.agent_chat.state = Some(State::Ready); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + set_model(&mut app, "smart"); + first.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + if quitting { + shutdown(&mut app); + } else { + app.preferences.ai_features = false; + poll(&mut app, &ctx); + } + assert_cleared(&app); + crate::documents::switch(&mut app, 0); + assert_cleared(&app); + assert!(app.preferences.agent_models.is_empty(), "an unpolled acknowledgement is discarded with its backend"); + } +} + +#[cfg(unix)] +#[test] +fn modern_config_requests_roundtrip_success_rejection_malformed_and_retry() { + let dir = std::env::temp_dir().join(format!("sc-chat-config-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = dir.join("requests.jsonl"); + let script = r#" +log="$1"; n=0 +while IFS= read -r line; do + printf '%s\n' "$line" >> "$log" + id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"agentInfo":{"name":"fake"}}}\n' "$id" ;; + *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s1","configOptions":[{"id":"vendor.model-key","name":"Model","category":"model","type":"select","currentValue":"fast","options":[{"value":"fast","name":"Fast"},{"value":"smart","name":"Smart"}]}]}}\n' "$id" ;; + *'"method":"session/set_config_option"'*) + n=$((n+1)) + case "$n" in + 1|4) v=smart; [ "$n" = 4 ] && v=fast; printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[{"id":"vendor.model-key","name":"Model","category":"model","type":"select","currentValue":"%s","options":[{"value":"fast","name":"Fast"},{"value":"smart","name":"Smart"}]}]}}\n' "$id" "$v" ;; + 2) printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32001,"message":"rejected"}}\n' "$id" ;; + 3) printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[{"type":"select"}]}}\n' "$id" ;; + esac ;; + esac +done +"#; + let argv = vec!["sh".into(), "-c".into(), script.into(), "fake".into(), log.to_string_lossy().into_owned()]; + let (wake_tx, wake_rx) = channel(); + let start = backend::StartContext { + cwd: dir.clone(), + bridge: None, + tools: None, + wake: Box::new(move || { + let _ = wake_tx.send(()); + }), + }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.backend = Some(Box::new(acp_client::AcpBackend::start(&argv, start).unwrap())); + app.agent_chat.running_id = "modern".into(); + app.agent_chat.state = Some(State::Starting); + let ctx = crate::fonts::test_context(); + let until = |app: &mut SolveApp, done: &dyn Fn(&SolveApp) -> bool| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15); + loop { + poll(app, &ctx); + if done(app) { + return; + } + let left = deadline.saturating_duration_since(std::time::Instant::now()); + assert!(!left.is_zero(), "timed out; status={}", status(app)); + wake_rx.recv_timeout(left).expect("backend wake"); + } + }; + until(&mut app, &|a| a.agent_chat.state() == State::Ready); + assert_eq!(app.agent_chat.model, "fast"); + for (value, expected, saved) in [("smart", "smart", "smart"), ("fast", "smart", "smart"), ("smart", "smart", "smart"), ("fast", "fast", "fast")] { + set_model(&mut app, value); + assert!(app.agent_chat.config_pending); + until(&mut app, &|a| !a.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, expected); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some(saved)); + } + disconnect(&mut app); + let requests: Vec = std::fs::read_to_string(&log).unwrap().lines().filter_map(|l| serde_json::from_str(l).ok()).collect(); + let configs: Vec<_> = requests.iter().filter(|v| v["method"] == "session/set_config_option").collect(); + assert_eq!(configs.len(), 4); + assert_eq!( + configs.iter().map(|v| v["params"].clone()).collect::>(), + ["smart", "fast", "smart", "fast"].map(|value| json!({"sessionId":"s1","configId":"vendor.model-key","value":value})) + ); + assert!(!requests.iter().any(|v| v["method"] == "session/set_model")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn modern_controls_route_by_category_and_wait_for_acknowledgement() { + let (mut app, script, _) = app_with_script(); + app.agent_chat.running_id = "modern".into(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + set_model(&mut app, "smart"); + assert!(app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert!(!app.preferences.agent_models.contains_key("modern")); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=smart"]); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + assert!(app.agent_chat.config_pending, "a notification does not acknowledge the request"); + app.agent_chat.on_event(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + assert!(!app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "smart"); + app.preferences.agent_models.insert("modern".into(), app.agent_chat.model.clone()); + set_mode(&mut app, "ask"); + assert_eq!(script.calls().last().map(String::as_str), Some("set_config_option: custom-mode-key=ask")); +} + +#[test] +fn modern_rejection_and_malformed_success_unlock_without_changing_confirmed_value() { + let (mut app, script, _) = app_with_script(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("fast"))); + set_model(&mut app, "smart"); + app.agent_chat.on_event(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Err("rejected".into()) }); + assert!(!app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + set_model(&mut app, "smart"); + app.agent_chat.on_event(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Err("malformed snapshot".into()) }); + assert!(!app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(script.calls().len(), 2); +} + +#[test] +fn modern_saved_model_restore_waits_for_ack_and_manual_confirmation_persists() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "modern".into(); + app.preferences.agent_models.insert("modern".into(), "smart".into()); + script.report(Event::ConfigOptions(modern_options("fast"))); + script.report(Event::Ready { agent: "modern".into(), images: false }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("smart")); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=smart"]); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "smart"); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("smart")); +} + +#[test] +fn modern_model_restore_then_mode_restore_are_acknowledged_before_queued_prompt() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "modern".into(); + app.preferences.agent_models.insert("modern".into(), "smart".into()); + app.agent_chat.restore_mode = Some("plan".into()); + app.agent_chat.queued = Some(("describe the model".into(), false, None, Vec::new())); + script.report(Event::ConfigOptions(modern_options("fast"))); + script.report(Event::Ready { agent: "modern".into(), images: false }); + poll(&mut app, &ctx); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=smart"]); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("smart")); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + poll(&mut app, &ctx); + assert_eq!(script.calls().get(1).map(String::as_str), Some("set_config_option: custom-mode-key=plan")); + assert!(app.agent_chat.queued.is_some(), "prompt waits for mode confirmation"); + let mut confirmed = modern_options("smart"); + confirmed[1].current_value = "plan".into(); + script.report(Event::ConfigOptionFinished { id: "custom-mode-key".into(), result: Ok(confirmed) }); + poll(&mut app, &ctx); + assert!(script.calls().iter().any(|s| s == "prompt: describe the model")); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("smart")); +} + +#[test] +fn invalidated_modern_sessions_do_not_expose_stale_legacy_choices() { + for event in [Event::AuthRequired { methods: vec![] }, Event::Exited { tail: vec![] }] { + let (mut app, _, _) = app_with_script(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("smart"))); + app.agent_chat.config_pending = true; + app.agent_chat.on_event(event); + assert!(app.agent_chat.config_options.is_none() && !app.agent_chat.config_pending); + assert!(app.agent_chat.models.is_empty() && app.agent_chat.modes.is_empty()); + assert!(app.agent_chat.model.is_empty() && app.agent_chat.mode.is_empty()); + } + let (mut app, _, _) = app_with_script(); + app.agent_chat.on_event(Event::ConfigOptions(modern_options("smart"))); + new_chat(&mut app); + assert_eq!(app.agent_chat.restore_mode.as_deref(), Some("ask")); + assert!(app.agent_chat.config_options.is_none() && app.agent_chat.models.is_empty()); +} + /// An agent that reports no models gets no picker; another agent's choice is not applied to it. #[test] fn an_agent_without_models_shows_no_picker() { @@ -1304,6 +2616,63 @@ done let _ = std::fs::remove_dir_all(&dir); } +/// An agent that lists `models` but does not serve the unstable `session/set_model` answers +/// "method not found": the choice stays and no error shows (#9970). Other errors still show, as +/// the refusal of the model they were about. +#[cfg(unix)] +#[test] +fn set_model_method_not_found_shows_no_error() { + let dir = std::env::temp_dir().join(format!("sc-agent-chat-model-unserved-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = dir.join("received.log"); + let script = r#" +log="$1"; n=0 +while IFS= read -r line; do + printf '%s\n' "$line" >> "$log" + id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"agentInfo":{"name":"fake","version":"1"}}}\n' "$id" ;; + *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s1","models":{"currentModelId":"fast","availableModels":[{"modelId":"fast","name":"Fast"},{"modelId":"smart","name":"Smart"}]}}}\n' "$id" ;; + *'"method":"session/set_model"'*) + n=$((n+1)) + if [ "$n" = 1 ]; then printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"\\"Method not found\\": session/set_model"}}\n' "$id" + else printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32001,"message":"model unavailable"}}\n' "$id"; fi ;; + esac +done +"#; + let argv = vec!["sh".to_string(), "-c".to_string(), script.to_string(), "fake-agent".to_string(), log.to_string_lossy().into_owned()]; + let start = backend::StartContext { cwd: dir.clone(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.backend = Some(Box::new(acp_client::AcpBackend::start(&argv, start).unwrap())); + app.agent_chat.state = Some(State::Starting); + app.agent_chat.running_id = "fake".into(); + let ctx = crate::fonts::test_context(); + let errors = |app: &SolveApp| -> Vec { + app.agent_chat.items.iter().filter_map(|i| if let Item::Notice { text, error: true } = i { Some(text.clone()) } else { None }).collect() + }; + let t = std::time::Instant::now(); + while !(app.agent_chat.state() == State::Ready && models_shown(&app)) { + poll(&mut app, &ctx); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "agent not ready: {}", status(&app)); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + set_model(&mut app, "smart"); + set_model(&mut app, "fast"); + // Replies come in order: once the second one's error shows, the first reply was handled too. + let t = std::time::Instant::now(); + let refused = trf("ui.agent_chat_model_rejected", &[("model", "fast"), ("error", "model unavailable")]); + while !errors(&app).contains(&refused) { + poll(&mut app, &ctx); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "no error for the second choice: {:?}", errors(&app)); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(errors(&app), [refused], "method not found is no error to show"); + assert!(app.agent_chat.state().running(), "the chat goes on"); + assert_eq!(std::fs::read_to_string(&log).unwrap().matches("session/set_model").count(), 2); + disconnect(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} + // ---- Files attached to a message ---- /// A folder of files to attach: a picture and a text file. @@ -1542,6 +2911,162 @@ fn narrow_chat() -> crate::scenario::Harness { h } +/// The rows `a_selection_held_at_the_edge_scrolls_and_keeps_its_start` draws that are in view: +/// each row's number, where its text is, and the conversation's view. +fn rows_in_view(h: &crate::scenario::Harness) -> Vec<(usize, egui::Rect, egui::Rect)> { + let mut rows = Vec::new(); + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape + && let Some(n) = text.galley.text().strip_prefix("Parts list row ").and_then(|n| n.parse::().ok()) + { + let at = egui::Rect::from_min_size(text.pos, text.galley.size()); + if clipped.clip_rect.intersects(at) { + rows.push((n, at, clipped.clip_rect)); + } + } + }); + } + rows.sort_by_key(|r| r.0); + rows +} + +/// #11527: a text selection held at the conversation's edge scrolls it, and keeps its start once +/// that has scrolled out of view, so Copy takes the hidden rows too. Resting there with no button +/// down, or after letting go, scrolls nothing. +#[test] +fn a_selection_held_at_the_edge_scrolls_and_keeps_its_start() { + let mut h = narrow_chat(); + for n in 0..80 { + h.app.agent_chat.items.push(Item::Agent { thought: false, text: format!("Parts list row {n}") }); + } + h.frames(4); + let rows = rows_in_view(&h); + let (&(top, _, view), &(last, last_at, _)) = (rows.first().expect("rows in view"), rows.last().expect("rows in view")); + assert_eq!(last, 79, "the conversation shows its end"); + let edge = egui::pos2(last_at.left() + 10.0, view.top() + 4.0); + let press = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.frame_with(vec![egui::Event::PointerMoved(edge)]); + h.frames(20); + assert_eq!(rows_in_view(&h)[0].0, top, "no button down: the pointer at the edge scrolls nothing"); + + // Start the selection at the end of the last row and hold it at the top edge. + let start = last_at.right_center() - egui::vec2(1.0, 0.0); + h.frame_with(vec![egui::Event::PointerMoved(start), press(start, true)]); + h.frame_with(vec![egui::Event::PointerMoved(edge)]); + for _ in 0..600 { + if !rows_in_view(&h).iter().any(|r| r.0 == last) { + break; + } + h.frame(); + } + let rows = rows_in_view(&h); + assert!(!rows.iter().any(|r| r.0 == last), "holding the selection at the top scrolls the last row out of view"); + let reached = rows[0].0; + assert!(reached < top, "row {reached} is in view, it was {top}"); + h.frame_with(vec![press(edge, false)]); + let after = rows_in_view(&h)[0].0; + h.frames(20); + assert_eq!(rows_in_view(&h)[0].0, after, "letting go stops the scrolling"); + assert!(h.ctx.plugin::().lock().has_selection(), "the selection keeps its start out of view"); + + h.frame_with(vec![egui::Event::Copy]); + let copied = h + .output + .commands + .iter() + .find_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text.clone()) } else { None }) + .expect("Copy takes the selection"); + // The selection's moving end is under the pointer, in the first row or two in view. + for n in [reached + 2, 78] { + assert!(copied.contains(&format!("Parts list row {n}\n")), "row {n} is copied whole: {copied:?}"); + } + assert!(copied.trim_end().ends_with("Parts list row 79"), "the selection ends where it started, out of view: {copied:?}"); +} + +/// #11527: only a drag towards the edge scrolls. Holding a press on the line at the top edge, a +/// double click there, or a drag from there into the conversation leaves it where it is. +#[test] +fn a_press_at_the_edge_without_a_drag_towards_it_scrolls_nothing() { + let mut h = narrow_chat(); + // One paragraph taller than the conversation: every point in view is on its text. + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "Bill of materials ".repeat(400) }); + h.frames(4); + // Where the answer's text starts, the conversation's view, and the first line wholly in view + // (egui itself scrolls a pressed line that is cut off at the edge into view). + let answer = |h: &crate::scenario::Harness| { + let mut found = None; + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape + && text.galley.text().starts_with("Bill of materials") + && clipped.clip_rect.intersects(egui::Rect::from_min_size(text.pos, text.galley.size())) + { + let line = text.galley.rows.iter().map(|r| r.rect().translate(text.pos.to_vec2())).find(|r| r.top() >= clipped.clip_rect.top()); + found = Some((text.pos.y, clipped.clip_rect, line.expect("a line wholly in view"))); + } + }); + } + found.expect("the answer is in view") + }; + let (rest, view, line) = answer(&h); + let press = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let edge = egui::pos2(view.left() + 40.0, line.center().y); + assert!(edge.y < view.top() + 32.0, "the first line in view is by the edge"); + h.frame_with(vec![egui::Event::PointerMoved(edge), press(edge, true)]); + h.frames(30); + assert_eq!(answer(&h).0, rest, "a press held at the edge scrolls nothing"); + h.frame_with(vec![press(edge, false)]); + for _ in 0..2 { + h.frame_with(vec![press(edge, true)]); + h.frame_with(vec![press(edge, false)]); + } + h.frames(10); + assert_eq!(answer(&h).0, rest, "a double click at the edge scrolls nothing"); + let inside = edge + egui::vec2(0.0, 20.0); + h.frame_with(vec![egui::Event::PointerMoved(edge), press(edge, true)]); + h.frame_with(vec![egui::Event::PointerMoved(inside)]); + h.frames(30); + assert_eq!(answer(&h).0, rest, "a drag from the edge into the conversation scrolls nothing"); + h.frame_with(vec![press(inside, false)]); + // Towards the edge it does. + let middle = view.center(); + h.frame_with(vec![egui::Event::PointerMoved(middle), press(middle, true)]); + h.frame_with(vec![egui::Event::PointerMoved(edge)]); + h.frames(30); + assert!(answer(&h).0 > rest, "a drag to the top edge scrolls the answer down"); + h.frame_with(vec![press(edge, false)]); +} + +/// #10172: before a connection, what the panel draws under the agent switcher (the Agent row +/// with Add agent and Refresh) keeps the panel's side margin, docked and floating: nothing starts +/// at the panel's edge or is cut off at the other one. +#[test] +fn the_agent_list_keeps_the_panels_side_margin() { + use crate::shell::LayoutMode; + for layout in [LayoutMode::Docked, LayoutMode::Floating] { + let mut h = narrow_chat(); + h.app.ui.layout = layout; + h.frames(3); + h.frame(); + let panel = crate::scenario::rect_of("agent_chat:panel").expect("the panel"); + let mut texts = Vec::new(); + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |s| { + if let egui::Shape::Text(t) = s { + texts.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.rect.size()))); + } + }); + } + let at = |label: &str| texts.iter().find(|(text, r)| text == label && panel.contains(r.center())).map(|(_, r)| *r); + let margin = crate::theme::Tokens::get().space_12 - 0.5; + let agent = at(tr("ui.agent_chat_pick")).expect("the Agent row"); + assert!(agent.left() >= panel.left() + margin, "{layout:?}: Agent at {agent:?} in {panel:?}"); + let refresh = at(tr("ui.agent_chat_refresh")).expect("Refresh"); + assert!(refresh.right() <= panel.right() - margin, "{layout:?}: Refresh at {refresh:?} in {panel:?}"); + } +} + /// Every chip and the text box sit inside the panel. fn assert_inside_the_panel(chips: usize) { use crate::scenario::rect_of; @@ -1858,7 +3383,7 @@ fn box_selection(app: &mut SolveApp) -> Vec { app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).expect("a box"); let face = app.session.execute("model.faces", &json!({"body": "Body1"})).expect("faces")["faces"][0].clone(); let edge = app.session.execute("model.edges", &json!({"body": "Body1"})).expect("edges")["edges"][0].clone(); - let at = |v: &Value| solidcraft_engine::geom::Vec3::new(v[0].as_f64().unwrap_or(0.0), v[1].as_f64().unwrap_or(0.0), v[2].as_f64().unwrap_or(0.0)); + let at = |v: &Value| solidcore_record::Vec3::new(v[0].as_f64().unwrap_or(0.0), v[1].as_f64().unwrap_or(0.0), v[2].as_f64().unwrap_or(0.0)); vec![ Sel::Face { body: "Body1".into(), index: face["index"].as_u64().unwrap_or(0) as usize, point: at(&face["point"]) }, Sel::Edge { body: "Body1".into(), index: edge["index"].as_u64().unwrap_or(0) as usize, point: at(&edge["mid"]) }, @@ -1936,8 +3461,8 @@ fn a_huge_selection_is_counted_not_dropped_silently() { assert_eq!((both.items.len(), both.total()), (context::MAX_ITEMS, 200)); // Unknown bodies, faces and features are described by what is known, without panicking. let odd = [ - Sel::Face { body: "Nope".into(), index: usize::MAX, point: solidcraft_engine::geom::Vec3::new(f64::NAN, f64::INFINITY, 0.0) }, - Sel::Edge { body: "Nope".into(), index: 7, point: solidcraft_engine::geom::Vec3::new(0.0, 0.0, 0.0) }, + Sel::Face { body: "Nope".into(), index: usize::MAX, point: solidcore_record::Vec3::new(f64::NAN, f64::INFINITY, 0.0) }, + Sel::Edge { body: "Nope".into(), index: 7, point: solidcore_record::Vec3::new(0.0, 0.0, 0.0) }, Sel::Feature { id: u64::MAX }, Sel::Plane { name: "XY".into() }, Sel::SketchCurve { id: "c1".into(), sketch: None }, @@ -2077,6 +3602,34 @@ fn a_connection_that_never_gets_ready_says_connection_failed_and_offers_retry() assert_eq!(app.agent_chat.state(), State::Failed); assert!(app.preferences.agent_last.is_empty(), "only an agent that started is remembered"); + // A found agent that failed its version check (#9034): the picker says it doesn't start, and + // connecting says why and how to install it again, besides the system's own message. + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let reason = "This version of opencode.exe is not compatible with the version of Windows you're running."; + app.agent_chat.detection = Some(discover::Detection { + found: vec![discover::Found { + id: "opencode", + name: "OpenCode", + argv: vec!["solidcraft-no-such-agent-9034".into(), "acp".into()], + version: None, + login: discover::Login::Unknown, + problem: Some(reason.into()), + install: "npm install -g opencode-ai", + }], + ..Default::default() + }); + let entry = agents::current(&app).unwrap(); + assert!(entry.detail().contains(reason), "{}", entry.detail()); + connect(&mut app, &ctx); + assert_eq!(app.agent_chat.state(), State::Failed); + let told = |needle: &str| app.agent_chat.items.iter().any(|i| matches!(i, Item::Notice { text, error: true } if text.contains(needle))); + assert!(told(reason) && told("npm install -g opencode-ai") && told("OpenCode"), "{:?}", app.agent_chat.items); + assert_eq!(status(&app)["agents"][0]["problem"], reason); + // One that answered has nothing to say. + let mut fine = entry.clone(); + fine.problem = None; + assert_eq!(fine.problem_hint(), None); + // No agent at all: the picker opens on what to install. let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); app.agent_chat.detection = Some(discover::Detection::default()); @@ -2402,15 +3955,19 @@ fn the_picks_go_with_the_next_message_once() { assert_eq!(script.calls().pop().as_deref(), Some("prompt: and now?")); } -/// Two clicks on two rims are two things, not four edges (a click on a rim selects both halves for -/// the commands; the chat counts and describes what was clicked). +/// Two clicks on two rims are two things (the chat counts and describes what was clicked). The +/// cylinder is a circle drawn as two half arcs, extruded: one wall, each rim one closed edge. #[test] fn a_rim_clicked_once_is_one_item_not_its_pieces() { use solidcraft_engine::Sel; let (mut app, script, ctx) = app_with_script(); - app.run("solid.cylinder", json!({"radius": 10, "height": 20})).expect("a cylinder"); + app.run("sketch.create", json!({"plane": "XY"})).expect("a sketch"); + app.run("sketch.arc.three_point", json!({"start": [10, 0], "end": [-10, 0], "through": [0, 10]})).expect("an arc"); + app.run("sketch.arc.three_point", json!({"start": [-10, 0], "end": [10, 0], "through": [0, -10]})).expect("an arc"); + app.run("sketch.finish", json!({})).expect("the sketch"); + app.run("solid.extrude", json!({"distance": 20})).expect("a cylinder"); let (name, top, bottom, mid_top, mid_bottom) = { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let body = &st.bodies[0]; let mesh = body.mesh(); let rim_at = |z: f64| mesh.edges.iter().position(|e| e.len() > 3 && e.iter().all(|p| (p.z - z).abs() < 1e-6)).expect("a rim"); @@ -2419,21 +3976,22 @@ fn a_rim_clicked_once_is_one_item_not_its_pieces() { }; crate::viewport::select(&mut app, Some(Sel::Edge { body: name.clone(), index: top, point: mid_top }), false, false); crate::viewport::select(&mut app, Some(Sel::Edge { body: name, index: bottom, point: mid_bottom }), true, false); - assert_eq!(app.session.selection.len(), 4, "two clicks selected four halves"); + assert_eq!(app.session.selection.len(), 2, "two clicks selected the two rims"); assert_eq!(selected_count(&mut app), 2, "the checkbox counts the two clicks"); app.agent_chat.attach_selection = true; send(&mut app, &ctx, "these two rims".into()); let prompt = script.calls().pop().expect("a prompt"); assert!(prompt.contains("2 item(s)"), "{prompt}"); - assert_eq!(prompt.matches("(2 pieces)").count(), 2, "{prompt}"); - // A rim of radius 10 is about 62.8 mm round (the kernel's own figure), both halves together. - assert!(prompt.contains("Edge 62.") && prompt.contains("mm (2 pieces)"), "{prompt}"); + assert!(!prompt.contains("pieces)"), "{prompt}"); + // A rim of radius 10 is about 62.8 mm round (the kernel's own figure), the whole circle. + assert_eq!(prompt.matches("Edge 62.").count(), 2, "{prompt}"); let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") }; assert_eq!(context.items.len(), 2); assert_eq!(context.total(), 2); - // The detail still names the piece indices the tools take. - assert!(context.items.iter().all(|i| i.detail.contains("indices [")), "{:?}", context.items); + // The detail names the index the tools take. + let indices = [top, bottom].map(|i| format!("index {i}, ")); + assert!(context.items.iter().zip(&indices).all(|(item, index)| item.detail.contains(index)), "{:?}", context.items); } /// The same for a surface the kernel splits at a seam: one click on the cylinder's wall is one item. @@ -2447,7 +4005,7 @@ fn a_split_wall_clicked_once_is_one_item() { .and_then(|faces| faces.iter().find(|f| f["cylinder"]["radius"].is_number()).cloned()) .expect("the wall"); let at = &wall["point"]; - let point = solidcraft_engine::geom::Vec3::new(at[0].as_f64().unwrap_or(0.0), at[1].as_f64().unwrap_or(0.0), at[2].as_f64().unwrap_or(0.0)); + let point = solidcore_record::Vec3::new(at[0].as_f64().unwrap_or(0.0), at[1].as_f64().unwrap_or(0.0), at[2].as_f64().unwrap_or(0.0)); crate::viewport::select( &mut app, Some(Sel::Face { body: "Body1".into(), index: wall["index"].as_u64().unwrap_or(0) as usize, point }), @@ -2663,6 +4221,27 @@ fn no_tool_turn_warning_leaves_answers_and_incomplete_turns_quiet() { } } +/// A turn that ends with nothing shown because the reply hit its length limit, or the model +/// declined, says so instead of blaming tool support (#9495). +#[test] +fn a_cut_off_or_declined_reply_says_so_instead_of_blaming_tools() { + for (reason, said) in [("max_tokens", "ui.agent_chat_reply_cut_off"), ("refusal", "ui.agent_chat_reply_declined")] { + let (mut app, _, _) = app_with_script(); + app.agent_chat.tools_port = Some(12345); + start_turn(&mut app, "Make a box".into(), false, None, vec![]); + app.agent_chat.on_event(Event::TurnEnded { reason: reason.into() }); + end_turn(&mut app); + assert!(status(&app)["turnWarning"].is_null(), "{reason}"); + let notices: Vec<&str> = app + .agent_chat + .items + .iter() + .filter_map(|i| if let Item::Notice { text, error: false } = i { Some(text.as_str()) } else { None }) + .collect(); + assert_eq!(notices, [tr(said)], "{reason}"); + } +} + // ---- Tool calls in words (#1457) ---- fn in_mm() -> summary::Units<'static> { @@ -2850,3 +4429,177 @@ fn a_screenshot_card_hides_the_path_until_details() { h.frames(3); assert!(h.widget("Result").is_some() && h.widget(path).is_some(), "Details holds the full path"); } + +/// The composer's input box fills its parent composer area on all four sides, in every layout: +/// the only inset left is the text's own padding inside the box (no second margin around it). +#[test] +fn the_composer_box_fills_its_parent_in_every_layout() { + use crate::scenario::rect_of; + for (layout, popped) in [("floating", false), ("docked", false), ("floating", true), ("docked", true)] { + let mut h = narrow_chat(); + h.call("ui.resize", json!({"width": 1600, "height": 1000})); + h.call("ui.set", json!({"layout": layout})); + h.app.preferences.agent_chat_popped = popped; + h.app.agent_chat.state = Some(State::Ready); + h.frames(4); + let footer = rect_of("agent_chat:composer_footer").unwrap_or_else(|| panic!("{layout} popped={popped}: the composer area")); + let boxed = rect_of("agent_chat:composer_box").expect("the input box"); + let (l, r, t, b) = + (boxed.left() - footer.left(), footer.right() - boxed.right(), boxed.top() - footer.top(), footer.bottom() - boxed.bottom()); + for (edge, gap) in [("left", l), ("right", r), ("top", t), ("bottom", b)] { + assert!(gap.abs() <= 1.0, "{layout} popped={popped}: box {edge} edge is {gap} from its parent ({boxed:?} in {footer:?})"); + } + let input = rect_of("agent_chat:input").expect("the text"); + assert!(input.left() > boxed.left() + 2.0, "{layout} popped={popped}: the text keeps its own padding"); + let send = rect_of("agent_chat:send").expect("Send"); + assert!(boxed.contains_rect(send), "{layout} popped={popped}: Send stays inside the box"); + } +} + +/// The composer hint (idle and busy, in every language) stays on one row, even at the narrowest +/// panel, and is cut with an ellipsis instead of wrapping. +#[test] +fn the_composer_hint_stays_on_one_row_at_the_narrowest_width() { + let mut h = narrow_chat(); + h.app.agent_chat.state = Some(State::Ready); + h.frames(4); + let width = crate::scenario::rect_of("agent_chat:input").expect("the text box").width(); + let ctx = crate::fonts::test_context(); + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/locales"); + let mut checked = 0; + for entry in std::fs::read_dir(dir).unwrap().filter_map(Result::ok) { + let path = entry.path(); + if path.extension().is_none_or(|x| x != "json") { + continue; + } + let language = path.file_stem().unwrap().to_string_lossy().into_owned(); + let _scope = crate::i18n::scope(&language); + for key in ["ui.agent_chat_placeholder", "ui.agent_chat_placeholder_busy"] { + let hint = crate::i18n::tr(key).to_owned(); + let mut rows = 0; + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + rows = crate::ui_kit::assistant_hint_galley(ui, &hint, width - 2.0 * crate::theme::Tokens::get().form_inset).rows.len(); + }); + output.textures_delta.clear(); + assert_eq!(rows, 1, "{language} {key} at {width} wide: {hint}"); + checked += 1; + } + } + assert!(checked >= 20, "every language was checked"); +} + +/// The room tool windows get beside the docked Assistant, in a view that came out inside out +/// (the window of #9492): the Assistant's side gives way instead of panicking in `f32::clamp`. +#[test] +fn tool_room_beside_the_docked_assistant_survives_an_inside_out_view() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.ui.layout = crate::shell::LayoutMode::Floating; + app.preferences.ai_features = true; + app.agent_chat.open = true; + app.preferences.agent_chat_popped = false; + app.agent_chat.panel_rect = Some(egui::Rect::from_min_max(egui::pos2(100.0, 40.0), egui::pos2(150.0, 600.0))); + let inside_out = egui::Rect::from_min_max(egui::pos2(264.1875, 40.0), egui::pos2(159.0, 600.0)); + for side in ["right", "left"] { + app.preferences.agent_chat_side = side.into(); + let free = tool_space(&app, inside_out); + assert!(free.min.x.is_finite() && free.max.x.is_finite(), "{side}: {free:?}"); + } +} + +// ---- Copy message (#10675) ---- + +/// A chat with a multi-paragraph prompt and a Markdown reply, both drawn. +fn chat_with_copiable_messages() -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::User { + text: "make a plate\n\nwith two holes:\n- 6 mm\n- 8 mm".into(), + image: false, + pictures: Vec::new(), + files: Vec::new(), + context: Context::default(), + }); + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```".into() }); + h.frames(3); + h +} + +/// The text the last frame copied to the clipboard, if any. +fn copied_text(h: &crate::scenario::Harness) -> Option { + h.output.commands.iter().rev().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) +} + +fn click_at(h: &mut crate::scenario::Harness, at: egui::Pos2, button: egui::PointerButton) { + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frame_with(vec![egui::Event::PointerButton { pos: at, button, pressed: true, modifiers: egui::Modifiers::NONE }]); + h.frame_with(vec![egui::Event::PointerButton { pos: at, button, pressed: false, modifiers: egui::Modifiers::NONE }]); +} + +/// The visible button on a sent prompt copies the whole prompt, as entered. +#[test] +fn the_copy_message_button_copies_the_prompt_as_entered() { + let mut h = chat_with_copiable_messages(); + let at = crate::scenario::handle_at("agent_chat:copy:0").expect("the prompt's Copy message button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("make a plate\n\nwith two holes:\n- 6 mm\n- 8 mm"), "the whole prompt, paragraphs and list items"); +} + +/// The visible button on a reply copies its original Markdown: heading, paragraphs, list and +/// fenced code, not the laid-out text. +#[test] +fn the_copy_message_button_copies_the_reply_as_original_markdown() { + let mut h = chat_with_copiable_messages(); + let at = crate::scenario::handle_at("agent_chat:copy:1").expect("the reply's Copy message button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```")); +} + +/// Right-clicking a message opens its menu, and its row copies the same whole reply. +#[test] +fn right_clicking_a_message_offers_copy_message() { + let mut h = chat_with_copiable_messages(); + let msg = crate::scenario::rect_of("agent_chat:msg:1").expect("the reply's message area"); + click_at(&mut h, msg.center(), egui::PointerButton::Secondary); + h.frames(1); // let the popup settle at its final place before clicking its row + let item = crate::scenario::handle_at("agent_chat:copy_menu:1").expect("the right-click menu's Copy message row"); + click_at(&mut h, item, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```")); +} + +/// A reply that is still streaming copies the stable text received so far. +#[test] +fn a_streaming_reply_copies_the_text_received_so_far() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "half a repl".into() }); + h.frames(3); + let at = crate::scenario::handle_at("agent_chat:copy:0").expect("the streaming reply's button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("half a repl")); +} + +/// A picture-only prompt has no text to copy: no button, no menu, and a thought has none +/// either — the clipboard is never overwritten with an empty string. +#[test] +fn a_picture_only_prompt_and_a_thought_have_no_copy_message_action() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::User { + text: String::new(), + image: true, + pictures: Vec::new(), + files: Vec::new(), + context: Context::default(), + }); + h.app.agent_chat.items.push(Item::Agent { thought: true, text: "pondering".into() }); + h.frames(3); + assert!(crate::scenario::handle_at("agent_chat:copy:0").is_none(), "a picture-only prompt hides the text-copy action"); + assert!(crate::scenario::handle_at("agent_chat:copy:1").is_none(), "a thought has no copy action"); + assert!(h.widget("Copy message").is_none(), "nothing to click"); +} diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rs index 9236e3ada..f26fc67a7 100644 --- a/crates/ui-egui/src/agent_cursor.rs +++ b/crates/ui-egui/src/agent_cursor.rs @@ -19,13 +19,14 @@ //! settings on the navigation bar, or `ui.agent_cursor {show, speed, follow_camera}`); a call //! with `"animate": false` skips it. +use solidcraft_engine::geom::prelude::*; use std::collections::VecDeque; use std::sync::mpsc::Sender; use egui::{Pos2, Stroke, pos2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use solidcraft_engine::geom::{Vec2, Vec3}; +use solidcore_record::{Vec2, Vec3}; use crate::SolveApp; use crate::control::ControlResponse; @@ -108,7 +109,7 @@ pub fn speed_slider(ui: &mut egui::Ui, speed: &mut Speed) -> egui::Response { 1.0..=5.5, crate::ui_kit::Slider { step: Some(0.5), - format: |v| if v > 5.25 { crate::i18n::tr_label("Instant").into() } else { Speed::Times(v).label() }, + format: |v| if v > 5.25 { crate::i18n::tr_label("Instant").into() } else { format!("{v:.2}x") }, ..Default::default() }, ); @@ -271,6 +272,9 @@ fn batch_targets(steps: &[Value]) -> Vec<(Pos2, &'static str)> { /// The places a command's parameters pick, in the world: [x, y, z] points (faces, edges, /// vertices, positions), active-sketch [x, y] points, and a new sketch's plane. pub fn picks(app: &SolveApp, command: &str, params: &Value) -> Vec { + if solidcraft_engine::panels::commands::is_command(command) { + return Vec::new(); + } let id = solidcraft_engine::find_command(command).map_or(command, |c| c.id); let mut out = Vec::new(); if id == "sketch.create" @@ -279,7 +283,7 @@ pub fn picks(app: &SolveApp, command: &str, params: &Value) -> Vec { { out.push((q[0] + q[1] + q[2] + q[3]) / 4.0); } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let sketch = app.session.active_sketch.and_then(|s| st.sketch(s)).map(|ss| ss.plane); walk(params, None, &mut |key, v| { let num = |i: usize| v.get(i).and_then(Value::as_f64).filter(|x| x.is_finite()); @@ -452,7 +456,8 @@ fn finish(app: &mut SolveApp, ctx: &egui::Context) { if follow && id == "sketch.create" { app.agent.saved_view = Some(app.cam); } - let (req, _rx) = crate::control::ControlRequest::new(job.method, params); + let (mut req, _rx) = crate::control::ControlRequest::new(job.method, params); + req.chat_turn = job.chat_turn; // What was computed ahead while the pointer glided is found rather than computed again here. let out = app.run_with_kept(job.ahead.map(|a| a.kept), |app| match crate::control::handle(app, ctx, &req) { crate::control::Outcome::Done(v) => v, @@ -497,7 +502,8 @@ pub fn paint(app: &SolveApp, ctx: &egui::Context) { .interactable(false) .fade_in(false) .show(ctx, |ui| { - Container::popup_frame(ui.style()).fill(t.overlay).show(ui, |ui| { + let frame = Container::popup_frame(ui.style()).fill(t.overlay); + Container::show_backing(ui, frame, |ui| { ui.label(egui::RichText::new(crate::i18n::tr_label(label)).size(t.font_label).color(t.text)); }); }); @@ -628,7 +634,7 @@ mod tests { assert!(h.app.dialog.is_none(), "programmatic commands do not open interactive tools"); h.frames(120); assert_eq!(rx.try_recv().unwrap()["ok"], true); - assert_eq!(h.app.session.world_state().bodies.len(), 1); + assert_eq!(crate::open_meshing::session_world(&h.app.session).bodies.len(), 1); assert!(!h.app.agent.busy()); assert!(h.widget("Box").is_none(), "the command label ends with the animation"); } diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rs index 4ac5dd4f0..10b06f375 100644 --- a/crates/ui-egui/src/apply_off_thread_tests.rs +++ b/crates/ui-egui/src/apply_off_thread_tests.rs @@ -103,6 +103,28 @@ fn cancel_while_computing_applies_nothing() { assert_eq!(h.app.session.doc.features.len(), features); } +#[test] +fn removing_the_edited_feature_discards_its_pending_result() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":"Block"})).unwrap(); + h.call("ui.editFeature", json!({"feature":"Block"})); + h.frames(2); + let prepared = result(&h); + let finish = hold_result(&mut h, false); + let progress = h.app.applying.as_ref().unwrap().progress.clone(); + h.app.run("edit.undo", json!({})).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + h.frames(2); + assert!(h.app.dialog.is_none() && h.app.applying.is_none() && h.app.editing_state.is_none()); + assert!(progress.is_cancelled()); + assert!(finish.send(prepared).is_err(), "the removed editor cannot adopt a late result"); + h.frames(2); + assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); +} + #[test] fn a_ready_transaction_waits_one_frame_before_adoption() { let mut h = square_on_a_block(); @@ -314,16 +336,52 @@ fn changed_first_cut_adopts_its_entire_suffix_without_window_evaluation() { assert!((redone - after_volume).abs() < 0.001); } +/// An edit in a dialog without a live preview (Offset Plane) is computed off the window thread +/// too: OK evaluates nothing here, the features after the plane included. +#[test] +fn an_edit_without_a_preview_adopts_its_suffix_without_window_evaluation() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.apply_off_thread = Some(Duration::ZERO); + h.app.run("construct.plane.offset", json!({"base":"XY","offset":10,"name":"Shelf"})).unwrap(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.app.run("solid.box", json!({"corner":[5,5,20],"length":10,"width":10,"height":5,"operation":"join"})).unwrap(); + let plane = h.app.session.doc.find_feature("Shelf").unwrap().id; + let undo = h.app.session.undo.len(); + h.call("ui.editFeature", json!({"feature":plane})); + h.frames(2); + assert!(h.app.dialog.as_ref().is_some_and(|d| !d.previews()), "Offset Plane has no live preview"); + if let Some(crate::dialogs::Kind::OffsetPlane { offset }) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + *offset = "15".into(); + } + let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default()); + solidcraft_engine::doc::progress::watch(window.clone(), || { + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + assert!(h.app.applying.is_some(), "computing beside the window"); + until_applied(&mut h); + }); + assert_eq!(window.features(), (0, 0), "nothing evaluated on the window thread"); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + assert_eq!(h.app.session.doc.marker, None); + assert_eq!(h.app.session.undo.len(), undo + 1); + let shelf = &h.app.session.doc.feature(plane).unwrap().kind; + assert!( + matches!(shelf, solidcraft_engine::doc::FeatureKind::ConstructionPlane { plane: solidcraft_engine::doc::PlaneRef::Offset { distance, .. } } if *distance == "15"), + "{shelf:?}" + ); + h.step(&json!({"expect":{"bodies":1,"volume":24500}})).unwrap(); +} + #[test] fn cancelling_an_edit_restores_pinned_geometry_without_evaluating_an_evicted_suffix() { let (mut h, target) = cut_chain(); h.app.run("solid.box", json!({"corner":[100,0,0],"length":2,"width":2,"height":2})).unwrap(); h.app.run("edit.undo", json!({})).unwrap(); - let before = h.app.session.world_state(); + let before = h.app.session.world_state().unwrap(); let history = (h.app.session.undo.len(), h.app.session.redo.len()); let visibility = h.app.session.visibility.clone(); h.call("ui.editFeature", json!({"feature":target})); - crate::dialogs::sync_feature_edit_sketch(&mut h.app); + crate::dialogs::sync_feature_edit(&mut h.app); let sketch = h.app.session.feature_edit_sketch.expect("edited Extrude exposes its sketch"); assert!(solidcraft_engine::view::sketch_shown(&h.app.session, sketch)); let prepared = result(&h); @@ -342,7 +400,7 @@ fn cancelling_an_edit_restores_pinned_geometry_without_evaluating_an_evicted_suf assert_eq!(h.app.session.visibility, visibility, "temporary sketch display does not change stored visibility"); assert_eq!(h.app.session.doc.marker, None); assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); - assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.world_state())); + assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.world_state().unwrap())); assert_eq!(h.app.session.selection, vec![solidcraft_engine::Sel::Axis { name: "X".into() }]); } @@ -420,7 +478,7 @@ fn a_worker_error_then_cancel_preserves_original_world_history_redo_and_selectio let (mut h, target) = cut_chain(); h.app.run("solid.box", json!({"corner":[100,0,0],"length":2,"width":2,"height":2})).unwrap(); h.app.run("edit.undo", json!({})).unwrap(); - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let document = h.app.session.doc.clone(); let history = (h.app.session.undo.len(), h.app.session.redo.len()); h.app.session.selection = vec![solidcraft_engine::Sel::Feature { id: target }]; @@ -445,7 +503,7 @@ fn a_worker_error_then_cancel_preserves_original_world_history_redo_and_selectio }); assert_eq!(window.features(), (0, 0)); assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc)); - assert!(std::sync::Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(std::sync::Arc::ptr_eq(&world, &h.app.session.world_state().unwrap())); assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); assert_eq!(h.app.session.selection, selection); } diff --git a/crates/ui-egui/src/bidi.rs b/crates/ui-egui/src/bidi.rs index 442d592ec..fd27783e2 100644 --- a/crates/ui-egui/src/bidi.rs +++ b/crates/ui-egui/src/bidi.rs @@ -89,6 +89,10 @@ pub fn visual_template(text: &str) -> Cow<'_, str> { } fn visual_line(line: &str, output: &mut String) { + // Empty paragraphs have no bidi levels. Their separators are kept by screen_order. + if line.is_empty() { + return; + } let info = unicode_bidi::ParagraphBidiInfo::new(line, None); let (levels, runs) = info.visual_runs(0..line.len()); for run in runs { @@ -169,6 +173,9 @@ mod tests { #[test] fn each_line_is_its_own_paragraph() { assert_eq!(visual("שלום עולם\nworld"), "עולם שלום\nworld"); + assert_eq!(visual("\nשלום עולם\n\nworld\n"), "\nעולם שלום\n\nworld\n"); + assert_eq!(visual_template("שלום\n\n{count}"), "שלום\n\n{count}"); + assert_eq!(screen_order("\n\n"), "\n\n"); } #[test] diff --git a/crates/ui-egui/src/blend_arrow_tests.rs b/crates/ui-egui/src/blend_arrow_tests.rs index 9ad9f0d22..d8cb9e142 100644 --- a/crates/ui-egui/src/blend_arrow_tests.rs +++ b/crates/ui-egui/src/blend_arrow_tests.rs @@ -6,8 +6,9 @@ use crate::canvas::{anchor, blend_grow_dir}; use crate::dialogs::Kind; use crate::scenario::Harness; use serde_json::json; +use solidcore_record::Vec3; use solidcraft_engine::Sel; -use solidcraft_engine::geom::Vec3; +use solidcraft_engine::geom::prelude::*; /// A 40 x 30 x 20 block with a 20 x 30 x 10 step on its left half: the edge along y at x 20, /// z 20 is inside (concave); the block's right top edge (x 40, z 20) and the step's top right @@ -21,7 +22,7 @@ fn l_step() -> Harness { } fn edge(h: &Harness, p: Vec3) -> Sel { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let m = st.body("Body1").unwrap().mesh(); let i = m.edges.iter().position(|e| e.windows(2).any(|w| p.dist_to_segment(w[0], w[1]) < 1e-9)).expect("an edge there"); Sel::Edge { body: "Body1".into(), index: i, point: p } @@ -29,7 +30,7 @@ fn edge(h: &Harness, p: Vec3) -> Sel { fn grow(h: &Harness, s: &Sel) -> Vec3 { let Sel::Edge { body, index, point } = s else { panic!("an edge") }; - blend_grow_dir(&h.app.session.world_state().body(body).unwrap().mesh(), *index, *point).unwrap() + blend_grow_dir(&h.app.session.world_state().unwrap().body(body).unwrap().mesh(), *index, *point).unwrap() } fn close(a: Vec3, b: Vec3) -> bool { diff --git a/crates/ui-egui/src/blend_dialog_tests.rs b/crates/ui-egui/src/blend_dialog_tests.rs index 09aaa8a5f..30094344f 100644 --- a/crates/ui-egui/src/blend_dialog_tests.rs +++ b/crates/ui-egui/src/blend_dialog_tests.rs @@ -5,8 +5,8 @@ use crate::dialogs::Kind; use crate::dialogs_surface::Surf; use crate::scenario::Harness; use serde_json::json; +use solidcore_record::Vec3; use solidcraft_engine::doc::{FeatureKind, kernel::Continuity}; -use solidcraft_engine::geom::Vec3; fn ok(h: &mut Harness) { h.frames(2); @@ -47,7 +47,7 @@ fn edges_at_each_end_make_a_blend_and_come_back_in_an_edit() { d.inputs[0].items = vec![from]; d.inputs[1].items = vec![to]; let Kind::Surface(Surf::Blend { continuity, bulge, .. }) = &mut d.kind else { panic!("{:?}", d.kind) }; - *continuity = [2, 1]; + *continuity = [Continuity::G2, Continuity::G1]; *bulge = [0.5, 0.0]; ok(&mut h); let name = h.app.session.doc.features.last().unwrap().name.clone(); @@ -55,7 +55,7 @@ fn edges_at_each_end_make_a_blend_and_come_back_in_an_edit() { assert_eq!((a.as_str(), b.as_str()), ("A", "B")); assert_eq!(continuity, [Continuity::G2, Continuity::G1]); assert_eq!((bulge, seam, stitch), ([0.5, 0.0], None, false)); - assert_eq!(h.app.session.world_state().bodies.len(), 3, "a new surface body beside the boxes"); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 3, "a new surface body beside the boxes"); // A blend made by the command with a seam the dialog does not show: an edit keeps it. h.app.session.execute("edit.undo", &json!({})).unwrap(); h.app @@ -69,7 +69,7 @@ fn edges_at_each_end_make_a_blend_and_come_back_in_an_edit() { h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); h.frames(8); let d = h.app.dialog.as_mut().unwrap(); - assert!(matches!(d.kind, Kind::Surface(Surf::Blend { continuity: [2, 1], stitch: false, .. })), "{:?}", d.kind); + assert!(matches!(d.kind, Kind::Surface(Surf::Blend { continuity: [Continuity::G2, Continuity::G1], stitch: false, .. })), "{:?}", d.kind); assert_eq!((d.inputs[0].items.len(), d.inputs[1].items.len()), (1, 1), "{:?}", d.inputs); let Kind::Surface(Surf::Blend { stitch, .. }) = &mut d.kind else { panic!() }; *stitch = true; @@ -78,5 +78,5 @@ fn edges_at_each_end_make_a_blend_and_come_back_in_an_edit() { assert_eq!(continuity, [Continuity::G2, Continuity::G1]); assert_eq!(seam, Some([Vec3::new(0.0, 10.0, 10.0), Vec3::new(0.0, 20.0, 15.0)])); assert!(stitch); - assert_eq!(h.app.session.world_state().bodies.len(), 1, "stitched onto both boxes"); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1, "stitched onto both boxes"); } diff --git a/crates/ui-egui/src/blur.rs b/crates/ui-egui/src/blur.rs new file mode 100644 index 000000000..d310c733e --- /dev/null +++ b/crates/ui-egui/src/blur.rs @@ -0,0 +1,238 @@ +//! Optional viewport-only blur. Plain frames do not record markers or own effect resources. +use egui::{Color32, Frame, Painter, Rect, Shape}; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub enum Capability { + Available, + Unavailable(&'static str), +} + +#[derive(Clone, Copy, Debug, Default, Serialize)] +pub struct Counters { + pub textures_created: u64, + pub buffers_created: u64, + pub bind_groups_created: u64, + pub pipelines_created: u64, + pub source_passes: u64, + pub blur_passes: u64, + pub composition_passes: u64, + pub present_passes: u64, + pub markers_emitted: u64, + pub markers_drawn: u64, + pub cache_hits: u64, + pub live_bytes: u64, + pub live_textures: u64, + pub live_buffers: u64, + pub live_bind_groups: u64, + pub live_pipelines: u64, +} + +impl Counters { + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn clear_live(&mut self) { + self.live_bytes = 0; + self.live_textures = 0; + self.live_buffers = 0; + self.live_bind_groups = 0; + self.live_pipelines = 0; + } +} + +pub fn validate_radius(radius: f32) -> Result { + if radius.is_finite() && (0.0..=60.0).contains(&radius) { + Ok(radius) + } else { + Err("blur radius must be finite and between 0 and 60 physical pixels") + } +} + +/// Original Kawase schedule. Offsets are in input texels; the first level is half sized. +pub fn schedule(radius: f32) -> Option<(usize, f32)> { + schedule_capped(radius, 5) +} + +/// A transient quality cap changes pass count, retaining the requested physical radius. +pub fn schedule_capped(radius: f32, cap: usize) -> Option<(usize, f32)> { + if validate_radius(radius).ok()? == 0.0 { + return None; + } + let steps = (if radius <= 8.0 { + 2 + } else if radius <= 18.0 { + 3 + } else if radius <= 30.0 { + 4 + } else { + 5 + }) + .min(cap.clamp(2, 5)); + // Per-axis tap variance: down 1/2, up 4/3, scaled by input texel size. + // Target tap sigma = radius / 2. Resampling adds its own measurable footprint. + let variance = (35.0 / 18.0) * (4.0_f32.powi(steps as i32) - 1.0); + Some((steps, radius / (2.0 * variance.sqrt()))) +} + +/// Evidence from the native pass owner's actual submission, never UI construction time. +#[derive(Clone, Copy, Debug)] +pub struct PaintedFrame { + pub frame: u64, + pub interval_ms: Option, + pub continuous: bool, +} + +#[derive(Debug)] +pub(crate) struct Guard { + pub cap: usize, + pub streak: u8, + pub notice: bool, + pub opted_out: bool, + original: Option, + announced: bool, +} + +impl Default for Guard { + fn default() -> Self { + Self { cap: 5, streak: 0, notice: false, opted_out: false, original: None, announced: false } + } +} + +impl Guard { + pub fn reset(&mut self) { + self.streak = 0; + } + + pub fn observe(&mut self, radius: f32, interval_ms: f64, eligible: bool) { + let steps = schedule_capped(radius, self.cap).map_or(0, |s| s.0); + if self.opted_out || !eligible || !interval_ms.is_finite() || interval_ms <= 22.0 || steps <= 2 { + self.reset(); + return; + } + self.streak = self.streak.saturating_add(1); + if self.streak == 60 { + self.original.get_or_insert(self.cap); + self.cap = steps - 1; + self.reset(); + if !self.announced { + self.notice = true; + self.announced = true; + } + } + } + + pub fn undo(&mut self) { + if let Some(original) = self.original.take() { + self.cap = original; + } + self.opted_out = true; + self.notice = false; + self.reset(); + } +} + +/// Session-only state. Harness inputs never replace a real GPU capability with success. +#[derive(Default)] +pub(crate) struct Session { + pub guard: Guard, + pub harness_radius: Option, + pub harness_unavailable: Option<&'static str>, + pub evidence_fixture: Option<&'static str>, + identity: Option<(u64, u32)>, + frame: Option, + painted: Option, + dismissed: std::collections::VecDeque, +} + +impl Session { + pub fn sample(&mut self, ctx: &egui::Context, revision: u64, radius: f32, available: bool, paint: Option) { + let frame = ctx.cumulative_frame_nr(); + if self.frame == Some(frame) { + return; + } // egui layout re-passes do not count twice. + self.frame = Some(frame); + let identity = (revision, radius.to_bits()); + if self.identity.as_ref() != Some(&identity) { + self.identity = Some(identity); + self.painted = paint.map(|p| p.frame); + self.guard.reset(); + return; + } + let eligible = available + && radius > 0.0 + && ctx.requested_repaint_last_pass() + && ctx.input(|i| i.viewport().visible() != Some(false)) + && paint.is_some_and(|p| p.frame.checked_add(1) == Some(frame) && self.painted != Some(p.frame) && p.continuous); + self.painted = paint.map(|p| p.frame); + self.guard.observe(radius, paint.and_then(|p| p.interval_ms).unwrap_or(0.0), eligible); + } + + pub fn dismissed(&self, key: u64) -> bool { + self.dismissed.contains(&key) + } + pub fn dismiss(&mut self, key: u64) { + if !self.dismissed(key) { + if self.dismissed.len() == 64 { + self.dismissed.pop_front(); + } + self.dismissed.push_back(key); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[path = "blur_native.rs"] +mod implementation; +#[cfg(not(target_arch = "wasm32"))] +pub use implementation::*; + +#[cfg(target_arch = "wasm32")] +mod implementation { + use super::*; + #[derive(Default)] + pub struct State { + radius: f32, + } + impl State { + pub fn install(&mut self, _: &egui_wgpu::RenderState, _: bool) {} + pub fn set_radius(&mut self, radius: f32) -> Result<(), &'static str> { + self.radius = validate_radius(radius)?; + Ok(()) + } + pub fn radius(&self) -> f32 { + self.radius + } + pub fn capability(&self) -> Capability { + Capability::Unavailable("web compositor integration unavailable") + } + pub fn capability_for(&self, _: egui::ViewportId) -> Capability { + self.capability() + } + pub fn counters(&self) -> Counters { + Counters::default() + } + pub fn begin(&mut self, _: &egui::Context, _: bool) {} + pub fn set_surface_alpha(&mut self, _: Option) {} + pub fn set_available(&mut self, _: bool) {} + pub fn set_tier_cap(&mut self, _: usize) {} + pub fn software_adapter(&self) -> bool { + false + } + pub fn painted_frame(&self) -> Option { + None + } + } + pub fn enabled() -> bool { + false + } + pub fn panel_fill(fill: Color32) -> Color32 { + fill + } + pub fn decorate(_: &Painter, _: Frame, _: Rect, shape: Shape) -> Shape { + shape + } + pub fn viewport(painter: &Painter, rect: Rect, cb: crate::gpu::ViewportCallback, _: Rect, _: [Color32; 2]) { + painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); + } +} +#[cfg(target_arch = "wasm32")] +pub use implementation::*; diff --git a/crates/ui-egui/src/blur.wgsl b/crates/ui-egui/src/blur.wgsl new file mode 100644 index 000000000..e947215ee --- /dev/null +++ b/crates/ui-egui/src/blur.wgsl @@ -0,0 +1,70 @@ +// Original SolidCraft backdrop dual-Kawase and rounded surface composition. +struct Params { a: vec4, rect: vec4, corners: vec4, top: vec4, bottom: vec4, outside: vec4 } +@group(0) @binding(0) var image: texture_2d; +@group(0) @binding(1) var filtering: sampler; +@group(0) @binding(2) var p: Params; +struct Vertex { @builtin(position) position: vec4, @location(0) uv: vec2 } +@vertex fn vertex(@builtin(vertex_index) i: u32) -> Vertex { + let uv = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + return Vertex(vec4(uv * vec2(2.0, -2.0) + vec2(-1.0, 1.0), 0.0, 1.0), uv); +} +fn linear(c: vec3) -> vec3 { + return select(c / 12.92, pow((c + vec3(0.055)) / 1.055, vec3(2.4)), c > vec3(0.04045)); +} +fn gamma(c: vec3) -> vec3 { + return select(c * 12.92, 1.055 * pow(max(c, vec3(0.0)), vec3(1.0 / 2.4)) - vec3(0.055), c > vec3(0.0031308)); +} +fn load_linear(at: vec2) -> vec4 { + let c = textureLoad(image, clamp(at, vec2(0), vec2(textureDimensions(image)) - vec2(1)), 0); + // Only the scene/composition input is gamma encoded on unorm targets. Decoding + // each texel BEFORE bilinear interpolation avoids filtering encoded colors. + return vec4(linear(c.rgb), c.a); +} +fn sample_at(uv: vec2) -> vec4 { + if p.a.y < 0.5 { return textureSampleLevel(image, filtering, uv, 0.0); } + let q = uv * vec2(textureDimensions(image)) - vec2(0.5); + let lo = vec2(floor(q)); let f = fract(q); + return mix(mix(load_linear(lo), load_linear(lo + vec2(1, 0)), f.x), + mix(load_linear(lo + vec2(0, 1)), load_linear(lo + vec2(1, 1)), f.x), f.y); +} +@fragment fn down(v: Vertex) -> @location(0) vec4 { + let d = vec2(p.a.x) / vec2(textureDimensions(image)); + return (4.0 * sample_at(v.uv) + sample_at(v.uv + d) + sample_at(v.uv - d) + + sample_at(v.uv + d * vec2(1.0, -1.0)) + sample_at(v.uv + d * vec2(-1.0, 1.0))) / 8.0; +} +@fragment fn up(v: Vertex) -> @location(0) vec4 { + let d = vec2(p.a.x) / vec2(textureDimensions(image)); + return (sample_at(v.uv + vec2(-2.0*d.x, 0.0)) + sample_at(v.uv + vec2(2.0*d.x, 0.0)) + + sample_at(v.uv + vec2(0.0, -2.0*d.y)) + sample_at(v.uv + vec2(0.0, 2.0*d.y)) + + 2.0 * (sample_at(v.uv + d) + sample_at(v.uv - d) + + sample_at(v.uv + d * vec2(1.0, -1.0)) + sample_at(v.uv + d * vec2(-1.0, 1.0)))) / 12.0; +} +@fragment fn background(v: Vertex) -> @location(0) vec4 { + let q = v.position.xy; + var c = p.outside; + if all(q >= p.rect.xy) && all(q < p.rect.zw) && all(q >= p.corners.xy) && all(q < p.corners.zw) { + c = mix(p.top, p.bottom, clamp((q.y - p.rect.y) / max(1.0, p.rect.w - p.rect.y), 0.0, 1.0)); + } + if p.a.z > 0.5 { return vec4(linear(c.rgb), 1.0); } + return vec4(c.rgb, 1.0); +} +@fragment fn panel(v: Vertex) -> @location(0) vec4 { + let center = (p.rect.xy + p.rect.zw) * 0.5; + let half_size = (p.rect.zw - p.rect.xy) * 0.5; + let relative = v.position.xy - center; + let upper = relative.y < 0.0; + let radius = select(select(p.corners.w, p.corners.z, relative.x < 0.0), select(p.corners.y, p.corners.x, relative.x < 0.0), upper); + let r = min(radius, min(half_size.x, half_size.y)); + let d = abs(relative) - half_size + vec2(r); + let distance = min(max(d.x, d.y), 0.0) + length(max(d, vec2(0.0))) - r; + let alpha = clamp(0.5 - distance, 0.0, 1.0) * p.a.w; + let c = textureSample(image, filtering, v.position.xy / vec2(textureDimensions(image))); + // Match egui: coverage/opacity multiply gamma-premultiplied RGB BEFORE the + // framebuffer conversion. The sampled backdrop remains linear color. + let premultiplied_gamma = gamma(c.rgb) * alpha; + let rgb = select(premultiplied_gamma, linear(premultiplied_gamma), p.a.z > 0.5); + return vec4(rgb, alpha); +} +@fragment fn present(v: Vertex) -> @location(0) vec4 { + return textureSample(image, filtering, v.uv); +} diff --git a/crates/ui-egui/src/blur_native.rs b/crates/ui-egui/src/blur_native.rs new file mode 100644 index 000000000..6443785e8 --- /dev/null +++ b/crates/ui-egui/src/blur_native.rs @@ -0,0 +1,1156 @@ +use super::*; +use crate::gpu::{Renderer as ViewRenderer, ViewportCallback}; +use egui_wgpu::{CallbackResources, CallbackTrait, FrameCompositor, ScreenDescriptor, wgpu}; +use std::cell::RefCell; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +thread_local! { static CURRENT: RefCell>> = const { RefCell::new(None) }; } +thread_local! { static SURFACE_ALPHA: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +const BUDGET: u64 = 256 * 1024 * 1024; +const MAX_MARKERS: usize = 256; +type Params = [f32; 24]; + +fn capability(adapter: &wgpu::Adapter, device_type: wgpu::DeviceType, format: wgpu::TextureFormat, split: bool, msaa: u32) -> Capability { + if device_type == wgpu::DeviceType::Cpu { + return Capability::Unavailable("software adapter (gpu-software)"); + } + rendering_capability(adapter, format, split, msaa) +} + +fn rendering_capability(adapter: &wgpu::Adapter, format: wgpu::TextureFormat, split: bool, msaa: u32) -> Capability { + let allowed = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC; + if !split || msaa != 1 { + Capability::Unavailable("requires a native split scene and 1x UI without depth") + } else if !matches!( + format, + wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Bgra8UnormSrgb + ) || [format, wgpu::TextureFormat::Rgba16Float].iter().any(|f| { + let features = adapter.get_texture_format_features(*f); + !features.allowed_usages.contains(allowed) || !features.flags.contains(wgpu::TextureFormatFeatureFlags::FILTERABLE) + }) { + Capability::Unavailable("required renderable filterable formats unavailable") + } else { + Capability::Available + } +} + +#[derive(Clone)] +struct Host { + adapter: wgpu::Adapter, + device_type: wgpu::DeviceType, + device: wgpu::Device, + queue: wgpu::Queue, + renderer: std::sync::Weak>, + lost: egui_wgpu::DeviceLost, + format: wgpu::TextureFormat, + capability: std::sync::OnceLock, + split: bool, + msaa: u32, +} +impl Host { + fn capability(&self) -> Capability { + *self.capability.get_or_init(|| capability(&self.adapter, self.device_type, self.format, self.split, self.msaa)) + } +} + +pub struct State { + radius: f32, + available: bool, + tier_cap: usize, + host: Option, + active: Option>, + retired: Counters, + source_supported: bool, + failure: Option<&'static str>, + surface_alpha: Option, + last_size: Option<[u32; 2]>, + last_background: Option<[Color32; 3]>, +} + +impl Default for State { + fn default() -> Self { + Self { + radius: 0.0, + available: true, + tier_cap: 5, + host: None, + active: None, + retired: Counters::default(), + source_supported: true, + failure: None, + surface_alpha: None, + last_size: None, + last_background: None, + } + } +} + +impl State { + pub fn install(&mut self, rs: &egui_wgpu::RenderState, split: bool) { + self.retire(); + self.failure = None; + self.host = Some(Host { + adapter: rs.adapter.clone(), + device_type: rs.adapter.get_info().device_type, + device: rs.device.clone(), + queue: rs.queue.clone(), + renderer: Arc::downgrade(&rs.renderer), + lost: rs.device_lost.clone(), + format: rs.target_format, + capability: std::sync::OnceLock::new(), + split, + msaa: rs.msaa_samples, + }); + } + + fn retire(&mut self) { + if let Some(shared) = self.active.take() { + if let Ok(mut inner) = shared.inner.lock() { + self.retired = inner.counts; + self.retired.clear_live(); + self.failure = inner.failure.or(self.failure); + inner.gpu = None; + } + if let Some(renderer) = self.host.as_ref().and_then(|h| h.renderer.upgrade()) { + renderer.write().frame_compositor = None; + } + } + } + + pub fn set_radius(&mut self, radius: f32) -> Result<(), &'static str> { + let radius = validate_radius(radius)?; + if radius != self.radius { + self.retire(); + self.radius = radius; + self.failure = None; + } + Ok(()) + } + pub fn radius(&self) -> f32 { + self.radius + } + pub fn software_adapter(&self) -> bool { + self.host.as_ref().is_some_and(|h| h.device_type == wgpu::DeviceType::Cpu) + } + pub fn set_available(&mut self, available: bool) { + self.available = available; + if !available { + self.retire(); + } + } + pub fn set_tier_cap(&mut self, cap: usize) { + let cap = cap.clamp(2, 5); + if self.tier_cap != cap { + self.retire(); + self.tier_cap = cap; + } + } + pub fn painted_frame(&self) -> Option { + self.active.as_ref()?.inner.lock().ok()?.painted + } + pub fn capability(&self) -> Capability { + let base = self.base_capability(); + if base == Capability::Available && self.active.as_ref().is_some_and(|s| s.inner.lock().is_ok_and(|i| i.missing_source)) { + return Capability::Unavailable("no viewport source in the last painted frame"); + } + base + } + pub fn capability_for(&self, viewport: egui::ViewportId) -> Capability { + if viewport != egui::ViewportId::ROOT { + return Capability::Unavailable("native pop-out source integration unavailable"); + } + self.capability() + } + fn base_capability(&self) -> Capability { + let Some(host) = &self.host else { return Capability::Unavailable("no GPU host") }; + if host.lost.is_lost() { + return Capability::Unavailable("device lost"); + } + let available = host.capability(); + if available != Capability::Available { + return available; + } + if !self.source_supported { + return Capability::Unavailable("workspace has no viewport source recipe"); + } + if let Some(reason) = self.failure { + return Capability::Unavailable(reason); + } + if let Some(shared) = &self.active { + return match shared.inner.lock() { + Ok(inner) => inner.failure.map_or(Capability::Available, Capability::Unavailable), + Err(_) => Capability::Unavailable("blur state unavailable"), + }; + } + Capability::Available + } + pub fn counters(&self) -> Counters { + self.active.as_ref().and_then(|s| s.inner.lock().ok().map(|i| i.counts)).unwrap_or(self.retired) + } + #[cfg(test)] + pub(crate) fn source_texture(&self) -> Option { + let inner = self.active.as_ref()?.inner.lock().ok()?; + Some(inner.gpu.as_ref()?.source._texture.clone()) + } + #[cfg(test)] + pub(crate) fn source_geometry(&self) -> Option<[Rect; 3]> { + self.active.as_ref()?.inner.lock().ok()?.geometry + } + /// Internal capture tint only; deliberately not a user preference. + pub fn set_surface_alpha(&mut self, alpha: Option) { + self.surface_alpha = alpha; + } + + pub fn begin(&mut self, ctx: &egui::Context, source_supported: bool) -> Scope { + let previous = CURRENT.with(|c| c.replace(None)); + let alpha = SURFACE_ALPHA.with(|a| a.replace(self.surface_alpha)); + if ctx.viewport_id() != egui::ViewportId::ROOT { + return Scope { previous, alpha }; + } + self.source_supported = source_supported; + if self.radius == 0.0 { + self.retire(); + return Scope { previous, alpha }; + } + let colors = crate::theme::Tokens::get(); + let background = [colors.viewport_top, colors.viewport_bottom, colors.app_bar]; + if self.last_background != Some(background) { + let failed = self.failure.is_some() || self.active.as_ref().is_some_and(|s| s.inner.lock().is_ok_and(|i| i.failure.is_some())); + if failed { + self.retire(); + self.failure = None; + } + self.last_background = Some(background); + } + let size = ctx.content_rect().size() * ctx.pixels_per_point(); + if size.is_finite() && size.x > 0.0 && size.y > 0.0 { + let size_key = [size.x.round() as u32, size.y.round() as u32]; + if self.last_size != Some(size_key) { + self.retire(); + self.failure = None; + self.last_size = Some(size_key); + } + } + if !self.available || self.base_capability() != Capability::Available || !size.is_finite() || size.x <= 0.0 || size.y <= 0.0 { + self.retire(); + return Scope { previous, alpha }; + } + let Some(host) = &self.host else { return Scope { previous, alpha } }; + let shared = self.active.get_or_insert_with(|| { + Arc::new(Shared { + host: host.clone(), + radius: self.radius, + tier_cap: self.tier_cap, + painting_owner: std::sync::atomic::AtomicBool::new(true), + inner: Mutex::new(Inner { counts: self.retired, ..Inner::default() }), + }) + }); + if let Ok(mut inner) = shared.inner.lock() { + inner.markers.clear(); + inner.serial = inner.serial.wrapping_add(1); + inner.source_seen = false; + inner.source_count = 0; + if inner.frame != ctx.cumulative_frame_nr() { + inner.frame = ctx.cumulative_frame_nr(); + inner.continuous = ctx.requested_repaint_last_pass(); + } + inner.rendered = false; + inner.drawn_before = inner.counts.markers_drawn; + } + if let Some(renderer) = host.renderer.upgrade() { + renderer.write().frame_compositor = Some(shared.clone()); + } + CURRENT.with(|c| *c.borrow_mut() = Some(shared.clone())); + Scope { previous, alpha } + } +} + +/// Select production policy or bypass only its software rejection for rendering fixtures. +#[cfg(test)] +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum FixturePolicy { + Production, + Rendering, +} + +#[cfg(test)] +pub(crate) fn fixture_state( + adapter: &wgpu::Adapter, + device: &wgpu::Device, + queue: &wgpu::Queue, + renderer: &Arc>, + format: wgpu::TextureFormat, + policy: FixturePolicy, +) -> State { + State { + radius: 0.0, + available: true, + tier_cap: 5, + host: Some(Host { + adapter: adapter.clone(), + device_type: adapter.get_info().device_type, + device: device.clone(), + queue: queue.clone(), + renderer: Arc::downgrade(renderer), + lost: egui_wgpu::DeviceLost::watch(device), + format, + capability: match policy { + FixturePolicy::Production => std::sync::OnceLock::new(), + FixturePolicy::Rendering => std::sync::OnceLock::from(rendering_capability(adapter, format, true, 1)), + }, + split: true, + msaa: 1, + }), + active: None, + retired: Counters::default(), + source_supported: true, + failure: None, + surface_alpha: None, + last_size: None, + last_background: None, + } +} + +#[cfg(test)] +pub(crate) fn fixture_budget(size: [u32; 2], steps: usize) -> Option { + target_bytes(size, steps, 16384) +} +impl Drop for State { + fn drop(&mut self) { + self.retire(); + } +} + +/// Restores the previous context even on early UI returns. No heap allocation. +pub struct Scope { + previous: Option>, + alpha: Option, +} +impl Drop for Scope { + fn drop(&mut self) { + CURRENT.with(|c| *c.borrow_mut() = self.previous.take()); + SURFACE_ALPHA.with(|a| a.set(self.alpha)); + } +} + +pub fn enabled() -> bool { + CURRENT.with(|c| c.borrow().is_some()) +} +pub fn panel_fill(fill: Color32) -> Color32 { + if fill.a() == 0 { + return fill; + } + SURFACE_ALPHA.with(|a| { + a.get().map_or(fill, |alpha| { + let [r, g, b, _] = fill.to_srgba_unmultiplied(); + Color32::from_rgba_unmultiplied(r, g, b, alpha) + }) + }) +} + +struct Shared { + host: Host, + radius: f32, + tier_cap: usize, + inner: Mutex, + painting_owner: std::sync::atomic::AtomicBool, +} +#[derive(Default)] +struct Inner { + frame: u64, + continuous: bool, + rendered: bool, + drawn_before: u64, + painted: Option, + submitted_at: Option, + gpu: Option, + markers: Vec, + counts: Counters, + failure: Option<&'static str>, + serial: u64, + source_seen: bool, + screen: Option<([u32; 2], f32)>, + missing_source: bool, + source_count: u16, + #[cfg(test)] + geometry: Option<[Rect; 3]>, +} +#[derive(Clone, Copy)] +struct Marker { + rect: Rect, + corners: egui::CornerRadius, + opacity: f32, + snap: bool, + // Identity only: the paint job owns this callback for the entire frame. Keeping + // its Arc here would create a Shared -> callback -> Shared ownership cycle. + callback_id: usize, +} + +pub fn decorate(painter: &Painter, frame: Frame, content: Rect, ordinary: Shape) -> Shape { + let opacity = painter.opacity(); + if frame.fill.a() == 0 || (frame.fill.a() == 255 && opacity >= 1.0) || !opacity.is_finite() || opacity <= 0.0 || !painter.is_visible() { + return ordinary; + } + CURRENT.with(|c| { + let kept = c.borrow(); + let Some(shared) = kept.as_ref() else { return ordinary }; + if painter.ctx().viewport_id() != egui::ViewportId::ROOT { + return ordinary; + } + let rect = frame.widget_rect(content); + if !rect.is_finite() || !rect.is_positive() { + return ordinary; + } + let callback = if let Ok(mut inner) = shared.inner.lock() { + if inner.markers.len() >= MAX_MARKERS { + inner.failure = Some("blur panel limit exceeded"); + inner.gpu = None; + inner.counts.clear_live(); + return ordinary; + } + let index = inner.markers.len(); + let callback = egui_wgpu::Callback::new_paint_callback(rect, PanelMarker { shared: shared.clone(), index }); + inner.markers.push(Marker { + rect, + corners: frame.corner_radius, + opacity, + snap: painter.ctx().tessellation_options(|o| o.round_rects_to_pixels), + callback_id: Arc::as_ptr(&callback.callback) as *const () as usize, + }); + inner.counts.markers_emitted += 1; + callback + } else { + return ordinary; + }; + Shape::Vec(vec![Shape::Callback(callback), ordinary]) + }) +} + +pub fn viewport(painter: &Painter, rect: Rect, cb: ViewportCallback, background: Rect, colors: [Color32; 2]) { + CURRENT.with(|c| { + if let Some(shared) = c.borrow().as_ref() { + if let Ok(mut inner) = shared.inner.lock() { + inner.source_count = inner.source_count.saturating_add(1); + } + let outside = crate::theme::Tokens::get().app_bar; + painter.add(egui_wgpu::Callback::new_paint_callback( + rect, + Source { + cb, + rect, + clip: painter.clip_rect(), + background, + colors, + outside, + context: painter.ctx().clone(), + layer: painter.layer_id(), + shared: shared.clone(), + }, + )); + } else { + painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); + } + }); +} + +struct Source { + cb: ViewportCallback, + rect: Rect, + clip: Rect, + background: Rect, + colors: [Color32; 2], + outside: Color32, + context: egui::Context, + layer: egui::LayerId, + shared: Arc, +} +impl CallbackTrait for Source { + fn prepare( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + screen: &ScreenDescriptor, + encoder: &mut wgpu::CommandEncoder, + resources: &mut CallbackResources, + ) -> Vec { + self.cb.prepare(device, queue, screen, encoder, resources) + } + fn finish_prepare( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + resources: &mut CallbackResources, + ) -> Vec { + let Some(view) = resources.get::() else { return Vec::new() }; + if !self.shared.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return Vec::new(); + } + // Physical surface clamping is supplied by the pass owner, not inferred from DPI. + let Ok(mut inner) = self.shared.inner.lock() else { return Vec::new() }; + let Some((size, scale)) = inner.screen else { return Vec::new() }; + let screen = ScreenDescriptor { size_in_pixels: size, pixels_per_point: scale }; + if self.shared.host.lost.is_lost() || inner.failure.is_some() { + return Vec::new(); + } + // Read once after UI emission/output processing; transforms can be set after + // this callback was emitted. The callback shape itself stays in local space. + let Some([rect, clip, background]) = self.effective_geometry() else { + inner.failure = Some("invalid viewport source geometry"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + }; + #[cfg(test)] + { + inner.geometry = Some([rect, clip, background]); + } + if self.colors.iter().any(|color| color.a() != 255) || self.outside.a() != 255 { + inner.failure = Some("translucent viewport/background source unsupported"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + if screen.size_in_pixels.contains(&0) || !screen.pixels_per_point.is_finite() || screen.pixels_per_point <= 0.0 { + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + if inner.source_seen || inner.source_count != 1 { + inner.failure = Some("multiple viewport sources in one frame"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + inner.source_seen = true; + let Some((steps, offset)) = schedule_capped(self.shared.radius, self.shared.tier_cap) else { return Vec::new() }; + let Some(bytes) = target_bytes(screen.size_in_pixels, steps, self.shared.host.device.limits().max_texture_dimension_2d) else { + inner.failure = Some("blur target is empty, exceeds device limits or memory budget"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + }; + let replace = inner.gpu.as_ref().is_none_or(|g| g.size != screen.size_in_pixels || g.steps != steps); + if replace { + inner.gpu = None; + inner.counts.clear_live(); + let (gpu, failure) = egui_wgpu::capture_errors(device, || { + Gpu::new(device, self.shared.host.format, screen.size_in_pixels, steps, offset, &mut inner.counts) + }); + if let Some(error) = failure { + log::warn!("blur resources refused: {error}"); + inner.failure = Some("GPU refused blur resources"); + inner.counts.clear_live(); + return Vec::new(); + } + inner.gpu = Some(gpu); + inner.counts.live_bytes += bytes; + } + let key = self.key(&screen, [rect, clip, background]); + let serial = inner.serial; + let marker_count = inner.markers.len(); + let Inner { gpu, counts, .. } = &mut *inner; + let Some(gpu) = gpu else { return Vec::new() }; + gpu.ready_serial = serial; + let (_, failed) = egui_wgpu::capture_errors(device, || gpu.grow_markers(device, marker_count, counts)); + if let Some(error) = failed { + log::warn!("blur marker resources refused: {error}"); + inner.failure = Some("GPU refused blur marker resources"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + if gpu.valid == Some(key) { + counts.cache_hits += 1; + return Vec::new(); + } + let params = background_params(background, clip, self.colors, self.outside, screen.pixels_per_point, self.shared.host.format.is_srgb()); + if params.iter().any(|value| !value.is_finite()) { + inner.failure = Some("invalid physical viewport source geometry"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + queue.write_buffer(&gpu.background.uniform, 0, &bytes_of(¶ms)); + { + let mut pass = pass(encoder, "blur_source", &gpu.source.view, wgpu::Color::BLACK); + pass.set_pipeline(&gpu.background_pipeline); + pass.set_bind_group(0, &gpu.background.group, &[]); + pass.draw(0..3, 0..1); + let viewport = pixel_rect(rect, screen.pixels_per_point, screen.size_in_pixels); + let clipped = pixel_rect(rect.intersect(clip), screen.pixels_per_point, screen.size_in_pixels); + if let (Some([x, y, w, h]), Some([cx, cy, cw, ch])) = (viewport, clipped) { + pass.set_scissor_rect(cx, cy, cw, ch); + view.paint(&self.cb.0, &mut pass, [x as f32, y as f32, w as f32, h as f32]); + } + } + counts.source_passes += 1; + // The backdrop pyramid is built at paint-order boundaries in render(), + // after the underlying UI has actually been drawn, rather than from this + // scene-only texture during preparation. + gpu.pending = Some(key); + Vec::new() + } + fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &CallbackResources) { + self.cb.paint(info, pass, resources); + } +} + +impl Source { + fn effective_geometry(&self) -> Option<[Rect; 3]> { + let transform = self.context.layer_transform_to_global(self.layer).unwrap_or(egui::emath::TSTransform::IDENTITY); + if !transform.translation.is_finite() || !transform.scaling.is_finite() || transform.scaling <= 0.0 { + return None; + } + let geometry = [self.rect, self.clip, self.background].map(|r| transform.mul_rect(r)); + (geometry.iter().all(|r| r.is_finite()) && geometry[0].is_positive()).then_some(geometry) + } + + fn key(&self, screen: &ScreenDescriptor, geometry: [Rect; 3]) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + solidcraft_gpu::view::frame_key(&self.cb.0).hash(&mut h); + for r in geometry { + [r.min.x, r.min.y, r.max.x, r.max.y].map(f32::to_bits).hash(&mut h); + } + self.colors.hash(&mut h); + self.outside.hash(&mut h); + screen.size_in_pixels.hash(&mut h); + screen.pixels_per_point.to_bits().hash(&mut h); + self.shared.radius.to_bits().hash(&mut h); + self.shared.tier_cap.hash(&mut h); + self.shared.host.format.hash(&mut h); + h.finish() + } +} + +struct PanelMarker { + shared: Arc, + index: usize, +} +impl CallbackTrait for PanelMarker { + fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, _: &CallbackResources) { + let Ok(mut inner) = self.shared.inner.lock() else { return }; + if !self.shared.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if inner.failure.is_some() || self.shared.host.lost.is_lost() { + return; + } + let Some(marker) = inner.markers.get(self.index).copied() else { return }; + let Some(gpu) = inner.gpu.as_ref() else { return }; + if gpu.ready_serial != inner.serial || !inner.source_seen { + return; + } + let Some(binding) = gpu.markers.get(self.index) else { return }; + let mut p = [0.0; 24]; + p[2] = u8::from(self.shared.host.format.is_srgb()) as f32; + p[3] = marker.opacity; + let r = info.viewport; + if !r.is_finite() || !r.is_positive() { + return; + } + p[4..8].copy_from_slice(&[ + r.min.x * info.pixels_per_point, + r.min.y * info.pixels_per_point, + r.max.x * info.pixels_per_point, + r.max.y * info.pixels_per_point, + ]); + if marker.snap { + for value in &mut p[4..8] { + *value = value.round(); + } + } + let scale = info.pixels_per_point * r.width() / marker.rect.width(); + if !scale.is_finite() || p[4..8].iter().any(|v| !v.is_finite()) { + return; + } + p[8..12].copy_from_slice(&[marker.corners.nw, marker.corners.ne, marker.corners.sw, marker.corners.se].map(|v| f32::from(v) * scale)); + if p.iter().any(|value| !value.is_finite()) { + return; + } + // A distinct retained uniform per marker: queue writes never alias another marker's draw. + self.shared.host.queue.write_buffer(&binding.uniform, 0, &bytes_of(&p)); + pass.set_viewport(0.0, 0.0, gpu.size[0] as f32, gpu.size[1] as f32, 0.0, 1.0); + pass.set_pipeline(&gpu.panel); + pass.set_bind_group(0, &binding.group, &[]); + pass.draw(0..3, 0..1); + inner.counts.markers_drawn += 1; + } +} + +impl FrameCompositor for Shared { + fn begin_viewport(&self, viewport: u64) { + self.painting_owner.store(viewport == egui::ViewportId::ROOT.0.value(), std::sync::atomic::Ordering::Relaxed); + } + fn screen(&self, screen: &ScreenDescriptor, _: &mut CallbackResources) { + if !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Ok(mut inner) = self.inner.lock() { + inner.screen = Some((screen.size_in_pixels, screen.pixels_per_point)); + } + } + fn suspend(&self) { + if !self.host.lost.is_lost() && !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Ok(mut inner) = self.inner.lock() { + inner.gpu = None; + inner.counts.clear_live(); + inner.source_seen = false; + } + } + fn render( + &self, + renderer: &egui_wgpu::Renderer, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + jobs: &[egui::ClippedPrimitive], + screen: &ScreenDescriptor, + clear: [f32; 4], + ) -> bool { + if self.host.lost.is_lost() { + return false; + } + if !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return false; + } + let (composition, pipeline, binding, marker_ids) = { + let Ok(mut inner) = self.inner.lock() else { return false }; + if !inner.source_seen { + inner.missing_source = true; + inner.gpu = None; + inner.counts.clear_live(); + return false; + } + inner.missing_source = false; + if inner.failure.is_some() { + return false; + } + let Some(gpu) = inner.gpu.as_ref() else { return false }; + if gpu.ready_serial != inner.serial || gpu.size != screen.size_in_pixels { + return false; + } + let mut marker_ids: Vec<_> = inner.markers.iter().map(|marker| marker.callback_id).collect(); + marker_ids.sort_unstable(); + let data = (gpu.composition.view.clone(), gpu.present.clone(), gpu.presentation.group.clone(), marker_ids); + inner.counts.composition_passes += 1; + data + }; + { + let color = wgpu::Color { r: clear[0] as f64, g: clear[1] as f64, b: clear[2] as f64, a: clear[3] as f64 }; + let _clear = pass(encoder, "blur_ui_composition", &composition, color); + } + let mut start = 0; + let mut mesh_offset = 0; + let mut segment_passes = 0; + for end in 0..=jobs.len() { + let callback_id = jobs.get(end).and_then(|job| { + let egui::epaint::Primitive::Callback(callback) = &job.primitive else { return None }; + Some(Arc::as_ptr(&callback.callback) as *const () as usize) + }); + let marker = callback_id.is_some_and(|identity| marker_ids.binary_search(&identity).is_ok()); + if !marker && end != jobs.len() { + continue; + } + if start < end { + let mut ui = load_pass(encoder, "blur_ui_segment", &composition); + renderer.render_with_mesh_offset(&mut ui, &jobs[start..end], screen, mesh_offset); + mesh_offset += jobs[start..end].iter().filter(|job| matches!(&job.primitive, egui::epaint::Primitive::Mesh(_))).count(); + segment_passes += 1; + } + if marker { + // The preceding segment is complete before sampling its color target. + // Reuse the pyramid, but include previously painted UI in the backdrop. + if let Ok(mut inner) = self.inner.lock() { + let Inner { gpu, counts, .. } = &mut *inner; + if let Some(gpu) = gpu { + for step in &gpu.chain { + let mut blur = pass(encoder, "blur_backdrop", &step.target.view, wgpu::Color::TRANSPARENT); + blur.set_pipeline(if step.down { &gpu.down } else { &gpu.up }); + blur.set_bind_group(0, &step.binding.group, &[]); + blur.draw(0..3, 0..1); + counts.blur_passes += 1; + } + } + } + } + start = end; + } + { + let mut present = pass(encoder, "blur_present", target, wgpu::Color::TRANSPARENT); + present.set_pipeline(&pipeline); + present.set_bind_group(0, &binding, &[]); + present.draw(0..3, 0..1); + } + if let Ok(mut inner) = self.inner.lock() { + inner.counts.composition_passes += segment_passes; + inner.counts.present_passes += 1; + inner.rendered = true; + } + true + } + fn submitted(&self) { + if !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Ok(mut inner) = self.inner.lock() { + if inner.rendered && inner.counts.markers_drawn > inner.drawn_before && !self.host.lost.is_lost() { + let now = std::time::Instant::now(); + inner.painted = Some(PaintedFrame { + frame: inner.frame, + interval_ms: inner.submitted_at.map(|at| now.duration_since(at).as_secs_f64() * 1000.0), + continuous: inner.continuous, + }); + inner.submitted_at = Some(now); + inner.rendered = false; + } else { + inner.painted = None; + inner.submitted_at = None; + } + if self.host.lost.is_lost() { + inner.gpu = None; + inner.counts.clear_live(); + inner.failure = Some("device lost"); + } else if let Some(gpu) = inner.gpu.as_mut() + && let Some(key) = gpu.pending.take() + { + gpu.valid = Some(key); + } + } + } +} + +struct Target { + _texture: wgpu::Texture, + view: wgpu::TextureView, +} +struct Binding { + uniform: wgpu::Buffer, + group: wgpu::BindGroup, +} +struct Step { + target: Target, + binding: Binding, + down: bool, +} +struct Gpu { + size: [u32; 2], + steps: usize, + source: Target, + composition: Target, + chain: Vec, + background: Binding, + presentation: Binding, + markers: Vec, + background_pipeline: wgpu::RenderPipeline, + down: wgpu::RenderPipeline, + up: wgpu::RenderPipeline, + panel: wgpu::RenderPipeline, + present: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, + valid: Option, + pending: Option, + ready_serial: u64, +} + +fn bytes_of(params: &Params) -> [u8; 96] { + let mut bytes = [0; 96]; + for (out, value) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(params) { + out.copy_from_slice(&value.to_le_bytes()); + } + bytes +} + +fn target_bytes(size: [u32; 2], steps: usize, max: u32) -> Option { + let [w, h] = size; + if w == 0 || h == 0 || w > max || h > max || !(2..=5).contains(&steps) { + return None; + } + // S/C are four-byte UI textures; every down/up target is linear RGBA16F. + let mut total = u64::from(w).checked_mul(u64::from(h))?.checked_mul(8)?; + let mut dims = size; + for _ in 0..steps { + dims = dims.map(|d| d.div_ceil(2)); + total = total.checked_add(u64::from(dims[0]).checked_mul(u64::from(dims[1]))?.checked_mul(8)?)?; + } + dims = size; + for _ in 0..steps { + total = total.checked_add(u64::from(dims[0]).checked_mul(u64::from(dims[1]))?.checked_mul(8)?)?; + dims = dims.map(|d| d.div_ceil(2)); + } + (total <= BUDGET).then_some(total) +} + +fn pixel_rect(rect: Rect, scale: f32, size: [u32; 2]) -> Option<[u32; 4]> { + if !rect.is_finite() || !rect.is_positive() || !scale.is_finite() || scale <= 0.0 { + return None; + } + let x = (rect.min.x * scale).round().clamp(0.0, size[0] as f32) as u32; + let y = (rect.min.y * scale).round().clamp(0.0, size[1] as f32) as u32; + let right = (rect.max.x * scale).round().clamp(x as f32, size[0] as f32) as u32; + let bottom = (rect.max.y * scale).round().clamp(y as f32, size[1] as f32) as u32; + (right > x && bottom > y).then_some([x, y, right - x, bottom - y]) +} + +fn background_params(rect: Rect, clip: Rect, colors: [Color32; 2], outside: Color32, scale: f32, srgb: bool) -> Params { + let mut p = [0.0; 24]; + p[2] = u8::from(srgb) as f32; + p[4..8].copy_from_slice(&[rect.min.x * scale, rect.min.y * scale, rect.max.x * scale, rect.max.y * scale]); + p[8..12].copy_from_slice(&[clip.min.x * scale, clip.min.y * scale, clip.max.x * scale, clip.max.y * scale]); + for (out, color) in p[12..24].as_chunks_mut::<4>().0.iter_mut().zip(colors.into_iter().chain([outside])) { + out.copy_from_slice(&color.to_normalized_gamma_f32()); + } + p +} + +fn pass(encoder: &mut wgpu::CommandEncoder, label: &'static str, view: &wgpu::TextureView, clear: wgpu::Color) -> wgpu::RenderPass<'static> { + attachment_pass(encoder, label, view, wgpu::LoadOp::Clear(clear)) +} + +fn load_pass(encoder: &mut wgpu::CommandEncoder, label: &'static str, view: &wgpu::TextureView) -> wgpu::RenderPass<'static> { + attachment_pass(encoder, label, view, wgpu::LoadOp::Load) +} + +fn attachment_pass( + encoder: &mut wgpu::CommandEncoder, + label: &'static str, + view: &wgpu::TextureView, + load: wgpu::LoadOp, +) -> wgpu::RenderPass<'static> { + encoder + .begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(label), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + .forget_lifetime() +} + +impl Gpu { + fn new(device: &wgpu::Device, format: wgpu::TextureFormat, size: [u32; 2], steps: usize, offset: f32, counts: &mut Counters) -> Self { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("blur bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: std::num::NonZeroU64::new(96), + }, + count: None, + }, + ], + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("blur clamp"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("SolidCraft blur"), + source: wgpu::ShaderSource::Wgsl(include_str!("blur.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("blur pipeline layout"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let background_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("blur background uniform only"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: std::num::NonZeroU64::new(96), + }, + count: None, + }], + }); + let background_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("blur source cannot sample composition"), + bind_group_layouts: &[Some(&background_layout)], + immediate_size: 0, + }); + let pipeline = |entry: &str, target, blend, layout: &wgpu::PipelineLayout| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vertex"), buffers: &[], compilation_options: Default::default() }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(entry), + targets: &[Some(wgpu::ColorTargetState { format: target, blend, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let down = pipeline("down", wgpu::TextureFormat::Rgba16Float, None, &pipeline_layout); + let up = pipeline("up", wgpu::TextureFormat::Rgba16Float, None, &pipeline_layout); + let panel = pipeline("panel", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), &pipeline_layout); + let present = pipeline("present", format, None, &pipeline_layout); + let background_pipeline = pipeline("background", format, None, &background_pipeline_layout); + counts.pipelines_created += 5; + counts.live_pipelines += 5; + let source = Target::new(device, size, format, counts); + let composition = Target::new(device, size, format, counts); + let background = Binding::background(device, &background_layout, counts); + let presentation = Binding::new(device, &layout, &sampler, &composition.view, [0.0; 24], counts); + let mut chain: Vec = Vec::new(); + let mut dimensions = Vec::with_capacity(steps + 1); + dimensions.push(size); + for _ in 0..steps { + let last = dimensions.last().copied().unwrap_or(size); + dimensions.push(last.map(|d| d.div_ceil(2))); + } + for (index, dims) in dimensions.iter().skip(1).enumerate() { + let input = chain.last().map_or(&composition.view, |s| &s.target.view); + let mut p = [0.0; 24]; + p[0] = offset; + p[1] = u8::from(index == 0 && !format.is_srgb()) as f32; + let binding = Binding::new(device, &layout, &sampler, input, p, counts); + let target = Target::new(device, *dims, wgpu::TextureFormat::Rgba16Float, counts); + chain.push(Step { target, binding, down: true }); + } + for dims in dimensions.iter().take(steps).rev() { + let input = chain.last().map_or(&composition.view, |s| &s.target.view); + let mut p = [0.0; 24]; + p[0] = offset; + let binding = Binding::new(device, &layout, &sampler, input, p, counts); + let target = Target::new(device, *dims, wgpu::TextureFormat::Rgba16Float, counts); + chain.push(Step { target, binding, down: false }); + } + Self { + size, + steps, + source, + composition, + chain, + background, + presentation, + markers: Vec::new(), + background_pipeline, + down, + up, + panel, + present, + layout, + sampler, + valid: None, + pending: None, + ready_serial: 0, + } + } + fn grow_markers(&mut self, device: &wgpu::Device, count: usize, counts: &mut Counters) { + let Some(last) = self.chain.last() else { return }; + while self.markers.len() < count { + self.markers.push(Binding::new(device, &self.layout, &self.sampler, &last.target.view, [0.0; 24], counts)); + } + } +} + +impl Target { + fn new(device: &wgpu::Device, size: [u32; 2], format: wgpu::TextureFormat, counts: &mut Counters) -> Self { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("blur target"), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + counts.textures_created += 1; + counts.live_textures += 1; + let view = texture.create_view(&Default::default()); + Self { _texture: texture, view } + } +} +impl Binding { + fn background(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, counts: &mut Counters) -> Self { + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("blur background parameters"), + size: 96, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + counts.buffers_created += 1; + counts.live_buffers += 1; + counts.live_bytes += 96; + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("blur background has no input texture"), + layout, + entries: &[wgpu::BindGroupEntry { binding: 2, resource: uniform.as_entire_binding() }], + }); + counts.bind_groups_created += 1; + counts.live_bind_groups += 1; + Self { uniform, group } + } + fn new( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + sampler: &wgpu::Sampler, + view: &wgpu::TextureView, + params: Params, + counts: &mut Counters, + ) -> Self { + use wgpu::util::DeviceExt as _; + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("blur parameters"), + contents: &bytes_of(¶ms), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + counts.buffers_created += 1; + counts.live_buffers += 1; + counts.live_bytes += 96; + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("blur sample"), + layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }, + wgpu::BindGroupEntry { binding: 2, resource: uniform.as_entire_binding() }, + ], + }); + counts.bind_groups_created += 1; + counts.live_bind_groups += 1; + Self { uniform, group } + } +} diff --git a/crates/ui-egui/src/boundary_dialog_tests.rs b/crates/ui-egui/src/boundary_dialog_tests.rs index 54a1c44d8..ae487d3d6 100644 --- a/crates/ui-egui/src/boundary_dialog_tests.rs +++ b/crates/ui-egui/src/boundary_dialog_tests.rs @@ -5,9 +5,9 @@ use crate::dialogs::Kind; use crate::dialogs_surface::Surf; use crate::scenario::Harness; use serde_json::{Map, json}; +use solidcore_record::Vec3; use solidcraft_engine::Sel; use solidcraft_engine::doc::{FeatureKind, Operation, kernel::Continuity}; -use solidcraft_engine::geom::Vec3; fn ok(h: &mut Harness) { h.frames(2); @@ -40,7 +40,7 @@ fn a_loop_of_sketch_curves_is_the_loop_patch() { let FeatureKind::SurfaceBoundary { curves, orders, .. } = &f.kind else { panic!("{:?}", f.kind) }; assert_eq!(curves, &["s1", "s2", "s3", "s4"]); assert!(orders.iter().all(|o| *o == Continuity::G1), "{orders:?}"); - assert_eq!(h.app.session.world_state().bodies.len(), 1); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); } /// A quarter cylinder sheet (its top edge open at y = 10, z = 0) and a 3D line above it. @@ -70,7 +70,7 @@ fn edges_and_curves_make_a_network_and_come_back_in_an_edit() { let d = h.app.dialog.as_mut().unwrap(); d.inputs[0].items = vec![rim.clone(), Sel::SketchCurve { id: top.clone(), sketch: None }]; let Kind::Surface(Surf::Boundary { continuity, join }) = &mut d.kind else { panic!("{:?}", d.kind) }; - *continuity = 2; + *continuity = Continuity::G2; *join = true; ok(&mut h); let name = h.app.session.doc.features.last().unwrap().name.clone(); @@ -84,14 +84,14 @@ fn edges_and_curves_make_a_network_and_come_back_in_an_edit() { assert_eq!(u[0].continuity, Continuity::G2); assert_eq!(u[1].curves, vec![top.clone()]); // Joined into the sheet: one body, two faces. - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); assert_eq!(st.bodies.len(), 1); assert_eq!(st.body(&body).map(|b| b.body.face_count()), Some(2)); drop(st); h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); h.frames(8); let d = h.app.dialog.as_ref().unwrap(); - assert!(matches!(d.kind, Kind::Surface(Surf::Boundary { continuity: 2, join: true })), "{:?}", d.kind); + assert!(matches!(d.kind, Kind::Surface(Surf::Boundary { continuity: Continuity::G2, join: true })), "{:?}", d.kind); assert_eq!(d.inputs[0].items.len(), 2, "{:?}", d.inputs[0].items); ok(&mut h); let (u2, v2, op2) = network(&h); @@ -112,7 +112,7 @@ fn curves_that_meet_are_one_chain() { h.app.run("sketch.line", json!({"points":[[10,0],[10,8]],"ids":["d"]})).unwrap(); h.app.run("sketch.finish", json!({})).unwrap(); let sketch = h.app.session.doc.find_feature("Net").unwrap().id; - let k = Surf::Boundary { continuity: 0, join: false }; + let k = Surf::Boundary { continuity: Continuity::G0, join: false }; let (_, mut inputs) = crate::dialogs_surface::start(&h.app, "surface.boundary").unwrap(); inputs[0].items = ["a2", "b", "a1"].iter().map(|id| Sel::SketchCurve { id: (*id).into(), sketch: None }).collect(); inputs[1].items = ["c", "d"].iter().map(|id| Sel::SketchCurve { id: (*id).into(), sketch: None }).collect(); @@ -123,5 +123,5 @@ fn curves_that_meet_are_one_chain() { assert_eq!(p["v"], json!([{"sketch": sketch, "curves": ["c"]}, {"sketch": sketch, "curves": ["d"]}]), "{p}"); // And it builds: the chain a1–a2 is one boundary of the patch. h.app.run("surface.boundary", p.clone()).unwrap(); - assert_eq!(h.app.session.world_state().bodies.len(), 1); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); } diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 7acf821b7..49a35a325 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -6,7 +6,9 @@ //! viewport, a double-click on a sketch edits it, and a right-click opens the item's menu //! ([`crate::context_menu`]). +use crate::ui_kit::BackingTooltipExt as _; use crate::ui_kit::{Container, Surface}; +use solidcraft_engine::geom::prelude::*; #[path = "browser_cache.rs"] mod cache; @@ -24,6 +26,7 @@ mod model; mod features; mod point_clouds; pub use point_clouds::CloudPanel; +pub(crate) use point_clouds::point_cloud_tracks; pub(crate) fn reveal_feature(app: &mut SolveApp, id: u64, body: &str) { features::reveal(app, id, body); @@ -33,12 +36,16 @@ pub(crate) fn reveal_feature(app: &mut SolveApp, id: u64, body: &str) { /// to it, its Bodies folder and any group around it) and scroll its row into view. The rows /// are opened here, not while drawing, because a collapsed ancestor never draws its children. pub(crate) fn reveal_body(app: &mut SolveApp, body: &str) { + sync_reveals(app); app.ui.show_browser = true; app.preferences.timeline_left_browser_collapsed = false; app.tree.reveal_feature = None; app.tree.reveal = Some(body.to_string()); + remember_reveal_source(app, body); let state = app.session.model.state(); - let Some(source) = app.session.world_state().body(body).map(|selected| selected.definition_name().to_string()) else { return }; + let Some(source) = crate::open_meshing::session_world(&app.session).body(body).map(|selected| selected.definition_name().to_string()) else { + return; + }; let Some(component) = state.body(&source).map(|definition| definition.component) else { return }; // Every component's first placement keeps the definition's name, so the owner must match too. let Some((_, path, _)) = app @@ -52,13 +59,21 @@ pub(crate) fn reveal_body(app: &mut SolveApp, body: &str) { }; app.tree.collapsed.remove("c0"); for depth in 1..=path.len() { - app.tree.collapsed.remove(&occurrence_key(&path[..depth])); + app.tree.open_row(&occurrence_key(&path[..depth])); } let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(&path) }; - app.tree.collapsed.remove(&scope); + app.tree.open_row(&scope); app.tree.collapsed.remove(&format!("{scope}/bodies")); - for g in app.session.doc.browser_groups.iter().filter(|g| g.component == component && g.folder == "bodies" && g.items.contains(&source)) { - app.tree.collapsed.remove(&format!("{scope}/g{}", g.id)); + open_group_chain(app, &scope, component, "bodies", &source); +} + +/// Open the group holding an item, and the groups holding that one. +fn open_group_chain(app: &mut SolveApp, scope: &str, component: u64, folder: &str, key: &str) { + let mut at = app.session.doc.group_of_item(component, folder, key).map(|g| g.id); + for _ in 0..=solidcraft_engine::doc::MAX_GROUP_NESTING { + let Some(id) = at else { return }; + app.tree.collapsed.remove(&if scope.is_empty() { format!("g{id}") } else { format!("{scope}/g{id}") }); + at = app.session.doc.browser_group(id).and_then(|g| g.parent); } } @@ -76,27 +91,21 @@ use std::sync::{Arc, Weak}; use egui::{Color32, FontId, Pos2, Rect, Sense, Stroke, pos2, vec2}; use serde_json::{Value, json}; use solidcraft_engine::Sel; -use solidcraft_engine::doc::{Document, FeatureKind}; +use solidcraft_engine::doc::{BrowserEntry, Document, FeatureKind}; use crate::context_menu::{Item, Target}; use crate::theme::Tokens; use crate::SolveApp; -thread_local! { - /// The rows drawn this frame: (label, row, fold arrow area, open). For automation - /// (`ui.at {browser | chevron}`, `ui.browser`). - static DRAWN: std::cell::RefCell, Option)>> = const { std::cell::RefCell::new(Vec::new()) }; - static OCCURRENCES: std::cell::RefCell, String, Rect, bool)>> = const { std::cell::RefCell::new(Vec::new()) }; +/// The Browser's rows on screen: (label, row rect, fold arrow area, open). +/// Other presentations expose their geometry through `semantic_content::output`. +pub fn drawn_rows() -> Vec { + crate::semantic_content::output(crate::semantic_content::ContentOwner::BROWSER).rows } -/// The rows on screen: (label, row rect, fold arrow area, open). -pub fn drawn_rows() -> Vec<(String, Rect, Option, Option)> { - DRAWN.with(|d| d.borrow().clone()) -} - -pub fn drawn_occurrences() -> Vec<(Vec, String, Rect, bool)> { - OCCURRENCES.with(|d| d.borrow().clone()) +pub fn drawn_occurrences() -> Vec { + crate::semantic_content::output(crate::semantic_content::ContentOwner::BROWSER).occurrences } /// Browser state kept between frames. @@ -112,6 +121,10 @@ pub struct TreeState { /// of a part apart) and open the components, placements and folders above it: Find in /// Browser, and a body picked in the viewport (#3005). pub reveal: Option, + /// Enough provenance to distinguish temporary rollback/suppression from target removal. + reveal_source: Option, + /// Runtime owner of the active pending requests, including requests with numeric IDs. + reveal_session: Option, /// A native feature to reveal in its placed component's Features folder (Find in Timeline). pub(super) reveal_feature: Option, /// The Move/Copy panel of an occurrence. @@ -134,21 +147,19 @@ pub struct TreeState { /// Find in Timeline: the feature the history scrolls to the next time it draws its items, in /// the bottom strip or in the history on the left (#5850). pub timeline_reveal: Option, + /// Show components marked out of the History bar anyway (#10393). Held by the session, like + /// the bar's Show All toggle; the History controls' menu carries the switch. + pub history_show_hidden: bool, /// The feature of the face or edge last picked in the view, so a new pick scrolls the /// history to it once. pub view_pick: Option, /// The Edit Canvas / Calibrate panel. pub canvas_panel: Option, - /// The bodies a row at the top of the history lights this frame (`history_rows`), for the - /// browser, drawn after it, to keep. - history_hover: Vec, /// The Edit Point Cloud panel. pub cloud_panel: Option, - /// The plane a row at the top of the history lights this frame, kept the same way (#6975). - history_plane: Option, /// A Section Analysis hidden with its eye in the Analysis folder: its plane (origin, /// normal), so the eye can bring it back (#822). - pub hidden_section: Option<(solidcraft_engine::geom::Vec3, solidcraft_engine::geom::Vec3)>, + pub hidden_section: Option<(solidcore_record::Vec3, solidcore_record::Vec3)>, /// What the Section Analysis dialog's OK last made, for Edit to start from. pub section_dialog: Option, /// The Analysis folder hidden with its own eye, and the Section Analysis hidden with its @@ -157,14 +168,10 @@ pub struct TreeState { pub section_hidden: bool, /// What waits for the Capture Position question: a command id, or [`SAVE`]. pub capture_prompt: Option, - /// The last row clicked (for Shift ranges). - anchor: Option, - /// Row keys in drawing order this frame (for Shift ranges). - order: Vec, - /// The previous frame's complete row order: a Shift click resolves its range here, since - /// this frame's `order` does not yet hold the rows below the clicked one (#4991). - order_prev: Vec, - order_len: usize, + /// The design, undo depth and visibility when the button last went down: a drag over the eyes + /// merges the steps it made into one (`eye_drag_frame`). + eye_press: Option<(u64, Arc, usize, solidcraft_engine::Visibility)>, + pub(crate) content: crate::semantic_content::Frame, cache: Option, } @@ -174,6 +181,71 @@ struct FolderPick { doc: Weak, } +struct BodyRevealSource { + body: String, + session: u64, + creator: u64, +} + +/// Pending presentation requests parked alongside their session in a bounded document slot. +/// Pointer input (`view_pick`) deliberately never travels with the slot. +#[derive(Default)] +pub(crate) struct PendingReveals { + session: Option, + body: Option, + source: Option, + feature: Option, + timeline: Option, +} + +pub(crate) fn discard_reveals(app: &mut SolveApp) { + app.tree.reveal = None; + app.tree.reveal_source = None; + app.tree.reveal_feature = None; + app.tree.timeline_reveal = None; + app.tree.view_pick = None; + app.tree.reveal_session = Some(app.session.uid); +} + +/// Guard request creation and presentation even when a session changes after frame begin. +pub(crate) fn sync_reveals(app: &mut SolveApp) { + if app.tree.reveal_session.is_some_and(|session| session != app.session.uid) { + discard_reveals(app); + } + if app.tree.reveal_source.as_ref().is_some_and(|source| source.session != app.session.uid) { + app.tree.reveal = None; + app.tree.reveal_source = None; + } + app.tree.reveal_session = Some(app.session.uid); +} + +pub(crate) fn take_reveals(app: &mut SolveApp) -> PendingReveals { + sync_reveals(app); + app.tree.view_pick = None; + PendingReveals { + session: Some(app.session.uid), + body: app.tree.reveal.take(), + source: app.tree.reveal_source.take(), + feature: app.tree.reveal_feature.take(), + timeline: app.tree.timeline_reveal.take(), + } +} + +pub(crate) fn restore_reveals(app: &mut SolveApp, pending: PendingReveals) { + discard_reveals(app); + if pending.session == Some(app.session.uid) { + app.tree.reveal = pending.body; + app.tree.reveal_source = pending.source; + app.tree.reveal_feature = pending.feature; + app.tree.timeline_reveal = pending.timeline; + } +} + +pub(crate) fn request_timeline_reveal(app: &mut SolveApp, id: u64) { + sync_reveals(app); + app.tree.timeline_reveal = Some(id); +} + impl FolderPick { fn current(&self, app: &SolveApp) -> bool { self.session == app.session.uid && std::ptr::eq(self.doc.as_ptr(), Arc::as_ptr(&app.session.doc)) @@ -181,20 +253,35 @@ impl FolderPick { } impl TreeState { + pub(crate) fn for_session(session: u64) -> Self { + Self { reveal_session: Some(session), ..Default::default() } + } + pub(crate) fn clear_folder_pick(&mut self) { self.picked_folder = None; } - fn remember(&mut self, key: &str) { - if let Some(slot) = self.order.get_mut(self.order_len) { - if slot != key { - slot.clear(); - slot.push_str(key); - } - } else { - self.order.push(key.to_owned()); + /// Open a row. A placement's row is noted open in `expanded` as well, because it starts + /// closed unless the "Components start open" preference is on (#9274). + pub(crate) fn open_row(&mut self, key: &str) { + self.collapsed.remove(key); + if is_placement_key(key) && !self.expanded.contains(key) { + self.expanded.insert(key.to_owned()); } - self.order_len += 1; + } + + /// Close a row, whichever way its placement starts. + pub(crate) fn close_row(&mut self, key: &str) { + if !self.collapsed.contains(key) { + self.collapsed.insert(key.to_owned()); + } + if is_placement_key(key) { + self.expanded.remove(key); + } + } + + fn remember(&mut self, key: &str) { + self.content.current_mut().remember(key); } } @@ -211,7 +298,7 @@ pub struct OccMove { pub translate: [f64; 3], pub angles: [f64; 3], /// The occurrence's origin when the move began: what it turns about. - pub pivot: Option, + pub pivot: Option, /// The values when the current triad drag began. drag0: Option<([f64; 3], [f64; 3])>, } @@ -252,7 +339,7 @@ fn find_group(app: &SolveApp, id: u64) -> Option<&solidcraft_engine::doc::Browse /// World bodies of a component picked in the tree. The root is the whole design; a nested /// component is its own placement, including bodies inside it. pub(crate) fn bodies_of_component(app: &SolveApp, id: u64) -> Vec { - let present: Vec = app.session.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let present: Vec = crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect(); let mut names = if id == 0 { present.clone() } else { @@ -291,7 +378,7 @@ fn offer_bodies(app: &mut SolveApp, names: &[String], take: Take) -> bool { if !dialog_takes_body(app) || app.dialog.as_ref().is_some_and(|d| d.takes_components()) { return false; } - let world = app.session.world_state(); + let world = crate::open_meshing::session_world(&app.session); let picked: Vec = names.iter().filter(|n| world.body(n).is_some() && !app.session.body_removed_later(n)).map(|n| Sel::Body { name: n.clone() }).collect(); if picked.is_empty() { @@ -313,10 +400,10 @@ fn offer_bodies(app: &mut SolveApp, names: &[String], take: Take) -> bool { /// The bodies in a group (none for sketch and plane groups). pub fn group_bodies(app: &SolveApp, id: u64) -> Vec { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); find_group(app, id) .filter(|g| g.folder == "bodies") - .map(|g| g.items.iter().filter(|b| st.body(b).is_some()).cloned().collect()) + .map(|_| app.session.doc.group_item_keys(id).into_iter().filter(|b| st.body(b).is_some()).collect()) .unwrap_or_default() } @@ -347,8 +434,12 @@ pub fn group_items(app: &SolveApp, id: u64, scope: &str) -> Vec { if g.folder == "bodies" || g.folder == "sketches" { v.push(paste_item(app, g.component, scope, &g.folder, Some(id))); } + // A group inside this one, unless it is already as deep as groups go. + if app.session.doc.group_level(id) < solidcraft_engine::doc::MAX_GROUP_NESTING { + v.push(Item::action("ui.newGroup", "New Group", "folder").with(json!({ "component": g.component, "folder": g.folder, "parent": id }))); + } v.extend([ - Item::action("ui.rename", "Rename", "rename").with(json!({ "group": id })), + Item::action("ui.rename", "Rename", "rename").key("F2").with(json!({ "group": id })), Item::action("ui.ungroup", "Ungroup", "folder").with(json!({ "group": id })), Item::sep(), // The group itself: its items keep their own state. @@ -360,6 +451,11 @@ pub fn group_items(app: &SolveApp, id: u64, scope: &str) -> Vec { v } +/// Move Sketches to Their Parts (`component.move_sketches.to_parts`) for `sketches` (ids). +pub(crate) fn sketches_to_parts_item(sketches: Vec) -> Item { + Item::action("component.move_sketches.to_parts", "Move Sketches to Their Parts", "move").with(json!({ "sketches": sketches })) +} + /// The menu of a folder row (Bodies, Sketches, Construction). pub fn folder_items(app: &SolveApp, component: u64, folder: &str, scope: &str) -> Vec { let sel: Vec = selected_keys(app, component, folder); @@ -372,11 +468,13 @@ pub fn folder_items(app: &SolveApp, component: u64, folder: &str, scope: &str) - } if folder == "sketches" { v.push(paste_item(app, component, scope, folder, None)); + // The folder's selected sketches, or all of them, go to the part whose face they are on (#10218). + if !app.session.doc.components.is_empty() && !all.is_empty() { + let sketches = if sel.is_empty() { all.iter().map(|e| e.key.clone()).collect() } else { sel.clone() }; + v.push(sketches_to_parts_item(sketches)); + } } - v.push( - Item::action("ui.newGroup", if folder == "sketches" { "New Sketch Group" } else { "New Group" }, "folder") - .with(json!({ "component": component, "folder": folder })), - ); + v.push(Item::action("ui.newGroup", "New Group", "folder").with(json!({ "component": component, "folder": folder }))); if sel.len() > 1 { v.push(Item::action("ui.groupSelected", "Group Selected", "folder").with(json!({ "component": component, "folder": folder, "items": sel }))); } @@ -425,6 +523,53 @@ pub fn toggle_folder(app: &mut SolveApp, key: &str) { let _ = app.run("browser.visibility", json!({ "tree_folders": [key], "visible": app.session.folder_hidden(key) })); } +/// A drag over the eyes is one undo step (#9680). When the button goes down the undo depth and the +/// hidden items are noted; when it comes up, the steps the drag made are merged into the first of +/// them. Runs every frame, whatever else is open, so a release is never missed. +pub(crate) fn eye_drag_frame(app: &mut SolveApp, ctx: &egui::Context) { + crate::semantic_content::ensure_session(app, ctx); + let (pressed, down) = ctx.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_down())); + if pressed && app.tree.eye_press.is_none() { + app.tree.eye_press = Some((app.session.uid, app.session.doc.clone(), app.session.undo.len(), without_origin(app.session.visibility.clone()))); + } + if down { + return; + } + end_eye_drag(app, ctx); +} + +/// Also called when the presentation holding the gesture disappears while the button is down. +pub(crate) fn end_eye_drag(app: &mut SolveApp, ctx: &egui::Context) { + let capture = crate::semantic_content::release_eye(ctx); + let dragged = ctx.data_mut(|d| d.remove_temp::(crate::ui_kit::eye_drag_id())).is_some(); + let Some((_, doc, depth, visibility)) = app + .tree + .eye_press + .take() + .filter(|(session, ..)| dragged && *session == app.session.uid && capture.is_none_or(|source| source.session == *session)) + else { + return; + }; + // shortcut: once the history is full (200 steps) its length stops growing, so the drag is left as + // separate steps, like the point-cloud and canvas drags; the visibility test keeps a trimmed front + // from being merged wrongly. + let undo = &mut app.session.undo; + if undo.len() > depth + 1 && undo.get(depth).is_some_and(|s| Arc::ptr_eq(&s.doc, &doc) && without_origin(s.visibility.clone()) == visibility) { + undo.truncate(depth + 1); + } +} + +pub(crate) fn discard_eye_press(app: &mut SolveApp) { + app.tree.eye_press = None; +} + +/// The Origin's own eye is not an undo step (`set_origin_shown`), so the drag's steps do not hold it: +/// it is left out of the comparison. +fn without_origin(mut visibility: solidcraft_engine::Visibility) -> solidcraft_engine::Visibility { + visibility.origin_hidden = None; + visibility +} + /// A folder shortcut target lasts until another click, Escape, or a change of design/model. /// Visibility changes keep the document snapshot, so V can toggle the same folder again. pub(crate) fn update_folder_pick(app: &mut SolveApp, ctx: &egui::Context) { @@ -439,6 +584,14 @@ fn pick_folder(app: &mut SolveApp, key: &str) { app.tree.picked_folder = Some(FolderPick { key: key.into(), session: app.session.uid, doc: Arc::downgrade(&app.session.doc) }); } +/// The group whose row was clicked last (its key ends in `/g`), while that pick still holds +/// and the group exists: F2 renames it (#10005). +pub(crate) fn picked_group(app: &SolveApp) -> Option { + let pick = app.tree.picked_folder.as_ref().filter(|pick| pick.current(app))?; + let id = pick.key.rsplit_once("/g")?.1.parse().ok()?; + find_group(app, id).map(|g| g.id) +} + pub(crate) fn toggle_picked_folder(app: &mut SolveApp) -> bool { let Some(pick) = app.tree.picked_folder.as_ref().filter(|pick| pick.current(app)) else { return false }; let key = pick.key.clone(); @@ -451,7 +604,7 @@ pub(crate) fn toggle_picked_folder(app: &mut SolveApp) -> bool { pub fn selection_group(app: &SolveApp, target: &Target) -> Option { let (comp, folder) = match target { Target::Body { name } => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let b = st.body(name)?; (b.component, "bodies") } @@ -470,9 +623,13 @@ pub fn group_action(app: &mut SolveApp, action: &str, p: &Value) { let folder = p.get("folder").and_then(Value::as_str).unwrap_or("bodies"); let comp = p.get("component").and_then(Value::as_u64).unwrap_or(0); let items = p.get("items").cloned().unwrap_or(json!([])); - if let Ok(r) = app.run("browser.group", json!({ "component": comp, "folder": folder, "items": items })) + let parent = p.get("parent").and_then(Value::as_u64); + if let Ok(r) = app.run("browser.group", json!({ "component": comp, "folder": folder, "items": items, "parent": parent })) && let Some(g) = r.get("group").and_then(Value::as_u64) { + if let Some(parent) = parent { + app.tree.collapsed.remove(&format!("c{comp}/g{parent}")); + } app.tree.collapsed.remove(&format!("c{comp}/{folder}")); app.tree.collapsed.remove(&format!("c{comp}/g{g}")); } @@ -511,13 +668,23 @@ fn compact_tree(ui: &egui::Ui) -> bool { ui.ctx().data(|d| d.get_temp::(egui::Id::new("sc_compact_tree"))).unwrap_or(false) } +/// Where tree rows put their eye this frame (Preferences › Interface, #8718). +pub(crate) fn publish_row_prefs(app: &SolveApp, ctx: &egui::Context) { + ctx.data_mut(|d| d.insert_temp(egui::Id::new("sc_tree_eye_left"), app.preferences.browser_eye_left)); +} + +fn eye_left(ui: &egui::Ui) -> bool { + ui.ctx().data(|d| d.get_temp::(egui::Id::new("sc_tree_eye_left"))).unwrap_or(false) +} + pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row<'_>) -> RowResp { let compact = compact_tree(ui); - let out = crate::ui_kit::tree_row(ui, id, &Row { compact, ..*row }); + let mut out = crate::ui_kit::tree_row(ui, id, &Row { compact, eye_left: eye_left(ui), ..*row }); + crate::semantic_content::route_response(ui, id, &mut out); if let Some(r) = out.rect.filter(|r| ui.is_rect_visible(*r)) { let x = r.left() + if compact { Tokens::get().space_8 } else { 2.0 } + row.depth as f32 * INDENT; let fold = row.fold.map(|_| Rect::from_min_max(pos2(x - 4.0, r.top()), pos2(x + 15.0, r.bottom()))); - DRAWN.with(|d| d.borrow_mut().push((row.label.to_string(), r, fold, row.fold))); + crate::semantic_content::record_row(ui, (row.label.to_string(), r, fold, row.fold), &out); } out } @@ -525,11 +692,11 @@ pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row<'_>) -> RowRes /// A Ctrl/Shift-aware click on a selectable row. fn click_select(app: &mut SolveApp, ui: &egui::Ui, key: String, sel: Option) { let mods = ui.input(|i| i.modifiers); + let rows = app.tree.content.current_mut(); if mods.shift - && let Some(a) = app.tree.anchor.as_deref() + && let Some(a) = rows.anchor.as_deref() { - let order = app.tree.order.get(..app.tree.order_len).unwrap_or(&[]); - let items = shift_range(&app.tree.order_prev, a, &key).or_else(|| shift_range(order, a, &key)); + let items = shift_range(&rows.previous, a, &key).or_else(|| shift_range(rows.current_order(), a, &key)); if let Some(items) = items { // Move/Copy (and any open command whose active input takes bodies) gets every body // in the range. Otherwise the range is an ordinary selection. @@ -547,7 +714,7 @@ fn click_select(app: &mut SolveApp, ui: &egui::Ui, key: String, sel: Option return; } } - app.tree.anchor = Some(key); + app.tree.content.current_mut().anchor = Some(key); let Some(sel) = sel else { return }; if mods.command || mods.ctrl { if app.session.selection.contains(&sel) { @@ -602,28 +769,59 @@ pub(crate) fn picked_body(sel: &Sel) -> Option<&str> { /// A pick in the viewport: the Browser, when shown, opens down to the picked body's row and /// scrolls to it (#3005). The body of the last item picked. pub(crate) fn reveal_pick(app: &mut SolveApp) { + sync_reveals(app); if app.ui.show_browser && let Some(body) = app.session.selection.last().and_then(picked_body) { - app.tree.reveal = Some(body.to_string()); + let body = body.to_owned(); + remember_reveal_source(app, &body); + app.tree.reveal = Some(body); } } +fn remember_reveal_source(app: &mut SolveApp, body: &str) { + app.tree.reveal_source = crate::open_meshing::session_world(&app.session).body(body).map(|selected| BodyRevealSource { + body: body.to_owned(), + session: app.session.uid, + creator: selected.feature, + }); +} + /// The placement path of the body being revealed, resolved once per model: a row opens when /// the body's path runs through it, instead of every row expanding its subtree to test /// containment (#7502). `None` when nothing is revealed or the body is a top-level design body. fn reveal_path(app: &mut SolveApp) -> Option> { - let body = app.tree.reveal.clone()?; + let body = body_reveal(app)?.to_owned(); prepare_model(app); app.tree.model.as_mut()?.body_path(&app.session, &body) } +/// A placement's own row (`o:1/2`), not a folder under it (`o:1/2/bodies`). +pub(crate) fn is_placement_key(key: &str) -> bool { + key.strip_prefix("o:").is_some_and(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit() || b == b'/')) +} + +/// Whether a placement's row is open. Placements start closed, so a large assembly opens as a +/// short list (#9274); the "Components start open" preference keeps them open as before. +pub(crate) fn placement_open(app: &SolveApp, key: &str) -> bool { + !app.tree.collapsed.contains(key) && (app.preferences.browser_components_open || app.tree.expanded.contains(key)) +} + pub(crate) fn is_open(app: &SolveApp, key: &str, default: bool) -> bool { + if is_placement_key(key) { + return placement_open(app, key); + } if default { !app.tree.collapsed.contains(key) } else { app.tree.expanded.contains(key) } } pub(crate) fn toggle(app: &mut SolveApp, key: &str, default: bool) { - if default { + if is_placement_key(key) { + if placement_open(app, key) { + app.tree.close_row(key); + } else { + app.tree.open_row(key); + } + } else if default { if !app.tree.collapsed.remove(key) { app.tree.collapsed.insert(key.to_string()); } @@ -633,18 +831,19 @@ pub(crate) fn toggle(app: &mut SolveApp, key: &str, default: bool) { } /// Apply Expand All / Collapse All: open-by-default keys live in `collapsed` when closed; -/// closed-by-default keys live in `expanded` when open. +/// closed-by-default keys live in `expanded` when open. Placements, whichever way they start, +/// are noted in both. pub fn apply_fold(app: &mut SolveApp, open: bool, open_by_default: &[String], closed_by_default: &[String]) { if open { for key in open_by_default { - app.tree.collapsed.remove(key); + app.tree.open_row(key); } for key in closed_by_default { app.tree.expanded.insert(key.clone()); } } else { for key in open_by_default { - app.tree.collapsed.insert(key.clone()); + app.tree.close_row(key); } for key in closed_by_default { app.tree.expanded.remove(key); @@ -654,17 +853,24 @@ pub fn apply_fold(app: &mut SolveApp, open: bool, open_by_default: &[String], cl /// Everything a frame's rows want done, applied after drawing. #[derive(Default)] -struct Actions { +pub(crate) struct Actions { + pub(crate) session: Option, menu: Option<(Pos2, Target)>, - hover_bodies: Vec, - hovered: bool, + pub(crate) hover_bodies: Vec, + pub(crate) hovered: bool, /// The plane whose row is under the pointer, lit in the view (#6975). - hover_plane: Option, - drop: Option, + pub(crate) hover_plane: Option, + drop: Option<(crate::semantic_content::ContentSource, DropAction)>, /// What the selection and the 3D view's pointer light in the tree. lit: Lit, } +impl Actions { + fn drop_from(&mut self, source: crate::semantic_content::ContentSource, action: DropAction) { + self.drop = Some((source, action)); + } +} + /// Something in the 3D view with a row in the tree. #[derive(Clone, Debug, PartialEq, Eq, Hash)] enum Thing { @@ -702,10 +908,11 @@ impl Lit { // which does not rewrite the browser selection. let dialog_picks = app.dialog.as_ref().map(|d| d.items()).unwrap_or_default(); for s in app.session.selection.iter().chain(&dialog_picks) { - selected.insert(match s { - Sel::Body { name } | Sel::Face { body: name, .. } | Sel::Edge { body: name, .. } | Sel::Vertex { body: name, .. } => { - Thing::Body(name.clone()) - } + let thing = match s { + Sel::Body { name } => Thing::Body(name.clone()), + // A picked face, edge or vertex lights the feature it belongs to (see + // `browser::features`), not the whole body as if the body were selected. + Sel::Face { .. } | Sel::Edge { .. } | Sel::Vertex { .. } => continue, Sel::Feature { id } => Thing::Sketch(*id), Sel::Profile { sketch, .. } | Sel::ExternalSketchCurve { sketch, .. } | Sel::ExternalSketchPoint { sketch, .. } => { Thing::Sketch(*sketch) @@ -720,7 +927,8 @@ impl Lit { Sel::Axis { name } => Thing::Axis(name.clone()), Sel::ConstructionPoint { name } => Thing::Point(name.clone()), Sel::Occurrence { .. } | Sel::Drawing { .. } => continue, - }); + }; + selected.insert(thing); } let hovered = match &app.viewport.hover { Some(Hit::Face { body, .. } | Hit::Edge { body, .. } | Hit::Vertex { body, .. }) => Some(Thing::Body(body.clone())), @@ -896,16 +1104,11 @@ fn reveal_tab(ui: &egui::Ui, card: Rect, opacity: f32) { /// One content-hugging browser; the shared container supplies floating or flush compact chrome. pub fn browser(app: &mut SolveApp, ui: &mut egui::Ui) { + sync_reveals(app); let available = ui.available_rect_before_wrap(); let t = Tokens::get(); - std::mem::swap(&mut app.tree.order_prev, &mut app.tree.order); - app.tree.order_len = 0; - DRAWN.with(|d| d.borrow_mut().clear()); - OCCURRENCES.with(|d| d.borrow_mut().clear()); - let mut acts = Actions { hover_bodies: std::mem::take(&mut app.viewport.hover_bodies), ..Default::default() }; if crate::render_workspace::active(app) { - render_card(app, ui, &mut acts); - finish_browser(app, ui, acts); + render_card(app, ui); return; } let stacked = !crate::drawing_workspace::active(app) && crate::timeline_left::stacked(app); @@ -963,7 +1166,7 @@ pub fn browser(app: &mut SolveApp, ui: &mut egui::Ui) { if collapsed { browser_collapsed_rail(app, ui); } else { - browser_contents(app, ui, &mut acts, true); + browser_contents(app, ui, true); } }) }) @@ -983,10 +1186,9 @@ pub fn browser(app: &mut SolveApp, ui: &mut egui::Ui) { crate::scenario::publish_rect("browser:float", rect); } } - finish_browser(app, ui, acts); } -fn render_card(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { +fn render_card(app: &mut SolveApp, ui: &mut egui::Ui) { let bounds = crate::shell::panel_bounds(app, ui.available_rect_before_wrap()); let narrow = bounds.width() < 800.0; crate::shell::register_panel(app, "render:browser:show", None, None); @@ -1033,7 +1235,7 @@ fn render_card(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { } } ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("sc_compact_tree"), true)); - browser_contents(app, ui, acts, true); + browser_contents(app, ui, true); ui.ctx().data_mut(|d| d.remove::(egui::Id::new("sc_compact_tree"))); }, ); @@ -1081,7 +1283,7 @@ fn browser_collapsed_rail(app: &mut SolveApp, ui: &mut egui::Ui) { crate::scenario::publish_handle("left-browser-toggle", disclosure.center()); crate::scenario::publish_target("browser:header", disclosure); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("ui.browser_title"))); - if response.on_hover_text(crate::i18n::tr("ui.browser_expand")).clicked() { + if response.backing_on_hover_text(crate::i18n::tr("ui.browser_expand")).clicked() { app.preferences.timeline_left_browser_collapsed = false; } let galley = ui.painter().layout_no_wrap(crate::i18n::tr("ui.browser_title").to_owned(), crate::fonts::semibold(t.font_body), t.text); @@ -1099,7 +1301,7 @@ pub(crate) fn panel_bounds(available: Rect, history: Option, width: f32, g Rect::from_min_max(min, pos2((min.x + width).min(right), bottom)) } -fn browser_contents(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, collapsible: bool) { +fn browser_contents(app: &mut SolveApp, ui: &mut egui::Ui, collapsible: bool) { let t = Tokens::get(); // Only the floating card folds; the docked column keeps its full height. let render = crate::render_workspace::active(app); @@ -1129,9 +1331,9 @@ fn browser_contents(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, c } crate::edit_in_place::browser_strip(app, ui); if collapsible && !stacked { - browser_rows_hugging(app, ui, acts); + browser_rows_hugging(app, ui); } else { - browser_rows(app, ui, acts); + browser_rows(app, ui); } } @@ -1175,7 +1377,7 @@ fn browser_header(app: &mut SolveApp, ui: &mut egui::Ui, collapsible: bool) { ui.painter().galley(pos2(right - galley.size().x, rect.center().y - galley.size().y / 2.0), galley, t.text_dim); if collapsible { let tip = crate::i18n::tr(if collapsed { "ui.browser_expand" } else { "ui.browser_collapse" }); - if response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tip).clicked() { + if response.on_hover_cursor(egui::CursorIcon::PointingHand).backing_on_hover_text(tip).clicked() { if stacked { app.preferences.timeline_left_browser_collapsed = !app.preferences.timeline_left_browser_collapsed; } else if vertical { @@ -1230,6 +1432,7 @@ fn model_feature_indices(app: &SolveApp, component: u64, sketches: bool) -> Vec< .doc .features .iter() + .take(app.session.doc.marker.unwrap_or(app.session.doc.features.len())) .enumerate() .filter_map(|(i, f)| { let kind = if sketches { @@ -1246,14 +1449,24 @@ fn model_feature_indices(app: &SolveApp, component: u64, sketches: bool) -> Vec< } } -fn browser_rows(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { - rows_scrolling(app, ui, acts, false); +fn browser_rows(app: &mut SolveApp, ui: &mut egui::Ui) { + crate::semantic_content::show( + app, + ui, + crate::semantic_content::ContentOwner::BROWSER, + crate::semantic_content::ContentRequest::Browser { shrink_height: false }, + ); } /// As [browser_rows], but the area hugs the rows it drew (the floating card), up to the height /// the caller allowed. -fn browser_rows_hugging(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { - rows_scrolling(app, ui, acts, true); +fn browser_rows_hugging(app: &mut SolveApp, ui: &mut egui::Ui) { + crate::semantic_content::show( + app, + ui, + crate::semantic_content::ContentOwner::BROWSER, + crate::semantic_content::ContentRequest::Browser { shrink_height: true }, + ); } fn rows_scrolling(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, shrink_height: bool) { @@ -1262,7 +1475,6 @@ fn rows_scrolling(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, shr return; } prepare_model(app); - acts.lit = Lit::of(app); let mut cache = app.tree.cache.take().unwrap_or_default(); cache.prepare(app); egui::ScrollArea::vertical() @@ -1282,23 +1494,32 @@ fn rows_scrolling(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, shr component_rows(app, ui, 0, 0, acts, &mut cache); } }); - // The row was reached and scrolled to, or isn't in the tree (a body a later feature removes): - // either way the reveal is done. - app.tree.reveal = None; app.tree.cache = Some(cache); } -/// The Bodies folder and the Origin at the top of the vertical History (Preferences › Interface: -/// Show origin and bodies at the top, #6490): the browser's own rows, with their eyes, selection, -/// menus and fold state. The bodies are the active component's, in the placement being edited, -/// as that component's folder in the browser lists them. The rows stay out of the browser's row -/// order, automation list and reveal, which the browser keeps for its own rows. +/// Existing semantic rows, reusable by either presentation without a panel host. +pub(crate) fn render_content(app: &mut SolveApp, ui: &mut egui::Ui, request: crate::semantic_content::ContentRequest) -> Actions { + crate::semantic_content::ensure_session(app, ui.ctx()); + let mut acts = Actions { session: Some(app.session.uid), lit: Lit::of(app), ..Default::default() }; + match request { + crate::semantic_content::ContentRequest::Browser { shrink_height } => rows_scrolling(app, ui, &mut acts, shrink_height), + crate::semantic_content::ContentRequest::ActiveBodiesOrigin => active_bodies_origin(app, ui, &mut acts), + } + acts +} + +/// History's optional prefix shares the Browser's cache, folds, row renderers and commands. pub(crate) fn history_rows(app: &mut SolveApp, ui: &mut egui::Ui) { + crate::semantic_content::show( + app, + ui, + crate::semantic_content::ContentOwner::HISTORY, + crate::semantic_content::ContentRequest::ActiveBodiesOrigin, + ); +} + +fn active_bodies_origin(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { prepare_model(app); - let mut acts = Actions { lit: Lit::of(app), ..Default::default() }; - let reveal = app.tree.reveal.take(); - let order = app.tree.order_len; - let drawn = DRAWN.with(|d| d.borrow().len()); let component = app.session.active_component; let path = (component != 0) .then(|| app.session.active_occurrence_path.clone().unwrap_or_else(|| app.session.doc.first_path(component))) @@ -1310,18 +1531,18 @@ pub(crate) fn history_rows(app: &mut SolveApp, ui: &mut egui::Ui) { app.tree.cache = Some(cache); ui.scope(|ui| { ui.spacing_mut().item_spacing.y = 0.0; - folder_rows_at(app, ui, component, path.as_deref(), "bodies", 0, &mut acts, &bodies); - origin_rows(app, ui, 0, &mut acts); + folder_rows_at(app, ui, component, path.as_deref(), "bodies", 0, acts, &bodies); + origin_rows(app, ui, 0, acts); }); - app.tree.reveal = reveal; - // The browser's own rows reuse these order slots (`TreeState::remember`). - app.tree.order_len = order; - DRAWN.with(|d| d.borrow_mut().truncate(drawn)); - app.viewport.hover_bodies = acts.hover_bodies.clone(); - app.tree.history_hover = acts.hover_bodies; - app.viewport.hover_plane = acts.hover_plane.clone(); - app.tree.history_plane = acts.hover_plane; - if let Some(d) = acts.drop { +} + +pub(crate) fn apply_content_actions(app: &mut SolveApp, acts: Actions) { + if acts.session != Some(app.session.uid) { + return; + } + if let Some((_, d)) = acts.drop.filter(|(source, _)| crate::semantic_content::source_present(app, *source)) { + // The target may have consumed a payload before its source's absence was known. + // Commit only after all owners have reported, using the payload's original source. apply_drop(app, d); } if let Some((at, target)) = acts.menu { @@ -1329,22 +1550,16 @@ pub(crate) fn history_rows(app: &mut SolveApp, ui: &mut egui::Ui) { } } -fn finish_browser(app: &mut SolveApp, ui: &mut egui::Ui, mut acts: Actions) { - app.tree.order.truncate(app.tree.order_len); - if !acts.hovered { - acts.hover_bodies.clear(); - } - // The history's rows, drawn before the browser, light bodies too (`history_rows`). - let history = std::mem::take(&mut app.tree.history_hover); - app.viewport.hover_bodies = if acts.hover_bodies.is_empty() { history } else { acts.hover_bodies }; - let history_plane = app.tree.history_plane.take(); - app.viewport.hover_plane = acts.hover_plane.or(history_plane); - if let Some(d) = acts.drop { - apply_drop(app, d); - } - if let Some((at, target)) = acts.menu { - crate::context_menu::open_for(app, at, target); +pub(crate) fn cancel_content_drag(ctx: &egui::Context, session: u64) { + if egui::DragAndDrop::payload::(ctx).is_some_and(|payload| payload.source.session == session) + || egui::DragAndDrop::payload::(ctx).is_some_and(|payload| payload.source.session == session) + { + egui::DragAndDrop::clear_payload(ctx); } +} + +/// App-owned editor lifecycle; these windows do not depend on any tree being presented. +pub(crate) fn editors(app: &mut SolveApp, ui: &mut egui::Ui) { crate::browser_prompts::occurrence_panel(app, ui); crate::browser_prompts::capture_prompt(app, ui.ctx()); crate::browser_canvas::panel(app, ui.ctx()); @@ -1352,6 +1567,43 @@ fn finish_browser(app: &mut SolveApp, ui: &mut egui::Ui, mut acts: Actions) { crate::sketch_attachment_ui::panel(app, ui.ctx()); } +/// History's prefix must neither open ancestors nor acknowledge a Browser reveal. +fn body_reveal(app: &SolveApp) -> Option<&str> { + app.tree.content.browser_presentation().then_some(app.tree.reveal.as_deref()).flatten() +} + +/// A hidden or collapsed presentation retains its request. Removed targets expire here. +pub(crate) fn prune_reveals(app: &mut SolveApp) { + sync_reveals(app); + if let Some(body) = app.tree.reveal.as_ref() { + let world = crate::open_meshing::session_world(&app.session); + let source = app.tree.reveal_source.as_ref().filter(|source| source.body == *body); + let removed = source.is_some_and(|source| source.session != app.session.uid || app.session.doc.feature(source.creator).is_none()); + let evaluated = match source { + Some(source) => app.session.doc.features.iter().enumerate().any(|(index, feature)| { + feature.id == source.creator && !feature.suppressed && app.session.doc.marker.is_none_or(|marker| index < marker) + }), + None => app.session.doc.marker.is_none() && !app.session.doc.features.iter().any(|feature| feature.suppressed), + }; + // A refused feature can temporarily remove a body from evaluation too. Its pending + // reveal remains useful when the feature is repaired. + let healthy = + app.session.model.results.iter().all(|result| result.error.is_none()) && crate::open_meshing::placement_error(&app.session).is_none(); + if world.body(body).is_none() && (removed || (evaluated && healthy)) { + app.tree.reveal = None; + app.tree.reveal_source = None; + } + } else { + app.tree.reveal_source = None; + } + if app.tree.reveal_feature.as_ref().is_some_and(|target| app.session.doc.feature(target.id).is_none()) { + app.tree.reveal_feature = None; + } + if app.tree.timeline_reveal.is_some_and(|id| app.session.doc.feature(id).is_none()) { + app.tree.timeline_reveal = None; + } +} + fn component_name(app: &SolveApp, id: u64) -> String { if id == 0 { return app.session.doc.name.clone(); @@ -1388,7 +1640,7 @@ fn component_rows_inner( return; } let key = &root.key; - let reveal = app.tree.reveal.clone(); + let reveal = body_reveal(app).map(str::to_owned); if let Some(body) = reveal.as_ref() { let reveals = cache.root_bodies.contains(body) || reveal_path(app).is_some_and(|rp| root.children.iter().any(|path| rp.starts_with(path.as_slice()))); @@ -1469,9 +1721,9 @@ fn component_rows_inner( } // Bodies and sketches dropped on a component move into it. if let Some(resp) = &r.resp - && let Some(d) = drop_target(ui, resp, |d: &Drag| d.comp != id && d.folder != "construction", DropMark::Box) + && let Some(d) = drop_target(ui, resp, |d: &Drag| d.comp != id && d.folder != "construction" && d.groups.is_empty(), DropMark::Box) { - acts.drop = Some(DropAction::Component { to: id, folder: d.folder, keys: d.keys.clone() }); + acts.drop_from(d.source, DropAction::Component { to: id, folder: d.folder, keys: d.keys.clone() }); } // A placement row dropped on the design row moves out to the design. @@ -1479,7 +1731,7 @@ fn component_rows_inner( && let Some(d) = occurrence_drop_target(ui, resp, |d| occurrence_can_land(app, d, id)) { let occurrence = d.path.last().copied().unwrap_or(0); - acts.drop = Some(DropAction::Reparent { occurrence, path: d.path.clone(), parent: id, parent_path: None }); + acts.drop_from(d.source, DropAction::Reparent { occurrence, path: d.path.clone(), parent: id, parent_path: None }); } if !open { return; @@ -1527,7 +1779,7 @@ fn occurrence_key(path: &[u64]) -> String { /// Show a placement's row closed: a pasted (or moved) component arrives folded, whatever a row /// at that path showed before. pub(crate) fn close_placement(app: &mut SolveApp, path: &[u64]) { - app.tree.collapsed.insert(occurrence_key(path)); + app.tree.close_row(&occurrence_key(path)); } /// A placement, rather than a component definition: repeated child IDs remain distinct @@ -1550,7 +1802,7 @@ fn occurrence_rows_inner( ) { let key = &placement.key; if reveal_path(app).is_some_and(|rp| rp.starts_with(path)) { - app.tree.collapsed.remove(key); + app.tree.open_row(key); } let open = is_open(app, key, true); let on_screen = ui.is_rect_visible(row_rect(ui)); @@ -1593,16 +1845,19 @@ fn occurrence_rows_inner( }, ); if let Some(rect) = r.rect.filter(|_| r.resp.is_some()) { - OCCURRENCES.with(|d| d.borrow_mut().push((path.to_vec(), placement.name.clone(), rect, open))); - crate::scenario::publish_handle(&format!("row:occurrence:{}", key.trim_start_matches("o:")), pos2(rect.right() - 12.0, rect.center().y)); - let x = rect.left() + 2.0 + depth as f32 * INDENT; - for (control, offset) in [("fold", 6.0), ("eye", 22.0), ("activate", 38.0)] { - crate::scenario::publish_handle(&format!("{control}:occurrence:{}", key.trim_start_matches("o:")), pos2(x + offset, rect.center().y)); + crate::semantic_content::record_occurrence(ui, (path.to_vec(), placement.name.clone(), rect, open)); + // Near the row's end, clear of an eye there. + let end = r.eye_at.filter(|e| e.x > rect.center().x).map_or(rect.right() - 12.0, |e| e.x - 24.0); + crate::scenario::publish_handle(&format!("row:occurrence:{}", key.trim_start_matches("o:")), pos2(end, rect.center().y)); + for (control, at) in [("fold", r.fold_at), ("eye", r.eye_at), ("activate", r.radio_at)] { + if let Some(at) = at { + crate::scenario::publish_handle(&format!("{control}:occurrence:{}", key.trim_start_matches("o:")), at); + } } } if let Some(resp) = &r.resp { let inherited = if own_visible && !visible { "\nHidden by a parent placement. Show the parent to reveal this instance." } else { "" }; - resp.clone().on_hover_ui(|ui| { + resp.clone().backing_on_hover_ui(|ui| { ui.label(&placement.tooltip); if !inherited.is_empty() { ui.label(inherited.trim_start()); @@ -1610,8 +1865,11 @@ fn occurrence_rows_inner( }); // Dragging the row moves the placement it stands for. A press on its fold arrow, eye or // radio is not a drag of the row, so those controls keep their own jobs. - if resp.drag_started() && !r.on_control { - resp.dnd_set_drag_payload(OccurrenceDrag { path: path.to_vec(), component: placement.component }); + if resp.drag_started() + && !r.on_control + && let Some(source) = crate::semantic_content::current_source(app) + { + resp.dnd_set_drag_payload(OccurrenceDrag { source, path: path.to_vec(), component: placement.component }); } } if r.fold { @@ -1630,7 +1888,7 @@ fn occurrence_rows_inner( if r.double && !takes_components && app.session.doc.parts.contains_key(&placement.component) { crate::dialogs_part_size::open(app, placement.component); } - if r.clicked && takes_components { + if r.clicked && (takes_components || crate::dialogs_move::picks_components(app)) { if let Some(mut d) = app.dialog.take() { d.pick(&app.session, Sel::Occurrence { path: path.to_vec() }); app.dialog = Some(d); @@ -1652,17 +1910,38 @@ fn occurrence_rows_inner( acts.menu = Some((p, Target::Occurrence { path: path.to_vec() })); } if let Some(resp) = &r.resp - && let Some(d) = drop_target(ui, resp, |d: &Drag| d.comp != placement.component && d.folder != "construction", DropMark::Box) + && let Some(d) = + drop_target(ui, resp, |d: &Drag| d.comp != placement.component && d.folder != "construction" && d.groups.is_empty(), DropMark::Box) { - acts.drop = Some(DropAction::Component { to: placement.component, folder: d.folder, keys: d.keys.clone() }); + acts.drop_from(d.source, DropAction::Component { to: placement.component, folder: d.folder, keys: d.keys.clone() }); } + // The top of a sibling's row puts the dragged placement before it; the rest of the row, and + // any other row, moves the placement into this row's component. + let top = r.resp.as_ref().is_some_and(|resp| pointer_in_top(ui, resp.rect)); + if let Some(resp) = &r.resp + && top + && let Some(d) = occurrence_reorder_target(ui, resp, |d| occurrence_sibling(app, d, placement.occurrence).is_some()) + && let Some(parent) = occurrence_sibling(app, &d, placement.occurrence) + { + let dragged = d.path.last().copied().unwrap_or(0); + let mut order: Vec = app.session.doc.occurrences.iter().filter(|o| o.parent == parent && o.id != dragged).map(|o| o.id).collect(); + app.session.doc.sort_placements(parent, &mut order); + let at = order.iter().position(|o| *o == placement.occurrence).unwrap_or(order.len()); + order.insert(at, dragged); + acts.drop_from(d.source, DropAction::OccurrenceOrder { parent, order }); + } // A placement row dropped on this one moves into this row's component. if let Some(resp) = &r.resp - && let Some(d) = occurrence_drop_target(ui, resp, |d| occurrence_can_land(app, d, placement.component)) + && let Some(d) = occurrence_drop_target(ui, resp, |d| { + occurrence_can_land(app, d, placement.component) && !(top && occurrence_sibling(app, d, placement.occurrence).is_some()) + }) { let occurrence = d.path.last().copied().unwrap_or(0); - acts.drop = Some(DropAction::Reparent { occurrence, path: d.path.clone(), parent: placement.component, parent_path: Some(path.to_vec()) }); + acts.drop_from( + d.source, + DropAction::Reparent { occurrence, path: d.path.clone(), parent: placement.component, parent_path: Some(path.to_vec()) }, + ); } if !open { return; @@ -1677,6 +1956,8 @@ fn occurrence_rows_inner( } if !render { features::rows(app, ui, placement.component, path, depth + 1, acts); + // The joints that attach this placement, as the root's Joints folder lists them (#9130). + crate::dialogs_assembly::component_joints(app, ui, path, key, depth + 1); } if path.len() < 64 { for child in &placement.children { @@ -1778,7 +2059,7 @@ fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut A app.set_origin_shown(!app.origin_shown()); } if let Some(p) = r.secondary { - crate::context_menu::open_for(app, p, Target::Origin); + acts.menu = Some((p, Target::Origin)); } if !open { return; @@ -1790,7 +2071,7 @@ fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut A 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 }), + _ => Some(Sel::Vertex { body: String::new(), point: solidcore_record::Vec3::ZERO }), }; let (selected, mark) = lit_row(lit(&thing)); let r = draw_row( @@ -1821,7 +2102,7 @@ fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut A _ => None, }; if let Some(target) = target { - crate::context_menu::open_for(app, p, target); + acts.menu = Some((p, target)); } } if r.hovered && icon == "plane" { @@ -2092,7 +2373,7 @@ pub fn canvas_items(app: &SolveApp, id: u64) -> Vec { Item::action("canvas.to_sketch", "Canvas to Sketch", "canvas").with(json!({ "canvas": id })), Item::sep(), Item::action("ui.delete", "Delete", "delete").with(json!({ "canvases": [id] })), - Item::action("ui.rename", "Rename", "rename").with(json!({ "canvas": id })), + Item::action("ui.rename", "Rename", "rename").key("F2").with(json!({ "canvas": id })), Item::sep(), Item::action("ui.canvasVisible", "Show/Hide", "eye").key("V").with(json!({ "canvas": id, "visible": !visible })), ] @@ -2136,6 +2417,16 @@ fn dialog_takes_body(app: &SolveApp) -> bool { app.dialog.as_ref().and_then(|d| d.active_input()).is_some_and(|i| i.accept & crate::selection::BODIES != 0) } +/// A plain click on a sketch (a Browser row or a History item) while Extrude, Revolve or Emboss +/// is open gives the dialog every profile of that sketch (#6106). False when it is not one: the +/// click then selects as usual. +pub(crate) fn pick_sketch_into_dialog(app: &mut SolveApp, id: u64) -> bool { + let Some(mut d) = app.dialog.take() else { return false }; + let taken = d.pick_sketch(&app.session, id); + app.dialog = Some(d); + taken +} + /// Browser picks go only into compatible active dialog inputs. Outside a dialog, planes and /// axes become the selection; body rows use the ordinary Ctrl/Shift-aware selection path. fn pick_from_browser(app: &mut SolveApp, x: Sel) { @@ -2155,7 +2446,7 @@ fn pick_from_browser(app: &mut SolveApp, x: Sel) { return; } let hit = match &x { - Sel::Plane { name } => crate::viewport::Hit::Plane { name: name.clone(), point: solidcraft_engine::geom::Vec3::ZERO }, + Sel::Plane { name } => crate::viewport::Hit::Plane { name: name.clone(), point: solidcore_record::Vec3::ZERO }, Sel::Axis { name } => crate::viewport::Hit::Axis { name: name.clone() }, Sel::ConstructionPoint { name } => crate::viewport::Hit::ConstructionPoint { name: name.clone() }, // The origin point goes only into a dialog input that takes it. @@ -2213,12 +2504,13 @@ impl Entry { key: b.name.clone(), row_key: format!("b:{world}"), patterns: None, - label: b.name.clone(), + // A part the modelling kernel refuses says so (Repair Part is in its menu). + label: if b.body.smlib_refused().is_some() { crate::i18n::format("browser.needs_repair", &[("name", &b.name)]) } else { b.name.clone() }, icon, tip: Some(tip), - visible: !app.session.visibility.hidden_bodies.contains(&world), + visible: app.body_visible(&world), selected: app.session.selection.iter().any(|s| matches!(s, Sel::Body { name } if name == &world)), - color: None, + color: b.body.smlib_refused().map(|_| Tokens::get().warning), sketch_state: None, locked: app.session.visibility.locked_bodies.contains(&world), sel: Some(Sel::Body { name: world.clone() }), @@ -2303,14 +2595,25 @@ impl Entry { /// What is being dragged in the tree: items of one component folder. #[derive(Clone, Debug)] struct Drag { + source: crate::semantic_content::ContentSource, comp: u64, folder: &'static str, keys: Vec, + /// Groups dragged by their rows (alone: a drag carries items or groups). + groups: Vec, +} + +impl Drag { + /// What is dragged, as the browser commands name it. + fn entries(&self) -> Vec { + self.keys.iter().map(|k| BrowserEntry::item(k)).chain(self.groups.iter().map(|g| BrowserEntry::Group(*g))).collect() + } } /// A placement row dragged in the tree: the exact path it sits at, and the component it places. #[derive(Clone, Debug)] struct OccurrenceDrag { + source: crate::semantic_content::ContentSource, /// The placement's path from the design root (its own occurrence id last). path: Vec, /// The component the placement is an instance of. @@ -2342,34 +2645,56 @@ fn construction_sel(f: &solidcraft_engine::doc::Feature) -> Sel { } } -/// A folder's groups (with their items) and the items in no group, in browser order. -fn arrange<'a>( - doc: &'a solidcraft_engine::doc::Document, - comp: u64, - folder: &str, - all: Vec, -) -> (Vec<(&'a solidcraft_engine::doc::BrowserGroup, Vec)>, Vec) { - let mut rest: Vec> = all.into_iter().map(Some).collect(); - let mut take = |key: &str| rest.iter_mut().find(|e| e.as_ref().is_some_and(|e| e.key == key)).and_then(Option::take); - let grouped: Vec<_> = doc - .browser_groups - .iter() - .filter(|g| g.component == comp && g.folder == folder) - .map(|g| { - let items = g.items.iter().filter_map(|k| take(k)).collect(); - (g, items) - }) - .collect(); - let mut loose: Vec = rest.into_iter().flatten().collect(); - if let Some(order) = doc.browser_order.get(&format!("{comp}/{folder}")) { - let mut positions = std::collections::HashMap::with_capacity(order.len()); - for (i, key) in order.iter().enumerate() { - positions.entry(key.as_str()).or_insert(i); - } - let pos = |k: &str| positions.get(k).copied().unwrap_or(usize::MAX); - loose.sort_by_key(|e| pos(&e.key)); +/// A folder's rows in browser order (see `Document::ordered_entries`), then the items in no list +/// in their natural order. A group's rows are ordered the same way by its own list. `prefix` is +/// the scope the groups' tree keys start with. +fn arrange(doc: &solidcraft_engine::doc::Document, comp: u64, folder: &str, prefix: &str, all: Vec) -> Vec { + use cache::Row; + use solidcraft_engine::doc::BrowserEntry; + let mut index: std::collections::HashMap = std::collections::HashMap::with_capacity(all.len()); + for (i, e) in all.iter().enumerate() { + index.entry(e.key.clone()).or_insert(i); } - (grouped, loose) + let mut pool: Vec> = all.into_iter().map(Some).collect(); + let mut take = |key: &str| index.get(key).and_then(|i| pool[*i].take()).map(|e| Row::Item(Box::new(e))); + fn build( + doc: &solidcraft_engine::doc::Document, + comp: u64, + folder: &str, + prefix: &str, + id: u64, + left: usize, + take: &mut dyn FnMut(&str) -> Option, + ) -> Option { + let g = doc.browser_group(id)?; + let mut rows = Vec::new(); + for e in doc.ordered_entries(comp, folder, Some(id)) { + match e { + BrowserEntry::Item(k) => rows.extend(take(&k)), + BrowserEntry::Group(c) if left > 0 => rows.extend(build(doc, comp, folder, prefix, c, left - 1, take).map(Row::Group)), + BrowserEntry::Group(_) => {} + } + } + let count = rows.iter().map(Row::count).sum(); + Some(cache::Group { id, key: format!("{prefix}/g{id}"), label: format!("{} ({count})", g.name), count, rows }) + } + let order = doc.ordered_entries(comp, folder, None); + // Groups first, so an item in a group is never also listed loose. + let mut groups: std::collections::HashMap = std::collections::HashMap::new(); + for e in &order { + if let BrowserEntry::Group(id) = e { + groups.extend(build(doc, comp, folder, prefix, *id, solidcraft_engine::doc::MAX_GROUP_NESTING, &mut take).map(|g| (*id, g))); + } + } + let mut rows = Vec::new(); + for e in order { + match e { + BrowserEntry::Group(id) => rows.extend(groups.remove(&id).map(Row::Group)), + BrowserEntry::Item(k) => rows.extend(take(&k)), + } + } + rows.extend(pool.into_iter().flatten().map(|e| Row::Item(Box::new(e)))); + rows } /// Show or hide items of a folder, through `browser.visibility` so each is an undo step (#2219). @@ -2444,20 +2769,18 @@ fn folder_rows_at( let fstatic = folder_static(folder); let key = &data.key; let prefix = key.rsplit_once('/').map_or(key.as_str(), |(prefix, _)| prefix); - if let Some(r) = app.tree.reveal.as_deref() + if let Some(r) = body_reveal(app) && folder == "bodies" && let Some(e) = data.entries().find(|e| e.row_key.strip_prefix("b:") == Some(r)) { app.tree.collapsed.remove(key); app.tree.collapsed.remove(&format!("c{comp}")); - for g in app.session.doc.browser_groups.iter().filter(|g| g.items.contains(&e.key)) { - app.tree.collapsed.remove(&format!("g{}", g.id)); - } + open_group_chain(app, "", comp, "bodies", &e.key); } // A folded folder draws no row: its groups and items move up into its place, and their own // eyes, hover and drops do its jobs. It is always open, as nothing could open it again. let render = crate::render_workspace::active(app); - let folded = !render && folder == "bodies" && bodies_folded(app, comp, prefix, data.entries().count()); + let folded = !render && folder == "bodies" && bodies_folded(app, comp, prefix, data.count); // With the history in the browser the sketches are there too: their folder starts closed. let default_open = !(folder == "sketches" && app.preferences.history_in_browser); let open = folded || is_open(app, key, default_open); @@ -2481,7 +2804,7 @@ fn folder_rows_at( icon: "folder", label: folder_label(folder), dim: folder_faded, - mark: acts.lit.branch(app, data.entries()), + mark: if acts.lit.any() { acts.lit.branch(app, data.entries()) } else { Mark::None }, ..Default::default() }, ) @@ -2510,40 +2833,82 @@ fn folder_rows_at( // from another component's folder move into this component, as a drop on its row does // (#3270: the Bodies folder looked like the place to drop a body, and took nothing). if let Some(resp) = &r.resp - && let Some(d) = drop_target(ui, resp, |d: &Drag| d.folder == fstatic && (d.comp == comp || d.folder != "construction"), DropMark::Box) + && let Some(d) = drop_target( + ui, + resp, + |d: &Drag| d.folder == fstatic && (d.comp == comp || (d.folder != "construction" && d.groups.is_empty())), + DropMark::Box, + ) { - acts.drop = Some(if d.comp == comp { - DropAction::Move { comp, folder: fstatic, keys: d.keys.clone(), group: None, before: None } - } else { - DropAction::Component { to: comp, folder: d.folder, keys: d.keys.clone() } - }); + acts.drop_from( + d.source, + if d.comp == comp { + DropAction::Order { + comp, + folder: fstatic, + keys: d.keys.clone(), + groups: d.groups.clone(), + order: order_before(&data.top_order, &d.entries(), None), + } + } else { + DropAction::Component { to: comp, folder: d.folder, keys: d.keys.clone() } + }, + ); } if !open { return; } } - let loose_keys = &data.loose_keys; - if render { - for e in &data.loose { - entry_row(app, ui, comp, path, fstatic, e, depth + 1, None, loose_keys, folder_faded, acts); - } - } - for group in &data.groups { - let (id, items, gkey) = (group.id, &group.items, &group.key); + folder_level(app, ui, comp, path, fstatic, prefix, &data.rows, None, inner, &data.top_order, folder_faded, acts); +} + +/// The rows of a folder's top level, or of one group (`holder`), at `depth`; groups draw their +/// own rows the same way one level deeper. `top` is the folder's top-level order as drawn. +#[allow(clippy::too_many_arguments)] +fn folder_level( + app: &mut SolveApp, + ui: &mut egui::Ui, + comp: u64, + path: Option<&[u64]>, + fstatic: &'static str, + prefix: &str, + rows: &[cache::Row], + holder: Option, + depth: usize, + top: &[BrowserEntry], + faded: bool, + acts: &mut Actions, +) { + let render = crate::render_workspace::active(app); + // The render workspace has always listed a folder's loose items above its groups. + let items_first = render && holder.is_none(); + let rows = rows + .iter() + .filter(|r| items_first && matches!(r, cache::Row::Item(_))) + .chain(rows.iter().filter(|r| !items_first || matches!(r, cache::Row::Group(_)))); + for row in rows { + let group = match row { + cache::Row::Item(e) => { + entry_row(app, ui, comp, path, fstatic, e, depth, holder, top, faded, acts); + continue; + } + cache::Row::Group(g) => g, + }; + let (id, gkey) = (group.id, &group.key); let gopen = is_open(app, gkey, true); let gshown = !app.session.folder_hidden(gkey); - let group_faded = folder_faded || !gshown; + let group_faded = faded || !gshown; let label = if render { app.session.doc.browser_groups.iter().find(|g| g.id == id).map_or(group.label.as_str(), |g| g.name.as_str()) } else { &group.label }; - let count = if render && !gopen { crate::i18n::format("render.tree_more", &[("count", &items.len().to_string())]) } else { String::new() }; + let count = if render && !gopen { crate::i18n::format("render.tree_more", &[("count", &group.count.to_string())]) } else { String::new() }; let r = draw_row( ui, ui.id().with(gkey), &Row { - depth: inner, + depth, fold: Some(gopen), eye: (!render || gopen).then_some(gshown), icon: if render { "" } else { "folder" }, @@ -2551,14 +2916,14 @@ fn folder_rows_at( name: true, dim: group_faded || (render && !gopen), count: &count, - mark: acts.lit.branch(app, items), + mark: if acts.lit.any() { acts.lit.branch(app, group.entries()) } else { Mark::None }, ..Default::default() }, ); if r.fold { toggle(app, gkey, true); } else if r.clicked { - let names: Vec = items.iter().flat_map(|e| e.bodies.clone()).collect(); + let names: Vec = group.entries().into_iter().flat_map(|e| e.bodies.clone()).collect(); if !offer_bodies(app, &names, Take::Toggle) { pick_folder(app, gkey); toggle(app, gkey, true); @@ -2568,40 +2933,79 @@ fn folder_rows_at( toggle_folder(app, gkey); } if r.hovered { - acts.hover(items.iter().flat_map(|e| &e.bodies)); + acts.hover(group.entries().into_iter().flat_map(|e| &e.bodies)); } if let Some(p) = r.secondary { acts.menu = Some((p, Target::Group { id, scope: prefix.to_owned() })); } - if let Some(resp) = &r.resp - && let Some(d) = drop_target(ui, resp, |d: &Drag| d.comp == comp && d.folder == fstatic, DropMark::Box) - { - acts.drop = Some(DropAction::Move { comp, folder: fstatic, keys: d.keys.clone(), group: Some(id), before: None }); - } - if gopen { - for e in items { - entry_row(app, ui, comp, path, fstatic, e, inner + 1, Some(id), loose_keys, group_faded, acts); + if let Some(resp) = &r.resp { + // Dragging a group row moves the group; a press on its arrow or eye is not a drag. + if resp.drag_started() + && !r.on_control + && let Some(source) = crate::semantic_content::current_source(app) + { + resp.dnd_set_drag_payload(Drag { source, comp, folder: fstatic, keys: Vec::new(), groups: vec![id] }); + } + // The top of the row puts the drop before the group; the rest puts it inside. + let level = app.session.doc.group_level(id); + let fits = |d: &Drag, parent_level: usize| { + let doc = &app.session.doc; + d.groups.iter().all(|g| !doc.group_within(id, *g) && parent_level + doc.group_height(*g) <= solidcraft_engine::doc::MAX_GROUP_NESTING) + }; + if let Some((d, zone)) = drop_target_zone(ui, resp, |d: &Drag, zone| { + d.comp == comp && d.folder == fstatic && fits(d, if zone == DropMark::Above { level - 1 } else { level }) + }) { + let before = BrowserEntry::Group(id); + acts.drop_from( + d.source, + match (zone, holder) { + (DropMark::Box, _) => { + DropAction::Move { comp, folder: fstatic, keys: d.keys.clone(), groups: d.groups.clone(), group: Some(id), before: None } + } + (DropMark::Above, Some(h)) => DropAction::Move { + comp, + folder: fstatic, + keys: d.keys.clone(), + groups: d.groups.clone(), + group: Some(h), + before: Some(before), + }, + (DropMark::Above, None) => DropAction::Order { + comp, + folder: fstatic, + order: order_before(top, &d.entries(), Some(&before)), + keys: d.keys.clone(), + groups: d.groups.clone(), + }, + }, + ); } } - } - if !render { - for e in &data.loose { - entry_row(app, ui, comp, path, fstatic, e, inner, None, loose_keys, folder_faded, acts); + if gopen { + folder_level(app, ui, comp, path, fstatic, prefix, &group.rows, Some(id), depth + 1, top, group_faded, acts); } } } +/// `top` with the dragged entries moved to just before `before` (to the end without it). +fn order_before(top: &[BrowserEntry], dragged: &[BrowserEntry], before: Option<&BrowserEntry>) -> Vec { + let mut order: Vec = top.iter().filter(|e| !dragged.contains(e)).cloned().collect(); + let at = before.and_then(|b| order.iter().position(|e| e == b)).unwrap_or(order.len()); + for (i, e) in dragged.iter().enumerate() { + order.insert(at + i, e.clone()); + } + order +} + /// The body's name edited in its row (started by a double-click): Enter or leaving the box keeps /// the name, Escape cancels. -fn inline_rename(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect, e: &Entry, depth: usize) { +fn inline_rename(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect, label_left: f32, e: &Entry) { let editing = app.menu.rename.as_ref().is_some_and(|r| r.inline && matches!(&r.what, crate::context_menu::RenameWhat::Body(b) if *b == e.key)); if !editing { return; } let Some(mut rename) = app.menu.rename.take() else { return }; - // Where the label starts: the fold arrow, eye and icon come first. - let left = row.left() + 2.0 + depth as f32 * INDENT + 14.0 + 18.0 + 21.0; - let edit_rect = Rect::from_min_max(pos2(left, row.top() + 1.0), pos2(row.right() - 3.0, row.bottom() - 1.0)); + let edit_rect = Rect::from_min_max(pos2(label_left, row.top() + 1.0), pos2(row.right() - 3.0, row.bottom() - 1.0)); ui.painter().rect_filled(edit_rect, 3.0, Tokens::get().field); let id = ui.id().with(("browser_rename", &e.row_key)); let response = crate::ui_kit::inline_name(ui, edit_rect, id, &mut rename.text); @@ -2621,7 +3025,9 @@ fn inline_rename(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect, e: &Entry, de if escape { // Dropping the state cancels the edit. } else if commit { - crate::context_menu::commit_rename(app, &rename); + if crate::context_menu::commit_rename(app, &rename).is_err() { + app.menu.rename = Some(rename); + } } else { app.menu.rename = Some(rename); } @@ -2638,7 +3044,7 @@ fn entry_row( e: &Entry, depth: usize, group: Option, - loose: &[String], + top: &[BrowserEntry], // A placement or folder above is hidden: the row fades, its eye stays its own. parent_hidden: bool, acts: &mut Actions, @@ -2651,7 +3057,7 @@ fn entry_row( let pattern_key = e.patterns.as_deref(); let patterns_open = pattern_key.is_some_and(|key| is_open(app, key, true)); let rect = row_rect(ui); - let revealed = folder == "bodies" && app.tree.reveal.as_ref().is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b.as_str())); + let revealed = folder == "bodies" && body_reveal(app).is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b)); if !ui.is_rect_visible(rect) && !patterns_open && !revealed { ui.allocate_space(rect.size()); return; @@ -2682,7 +3088,7 @@ fn entry_row( label: &e.label, name: true, selected, - dim: !e.visible || parent_hidden, + dim: !visible || parent_hidden, cut, color: e.color, swatch: appearance.swatch, @@ -2695,16 +3101,24 @@ fn entry_row( ..Default::default() }, ); + // A part that needs repair, under the pointer: its refused face is ringed in the view. + if r.hovered + && folder == "bodies" + && let Some(Sel::Body { name }) = &e.sel + && let Some(face) = app.session.model.state().body(&e.key).and_then(|b| b.body.smlib_refused()).and_then(|r| r.face) + { + crate::refused_part::ring(app, name, face); + } if r.fold && let Some(key) = pattern_key { toggle(app, key, true); } if folder == "bodies" - && app.tree.reveal.as_ref().is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b.as_str())) + && body_reveal(app).is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b)) && let Some(rect) = r.rect + && crate::semantic_content::scroll_acknowledged(ui, rect) { - ui.scroll_to_rect(rect, Some(egui::Align::Center)); app.tree.reveal = None; } if r.eye { @@ -2721,10 +3135,16 @@ fn entry_row( if folder == "construction" || (folder == "bodies" && !shift && app.dialog.is_some()) { if let Some(s) = e.sel.clone() { if matches!(s, Sel::Body { .. }) { - app.tree.anchor = Some(e.row_key.clone()); + app.tree.content.current_mut().anchor = Some(e.row_key.clone()); } pick_from_browser(app, s); } + } else if folder == "sketches" + && !ui.input(|i| i.modifiers.any()) + && let Some(Sel::Feature { id }) = e.sel + && pick_sketch_into_dialog(app, id) + { + // Extrude, Revolve or Emboss took all the sketch's profiles (#6106). } else { click_select(app, ui, e.row_key.clone(), e.sel.clone()); } @@ -2741,9 +3161,9 @@ fn entry_row( } } if folder == "bodies" - && let Some(rect) = r.rect + && let (Some(rect), Some(label_left)) = (r.rect, r.label_left) { - inline_rename(app, ui, rect, e, depth); + inline_rename(app, ui, rect, label_left, e); } if r.hovered && !e.bodies.is_empty() { acts.hover(e.bodies.iter()); @@ -2766,22 +3186,35 @@ fn entry_row( } let Some(resp) = &r.resp else { return }; // Drag: the selected items of this folder when this one is selected, else just this one. - if resp.drag_started() && !r.on_control { + if resp.drag_started() + && !r.on_control + && let Some(source) = crate::semantic_content::current_source(app) + { let keys: Vec = if selected { selected_keys(app, comp, folder) } else { vec![e.key.clone()] }; - resp.dnd_set_drag_payload(Drag { comp, folder, keys }); + resp.dnd_set_drag_payload(Drag { source, comp, folder, keys, groups: Vec::new() }); } - if let Some(d) = drop_target(ui, resp, |d: &Drag| d.comp == comp && d.folder == folder && !d.keys.contains(&e.key), DropMark::Above) { - acts.drop = Some(match group { - Some(g) => DropAction::Move { comp, folder, keys: d.keys.clone(), group: Some(g), before: Some(e.key.clone()) }, - None => { - let mut order: Vec = loose.iter().filter(|k| !d.keys.contains(k)).cloned().collect(); - let at = order.iter().position(|k| *k == e.key).unwrap_or(order.len()); - for (i, k) in d.keys.iter().enumerate() { - order.insert(at + i, k.clone()); - } - DropAction::Order { comp, folder, keys: d.keys.clone(), order } - } - }); + let fits = |d: &Drag| { + let doc = &app.session.doc; + let level = group.map_or(0, |g| doc.group_level(g)); + d.groups + .iter() + .all(|g| group.is_none_or(|h| !doc.group_within(h, *g)) && level + doc.group_height(*g) <= solidcraft_engine::doc::MAX_GROUP_NESTING) + }; + if let Some(d) = drop_target(ui, resp, |d: &Drag| d.comp == comp && d.folder == folder && !d.keys.contains(&e.key) && fits(d), DropMark::Above) { + let before = BrowserEntry::item(&e.key); + acts.drop_from( + d.source, + match group { + Some(g) => DropAction::Move { comp, folder, keys: d.keys.clone(), groups: d.groups.clone(), group: Some(g), before: Some(before) }, + None => DropAction::Order { + comp, + folder, + order: order_before(top, &d.entries(), Some(&before)), + keys: d.keys.clone(), + groups: d.groups.clone(), + }, + }, + ); } } @@ -2800,6 +3233,7 @@ enum DropMark { /// While a matching payload hovers the row, mark where it would land; on release, the payload. fn drop_target(ui: &egui::Ui, resp: &egui::Response, accept: impl Fn(&Drag) -> bool, mark: DropMark) -> Option> { + let accept = |drag: &Drag| crate::semantic_content::same_document(ui, drag.source) && accept(drag); let t = Tokens::get(); let hovering = resp.dnd_hover_payload::().filter(|d| accept(d)); if hovering.is_some() { @@ -2818,6 +3252,27 @@ fn drop_target(ui: &egui::Ui, resp: &egui::Response, accept: impl Fn(&Drag) -> b resp.dnd_release_payload::().filter(|d| accept(d)) } +/// Like [`drop_target`] for a row that takes a drop above it (its top part) or inside it. +fn drop_target_zone(ui: &egui::Ui, resp: &egui::Response, accept: impl Fn(&Drag, DropMark) -> bool) -> Option<(std::sync::Arc, DropMark)> { + let accept = |drag: &Drag, zone| crate::semantic_content::same_document(ui, drag.source) && accept(drag, zone); + let t = Tokens::get(); + let r = resp.rect; + let at = ui.input(|i| i.pointer.hover_pos().or(i.pointer.latest_pos())); + let zone = if at.is_some_and(|p| p.y < r.top() + r.height() * 0.3) { DropMark::Above } else { DropMark::Box }; + if resp.dnd_hover_payload::().is_some_and(|d| accept(&d, zone)) { + match zone { + DropMark::Above => ui.painter().hline(r.x_range(), r.top(), Stroke::new(2.0, t.accent)), + DropMark::Box => { + ui.painter().rect_stroke(r.shrink(0.5), t.radius_sm.saturating_sub(1), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside) + } + }; + } + if !egui::DragAndDrop::has_payload_of_type::(ui.ctx()) { + return None; + } + resp.dnd_release_payload::().filter(|d| accept(d, zone)).map(|d| (d, zone)) +} + /// Whether a placement dragged from `d` may land in component `parent`: not where it already is, /// and not in itself or a component it holds. The command refuses those too; this keeps the row /// from showing a drop mark it would refuse. @@ -2832,8 +3287,39 @@ fn occurrence_can_land(app: &SolveApp, d: &OccurrenceDrag, parent: u64) -> bool o.parent != parent && !app.session.doc.inside_component(parent, d.component) } +/// Whether the pointer is over the top part of a row (where a drop goes before it). +fn pointer_in_top(ui: &egui::Ui, row: Rect) -> bool { + ui.input(|i| i.pointer.hover_pos().or(i.pointer.latest_pos())).is_some_and(|p| p.y < row.top() + row.height() * 0.3) +} + +/// The component a placement shares with the placement under it, when both sit in the same one +/// (and are two placements): the parent whose sub-components they are ordered among. +fn occurrence_sibling(app: &SolveApp, d: &OccurrenceDrag, target: u64) -> Option { + let dragged = d.path.last().copied().filter(|o| *o != target)?; + let occurrences = &app.session.doc.occurrences; + let parent = occurrences.iter().find(|o| o.id == dragged)?.parent; + occurrences.iter().any(|o| o.id == target && o.parent == parent).then_some(parent) +} + +/// While a matching placement drag hovers the row, mark a drop before it; on release, the payload. +fn occurrence_reorder_target( + ui: &egui::Ui, + resp: &egui::Response, + accept: impl Fn(&OccurrenceDrag) -> bool, +) -> Option> { + let accept = |drag: &OccurrenceDrag| crate::semantic_content::same_document(ui, drag.source) && accept(drag); + if resp.dnd_hover_payload::().is_some_and(|d| accept(&d)) { + ui.painter().hline(resp.rect.x_range(), resp.rect.top(), Stroke::new(2.0, Tokens::get().accent)); + } + if !egui::DragAndDrop::has_payload_of_type::(ui.ctx()) { + return None; + } + resp.dnd_release_payload::().filter(|d| accept(d)) +} + /// While a matching placement drag hovers the row, mark where it would land; on release, the payload. fn occurrence_drop_target(ui: &egui::Ui, resp: &egui::Response, accept: impl Fn(&OccurrenceDrag) -> bool) -> Option> { + let accept = |drag: &OccurrenceDrag| crate::semantic_content::same_document(ui, drag.source) && accept(drag); let t = Tokens::get(); let hovering = resp.dnd_hover_payload::().filter(|d| accept(d)); if hovering.is_some() { @@ -2849,23 +3335,68 @@ fn occurrence_drop_target(ui: &egui::Ui, resp: &egui::Response, accept: impl Fn( /// A drop, applied after the tree is drawn. enum DropAction { + OccurrenceOrder { + parent: u64, + order: Vec, + }, /// Into a group (before an item of it), or out of groups. - Move { comp: u64, folder: &'static str, keys: Vec, group: Option, before: Option }, - /// Out of groups, in this order of the folder's loose items. - Order { comp: u64, folder: &'static str, keys: Vec, order: Vec }, + Move { + comp: u64, + folder: &'static str, + keys: Vec, + groups: Vec, + group: Option, + before: Option, + }, + /// Out of groups, in this order of the folder's top level. + Order { + comp: u64, + folder: &'static str, + keys: Vec, + groups: Vec, + order: Vec, + }, /// Into another component (bodies and sketches). - Component { to: u64, folder: &'static str, keys: Vec }, + Component { + to: u64, + folder: &'static str, + keys: Vec, + }, /// A placement moved into another component (or the design, `parent` 0). - Reparent { occurrence: u64, path: Vec, parent: u64, parent_path: Option> }, + Reparent { + occurrence: u64, + path: Vec, + parent: u64, + parent_path: Option>, + }, +} + +fn entry_json(e: &BrowserEntry) -> Value { + match e { + BrowserEntry::Group(id) => json!(id), + BrowserEntry::Item(k) => json!(k), + } +} + +/// Items (strings) and groups (numbers), as the browser commands take them. +fn entries_json(keys: &[String], groups: &[u64]) -> Vec { + keys.iter().map(|k| json!(k)).chain(groups.iter().map(|g| json!(g))).collect() } fn apply_drop(app: &mut SolveApp, d: DropAction) { match d { - DropAction::Move { comp, folder, keys, group, before } => { - let _ = app.run("browser.move", json!({ "component": comp, "folder": folder, "items": keys, "group": group, "before": before })); + DropAction::OccurrenceOrder { parent, order } => { + let order: Vec = order.iter().map(u64::to_string).collect(); + let _ = app.run("browser.order", json!({ "folder": "components", "component": parent, "order": order })); } - DropAction::Order { comp, folder, keys, order } => { - let _ = app.run("browser.move", json!({ "component": comp, "folder": folder, "items": keys })); + DropAction::Move { comp, folder, keys, groups, group, before } => { + let items = entries_json(&keys, &groups); + let before = before.map(|b| entry_json(&b)); + let _ = app.run("browser.move", json!({ "component": comp, "folder": folder, "items": items, "group": group, "before": before })); + } + DropAction::Order { comp, folder, keys, groups, order } => { + let _ = app.run("browser.move", json!({ "component": comp, "folder": folder, "items": entries_json(&keys, &groups) })); + let order: Vec = order.iter().map(entry_json).collect(); let _ = app.run("browser.order", json!({ "component": comp, "folder": folder, "order": order })); } DropAction::Component { to, folder, keys } => { @@ -2912,7 +3443,7 @@ pub(crate) fn revert_occurrence_dialog(app: &mut SolveApp, m: &OccMove) { /// The pending move: turned about X, then Y, then Z through the starting origin, then moved. pub fn apply_occurrence_move(app: &mut SolveApp, m: &OccMove) { use crate::gizmo; - use solidcraft_engine::geom::Vec3; + use solidcore_record::Vec3; let a = m.angles.map(f64::to_radians); let r = gizmo::mul(&gizmo::mul(&gizmo::rotation(Vec3::Z, a[2]), &gizmo::rotation(Vec3::Y, a[1])), &gizmo::rotation(Vec3::X, a[0])); let (axis, angle) = gizmo::axis_angle(&r); @@ -2931,7 +3462,7 @@ pub fn apply_occurrence_move(app: &mut SolveApp, m: &OccMove) { /// The shared move triad at the occurrence's origin: arrows and squares move it, rings turn it. pub(crate) fn occurrence_triad_model(app: &SolveApp) -> Option { let movement = app.tree.occurrence_move.as_ref()?; - let center = movement.pivot? + solidcraft_engine::geom::Vec3::new(movement.translate[0], movement.translate[1], movement.translate[2]); + let center = movement.pivot? + solidcore_record::Vec3::new(movement.translate[0], movement.translate[1], movement.translate[2]); Some(crate::gizmo::Triad { center, translate: true, rotate: true }) } @@ -2968,7 +3499,7 @@ pub(crate) fn occurrence_triad(app: &mut SolveApp, ui: &mut egui::Ui, painter: & /// viewport like the sketch being edited draws its own (`crate::dim_view`). A double-click on a /// value edits it in place without editing the sketch (`crate::dim_view::model_double_click`). pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { - use solidcraft_engine::geom::Vec2; + use solidcore_record::Vec2; use solidcraft_engine::sketch::{DimFrame, chain_centres, default_text, dim_frame, dim_layout_reaching, dim_reach}; crate::dim_view::set_model_drawn(Vec::new()); let Some(rect) = app.viewport.rect else { return }; @@ -2979,7 +3510,7 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { let tk = Tokens::get(); let proj = crate::viewport::projection(app, rect); let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect); - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); for id in app .session .visibility @@ -3089,11 +3620,11 @@ pub fn answer_capture(app: &mut SolveApp, action: &str) -> Result<(), String> { } /// Where an occurrence's origin is now (with its pending move). -pub(crate) fn occurrence_origin(app: &SolveApp, occurrence: u64) -> Option { +pub(crate) fn occurrence_origin(app: &SolveApp, occurrence: u64) -> Option { let o = app.session.doc.occurrences.iter().find(|o| o.id == occurrence)?; let parent = app.session.doc.component_transform(o.parent); let own = app.session.pending_moves.get(&occurrence).copied().unwrap_or(o.transform); - Some(solidcraft_engine::doc::apply_point(&solidcraft_engine::doc::mat_mul(&parent, &own), solidcraft_engine::geom::Vec3::ZERO)) + Some(solidcraft_engine::doc::apply_point(&solidcraft_engine::doc::mat_mul(&parent, &own), solidcore_record::Vec3::ZERO)) } /// The names the Bodies folder lists at the top level, for tests. diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rs index 37c4f4690..4d1d9b434 100644 --- a/crates/ui-egui/src/browser/features.rs +++ b/crates/ui-egui/src/browser/features.rs @@ -2,24 +2,34 @@ use super::*; use crate::history_rows::{HistoryFeature, HistoryRows}; +use crate::semantic_content::FeatureDrag; #[derive(Clone, Debug)] pub(crate) struct Reveal { pub id: u64, pub path: Vec, + /// Native Features and combined History are distinct presentations of the same feature. + history: bool, +} + +#[cfg(test)] +thread_local! { + /// Folded Features folders whose mark was worked out (the tests count them). + static MARKS_WORKED_OUT: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Open the Features folder that lists this feature and scroll to its row, without changing the /// active component or history marker. The folder is the one of the placement `body` belongs to: /// without a body there is no telling which copy of a component was meant. pub(crate) fn reveal(app: &mut SolveApp, id: u64, body: &str) { + sync_reveals(app); let Some(feature) = app.session.doc.feature(id) else { return }; if matches!(feature.kind, FeatureKind::Sketch { .. }) { return; // Sketches are listed in Sketches, not Features. } let component = feature.component; let state = app.session.model.state(); - let world = app.session.world_state(); + let world = crate::open_meshing::session_world(&app.session); let Some(source) = world.body(body).map(|selected| selected.definition_name()) else { return }; let Some((_, path, _)) = app .session @@ -35,35 +45,57 @@ pub(crate) fn reveal(app: &mut SolveApp, id: u64, body: &str) { app.tree.reveal = None; app.tree.collapsed.remove("c0"); for depth in 1..=path.len() { - app.tree.collapsed.remove(&occurrence_key(&path[..depth])); + app.tree.open_row(&occurrence_key(&path[..depth])); } let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(&path) }; - app.tree.collapsed.remove(&scope); + app.tree.open_row(&scope); app.tree.expanded.insert(format!("{scope}/features")); - app.tree.reveal_feature = Some(Reveal { id, path }); + app.tree.reveal_feature = Some(Reveal { id, path, history: false }); } /// With the history in the browser: open the feature's component and history, and scroll to it. pub(crate) fn reveal_in_history(app: &mut SolveApp, id: u64) { + sync_reveals(app); let Some(component) = app.session.doc.feature(id).map(|feature| feature.component) else { return }; + let path = if component == 0 { + Vec::new() + } else { + app.session + .active_occurrence_path + .clone() + .filter(|_| app.session.active_component == component) + .unwrap_or_else(|| app.session.doc.first_path(component)) + }; app.ui.show_browser = true; app.tree.collapsed.remove("c0"); - app.tree.collapsed.remove(&format!("c{component}")); - app.tree.collapsed.remove(&format!("c{component}/history")); - app.tree.reveal_feature = Some(Reveal { id, path: Vec::new() }); + for depth in 1..=path.len() { + app.tree.open_row(&occurrence_key(&path[..depth])); + } + let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(&path) }; + app.tree.open_row(&scope); + app.tree.collapsed.remove(&format!("{scope}/history")); + app.tree.reveal_feature = Some(Reveal { id, path, history: true }); +} + +/// Feature folders hide later rows only while editing; history always lists every feature. +fn shown_features(app: &SolveApp, compact: bool) -> usize { + let n = app.session.doc.features.len(); + if !compact && app.dialog.as_ref().is_some_and(|d| d.editing.is_some()) { app.session.doc.marker.unwrap_or(n) } else { n } } pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path: &[u64], depth: usize, acts: &mut Actions) { // Compact history: every feature of the component, sketches too, in history order with the // marker, in place of the timeline. let compact = app.preferences.history_in_browser; + let shown = shown_features(app, compact); let has_features = match app.tree.model.as_ref().filter(|m| m.matches(&app.session) && !compact) { - Some(model) => model.features.get(&component).is_some_and(|features| !features.is_empty()), + Some(model) => model.features.get(&component).is_some_and(|features| features.iter().any(|&index| index < shown)), None => app .session .doc .features .iter() + .take(shown) .any(|feature| feature.component == component && (compact || !matches!(feature.kind, FeatureKind::Sketch { .. }))), }; if !has_features { @@ -74,10 +106,14 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path: let (key, label) = if compact { (format!("{scope}/history"), crate::i18n::tr("ui.history_title")) } else { (format!("{scope}/features"), "Features") }; let open = is_open(app, &key, compact); - // Folded, it carries the worst mark of what it holds. - let ids: Vec = if open { + // Folded, it carries the worst mark of what it holds. A row scrolled out of view paints + // nothing, so its mark is not worked out: in a long tree of placements of a part with a long + // history, every folder's mark scanned the design's whole history on every frame (#6083). + let ids: Vec = if open || !ui.is_rect_visible(row_rect(ui)) { Vec::new() } else { + #[cfg(test)] + MARKS_WORKED_OUT.with(|n| n.set(n.get() + 1)); app.session .doc .features @@ -102,6 +138,7 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path: .doc .features .iter() + .take(shown) .enumerate() .filter_map(|(i, f)| (f.component == component && (compact || !matches!(f.kind, FeatureKind::Sketch { .. }))).then_some(i)) .collect(), @@ -116,8 +153,8 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path: if id.is_some_and(|id| lit.contains(&id) || from_view.contains(&Some(id))) { Mark::Here } else { Mark::None } }; if !compact { - for index in indices { - let _ = feature_row(app, ui, acts, &here, index, depth + 1, None, mark(app, index)); + for index in indices.into_iter().take_while(|&index| index < shown) { + let _ = feature_row(app, ui, acts, &here, index, depth + 1, None, mark(app, index), None); } return; } @@ -129,32 +166,59 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path: // Where the marker can be dropped: the top of each row (it and the sketches listed under it // first rolled back) and below the last. let mut slots: Vec<(f32, usize)> = Vec::new(); + // Where dragged rows can be dropped, as in the History at the left: these slots and one + // before the marker, each with the folder the rows join (#9565). + let drag_id = ui.id().with(("sc_browser_history_drag", &scope)); + let mut dragged = app.tree.content.current_mut().feature_drags.get(&drag_id).cloned(); + let mut drops: Vec = Vec::new(); let mut marker_resp = None; for row in &plan.rows { let index = global(row.index); + let drop = DropSlot { + y: ui.cursor().min.y, + position: global(row.slot.min(row.index)), + group: crate::timeline_left::group_for(&app.session.doc.timeline_groups, row.feature), + }; if marker_resp.is_none() && index >= marker { + drops.push(drop); marker_resp = Some(marker_row(app, ui, depth + 1)); } slots.push((ui.cursor().min.y, global(row.slot))); + drops.push(DropSlot { y: ui.cursor().min.y, ..drop }); // The same fold as in the vertical History, so it stays open when the layout changes. let key = crate::timeline_left::sketches_key(row.feature); let open = is_open(app, &key, false); let listed: Vec = row.listed.iter().filter(|listed| !listed.reference).map(|listed| global(listed.index)).collect(); let fold = (!listed.is_empty()).then_some(open); - if feature_row(app, ui, acts, &here, index, depth + 1, fold, mark(app, index)) { + if feature_row(app, ui, acts, &here, index, depth + 1, fold, mark(app, index), Some(&mut dragged)) { toggle(app, &key, false); } if open { for index in listed { - let _ = feature_row(app, ui, acts, &here, index, depth + 2, None, mark(app, index)); + let _ = feature_row(app, ui, acts, &here, index, depth + 2, None, mark(app, index), Some(&mut dragged)); } } } + let end = global(indices.len()); + if marker_resp.is_none() { + drops.push(DropSlot { y: ui.cursor().min.y, position: end, group: None }); + } let resp = marker_resp.unwrap_or_else(|| marker_row(app, ui, depth + 1)); if !plan.rows.is_empty() { - slots.push((ui.cursor().min.y, global(indices.len()))); + slots.push((ui.cursor().min.y, end)); + drops.push(DropSlot { y: ui.cursor().min.y, position: end, group: None }); } drag_marker(app, ui, &resp, &slots, marker); + drag_rows(app, ui, &plan, drag_id, dragged, &drops, resp.rect.center().y); +} + +/// A place in the browser's History where dragged rows can land: its height, the timeline +/// position they move to and the folder they join (`None`: the timeline root). +#[derive(Clone, Copy)] +struct DropSlot { + y: f32, + position: usize, + group: Option, } /// Where a history row is drawn: its component and placement. @@ -205,6 +269,7 @@ fn feature_row( depth: usize, fold: Option, mark: Mark, + drag: Option<&mut Option>, ) -> bool { let Some(feature) = app.session.doc.features.get(index) else { return false }; let (component, path) = (here.component, here.path); @@ -213,7 +278,11 @@ fn feature_row( let sketch = crate::timeline::TimelineKind::of(&feature.kind).profile_sketch(); // Behind the history marker or suppressed: not built, drawn faint as in the timeline. let dim = feature.suppressed || app.session.doc.marker.is_some_and(|marker| index >= marker); - let selected = app.session.selection.contains(&Sel::Feature { id }); + // A feature picked by its geometry (a face or edge of it chosen in the view) shows as + // selected in the tree, as NX marks the feature of a picked face; the session's selection + // stays the face or edge. + let by_geometry = !app.session.selection.contains(&Sel::Feature { id }) && crate::timeline::picked_feature(app) == Some(id); + let selected = app.session.selection.contains(&Sel::Feature { id }) || by_geometry; app.tree.remember(&format!("f:{id}")); let action = sketch.map(|_| ("sketch", "Edit Profile Sketch")); // A sketch row has the eye its Sketches folder row has. A feature's eye shows and hides the @@ -264,10 +333,16 @@ fn feature_row( let scope = here.scope; if let Some(rect) = r.rect { crate::scenario::publish_handle(&format!("row:browser-feature:{scope}:{id}"), rect.center()); - if app.tree.reveal_feature.as_ref().is_some_and(|target| target.id == id && target.path == path) { - ui.scroll_to_rect(rect, Some(egui::Align::Center)); + let history = app.preferences.history_in_browser; + if app.tree.content.browser_presentation() + && app.tree.reveal_feature.as_ref().is_some_and(|target| target.id == id && target.path == path && target.history == history) + && crate::semantic_content::scroll_acknowledged(ui, rect) + { app.tree.reveal_feature = None; } + if history && app.tree.timeline_reveal == Some(id) && crate::semantic_content::scroll_acknowledged(ui, rect) { + app.tree.timeline_reveal = None; + } } if r.double { if !path.is_empty() { @@ -280,6 +355,14 @@ fn feature_row( if let Some(at) = r.secondary { acts.menu = Some((at, if is_sketch { Target::Sketch { id } } else { Target::Feature { id } })); } + // In the History: a drag of the row (not of its fold arrow or eye) moves the feature (#9565). + if let Some(drag) = drag + && !r.on_control + && r.resp.as_ref().is_some_and(egui::Response::drag_started) + && let Some(source) = crate::semantic_content::current_source(app) + { + *drag = Some(FeatureDrag { source, features: crate::timeline_left::drag_features(app, id, selected) }); + } r.fold } @@ -287,13 +370,14 @@ fn feature_row( fn marker_row(app: &SolveApp, ui: &mut egui::Ui, depth: usize) -> egui::Response { let t = Tokens::get(); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.space_12), Sense::drag()); + crate::semantic_content::record_capture(ui, &response); let line = Rect::from_min_max(pos2(rect.left() + 2.0 + depth as f32 * INDENT, rect.top()), rect.max); crate::ui_kit::history_marker(ui.painter(), line, true, crate::theme::TabAccent::for_tab(&t, &app.ui.tab)); crate::scenario::publish_handle("browser:rollback", rect.center()); if response.hovered() || response.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } - response.on_hover_text(crate::i18n::tr("ui.history_marker_tip")) + response.backing_on_hover_text(crate::i18n::tr("ui.history_marker_tip")) } /// Dragging the marker shows where it lands; letting go rolls the history there, through the @@ -308,12 +392,66 @@ fn drag_marker(app: &mut SolveApp, ui: &egui::Ui, resp: &egui::Response, slots: let accent = crate::theme::TabAccent::current(ui.ctx()).color; ui.painter().hline(resp.rect.left() + 4.0..=resp.rect.right() - 4.0, slot_y, Stroke::new(2.0, accent)); } - if resp.drag_stopped() && position != marker { + if resp.drag_stopped() + && position != marker + && crate::semantic_content::current_source(app).is_some_and(|source| crate::semantic_content::source_present(app, source)) + && crate::semantic_content::claim_action(ui, resp.id) + { let n = app.session.doc.features.len(); let _ = app.run_heavy("timeline.roll_to", if position >= n { json!({}) } else { json!({ "position": position }) }); } } +/// Dragging feature rows shows where they land with the History's drop bar; letting go moves them +/// with the History's own move, before or behind the marker by the side of it they land on. +fn drag_rows( + app: &mut SolveApp, + ui: &egui::Ui, + plan: &HistoryRows, + drag_id: egui::Id, + dragged: Option, + drops: &[DropSlot], + marker_y: f32, +) { + let Some(drag) = dragged else { return }; + if !crate::semantic_content::source_present(app, drag.source) { + app.tree.content.current_mut().feature_drags.remove(&drag_id); + return; + } + let (released, down) = ui.input(|i| (i.pointer.any_released(), i.pointer.any_down())); + if released || !down { + app.tree.content.current_mut().feature_drags.remove(&drag_id); + } + if !released && !down { + return; + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + // Only over the History's rows: let go anywhere else, nothing moves. + let reach = crate::ui_kit::TREE_ROW_HEIGHT; + let (top, bottom) = drops.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(top, bottom), drop| (top.min(drop.y), bottom.max(drop.y))); + let slot = ui + .ctx() + .pointer_latest_pos() + .filter(|p| ui.max_rect().x_range().contains(p.x) && p.y >= top - reach && p.y <= bottom + reach) + .and_then(|p| drops.iter().min_by(|a, b| (a.y - p.y).abs().total_cmp(&(b.y - p.y).abs())).copied()); + if released { + if let Some(drop) = slot { + crate::timeline_left::drop_items(app, plan, &drag.features, &[], drop.group, drop.position, drop.y < marker_y); + } + return; + } + if let Some(drop) = slot { + let rect = ui.max_rect(); + crate::ui_kit::history_drop_bar( + ui.painter(), + Rect::from_min_max(pos2(rect.left() + 4.0, drop.y), pos2(rect.right() - 5.0, drop.y)), + true, + Tokens::get().sketch_accent, + ); + } + app.tree.content.current_mut().feature_drags.insert(drag_id, drag); +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { @@ -327,9 +465,20 @@ mod tests { _ => None, }; h.app.tree.expanded.insert("c0/features".into()); - DRAWN.with(|d| d.borrow_mut().clear()); let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; - h.ctx.run_ui(raw, |ui| rows(&mut h.app, ui, 0, &[], 0, &mut Actions::default())).textures_delta.clear(); + h.ctx + .run_ui(raw, |ui| { + use crate::semantic_content::{self, ContentOwner, ContentRequest}; + semantic_content::begin(&mut h.app, ui.ctx()); + semantic_content::render_scope(&mut h.app, ui, ContentOwner::BROWSER, ContentRequest::Browser { shrink_height: false }, |app, ui| { + let mut actions = Actions::default(); + rows(app, ui, 0, &[], 0, &mut actions); + actions + }); + semantic_content::finalize(&mut h.app, ui.ctx()); + }) + .textures_delta + .clear(); drawn_rows().into_iter().map(|(label, ..)| label).collect() } @@ -346,6 +495,48 @@ mod tests { assert!(h.app.session.visibility.hidden_bodies.is_empty()); } + #[test] + fn browser_feature_rows_stay_listed_after_manual_rollback() { + let mut h = Harness::new(); + for name in ["Before", "After"] { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":name})).unwrap(); + } + h.app.run("timeline.roll_to", json!({"position":1})).unwrap(); + for cache in ["current", "missing", "stale"] { + assert_eq!(feature_rows(&mut h, cache), ["Features", "Before", "After"], "{cache}"); + } + h.app.run("timeline.roll_to", json!({})).unwrap(); + for cache in ["current", "missing", "stale"] { + assert_eq!(feature_rows(&mut h, cache), ["Features", "Before", "After"], "{cache}"); + } + } + + #[test] + fn browser_feature_rows_follow_the_editor_and_restore_the_manual_marker() { + let mut h = Harness::new(); + let mut ids = Vec::new(); + for name in ["Before", "Edited", "After"] { + ids.push(h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":name})).unwrap()["feature"].as_u64().unwrap()); + } + h.app.run("timeline.roll_to", json!({"position":2})).unwrap(); + h.app.edit_feature(ids[1]); + assert!(h.app.dialog.as_ref().is_some_and(|d| d.editing.is_some())); + for cache in ["current", "missing", "stale"] { + assert_eq!(feature_rows(&mut h, cache), ["Features", "Before"], "{cache}"); + assert_eq!(shown_features(&h.app, true), 3, "history keeps all rows during editing"); + } + crate::dialogs::cancel(&mut h.app); + assert_eq!(h.app.session.doc.marker, Some(2)); + for cache in ["current", "missing", "stale"] { + assert_eq!(feature_rows(&mut h, cache), ["Features", "Before", "Edited", "After"], "{cache}"); + } + h.app.edit_feature(ids[0]); + for cache in ["current", "missing", "stale"] { + assert!(feature_rows(&mut h, cache).is_empty(), "{cache}: no feature precedes the editor"); + } + crate::dialogs::cancel(&mut h.app); + } + #[test] fn browser_feature_sketch_only_has_one_sketch_row_and_no_features_folder() { let mut h = Harness::new(); @@ -423,11 +614,11 @@ mod tests { } fn find_in_timeline(app: &mut SolveApp, feature: u64, body: &str) { - let state = app.session.world_state(); + let state = app.session.world_state().unwrap(); let model_body = state.body(body).unwrap(); let names = solidcraft_engine::doc::naming::face_names(model_body); let index = names.iter().position(|name| name.starts_with(&format!("F{feature}:"))).unwrap(); - app.session.selection = vec![Sel::Face { body: body.into(), index, point: solidcraft_engine::geom::Vec3::ZERO }]; + app.session.selection = vec![Sel::Face { body: body.into(), index, point: solidcore_record::Vec3::ZERO }]; let item = crate::context_menu::items(app, &Target::Viewport).into_iter().find(|item| item.id == "ui.findTimeline").unwrap(); assert!(item.enabled); crate::context_menu::run_item(app, &item, pos2(0.0, 0.0)); @@ -518,7 +709,7 @@ mod tests { fn browser_find_from_a_body_or_its_face_reveals_the_body() { let mut h = Harness::new(); h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap(); - for pick in [Sel::Body { name: "Plate".into() }, Sel::Face { body: "Plate".into(), index: 0, point: solidcraft_engine::geom::Vec3::ZERO }] { + for pick in [Sel::Body { name: "Plate".into() }, Sel::Face { body: "Plate".into(), index: 0, point: solidcore_record::Vec3::ZERO }] { h.app.tree.reveal = None; h.app.session.selection = vec![pick.clone()]; let item = crate::context_menu::items(&h.app, &Target::Viewport).into_iter().find(|item| item.id == "ui.findBrowser").unwrap(); @@ -536,7 +727,7 @@ mod tests { } fn face(body: &str) -> Sel { - Sel::Face { body: body.into(), index: 0, point: solidcraft_engine::geom::Vec3::ZERO } + Sel::Face { body: body.into(), index: 0, point: solidcore_record::Vec3::ZERO } } #[test] @@ -587,6 +778,31 @@ mod tests { } } + /// #6083: in a long tree of placements, only the folded Features folders on screen work out + /// their mark (each scanned the design's whole history, every frame); those on screen still + /// show it. + #[test] + fn only_folded_features_folders_on_screen_work_out_their_mark() { + let mut h = Harness::new(); + // The folders sit inside placements, which start closed (#9274). + h.app.preferences.browser_components_open = true; + let component = h.app.run("component.create", json!({"name":"Part"})).unwrap(); + let feature = h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap()["feature"].as_u64().unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let first = component["occurrence"].as_u64().unwrap(); + for i in 1..=80 { + h.app.run("occurrence.copy", json!({"occurrence":first,"translate":[20.0 * f64::from(i),0,0]})).unwrap(); + } + h.frames(2); + let result = h.app.session.model.results.iter_mut().find(|r| r.id == feature).unwrap(); + result.error = Some("the blend is larger than the neighbouring faces".into()); + MARKS_WORKED_OUT.with(|n| n.set(0)); + h.frame(); + let worked = MARKS_WORKED_OUT.with(std::cell::Cell::get); + assert!(worked > 0 && worked < 40, "{worked} of 81 folded Features folders worked out their mark"); + assert!(!crate::scenario::handles("status:error:Features").is_empty(), "a folder on screen shows its mark"); + } + #[test] fn browser_find_reveals_a_placed_body_whose_row_is_off_screen() { let mut h = Harness::new(); @@ -637,10 +853,10 @@ mod tests { let inserted = h.app.run("component.insert_design", json!({"path":source.0.to_string_lossy()})).unwrap(); let path = vec![inserted["occurrence"].as_u64().unwrap()]; let name = h.app.session.occurrence_bodies(&path, false).unwrap()[0].clone(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let owner = state.body(&name).unwrap().feature; assert_ne!(owner, base); - h.app.session.selection = vec![Sel::Face { body: name, index: 0, point: solidcraft_engine::geom::Vec3::ZERO }]; + h.app.session.selection = vec![Sel::Face { body: name, index: 0, point: solidcore_record::Vec3::ZERO }]; for id in ["ui.findTimeline", "ui.editFeature"] { let item = crate::context_menu::items(&h.app, &Target::Viewport).into_iter().find(|item| item.id == id).unwrap(); assert!(!item.enabled || item.params.as_ref().unwrap()["feature"] == json!(owner), "{id}: {item:?}"); @@ -698,6 +914,58 @@ mod tests { assert!(labels.contains(&block_name), "a rolled-back feature stays listed: {labels:?}"); } + /// #10079: three extrusions of one visible sketch, the first renamed. A click just past the end + /// of a feature's name, or a press on the name that slips a few points before its release, + /// selects the feature; only the sketch button itself opens the sketch. + #[test] + fn clicking_just_past_a_feature_name_selects_it_without_opening_its_sketch() { + let mut h = Harness::new(); + let sketch = h.app.run("sketch.create", json!({"plane":"XY","name":"Sketch1"})).unwrap()["sketch"].as_u64().unwrap(); + for (p0, p1) in [([0, 0], [10, 10]), ([20, 0], [30, 10]), ([40, 0], [50, 10])] { + h.app.run("sketch.rectangle.two_point", json!({"p0":p0,"p1":p1})).unwrap(); + } + h.app.run("sketch.finish", json!({})).unwrap(); + let mut ids = Vec::new(); + for profile in 0..3 { + let made = h.app.run("solid.extrude", json!({"sketch":sketch,"profiles":[profile],"distance":5})).unwrap(); + ids.push(made["feature"].as_u64().unwrap()); + if profile == 0 { + h.app.run("timeline.rename", json!({"feature":ids[0],"name":"Lid"})).unwrap(); + } + } + // The sketch stays shown, as in the report. + crate::browser::set_sketch_visible(&mut h.app, sketch, true); + h.app.tree.expanded.insert("c0/features".into()); + h.settle(); + assert!(crate::browser::sketch_visible(&h.app, sketch)); + let press = |h: &mut Harness, at: Pos2, pressed: bool| { + h.frame_with(vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }]); + }; + // A press at `from` released at `to`, then long enough that the next click is not a double. + let click = |h: &mut Harness, from: Pos2, to: Pos2| { + h.frame_with(vec![egui::Event::PointerMoved(from)]); + press(h, from, true); + h.frame_with(vec![egui::Event::PointerMoved(to)]); + press(h, to, false); + h.frames(30); + }; + for (round, id) in ids.iter().chain(&ids).enumerate() { + let name = h.app.session.doc.feature(*id).unwrap().name.clone(); + for (from, to) in [(1.0, 1.0), (5.0, 5.0), (-2.0, 4.0)] { + // Selected rows draw their name in semibold, wider: measure it each time. + let label = crate::scenario::rect_of(&format!("row_label:{name}")).unwrap(); + let at = |dx: f32| pos2(label.right() + dx, label.center().y); + click(&mut h, at(from), at(to)); + assert_eq!(h.app.session.active_sketch, None, "round {round}: {name} clicked {from}..{to} points past its name opened the sketch"); + assert!(h.app.dialog.is_none(), "round {round}: {name} opened a dialog"); + assert_eq!(h.app.session.selection, [Sel::Feature { id: *id }], "round {round}: {name} {from}..{to}"); + } + } + h.step(&json!({"click": {"handle": "action:Extrude1"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.session.active_sketch, Some(sketch), "the sketch button still opens the sketch"); + } + fn settle_heavy(h: &mut Harness) { for _ in 0..500 { if h.app.deferred.is_none() && h.app.deferred_queue.is_empty() { @@ -871,4 +1139,33 @@ mod tests { h.frames(2); assert_eq!(marks(), ["status:warning:Warned"], "a suppressed feature isn't built and has no mark"); } + + /// #9565: with the History in the browser, dragging a feature row moves the feature as the + /// History at the left does, and the marker still drags on its own. + #[test] + fn browser_history_rows_reorder_by_drag_and_the_marker_still_rolls_back() { + let mut h = Harness::new(); + let mut ids = Vec::new(); + for (i, name) in ["First", "Second", "Third"].into_iter().enumerate() { + let size = 5 + i as u64; + let r = h.app.run("solid.box", json!({"length":size,"width":size,"height":size,"name":name,"body_name":name})).unwrap(); + ids.push(r["feature"].as_u64().unwrap()); + } + h.app.run("view.history_layout", json!({"dock":"browser"})).unwrap(); + settle_heavy(&mut h); + let order = |h: &Harness| h.app.session.doc.features.iter().map(|f| f.id).collect::>(); + assert_eq!(order(&h), ids); + + let first = crate::scenario::handle_at(&format!("row:browser-feature:c0:{}", ids[0])).unwrap(); + h.step(&json!({"drag":[{"handle":format!("row:browser-feature:c0:{}", ids[2])},[first.x, first.y - 8.0]]})).unwrap(); + settle_heavy(&mut h); + assert_eq!(order(&h), [ids[2], ids[0], ids[1]], "dropped above the first row: the third feature moves to the top"); + assert_eq!(h.app.session.doc.marker, None, "dropped above the marker: still built"); + + let second = crate::scenario::handle_at(&format!("row:browser-feature:c0:{}", ids[1])).unwrap(); + h.step(&json!({"drag":[{"handle":"browser:rollback"},[second.x, second.y - 8.0]]})).unwrap(); + settle_heavy(&mut h); + assert_eq!(h.app.session.doc.marker, Some(2), "the marker drag still rolls back"); + assert_eq!(order(&h), [ids[2], ids[0], ids[1]], "rolling back moves no feature"); + } } diff --git a/crates/ui-egui/src/browser/point_cloud_tracks.rs b/crates/ui-egui/src/browser/point_cloud_tracks.rs new file mode 100644 index 000000000..04e32694c --- /dev/null +++ b/crates/ui-egui/src/browser/point_cloud_tracks.rs @@ -0,0 +1,219 @@ +//! What the Edit Point Cloud card's range tracks draw, worked out off the frame: each track's +//! bars over the whole span and over its loupe, and the values its ends snap to. A track asks +//! every frame; a worker thread answers the newest asks (on the web, where there are no threads, +//! they are answered at once), and until then the track shows its last answer. The view asks too, +//! for the values the coloured property takes over what is kept: the ramp's automatic range. + +use std::collections::HashMap; +use std::sync::{Arc, Condvar, Mutex}; + +use egui::Color32; +use solidcraft_engine::doc::point_cloud::{Filter, PALETTE, PLAIN, PointCloud, byte, height_ramp}; +use solidcraft_engine::doc::point_cloud_distribution::{Colour, Geometry, histogram, label_changes}; + +use super::range_track::Bars; +use crate::theme::model_color; + +/// Equal bands a ramp's bars are split into. +const RAMP_BANDS: usize = 32; + +/// How a track's bars are coloured. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Paint { + /// One colour. + One, + /// The ramp over `range` of `property`; painted at each value when the track is that property. + Ramp { property: String, range: [f64; 2] }, + /// The palette of a whole-numbered `property`. + Palette { property: String }, +} + +/// What a track asks for: its property's bars over the whole span and over the loupe, in `bins` +/// bins each, over what `filters` keep; and the values where `changes_of` changes along it. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Ask { + pub property: String, + pub span: [f64; 2], + pub loupe: [f64; 2], + pub bins: usize, + pub paint: Paint, + pub filters: Vec, + pub changes_of: Option, +} + +/// A track's answer. +#[derive(Clone, Debug, Default)] +pub(crate) struct Answer { + pub(super) overview: Bars, + pub(super) loupe: Bars, + pub(super) changes: Arc>, + /// The least and the greatest value the property takes over what is kept. + pub extent: Option<[f64; 2]>, +} + +/// The cloud's data as far as the tracks are concerned: its points, columns and placement. +type DataKey = Vec; + +fn data_key(c: &PointCloud) -> DataKey { + let mut k = vec![Arc::as_ptr(c.points.values()).cast::() as u64, c.origin.x.to_bits(), c.origin.y.to_bits(), c.origin.z.to_bits()]; + k.extend(c.complex.columns.iter().map(|col| Arc::as_ptr(&col.values.0).cast::() as u64)); + k.extend(c.transform.iter().flatten().map(|v| v.to_bits())); + k +} + +/// What answers need of a cloud, worked out once for its data. +struct Prepared { + key: DataKey, + cloud: Arc, + geometry: Option>, + changes: HashMap<(String, String), Arc>>, +} + +impl Prepared { + fn answer(&mut self, ask: &Ask) -> Answer { + let c = &self.cloud; + let geometry = self.geometry.get_or_insert_with(|| Arc::new(Geometry::of(c))).clone(); + let (colour, colours, ramp) = match &ask.paint { + // Coloured by its own property, each value has its colour: the bars are one slot, + // painted along the ramp. + Paint::Ramp { property, range } if *property == ask.property => (Colour::One, vec![plain()], Some(*range)), + Paint::Ramp { property, range } => ( + Colour::Ramp { property, range: *range, bands: RAMP_BANDS }, + (0..RAMP_BANDS).map(|k| model_color(height_ramp((k as f64 + 0.5) / RAMP_BANDS as f64))).chain([plain()]).collect(), + None, + ), + Paint::Palette { property } => { + (Colour::Palette { property }, PALETTE.iter().map(|c| model_color(*c)).chain([plain(), plain()]).collect(), None) + } + Paint::One => (Colour::One, vec![plain()], None), + }; + let bars = |axis: [f64; 2]| { + let h = histogram(c, &geometry, &ask.property, axis, ask.bins, &colour, &ask.filters); + let extent = h.as_ref().and_then(|h| h.extent); + (Bars { axis, slots: h.map(|h| h.slots).unwrap_or_default(), colours: colours.clone(), ramp }, extent) + }; + let (overview, extent) = bars(ask.span); + let loupe = if ask.loupe == ask.span { overview.clone() } else { bars(ask.loupe).0 }; + let changes = match &ask.changes_of { + Some(label) => self + .changes + .entry((label.clone(), ask.property.clone())) + .or_insert_with(|| Arc::new(label_changes(c, &geometry, label, &ask.property))) + .clone(), + None => Arc::default(), + }; + Answer { overview, loupe, changes, extent } + } +} + +/// What has no colour of its own: the cloud's plain colour. +fn plain() -> Color32 { + model_color(PLAIN.map(byte)) +} + +#[derive(Default)] +struct Inner { + cloud: Option<(DataKey, Arc)>, + asked: HashMap, + answers: HashMap)>, +} + +#[derive(Default)] +struct Shared { + inner: Mutex, + asked: Condvar, +} + +/// The answers of one card's tracks; clones share them. +#[derive(Clone, Default)] +pub(crate) struct Tracks { + shared: Arc, + #[cfg(not(target_arch = "wasm32"))] + worker: Arc>, +} + +impl std::fmt::Debug for Tracks { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Tracks") + } +} + +impl Tracks { + /// The last answer to the track `key` (maybe to an older ask), asking `ask` of `cloud` when + /// that is new. + pub(crate) fn answer(&self, ctx: &egui::Context, cloud: &PointCloud, key: &str, ask: Ask) -> Option> { + let Ok(mut inner) = self.shared.inner.lock() else { return None }; + let data = data_key(cloud); + if inner.cloud.as_ref().is_none_or(|(k, _)| *k != data) { + inner.cloud = Some((data, Arc::new(cloud.clone()))); + } + let last = inner.answers.get(key).cloned(); + let answered = last.as_ref().is_some_and(|(a, _)| *a == ask); + if !answered && inner.asked.get(key) != Some(&ask) { + inner.asked.insert(key.to_string(), ask); + drop(inner); + self.work(ctx); + } + last.map(|(_, a)| a) + } + + /// Whether the track `key` has an answer to its last ask. + #[cfg(test)] + pub(super) fn answered(&self, key: &str) -> bool { + self.shared.inner.lock().is_ok_and(|i| !i.asked.contains_key(key) && i.answers.contains_key(key)) + } + + #[cfg(not(target_arch = "wasm32"))] + fn work(&self, ctx: &egui::Context) { + self.shared.asked.notify_one(); + self.worker.get_or_init(|| { + let shared = Arc::downgrade(&self.shared); + let ctx = ctx.clone(); + let _ = std::thread::Builder::new().name("point-cloud-tracks".into()).spawn(move || work(&shared, &ctx)); + }); + } + + #[cfg(target_arch = "wasm32")] + fn work(&self, ctx: &egui::Context) { + let mut prepared = None; + while answer_one(&self.shared, &mut prepared) {} + ctx.request_repaint(); + } +} + +/// Answer one ask, if there is one. +fn answer_one(shared: &Shared, prepared: &mut Option) -> bool { + let (key, ask, data, cloud) = { + let Ok(mut inner) = shared.inner.lock() else { return false }; + let Some(key) = inner.asked.keys().next().cloned() else { return false }; + let Some(ask) = inner.asked.remove(&key) else { return false }; + let Some((data, cloud)) = inner.cloud.clone() else { return false }; + (key, ask, data, cloud) + }; + if prepared.as_ref().is_none_or(|p| p.key != data) { + *prepared = Some(Prepared { key: data, cloud, geometry: None, changes: HashMap::new() }); + } + let Some(p) = prepared.as_mut() else { return false }; + let answer = Arc::new(p.answer(&ask)); + if let Ok(mut inner) = shared.inner.lock() { + inner.answers.insert(key, (ask, answer)); + } + true +} + +/// The worker: answers asks as they come, until the card is gone. +#[cfg(not(target_arch = "wasm32"))] +fn work(shared: &std::sync::Weak, ctx: &egui::Context) { + let mut prepared = None; + loop { + let Some(s) = shared.upgrade() else { return }; + if answer_one(&s, &mut prepared) { + ctx.request_repaint(); + continue; + } + let Ok(inner) = s.inner.lock() else { return }; + if inner.asked.is_empty() { + let _ = s.asked.wait_timeout(inner, std::time::Duration::from_millis(500)); + } + } +} diff --git a/crates/ui-egui/src/browser/point_clouds.rs b/crates/ui-egui/src/browser/point_clouds.rs index 0e504e1bc..2c17627f3 100644 --- a/crates/ui-egui/src/browser/point_clouds.rs +++ b/crates/ui-egui/src/browser/point_clouds.rs @@ -1,10 +1,13 @@ //! The Point Clouds folder of the Browser (#5151): an eye per cloud and for the folder, a menu, -//! and the Edit Point Cloud card (the file's units, the size of the dots, how they are coloured: -//! the file's colours, one colour, or by height between two heights), whose live edits of one -//! opening are one undo step. +//! and the Edit Point Cloud card: the file's units, the size of the dots, how the cloud is +//! coloured (its colours, one colour, a ramp over a property, its range on a track, or the +//! palette of a label, with its legend), and its filters (a range on a track, played with ▶ or +//! Space, or the values of a label picked in its legend). Each track shows how much of the cloud +//! lies at each value, over what the other filters keep. The live edits of one opening are one +//! undo step. use serde_json::{Value, json}; -use solidcraft_engine::doc::point_cloud::{ColorBy, PLAIN, PointCloud, UNITS, byte}; +use solidcraft_engine::doc::point_cloud::{COORDINATES, ColorBy, Filter, Keep, MAX_FILTERS, Names, PLAIN, PointCloud, UNITS, byte, label_color}; use solidcraft_engine::view::POINT_CLOUDS_FOLDER; use super::{Actions, Row, draw_row, is_open, panel_pos, toggle, toggle_folder}; @@ -12,18 +15,86 @@ use crate::SolveApp; use crate::context_menu::{Item, Target}; use crate::ui_kit; -/// The Edit Point Cloud card: the cloud, the undo depth when it opened, and the automatic -/// height range of the points it was worked out for (it sorts a sample of them). +#[path = "point_cloud_tracks.rs"] +pub(crate) mod point_cloud_tracks; +#[path = "range_track.rs"] +mod range_track; +use point_cloud_tracks::{Ask, Paint, Tracks}; +use range_track::{Part, Track, range_track}; + +/// Filters the GPU applies; the others are kept but not drawn. +pub const DRAWN_FILTERS: usize = solidcraft_gpu::view::FILTERS; + +/// The Edit Point Cloud card: the cloud, the undo depth when it opened, what it worked out once +/// for the cloud's data (the automatic height range), its tracks' bars, and a filter playing. #[derive(Clone, Debug)] pub struct CloudPanel { pub cloud: u64, pub(crate) depth: usize, auto: Option<(usize, [u64; 16], Option<[f64; 2]>)>, + tracks: Tracks, + pub play: Option, +} + +/// A range filter moving on its own: the part of it touched last moves forward (its upper end +/// unrolls, its band slides, its lower end wipes), across its track's loupe in [`PLAY_SECONDS`]. +/// It is written to the design once, when it stops. +#[derive(Clone, Debug)] +pub struct Play { + pub filter: usize, + part: Part, + /// When it last moved, and where it is exactly. + at: f64, + exact: [f64; 2], + /// The range now (a whole-numbered property's ends whole). + pub now: [f64; 2], +} + +/// How long playing a filter across its track's loupe takes, in seconds: zooming in slows it. +const PLAY_SECONDS: f64 = 20.0; + +/// The names of a cloud's tracks. +fn filter_key(cloud: u64, k: usize) -> String { + format!("point_cloud_{cloud}_filter_{k}") +} +fn colour_key(cloud: u64) -> String { + format!("point_cloud_{cloud}_colour") +} + +impl Play { + /// Start playing `part` of `range` within `span`, from the start again when it is at the end. + fn new(filter: usize, part: Part, [lo, hi]: [f64; 2], span: [f64; 2], at: f64) -> Play { + let exact = match part { + Part::High if hi >= span[1] => [lo, lo], + Part::Band if hi >= span[1] => [span[0], span[0] + hi - lo], + Part::Low if lo >= hi => [span[0], hi], + _ => [lo, hi], + }; + Play { filter, part, at, exact, now: exact } + } + /// Move on to time `now` at `speed` units a second; whether it reached the end. + fn step(&mut self, now: f64, speed: f64, span: [f64; 2], integer: bool) -> bool { + let d = speed * (now - self.at).max(0.0); + self.at = now; + let [lo, hi] = self.exact; + let (exact, end) = match self.part { + Part::High => ([lo, (hi + d).min(span[1])], hi + d >= span[1]), + Part::Low => ([(lo + d).min(hi), hi], lo + d >= hi), + Part::Band => { + let w = hi - lo; + let start = (lo + d).min(span[1] - w); + ([start, start + w], lo + d >= span[1] - w) + } + }; + self.exact = exact; + self.now = if integer { exact.map(f64::floor) } else { exact }; + end + } } impl CloudPanel { pub fn new(app: &SolveApp, cloud: u64) -> Self { - CloudPanel { cloud, depth: app.session.undo.len(), auto: None } + CloudPanel { cloud, depth: app.session.undo.len(), auto: None, tracks: Tracks::default(), play: None } } /// The cloud's automatic height range, worked out again only when its points or placement /// change. @@ -38,11 +109,80 @@ impl CloudPanel { } } } + /// The range filter `k` of this card's cloud shows now, while it plays. + pub fn playing(&self, cloud: u64, k: usize) -> Option<[f64; 2]> { + self.play.as_ref().filter(|p| self.cloud == cloud && p.filter == k).map(|p| p.now) + } } /// The ways the card colours the points, as the dropdown lists them. const COLOR_BY: [(ColorBy, &str); 3] = [(ColorBy::File, "File Colors"), (ColorBy::Single, "Single Color"), (ColorBy::Height, "Height")]; +/// The names of `property` when it is filtered by a set of values: a label whose values span +/// fewer than the 32 the view's mask holds. Any other property is filtered by a range. +fn label<'a>(c: &'a PointCloud, property: &str) -> Option<&'a Names> { + let names = c.complex.names(property)?; + let (lo, hi) = names.values.iter().fold((i32::MAX, i32::MIN), |(lo, hi), (v, _)| (lo.min(*v), hi.max(*v))); + (i64::from(hi) - i64::from(lo) < 32).then_some(names) +} + +/// Bins of a track's bars: about one a point across the card. +fn bins(ui: &egui::Ui) -> usize { + (ui.available_width().round() as usize).clamp(16, 1024) +} + +/// The filters as `pointcloud.edit` takes them. +fn filters_json(filters: &[Filter]) -> Vec { + filters.iter().map(|f| serde_json::to_value(f).unwrap_or(Value::Null)).collect() +} + +/// The filters with `value` of the label `property` shown or hidden: in its set filter, or in a +/// new one keeping every named value but it. +fn toggled(c: &PointCloud, names: &Names, value: i32) -> Vec { + let mut filters = c.filters.clone(); + match filters.iter_mut().find(|f| f.property == names.property && matches!(f.keep, Keep::Values { .. })) { + Some(Filter { keep: Keep::Values { values }, .. }) => { + if let Some(k) = values.iter().position(|v| *v == value) { + values.remove(k); + } else { + values.push(value); + } + } + _ => filters.push(Filter { + property: names.property.clone(), + keep: Keep::Values { values: names.values.iter().map(|(v, _)| *v).filter(|v| *v != value).collect() }, + }), + } + filters_json(&filters) +} + +/// A label's legend: a swatch and a name per value, dimmed when a filter hides it. The value +/// clicked, to show or hide. +fn legend(ui: &mut egui::Ui, c: &PointCloud, names: &Names) -> Option { + let kept = c.filters.iter().find_map(|f| match &f.keep { + Keep::Values { values } if f.property == names.property => Some(values.clone()), + _ => None, + }); + let mut clicked = None; + for (v, name) in &names.values { + let shown = kept.as_ref().is_none_or(|k| k.contains(v)); + let colour = crate::theme::model_color(label_color(f64::from(*v))); + let swatch = if shown { colour } else { colour.gamma_multiply(0.16) }; + let response = ui + .horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); + ui.painter().rect_filled(rect, 3.0, swatch); + let text = egui::RichText::new(name.as_str()); + ui.add(egui::Label::new(if shown { text } else { text.weak().strikethrough() }).sense(egui::Sense::click())) + }) + .inner; + if response.clicked() { + clicked = Some(*v); + } + } + clicked +} + pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut Actions) { let clouds: Vec<(u64, String, bool)> = app.session.doc.point_clouds.iter().map(|c| (c.id, c.name.clone(), c.visible)).collect(); if clouds.is_empty() { @@ -104,8 +244,29 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) { }; let mut edit: Option = None; let title = crate::i18n::format("browser.edit_point_cloud_title", &[("name", &c.name)]); - let (units, decimals) = (app.session.doc.units.clone(), app.preferences.length_decimals); let auto = if c.color_by == ColorBy::Height { m.auto_range(&c) } else { None }; + let now = ctx.input(|i| i.time); + // A playing filter moves on; at the end of its span it stops, and is written once. + let mut stop_play = false; + if let Some(p) = m.play.as_mut() + && let Some(span) = c.filters.get(p.filter).and_then(|f| c.span(&f.property)) + { + let integer = c.filters.get(p.filter).is_some_and(|f| c.complex.integer(&f.property)); + let [a, b] = range_track::loupe(ctx, &filter_key(c.id, p.filter), span); + stop_play = p.step(now, (b - a) / PLAY_SECONDS, span, integer); + ctx.request_repaint(); + } + // The cloud as the view draws it now, a playing filter where it is: the filters the tracks + // apply, how their bars are coloured, as the cloud is, and the values they snap to, where a + // label changes. + let live = crate::point_clouds::as_drawn(&c, |k| m.playing(c.id, k)).into_owned(); + let drawn: Vec = live.filters.iter().take(DRAWN_FILTERS).cloned().collect(); + let paint = match (c.colored_property(), crate::point_clouds::color_range(ctx, &live)) { + (Some(n), _) if c.complex.integer(n) => Paint::Palette { property: n.to_string() }, + (Some(n), Some(range)) => Paint::Ramp { property: n.to_string(), range }, + _ => Paint::One, + }; + let changes_of = c.colored_property().filter(|n| c.complex.integer(n)).map(str::to_string); let at = panel_pos(app); let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_point_cloud_panel"), "point", &title) .placed(egui::Align2::LEFT_TOP, at) @@ -113,29 +274,39 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) { .actions("", crate::i18n::tr("ui.close"), None) .show(ctx, true, |ui| { ui_kit::row(ui, crate::i18n::tr_label("Points"), |ui| ui.label(c.len().to_string())); - let names: Vec<&str> = UNITS.iter().map(|(u, _)| *u).collect(); - let was = names.iter().position(|u| *u == c.units).unwrap_or(0); - let mut unit = was; - // A dropdown's response doesn't report the pick: compare the index. - ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_units"), |ui| ui_kit::dropdown(ui, "point_cloud_units", &mut unit, &names)); - if unit != was - && let Some(u) = names.get(unit) - { - edit = Some(json!({ "cloud": c.id, "units": u })); - } let mut size = c.point_size; if ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_size"), |ui| ui_kit::slider(ui, &mut size, 0.5..=16.0, Default::default())).changed() { edit = Some(json!({ "cloud": c.id, "point_size": size })); } - let labels: Vec<&str> = COLOR_BY.iter().map(|(_, l)| *l).collect(); - let was = COLOR_BY.iter().position(|(b, _)| *b == c.color_by).unwrap_or(0); + let units: Vec<&str> = UNITS.iter().map(|(u, _)| *u).collect(); + let was = units.iter().position(|u| *u == c.units).unwrap_or(0); + let mut unit = was; + // A dropdown's response doesn't report the pick: compare the index. + ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_units"), |ui| ui_kit::dropdown(ui, "point_cloud_units", &mut unit, &units)); + if unit != was + && let Some(u) = units.get(unit) + { + edit = Some(json!({ "cloud": c.id, "units": u })); + } + // The ways of colouring, then every property of the file. + let properties: Vec<&str> = c.property_names().filter(|n| !COORDINATES.contains(n)).collect(); + let labels: Vec<&str> = COLOR_BY.iter().map(|(_, l)| *l).chain(properties.iter().copied()).collect(); + let was = match c.color_by { + ColorBy::Property => { + c.color_property.as_deref().and_then(|n| properties.iter().position(|p| *p == n)).map_or(0, |k| COLOR_BY.len() + k) + } + by => COLOR_BY.iter().position(|(b, _)| *b == by).unwrap_or(0), + }; let mut by = was; ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_color_by"), |ui| ui_kit::dropdown(ui, "point_cloud_color_by", &mut by, &labels)); - if by != was - && let Some((b, _)) = COLOR_BY.get(by) - { - edit = Some(json!({ "cloud": c.id, "color_by": b.name() })); + if by != was { + let name = COLOR_BY.get(by).map(|(b, _)| b.name()).or_else(|| properties.get(by - COLOR_BY.len()).copied()); + if let Some(name) = name { + edit = Some(json!({ "cloud": c.id, "color_by": name })); + } } + let colored = c.colored_property(); + let legend_shown = colored.and_then(|n| label(&c, n)); match c.color_by { ColorBy::File if c.colors.is_empty() => { ui_kit::row(ui, "", |ui| ui.weak(crate::i18n::tr("ui.point_cloud_no_file_colors"))); @@ -147,33 +318,201 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) { edit = Some(json!({ "cloud": c.id, "color": rgb.map(|v| f64::from(v) / 255.0) })); } } - ColorBy::Height => { - let automatic = c.height_range.is_none(); - if ui_kit::checkbox_row(ui, "point_cloud_auto_range", crate::i18n::tr("ui.point_cloud_auto_range"), automatic) { - // Off: start from the range worked out, which the fields then show. - edit = Some(json!({ "cloud": c.id, "height_range": if automatic { json!(auto) } else { Value::Null } })); - } - if let Some([mut lo, mut hi]) = c.height_range.or(auto) { - let mut changed = false; - ui.add_enabled_ui(!automatic, |ui| { - changed |= ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_height_low"), |ui| { - ui_kit::length_field(ui, &mut lo, &units, decimals) - }) - .changed(); - changed |= ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_height_high"), |ui| { - ui_kit::length_field(ui, &mut hi, &units, decimals) - }) - .changed(); - }); - // The two heights stay apart, lowest first. - if changed && !automatic { - let hi = hi.max(lo + 1e-3); - edit = Some(json!({ "cloud": c.id, "height_range": [lo, hi] })); + ColorBy::Height | ColorBy::Property => { + let name = colored.unwrap_or_default(); + if let Some(names) = legend_shown { + // A label: its legend, which also shows and hides its values. + if let Some(v) = legend(ui, &c, names) { + edit = Some(json!({ "cloud": c.id, "filters": toggled(&c, names, v) })); + } + } else if !c.complex.integer(name) + && let Some(span) = if c.color_by == ColorBy::Height { c.span("z").or(auto) } else { c.span(name) } + { + // A ramp over what is shown, unless its range is set. + let automatic = c.height_range.is_none(); + if ui_kit::checkbox_row(ui, "point_cloud_auto_range", crate::i18n::tr("ui.point_cloud_auto_range"), automatic) { + edit = Some(json!({ "cloud": c.id, "color_range": if automatic { json!(crate::point_clouds::color_range(ui.ctx(), &live)) } else { Value::Null } })); + } + // The ramp's range is a range on a track of the property, over what the + // filters keep; a double click beside it gives it back to the filters. + let shown = crate::point_clouds::color_range(ui.ctx(), &live).unwrap_or(span); + let key = colour_key(c.id); + let ask = Ask { + property: name.to_string(), + span, + loupe: range_track::loupe(ui.ctx(), &key, span), + bins: bins(ui), + paint: Paint::Ramp { property: name.to_string(), range: shown }, + filters: drawn.clone(), + changes_of: None, + }; + let answer = m.tracks.answer(ui.ctx(), &c, &key, ask); + let out = range_track( + ui, + &Track { + key: &key, + range: shown, + span, + integer: false, + overview: answer.as_ref().map(|a| &a.overview), + loupe: answer.as_ref().map(|a| &a.loupe), + changes: &[], + // An automatic range moves with a playing filter: its moving end + // stays in the loupe. + follow: m.play.as_ref().filter(|_| automatic).map(|p| if p.part == Part::Low { shown[0] } else { shown[1] }), + }, + ); + if let Some(range) = out.range { + edit = Some(json!({ "cloud": c.id, "color_range": range })); + } else if out.whole { + edit = Some(json!({ "cloud": c.id, "color_range": Value::Null })); } } } } + // Filters: only what every one of them keeps is shown. + let mut filters = c.filters.clone(); + let mut changed = false; + let mut removed = None; + for (k, f) in c.filters.iter().enumerate() { + let span = c.span(&f.property); + let integer = c.complex.integer(&f.property); + // Play or stop, by ▶ or Space on the track. + let mut toggle = None; + ui.horizontal(|ui| { + ui.label(crate::i18n::tr_dyn(&format!("Filter: {}", f.property))); + let playing = m.play.as_ref().is_some_and(|p| p.filter == k); + if let (Some(range), Some(span)) = (f.range(), span) + && ui_kit::button( + ui, + if playing { + format!("⏸ {}", crate::i18n::tr_label("Pause")) + } else { + format!("▶ {}", crate::i18n::tr_label("Play")) + }, + ui_kit::Button::Small, + ) + .clicked() + { + toggle = Some((m.playing(c.id, k).unwrap_or(range), span)); + } + if ui_kit::button(ui, "×", ui_kit::Button::Small).clicked() { + removed = Some(k); + } + }); + if k >= DRAWN_FILTERS { + ui.weak(crate::i18n::tr_dyn(&format!("Not drawn: the view applies {DRAWN_FILTERS} filters at most"))); + } + match (&f.keep, span) { + (Keep::Values { .. }, _) => match label(&c, &f.property) { + Some(names) if legend_shown.is_some_and(|l| l.property == names.property) => { + ui.weak(crate::i18n::tr_label("Shown and hidden in the legend above")); + } + Some(names) => { + if let Some(v) = legend(ui, &c, names) { + edit = Some(json!({ "cloud": c.id, "filters": toggled(&c, names, v) })); + } + } + None => {} + }, + (Keep::Range { range }, Some(span)) => { + let shown = m.playing(c.id, k).unwrap_or(*range); + let key = filter_key(c.id, k); + // The track shows what the other filters keep. + let others = drawn.iter().enumerate().filter(|(j, _)| *j != k).map(|(_, f)| f.clone()).collect(); + let ask = Ask { + property: f.property.clone(), + span, + loupe: range_track::loupe(ui.ctx(), &key, span), + bins: bins(ui), + paint: paint.clone(), + filters: others, + changes_of: changes_of.clone(), + }; + let answer = m.tracks.answer(ui.ctx(), &c, &key, ask); + let moving = m.play.as_ref().filter(|p| p.filter == k).map(|p| if p.part == Part::Low { shown[0] } else { shown[1] }); + let out = range_track( + ui, + &Track { + key: &key, + range: shown, + span, + integer, + overview: answer.as_ref().map(|a| &a.overview), + loupe: answer.as_ref().map(|a| &a.loupe), + changes: answer.as_ref().map_or(&[][..], |a| &a.changes[..]), + follow: moving, + }, + ); + let moved = out.range.or(out.whole.then_some(span)); + if let Some(range) = moved + && let Some(slot) = filters.get_mut(k) + { + slot.keep = Keep::Range { range }; + changed = true; + // Moving it by hand stops it playing. + if m.play.as_ref().is_some_and(|p| p.filter == k) { + m.play = None; + } + } + if out.play { + toggle = Some((moved.unwrap_or(shown), span)); + } + } + (Keep::Range { .. }, None) => {} + } + if let Some((range, span)) = toggle { + if m.play.as_ref().is_some_and(|p| p.filter == k) { + stop_play = true; + } else { + // Another filter playing stops where it is. + if let Some(p) = m.play.take() + && let Some(slot) = filters.get_mut(p.filter) + { + slot.keep = Keep::Range { range: p.now }; + changed = true; + } + let part = range_track::last_part(ui.ctx(), &filter_key(c.id, k)); + m.play = Some(Play::new(k, part, range, span, now)); + } + } + } + if let Some(k) = removed { + filters.remove(k); + changed = true; + m.play = None; + } + let all: Vec<&str> = c.property_names().collect(); + if c.filters.len() < MAX_FILTERS { + let mut add_labels = vec![crate::i18n::tr_label("Add filter…")]; + add_labels.extend(all.iter().copied()); + let mut pick = 0; + ui_kit::row(ui, crate::i18n::tr_label("Filter by"), |ui| ui_kit::dropdown(ui, "point_cloud_add_filter", &mut pick, &add_labels)); + if let Some(name) = all.get(pick.wrapping_sub(1)) { + // A label keeps all its values at first, anything else its whole span. + let keep = match (label(&c, name), c.span(name)) { + (Some(names), _) => Some(Keep::Values { values: names.values.iter().map(|(v, _)| *v).collect() }), + (None, Some(span)) => Some(Keep::Range { range: span }), + (None, None) => None, + }; + if let Some(keep) = keep { + filters.push(Filter { property: name.to_string(), keep }); + changed = true; + } + } + } + if changed { + edit = Some(json!({ "cloud": c.id, "filters": filters_json(&filters) })); + } }); + // A filter that stops playing is written where it stopped. + if stop_play && let Some(p) = m.play.take() { + let mut filters = c.filters.clone(); + if let Some(f) = filters.get_mut(p.filter) { + f.keep = Keep::Range { range: p.now }; + edit = Some(json!({ "cloud": c.id, "filters": filters_json(&filters) })); + } + } if let Some(p) = edit && app.run("pointcloud.edit", p).is_ok() { @@ -225,4 +564,96 @@ mod tests { assert_eq!(h.app.session.doc.point_clouds.len(), 1); let _ = std::fs::remove_dir_all(dir); } + + /// A PLY file of points along x, `t` running 0 to 10 by halves, a layer every 2: the layer + /// changes at t = 2, 4, 6 and 8. + fn layered_points(dir: &std::path::Path) -> std::path::PathBuf { + let mut ply = String::from( + "ply\nformat ascii 1.0\nelement vertex 21\nproperty float x\nproperty float y\nproperty float z\nproperty float t\nproperty int layer\nend_header\n", + ); + for i in 0..=20 { + let t = f64::from(i) / 2.0; + ply += &format!("{t} 0 0 {t} {}\n", (i / 4).min(4)); + } + let path = dir.join("layers.ply"); + std::fs::write(&path, ply).unwrap(); + path + } + + #[test] + fn a_filter_track_draws_snaps_steps_frames_and_plays() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let dir = std::env::temp_dir().join(format!("solidcraft-browser-track-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = layered_points(&dir); + let id = h.app.run("pointcloud.insert", json!({"path": path.to_string_lossy()})).unwrap()["cloud"].as_u64().unwrap(); + h.app.run("pointcloud.edit", json!({"cloud": id, "color_by": "layer", "filters": [{"property": "t", "range": [2.0, 5.0]}]})).unwrap(); + h.app.tree.cloud_panel = Some(super::CloudPanel::new(&h.app, id)); + let key = super::filter_key(id, 0); + let range = |h: &crate::scenario::Harness| h.app.session.doc.point_clouds[0].filters[0].range().unwrap(); + // The bars come from the worker: wait for them, and for the layer changes to snap to. + let mut bars = None; + for _ in 0..200 { + h.frames(1); + bars = crate::scenario::rect_of(&format!("range_track:{key}:bars")); + if bars.is_some() && h.app.tree.cloud_panel.as_ref().is_some_and(|m| m.tracks.answered(&key)) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.frames(2); + let r = bars.expect("the track is drawn"); + let x = |t: f64| f64::from(r.left()) + t / 10.0 * f64::from(r.width()); + let y = f64::from(r.center().y); + let drag = |h: &mut crate::scenario::Harness, a: f64, b: f64| { + h.call("ui.drag", json!({"x0": x(a), "y0": y, "x1": x(b), "y1": y, "steps": 8})); + h.frames(2); + }; + // Drawn beside the range: a new range, its start snapped to the layer change at 6. + drag(&mut h, 6.04, 8.9); + let [lo, hi] = range(&h); + assert!(lo == 6.0 && (hi - 8.9).abs() < 0.05, "{lo} {hi}"); + // Its end dragged near 8 snaps to it; its start, far from any change, does not. + drag(&mut h, 8.9, 7.97); + drag(&mut h, 6.0, 6.5); + let [lo, hi] = range(&h); + assert!((lo - 6.5).abs() < 0.05 && hi == 8.0, "{lo} {hi}"); + // ← steps the start, touched last, to the change before it, then the one before that. + for _ in 0..2 { + h.call("ui.key", json!({"key": "ArrowLeft"})); + h.frames(2); + } + assert_eq!(range(&h), [4.0, 8.0]); + // A double click on the range frames the loupe on it; beside it, the whole span. + h.call("ui.click", json!({"x": x(6.0), "y": y, "double": true})); + h.frames(2); + let [a, b] = super::range_track::loupe(&h.ctx, &key, [0.0, 10.0]); + assert!(a > 3.0 && a < 4.0 && b > 8.0 && b < 9.0, "{a} {b}"); + // A double click on the strip above shows the whole span again; beside the range, the + // range becomes the whole span. + // (Past the double click's time, so that it is not a third click.) + h.frames(30); + let strip = crate::scenario::rect_of(&format!("range_track:{key}:strip")).unwrap(); + h.call("ui.click", json!({"x": f64::from(strip.center().x), "y": f64::from(strip.center().y), "double": true})); + h.frames(2); + assert_eq!(super::range_track::loupe(&h.ctx, &key, [0.0, 10.0]), [0.0, 10.0]); + h.frames(30); + h.call("ui.click", json!({"x": x(9.5), "y": y, "double": true})); + h.frames(2); + assert_eq!(range(&h), [0.0, 10.0]); + // Space plays the part touched last (here the end, unrolling), written once when it stops. + drag(&mut h, 10.0, 7.0); + assert!((range(&h)[1] - 7.0).abs() < 0.05); + h.call("ui.key", json!({"key": "Space"})); + h.frames(2); + assert!(h.app.tree.cloud_panel.as_ref().unwrap().play.is_some()); + h.frames(20); + h.call("ui.key", json!({"key": "Space"})); + h.frames(2); + assert!(h.app.tree.cloud_panel.as_ref().unwrap().play.is_none()); + let [lo, hi] = range(&h); + assert!(lo == 0.0 && hi > 7.0 && hi < 10.0, "played on from 7: {hi}"); + let _ = std::fs::remove_dir_all(dir); + } } diff --git a/crates/ui-egui/src/browser/range_track.rs b/crates/ui-egui/src/browser/range_track.rs new file mode 100644 index 000000000..e399be472 --- /dev/null +++ b/crates/ui-egui/src/browser/range_track.rs @@ -0,0 +1,580 @@ +//! A range on a track, as in an audio editor. The track draws how much of the cloud lies at each +//! value (its bars) under the range. A thin strip above shows the whole span, with the part the +//! track shows (its loupe) framed: the strip is the same range widget, its range being the loupe. +//! +//! Gestures: drag a range's end or its band to move them; drag elsewhere to draw a new range; +//! Shift-click to bring the nearer end to the pointer; double-click the band to frame the loupe on +//! it, elsewhere to ask for the whole (`Outcome::whole`); the wheel or a pinch zooms the loupe +//! around the pointer, a sideways scroll moves it. An end snaps to a value where the colour +//! changes when that value stands alone at this zoom (nothing else within twice the reach), and +//! a whole-numbered property's ends to whole numbers; ⌥ moves ten times slower, without +//! snapping. With the keyboard, once the track is touched: ← and → bring the part touched last to +//! the previous or next change (one pixel with ⌥ or where there is none), Space asks to play it. +//! The ends and the length are fields too; a field's value may be typed relative, as `+30`. + +use egui::{Color32, Mesh, Pos2, Rect, Sense, Stroke, Ui, vec2}; + +use crate::ui_kit; + +use crate::theme::Tokens; + +/// The part of a range a gesture moves, and that playing moves. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Part { + Low, + #[default] + High, + Band, +} + +/// How much lies at each value of an axis: `slots[s][b]`, stacked in slot order, slot `s` in +/// `colours[s]`; or, with `ramp`, one slot painted at each value with the ramp over that range. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct Bars { + pub axis: [f64; 2], + pub slots: Vec>, + pub colours: Vec, + pub ramp: Option<[f64; 2]>, +} + +/// What a track shows and snaps to. +pub(super) struct Track<'a> { + /// Names the track among all of them. + pub key: &'a str, + pub range: [f64; 2], + pub span: [f64; 2], + pub integer: bool, + pub overview: Option<&'a Bars>, + pub loupe: Option<&'a Bars>, + /// Values the ends snap to and the arrows step through, lowest first. + pub changes: &'a [f64], + /// A value moving on its own (a range playing), kept in the loupe. + pub follow: Option, +} + +/// What a frame's input asks for. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Outcome { + /// The range moved. + pub range: Option<[f64; 2]>, + /// The whole: a double click beside the range. + pub whole: bool, + /// Play or stop: Space. + pub play: bool, + /// The range was touched by a gesture, a field or a key. + pub touched: bool, +} + +/// What a drag moves: an end, the band, or a new range from where it started. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Grab { + Low, + High, + Band, + New(f64), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Drag { + /// On the strip (moving the loupe) or the track (moving the range). + strip: bool, + grab: Grab, + /// The range when it started, and the value under the pointer now (slowed by ⌥). + start: [f64; 2], + at: f64, + from: f64, + last_x: f32, +} + +/// What the track keeps between frames. +#[derive(Clone, Copy, Debug, Default)] +struct State { + loupe: Option<[f64; 2]>, + drag: Option, + last: Part, + /// Where an end snapped during the drag. + snapped: Option, +} + +/// The loupe's narrowest width, as a fraction of the span. +const MIN_LOUPE: f64 = 1e-6; +/// Zoom per point of wheel scroll. +const ZOOM: f64 = 0.004; +/// How close to an end a press grabs it, and an end snaps, in points. +const REACH: f32 = 6.0; +/// ⌥'s slowing. +const FINE: f64 = 0.1; +const STRIP: f32 = 12.0; +const RULER: f32 = 14.0; +const BARS: f32 = 40.0; + +fn id(key: &str) -> egui::Id { + egui::Id::new(("sc_range_track", key)) +} + +fn state(ctx: &egui::Context, key: &str) -> State { + ctx.data(|d| d.get_temp(id(key))).unwrap_or_default() +} + +fn whole(span: [f64; 2]) -> [f64; 2] { + [span[0], span[1].max(span[0] + 1e-9)] +} + +/// The part of `span` a track shows now. +pub(super) fn loupe(ctx: &egui::Context, key: &str, span: [f64; 2]) -> [f64; 2] { + state(ctx, key).loupe.map_or(whole(span), |l| fit(l, whole(span))) +} + +/// The part of a track's range touched last. +pub(super) fn last_part(ctx: &egui::Context, key: &str) -> Part { + state(ctx, key).last +} + +/// `l` moved and narrowed to lie within `span`, at least its narrowest. +fn fit([a, b]: [f64; 2], span: [f64; 2]) -> [f64; 2] { + let full = span[1] - span[0]; + let w = (b - a).clamp(full * MIN_LOUPE, full); + let left = (a + (b - a - w) / 2.0).clamp(span[0], span[1] - w); + [left, left + w] +} + +/// The change nearest `v` within `r`, when no other change is within `2r` of it. +fn lone_change(changes: &[f64], v: f64, r: f64) -> Option { + let i = changes.partition_point(|c| *c < v); + let near = [i.checked_sub(1), Some(i)].into_iter().flatten().filter_map(|k| changes.get(k).map(|c| (k, *c))); + let (k, c) = near.min_by(|a, b| (a.1 - v).abs().total_cmp(&(b.1 - v).abs()))?; + let alone = k.checked_sub(1).and_then(|j| changes.get(j)).is_none_or(|p| c - p > 2.0 * r) && changes.get(k + 1).is_none_or(|n| n - c > 2.0 * r); + ((c - v).abs() <= r && alone).then_some(c) +} + +/// The changes standing alone at this zoom within `[a, b]`, at most `n`. +fn lone_changes(changes: &[f64], [a, b]: [f64; 2], r: f64, n: usize) -> Vec { + let (i, j) = (changes.partition_point(|c| *c < a), changes.partition_point(|c| *c <= b)); + (i..j) + .filter(|k| { + let c = changes.get(*k).copied().unwrap_or(f64::NAN); + k.checked_sub(1).and_then(|p| changes.get(p)).is_none_or(|p| c - p > 2.0 * r) && changes.get(k + 1).is_none_or(|q| q - c > 2.0 * r) + }) + .filter_map(|k| changes.get(k).copied()) + .take(n) + .collect() +} + +/// The next change after `v` (`dir` 1) or before it (-1). +fn next_change(changes: &[f64], v: f64, dir: f64) -> Option { + let eps = v.abs().max(1.0) * 1e-12; + if dir > 0.0 { + changes.get(changes.partition_point(|c| *c <= v + eps)).copied() + } else { + changes.partition_point(|c| *c < v - eps).checked_sub(1).and_then(|k| changes.get(k)).copied() + } +} + +/// Bar and tick steps: 1, 2 or 5 times a power of ten, at least `min` apart. +fn nice_step(min: f64) -> f64 { + let k = 10f64.powf(min.max(1e-300).log10().floor()); + [1.0, 2.0, 5.0, 10.0].into_iter().map(|m| m * k).find(|s| *s >= min).unwrap_or(10.0 * k) +} + +/// Paint `bars` within `rect`, showing `axis`; each column scaled to the tallest shown. +fn paint_bars(painter: &egui::Painter, rect: Rect, axis: [f64; 2], bars: &Bars, fill: Color32, ink: Color32) { + painter.rect_filled(rect, 2.0, fill); + let n = bars.slots.first().map_or(0, Vec::len); + if n == 0 || !(bars.axis[1] > bars.axis[0]) { + return; + } + let width = (bars.axis[1] - bars.axis[0]) / n as f64; + let x_of = |v: f64| rect.left() + ((v - axis[0]) / (axis[1] - axis[0])) as f32 * rect.width(); + let total = |b: usize| bars.slots.iter().filter_map(|s| s.get(b)).sum::(); + let shown: Vec = (0..n) + .filter(|b| { + let lo = bars.axis[0] + *b as f64 * width; + lo + width >= axis[0] && lo <= axis[1] + }) + .collect(); + let peak = shown.iter().map(|b| total(*b)).fold(0.0, f64::max); + if !(peak > 0.0) { + return; + } + let mut mesh = Mesh::default(); + for b in shown { + let lo = bars.axis[0] + b as f64 * width; + let (x0, x1) = (x_of(lo).max(rect.left()), x_of(lo + width).min(rect.right()).max(x_of(lo).max(rect.left()) + 1.0)); + let mut y = rect.bottom(); + for (s, slot) in bars.slots.iter().enumerate() { + let h = (slot.get(b).copied().unwrap_or(0.0) / peak) as f32 * (rect.height() - 2.0); + if h <= 0.0 { + continue; + } + let colour = match bars.ramp { + Some([a, z]) if z > a => { + crate::theme::model_color(solidcraft_engine::doc::point_cloud::height_ramp((lo + width / 2.0 - a) / (z - a))) + } + _ => bars.colours.get(s).copied().unwrap_or(ink), + }; + mesh.add_colored_rect(Rect::from_min_max(Pos2::new(x0, y - h), Pos2::new(x1, y)), colour); + y -= h; + } + } + painter.add(mesh); +} + +/// The range within `span` after this frame's input, and what else the input asks for. +pub(super) fn range_track(ui: &mut Ui, track: &Track) -> Outcome { + let t = Tokens::get(); + let ctx = ui.ctx().clone(); + let mut st = state(&ctx, track.key); + let span = whole(track.span); + let mut out = Outcome::default(); + let mut range = track.range; + let mut view = st.loupe.map_or(span, |l| fit(l, span)); + if let Some(f) = track.follow + && (f < view[0] || f > view[1]) + { + let w = view[1] - view[0]; + view = fit([f - 0.1 * w, f + 0.9 * w], span); + st.loupe = Some(view); + } + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP + RULER + BARS + 4.0), Sense::click_and_drag()); + let inner = rect.shrink2(vec2(REACH, 0.0)); + let strip = Rect::from_min_size(inner.min, vec2(inner.width(), STRIP)); + let ruler = Rect::from_min_size(Pos2::new(inner.left(), strip.bottom() + 2.0), vec2(inner.width(), RULER)); + let bars = Rect::from_min_size(Pos2::new(inner.left(), ruler.bottom() + 2.0), vec2(inner.width(), BARS)); + // Named for agents and tests: the strip and the bars. + crate::scenario::publish_rect(&format!("range_track:{}:strip", track.key), strip); + crate::scenario::publish_rect(&format!("range_track:{}:bars", track.key), bars); + let on_strip = |p: Pos2| p.y < strip.bottom() + 1.0; + let axis_of = |strip: bool, view: [f64; 2]| if strip { span } else { view }; + let x_of = |axis: [f64; 2], v: f64| inner.left() + ((v - axis[0]) / (axis[1] - axis[0])) as f32 * inner.width(); + let v_of = |axis: [f64; 2], x: f32| axis[0] + f64::from((x - inner.left()) / inner.width().max(1.0)) * (axis[1] - axis[0]); + let per_point = (view[1] - view[0]) / f64::from(inner.width().max(1.0)); + let reach = f64::from(REACH) * per_point; + let mods = ui.input(|i| i.modifiers); + let snap = |v: f64, fine: bool, snapped: &mut Option| { + let s = if fine { None } else { lone_change(track.changes, v, reach) }; + *snapped = s; + let v = s.unwrap_or(v); + if track.integer { v.round() } else { v } + }; + let grab_at = |strip: bool, x: f32, view: [f64; 2], range: [f64; 2]| { + let (axis, [a, b]) = (axis_of(strip, view), if strip { view } else { range }); + let (xa, xb) = (x_of(axis, a), x_of(axis, b)); + if (x - xa).abs().min((x - xb).abs()) <= REACH { + Some(if (x - xa).abs() < (x - xb).abs() { Grab::Low } else { Grab::High }) + } else if x > xa && x < xb { + Some(Grab::Band) + } else { + None + } + }; + + // Zoom and move the loupe. + if response.hovered() + && let Some(p) = response.hover_pos() + { + let (zoom, sideways, pinch) = crate::navigation::axis_wheel(&ctx, rect.height()); + if sideways != 0.0 { + let d = -f64::from(sideways) * per_point; + view = fit([view[0] + d, view[1] + d], span); + st.loupe = Some(view); + } + if zoom != 0.0 || pinch != 1.0 { + let k = (-f64::from(zoom) * ZOOM).exp() / f64::from(pinch); + let at = v_of(axis_of(on_strip(p), view), p.x).clamp(view[0], view[1]); + view = fit([at - (at - view[0]) * k, at + (view[1] - at) * k], span); + st.loupe = Some(view); + } + } + if response.drag_started() + && let Some(p) = ui.input(|i| i.pointer.press_origin()) + { + response.request_focus(); + let strip = on_strip(p); + let axis = axis_of(strip, view); + let v = v_of(axis, p.x); + let start = if strip { view } else { range }; + let grab = match grab_at(strip, p.x, view, range) { + Some(g) => g, + None if mods.shift => { + if (v - start[0]).abs() < (v - start[1]).abs() { + Grab::Low + } else { + Grab::High + } + } + None => Grab::New(if strip { v } else { snap(v, mods.alt, &mut st.snapped) }), + }; + if !strip { + st.last = match grab { + Grab::Low => Part::Low, + Grab::Band => Part::Band, + Grab::High | Grab::New(_) => Part::High, + }; + out.touched = true; + } + st.drag = Some(Drag { strip, grab, start, at: v, from: v, last_x: p.x }); + } + if response.dragged() + && let (Some(mut d), Some(p)) = (st.drag, response.interact_pointer_pos()) + { + let axis = if d.strip { span } else { view }; + let scale = (axis[1] - axis[0]) / f64::from(inner.width().max(1.0)); + d.at += f64::from(p.x - d.last_x) * scale * if mods.alt { FINE } else { 1.0 }; + d.last_x = p.x; + let mut snapped = None; + let mut put = |v: f64| if d.strip { v } else { snap(v.clamp(span[0], span[1]), mods.alt, &mut snapped) }; + let [a, b] = d.start; + let moved = match d.grab { + Grab::Band => { + let w = b - a; + let mut shift = d.at - d.from; + if !d.strip { + // The band snaps by whichever end lands on a change. + let (la, lb) = (put(a + shift) - (a + shift), put(b + shift) - (b + shift)); + shift += if la.abs() > 0.0 && (lb == 0.0 || la.abs() <= lb.abs()) { la } else { lb }; + } + let lo = (a + shift).clamp(span[0], span[1] - w); + [lo, lo + w] + } + Grab::New(anchor) => { + let v = put(d.at); + [anchor.min(v), anchor.max(v)] + } + Grab::Low | Grab::High => { + let v = put(d.at); + let other = if d.grab == Grab::Low { b } else { a }; + // An end dragged past the other becomes the other. + let low = v < other; + if !d.strip { + st.last = if low { Part::Low } else { Part::High }; + } + d.grab = if low { Grab::Low } else { Grab::High }; + d.start = if low { [a, other] } else { [other, b] }; + [v.min(other), v.max(other)] + } + }; + st.snapped = snapped; + if d.strip { + view = fit(moved, span); + st.loupe = Some(view); + } else { + range = moved; + out.touched = true; + } + st.drag = Some(d); + } + if response.drag_stopped() { + st.drag = None; + st.snapped = None; + } + if response.clicked() + && let Some(p) = response.interact_pointer_pos() + { + response.request_focus(); + let strip = on_strip(p); + let v = v_of(axis_of(strip, view), p.x); + if strip && grab_at(true, p.x, view, range).is_none() { + // A click beside the loupe brings it there. + let w = view[1] - view[0]; + view = fit([v - w / 2.0, v + w / 2.0], span); + st.loupe = Some(view); + } else if !strip && mods.shift && grab_at(false, p.x, view, range).is_none() { + let v = snap(v, mods.alt, &mut st.snapped); + let low = (v - range[0]).abs() < (v - range[1]).abs(); + range = if low { [v.min(range[1]), range[1]] } else { [range[0], v.max(range[0])] }; + st.last = if low { Part::Low } else { Part::High }; + out.touched = true; + } + } + if response.double_clicked() + && let Some(p) = response.interact_pointer_pos() + { + if on_strip(p) { + view = span; + st.loupe = None; + } else if grab_at(false, p.x, view, range) == Some(Grab::Band) { + let m = (range[1] - range[0]) * 0.08; + view = fit([range[0] - m, range[1] + m], span); + st.loupe = Some(view); + } else { + out.whole = true; + out.touched = true; + } + } + // The keyboard, while the track has it. + if response.has_focus() { + ui.memory_mut(|m| m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() })); + let (left, right, space) = ui.input_mut(|i| { + ( + i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft) || i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowLeft), + i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight) || i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowRight), + i.consume_key(egui::Modifiers::NONE, egui::Key::Space), + ) + }); + out.play = space; + if left || right { + let dir = if right { 1.0 } else { -1.0 }; + let step = |v: f64| { + let n = if mods.alt { None } else { next_change(track.changes, v, dir) }; + let v = n.unwrap_or(v + dir * per_point); + let v = if track.integer && n.is_none() { (v + dir * 0.5).round() } else { v }; + v.clamp(span[0], span[1]) + }; + range = match st.last { + Part::Low => [step(range[0]).min(range[1]), range[1]], + Part::High => [range[0], step(range[1]).max(range[0])], + Part::Band => { + let lead = if right { range[1] } else { range[0] }; + let w = range[1] - range[0]; + let lo = (range[0] + step(lead) - lead).clamp(span[0], span[1] - w); + [lo, lo + w] + } + }; + let moving = match st.last { + Part::Low => range[0], + Part::High => range[1], + Part::Band => { + if right { + range[1] + } else { + range[0] + } + } + }; + if moving < view[0] || moving > view[1] { + let w = view[1] - view[0]; + view = fit([moving - w / 2.0, moving + w / 2.0], span); + st.loupe = Some(view); + } + out.touched = true; + } + } + + // The pointer says what a press would take: an end, the band, or a new range beside them. + if let Some(p) = response.hover_pos().or_else(|| st.drag.and_then(|_| response.interact_pointer_pos())) { + let icon = match st.drag.map(|d| d.grab) { + Some(Grab::Band) => egui::CursorIcon::Grabbing, + Some(_) => egui::CursorIcon::ResizeHorizontal, + None => match grab_at(on_strip(p), p.x, view, range) { + Some(Grab::Band) => egui::CursorIcon::Grab, + Some(_) => egui::CursorIcon::ResizeHorizontal, + None if on_strip(p) => egui::CursorIcon::PointingHand, + None => egui::CursorIcon::Crosshair, + }, + }; + ctx.set_cursor_icon(icon); + } + + // The strip: the whole span, the range, and the loupe framed. + let painter = ui.painter_at(rect); + let empty = Bars::default(); + paint_bars(&painter, strip, span, track.overview.unwrap_or(&empty), t.control_fill, t.text_dim); + let band = |r: Rect, axis: [f64; 2], [a, b]: [f64; 2]| { + Rect::from_min_max(Pos2::new(x_of(axis, a).max(r.left()), r.top()), Pos2::new(x_of(axis, b).min(r.right()), r.bottom())) + }; + painter.rect_filled(band(strip, span, range), 0.0, t.form_primary.gamma_multiply(0.35)); + let frame = band(strip, span, view); + let shade = t.panel.gamma_multiply(0.7); + painter.rect_filled(Rect::from_min_max(strip.min, Pos2::new(frame.left(), strip.bottom())), 0.0, shade); + painter.rect_filled(Rect::from_min_max(Pos2::new(frame.right(), strip.top()), strip.max), 0.0, shade); + painter.rect_stroke(frame, 1.0, Stroke::new(1.5, t.text), egui::StrokeKind::Inside); + + // The ruler: steps of 1, 2 or 5 times a power of ten, at least 60 points apart. + let step = nice_step(60.0 * per_point); + let decimals = (-step.log10().floor()).clamp(0.0, 9.0) as usize; + let font = egui::FontId::proportional(t.font_micro); + let mut v = (view[0] / step).ceil() * step; + for _ in 0..64 { + if v > view[1] { + break; + } + let x = x_of(view, v); + painter.line_segment([Pos2::new(x, ruler.bottom() - 5.0), Pos2::new(x, ruler.bottom())], Stroke::new(1.0, t.border)); + painter.text(Pos2::new(x + 2.0, ruler.top()), egui::Align2::LEFT_TOP, format!("{v:.decimals$}"), font.clone(), t.text_dim); + v += step; + } + for c in lone_changes(track.changes, view, reach, 512) { + let x = x_of(view, c); + painter.line_segment([Pos2::new(x, ruler.bottom() - 3.0), Pos2::new(x, ruler.bottom() + 1.0)], Stroke::new(1.0, t.warning)); + } + + // The bars, what lies outside the range shaded, and the range's ends. + paint_bars(&painter, bars, view, track.loupe.unwrap_or(&empty), t.control_fill, t.text_dim); + let r = band(bars, view, range); + painter.rect_filled(Rect::from_min_max(bars.min, Pos2::new(r.left(), bars.bottom())), 0.0, shade); + painter.rect_filled(Rect::from_min_max(Pos2::new(r.right(), bars.top()), bars.max), 0.0, shade); + painter.rect_filled(r, 0.0, t.form_primary.gamma_multiply(0.18)); + for (v, part) in [(range[0], Part::Low), (range[1], Part::High)] { + if v < view[0] || v > view[1] { + continue; + } + let x = x_of(view, v); + let width = if response.has_focus() && st.last == part { 3.0 } else { 2.0 }; + painter.line_segment([Pos2::new(x, bars.top()), Pos2::new(x, bars.bottom())], Stroke::new(width, t.form_primary)); + painter.add(egui::Shape::convex_polygon( + vec![Pos2::new(x - 5.0, bars.top()), Pos2::new(x + 5.0, bars.top()), Pos2::new(x, bars.top() + 6.0)], + t.form_primary, + Stroke::NONE, + )); + } + if let (Some(s), Some(_)) = (st.snapped, st.drag) { + let x = x_of(view, s); + painter.line_segment([Pos2::new(x, bars.top()), Pos2::new(x, bars.bottom())], Stroke::new(1.0, t.warning)); + } + if response.has_focus() && st.last == Part::Band { + painter.rect_stroke(r, 0.0, Stroke::new(1.0, t.form_primary), egui::StrokeKind::Inside); + } + + // The ends and the length as numbers. + let decimals = if track.integer { 0 } else { (-(per_point.max(1e-12)).log10()).ceil().clamp(0.0, 6.0) as usize }; + let speed = if track.integer { 1.0 } else { per_point }; + ui.horizontal(|ui| { + let field = |ui: &mut Ui, v: &mut f64| ui_kit::track_number(ui, v, speed, decimals).changed(); + let (mut lo, mut hi) = (range[0], range[1]); + let mut length = hi - lo; + let changed_lo = field(ui, &mut lo); + ui.label("…"); + let changed_hi = field(ui, &mut hi); + ui.weak("↔"); + let changed_length = field(ui, &mut length); + let round = |v: f64| if track.integer { v.round() } else { v }; + if changed_lo { + range = [round(lo).min(range[1]), range[1]]; + st.last = Part::Low; + } else if changed_hi { + range = [range[0], round(hi).max(range[0])]; + st.last = Part::High; + } else if changed_length { + range = [range[0], range[0] + round(length).max(0.0)]; + st.last = Part::High; + } + if changed_lo || changed_hi || changed_length { + out.touched = true; + } + }); + + ctx.data_mut(|d| d.insert_temp(id(track.key), st)); + out.range = (range != track.range).then_some(range); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_change_snaps_only_when_it_stands_alone_at_this_zoom() { + let changes = [0.0, 10.0, 11.0, 30.0]; + assert_eq!(lone_change(&changes, 29.0, 2.0), Some(30.0)); + assert_eq!(lone_change(&changes, 10.4, 2.0), None, "10 and 11 are too close to tell apart"); + assert_eq!(lone_change(&changes, 10.4, 0.45), Some(10.0)); + assert_eq!(lone_changes(&changes, [0.0, 40.0], 2.0, 10), vec![0.0, 30.0]); + assert_eq!( + (next_change(&changes, 10.0, 1.0), next_change(&changes, 10.0, -1.0), next_change(&changes, 30.0, 1.0)), + (Some(11.0), Some(0.0), None) + ); + assert_eq!(nice_step(3.2), 5.0); + assert_eq!(nice_step(0.07), 0.1); + } +} diff --git a/crates/ui-egui/src/browser_cache.rs b/crates/ui-egui/src/browser_cache.rs index 50e2b96f4..b83b05817 100644 --- a/crates/ui-egui/src/browser_cache.rs +++ b/crates/ui-egui/src/browser_cache.rs @@ -25,24 +25,63 @@ pub(super) struct Node { pub folders: [Option; 3], } +/// A row of a folder or group: an item, or a group with its own rows. +pub(super) enum Row { + Item(Box), + Group(Group), +} + +impl Row { + pub fn count(&self) -> usize { + match self { + Row::Item(_) => 1, + Row::Group(g) => g.count, + } + } +} + pub(super) struct Group { pub id: u64, pub key: String, pub label: String, - pub items: Vec, + /// How many items it holds, groups inside it included. + pub count: usize, + pub rows: Vec, +} + +fn collect<'a>(rows: &'a [Row], out: &mut Vec<&'a Entry>) { + for r in rows { + match r { + Row::Item(e) => out.push(e), + Row::Group(g) => collect(&g.rows, out), + } + } +} + +impl Group { + /// Everything in the group, groups inside it included, in display order. + pub fn entries(&self) -> Vec<&Entry> { + let mut all = Vec::new(); + collect(&self.rows, &mut all); + all + } } #[derive(Default)] pub(super) struct Folder { pub key: String, - pub groups: Vec, - pub loose: Vec, - pub loose_keys: Vec, + pub rows: Vec, + /// The top-level rows as drawn: the order a drop among them keeps. + pub top_order: Vec, + /// How many items the folder holds, groups included. + pub count: usize, } impl Folder { pub fn entries(&self) -> impl Iterator { - self.groups.iter().flat_map(|g| &g.items).chain(&self.loose) + let mut all = Vec::new(); + collect(&self.rows, &mut all); + all.into_iter() } } @@ -166,7 +205,15 @@ impl Cache { "sketches" => &model.sketches, _ => &model.planes, }; - let Some(indices) = indices.get(&component) else { return Folder::default() }; + // A folder that holds only groups (a New Group made before anything is in it) is still + // drawn, or the group can't be seen or filled (#10526). + let grouped = doc.browser_groups.iter().any(|g| g.component == component && g.folder == folder); + let none = Vec::new(); + let indices = match indices.get(&component) { + Some(indices) => indices, + None if grouped => &none, + None => return Folder::default(), + }; let mut all = Vec::with_capacity(indices.len()); for i in indices { let entry = match folder { @@ -187,19 +234,18 @@ impl Cache { all.push(entry); } } - if all.is_empty() { + if all.is_empty() && !grouped { return Folder::default(); } - let (groups, loose) = arrange(&doc, component, folder, all); - let loose_keys = loose.iter().map(|e| e.key.clone()).collect(); - let groups = groups - .into_iter() - .map(|(group, items)| { - let key = format!("{prefix}/g{}", group.id); - let label = format!("{} ({})", group.name, items.len()); - Group { id: group.id, key, label, items } + let rows = arrange(&doc, component, folder, &prefix, all); + let top_order = rows + .iter() + .map(|r| match r { + Row::Item(e) => solidcraft_engine::doc::BrowserEntry::item(&e.key), + Row::Group(g) => solidcraft_engine::doc::BrowserEntry::Group(g.id), }) .collect(); - Folder { key: format!("{prefix}/{folder}"), groups, loose, loose_keys } + let count = rows.iter().map(Row::count).sum(); + Folder { key: format!("{prefix}/{folder}"), rows, top_order, count } } } diff --git a/crates/ui-egui/src/browser_canvas.rs b/crates/ui-egui/src/browser_canvas.rs index dc1c28114..20a3963f4 100644 --- a/crates/ui-egui/src/browser_canvas.rs +++ b/crates/ui-egui/src/browser_canvas.rs @@ -4,8 +4,9 @@ use egui::{Pos2, Stroke, vec2}; use serde_json::{Value, json}; +use solidcore_record::Vec2; use solidcraft_engine::doc::canvas::Canvas; -use solidcraft_engine::geom::Vec2; +use solidcraft_engine::geom::prelude::*; use crate::SolveApp; use crate::browser::panel_pos; @@ -170,6 +171,7 @@ fn on_image(c: &Canvas, p: Vec2) -> bool { #[cfg(test)] mod tests { use serde_json::json; + use solidcraft_engine::geom::prelude::*; fn canvas(h: &mut crate::scenario::Harness) -> u64 { let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); @@ -183,6 +185,7 @@ mod tests { #[test] fn edit_canvas_is_a_card_whose_close_keeps_the_live_edits() { let mut h = crate::scenario::Harness::new(); + h.app.preferences.language = "en".into(); h.app.home.open = false; let id = canvas(&mut h); h.app.tree.canvas_panel = Some(crate::browser::CanvasPanel::new(&h.app, id, false)); @@ -235,8 +238,8 @@ mod tests { let plane = h.app.session.doc.canvas_plane(&vals, &c).unwrap(); let ax = c.center.x - 20.0; let bx = c.center.x + 20.0; - let sa = proj.to_screen(plane.to_world(solidcraft_engine::geom::Vec2::new(ax, c.center.y))).expect("point A on screen"); - let sb = proj.to_screen(plane.to_world(solidcraft_engine::geom::Vec2::new(bx, c.center.y))).expect("point B on screen"); + let sa = proj.to_screen(plane.to_world(solidcore_record::Vec2::new(ax, c.center.y))).expect("point A on screen"); + let sb = proj.to_screen(plane.to_world(solidcore_record::Vec2::new(bx, c.center.y))).expect("point B on screen"); assert!(super::click(&mut h.app, &proj, sa), "first click sets A"); let panel = h.app.tree.canvas_panel.as_ref().unwrap(); assert_eq!(panel.next, 1); @@ -246,7 +249,7 @@ mod tests { assert_eq!(panel.next, 0); assert!((panel.b[0] - bx).abs() < 0.5, "{:?}", panel.b); let before = panel.a; - let miss = plane.to_world(solidcraft_engine::geom::Vec2::new(c.center.x + 500.0, c.center.y)); + let miss = plane.to_world(solidcore_record::Vec2::new(c.center.x + 500.0, c.center.y)); if let Some(sm) = proj.to_screen(miss) { assert!(!super::click(&mut h.app, &proj, sm)); assert_eq!(h.app.tree.canvas_panel.as_ref().unwrap().a, before); diff --git a/crates/ui-egui/src/browser_card_tests.rs b/crates/ui-egui/src/browser_card_tests.rs index 6114065d6..ae5df4d43 100644 --- a/crates/ui-egui/src/browser_card_tests.rs +++ b/crates/ui-egui/src/browser_card_tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::scenario::{Harness, handle_at, rect_of}; +use crate::semantic_content::{self, ContentOwner, ContentRequest}; use crate::shell::{LayoutMode, SHELL_GAP}; #[test] @@ -43,6 +44,96 @@ fn clicked_browser_folders_toggle_visibility_with_v() { } } +/// #10526: New Group from the root's context menu in a design with no bodies yet makes a group +/// the Browser shows, and a body made later can be dropped into it. +#[test] +fn a_new_group_in_a_folder_with_nothing_in_it_yet_shows() { + let mut h = Harness::new(); + h.app.home.open = false; + h.settle(); + assert!(handle_at("row:Bodies").is_none(), "no bodies, no Bodies folder"); + // What the root's New Group item runs. + group_action(&mut h.app, "ui.newGroup", &json!({"component": 0})); + h.settle(); + let group = h.app.session.doc.browser_groups.first().map(|g| (g.id, g.name.clone())).expect("New Group makes a group"); + assert!(handle_at(&format!("row:{} (0)", group.1)).is_some(), "the new group shows in the Browser"); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"operation":"new_body","body_name":"One"})).unwrap(); + h.settle(); + h.step(&json!({"drag":[{"handle":"row:One"},{"handle":format!("row:{} (0)", group.1)}]})).unwrap(); + h.settle(); + let items = h.app.session.doc.browser_group(group.0).map(|g| g.items.len()).unwrap_or(0); + assert_eq!(items, 1, "the body went into the group"); +} + +/// #10005: F2 on a group picked in the Browser opens its Rename box, as for other rows, and the +/// typed name renames the group, at the top level and inside a component; a body selected +/// alongside does not take the rename from the clicked group. +#[test] +fn f2_on_a_clicked_browser_group_renames_the_group() { + for inside_component in [false, true] { + let (mut h, component) = if inside_component { + let (h, component, _) = crate::test_support::component_box(); + (h, component) + } else { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Body1"})).unwrap(); + (h, 0) + }; + // The group's row sits inside a placement, which starts closed (#9274). + h.app.preferences.browser_components_open = true; + let body = h.app.session.model.state().bodies[0].name.clone(); + let group = h.app.run("browser.group", json!({"component":component,"folder":"bodies","items":[body],"name":"Group"})).unwrap()["group"] + .as_u64() + .unwrap(); + h.app.preferences.browser_bodies_folders = crate::prefs::BodiesFolders::Always; + h.settle(); + let world_body = crate::open_meshing::session_world(&h.app.session).bodies[0].name.clone(); + h.app.run("select.set", json!({"items":[Sel::Body { name: world_body.clone() }]})).unwrap(); + h.step(&json!({"click":{"handle":"row:Group (1)"}})).unwrap(); + h.step(&json!({"key":"F2"})).unwrap(); + h.frames(2); + let what = h.app.menu.rename.as_ref().map(|r| (r.what.clone(), r.text.clone())); + assert_eq!( + what, + Some((crate::context_menu::RenameWhat::Group(group), "Group".to_string())), + "component {inside_component}: F2 renames the group" + ); + h.step(&json!({"text":"Fasteners"})).unwrap(); + h.frames(1); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(2); + assert!(h.app.menu.rename.is_none()); + let names: Vec<&str> = h.app.session.doc.browser_groups.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Fasteners"], "component {inside_component}: Enter renames the group; status {:?}", h.app.status); + assert!(crate::open_meshing::session_world(&h.app.session).body(&world_body).is_some(), "the body keeps its name"); + } +} + +/// #10654: a refused inline rename keeps the editor open and says why, instead of closing +/// silently and leaving the old name. +#[test] +fn a_refused_inline_rename_keeps_the_editor_and_shows_the_error() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"A"})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"B"})).unwrap(); + h.app.preferences.browser_bodies_folders = crate::prefs::BodiesFolders::Always; + h.settle(); + h.app.menu.rename = Some(crate::context_menu::Rename { + what: crate::context_menu::RenameWhat::Body("B".into()), + text: "A".into(), + at: egui::Pos2::ZERO, + focused: true, + inline: true, + }); + h.frames(2); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(2); + assert!(h.app.menu.rename.is_some(), "the editor stays open after a refused rename"); + let (text, _, error) = h.app.status.clone().expect("the refusal is shown"); + assert!(error && text.contains("another body is called"), "{text}"); + assert!(h.app.session.world_state().unwrap().body("B").is_some(), "the body keeps its name"); +} + #[test] fn folder_visibility_target_clears_when_the_user_moves_on() { for action in ["body click", "selection command", "empty click", "escape", "design tab", "model edit", "tool"] { @@ -268,7 +359,7 @@ fn card_and_column_keep_body_eyes_menus_and_group_drops() { h.step(&json!({"drag":[{"handle":"row:Two"},{"handle":"row:Group (1)"}]})).unwrap(); h.settle(); let group = h.app.session.doc.browser_groups.iter().find(|g| g.id == group).unwrap(); - assert!(group.items.iter().any(|name| name == "Two"), "body drop into the folder failed in {mode:?}"); + assert!(group.has_item("Two"), "body drop into the folder failed in {mode:?}"); } } @@ -634,10 +725,10 @@ fn collapsed_rail_shares_header_hover_inset_and_expands_from_its_whole_card() { /// #6907: a mesh body's row has its own icon and tooltip, so it can be told from a solid one. #[test] fn mesh_and_solid_body_rows_have_different_icons_and_tooltips() { + use solidcore_record::Vec3; use solidcraft_engine::doc::{Document, FeatureKind, MeshData}; - use solidcraft_engine::geom::Vec3; let solid = solidcraft_engine::kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap(); - let mesh = solid.tessellate(0.01).unwrap(); + let mesh = solid.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(0.01)).unwrap(); let mut doc = Document::default(); doc.add_feature( FeatureKind::MeshImport { @@ -680,7 +771,7 @@ fn browser_occurrence_clicks_fill_align_components_input() { h.app.start("solid.align"); { let d = h.app.dialog.as_mut().unwrap(); - d.kind = crate::dialogs::Kind::Align { flip: false, components: true }; + d.kind = crate::dialogs::Kind::Align { flip: false, components: true, axes: [true; 3], angle: String::new() }; d.inputs[0].label = "Components"; d.active = 0; } @@ -696,3 +787,1416 @@ fn browser_occurrence_clicks_fill_align_components_input() { h.step(&json!({"click": {"handle": &handle}})).unwrap(); assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty()); } + +/// #8718: the eyes form one column at the rows' right end, right of each name and radio at every +/// depth, and a click on one hides without activating; the preference puts them back by the fold arrow. +#[test] +fn row_eyes_line_up_at_the_right_end_unless_the_preference_keeps_them_left() { + let mut h = Harness::new(); + // These rows are read with every placement open, as placements started before #9274. + h.app.preferences.browser_components_open = true; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Top"})).unwrap(); + let part = h.app.run("component.create", json!({"name":"Part"})).unwrap()["occurrence"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"corner":[20,0,0],"body_name":"Inner"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + h.settle(); + let placement = format!("occurrence:{part}"); + let eye = |name: &str| handle_at(&format!("eye:{name}")).unwrap_or_else(|| panic!("eye:{name}")); + let label = |name: &str| rect_of(&format!("row_label:{name}")).unwrap_or_else(|| panic!("row_label:{name}")); + let activate = || handle_at(&format!("activate:{placement}")).unwrap(); + let card = rect_of("browser:card").unwrap(); + let column = eye(&placement).x; + for name in ["Bodies", "Top", "Inner", placement.as_str()] { + assert!((eye(name).x - column).abs() < 0.5, "{name}: {} is off the column at {column}", eye(name).x); + } + for name in ["Bodies", "Top", "Inner"] { + assert!(eye(name).x > label(name).right(), "{name}: the eye is right of the name"); + } + assert!(column > activate().x + 40.0 && column > card.right() - 40.0, "the eye sits at the row's end, apart from the radio"); + assert!(eye("Inner").y > eye(&placement).y + 10.0, "the body sits under its placement"); + let indent = |name: &str| handle_at(&format!("indent:{name}")).unwrap_or_else(|| panic!("indent:{name}")).x; + assert!((indent("Inner") - indent("Part:1") - super::INDENT).abs() < 0.5, "one level deeper, one indent further right"); + assert!((label("Inner").left() - label("Top").left()).abs() < 0.5, "bodies at one depth start their names together"); + // Its tip shows by the eye, not under the name. + h.step(&json!({"move":{"handle":"eye:Top"}})).unwrap(); + h.frames(60); + h.frame(); + let mut tip = None; + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |s| { + if let egui::Shape::Text(t) = s + && t.galley.text() == "Hide" + { + tip = Some(t.pos.x + t.galley.rect.center().x); + } + }); + } + let tip = tip.expect("the eye's Hide tip"); + assert!(tip > label("Top").right(), "the tip at {tip} is by the eye at {}", eye("Top").x); + + // Between the fold arrow and the radio, a click neither folds nor activates. + let (fold, radio) = (handle_at(&format!("fold:{placement}")).unwrap(), activate()); + assert!(radio.x - fold.x >= 24.0, "the radio keeps clear of the fold arrow: {fold:?} {radio:?}"); + for dx in [11.0, 14.0] { + h.frames(40); + h.step(&json!({"click":[fold.x + dx, fold.y]})).unwrap(); + h.settle(); + assert!(handle_at("indent:Inner").is_some(), "{dx}: the placement stays open"); + assert_eq!(h.app.session.active_component, 0, "{dx}: nothing is activated"); + } + h.frames(40); + h.step(&json!({"click":{"handle":format!("eye:{placement}")}})).unwrap(); + assert!(h.app.session.occurrence_hidden(&[part]), "the placement's eye hides it"); + h.step(&json!({"click":{"handle":"eye:Top"}})).unwrap(); + assert!(h.app.session.visibility.hidden_bodies.iter().any(|b| b == "Top"), "the body's eye hides it"); + assert_eq!(h.app.session.active_component, 0, "an eye click activates nothing"); + assert!(h.app.session.active_occurrence_path.is_none()); + + h.call("ui.prefs", json!({"browser_eye_left": true})); + h.settle(); + assert!(eye("Top").x < label("Top").left() && eye(&placement).x < activate().x, "beside the fold arrow, as before"); + assert!((eye("Inner").x - eye(&placement).x - super::INDENT).abs() < 0.5, "one level deeper, one indent further right"); + h.step(&json!({"click":{"handle":"eye:Top"}})).unwrap(); + assert!(!h.app.session.visibility.hidden_bodies.iter().any(|b| b == "Top"), "the eye still shows it"); + assert_eq!(h.app.session.active_component, 0); +} + +/// #8718: with the rows overflowing the card, an eye at the rows' end stays clear of the scroll +/// bar laid over them: a click on it hides the sketch and scrolls nothing. +#[test] +fn an_eye_at_the_row_end_takes_its_click_from_the_scroll_bar() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + for i in 0..35 { + h.app.run("sketch.create", json!({"plane":"XY", "name":format!("Sketch{i}")})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + } + h.settle(); + assert!(handle_at("row:Sketch34").is_none(), "the rows overflow the card"); + let card = rect_of("browser:card").unwrap(); + let eye = handle_at("eye:Sketch3").unwrap(); + let row = handle_at("row:Sketch3").unwrap(); + let bar = h.ctx.global_style().spacing.scroll.bar_width; + let row_rect = drawn_rows().into_iter().find(|r| r.0 == "Sketch3").unwrap().1; + assert!(card.contains_rect(row_rect)); + let half = (Tokens::get().space_16 + Tokens::get().space_3) / 2.0; + assert!(eye.x + half <= row_rect.right() - bar, "the eye at {} is left of the bar along {}", eye.x, row_rect.right()); + // The bar widens under the pointer before the click. + h.step(&json!({"move":[row_rect.right() - 3.0, eye.y]})).unwrap(); + h.frames(30); + // The eye's edge nearest the bar. + h.step(&json!({"click":[eye.x + half - 1.0, eye.y]})).unwrap(); + h.settle(); + assert_eq!(h.app.session.visibility.hidden_sketches.len(), 1, "the eye hides its sketch"); + assert_eq!(handle_at("row:Sketch3"), Some(row), "the list did not scroll"); +} + +/// Dragging a group's row onto the middle of another group's row nests it; onto the top of a row +/// puts it before that group. A group cannot be dropped into one of its own groups. +#[test] +fn a_group_dragged_onto_another_group_nests_in_it_or_goes_before_it() { + let mut h = Harness::new(); + let ids: Vec = ["Alpha", "Beta", "Gamma"] + .into_iter() + .enumerate() + .map(|(i, name)| { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"corner":[i as f64 * 20.0,0,0],"body_name":name})).unwrap(); + h.app.run("browser.group", json!({"component":0,"folder":"bodies","items":[name],"name":name})).unwrap()["group"].as_u64().unwrap() + }) + .collect(); + let (alpha, beta, gamma) = (ids[0], ids[1], ids[2]); + h.settle(); + let drag = |h: &mut Harness, from: &str, to: &str, dy: f32| { + let (from, to) = (handle_at(from).unwrap(), handle_at(to).unwrap()); + assert_eq!(h.call("ui.drag", json!({"x0":from.x,"y0":from.y,"x1":to.x,"y1":to.y + dy,"steps":12}))["ok"], true); + h.settle(); + }; + let parent = |h: &Harness, id: u64| h.app.session.doc.browser_group(id).unwrap().parent; + drag(&mut h, "row:Alpha (1)", "row:Beta (1)", 0.0); + assert_eq!(parent(&h, alpha), Some(beta)); + drag(&mut h, "row:Beta (2)", "row:Alpha (1)", 0.0); + assert_eq!(parent(&h, beta), None, "a group does not go into its own group"); + drag(&mut h, "row:Gamma (1)", "row:Beta (2)", -10.0); + assert_eq!(h.app.session.doc.ordered_entries(0, "bodies", None), [BrowserEntry::Group(gamma), BrowserEntry::Group(beta)]); +} + +/// Three bodies with their eyes in the Browser, the first one's eye hidden or shown per the test. +fn three_bodies(h: &mut Harness) { + for (name, x) in [("One", 0), ("Two", 20), ("Three", 40)] { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"corner":[x,0,0],"operation":"new_body","body_name":name})).unwrap(); + } + h.settle(); +} + +fn body_hidden(h: &Harness, name: &str) -> bool { + h.app.session.visibility.hidden_bodies.iter().any(|b| b == name) +} + +/// #9680: a press on an eye that drags over other eyes sets each eye it passes to the first eye's +/// new state, and the whole drag is one undo step. +#[test] +fn eye_drag_sets_every_eye_it_passes_in_one_undo_step() { + for eye_left in [false, true] { + let mut h = Harness::new(); + three_bodies(&mut h); + if eye_left { + h.call("ui.prefs", json!({"browser_eye_left": true})); + h.settle(); + } + let undo = h.app.session.undo.len(); + h.step(&json!({"drag":[{"handle":"eye:One"},{"handle":"eye:Three"}],"steps":40})).unwrap(); + h.settle(); + for name in ["One", "Two", "Three"] { + assert!(body_hidden(&h, name), "eye_left {eye_left}: {name} is hidden by the drag"); + } + assert_eq!(h.app.session.undo.len(), undo + 1, "eye_left {eye_left}: the drag is one undo step"); + h.app.run("edit.undo", json!({})).unwrap(); + for name in ["One", "Two", "Three"] { + assert!(!body_hidden(&h, name), "eye_left {eye_left}: one undo shows {name} again"); + } + } +} + +/// #9680: an eye already in the target state stays as it is: a drag from a shown eye over a hidden +/// one hides both, and undo brings back the hidden one as it was. +#[test] +fn eye_drag_leaves_an_eye_already_in_the_target_state_alone() { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.run("browser.visibility", json!({"items":["Two"],"visible":false})).unwrap(); + h.settle(); + h.step(&json!({"drag":[{"handle":"eye:One"},{"handle":"eye:Three"}],"steps":40})).unwrap(); + h.settle(); + for name in ["One", "Two", "Three"] { + assert!(body_hidden(&h, name), "{name} is hidden: the hidden eye is not flipped back"); + } + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!body_hidden(&h, "One") && !body_hidden(&h, "Three"), "undo shows the two the drag hid"); + assert!(body_hidden(&h, "Two"), "undo keeps the eye hidden before the drag"); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!body_hidden(&h, "Two"), "the hide before the drag is its own undo step"); +} + +/// #9680: a plain click on an eye still toggles that one row, as one undo step. +#[test] +fn a_plain_eye_click_still_toggles_one_row_as_one_undo_step() { + let mut h = Harness::new(); + three_bodies(&mut h); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"eye:Two"}})).unwrap(); + h.settle(); + assert!(body_hidden(&h, "Two") && !body_hidden(&h, "One") && !body_hidden(&h, "Three"), "only Two is hidden"); + assert_eq!(h.app.session.undo.len(), undo + 1, "the click is one undo step"); +} + +/// #9680: a drag over the eyes that rests near the rows' bottom edge scrolls them, and the eyes +/// the rows bring under the pointer take the drag's state too. +#[test] +fn eye_drag_near_the_rows_bottom_edge_scrolls_them() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + for i in 0..35 { + h.app.run("sketch.create", json!({"plane":"XY", "name":format!("Sketch{i}")})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + } + h.settle(); + assert!(handle_at("row:Sketch34").is_none(), "the rows overflow the card"); + let card = rect_of("browser:card").unwrap(); + let eye = handle_at("eye:Sketch0").unwrap(); + h.call("ui.drag", json!({"x0": eye.x, "y0": eye.y, "x1": eye.x, "y1": card.bottom() - 10.0, "steps": 20, "hold_end": 240})); + h.settle(); + assert!(handle_at("row:Sketch34").is_some(), "the drag scrolled the list down to its last row"); + assert!(h.app.session.visibility.hidden_sketches.len() > 10, "the eyes the drag reached are hidden"); +} + +/// #9680: a drag from the Origin's eye over the plane eyes is one undo step of its own, and the show +/// before it stays a step: one undo takes back only the drag. The Origin's eye is not an undo step (a +/// click on it is not either), so that one undo leaves it as the drag set it. +#[test] +fn eye_drag_from_the_origin_is_its_own_undo_step_and_leaves_an_earlier_show_alone() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"One"})).unwrap(); + h.app.run("browser.visibility", json!({"items":["One"],"visible":false})).unwrap(); + h.app.run("browser.visibility", json!({"items":["One"],"visible":true})).unwrap(); + h.app.run("browser.expand_all", json!({})).unwrap(); + h.settle(); + let undo = h.app.session.undo.len(); + h.step(&json!({"drag":[{"handle":"eye:Origin"},{"handle":"eye:YZ"}],"steps":40})).unwrap(); + h.settle(); + let origin_hidden = |h: &Harness| h.app.session.visibility.origin_hidden == Some(true); + assert!(origin_hidden(&h) && h.app.session.visibility.hidden_origin.iter().any(|k| k == "YZ"), "the drag hid the Origin and its planes"); + assert_eq!(h.app.session.undo.len(), undo + 1, "the drag is one undo step"); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!body_hidden(&h, "One"), "one undo takes back only the drag: the show before it stays"); + assert!(h.app.session.visibility.hidden_origin.is_empty(), "the planes the drag hid are shown again"); + assert!(origin_hidden(&h), "the Origin's eye is not an undo step: it keeps what the drag set"); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(body_hidden(&h, "One"), "the show is its own undo step: undoing it hides One again"); +} + +/// #9953: hiding or showing a sketch or body dynamically dims/undims the row without needing a full row rebuild. +#[test] +fn hiding_or_showing_body_or_sketch_updates_row_dimming() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"One"})).unwrap(); + h.app.run("browser.expand_all", json!({})).unwrap(); + h.settle(); + + // Toggle body hidden via eye click + h.step(&json!({"click":{"handle":"eye:One"}})).unwrap(); + h.settle(); + assert!(body_hidden(&h, "One")); + + // Toggle body shown again via eye click + h.step(&json!({"click":{"handle":"eye:One"}})).unwrap(); + h.settle(); + assert!(!body_hidden(&h, "One")); +} + +/// Draw content without either panel host. Changing submission order does not change IDs, +/// screen placement or the input stream, so these exercise the adapters' shared boundary. +fn semantic_frame(h: &mut Harness, owners: &[ContentOwner], events: Vec, modifiers: egui::Modifiers) { + semantic_frame_switch(h, owners, events, modifiers, None); +} + +fn semantic_frame_switch(h: &mut Harness, owners: &[ContentOwner], events: Vec, modifiers: egui::Modifiers, tab: Option) { + semantic_frame_transitions(h, owners, events, modifiers, tab, None); +} + +fn semantic_frame_transitions( + h: &mut Harness, + owners: &[ContentOwner], + events: Vec, + modifiers: egui::Modifiers, + tab: Option, + after_content: Option, +) { + let raw = egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(900.0, 900.0))), + focused: true, + events: std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(), + ..Default::default() + }; + h.ctx + .run_ui(raw, |ui| { + crate::scenario::clear_handles(); + publish_row_prefs(&h.app, ui.ctx()); + eye_drag_frame(&mut h.app, ui.ctx()); + semantic_content::begin(&mut h.app, ui.ctx()); + if let Some(tab) = tab { + crate::documents::switch(&mut h.app, tab); + } + for &owner in owners { + let x = if owner == ContentOwner::BROWSER { 10.0 } else { 450.0 }; + let mut content = ui.new_child( + egui::UiBuilder::new().id_salt(("semantic-test", owner)).max_rect(Rect::from_min_size(pos2(x, 10.0), vec2(400.0, 850.0))), + ); + let request = if owner == ContentOwner::HISTORY { + ContentRequest::ActiveBodiesOrigin + } else { + ContentRequest::Browser { shrink_height: false } + }; + semantic_content::show(&mut h.app, &mut content, owner, request); + } + if let Some(tab) = after_content { + crate::documents::switch(&mut h.app, tab); + } + semantic_content::finalize(&mut h.app, ui.ctx()); + // App paths may converge after an early return; finalization must be idempotent. + semantic_content::finalize(&mut h.app, ui.ctx()); + if ui.ctx().data_mut(|data| data.remove_temp::(egui::Id::new("semantic-test-discard"))).unwrap_or(false) { + ui.ctx().request_discard("repeat semantic layout after input"); + } + }) + .textures_delta + .clear(); +} + +fn semantic_at(owner: ContentOwner, label: &str) -> Pos2 { + semantic_content::output(owner).rows.into_iter().find(|(name, ..)| name == label).unwrap().1.center() +} + +fn semantic_control(owner: ContentOwner, handle: &str) -> Pos2 { + let rows = semantic_content::output(owner).rows; + crate::scenario::handles(handle) + .into_iter() + .find(|(name, point)| name == handle && rows.iter().any(|(_, rect, ..)| rect.contains(*point))) + .unwrap() + .1 +} + +fn semantic_button(at: Pos2, button: egui::PointerButton, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::PointerButton { pos: at, button, pressed, modifiers } +} + +fn semantic_click(h: &mut Harness, owners: &[ContentOwner], at: Pos2, modifiers: egui::Modifiers) { + semantic_frame(h, owners, vec![egui::Event::PointerMoved(at)], modifiers); + semantic_frame(h, owners, vec![semantic_button(at, egui::PointerButton::Primary, true, modifiers)], modifiers); + semantic_frame(h, owners, vec![semantic_button(at, egui::PointerButton::Primary, false, modifiers)], modifiers); +} + +#[test] +fn history_bodies_and_origin_work_with_browser_hidden() { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.ui.show_browser = false; + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = 260.0; + h.app.preferences.timeline_origin_bodies = true; + h.app.tree.expanded.insert("origin".into()); + h.frames(4); + assert!(drawn_rows().is_empty() && drawn_occurrences().is_empty()); + let body = semantic_at(ContentOwner::HISTORY, "One"); + h.step(&json!({"move":[body.x, body.y]})).unwrap(); + assert_eq!(h.app.viewport.hover_bodies, ["One"]); + h.step(&json!({"click":[body.x, body.y]})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "One".into() }]); + let eye = semantic_control(ContentOwner::HISTORY, "eye:One"); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":[eye.x, eye.y]})).unwrap(); + assert!(body_hidden(&h, "One")); + assert_eq!(h.app.session.undo.len(), undo + 1); + let plane = semantic_at(ContentOwner::HISTORY, "XY"); + h.step(&json!({"move":[plane.x, plane.y]})).unwrap(); + assert_eq!(h.app.viewport.hover_plane.as_deref(), Some("XY")); + h.step(&json!({"click":[plane.x, plane.y]})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Plane { name: "XY".into() }]); + h.step(&json!({"click":[plane.x, plane.y],"button":"right"})).unwrap(); + assert_eq!(h.app.menu.target, Target::OriginPlane { name: "XY".into() }); + crate::context_menu::close(&mut h.app); + h.frames(2); + let body = semantic_at(ContentOwner::HISTORY, "Two"); + h.step(&json!({"click":[body.x, body.y],"button":"right"})).unwrap(); + assert_eq!(h.app.menu.target, Target::Body { name: "Two".into() }); + crate::context_menu::close(&mut h.app); + h.app.run("select.clear", json!({})).unwrap(); + h.app.start("solid.combine"); + h.frames(2); + for name in ["One", "Two"] { + let body = semantic_at(ContentOwner::HISTORY, name); + h.step(&json!({"click":[body.x, body.y]})).unwrap(); + } + let dialog = h.app.dialog.as_ref().unwrap(); + assert_eq!(dialog.inputs[0].items, [Sel::Body { name: "One".into() }]); + assert_eq!(dialog.inputs[1].items, [Sel::Body { name: "Two".into() }]); + assert!(h.app.session.selection.is_empty(), "tool picks do not leak into document selection"); +} + +#[test] +fn semantic_owner_submission_order_preserves_hover_selection_picks_and_single_visibility_command() { + for owners in [[ContentOwner::BROWSER, ContentOwner::HISTORY], [ContentOwner::HISTORY, ContentOwner::BROWSER]] { + for owner in [ContentOwner::BROWSER, ContentOwner::HISTORY] { + let mut h = Harness::new(); + three_bodies(&mut h); + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let body = semantic_at(owner, "One"); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(body)], egui::Modifiers::NONE); + assert_eq!(h.app.viewport.hover_bodies, ["One"], "{owners:?}, {owner:?}"); + let ctrl = egui::Modifiers { ctrl: true, ..Default::default() }; + semantic_click(&mut h, &owners, body, ctrl); + assert_eq!(h.app.session.selection, [Sel::Body { name: "One".into() }], "Ctrl must toggle exactly once"); + let eye = semantic_control(owner, "eye:Two"); + let undo = h.app.session.undo.len(); + semantic_click(&mut h, &owners, eye, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + 1, "visibility command runs once"); + assert!(body_hidden(&h, "Two")); + h.app.run("select.clear", json!({})).unwrap(); + h.app.start("solid.combine"); + for name in ["One", "Three"] { + let body = semantic_at(owner, name); + semantic_click(&mut h, &owners, body, egui::Modifiers::NONE); + } + let dialog = h.app.dialog.as_ref().unwrap(); + assert_eq!(dialog.inputs[0].items, [Sel::Body { name: "One".into() }]); + assert_eq!(dialog.inputs[1].items, [Sel::Body { name: "Three".into() }]); + assert!(h.app.session.selection.is_empty()); + } + } +} + +#[test] +fn absent_semantic_owners_expire_geometry_and_hover_without_losing_selection_or_folds() { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.tree.expanded.insert("origin".into()); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let body = semantic_at(ContentOwner::HISTORY, "One"); + semantic_click(&mut h, &owners, body, egui::Modifiers::NONE); + assert_eq!(h.app.viewport.hover_bodies, ["One"]); + let selected = h.app.session.selection.clone(); + let folds = (h.app.tree.collapsed.clone(), h.app.tree.expanded.clone()); + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert!(h.app.viewport.hover_bodies.is_empty() && h.app.viewport.hover_plane.is_none()); + for owner in owners { + let output = semantic_content::output(owner); + assert!(output.rows.is_empty() && output.occurrences.is_empty()); + } + assert_eq!(h.app.session.selection, selected); + assert_eq!((h.app.tree.collapsed.clone(), h.app.tree.expanded.clone()), folds); + // Unrelated viewport contributors must survive frames with no semantic presentations. + h.app.viewport.hover_bodies = vec!["external contributor".into()]; + h.app.viewport.hover_plane = Some("external plane".into()); + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert_eq!(h.app.viewport.hover_bodies, ["external contributor"]); + assert_eq!(h.app.viewport.hover_plane.as_deref(), Some("external plane")); + // Egui hit-tests the previous pass: register the reappearing rows before moving to one. + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + let body = semantic_at(ContentOwner::HISTORY, "One"); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(body)], egui::Modifiers::NONE); + assert!( + h.app.viewport.hover_bodies.contains(&"external contributor".into()) && h.app.viewport.hover_bodies.contains(&"One".into()), + "hover contributors: {:?}", + h.app.viewport.hover_bodies + ); + let plane = semantic_at(ContentOwner::HISTORY, "XY"); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(plane)], egui::Modifiers::NONE); + assert_eq!(h.app.viewport.hover_plane.as_deref(), Some("XY")); + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert_eq!(h.app.viewport.hover_bodies, ["external contributor"]); + assert_eq!(h.app.viewport.hover_plane.as_deref(), Some("external plane")); +} + +#[test] +fn semantic_shift_and_ctrl_ranges_use_each_owners_anchor_and_complete_previous_order() { + for owners in [[ContentOwner::BROWSER, ContentOwner::HISTORY], [ContentOwner::HISTORY, ContentOwner::BROWSER]] { + for (owner, other) in [(ContentOwner::BROWSER, ContentOwner::HISTORY), (ContentOwner::HISTORY, ContentOwner::BROWSER)] { + let mut h = Harness::new(); + three_bodies(&mut h); + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let first = semantic_at(owner, "One"); + semantic_click(&mut h, &owners, first, egui::Modifiers::NONE); + let unrelated = semantic_at(other, "Three"); + semantic_click(&mut h, &owners, unrelated, egui::Modifiers::NONE); + let middle = semantic_at(owner, "Two"); + semantic_click(&mut h, &owners, middle, egui::Modifiers { shift: true, ..Default::default() }); + assert_eq!(h.app.session.selection, [Sel::Body { name: "One".into() }, Sel::Body { name: "Two".into() }]); + // Start below the target, so the current order is incomplete at the Shift click. + let last = semantic_at(owner, "Three"); + semantic_click(&mut h, &owners, last, egui::Modifiers::NONE); + let first = semantic_at(owner, "One"); + semantic_click(&mut h, &owners, first, egui::Modifiers { shift: true, ctrl: true, ..Default::default() }); + let names: BTreeSet<_> = h.app.session.selection.iter().filter_map(|selection| picked_body(selection).map(str::to_owned)).collect(); + assert_eq!(names, BTreeSet::from(["One".into(), "Two".into(), "Three".into()])); + } + } +} + +#[test] +fn browser_body_reveal_survives_history_only_and_unrelated_presentations() { + let mut h = Harness::new(); + three_bodies(&mut h); + reveal_body(&mut h.app, "Three"); + for owners in [&[ContentOwner::HISTORY][..], &[][..], &[ContentOwner::HISTORY][..]] { + semantic_frame(&mut h, owners, Vec::new(), egui::Modifiers::NONE); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Three")); + } + h.app.ui.show_browser = true; + h.app.ui.show_timeline = false; + h.app.preferences.browser_collapsed = true; + h.frames(3); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Three"), "collapsed Browser does not acknowledge a row"); + h.app.preferences.browser_collapsed = false; + for _ in 0..4 { + semantic_frame(&mut h, &[ContentOwner::HISTORY, ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE); + } + assert!(h.app.tree.reveal.is_none()); + assert!(drawn_rows().iter().any(|(label, ..)| label == "Three")); +} + +#[test] +fn history_reveal_survives_hidden_and_nonmatching_content_in_all_existing_compositions() { + for (left, combined) in [(false, false), (true, false), (false, true)] { + let mut h = Harness::new(); + h.app.home.open = false; + let feature = h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":"Target","body_name":"Body"})).unwrap()["feature"] + .as_u64() + .unwrap(); + h.app.preferences.timeline_left = left; + h.app.preferences.history_in_browser = combined; + h.app.ui.show_timeline = false; + h.app.ui.show_browser = false; + h.app.tree.timeline_reveal = Some(feature); + h.frames(3); + assert_eq!(h.app.tree.timeline_reveal, Some(feature)); + semantic_frame(&mut h, &[ContentOwner::HISTORY], Vec::new(), egui::Modifiers::NONE); + assert_eq!(h.app.tree.timeline_reveal, Some(feature), "Bodies/Origin is not a feature presentation"); + if combined { + h.app.ui.show_browser = true; + h.app.preferences.browser_collapsed = false; + h.app.tree.collapsed.insert("c0/history".into()); + h.frames(3); + assert_eq!(h.app.tree.timeline_reveal, Some(feature), "a folded combined History retains the request"); + h.app.tree.collapsed.remove("c0/history"); + } else { + h.app.ui.show_timeline = true; + } + h.frames(8); + assert!(h.app.tree.timeline_reveal.is_none(), "left={left}, combined={combined}"); + } +} + +#[test] +fn native_feature_reveal_waits_for_its_intended_browser_composition() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Body"})).unwrap(); + let id = h.app.session.doc.features[0].id; + reveal_feature(&mut h.app, id, "Body"); + h.app.preferences.history_in_browser = true; + h.frames(3); + assert!(h.app.tree.reveal_feature.is_some(), "combined History does not consume a native Features request"); + h.app.preferences.history_in_browser = false; + h.frames(4); + assert!(h.app.tree.reveal_feature.is_none()); +} + +#[test] +fn eye_capture_disappearance_finishes_one_undo_group_and_does_not_transfer_to_another_owner() { + for owner in [ContentOwner::BROWSER, ContentOwner::HISTORY] { + let mut h = Harness::new(); + three_bodies(&mut h); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let first = semantic_control(owner, "eye:One"); + let undo = h.app.session.undo.len(); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(first)], egui::Modifiers::NONE); + semantic_frame( + &mut h, + &owners, + vec![semantic_button(first, egui::PointerButton::Primary, true, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + let middle = semantic_control(owner, "eye:Two"); + for at in [first + vec2(0.0, 7.0), middle] { + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + } + assert!(h.ctx.data(|data| data.get_temp::(crate::ui_kit::eye_drag_id())).is_some()); + assert!(body_hidden(&h, "One") && body_hidden(&h, "Two") && !body_hidden(&h, "Three")); + let other = if owner == ContentOwner::BROWSER { ContentOwner::HISTORY } else { ContentOwner::BROWSER }; + let other_eye = semantic_control(other, "eye:Three"); + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert!(h.ctx.data(|data| data.get_temp::(crate::ui_kit::eye_drag_id())).is_none()); + assert!(h.app.tree.eye_press.is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1, "disappearance closes the existing drag group"); + semantic_frame(&mut h, &[other], vec![egui::Event::PointerMoved(other_eye)], egui::Modifiers::NONE); + assert!(!body_hidden(&h, "Three"), "the vanished owner's eye target cannot transfer to another presentation"); + semantic_frame( + &mut h, + &owners, + vec![semantic_button(other_eye, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!body_hidden(&h, "One") && !body_hidden(&h, "Two") && !body_hidden(&h, "Three")); + } +} + +#[test] +fn shared_body_origin_rows_keep_their_geometry_labels_and_composition() { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.tree.expanded.insert("origin".into()); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let browser = semantic_content::output(ContentOwner::BROWSER); + let history = semantic_content::output(ContentOwner::HISTORY); + let labels: Vec<_> = history.rows.iter().map(|(label, ..)| label.as_str()).collect(); + assert_eq!(labels, ["Bodies", "One", "Two", "Three", "Origin", "O", "X", "Y", "Z", "XY", "XZ", "YZ"]); + for (label, rect, fold, open) in history.rows { + let (_, browser_rect, browser_fold, browser_open) = browser.rows.iter().find(|(name, ..)| *name == label).unwrap(); + assert_eq!(rect.height(), browser_rect.height(), "{label}: existing shared row height"); + assert_eq!(fold.is_some(), browser_fold.is_some(), "{label}: existing disclosure composition"); + assert_eq!(open, *browser_open, "{label}: canonical fold state"); + } + assert_eq!(drawn_rows(), browser.rows, "legacy automation remains Browser-only"); +} + +#[test] +fn semantic_drop_runs_once_in_either_owner_submission_order() { + for owners in [[ContentOwner::BROWSER, ContentOwner::HISTORY], [ContentOwner::HISTORY, ContentOwner::BROWSER]] { + for owner in [ContentOwner::BROWSER, ContentOwner::HISTORY] { + let mut h = Harness::new(); + three_bodies(&mut h); + let group = h.app.run("browser.group", json!({"component":0,"folder":"bodies","name":"Destination"})).unwrap()["group"].as_u64().unwrap(); + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_at(owner, "One"); + let to = semantic_at(owner, "Destination (0)"); + let undo = h.app.session.undo.len(); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(from)], egui::Modifiers::NONE); + semantic_frame( + &mut h, + &owners, + vec![semantic_button(from, egui::PointerButton::Primary, true, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + for at in [from + vec2(8.0, 0.0), to] { + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + } + semantic_frame( + &mut h, + &owners, + vec![semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + assert!(h.app.session.doc.browser_group(group).unwrap().has_item("One")); + assert_eq!(h.app.session.undo.len(), undo + 1, "{owners:?}, {owner:?}: exactly one drop command"); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!h.app.session.doc.browser_group(group).unwrap().has_item("One")); + } + } +} + +#[test] +fn disappearing_semantic_drag_owner_releases_only_its_payload_and_widget_capture() { + for owner in [ContentOwner::BROWSER, ContentOwner::HISTORY] { + let mut h = Harness::new(); + three_bodies(&mut h); + for _ in 0..3 { + semantic_frame(&mut h, &[owner], Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_at(owner, "One"); + semantic_frame(&mut h, &[owner], vec![egui::Event::PointerMoved(from)], egui::Modifiers::NONE); + semantic_frame( + &mut h, + &[owner], + vec![semantic_button(from, egui::PointerButton::Primary, true, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + semantic_frame(&mut h, &[owner], vec![egui::Event::PointerMoved(from + vec2(10.0, 0.0))], egui::Modifiers::NONE); + assert!(egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert!(!egui::DragAndDrop::has_any_payload(&h.ctx)); + assert!(h.ctx.dragged_id().is_none()); + assert!(semantic_content::output(owner).rows.is_empty()); + } +} + +#[test] +fn pending_semantic_reveals_expire_when_their_targets_are_removed() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Body"})).unwrap(); + let feature = h.app.session.doc.features[0].id; + let other = h + .app + .run("solid.box", json!({"length":10,"width":10,"height":10,"corner":[20,0,0],"operation":"new_body","body_name":"Other"})) + .unwrap()["feature"] + .as_u64() + .unwrap(); + h.app.run("timeline.suppress", json!({"feature":other})).unwrap(); + reveal_body(&mut h.app, "Body"); + reveal_feature(&mut h.app, feature, "Body"); + h.app.tree.reveal = Some("Body".into()); + h.app.tree.timeline_reveal = Some(feature); + h.app.run("selection.delete", json!({"items":[Sel::Feature { id: feature }]})).unwrap(); + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert!(h.app.tree.reveal.is_none() && h.app.tree.reveal_feature.is_none() && h.app.tree.timeline_reveal.is_none()); +} + +#[test] +fn semantic_row_commands_are_consumed_once_across_layout_repeats() { + let mut h = Harness::new(); + three_bodies(&mut h); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let at = semantic_control(ContentOwner::HISTORY, "eye:One"); + let undo = h.app.session.undo.len(); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + semantic_frame(&mut h, &owners, vec![semantic_button(at, egui::PointerButton::Primary, true, egui::Modifiers::NONE)], egui::Modifiers::NONE); + h.ctx.data_mut(|data| data.insert_temp(egui::Id::new("semantic-test-discard"), true)); + semantic_frame(&mut h, &owners, vec![semantic_button(at, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], egui::Modifiers::NONE); + assert!(body_hidden(&h, "One"), "a repeated layout cannot toggle the eye back on"); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn invisible_browser_content_keeps_its_reveal_and_publishes_no_geometry() { + let mut h = Harness::new(); + three_bodies(&mut h); + reveal_body(&mut h.app, "Three"); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(900.0, 900.0))), ..Default::default() }; + h.ctx + .run_ui(raw, |ui| { + semantic_content::begin(&mut h.app, ui.ctx()); + ui.set_opacity(0.0); + semantic_content::show(&mut h.app, ui, ContentOwner::BROWSER, ContentRequest::Browser { shrink_height: false }); + semantic_content::finalize(&mut h.app, ui.ctx()); + }) + .textures_delta + .clear(); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Three")); + assert!(drawn_rows().is_empty() && drawn_occurrences().is_empty()); +} + +#[test] +fn combined_history_reveal_opens_and_acknowledges_the_features_placement() { + let (mut h, _, occurrence) = crate::test_support::component_box(); + let feature = h.app.session.model.state().body("Body1").unwrap().feature; + h.app.preferences.history_in_browser = true; + h.app.tree.close_row(&occurrence_key(&[occurrence])); + reveal_in_history(&mut h.app, feature); + h.app.tree.timeline_reveal = Some(feature); + h.frames(6); + assert!(is_open(&h.app, &occurrence_key(&[occurrence]), true)); + assert!(h.app.tree.reveal_feature.is_none() && h.app.tree.timeline_reveal.is_none()); + let name = &h.app.session.doc.feature(feature).unwrap().name; + assert!(drawn_rows().iter().any(|(label, ..)| label == name)); +} + +#[test] +fn browser_editors_have_one_app_owned_host_when_both_presentations_are_hidden() { + let (mut h, _, occurrence) = crate::test_support::component_box(); + h.app.ui.show_browser = false; + h.app.ui.show_timeline = false; + h.app.tree.occurrence_move = Some(OccMove::new(occurrence)); + h.frames(4); + assert!(drawn_rows().is_empty()); + let fields = crate::scenario::handles("occurrence-move:distance:0"); + assert_eq!( + fields.iter().filter(|(name, _)| name == "occurrence-move:distance:0").count(), + 1, + "the editor is hosted once despite both panels being hidden" + ); + assert!(h.app.tree.occurrence_move.as_ref().unwrap().baseline.is_some()); +} + +#[test] +fn body_reveal_waits_through_rollback_until_its_creator_is_presented_again() { + let mut h = Harness::new(); + three_bodies(&mut h); + reveal_body(&mut h.app, "Three"); + h.app.run("timeline.roll_to", json!({"position":1})).unwrap(); + for _ in 0..3 { + semantic_frame(&mut h, &[ContentOwner::HISTORY, ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Three"), "rollback is not removal"); + } + h.app.run("timeline.roll_to", json!({})).unwrap(); + for _ in 0..4 { + semantic_frame(&mut h, &[ContentOwner::HISTORY, ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE); + } + assert!(h.app.tree.reveal.is_none()); +} + +/// Make an actual second document tab with identical semantic names and IDs. Return to A; +/// tests can switch during an input frame without rebuilding or rendering B first. +fn matching_semantic_tab(h: &mut Harness) -> (usize, String, usize) { + let original = h.app.docs.active; + let incoming = solidcraft_engine::Session::new((*h.app.session.doc).clone()); + let original_session = h.app.session.uid; + crate::documents::open_tab(&mut h.app, incoming).unwrap(); + assert_ne!(h.app.session.uid, original_session); + let tab = h.app.docs.active; + let document = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + crate::documents::switch(&mut h.app, original); + (tab, document, undo) +} + +fn semantic_drag_start(h: &mut Harness, owners: &[ContentOwner], from: Pos2) { + semantic_frame(h, owners, vec![egui::Event::PointerMoved(from)], egui::Modifiers::NONE); + semantic_frame(h, owners, vec![semantic_button(from, egui::PointerButton::Primary, true, egui::Modifiers::NONE)], egui::Modifiers::NONE); + semantic_frame(h, owners, vec![egui::Event::PointerMoved(from + vec2(10.0, 0.0))], egui::Modifiers::NONE); +} + +fn semantic_occurrence_at(owner: ContentOwner, occurrence: u64) -> Pos2 { + semantic_content::output(owner).occurrences.into_iter().find(|(path, ..)| path.last() == Some(&occurrence)).unwrap().2.center() +} + +#[test] +fn switching_documents_cancels_body_payloads_before_matching_incoming_groups_can_drop() { + for after_begin in [false, true] { + for owner in [ContentOwner::BROWSER, ContentOwner::HISTORY] { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.run("browser.group", json!({"component":0,"folder":"bodies","name":"Destination"})).unwrap(); + let (tab, document, undo) = matching_semantic_tab(&mut h); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_at(owner, "One"); + let to = semantic_at(owner, "Destination (0)"); + semantic_drag_start(&mut h, &owners, from); + let outgoing = h.app.session.uid; + let payload = egui::DragAndDrop::payload::(&h.ctx).unwrap(); + assert_eq!(payload.source.session, outgoing); + let stale_payload = (*payload).clone(); + if !after_begin { + crate::documents::switch(&mut h.app, tab); + } + semantic_frame_switch( + &mut h, + &owners, + vec![egui::Event::PointerMoved(to), semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + after_begin.then_some(tab), + ); + assert_ne!(h.app.session.uid, outgoing); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + assert!(h.ctx.dragged_id().is_none()); + // Even a delayed payload reintroduced after cancellation must fail provenance + // validation; matching body/group names cannot make it belong to the new tab. + egui::DragAndDrop::set_payload(&h.ctx, stale_payload); + semantic_frame( + &mut h, + &owners, + vec![semantic_button(to, egui::PointerButton::Primary, true, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + semantic_frame( + &mut h, + &owners, + vec![semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + } + } +} + +#[test] +fn switching_documents_cancels_occurrence_payloads_with_matching_component_and_path_ids() { + for after_begin in [false, true] { + let (mut h, _, occurrence) = crate::test_support::component_box(); + let destination = h.app.run("component.create", json!({"name":"Destination"})).unwrap()["occurrence"].as_u64().unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let (tab, document, undo) = matching_semantic_tab(&mut h); + let owners = [ContentOwner::BROWSER]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_occurrence_at(ContentOwner::BROWSER, occurrence); + let to = semantic_occurrence_at(ContentOwner::BROWSER, destination); + semantic_drag_start(&mut h, &owners, from); + assert!(egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + if !after_begin { + crate::documents::switch(&mut h.app, tab); + } + semantic_frame_switch( + &mut h, + &owners, + vec![egui::Event::PointerMoved(to), semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + after_begin.then_some(tab), + ); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + assert!(h.ctx.dragged_id().is_none()); + } +} + +#[test] +fn switching_documents_clears_combined_history_drag_even_when_feature_ids_match() { + for after_begin in [false, true] { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.preferences.history_in_browser = true; + let source = h.app.session.doc.features[2].id; + let target = h.app.session.doc.features[0].id; + let (tab, document, undo) = matching_semantic_tab(&mut h); + let owners = [ContentOwner::BROWSER]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_control(ContentOwner::BROWSER, &format!("row:browser-feature:c0:{source}")); + let to = semantic_control(ContentOwner::BROWSER, &format!("row:browser-feature:c0:{target}")); + semantic_drag_start(&mut h, &owners, from); + assert!(!h.app.tree.content.owner(ContentOwner::BROWSER).unwrap().feature_drags.is_empty()); + if !after_begin { + crate::documents::switch(&mut h.app, tab); + } + semantic_frame_switch( + &mut h, + &owners, + vec![egui::Event::PointerMoved(to), semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + after_begin.then_some(tab), + ); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.tree.content.owner(ContentOwner::BROWSER).unwrap().feature_drags.is_empty()); + assert!(h.ctx.dragged_id().is_none()); + } +} + +#[test] +fn document_switch_drops_shift_anchors_without_changing_the_incoming_document_or_undo() { + for owner in [ContentOwner::BROWSER, ContentOwner::HISTORY] { + let mut h = Harness::new(); + three_bodies(&mut h); + let (tab, document, undo) = matching_semantic_tab(&mut h); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let at = semantic_at(owner, "One"); + semantic_click(&mut h, &owners, at, egui::Modifiers::NONE); + assert!(h.app.tree.content.owner(owner).unwrap().anchor.is_some()); + semantic_frame_switch(&mut h, &owners, Vec::new(), egui::Modifiers::NONE, Some(tab)); + assert!(h.app.tree.content.owner(owner).unwrap().anchor.is_none()); + let at = semantic_at(owner, "Two"); + semantic_click(&mut h, &owners, at, egui::Modifiers { shift: true, ..Default::default() }); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Two".into() }], "A's One anchor cannot extend B's selection"); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn switching_documents_finishes_eye_undo_group_in_the_outgoing_session_only() { + let mut h = Harness::new(); + three_bodies(&mut h); + let original = h.app.docs.active; + let (tab, document, undo_b) = matching_semantic_tab(&mut h); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let undo_a = h.app.session.undo.len(); + let one = semantic_control(ContentOwner::BROWSER, "eye:One"); + let two = semantic_control(ContentOwner::BROWSER, "eye:Two"); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(one)], egui::Modifiers::NONE); + semantic_frame(&mut h, &owners, vec![semantic_button(one, egui::PointerButton::Primary, true, egui::Modifiers::NONE)], egui::Modifiers::NONE); + for point in [one + vec2(0.0, 7.0), two] { + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(point)], egui::Modifiers::NONE); + } + assert!(body_hidden(&h, "One") && body_hidden(&h, "Two")); + semantic_frame_switch(&mut h, &owners, Vec::new(), egui::Modifiers::NONE, Some(tab)); + let three = semantic_control(ContentOwner::BROWSER, "eye:Three"); + semantic_frame(&mut h, &owners, vec![egui::Event::PointerMoved(three)], egui::Modifiers::NONE); + semantic_frame(&mut h, &owners, vec![semantic_button(three, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], egui::Modifiers::NONE); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo_b); + assert!(!body_hidden(&h, "One") && !body_hidden(&h, "Two") && !body_hidden(&h, "Three")); + crate::documents::switch(&mut h.app, original); + assert_eq!(h.app.session.undo.len(), undo_a + 1, "only the outgoing session receives the merged drag undo group"); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!body_hidden(&h, "One") && !body_hidden(&h, "Two")); +} + +#[test] +fn switching_semantic_documents_preserves_unrelated_payload_and_capture() { + let mut h = Harness::new(); + three_bodies(&mut h); + let (tab, _, _) = matching_semantic_tab(&mut h); + let owners = [ContentOwner::BROWSER]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_at(ContentOwner::BROWSER, "One"); + semantic_drag_start(&mut h, &owners, from); + let external = egui::Id::new("external capture"); + egui::DragAndDrop::set_payload(&h.ctx, "external payload".to_string()); + h.ctx.set_dragged_id(external); + crate::documents::switch(&mut h.app, tab); + assert_eq!(egui::DragAndDrop::payload::(&h.ctx).as_deref().map(String::as_str), Some("external payload")); + assert_eq!(h.ctx.dragged_id(), Some(external)); +} + +#[test] +fn hidden_body_or_group_drag_source_cannot_drop_through_a_surviving_history_target() { + for group_source in [false, true] { + for keep_source in [false, true] { + let mut h = Harness::new(); + three_bodies(&mut h); + if group_source { + h.app.run("browser.group", json!({"component":0,"folder":"bodies","name":"Source","items":["One"]})).unwrap(); + } + let destination = + h.app.run("browser.group", json!({"component":0,"folder":"bodies","name":"Destination"})).unwrap()["group"].as_u64().unwrap(); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_at(ContentOwner::BROWSER, if group_source { "Source (1)" } else { "One" }); + let to = semantic_at(ContentOwner::HISTORY, "Destination (0)"); + let document = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + semantic_drag_start(&mut h, &owners, from); + assert!(egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + let presented = if keep_source { &owners[..] } else { &[ContentOwner::HISTORY][..] }; + semantic_frame( + &mut h, + presented, + vec![egui::Event::PointerMoved(to), semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + if keep_source { + assert_ne!(h.app.session.doc.to_json(), document, "cross-owner drops remain valid while both owners are presented"); + assert_eq!(h.app.session.undo.len(), undo + 1); + if !group_source { + assert!(h.app.session.doc.browser_group(destination).unwrap().has_item("One")); + } + } else { + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + } + assert!(!egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + assert!(h.ctx.dragged_id().is_none()); + } + } +} + +#[test] +fn hidden_occurrence_source_cannot_reparent_or_reorder_through_a_surviving_adapter() { + for reorder in [false, true] { + for keep_source in [false, true] { + let (mut h, _, occurrence) = crate::test_support::component_box(); + let destination = h.app.run("component.create", json!({"name":"Destination"})).unwrap()["occurrence"].as_u64().unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let adapter = ContentOwner(2); + let owners = [ContentOwner::BROWSER, adapter]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + // Move the later placement before the earlier one for a real reorder change. + let (source, target) = if reorder { (destination, occurrence) } else { (occurrence, destination) }; + let from = semantic_occurrence_at(ContentOwner::BROWSER, source); + let mut to = semantic_occurrence_at(adapter, target); + if reorder { + to.y -= crate::ui_kit::TREE_ROW_HEIGHT * 0.4; + } + let document = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + semantic_drag_start(&mut h, &owners, from); + assert!(egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + let presented = if keep_source { &owners[..] } else { std::slice::from_ref(&adapter) }; + semantic_frame( + &mut h, + presented, + vec![egui::Event::PointerMoved(to), semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + if keep_source { + assert_ne!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo + 1); + } else { + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + } + assert!(!egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + assert!(h.ctx.dragged_id().is_none()); + } + } +} + +#[test] +fn session_switch_after_target_rows_render_discards_their_already_queued_drop() { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.run("browser.group", json!({"component":0,"folder":"bodies","name":"Destination"})).unwrap(); + let (tab, document, undo) = matching_semantic_tab(&mut h); + let owners = [ContentOwner::BROWSER, ContentOwner::HISTORY]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_at(ContentOwner::BROWSER, "One"); + let to = semantic_at(ContentOwner::HISTORY, "Destination (0)"); + semantic_drag_start(&mut h, &owners, from); + semantic_frame_transitions( + &mut h, + &owners, + vec![egui::Event::PointerMoved(to), semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + None, + Some(tab), + ); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + assert!(semantic_content::output(ContentOwner::BROWSER).rows.is_empty()); + assert!(semantic_content::output(ContentOwner::HISTORY).rows.is_empty()); +} + +#[test] +fn semantic_entrypoints_reject_replaced_sessions_even_without_a_documents_hook() { + let mut h = Harness::new(); + three_bodies(&mut h); + h.app.run("browser.group", json!({"component":0,"folder":"bodies","name":"Destination"})).unwrap(); + let incoming = solidcraft_engine::Session::new((*h.app.session.doc).clone()); + let document = incoming.doc.to_json(); + let undo = incoming.undo.len(); + let owners = [ContentOwner::BROWSER]; + for _ in 0..3 { + semantic_frame(&mut h, &owners, Vec::new(), egui::Modifiers::NONE); + } + let from = semantic_at(ContentOwner::BROWSER, "One"); + semantic_click(&mut h, &owners, from, egui::Modifiers::NONE); + let to = semantic_at(ContentOwner::BROWSER, "Destination (0)"); + semantic_drag_start(&mut h, &owners, from); + assert!(egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + h.app.session.replace_design(incoming); + semantic_frame( + &mut h, + &owners, + vec![egui::Event::PointerMoved(to), semantic_button(to, egui::PointerButton::Primary, false, egui::Modifiers::NONE)], + egui::Modifiers::NONE, + ); + assert_eq!(h.app.session.doc.to_json(), document); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.tree.content.owner(ContentOwner::BROWSER).unwrap().anchor.is_none()); + assert!(!egui::DragAndDrop::has_payload_of_type::(&h.ctx)); + assert!(h.ctx.dragged_id().is_none()); +} + +fn reveal_browser_at_height(h: &mut Harness, height: f32) { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(900.0, 600.0))), ..Default::default() }; + h.ctx + .run_ui(raw, |ui| { + semantic_content::begin(&mut h.app, ui.ctx()); + let mut content = ui.new_child( + egui::UiBuilder::new().id_salt("reveal-document-test").max_rect(Rect::from_min_size(pos2(10.0, 10.0), vec2(400.0, height))), + ); + semantic_content::show(&mut h.app, &mut content, ContentOwner::BROWSER, ContentRequest::Browser { shrink_height: false }); + semantic_content::finalize(&mut h.app, ui.ctx()); + }) + .textures_delta + .clear(); +} + +fn assert_no_pending_reveals(h: &Harness) { + assert!(h.app.tree.reveal.is_none()); + assert!(h.app.tree.reveal_source.is_none()); + assert!(h.app.tree.reveal_feature.is_none()); + assert!(h.app.tree.timeline_reveal.is_none()); + assert!(h.app.tree.view_pick.is_none()); +} + +fn queue_all_document_reveals(h: &mut Harness) -> u64 { + let feature = h.app.session.model.state().body("Three").unwrap().feature; + reveal_body(&mut h.app, "Three"); + reveal_feature(&mut h.app, feature, "Three"); + // Keep both independently pending presentations, with the body's real provenance from + // reveal_body. Public request fields also remain supported for existing adapters. + h.app.tree.reveal = Some("Three".into()); + request_timeline_reveal(&mut h.app, feature); + h.app.tree.view_pick = Some(feature); + h.app.ui.show_browser = false; + h.app.ui.show_timeline = false; + feature +} + +#[test] +fn body_reveals_park_with_each_document_and_cannot_scroll_a_matching_incoming_browser() { + let mut h = Harness::new(); + three_bodies(&mut h); + let original = h.app.docs.active; + let original_uid = h.app.session.uid; + let (tab, _, _) = matching_semantic_tab(&mut h); + crate::documents::switch(&mut h.app, tab); + for _ in 0..3 { + reveal_browser_at_height(&mut h, 120.0); + } + let root = h.app.session.doc.name.clone(); + let incoming_root = semantic_at(ContentOwner::BROWSER, &root); + assert!(!drawn_rows().iter().any(|(label, ..)| label == "Three"), "the target starts outside the scroll viewport"); + crate::documents::switch(&mut h.app, original); + reveal_body(&mut h.app, "Three"); + h.app.ui.show_browser = false; + h.app.tree.view_pick = Some(h.app.session.doc.features[2].id); + semantic_frame_transitions(&mut h, &[ContentOwner::HISTORY], Vec::new(), egui::Modifiers::NONE, None, Some(tab)); + assert_no_pending_reveals(&h); + for _ in 0..8 { + reveal_browser_at_height(&mut h, 120.0); + } + assert_eq!(semantic_at(ContentOwner::BROWSER, &root), incoming_root, "B must not scroll in response to A's same-named body"); + reveal_body(&mut h.app, "Two"); + h.app.ui.show_browser = false; + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Two")); + crate::documents::switch(&mut h.app, original); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Three")); + assert_eq!(h.app.tree.reveal_source.as_ref().unwrap().session, original_uid); + assert!(h.app.tree.view_pick.is_none()); + for _ in 0..30 { + reveal_browser_at_height(&mut h, 120.0); + } + assert!(h.app.tree.reveal.is_none(), "A acknowledges its restored target only after scrolling presents it"); + crate::documents::switch(&mut h.app, tab); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Two"), "B's independent request survives A's acknowledgment"); + for _ in 0..30 { + reveal_browser_at_height(&mut h, 120.0); + } + assert!(h.app.tree.reveal.is_none()); +} + +#[test] +fn native_feature_reveals_restore_only_in_their_document_even_when_feature_ids_match() { + let mut h = Harness::new(); + three_bodies(&mut h); + let original = h.app.docs.active; + let target_a = h.app.session.doc.features[2].id; + let target_b = h.app.session.doc.features[0].id; + let (tab, _, _) = matching_semantic_tab(&mut h); + reveal_feature(&mut h.app, target_a, "Three"); + h.app.ui.show_browser = false; + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + semantic_frame_switch(&mut h, &[ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE, Some(tab)); + assert_no_pending_reveals(&h); + assert!(h.app.session.doc.feature(target_a).is_some(), "matching numeric IDs do exist in B"); + reveal_feature(&mut h.app, target_b, "One"); + h.app.ui.show_browser = false; + crate::documents::switch(&mut h.app, original); + assert_eq!(h.app.tree.reveal_feature.as_ref().map(|target| target.id), Some(target_a)); + for _ in 0..4 { + semantic_frame(&mut h, &[ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE); + } + assert!(h.app.tree.reveal_feature.is_none()); + crate::documents::switch(&mut h.app, tab); + assert_eq!(h.app.tree.reveal_feature.as_ref().map(|target| target.id), Some(target_b)); + for _ in 0..4 { + semantic_frame(&mut h, &[ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE); + } + assert!(h.app.tree.reveal_feature.is_none()); +} + +#[test] +fn timeline_reveals_remain_per_document_in_bottom_vertical_and_combined_history() { + for (left, combined) in [(false, false), (true, false), (false, true)] { + let mut h = Harness::new(); + three_bodies(&mut h); + let original = h.app.docs.active; + let target_a = h.app.session.doc.features[2].id; + let target_b = h.app.session.doc.features[0].id; + let (tab, _, _) = matching_semantic_tab(&mut h); + h.app.preferences.timeline_left = left; + h.app.preferences.history_in_browser = combined; + if combined { + reveal_in_history(&mut h.app, target_a); + } + request_timeline_reveal(&mut h.app, target_a); + h.app.tree.view_pick = Some(target_a); + h.app.ui.show_timeline = false; + h.app.ui.show_browser = false; + h.frames(2); + semantic_frame_switch(&mut h, &[], Vec::new(), egui::Modifiers::NONE, Some(tab)); + assert_no_pending_reveals(&h); + h.app.ui.show_timeline = true; + h.app.ui.show_browser = combined; + h.frames(4); + assert!(h.app.tree.timeline_reveal.is_none()); + request_timeline_reveal(&mut h.app, target_b); + h.app.ui.show_timeline = false; + h.app.ui.show_browser = false; + h.frames(2); + semantic_frame_switch(&mut h, &[], Vec::new(), egui::Modifiers::NONE, Some(original)); + assert_eq!(h.app.tree.timeline_reveal, Some(target_a)); + assert!(h.app.tree.view_pick.is_none()); + if combined { + assert_eq!(h.app.tree.reveal_feature.as_ref().map(|target| target.id), Some(target_a)); + } + h.app.ui.show_timeline = true; + h.app.ui.show_browser = combined; + h.frames(8); + assert!(h.app.tree.timeline_reveal.is_none(), "left={left}, combined={combined}: A acknowledges its own request"); + assert!(h.app.tree.reveal_feature.is_none()); + crate::documents::switch(&mut h.app, tab); + assert_eq!(h.app.tree.timeline_reveal, Some(target_b)); + h.frames(8); + assert!(h.app.tree.timeline_reveal.is_none(), "B acknowledges its independent request"); + } +} + +#[test] +fn closing_a_document_destroys_its_parked_reveals_and_clears_stale_view_pick() { + for active in [false, true] { + let mut h = Harness::new(); + three_bodies(&mut h); + let original = h.app.docs.active; + let (tab, _, _) = matching_semantic_tab(&mut h); + queue_all_document_reveals(&mut h); + if !active { + crate::documents::switch(&mut h.app, tab); + } + crate::documents::close(&mut h.app, original, true); + assert_eq!(h.app.docs.count(), 1); + assert_no_pending_reveals(&h); + let replacement = solidcraft_engine::Session::new((*h.app.session.doc).clone()); + crate::documents::open_tab(&mut h.app, replacement).unwrap(); + assert_no_pending_reveals(&h); + for _ in 0..3 { + semantic_frame(&mut h, &[ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE); + } + assert_no_pending_reveals(&h); + } +} + +#[test] +fn last_close_blank_adoption_and_direct_replacement_discard_outgoing_reveal_requests() { + for replacement in ["last-close", "blank-adopt", "direct"] { + let mut h = Harness::new(); + three_bodies(&mut h); + let incoming = solidcraft_engine::Session::new((*h.app.session.doc).clone()); + queue_all_document_reveals(&mut h); + match replacement { + "last-close" => { + let original = h.app.docs.active; + crate::documents::close(&mut h.app, original, true); + assert_no_pending_reveals(&h); + crate::documents::adopt(&mut h.app, incoming); + assert_no_pending_reveals(&h); + } + "blank-adopt" => { + h.app.session.replace_design(solidcraft_engine::Session::default()); + crate::documents::adopt(&mut h.app, incoming); + assert_no_pending_reveals(&h); + } + _ => h.app.session.replace_design(incoming), + } + for _ in 0..3 { + semantic_frame(&mut h, &[ContentOwner::BROWSER], Vec::new(), egui::Modifiers::NONE); + } + assert_no_pending_reveals(&h); + assert!(h.app.session.model.state().body("Three").is_some(), "the incoming target still exists; matching names cannot preserve A's request"); + } +} + +#[test] +fn unpresented_app_requests_have_provenance_before_a_direct_session_replacement() { + let mut h = Harness::new(); + three_bodies(&mut h); + let document = (*h.app.session.doc).clone(); + h.app = crate::SolveApp::new(solidcraft_engine::Session::new(document.clone()), crate::Services::default()); + // Existing callers can set the public request fields before the first UI frame. + h.app.tree.reveal = Some("Three".into()); + h.app.tree.timeline_reveal = Some(document.features[2].id); + h.app.tree.view_pick = Some(document.features[2].id); + h.app.session.replace_design(solidcraft_engine::Session::new(document)); + semantic_frame(&mut h, &[ContentOwner::HISTORY], Vec::new(), egui::Modifiers::NONE); + assert_no_pending_reveals(&h); +} + +#[test] +fn parked_reveals_are_pruned_against_their_own_document_when_the_target_is_removed() { + let mut h = Harness::new(); + three_bodies(&mut h); + let original = h.app.docs.active; + let owner = h.app.session.uid; + let (tab, _, _) = matching_semantic_tab(&mut h); + let feature = queue_all_document_reveals(&mut h); + crate::documents::switch(&mut h.app, tab); + let parked = h.app.docs.background_mut().find(|slot| slot.session.uid == owner).unwrap(); + parked.session.execute("selection.delete", &json!({"items":[Sel::Feature { id: feature }]})).unwrap(); + assert_no_pending_reveals(&h); + assert!(h.app.session.doc.feature(feature).is_some(), "B retains the matching feature"); + crate::documents::switch(&mut h.app, original); + assert_eq!(h.app.tree.timeline_reveal, Some(feature), "the request returns to A before ordinary target pruning"); + semantic_frame(&mut h, &[], Vec::new(), egui::Modifiers::NONE); + assert_no_pending_reveals(&h); +} diff --git a/crates/ui-egui/src/browser_model.rs b/crates/ui-egui/src/browser_model.rs index 1def45967..9b116b6db 100644 --- a/crates/ui-egui/src/browser_model.rs +++ b/crates/ui-egui/src/browser_model.rs @@ -38,6 +38,9 @@ impl Model { if !matches!(feature.kind, FeatureKind::Sketch { .. }) { features.entry(feature.component).or_default().push(i); } + if session.doc.marker.is_some_and(|marker| i >= marker) { + continue; + } let index = match feature.kind { FeatureKind::Sketch { .. } => &mut sketches, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. } => &mut planes, @@ -49,6 +52,10 @@ impl Model { for occurrence in &session.doc.occurrences { children.entry(occurrence.parent).or_default().push(occurrence.id); } + // Sub-components in the order the design saved for them; the rest follow in placement order. + for (parent, ids) in &mut children { + session.doc.sort_placements(*parent, ids); + } Self { doc: session.doc.clone(), state, diff --git a/crates/ui-egui/src/browser_model_tests.rs b/crates/ui-egui/src/browser_model_tests.rs index 9e6931023..a562ace07 100644 --- a/crates/ui-egui/src/browser_model_tests.rs +++ b/crates/ui-egui/src/browser_model_tests.rs @@ -29,7 +29,7 @@ fn pending_and_reverted_moves_replace_cached_transforms() { h.app.run("occurrence.move", json!({"occurrence":occurrence,"translate":[20,0,0],"capture":false})).unwrap(); let moved = super::model_placement(&mut h.app, &[occurrence]).unwrap(); assert!(!Arc::ptr_eq(&first, &moved)); - assert!((solidcraft_engine::doc::apply_point(&moved.world, solidcraft_engine::geom::Vec3::ZERO).x - 20.0).abs() < 1e-9); + assert!((solidcraft_engine::doc::apply_point(&moved.world, solidcore_record::Vec3::ZERO).x - 20.0).abs() < 1e-9); h.app.run("component.revert_position", json!({"occurrences":[occurrence]})).unwrap(); let reverted = super::model_placement(&mut h.app, &[occurrence]).unwrap(); assert!(!Arc::ptr_eq(&moved, &reverted)); @@ -95,16 +95,25 @@ fn a_face_picked_in_the_viewport_opens_the_browser_to_its_placements_body() { let (one, two) = (super::occurrence_key(&[occurrence]), super::occurrence_key(&[copy])); h.app.tree.collapsed.extend([one.clone(), two.clone(), format!("{two}/bodies")]); h.frames(2); - assert!(!h.app.tree.order.contains(&format!("b:{second}")), "the body's row is closed away"); - let face = Sel::Face { body: second.clone(), index: 0, point: solidcraft_engine::geom::Vec3::new(55.0, 5.0, 10.0) }; + assert!( + !h.app.tree.content.owner(crate::semantic_content::ContentOwner::BROWSER).unwrap().order.contains(&format!("b:{second}")), + "the body's row is closed away" + ); + let face = Sel::Face { body: second.clone(), index: 0, point: solidcore_record::Vec3::new(55.0, 5.0, 10.0) }; crate::viewport::select(&mut h.app, Some(face), false, false); assert_eq!(h.app.tree.reveal.as_deref(), Some(second.as_str())); h.frames(2); assert!(h.app.tree.reveal.is_none(), "revealed"); assert!(!h.app.tree.collapsed.contains(&two) && !h.app.tree.collapsed.contains(&format!("{two}/bodies"))); assert!(h.app.tree.collapsed.contains(&one), "the other placement stays as it was"); - assert!(h.app.tree.order.contains(&format!("b:{second}")), "the row is drawn"); - assert!(!h.app.tree.order.contains(&format!("b:{first}")), "the other placement's row stays closed away"); + assert!( + h.app.tree.content.owner(crate::semantic_content::ContentOwner::BROWSER).unwrap().order.contains(&format!("b:{second}")), + "the row is drawn" + ); + assert!( + !h.app.tree.content.owner(crate::semantic_content::ContentOwner::BROWSER).unwrap().order.contains(&format!("b:{first}")), + "the other placement's row stays closed away" + ); } /// Hovering a placement row lights its whole subtree: the subtree is walked once per model, not @@ -207,9 +216,9 @@ fn render_browser_swatch_resolves_face_body_component_then_physical_material() { assert_eq!(swatch(&h).name, "ABS - Red"); h.app.run("appearance.assign", json!({"bodies":["Body1"],"appearance":"ABS - Blue"})).unwrap(); assert_eq!(swatch(&h).name, "ABS - Blue"); - let point = solidcraft_engine::geom::Vec3::new(0.0, 5.0, 5.0); + let point = solidcore_record::Vec3::new(0.0, 5.0, 5.0); h.app.run("appearance.assign", json!({"body":"Body1","faces":[point],"appearance":"ABS - Red"})).unwrap(); - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let body = state.body("Body1").unwrap(); let face = solidcraft_engine::doc::appearance::face_index_at(body, point).unwrap(); h.app.run("select.set", json!({"items":[Sel::Face{body:"Body1".into(),index:face,point}]})).unwrap(); @@ -237,6 +246,15 @@ fn body_names(app: &crate::SolveApp) -> Vec { .unwrap_or_default() } +/// The bodies the open Move/Copy would move, a picked component's bodies included. +fn move_bodies(app: &crate::SolveApp) -> Vec { + let Some(d) = app.dialog.as_ref() else { return Vec::new() }; + crate::dialogs_move::params(app, d) + .ok() + .and_then(|p| p["bodies"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())) + .unwrap_or_default() +} + fn two_bodies(h: &mut crate::scenario::Harness) { h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Left"})).unwrap(); h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0], "body_name": "Right"})).unwrap(); @@ -309,7 +327,7 @@ fn browser_move_copy_takes_a_component_clicked_in_the_tree() { open_move(&mut h); h.frames(2); click(&mut h, &format!("row:occurrence:{occurrence}")); - assert_eq!(body_names(&h.app), owned, "the component's bodies are the Move/Copy selection"); + assert_eq!(move_bodies(&h.app), owned, "the component's bodies are the Move/Copy selection"); assert!(h.app.tree.occurrence_move.is_none(), "the open body dialog stays; this click does not switch to component Move"); h.app.dialog = None; @@ -318,7 +336,7 @@ fn browser_move_copy_takes_a_component_clicked_in_the_tree() { click(&mut h, "row:Untitled"); assert_eq!(h.app.tree.picked_components, vec![0]); h.app.start("solid.move"); - let names = body_names(&h.app); + let names = move_bodies(&h.app); assert!(names.iter().any(|n| owned.contains(n)), "Move/Copy starts from the component picked in the tree: {names:?}"); } @@ -410,6 +428,35 @@ fn browser_rows_still_fold_or_select_when_move_copy_is_not_open() { assert!(h.app.tree.collapsed.contains("c0/bodies")); } +#[test] +fn feature_editor_browser_rows_follow_the_marker_and_return_after_cancel() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY","name":"Base"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,10]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("solid.extrude", json!({"sketch":"Base","distance":10,"name":"Depth"})).unwrap(); + let feature = h.app.session.doc.find_feature("Depth").unwrap().id; + h.app.run("sketch.create", json!({"plane":"YZ","name":"Later sketch"})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("construct.plane.offset", json!({"base":"XY","offset":20,"name":"Later plane"})).unwrap(); + super::prepare_model(&mut h.app); + assert_eq!(super::entries(&h.app, 0, "sketches").len(), 2); + assert_eq!(super::entries(&h.app, 0, "construction").len(), 1); + h.app.edit_feature(feature); + // Both the fallback queries and the cached index must follow rollback. + assert_eq!(super::entries(&h.app, 0, "sketches").iter().map(|e| e.label.as_str()).collect::>(), ["Base"]); + assert!(super::entries(&h.app, 0, "construction").is_empty()); + assert!(super::entries(&h.app, 0, "bodies").is_empty()); + super::prepare_model(&mut h.app); + assert_eq!(super::entries(&h.app, 0, "sketches").len(), 1); + assert!(super::entries(&h.app, 0, "construction").is_empty()); + crate::dialogs::cancel(&mut h.app); + super::prepare_model(&mut h.app); + assert_eq!(super::entries(&h.app, 0, "sketches").len(), 2); + assert_eq!(super::entries(&h.app, 0, "construction").len(), 1); + assert_eq!(super::entries(&h.app, 0, "bodies").len(), 1); +} + /// The sketch being edited is marked in the user's language, not with an English "(editing)", /// and its default name reads as the browser shows it elsewhere. #[test] @@ -420,3 +467,103 @@ fn the_edited_sketch_is_marked_in_the_users_language() { let rows = super::entries(&h.app, 0, "sketches"); assert_eq!(rows.iter().map(|r| r.label.as_str()).collect::>(), ["スケッチ1 (編集中)"]); } + +/// A design saved before groups could nest or be ordered shows the browser it always did: the +/// groups in creation order, each with its items, above the loose items, which follow the saved +/// order and leave the ones it does not name to the end. That layout is spelled out here and +/// compared with the rows drawn now, including a saved order that still names a grouped item. +#[test] +fn a_design_saved_before_nested_groups_keeps_its_browser_order() { + use super::cache::Row; + const BODIES: [&str; 5] = ["Plate", "Washer", "Bolt", "Nut", "Cap"]; + fn drawn(rows: &[Row]) -> Vec { + rows.iter() + .map(|r| match r { + Row::Item(e) => e.key.clone(), + Row::Group(g) => format!("{{{}: {}}}", g.label, drawn(&g.rows).join(",")), + }) + .collect() + } + let cases: [(&[(&str, &[&str])], &[&str]); 3] = [ + (&[("Fasteners", &["Bolt", "Nut"])], &[]), + (&[("Fasteners", &["Bolt", "Nut"])], &["Washer", "Bolt", "Cap"]), + (&[("Zeta", &["Plate"]), ("Alpha", &["Cap", "Washer"])], &["Cap", "Nut"]), + ]; + for (groups, saved) in cases { + let mut h = crate::scenario::Harness::new(); + for (i, name) in BODIES.iter().enumerate() { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"corner":[i as f64 * 20.0, 0, 0],"body_name":name})).unwrap(); + } + for (name, items) in groups { + h.app.run("browser.group", json!({"component":0,"folder":"bodies","name":name,"items":items})).unwrap(); + } + if !saved.is_empty() { + h.app.run("browser.order", json!({"folder":"bodies","order":saved})).unwrap(); + } + // The old layout: groups in creation order, then the loose items by their saved place. + let mut expected: Vec = groups.iter().map(|(n, items)| format!("{{{n} ({}): {}}}", items.len(), items.join(","))).collect(); + let mut loose: Vec<&str> = BODIES.into_iter().filter(|b| !groups.iter().any(|(_, items)| items.contains(b))).collect(); + loose.sort_by_key(|b| saved.iter().position(|s| s == b).unwrap_or(usize::MAX)); + expected.extend(loose.into_iter().map(String::from)); + let rows = super::arrange(&h.app.session.doc, 0, "bodies", "c0", super::entries(&h.app, 0, "bodies")); + assert_eq!(drawn(&rows), expected, "groups {groups:?}, saved order {saved:?}"); + } +} + +/// #9274: placements start closed, so a large assembly opens as a short list. Opening one shows +/// its own placements still closed, and closing and reopening it leaves them as they were. +/// Expand All opens them, and the "Components start open" preference opens every one as before. +#[test] +fn placements_start_closed_and_the_preference_opens_them_as_before() { + fn drawn(h: &mut crate::scenario::Harness) -> Vec<(Vec, bool)> { + h.frames(2); + super::drawn_occurrences().into_iter().map(|(path, _, _, open)| (path, open)).collect() + } + let mut h = crate::scenario::Harness::new(); + h.app.ui.show_browser = true; + let sub = h.app.run("component.create", json!({"name":"Sub"})).unwrap(); + let outer = vec![sub["occurrence"].as_u64().unwrap()]; + let leaf = h.app.run("component.create", json!({"name":"Leaf"})).unwrap()["occurrence"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let inner = vec![outer[0], leaf]; + let fold = format!("fold:occurrence:{}", outer[0]); + + assert_eq!(drawn(&mut h), [(outer.clone(), false)], "only the top placement is listed, closed"); + click(&mut h, &fold); + assert_eq!(drawn(&mut h), [(outer.clone(), true), (inner.clone(), false)], "the placement inside stays closed"); + click(&mut h, &fold); + assert_eq!(drawn(&mut h), [(outer.clone(), false)]); + click(&mut h, &fold); + assert_eq!(drawn(&mut h), [(outer.clone(), true), (inner.clone(), false)], "reopening shows it as it was"); + + h.app.run("browser.expand_all", json!({})).unwrap(); + assert_eq!(drawn(&mut h), [(outer.clone(), true), (inner.clone(), true)], "Expand All opens every placement"); + h.app.run("browser.collapse_all", json!({})).unwrap(); + assert_eq!(drawn(&mut h), [(outer.clone(), false)], "Collapse All closes them again"); + + h.app.tree.collapsed.clear(); + h.app.tree.expanded.clear(); + h.call("ui.prefs", json!({"browser_components_open": true})); + assert!(h.app.preferences.browser_components_open); + assert_eq!(drawn(&mut h), [(outer.clone(), true), (inner, true)], "the preference opens every placement, as before #9274"); + click(&mut h, &fold); + assert_eq!(drawn(&mut h), [(outer, false)], "and its arrow still closes one"); +} + +/// #9274: Find in Browser opens the placements, closed from the start, down to the body's row. +#[test] +fn find_in_browser_opens_placements_that_start_closed() { + let (mut h, _, occurrence) = fixture(); + h.app.ui.show_browser = true; + let body = super::model_placement(&mut h.app, &[occurrence]).unwrap().bodies[0].world.clone(); + h.frames(2); + assert!(!super::is_open(&h.app, &super::occurrence_key(&[occurrence]), true), "the placement starts closed"); + super::reveal_body(&mut h.app, &body); + h.frames(3); + assert!(super::is_open(&h.app, &super::occurrence_key(&[occurrence]), true)); + assert!( + h.app.tree.content.owner(crate::semantic_content::ContentOwner::BROWSER).unwrap().order.contains(&format!("b:{body}")), + "the body's row is drawn" + ); +} diff --git a/crates/ui-egui/src/browser_prompts.rs b/crates/ui-egui/src/browser_prompts.rs index bab9dd292..75341945d 100644 --- a/crates/ui-egui/src/browser_prompts.rs +++ b/crates/ui-egui/src/browser_prompts.rs @@ -32,7 +32,7 @@ pub(crate) fn occurrence_panel(app: &mut SolveApp, ui: &mut egui::Ui) { m.pivot = if m.path.is_empty() { occurrence_origin(app, m.occurrence) } else { - app.session.occurrence_placement(&m.path).ok().map(|p| solidcraft_engine::doc::apply_point(&p.world, solidcraft_engine::geom::Vec3::ZERO)) + app.session.occurrence_placement(&m.path).ok().map(|p| solidcraft_engine::doc::apply_point(&p.world, solidcore_record::Vec3::ZERO)) }; } let name = app.session.doc.occurrences.iter().find(|o| o.id == m.occurrence).map(|o| o.name.clone()).unwrap_or_default(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f6ac71395..1bed89a68 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,11 +5,14 @@ //! command has its geometry, so typing a number sets the value at once; Enter applies, Tab //! moves on, Esc cancels. +use crate::ui_kit::BackingTooltipExt as _; use crate::ui_kit::{Container, Surface}; use egui::{Color32, Pos2, Stroke, vec2}; +use solidcore_record::{Vec2, Vec3}; use solidcraft_engine::Sel; use solidcraft_engine::doc::expr::Kind as ValueKind; -use solidcraft_engine::geom::{Mesh, Vec2, Vec3}; +use solidcraft_engine::geom::Mesh; +use solidcraft_engine::geom::prelude::*; use crate::SolveApp; use crate::dialogs::{Dialog, Kind}; @@ -19,8 +22,9 @@ use crate::viewport::{Proj, projected_polygon}; /// Where the dialog's geometry is: a base point and, for values that can be dragged, the /// direction a growing value points. pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { - let st = app.session.world_state(); - let first = d.inputs.first()?.items.first()?; + let st = crate::open_meshing::session_world(&app.session); + let item = anchor_item(app, d); + let Some(first) = &item else { return section_plane(d) }; let (at, normal) = match first { Sel::Profile { sketch, index } => { let ss = st.sketch(*sketch)?; @@ -39,7 +43,7 @@ pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { .collect(); let regions = solidcraft_engine::sketch::merge_regions(®ions); let points: Vec<_> = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect(); - points.iter().fold(solidcraft_engine::geom::Vec2::default(), |sum, p| sum + *p) * (1.0 / points.len().max(1) as f64) + points.iter().fold(solidcore_record::Vec2::default(), |sum, p| sum + *p) * (1.0 / points.len().max(1) as f64) } else { p.region.interior_point() }; @@ -77,7 +81,7 @@ pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { // made, as a body sits at the middle of its box. Sel::Feature { id } => (crate::viewport::feature_bounds(app, *id)?.center(), None), Sel::Plane { name } => { - let pl = solidcraft_engine::geom::Plane::named(name).or_else(|| { + let pl = solidcore_record::Plane::named(name).or_else(|| { solidcraft_engine::view::construction_planes(&app.session).into_iter().find(|(_, n, _)| n == name).map(|(_, _, pl)| pl) })?; (pl.origin, Some(pl.normal())) @@ -87,7 +91,7 @@ pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { Some(match &d.kind { Kind::Extrude { start, .. } => { let n = normal?; - let plane = solidcraft_engine::geom::Plane::from_normal(at, n)?; + let plane = solidcore_record::Plane::from_normal(at, n)?; let from = reference_height(app, d, "From Object", &plane, at).unwrap_or(0.0); let offset = if start.trim().is_empty() { 0.0 } else { crate::length_input::eval(&app.session.doc, start, ValueKind::Length).ok()? }; (at + n * (from + offset), Some(n)) @@ -189,23 +193,23 @@ fn poly_mid(poly: &[Vec2]) -> Option<(Vec2, Vec2)> { last } -pub(crate) fn profile_plane(app: &SolveApp, sketch: u64) -> Option { +pub(crate) fn profile_plane(app: &SolveApp, sketch: u64) -> Option { let component = app.session.doc.feature(sketch)?.component; let state = app.session.model.state(); let plane = state.sketch(sketch)?.plane; let frame = crate::dialogs::feature_frame(&app.session, component); - solidcraft_engine::geom::Plane::new( + solidcore_record::Plane::new( solidcraft_engine::doc::apply_point(&frame, plane.origin), solidcraft_engine::doc::apply_vector(&frame, plane.x), solidcraft_engine::doc::apply_vector(&frame, plane.y), ) } -fn reference_height(app: &SolveApp, d: &Dialog, label: &str, plane: &solidcraft_engine::geom::Plane, centre: Vec3) -> Option { +fn reference_height(app: &SolveApp, d: &Dialog, label: &str, plane: &solidcore_record::Plane, centre: Vec3) -> Option { let point = crate::dialogs::object_point(&d.inputs, label)?; let p = point.as_array()?; let p = Vec3::new(p.first()?.as_f64()?, p.get(1)?.as_f64()?, p.get(2)?.as_f64()?); - Some(solidcraft_engine::doc::object_height(&app.session.world_state(), plane, centre, p)) + Some(solidcraft_engine::doc::object_height(&crate::open_meshing::session_world(&app.session), plane, centre, p)) } /// The two faces at an edge, near `p`: for each, the normal and centroid of its triangle nearest @@ -250,13 +254,57 @@ pub(crate) fn blend_grow_dir(m: &Mesh, index: usize, p: Vec3) -> Option { Some(if edge_concave(m, index, p).unwrap_or(false) { n } else { -n }) } +/// A Section Analysis dialog reopened from its section's own geometry (Show viewport section +/// status): the plane it keeps as numbers when nothing is picked, so its arrow stands there as on +/// a picked plane (#11423). +fn section_plane(d: &Dialog) -> Option<(Vec3, Option)> { + if !matches!(d.kind, Kind::Section { .. }) { + return None; + } + let plane = d.extra.get("plane")?; + let point = |key: &str| serde_json::from_value::<[f64; 3]>(plane.get(key)?.clone()).ok().map(|[x, y, z]| Vec3::new(x, y, z)); + Some((point("origin")?, Some(point("normal")?.normalized()?))) +} + +/// The pick the dialog's arrow sits on: the first, or for a fillet or chamfer reopened from a +/// click on one of its faces (Press Pull), its edge nearest the click, at the point on it nearest +/// the click (#4986). +fn anchor_item(app: &SolveApp, d: &Dialog) -> Option { + let items = &d.inputs.first()?.items; + let first = items.first()?.clone(); + let (Some(hint), Kind::Fillet { .. }) = (d.anchor_hint, &d.kind) else { return Some(first) }; + let st = crate::open_meshing::session_world(&app.session); + let nearest = items + .iter() + .filter_map(|s| { + let Sel::Edge { body, index, .. } = s else { return None }; + let at = nearest_on_polyline(st.body(body)?.mesh().edges.get(*index)?, hint)?; + Some((at.dist(hint), Sel::Edge { body: body.clone(), index: *index, point: at })) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)); + Some(nearest.map_or(first, |(_, s)| s)) +} + +/// The point of the polyline `pts` nearest `p`. +fn nearest_on_polyline(pts: &[Vec3], p: Vec3) -> Option { + let on = |a: Vec3, b: Vec3| { + let ab = b - a; + let len2 = ab.dot(ab); + a + ab * if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 } + }; + pts.windows(2) + .filter_map(|w| if let [a, b] = w { Some(on(*a, *b)) } else { None }) + .min_by(|x, y| x.dist(p).total_cmp(&y.dist(p))) + .or_else(|| pts.first().copied()) +} + /// The directions Distance 1 and Distance 2 of a chamfer of two distances run from its edge at /// `at`: along the face that faces up most, or the other one with Flip, and along the remaining /// face (the kernel's `chamfer_tool_sides` picks them the same way). None for any other dialog. pub(crate) fn chamfer_face_dirs(app: &SolveApp, d: &Dialog, at: Vec3) -> Option<(Vec3, Vec3)> { let Kind::Fillet { chamfer: true, ctype: 1, flip, .. } = &d.kind else { return None }; - let Some(Sel::Edge { body, index, .. }) = d.inputs.first()?.items.first() else { return None }; - let st = app.session.world_state(); + let Some(Sel::Edge { body, index, .. }) = &anchor_item(app, d) else { return None }; + let st = crate::open_meshing::session_world(&app.session); let mesh = st.body(body)?.mesh(); let sides = edge_sides(&mesh, *index, at)?; let [(n1, c1), (n2, c2)] = sides.as_slice() else { return None }; @@ -287,6 +335,7 @@ pub(crate) fn owns_pointer(app: &SolveApp, proj: &Proj, p: Pos2) -> bool { && app.tool.is_none() && crate::browser::occurrence_triad_model(app).is_some_and(|t| crate::gizmo::contains_pointer(proj, &t, p))) || crate::place_gizmo::contains_pointer(app, p) + || app.dialog.as_ref().is_some_and(|d| matches!(&d.kind, Kind::Measure { labels, .. } if labels.contains(p))) } /// Draw the manipulator and the value box (called by the viewport after the model is drawn). @@ -308,10 +357,16 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj app.dialog = Some(d); return; } - if let Kind::Measure { result: Some(r), show, .. } = &d.kind { - measure_line(app, painter, proj, r, *show); - app.dialog = Some(d); - return; + if let Kind::Measure { result, show, labels, .. } = &mut d.kind { + labels.drawn = Default::default(); + if !ui.input(|i| i.pointer.primary_down()) { + labels.grab = None; + } + if let Some(r) = result { + measure_line(app, ui, painter, proj, r, *show, labels); + app.dialog = Some(d); + return; + } } // Move: the triad at the pivot; dragging it sets the distances and angles. Its value box // sits beside it and reads the move's main value, so a drag shows its number and typing @@ -349,7 +404,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj crate::dialogs_move::step_value_field(&mut d, if back { -1 } else { 1 }); d.focus = true; } - let focus = std::mem::take(&mut d.focus); + let focus = take_focus(ui.ctx(), &mut d); if let Some(bs) = at.and_then(|base| proj.to_screen(base)) && let Some((label, _, value)) = d.primary() { @@ -484,15 +539,15 @@ fn offset_plane_quad(proj: &Proj, c: Vec3, n: Vec3, h: f64) -> Option> fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, d: &mut Dialog, base: Vec3, bs: Pos2, dir: Option) { let t = Tokens::get(); let to_span = dir.and_then(|n| { - let plane = solidcraft_engine::geom::Plane::from_normal(base, n)?; + let plane = solidcore_record::Plane::from_normal(base, n)?; reference_height(app, d, "To Object", &plane, base) }); let all_span = if matches!(d.kind, Kind::Extrude { all: true, .. }) { dir.and_then(|n| { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let plane = match d.inputs.first()?.items.first()? { Sel::Profile { sketch, .. } => profile_plane(app, *sketch)?, - _ => solidcraft_engine::geom::Plane::from_normal(base, n)?, + _ => solidcore_record::Plane::from_normal(base, n)?, }; let targets: Vec = d .extra @@ -541,7 +596,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, Kind::SketchModify(crate::sketch_modify_ui::Mod::Offset { mode, .. }) => !crate::sketch_modify_ui::offset_symmetric(*mode), _ => false, }; - let mut focus = std::mem::take(&mut d.focus); + let mut focus = take_focus(ui.ctx(), d); let half_height = app.cam.half_height(); let axis = revolve_axis(app, d); if matches!(d.kind, Kind::Revolve { .. }) { @@ -593,7 +648,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, // An offset plane shows where it will be: at the distance, or through the picked point. let through = crate::dialogs::offset_through_point(d).and_then(|p| match p { Sel::Vertex { point, .. } => Some(*point), - Sel::SketchPoint { id } => sketch_point_at(app, &app.session.world_state(), id), + Sel::SketchPoint { id } => sketch_point_at(app, &crate::open_meshing::session_world(&app.session), id), _ => None, }); if let (Kind::OffsetPlane { offset }, Some(n)) = (&d.kind, dir) @@ -607,7 +662,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, let mut dir = dir; // Extrude taper: a handle beside the arrow tip; dragging it sideways tilts the walls. let cam_right = app.cam.basis().0; - if let (Kind::Extrude { direction: 0 | 1, distance, taper, taper_present, to_offset, .. }, Some(n)) = (&mut d.kind, dir) { + if let (Kind::Extrude { direction: 0 | 1, distance, taper, taper_present, to_offset, smart, .. }, Some(n)) = (&mut d.kind, dir) { let n = n * sign; let span = to_span.map(|span| span.abs() + crate::length_input::eval(&app.session.doc, to_offset, ValueKind::Length).unwrap_or(0.0)).or(all_span); @@ -619,8 +674,8 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, let px = 2.0 * half_height / f64::from(proj.rect.height().max(1.0)); let ang = crate::length_input::eval(&app.session.doc, taper, ValueKind::Angle).ok().filter(|v| v.is_finite()).unwrap_or(0.0); let before = taper.clone(); - let st = app.session.world_state(); - let regions: Vec<&solidcraft_engine::geom::Region2> = d + let st = crate::open_meshing::session_world(&app.session); + let regions: Vec<&solidcore_record::Region2> = d .inputs .first() .map(|i| &i.items[..]) @@ -631,7 +686,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, _ => None, }) .collect(); - let limits = taper_limits(®ions, l.abs()); + let limits = taper_limits(taper_radii_kept(&mut smart.taper_radii, ®ions), l.abs()); taper_handle(ui, painter, proj, base - e * (40.0 * px), n * l, -e, ang, limits, taper); if *taper != before { *taper_present = true; @@ -785,6 +840,28 @@ pub(crate) fn box_place(app: &SolveApp, proj: &Proj) -> BoxPlace { BoxPlace { dialog: app.viewport.dialog_rect, view: Some(proj.rect), handles: None } } +fn boxes_shown_id() -> egui::Id { + egui::Id::new("sc_canvas_value_boxes") +} + +/// Show commands' values in boxes in the view or not, from the preference (the app calls this +/// every frame). +pub(crate) fn set_boxes_shown(ctx: &egui::Context, on: bool) { + ctx.data_mut(|d| d.insert_temp(boxes_shown_id(), on)); +} + +/// Whether a command's values have boxes in the view. Off (Preferences), they are typed in the +/// command window only, and the view stays clear for picking (#9479). +pub(crate) fn boxes_shown(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(boxes_shown_id())).unwrap_or(true) +} + +/// Whether the command's value box takes the keyboard this frame: as the window opens, and after +/// a pick. Without boxes in the view, it is left for the command window's value field (#9479). +fn take_focus(ctx: &egui::Context, d: &mut Dialog) -> bool { + boxes_shown(ctx) && std::mem::take(&mut d.focus) +} + /// The command's main value in the viewport, next to the geometry: the keyboard goes here while /// the window is open, so a number typed straight after a pick sets the value. `at` is its /// top-left corner. `select_all` re-selects the whole field, both right after a pick and on every @@ -838,6 +915,10 @@ fn value_box_full( note: Option<&str>, place: BoxPlace, ) -> Option { + // Off in Preferences: the value is typed in the command window only (#9479). + if !boxes_shown(ui.ctx()) { + return None; + } let t = Tokens::get(); // Held in place while the pointer is over it and value stepping is on (see `value_box`): by // its pivot, the point of the box that sits at `at`, which is not always its top-left corner. @@ -860,7 +941,8 @@ fn value_box_full( // Background: under Preferences, Report a bug and other system windows (#9016). The box is // already kept clear of the command window (#6608), which floats at Middle with Features. Container::new(ui.ctx(), Surface::Canvas).area(area).fixed_pos(at).pivot(pivot).order(egui::Order::Background).show(ui.ctx(), |ui| { - Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { + let frame = Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)); + Container::show_backing(ui, frame, |ui| { ui.horizontal(|ui| { ui.label(egui::RichText::new(crate::i18n::tr_label(label)).color(t.text_dim).size(crate::theme::Tokens::get().font_caption)); let r = crate::ui_kit::canvas_value_field(ui, id, value, keep_tab); @@ -1080,7 +1162,7 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain } let t = Tokens::get(); let Kind::Fillet { chamfer: false, .. } = d.kind else { return false }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let edges: Vec<(std::sync::Arc, usize, Vec3, Vec3)> = d .inputs .first() @@ -1274,9 +1356,85 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain true } +/// The Measure labels in the view the user dragged away from the part (#8510): the distance's, +/// then X, Y and Z's. They last while the measurement does; another one starts them over. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct MeasureLabels { + /// How far each label was dragged from its own place, in points. + offset: [egui::Vec2; 4], + /// Where each was drawn in the last frame, so a press on one drags it instead of picking + /// under it or navigating. + drawn: [Option; 4], + /// The dragged label's offset when the button went down (while it is held). + grab: Option, +} + +impl MeasureLabels { + /// Whether `p` is on one of the labels drawn in the last frame. + pub(crate) fn contains(&self, p: Pos2) -> bool { + self.drawn.iter().flatten().any(|r| r.contains(p)) + } + + /// How far label `i` was dragged (zero: in its own place). + pub(crate) fn offset(&self, i: usize) -> egui::Vec2 { + self.offset.get(i).copied().unwrap_or(egui::Vec2::ZERO) + } +} + +/// Label `i`, drawn at `rect`, follows a drag of the pointer; a double-click puts it back. +fn drag_label(ui: &mut egui::Ui, labels: &mut MeasureLabels, i: usize, rect: egui::Rect) { + if let Some(drawn) = labels.drawn.get_mut(i) { + *drawn = Some(rect); + } + let r = ui.interact(rect, egui::Id::new(("sc_measure_label", i)), egui::Sense::click_and_drag()); + if r.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } else if r.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + let Some(offset) = labels.offset.get_mut(i) else { return }; + if r.double_clicked() { + *offset = egui::Vec2::ZERO; + } else if r.dragged() + && let (Some(from), Some(to)) = (ui.input(|i| i.pointer.press_origin()), r.interact_pointer_pos()) + { + // Where it was at the press, plus how far the pointer went since: the label stays under + // the pointer where it was grabbed. + let start = *labels.grab.get_or_insert(*offset); + let moved = start + (to - from); + // Far enough to leave any view, finite whatever the pointer reports. + if moved.is_finite() { + *offset = moved.clamp(egui::Vec2::splat(-10_000.0), egui::Vec2::splat(10_000.0)); + } + } +} + +/// `rect` moved by a dragged label's `offset`, kept inside the view so it can be dragged back. +fn moved_label(proj: &Proj, rect: egui::Rect, offset: egui::Vec2) -> egui::Rect { + if offset == egui::Vec2::ZERO { + return rect; + } + let bounds = proj.rect.shrink(4.0); + let moved = rect.translate(offset); + let min = egui::pos2( + moved.left().clamp(bounds.left(), (bounds.right() - rect.width()).max(bounds.left())), + moved.top().clamp(bounds.top(), (bounds.bottom() - rect.height()).max(bounds.top())), + ); + egui::Rect::from_min_size(min, rect.size()) +} + /// The measured distance: a line between the ends of the shown measure (the centres for -/// centre to centre, the closest or farthest points) with its length. -fn measure_line(app: &SolveApp, painter: &egui::Painter, proj: &Proj, r: &serde_json::Value, show: Option) { +/// centre to centre, the closest or farthest points) with its length. Its labels can be dragged +/// away from the part; a moved one keeps a leader to what it measures. +fn measure_line( + app: &SolveApp, + ui: &mut egui::Ui, + painter: &egui::Painter, + proj: &Proj, + r: &serde_json::Value, + show: Option, + labels: &mut MeasureLabels, +) { let t = Tokens::get(); let Some((_, d, a, b)) = crate::dialogs::shown_distance(r, show) else { return }; if !a.is_finite() || !b.is_finite() || !d.is_finite() { @@ -1291,15 +1449,20 @@ fn measure_line(app: &SolveApp, painter: &egui::Painter, proj: &Proj, r: &serde_ painter.circle(s, 3.5, t.manipulator, Stroke::new(1.0, Color32::WHITE)); } pick_numbers(painter, sa, sb); - let mid = sa + (sb - sa) * 0.5 + vec2(10.0, -14.0); + let mid = sa + (sb - sa) * 0.5; let galley = painter.layout_no_wrap(crate::prefs::show_mm(app, d, 1), egui::FontId::proportional(crate::theme::Tokens::get().font_label), t.text); - let rect = egui::Rect::from_min_size(mid, galley.size() + vec2(10.0, 6.0)); + let own = egui::Rect::from_min_size(mid + vec2(10.0, -14.0), galley.size() + vec2(10.0, 6.0)); + let rect = moved_label(proj, own, labels.offset(0)); crate::scenario::publish_target("measure:label", rect); if app.preferences.measure_axis_distances { - measure_components(app, painter, proj, a, b, rect); + measure_components(app, ui, painter, proj, a, b, rect, labels); + } + if rect != own { + painter.line_segment([mid, rect.clamp(mid)], Stroke::new(1.0, t.manipulator)); } painter.rect(rect, t.radius_sm.saturating_sub(1), t.overlay, t.control_border_stroke(t.border), egui::StrokeKind::Inside); painter.galley(rect.min + vec2(5.0, 3.0), galley, t.text); + drag_label(ui, labels, 0, rect); } /// "1" and "2" beside the measured line's ends (#6020), as the panel lists the picks: each just @@ -1321,13 +1484,24 @@ fn pick_numbers(painter: &egui::Painter, sa: Pos2, sb: Pos2) { } /// A world-axis-aligned chain between the same two measured points. Zero-length and -/// view-aligned legs still get a label; labels move apart when their projections coincide. -fn measure_components(app: &SolveApp, painter: &egui::Painter, proj: &Proj, a: Vec3, b: Vec3, total: egui::Rect) { +/// view-aligned legs still get a label; labels move apart when their projections coincide, and +/// the user can drag each away (`labels` 1 to 3). +#[allow(clippy::too_many_arguments)] +fn measure_components( + app: &SolveApp, + ui: &mut egui::Ui, + painter: &egui::Painter, + proj: &Proj, + a: Vec3, + b: Vec3, + total: egui::Rect, + labels: &mut MeasureLabels, +) { let t = Tokens::get(); let x = Vec3::new(b.x, a.y, a.z); let y = Vec3::new(b.x, b.y, a.z); let mut occupied = vec![total]; - for (axis, start, end, color) in [("x", a, x, t.axis_x), ("y", x, y, t.axis_y), ("z", y, b, t.axis_z)] { + for (i, (axis, start, end, color)) in [("x", a, x, t.axis_x), ("y", x, y, t.axis_y), ("z", y, b, t.axis_z)].into_iter().enumerate() { let color = color.lerp_to_gamma(t.text, 0.25); let distance = start.dist(end); if !distance.is_finite() { @@ -1375,28 +1549,65 @@ fn measure_components(app: &SolveApp, painter: &egui::Painter, proj: &Proj, a: V } } } + let rect = moved_label(proj, rect, labels.offset(i + 1)); painter.line_segment([at, rect.center()], Stroke::new(0.8, color)); painter.rect(rect, t.radius_sm.saturating_sub(1), t.overlay, Stroke::new(1.0, color), egui::StrokeKind::Inside); painter.galley(rect.min + vec2(5.0, 3.0), galley, t.text); let handle = format!("measure:label:{axis}"); crate::scenario::publish_target(&handle, rect); occupied.push(rect); + drag_label(ui, labels, i + 1, rect); } } -/// The tapers (degrees, least and most) a drag of the taper handle may reach for `regions` -/// extruded `height` (#1602): going in, the sides close the material where they have moved its -/// inradius; going out, they close the smallest hole. Each stops just short, so the drag ends at -/// the largest taper that builds instead of one that fails. A typed angle is not limited. -pub(crate) fn taper_limits(regions: &[&solidcraft_engine::geom::Region2], height: f64) -> (f64, f64) { +/// The tapers (degrees, least and most) a drag of the taper handle may reach for profiles of +/// `radii` ([`taper_radii`]) extruded `height` (#1602): going in, the sides close the material +/// where they have moved its inradius; going out, they close the smallest hole. Each stops just +/// short, so the drag ends at the largest taper that builds instead of one that fails. A typed +/// angle is not limited. +pub(crate) fn taper_limits((inward, outward): (f64, f64), height: f64) -> (f64, f64) { const MAX: f64 = 89.0; - if !(height > 1e-9) || regions.is_empty() { + if !(height > 1e-9) { return (-MAX, MAX); } let at = |r: f64| (0.99 * r / height).atan().to_degrees().min(MAX); + (if inward.is_finite() { -at(inward) } else { -MAX }, if outward.is_finite() { at(outward) } else { MAX }) +} + +/// The smallest inradius of `regions` and of their holes (infinite for none), which +/// [`taper_limits`] turns into angles. A grid search over every side of every loop, so the +/// extrude window keeps it while its profiles stay the same ([`taper_radii_kept`]). +pub(crate) fn taper_radii(regions: &[&solidcore_record::Region2]) -> (f64, f64) { + #[cfg(test)] + TAPER_RADII_WORKED_OUT.with(|n| n.set(n.get() + 1)); let inward = regions.iter().map(|r| r.inradius(1e-3)).fold(f64::INFINITY, f64::min); let outward = regions.iter().flat_map(|r| &r.holes).map(|h| h.inradius(1e-3)).fold(f64::INFINITY, f64::min); - (if inward.is_finite() { -at(inward) } else { -MAX }, if outward.is_finite() { at(outward) } else { MAX }) + (inward, outward) +} + +/// [`taper_radii`] of `regions`, worked out again only when they differ from the ones `kept` +/// holds: the extrude window draws its taper handle every frame, and only the height changes. +fn taper_radii_kept(kept: &mut Option<(Vec, (f64, f64))>, regions: &[&solidcore_record::Region2]) -> (f64, f64) { + if let Some((was, radii)) = kept + && was.len() == regions.len() + && was.iter().zip(regions).all(|(a, b)| a == *b) + { + return *radii; + } + let radii = taper_radii(regions); + *kept = Some((regions.iter().map(|r| (*r).clone()).collect(), radii)); + radii +} + +#[cfg(test)] +thread_local! { + static TAPER_RADII_WORKED_OUT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How often the taper handle's radii were worked out on this thread. +#[cfg(test)] +pub(crate) fn taper_radii_worked_out() -> usize { + TAPER_RADII_WORKED_OUT.with(std::cell::Cell::get) } /// The taper handle: a line from `foot` along the extrude (`span`) leaning by `angle` towards @@ -1605,7 +1816,8 @@ fn draw_revolve( .order(egui::Order::Background) .interactable(false); area.show(ui.ctx(), |ui| { - Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { + let frame = Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)); + Container::show_backing(ui, frame, |ui| { let text = if extent.curved_to { "To surface".into() } else if extent.sweep.is_finite() { @@ -1613,7 +1825,7 @@ fn draw_revolve( } else { "Choose target".into() }; - ui.label(text).on_hover_text(crate::i18n::tr_label("Determined by To Object. Choose Angle to edit the angular extent.")); + ui.label(text).backing_on_hover_text(crate::i18n::tr_label("Determined by To Object. Choose Angle to edit the angular extent.")); }); }); } else if let Kind::Revolve { angle, .. } = &mut d.kind { @@ -1631,7 +1843,7 @@ fn revolve_convention(d: &Dialog) -> solidcraft_engine::doc::RevolveConvention { fn revolve_display_extent(app: &SolveApp, d: &Dialog, axis: (Vec3, Vec3)) -> Option { let Sel::Profile { sketch, .. } = d.inputs.first()?.items.first()? else { return None }; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let ss = state.sketch(*sketch)?; let regions: Vec<_> = d .inputs @@ -1665,7 +1877,9 @@ fn revolve_display_extent(app: &SolveApp, d: &Dialog, axis: (Vec3, Vec3)) -> Opt .ok()?; (angle, other) }; - solidcraft_engine::doc::revolve_extent_with_convention( + // The solid refuses 0° and a sweep past a full turn, and the dialog says so. The handle + // still uses that boundary, so the grab point stays and the angle can be dragged back. + solidcraft_engine::doc::revolve_extent_for_handle( &state, &plane, ®ions, @@ -1798,6 +2012,19 @@ fn arrow(painter: &egui::Painter, a: Pos2, b: Pos2, col: Color32) { mod tests { use super::*; + /// The arrow's point on a picked edge: one point, a zero-length piece, a click past the end. + #[test] + fn nearest_on_polyline_handles_short_edges_and_clicks_past_the_end() { + let p = |x: f64, y: f64| Vec3::new(x, y, 0.0); + assert_eq!(nearest_on_polyline(&[], p(1.0, 1.0)), None); + assert_eq!(nearest_on_polyline(&[p(2.0, 3.0)], p(9.0, 9.0)), Some(p(2.0, 3.0))); + assert_eq!(nearest_on_polyline(&[p(2.0, 3.0), p(2.0, 3.0)], p(9.0, 9.0)), Some(p(2.0, 3.0))); + let edge = [p(0.0, 0.0), p(0.0, 0.0), p(10.0, 0.0)]; + assert_eq!(nearest_on_polyline(&edge, p(4.0, 2.0)), Some(p(4.0, 0.0))); + assert_eq!(nearest_on_polyline(&edge, p(15.0, 1.0)), Some(p(10.0, 0.0))); + assert_eq!(nearest_on_polyline(&edge, p(-3.0, -1.0)), Some(p(0.0, 0.0))); + } + #[test] fn offset_plane_preview_stays_within_its_square() { let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); @@ -1944,8 +2171,9 @@ mod tests { #[cfg(test)] mod taper_limit_tests { - use super::taper_limits; - use solidcraft_engine::geom::{Loop2, Region2, Vec2}; + use super::{taper_limits, taper_radii}; + use solidcore_record::{Loop2, Region2, Vec2}; + use solidcraft_engine::geom::prelude::*; /// #1602: a drag stops just short of the taper that closes the profile, either way. #[test] @@ -1957,16 +2185,16 @@ mod taper_limit_tests { outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 4.0), Vec2::new(0.0, 4.0)]), holes: Vec::new(), }; - let (lo, hi) = taper_limits(&[&rect], 26.0); + let (lo, hi) = taper_limits(taper_radii(&[&rect]), 26.0); assert!(close(lo, -deg(2.0, 26.0)) && hi == 89.0, "{lo} {hi}"); // A ring 10 to 6, 10 high: in, its 4 mm wall; out, its hole of radius 6. let ring = Region2 { outer: Loop2::circle(Vec2::ZERO, 10.0), holes: vec![Loop2::circle(Vec2::ZERO, 6.0).reversed()] }; - let (lo, hi) = taper_limits(&[&ring], 10.0); + let (lo, hi) = taper_limits(taper_radii(&[&ring]), 10.0); assert!(close(lo, -deg(2.0, 10.0)) && close(hi, deg(6.0, 10.0)), "{lo} {hi}"); // The tightest of several profiles; no profile or no height, no limit. - let (lo, _) = taper_limits(&[&ring, &rect], 10.0); + let (lo, _) = taper_limits(taper_radii(&[&ring, &rect]), 10.0); assert!(close(lo, -deg(2.0, 10.0))); - assert_eq!(taper_limits(&[], 10.0), (-89.0, 89.0)); - assert_eq!(taper_limits(&[&rect], 0.0), (-89.0, 89.0)); + assert_eq!(taper_limits(taper_radii(&[]), 10.0), (-89.0, 89.0)); + assert_eq!(taper_limits(taper_radii(&[&rect]), 0.0), (-89.0, 89.0)); } } diff --git a/crates/ui-egui/src/colour_tokens_tests.rs b/crates/ui-egui/src/colour_tokens_tests.rs index 8be8a444c..68aac2bb6 100644 --- a/crates/ui-egui/src/colour_tokens_tests.rs +++ b/crates/ui-egui/src/colour_tokens_tests.rs @@ -31,6 +31,8 @@ fn moved_colours_keep_the_values_they_were_drawn_with() { assert_eq!(t.logo, [Color32::from_rgb(96, 158, 236), Color32::from_rgb(58, 136, 238), Color32::from_rgb(55, 108, 197)]); assert_eq!(t.icons.marker_halo, Color32::from_black_alpha(150)); assert_eq!(t.icons.agent, Color32::from_rgb(168, 85, 247)); + assert_eq!(t.figure_white, Color32::WHITE); + assert_eq!(t.figure_black, Color32::BLACK); } let (l, d) = (Tokens::light(), Tokens::dark()); assert_eq!((l.bend_up, l.bend_down), (Color32::from_rgb(30, 140, 50), Color32::from_rgb(200, 90, 20))); @@ -69,7 +71,7 @@ fn stroke_colours(shapes: &[egui::epaint::ClippedShape]) -> std::collections::BT fn every_axis_is_drawn_in_one_set_of_colours() { use crate::theme::{ColorVision, set_dark, set_vision}; use egui::{Pos2, Rect, vec2}; - use solidcraft_engine::geom::Vec3; + use solidcore_record::Vec3; let ctx = crate::fonts::test_context(); let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); let cam = solidcraft_engine::render::Camera::default(); @@ -276,9 +278,10 @@ fn every_engine_colour_tag_is_placed() { "AXIS_Y", "AXIS_Z", ]; - // Bodies, edges, profiles, the grid and the background: the GPU viewport draws these from - // their own tokens; the engine's values are only the headless snapshot's. - const NEUTRAL: &[&str] = &["BODY", "BODY_SELECTED", "EDGE", "PROFILE", "GRID", "GRID_MAJOR", "BG_TOP", "BG_BOTTOM", "SECTION_CAP"]; + // Bodies, edges, profiles, the grid, the background and Isocurve Analysis curves (the accent): + // the GPU viewport draws these from their own tokens; the engine's values are only the + // headless snapshot's. + const NEUTRAL: &[&str] = &["BODY", "BODY_SELECTED", "EDGE", "PROFILE", "GRID", "GRID_MAJOR", "BG_TOP", "BG_BOTTOM", "SECTION_CAP", "ISOCURVE"]; let src = include_str!("../../engine/src/view.rs"); let start = src.find("pub mod colors {").unwrap_or(0); let block = &src[start..]; diff --git a/crates/ui-egui/src/colour_vision_tests.rs b/crates/ui-egui/src/colour_vision_tests.rs index 5e9fdbe78..be774a3ea 100644 --- a/crates/ui-egui/src/colour_vision_tests.rs +++ b/crates/ui-egui/src/colour_vision_tests.rs @@ -287,6 +287,43 @@ fn groups(t: &Tokens) -> Vec { group("card hints", &[("form_dim", t.form_dim)], &[("dialog_body", t.dialog_body)]), group("card primary", &[("form_primary", t.form_primary)], &[("dialog_body", t.dialog_body)]), group("navigation status", &[("form_primary", t.form_primary), ("warning", t.warning)], &[("dialog_body", t.dialog_body)]), + // NAVIGATOR_AXES draws all three axes on the figure ground; its filled tips have letters. + group( + "Preferences figure axes", + &[("figure_axis_x", t.figure_axis_x), ("figure_axis_y", t.figure_axis_y), ("figure_axis_z", t.figure_axis_z)], + &[("figure_ground", t.figure_ground)], + ), + group( + "Preferences axis letters", + &[("pref_on_accent", t.pref_on_accent)], + &[("figure_axis_x", t.figure_axis_x), ("figure_axis_y", t.figure_axis_y), ("figure_axis_z", t.figure_axis_z)], + ), + // Selection outlines and active geometry are drawn over the model and paper surfaces. + group( + "Preferences figure actions", + &[("figure_accent", t.figure_accent)], + &[ + ("figure_ground", t.figure_ground), + ("figure_card", t.figure_card), + ("figure_face_top", t.figure_face_top), + ("figure_face_left", t.figure_face_left), + ("figure_face_right", t.figure_face_right), + ], + ), + // ASSEMBLY_MOVE and the orbit figures distinguish the active ring from the reference dot. + group("Preferences figure markers", &[("figure_accent", t.figure_accent), ("figure_reference", t.figure_reference)], &[]), + group("Preferences reference dots", &[("figure_reference", t.figure_reference)], &[("figure_ground", t.figure_ground)]), + // SKETCH_STATE_ICONS shows these three states together on top-face pads. + group( + "Preferences sketch states", + &[("figure_ok", t.figure_ok), ("figure_warn", t.figure_warn), ("figure_conflict", t.figure_conflict)], + &[("figure_ground", t.figure_ground), ("figure_face_top", t.figure_face_top)], + ), + // Badge text and selected-card marks use these exact pairs; WCAG ratios are also + // guarded by theme::tests::preferences_foreground_pairs_hold_small_text_contrast. + group("Preferences warning badge", &[("pref_note", t.pref_note)], &[("pref_note_fill", t.pref_note_fill)]), + group("Preferences success badge", &[("pref_ok", t.pref_ok)], &[("pref_ok_fill", t.pref_ok_fill)]), + group("Preferences selected marks", &[("pref_on_accent", t.pref_on_accent)], &[("figure_accent", t.figure_accent)]), // Validation is identified by its words as well as colour. Measure both the // ink and badge surfaces against the corresponding failure states. group( @@ -311,6 +348,7 @@ fn groups(t: &Tokens) -> Vec { ], ), group("bend lines", &[("bend_up", t.bend_up), ("bend_down", t.bend_down)], &[("viewport_top", t.viewport_top)]), + group("curvature comb", &[("comb_envelope", t.comb_envelope), ("comb_teeth", t.comb_teeth)], &[("viewport_top", t.viewport_top)]), group("box select", &[("box_window", t.box_window), ("box_crossing", t.box_crossing)], &[("viewport_top", t.viewport_top)]), // Sketch dimensions (#7861): their lines and values, driving and driven, apart from the // curves they measure, the construction lines and the conflict red (each its own group: @@ -338,7 +376,11 @@ fn groups(t: &Tokens) -> Vec { ], &[], ), - group("section", &[("section_cap", t.section_cap)], &[("body", t.body)]), + group( + "section", + &[("section_cap", t.section_cap), ("section_hatch[0]", t.section_hatch[0]), ("section_hatch[1]", t.section_hatch[1])], + &[("body", t.body)], + ), group("interference", &[("interference", t.interference)], &[("body", t.body)]), group( "continuity seams", @@ -396,6 +438,35 @@ fn groups(t: &Tokens) -> Vec { out.push(group(name, &[(key, fill)], &[("panel", t.panel)])); } out.push(group("dark pill text", &[("tab_on_fill_dark", t.tab_on_fill_dark)], &[("mesh_fill", t.mesh_fill)])); + // Miniature figures identify axes by labels and direction, reference points by + // position. Each ink must remain visible on its surfaces; + // the hues are not the only way to distinguish these marks from one another. + for (key, ink) in [ + ("figure_line", t.figure_line), + ("figure_accent", t.figure_accent), + ("figure_reference", t.figure_reference), + ("figure_axis_x", t.figure_axis_x), + ("figure_axis_y", t.figure_axis_y), + ("figure_axis_z", t.figure_axis_z), + ("figure_ok", t.figure_ok), + ("figure_warn", t.figure_warn), + ] { + out.push(group(key, &[(key, ink)], &[("figure_ground", t.figure_ground), ("figure_card", t.figure_card)])); + } + // The static sketch-state illustration uses success and warm alert inks on + // the top face. Keep success apart from each alert; the two warm warning + // shades are not a colour-only legend for live solver states. + out.push(group( + "preferences sketch states", + &[("figure_ok", t.figure_ok), ("figure_warn", t.figure_warn)], + &[("figure_face_top", t.figure_face_top)], + )); + out.push(group("preferences sketch note", &[("figure_ok", t.figure_ok), ("pref_note", t.pref_note)], &[("figure_face_top", t.figure_face_top)])); + // Badge words identify the status; check the ink against its own fill, as for + // tab text above, rather than treating an ink and its tint as competing states. + out.push(group("preferences note", &[("pref_note", t.pref_note)], &[("pref_note_fill", t.pref_note_fill)])); + out.push(group("preferences success", &[("pref_ok", t.pref_ok)], &[("pref_ok_fill", t.pref_ok_fill)])); + out.push(group("preferences accent ink", &[("pref_on_accent", t.pref_on_accent)], &[("form_primary", t.form_primary)])); // The removed part of a cut preview is translucent over the body. if let Some(sel) = out.iter_mut().find(|g| g.name == "selection") { sel.members.push(("preview_cut", over(t.preview_cut, t.body))); @@ -409,6 +480,12 @@ const SHADED: [&str; 2] = ["analysis.draft", "analysis.access"]; /// Tokens no colour vision mode needs to keep apart, and why. A new token fails /// `every_token_is_measured_or_carries_no_meaning` until it is in a group above or here. const NO_MEANING: &[(&str, &str)] = &[ + ("figure_white", "neutral axis label and highlight ink; letters identify the axes"), + ("figure_black", "neutral hatching and shadows; pattern and geometry carry the meaning"), + ("pref_well", "neutral well behind a labelled control or illustration"), + ("pref_disabled", "dimmed control ink; label and disabled interaction identify availability"), + ("figure_highlight", "neutral model lighting; face geometry and outlines identify the model, not the highlight's hue"), + ("figure_shadow", "neutral model shading, never an axis, selection or status category"), ("nav_hover", "neutral hover surface; placement and pointer feedback identify the control"), ("nav_press", "neutral pressed/open surface; interaction and menu presence identify the state"), ("nav_dim", "neutral secondary ink; the Later label identifies the unavailable option"), @@ -483,6 +560,7 @@ const NO_MEANING: &[(&str, &str)] = &[ ("font_compass", "layout dimension"), ("font_subtitle", "layout dimension"), ("font_intro", "layout dimension"), + ("font_page_heading", "layout dimension"), ("font_article_heading", "layout dimension"), ("font_title", "layout dimension"), ("font_display", "layout dimension"), @@ -772,6 +850,12 @@ fn each_mode_changes_only_its_table() { let red_green_both = [ "axis_x", "axis_y", + "figure_axis_x", + "figure_axis_y", + "figure_axis_z", + "figure_ok", + "figure_warn", + "figure_conflict", "analysis.draft", "analysis.access", "analysis.hatch", @@ -797,6 +881,12 @@ fn each_mode_changes_only_its_table() { false, ColorVision::Tritan, set(&[ + "figure_axis_x", + "figure_axis_y", + "figure_axis_z", + "figure_ok", + "figure_warn", + "figure_conflict", "surface_accent", "mesh_accent", "form_accent", @@ -814,6 +904,12 @@ fn each_mode_changes_only_its_table() { true, ColorVision::Tritan, set(&[ + "figure_axis_x", + "figure_axis_y", + "figure_axis_z", + "figure_ok", + "figure_warn", + "figure_conflict", "surface_accent", "mesh_accent", "form_accent", @@ -1056,33 +1152,86 @@ fn ui_prefs_sets_each_mode_and_refuses_anything_else() { /// colours. The status chips beside it keep theirs in every mode. #[test] fn the_sample_previews_the_mode_being_chosen() { - let mut h = crate::scenario::Harness::new(); - crate::prefs::control(&mut h.app, &json!({"open": "Interface"})).unwrap(); - let lines = |h: &crate::scenario::Harness| { - let mut out = BTreeSet::new(); - for s in &h.shapes { - crate::test_support::each_shape(&s.shape, &mut |shape| { - if let egui::Shape::LineSegment { stroke, .. } = shape { - out.insert(stroke.color.to_array()); - } - }); - } - out - }; - for mode in [ColorVision::Protan, ColorVision::Tritan, ColorVision::Off] { - crate::prefs::control(&mut h.app, &json!({"color_vision": mode.id()})).unwrap(); - h.frames(2); - let (want, off) = (Tokens::get_in(mode), Tokens::get_in(ColorVision::Off)); - let painted = lines(&h); - for (name, c) in [("axis_x", want.axis_x), ("axis_y", want.axis_y), ("sketch_locked", want.sketch_locked)] { - assert!(painted.contains(&c.to_array()), "{mode:?}: the sample draws {name} {c:?}"); - } - if mode != ColorVision::Off { - let changed = [(want.axis_x, off.axis_x), (want.sketch_locked, off.sketch_locked)]; - assert!(changed.iter().any(|(a, b)| a != b), "{mode:?} recolours what the sample shows"); + for base in ["light", "dark"] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + crate::prefs::control(&mut h.app, &json!({"theme":base,"language":"en","open":"Interface"})).unwrap(); + h.frames(3); + for mode in ColorVision::ALL { + let handle = format!("prefs:color_vision:{}", mode.id()); + crate::prefs::reveal_preference(&mut h, &handle); + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.color_vision, mode, "the real Appearance segments edit the preference"); + crate::prefs::reveal_preference(&mut h, "prefs:colour_vision_samples"); + let (want, off) = (Tokens::get_in(mode), Tokens::get_in(ColorVision::Off)); + if mode != ColorVision::Off { + assert!( + want.axis_x != off.axis_x || want.sketch_locked != off.sketch_locked, + "{base} {mode:?}: axis X or locked sketch geometry must differ from Off" + ); + } + // The shared painter clips each figure to its fitted cell. Isolate those actual + // page shapes by that clip, preserving their order and geometry. Cropping the whole + // page still tessellates unrelated atlas content, which requires its real textures. + // Rounded vector shapes also use atlas-backed discs, so retain the rendered page's atlas. + let textures = std::collections::HashMap::from([(egui::TextureId::default(), h.ctx.fonts(|fonts| fonts.image()))]); + let images: Vec<_> = (0..6) + .map(|i| { + let cell = crate::scenario::rect_of(&format!("prefs:colour_vision_sample:{i}")).unwrap(); + let artwork: Vec<_> = h + .shapes + .iter() + .filter(|shape| shape.clip_rect.min.distance(cell.min) < 0.01 && shape.clip_rect.max.distance(cell.max) < 0.01) + .cloned() + .collect(); + assert!(!artwork.is_empty(), "{base} {mode:?}: sample {i} has actual cell-clipped artwork"); + crate::ui_kit::raster_test_shapes(&h.ctx, artwork, 1.0, cell, &textures) + }) + .collect(); + let near = |actual: [u8; 4], expected: egui::Color32| actual.into_iter().zip(expected.to_array()).all(|(a, b)| a.abs_diff(b) <= 2); + let pixel = |i: usize, x, y, colour| { + assert!( + near(images[i].get_pixel(x, y).0, colour), + "{base} {mode:?}: sample {i} pixel {x},{y} must be {colour:?}, got {:?}", + images[i].get_pixel(x, y) + ); + }; + pixel(0, 42, 22, want.sketch_locked); + pixel(1, 42, 22, want.sketch_projected); + pixel(2, 40, 34, want.axis_x); + pixel(2, 14, 20, want.axis_y); + // The canonical bends are dashed. Require visible runs in each semantic colour. + for (colour, y) in [(want.bend_up, 14), (want.bend_down, 30)] { + assert!((12..72).any(|x| near(images[3].get_pixel(x, y).0, colour)), "{base} {mode:?}: bend stroke {colour:?}"); + } + pixel(4, 18, 18, crate::theme::srgb(want.analysis.draft[0])); + pixel(4, 40, 18, crate::theme::srgb(want.analysis.draft[1])); + pixel(4, 2, 2, want.figure_ground); + let negative = crate::theme::srgb(want.analysis.draft[2]); + let hatch = crate::theme::srgb(want.analysis.draft[2].map(|c| c * 0.6)); + let draft = &images[4]; + let band: Vec<_> = (54..74).flat_map(|x| (24..34).map(move |y| draft.get_pixel(x, y).0)).collect(); + assert!(band.iter().any(|p| near(*p, negative)), "{base} {mode:?}: Draft retains its negative analysis colour"); + assert!(band.iter().any(|p| near(*p, hatch)), "{base} {mode:?}: Draft hatching is visible, including Off"); + // Both diagonals must be visible inside the error box; a blank rounded box fails. + for (x, y) in [(38, 19), (46, 18), (38, 25), (46, 25)] { + pixel(5, x, y, want.error); + } + pixel(5, 24, 22, want.timeline_item_error); + let area = crate::scenario::rect_of("prefs:colour_vision_samples").unwrap(); + let page = crate::scenario::rect_of("prefs:page_body").unwrap(); + assert!(page.expand(1.0).contains_rect(area)); + for i in 0..6 { + let cell = crate::scenario::rect_of(&format!("prefs:colour_vision_sample:{i}")).unwrap(); + assert!(area.contains_rect(cell)); + assert_eq!(cell.size(), egui::vec2(84.0, 44.0)); + } + assert_eq!(crate::scenario::rects("prefs:status_sample:").len(), 4); } + crate::prefs::control(&mut h.app, &json!({"button":"cancel"})).unwrap(); + assert_eq!(h.app.preferences.color_vision, ColorVision::Off); } - crate::prefs::control(&mut h.app, &json!({"button": "cancel"})).unwrap(); } #[test] diff --git a/crates/ui-egui/src/command_help.rs b/crates/ui-egui/src/command_help.rs index 390966946..0901b8c25 100644 --- a/crates/ui-egui/src/command_help.rs +++ b/crates/ui-egui/src/command_help.rs @@ -2,19 +2,188 @@ //! tool name when the pointer rests on its button. The names stay as they are; the help is a //! separate message `help.` in the catalogs, so a tool without help keeps its plain //! tooltip. Text only for now; pictures and animations are a later step. A new toolbar command -//! ships with its help: `every_toolbar_command_has_help_or_is_on_the_backlog` fails otherwise. +//! ships with its help: `every_toolbar_command_has_help` fails otherwise. use crate::i18n; +use crate::ui_kit::BackingTooltipExt as _; /// The commands that have help text. Each one needs a `help.` message in the catalogs. pub const DOCUMENTED: &[&str] = &[ "appearance.assign", + "assembly.bom", + "canvas.decal", + "canvas.edit", + "canvas.insert", + "component.break_link", + "component.capture_position", + "component.create", "component.finish_edit", + "component.from_bodies", + "component.insert_design", + "component.properties", + "component.revert_position", + "component.update_links", + "config.configure", + "config.preview", + "config.rules", + "config.table", + "construct.axis.edge", + "construct.axis.normal_to_face", + "construct.axis.through_cylinder", + "construct.axis.two_planes", + "construct.axis.two_points", + "construct.plane.along_path", + "construct.plane.at_angle", + "construct.plane.axis_point", + "construct.plane.midplane", + "construct.plane.offset", + "construct.plane.perpendicular", + "construct.plane.tangent", + "construct.plane.three_points", + "construct.plane.two_edges", + "construct.point.along_path", + "construct.point.center", + "construct.point.edge_plane", + "construct.point.three_planes", + "construct.point.two_edges", + "construct.point.vertex", + "contact.check", + "contact.create", + "contact.disable_all", + "contact.edit", + "contact.enable_all", + "contact.enable_sets", + "contact.list", + "document.inspect", + "document.units", + "edit.checkpoint", + "edit.restore_checkpoint", + "explode.create", "face.delete", + "file.insert_mesh", + "file.insert_step", + "file.save_mesh", + "file.send_to_slicer", + "frame.member", + "inspect.accessibility", + "inspect.center_of_mass", + "inspect.colored_components", + "inspect.compare", + "inspect.continuity", + "inspect.curvature_comb", + "inspect.curvature_map", + "inspect.draft", + "inspect.environment_map", + "inspect.interference", + "inspect.isocurve", + "inspect.measure", + "inspect.minimum_radius", + "inspect.section", + "inspect.zebra", + "joint.as_built", + "joint.cam", + "joint.create", + "joint.drive", + "joint.gear", + "joint.limits", + "joint.motion_link", + "joint.origin", + "joint.rack_pinion", + "joint.reach", + "joint.rigid_group", + "joint.screw", + "layout.apply", + "layout.get", + "layout.reset", + "layout.save", + "layout.workspace.select", + "library.apply", + "library.export", + "library.inspect", "material.assign", + "material.properties.validate", + "mesh.convert", + "motion.study", + "motion.trace", + "occurrence.ground", "occurrence.move", + "panel.activate", + "panel.close", + "panel.collapse", + "panel.dismiss", + "panel.float", + "panel.focus", + "panel.list", + "panel.move", + "panel.native_close", + "panel.open", + "panel.peek", + "panel.popout", + "panel.reset_pair", + "panel.resize", + "panel.resize_pair", "parameters.change", + "parameters.export", + "parameters.graph", + "parameters.import", + "parameters.move", + "parts.fastener", + "parts.insert", + "parts.library", + "parts.resize", + "plastic.assign_rule", + "plastic.boss", + "plastic.lip", + "plastic.manage_rules", + "plastic.rest", + "plastic.snap_fit", "pointcloud.insert", + "sheet.convert", + "sheet.export_bend_table", + "sheet.export_dxf", + "sheet.flange", + "sheet.flat_pattern", + "sheet.fold", + "sheet.hem", + "sheet.manage_rules", + "sheet.path_flange", + "sheet.perforate", + "sheet.refold", + "sheet.unfold", + "sketch.arc.center_point", + "sketch.arc.tangent", + "sketch.arc.three_point", + "sketch.arc3d", + "sketch.auto_constrain", + "sketch.auto_constrain_from_datum", + "sketch.blend_curve", + "sketch.break", + "sketch.cancel", + "sketch.centerline", + "sketch.chamfer.distance_angle", + "sketch.chamfer.equal_distance", + "sketch.chamfer.two_distance", + "sketch.circle.center", + "sketch.circle.three_point", + "sketch.circle.three_tangent", + "sketch.circle.two_point", + "sketch.circle.two_tangent", + "sketch.conic", + "sketch.constrainer", + "sketch.constraint.coincident", + "sketch.constraint.collinear", + "sketch.constraint.concentric", + "sketch.constraint.curvature", + "sketch.constraint.equal", + "sketch.constraint.fix", + "sketch.constraint.horizontal_vertical", + "sketch.constraint.midpoint", + "sketch.constraint.parallel", + "sketch.constraint.perpendicular", + "sketch.constraint.polygon", + "sketch.constraint.symmetry", + "sketch.constraint.tangent", + "sketch.construction", "sketch.construction_line", "sketch.construction_line.angle", "sketch.construction_line.bisector", @@ -25,11 +194,71 @@ pub const DOCUMENTED: &[&str] = &[ "sketch.construction_line.tangent_external", "sketch.construction_line.tangent_two", "sketch.construction_line.vertical", + "sketch.copy", + "sketch.create", + "sketch.cut", + "sketch.dimension", + "sketch.edit", + "sketch.ellipse", "sketch.equation_curve", + "sketch.extend", + "sketch.fillet", + "sketch.finish", + "sketch.finish_auto_constrain", + "sketch.fit_curves_to_section", + "sketch.include_3d", + "sketch.infinite", + "sketch.insert_dxf", + "sketch.insert_svg", + "sketch.inspect", + "sketch.intersect", + "sketch.intersection_curve", + "sketch.isoparametric_curve", + "sketch.line", + "sketch.line.midpoint", + "sketch.line3d", + "sketch.mirror", + "sketch.move", + "sketch.offset", + "sketch.paste", + "sketch.pattern.circular", + "sketch.pattern.rectangular", + "sketch.point", + "sketch.point3d", + "sketch.polygon.circumscribed", + "sketch.polygon.edge", + "sketch.polygon.inscribed", + "sketch.project", + "sketch.project_to_surface", + "sketch.rectangle.center", + "sketch.rectangle.rounded", + "sketch.rectangle.three_point", + "sketch.rectangle.two_point", + "sketch.scale", + "sketch.slot.arc_center", + "sketch.slot.arc_three_point", + "sketch.slot.center_point", + "sketch.slot.center_to_center", + "sketch.slot.overall", + "sketch.spline.control_point", + "sketch.spline.control_point_5", + "sketch.spline.fit_point", + "sketch.spline3d", + "sketch.spun_profile", + "sketch.text", + "sketch.transform", + "sketch.trim", "solid.align", + "solid.boundary_fill", + "solid.bounding_solid", + "solid.box", "solid.chamfer", + "solid.coil", "solid.combine", + "solid.cone", + "solid.cylinder", "solid.draft", + "solid.emboss", "solid.extrude", "solid.fillet", "solid.hole", @@ -38,19 +267,59 @@ pub const DOCUMENTED: &[&str] = &[ "solid.move", "solid.offset_face", "solid.pattern.circular", + "solid.pattern.path", "solid.pattern.rectangular", + "solid.pipe", "solid.press_pull", "solid.remove", "solid.replace_face", "solid.revolve", + "solid.rib", "solid.scale", "solid.shell", + "solid.sphere", "solid.split_body", "solid.split_face", "solid.sweep", + "solid.thread", + "solid.torus", + "solid.web", + "surface.blend", + "surface.boundary", + "surface.extend", + "surface.extrude", + "surface.fair", + "surface.loft", + "surface.match", + "surface.offset", + "surface.patch", + "surface.reverse_normal", + "surface.revolve", + "surface.ruled", + "surface.stitch", + "surface.sweep", + "surface.thicken", + "surface.trim", + "surface.unstitch", + "surface.untrim", "timeline.compute_all", "timeline.delete", + "timeline.dependents", "timeline.play", + "view.apply", + "view.delete", + "view.fit", + "view.grid", + "view.ground_shadow", + "view.home", + "view.list", + "view.navigate", + "view.navigation_bar", + "view.rename", + "view.save", + "view.spin", + "view.tool", + "view.visual_style", ]; /// The help for `command` in the current language, when it has any. @@ -67,7 +336,7 @@ pub fn help(command: &str) -> Option { /// 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| { + response.backing_on_hover_ui(move |ui| { ui.set_max_width(300.0); ui.label(tip); if let Some(help) = help { @@ -103,257 +372,6 @@ mod tests { .collect() } - /// Toolbar commands written before every tool needed help (#2758). The list only shrinks: write - /// the help for one of these and take it off; a new toolbar command never goes on it. - const BACKLOG: &[&str] = &[ - "assembly.bom", - "canvas.decal", - "canvas.edit", - "canvas.insert", - "component.break_link", - "component.capture_position", - "component.create", - "component.from_bodies", - "component.insert_design", - "component.properties", - "component.revert_position", - "component.update_links", - "config.configure", - "config.preview", - "config.rules", - "config.table", - "construct.axis.edge", - "construct.axis.normal_to_face", - "construct.axis.through_cylinder", - "construct.axis.two_planes", - "construct.axis.two_points", - "construct.plane.along_path", - "construct.plane.at_angle", - "construct.plane.midplane", - "construct.plane.offset", - "construct.plane.perpendicular", - "construct.plane.tangent", - "construct.plane.three_points", - "construct.plane.two_edges", - "construct.point.along_path", - "construct.point.center", - "construct.point.edge_plane", - "construct.point.three_planes", - "construct.point.two_edges", - "construct.point.vertex", - "contact.check", - "contact.create", - "contact.disable_all", - "contact.edit", - "contact.enable_all", - "contact.enable_sets", - "contact.list", - "document.inspect", - "document.units", - "edit.checkpoint", - "edit.restore_checkpoint", - "explode.create", - "file.insert_mesh", - "file.insert_step", - "file.save_mesh", - "file.send_to_slicer", - "frame.member", - "inspect.accessibility", - "inspect.center_of_mass", - "inspect.colored_components", - "inspect.compare", - "inspect.continuity", - "inspect.curvature_comb", - "inspect.curvature_map", - "inspect.draft", - "inspect.environment_map", - "inspect.interference", - "inspect.isocurve", - "inspect.measure", - "inspect.minimum_radius", - "inspect.section", - "inspect.zebra", - "joint.as_built", - "joint.cam", - "joint.create", - "joint.drive", - "joint.gear", - "joint.limits", - "joint.motion_link", - "joint.origin", - "joint.rack_pinion", - "joint.reach", - "joint.rigid_group", - "joint.screw", - "library.apply", - "library.export", - "library.inspect", - "material.properties.validate", - "mesh.convert", - "motion.study", - "motion.trace", - "occurrence.ground", - "parameters.export", - "parameters.graph", - "parameters.import", - "parameters.move", - "parts.fastener", - "parts.insert", - "parts.library", - "parts.resize", - "plastic.assign_rule", - "plastic.boss", - "plastic.lip", - "plastic.manage_rules", - "plastic.rest", - "plastic.snap_fit", - "sheet.convert", - "sheet.export_bend_table", - "sheet.export_dxf", - "sheet.flange", - "sheet.flat_pattern", - "sheet.fold", - "sheet.hem", - "sheet.manage_rules", - "sheet.path_flange", - "sheet.perforate", - "sheet.refold", - "sheet.unfold", - "sketch.arc.center_point", - "sketch.arc.tangent", - "sketch.arc.three_point", - "sketch.arc3d", - "sketch.auto_constrain", - "sketch.auto_constrain_from_datum", - "sketch.blend_curve", - "sketch.break", - "sketch.cancel", - "sketch.centerline", - "sketch.chamfer.distance_angle", - "sketch.chamfer.equal_distance", - "sketch.chamfer.two_distance", - "sketch.circle.center", - "sketch.circle.three_point", - "sketch.circle.three_tangent", - "sketch.circle.two_point", - "sketch.circle.two_tangent", - "sketch.conic", - "sketch.constrainer", - "sketch.constraint.coincident", - "sketch.constraint.collinear", - "sketch.constraint.concentric", - "sketch.constraint.curvature", - "sketch.constraint.equal", - "sketch.constraint.fix", - "sketch.constraint.horizontal_vertical", - "sketch.constraint.midpoint", - "sketch.constraint.parallel", - "sketch.constraint.perpendicular", - "sketch.constraint.polygon", - "sketch.constraint.symmetry", - "sketch.constraint.tangent", - "sketch.construction", - "sketch.copy", - "sketch.create", - "sketch.cut", - "sketch.dimension", - "sketch.edit", - "sketch.ellipse", - "sketch.extend", - "sketch.fillet", - "sketch.finish", - "sketch.finish_auto_constrain", - "sketch.fit_curves_to_section", - "sketch.include_3d", - "sketch.infinite", - "sketch.insert_dxf", - "sketch.insert_svg", - "sketch.intersect", - "sketch.intersection_curve", - "sketch.isoparametric_curve", - "sketch.line", - "sketch.line.midpoint", - "sketch.line3d", - "sketch.mirror", - "sketch.move", - "sketch.offset", - "sketch.paste", - "sketch.pattern.circular", - "sketch.pattern.rectangular", - "sketch.point", - "sketch.point3d", - "sketch.polygon.circumscribed", - "sketch.polygon.edge", - "sketch.polygon.inscribed", - "sketch.project", - "sketch.project_to_surface", - "sketch.rectangle.center", - "sketch.rectangle.rounded", - "sketch.rectangle.three_point", - "sketch.rectangle.two_point", - "sketch.scale", - "sketch.slot.arc_center", - "sketch.slot.arc_three_point", - "sketch.slot.center_point", - "sketch.slot.center_to_center", - "sketch.slot.overall", - "sketch.spline.control_point", - "sketch.spline.control_point_5", - "sketch.spline.fit_point", - "sketch.spline3d", - "sketch.spun_profile", - "sketch.text", - "sketch.transform", - "sketch.trim", - "solid.boundary_fill", - "solid.bounding_solid", - "solid.box", - "solid.coil", - "solid.cone", - "solid.cylinder", - "solid.emboss", - "solid.pattern.path", - "solid.pipe", - "solid.rib", - "solid.sphere", - "solid.thread", - "solid.torus", - "solid.web", - "surface.blend", - "surface.boundary", - "surface.extend", - "surface.extrude", - "surface.fair", - "surface.loft", - "surface.match", - "surface.offset", - "surface.patch", - "surface.reverse_normal", - "surface.revolve", - "surface.ruled", - "surface.stitch", - "surface.sweep", - "surface.thicken", - "surface.trim", - "surface.unstitch", - "surface.untrim", - "timeline.dependents", - "view.apply", - "view.delete", - "view.fit", - "view.grid", - "view.ground_shadow", - "view.home", - "view.list", - "view.navigate", - "view.navigation_bar", - "view.rename", - "view.save", - "view.spin", - "view.tool", - "view.visual_style", - ]; - /// Every command the ribbon offers people, gathered the way the toolbar lays out its panels. A /// planned command only says "not supported yet"; it gets its help when it is built. fn toolbar_commands() -> BTreeSet<&'static str> { @@ -368,17 +386,13 @@ mod tests { } #[test] - fn every_toolbar_command_has_help_or_is_on_the_backlog() { - let toolbar = toolbar_commands(); - let missing: Vec<_> = toolbar.iter().filter(|id| !DOCUMENTED.contains(id) && !BACKLOG.contains(id)).collect(); - let stale: Vec<_> = BACKLOG.iter().filter(|id| !toolbar.contains(*id) || DOCUMENTED.contains(id)).collect(); + fn every_toolbar_command_has_help() { + let missing: Vec<_> = toolbar_commands().into_iter().filter(|id| !DOCUMENTED.contains(id)).collect(); assert!( - missing.is_empty() && stale.is_empty(), + missing.is_empty(), "toolbar commands without help: {missing:?}. Add `help.` (two short sentences: what the tool does, \ - then when to use it) to a file in assets/locales/pending/ and the id to DOCUMENTED. Take these off the backlog \ - (documented now, or not on the toolbar): {stale:?}" + then when to use it) to a file in assets/locales/pending/ and the id to DOCUMENTED." ); - assert!(BACKLOG.is_sorted()); } #[test] @@ -419,7 +433,7 @@ mod tests { for id in DOCUMENTED { assert!(help(id).is_some_and(|text| !text.is_empty()), "{id}"); } - assert!(help("solid.rib").is_none()); + assert!(help("sketch.drag").is_none()); } #[test] @@ -427,7 +441,7 @@ mod tests { 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.rib", "Rib", None, None), None); - assert_eq!(row_tip("solid.rib", "Rib", None, Some("No body")).as_deref(), Some("No body")); + assert_eq!(row_tip("sketch.drag", "Drag Sketch Geometry", None, None), None); + assert_eq!(row_tip("sketch.drag", "Drag Sketch Geometry", None, Some("No body")).as_deref(), Some("No body")); } } diff --git a/crates/ui-egui/src/configuration_rules_ui.rs b/crates/ui-egui/src/configuration_rules_ui.rs index 1fe0f88f8..958760abc 100644 --- a/crates/ui-egui/src/configuration_rules_ui.rs +++ b/crates/ui-egui/src/configuration_rules_ui.rs @@ -1,6 +1,7 @@ //! Structured configuration rule editing and non-mutating row preview. use crate::SolveApp; use crate::ui_kit; +use crate::ui_kit::BackingTooltipExt as _; use egui::Ui; use serde_json::{Value, json}; use solidcraft_engine::doc::config::{Column, ConfigRule, RuleCondition, RuleEffect, RuleOperator}; @@ -86,6 +87,10 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, let features: Vec<(u64, String)> = app.session.doc.features.iter().map(|f| (f.id, f.name.clone())).collect(); let suppression_features: Vec<(u64, String)> = features.iter().filter(|(id, _)| app.session.doc.configs.columns.contains(&Column::Suppress(*id))).cloned().collect(); + // A rule's target must be a column of the table (the engine refuses any other), so the Then + // lists leave out what has none; a note then says so, where When lists everything (#10532). + let unlisted_features = suppression_features.len() < features.len(); + let unlisted_parameters = all_parameters.iter().any(|p| !parameters.contains(p)); ui_kit::divider(ui, "configuration_rules"); ui_kit::text(ui, crate::i18n::tr_label("Configuration rules"), ui_kit::Text::Heading("rules_heading")); ui_kit::text( @@ -112,13 +117,13 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, if ui_kit::button(ui, crate::i18n::tr_label("Edit"), ui_kit::Button::Normal).clicked() { editor.rule = rule.clone(); } - let up = ui_kit::button(ui, "↑", ui_kit::Button::Enabled(index > 0)).on_hover_text(crate::i18n::tr_label("Move earlier")); + let up = ui_kit::button(ui, "↑", ui_kit::Button::Enabled(index > 0)).backing_on_hover_text(crate::i18n::tr_label("Move earlier")); crate::scenario::publish_handle(&format!("config:rule:{}:up", rule.id), up.rect.center()); if up.clicked() { *error = app.run("config.rule", json!({"id":rule.id,"index":index-1})).err(); } if ui_kit::button(ui, "↓", ui_kit::Button::Enabled(index + 1 < rules.len())) - .on_hover_text(crate::i18n::tr_label("Move later")) + .backing_on_hover_text(crate::i18n::tr_label("Move later")) .clicked() { *error = app.run("config.rule", json!({"id":rule.id,"index":index+1})).err(); @@ -179,17 +184,20 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, RuleEffect::DriveParameter { parameter, expression: value } => { ui.vertical(|ui| { choose(ui, "effect_parameter", parameter, ¶meters); + columns_note(ui, unlisted_parameters, "config.rule_parameter_columns"); expression(ui, "Value", value); }); } RuleEffect::DriveSuppression { feature, value } => { ui.vertical(|ui| { feature_choice(ui, "effect_feature", feature, &suppression_features); + columns_note(ui, unlisted_features, "config.rule_suppression_columns"); ui_kit::checkbox(ui, crate::i18n::tr_label("Suppressed"), value); }); } RuleEffect::ParameterRange { parameter, minimum, maximum } => { choose(ui, "range_parameter", parameter, ¶meters); + columns_note(ui, unlisted_parameters, "config.rule_parameter_columns"); ui.vertical(|ui| { expression(ui, "Minimum", minimum); }); @@ -199,6 +207,7 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, } RuleEffect::AllowParameterValues { parameter, expressions } => { choose(ui, "allowed_parameter", parameter, ¶meters); + columns_note(ui, unlisted_parameters, "config.rule_parameter_columns"); let mut text = expressions.join("; "); if ui_kit::row(ui, "Allowed expressions, separated by semicolons", |ui| ui_kit::text_field(ui, &mut text, "").1) { *expressions = text.split(';').map(|s| s.trim().to_string()).collect(); @@ -313,6 +322,13 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, } }); } +/// Under a Then list that leaves some out (`unlisted`): only the table's columns are listed, and +/// how to add one. +fn columns_note(ui: &mut Ui, unlisted: bool, message: &'static str) { + if unlisted { + ui_kit::text(ui, crate::i18n::tr(message), ui_kit::Text::Note(message)); + } +} fn report(ui: &mut Ui, text: impl AsRef) { ui_kit::text(ui, crate::i18n::tr_label(text.as_ref()), ui_kit::Text::Report("rule_report", false)); } diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index c463714de..4dbf3dbf4 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -15,7 +15,8 @@ use crate::ui_kit::{Container, Surface}; use egui::{Color32, Pos2, Rect, Sense, Vec2, pos2, vec2}; use serde::Serialize; use serde_json::{Value, json}; -use solidcraft_engine::Sel; +use solidcraft_engine::geom::prelude::*; +use solidcraft_engine::{Sel, doc::FeatureKind}; use crate::SolveApp; @@ -65,6 +66,8 @@ pub enum Target { Units, /// Insert › Insert Design: the designs open in other tabs, and Browse… (#8570). InsertDesign, + /// Model › Edit Sketch: choose an existing sketch when none is uniquely selected. + EditSketch, /// View › Visual style: the four styles, the current one marked (#8868). VisualStyle, /// View › Navigation tool: Orbit, Pan, Zoom; the latched one marked (#8868). @@ -236,7 +239,7 @@ pub struct MenuState { /// A delete waiting for its confirmation (it takes or breaks other features). pub confirm: Option, /// A selected part has no free joint value for the explicit assembly Move command. - pub joint_move_warning: Option, + pub(crate) joint_move_warning: Option, /// Identical copies Extract to File found, waiting to be linked too. pub link_copies: Option, /// The Properties window: title and measurements. @@ -333,7 +336,7 @@ fn touched_bodies(app: &SolveApp) -> Vec { } fn body_feature(app: &SolveApp, body: &str) -> Option { - app.session.world_state().body(body).map(|b| b.feature) + crate::open_meshing::session_world(&app.session).body(body).map(|b| b.feature) } /// Bodies in a component and its subcomponents. @@ -446,6 +449,17 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec { .collect(), Target::NamedView { name } => crate::browser::view_items(app, name), Target::InsertDesign => insert_design_items(app), + Target::EditSketch => { + let items: Vec = app + .session + .doc + .features + .iter() + .filter(|f| matches!(f.kind, FeatureKind::Sketch { .. })) + .map(|f| act("ui.editSketch", &f.name, "sketch").with(json!({"sketch": f.id}))) + .collect(); + if items.is_empty() { vec![act("ui.editSketch", app.tr("ui.edit_sketch_empty"), "sketch").on(false)] } else { items } + } Target::VisualStyle => crate::navigation_bar::VISUAL_STYLES .iter() .enumerate() @@ -574,7 +588,7 @@ fn picked_face_feature(app: &SolveApp) -> Option { /// The feature that made face `index` of `body` (by its world name). pub(crate) fn face_feature(app: &SolveApp, body: &str, index: usize) -> Option { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let body = state.body(body)?; let names = solidcraft_engine::doc::naming::face_names(body); let name = names.get(index)?; @@ -607,7 +621,7 @@ fn feature_items(app: &SolveApp, id: u64) -> Vec { vec![ act("ui.editFeature", "Edit Feature", "edit").with(json!({"feature":id})).on(exists), act("ui.editSketch", "Edit Profile Sketch", "sketch").with(json!({"sketch": sketch.map(|s| s.0)})).on(sketch.is_some()), - act("ui.rename", "Rename", "rename").with(json!({"feature":id})).on(exists), + act("ui.rename", "Rename", "rename").key("F2").with(json!({"feature":id})).on(exists), act("timeline.suppress", if suppressed { "Unsuppress" } else { "Suppress" }, "suppress") .with(json!({"feature":id, "suppressed": !suppressed})) .on(exists), @@ -678,6 +692,9 @@ fn viewport_items(app: &SolveApp) -> Vec { let planar = sel.iter().any(|s| matches!(s, Sel::Face { body, index, .. } if crate::dialogs::planar_face(&app.session, body, *index).is_some())); v.push(act("ui.lookAt", "Look At", "lookat").on(planar)); + let marked = matches!(sel.as_slice(), [Sel::Face { body, index, .. }] if crate::print_face_ui::is_print_face(app, body, *index)); + let one_flat = planar && matches!(sel.as_slice(), [Sel::Face { .. }]); + v.push(cmd(app, "body.print_face", if marked { "Clear Print Face" } else { "Print Face" }).on(one_flat)); v.push(Item::sep()); v.push(act("ui.appearance", "Appearance", "appearance").key("A")); v.push(act("ui.properties", "Properties", "measure").with(json!({ "bodies": [face] }))); @@ -729,11 +746,11 @@ fn viewport_items(app: &SolveApp) -> Vec { v.push(act("ui.fit", "Fit", "fit")); v.push(act("ui.home", "Home View", "home")); v.push(Item::sep()); - let anything_hidden = !app.session.visibility.hidden_bodies.is_empty() - || !app.session.visibility.hidden_sketches.is_empty() - || !app.session.visibility.hidden_folders.is_empty(); + let can_unisolate = !app.session.visibility.hidden_bodies.is_empty() || !app.session.visibility.hidden_occurrences.is_empty(); + let anything_hidden = + can_unisolate || !app.session.visibility.hidden_sketches.is_empty() || !app.session.visibility.hidden_folders.is_empty(); v.push(act("ui.showAll", "Show All", "eye").on(anything_hidden)); - v.push(act("ui.showAll", "Unisolate", "eye").on(!app.session.visibility.hidden_bodies.is_empty())); + v.push(act("ui.showAll", "Unisolate", "eye").on(can_unisolate)); v.push(Item::sep()); v.push(cmd(app, "solid.extrude", "Extrude")); v.push(cmd(app, "solid.fillet", "Fillet")); @@ -783,7 +800,7 @@ fn body_items(app: &SolveApp, bodies: &[String], browser: bool) -> Vec { act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste(app)), act("ui.delete", "Delete", "delete").key("Del").with(json!({ "items": items })).on(!locked), cmd(app, "solid.remove", "Remove").with(json!({ "bodies": names })).on(!locked), - act("ui.rename", "Rename", "rename").with(json!({ "body": bodies.first() })).on(one), + act("ui.rename", "Rename", "rename").key("F2").with(json!({ "body": bodies.first() })).on(one), Item::sep(), act(if all_hidden { "ui.show" } else { "ui.hide" }, "Show/Hide", "eye").key("V").with(json!({ "bodies": names })), act("ui.lock", if locked { "Unlock" } else { "Lock" }, "ground").with(json!({ "bodies": names })), @@ -799,6 +816,11 @@ fn body_items(app: &SolveApp, bodies: &[String], browser: bool) -> Vec { v.push(act("ui.findBrowser", "Find in Browser", "list").with(json!({ "body": b }))); } v.push(act("ui.findTimeline", "Find in Timeline", "rollback").with(json!({ "body": b }))); + // A part the modelling kernel refuses can be repaired. + if crate::open_meshing::session_world(&app.session).body(&b).is_some_and(|m| m.body.smlib_refused().is_some()) { + v.push(Item::sep()); + v.push(cmd(app, crate::refused_part::REPAIR, "Repair Part").with(json!({ "body": b }))); + } } v } @@ -808,8 +830,24 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec { let profiles = !app.session.visibility.hidden_profiles.contains(&id); let dims = app.session.visibility.shown_dimensions.contains(&id); let editing = app.session.active_sketch == Some(id); - let has_profiles = app.session.world_state().sketch(id).is_some_and(|s| !s.profiles.is_empty()); - vec![ + let has_profiles = crate::open_meshing::session_world(&app.session).sketch(id).is_some_and(|s| !s.profiles.is_empty()); + // This sketch, or every selected sketch when it is one of them, to the part it is on (#10218). + let selected: Vec = app + .session + .selection + .iter() + .filter_map(|sel| match sel { + solidcraft_engine::Sel::Feature { id } + if app.session.doc.feature(*id).is_some_and(|f| matches!(f.kind, solidcraft_engine::doc::FeatureKind::Sketch { .. })) => + { + Some(id.to_string()) + } + _ => None, + }) + .collect(); + let sketches = if selected.contains(&id.to_string()) { selected } else { vec![id.to_string()] }; + let parts = !app.session.doc.components.is_empty(); + let mut items = vec![ act("ui.extrudeSketch", "Extrude", "extrude").key("E").with(json!({ "sketch": id })).on(has_profiles && !editing), Item::sep(), act("ui.editSketch", "Edit Sketch", "sketch").with(json!({ "sketch": id })).on(!editing), @@ -820,7 +858,8 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec { act("ui.copy", "Copy", "copy").key("Ctrl+C").on(crate::edit_clipboard::something_to_copy(app)), act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste(app)), act("ui.delete", "Delete", "delete").key("Del").with(json!({ "items": [{"type": "feature", "id": id}] })), - act("ui.rename", "Rename", "rename").with(json!({ "feature": id })), + act("ui.rename", "Rename", "rename").key("F2").with(json!({ "feature": id })), + crate::browser::sketches_to_parts_item(sketches).on(parts && !editing), Item::sep(), act("ui.lookAt", "Look At", "lookat").with(json!({ "sketch": id })), act("ui.sketchProfile", if profiles { "Hide Profile" } else { "Show Profile" }, "sketch").with(json!({ "sketch": id })), @@ -828,7 +867,9 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec { act(if visible { "ui.hideSketch" } else { "ui.showSketch" }, "Show/Hide", "eye").key("V").with(json!({ "sketch": id })), Item::sep(), act("ui.findTimeline", "Find in Timeline", "rollback").with(json!({ "feature": id })), - ] + ]; + items.retain(|item| parts || item.id != "component.move_sketches.to_parts"); + items } /// Construction geometry's row: edit, delete, rename, show or hide; sketch on planes. @@ -844,7 +885,7 @@ fn plane_items(app: &SolveApp, id: u64) -> Vec { items.push(Item::sep()); items.extend([ act("ui.delete", "Delete", "delete").key("Del").with(json!({ "items": [{"type": "feature", "id": id}] })), - act("ui.rename", "Rename", "rename").with(json!({ "feature": id })), + act("ui.rename", "Rename", "rename").key("F2").with(json!({ "feature": id })), Item::sep(), act("ui.originPart", "Show/Hide", "eye").key("V").with(json!({ "keys": [f.name], "show": !visible })), Item::sep(), @@ -1059,12 +1100,24 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { if id != 0 { v.push(act("ui.delete", "Delete", "delete").key("Del").with(json!({ "occurrences": [occ.map(|o| o.id)] })).on(occ.is_some())); } - v.push(act("ui.rename", "Rename", "rename").with(json!({ "component": id }))); + v.push(act("ui.rename", "Rename", "rename").key("F2").with(json!({ "component": id }))); v.push(Item::sep()); v.push(act(if hidden { "ui.show" } else { "ui.hide" }, "Show/Hide", "eye").key("V").with(json!({ "bodies": names })).on(!bodies.is_empty())); v.push(act("ui.showAll", "Show All Bodies", "eye")); v.push(act("ui.isolate", "Isolate", "body").with(json!({ "bodies": names })).on(!bodies.is_empty() && id != 0)); v.push(act("ui.newGroup", "New Group", "folder").with(json!({ "component": id }))); + if id != 0 { + // Keep the component in the design but leave its features out of the History bar (#10393). + let hidden = doc.component_history_hidden(id); + v.push( + cmd( + app, + if hidden { "component.show_history" } else { "component.hide_history" }, + if hidden { "Show its History" } else { "Hide its History" }, + ) + .with(json!({ "component": id })), + ); + } v.push(Item::sep()); v.push(cmd(app, "browser.expand_all", "Expand All").with(json!({ "component": id }))); v.push(cmd(app, "browser.collapse_all", "Collapse All").with(json!({ "component": id }))); @@ -1078,6 +1131,23 @@ fn explode_text(app: &SolveApp) -> Option { Some(cmd(app, "sketch.break_link", "Explode Text").with(json!({ "link": link }))) } +/// Break Link (#10417): projected geometry among the selection (a model edge or vertex, another +/// sketch's curve) becomes normal sketch geometry, which Trim, drags and dimensions change like +/// any other. Messages already send people here ("use Break Link on it"); text has Explode Text. +fn break_link(app: &SolveApp, sk: &solidcraft_engine::sketch::Sketch, ents: &[String]) -> Option { + let projected = |link: Option<&String>| { + link.and_then(|l| sk.link(l)).is_some_and(|l| !matches!(l.source, solidcraft_engine::sketch::LinkSource::Text { .. })) + }; + let linked: Vec<&str> = ents + .iter() + .filter_map(|id| match sk.curves.iter().find(|c| &c.id == id) { + Some(c) => projected(c.link.as_ref()).then_some(c.id.as_str()), + None => sk.resolve_point(id).and_then(|i| sk.points.get(i)).filter(|p| projected(p.link.as_ref())).map(|p| p.id.as_str()), + }) + .collect(); + (!linked.is_empty()).then(|| cmd(app, "sketch.break_link", "Break Link").with(json!({ "entities": linked }))) +} + fn alignment_items(selection: &[Sel]) -> Vec { let Some(points) = crate::selection::alignment_points(selection) else { return Vec::new() }; vec![ @@ -1092,10 +1162,13 @@ fn alignment_items(selection: &[Sel]) -> Vec { fn sketch_entity_items(app: &SolveApp) -> Vec { use solidcraft_engine::sketch::{ConstraintKind, CurveKind}; let Some(sid) = app.session.active_sketch else { return Vec::new() }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = st.sketch(sid) else { return Vec::new() }; if app.session.selection.iter().any(|sel| matches!(sel, Sel::SketchMidpoint { .. })) { - return alignment_items(&app.session.selection); + // A midpoint with a point or curve can also be made coincident with it (#10311). + let coincident = crate::selection::coincident_operands(&app.session.selection) + .map(|operands| cmd(app, "sketch.constraint.coincident", "Coincident").with(operands)); + return coincident.into_iter().chain(alignment_items(&app.session.selection)).collect(); } let mut lines = Vec::new(); let mut rounds = Vec::new(); @@ -1163,7 +1236,7 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { v.push(cmd(app, "sketch.circle.center", "Circle")); v.push(cmd(app, "sketch.dimension", "Sketch Dimension")); v.push(Item::sep()); - v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(app.session.sketch_clipboard.is_some())); + v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste_sketch(app))); return v; } let ents: Vec = curves.iter().chain(points.iter()).cloned().collect(); @@ -1178,6 +1251,7 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { v.push(cmd(app, "sketch.edit_text", "Edit Text")); v.extend(explode_text(app)); } + v.extend(break_link(app, &ss.sketch, &ents)); if let Some(curve) = crate::sketch_modify_ui::selected_equation(app) { v.push(act("ui.editEquationCurve", "Edit Equation Curve", "equation_curve").with(json!({ "curve": curve }))); } @@ -1224,11 +1298,24 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { { v.push(cmd(app, "sketch.spline.reverse", "Reverse Spline Direction").with(json!({ "curve": curve }))); } + // #10783: a point of one spline of the sketch's own, alone, comes out of that spline. + if let ([], [point]) = (curves.as_slice(), points.as_slice()) + && let Some(at) = ss.sketch.resolve_point(point) + && let [spline] = ss + .sketch + .curves + .iter() + .filter(|c| c.link.is_none() && matches!(&c.kind, CurveKind::Spline { pts, .. } if pts.contains(&at))) + .collect::>() + .as_slice() + { + v.push(cmd(app, "sketch.spline.remove_point", "Remove Spline Point").with(json!({ "curve": spline.id, "point": point }))); + } v.push(act("ui.fix", "Fix/Unfix", "c_fix").with(json!({ "entities": ents }))); // The clipboard beside Delete, as in every menu. v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X")); v.push(act("ui.copy", "Copy", "copy").key("Ctrl+C")); - v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(app.session.sketch_clipboard.is_some())); + v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste_sketch(app))); v.push(act("ui.delete", "Delete", "delete").key("Del")); v.push(cmd(app, "sketch.dimension", "Sketch Dimension").with(json!({ "entities": ents })).on(ents.len() <= 2)); // One arc alone: Sketch Dimension gives its radius, this its length along the curve (#6039). @@ -1278,6 +1365,9 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { c.push(cmd(app, "sketch.constraint.equal", "Equal").with(ab.clone())); c.push(cmd(app, "sketch.constraint.tangent", "Tangent").with(ab)); } + if r == 1 && p == 1 && n == 2 { + c.push(cmd(app, "sketch.constraint.concentric", "Concentric").with(json!({ "a": picked[0], "b": picked[1] }))); + } if l == 1 && r == 1 && n == 2 { c.push(cmd(app, "sketch.constraint.tangent", "Tangent").with(json!({ "a": picked[0], "b": picked[1] }))); } @@ -1292,7 +1382,7 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { } /// Where on the active sketch's plane the viewport menu was opened (sketch coordinates). -fn menu_sketch_point(app: &SolveApp, plane: &solidcraft_engine::geom::Plane) -> Option { +fn menu_sketch_point(app: &SolveApp, plane: &solidcore_record::Plane) -> Option { let (at, _) = app.menu.opened?; let proj = crate::viewport::projection(app, app.viewport.rect?); let (o, d) = proj.ray(at); @@ -1428,13 +1518,10 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { let _ = app.run("browser.visibility", json!({ "folder": "all", "visible": true })); } "ui.isolate" => { - // The picked bodies stay (shown first if they were hidden), everything else goes. - let others: Vec = app.session.world_state().bodies.iter().map(|b| b.name.clone()).filter(|b| !bodies.contains(b)).collect(); + // The picked bodies stay (shown if they were hidden) and everything else goes, other + // components as components (#7896), in one step. if !bodies.is_empty() { - let _ = app.run("browser.visibility", json!({ "items": bodies, "visible": true })); - } - if !others.is_empty() { - let _ = app.run("browser.visibility", json!({ "items": others, "visible": false })); + let _ = app.run("browser.visibility", json!({ "items": bodies, "visible": true, "isolate": true })); } } "ui.lock" => { @@ -1527,7 +1614,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } } let _ = app.run("select.set", json!({"items": [{"type": "feature", "id": f}]})); - app.tree.timeline_reveal = Some(f); + crate::browser::request_timeline_reveal(app, f); } } "ui.tangentChain" => tangent_chain(app), @@ -1638,6 +1725,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { app.set_status(e, true); } } + "ui.historyShowHidden" => app.tree.history_show_hidden = p["show"].as_bool().unwrap_or(false), "ui.workspace" | "ui.workspace.design" | "ui.workspace.render" | "ui.workspace.drawing" => { let result = p.get("workspace").and_then(Value::as_str).map_or(Ok(()), |workspace| crate::workspace::enter(app, workspace)); if let Err(error) = result { @@ -1733,18 +1821,18 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } "ui.extrudeSketch" => { if let Some(id) = id_of(&p, "sketch") { - let n = app.session.world_state().sketch(id).map_or(0, |s| s.profiles.len()); + let n = crate::open_meshing::session_world(&app.session).sketch(id).map_or(0, |s| s.profiles.len()); let items: Vec = (0..n).map(|i| json!({"type": "profile", "sketch": id, "index": i})).collect(); let _ = app.run("select.set", json!({ "items": items })); app.start("solid.extrude"); } } "ui.lookAt" => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); if let Some(ss) = id_of(&p, "sketch").and_then(|id| st.sketch(id)) { let to = crate::dialogs::onto_sketch(app.cam.looking_from(ss.plane.normal()), ss); app.animate_to(to); - } else if let Some(plane) = p.get("plane").and_then(Value::as_str).and_then(solidcraft_engine::geom::Plane::named) { + } else if let Some(plane) = p.get("plane").and_then(Value::as_str).and_then(solidcore_record::Plane::named) { let mut to = app.cam.looking_from(crate::dialogs::facing(app, plane.normal(), true)); to.target = plane.origin; app.animate_to(to); @@ -1784,6 +1872,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } // They recompute the history from the changed feature on: off the frame, as the timeline does. "timeline.suppress" | "timeline.roll_to" if item.params.is_some() => drop(app.run_heavy(&item.id, p)), + "component.move_sketches.to_parts" => sketches_to_parts(app, p), id if item.params.is_some() => { let _ = app.run(id, p); } @@ -1791,6 +1880,30 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } } +/// Move Sketches to the Part They're On, and say in the status bar how many moved and why the +/// others stayed (#10218). +fn sketches_to_parts(app: &mut SolveApp, p: Value) { + let out = match app.run("component.move_sketches.to_parts", p) { + Ok(out) => out, + Err(error) => return app.set_status(crate::friendly_error("component.move_sketches.to_parts", &error), true), + }; + let count = |key: &str| out.get(key).and_then(Value::as_u64).unwrap_or(0).to_string(); + let mut why: Vec = Vec::new(); + for kept in out.get("kept").and_then(Value::as_array).into_iter().flatten() { + let code = kept.get("code").and_then(Value::as_str).unwrap_or_default(); + let reason = crate::i18n::tr(&format!("browser.sketches_to_parts_{code}")).to_string(); + if !why.contains(&reason) { + why.push(reason); + } + } + let message = if why.is_empty() { + crate::i18n::format("browser.sketches_to_parts_moved", &[("moved", &count("moved"))]) + } else { + crate::i18n::format("browser.sketches_to_parts_result", &[("moved", &count("moved")), ("stayed", &count("stayed")), ("why", &why.join("; "))]) + }; + app.set_status(message, false); +} + /// Delete what is selected: sketch entities, features, and bodies (a Remove feature). pub fn delete(app: &mut SolveApp) { crate::delete::delete_selection(app); @@ -1872,8 +1985,13 @@ pub fn toggle_visibility(app: &mut SolveApp) { } /// Rename what is selected (F2): one body, sketch or feature, construction plane, component -/// picked in the browser, or canvas. +/// picked in the browser, canvas, or a group whose Browser row was clicked. pub fn rename_selection(app: &mut SolveApp, at: Pos2) -> bool { + // A clicked group row takes precedence, as it does for V: groups have no selection of their own. + if let Some(g) = crate::browser::picked_group(app) { + start_rename(app, RenameWhat::Group(g), at); + return true; + } let what = match (app.session.selection.as_slice(), app.tree.picked_components.as_slice(), app.tree.picked_canvases.as_slice()) { ([Sel::Body { name }], [], []) => RenameWhat::Body(name.clone()), ([Sel::Feature { id }], [], []) => RenameWhat::Feature(*id), @@ -1895,7 +2013,7 @@ pub fn rename_selection(app: &mut SolveApp, at: Pos2) -> bool { /// Add the edges that continue the selected edges smoothly to the selection. fn tangent_chain(app: &mut SolveApp) { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let mut out: Vec = Vec::new(); for s in &app.session.selection { let Sel::Edge { body, index, .. } = s else { continue }; @@ -1931,24 +2049,30 @@ pub fn start_rename(app: &mut SolveApp, what: RenameWhat, at: Pos2) { app.menu.rename = Some(Rename { what, text, at, focused: false, inline: false }); } -pub(crate) fn commit_rename(app: &mut SolveApp, r: &Rename) { +pub(crate) fn commit_rename(app: &mut SolveApp, r: &Rename) -> Result<(), String> { let name = r.text.trim().to_string(); if name.is_empty() { - return; + return Ok(()); } - match &r.what { + let result = match &r.what { RenameWhat::Body(old) => { // The command renames the body where it is hidden or locked too. - drop(app.run_heavy("body.rename", json!({ "body": old, "name": name }))); + app.run_heavy("body.rename", json!({ "body": old, "name": name })).map(|_| ()) } - RenameWhat::Feature(f) => drop(app.run("timeline.rename", json!({ "feature": f, "name": name }))), - RenameWhat::Component(c) => drop(app.run("component.rename", json!({ "component": c, "name": name }))), - RenameWhat::Group(g) => crate::browser::group_action(app, "ui.renameGroup", &json!({ "group": g, "name": name })), - RenameWhat::TimelineGroup(g) => drop(app.run("timeline.rename_group", json!({ "group": g, "name": name }))), - RenameWhat::Canvas(c) => drop(app.run("canvas.edit", json!({ "canvas": c, "name": name }))), - RenameWhat::View(v) => drop(app.run("view.rename", json!({ "view": v, "name": name }))), - RenameWhat::Joint(j) => drop(app.run("joint.edit", json!({ "joint": j, "name": name }))), - } + RenameWhat::Feature(f) => app.run("timeline.rename", json!({ "feature": f, "name": name })).map(|_| ()), + RenameWhat::Component(c) => app.run("component.rename", json!({ "component": c, "name": name })).map(|_| ()), + RenameWhat::Group(g) => { + crate::browser::group_action(app, "ui.renameGroup", &json!({ "group": g, "name": name })); + Ok(()) + } + RenameWhat::TimelineGroup(g) => app.run("timeline.rename_group", json!({ "group": g, "name": name })).map(|_| ()), + RenameWhat::Canvas(c) => app.run("canvas.edit", json!({ "canvas": c, "name": name })).map(|_| ()), + RenameWhat::View(v) => app.run("view.rename", json!({ "view": v, "name": name })).map(|_| ()), + RenameWhat::Joint(j) => app.run("joint.edit", json!({ "joint": j, "name": name })).map(|_| ()), + }; + // The command's own status line explains a refusal; the caller decides whether to keep the + // editor open on it. + result } // --------------------------------------------------------------------------------------------- @@ -2478,7 +2602,9 @@ fn show_rename(app: &mut SolveApp, ctx: &egui::Context) { done = Some(true); } match done { - Some(true) => commit_rename(app, &r), + Some(true) => { + let _ = commit_rename(app, &r); + } Some(false) => {} None => app.menu.rename = Some(r), } @@ -2491,7 +2617,7 @@ pub fn finish_rename(app: &mut SolveApp, text: Option<&str>, commit: bool) -> bo r.text = s.to_string(); } if commit { - commit_rename(app, &r); + let _ = commit_rename(app, &r); } true } @@ -2523,7 +2649,7 @@ mod tests { .to_owned(); let horiz = h.app.run("sketch.constrainer", json!({"entities":[l]})).unwrap()["constraint"].as_str().unwrap().to_owned(); let is_driven = |h: &crate::scenario::Harness| { - h.app.session.world_state().sketch(sid).unwrap().sketch.constraints.iter().any(|c| c.id == dim && c.driven) + crate::open_meshing::session_world(&h.app.session).sketch(sid).unwrap().sketch.constraints.iter().any(|c| c.id == dim && c.driven) }; // A selected dimension offers the toggle, aimed at that constraint. @@ -2565,7 +2691,15 @@ mod tests { let pc = h.app.run("sketch.dimension", json!({"entities":[c]})).unwrap()["param"].as_str().unwrap().to_owned(); let pl = h.app.run("sketch.dimension", json!({"entities":[l],"value":20})).unwrap()["param"].as_str().unwrap().to_owned(); let dim = |h: &crate::scenario::Harness, p: &str| { - h.app.session.world_state().sketch(sid).unwrap().sketch.constraints.iter().find(|c| c.param.as_deref() == Some(p)).unwrap().clone() + crate::open_meshing::session_world(&h.app.session) + .sketch(sid) + .unwrap() + .sketch + .constraints + .iter() + .find(|c| c.param.as_deref() == Some(p)) + .unwrap() + .clone() }; let did = dim(&h, &pc).id; @@ -2696,7 +2830,8 @@ mod tests { #[test] fn line_offset_context_menu_breaks_association_and_allows_trim() { - use solidcraft_engine::{geom::Vec2, sketch::Shape}; + use solidcore_record::Vec2; + use solidcraft_engine::sketch::Shape; let mut h = crate::scenario::Harness::new(); h.app.home.open = false; @@ -2709,7 +2844,7 @@ mod tests { h.app.run("sketch.offset", json!({"curves":[source],"distance":2,"chain":false})).unwrap()["curves"][0].as_str().unwrap().to_owned(); h.app.run("sketch.line", json!({"points":[[10,-5],[10,5]],"connect":false,"infer":false})).unwrap(); let sid = h.app.session.active_sketch.unwrap(); - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let sk = &state.sketch(sid).unwrap().sketch; let Shape::Line { a, b } = sk.shape(sk.curve_index(&output).unwrap()).unwrap() else { panic!("offset must be a line") }; let cut = Vec2::new(15.0, a.y); @@ -2727,15 +2862,63 @@ mod tests { assert!(item.enabled); assert_eq!(item.params, Some(json!({"curve":output}))); h.step(&json!({"click":{"handle":"menu:sketch.offset.break"}})).unwrap(); - assert!(h.app.session.world_state().sketch(sid).unwrap().sketch.offset_distance(&output).is_none()); + assert!(crate::open_meshing::session_world(&h.app.session).sketch(sid).unwrap().sketch.offset_distance(&output).is_none()); h.app.run("sketch.trim", json!({"curve":output,"at":[cut.x,cut.y]})).unwrap(); - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let sk = &state.sketch(sid).unwrap().sketch; let remaining = sk.shape(sk.curve_index(&output).unwrap()).unwrap(); assert!(matches!(remaining, Shape::Line { a, b } if (a.dist(b) - 10.0).abs() < 1e-6), "{remaining:?}"); assert!(remaining.dist(cut) > 1.0); } + /// #10417: a projected edge's context menu offers Break Link, and the item makes it normal + /// sketch geometry that Trim then cuts. A line drawn in the sketch is offered no Break Link. + #[test] + fn projected_geometry_context_menu_breaks_its_link_and_allows_trim() { + use solidcore_record::Vec2; + + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":20,"width":20,"height":10})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.project", json!({"refs":[{"body":"Body1"}],"projection_link":true})).unwrap(); + let drawn = h.app.run("sketch.line", json!({"points":[[10,-5],[10,5]],"connect":false,"infer":false})).unwrap()["curves"][0] + .as_str() + .unwrap() + .to_owned(); + let sid = h.app.session.active_sketch.unwrap(); + let cut = Vec2::new(15.0, 0.0); + let edge = { + let state = h.app.session.world_state().unwrap(); + let sk = &state.sketch(sid).unwrap().sketch; + (0..sk.curves.len()) + .find(|i| sk.curves[*i].link.is_some() && sk.shape(*i).is_some_and(|shape| shape.dist(cut) < 1e-6)) + .map(|i| sk.curves[i].id.clone()) + } + .expect("the box's edge along y = 0 is projected"); + assert!(h.app.run("sketch.trim", json!({"curve":edge,"at":[cut.x,cut.y]})).is_err(), "a linked edge is not trimmed"); + + h.call("ui.view", json!({"view":"top"})); + h.app.cam.distance = 80.0; + h.settle(); + h.step(&json!({"click":{"world":[10,3,0]},"button":"right"})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchCurve { id: drawn.clone(), sketch: None }]); + assert!(!items(&h.app, &Target::Viewport).iter().any(|item| item.id == "sketch.break_link"), "a drawn line has no link to break"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"click":{"world":[cut.x,cut.y,0]},"button":"right"})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchCurve { id: edge.clone(), sketch: None }]); + let menu = items(&h.app, &Target::Viewport); + let item = menu.iter().find(|item| item.id == "sketch.break_link").expect("a projected edge must offer Break Link"); + assert_eq!(item.label, "Break Link"); + assert!(item.enabled); + assert_eq!(item.params, Some(json!({"entities":[edge]}))); + h.step(&json!({"click":{"handle":"menu:sketch.break_link"}})).unwrap(); + let unlinked = + h.app.session.world_state().unwrap().sketch(sid).unwrap().sketch.curves.iter().find(|c| c.id == edge).is_some_and(|c| c.link.is_none()); + assert!(unlinked, "Break Link makes the edge normal sketch geometry"); + h.app.run("sketch.trim", json!({"curve":edge,"at":[cut.x,cut.y]})).unwrap(); + } + /// #6533: a right-click on a fit point spline offers Add Spline Point at the clicked spot, and /// the item puts a fit point there. A control point spline is not offered it. Every spline is /// offered Reverse Spline Direction (#8224), which runs it the other way. @@ -2754,12 +2937,12 @@ mod tests { .to_owned(); let sid = h.app.session.active_sketch.unwrap(); let spot = |h: &crate::scenario::Harness, id: &str, piece: usize| { - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let sk = &state.sketch(sid).unwrap().sketch; sk.exact_segs(sk.curve_index(id).unwrap()).unwrap()[piece].point_at(0.5) }; let count = |h: &crate::scenario::Harness, id: &str| { - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let sk = &state.sketch(sid).unwrap().sketch; sk.curves[sk.curve_index(id).unwrap()].kind.point_ids().len() }; @@ -2775,7 +2958,7 @@ mod tests { let item = menu.iter().find(|item| item.id == "sketch.spline.reverse").expect("a control point spline offers Reverse Spline Direction"); assert_eq!((item.label.as_str(), item.params.clone()), ("Reverse Spline Direction", Some(json!({"curve": control})))); let points = |h: &crate::scenario::Harness, id: &str| { - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let sk = &state.sketch(sid).unwrap().sketch; sk.curves[sk.curve_index(id).unwrap()].kind.point_ids() }; @@ -2794,22 +2977,63 @@ mod tests { assert!(item.enabled); let p = item.params.clone().unwrap(); assert_eq!(p["curve"], json!(fit)); - let clicked = solidcraft_engine::geom::Vec2::new(p["at"][0].as_f64().unwrap(), p["at"][1].as_f64().unwrap()); + let clicked = solidcore_record::Vec2::new(p["at"][0].as_f64().unwrap(), p["at"][1].as_f64().unwrap()); assert!(clicked.dist(at) < 0.5, "the item carries the clicked spot: {clicked:?} for {at:?}"); h.step(&json!({"click":{"handle":"menu:sketch.spline.insert_point"}})).unwrap(); assert_eq!(count(&h, &fit), 5); - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let sk = &state.sketch(sid).unwrap().sketch; let added = sk.point(sk.curves[sk.curve_index(&fit).unwrap()].kind.point_ids()[2]).unwrap(); assert!(added.dist(at) < 0.5, "the new fit point is where the menu was opened: {added:?}"); } + /// #10783: a right-click on one of a spline's points offers Remove Spline Point, and the item + /// takes that point out: the spline stays, through its other points. A line's end isn't + /// offered it. + #[test] + fn spline_context_menu_removes_the_clicked_point() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let fit = h.app.run("sketch.spline.fit_point", json!({"points":[[0,0],[10,8],[20,0],[30,6]],"connect":false})).unwrap()["curves"][0] + .as_str() + .unwrap() + .to_owned(); + h.app.run("sketch.line", json!({"points":[[0,-12],[20,-12]],"connect":false})).unwrap(); + let sid = h.app.session.active_sketch.unwrap(); + let places = |h: &crate::scenario::Harness| { + let state = h.app.session.world_state().unwrap(); + let sk = &state.sketch(sid).unwrap().sketch; + sk.curves[sk.curve_index(&fit).unwrap()].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect::>() + }; + h.call("ui.view", json!({"view":"top"})); + h.app.cam.distance = 80.0; + h.settle(); + + h.step(&json!({"click":{"world":[20,-12,0]},"button":"right"})).unwrap(); + assert!(matches!(h.app.session.selection.as_slice(), [Sel::SketchPoint { .. }]), "{:?}", h.app.session.selection); + assert!(items(&h.app, &Target::Viewport).iter().all(|item| item.id != "sketch.spline.remove_point"), "a line's end"); + close(&mut h.app); + + let mut left = places(&h); + left.remove(1); + h.step(&json!({"click":{"world":[10,8,0]},"button":"right"})).unwrap(); + let [Sel::SketchPoint { id }] = h.app.session.selection.as_slice() else { panic!("{:?}", h.app.session.selection) }; + let id = id.clone(); + let menu = items(&h.app, &Target::Viewport); + let item = menu.iter().find(|item| item.id == "sketch.spline.remove_point").expect("a spline's point offers Remove Spline Point"); + assert_eq!((item.label.as_str(), item.params.clone()), ("Remove Spline Point", Some(json!({"curve": fit, "point": id})))); + assert!(item.enabled); + h.step(&json!({"click":{"handle":"menu:sketch.spline.remove_point"}})).unwrap(); + assert_eq!(places(&h), left, "the spline runs through its other points"); + } + #[test] fn solidworks_face_menu_runs_normal_to_selection_and_rejects_curved_faces() { let mut h = crate::scenario::Harness::new(); h.app.home.open = false; h.app.run("solid.cylinder", json!({"diameter":30,"height":20})).unwrap(); - let state = h.app.session.world_state(); + let state = crate::open_meshing::session_world(&h.app.session); let body = state.bodies.first().unwrap(); let faces = body.body.faces(0.1).unwrap(); let flat = faces.iter().find(|f| f.plane_normal.is_some()).unwrap(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d588bb0a7..d84a9d162 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -32,7 +32,7 @@ //! - `ui.window {action: minimize|maximize|restore|toggle|close}`: what the title bar's buttons do //! - `ui.confirm {accept?}`: the Delete confirmation (without `accept`: what it lists) //! - `ui.shortcut {command, key?, slot?, replace?}`: a command's keys, or bind one ("" clears) -//! - `ui.help {item?: about|shortcuts|report}`: the Help menu; returns the version and diagnostics +//! - `ui.help {item?: about|updates|shortcuts|report}`: the Help menu; returns the version and diagnostics //! - `ui.prefs {...}`: the preferences (default_units, default_projection, nav, zoom_reverse, //! orbit_around, msaa, length_decimals, angle_decimals); returns them all //! - `ui.capture {action?: capture|revert|cancel}`: the Capture Position question @@ -41,6 +41,7 @@ //! and replies once the command has run (`"animate": false` skips that one call) //! - `ui.resize {width, height}`, `app.quit` +use solidcraft_engine::geom::prelude::*; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::Sender; use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; @@ -175,7 +176,12 @@ fn ok(v: Value) -> Outcome { Outcome::Done(json!({"ok": true, "result": v})) } fn err(e: impl std::fmt::Display) -> Outcome { - Outcome::Done(json!({"ok": false, "error": e.to_string()})) + let text = e.to_string(); + let mut reply = json!({"ok": false, "error": text}); + if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&text) { + reply["panel_error"] = reason; + } + Outcome::Done(reply) } fn wrap(r: Result) -> Outcome { match r { @@ -187,6 +193,55 @@ fn wrap(r: Result) -> Outcome { /// The design's own Sketches folder (`Visibility::hidden_folders`), which `showSketches` sets. const SKETCHES_FOLDER: &str = "c0/sketches"; +/// The open dialog as `ui.inspect`, `ui.start` and `ui.editFeature` report it: its command, its +/// picks and what OK runs, in the commands' own terms rather than the form's internals (#9087). +fn dialog_state(app: &SolveApp) -> Value { + let Some(d) = app.dialog.as_ref() else { return Value::Null }; + let runs = crate::dialogs::apply_commands(app, d); + json!({ + "command": d.command(), + "title": crate::dialogs::report_title(d), + "editing": d.editing.map(|(feature, _)| feature), + "inputs": d.inputs.iter().enumerate().map(|(i, input)| json!({"label": input.label, "items": input.items, "active": i == d.active})).collect::>(), + "error": d.error, + "commands": runs.as_ref().ok().map(|cmds| cmds.iter().map(|(command, params)| json!({"command": command, "params": params})).collect::>()), + "waiting": runs.err(), + }) +} + +/// The windows open beside the model (#9087), each named by what opens it: the command +/// `ui.start` takes, or the `ui.help` item. +fn open_windows(app: &SolveApp) -> Vec<&'static str> { + [ + (app.params.is_some(), "parameters.change"), + (app.design_properties.is_some(), "document.metadata"), + (app.sketch_report.is_some(), "sketch.inspect"), + (app.bom.is_some(), "assembly.bom"), + (app.material_card_review.is_some(), "material.properties.validate"), + (app.help.about, "about"), + (app.updater.open, "updates"), + (app.keymap.open, "shortcuts"), + (app.crashes.open, "crashes"), + (app.issue_report.draft.is_some(), "report"), + (app.messages.open, "messages"), + ] + .into_iter() + .filter_map(|(open, command)| open.then_some(command)) + .collect() +} + +/// What a start or an edit opened: the tool, the dialog and the windows. `pending` while it +/// waits for the history to compute first; it opens on a later frame (`ui.inspect` shows it). +fn started(app: &SolveApp) -> Value { + json!({ + "tool": app.tool.as_ref().map(|t| t.cmd), + "dialog": dialog_state(app), + "windows": open_windows(app), + "pending": app.pending_feature_edit.is_some() || app.start_after_roll.is_some(), + "status": app.status.as_ref().map(|(text, _, error)| json!({"text": text, "error": error})), + }) +} + /// `UiState` as `ui.inspect` and `ui.set` report it, with the browser's view of the design /// (kept in the session) under the names the UI state used to give it. fn ui_state(app: &SolveApp) -> Value { @@ -216,6 +271,22 @@ fn key_from(name: &str) -> Option { /// Run one command as `engine.execute` does: through `app.run`, then the first-body fit and the /// camera the command asked for. fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result { + if solidcraft_engine::panels::commands::is_command(id) { + // No first-body meshing, camera-follow or fit tail for application layout. + return app.run(id, params); + } + // User bindings live in the UI. A bridged agent needs the same key the menus show, + // including null for a cleared binding; the standalone engine keeps its defaults. + if id == "engine.commands" { + let mut commands = app.session.execute(id, ¶ms).map_err(|e| e.to_string())?; + if let Some(rows) = commands.as_array_mut() { + for row in rows.iter_mut().filter_map(Value::as_object_mut) { + let key = row.get("id").and_then(Value::as_str).and_then(|id| crate::keymap::effective(app, id)); + row.insert("shortcut".into(), json!(key)); + } + } + return Ok(commands); + } // `view.pick` is answered by the viewport, not the engine: pixels and rays need the // window's camera and pick index, and the command must not touch the document, the // selection or the undo stack. Intercepted here so `engine.execute` and `engine.batch` @@ -254,7 +325,7 @@ fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result ) && !id.starts_with("settings.") && app.session.active_sketch.is_none() - && app.session.world_state().bodies.len() == 1 + && crate::open_meshing::session_world(&app.session).bodies.len() == 1 && app.session.undo.len() <= 2 { app.fit_view(); @@ -317,6 +388,38 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome { let Some(steps) = p.get("commands").and_then(Value::as_array).filter(|s| s.len() <= MAX_BATCH) else { return err(format!("engine.batch: commands must be an array of at most {MAX_BATCH} steps")); }; + let panels = steps.iter().filter(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command)).count(); + if panels > 0 { + if let Some(why) = batch_refusal(steps) { + return err(why); + } + if let Some(refusal) = solidcraft_engine::batch_preflight::check(steps, app.session.param_check, &["view.pick"]) { + return ok(refusal.reply(steps.len())); + } + let rollback = p.get("rollback").and_then(Value::as_bool).unwrap_or(true); + if rollback { + if panels != steps.len() { + return err(solidcraft_engine::panels::commands::error_text(solidcraft_engine::panels::error( + solidcraft_engine::panels::Rule::Capability, + "atomic mixed document/layout batches are unavailable; use rollback:false or separate transactions", + ))); + } + return wrap(app.run_panel_batch(steps).map_err(solidcraft_engine::panels::commands::error_text)); + } + // Explicit sequential mode has per-command atomicity and no document + // checkpoint; previous application changes are truthfully retained. + let mut results = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let result = command(step) + .ok_or_else(|| "missing command".to_string()) + .and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({})))); + match result { + Ok(result) => results.push(result), + Err(error) => return ok(solidcraft_engine::panels::commands::sequential_failure(i, command(step), error, results)), + } + } + return ok(json!({"completed":results.len(),"results":results,"undone":0})); + } // (With the agent cursor shown, the pointer has already acted out a short summary of the // batch: `agent_cursor::intercept`.) if let Some(why) = batch_refusal(steps) { @@ -413,7 +516,7 @@ pub fn request_scope(app: &SolveApp, params: &Value) -> Result solidcraft_engine::render::Scene { +pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides) -> Result { let mut palette = crate::viewport::scene_palette(app.viewport_dark(), app.preferences.color_vision); // The view's own background colour (#7688). if let Some([r, g, b]) = app.preferences.viewport_background { @@ -427,9 +530,13 @@ pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides &palette, guides, app.preferences.cosmetic_threads, - ); + ) + .map_err(|e| e.to_string())?; scene.plain_cap = !crate::viewport::section_hatch(app); - scene + if app.preferences.section_hatch == crate::prefs::SectionHatch::One { + scene.part_hatch = None; + } + Ok(scene) } /// The grid and the origin's axes as the window shows them (the Grid and Origin switches). @@ -443,7 +550,7 @@ pub(crate) fn window_guides(app: &SolveApp) -> solidcraft_engine::view::Guides { /// A picture of the view as the window shows it, RGBA, drawn on the GPU with the viewport's /// pipelines (the renderer the app installs). pub(crate) fn view_rgba(app: &SolveApp, w: u32, h: u32) -> Result, String> { - solidcraft_engine::capture::rgba(&view_scene(app, window_guides(app)), &app.cam, w, h).map(|p| p.rgba) + solidcraft_engine::capture::rgba(&view_scene(app, window_guides(app))?, &app.cam, w, h).map(|p| p.rgba) } /// [`view_rgba`] as PNG. @@ -453,6 +560,10 @@ pub fn view_png(app: &SolveApp, w: u32, h: u32) -> Result, String> { } pub fn handle(app: &mut SolveApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + crate::agent_chat::with_tool_request(app, req.chat_turn.as_ref(), |app| handle_request(app, ctx, req)) +} + +fn handle_request(app: &mut SolveApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let level = match request_param_check(&req.method, &req.params) { Ok(level) => level, Err(e) => return err(e), @@ -539,6 +650,95 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> let f = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()); let b = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false); match method { + "ui.blur" => { + // Internal rendering harness; deliberately no saved preference or product UI. + let radius = if let Some(radius) = p.get("radius_px") { + let Some(radius) = radius.as_f64().filter(|v| v.is_finite() && (0.0..=60.0).contains(v)) else { + return err("radius_px must be finite and between 0 and 60"); + }; + Some(radius as f32) + } else { + None + }; + let alpha = if let Some(alpha) = p.get("surface_alpha") { + let alpha = if alpha.is_null() { + None + } else { + let Some(alpha) = alpha.as_f64().filter(|v| v.is_finite() && (0.0..=1.0).contains(v)) else { + return err("surface_alpha must be null or between 0 and 1"); + }; + Some((alpha * 255.0).round() as u8) + }; + Some(alpha) + } else { + None + }; + // Explicit, labelled evidence fixtures only. They can force a failure, never fake + // real renderer support. All validation precedes mutation, including old fields. + let fixture = if let Some(fixture) = p.get("fixture") { + let Some(fixture) = + fixture.as_str().filter(|s| matches!(*s, "clear" | "gpu-software" | "reduce-transparency" | "web-unsupported" | "guard-60")) + else { + return err("unknown blur evidence fixture"); + }; + Some(fixture) + } else { + None + }; + if let Some(radius) = radius { + if let Err(error) = app.blur.set_radius(radius) { + return err(error); + } + app.blur_session.harness_radius = Some(radius); + ctx.request_repaint(); + } + if let Some(alpha) = alpha { + app.blur.set_surface_alpha(alpha); + ctx.request_repaint(); + } + if let Some(fixture) = fixture { + match fixture { + "clear" => { + app.blur_session.harness_unavailable = None; + app.blur_session.harness_radius = None; + app.blur_session.evidence_fixture = None; + } + "gpu-software" => { + app.blur_session.harness_unavailable = Some("prefs.blur_software"); + app.blur_session.evidence_fixture = Some("gpu-software"); + } + "reduce-transparency" => { + app.blur_session.harness_unavailable = Some("prefs.blur_reduce_transparency"); + app.blur_session.evidence_fixture = Some("reduce-transparency"); + } + "web-unsupported" => { + app.blur_session.harness_unavailable = Some("prefs.blur_web"); + app.blur_session.evidence_fixture = Some("web-unsupported"); + } + "guard-60" => { + let radius = app.blur.radius(); + for _ in 0..60 { + app.blur_session.guard.observe(radius, 23.0, true); + } + app.blur_session.evidence_fixture = Some("guard-60"); + } + _ => {} + } + ctx.request_repaint(); + } + let availability = crate::prefs::blur_availability(app); + let reason = match availability { + crate::theme_options::Availability::Unavailable(reason) => Some(app.tr(reason)), + crate::theme_options::Availability::Available => None, + }; + ok( + json!({"radius_px":app.blur.radius(), "max_radius_px":60, "capability":app.blur.capability_for(ctx.viewport_id()), "counters":app.blur.counters(), + "available": availability == crate::theme_options::Availability::Available, "reason": reason, + "evidence_fixture": app.blur_session.evidence_fixture, + "guard": {"tier_cap": app.blur_session.guard.cap, "streak": app.blur_session.guard.streak, + "notice": app.blur_session.guard.notice, "opted_out": app.blur_session.guard.opted_out}}), + ) + } "ui.status_fixture" => wrap(crate::viewport_status_fixture::control(app, p)), "ui.workspace" => { if let Some(workspace) = s("workspace") @@ -576,6 +776,30 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> if let Some(c) = steps.and_then(|steps| steps.iter().find_map(switches_design)) { return err(format!("engine.script unavailable: {c} switches to another design (send it on its own)")); } + if let Some(steps) = + steps.filter(|steps| steps.iter().any(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command))) + { + if steps.len() > 100_000 { + return err("script too long"); + } + let mut results = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let result = command(step) + .ok_or_else(|| "missing command".to_string()) + .and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({})))); + match result { + Ok(result) => results.push(result), + Err(error) => { + let mut reply = json!({"ok":false,"error":error,"step":i + 1}); + if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&error) { + reply["panel_error"] = reason; + } + return Outcome::Done(reply); + } + } + } + return ok(json!(results)); + } let mut replaced = false; let r = app .session @@ -593,7 +817,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> app.follow_view_request(false); wrap(r) } - "engine.commands" => wrap(app.session.execute("engine.commands", &json!({})).map_err(|e| e.to_string())), + "engine.commands" => wrap(execute(app, "engine.commands", json!({}))), "document.inspect" => wrap(app.session.execute("document.inspect", p).map_err(|e| e.to_string())), "document.revision" => wrap(app.session.execute("document.revision", p).map_err(|e| e.to_string())), // The connection already counts as subscribed (`DesignWatch::join`), and its events start @@ -611,9 +835,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> "viewport": app.viewport.rect.map(|r| json!([r.left(), r.top(), r.width(), r.height()])), "camera": app.cam, "tool": app.tool.as_ref().map(|t| t.cmd), - "dialog": app.dialog.as_ref().map(|d| format!("{d:?}")), + "dialog": dialog_state(app), + "windows": open_windows(app), "status": app.status.as_ref().map(|(text, _, error)| json!({"text": text, "error": error})), - "hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")), + "hover": app.viewport.hover, "renderer": if app.viewport.gpu.is_some() { "gpu" } else { "cpu" }, "frame_ms": app.frame_ms, "draw": app.viewport.draw_stats.as_ref().and_then(|s| s.lock().ok().map(|d| json!({ @@ -808,7 +1033,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> return err(e); } } - ok(json!({"tool": app.tool.as_ref().map(|t| t.cmd), "dialog": app.dialog.as_ref().map(|d| format!("{d:?}"))})) + ok(started(app)) } "ui.move" | "ui.click" => { let (Some(x), Some(y)) = (f("x"), f("y")) else { return err("missing x/y") }; @@ -856,8 +1081,22 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> app.synthetic.push(egui::Event::PointerMoved(a)); } let steps = f("steps").unwrap_or(10.0).clamp(1.0, 200.0) as usize; - for k in 1..=steps { - app.synthetic.push(egui::Event::PointerMoved(a + (z - a) * (k as f32 / steps as f32))); + // `via`: [[x, y], ...] the pointer passes through on its way (a lasso's loop, #4376). + let via: Vec = p + .get("via") + .and_then(Value::as_array) + .into_iter() + .flatten() + .take(500) + .filter_map(|q| Some(egui::pos2(q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32))) + .filter(|q| q.is_finite()) + .collect(); + let mut from = a; + for to in via.into_iter().chain([z]) { + for k in 1..=steps { + app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (k as f32 / steps as f32))); + } + from = to; } // `hold_end`: frames to keep the button down at the end (to look at a drag's snap). for _ in 0..f("hold_end").unwrap_or(0.0).clamp(0.0, 600.0) as usize { @@ -874,12 +1113,16 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> }; let Some(id) = app.session.doc.find_feature(&key).map(|f| f.id) else { return err(format!("no feature `{key}`")) }; app.edit_feature(id); - ok(json!({"dialog": app.dialog.as_ref().map(|d| format!("{d:?}")), "marker": app.session.doc.marker})) + let mut reply = started(app); + if let Some(o) = reply.as_object_mut() { + o.insert("marker".into(), json!(app.session.doc.marker)); + } + ok(reply) } "ui.selection" => ok(json!({ "selection": app.session.selection, "dialog": app.dialog.as_ref().map(|d| d.inputs.iter().map(|i| json!({"label": i.label, "items": i.items})).collect::>()), - "hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")), + "hover": app.viewport.hover, "dimensions": crate::dim_view::drawn().into_iter().map(|(id, p)| json!({"id": id, "x": p.x, "y": p.y})).collect::>(), "shown_dimensions": crate::dim_view::model_drawn() .into_iter() @@ -956,13 +1199,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> let proj = crate::viewport::projection(app, rect); let num = |v: &Value, i: usize| v.get(i).and_then(Value::as_f64).unwrap_or(0.0); let world = if let Some(w) = p.get("world") { - Some(solidcraft_engine::geom::Vec3::new(num(w, 0), num(w, 1), num(w, 2))) + Some(solidcore_record::Vec3::new(num(w, 0), num(w, 1), num(w, 2))) } else if let Some(s) = p.get("sketch") { - let st = app.session.world_state(); - app.session - .active_sketch - .and_then(|id| st.sketch(id)) - .map(|ss| ss.plane.to_world(solidcraft_engine::geom::Vec2::new(num(s, 0), num(s, 1)))) + let st = crate::open_meshing::session_world(&app.session); + app.session.active_sketch.and_then(|id| st.sketch(id)).map(|ss| ss.plane.to_world(solidcore_record::Vec2::new(num(s, 0), num(s, 1)))) } else if let Some(n) = p.get("plane").and_then(Value::as_str) { crate::viewport::origin_plane_target(app, &proj, n) } else if let Some(n) = p.get("axis").and_then(Value::as_str) { @@ -972,7 +1212,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } else if let Some(n) = p.get("gizmo").and_then(Value::as_str) { // A handle of the move triad ("x", "xy", "rz", "ball"), moved `by` [x,y,z] mm or // turned `turn` degrees (rings). - let by = p.get("by").map(|b| solidcraft_engine::geom::Vec3::new(num(b, 0), num(b, 1), num(b, 2))).unwrap_or_default(); + let by = p.get("by").map(|b| solidcore_record::Vec3::new(num(b, 0), num(b, 1), num(b, 2))).unwrap_or_default(); crate::gizmo::handle_point(n, by, p.get("turn").and_then(Value::as_f64).unwrap_or(0.0)) } else { None @@ -993,14 +1233,14 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> .take(1000) .map(|v| { let c = |i: usize| v.get(i).and_then(Value::as_f64).unwrap_or(0.0); - proj.to_screen(solidcraft_engine::geom::Vec3::new(c(0), c(1), c(2))).map_or(Value::Null, |q| json!([q.x, q.y])) + proj.to_screen(solidcore_record::Vec3::new(c(0), c(1), c(2))).map_or(Value::Null, |q| json!([q.x, q.y])) }) .collect(); ok(json!(pts)) } "ui.sketchToScreen" => { // Screen points of active-sketch coordinates (for driving sketch interaction). - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let (Some(rect), Some(ss)) = (app.viewport.rect, app.session.active_sketch.and_then(|s| st.sketch(s))) else { return err("no active sketch in a drawn viewport"); }; @@ -1013,7 +1253,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> .take(1000) .map(|v| { let c = |i: usize| v.get(i).and_then(Value::as_f64).unwrap_or(0.0); - let q = solidcraft_engine::geom::Vec2::new(c(0), c(1)); + let q = solidcore_record::Vec2::new(c(0), c(1)); proj.to_screen(ss.plane.to_world(q)).map_or(Value::Null, |p| json!([p.x, p.y])) }) .collect(); @@ -1151,7 +1391,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> "ui.prefs" => wrap(crate::prefs::control(app, p)), "ui.agent_chat" => wrap(crate::agent_chat::control(app, ctx, p)), "ui.help" => match s("item") { - Some(i @ ("about" | "shortcuts" | "report" | "crashes")) => { + Some(i @ ("about" | "updates" | "shortcuts" | "report" | "crashes")) => { crate::help::run(app, ctx, i); ok( json!({"diagnostics": crate::help::diagnostics(app), "version": crate::help::VERSION, "commit": crate::help::COMMIT, "built": crate::help::BUILD_DATE}), @@ -1200,7 +1440,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> if let Some(Err(e)) = s("path").map(vfs::check) { return err(e); } - let scene = view_scene(app, guides); + let scene = match view_scene(app, guides) { + Ok(scene) => scene, + Err(e) => return err(e), + }; let png = match solidcraft_engine::capture::png(&scene, &app.cam, w, h) { Ok(png) => png, Err(e) => return err(format!("render failed: {e}")), @@ -1360,6 +1603,224 @@ pub(crate) fn write_screenshot(image: &egui::ColorImage, path: &str) -> Result<( #[cfg(test)] mod tests { + fn panel_command_app() -> crate::SolveApp { + use crate::panel_runtime::*; + let h = PanelMountHarness::new(false).unwrap(); + let catalogue = solidcraft_engine::panels::fixture_command_catalogue(h.runtime.layout().registry()).unwrap(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.enable_panel_runtime(h.runtime, Box::::default()).unwrap(); + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(FakeNativeAdapter::new(false))).unwrap(); + app + } + fn panel_control(app: &mut crate::SolveApp, method: &str, params: serde_json::Value) -> serde_json::Value { + let (request, _) = super::ControlRequest::new(method, params); + match super::handle(app, &egui::Context::default(), &request) { + super::Outcome::Done(reply) => reply, + _ => panic!("unexpected screenshot"), + } + } + fn panel_steps() -> Vec { + vec![ + json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"log","destination":{"type":"new_section","section":"logs","index":0, + "location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}), + json!({"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}), + ] + } + #[test] + fn panel_control_single_atomic_batch_and_script_share_live_runtime_without_geometry_or_camera_work() { + use solidcraft_engine::panels::ActionSink; + let mut single = panel_command_app(); + let mut batch = panel_command_app(); + let mut script = panel_command_app(); + // A one-body design with a deliberately different camera exercises the + // old first-body-fit condition, rather than making it vacuously false. + for app in [&mut single, &mut batch, &mut script] { + app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + app.cam.distance *= 1.5; + app.session.mark_saved(); + } + let doc = single.session.doc.clone(); + let model = single.session.model.state(); + let camera = single.cam; + let meshes: Vec<_> = model.bodies.iter().map(|body| body.cached_mesh()).collect(); + let invariant = (single.session.document_id.clone(), single.session.revision, single.session.undo.len(), single.session.is_dirty()); + for step in panel_steps() { + assert_eq!(panel_control(&mut single, "engine.execute", step)["ok"], true); + } + assert_eq!(panel_control(&mut batch, "engine.batch", json!({"commands":panel_steps(),"param_check":"strict"}))["ok"], true); + assert_eq!(panel_control(&mut script, "engine.script", json!({"commands":panel_steps(),"param_check":"strict"}))["ok"], true); + let live = single.panel_runtime().unwrap().layout().inspect(); + assert_eq!(batch.panel_runtime().unwrap().layout().layout(), &live.layout); + assert_eq!(script.panel_runtime().unwrap().layout().layout(), &live.layout); + assert_eq!(panel_control(&mut single, "engine.execute", json!({"command":"layout.get"}))["result"]["state"]["revision"], live.revision); + assert!(crate::agent_cursor::picks(&single, "panel.open", &panel_steps()[0]["params"]).is_empty()); + assert_eq!(single.cam, camera); + assert_eq!((single.session.document_id.clone(), single.session.revision, single.session.undo.len(), single.session.is_dirty()), invariant); + assert!(std::sync::Arc::ptr_eq(&doc, &single.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &single.session.model.state())); + for (old, new) in meshes.iter().zip(single.session.model.state().bodies.iter().map(|body| body.cached_mesh())) { + match (old, new) { + (Some(a), Some(b)) => assert!(std::sync::Arc::ptr_eq(a, &b)), + (None, None) => {} + _ => panic!("layout changed tessellation cache"), + } + } + } + #[test] + fn panel_control_reports_structured_missing_capability_unknown_fields_and_lifecycle_batch_errors() { + use solidcraft_engine::panels::ActionSink; + let mut disabled = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let reply = panel_control(&mut disabled, "engine.execute", json!({"command":"layout.get"})); + assert_eq!(reply["ok"], false); + assert_eq!(reply["panel_error"]["rule"], "capability"); + let mut app = panel_command_app(); + for check in ["off", "warn", "strict"] { + let reply = panel_control(&mut app, "engine.execute", json!({"command":"panel.list","params":{"unknown":true},"param_check":check})); + assert_eq!(reply["ok"], false); + assert_eq!(reply["panel_error"]["rule"], "schema"); + assert_eq!(reply["param_check"], check); + } + panel_control(&mut app, "engine.execute", panel_steps()[0].clone()); + let before = app.panel_runtime().unwrap().layout().inspect(); + let reply = panel_control( + &mut app, + "engine.batch", + json!({"commands":[ + {"command":"panel.close","params":{"target":{"type":"instance","id":"log"}}}, + {"command":"panel.open","params":{"kind":"fixture.log","instance":"log"}}]}), + ); + assert_eq!(reply["ok"], false); + assert_eq!(reply["panel_error"]["rule"], "lifecycle"); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); + } + #[test] + fn panel_control_catalogue_batches_and_scripts_retain_memory_and_refuse_unsupported_atomic_domains() { + let mut app = panel_command_app(); + panel_control(&mut app, "engine.execute", panel_steps()[0].clone()); + let reply = panel_control( + &mut app, + "engine.batch", + json!({"commands":[ + {"command":"layout.save","params":{"name":"Control saved"}}, + {"command":"layout.reset"}, {"command":"layout.apply","params":{"name":"Control saved"}}, {"command":"layout.get"}]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["completed"], 4); + assert_eq!(reply["result"]["results"][3]["state"]["layout"]["instances"][0]["id"], "log"); + let mixed = json!({"commands":[{"command":"layout.get"},{"command":"file.new"}]}); + let before = app.session.document_id.clone(); + let reply = panel_control(&mut app, "engine.batch", mixed); + assert_eq!(reply["panel_error"]["rule"], "capability"); + assert_eq!(app.session.document_id, before); + let reply = panel_control( + &mut app, + "engine.script", + json!({"commands":[ + {"command":"layout.workspace.select","params":{"workspace":"fixture.other"}}, + {"command":"layout.apply","params":{"name":"Control saved"}}, {"command":"layout.get"}]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"][2]["state"]["layout"]["workspace"], "fixture.other"); + } + + #[test] + fn null_panel_params_match_single_atomic_sequential_and_script_routes() { + let mut app = panel_command_app(); + let expected = app.run("panel.list", json!({})).unwrap(); + assert_eq!(app.run("panel.list", serde_json::Value::Null).unwrap(), expected); + let single = panel_control(&mut app, "engine.execute", json!({"command":"panel.list","params":null})); + assert_eq!(single["result"], expected); + for (method, rollback) in [("engine.batch", true), ("engine.batch", false), ("engine.script", false)] { + let reply = panel_control( + &mut app, + method, + json!({"rollback":rollback,"commands":[ + {"command":"panel.list","params":null},{"command":"layout.get","params":null}, + ]}), + ); + assert_eq!(reply["ok"], true, "{method}: {reply}"); + let results = if method == "engine.script" { &reply["result"] } else { &reply["result"]["results"] }; + assert_eq!(results[0], expected, "{method}"); + assert_eq!(results[1]["state"], expected["state"]); + } + } + + #[test] + fn null_normal_document_params_remain_accepted_in_panel_containing_sequences() { + for method in ["engine.batch", "engine.script"] { + let mut app = panel_command_app(); + let previous = app.session.document_id.clone(); + let reply = panel_control( + &mut app, + method, + json!({"rollback":false,"commands":[ + {"command":"file.new","params":null},{"command":"panel.list","params":null},{"command":"parameters.list","params":null}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(reply["result"].get("failed").is_none(), "{reply}"); + assert_ne!(app.session.document_id, previous); + assert_eq!(app.panel_runtime().unwrap().environment().document.as_ref().unwrap().0, app.session.document_id); + } + } + #[test] + fn blur_control_validates_before_mutation_and_reports_no_gpu() { + let mut h = crate::scenario::Harness::new(); + for invalid in [json!(-1), json!(61), json!("18"), json!(null)] { + let reply = h.call("ui.blur", json!({"radius_px":invalid})); + assert_eq!(reply["ok"], false, "{reply}"); + assert_eq!(h.app.blur.radius(), 0.0); + } + let reply = h.call("ui.blur", json!({"radius_px":18,"surface_alpha":2})); + assert_eq!(reply["ok"], false); + assert_eq!(h.app.blur.radius(), 0.0); + let reply = h.call("ui.blur", json!({"radius_px":18,"surface_alpha":0.7})); + assert_eq!(reply["ok"], true); + assert!(matches!(h.app.blur.capability(), crate::blur::Capability::Unavailable(_))); + h.frames(2); + assert_eq!(h.app.blur.counters().textures_created, 0); + assert_eq!(h.app.blur.counters().markers_emitted, 0); + h.call("ui.blur", json!({"radius_px":0,"surface_alpha":null})); + assert_eq!(h.app.blur.radius(), 0.0); + } + + #[test] + fn blur_evidence_fixtures_are_atomic_transient_and_never_fake_support() { + let mut h = crate::scenario::Harness::new(); + let source: Value = serde_json::from_str(include_str!("../tests/fixtures/theme-blur.json")).unwrap(); + assert_eq!(h.call("ui.prefs", json!({"theme_import":source,"theme_options":{"blur-review":{"blur":40}}}))["ok"], true); + h.frames(2); + let saved = h.app.preferences.theme_options.clone(); + let revision = h.app.session.revision; + for invalid in [json!(null), json!([]), json!("available"), json!("unknown")] { + assert_eq!(h.call("ui.blur", json!({"fixture":invalid,"radius_px":8}))["ok"], false); + assert_eq!(h.app.blur.radius(), 40.0); + assert_eq!(h.app.blur_session.harness_radius, None); + } + for fixture in ["gpu-software", "reduce-transparency", "web-unsupported"] { + let reply = h.call("ui.blur", json!({"fixture":fixture})); + assert_eq!(reply["result"]["evidence_fixture"], fixture); + assert_eq!(reply["result"]["available"], false); + h.frames(2); + assert_eq!(h.app.blur.counters().textures_created, 0); + assert_eq!(h.app.blur.counters().markers_emitted, 0); + assert_eq!(h.app.preferences.theme_options, saved); + } + h.call("ui.blur", json!({"fixture":"clear"})); + h.call("ui.blur", json!({"fixture":"guard-60"})); + assert_eq!((h.app.blur_session.guard.cap, h.app.blur_session.guard.notice), (4, true)); + assert_eq!(h.app.blur_session.evidence_fixture, Some("guard-60")); + h.app.blur_session.guard.undo(); + assert_eq!((h.app.blur_session.guard.cap, h.app.blur_session.guard.opted_out), (5, true)); + h.call("ui.blur", json!({"fixture":"guard-60"})); + assert_eq!(h.app.blur_session.guard.cap, 5); + assert_eq!(h.app.session.revision, revision, "quality actions never enter document undo"); + assert_eq!(h.app.preferences.theme_options, saved); + h.call("ui.blur", json!({"fixture":"clear"})); + assert!(h.app.blur_session.evidence_fixture.is_none()); + assert!(matches!(h.app.blur.capability(), crate::blur::Capability::Unavailable(_)), "clearing a fixture cannot manufacture a GPU"); + } + use serde_json::json; use solidcraft_engine::{Sel, Session}; @@ -1721,7 +2182,7 @@ mod tests { app.preferences.cosmetic_threads = cosmetic_threads; for hatch in [false, true] { app.session.section_hatch = hatch; - assert_eq!(view_scene(&app, Default::default()).plain_cap, !hatch); + assert_eq!(view_scene(&app, Default::default()).unwrap().plain_cap, !hatch); app.session.selection = vec![Sel::Plane { name: "XZ".into() }]; app.start("inspect.section"); let Some(crate::dialogs::Kind::Section { hatch: preview_hatch, .. }) = app.dialog.as_mut().map(|d| &mut d.kind) else { @@ -1729,7 +2190,7 @@ mod tests { }; *preview_hatch = !hatch; assert_eq!( - view_scene(&app, Default::default()).plain_cap, + view_scene(&app, Default::default()).unwrap().plain_cap, hatch, "the preview's hatch overrides the session with cosmetic_threads={cosmetic_threads}" ); @@ -2194,12 +2655,23 @@ mod tests { assert_eq!(call("ui.render", json!({"path": at(&root, "a.png"), "width": 32, "height": 32}), true)["ok"], true); } assert_eq!(call("ui.screenshot", json!({"path": at(&root, "b.png")}), true)["ok"], true); + // Settings profiles are read and written by the app, not the engine, and stay inside too (#11362). + let profile = |id: &str, params: Value| json!({"command": id, "params": params}); + let poc = json!({"format": "solidcraft-profile/1", "name": "scope-poc"}); + assert_eq!(call("engine.execute", profile("settings.profile.import", json!({"profile": poc})), true)["ok"], true); + let inside = json!({"name": "scope-poc", "path": at(&root, "p.json")}); + assert_eq!(call("engine.execute", profile("settings.profile.export", inside), true)["ok"], true); + assert_eq!(call("engine.execute", profile("settings.profile.import", json!({"path": at(&root, "p.json")})), true)["ok"], true); + std::fs::write(at(&base, "p.json"), poc.to_string()).unwrap(); for (method, params) in [ ("engine.execute", export(at(&out, "a.step"))), ("engine.execute", export(at(&root, "../out/a.step"))), ("engine.script", json!({"commands": [{"command": "file.export", "params": {"path": at(&out, "a.step")}}]})), ("ui.render", json!({"path": at(&out, "a.png"), "width": 32, "height": 32})), ("ui.screenshot", json!({"path": at(&out, "b.png")})), + ("engine.execute", profile("settings.profile.export", json!({"name": "scope-poc", "path": at(&out, "p.json")}))), + ("engine.execute", profile("settings.profile.import", json!({"path": at(&base, "p.json")}))), + ("engine.execute", profile("settings.profile.import", json!({"path": at(&out, "missing.json")}))), ] { let v = call(method, params, true); assert!(v["ok"] == false && v.to_string().contains("outside the folders this agent may use"), "{method}: {v}"); @@ -2428,6 +2900,55 @@ mod tests { } } + /// #9087: the dialog is reported as data (its command, inputs and what OK runs), not as the + /// form's Debug text; `ui.start` and `ui.editFeature` reply with what they opened, and the + /// tool windows (Parameters, Bill of Materials) are reported by the command that opens them. + #[test] + fn dialogs_and_tool_windows_are_reported_as_data() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app = SolveApp::new(s, Services::default()); + let r = h.call("ui.start", json!({"command": "solid.fillet"})); + let d = &r["result"]["dialog"]; + assert_eq!((&d["command"], &d["title"], &d["editing"]), (&json!("solid.fillet"), &json!("FILLET"), &Value::Null), "{r}"); + assert_eq!((&d["inputs"][0]["active"], &d["inputs"][0]["items"]), (&json!(true), &json!([])), "{r}"); + assert!(d["commands"].is_null() && d["waiting"].is_string(), "no edge picked yet: {r}"); + assert_eq!((&r["result"]["pending"], &r["result"]["windows"]), (&json!(false), &json!([])), "{r}"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["dialog"], *d, "ui.inspect reports the same"); + crate::dialogs::cancel(&mut h.app); + + let feature = h.app.session.doc.features[0].id; + let r = h.call("ui.editFeature", json!({"feature": feature})); + let d = &r["result"]["dialog"]; + assert_eq!((&d["command"], &d["editing"]), (&json!("solid.box"), &json!(feature)), "{r}"); + // OK rebuilds the feature in place, from what the form holds. + let runs = &d["commands"][0]; + assert_eq!((&runs["command"], &runs["params"]["command"]), (&json!("timeline.redefine"), &json!("solid.box")), "{r}"); + assert_eq!((&runs["params"]["feature"], &runs["params"]["params"]["length"]), (&json!(feature), &json!("40")), "{r}"); + assert!(r["result"].get("marker").is_some(), "{r}"); + crate::dialogs::cancel(&mut h.app); + + for (command, windows) in + [("parameters.change", json!(["parameters.change"])), ("assembly.bom", json!(["parameters.change", "assembly.bom"]))] + { + let r = h.call("ui.start", json!({"command": command})); + assert_eq!((&r["result"]["dialog"], &r["result"]["tool"], &r["result"]["windows"]), (&Value::Null, &Value::Null, &windows), "{r}"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["windows"], windows, "{command}"); + } + h.call("ui.help", json!({"item": "about"})); + assert_eq!( + h.call("ui.inspect", json!({}))["result"]["windows"], + json!(["parameters.change", "assembly.bom", "about"]), + "the Help menu's windows too" + ); + + // What is under the pointer is a selection-like item, not the viewport's Debug text. + h.app.viewport.hover = Some(crate::viewport::Hit::Face { body: "Body1".into(), index: 2, point: solidcore_record::Vec3::new(1.0, 2.0, 3.0) }); + let hover = json!({"type": "face", "body": "Body1", "index": 2, "point": [1.0, 2.0, 3.0]}); + assert_eq!(h.call("ui.selection", json!({}))["result"]["hover"], hover); + } + /// #9087: a sample index that names no sample is refused, so an agent can tell a typo from /// a sample that opened. The index is checked before it reaches `open_sample`, which would /// otherwise drop it and reply `ok`. diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rs index 33829820f..931f7ce4b 100644 --- a/crates/ui-egui/src/control_job.rs +++ b/crates/ui-egui/src/control_job.rs @@ -67,13 +67,22 @@ const AHEAD_AREAS: &[&str] = &[ const NAMES_A_FILE: &[&str] = &["path", "paths", "file", "files", "dir", "folder", "url", "out"]; /// Commands that change nothing in the design and write a file: they run on a copy. -const ANSWERED_ON_A_COPY: &[&str] = &["file.export", "file.save_mesh"]; +const ANSWERED_ON_A_COPY: &[&str] = + &["file.export", "file.export_3mf", "file.export_obj", "file.export_step", "file.export_stl", "file.export_urdf", "file.save_mesh"]; /// Commands that only read the design, which can take long on a large one (a measure of every /// body, an inspection that measures them, #4604; a clearance or interference check of every pair /// of bodies, minutes on an assembly of 150): they run on a copy too, whatever the preference, /// since an answer from the design as it was when asked has no order to keep. -const READ_ON_A_COPY: &[&str] = &["inspect.measure", "document.inspect", "inspect.clearance", "inspect.interference"]; +const READ_ON_A_COPY: &[&str] = &[ + "inspect.measure", + "document.inspect", + "inspect.clearance", + "inspect.interference", + // Physical properties of a component or placement: every body of every placement (#8706). + "component.properties", + "occurrence.properties", +]; /// Exports and readings computing at once; more run here. const MAX_ANSWERING: usize = 4; @@ -126,6 +135,19 @@ pub(crate) fn changes_the_design(method: &str) -> bool { matches!(method, "engine.execute" | "command" | "engine.script" | "engine.batch") } +/// Whether `doc` is the design `session` shows, as it is or edited since (an undo step away). +fn shows_design(session: &solidcraft_engine::Session, doc: &Arc) -> bool { + Arc::ptr_eq(&session.doc, doc) || session.undo.iter().chain(&session.redo).any(|snap| Arc::ptr_eq(&snap.doc, doc)) +} + +/// The reply to a request whose design left the window while it computed. +fn design_replaced(label: &str) -> Value { + json!({ + "ok": false, + "error": format!("the design was replaced (another tab, or a file opened) while `{label}` computed; nothing was applied"), + }) +} + /// What a request computes off the window thread. enum Work { /// Evaluated ahead: once in, the request runs here. `doc` and `revision` are the design it @@ -413,9 +435,19 @@ impl SolveApp { if let Some(level) = level { copy.param_check = level; } + // The copy has no history and no file (#9624): an inspection reports the design's own. + let s = &self.session; + let own = (id == "document.inspect").then(|| (s.undo.len(), s.redo.len(), s.path.clone())); let rx = spawn(scope, move || { let mut reply = match copy.execute(id, ¶ms) { - Ok(v) => json!({"ok": true, "result": v}), + Ok(mut v) => { + if let (Some((undo, redo, path)), Some(o)) = (own, v.as_object_mut()) { + o.insert("undo".into(), json!(undo)); + o.insert("redo".into(), json!(redo)); + o.insert("path".into(), json!(path)); + } + json!({"ok": true, "result": v}) + } Err(e) => json!({"ok": false, "error": e.to_string()}), }; if let Some(level) = level { @@ -471,6 +503,16 @@ impl SolveApp { self.control_job = None; return; } + // The design it computes for has left the window (closed, another tab, a file opened): + // refused now, however long its computation has left, so the requests behind it, which + // are for the design shown, don't wait for it. + let left = matches!(&job.work, Work::Ahead { doc, .. } if !shows_design(&self.session, doc)); + if left { + if let Some(job) = self.control_job.take() { + let _ = job.req.reply.send(design_replaced(&job.label)); + } + return; + } if job.poll().is_none() { ctx.request_repaint_after(std::time::Duration::from_millis(100)); return; @@ -484,13 +526,8 @@ impl SolveApp { let Work::Ahead { commands, doc, revision, tries, kept } = job.work else { return }; let s = &self.session; let same = Arc::ptr_eq(&s.doc, &doc); - // The design it was computed for is still this one, edited since (an undo step away). - let edited = !same && s.undo.iter().chain(&s.redo).any(|snap| Arc::ptr_eq(&snap.doc, &doc)); - if !same && !edited { - let _ = job.req.reply.send(json!({ - "ok": false, - "error": format!("the design was replaced (another tab, or a file opened) while `{}` computed; nothing was applied", job.label), - })); + if !shows_design(s, &doc) { + let _ = job.req.reply.send(design_replaced(&job.label)); return; } if (!same || s.revision != revision) && tries < MAX_TRIES { diff --git a/crates/ui-egui/src/crash_ui.rs b/crates/ui-egui/src/crash_ui.rs index 130f058f4..f09b3d785 100644 --- a/crates/ui-egui/src/crash_ui.rs +++ b/crates/ui-egui/src/crash_ui.rs @@ -309,7 +309,41 @@ mod tests { fn inventory_actions_details_empty_state_and_keyboard_remain_reachable() { let d = folder("inventory"); let mut h = crate::scenario::Harness::new(); + h.app.preferences.language = "en".into(); + h.app.home.open = false; h.app.crashes.folder = Some(d.clone()); + let assert_general_count = |h: &mut crate::scenario::Harness, count: usize| { + // The fixture folder was assigned after startup; programmatic Preferences uses the cached inventory. + h.app.crashes.refresh(); + for theme in ["light", "dark"] { + h.call("ui.prefs", json!({"open":"General", "theme":theme})); + crate::prefs::reveal_preference(h, "prefs:crash_count"); + assert_eq!(h.app.crashes.saved_count(), count); + assert!(h.widget(&format!("{count} saved")).is_some()); + let badge = crate::scenario::rect_of("prefs:crash_count").unwrap(); + assert!((badge.height() - 18.0).abs() < 0.5); + assert!(crate::scenario::rect_of("prefs:page_body").unwrap().contains_rect(badge)); + let t = crate::theme::Tokens::get(); + let fill = if count == 0 { t.dialog_footer } else { t.pref_note_fill }; + assert!( + h.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Rect(rect) if rect.rect == badge && rect.fill == fill)), + "{theme}: count tone reflects reports waiting" + ); + let buttons: Vec<_> = h + .output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .filter(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some(h.app.tr("prefs.crash_reports"))) + .collect(); + assert_eq!(buttons.len(), 1); + assert!(!buttons[0].1.is_disabled(), "opening reports stays available even at zero"); + h.step(&json!({"click":{"handle":"prefs:cancel"}})).unwrap(); + } + }; + assert_general_count(&mut h, 1); super::open(&mut h.app); h.frames(5); for handle in [ @@ -349,6 +383,7 @@ mod tests { assert!(h.app.crashes.reports.is_empty()); h.step(&json!({"key":"Escape"})).unwrap(); assert!(!h.app.crashes.open); + assert_general_count(&mut h, 0); let _ = std::fs::remove_dir_all(d); } } diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rs index d9e945a0b..ad801ed55 100644 --- a/crates/ui-egui/src/deferred.rs +++ b/crates/ui-egui/src/deferred.rs @@ -52,6 +52,28 @@ impl Deferred { } } +#[cfg(test)] +impl Deferred { + /// A command that never finishes computing, with the sender that keeps it so, for the tests + /// of what waits for one (the real worker would finish in a moment). + pub(crate) fn never_done(id: &str, params: Value, revision: u64) -> (Self, std::sync::mpsc::Sender>) { + let (tx, rx) = std::sync::mpsc::channel(); + let job = Deferred { done: rx, evaluated: None, started: crate::now_ms(), command: (id.to_string(), params), revision, kept: None }; + (job, tx) + } +} + +/// What one design has computing off the window thread or waiting its turn. It belongs to that +/// design: it waits with its tab while another is shown, holds up nothing there, and goes when +/// the design closes (the worker runs on to its end and its result is dropped). +#[derive(Default)] +pub struct DocJobs { + deferred: Option, + queue: Vec<(String, Value)>, + start_after_roll: Option<(String, u64)>, + delete_check: Option, +} + /// How a command asked to run off the window thread goes. enum Start { /// It computes off the window thread. @@ -66,6 +88,9 @@ pub struct DeleteCheck { /// When it started (ms). pub(crate) started: f64, then: AfterCheck, + /// What the check computes, for the delete itself to find instead of building it again on + /// the window thread (#9917). + kept: std::sync::Arc, /// The design's revision it was computed for: a design changed meanwhile checks again. revision: u64, } @@ -97,8 +122,8 @@ impl AfterCheck { } } - /// Carry on with the check's replies. - fn finish(self, app: &mut SolveApp, replies: Vec>) { + /// Carry on with the check's replies, and what it `kept` (when it ran ahead) for the delete. + fn finish(self, app: &mut SolveApp, replies: Vec>, kept: Option>) { match self { AfterCheck::Timeline { features, groups } => { let reports: Vec = replies.into_iter().map(Result::unwrap_or_default).collect(); @@ -106,7 +131,7 @@ impl AfterCheck { } AfterCheck::Selection(params) => { let report = replies.into_iter().next().unwrap_or_else(|| Err("the delete was not checked".into())); - crate::delete::checked(app, params, report); + crate::delete::checked(app, params, report, kept); } } } @@ -119,6 +144,45 @@ fn replaced_by_a_later_one(id: &str) -> bool { } impl SolveApp { + /// Swap the active design's [`DocJobs`] for `incoming`, the jobs of the design taking its + /// place, and hand back the outgoing ones. + pub(crate) fn swap_jobs(&mut self, incoming: DocJobs) -> DocJobs { + DocJobs { + deferred: std::mem::replace(&mut self.deferred, incoming.deferred), + queue: std::mem::replace(&mut self.deferred_queue, incoming.queue), + start_after_roll: std::mem::replace(&mut self.start_after_roll, incoming.start_after_roll), + delete_check: std::mem::replace(&mut self.delete_check, incoming.delete_check), + } + } + + /// The active design's revision moved from `before` to `after` only to refresh the views + /// (a tab shown again): its jobs were not computed for an older design. + pub(crate) fn jobs_view_changed(&mut self, before: u64, after: u64) { + if let Some(job) = &mut self.deferred + && job.revision == before + { + job.revision = after; + } + if let Some(check) = &mut self.delete_check + && check.revision == before + { + check.revision = after; + } + } + + /// A direct exit or editor switch supersedes any queued sketch exit. A late worker must + /// never finish a different sketch that was opened while it computed. + pub(crate) fn take_sketch_exit(&mut self) -> Option { + let is_exit = |id: &str| matches!(id, "sketch.finish" | "sketch.cancel"); + let pending = self.deferred.as_ref().filter(|job| is_exit(&job.command.0)).map(|job| job.command.0.clone()); + if pending.is_some() { + self.deferred = None; + } + let queued = self.deferred_queue.iter().find(|(id, _)| is_exit(id)).map(|(id, _)| id.clone()); + self.deferred_queue.retain(|(id, _)| !is_exit(id)); + pending.or(queued) + } + /// Run a command that may recompute much of the history, off the window thread when it takes /// a while (see the module notes). `Ok(Null)` when it is left computing or waiting its turn: /// its outcome then shows as any command's does (an error in the status line). @@ -126,6 +190,9 @@ impl SolveApp { if id == "timeline.play" { return self.run(id, params); } + if matches!(id, "edit.undo" | "edit.redo" | "timeline.roll_to") { + self.close_editor_for_history()?; + } // A manual history action takes over from playback. Playback takes its state out // while submitting its own next step, then puts it back to wait for that step. crate::timeline::stop_playback(self); @@ -173,6 +240,25 @@ impl SolveApp { started.into_iter().flatten().reduce(f64::min) } + /// Whether the "Computing" toast can stop what it waits for (#8266): a history command or a + /// delete's check computing off the window thread. A feature edit applying has its own + /// dialog, with its own Cancel. + pub fn can_cancel_computing(&self) -> bool { + self.deferred.is_some() || self.delete_check.is_some() + } + + /// Stop waiting for the history command, and the delete check, computing off the window thread + /// (#8266), and drop the commands waiting behind them. The design is as it was before they + /// started: a command only runs for real once its evaluation is in. The worker threads run + /// to the end of what they evaluate and their results are dropped (the same as Cancel while a + /// feature is applying). + pub fn cancel_computing(&mut self) { + self.deferred = None; + self.deferred_queue.clear(); + self.delete_check = None; + self.start_after_roll = None; + } + /// Run a delete's check `commands` and carry on with `then` once their replies are in: off /// the window thread when it takes longer than the app's wait (see the module notes), /// otherwise right away. A Delete while another delete is being checked is left out. @@ -186,6 +272,7 @@ impl SolveApp { && self.file_picker.is_none() { let ahead = self.session.ahead(); + let kept = ahead.kept(); let (tx, rx) = std::sync::mpsc::channel(); let checks = commands.clone(); let spawned = std::thread::Builder::new().name("delete check".into()).spawn(move || { @@ -193,17 +280,17 @@ impl SolveApp { let _ = tx.send(replies); }); if spawned.is_ok() { - let check = DeleteCheck { done: rx, started: crate::now_ms(), then, revision: self.session.revision }; + let check = DeleteCheck { done: rx, started: crate::now_ms(), then, revision: self.session.revision, kept }; // As with the history's commands, zero always leaves it for a later frame. match (wait.is_zero(), check.done.recv_timeout(wait)) { - (false, Ok(replies)) => check.then.finish(self, replies), + (false, Ok(replies)) => check.then.finish(self, replies, Some(check.kept.clone())), _ => self.delete_check = Some(check), } return; } } let replies = commands.iter().map(|(id, params)| self.session.execute(id, params).map_err(|e| e.to_string())).collect(); - then.finish(self, replies); + then.finish(self, replies, None); } /// Each frame: a delete whose check is in carries on (checked again when the design changed @@ -222,7 +309,7 @@ impl SolveApp { match replies { None => self.set_status("the delete could not be checked", true), Some(_) if check.revision != self.session.revision => check.then.restart(self), - Some(replies) => check.then.finish(self, replies), + Some(replies) => check.then.finish(self, replies, Some(check.kept)), } } diff --git a/crates/ui-egui/src/delete.rs b/crates/ui-egui/src/delete.rs index ac35f4109..cee70ad27 100644 --- a/crates/ui-egui/src/delete.rs +++ b/crates/ui-egui/src/delete.rs @@ -2,7 +2,10 @@ //! the viewport or the browser goes in one undoable step through `selection.delete`. When it //! takes other features with it or makes some fail, a confirmation lists them first. +use std::sync::Arc; + use serde_json::{Value, json}; +use solidcraft_engine::doc::KeptResults; use crate::SolveApp; use crate::ui_kit; @@ -15,6 +18,8 @@ const MAX_LISTED: usize = 20; pub struct Pending { pub params: Value, pub report: Value, + /// What the dry run computed ahead, for the delete to find (#9917). + pub kept: Option>, } /// What Delete acts on now: the selection (bodies not locked), plus the components picked in @@ -71,6 +76,11 @@ pub fn delete_selection(app: &mut SolveApp) { request(app, params); } +/// Whether Delete has nothing to act on: nothing selected, and no joint open in Edit Joint. +pub fn nothing_to_delete(app: &SolveApp) -> bool { + is_empty(&selection_params(app)) && edited_joint(app).is_none() +} + /// The joint the open Edit Joint dialog edits. fn edited_joint(app: &SolveApp) -> Option { match app.dialog.as_ref().map(|d| &d.kind) { @@ -122,7 +132,7 @@ pub fn request(app: &mut SolveApp, params: Value) { } /// [`request`] once its dry run's report is in. -pub(crate) fn checked(app: &mut SolveApp, params: Value, report: Result) { +pub(crate) fn checked(app: &mut SolveApp, params: Value, report: Result, kept: Option>) { let report = match report { Ok(r) => r, Err(e) => { @@ -136,14 +146,16 @@ pub(crate) fn checked(app: &mut SolveApp, params: Value, report: Result>) { + match app.run_with_kept(kept, |app| app.run("selection.delete", params.clone())) { Ok(r) => { app.tree.picked_components.clear(); app.tree.picked_canvases.clear(); @@ -160,7 +172,7 @@ fn run(app: &mut SolveApp, params: &Value) { pub fn confirm(app: &mut SolveApp, accept: bool) -> bool { let Some(p) = app.menu.confirm.take() else { return false }; if accept { - run(app, &p.params); + run(app, &p.params, p.kept); } true } diff --git a/crates/ui-egui/src/design_properties.rs b/crates/ui-egui/src/design_properties.rs index 92a66eb5c..254f6e572 100644 --- a/crates/ui-egui/src/design_properties.rs +++ b/crates/ui-egui/src/design_properties.rs @@ -9,10 +9,14 @@ //! about; both are `ui_kit::Window` cards. While the card is open, [`overlay`] marks the centre //! of mass in the view with the principal axes standing out of it. +use solidcraft_engine::geom::prelude::*; +use std::sync::Arc; + use egui::{Align2, FontId, Stroke}; use serde_json::{Map, Value, json}; +use solidcore_record::Vec3; use solidcraft_engine::doc::metadata::{DESCRIPTION, Owner, keys}; -use solidcraft_engine::geom::Vec3; +use solidcraft_engine::doc::progress::Progress; use crate::SolveApp; use crate::ui_kit; @@ -127,12 +131,26 @@ pub fn open_object(app: &mut SolveApp, command: &str, params: &Value, fallback: close_object(app); // A large assembly takes seconds to measure, which froze the window (#5203): measured on a // copy beside it, the card shows when done. Headless and in tests (no wait set), here. + // The worker reports how many bodies it has measured, and stops when the card closes (#8706). + let progress = Arc::new(Progress::default()); + // Tests hold the reply until let go (`apply_gate`), so a window thread held up under load + // cannot find the measurement already in where the card should still be measuring. + #[cfg(test)] + let gate = app.apply_gate.clone(); + let hold = move || { + #[cfg(test)] + if let Some(gate) = gate + && let Ok(gate) = gate.lock() + { + let _ = gate.recv(); + } + }; if let Some(wait) = app.apply_off_thread - && let Some(rx) = measure_beside(app.session.scratch(), command, params) + && let Some(rx) = measure_beside(app.session.scratch(), command, params, progress.clone(), hold) { match rx.recv_timeout(wait) { Ok(reply) => opened(app, reply, fallback), - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => app.menu.props_measuring = Some(Measuring { fallback, rx }), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => app.menu.props_measuring = Some(Measuring { fallback, rx, progress }), Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => app.set_status(app.tr("ui.properties.measuring_failed").to_string(), true), } return; @@ -148,10 +166,27 @@ pub fn close_object(app: &mut SolveApp) { } /// A Properties measurement running beside the window (#5203): the card's title when the reply -/// has no name, and the reply to come. +/// has no name, the reply to come, and how far the worker is (#8706). pub struct Measuring { fallback: String, rx: std::sync::mpsc::Receiver>, + /// The worker's progress; cancelling it stops the measuring at its next body. + progress: Arc, +} + +impl Measuring { + /// Bodies measured so far and how many there are (none before the worker counts them). + pub fn bodies(&self) -> Option<(usize, usize)> { + self.progress.work().filter(|(stage, _, _)| *stage == "measuring").map(|(_, done, total)| (done, total)) + } +} + +impl Drop for Measuring { + /// A card closed (or a design switched away from) stops its measuring, which on a large + /// assembly would otherwise run on for minutes (#8706). + fn drop(&mut self) { + self.progress.cancel(); + } } /// Show `reply` in the card, titled with its name (else `fallback`); a refusal goes to the @@ -166,15 +201,24 @@ fn opened(app: &mut SolveApp, reply: Result, fallback: String) { } } -/// Run `command` on `copy` on a worker; the reply comes on the returned channel. +/// Run `command` on `copy` on a worker, watched by `progress`; the reply comes on the returned +/// channel once `hold` returns (which only tests make wait). #[cfg(not(target_arch = "wasm32"))] -fn measure_beside(mut copy: solidcraft_engine::Session, command: &str, params: &Value) -> Option>> { +fn measure_beside( + mut copy: solidcraft_engine::Session, + command: &str, + params: &Value, + progress: Arc, + hold: impl FnOnce() + Send + 'static, +) -> Option>> { let (tx, rx) = std::sync::mpsc::channel(); let (command, params) = (command.to_string(), params.clone()); std::thread::Builder::new() .name("properties".into()) .spawn(move || { - let _ = tx.send(copy.execute(&command, ¶ms).map_err(|e| e.to_string())); + let reply = solidcraft_engine::doc::progress::watch(progress, || copy.execute(&command, ¶ms)); + hold(); + let _ = tx.send(reply.map_err(|e| e.to_string())); }) .ok()?; Some(rx) @@ -182,26 +226,41 @@ fn measure_beside(mut copy: solidcraft_engine::Session, command: &str, params: & /// No threads on the web: measured here. #[cfg(target_arch = "wasm32")] -fn measure_beside(_copy: solidcraft_engine::Session, _command: &str, _params: &Value) -> Option>> { +fn measure_beside( + _copy: solidcraft_engine::Session, + _command: &str, + _params: &Value, + _progress: Arc, + _hold: impl FnOnce() + Send + 'static, +) -> Option>> { None } /// While a measurement runs beside the window: a card saying so (Close drops it), and the /// Properties card in its place once the reply is in. fn show_measuring(app: &mut SolveApp, ctx: &egui::Context) { - let Some(m) = app.menu.props_measuring.take() else { return }; + let Some(mut m) = app.menu.props_measuring.take() else { return }; match m.rx.try_recv() { - Ok(reply) => return opened(app, reply, m.fallback), + Ok(reply) => return opened(app, reply, std::mem::take(&mut m.fallback)), Err(std::sync::mpsc::TryRecvError::Disconnected) => return app.set_status(app.tr("ui.properties.measuring_failed").to_string(), true), Err(std::sync::mpsc::TryRecvError::Empty) => {} } ctx.request_repaint_after(std::time::Duration::from_millis(100)); - let (heading, text) = (app.tr("ui.properties").to_string(), app.tr("ui.properties.measuring").to_string()); + // How far it is, once the worker has counted the bodies (#8706). + let bodies = m.bodies(); + let heading = app.tr("ui.properties").to_string(); + let text = match bodies { + Some((done, total)) => crate::i18n::format("ui.properties.measuring_bodies", &[("done", &done.to_string()), ("total", &total.to_string())]), + None => app.tr("ui.properties.measuring").to_string(), + }; let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_props"), "settings", &heading).actions("", "Close", None).show(ctx, true, |ui| { ui.horizontal(|ui| { ui.spinner(); ui_kit::text(ui, &text, ui_kit::Text::Note("measuring")); }); + if let Some((done, total)) = bodies.filter(|(_, total)| *total > 0) { + ui_kit::progress(ui, "properties_measuring", done as f32 / total as f32); + } }); if !(closed || action == ui_kit::Action::Cancel) { app.menu.props_measuring = Some(m); @@ -422,6 +481,7 @@ pub fn show_object(app: &mut SolveApp, ctx: &egui::Context) { #[cfg(test)] mod tests { use serde_json::json; + use solidcraft_engine::geom::prelude::*; use crate::scenario::Harness; @@ -503,6 +563,7 @@ mod tests { assert_ne!(english.text(k.label), k.label, "`{}`'s label is in the English catalog", k.name); } let mut h = Harness::new(); + h.app.preferences.language = "en".into(); // A key a newer SolidCraft might read: kept as another tool's data, never labelled as one of ours. h.app.session.doc_mut().metadata.0.insert("future_key".into(), json!("kept")); h.step(&json!({"start": "document.metadata"})).unwrap(); @@ -522,7 +583,7 @@ mod tests { /// its centre of mass with three principal axes a third of the box's diagonal long. #[test] fn the_measure_panels_properties_button_opens_the_window_with_the_moment_of_inertia() { - use solidcraft_engine::geom::Vec3; + use solidcore_record::Vec3; let mut h = Harness::new(); h.app.run("solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"})).unwrap(); h.step(&json!({"start": "component.properties"})).unwrap(); @@ -585,13 +646,18 @@ mod tests { h.app.run("solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"})).unwrap(); let here = h.app.session.execute("component.properties", &json!({})).unwrap(); h.app.apply_off_thread = Some(std::time::Duration::ZERO); + // The worker holds its reply until let go, so a window thread held up under load cannot + // find it already in. + let (finish, gate) = std::sync::mpsc::channel(); + h.app.apply_gate = Some(std::sync::Arc::new(std::sync::Mutex::new(gate))); super::open_object(&mut h.app, "component.properties", &json!({}), String::new()); assert!(h.app.menu.props.is_none(), "nothing is waited for on the window thread"); let m = h.app.menu.props_measuring.take().expect("measuring beside the window"); + finish.send(()).unwrap(); assert_eq!(m.rx.recv().unwrap().unwrap(), here, "the copy measures what the design here does"); let (tx, rx) = std::sync::mpsc::channel(); - h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx }); + h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx, progress: Default::default() }); h.frames(2); assert!(h.widget("Measuring…").is_some() && h.app.menu.props.is_none()); tx.send(Ok(here.clone())).unwrap(); @@ -599,12 +665,58 @@ mod tests { assert_eq!(h.app.menu.props.as_ref().map(|(_, v)| v), Some(&here)); assert!(h.widget("Moment of inertia").is_some()); + // #8706: while it measures, the card says how many bodies are done, and Close stops the + // worker rather than leaving it to measure on for minutes. let (_tx, rx) = std::sync::mpsc::channel::>(); super::close_object(&mut h.app); - h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx }); + let progress = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default()); + h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx, progress: progress.clone() }); + solidcraft_engine::doc::progress::watch(progress.clone(), || { + if let Some(w) = solidcraft_engine::kernel::watch::current() { + w.progress("measuring", 3, 10); + } + }); h.frames(2); + assert!(h.widget("Measuring… 3 of 10 bodies").is_some()); h.step(&json!({"widget": "Close"})).unwrap(); assert!(h.app.menu.props_measuring.is_none() && h.app.menu.props.is_none(), "Close drops the measurement"); + assert!(progress.is_cancelled(), "Close stops the worker"); + } + + /// #8706: Properties of an assembly from the Browser's menu returns at once with the card + /// measuring on a copy, and the result (the same a script gets) fills it in. + #[test] + fn assembly_properties_from_the_menu_measure_off_the_window_thread() { + let mut h = Harness::new(); + let block = h.app.run("component.create", json!({"name": "Block"})).unwrap()["component"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap(); + for i in 1..12 { + h.app.run("occurrence.copy", json!({"component": block, "translate": [20 * i, 0, 0]})).unwrap(); + } + h.app.apply_off_thread = Some(std::time::Duration::ZERO); + // Held until checked: under load the worker could otherwise finish before the menu returns. + let (finish, gate) = std::sync::mpsc::channel(); + h.app.apply_gate = Some(std::sync::Arc::new(std::sync::Mutex::new(gate))); + let items = crate::context_menu::items(&h.app, &crate::context_menu::Target::Component { id: 0 }); + let item = items.iter().find(|i| i.label == "Properties").expect("Properties item"); + crate::context_menu::run_item(&mut h.app, item, egui::pos2(0.0, 0.0)); + assert!(h.app.menu.props_measuring.is_some(), "the menu returns at once, the card measuring"); + assert!(h.app.menu.props.is_none()); + finish.send(()).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300); + while h.app.menu.props.is_none() { + assert!(std::time::Instant::now() < deadline, "the measurements never came in"); + assert!(h.app.menu.props_measuring.is_some(), "still measuring until the result is in"); + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(h.app.menu.props_measuring.is_none()); + let (title, v) = h.app.menu.props.clone().unwrap(); + assert_eq!(title, h.app.session.doc.name); + assert_eq!(v["body_count"], 12); + assert!((v["total"]["volume_mm3"].as_f64().unwrap() - 12_000.0).abs() < 1e-6, "{v}"); + let script = h.app.session.execute("component.properties", &json!({"component": 0})).unwrap(); + assert_eq!(v, script); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index df1acab07..bd1a3e120 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2,18 +2,19 @@ //! inputs (geometry picked in the viewport, never typed), then runs its command; it never //! changes the design itself. Things selected before the command starts become its input. +use crate::ui_kit::BackingTooltipExt as _; use crate::ui_kit::choice_row; +use solidcraft_engine::geom::prelude::*; use std::hash::{Hash, Hasher}; use egui::{RichText, vec2}; use serde_json::{Value, json}; +use solidcore_record::Vec3; use solidcraft_engine::Sel; use solidcraft_engine::Session; use solidcraft_engine::doc::expr::Kind as ValueKind; -use solidcraft_engine::doc::{ - AxisRef, Direction, FeatureKind, FilletStyle, HoleKind, Operation, PatternKind, PlaneRef, ProfileSel, ThinSide, ThreadHandedness, -}; -use solidcraft_engine::geom::{Aabb3, Vec3}; +use solidcraft_engine::doc::{AxisRef, Direction, FeatureKind, FilletStyle, HoleKind, Operation, PatternKind, PlaneRef, ProfileSel, ThinSide}; +use solidcraft_engine::geom::Aabb3; use crate::SolveApp; use crate::selection::{ @@ -99,6 +100,12 @@ const EXTRUDE_ACCEPT: Accept = PROFILES | PLANAR_FACES; const THIN_ACCEPT: Accept = PROFILES | CURVES; const PROJECT_GEOMETRY: Accept = EDGES | FACES | selection::VERTICES | PLANES | AXES | selection::SKETCH_LINES | selection::EXTERNAL_POINTS | selection::ORIGIN; +/// What Intersect cuts with the sketch plane, picked one by one: faces, model edges and the +/// curves of other sketches (#10484); an edge or a sketch line gives the points where it crosses. +const INTERSECT_GEOMETRY: Accept = EDGES | FACES | selection::SKETCH_LINES; +/// What Align's From and To pick: model geometry, planes and the origin, and sketch points and +/// circles (a frame the bodies follow, #6257). +const ALIGN_PICKS: Accept = FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN | selection::POINTS | CURVES; const HOLE_TYPES: [&str; 3] = ["simple", "counterbore", "countersink"]; const HOLE_LABELS: [&str; 3] = ["Simple", "Counterbore", "Countersink"]; @@ -107,20 +114,25 @@ crate::dialog_descriptor::dialog_descriptors! { pub enum Kind { Shell("solid.shell", "SHELL", [("Faces/Body", FACES, true)], FeatureKind::Shell { thickness, .. }) { - thickness: String = "2 mm".into() => thickness.to_string(), + thickness: String = "2 mm".into() => shown_expr(thickness, ValueKind::Length), } => json!({"thickness": thickness}); Draft("solid.draft", "DRAFT", [("Faces", FACES, true), ("Neutral plane", PLANES | PLANAR_FACES, false)], FeatureKind::Draft { angle, .. }) { - angle: String = "5 deg".into() => angle.to_string(), + angle: String = "5 deg".into() => shown_expr(angle, ValueKind::Angle), } => json!({"angle": angle}); // A point picked as well puts the plane through it instead of at the distance. OffsetPlane("construct.plane.offset", "OFFSET PLANE", [("Plane", PLANES | PLANAR_FACES, false), ("Through point", selection::VERTICES | selection::POINTS, false)], FeatureKind::ConstructionPlane { plane: PlaneRef::Offset { distance, .. } }) { - offset: String = "0 mm".into() => distance.to_string(), + offset: String = "0 mm".into() => shown_expr(distance, ValueKind::Length), } => json!({"offset": offset}); AnglePlane("construct.plane.at_angle", "PLANE AT ANGLE", [("Plane", PLANES | PLANAR_FACES, false), ("Axis", AXIS_PICKS, false)], FeatureKind::ConstructionPlane { plane: PlaneRef::AtAngle { angle, .. } }) { - angle: String = "45 deg".into() => angle.to_string(), + angle: String = "45 deg".into() => shown_expr(angle, ValueKind::Angle), + } => json!({"angle": angle}); + // With a reference plane, the plane touches where the face turns towards it (#8822). + TangentPlane("construct.plane.tangent", "TANGENT PLANE", [("Face", FACES, false), ("Reference plane", PLANES | PLANAR_FACES, false)], + FeatureKind::ConstructionPlane { plane: PlaneRef::Tangent { angle, .. } }) { + angle: String = "0 deg".into() => angle.as_ref().map_or_else(|| "0 deg".to_string(), ToString::to_string), } => json!({"angle": angle}); Scale("solid.scale", "SCALE", [("Bodies", BODIES, true)], FeatureKind::Scale { factor, .. }) { @@ -128,21 +140,21 @@ crate::dialog_descriptor::dialog_descriptors! { } => json!({"factor": factor}); OffsetFaces("solid.offset_face", "OFFSET FACE", [("Faces", FACES, true)], FeatureKind::OffsetFace { distance, .. }) { - distance: String = "2 mm".into() => distance.to_string(), + distance: String = "2 mm".into() => shown_expr(distance, ValueKind::Length), } => json!({"distance": distance}); Stock("solid.bounding_solid", "STOCK", [("Bodies (all if none)", BODIES, true)], FeatureKind::BoundingSolid { margin, .. }) { - margin: String = "2 mm".into() => margin.to_string(), + margin: String = "2 mm".into() => shown_expr(margin, ValueKind::Length), } => json!({"margin": margin}); Pipe("solid.pipe", "PIPE", [("Path", CURVES, true)], FeatureKind::Pipe { diameter, wall, operation, .. }) { - diameter: String = "5 mm".into() => diameter.to_string(), - wall: String = String::new() => wall.as_deref().map(str::to_string).unwrap_or_default(), + diameter: String = "5 mm".into() => shown_expr(diameter, ValueKind::Length), + wall: String = String::new() => wall.as_deref().map(|e| shown_expr(e, ValueKind::Length)).unwrap_or_default(), operation: usize = 0 => op_index(operation), } => json!({"diameter": diameter, "operation": OPS.get(*operation).copied().unwrap_or("new")}); Emboss("solid.emboss", "EMBOSS", [("Profiles", PROFILES, true), ("Target Face (optional)", FACES, false)], FeatureKind::Emboss { depth, deboss, .. }) { - depth: String = "1 mm".into() => depth.to_string(), + depth: String = "1 mm".into() => shown_expr(depth, ValueKind::Length), deboss: bool = false => *deboss, } => json!({"depth": depth, "mode": if *deboss { "deboss" } else { "emboss" }}); ; custom { @@ -194,6 +206,10 @@ crate::dialog_descriptor::dialog_descriptors! { distance2: String, angle: String, flip: bool, + /// A smooth-patch corner's setback along each edge, as typed; `None` until the + /// user types one: the field then shows the command's own default (1.5 × the + /// radius) as a length that follows the radius, and the command gets none. + setback: Option, }, Mirror, /// Rectangular pattern of bodies: along one direction, optionally a second. @@ -244,12 +260,12 @@ crate::dialog_descriptor::dialog_descriptors! { Thread { designation: String, length: String, - handedness: ThreadHandedness, /// The last automatic size; a different value is a manual override. Keep automatic /// features automatic when applying, even though their resolved size is visible. suggested: Option, /// The picks used for the suggestion, so an unchanged dialog does no geometry work. of: Vec, + options: crate::dialogs_thread::Options, }, /// A rib (one wall along open curves) or a web (a wall per curve). Rib { @@ -274,6 +290,10 @@ crate::dialog_descriptor::dialog_descriptors! { Align { flip: bool, components: bool, + /// Point-to-point: which of the world X, Y and Z axes take the offset. + axes: [bool; 3], + /// A turn about the target's direction after the move (blank: none). + angle: String, }, /// Remove bodies from here on in the timeline. Remove, @@ -302,6 +322,8 @@ crate::dialog_descriptor::dialog_descriptors! { /// The measure chosen in the panel (centre, min or max); `None` follows the result's /// own default (centre where a round item gives one). show: Option, + /// Where the labels in the view were dragged to (#8510). + labels: crate::canvas::MeasureLabels, }, /// Move bodies by a distance along X, Y and Z. /// Move/Copy (see `dialogs_move`): the move type, X/Y/Z distances (Point to Position: the @@ -434,7 +456,15 @@ pub struct HoleOpts { /// Use the full useful cylindrical wall, independently of the drill extents. pub thread_full_depth: bool, pub thread_depth: String, - pub handedness: ThreadHandedness, + /// The tapped thread's hand (right or left). + pub hand: solidcraft_engine::doc::thread_forms::ThreadHand, + /// The tapped thread cut into the wall, not only listed. + pub modeled: bool, + /// A modelled tapped thread's inner end, towards the bottom: square or a fade. + pub ease_out: crate::dialogs_thread::Ease, + /// A tapped hole's drill when it is not the tap maker's for the size (the command's + /// `diameter`); none: the tap maker's. + pub drill: Option, } impl Default for HoleOpts { @@ -450,7 +480,10 @@ impl Default for HoleOpts { refs: Default::default(), thread_full_depth: true, thread_depth: "10 mm".into(), - handedness: ThreadHandedness::Right, + hand: solidcraft_engine::doc::thread_forms::ThreadHand::Right, + modeled: false, + ease_out: crate::dialogs_thread::Ease::default(), + drill: None, } } } @@ -464,6 +497,9 @@ pub struct Dialog { pub error: Option, /// Editing an existing feature (its id, and the timeline marker to restore afterwards). pub editing: Option<(u64, Option)>, + /// Hidden face-profile sources shown only for this editor's lifetime. Visibility itself is + /// unchanged, so OK, Cancel, failed apply and replacing the dialog cannot leak an override. + pub(crate) edit_source_bodies: Vec, /// A user pick or clear makes the profile selector explicit, even if all are reselected. pub profile_selection_changed: bool, /// Give the on-canvas value box the keyboard (and select its text) on the next frame. @@ -491,6 +527,11 @@ pub struct Dialog { pub(crate) chain_applied: bool, /// A pattern's objects of the Object Type not shown now, restored when it is chosen again. pub(crate) other_objects: Vec, + /// The multi-pick input whose picked items are listed under it, each removable (#3683). + pub(crate) listed: Option, + /// The listed item (and its input) whose row is under the pointer: the view lights it as a + /// hover (`viewport::list_hover`). + pub(crate) list_hover: Option<(usize, Sel)>, /// Shell feedback is derived from the picks, never saved as additional face references. shell_chain: std::cell::RefCell>, /// An extrude Press Pull opened with nothing selected: its first pick may be a curved face or @@ -498,6 +539,9 @@ pub struct Dialog { pub press_pull: bool, /// The operation the window chooses by itself (#6901). pub op_auto: crate::op_auto::OpAuto, + /// Where the face that reopened this fillet or chamfer was clicked (Press Pull): its arrow + /// sits on the edge nearest it. UI state only, never saved. + pub(crate) anchor_hint: Option, } #[derive(Clone, Debug)] @@ -535,8 +579,11 @@ impl DialogComputation { session, cmds, marker: d.editing.map(|(_, marker)| marker), + // The editor's pinned original is for a dialog that previews (as `open_feature_edit` + // keeps it); one that no longer does (Modeled unticked) edits the design as it is. editing: d .editing + .filter(|_| d.previews()) .and(app.editing_state.as_ref()) .map(|state| EditingState { source: state.source.scratch(), original: state.original.scratch() }), }) @@ -606,12 +653,13 @@ fn display_quality(app: &SolveApp) -> solidcraft_engine::doc::display_quality::D solidcraft_engine::doc::display_quality::DisplayQuality::parse(&app.preferences.display_quality).unwrap_or_default() } -/// Desktop feature dialogs evaluate the entire command and its dependent suffix once. -/// Results wait until a later frame before adoption, keeping the computing state visible. +/// Desktop feature dialogs evaluate the entire command and its dependent suffix once; so does +/// any feature edit, with a live preview or without. Results wait until a later frame before +/// adoption, keeping the computing state visible. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn begin_applying(app: &SolveApp, d: &Dialog) -> Option { let wait = app.apply_off_thread?; - if !d.previews() { + if !d.previews() && d.editing.is_none() { return None; } let computation = DialogComputation::new(app, d).ok()?; @@ -645,7 +693,7 @@ fn start_applying( if watching.is_cancelled() { return Err("feature computation cancelled".into()); } - prepared.warm_display(quality, || !watching.is_cancelled()); + prepared.warm_display(quality, || !watching.is_cancelled()).map_err(|e| e.to_string())?; if watching.is_cancelled() { return Err("feature computation cancelled".into()); } @@ -736,6 +784,7 @@ impl Dialog { active: 0, error: None, editing: None, + edit_source_bodies: Vec::new(), profile_selection_changed: false, focus: true, value_focus: None, @@ -750,9 +799,12 @@ impl Dialog { picked_edges: Vec::new(), chain_applied, other_objects: Vec::new(), + listed: None, + list_hover: None, shell_chain: Default::default(), press_pull: false, op_auto: Default::default(), + anchor_hint: None, } } @@ -804,14 +856,14 @@ impl Dialog { pub fn for_command(app: &SolveApp, id: &str) -> Option { let s = &app.session; - let has_bodies = !s.world_state().bodies.is_empty(); + let has_bodies = !crate::open_meshing::session_world(s).bodies.is_empty(); let mut d = match id { "sketch.create" => Dialog::new(Kind::Sketch, vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)]), "sketch.intersect" => { let bodies = s.selection.iter().any(|sel| matches!(sel, Sel::Body { .. })); Dialog::new( Kind::SketchIntersect { bodies, projection_link: true }, - vec![SelInput::new("ui.sketch_intersect_geometry", if bodies { BODIES } else { FACES }, true)], + vec![SelInput::new("ui.sketch_intersect_geometry", if bodies { BODIES } else { INTERSECT_GEOMETRY }, true)], ) } "sketch.project" => { @@ -871,12 +923,14 @@ impl Dialog { } "solid.align" => { let components = s.selection.iter().any(|x| matches!(x, Sel::Occurrence { .. })); + // Bodies also take sketch points and circles: a frame the bodies follow (#6257). + let picks = if components { FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN } else { ALIGN_PICKS }; Dialog::new( - Kind::Align { flip: false, components }, + Kind::Align { flip: false, components, axes: [true; 3], angle: String::new() }, vec![ SelInput::new(if components { "Components" } else { "Bodies" }, BODIES, true), - SelInput::new("From", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), - SelInput::new("To", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), + SelInput::new("From", picks, false), + SelInput::new("To", picks, false), ], ) } @@ -908,14 +962,8 @@ impl Dialog { vec![SelInput::new("Body to split", BODIES, false), SelInput::new("Splitting tool", PLANES | FACES | AXES, false)], ), "solid.thread" => Dialog::new( - Kind::Thread { - designation: String::new(), - length: String::new(), - handedness: ThreadHandedness::Right, - suggested: None, - of: Vec::new(), - }, - vec![SelInput::new("Cylindrical face", FACES, false)], + Kind::Thread { designation: String::new(), length: String::new(), suggested: None, of: Vec::new(), options: Default::default() }, + crate::dialogs_thread::inputs(), ), "material.assign" => { Dialog::new(Kind::Material { index: usize::MAX, editor: Default::default() }, vec![SelInput::new("Bodies", BODIES, true)]) @@ -925,7 +973,7 @@ impl Dialog { vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)], ), "inspect.measure" => Dialog::new( - Kind::Measure { result: None, of: Vec::new(), show: None }, + Kind::Measure { result: None, of: Vec::new(), show: None, labels: Default::default() }, vec![SelInput::new( "Items", FACES @@ -935,7 +983,11 @@ impl Dialog { | selection::POINTS | PROFILES | selection::SKETCH_LINES - | selection::EXTERNAL_POINTS, + | selection::EXTERNAL_POINTS + | PLANES + | AXES + | selection::CONSTRUCTION_POINTS + | selection::ORIGIN, true, )], ), @@ -1097,6 +1149,19 @@ impl Dialog { continue; } } + // Move/Copy keeps a selected component as the component, so Create Copy can still be + // ticked after it (the bodies are what a move without a copy moves). + if matches!(d.kind, Kind::Move { .. }) + && let Sel::Occurrence { path } = sel + && !path.is_empty() + && let Some(inp) = d.inputs.first_mut() + && inp.accept == BODIES + { + if !inp.items.contains(sel) { + inp.items.push(sel.clone()); + } + continue; + } let as_body = match sel { Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => Some(Sel::Body { name: body.to_string() }), _ => None, @@ -1164,11 +1229,16 @@ impl Dialog { } } Self::take_component_bodies(app, &mut d); - // A primitive goes where a face or vertex is picked, standing on a planar face. - if let Kind::Primitive { at, .. } = &mut d.kind { + // A primitive goes where a face or vertex is picked, standing on a planar face. The Box, + // Sphere and Torus also go to a sketch point (#9403). + if let Kind::Primitive { cmd, at, .. } = &mut d.kind { + let sketch_points = !crate::primitive_placement::inputs(cmd).is_empty(); *at = s.selection.iter().find_map(|sel| match sel { Sel::Face { body, index, point } => Some((*point, planar_face(s, body, *index).map(|(_, n)| n))), Sel::Vertex { point, .. } => Some((*point, None)), + Sel::ExternalSketchPoint { .. } | Sel::SketchPoint { .. } if sketch_points => { + crate::primitive_placement::world_point(s, sel).map(|p| (p, None)) + } _ => None, }); } @@ -1183,6 +1253,9 @@ impl Dialog { d.sync_thread(s); d.sync_material(s); d.advance(); + // Preselected items are already the dialog's inputs: the control reply and the first + // viewport paint must see the same measurement, without waiting for the panel to draw. + update_measure(app, &mut d); Some(d) } @@ -1195,7 +1268,7 @@ impl Dialog { /// Resolve a newly selected face without replacing an authored size or changing the /// document. Clearing the face also clears a suggestion that no longer applies. fn sync_thread(&mut self, s: &Session) { - let Kind::Thread { designation, suggested, of, .. } = &mut self.kind else { return }; + let Kind::Thread { designation, suggested, of, options, .. } = &mut self.kind else { return }; if !designation.trim().is_empty() && suggested.as_deref() != Some(designation.as_str()) { return; } @@ -1204,12 +1277,7 @@ impl Dialog { return; } *of = picks.to_vec(); - *suggested = picks.first().and_then(|sel| match sel { - Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&s.world_state(), *point).ok().map(|value| { - solidcraft_engine::doc::parse_metric_thread(&value).map(|(d, p)| crate::dialogs_thread::designation(d, p)).unwrap_or(value) - }), - _ => None, - }); + *suggested = crate::dialogs_thread::suggested(s, picks, options); *designation = suggested.clone().unwrap_or_default(); } @@ -1290,6 +1358,7 @@ impl Dialog { | Kind::Loft { .. } | Kind::Sweep { .. } | Kind::AnglePlane { .. } + | Kind::TangentPlane { .. } | Kind::PathPlane { .. } | Kind::Midplane | Kind::Construct { .. } @@ -1406,7 +1475,7 @@ impl Dialog { { return Some(chain.faces.clone()); } - let state = s.world_state(); + let state = crate::open_meshing::session_world(s); let mut by_body = std::collections::BTreeMap::<&str, Vec>::new(); for pick in picks { if let Sel::Face { body, point, .. } = pick { @@ -1453,7 +1522,7 @@ impl Dialog { return None; } let Some(Hit::Face { body, index, .. }) = hits.iter().find(|h| matches!(h, Hit::Face { .. })) else { return None }; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let near: Vec = hits .iter() .filter_map(|h| match h { @@ -1496,7 +1565,7 @@ impl Dialog { && let Hit::SketchPoint { sketch, at, .. } = h { let snap = snap?; - return snap.place_at(s.world_state().sketch(*sketch)?.plane.to_world(*at)); + return snap.place_at(crate::open_meshing::session_world(s).sketch(*sketch)?.plane.to_world(*at)); } if let Some(sel) = self.circle_centre_pick(s, inp, h, snap) { return Some(sel); @@ -1537,7 +1606,7 @@ impl Dialog { fn extrude_target(&self, s: &Session, h: &Hit) -> Option { let Kind::Extrude { thin: false, smart, .. } = &self.kind else { return None }; let to_active = self.active_input().is_some_and(|i| i.label == TO_OBJECT); - if !to_active && (self.active != 0 || !smart.auto_to_object) { + if !to_active && (self.active != 0 || !smart.auto_to_object || smart.profiles_chosen) { return None; } let reference = profile_plane(s, self.inputs.first()?.items.first()?)?; @@ -1562,7 +1631,10 @@ impl Dialog { /// To Object with it. False when the pick is not one. fn take_extrude_target(&mut self, s: &Session, sel: &Sel) -> bool { if self.active != 0 - || !matches!(self.kind, Kind::Extrude { thin: false, smart: crate::smart_extrude::Smart { auto_to_object: true, .. }, .. }) + || !matches!( + self.kind, + Kind::Extrude { thin: false, smart: crate::smart_extrude::Smart { auto_to_object: true, profiles_chosen: false, .. }, .. } + ) { return false; } @@ -1586,12 +1658,65 @@ impl Dialog { true } + /// Give the keyboard to the form's value field `id`, its text selected, once the pointer is + /// idle: where a pick gives it when values have no boxes in the view (#9479). + pub(crate) fn give_keyboard(&mut self, id: egui::Id) { + self.value_focus = Some(id); + self.restore_value_focus = true; + } + + /// A sketch clicked in the Browser or the History while Extrude, Revolve or Emboss is open + /// (#6106): Profiles takes every profile of the sketch, as when the sketch is selected before + /// the command starts. The island inside another profile's hole is left out, or it would fill + /// the hole. False when the click is not one of those (the caller selects it as usual). + pub fn pick_sketch(&mut self, s: &Session, id: u64) -> bool { + if self.refuse_sketch(s, id) { + return true; + } + if self.active != 0 + || !matches!(self.kind, Kind::Extrude { .. } | Kind::Revolve { .. } | Kind::Emboss { .. }) + || !self.inputs.first().is_some_and(|i| i.accept & PROFILES != 0) + || !s.doc.feature(id).is_some_and(|f| matches!(f.kind, FeatureKind::Sketch { .. })) + { + return false; + } + let profiles: Vec = crate::open_meshing::session_world(s) + .sketch(id) + .map(|ss| outermost_profiles(&ss.profiles).map(|index| Sel::Profile { sketch: id, index }).collect()) + .unwrap_or_default(); + let Some(input) = self.inputs.first_mut() else { return false }; + if profiles.is_empty() { + return false; + } + input.items = profiles; + self.profile_selection_changed = true; + self.focus = true; + self.error = None; + self.sync_thread(s); + true + } + + /// A sketch clicked (in the view, the Browser or the History) while a pattern or Mirror waits + /// for its bodies or features: a sketch is neither, so the dialog says what to do instead of + /// taking nothing in silence (#10057). False when the click is not one of those. + pub fn refuse_sketch(&mut self, s: &Session, id: u64) -> bool { + if self.active != 0 + || !is_pattern(&self.kind) + || !self.inputs.first().is_some_and(|i| i.accept == BODIES || i.accept == selection::FEATURES) + || !s.doc.feature(id).is_some_and(|f| matches!(f.kind, FeatureKind::Sketch { .. })) + { + return false; + } + self.error = Some(SKETCH_NOT_OBJECT.to_string()); + true + } + /// A pick in the viewport (already accepted by the active input). pub fn pick(&mut self, s: &Session, sel: Sel) { if self.take_extrude_target(s, &sel) { return; } - if let Some(key) = feature_pattern_reference_key(self, self.active) { + if let Some(key) = stored_input_reference_key(self, self.active) { self.extra.remove(key); } if let Kind::PathPlane { sketch, .. } = &mut self.kind { @@ -1602,8 +1727,9 @@ impl Dialog { self.profile_selection_changed = true; } let measure = matches!(self.kind, Kind::Measure { .. }); - // The chat's picks stay what was clicked: a rim is one edge there, not its pieces. - let one = measure || matches!(self.kind, Kind::ChatContext); + // The chat's picks stay what was clicked: a rim is one edge there, not its pieces. So do + // print faces: a click on one takes it out, not the other pieces of its surface in. + let one = measure || matches!(self.kind, Kind::ChatContext | Kind::SaveMesh(_)); let sel = if measure { crate::viewport::measurement_selection(s, &sel) } else { sel }; let chain = matches!(self.kind, Kind::Fillet { chain: true, .. }); let single = @@ -1664,6 +1790,9 @@ impl Dialog { /// Box selection result: replace (or add to) the active input. pub fn take_box(&mut self, s: &Session, sels: Vec, add: bool) { + if let Some(key) = stored_input_reference_key(self, self.active) { + self.extra.remove(key); + } if let Kind::PathPlane { sketch, .. } = &mut self.kind { *sketch = None; self.extra.remove("path"); @@ -1742,6 +1871,80 @@ impl Dialog { inp.items = items; self.error = None; } + + /// What input `i`'s list of picked items shows, one row each (#3683): what its chip counts. + /// A rim or a surface split into pieces is one row, as it is one pick; a Shell with Tangent + /// Chain lists every face it opens. + pub(crate) fn listed_items(&self, s: &Session, i: usize) -> Vec { + if i == 0 + && let Some(faces) = self.shell_faces(s) + { + return faces; + } + let mut rows: Vec = Vec::new(); + let mut shown: Vec = Vec::new(); + for item in self.inputs.get(i).map(|inp| inp.items.as_slice()).unwrap_or_default() { + if shown.iter().any(|x| selection::same_item(x, item)) { + continue; + } + shown.extend(crate::viewport::grouped_selection(s, item)); + rows.push(item.clone()); + } + rows + } + + /// Remove a listed row's item from input `i`, as picking it again toggles it off: the + /// pieces of its rim or surface go with it, and the hand-picked edges and the explicit + /// profile choice follow. A face a Shell's tangent chain opens goes with the picks whose + /// chain holds it. + pub(crate) fn remove_listed(&mut self, s: &Session, i: usize, item: &Sel) { + let shell_chain = i == 0 && self.shell_faces(s).is_some(); + // A Fillet or Chamfer row its Tangent Chain brought goes with the picks whose chain holds + // it, as picking it again would; else ticking Tangent Chain again brings it back. + let fillet_chain = i == 0 && matches!(self.kind, Kind::Fillet { chain: true, .. }) && self.chain_applied; + let state = s.world_state().ok(); + let mut gone = if shell_chain { Vec::new() } else { crate::viewport::grouped_selection(s, item) }; + gone.push(item.clone()); + if fillet_chain { + let seeds: Vec = self + .picked_edges + .iter() + .filter(|seed| fillet_edges(s, seed, true).iter().any(|x| gone.iter().any(|g| selection::same_item(x, g)))) + .cloned() + .collect(); + for seed in &seeds { + gone.extend(fillet_edges(s, seed, true)); + } + gone.extend(seeds); + } + let Some(inp) = self.inputs.get_mut(i) else { return }; + match (shell_chain, item, state.as_ref()) { + (true, Sel::Face { body, index, .. }, Some(st)) => { + let model = st.body(body); + inp.items.retain(|pick| { + let Sel::Face { body: b, point, .. } = pick else { return true }; + b != body || !model.is_some_and(|m| solidcraft_engine::doc::tangent_face_chain(m, &[*point]).iter().any(|(f, _)| f == index)) + }); + } + // Without the model to find the chain in, the row goes on its own. + _ => { + inp.items.retain(|x| !gone.iter().any(|g| selection::same_item(x, g))); + if i == 0 { + self.picked_edges.retain(|x| !gone.iter().any(|g| selection::same_item(x, g))); + } + } + } + let empty = inp.items.is_empty(); + if empty && self.listed == Some(i) { + self.listed = None; + } + if i == 0 && matches!(self.kind, Kind::Extrude { .. } | Kind::Revolve { .. } | Kind::Emboss { .. }) { + self.profile_selection_changed = true; + } + self.list_hover = None; + self.error = None; + self.sync_thread(s); + } } /// The edges a Fillet or Chamfer pick stands for: its tangent chain when `chain` is on, else @@ -1750,7 +1953,7 @@ fn fillet_edges(s: &Session, sel: &Sel, chain: bool) -> Vec { let mut picked = crate::viewport::picked_selection(s, sel); if chain && let Sel::Edge { body, index, .. } = sel - && let Some(b) = s.world_state().body(body) + && let Some(b) = crate::open_meshing::session_world(s).body(body) { let m = b.mesh(); for i in m.tangent_chain(*index, 2f64.to_radians()) { @@ -1764,6 +1967,113 @@ fn fillet_edges(s: &Session, sel: &Sel, chain: bool) -> Vec { picked } +/// How close two edge ends are to be one vertex (mm). +const VERTEX_TOLERANCE: f64 = 1e-6; + +/// The B-rep edges a Fillet dialog rounds, by body and index: the picked edges, and each edge of a +/// picked face but its seams. +fn fillet_edge_ids(s: &Session, items: &[Sel]) -> Vec<(String, usize)> { + let st = crate::open_meshing::session_world(s); + let mut ids: Vec<(String, usize)> = Vec::new(); + for x in items { + match x { + Sel::Edge { body, index, .. } => ids.push((body.clone(), *index)), + Sel::Face { body, index, .. } => { + if let Some(b) = st.body(body) { + let m = b.mesh(); + for e in m.face_edges(u32::try_from(*index).unwrap_or(u32::MAX)) { + if !m.seams.get(e).copied().unwrap_or(false) { + ids.push((body.clone(), e)); + } + } + } + } + _ => {} + } + } + ids.sort(); + ids.dedup(); + ids +} + +/// The corners of a Fillet dialog's edges where a smooth patch goes (`corner: g2`): each vertex +/// where three or more of the edges meet and every other edge there is rounded too, once. +pub(crate) fn fillet_corners(s: &Session, items: &[Sel]) -> Vec { + let st = crate::open_meshing::session_world(s); + let ids = fillet_edge_ids(s, items); + let mut corners: Vec = Vec::new(); + let mut bodies: Vec<&str> = ids.iter().map(|(b, _)| b.as_str()).collect(); + bodies.dedup(); + for body in bodies { + let Some(b) = st.body(body) else { continue }; + let m = b.mesh(); + let picked: Vec = ids.iter().filter(|(x, _)| x == body).map(|(_, e)| *e).collect(); + // An open edge's two ends (a closed one has no vertex to share). + let ends = |e: usize| m.edges.get(e).and_then(|p| Some((*p.first()?, *p.last()?))).filter(|(a, b)| a.dist(*b) > VERTEX_TOLERANCE); + let mut meeting: Vec<(Vec3, usize)> = Vec::new(); + for (a, b) in picked.iter().filter_map(|e| ends(*e)) { + for v in [a, b] { + match meeting.iter_mut().find(|(c, _)| c.dist(v) < VERTEX_TOLERANCE) { + Some((_, n)) => *n += 1, + None => meeting.push((v, 1)), + } + } + } + for (v, n) in meeting { + let at = |e: &usize| ends(*e).is_some_and(|(a, b)| a.dist(v) < VERTEX_TOLERANCE || b.dist(v) < VERTEX_TOLERANCE); + let real = |e: &usize| !m.seams.get(*e).copied().unwrap_or(false); + if n >= 3 + && (0..m.edges.len()).filter(real).filter(at).all(|e| picked.contains(&e)) + && !corners.iter().any(|c| c.dist(v) < VERTEX_TOLERANCE) + { + corners.push(v); + } + } + } + corners +} + +/// The least setback the smooth-patch `corners` of a Fillet dialog's edges take with rounds of +/// `radius`: the largest the kernel names at any of them ([`kernel::fillet_least_setback`]; a +/// setback must be more than this). `None` where the kernel names none (a corner whose least +/// SMLib decides). Kept per design revision, radius and corners: the kernel reads the bodies' +/// faces, and the form asks every frame. +pub(crate) fn fillet_least_setback(ctx: &egui::Context, s: &Session, items: &[Sel], corners: &[Vec3], radius: f64) -> Option { + let mut bodies: Vec = fillet_edge_ids(s, items).into_iter().map(|(b, _)| b).collect(); + bodies.dedup(); + let mut key = std::collections::hash_map::DefaultHasher::new(); + (&s.document_id, s.revision, radius.to_bits(), &bodies).hash(&mut key); + corners.iter().for_each(|c| [c.x, c.y, c.z].map(f64::to_bits).hash(&mut key)); + let key = key.finish(); + let id = egui::Id::new("fillet_least_setback"); + if let Some((k, least)) = ctx.data(|d| d.get_temp::<(u64, Option)>(id)) + && k == key + { + return least; + } + let st = crate::open_meshing::session_world(s); + let least = bodies + .iter() + .filter_map(|b| st.body(b)) + .flat_map(|b| corners.iter().filter_map(|c| solidcraft_engine::doc::kernel::fillet_least_setback(&b.body, *c, radius).ok().flatten())) + .reduce(f64::max); + ctx.data_mut(|d| d.insert_temp(id, (key, least))); + least +} + +/// The profiles of a sketch that aren't the island inside another profile's hole: a circle in a +/// rectangle gives the rectangle-with-hole and the disc, and taking both would fill the hole. +/// Loops are compared as sets of curve ids, so where a loop starts or which way it runs doesn't matter. +fn outermost_profiles(profiles: &[solidcraft_engine::sketch::Profile]) -> impl Iterator + '_ { + let key = |ids: &[String]| { + let mut v = ids.to_vec(); + v.sort(); + v + }; + let holes: Vec> = profiles.iter().flat_map(|p| p.hole_curves.iter().map(|h| key(h))).collect(); + (0..profiles.len()).filter(move |&i| profiles.get(i).is_some_and(|p| !holes.contains(&key(&p.outer_curves)))) +} + /// Profiles of the sketch a feature would use, when there is just one: the active sketch's, else /// the last sketch's while no feature builds from it yet. A used profile (a cube's sketch on its /// bottom face) is only taken when it is picked. @@ -1775,7 +2085,7 @@ fn default_profiles(s: &Session) -> Vec { } fn single_profile(s: &Session, sketch: u64) -> Vec { - match s.world_state().sketch(sketch).map(|ss| ss.profiles.len()) { + match crate::open_meshing::session_world(s).sketch(sketch).map(|ss| ss.profiles.len()) { Some(1) => vec![Sel::Profile { sketch, index: 0 }], _ => Vec::new(), } @@ -1788,7 +2098,7 @@ fn single_hole_point(app: &SolveApp, d: &Dialog, x: &Sel) -> Option<(u64, String if let Some(k) = d.extra.get("single_point").filter(|k| k["point"] == pt3(*point)) { return Some((k["sketch"].as_u64()?, k["id"].as_str()?.to_string())); } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); crate::viewport::visible_sketches(app).into_iter().find_map(|sid| { let ss = st.sketch(sid)?; let shown = SnapPoints::of(&ss.sketch); @@ -1892,7 +2202,7 @@ impl FaceSnap { /// Face `face` of `body`, for sketch points at `near` (in the world). fn new(s: &Session, body: &str, face: usize, near: &[Vec3]) -> FaceSnap { let mut snap = FaceSnap { body: body.to_string(), face, plane: None, tris: Vec::new(), budget: std::cell::Cell::new(snap_budget()) }; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let (Some((origin, normal)), Some(b)) = (planar_face(s, body, face), st.body(body)) else { return snap }; let m = b.mesh(); #[cfg(test)] @@ -1985,7 +2295,7 @@ mod face_snap_tests { let mut s = Session::default(); s.execute("solid.box", &json!({"length":40,"width":30,"height":20})).unwrap(); let top = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); let b = st.bodies.first().unwrap(); let faces = b.body.faces(1e-3).unwrap(); let f = faces.iter().max_by(|a, b| a.centroid.z.total_cmp(&b.centroid.z)).unwrap(); @@ -2067,7 +2377,7 @@ fn sketch_curve_edge(s: &Session, sel: &Sel) -> Option { Sel::ExternalSketchCurve { sketch, id } => (*sketch, id), _ => return None, }; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let ss = st.sketch(sketch)?; let segs = ss.sketch.segs(ss.sketch.curve_index(id)?); let (a, b) = (ss.plane.to_world(segs.first()?.start()), ss.plane.to_world(segs.last()?.end())); @@ -2107,7 +2417,7 @@ fn sketch_curve_edge(s: &Session, sel: &Sel) -> Option { } pub fn planar_face(s: &Session, body: &str, face: usize) -> Option<(Vec3, Vec3)> { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let known = FACE_PLANES.with(|c| { let c = c.borrow(); c.0.as_ref().filter(|k| std::sync::Arc::ptr_eq(k, &st)).and_then(|_| c.1.iter().find(|(b, f, _)| b == body && *f == face).map(|x| x.2)) @@ -2138,7 +2448,7 @@ pub fn planar_face(s: &Session, body: &str, face: usize) -> Option<(Vec3, Vec3)> /// The fillet or chamfer feature whose blend a body face is (a piece or copy of one too). pub fn blend_feature(s: &Session, body: &str, face: usize) -> Option { use solidcraft_engine::doc::persistent_name; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let b = st.body(body)?; let names = solidcraft_engine::doc::naming::face_names(b); let name = names.get(face).filter(|n| persistent_name::is_blend(n))?; @@ -2354,6 +2664,11 @@ fn objects_label(accept: Accept) -> &'static str { if accept == selection::FEATURES { "Features" } else { "Objects" } } +/// What a pattern or Mirror says when a sketch is clicked for its objects (#10057). It names what +/// to pick, so it shows as a hint rather than an error ([`missing_pick`]). +const SKETCH_NOT_OBJECT: &str = + "Pick bodies or features: a sketch is neither. Repeat its curves with the sketch's own Pattern or Mirror, or extrude it first."; + fn is_pattern(k: &Kind) -> bool { matches!(k, Kind::PatternRect { .. } | Kind::PatternCirc { .. } | Kind::PathPattern { .. } | Kind::Mirror) } @@ -2364,7 +2679,8 @@ fn object_type_row(d: &mut Dialog, ui: &mut egui::Ui) { let Some(inp) = d.inputs.first_mut() else { return }; let cur = usize::from(inp.accept == selection::FEATURES); let mut ty = cur; - choice_row(ui, "Object Type", "pat_obj", &mut ty, &["Bodies", "Features"]); + // What the two kinds are, and that a sketch is neither (#10057). + choice_row(ui, "Object Type", "pat_obj", &mut ty, &["Bodies", "Features"]).backing_on_hover_text(crate::i18n::tr("ui.pattern_object_type_tip")); if ty != cur { inp.accept = if ty == 1 { selection::FEATURES } else { BODIES }; inp.label = objects_label(inp.accept); @@ -2473,7 +2789,7 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui, app: &SolveApp) { /// active a part inside a subassembly picks the subassembly; with the subassembly (or the part) /// active it picks the part. A body outside the active component picks its top-level placement. pub(crate) fn occurrence_path_of_body(s: &Session, body: &str) -> Option> { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let b = st.body(body)?; if s.doc.model_body_component(b) == 0 { return None; @@ -2532,9 +2848,25 @@ fn occurrence_paths(s: &Session, items: &[Sel]) -> Vec> { /// the name the preferences give it. pub(crate) fn selection_label(s: &Session, names: crate::prefs::OriginPlaneNames, d: &Dialog, inp: &SelInput, item: &Sel) -> String { let axis = inp.accept == selection::AXIS_PICKS && round_axis(s, item).is_some(); + let sketch_name = + |id| s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_else(|| crate::i18n::format("browser.sketch_name", &[("number", &id.to_string())])); match item { Sel::SketchCurve { id, .. } => id.clone(), Sel::SketchPoint { id } => crate::sketch_modify_ui::point_id(s, item).unwrap_or(id).to_string(), + Sel::SketchMidpoint { id } => crate::i18n::format("dialog.selection_midpoint", &[("id", id)]), + Sel::ExternalSketchCurve { sketch, id } => { + crate::i18n::format("dialog.selection_external_curve", &[("sketch", &sketch_name(*sketch)), ("id", id)]) + } + // Another sketch's point (a Sphere's centre, #9403), named as Select Other names it. + Sel::ExternalSketchPoint { sketch, id } => { + let state = crate::open_meshing::session_world(s); + let point = state.sketch(*sketch).map_or_else(|| id.clone(), |ss| crate::select_other::point_label(&ss.sketch, id)); + crate::i18n::format("dialog.selection_external_point", &[("point", &point), ("sketch", &sketch_name(*sketch))]) + } + Sel::SketchConstraint { id } => crate::i18n::format("dialog.selection_constraint", &[("id", id)]), + Sel::Profile { sketch, index } => { + crate::i18n::format("dialog.selection_profile", &[("sketch", &sketch_name(*sketch)), ("number", &index.saturating_add(1).to_string())]) + } Sel::Plane { name } => names.label(name).to_string(), Sel::Axis { name } | Sel::ConstructionPoint { name } | Sel::Body { name } => name.clone(), Sel::Face { body, index, .. } if axis => format!("{body} · face {index} axis"), @@ -2547,14 +2879,15 @@ pub(crate) fn selection_label(s: &Session, names: crate::prefs::OriginPlaneNames // A point of the model: a vertex, or the centre a round edge stands for. Sel::Vertex { body, .. } if !body.is_empty() => format!("{body} · point"), Sel::Feature { id } => s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_else(|| format!("Feature {id}")), + Sel::Drawing { object, .. } => format!("Drawing object {object}"), + Sel::Occurrence { path } if path.is_empty() => s.doc.name.clone(), Sel::Occurrence { path } => s.occurrence_placement(path).map(|p| p.name).unwrap_or_else(|_| "Component".into()), Sel::Vertex { body, point } if body.is_empty() => { - let state = s.world_state(); + let state = crate::open_meshing::session_world(s); let p = s.active_sketch.and_then(|id| state.sketch(id)).map(|sk| sk.plane.to_local(*point)).unwrap_or_default(); format!("({:.2}, {:.2}) mm", p.x, p.y) } Sel::Vertex { body, .. } => format!("{body} · vertex"), - _ => format!("{item:?}"), } } @@ -2565,7 +2898,13 @@ fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: crate::pref } /// Saved vectors/axes are real inputs even when they have no origin-axis selection chip. -fn feature_pattern_reference_key(d: &Dialog, index: usize) -> Option<&'static str> { +fn stored_input_reference_key(d: &Dialog, index: usize) -> Option<&'static str> { + if let Kind::Construct { command: "construct.plane.axis_point", keys, .. } = &d.kind { + return keys.get(index).copied(); + } + if matches!(d.kind, Kind::Section { .. }) && index == 0 { + return Some("plane"); + } if !d.inputs.first().is_some_and(|i| i.accept == selection::FEATURES) { return None; } @@ -2584,6 +2923,14 @@ fn stored_revolve_axis(kind: &Kind) -> Option<&Value> { } } +/// Give the keyboard back from whatever text editor holds it, so the pick field clicked into +/// becomes the one field that looks active (#10066). +fn surrender_keyboard_focus(ui: &egui::Ui) { + if let Some(id) = ui.ctx().memory(|memory| memory.focused()) { + ui.ctx().memory_mut(|memory| memory.surrender_focus(id)); + } +} + pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: crate::prefs::OriginPlaneNames, range: std::ops::Range) { // Edit Text shows its Path input among its own rows. if matches!(d.kind, Kind::Text(_)) { @@ -2593,17 +2940,24 @@ pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, n let mut clear: Option = None; let mut activate: Option = None; let mut remove = None; + // Only one field may look active at a time (#10066): while a text editor holds the keyboard, + // no pick field draws its accent ring, and clicking a pick field takes the keyboard back. + let text_focus = crate::ui_kit::editor_has_focus(ui.ctx()); + let mut toggle_list: Option = None; + let mut hovered: Option<(usize, Sel)> = None; let shell_count = d.shell_faces(s).map(|faces| faces.len()); for (i, inp) in d.inputs.iter().enumerate().skip(range.start).take(range.end.saturating_sub(range.start)) { - let stored_reference = feature_pattern_reference_key(d, i).and_then(|key| d.extra.get(key)).filter(|_| inp.items.is_empty()); + let stored_reference = stored_input_reference_key(d, i).and_then(|key| d.extra.get(key)).filter(|_| inp.items.is_empty()); form_row(ui, inp.label, |ui| { ui.horizontal(|ui| { - let active = i == d.active; + let active = i == d.active && !text_focus; // A chip: "↖ Select" (outlined) while empty, "N selected" (filled) once picked. let custom_axis = i == 1 && inp.items.is_empty() && stored_revolve_axis(&d.kind).is_some(); let filled = !inp.items.is_empty() || custom_axis || stored_reference.is_some(); let text = if filled { - RichText::new(if custom_axis || stored_reference.is_some() { + RichText::new(if stored_reference.is_some() && matches!(d.kind, Kind::Section { .. }) { + crate::i18n::tr("ui.viewport_status_section_plane").into() + } else if custom_axis || stored_reference.is_some() { crate::i18n::tr("dialog.custom_axis").into() } else if !inp.multi { inp.items.first().map(|item| selection_label(s, names, d, inp, item)).unwrap_or_default() @@ -2645,8 +2999,9 @@ pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, n } else { format!("{} (click to pick into this input)", hint(inp)) }; - if chip.on_hover_text(tooltip).clicked() { + if chip.backing_on_hover_text(tooltip).clicked() { activate = Some(i); + surrender_keyboard_focus(ui); } if !inp.items.is_empty() || stored_reference.is_some() { let rect = egui::Rect::from_center_size( @@ -2657,31 +3012,69 @@ pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, n crate::scenario::publish_handle(&format!("dialog:clear:{}", inp.label), button.rect.center()); if button.clicked() { clear = Some(i); + surrender_keyboard_focus(ui); + } + // Several picks: an arrow beside the clear button lists them, each with its + // own remove button (#3683). Drawn straight into the row, which is this field's + // own: a scope around it would take room and widen the dialog. + if inp.multi { + let open = d.listed == Some(i); + let at = rect.translate(vec2(-t.space_24, 0.0)); + let label = crate::i18n::tr_label(if open { "Hide the picked items" } else { "Show the picked items" }); + let arrow = crate::ui_kit::disclosure_button_at(ui, at, open, label); + crate::scenario::publish_handle(&format!("dialog:list_toggle:{}", inp.label), arrow.rect.center()); + if arrow.clicked() { + toggle_list = Some(i); + } } } }); }); - if matches!(d.kind, Kind::SketchModify(_)) && inp.multi { - for (index, item) in inp.items.iter().enumerate() { - if crate::ui_kit::list_row(ui, &format!("{}:{index}", inp.label), &selection_label(s, names, d, inp, item)).clicked() { - remove = Some((i, index)); + if inp.multi && d.listed == Some(i) && !inp.items.is_empty() { + let rows = d.listed_items(s, i); + egui::ScrollArea::vertical().id_salt(("picked_items", i)).max_height(t.control_height * 6.5).show(ui, |ui| { + for (index, item) in rows.into_iter().enumerate() { + let row = crate::ui_kit::list_row(ui, &format!("{}:{index}", inp.label), &selection_label(s, names, d, inp, &item)); + if row.hovered() { + hovered = Some((i, item.clone())); + } + if row.clicked() { + remove = Some((i, item)); + } } - } + }); } } - if let Some((input, index)) = remove - && let Some(input) = d.inputs.get_mut(input) - && index < input.items.len() - { - input.items.remove(index); + // The row under the pointer lights its item in the view; rows of inputs drawn elsewhere + // keep theirs. + let ours = |h: &Option<(usize, Sel)>| h.as_ref().is_some_and(|(i, _)| range.contains(i)); + if hovered.is_some() || ours(&d.list_hover) { + if d.list_hover != hovered { + ui.ctx().request_repaint(); + } + d.list_hover = hovered; + } + if let Some(i) = toggle_list { + d.listed = if d.listed == Some(i) { None } else { Some(i) }; + } + if let Some((input, item)) = remove { + d.remove_listed(s, input, &item); } if let Some(i) = activate { d.active = i; + // A click into the Profiles box is a choice to add profiles by pick (Extrude's automatic To Object). + if let Kind::Extrude { smart, .. } = &mut d.kind { + smart.profiles_chosen = i == 0; + } } if let Some(i) = clear { - if let Some(key) = feature_pattern_reference_key(d, i) { + if let Some(key) = stored_input_reference_key(d, i) { d.extra.remove(key); } + if d.listed == Some(i) { + d.listed = None; + d.list_hover = None; + } let Some(inp) = d.inputs.get_mut(i) else { return }; inp.items.clear(); if i == 0 { @@ -2730,6 +3123,16 @@ fn missing_pick(error: &str) -> bool { awaiting_selection(error) || error.get(..5).is_some_and(|start| start.eq_ignore_ascii_case("pick ")) } +/// A refusal that says the command is not available in this context ("`sketch.project` is not +/// available right now: no sketch is being edited"): the engine's own `Disabled` refusal for the +/// command this dialog runs, so the sketch ended or the mode changed under it. Guidance, not a +/// failure of the design: there is nothing to report (#10181). +fn context_refusal(app: &SolveApp, d: &Dialog, error: &str) -> bool { + let Some(id) = d.command() else { return false }; + let Some(spec) = solidcraft_engine::find_command(id) else { return false }; + spec.disabled_refusal(&app.session).is_some_and(|refusal| refusal == error) +} + fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut egui::Ui) { if matches!(d.kind, Kind::SketchModify(_)) && d.previews() @@ -2737,11 +3140,6 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut { d.refuse(app, error); } - // For Corner dialogs (fillet/chamfer), propagate preview errors to `d.error` - // so impossible sizes still show a refusal message and tests can check it. - if matches!(d.kind, Kind::SketchModify(crate::sketch_modify_ui::Mod::Corner { .. })) && app.preview.error.is_some() && d.error.is_none() { - d.error = app.preview.error.clone(); - } let shown_id = egui::Id::new("sc_dialog_refusal_shown"); if d.error.is_none() && app.preview.error.is_none() { ui.data_mut(|m| m.remove::(shown_id)); @@ -2754,16 +3152,78 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut } // Other dialogs say so on OK ("select a plane first", "pick an axis"): that is what is // left to pick, not a failure, so it is shown plainly, with no Create Issue (#3292, #3773). + // An operation on a part the kernel refuses: the part, what is wrong with it, and what + // to do, instead of the kernel's words and an issue report. + if !missing_pick(&error) + && let Some(part) = refused_operand(app, d) + { + if let Some(face) = part.face { + crate::refused_part::ring(app, &part.body, face); + } + let operation = + dialog_commands(app, d).ok().and_then(|c| c.iter().find_map(|(_, p)| p.get("operation").and_then(Value::as_str).map(str::to_string))); + ui.vertical(|ui| { + crate::ui_kit::text(ui, &crate::refused_part::message(&part, operation.as_deref()), crate::ui_kit::Text::Report("error", true)); + ui.horizontal(|ui| { + let ready = solidcraft_engine::find_command(crate::refused_part::REPAIR).map(|c| c.info(&app.session)); + let enabled = ready.as_ref().is_some_and(|i| i.enabled); + let repair = crate::ui_kit::button(ui, crate::i18n::tr("refused.repair"), crate::ui_kit::Button::Enabled(enabled)); + crate::scenario::publish_handle("dialog:repair_part", repair.rect.center()); + if repair.clicked() { + crate::refused_part::repair(app, &part.body); + } + if part.face.is_some() { + let show = crate::ui_kit::button(ui, crate::i18n::tr("refused.show_face"), crate::ui_kit::Button::Normal); + crate::scenario::publish_handle("dialog:show_face", show.rect.center()); + if show.clicked() { + crate::refused_part::show_face(app, &part); + } + } + }); + }); + return; + } + // A command that is not available in this context ("`sketch.project` is not available + // right now: no sketch is being edited") is guidance too: the context went away, not the + // design, so there is nothing to report (#10181). let rect = if missing_pick(&error) { crate::ui_kit::text(ui, &shown_error(&error), crate::ui_kit::Text::Hint("missing_pick")).rect + } else if context_refusal(app, d, &error) { + crate::ui_kit::text(ui, &shown_error(&error), crate::ui_kit::Text::Hint("context")).rect } else { + // A fillet's refusal reads in plain words, or not at all where its Setback field already + // says what is wrong; the kernel's own text stays in the hover text, Copy Details and the + // issue report. + let setback_in_field = d.extra.get("setbacks").is_none(); + let plain = if matches!(d.kind, Kind::Fillet { chamfer: false, .. }) { fillet_plain_error(&error, setback_in_field) } else { None }; ui.vertical(|ui| { - crate::ui_kit::text(ui, &shown_error(&error), crate::ui_kit::Text::Report("error", true)); - let response = crate::ui_kit::button(ui, "Create Issue…", crate::ui_kit::Button::Normal); - crate::scenario::publish_handle("dialog:create_issue", response.rect.center()); - if response.clicked() { - crate::issue_report::begin(app, ctx, Some(d), Some(&error)); + match &plain { + Some(FilletRefusal::Plain(plain)) => { + crate::ui_kit::text(ui, plain, crate::ui_kit::Text::Report("error", true)).backing_on_hover_text(shown_error(&error)); + } + Some(FilletRefusal::InField) => {} + None => { + crate::ui_kit::text(ui, &shown_error(&error), crate::ui_kit::Text::Report("error", true)); + } } + ui.horizontal(|ui| { + if plain.is_some() { + let copy = crate::ui_kit::button(ui, tr("ui.copy_details"), crate::ui_kit::Button::Normal); + crate::scenario::publish_handle("dialog:copy_details", copy.rect.center()); + if copy.backing_on_hover_text(tr("ui.copy_details_tip")).clicked() { + ui.ctx().copy_text(error.clone()); + } + } + // A value the field flags is the user's to change, not a failure to report. + if matches!(plain, Some(FilletRefusal::InField)) { + return; + } + let response = crate::ui_kit::button(ui, "Create Issue…", crate::ui_kit::Button::Normal); + crate::scenario::publish_handle("dialog:create_issue", response.rect.center()); + if response.clicked() { + crate::issue_report::begin(app, ctx, Some(d), Some(&error)); + } + }); }) .response .rect @@ -2780,6 +3240,56 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut } } +/// How the Fillet dialog shows a kernel refusal ([`fillet_plain_error`]). +#[derive(Debug, PartialEq)] +pub(crate) enum FilletRefusal { + /// In these plain words. + Plain(String), + /// Not again: the Setback field already flags the value and names the least it takes. + InField, +} + +/// A fillet's refusal by the kernel in plain words, for the dialog: what happened and what may +/// help, without SMLib's status codes, its check's test list or the command's parameter names; +/// a setback short of the least is left to the Setback field (`setback_in_field`: the setback +/// came from it, so it is flagged there). `None` for a refusal that is no kernel failure (an +/// expression, a pick), shown as it is. +pub(crate) fn fillet_plain_error(error: &str, setback_in_field: bool) -> Option { + // The kernel's refusals as the timeline records them (`KernelError`, `blend_smlib`). + if setback_in_field && error.contains("the setback must be more than") { + return Some(FilletRefusal::InField); + } + // A setback too short for its corner's patch: the least that builds, as the kernel names it + if let Some((_, rest)) = error.split_once(solidcraft_engine::kernel::SETBACK_AT_LEAST) + && let Some(least) = rest.split_once(" mm").map(|(n, _)| n.trim()).filter(|n| n.parse::().is_ok()) + { + return Some(FilletRefusal::Plain(crate::i18n::format("ui.fillet_error_setback_short", &[("least", &format!("{least} mm"))]))); + } + let too_large = error.contains("larger than the faces beside its edges allow"); + let corner = error.contains("setback") || error.contains("G2 corner") || error.contains("corner patch"); + let kernel = error.contains("SMLib") + || error.contains("the operation failed") + || error.contains("not supported yet") + || error.contains("kernel internal error") + || error.contains("the rounds would leave openings"); + if too_large { + Some(FilletRefusal::Plain(tr("ui.fillet_error_too_large").to_string())) + } else if corner && kernel { + Some(FilletRefusal::Plain(tr("ui.fillet_error_corner").to_string())) + } else if kernel { + Some(FilletRefusal::Plain(tr("ui.fillet_error_failed").to_string())) + } else { + None + } +} + +/// The part a failed dialog's operation uses that the kernel refused, if one did. +fn refused_operand(app: &SolveApp, d: &Dialog) -> Option { + let commands = dialog_commands(app, d).unwrap_or_default(); + let names = crate::refused_part::operands(app, &commands, &d.items()); + crate::refused_part::refused_among(&app.session.model.state(), names.iter().map(String::as_str)) +} + /// Whether a dialog scrolls `error` into view this frame: once per refusal, a refusal on OK at once /// and a preview's once no field is typed in. fn reveal_refusal(on_ok: bool, typing: bool, shown: Option<&str>, error: &str) -> bool { @@ -2806,7 +3316,7 @@ fn update_fill_cells(app: &SolveApp, d: &mut Dialog) { // Editing: the tools as they were before this feature (it may have removed them). let st = match d.editing { Some((id, _)) => app.session.model.state_before(id), - None => app.session.world_state(), + None => crate::open_meshing::session_world(&app.session), }; let found = fill_cells(&st, &names); let kept: Vec = cells.iter().filter(|c| c.2).map(|c| c.1.clone()).collect(); @@ -2858,9 +3368,11 @@ pub(crate) fn fill_cells(st: &solidcraft_engine::doc::ModelState, tools: &[Strin /// Measure again when the picked items changed. fn update_measure(app: &SolveApp, d: &mut Dialog) { let items: Vec = sels(d, 0).to_vec(); - if let Kind::Measure { result, of, .. } = &mut d.kind + if let Kind::Measure { result, of, labels, .. } = &mut d.kind && *of != items { + // Another measurement: its labels start in their own places. + *labels = Default::default(); *result = if items.is_empty() { None } else { Some(app.session.measure_items(&items)) }; *of = items; } @@ -2965,20 +3477,56 @@ fn auto_operation(app: &SolveApp, d: &mut Dialog) { smart.start = start; smart.latch = None; } + // Showing or hiding a body changes what the extrude meets: the latch was decided among the + // bodies shown before (#9919). + let shown = solidcraft_engine::shown_scope(&app.session); + if let Kind::Extrude { smart, .. } = &mut d.kind + && smart.shown != shown + { + smart.shown = shown.clone(); + smart.latch = None; + } // To an object, the extrude goes to it on whichever side it is: that is the side (#1633). if params.get("to").is_some() && let Some(reach) = solidcraft_engine::extrude_reach(&app.session, ¶ms) { side = crate::smart_extrude::side(reach, 0); } - // Hidden bodies are out of its scope (#6901). + // Hidden bodies are out of its scope (#6901). With none shown there is nothing to join or + // cut: an empty `participants` would read as every body, hidden ones too (#9919). let mut params = params; - if let Some(shown) = solidcraft_engine::shown_scope(&app.session) + let mut nothing_shown = false; + if let Some(shown) = shown && params.get("participants").is_none() { + nothing_shown = shown.is_empty(); params["participants"] = json!(shown); } - let Some(fresh) = solidcraft_engine::auto_operation(&app.session, ¶ms).and_then(|op| OPS.iter().position(|o| *o == op)) else { + // A model that cannot be placed suggests nothing; running the command reports why. + let fresh = if nothing_shown { + Some("new") + } else { + // Asked again only when the parameters or the design change: it casts rays through + // every triangle of the bodies, milliseconds a frame on a large part. + let key = auto_operation_key(app, ¶ms); + let cached = match &d.kind { + Kind::Extrude { smart, .. } => smart.auto.filter(|(k, _)| *k == key).map(|(_, op)| op), + _ => None, + }; + match cached { + Some(op) => op, + None => { + #[cfg(test)] + AUTO_OPERATION_ASKED.with(|n| n.set(n.get() + 1)); + let op = solidcraft_engine::auto_operation(&app.session, ¶ms).ok().flatten(); + if let Kind::Extrude { smart, .. } = &mut d.kind { + smart.auto = Some((key, op)); + } + op + } + } + }; + let Some(fresh) = fresh.and_then(|op| OPS.iter().position(|o| *o == op)) else { return; }; if let Kind::Extrude { operation, smart, .. } = &mut d.kind { @@ -2986,12 +3534,39 @@ fn auto_operation(app: &SolveApp, d: &mut Dialog) { } } +/// What [`solidcraft_engine::auto_operation`] depends on besides its parameters: the design +/// (its revision counts every change, shown bodies too), which design it is, and the active +/// component the extrude goes into. +fn auto_operation_key(app: &SolveApp, params: &Value) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + params.to_string().hash(&mut h); + app.session.revision.hash(&mut h); + app.session.document_id.hash(&mut h); + app.session.active_component.hash(&mut h); + app.session.active_occurrence_path.hash(&mut h); + h.finish() +} + +#[cfg(test)] +thread_local! { + static AUTO_OPERATION_ASKED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How often the extrude window asked the engine for its automatic operation on this thread. +#[cfg(test)] +pub(crate) fn auto_operation_asked() -> usize { + AUTO_OPERATION_ASKED.with(std::cell::Cell::get) +} + /// The one-side direction a new extrude takes for its first pick: toward the side of a sketch /// profile (or curve) the camera looks from; None for picks that keep their own way. fn picked_side(app: &SolveApp, d: &Dialog, first: &Sel) -> Option { let normal = match first { Sel::Profile { sketch, .. } => crate::canvas::profile_plane(app, *sketch)?.normal(), - Sel::SketchCurve { .. } => app.session.world_state().sketch(picks_sketch(app, std::slice::from_ref(first), None)?)?.plane.normal(), + Sel::SketchCurve { .. } => { + crate::open_meshing::session_world(&app.session).sketch(picks_sketch(app, std::slice::from_ref(first), None)?)?.plane.normal() + } Sel::Face { .. } => return Some(0), _ => return None, }; @@ -2999,10 +3574,28 @@ fn picked_side(app: &SolveApp, d: &Dialog, first: &Sel) -> Option { Some(crate::smart_extrude::picked_direction(crate::smart_extrude::view_ray(&app.cam, at), normal, false)) } -/// Show the sketch of the Extrude, Revolve, sheet metal base or contour flange, or Hole at sketch +/// Discard an editor whose target was removed, before its preview can draw again. Show the sketch +/// of the Extrude, Revolve, sheet metal base or contour flange, or Hole at sketch /// points the open dialog edits, and only while it is open: whichever way the dialog closed (OK, /// Cancel, another tool, another design), the sketch returns to its own visibility. -pub(crate) fn sync_feature_edit_sketch(app: &mut SolveApp) { +pub(crate) fn sync_feature_edit(app: &mut SolveApp) { + if app.dialog.as_ref().and_then(|d| d.editing).is_some_and(|(id, _)| app.session.doc.feature(id).is_none()) { + // Undo or deletion already chose the current document and history. Cancel's rollback + // would try to restore the obsolete editing session; just discard its work instead. + app.dialog = None; + app.applying = None; + if let Some(state) = app.editing_state.take() { + // Undo can save the editor's temporary rollback in Redo (deletion saves it in + // Undo). Those exact snapshots belong to the complete design, with its old marker. + for snapshot in app.session.undo.iter_mut().chain(&mut app.session.redo) { + if std::sync::Arc::ptr_eq(&snapshot.doc, &state.source.doc) { + snapshot.doc = state.original.doc.clone(); + } + } + } + app.preview.reset(); + app.op_check.abandon(); + } app.session.feature_edit_sketch = app.dialog.as_ref().and_then(|d| d.editing).and_then(|(id, _)| match &app.session.doc.feature(id)?.kind { FeatureKind::Extrude { sketch, .. } | FeatureKind::Revolve { sketch, .. } @@ -3054,11 +3647,11 @@ pub(crate) fn corner_confirms(d: &Dialog) -> bool { /// Sketch Palette keeps the right there, and the dialog takes the left so both stay on screen. /// With Dialogs › In the left column it holds the left column instead (`dialog_column`). pub fn show(app: &mut SolveApp, ctx: &egui::Context) { - let escape_routed_here = !app.preferences.viewport_analysis_status || app.escape_owner.is_none_or(|owner| owner == crate::EscapeOwner::Dialog); + let escape_routed_here = !crate::viewport_status::enabled(app) || app.escape_owner.is_none_or(|owner| owner == crate::EscapeOwner::Dialog); // A click in the view's corner is for the dialog open this frame, or for none. let corner = app.viewport.corner.take(); app.viewport.corner_ok = false; - sync_feature_edit_sketch(app); + sync_feature_edit(app); app.op_check.poll(); if app.tree.redefine.is_none() { app.viewport.dialog_rect = None; @@ -3163,6 +3756,20 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let (ok_label, close_label) = action_labels(&d.kind); // What the footer's OK takes, for the check in the view's corner too (#6709). let ok_enabled = valid && !ok_label.is_empty() && app.applying.is_none(); + // #10620: the card widens to fit its widest label in the current language. The body + // publishes the extra it needs under this key each pass; the card applies it next pass, + // so the label column grows and the control column keeps its design width. Manager cards + // keep their approved fixed width. + let manager = matches!( + d.kind, + Kind::Material { .. } + | Kind::Appearance(_) + | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }) + | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. }) + | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. }) + ); + let grow_key = egui::Id::new(("sc_dialog_label_grow", raw_title)); + let label_grow = ctx.data(|data| data.get_temp::(grow_key)).unwrap_or(0.0).min((vp.width() - t.space_24 - card_width(&d)).max(0.0)); let panel = crate::ui_kit::Panel::new(&heading, egui::Id::new(("sc_dialog", title(&d.kind))), anchor, drag_bounds, side, frame) .actions(ok_label, close_label); let panel = if let Some(column) = column { @@ -3170,8 +3777,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } else if wide && side == crate::frame::Side::Left { let available = app.viewport.palette_rect.map_or(vp.width(), |r| (r.left() - vp.left() - t.space_8).max(0.0)); panel.width(card_width(&d).min(available)) - } else { + } else if manager { panel.width(card_width(&d)) + } else { + panel.width(card_width(&d) + label_grow).grow_label(grow_key) }; let reset_scroll = d.reset_scroll; let panel = @@ -3205,14 +3814,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let heading = crate::ui_kit::FeatureOptions { icon, title: label, drag_key, moved, docked, apply_label: repeatable.then_some("Apply") }; let applying = app.applying.is_some(); let mut collapsed = d.collapsed; - let manager = matches!( - d.kind, - Kind::Material { .. } - | Kind::Appearance(_) - | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }) - | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. }) - | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. }) - ); // A study/configuration owns Enter for its cells, including when folded. let cell_enter = matches!(&d.kind, Kind::Motion(k) if k.wide()) || matches!(&d.kind, Kind::Material { editor, .. } if editor.editing()); if cell_enter && collapsed { @@ -3221,6 +3822,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let body = |ui: &mut egui::Ui| { d.sync_fillet_chain(&app.session); crate::hole_presets::rows(ui, &mut d, &mut app.preferences.hole_presets, &app.session.doc, reset_scroll); + crate::personal_sheet_rules::rows(ui, &mut d, &mut app.preferences.personal_sheet_rules, &app.session.doc, reset_scroll); let (accepted, fields) = crate::ui_kit::value_fields(ctx, || dense::rows(app, ctx, &mut d, ui)); enter |= accepted; value_fields = fields; @@ -3282,6 +3884,12 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { if let Some(field) = crate::ui_kit::canvas_value_focus(ctx) { value_fields.push(field); } + // Without value boxes in the view (#9479), the keyboard the window's opening or a pick gives + // the box goes to the form's value field, once the form has drawn one. + if d.focus && !crate::canvas::boxes_shown(ctx) && !value_fields.is_empty() { + d.focus = false; + d.restore_value_focus = true; + } // The editor loses the keyboard while the click is still being handled, possibly in a later // pass of the same frame, so give it back once the pointer is idle again. let pointer_busy = ctx.input(|i| i.pointer.any_down() || i.pointer.any_pressed() || i.pointer.any_released()); @@ -3304,7 +3912,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } else { d.value_focus = ctx.memory(|memory| memory.focused()).filter(|id| value_fields.iter().any(|(field, _)| field == id)); } - let preset_prompt = crate::hole_presets::name_prompt(ctx, &mut d, &mut app.preferences.hole_presets, &app.session.doc); + // Each prompt draws only for its own dialog, so both run (`|`, not `||`). + let preset_prompt = crate::hole_presets::name_prompt(ctx, &mut d, &mut app.preferences.hole_presets, &app.session.doc) + | crate::personal_sheet_rules::name_prompt(ctx, &mut d, &mut app.preferences.personal_sheet_rules, &app.session.doc); if preset_prompt { enter = false; ok = false; @@ -3335,7 +3945,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { { plane["fixed"] = json!(true); let before = app.settled_cam(); - match app.run("sketch.create", json!({"plane":plane})) { + let mut params = json!({"plane":plane}); + if app.preferences.sketch_face_activates_part { + params["activate_part"] = json!(true); + } + match app.run("sketch.create", params) { Ok(_) => { app.look_at_opened_sketch(before); cancel = true; @@ -3552,8 +4166,14 @@ pub(crate) fn preset_to_object(d: &mut Dialog, on: bool) { } fn set_object(inputs: &mut Vec, active: &mut usize, label: &'static str, on: bool) { + set_object_accepting(inputs, active, label, FACES | selection::VERTICES, on); +} + +/// Add or remove the pick input `label` accepting `accept`; the active input moves to it when it +/// is added. +pub(crate) fn set_object_accepting(inputs: &mut Vec, active: &mut usize, label: &'static str, accept: selection::Accept, on: bool) { if on && !object_on(inputs, label) { - inputs.push(SelInput::new(label, FACES | selection::VERTICES, false)); + inputs.push(SelInput::new(label, accept, false)); *active = inputs.len() - 1; } else if !on && object_on(inputs, label) { inputs.retain(|i| i.label != label); @@ -3562,8 +4182,8 @@ fn set_object(inputs: &mut Vec, active: &mut usize, label: &'static st } /// The plane an extrude's picked profiles lie in: the first pick's sketch plane, or its planar face. -fn profile_plane(s: &Session, first: &Sel) -> Option { - let st = s.world_state(); +fn profile_plane(s: &Session, first: &Sel) -> Option { + let st = crate::open_meshing::session_world(s); match first { Sel::Profile { sketch, .. } => st.sketch(*sketch).map(|ss| ss.plane), Sel::Face { body, index, .. } => st.body(body)?.body.planar_face(*index), @@ -3573,11 +4193,11 @@ fn profile_plane(s: &Session, first: &Sel) -> Option bool { +fn object_target(s: &Session, reference: &solidcore_record::Plane, sel: &Sel) -> bool { const TOLERANCE: f64 = 1e-6; match sel { Sel::Face { body, index, .. } => { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let Some(b) = st.body(body) else { return false }; b.body .planar_face(*index) @@ -3699,7 +4319,7 @@ pub(crate) const CHAMFER_TYPES: [&str; 3] = ["Equal Distance", "Two Distances", /// A new Fillet or Chamfer dialog's values. fn fillet_kind(size: &str, chamfer: bool) -> Kind { - Kind::Fillet { radius: size.into(), chamfer, chain: true, ctype: 0, distance2: size.into(), angle: "45 deg".into(), flip: false } + Kind::Fillet { radius: size.into(), chamfer, chain: true, ctype: 0, distance2: size.into(), angle: "45 deg".into(), flip: false, setback: None } } /// A length field's first text: `number` in the design's units, with the unit written out so the @@ -3746,7 +4366,10 @@ fn hole_defaults(s: &Session) -> Kind { pub fn start_sketch(app: &mut SolveApp, sel: &Sel) -> Result<(), String> { let mut params = match sel { Sel::Plane { name } => json!({ "plane": shown_origin_plane(app, name).unwrap_or_else(|| json!(name)) }), - Sel::Face { .. } => json!({ "plane": crate::sketch_attachment_ui::face_plane(app, sel).ok_or("Selected face placement no longer exists")? }), + Sel::Face { .. } => json!({ + "plane": crate::sketch_attachment_ui::face_plane(app, sel).ok_or("Selected face placement no longer exists")?, + "activate_part": app.preferences.sketch_face_activates_part, + }), _ => return Err("Select an origin plane, construction plane or planar body face".into()), }; if let Sel::Plane { name } = sel @@ -3791,7 +4414,7 @@ fn flip_toward_viewer(app: &SolveApp, name: &str) -> Option<&'static str> { /// the sketch, the view turning to it and the extrude all went the wrong way. `None` while the /// active component sits at the origin (the name says the same) or for a construction plane. fn shown_origin_plane(app: &SolveApp, name: &str) -> Option { - let p = solidcraft_engine::geom::Plane::named(name)?; + let p = solidcore_record::Plane::named(name)?; if app.session.doc.find_feature(name).is_some() || solidcraft_engine::doc::is_identity(&app.session.active_component_frame()) { return None; } @@ -3799,11 +4422,11 @@ fn shown_origin_plane(app: &SolveApp, name: &str) -> Option { } /// The world plane of an origin plane or a construction plane by name, where it is shown. -pub(crate) fn plane_by_name(s: &Session, name: &str) -> Option { - if let Some(p) = solidcraft_engine::geom::Plane::named(name) { +pub(crate) fn plane_by_name(s: &Session, name: &str) -> Option { + if let Some(p) = solidcore_record::Plane::named(name) { return Some(p); } - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); st.construct .iter() .find(|c| c.name == name) @@ -3828,7 +4451,7 @@ pub fn look_at_sketch_again(app: &mut SolveApp) { } fn look_at_sketch_from(app: &mut SolveApp, again: bool) { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); if let Some(ss) = app.session.active_sketch.and_then(|id| st.sketch(id)) { let n = facing(app, ss.plane.normal(), again); let to = square_sketch_axes(app.cam.looking_from(n), ss.plane.x, ss.plane.y); @@ -3878,7 +4501,7 @@ pub(crate) fn onto_sketch(mut to: solidcraft_engine::render::Camera, ss: &solidc return to; }; let mut b = Aabb3::default(); - for p in [lo, hi, solidcraft_engine::geom::Vec2::new(lo.x, hi.y), solidcraft_engine::geom::Vec2::new(hi.x, lo.y)] { + for p in [lo, hi, solidcore_record::Vec2::new(lo.x, hi.y), solidcore_record::Vec2::new(hi.x, lo.y)] { b.add(ss.plane.to_world(p)); } let keep = to.distance; @@ -3955,18 +4578,42 @@ pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> { if let Kind::Section { offset, flip, hatch } = &d.kind && let Some(cut) = app.session.section { - app.tree.section_dialog = Some(SectionDraft { offset: offset.clone(), flip: *flip, hatch: *hatch, plane: sels(d, 0).to_vec(), cut }); + app.tree.section_dialog = if d.extra.contains_key("plane") && sels(d, 0).is_empty() { + None // Programmatic geometry is reconstructed from the actual session, never cached. + } else { + Some(SectionDraft { offset: offset.clone(), flip: *flip, hatch: *hatch, plane: sels(d, 0).to_vec(), cut }) + }; } Ok(()) } /// Edit Section Analysis: its dialog, where the dialog that made the section shown (or hidden) -/// now left it, so the cut moves on from there. A section made some other way opens it afresh, -/// as the toolbar always does (a new section, in place of the old). +/// now left it. Programmatic cuts use their actual geometry in the same existing form. pub fn edit_section(app: &mut SolveApp) { - app.start("inspect.section"); + app.start_section_edit(); let cut = app.session.section.or(app.tree.hidden_section); - let Some(last) = app.tree.section_dialog.clone().filter(|last| cut.is_some_and(|c| same_cut(c, last.cut))) else { return }; + let last = app.tree.section_dialog.clone().filter(|last| cut.is_some_and(|c| same_cut(c, last.cut))); + if app.preferences.viewport_section_status { + if let Some((origin, normal)) = cut { + let o = [origin.x, origin.y, origin.z]; + let n = [normal.x, normal.y, normal.z]; + if let Some((_, distance, canonical)) = crate::viewport_status::section_coordinates(o, n) { + let flip = n.iter().zip(canonical).map(|(a, b)| a * b).sum::() < 0.0; + let offset = format!("{distance} mm"); + let hatch = app.session.section_hatch; + if let Some(d) = app.dialog.as_mut().filter(|d| matches!(d.kind, Kind::Section { .. })) { + d.kind = Kind::Section { offset, flip, hatch }; + if let Some(input) = d.inputs.first_mut() { + input.items.clear(); + } + let base = o.into_iter().zip(canonical).map(|(o, n)| o - n * distance).collect::>(); + d.extra.insert("plane".into(), json!({"origin":base,"normal":canonical})); + } + } + } + return; + } + let Some(last) = last else { return }; if let Some(d) = app.dialog.as_mut().filter(|d| matches!(d.kind, Kind::Section { .. })) { d.kind = Kind::Section { offset: last.offset, flip: last.flip, hatch: last.hatch }; if let Some(plane) = d.inputs.first_mut() { @@ -4024,7 +4671,7 @@ pub fn apply_commands(app: &SolveApp, d: &Dialog) -> Result }; if let Some(sketch) = original_all && !d.profile_selection_changed - && let Some(ss) = app.session.world_state().sketch(sketch.0) + && let Some(ss) = crate::open_meshing::session_world(&app.session).sketch(sketch.0) { let mut selected: Vec = sels(d, 0) .iter() @@ -4073,7 +4720,7 @@ pub fn preview_commands(app: &SolveApp, d: &Dialog) -> Result Result, String> { +pub(crate) fn emboss_profile_plane(app: &SolveApp, sketch: u64) -> Result, String> { let Some(dialog) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Emboss { .. })) else { return Ok(None) }; let Some((feature, _)) = dialog.editing else { return Ok(None) }; let Some(feature) = app.session.doc.feature(feature) else { return Err("the edited feature is missing".into()) }; @@ -4087,7 +4734,7 @@ pub(crate) fn emboss_profile_plane(app: &SolveApp, sketch: u64) -> Result